[
  {
    "path": ".asf.yaml",
    "content": "# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements.  See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License.  You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\ngithub:\n  description: The Java Multi-Cloud Toolkit\n  homepage: https://jclouds.apache.org/\n  labels:\n    - java\n    - library\n    - cloud\n    - jclouds\n\n  # Uncomment the following lines if at some point we feel like\n  # we want to control merges and pull request builds.\n  #\n  # enabled_merge_buttons:\n  #   squash:  true\n  #   merge:   false\n  #   rebase:  false\n  # protected_branches:\n  #   master:\n  #     required_status_checks:\n  #       contexts:\n  #         - build\n  #     required_pull_request_reviews:\n  #       required_approving_review_count: 1\n"
  },
  {
    "path": ".dir-locals.el",
    "content": ";;   Licensed to the Apache Software Foundation (ASF) under one or more\n;;   contributor license agreements.  See the NOTICE file distributed with\n;;   this work for additional information regarding copyright ownership.\n;;   The ASF licenses this file to You under the Apache License, Version 2.0\n;;   (the \"License\"); you may not use this file except in compliance with\n;;   the License.  You may obtain a copy of the License at\n;;\n;;       http://www.apache.org/licenses/LICENSE-2.0\n;;\n;;   Unless required by applicable law or agreed to in writing, software\n;;   distributed under the License is distributed on an \"AS IS\" BASIS,\n;;   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n;;   See the License for the specific language governing permissions and\n;;   limitations under the License.\n\n((nil . ((c-basic-offset . 3))))"
  },
  {
    "path": ".gitattributes",
    "content": "* text eol=lf\n*.cmd binary\n"
  },
  {
    "path": ".github/workflows/ci.yaml",
    "content": "# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements.  See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License.  You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nname: CI\n\non:\n  push:\n    branches:\n      - master\n  pull_request:\n    branches:\n      - master\n\njobs:\n  build:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v3\n      - uses: actions/setup-java@v4\n        with:\n          java-version: \"11\"\n          distribution: temurin\n          cache: maven\n      - name: Build\n        run: mvn clean verify checkstyle:checkstyle -B -q -Dorg.slf4j.simpleLogger.defaultLogLevel=ERROR -Pdoc,src\n"
  },
  {
    "path": ".gitignore",
    "content": "# use glob syntax.\nsyntax: glob\ntarget/\ntest-output/\nbin/\n.settings/\n.classpath\n.project\n.idea/\n*.iml\n*.eml\n*.ipr\n*.iws\n*.DS_STORE\nTAGS\n.metadata/\natlassian-ide-plugin.xml\n.DS_Store\n.java-version\n.factorypath\n.apt_generated\n.apt_generated_tests\n.checkstyle\nnb-configuration.xml\nnbactions.xml\n/.nb-gradle/\ndependency-reduced-pom.xml\n.vscode\n"
  },
  {
    "path": ".mailmap",
    "content": "Adrian Cole <acole@.eng.vmware.com>\nAdrian Cole <acole@twitter.com>\nAdrian Cole <adrian.f.cole@3d8758e0-26b5-11de-8745-db77d3ebf521>\nAdrian Cole <adrian.f.cole@gmail.com>\nAdrian Cole <ferncam1@3d8758e0-26b5-11de-8745-db77d3ebf521>\nAlex Yarmula <oleksiy.yarmula+hosting@gmail.com>\nAlfredo Morresi <rainbowbreeze@gmx.com>\nAlfredo Morresi <rainbowbreeze@pc-alfredo.(none)>\nAndrea Turli <andrea@bigmac.local>\nAndrea Turli <andrea.turli@.dir.svc.accenture.com>\nAndrea Turli <Andrea_Turli@.dub.emea.dell.com>\nAndrea Turli <andrea.turli@gmail.com>\nAndrea Turli <toor@toor.(none)>\nAndrei Savu <asavu@apache.org>\nAndrew Phillips <sharedocs1@gmail.com@3d8758e0-26b5-11de-8745-db77d3ebf521>\nAntoni Batchelli <tbatchelli@acm.org>\nBarak Merimovich <barakme@gmail.com>\nCarlos Sanchez <carlos@apache.org>\nDan Lo Bianco <dan.lobianco@cloudsoftcorp.com>\nDmitry Durnev <ddurnev@griddynamics.com>\nHans Hrasna <hans.hrasna@gmail.com>\nHunter Hutchinson <hunter.hutchinson@gmail.com>\nIlja Bobkevic <ilja.bobkevic@gmail.com>\nIvan Meredith <ivan@ivan.net.nz@3d8758e0-26b5-11de-8745-db77d3ebf521>\nJames Murty <jamurty@3d8758e0-26b5-11de-8745-db77d3ebf521>\nKarthik Ganesan <karthikwrites@yahoo.com>\nNicholas Terry <nterry@familysearch.org>\nNirmal Fernando <nirmal@nirmal.(none)>\nSeshu Pasam <github@pasam.com>\nShane Witbeck <shane@digitalsanctum.com>\nTibor Kiss <tibor.kiss@omixon.com>\nVictor Galkin <vgalkin@griddynamics.net>\nVijay Kiran <mail@vijaykiran.com>\nZack Shoylev <zack.shoylev@rackspace.com>\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "Please review the [How to Contribute](https://cwiki.apache.org/confluence/display/JCLOUDS/Contribute) page for information on how to submit your patch and how the review process works.\n\nAlso make sure all the changes are aligned with the [Coding Standards](https://cwiki.apache.org/confluence/display/JCLOUDS/Writing+jclouds+Code) of the project.\n\nThanks!\n\nThe Apache jclouds team\n"
  },
  {
    "path": "README.md",
    "content": "jclouds\n======\n\nApache jclouds is an open source multi-cloud toolkit for the Java platform that gives you the freedom to create applications that are portable across clouds while giving you full control to use cloud-specific features.\n\nFor more information about using or contributing to jclouds, please visit our website at [jclouds.apache.org](http://jclouds.apache.org/).\n\nLicense\n-------\nCopyright (C) 2009-2022 The Apache Software Foundation\n\nLicensed under the Apache License, Version 2.0\n"
  },
  {
    "path": "all/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>        \n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../project/pom.xml</relativePath>\n  </parent>\n  <artifactId>jclouds-all</artifactId>\n  <name>all</name>\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>rackspace-cloudidentity</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-cinder</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>rackspace-clouddns</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.provider</groupId>\n      <artifactId>aws-cloudwatch</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.provider</groupId>\n      <artifactId>rackspace-cloudblockstorage-us</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.provider</groupId>\n      <artifactId>rackspace-cloudblockstorage-uk</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.provider</groupId>\n      <artifactId>rackspace-clouddns-us</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.provider</groupId>\n      <artifactId>rackspace-clouddns-uk</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.provider</groupId>\n      <artifactId>rackspace-clouddatabases-us</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.provider</groupId>\n      <artifactId>rackspace-clouddatabases-uk</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.provider</groupId>\n      <artifactId>aws-sqs</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.provider</groupId>\n      <artifactId>aws-sts</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.provider</groupId>\n      <artifactId>aws-route53</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.provider</groupId>\n      <artifactId>ultradns-ws</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.provider</groupId>\n      <artifactId>dynect</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>chef</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>${project.groupId}</groupId>\n      <artifactId>jclouds-allloadbalancer</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>${project.groupId}</groupId>\n      <artifactId>jclouds-allcompute</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>${project.groupId}</groupId>\n      <artifactId>jclouds-allblobstore</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n  </dependencies>\n</project>\n"
  },
  {
    "path": "allblobstore/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>        \n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../project/pom.xml</relativePath>\n  </parent>\n  <artifactId>jclouds-allblobstore</artifactId>\n  <name>allblobstore</name>\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>s3</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.provider</groupId>\n      <artifactId>aws-s3</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.provider</groupId>\n      <artifactId>azureblob</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>atmos</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.provider</groupId>\n      <artifactId>b2</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>glacier</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.provider</groupId>\n      <artifactId>google-cloud-storage</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-swift</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.provider</groupId>\n      <artifactId>rackspace-cloudfiles-us</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.provider</groupId>\n      <artifactId>rackspace-cloudfiles-uk</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n  </dependencies>\n</project>\n"
  },
  {
    "path": "allcompute/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>        \n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../project/pom.xml</relativePath>\n  </parent>\n  <artifactId>jclouds-allcompute</artifactId>\n  <name>allcompute</name>\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds.provider</groupId>\n      <artifactId>aws-ec2</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-nova</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-nova-ec2</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>byon</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>ec2</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.provider</groupId>\n      <artifactId>gogrid</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>elasticstack</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.provider</groupId>\n      <artifactId>elastichosts-lon-p</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.provider</groupId>\n      <artifactId>elastichosts-sat-p</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.provider</groupId>\n      <artifactId>elastichosts-lon-b</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.provider</groupId>\n      <artifactId>openhosting-east1</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.provider</groupId>\n      <artifactId>serverlove-z1-man</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.provider</groupId>\n      <artifactId>skalicloud-sdg-my</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.provider</groupId>\n      <artifactId>go2cloud-jhb1</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.provider</groupId>\n      <artifactId>softlayer</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>cloudstack</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.provider</groupId>\n      <artifactId>rackspace-cloudservers-us</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.provider</groupId>\n      <artifactId>rackspace-cloudservers-uk</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.provider</groupId>\n      <artifactId>google-compute-engine</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.provider</groupId>\n      <artifactId>digitalocean2</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.provider</groupId>\n      <artifactId>profitbricks</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>docker</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.provider</groupId>\n      <artifactId>packet</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.provider</groupId>\n      <artifactId>azurecompute-arm</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n  </dependencies>\n</project>\n"
  },
  {
    "path": "allloadbalancer/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>        \n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../project/pom.xml</relativePath>\n  </parent>\n  <artifactId>jclouds-allloadbalancer</artifactId>\n  <name>allloadbalancer</name>\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds.provider</groupId>\n      <artifactId>rackspace-cloudloadbalancers-uk</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.provider</groupId>\n      <artifactId>rackspace-cloudloadbalancers-us</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n  </dependencies>\n</project>\n"
  },
  {
    "path": "apis/atmos/README.txt",
    "content": "#\n# The jclouds API for EMC's Atmos Online Storage (http://www.emccis.com/).\n#\n# TODO: Implementation status.\n# TODO: Supported features.\n# TODO: Usage example.\n"
  },
  {
    "path": "apis/atmos/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.atmos.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "apis/atmos/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n\n  <groupId>org.apache.jclouds.api</groupId>\n  <artifactId>atmos</artifactId>\n  <name>jclouds atmos components</name>\n\n  <properties>\n    <test.atmos.endpoint>https://accesspoint.atmosonline.com</test.atmos.endpoint>\n    <test.atmos.api-version>1.3.0</test.atmos.api-version>\n    <test.atmos.build-version />\n    <test.atmos.identity>FIXME_IDENTITY</test.atmos.identity>\n    <test.atmos.credential>FIXME_CREDENTIAL</test.atmos.credential>\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-blobstore</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-blobstore</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.logging.log4j</groupId>\n      <artifactId>log4j-core</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-log4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <jclouds.blobstore.httpstream.url>${jclouds.blobstore.httpstream.url}</jclouds.blobstore.httpstream.url>\n                    <jclouds.blobstore.httpstream.md5>${jclouds.blobstore.httpstream.md5}</jclouds.blobstore.httpstream.md5>\n                    <test.atmos.endpoint>${test.atmos.endpoint}</test.atmos.endpoint>\n                    <test.atmos.api-version>${test.atmos.api-version}</test.atmos.api-version>\n                    <test.atmos.build-version>${test.atmos.build-version}</test.atmos.build-version>\n                    <test.atmos.identity>${test.atmos.identity}</test.atmos.identity>\n                    <test.atmos.credential>${test.atmos.credential}</test.atmos.credential>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n  \n</project>\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/AtmosApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos;\n\nimport static org.jclouds.Constants.PROPERTY_IDEMPOTENT_METHODS;\nimport static org.jclouds.blobstore.reference.BlobStoreConstants.PROPERTY_USER_METADATA_PREFIX;\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_REGIONS;\nimport static org.jclouds.reflect.Reflection2.typeToken;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.atmos.blobstore.config.AtmosBlobStoreContextModule;\nimport org.jclouds.atmos.config.AtmosHttpApiModule;\nimport org.jclouds.blobstore.BlobStoreContext;\nimport org.jclouds.rest.internal.BaseHttpApiMetadata;\n\nimport com.google.auto.service.AutoService;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n@AutoService(ApiMetadata.class)\npublic class AtmosApiMetadata extends BaseHttpApiMetadata {\n   \n   private static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromApiMetadata(this);\n   }\n\n   public AtmosApiMetadata() {\n      this(builder());\n   }\n\n   protected AtmosApiMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = BaseHttpApiMetadata.defaultProperties();\n      properties.setProperty(PROPERTY_REGIONS, \"DEFAULT\");\n      properties.setProperty(PROPERTY_USER_METADATA_PREFIX, \"X-Object-Meta-\");\n      properties.setProperty(PROPERTY_IDEMPOTENT_METHODS, \"DELETE,GET,HEAD,OPTIONS,POST,PUT\");\n      return properties;\n   }\n\n   public static class Builder extends BaseHttpApiMetadata.Builder<AtmosClient, Builder> {\n      protected Builder() {\n         super(AtmosClient.class);\n         id(\"atmos\")\n         .name(\"EMC's Atmos API\")\n         .identityName(\"Subtenant ID (UID)\")\n         .credentialName(\"Shared Secret\")\n         .documentation(URI.create(\"https://community.emc.com/docs/DOC-10508\"))\n         .version(\"1.4.0\")\n         .defaultEndpoint(\"https://accesspoint.atmosonline.com\")\n         .defaultProperties(AtmosApiMetadata.defaultProperties())\n         .view(typeToken(BlobStoreContext.class))\n         .defaultModules(ImmutableSet.<Class<? extends Module>>of(AtmosHttpApiModule.class, AtmosBlobStoreContextModule.class));\n      }\n\n      @Override\n      public AtmosApiMetadata build() {\n         return new AtmosApiMetadata(this);\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/AtmosClient.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos;\n\nimport static com.google.common.net.HttpHeaders.EXPECT;\n\nimport java.io.Closeable;\nimport java.net.URI;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.HEAD;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.atmos.binders.BindMetadataToHeaders;\nimport org.jclouds.atmos.domain.AtmosObject;\nimport org.jclouds.atmos.domain.BoundedSet;\nimport org.jclouds.atmos.domain.DirectoryEntry;\nimport org.jclouds.atmos.domain.SystemMetadata;\nimport org.jclouds.atmos.domain.UserMetadata;\nimport org.jclouds.atmos.fallbacks.TrueOn404FalseOnPathNotEmpty;\nimport org.jclouds.atmos.filters.SignRequest;\nimport org.jclouds.atmos.functions.AtmosObjectName;\nimport org.jclouds.atmos.functions.ParseDirectoryListFromContentAndHeaders;\nimport org.jclouds.atmos.functions.ParseObjectFromHeadersAndHttpContent;\nimport org.jclouds.atmos.functions.ParseSystemMetadataFromHeaders;\nimport org.jclouds.atmos.functions.ParseUserMetadataFromHeaders;\nimport org.jclouds.atmos.functions.ReturnTrueIfGroupACLIsOtherRead;\nimport org.jclouds.atmos.options.ListOptions;\nimport org.jclouds.atmos.options.PutOptions;\nimport org.jclouds.blobstore.BlobStoreFallbacks.NullOnKeyAlreadyExists;\nimport org.jclouds.blobstore.BlobStoreFallbacks.ThrowContainerNotFoundOn404;\nimport org.jclouds.blobstore.BlobStoreFallbacks.ThrowKeyNotFoundOn404;\nimport org.jclouds.http.functions.ParseURIFromListOrLocationHeaderIf20x;\nimport org.jclouds.http.options.GetOptions;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.Headers;\nimport org.jclouds.rest.annotations.ParamParser;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\n\nimport com.google.inject.Provides;\n\n/** Provides access to EMC Atmos Online Storage resources via their REST API. */\n@RequestFilters(SignRequest.class)\n@Path(\"/rest/namespace\")\npublic interface AtmosClient extends Closeable {\n\n   @Provides\n   AtmosObject newObject();\n\n   @Named(\"ListDirectory\")\n   @GET\n   @Path(\"/\")\n   @ResponseParser(ParseDirectoryListFromContentAndHeaders.class)\n   @Consumes(MediaType.TEXT_XML)\n   BoundedSet<? extends DirectoryEntry> listDirectories(ListOptions... options);\n\n   @Named(\"ListDirectory\")\n   @GET\n   @Path(\"/{directoryName}/\")\n   @ResponseParser(ParseDirectoryListFromContentAndHeaders.class)\n   @Fallback(ThrowContainerNotFoundOn404.class)\n   @Consumes(MediaType.TEXT_XML)\n   @Headers(keys = \"x-emc-include-meta\", values = \"1\")\n   BoundedSet<? extends DirectoryEntry> listDirectory(\n         @PathParam(\"directoryName\") String directoryName, ListOptions... options);\n\n   @Named(\"CreateDirectory\")\n   @POST\n   @Path(\"/{directoryName}/\")\n   @Fallback(NullOnKeyAlreadyExists.class)\n   @Produces(MediaType.APPLICATION_OCTET_STREAM)\n   @Consumes(MediaType.WILDCARD)\n   URI createDirectory(@PathParam(\"directoryName\") String directoryName, PutOptions... options);\n\n   @Nullable\n   @Named(\"CreateObject\")\n   @POST\n   @Path(\"/{parent}/{name}\")\n   @Headers(keys = EXPECT, values = \"100-continue\")\n   @ResponseParser(ParseURIFromListOrLocationHeaderIf20x.class)\n   @Consumes(MediaType.WILDCARD)\n   URI createFile(@PathParam(\"parent\") String parent, @PathParam(\"name\") @ParamParser(AtmosObjectName.class)\n      @BinderParam(BindMetadataToHeaders.class) AtmosObject object, PutOptions... options);\n\n   @Named(\"UpdateObject\")\n   @PUT\n   @Path(\"/{parent}/{name}\")\n   @Headers(keys = EXPECT, values = \"100-continue\")\n   @Fallback(ThrowKeyNotFoundOn404.class)\n   @Consumes(MediaType.WILDCARD)\n   void updateFile(@PathParam(\"parent\") String parent, @PathParam(\"name\") @ParamParser(AtmosObjectName.class)\n      @BinderParam(BindMetadataToHeaders.class) AtmosObject object, PutOptions... options);\n\n   @Named(\"ReadObject\")\n   @GET\n   @ResponseParser(ParseObjectFromHeadersAndHttpContent.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   @Path(\"/{path}\")\n   @Consumes(MediaType.WILDCARD)\n   AtmosObject readFile(@PathParam(\"path\") String path, GetOptions... options);\n\n   @Named(\"GetObjectMetadata\")\n   @HEAD\n   @ResponseParser(ParseObjectFromHeadersAndHttpContent.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   @Path(\"/{path}\")\n   @Consumes(MediaType.WILDCARD)\n   AtmosObject headFile(@PathParam(\"path\") String path);\n\n   @Named(\"GetSystemMetadata\")\n   @HEAD\n   @ResponseParser(ParseSystemMetadataFromHeaders.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   // currently throws 403 errors @QueryParams(keys = \"metadata/system\")\n   @Path(\"/{path}\")\n   @Consumes(MediaType.WILDCARD)\n   SystemMetadata getSystemMetadata(@PathParam(\"path\") String path);\n\n   @Named(\"GetUserMetadata\")\n   @HEAD\n   @ResponseParser(ParseUserMetadataFromHeaders.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   @Path(\"/{path}\")\n   @QueryParams(keys = \"metadata/user\")\n   @Consumes(MediaType.WILDCARD)\n   UserMetadata getUserMetadata(@PathParam(\"path\") String path);\n\n   @Named(\"DeleteObject\")\n   @DELETE\n   @Fallback(TrueOn404FalseOnPathNotEmpty.class)\n   @Path(\"/{path}\")\n   @Consumes(MediaType.WILDCARD)\n   boolean deletePath(@PathParam(\"path\") String path);\n\n   @Named(\"GetObjectMetadata\")\n   @HEAD\n   @Fallback(FalseOnNotFoundOr404.class)\n   @Path(\"/{path}\")\n   @Consumes(MediaType.WILDCARD)\n   boolean pathExists(@PathParam(\"path\") String path);\n\n   @Named(\"GetObjectMetadata\")\n   @HEAD\n   @ResponseParser(ReturnTrueIfGroupACLIsOtherRead.class)\n   @Path(\"/{path}\")\n   @Consumes(MediaType.WILDCARD)\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean isPublic(@PathParam(\"path\") String path);\n\n   @Named(\"SetObjectMetadata\")\n   @POST\n   @Path(\"/{path}\")\n   @QueryParams(keys = \"acl\")\n   @Produces(MediaType.APPLICATION_OCTET_STREAM)\n   @Fallback(ThrowKeyNotFoundOn404.class)\n   @Consumes(MediaType.WILDCARD)\n   void setGroupAcl(@PathParam(\"path\") String path, PutOptions options);\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/AtmosResponseException.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos;\n\nimport org.jclouds.atmos.domain.AtmosError;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.javax.annotation.Nullable;\n\n/**\n * Encapsulates an Error from Atmos Storage Services.\n * \n * @see AtmosError\n * @see ParseAtmosErrorFromXmlContent\n */\npublic class AtmosResponseException extends HttpResponseException {\n\n   private transient AtmosError error;\n\n   public AtmosResponseException(HttpCommand command, HttpResponse response,\n            AtmosError error) {\n      super(String.format(\"command %s failed with code %s, error: %s\", command.getCurrentRequest()\n               .getRequestLine(), response.getStatusCode(), error.toString()), command, response);\n      this.setError(error);\n\n   }\n\n   public AtmosResponseException(HttpCommand command, HttpResponse response,\n            AtmosError error, Throwable cause) {\n      super(String.format(\"command %1$s failed with error: %2$s\", command.getCurrentRequest()\n               .getRequestLine(), error.toString()), command, response, cause);\n      this.setError(error);\n\n   }\n\n   public AtmosResponseException(String message, HttpCommand command, HttpResponse response,\n            AtmosError error) {\n      super(message, command, response);\n      this.setError(error);\n\n   }\n\n   public AtmosResponseException(String message, HttpCommand command, HttpResponse response,\n            AtmosError error, Throwable cause) {\n      super(message, command, response, cause);\n      this.setError(error);\n\n   }\n\n   public void setError(AtmosError error) {\n      this.error = error;\n   }\n\n   @Nullable\n   public AtmosError getError() {\n      return error;\n   }\n\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/binders/BindMetadataToHeaders.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport com.google.common.io.BaseEncoding;\n\nimport org.jclouds.atmos.domain.AtmosObject;\nimport org.jclouds.atmos.reference.AtmosHeaders;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\n@Singleton\npublic class BindMetadataToHeaders implements Binder {\n   private final BindUserMetadataToHeaders metaBinder;\n\n   @Inject\n   protected BindMetadataToHeaders(BindUserMetadataToHeaders metaBinder) {\n      this.metaBinder = metaBinder;\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkArgument(checkNotNull(input, \"input\") instanceof AtmosObject, \"this binder is only valid for AtmosObject!\");\n      checkNotNull(request, \"request\");\n\n      AtmosObject object = AtmosObject.class.cast(input);\n      checkNotNull(object.getPayload(), \"object payload\");\n      checkArgument(object.getPayload().getContentMetadata().getContentLength() != null,\n            \"contentLength must be set, streaming not supported\");\n      byte[] contentMD5 = object.getContentMetadata().getContentMD5();\n      if (contentMD5 != null) {\n         request = (R) request.toBuilder()\n               .addHeader(AtmosHeaders.CHECKSUM, \"MD5/0/\" +\n                     BaseEncoding.base16().encode(contentMD5))\n               .build();\n      }\n      return metaBinder.bindToRequest(request, object.getUserMetadata());\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/binders/BindUserMetadataToHeaders.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.atmos.domain.UserMetadata;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Joiner;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMap.Builder;\nimport com.google.common.collect.Multimaps;\n\n@Singleton\npublic class BindUserMetadataToHeaders implements Binder, Function<UserMetadata, Map<String, String>> {\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkArgument(checkNotNull(input, \"input\") instanceof UserMetadata,\n            \"this binder is only valid for UserMetadatas!\");\n      checkNotNull(request, \"request\");\n      return (R) request.toBuilder().replaceHeaders(Multimaps.forMap(apply(UserMetadata.class.cast(input)))).build();\n   }\n\n   @Override\n   public Map<String, String> apply(UserMetadata md) {\n      Builder<String, String> headers = ImmutableMap.builder();\n      if (!md.getMetadata().isEmpty()) {\n         String header = Joiner.on(',').withKeyValueSeparator(\"=\").join(md.getMetadata());\n         headers.put(\"x-emc-meta\", header);\n      }\n      if (!md.getListableMetadata().isEmpty()) {\n         String header = Joiner.on(',').withKeyValueSeparator(\"=\").join(md.getListableMetadata());\n         headers.put(\"x-emc-listable-meta\", header);\n      }\n      if (!md.getTags().isEmpty()) {\n         String header = Joiner.on(',').join(md.getTags());\n         headers.put(\"x-emc-tags\", header);\n      }\n      if (!md.getListableTags().isEmpty()) {\n         String header = Joiner.on(',').join(md.getListableTags());\n         headers.put(\"x-emc-listable-tags\", header);\n      }\n      return headers.build();\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/blobstore/AtmosBlobRequestSigner.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.blobstore;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.blobstore.util.BlobStoreUtils.cleanRequest;\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport java.net.URI;\nimport java.util.Date;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.atmos.AtmosClient;\nimport org.jclouds.atmos.blobstore.functions.BlobToObject;\nimport org.jclouds.atmos.domain.AtmosObject;\nimport org.jclouds.atmos.filters.SignRequest;\nimport org.jclouds.atmos.options.PutOptions;\nimport org.jclouds.blobstore.BlobRequestSigner;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.functions.BlobToHttpGetOptions;\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.Uris;\nimport org.jclouds.http.options.GetOptions;\nimport org.jclouds.reflect.Invocation;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.reflect.Invokable;\nimport com.google.inject.Provider;\n\n@Singleton\npublic class AtmosBlobRequestSigner implements BlobRequestSigner {\n   private static final int DEFAULT_EXPIRY_SECONDS = 15 * 60;\n\n   private final Function<Invocation, HttpRequest> processor;\n   private final BlobToObject blobToObject;\n   private final BlobToHttpGetOptions blob2ObjectGetOptions;\n\n   private final Invokable<?, ?> getMethod;\n   private final Invokable<?, ?> deleteMethod;\n   private final Invokable<?, ?> createMethod;\n\n   private final SignRequest signer;\n   private final URI endpoint;\n   private final String identity;\n   private final DateService dateService;\n   private final Provider<String> timeStampProvider;\n\n   @Inject\n   public AtmosBlobRequestSigner(Function<Invocation, HttpRequest> processor, BlobToObject blobToObject,\n         BlobToHttpGetOptions blob2ObjectGetOptions, SignRequest signer,\n         @org.jclouds.location.Provider Supplier<URI> endpointProvider,\n         @org.jclouds.location.Provider Supplier<Credentials> creds,\n         DateService dateService, @TimeStamp Provider<String> timeStampProvider)\n         throws SecurityException, NoSuchMethodException {\n      this.processor = checkNotNull(processor, \"processor\");\n      this.blobToObject = checkNotNull(blobToObject, \"blobToObject\");\n      this.blob2ObjectGetOptions = checkNotNull(blob2ObjectGetOptions, \"blob2ObjectGetOptions\");\n      this.getMethod = method(AtmosClient.class, \"readFile\", String.class, GetOptions[].class);\n      this.deleteMethod = method(AtmosClient.class, \"deletePath\", String.class);\n      this.createMethod = method(AtmosClient.class, \"createFile\", String.class, AtmosObject.class, PutOptions[].class);\n      this.signer = signer;\n      this.endpoint = endpointProvider.get();\n      this.identity = creds.get().identity;\n      this.dateService = dateService;\n      this.timeStampProvider = timeStampProvider;\n   }\n\n   @Override\n   public HttpRequest signGetBlob(String container, String name) {\n      return signGetBlob(container, name, DEFAULT_EXPIRY_SECONDS);\n   }\n\n   @Override\n   public HttpRequest signGetBlob(String container, String name, long timeInSeconds) {\n      checkNotNull(container, \"container\");\n      checkNotNull(name, \"name\");\n      return sign(\"GET\", \"/rest/namespace/\" + container + \"/\" + name, timeInSeconds);\n   }\n\n   @Override\n   public HttpRequest signPutBlob(String container, Blob blob) {\n      checkNotNull(container, \"container\");\n      checkNotNull(blob, \"blob\");\n      return cleanRequest(processor.apply(Invocation.create(createMethod,\n            ImmutableList.<Object> of(container, blobToObject.apply(blob)))));\n   }\n\n   @Override\n   public HttpRequest signPutBlob(String container, Blob blob, long timeInSeconds) {\n      throw new UnsupportedOperationException();\n   }\n\n   private String getPath(String container, String name) {\n      return checkNotNull(container, \"container\") + \"/\" + checkNotNull(name, \"name\");\n   }\n\n   @Override\n   public HttpRequest signGetBlob(String container, String name, org.jclouds.blobstore.options.GetOptions options) {\n      checkNotNull(container, \"container\");\n      checkNotNull(name, \"name\");\n      return cleanRequest(processor.apply(Invocation.create(getMethod,\n            ImmutableList.of(getPath(container, name), blob2ObjectGetOptions.apply(checkNotNull(options, \"options\"))))));\n   }\n\n   private HttpRequest sign(String method, String path, long timeInSeconds) {\n      Date now = dateService.rfc1123DateParse(timeStampProvider.get());\n      String expires = String.valueOf(now.getTime() / 1000 + timeInSeconds);\n      String stringToSign = method + \"\\n\" +\n            path + \"\\n\" +\n            identity + \"\\n\" +\n            expires;\n      return HttpRequest.builder()\n            .method(method)\n            .endpoint(Uris.uriBuilder(endpoint.getScheme() + \"://\" + endpoint.getHost()).appendPath(path).build())\n            .addQueryParam(\"uid\", identity)\n            .addQueryParam(\"expires\", expires)\n            .addQueryParam(\"signature\", signer.calculateSignature(stringToSign))\n            .build();\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/blobstore/AtmosBlobStore.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.blobstore;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.atmos.options.PutOptions.Builder.publicRead;\n\nimport java.io.InputStream;\nimport java.util.List;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Provider;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.atmos.AtmosClient;\nimport org.jclouds.atmos.blobstore.functions.BlobStoreListOptionsToListOptions;\nimport org.jclouds.atmos.blobstore.functions.BlobToObject;\nimport org.jclouds.atmos.blobstore.functions.DirectoryEntryListToResourceMetadataList;\nimport org.jclouds.atmos.blobstore.functions.ObjectToBlob;\nimport org.jclouds.atmos.blobstore.functions.ObjectToBlobMetadata;\nimport org.jclouds.atmos.options.ListOptions;\nimport org.jclouds.atmos.util.AtmosUtils;\nimport org.jclouds.blobstore.BlobStoreContext;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.BlobAccess;\nimport org.jclouds.blobstore.domain.BlobMetadata;\nimport org.jclouds.blobstore.domain.ContainerAccess;\nimport org.jclouds.blobstore.domain.MultipartPart;\nimport org.jclouds.blobstore.domain.MultipartUpload;\nimport org.jclouds.blobstore.domain.PageSet;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.functions.BlobToHttpGetOptions;\nimport org.jclouds.blobstore.internal.BaseBlobStore;\nimport org.jclouds.blobstore.options.CopyOptions;\nimport org.jclouds.blobstore.options.CreateContainerOptions;\nimport org.jclouds.blobstore.options.PutOptions;\nimport org.jclouds.blobstore.strategy.internal.FetchBlobMetadata;\nimport org.jclouds.blobstore.util.BlobUtils;\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.crypto.Crypto;\nimport org.jclouds.domain.Location;\nimport org.jclouds.http.options.GetOptions;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.PayloadSlicer;\n\nimport com.google.common.base.Strings;\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\n\n@Singleton\npublic class AtmosBlobStore extends BaseBlobStore {\n   private final AtmosClient sync;\n   private final ObjectToBlob object2Blob;\n   private final ObjectToBlobMetadata object2BlobMd;\n   private final BlobToObject blob2Object;\n   private final BlobStoreListOptionsToListOptions container2ContainerListOptions;\n   private final DirectoryEntryListToResourceMetadataList container2ResourceList;\n   private final Crypto crypto;\n   private final BlobToHttpGetOptions blob2ObjectGetOptions;\n   private final Provider<FetchBlobMetadata> fetchBlobMetadataProvider;\n   private final LoadingCache<String, Boolean> isPublic;\n\n   @Inject\n   AtmosBlobStore(BlobStoreContext context, BlobUtils blobUtils, Supplier<Location> defaultLocation,\n            @Memoized Supplier<Set<? extends Location>> locations, PayloadSlicer slicer, AtmosClient sync,\n            ObjectToBlob object2Blob, ObjectToBlobMetadata object2BlobMd, BlobToObject blob2Object,\n            BlobStoreListOptionsToListOptions container2ContainerListOptions,\n            DirectoryEntryListToResourceMetadataList container2ResourceList, Crypto crypto,\n            BlobToHttpGetOptions blob2ObjectGetOptions, Provider<FetchBlobMetadata> fetchBlobMetadataProvider,\n            LoadingCache<String, Boolean> isPublic) {\n      super(context, blobUtils, defaultLocation, locations, slicer);\n      this.blob2ObjectGetOptions = checkNotNull(blob2ObjectGetOptions, \"blob2ObjectGetOptions\");\n      this.sync = checkNotNull(sync, \"sync\");\n      this.container2ContainerListOptions = checkNotNull(container2ContainerListOptions,\n               \"container2ContainerListOptions\");\n      this.container2ResourceList = checkNotNull(container2ResourceList, \"container2ResourceList\");\n      this.object2Blob = checkNotNull(object2Blob, \"object2Blob\");\n      this.blob2Object = checkNotNull(blob2Object, \"blob2Object\");\n      this.object2BlobMd = checkNotNull(object2BlobMd, \"object2BlobMd\");\n      this.crypto = checkNotNull(crypto, \"crypto\");\n      this.fetchBlobMetadataProvider = checkNotNull(fetchBlobMetadataProvider, \"fetchBlobMetadataProvider\");\n      this.isPublic = checkNotNull(isPublic, \"isPublic\");\n   }\n\n   /**\n    * This implementation invokes {@link AtmosClient#headFile}\n    */\n   @Override\n   public BlobMetadata blobMetadata(String container, String key) {\n      return object2BlobMd.apply(sync.headFile(container + \"/\" + key));\n   }\n\n   /**\n    * This implementation invokes {@link AtmosClient#deletePath} followed by\n    * {@link AtmosClient#pathExists} until it is true.\n    */\n   protected boolean deleteAndVerifyContainerGone(final String container) {\n      sync.deletePath(container + \"/\");\n      return !sync.pathExists(container + \"/\");\n   }\n\n   /**\n    * This implementation invokes {@link AtmosClient#createDirectory}\n    *\n    * @param location\n    *           currently ignored\n    * @param container\n    *           directory name\n    */\n   @Override\n   public boolean createContainerInLocation(Location location, String container) {\n      return sync.createDirectory(container) != null;\n   }\n\n   @Override\n   public ContainerAccess getContainerAccess(String container) {\n      if (sync.isPublic(container)) {\n         return ContainerAccess.PUBLIC_READ;\n      } else {\n         return ContainerAccess.PRIVATE;\n      }\n   }\n\n   @Override\n   public void setContainerAccess(String container, ContainerAccess access) {\n      org.jclouds.atmos.options.PutOptions options = new org.jclouds.atmos.options.PutOptions();\n      if (access == ContainerAccess.PUBLIC_READ) {\n         options.publicRead();\n      } else {\n         options.publicNone();\n      }\n      sync.setGroupAcl(container, options);\n   }\n\n   /**\n    * This implementation invokes {@link AtmosClient#createDirectory}\n    *\n    * @param container\n    *           directory name\n    */\n   @Override\n   public void createDirectory(String container, String directory) {\n      sync.createDirectory(container + \"/\" + directory);\n   }\n\n   /**\n    * This implementation invokes {@link #removeBlob}\n    */\n   @Override\n   public void deleteDirectory(String containerName, String directory) {\n      removeBlob(containerName, directory + \"/\");\n   }\n\n   /**\n    * This implementation invokes {@link AtmosClient#pathExists}\n    */\n   @Override\n   public boolean containerExists(String container) {\n      return sync.pathExists(container + \"/\");\n   }\n\n   /**\n    * This implementation invokes {@link AtmosClient#pathExists}\n    */\n   @Override\n   public boolean directoryExists(String container, String directory) {\n      return sync.pathExists(container + \"/\" + directory + \"/\");\n   }\n\n   /**\n    * This implementation invokes {@link AtmosClient#pathExists}\n    *\n    * @param container\n    *           container\n    * @param key\n    *           file name\n    */\n   @Override\n   public boolean blobExists(String container, String key) {\n      return sync.pathExists(container + \"/\" + key);\n   }\n\n   /**\n    * This implementation invokes {@link AtmosClient#readFile}\n    */\n   @Override\n   public Blob getBlob(String container, String key, org.jclouds.blobstore.options.GetOptions options) {\n      GetOptions httpOptions = blob2ObjectGetOptions.apply(options);\n      return object2Blob.apply(sync.readFile(container + \"/\" + key, httpOptions));\n   }\n\n   /**\n    * This implementation invokes {@link AtmosClient#listDirectories}\n    */\n   @Override\n   public PageSet<? extends StorageMetadata> list() {\n      return container2ResourceList.apply(sync.listDirectories());\n   }\n\n   /**\n    * This implementation invokes {@link AtmosClient#listDirectory}\n    */\n   @Override\n   public PageSet<? extends StorageMetadata> list(String container,\n            org.jclouds.blobstore.options.ListContainerOptions options) {\n      // TODO: recursive?\n      if (!Strings.nullToEmpty(options.getDelimiter()).equals(\"/\") && !Strings.isNullOrEmpty(options.getPrefix())) {\n         throw new IllegalArgumentException(\"Atmos can only list via prefix if delimiter is / and the prefix matches an existing directory\");\n      }\n      container = AtmosUtils.adjustContainerIfDirOptionPresent(container, options);\n      if (!Strings.isNullOrEmpty(options.getPrefix())) {\n         // this only works when the prefix exactly matches a directory, the common usage\n         container += \"/\" + options.getPrefix();\n      }\n      ListOptions nativeOptions = container2ContainerListOptions.apply(options);\n      // until includeMeta() option works for namespace interface\n      PageSet<? extends StorageMetadata> list = container2ResourceList.apply(sync.listDirectory(container,\n               nativeOptions));\n      return options.isDetailed() ? fetchBlobMetadataProvider.get().setContainerName(container).apply(list) : list;\n   }\n\n   /**\n    * This implementation invokes {@link AtmosClient#createFile}\n    * <p/>\n    * Since there is no etag support in atmos, we just return the path.\n    */\n   @Override\n   public String putBlob(final String container, final Blob blob) {\n      return putBlob(container, blob, PutOptions.NONE);\n   }\n\n   /**\n    * This implementation invokes {@link AtmosClient#createFile}\n    * <p/>\n    * Since there is no etag support in atmos, we just return the path.\n    */\n   @Override\n   public String putBlob(String container, Blob blob, PutOptions options) {\n      if (options.isMultipart()) {\n         throw new UnsupportedOperationException(\"Atmos does not support multipart uploads\");\n      }\n      org.jclouds.atmos.options.PutOptions atmosOptions = new org.jclouds.atmos.options.PutOptions();\n      atmosOptions.publicNone();\n      try {\n         // TODO: not needed\n         if (isPublic.getUnchecked(container + \"/\"))\n            atmosOptions.publicRead();\n      } catch (CacheLoader.InvalidCacheLoadException e) {\n         // nulls not permitted\n      }\n      if (options.getBlobAccess() == BlobAccess.PUBLIC_READ) {\n         atmosOptions.publicRead();\n      }\n      return AtmosUtils.putBlob(sync, crypto, blob2Object, container, blob, atmosOptions);\n   }\n\n   /**\n    * This implementation invokes {@link AtmosClient#deletePath}\n    */\n   @Override\n   public void removeBlob(String container, String key) {\n      sync.deletePath(container + \"/\" + key);\n   }\n\n   @Override\n   public BlobAccess getBlobAccess(String container, String key) {\n      if (sync.isPublic(container + \"/\" + key)) {\n         return BlobAccess.PUBLIC_READ;\n      } else {\n         return BlobAccess.PRIVATE;\n      }\n   }\n\n   @Override\n   public void setBlobAccess(String container, String key, BlobAccess access) {\n      org.jclouds.atmos.options.PutOptions options = new org.jclouds.atmos.options.PutOptions();\n      if (access == BlobAccess.PUBLIC_READ) {\n         options.publicRead();\n      } else {\n         options.publicNone();\n      }\n      sync.setGroupAcl(container + \"/\" + key, options);\n   }\n\n   @Override\n   public boolean createContainerInLocation(Location location, String container, CreateContainerOptions options) {\n      if (options.isPublicRead()) {\n         return sync.createDirectory(container, publicRead()) != null;\n      }\n      return createContainerInLocation(location, container);\n   }\n\n   @Override\n   public MultipartUpload initiateMultipartUpload(String container, BlobMetadata blobMetadata, PutOptions options) {\n      throw new UnsupportedOperationException(\"Atmos does not support multipart uploads\");\n   }\n\n   @Override\n   public void abortMultipartUpload(MultipartUpload mpu) {\n      throw new UnsupportedOperationException(\"Atmos does not support multipart uploads\");\n   }\n\n   @Override\n   public String completeMultipartUpload(MultipartUpload mpu, List<MultipartPart> parts) {\n      throw new UnsupportedOperationException(\"Atmos does not support multipart uploads\");\n   }\n\n   @Override\n   public MultipartPart uploadMultipartPart(MultipartUpload mpu, int partNumber, Payload payload) {\n      throw new UnsupportedOperationException(\"Atmos does not support multipart uploads\");\n   }\n\n   @Override\n   public List<MultipartPart> listMultipartUpload(MultipartUpload mpu) {\n      throw new UnsupportedOperationException(\"Atmos does not support multipart uploads\");\n   }\n\n   @Override\n   public List<MultipartUpload> listMultipartUploads(String container) {\n      throw new UnsupportedOperationException(\"Atmos does not support multipart uploads\");\n   }\n\n   @Override\n   public long getMinimumMultipartPartSize() {\n      throw new UnsupportedOperationException(\"Atmos does not support multipart uploads\");\n   }\n\n   @Override\n   public long getMaximumMultipartPartSize() {\n      throw new UnsupportedOperationException(\"Atmos does not support multipart uploads\");\n   }\n\n   @Override\n   public int getMaximumNumberOfParts() {\n      throw new UnsupportedOperationException(\"Atmos does not support multipart uploads\");\n   }\n\n   @Override\n   public InputStream streamBlob(String container, String name) {\n      throw new UnsupportedOperationException(\"Atmos does not support multipart uploads\");\n   }\n\n   @Override\n   public String copyBlob(String fromContainer, String fromName, String toContainer, String toName,\n         CopyOptions options) {\n      if (options.ifMatch() != null) {\n         throw new UnsupportedOperationException(\"Atmos does not support ifMatch\");\n      }\n      if (options.ifNoneMatch() != null) {\n         throw new UnsupportedOperationException(\"Atmos does not support ifNoneMatch\");\n      }\n      return super.copyBlob(fromContainer, fromName, toContainer, toName, options);\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/blobstore/config/AtmosBlobStoreContextModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.blobstore.config;\n\nimport java.util.concurrent.TimeUnit;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.atmos.AtmosClient;\nimport org.jclouds.atmos.blobstore.AtmosBlobRequestSigner;\nimport org.jclouds.atmos.blobstore.AtmosBlobStore;\nimport org.jclouds.blobstore.BlobRequestSigner;\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.attr.ConsistencyModel;\n\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Provides;\nimport com.google.inject.Scopes;\n\npublic class AtmosBlobStoreContextModule extends AbstractModule {\n\n   @Override\n   protected void configure() {\n      bind(ConsistencyModel.class).toInstance(ConsistencyModel.EVENTUAL);\n      bind(BlobStore.class).to(AtmosBlobStore.class).in(Scopes.SINGLETON);\n      bind(BlobRequestSigner.class).to(AtmosBlobRequestSigner.class);\n   }\n\n   @Provides\n   @Singleton\n   protected final LoadingCache<String, Boolean> isPublic(final AtmosClient client) {\n      return CacheBuilder.newBuilder().expireAfterWrite(30, TimeUnit.SECONDS).build(new CacheLoader<String, Boolean>() {\n\n         @Override\n         public String toString() {\n            return \"isPublic()\";\n         }\n\n         @Override\n         public Boolean load(String arg0) throws Exception {\n            return client.isPublic(arg0);\n         }\n      });\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/blobstore/functions/BlobMetadataToObject.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.blobstore.functions;\n\nimport java.util.Map.Entry;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.atmos.domain.AtmosObject;\nimport org.jclouds.atmos.domain.UserMetadata;\nimport org.jclouds.blobstore.domain.BlobMetadata;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class BlobMetadataToObject implements Function<BlobMetadata, AtmosObject> {\n   private final AtmosObject.Factory factory;\n   private final BlobToContentMetadata blob2ContentMd;\n   private final BlobToSystemMetadata blob2SysMd;\n\n   @Inject\n   protected BlobMetadataToObject(AtmosObject.Factory factory,\n            BlobToContentMetadata blob2ContentMd, BlobToSystemMetadata blob2SysMd) {\n      this.factory = factory;\n      this.blob2ContentMd = blob2ContentMd;\n      this.blob2SysMd = blob2SysMd;\n   }\n\n   public AtmosObject apply(BlobMetadata from) {\n      if (from == null)\n         return null;\n      UserMetadata userMd = new UserMetadata();\n      if (from.getUserMetadata() != null) {\n         for (Entry<String, String> entry : from.getUserMetadata().entrySet())\n            userMd.getMetadata().put(entry.getKey().toLowerCase(), entry.getValue());\n      }\n      return factory.create(blob2ContentMd.apply(from), blob2SysMd.apply(from), userMd);\n   }\n\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/blobstore/functions/BlobStoreListOptionsToListOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.blobstore.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.blobstore.options.ListContainerOptions;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Strings;\n\n@Singleton\npublic class BlobStoreListOptionsToListOptions implements\n         Function<ListContainerOptions, org.jclouds.atmos.options.ListOptions> {\n   @Override\n   public org.jclouds.atmos.options.ListOptions apply(ListContainerOptions from) {\n      checkNotNull(from, \"set options to instance NONE instead of passing null\");\n      org.jclouds.atmos.options.ListOptions httpOptions = new org.jclouds.atmos.options.ListOptions();\n      if (!Strings.isNullOrEmpty(from.getMarker())) {\n         httpOptions.token(from.getMarker());\n      }\n      if (from.getMaxResults() != null) {\n         httpOptions.limit(from.getMaxResults());\n      }\n      if (from.isDetailed()) {\n         httpOptions.includeMeta();\n      }\n      return httpOptions;\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/blobstore/functions/BlobToContentMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.blobstore.functions;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.atmos.domain.MutableContentMetadata;\nimport org.jclouds.atmos.domain.internal.DelegatingMutableContentMetadata;\nimport org.jclouds.blobstore.domain.BlobMetadata;\nimport org.jclouds.blobstore.domain.internal.MutableBlobMetadataImpl;\nimport org.jclouds.http.HttpUtils;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class BlobToContentMetadata implements Function<BlobMetadata, MutableContentMetadata> {\n   public MutableContentMetadata apply(BlobMetadata base) {\n      MutableBlobMetadataImpl to = new MutableBlobMetadataImpl();\n      HttpUtils.copy(base.getContentMetadata(), to.getContentMetadata());\n      return new DelegatingMutableContentMetadata(base.getUri(), base.getName(), base.getUri() != null ? base.getUri()\n               .getPath() : null, to.getContentMetadata());\n   }\n\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/blobstore/functions/BlobToObject.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.blobstore.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.atmos.domain.AtmosObject;\nimport org.jclouds.blobstore.domain.Blob;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class BlobToObject implements Function<Blob, AtmosObject> {\n   private final BlobMetadataToObject blobMd2Object;\n\n   @Inject\n   BlobToObject(BlobMetadataToObject blobMd2Object) {\n      this.blobMd2Object = blobMd2Object;\n   }\n\n   public AtmosObject apply(Blob from) {\n      if (from == null)\n         return null;\n      AtmosObject object = blobMd2Object.apply(from.getMetadata());\n      object.setPayload(checkNotNull(from.getPayload(), \"payload: \" + from));\n      object.setAllHeaders(from.getAllHeaders());\n      return object;\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/blobstore/functions/BlobToSystemMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.blobstore.functions;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.atmos.domain.FileType;\nimport org.jclouds.atmos.domain.SystemMetadata;\nimport org.jclouds.blobstore.domain.BlobMetadata;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class BlobToSystemMetadata implements Function<BlobMetadata, SystemMetadata> {\n   public SystemMetadata apply(BlobMetadata base) {\n      return new SystemMetadata(base.getContentMetadata().getContentMD5(), null, base.getLastModified(), null, null,\n               null, 1, null, base.getName(), null, (base.getContentMetadata().getContentLength() != null) ? base\n                        .getContentMetadata().getContentLength() : 0, FileType.REGULAR, \"root\");\n   }\n\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/blobstore/functions/DirectoryEntryListToResourceMetadataList.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.blobstore.functions;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.atmos.domain.BoundedSet;\nimport org.jclouds.atmos.domain.DirectoryEntry;\nimport org.jclouds.atmos.domain.FileType;\nimport org.jclouds.blobstore.domain.PageSet;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.domain.StorageType;\nimport org.jclouds.blobstore.domain.internal.BlobMetadataImpl;\nimport org.jclouds.blobstore.domain.internal.MutableBlobMetadataImpl;\nimport org.jclouds.blobstore.domain.internal.PageSetImpl;\nimport org.jclouds.blobstore.domain.internal.StorageMetadataImpl;\nimport org.jclouds.domain.Location;\nimport org.jclouds.io.payloads.BaseMutableContentMetadata;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\n\n@Singleton\npublic class DirectoryEntryListToResourceMetadataList implements\n         Function<BoundedSet<? extends DirectoryEntry>, PageSet<? extends StorageMetadata>> {\n   private Supplier<Location> defaultLocation;\n\n   @Inject\n   DirectoryEntryListToResourceMetadataList(Supplier<Location> defaultLocation) {\n      this.defaultLocation = defaultLocation;\n   }\n\n   public PageSet<? extends StorageMetadata> apply(BoundedSet<? extends DirectoryEntry> from) {\n\n      return new PageSetImpl<StorageMetadata>(Iterables.transform(from,\n               new Function<DirectoryEntry, StorageMetadata>() {\n\n                  public StorageMetadata apply(DirectoryEntry from) {\n                     StorageType type = from.getType() == FileType.DIRECTORY ? StorageType.FOLDER : StorageType.BLOB;\n                     if (type == StorageType.FOLDER)\n                        return new StorageMetadataImpl(type, from.getObjectID(), from.getObjectName(), defaultLocation\n                                 .get(), null, null, null, null, ImmutableMap.<String, String>of());\n                     else {\n                        BlobMetadataImpl metadata = new BlobMetadataImpl(from.getObjectID(), from.getObjectName(), defaultLocation.get(),\n                                 null, from.getObjectID(), null, from.getModifiedTime(), ImmutableMap.<String, String>of(), null,\n                                 null, new BaseMutableContentMetadata());\n                        MutableBlobMetadataImpl mutable = new MutableBlobMetadataImpl(metadata);\n                        mutable.setSize(from.getSize());\n                        return mutable;\n                     }\n                  }\n\n               }), from.getToken());\n\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/blobstore/functions/ObjectToBlob.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.blobstore.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.atmos.domain.AtmosObject;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.Blob.Factory;\nimport org.jclouds.http.HttpUtils;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class ObjectToBlob implements Function<AtmosObject, Blob> {\n   private final Factory blobFactory;\n   private final ObjectToBlobMetadata object2BlobMd;\n\n   @Inject\n   ObjectToBlob(Factory blobFactory, ObjectToBlobMetadata object2BlobMd) {\n      this.blobFactory = blobFactory;\n      this.object2BlobMd = object2BlobMd;\n   }\n\n   public Blob apply(AtmosObject from) {\n      if (from == null)\n         return null;\n      Blob blob = blobFactory.create(object2BlobMd.apply(from));\n      blob.setPayload(checkNotNull(from.getPayload(), \"payload: \" + from));\n      HttpUtils.copy(from.getContentMetadata(), blob.getPayload().getContentMetadata());\n      blob.setAllHeaders(from.getAllHeaders());\n      return blob;\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/blobstore/functions/ObjectToBlobMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.blobstore.functions;\n\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.Map.Entry;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.atmos.domain.AtmosObject;\nimport org.jclouds.atmos.domain.FileType;\nimport org.jclouds.atmos.filters.ShareUrl;\nimport org.jclouds.atmos.functions.AtmosObjectName;\nimport org.jclouds.blobstore.domain.MutableBlobMetadata;\nimport org.jclouds.blobstore.domain.StorageType;\nimport org.jclouds.blobstore.domain.Tier;\nimport org.jclouds.blobstore.domain.internal.MutableBlobMetadataImpl;\nimport org.jclouds.http.HttpUtils;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Maps;\n\n@Singleton\npublic class ObjectToBlobMetadata implements Function<AtmosObject, MutableBlobMetadata> {\n   private final AtmosObjectName objectName;\n   private final ShareUrl shareUrl;\n\n   private static final Set<String> systemMetadata = ImmutableSet.of(\"atime\", \"mtime\", \"ctime\", \"itime\", \"type\", \"uid\",\n            \"gid\", \"objectid\", \"objname\", \"size\", \"nlink\", \"policyname\");\n\n   @Inject\n   protected ObjectToBlobMetadata(AtmosObjectName objectName, ShareUrl shareUrl)\n            throws SecurityException, NoSuchMethodException {\n      this.objectName = objectName;\n      this.shareUrl = shareUrl;\n   }\n\n   public MutableBlobMetadata apply(AtmosObject from) {\n      if (from == null)\n         return null;\n      MutableBlobMetadata to = new MutableBlobMetadataImpl();\n      to.setId(from.getSystemMetadata().getObjectID());\n      to.setLastModified(from.getSystemMetadata().getLastUserDataModification());\n      HttpUtils.copy(from.getContentMetadata(), to.getContentMetadata());\n      to.setName(objectName.apply(from));\n      to.setUri(from.getContentMetadata().getUri());\n      to.setContainer(Iterables.get(Splitter.on('/').split(from.getContentMetadata().getPath()), 0));\n      if (from.getAllHeaders().containsEntry(\"x-emc-groupacl\", \"other=READ\"))\n         to.setPublicUri(shareUrl.apply(from.getContentMetadata().getPath()));\n      if (from.getSystemMetadata().getType() == FileType.DIRECTORY) {\n         to.setType(StorageType.FOLDER);\n      } else {\n         to.setType(StorageType.BLOB);\n      }\n      Map<String, String> lowerKeyMetadata = Maps.newHashMap();\n      for (Entry<String, String> entry : from.getUserMetadata().getMetadata().entrySet()) {\n         String key = entry.getKey().toLowerCase();\n         if (!systemMetadata.contains(key))\n            lowerKeyMetadata.put(key, entry.getValue());\n      }\n      to.setUserMetadata(lowerKeyMetadata);\n      to.setSize(from.getContentMetadata().getContentLength());\n      to.setTier(Tier.STANDARD);\n      to.setETag(from.getSystemMetadata().getObjectID());\n      to.getContentMetadata().setContentMD5(from.getSystemMetadata().getContentMD5());\n      return to;\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/config/AtmosHttpApiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.config;\n\nimport java.util.Date;\nimport java.util.concurrent.TimeUnit;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.Constants;\nimport org.jclouds.atmos.AtmosClient;\nimport org.jclouds.atmos.handlers.AtmosClientErrorRetryHandler;\nimport org.jclouds.atmos.handlers.AtmosServerErrorRetryHandler;\nimport org.jclouds.atmos.handlers.ParseAtmosErrorFromXmlContent;\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpRetryHandler;\nimport org.jclouds.http.annotation.ClientError;\nimport org.jclouds.http.annotation.Redirection;\nimport org.jclouds.http.annotation.ServerError;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.config.HttpApiModule;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.inject.Provides;\n\n/**\n * Configures the EMC Atmos Online Storage authentication service connection, including logging and\n * http transport.\n */\n@ConfiguresHttpApi\npublic class AtmosHttpApiModule extends HttpApiModule<AtmosClient> {\n\n   @Override\n   protected void configure() {\n      install(new AtmosParserModule());\n      install(new AtmosObjectModule());\n      super.configure();\n   }\n\n   @Provides\n   @TimeStamp\n   protected final String guiceProvideTimeStamp(@TimeStamp Supplier<String> cache) {\n      return provideTimeStamp(cache);\n   }\n\n   protected String provideTimeStamp(@TimeStamp Supplier<String> cache) {\n      return cache.get();\n   }\n\n   /**\n    * borrowing concurrency code to ensure that caching takes place properly\n    */\n   @Provides\n   @TimeStamp\n   final Supplier<String> provideTimeStampCache(@Named(Constants.PROPERTY_SESSION_INTERVAL) long seconds,\n            final DateService dateService) {\n      return Suppliers.memoizeWithExpiration(new Supplier<String>() {\n         @Override\n         public String get() {\n            return dateService.rfc822DateFormat();\n         }\n      }, seconds, TimeUnit.SECONDS);\n   }\n\n   @Provides\n   @TimeStamp\n   protected final Long provideShareableUrlTimeout() {\n      return new Date().getTime() + TimeUnit.HOURS.toMillis(1);\n   }\n\n   @Override\n   protected void bindErrorHandlers() {\n      bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(ParseAtmosErrorFromXmlContent.class);\n      bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(ParseAtmosErrorFromXmlContent.class);\n      bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(ParseAtmosErrorFromXmlContent.class);\n   }\n\n   @Override\n   protected void bindRetryHandlers() {\n      bind(HttpRetryHandler.class).annotatedWith(ClientError.class).to(AtmosClientErrorRetryHandler.class);\n      bind(HttpRetryHandler.class).annotatedWith(ServerError.class).to(AtmosServerErrorRetryHandler.class);\n   }\n\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/config/AtmosObjectModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.config;\n\nimport org.jclouds.atmos.domain.AtmosObject;\nimport org.jclouds.atmos.domain.MutableContentMetadata;\nimport org.jclouds.blobstore.config.BlobStoreObjectModule;\n\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Provides;\n\n/**\n * Configures the domain object mappings needed for all Atmos implementations\n */\npublic class AtmosObjectModule extends AbstractModule {\n\n   /**\n    * explicit factories are created here as it has been shown that Assisted Inject is extremely\n    * inefficient. http://code.google.com/p/google-guice/issues/detail?id=435\n    */\n   @Override\n   protected void configure() {\n      // for converters\n      install(new BlobStoreObjectModule());\n   }\n\n   @Provides\n   final AtmosObject provideAtmosObject(AtmosObject.Factory factory) {\n      return factory.create((MutableContentMetadata) null);\n   }\n\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/config/AtmosParserModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.config;\n\nimport org.jclouds.json.config.GsonModule.DateAdapter;\nimport org.jclouds.json.config.GsonModule.Iso8601DateAdapter;\n\nimport com.google.inject.AbstractModule;\n\npublic class AtmosParserModule extends AbstractModule {\n\n   @Override\n   protected void configure() {\n      bind(DateAdapter.class).to(Iso8601DateAdapter.class);\n   }\n\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/domain/AtmosError.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.domain;\n\n/**\n * When an Atmos Storage request is in error, the client receives an error response.\n * \n * Provides access to EMC Atmos Online Storage resources via their REST API.\n */\npublic class AtmosError {\n   private final int code;\n   private final String message;\n   private String stringSigned;\n\n   @Override\n   public String toString() {\n      return \"AtmosError [code=\" + code + \", message=\" + message\n               + (stringSigned != null ? (\", stringSigned=\" + stringSigned) : \"\") + \"]\";\n   }\n\n   public AtmosError(int code, String message) {\n      this.code = code;\n      this.message = message;\n   }\n\n   public int getCode() {\n      return code;\n   }\n\n   public String getMessage() {\n      return message;\n   }\n\n   public void setStringSigned(String stringSigned) {\n      this.stringSigned = stringSigned;\n   }\n\n   /**\n    * @return what jclouds signed before sending the request.\n    */\n   public String getStringSigned() {\n      return stringSigned;\n   }\n\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/domain/AtmosObject.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.domain;\n\nimport org.jclouds.atmos.domain.internal.AtmosObjectImpl.AtmosObjectFactory;\nimport org.jclouds.io.PayloadEnclosing;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.collect.Multimap;\nimport com.google.inject.ImplementedBy;\n\npublic interface AtmosObject extends PayloadEnclosing, Comparable<AtmosObject> {\n   @ImplementedBy(AtmosObjectFactory.class)\n   public interface Factory {\n      AtmosObject create(@Nullable MutableContentMetadata contentMetadata);\n\n      AtmosObject create(SystemMetadata systemMetadata, UserMetadata userMetadata);\n\n      AtmosObject create(MutableContentMetadata contentMetadata, SystemMetadata systemMetadata,\n            UserMetadata userMetadata);\n\n   }\n\n   MutableContentMetadata getContentMetadata();\n\n   /**\n    * @return System and User metadata relevant to this object.\n    */\n   SystemMetadata getSystemMetadata();\n\n   UserMetadata getUserMetadata();\n\n   Multimap<String, String> getAllHeaders();\n\n   void setAllHeaders(Multimap<String, String> allHeaders);\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/domain/BoundedSet.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.domain;\n\nimport java.util.Set;\n\nimport org.jclouds.atmos.domain.internal.BoundedLinkedHashSet;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.inject.ImplementedBy;\n\n@ImplementedBy(BoundedLinkedHashSet.class)\npublic interface BoundedSet<T> extends Set<T> {\n\n   @Nullable\n   String getToken();\n\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/domain/DirectoryEntry.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.domain;\n\nimport java.util.Date;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.Objects;\n\n/**\n * Metadata of a Atmos Online object\n */\npublic class DirectoryEntry implements Comparable<DirectoryEntry> {\n   private final String objectid;\n   private final FileType type;\n   private final String objname;\n   private final long size;\n   @Nullable private final Date modifiedTime;\n\n   @Deprecated\n   public DirectoryEntry(String objectid, FileType type, String objname, long size) {\n      this(objectid, type, objname, size, null);\n   }\n\n   public DirectoryEntry(String objectid, FileType type, String objname, long size, Date modifiedTime) {\n      this.objectid = objectid;\n      this.objname = objname;\n      this.type = type;\n      this.size = size;\n      this.modifiedTime = modifiedTime != null ? (Date) modifiedTime.clone() : null;\n   }\n\n   public String getObjectID() {\n      return objectid;\n   }\n\n   public String getObjectName() {\n      return objname;\n   }\n\n   public FileType getType() {\n      return type;\n   }\n\n   public long getSize() {\n      return size;\n   }\n\n   public Date getModifiedTime() {\n      return modifiedTime != null ? (Date) modifiedTime.clone() : null;\n   }\n\n   public int compareTo(DirectoryEntry o) {\n      if (getObjectName() == null)\n         return -1;\n      return (this == o) ? 0 : getObjectName().compareTo(o.getObjectName());\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(objectid, objname, type, size);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      DirectoryEntry other = (DirectoryEntry) obj;\n      return Objects.equal(objectid, other.objectid) &&\n            Objects.equal(objname, other.objname) &&\n            Objects.equal(type, other.type) &&\n            Objects.equal(size, other.size);\n   }\n\n   @Override\n   public String toString() {\n      return \"DirectoryEntry [type=\" + type + \", objectid=\" + objectid + \", objname=\" + objname\n               + \", size=\" + size + \"]\";\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/domain/FileType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.domain;\n\npublic enum FileType {\n\n   DIRECTORY, REGULAR, UNRECOGNIZED;\n\n   public String value() {\n      return name().toLowerCase();\n   }\n\n   public static FileType fromValue(String v) {\n      try {\n         return valueOf(v.toUpperCase());\n      } catch (IllegalArgumentException e) {\n         return UNRECOGNIZED;\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/domain/MutableContentMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.domain;\n\nimport java.net.URI;\n\nimport org.jclouds.atmos.domain.internal.DelegatingMutableContentMetadata;\n\nimport com.google.inject.ImplementedBy;\n\n/**\n * metadata of the object\n */\n@ImplementedBy(DelegatingMutableContentMetadata.class)\npublic interface MutableContentMetadata extends org.jclouds.io.MutableContentMetadata {\n\n   String getName();\n\n   void setName(String name);\n\n   URI getUri();\n\n   void setUri(URI uri);\n\n   String getPath();\n\n   void setPath(String path);\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/domain/SystemMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.domain;\n\nimport java.util.Date;\n\nimport org.jclouds.javax.annotation.Nullable;\n\n/**\n * Metadata of a Atmos Online object\n */\npublic class SystemMetadata extends DirectoryEntry {\n\n   private final Date atime;\n   private final Date ctime;\n   private final String gid;\n   private final Date itime;\n   private final Date mtime;\n   private final int nlink;\n   private final String policyname;\n   private final long size;\n   private final String uid;\n   private final byte[] contentmd5;\n\n   public SystemMetadata(@Nullable byte [] contentmd5, Date atime, Date ctime, String gid, Date itime, Date mtime, int nlink,\n            String objectid, String objname, String policyname, long size, FileType type, String uid) {\n      super(objectid, type, objname, size);\n      this.contentmd5 = contentmd5;\n      this.atime = atime;\n      this.ctime = ctime;\n      this.gid = gid;\n      this.itime = itime;\n      this.mtime = mtime;\n      this.nlink = nlink;\n      this.policyname = policyname;\n      this.size = size;\n      this.uid = uid;\n   }\n\n   public String getGroupID() {\n      return gid;\n   }\n\n   public int getHardLinkCount() {\n      return nlink;\n   }\n\n   public Date getInceptionTime() {\n      return itime;\n   }\n\n   public Date getLastAccessTime() {\n      return atime;\n   }\n\n   public Date getLastMetadataModification() {\n      return mtime;\n   }\n\n   public Date getLastUserDataModification() {\n      return ctime;\n   }\n\n   public String getPolicyName() {\n      return policyname;\n   }\n\n   public long getSize() {\n      return size;\n   }\n\n   public String getUserID() {\n      return uid;\n   }\n\n   public byte[] getContentMD5() {\n      return contentmd5;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = super.hashCode();\n      result = prime * result + ((atime == null) ? 0 : atime.hashCode());\n      result = prime * result + ((ctime == null) ? 0 : ctime.hashCode());\n      result = prime * result + ((gid == null) ? 0 : gid.hashCode());\n      result = prime * result + ((itime == null) ? 0 : itime.hashCode());\n      result = prime * result + ((mtime == null) ? 0 : mtime.hashCode());\n      result = prime * result + nlink;\n      result = prime * result + ((policyname == null) ? 0 : policyname.hashCode());\n      result = prime * result + (int) (size ^ (size >>> 32));\n      result = prime * result + ((uid == null) ? 0 : uid.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (!super.equals(obj))\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      SystemMetadata other = (SystemMetadata) obj;\n      if (atime == null) {\n         if (other.atime != null)\n            return false;\n      } else if (!atime.equals(other.atime))\n         return false;\n      if (ctime == null) {\n         if (other.ctime != null)\n            return false;\n      } else if (!ctime.equals(other.ctime))\n         return false;\n      if (gid == null) {\n         if (other.gid != null)\n            return false;\n      } else if (!gid.equals(other.gid))\n         return false;\n      if (itime == null) {\n         if (other.itime != null)\n            return false;\n      } else if (!itime.equals(other.itime))\n         return false;\n      if (mtime == null) {\n         if (other.mtime != null)\n            return false;\n      } else if (!mtime.equals(other.mtime))\n         return false;\n      if (nlink != other.nlink)\n         return false;\n      if (policyname == null) {\n         if (other.policyname != null)\n            return false;\n      } else if (!policyname.equals(other.policyname))\n         return false;\n      if (size != other.size)\n         return false;\n      if (uid == null) {\n         if (other.uid != null)\n            return false;\n      } else if (!uid.equals(other.uid))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"[type=\" + getType() + \", id=\" + getObjectID() + \", name=\" + getObjectName() + \"]\";\n   }\n\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/domain/UploadInfo.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.domain;\n\nimport java.net.URI;\n\npublic class UploadInfo {\n   private final String token;\n   private final URI host;\n\n   public UploadInfo(String token, URI host) {\n      this.token = token;\n      this.host = host;\n   }\n\n   public String getToken() {\n      return token;\n   }\n\n   public URI getHost() {\n      return host;\n   }\n\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/domain/UserMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport com.google.common.collect.Maps;\nimport com.google.common.collect.Sets;\n\n/**\n * User metadata\n */\npublic class UserMetadata {\n   private final Map<String, String> metadata;\n   private final Map<String, String> listableMetadata;\n   private final Set<String> tags;\n   private final Set<String> listableTags;\n\n   public UserMetadata(Map<String, String> metadata, Map<String, String> listableMetadata, Iterable<String> tags,\n         Iterable<String> listableTags) {\n      this.metadata = Maps.newLinkedHashMap(checkNotNull(metadata, \"metadata\"));\n      this.listableMetadata = Maps.newLinkedHashMap(checkNotNull(listableMetadata, \"listableMetadata\"));\n      this.tags = Sets.newLinkedHashSet(checkNotNull(tags, \"tags\"));\n      this.listableTags = Sets.newLinkedHashSet(checkNotNull(listableTags, \"listableTags\"));\n   }\n\n   public UserMetadata() {\n      this.metadata = Maps.newLinkedHashMap();\n      this.listableMetadata = Maps.newLinkedHashMap();\n      this.tags = Sets.newLinkedHashSet();\n      this.listableTags = Sets.newLinkedHashSet();\n   }\n\n   public Map<String, String> getMetadata() {\n      return metadata;\n   }\n\n   public Map<String, String> getListableMetadata() {\n      return listableMetadata;\n   }\n\n   public Set<String> getTags() {\n      return tags;\n   }\n\n   public Set<String> getListableTags() {\n      return listableTags;\n   }\n\n   @Override\n   public String toString() {\n      return \"[metadata=\" + metadata + \", listableMetadata=\" + listableMetadata + \", tags=\" + tags + \", listableTags=\"\n            + listableTags + \"]\";\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((listableMetadata == null) ? 0 : listableMetadata.hashCode());\n      result = prime * result + ((listableTags == null) ? 0 : listableTags.hashCode());\n      result = prime * result + ((metadata == null) ? 0 : metadata.hashCode());\n      result = prime * result + ((tags == null) ? 0 : tags.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      UserMetadata other = (UserMetadata) obj;\n      if (listableMetadata == null) {\n         if (other.listableMetadata != null)\n            return false;\n      } else if (!listableMetadata.equals(other.listableMetadata))\n         return false;\n      if (listableTags == null) {\n         if (other.listableTags != null)\n            return false;\n      } else if (!listableTags.equals(other.listableTags))\n         return false;\n      if (metadata == null) {\n         if (other.metadata != null)\n            return false;\n      } else if (!metadata.equals(other.metadata))\n         return false;\n      if (tags == null) {\n         if (other.tags != null)\n            return false;\n      } else if (!tags.equals(other.tags))\n         return false;\n      return true;\n   }\n\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/domain/internal/AtmosObjectImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.domain.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Provider;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.atmos.domain.AtmosObject;\nimport org.jclouds.atmos.domain.MutableContentMetadata;\nimport org.jclouds.atmos.domain.SystemMetadata;\nimport org.jclouds.atmos.domain.UserMetadata;\nimport org.jclouds.http.internal.PayloadEnclosingImpl;\nimport org.jclouds.io.Payload;\n\nimport com.google.common.collect.LinkedHashMultimap;\nimport com.google.common.collect.Multimap;\n\n/**\n * Default Implementation of {@link AtmosObject}.\n */\npublic class AtmosObjectImpl extends PayloadEnclosingImpl implements AtmosObject, Comparable<AtmosObject> {\n   @Singleton\n   public static class AtmosObjectFactory implements AtmosObject.Factory {\n\n      @Inject\n      Provider<MutableContentMetadata> metadataProvider;\n\n      public AtmosObject create(MutableContentMetadata contentMetadata) {\n         return new AtmosObjectImpl(contentMetadata != null ? contentMetadata : metadataProvider.get());\n      }\n\n      public AtmosObject create(SystemMetadata systemMetadata, UserMetadata userMetadata) {\n         return new AtmosObjectImpl(metadataProvider.get(), systemMetadata, userMetadata);\n      }\n\n      public AtmosObject create(MutableContentMetadata contentMetadata, SystemMetadata systemMetadata,\n               UserMetadata userMetadata) {\n         return new AtmosObjectImpl(contentMetadata, systemMetadata, userMetadata);\n      }\n   }\n\n   private final UserMetadata userMetadata;\n   private final SystemMetadata systemMetadata;\n\n   public SystemMetadata getSystemMetadata() {\n      return systemMetadata;\n   }\n\n   public UserMetadata getUserMetadata() {\n      return userMetadata;\n   }\n\n   private MutableContentMetadata contentMetadata;\n   private Multimap<String, String> allHeaders = LinkedHashMultimap.create();\n\n   public AtmosObjectImpl(MutableContentMetadata contentMetadata, SystemMetadata systemMetadata,\n            UserMetadata userMetadata) {\n      this.contentMetadata = contentMetadata;\n      this.systemMetadata = systemMetadata;\n      this.userMetadata = userMetadata;\n   }\n\n   @Inject\n   public AtmosObjectImpl(MutableContentMetadata contentMetadata) {\n      this(contentMetadata, null, new UserMetadata());\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public MutableContentMetadata getContentMetadata() {\n      return contentMetadata;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Multimap<String, String> getAllHeaders() {\n      return allHeaders;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void setAllHeaders(Multimap<String, String> allHeaders) {\n      this.allHeaders = checkNotNull(allHeaders, \"allHeaders\");\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public int compareTo(AtmosObject o) {\n      if (getContentMetadata().getName() == null)\n         return -1;\n      return (this == o) ? 0 : getContentMetadata().getName().compareTo(o.getContentMetadata().getName());\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = super.hashCode();\n      result = prime * result + ((contentMetadata == null) ? 0 : contentMetadata.hashCode());\n      result = prime * result + ((systemMetadata == null) ? 0 : systemMetadata.hashCode());\n      result = prime * result + ((userMetadata == null) ? 0 : userMetadata.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (!super.equals(obj))\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      AtmosObjectImpl other = (AtmosObjectImpl) obj;\n      if (contentMetadata == null) {\n         if (other.contentMetadata != null)\n            return false;\n      } else if (!contentMetadata.equals(other.contentMetadata))\n         return false;\n      if (systemMetadata == null) {\n         if (other.systemMetadata != null)\n            return false;\n      } else if (!systemMetadata.equals(other.systemMetadata))\n         return false;\n      if (userMetadata == null) {\n         if (other.userMetadata != null)\n            return false;\n      } else if (!userMetadata.equals(other.userMetadata))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"[contentMetadata=\" + contentMetadata + \"]\";\n   }\n\n   @Override\n   public void setPayload(Payload data) {\n      this.payload = data;\n      this.contentMetadata = new DelegatingMutableContentMetadata(contentMetadata.getUri(), contentMetadata.getName(),\n               contentMetadata.getPath(), payload.getContentMetadata());\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/domain/internal/BoundedLinkedHashSet.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.domain.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.LinkedHashSet;\n\nimport org.jclouds.atmos.domain.BoundedSet;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.collect.Iterables;\n\npublic class BoundedLinkedHashSet<T> extends LinkedHashSet<T> implements BoundedSet<T> {\n\n   protected final String token;\n\n   public BoundedLinkedHashSet(Iterable<T> contents, @Nullable String token) {\n      Iterables.addAll(this, checkNotNull(contents, \"contents\"));\n      this.token = token;\n   }\n\n   @Nullable\n   public String getToken() {\n      return token;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = super.hashCode();\n      result = prime * result + ((token == null) ? 0 : token.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (!super.equals(obj))\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      BoundedLinkedHashSet<?> other = (BoundedLinkedHashSet<?>) obj;\n      if (token == null) {\n         if (other.token != null)\n            return false;\n      } else if (!token.equals(other.token))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"[token=\" + token + \", contents=\" + super.toString() + \"]\";\n   }\n\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/domain/internal/DelegatingMutableContentMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.domain.internal;\n\nimport java.net.URI;\nimport java.util.Date;\n\nimport org.jclouds.atmos.domain.MutableContentMetadata;\nimport org.jclouds.io.ContentMetadataBuilder;\nimport org.jclouds.io.payloads.BaseMutableContentMetadata;\n\nimport com.google.common.hash.HashCode;\n\npublic class DelegatingMutableContentMetadata implements MutableContentMetadata {\n   private URI uri;\n   private String name;\n   private String path;\n   private final org.jclouds.io.MutableContentMetadata delegate;\n\n   public DelegatingMutableContentMetadata() {\n      this(null, null, null, new BaseMutableContentMetadata());\n   }\n\n   public DelegatingMutableContentMetadata(URI uri, String name, String path,\n            org.jclouds.io.MutableContentMetadata delegate) {\n      this.uri = uri;\n      this.name = name;\n      this.delegate = delegate;\n      this.path = path;\n   }\n\n   @Override\n   public Long getContentLength() {\n      return delegate.getContentLength();\n   }\n\n   /** @deprecated use {@link #getContentMD5AsHashCode()} instead. */\n   @Deprecated\n   @Override\n   public byte[] getContentMD5() {\n      return delegate.getContentMD5();\n   }\n\n   @Override\n   public HashCode getContentMD5AsHashCode() {\n      return delegate.getContentMD5AsHashCode();\n   }\n\n   @Override\n   public String getContentType() {\n      return delegate.getContentType();\n   }\n\n   @Override\n   public String getName() {\n      return name;\n   }\n\n   @Override\n   public void setContentLength(Long contentLength) {\n      delegate.setContentLength(contentLength);\n   }\n\n   /** @deprecated use {@link #setContentMD5(HashCode)} instead. */\n   @Deprecated\n   @Override\n   public void setContentMD5(byte[] contentMD5) {\n      delegate.setContentMD5(contentMD5);\n   }\n\n   @Override\n   public void setContentMD5(HashCode contentMD5) {\n      delegate.setContentMD5(contentMD5);\n   }\n\n   @Override\n   public void setContentType(String contentType) {\n      delegate.setContentType(contentType);\n   }\n\n   @Override\n   public void setName(String name) {\n      this.name = name;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      DelegatingMutableContentMetadata other = (DelegatingMutableContentMetadata) obj;\n      if (uri == null) {\n         if (other.uri != null)\n            return false;\n      } else if (!uri.equals(other.uri))\n         return false;\n      return true;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((uri == null) ? 0 : uri.hashCode());\n      return result;\n   }\n\n   @Override\n   public String toString() {\n      return \"[uri=\" + uri + \", name=\" + name + \", path=\" + path + \", delegate=\" + delegate + \"]\";\n   }\n\n   public org.jclouds.io.MutableContentMetadata getDelegate() {\n      return delegate;\n   }\n\n   @Override\n   public void setCacheControl(String cacheControl) {\n      delegate.setCacheControl(cacheControl);\n   }\n\n   @Override\n   public void setContentDisposition(String contentDisposition) {\n      delegate.setContentDisposition(contentDisposition);\n   }\n\n   @Override\n   public void setContentEncoding(String contentEncoding) {\n      delegate.setContentEncoding(contentEncoding);\n   }\n\n   @Override\n   public void setContentLanguage(String contentLanguage) {\n      delegate.setContentLanguage(contentLanguage);\n   }\n\n   @Override\n   public String getCacheControl() {\n      return delegate.getCacheControl();\n   }\n\n   @Override\n   public String getContentDisposition() {\n      return delegate.getContentDisposition();\n   }\n\n   @Override\n   public String getContentEncoding() {\n      return delegate.getContentEncoding();\n   }\n\n   @Override\n   public String getContentLanguage() {\n      return delegate.getContentLanguage();\n   }\n\n   @Override\n   public void setExpires(Date expires) {\n      delegate.setExpires(expires);\n   }\n\n   @Override\n   public Date getExpires() {\n      return delegate.getExpires();\n   }\n\n   @Override\n   public ContentMetadataBuilder toBuilder() {\n      return delegate.toBuilder();\n   }\n\n   @Override\n   public URI getUri() {\n      return uri;\n   }\n\n   @Override\n   public void setUri(URI uri) {\n      this.uri = uri;\n   }\n\n   @Override\n   public String getPath() {\n      return path;\n   }\n\n   @Override\n   public void setPath(String path) {\n      this.path = path;\n   }\n\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/fallbacks/EndpointIfAlreadyExists.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.fallbacks;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Throwables.propagate;\n\nimport java.net.URI;\n\nimport org.jclouds.Fallback;\nimport org.jclouds.blobstore.KeyAlreadyExistsException;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.rest.InvocationContext;\n\nimport com.google.common.annotations.VisibleForTesting;\n\npublic class EndpointIfAlreadyExists implements Fallback<URI>, InvocationContext<EndpointIfAlreadyExists> {\n\n   private URI endpoint;\n\n   @Override\n   public URI createOrPropagate(Throwable t) throws Exception {\n      if (checkNotNull(t, \"throwable\") instanceof KeyAlreadyExistsException) {\n         return endpoint;\n      }\n      throw propagate(t);\n   }\n\n   @Override\n   public EndpointIfAlreadyExists setContext(HttpRequest request) {\n      return setEndpoint(request == null ? null : request.getEndpoint());\n   }\n\n   @VisibleForTesting\n   EndpointIfAlreadyExists setEndpoint(@Nullable URI endpoint) {\n      this.endpoint = endpoint;\n      return this;\n   }\n\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/fallbacks/TrueOn404FalseOnPathNotEmpty.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.fallbacks;\n\nimport static com.google.common.base.Throwables.propagate;\nimport static org.jclouds.util.Throwables2.getFirstThrowableOfType;\n\nimport org.jclouds.Fallback;\nimport org.jclouds.atmos.AtmosResponseException;\nimport org.jclouds.atmos.reference.AtmosErrorCode;\nimport org.jclouds.http.HttpUtils;\n\npublic final class TrueOn404FalseOnPathNotEmpty implements Fallback<Boolean> {\n   @Override\n   public Boolean createOrPropagate(Throwable t) throws Exception {\n      if (HttpUtils.contains404(t)) {\n         return true;\n      }\n      AtmosResponseException exception = getFirstThrowableOfType(t, AtmosResponseException.class);\n      if (exception != null && exception.getError().getCode() == AtmosErrorCode.DIRECTORY_NOT_EMPTY.getCode()) {\n         return false;\n      }\n      throw propagate(t);\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/filters/ShareUrl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.filters;\n\nimport static com.google.common.base.Throwables.propagate;\nimport static com.google.common.io.BaseEncoding.base64;\nimport static com.google.common.io.ByteStreams.readBytes;\nimport static org.jclouds.Constants.LOGGER_SIGNATURE;\nimport static org.jclouds.crypto.Macs.asByteProcessor;\nimport static org.jclouds.http.Uris.uriBuilder;\nimport static org.jclouds.util.Strings2.toInputStream;\n\nimport java.io.IOException;\nimport java.net.URI;\nimport java.security.InvalidKeyException;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.crypto.Crypto;\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.location.Provider;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.io.ByteProcessor;\n\n/**\n * Signs the EMC Atmos Online Storage request.\n * \n * @see <a href=\"https://community.emc.com/community/labs/atmos_online\" />\n */\n@Singleton\npublic class ShareUrl implements Function<String, URI> {\n\n   private final Supplier<Credentials> creds;\n   private final Supplier<URI> provider;\n   private final jakarta.inject.Provider<Long> timeStampProvider;\n   private final Crypto crypto;\n\n   @Resource\n   Logger logger = Logger.NULL;\n\n   @Resource\n   @Named(LOGGER_SIGNATURE)\n   Logger signatureLog = Logger.NULL;\n\n   @Inject\n   public ShareUrl(@Provider Supplier<Credentials> creds, @Provider Supplier<URI> provider,\n         @TimeStamp jakarta.inject.Provider<Long> timeStampProvider, Crypto crypto) {\n      this.creds = creds;\n      this.provider = provider;\n      this.timeStampProvider = timeStampProvider;\n      this.crypto = crypto;\n   }\n\n   @Override\n   public URI apply(String path) throws HttpException {\n      String requestedResource = new StringBuilder().append(\"/rest/namespace/\").append(path).toString();\n      String expires = timeStampProvider.get().toString();\n      String signature = signString(createStringToSign(requestedResource, expires));\n      return uriBuilder(provider.get())\n            .replaceQuery(ImmutableMap.of(\"uid\", creds.get().identity, \"expires\", expires, \"signature\", signature))\n            .appendPath(requestedResource).build();\n   }\n\n   public String createStringToSign(String requestedResource, String expires) {\n      StringBuilder toSign = new StringBuilder();\n      toSign.append(\"GET\\n\");\n      toSign.append(requestedResource.toLowerCase()).append(\"\\n\");\n      toSign.append(creds.get().identity).append(\"\\n\");\n      toSign.append(expires);\n      return toSign.toString();\n   }\n\n   public String signString(String toSign) {\n      try {\n         ByteProcessor<byte[]> hmacSHA1 = asByteProcessor(crypto.hmacSHA1(base64().decode(creds.get().credential)));\n         return base64().encode(readBytes(toInputStream(toSign), hmacSHA1));\n      } catch (InvalidKeyException e) {\n         throw propagate(e);\n      } catch (IOException e) {\n         throw propagate(e);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/filters/SignRequest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.filters;\n\nimport static com.google.common.io.BaseEncoding.base64;\nimport static com.google.common.io.ByteStreams.readBytes;\nimport static org.jclouds.Constants.LOGGER_SIGNATURE;\nimport static org.jclouds.crypto.Macs.asByteProcessor;\nimport static org.jclouds.util.Patterns.NEWLINE_PATTERN;\nimport static org.jclouds.util.Strings2.toInputStream;\n\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Provider;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.atmos.reference.AtmosHeaders;\nimport org.jclouds.crypto.Crypto;\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpRequestFilter;\nimport org.jclouds.http.HttpUtils;\nimport org.jclouds.http.internal.SignatureWire;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.util.Strings2;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Strings;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMap.Builder;\nimport com.google.common.collect.Multimaps;\nimport com.google.common.collect.Sets;\nimport com.google.common.io.ByteProcessor;\nimport com.google.common.net.HttpHeaders;\n\n/**\n * Signs the EMC Atmos Online Storage request.\n * \n * @see <a href=\"https://community.emc.com/community/labs/atmos_online\" />\n */\n@Singleton\npublic class SignRequest implements HttpRequestFilter {\n\n   private final SignatureWire signatureWire;\n   private final Supplier<Credentials> creds;\n   private final Provider<String> timeStampProvider;\n   private final Crypto crypto;\n   private final HttpUtils utils;\n\n   @Resource\n   Logger logger = Logger.NULL;\n\n   @Resource\n   @Named(LOGGER_SIGNATURE)\n   Logger signatureLog = Logger.NULL;\n\n   @Inject\n   public SignRequest(SignatureWire signatureWire, @org.jclouds.location.Provider Supplier<Credentials> creds,\n         @TimeStamp Provider<String> timeStampProvider, Crypto crypto, HttpUtils utils) {\n      this.signatureWire = signatureWire;\n      this.creds = creds;\n      this.timeStampProvider = timeStampProvider;\n      this.crypto = crypto;\n      this.utils = utils;\n   }\n\n   @Override\n   public HttpRequest filter(HttpRequest request) throws HttpException {\n      Builder<String, String> builder = ImmutableMap.builder();\n      builder.put(AtmosHeaders.UID, creds.get().identity);\n      String date = timeStampProvider.get();\n      builder.put(HttpHeaders.DATE, date);\n      if (request.getFirstHeaderOrNull(AtmosHeaders.DATE) != null)\n         builder.put(AtmosHeaders.DATE, date);\n      request = request.toBuilder().replaceHeaders(Multimaps.forMap(builder.build())).build();\n      String signature = calculateSignature(createStringToSign(request));\n      request = request.toBuilder().replaceHeader(AtmosHeaders.SIGNATURE, signature).build();\n      utils.logRequest(signatureLog, request, \"<<\");\n      return request;\n   }\n\n   public String createStringToSign(HttpRequest request) {\n      utils.logRequest(signatureLog, request, \">>\");\n      StringBuilder buffer = new StringBuilder();\n      // re-sign the request\n      appendMethod(request, buffer);\n      appendPayloadMetadata(request, buffer);\n      appendHttpHeaders(request, buffer);\n      appendCanonicalizedResource(request, buffer);\n      appendCanonicalizedHeaders(request, buffer);\n      if (signatureWire.enabled())\n         signatureWire.output(buffer.toString());\n      return buffer.toString();\n   }\n\n   public String calculateSignature(String toSign) {\n      String signature = signString(toSign);\n      if (signatureWire.enabled())\n         signatureWire.input(Strings2.toInputStream(signature));\n      return signature;\n   }\n\n   public String signString(String toSign) {\n      try {\n         ByteProcessor<byte[]> hmacSHA1 = asByteProcessor(crypto.hmacSHA1(base64().decode(creds.get().credential)));\n         return base64().encode(readBytes(toInputStream(toSign), hmacSHA1));\n      } catch (Exception e) {\n         throw new HttpException(\"error signing request\", e);\n      }\n   }\n\n   private void appendMethod(HttpRequest request, StringBuilder toSign) {\n      toSign.append(request.getMethod()).append(\"\\n\");\n   }\n   \n   private void appendCanonicalizedHeaders(HttpRequest request, StringBuilder toSign) {\n      // TreeSet == Sort the headers alphabetically.\n      Set<String> headers = Sets.newTreeSet(request.getHeaders().keySet());\n      for (String header : headers) {\n         if (header.startsWith(\"x-emc-\") && !header.equals(AtmosHeaders.SIGNATURE)) {\n            // Convert all header names to lowercase.\n            toSign.append(header.toLowerCase()).append(\":\");\n            // For headers with values that span multiple lines, convert them into one line by\n            // replacing any\n            // newline characters and extra embedded white spaces in the value.\n            for (String value : request.getHeaders().get(header)) {\n               value = value.replace(\"  \", \" \");\n               value = NEWLINE_PATTERN.matcher(value).replaceAll(\"\");\n               toSign.append(value).append(' ');\n            }\n            toSign.deleteCharAt(toSign.lastIndexOf(\" \"));\n            // Concatenate all headers together, using newlines (\\n) separating each header from the\n            // next one.\n            toSign.append(\"\\n\");\n         }\n      }\n      // There should be no terminating newline character at the end of the last header.\n      if (toSign.charAt(toSign.length() - 1) == '\\n')\n         toSign.deleteCharAt(toSign.length() - 1);\n   }\n\n   private void appendPayloadMetadata(HttpRequest request, StringBuilder buffer) {\n      buffer.append(\n            Strings.nullToEmpty(request.getPayload() == null ? null : request.getPayload().getContentMetadata()\n                  .getContentType())).append(\"\\n\");\n   }\n\n   @VisibleForTesting\n   void appendHttpHeaders(HttpRequest request, StringBuilder toSign) {\n      // Only the value is used, not the header\n      // name. If a request does not include the header, this is an empty string.\n      toSign.append(HttpUtils.nullToEmpty(request.getHeaders().get(\"Range\")).toLowerCase()).append(\"\\n\");\n      // Standard HTTP header, in UTC format. Only the date value is used, not the header name.\n      toSign.append(request.getFirstHeaderOrNull(HttpHeaders.DATE)).append(\"\\n\");\n   }\n\n   @VisibleForTesting\n   void appendCanonicalizedResource(HttpRequest request, StringBuilder toSign) {\n      // Path portion of the HTTP request URI, in lowercase.\n      toSign.append(request.getEndpoint().getRawPath().toLowerCase());\n      String query = request.getEndpoint().getRawQuery();\n      if (query != null) {\n         toSign.append(\"?\").append(query);\n      }\n      toSign.append(\"\\n\");\n   }\n\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/functions/AtmosObjectName.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.functions;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.atmos.domain.AtmosObject;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class AtmosObjectName implements Function<Object, String> {\n   @Override\n   public String apply(Object input) {\n      checkArgument(checkNotNull(input, \"input\") instanceof AtmosObject,\n            \"this function is only valid for AtmosObjects!\");\n      AtmosObject object = AtmosObject.class.cast(input);\n\n      return checkNotNull(object.getContentMetadata().getName() != null ? object.getContentMetadata().getName()\n            : object.getSystemMetadata().getObjectName(), \"objectName\");\n   }\n\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/functions/ParseDirectoryListFromContentAndHeaders.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Provider;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.atmos.domain.BoundedSet;\nimport org.jclouds.atmos.domain.DirectoryEntry;\nimport org.jclouds.atmos.domain.internal.BoundedLinkedHashSet;\nimport org.jclouds.atmos.reference.AtmosHeaders;\nimport org.jclouds.atmos.xml.ListDirectoryResponseHandler;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.http.functions.ParseSax.Factory;\n\nimport com.google.common.base.Function;\n\n/**\n * This parses {@link BoundedSet} from HTTP headers and xml content.\n */\n@Singleton\npublic class ParseDirectoryListFromContentAndHeaders implements Function<HttpResponse, BoundedSet<DirectoryEntry>> {\n\n   private final ParseSax.Factory factory;\n   private final Provider<ListDirectoryResponseHandler> listHandlerProvider;\n\n   @Inject\n   ParseDirectoryListFromContentAndHeaders(Factory factory, Provider<ListDirectoryResponseHandler> listHandlerProvider) {\n      this.factory = checkNotNull(factory, \"factory\");\n      this.listHandlerProvider = checkNotNull(listHandlerProvider, \"listHandlerProvider\");\n   }\n\n   /**\n    * parses the http response headers to create a new {@link BoundedSet} object.\n    */\n   public BoundedSet<DirectoryEntry> apply(HttpResponse from) {\n      checkNotNull(from, \"http response\");\n      String token = from.getFirstHeaderOrNull(AtmosHeaders.TOKEN);\n      return new BoundedLinkedHashSet<DirectoryEntry>(factory.create(listHandlerProvider.get()).parse(\n            from.getPayload().getInput()), token);\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/functions/ParseObjectFromHeadersAndHttpContent.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.http.HttpUtils.attemptToParseSizeAndRangeFromHeaders;\n\nimport java.net.URI;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.atmos.domain.AtmosObject;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rest.InvocationContext;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\n\nimport com.google.common.base.Function;\n\n/**\n * Parses response headers and creates a new AtmosObject from them and the HTTP content.\n * \n * @see ParseMetadataFromHeaders\n */\npublic class ParseObjectFromHeadersAndHttpContent implements Function<HttpResponse, AtmosObject>,\n         InvocationContext<ParseObjectFromHeadersAndHttpContent> {\n\n   private final ParseSystemMetadataFromHeaders systemMetadataParser;\n   private final ParseUserMetadataFromHeaders userMetadataParser;\n   private final AtmosObject.Factory objectProvider;\n   private URI uri;\n   private String path;\n\n   @Inject\n   public ParseObjectFromHeadersAndHttpContent(ParseSystemMetadataFromHeaders systemMetadataParser,\n            ParseUserMetadataFromHeaders userMetadataParser, AtmosObject.Factory objectProvider) {\n      this.systemMetadataParser = checkNotNull(systemMetadataParser, \"systemMetadataParser\");\n      this.userMetadataParser = checkNotNull(userMetadataParser, \"userMetadataParser\");\n      this.objectProvider = checkNotNull(objectProvider, \"objectProvider\");\n   }\n\n   /**\n    * First, calls {@link ParseSystemAndUserMetadataFromHeaders}.\n    * \n    * Then, sets the object size based on the Content-Length header and adds the content to the\n    * {@link AtmosObject} result.\n    * \n    * @throws org.jclouds.http.HttpException\n    */\n   public AtmosObject apply(HttpResponse from) {\n      checkNotNull(from, \"http response\");\n      AtmosObject object = objectProvider.create(systemMetadataParser.apply(from), userMetadataParser.apply(from));\n      object.getContentMetadata().setName(object.getSystemMetadata().getObjectName());\n      object.getContentMetadata().setPath(path);\n      object.getContentMetadata().setUri(uri);\n      object.getAllHeaders().putAll(from.getHeaders());\n      object.setPayload(from.getPayload());\n      object.getContentMetadata().setContentLength(attemptToParseSizeAndRangeFromHeaders(from));\n      object.getContentMetadata().setContentMD5(object.getSystemMetadata().getContentMD5());\n      return object;\n   }\n\n   @Override\n   public ParseObjectFromHeadersAndHttpContent setContext(HttpRequest request) {\n      this.uri = request.getEndpoint();\n      return setPath(GeneratedHttpRequest.class.cast(request).getInvocation().getArgs().get(0).toString());\n   }\n\n   private ParseObjectFromHeadersAndHttpContent setPath(String path) {\n      this.path = path;\n      return this;\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/functions/ParseSystemMetadataFromHeaders.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.io.BaseEncoding.base16;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.atmos.domain.FileType;\nimport org.jclouds.atmos.domain.SystemMetadata;\nimport org.jclouds.atmos.reference.AtmosHeaders;\nimport org.jclouds.date.DateService;\nimport org.jclouds.http.HttpResponse;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Splitter;\n\n@Singleton\npublic class ParseSystemMetadataFromHeaders implements Function<HttpResponse, SystemMetadata> {\n   private final DateService dateService;\n\n   @Inject\n   public ParseSystemMetadataFromHeaders(DateService dateService) {\n      this.dateService = checkNotNull(dateService, \"dateService\");\n   }\n\n   public SystemMetadata apply(HttpResponse from) {\n      checkNotNull(from, \"http response\");\n      String meta = checkNotNull(from.getFirstHeaderOrNull(AtmosHeaders.META), AtmosHeaders.META);\n      Map<String, String> metaMap = Splitter.on(\", \").withKeyValueSeparator('=').split(meta);\n      assert metaMap.size() >= 12 : String.format(\"Should be 12 entries in %s\", metaMap);\n\n      byte[] md5 = null;\n      String wschecksum = from.getFirstHeaderOrNull(AtmosHeaders.CHECKSUM);\n      if (wschecksum != null) {\n         String[] parts = wschecksum.split(\"/\");\n         if (parts[0].equalsIgnoreCase(\"MD5\") && parts.length == 3) {\n            md5 = base16().lowerCase().decode(parts[2]);\n         }\n      }\n\n      return new SystemMetadata(md5, dateService.iso8601SecondsDateParse(checkNotNull(metaMap.get(\"atime\"), \"atime\")),\n            dateService.iso8601SecondsDateParse(checkNotNull(metaMap.get(\"ctime\"), \"ctime\")), checkNotNull(\n                  metaMap.get(\"gid\"), \"gid\"), dateService.iso8601SecondsDateParse(checkNotNull(metaMap.get(\"itime\"),\n                  \"itime\")), dateService.iso8601SecondsDateParse(checkNotNull(metaMap.get(\"mtime\"), \"mtime\")),\n            Integer.parseInt(checkNotNull(metaMap.get(\"nlink\"), \"nlink\")), checkNotNull(metaMap.get(\"objectid\"),\n                  \"objectid\"), checkNotNull(metaMap.get(\"objname\"), \"objname\"), checkNotNull(metaMap.get(\"policyname\"),\n                  \"policyname\"), Long.parseLong(checkNotNull(metaMap.get(\"size\"), \"size\")),\n            FileType.fromValue(checkNotNull(metaMap.get(\"type\"), \"type\")), checkNotNull(metaMap.get(\"uid\"), \"uid\"));\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/functions/ParseUserMetadataFromHeaders.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.atmos.domain.UserMetadata;\nimport org.jclouds.atmos.reference.AtmosHeaders;\nimport org.jclouds.http.HttpResponse;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicates;\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Maps;\n\n@Singleton\npublic class ParseUserMetadataFromHeaders implements Function<HttpResponse, UserMetadata> {\n   private static final Set<String> SYS_KEYS = ImmutableSet.of(\n         \"atime\", \"ctime\", \"gid\", \"itime\", \"mtime\", \"nlink\",\n         \"parent\",\n         \"policyname\", \"size\", \"uid\", \"content-md5\", \"objectid\", \"objname\", \"type\");\n\n   public UserMetadata apply(HttpResponse from) {\n      checkNotNull(from, \"http response\");\n\n      Map<String, String> meta = Maps.filterKeys(\n            getMetaMap(checkNotNull(from.getFirstHeaderOrNull(AtmosHeaders.META), AtmosHeaders.META)),\n            Predicates.not(Predicates.in(SYS_KEYS)));\n\n      Map<String, String> listableMeta = (from.getFirstHeaderOrNull(AtmosHeaders.LISTABLE_META) != null) ? getMetaMap(from\n            .getFirstHeaderOrNull(AtmosHeaders.LISTABLE_META)) : ImmutableMap.<String, String> of();\n\n      Iterable<String> tags = (from.getFirstHeaderOrNull(AtmosHeaders.TAGS) != null) ? Splitter.on(\", \").split(\n            from.getFirstHeaderOrNull(AtmosHeaders.TAGS)) : ImmutableSet.<String> of();\n\n      Iterable<String> listableTags = (from.getFirstHeaderOrNull(AtmosHeaders.LISTABLE_TAGS) != null) ? Splitter\n            .on(\", \").split(from.getFirstHeaderOrNull(AtmosHeaders.LISTABLE_TAGS)) : ImmutableSet.<String> of();\n\n      return new UserMetadata(meta, listableMeta, tags, listableTags);\n   }\n\n   private static Map<String, String> getMetaMap(String meta) {\n      return Splitter.on(\", \").withKeyValueSeparator('=').split(meta);\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/functions/ReturnTrueIfGroupACLIsOtherRead.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpResponse;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class ReturnTrueIfGroupACLIsOtherRead implements Function<HttpResponse, Boolean> {\n\n   public Boolean apply(HttpResponse from) {\n      checkNotNull(from, \"http response\");\n      return from.getHeaders().containsEntry(\"x-emc-groupacl\", \"other=READ\");\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/handlers/AtmosClientErrorRetryHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.handlers;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\n\nimport org.jclouds.Constants;\nimport org.jclouds.atmos.domain.AtmosError;\nimport org.jclouds.atmos.reference.AtmosErrorCode;\nimport org.jclouds.atmos.util.AtmosUtils;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpRetryHandler;\nimport org.jclouds.http.HttpUtils;\nimport org.jclouds.http.handlers.BackoffLimitedRetryHandler;\nimport org.jclouds.logging.Logger;\n\nimport com.google.inject.Inject;\n\n/**\n * Handles Retryable responses with error codes in the 4xx range\n * \n * @see Error codes section at <a href=\"https://www.synaptic.att.com/assets/us/en/home/Atmos_Programmers_Guide_1.3.4A.pdf\" />\n */\npublic class AtmosClientErrorRetryHandler implements HttpRetryHandler {\n   private final AtmosUtils utils;\n   private final BackoffLimitedRetryHandler backoffHandler;\n\n   @Inject\n   public AtmosClientErrorRetryHandler(BackoffLimitedRetryHandler backoffHandler,\n            AtmosUtils utils) {\n      this.backoffHandler = backoffHandler;\n      this.utils = utils;\n   }\n\n   @Inject(optional = true)\n   @Named(Constants.PROPERTY_MAX_RETRIES)\n   private int retryCountLimit = 5;\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) {\n      if (command.getFailureCount() > retryCountLimit)\n         return false;\n      if (response.getStatusCode() == 404 && command.getCurrentRequest().getMethod().equals(\"DELETE\")) {\n         command.incrementFailureCount();\n         return true;\n      } else if (response.getStatusCode() == 409) {\n         byte[] content = HttpUtils.closeClientButKeepContentStream(response);\n         // Content can be null in the case of HEAD requests\n         if (content != null) {\n            try {\n               AtmosError error = utils.parseAtmosErrorFromContent(command, response,\n                        new String(content));\n               if (error.getCode() == AtmosErrorCode.CONFLICTING_OPERATION.getCode()) {\n                  return backoffHandler.shouldRetryRequest(command, response);\n               }\n               // don't increment count before here, since backoff handler does already\n               command.incrementFailureCount();\n            } catch (HttpException e) {\n               logger.warn(e, \"error parsing response: %s\", new String(content));\n            }\n         } else {\n            command.incrementFailureCount();\n         }\n         return true;\n      }\n      return false;\n   }\n\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/handlers/AtmosServerErrorRetryHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.handlers;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\n\nimport org.jclouds.Constants;\nimport org.jclouds.atmos.domain.AtmosError;\nimport org.jclouds.atmos.reference.AtmosErrorCode;\nimport org.jclouds.atmos.util.AtmosUtils;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpRetryHandler;\nimport org.jclouds.http.HttpUtils;\nimport org.jclouds.http.handlers.BackoffLimitedRetryHandler;\nimport org.jclouds.logging.Logger;\n\nimport com.google.inject.Inject;\n\n/**\n * Handles Retryable responses with error codes in the 5xx range\n *\n * @see Error codes section at <a href=\"https://www.synaptic.att.com/assets/us/en/home/Atmos_Programmers_Guide_1.3.4A.pdf\" />\n */\npublic class AtmosServerErrorRetryHandler implements HttpRetryHandler {\n   private final AtmosUtils utils;\n   private final BackoffLimitedRetryHandler backoffHandler;\n\n   @Inject\n   public AtmosServerErrorRetryHandler(BackoffLimitedRetryHandler backoffHandler,\n            AtmosUtils utils) {\n      this.backoffHandler = backoffHandler;\n      this.utils = utils;\n   }\n\n   @Inject(optional = true)\n   @Named(Constants.PROPERTY_MAX_RETRIES)\n   private int retryCountLimit = 5;\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) {\n      if (command.getFailureCount() > retryCountLimit) {\n         return false;\n      }\n      if (response.getStatusCode() == 500) {\n         byte[] content = HttpUtils.closeClientButKeepContentStream(response);\n         // Content can be null in the case of HEAD requests\n         if (content != null) {\n            try {\n               AtmosError error = utils.parseAtmosErrorFromContent(command, response,\n                        new String(content));\n               if (error.getCode() == AtmosErrorCode.SERVER_BUSY.getCode()) {\n                  return backoffHandler.shouldRetryRequest(command, response);\n               }\n               // don't increment count before here, since backoff handler does already\n               command.incrementFailureCount();\n            } catch (HttpException e) {\n               logger.warn(e, \"error parsing response: %s\", new String(content));\n            }\n         } else {\n            command.incrementFailureCount();\n         }\n         return false;\n      }\n      return false;\n   }\n\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/handlers/ParseAtmosErrorFromXmlContent.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.handlers;\n\nimport static org.jclouds.http.HttpUtils.releasePayload;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.atmos.AtmosResponseException;\nimport org.jclouds.atmos.domain.AtmosError;\nimport org.jclouds.atmos.reference.AtmosErrorCode;\nimport org.jclouds.atmos.util.AtmosUtils;\nimport org.jclouds.blobstore.ContainerNotFoundException;\nimport org.jclouds.blobstore.KeyAlreadyExistsException;\nimport org.jclouds.blobstore.KeyNotFoundException;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.util.Strings2;\n\n/**\n * This will parse and set an appropriate exception on the command object.\n * \n * @see AtmosError\n */\n@Singleton\npublic class ParseAtmosErrorFromXmlContent implements HttpErrorHandler {\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   private final AtmosUtils utils;\n\n   @Inject\n   public ParseAtmosErrorFromXmlContent(AtmosUtils utils) {\n      this.utils = utils;\n   }\n\n   public static final Pattern DIRECTORY_PATH = Pattern.compile(\"^/rest/namespace/?([^/]+)/$\");\n   public static final Pattern DIRECTORY_KEY_PATH = Pattern.compile(\"^/rest/namespace/?([^/]+)/(.*)\");\n\n   public void handleError(HttpCommand command, HttpResponse response) {\n      Exception exception = new HttpResponseException(command, response);\n      try {\n         AtmosError error = null;\n         if (response.getPayload() != null) {\n            try {\n               String content = Strings2.toStringAndClose(response.getPayload().openStream());\n               if (content != null && content.indexOf('<') >= 0) {\n                  error = utils.parseAtmosErrorFromContent(command, response, Strings2.toInputStream(content));\n               } else {\n                  exception = content != null ? new HttpResponseException(command, response, content) : exception;\n               }\n            } catch (IOException e) {\n               logger.warn(e, \"exception reading error from response\", response);\n            }\n         }\n         if (error != null && error.getCode() == AtmosErrorCode.RESOURCE_ALREADY_EXISTS.getCode()) {\n            File file = new File(command.getCurrentRequest().getEndpoint().getPath());\n            exception = new KeyAlreadyExistsException(file.getParentFile().getAbsolutePath(), file.getName());\n         } else {\n            switch (response.getStatusCode()) {\n            case 401:\n               exception = new AuthorizationException(exception.getMessage(), exception);\n               break;\n            case 404:\n               if (!command.getCurrentRequest().getMethod().equals(\"DELETE\")) {\n                  String message = error != null ? error.getMessage() : String.format(\"%s -> %s\", command.getCurrentRequest()\n                        .getRequestLine(), response.getStatusLine());\n                  String path = command.getCurrentRequest().getEndpoint().getPath();\n                  Matcher matcher = DIRECTORY_PATH.matcher(path);\n                  if (matcher.find()) {\n                     exception = new ContainerNotFoundException(matcher.group(1), message);\n                  } else {\n                     matcher = DIRECTORY_KEY_PATH.matcher(path);\n                     if (matcher.find()) {\n                        exception = new KeyNotFoundException(matcher.group(1), matcher.group(2), message);\n                     }\n                  }\n               }\n               break;\n            default:\n               exception = error != null ? new AtmosResponseException(command, response, error)\n                     : new HttpResponseException(command, response);\n\n            }\n         }\n      } finally {\n         releasePayload(response);\n         command.setException(exception);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/options/ListOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\n\nimport java.util.Collection;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Options used to control paginated results (aka list commands).\n */\npublic class ListOptions extends BaseHttpRequestOptions {\n   public static final ListOptions NONE = new ListOptions();\n   private static final Collection<String> INCLUDE_META = ImmutableList.of(Integer.toString(1));\n\n   /**\n    * specifies the position to resume listing\n    * <p/>\n    * note this is an opaque value and should not be interpreted.\n    */\n   public ListOptions token(String token) {\n      this.headers.put(\"x-emc-token\", checkNotNull(token, \"x-emc-token\"));\n      return this;\n   }\n\n   public String getToken() {\n      return getFirstHeaderOrNull(\"x-emc-token\");\n   }\n\n   /**\n    * the maximum number of items that should be returned. If this is not specified, there is no\n    * limit.\n    */\n   public ListOptions limit(int maxresults) {\n      checkState(maxresults >= 0, \"maxresults must be >= 0\");\n      checkState(maxresults <= 10000, \"maxresults must be <= 10000\");\n      headers.put(\"x-emc-limit\", Integer.toString(maxresults));\n      return this;\n   }\n\n   /**\n    * the maximum number of items that should be returned. If this is not specified, there is no\n    * limit.\n    */\n   public ListOptions includeMeta() {\n      headers.replaceValues(\"x-emc-include-meta\", INCLUDE_META);\n      return this;\n   }\n\n   public boolean metaIncluded() {\n      String meta = getFirstHeaderOrNull(\"x-emc-include-meta\");\n      return (meta != null) ? meta.equals(\"1\") : false;\n   }\n\n   public Integer getLimit() {\n      String maxresults = getFirstHeaderOrNull(\"x-emc-limit\");\n      return (maxresults != null) ? Integer.valueOf(maxresults) : null;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see ListOptions#token(String)\n       */\n      public static ListOptions token(String token) {\n         ListOptions options = new ListOptions();\n         return options.token(token);\n      }\n\n      /**\n       * @see ListOptions#includeMeta()\n       */\n      public static ListOptions includeMeta() {\n         ListOptions options = new ListOptions();\n         return options.includeMeta();\n      }\n\n      /**\n       * @see ListOptions#limit(int)\n       */\n      public static ListOptions limit(int maxKeys) {\n         ListOptions options = new ListOptions();\n         return options.limit(maxKeys);\n      }\n\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/options/PutOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\n/**\n * Contains options supported in the REST API for the PUT operations.\n * <p/>\n * <h2>\n * Usage</h2> The recommended way to instantiate a PutOptions object is to statically import\n * PutOptions.Builder.* and invoke a static creation method followed by an instance mutator (if\n * needed):\n * <p/>\n * <code>\n * import org.jclouds.atmos.options.PutOptions.Builder.*\n * import org.jclouds.atmos.AtmosClient;\n * \n * AtmosClient connection = // get connection\n *  connection.createDirectory(\"directory\", publicRead());\n * <code>\n */\npublic class PutOptions extends BaseHttpRequestOptions {\n   public static final PutOptions NONE = new PutOptions();\n\n   /**\n    * Add public access to all users\n    * \n    */\n   public PutOptions publicRead() {\n      this.replaceHeader(\"x-emc-useracl\", \"root=FULL_CONTROL\");\n      this.replaceHeader(\"x-emc-groupacl\", \"other=READ\");\n      return this;\n   }\n\n   public PutOptions publicNone() {\n      this.replaceHeader(\"x-emc-useracl\", \"root=FULL_CONTROL\");\n      this.replaceHeader(\"x-emc-groupacl\", \"other=NONE\");\n      return this;\n   }\n\n   /**\n    * By default Atmos does not allow overwriting objects.\n    *\n    * Note: older versions of Atmos do not support this header.\n    */\n   public PutOptions overwrite() {\n      this.replaceHeader(\"x-emc-force-overwrite\", \"true\");\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see PutOptions#publicRead\n       */\n      public static PutOptions publicRead() {\n         PutOptions options = new PutOptions();\n         return options.publicRead();\n      }\n\n      public static PutOptions publicNone() {\n         PutOptions options = new PutOptions();\n         return options.publicNone();\n      }\n\n      public static PutOptions overwrite() {\n         PutOptions options = new PutOptions();\n         return options.overwrite();\n      }\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/reference/AtmosErrorCode.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.atmos.reference;\n\n/** Atmos error codes. */\npublic enum AtmosErrorCode {\n   /** Operation aborted because of a conflicting operation in progess against the resource. */\n   CONFLICTING_OPERATION(1006),\n   /** The directory you are attempting to delete is not empty. */\n   DIRECTORY_NOT_EMPTY(1023),\n   /** The requested object was not found. */\n   OBJECT_NOT_FOUND(1003),\n   /** The resource you are trying to create already exists. */\n   RESOURCE_ALREADY_EXISTS(1016),\n   /** The server is busy. Please try again. */\n   SERVER_BUSY(1040),\n   /** There was a mismatch between the signature in the request and the signature as computed by the server. */\n   SIGNATURE_MISMATCH(1032);\n\n   private final int code;\n\n   private AtmosErrorCode(int code) {\n      this.code = code;\n   }\n\n   public int getCode() {\n      return code;\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/reference/AtmosHeaders.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.reference;\n\n/**\n * Query parameters common to Atmos apis.\n * \n * @see <a href=\"https://community.emc.com/community/labs/atmos_online\" />\n */\npublic final class AtmosHeaders {\n\n   public static final String SIGNATURE = \"x-emc-signature\";\n   public static final String LISTABLE_META = \"x-emc-listable-meta\";\n   public static final String META = \"x-emc-meta\";\n   public static final String LISTABLE_TAGS = \"x-emc-listable-tags\";\n   public static final String TAGS = \"x-emc-tags\";\n   public static final String USER_ACL = \"x-emc-useracl\";\n   public static final String DATE = \"x-emc-date\";\n   public static final String GROUP_ACL = \"x-emc-groupacl\";\n   public static final String UID = \"x-emc-uid\";\n   public static final String TOKEN = \"x-emc-token\";\n   public static final String CHECKSUM = \"x-emc-wschecksum\";\n\n   private AtmosHeaders() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/util/AtmosUtils.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.util;\nimport static com.google.common.base.Preconditions.checkState;\nimport static org.jclouds.util.Predicates2.retry;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.InputStream;\nimport java.net.URI;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Provider;\n\nimport org.jclouds.atmos.AtmosClient;\nimport org.jclouds.atmos.blobstore.functions.BlobToObject;\nimport org.jclouds.atmos.domain.AtmosError;\nimport org.jclouds.atmos.domain.AtmosObject;\nimport org.jclouds.atmos.filters.SignRequest;\nimport org.jclouds.atmos.options.PutOptions;\nimport org.jclouds.atmos.reference.AtmosErrorCode;\nimport org.jclouds.atmos.xml.ErrorHandler;\nimport org.jclouds.blobstore.ContainerNotFoundException;\nimport org.jclouds.blobstore.KeyAlreadyExistsException;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.crypto.Crypto;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseSax;\n\nimport com.google.common.base.Predicate;\n\n/**\n * Encryption, Hashing, and IO Utilities needed to sign and verify Atmos Storage requests and\n * responses.\n */\npublic class AtmosUtils {\n\n   @Inject\n   SignRequest signer;\n\n   @Inject\n   ParseSax.Factory factory;\n\n   @Inject\n   Provider<ErrorHandler> errorHandlerProvider;\n\n   public AtmosError parseAtmosErrorFromContent(HttpCommand command, HttpResponse response, InputStream content)\n            throws HttpException {\n      AtmosError error = factory.create(errorHandlerProvider.get()).parse(content);\n      if (error.getCode() == AtmosErrorCode.SIGNATURE_MISMATCH.getCode()) {\n         error.setStringSigned(signer.createStringToSign(command.getCurrentRequest()));\n      }\n      return error;\n\n   }\n\n   public static String putBlob(final AtmosClient sync, Crypto crypto, BlobToObject blob2Object, String container,\n            Blob blob, PutOptions options) {\n      final String path = container + \"/\" + blob.getMetadata().getName();\n      final AtmosObject object = blob2Object.apply(blob);\n\n      URI uri;\n      try {\n         uri = sync.createFile(container, object, options);\n      } catch (KeyAlreadyExistsException e) {\n         deletePathAndEnsureGone(sync, path);\n         uri = sync.createFile(container, object, options);\n      }\n\n      // return object ID as the ETag\n      String objectId = uri.getPath();\n      String prefix = \"/rest/objects/\";\n      checkState(objectId.startsWith(prefix), objectId);\n      return objectId.substring(prefix.length());\n   }\n   \n   public static void deletePathAndEnsureGone(final AtmosClient sync, String path) {\n      checkState(retry(new Predicate<String>() {\n         public boolean apply(String in) {\n            try {\n               sync.deletePath(in);\n               return !sync.pathExists(in);\n            } catch (ContainerNotFoundException e) {\n               return true;\n            }\n         }\n      }, 3000).apply(path), \"%s still exists after deleting!\", path);\n   }\n\n   public AtmosError parseAtmosErrorFromContent(HttpCommand command, HttpResponse response, String content)\n            throws HttpException {\n      return parseAtmosErrorFromContent(command, response, new ByteArrayInputStream(content.getBytes()));\n   }\n\n   public static String adjustContainerIfDirOptionPresent(String container,\n            org.jclouds.blobstore.options.ListContainerOptions options) {\n      if (options != org.jclouds.blobstore.options.ListContainerOptions.NONE) {\n         // if (options.isRecursive()) {\n         // throw new UnsupportedOperationException(\"recursive not currently supported in emcsaas\");\n         // }\n         if (options.getDir() != null) {\n            container = container + \"/\" + options.getDir();\n         }\n      }\n      return container;\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/xml/ErrorHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.xml;\n\nimport org.jclouds.atmos.domain.AtmosError;\nimport org.jclouds.http.functions.ParseSax;\n\n/**\n * Parses the error from the Atmos Online Storage REST API.\n */\npublic class ErrorHandler extends ParseSax.HandlerWithResult<AtmosError> {\n\n   private StringBuilder currentText = new StringBuilder();\n   private int code;\n   private String message;\n\n   public AtmosError getResult() {\n      return new AtmosError(code, message);\n   }\n\n   public void endElement(String uri, String name, String qName) {\n\n      if (qName.equals(\"Code\")) {\n         this.code = Integer.parseInt(currentText.toString().trim());\n      } else if (qName.equals(\"Message\")) {\n         this.message = currentText.toString().trim();\n      }\n      currentText.setLength(0);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/main/java/org/jclouds/atmos/xml/ListDirectoryResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.xml;\n\nimport java.util.Date;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.atmos.domain.DirectoryEntry;\nimport org.jclouds.atmos.domain.FileType;\nimport org.jclouds.date.DateService;\nimport org.jclouds.http.functions.ParseSax;\n\nimport com.google.common.collect.Sets;\n\n/**\n * Parses an object list\n * <p/>\n * \n * @see <a href=\"https://community.emc.com/community/labs/atmos_online\" />\n */\npublic class ListDirectoryResponseHandler extends ParseSax.HandlerWithResult<Set<DirectoryEntry>> {\n\n   private Set<DirectoryEntry> entries = Sets.newLinkedHashSet();\n   private String currentObjectId;\n   private FileType currentType;\n   private String currentFileName;\n   private long currentSize;\n   private Date currentModificationTime;\n\n   // metadata parsing\n   private String currentName;\n\n   private StringBuilder currentText = new StringBuilder();\n\n   private final DateService dateService;\n\n   @Inject\n   ListDirectoryResponseHandler(DateService dateService) {\n      this.dateService = dateService;\n   }\n\n   public Set<DirectoryEntry> getResult() {\n      return entries;\n   }\n\n   public void endElement(String uri, String name, String qName) {\n      if (qName.equals(\"ObjectID\")) {\n         currentObjectId = currentText.toString().trim();\n      } else if (qName.equals(\"FileType\")) {\n         currentType = FileType.fromValue(currentText.toString().trim());\n      } else if (qName.equals(\"Filename\")) {\n         currentFileName = currentText.toString().trim();\n         if (currentFileName.equals(\"\"))\n            currentFileName = null;\n      } else if (qName.equals(\"Name\")) {\n         currentName = currentText.toString().trim();\n      } else if (qName.equals(\"Value\")) {\n         if (currentName.equals(\"size\")) {\n            currentSize = Long.parseLong(currentText.toString().trim());\n         } else if (currentName.equals(\"mtime\")) {\n            currentModificationTime = dateService.iso8601DateOrSecondsDateParse(currentText.toString().trim());\n         }\n      } else if (qName.equals(\"DirectoryEntry\")) {\n         entries.add(new DirectoryEntry(currentObjectId, currentType, currentFileName, currentSize, currentModificationTime));\n      }\n      currentText.setLength(0);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/test/java/org/jclouds/atmos/AtmosApiMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos;\n\nimport org.jclouds.blobstore.internal.BaseBlobStoreApiMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"AtmosApiMetadataTest\")\npublic class AtmosApiMetadataTest extends BaseBlobStoreApiMetadataTest {\n\n   public AtmosApiMetadataTest() {\n      super(new AtmosApiMetadata());\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/test/java/org/jclouds/atmos/AtmosClientLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.base.Preconditions.checkState;\nimport static org.jclouds.util.Predicates2.retry;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\n\nimport java.io.IOException;\nimport java.lang.reflect.UndeclaredThrowableException;\nimport java.net.URI;\nimport java.security.SecureRandom;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.TimeoutException;\n\nimport org.jclouds.atmos.domain.AtmosObject;\nimport org.jclouds.atmos.domain.BoundedSet;\nimport org.jclouds.atmos.domain.DirectoryEntry;\nimport org.jclouds.atmos.domain.FileType;\nimport org.jclouds.atmos.domain.SystemMetadata;\nimport org.jclouds.atmos.options.ListOptions;\nimport org.jclouds.blobstore.ContainerNotFoundException;\nimport org.jclouds.blobstore.KeyAlreadyExistsException;\nimport org.jclouds.blobstore.KeyNotFoundException;\nimport org.jclouds.blobstore.integration.internal.BaseBlobStoreIntegrationTest;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.io.payloads.InputStreamPayload;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Throwables;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Sets;\nimport com.google.common.hash.HashCode;\nimport com.google.common.hash.Hashing;\n\n/**\n * Tests behavior of {@code AtmosClient}\n */\n@Test(groups = \"live\", singleThreaded = true)\npublic class AtmosClientLiveTest extends BaseBlobStoreIntegrationTest {\n   public AtmosClientLiveTest() {\n      provider = \"atmos\";\n   }\n\n   public AtmosClient getApi() {\n      return view.unwrapApi(AtmosClient.class);\n   }\n\n   private static final class HeadMatches implements Runnable {\n      private final AtmosClient connection;\n      private final String name;\n      private final String metadataValue;\n\n      private HeadMatches(AtmosClient connection, String name, String metadataValue) {\n         this.connection = connection;\n         this.name = name;\n         this.metadataValue = metadataValue;\n      }\n\n      public void run() {\n         try {\n            verifyHeadObject(connection, name, metadataValue);\n         } catch (Exception e) {\n            throw new AssertionError(e);\n         }\n      }\n   }\n\n   private static final class ObjectMatches implements Runnable {\n      private final AtmosClient connection;\n      private final String name;\n      private final String metadataValue;\n      private final String compare;\n\n      private ObjectMatches(AtmosClient connection, String name, String metadataValue, String compare) {\n         this.connection = connection;\n         this.name = name;\n         this.metadataValue = metadataValue;\n         this.compare = compare;\n      }\n\n      public void run() {\n         try {\n            verifyObject(connection, name, compare, metadataValue);\n         } catch (Exception e) {\n            throw new AssertionError(e);\n         }\n      }\n   }\n\n   private static final int INCONSISTENCY_WINDOW = 5000;\n   private String containerPrefix = BaseBlobStoreIntegrationTest.CONTAINER_PREFIX + \"live\";\n\n   URI container1;\n   URI container2;\n\n   @Test\n   public void testListDirectorys() throws Exception {\n      BoundedSet<? extends DirectoryEntry> response = getApi().listDirectories();\n      assert null != response;\n   }\n\n   String privateDirectory;\n   String publicDirectory;\n\n   @Test(timeOut = 5 * 60 * 1000)\n   public void testCreateDirectory() throws Exception {\n      boolean created = false;\n      while (!created) {\n         privateDirectory = containerPrefix + new SecureRandom().nextInt();\n         try {\n            created = getApi().createDirectory(privateDirectory) != null;\n         } catch (UndeclaredThrowableException e) {\n            HttpResponseException htpe = (HttpResponseException) e.getCause().getCause();\n            if (htpe.getResponse().getStatusCode() == 409)\n               continue;\n            throw e;\n         }\n      }\n      BoundedSet<? extends DirectoryEntry> response = getApi().listDirectories();\n      for (DirectoryEntry id : response) {\n         BoundedSet<? extends DirectoryEntry> r2 = getApi().listDirectory(id.getObjectName());\n         assert r2 != null;\n      }\n      // subsequent creation should fail\n      assertNull(getApi().createDirectory(privateDirectory));\n   }\n\n   @Test(timeOut = 5 * 60 * 1000, dependsOnMethods = { \"testCreateDirectory\" })\n   public void testListOptions() throws Exception {\n      String data = \"here is my data!\";\n      HashCode hashCode = Hashing.md5().hashString(data, UTF_8);\n      createOrReplaceObject(\"object2\", data, hashCode, \"meta-value1\");\n      createOrReplaceObject(\"object3\", data, hashCode, \"meta-value1\");\n      createOrReplaceObject(\"object4\", data, hashCode, \"meta-value1\");\n      BoundedSet<? extends DirectoryEntry> r2 = getApi().listDirectory(privateDirectory, ListOptions.Builder.limit(1));\n      assertEquals(r2.size(), 1);\n      assert r2.getToken() != null;\n      assertEquals(Iterables.getLast(Sets.newTreeSet(r2)).getObjectName(), \"object2\");\n      r2 = getApi().listDirectory(privateDirectory, ListOptions.Builder.token(r2.getToken()));\n      assertEquals(r2.size(), 2);\n      assert r2.getToken() == null;\n      assertEquals(Iterables.getLast(Sets.newTreeSet(r2)).getObjectName(), \"object4\");\n   }\n\n   @Test(timeOut = 5 * 60 * 1000, dependsOnMethods = { \"testListOptions\" })\n   public void testFileOperations() throws Exception {\n      // create the object\n      System.err.printf(\"creating%n\");\n      String data1 = \"here is my data!\";\n      createOrReplaceObject(\"object\", data1, Hashing.md5().hashString(data1, UTF_8), \"meta-value1\");\n      assertEventuallyObjectMatches(\"object\", \"here is my data!\", \"meta-value1\");\n      assertEventuallyHeadMatches(\"object\", \"meta-value1\");\n\n      // try overwriting the object\n      System.err.printf(\"overwriting%n\");\n      String data2 = \"here is my data?\";\n      createOrReplaceObject(\"object\", data2, Hashing.md5().hashString(data2, UTF_8), \"meta-value?\");\n      assertEventuallyObjectMatches(\"object\", \"here is my data?\", \"meta-value?\");\n\n      for (boolean stream : new boolean[] { true, false }) {\n         System.err.printf(\"upload/delete/create type %s%n\", stream ? \"stream\" : \"string\");\n         // try updating\n         createOrUpdateWithErrorLoop(stream, \"there is my data\", \"2\");\n\n         deleteConfirmed(privateDirectory + \"/object\");\n         // now create\n         createOrUpdateWithErrorLoop(stream, \"where is my data\", \"3\");\n      }\n   }\n\n   @Test(timeOut = 5 * 60 * 1000, dependsOnMethods = { \"testFileOperations\" })\n   public void testPutZeroLengthBlob() throws Exception {\n      AtmosObject object = getApi().newObject();\n      object.getContentMetadata().setName(\"object\");\n      byte[] payload = new byte[0];\n      object.setPayload(Payloads.newPayload(payload));\n      object.getContentMetadata().setContentLength(Long.valueOf(payload.length));\n      replaceObject(object);\n   }\n\n   private void createOrUpdateWithErrorLoop(boolean stream, String data, String metadataValue) throws Exception {\n      createOrReplaceObject(\"object\", makeData(data, stream), Hashing.md5().hashString(data, UTF_8), metadataValue);\n      assertEventuallyObjectMatches(\"object\", data, metadataValue);\n   }\n\n   Object makeData(String in, boolean stream) {\n      return stream ? Strings2.toInputStream(in) : in;\n   }\n\n   private void createOrReplaceObject(String name, Object data, HashCode hashCode, String metadataValue) throws Exception {\n      // Test PUT with string data, ETag hash, and a piece of metadata\n      AtmosObject object = getApi().newObject();\n      object.getContentMetadata().setName(name);\n      object.setPayload(Payloads.newPayload(data));\n      object.getContentMetadata().setContentLength(16L);\n      object.getContentMetadata().setContentMD5(hashCode.asBytes());\n      object.getContentMetadata().setContentType(\"text/plain\");\n      object.getUserMetadata().getMetadata().put(\"Metadata\", metadataValue);\n      replaceObject(object);\n   }\n\n   /**\n    * Due to eventual consistency, container commands may not return correctly immediately. Hence,\n    * we will try up to the inconsistency window to see if the assertion completes.\n    */\n   protected static void assertEventually(Runnable assertion) throws InterruptedException {\n      long start = System.currentTimeMillis();\n      AssertionError error = null;\n      for (int i = 0; i < 30; i++) {\n         try {\n            assertion.run();\n            if (i > 0)\n               System.err.printf(\"%d attempts and %dms asserting %s%n\", i + 1, System.currentTimeMillis() - start,\n                        assertion.getClass().getSimpleName());\n            return;\n         } catch (AssertionError e) {\n            error = e;\n         }\n         Thread.sleep(INCONSISTENCY_WINDOW / 30);\n      }\n      if (error != null)\n         throw error;\n\n   }\n\n   protected void assertEventuallyObjectMatches(final String name, final String compare, final String metadataValue)\n            throws InterruptedException {\n      assertEventually(new ObjectMatches(getApi(), privateDirectory + \"/\" + name, metadataValue, compare));\n   }\n\n   protected void assertEventuallyHeadMatches(final String name, final String metadataValue)\n            throws InterruptedException {\n      assertEventually(new HeadMatches(getApi(), privateDirectory + \"/\" + name, metadataValue));\n   }\n\n   private static void verifyHeadObject(AtmosClient connection, String path, String metadataValue)\n            throws InterruptedException, ExecutionException, TimeoutException, IOException {\n      AtmosObject getBlob = connection.headFile(path);\n      assertEquals(Strings2.toStringAndClose(getBlob.getPayload().openStream()), \"\");\n      verifyMetadata(metadataValue, getBlob);\n   }\n\n   private static void verifyObject(AtmosClient connection, String path, String compare, String metadataValue)\n            throws InterruptedException, ExecutionException, TimeoutException, IOException {\n      AtmosObject getBlob = connection.readFile(path);\n      assertEquals(Strings2.toStringAndClose(getBlob.getPayload().openStream()), compare);\n      verifyMetadata(metadataValue, getBlob);\n   }\n\n   private static void verifyMetadata(String metadataValue, AtmosObject getBlob) {\n      assertEquals(getBlob.getContentMetadata().getContentLength(), Long.valueOf(16));\n      assert getBlob.getContentMetadata().getContentType().startsWith(\"text/plain\");\n      assertEquals(getBlob.getUserMetadata().getMetadata().get(\"Metadata\"), metadataValue);\n      SystemMetadata md = getBlob.getSystemMetadata();\n      assertEquals(md.getSize(), 16);\n      assert md.getGroupID() != null;\n      assertEquals(md.getHardLinkCount(), 1);\n      assert md.getInceptionTime() != null;\n      assert md.getLastAccessTime() != null;\n      assert md.getLastMetadataModification() != null;\n      assert md.getLastUserDataModification() != null;\n      assert md.getObjectID() != null;\n      assertEquals(md.getObjectName(), \"object\");\n      assert md.getPolicyName() != null;\n      assertEquals(md.getType(), FileType.REGULAR);\n      assert md.getUserID() != null;\n   }\n\n   private void replaceObject(AtmosObject object) throws Exception {\n      alwaysDeleteFirstReplaceStrategy(object);\n      // retryAndCheckSystemMetadataAndPutIfPresentReplaceStrategy(object); // HEAD 200 followed by\n      // PUT = 404!\n   }\n\n   private void alwaysDeleteFirstReplaceStrategy(AtmosObject object) throws Exception {\n      deleteConfirmed(privateDirectory + \"/\" + object.getContentMetadata().getName());\n      long time = System.currentTimeMillis();\n      try {\n         getApi().createFile(privateDirectory, object);\n         System.err.printf(\"%s %s; %dms%n\", \"created\", object.getPayload() instanceof InputStreamPayload ? \"stream\"\n                  : \"string\", System.currentTimeMillis() - time);\n      } catch (Exception e) {\n         String message = Throwables.getRootCause(e).getMessage();\n         System.err.printf(\"failure %s %s; %dms: [%s]%n\", \"creating\",\n                  object.getPayload() instanceof InputStreamPayload ? \"stream\" : \"string\", System.currentTimeMillis()\n                           - time, message);\n         throw e;\n      }\n   }\n\n   private void deleteConfirmed(final String path) throws InterruptedException, ExecutionException, TimeoutException {\n      long time = System.currentTimeMillis();\n      deleteConsistencyAware(path);\n      System.err.printf(\"confirmed deletion after %dms%n\", System.currentTimeMillis() - time);\n   }\n\n   protected void deleteImmediateAndVerifyWithHead(final String path) throws InterruptedException, ExecutionException,\n            TimeoutException {\n      try {\n         getApi().deletePath(path);\n      } catch (KeyNotFoundException ex) {\n      }\n      assert !getApi().pathExists(path);\n      System.err.printf(\"path %s doesn't exist%n\", path);\n      assert !getApi().pathExists(path);\n      System.err.printf(\"path %s doesn't exist%n\", path);\n\n   }\n\n   protected void deleteConsistencyAware(String path) throws InterruptedException, ExecutionException,\n            TimeoutException {\n      try {\n         getApi().deletePath(path);\n      } catch (KeyNotFoundException ex) {\n      }\n      checkState(retry(new Predicate<String>() {\n         public boolean apply(String in) {\n            try {\n               return !getApi().pathExists(in);\n            } catch (ContainerNotFoundException e) {\n               return true;\n            }\n         }\n      }, INCONSISTENCY_WINDOW).apply(path), \"%s still exists after deleting!\", path);\n   }\n\n   protected void retryAndCheckSystemMetadataAndPutIfPresentReplaceStrategy(AtmosObject object) throws Exception {\n\n      int failures = 0;\n      while (true) {\n         try {\n            checkSystemMetadataAndPutIfPresentReplaceStrategy(object);\n            break;\n         } catch (ExecutionException e1) {// bug\n            if (!(e1.getCause() instanceof KeyAlreadyExistsException))\n               throw e1;\n            else\n               failures++;\n         }\n      }\n      if (failures > 0)\n         System.err.printf(\"%d failures create/replacing %s%n\", failures,\n                  object.getPayload() instanceof InputStreamPayload ? \"stream\" : \"string\");\n   }\n\n   private void checkSystemMetadataAndPutIfPresentReplaceStrategy(AtmosObject object) throws Exception {\n      long time = System.currentTimeMillis();\n      boolean update = true;\n      try {\n         getApi().getSystemMetadata(privateDirectory + \"/object\");\n      } catch (KeyNotFoundException ex) {\n         update = false;\n      }\n      try {\n         if (update)\n            getApi().updateFile(privateDirectory, object);\n         else\n            getApi().createFile(privateDirectory, object);\n         System.err.printf(\"%s %s; %dms%n\", update ? \"updated\" : \"created\",\n                  object.getPayload() instanceof InputStreamPayload ? \"stream\" : \"string\", System.currentTimeMillis()\n                           - time);\n      } catch (Exception e) {\n         String message = Throwables.getRootCause(e).getMessage();\n         System.err.printf(\"failure %s %s; %dms: [%s]%n\", update ? \"updating\" : \"creating\",\n                  object.getPayload() instanceof InputStreamPayload ? \"stream\" : \"string\", System.currentTimeMillis()\n                           - time, message);\n         throw e;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/test/java/org/jclouds/atmos/AtmosClientTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos;\n\nimport static org.jclouds.reflect.Reflection2.method;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\n\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.atmos.blobstore.functions.BlobToObject;\nimport org.jclouds.atmos.config.AtmosHttpApiModule;\nimport org.jclouds.atmos.domain.AtmosObject;\nimport org.jclouds.atmos.fallbacks.TrueOn404FalseOnPathNotEmpty;\nimport org.jclouds.atmos.filters.SignRequest;\nimport org.jclouds.atmos.functions.ParseDirectoryListFromContentAndHeaders;\nimport org.jclouds.atmos.functions.ParseObjectFromHeadersAndHttpContent;\nimport org.jclouds.atmos.functions.ParseSystemMetadataFromHeaders;\nimport org.jclouds.atmos.functions.ReturnTrueIfGroupACLIsOtherRead;\nimport org.jclouds.atmos.options.ListOptions;\nimport org.jclouds.atmos.options.PutOptions;\nimport org.jclouds.blobstore.BlobStoreFallbacks.NullOnKeyAlreadyExists;\nimport org.jclouds.blobstore.BlobStoreFallbacks.ThrowContainerNotFoundOn404;\nimport org.jclouds.blobstore.BlobStoreFallbacks.ThrowKeyNotFoundOn404;\nimport org.jclouds.blobstore.binders.BindBlobToMultipartFormTest;\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.functions.ParseURIFromListOrLocationHeaderIf20x;\nimport org.jclouds.http.functions.ReleasePayloadAndReturn;\nimport org.jclouds.http.functions.ReturnTrueIf2xx;\nimport org.jclouds.http.options.GetOptions;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.internal.BaseRestAnnotationProcessingTest;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.net.HttpHeaders;\nimport com.google.common.reflect.Invokable;\nimport com.google.inject.Module;\n\n@Test(groups = \"unit\", testName = \"AtmosClientTest\")\npublic class AtmosClientTest extends BaseRestAnnotationProcessingTest<AtmosClient> {\n\n   private BlobToObject blobToObject;\n\n   public void testListDirectories() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AtmosClient.class, \"listDirectories\", ListOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(request, \"GET https://accesspoint.atmosonline.com/rest/namespace/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, HttpHeaders.ACCEPT + \": text/xml\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ParseDirectoryListFromContentAndHeaders.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testListDirectory() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AtmosClient.class, \"listDirectory\", String.class, ListOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"directory\"));\n\n      assertRequestLineEquals(request, \"GET https://accesspoint.atmosonline.com/rest/namespace/directory/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, HttpHeaders.ACCEPT + \": text/xml\\nx-emc-include-meta: 1\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ParseDirectoryListFromContentAndHeaders.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, ThrowContainerNotFoundOn404.class);\n\n      checkFilters(request);\n   }\n\n   public void testListDirectoriesOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AtmosClient.class, \"listDirectories\", ListOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(new ListOptions().limit(1).token(\"asda\")));\n\n      assertRequestLineEquals(request, \"GET https://accesspoint.atmosonline.com/rest/namespace/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, HttpHeaders.ACCEPT + \": text/xml\\nx-emc-limit: 1\\nx-emc-token: asda\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ParseDirectoryListFromContentAndHeaders.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testListDirectoryOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AtmosClient.class, \"listDirectory\", String.class, ListOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"directory\", new ListOptions().limit(1).token(\"asda\")));\n\n      assertRequestLineEquals(request, \"GET https://accesspoint.atmosonline.com/rest/namespace/directory/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, HttpHeaders.ACCEPT + \": text/xml\\nx-emc-include-meta: 1\\nx-emc-limit: 1\\nx-emc-token: asda\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ParseDirectoryListFromContentAndHeaders.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, ThrowContainerNotFoundOn404.class);\n\n      checkFilters(request);\n   }\n\n   public void testCreateDirectory() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AtmosClient.class, \"createDirectory\", String.class, PutOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"dir\"));\n\n      assertRequestLineEquals(request, \"POST https://accesspoint.atmosonline.com/rest/namespace/dir/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, HttpHeaders.ACCEPT + \": */*\\n\");\n      assertPayloadEquals(request, \"\", \"application/octet-stream\", false);\n\n      assertResponseParserClassEquals(method, request, ParseURIFromListOrLocationHeaderIf20x.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnKeyAlreadyExists.class);\n\n      checkFilters(request);\n   }\n\n   public void testCreateDirectoryOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AtmosClient.class, \"createDirectory\", String.class, PutOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"dir\", PutOptions.Builder.publicRead()));\n\n      assertRequestLineEquals(request, \"POST https://accesspoint.atmosonline.com/rest/namespace/dir/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, HttpHeaders.ACCEPT\n               + \": */*\\nx-emc-groupacl: other=READ\\nx-emc-useracl: root=FULL_CONTROL\\n\");\n      assertPayloadEquals(request, \"\", \"application/octet-stream\", false);\n\n      assertResponseParserClassEquals(method, request, ParseURIFromListOrLocationHeaderIf20x.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnKeyAlreadyExists.class);\n\n      checkFilters(request);\n   }\n\n   public void testCreateFile() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AtmosClient.class, \"createFile\", String.class, AtmosObject.class,\n               PutOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"dir\", blobToObject\n               .apply(BindBlobToMultipartFormTest.TEST_BLOB)));\n\n      assertRequestLineEquals(request, \"POST https://accesspoint.atmosonline.com/rest/namespace/dir/hello HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, HttpHeaders.ACCEPT + \": */*\\nExpect: 100-continue\\n\");\n      assertPayloadEquals(request, \"hello\", \"text/plain\", false);\n\n      assertResponseParserClassEquals(method, request, ParseURIFromListOrLocationHeaderIf20x.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testCreateFileOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AtmosClient.class, \"createFile\", String.class, AtmosObject.class,\n               PutOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"dir\", blobToObject\n               .apply(BindBlobToMultipartFormTest.TEST_BLOB), PutOptions.Builder.publicRead()));\n\n      assertRequestLineEquals(request, \"POST https://accesspoint.atmosonline.com/rest/namespace/dir/hello HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, HttpHeaders.ACCEPT\n               + \": */*\\nExpect: 100-continue\\nx-emc-groupacl: other=READ\\nx-emc-useracl: root=FULL_CONTROL\\n\");\n      assertPayloadEquals(request, \"hello\", \"text/plain\", false);\n\n      assertResponseParserClassEquals(method, request, ParseURIFromListOrLocationHeaderIf20x.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testUpdateFile() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AtmosClient.class, \"updateFile\", String.class, AtmosObject.class,\n               PutOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"dir\", blobToObject\n               .apply(BindBlobToMultipartFormTest.TEST_BLOB)));\n\n      assertRequestLineEquals(request, \"PUT https://accesspoint.atmosonline.com/rest/namespace/dir/hello HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, HttpHeaders.ACCEPT + \": */*\\nExpect: 100-continue\\n\");\n      assertPayloadEquals(request, \"hello\", \"text/plain\", false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, ThrowKeyNotFoundOn404.class);\n\n      checkFilters(request);\n   }\n\n   public void testUpdateFileOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AtmosClient.class, \"updateFile\", String.class, AtmosObject.class,\n               PutOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"dir\", blobToObject\n               .apply(BindBlobToMultipartFormTest.TEST_BLOB), PutOptions.Builder.publicRead()));\n\n      assertRequestLineEquals(request, \"PUT https://accesspoint.atmosonline.com/rest/namespace/dir/hello HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, HttpHeaders.ACCEPT\n               + \": */*\\nExpect: 100-continue\\nx-emc-groupacl: other=READ\\nx-emc-useracl: root=FULL_CONTROL\\n\");\n      assertPayloadEquals(request, \"hello\", \"text/plain\", false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, ThrowKeyNotFoundOn404.class);\n\n      checkFilters(request);\n   }\n\n   public void testReadFile() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AtmosClient.class, \"readFile\", String.class, GetOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"dir/file\"));\n\n      assertRequestLineEquals(request, \"GET https://accesspoint.atmosonline.com/rest/namespace/dir/file HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, HttpHeaders.ACCEPT + \": */*\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ParseObjectFromHeadersAndHttpContent.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(request);\n   }\n\n   public void testGetSystemMetadata() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AtmosClient.class, \"getSystemMetadata\", String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"dir/file\"));\n\n      assertRequestLineEquals(request, \"HEAD https://accesspoint.atmosonline.com/rest/namespace/dir/file HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, HttpHeaders.ACCEPT + \": */*\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ParseSystemMetadataFromHeaders.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(request);\n   }\n\n   public void testDeletePath() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AtmosClient.class, \"deletePath\", String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"dir/file\"));\n\n      assertRequestLineEquals(request, \"DELETE https://accesspoint.atmosonline.com/rest/namespace/dir/file HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, HttpHeaders.ACCEPT + \": */*\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ReturnTrueIf2xx.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, TrueOn404FalseOnPathNotEmpty.class);\n\n      checkFilters(request);\n   }\n\n   public void testIsPublic() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AtmosClient.class, \"isPublic\", String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"dir/file\"));\n\n      assertRequestLineEquals(request, \"HEAD https://accesspoint.atmosonline.com/rest/namespace/dir/file HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, HttpHeaders.ACCEPT + \": */*\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ReturnTrueIfGroupACLIsOtherRead.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, FalseOnNotFoundOr404.class);\n\n      checkFilters(request);\n   }\n\n   public void testNewObject() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AtmosClient.class, \"newObject\");\n      assertEquals(method.getReturnType().getRawType(), AtmosObject.class);\n   }\n\n   @Override\n   protected void checkFilters(HttpRequest request) {\n      assertEquals(request.getFilters().size(), 1);\n      assertEquals(request.getFilters().get(0).getClass(), SignRequest.class);\n   }\n\n   @BeforeClass\n   @Override\n   protected void setupFactory() throws IOException {\n      super.setupFactory();\n      blobToObject = injector.getInstance(BlobToObject.class);\n   }\n\n   @Override\n   protected Module createModule() {\n      return new TestAtmosHttpApiModule();\n   }\n\n      @ConfiguresHttpApi\n   private static final class TestAtmosHttpApiModule extends AtmosHttpApiModule {\n      @Override\n      protected void configure() {\n         super.configure();\n      }\n\n      @Override\n      protected String provideTimeStamp(@TimeStamp Supplier<String> cache) {\n         return \"Thu, 05 Jun 2008 16:38:19 GMT\";\n      }\n   }\n\n   protected String provider = \"atmos\";\n\n   @Override\n   public ApiMetadata createApiMetadata() {\n      return new AtmosApiMetadata();\n   }\n\n}\n"
  },
  {
    "path": "apis/atmos/src/test/java/org/jclouds/atmos/binders/BindMetadataToHeadersTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.File;\n\nimport org.jclouds.atmos.domain.AtmosObject;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n/**\n * Tests behavior of {@code BindMetadataToHeaders}\n */\n@Test(groups = \"unit\")\npublic class BindMetadataToHeadersTest {\n   Injector injector = Guice.createInjector();\n   BindMetadataToHeaders binder = injector.getInstance(BindMetadataToHeaders.class);\n\n   public void testGood() {\n      AtmosObject object = injector.getInstance(AtmosObject.Factory.class).create(null);\n      Payload payload = Payloads.newStringPayload(\"\");\n      object.setPayload(payload);\n      object.getUserMetadata().getListableMetadata().put(\"apple\", \"bear\");\n      object.getUserMetadata().getListableMetadata().put(\"sushi\", \"king\");\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://localhost\").build();\n      request = binder.bindToRequest(request, object);\n      assertEquals(request.getFirstHeaderOrNull(\"x-emc-listable-meta\"), \"apple=bear,sushi=king\");\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testMustBeAtmosObject() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      binder.bindToRequest(request, new File(\"foo\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testNullIsBad() {\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").build();\n      binder.bindToRequest(request, null);\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testNullPayloadIsBad() {\n      AtmosObject object = injector.getInstance(AtmosObject.Factory.class).create(null);\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://localhost\").build();\n      binder.bindToRequest(request, object);\n   }\n   \n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testNullContentLengthIllegal() {\n      AtmosObject object = injector.getInstance(AtmosObject.Factory.class).create(null);\n      Payload payload = Payloads.newStringPayload(\"\");\n      payload.getContentMetadata().setContentLength(null);\n      object.setPayload(payload);\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://localhost\").build();\n      binder.bindToRequest(request, object);\n   }\n\n \n}\n"
  },
  {
    "path": "apis/atmos/src/test/java/org/jclouds/atmos/binders/BindUserMetadataToHeadersTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.File;\n\nimport org.jclouds.atmos.domain.UserMetadata;\nimport org.jclouds.http.HttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n/**\n * Tests behavior of {@code BindUserMetadataToHeaders}\n */\n@Test(groups = \"unit\")\npublic class BindUserMetadataToHeadersTest {\n   Injector injector = Guice.createInjector();\n   BindUserMetadataToHeaders binder = injector.getInstance(BindUserMetadataToHeaders.class);\n\n   public void testMeta() {\n      UserMetadata metadata = new UserMetadata();\n      metadata.getMetadata().put(\"apple\", \"bear\");\n      metadata.getMetadata().put(\"sushi\", \"king\");\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://localhost\").build();\n      request = binder.bindToRequest(request, metadata);\n      assertEquals(request.getFirstHeaderOrNull(\"x-emc-meta\"), \"apple=bear,sushi=king\");\n   }\n\n   public void testListableMeta() {\n      UserMetadata metadata = new UserMetadata();\n      metadata.getListableMetadata().put(\"apple\", \"bear\");\n      metadata.getListableMetadata().put(\"sushi\", \"king\");\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://localhost\").build();\n      request = binder.bindToRequest(request, metadata);\n      assertEquals(request.getFirstHeaderOrNull(\"x-emc-listable-meta\"), \"apple=bear,sushi=king\");\n   }\n\n   public void testTags() {\n      UserMetadata tagsdata = new UserMetadata();\n      tagsdata.getTags().add(\"apple\");\n      tagsdata.getTags().add(\"sushi\");\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://localhost\").build();\n      request = binder.bindToRequest(request, tagsdata);\n      assertEquals(request.getFirstHeaderOrNull(\"x-emc-tags\"), \"apple,sushi\");\n   }\n\n   public void testListableTags() {\n      UserMetadata tagsdata = new UserMetadata();\n      tagsdata.getListableTags().add(\"apple\");\n      tagsdata.getListableTags().add(\"sushi\");\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://localhost\").build();\n      request = binder.bindToRequest(request, tagsdata);\n      assertEquals(request.getFirstHeaderOrNull(\"x-emc-listable-tags\"), \"apple,sushi\");\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testMustBeUserMetadata() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      binder.bindToRequest(request, new File(\"foo\"));\n   }\n\n   @Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class })\n   public void testNullIsBad() {\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").build();\n      binder.bindToRequest(request, null);\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/test/java/org/jclouds/atmos/blobstore/AtmosBlobRequestSignerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.blobstore;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.util.Date;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.atmos.AtmosApiMetadata;\nimport org.jclouds.atmos.AtmosClient;\nimport org.jclouds.atmos.config.AtmosHttpApiModule;\nimport org.jclouds.atmos.filters.SignRequest;\nimport org.jclouds.blobstore.BlobRequestSigner;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.Blob.Factory;\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.internal.BaseRestAnnotationProcessingTest;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.hash.HashCode;\nimport com.google.inject.Module;\n\n/**\n * Tests behavior of {@code AtmosBlobRequestSigner}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"AtmosBlobRequestSignerTest\")\npublic class AtmosBlobRequestSignerTest extends BaseRestAnnotationProcessingTest<AtmosClient> {\n\n   public AtmosBlobRequestSignerTest() {\n      // this is base64 decoded in the signer;\n      credential = \"aaaabbbb\"; \n   }\n   \n   private BlobRequestSigner signer;\n   private Factory blobFactory;\n\n   public void testSignGetBlob() throws ArrayIndexOutOfBoundsException, SecurityException, IllegalArgumentException,\n            NoSuchMethodException, IOException {\n      HttpRequest request = signer.signGetBlob(\"container\", \"name\");\n\n      assertRequestLineEquals(request, \"GET https://accesspoint.atmosonline.com/rest/namespace/container/name?uid=identity&expires=1212684799&signature=oijXdvPjHQ/LwWDcdx9Eozsu77o%3D HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertEquals(request.getFilters().size(), 0);\n   }\n\n   public void testSignPutBlob() throws ArrayIndexOutOfBoundsException, SecurityException, IllegalArgumentException,\n            NoSuchMethodException, IOException {\n      HashCode hashCode = HashCode.fromBytes(new byte[16]);\n      Blob blob = blobFactory.create(null);\n      blob.getMetadata().setName(\"name\");\n      blob.setPayload(\"\");\n      blob.getPayload().getContentMetadata().setContentLength(2L);\n      blob.getPayload().getContentMetadata().setContentMD5(hashCode.asBytes());\n      blob.getPayload().getContentMetadata().setContentType(\"text/plain\");\n      blob.getPayload().getContentMetadata().setExpires(new Date(1000));\n      \n      HttpRequest request = signer.signPutBlob(\"container\", blob);\n\n      assertRequestLineEquals(request,\n               \"POST https://accesspoint.atmosonline.com/rest/namespace/container/name HTTP/1.1\");\n      assertNonPayloadHeadersEqual(\n               request,\n               \"Accept: */*\\n\" +\n               \"Date: Thu, 05 Jun 2008 16:38:19 GMT\\n\" +\n               \"Expect: 100-continue\\n\" +\n               \"x-emc-signature: OlAHsoIDCsO5YmqjRxOIM5sp3r0=\\n\" +\n               \"x-emc-uid: identity\\n\" +\n               \"x-emc-wschecksum: MD5/0/00000000000000000000000000000000\\n\");\n\n      assertContentHeadersEqual(request, \"text/plain\", null, null, null, 2L, hashCode.asBytes(), new Date(1000));\n\n      assertEquals(request.getFilters().size(), 0);\n   }\n\n   @BeforeClass\n   protected void setupFactory() throws IOException {\n      super.setupFactory();\n      this.blobFactory = injector.getInstance(Blob.Factory.class);\n      this.signer = injector.getInstance(BlobRequestSigner.class);\n   }\n\n   @Override\n   protected void checkFilters(HttpRequest request) {\n      assertEquals(request.getFilters().size(), 1);\n      assertEquals(request.getFilters().get(0).getClass(), SignRequest.class);\n   }\n\n   @Override\n   protected Module createModule() {\n      return new TestAtmosHttpApiModule();\n   }\n\n      @ConfiguresHttpApi\n   private static final class TestAtmosHttpApiModule extends AtmosHttpApiModule {\n      @Override\n      protected void configure() {\n         super.configure();\n      }\n\n      @Override\n      protected String provideTimeStamp(@TimeStamp Supplier<String> cache) {\n         return \"Thu, 05 Jun 2008 16:38:19 GMT\";\n      }\n   }\n\n   @Override\n   public ApiMetadata createApiMetadata() {\n      return new AtmosApiMetadata();\n   }\n\n}\n"
  },
  {
    "path": "apis/atmos/src/test/java/org/jclouds/atmos/blobstore/functions/ListOptionsToBlobStoreListOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.blobstore.functions;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.blobstore.options.ListContainerOptions;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class ListOptionsToBlobStoreListOptions implements\n         Function<org.jclouds.atmos.options.ListOptions[], ListContainerOptions> {\n   public ListContainerOptions apply(org.jclouds.atmos.options.ListOptions[] optionsList) {\n      ListContainerOptions options = new ListContainerOptions();\n      if (optionsList.length != 0) {\n         if (optionsList[0].getToken() != null) {\n            options.afterMarker(optionsList[0].getToken());\n         }\n         if (optionsList[0].getLimit() != null) {\n            options.maxResults(optionsList[0].getLimit());\n         }\n         if (optionsList[0].metaIncluded()) {\n            options.withDetails();\n         }\n      }\n      return options;\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/test/java/org/jclouds/atmos/blobstore/functions/ResourceMetadataListToDirectoryEntryList.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.blobstore.functions;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.atmos.domain.BoundedSet;\nimport org.jclouds.atmos.domain.DirectoryEntry;\nimport org.jclouds.atmos.domain.FileType;\nimport org.jclouds.atmos.domain.internal.BoundedLinkedHashSet;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.domain.StorageType;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.Iterables;\n\n@Singleton\npublic class ResourceMetadataListToDirectoryEntryList\n         implements\n         Function<org.jclouds.blobstore.domain.PageSet<? extends StorageMetadata>, BoundedSet<? extends DirectoryEntry>> {\n\n   public BoundedSet<DirectoryEntry> apply(\n            org.jclouds.blobstore.domain.PageSet<? extends StorageMetadata> from) {\n\n      return new BoundedLinkedHashSet<DirectoryEntry>(Iterables.transform(from,\n               new Function<StorageMetadata, DirectoryEntry>() {\n                  public DirectoryEntry apply(StorageMetadata from) {\n                     FileType type = (from.getType() == StorageType.FOLDER || from.getType() == StorageType.RELATIVE_PATH) ? FileType.DIRECTORY\n                              : FileType.REGULAR;\n                     return new DirectoryEntry(from.getProviderId(), type, from.getName(), from.getSize());\n                  }\n\n               }), from.getNextMarker());\n\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/test/java/org/jclouds/atmos/blobstore/integration/AtmosBlobSignerLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.blobstore.integration;\n\nimport static org.testng.Assert.fail;\n\nimport org.jclouds.blobstore.integration.internal.BaseBlobSignerLiveTest;\nimport org.testng.SkipException;\nimport org.testng.annotations.Test;\n\n@Test(groups = { \"live\" })\npublic class AtmosBlobSignerLiveTest extends BaseBlobSignerLiveTest {\n   public AtmosBlobSignerLiveTest() {\n      provider = \"atmos\";\n   }\n\n   @Test\n   public void testSignPutUrlWithTime() throws Exception {\n      try {\n         super.testSignPutUrlWithTime();\n         fail();\n      } catch (UnsupportedOperationException uoe) {\n         throw new SkipException(\"not supported in Atmos\", uoe);\n      }\n   }\n\n   @Test\n   public void testSignPutUrlWithTimeExpired() throws Exception {\n      try {\n         super.testSignPutUrlWithTimeExpired();\n         fail();\n      } catch (UnsupportedOperationException uoe) {\n         throw new SkipException(\"not supported in Atmos\", uoe);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/test/java/org/jclouds/atmos/blobstore/integration/AtmosContainerIntegrationLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.blobstore.integration;\n\nimport org.jclouds.blobstore.integration.internal.BaseContainerIntegrationTest;\nimport org.testng.annotations.Test;\nimport org.testng.SkipException;\n\n@Test(groups = \"live\")\npublic class AtmosContainerIntegrationLiveTest extends BaseContainerIntegrationTest {\n   public AtmosContainerIntegrationLiveTest() {\n      provider = \"atmos\";\n   }\n\n   @Override\n   public void testDelimiter() throws Exception {\n      throw new SkipException(\"Atmos does not use key names for markers\");\n   }\n\n   @Override\n   public void testListMarkerAfterLastKey() throws Exception {\n      throw new SkipException(\"cannot specify arbitrary markers\");\n   }\n\n   @Override\n   public void testListMarkerPrefix() throws Exception {\n      throw new SkipException(\"cannot specify arbitrary markers\");\n   }\n\n   @Override\n   public void testListContainerWithZeroMaxResults() throws Exception {\n      throw new SkipException(\"Atmos requires a positive integer for max results\");\n   }\n\n   @Override\n   public void testContainerListWithPrefix() {\n      throw new SkipException(\"Atmos can only list prefix which matches an existing directory\");\n   }\n\n   @Override\n   public void testDelimiterList() {\n      throw new SkipException(\"Delimiter support is not yet implemented\");\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/test/java/org/jclouds/atmos/blobstore/integration/AtmosContainerLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.blobstore.integration;\n\nimport org.jclouds.blobstore.integration.internal.BaseContainerLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = { \"live\" })\npublic class AtmosContainerLiveTest extends BaseContainerLiveTest {\n   public AtmosContainerLiveTest() {\n      provider = \"atmos\";\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/test/java/org/jclouds/atmos/blobstore/integration/AtmosIntegrationLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.blobstore.integration;\n\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown;\n\nimport java.io.IOException;\nimport java.util.concurrent.ExecutionException;\n\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.BlobMetadata;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.domain.Tier;\nimport org.jclouds.blobstore.integration.internal.BaseBlobIntegrationTest;\nimport org.jclouds.blobstore.options.ListContainerOptions;\nimport org.testng.SkipException;\nimport org.testng.annotations.DataProvider;\nimport org.testng.annotations.Test;\n\nimport com.google.common.io.ByteSource;\n\n@Test(groups = { \"integration\", \"live\" })\npublic class AtmosIntegrationLiveTest extends BaseBlobIntegrationTest {\n   public AtmosIntegrationLiveTest() {\n      provider = \"atmos\";\n   }\n   @DataProvider(name = \"delete\")\n   // no unicode support\n   @Override\n   public Object[][] createData() {\n      return new Object[][] { { \"normal\" } };\n   }\n\n   @Override\n   public void testGetTwoRanges() {\n      throw new SkipException(\"Atmos MIME-encodes multiple ranges\");\n   }\n\n   // not supported\n   @Override\n   protected void checkCacheControl(Blob blob, String cacheControl) {\n      assertThat(blob.getPayload().getContentMetadata().getCacheControl()).isNull();\n      assertThat(blob.getMetadata().getContentMetadata().getCacheControl()).isNull();\n   }\n\n   // not supported\n   @Override\n   protected void checkContentDisposition(Blob blob, String contentDisposition) {\n      assert blob.getPayload().getContentMetadata().getContentDisposition() == null;\n      assert blob.getMetadata().getContentMetadata().getContentDisposition() == null;\n   }\n\n   // not supported\n   @Override\n   protected void checkContentEncoding(Blob blob, String contentEncoding) {\n      assert blob.getPayload().getContentMetadata().getContentEncoding() == null;\n      assert blob.getMetadata().getContentMetadata().getContentEncoding() == null;\n   }\n\n   // not supported\n   @Override\n   protected void checkContentLanguage(Blob blob, String contentLanguage) {\n      assert blob.getPayload().getContentMetadata().getContentLanguage() == null;\n      assert blob.getMetadata().getContentMetadata().getContentLanguage() == null;\n   }\n\n   @Override\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testPutObjectStream() throws InterruptedException, IOException, ExecutionException {\n      super.testPutObjectStream();\n   }\n\n   @Override\n   public void testCreateBlobWithExpiry() throws InterruptedException {\n      throw new SkipException(\"Expiration not yet implemented\");\n   }\n\n   @Override\n   public void testMultipartUploadNoPartsAbort() throws Exception {\n      throw new SkipException(\"Atmos does not support multipart uploads\");\n   }\n\n   @Override\n   public void testMultipartUploadSinglePart() throws Exception {\n      throw new SkipException(\"Atmos does not support multipart uploads\");\n   }\n\n   @Override\n   public void testMultipartUploadMultipleParts() throws Exception {\n      throw new SkipException(\"Atmos does not support multipart uploads\");\n   }\n\n   @Override\n   public void testListMultipartUploads() throws Exception {\n      try {\n         super.testListMultipartUploads();\n      } catch (UnsupportedOperationException uoe) {\n         throw new SkipException(\"Atmos does not support multipart uploads\", uoe);\n      }\n   }\n\n   @Override\n   public void testPutMultipartByteSource() throws Exception {\n      throw new SkipException(\"Atmos does not support multipart uploads\");\n   }\n\n   @Override\n   public void testPutMultipartInputStream() throws Exception {\n      throw new SkipException(\"Atmos does not support multipart uploads\");\n   }\n\n   @Override\n   @Test(groups = { \"integration\", \"live\" }, expectedExceptions = UnsupportedOperationException.class)\n   public void testPutBlobAccessMultipart() throws Exception {\n      super.testPutBlobAccessMultipart();\n   }\n\n   @Override\n   @Test(groups = { \"integration\", \"live\" }, expectedExceptions = UnsupportedOperationException.class)\n   public void testCopyIfMatch() throws Exception {\n      super.testCopyIfMatch();\n   }\n\n   @Override\n   @Test(groups = { \"integration\", \"live\" }, expectedExceptions = UnsupportedOperationException.class)\n   public void testCopyIfMatchNegative() throws Exception {\n      super.testCopyIfMatchNegative();\n   }\n\n   @Override\n   @Test(groups = { \"integration\", \"live\" }, expectedExceptions = UnsupportedOperationException.class)\n   public void testCopyIfNoneMatch() throws Exception {\n      super.testCopyIfNoneMatch();\n   }\n\n   @Override\n   @Test(groups = { \"integration\", \"live\" }, expectedExceptions = UnsupportedOperationException.class)\n   public void testCopyIfNoneMatchNegative() throws Exception {\n      super.testCopyIfNoneMatchNegative();\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testPutBlobTierStandardMultipart() throws Exception {\n      try {\n         super.testPutBlobTierStandardMultipart();\n         failBecauseExceptionWasNotThrown(UnsupportedOperationException.class);\n      } catch (UnsupportedOperationException uoe) {\n         throw new SkipException(\"Atmos does not support multipart\", uoe);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testPutBlobTierInfrequentMultipart() throws Exception {\n      try {\n         super.testPutBlobTierInfrequentMultipart();\n         failBecauseExceptionWasNotThrown(UnsupportedOperationException.class);\n      } catch (UnsupportedOperationException uoe) {\n         throw new SkipException(\"Atmos does not support multipart\", uoe);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testPutBlobTierArchiveMultipart() throws Exception {\n      try {\n         super.testPutBlobTierArchiveMultipart();\n         failBecauseExceptionWasNotThrown(UnsupportedOperationException.class);\n      } catch (UnsupportedOperationException uoe) {\n         throw new SkipException(\"Atmos does not support multipart\", uoe);\n      }\n   }\n\n   @Override\n   protected void checkTier(BlobMetadata metadata, Tier expected) {\n      // Atmos maps all tiers to STANDARD\n      assertThat(metadata.getTier()).isEqualTo(Tier.STANDARD);\n   }\n\n   // TODO: promote test to portable abstraction?\n   @Test(groups = { \"integration\", \"live\" })\n   public void testETag() throws Exception {\n      String blobName = \"test-etag\";\n      ByteSource payload = ByteSource.empty();\n      BlobStore blobStore = view.getBlobStore();\n      String containerName = getContainerName();\n      try {\n         Blob blob = blobStore.blobBuilder(blobName)\n            .payload(payload)\n            .contentLength(payload.size())\n            .build();\n         String eTag = blobStore.putBlob(containerName, blob);\n         assertThat(eTag).hasSize(44);\n\n         BlobMetadata metadata = blobStore.blobMetadata(containerName, blobName);\n         assertThat(metadata.getETag()).isEqualTo(eTag);\n\n         for (StorageMetadata sm : blobStore.list(containerName, ListContainerOptions.NONE)) {\n            assertThat(sm.getETag()).isEqualTo(eTag);\n         }\n      } finally {\n         returnContainer(containerName);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/test/java/org/jclouds/atmos/blobstore/integration/AtmosLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.blobstore.integration;\n\nimport org.jclouds.blobstore.integration.internal.BaseBlobLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = { \"live\" })\npublic class AtmosLiveTest extends BaseBlobLiveTest {\n   public AtmosLiveTest() {\n      provider = \"atmos\";\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/test/java/org/jclouds/atmos/blobstore/integration/AtmosServiceIntegrationLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.blobstore.integration;\n\nimport org.jclouds.blobstore.integration.internal.BaseServiceIntegrationTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\")\npublic class AtmosServiceIntegrationLiveTest extends BaseServiceIntegrationTest {\n   public AtmosServiceIntegrationLiveTest() {\n      provider = \"atmos\";\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/test/java/org/jclouds/atmos/fallbacks/EndpointIfAlreadyExistsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.fallbacks;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\n\nimport java.net.URI;\n\nimport org.jclouds.blobstore.KeyAlreadyExistsException;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class EndpointIfAlreadyExistsTest {\n\n   @Test\n   public void testFoundIsNullWhenEndpointNotSet() throws Exception {\n      assertNull(new EndpointIfAlreadyExists().createOrPropagate(new KeyAlreadyExistsException()));\n   }\n\n   @Test\n   public void testFoundIsEndpointWhenSet() throws Exception {\n      assertEquals(\n            new EndpointIfAlreadyExists().setEndpoint(URI.create(\"foo\")).createOrPropagate(\n                  new KeyAlreadyExistsException()), URI.create(\"foo\"));\n   }\n\n   @Test(expectedExceptions = RuntimeException.class)\n   public void testNotFoundPropagates() throws Exception {\n      new EndpointIfAlreadyExists().createOrPropagate(new RuntimeException());\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testNullIsBad() throws Exception {\n      new EndpointIfAlreadyExists().createOrPropagate(null);\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/test/java/org/jclouds/atmos/filters/SignRequestTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.filters;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.security.InvalidKeyException;\nimport java.security.NoSuchAlgorithmException;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.atmos.config.AtmosHttpApiModule;\nimport org.jclouds.atmos.reference.AtmosHeaders;\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.logging.config.NullLoggingModule;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.internal.BaseRestApiTest.MockModule;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableMultimap.Builder;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Multimap;\nimport com.google.common.net.HttpHeaders;\nimport com.google.inject.Injector;\nimport com.google.inject.Module;\n\n@Test(groups = \"unit\")\npublic class SignRequestTest {\n\n   private static final String EXPECTED_SIGNATURE = \"WHJo1MFevMnK4jCthJ974L3YHoo=\";\n   private static final String UID = \"6039ac182f194e15b9261d73ce044939/user1\";\n   private static final String DEFAULT_DATE = \"Thu, 05 Jun 2008 16:38:19 GMT\";\n   private static final String KEY = \"LJLuryj6zs8ste6Y3jTGQp71xq0=\";\n\n   private SignRequest filter;\n\n   @Test\n   void testCreateStringToSign() throws IOException {\n      String expects = Strings2.toStringAndClose(getClass().getResourceAsStream(\"/hashstring.txt\"));\n      HttpRequest request = newRequest(preconstructedHeaders().build());\n      String toSign = filter.createStringToSign(request);\n      assertEquals(toSign, expects);\n   }\n\n   @Test\n   void testSignString() throws IOException, NoSuchAlgorithmException, InvalidKeyException {\n      HttpRequest request = newRequest(preconstructedHeaders().build());\n      String toSign = filter.createStringToSign(request);\n      String signature = filter.signString(toSign);\n      assertEquals(signature, EXPECTED_SIGNATURE);\n   }\n\n   @Test\n   void testFilter() throws IOException, NoSuchAlgorithmException, InvalidKeyException {\n      HttpRequest request = newRequest(inputHeaders().build());\n      request = filter.filter(request);\n      assertEquals(request.getFirstHeaderOrNull(AtmosHeaders.SIGNATURE), EXPECTED_SIGNATURE);\n   }\n\n   @Test\n   void testFilterReplacesOldValues() throws IOException, NoSuchAlgorithmException, InvalidKeyException {\n      HttpRequest request = newRequest(inputHeaders().put(AtmosHeaders.SIGNATURE, \"foo\")\n            .put(HttpHeaders.DATE, \"foo\").put(AtmosHeaders.DATE, \"foo\").put(AtmosHeaders.UID, \"foo\")\n            .build());\n      request = filter.filter(request);\n      assertEquals(request.getFirstHeaderOrNull(AtmosHeaders.SIGNATURE), EXPECTED_SIGNATURE);\n   }\n\n   @BeforeClass\n   protected void createFilter() {\n      Injector injector = ContextBuilder\n            .newBuilder(\"atmos\")\n            .credentials(UID, KEY)\n            .modules(\n                  ImmutableSet.<Module> of(new MockModule(), new TestAtmosHttpApiModule(), new NullLoggingModule()))\n            .buildInjector();\n\n      filter = injector.getInstance(SignRequest.class);\n\n   }\n\n      @ConfiguresHttpApi\n   private static final class TestAtmosHttpApiModule extends AtmosHttpApiModule {\n\n      @Override\n      protected void configure() {\n         super.configure();\n      }\n\n      @Override\n      protected String provideTimeStamp(@TimeStamp Supplier<String> cache) {\n         return DEFAULT_DATE;\n      }\n   }\n\n   public HttpRequest newRequest(Multimap<String, String> headers) {\n      HttpRequest request = HttpRequest.builder()\n                                       .method(\"POST\")\n                                       .endpoint(\"http://localhost/rest/objects\")\n                                       .headers(headers).build();\n      request.setPayload(\"\");\n      request.getPayload().getContentMetadata().setContentLength(4286L);\n      request.getPayload().getContentMetadata().setContentType(MediaType.APPLICATION_OCTET_STREAM);\n      return request;\n   }\n\n   protected Builder<String, String> preconstructedHeaders() {\n      Builder<String, String> builder = inputHeaders();\n      builder.put(HttpHeaders.DATE, DEFAULT_DATE);\n      builder.put(AtmosHeaders.UID, UID);\n      return builder;\n   }\n\n   protected Builder<String, String> inputHeaders() {\n      Builder<String, String> builder = ImmutableMultimap.builder();\n      builder.put(AtmosHeaders.LISTABLE_META, \"part4/part7/part8=quick\");\n      builder.put(AtmosHeaders.META, \"part1=buy\");\n      builder.put(HttpHeaders.ACCEPT, \"*/*\");\n      builder.put(AtmosHeaders.USER_ACL, \"john=FULL_CONTROL,mary=WRITE\");\n      builder.put(AtmosHeaders.GROUP_ACL, \"other=NONE\");\n      builder.put(AtmosHeaders.DATE, DEFAULT_DATE);\n      builder.put(HttpHeaders.HOST, \"10.5.115.118\");\n      return builder;\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/test/java/org/jclouds/atmos/functions/AtmosObjectNameTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.File;\n\nimport org.jclouds.atmos.domain.AtmosObject;\nimport org.jclouds.atmos.domain.SystemMetadata;\nimport org.jclouds.atmos.domain.UserMetadata;\nimport org.jclouds.atmos.domain.AtmosObject.Factory;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Guice;\n\n@Test(groups = \"unit\")\npublic class AtmosObjectNameTest {\n   AtmosObjectName fn = new AtmosObjectName();\n   private static final Factory BLOB_FACTORY = Guice.createInjector().getInstance(AtmosObject.Factory.class);\n\n   @Test\n   public void testCorrectContentMetadataName() throws SecurityException, NoSuchMethodException {\n\n      AtmosObject blob = BLOB_FACTORY.create(null);\n      blob.getContentMetadata().setName(\"foo\");\n\n      assertEquals(fn.apply(blob), \"foo\");\n   }\n\n   @Test\n   public void testCorrectSystemMetadataObjectName() throws SecurityException, NoSuchMethodException {\n\n      AtmosObject blob = BLOB_FACTORY.create(new SystemMetadata(null, null, null, null, null, null, 0, null, \"foo\",\n            null, 0, null, null), new UserMetadata());\n      assertEquals(fn.apply(blob), \"foo\");\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testMustBeAtmosObject() {\n      fn.apply(new File(\"foo\"));\n   }\n\n   @Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class })\n   public void testNullIsBad() {\n      fn.apply(null);\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/test/java/org/jclouds/atmos/functions/ParseDirectoryListFromContentAndHeadersTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Set;\n\nimport org.jclouds.atmos.domain.BoundedSet;\nimport org.jclouds.atmos.domain.DirectoryEntry;\nimport org.jclouds.atmos.domain.FileType;\nimport org.jclouds.atmos.domain.internal.BoundedLinkedHashSet;\nimport org.jclouds.atmos.reference.AtmosHeaders;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.io.Payloads;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\n\n/**\n * Tests behavior of {@code ParseDirectoryListFromContentAndHeaders}\n */\n//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"ParseDirectoryListFromContentAndHeadersTest\")\npublic class ParseDirectoryListFromContentAndHeadersTest extends BaseHandlerTest {\n\n   Function<HttpResponse, BoundedSet<DirectoryEntry>> createFn() {\n      return injector.getInstance(ParseDirectoryListFromContentAndHeaders.class);\n   }\n\n   public void testWithToken() {\n      HttpResponse response = HttpResponse.builder()\n                                          .statusCode(200)\n                                          .message(\"ok\")\n                                          .payload(Payloads.newPayload(getClass().getResourceAsStream(\"/list_basic.xml\")))\n                                          .addHeader(AtmosHeaders.TOKEN, \"token\").build();\n\n      BoundedSet<DirectoryEntry> result = createFn().apply(response);\n      assertEquals(result, new BoundedLinkedHashSet<DirectoryEntry>(values(), \"token\"));\n      assertEquals(result.getToken(), \"token\");\n   }\n\n   public void testWithoutToken() {\n      HttpResponse response = HttpResponse.builder()\n                                          .statusCode(200)\n                                          .message(\"ok\")\n                                          .payload(Payloads.newPayload(getClass().getResourceAsStream(\"/list_basic.xml\"))).build();\n\n      BoundedSet<DirectoryEntry> result = createFn().apply(response);\n\n      assertEquals(ImmutableSet.copyOf(result), values());\n      assertEquals(result.getToken(), null);\n   }\n\n   protected Set<DirectoryEntry> values() {\n      Builder<DirectoryEntry> expected = ImmutableSet.builder();\n      expected.add(new DirectoryEntry(\"4980cdb2a411106a04a4538c92a1b204ad92077de6e3\", FileType.DIRECTORY,\n            \"adriancole-blobstore-2096685753\", 0));\n      expected.add(new DirectoryEntry(\"4980cdb2a410105404980d99e53a0504ad93939e7dc3\", FileType.DIRECTORY,\n            \"adriancole-blobstore247496608\", 0));\n      return expected.build();\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/test/java/org/jclouds/atmos/functions/ParseObjectFromHeadersAndHttpContentTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.atmos.domain.AtmosObject;\nimport org.jclouds.atmos.reference.AtmosHeaders;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.inject.Guice;\n\n/**\n * Tests behavior of {@code ParseObjectFromHeadersAndHttpContent}\n */\n@Test(groups = \"unit\", testName = \"ParseObjectFromHeadersAndHttpContentTest\")\npublic class ParseObjectFromHeadersAndHttpContentTest {\n\n   static final HttpResponse RESPONSE = HttpResponse.builder()\n                                                    .statusCode(200)\n                                                    .message(\"ok\")\n                                                    .payload(\"\")\n                                                    .headers(\n         ImmutableMultimap.of(AtmosHeaders.TAGS, \"tag1, tag2\", AtmosHeaders.LISTABLE_TAGS,\n               \"listabletag1, listabletag2\", AtmosHeaders.META,\n               \"meta1=foo1, content-md5=1f3870be274f6c49b3e31a0c6728957f, atime=2009-10-12T16:09:42Z, mtime=2009-10-19T04:37:00Z,\"\n                     + \" ctime=2009-10-19T04:37:00Z, itime=2009-10-12T16:09:42Z, type=directory, uid=root, \"\n                     + \"gid=rootr, objectid=4980cdb2b010109b04a44f7bb83f5f04ad354c638ae5, \"\n                     + \"objname=e913e09366364e9ba384b8fead643d43, size=4096, nlink=1, policyname=default\",\n               AtmosHeaders.LISTABLE_META, \"listablemeta1=listablefoo1, listablemeta2=listablefoo2\")).build();\n\n   public static final AtmosObject EXPECTED;\n\n   static {\n      EXPECTED = Guice.createInjector().getInstance(AtmosObject.Factory.class)\n            .create(ParseSystemMetadataFromHeadersTest.EXPECTED, ParseUserMetadataFromHeadersTest.EXPECTED);\n      EXPECTED.getContentMetadata().setName(\"e913e09366364e9ba384b8fead643d43\");\n      EXPECTED.setPayload(RESPONSE.getPayload());\n   }\n\n   public void test() {\n      ParseObjectFromHeadersAndHttpContent parser = Guice.createInjector().getInstance(\n            ParseObjectFromHeadersAndHttpContent.class);\n      AtmosObject data = parser.apply(RESPONSE);\n\n      assertEquals(data, EXPECTED);\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/test/java/org/jclouds/atmos/functions/ParseSystemMetadataFromHeadersTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.functions;\n\nimport static com.google.common.io.BaseEncoding.base16;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.atmos.domain.FileType;\nimport org.jclouds.atmos.domain.SystemMetadata;\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Guice;\n\n/**\n * Tests behavior of {@code ParseSystemMetadataFromHeaders}\n */\n@Test(groups = \"unit\")\npublic class ParseSystemMetadataFromHeadersTest {\n   static final DateService dateService = new SimpleDateFormatDateService();\n   static final SystemMetadata EXPECTED = new SystemMetadata(base16().lowerCase().decode(\"1f3870be274f6c49b3e31a0c6728957f\"),\n   dateService.iso8601SecondsDateParse(\"2009-10-12T16:09:42Z\"),\n         dateService.iso8601SecondsDateParse(\"2009-10-19T04:37:00Z\"), \"rootr\",\n         dateService.iso8601SecondsDateParse(\"2009-10-12T16:09:42Z\"),\n         dateService.iso8601SecondsDateParse(\"2009-10-19T04:37:00Z\"), 1,\n         \"4980cdb2b010109b04a44f7bb83f5f04ad354c638ae5\", \"e913e09366364e9ba384b8fead643d43\", \"default\", 4096L,\n         FileType.DIRECTORY, \"root\"\n\n   );\n\n   public void test() {\n      ParseSystemMetadataFromHeaders parser = Guice.createInjector().getInstance(ParseSystemMetadataFromHeaders.class);\n\n      SystemMetadata data = parser.apply(ParseObjectFromHeadersAndHttpContentTest.RESPONSE);\n\n      assertEquals(data, EXPECTED);\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/test/java/org/jclouds/atmos/functions/ParseUserMetadataFromHeadersTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.atmos.domain.UserMetadata;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\n\n/**\n * Tests behavior of {@code ParseUserMetadataFromHeaders}\n */\n@Test(groups = \"unit\")\npublic class ParseUserMetadataFromHeadersTest {\n   static final UserMetadata EXPECTED = new UserMetadata(ImmutableMap.<String, String> of(\"meta1\", \"foo1\"),\n         ImmutableMap.of(\"listablemeta1\", \"listablefoo1\", \"listablemeta2\", \"listablefoo2\"), ImmutableSet.of(\"tag1\",\n               \"tag2\"), ImmutableSet.of(\"listabletag1\", \"listabletag2\"));\n\n   public void test() {\n      ParseUserMetadataFromHeaders parser = Guice.createInjector().getInstance(ParseUserMetadataFromHeaders.class);\n      UserMetadata data = parser.apply(ParseObjectFromHeadersAndHttpContentTest.RESPONSE);\n\n      assertEquals(data, EXPECTED);\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/test/java/org/jclouds/atmos/handlers/AtmosServerErrorRetryHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.handlers;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.atmos.domain.AtmosError;\nimport org.jclouds.atmos.util.AtmosUtils;\nimport org.jclouds.http.handlers.BackoffLimitedRetryHandler;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code AtmosServerErrorRetryHandler}\n */\n@Test(groups = \"unit\")\npublic class AtmosServerErrorRetryHandlerTest {\n   private static final String HTTP_MESSAGE_FORMAT =\n         \"<?xml version='1.0' encoding='UTF-8'?>\\n\" +\n         \"<Error>\\n\" +\n         \"<Code>%d</Code>\\n\" +\n         \"<Message>%s</Message>\\n\" +\n         \"</Error>\\n\";\n\n   @Test\n   public void testGet500WithoutError() {\n      AtmosUtils utils = createMock(AtmosUtils.class);\n      BackoffLimitedRetryHandler backoffLimitedRetryHandler = createMock(BackoffLimitedRetryHandler.class);\n      HttpCommand command = createMock(HttpCommand.class);\n\n      expect(command.getFailureCount()).andReturn(0).once();\n      expect(command.incrementFailureCount()).andReturn(1).once();\n\n      replay(utils, backoffLimitedRetryHandler, command);\n\n      AtmosServerErrorRetryHandler retry = new AtmosServerErrorRetryHandler(backoffLimitedRetryHandler, utils);\n\n      assertFalse(retry.shouldRetryRequest(command, HttpResponse.builder().statusCode(500).build()));\n\n      verify(utils, backoffLimitedRetryHandler, command);\n   }\n\n   @Test\n   public void testGet500WithError1040() {\n      AtmosUtils utils = createMock(AtmosUtils.class);\n      BackoffLimitedRetryHandler backoffLimitedRetryHandler = createMock(BackoffLimitedRetryHandler.class);\n      HttpCommand command = createMock(HttpCommand.class);\n      String content = String.format(HTTP_MESSAGE_FORMAT, 1040, \"The server is busy. Please try again\");\n      HttpResponse response = HttpResponse.builder().statusCode(500).payload(content).build();\n\n      expect(command.getFailureCount()).andReturn(0).once();\n      expect(utils.parseAtmosErrorFromContent(command, response, content)).andReturn(new AtmosError(1040, \"The server is busy. Please try again\")).once();\n      expect(backoffLimitedRetryHandler.shouldRetryRequest(command, response)).andReturn(true).once();\n\n      replay(utils, backoffLimitedRetryHandler, command);\n\n      AtmosServerErrorRetryHandler retry = new AtmosServerErrorRetryHandler(backoffLimitedRetryHandler, utils);\n\n      assertTrue(retry.shouldRetryRequest(command, response));\n\n      verify(utils, backoffLimitedRetryHandler, command);\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/test/java/org/jclouds/atmos/options/ListOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.options;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tests behavior of {@code ListOptions}\n */\n@Test(groups = \"unit\")\npublic class ListOptionsTest {\n\n   public void testToken() {\n      ListOptions options = new ListOptions().token(\"a\");\n      assertEquals(ImmutableList.of(\"a\"), options.buildRequestHeaders().get(\"x-emc-token\"));\n   }\n\n   public void testTokenStatic() {\n      ListOptions options = ListOptions.Builder.token(\"a\");\n      assertEquals(ImmutableList.of(\"a\"), options.buildRequestHeaders().get(\"x-emc-token\"));\n   }\n\n   public void testLimit() {\n      int limit = 1;\n      ListOptions options = new ListOptions().limit(limit);\n      assertEquals(ImmutableList.of(\"1\"), options.buildRequestHeaders().get(\"x-emc-limit\"));\n   }\n\n   public void testLimitStatic() {\n      int limit = 1;\n      ListOptions options = ListOptions.Builder.limit(limit);\n      assertEquals(ImmutableList.of(\"1\"), options.buildRequestHeaders().get(\"x-emc-limit\"));\n   }\n\n   public void testNoMeta() {\n      ListOptions options = new ListOptions();\n      assert !options.metaIncluded();\n   }\n\n   public void testMeta() {\n      ListOptions options = new ListOptions().includeMeta();\n      assertEquals(ImmutableList.of(\"1\"), options.buildRequestHeaders().get(\"x-emc-include-meta\"));\n      assert options.metaIncluded();\n   }\n\n   public void testMetaStatic() {\n      ListOptions options = ListOptions.Builder.includeMeta();\n      assertEquals(ImmutableList.of(\"1\"), options.buildRequestHeaders().get(\"x-emc-include-meta\"));\n      assert options.metaIncluded();\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/test/java/org/jclouds/atmos/xml/ErrorHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.xml;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.atmos.domain.AtmosError;\nimport org.jclouds.atmos.reference.AtmosErrorCode;\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.http.functions.ParseSax;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code ErrorHandler}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"ErrorHandlerTest\")\npublic class ErrorHandlerTest extends BaseHandlerTest {\n\n   ParseSax<AtmosError> createParser() {\n      ParseSax<AtmosError> parser = factory.create(injector\n               .getInstance(ErrorHandler.class));\n      return parser;\n   }\n\n   public void testApplyInputStream() {\n      InputStream is = getClass().getResourceAsStream(\"/error.xml\");\n      ParseSax<AtmosError> parser = createParser();\n      AtmosError result = parser.parse(is);\n      assertEquals(result.getCode(), AtmosErrorCode.OBJECT_NOT_FOUND.getCode());\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/test/java/org/jclouds/atmos/xml/ListDirectoryResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.atmos.xml;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\nimport java.util.Set;\n\nimport org.jclouds.atmos.domain.DirectoryEntry;\nimport org.jclouds.atmos.domain.FileType;\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.http.functions.ParseSax;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Sets;\n\n/**\n * Tests behavior of {@code ListDirectoryResponseHandler}\n */\n//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"ListDirectoryResponseHandlerTest\")\npublic class ListDirectoryResponseHandlerTest extends BaseHandlerTest {\n\n   ParseSax<Set<DirectoryEntry>> createParser() {\n      ParseSax<Set<DirectoryEntry>> parser = factory\n               .create(injector.getInstance(ListDirectoryResponseHandler.class));\n      return parser;\n   }\n\n   public void testApplyInputStreamBase() {\n      InputStream is = getClass().getResourceAsStream(\"/list_basic.xml\");\n      ParseSax<Set<DirectoryEntry>> parser = createParser();\n      Set<DirectoryEntry> expected = Sets.newTreeSet();\n      expected.add(new DirectoryEntry(\"4980cdb2a411106a04a4538c92a1b204ad92077de6e3\",\n               FileType.DIRECTORY, \"adriancole-blobstore-2096685753\", 0));\n      expected.add(new DirectoryEntry(\"4980cdb2a410105404980d99e53a0504ad93939e7dc3\",\n               FileType.DIRECTORY, \"adriancole-blobstore247496608\", 0));\n      Set<DirectoryEntry> result = parser.parse(is);\n      assertEquals(result, expected);\n   }\n}\n"
  },
  {
    "path": "apis/atmos/src/test/resources/error.xml",
    "content": "<?xml version='1.0' encoding='UTF-8'?> \n<Error> \n<Code>1003</Code> \n<Message>The requested object was not found.</Message> \n</Error> "
  },
  {
    "path": "apis/atmos/src/test/resources/hashstring.txt",
    "content": "POST\napplication/octet-stream\n\nThu, 05 Jun 2008 16:38:19 GMT\n/rest/objects\nx-emc-date:Thu, 05 Jun 2008 16:38:19 GMT\nx-emc-groupacl:other=NONE\nx-emc-listable-meta:part4/part7/part8=quick\nx-emc-meta:part1=buy\nx-emc-uid:6039ac182f194e15b9261d73ce044939/user1\nx-emc-useracl:john=FULL_CONTROL,mary=WRITE"
  },
  {
    "path": "apis/atmos/src/test/resources/list_basic.xml",
    "content": "<?xml version='1.0' encoding='UTF-8'?>\n<ListDirectoryResponse xmlns='http://www.emc.com/cos/'>\n\t<DirectoryList>\n\t<DirectoryEntry>\n\t\t<ObjectID>4980cdb2a411106a04a4538c92a1b204ad92077de6e3</ObjectID>\n \t\t<FileType>directory</FileType>\n \t\t<Filename>adriancole-blobstore-2096685753</Filename>\n\t</DirectoryEntry>\n\t<DirectoryEntry>\n\t\t<ObjectID>4980cdb2a410105404980d99e53a0504ad93939e7dc3</ObjectID>\n \t\t<FileType>directory</FileType>\n \t\t<Filename>adriancole-blobstore247496608</Filename>\n\t</DirectoryEntry>\n\t</DirectoryList>\n</ListDirectoryResponse>\n"
  },
  {
    "path": "apis/atmos/src/test/resources/list_meta.xml",
    "content": "<?xml version='1.0' encoding='UTF-8'?>\n<ListObjectsResponse xmlns='http://www.emc.com/cos/'>\n    <Object>\n        <ObjectID>499ad542a2a8bc200499ad5a7099940499b44f51e97d\n        </ObjectID>\n        <SystemMetadataList>\n            <Metadata>\n                <Name>atime</Name>\n                <Value>2009-02-17T23:15:01Z</Value>\n            </Metadata>\n            <Metadata>\n                <Name>mtime</Name>\n                <Value>2009-02-17T23:15:01Z</Value>\n            </Metadata>\n            <Metadata>\n                <Name>ctime</Name>\n                <Value>2009-02-17T23:15:01Z</Value>\n            </Metadata>\n            <Metadata>\n                <Name>itime</Name>\n                <Value>2009-02-17T23:15:01Z</Value>\n            </Metadata>\n            <Metadata>\n                <Name>type</Name>\n                <Value>regular</Value>\n            </Metadata>\n            <Metadata>\n                <Name>uid</Name>\n                <Value>user1</Value>\n            </Metadata>\n            <Metadata>\n                <Name>gid</Name>\n                <Value>apache</Value>\n            </Metadata>\n            <Metadata>\n                <Name>objectid</Name>\n                <Value>499ad542a2a8bc200499ad5a7099940499b44f51e97d\n                </Value>\n            </Metadata>\n            <Metadata>\n                <Name>objname</Name>\n                <Value></Value>\n            </Metadata>\n            <Metadata>\n                <Name>size</Name>\n                <Value>7589</Value>\n            </Metadata>\n            <Metadata>\n                <Name>nlink</Name>\n                <Value>0</Value>\n            </Metadata>\n            <Metadata>\n                <Name>policyname</Name>\n                <Value>default</Value>\n            </Metadata>\n        </SystemMetadataList>\n        <UserMetadataList>\n            <Metadata>\n                <Name>part1</Name>\n                <Value>order</Value>\n                <Listable>false</Listable>\n            </Metadata>\n            <Metadata>\n                <Name>part4/part7/part8</Name>\n                <Value>quick</Value>\n                <Listable>true</Listable>\n            </Metadata>\n        </UserMetadataList>\n    </Object>\n</ListObjectsResponse>\n"
  },
  {
    "path": "apis/atmos/src/test/resources/log4j.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE log4j:configuration SYSTEM \"log4j.dtd\">\n\n    <!--\n        For more configuration infromation and examples see the Apache\n        Log4j website: http://logging.apache.org/log4j/\n    -->\n<log4j:configuration xmlns:log4j=\"http://jakarta.apache.org/log4j/\"\n    debug=\"false\">\n\n    <!-- A time/date based rolling appender -->\n    <appender name=\"WIREFILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds-wire.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n\n    <!-- A time/date based rolling appender -->\n    <appender name=\"FILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n\n    <appender name=\"ASYNC\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"FILE\" />\n    </appender>\n\n    <appender name=\"ASYNCWIRE\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"WIREFILE\" />\n    </appender>\n\n    <!-- A time/date based rolling appender -->\n    <appender name=\"BLOBSTOREFILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds-blobstore.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n\n    <appender name=\"ASYNCBLOBSTORE\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"BLOBSTOREFILE\" />\n    </appender>\n    <!-- ================ -->\n    <!-- Limit categories -->\n    <!-- ================ -->\n    <category name=\"jclouds.blobstore\">\n        <priority value=\"TRACE\" />\n        <appender-ref ref=\"ASYNCBLOBSTORE\" />\n    </category>\n\n    <category name=\"org.jclouds\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNC\" />\n    </category>\n\n    <category name=\"jclouds.headers\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNCWIRE\" />\n    </category>\n\n    <category name=\"jclouds.wire\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNCWIRE\" />\n    </category>\n   \n   \n    <!-- ======================= -->\n    <!-- Setup the Root category -->\n    <!-- ======================= -->\n\n    <root>\n        <priority value=\"WARN\" />\n    </root>\n\n</log4j:configuration>\n"
  },
  {
    "path": "apis/byon/README.txt",
    "content": "= Bring Your Own Nodes to the jclouds ComputeService =\nThe bring your own node provider (byon) allows you to specify a source which jclouds will read\nnodes from.  Using this, you can have jclouds control your standalone machines, or even cloud\nhosts that are sitting idle.\n\n== Constraints ==\nThe byon provider only supports the following functions of ComputeService:\n  * listNodes\n  * listNodesDetailsMatching\n  * getNodeMetadata\n  * runScriptOnNodesMatching\n\n== How to use the byon provider == \nThe byon provider requires you supply a list of nodes using a property.  Here are \nthe valid properties you can use:\n  * byon.endpoint - url to access the list, can be http://, file://, classpath://\n  * byon.nodes    - inline defined yaml in string form.\n\nNote:\n\nThe identity and credential fields of the ComputeServiceContextFactory are ignored.\n\n=== Java example ===\n\nProperties props = new Properties();\n\n// if you built the yaml string by hand\nprops.setProperty(\"byon.nodes\", stringLiteral);\n\n// or you can specify an external reference\nprops.setProperty(\"byon.endpoint\", \"file://path/to/byon.yaml\");\n\n// or you can specify a file in your classpath\nprops.setProperty(\"byon.endpoint\", \"classpath:///byon.yaml\");\n\ncontext = new ComputeServiceContextFactory().createContext(\"byon\", \"foo\", \"bar\", \n               ImmutableSet.<Module> of(new JschSshClientModule()), props);\n\n== File format == \nYou must define your nodes in yaml, and they must be in a collection called nodes.\n\nHere are the properties:\n\n  * id             - opaque unique id\n  * name           - optional; user specified name\n  * description    - optional; long description of this node \n                               * note this is not yet in jclouds NodeMetadata\n  * hostname       - name or ip address to contact the node on\n  * location_id    - optional; correlates to a ZONE-scoped Location\n                               * note that if present for one node, must be present for all\n  * os_arch        - ex. x86 \n  * os_family      - must conform to org.jclouds.compute.domain.OsFamily in lower-hyphen format\n                     ex. rhel, ubuntu, centos, debian, amzn-linux\n  * os_description - long description of the os ex. Ubuntu with lamp stack \n  * os_version     - normalized to numbers when possible. ex. for centos: 5.3, ubuntu: 10.10 \n  * login_port     - optional; alternate port for ssh access\n  * group          - primary group of the machine. ex. hadoop \n  * tags           - optional; list of arbitrary tags. \n                               * note this list is not yet in jclouds NodeMetadata \n  * username       - primary login user. ex. ubuntu, toor, root \n  * sudo_password  - optional; when a script is run with the \"runAsRoot\" option true, yet the\n                               username is not root, a sudo command is invoked. If sudo_password\n                               is set, the contents will be passed to sudo -S.  \n                               Ex. echo 'foobar'| sudo -S init 5\n \n  one of:\n  \n    * credential     - RSA private key or password \n    * credential_url - location of plain-text RSA private key or password.\n                       ex. file:///home/me/.ssh/id_rsa\n                           classpath:///id_rsa\n\nNote that username and credentials are optional if a CredentialStoreModule is configured in \njclouds.\n\n=== Example File ===\n\nnodes:\n    - id: i-sdfkjh7\n      name: cluster-1\n      description: accounting analytics cluster\n      hostname: cluster-1.mydomain.com\n      location_id: virginia\n      os_arch: x86\n      os_family: rhel\n      os_description: redhat with CDH\n      os_version: 5.3\n      group: hadoop\n      tags:\n          - vanilla\n      username: myUser\n      credential: |\n                  -----BEGIN RSA PRIVATE KEY-----\n                  MIIEowIBAAKCAQEAuzaE6azgUxwESX1rCGdJ5xpdrc1XC311bOGZBCE8NA+CpFh2\n                  u01Vfv68NC4u6LFgdXSY1vQt6hiA5TNqQk0TyVfFAunbXgTekF6XqDPQUf1nq9aZ\n                  lMvo4vlaLDKBkhG5HJE/pIa0iB+RMZLS0GhxsIWerEDmYdHKM25o\n                  -----END RSA PRIVATE KEY-----\n      sudo_password: go panthers!\n"
  },
  {
    "path": "apis/byon/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.byon.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "apis/byon/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n\n  <groupId>org.apache.jclouds.api</groupId>\n  <artifactId>byon</artifactId>\n  <name>jclouds bring your own node provider</name>\n\n  <properties>\n    <test.byon.endpoint>file://c:/test.txt</test.byon.endpoint>\n    <test.byon.sudo-password />\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-log4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-sshj</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.yaml</groupId>\n      <artifactId>snakeyaml</artifactId>\n      <version>2.3</version>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.byon.endpoint>${test.byon.endpoint}</test.byon.endpoint>\n                    <test.byon.sudo-password>${test.byon.sudo-password}</test.byon.sudo-password>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n"
  },
  {
    "path": "apis/byon/src/main/java/org/jclouds/byon/BYONApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.byon;\n\nimport java.net.URI;\n\nimport org.jclouds.JcloudsVersion;\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.apis.internal.BaseApiMetadata;\nimport org.jclouds.byon.config.BYONComputeServiceContextModule;\nimport org.jclouds.byon.config.YamlNodeStoreModule;\nimport org.jclouds.compute.ComputeServiceContext;\n\nimport com.google.auto.service.AutoService;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n/**\n * Implementation of {@link ApiMetadata} for jclouds BYON API\n * \n * <h3>note</h3>\n * \n * This class is not setup to allow a subclasses to override the type of api,\n * asyncapi, or context. This is an optimization for s.\n */\n@AutoService(ApiMetadata.class)\npublic class BYONApiMetadata extends BaseApiMetadata {\n\n   @Override\n   public Builder toBuilder() {\n      return new Builder().fromApiMetadata(this);\n   }\n\n   public BYONApiMetadata() {\n      this(new Builder());\n   }\n\n   protected BYONApiMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static class Builder extends BaseApiMetadata.Builder<Builder> {\n\n      protected Builder() {\n         id(\"byon\")\n         .name(\"Bring Your Own Node (BYON) API\")\n         .identityName(\"Unused\")\n         .defaultIdentity(\"foo\")\n         .defaultCredential(\"bar\")\n         .defaultEndpoint(\"file://byon.yaml\")\n         .documentation(URI.create(\"https://github.com/jclouds/jclouds/tree/master/apis/byon\"))\n         .version(String.format(\"%s.%s\", JcloudsVersion.get().majorVersion, JcloudsVersion.get().minorVersion))\n         .buildVersion(JcloudsVersion.get().toString())\n         .view(ComputeServiceContext.class)\n         .defaultModules(ImmutableSet.<Class<? extends Module>>of(YamlNodeStoreModule.class, BYONComputeServiceContextModule.class));\n      }\n\n      @Override\n      public BYONApiMetadata build() {\n         return new BYONApiMetadata(this);\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/byon/src/main/java/org/jclouds/byon/Node.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.byon;\n\nimport java.net.URI;\nimport java.util.Map;\nimport java.util.Set;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Maps;\nimport com.google.common.collect.Sets;\n\npublic class Node {\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n      private String id;\n      private String name;\n      private String description;\n      private String hostname;\n      private String locationId;\n      private String osArch;\n      private String osFamily;\n      private String osDescription;\n      private String osVersion;\n      private boolean os64Bit;\n      private int loginPort = 22;\n      private String group;\n      private Set<String> tags = ImmutableSet.of();\n      private Map<String, String> metadata = ImmutableMap.<String, String>of();\n      private String username;\n      private String credential;\n      private URI credentialUrl;\n      private String sudoPassword;\n\n      public Builder id(String id) {\n         this.id = id;\n         return this;\n      }\n\n      public Builder name(String name) {\n         this.name = name;\n         return this;\n      }\n\n      public Builder description(String description) {\n         this.description = description;\n         return this;\n      }\n\n      public Builder hostname(String hostname) {\n         this.hostname = hostname;\n         return this;\n      }\n\n      public Builder loginPort(int loginPort) {\n         this.loginPort = loginPort;\n         return this;\n      }\n      \n      public Builder locationId(String locationId) {\n         this.locationId = locationId;\n         return this;\n      }\n\n      public Builder osArch(String osArch) {\n         this.osArch = osArch;\n         return this;\n      }\n\n      public Builder osFamily(String osFamily) {\n         this.osFamily = osFamily;\n         return this;\n      }\n\n      public Builder osDescription(String osDescription) {\n         this.osDescription = osDescription;\n         return this;\n      }\n\n      public Builder osVersion(String osVersion) {\n         this.osVersion = osVersion;\n         return this;\n      }\n\n      public Builder os64Bit(boolean os64Bit) {\n         this.os64Bit = os64Bit;\n         return this;\n      }\n\n      public Builder group(String group) {\n         this.group = group;\n         return this;\n      }\n\n      public Builder tags(Iterable<String> tags) {\n         this.tags = ImmutableSet.copyOf(tags);\n         return this;\n      }\n      \n      public Builder metadata(Map<String, String> metadata) {\n         this.metadata = ImmutableMap.copyOf(metadata);\n         return this;\n      }\n      \n      public Builder username(String username) {\n         this.username = username;\n         return this;\n      }\n\n      public Builder credential(String credential) {\n         this.credential = credential;\n         return this;\n      }\n\n      public Builder credentialUrl(URI credentialUrl) {\n         this.credentialUrl = credentialUrl;\n         return this;\n      }\n\n      public Builder sudoPassword(String sudoPassword) {\n         this.sudoPassword = sudoPassword;\n         return this;\n      }\n\n      public Node build() {\n         return new Node(id, name, description, hostname, locationId, osArch, osFamily, osDescription, osVersion,\n                  os64Bit, loginPort, group, tags, metadata, username, credential, credentialUrl, sudoPassword);\n      }\n   }\n\n   public Node(String id, String name, String description, String hostname, String locationId, String osArch,\n         String osFamily, String osDescription, String osVersion, boolean os64Bit, int loginPort, String group,\n         Iterable<String> tags, Map<String, String> metadata, String username, String credential, URI credentialUrl,\n         String sudoPassword) {\n      this.id = id;\n      this.name = name;\n      this.description = description;\n      this.hostname = hostname;\n      this.locationId = locationId;\n      this.osArch = osArch;\n      this.osFamily = osFamily;\n      this.osDescription = osDescription;\n      this.osVersion = osVersion;\n      this.os64Bit = os64Bit;\n      this.loginPort = loginPort;\n      this.group = group;\n      this.tags = ImmutableSet.copyOf(tags);\n      this.metadata = ImmutableMap.copyOf(metadata);\n      this.username = username;\n      this.credential = credential;\n      this.credentialUrl = credentialUrl;\n      this.sudoPassword = sudoPassword;\n   }\n\n   private final String id;\n   private final String name;\n   private final String description;\n   private final String hostname;\n   private final String locationId;\n   private final String osArch;\n   private final String osFamily;\n   private final String osDescription;\n   private final String osVersion;\n   private final int loginPort;\n   private final boolean os64Bit;\n   private final String group;\n   private final Set<String> tags;\n   private final Map<String, String> metadata;\n   private final String username;\n   private final String credential;\n   private final URI credentialUrl;\n   private final String sudoPassword;\n\n   public String getId() {\n      return id;\n   }\n\n   public String getLocationId() {\n      return locationId;\n   }\n\n   public String getName() {\n      return name;\n   }\n\n   public String getDescription() {\n      return description;\n   }\n\n   public String getGroup() {\n      return group;\n   }\n\n   public String getHostname() {\n      return hostname;\n   }\n\n   public String getOsArch() {\n      return osArch;\n   }\n\n   public String getOsFamily() {\n      return osFamily;\n   }\n\n   public String getOsDescription() {\n      return osDescription;\n   }\n\n   public String getOsVersion() {\n      return osVersion;\n   }\n\n   public boolean isOs64Bit() {\n      return os64Bit;\n   }\n   \n   public int getLoginPort() {\n      return loginPort;\n   }\n   \n   public Set<String> getTags() {\n      Set<String> tagSet = Sets.newHashSet();\n      for (String tag : tags)\n         tagSet.add(tag);\n      return tagSet;\n   }\n\n   public Map<String, String> getMetadata() {\n      return Maps.newLinkedHashMap(this.metadata);\n   }\n\n   public String getUsername() {\n      return username;\n   }\n\n   public String getCredential() {\n      return credential;\n   }\n\n   public URI getCredentialUrl() {\n      return credentialUrl;\n   }\n\n   public String getSudoPassword() {\n      return sudoPassword;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (obj == null)\n         return false;\n      if (!(obj instanceof Node)) {\n         return false;\n      }\n      Node that = (Node) obj;\n      return Objects.equal(this.id, that.id)\n         && Objects.equal(this.name, that.name)\n         && Objects.equal(this.description, that.description)\n         && Objects.equal(this.hostname, that.hostname)\n         && Objects.equal(this.locationId, that.locationId)\n         && Objects.equal(this.osArch, that.osArch)\n         && Objects.equal(this.osFamily, that.osFamily)\n         && Objects.equal(this.osDescription, that.osDescription)\n         && Objects.equal(this.osVersion, that.osVersion)\n         && Objects.equal(this.loginPort, that.loginPort)\n         && Objects.equal(this.os64Bit, that.os64Bit)\n         && Objects.equal(this.group, that.group)\n         && Objects.equal(this.tags, that.tags)\n         && Objects.equal(this.metadata, that.metadata)\n         && Objects.equal(this.username, that.username)\n         // not comparing credential and credentialUrl\n         && Objects.equal(this.sudoPassword, that.sudoPassword);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).add(\"id\", id).add(\"name\", name).add(\"description\", description)\n            .add(\"locationId\", locationId).add(\"hostname\", hostname).add(\"osArch\", osArch).add(\"osFamily\", osFamily)\n            .add(\"osDescription\", osDescription).add(\"osVersion\", osVersion).add(\"os64Bit\", os64Bit)\n            .add(\"group\", group).add(\"loginPort\", loginPort).add(\"tags\", tags).add(\"metadata\", metadata)\n            .add(\"username\", username).add(\"hasCredential\", credential != null || credentialUrl != null)\n            .add(\"hasSudoPassword\", sudoPassword != null).toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/byon/src/main/java/org/jclouds/byon/config/BYONComputeServiceContextModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.byon.config;\n\nimport java.io.InputStream;\nimport java.net.URI;\n\nimport org.jclouds.byon.internal.BYONComputeServiceAdapter;\nimport org.jclouds.byon.suppliers.SupplyFromProviderURIOrNodesProperty;\nimport org.jclouds.compute.config.JCloudsNativeComputeServiceAdapterContextModule;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.concurrent.SingleThreaded;\nimport org.jclouds.domain.Location;\nimport org.jclouds.location.Provider;\n\nimport com.google.common.base.Function;\nimport com.google.common.io.ByteSource;\nimport com.google.inject.TypeLiteral;\n\n@SingleThreaded\npublic class BYONComputeServiceContextModule extends JCloudsNativeComputeServiceAdapterContextModule {\n\n   public BYONComputeServiceContextModule() {\n      super(BYONComputeServiceAdapter.class);\n   }\n\n   @Override\n   protected void configure() {\n      super.configure();\n      bind(new TypeLiteral<Function<URI, InputStream>>() {\n      }).to(SupplyFromProviderURIOrNodesProperty.class);\n      bind(ByteSource.class).annotatedWith(Provider.class).to(SupplyFromProviderURIOrNodesProperty.class);\n      bind(new TypeLiteral<Function<URI, InputStream>>() {\n      }).to(SupplyFromProviderURIOrNodesProperty.class);\n      install(new LocationsFromComputeServiceAdapterModule<NodeMetadata, Hardware, Image, Location>() {\n      });\n   }\n}\n"
  },
  {
    "path": "apis/byon/src/main/java/org/jclouds/byon/config/CacheNodeStoreModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.byon.config;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\n\nimport org.jclouds.byon.Node;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Functions;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.TypeLiteral;\n\n@ConfiguresNodeStore\n@Beta\npublic class CacheNodeStoreModule extends AbstractModule {\n   private final LoadingCache<String, Node> backing;\n\n   public CacheNodeStoreModule(LoadingCache<String, Node> backing) {\n      this.backing = checkNotNull(backing, \"backing\");\n   }\n\n   public CacheNodeStoreModule(Map<String, Node> backing) {\n      this(CacheBuilder.newBuilder().<String, Node>build(CacheLoader.from(Functions.forMap(backing))));\n      for (String node : backing.keySet())\n         this.backing.getUnchecked(node);\n   }\n\n   @Override\n   protected void configure() {\n      bind(new TypeLiteral<LoadingCache<String, Node>>() {\n      }).toInstance(backing);\n      bind(new TypeLiteral<Supplier<LoadingCache<String, Node>>>() {\n      }).toInstance(Suppliers.<LoadingCache<String, Node>> ofInstance(backing));\n   }\n\n}\n"
  },
  {
    "path": "apis/byon/src/main/java/org/jclouds/byon/config/ConfiguresNodeStore.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.byon.config;\n\nimport static java.lang.annotation.ElementType.TYPE;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\nimport com.google.common.annotations.Beta;\n\n/**\n * designates the module configures a {@code LoadingCache<String, Node>}\n */\n@Beta\n@Retention(RUNTIME)\n@Target(TYPE)\npublic @interface ConfiguresNodeStore {\n\n}\n"
  },
  {
    "path": "apis/byon/src/main/java/org/jclouds/byon/config/YamlNodeStoreModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.byon.config;\n\nimport java.util.Map;\nimport java.util.concurrent.ConcurrentHashMap;\n\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.byon.Node;\nimport org.jclouds.byon.domain.YamlNode;\nimport org.jclouds.byon.functions.NodesFromYamlStream;\nimport org.jclouds.byon.suppliers.NodesParsedFromSupplier;\nimport org.jclouds.collect.TransformingMap;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Function;\nimport com.google.common.base.Functions;\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.io.ByteSource;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Provides;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.name.Names;\n\n@ConfiguresNodeStore\n@Beta\npublic class YamlNodeStoreModule extends AbstractModule {\n   private static final Map<String, ByteSource> BACKING = new ConcurrentHashMap<String, ByteSource>();\n   private final Map<String, ByteSource> backing;\n\n   public YamlNodeStoreModule(Map<String, ByteSource> backing) {\n      this.backing = backing;\n   }\n\n   public YamlNodeStoreModule() {\n      this(null);\n   }\n\n   @Override\n   protected void configure() {\n      bind(new TypeLiteral<Supplier<LoadingCache<String, Node>>>() {\n      }).to(NodesParsedFromSupplier.class);\n      bind(new TypeLiteral<Function<ByteSource, LoadingCache<String, Node>>>() {\n      }).to(NodesFromYamlStream.class);\n      bind(new TypeLiteral<Function<YamlNode, ByteSource>>() {\n      }).toInstance(org.jclouds.byon.domain.YamlNode.yamlNodeToByteSource);\n      bind(new TypeLiteral<Function<ByteSource, YamlNode>>() {\n      }).toInstance(org.jclouds.byon.domain.YamlNode.byteSourceToYamlNode);\n      bind(new TypeLiteral<Function<Node, YamlNode>>() {\n      }).toInstance(org.jclouds.byon.domain.YamlNode.nodeToYamlNode);\n      bind(new TypeLiteral<Function<YamlNode, Node>>() {\n      }).toInstance(org.jclouds.byon.domain.YamlNode.toNode);\n      if (backing != null) {\n         bind(new TypeLiteral<Map<String, ByteSource>>() {\n         }).annotatedWith(Names.named(\"yaml\")).toInstance(backing);\n      } else {\n         bind(new TypeLiteral<Map<String, ByteSource>>() {\n         }).annotatedWith(Names.named(\"yaml\")).toInstance(BACKING);\n      }\n\n   }\n\n   @Provides\n   @Singleton\n   protected final LoadingCache<String, Node> provideNodeStore(Map<String, YamlNode> backing, Function<Node, YamlNode> yamlSerializer,\n         Function<YamlNode, Node> yamlDeserializer) {\n      return CacheBuilder.newBuilder().build(CacheLoader.from(Functions.forMap(new TransformingMap<String, YamlNode, Node>(backing, yamlDeserializer, yamlSerializer))));\n   }\n\n   @Provides\n   @Singleton\n   protected final Map<String, YamlNode> provideYamlStore(@Named(\"yaml\") Map<String, ByteSource> backing,\n         Function<YamlNode, ByteSource> yamlSerializer, Function<ByteSource, YamlNode> yamlDeserializer) {\n      return new TransformingMap<String, ByteSource, YamlNode>(backing, yamlDeserializer, yamlSerializer);\n   }\n}\n"
  },
  {
    "path": "apis/byon/src/main/java/org/jclouds/byon/domain/YamlNode.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.byon.domain;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.net.URI;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.byon.Node;\nimport org.jclouds.util.Closeables2;\nimport org.yaml.snakeyaml.DumperOptions;\nimport org.yaml.snakeyaml.LoaderOptions;\nimport org.yaml.snakeyaml.Yaml;\nimport org.yaml.snakeyaml.constructor.Constructor;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.base.Function;\nimport com.google.common.base.Throwables;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Lists;\nimport com.google.common.collect.Maps;\nimport com.google.common.collect.ImmutableMap.Builder;\nimport com.google.common.io.ByteSource;\n\n/**\n * Serializes to the following\n * \n * <pre>\n *       id: cluster-1\n *       name: cluster-1\n *       description: xyz\n *       hostname: cluster-1.mydomain.com\n *       location_id: virginia\n *       os_arch: x86\n *       os_family: linux\n *       os_description: redhat\n *       os_version: 5.3\n *       os_64bit: 5.3\n *       login_port: 2022\n *       group: hadoop\n *       tags:\n *           - vanilla\n *       metadata:\n *           key1: val1\n *       username: kelvin\n *       credential: password_or_rsa\n *         or\n *       credential_url: password_or_rsa_file ex. resource:///id_rsa will get the classpath /id_rsa; file://path/to/id_rsa\n *       sudo_password: password\n * </pre>\n */\npublic class YamlNode {\n   public String id;\n   public String name;\n   public String description;\n   public String hostname;\n   public String location_id;\n   public String os_arch;\n   public String os_family;\n   public String os_description;\n   public String os_version;\n   public int login_port = 22;\n   public boolean os_64bit;\n   public String group;\n   public List<String> tags = Lists.newArrayList();\n   public Map<String, String> metadata = Maps.newLinkedHashMap();\n   public String username;\n   public String credential;\n   public String credential_url;\n   public String sudo_password;\n\n   public static final Function<YamlNode, Node> toNode = new Function<YamlNode, Node>() {\n      @Override\n      public Node apply(YamlNode arg0) {\n         if (arg0 == null)\n            return null;\n         return Node.builder().id(arg0.id).name(arg0.name).description(arg0.description).locationId(arg0.location_id)\n                  .hostname(arg0.hostname).osArch(arg0.os_arch).osFamily(arg0.os_family).osDescription(\n                           arg0.os_description).osVersion(arg0.os_version).os64Bit(arg0.os_64bit).group(arg0.group)\n                  .loginPort(arg0.login_port).tags(arg0.tags).metadata(arg0.metadata).username(arg0.username).credential(arg0.credential).credentialUrl(\n                           arg0.credential_url != null ? URI.create(arg0.credential_url) : null).sudoPassword(\n                           arg0.sudo_password).build();\n      }\n   };\n\n   public Node toNode() {\n      return toNode.apply(this);\n   }\n\n   public static final Function<ByteSource, YamlNode> byteSourceToYamlNode = new Function<ByteSource, YamlNode>() {\n      @Override\n      public YamlNode apply(ByteSource byteSource) {\n         if (byteSource == null)\n            return null;\n         InputStream in = null;\n         try {\n            in = byteSource.openStream();\n            return (YamlNode) new Yaml(new Constructor(YamlNode.class, new LoaderOptions())).load(in);\n         } catch (IOException ioe) {\n            throw Throwables.propagate(ioe);\n         } finally {\n            Closeables2.closeQuietly(in);\n         }\n      }\n   };\n\n   public static YamlNode fromYaml(ByteSource in) {\n      return byteSourceToYamlNode.apply(in);\n   }\n\n   public static final Function<YamlNode, ByteSource> yamlNodeToByteSource = new Function<YamlNode, ByteSource>() {\n      @Override\n      public ByteSource apply(YamlNode in) {\n         if (in == null)\n            return null;\n         Builder<String, Object> prettier = ImmutableMap.builder();\n         if (in.id != null)\n            prettier.put(\"id\", in.id);\n         if (in.name != null)\n            prettier.put(\"name\", in.name);\n         if (in.description != null)\n            prettier.put(\"description\", in.description);\n         if (in.hostname != null)\n            prettier.put(\"hostname\", in.hostname);\n         if (in.location_id != null)\n            prettier.put(\"location_id\", in.location_id);\n         if (in.os_arch != null)\n            prettier.put(\"os_arch\", in.os_arch);\n         if (in.os_family != null)\n            prettier.put(\"os_family\", in.os_family);\n         if (in.os_description != null)\n            prettier.put(\"os_description\", in.os_description);\n         if (in.os_version != null)\n            prettier.put(\"os_version\", in.os_version);\n         if (in.os_64bit)\n            prettier.put(\"os_64bit\", in.os_64bit);\n         if (in.login_port != 22)\n            prettier.put(\"login_port\", in.login_port);\n         if (in.group != null)\n            prettier.put(\"group\", in.group);\n         if (in.tags.size() != 0)\n            prettier.put(\"tags\", in.tags);\n         if (in.metadata.size() != 0)\n            prettier.put(\"metadata\", in.metadata);\n         if (in.username != null)\n            prettier.put(\"username\", in.username);\n         if (in.credential != null)\n            prettier.put(\"credential\", in.credential);\n         if (in.credential_url != null)\n            prettier.put(\"credential_url\", in.credential_url);\n         if (in.sudo_password != null)\n            prettier.put(\"sudo_password\", in.sudo_password);\n         DumperOptions options = new DumperOptions();\n         options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);\n         return ByteSource.wrap(new Yaml(options).dump(prettier.build()).getBytes(Charsets.UTF_8));\n      }\n   };\n\n   public ByteSource toYaml() {\n      return yamlNodeToByteSource.apply(this);\n   }\n\n   public static YamlNode fromNode(Node in) {\n      return nodeToYamlNode.apply(in);\n   }\n\n   public static final Function<Node, YamlNode> nodeToYamlNode = new Function<Node, YamlNode>() {\n      @Override\n      public YamlNode apply(Node arg0) {\n         if (arg0 == null)\n            return null;\n         YamlNode yaml = new YamlNode();\n         yaml.id = arg0.getId();\n         yaml.name = arg0.getName();\n         yaml.description = arg0.getDescription();\n         yaml.hostname = arg0.getHostname();\n         yaml.location_id = arg0.getLocationId();\n         yaml.os_arch = arg0.getOsArch();\n         yaml.os_family = arg0.getOsFamily();\n         yaml.os_description = arg0.getOsDescription();\n         yaml.os_version = arg0.getOsVersion();\n         yaml.os_64bit = arg0.isOs64Bit();\n         yaml.login_port = arg0.getLoginPort();\n         yaml.group = arg0.getGroup();\n         yaml.tags = ImmutableList.copyOf(arg0.getTags());\n         yaml.metadata = ImmutableMap.copyOf(arg0.getMetadata());\n         yaml.username = arg0.getUsername();\n         yaml.credential = arg0.getCredential();\n         yaml.credential_url = arg0.getCredentialUrl() != null ? arg0.getCredentialUrl().toASCIIString() : null;\n         yaml.sudo_password = arg0.getSudoPassword();\n         return yaml;\n      }\n   };\n\n}\n"
  },
  {
    "path": "apis/byon/src/main/java/org/jclouds/byon/functions/NodeToNodeMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.byon.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.net.URI;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.byon.Node;\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadataBuilder;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.NodeMetadata.Status;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.domain.LoginCredentials.Builder;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.util.Strings2;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\n\n@Singleton\npublic class NodeToNodeMetadata implements Function<Node, NodeMetadata> {\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   private final Supplier<Location> location;\n   private final Supplier<Set<? extends Location>> locations;\n   private final Map<String, Credentials> credentialStore;\n   private final Function<URI, InputStream> slurp;\n\n   @Inject\n   NodeToNodeMetadata(Supplier<Location> location, @Memoized Supplier<Set<? extends Location>> locations,\n            Function<URI, InputStream> slurp, Map<String, Credentials> credentialStore) {\n      this.location = checkNotNull(location, \"location\");\n      this.locations = checkNotNull(locations, \"locations\");\n      this.credentialStore = checkNotNull(credentialStore, \"credentialStore\");\n      this.slurp = checkNotNull(slurp, \"slurp\");\n   }\n\n   @Override\n   public NodeMetadata apply(Node from) {\n      NodeMetadataBuilder builder = new NodeMetadataBuilder();\n      builder.ids(from.getId());\n      builder.name(from.getName());\n      builder.loginPort(from.getLoginPort());\n      builder.hostname(from.getHostname());\n      builder.location(findLocationWithId(from.getLocationId()));\n      builder.group(from.getGroup());\n      builder.tags(from.getTags());\n      builder.userMetadata(from.getMetadata());\n      builder.operatingSystem(OperatingSystem.builder().arch(from.getOsArch()).family(\n               OsFamily.fromValue(from.getOsFamily())).description(from.getOsDescription())\n               .version(from.getOsVersion()).build());\n      builder.status(Status.RUNNING);\n      builder.publicAddresses(ImmutableSet.<String> of(from.getHostname()));\n\n      if (from.getUsername() != null) {\n         Builder credBuilder = LoginCredentials.builder().user(from.getUsername());\n         if (from.getCredentialUrl() != null) {\n            try {\n               credBuilder.credential(Strings2.toStringAndClose(slurp.apply(from.getCredentialUrl())));\n            } catch (IOException e) {\n               logger.error(e, \"URI could not be read: %s\", from.getCredentialUrl());\n            }\n         } else if (from.getCredential() != null) {\n            credBuilder.credential(from.getCredential());\n         }\n         if (from.getSudoPassword() != null) {\n            credBuilder.password(from.getSudoPassword());\n            credBuilder.authenticateSudo(true);\n         }\n         LoginCredentials creds = credBuilder.build();\n         builder.credentials(creds);\n         credentialStore.put(\"node#\" + from.getId(), creds);\n      }\n\n      return builder.build();\n   }\n\n   private Location findLocationWithId(final String locationId) {\n      if (locationId == null)\n         return location.get();\n      try {\n         Location location = Iterables.find(locations.get(), new Predicate<Location>() {\n\n            @Override\n            public boolean apply(Location input) {\n               return input.getId().equals(locationId);\n            }\n\n         });\n         return location;\n\n      } catch (NoSuchElementException e) {\n         logger.debug(\"couldn't match instance location %s in: %s\", locationId, locations.get());\n         return location.get();\n      }\n   }\n}\n"
  },
  {
    "path": "apis/byon/src/main/java/org/jclouds/byon/functions/NodesFromYamlStream.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.byon.functions;\n\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.common.base.Throwables.propagate;\nimport static org.jclouds.util.Closeables2.closeQuietly;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.List;\nimport java.util.Map;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.byon.Node;\nimport org.jclouds.byon.domain.YamlNode;\nimport org.yaml.snakeyaml.LoaderOptions;\nimport org.yaml.snakeyaml.TypeDescription;\nimport org.yaml.snakeyaml.Yaml;\nimport org.yaml.snakeyaml.constructor.Constructor;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Functions;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Maps;\nimport com.google.common.io.ByteSource;\n\n/**\n * Parses the following syntax.\n * \n * <pre>\n * nodes:\n *     - id: cluster-1:\n *       name: cluster-1\n *       description: xyz\n *       hostname: cluster-1.mydomain.com\n *       location_id: virginia\n *       os_arch: x86\n *       os_family: linux\n *       os_description: redhat\n *       os_version: 5.3\n *       group: hadoop\n *       tags:\n *           - vanilla\n *       username: kelvin\n *       credential: password_or_rsa\n *         or\n *       credential_url: password_or_rsa_file ex. resource:///id_rsa will get the classpath /id_rsa; file://path/to/id_rsa\n *       sudo_password: password\n * </pre>\n */\n@Singleton\npublic class NodesFromYamlStream implements Function<ByteSource, LoadingCache<String, Node>> {\n\n   /**\n    * Type-safe config class for YAML\n    * \n    */\n   public static class Config {\n      public List<YamlNode> nodes;\n   }\n\n   @Override\n   public LoadingCache<String, Node> apply(ByteSource source) {\n\n      Constructor constructor = new Constructor(Config.class, new LoaderOptions());\n\n      TypeDescription nodeDesc = new TypeDescription(YamlNode.class);\n      nodeDesc.putListPropertyType(\"tags\", String.class);\n      constructor.addTypeDescription(nodeDesc);\n\n      TypeDescription configDesc = new TypeDescription(Config.class);\n      configDesc.putListPropertyType(\"nodes\", YamlNode.class);\n      constructor.addTypeDescription(configDesc);\n      Yaml yaml = new Yaml(constructor);\n      Config config;\n      InputStream in = null;\n      try {\n         in = source.openStream();\n         config = (Config) yaml.load(in);\n      } catch (IOException ioe) {\n         throw propagate(ioe);\n      } finally {\n         closeQuietly(in);\n      }\n      checkState(config != null, \"missing config: class\");\n      checkState(config.nodes != null, \"missing nodes: collection\");\n\n      Map<String, Node> backingMap = Maps.uniqueIndex(Iterables.transform(config.nodes, YamlNode.toNode),\n            new Function<Node, String>() {\n               public String apply(Node node) {\n                  return node.getId();\n               }\n            });\n      LoadingCache<String, Node> cache = CacheBuilder.newBuilder().build(CacheLoader.from(Functions.forMap(backingMap)));\n      for (String node : backingMap.keySet())\n         cache.getUnchecked(node);\n      return cache;\n   }\n}\n"
  },
  {
    "path": "apis/byon/src/main/java/org/jclouds/byon/internal/BYONComputeServiceAdapter.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.byon.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Predicates.in;\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static com.google.common.collect.Iterables.transform;\nimport static com.google.common.collect.Maps.filterKeys;\n\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.byon.Node;\nimport org.jclouds.byon.functions.NodeToNodeMetadata;\nimport org.jclouds.compute.JCloudsNativeComputeServiceAdapter;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.location.suppliers.all.JustProvider;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicates;\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\nimport com.google.common.util.concurrent.UncheckedExecutionException;\n@Singleton\npublic class BYONComputeServiceAdapter implements JCloudsNativeComputeServiceAdapter {\n   private final Supplier<LoadingCache<String, Node>> nodes;\n   private final NodeToNodeMetadata converter;\n   private final JustProvider locationSupplier;\n\n   @Inject\n   public BYONComputeServiceAdapter(Supplier<LoadingCache<String, Node>> nodes, NodeToNodeMetadata converter,\n            JustProvider locationSupplier) {\n      this.nodes = checkNotNull(nodes, \"nodes\");\n      this.converter = checkNotNull(converter, \"converter\");\n      this.locationSupplier = checkNotNull(locationSupplier, \"locationSupplier\");\n   }\n\n   @Override\n   public NodeWithInitialCredentials createNodeWithGroupEncodedIntoName(String group, String name, Template template) {\n      throw new UnsupportedOperationException();\n   }\n\n   @Override\n   public Iterable<Hardware> listHardwareProfiles() {\n      return ImmutableSet.<Hardware> of();\n   }\n\n   @Override\n   public Iterable<Image> listImages() {\n      return ImmutableSet.<Image> of();\n   }\n\n   @Override\n   public Iterable<NodeMetadata> listNodes() {\n      return transform(nodes.get().asMap().values(), converter);\n   }\n\n   @Override\n   public Iterable<NodeMetadata> listNodesByIds(Iterable<String> ids) {\n      return transform(filterKeys(nodes.get().asMap(), in(ImmutableSet.copyOf(ids))).values(), converter);\n   }\n\n   @Override\n   public Iterable<Location> listLocations() {\n      Builder<Location> locations = ImmutableSet.builder();\n      Location provider = getOnlyElement(locationSupplier.get());\n      Set<String> zones = ImmutableSet.copyOf(filter(transform(nodes.get().asMap().values(),\n               new Function<Node, String>() {\n\n                  @Override\n                  public String apply(Node arg0) {\n                     return arg0.getLocationId();\n                  }\n               }), Predicates.notNull()));\n      if (zones.isEmpty())\n         return locations.add(provider).build();\n      else\n         for (String zone : zones) {\n            locations.add(new LocationBuilder().scope(LocationScope.ZONE).id(zone).description(zone).parent(provider)\n                     .build());\n         }\n      return locations.build();\n   }\n\n   @Override\n   public NodeMetadata getNode(String id) {\n\n      Node node = null;\n      try {\n         node = nodes.get().getUnchecked(id);\n      } catch (UncheckedExecutionException e) {\n\n      }\n      return node != null ? converter.apply(node) : null;\n   }\n\n   @Override\n   public Image getImage(final String id) {\n      throw new UnsupportedOperationException();\n   }\n\n   @Override\n   public void destroyNode(final String id) {\n      throw new UnsupportedOperationException();\n   }\n\n   @Override\n   public void rebootNode(String id) {\n      throw new UnsupportedOperationException();\n   }\n\n   @Override\n   public void resumeNode(String id) {\n      throw new UnsupportedOperationException();\n   }\n\n   @Override\n   public void suspendNode(String id) {\n      throw new UnsupportedOperationException();\n   }\n}\n"
  },
  {
    "path": "apis/byon/src/main/java/org/jclouds/byon/suppliers/NodesParsedFromSupplier.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.byon.suppliers;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.byon.Node;\nimport org.jclouds.location.Provider;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.io.ByteSource;\n\n@Singleton\npublic class NodesParsedFromSupplier implements Supplier<LoadingCache<String, Node>> {\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   private final ByteSource supplier;\n   private final Function<ByteSource, LoadingCache<String, Node>> parser;\n\n   @Inject\n   NodesParsedFromSupplier(@Provider ByteSource supplier, Function<ByteSource, LoadingCache<String, Node>> parser) {\n      this.supplier = checkNotNull(supplier, \"supplier\");\n      this.parser = checkNotNull(parser, \"parser\");\n   }\n\n   @Override\n   public LoadingCache<String, Node> get() {\n      LoadingCache<String, Node> nodes = parser.apply(supplier);\n      checkState(nodes != null && nodes.size() > 0, \"no nodes parsed from supplier: %s\", supplier);\n      return nodes;\n   }\n\n}\n"
  },
  {
    "path": "apis/byon/src/main/java/org/jclouds/byon/suppliers/SupplyFromProviderURIOrNodesProperty.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.byon.suppliers;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.net.URI;\n\nimport jakarta.annotation.Resource;\n\nimport org.jclouds.location.Provider;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.util.Strings2;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.base.Throwables;\nimport com.google.common.io.ByteSource;\nimport com.google.inject.Inject;\nimport com.google.inject.name.Named;\n\npublic class SupplyFromProviderURIOrNodesProperty extends ByteSource implements Function<URI, InputStream> {\n   @Resource\n   protected Logger logger = Logger.NULL;\n   private final Supplier<URI> url;\n\n   @Inject(optional = true)\n   @Named(\"byon.nodes\")\n   @VisibleForTesting\n   String nodes;\n   \n   @VisibleForTesting\n   public SupplyFromProviderURIOrNodesProperty(URI url) {\n      this(Suppliers.ofInstance(checkNotNull(url, \"url\")));\n   }\n   \n   @Inject\n   public SupplyFromProviderURIOrNodesProperty(@Provider Supplier<URI> url) {\n      this.url = checkNotNull(url, \"url\");\n   }\n\n   @Override\n   public InputStream openStream() {\n      if (nodes != null)\n         return Strings2.toInputStream(nodes);\n      return apply(url.get());\n   }\n\n   @Override\n   public String toString() {\n      return \"[url=\" + url + \"]\";\n   }\n\n   @Override\n   public InputStream apply(URI input) {\n      try {\n         if (input.getScheme() != null && input.getScheme().equals(\"classpath\"))\n            return getClass().getResourceAsStream(input.getPath());\n         return input.toURL().openStream();\n      } catch (IOException e) {\n         logger.error(e, \"URI could not be read: %s\", url);\n         throw Throwables.propagate(e);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/byon/src/test/java/org/jclouds/byon/BYONApiMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.byon;\n\nimport org.jclouds.compute.internal.BaseComputeServiceApiMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"BYONApiMetadataTest\")\npublic class BYONApiMetadataTest extends BaseComputeServiceApiMetadataTest {\n\n   public BYONApiMetadataTest() {\n      super(new BYONApiMetadata());\n   }\n}\n"
  },
  {
    "path": "apis/byon/src/test/java/org/jclouds/byon/BYONComputeServiceLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.byon;\n\nimport static org.jclouds.compute.options.RunScriptOptions.Builder.wrapInInitScript;\nimport static org.jclouds.scriptbuilder.domain.Statements.exec;\n\nimport java.io.FileNotFoundException;\nimport java.io.IOException;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.Map.Entry;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.compute.domain.ExecResponse;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.logging.log4j.config.Log4JLoggingModule;\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.jclouds.sshj.config.SshjSshClientModule;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicates;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n@Test(groups = \"live\")\npublic class BYONComputeServiceLiveTest {\n\n   private ComputeServiceContext context;\n\n   @BeforeClass(groups = \"live\")\n   public void setup() throws FileNotFoundException, IOException {\n      Properties contextProperties = new Properties();\n\n      StringBuilder nodes = new StringBuilder();\n      nodes.append(\"nodes:\\n\");\n      nodes.append(\"    - id: mymachine\\n\");\n      nodes.append(\"      name: my local machine\\n\");\n      nodes.append(\"      hostname: localhost\\n\");\n      nodes.append(\"      os_arch: \").append(System.getProperty(\"os.arch\")).append(\"\\n\");\n      nodes.append(\"      os_family: \").append(OsFamily.UNIX).append(\"\\n\");\n      nodes.append(\"      os_description: \").append(System.getProperty(\"os.name\")).append(\"\\n\");\n      nodes.append(\"      os_version: \").append(System.getProperty(\"os.version\")).append(\"\\n\");\n      nodes.append(\"      group: \").append(\"ssh\").append(\"\\n\");\n      nodes.append(\"      tags:\\n\");\n      nodes.append(\"          - local\\n\");\n      nodes.append(\"      username: \").append(System.getProperty(\"user.name\")).append(\"\\n\");\n      nodes.append(\"      credential_url: file://\").append(System.getProperty(\"user.home\")).append(\"/.ssh/id_rsa\")\n               .append(\"\\n\");\n\n      contextProperties.setProperty(\"byon.nodes\", nodes.toString());\n      context = ContextBuilder.newBuilder(new BYONApiMetadata()).overrides(contextProperties).modules(\n               ImmutableSet.<Module> of(new SshjSshClientModule(), new Log4JLoggingModule())).build(\n               ComputeServiceContext.class);\n   }\n\n   public void testCanRunCommandAsCurrentUser() throws Exception {\n      Map<? extends NodeMetadata, ExecResponse> responses = context.getComputeService().runScriptOnNodesMatching(\n               Predicates.<NodeMetadata> alwaysTrue(), exec(\"id\"), wrapInInitScript(false).runAsRoot(false));\n\n      for (Entry<? extends NodeMetadata, ExecResponse> response : responses.entrySet())\n         assert response.getValue().getOutput().trim().contains(System.getProperty(\"user.name\")) : response.getKey()\n                  + \": \" + response.getValue();\n   }\n\n   @AfterClass(groups = \"live\")\n   public void close() throws FileNotFoundException, IOException {\n      if (context != null)\n         context.close();\n   }\n}\n"
  },
  {
    "path": "apis/byon/src/test/java/org/jclouds/byon/BYONComputeServiceTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.byon;\n\nimport static org.jclouds.byon.functions.NodeToNodeMetadataTest.expectedNodeMetadataFromResource;\nimport static org.jclouds.byon.functions.NodeToNodeMetadataTest.expectedProviderLocationFromResource;\nimport static org.jclouds.byon.functions.NodeToNodeMetadataTest.zoneCalled;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.byon.config.BYONComputeServiceContextModule;\nimport org.jclouds.byon.config.CacheNodeStoreModule;\nimport org.jclouds.byon.functions.NodesFromYamlTest;\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LoginCredentials;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.inject.Key;\nimport com.google.inject.Module;\nimport com.google.inject.TypeLiteral;\n\n@Test(singleThreaded = true, testName = \"BYONComputeServiceTest\")\npublic class BYONComputeServiceTest {\n\n   @Test\n   public void testNodesParseNodeMap() throws Exception {\n      assertNodesParse(\"foo\", ContextBuilder.newBuilder(\n               new BYONApiMetadata().toBuilder().defaultModule(BYONComputeServiceContextModule.class).build())\n               .endpoint(\"foo\").modules(\n                        ImmutableSet.<Module> of(new CacheNodeStoreModule(ImmutableMap.<String, Node> of(\n                                 NodesFromYamlTest.TEST1.getId(), NodesFromYamlTest.TEST1)))).build(\n                        ComputeServiceContext.class));\n   }\n\n   @Test\n   public void testNodesParseWithFileUrl() throws Exception {\n      assertNodesParse(\"file://\" + getClass().getResource(\"/test1.yaml\").getPath(),  ContextBuilder.newBuilder(new BYONApiMetadata()).endpoint(\n               \"file://\" + getClass().getResource(\"/test1.yaml\").getPath()).build(ComputeServiceContext.class));\n   }\n\n   @Test\n   public void testNodesParseWithClasspathUrl() throws Exception {\n      assertNodesParse(\"classpath:///test1.yaml\", ContextBuilder.newBuilder(new BYONApiMetadata()).endpoint(\n               \"classpath:///test1.yaml\").build(ComputeServiceContext.class));\n   }\n\n   private void assertNodesParse(String endpoint, ComputeServiceContext context) {\n      try {\n         Location providerLocation = expectedProviderLocationFromResource(endpoint);\n\n         Supplier<LoadingCache<String, Node>> supplier = supplier(context);\n\n         assertEquals(supplier.get().size(), context.getComputeService().listNodes().size());\n         assertEquals(supplier.get().asMap(),\n               ImmutableMap.<String, Node> of(NodesFromYamlTest.TEST1.getId(), NodesFromYamlTest.TEST1));\n\n         assertEquals(context.getComputeService().listNodes().toString(),\n               ImmutableSet.of(expectedNodeMetadataFromResource(endpoint)).toString());\n         assertEquals(context.getComputeService().listAssignableLocations(), ImmutableSet.of(providerLocation));\n      } finally {\n         if (context != null)\n            context.close();\n      }\n   }\n\n   public void testNodesWithLocations() {\n      ComputeServiceContext context = null;\n      try {\n         String endpoint = \"file://\" + getClass().getResource(\"/test_location.yaml\").getPath();\n         context = ContextBuilder.newBuilder(new BYONApiMetadata()).endpoint(endpoint).build(ComputeServiceContext.class);\n\n         Supplier<LoadingCache<String, Node>> supplier = supplier(context);\n\n         assertEquals(supplier.get().size(), context.getComputeService().listNodes().size());\n         assertEquals(supplier.get().asMap(), ImmutableMap.<String, Node> of(NodesFromYamlTest.TEST2.getId(),\n               NodesFromYamlTest.TEST2, NodesFromYamlTest.TEST3.getId(), NodesFromYamlTest.TEST3));\n         Location providerLocation = expectedProviderLocationFromResource(endpoint);\n\n         Location virginia = zoneCalled(\"virginia\", providerLocation);\n         Location maryland = zoneCalled(\"maryland\", providerLocation);\n\n         assertEquals(\n               context.getComputeService().listNodes().toString(),\n               ImmutableSet.of(expectedNodeMetadataFromResource(1, endpoint, virginia),\n                     expectedNodeMetadataFromResource(2, endpoint, maryland, 2022)).toString());\n\n         assertEquals(NodeMetadata.class.cast(Iterables.get(context.getComputeService().listNodes(), 0))\n               .getCredentials(),\n               LoginCredentials\n                     .builder()\n                     .user(\"myUser\")\n                     .password(\"happy bear\")\n                     .authenticateSudo(true)\n                     .privateKey(\n                           \"-----BEGIN RSA PRIVATE KEY-----\\n\"\n                                 + \"MIIEowIBAAKCAQEAuzaE6azgUxwESX1rCGdJ5xpdrc1XC311bOGZBCE8NA+CpFh2\\n\"\n                                 + \"u01Vfv68NC4u6LFgdXSY1vQt6hiA5TNqQk0TyVfFAunbXgTekF6XqDPQUf1nq9aZ\\n\"\n                                 + \"lMvo4vlaLDKBkhG5HJE/pIa0iB+RMZLS0GhxsIWerEDmYdHKM25o\\n\"\n                                 + \"-----END RSA PRIVATE KEY-----\\n\").build()\n\n         );\n\n         assertEquals(context.getComputeService().listAssignableLocations(), ImmutableSet.of(virginia, maryland));\n      } finally {\n         if (context != null)\n            context.close();\n      }\n   }\n\n   private Supplier<LoadingCache<String, Node>> supplier(ComputeServiceContext context) {\n      Supplier<LoadingCache<String, Node>> supplier = context.utils().injector().getInstance(\n               Key.get(new TypeLiteral<Supplier<LoadingCache<String, Node>>>() {\n               }));\n      return supplier;\n   }\n}\n"
  },
  {
    "path": "apis/byon/src/test/java/org/jclouds/byon/config/CacheNodeStoreModuleTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.byon.config;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.fail;\n\nimport java.io.IOException;\nimport java.util.Map;\n\nimport org.jclouds.byon.Node;\nimport org.jclouds.location.Provider;\nimport org.testng.annotations.DataProvider;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Functions;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.Maps;\nimport com.google.common.io.ByteSource;\nimport com.google.common.util.concurrent.UncheckedExecutionException;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport com.google.inject.Key;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.util.Providers;\n\n@Test(groups = \"unit\", singleThreaded = true, testName = \"CacheNodeStoreModuleTest\")\npublic class CacheNodeStoreModuleTest {\n\n   @DataProvider(name = \"names\")\n   public Object[][] createData() {\n      return new Object[][] { { \"instance1\", \"bear\" }, { \"instance2\", \"apple\" }, { \"instance2\", \"francis\" },\n            { \"instance4\", \"robot\" } };\n   }\n\n   public void testProvidedMapWithValue() throws IOException {\n      Map<String, Node> map = Maps.newConcurrentMap();\n\n      map.put(\"test\", Node.builder().id(\"instance1\").name(\"instancename\").build());\n      checkConsistent(map, getStore(createInjectorWithProvidedMap(map)), \"test\", \"instance1\", \"instancename\");\n      checkConsistent(map, getStore(createInjectorWithProvidedMap(map)), \"test\", \"instance1\", \"instancename\");\n      remove(map, getStore(createInjectorWithProvidedMap(map)), \"test\");\n\n   }\n\n   public void testProvidedConsistentAcrossRepeatedWrites() throws IOException {\n      Map<String, Node> map = Maps.newConcurrentMap();\n\n      Injector injector = createInjectorWithProvidedMap(map);\n      assertEquals(injector.getInstance(Key.get(new TypeLiteral<LoadingCache<String, Node>>() {\n      })).asMap(), map);\n      LoadingCache<String, Node> store = getStore(injector);\n\n      for (int i = 0; i < 10; i++)\n         check(map, store, \"test\" + i, \"instance1\" + i, \"instancename\" + i);\n\n   }\n\n   public void testProvidedConsistentAcrossMultipleInjectors() throws IOException {\n      Map<String, Node> map = Maps.newConcurrentMap();\n\n      put(map, getStore(createInjectorWithProvidedMap(map)), \"test\", \"instance1\", \"instancename\");\n      checkConsistent(map, getStore(createInjectorWithProvidedMap(map)), \"test\", \"instance1\", \"instancename\");\n      checkConsistent(map, getStore(createInjectorWithProvidedMap(map)), \"test\", \"instance1\", \"instancename\");\n      remove(map, getStore(createInjectorWithProvidedMap(map)), \"test\");\n\n   }\n\n   public void testProvidedCacheConsistentAcrossMultipleInjectors() throws IOException {\n      Map<String, Node> map = Maps.newConcurrentMap();\n\n      LoadingCache<String, Node> cache = CacheBuilder.newBuilder().build(CacheLoader.from(Functions.forMap(map)));\n\n      put(map, getStore(createInjectorWithProvidedCache(cache)), \"test\", \"instance1\", \"instancename\");\n      checkConsistent(map, getStore(createInjectorWithProvidedCache(cache)), \"test\", \"instance1\", \"instancename\");\n      checkConsistent(map, getStore(createInjectorWithProvidedCache(cache)), \"test\", \"instance1\", \"instancename\");\n      remove(map, getStore(createInjectorWithProvidedCache(cache)), \"test\");\n\n   }\n\n   private LoadingCache<String, Node> getStore(Injector injector) {\n      return injector.getInstance(Key.get(new TypeLiteral<LoadingCache<String, Node>>() {\n      }));\n   }\n\n   private Injector createInjectorWithProvidedMap(Map<String, Node> map) {\n      return Guice.createInjector(new CacheNodeStoreModule(map), new AbstractModule() {\n\n         @Override\n         public void configure() {\n            bind(ByteSource.class).annotatedWith(Provider.class).toProvider(Providers.<ByteSource>of(null));\n         }\n\n      });\n   }\n\n   private Injector createInjectorWithProvidedCache(LoadingCache<String, Node> cache) {\n      return Guice.createInjector(new CacheNodeStoreModule(cache), new AbstractModule() {\n\n         @Override\n         public void configure() {\n            bind(ByteSource.class).annotatedWith(Provider.class).toProvider(Providers.<ByteSource>of(null));\n         }\n\n      });\n   }\n\n   private void check(Map<String, Node> map, LoadingCache<String, Node> store, String key, String id, String name)\n         throws IOException {\n      put(map, store, key, id, name);\n      checkConsistent(map, store, key, id, name);\n      remove(map, store, key);\n   }\n\n   private void remove(Map<String, Node> map, LoadingCache<String, Node> store, String key) {\n      store.invalidate(key);\n      assertEquals(store.size(), 0);\n      map.remove(key);\n      assertEquals(map.size(), 0);\n      try {\n         assertEquals(store.getUnchecked(key), null);\n         fail(\"should not work as null is invalid\");\n      } catch (UncheckedExecutionException e) {\n\n      }\n      assertEquals(map.get(key), null);\n   }\n\n   private void checkConsistent(Map<String, Node> map, LoadingCache<String, Node> store, String key, String id, String name)\n         throws IOException {\n      assertEquals(map.size(), 1);\n      if (store.size() == 0)\n         store.getUnchecked(key);\n      assertEquals(store.size(), 1);\n      // checkRepeatedRead\n      assertEquals(store.getUnchecked(key), Node.builder().id(id).name(name).build());\n      assertEquals(store.getUnchecked(key), Node.builder().id(id).name(name).build());\n   }\n\n   private void put(Map<String, Node> map, LoadingCache<String, Node> store, String key, String id, String name) {\n      assertEquals(store.size(), 0);\n      assertEquals(map.size(), 0);\n      map.put(key, Node.builder().id(id).name(name).build());\n      store.getUnchecked(key);\n   }\n}\n"
  },
  {
    "path": "apis/byon/src/test/java/org/jclouds/byon/config/YamlNodeStoreModuleTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.byon.config;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.fail;\n\nimport java.io.IOException;\nimport java.util.Map;\nimport java.util.concurrent.ConcurrentHashMap;\n\nimport org.jclouds.byon.Node;\nimport org.jclouds.location.Provider;\nimport org.testng.annotations.DataProvider;\nimport org.testng.annotations.Test;\nimport org.yaml.snakeyaml.Yaml;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.io.ByteSource;\nimport com.google.common.util.concurrent.UncheckedExecutionException;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport com.google.inject.Key;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.name.Names;\nimport com.google.inject.util.Providers;\n\n@Test(groups = \"unit\", singleThreaded = true)\npublic class YamlNodeStoreModuleTest {\n   Yaml yaml = createInjector().getInstance(Yaml.class);\n\n   @DataProvider(name = \"names\")\n   public Object[][] createData() {\n      return new Object[][] { { \"instance1\", \"bear\" }, { \"instance2\", \"apple\" }, { \"instance2\", \"francis\" },\n            { \"instance4\", \"robot\" } };\n   }\n\n   @Test(dataProvider = \"names\")\n   public void deleteObject(String id, String name) throws InterruptedException, IOException {\n      Injector injector = createInjector();\n      Map<String, ByteSource> map = getMap(injector);\n      check(map, getStore(injector), \"i-20312\", id, name);\n   }\n\n   public void testProvidedMapWithValue() throws IOException {\n      Map<String, ByteSource> map =\n            new ConcurrentHashMap<String, ByteSource>();\n\n      map.put(\"test\", ByteSource.wrap(\"id: instance1\\nname: instancename\\n\".getBytes()));\n      checkConsistent(map, getStore(createInjectorWithProvidedMap(map)), \"test\", \"instance1\", \"instancename\");\n      checkConsistent(map, getStore(createInjectorWithProvidedMap(map)), \"test\", \"instance1\", \"instancename\");\n      remove(map, getStore(createInjectorWithProvidedMap(map)), \"test\");\n\n   }\n\n   public void testProvidedConsistentAcrossRepeatedWrites() throws IOException {\n      Map<String, ByteSource> map =\n            new ConcurrentHashMap<String, ByteSource>();\n\n      Injector injector = createInjectorWithProvidedMap(map);\n      assertEquals(injector.getInstance(Key.get(new TypeLiteral<Map<String, ByteSource>>() {\n      }, Names.named(\"yaml\"))), map);\n      LoadingCache<String, Node> store = getStore(injector);\n\n      for (int i = 0; i < 10; i++)\n         check(map, store, \"test\" + i, \"instance1\" + i, \"instancename\" + i);\n\n   }\n\n   public void testProvidedConsistentAcrossMultipleInjectors() throws IOException {\n      Map<String, ByteSource> map =\n            new ConcurrentHashMap<String, ByteSource>();\n\n      put(map, getStore(createInjectorWithProvidedMap(map)), \"test\", \"instance1\", \"instancename\");\n      checkConsistent(map, getStore(createInjectorWithProvidedMap(map)), \"test\", \"instance1\", \"instancename\");\n      checkConsistent(map, getStore(createInjectorWithProvidedMap(map)), \"test\", \"instance1\", \"instancename\");\n      remove(map, getStore(createInjectorWithProvidedMap(map)), \"test\");\n\n   }\n\n   public void testDefaultConsistentAcrossMultipleInjectors() throws IOException {\n      Map<String, ByteSource> map = getMap(createInjector());\n\n      put(map, getStore(createInjector()), \"test\", \"instance1\", \"instancename\");\n      \n      checkConsistent(map, getStore(createInjector()), \"test\", \"instance1\", \"instancename\");\n      checkConsistent(map, getStore(createInjector()), \"test\", \"instance1\", \"instancename\");\n      remove(map, getStore(createInjector()), \"test\");\n\n   }\n\n   protected LoadingCache<String, Node> getStore(Injector injector) {\n      return injector.getInstance(Key.get(new TypeLiteral<LoadingCache<String, Node>>() {\n      }));\n   }\n\n   protected Map<String, ByteSource> getMap(Injector injector) {\n      return injector.getInstance(Key.get(new TypeLiteral<Map<String, ByteSource>>() {\n      }, Names.named(\"yaml\")));\n   }\n\n   protected Injector createInjectorWithProvidedMap(Map<String, ByteSource> map) {\n      return Guice.createInjector(new YamlNodeStoreModule(map), new AbstractModule() {\n\n         @Override\n         protected void configure() {\n            bind(ByteSource.class).annotatedWith(Provider.class).toProvider(Providers.<ByteSource>of(null));\n         }\n\n      });\n   }\n\n   protected Injector createInjector() {\n      return Guice.createInjector(new YamlNodeStoreModule(), new AbstractModule() {\n\n         @Override\n         protected void configure() {\n            bind(ByteSource.class).annotatedWith(Provider.class).toProvider(Providers.<ByteSource>of(null));\n         }\n\n      });\n   }\n\n   protected void check(Map<String, ByteSource> map, LoadingCache<String, Node> store, String key, String id, String name)\n         throws IOException {\n      put(map, store, key, id, name);\n      checkConsistent(map, store, key, id, name);\n      remove(map, store, key);\n   }\n\n   protected void remove(Map<String, ByteSource> map, LoadingCache<String, Node> store, String key) {\n      store.invalidate(key);\n      assertEquals(store.size(), 0);\n      map.remove(key);\n      assertEquals(map.size(), 0);\n      try {\n         assertEquals(store.getUnchecked(key), null);\n         fail(\"should not work as null is invalid\");\n      } catch (UncheckedExecutionException e) {\n\n      }\n      assertEquals(map.get(key), null);\n   }\n\n   protected void checkConsistent(Map<String, ByteSource> map, LoadingCache<String, Node> store, String key, String id,\n         String name) throws IOException {\n      assertEquals(map.size(), 1);\n      if (store.size() == 0)\n         store.getUnchecked(key);\n      assertEquals(store.size(), 1);\n      // checkRepeatedRead\n      assertEquals(store.getUnchecked(key), Node.builder().id(id).name(name).build());\n      assertEquals(store.getUnchecked(key), Node.builder().id(id).name(name).build());\n      // checkRepeatedRead\n      checkToYaml(map, key, id, name);\n      checkToYaml(map, key, id, name);\n   }\n\n   protected void checkToYaml(Map<String, ByteSource> map, String key, String id, String name) throws IOException {\n      assertEquals(map.get(key).asCharSource(Charsets.UTF_8).read(), String.format(\"id: %s\\nname: %s\\n\", id, name));\n   }\n\n   protected void put(Map<String, ByteSource> map, LoadingCache<String, Node> store, String key, String id, String name) {\n      assertEquals(store.size(), 0);\n      assertEquals(map.size(), 0);\n      map.put(key, ByteSource.wrap(String.format(\"id: %s\\nname: %s\\n\", id, name).getBytes()));\n      store.getUnchecked(key);\n   }\n}\n"
  },
  {
    "path": "apis/byon/src/test/java/org/jclouds/byon/functions/NodeToNodeMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.byon.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.byon.suppliers.SupplyFromProviderURIOrNodesProperty;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadataBuilder;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.NodeMetadata.Status;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.domain.LoginCredentials;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Maps;\n\n@Test(singleThreaded = true, testName = \"NodeToNodeMetadataTest\")\npublic class NodeToNodeMetadataTest {\n   public static Location expectedProviderLocationFromResource(String resource) {\n      return new LocationBuilder().scope(LocationScope.PROVIDER).id(\"byon\").description(resource).build();\n   }\n\n   public static Location zoneCalled(String zone, Location parent) {\n      return new LocationBuilder().scope(LocationScope.ZONE).id(zone).description(zone).parent(parent).build();\n   }\n\n   String resource = \"location\";\n\n   Location provider = expectedProviderLocationFromResource(resource);\n\n   Map<String, Credentials> credentialStore = Maps.newLinkedHashMap();\n\n   NodeToNodeMetadata parser = new NodeToNodeMetadata(Suppliers.ofInstance(provider),\n         Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet.of(provider, zoneCalled(\"virginia\", provider))),\n         new SupplyFromProviderURIOrNodesProperty(URI.create(\"test\")), credentialStore);\n\n   public static NodeMetadata expectedNodeMetadataFromResource(String resource) {\n      return expectedNodeMetadataFromResource(resource, expectedProviderLocationFromResource(resource));\n   }\n\n   public static NodeMetadata expectedNodeMetadataFromResource(String resource, Location location) {\n      return expectedNodeMetadataFromResource(1, resource, location);\n   }\n\n   public static NodeMetadata expectedNodeMetadataFromResource(int id, String resource, Location location) {\n      return expectedNodeMetadataFromResource(id, resource, location, 22);\n   }\n\n   public static NodeMetadata expectedNodeMetadataFromResource(int id, String resource, Location location, int loginPort) {\n      return new NodeMetadataBuilder()\n            .ids(\"cluster-\" + id)\n            .group(\"hadoop\")\n            .name(\"cluster-\" + id)\n            .loginPort(loginPort)\n            .hostname(\"cluster-\" + id + \".mydomain.com\")\n            .location(location)\n            .userMetadata(ImmutableMap.of(\"Name\", \"foo\"))\n            .tags(ImmutableSet.of(\"vanilla\"))\n            .status(Status.RUNNING)\n            .operatingSystem(\n                  OperatingSystem.builder().description(\"redhat\").family(OsFamily.RHEL).arch(\"x86\").version(\"5.3\")\n                        .build())\n            .publicAddresses(ImmutableSet.of(\"cluster-\" + id + \".mydomain.com\"))\n            .credentials(\n                  LoginCredentials.builder().user(\"myUser\").privateKey(NodesFromYamlTest.key).password(\"happy bear\")\n                        .authenticateSudo(true).build()).build();\n   }\n\n   @Test\n   public void testNodesParse() throws Exception {\n      assertEquals(parser.apply(NodesFromYamlTest.TEST1), expectedNodeMetadataFromResource(resource, provider));\n      assertEquals(credentialStore, ImmutableMap.of(\"node#cluster-1\", new Credentials(\"myUser\", NodesFromYamlTest.key)));\n   }\n\n   @Test\n   public void testNodesParseLocation() throws Exception {\n      assertEquals(parser.apply(NodesFromYamlTest.TEST2),\n            expectedNodeMetadataFromResource(resource, zoneCalled(\"virginia\", provider)));\n      assertEquals(credentialStore, ImmutableMap.of(\"node#cluster-1\", new Credentials(\"myUser\", NodesFromYamlTest.key)));\n   }\n\n   @Test\n   public void testNodesParseLoginPort() throws Exception {\n      assertEquals(parser.apply(NodesFromYamlTest.TEST3), expectedNodeMetadataFromResource(2, resource, provider, 2022));\n   }\n}\n"
  },
  {
    "path": "apis/byon/src/test/java/org/jclouds/byon/functions/NodesFromYamlTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.byon.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.byon.Node;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.io.ByteSource;\nimport com.google.common.io.Resources;\n\npublic class NodesFromYamlTest {\n   public static final String key = new StringBuilder().append(\"-----BEGIN RSA PRIVATE KEY-----\\n\")\n         .append(\"MIIEowIBAAKCAQEAuzaE6azgUxwESX1rCGdJ5xpdrc1XC311bOGZBCE8NA+CpFh2\\n\")\n         .append(\"u01Vfv68NC4u6LFgdXSY1vQt6hiA5TNqQk0TyVfFAunbXgTekF6XqDPQUf1nq9aZ\\n\")\n         .append(\"lMvo4vlaLDKBkhG5HJE/pIa0iB+RMZLS0GhxsIWerEDmYdHKM25o\\n\").append(\"-----END RSA PRIVATE KEY-----\\n\")\n         .toString();\n\n   public static final Node TEST1 = new Node(\"cluster-1\", \"cluster-1\", \"accounting analytics cluster\",\n         \"cluster-1.mydomain.com\", null, \"x86\", \"rhel\", \"redhat\", \"5.3\", false, 22, \"hadoop\",\n         ImmutableList.of(\"vanilla\"), ImmutableMap.of(\"Name\", \"foo\"), \"myUser\", key, null, \"happy bear\");\n\n   public static final Node TEST2 = new Node(\"cluster-1\", \"cluster-1\", \"accounting analytics cluster\",\n         \"cluster-1.mydomain.com\", \"virginia\", \"x86\", \"rhel\", \"redhat\", \"5.3\", false, 22, \"hadoop\",\n         ImmutableList.of(\"vanilla\"), ImmutableMap.of(\"Name\", \"foo\"), \"myUser\", key, null, \"happy bear\");\n\n   public static final Node TEST3 = new Node(\"cluster-2\", \"cluster-2\", \"accounting analytics cluster\",\n         \"cluster-2.mydomain.com\", \"maryland\", \"x86\", \"rhel\", \"redhat\", \"5.3\", false, 2022, \"hadoop\",\n         ImmutableList.of(\"vanilla\"), ImmutableMap.of(\"Name\", \"foo\"), \"myUser\", key, null, \"happy bear\");\n\n   @Test\n   public void testNodesParse() throws Exception {\n\n      ByteSource byteSource = Resources.asByteSource(Resources.getResource(\"test1.yaml\"));\n      NodesFromYamlStream parser = new NodesFromYamlStream();\n\n      assertEquals(parser.apply(byteSource).asMap(), ImmutableMap.of(TEST1.getId(), TEST1));\n   }\n\n   @Test\n   public void testNodesParseLocation() throws Exception {\n\n      ByteSource byteSource = Resources.asByteSource(Resources.getResource(\"test_location.yaml\"));\n      NodesFromYamlStream parser = new NodesFromYamlStream();\n\n      assertEquals(parser.apply(byteSource).asMap(), ImmutableMap.of(TEST2.getId(), TEST2, TEST3.getId(), TEST3));\n   }\n\n   @Test\n   public void testNodesParseWhenCredentialInUrl() throws Exception {\n\n      ByteSource byteSource = Resources.asByteSource(Resources.getResource(\"test_with_url.yaml\"));\n      NodesFromYamlStream parser = new NodesFromYamlStream();\n\n      assertEquals(parser.apply(byteSource).asMap(), ImmutableMap.of(TEST1.getId(), TEST1));\n   }\n\n   @Test(expectedExceptions = IllegalStateException.class)\n   public void testMustParseSomething() throws Exception {\n      new NodesFromYamlStream().apply(ByteSource.empty());\n   }\n\n}\n"
  },
  {
    "path": "apis/byon/src/test/java/org/jclouds/byon/suppliers/NodesParsedFromSupplierTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.byon.suppliers;\n\nimport org.jclouds.byon.functions.NodesFromYamlStream;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.io.ByteSource;\n\npublic class NodesParsedFromSupplierTest {\n\n   @Test(expectedExceptions = IllegalStateException.class)\n   public void testMustParseSomething() throws Exception {\n\n      new NodesParsedFromSupplier(ByteSource.wrap(\"nodes:\\n\".getBytes(Charsets.UTF_8)), new NodesFromYamlStream()).get();\n\n   }\n}\n"
  },
  {
    "path": "apis/byon/src/test/java/org/jclouds/byon/suppliers/SupplyFromProviderURIOrNodesPropertyTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.byon.suppliers;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\n\nimport com.google.common.base.Charsets;\n\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.Test;\n\npublic class SupplyFromProviderURIOrNodesPropertyTest {\n\n   @Test\n   public void testFromURI() throws Exception {\n\n      String path = getClass().getResource(\"/test1.yaml\").getPath();\n      SupplyFromProviderURIOrNodesProperty supplier = new SupplyFromProviderURIOrNodesProperty(URI.create(\"file://\"\n               + path));\n\n      assertEquals(supplier.asCharSource(Charsets.UTF_8).read(), Strings2.toStringAndClose(getClass().getResourceAsStream(\n               \"/test1.yaml\")));\n\n   }\n\n   @Test\n   public void testFromURIClasspath() throws Exception {\n\n      SupplyFromProviderURIOrNodesProperty supplier = new SupplyFromProviderURIOrNodesProperty(URI\n               .create(\"classpath:///test1.yaml\"));\n\n      assertEquals(supplier.asCharSource(Charsets.UTF_8).read(), Strings2.toStringAndClose(getClass().getResourceAsStream(\n               \"/test1.yaml\")));\n\n   }\n\n   @Test\n   public void testFromProperty() throws Exception {\n\n      SupplyFromProviderURIOrNodesProperty supplier = new SupplyFromProviderURIOrNodesProperty(URI.create(\"file://bar\"));\n      supplier.nodes = Strings2.toStringAndClose(getClass().getResourceAsStream(\"/test1.yaml\"));\n\n      assertEquals(supplier.asCharSource(Charsets.UTF_8).read(), Strings2.toStringAndClose(getClass().getResourceAsStream(\n               \"/test1.yaml\")));\n\n   }\n\n   @Test\n   public void testSupplyMultipleTimes() throws Exception {\n      String path = getClass().getResource(\"/test1.yaml\").getPath();\n      SupplyFromProviderURIOrNodesProperty supplier = new SupplyFromProviderURIOrNodesProperty(URI.create(\"file://\"\n               + path));\n      for (int i = 0; i < 5; i++)\n         assertEquals(supplier.asCharSource(Charsets.UTF_8).read(), Strings2.toStringAndClose(getClass()\n                  .getResourceAsStream(\"/test1.yaml\")));\n   }\n}\n"
  },
  {
    "path": "apis/byon/src/test/resources/log4j.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE log4j:configuration SYSTEM \"log4j.dtd\">\n\n    <!--\n        For more configuration infromation and examples see the Apache\n        Log4j website: http://logging.apache.org/log4j/\n    -->\n<log4j:configuration xmlns:log4j=\"http://jakarta.apache.org/log4j/\"\n    debug=\"false\">\n\n    <!-- A time/date based rolling appender -->\n    <appender name=\"SSHFILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds-ssh.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n\n    <!-- A time/date based rolling appender -->\n    <appender name=\"FILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n    <!-- A time/date based rolling appender -->\n    <appender name=\"COMPUTEFILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds-compute.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n\n    <appender name=\"ASYNCCOMPUTE\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"COMPUTEFILE\" />\n    </appender>\n    <appender name=\"ASYNC\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"FILE\" />\n    </appender>\n\n    <appender name=\"ASYNCSSH\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"SSHFILE\" />\n    </appender>\n\n    <!-- ================ -->\n    <!-- Limit categories -->\n    <!-- ================ -->\n\n    <category name=\"org.jclouds\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNC\" />\n    </category>\n\n    <category name=\"jclouds.ssh\">\n        <priority value=\"TRACE\" />\n        <appender-ref ref=\"ASYNCSSH\" />\n    </category>\n\n    <category name=\"jclouds.compute\">\n        <priority value=\"TRACE\" />\n        <appender-ref ref=\"ASYNCCOMPUTE\" />\n    </category>\n    <!-- ======================= -->\n    <!-- Setup the Root category -->\n    <!-- ======================= -->\n\n    <root>\n        <priority value=\"WARN\" />\n    </root>\n\n</log4j:configuration>\n"
  },
  {
    "path": "apis/byon/src/test/resources/test1.yaml",
    "content": "#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\nnodes:\n    - id: cluster-1\n      name: cluster-1\n      description: accounting analytics cluster\n      hostname: cluster-1.mydomain.com\n      os_arch: x86\n      os_family: rhel\n      os_description: redhat\n      os_version: 5.3\n      group: hadoop\n      tags:\n          - vanilla\n      metadata:\n          Name: foo\n      username: myUser\n      credential: |\n                  -----BEGIN RSA PRIVATE KEY-----\n                  MIIEowIBAAKCAQEAuzaE6azgUxwESX1rCGdJ5xpdrc1XC311bOGZBCE8NA+CpFh2\n                  u01Vfv68NC4u6LFgdXSY1vQt6hiA5TNqQk0TyVfFAunbXgTekF6XqDPQUf1nq9aZ\n                  lMvo4vlaLDKBkhG5HJE/pIa0iB+RMZLS0GhxsIWerEDmYdHKM25o\n                  -----END RSA PRIVATE KEY-----\n      sudo_password: happy bear\n"
  },
  {
    "path": "apis/byon/src/test/resources/test_location.yaml",
    "content": "#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\nnodes:\n    - id: cluster-1\n      name: cluster-1\n      description: accounting analytics cluster\n      hostname: cluster-1.mydomain.com\n      location_id: virginia\n      os_arch: x86\n      os_family: rhel\n      os_description: redhat\n      os_version: 5.3\n      group: hadoop\n      tags:\n          - vanilla\n      metadata:\n          Name: foo\n      username: myUser\n      credential: |\n                  -----BEGIN RSA PRIVATE KEY-----\n                  MIIEowIBAAKCAQEAuzaE6azgUxwESX1rCGdJ5xpdrc1XC311bOGZBCE8NA+CpFh2\n                  u01Vfv68NC4u6LFgdXSY1vQt6hiA5TNqQk0TyVfFAunbXgTekF6XqDPQUf1nq9aZ\n                  lMvo4vlaLDKBkhG5HJE/pIa0iB+RMZLS0GhxsIWerEDmYdHKM25o\n                  -----END RSA PRIVATE KEY-----\n      sudo_password: happy bear\n      \n    - id: cluster-2\n      name: cluster-2\n      description: accounting analytics cluster\n      hostname: cluster-2.mydomain.com\n      location_id: maryland\n      os_arch: x86\n      os_family: rhel\n      os_description: redhat\n      os_version: 5.3\n      login_port: 2022\n      group: hadoop\n      tags:\n          - vanilla\n      metadata:\n          Name: foo          \n      username: myUser\n      credential: |\n                  -----BEGIN RSA PRIVATE KEY-----\n                  MIIEowIBAAKCAQEAuzaE6azgUxwESX1rCGdJ5xpdrc1XC311bOGZBCE8NA+CpFh2\n                  u01Vfv68NC4u6LFgdXSY1vQt6hiA5TNqQk0TyVfFAunbXgTekF6XqDPQUf1nq9aZ\n                  lMvo4vlaLDKBkhG5HJE/pIa0iB+RMZLS0GhxsIWerEDmYdHKM25o\n                  -----END RSA PRIVATE KEY-----\n      sudo_password: happy bear      \n      "
  },
  {
    "path": "apis/byon/src/test/resources/test_with_url.yaml",
    "content": "#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\nnodes:\n    - id: cluster-1\n      name: cluster-1\n      description: accounting analytics cluster\n      hostname: cluster-1.mydomain.com\n      os_arch: x86\n      os_family: rhel\n      os_description: redhat\n      os_version: 5.3\n      group: hadoop\n      tags:\n          - vanilla\n      metadata:\n          Name: foo          \n      username: myUser\n      credential_url: classpath:///testkey.txt\n      sudo_password: happy bear\n"
  },
  {
    "path": "apis/byon/src/test/resources/testkey.txt",
    "content": "-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEAuzaE6azgUxwESX1rCGdJ5xpdrc1XC311bOGZBCE8NA+CpFh2\nu01Vfv68NC4u6LFgdXSY1vQt6hiA5TNqQk0TyVfFAunbXgTekF6XqDPQUf1nq9aZ\nlMvo4vlaLDKBkhG5HJE/pIa0iB+RMZLS0GhxsIWerEDmYdHKM25o\n-----END RSA PRIVATE KEY-----"
  },
  {
    "path": "apis/chef/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.chef.*;version=\"${project.version}\";-noimport:=true, \\\n    org.jclouds.ohai.*;version=\"${project.version}\";-noimport:=true"
  },
  {
    "path": "apis/chef/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.api</groupId>\n  <artifactId>chef</artifactId>\n  <name>jclouds Chef api</name>\n  <description>jclouds components to access Chef</description>\n\n  <properties>\n    <test.chef.endpoint>http://localhost:4000</test.chef.endpoint>\n    <test.chef.api-version />\n    <test.chef.build-version />\n    <test.chef.identity>chef-webui</test.chef.identity>\n    <test.chef.credential>${user.home}/.chef/webui.pem</test.chef.credential>\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-scriptbuilder</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-scriptbuilder</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <!--  for transient chef provider -->\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-blobstore</artifactId>\n      <version>${project.version}</version>\n      <optional>true</optional>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-slf4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>ch.qos.logback</groupId>\n      <artifactId>logback-classic</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.chef.endpoint>${test.chef.endpoint}</test.chef.endpoint>\n                    <test.chef.api-version>${test.chef.api-version}</test.chef.api-version>\n                    <test.chef.build-version>${test.chef.build-version}</test.chef.build-version>\n                    <test.chef.identity>${test.chef.identity}</test.chef.identity>\n                    <test.chef.credential>${test.chef.credential}</test.chef.credential>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n</project>\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/ChefApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef;\n\nimport java.io.Closeable;\nimport java.io.InputStream;\nimport java.net.URI;\nimport java.util.List;\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Constants;\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.chef.binders.BindChecksumsToJsonPayload;\nimport org.jclouds.chef.binders.BindCreateClientOptionsToJsonPayload;\nimport org.jclouds.chef.binders.BindGenerateKeyForClientToJsonPayload;\nimport org.jclouds.chef.binders.DatabagItemId;\nimport org.jclouds.chef.binders.EnvironmentName;\nimport org.jclouds.chef.binders.NodeName;\nimport org.jclouds.chef.binders.RoleName;\nimport org.jclouds.chef.domain.Client;\nimport org.jclouds.chef.domain.CookbookDefinition;\nimport org.jclouds.chef.domain.CookbookVersion;\nimport org.jclouds.chef.domain.DatabagItem;\nimport org.jclouds.chef.domain.Environment;\nimport org.jclouds.chef.domain.Node;\nimport org.jclouds.chef.domain.Resource;\nimport org.jclouds.chef.domain.Role;\nimport org.jclouds.chef.domain.Sandbox;\nimport org.jclouds.chef.domain.SearchResult;\nimport org.jclouds.chef.domain.UploadSandbox;\nimport org.jclouds.chef.features.OrganizationApi;\nimport org.jclouds.chef.filters.SignedHeaderAuth;\nimport org.jclouds.chef.functions.ParseCookbookDefinitionFromJson;\nimport org.jclouds.chef.functions.ParseCookbookDefinitionListFromJson;\nimport org.jclouds.chef.functions.ParseCookbookNamesFromJson;\nimport org.jclouds.chef.functions.ParseCookbookVersionsFromJson;\nimport org.jclouds.chef.functions.ParseKeySetFromJson;\nimport org.jclouds.chef.functions.ParseSearchClientsFromJson;\nimport org.jclouds.chef.functions.ParseSearchDatabagFromJson;\nimport org.jclouds.chef.functions.ParseSearchEnvironmentsFromJson;\nimport org.jclouds.chef.functions.ParseSearchNodesFromJson;\nimport org.jclouds.chef.functions.ParseSearchRolesFromJson;\nimport org.jclouds.chef.functions.UriForResource;\nimport org.jclouds.chef.options.CreateClientOptions;\nimport org.jclouds.chef.options.SearchOptions;\nimport org.jclouds.io.Payload;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Delegate;\nimport org.jclouds.rest.annotations.EndpointParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.Headers;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.ParamParser;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.SinceApiVersion;\nimport org.jclouds.rest.annotations.SkipEncoding;\nimport org.jclouds.rest.annotations.WrapWith;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport com.google.common.base.Optional;\nimport com.google.inject.Provides;\n\n/**\n * Provides synchronous access to Chef.\n */\n@RequestFilters(SignedHeaderAuth.class)\n@Headers(keys = \"X-Chef-Version\", values = \"{\" + Constants.PROPERTY_API_VERSION + \"}\")\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface ChefApi extends Closeable {\n   \n   /**\n    * Provides access to high level Chef features.\n    */\n   @Provides\n   ChefService chefService();\n   \n   /**\n    * Provides access to the organization, user and group management endpoints.\n    */\n   @Delegate\n   Optional<OrganizationApi> organizationApi();\n\n   // Clients\n\n   /**\n    * Lists the names of the existing clients.\n    * \n    * @return The names of the existing clients.\n    */\n   @Named(\"client:list\")\n   @GET\n   @Path(\"/clients\")\n   @ResponseParser(ParseKeySetFromJson.class)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<String> listClients();\n\n   /**\n    * Gets the details of existing client.\n    * \n    * @param clientName The name of the client to get.\n    * @return The details of the given client.\n    */\n   @Named(\"client:get\")\n   @GET\n   @Path(\"/clients/{clientname}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   Client getClient(@PathParam(\"clientname\") String clientName);\n\n   /**\n    * Creates a new client.\n    * \n    * @param clientName The name of the new client\n    * @return The client with the generated private key. This key should be\n    *         stored so client can be properly authenticated .\n    */\n   @Named(\"client:create\")\n   @POST\n   @Path(\"/clients\")\n   @MapBinder(BindToJsonPayload.class)\n   Client createClient(@PayloadParam(\"name\") String clientName);\n\n   /**\n    * Creates a new client with custom options.\n    * \n    * @param clientName The name of the new client\n    * @param options The options to customize the client creation.\n    * @return The client with the generated private key. This key should be\n    *         stored so client can be properly authenticated .\n    */\n   @Named(\"client:create\")\n   @POST\n   @Path(\"/clients\")\n   @MapBinder(BindCreateClientOptionsToJsonPayload.class)\n   Client createClient(@PayloadParam(\"name\") String clientName, CreateClientOptions options);\n\n   /**\n    * Generates a new key-pair for this client, and return the new private key in\n    * the response body.\n    * \n    * @param clientName The name of the client.\n    * @return The details of the client with the new private key.\n    */\n   @Named(\"client:generatekey\")\n   @PUT\n   @Path(\"/clients/{clientname}\")\n   Client generateKeyForClient(\n         @PathParam(\"clientname\") @BinderParam(BindGenerateKeyForClientToJsonPayload.class) String clientName);\n\n   /**\n    * Deletes the given client.\n    * \n    * @param clientName The name of the client to delete.\n    * @return The deleted client.\n    */\n   @Named(\"client:delete\")\n   @DELETE\n   @Path(\"/clients/{clientname}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   Client deleteClient(@PathParam(\"clientname\") String clientName);\n\n   // Cookbooks\n\n   /**\n    * Lists the names of the existing cookbooks.\n    * \n    * @return The names of the exsisting cookbooks.\n    */\n   @Named(\"cookbook:list\")\n   @GET\n   @Path(\"/cookbooks\")\n   @ResponseParser(ParseCookbookNamesFromJson.class)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<String> listCookbooks();\n\n   /**\n    * Lists the cookbooks that are available in the given environment.\n    * \n    * @param environmentName The name of the environment to get the cookbooks\n    *        from.\n    * @return The definitions of the cookbooks (name, URL and versions) available in\n    *         the given environment.\n    */\n   @SinceApiVersion(\"0.10.0\")\n   @Named(\"cookbook:list\")\n   @GET\n   @ResponseParser(ParseCookbookDefinitionListFromJson.class)\n   @Path(\"/environments/{environmentname}/cookbooks\")\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<CookbookDefinition> listCookbooksInEnvironment(@PathParam(\"environmentname\") String environmentName);\n\n   /**\n    * Lists the cookbooks that are available in the given environment, limiting\n    * the number of versions returned for each cookbook.\n    * \n    * @param environmentName The name of the environment to get the cookbooks\n    *        from.\n    * @param numVersions The number of cookbook versions to include in the\n    *        response, where n is the number of cookbook versions.\n    * @return The definitions of the cookbooks (name, URL and versions) available in\n    *         the given environment.\n    */\n   @SinceApiVersion(\"0.10.0\")\n   @Named(\"cookbook:list\")\n   @GET\n   @ResponseParser(ParseCookbookDefinitionListFromJson.class)\n   @Path(\"/environments/{environmentname}/cookbooks?num_versions={numversions}\")\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<CookbookDefinition> listCookbooksInEnvironment(@PathParam(\"environmentname\") String environmentName,\n         @PathParam(\"numversions\") String numVersions);\n\n   /**\n    * Lists the available versions of the given cookbook.\n    * \n    * @param cookbookName The name of the cookbook.\n    * @return The available versions of the given cookbook.\n    */\n   @Named(\"cookbook:versions\")\n   @GET\n   @Path(\"/cookbooks/{cookbookname}\")\n   @ResponseParser(ParseCookbookVersionsFromJson.class)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<String> listVersionsOfCookbook(@PathParam(\"cookbookname\") String cookbookName);\n\n   /**\n    * Gets the details of the given cookbook, with the links to each resource\n    * such as recipe files, attributes, etc.\n    * \n    * @param cookbookName The name of the cookbook.\n    * @param version The version of the cookbook to get.\n    * @return The details of the given cookbook.\n    */\n   @Named(\"cookbook:get\")\n   @GET\n   @Path(\"/cookbooks/{cookbookname}/{version}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   CookbookVersion getCookbook(@PathParam(\"cookbookname\") String cookbookName, @PathParam(\"version\") String version);\n\n   /**\n    * Gets the definition of the cookbook in the given environment.\n    * \n    * @param environmentName The name of the environment.\n    * @param cookbookName The name of the cookbook.\n    * @return The definition of the cookbook (URL and versions) of the cookbook\n    *         in the given environment.\n    */\n   @SinceApiVersion(\"0.10.0\")\n   @Named(\"environment:cookbook\")\n   @GET\n   @ResponseParser(ParseCookbookDefinitionFromJson.class)\n   @Path(\"/environments/{environmentname}/cookbooks/{cookbookname}\")\n   CookbookDefinition getCookbookInEnvironment(@PathParam(\"environmentname\") String environmentName,\n         @PathParam(\"cookbookname\") String cookbookName);\n\n   /**\n    * Gets the definition of the cookbook in the given environment.\n    * \n    * @param environmentName The name of the environment.\n    * @param cookbookName The name of the cookbook.\n    * @param numVersions The number of cookbook versions to include in the\n    *        response, where n is the number of cookbook versions.\n    * @return The definition of the cookbook (URL and versions) of the cookbook\n    *         in the given environment.\n    */\n   @SinceApiVersion(\"0.10.0\")\n   @Named(\"environment:cookbook\")\n   @GET\n   @ResponseParser(ParseCookbookDefinitionFromJson.class)\n   @Path(\"/environments/{environmentname}/cookbooks/{cookbookname}?num_versions={numversions}\")\n   CookbookDefinition getCookbookInEnvironment(@PathParam(\"environmentname\") String environmentName,\n         @PathParam(\"cookbookname\") String cookbookName, @PathParam(\"numversions\") String numVersions);\n\n   /**\n    * Lists the names of the recipes in the given environment.\n    * \n    * @param environmentName The name of the environment.\n    * @return The names of the recipes in the given environment.\n    */\n   @SinceApiVersion(\"0.10.0\")\n   @Named(\"environment:recipelist\")\n   @GET\n   @Path(\"/environments/{environmentname}/recipes\")\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<String> listRecipesInEnvironment(@PathParam(\"environmentname\") String environmentName);\n\n   /**\n    * Creates or updates the given cookbook.\n    * \n    * @param cookbookName The name of the cookbook to create or update.\n    * @param version The version of the cookbook to create or update.\n    * @param cookbook The contents of the cookbook to create or update.\n    * @return The details of the created or updated cookbook.\n    */\n   @Named(\"cookbook:update\")\n   @PUT\n   @Path(\"/cookbooks/{cookbookname}/{version}\")\n   CookbookVersion updateCookbook(@PathParam(\"cookbookname\") String cookbookName, @PathParam(\"version\") String version,\n         @BinderParam(BindToJsonPayload.class) CookbookVersion cookbook);\n\n   /**\n    * Deletes the given cookbook.\n    * \n    * @param cookbookName The name of the cookbook to delete.\n    * @param version The version of the cookbook to delete.\n    * @return The details of the deleted cookbook.\n    */\n   @Named(\"cookbook:delete\")\n   @DELETE\n   @Path(\"/cookbooks/{cookbookname}/{version}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   CookbookVersion deleteCookbook(@PathParam(\"cookbookname\") String cookbookName, @PathParam(\"version\") String version);\n\n   // Data bags\n\n   /**\n    * Lists the names of the existing data bags.\n    * \n    * @return The names of the existing data bags.\n    */\n   @Named(\"databag:list\")\n   @GET\n   @Path(\"/data\")\n   @ResponseParser(ParseKeySetFromJson.class)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<String> listDatabags();\n\n   /**\n    * Creates a new data bag.\n    * \n    * @param databagName The name for the new data bag.\n    */\n   @Named(\"databag:create\")\n   @POST\n   @Path(\"/data\")\n   void createDatabag(@WrapWith(\"name\") String databagName);\n\n   /**\n    * Deletes a data bag, including its items.\n    * \n    * @param databagName The name of the data bag to delete.\n    */\n   @Named(\"databag:delete\")\n   @DELETE\n   @Path(\"/data/{name}\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void deleteDatabag(@PathParam(\"name\") String databagName);\n\n   /**\n    * Lists the names of the items in a data bag.\n    * \n    * @param databagName The name of the data bag.\n    * @return The names of the items in the given data bag.\n    */\n   @Named(\"databag:listitems\")\n   @GET\n   @Path(\"/data/{name}\")\n   @ResponseParser(ParseKeySetFromJson.class)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<String> listDatabagItems(@PathParam(\"name\") String databagName);\n\n   /**\n    * Gets an item in a data bag.\n    * \n    * @param databagName The name of the data bag.\n    * @param databagItemId The identifier of the item to get.\n    * @return The details of the item in the given data bag.\n    */\n   @Named(\"databag:getitem\")\n   @GET\n   @Path(\"/data/{databagName}/{databagItemId}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   DatabagItem getDatabagItem(@PathParam(\"databagName\") String databagName,\n         @PathParam(\"databagItemId\") String databagItemId);\n\n   /**\n    * Adds an item in a data bag.\n    * \n    * @param databagName The name of the data bag.\n    * @param databagItem item to add to the data bag.\n    * @return The item just added to the data bag.\n    */\n   @Named(\"databag:createitem\")\n   @POST\n   @Path(\"/data/{databagName}\")\n   DatabagItem createDatabagItem(@PathParam(\"databagName\") String databagName,\n         @BinderParam(BindToJsonPayload.class) DatabagItem databagItem);\n\n   /**\n    * Updates an item in a data bag.\n    * \n    * @param databagName The name of the data bag.\n    * @param item The new contents for the item in the data bag.\n    * @return The details for the updated item in the data bag.\n    */\n   @Named(\"databag:updateitem\")\n   @PUT\n   @Path(\"/data/{databagName}/{databagItemId}\")\n   DatabagItem updateDatabagItem(\n         @PathParam(\"databagName\") String databagName,\n         @PathParam(\"databagItemId\") @ParamParser(DatabagItemId.class) @BinderParam(BindToJsonPayload.class) DatabagItem item);\n\n   /**\n    * Deletes an item from a data bag.\n    * \n    * @param databagName The name of the data bag.\n    * @param databagItemId The identifier of the item to delete.\n    * @return The item deleted from the data bag.\n    */\n   @Named(\"databag:deleteitem\")\n   @DELETE\n   @Path(\"/data/{databagName}/{databagItemId}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @SelectJson(\"raw_data\")\n   DatabagItem deleteDatabagItem(@PathParam(\"databagName\") String databagName,\n         @PathParam(\"databagItemId\") String databagItemId);\n\n   // Environments\n\n   /**\n    * Lists the names of the existing environments.\n    * \n    * @return The names of the existing environments.\n    */\n   @SinceApiVersion(\"0.10.0\")\n   @Named(\"environment:list\")\n   @GET\n   @Path(\"/environments\")\n   @ResponseParser(ParseKeySetFromJson.class)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<String> listEnvironments();\n\n   /**\n    * Gets the details of an existing environment.\n    * \n    * @param environmentName The name of the environment to get.\n    * @return The details of the given environment.\n    */\n   @SinceApiVersion(\"0.10.0\")\n   @Named(\"environment:get\")\n   @GET\n   @Path(\"/environments/{environmentname}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   Environment getEnvironment(@PathParam(\"environmentname\") String environmentName);\n\n   /**\n    * Creates a new environment.\n    * \n    * @param environment The environment to create.\n    */\n   @SinceApiVersion(\"0.10.0\")\n   @Named(\"environment:create\")\n   @POST\n   @Path(\"/environments\")\n   void createEnvironment(@BinderParam(BindToJsonPayload.class) Environment environment);\n\n   /**\n    * Updates the given environment.\n    * \n    * @param environment The new details for the environment.\n    * @return The details of the updated environment.\n    */\n   @SinceApiVersion(\"0.10.0\")\n   @Named(\"environment:update\")\n   @PUT\n   @Path(\"/environments/{environmentname}\")\n   Environment updateEnvironment(\n         @PathParam(\"environmentname\") @ParamParser(EnvironmentName.class) @BinderParam(BindToJsonPayload.class) Environment environment);\n\n   /**\n    * Deletes the given environment.\n    * \n    * @param environmentName The name of the environment to delete.\n    * @return The details of the deleted environment.\n    */\n   @SinceApiVersion(\"0.10.0\")\n   @Named(\"environment:delete\")\n   @DELETE\n   @Path(\"/environments/{environmentname}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   Environment deleteEnvironment(@PathParam(\"environmentname\") String environmentName);\n\n   // Nodes\n\n   /**\n    * Lists the names of the existing nodes.\n    * \n    * @return The names of the existing nodes.\n    */\n   @Named(\"node:list\")\n   @GET\n   @Path(\"/nodes\")\n   @ResponseParser(ParseKeySetFromJson.class)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<String> listNodes();\n\n   /**\n    * Lists the names of the nodes in the given environment.\n    * \n    * @param environmentName The name of the environment.\n    * @return The names of the existing nodes in the given environment.\n    */\n   @SinceApiVersion(\"0.10.0\")\n   @Named(\"environment:nodelist\")\n   @GET\n   @Path(\"/environments/{environmentname}/nodes\")\n   @ResponseParser(ParseKeySetFromJson.class)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<String> listNodesInEnvironment(@PathParam(\"environmentname\") String environmentName);\n\n   /**\n    * Gets the details of the given node.\n    * \n    * @param nodeName The name of the node to get.\n    * @return The details of the given node.\n    */\n   @Named(\"node:get\")\n   @GET\n   @Path(\"/nodes/{nodename}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   Node getNode(@PathParam(\"nodename\") String nodeName);\n\n   /**\n    * Creates a new node.\n    * \n    * @param node The details of the node to create.\n    */\n   @Named(\"node:create\")\n   @POST\n   @Path(\"/nodes\")\n   void createNode(@BinderParam(BindToJsonPayload.class) Node node);\n\n   /**\n    * Updates an existing node.\n    * \n    * @param node The new details for the node.\n    * @return The details of the updated node.\n    */\n   @Named(\"node:update\")\n   @PUT\n   @Path(\"/nodes/{nodename}\")\n   Node updateNode(@PathParam(\"nodename\") @ParamParser(NodeName.class) @BinderParam(BindToJsonPayload.class) Node node);\n\n   /**\n    * Deletes the given node.\n    * \n    * @param nodeName The name of the node to delete.\n    * @return The details of the deleted node.\n    */\n   @Named(\"node:delete\")\n   @DELETE\n   @Path(\"/nodes/{nodename}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   Node deleteNode(@PathParam(\"nodename\") String nodeName);\n\n   // Roles\n\n   /**\n    * Lists the names of the existing roles.\n    * \n    * @return The names of the existing roles.\n    */\n   @Named(\"role:list\")\n   @GET\n   @Path(\"/roles\")\n   @ResponseParser(ParseKeySetFromJson.class)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<String> listRoles();\n\n   /**\n    * Gets the details of the given role.\n    * \n    * @param roleName The name of the role to get.\n    * @return The details of the given role.\n    */\n   @Named(\"role:get\")\n   @GET\n   @Path(\"/roles/{rolename}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   Role getRole(@PathParam(\"rolename\") String roleName);\n\n   /**\n    * Creates a new role.\n    * \n    * @param role The details for the new role.\n    */\n   @Named(\"role:create\")\n   @POST\n   @Path(\"/roles\")\n   void createRole(@BinderParam(BindToJsonPayload.class) Role role);\n\n   /**\n    * Updates the given role.\n    * \n    * @param role The new details for the role.\n    * @return The details of the updated role.\n    */\n   @Named(\"role:update\")\n   @PUT\n   @Path(\"/roles/{rolename}\")\n   Role updateRole(@PathParam(\"rolename\") @ParamParser(RoleName.class) @BinderParam(BindToJsonPayload.class) Role role);\n\n   /**\n    * Deletes the given role.\n    * \n    * @param roleName The name of the role to delete.\n    * @return The details of the deleted role.\n    */\n   @Named(\"role:delete\")\n   @DELETE\n   @Path(\"/roles/{rolename}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   Role deleteRole(@PathParam(\"rolename\") String roleName);\n\n   // Sandboxes\n\n   /**\n    * Creates a new sandbox.\n    * <p>\n    * It accepts a list of checksums as input and returns the URLs against which\n    * to PUT files that need to be uploaded.\n    * \n    * @param md5s The raw md5 sums. Uses {@code Bytes.asList()} and\n    *        {@code Bytes.toByteArray()} as necessary\n    * @return The upload sandbox with the URLs against which to PUT files that\n    *         need to be uploaded.\n    */\n   @Named(\"sandbox:upload\")\n   @POST\n   @Path(\"/sandboxes\")\n   UploadSandbox createUploadSandboxForChecksums(@BinderParam(BindChecksumsToJsonPayload.class) Set<List<Byte>> md5s);\n\n   /**\n    * Uploads the given content to the sandbox at the given URI.\n    * <p>\n    * The URI must be obtained, after uploading a sandbox, from the\n    * {@link UploadSandbox#getUri()}.\n    * \n    * @param location The URI where the upload must be performed.\n    * @param content The contents to upload.\n    */\n   @Named(\"content:upload\")\n   @PUT\n   @Produces(\"application/x-binary\")\n   void uploadContent(@EndpointParam URI location, Payload content);\n\n   /**\n    * Gets the contents of the given resource.\n    * \n    * @param resource The resource to get.\n    * @return An input stream for the content of the requested resource.\n    */\n   @Named(\"content:get\")\n   @GET\n   @Fallback(NullOnNotFoundOr404.class)\n   @SkipEncoding({ '+', ' ', '/', '=', ':', ';' })\n   InputStream getResourceContents(@EndpointParam(parser = UriForResource.class) Resource resource);\n\n   /**\n    * Confirms if the sandbox is completed or not.\n    * <p>\n    * This method should be used after uploading contents to the sandbox.\n    * \n    * @param id The id of the sandbox to commit.\n    * @param isCompleted Flag to set if the sandbox is completed or not.\n    * @return The details of the sandbox.\n    */\n   @Named(\"sandbox:commit\")\n   @PUT\n   @Path(\"/sandboxes/{id}\")\n   Sandbox commitSandbox(@PathParam(\"id\") String id, @WrapWith(\"is_completed\") boolean isCompleted);\n\n   // Search\n\n   /**\n    * Lists the names of the available search indexes.\n    * <p>\n    * By default, the \"role\", \"node\" and \"api\" indexes will always be available.\n    * <p>\n    * Note that the search indexes may lag behind the most current data by at\n    * least 10 seconds at any given time - so if you need to write data and\n    * immediately query it, you likely need to produce an artificial delay (or\n    * simply retry until the data is available).\n    * \n    * @return The names of the available search indexes.\n    */\n   @Named(\"search:indexes\")\n   @GET\n   @Path(\"/search\")\n   @ResponseParser(ParseKeySetFromJson.class)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<String> listSearchIndexes();\n\n   /**\n    * Searches all clients.\n    * <p>\n    * Note that without any request parameters this will return all of the data\n    * within the index.\n    * \n    * @return The response contains the total number of rows that matched the\n    *         request, the position this result set returns (useful for paging)\n    *         and the rows themselves.\n    */\n   @Named(\"search:clients\")\n   @GET\n   @Path(\"/search/client\")\n   @ResponseParser(ParseSearchClientsFromJson.class)\n   SearchResult<? extends Client> searchClients();\n\n   /**\n    * Searches all clients that match the given options.\n    * \n    * @return The response contains the total number of rows that matched the\n    *         request, the position this result set returns (useful for paging)\n    *         and the rows themselves.\n    */\n   @Named(\"search:clients\")\n   @GET\n   @Path(\"/search/client\")\n   @ResponseParser(ParseSearchClientsFromJson.class)\n   SearchResult<? extends Client> searchClients(SearchOptions options);\n\n   /**\n    * Searches all items in a data bag.\n    * <p>\n    * Note that without any request parameters this will return all of the data\n    * within the index.\n    * \n    * @return The response contains the total number of rows that matched the\n    *         request, the position this result set returns (useful for paging)\n    *         and the rows themselves.\n    */\n   @Named(\"search:databag\")\n   @GET\n   @Path(\"/search/{databagName}\")\n   @ResponseParser(ParseSearchDatabagFromJson.class)\n   SearchResult<? extends DatabagItem> searchDatabagItems(@PathParam(\"databagName\") String databagName);\n\n   /**\n    * Searches all items in a data bag that match the given options.\n    * \n    * @return The response contains the total number of rows that matched the\n    *         request, the position this result set returns (useful for paging)\n    *         and the rows themselves.\n    */\n   @Named(\"search:databag\")\n   @GET\n   @Path(\"/search/{databagName}\")\n   @ResponseParser(ParseSearchDatabagFromJson.class)\n   SearchResult<? extends DatabagItem> searchDatabagItems(@PathParam(\"databagName\") String databagName,\n         SearchOptions options);\n\n   /**\n    * Searches all environments.\n    * <p>\n    * Note that without any request parameters this will return all of the data\n    * within the index.\n    * \n    * @return The response contains the total number of rows that matched the\n    *         request, the position this result set returns (useful for paging)\n    *         and the rows themselves.\n    */\n   @SinceApiVersion(\"0.10.0\")\n   @Named(\"search:environments\")\n   @GET\n   @Path(\"/search/environment\")\n   @ResponseParser(ParseSearchEnvironmentsFromJson.class)\n   SearchResult<? extends Environment> searchEnvironments();\n\n   /**\n    * Searches all environments that match the given options.\n    * \n    * @return The response contains the total number of rows that matched the\n    *         request, the position this result set returns (useful for paging)\n    *         and the rows themselves.\n    */\n   @SinceApiVersion(\"0.10.0\")\n   @Named(\"search:environments\")\n   @GET\n   @Path(\"/search/environment\")\n   @ResponseParser(ParseSearchEnvironmentsFromJson.class)\n   SearchResult<? extends Environment> searchEnvironments(SearchOptions options);\n\n   /**\n    * Searches all nodes.\n    * <p>\n    * Note that without any request parameters this will return all of the data\n    * within the index.\n    * \n    * @return The response contains the total number of rows that matched the\n    *         request, the position this result set returns (useful for paging)\n    *         and the rows themselves.\n    */\n   @Named(\"search:nodes\")\n   @GET\n   @Path(\"/search/node\")\n   @ResponseParser(ParseSearchNodesFromJson.class)\n   SearchResult<? extends Node> searchNodes();\n\n   /**\n    * Searches all nodes that match the given options.\n    * \n    * @return The response contains the total number of rows that matched the\n    *         request, the position this result set returns (useful for paging)\n    *         and the rows themselves.\n    */\n   @Named(\"search:nodes\")\n   @GET\n   @Path(\"/search/node\")\n   @ResponseParser(ParseSearchNodesFromJson.class)\n   SearchResult<? extends Node> searchNodes(SearchOptions options);\n\n   /**\n    * Searches all roles.\n    * <p>\n    * Note that without any request parameters this will return all of the data\n    * within the index.\n    * \n    * @return The response contains the total number of rows that matched the\n    *         request, the position this result set returns (useful for paging)\n    *         and the rows themselves.\n    */\n   @Named(\"search:roles\")\n   @GET\n   @Path(\"/search/role\")\n   @ResponseParser(ParseSearchRolesFromJson.class)\n   SearchResult<? extends Role> searchRoles();\n\n   /**\n    * Searches all roles that match the given options.\n    * \n    * @return The response contains the total number of rows that matched the\n    *         request, the position this result set returns (useful for paging)\n    *         and the rows themselves.\n    */\n   @Named(\"search:roles\")\n   @GET\n   @Path(\"/search/role\")\n   @ResponseParser(ParseSearchRolesFromJson.class)\n   SearchResult<? extends Role> searchRoles(SearchOptions options);\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/ChefApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef;\n\nimport static java.util.concurrent.TimeUnit.MINUTES;\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL;\nimport static org.jclouds.Constants.PROPERTY_TIMEOUTS_PREFIX;\nimport static org.jclouds.chef.config.ChefProperties.CHEF_BOOTSTRAP_DATABAG;\nimport static org.jclouds.chef.config.ChefProperties.CHEF_UPDATE_GEMS;\nimport static org.jclouds.chef.config.ChefProperties.CHEF_UPDATE_GEM_SYSTEM;\nimport static org.jclouds.chef.config.ChefProperties.CHEF_USE_OMNIBUS;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.chef.config.ChefBootstrapModule;\nimport org.jclouds.chef.config.ChefHttpApiModule;\nimport org.jclouds.chef.config.ChefParserModule;\nimport org.jclouds.ohai.config.JMXOhaiModule;\nimport org.jclouds.rest.internal.BaseHttpApiMetadata;\n\nimport com.google.auto.service.AutoService;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n/**\n * Implementation of {@link ApiMetadata} for Chef.\n */\n@AutoService(ApiMetadata.class)\npublic class ChefApiMetadata extends BaseHttpApiMetadata<ChefApi> {\n\n   /**\n    * The default Chef Server API version to use.\n    */\n   public static final String DEFAULT_API_VERSION = \"12.0.2\";\n\n   @Override\n   public Builder toBuilder() {\n      return new Builder().fromApiMetadata(this);\n   }\n\n   public ChefApiMetadata() {\n      this(new Builder());\n   }\n\n   protected ChefApiMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = BaseHttpApiMetadata.defaultProperties();\n      properties.setProperty(PROPERTY_TIMEOUTS_PREFIX + \"default\", SECONDS.toMillis(30) + \"\");\n      properties.setProperty(PROPERTY_TIMEOUTS_PREFIX + \"ChefApi.updateCookbook\", MINUTES.toMillis(10) + \"\");\n      properties.setProperty(PROPERTY_TIMEOUTS_PREFIX + \"ChefApi.createClient\", MINUTES.toMillis(2) + \"\");\n      properties.setProperty(PROPERTY_TIMEOUTS_PREFIX + \"ChefApi.generateKeyForClient\", MINUTES.toMillis(2) + \"\");\n      properties.setProperty(PROPERTY_TIMEOUTS_PREFIX + \"ChefApi.createNode\", MINUTES.toMillis(2) + \"\");\n      properties.setProperty(PROPERTY_TIMEOUTS_PREFIX + \"ChefApi.updateNode\", MINUTES.toMillis(10) + \"\");\n      properties.setProperty(PROPERTY_TIMEOUTS_PREFIX + \"ChefApi.createRole\", MINUTES.toMillis(2) + \"\");\n      properties.setProperty(PROPERTY_TIMEOUTS_PREFIX + \"ChefApi.updateRole\", MINUTES.toMillis(10) + \"\");\n      properties.setProperty(PROPERTY_TIMEOUTS_PREFIX + \"ChefApi.createEnvironment\", MINUTES.toMillis(2) + \"\");\n      properties.setProperty(PROPERTY_SESSION_INTERVAL, \"1\");\n      properties.setProperty(CHEF_BOOTSTRAP_DATABAG, \"bootstrap\");\n      properties.setProperty(CHEF_UPDATE_GEM_SYSTEM, \"false\");\n      properties.setProperty(CHEF_UPDATE_GEMS, \"false\");\n      properties.setProperty(CHEF_USE_OMNIBUS, \"true\");\n      return properties;\n   }\n\n   public static class Builder extends BaseHttpApiMetadata.Builder<ChefApi, Builder> {\n\n      protected Builder() {\n         id(\"chef\")\n               .name(\"Chef Api\")\n               .identityName(\"User\")\n               .credentialName(\"Certificate\")\n               .version(DEFAULT_API_VERSION)\n               .documentation(URI.create(\"https://docs.chef.io/api_chef_server.html\"))\n               .defaultEndpoint(\"http://localhost:4000\")\n               .defaultProperties(ChefApiMetadata.defaultProperties())\n               .defaultModules(\n                     ImmutableSet.<Class<? extends Module>> of(ChefHttpApiModule.class, ChefParserModule.class,\n                           ChefBootstrapModule.class, JMXOhaiModule.class));\n      }\n\n      @Override\n      public ChefApiMetadata build() {\n         return new ChefApiMetadata(this);\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/ChefService.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.concurrent.ExecutorService;\n\nimport org.jclouds.chef.config.ChefProperties;\nimport org.jclouds.chef.domain.BootstrapConfig;\nimport org.jclouds.chef.domain.Client;\nimport org.jclouds.chef.domain.CookbookVersion;\nimport org.jclouds.chef.domain.Environment;\nimport org.jclouds.chef.domain.Node;\nimport org.jclouds.chef.internal.BaseChefService;\nimport org.jclouds.chef.util.ChefUtils;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.ohai.config.OhaiModule;\nimport org.jclouds.rest.annotations.SinceApiVersion;\nimport org.jclouds.scriptbuilder.domain.Statement;\n\nimport com.google.inject.ImplementedBy;\n\n/**\n * Provides high level Chef operations.\n */\n@ImplementedBy(BaseChefService.class)\npublic interface ChefService {\n\n   // Crypto\n\n   /**\n    * Encrypts the given input stream.\n    *\n    * @param input The input stream to encrypt.\n    * @return The encrypted bytes for the given input stream.\n    * @throws IOException If there is an error reading from the input stream.\n    */\n   byte[] encrypt(InputStream input) throws IOException;\n\n   /**\n    * Decrypts the given input stream.\n    *\n    * @param input The input stream to decrypt.\n    * @return The decrypted bytes for the given input stream.\n    * @throws IOException If there is an error reading from the input stream.\n    */\n   byte[] decrypt(InputStream input) throws IOException;\n\n   // Bootstrap\n\n   /**\n    * Creates all steps necessary to bootstrap the node.\n    *\n    * @param group corresponds to a configured\n    *              {@link ChefProperties#CHEF_BOOTSTRAP_DATABAG} data bag where\n    *              run_list and other information are stored.\n    * @return The script used to bootstrap the node.\n    */\n   Statement createBootstrapScriptForGroup(String group);\n\n   /**\n    * Creates all steps necessary to bootstrap the node.\n    *\n    * @param group corresponds to a configured\n    *              {@link ChefProperties#CHEF_BOOTSTRAP_DATABAG} data bag where\n    *              run_list and other information are stored.\n    * @param nodeName The name of the node to create.\n    * @return The script used to bootstrap the node.\n    */\n   Statement createBootstrapScriptForGroup(String group, @Nullable String nodeName);\n\n   /**\n    * Configures how the nodes of a certain group will be bootstrapped\n    *\n    * @param group           The group where the given bootstrap configuration will be\n    *                        applied.\n    * @param bootstrapConfig The configuration to be applied to the nodes in the\n    *                        group.\n    */\n   void updateBootstrapConfigForGroup(String group, BootstrapConfig bootstrapConfig);\n\n   /**\n    * Gets the bootstrap configuration for a given group.\n    *\n    * @param group The name of the group.\n    * @return The bootstrap configuration for the given group.\n    */\n   BootstrapConfig getBootstrapConfigForGroup(String group);\n\n   // Nodes / Clients\n\n   /**\n    * Creates a new node and populates the automatic attributes.\n    *\n    * @param nodeName The name of the node to create.\n    * @param runList  The run list for the created node.\n    * @return The created node with the automatic attributes populated.\n    * @see OhaiModule\n    * @see ChefUtils#ohaiAutomaticAttributeBinder(com.google.inject.Binder)\n    */\n   Node createNodeAndPopulateAutomaticAttributes(String nodeName, Iterable<String> runList);\n\n   /**\n    * Updates and populate the automatic attributes of the given node.\n    *\n    * @param nodeName The node to update.\n    */\n   void updateAutomaticAttributesOnNode(String nodeName);\n\n   /**\n    * Removes the nodes and clients that have been inactive for a given amount of\n    * time.\n    *\n    * @param prefix       The prefix for the nodes and clients to delete.\n    * @param secondsStale The seconds of inactivity to consider a node and\n    *                     client obsolete.\n    */\n   void cleanupStaleNodesAndClients(String prefix, int secondsStale);\n\n   /**\n    * Deletes the given nodes.\n    *\n    * @param names The names of the nodes to delete.\n    */\n   void deleteAllNodesInList(Iterable<String> names);\n\n   /**\n    * Deletes the given clients.\n    *\n    * @param names The names of the client to delete.\n    */\n   void deleteAllClientsInList(Iterable<String> names);\n\n   /**\n    * Lists the details of all existing nodes.\n    *\n    * @return The details of all existing nodes.\n    */\n   Iterable<? extends Node> listNodes();\n\n   /**\n    * Lists the details of all existing nodes, executing concurrently using the executorService.\n    *\n    * @return The details of all existing nodes.\n    */\n   Iterable<? extends Node> listNodes(ExecutorService executorService);\n\n   /**\n    * Lists the details of all existing nodes in the given environment.\n    *\n    * @param environmentName The name fo the environment.\n    * @return The details of all existing nodes in the given environment.\n    */\n   @SinceApiVersion(\"0.10.0\")\n   Iterable<? extends Node> listNodesInEnvironment(String environmentName);\n\n   /**\n    * Lists the details of all existing nodes in the given environment, using the ExecutorService to paralleling the execution.\n    *\n    * @param executorService The thread pool used in this operation\n    * @param environmentName The name fo the environment.\n    * @return The details of all existing nodes in the given environment.\n    */\n   @SinceApiVersion(\"0.10.0\")\n   Iterable<? extends Node> listNodesInEnvironment(String environmentName, ExecutorService executorService);\n\n   /**\n    * Lists the details of all existing clients.\n    *\n    * @return The details of all existing clients.\n    */\n   Iterable<? extends Client> listClients();\n\n   /**\n    * Lists the details of all existing clients, but executing concurrently using the threads available in the ExecutorService.\n    *\n    * @return The details of all existing clients.\n    */\n   Iterable<? extends Client> listClients(ExecutorService executorService);\n\n   /**\n    * Lists the details of all existing cookbooks.\n    *\n    * @return The details of all existing cookbooks.\n    */\n   Iterable<? extends CookbookVersion> listCookbookVersions();\n\n   /**\n    * Lists the details of all existing cookbooks. This method is executed concurrently, using the threads available in the ExecutorService.\n    *\n    * @return The details of all existing cookbooks.\n    */\n   Iterable<? extends CookbookVersion> listCookbookVersions(ExecutorService executorService);\n\n   /**\n    * Lists the details of all existing cookbooks in an environment.\n    *\n    * @param environmentName The environment name.\n    * @return The details of all existing cookbooks in an environment.\n    */\n   Iterable<? extends CookbookVersion> listCookbookVersionsInEnvironment(String environmentName);\n\n   /**\n    * Lists the details of all existing cookbooks in an environment.\n\n    * @param executorService The thread pool to do the concurrent execution.\n    * @param environmentName The environment name.\n    * @return The details of all existing cookbooks in an environment.\n    */\n   Iterable<? extends CookbookVersion> listCookbookVersionsInEnvironment(String environmentName, ExecutorService executorService);\n\n   /**\n    * Lists the details of all existing cookbooks in an environment\n    * limiting number of versions.\n    *\n    * @param environmentName The environment name.\n    * @param numVersions     The number of cookbook versions to include.\n    *                        Use 'all' to return all cookbook versions.\n    * @return The details of all existing cookbooks in environment.\n    */\n   Iterable<? extends CookbookVersion> listCookbookVersionsInEnvironment(String environmentName, String numVersions);\n\n   /**\n    * Lists the details of all existing cookbooks in an environment\n    * limiting number of versions.\n    *\n    * @param executorService The executorService used to do this operation concurrently.\n    * @param environmentName The environment name.\n    * @param numVersions     The number of cookbook versions to include.\n    *                        Use 'all' to return all cookbook versions.\n    * @return The details of all existing cookbooks in environment.\n    */\n   Iterable<? extends CookbookVersion> listCookbookVersionsInEnvironment(String environmentName, String numVersions, ExecutorService executorService);\n\n   /**\n    * Lists the details of all existing environments.\n    *\n    * @return The details of all existing environments.\n    */\n   @SinceApiVersion(\"0.10.0\")\n   Iterable<? extends Environment> listEnvironments();\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/binders/BindChecksumsToJsonPayload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.io.BaseEncoding.base16;\nimport static com.google.common.primitives.Bytes.toArray;\n\nimport java.util.List;\nimport java.util.Set;\n\nimport jakarta.inject.Singleton;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.binders.BindToStringPayload;\n\n@Singleton\npublic class BindChecksumsToJsonPayload extends BindToStringPayload {\n\n   @SuppressWarnings(\"unchecked\")\n   public HttpRequest bindToRequest(HttpRequest request, Object input) {\n      checkArgument(checkNotNull(input, \"input\") instanceof Set, \"this binder is only valid for Set!\");\n\n      Set<List<Byte>> md5s = (Set<List<Byte>>) input;\n\n      StringBuilder builder = new StringBuilder();\n      builder.append(\"{\\\"checksums\\\":{\");\n\n      for (List<Byte> md5 : md5s)\n         builder.append(String.format(\"\\\"%s\\\":null,\", base16().lowerCase().encode(toArray(md5))));\n      builder.deleteCharAt(builder.length() - 1);\n      builder.append(\"}}\");\n      super.bindToRequest(request, builder.toString());\n      request.getPayload().getContentMetadata().setContentType(MediaType.APPLICATION_JSON);\n      return request;\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/binders/BindCreateClientOptionsToJsonPayload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.chef.options.CreateClientOptions;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.json.Json;\nimport org.jclouds.rest.binders.BindToJsonPayload;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\n\nimport com.google.common.base.Predicates;\nimport com.google.common.collect.Iterables;\n\n/**\n * Bind the parameters of a {@link CreateClientOptions} to the payload.\n */\npublic class BindCreateClientOptionsToJsonPayload extends BindToJsonPayload {\n   @Inject\n   public BindCreateClientOptionsToJsonPayload(Json jsonBinder) {\n      super(jsonBinder);\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      checkArgument(checkNotNull(request, \"request\") instanceof GeneratedHttpRequest,\n            \"this binder is only valid for GeneratedHttpRequests\");\n      GeneratedHttpRequest gRequest = (GeneratedHttpRequest) request;\n      checkState(gRequest.getInvocation().getArgs() != null, \"args should be initialized at this point\");\n\n      String name = checkNotNull(postParams.remove(\"name\"), \"name\").toString();\n      CreateClientOptions options = (CreateClientOptions) Iterables.find(gRequest.getInvocation().getArgs(),\n            Predicates.instanceOf(CreateClientOptions.class));\n\n      return bindToRequest(request, new CreateClientParams(name, options));\n   }\n\n   @SuppressWarnings(\"unused\")\n   private static class CreateClientParams {\n      private String name;\n\n      private boolean admin;\n\n      public CreateClientParams(String name, CreateClientOptions options) {\n         this.name = name;\n         this.admin = options.isAdmin();\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/binders/BindGenerateKeyForClientToJsonPayload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.binders;\n\nimport jakarta.inject.Singleton;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.binders.BindToStringPayload;\n\n@Singleton\npublic class BindGenerateKeyForClientToJsonPayload extends BindToStringPayload {\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object payload) {\n      super.bindToRequest(request, String.format(\"{\\\"name\\\":\\\"%s\\\", \\\"private_key\\\": true}\", payload));\n      request.getPayload().getContentMetadata().setContentType(MediaType.APPLICATION_JSON);\n      return request;\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/binders/BindGroupToUpdateRequestJsonPayload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.chef.domain.Group;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.json.Json;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\n/**\n * Binds a group to the payload expected for the Put method in the Enterprise Chef\n * Api.\n */\n@Singleton\npublic class BindGroupToUpdateRequestJsonPayload extends BindToJsonPayload {\n\n   @Inject\n   public BindGroupToUpdateRequestJsonPayload(Json jsonBinder) {\n      super(jsonBinder);\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object payload) {\n      checkArgument(checkNotNull(payload, \"payload\") instanceof Group, \"this binder is only valid for Group objects\");\n      GroupUpdateRequest updateGroup = new GroupUpdateRequest((Group) payload);\n      return super.bindToRequest(request, updateGroup);\n   }\n\n   @SuppressWarnings(\"unused\")\n   private static class GroupUpdateRequest {\n      private String name;\n      private String groupname;\n      private String orgname;\n      private ActorConfiguration actors;\n\n      public GroupUpdateRequest(Group group) {\n         this.name = group.getName();\n         this.groupname = group.getGroupname();\n         this.orgname = group.getOrgname();\n         this.actors = new ActorConfiguration(group);\n      }\n   }\n\n   @SuppressWarnings(\"unused\")\n   private static class ActorConfiguration {\n      private Set<String> clients;\n      private Set<String> groups;\n      private Set<String> users;\n\n      public ActorConfiguration(Group group) {\n         this.clients = group.getClients();\n         this.groups = group.getGroups();\n         this.users = group.getUsers();\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/binders/DatabagItemId.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.binders;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.chef.domain.DatabagItem;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class DatabagItemId implements Function<Object, String> {\n\n   public String apply(Object from) {\n      return ((DatabagItem) from).getId();\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/binders/EnvironmentName.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.binders;\n\nimport com.google.common.base.Function;\nimport org.jclouds.chef.domain.Environment;\n\nimport jakarta.inject.Singleton;\n\n@Singleton\npublic class EnvironmentName implements Function<Object, String> {\n\n   @Override\n   public String apply(Object input) {\n      return ((Environment) input).getName();\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/binders/GroupName.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.binders;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.chef.domain.Group;\n\nimport com.google.common.base.Function;\n\n/**\n * Gets the name of a group.\n */\n@Singleton\npublic class GroupName implements Function<Object, String> {\n\n   @Override\n   public String apply(Object from) {\n      return ((Group) checkNotNull(from, \"from\")).getGroupname();\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/binders/NodeName.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.binders;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.chef.domain.Node;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class NodeName implements Function<Object, String> {\n\n   public String apply(Object from) {\n      return ((Node) from).getName();\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/binders/RoleName.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.binders;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.chef.domain.Role;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class RoleName implements Function<Object, String> {\n\n   public String apply(Object from) {\n      return ((Role) from).getName();\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/config/ChefBootstrapModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.config;\n\nimport static org.jclouds.chef.config.ChefProperties.CHEF_GEM_SYSTEM_VERSION;\nimport static org.jclouds.chef.config.ChefProperties.CHEF_UPDATE_GEMS;\nimport static org.jclouds.chef.config.ChefProperties.CHEF_UPDATE_GEM_SYSTEM;\nimport static org.jclouds.chef.config.ChefProperties.CHEF_USE_OMNIBUS;\nimport static org.jclouds.chef.config.ChefProperties.CHEF_VERSION;\n\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.scriptbuilder.domain.Statement;\nimport org.jclouds.scriptbuilder.domain.StatementList;\nimport org.jclouds.scriptbuilder.statements.chef.InstallChefGems;\nimport org.jclouds.scriptbuilder.statements.chef.InstallChefUsingOmnibus;\nimport org.jclouds.scriptbuilder.statements.ruby.InstallRuby;\nimport org.jclouds.scriptbuilder.statements.ruby.InstallRubyGems;\n\nimport com.google.common.base.Optional;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Inject;\nimport com.google.inject.Provides;\n\n/**\n * Provides bootstrap configuration for nodes.\n */\npublic class ChefBootstrapModule extends AbstractModule {\n\n   @Provides\n   @Named(\"installChefGems\")\n   @Singleton\n   final Statement installChefGems(BootstrapProperties bootstrapProperties) {\n      InstallRubyGems installRubyGems = InstallRubyGems.builder()\n            .version(bootstrapProperties.gemSystemVersion().orNull())\n            .updateSystem(bootstrapProperties.updateGemSystem(), bootstrapProperties.gemSystemVersion().orNull())\n            .updateExistingGems(bootstrapProperties.updateGems()) //\n            .build();\n\n      Statement installChef = InstallChefGems.builder().version(bootstrapProperties.chefVersion().orNull()).build();\n\n      return new StatementList(InstallRuby.builder().build(), installRubyGems, installChef);\n   }\n\n   @Provides\n   @Named(\"installChefOmnibus\")\n   @Singleton\n   final Statement installChefUsingOmnibus(BootstrapProperties bootstrapProperties) {\n      return bootstrapProperties.chefVersion().isPresent() ?\n            new InstallChefUsingOmnibus(bootstrapProperties.chefVersion().get())\n            : new InstallChefUsingOmnibus();\n   }\n\n   @Provides\n   @InstallChef\n   @Singleton\n   final Statement installChef(BootstrapProperties bootstrapProperties, @Named(\"installChefGems\") Statement installChefGems,\n         @Named(\"installChefOmnibus\") Statement installChefOmnibus) {\n      return bootstrapProperties.useOmnibus() ? installChefOmnibus : installChefGems;\n   }\n\n   @Singleton\n   private static class BootstrapProperties {\n      @Named(CHEF_VERSION)\n      @Inject(optional = true)\n      private String chefVersionProperty;\n\n      @Named(CHEF_GEM_SYSTEM_VERSION)\n      @Inject(optional = true)\n      private String gemSystemVersionProperty;\n\n      @Named(CHEF_UPDATE_GEM_SYSTEM)\n      @Inject\n      private String updateGemSystemProeprty;\n\n      @Named(CHEF_UPDATE_GEMS)\n      @Inject\n      private String updateGemsProperty;\n\n      @Named(CHEF_USE_OMNIBUS)\n      @Inject\n      private String useOmnibus;\n\n      public Optional<String> chefVersion() {\n         return Optional.fromNullable(chefVersionProperty);\n      }\n\n      public Optional<String> gemSystemVersion() {\n         return Optional.fromNullable(gemSystemVersionProperty);\n      }\n\n      public boolean updateGemSystem() {\n         return Boolean.parseBoolean(updateGemSystemProeprty);\n      }\n\n      public boolean updateGems() {\n         return Boolean.parseBoolean(updateGemsProperty);\n      }\n\n      public boolean useOmnibus() {\n         return Boolean.parseBoolean(useOmnibus);\n      }\n   }\n\n   @Override\n   protected void configure() {\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/config/ChefHttpApiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.config;\n\nimport static com.google.common.base.Suppliers.compose;\nimport static com.google.common.base.Suppliers.memoizeWithExpiration;\nimport static com.google.common.base.Throwables.propagate;\nimport static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL;\nimport static org.jclouds.chef.config.ChefProperties.CHEF_VALIDATOR_CREDENTIAL;\nimport static org.jclouds.chef.config.ChefProperties.CHEF_VALIDATOR_NAME;\nimport static org.jclouds.crypto.Pems.privateKeySpec;\n\nimport java.io.IOException;\nimport java.security.PrivateKey;\nimport java.security.spec.InvalidKeySpecException;\nimport java.util.concurrent.TimeUnit;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.chef.ChefApi;\nimport org.jclouds.chef.domain.BootstrapConfig;\nimport org.jclouds.chef.domain.Client;\nimport org.jclouds.chef.functions.BootstrapConfigForGroup;\nimport org.jclouds.chef.functions.ClientForGroup;\nimport org.jclouds.chef.handlers.ChefApiErrorRetryHandler;\nimport org.jclouds.chef.handlers.ChefErrorHandler;\nimport org.jclouds.crypto.Crypto;\nimport org.jclouds.crypto.Pems;\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpRetryHandler;\nimport org.jclouds.http.annotation.ClientError;\nimport org.jclouds.http.annotation.Redirection;\nimport org.jclouds.http.annotation.ServerError;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.config.HttpApiModule;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Charsets;\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.io.ByteSource;\nimport com.google.inject.ConfigurationException;\nimport com.google.inject.Injector;\nimport com.google.inject.Key;\nimport com.google.inject.Provides;\nimport com.google.inject.name.Names;\n\n/**\n * Configures the Chef connection.\n */\n@ConfiguresHttpApi\npublic class ChefHttpApiModule extends HttpApiModule<ChefApi> {\n\n   @Provides\n   @TimeStamp\n   protected final String guiceProvideTimeStamp(@TimeStamp Supplier<String> cache) {\n      return provideTimeStamp(cache);\n   }\n\n   protected String provideTimeStamp(@TimeStamp Supplier<String> cache) {\n      return cache.get();\n   }\n\n   /**\n    * borrowing concurrency code to ensure that caching takes place properly\n    */\n   @Provides\n   @TimeStamp\n   final Supplier<String> provideTimeStampCache(@Named(PROPERTY_SESSION_INTERVAL) long seconds,\n         final DateService dateService) {\n      return memoizeWithExpiration(new Supplier<String>() {\n         @Override\n         public String get() {\n            return dateService.iso8601SecondsDateFormat();\n         }\n      }, seconds, TimeUnit.SECONDS);\n   }\n\n   // TODO: potentially change this\n   @Provides\n   @Singleton\n   public final Supplier<PrivateKey> supplyKey(final LoadingCache<Credentials, PrivateKey> keyCache,\n         @org.jclouds.location.Provider final Supplier<Credentials> creds) {\n      return compose(new Function<Credentials, PrivateKey>() {\n         @Override\n         public PrivateKey apply(Credentials in) {\n            return keyCache.getUnchecked(in);\n         }\n      }, creds);\n   }\n\n   @Provides\n   @Singleton\n   final LoadingCache<Credentials, PrivateKey> privateKeyCache(PrivateKeyForCredentials loader) {\n      // throw out the private key related to old credentials\n      return CacheBuilder.newBuilder().maximumSize(2).build(loader);\n   }\n\n   /**\n    * it is relatively expensive to extract a private key from a PEM. cache the\n    * relationship between current credentials so that the private key is only\n    * recalculated once.\n    */\n   @VisibleForTesting\n   @Singleton\n   private static class PrivateKeyForCredentials extends CacheLoader<Credentials, PrivateKey> {\n      private final Crypto crypto;\n\n      @Inject\n      private PrivateKeyForCredentials(Crypto crypto) {\n         this.crypto = crypto;\n      }\n\n      @Override\n      public PrivateKey load(Credentials in) {\n         try {\n            return crypto.rsaKeyFactory().generatePrivate(\n                  privateKeySpec(ByteSource.wrap(in.credential.getBytes(Charsets.UTF_8))));\n         } catch (InvalidKeySpecException e) {\n            throw propagate(e);\n         } catch (IOException e) {\n            throw propagate(e);\n         }\n      }\n   }\n\n   @Provides\n   @Singleton\n   @Validator\n   public final Optional<String> provideValidatorName(Injector injector) {\n      // Named properties can not be injected as optional here, so let's use the\n      // injector to bypass it\n      Key<String> key = Key.get(String.class, Names.named(CHEF_VALIDATOR_NAME));\n      try {\n         return Optional.<String> of(injector.getInstance(key));\n      } catch (ConfigurationException ex) {\n         return Optional.<String> absent();\n      }\n   }\n\n   @Provides\n   @Singleton\n   @Validator\n   public final Optional<PrivateKey> provideValidatorCredential(Crypto crypto, Injector injector)\n         throws InvalidKeySpecException, IOException {\n      // Named properties can not be injected as optional here, so let's use the\n      // injector to bypass it\n      Key<String> key = Key.get(String.class, Names.named(CHEF_VALIDATOR_CREDENTIAL));\n      try {\n         String validatorCredential = injector.getInstance(key);\n         PrivateKey validatorKey = crypto.rsaKeyFactory().generatePrivate(\n               Pems.privateKeySpec(ByteSource.wrap(validatorCredential.getBytes(Charsets.UTF_8))));\n         return Optional.<PrivateKey> of(validatorKey);\n      } catch (ConfigurationException ex) {\n         return Optional.<PrivateKey> absent();\n      }\n   }\n\n   @Provides\n   @Singleton\n   final CacheLoader<String, BootstrapConfig> bootstrapConfigForGroup(BootstrapConfigForGroup bootstrapConfigForGroup) {\n      return CacheLoader.from(bootstrapConfigForGroup);\n   }\n\n   @Provides\n   @Singleton\n   final CacheLoader<String, Client> groupToClient(ClientForGroup clientForGroup) {\n      return CacheLoader.from(clientForGroup);\n   }\n\n   @Override\n   protected void bindErrorHandlers() {\n      bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(ChefErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(ChefErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(ChefErrorHandler.class);\n   }\n\n   @Override\n   protected void bindRetryHandlers() {\n      bind(HttpRetryHandler.class).annotatedWith(ClientError.class).to(ChefApiErrorRetryHandler.class);\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/config/ChefParserModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.config;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkState;\n\nimport java.io.IOException;\nimport java.io.UnsupportedEncodingException;\nimport java.lang.reflect.Type;\nimport java.security.PrivateKey;\nimport java.security.PublicKey;\nimport java.security.cert.CertificateException;\nimport java.security.cert.X509Certificate;\nimport java.security.spec.InvalidKeySpecException;\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.chef.domain.DatabagItem;\nimport org.jclouds.crypto.Crypto;\nimport org.jclouds.crypto.Pems;\nimport org.jclouds.json.config.GsonModule.DateAdapter;\nimport org.jclouds.json.config.GsonModule.Iso8601DateAdapter;\nimport com.google.gson.internal.JsonReaderInternalAccess;\nimport org.jclouds.json.internal.NullFilteringTypeAdapterFactories;\nimport org.jclouds.json.internal.NullFilteringTypeAdapterFactories.MapTypeAdapterFactory;\nimport org.jclouds.json.internal.NullHackJsonLiteralAdapter;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.base.Throwables;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Maps;\nimport com.google.common.io.ByteSource;\nimport com.google.gson.Gson;\nimport com.google.gson.JsonDeserializationContext;\nimport com.google.gson.JsonDeserializer;\nimport com.google.gson.JsonElement;\nimport com.google.gson.JsonParseException;\nimport com.google.gson.JsonSyntaxException;\nimport com.google.gson.TypeAdapter;\nimport com.google.gson.stream.JsonReader;\nimport com.google.gson.stream.JsonToken;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.ImplementedBy;\nimport com.google.inject.Provides;\n\npublic class ChefParserModule extends AbstractModule {\n   @ImplementedBy(PrivateKeyAdapterImpl.class)\n   public interface PrivateKeyAdapter extends JsonDeserializer<PrivateKey> {\n\n   }\n\n   @Singleton\n   public static class PrivateKeyAdapterImpl implements PrivateKeyAdapter {\n      private final Crypto crypto;\n\n      @Inject\n      PrivateKeyAdapterImpl(Crypto crypto) {\n         this.crypto = crypto;\n      }\n\n      @Override\n      public PrivateKey deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)\n            throws JsonParseException {\n         String keyText = json.getAsString().replaceAll(\"\\\\n\", \"\\n\");\n         try {\n            return crypto.rsaKeyFactory().generatePrivate(\n                  Pems.privateKeySpec(ByteSource.wrap(keyText.getBytes(Charsets.UTF_8))));\n         } catch (UnsupportedEncodingException e) {\n            Throwables.propagate(e);\n            return null;\n         } catch (InvalidKeySpecException e) {\n            Throwables.propagate(e);\n            return null;\n         } catch (IOException e) {\n            Throwables.propagate(e);\n            return null;\n         }\n      }\n   }\n\n   @ImplementedBy(PublicKeyAdapterImpl.class)\n   public interface PublicKeyAdapter extends JsonDeserializer<PublicKey> {\n\n   }\n\n   @Singleton\n   public static class PublicKeyAdapterImpl implements PublicKeyAdapter {\n      private final Crypto crypto;\n\n      @Inject\n      PublicKeyAdapterImpl(Crypto crypto) {\n         this.crypto = crypto;\n      }\n\n      @Override\n      public PublicKey deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)\n            throws JsonParseException {\n         String keyText = json.getAsString().replaceAll(\"\\\\n\", \"\\n\");\n         try {\n            return crypto.rsaKeyFactory().generatePublic(\n                  Pems.publicKeySpec(ByteSource.wrap(keyText.getBytes(Charsets.UTF_8))));\n         } catch (UnsupportedEncodingException e) {\n            Throwables.propagate(e);\n            return null;\n         } catch (InvalidKeySpecException e) {\n            Throwables.propagate(e);\n            return null;\n         } catch (IOException e) {\n            Throwables.propagate(e);\n            return null;\n         }\n      }\n   }\n\n   @ImplementedBy(X509CertificateAdapterImpl.class)\n   public interface X509CertificateAdapter extends JsonDeserializer<X509Certificate> {\n\n   }\n\n   @Singleton\n   public static class X509CertificateAdapterImpl implements X509CertificateAdapter {\n      private final Crypto crypto;\n\n      @Inject\n      X509CertificateAdapterImpl(Crypto crypto) {\n         this.crypto = crypto;\n      }\n\n      @Override\n      public X509Certificate deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)\n            throws JsonParseException {\n         String keyText = json.getAsString().replaceAll(\"\\\\n\", \"\\n\");\n         try {\n            return Pems.x509Certificate(ByteSource.wrap(keyText.getBytes(Charsets.UTF_8)),\n                  crypto.certFactory());\n         } catch (UnsupportedEncodingException e) {\n            Throwables.propagate(e);\n            return null;\n         } catch (IOException e) {\n            Throwables.propagate(e);\n            return null;\n         } catch (CertificateException e) {\n            Throwables.propagate(e);\n            return null;\n         }\n      }\n   }\n\n   /**\n    * writes or reads the literal directly\n    */\n   @Singleton\n   public static class DataBagItemAdapter extends NullHackJsonLiteralAdapter<DatabagItem> {\n      final Gson gson = new Gson();\n\n      @Override\n      protected DatabagItem createJsonLiteralFromRawJson(String text) {\n         IdHolder idHolder = gson.fromJson(text, IdHolder.class);\n         checkState(idHolder.id != null,\n               \"databag item must be a json hash ex. {\\\"id\\\":\\\"item1\\\",\\\"my_key\\\":\\\"my_data\\\"}; was %s\", text);\n         text = text.replaceFirst(String.format(\"\\\\{\\\"id\\\"[ ]?:\\\"%s\\\",\", idHolder.id), \"{\");\n         return new DatabagItem(idHolder.id, text);\n      }\n\n      @Override\n      protected String toString(DatabagItem value) {\n         String text = value.toString();\n\n         try {\n            IdHolder idHolder = gson.fromJson(text, IdHolder.class);\n            if (idHolder.id == null) {\n               text = text.replaceFirst(\"\\\\{\", String.format(\"{\\\"id\\\":\\\"%s\\\",\", value.getId()));\n            } else {\n               checkArgument(value.getId().equals(idHolder.id),\n                     \"incorrect id in databagItem text, should be %s: was %s\", value.getId(), idHolder.id);\n            }\n         } catch (JsonSyntaxException e) {\n            throw new IllegalArgumentException(e);\n         }\n\n         return text;\n      }\n   }\n\n   private static class IdHolder {\n      private String id;\n   }\n\n   private static final class KeepLastRepeatedKeyMapTypeAdapter<K, V>\n         extends NullFilteringTypeAdapterFactories.MapTypeAdapter<K, V> {\n\n      protected KeepLastRepeatedKeyMapTypeAdapter(TypeAdapter<K> keyAdapter, TypeAdapter<V> valueAdapter) {\n         super(keyAdapter, valueAdapter);\n      }\n\n      @Override\n      public Map<K, V> read(JsonReader in) throws IOException {\n         if (in.peek() == JsonToken.NULL) {\n            in.nextNull();\n            return null;\n         }\n         Map<K, V> result = Maps.newHashMap();\n         in.beginObject();\n         while (in.hasNext()) {\n            JsonReaderInternalAccess.INSTANCE.promoteNameToValue(in);\n            K name = keyAdapter.read(in);\n            V value = valueAdapter.read(in);\n            if (value != null) {\n               // If there are repeated keys, overwrite them to only keep the\n               // last one\n               result.put(name, value);\n            }\n         }\n         in.endObject();\n         return ImmutableMap.copyOf(result);\n      }\n   }\n\n   public static class KeepLastRepeatedKeyMapTypeAdapterFactory extends MapTypeAdapterFactory {\n\n      public KeepLastRepeatedKeyMapTypeAdapterFactory() {\n         super(Map.class);\n      }\n\n      @SuppressWarnings(\"unchecked\")\n      @Override\n      protected <K, V, T> TypeAdapter<T> newAdapter(TypeAdapter<K> keyAdapter, TypeAdapter<V> valueAdapter) {\n         return (TypeAdapter<T>) new KeepLastRepeatedKeyMapTypeAdapter<K, V>(keyAdapter, valueAdapter);\n      }\n   }\n   \n   @Provides\n   @Singleton\n   public final Map<Type, Object> provideCustomAdapterBindings(DataBagItemAdapter adapter, PrivateKeyAdapter privateAdapter,\n         PublicKeyAdapter publicAdapter, X509CertificateAdapter certAdapter) {\n      return ImmutableMap.<Type, Object> of(DatabagItem.class, adapter, PrivateKey.class, privateAdapter,\n            PublicKey.class, publicAdapter, X509Certificate.class, certAdapter);\n   }\n\n   @Override\n   protected void configure() {\n      bind(DateAdapter.class).to(Iso8601DateAdapter.class);\n      bind(MapTypeAdapterFactory.class).to(KeepLastRepeatedKeyMapTypeAdapterFactory.class);\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/config/ChefProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.config;\n\n\n/**\n * Configuration properties and constants used in Chef connections.\n */\npublic final class ChefProperties {\n\n   /**\n    * The name of the Chef logger.\n    */\n   public static final String CHEF_LOGGER = \"jclouds.chef\";\n\n   /**\n    * Databag that holds chef bootstrap hints, should be a json ball in the\n    * following format:\n    * <p>\n    * {\"tag\":{\"run_list\":[\"recipe[apache2]\"]}}\n    */\n   public static final String CHEF_BOOTSTRAP_DATABAG = \"chef.bootstrap-databag\";\n\n   /**\n    * The name of the validator client used to allow nodes to autoregister in\n    * the Chef server.\n    * <p>\n    * This property must be set prior to running the\n    * {@link ChefService#createBootstrapScriptForGroup(String)} method.\n    */\n   public static final String CHEF_VALIDATOR_NAME = \"chef.validator-name\";\n\n   /**\n    * The credential of the validator client used to allow nodes to autoregister\n    * in the Chef server.\n    * <p>\n    * This property must be set prior to running the\n    * {@link ChefService#createBootstrapScriptForGroup(String)} method.\n    */\n   public static final String CHEF_VALIDATOR_CREDENTIAL = \"chef.validator-credential\";\n\n   /**\n    * The version of the Chef gem to install when bootstrapping nodes.\n    * <p>\n    * If this property is not set, by default the latest available Chef gem will\n    * be installed. The values can be fixed versions such as '0.10.8' or\n    * constrained values such as '>= 0.10.8'.\n    * <p>\n    * This property must be set prior to running the\n    * {@link ChefService#createBootstrapScriptForGroup(String)} method.\n    */\n   public static final String CHEF_VERSION = \"chef.version\";\n\n   /**\n    * Boolean property. Default (false).\n    * <p>\n    * When bootstrapping a node, forces a gem system update before installing\n    * the Chef gems.\n    * <p>\n    * This property must be set prior to running the\n    * {@link ChefService#createBootstrapScriptForGroup(String)} method.\n    */\n   public static final String CHEF_UPDATE_GEM_SYSTEM = \"chef.update-gem-system\";\n\n   /**\n    * To be used in conjunction with {@link #CHEF_UPDATE_GEM_SYSTEM}. This\n    * property will force the version of RubyGems to update the system to.\n    * <p>\n    * This property must be set prior to running the\n    * {@link ChefService#createBootstrapScriptForGroup(String)} method.\n    */\n   public static final String CHEF_GEM_SYSTEM_VERSION = \"chef.gem-system-version\";\n\n   /**\n    * Boolean property. Default (false).\n    * <p>\n    * When bootstrapping a node, updates the existing gems before installing\n    * Chef.\n    * <p>\n    * This property must be set prior to running the\n    * {@link ChefService#createBootstrapScriptForGroup(String)} method.\n    */\n   public static final String CHEF_UPDATE_GEMS = \"chef.update-gems\";\n\n   /**\n    * Boolean property. Default (true).\n    * <p>\n    * When bootstrapping a node, install the Chef client using the Omnibus\n    * installer.\n    * <p>\n    * This property must be set prior to running the\n    * {@link ChefService#createBootstrapScriptForGroup(String)} method.\n    */\n   public static final String CHEF_USE_OMNIBUS = \"chef.use-omnibus\";\n\n   private ChefProperties() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/config/InstallChef.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.config;\n\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.ElementType.PARAMETER;\nimport static java.lang.annotation.ElementType.FIELD;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\nimport jakarta.inject.Qualifier;\n\n/**\n * Used to configure the Chef install script.\n */\n@Target({ METHOD, PARAMETER, FIELD })\n@Retention(RUNTIME)\n@Qualifier\npublic @interface InstallChef {\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/config/Validator.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.config;\n\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.ElementType.PARAMETER;\nimport static java.lang.annotation.ElementType.FIELD;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\nimport jakarta.inject.Qualifier;\n\n/**\n * Used to configure the validator client information.\n * <p>\n * In a Chef server it must be only one validator client. This client is used by\n * new nodes to autoregister themselves in the Chef server.\n */\n@Target({ METHOD, PARAMETER, FIELD })\n@Retention(RUNTIME)\n@Qualifier\npublic @interface Validator {\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/domain/Attribute.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.domain;\n\nimport static org.jclouds.chef.util.CollectionUtils.copyOfOrEmpty;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.List;\nimport java.util.Set;\n\nimport org.jclouds.domain.JsonBall;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.gson.annotations.SerializedName;\n\n/**\n * An attribute in a cookbook metadata.\n */\npublic class Attribute {\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n      private String required;\n      private boolean calculated;\n      private ImmutableSet.Builder<String> choice = ImmutableSet.builder();\n      private JsonBall defaultValue;\n      private String type;\n      private ImmutableList.Builder<String> recipes = ImmutableList.builder();\n      private String displayName;\n      private String description;\n\n      public Builder required(String required) {\n         this.required = checkNotNull(required, \"required\");\n         return this;\n      }\n\n      public Builder calculated(boolean calculated) {\n         this.calculated = calculated;\n         return this;\n      }\n\n      public Builder choice(String choice) {\n         this.choice.add(checkNotNull(choice, \"choice\"));\n         return this;\n      }\n\n      public Builder choices(Iterable<String> choices) {\n         this.choice.addAll(checkNotNull(choices, \"choices\"));\n         return this;\n      }\n\n      public Builder defaultValue(JsonBall defaultValue) {\n         this.defaultValue = checkNotNull(defaultValue, \"defaultValue\");\n         return this;\n      }\n\n      public Builder type(String type) {\n         this.type = checkNotNull(type, \"type\");\n         return this;\n      }\n\n      public Builder recipe(String recipe) {\n         this.recipes.add(checkNotNull(recipe, \"recipe\"));\n         return this;\n      }\n\n      public Builder recipes(Iterable<String> recipes) {\n         this.recipes.addAll(checkNotNull(recipes, \"recipes\"));\n         return this;\n      }\n\n      public Builder displayName(String displayName) {\n         this.displayName = checkNotNull(displayName, \"displayName\");\n         return this;\n      }\n\n      public Builder description(String description) {\n         this.description = checkNotNull(description, \"description\");\n         return this;\n      }\n\n      public Attribute build() {\n         return new Attribute(required, calculated, choice.build(), defaultValue, type, recipes.build(), displayName,\n               description);\n      }\n   }\n\n   private final String required;\n   private final boolean calculated;\n   private final Set<String> choice;\n   @SerializedName(\"default\")\n   private final JsonBall defaultValue;\n   private final String type;\n   private final List<String> recipes;\n   @SerializedName(\"display_name\")\n   private final String displayName;\n   private final String description;\n\n   @ConstructorProperties({ \"required\", \"calculated\", \"choice\", \"default\", \"type\", \"recipes\", \"display_name\",\n         \"description\" })\n   protected Attribute(String required, boolean calculated, @Nullable Set<String> choice, JsonBall defaultValue,\n         String type, @Nullable List<String> recipes, String displayName, String description) {\n      this.required = required;\n      this.calculated = calculated;\n      this.choice = copyOfOrEmpty(choice);\n      this.defaultValue = defaultValue;\n      this.type = type;\n      this.recipes = copyOfOrEmpty(recipes);\n      this.displayName = displayName;\n      this.description = description;\n   }\n\n   public String getRequired() {\n      return required;\n   }\n\n   public boolean isCalculated() {\n      return calculated;\n   }\n\n   public Set<String> getChoice() {\n      return choice;\n   }\n\n   public JsonBall getDefaultValue() {\n      return defaultValue;\n   }\n\n   public String getType() {\n      return type;\n   }\n\n   public List<String> getRecipes() {\n      return recipes;\n   }\n\n   public String getDisplayName() {\n      return displayName;\n   }\n\n   public String getDescription() {\n      return description;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + (calculated ? 1231 : 1237);\n      result = prime * result + ((choice == null) ? 0 : choice.hashCode());\n      result = prime * result + ((defaultValue == null) ? 0 : defaultValue.hashCode());\n      result = prime * result + ((description == null) ? 0 : description.hashCode());\n      result = prime * result + ((displayName == null) ? 0 : displayName.hashCode());\n      result = prime * result + ((recipes == null) ? 0 : recipes.hashCode());\n      result = prime * result + ((required == null) ? 0 : required.hashCode());\n      result = prime * result + ((type == null) ? 0 : type.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      Attribute other = (Attribute) obj;\n      if (calculated != other.calculated)\n         return false;\n      if (choice == null) {\n         if (other.choice != null)\n            return false;\n      } else if (!choice.equals(other.choice))\n         return false;\n      if (defaultValue == null) {\n         if (other.defaultValue != null)\n            return false;\n      } else if (!defaultValue.equals(other.defaultValue))\n         return false;\n      if (description == null) {\n         if (other.description != null)\n            return false;\n      } else if (!description.equals(other.description))\n         return false;\n      if (displayName == null) {\n         if (other.displayName != null)\n            return false;\n      } else if (!displayName.equals(other.displayName))\n         return false;\n      if (recipes == null) {\n         if (other.recipes != null)\n            return false;\n      } else if (!recipes.equals(other.recipes))\n         return false;\n      if (required == null) {\n         if (other.required != null)\n            return false;\n      } else if (!required.equals(other.required))\n         return false;\n      if (type == null) {\n         if (other.type != null)\n            return false;\n      } else if (!type.equals(other.type))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"Attribute [calculated=\" + calculated + \", choice=\" + choice + \", defaultValue=\" + defaultValue\n            + \", description=\" + description + \", displayName=\" + displayName + \", recipes=\" + recipes + \", required=\"\n            + required + \", type=\" + type + \"]\";\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/domain/BootstrapConfig.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.List;\n\nimport org.jclouds.domain.JsonBall;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.gson.annotations.SerializedName;\n\n/**\n * Configures how the nodes in a group will bootstrap.\n * \n * @since 1.7\n */\npublic class BootstrapConfig {\n\n   public static enum SSLVerifyMode {\n      NONE, PEER;\n\n      @Override\n      public String toString() {\n         return \":verify_\" + name().toLowerCase();\n      }\n\n      public static SSLVerifyMode fromValue(String value) {\n          return valueOf(value.replaceAll(\":verify_\", \"\").toUpperCase());\n      }\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n      private ImmutableList.Builder<String> runList = ImmutableList.builder();\n      private String environment;\n      private JsonBall attribtues;\n      private String sslCAFile;\n      private String sslCAPath;\n      private SSLVerifyMode sslVerifyMode;\n      private Boolean verifyApiCert;\n\n      /**\n       * Sets the run list that will be executed in the nodes of the group.\n       */\n      public Builder runList(Iterable<String> runList) {\n         this.runList.addAll(checkNotNull(runList, \"runList\"));\n         return this;\n      }\n\n      /**\n       * Sets the environment where the nodes in the group will be deployed.\n       */\n      public Builder environment(String environment) {\n         this.environment = checkNotNull(environment, \"environment\");\n         return this;\n      }\n\n      /**\n       * Sets the attributes that will be populated to the deployed nodes.\n       */\n      public Builder attributes(JsonBall attributes) {\n         this.attribtues = checkNotNull(attributes, \"attributes\");\n         return this;\n      }\n\n      /**\n       * The file in which the OpenSSL key is saved. To be used by the Chef\n       * client to verify the certificate of the Chef Server.\n       */\n      public Builder sslCAFile(String sslCAFile) {\n         this.sslCAFile = checkNotNull(sslCAFile, \"sslCAFile\");\n         return this;\n      }\n\n      /**\n       * The path to where the OpenSSL keys that are used by the Chef client are\n       * located.\n       */\n      public Builder sslCAPath(String sslCAPath) {\n         this.sslCAPath = checkNotNull(sslCAPath, \"sslCAPath\");\n         return this;\n      }\n\n      /**\n       * The verify mode for HTTPS requests.\n       * <ul>\n       * <li>NONE - to do no validation of SSL certificates.</li>\n       * <li>PEER - to do validation of all SSL certificate, including the Chef\n       * server connections</li>\n       * </ul>\n       */\n      public Builder sslVerifyMode(SSLVerifyMode sslVerifyMode) {\n         this.sslVerifyMode = checkNotNull(sslVerifyMode, \"sslVerifyMode\");\n         return this;\n      }\n\n      /**\n       * Use to only do SSL validation of the Chef server connection; may be\n       * needed if the Chef client needs to talk to other services that have\n       * broken SSL certificates.\n       */\n      public Builder verifyApiCert(boolean verifyApiCert) {\n         this.verifyApiCert = verifyApiCert;\n         return this;\n      }\n\n      public BootstrapConfig build() {\n         return new BootstrapConfig(runList.build(), environment, attribtues, sslCAFile, sslCAPath, sslVerifyMode,\n               verifyApiCert);\n      }\n   }\n\n   @SerializedName(\"run_list\")\n   private final List<String> runList;\n   @Nullable\n   private final String environment;\n   @Nullable\n   private final JsonBall attributes;\n   @SerializedName(\"ssl_ca_file\")\n   @Nullable\n   private final String sslCAFile;\n   @SerializedName(\"ssl_ca_path\")\n   @Nullable\n   private final String sslCAPath;\n   @SerializedName(\"ssl_verify_mode\")\n   @Nullable\n   private final SSLVerifyMode sslVerifyMode;\n   @SerializedName(\"verify_api_cert\")\n   @Nullable\n   private final Boolean verifyApiCert;\n\n   @ConstructorProperties({ \"run_list\", \"environment\", \"attributes\", \"ssl_ca_file\", \"ssl_ca_path\", \"ssl_verify_mode\",\n         \"verify_api_cert\" })\n   protected BootstrapConfig(List<String> runList, @Nullable String environment, @Nullable JsonBall attributes,\n         @Nullable String sslCAFile, @Nullable String sslCAPath, @Nullable SSLVerifyMode sslVerifyMode,\n         @Nullable Boolean verifyApiCert) {\n      this.runList = ImmutableList.copyOf(checkNotNull(runList, \"runList\"));\n      this.environment = environment;\n      this.attributes = attributes;\n      this.sslCAFile = sslCAFile;\n      this.sslCAPath = sslCAPath;\n      this.sslVerifyMode = sslVerifyMode;\n      this.verifyApiCert = verifyApiCert;\n   }\n\n   public List<String> getRunList() {\n      return runList;\n   }\n\n   @Nullable\n   public String getEnvironment() {\n      return environment;\n   }\n\n   @Nullable\n   public JsonBall getAttributes() {\n      return attributes;\n   }\n\n   @Nullable\n   public String getSslCAFile() {\n      return sslCAFile;\n   }\n\n   @Nullable\n   public String getSslCAPath() {\n      return sslCAPath;\n   }\n\n   @Nullable\n   public SSLVerifyMode getSslVerifyMode() {\n      return sslVerifyMode;\n   }\n\n   @Nullable\n   public Boolean getVerifyApiCert() {\n      return verifyApiCert;\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/domain/ChecksumStatus.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport java.beans.ConstructorProperties;\nimport java.net.URI;\n\nimport com.google.gson.annotations.SerializedName;\n\n/**\n * The checksum of an uploaded resource.\n */\npublic class ChecksumStatus {\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n      private URI url;\n      private boolean needsUpload;\n\n      public Builder url(URI url) {\n         this.url = checkNotNull(url, \"url\");\n         return this;\n      }\n\n      public Builder needsUpload(boolean needsUpload) {\n         this.needsUpload = needsUpload;\n         return this;\n      }\n\n      public ChecksumStatus build() {\n         return new ChecksumStatus(url, needsUpload);\n      }\n   }\n\n   private final URI url;\n   @SerializedName(\"needs_upload\")\n   private final boolean needsUpload;\n\n   @ConstructorProperties({ \"url\", \"needs_upload\" })\n   protected ChecksumStatus(URI url, boolean needsUpload) {\n      this.url = url;\n      this.needsUpload = needsUpload;\n   }\n\n   public URI getUrl() {\n      return url;\n   }\n\n   public boolean needsUpload() {\n      return needsUpload;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + (needsUpload ? 1231 : 1237);\n      result = prime * result + ((url == null) ? 0 : url.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      ChecksumStatus other = (ChecksumStatus) obj;\n      if (needsUpload != other.needsUpload)\n         return false;\n      if (url == null) {\n         if (other.url != null)\n            return false;\n      } else if (!url.equals(other.url))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"ChecksumStatus [needsUpload=\" + needsUpload + \", url=\" + url + \"]\";\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/domain/Client.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.security.PrivateKey;\nimport java.security.PublicKey;\nimport java.security.cert.X509Certificate;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.gson.annotations.SerializedName;\n\n/**\n * Client object.\n */\npublic class Client {\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n      private X509Certificate certificate;\n      private PrivateKey privateKey;\n      private String orgname;\n      private String clientname;\n      private String name;\n      private boolean validator;\n      private PublicKey publicKey;\n\n      public Builder certificate(X509Certificate certificate) {\n         this.certificate = checkNotNull(certificate, \"certificate\");\n         return this;\n      }\n\n      public Builder privateKey(PrivateKey privateKey) {\n         this.privateKey = checkNotNull(privateKey, \"privateKey\");\n         return this;\n      }\n\n      public Builder publicKey(PublicKey publicKey) {\n         this.publicKey = checkNotNull(publicKey, \"publicKey\");\n         return this;\n      }\n\n      public Builder orgname(String orgname) {\n         this.orgname = checkNotNull(orgname, \"orgname\");\n         return this;\n      }\n\n      public Builder clientname(String clientname) {\n         this.clientname = checkNotNull(clientname, \"clientname\");\n         return this;\n      }\n\n      public Builder name(String name) {\n         this.name = checkNotNull(name, \"name\");\n         return this;\n      }\n\n      public Builder isValidator(boolean validator) {\n         this.validator = validator;\n         return this;\n      }\n\n      public Client build() {\n         return new Client(certificate, orgname, clientname, name, validator, privateKey, publicKey);\n      }\n   }\n\n   private final X509Certificate certificate;\n   @SerializedName(\"private_key\")\n   private final PrivateKey privateKey;\n   @SerializedName(\"public_key\")\n   private final PublicKey publicKey;\n   private final String orgname;\n   private final String clientname;\n   private final String name;\n   private final boolean validator;\n\n   @ConstructorProperties({ \"certificate\", \"orgname\", \"clientname\", \"name\", \"validator\", \"private_key\", \"public_key\"})\n   protected Client(X509Certificate certificate, String orgname, String clientname, String name, boolean validator,\n         @Nullable PrivateKey privateKey, @Nullable PublicKey publicKey) {\n      this.certificate = certificate;\n      this.orgname = orgname;\n      this.clientname = clientname;\n      this.name = name;\n      this.validator = validator;\n      this.privateKey = privateKey;\n      this.publicKey = publicKey;\n   }\n\n   public PublicKey getPublicKey() {\n     return publicKey;\n   }\n\n   public PrivateKey getPrivateKey() {\n      return privateKey;\n   }\n\n   public X509Certificate getCertificate() {\n      return certificate;\n   }\n\n   public String getOrgname() {\n      return orgname;\n   }\n\n   public String getClientname() {\n      return clientname;\n   }\n\n   public String getName() {\n      return name;\n   }\n\n   public boolean isValidator() {\n      return validator;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((certificate == null) ? 0 : certificate.hashCode());\n      result = prime * result + ((clientname == null) ? 0 : clientname.hashCode());\n      result = prime * result + ((name == null) ? 0 : name.hashCode());\n      result = prime * result + ((orgname == null) ? 0 : orgname.hashCode());\n      result = prime * result + ((privateKey == null) ? 0 : privateKey.hashCode());\n      result = prime * result + ((publicKey == null) ? 0 : publicKey.hashCode());\n      result = prime * result + (validator ? 1231 : 1237);\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      Client other = (Client) obj;\n      if (certificate == null) {\n         if (other.certificate != null)\n            return false;\n      } else if (!certificate.equals(other.certificate))\n         return false;\n      if (clientname == null) {\n         if (other.clientname != null)\n            return false;\n      } else if (!clientname.equals(other.clientname))\n         return false;\n      if (name == null) {\n         if (other.name != null)\n            return false;\n      } else if (!name.equals(other.name))\n         return false;\n      if (orgname == null) {\n         if (other.orgname != null)\n            return false;\n      } else if (!orgname.equals(other.orgname))\n         return false;\n      if (publicKey == null) {\n        if (other.publicKey != null)\n          return false;\n      } else if (!publicKey.equals(other.publicKey))\n        return false;\n      if (privateKey == null) {\n         if (other.privateKey != null)\n            return false;\n      } else if (!privateKey.equals(other.privateKey))\n         return false;\n      if (validator != other.validator)\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"Client [name=\" + name + \", clientname=\" + clientname + \", orgname=\" + orgname + \", isValidator=\"\n            + validator + \", certificate=\" + certificate + \", publicKey=\" + publicKey + \", privateKey=\" + (privateKey == null ? \"not \" : \"\")\n            + \"present]\";\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/domain/CookbookDefinition.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.chef.util.CollectionUtils.copyOfOrEmpty;\n\nimport java.beans.ConstructorProperties;\nimport java.net.URI;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Cookbook definition as returned by the Chef server >= 0.10.8.\n */\npublic class CookbookDefinition {\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n      private String name;\n      private URI url;\n      private ImmutableSet.Builder<Version> versions = ImmutableSet.builder();\n\n      public Builder name(String name) {\n         this.name = checkNotNull(name, \"name\");\n         return this;\n      }\n\n      public Builder url(URI url) {\n         this.url = checkNotNull(url, \"url\");\n         return this;\n      }\n\n      public Builder version(Version version) {\n         this.versions.add(checkNotNull(version, \"version\"));\n         return this;\n      }\n\n      public Builder versions(Iterable<Version> versions) {\n         this.versions.addAll(checkNotNull(versions, \"versions\"));\n         return this;\n      }\n\n      public Builder from(CookbookDefinition def) {\n         this.url = checkNotNull(def.getUrl(), \"url\");\n         this.versions.addAll(checkNotNull(def.getVersions(), \"versions\"));\n         this.name = def.getName();\n         return this;\n      }\n\n      public CookbookDefinition build() {\n         return new CookbookDefinition(name, url, versions.build());\n      }\n   }\n\n   private final String name;\n   private final URI url;\n   private final Set<Version> versions;\n\n   @ConstructorProperties({\"name\", \"url\", \"versions\" })\n   protected CookbookDefinition(String name, URI url, @Nullable Set<Version> versions) {\n      this.name = name;\n      this.url = url;\n      this.versions = copyOfOrEmpty(versions);\n   }\n\n   public String getName() {\n      return name;\n   }\n\n   public URI getUrl() {\n      return url;\n   }\n\n   public Set<Version> getVersions() {\n      return versions;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((name == null) ? 0 : name.hashCode());\n      result = prime * result + ((url == null) ? 0 : url.hashCode());\n      result = prime * result + ((versions == null) ? 0 : versions.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      CookbookDefinition other = (CookbookDefinition) obj;\n      if (name == null) {\n         if (other.name != null)\n            return false;\n      } else if (!name.equals(other.name))\n         return false;\n      if (url == null) {\n         if (other.url != null)\n            return false;\n      } else if (!url.equals(other.url))\n         return false;\n      if (versions == null) {\n         if (other.versions != null)\n            return false;\n      } else if (!versions.equals(other.versions))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"CookbookDefinition [name=\" + name + \", url=\" + url + \", versions=\" + versions + \"]\";\n   }\n\n   public static class Version {\n      public static Builder builder() {\n         return new Builder();\n      }\n\n      public static class Builder {\n         private URI url;\n         private String version;\n\n         public Builder url(URI url) {\n            this.url = checkNotNull(url, \"url\");\n            return this;\n         }\n\n         public Builder version(String version) {\n            this.version = checkNotNull(version, \"version\");\n            return this;\n         }\n\n         public Version build() {\n            return new Version(url, version);\n         }\n      }\n\n      private final URI url;\n      private final String version;\n\n      @ConstructorProperties({ \"url\", \"version\" })\n      protected Version(URI url, String version) {\n         this.url = url;\n         this.version = version;\n      }\n\n      public URI getUrl() {\n         return url;\n      }\n\n      public String getVersion() {\n         return version;\n      }\n\n      @Override\n      public int hashCode() {\n         final int prime = 31;\n         int result = 1;\n         result = prime * result + ((url == null) ? 0 : url.hashCode());\n         result = prime * result + ((version == null) ? 0 : version.hashCode());\n         return result;\n      }\n\n      @Override\n      public boolean equals(Object obj) {\n         if (this == obj)\n            return true;\n         if (obj == null)\n            return false;\n         if (getClass() != obj.getClass())\n            return false;\n         Version other = (Version) obj;\n         if (url == null) {\n            if (other.url != null)\n               return false;\n         } else if (!url.equals(other.url))\n            return false;\n         if (version == null) {\n            if (other.version != null)\n               return false;\n         } else if (!version.equals(other.version))\n            return false;\n         return true;\n      }\n\n      @Override\n      public String toString() {\n         return \"Version [url=\" + url + \", version=\" + version + \"]\";\n      }\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/domain/CookbookVersion.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.chef.util.CollectionUtils.copyOfOrEmpty;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.gson.annotations.SerializedName;\n\n/**\n * Cookbook object.\n */\npublic class CookbookVersion {\n   public static Builder builder(String name, String version) {\n      return new Builder(name, version);\n   }\n\n   public static class Builder {\n      private String cookbookName;\n      private ImmutableSet.Builder<Resource> definitions = ImmutableSet.builder();\n      private ImmutableSet.Builder<Resource> attributes = ImmutableSet.builder();\n      private ImmutableSet.Builder<Resource> files = ImmutableSet.builder();\n      private Metadata metadata = Metadata.builder().build();\n      private ImmutableSet.Builder<Resource> providers = ImmutableSet.builder();\n      private ImmutableSet.Builder<Resource> resources = ImmutableSet.builder();\n      private ImmutableSet.Builder<Resource> templates = ImmutableSet.builder();\n      private ImmutableSet.Builder<Resource> libraries = ImmutableSet.builder();\n      private String version;\n      private ImmutableSet.Builder<Resource> recipes = ImmutableSet.builder();\n      private ImmutableSet.Builder<Resource> rootFiles = ImmutableSet.builder();\n\n      public Builder(String name, String version) {\n         this.cookbookName = checkNotNull(name, \"name\");\n         this.version = checkNotNull(version, \"version\");\n      }\n\n      public Builder cookbookName(String cookbookName) {\n         this.cookbookName = checkNotNull(cookbookName, \"cookbookName\");\n         return this;\n      }\n\n      public Builder definition(Resource definition) {\n         this.definitions.add(checkNotNull(definition, \"definition\"));\n         return this;\n      }\n\n      public Builder definitions(Iterable<Resource> definitions) {\n         this.definitions.addAll(checkNotNull(definitions, \"definitions\"));\n         return this;\n      }\n\n      public Builder attribute(Resource attribute) {\n         this.attributes.add(checkNotNull(attribute, \"attribute\"));\n         return this;\n      }\n\n      public Builder attributes(Iterable<Resource> attributes) {\n         this.attributes.addAll(checkNotNull(attributes, \"attributes\"));\n         return this;\n      }\n\n      public Builder file(Resource file) {\n         this.files.add(checkNotNull(file, \"file\"));\n         return this;\n      }\n\n      public Builder files(Iterable<Resource> files) {\n         this.files.addAll(checkNotNull(files, \"files\"));\n         return this;\n      }\n\n      public Builder metadata(Metadata metadata) {\n         this.metadata = checkNotNull(metadata, \"metadata\");\n         return this;\n      }\n\n      public Builder provider(Resource provider) {\n         this.providers.add(checkNotNull(provider, \"provider\"));\n         return this;\n      }\n\n      public Builder providers(Iterable<Resource> providers) {\n         this.providers.addAll(checkNotNull(providers, \"providers\"));\n         return this;\n      }\n\n      public Builder resource(Resource resource) {\n         this.resources.add(checkNotNull(resource, \"resource\"));\n         return this;\n      }\n\n      public Builder resources(Iterable<Resource> resources) {\n         this.resources.addAll(checkNotNull(resources, \"resources\"));\n         return this;\n      }\n\n      public Builder template(Resource template) {\n         this.templates.add(checkNotNull(template, \"template\"));\n         return this;\n      }\n\n      public Builder templates(Iterable<Resource> templates) {\n         this.templates.addAll(checkNotNull(templates, \"templates\"));\n         return this;\n      }\n\n      public Builder library(Resource library) {\n         this.libraries.add(checkNotNull(library, \"library\"));\n         return this;\n      }\n\n      public Builder libraries(Iterable<Resource> libraries) {\n         this.libraries.addAll(checkNotNull(libraries, \"libraries\"));\n         return this;\n      }\n\n      public Builder version(String version) {\n         this.version = checkNotNull(version, \"version\");\n         return this;\n      }\n\n      public Builder recipe(Resource recipe) {\n         this.recipes.add(checkNotNull(recipe, \"recipe\"));\n         return this;\n      }\n\n      public Builder recipes(Iterable<Resource> recipes) {\n         this.recipes.addAll(checkNotNull(recipes, \"recipes\"));\n         return this;\n      }\n\n      public Builder rootFile(Resource rootFile) {\n         this.rootFiles.add(checkNotNull(rootFile, \"rootFile\"));\n         return this;\n      }\n\n      public Builder rootFiles(Iterable<Resource> rootFiles) {\n         this.rootFiles.addAll(checkNotNull(rootFiles, \"rootFiles\"));\n         return this;\n      }\n\n      public CookbookVersion build() {\n         return new CookbookVersion(checkNotNull(cookbookName, \"name\") + \"-\" + checkNotNull(version, \"version\"),\n               definitions.build(), attributes.build(), files.build(), metadata, providers.build(), cookbookName,\n               resources.build(), templates.build(), libraries.build(), version, recipes.build(), rootFiles.build());\n      }\n   }\n\n   private final String name;\n   private final Set<Resource> definitions;\n   private final Set<Resource> attributes;\n   private final Set<Resource> files;\n   private final Metadata metadata;\n   private final Set<Resource> providers;\n   @SerializedName(\"cookbook_name\")\n   private final String cookbookName;\n   private final Set<Resource> resources;\n   private final Set<Resource> templates;\n   private final Set<Resource> libraries;\n   private final String version;\n   private final Set<Resource> recipes;\n   @SerializedName(\"root_files\")\n   private final Set<Resource> rootFiles;\n\n   // internal\n   @SerializedName(\"json_class\")\n   private String _jsonClass = \"Chef::CookbookVersion\";\n   @SerializedName(\"chef_type\")\n   private String _chefType = \"cookbook_version\";\n\n   @ConstructorProperties({ \"name\", \"definitions\", \"attributes\", \"files\", \"metadata\", \"providers\", \"cookbook_name\",\n         \"resources\", \"templates\", \"libraries\", \"version\", \"recipes\", \"root_files\" })\n   protected CookbookVersion(String name, @Nullable Set<Resource> definitions, @Nullable Set<Resource> attributes,\n         @Nullable Set<Resource> files, Metadata metadata, @Nullable Set<Resource> providers, String cookbookName,\n         @Nullable Set<Resource> resources, @Nullable Set<Resource> templates, @Nullable Set<Resource> libraries,\n         String version, @Nullable Set<Resource> recipes, @Nullable Set<Resource> rootFiles) {\n      this.name = name;\n      this.definitions = copyOfOrEmpty(definitions);\n      this.attributes = copyOfOrEmpty(attributes);\n      this.files = copyOfOrEmpty(files);\n      this.metadata = metadata;\n      this.providers = copyOfOrEmpty(providers);\n      this.cookbookName = cookbookName;\n      this.resources = copyOfOrEmpty(resources);\n      this.templates = copyOfOrEmpty(templates);\n      this.libraries = copyOfOrEmpty(libraries);\n      this.version = version;\n      this.recipes = copyOfOrEmpty(recipes);\n      this.rootFiles = copyOfOrEmpty(rootFiles);\n   }\n\n   public String getName() {\n      return name;\n   }\n\n   public Set<Resource> getDefinitions() {\n      return definitions;\n   }\n\n   public Set<Resource> getAttributes() {\n      return attributes;\n   }\n\n   public Set<Resource> getFiles() {\n      return files;\n   }\n\n   public Metadata getMetadata() {\n      return metadata;\n   }\n\n   public Set<Resource> getSuppliers() {\n      return providers;\n   }\n\n   public String getCookbookName() {\n      return cookbookName;\n   }\n\n   public Set<Resource> getResources() {\n      return resources;\n   }\n\n   public Set<Resource> getTemplates() {\n      return templates;\n   }\n\n   public Set<Resource> getLibraries() {\n      return libraries;\n   }\n\n   public String getVersion() {\n      return version;\n   }\n\n   public Set<Resource> getRecipes() {\n      return recipes;\n   }\n\n   public Set<Resource> getRootFiles() {\n      return rootFiles;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((attributes == null) ? 0 : attributes.hashCode());\n      result = prime * result + ((cookbookName == null) ? 0 : cookbookName.hashCode());\n      result = prime * result + ((definitions == null) ? 0 : definitions.hashCode());\n      result = prime * result + ((files == null) ? 0 : files.hashCode());\n      result = prime * result + ((libraries == null) ? 0 : libraries.hashCode());\n      result = prime * result + ((metadata == null) ? 0 : metadata.hashCode());\n      result = prime * result + ((name == null) ? 0 : name.hashCode());\n      result = prime * result + ((providers == null) ? 0 : providers.hashCode());\n      result = prime * result + ((recipes == null) ? 0 : recipes.hashCode());\n      result = prime * result + ((resources == null) ? 0 : resources.hashCode());\n      result = prime * result + ((rootFiles == null) ? 0 : rootFiles.hashCode());\n      result = prime * result + ((templates == null) ? 0 : templates.hashCode());\n      result = prime * result + ((version == null) ? 0 : version.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      CookbookVersion other = (CookbookVersion) obj;\n      if (attributes == null) {\n         if (other.attributes != null)\n            return false;\n      } else if (!attributes.equals(other.attributes))\n         return false;\n      if (cookbookName == null) {\n         if (other.cookbookName != null)\n            return false;\n      } else if (!cookbookName.equals(other.cookbookName))\n         return false;\n      if (definitions == null) {\n         if (other.definitions != null)\n            return false;\n      } else if (!definitions.equals(other.definitions))\n         return false;\n      if (files == null) {\n         if (other.files != null)\n            return false;\n      } else if (!files.equals(other.files))\n         return false;\n      if (libraries == null) {\n         if (other.libraries != null)\n            return false;\n      } else if (!libraries.equals(other.libraries))\n         return false;\n      if (metadata == null) {\n         if (other.metadata != null)\n            return false;\n      } else if (!metadata.equals(other.metadata))\n         return false;\n      if (name == null) {\n         if (other.name != null)\n            return false;\n      } else if (!name.equals(other.name))\n         return false;\n      if (providers == null) {\n         if (other.providers != null)\n            return false;\n      } else if (!providers.equals(other.providers))\n         return false;\n      if (recipes == null) {\n         if (other.recipes != null)\n            return false;\n      } else if (!recipes.equals(other.recipes))\n         return false;\n      if (resources == null) {\n         if (other.resources != null)\n            return false;\n      } else if (!resources.equals(other.resources))\n         return false;\n      if (rootFiles == null) {\n         if (other.rootFiles != null)\n            return false;\n      } else if (!rootFiles.equals(other.rootFiles))\n         return false;\n      if (templates == null) {\n         if (other.templates != null)\n            return false;\n      } else if (!templates.equals(other.templates))\n         return false;\n      if (version == null) {\n         if (other.version != null)\n            return false;\n      } else if (!version.equals(other.version))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"Cookbook [attributes=\" + attributes + \", cookbookName=\" + cookbookName + \", definitions=\" + definitions\n            + \", files=\" + files + \", libraries=\" + libraries + \", metadata=\" + metadata + \", name=\" + name\n            + \", providers=\" + providers + \", recipes=\" + recipes + \", resources=\" + resources + \", rootFiles=\"\n            + rootFiles + \", templates=\" + templates + \", version=\" + version + \"]\";\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/domain/DatabagItem.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.domain.JsonBall;\n\n/**\n * An item in a data bag.\n */\npublic class DatabagItem extends JsonBall {\n\n   private final String id;\n\n   public DatabagItem(String id, String value) {\n      super(value);\n      this.id = checkNotNull(id, \"id\");\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = super.hashCode();\n      result = prime * result + ((id == null) ? 0 : id.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (!super.equals(obj))\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      DatabagItem other = (DatabagItem) obj;\n      if (id == null) {\n         if (other.id != null)\n            return false;\n      } else if (!id.equals(other.id))\n         return false;\n      return true;\n   }\n\n   public String getId() {\n      return id;\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/domain/Environment.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.chef.util.CollectionUtils.copyOfOrEmpty;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Map;\n\nimport org.jclouds.domain.JsonBall;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.gson.annotations.SerializedName;\n\n/**\n * An environment.\n */\npublic class Environment {\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n      private String name;\n      private ImmutableMap.Builder<String, JsonBall> attributes = ImmutableMap.builder();\n      private ImmutableMap.Builder<String, JsonBall> overrideAttributes = ImmutableMap.builder();\n      private String description = \"\";\n      private ImmutableMap.Builder<String, String> cookbookVersions = ImmutableMap.builder();\n\n      public Builder name(String name) {\n         this.name = checkNotNull(name, \"name\");\n         return this;\n      }\n\n      public Builder attribute(String key, JsonBall value) {\n         this.attributes.put(checkNotNull(key, \"key\"), checkNotNull(value, \"value\"));\n         return this;\n      }\n\n      public Builder attributes(Map<String, JsonBall> attributes) {\n         this.attributes.putAll(checkNotNull(attributes, \"attributes\"));\n         return this;\n      }\n\n      public Builder overrideAttribute(String key, JsonBall value) {\n         this.overrideAttributes.put(checkNotNull(key, \"key\"), checkNotNull(value, \"value\"));\n         return this;\n      }\n\n      public Builder overrideAttributes(Map<String, JsonBall> overrideAttributes) {\n         this.overrideAttributes.putAll(checkNotNull(overrideAttributes, \"overrideAttributes\"));\n         return this;\n      }\n\n      public Builder cookbookVersion(String key, String version) {\n         this.cookbookVersions.put(checkNotNull(key, \"key\"), checkNotNull(version, \"version\"));\n         return this;\n      }\n\n      public Builder cookbookVersions(Map<String, String> cookbookVersions) {\n         this.cookbookVersions.putAll(checkNotNull(cookbookVersions, \"cookbookVersions\"));\n         return this;\n      }\n\n      public Builder description(String description) {\n         this.description = checkNotNull(description, \"description\");\n         return this;\n      }\n\n      public Environment build() {\n         return new Environment(name, attributes.build(), overrideAttributes.build(), description,\n               cookbookVersions.build());\n      }\n   }\n\n   private final String name;\n   @SerializedName(\"default_attributes\")\n   private final Map<String, JsonBall> attributes;\n   @SerializedName(\"override_attributes\")\n   private final Map<String, JsonBall> overrideAttributes;\n   private final String description;\n   @SerializedName(\"cookbook_versions\")\n   private final Map<String, String> cookbookVersions;\n\n   // internal\n   @SerializedName(\"json_class\")\n   private final String _jsonClass = \"Chef::Environment\";\n   @SerializedName(\"chef_type\")\n   private final String _chefType = \"environment\";\n\n   @ConstructorProperties({ \"name\", \"default_attributes\", \"override_attributes\", \"description\", \"cookbook_versions\" })\n   protected Environment(String name, @Nullable Map<String, JsonBall> attributes,\n         @Nullable Map<String, JsonBall> overrideAttributes, String description,\n         @Nullable Map<String, String> cookbookVersions) {\n      this.name = name;\n      this.attributes = copyOfOrEmpty(attributes);\n      this.overrideAttributes = copyOfOrEmpty(overrideAttributes);\n      this.description = description;\n      this.cookbookVersions = copyOfOrEmpty(cookbookVersions);\n   }\n\n   public String getName() {\n      return name;\n   }\n\n   public Map<String, JsonBall> getAttributes() {\n      return attributes;\n   }\n\n   public Map<String, JsonBall> getOverrideAttributes() {\n      return overrideAttributes;\n   }\n\n   public String getDescription() {\n      return description;\n   }\n\n   public Map<String, String> getCookbookVersions() {\n      return cookbookVersions;\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o)\n         return true;\n      if (o == null || getClass() != o.getClass())\n         return false;\n\n      Environment that = (Environment) o;\n\n      if (attributes != null ? !attributes.equals(that.attributes) : that.attributes != null)\n         return false;\n      if (cookbookVersions != null ? !cookbookVersions.equals(that.cookbookVersions) : that.cookbookVersions != null)\n         return false;\n      if (description != null ? !description.equals(that.description) : that.description != null)\n         return false;\n      if (!name.equals(that.name))\n         return false;\n      if (overrideAttributes != null ? !overrideAttributes.equals(that.overrideAttributes)\n            : that.overrideAttributes != null)\n         return false;\n\n      return true;\n   }\n\n   @Override\n   public int hashCode() {\n      int result = name.hashCode();\n      result = 31 * result + (attributes != null ? attributes.hashCode() : 0);\n      result = 31 * result + (overrideAttributes != null ? overrideAttributes.hashCode() : 0);\n      result = 31 * result + (description != null ? description.hashCode() : 0);\n      result = 31 * result + (cookbookVersions != null ? cookbookVersions.hashCode() : 0);\n      return result;\n   }\n\n   @Override\n   public String toString() {\n      return \"Environment [\" + \"name='\" + name + '\\'' + \", attributes=\" + attributes + \", overrideAttributes=\"\n            + overrideAttributes + \", description='\" + description + '\\'' + \", cookbookVersions=\" + cookbookVersions\n            + ']';\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/domain/Group.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.domain;\n\nimport static org.jclouds.chef.util.CollectionUtils.copyOfOrEmpty;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Group object.\n */\npublic class Group {\n   public static Builder builder(String groupname) {\n      return new Builder(groupname);\n   }\n\n   public static class Builder {\n      private String name;\n      private String groupname;\n      private String orgname;\n      private ImmutableSet.Builder<String> actors = ImmutableSet.builder();\n      private ImmutableSet.Builder<String> clients = ImmutableSet.builder();\n      private ImmutableSet.Builder<String> groups = ImmutableSet.builder();\n      private ImmutableSet.Builder<String> users = ImmutableSet.builder();\n\n      public Builder(String groupname) {\n         this.groupname = groupname;\n      }\n\n      public Builder name(String name) {\n         this.name = checkNotNull(name, \"name\");\n         return this;\n      }\n\n      public Builder groupname(String groupname) {\n         this.groupname = checkNotNull(groupname, \"groupname\");\n         return this;\n      }\n\n      public Builder orgname(String orgname) {\n         this.orgname = checkNotNull(orgname, \"orgname\");\n         return this;\n      }\n\n      public Builder actor(String actor) {\n         this.actors.add(checkNotNull(actor, \"actor\"));\n         return this;\n      }\n\n      public Builder actors(Iterable<String> actors) {\n         this.actors.addAll(checkNotNull(actors, \"actors\"));\n         return this;\n      }\n\n      public Builder client(String client) {\n         this.clients.add(checkNotNull(client, \"client\"));\n         return this;\n      }\n\n      public Builder clients(Iterable<String> clients) {\n         this.clients.addAll(checkNotNull(clients, \"clients\"));\n         return this;\n      }\n\n      public Builder group(String group) {\n         this.groups.add(checkNotNull(group, \"group\"));\n         return this;\n      }\n\n      public Builder groups(Iterable<String> groups) {\n         this.groups.addAll(checkNotNull(groups, \"groups\"));\n         return this;\n      }\n\n      public Builder user(String user) {\n         this.users.add(checkNotNull(user, \"user\"));\n         return this;\n      }\n\n      public Builder users(Iterable<String> users) {\n         this.users.addAll(checkNotNull(users, \"users\"));\n         return this;\n      }\n\n      public Group build() {\n         return new Group(name, checkNotNull(groupname, \"groupname\"), orgname, actors.build(), clients.build(),\n               groups.build(), users.build());\n      }\n   }\n\n   private final String name;\n   private final String groupname;\n   private final String orgname;\n   private final Set<String> actors;\n   private final Set<String> clients;\n   private final Set<String> groups;\n   private final Set<String> users;\n\n   @ConstructorProperties({ \"name\", \"groupname\", \"orgname\", \"actors\", \"clients\", \"groups\", \"users\" })\n   public Group(String name, String groupname, String orgname, @Nullable Set<String> actors,\n         @Nullable Set<String> clients, @Nullable Set<String> groups, @Nullable Set<String> users) {\n      this.name = name;\n      this.groupname = groupname;\n      this.orgname = orgname;\n      this.actors = copyOfOrEmpty(actors);\n      this.clients = copyOfOrEmpty(clients);\n      this.groups = copyOfOrEmpty(groups);\n      this.users = copyOfOrEmpty(users);\n   }\n\n   public String getName() {\n      return name;\n   }\n\n   public String getGroupname() {\n      return groupname;\n   }\n\n   public String getOrgname() {\n      return orgname;\n   }\n\n   public Set<String> getActors() {\n      return actors;\n   }\n\n   public Set<String> getClients() {\n      return clients;\n   }\n\n   public Set<String> getGroups() {\n      return groups;\n   }\n\n   public Set<String> getUsers() {\n      return users;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + (groupname == null ? 0 : groupname.hashCode());\n      result = prime * result + (name == null ? 0 : name.hashCode());\n      result = prime * result + (orgname == null ? 0 : orgname.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) {\n         return true;\n      }\n      if (obj == null) {\n         return false;\n      }\n      if (getClass() != obj.getClass()) {\n         return false;\n      }\n      Group other = (Group) obj;\n      if (groupname == null) {\n         if (other.groupname != null) {\n            return false;\n         }\n      } else if (!groupname.equals(other.groupname)) {\n         return false;\n      }\n      if (name == null) {\n         if (other.name != null) {\n            return false;\n         }\n      } else if (!name.equals(other.name)) {\n         return false;\n      }\n      if (orgname == null) {\n         if (other.orgname != null) {\n            return false;\n         }\n      } else if (!orgname.equals(other.orgname)) {\n         return false;\n      }\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"Group [name=\" + name + \", groupname=\" + groupname + \", orgname=\" + orgname + \", actors=\" + actors\n            + \", clients=\" + clients + \", groups=\" + groups + \", users=\" + users + \"]\";\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/domain/Grouping.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\n/**\n * Information of a group of attributes in a namespace.\n */\npublic class Grouping {\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n      private String title;\n      private String description;\n\n      public Builder title(String title) {\n         this.title = checkNotNull(title, \"title\");\n         return this;\n      }\n\n      public Builder description(String description) {\n         this.description = description;\n         return this;\n      }\n\n      public Grouping build() {\n         return new Grouping(title, description);\n      }\n   }\n\n   private final String title;\n   private final String description;\n\n   @ConstructorProperties({ \"title\", \"description\" })\n   protected Grouping(String title, String description) {\n      this.title = title;\n      this.description = description;\n   }\n\n   public String getTitle() {\n      return title;\n   }\n\n   public String getDescription() {\n      return description;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((description == null) ? 0 : description.hashCode());\n      result = prime * result + ((title == null) ? 0 : title.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      Grouping other = (Grouping) obj;\n      if (description == null) {\n         if (other.description != null)\n            return false;\n      } else if (!description.equals(other.description))\n         return false;\n      if (title == null) {\n         if (other.title != null)\n            return false;\n      } else if (!title.equals(other.title))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"Grouping [title=\" + title + \", description=\" + description + \"]\";\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/domain/Metadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.chef.util.CollectionUtils.copyOfOrEmpty;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Map;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.gson.annotations.SerializedName;\n\n/**\n * A metadata object.\n */\npublic class Metadata {\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n      private String license;\n      private String maintainer;\n      private ImmutableMap.Builder<String, String> suggestions = ImmutableMap.builder();\n      private ImmutableMap.Builder<String, String> dependencies = ImmutableMap.builder();\n      private String maintainerEmail;\n      private ImmutableMap.Builder<String, String> conflicting = ImmutableMap.builder();\n      private String description;\n      private ImmutableMap.Builder<String, String> providing = ImmutableMap.builder();\n      private ImmutableMap.Builder<String, String> platforms = ImmutableMap.builder();\n      private String version;\n      private ImmutableMap.Builder<String, String> recipes = ImmutableMap.builder();\n      private ImmutableMap.Builder<String, String> replacing = ImmutableMap.builder();\n      private String name;\n      private ImmutableMap.Builder<String, Grouping> groupings = ImmutableMap.builder();\n      private String longDescription;\n      private ImmutableMap.Builder<String, Attribute> attributes = ImmutableMap.builder();\n      private ImmutableMap.Builder<String, String> recommendations = ImmutableMap.builder();\n\n      public Builder license(String license) {\n         this.license = checkNotNull(license, \"license\");\n         return this;\n      }\n\n      public Builder maintainer(String maintainer) {\n         this.maintainer = checkNotNull(maintainer, \"maintainer\");\n         return this;\n      }\n\n      public Builder suggestion(String key, String value) {\n         this.suggestions.put(checkNotNull(key, \"key\"), checkNotNull(value, \"value\"));\n         return this;\n      }\n\n      public Builder suggestions(Map<String, String> suggestions) {\n         this.suggestions.putAll(checkNotNull(suggestions, \"suggestions\"));\n         return this;\n      }\n\n      public Builder dependency(String key, String value) {\n         this.dependencies.put(checkNotNull(key, \"key\"), checkNotNull(value, \"value\"));\n         return this;\n      }\n\n      public Builder dependencies(Map<String, String> dependencies) {\n         this.dependencies.putAll(checkNotNull(dependencies, \"dependencies\"));\n         return this;\n      }\n\n      public Builder maintainerEmail(String maintainerEmail) {\n         this.maintainerEmail = checkNotNull(maintainerEmail, \"maintainerEmail\");\n         return this;\n      }\n\n      public Builder conflicting(String key, String value) {\n         this.conflicting.put(checkNotNull(key, \"key\"), checkNotNull(value, \"value\"));\n         return this;\n      }\n\n      public Builder conflicting(Map<String, String> conflicting) {\n         this.conflicting.putAll(checkNotNull(conflicting, \"conflicting\"));\n         return this;\n      }\n\n      public Builder description(String description) {\n         this.description = checkNotNull(description, \"description\");\n         return this;\n      }\n\n      public Builder providing(String key, String value) {\n         this.providing.put(checkNotNull(key, \"key\"), checkNotNull(value, \"value\"));\n         return this;\n      }\n\n      public Builder providing(Map<String, String> providing) {\n         this.providing.putAll(checkNotNull(providing, \"providing\"));\n         return this;\n      }\n\n      public Builder platform(String key, String value) {\n         this.platforms.put(checkNotNull(key, \"key\"), checkNotNull(value, \"value\"));\n         return this;\n      }\n\n      public Builder platforms(Map<String, String> platforms) {\n         this.platforms.putAll(checkNotNull(platforms, \"platforms\"));\n         return this;\n      }\n\n      public Builder version(String version) {\n         this.version = checkNotNull(version, \"version\");\n         return this;\n      }\n\n      public Builder recipe(String key, String value) {\n         this.recipes.put(checkNotNull(key, \"key\"), checkNotNull(value, \"value\"));\n         return this;\n      }\n\n      public Builder recipes(Map<String, String> recipes) {\n         this.recipes.putAll(checkNotNull(recipes, \"recipes\"));\n         return this;\n      }\n\n      public Builder replacing(String key, String value) {\n         this.replacing.put(checkNotNull(key, \"key\"), checkNotNull(value, \"value\"));\n         return this;\n      }\n\n      public Builder replacing(Map<String, String> replacing) {\n         this.replacing.putAll(checkNotNull(replacing, \"replacing\"));\n         return this;\n      }\n\n      public Builder name(String name) {\n         this.name = checkNotNull(name, \"name\");\n         return this;\n      }\n\n      public Builder grouping(String key, Grouping value) {\n         this.groupings.put(checkNotNull(key, \"key\"), checkNotNull(value, \"value\"));\n         return this;\n      }\n\n      public Builder grouping(Map<String, Grouping> groupings) {\n         this.groupings.putAll(checkNotNull(groupings, \"groupings\"));\n         return this;\n      }\n\n      public Builder longDescription(String longDescription) {\n         this.longDescription = checkNotNull(longDescription, \"longDescription\");\n         return this;\n      }\n\n      public Builder attribute(String key, Attribute value) {\n         this.attributes.put(checkNotNull(key, \"key\"), checkNotNull(value, \"value\"));\n         return this;\n      }\n\n      public Builder attributes(Map<String, Attribute> attributes) {\n         this.attributes.putAll(checkNotNull(attributes, \"attributes\"));\n         return this;\n      }\n\n      public Builder recommendation(String key, String value) {\n         this.recommendations.put(checkNotNull(key, \"key\"), checkNotNull(value, \"value\"));\n         return this;\n      }\n\n      public Builder recommendations(Map<String, String> recommendations) {\n         this.recommendations.putAll(checkNotNull(recommendations, \"recommendations\"));\n         return this;\n      }\n\n      public Metadata build() {\n         return new Metadata(license, maintainer, suggestions.build(), dependencies.build(), maintainerEmail,\n               conflicting.build(), description, providing.build(), platforms.build(), version, recipes.build(),\n               replacing.build(), name, groupings.build(), longDescription, attributes.build(), recommendations.build());\n      }\n\n   }\n\n   private final String license;\n   private final String maintainer;\n   private final Map<String, String> suggestions;\n   private final Map<String, String> dependencies;\n   @SerializedName(\"maintainer_email\")\n   private final String maintainerEmail;\n   private final Map<String, String> conflicting;\n   private final String description;\n   private final Map<String, String> providing;\n   private final Map<String, String> platforms;\n   private final String version;\n   private final Map<String, String> recipes;\n   private final Map<String, String> replacing;\n   private final String name;\n   private final Map<String, Grouping> groupings;\n   @SerializedName(\"long_description\")\n   private final String longDescription;\n   private final Map<String, Attribute> attributes;\n   private final Map<String, String> recommendations;\n\n   @ConstructorProperties({ \"license\", \"maintainer\", \"suggestions\", \"dependencies\", \"maintainer_email\", \"conflicting\",\n         \"description\", \"providing\", \"platforms\", \"version\", \"recipes\", \"replacing\", \"name\", \"groupings\",\n         \"long_description\", \"attributes\", \"recommendations\" })\n   protected Metadata(String license, String maintainer, @Nullable Map<String, String> suggestions,\n         @Nullable Map<String, String> dependencies, String maintainerEmail, @Nullable Map<String, String> conflicting,\n         String description, @Nullable Map<String, String> providing, @Nullable Map<String, String> platforms,\n         String version, @Nullable Map<String, String> recipes, @Nullable Map<String, String> replacing, String name,\n         @Nullable Map<String, Grouping> groupings, String longDescription, @Nullable Map<String, Attribute> attributes,\n         @Nullable Map<String, String> recommendations) {\n      this.license = license;\n      this.maintainer = maintainer;\n      this.suggestions = copyOfOrEmpty(suggestions);\n      this.dependencies = copyOfOrEmpty(dependencies);\n      this.maintainerEmail = maintainerEmail;\n      this.conflicting = copyOfOrEmpty(conflicting);\n      this.description = description;\n      this.providing = copyOfOrEmpty(providing);\n      this.platforms = copyOfOrEmpty(platforms);\n      this.version = version;\n      this.recipes = copyOfOrEmpty(recipes);\n      this.replacing = copyOfOrEmpty(replacing);\n      this.name = name;\n      this.groupings = copyOfOrEmpty(groupings);\n      this.longDescription = longDescription;\n      this.attributes = copyOfOrEmpty(attributes);\n      this.recommendations = copyOfOrEmpty(recommendations);\n   }\n\n   public String getLicense() {\n      return license;\n   }\n\n   public String getMaintainer() {\n      return maintainer;\n   }\n\n   public Map<String, String> getSuggestions() {\n      return suggestions;\n   }\n\n   public Map<String, String> getDependencies() {\n      return dependencies;\n   }\n\n   public String getMaintainerEmail() {\n      return maintainerEmail;\n   }\n\n   public Map<String, String> getConflicting() {\n      return conflicting;\n   }\n\n   public String getDescription() {\n      return description;\n   }\n\n   public Map<String, String> getProviding() {\n      return providing;\n   }\n\n   public Map<String, String> getPlatforms() {\n      return platforms;\n   }\n\n   public String getVersion() {\n      return version;\n   }\n\n   public Map<String, String> getRecipes() {\n      return recipes;\n   }\n\n   public Map<String, String> getReplacing() {\n      return replacing;\n   }\n\n   public String getName() {\n      return name;\n   }\n\n   public Map<String, Grouping> getGroupings() {\n      return groupings;\n   }\n\n   public String getLongDescription() {\n      return longDescription;\n   }\n\n   public Map<String, Attribute> getAttributes() {\n      return attributes;\n   }\n\n   public Map<String, String> getRecommendations() {\n      return recommendations;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((attributes == null) ? 0 : attributes.hashCode());\n      result = prime * result + ((conflicting == null) ? 0 : conflicting.hashCode());\n      result = prime * result + ((dependencies == null) ? 0 : dependencies.hashCode());\n      result = prime * result + ((description == null) ? 0 : description.hashCode());\n      result = prime * result + ((groupings == null) ? 0 : groupings.hashCode());\n      result = prime * result + ((license == null) ? 0 : license.hashCode());\n      result = prime * result + ((longDescription == null) ? 0 : longDescription.hashCode());\n      result = prime * result + ((maintainer == null) ? 0 : maintainer.hashCode());\n      result = prime * result + ((maintainerEmail == null) ? 0 : maintainerEmail.hashCode());\n      result = prime * result + ((name == null) ? 0 : name.hashCode());\n      result = prime * result + ((platforms == null) ? 0 : platforms.hashCode());\n      result = prime * result + ((providing == null) ? 0 : providing.hashCode());\n      result = prime * result + ((recipes == null) ? 0 : recipes.hashCode());\n      result = prime * result + ((recommendations == null) ? 0 : recommendations.hashCode());\n      result = prime * result + ((replacing == null) ? 0 : replacing.hashCode());\n      result = prime * result + ((suggestions == null) ? 0 : suggestions.hashCode());\n      result = prime * result + ((version == null) ? 0 : version.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      Metadata other = (Metadata) obj;\n      if (attributes == null) {\n         if (other.attributes != null)\n            return false;\n      } else if (!attributes.equals(other.attributes))\n         return false;\n      if (conflicting == null) {\n         if (other.conflicting != null)\n            return false;\n      } else if (!conflicting.equals(other.conflicting))\n         return false;\n      if (dependencies == null) {\n         if (other.dependencies != null)\n            return false;\n      } else if (!dependencies.equals(other.dependencies))\n         return false;\n      if (description == null) {\n         if (other.description != null)\n            return false;\n      } else if (!description.equals(other.description))\n         return false;\n      if (groupings == null) {\n         if (other.groupings != null)\n            return false;\n      } else if (!groupings.equals(other.groupings))\n         return false;\n      if (license == null) {\n         if (other.license != null)\n            return false;\n      } else if (!license.equals(other.license))\n         return false;\n      if (longDescription == null) {\n         if (other.longDescription != null)\n            return false;\n      } else if (!longDescription.equals(other.longDescription))\n         return false;\n      if (maintainer == null) {\n         if (other.maintainer != null)\n            return false;\n      } else if (!maintainer.equals(other.maintainer))\n         return false;\n      if (maintainerEmail == null) {\n         if (other.maintainerEmail != null)\n            return false;\n      } else if (!maintainerEmail.equals(other.maintainerEmail))\n         return false;\n      if (name == null) {\n         if (other.name != null)\n            return false;\n      } else if (!name.equals(other.name))\n         return false;\n      if (platforms == null) {\n         if (other.platforms != null)\n            return false;\n      } else if (!platforms.equals(other.platforms))\n         return false;\n      if (providing == null) {\n         if (other.providing != null)\n            return false;\n      } else if (!providing.equals(other.providing))\n         return false;\n      if (recipes == null) {\n         if (other.recipes != null)\n            return false;\n      } else if (!recipes.equals(other.recipes))\n         return false;\n      if (recommendations == null) {\n         if (other.recommendations != null)\n            return false;\n      } else if (!recommendations.equals(other.recommendations))\n         return false;\n      if (replacing == null) {\n         if (other.replacing != null)\n            return false;\n      } else if (!replacing.equals(other.replacing))\n         return false;\n      if (suggestions == null) {\n         if (other.suggestions != null)\n            return false;\n      } else if (!suggestions.equals(other.suggestions))\n         return false;\n      if (version == null) {\n         if (other.version != null)\n            return false;\n      } else if (!version.equals(other.version))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"Metadata [attributes=\" + attributes + \", conflicting=\" + conflicting + \", dependencies=\" + dependencies\n            + \", description=\" + description + \", groupings=\" + groupings + \", license=\" + license\n            + \", longDescription=\" + longDescription + \", maintainer=\" + maintainer + \", maintainerEmail=\"\n            + maintainerEmail + \", name=\" + name + \", platforms=\" + platforms + \", providing=\" + providing\n            + \", recipes=\" + recipes + \", recommendations=\" + recommendations + \", replacing=\" + replacing\n            + \", suggestions=\" + suggestions + \", version=\" + version + \"]\";\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/domain/Node.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.chef.util.CollectionUtils.copyOfOrEmpty;\n\nimport java.beans.ConstructorProperties;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.domain.JsonBall;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.gson.annotations.SerializedName;\n\n/**\n * Node object.\n */\npublic class Node {\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n      private String name;\n      private ImmutableMap.Builder<String, JsonBall> normalAttributes = ImmutableMap.builder();\n      private ImmutableMap.Builder<String, JsonBall> overrideAttributes = ImmutableMap.builder();\n      private ImmutableMap.Builder<String, JsonBall> defaultAttributes = ImmutableMap.builder();\n      private ImmutableMap.Builder<String, JsonBall> automaticAttributes = ImmutableMap.builder();\n      private ImmutableList.Builder<String> runList = ImmutableList.builder();\n      private String environment;\n\n      public Builder name(String name) {\n         this.name = checkNotNull(name, \"name\");\n         return this;\n      }\n\n      public Builder normalAttribute(String key, JsonBall value) {\n         this.normalAttributes.put(checkNotNull(key, \"key\"), checkNotNull(value, \"value\"));\n         return this;\n      }\n\n      public Builder normalAttributes(Map<String, JsonBall> normalAttributes) {\n         this.normalAttributes.putAll(checkNotNull(normalAttributes, \"normalAttributes\"));\n         return this;\n      }\n\n      public Builder overrideAttribute(String key, JsonBall value) {\n         this.overrideAttributes.put(checkNotNull(key, \"key\"), checkNotNull(value, \"value\"));\n         return this;\n      }\n\n      public Builder overrideAttributes(Map<String, JsonBall> overrideAttributes) {\n         this.overrideAttributes.putAll(checkNotNull(overrideAttributes, \"overrideAttributes\"));\n         return this;\n      }\n\n      public Builder defaultAttribute(String key, JsonBall value) {\n         this.defaultAttributes.put(checkNotNull(key, \"key\"), checkNotNull(value, \"value\"));\n         return this;\n      }\n\n      public Builder defaultAttributes(Map<String, JsonBall> defaultAttributes) {\n         this.defaultAttributes.putAll(checkNotNull(defaultAttributes, \"defaultAttributes\"));\n         return this;\n      }\n\n      public Builder automaticAttribute(String key, JsonBall value) {\n         this.automaticAttributes.put(checkNotNull(key, \"key\"), checkNotNull(value, \"value\"));\n         return this;\n      }\n\n      public Builder automaticAttributes(Map<String, JsonBall> automaticAttribute) {\n         this.automaticAttributes.putAll(checkNotNull(automaticAttribute, \"automaticAttribute\"));\n         return this;\n      }\n\n      public Builder runListElement(String element) {\n         this.runList.add(checkNotNull(element, \"element\"));\n         return this;\n      }\n\n      public Builder runList(Iterable<String> runList) {\n         this.runList.addAll(checkNotNull(runList, \"runList\"));\n         return this;\n      }\n\n      /**\n       * @since Chef 0.10\n       */\n      public Builder environment(String environment) {\n         this.environment = checkNotNull(environment, \"environment\");\n         return this;\n      }\n\n      public Node build() {\n         return new Node(name, normalAttributes.build(), overrideAttributes.build(), defaultAttributes.build(),\n               automaticAttributes.build(), runList.build(), environment);\n      }\n   }\n\n   private final String name;\n   @SerializedName(\"normal\")\n   private final Map<String, JsonBall> normalAttributes;\n   @SerializedName(\"override\")\n   private final Map<String, JsonBall> overrideAttributes;\n   @SerializedName(\"default\")\n   private final Map<String, JsonBall> defaultAttributes;\n   @SerializedName(\"automatic\")\n   private final Map<String, JsonBall> automaticAttributes;\n   @SerializedName(\"run_list\")\n   private final List<String> runList;\n   @SerializedName(\"chef_environment\")\n   private final String environment;\n\n   // internal\n   @SerializedName(\"json_class\")\n   private final String _jsonClass = \"Chef::Node\";\n   @SerializedName(\"chef_type\")\n   private final String _chefType = \"node\";\n\n   @ConstructorProperties({ \"name\", \"normal\", \"override\", \"default\", \"automatic\", \"run_list\", \"chef_environment\" })\n   protected Node(String name, @Nullable Map<String, JsonBall> normalAttributes,\n         @Nullable Map<String, JsonBall> overrideAttributes, @Nullable Map<String, JsonBall> defaultAttributes,\n         @Nullable Map<String, JsonBall> automaticAttributes, List<String> runList, @Nullable String environment) {\n      this.name = name;\n      this.environment = environment;\n      this.normalAttributes = copyOfOrEmpty(normalAttributes);\n      this.overrideAttributes = copyOfOrEmpty(overrideAttributes);\n      this.defaultAttributes = copyOfOrEmpty(defaultAttributes);\n      this.automaticAttributes = copyOfOrEmpty(automaticAttributes);\n      this.runList = copyOfOrEmpty(runList);\n   }\n\n   public String getName() {\n      return name;\n   }\n\n   public Map<String, JsonBall> getNormalAttributes() {\n      return normalAttributes;\n   }\n\n   public Map<String, JsonBall> getOverrideAttributes() {\n      return overrideAttributes;\n   }\n\n   public Map<String, JsonBall> getDefaultAttributes() {\n      return defaultAttributes;\n   }\n\n   public Map<String, JsonBall> getAutomaticAttributes() {\n      return automaticAttributes;\n   }\n\n   public List<String> getRunList() {\n      return runList;\n   }\n\n   /**\n    * @since Chef 0.10\n    */\n   public String getEnvironment() {\n      return environment;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((_chefType == null) ? 0 : _chefType.hashCode());\n      result = prime * result + ((_jsonClass == null) ? 0 : _jsonClass.hashCode());\n      result = prime * result + ((automaticAttributes == null) ? 0 : automaticAttributes.hashCode());\n      result = prime * result + ((defaultAttributes == null) ? 0 : defaultAttributes.hashCode());\n      result = prime * result + ((name == null) ? 0 : name.hashCode());\n      result = prime * result + ((normalAttributes == null) ? 0 : normalAttributes.hashCode());\n      result = prime * result + ((overrideAttributes == null) ? 0 : overrideAttributes.hashCode());\n      result = prime * result + ((runList == null) ? 0 : runList.hashCode());\n      result = prime * result + ((environment == null) ? 0 : environment.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      Node other = (Node) obj;\n      if (_chefType == null) {\n         if (other._chefType != null)\n            return false;\n      } else if (!_chefType.equals(other._chefType))\n         return false;\n      if (_jsonClass == null) {\n         if (other._jsonClass != null)\n            return false;\n      } else if (!_jsonClass.equals(other._jsonClass))\n         return false;\n      if (automaticAttributes == null) {\n         if (other.automaticAttributes != null)\n            return false;\n      } else if (!automaticAttributes.equals(other.automaticAttributes))\n         return false;\n      if (defaultAttributes == null) {\n         if (other.defaultAttributes != null)\n            return false;\n      } else if (!defaultAttributes.equals(other.defaultAttributes))\n         return false;\n      if (name == null) {\n         if (other.name != null)\n            return false;\n      } else if (!name.equals(other.name))\n         return false;\n      if (normalAttributes == null) {\n         if (other.normalAttributes != null)\n            return false;\n      } else if (!normalAttributes.equals(other.normalAttributes))\n         return false;\n      if (overrideAttributes == null) {\n         if (other.overrideAttributes != null)\n            return false;\n      } else if (!overrideAttributes.equals(other.overrideAttributes))\n         return false;\n      if (runList == null) {\n         if (other.runList != null)\n            return false;\n      } else if (!runList.equals(other.runList))\n         return false;\n      if (environment == null) {\n         if (other.environment != null)\n            return false;\n      } else if (!environment.equals(other.environment))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"Node [name=\" + name + \", runList=\" + runList + \", normalAttributes=\" + normalAttributes\n            + \", defaultAttributes=\" + defaultAttributes + \", overrideAttributes=\" + overrideAttributes\n            + \", chefEnvironment=\" + environment + \", automaticAttributes=\" + automaticAttributes + \"]\";\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/domain/Resource.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.net.URI;\nimport java.util.Arrays;\n\nimport org.jclouds.io.payloads.FilePayload;\n\nimport com.google.common.primitives.Bytes;\n\n/**\n * Resource object.\n */\npublic class Resource {\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n      private String name;\n      private URI url;\n      private byte[] checksum;\n      private String path;\n      private String specificity = \"default\";\n\n      public Builder name(String name) {\n         this.name = checkNotNull(name, \"name\");\n         return this;\n      }\n\n      public Builder url(URI url) {\n         this.url = checkNotNull(url, \"url\");\n         return this;\n      }\n\n      public Builder checksum(byte[] checksum) {\n         this.checksum = checkNotNull(checksum, \"checksum\");\n         return this;\n      }\n\n      public Builder path(String path) {\n         this.path = checkNotNull(path, \"path\");\n         return this;\n      }\n\n      public Builder specificity(String specificity) {\n         this.specificity = checkNotNull(specificity, \"specificity\");\n         return this;\n      }\n\n      public Builder fromPayload(FilePayload payload) {\n         checkNotNull(payload, \"payload\");\n         this.name(payload.getRawContent().getName());\n         this.checksum(payload.getContentMetadata().getContentMD5());\n         this.path(payload.getRawContent().getPath());\n         return this;\n      }\n\n      public Resource build() {\n         return new Resource(name, url, checksum, path, specificity);\n      }\n   }\n\n   private final String name;\n   private final URI url;\n   private final byte[] checksum;\n   private final String path;\n   private final String specificity;\n\n   @ConstructorProperties({ \"name\", \"url\", \"checksum\", \"path\", \"specificity\" })\n   protected Resource(String name, URI url, byte[] checksum, String path, String specificity) {\n      this.name = name;\n      this.url = url;\n      this.checksum = checksum;\n      this.path = path;\n      this.specificity = specificity;\n   }\n\n   public String getName() {\n      return name;\n   }\n\n   public URI getUrl() {\n      return url;\n   }\n\n   public byte[] getChecksum() {\n      return checksum;\n   }\n\n   public String getPath() {\n      return path;\n   }\n\n   public String getSpecificity() {\n      return specificity;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + Arrays.hashCode(checksum);\n      result = prime * result + ((name == null) ? 0 : name.hashCode());\n      result = prime * result + ((path == null) ? 0 : path.hashCode());\n      result = prime * result + ((specificity == null) ? 0 : specificity.hashCode());\n      result = prime * result + ((url == null) ? 0 : url.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      Resource other = (Resource) obj;\n      if (!Arrays.equals(checksum, other.checksum))\n         return false;\n      if (name == null) {\n         if (other.name != null)\n            return false;\n      } else if (!name.equals(other.name))\n         return false;\n      if (path == null) {\n         if (other.path != null)\n            return false;\n      } else if (!path.equals(other.path))\n         return false;\n      if (specificity == null) {\n         if (other.specificity != null)\n            return false;\n      } else if (!specificity.equals(other.specificity))\n         return false;\n      if (url == null) {\n         if (other.url != null)\n            return false;\n      } else if (!url.equals(other.url))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"Resource [checksum=\" + Bytes.asList(checksum) + \", name=\" + name + \", path=\" + path + \", specificity=\"\n            + specificity + \", url=\" + url + \"]\";\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/domain/Role.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.chef.util.CollectionUtils.copyOfOrEmpty;\n\nimport java.beans.ConstructorProperties;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.domain.JsonBall;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Maps;\nimport com.google.gson.annotations.SerializedName;\n\n/**\n * Role object.\n */\npublic class Role {\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n      private String name;\n      private String description;\n      private ImmutableMap.Builder<String, JsonBall> overrideAttributes = ImmutableMap.builder();\n      private ImmutableMap.Builder<String, JsonBall> defaultAttributes = ImmutableMap.builder();\n      private ImmutableList.Builder<String> runList = ImmutableList.builder();\n      // envRunList is a nested set of collections. The Immutable* classes in google collections don't appear to\n      // support this nested immutability, so the builder will utilize native collections as the envRunList is\n      // assembled. An immutable, nested map of collections will be assembled in the build() method.\n      private Map<String, List<String>> envRunList = new HashMap<String, List<String>>();\n\n      public Builder name(String name) {\n         this.name = checkNotNull(name, \"name\");\n         return this;\n      }\n\n      public Builder description(String description) {\n         this.description = checkNotNull(description, \"description\");\n         return this;\n      }\n\n      public Builder overrideAttribute(String key, JsonBall value) {\n         this.overrideAttributes.put(checkNotNull(key, \"key\"), checkNotNull(value, \"value\"));\n         return this;\n      }\n\n      public Builder overrideAttributes(Map<String, JsonBall> overrideAttributes) {\n         this.overrideAttributes.putAll(checkNotNull(overrideAttributes, \"overrideAttributes\"));\n         return this;\n      }\n\n      public Builder defaultAttribute(String key, JsonBall value) {\n         this.defaultAttributes.put(checkNotNull(key, \"key\"), checkNotNull(value, \"value\"));\n         return this;\n      }\n\n      public Builder defaultAttributes(Map<String, JsonBall> defaultAttributes) {\n         this.defaultAttributes.putAll(checkNotNull(defaultAttributes, \"defaultAttributes\"));\n         return this;\n      }\n\n      public Builder runListElement(String element) {\n         this.runList.add(checkNotNull(element, \"element\"));\n         return this;\n      }\n\n      public Builder runList(Iterable<String> runList) {\n         this.runList.addAll(checkNotNull(runList, \"runList\"));\n         return this;\n      }\n\n      public Builder envRunList(Map<String, List<String>> envRunList) {\n         this.envRunList.putAll(checkNotNull(envRunList, \"envRunList\"));\n         return this;\n      }\n\n      public Builder envRunList(String name, List<String> runList) {\n         this.envRunList.put(checkNotNull(name, \"name\"), checkNotNull(runList, \"runList\"));\n         return this;\n      }\n\n      public Builder envRunListElement(String name, String value) {\n         checkNotNull(name, \"name\");\n         checkNotNull(value, \"value\");\n         List<String> runList = this.envRunList.get(name);\n         if (runList == null) {\n            runList = new ArrayList<String>();\n            this.envRunList.put(name, runList);\n         }\n         runList.add(value);\n         return this;\n      }\n\n      public Role build() {\n         // Assemble an immutable envRunList where each entry is an immutable list of entries.\n         Map<String, List<String>> immutableEnvRunList = Maps.transformValues(envRunList,\n               new Function<List<String>, List<String>>() {\n                  @Override\n                  public List<String> apply(List<String> input) {\n                     return ImmutableList.copyOf(input);\n                  }\n               });\n         \n         return new Role(name, description, defaultAttributes.build(), runList.build(), overrideAttributes.build(), \n               immutableEnvRunList);\n      }\n   }\n\n   private final String name;\n   private final String description;\n   @SerializedName(\"override_attributes\")\n   private final Map<String, JsonBall> overrideAttributes;\n   @SerializedName(\"default_attributes\")\n   private final Map<String, JsonBall> defaultAttributes;\n   @SerializedName(\"run_list\")\n   private final List<String> runList;\n   @SerializedName(\"env_run_lists\")\n   private Map<String, List<String>> envRunList;\n\n   // internal\n   @SerializedName(\"json_class\")\n   private final String _jsonClass = \"Chef::Role\";\n   @SerializedName(\"chef_type\")\n   private final String _chefType = \"role\";\n\n   @ConstructorProperties({ \"name\", \"description\", \"default_attributes\", \"run_list\", \"override_attributes\", \n      \"env_run_lists\"  })\n   protected Role(String name, String description, @Nullable Map<String, JsonBall> defaultAttributes,\n         @Nullable List<String> runList, @Nullable Map<String, JsonBall> overrideAttributes,\n         @Nullable Map<String, List<String>> envRunList) {\n      this.name = name;\n      this.description = description;\n      this.defaultAttributes = copyOfOrEmpty(defaultAttributes);\n      this.runList = copyOfOrEmpty(runList);\n      this.overrideAttributes = copyOfOrEmpty(overrideAttributes);\n      this.envRunList = envRunList;\n   }\n\n   public String getName() {\n      return name;\n   }\n\n   public String getDescription() {\n      return description;\n   }\n\n   public Map<String, JsonBall> getOverrideAttributes() {\n      return overrideAttributes;\n   }\n\n   public Map<String, JsonBall> getDefaultAttributes() {\n      return defaultAttributes;\n   }\n\n   public List<String> getRunList() {\n      return runList;\n   }\n\n   public Map<String, List<String>> getEnvRunList() {\n      return envRunList;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((_chefType == null) ? 0 : _chefType.hashCode());\n      result = prime * result + ((_jsonClass == null) ? 0 : _jsonClass.hashCode());\n      result = prime * result + ((defaultAttributes == null) ? 0 : defaultAttributes.hashCode());\n      result = prime * result + ((description == null) ? 0 : description.hashCode());\n      result = prime * result + ((name == null) ? 0 : name.hashCode());\n      result = prime * result + ((overrideAttributes == null) ? 0 : overrideAttributes.hashCode());\n      result = prime * result + ((runList == null) ? 0 : runList.hashCode());\n      result = prime * result + ((envRunList == null) ? 0 : envRunList.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      Role other = (Role) obj;\n      if (_chefType == null) {\n         if (other._chefType != null)\n            return false;\n      } else if (!_chefType.equals(other._chefType))\n         return false;\n      if (_jsonClass == null) {\n         if (other._jsonClass != null)\n            return false;\n      } else if (!_jsonClass.equals(other._jsonClass))\n         return false;\n      if (defaultAttributes == null) {\n         if (other.defaultAttributes != null)\n            return false;\n      } else if (!defaultAttributes.equals(other.defaultAttributes))\n         return false;\n      if (description == null) {\n         if (other.description != null)\n            return false;\n      } else if (!description.equals(other.description))\n         return false;\n      if (name == null) {\n         if (other.name != null)\n            return false;\n      } else if (!name.equals(other.name))\n         return false;\n      if (overrideAttributes == null) {\n         if (other.overrideAttributes != null)\n            return false;\n      } else if (!overrideAttributes.equals(other.overrideAttributes))\n         return false;\n      if (runList == null) {\n         if (other.runList != null)\n            return false;\n      } else if (!runList.equals(other.runList))\n         return false;\n      if (envRunList == null) {\n         if (other.envRunList != null)\n            return false;\n      } else if (!envRunList.equals(other.envRunList))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"Role [name=\" + name + \", description=\" + description + \", defaultAttributes=\" + defaultAttributes\n            + \", overrideAttributes=\" + overrideAttributes + \", runList=\" + runList\n            + \", envRunList=\" + this.envRunList + \"]\";\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/domain/Sandbox.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.chef.util.CollectionUtils.copyOfOrEmpty;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.gson.annotations.SerializedName;\n\n/**\n * Sandbox object.\n */\npublic class Sandbox {\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n      private String rev;\n      private boolean isCompleted;\n      private Date createTime;\n      private ImmutableSet.Builder<String> checksums = ImmutableSet.builder();\n      private String name;\n      private String guid;\n\n      public Builder rev(String rev) {\n         this.rev = checkNotNull(rev, \"rev\");\n         return this;\n      }\n\n      public Builder isCompleted(boolean isCompleted) {\n         this.isCompleted = isCompleted;\n         return this;\n      }\n\n      public Builder createTime(Date createTime) {\n         this.createTime = createTime;\n         return this;\n      }\n\n      public Builder checksum(String checksum) {\n         this.checksums.add(checkNotNull(checksum, \"checksum\"));\n         return this;\n      }\n\n      public Builder checksums(Iterable<String> checksums) {\n         this.checksums.addAll(checkNotNull(checksums, \"checksums\"));\n         return this;\n      }\n\n      public Builder name(String name) {\n         this.name = checkNotNull(name, \"name\");\n         return this;\n      }\n\n      public Builder guid(String guid) {\n         this.guid = checkNotNull(guid, \"guid\");\n         return this;\n      }\n\n      public Sandbox build() {\n         return new Sandbox(rev, isCompleted, createTime, checksums.build(), name, guid);\n      }\n   }\n\n   @SerializedName(\"_rev\")\n   private final String rev;\n   @SerializedName(\"is_completed\")\n   private final boolean isCompleted;\n   @SerializedName(\"create_time\")\n   private final Date createTime;\n   private final Set<String> checksums;\n   private final String name;\n   private final String guid;\n\n   // internal\n   @SerializedName(\"json_class\")\n   private final String _jsonClass = \"Chef::Sandbox\";\n   @SerializedName(\"chef_type\")\n   private final String _chefType = \"sandbox\";\n\n   @ConstructorProperties({ \"_rev\", \"is_completed\", \"create_time\", \"checksums\", \"name\", \"guid\" })\n   protected Sandbox(String rev, boolean isCompleted, Date createTime, @Nullable Set<String> checksums, String name,\n         String guid) {\n      this.rev = rev;\n      this.isCompleted = isCompleted;\n      this.createTime = createTime;\n      this.checksums = copyOfOrEmpty(checksums);\n      this.name = name;\n      this.guid = guid;\n   }\n\n   public String getRev() {\n      return rev;\n   }\n\n   public boolean isCompleted() {\n      return isCompleted;\n   }\n\n   public Date getCreateTime() {\n      return createTime;\n   }\n\n   public Set<String> getChecksums() {\n      return checksums;\n   }\n\n   public String getName() {\n      return name;\n   }\n\n   public String getGuid() {\n      return guid;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((checksums == null) ? 0 : checksums.hashCode());\n      result = prime * result + ((createTime == null) ? 0 : createTime.hashCode());\n      result = prime * result + ((guid == null) ? 0 : guid.hashCode());\n      result = prime * result + (isCompleted ? 1231 : 1237);\n      result = prime * result + ((name == null) ? 0 : name.hashCode());\n      result = prime * result + ((rev == null) ? 0 : rev.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      Sandbox other = (Sandbox) obj;\n      if (checksums == null) {\n         if (other.checksums != null)\n            return false;\n      } else if (!checksums.equals(other.checksums))\n         return false;\n      if (createTime == null) {\n         if (other.createTime != null)\n            return false;\n      } else if (!createTime.equals(other.createTime))\n         return false;\n      if (guid == null) {\n         if (other.guid != null)\n            return false;\n      } else if (!guid.equals(other.guid))\n         return false;\n      if (isCompleted != other.isCompleted)\n         return false;\n      if (name == null) {\n         if (other.name != null)\n            return false;\n      } else if (!name.equals(other.name))\n         return false;\n      if (rev == null) {\n         if (other.rev != null)\n            return false;\n      } else if (!rev.equals(other.rev))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"Sandbox [checksums=\" + checksums + \", createTime=\" + createTime + \", guid=\" + guid + \", isCompleted=\"\n            + isCompleted + \", name=\" + name + \", rev=\" + rev + \"]\";\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/domain/SearchResult.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.domain;\n\nimport java.util.LinkedHashSet;\n\nimport com.google.common.collect.Iterables;\n\n/**\n * A result of a search.\n */\npublic class SearchResult<T> extends LinkedHashSet<T> {\n   private static final long serialVersionUID = 4000610660948065287L;\n   private long start;\n\n   SearchResult() {\n   }\n\n   public SearchResult(long start, Iterable<T> results) {\n      this.start = start;\n      Iterables.addAll(this, results);\n   }\n\n   /**\n    * \n    * @return the result position this started from from\n    */\n   long getStart() {\n      return start;\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/domain/UploadSandbox.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.chef.util.CollectionUtils.copyOfOrEmpty;\n\nimport java.beans.ConstructorProperties;\nimport java.net.URI;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.gson.annotations.SerializedName;\n\n/**\n * An upload sandbox.\n */\npublic class UploadSandbox {\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n      private URI uri;\n      private ImmutableMap.Builder<List<Byte>, ChecksumStatus> checksums = ImmutableMap.builder();\n      private String sandboxId;\n\n      public Builder uri(URI uri) {\n         this.uri = checkNotNull(uri, \"uri\");\n         return this;\n      }\n\n      public Builder checksum(List<Byte> key, ChecksumStatus value) {\n         this.checksums.put(checkNotNull(key, \"key\"), checkNotNull(value, \"value\"));\n         return this;\n      }\n\n      public Builder checksums(Map<List<Byte>, ChecksumStatus> checksums) {\n         this.checksums.putAll(checkNotNull(checksums, \"checksums\"));\n         return this;\n      }\n\n      public Builder sandboxId(String sandboxId) {\n         this.sandboxId = checkNotNull(sandboxId, \"sandboxId\");\n         return this;\n      }\n\n      public UploadSandbox build() {\n         return new UploadSandbox(uri, checksums.build(), sandboxId);\n      }\n   }\n\n   private final URI uri;\n   private final Map<List<Byte>, ChecksumStatus> checksums;\n   @SerializedName(\"sandbox_id\")\n   private final String sandboxId;\n\n   @ConstructorProperties({ \"uri\", \"checksums\", \"sandbox_id\" })\n   protected UploadSandbox(URI uri, @Nullable Map<List<Byte>, ChecksumStatus> checksums, String sandboxId) {\n      this.uri = uri;\n      this.checksums = copyOfOrEmpty(checksums);\n      this.sandboxId = sandboxId;\n   }\n\n   public URI getUri() {\n      return uri;\n   }\n\n   public Map<List<Byte>, ChecksumStatus> getChecksums() {\n      return checksums;\n   }\n\n   public String getSandboxId() {\n      return sandboxId;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((checksums == null) ? 0 : checksums.hashCode());\n      result = prime * result + ((sandboxId == null) ? 0 : sandboxId.hashCode());\n      result = prime * result + ((uri == null) ? 0 : uri.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      UploadSandbox other = (UploadSandbox) obj;\n      if (checksums == null) {\n         if (other.checksums != null)\n            return false;\n      } else if (!checksums.equals(other.checksums))\n         return false;\n      if (sandboxId == null) {\n         if (other.sandboxId != null)\n            return false;\n      } else if (!sandboxId.equals(other.sandboxId))\n         return false;\n      if (uri == null) {\n         if (other.uri != null)\n            return false;\n      } else if (!uri.equals(other.uri))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"UploadSandbox [checksums=\" + checksums + \", id=\" + sandboxId + \", uri=\" + uri + \"]\";\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/domain/User.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.security.PublicKey;\n\nimport com.google.gson.annotations.SerializedName;\n\n/**\n * User object.\n */\npublic class User {\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n      private String username;\n      private String firstName;\n      private String middleName;\n      private String lastName;\n      private String displayName;\n      private String email;\n      private PublicKey publicKey;\n\n      public Builder username(String username) {\n         this.username = checkNotNull(username, \"username\");\n         return this;\n      }\n\n      public Builder firstName(String firstName) {\n         this.firstName = checkNotNull(firstName, \"firstName\");\n         return this;\n      }\n\n      public Builder middleName(String middleName) {\n         this.middleName = checkNotNull(middleName, \"middleName\");\n         return this;\n      }\n\n      public Builder lastName(String lastName) {\n         this.lastName = checkNotNull(lastName, \"lastName\");\n         return this;\n      }\n\n      public Builder displayName(String displayName) {\n         this.displayName = checkNotNull(displayName, \"displayName\");\n         return this;\n      }\n\n      public Builder email(String email) {\n         this.email = checkNotNull(email, \"email\");\n         return this;\n      }\n\n      public Builder publicKey(PublicKey publicKey) {\n         this.publicKey = checkNotNull(publicKey, \"publicKey\");\n         return this;\n      }\n\n      public User build() {\n         return new User(username, firstName, middleName, lastName, displayName, email, publicKey);\n      }\n   }\n\n   private final String username;\n   @SerializedName(\"first_name\")\n   private final String firstName;\n   @SerializedName(\"middle_name\")\n   private final String middleName;\n   @SerializedName(\"last_name\")\n   private final String lastName;\n   @SerializedName(\"display_name\")\n   private final String displayName;\n   private final String email;\n   @SerializedName(\"public_key\")\n   private final PublicKey publicKey;\n\n   @ConstructorProperties({ \"username\", \"first_name\", \"middle_name\", \"last_name\", \"display_name\", \"email\", \"public_key\" })\n   protected User(String username, String firstName, String middleName, String lastName, String displayName,\n         String email, PublicKey publicKey) {\n      this.username = username;\n      this.firstName = firstName;\n      this.middleName = middleName;\n      this.lastName = lastName;\n      this.displayName = displayName;\n      this.email = email;\n      this.publicKey = publicKey;\n   }\n\n   public String getUsername() {\n      return username;\n   }\n\n   public String getFirstName() {\n      return firstName;\n   }\n\n   public String getMiddleName() {\n      return middleName;\n   }\n\n   public String getLastName() {\n      return lastName;\n   }\n\n   public String getDisplayName() {\n      return displayName;\n   }\n\n   public String getEmail() {\n      return email;\n   }\n\n   public PublicKey getPublicKey() {\n      return publicKey;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + (displayName == null ? 0 : displayName.hashCode());\n      result = prime * result + (email == null ? 0 : email.hashCode());\n      result = prime * result + (firstName == null ? 0 : firstName.hashCode());\n      result = prime * result + (lastName == null ? 0 : lastName.hashCode());\n      result = prime * result + (middleName == null ? 0 : middleName.hashCode());\n      result = prime * result + (publicKey == null ? 0 : publicKey.hashCode());\n      result = prime * result + (username == null ? 0 : username.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) {\n         return true;\n      }\n      if (obj == null) {\n         return false;\n      }\n      if (getClass() != obj.getClass()) {\n         return false;\n      }\n      User other = (User) obj;\n      if (displayName == null) {\n         if (other.displayName != null) {\n            return false;\n         }\n      } else if (!displayName.equals(other.displayName)) {\n         return false;\n      }\n      if (email == null) {\n         if (other.email != null) {\n            return false;\n         }\n      } else if (!email.equals(other.email)) {\n         return false;\n      }\n      if (firstName == null) {\n         if (other.firstName != null) {\n            return false;\n         }\n      } else if (!firstName.equals(other.firstName)) {\n         return false;\n      }\n      if (lastName == null) {\n         if (other.lastName != null) {\n            return false;\n         }\n      } else if (!lastName.equals(other.lastName)) {\n         return false;\n      }\n      if (middleName == null) {\n         if (other.middleName != null) {\n            return false;\n         }\n      } else if (!middleName.equals(other.middleName)) {\n         return false;\n      }\n      if (publicKey == null) {\n         if (other.publicKey != null) {\n            return false;\n         }\n      } else if (!publicKey.equals(other.publicKey)) {\n         return false;\n      }\n      if (username == null) {\n         if (other.username != null) {\n            return false;\n         }\n      } else if (!username.equals(other.username)) {\n         return false;\n      }\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"User [username=\" + username + \", firstName=\" + firstName + \", middleName=\" + middleName + \", lastName=\"\n            + lastName + \", displayName=\" + displayName + \", email=\" + email + \", publicKey=\" + publicKey + \"]\";\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/features/OrganizationApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.features;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Constants;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.chef.ChefApi;\nimport org.jclouds.chef.binders.BindGroupToUpdateRequestJsonPayload;\nimport org.jclouds.chef.binders.GroupName;\nimport org.jclouds.chef.domain.Group;\nimport org.jclouds.chef.domain.User;\nimport org.jclouds.chef.filters.SignedHeaderAuth;\nimport org.jclouds.chef.functions.ParseKeySetFromJson;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.Headers;\nimport org.jclouds.rest.annotations.ParamParser;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SinceApiVersion;\nimport org.jclouds.rest.annotations.WrapWith;\n\n/**\n * Provides synchronous access to the Enterprise Chef Api.\n */\n@RequestFilters(SignedHeaderAuth.class)\n@Consumes(MediaType.APPLICATION_JSON)\n@Headers(keys = \"X-Chef-Version\", values = \"{\" + Constants.PROPERTY_API_VERSION + \"}\")\n@SinceApiVersion(\"12.0.0\")\npublic interface OrganizationApi extends ChefApi {\n   /**\n    * Retrieves an existing user.\n    * \n    * @param name\n    *           The name of the user to get.\n    * @return The details of the user or <code>null</code> if not found.\n    */\n   @Named(\"user:get\")\n   @GET\n   @Path(\"/users/{name}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   User getUser(@PathParam(\"name\") String name);\n\n   /**\n    * List all existing groups.\n    * \n    * @return The list of groups.\n    */\n   @Named(\"group:list\")\n   @GET\n   @Path(\"/groups\")\n   @ResponseParser(ParseKeySetFromJson.class)\n   Set<String> listGroups();\n\n   /**\n    * Retrieves an existing group.\n    * \n    * @param name\n    *           The name of the group to get.\n    * @return The details of the group or <code>null</code> if not found.\n    */\n   @Named(\"group:get\")\n   @GET\n   @Path(\"/groups/{name}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   Group getGroup(@PathParam(\"name\") String name);\n\n   /**\n    * Creates a new group.\n    * \n    * @param name\n    *           The name of the group to create.\n    */\n   @Named(\"group:create\")\n   @POST\n   @Path(\"/groups\")\n   void createGroup(@WrapWith(\"groupname\") String name);\n\n   /**\n    * Updates a group.\n    * <p>\n    * This method can be used to add actors (clients, groups) to the group.\n    * \n    * @param group\n    *           The group with the updated information.\n    */\n   @Named(\"group:update\")\n   @PUT\n   @Path(\"/groups/{name}\")\n   void updateGroup(\n         @PathParam(\"name\") @ParamParser(GroupName.class) @BinderParam(BindGroupToUpdateRequestJsonPayload.class) Group group);\n\n   /**\n    * Deletes a group.\n    * \n    * @param name\n    *           The name of the group to delete.\n    */\n   @Named(\"group:delete\")\n   @DELETE\n   @Path(\"/groups/{name}\")\n   void deleteGroup(@PathParam(\"name\") String name);\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/filters/SignedHeaderAuth.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.filters;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.hash.Hashing.sha1;\nimport static com.google.common.io.BaseEncoding.base64;\n\nimport java.io.IOException;\nimport java.security.PrivateKey;\nimport java.util.NoSuchElementException;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Provider;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Constants;\nimport org.jclouds.crypto.Crypto;\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpRequestFilter;\nimport org.jclouds.http.HttpUtils;\nimport org.jclouds.http.internal.SignatureWire;\nimport org.jclouds.io.ByteStreams2;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.io.payloads.MultipartForm;\nimport org.jclouds.io.payloads.Part;\nimport org.jclouds.io.payloads.RSAEncryptingPayload;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.util.Strings2;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Splitter;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Throwables;\nimport com.google.common.collect.ArrayListMultimap;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Multimap;\nimport com.google.common.io.ByteSource;\n\n/**\n * Ported from mixlib-authentication in order to sign Chef requests.\n * \n * @see <a href= \"https://github.com/chef/mixlib-authentication\" />\n */\n@Singleton\npublic class SignedHeaderAuth implements HttpRequestFilter {\n   public static final String SIGNING_DESCRIPTION = \"version=1.0\";\n\n   private final SignatureWire signatureWire;\n   private final Supplier<Credentials> creds;\n   private final Supplier<PrivateKey> supplyKey;\n   private final Provider<String> timeStampProvider;\n   private final String emptyStringHash;\n   private final HttpUtils utils;\n   private final Crypto crypto;\n\n   @Resource\n   @Named(Constants.LOGGER_SIGNATURE)\n   Logger signatureLog = Logger.NULL;\n\n   @Inject\n   public SignedHeaderAuth(SignatureWire signatureWire, @org.jclouds.location.Provider Supplier<Credentials> creds,\n         Supplier<PrivateKey> supplyKey, @TimeStamp Provider<String> timeStampProvider, HttpUtils utils, Crypto crypto) {\n      this.signatureWire = checkNotNull(signatureWire, \"signatureWire\");\n      this.creds = checkNotNull(creds, \"creds\");\n      this.supplyKey = checkNotNull(supplyKey, \"supplyKey\");\n      this.timeStampProvider = checkNotNull(timeStampProvider, \"timeStampProvider\");\n      this.emptyStringHash = hashBody(Payloads.newStringPayload(\"\"));\n      this.utils = checkNotNull(utils, \"utils\");\n      this.crypto = checkNotNull(crypto, \"crypto\");\n   }\n\n   public HttpRequest filter(HttpRequest input) throws HttpException {\n      HttpRequest request = input.toBuilder().endpoint(input.getEndpoint().toString().replace(\"%3F\", \"?\")).build();\n      String contentHash = hashBody(request.getPayload());\n      Multimap<String, String> headers = ArrayListMultimap.create();\n      headers.put(\"X-Ops-Content-Hash\", contentHash);\n      String timestamp = timeStampProvider.get();\n      String toSign = createStringToSign(request.getMethod(), hashPath(request.getEndpoint().getPath()), contentHash,\n            timestamp);\n      headers.put(\"X-Ops-Userid\", creds.get().identity);\n      headers.put(\"X-Ops-Sign\", SIGNING_DESCRIPTION);\n      request = calculateAndReplaceAuthorizationHeaders(request, toSign);\n      headers.put(\"X-Ops-Timestamp\", timestamp);\n      utils.logRequest(signatureLog, request, \"<<\");\n\n      return request.toBuilder().replaceHeaders(headers).build();\n   }\n\n   @VisibleForTesting\n   HttpRequest calculateAndReplaceAuthorizationHeaders(HttpRequest request, String toSign) throws HttpException {\n      String signature = sign(toSign);\n      if (signatureWire.enabled())\n         signatureWire.input(Strings2.toInputStream(signature));\n      String[] signatureLines = Iterables.toArray(Splitter.fixedLength(60).split(signature), String.class);\n\n      Multimap<String, String> headers = ArrayListMultimap.create();\n      for (int i = 0; i < signatureLines.length; i++) {\n         headers.put(\"X-Ops-Authorization-\" + (i + 1), signatureLines[i]);\n      }\n      return request.toBuilder().replaceHeaders(headers).build();\n   }\n\n   public String createStringToSign(String request, String hashedPath, String contentHash, String timestamp) {\n\n      return new StringBuilder().append(\"Method:\").append(request).append(\"\\n\").append(\"Hashed Path:\")\n            .append(hashedPath).append(\"\\n\").append(\"X-Ops-Content-Hash:\").append(contentHash).append(\"\\n\")\n            .append(\"X-Ops-Timestamp:\").append(timestamp).append(\"\\n\").append(\"X-Ops-UserId:\")\n            .append(creds.get().identity).toString();\n\n   }\n\n   @VisibleForTesting\n   String hashPath(String path) {\n      try {\n         return base64().encode(ByteSource.wrap(canonicalPath(path).getBytes(UTF_8)).hash(sha1()).asBytes());\n      } catch (Exception e) {\n         Throwables.propagateIfPossible(e);\n         throw new HttpException(\"error creating sigature for path: \" + path, e);\n      }\n   }\n\n   /**\n    * Build the canonicalized path, which collapses multiple slashes (/) and\n    * removes a trailing slash unless the path is only \"/\"\n    */\n   @VisibleForTesting\n   String canonicalPath(String path) {\n      path = path.replaceAll(\"\\\\/+\", \"/\");\n      return path.endsWith(\"/\") && path.length() > 1 ? path.substring(0, path.length() - 1) : path;\n   }\n\n   @VisibleForTesting\n   String hashBody(Payload payload) {\n      if (payload == null)\n         return emptyStringHash;\n      payload = useTheFilePartIfForm(payload);\n      checkArgument(payload != null, \"payload was null\");\n      checkArgument(payload.isRepeatable(), \"payload must be repeatable: \" + payload);\n      try {\n         return base64().encode(ByteStreams2.hashAndClose(payload.getInput(), sha1()).asBytes());\n      } catch (Exception e) {\n         Throwables.propagateIfPossible(e);\n         throw new HttpException(\"error creating sigature for payload: \" + payload, e);\n      }\n   }\n\n   private Payload useTheFilePartIfForm(Payload payload) {\n      if (payload instanceof MultipartForm) {\n         Iterable<? extends Part> parts = MultipartForm.class.cast(payload).getRawContent();\n         try {\n            payload = Iterables.find(parts, new Predicate<Part>() {\n\n               @Override\n               public boolean apply(Part input) {\n                  return \"file\".equals(input.getName());\n               }\n\n            });\n         } catch (NoSuchElementException e) {\n\n         }\n      }\n      return payload;\n   }\n\n   public String sign(String toSign) {\n      try {\n         byte[] encrypted = ByteStreams2.toByteArrayAndClose(new RSAEncryptingPayload(crypto, Payloads.newStringPayload(toSign), supplyKey.get()).openStream());\n         return base64().encode(encrypted);\n      } catch (IOException e) {\n         throw new HttpException(\"error signing request\", e);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/functions/BootstrapConfigForGroup.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.functions;\n\nimport static com.google.common.base.Preconditions.checkState;\nimport static org.jclouds.chef.config.ChefProperties.CHEF_BOOTSTRAP_DATABAG;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.chef.ChefApi;\nimport org.jclouds.chef.domain.BootstrapConfig;\nimport org.jclouds.chef.domain.DatabagItem;\nimport org.jclouds.json.Json;\n\nimport com.google.common.base.Function;\n\n/**\n * Retrieves the bootstrap configuration for a specific group\n */\n@Singleton\npublic class BootstrapConfigForGroup implements Function<String, BootstrapConfig> {\n   \n   private final ChefApi api;\n   private final String databag;\n   private final Json json;\n\n   @Inject\n   BootstrapConfigForGroup(@Named(CHEF_BOOTSTRAP_DATABAG) String databag, ChefApi api, Json json) {\n      this.databag = databag;\n      this.api = api;\n      this.json = json;\n   }\n\n   @Override\n   public BootstrapConfig apply(String from) {\n      DatabagItem bootstrapConfig = api.getDatabagItem(databag, from);\n      checkState(bootstrapConfig != null, \"databag item %s/%s not found\", databag, from);\n      // A DatabagItem is already a JsonBall, to we can easily deserialize it\n      return json.fromJson(bootstrapConfig.toString(), BootstrapConfig.class);\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/functions/ClientForGroup.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Sets.newHashSet;\n\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.chef.ChefApi;\nimport org.jclouds.chef.domain.Client;\n\nimport com.google.common.base.Function;\n\n/**\n * \n * Generates a client relevant for a particular group\n */\n@Singleton\npublic class ClientForGroup implements Function<String, Client> {\n   private final ChefApi chefApi;\n\n   @Inject\n   public ClientForGroup(ChefApi chefApi) {\n      this.chefApi = checkNotNull(chefApi, \"chefApi\");\n   }\n\n   @Override\n   public Client apply(String from) {\n      String clientName = findNextClientName(chefApi.listClients(), from + \"-client-%02d\");\n      Client client = chefApi.createClient(clientName);\n      // response from create only includes the key\n      return Client.builder() //\n            .clientname(clientName) //\n            .name(clientName) //\n            .isValidator(false) //\n            .privateKey(client.getPrivateKey()) //\n            .build();\n   }\n\n   private static String findNextClientName(Set<String> clients, String pattern) {\n      String clientName;\n      Set<String> names = newHashSet(clients);\n      int index = 0;\n      while (true) {\n         clientName = String.format(pattern, index++);\n         if (!names.contains(clientName))\n            break;\n      }\n      return clientName;\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/functions/GroupToBootScript.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.transform;\nimport static org.jclouds.scriptbuilder.domain.Statements.createOrOverwriteFile;\nimport static org.jclouds.scriptbuilder.domain.Statements.exec;\n\nimport java.net.URI;\nimport java.security.PrivateKey;\nimport java.util.Collections;\nimport java.util.regex.Pattern;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.chef.config.InstallChef;\nimport org.jclouds.chef.config.Validator;\nimport org.jclouds.chef.domain.BootstrapConfig;\nimport org.jclouds.crypto.Pems;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.location.Provider;\nimport org.jclouds.scriptbuilder.ExitInsteadOfReturn;\nimport org.jclouds.scriptbuilder.domain.Statement;\nimport org.jclouds.scriptbuilder.domain.StatementList;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Joiner;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Splitter;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Throwables;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Generates a bootstrap script relevant for a particular group\n */\n@Singleton\npublic class GroupToBootScript {\n   private static final Pattern newLinePattern = Pattern.compile(\"(\\\\r\\\\n)|(\\\\n)\");\n\n   private final Supplier<URI> endpoint;\n   private final CacheLoader<String, BootstrapConfig> bootstrapConfigForGroup;\n   private final Statement installChef;\n   private final Optional<String> validatorName;\n   private final Optional<PrivateKey> validatorCredential;\n\n   @Inject\n   GroupToBootScript(@Provider Supplier<URI> endpoint, CacheLoader<String, BootstrapConfig> bootstrapConfigForGroup,\n         @InstallChef Statement installChef, @Validator Optional<String> validatorName,\n         @Validator Optional<PrivateKey> validatorCredential) {\n      this.endpoint = endpoint;\n      this.bootstrapConfigForGroup = bootstrapConfigForGroup;\n      this.installChef = installChef;\n      this.validatorName = validatorName;\n      this.validatorCredential = validatorCredential;\n   }\n\n   public Statement apply(String group, @Nullable String nodeName) {\n      BootstrapConfig config = null;\n      try {\n         config = bootstrapConfigForGroup.load(checkNotNull(group, \"group\"));\n      } catch (Exception ex) {\n         throw Throwables.propagate(ex);\n      }\n\n      String chefConfigDir = \"{root}etc{fs}chef\";\n      String chefBootFile = chefConfigDir + \"{fs}first-boot.json\";\n\n      ImmutableList.Builder<Statement> statements = ImmutableList.builder();\n      statements.add(new ExitInsteadOfReturn(installChef));\n      statements.add(exec(\"{md} \" + chefConfigDir));\n      if (config.getSslCAFile() != null) {\n         statements.add(createOrOverwriteFile(chefConfigDir + \"{fs}chef-server.crt\",\n               Splitter.on(newLinePattern).split(config.getSslCAFile())));\n      }\n      statements.add(createClientRbFile(chefConfigDir + \"{fs}client.rb\", group, nodeName, config));\n      statements.add(createOrOverwriteFile(chefConfigDir + \"{fs}validation.pem\",\n            Splitter.on(newLinePattern).split(Pems.pem(validatorCredential.get()))));\n      statements.add(createAttributesFile(chefBootFile, config));\n      statements.add(exec(\"chef-client -j \" + chefBootFile));\n\n      return new StatementList(statements.build());\n   }\n\n   private Statement createClientRbFile(String clientRbFile, String group, String nodeName, BootstrapConfig config) {\n      ImmutableList.Builder<String> clientRb = ImmutableList.builder();\n      clientRb.add(\"require 'rubygems'\");\n      clientRb.add(\"require 'ohai'\");\n      clientRb.add(\"o = Ohai::System.new\");\n      clientRb.add(\"o.all_plugins\");\n      clientRb.add(\"node_name \\\"\" + (nodeName != null ? nodeName + \"\\\"\" : group + \"-\\\" + o[:ipaddress]\"));\n      clientRb.add(\"log_level :info\");\n      clientRb.add(\"log_location STDOUT\");\n      clientRb.add(String.format(\"validation_client_name \\\"%s\\\"\", validatorName.get()));\n      clientRb.add(String.format(\"chef_server_url \\\"%s\\\"\", endpoint.get()));\n      addIfPresent(clientRb, \"environment\", config.getEnvironment());\n      if (config.getSslCAFile() != null) {\n         addIfPresent(clientRb, \"ssl_ca_file\", \"/etc/chef/chef-server.crt\");\n      }\n      addIfPresent(clientRb, \"ssl_ca_path\", config.getSslCAPath());\n      addIfPresent(clientRb, \"ssl_verify_mode\", config.getSslVerifyMode());\n      addIfPresent(clientRb, \"verify_api_cert\", config.getVerifyApiCert());\n      return createOrOverwriteFile(clientRbFile, clientRb.build());\n   }\n\n   private Statement createAttributesFile(String chefBootFile, BootstrapConfig config) {\n      String runlist = Joiner.on(',').join(transform(config.getRunList(), new Function<String, String>() {\n         @Override\n         public String apply(String input) {\n            return \"\\\"\" + input + \"\\\"\";\n         }\n      }));\n\n      StringBuilder sb = new StringBuilder();\n      sb.append(\"{\");\n\n      if (config.getAttributes() != null) {\n         String attributes = config.getAttributes().toString();\n         // Omit the opening and closing json characters\n         sb.append(attributes.trim().substring(1, attributes.length() - 1));\n         sb.append(\",\");\n      }\n\n      sb.append(\"\\\"run_list\\\":[\").append(runlist).append(\"]\");\n      sb.append(\"}\");\n\n      return createOrOverwriteFile(chefBootFile, Collections.singleton(sb.toString()));\n   }\n\n   private void addIfPresent(ImmutableList.Builder<String> lines, String key, Object value) {\n      if (value != null) {\n         // Quote the value if it is a String\n         lines.add(String.format(\"%s %s\", key, value instanceof String ? \"\\\"\" + value + \"\\\"\" : value.toString()));\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/functions/ParseCookbookDefinitionFromJson.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.functions;\n\nimport com.google.common.base.Function;\nimport org.jclouds.chef.domain.CookbookDefinition;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseJson;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\nimport java.util.Map;\n\n/**\n * Parses the cookbook versions in a Chef Server >= 0.10.8.\n */\n@Singleton\npublic class ParseCookbookDefinitionFromJson implements Function<HttpResponse, CookbookDefinition> {\n\n   /** Parser for responses from chef server >= 0.10.8 */\n   private final ParseJson<Map<String, CookbookDefinition>> parser;\n\n   @Inject\n   ParseCookbookDefinitionFromJson(ParseJson<Map<String, CookbookDefinition>> parser) {\n      this.parser = parser;\n   }\n\n   @Override\n   public CookbookDefinition apply(HttpResponse response) {\n      Map<String, CookbookDefinition> result = parser.apply(response);\n      String cookbookName = result.keySet().iterator().next();\n      CookbookDefinition def = result.values().iterator().next();\n      return CookbookDefinition.builder() //\n             .from(def) //\n             .name(cookbookName) //\n             .build();\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/functions/ParseCookbookDefinitionListFromJson.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.functions;\n\nimport com.google.common.base.Function;\nimport org.jclouds.chef.domain.CookbookDefinition;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseJson;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\nimport java.util.Map;\nimport java.util.Set;\n\nimport static com.google.common.collect.Iterables.transform;\nimport static com.google.common.collect.Sets.newLinkedHashSet;\n\n/**\n * Parses the cookbook versions in a Chef Server >= 0.10.8.\n */\n@Singleton\npublic class ParseCookbookDefinitionListFromJson implements Function<HttpResponse, Set<CookbookDefinition>> {\n\n   /**\n    * Parser for responses from chef server >= 0.10.8\n    */\n   private final ParseJson<Map<String, CookbookDefinition>> parser;\n\n   @Inject\n   ParseCookbookDefinitionListFromJson(ParseJson<Map<String, CookbookDefinition>> parser) {\n      this.parser = parser;\n   }\n\n   @Override\n   public Set<CookbookDefinition> apply(HttpResponse response) {\n      Set<Map.Entry<String, CookbookDefinition>> result = parser.apply(response).entrySet();\n      return newLinkedHashSet(transform(result, new Function<Map.Entry<String, CookbookDefinition>, CookbookDefinition>() {\n         @Override\n         public CookbookDefinition apply(Map.Entry<String, CookbookDefinition> input) {\n            String cookbookName = input.getKey();\n            CookbookDefinition def = input.getValue();\n            return CookbookDefinition.builder() //\n                   .from(def) //              \n                   .name(cookbookName) //\n                   .build();\n         }\n      }));\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/functions/ParseCookbookNamesFromJson.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.functions;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.chef.domain.CookbookDefinition;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseJson;\n\nimport com.google.common.base.Function;\n\n/**\n * Parses a cookbook definition from a Json response, assuming a Chef Server >=\n * 0.10.8.\n */\n@Singleton\npublic class ParseCookbookNamesFromJson implements Function<HttpResponse, Set<String>> {\n\n   /** Parser for responses from chef server >= 0.10.8 */\n   private final ParseJson<Map<String, CookbookDefinition>> parser;\n\n   @Inject\n   ParseCookbookNamesFromJson(ParseJson<Map<String, CookbookDefinition>> parser) {\n      this.parser = parser;\n   }\n\n   @Override\n   public Set<String> apply(HttpResponse response) {\n      return parser.apply(response).keySet();\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/functions/ParseCookbookVersionsFromJson.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.functions;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.chef.domain.CookbookDefinition;\nimport org.jclouds.chef.domain.CookbookDefinition.Version;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseJson;\n\nimport com.google.common.base.Function;\nimport static com.google.common.collect.Iterables.getFirst;\nimport static com.google.common.collect.Iterables.transform;\nimport static com.google.common.collect.Sets.newLinkedHashSet;\n\n/**\n * Parses the cookbook versions in a Chef Server >= 0.10.8.\n */\n@Singleton\npublic class ParseCookbookVersionsFromJson implements Function<HttpResponse, Set<String>> {\n\n   /** Parser for responses from chef server >= 0.10.8 */\n   private final ParseJson<Map<String, CookbookDefinition>> parser;\n\n   @Inject\n   ParseCookbookVersionsFromJson(ParseJson<Map<String, CookbookDefinition>> parser) {\n      this.parser = parser;\n   }\n\n   @Override\n   public Set<String> apply(HttpResponse response) {\n      CookbookDefinition def = getFirst(parser.apply(response).values(), null);\n      return newLinkedHashSet(transform(def.getVersions(), new Function<Version, String>() {\n         @Override\n         public String apply(Version input) {\n            return input.getVersion();\n         }\n      }));\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/functions/ParseErrorFromJsonOrReturnBody.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.functions;\n\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ReturnStringIf2xx;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class ParseErrorFromJsonOrReturnBody implements Function<HttpResponse, String> {\n   Pattern pattern = Pattern.compile(\".*\\\\[\\\"([^\\\"]+)\\\"\\\\].*\");\n   private final ReturnStringIf2xx returnStringIf200;\n\n   @Inject\n   ParseErrorFromJsonOrReturnBody(ReturnStringIf2xx returnStringIf200) {\n      this.returnStringIf200 = returnStringIf200;\n   }\n\n   @Override\n   public String apply(HttpResponse response) {\n      String content = returnStringIf200.apply(response);\n      if (content == null)\n         return null;\n      return parse(content);\n   }\n\n   public String parse(String in) {\n      Matcher matcher = pattern.matcher(in);\n      if (matcher.find()) {\n         return matcher.group(1);\n      }\n      return in;\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/functions/ParseKeySetFromJson.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.functions;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseJson;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class ParseKeySetFromJson implements Function<HttpResponse, Set<String>> {\n\n   private final ParseJson<Map<String, String>> json;\n\n   @Inject\n   ParseKeySetFromJson(ParseJson<Map<String, String>> json) {\n      this.json = json;\n   }\n\n   @Override\n   public Set<String> apply(HttpResponse response) {\n      return json.apply(response).keySet();\n\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/functions/ParseSearchClientsFromJson.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.functions;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.chef.domain.Client;\nimport org.jclouds.http.functions.ParseJson;\n\n@Singleton\npublic class ParseSearchClientsFromJson extends ParseSearchResultFromJson<Client> {\n\n   // TODO add generic json parser detector\n\n   @Inject\n   ParseSearchClientsFromJson(ParseJson<Response<Client>> json) {\n      super(json);\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/functions/ParseSearchDatabagFromJson.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.functions;\n\nimport java.util.List;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.chef.domain.DatabagItem;\nimport org.jclouds.chef.domain.SearchResult;\nimport org.jclouds.domain.JsonBall;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\n\nimport com.google.common.base.Function;\nimport com.google.gson.annotations.SerializedName;\nimport static com.google.common.collect.Iterables.transform;\n\n/**\n * Parses the search result into a {@link DatabagItem} object.\n * <p>\n * When searching databags, the items are contained inside the\n * <code>raw_data</code> list.\n */\n@Singleton\npublic class ParseSearchDatabagFromJson implements Function<HttpResponse, SearchResult<DatabagItem>> {\n\n   private final ParseJson<Response> responseParser;\n\n   private final Json json;\n\n   static class Row {\n      @SerializedName(\"raw_data\")\n      JsonBall rawData;\n   }\n\n   static class Response {\n      long start;\n      List<Row> rows;\n   }\n\n   @Inject\n   ParseSearchDatabagFromJson(ParseJson<Response> responseParser, Json json) {\n      this.responseParser = responseParser;\n      this.json = json;\n   }\n\n   @Override\n   public SearchResult<DatabagItem> apply(HttpResponse response) {\n      Response returnVal = responseParser.apply(response);\n      Iterable<DatabagItem> items = transform(returnVal.rows, new Function<Row, DatabagItem>() {\n         @Override\n         public DatabagItem apply(Row input) {\n            return json.fromJson(input.rawData.toString(), DatabagItem.class);\n         }\n      });\n\n      return new SearchResult<DatabagItem>(returnVal.start, items);\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/functions/ParseSearchEnvironmentsFromJson.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.functions;\n\nimport org.jclouds.chef.domain.Environment;\nimport org.jclouds.http.functions.ParseJson;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\n@Singleton\npublic class ParseSearchEnvironmentsFromJson extends ParseSearchResultFromJson<Environment> {\n\n   // TODO add generic json parser detector\n\n   @Inject\n   ParseSearchEnvironmentsFromJson(ParseJson<Response<Environment>> json) {\n      super(json);\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/functions/ParseSearchNodesFromJson.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.functions;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.chef.domain.Node;\nimport org.jclouds.http.functions.ParseJson;\n\n@Singleton\npublic class ParseSearchNodesFromJson extends ParseSearchResultFromJson<Node> {\n\n   // TODO add generic json parser detector\n\n   @Inject\n   ParseSearchNodesFromJson(ParseJson<Response<Node>> json) {\n      super(json);\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/functions/ParseSearchResultFromJson.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.functions;\n\nimport java.util.List;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.chef.domain.SearchResult;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseJson;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class ParseSearchResultFromJson<T> implements Function<HttpResponse, SearchResult<T>> {\n\n   private final ParseJson<Response<T>> json;\n\n   static class Response<T> {\n      long start;\n      List<T> rows;\n   }\n\n   @Inject\n   ParseSearchResultFromJson(ParseJson<Response<T>> json) {\n      this.json = json;\n   }\n\n   @Override\n   public SearchResult<T> apply(HttpResponse response) {\n      Response<T> returnVal = json.apply(response);\n      return new SearchResult<T>(returnVal.start, returnVal.rows);\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/functions/ParseSearchRolesFromJson.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.functions;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.chef.domain.Role;\nimport org.jclouds.http.functions.ParseJson;\n\n@Singleton\npublic class ParseSearchRolesFromJson extends ParseSearchResultFromJson<Role> {\n\n   // TODO add generic json parser detector\n\n   @Inject\n   ParseSearchRolesFromJson(ParseJson<Response<Role>> json) {\n      super(json);\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/functions/UriForResource.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.functions;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.net.URI;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.chef.domain.Resource;\n\nimport com.google.common.base.Function;\n\n/**\n * Extracts the uri field of the given {@link Resource}.\n */\n@Singleton\npublic class UriForResource implements Function<Object, URI> {\n\n   @Override\n   public URI apply(Object input) {\n      checkArgument(checkNotNull(input, \"input\") instanceof Resource,\n            \"This function can only be applied to Resource objects\");\n      return ((Resource) input).getUrl();\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/handlers/ChefApiErrorRetryHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.handlers;\n\nimport static org.jclouds.http.HttpUtils.closeClientButKeepContentStream;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\n\nimport org.jclouds.Constants;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpRetryHandler;\nimport org.jclouds.http.handlers.BackoffLimitedRetryHandler;\nimport org.jclouds.logging.Logger;\n\nimport com.google.inject.Inject;\n\n/**\n * Allow for eventual consistency on sandbox requests.\n */\npublic class ChefApiErrorRetryHandler implements HttpRetryHandler {\n\n   @Inject(optional = true)\n   @Named(Constants.PROPERTY_MAX_RETRIES)\n   private int retryCountLimit = 5;\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   private final BackoffLimitedRetryHandler backoffLimitedRetryHandler;\n\n   @Inject\n   ChefApiErrorRetryHandler(BackoffLimitedRetryHandler backoffLimitedRetryHandler) {\n      this.backoffLimitedRetryHandler = backoffLimitedRetryHandler;\n   }\n\n   public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) {\n      if (command.getFailureCount() > retryCountLimit)\n         return false;\n      if (response.getStatusCode() == 400 && command.getCurrentRequest().getMethod().equals(\"PUT\")\n            && command.getCurrentRequest().getEndpoint().getPath().indexOf(\"sandboxes\") != -1) {\n         if (response.getPayload() != null) {\n            String error = new String(closeClientButKeepContentStream(response));\n            if (error != null && error.indexOf(\"was not uploaded\") != -1) {\n               return backoffLimitedRetryHandler.shouldRetryRequest(command, response);\n            }\n         }\n      }\n      return false;\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/handlers/ChefErrorHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.handlers;\n\nimport static org.jclouds.util.Closeables2.closeQuietly;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.chef.functions.ParseErrorFromJsonOrReturnBody;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.ResourceNotFoundException;\n\n/**\n * This will parse and set an appropriate exception on the command object.\n */\n@Singleton\npublic class ChefErrorHandler implements HttpErrorHandler {\n   @Resource\n   protected Logger logger = Logger.NULL;\n   private final ParseErrorFromJsonOrReturnBody errorParser;\n\n   @Inject\n   ChefErrorHandler(ParseErrorFromJsonOrReturnBody errorParser) {\n      this.errorParser = errorParser;\n   }\n\n   public void handleError(HttpCommand command, HttpResponse response) {\n      String message = errorParser.apply(response);\n      Exception exception = new HttpResponseException(command, response, message);\n      try {\n         message = message != null ? message : String.format(\"%s -> %s\", command.getCurrentRequest().getRequestLine(),\n               response.getStatusLine());\n         switch (response.getStatusCode()) {\n            case 401:\n            case 403:\n               exception = new AuthorizationException(message, exception);\n               break;\n            case 404:\n               if (!command.getCurrentRequest().getMethod().equals(\"DELETE\")) {\n                  exception = new ResourceNotFoundException(message, exception);\n               }\n               break;\n         }\n      } finally {\n         closeQuietly(response.getPayload());\n         command.setException(exception);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/internal/BaseChefService.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.chef.config.ChefProperties.CHEF_BOOTSTRAP_DATABAG;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.security.PrivateKey;\nimport java.util.concurrent.ExecutorService;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.chef.ChefApi;\nimport org.jclouds.chef.ChefService;\nimport org.jclouds.chef.config.ChefProperties;\nimport org.jclouds.chef.domain.BootstrapConfig;\nimport org.jclouds.chef.domain.Client;\nimport org.jclouds.chef.domain.CookbookVersion;\nimport org.jclouds.chef.domain.DatabagItem;\nimport org.jclouds.chef.domain.Environment;\nimport org.jclouds.chef.domain.Node;\nimport org.jclouds.chef.functions.BootstrapConfigForGroup;\nimport org.jclouds.chef.functions.GroupToBootScript;\nimport org.jclouds.chef.strategy.CleanupStaleNodesAndClients;\nimport org.jclouds.chef.strategy.CreateNodeAndPopulateAutomaticAttributes;\nimport org.jclouds.chef.strategy.DeleteAllClientsInList;\nimport org.jclouds.chef.strategy.DeleteAllNodesInList;\nimport org.jclouds.chef.strategy.ListClients;\nimport org.jclouds.chef.strategy.ListCookbookVersions;\nimport org.jclouds.chef.strategy.ListCookbookVersionsInEnvironment;\nimport org.jclouds.chef.strategy.ListEnvironments;\nimport org.jclouds.chef.strategy.ListNodes;\nimport org.jclouds.chef.strategy.ListNodesInEnvironment;\nimport org.jclouds.chef.strategy.UpdateAutomaticAttributesOnNode;\nimport org.jclouds.crypto.Crypto;\nimport org.jclouds.io.ByteStreams2;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.io.payloads.RSADecryptingPayload;\nimport org.jclouds.io.payloads.RSAEncryptingPayload;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.Json;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.scriptbuilder.domain.Statement;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Supplier;\n\n@Singleton\npublic class BaseChefService implements ChefService {\n\n   private final ChefApi api;\n   private final CleanupStaleNodesAndClients cleanupStaleNodesAndClients;\n   private final CreateNodeAndPopulateAutomaticAttributes createNodeAndPopulateAutomaticAttributes;\n   private final DeleteAllNodesInList deleteAllNodesInList;\n   private final ListNodes listNodes;\n   private final DeleteAllClientsInList deleteAllClientsInList;\n   private final ListClients listClients;\n   private final UpdateAutomaticAttributesOnNode updateAutomaticAttributesOnNode;\n   private final Supplier<PrivateKey> privateKey;\n   private final GroupToBootScript groupToBootScript;\n   private final String databag;\n   private final BootstrapConfigForGroup bootstrapConfigForGroup;\n   private final ListCookbookVersions listCookbookVersions;\n   private final ListCookbookVersionsInEnvironment listCookbookVersionsInEnvironment;\n   private final ListEnvironments listEnvironments;\n   private final ListNodesInEnvironment listNodesInEnvironment;\n   private final Json json;\n   private final Crypto crypto;\n\n   @Resource\n   @Named(ChefProperties.CHEF_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   @Inject\n   BaseChefService(ChefApi api, CleanupStaleNodesAndClients cleanupStaleNodesAndClients,\n         CreateNodeAndPopulateAutomaticAttributes createNodeAndPopulateAutomaticAttributes,\n         DeleteAllNodesInList deleteAllNodesInList, ListNodes listNodes, DeleteAllClientsInList deleteAllClientsInList,\n         ListClients listClients, ListCookbookVersions listCookbookVersions,\n         UpdateAutomaticAttributesOnNode updateAutomaticAttributesOnNode, Supplier<PrivateKey> privateKey,\n         @Named(CHEF_BOOTSTRAP_DATABAG) String databag, GroupToBootScript groupToBootScript,\n         BootstrapConfigForGroup bootstrapConfigForGroup, ListEnvironments listEnvironments,\n         ListNodesInEnvironment listNodesInEnvironment,\n         ListCookbookVersionsInEnvironment listCookbookVersionsInEnvironment, Json json, Crypto crypto) {\n      this.api = api;\n      this.cleanupStaleNodesAndClients = cleanupStaleNodesAndClients;\n      this.createNodeAndPopulateAutomaticAttributes = createNodeAndPopulateAutomaticAttributes;\n      this.deleteAllNodesInList = deleteAllNodesInList;\n      this.listNodes = listNodes;\n      this.deleteAllClientsInList = deleteAllClientsInList;\n      this.listClients = listClients;\n      this.listCookbookVersions = listCookbookVersions;\n      this.updateAutomaticAttributesOnNode = updateAutomaticAttributesOnNode;\n      this.privateKey = privateKey;\n      this.groupToBootScript = groupToBootScript;\n      this.databag = databag;\n      this.bootstrapConfigForGroup = bootstrapConfigForGroup;\n      this.listEnvironments = listEnvironments;\n      this.listNodesInEnvironment = listNodesInEnvironment;\n      this.listCookbookVersionsInEnvironment = listCookbookVersionsInEnvironment;\n      this.json = json;\n      this.crypto = crypto;\n   }\n\n   @Override\n   public byte[] encrypt(InputStream input) throws IOException {\n      @SuppressWarnings(\"resource\")\n      Payload payload = new RSAEncryptingPayload(crypto, Payloads.newPayload(input), privateKey.get());\n      return ByteStreams2.toByteArrayAndClose(payload.openStream());\n   }\n\n   @Override\n   public byte[] decrypt(InputStream input) throws IOException {\n      @SuppressWarnings(\"resource\")\n      Payload payload = new RSADecryptingPayload(crypto, Payloads.newPayload(input), privateKey.get());\n      return ByteStreams2.toByteArrayAndClose(payload.openStream());\n   }\n\n   @Override\n   public Statement createBootstrapScriptForGroup(String group, @Nullable String nodeName) {\n      return groupToBootScript.apply(group, nodeName);\n   }\n\n   @Override\n   public Statement createBootstrapScriptForGroup(String group) {\n      return groupToBootScript.apply(group, null);\n   }\n\n   @Override\n   public void updateBootstrapConfigForGroup(String group, BootstrapConfig bootstrapConfig) {\n      checkNotNull(bootstrapConfig, \"bootstrapConfig cannot be null\");\n      try {\n         api.createDatabag(databag);\n      } catch (IllegalStateException e) {\n\n      }\n\n      String jsonConfig = buildBootstrapConfiguration(bootstrapConfig);\n      DatabagItem config = new DatabagItem(group, jsonConfig);\n\n      if (api.getDatabagItem(databag, group) == null) {\n         api.createDatabagItem(databag, config);\n      } else {\n         api.updateDatabagItem(databag, config);\n      }\n   }\n   \n   @VisibleForTesting\n   String buildBootstrapConfiguration(BootstrapConfig config) {\n      return json.toJson(config);\n   }\n\n   @Override\n   public BootstrapConfig getBootstrapConfigForGroup(String group) {\n      return bootstrapConfigForGroup.apply(group);\n   }\n\n   @Override\n   public void cleanupStaleNodesAndClients(String prefix, int secondsStale) {\n      cleanupStaleNodesAndClients.execute(prefix, secondsStale);\n   }\n\n   @Override\n   public Node createNodeAndPopulateAutomaticAttributes(String nodeName, Iterable<String> runList) {\n      return createNodeAndPopulateAutomaticAttributes.execute(nodeName, runList);\n   }\n\n   @Override\n   public void updateAutomaticAttributesOnNode(String nodeName) {\n      updateAutomaticAttributesOnNode.execute(nodeName);\n   }\n\n   @Override\n   public void deleteAllNodesInList(Iterable<String> names) {\n      deleteAllNodesInList.execute(names);\n   }\n\n   @Override\n   public void deleteAllClientsInList(Iterable<String> names) {\n      deleteAllClientsInList.execute(names);\n   }\n\n   @Override\n   public Iterable<? extends Node> listNodes() {\n      return listNodes.execute();\n   }\n\n   @Override\n   public Iterable<? extends Node> listNodes(ExecutorService executorService) {\n      return listNodes.execute(executorService);\n   }\n\n   @Override\n   public Iterable<? extends Client> listClients() {\n      return listClients.execute();\n   }\n\n   @Override\n   public Iterable<? extends Client> listClients(ExecutorService executorService) {\n      return listClients.execute(executorService);\n   }\n\n   @Override\n   public Iterable<? extends CookbookVersion> listCookbookVersions() {\n      return listCookbookVersions.execute();\n   }\n\n   @Override\n   public Iterable<? extends CookbookVersion> listCookbookVersions(ExecutorService executorService) {\n      return listCookbookVersions.execute(executorService);\n   }\n\n   @Override\n   public Iterable<? extends CookbookVersion> listCookbookVersionsInEnvironment(String environmentName) {\n      return listCookbookVersionsInEnvironment.execute(environmentName);\n   }\n\n   @Override\n   public Iterable<? extends CookbookVersion> listCookbookVersionsInEnvironment(String environmentName,\n         ExecutorService executorService) {\n      return listCookbookVersionsInEnvironment.execute(executorService, environmentName);\n   }\n\n   @Override\n   public Iterable<? extends CookbookVersion> listCookbookVersionsInEnvironment(String environmentName,\n         String numVersions) {\n      return listCookbookVersionsInEnvironment.execute(environmentName, numVersions);\n   }\n\n   @Override\n   public Iterable<? extends CookbookVersion> listCookbookVersionsInEnvironment(String environmentName,\n         String numVersions, ExecutorService executorService) {\n      return listCookbookVersionsInEnvironment.execute(executorService, environmentName, numVersions);\n   }\n\n   @Override\n   public Iterable<? extends Environment> listEnvironments() {\n      return listEnvironments.execute();\n   }\n\n   @Override\n   public Iterable<? extends Node> listNodesInEnvironment(String environmentName) {\n      return listNodesInEnvironment.execute(environmentName);\n   }\n\n   @Override\n   public Iterable<? extends Node> listNodesInEnvironment(String environmentName, ExecutorService executorService) {\n      return listNodesInEnvironment.execute(executorService, environmentName);\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/options/CreateClientOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.options;\n\n/**\n * Options for the create client method.\n */\npublic class CreateClientOptions implements Cloneable {\n   /** Administrator flag. This flag will be ignored in Chef 12. */\n   private boolean admin;\n\n   public CreateClientOptions() {\n   }\n\n   CreateClientOptions(final boolean admin) {\n      super();\n      this.admin = admin;\n   }\n\n   public boolean isAdmin() {\n      return admin;\n   }\n\n   public CreateClientOptions admin() {\n      this.admin = true;\n      return this;\n   }\n\n   @Override\n   protected Object clone() throws CloneNotSupportedException {\n      return new CreateClientOptions(admin);\n   }\n\n   @Override\n   public String toString() {\n      return \"[admin=\" + admin + \"]\";\n   }\n\n   public static class Builder {\n      /**\n       * @see CreateClientOptions#admin()\n       */\n      public static CreateClientOptions admin() {\n         CreateClientOptions options = new CreateClientOptions();\n         return options.admin();\n      }\n\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/options/SearchOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\n/**\n * Options for the search api.\n */\npublic class SearchOptions extends BaseHttpRequestOptions {\n\n   /**\n    * A valid search string.\n    */\n   public SearchOptions query(String query) {\n      this.queryParameters.put(\"q\", checkNotNull(query, \"query\"));\n      return this;\n   }\n\n   /**\n    * A sort string, such as 'name DESC'.\n    */\n   public SearchOptions sort(String sort) {\n      this.queryParameters.put(\"sort\", checkNotNull(sort, \"sort\"));\n      return this;\n   }\n\n   /**\n    * The number of rows to return.\n    */\n   public SearchOptions rows(int rows) {\n      this.queryParameters.put(\"rows\", String.valueOf(rows));\n      return this;\n   }\n\n   /**\n    * The result number to start from.\n    */\n   public SearchOptions start(int start) {\n      this.queryParameters.put(\"start\", String.valueOf(start));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see SearchOptions#query(String)\n       */\n      public static SearchOptions query(String query) {\n         SearchOptions options = new SearchOptions();\n         return options.query(query);\n      }\n\n      /**\n       * @see SearchOptions#sort(String)\n       */\n      public static SearchOptions start(String start) {\n         SearchOptions options = new SearchOptions();\n         return options.sort(start);\n      }\n\n      /**\n       * @see SearchOptions#rows(int)\n       */\n      public static SearchOptions rows(int rows) {\n         SearchOptions options = new SearchOptions();\n         return options.rows(rows);\n      }\n\n      /**\n       * @see SearchOptions#start(int)\n       */\n      public static SearchOptions start(int start) {\n         SearchOptions options = new SearchOptions();\n         return options.start(start);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/predicates/CookbookVersionPredicates.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.any;\nimport static com.google.common.collect.Iterables.get;\n\nimport org.jclouds.chef.domain.CookbookVersion;\nimport org.jclouds.chef.domain.Resource;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.LinkedListMultimap;\nimport com.google.common.collect.Multimap;\n\n/**\n * Container for cookbook filters (predicates).\n * \n * This class has static methods that create customized predicates to use with\n * {@link org.jclouds.chef.ChefService}.\n */\npublic class CookbookVersionPredicates {\n   /**\n    * @see #containsRecipes\n    */\n   public static Predicate<CookbookVersion> containsRecipe(String recipe) {\n      return containsRecipes(checkNotNull(recipe, \"recipe must be defined\"));\n   }\n\n   /**\n    * Note that the default recipe of a cookbook is its name. Otherwise, you\n    * prefix the recipe with the name of the cookbook. ex. {@code apache2} will\n    * be the default recipe where {@code apache2::mod_proxy} is a specific one\n    * in the cookbook.\n    * \n    * @param recipes\n    *           names of the recipes.\n    * @return true if the cookbook version contains a recipe in the list.\n    */\n   public static Predicate<CookbookVersion> containsRecipes(String... recipes) {\n      checkNotNull(recipes, \"recipes must be defined\");\n      final Multimap<String, String> search = LinkedListMultimap.create();\n      for (String recipe : recipes) {\n         if (recipe.indexOf(\"::\") != -1) {\n            Iterable<String> nameRecipe = Splitter.on(\"::\").split(recipe);\n            search.put(get(nameRecipe, 0), get(nameRecipe, 1) + \".rb\");\n         } else {\n            search.put(recipe, \"default.rb\");\n         }\n      }\n      return new Predicate<CookbookVersion>() {\n         @Override\n         public boolean apply(final CookbookVersion cookbookVersion) {\n            return search.containsKey(cookbookVersion.getCookbookName())\n                  && any(search.get(cookbookVersion.getCookbookName()), new Predicate<String>() {\n\n                     @Override\n                     public boolean apply(final String recipeName) {\n                        return any(cookbookVersion.getRecipes(), new Predicate<Resource>() {\n\n                           @Override\n                           public boolean apply(Resource resource) {\n                              return resource.getName().equals(recipeName);\n                           }\n\n                        });\n                     }\n\n                  });\n         }\n\n         @Override\n         public String toString() {\n            return \"containsRecipes(\" + search + \")\";\n         }\n      };\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/strategy/CleanupStaleNodesAndClients.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.strategy;\n\nimport org.jclouds.chef.strategy.internal.CleanupStaleNodesAndClientsImpl;\n\nimport com.google.inject.ImplementedBy;\n\n/**\n * \n * Cleans up nodes and clients who have been hanging around too long.\n */\n@ImplementedBy(CleanupStaleNodesAndClientsImpl.class)\npublic interface CleanupStaleNodesAndClients {\n\n   void execute(String prefix, int secondsStale);\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/strategy/CreateNodeAndPopulateAutomaticAttributes.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.strategy;\n\nimport org.jclouds.chef.domain.Node;\nimport org.jclouds.chef.strategy.internal.CreateNodeAndPopulateAutomaticAttributesImpl;\n\nimport com.google.inject.ImplementedBy;\n\n/**\n * \n * Creates a new node with automatic attributes.\n */\n@ImplementedBy(CreateNodeAndPopulateAutomaticAttributesImpl.class)\npublic interface CreateNodeAndPopulateAutomaticAttributes {\n   Node execute(Node node);\n\n   Node execute(String nodeName, Iterable<String> runList);\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/strategy/DeleteAllClientsInList.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.strategy;\n\nimport org.jclouds.chef.strategy.internal.DeleteAllClientsInListImpl;\n\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.inject.ImplementedBy;\n\n/**\n * Deletes all clients in a given list.\n */\n@ImplementedBy(DeleteAllClientsInListImpl.class)\npublic interface DeleteAllClientsInList {\n\n   void execute(Iterable<String> names);\n\n   void execute(ListeningExecutorService executor, Iterable<String> names);\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/strategy/DeleteAllNodesInList.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.strategy;\n\nimport org.jclouds.chef.strategy.internal.DeleteAllNodesInListImpl;\n\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.inject.ImplementedBy;\n\n@ImplementedBy(DeleteAllNodesInListImpl.class)\npublic interface DeleteAllNodesInList {\n\n   void execute(Iterable<String> names);\n\n   void execute(ListeningExecutorService executor, Iterable<String> names);\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/strategy/ListClients.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.strategy;\n\nimport com.google.inject.ImplementedBy;\nimport org.jclouds.chef.domain.Client;\nimport org.jclouds.chef.strategy.internal.ListClientsImpl;\n\nimport java.util.concurrent.ExecutorService;\n\n@ImplementedBy(ListClientsImpl.class)\npublic interface ListClients {\n\n   Iterable<? extends Client> execute();\n\n   Iterable<? extends Client> execute(ExecutorService executor);\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/strategy/ListCookbookVersions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.strategy;\n\nimport com.google.inject.ImplementedBy;\nimport org.jclouds.chef.domain.CookbookVersion;\nimport org.jclouds.chef.strategy.internal.ListCookbookVersionsImpl;\n\nimport java.util.concurrent.ExecutorService;\n\n@ImplementedBy(ListCookbookVersionsImpl.class)\npublic interface ListCookbookVersions {\n\n   Iterable<? extends CookbookVersion> execute();\n\n   Iterable<? extends CookbookVersion> execute(ExecutorService executor);\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/strategy/ListCookbookVersionsInEnvironment.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.strategy;\n\nimport com.google.inject.ImplementedBy;\nimport org.jclouds.chef.domain.CookbookVersion;\nimport org.jclouds.chef.strategy.internal.ListCookbookVersionsInEnvironmentImpl;\n\nimport java.util.concurrent.ExecutorService;\n\n@ImplementedBy(ListCookbookVersionsInEnvironmentImpl.class)\npublic interface ListCookbookVersionsInEnvironment {\n\n   Iterable<? extends CookbookVersion> execute(String environmentName);\n\n   Iterable<? extends CookbookVersion> execute(String environmentName, String numVersions);\n\n   Iterable<? extends CookbookVersion> execute(ExecutorService executor, String environmentName);\n\n   Iterable<? extends CookbookVersion> execute(ExecutorService executor, String environmentName, String numVersions);\n\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/strategy/ListEnvironments.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.strategy;\n\nimport com.google.inject.ImplementedBy;\nimport org.jclouds.chef.domain.Environment;\nimport org.jclouds.chef.strategy.internal.ListEnvironmentsImpl;\n\nimport java.util.concurrent.ExecutorService;\n\n@ImplementedBy(ListEnvironmentsImpl.class)\npublic interface ListEnvironments {\n\n   Iterable<? extends Environment> execute();\n\n   Iterable<? extends Environment> execute(ExecutorService executor);\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/strategy/ListNodes.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.strategy;\n\nimport com.google.inject.ImplementedBy;\nimport org.jclouds.chef.domain.Node;\nimport org.jclouds.chef.strategy.internal.ListNodesImpl;\n\nimport java.util.concurrent.ExecutorService;\n\n@ImplementedBy(ListNodesImpl.class)\npublic interface ListNodes {\n\n   Iterable<? extends Node> execute();\n\n   Iterable<? extends Node> execute(ExecutorService executor);\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/strategy/ListNodesInEnvironment.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.strategy;\n\nimport com.google.inject.ImplementedBy;\nimport org.jclouds.chef.domain.Node;\nimport org.jclouds.chef.strategy.internal.ListNodesInEnvironmentImpl;\n\nimport java.util.concurrent.ExecutorService;\n\n@ImplementedBy(ListNodesInEnvironmentImpl.class)\npublic interface ListNodesInEnvironment {\n\n   Iterable<? extends Node> execute(String environmentName);\n\n   Iterable<? extends Node> execute(ExecutorService executor, String environmentName);\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/strategy/UpdateAutomaticAttributesOnNode.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.strategy;\n\nimport org.jclouds.chef.strategy.internal.UpdateAutomaticAttributesOnNodeImpl;\n\nimport com.google.inject.ImplementedBy;\n\n/**\n * \n * Updates node with new automatic attributes.\n */\n@ImplementedBy(UpdateAutomaticAttributesOnNodeImpl.class)\npublic interface UpdateAutomaticAttributesOnNode {\n\n   void execute(String nodeName);\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/strategy/internal/BaseListCookbookVersionsImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.strategy.internal;\n\nimport com.google.common.base.Function;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport org.jclouds.chef.ChefApi;\nimport org.jclouds.chef.domain.CookbookVersion;\nimport org.jclouds.logging.Logger;\n\nimport java.util.List;\nimport java.util.Set;\nimport java.util.concurrent.Callable;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.concat;\nimport static com.google.common.collect.Iterables.transform;\nimport static com.google.common.util.concurrent.Futures.allAsList;\nimport static com.google.common.util.concurrent.Futures.getUnchecked;\n\npublic abstract class BaseListCookbookVersionsImpl {\n\n   protected final ChefApi api;\n\n   protected Logger logger = Logger.NULL;\n\n   BaseListCookbookVersionsImpl(ChefApi api) {\n      this.api = checkNotNull(api, \"api\");\n   }\n\n   protected Iterable<? extends CookbookVersion> execute(Iterable<String> toGet) {\n      return concat(transform(toGet, new Function<String, Iterable<? extends CookbookVersion>>() {\n\n         @Override\n         public Iterable<? extends CookbookVersion> apply(final String cookbook) {\n            // TODO getting each version could also go parallel\n            Set<String> cookbookVersions = api.listVersionsOfCookbook(cookbook);\n            Iterable<? extends CookbookVersion> cookbooksVersions = transform(cookbookVersions,\n                  new Function<String, CookbookVersion>() {\n                     @Override\n                     public CookbookVersion apply(final String version) {\n                        return api.getCookbook(cookbook, version);\n                     }\n                  }\n            );\n\n            logger.trace(String.format(\"getting versions of cookbook: %s\", cookbook));\n            return cookbooksVersions;\n         }\n      }));\n\n   }\n\n   protected Iterable<? extends CookbookVersion> executeConcurrently(final ListeningExecutorService executor,\n         Iterable<String> cookbookNames) {\n      return concat(transform(cookbookNames, new Function<String, Iterable<? extends CookbookVersion>>() {\n\n         @Override\n         public Iterable<? extends CookbookVersion> apply(final String cookbook) {\n            // TODO getting each version could also go parallel\n            Set<String> cookbookVersions = api.listVersionsOfCookbook(cookbook);\n            ListenableFuture<List<CookbookVersion>> futures = allAsList(transform(cookbookVersions,\n                  new Function<String, ListenableFuture<CookbookVersion>>() {\n                     @Override\n                     public ListenableFuture<CookbookVersion> apply(final String version) {\n                        return executor.submit(new Callable<CookbookVersion>() {\n                           @Override\n                           public CookbookVersion call() throws Exception {\n                              return api.getCookbook(cookbook, version);\n                           }\n                        });\n                     }\n                  }\n            ));\n\n            logger.trace(String.format(\"getting versions of cookbook: %s\", cookbook));\n            return getUnchecked(futures);\n         }\n      }));\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/strategy/internal/BaseListNodesImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.strategy.internal;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Joiner;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport org.jclouds.chef.ChefApi;\nimport org.jclouds.chef.domain.Node;\nimport org.jclouds.logging.Logger;\n\nimport java.util.List;\nimport java.util.concurrent.Callable;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.transform;\nimport static com.google.common.util.concurrent.Futures.allAsList;\nimport static com.google.common.util.concurrent.Futures.getUnchecked;\n\npublic abstract class BaseListNodesImpl {\n\n   protected final ChefApi api;\n\n   protected Logger logger = Logger.NULL;\n\n   BaseListNodesImpl(ChefApi api) {\n      this.api = checkNotNull(api, \"api\");\n   }\n\n   protected Iterable<? extends Node> execute(Iterable<String> toGet) {\n      Iterable<? extends Node> nodes = transform(toGet, new Function<String, Node>() {\n               @Override\n               public Node apply(final String input) {\n                  return api.getNode(input);\n               }\n            }\n      );\n\n      logger.trace(String.format(\"getting nodes: %s\", Joiner.on(',').join(toGet)));\n      return nodes;\n\n   }\n\n   protected Iterable<? extends Node> executeConcurrently(final ListeningExecutorService executor,\n         Iterable<String> toGet) {\n      ListenableFuture<List<Node>> futures = allAsList(transform(toGet, new Function<String, ListenableFuture<Node>>() {\n         @Override\n         public ListenableFuture<Node> apply(final String input) {\n            return executor.submit(new Callable<Node>() {\n               @Override\n               public Node call() throws Exception {\n                  return api.getNode(input);\n               }\n            });\n         }\n      }));\n\n      logger.trace(String.format(\"getting nodes: %s\", Joiner.on(',').join(toGet)));\n      return getUnchecked(futures);\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/strategy/internal/CleanupStaleNodesAndClientsImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.strategy.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Predicates.and;\nimport static com.google.common.base.Predicates.notNull;\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.transform;\nimport static org.jclouds.chef.util.ChefUtils.fromOhaiTime;\n\nimport java.util.Calendar;\nimport java.util.Date;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.chef.config.ChefProperties;\nimport org.jclouds.chef.domain.Node;\nimport org.jclouds.chef.strategy.CleanupStaleNodesAndClients;\nimport org.jclouds.chef.strategy.DeleteAllClientsInList;\nimport org.jclouds.chef.strategy.DeleteAllNodesInList;\nimport org.jclouds.chef.strategy.ListNodes;\nimport org.jclouds.domain.JsonBall;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\n\n/**\n * \n * Cleans up nodes and apis who have been hanging around too long.\n */\n@Singleton\npublic class CleanupStaleNodesAndClientsImpl implements CleanupStaleNodesAndClients {\n   @Resource\n   @Named(ChefProperties.CHEF_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   private final ListNodes nodeLister;\n   private final DeleteAllNodesInList nodeDeleter;\n   private final DeleteAllClientsInList clientDeleter;\n\n   @Inject\n   public CleanupStaleNodesAndClientsImpl(DeleteAllNodesInList nodeDeleter, DeleteAllClientsInList clientDeleter,\n         ListNodes nodeLister) {\n      this.nodeLister = checkNotNull(nodeLister, \"nodeLister\");\n      this.nodeDeleter = checkNotNull(nodeDeleter, \"nodeDeleter\");\n      this.clientDeleter = checkNotNull(clientDeleter, \"clientDeleter\");\n   }\n\n   @Override\n   public void execute(final String prefix, int secondsStale) {\n      final Calendar expired = Calendar.getInstance();\n      expired.setTime(new Date());\n      expired.add(Calendar.SECOND, -secondsStale);\n      Iterable<? extends Node> staleNodes = filter(\n         nodeLister.execute(), and(notNull(), new Predicate<Node>() {\n               @Override\n               public boolean apply(Node input) {\n                  return input.getName().startsWith(prefix);\n               }\n         },\n         new Predicate<Node>() {\n             @Override\n             public boolean apply(Node input) {\n                JsonBall dateLong = input.getAutomaticAttributes().get(\"ohai_time\");\n                if (dateLong == null)\n                   return true;\n                Calendar nodeUpdate = Calendar.getInstance();\n                nodeUpdate.setTime(fromOhaiTime(dateLong));\n                return expired.after(nodeUpdate);\n             }\n         }));\n      Iterable<String> nodeNames = transform(staleNodes, new Function<Node, String>() {\n\n         @Override\n         public String apply(Node from) {\n            return from.getName();\n         }\n\n      });\n      nodeDeleter.execute(nodeNames);\n      clientDeleter.execute(nodeNames);\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/strategy/internal/CreateNodeAndPopulateAutomaticAttributesImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.strategy.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.chef.ChefApi;\nimport org.jclouds.chef.config.ChefProperties;\nimport org.jclouds.chef.domain.Node;\nimport org.jclouds.chef.strategy.CreateNodeAndPopulateAutomaticAttributes;\nimport org.jclouds.domain.JsonBall;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.ohai.Automatic;\n\nimport com.google.common.base.Supplier;\n\n/**\n * \n * Updates node with new automatic attributes.\n */\n@Singleton\npublic class CreateNodeAndPopulateAutomaticAttributesImpl implements CreateNodeAndPopulateAutomaticAttributes {\n\n   @Resource\n   @Named(ChefProperties.CHEF_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   private final ChefApi chef;\n   private final Supplier<Map<String, JsonBall>> automaticSupplier;\n\n   @Inject\n   public CreateNodeAndPopulateAutomaticAttributesImpl(ChefApi chef,\n         @Automatic Supplier<Map<String, JsonBall>> automaticSupplier) {\n      this.chef = checkNotNull(chef, \"chef\");\n      this.automaticSupplier = checkNotNull(automaticSupplier, \"automaticSupplier\");\n   }\n\n   @Override\n   public Node execute(Node node) {\n      logger.trace(\"creating node %s\", node.getName());\n      Node withAutomatic = Node.builder() //\n            .name(node.getName()) //\n            .normalAttributes(node.getNormalAttributes()) //\n            .overrideAttributes(node.getOverrideAttributes()) //\n            .defaultAttributes(node.getDefaultAttributes()) //\n            .automaticAttributes(node.getAutomaticAttributes()) //\n            .automaticAttributes(automaticSupplier.get()) //\n            .runList(node.getRunList()) //\n            .environment(node.getEnvironment()) //\n            .build();\n      \n      \n      chef.createNode(withAutomatic);\n      logger.debug(\"created node %s\", withAutomatic.getName());\n      return node;\n   }\n\n   @Override\n   public Node execute(String nodeName, Iterable<String> runList) {\n      return execute(Node.builder().name(nodeName).runList(runList).environment(\"_default\").build());\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/strategy/internal/DeleteAllClientsInListImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.strategy.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.transform;\nimport static com.google.common.util.concurrent.Futures.allAsList;\nimport static com.google.common.util.concurrent.Futures.getUnchecked;\n\nimport java.util.List;\nimport java.util.concurrent.Callable;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Constants;\nimport org.jclouds.chef.ChefApi;\nimport org.jclouds.chef.config.ChefProperties;\nimport org.jclouds.chef.domain.Client;\nimport org.jclouds.chef.strategy.DeleteAllClientsInList;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Joiner;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.inject.Inject;\n\n/**\n * Concurrently delete all given clients.\n */\n@Singleton\npublic class DeleteAllClientsInListImpl implements DeleteAllClientsInList {\n\n   protected final ChefApi api;\n   protected final ListeningExecutorService userExecutor;\n   @Resource\n   @Named(ChefProperties.CHEF_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   @Inject\n   DeleteAllClientsInListImpl(@Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor, ChefApi api) {\n      this.userExecutor = checkNotNull(userExecutor, \"userExecuor\");\n      this.api = checkNotNull(api, \"api\");\n   }\n\n   @Override\n   public void execute(Iterable<String> names) {\n      execute(userExecutor, names);\n   }\n\n   @Override\n   public void execute(final ListeningExecutorService executor, Iterable<String> names) {\n      ListenableFuture<List<Client>> futures = allAsList(transform(names,\n            new Function<String, ListenableFuture<Client>>() {\n               @Override\n               public ListenableFuture<Client> apply(final String input) {\n                  return executor.submit(new Callable<Client>() {\n                     @Override\n                     public Client call() throws Exception {\n                        return api.deleteClient(input);\n                     }\n                  });\n               }\n            }));\n\n      logger.trace(String.format(\"deleting clients: %s\", Joiner.on(',').join(names)));\n      getUnchecked(futures);\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/strategy/internal/DeleteAllNodesInListImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.strategy.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.transform;\nimport static com.google.common.util.concurrent.Futures.allAsList;\nimport static com.google.common.util.concurrent.Futures.getUnchecked;\n\nimport java.util.List;\nimport java.util.concurrent.Callable;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Constants;\nimport org.jclouds.chef.ChefApi;\nimport org.jclouds.chef.config.ChefProperties;\nimport org.jclouds.chef.domain.Node;\nimport org.jclouds.chef.strategy.DeleteAllNodesInList;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Joiner;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.inject.Inject;\n\n@Singleton\npublic class DeleteAllNodesInListImpl implements DeleteAllNodesInList {\n\n   protected final ChefApi api;\n   protected final ListeningExecutorService userExecutor;\n   @Resource\n   @Named(ChefProperties.CHEF_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   @Inject\n   DeleteAllNodesInListImpl(@Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor, ChefApi api) {\n      this.userExecutor = checkNotNull(userExecutor, \"userExecuor\");\n      this.api = checkNotNull(api, \"api\");\n   }\n\n   @Override\n   public void execute(Iterable<String> names) {\n      execute(userExecutor, names);\n   }\n\n   @Override\n   public void execute(final ListeningExecutorService executor, Iterable<String> names) {\n      ListenableFuture<List<Node>> futures = allAsList(transform(names, new Function<String, ListenableFuture<Node>>() {\n         @Override\n         public ListenableFuture<Node> apply(final String input) {\n            return executor.submit(new Callable<Node>() {\n               @Override\n               public Node call() throws Exception {\n                  return api.deleteNode(input);\n               }\n            });\n         }\n      }));\n\n      logger.trace(String.format(\"deleting nodes: %s\", Joiner.on(',').join(names)));\n      getUnchecked(futures);\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/strategy/internal/ListClientsImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.strategy.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.transform;\nimport static com.google.common.util.concurrent.Futures.allAsList;\nimport static com.google.common.util.concurrent.Futures.getUnchecked;\n\nimport java.util.List;\nimport java.util.concurrent.Callable;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Joiner;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.common.util.concurrent.MoreExecutors;\nimport com.google.inject.Inject;\nimport org.jclouds.chef.ChefApi;\nimport org.jclouds.chef.config.ChefProperties;\nimport org.jclouds.chef.domain.Client;\nimport org.jclouds.chef.strategy.ListClients;\nimport org.jclouds.logging.Logger;\n\nimport java.util.concurrent.ExecutorService;\n\n\n@Singleton\npublic class ListClientsImpl implements ListClients {\n\n   protected final ChefApi api;\n   @Resource\n   @Named(ChefProperties.CHEF_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   @Inject\n   ListClientsImpl(ChefApi api) {\n      this.api = checkNotNull(api, \"api\");\n   }\n\n   @Override\n   public Iterable<? extends Client> execute() {\n\n      Iterable<String> toGet = api.listClients();\n      Iterable<? extends Client> clients = transform(toGet,\n            new Function<String, Client>() {\n               @Override\n               public Client apply(final String input) {\n\n                  return api.getClient(input);\n               }\n\n            }\n      );\n\n      logger.trace(String.format(\"getting clients: %s\", Joiner.on(',').join(toGet)));\n      return clients;\n\n   }\n\n   @Override\n   public Iterable<? extends Client> execute(ExecutorService executorService) {\n      return this.execute(MoreExecutors.listeningDecorator(executorService));\n   }\n\n\n   private Iterable<? extends Client> execute(ListeningExecutorService listeningExecutor) {\n      return executeConcurrently(listeningExecutor, api.listClients());\n   }\n\n   private Iterable<? extends Client> executeConcurrently(final ListeningExecutorService executor,\n         Iterable<String> toGet) {\n      ListenableFuture<List<Client>> futures = allAsList(transform(toGet,\n            new Function<String, ListenableFuture<Client>>() {\n               @Override\n               public ListenableFuture<Client> apply(final String input) {\n                  return executor.submit(new Callable<Client>() {\n                     @Override\n                     public Client call() throws Exception {\n                        return api.getClient(input);\n                     }\n                  });\n               }\n            }\n      ));\n\n      logger.trace(String.format(\"getting clients: %s\", Joiner.on(',').join(toGet)));\n      return getUnchecked(futures);\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/strategy/internal/ListCookbookVersionsImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.strategy.internal;\n\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.common.util.concurrent.MoreExecutors;\nimport com.google.inject.Inject;\nimport org.jclouds.chef.ChefApi;\nimport org.jclouds.chef.config.ChefProperties;\nimport org.jclouds.chef.domain.CookbookVersion;\nimport org.jclouds.chef.strategy.ListCookbookVersions;\nimport org.jclouds.logging.Logger;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\nimport java.util.concurrent.ExecutorService;\n\n@Singleton\npublic class ListCookbookVersionsImpl extends BaseListCookbookVersionsImpl implements ListCookbookVersions {\n\n   @Resource\n   @Named(ChefProperties.CHEF_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   @Inject\n   ListCookbookVersionsImpl(ChefApi api) {\n      super(api);\n   }\n\n   @Override\n   public Iterable<? extends CookbookVersion> execute() {\n      return super.execute(api.listCookbooks());\n   }\n\n   @Override\n   public Iterable<? extends CookbookVersion> execute(ExecutorService executor) {\n      return this.executeConcurrently(MoreExecutors.listeningDecorator(executor));\n   }\n\n\n   private Iterable<? extends CookbookVersion> executeConcurrently(ListeningExecutorService executor) {\n      return super.executeConcurrently(executor, api.listCookbooks());\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/strategy/internal/ListCookbookVersionsInEnvironmentImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.strategy.internal;\n\nimport static com.google.common.collect.Iterables.transform;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport com.google.common.base.Function;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.common.util.concurrent.MoreExecutors;\nimport com.google.inject.Inject;\nimport org.jclouds.chef.ChefApi;\nimport org.jclouds.chef.config.ChefProperties;\nimport org.jclouds.chef.domain.CookbookDefinition;\nimport org.jclouds.chef.domain.CookbookVersion;\nimport org.jclouds.chef.strategy.ListCookbookVersionsInEnvironment;\nimport org.jclouds.logging.Logger;\n\nimport java.util.concurrent.ExecutorService;\n\n@Singleton\npublic class ListCookbookVersionsInEnvironmentImpl extends BaseListCookbookVersionsImpl\n      implements ListCookbookVersionsInEnvironment {\n\n   @Resource\n   @Named(ChefProperties.CHEF_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   @Inject\n   ListCookbookVersionsInEnvironmentImpl(ChefApi api) {\n      super(api);\n   }\n\n   @Override\n   public Iterable<? extends CookbookVersion> execute(String environmentName) {\n      return super.execute(transform(api.listCookbooksInEnvironment(environmentName),\n            new Function<CookbookDefinition, String>() {\n\n               @Override\n               public String apply(CookbookDefinition cookbookDefinition) {\n                  return cookbookDefinition.getName();\n               }\n            }\n      ));\n   }\n\n   @Override\n   public Iterable<? extends CookbookVersion> execute(String environmentName, String numVersions) {\n      return super.execute(transform(api.listCookbooksInEnvironment(environmentName, numVersions),\n            new Function<CookbookDefinition, String>() {\n\n               @Override\n               public String apply(CookbookDefinition cookbookDefinition) {\n                  return cookbookDefinition.getName();\n               }\n            }\n      ));\n   }\n\n   @Override\n   public Iterable<? extends CookbookVersion> execute(ExecutorService executor,\n         String environmentName) {\n      return this.executeConcurrently(MoreExecutors.listeningDecorator(executor), environmentName);\n   }\n\n   @Override\n   public Iterable<? extends CookbookVersion> execute(ExecutorService executor,\n         String environmentName, String numVersions) {\n      return this.executeConcurrently(MoreExecutors.listeningDecorator(executor), environmentName, numVersions);\n   }\n\n\n   private Iterable<? extends CookbookVersion> executeConcurrently(ListeningExecutorService executor,\n         String environmentName) {\n      return super.execute(\n            transform(api.listCookbooksInEnvironment(environmentName), new Function<CookbookDefinition, String>() {\n\n               @Override\n               public String apply(CookbookDefinition cookbookDefinition) {\n                  return cookbookDefinition.getName();\n               }\n            })\n      );\n   }\n\n\n   private Iterable<? extends CookbookVersion> executeConcurrently(ListeningExecutorService executor,\n         String environmentName, String numVersions) {\n      return super.execute(transform(api.listCookbooksInEnvironment(environmentName, numVersions),\n            new Function<CookbookDefinition, String>() {\n\n               @Override\n               public String apply(CookbookDefinition cookbookDefinition) {\n                  return cookbookDefinition.getName();\n               }\n            }\n      ));\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/strategy/internal/ListEnvironmentsImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.strategy.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.transform;\nimport static com.google.common.util.concurrent.Futures.allAsList;\nimport static com.google.common.util.concurrent.Futures.getUnchecked;\n\nimport java.util.List;\nimport java.util.concurrent.Callable;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Constants;\nimport org.jclouds.chef.ChefApi;\nimport org.jclouds.chef.config.ChefProperties;\nimport org.jclouds.chef.domain.Environment;\nimport org.jclouds.chef.strategy.ListEnvironments;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Joiner;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.inject.Inject;\nimport com.google.common.util.concurrent.MoreExecutors;\n\n\nimport java.util.concurrent.ExecutorService;\n\n\n\n@Singleton\npublic class ListEnvironmentsImpl implements ListEnvironments {\n\n   protected final ChefApi api;\n   protected final ListeningExecutorService userExecutor;\n   @Resource\n   @Named(ChefProperties.CHEF_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   @Inject\n   ListEnvironmentsImpl(@Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor, ChefApi api) {\n      this.userExecutor = checkNotNull(userExecutor, \"userExecuor\");\n      this.api = checkNotNull(api, \"api\");\n   }\n\n   @Override\n   public Iterable<? extends Environment> execute() {\n      return execute(userExecutor);\n   }\n\n   @Override\n   public Iterable<? extends Environment> execute(ExecutorService executor) {\n      return this.execute(MoreExecutors.listeningDecorator(executor));\n   }\n\n   private Iterable<? extends Environment> execute(ListeningExecutorService executor) {\n      return execute(executor, api.listEnvironments());\n   }\n\n   private Iterable<? extends Environment> execute(final ListeningExecutorService executor, Iterable<String> toGet) {\n      ListenableFuture<List<Environment>> futures = allAsList(transform(toGet,\n            new Function<String, ListenableFuture<Environment>>() {\n               @Override\n               public ListenableFuture<Environment> apply(final String input) {\n                  return executor.submit(new Callable<Environment>() {\n                     @Override\n                     public Environment call() throws Exception {\n                        return api.getEnvironment(input);\n                     }\n                  });\n               }\n            }));\n\n      logger.trace(String.format(\"deleting environments: %s\", Joiner.on(',').join(toGet)));\n      return getUnchecked(futures);\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/strategy/internal/ListNodesImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.strategy.internal;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.common.util.concurrent.MoreExecutors;\nimport com.google.inject.Inject;\nimport org.jclouds.chef.ChefApi;\nimport org.jclouds.chef.config.ChefProperties;\nimport org.jclouds.chef.domain.Node;\nimport org.jclouds.chef.strategy.ListNodes;\nimport org.jclouds.logging.Logger;\n\nimport java.util.concurrent.ExecutorService;\n\n@Singleton\npublic class ListNodesImpl extends BaseListNodesImpl implements ListNodes {\n\n\n   @Resource\n   @Named(ChefProperties.CHEF_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   @Inject\n   ListNodesImpl(ChefApi api) {\n      super(api);\n   }\n\n   @Override\n   public Iterable<? extends Node> execute() {\n      return super.execute(api.listNodes());\n   }\n\n   @Override\n   public Iterable<? extends Node> execute(ExecutorService executor) {\n      return this.executeConcurrently(MoreExecutors.listeningDecorator(executor));\n   }\n\n\n   private Iterable<? extends Node> executeConcurrently(ListeningExecutorService executor) {\n      return super.executeConcurrently(executor, api.listNodes());\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/strategy/internal/ListNodesInEnvironmentImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.strategy.internal;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.common.util.concurrent.MoreExecutors;\nimport com.google.inject.Inject;\nimport org.jclouds.chef.ChefApi;\nimport org.jclouds.chef.config.ChefProperties;\nimport org.jclouds.chef.domain.Node;\nimport org.jclouds.chef.strategy.ListNodesInEnvironment;\nimport org.jclouds.logging.Logger;\n\nimport java.util.concurrent.ExecutorService;\n\n@Singleton\npublic class ListNodesInEnvironmentImpl extends BaseListNodesImpl implements ListNodesInEnvironment {\n\n   @Resource\n   @Named(ChefProperties.CHEF_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   @Inject\n   ListNodesInEnvironmentImpl(ChefApi api) {\n      super(api);\n   }\n\n   @Override\n   public Iterable<? extends Node> execute(String environmentName) {\n      return super.execute(api.listNodesInEnvironment(environmentName));\n   }\n\n   @Override\n   public Iterable<? extends Node> execute(ExecutorService executor, String environmentName) {\n      return this.executeConcurrently(MoreExecutors.listeningDecorator(executor), environmentName);\n   }\n\n\n   private Iterable<? extends Node> executeConcurrently(ListeningExecutorService executor,\n         String environmentName) {\n      return super.executeConcurrently(executor, api.listNodesInEnvironment(environmentName));\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/strategy/internal/UpdateAutomaticAttributesOnNodeImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.strategy.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.chef.ChefApi;\nimport org.jclouds.chef.config.ChefProperties;\nimport org.jclouds.chef.domain.Node;\nimport org.jclouds.chef.strategy.UpdateAutomaticAttributesOnNode;\nimport org.jclouds.domain.JsonBall;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.ohai.Automatic;\n\nimport com.google.common.base.Supplier;\n\n/**\n * \n * Updates node with new automatic attributes.\n */\n@Singleton\npublic class UpdateAutomaticAttributesOnNodeImpl implements UpdateAutomaticAttributesOnNode {\n\n   @Resource\n   @Named(ChefProperties.CHEF_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   private final ChefApi chef;\n   private final Supplier<Map<String, JsonBall>> automaticSupplier;\n\n   @Inject\n   public UpdateAutomaticAttributesOnNodeImpl(ChefApi chef, @Automatic Supplier<Map<String, JsonBall>> automaticSupplier) {\n      this.chef = checkNotNull(chef, \"chef\");\n      this.automaticSupplier = checkNotNull(automaticSupplier, \"automaticSupplier\");\n   }\n\n   @Override\n   public void execute(String nodeName) {\n      logger.trace(\"updating node %s\", nodeName);\n      Node node = chef.getNode(nodeName);\n      Node updated = Node.builder() //\n            .name(node.getName()) //\n            .normalAttributes(node.getNormalAttributes()) //\n            .overrideAttributes(node.getOverrideAttributes()) //\n            .defaultAttributes(node.getDefaultAttributes()) //\n            .automaticAttributes(automaticSupplier.get()) //\n            .runList(node.getRunList()) //\n            .environment(node.getEnvironment()) //\n            .build();\n\n      chef.updateNode(updated);\n      logger.debug(\"updated node %s\", nodeName);\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/suppliers/ChefVersionSupplier.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.suppliers;\n\nimport static com.google.common.base.MoreObjects.firstNonNull;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.chef.config.ChefProperties;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.rest.annotations.ApiVersion;\n\nimport com.google.common.base.Supplier;\n\n/**\n * Properly supply the version of the Chef Server.\n */\n@Singleton\npublic class ChefVersionSupplier implements Supplier<Integer> {\n\n   /** The default version to assume in case we can not parse it. */\n   public static final Integer FALLBACK_VERSION = 10;\n\n   @Resource\n   @Named(ChefProperties.CHEF_LOGGER)\n   private Logger logger = Logger.NULL;\n\n   /** The configured version of the Chef Server API. */\n   private final String apiVersion;\n\n   @Inject\n   ChefVersionSupplier(@ApiVersion String apiVersion) {\n      this.apiVersion = checkNotNull(apiVersion, \"apiVersion must not be null\");\n   }\n\n   @Override\n   public Integer get() {\n      // Old versions of Chef have versions like 0.9.x, 0.10.x, but newer\n      // versions are in the format 10.x.y, 11.x.y\n      Pattern versionPattern = Pattern.compile(\"(?:0\\\\.(\\\\d+)|(\\\\d+)\\\\.\\\\d+)(?:\\\\.\\\\d)*\");\n\n      Matcher m = versionPattern.matcher(apiVersion);\n      if (!m.matches()) {\n         logger.warn(\"Configured version does not match the standard version pattern. Assuming version %s\",\n               FALLBACK_VERSION);\n         return FALLBACK_VERSION;\n      }\n\n      return Integer.valueOf(firstNonNull(m.group(1), m.group(2)));\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/util/ChefUtils.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.util;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Date;\nimport java.util.List;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport org.jclouds.domain.JsonBall;\nimport org.jclouds.ohai.Automatic;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.Iterables;\nimport com.google.inject.Binder;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.multibindings.MapBinder;\n\npublic class ChefUtils {\n\n   public static Date fromOhaiTime(JsonBall ohaiDate) {\n      return new Date(Long.parseLong(checkNotNull(ohaiDate, \"ohaiDate\").toString().replaceAll(\"\\\\.[0-9]*$\", \"\")));\n   }\n\n   public static JsonBall toOhaiTime(long millis) {\n      return new JsonBall(millis + \"\");\n   }\n\n   public static MapBinder<String, Supplier<JsonBall>> ohaiAutomaticAttributeBinder(Binder binder) {\n      MapBinder<String, Supplier<JsonBall>> mapbinder = MapBinder.newMapBinder(binder, new TypeLiteral<String>() {\n      }, new TypeLiteral<Supplier<JsonBall>>() {\n      }, Automatic.class);\n      return mapbinder;\n   }\n\n   /**\n    * \n    * @return NoSuchElementException if no element in the runList is a role.\n    */\n   public static String findRoleInRunList(List<String> runList) {\n      final Pattern pattern = Pattern.compile(\"^role\\\\[(.*)\\\\]$\");\n      String roleToParse = Iterables.find(runList, new Predicate<String>() {\n\n         @Override\n         public boolean apply(String input) {\n            return pattern.matcher(input).matches();\n         }\n\n      });\n      Matcher matcher = pattern.matcher(roleToParse);\n      matcher.find();\n      return matcher.group(1);\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/util/CollectionUtils.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.util;\n\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Utility methods to work with collections.\n */\npublic class CollectionUtils {\n\n   /**\n    * Creates an immutable list with the elements of the given list. If the\n    * input list is <code>null</code>, it returns an empty list.\n    * \n    * @param input\n    *           The list used to build the immutable one.\n    * @return An immutable list with the elements of the given list.\n    */\n   public static <T> ImmutableList<T> copyOfOrEmpty(@Nullable List<T> input) {\n      return input == null ? ImmutableList.<T> of() : ImmutableList.copyOf(input);\n   }\n\n   /**\n    * Creates an immutable set with the elements of the given set. If the input\n    * set is <code>null</code>, it returns an empty set.\n    * \n    * @param input\n    *           The set used to build the immutable one.\n    * @return An immutable set with the elements of the given set.\n    */\n   public static <T> ImmutableSet<T> copyOfOrEmpty(@Nullable Set<T> input) {\n      return input == null ? ImmutableSet.<T> of() : ImmutableSet.copyOf(input);\n   }\n\n   /**\n    * Creates an immutable map with the elements of the given map. If the input\n    * map is <code>null</code>, it returns an empty map.\n    * \n    * @param input\n    *           The map used to build the immutable one.\n    * @return An immutable map with the elements of the given map.\n    */\n   public static <K, V> ImmutableMap<K, V> copyOfOrEmpty(@Nullable Map<K, V> input) {\n      return input == null ? ImmutableMap.<K, V> of() : ImmutableMap.copyOf(input);\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/chef/util/RunListBuilder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.util;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.addAll;\nimport static com.google.common.collect.Lists.newArrayList;\nimport static com.google.common.collect.Lists.transform;\n\nimport java.util.Arrays;\nimport java.util.List;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableList;\n\n/**\n * builds a run list in the correct syntax for chef.\n */\npublic class RunListBuilder {\n   private List<String> list = newArrayList();\n\n   /**\n    * Add the following recipe to the run list\n    */\n   public RunListBuilder addRecipe(String recipe) {\n      return addRecipes(checkNotNull(recipe, \"recipe\"));\n   }\n\n   /**\n    * Add the following recipes to the run list\n    */\n   public RunListBuilder addRecipes(String... recipes) {\n      addAll(list, transform(Arrays.asList(checkNotNull(recipes, \"recipes\")), new Function<String, String>() {\n\n         @Override\n         public String apply(String from) {\n            return \"recipe[\" + from + \"]\";\n         }\n\n      }));\n      return this;\n   }\n\n   /**\n    * Add the following role to the run list\n    */\n   public RunListBuilder addRole(String role) {\n      return addRoles(checkNotNull(role, \"role\"));\n   }\n\n   /**\n    * Add the following roles to the run list\n    */\n   public RunListBuilder addRoles(String... roles) {\n      addAll(list, transform(Arrays.asList(checkNotNull(roles, \"roles\")), new Function<String, String>() {\n\n         @Override\n         public String apply(String from) {\n            return \"role[\" + from + \"]\";\n         }\n\n      }));\n      return this;\n   }\n\n   public List<String> build() {\n      return ImmutableList.copyOf(list);\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/ohai/Automatic.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ohai;\n\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.ElementType.PARAMETER;\nimport static java.lang.annotation.ElementType.TYPE;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\nimport jakarta.inject.Qualifier;\n\n@Retention(RUNTIME)\n@Target({ TYPE, METHOD, PARAMETER })\n@Qualifier\npublic @interface Automatic {\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/ohai/AutomaticSupplier.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ohai;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.domain.JsonBall;\nimport org.jclouds.ohai.functions.NestSlashKeys;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.Multimap;\n\n@Singleton\npublic class AutomaticSupplier implements Supplier<Map<String, JsonBall>> {\n   private final Multimap<String, Supplier<JsonBall>> autoAttrs;\n   private final NestSlashKeys nester;\n\n   @Inject\n   AutomaticSupplier(@Automatic Multimap<String, Supplier<JsonBall>> autoAttrs, NestSlashKeys nester) {\n      this.autoAttrs = checkNotNull(autoAttrs, \"autoAttrs\");\n      this.nester = checkNotNull(nester, \"nester\");\n   }\n\n   @Override\n   public Map<String, JsonBall> get() {\n      return nester.apply(autoAttrs);\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/ohai/config/ConfiguresOhai.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ohai.config;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\nimport static java.lang.annotation.ElementType.TYPE;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\n@Retention(RUNTIME)\n@Target(TYPE)\npublic @interface ConfiguresOhai {\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/ohai/config/JMXOhaiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ohai.config;\n\nimport java.lang.management.ManagementFactory;\nimport java.lang.management.RuntimeMXBean;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.domain.JsonBall;\nimport org.jclouds.ohai.suppliers.UptimeSecondsSupplier;\n\nimport com.google.common.base.Supplier;\nimport com.google.inject.Provides;\nimport com.google.inject.multibindings.MapBinder;\n\n/**\n * Wires the components needed to parse ohai data from a JVM\n */\n@ConfiguresOhai\npublic class JMXOhaiModule extends OhaiModule {\n\n   @Provides\n   @Singleton\n   protected final RuntimeMXBean guiceProvideRuntimeMXBean() {\n      return provideRuntimeMXBean();\n   }\n\n   protected RuntimeMXBean provideRuntimeMXBean() {\n      return ManagementFactory.getRuntimeMXBean();\n   }\n\n   @Override\n   public MapBinder<String, Supplier<JsonBall>> bindOhai() {\n      MapBinder<String, Supplier<JsonBall>> mapBinder = super.bindOhai();\n      mapBinder.addBinding(\"uptime_seconds\").to(UptimeSecondsSupplier.class);\n      return mapBinder;\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/ohai/config/OhaiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ohai.config;\n\nimport static org.jclouds.chef.util.ChefUtils.ohaiAutomaticAttributeBinder;\nimport static org.jclouds.chef.util.ChefUtils.toOhaiTime;\n\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Provider;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.domain.JsonBall;\nimport org.jclouds.json.Json;\nimport org.jclouds.ohai.Automatic;\nimport org.jclouds.ohai.AutomaticSupplier;\nimport org.jclouds.ohai.functions.ByteArrayToMacAddress;\nimport org.jclouds.ohai.functions.MapSetToMultimap;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.Multimap;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Provides;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.multibindings.MapBinder;\n\n/**\n * Wires the components needed to parse ohai data\n */\n@ConfiguresOhai\npublic class OhaiModule extends AbstractModule {\n\n   @Override\n   protected void configure() {\n      bind(new TypeLiteral<Function<byte[], String>>() {\n      }).to(new TypeLiteral<ByteArrayToMacAddress>() {\n      });\n      bindOhai();\n   }\n\n   @Provides\n   @Automatic\n   protected final Supplier<Map<String, JsonBall>> guiceProvideAutomatic(AutomaticSupplier in) {\n      return provideAutomatic(in);\n   }\n\n   protected Supplier<Map<String, JsonBall>> provideAutomatic(AutomaticSupplier in) {\n      return in;\n   }\n\n   @Provides\n   @Automatic\n   final Multimap<String, Supplier<JsonBall>> provideAutomatic(MapSetToMultimap<String, Supplier<JsonBall>> converter,\n         @Automatic Map<String, Set<Supplier<JsonBall>>> input) {\n      return converter.apply(input);\n\n   }\n\n   @Named(\"systemProperties\")\n   @Provides\n   protected final Properties provideSystemProperties() {\n      return systemProperties();\n   }\n\n   protected Properties systemProperties() {\n      return System.getProperties();\n   }\n\n   public MapBinder<String, Supplier<JsonBall>> bindOhai() {\n      MapBinder<String, Supplier<JsonBall>> mapbinder = ohaiAutomaticAttributeBinder(binder()).permitDuplicates();\n      mapbinder.addBinding(\"ohai_time\").to(OhaiTimeProvider.class);\n      mapbinder.addBinding(\"jvm/system\").to(SystemPropertiesProvider.class);\n      mapbinder.addBinding(\"platform\").to(PlatformProvider.class);\n      mapbinder.addBinding(\"platform_version\").to(PlatformVersionProvider.class);\n      mapbinder.addBinding(\"current_user\").to(CurrentUserProvider.class);\n      return mapbinder;\n   }\n\n   @Singleton\n   public static class OhaiTimeProvider implements Supplier<JsonBall> {\n      private final Provider<Long> timeProvider;\n\n      @Inject\n      OhaiTimeProvider(@TimeStamp Provider<Long> timeProvider) {\n         this.timeProvider = timeProvider;\n      }\n\n      @Override\n      public JsonBall get() {\n         return toOhaiTime(timeProvider.get());\n      }\n\n   }\n\n   @Provides\n   @TimeStamp\n   protected final Long provideMillis() {\n      return millis();\n   }\n\n   protected Long millis() {\n      return System.currentTimeMillis();\n   }\n\n   @Singleton\n   public static class SystemPropertiesProvider implements Supplier<JsonBall> {\n\n      private final Json json;\n      private final Properties systemProperties;\n\n      @Inject\n      SystemPropertiesProvider(Json json, @Named(\"systemProperties\") Properties systemProperties) {\n         this.json = json;\n         this.systemProperties = systemProperties;\n      }\n\n      @Override\n      public JsonBall get() {\n         return new JsonBall(json.toJson(systemProperties));\n      }\n\n   }\n\n   @Singleton\n   public static class PlatformProvider extends SystemPropertyProvider {\n\n      @Inject\n      PlatformProvider(@Named(\"systemProperties\") Properties systemProperties) {\n         super(\"os.name\", systemProperties);\n      }\n\n      @Override\n      public JsonBall get() {\n         JsonBall returnValue = super.get();\n         return returnValue != null ? new JsonBall(returnValue.toString().replaceAll(\"[ -]\", \"\").toLowerCase()) : null;\n      }\n\n   }\n\n   @Singleton\n   public static class PlatformVersionProvider extends SystemPropertyProvider {\n\n      @Inject\n      PlatformVersionProvider(@Named(\"systemProperties\") Properties systemProperties) {\n         super(\"os.version\", systemProperties);\n      }\n\n   }\n\n   @Singleton\n   public static class CurrentUserProvider extends SystemPropertyProvider {\n\n      @Inject\n      CurrentUserProvider(@Named(\"systemProperties\") Properties systemProperties) {\n         super(\"user.name\", systemProperties);\n      }\n\n   }\n\n   public static class SystemPropertyProvider implements Supplier<JsonBall> {\n      private final Properties systemProperties;\n      private final String property;\n\n      @Inject\n      SystemPropertyProvider(String property, @Named(\"systemProperties\") Properties systemProperties) {\n         this.property = property;\n         this.systemProperties = systemProperties;\n      }\n\n      @Override\n      public JsonBall get() {\n         return systemProperties.containsKey(property) ? new JsonBall(systemProperties.getProperty(property)) : null;\n      }\n\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/ohai/functions/ByteArrayToMacAddress.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ohai.functions;\n\nimport static com.google.common.collect.Iterables.transform;\nimport static com.google.common.collect.Lists.partition;\nimport static com.google.common.io.BaseEncoding.base16;\nimport static com.google.common.primitives.Bytes.asList;\nimport static com.google.common.primitives.Bytes.toArray;\n\nimport java.util.List;\n\nimport jakarta.inject.Singleton;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Joiner;\n\n/**\n * \n * Creates a string in the form: {@code 00:26:bb:09:e6:c4 }\n */\n@Singleton\npublic class ByteArrayToMacAddress implements Function<byte[], String> {\n\n   @Override\n   public String apply(byte[] from) {\n      return Joiner.on(':').join(transform(partition(asList(from), 1), new Function<List<Byte>, String>() {\n\n         @Override\n         public String apply(List<Byte> from) {\n            return base16().lowerCase().encode(toArray(from));\n         }\n\n      }));\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/ohai/functions/MapSetToMultimap.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ohai.functions;\n\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.Map.Entry;\n\nimport jakarta.inject.Singleton;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.LinkedHashMultimap;\nimport com.google.common.collect.Multimap;\n\n@Singleton\npublic class MapSetToMultimap<K, V> implements Function<Map<K, Set<V>>, Multimap<K, V>> {\n\n   @Override\n   public Multimap<K, V> apply(Map<K, Set<V>> from) {\n      Multimap<K, V> returnV = LinkedHashMultimap.create();\n      for (Entry<K, Set<V>> entry : from.entrySet()) {\n         for (V value : entry.getValue())\n            returnV.put(entry.getKey(), value);\n      }\n      return returnV;\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/ohai/functions/NestSlashKeys.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ohai.functions;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.lang.reflect.Type;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.domain.JsonBall;\nimport org.jclouds.json.Json;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Splitter;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.Lists;\nimport com.google.common.collect.Maps;\nimport com.google.common.collect.Multimap;\nimport com.google.common.collect.Sets;\nimport com.google.inject.TypeLiteral;\n\n@Singleton\npublic class NestSlashKeys implements Function<Multimap<String, Supplier<JsonBall>>, Map<String, JsonBall>> {\n\n   private final Json json;\n\n   @Inject\n   NestSlashKeys(Json json) {\n      this.json = checkNotNull(json, \"json\");\n   }\n\n   @Override\n   public Map<String, JsonBall> apply(Multimap<String, Supplier<JsonBall>> from) {\n\n      Map<String, JsonBall> autoAttrs = mergeSameKeys(from);\n\n      Map<String, JsonBall> modifiableFlatMap = Maps.newLinkedHashMap(Maps.filterKeys(autoAttrs,\n            new Predicate<String>() {\n\n               @Override\n               public boolean apply(String input) {\n                  return input.indexOf('/') == -1;\n               }\n\n            }));\n      Map<String, JsonBall> withSlashesMap = Maps.difference(autoAttrs, modifiableFlatMap).entriesOnlyOnLeft();\n      for (Entry<String, JsonBall> entry : withSlashesMap.entrySet()) {\n         List<String> keyParts = Lists.newArrayList(Splitter.on('/').split(entry.getKey()));\n         JsonBall toInsert = entry.getValue();\n         try {\n            putUnderContext(keyParts, toInsert, modifiableFlatMap);\n         } catch (IllegalArgumentException e) {\n            throw new IllegalArgumentException(\"error inserting value in entry: \" + entry.getKey(), e);\n         }\n      }\n      return modifiableFlatMap;\n   }\n\n   private Map<String, JsonBall> mergeSameKeys(Multimap<String, Supplier<JsonBall>> from) {\n      Map<String, JsonBall> merged = Maps.newLinkedHashMap();\n      for (Entry<String, Supplier<JsonBall>> entry : from.entries()) {\n         if (merged.containsKey(entry.getKey())) {\n            mergeAsPeer(entry.getKey(), entry.getValue().get(), merged);\n         } else {\n            merged.put(entry.getKey(), entry.getValue().get());\n         }\n      }\n      return merged;\n   }\n\n   @VisibleForTesting\n   void mergeAsPeer(String key, JsonBall value, Map<String, JsonBall> insertionContext) {\n      Map<String, JsonBall> immutableValueContext = json.fromJson(insertionContext.get(key).toString(), mapLiteral);\n      Map<String, JsonBall> valueContext = Maps.newLinkedHashMap(immutableValueContext);\n      Map<String, JsonBall> toPut = json.<Map<String, JsonBall>> fromJson(value.toString(), mapLiteral);\n      Set<String> uniques = Sets.difference(toPut.keySet(), valueContext.keySet());\n      for (String k : uniques) {\n         valueContext.put(k, toPut.get(k));\n      }\n      Set<String> conflicts = Sets.difference(toPut.keySet(), uniques);\n      for (String k : conflicts) {\n         JsonBall v = toPut.get(k);\n         if (v.toString().matches(\"^\\\\{.*\\\\}$\")) {\n            mergeAsPeer(k, v, valueContext);\n         } else {\n            // replace\n            valueContext.put(k, v);\n         }\n      }\n      insertionContext.put(key, new JsonBall(json.toJson(valueContext, mapLiteral)));\n   }\n\n   /**\n    * @param keyParts\n    * @param toInsert\n    * @param destination\n    * @throws IllegalArgumentException\n    *            <p/>\n    *            if destination.get(keyParts(0)) is not a map *\n    *            <p/>\n    *            keyParts is zero length\n    */\n   void putUnderContext(List<String> keyParts, JsonBall toInsert, Map<String, JsonBall> destination) {\n      checkNotNull(keyParts, \"keyParts\");\n      checkArgument(keyParts.size() >= 1, \"keyParts must contain at least one element\");\n\n      checkNotNull(toInsert, \"toInsert\");\n      checkNotNull(destination, \"destination\");\n\n      String rootKey = keyParts.remove(0);\n      String rootValue = destination.containsKey(rootKey) ? destination.get(rootKey).toString() : \"{}\";\n\n      checkArgument(rootValue.matches(\"^\\\\{.*\\\\}$\"), \"value must be a hash: %s\", rootValue);\n      Map<String, JsonBall> immutableInsertionContext = json.fromJson(rootValue, mapLiteral);\n      Map<String, JsonBall> insertionContext = Maps.newLinkedHashMap(immutableInsertionContext);\n      if (keyParts.size() == 1) {\n         if (!insertionContext.containsKey(keyParts.get(0))) {\n            insertionContext.put(keyParts.get(0), toInsert);\n         } else {\n            String key = keyParts.get(0);\n            mergeAsPeer(key, toInsert, insertionContext);\n         }\n      } else {\n         putUnderContext(keyParts, toInsert, insertionContext);\n      }\n      destination.put(rootKey, new JsonBall(json.toJson(insertionContext, mapLiteral)));\n   }\n\n   final Type mapLiteral = new TypeLiteral<Map<String, JsonBall>>() {\n   }.getType();\n   final Type listLiteral = new TypeLiteral<List<JsonBall>>() {\n   }.getType();\n}\n"
  },
  {
    "path": "apis/chef/src/main/java/org/jclouds/ohai/suppliers/UptimeSecondsSupplier.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ohai.suppliers;\n\nimport java.lang.management.RuntimeMXBean;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.domain.JsonBall;\n\nimport com.google.common.base.Supplier;\n\n@Singleton\npublic class UptimeSecondsSupplier implements Supplier<JsonBall> {\n\n   @Inject\n   UptimeSecondsSupplier(RuntimeMXBean runtime) {\n      this.runtime = runtime;\n   }\n\n   private final RuntimeMXBean runtime;\n\n   @Override\n   public JsonBall get() {\n      long uptimeInSeconds = runtime.getUptime() / 1000;\n      return new JsonBall(uptimeInSeconds);\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/BaseChefApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef;\n\nimport org.jclouds.chef.filters.SignedHeaderAuth;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rest.internal.BaseRestApiExpectTest;\n\nimport com.google.common.base.Functions;\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Base class for Chef Api expect tests.\n */\npublic abstract class BaseChefApiExpectTest<S> extends BaseRestApiExpectTest<S> {\n   public static final String PRIVATE_KEY = \"-----BEGIN RSA PRIVATE KEY-----\\nMIIEpQIBAAKCAQEAyb2ZJJqGm0KKR+8nfQJNsSd+F9tXNMV7CfOcW6jsqs8EZgiV\\nR09hD1IYOj4YqM0qJONlgyg4xRWewdSG7QTPj1lJpVAida9sXy2+kzyagZA1Am0O\\nZcbqb5hoeIDgcX+eDa79s0u0DomjcfO9EKhvHLBz+zM+3QqPRkPV8nYTbfs+HjVz\\nzOU6D1B0XR3+IPZZl2AnWs2d0qhnStHcDUvnRVQ0P482YwN9VgceOZtpPz0DCKEJ\\n5Tx5STub8k0/zt/VAMHQafLSuQMLd2s4ZLuOZptN//uAsTmxireqd37z+8ZTdBbJ\\n8LEpJ+iCXuSfm5aUh7iw6oxvToY2AL53+jK2UQIDAQABAoIBAQDA88B3i/xWn0vX\\nBVxFamCYoecuNjGwXXkSyZew616A+EOCu47bh4aTurdFbYL0YFaAtaWvzlaN2eHg\\nDb+HDuTefE29+WkcGk6SshPmiz5T0XOCAICWw6wSVDkHmGwS4jZvbAFm7W8nwGk9\\nYhxgxFiRngswJZFopOLoF5WXs2td8guIYNslMpo7tu50iFnBHwKO2ZsPAk8t9nnS\\nxlDavKruymEmqHCr3+dtio5eaenJcp3fjoXBQOKUk3ipII29XRB8NqeCVV/7Kxwq\\nckqOBEbRwBclckyIbD+RiAgKvOelORjEiE9R42vuqvxRA6k9kd9o7utlX0AUtpEn\\n3gZc6LepAoGBAP9ael5Y75+sK2JJUNOOhO8ae45cdsilp2yI0X+UBaSuQs2+dyPp\\nkpEHAxd4pmmSvn/8c9TlEZhr+qYbABXVPlDncxpIuw2Ajbk7s/S4XaSKsRqpXL57\\nzj/QOqLkRk8+OVV9q6lMeQNqLtEj1u6JPviX70Ro+FQtRttNOYbfdP/fAoGBAMpA\\nXjR5woV5sUb+REg9vEuYo8RSyOarxqKFCIXVUNsLOx+22+AK4+CQpbueWN7jotrl\\nYD6uT6svWi3AAC7kiY0UI/fjVPRCUi8tVoQUE0TaU5VLITaYOB+W/bBaDE4M9560\\n1NuDWO90baA5dfU44iuzva02rGJXK9+nS3o8nk/PAoGBALOL6djnDe4mwAaG6Jco\\ncd4xr8jkyPzCRZuyBCSBbwphIUXLc7hDprPky064ncJD1UDmwIdkXd/fpMkg2QmA\\n/CUk6LEFjMisqHojOaCL9gQZJPhLN5QUN2x1PJWGjs1vQh8Tkx0iUUCOa8bQPXNR\\n+34OTsW6TUna4CSZAycLfhffAoGBAIggVsefBCvuQkF0NeUhmDCRZfhnd8y55RHR\\n1HCvqKIlpv+rhcX/zmyBLuteopYyRJRsOiE2FW00i8+rIPRu4Z3Q5nybx7w3PzV9\\noHN5R5baE9OyI4KpZWztpYYitZF67NcnAvVULHHOvVJQGnKYfLHJYmrJF7GA1ojM\\nAuMdFbjFAoGAPxUhxwFy8gaqBahKUEZn4F81HFP5ihGhkT4QL6AFPO2e+JhIGjuR\\n27+85hcFqQ+HHVtFsm81b/a+R7P4UuCRgc8eCjxQMoJ1Xl4n7VbjPbHMnIN0Ryvd\\nO4ZpWDWYnCO021JTOUUOJ4J/y0416Bvkw0z59y7sNX7wDBBHHbK/XCc=\\n-----END RSA PRIVATE KEY-----\\n\";\n\n   protected SignedHeaderAuth signedHeaderAuth;\n\n   public BaseChefApiExpectTest() {\n      provider = \"chef\";\n      credential = PRIVATE_KEY;\n      signedHeaderAuth = createInjector(Functions.forMap(ImmutableMap.<HttpRequest, HttpResponse> of()),\n            createModule(), setupProperties()).getInstance(SignedHeaderAuth.class);\n   }\n\n   protected HttpRequest signed(HttpRequest input) {\n      return signedHeaderAuth.filter(input);\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/ChefApiDelegationTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef;\n\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\n\nimport org.jclouds.ContextBuilder;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ChefApiDelegationTest\")\npublic class ChefApiDelegationTest {\n\n   public void testOrganizationApiNotAvailableInOldVersions() throws IOException {\n      ChefApi chef = ContextBuilder.newBuilder(new ChefApiMetadata())\n            .credentials(\"foo\", \"bar\")\n            .apiVersion(\"11.0.4\")\n            .buildApi(ChefApi.class);\n      \n      try {\n         assertFalse(chef.organizationApi().isPresent());\n      } finally {\n         chef.close();\n      }\n   }\n   \n   public void testOrganizationApiPresentInRecentVersions() throws IOException {\n      ChefApi chef = ContextBuilder.newBuilder(new ChefApiMetadata())\n            .credentials(\"foo\", \"bar\")\n            .apiVersion(\"12.0.4\")\n            .buildApi(ChefApi.class);\n      \n      try {\n         assertTrue(chef.organizationApi().isPresent());\n      } finally {\n         chef.close();\n      }\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/ChefApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.chef.config.ChefHttpApiModule;\nimport org.jclouds.chef.domain.CookbookDefinition;\nimport org.jclouds.chef.domain.Role;\nimport org.jclouds.chef.domain.SearchResult;\nimport org.jclouds.chef.options.SearchOptions;\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.inject.Module;\n\n/**\n * Expect tests for the {@link ChefApi} class.\n */\n@Test(groups = \"unit\", testName = \"ChefApiExpectTest\")\npublic class ChefApiExpectTest extends BaseChefApiExpectTest<ChefApi> {\n\n   private HttpRequest.Builder<?> getHttpRequestBuilder(String method, String endPoint) {\n      return HttpRequest.builder() //\n                  .method(method) //\n                  .endpoint(\"http://localhost:4000\" + endPoint) //\n                  .addHeader(\"X-Chef-Version\", ChefApiMetadata.DEFAULT_API_VERSION) //\n                  .addHeader(\"Accept\", MediaType.APPLICATION_JSON);\n   }\n\n   public void testListClientsReturnsValidSet() {\n      ChefApi api = requestSendsResponse(\n            signed(getHttpRequestBuilder(\"GET\", \"/clients\").build()),\n            HttpResponse.builder().statusCode(200) //\n                        .payload(payloadFromResourceWithContentType(\"/clients_list.json\", MediaType.APPLICATION_JSON)) //\n                        .build());\n      Set<String> nodes = api.listClients();\n      assertEquals(nodes.size(), 3);\n      assertTrue(nodes.contains(\"adam\"), String.format(\"Expected nodes to contain 'adam' but was: %s\", nodes));\n   }\n\n   public void testListClientsReturnsEmptySetOn404() {\n      ChefApi api = requestSendsResponse(\n            signed(getHttpRequestBuilder(\"GET\", \"/clients\").build()),\n            HttpResponse.builder().statusCode(404)\n                  .build());\n      Set<String> clients = api.listClients();\n      assertTrue(clients.isEmpty(), String.format(\"Expected clients to be empty but was: %s\", clients));\n   }\n\n   public void testListNodesReturnsValidSet() {\n      ChefApi api = requestSendsResponse(\n            signed(getHttpRequestBuilder(\"GET\", \"/nodes\").build()),\n            HttpResponse.builder().statusCode(200)\n                  .payload(payloadFromResourceWithContentType(\"/nodes_list.json\", MediaType.APPLICATION_JSON)) //\n                  .build());\n      Set<String> nodes = api.listNodes();\n      assertEquals(nodes.size(), 3);\n      assertTrue(nodes.contains(\"blah\"), String.format(\"Expected nodes to contain 'blah' but was: %s\", nodes));\n   }\n\n   public void testListNodesReturnsEmptySetOn404() {\n      ChefApi api = requestSendsResponse(\n            signed(getHttpRequestBuilder(\"GET\", \"/nodes\").build()),\n            HttpResponse.builder().statusCode(404).build());\n      Set<String> nodes = api.listNodes();\n      assertTrue(nodes.isEmpty(), String.format(\"Expected nodes to be empty but was: %s\", nodes));\n   }\n\n   public void testListRecipesInEnvironmentReturnsValidSet() {\n      ChefApi api = requestSendsResponse(\n            signed(getHttpRequestBuilder(\"GET\", \"/environments/dev/recipes\").build()),\n            HttpResponse.builder().statusCode(200)\n                  .payload(payloadFromResourceWithContentType(\"/environment_recipes.json\", MediaType.APPLICATION_JSON)) //\n                  .build());\n      Set<String> recipes = api.listRecipesInEnvironment(\"dev\");\n      assertEquals(recipes.size(), 3);\n      assertTrue(recipes.contains(\"apache2\"), String.format(\"Expected recipes to contain 'apache2' but was: %s\", recipes));\n   }\n\n   public void testListRecipesInEnvironmentReturnsEmptySetOn404() {\n      ChefApi api = requestSendsResponse(\n            signed(getHttpRequestBuilder(\"GET\", \"/environments/dev/recipes\").build()),\n            HttpResponse.builder().statusCode(404).build());\n      Set<String> recipes = api.listRecipesInEnvironment(\"dev\");\n      assertTrue(recipes.isEmpty(), String.format(\"Expected recipes to be empty but was: %s\", recipes));\n   }\n\n   public void testListNodesInEnvironmentReturnsValidSet() {\n      ChefApi api = requestSendsResponse(\n            signed(getHttpRequestBuilder(\"GET\", \"/environments/dev/nodes\").build()),\n            HttpResponse.builder().statusCode(200)\n                  .payload(payloadFromResourceWithContentType(\"/nodes_list.json\", MediaType.APPLICATION_JSON)) //\n                  .build());\n      Set<String> nodes = api.listNodesInEnvironment(\"dev\");\n      assertEquals(nodes.size(), 3);\n      assertTrue(nodes.contains(\"blah\"), String.format(\"Expected nodes to contain 'blah' but was: %s\", nodes));\n   }\n\n   public void testListNodesInEnvironmentReturnsEmptySetOn404() {\n      ChefApi api = requestSendsResponse(\n            signed(getHttpRequestBuilder(\"GET\", \"/environments/dev/nodes\").build()),\n            HttpResponse.builder().statusCode(404).build());\n      Set<String> nodes = api.listNodesInEnvironment(\"dev\");\n      assertTrue(nodes.isEmpty(), String.format(\"Expected nodes to be empty but was: %s\", nodes));\n   }\n\n   public void testListCookbooksReturnsValidSet() {\n      ChefApi api = requestSendsResponse(\n            signed(getHttpRequestBuilder(\"GET\", \"/cookbooks\").build()),\n            HttpResponse.builder().statusCode(200)\n                  .payload(payloadFromResourceWithContentType(\"/env_cookbooks.json\", MediaType.APPLICATION_JSON)) //\n                  .build());\n      Set<String> cookbooks = api.listCookbooks();\n      assertEquals(cookbooks.size(), 2);\n      assertTrue(cookbooks.contains(\"apache2\"), String.format(\"Expected cookbooks to contain 'apache2' but was: %s\", cookbooks));\n   }\n\n   public void testListCookbooksReturnsEmptySetOn404() {\n      ChefApi api = requestSendsResponse(\n            signed(getHttpRequestBuilder(\"GET\", \"/cookbooks\").build()),\n            HttpResponse.builder().statusCode(404).build());\n      Set<String> cookbooks = api.listCookbooks();\n      assertTrue(cookbooks.isEmpty(), String.format(\"Expected cookbooks to be empty but was: %s\", cookbooks));\n   }\n\n   public void testListCookbooksInEnvironmentReturnsValidSet() {\n      ChefApi api = requestSendsResponse(\n            signed(getHttpRequestBuilder(\"GET\", \"/environments/dev/cookbooks\").build()),\n            HttpResponse.builder().statusCode(200)\n                  .payload(payloadFromResourceWithContentType(\"/env_cookbooks.json\", MediaType.APPLICATION_JSON)) //\n                  .build());\n      Set<CookbookDefinition> cookbooks = api.listCookbooksInEnvironment(\"dev\");\n      assertEquals(cookbooks.size(), 2);\n   }\n\n   public void testListCookbooksInEnvironmentReturnsEmptySetOn404() {\n      ChefApi api = requestSendsResponse(\n            signed(getHttpRequestBuilder(\"GET\", \"/environments/dev/cookbooks\").build()),\n            HttpResponse.builder().statusCode(404).build());\n      Set<CookbookDefinition> cookbooks = api.listCookbooksInEnvironment(\"dev\");\n      assertTrue(cookbooks.isEmpty(), String.format(\"Expected cookbooks to be empty but was: %s\", cookbooks));\n   }\n\n   public void testListCookbooksInEnvironmentWithNumVersionReturnsEmptySetOn404() {\n      ChefApi api = requestSendsResponse(\n            signed(getHttpRequestBuilder(\"GET\", \"/environments/dev/cookbooks\").addQueryParam(\"num_versions\", \"2\").build()),\n            HttpResponse.builder().statusCode(404).build());\n      Set<CookbookDefinition> cookbooks = api.listCookbooksInEnvironment(\"dev\", \"2\");\n      assertTrue(cookbooks.isEmpty(), String.format(\"Expected cookbooks to be empty but was: %s\", cookbooks));\n   }\n\n   public void testSearchRolesReturnsValidResult() {\n      ChefApi api = requestSendsResponse(\n            signed(getHttpRequestBuilder(\"GET\", \"/search/role\").build()),\n            HttpResponse.builder().statusCode(200)\n                  .payload(payloadFromResourceWithContentType(\"/search_role.json\", MediaType.APPLICATION_JSON)) //\n                  .build());\n      SearchResult<? extends Role> result = api.searchRoles();\n      assertEquals(result.size(), 1);\n      assertEquals(result.iterator().next().getName(), \"webserver\");\n   }\n\n   public void testSearchRolesReturnsEmptyResult() {\n      ChefApi api = requestSendsResponse(\n            signed(getHttpRequestBuilder(\"GET\", \"/search/role\").build()),\n            HttpResponse.builder().statusCode(200)\n                  .payload(payloadFromResourceWithContentType(\"/search_role_empty.json\", MediaType.APPLICATION_JSON)) //\n                  .build());\n      SearchResult<? extends Role> result = api.searchRoles();\n      assertTrue(result.isEmpty(), String.format(\"Expected search result to be empty but was: %s\", result));\n   }\n\n   public void testSearchRolesWithOptionsReturnsValidResult() {\n      ChefApi api = requestSendsResponse(\n            signed(getHttpRequestBuilder(\"GET\", \"/search/role\").addQueryParam(\"q\", \"name:webserver\").build()),\n            HttpResponse.builder().statusCode(200)\n                  .payload(payloadFromResourceWithContentType(\"/search_role.json\", MediaType.APPLICATION_JSON)) //\n                  .build());\n      SearchOptions options = SearchOptions.Builder.query(\"name:webserver\");\n      SearchResult<? extends Role> result = api.searchRoles(options);\n      assertEquals(result.size(), 1);\n      assertEquals(result.iterator().next().getName(), \"webserver\");\n   }\n\n   public void testSearchRolesWithOptionsReturnsEmptyResult() {\n      ChefApi api = requestSendsResponse(\n            signed(getHttpRequestBuilder(\"GET\", \"/search/role\").addQueryParam(\"q\", \"name:dummy\").build()),\n            HttpResponse.builder().statusCode(200)\n                  .payload(payloadFromResourceWithContentType(\"/search_role_empty.json\", MediaType.APPLICATION_JSON)) //\n                  .build());\n      SearchOptions options = SearchOptions.Builder.query(\"name:dummy\");\n      SearchResult<? extends Role> result = api.searchRoles(options);\n      assertTrue(result.isEmpty(), String.format(\"Expected search result to be empty but was: %s\", result));\n   }\n\n   public void testListRolesReturnsValidSet() {\n      ChefApi api = requestSendsResponse(\n            signed(getHttpRequestBuilder(\"GET\", \"/roles\").build()),\n            HttpResponse.builder().statusCode(200)\n                  .payload(payloadFromResourceWithContentType(\"/roles_list.json\", MediaType.APPLICATION_JSON)) //\n                  .build());\n      Set<String> roles = api.listRoles();\n      assertEquals(roles.size(), 2);\n      assertTrue(roles.contains(\"webserver\"), String.format(\"Expected roles to contain 'websever' but was: %s\", roles));\n   }\n\n   public void testListRolesReturnsEmptySetOn404() {\n      ChefApi api = requestSendsResponse(\n            signed(getHttpRequestBuilder(\"GET\", \"/roles\").build()),\n            HttpResponse.builder().statusCode(404).build());\n      Set<String> roles = api.listRoles();\n      assertTrue(roles.isEmpty(), String.format(\"Expected roles to be empty but was: %s\", roles));\n   }\n\n   public void testListDatabagsReturnsValidSet() {\n      ChefApi api = requestSendsResponse(\n            signed(getHttpRequestBuilder(\"GET\", \"/data\").build()),\n            HttpResponse.builder().statusCode(200)\n                  .payload(payloadFromResourceWithContentType(\"/data_list.json\", MediaType.APPLICATION_JSON)) //\n                  .build());\n      Set<String> databags = api.listDatabags();\n      assertEquals(databags.size(), 2);\n      assertTrue(databags.contains(\"applications\"), String.format(\"Expected databags to contain 'applications' but was: %s\", databags));\n   }\n\n   public void testListDatabagsReturnsEmptySetOn404() {\n      ChefApi api = requestSendsResponse(\n            signed(getHttpRequestBuilder(\"GET\", \"/data\").build()),\n            HttpResponse.builder().statusCode(404).build());\n      Set<String> databags = api.listDatabags();\n      assertTrue(databags.isEmpty(), String.format(\"Expected databags to be empty but was: %s\", databags));\n   }\n\n   @Override\n   protected Module createModule() {\n      return new TestChefHttpApiModule();\n   }\n\n   @ConfiguresHttpApi\n   static class TestChefHttpApiModule extends ChefHttpApiModule {\n      @Override\n      protected String provideTimeStamp(@TimeStamp Supplier<String> cache) {\n         return \"timestamp\";\n      }\n   }\n\n   @Override\n   protected ChefApiMetadata createApiMetadata() {\n      return new ChefApiMetadata();\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/ChefApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef;\n\nimport static com.google.common.collect.Iterables.any;\nimport static com.google.common.collect.Iterables.isEmpty;\nimport static com.google.common.hash.Hashing.md5;\nimport static java.util.concurrent.TimeUnit.MILLISECONDS;\nimport static org.jclouds.chef.domain.RoleTest.verifyRunListForEnvironment;\nimport static org.jclouds.util.Closeables2.closeQuietly;\nimport static org.jclouds.util.Predicates2.retry;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.Assert.fail;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport org.jclouds.chef.domain.ChecksumStatus;\nimport org.jclouds.chef.domain.Client;\nimport org.jclouds.chef.domain.CookbookDefinition;\nimport org.jclouds.chef.domain.CookbookVersion;\nimport org.jclouds.chef.domain.DatabagItem;\nimport org.jclouds.chef.domain.Environment;\nimport org.jclouds.chef.domain.Metadata;\nimport org.jclouds.chef.domain.Node;\nimport org.jclouds.chef.domain.Resource;\nimport org.jclouds.chef.domain.Role;\nimport org.jclouds.chef.domain.Sandbox;\nimport org.jclouds.chef.domain.SearchResult;\nimport org.jclouds.chef.domain.UploadSandbox;\nimport org.jclouds.chef.internal.BaseChefLiveTest;\nimport org.jclouds.chef.options.CreateClientOptions;\nimport org.jclouds.chef.options.SearchOptions;\nimport org.jclouds.crypto.Pems;\nimport org.jclouds.io.ByteStreams2;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.io.payloads.FilePayload;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.hash.Hashing;\nimport com.google.common.io.Files;\nimport com.google.common.primitives.Bytes;\n\n/**\n * Tests behavior of {@code ChefApi}\n */\n@Test(groups = { \"live\", \"integration\" })\npublic class ChefApiLiveTest extends BaseChefLiveTest {\n   public static final String PREFIX = \"jcloudstest-\" + System.getProperty(\"user.name\");\n   public static final String ADMIN_PREFIX = \"jcloudstest-adm-\" + System.getProperty(\"user.name\");\n   public static final String ENV_NODE = PREFIX + \"-env-node\";\n\n   // It may take a bit until the search index is populated\n   protected int maxWaitForIndexInMs = 60000;\n\n   // The id of the data bag item used in search tests\n   private String databagitemId;\n\n   public void testCreateNewCookbook() throws Exception {\n      // Define the file you want in the cookbook\n      File file = new File(System.getProperty(\"user.dir\"), \"pom.xml\");\n      FilePayload content = uploadAndGetFilePayload(file);\n\n      // Create the metadata of the cookbook\n      Metadata metadata = Metadata.builder() //\n            .name(PREFIX) //\n            .version(\"0.0.0\") //\n            .description(\"Jclouds test uploaded cookbook\") //\n            .maintainer(\"jclouds\") //\n            .maintainerEmail(\"someone@jclouds.org\") //\n            .license(\"Apache 2.0\") //\n            .build();\n\n      // Create a new cookbook\n      CookbookVersion cookbook = CookbookVersion.builder(PREFIX, \"0.0.0\") //\n            .metadata(metadata) //\n            .rootFile(Resource.builder().fromPayload(content).build()) //\n            .attribute(Resource.builder().fromPayload(content).name(\"default.rb\").build())\n            .build();\n\n      // upload the cookbook to the remote server\n      api.updateCookbook(PREFIX, \"0.0.0\", cookbook);\n   }\n\n   private FilePayload uploadAndGetFilePayload(File file) throws IOException {\n      FilePayload content = Payloads.newFilePayload(file);\n      content.getContentMetadata().setContentType(\"application/x-binary\");\n\n      // Get an md5 so that you can see if the server already has it or not\n      content.getContentMetadata().setContentMD5(Files.asByteSource(file).hash(Hashing.md5()).asBytes());\n\n      // Note that java collections cannot effectively do equals or hashcodes on\n      // byte arrays, so let's convert to a list of bytes.\n      List<Byte> md5 = Bytes.asList(content.getContentMetadata().getContentMD5());\n\n      // Request an upload site for this file\n      UploadSandbox site = api.createUploadSandboxForChecksums(ImmutableSet.of(md5));\n      assertTrue(site.getChecksums().containsKey(md5), md5 + \" not in \" + site.getChecksums());\n\n      try {\n         // Upload the file contents, if still not uploaded\n         ChecksumStatus status = site.getChecksums().get(md5);\n         if (status.needsUpload()) {\n            api.uploadContent(status.getUrl(), content);\n         }\n         Sandbox sandbox = api.commitSandbox(site.getSandboxId(), true);\n         assertTrue(sandbox.isCompleted(), \"Sandbox should be completed after uploading\");\n      } catch (RuntimeException e) {\n         api.commitSandbox(site.getSandboxId(), false);\n         fail(\"Could not upload content\");\n      }\n      return content;\n   }\n\n   public void testListCookbooks() throws Exception {\n      Set<String> cookbookNames = api.listCookbooks();\n      assertFalse(cookbookNames.isEmpty(), \"No cookbooks were found\");\n\n      for (String cookbookName : cookbookNames) {\n         Set<String> versions = api.listVersionsOfCookbook(cookbookName);\n         assertFalse(versions.isEmpty(), \"There are no versions of the cookbook: \" + cookbookName);\n\n         for (String version : api.listVersionsOfCookbook(cookbookName)) {\n            CookbookVersion cookbook = api.getCookbook(cookbookName, version);\n            assertNotNull(cookbook, \"Could not get cookbook: \" + cookbookName);\n         }\n      }\n   }\n\n   @Test(dependsOnMethods = \"testListCookbooks\")\n   public void testListCookbookVersionsWithChefService() throws Exception {\n      Iterable<? extends CookbookVersion> cookbooks = chefService.listCookbookVersions();\n      assertFalse(isEmpty(cookbooks), \"No cookbooks were found\");\n   }\n\n   @Test(dependsOnMethods = \"testListCookbookVersionsWithChefService\")\n   public void testDownloadCookbooks() throws Exception {\n      Iterable<? extends CookbookVersion> cookbooks = chefService.listCookbookVersions();\n      for (CookbookVersion cookbook : cookbooks) {\n         for (Resource resource : ImmutableList.<Resource> builder().addAll(cookbook.getDefinitions())\n                 .addAll(cookbook.getFiles()).addAll(cookbook.getLibraries()).addAll(cookbook.getSuppliers())\n                 .addAll(cookbook.getRecipes()).addAll(cookbook.getResources()).addAll(cookbook.getRootFiles())\n                 .addAll(cookbook.getTemplates()).addAll(cookbook.getAttributes()).build()) {\n\n            InputStream stream = api.getResourceContents(resource);\n            assertNotNull(stream, \"Resource contents are null for resource: \" + resource.getName());\n\n            byte[] md5 = ByteStreams2.hashAndClose(stream, md5()).asBytes();\n            assertEquals(md5, resource.getChecksum());\n         }\n      }\n   }\n\n   @Test(dependsOnMethods = \"testCreateNewCookbook\")\n   public void testUpdateCookbook() throws Exception {\n      CookbookVersion cookbook = api.getCookbook(PREFIX, \"0.0.0\");\n      assertNotNull(cookbook, \"Cookbook not found: \" + PREFIX);\n      assertNotNull(api.updateCookbook(PREFIX, \"0.0.0\", cookbook), \"Updated cookbook was null\");\n   }\n\n   @Test(dependsOnMethods = { \"testCreateNewCookbook\", \"testUpdateCookbook\" })\n   public void testDeleteCookbook() throws Exception {\n      assertNotNull(api.deleteCookbook(PREFIX, \"0.0.0\"), \"Deleted cookbook was null\");\n   }\n\n   @Test\n   public void testCreateClient() throws Exception {\n      api.deleteClient(PREFIX);\n      String credential = Pems.pem(api.createClient(PREFIX).getPrivateKey());\n      assertClientCreated(PREFIX, credential);\n   }\n\n   @Test\n   public void testCreateAdminClient() throws Exception {\n      api.deleteClient(ADMIN_PREFIX);\n      String credential = Pems.pem(api.createClient(ADMIN_PREFIX, CreateClientOptions.Builder.admin()).getPrivateKey());\n      assertClientCreated(ADMIN_PREFIX, credential);\n   }\n\n   @Test(dependsOnMethods = \"testCreateClient\")\n   public void testGenerateKeyForClient() throws Exception {\n      String credential = Pems.pem(api.generateKeyForClient(PREFIX).getPrivateKey());\n      assertClientCreated(PREFIX, credential);\n   }\n\n   @Test\n   public void testListNodes() throws Exception {\n      Set<String> nodes = api.listNodes();\n      assertNotNull(nodes, \"No nodes were found\");\n   }\n\n   @Test(dependsOnMethods = \"testCreateRole\")\n   public void testCreateNode() throws Exception {\n      api.deleteNode(PREFIX);\n      api.createNode(Node.builder().name(PREFIX).runListElement(\"role[\" + PREFIX + \"]\").environment(\"_default\").build());\n      Node node = api.getNode(PREFIX);\n      // TODO check recipes\n      assertNotNull(node, \"Created node should not be null\");\n      Set<String> nodes = api.listNodes();\n      assertTrue(nodes.contains(PREFIX), String.format(\"node %s not in %s\", PREFIX, nodes));\n   }\n\n   @Test(dependsOnMethods = \"testCreateNode\")\n   public void testUpdateNode() throws Exception {\n      for (String nodename : api.listNodes()) {\n         Node node = api.getNode(nodename);\n         api.updateNode(node);\n      }\n   }\n\n   @Test\n   public void testListRoles() throws Exception {\n      Set<String> roles = api.listRoles();\n      assertNotNull(roles, \"Role list was null\");\n   }\n\n   @Test\n   public void testCreateRole() throws Exception {\n      String env1 = \"env1\";\n      String env2 = \"env2\";\n      String env1Alpha = \"recipe[env1.alpha]\";\n      String env2Alpha = \"recipe[env2.alpha]\";\n      String env2Bravo = \"recipe[env2.bravo]\";\n\n      api.deleteRole(PREFIX);\n      api.createRole(Role.builder().name(PREFIX).runListElement(\"recipe[java]\")\n            .envRunListElement(env1, env1Alpha)\n            .envRunListElement(env2, env2Alpha)\n            .envRunListElement(env2, env2Bravo)\n            .build());\n      Role role = api.getRole(PREFIX);\n      assertNotNull(role, \"Created role should not be null\");\n      assertEquals(role.getName(), PREFIX);\n      assertEquals(role.getRunList(), Collections.singleton(\"recipe[java]\"));\n\n      assertNotNull(role.getEnvRunList(), \"envRunList should not be null\");\n      assertEquals(role.getEnvRunList().size(), 2, \"envRunList.size should be 2\");\n      verifyRunListForEnvironment(role.getEnvRunList(), env1, env1Alpha);\n      verifyRunListForEnvironment(role.getEnvRunList(), env2, env2Alpha, env2Bravo);\n   }\n\n   @Test(dependsOnMethods = \"testCreateRole\")\n   public void testUpdateRole() throws Exception {\n      for (String rolename : api.listRoles()) {\n         Role role = api.getRole(rolename);\n         api.updateRole(role);\n      }\n   }\n\n   @Test\n   public void testListDatabags() throws Exception {\n      Set<String> databags = api.listDatabags();\n      assertNotNull(databags, \"Data bag list was null\");\n   }\n\n   @Test\n   public void testCreateDatabag() throws Exception {\n      api.deleteDatabag(PREFIX);\n      api.createDatabag(PREFIX);\n   }\n\n   @Test(dependsOnMethods = \"testCreateDatabagItem\")\n   public void testListDatabagItems() throws Exception {\n      Set<String> databagItems = api.listDatabagItems(PREFIX);\n      assertNotNull(databagItems, \"Data bag item list was null\");\n   }\n\n   @Test(dependsOnMethods = \"testCreateDatabag\")\n   public void testCreateDatabagItem() throws Exception {\n      Properties config = new Properties();\n      config.setProperty(\"foo\", \"bar\");\n      api.deleteDatabagItem(PREFIX, PREFIX);\n      DatabagItem databagItem = api.createDatabagItem(PREFIX, new DatabagItem(\"config\", json.toJson(config)));\n      databagitemId = databagItem.getId();\n      assertNotNull(databagItem, \"Created data bag item should not be null\");\n      assertEquals(databagItem.getId(), \"config\");\n\n      // The databagItem json contains extra keys: (the name and the type if the\n      // item)\n      Properties props = json.fromJson(databagItem.toString(), Properties.class);\n      for (Object key : config.keySet()) {\n         assertTrue(props.containsKey(key));\n         assertEquals(config.get(key), props.get(key));\n      }\n   }\n\n   @Test(dependsOnMethods = \"testCreateDatabagItem\")\n   public void testUpdateDatabagItem() throws Exception {\n      for (String databagItemId : api.listDatabagItems(PREFIX)) {\n         DatabagItem databagItem = api.getDatabagItem(PREFIX, databagItemId);\n         api.updateDatabagItem(PREFIX, databagItem);\n      }\n   }\n\n   @Test(dependsOnMethods = \"testSearchDatabagWithOptions\")\n   public void testDeleteDatabagItem() throws Exception {\n      for (String databagItemId : api.listDatabagItems(PREFIX)) {\n         DatabagItem databagItem = api.deleteDatabagItem(PREFIX, databagItemId);\n         assertNotNull(databagItem, \"Deleted data bag item should not be null\");\n         assertEquals(databagItem.getId(), databagItemId, \"Deleted data bag item id must match the original id\");\n         assertNull(api.getDatabagItem(PREFIX, databagItemId), \"Data bag item should not exist\");\n      }\n   }\n\n   @Test\n   public void testListSearchIndexes() throws Exception {\n      Set<String> indexes = api.listSearchIndexes();\n      assertNotNull(indexes, \"The index list should not be null\");\n      assertTrue(indexes.contains(\"node\"));\n      assertTrue(indexes.contains(\"client\"));\n      assertTrue(indexes.contains(\"role\"));\n   }\n\n   @Test\n   public void testSearchNodes() throws Exception {\n      SearchResult<? extends Node> results = api.searchNodes();\n      assertNotNull(results, \"Node result list should not be null\");\n   }\n\n   @Test(dependsOnMethods = { \"testListSearchIndexes\", \"testCreateNode\" })\n   public void testSearchNodesWithOptions() throws Exception {\n      Predicate<SearchOptions> waitForIndex = retry(new Predicate<SearchOptions>() {\n         @Override\n         public boolean apply(SearchOptions input) {\n            SearchResult<? extends Node> results = api.searchNodes(input);\n            assertNotNull(results);\n            if (results.size() > 0) {\n               assertEquals(results.size(), 1);\n               assertEquals(results.iterator().next().getName(), PREFIX);\n               return true;\n            } else {\n               // The index may still not be populated\n               return false;\n            }\n         }\n      }, maxWaitForIndexInMs, 5000L, MILLISECONDS);\n\n      SearchOptions options = SearchOptions.Builder.query(\"name:\" + PREFIX);\n      assertTrue(waitForIndex.apply(options));\n   }\n\n   @Test\n   public void testSearchClients() throws Exception {\n      SearchResult<? extends Client> results = api.searchClients();\n      assertNotNull(results, \"Client result list should not be null\");\n   }\n\n   @Test(dependsOnMethods = { \"testListSearchIndexes\", \"testCreateClient\" })\n   public void testSearchClientsWithOptions() throws Exception {\n      Predicate<SearchOptions> waitForIndex = retry(new Predicate<SearchOptions>() {\n         @Override\n         public boolean apply(SearchOptions input) {\n            SearchResult<? extends Client> results = api.searchClients(input);\n            assertNotNull(results);\n            if (results.size() > 0) {\n               assertEquals(results.size(), 1);\n               assertEquals(results.iterator().next().getName(), PREFIX);\n               return true;\n            } else {\n               // The index may still not be populated\n               return false;\n            }\n         }\n      }, maxWaitForIndexInMs, 5000L, MILLISECONDS);\n\n      SearchOptions options = SearchOptions.Builder.query(\"name:\" + PREFIX);\n      assertTrue(waitForIndex.apply(options));\n   }\n\n   @Test\n   public void testSearchRoles() throws Exception {\n      SearchResult<? extends Role> results = api.searchRoles();\n      assertNotNull(results, \"Role result list should not be null\");\n   }\n\n   @Test(dependsOnMethods = { \"testListSearchIndexes\", \"testCreateRole\" })\n   public void testSearchRolesWithOptions() throws Exception {\n      Predicate<SearchOptions> waitForIndex = retry(new Predicate<SearchOptions>() {\n         @Override\n         public boolean apply(SearchOptions input) {\n            SearchResult<? extends Role> results = api.searchRoles(input);\n            assertNotNull(results);\n            if (results.size() > 0) {\n               assertEquals(results.size(), 1);\n               assertEquals(results.iterator().next().getName(), PREFIX);\n               return true;\n            } else {\n               // The index may still not be populated\n               return false;\n            }\n         }\n      }, maxWaitForIndexInMs, 5000L, MILLISECONDS);\n\n      SearchOptions options = SearchOptions.Builder.query(\"name:\" + PREFIX);\n      assertTrue(waitForIndex.apply(options));\n   }\n\n   @Test(dependsOnMethods = { \"testListSearchIndexes\", \"testCreateDatabagItem\" })\n   public void testSearchDatabag() throws Exception {\n      SearchResult<? extends DatabagItem> results = api.searchDatabagItems(PREFIX);\n      assertNotNull(results, \"Data bag item result list should not be null\");\n   }\n\n   @Test(dependsOnMethods = { \"testListSearchIndexes\", \"testCreateDatabagItem\" })\n   public void testSearchDatabagWithOptions() throws Exception {\n      Predicate<SearchOptions> waitForIndex = retry(new Predicate<SearchOptions>() {\n         @Override\n         public boolean apply(SearchOptions input) {\n            SearchResult<? extends DatabagItem> results = api.searchDatabagItems(PREFIX, input);\n            assertNotNull(results);\n            if (results.size() > 0) {\n               assertEquals(results.size(), 1);\n               assertEquals(results.iterator().next().getId(), databagitemId);\n               return true;\n            } else {\n               // The index may still not be populated\n               return false;\n            }\n         }\n      }, maxWaitForIndexInMs, 5000L, MILLISECONDS);\n\n      SearchOptions options = SearchOptions.Builder.query(\"id:\" + databagitemId);\n      assertTrue(waitForIndex.apply(options));\n   }\n\n   @Test(expectedExceptions = ResourceNotFoundException.class, dependsOnMethods = \"testListSearchIndexes\")\n   public void testSearchDatabagNotFound() throws Exception {\n      SearchResult<? extends DatabagItem> results = api.searchDatabagItems(\"whoopie\");\n      assertNotNull(results, \"Data bag item result list should not be null\");\n   }\n\n   @Test\n   public void testCreateEnvironment() {\n      api.deleteEnvironment(PREFIX);\n      api.createEnvironment(Environment.builder().name(PREFIX).description(PREFIX).build());\n      Environment env = api.getEnvironment(PREFIX);\n      assertNotNull(env, \"Created environment should not be null\");\n      assertEquals(env.getName(), PREFIX);\n      assertEquals(env.getDescription(), PREFIX);\n   }\n\n   @Test(dependsOnMethods = \"testCreateEnvironment\")\n   public void testListEnvironment() {\n      Set<String> envList = api.listEnvironments();\n      assertNotNull(envList, \"Environment list was null\");\n      assertTrue(envList.contains(PREFIX));\n   }\n\n   @Test(dependsOnMethods = \"testCreateEnvironment\")\n   public void testSearchEnvironments() throws Exception {\n      SearchResult<? extends Environment> results = api.searchEnvironments();\n      assertNotNull(results, \"Environment result list was null\");\n   }\n\n   @Test(dependsOnMethods = { \"testListSearchIndexes\", \"testCreateEnvironment\" })\n   public void testSearchEnvironmentsWithOptions() throws Exception {\n      Predicate<SearchOptions> waitForIndex = retry(new Predicate<SearchOptions>() {\n         @Override\n         public boolean apply(SearchOptions input) {\n            SearchResult<? extends Environment> results = api.searchEnvironments(input);\n            assertNotNull(results);\n            if (results.size() > 0) {\n               assertEquals(results.size(), 1);\n               assertEquals(results.iterator().next().getName(), PREFIX);\n               return true;\n            } else {\n               // The index may still not be populated\n               return false;\n            }\n         }\n      }, maxWaitForIndexInMs, 5000L, MILLISECONDS);\n\n      SearchOptions options = SearchOptions.Builder.query(\"name:\" + PREFIX);\n      assertTrue(waitForIndex.apply(options));\n   }\n\n   @Test(dependsOnMethods = \"testCreateEnvironment\")\n   public void testListRecipesInEnvironment() {\n      Set<String> recipeList = api.listRecipesInEnvironment(PREFIX);\n      assertTrue(!recipeList.isEmpty());\n   }\n\n   @Test(dependsOnMethods = \"testCreateEnvironment\")\n   public void testListNodesInEnvironment() {\n      api.deleteNode(ENV_NODE);\n      api.createNode(Node.builder().name(ENV_NODE).runListElement(\"role[\" + PREFIX + \"]\").environment(PREFIX).build());\n      Node node = api.getNode(ENV_NODE);\n      assertNotNull(node, \"Created node should not be null\");\n      Set<String> nodeList = api.listNodesInEnvironment(PREFIX);\n      assertTrue(!nodeList.isEmpty());\n   }\n\n   @Test(dependsOnMethods = \"testCreateNewCookbook\")\n   public void testListCookbooksInEnvironment() throws Exception {\n      Set<CookbookDefinition> cookbooks = api.listCookbooksInEnvironment(\"_default\");\n      assertTrue(any(cookbooks, new Predicate<CookbookDefinition>() {\n         @Override\n         public boolean apply(CookbookDefinition input) {\n            return PREFIX.equals(input.getName());\n         }}), String.format(\"Cookbook %s not in %s\", PREFIX, cookbooks));\n   }\n\n   @AfterClass(groups = { \"live\", \"integration\" })\n   @Override\n   public void tearDown() {\n      api.deleteClient(PREFIX);\n      api.deleteClient(ADMIN_PREFIX);\n      api.deleteNode(PREFIX);\n      api.deleteNode(ENV_NODE);\n      api.deleteRole(PREFIX);\n      api.deleteDatabag(PREFIX);\n      api.deleteEnvironment(PREFIX);\n      super.tearDown();\n   }\n\n   private void assertClientCreated(String identity, String credential) {\n      Properties overrides = super.setupProperties();\n      overrides.setProperty(provider + \".identity\", identity);\n      overrides.setProperty(provider + \".credential\", credential);\n\n      ChefApi clientApi = create(overrides, setupModules());\n\n      try {\n         Client client = clientApi.getClient(identity);\n         assertNotNull(client, \"Client not found: \" + identity);\n      } finally {\n         closeQuietly(clientApi);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/ChefApiMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef;\n\nimport org.jclouds.View;\nimport org.jclouds.rest.internal.BaseHttpApiMetadataTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.reflect.TypeToken;\n\n@Test(groups = \"unit\", testName = \"ChefApiMetadataTest\")\npublic class ChefApiMetadataTest extends BaseHttpApiMetadataTest {\n\n   // no config management abstraction, yet\n   public ChefApiMetadataTest() {\n      super(new ChefApiMetadata(), ImmutableSet.<TypeToken<? extends View>> of());\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/ChefApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef;\n\nimport static com.google.common.io.BaseEncoding.base16;\nimport static com.google.common.primitives.Bytes.asList;\nimport static org.jclouds.reflect.Reflection2.method;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.net.URI;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport org.jclouds.Constants;\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.chef.config.ChefHttpApiModule;\nimport org.jclouds.chef.domain.CookbookVersion;\nimport org.jclouds.chef.domain.DatabagItem;\nimport org.jclouds.chef.domain.Node;\nimport org.jclouds.chef.domain.Resource;\nimport org.jclouds.chef.domain.Role;\nimport org.jclouds.chef.filters.SignedHeaderAuth;\nimport org.jclouds.chef.filters.SignedHeaderAuthTest;\nimport org.jclouds.chef.functions.ParseCookbookVersionsFromJson;\nimport org.jclouds.chef.functions.ParseKeySetFromJson;\nimport org.jclouds.chef.functions.ParseSearchClientsFromJson;\nimport org.jclouds.chef.functions.ParseSearchDatabagFromJson;\nimport org.jclouds.chef.functions.ParseSearchNodesFromJson;\nimport org.jclouds.chef.options.CreateClientOptions;\nimport org.jclouds.chef.options.SearchOptions;\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.fallbacks.MapHttp4xxCodesToExceptions;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.functions.ParseFirstJsonValueNamed;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.http.functions.ReleasePayloadAndReturn;\nimport org.jclouds.http.functions.ReturnInputStream;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.payloads.StringPayload;\nimport org.jclouds.reflect.Invocation;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.internal.BaseRestAnnotationProcessingTest;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.reflect.Invokable;\nimport com.google.inject.Module;\n\n/**\n * Tests annotation parsing of {@code ChefApi}.\n */\n@Test(groups = { \"unit\" })\npublic class ChefApiTest extends BaseRestAnnotationProcessingTest<ChefApi> {\n\n   public void testCommitSandbox() throws SecurityException, NoSuchMethodException, IOException {\n\n      Invokable<?, ?> method = method(ChefApi.class, \"commitSandbox\", String.class, boolean.class);\n      GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(\"0189e76ccc476701d6b374e5a1a27347\", true)));\n      assertRequestLineEquals(httpRequest,\n            \"PUT http://localhost:4000/sandboxes/0189e76ccc476701d6b374e5a1a27347 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\nX-Chef-Version: \" + ChefApiMetadata.DEFAULT_API_VERSION\n            + \"-test\\n\");\n      assertPayloadEquals(httpRequest, \"{\\\"is_completed\\\":true}\", \"application/json\", false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseJson.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testCreateUploadSandboxForChecksums() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ChefApi.class, \"createUploadSandboxForChecksums\", Set.class);\n      GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method, ImmutableList\n            .<Object> of(ImmutableSet.of(asList(base16().lowerCase().decode(\"0189e76ccc476701d6b374e5a1a27347\")),\n                  asList(base16().lowerCase().decode(\"0c5ecd7788cf4f6c7de2a57193897a6c\")), asList(base16().lowerCase()\n                        .decode(\"1dda05ed139664f1f89b9dec482b77c0\"))))));\n      assertRequestLineEquals(httpRequest, \"POST http://localhost:4000/sandboxes HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\nX-Chef-Version: \" + ChefApiMetadata.DEFAULT_API_VERSION\n            + \"-test\\n\");\n      assertPayloadEquals(httpRequest,\n            \"{\\\"checksums\\\":{\\\"0189e76ccc476701d6b374e5a1a27347\\\":null,\\\"0c5ecd7788cf4f6c7de2a57193897a6c\\\":null,\"\n                  + \"\\\"1dda05ed139664f1f89b9dec482b77c0\\\":null}}\", \"application/json\", false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseJson.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testUploadContent() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ChefApi.class, \"uploadContent\", URI.class, Payload.class);\n      GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(URI.create(\"http://foo/bar\"), new StringPayload(\"{\\\"foo\\\": \\\"bar\\\"}\"))));\n      assertRequestLineEquals(httpRequest, \"PUT http://foo/bar HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\nX-Chef-Version: \" + ChefApiMetadata.DEFAULT_API_VERSION\n            + \"-test\\n\");\n      assertPayloadEquals(httpRequest, \"{\\\"foo\\\": \\\"bar\\\"}\", \"application/x-binary\", false);\n\n      assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testGetCookbook() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ChefApi.class, \"getCookbook\", String.class, String.class);\n      GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(\"cookbook\", \"1.0.0\")));\n      assertRequestLineEquals(httpRequest, \"GET http://localhost:4000/cookbooks/cookbook/1.0.0 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\nX-Chef-Version: \" + ChefApiMetadata.DEFAULT_API_VERSION\n            + \"-test\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseJson.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testDeleteCookbook() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ChefApi.class, \"deleteCookbook\", String.class, String.class);\n      GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(\"cookbook\", \"1.0.0\")));\n      assertRequestLineEquals(httpRequest, \"DELETE http://localhost:4000/cookbooks/cookbook/1.0.0 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\nX-Chef-Version: \" + ChefApiMetadata.DEFAULT_API_VERSION\n            + \"-test\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseJson.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testUpdateCookbook() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ChefApi.class, \"updateCookbook\", String.class, String.class,\n            CookbookVersion.class);\n      GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(\"cookbook\", \"1.0.1\", CookbookVersion.builder(\"cookbook\", \"1.0.1\").build())));\n\n      assertRequestLineEquals(httpRequest, \"PUT http://localhost:4000/cookbooks/cookbook/1.0.1 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\nX-Chef-Version: \" + ChefApiMetadata.DEFAULT_API_VERSION\n            + \"-test\\n\");\n      assertPayloadEquals(httpRequest,\n            \"{\\\"name\\\":\\\"cookbook-1.0.1\\\",\\\"definitions\\\":[],\\\"attributes\\\":[],\\\"files\\\":[],\"\n                  + \"\\\"metadata\\\":{\\\"suggestions\\\":{},\\\"dependencies\\\":{},\\\"conflicting\\\":{},\\\"providing\\\":{},\"\n                  + \"\\\"platforms\\\":{},\\\"recipes\\\":{},\\\"replacing\\\":{},\"\n                  + \"\\\"groupings\\\":{},\\\"attributes\\\":{},\\\"recommendations\\\":{}},\"\n                  + \"\\\"providers\\\":[],\\\"cookbook_name\\\":\\\"cookbook\\\",\\\"resources\\\":[],\\\"templates\\\":[],\"\n                  + \"\\\"libraries\\\":[],\\\"version\\\":\\\"1.0.1\\\",\"\n                  + \"\\\"recipes\\\":[],\\\"root_files\\\":[],\\\"json_class\\\":\\\"Chef::CookbookVersion\\\",\"\n                  + \"\\\"chef_type\\\":\\\"cookbook_version\\\"}\", \"application/json\", false);\n      assertResponseParserClassEquals(method, httpRequest, ParseJson.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testListVersionsOfCookbook() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ChefApi.class, \"listVersionsOfCookbook\", String.class);\n      GeneratedHttpRequest httpRequest = processor\n            .apply(Invocation.create(method, ImmutableList.<Object> of(\"apache2\")));\n\n      assertRequestLineEquals(httpRequest, \"GET http://localhost:4000/cookbooks/apache2 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\nX-Chef-Version: \" + ChefApiMetadata.DEFAULT_API_VERSION\n            + \"-test\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseCookbookVersionsFromJson.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testDeleteClient() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ChefApi.class, \"deleteClient\", String.class);\n      GeneratedHttpRequest httpRequest = processor\n            .apply(Invocation.create(method, ImmutableList.<Object> of(\"client\")));\n      assertRequestLineEquals(httpRequest, \"DELETE http://localhost:4000/clients/client HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\nX-Chef-Version: \" + ChefApiMetadata.DEFAULT_API_VERSION\n            + \"-test\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseJson.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testCreateApi() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ChefApi.class, \"createClient\", String.class);\n      GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method, ImmutableList.<Object> of(\"api\")));\n\n      assertRequestLineEquals(httpRequest, \"POST http://localhost:4000/clients HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\nX-Chef-Version: \" + ChefApiMetadata.DEFAULT_API_VERSION\n            + \"-test\\n\");\n      assertPayloadEquals(httpRequest, \"{\\\"name\\\":\\\"api\\\"}\", \"application/json\", false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseJson.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testCreateAdminApi() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ChefApi.class, \"createClient\", String.class, CreateClientOptions.class);\n      GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(\"api\", CreateClientOptions.Builder.admin())));\n\n      assertRequestLineEquals(httpRequest, \"POST http://localhost:4000/clients HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\nX-Chef-Version: \" + ChefApiMetadata.DEFAULT_API_VERSION\n            + \"-test\\n\");\n      assertPayloadEquals(httpRequest, \"{\\\"name\\\":\\\"api\\\",\\\"admin\\\":true}\", \"application/json\", false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseJson.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testGenerateKeyForClient() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ChefApi.class, \"generateKeyForClient\", String.class);\n      GeneratedHttpRequest httpRequest = processor\n            .apply(Invocation.create(method, ImmutableList.<Object> of(\"client\")));\n      assertRequestLineEquals(httpRequest, \"PUT http://localhost:4000/clients/client HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\nX-Chef-Version: \" + ChefApiMetadata.DEFAULT_API_VERSION\n            + \"-test\\n\");\n      assertPayloadEquals(httpRequest, \"{\\\"name\\\":\\\"client\\\", \\\"private_key\\\": true}\", \"application/json\", false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseJson.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testDeleteNode() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ChefApi.class, \"deleteNode\", String.class);\n      GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method, ImmutableList.<Object> of(\"node\")));\n      assertRequestLineEquals(httpRequest, \"DELETE http://localhost:4000/nodes/node HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\nX-Chef-Version: \" + ChefApiMetadata.DEFAULT_API_VERSION\n            + \"-test\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseJson.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testCreateNode() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ChefApi.class, \"createNode\", Node.class);\n      GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(\n            method,\n            ImmutableList.<Object> of(Node.builder().name(\"testnode\").runListElement(\"recipe[java]\")\n                  .environment(\"_default\").build())));\n\n      assertRequestLineEquals(httpRequest, \"POST http://localhost:4000/nodes HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\nX-Chef-Version: \" + ChefApiMetadata.DEFAULT_API_VERSION\n            + \"-test\\n\");\n      assertPayloadEquals(httpRequest,\n            \"{\\\"name\\\":\\\"testnode\\\",\\\"normal\\\":{},\\\"override\\\":{},\\\"default\\\":{},\\\"automatic\\\":{},\"\n                  + \"\\\"run_list\\\":[\\\"recipe[java]\\\"],\\\"chef_environment\\\":\\\"_default\\\",\\\"json_class\\\":\\\"Chef::Node\\\",\"\n                  + \"\\\"chef_type\\\":\\\"node\\\"}\", \"application/json\", false);\n\n      assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testUpdateNode() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ChefApi.class, \"updateNode\", Node.class);\n      GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(\n            method,\n            ImmutableList.<Object> of(Node.builder().name(\"testnode\").runListElement(\"recipe[java]\")\n                  .environment(\"_default\").build())));\n\n      assertRequestLineEquals(httpRequest, \"PUT http://localhost:4000/nodes/testnode HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\nX-Chef-Version: \" + ChefApiMetadata.DEFAULT_API_VERSION\n            + \"-test\\n\");\n      assertPayloadEquals(httpRequest,\n            \"{\\\"name\\\":\\\"testnode\\\",\\\"normal\\\":{},\\\"override\\\":{},\\\"default\\\":{},\\\"automatic\\\":{},\"\n                  + \"\\\"run_list\\\":[\\\"recipe[java]\\\"],\\\"chef_environment\\\":\\\"_default\\\",\\\"json_class\\\":\\\"Chef::Node\\\",\"\n                  + \"\\\"chef_type\\\":\\\"node\\\"}\", \"application/json\", false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseJson.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testDeleteRole() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ChefApi.class, \"deleteRole\", String.class);\n      GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method, ImmutableList.<Object> of(\"role\")));\n      assertRequestLineEquals(httpRequest, \"DELETE http://localhost:4000/roles/role HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\nX-Chef-Version: \" + ChefApiMetadata.DEFAULT_API_VERSION\n            + \"-test\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseJson.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testCreateRole() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ChefApi.class, \"createRole\", Role.class);\n      GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(Role.builder().name(\"testrole\").runListElement(\"recipe[java]\")\n            .envRunListElement(\"erl.one\", \"erl.one.alpha\")\n            .envRunListElement(\"erl.one\", \"erl.one.bravo\")\n            .envRunListElement(\"erl.two\", \"erl.two.alpha\")\n            .envRunListElement(\"erl.two\", \"erl.two.bravo\")\n            .build())));\n\n      assertRequestLineEquals(httpRequest, \"POST http://localhost:4000/roles HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\nX-Chef-Version: \" + ChefApiMetadata.DEFAULT_API_VERSION\n            + \"-test\\n\");\n      assertPayloadEquals(httpRequest, \"{\\\"name\\\":\\\"testrole\\\",\\\"override_attributes\\\":{},\\\"default_attributes\\\":{},\"\n            + \"\\\"run_list\\\":[\\\"recipe[java]\\\"],\\\"env_run_lists\\\":{\\\"erl.one\\\":[\\\"erl.one.alpha\\\",\\\"erl.one.bravo\\\"],\\\"erl.two\\\":[\\\"erl.two.alpha\\\",\\\"erl.two.bravo\\\"]},\\\"json_class\\\":\\\"Chef::Role\\\",\\\"chef_type\\\":\\\"role\\\"}\",\n            \"application/json\", false);\n\n      assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testUpdateRole() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ChefApi.class, \"updateRole\", Role.class);\n      GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(Role.builder().name(\"testrole\").runListElement(\"recipe[java]\")\n            .envRunListElement(\"erl.one\", \"erl.one.alpha\")\n            .envRunListElement(\"erl.one\", \"erl.one.bravo\")\n            .envRunListElement(\"erl.two\", \"erl.two.alpha\")\n            .envRunListElement(\"erl.two\", \"erl.two.bravo\")\n            .build())));\n\n      assertRequestLineEquals(httpRequest, \"PUT http://localhost:4000/roles/testrole HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\nX-Chef-Version: \" + ChefApiMetadata.DEFAULT_API_VERSION\n            + \"-test\\n\");\n      assertPayloadEquals(httpRequest, \"{\\\"name\\\":\\\"testrole\\\",\\\"override_attributes\\\":{},\\\"default_attributes\\\":{},\"\n            + \"\\\"run_list\\\":[\\\"recipe[java]\\\"],\\\"env_run_lists\\\":{\\\"erl.one\\\":[\\\"erl.one.alpha\\\",\\\"erl.one.bravo\\\"],\\\"erl.two\\\":[\\\"erl.two.alpha\\\",\\\"erl.two.bravo\\\"]},\\\"json_class\\\":\\\"Chef::Role\\\",\\\"chef_type\\\":\\\"role\\\"}\",\n            \"application/json\", false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseJson.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testDeleteDatabag() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ChefApi.class, \"deleteDatabag\", String.class);\n      GeneratedHttpRequest httpRequest = processor\n            .apply(Invocation.create(method, ImmutableList.<Object> of(\"databag\")));\n      assertRequestLineEquals(httpRequest, \"DELETE http://localhost:4000/data/databag HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\nX-Chef-Version: \" + ChefApiMetadata.DEFAULT_API_VERSION\n            + \"-test\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, VoidOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testCreateDatabag() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ChefApi.class, \"createDatabag\", String.class);\n      GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method, ImmutableList.<Object> of(\"name\")));\n\n      assertRequestLineEquals(httpRequest, \"POST http://localhost:4000/data HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\nX-Chef-Version: \" + ChefApiMetadata.DEFAULT_API_VERSION\n            + \"-test\\n\");\n      assertPayloadEquals(httpRequest, \"{\\\"name\\\":\\\"name\\\"}\", \"application/json\", false);\n\n      assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testDeleteDatabagItem() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ChefApi.class, \"deleteDatabagItem\", String.class, String.class);\n      GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(\"name\", \"databagItem\")));\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\nX-Chef-Version: \" + ChefApiMetadata.DEFAULT_API_VERSION\n            + \"-test\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testCreateDatabagItemThrowsIllegalArgumentOnPrimitive() throws SecurityException, NoSuchMethodException,\n         IOException {\n      Invokable<?, ?> method = method(ChefApi.class, \"createDatabagItem\", String.class, DatabagItem.class);\n      GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(\"name\", new DatabagItem(\"id\", \"100\"))));\n\n      assertRequestLineEquals(httpRequest, \"POST http://localhost:4000/data/name HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\nX-Chef-Version: \" + ChefApiMetadata.DEFAULT_API_VERSION\n            + \"-test\\n\");\n      assertPayloadEquals(\n            httpRequest,\n            \"{\\\"name\\\":\\\"testdatabagItem\\\",\\\"override_attributes\\\":{},\\\"default_attributes\\\":{},\"\n                  + \"\\\"run_list\\\":[\\\"recipe[java]\\\"],\\\"json_class\\\":\\\"Chef::DatabagItem\\\",\\\"chef_type\\\":\\\"databagItem\\\"}\",\n            \"application/json\", false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseJson.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(httpRequest);\n\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testCreateDatabagItemThrowsIllegalArgumentOnWrongId() throws SecurityException, NoSuchMethodException,\n         IOException {\n      Invokable<?, ?> method = method(ChefApi.class, \"createDatabagItem\", String.class, DatabagItem.class);\n      GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(\"name\", new DatabagItem(\"id\", \"{\\\"id\\\": \\\"item1\\\",\\\"my_key\\\": \\\"my_data\\\"}\"))));\n\n      assertRequestLineEquals(httpRequest, \"POST http://localhost:4000/data/name HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\nX-Chef-Version: \" + ChefApiMetadata.DEFAULT_API_VERSION\n            + \"-test\\n\");\n      assertPayloadEquals(\n            httpRequest,\n            \"{\\\"name\\\":\\\"testdatabagItem\\\",\\\"override_attributes\\\":{},\\\"default_attributes\\\":{},\"\n                  + \"\\\"run_list\\\":[\\\"recipe[java]\\\"],\\\"json_class\\\":\\\"Chef::DatabagItem\\\",\\\"chef_type\\\":\\\"databagItem\\\"}\",\n            \"application/json\", false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseJson.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testCreateDatabagItem() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ChefApi.class, \"createDatabagItem\", String.class, DatabagItem.class);\n      GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(\"name\", new DatabagItem(\"id\", \"{\\\"id\\\": \\\"id\\\",\\\"my_key\\\": \\\"my_data\\\"}\"))));\n\n      assertRequestLineEquals(httpRequest, \"POST http://localhost:4000/data/name HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\nX-Chef-Version: \" + ChefApiMetadata.DEFAULT_API_VERSION\n            + \"-test\\n\");\n      assertPayloadEquals(httpRequest, \"{\\\"id\\\": \\\"id\\\",\\\"my_key\\\": \\\"my_data\\\"}\", \"application/json\", false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseJson.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testCreateDatabagItemEvenWhenUserForgotId() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ChefApi.class, \"createDatabagItem\", String.class, DatabagItem.class);\n      GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(\"name\", new DatabagItem(\"id\", \"{\\\"my_key\\\": \\\"my_data\\\"}\"))));\n\n      assertRequestLineEquals(httpRequest, \"POST http://localhost:4000/data/name HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\nX-Chef-Version: \" + ChefApiMetadata.DEFAULT_API_VERSION\n            + \"-test\\n\");\n      assertPayloadEquals(httpRequest, \"{\\\"id\\\":\\\"id\\\",\\\"my_key\\\": \\\"my_data\\\"}\", \"application/json\", false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseJson.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testUpdateDatabagItem() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ChefApi.class, \"updateDatabagItem\", String.class, DatabagItem.class);\n      GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(\"name\", new DatabagItem(\"id\", \"{\\\"my_key\\\": \\\"my_data\\\"}\"))));\n\n      assertRequestLineEquals(httpRequest, \"PUT http://localhost:4000/data/name/id HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\nX-Chef-Version: \" + ChefApiMetadata.DEFAULT_API_VERSION\n            + \"-test\\n\");\n\n      assertPayloadEquals(httpRequest, \"{\\\"id\\\":\\\"id\\\",\\\"my_key\\\": \\\"my_data\\\"}\", \"application/json\", false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseJson.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testListDatabagItems() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ChefApi.class, \"listDatabagItems\", String.class);\n      GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method, ImmutableList.<Object> of(\"name\")));\n\n      assertRequestLineEquals(httpRequest, \"GET http://localhost:4000/data/name HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\nX-Chef-Version: \" + ChefApiMetadata.DEFAULT_API_VERSION\n            + \"-test\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseKeySetFromJson.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testListSearchIndexes() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ChefApi.class, \"listSearchIndexes\");\n      GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method, ImmutableList.of()));\n\n      assertRequestLineEquals(httpRequest, \"GET http://localhost:4000/search HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\nX-Chef-Version: \" + ChefApiMetadata.DEFAULT_API_VERSION\n            + \"-test\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseKeySetFromJson.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n\n   public void testSearchClients() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ChefApi.class, \"searchClients\");\n      GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method, ImmutableList.of()));\n\n      assertRequestLineEquals(httpRequest, \"GET http://localhost:4000/search/client HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\nX-Chef-Version: \" + ChefApiMetadata.DEFAULT_API_VERSION\n            + \"-test\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseSearchClientsFromJson.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testSearchClientsWithOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ChefApi.class, \"searchClients\", SearchOptions.class);\n      GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(SearchOptions.Builder.query(\"text\").rows(5))));\n\n      assertRequestLineEquals(httpRequest, \"GET http://localhost:4000/search/client?q=text&rows=5 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\nX-Chef-Version: \" + ChefApiMetadata.DEFAULT_API_VERSION\n            + \"-test\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseSearchClientsFromJson.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testSearchNodes() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ChefApi.class, \"searchNodes\");\n      GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method, ImmutableList.of()));\n\n      assertRequestLineEquals(httpRequest, \"GET http://localhost:4000/search/node HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\nX-Chef-Version: \" + ChefApiMetadata.DEFAULT_API_VERSION\n            + \"-test\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseSearchNodesFromJson.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testSearchNodesWithOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ChefApi.class, \"searchNodes\", SearchOptions.class);\n      GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(SearchOptions.Builder.query(\"foo:foo\").start(3))));\n\n      assertRequestLineEquals(httpRequest, \"GET http://localhost:4000/search/node?q=foo%3Afoo&start=3 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\nX-Chef-Version: \" + ChefApiMetadata.DEFAULT_API_VERSION\n            + \"-test\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseSearchNodesFromJson.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testSearchDatabagItems() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ChefApi.class, \"searchDatabagItems\", String.class);\n      GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method, ImmutableList.<Object> of(\"foo\")));\n\n      assertRequestLineEquals(httpRequest, \"GET http://localhost:4000/search/foo HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\nX-Chef-Version: \" + ChefApiMetadata.DEFAULT_API_VERSION\n            + \"-test\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseSearchDatabagFromJson.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testSearchDatabagItemsWithOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ChefApi.class, \"searchDatabagItems\", String.class, SearchOptions.class);\n      GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(\"foo\", SearchOptions.Builder.query(\"bar\").sort(\"name DESC\"))));\n\n      assertRequestLineEquals(httpRequest, \"GET http://localhost:4000/search/foo?q=bar&sort=name%20DESC HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\nX-Chef-Version: \" + ChefApiMetadata.DEFAULT_API_VERSION\n            + \"-test\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseSearchDatabagFromJson.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testGetResourceContents() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ChefApi.class, \"getResourceContents\", Resource.class);\n      GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(Resource.builder().name(\"test\").url(URI.create(\"http://foo/bar\")).build())));\n\n      assertRequestLineEquals(httpRequest, \"GET http://foo/bar HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\nX-Chef-Version: \" + ChefApiMetadata.DEFAULT_API_VERSION\n            + \"-test\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ReturnInputStream.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   @Override\n   protected void checkFilters(HttpRequest request) {\n      assertEquals(request.getFilters().size(), 1);\n      assertEquals(request.getFilters().get(0).getClass(), SignedHeaderAuth.class);\n   }\n\n   @Override\n   protected Module createModule() {\n      return new TestChefHttpApiModule();\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      props.put(Constants.PROPERTY_API_VERSION, ChefApiMetadata.DEFAULT_API_VERSION + \"-test\");\n      return props;\n   }\n\n   @ConfiguresHttpApi\n   static class TestChefHttpApiModule extends ChefHttpApiModule {\n      @Override\n      protected String provideTimeStamp(@TimeStamp Supplier<String> cache) {\n         return \"timestamp\";\n      }\n   }\n\n   @Override\n   public ApiMetadata createApiMetadata() {\n      identity = \"user\";\n      credential = SignedHeaderAuthTest.PRIVATE_KEY;\n      return new ChefApiMetadata();\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/binders/BindGroupToUpdateRequestJsonPayloadTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.net.URI;\n\nimport org.jclouds.chef.ChefApiMetadata;\nimport org.jclouds.chef.config.ChefParserModule;\nimport org.jclouds.chef.domain.Group;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.rest.annotations.ApiVersion;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n/**\n * Unit tests for the {@link BindGroupToUpdateRequestJsonPayload} class.\n */\n@Test(groups = \"unit\", testName = \"BindGroupToUpdateRequestJsonPayloadTest\")\npublic class BindGroupToUpdateRequestJsonPayloadTest {\n\n   private Injector injector = Guice.createInjector(new AbstractModule() {\n      @Override\n      protected void configure() {\n         bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefApiMetadata.DEFAULT_API_VERSION);\n      }\n   }, new ChefParserModule(), new GsonModule());\n\n   private BindGroupToUpdateRequestJsonPayload binder = injector.getInstance(BindGroupToUpdateRequestJsonPayload.class);\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testInvalidNullInput() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(URI.create(\"http://localhost\")).build();\n      binder.bindToRequest(request, null);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testInvalidTypeInput() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(URI.create(\"http://localhost\")).build();\n      binder.bindToRequest(request, new Object());\n   }\n\n   public void testBindOnlyName() throws IOException {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(URI.create(\"http://localhost\")).build();\n      HttpRequest newRequest = binder.bindToRequest(request, Group.builder(\"foo\").build());\n\n      String payload = Strings2.toStringAndClose(newRequest.getPayload().getInput());\n      assertEquals(payload, \"{\\\"groupname\\\":\\\"foo\\\",\\\"actors\\\":{\\\"clients\\\":[],\\\"groups\\\":[],\\\"users\\\":[]}}\");\n   }\n\n   public void testBindNameAndLists() throws IOException {\n      Group group = Group.builder(\"foo\").client(\"nacx-validator\").group(\"admins\").user(\"nacx\").build();\n\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(URI.create(\"http://localhost\")).build();\n      HttpRequest newRequest = binder.bindToRequest(request, group);\n\n      String payload = Strings2.toStringAndClose(newRequest.getPayload().getInput());\n      assertEquals(payload,\n            \"{\\\"groupname\\\":\\\"foo\\\",\\\"actors\\\":{\\\"clients\\\":[\\\"nacx-validator\\\"],\\\"groups\\\":[\\\"admins\\\"],\\\"users\\\":[\\\"nacx\\\"]}}\");\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/binders/BindHexEncodedMD5sToJsonPayloadTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.binders;\n\nimport static com.google.common.io.BaseEncoding.base16;\nimport static com.google.common.primitives.Bytes.asList;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.File;\n\nimport jakarta.ws.rs.HttpMethod;\n\nimport org.jclouds.chef.ChefApiMetadata;\nimport org.jclouds.chef.config.ChefParserModule;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.rest.annotations.ApiVersion;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = { \"unit\" })\npublic class BindHexEncodedMD5sToJsonPayloadTest {\n\n   Injector injector = Guice.createInjector(new AbstractModule() {\n      @Override\n      protected void configure() {\n         bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefApiMetadata.DEFAULT_API_VERSION);\n      }\n   }, new ChefParserModule(), new GsonModule());\n\n   BindChecksumsToJsonPayload binder = injector.getInstance(BindChecksumsToJsonPayload.class);\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testMustBeIterable() {\n      HttpRequest request = HttpRequest.builder().method(HttpMethod.POST).endpoint(\"http://localhost\").build();\n      binder.bindToRequest(request, new File(\"foo\"));\n   }\n\n   public void testCorrect() {\n      HttpRequest request = HttpRequest.builder().method(HttpMethod.POST).endpoint(\"http://localhost\").build();\n      binder.bindToRequest(request,\n            ImmutableSet.of(asList(base16().lowerCase().decode(\"abddef\")), asList(base16().lowerCase().decode(\"1234\"))));\n      assertEquals(request.getPayload().getRawContent(), \"{\\\"checksums\\\":{\\\"abddef\\\":null,\\\"1234\\\":null}}\");\n   }\n\n   @Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class })\n   public void testNullIsBad() {\n      HttpRequest request = HttpRequest.builder().method(HttpMethod.POST).endpoint(\"http://localhost\").build();\n      binder.bindToRequest(request, null);\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/binders/GroupNameTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\n\nimport org.jclouds.chef.domain.Group;\nimport org.testng.annotations.Test;\n\n/**\n * Unit tests for the {@link GroupName} class.\n */\n@Test(groups = \"unit\", testName = \"GroupNameTest\")\npublic class GroupNameTest {\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testInvalidNullInput() {\n      new GroupName().apply(null);\n   }\n\n   public void testApplyGroupName() throws IOException {\n      assertEquals(new GroupName().apply(Group.builder(\"foo\").build()), \"foo\");\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/config/ChefParserModuleTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.config;\n\nimport static com.google.common.base.Objects.equal;\nimport static org.testng.Assert.assertEquals;\n\nimport java.lang.reflect.Type;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.chef.config.ChefParserModule.KeepLastRepeatedKeyMapTypeAdapterFactory;\nimport org.jclouds.json.internal.NullFilteringTypeAdapterFactories.ListTypeAdapterFactory;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.reflect.TypeToken;\nimport com.google.gson.Gson;\nimport com.google.gson.GsonBuilder;\n\n/**\n * Unit tests for the {@link ChefParserModule} class.\n */\n@Test(groups = \"unit\", testName = \"ChefParserModuleTest\")\npublic class ChefParserModuleTest {\n\n   private static class KeyValue {\n      private final String key;\n      private final String value;\n\n      private KeyValue(String key, String value) {\n         this.key = key;\n         this.value = value;\n      }\n\n      @Override\n      public int hashCode() {\n         return Objects.hashCode(key, value);\n      }\n\n      @Override\n      public boolean equals(Object obj) {\n         if (this == obj)\n            return true;\n         if (obj == null || getClass() != obj.getClass())\n            return false;\n         KeyValue that = KeyValue.class.cast(obj);\n         return equal(this.key, that.key) && equal(this.value, that.value);\n      }\n   }\n\n   private Gson map = new GsonBuilder().registerTypeAdapterFactory(new KeepLastRepeatedKeyMapTypeAdapterFactory())\n         .create();\n   private Type mapType = new TypeToken<Map<String, String>>() {\n      private static final long serialVersionUID = 1L;\n   }.getType();\n   private Type mapkeyValueType = new TypeToken<Map<String, KeyValue>>() {\n      private static final long serialVersionUID = 1L;\n   }.getType();\n\n   public void testKeepLastRepeatedKeyMapTypeAdapter() {\n      Map<String, String> noNulls = map.fromJson(\"{\\\"value\\\":\\\"a test string!\\\"}\", mapType);\n      assertEquals(noNulls, ImmutableMap.of(\"value\", \"a test string!\"));\n      Map<String, String> withNull = map.fromJson(\"{\\\"value\\\":null}\", mapType);\n      assertEquals(withNull, ImmutableMap.of());\n      Map<String, String> withEmpty = map.fromJson(\"{\\\"value\\\":\\\"\\\"}\", mapType);\n      assertEquals(withEmpty, ImmutableMap.of(\"value\", \"\"));\n      Map<String, KeyValue> keyValues = map.fromJson(\n            \"{\\\"i-foo\\\":{\\\"key\\\":\\\"i-foo\\\",\\\"value\\\":\\\"foo\\\"},\\\"i-bar\\\":{\\\"key\\\":\\\"i-bar\\\",\\\"value\\\":\\\"bar\\\"}}\",\n            mapkeyValueType);\n      assertEquals(keyValues,\n            ImmutableMap.of(\"i-foo\", new KeyValue(\"i-foo\", \"foo\"), \"i-bar\", new KeyValue(\"i-bar\", \"bar\")));\n      Map<String, KeyValue> duplicates = map\n            .fromJson(\n                  \"{\\\"i-foo\\\":{\\\"key\\\":\\\"i-foo\\\",\\\"value\\\":\\\"foo\\\", \\\"value\\\":\\\"foo2\\\"},\\\"i-bar\\\":{\\\"key\\\":\\\"i-bar\\\",\\\"value\\\":\\\"bar\\\",\\\"value\\\":\\\"bar2\\\"}}\",\n                  mapkeyValueType);\n      assertEquals(duplicates,\n            ImmutableMap.of(\"i-foo\", new KeyValue(\"i-foo\", \"foo2\"), \"i-bar\", new KeyValue(\"i-bar\", \"bar2\")));\n   }\n\n   private Gson listInMap = new GsonBuilder().registerTypeAdapterFactory(new KeepLastRepeatedKeyMapTypeAdapterFactory())\n         .registerTypeAdapterFactory(new ListTypeAdapterFactory()).create();\n   private Type listInMapType = new TypeToken<Map<String, List<Map<String, String>>>>() {\n      private static final long serialVersionUID = 1L;\n   }.getType();\n\n   public void testListInMap() {\n      Map<String, List<Map<String, String>>> notNull = listInMap\n            .fromJson(\"{\\\"value\\\":[{\\\"x\\\":\\\"y\\\",\\\"a\\\":\\\"b\\\"},{\\\"u\\\":\\\"v\\\"}]}\", listInMapType);\n      assertEquals(notNull,\n            ImmutableMap.of(\"value\", ImmutableList.of(ImmutableMap.of(\"x\", \"y\", \"a\", \"b\"), ImmutableMap.of(\"u\", \"v\"))));\n      Map<String, List<Map<String, String>>> innerMapValueNull = listInMap\n            .fromJson(\"{\\\"value\\\":[{\\\"x\\\":\\\"y\\\",\\\"a\\\":null},{\\\"u\\\":\\\"v\\\"}]}\", listInMapType);\n      assertEquals(innerMapValueNull,\n            ImmutableMap.of(\"value\", ImmutableList.of(ImmutableMap.of(\"x\", \"y\"), ImmutableMap.of(\"u\", \"v\"))));\n      Map<String, List<Map<String, String>>> withNullInList = listInMap.fromJson(\"{\\\"value\\\":[null]}\", listInMapType);\n      assertEquals(withNullInList, ImmutableMap.of(\"value\", ImmutableList.of()));\n      Map<String, List<Map<String, String>>> withNullAsList = listInMap.fromJson(\"{\\\"parent\\\":null}\", listInMapType);\n      assertEquals(withNullAsList, ImmutableMap.of());\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/domain/RoleTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.domain;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNotEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.testng.annotations.Test;\n\n/**\n * Tests behaviors of {@code Role}.\n */\n@Test(groups = { \"unit\" })\npublic class RoleTest {\n   @Test(expectedExceptions = NullPointerException.class)\n   public void canNotAddEnvRunListMapThatIsNull() {\n      Role.builder().envRunList((Map<String, List<String>>) null);\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void canNotAddRunListForEnvironmentThatIsNull() {\n      Role.builder().envRunList(\"does.not.matter\", (List<String>) null);\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void canNotUseNullEnvNameWhenAddingEnvRunListEntry() {\n      Role.builder().envRunListElement((String) null, \"does.not.matter\");\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void canNotUseNullEntryWhenAddingEnvRunListEntry() {\n      Role.builder().envRunListElement(\"does.not.matter\", (String) null);\n   }\n\n   public void multipleEnvRunListsCanBePopulated() {\n      String env1 = \"env1\";\n      String env2 = \"env2\";\n      String env1Alpha = \"env1.alpha\";\n      String env2Alpha = \"env2.alpha\";\n      String env2Bravo = \"env2.bravo\";\n      Role role = Role.builder().envRunListElement(env1, env1Alpha).envRunListElement(env2, env2Alpha)\n            .envRunListElement(env2, env2Bravo).build();\n      Map<String, List<String>> envRunList = role.getEnvRunList();\n      assertNotNull(envRunList, \"envRunList\");\n      assertEquals(envRunList.size(), 2, \"envRunList.size\");\n\n      verifyRunListForEnvironment(envRunList, env1, env1Alpha);\n      verifyRunListForEnvironment(envRunList, env2, env2Alpha, env2Bravo);\n   }\n\n   @Test(expectedExceptions = UnsupportedOperationException.class)\n   public void envRunListOnNewlyBuiltRoleIsImmutable() {\n      String env = \"env\";\n      Role role = Role.builder().envRunListElement(env, env + \"1\").build();\n      role.getEnvRunList().put(\"does.not.matter\", new ArrayList<String>());\n   }\n\n   @Test(expectedExceptions = UnsupportedOperationException.class)\n   public void envRunListEntriesOnNewlyBuiltRoleIsImmutable() {\n      String env = \"env\";\n      Role role = Role.builder().envRunListElement(env, env + \"1\").build();\n      role.getEnvRunList().get(env).add(\"does.not.matter\");\n   }\n\n   public void rolesWithSameEnvRunListAreEqual() {\n      String env = \"env\";\n      String entry = \"entry\";\n\n      Role role1 = Role.builder().envRunListElement(env, entry).build();\n      Role role2 = Role.builder().envRunListElement(env, entry).build();\n\n      assertEquals(role1.hashCode(), role2.hashCode(), \"hashCodes should be equal\");\n      assertEquals(role1, role2, \"role1 should equal role2\");\n      assertEquals(role2, role1, \"role2 should equal role1\");\n   }\n\n   public void rolesWithDifferentEnvRunListAreNotEqual() {\n      String env = \"env\";\n      String entry = \"entry\";\n\n      Role role1 = Role.builder().envRunListElement(env, entry.toUpperCase()).build();\n      Role role2 = Role.builder().envRunListElement(env, entry.toLowerCase()).build();\n\n      assertNotEquals(role1.hashCode(), role2.hashCode(), \"hashCodes should not be equal\");\n      assertNotEquals(role1, role2, \"role1 should not equal role2\");\n      assertNotEquals(role2, role1, \"role2 should not equal role1\");\n   }\n\n   @Test(enabled = false)\n   public static void verifyRunListForEnvironment(Map<String, List<String>> envRunList, String envName,\n         String... expectedEntries) {\n      assertTrue(envRunList.containsKey(envName), \"envRunList contains \" + envName);\n      assertEquals(envRunList.get(envName).size(), expectedEntries.length, \"envRunList size for '\" + envName);\n      assertTrue(envRunList.get(envName).containsAll(Arrays.asList(expectedEntries)), \"envRunList for e1 contains \"\n            + Arrays.asList(expectedEntries));\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/features/OrganizationApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.chef.BaseChefApiExpectTest;\nimport org.jclouds.chef.ChefApi;\nimport org.jclouds.chef.ChefApiMetadata;\nimport org.jclouds.chef.config.ChefHttpApiModule;\nimport org.jclouds.chef.domain.Group;\nimport org.jclouds.chef.domain.User;\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.inject.Module;\n\n/**\n * Expect tests for the {@link OrganizationApi} class.\n */\n@Test(groups = \"unit\", testName = \"OrganizationApiExpectTest\")\npublic class OrganizationApiExpectTest extends BaseChefApiExpectTest<ChefApi> {\n\n   public void testGetUserReturns2xx() {\n      ChefApi api = requestSendsResponse(\n            signed(HttpRequest.builder() //\n                  .method(\"GET\") //\n                  .endpoint(\"http://localhost:4000/users/nacx\") //\n                  .addHeader(\"X-Chef-Version\", ChefApiMetadata.DEFAULT_API_VERSION) //\n                  .addHeader(\"Accept\", MediaType.APPLICATION_JSON).build()), //\n            HttpResponse.builder().statusCode(200)\n                  .payload(payloadFromResourceWithContentType(\"/user.json\", MediaType.APPLICATION_JSON)) //\n                  .build());\n\n      User user = api.organizationApi().get().getUser(\"nacx\");\n      assertEquals(user.getUsername(), \"nacx\");\n      assertEquals(user.getDisplayName(), \"Ignasi Barrera\");\n   }\n\n   public void testGetUserReturns404() {\n      ChefApi api = requestSendsResponse(signed(HttpRequest.builder() //\n            .method(\"GET\") //\n            .endpoint(\"http://localhost:4000/users/foo\") //\n            .addHeader(\"X-Chef-Version\", ChefApiMetadata.DEFAULT_API_VERSION) //\n            .addHeader(\"Accept\", MediaType.APPLICATION_JSON) //\n            .build()), //\n            HttpResponse.builder().statusCode(404).build());\n\n      assertNull(api.organizationApi().get().getUser(\"foo\"));\n   }\n\n   public void testListGroups() {\n      ChefApi api = requestSendsResponse(\n            signed(HttpRequest.builder() //\n                  .method(\"GET\") //\n                  .endpoint(\"http://localhost:4000/groups\") //\n                  .addHeader(\"X-Chef-Version\", ChefApiMetadata.DEFAULT_API_VERSION) //\n                  .addHeader(\"Accept\", MediaType.APPLICATION_JSON).build()), //\n            HttpResponse.builder().statusCode(200)\n                  .payload(payloadFromResourceWithContentType(\"/groups.json\", MediaType.APPLICATION_JSON)) //\n                  .build());\n\n      Set<String> groups = api.organizationApi().get().listGroups();\n      assertEquals(groups.size(), 5);\n      assertTrue(groups.contains(\"admins\"));\n   }\n\n   public void testGetGroupReturns2xx() {\n      ChefApi api = requestSendsResponse(\n            signed(HttpRequest.builder() //\n                  .method(\"GET\") //\n                  .endpoint(\"http://localhost:4000/groups/admins\") //\n                  .addHeader(\"X-Chef-Version\", ChefApiMetadata.DEFAULT_API_VERSION) //\n                  .addHeader(\"Accept\", MediaType.APPLICATION_JSON).build()), //\n            HttpResponse.builder().statusCode(200)\n                  .payload(payloadFromResourceWithContentType(\"/group.json\", MediaType.APPLICATION_JSON)) //\n                  .build());\n\n      Group group = api.organizationApi().get().getGroup(\"admins\");\n      assertEquals(group.getName(), \"admins\");\n      assertEquals(group.getGroupname(), \"admins\");\n   }\n\n   public void testGetGroupReturns404() {\n      ChefApi api = requestSendsResponse(signed(HttpRequest.builder() //\n            .method(\"GET\") //\n            .endpoint(\"http://localhost:4000/groups/foo\") //\n            .addHeader(\"X-Chef-Version\", ChefApiMetadata.DEFAULT_API_VERSION) //\n            .addHeader(\"Accept\", MediaType.APPLICATION_JSON) //\n            .build()), //\n            HttpResponse.builder().statusCode(404).build());\n\n      assertNull(api.organizationApi().get().getGroup(\"foo\"));\n   }\n\n   public void testCreateGroupReturns2xx() {\n      ChefApi api = requestSendsResponse(signed(HttpRequest.builder() //\n            .method(\"POST\") //\n            .endpoint(\"http://localhost:4000/groups\") //\n            .addHeader(\"X-Chef-Version\", ChefApiMetadata.DEFAULT_API_VERSION) //\n            .addHeader(\"Accept\", MediaType.APPLICATION_JSON) //\n            .payload(payloadFromStringWithContentType(\"{\\\"groupname\\\":\\\"foo\\\"}\", MediaType.APPLICATION_JSON)) //\n            .build()), //\n            HttpResponse.builder().statusCode(201).build());\n\n      api.organizationApi().get().createGroup(\"foo\");\n   }\n\n   public void testDeleteGroupReturns2xx() {\n      ChefApi api = requestSendsResponse(signed(HttpRequest.builder() //\n            .method(\"DELETE\") //\n            .endpoint(\"http://localhost:4000/groups/foo\") //\n            .addHeader(\"X-Chef-Version\", ChefApiMetadata.DEFAULT_API_VERSION) //\n            .addHeader(\"Accept\", MediaType.APPLICATION_JSON) //\n            .build()), //\n            HttpResponse.builder().statusCode(200).build());\n\n      api.organizationApi().get().deleteGroup(\"foo\");\n   }\n\n   @Test(expectedExceptions = HttpResponseException.class)\n   public void testDeleteGroupFailsOn404() {\n      ChefApi api = requestSendsResponse(signed(HttpRequest.builder() //\n            .method(\"DELETE\") //\n            .endpoint(\"http://localhost:4000/groups/foo\") //\n            .addHeader(\"X-Chef-Version\", ChefApiMetadata.DEFAULT_API_VERSION) //\n            .addHeader(\"Accept\", MediaType.APPLICATION_JSON) //\n            .build()), //\n            HttpResponse.builder().statusCode(404).build());\n\n      api.organizationApi().get().deleteGroup(\"foo\");\n   }\n\n   public void testUpdateGroupReturns2xx() {\n      ChefApi api = requestSendsResponse(signed(HttpRequest.builder() //\n            .method(\"PUT\") //\n            .endpoint(\"http://localhost:4000/groups/admins\") //\n            .addHeader(\"X-Chef-Version\", ChefApiMetadata.DEFAULT_API_VERSION) //\n            .addHeader(\"Accept\", MediaType.APPLICATION_JSON) //\n            .payload(payloadFromResourceWithContentType(\"/group-update.json\", MediaType.APPLICATION_JSON)) //\n            .build()), //\n            HttpResponse.builder().statusCode(200).build());\n\n      Group group = Group.builder(\"admins\").client(\"abiquo\").group(\"admins\").user(\"nacx\").build();\n      api.organizationApi().get().updateGroup(group);\n   }\n\n   @Test(expectedExceptions = ResourceNotFoundException.class)\n   public void testUpdateGroupFailsOn404() {\n      ChefApi api = requestSendsResponse(signed(HttpRequest.builder() //\n            .method(\"PUT\") //\n            .endpoint(\"http://localhost:4000/groups/admins\") //\n            .addHeader(\"X-Chef-Version\", ChefApiMetadata.DEFAULT_API_VERSION) //\n            .addHeader(\"Accept\", MediaType.APPLICATION_JSON) //\n            .payload(payloadFromResourceWithContentType(\"/group-update.json\", MediaType.APPLICATION_JSON)) //\n            .build()), //\n            HttpResponse.builder().statusCode(404).build());\n\n      Group group = Group.builder(\"admins\").client(\"abiquo\").group(\"admins\").user(\"nacx\").build();\n      api.organizationApi().get().updateGroup(group);\n   }\n\n   @Override\n   protected Module createModule() {\n      return new TestChefHttpApiModule();\n   }\n\n   @ConfiguresHttpApi\n   static class TestChefHttpApiModule extends ChefHttpApiModule {\n      @Override\n      protected String provideTimeStamp(@TimeStamp Supplier<String> cache) {\n         return \"timestamp\";\n      }\n   }\n\n   @Override\n   protected ApiMetadata createApiMetadata() {\n      return new ChefApiMetadata();\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/features/OrganizationApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\nimport java.util.UUID;\n\nimport org.jclouds.chef.domain.Group;\nimport org.jclouds.chef.domain.User;\nimport org.jclouds.chef.internal.BaseChefLiveTest;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.testng.SkipException;\nimport org.testng.annotations.BeforeMethod;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of the OrganizationApi.\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"OrganizationApiLiveTest\")\npublic class OrganizationApiLiveTest extends BaseChefLiveTest {\n   private static final String GROUP_NAME = System.getProperty(\"user.name\") + \"-jcloudstest\";\n\n   private OrganizationApi orgApi;\n\n   @BeforeMethod\n   public void skipIfApiNotAvailable() {\n      // Throwing SkipExceptions only works with @Test and @BeforeMethod methods\n      if (!api.organizationApi().isPresent()) {\n         throw new SkipException(\"Organization api not available in this Chef version\");\n      }\n      orgApi = api.organizationApi().get();\n   }\n\n   public void testGetUser() {\n      User user = orgApi.getUser(identity);\n      assertEquals(user.getUsername(), identity);\n      assertNotNull(user.getPublicKey());\n   }\n\n   public void testGetUnexistingUser() {\n      User user = orgApi.getUser(UUID.randomUUID().toString());\n      assertNull(user);\n   }\n\n   public void testListGroups() {\n      Set<String> groups = orgApi.listGroups();\n      assertNotNull(groups);\n      assertFalse(groups.isEmpty());\n   }\n\n   public void testGetUnexistingGroup() {\n      Group group = orgApi.getGroup(UUID.randomUUID().toString());\n      assertNull(group);\n   }\n\n   public void testCreateGroup() {\n      orgApi.createGroup(GROUP_NAME);\n      Group group = orgApi.getGroup(GROUP_NAME);\n      assertNotNull(group);\n      assertEquals(group.getGroupname(), GROUP_NAME);\n   }\n\n   @Test(dependsOnMethods = \"testCreateGroup\")\n   public void testUpdateGroup() {\n      Group group = orgApi.getGroup(GROUP_NAME);\n      Group updated = Group.builder(group.getGroupname()) //\n            .actors(group.getActors()) //\n            .orgname(group.getOrgname()) //\n            .name(group.getName()) //\n            .groups(group.getGroups()) //\n            .client(group.getOrgname() + \"-validator\") //\n            .user(identity) //\n            .build();\n\n      orgApi.updateGroup(updated);\n      group = orgApi.getGroup(GROUP_NAME);\n\n      assertNotNull(group);\n      assertTrue(group.getUsers().contains(identity));\n      assertTrue(group.getClients().contains(group.getOrgname() + \"-validator\"));\n   }\n\n   @Test(expectedExceptions = ResourceNotFoundException.class)\n   public void testUpdateUnexistingGroup() {\n      orgApi.updateGroup(Group.builder(UUID.randomUUID().toString()).build());\n   }\n\n   @Test(dependsOnMethods = \"testUpdateGroup\", alwaysRun = true)\n   public void testDeleteGroup() {\n      orgApi.deleteGroup(GROUP_NAME);\n      Group group = orgApi.getGroup(GROUP_NAME);\n      assertNull(group);\n   }\n\n   @Test(expectedExceptions = ResourceNotFoundException.class)\n   public void testDeleteUnexistingGroup() {\n      orgApi.deleteGroup(UUID.randomUUID().toString());\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/filters/SignedHeaderAuthTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.filters;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertEqualsNoOrder;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.security.PrivateKey;\n\nimport jakarta.inject.Provider;\nimport jakarta.ws.rs.HttpMethod;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.chef.ChefApiMetadata;\nimport org.jclouds.crypto.Crypto;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpUtils;\nimport org.jclouds.http.internal.SignatureWire;\nimport org.jclouds.logging.config.NullLoggingModule;\nimport org.jclouds.rest.internal.BaseRestApiTest.MockModule;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Joiner;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.base.Throwables;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.LinkedHashMultimap;\nimport com.google.common.collect.Multimap;\nimport com.google.common.net.HttpHeaders;\nimport com.google.inject.Injector;\nimport com.google.inject.Key;\nimport com.google.inject.Module;\nimport com.google.inject.TypeLiteral;\n\n@Test(groups = { \"unit\" })\npublic class SignedHeaderAuthTest {\n\n   public static final String USER_ID = \"spec-user\";\n   public static final String BODY = \"Spec Body\";\n   // Base64.encode64(Digest::SHA1.digest(\"Spec Body\")).chomp\n   public static final String HASHED_BODY = \"DFteJZPVv6WKdQmMqZUQUumUyRs=\";\n   public static final String TIMESTAMP_ISO8601 = \"2009-01-01T12:00:00Z\";\n\n   public static final String PATH = \"/organizations/clownco\";\n   // Base64.encode64(Digest::SHA1.digest(\"/organizations/clownco\")).chomp\n\n   public static final String HASHED_CANONICAL_PATH = \"YtBWDn1blGGuFIuKksdwXzHU9oE=\";\n   public static final String REQUESTING_ACTOR_ID = \"c0f8a68c52bffa1020222a56b23cccfa\";\n\n   // Content hash is ???TODO\n   public static final String X_OPS_CONTENT_HASH = \"DFteJZPVv6WKdQmMqZUQUumUyRs=\";\n\n   public static final String[] X_OPS_AUTHORIZATION_LINES = new String[] {\n         \"jVHrNniWzpbez/eGWjFnO6lINRIuKOg40ZTIQudcFe47Z9e/HvrszfVXlKG4\",\n         \"NMzYZgyooSvU85qkIUmKuCqgG2AIlvYa2Q/2ctrMhoaHhLOCWWoqYNMaEqPc\",\n         \"3tKHE+CfvP+WuPdWk4jv4wpIkAz6ZLxToxcGhXmZbXpk56YTmqgBW2cbbw4O\",\n         \"IWPZDHSiPcw//AYNgW1CCDptt+UFuaFYbtqZegcBd2n/jzcWODA7zL4KWEUy\",\n         \"9q4rlh/+1tBReg60QdsmDRsw/cdO1GZrKtuCwbuD4+nbRdVBKv72rqHX9cu0\", \"utju9jzczCyB+sSAQWrxSsXB/b8vV2qs0l4VD2ML+w==\" };\n\n   // We expect Mixlib::Authentication::SignedHeaderAuth//sign to return this\n   // if passed the BODY above.\n   public static final Multimap<String, String> EXPECTED_SIGN_RESULT = ImmutableMultimap.<String, String> builder()\n         .put(\"X-Ops-Content-Hash\", X_OPS_CONTENT_HASH).put(\"X-Ops-Userid\", USER_ID).put(\"X-Ops-Sign\", \"version=1.0\")\n         .put(\"X-Ops-Authorization-1\", X_OPS_AUTHORIZATION_LINES[0])\n         .put(\"X-Ops-Authorization-2\", X_OPS_AUTHORIZATION_LINES[1])\n         .put(\"X-Ops-Authorization-3\", X_OPS_AUTHORIZATION_LINES[2])\n         .put(\"X-Ops-Authorization-4\", X_OPS_AUTHORIZATION_LINES[3])\n         .put(\"X-Ops-Authorization-5\", X_OPS_AUTHORIZATION_LINES[4])\n         .put(\"X-Ops-Authorization-6\", X_OPS_AUTHORIZATION_LINES[5]).put(\"X-Ops-Timestamp\", TIMESTAMP_ISO8601).build();\n\n   // Content hash for empty string\n   public static final String X_OPS_CONTENT_HASH_EMPTY = \"2jmj7l5rSw0yVb/vlWAYkK/YBwk=\";\n   public static final Multimap<String, String> EXPECTED_SIGN_RESULT_EMPTY = ImmutableMultimap\n         .<String, String> builder().put(\"X-Ops-Content-Hash\", X_OPS_CONTENT_HASH_EMPTY).put(\"X-Ops-Userid\", USER_ID)\n         .put(\"X-Ops-Sign\", \"version=1.0\")\n         .put(\"X-Ops-Authorization-1\", \"N6U75kopDK64cEFqrB6vw+PnubnXr0w5LQeXnIGNGLRP2LvifwIeisk7QxEx\")\n         .put(\"X-Ops-Authorization-2\", \"mtpQOWAw8HvnWErjzuk9AvUsqVmWpv14ficvkaD79qsPMvbje+aLcIrCGT1P\")\n         .put(\"X-Ops-Authorization-3\", \"3d2uvf4w7iqwzrIscPnkxLR6o6pymR90gvJXDPzV7Le0jbfD8kmZ8AAK0sGG\")\n         .put(\"X-Ops-Authorization-4\", \"09F1ftW80bLatJTA66Cw2wBz261r6x/abZhIKFJFDWLzyQGJ8ZNOkUrDDtgI\")\n         .put(\"X-Ops-Authorization-5\", \"svLVXpOJKZZfKunsElpWjjsyNt3k8vpI1Y4ANO8Eg2bmeCPeEK+YriGm5fbC\")\n         .put(\"X-Ops-Authorization-6\", \"DzWNPylHJqMeGKVYwGQKpg62QDfe5yXh3wZLiQcXow==\")\n         .put(\"X-Ops-Timestamp\", TIMESTAMP_ISO8601).build();\n\n   public static final String PUBLIC_KEY;\n   public static final String PRIVATE_KEY;\n\n   static {\n      try {\n         PUBLIC_KEY = Strings2.toStringAndClose(SignedHeaderAuthTest.class.getResourceAsStream(\"/pubkey.txt\"));\n\n         PRIVATE_KEY = Strings2.toStringAndClose(SignedHeaderAuthTest.class.getResourceAsStream(\"/privkey.txt\"));\n      } catch (IOException e) {\n         throw Throwables.propagate(e);\n      }\n   }\n\n   @Test\n   void canonicalizedPathRemovesMultipleSlashes() {\n      assertEquals(signing_obj.canonicalPath(\"///\"), \"/\");\n   }\n\n   @Test\n   void canonicalizedPathRemovesTrailingSlash() {\n      assertEquals(signing_obj.canonicalPath(\"/path/\"), \"/path\");\n   }\n\n   @Test\n   void shouldGenerateTheCorrectStringToSignAndSignature() {\n\n      HttpRequest request = HttpRequest.builder().method(HttpMethod.POST).endpoint(\"http://localhost/\" + PATH)\n            .payload(BODY).build();\n\n      String expected_string_to_sign = new StringBuilder().append(\"Method:POST\").append(\"\\n\").append(\"Hashed Path:\")\n            .append(HASHED_CANONICAL_PATH).append(\"\\n\").append(\"X-Ops-Content-Hash:\").append(HASHED_BODY).append(\"\\n\")\n            .append(\"X-Ops-Timestamp:\").append(TIMESTAMP_ISO8601).append(\"\\n\").append(\"X-Ops-UserId:\").append(USER_ID)\n            .toString();\n\n      assertEquals(signing_obj.createStringToSign(\"POST\", HASHED_CANONICAL_PATH, HASHED_BODY, TIMESTAMP_ISO8601),\n            expected_string_to_sign);\n      assertEquals(signing_obj.sign(expected_string_to_sign), Joiner.on(\"\").join(X_OPS_AUTHORIZATION_LINES));\n\n      request = signing_obj.filter(request);\n      Multimap<String, String> headersWithoutContentLength = LinkedHashMultimap.create(request.getHeaders());\n      headersWithoutContentLength.removeAll(HttpHeaders.CONTENT_LENGTH);\n      assertEqualsNoOrder(headersWithoutContentLength.values().toArray(), EXPECTED_SIGN_RESULT.values().toArray());\n   }\n\n   @Test\n   void shouldGenerateTheCorrectStringToSignAndSignatureWithNoBody() {\n\n      HttpRequest request = HttpRequest.builder().method(HttpMethod.DELETE).endpoint(\"http://localhost/\" + PATH)\n            .build();\n\n      request = signing_obj.filter(request);\n      Multimap<String, String> headersWithoutContentLength = LinkedHashMultimap.create(request.getHeaders());\n      assertEqualsNoOrder(headersWithoutContentLength.entries().toArray(), EXPECTED_SIGN_RESULT_EMPTY.entries()\n            .toArray());\n   }\n\n   @Test\n   void shouldNotChokeWhenSigningARequestForAResourceWithALongName() {\n      StringBuilder path = new StringBuilder(\"nodes/\");\n      for (int i = 0; i < 100; i++)\n         path.append('A');\n      HttpRequest request = HttpRequest.builder().method(HttpMethod.PUT)\n            .endpoint(\"http://localhost/\" + path.toString()).payload(BODY).build();\n\n      signing_obj.filter(request);\n   }\n\n   @Test\n   void shouldReplacePercentage3FWithQuestionMarkAtUrl() {\n      StringBuilder path = new StringBuilder(\"nodes/\");\n      path.append(\"test/cookbooks/myCookBook%3Fnum_versions=5\");\n      HttpRequest request = HttpRequest.builder().method(HttpMethod.GET)\n            .endpoint(\"http://localhost/\" + path.toString()).payload(BODY).build();\n      request = signing_obj.filter(request);\n      assertTrue(request.getRequestLine().contains(\"?num_versions=5\"));\n   }\n\n   private SignedHeaderAuth signing_obj;\n\n   /**\n    * before class, as we need to ensure that the filter is threadsafe.\n    * \n    * @throws IOException\n    * \n    */\n   @BeforeClass\n   protected void createFilter() throws IOException {\n\n      Injector injector = ContextBuilder.newBuilder(new ChefApiMetadata()).credentials(USER_ID, PRIVATE_KEY)\n            .modules(ImmutableSet.<Module> of(new MockModule(), new NullLoggingModule())).buildInjector();\n\n      HttpUtils utils = injector.getInstance(HttpUtils.class);\n      Crypto crypto = injector.getInstance(Crypto.class);\n\n      Supplier<PrivateKey> privateKey = injector.getInstance(Key.get(new TypeLiteral<Supplier<PrivateKey>>() {\n      }));\n\n      signing_obj = new SignedHeaderAuth(new SignatureWire(),\n            Suppliers.ofInstance(new Credentials(USER_ID, PRIVATE_KEY)), privateKey, new Provider<String>() {\n\n               @Override\n               public String get() {\n                  return TIMESTAMP_ISO8601;\n               }\n\n            }, utils, crypto);\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/functions/BootstrapConfigForGroupTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.functions;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\n\nimport org.jclouds.chef.ChefApi;\nimport org.jclouds.chef.domain.BootstrapConfig;\nimport org.jclouds.chef.domain.Client;\nimport org.jclouds.chef.domain.DatabagItem;\nimport org.jclouds.chef.domain.BootstrapConfig.SSLVerifyMode;\nimport org.jclouds.json.Json;\nimport org.jclouds.json.config.GsonModule;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\", testName = \"BootstrapConfigForGroupTest\")\npublic class BootstrapConfigForGroupTest {\n\n   private Json json;\n\n   @BeforeClass\n   public void setup() {\n      Injector injector = Guice.createInjector(new GsonModule());\n      json = injector.getInstance(Json.class);\n   }\n\n   @Test(expectedExceptions = IllegalStateException.class)\n   public void testWhenNoDatabagItem() throws IOException {\n      ChefApi chefApi = createMock(ChefApi.class);\n      Client client = createMock(Client.class);\n\n      BootstrapConfigForGroup fn = new BootstrapConfigForGroup(\"jclouds\", chefApi, json);\n\n      expect(chefApi.getDatabagItem(\"jclouds\", \"foo\")).andReturn(null);\n      replay(client, chefApi);\n\n      fn.apply(\"foo\");\n\n      verify(client, chefApi);\n   }\n\n   @Test\n   public void testReturnsItem() throws IOException {\n      ChefApi chefApi = createMock(ChefApi.class);\n      Client client = createMock(Client.class);\n\n      BootstrapConfigForGroup fn = new BootstrapConfigForGroup(\"jclouds\", chefApi, json);\n      DatabagItem databag = new DatabagItem(\"foo\",\n            \"{\\\"environment\\\":\\\"development\\\",\\\"ssl_ca_file\\\":\\\"/etc/certs/chef-server.crt\\\",\"\n                  + \"\\\"ssl_verify_mode\\\": \\\":verify_peer\\\",\"\n                  + \"\\\"run_list\\\":[\\\"recipe[apache2]\\\",\\\"role[webserver]\\\"],\"\n                  + \"\\\"attributes\\\":{\\\"tomcat6\\\":{\\\"ssl_port\\\":8433}}}\");\n\n      expect(chefApi.getDatabagItem(\"jclouds\", \"foo\")).andReturn(databag);\n      replay(client, chefApi);\n\n      BootstrapConfig config = fn.apply(\"foo\");\n      assertEquals(config.getEnvironment(), \"development\");\n      assertEquals(config.getSslCAFile(), \"/etc/certs/chef-server.crt\");\n      assertEquals(config.getSslVerifyMode(), SSLVerifyMode.PEER);\n      assertEquals(config.getRunList().get(0), \"recipe[apache2]\");\n      assertEquals(config.getRunList().get(1), \"role[webserver]\");\n      assertEquals(config.getAttributes().toString(), \"{\\\"tomcat6\\\":{\\\"ssl_port\\\":8433}}\");\n\n      verify(client, chefApi);\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/functions/ClientForGroupTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.functions;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.security.PrivateKey;\n\nimport org.jclouds.chef.ChefApi;\nimport org.jclouds.chef.domain.Client;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\", testName = \"ClientForGroupTest\")\npublic class ClientForGroupTest {\n\n   public void testWhenNoClientsInList() throws IOException {\n      ChefApi chefApi = createMock(ChefApi.class);\n      Client client = createMock(Client.class);\n      PrivateKey privateKey = createMock(PrivateKey.class);\n\n      ClientForGroup fn = new ClientForGroup(chefApi);\n\n      expect(chefApi.listClients()).andReturn(ImmutableSet.<String> of());\n      expect(chefApi.createClient(\"foo-client-00\")).andReturn(client);\n      expect(client.getPrivateKey()).andReturn(privateKey);\n\n      replay(client);\n      replay(chefApi);\n\n      Client compare = fn.apply(\"foo\");\n      assertEquals(compare.getClientname(), \"foo-client-00\");\n      assertEquals(compare.getName(), \"foo-client-00\");\n      assertEquals(compare.getPrivateKey(), privateKey);\n\n      verify(client);\n      verify(chefApi);\n   }\n\n   public void testWhenClientsInListAddsToEnd() throws IOException {\n      ChefApi chefApi = createMock(ChefApi.class);\n      Client client = createMock(Client.class);\n      PrivateKey privateKey = createMock(PrivateKey.class);\n\n      ClientForGroup fn = new ClientForGroup(chefApi);\n\n      expect(chefApi.listClients()).andReturn(\n            ImmutableSet.<String> of(\"foo-client-00\", \"foo-client-01\", \"foo-client-02\"));\n      expect(chefApi.createClient(\"foo-client-03\")).andReturn(client);\n      expect(client.getPrivateKey()).andReturn(privateKey);\n\n      replay(client);\n      replay(chefApi);\n\n      Client compare = fn.apply(\"foo\");\n      assertEquals(compare.getClientname(), \"foo-client-03\");\n      assertEquals(compare.getName(), \"foo-client-03\");\n      assertEquals(compare.getPrivateKey(), privateKey);\n\n      verify(client);\n      verify(chefApi);\n   }\n\n   public void testWhenClientsInListReplacesMissing() throws IOException {\n      ChefApi chefApi = createMock(ChefApi.class);\n      Client client = createMock(Client.class);\n      PrivateKey privateKey = createMock(PrivateKey.class);\n\n      ClientForGroup fn = new ClientForGroup(chefApi);\n\n      expect(chefApi.listClients()).andReturn(ImmutableSet.<String> of(\"foo-client-00\", \"foo-client-02\"));\n      expect(chefApi.createClient(\"foo-client-01\")).andReturn(client);\n      expect(client.getPrivateKey()).andReturn(privateKey);\n\n      replay(client);\n      replay(chefApi);\n\n      Client compare = fn.apply(\"foo\");\n      assertEquals(compare.getClientname(), \"foo-client-01\");\n      assertEquals(compare.getName(), \"foo-client-01\");\n      assertEquals(compare.getPrivateKey(), privateKey);\n\n      verify(client);\n      verify(chefApi);\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/functions/GroupToBootScriptTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.functions;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.jclouds.chef.config.ChefProperties.CHEF_UPDATE_GEMS;\nimport static org.jclouds.chef.config.ChefProperties.CHEF_UPDATE_GEM_SYSTEM;\nimport static org.jclouds.chef.config.ChefProperties.CHEF_USE_OMNIBUS;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.net.URI;\nimport java.security.PrivateKey;\n\nimport org.jclouds.chef.ChefApiMetadata;\nimport org.jclouds.chef.config.ChefBootstrapModule;\nimport org.jclouds.chef.config.ChefParserModule;\nimport org.jclouds.chef.config.InstallChef;\nimport org.jclouds.chef.domain.BootstrapConfig;\nimport org.jclouds.chef.domain.BootstrapConfig.SSLVerifyMode;\nimport org.jclouds.chef.util.RunListBuilder;\nimport org.jclouds.crypto.PemsTest;\nimport org.jclouds.domain.JsonBall;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.rest.annotations.ApiVersion;\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.jclouds.scriptbuilder.domain.ShellToken;\nimport org.jclouds.scriptbuilder.domain.Statement;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.base.Functions;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Suppliers;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.io.Resources;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport com.google.inject.Key;\nimport com.google.inject.name.Names;\n\n@Test(groups = \"unit\", testName = \"GroupToBootScriptTest\")\npublic class GroupToBootScriptTest {\n\n   private Statement installChefGems;\n   private Statement installChefOmnibus;\n   private Optional<String> validatorName;\n\n   @BeforeClass\n   public void setup() {\n      Injector injectorGems = Guice.createInjector(new AbstractModule() {\n         @Override\n         protected void configure() {\n            bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefApiMetadata.DEFAULT_API_VERSION);\n            bind(String.class).annotatedWith(Names.named(CHEF_UPDATE_GEM_SYSTEM)).toInstance(\"true\");\n            bind(String.class).annotatedWith(Names.named(CHEF_UPDATE_GEMS)).toInstance(\"true\");\n            bind(String.class).annotatedWith(Names.named(CHEF_USE_OMNIBUS)).toInstance(\"false\");\n         }\n      }, new ChefParserModule(), new GsonModule(), new ChefBootstrapModule());\n\n      Injector injectorOmnibus = Guice.createInjector(new AbstractModule() {\n         @Override\n         protected void configure() {\n            bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefApiMetadata.DEFAULT_API_VERSION);\n            bind(String.class).annotatedWith(Names.named(CHEF_UPDATE_GEM_SYSTEM)).toInstance(\"true\");\n            bind(String.class).annotatedWith(Names.named(CHEF_UPDATE_GEMS)).toInstance(\"true\");\n            bind(String.class).annotatedWith(Names.named(CHEF_USE_OMNIBUS)).toInstance(\"true\");\n         }\n      }, new ChefParserModule(), new GsonModule(), new ChefBootstrapModule());\n\n      installChefGems = injectorGems.getInstance(Key.get(Statement.class, InstallChef.class));\n      installChefOmnibus = injectorOmnibus.getInstance(Key.get(Statement.class, InstallChef.class));\n      validatorName = Optional.<String> of(\"chef-validator\");\n   }\n\n   @Test(expectedExceptions = IllegalStateException.class)\n   public void testMustHaveValidatorName() {\n      Optional<PrivateKey> validatorCredential = Optional.of(createMock(PrivateKey.class));\n      GroupToBootScript fn = new GroupToBootScript(Suppliers.ofInstance(URI.create(\"http://localhost:4000\")),\n            CacheLoader.from(Functions.forMap(ImmutableMap.of(\"foo\", BootstrapConfig.builder().build()))),\n            installChefOmnibus, Optional.<String> absent(), validatorCredential);\n      fn.apply(\"foo\", null);\n   }\n\n   @Test(expectedExceptions = IllegalStateException.class)\n   public void testMustHaveValidatorCredential() {\n      GroupToBootScript fn = new GroupToBootScript(Suppliers.ofInstance(URI.create(\"http://localhost:4000\")),\n            CacheLoader.from(Functions.forMap(ImmutableMap.of(\"foo\", BootstrapConfig.builder().build()))),\n            installChefOmnibus, validatorName, Optional.<PrivateKey> absent());\n      fn.apply(\"foo\", null);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = \"Key 'foo' not present in map\")\n   public void testMustHaveRunScriptsName() {\n      Optional<PrivateKey> validatorCredential = Optional.of(createMock(PrivateKey.class));\n      GroupToBootScript fn = new GroupToBootScript(Suppliers.ofInstance(URI.create(\"http://localhost:4000\")),\n            CacheLoader.from(Functions.forMap(ImmutableMap.<String, BootstrapConfig> of())), installChefOmnibus,\n            validatorName, validatorCredential);\n      fn.apply(\"foo\", null);\n   }\n\n   @Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = \"null value in entry: foo=null\")\n   public void testMustHaveRunScriptsValue() {\n      Optional<PrivateKey> validatorCredential = Optional.of(createMock(PrivateKey.class));\n      GroupToBootScript fn = new GroupToBootScript(Suppliers.ofInstance(URI.create(\"http://localhost:4000\")),\n            CacheLoader.from(Functions.forMap(ImmutableMap.of(\"foo\", (BootstrapConfig) null))), installChefOmnibus,\n            validatorName, validatorCredential);\n      fn.apply(\"foo\", null);\n   }\n\n   public void testOneRecipe() throws IOException {\n      Optional<PrivateKey> validatorCredential = Optional.of(createMock(PrivateKey.class));\n      BootstrapConfig config = BootstrapConfig.builder().attributes(new JsonBall(\"{\\\"tomcat6\\\":{\\\"ssl_port\\\":8433}}\"))\n            .runList(new RunListBuilder().addRecipe(\"apache2\").addRole(\"webserver\").build()).build();\n\n      GroupToBootScript fn = groupToBootScriptFor(config, validatorCredential, false);\n\n      PrivateKey validatorKey = validatorCredential.get();\n      expect(validatorKey.getEncoded()).andReturn(PemsTest.PRIVATE_KEY.getBytes());\n      replay(validatorKey);\n\n      assertEquals(\n            fn.apply(\"foo\", null).render(OsFamily.UNIX),\n            exitInsteadOfReturn(OsFamily.UNIX, readContent(\"test_install_ruby.sh\")\n                  + readContent(\"test_install_rubygems.sh\"))\n                  + \"gem install chef --no-rdoc --no-ri\\n\" + readContent(\"bootstrap.sh\"));\n\n      verify(validatorKey);\n   }\n\n   public void testOneRecipeAndEnvironment() throws IOException {\n      Optional<PrivateKey> validatorCredential = Optional.of(createMock(PrivateKey.class));\n      BootstrapConfig config = BootstrapConfig.builder().attributes(new JsonBall(\"{\\\"tomcat6\\\":{\\\"ssl_port\\\":8433}}\"))\n            .environment(\"env\").runList(new RunListBuilder().addRecipe(\"apache2\").addRole(\"webserver\").build()).build();\n\n      GroupToBootScript fn = groupToBootScriptFor(config, validatorCredential, false);\n\n      PrivateKey validatorKey = validatorCredential.get();\n      expect(validatorKey.getEncoded()).andReturn(PemsTest.PRIVATE_KEY.getBytes());\n      replay(validatorKey);\n\n      assertEquals(\n            fn.apply(\"foo\", null).render(OsFamily.UNIX),\n            exitInsteadOfReturn(OsFamily.UNIX, readContent(\"test_install_ruby.sh\")\n                  + readContent(\"test_install_rubygems.sh\") + \"gem install chef --no-rdoc --no-ri\\n\"\n                  + readContent(\"bootstrap-env.sh\")));\n\n      verify(validatorKey);\n   }\n\n   public void testOneRecipeOmnibus() throws IOException {\n      Optional<PrivateKey> validatorCredential = Optional.of(createMock(PrivateKey.class));\n      BootstrapConfig config = BootstrapConfig.builder().attributes(new JsonBall(\"{\\\"tomcat6\\\":{\\\"ssl_port\\\":8433}}\"))\n            .runList(new RunListBuilder().addRecipe(\"apache2\").addRole(\"webserver\").build()).build();\n\n      GroupToBootScript fn = groupToBootScriptFor(config, validatorCredential, true);\n\n      PrivateKey validatorKey = validatorCredential.get();\n      expect(validatorKey.getEncoded()).andReturn(PemsTest.PRIVATE_KEY.getBytes());\n      replay(validatorKey);\n\n      assertEquals(fn.apply(\"foo\", null).render(OsFamily.UNIX),\n            \"setupPublicCurl || exit 1\\ncurl -q -s -S -L --connect-timeout 10 --max-time 600 --retry 20 \"\n                  + \"-X GET  https://www.opscode.com/chef/install.sh |(bash)\\n\" + readContent(\"bootstrap.sh\"));\n\n      verify(validatorKey);\n   }\n\n   public void testOneRecipeAndEnvironmentOmnibus() throws IOException {\n      Optional<PrivateKey> validatorCredential = Optional.of(createMock(PrivateKey.class));\n      BootstrapConfig config = BootstrapConfig.builder().attributes(new JsonBall(\"{\\\"tomcat6\\\":{\\\"ssl_port\\\":8433}}\"))\n            .environment(\"env\").runList(new RunListBuilder().addRecipe(\"apache2\").addRole(\"webserver\").build()).build();\n\n      GroupToBootScript fn = groupToBootScriptFor(config, validatorCredential, true);\n\n      PrivateKey validatorKey = validatorCredential.get();\n      expect(validatorKey.getEncoded()).andReturn(PemsTest.PRIVATE_KEY.getBytes());\n      replay(validatorKey);\n\n      assertEquals(fn.apply(\"foo\", null).render(OsFamily.UNIX),\n            \"setupPublicCurl || exit 1\\ncurl -q -s -S -L --connect-timeout 10 --max-time 600 --retry 20 \"\n                  + \"-X GET  https://www.opscode.com/chef/install.sh |(bash)\\n\" + readContent(\"bootstrap-env.sh\"));\n\n      verify(validatorKey);\n   }\n\n   public void testNoAttribtues() throws IOException {\n      Optional<PrivateKey> validatorCredential = Optional.of(createMock(PrivateKey.class));\n      BootstrapConfig config = BootstrapConfig.builder()\n            .environment(\"env\").runList(new RunListBuilder().addRecipe(\"apache2\").addRole(\"webserver\").build()).build();\n\n      GroupToBootScript fn = groupToBootScriptFor(config, validatorCredential, true);\n\n      PrivateKey validatorKey = validatorCredential.get();\n      expect(validatorKey.getEncoded()).andReturn(PemsTest.PRIVATE_KEY.getBytes());\n      replay(validatorKey);\n\n      assertEquals(fn.apply(\"foo\", null).render(OsFamily.UNIX),\n            \"setupPublicCurl || exit 1\\ncurl -q -s -S -L --connect-timeout 10 --max-time 600 --retry 20 \"\n                  + \"-X GET  https://www.opscode.com/chef/install.sh |(bash)\\n\" + readContent(\"bootstrap-env-noattrs.sh\"));\n\n      verify(validatorKey);\n   }\n\n   public void testCustomNodeName() throws IOException {\n      Optional<PrivateKey> validatorCredential = Optional.of(createMock(PrivateKey.class));\n      BootstrapConfig config = BootstrapConfig.builder().attributes(new JsonBall(\"{\\\"tomcat6\\\":{\\\"ssl_port\\\":8433}}\"))\n            .environment(\"env\").runList(new RunListBuilder().addRecipe(\"apache2\").addRole(\"webserver\").build()).build();\n\n      GroupToBootScript fn = groupToBootScriptFor(config, validatorCredential, true);\n\n      PrivateKey validatorKey = validatorCredential.get();\n      expect(validatorKey.getEncoded()).andReturn(PemsTest.PRIVATE_KEY.getBytes());\n      replay(validatorKey);\n\n      assertEquals(fn.apply(\"foo\", \"bar\").render(OsFamily.UNIX),\n            \"setupPublicCurl || exit 1\\ncurl -q -s -S -L --connect-timeout 10 --max-time 600 --retry 20 \"\n                  + \"-X GET  https://www.opscode.com/chef/install.sh |(bash)\\n\" + readContent(\"bootstrap-node-env.sh\"));\n\n      verify(validatorKey);\n   }\n\n   public void testCustomSecurityOptions() throws IOException {\n      Optional<PrivateKey> validatorCredential = Optional.of(createMock(PrivateKey.class));\n      BootstrapConfig config = BootstrapConfig.builder().attributes(new JsonBall(\"{\\\"tomcat6\\\":{\\\"ssl_port\\\":8433}}\"))\n            .runList(new RunListBuilder().addRecipe(\"apache2\").addRole(\"webserver\").build())\n            .sslCAFile(readContent(\"chef.crt\")).sslCAPath(\"/etc/chef\").sslVerifyMode(SSLVerifyMode.PEER)\n            .verifyApiCert(true).build();\n\n      GroupToBootScript fn = groupToBootScriptFor(config, validatorCredential, true);\n\n      PrivateKey validatorKey = validatorCredential.get();\n      expect(validatorKey.getEncoded()).andReturn(PemsTest.PRIVATE_KEY.getBytes());\n      replay(validatorKey);\n\n      assertEquals(fn.apply(\"foo\", null).render(OsFamily.UNIX),\n            \"setupPublicCurl || exit 1\\ncurl -q -s -S -L --connect-timeout 10 --max-time 600 --retry 20 \"\n                  + \"-X GET  https://www.opscode.com/chef/install.sh |(bash)\\n\" + readContent(\"bootstrap-ssl.sh\"));\n\n      verify(validatorKey);\n   }\n\n   private static String exitInsteadOfReturn(OsFamily family, String input) {\n      return input.replaceAll(ShellToken.RETURN.to(family), ShellToken.EXIT.to(family));\n   }\n\n   private GroupToBootScript groupToBootScriptFor(BootstrapConfig config, Optional<PrivateKey> validatorCredential,\n         boolean useOmnibus) {\n      return new GroupToBootScript(Suppliers.ofInstance(URI.create(\"http://localhost:4000\")),\n            CacheLoader.from(Functions.forMap(ImmutableMap.of(\"foo\", config))), useOmnibus ? installChefOmnibus\n                  : installChefGems, validatorName, validatorCredential);\n   }\n\n   private static String readContent(String resource) throws IOException {\n      return Resources.toString(Resources.getResource(resource), Charsets.UTF_8);\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/functions/ParseClientFromJsonTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.PrivateKey;\nimport java.security.PublicKey;\nimport java.security.cert.CertificateException;\nimport java.security.cert.X509Certificate;\nimport java.security.spec.InvalidKeySpecException;\n\nimport org.jclouds.chef.ChefApiMetadata;\nimport org.jclouds.chef.config.ChefParserModule;\nimport org.jclouds.chef.domain.Client;\nimport org.jclouds.crypto.Crypto;\nimport org.jclouds.crypto.Pems;\nimport org.jclouds.encryption.internal.JCECrypto;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.io.ByteStreams2;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.io.payloads.RSADecryptingPayload;\nimport org.jclouds.io.payloads.RSAEncryptingPayload;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.rest.annotations.ApiVersion;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.io.ByteSource;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport com.google.inject.Key;\nimport com.google.inject.TypeLiteral;\n\nimport java.security.interfaces.RSAPrivateCrtKey;\nimport java.security.spec.RSAPublicKeySpec;\n\n/**\n * Tests behavior of {@code ParseClientFromJson}\n */\n@Test(groups = { \"unit\" })\npublic class ParseClientFromJsonTest {\n\n   private static final String PRIVATE_KEY = \"-----BEGIN RSA PRIVATE KEY-----\\nMIIEpQIBAAKCAQEAyb2ZJJqGm0KKR+8nfQJNsSd+F9tXNMV7CfOcW6jsqs8EZgiV\\nR09hD1IYOj4YqM0qJONlgyg4xRWewdSG7QTPj1lJpVAida9sXy2+kzyagZA1Am0O\\nZcbqb5hoeIDgcX+eDa79s0u0DomjcfO9EKhvHLBz+zM+3QqPRkPV8nYTbfs+HjVz\\nzOU6D1B0XR3+IPZZl2AnWs2d0qhnStHcDUvnRVQ0P482YwN9VgceOZtpPz0DCKEJ\\n5Tx5STub8k0/zt/VAMHQafLSuQMLd2s4ZLuOZptN//uAsTmxireqd37z+8ZTdBbJ\\n8LEpJ+iCXuSfm5aUh7iw6oxvToY2AL53+jK2UQIDAQABAoIBAQDA88B3i/xWn0vX\\nBVxFamCYoecuNjGwXXkSyZew616A+EOCu47bh4aTurdFbYL0YFaAtaWvzlaN2eHg\\nDb+HDuTefE29+WkcGk6SshPmiz5T0XOCAICWw6wSVDkHmGwS4jZvbAFm7W8nwGk9\\nYhxgxFiRngswJZFopOLoF5WXs2td8guIYNslMpo7tu50iFnBHwKO2ZsPAk8t9nnS\\nxlDavKruymEmqHCr3+dtio5eaenJcp3fjoXBQOKUk3ipII29XRB8NqeCVV/7Kxwq\\nckqOBEbRwBclckyIbD+RiAgKvOelORjEiE9R42vuqvxRA6k9kd9o7utlX0AUtpEn\\n3gZc6LepAoGBAP9ael5Y75+sK2JJUNOOhO8ae45cdsilp2yI0X+UBaSuQs2+dyPp\\nkpEHAxd4pmmSvn/8c9TlEZhr+qYbABXVPlDncxpIuw2Ajbk7s/S4XaSKsRqpXL57\\nzj/QOqLkRk8+OVV9q6lMeQNqLtEj1u6JPviX70Ro+FQtRttNOYbfdP/fAoGBAMpA\\nXjR5woV5sUb+REg9vEuYo8RSyOarxqKFCIXVUNsLOx+22+AK4+CQpbueWN7jotrl\\nYD6uT6svWi3AAC7kiY0UI/fjVPRCUi8tVoQUE0TaU5VLITaYOB+W/bBaDE4M9560\\n1NuDWO90baA5dfU44iuzva02rGJXK9+nS3o8nk/PAoGBALOL6djnDe4mwAaG6Jco\\ncd4xr8jkyPzCRZuyBCSBbwphIUXLc7hDprPky064ncJD1UDmwIdkXd/fpMkg2QmA\\n/CUk6LEFjMisqHojOaCL9gQZJPhLN5QUN2x1PJWGjs1vQh8Tkx0iUUCOa8bQPXNR\\n+34OTsW6TUna4CSZAycLfhffAoGBAIggVsefBCvuQkF0NeUhmDCRZfhnd8y55RHR\\n1HCvqKIlpv+rhcX/zmyBLuteopYyRJRsOiE2FW00i8+rIPRu4Z3Q5nybx7w3PzV9\\noHN5R5baE9OyI4KpZWztpYYitZF67NcnAvVULHHOvVJQGnKYfLHJYmrJF7GA1ojM\\nAuMdFbjFAoGAPxUhxwFy8gaqBahKUEZn4F81HFP5ihGhkT4QL6AFPO2e+JhIGjuR\\n27+85hcFqQ+HHVtFsm81b/a+R7P4UuCRgc8eCjxQMoJ1Xl4n7VbjPbHMnIN0Ryvd\\nO4ZpWDWYnCO021JTOUUOJ4J/y0416Bvkw0z59y7sNX7wDBBHHbK/XCc=\\n-----END RSA PRIVATE KEY-----\\n\";\n   private static final String CERTIFICATE = \"-----BEGIN CERTIFICATE-----\\nMIIClzCCAgCgAwIBAgIBATANBgkqhkiG9w0BAQUFADCBnjELMAkGA1UEBhMCVVMx\\nEzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxFjAUBgNVBAoM\\nDU9wc2NvZGUsIEluYy4xHDAaBgNVBAsME0NlcnRpZmljYXRlIFNlcnZpY2UxMjAw\\nBgNVBAMMKW9wc2NvZGUuY29tL2VtYWlsQWRkcmVzcz1hdXRoQG9wc2NvZGUuY29t\\nMB4XDTEwMDczMDIwNDEzMFoXDTIwMDcyNzIwNDEzMFowADCCASIwDQYJKoZIhvcN\\nAQEBBQADggEPADCCAQoCggEBAMm9mSSahptCikfvJ30CTbEnfhfbVzTFewnznFuo\\n7KrPBGYIlUdPYQ9SGDo+GKjNKiTjZYMoOMUVnsHUhu0Ez49ZSaVQInWvbF8tvpM8\\nmoGQNQJtDmXG6m+YaHiA4HF/ng2u/bNLtA6Jo3HzvRCobxywc/szPt0Kj0ZD1fJ2\\nE237Ph41c8zlOg9QdF0d/iD2WZdgJ1rNndKoZ0rR3A1L50VUND+PNmMDfVYHHjmb\\naT89AwihCeU8eUk7m/JNP87f1QDB0Gny0rkDC3drOGS7jmabTf/7gLE5sYq3qnd+\\n8/vGU3QWyfCxKSfogl7kn5uWlIe4sOqMb06GNgC+d/oytlECAwEAATANBgkqhkiG\\n9w0BAQUFAAOBgQBftzSZxstWw60GqRTDNN/F2GnrdtnKBoXzHww3r6jtGEylYq20\\n5KfKpEx+sPX0gyZuYJiXC2CkEjImAluWKcdN9ZF6VD541sheAjbiaU7q7ZsztTxF\\nWUH2tCvHeDXYKPKek3QzL7bYpUhLnCN/XxEv6ibeMDwtI7f5qpk2Aspzcw==\\n-----END CERTIFICATE-----\\n\";\n   private ParseJson<Client> handler;\n   private Crypto crypto;\n   private PrivateKey privateKey;\n   private X509Certificate certificate;\n   private PublicKey publicKey;\n\n   @BeforeTest\n   protected void setUpInjector() throws IOException, CertificateException, InvalidKeySpecException, NoSuchAlgorithmException {\n      Injector injector = Guice.createInjector(new AbstractModule() {\n         @Override\n         protected void configure() {\n            bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefApiMetadata.DEFAULT_API_VERSION);\n         }\n      }, new ChefParserModule(), new GsonModule());\n\n      handler = injector.getInstance(Key.get(new TypeLiteral<ParseJson<Client>>() {\n      }));\n      crypto = injector.getInstance(Crypto.class);\n      certificate = Pems.x509Certificate(ByteSource.wrap(CERTIFICATE.getBytes(Charsets.UTF_8)), null);\n      privateKey = crypto.rsaKeyFactory().generatePrivate(Pems.privateKeySpec(ByteSource.wrap(PRIVATE_KEY.getBytes(Charsets.UTF_8))));\n\n      RSAPrivateCrtKey privk = (RSAPrivateCrtKey)privateKey;\n      RSAPublicKeySpec publicKeySpec = new java.security.spec.RSAPublicKeySpec(privk.getModulus(), privk.getPublicExponent());\n      publicKey = crypto.rsaKeyFactory().generatePublic(publicKeySpec);\n   }\n\n   public void testClientWithPubKey() throws IOException, CertificateException, NoSuchAlgorithmException {\n\n      Client user = Client.builder().certificate(certificate).orgname(\"jclouds\").clientname(\"adriancole-jcloudstest\")\n            .name(\"adriancole-jcloudstest\").isValidator(false).privateKey(privateKey).publicKey(publicKey).build();\n\n      assertEquals(\n            handler.apply(HttpResponse.builder().statusCode(200).message(\"ok\")\n                  .payload(ParseClientFromJsonTest.class.getResourceAsStream(\"/client.json\")).build()), user);\n   }\n\n   public void testClientWithoutPubKey() throws IOException, CertificateException, NoSuchAlgorithmException {\n\n      Client user = Client.builder().certificate(certificate).orgname(\"jclouds\").clientname(\"adriancole-jcloudstest\")\n              .name(\"adriancole-jcloudstest\").isValidator(false).privateKey(privateKey).build();\n\n      assertEquals(\n              handler.apply(HttpResponse.builder().statusCode(200).message(\"ok\")\n                      .payload(ParseClientFromJsonTest.class.getResourceAsStream(\"/client-no-pub-key.json\")).build()), user);\n   }\n\n   @SuppressWarnings(\"resource\")\n   public void testEncryptionWithClientPriv() throws IOException, CertificateException, NoSuchAlgorithmException {\n\n      Client user = Client.builder().certificate(certificate).orgname(\"jclouds\").clientname(\"adriancole-jcloudstest\")\n              .name(\"adriancole-jcloudstest\").isValidator(false).privateKey(privateKey).publicKey(publicKey).build();\n\n      byte[] encrypted = ByteStreams2.toByteArrayAndClose(new RSAEncryptingPayload(new JCECrypto(), Payloads.newPayload(\"fooya\"), user\n              .getCertificate().getPublicKey()).openStream());\n\n      assertEquals(\n              ByteStreams2.toByteArrayAndClose(new RSADecryptingPayload(new JCECrypto(), Payloads.newPayload(encrypted), user.getPrivateKey()).openStream()),\n              \"fooya\".getBytes());\n\n      assertEquals(\n              handler.apply(HttpResponse.builder().statusCode(200).message(\"ok\")\n                      .payload(ParseClientFromJsonTest.class.getResourceAsStream(\"/client.json\")).build()), user);\n   }\n\n\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/functions/ParseCookbookDefinitionFromJsonTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.net.URI;\nimport java.net.URISyntaxException;\n\nimport org.jclouds.chef.ChefApiMetadata;\nimport org.jclouds.chef.config.ChefParserModule;\nimport org.jclouds.chef.domain.CookbookDefinition;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.rest.annotations.ApiVersion;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = { \"unit\" }, singleThreaded = true)\npublic class ParseCookbookDefinitionFromJsonTest\n{\n\n   private ParseCookbookDefinitionFromJson handler;\n\n   @BeforeTest\n   protected void setUpInjector() throws IOException {\n      Injector injector = Guice.createInjector(new AbstractModule() {\n         @Override\n         protected void configure() {\n            bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefApiMetadata.DEFAULT_API_VERSION);\n         }\n      }, new ChefParserModule(), new GsonModule());\n\n      handler = injector.getInstance(ParseCookbookDefinitionFromJson.class);\n   }\n\n   public void testCookbokDefinitionParsing() throws URISyntaxException {\n      CookbookDefinition.Version v510 = CookbookDefinition.Version.builder()\n            .url(new URI(\"http://localhost:4000/cookbooks/apache2/5.1.0\")).version(\"5.1.0\").build();\n      CookbookDefinition.Version v420 = CookbookDefinition.Version.builder()\n            .url(new URI(\"http://localhost:4000/cookbooks/apache2/4.2.0\")).version(\"4.2.0\").build();\n      CookbookDefinition definition = CookbookDefinition.builder()\n            .name(\"apache2\").url(new URI(\"http://localhost:4000/cookbooks/apache2\")).version(v510).version(v420).build();\n\n      assertEquals(handler.apply(HttpResponse\n            .builder()\n            .statusCode(200)\n            .message(\"ok\")\n            .payload(\n                  \"{\" + \"\\\"apache2\\\" => {\" + \"\\\"url\\\" => \\\"http://localhost:4000/cookbooks/apache2\\\",\"\n                        + \"\\\"versions\\\" => [\" + \"{\\\"url\\\" => \\\"http://localhost:4000/cookbooks/apache2/5.1.0\\\",\"\n                        + \"\\\"version\\\" => \\\"5.1.0\\\"},\"\n                        + \"{\\\"url\\\" => \\\"http://localhost:4000/cookbooks/apache2/4.2.0\\\",\"\n                        + \"\\\"version\\\" => \\\"4.2.0\\\"}\" + \"]\" + \"}\" + \"}\").build()), definition);\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/functions/ParseCookbookDefinitionListFromJsonTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.net.URI;\nimport java.net.URISyntaxException;\n\nimport org.jclouds.chef.ChefApiMetadata;\nimport org.jclouds.chef.config.ChefParserModule;\nimport org.jclouds.chef.domain.CookbookDefinition;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.rest.annotations.ApiVersion;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = {\"unit\"}, singleThreaded = true)\npublic class ParseCookbookDefinitionListFromJsonTest\n{\n   private ParseCookbookDefinitionListFromJson handler;\n\n   @BeforeTest\n   protected void setUpInjector() throws IOException {\n      Injector injector = Guice.createInjector(new AbstractModule() {\n         @Override\n         protected void configure() {\n            bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefApiMetadata.DEFAULT_API_VERSION);\n         }\n      }, new ChefParserModule(), new GsonModule());\n\n      handler = injector.getInstance(ParseCookbookDefinitionListFromJson.class);\n   }\n\n   public void testCookbokDefinitionListParsing() throws URISyntaxException {\n      CookbookDefinition.Version v510 = CookbookDefinition.Version.builder()\n            .url(new URI(\"http://localhost:4000/cookbooks/apache2/5.1.0\")).version(\"5.1.0\").build();\n      CookbookDefinition.Version v420 = CookbookDefinition.Version.builder()\n            .url(new URI(\"http://localhost:4000/cookbooks/apache2/4.2.0\")).version(\"4.2.0\").build();\n      CookbookDefinition apache2 = CookbookDefinition.builder()\n            .name(\"apache2\").url(new URI(\"http://localhost:4000/cookbooks/apache2\")).version(v510).version(v420).build();\n      \n      CookbookDefinition.Version v100 = CookbookDefinition.Version.builder()\n            .url(new URI(\"http://localhost:4000/cookbooks/nginx/1.0.0\")).version(\"1.0.0\").build();\n      CookbookDefinition.Version v030 = CookbookDefinition.Version.builder()\n            .url(new URI(\"http://localhost:4000/cookbooks/nginx/0.3.0\")).version(\"0.3.0\").build();\n      CookbookDefinition nginx = CookbookDefinition.builder()\n            .name(\"nginx\").url(new URI(\"http://localhost:4000/cookbooks/nginx\")).version(v100).version(v030).build();\n      \n      assertEquals(handler.apply(HttpResponse\n            .builder()\n            .statusCode(200)\n            .message(\"ok\")\n            .payload(\n                  \"{\" + \"\\\"apache2\\\" => {\" + \"\\\"url\\\" => \\\"http://localhost:4000/cookbooks/apache2\\\",\"\n                        + \"\\\"versions\\\" => [\" + \"{\\\"url\\\" => \\\"http://localhost:4000/cookbooks/apache2/5.1.0\\\",\"\n                        + \"\\\"version\\\" => \\\"5.1.0\\\"},\"\n                        + \"{\\\"url\\\" => \\\"http://localhost:4000/cookbooks/apache2/4.2.0\\\",\"\n                        + \"\\\"version\\\" => \\\"4.2.0\\\"}\" + \"]\" + \"},\"\n                        + \"\\\"nginx\\\" => {\"\n                        + \"\\\"url\\\" => \\\"http://localhost:4000/cookbooks/nginx\\\",\"\n                        + \"\\\"versions\\\" => [\"\n                        + \"{\\\"url\\\" => \\\"http://localhost:4000/cookbooks/nginx/1.0.0\\\",\"\n                        + \"\\\"version\\\" => \\\"1.0.0\\\"},\"\n                        + \"{\\\"url\\\" => \\\"http://localhost:4000/cookbooks/nginx/0.3.0\\\",\"\n                        + \"\\\"version\\\" => \\\"0.3.0\\\"}\"\n                        + \"]}\" +\n                        \"}\").build()),\n            ImmutableSet.of(apache2, nginx));\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/functions/ParseCookbookNamesFromJsonTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\n\nimport org.jclouds.chef.ChefApiMetadata;\nimport org.jclouds.chef.config.ChefParserModule;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.rest.annotations.ApiVersion;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n/**\n * Tests behavior of {@code ParseCookbookNamesFromJson}.\n */\n@Test(groups = { \"unit\" }, singleThreaded = true)\npublic class ParseCookbookNamesFromJsonTest\n{\n   private ParseCookbookNamesFromJson handler;\n\n   @BeforeTest\n   protected void setUpInjector() throws IOException {\n      Injector injector = Guice.createInjector(new AbstractModule() {\n         @Override\n         protected void configure() {\n            bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefApiMetadata.DEFAULT_API_VERSION);\n         }\n      }, new ChefParserModule(), new GsonModule());\n\n      handler = injector.getInstance(ParseCookbookNamesFromJson.class);\n   }\n\n   public void testParse010Response() {\n      assertEquals(handler.apply(HttpResponse\n            .builder()\n            .statusCode(200)\n            .message(\"ok\")\n            .payload(\n                  \"{\" + \"\\\"apache2\\\" => {\" + \"\\\"url\\\" => \\\"http://localhost:4000/cookbooks/apache2\\\",\"\n                        + \"\\\"versions\\\" => [\" + \"{\\\"url\\\" => \\\"http://localhost:4000/cookbooks/apache2/5.1.0\\\",\"\n                        + \"\\\"version\\\" => \\\"5.1.0\\\"},\"\n                        + \"{\\\"url\\\" => \\\"http://localhost:4000/cookbooks/apache2/4.2.0\\\",\"\n                        + \"\\\"version\\\" => \\\"4.2.0\\\"}\" + \"]\" + \"},\" + \"\\\"nginx\\\" => {\"\n                        + \"\\\"url\\\" => \\\"http://localhost:4000/cookbooks/nginx\\\",\" + \"\\\"versions\\\" => [\"\n                        + \"{\\\"url\\\" => \\\"http://localhost:4000/cookbooks/nginx/1.0.0\\\",\" + \"\\\"version\\\" => \\\"1.0.0\\\"},\"\n                        + \"{\\\"url\\\" => \\\"http://localhost:4000/cookbooks/nginx/0.3.0\\\",\" + \"\\\"version\\\" => \\\"0.3.0\\\"}\"\n                        + \"]\" + \"}\" + \"}\").build()), ImmutableSet.of(\"apache2\", \"nginx\"));\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/functions/ParseCookbookVersionFromJsonTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.functions;\n\nimport static com.google.common.io.BaseEncoding.base16;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.net.URI;\n\nimport org.jclouds.chef.ChefApiMetadata;\nimport org.jclouds.chef.config.ChefParserModule;\nimport org.jclouds.chef.domain.CookbookVersion;\nimport org.jclouds.chef.domain.Grouping;\nimport org.jclouds.chef.domain.Metadata;\nimport org.jclouds.chef.domain.Resource;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.rest.annotations.ApiVersion;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport com.google.inject.Key;\nimport com.google.inject.TypeLiteral;\n\n/**\n * Tests behavior of {@code ParseCookbookVersionFromJson}\n */\n@Test(groups = { \"unit\" }, singleThreaded = true)\npublic class ParseCookbookVersionFromJsonTest {\n\n   private ParseJson<CookbookVersion> handler;\n   private Injector injector;\n   private Json json;\n\n   @BeforeTest\n   protected void setUpInjector() throws IOException {\n      injector = Guice.createInjector(new AbstractModule() {\n         @Override\n         protected void configure() {\n            bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefApiMetadata.DEFAULT_API_VERSION);\n         }\n      }, new ChefParserModule(), new GsonModule());\n\n      json = injector.getInstance(Json.class);\n      handler = injector.getInstance(Key.get(new TypeLiteral<ParseJson<CookbookVersion>>() {\n      }));\n   }\n\n   public void testBrew() throws IOException {\n      CookbookVersion cookbook = handler.apply(HttpResponse.builder().statusCode(200).message(\"ok\")\n            .payload(ParseCookbookVersionFromJsonTest.class.getResourceAsStream(\"/brew-cookbook.json\")).build());\n\n      assertEquals(cookbook,\n            handler.apply(HttpResponse.builder().statusCode(200).message(\"ok\").payload(json.toJson(cookbook)).build()));\n   }\n\n   public void testTomcat() {\n      CookbookVersion cookbook = handler.apply(HttpResponse.builder().statusCode(200).message(\"ok\")\n            .payload(ParseCookbookVersionFromJsonTest.class.getResourceAsStream(\"/tomcat-cookbook.json\")).build());\n\n      assertEquals(cookbook,\n            handler.apply(HttpResponse.builder().statusCode(200).message(\"ok\").payload(json.toJson(cookbook)).build()));\n   }\n\n   public void testMysql() throws IOException {\n      CookbookVersion cookbook = handler.apply(HttpResponse.builder().statusCode(200).message(\"ok\")\n            .payload(ParseCookbookVersionFromJsonTest.class.getResourceAsStream(\"/mysql-cookbook.json\")).build());\n\n      assertEquals(cookbook,\n            handler.apply(HttpResponse.builder().statusCode(200).message(\"ok\").payload(json.toJson(cookbook)).build()));\n   }\n\n   public void testApache() {\n      CookbookVersion fromJson = handler.apply(HttpResponse.builder().statusCode(200).message(\"ok\")\n            .payload(ParseCookbookVersionFromJsonTest.class.getResourceAsStream(\"/apache-chef-demo-cookbook.json\"))\n            .build());\n\n      CookbookVersion expected = CookbookVersion\n            .builder(\"apache-chef-demo\", \"0.0.0\")\n            .metadata(Metadata.builder() //\n                  .license(\"Apache v2.0\") //\n                  .maintainer(\"Your Name\") //\n                  .maintainerEmail(\"youremail@example.com\") //\n                  .description(\"A fabulous new cookbook\") //\n                  .version(\"0.0.0\") //\n                  .name(\"apache-chef-demo\") //\n                  .longDescription(\"\") //\n                  .grouping(\"one\", Grouping.builder().title(\"One title\").description(\"One description\").build()) //\n                  .grouping(\"two\", Grouping.builder().title(\"Two title\").description(\"Two description\").build()) //\n                  .build())\n            .rootFile(\n                  Resource\n                        .builder()\n                        .name(\"README\")\n                        .path(\"README\")\n                        .checksum(base16().lowerCase().decode(\"11637f98942eafbf49c71b7f2f048b78\"))\n                        .url(URI\n                              .create(\"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-11637f98942eafbf49c71b7f2f048b78?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277766181&Signature=zgpNl6wSxjTNovqZu2nJq0JztU8%3D\")) //\n                        .build())\n            .rootFile(\n                  Resource\n                        .builder()\n                        .name(\"Rakefile\")\n                        .path(\"Rakefile\")\n                        .checksum(base16().lowerCase().decode(\"ebcf925a1651b4e04b9cd8aac2bc54eb\"))\n                        .url(URI\n                              .create(\"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-ebcf925a1651b4e04b9cd8aac2bc54eb?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277766181&Signature=EFzzDSKKytTl7b%2FxrCeNLh05zj4%3D\"))\n                        .build()) //\n            .build();\n\n      assertEquals(fromJson, expected);\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/functions/ParseCookbookVersionsFromJsonTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\n\nimport org.jclouds.chef.ChefApiMetadata;\nimport org.jclouds.chef.config.ChefParserModule;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.rest.annotations.ApiVersion;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n/**\n * Tests behavior of {@code ParseCookbookVersionsFromJson}\n */\n@Test(groups = { \"unit\" }, singleThreaded = true)\npublic class ParseCookbookVersionsFromJsonTest\n{\n   private ParseCookbookVersionsFromJson handler;\n\n   @BeforeTest\n   protected void setUpInjector() throws IOException {\n      Injector injector = Guice.createInjector(new AbstractModule() {\n         @Override\n         protected void configure() {\n            bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefApiMetadata.DEFAULT_API_VERSION);\n         }\n      }, new ChefParserModule(), new GsonModule());\n\n      handler = injector.getInstance(ParseCookbookVersionsFromJson.class);\n   }\n\n   public void testRegex() {\n      assertEquals(handler.apply(HttpResponse\n            .builder()\n            .statusCode(200)\n            .message(\"ok\")\n            .payload(\n                  \"{\" + \"\\\"apache2\\\" => {\" + \"\\\"url\\\" => \\\"http://localhost:4000/cookbooks/apache2\\\",\"\n                        + \"\\\"versions\\\" => [\" + \"{\\\"url\\\" => \\\"http://localhost:4000/cookbooks/apache2/5.1.0\\\",\"\n                        + \"\\\"version\\\" => \\\"5.1.0\\\"},\"\n                        + \"{\\\"url\\\" => \\\"http://localhost:4000/cookbooks/apache2/4.2.0\\\",\"\n                        + \"\\\"version\\\" => \\\"4.2.0\\\"}\" + \"]\" + \"}\" + \"}\").build()), ImmutableSet.of(\"5.1.0\", \"4.2.0\"));\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/functions/ParseDataBagItemFromJsonTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\n\nimport org.jclouds.chef.ChefApiMetadata;\nimport org.jclouds.chef.config.ChefParserModule;\nimport org.jclouds.chef.domain.DatabagItem;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.rest.annotations.ApiVersion;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport com.google.inject.Key;\nimport com.google.inject.TypeLiteral;\n\n@Test(groups = { \"unit\" })\npublic class ParseDataBagItemFromJsonTest {\n   private ParseJson<DatabagItem> handler;\n   private Json mapper;\n\n   @BeforeTest\n   protected void setUpInjector() throws IOException {\n      Injector injector = Guice.createInjector(new AbstractModule() {\n         @Override\n         protected void configure() {\n            bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefApiMetadata.DEFAULT_API_VERSION);\n         }\n      }, new ChefParserModule(), new GsonModule());\n\n      handler = injector.getInstance(Key.get(new TypeLiteral<ParseJson<DatabagItem>>() {\n      }));\n      mapper = injector.getInstance(Json.class);\n   }\n\n   public void test1() {\n      String json = \"{\\\"my_key\\\":\\\"my_data\\\",\\\"id\\\":\\\"item1\\\"}\";\n      DatabagItem item = new DatabagItem(\"item1\", json);\n      assertEquals(handler.apply(HttpResponse.builder().statusCode(200).message(\"ok\").payload(json).build()), item);\n      assertEquals(mapper.toJson(item), json);\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/functions/ParseErrorFromJsonOrReturnBodyTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\nimport java.net.UnknownHostException;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ReturnStringIf2xx;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.Test;\n\n@Test(groups = { \"unit\" })\npublic class ParseErrorFromJsonOrReturnBodyTest {\n\n   @Test\n   public void testApplyInputStreamDetails() throws UnknownHostException {\n      InputStream is = Strings2\n            .toInputStream(\"{\\\"error\\\":[\\\"invalid tarball: tarball root must contain java-bytearray\\\"]}\");\n\n      ParseErrorFromJsonOrReturnBody parser = new ParseErrorFromJsonOrReturnBody(new ReturnStringIf2xx());\n      String response = parser.apply(HttpResponse.builder().statusCode(200).message(\"ok\").payload(is).build());\n      assertEquals(response, \"invalid tarball: tarball root must contain java-bytearray\");\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/functions/ParseKeySetFromJsonTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\n\nimport org.jclouds.chef.ChefApiMetadata;\nimport org.jclouds.chef.config.ChefParserModule;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.rest.annotations.ApiVersion;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n/**\n * Tests behavior of {@code ParseKeySetFromJson}\n */\n@Test(groups = { \"unit\" }, singleThreaded = true)\npublic class ParseKeySetFromJsonTest {\n\n   private ParseKeySetFromJson handler;\n\n   @BeforeTest\n   protected void setUpInjector() throws IOException {\n      Injector injector = Guice.createInjector(new AbstractModule() {\n         @Override\n         protected void configure() {\n            bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefApiMetadata.DEFAULT_API_VERSION);\n         }\n      }, new ChefParserModule(), new GsonModule());\n\n      handler = injector.getInstance(ParseKeySetFromJson.class);\n   }\n\n   public void testRegex() {\n      assertEquals(\n            handler.apply(HttpResponse\n                  .builder()\n                  .statusCode(200)\n                  .message(\"ok\")\n                  .payload(\n                        \"{\\n\\\"opscode-validator\\\": \\\"https://api.opscode.com/...\\\", \\\"pimp-validator\\\": \\\"https://api.opscode.com/...\\\"}\")\n                  .build()), ImmutableSet.of(\"opscode-validator\", \"pimp-validator\"));\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/functions/ParseNodeFromJsonTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\n\nimport org.jclouds.chef.ChefApiMetadata;\nimport org.jclouds.chef.config.ChefParserModule;\nimport org.jclouds.chef.domain.Node;\nimport org.jclouds.domain.JsonBall;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.rest.annotations.ApiVersion;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport com.google.inject.Key;\nimport com.google.inject.TypeLiteral;\n\n/**\n * Tests behavior of {@code ParseNodeFromJson}\n */\n@Test(groups = { \"unit\" }, singleThreaded = true)\npublic class ParseNodeFromJsonTest {\n\n   private ParseJson<Node> handler;\n\n   @BeforeTest\n   protected void setUpInjector() throws IOException {\n      Injector injector = Guice.createInjector(new AbstractModule() {\n         @Override\n         protected void configure() {\n            bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefApiMetadata.DEFAULT_API_VERSION);\n         }\n      }, new ChefParserModule(), new GsonModule());\n\n      handler = injector.getInstance(Key.get(new TypeLiteral<ParseJson<Node>>() {\n      }));\n   }\n\n   public void test() {\n      Node node = Node.builder() //\n            .name(\"adrian-jcloudstest\") //\n            .normalAttribute(\"tomcat6\", new JsonBall(\"{\\\"ssl_port\\\":8433}\")) //\n            .runListElement(\"recipe[java]\") //\n            .environment(\"prod\") //\n            .build();\n\n      assertEquals(\n            handler.apply(HttpResponse.builder().statusCode(200).message(\"ok\")\n                  .payload(ParseCookbookVersionFromJsonTest.class.getResourceAsStream(\"/node.json\")).build()), node);\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/functions/ParseSandboxFromJsonTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\n\nimport org.jclouds.chef.ChefApiMetadata;\nimport org.jclouds.chef.config.ChefParserModule;\nimport org.jclouds.chef.domain.Sandbox;\nimport org.jclouds.date.DateService;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.rest.annotations.ApiVersion;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport com.google.inject.Key;\nimport com.google.inject.TypeLiteral;\n\n/**\n * Tests behavior of {@code ParseSandboxFromJson}\n */\n@Test(groups = { \"unit\" }, singleThreaded = true)\npublic class ParseSandboxFromJsonTest {\n\n   private ParseJson<Sandbox> handler;\n   private DateService dateService;\n\n   @BeforeTest\n   protected void setUpInjector() throws IOException {\n      Injector injector = Guice.createInjector(new AbstractModule() {\n         @Override\n         protected void configure() {\n            bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefApiMetadata.DEFAULT_API_VERSION);\n         }\n      }, new ChefParserModule(), new GsonModule());\n\n      handler = injector.getInstance(Key.get(new TypeLiteral<ParseJson<Sandbox>>() {\n      }));\n      dateService = injector.getInstance(DateService.class);\n   }\n\n   public void test() {\n      assertEquals(\n            handler.apply(HttpResponse.builder().statusCode(200).message(\"ok\")\n                  .payload(ParseSandboxFromJsonTest.class.getResourceAsStream(\"/sandbox.json\")).build()),\n            Sandbox.builder().rev(\"1-8c27b0ea4c2b7aaedbb44cfbdfcc11b2\").isCompleted(false)\n                  .createTime(dateService.iso8601SecondsDateParse(\"2010-07-07T03:36:00+00:00\"))\n                  .name(\"f9d6d9b72bae465890aae87969f98a9c\").guid(\"f9d6d9b72bae465890aae87969f98a9c\").build());\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/functions/ParseSearchDataBagItemFromJsonTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\n\nimport org.jclouds.chef.ChefApiMetadata;\nimport org.jclouds.chef.config.ChefParserModule;\nimport org.jclouds.chef.domain.DatabagItem;\nimport org.jclouds.chef.domain.SearchResult;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.rest.annotations.ApiVersion;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = { \"unit\" })\npublic class ParseSearchDataBagItemFromJsonTest {\n   private ParseSearchDatabagFromJson handler;\n\n   @BeforeTest\n   protected void setUpInjector() throws IOException {\n      Injector injector = Guice.createInjector(new AbstractModule() {\n         @Override\n         protected void configure() {\n            bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefApiMetadata.DEFAULT_API_VERSION);\n         }\n      }, new ChefParserModule(), new GsonModule());\n\n      handler = injector.getInstance(ParseSearchDatabagFromJson.class);\n   }\n\n   public void test1() {\n      String itemJson = \"{\\\"my_key\\\":\\\"my_data\\\"}\";\n      String searchJson = \"{\\\"rows\\\":[{\\\"raw_data\\\": {\\\"id\\\":\\\"item1\\\",\\\"my_key\\\":\\\"my_data\\\"}}]}\";\n      DatabagItem item = new DatabagItem(\"item1\", itemJson);\n      SearchResult<DatabagItem> result = handler.apply(HttpResponse.builder().statusCode(200).message(\"ok\")\n            .payload(searchJson).build());\n      assertEquals(result.size(), 1);\n      assertEquals(result.iterator().next(), item);\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/functions/ParseUploadSandboxFromJsonTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.functions;\n\nimport static com.google.common.io.BaseEncoding.base16;\nimport static com.google.common.primitives.Bytes.asList;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.net.URI;\n\nimport org.jclouds.chef.ChefApiMetadata;\nimport org.jclouds.chef.config.ChefParserModule;\nimport org.jclouds.chef.domain.ChecksumStatus;\nimport org.jclouds.chef.domain.UploadSandbox;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.rest.annotations.ApiVersion;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport com.google.inject.Key;\nimport com.google.inject.TypeLiteral;\n\n/**\n * Tests behavior of {@code ParseUploadSiteFromJson}\n */\n@Test(groups = { \"unit\" }, singleThreaded = true)\npublic class ParseUploadSandboxFromJsonTest {\n\n   private ParseJson<UploadSandbox> handler;\n   private Injector injector;\n\n   @BeforeTest\n   protected void setUpInjector() throws IOException {\n      injector = Guice.createInjector(new AbstractModule() {\n         @Override\n         protected void configure() {\n            bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefApiMetadata.DEFAULT_API_VERSION);\n         }\n      }, new ChefParserModule(), new GsonModule());\n\n      handler = injector.getInstance(Key.get(new TypeLiteral<ParseJson<UploadSandbox>>() {\n      }));\n   }\n\n   public void test() {\n      assertEquals(\n            handler.apply(HttpResponse.builder().statusCode(200).message(\"ok\")\n                  .payload(ParseUploadSandboxFromJsonTest.class.getResourceAsStream(\"/upload-site.json\")).build()),\n            UploadSandbox\n                  .builder()\n                  .uri(URI\n                        .create(\"https://api.opscode.com/organizations/jclouds/sandboxes/d454f71e2a5f400c808d0c5d04c2c88c\"))\n                  .checksum(\n                        asList(base16().lowerCase().decode(\"0c5ecd7788cf4f6c7de2a57193897a6c\")),\n                        ChecksumStatus\n                              .builder()\n                              .url(URI\n                                    .create(\"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/sandbox-d454f71e2a5f400c808d0c5d04c2c88c/checksum-0c5ecd7788cf4f6c7de2a57193897a6c?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277344702&Signature=FtKyqvYEjhhEKmRY%2B0M8aGPMM7g%3D\"))\n                              .needsUpload(true).build())\n                  .checksum(asList(base16().lowerCase().decode(\"0189e76ccc476701d6b374e5a1a27347\")),\n                        ChecksumStatus.builder().build())\n                  .checksum(asList(base16().lowerCase().decode(\"1dda05ed139664f1f89b9dec482b77c0\")),\n                        ChecksumStatus.builder().build()).sandboxId(\"d454f71e2a5f400c808d0c5d04c2c88c\").build()\n\n      );\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/functions/UriForResourceTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\n\nimport org.jclouds.chef.domain.Resource;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\n\n/**\n * Tests behavior of {@code UriForResource}\n */\n@Test(groups = { \"unit\" })\npublic class UriForResourceTest {\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testWithNullInput() {\n      Function<Object, URI> function = new UriForResource();\n      function.apply(null);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testWithInvalidInput() {\n      Function<Object, URI> function = new UriForResource();\n      function.apply(new Object());\n   }\n\n   @Test\n   public void testWithValidResource() {\n      Function<Object, URI> function = new UriForResource();\n      Resource res = Resource.builder().name(\"test\").url(URI.create(\"http://foo/bar\")).build();\n      URI result = function.apply(res);\n      assertEquals(res.getUrl().toString(), result.toString());\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/handlers/ChefApiErrorRetryHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.handlers;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\n\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.handlers.BackoffLimitedRetryHandler;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code ChefClientErrorRetryHandler}\n */\n@Test(groups = { \"unit\" })\npublic class ChefApiErrorRetryHandlerTest {\n   @Test\n   public void test401DoesNotRetry() {\n\n      HttpCommand command = createMock(HttpCommand.class);\n      HttpResponse response = createMock(HttpResponse.class);\n      BackoffLimitedRetryHandler retry = createMock(BackoffLimitedRetryHandler.class);\n\n      expect(command.getFailureCount()).andReturn(0);\n      expect(response.getStatusCode()).andReturn(401).atLeastOnce();\n\n      replay(response);\n      replay(retry);\n      replay(command);\n\n      ChefApiErrorRetryHandler handler = new ChefApiErrorRetryHandler(retry);\n\n      assert !handler.shouldRetryRequest(command, response);\n\n      verify(retry);\n      verify(command);\n      verify(response);\n\n   }\n\n   @Test\n   public void test400DoesNotRetry() {\n\n      HttpCommand command = createMock(HttpCommand.class);\n      HttpResponse response = createMock(HttpResponse.class);\n      BackoffLimitedRetryHandler retry = createMock(BackoffLimitedRetryHandler.class);\n\n      expect(command.getFailureCount()).andReturn(0);\n      expect(response.getStatusCode()).andReturn(401).atLeastOnce();\n\n      replay(response);\n      replay(retry);\n      replay(command);\n\n      ChefApiErrorRetryHandler handler = new ChefApiErrorRetryHandler(retry);\n\n      assert !handler.shouldRetryRequest(command, response);\n\n      verify(retry);\n      verify(command);\n      verify(response);\n\n   }\n\n   @Test\n   public void testRetryOn400PutSandbox() {\n\n      HttpCommand command = createMock(HttpCommand.class);\n      BackoffLimitedRetryHandler retry = createMock(BackoffLimitedRetryHandler.class);\n\n      HttpRequest request = HttpRequest.builder().method(\"PUT\")\n            .endpoint(\"https://api.opscode.com/organizations/jclouds/sandboxes/bfd68d4052f44053b2e593a33b5e1cd5\")\n            .build();\n      HttpResponse response = HttpResponse\n            .builder()\n            .statusCode(400)\n            .message(\"400 Bad Request\")\n            .payload(\n                  \"{\\\"error\\\":[\\\"Cannot update sandbox bfd68d4052f44053b2e593a33b5e1cd5: checksum 9b7c23369f4b576451216c39f214af6c was not uploaded\\\"]}\")\n            .build();\n\n      expect(command.getFailureCount()).andReturn(0);\n      expect(command.getCurrentRequest()).andReturn(request).atLeastOnce();\n      expect(retry.shouldRetryRequest(command, response)).andReturn(true);\n\n      replay(retry);\n      replay(command);\n\n      ChefApiErrorRetryHandler handler = new ChefApiErrorRetryHandler(retry);\n\n      assert handler.shouldRetryRequest(command, response);\n\n      verify(retry);\n      verify(command);\n\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/internal/BaseChefLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.internal;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Properties;\n\nimport org.jclouds.apis.BaseApiLiveTest;\nimport org.jclouds.chef.ChefApi;\nimport org.jclouds.chef.ChefService;\nimport org.jclouds.json.Json;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.base.Throwables;\nimport com.google.common.io.Files;\nimport com.google.inject.Injector;\nimport com.google.inject.Module;\n\n@Test(groups = \"live\")\npublic abstract class BaseChefLiveTest extends BaseApiLiveTest<ChefApi> {\n\n   protected Injector injector;\n   protected ChefService chefService;\n   protected Json json;\n\n   protected BaseChefLiveTest() {\n      provider = \"chef\";\n   }\n\n   /**\n    * the credential is a path to the pem file.\n    */\n   @Override\n   protected Properties setupProperties() {\n      Properties overrides = super.setupProperties();\n      credential = setCredentialFromPemFile(overrides, identity, provider + \".credential\");\n      return overrides;\n   }\n\n   @Override\n   protected void initialize() {\n      super.initialize();\n      chefService = injector.getInstance(ChefService.class);\n      json = injector.getInstance(Json.class);\n   }\n\n   @Override\n   protected ChefApi create(Properties props, Iterable<Module> modules) {\n      injector = newBuilder().modules(modules).overrides(props).buildInjector();\n      return injector.getInstance(ChefApi.class);\n   }\n\n   protected String setCredentialFromPemFile(Properties overrides, String identity, String key) {\n      String val = null;\n      String credentialFromFile = null;\n      if (System.getProperties().containsKey(\"test.\" + key)) {\n         val = System.getProperty(\"test.\" + key);\n      } else {\n         val = System.getProperty(\"user.home\") + \"/.chef/\" + identity + \".pem\";\n      }\n      try {\n         credentialFromFile = Files.toString(new File(val), Charsets.UTF_8);\n      } catch (IOException e) {\n         throw Throwables.propagate(e);\n      }\n      overrides.setProperty(key, credentialFromFile);\n      return credentialFromFile;\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/internal/BaseChefServiceTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.internal;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.List;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.chef.ChefApiMetadata;\nimport org.jclouds.chef.domain.BootstrapConfig;\nimport org.jclouds.chef.filters.SignedHeaderAuthTest;\nimport org.jclouds.chef.util.RunListBuilder;\nimport org.jclouds.domain.JsonBall;\nimport org.jclouds.logging.config.NullLoggingModule;\nimport org.jclouds.rest.internal.BaseRestApiTest.MockModule;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Injector;\nimport com.google.inject.Module;\n\n/**\n * Unit tests for the <code>BaseChefService</code> class.\n */\n@Test(groups = \"unit\", testName = \"BaseChefServiceTest\")\npublic class BaseChefServiceTest {\n\n   private BaseChefService chefService;\n\n   @BeforeClass\n   public void setup() {\n      Injector injector = ContextBuilder.newBuilder(new ChefApiMetadata())\n            .credentials(SignedHeaderAuthTest.USER_ID, SignedHeaderAuthTest.PRIVATE_KEY)\n            .modules(ImmutableSet.<Module> of(new MockModule(), new NullLoggingModule())).buildInjector();\n\n      chefService = injector.getInstance(BaseChefService.class);\n   }\n\n   public void testBuildBootstrapConfigurationWithEmptyRunlist() {\n      BootstrapConfig bootstrapConfig = BootstrapConfig.builder().runList(ImmutableList.<String> of()).build();\n      String config = chefService.buildBootstrapConfiguration(bootstrapConfig);\n      assertEquals(config, \"{\\\"run_list\\\":[]}\");\n   }\n\n   public void testBuildBootstrapConfigurationWithRunlist() {\n      List<String> runlist = new RunListBuilder().addRecipe(\"apache2\").addRole(\"webserver\").build();\n      BootstrapConfig bootstrapConfig = BootstrapConfig.builder().runList(runlist).build();\n      String config = chefService.buildBootstrapConfiguration(bootstrapConfig);\n      assertEquals(config, \"{\\\"run_list\\\":[\\\"recipe[apache2]\\\",\\\"role[webserver]\\\"]}\");\n   }\n\n   public void testBuildBootstrapConfigurationWithRunlistAndEmptyAttributes() {\n      List<String> runlist = new RunListBuilder().addRecipe(\"apache2\").addRole(\"webserver\").build();\n      BootstrapConfig bootstrapConfig = BootstrapConfig.builder().runList(runlist).attributes(new JsonBall(\"{}\"))\n            .build();\n      String config = chefService.buildBootstrapConfiguration(bootstrapConfig);\n      assertEquals(config, \"{\\\"run_list\\\":[\\\"recipe[apache2]\\\",\\\"role[webserver]\\\"],\\\"attributes\\\":{}}\");\n   }\n\n   public void testBuildBootstrapConfigurationWithRunlistAndAttributes() {\n      List<String> runlist = new RunListBuilder().addRecipe(\"apache2\").addRole(\"webserver\").build();\n      BootstrapConfig bootstrapConfig = BootstrapConfig.builder().runList(runlist)\n            .attributes(new JsonBall(\"{\\\"tomcat6\\\":{\\\"ssl_port\\\":8433}}\")).build();\n      String config = chefService.buildBootstrapConfiguration(bootstrapConfig);\n      assertEquals(config,\n            \"{\\\"run_list\\\":[\\\"recipe[apache2]\\\",\\\"role[webserver]\\\"],\\\"attributes\\\":{\\\"tomcat6\\\":{\\\"ssl_port\\\":8433}}}\");\n   }\n\n   public void testBuildBootstrapConfigurationWithRunlistAndAttributesAndEnvironment() {\n      List<String> runlist = new RunListBuilder().addRecipe(\"apache2\").addRole(\"webserver\").build();\n      BootstrapConfig bootstrapConfig = BootstrapConfig.builder().runList(runlist)\n            .attributes(new JsonBall(\"{\\\"tomcat6\\\":{\\\"ssl_port\\\":8433}}\")).environment(\"env\").build();\n      String config = chefService.buildBootstrapConfiguration(bootstrapConfig);\n      assertEquals(config, \"{\\\"run_list\\\":[\\\"recipe[apache2]\\\",\\\"role[webserver]\\\"],\\\"environment\\\":\\\"env\\\",\"\n            + \"\\\"attributes\\\":{\\\"tomcat6\\\":{\\\"ssl_port\\\":8433}}}\");\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/strategy/internal/CleanupStaleNodesAndClientsImplLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.strategy.internal;\n\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\n\nimport org.jclouds.chef.internal.BaseChefLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code CleanupStaleNodesAndClientsImpl} strategies\n */\n@Test(groups = \"live\", testName = \"CleanupStaleNodesAndClientsImplLiveTest\")\npublic class CleanupStaleNodesAndClientsImplLiveTest extends BaseChefLiveTest {\n\n   private CreateNodeAndPopulateAutomaticAttributesImpl creator;\n   private CleanupStaleNodesAndClientsImpl strategy;\n\n   @Override\n   protected void initialize() {\n      super.initialize();\n      this.prefix = this.prefix + \"-\" + this.hashCode();\n      this.creator = injector.getInstance(CreateNodeAndPopulateAutomaticAttributesImpl.class);\n      this.strategy = injector.getInstance(CleanupStaleNodesAndClientsImpl.class);\n   }\n\n   @Test\n   public void testExecute() throws InterruptedException {\n      try {\n         creator.execute(prefix, ImmutableSet.<String> of());\n         // http://tickets.corp.opscode.com/browse/PL-522\n         // assert chef.nodeExists(prefix);\n         assertNotNull(api.getNode(prefix));\n         strategy.execute(prefix, 10);\n         assertNotNull(api.getNode(prefix));\n         Thread.sleep(1000);\n         strategy.execute(prefix, 1);\n         assertNull(api.getNode(prefix));\n      } finally {\n         api.deleteNode(prefix);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/strategy/internal/CreateNodeAndPopulateAutomaticAttributesImplLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.strategy.internal;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Set;\n\nimport org.jclouds.chef.domain.Node;\nimport org.jclouds.chef.internal.BaseChefLiveTest;\nimport org.jclouds.ohai.config.OhaiModule.CurrentUserProvider;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code CreateNodeAndPopulateAutomaticAttributesImpl}\n * strategies\n */\n@Test(groups = \"live\", testName = \"CreateNodeAndPopulateAutomaticAttributesImplLiveTest\")\npublic class CreateNodeAndPopulateAutomaticAttributesImplLiveTest extends BaseChefLiveTest {\n\n   private CurrentUserProvider currentUserProvider;\n   private CreateNodeAndPopulateAutomaticAttributesImpl strategy;\n\n   @Override\n   protected void initialize() {\n      super.initialize();\n      this.prefix = this.prefix + \"-\" + this.hashCode();\n      this.currentUserProvider = injector.getInstance(CurrentUserProvider.class);\n      this.strategy = injector.getInstance(CreateNodeAndPopulateAutomaticAttributesImpl.class);\n   }\n\n   @Test\n   public void testExecute() {\n      Set<String> runList = ImmutableSet.of(\"role[\" + prefix + \"]\");\n      try {\n         strategy.execute(prefix, runList);\n         Node node = api.getNode(prefix);\n         assertEquals(node.getName(), prefix);\n         assertEquals(node.getRunList(), runList);\n         assertEquals(node.getAutomaticAttributes().get(\"current_user\").toString(), currentUserProvider.get().toString());\n      } finally {\n         api.deleteNode(prefix);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/strategy/internal/CreateNodeAndPopulateAutomaticAttributesImplTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.strategy.internal;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\n\nimport java.util.Map;\n\nimport org.jclouds.chef.ChefApi;\nimport org.jclouds.chef.domain.Node;\nimport org.jclouds.domain.JsonBall;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code CreateNodeAndPopulateAutomaticAttributesImpl}\n */\n@Test(groups = \"unit\", testName = \"CreateNodeAndPopulateAutomaticAttributesImplTest\")\npublic class CreateNodeAndPopulateAutomaticAttributesImplTest {\n\n   @Test\n   public void testWithNoRunlist() {\n      ChefApi chef = createMock(ChefApi.class);\n\n      Supplier<Map<String, JsonBall>> automaticSupplier = Suppliers.<Map<String, JsonBall>> ofInstance(ImmutableMap.<String, JsonBall> of());\n\n      Node nodeWithAutomatic = Node.builder().name(\"name\").environment(\"_default\")\n            .automaticAttributes(automaticSupplier.get()).build();\n\n      chef.createNode(nodeWithAutomatic);\n\n      replay(chef);\n\n      CreateNodeAndPopulateAutomaticAttributesImpl updater = new CreateNodeAndPopulateAutomaticAttributesImpl(chef,\n            automaticSupplier);\n\n      updater.execute(\"name\", ImmutableSet.<String> of());\n      verify(chef);\n\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/strategy/internal/DeleteAllApisAndNodesInListImplLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.strategy.internal;\n\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\n\nimport org.jclouds.chef.internal.BaseChefLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code DeleteAllApisAndNodesInListImpl} strategies\n */\n@Test(groups = \"live\", testName = \"DeleteAllApisAndNodesInListImplLiveTest\")\npublic class DeleteAllApisAndNodesInListImplLiveTest extends BaseChefLiveTest {\n\n   private DeleteAllNodesInListImpl strategy;\n   private CreateNodeAndPopulateAutomaticAttributesImpl creator;\n\n   @Override\n   protected void initialize() {\n      super.initialize();\n      this.prefix = this.prefix + \"-\" + this.hashCode();\n      this.creator = injector.getInstance(CreateNodeAndPopulateAutomaticAttributesImpl.class);\n      this.strategy = injector.getInstance(DeleteAllNodesInListImpl.class);\n   }\n\n   @Test\n   public void testExecute() throws InterruptedException {\n      try {\n         creator.execute(prefix, ImmutableSet.<String> of());\n         creator.execute(prefix + 1, ImmutableSet.<String> of());\n\n         // http://tickets.corp.opscode.com/browse/PL-522\n         // assert api.nodeExists(prefix);\n         assertNotNull(api.getNode(prefix));\n         assertNotNull(api.getNode(prefix + 1));\n\n         strategy.execute(ImmutableSet.of(prefix, prefix + 1));\n         assertNull(api.getNode(prefix));\n         assertNull(api.getNode(prefix + 1));\n      } finally {\n         api.deleteNode(prefix);\n         api.deleteNode(prefix + 1);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/strategy/internal/ListCookbookVersionsInEnvironmentImplLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.strategy.internal;\n\nimport static com.google.common.collect.Iterables.size;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.Assert.fail;\n\nimport java.io.File;\nimport java.util.List;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\n\nimport org.jclouds.chef.domain.ChecksumStatus;\nimport org.jclouds.chef.domain.CookbookVersion;\nimport org.jclouds.chef.domain.Metadata;\nimport org.jclouds.chef.domain.Resource;\nimport org.jclouds.chef.domain.Sandbox;\nimport org.jclouds.chef.domain.UploadSandbox;\nimport org.jclouds.chef.internal.BaseChefLiveTest;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.io.payloads.FilePayload;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.hash.Hashing;\nimport com.google.common.io.Files;\nimport com.google.common.primitives.Bytes;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.common.util.concurrent.MoreExecutors;\n\n/**\n * Tests behavior of {@code ListCookbookVersionsInEnvironmentImpl} strategies\n */\n@Test(groups = \"live\", testName = \"ListCookbookVersionsInEnvironmentImplLiveTest\")\npublic class ListCookbookVersionsInEnvironmentImplLiveTest extends BaseChefLiveTest {\n   public static final String PREFIX = \"jcloudstest-strategy-\" + System.getProperty(\"user.name\");\n\n   private ListCookbookVersionsInEnvironmentImpl strategy;\n   private ExecutorService testExecutorService;\n   private ListeningExecutorService testListeningExecutorService;\n\n   @Override\n   protected void initialize() {\n      super.initialize();\n\n      try {\n         createCookbooksWithMultipleVersions(PREFIX);\n         createCookbooksWithMultipleVersions(PREFIX + 1);\n      } catch (Exception e) {\n         fail(\"Could not create cookbooks\", e);\n      }\n\n      this.strategy = injector.getInstance(ListCookbookVersionsInEnvironmentImpl.class);\n      this.testExecutorService = Executors.newFixedThreadPool(5);\n      this.testListeningExecutorService = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(5));\n   }\n\n   @AfterClass(groups = { \"integration\", \"live\" })\n   @Override\n   protected void tearDown() {\n      api.deleteCookbook(PREFIX, \"0.0.0\");\n      api.deleteCookbook(PREFIX, \"1.0.0\");\n      api.deleteCookbook(PREFIX + 1, \"0.0.0\");\n      api.deleteCookbook(PREFIX + 1, \"1.0.0\");\n\n      this.testExecutorService.shutdown();\n      this.testListeningExecutorService.shutdown();\n\n      super.tearDown();\n   }\n\n   @Test\n   public void testExecute() {\n      assertTrue(size(strategy.execute(\"_default\")) > 0, \"Expected one or more elements\");\n   }\n\n   @Test\n   public void testExecuteConcurrentlyWithExecutorService() {\n      assertTrue(size(strategy.execute(testExecutorService, \"_default\")) > 0,\n            \"Expected one or more elements\");\n   }\n\n   @Test\n   public void testExecuteConcurrentlyWithListeningExecutorService() {\n      assertTrue(size(strategy.execute(testListeningExecutorService, \"_default\")) > 0,\n            \"Expected one or more elements\");\n   }\n\n   @Test\n   public void testExecuteWithNumVersions() {\n      assertTrue(size(strategy.execute(\"_default\", \"2\")) > 0, \"Expected one or more elements\");\n   }\n\n   @Test\n   public void testExecuteConcurrentlyWithNumVersionsAndExecutorService() {\n      assertTrue(size(strategy.execute(testExecutorService, \"_default\", \"2\")) > 0,\n            \"Expected one or more elements\");\n   }\n\n   @Test\n   public void testExecuteConcurrentlyWithNumVersionsAndListeningExecutorService() {\n      assertTrue(size(strategy.execute(testListeningExecutorService, \"_default\", \"2\")) > 0,\n            \"Expected one or more elements\");\n   }\n\n   @Test\n   public void testExecuteWithNumVersionsAll() {\n      assertTrue(size(strategy.execute(\"_default\", \"all\")) > 0, \"Expected one or more elements\");\n   }\n\n   @Test\n   public void testExecuteConcurrentlyWithNumVersionsAllAndExecutorService() {\n      assertTrue(size(strategy.execute(testExecutorService, \"_default\", \"all\")) > 0,\n            \"Expected one or more elements\");\n   }\n\n   @Test\n   public void testExecuteConcurrentlyWithNumVersionsAllAndListeningExecutorService() {\n      assertTrue(size(strategy.execute(testListeningExecutorService, \"_default\", \"all\")) > 0,\n            \"Expected one or more elements\");\n   }\n\n   private FilePayload uploadContent(String fileName) throws Exception {\n      // Define the file you want in the cookbook\n      File file = new File(System.getProperty(\"user.dir\"), fileName);\n      FilePayload content = Payloads.newFilePayload(file);\n      content.getContentMetadata().setContentType(\"application/x-binary\");\n\n      // Get an md5 so that you can see if the server already has it or not\n      content.getContentMetadata().setContentMD5(Files.asByteSource(file).hash(Hashing.md5()).asBytes());\n\n      // Note that java collections cannot effectively do equals or hashcodes on\n      // byte arrays, so let's convert to a list of bytes.\n      List<Byte> md5 = Bytes.asList(content.getContentMetadata().getContentMD5());\n\n      // Request an upload site for this file\n      UploadSandbox site = api.createUploadSandboxForChecksums(ImmutableSet.of(md5));\n      assertTrue(site.getChecksums().containsKey(md5), md5 + \" not in \" + site.getChecksums());\n\n      try {\n         // Upload the file contents, if still not uploaded\n         ChecksumStatus status = site.getChecksums().get(md5);\n         if (status.needsUpload()) {\n            api.uploadContent(status.getUrl(), content);\n         }\n         Sandbox sandbox = api.commitSandbox(site.getSandboxId(), true);\n         assertTrue(sandbox.isCompleted(), \"Sandbox should be completed after uploading\");\n      } catch (RuntimeException e) {\n         api.commitSandbox(site.getSandboxId(), false);\n         fail(\"Could not upload content\", e);\n      }\n\n      return content;\n   }\n\n   private void createCookbooksWithMultipleVersions(String cookbookName) throws Exception {\n      FilePayload v0content = uploadContent(\"pom.xml\");\n      FilePayload v1content = uploadContent(\"../../README.md\");\n\n      // Create the metadata of the cookbook\n      Metadata metadata = Metadata.builder() //\n            .name(cookbookName) //\n            .version(\"0.0.0\") //\n            .description(\"Jclouds test uploaded cookbook\") //\n            .maintainer(\"jclouds\") //\n            .maintainerEmail(\"someone@jclouds.org\") //\n            .license(\"Apache 2.0\") //\n            .build();\n\n      // Create new cookbook version\n      CookbookVersion cookbook = CookbookVersion.builder(cookbookName, \"0.0.0\") //\n            .metadata(metadata) //\n            .rootFile(Resource.builder().fromPayload(v0content).build()) //\n            .build();\n\n      // upload the cookbook to the remote server\n      api.updateCookbook(cookbookName, \"0.0.0\", cookbook);\n\n      // Create the metadata of the cookbook\n      metadata = Metadata.builder() //\n            .name(cookbookName) //\n            .version(\"1.0.0\") //\n            .description(\"Jclouds test uploaded cookbook\") //\n            .maintainer(\"jclouds\") //\n            .maintainerEmail(\"someone@jclouds.org\") //\n            .license(\"Apache 2.0\") //\n            .build();\n\n      // Create a new cookbook version\n      cookbook = CookbookVersion.builder(cookbookName, \"1.0.0\") //\n            .metadata(metadata) //\n            .rootFile(Resource.builder().fromPayload(v1content).build()) //\n            .build();\n\n      // upload the cookbook to the remote server\n      api.updateCookbook(cookbookName, \"1.0.0\", cookbook);\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/strategy/internal/ListNodesImplLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.strategy.internal;\n\nimport static com.google.common.collect.Iterables.size;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\n\nimport org.jclouds.chef.internal.BaseChefLiveTest;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.common.util.concurrent.MoreExecutors;\n\n/**\n * Tests behavior of {@code ListNodesImpl} strategies\n */\n@Test(groups = \"live\", testName = \"ListNodesImplLiveTest\")\npublic class ListNodesImplLiveTest extends BaseChefLiveTest {\n\n   private ListNodesImpl strategy;\n   private CreateNodeAndPopulateAutomaticAttributesImpl creator;\n\n   private ExecutorService testExecutorService;\n   private ListeningExecutorService testListeningExecutorService;\n\n   @Override\n   protected void initialize() {\n      super.initialize();\n      this.creator = injector.getInstance(CreateNodeAndPopulateAutomaticAttributesImpl.class);\n      this.strategy = injector.getInstance(ListNodesImpl.class);\n      creator.execute(prefix, ImmutableSet.<String> of());\n      creator.execute(prefix + 1, ImmutableSet.<String> of());\n\n      this.testExecutorService = Executors.newFixedThreadPool(5);\n      this.testListeningExecutorService = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(5));\n   }\n\n   @AfterClass(groups = { \"integration\", \"live\" })\n   @Override\n   protected void tearDown() {\n      api.deleteNode(prefix);\n      api.deleteNode(prefix + 1);\n\n      this.testExecutorService.shutdown();\n      this.testListeningExecutorService.shutdown();\n\n      super.tearDown();\n   }\n\n   @Test\n   public void testExecute() {\n      assertTrue(size(strategy.execute()) > 0, \"Expected one or more elements\");\n   }\n\n   public void testExecuteConcurrentlyWithExecutorService() {\n      assertTrue(size(strategy.execute(testExecutorService)) > 0, \"Expected one or more elements\");\n   }\n\n   public void testExecuteConcurrentlyWithListeningExecutorService() {\n      assertTrue(size(strategy.execute(testListeningExecutorService)) > 0, \"Expected one or more elements\");\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/strategy/internal/ListNodesInEnvironmentImplLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.strategy.internal;\n\nimport static com.google.common.collect.Iterables.size;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\n\nimport org.jclouds.chef.internal.BaseChefLiveTest;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.common.util.concurrent.MoreExecutors;\n\n/**\n * Tests behavior of {@code ListNodesInEnvironmentImpl} strategies\n */\n@Test(groups = \"live\", testName = \"ListNodesInEnvironmentImplLiveTest\")\npublic class ListNodesInEnvironmentImplLiveTest extends BaseChefLiveTest {\n\n   private ListNodesInEnvironmentImpl strategy;\n   private CreateNodeAndPopulateAutomaticAttributesImpl creator;\n\n   private ExecutorService testExecutorService;\n   private ListeningExecutorService testListeningExecutorService;\n\n   @Override\n   protected void initialize() {\n      super.initialize();\n      this.prefix = this.prefix + \"-\" + this.hashCode();\n      this.creator = injector.getInstance(CreateNodeAndPopulateAutomaticAttributesImpl.class);\n      this.strategy = injector.getInstance(ListNodesInEnvironmentImpl.class);\n      creator.execute(prefix, ImmutableSet.<String>of());\n      creator.execute(prefix + 1, ImmutableSet.<String>of());\n\n      this.testExecutorService = Executors.newFixedThreadPool(5);\n      this.testListeningExecutorService = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(5));\n   }\n\n   @AfterClass(groups = { \"integration\", \"live\" })\n   @Override\n   protected void tearDown() {\n      api.deleteNode(prefix);\n      api.deleteNode(prefix + 1);\n\n      this.testExecutorService.shutdown();\n      this.testListeningExecutorService.shutdown();\n\n      super.tearDown();\n   }\n\n   @Test\n   public void testExecute() {\n      assertTrue(size(strategy.execute(\"_default\")) > 0, \"Expected one or more elements\");\n   }\n\n   @Test\n   public void testExecuteConcurrentlyWithExecutorService() {\n      assertTrue(size(strategy.execute(testExecutorService, \"_default\")) > 0,\n            \"Expected one or more elements\");\n   }\n\n   @Test\n   public void testExecuteConcurrentlyWithListeningExecutorService() {\n      assertTrue(size(strategy.execute(testListeningExecutorService, \"_default\")) > 0,\n            \"Expected one or more elements\");\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/strategy/internal/UpdateAutomaticAttributesOnNodeImplLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.strategy.internal;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Set;\n\nimport org.jclouds.chef.domain.Node;\nimport org.jclouds.chef.internal.BaseChefLiveTest;\nimport org.jclouds.ohai.config.OhaiModule.CurrentUserProvider;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code UpdateAutomaticAttributesOnNodeImpl} strategies\n */\n@Test(groups = \"live\", testName = \"UpdateAutomaticAttributesOnNodeImplLiveTest\")\npublic class UpdateAutomaticAttributesOnNodeImplLiveTest extends BaseChefLiveTest {\n\n   private CurrentUserProvider currentUserProvider;\n   private UpdateAutomaticAttributesOnNodeImpl strategy;\n\n   @Override\n   protected void initialize() {\n      super.initialize();\n      this.prefix = this.prefix + \"-\" + this.hashCode();\n      this.currentUserProvider = injector.getInstance(CurrentUserProvider.class);\n      this.strategy = injector.getInstance(UpdateAutomaticAttributesOnNodeImpl.class);\n   }\n\n   @Test\n   public void testExecute() {\n      Set<String> runList = ImmutableSet.of(\"role[\" + prefix + \"]\");\n      try {\n         api.createNode(Node.builder().name(prefix).runList(runList).environment(\"_default\").build());\n         strategy.execute(prefix);\n         Node node = api.getNode(prefix);\n         assertEquals(node.getName(), prefix);\n         assertEquals(node.getRunList(), runList);\n         assertEquals(node.getAutomaticAttributes().get(\"current_user\").toString(), currentUserProvider.get().toString());\n      } finally {\n         api.deleteNode(prefix);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/strategy/internal/UpdateAutomaticAttributesOnNodeImplTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.strategy.internal;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\n\nimport java.util.Map;\n\nimport org.jclouds.chef.ChefApi;\nimport org.jclouds.chef.domain.Node;\nimport org.jclouds.domain.JsonBall;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Tests behavior of {@code UpdateAutomaticAttributesOnNodeImpl}\n */\n@Test(groups = { \"unit\" })\npublic class UpdateAutomaticAttributesOnNodeImplTest {\n\n   @Test\n   public void test() {\n      ChefApi chef = createMock(ChefApi.class);\n\n      Map<String, JsonBall> automatic = ImmutableMap.<String, JsonBall> of();\n      Supplier<Map<String, JsonBall>> automaticSupplier = Suppliers.<Map<String, JsonBall>> ofInstance(automatic);\n\n      Node node = Node.builder().name(\"name\").environment(\"_default\").build();\n      Node nodeWithAutomatic = Node.builder().name(\"name\").environment(\"_default\").automaticAttributes(automatic)\n            .build();\n\n      expect(chef.getNode(\"name\")).andReturn(node);\n      expect(chef.updateNode(nodeWithAutomatic)).andReturn(null);\n\n      replay(chef);\n\n      UpdateAutomaticAttributesOnNodeImpl updater = new UpdateAutomaticAttributesOnNodeImpl(chef, automaticSupplier);\n\n      updater.execute(\"name\");\n      verify(chef);\n\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/suppliers/ChefVersionSupplierTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.suppliers;\n\nimport static org.jclouds.chef.suppliers.ChefVersionSupplier.FALLBACK_VERSION;\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\n/**\n * Unit tests for the {@link ChefVersionSupplier} class.\n */\n@Test(groups = \"unit\", testName = \"ChefVersionSupplierTest\")\npublic class ChefVersionSupplierTest {\n\n   public void testReturnsDefaultVersion() {\n      assertEquals(new ChefVersionSupplier(\"15\").get(), FALLBACK_VERSION);\n      assertEquals(new ChefVersionSupplier(\"0\").get(), FALLBACK_VERSION);\n      assertEquals(new ChefVersionSupplier(\"0.\").get(), FALLBACK_VERSION);\n   }\n\n   public void testReturnsMajorVersionIfNotZero() {\n      assertEquals(new ChefVersionSupplier(\"11.6\").get().intValue(), 11);\n      assertEquals(new ChefVersionSupplier(\"11.6.0\").get().intValue(), 11);\n      assertEquals(new ChefVersionSupplier(\"11.6.0.1\").get().intValue(), 11);\n   }\n\n   public void testReturnsMinorVersionIfMajorIsZero() {\n      assertEquals(new ChefVersionSupplier(\"0.9\").get().intValue(), 9);\n      assertEquals(new ChefVersionSupplier(\"0.9.8\").get().intValue(), 9);\n      assertEquals(new ChefVersionSupplier(\"0.9.8.2\").get().intValue(), 9);\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/util/ChefUtilsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.util;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Date;\nimport java.util.NoSuchElementException;\n\nimport org.jclouds.domain.JsonBall;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tests behavior of {@code ChefUtils}\n */\n@Test(groups = { \"unit\" }, singleThreaded = true)\npublic class ChefUtilsTest {\n   public static long millis = 1280251180727L;\n   public static String millisString = \"1280251180727\";\n   public static Date now = new Date(1280251180727L);\n\n   public void testToOhaiTime() {\n      assertEquals(ChefUtils.toOhaiTime(millis).toString(), millisString);\n   }\n\n   public void testFromOhaiTime() {\n      assertEquals(ChefUtils.fromOhaiTime(new JsonBall(millisString)), now);\n\n   }\n\n   @Test(expectedExceptions = NoSuchElementException.class)\n   public void testFindRoleInRunListThrowsNoSuchElementOnRecipe() {\n      ChefUtils.findRoleInRunList(ImmutableList.of(\"recipe[java]\"));\n   }\n\n   public void testFindRoleInRunList() {\n      assertEquals(ChefUtils.findRoleInRunList(ImmutableList.of(\"role[prod]\")), \"prod\");\n\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/chef/util/RunListBuilderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.chef.util;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tests possible uses of RunListBuilder\n */\npublic class RunListBuilderTest {\n\n   @Test\n   public void testRecipeAndRole() {\n      RunListBuilder options = new RunListBuilder();\n      options.addRecipe(\"recipe\").addRole(\"role\");\n      assertEquals(options.build(), ImmutableList.of(\"recipe[recipe]\", \"role[role]\"));\n   }\n\n   @Test\n   public void testRecipe() {\n      RunListBuilder options = new RunListBuilder();\n      options.addRecipe(\"test\");\n      assertEquals(options.build(), ImmutableList.of(\"recipe[test]\"));\n   }\n\n   @Test\n   public void testRecipes() {\n      RunListBuilder options = new RunListBuilder();\n      options.addRecipes(\"test\", \"test2\");\n      assertEquals(options.build(), ImmutableList.of(\"recipe[test]\", \"recipe[test2]\"));\n   }\n\n   @Test\n   public void testRole() {\n      RunListBuilder options = new RunListBuilder();\n      options.addRole(\"test\");\n      assertEquals(options.build(), ImmutableList.of(\"role[test]\"));\n   }\n\n   @Test\n   public void testRoles() {\n      RunListBuilder options = new RunListBuilder();\n      options.addRoles(\"test\", \"test2\");\n      assertEquals(options.build(), ImmutableList.of(\"role[test]\", \"role[test2]\"));\n   }\n\n   @Test\n   public void testNoneRecipe() {\n      RunListBuilder options = new RunListBuilder();\n      assertEquals(options.build(), ImmutableList.<String> of());\n   }\n\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/ohai/config/JMXTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ohai.config;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.testng.Assert.assertEquals;\n\nimport java.lang.management.RuntimeMXBean;\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.chef.ChefApiMetadata;\nimport org.jclouds.chef.config.ChefParserModule;\nimport org.jclouds.domain.JsonBall;\nimport org.jclouds.json.Json;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.ohai.Automatic;\nimport org.jclouds.rest.annotations.ApiVersion;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n/**\n * Tests behavior of {@code JMX}\n */\n@Test(groups = { \"unit\" })\npublic class JMXTest {\n\n   @Test\n   public void test() {\n\n      final RuntimeMXBean runtime = createMock(RuntimeMXBean.class);\n\n      expect(runtime.getUptime()).andReturn(69876000L);\n\n      replay(runtime);\n\n      Injector injector = Guice.createInjector(new AbstractModule() {\n         @Override\n         protected void configure() {\n            bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefApiMetadata.DEFAULT_API_VERSION);\n         }\n      }, new ChefParserModule(), new GsonModule(), new JMXOhaiModule() {\n         @Override\n         protected RuntimeMXBean provideRuntimeMXBean() {\n            return runtime;\n         }\n      });\n      Json json = injector.getInstance(Json.class);\n      Ohai ohai = injector.getInstance(Ohai.class);\n      assertEquals(json.toJson(ohai.ohai.get().get(\"uptime_seconds\")), \"69876\");\n   }\n\n   static class Ohai {\n      private Supplier<Map<String, JsonBall>> ohai;\n\n      @Inject\n      public Ohai(@Automatic Supplier<Map<String, JsonBall>> ohai) {\n         this.ohai = ohai;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/ohai/config/OhaiModuleTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ohai.config;\n\nimport static org.jclouds.chef.util.ChefUtils.ohaiAutomaticAttributeBinder;\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.SocketException;\nimport java.util.Map;\nimport java.util.Properties;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.chef.ChefApiMetadata;\nimport org.jclouds.chef.config.ChefParserModule;\nimport org.jclouds.domain.JsonBall;\nimport org.jclouds.json.Json;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.ohai.Automatic;\nimport org.jclouds.rest.annotations.ApiVersion;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.multibindings.MapBinder;\nimport com.google.inject.util.Providers;\n\n/**\n * Tests behavior of {@code OhaiModule}\n */\n@Test(groups = { \"unit\" })\npublic class OhaiModuleTest {\n\n   @Test\n   public void test() throws SocketException {\n\n      final Properties sysProperties = new Properties();\n\n      sysProperties.setProperty(\"os.name\", \"Mac OS X\");\n      sysProperties.setProperty(\"os.version\", \"10.3.0\");\n      sysProperties.setProperty(\"user.name\", \"user\");\n\n      Injector injector = Guice.createInjector(new AbstractModule() {\n         @Override\n         protected void configure() {\n            bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefApiMetadata.DEFAULT_API_VERSION);\n         }\n      }, new ChefParserModule(), new GsonModule(), new OhaiModule() {\n         @Override\n         protected Long millis() {\n            return 127999291932529L;\n         }\n\n         @Override\n         protected Properties systemProperties() {\n            return sysProperties;\n         }\n\n      });\n      Ohai ohai = injector.getInstance(Ohai.class);\n      Json json = injector.getInstance(Json.class);\n\n      assertEquals(\n            json.toJson(ohai.ohai.get(), new TypeLiteral<Map<String, JsonBall>>() {\n            }.getType()),\n            \"{\\\"ohai_time\\\":127999291932529,\\\"platform\\\":\\\"macosx\\\",\\\"platform_version\\\":\\\"10.3.0\\\",\\\"current_user\\\":\\\"user\\\",\\\"jvm\\\":{\\\"system\\\":{\\\"user.name\\\":\\\"user\\\",\\\"os.version\\\":\\\"10.3.0\\\",\\\"os.name\\\":\\\"Mac OS X\\\"}}}\");\n   }\n\n   public void test2modules() throws SocketException {\n\n      final Properties sysProperties = new Properties();\n\n      sysProperties.setProperty(\"os.name\", \"Mac OS X\");\n      sysProperties.setProperty(\"os.version\", \"10.3.0\");\n      sysProperties.setProperty(\"user.name\", \"user\");\n\n      Injector injector = Guice.createInjector(new AbstractModule() {\n         @Override\n         protected void configure() {\n            bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefApiMetadata.DEFAULT_API_VERSION);\n         }\n      }, new ChefParserModule(), new GsonModule(), new OhaiModule() {\n         @Override\n         protected Long millis() {\n            return 1279992919L;\n         }\n\n         @Override\n         protected Properties systemProperties() {\n            return sysProperties;\n         }\n\n      }, new AbstractModule() {\n\n         @Override\n         protected void configure() {\n            MapBinder<String, Supplier<JsonBall>> mapbinder = ohaiAutomaticAttributeBinder(binder());\n            mapbinder.addBinding(\"test\").toProvider(\n                  Providers.of(Suppliers.ofInstance(new JsonBall(\"{\\\"prop1\\\":\\\"test1\\\"}\"))));\n         }\n\n      }, new AbstractModule() {\n\n         @Override\n         protected void configure() {\n            MapBinder<String, Supplier<JsonBall>> mapbinder = ohaiAutomaticAttributeBinder(binder());\n            mapbinder.addBinding(\"test\").toProvider(\n                  Providers.of(Suppliers.ofInstance(new JsonBall(\"{\\\"prop2\\\":\\\"test2\\\"}\"))));\n         }\n\n      });\n      Ohai ohai = injector.getInstance(Ohai.class);\n      Json json = injector.getInstance(Json.class);\n\n      assertEquals(\n            json.toJson(ohai.ohai.get(), new TypeLiteral<Map<String, JsonBall>>() {\n            }.getType()),\n            \"{\\\"ohai_time\\\":1279992919,\\\"platform\\\":\\\"macosx\\\",\\\"platform_version\\\":\\\"10.3.0\\\",\\\"current_user\\\":\\\"user\\\",\\\"test\\\":{\\\"prop1\\\":\\\"test1\\\",\\\"prop2\\\":\\\"test2\\\"},\\\"jvm\\\":{\\\"system\\\":{\\\"user.name\\\":\\\"user\\\",\\\"os.version\\\":\\\"10.3.0\\\",\\\"os.name\\\":\\\"Mac OS X\\\"}}}\");\n   }\n\n   static class Ohai {\n      private Supplier<Map<String, JsonBall>> ohai;\n\n      @Inject\n      public Ohai(@Automatic Supplier<Map<String, JsonBall>> ohai) {\n         this.ohai = ohai;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/ohai/functions/ByteArrayToMacAddressTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ohai.functions;\n\nimport static com.google.common.io.BaseEncoding.base16;\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code ByteArrayToMacAddress}\n */\n@Test(groups = { \"unit\" }, singleThreaded = true)\npublic class ByteArrayToMacAddressTest {\n\n   public void test() {\n      assertEquals(new ByteArrayToMacAddress().apply(base16().lowerCase().decode(\"0026bb09e6c4\")), \"00:26:bb:09:e6:c4\");\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/test/java/org/jclouds/ohai/functions/NestSlashKeysTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ohai.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\n\nimport org.jclouds.chef.ChefApiMetadata;\nimport org.jclouds.chef.config.ChefParserModule;\nimport org.jclouds.domain.JsonBall;\nimport org.jclouds.json.Json;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.rest.annotations.ApiVersion;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableListMultimap;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n/**\n * Tests behavior of {@code NestSlashKeys}\n */\n@Test(groups = \"unit\", testName = \"NestSlashKeysTest\")\npublic class NestSlashKeysTest {\n\n   private NestSlashKeys converter;\n   private Json json;\n\n   @BeforeTest\n   protected void setUpInjector() throws IOException {\n      Injector injector = Guice.createInjector(new AbstractModule() {\n         @Override\n         protected void configure() {\n            bind(String.class).annotatedWith(ApiVersion.class).toInstance(ChefApiMetadata.DEFAULT_API_VERSION);\n         }\n      }, new ChefParserModule(), new GsonModule());\n      converter = injector.getInstance(NestSlashKeys.class);\n      json = injector.getInstance(Json.class);\n   }\n\n   @Test\n   public void testBase() {\n      assertEquals(\n            json.toJson(converter.apply(ImmutableListMultimap.<String, Supplier<JsonBall>> of(\"java\",\n                  Suppliers.ofInstance(new JsonBall(\"java\"))))), \"{\\\"java\\\":\\\"java\\\"}\");\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testIllegal() {\n      json.toJson(converter.apply(ImmutableListMultimap.<String, Supplier<JsonBall>> of(\"java\",\n            Suppliers.ofInstance(new JsonBall(\"java\")), \"java/system\", Suppliers.ofInstance(new JsonBall(\"system\")))));\n   }\n\n   @Test\n   public void testOne() {\n      assertEquals(\n            json.toJson(converter.apply(ImmutableListMultimap.<String, Supplier<JsonBall>> of(\"java\",\n                  Suppliers.ofInstance(new JsonBall(\"{\\\"time\\\":\\\"time\\\"}\")), \"java/system\",\n                  Suppliers.ofInstance(new JsonBall(\"system\"))))),\n            \"{\\\"java\\\":{\\\"time\\\":\\\"time\\\",\\\"system\\\":\\\"system\\\"}}\");\n   }\n\n   @Test\n   public void testOneDuplicate() {\n      assertEquals(\n            json.toJson(converter.apply(ImmutableListMultimap.<String, Supplier<JsonBall>> of(\"java\",\n                  Suppliers.ofInstance(new JsonBall(\"{\\\"time\\\":\\\"time\\\"}\")), \"java\",\n                  Suppliers.ofInstance(new JsonBall(\"{\\\"system\\\":\\\"system\\\"}\"))))),\n            \"{\\\"java\\\":{\\\"time\\\":\\\"time\\\",\\\"system\\\":\\\"system\\\"}}\");\n   }\n\n   @Test\n   public void testMerge() {\n      assertEquals(\n            json.toJson(converter.apply(ImmutableListMultimap.<String, Supplier<JsonBall>> of(\"java\",\n                  Suppliers.ofInstance(new JsonBall(\"{\\\"time\\\":{\\\"1\\\":\\\"hello\\\"}}\")), \"java/time\",\n                  Suppliers.ofInstance(new JsonBall(\"{\\\"2\\\":\\\"goodbye\\\"}\"))))),\n            \"{\\\"java\\\":{\\\"time\\\":{\\\"1\\\":\\\"hello\\\",\\\"2\\\":\\\"goodbye\\\"}}}\");\n   }\n\n   @Test\n   public void testMergeNestedTwice() {\n      assertEquals(\n            json.toJson(converter.apply(ImmutableListMultimap.<String, Supplier<JsonBall>> of(\"java\",\n                  Suppliers.ofInstance(new JsonBall(\"{\\\"time\\\":{\\\"1\\\":\\\"hello\\\"}}\")), \"java\",\n                  Suppliers.ofInstance(new JsonBall(\"{\\\"time\\\":{\\\"2\\\":\\\"goodbye\\\"}}\"))))),\n            \"{\\\"java\\\":{\\\"time\\\":{\\\"1\\\":\\\"hello\\\",\\\"2\\\":\\\"goodbye\\\"}}}\");\n   }\n\n   @Test\n   public void testReplaceList() {\n      assertEquals(\n            json.toJson(converter.apply(ImmutableListMultimap.<String, Supplier<JsonBall>> of(\"java\",\n                  Suppliers.ofInstance(new JsonBall(\"{\\\"time\\\":{\\\"1\\\":[\\\"hello\\\"]}}\")), \"java/time\",\n                  Suppliers.ofInstance(new JsonBall(\"{\\\"1\\\":[\\\"goodbye\\\"]}\"))))),\n            \"{\\\"java\\\":{\\\"time\\\":{\\\"1\\\":[\\\"goodbye\\\"]}}}\");\n   }\n}\n"
  },
  {
    "path": "apis/chef/src/test/resources/apache-chef-demo-cookbook.json",
    "content": "{\n    \"definitions\": [],\n    \"name\": \"apache-chef-demo-0.0.0\",\n    \"attributes\": [],\n    \"files\": [],\n    \"json_class\": \"Chef::CookbookVersion\",\n    \"providers\": [],\n    \"metadata\": {\n        \"dependencies\": {},\n        \"name\": \"apache-chef-demo\",\n        \"maintainer_email\": \"youremail@example.com\",\n        \"attributes\": {},\n        \"license\": \"Apache v2.0\",\n        \"maintainer\": \"Your Name\",\n        \"suggestions\": {},\n        \"platforms\": {},\n        \"long_description\": \"\",\n        \"recommendations\": {},\n        \"version\": \"0.0.0\",\n        \"groupings\": {\n            \"one\": {\n                \"title\": \"One title\",\n                \"description\": \"One description\"\n            },\n            \"two\": {\n                \"title\": \"Two title\",\n                \"description\": \"Two description\"\n            }\n        },\n        \"recipes\": {},\n        \"conflicting\": {},\n        \"description\": \"A fabulous new cookbook\",\n        \"replacing\": {},\n        \"providing\": {}\n    }, \"libraries\": [],\n    \"resources\": [],\n    \"templates\": [],\n    \"cookbook_name\": \"apache-chef-demo\",\n    \"version\": \"0.0.0\",\n    \"recipes\": [],\n    \"root_files\": [{\n        \"name\": \"README\",\n        \"url\": \"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-11637f98942eafbf49c71b7f2f048b78?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277766181&Signature=zgpNl6wSxjTNovqZu2nJq0JztU8%3D\",\n        \"checksum\": \"11637f98942eafbf49c71b7f2f048b78\",\n        \"path\": \"README\",\n        \"specificity\": \"default\"\n    }, {\n        \"name\": \"Rakefile\",\n        \"url\": \"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-ebcf925a1651b4e04b9cd8aac2bc54eb?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277766181&Signature=EFzzDSKKytTl7b%2FxrCeNLh05zj4%3D\",\n        \"checksum\": \"ebcf925a1651b4e04b9cd8aac2bc54eb\",\n        \"path\": \"Rakefile\",\n        \"specificity\": \"default\"\n    }],\n    \"chef_type\": \"cookbook_version\"\n}"
  },
  {
    "path": "apis/chef/src/test/resources/bootstrap-env-noattrs.sh",
    "content": "mkdir -p /etc/chef\ncat > /etc/chef/client.rb <<-'END_OF_JCLOUDS_FILE'\n\trequire 'rubygems'\n\trequire 'ohai'\n\to = Ohai::System.new\n\to.all_plugins\n\tnode_name \"foo-\" + o[:ipaddress]\n\tlog_level :info\n\tlog_location STDOUT\n\tvalidation_client_name \"chef-validator\"\n\tchef_server_url \"http://localhost:4000\"\n\tenvironment \"env\"\nEND_OF_JCLOUDS_FILE\ncat > /etc/chef/validation.pem <<-'END_OF_JCLOUDS_FILE'\n\t-----BEGIN PRIVATE KEY-----\n\tLS0tLS1CRUdJTiBSU0EgUFJJVkFURSBLRVktLS0tLQpNSUlFcFFJQkFBS0NBUUVB\n\teWIyWkpKcUdtMEtLUis4bmZRSk5zU2QrRjl0WE5NVjdDZk9jVzZqc3FzOEVaZ2lW\n\tClIwOWhEMUlZT2o0WXFNMHFKT05sZ3lnNHhSV2V3ZFNHN1FUUGoxbEpwVkFpZGE5\n\tc1h5MitrenlhZ1pBMUFtME8KWmNicWI1aG9lSURnY1grZURhNzlzMHUwRG9tamNm\n\tTzlFS2h2SExCeit6TSszUXFQUmtQVjhuWVRiZnMrSGpWegp6T1U2RDFCMFhSMytJ\n\tUFpabDJBbldzMmQwcWhuU3RIY0RVdm5SVlEwUDQ4Mll3TjlWZ2NlT1p0cFB6MERD\n\tS0VKCjVUeDVTVHViOGswL3p0L1ZBTUhRYWZMU3VRTUxkMnM0Wkx1T1pwdE4vL3VB\n\tc1RteGlyZXFkMzd6KzhaVGRCYkoKOExFcEoraUNYdVNmbTVhVWg3aXc2b3h2VG9Z\n\tMkFMNTMraksyVVFJREFRQUJBb0lCQVFEQTg4QjNpL3hXbjB2WApCVnhGYW1DWW9l\n\tY3VOakd3WFhrU3laZXc2MTZBK0VPQ3U0N2JoNGFUdXJkRmJZTDBZRmFBdGFXdnps\n\tYU4yZUhnCkRiK0hEdVRlZkUyOStXa2NHazZTc2hQbWl6NVQwWE9DQUlDV3c2d1NW\n\tRGtIbUd3UzRqWnZiQUZtN1c4bndHazkKWWh4Z3hGaVJuZ3N3SlpGb3BPTG9GNVdY\n\tczJ0ZDhndUlZTnNsTXBvN3R1NTBpRm5CSHdLTzJac1BBazh0OW5uUwp4bERhdkty\n\tdXltRW1xSENyMytkdGlvNWVhZW5KY3AzZmpvWEJRT0tVazNpcElJMjlYUkI4TnFl\n\tQ1ZWLzdLeHdxCmNrcU9CRWJSd0JjbGNreUliRCtSaUFnS3ZPZWxPUmpFaUU5UjQy\n\tdnVxdnhSQTZrOWtkOW83dXRsWDBBVXRwRW4KM2daYzZMZXBBb0dCQVA5YWVsNVk3\n\tNStzSzJKSlVOT09oTzhhZTQ1Y2RzaWxwMnlJMFgrVUJhU3VRczIrZHlQcAprcEVI\n\tQXhkNHBtbVN2bi84YzlUbEVaaHIrcVliQUJYVlBsRG5jeHBJdXcyQWpiazdzL1M0\n\tWGFTS3NScXBYTDU3CnpqL1FPcUxrUms4K09WVjlxNmxNZVFOcUx0RWoxdTZKUHZp\n\tWDcwUm8rRlF0UnR0Tk9ZYmZkUC9mQW9HQkFNcEEKWGpSNXdvVjVzVWIrUkVnOXZF\n\tdVlvOFJTeU9hcnhxS0ZDSVhWVU5zTE94KzIyK0FLNCtDUXBidWVXTjdqb3RybApZ\n\tRDZ1VDZzdldpM0FBQzdraVkwVUkvZmpWUFJDVWk4dFZvUVVFMFRhVTVWTElUYVlP\n\tQitXL2JCYURFNE05NTYwCjFOdURXTzkwYmFBNWRmVTQ0aXV6dmEwMnJHSlhLOStu\n\tUzNvOG5rL1BBb0dCQUxPTDZkam5EZTRtd0FhRzZKY28KY2Q0eHI4amt5UHpDUlp1\n\teUJDU0Jid3BoSVVYTGM3aERwclBreTA2NG5jSkQxVURtd0lka1hkL2ZwTWtnMlFt\n\tQQovQ1VrNkxFRmpNaXNxSG9qT2FDTDlnUVpKUGhMTjVRVU4yeDFQSldHanMxdlFo\n\tOFRreDBpVVVDT2E4YlFQWE5SCiszNE9Uc1c2VFVuYTRDU1pBeWNMZmhmZkFvR0JB\n\tSWdnVnNlZkJDdnVRa0YwTmVVaG1EQ1JaZmhuZDh5NTVSSFIKMUhDdnFLSWxwdity\n\taGNYL3pteUJMdXRlb3BZeVJKUnNPaUUyRlcwMGk4K3JJUFJ1NFozUTVueWJ4N3cz\n\tUHpWOQpvSE41UjViYUU5T3lJNEtwWld6dHBZWWl0WkY2N05jbkF2VlVMSEhPdlZK\n\tUUduS1lmTEhKWW1ySkY3R0Exb2pNCkF1TWRGYmpGQW9HQVB4VWh4d0Z5OGdhcUJh\n\taEtVRVpuNEY4MUhGUDVpaEdoa1Q0UUw2QUZQTzJlK0poSUdqdVIKMjcrODVoY0Zx\n\tUStISFZ0RnNtODFiL2ErUjdQNFV1Q1JnYzhlQ2p4UU1vSjFYbDRuN1ZialBiSE1u\n\tSU4wUnl2ZApPNFpwV0RXWW5DTzAyMUpUT1VVT0o0Si95MDQxNkJ2a3cwejU5eTdz\n\tTlg3d0RCQkhIYksvWENjPQotLS0tLUVORCBSU0EgUFJJVkFURSBLRVktLS0tLQo=\n\t-----END PRIVATE KEY-----\n\t\nEND_OF_JCLOUDS_FILE\ncat > /etc/chef/first-boot.json <<-'END_OF_JCLOUDS_FILE'\n\t{\"run_list\":[\"recipe[apache2]\",\"role[webserver]\"]}\nEND_OF_JCLOUDS_FILE\nchef-client -j /etc/chef/first-boot.json\n"
  },
  {
    "path": "apis/chef/src/test/resources/bootstrap-env.sh",
    "content": "mkdir -p /etc/chef\ncat > /etc/chef/client.rb <<-'END_OF_JCLOUDS_FILE'\n\trequire 'rubygems'\n\trequire 'ohai'\n\to = Ohai::System.new\n\to.all_plugins\n\tnode_name \"foo-\" + o[:ipaddress]\n\tlog_level :info\n\tlog_location STDOUT\n\tvalidation_client_name \"chef-validator\"\n\tchef_server_url \"http://localhost:4000\"\n\tenvironment \"env\"\nEND_OF_JCLOUDS_FILE\ncat > /etc/chef/validation.pem <<-'END_OF_JCLOUDS_FILE'\n\t-----BEGIN PRIVATE KEY-----\n\tLS0tLS1CRUdJTiBSU0EgUFJJVkFURSBLRVktLS0tLQpNSUlFcFFJQkFBS0NBUUVB\n\teWIyWkpKcUdtMEtLUis4bmZRSk5zU2QrRjl0WE5NVjdDZk9jVzZqc3FzOEVaZ2lW\n\tClIwOWhEMUlZT2o0WXFNMHFKT05sZ3lnNHhSV2V3ZFNHN1FUUGoxbEpwVkFpZGE5\n\tc1h5MitrenlhZ1pBMUFtME8KWmNicWI1aG9lSURnY1grZURhNzlzMHUwRG9tamNm\n\tTzlFS2h2SExCeit6TSszUXFQUmtQVjhuWVRiZnMrSGpWegp6T1U2RDFCMFhSMytJ\n\tUFpabDJBbldzMmQwcWhuU3RIY0RVdm5SVlEwUDQ4Mll3TjlWZ2NlT1p0cFB6MERD\n\tS0VKCjVUeDVTVHViOGswL3p0L1ZBTUhRYWZMU3VRTUxkMnM0Wkx1T1pwdE4vL3VB\n\tc1RteGlyZXFkMzd6KzhaVGRCYkoKOExFcEoraUNYdVNmbTVhVWg3aXc2b3h2VG9Z\n\tMkFMNTMraksyVVFJREFRQUJBb0lCQVFEQTg4QjNpL3hXbjB2WApCVnhGYW1DWW9l\n\tY3VOakd3WFhrU3laZXc2MTZBK0VPQ3U0N2JoNGFUdXJkRmJZTDBZRmFBdGFXdnps\n\tYU4yZUhnCkRiK0hEdVRlZkUyOStXa2NHazZTc2hQbWl6NVQwWE9DQUlDV3c2d1NW\n\tRGtIbUd3UzRqWnZiQUZtN1c4bndHazkKWWh4Z3hGaVJuZ3N3SlpGb3BPTG9GNVdY\n\tczJ0ZDhndUlZTnNsTXBvN3R1NTBpRm5CSHdLTzJac1BBazh0OW5uUwp4bERhdkty\n\tdXltRW1xSENyMytkdGlvNWVhZW5KY3AzZmpvWEJRT0tVazNpcElJMjlYUkI4TnFl\n\tQ1ZWLzdLeHdxCmNrcU9CRWJSd0JjbGNreUliRCtSaUFnS3ZPZWxPUmpFaUU5UjQy\n\tdnVxdnhSQTZrOWtkOW83dXRsWDBBVXRwRW4KM2daYzZMZXBBb0dCQVA5YWVsNVk3\n\tNStzSzJKSlVOT09oTzhhZTQ1Y2RzaWxwMnlJMFgrVUJhU3VRczIrZHlQcAprcEVI\n\tQXhkNHBtbVN2bi84YzlUbEVaaHIrcVliQUJYVlBsRG5jeHBJdXcyQWpiazdzL1M0\n\tWGFTS3NScXBYTDU3CnpqL1FPcUxrUms4K09WVjlxNmxNZVFOcUx0RWoxdTZKUHZp\n\tWDcwUm8rRlF0UnR0Tk9ZYmZkUC9mQW9HQkFNcEEKWGpSNXdvVjVzVWIrUkVnOXZF\n\tdVlvOFJTeU9hcnhxS0ZDSVhWVU5zTE94KzIyK0FLNCtDUXBidWVXTjdqb3RybApZ\n\tRDZ1VDZzdldpM0FBQzdraVkwVUkvZmpWUFJDVWk4dFZvUVVFMFRhVTVWTElUYVlP\n\tQitXL2JCYURFNE05NTYwCjFOdURXTzkwYmFBNWRmVTQ0aXV6dmEwMnJHSlhLOStu\n\tUzNvOG5rL1BBb0dCQUxPTDZkam5EZTRtd0FhRzZKY28KY2Q0eHI4amt5UHpDUlp1\n\teUJDU0Jid3BoSVVYTGM3aERwclBreTA2NG5jSkQxVURtd0lka1hkL2ZwTWtnMlFt\n\tQQovQ1VrNkxFRmpNaXNxSG9qT2FDTDlnUVpKUGhMTjVRVU4yeDFQSldHanMxdlFo\n\tOFRreDBpVVVDT2E4YlFQWE5SCiszNE9Uc1c2VFVuYTRDU1pBeWNMZmhmZkFvR0JB\n\tSWdnVnNlZkJDdnVRa0YwTmVVaG1EQ1JaZmhuZDh5NTVSSFIKMUhDdnFLSWxwdity\n\taGNYL3pteUJMdXRlb3BZeVJKUnNPaUUyRlcwMGk4K3JJUFJ1NFozUTVueWJ4N3cz\n\tUHpWOQpvSE41UjViYUU5T3lJNEtwWld6dHBZWWl0WkY2N05jbkF2VlVMSEhPdlZK\n\tUUduS1lmTEhKWW1ySkY3R0Exb2pNCkF1TWRGYmpGQW9HQVB4VWh4d0Z5OGdhcUJh\n\taEtVRVpuNEY4MUhGUDVpaEdoa1Q0UUw2QUZQTzJlK0poSUdqdVIKMjcrODVoY0Zx\n\tUStISFZ0RnNtODFiL2ErUjdQNFV1Q1JnYzhlQ2p4UU1vSjFYbDRuN1ZialBiSE1u\n\tSU4wUnl2ZApPNFpwV0RXWW5DTzAyMUpUT1VVT0o0Si95MDQxNkJ2a3cwejU5eTdz\n\tTlg3d0RCQkhIYksvWENjPQotLS0tLUVORCBSU0EgUFJJVkFURSBLRVktLS0tLQo=\n\t-----END PRIVATE KEY-----\n\t\nEND_OF_JCLOUDS_FILE\ncat > /etc/chef/first-boot.json <<-'END_OF_JCLOUDS_FILE'\n\t{\"tomcat6\":{\"ssl_port\":8433},\"run_list\":[\"recipe[apache2]\",\"role[webserver]\"]}\nEND_OF_JCLOUDS_FILE\nchef-client -j /etc/chef/first-boot.json\n"
  },
  {
    "path": "apis/chef/src/test/resources/bootstrap-node-env.sh",
    "content": "mkdir -p /etc/chef\ncat > /etc/chef/client.rb <<-'END_OF_JCLOUDS_FILE'\n\trequire 'rubygems'\n\trequire 'ohai'\n\to = Ohai::System.new\n\to.all_plugins\n\tnode_name \"bar\"\n\tlog_level :info\n\tlog_location STDOUT\n\tvalidation_client_name \"chef-validator\"\n\tchef_server_url \"http://localhost:4000\"\n\tenvironment \"env\"\nEND_OF_JCLOUDS_FILE\ncat > /etc/chef/validation.pem <<-'END_OF_JCLOUDS_FILE'\n\t-----BEGIN PRIVATE KEY-----\n\tLS0tLS1CRUdJTiBSU0EgUFJJVkFURSBLRVktLS0tLQpNSUlFcFFJQkFBS0NBUUVB\n\teWIyWkpKcUdtMEtLUis4bmZRSk5zU2QrRjl0WE5NVjdDZk9jVzZqc3FzOEVaZ2lW\n\tClIwOWhEMUlZT2o0WXFNMHFKT05sZ3lnNHhSV2V3ZFNHN1FUUGoxbEpwVkFpZGE5\n\tc1h5MitrenlhZ1pBMUFtME8KWmNicWI1aG9lSURnY1grZURhNzlzMHUwRG9tamNm\n\tTzlFS2h2SExCeit6TSszUXFQUmtQVjhuWVRiZnMrSGpWegp6T1U2RDFCMFhSMytJ\n\tUFpabDJBbldzMmQwcWhuU3RIY0RVdm5SVlEwUDQ4Mll3TjlWZ2NlT1p0cFB6MERD\n\tS0VKCjVUeDVTVHViOGswL3p0L1ZBTUhRYWZMU3VRTUxkMnM0Wkx1T1pwdE4vL3VB\n\tc1RteGlyZXFkMzd6KzhaVGRCYkoKOExFcEoraUNYdVNmbTVhVWg3aXc2b3h2VG9Z\n\tMkFMNTMraksyVVFJREFRQUJBb0lCQVFEQTg4QjNpL3hXbjB2WApCVnhGYW1DWW9l\n\tY3VOakd3WFhrU3laZXc2MTZBK0VPQ3U0N2JoNGFUdXJkRmJZTDBZRmFBdGFXdnps\n\tYU4yZUhnCkRiK0hEdVRlZkUyOStXa2NHazZTc2hQbWl6NVQwWE9DQUlDV3c2d1NW\n\tRGtIbUd3UzRqWnZiQUZtN1c4bndHazkKWWh4Z3hGaVJuZ3N3SlpGb3BPTG9GNVdY\n\tczJ0ZDhndUlZTnNsTXBvN3R1NTBpRm5CSHdLTzJac1BBazh0OW5uUwp4bERhdkty\n\tdXltRW1xSENyMytkdGlvNWVhZW5KY3AzZmpvWEJRT0tVazNpcElJMjlYUkI4TnFl\n\tQ1ZWLzdLeHdxCmNrcU9CRWJSd0JjbGNreUliRCtSaUFnS3ZPZWxPUmpFaUU5UjQy\n\tdnVxdnhSQTZrOWtkOW83dXRsWDBBVXRwRW4KM2daYzZMZXBBb0dCQVA5YWVsNVk3\n\tNStzSzJKSlVOT09oTzhhZTQ1Y2RzaWxwMnlJMFgrVUJhU3VRczIrZHlQcAprcEVI\n\tQXhkNHBtbVN2bi84YzlUbEVaaHIrcVliQUJYVlBsRG5jeHBJdXcyQWpiazdzL1M0\n\tWGFTS3NScXBYTDU3CnpqL1FPcUxrUms4K09WVjlxNmxNZVFOcUx0RWoxdTZKUHZp\n\tWDcwUm8rRlF0UnR0Tk9ZYmZkUC9mQW9HQkFNcEEKWGpSNXdvVjVzVWIrUkVnOXZF\n\tdVlvOFJTeU9hcnhxS0ZDSVhWVU5zTE94KzIyK0FLNCtDUXBidWVXTjdqb3RybApZ\n\tRDZ1VDZzdldpM0FBQzdraVkwVUkvZmpWUFJDVWk4dFZvUVVFMFRhVTVWTElUYVlP\n\tQitXL2JCYURFNE05NTYwCjFOdURXTzkwYmFBNWRmVTQ0aXV6dmEwMnJHSlhLOStu\n\tUzNvOG5rL1BBb0dCQUxPTDZkam5EZTRtd0FhRzZKY28KY2Q0eHI4amt5UHpDUlp1\n\teUJDU0Jid3BoSVVYTGM3aERwclBreTA2NG5jSkQxVURtd0lka1hkL2ZwTWtnMlFt\n\tQQovQ1VrNkxFRmpNaXNxSG9qT2FDTDlnUVpKUGhMTjVRVU4yeDFQSldHanMxdlFo\n\tOFRreDBpVVVDT2E4YlFQWE5SCiszNE9Uc1c2VFVuYTRDU1pBeWNMZmhmZkFvR0JB\n\tSWdnVnNlZkJDdnVRa0YwTmVVaG1EQ1JaZmhuZDh5NTVSSFIKMUhDdnFLSWxwdity\n\taGNYL3pteUJMdXRlb3BZeVJKUnNPaUUyRlcwMGk4K3JJUFJ1NFozUTVueWJ4N3cz\n\tUHpWOQpvSE41UjViYUU5T3lJNEtwWld6dHBZWWl0WkY2N05jbkF2VlVMSEhPdlZK\n\tUUduS1lmTEhKWW1ySkY3R0Exb2pNCkF1TWRGYmpGQW9HQVB4VWh4d0Z5OGdhcUJh\n\taEtVRVpuNEY4MUhGUDVpaEdoa1Q0UUw2QUZQTzJlK0poSUdqdVIKMjcrODVoY0Zx\n\tUStISFZ0RnNtODFiL2ErUjdQNFV1Q1JnYzhlQ2p4UU1vSjFYbDRuN1ZialBiSE1u\n\tSU4wUnl2ZApPNFpwV0RXWW5DTzAyMUpUT1VVT0o0Si95MDQxNkJ2a3cwejU5eTdz\n\tTlg3d0RCQkhIYksvWENjPQotLS0tLUVORCBSU0EgUFJJVkFURSBLRVktLS0tLQo=\n\t-----END PRIVATE KEY-----\n\t\nEND_OF_JCLOUDS_FILE\ncat > /etc/chef/first-boot.json <<-'END_OF_JCLOUDS_FILE'\n\t{\"tomcat6\":{\"ssl_port\":8433},\"run_list\":[\"recipe[apache2]\",\"role[webserver]\"]}\nEND_OF_JCLOUDS_FILE\nchef-client -j /etc/chef/first-boot.json\n"
  },
  {
    "path": "apis/chef/src/test/resources/bootstrap-ssl.sh",
    "content": "mkdir -p /etc/chef\ncat > /etc/chef/chef-server.crt <<-'END_OF_JCLOUDS_FILE'\n\t-----BEGIN CERTIFICATE-----\n\tMIIFDTCCA/WgAwIBAgIQBZ8R1sZP2Lbc8x554UUQ2DANBgkqhkiG9w0BAQsFADBN\n\tMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMScwJQYDVQQDEx5E\n\taWdpQ2VydCBTSEEyIFNlY3VyZSBTZXJ2ZXIgQ0EwHhcNMTQxMTEwMDAwMDAwWhcN\n\tMTcxMTE0MTIwMDAwWjBlMQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3Rv\n\tbjEQMA4GA1UEBxMHU2VhdHRsZTEbMBkGA1UEChMSQ2hlZiBTb2Z0d2FyZSwgSW5j\n\tMRIwEAYDVQQDDAkqLmNoZWYuaW8wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK\n\tAoIBAQC3xCIczkV10O5jTDpbd4YlPLC6kfnVoOkno2N/OOlcLQu3ulj/Lj1j4r6e\n\t2XthJLcFgTO+y+1/IKnnpLKDfkx1YngWEBXEBP+MrrpDUKKs053s45/bI9QBPISA\n\ttXgnYxMH9Glo6FWWd13TUq++OKGw1p1wazH64XK4MAf5y/lkmWXIWumNuO35ZqtB\n\tME3wJISwVHzHB2CQjlDklt+Mb0APEiIFIZflgu9JNBYzLdvUtxiz15FUZQI7SsYL\n\tTfXOD1KBNMWqN8snG2e5gRAzB2D161DFvAZt8OiYUe+3QurNlTYVzeHv1ok6UqgM\n\tZcLzg8m801rRip0D7FCGvMCU/ktdAgMBAAGjggHPMIIByzAfBgNVHSMEGDAWgBQP\n\tgGEcgjFh1S8o541GOLQs4cbZ4jAdBgNVHQ4EFgQUwldjw4Pb4HV+wxGZ7MSSRh+d\n\tpm4wHQYDVR0RBBYwFIIJKi5jaGVmLmlvggdjaGVmLmlvMA4GA1UdDwEB/wQEAwIF\n\toDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwawYDVR0fBGQwYjAvoC2g\n\tK4YpaHR0cDovL2NybDMuZGlnaWNlcnQuY29tL3NzY2Etc2hhMi1nMy5jcmwwL6At\n\toCuGKWh0dHA6Ly9jcmw0LmRpZ2ljZXJ0LmNvbS9zc2NhLXNoYTItZzMuY3JsMEIG\n\tA1UdIAQ7MDkwNwYJYIZIAYb9bAEBMCowKAYIKwYBBQUHAgEWHGh0dHBzOi8vd3d3\n\tLmRpZ2ljZXJ0LmNvbS9DUFMwfAYIKwYBBQUHAQEEcDBuMCQGCCsGAQUFBzABhhho\n\tdHRwOi8vb2NzcC5kaWdpY2VydC5jb20wRgYIKwYBBQUHMAKGOmh0dHA6Ly9jYWNl\n\tcnRzLmRpZ2ljZXJ0LmNvbS9EaWdpQ2VydFNIQTJTZWN1cmVTZXJ2ZXJDQS5jcnQw\n\tDAYDVR0TAQH/BAIwADANBgkqhkiG9w0BAQsFAAOCAQEAvcTWenNuvvrhX2omm8LQ\n\tzWOuu8jqpoflACwD4lOSZ4TgOe4pQGCjXq8aRBD5k+goqQrPVf9lHnelUHFQac0Q\n\t5WT4YUmisUbF0S4uY5OGQymM52MvUWG4ODL4gaWhFvN+HAXrDPP/9iitsjV0QOnl\n\tCDq7Q4/XYRYW3opu5nLLbfW6v4QvF5yzZagEACGs7Vt32p6l391UcU8f6wiB3uMD\n\teioCvjpv/+2YOUNlDPCM3uBubjUhHOwO817wBxXkzdk1OSRe4jzcw/uX6wL7birt\n\tfbaSkpilvVX529pSzB2Lvi9xWOoGMM578dpQ0h3PwhmmvKhhCWP+pI05k3oSkYCP\n\tng==\n\t-----END CERTIFICATE-----\n\t\nEND_OF_JCLOUDS_FILE\ncat > /etc/chef/client.rb <<-'END_OF_JCLOUDS_FILE'\n\trequire 'rubygems'\n\trequire 'ohai'\n\to = Ohai::System.new\n\to.all_plugins\n\tnode_name \"foo-\" + o[:ipaddress]\n\tlog_level :info\n\tlog_location STDOUT\n\tvalidation_client_name \"chef-validator\"\n\tchef_server_url \"http://localhost:4000\"\n\tssl_ca_file \"/etc/chef/chef-server.crt\"\n\tssl_ca_path \"/etc/chef\"\n\tssl_verify_mode :verify_peer\n\tverify_api_cert true\nEND_OF_JCLOUDS_FILE\ncat > /etc/chef/validation.pem <<-'END_OF_JCLOUDS_FILE'\n\t-----BEGIN PRIVATE KEY-----\n\tLS0tLS1CRUdJTiBSU0EgUFJJVkFURSBLRVktLS0tLQpNSUlFcFFJQkFBS0NBUUVB\n\teWIyWkpKcUdtMEtLUis4bmZRSk5zU2QrRjl0WE5NVjdDZk9jVzZqc3FzOEVaZ2lW\n\tClIwOWhEMUlZT2o0WXFNMHFKT05sZ3lnNHhSV2V3ZFNHN1FUUGoxbEpwVkFpZGE5\n\tc1h5MitrenlhZ1pBMUFtME8KWmNicWI1aG9lSURnY1grZURhNzlzMHUwRG9tamNm\n\tTzlFS2h2SExCeit6TSszUXFQUmtQVjhuWVRiZnMrSGpWegp6T1U2RDFCMFhSMytJ\n\tUFpabDJBbldzMmQwcWhuU3RIY0RVdm5SVlEwUDQ4Mll3TjlWZ2NlT1p0cFB6MERD\n\tS0VKCjVUeDVTVHViOGswL3p0L1ZBTUhRYWZMU3VRTUxkMnM0Wkx1T1pwdE4vL3VB\n\tc1RteGlyZXFkMzd6KzhaVGRCYkoKOExFcEoraUNYdVNmbTVhVWg3aXc2b3h2VG9Z\n\tMkFMNTMraksyVVFJREFRQUJBb0lCQVFEQTg4QjNpL3hXbjB2WApCVnhGYW1DWW9l\n\tY3VOakd3WFhrU3laZXc2MTZBK0VPQ3U0N2JoNGFUdXJkRmJZTDBZRmFBdGFXdnps\n\tYU4yZUhnCkRiK0hEdVRlZkUyOStXa2NHazZTc2hQbWl6NVQwWE9DQUlDV3c2d1NW\n\tRGtIbUd3UzRqWnZiQUZtN1c4bndHazkKWWh4Z3hGaVJuZ3N3SlpGb3BPTG9GNVdY\n\tczJ0ZDhndUlZTnNsTXBvN3R1NTBpRm5CSHdLTzJac1BBazh0OW5uUwp4bERhdkty\n\tdXltRW1xSENyMytkdGlvNWVhZW5KY3AzZmpvWEJRT0tVazNpcElJMjlYUkI4TnFl\n\tQ1ZWLzdLeHdxCmNrcU9CRWJSd0JjbGNreUliRCtSaUFnS3ZPZWxPUmpFaUU5UjQy\n\tdnVxdnhSQTZrOWtkOW83dXRsWDBBVXRwRW4KM2daYzZMZXBBb0dCQVA5YWVsNVk3\n\tNStzSzJKSlVOT09oTzhhZTQ1Y2RzaWxwMnlJMFgrVUJhU3VRczIrZHlQcAprcEVI\n\tQXhkNHBtbVN2bi84YzlUbEVaaHIrcVliQUJYVlBsRG5jeHBJdXcyQWpiazdzL1M0\n\tWGFTS3NScXBYTDU3CnpqL1FPcUxrUms4K09WVjlxNmxNZVFOcUx0RWoxdTZKUHZp\n\tWDcwUm8rRlF0UnR0Tk9ZYmZkUC9mQW9HQkFNcEEKWGpSNXdvVjVzVWIrUkVnOXZF\n\tdVlvOFJTeU9hcnhxS0ZDSVhWVU5zTE94KzIyK0FLNCtDUXBidWVXTjdqb3RybApZ\n\tRDZ1VDZzdldpM0FBQzdraVkwVUkvZmpWUFJDVWk4dFZvUVVFMFRhVTVWTElUYVlP\n\tQitXL2JCYURFNE05NTYwCjFOdURXTzkwYmFBNWRmVTQ0aXV6dmEwMnJHSlhLOStu\n\tUzNvOG5rL1BBb0dCQUxPTDZkam5EZTRtd0FhRzZKY28KY2Q0eHI4amt5UHpDUlp1\n\teUJDU0Jid3BoSVVYTGM3aERwclBreTA2NG5jSkQxVURtd0lka1hkL2ZwTWtnMlFt\n\tQQovQ1VrNkxFRmpNaXNxSG9qT2FDTDlnUVpKUGhMTjVRVU4yeDFQSldHanMxdlFo\n\tOFRreDBpVVVDT2E4YlFQWE5SCiszNE9Uc1c2VFVuYTRDU1pBeWNMZmhmZkFvR0JB\n\tSWdnVnNlZkJDdnVRa0YwTmVVaG1EQ1JaZmhuZDh5NTVSSFIKMUhDdnFLSWxwdity\n\taGNYL3pteUJMdXRlb3BZeVJKUnNPaUUyRlcwMGk4K3JJUFJ1NFozUTVueWJ4N3cz\n\tUHpWOQpvSE41UjViYUU5T3lJNEtwWld6dHBZWWl0WkY2N05jbkF2VlVMSEhPdlZK\n\tUUduS1lmTEhKWW1ySkY3R0Exb2pNCkF1TWRGYmpGQW9HQVB4VWh4d0Z5OGdhcUJh\n\taEtVRVpuNEY4MUhGUDVpaEdoa1Q0UUw2QUZQTzJlK0poSUdqdVIKMjcrODVoY0Zx\n\tUStISFZ0RnNtODFiL2ErUjdQNFV1Q1JnYzhlQ2p4UU1vSjFYbDRuN1ZialBiSE1u\n\tSU4wUnl2ZApPNFpwV0RXWW5DTzAyMUpUT1VVT0o0Si95MDQxNkJ2a3cwejU5eTdz\n\tTlg3d0RCQkhIYksvWENjPQotLS0tLUVORCBSU0EgUFJJVkFURSBLRVktLS0tLQo=\n\t-----END PRIVATE KEY-----\n\t\nEND_OF_JCLOUDS_FILE\ncat > /etc/chef/first-boot.json <<-'END_OF_JCLOUDS_FILE'\n\t{\"tomcat6\":{\"ssl_port\":8433},\"run_list\":[\"recipe[apache2]\",\"role[webserver]\"]}\nEND_OF_JCLOUDS_FILE\nchef-client -j /etc/chef/first-boot.json\n"
  },
  {
    "path": "apis/chef/src/test/resources/bootstrap.sh",
    "content": "mkdir -p /etc/chef\ncat > /etc/chef/client.rb <<-'END_OF_JCLOUDS_FILE'\n\trequire 'rubygems'\n\trequire 'ohai'\n\to = Ohai::System.new\n\to.all_plugins\n\tnode_name \"foo-\" + o[:ipaddress]\n\tlog_level :info\n\tlog_location STDOUT\n\tvalidation_client_name \"chef-validator\"\n\tchef_server_url \"http://localhost:4000\"\nEND_OF_JCLOUDS_FILE\ncat > /etc/chef/validation.pem <<-'END_OF_JCLOUDS_FILE'\n\t-----BEGIN PRIVATE KEY-----\n\tLS0tLS1CRUdJTiBSU0EgUFJJVkFURSBLRVktLS0tLQpNSUlFcFFJQkFBS0NBUUVB\n\teWIyWkpKcUdtMEtLUis4bmZRSk5zU2QrRjl0WE5NVjdDZk9jVzZqc3FzOEVaZ2lW\n\tClIwOWhEMUlZT2o0WXFNMHFKT05sZ3lnNHhSV2V3ZFNHN1FUUGoxbEpwVkFpZGE5\n\tc1h5MitrenlhZ1pBMUFtME8KWmNicWI1aG9lSURnY1grZURhNzlzMHUwRG9tamNm\n\tTzlFS2h2SExCeit6TSszUXFQUmtQVjhuWVRiZnMrSGpWegp6T1U2RDFCMFhSMytJ\n\tUFpabDJBbldzMmQwcWhuU3RIY0RVdm5SVlEwUDQ4Mll3TjlWZ2NlT1p0cFB6MERD\n\tS0VKCjVUeDVTVHViOGswL3p0L1ZBTUhRYWZMU3VRTUxkMnM0Wkx1T1pwdE4vL3VB\n\tc1RteGlyZXFkMzd6KzhaVGRCYkoKOExFcEoraUNYdVNmbTVhVWg3aXc2b3h2VG9Z\n\tMkFMNTMraksyVVFJREFRQUJBb0lCQVFEQTg4QjNpL3hXbjB2WApCVnhGYW1DWW9l\n\tY3VOakd3WFhrU3laZXc2MTZBK0VPQ3U0N2JoNGFUdXJkRmJZTDBZRmFBdGFXdnps\n\tYU4yZUhnCkRiK0hEdVRlZkUyOStXa2NHazZTc2hQbWl6NVQwWE9DQUlDV3c2d1NW\n\tRGtIbUd3UzRqWnZiQUZtN1c4bndHazkKWWh4Z3hGaVJuZ3N3SlpGb3BPTG9GNVdY\n\tczJ0ZDhndUlZTnNsTXBvN3R1NTBpRm5CSHdLTzJac1BBazh0OW5uUwp4bERhdkty\n\tdXltRW1xSENyMytkdGlvNWVhZW5KY3AzZmpvWEJRT0tVazNpcElJMjlYUkI4TnFl\n\tQ1ZWLzdLeHdxCmNrcU9CRWJSd0JjbGNreUliRCtSaUFnS3ZPZWxPUmpFaUU5UjQy\n\tdnVxdnhSQTZrOWtkOW83dXRsWDBBVXRwRW4KM2daYzZMZXBBb0dCQVA5YWVsNVk3\n\tNStzSzJKSlVOT09oTzhhZTQ1Y2RzaWxwMnlJMFgrVUJhU3VRczIrZHlQcAprcEVI\n\tQXhkNHBtbVN2bi84YzlUbEVaaHIrcVliQUJYVlBsRG5jeHBJdXcyQWpiazdzL1M0\n\tWGFTS3NScXBYTDU3CnpqL1FPcUxrUms4K09WVjlxNmxNZVFOcUx0RWoxdTZKUHZp\n\tWDcwUm8rRlF0UnR0Tk9ZYmZkUC9mQW9HQkFNcEEKWGpSNXdvVjVzVWIrUkVnOXZF\n\tdVlvOFJTeU9hcnhxS0ZDSVhWVU5zTE94KzIyK0FLNCtDUXBidWVXTjdqb3RybApZ\n\tRDZ1VDZzdldpM0FBQzdraVkwVUkvZmpWUFJDVWk4dFZvUVVFMFRhVTVWTElUYVlP\n\tQitXL2JCYURFNE05NTYwCjFOdURXTzkwYmFBNWRmVTQ0aXV6dmEwMnJHSlhLOStu\n\tUzNvOG5rL1BBb0dCQUxPTDZkam5EZTRtd0FhRzZKY28KY2Q0eHI4amt5UHpDUlp1\n\teUJDU0Jid3BoSVVYTGM3aERwclBreTA2NG5jSkQxVURtd0lka1hkL2ZwTWtnMlFt\n\tQQovQ1VrNkxFRmpNaXNxSG9qT2FDTDlnUVpKUGhMTjVRVU4yeDFQSldHanMxdlFo\n\tOFRreDBpVVVDT2E4YlFQWE5SCiszNE9Uc1c2VFVuYTRDU1pBeWNMZmhmZkFvR0JB\n\tSWdnVnNlZkJDdnVRa0YwTmVVaG1EQ1JaZmhuZDh5NTVSSFIKMUhDdnFLSWxwdity\n\taGNYL3pteUJMdXRlb3BZeVJKUnNPaUUyRlcwMGk4K3JJUFJ1NFozUTVueWJ4N3cz\n\tUHpWOQpvSE41UjViYUU5T3lJNEtwWld6dHBZWWl0WkY2N05jbkF2VlVMSEhPdlZK\n\tUUduS1lmTEhKWW1ySkY3R0Exb2pNCkF1TWRGYmpGQW9HQVB4VWh4d0Z5OGdhcUJh\n\taEtVRVpuNEY4MUhGUDVpaEdoa1Q0UUw2QUZQTzJlK0poSUdqdVIKMjcrODVoY0Zx\n\tUStISFZ0RnNtODFiL2ErUjdQNFV1Q1JnYzhlQ2p4UU1vSjFYbDRuN1ZialBiSE1u\n\tSU4wUnl2ZApPNFpwV0RXWW5DTzAyMUpUT1VVT0o0Si95MDQxNkJ2a3cwejU5eTdz\n\tTlg3d0RCQkhIYksvWENjPQotLS0tLUVORCBSU0EgUFJJVkFURSBLRVktLS0tLQo=\n\t-----END PRIVATE KEY-----\n\t\nEND_OF_JCLOUDS_FILE\ncat > /etc/chef/first-boot.json <<-'END_OF_JCLOUDS_FILE'\n\t{\"tomcat6\":{\"ssl_port\":8433},\"run_list\":[\"recipe[apache2]\",\"role[webserver]\"]}\nEND_OF_JCLOUDS_FILE\nchef-client -j /etc/chef/first-boot.json\n"
  },
  {
    "path": "apis/chef/src/test/resources/brew-cookbook.json",
    "content": "{ \"attributes\" : [  ],\n  \"chef_type\" : \"cookbook_version\",\n  \"cookbook_name\" : \"brew\",\n  \"definitions\" : [  ],\n  \"files\" : [  ],\n  \"json_class\" : \"Chef::CookbookVersion\",\n  \"libraries\" : [  ],\n  \"metadata\" : { \"attributes\" : {  },\n      \"conflicting\" : {  },\n      \"dependencies\" : {  },\n      \"description\" : \"A fabulous new cookbook\",\n      \"groupings\" : {  },\n      \"license\" : \"Apache v2.0\",\n      \"long_description\" : \"\",\n      \"maintainer\" : \"Your Name\",\n      \"maintainer_email\" : \"youremail@example.com\",\n      \"name\" : \"brew\",\n      \"platforms\" : {  },\n      \"providing\" : { \"brew\" : \"0.0.0\" },\n      \"recipes\" : { \"brew\" : \"\" },\n      \"recommendations\" : {  },\n      \"replacing\" : {  },\n      \"suggestions\" : {  },\n      \"version\" : \"0.0.0\"\n    },\n  \"name\" : \"brew-0.0.0\",\n  \"providers\" : [ { \"checksum\" : \"0c5ecd7788cf4f6c7de2a57193897a6c\",\n        \"name\" : \"brew.rb\",\n        \"path\" : \"providers/brew.rb\",\n        \"specificity\" : \"default\",\n        \"url\" : \"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-0c5ecd7788cf4f6c7de2a57193897a6c?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774465&Signature=brTA3YkBF7iDnjPGCCHxgm7AHko%3D\"\n      } ],\n  \"recipes\" : [ { \"checksum\" : \"1dda05ed139664f1f89b9dec482b77c0\",\n        \"name\" : \"default.rb\",\n        \"path\" : \"recipes/default.rb\",\n        \"specificity\" : \"default\",\n        \"url\" : \"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-1dda05ed139664f1f89b9dec482b77c0?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774465&Signature=dOzPk64at92zOfZlxt1suDpGuPs%3D\"\n      } ],\n  \"resources\" : [ { \"checksum\" : \"0189e76ccc476701d6b374e5a1a27347\",\n        \"name\" : \"brew.rb\",\n        \"path\" : \"resources/brew.rb\",\n        \"specificity\" : \"default\",\n        \"url\" : \"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-0189e76ccc476701d6b374e5a1a27347?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774465&Signature=ufrI1k6pKJ1%2FBRMAaIGr6icJlpc%3D\"\n      } ],\n  \"root_files\" : [  ],\n  \"templates\" : [  ],\n  \"version\" : \"0.0.0\"\n}"
  },
  {
    "path": "apis/chef/src/test/resources/chef.crt",
    "content": "-----BEGIN CERTIFICATE-----\nMIIFDTCCA/WgAwIBAgIQBZ8R1sZP2Lbc8x554UUQ2DANBgkqhkiG9w0BAQsFADBN\nMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMScwJQYDVQQDEx5E\naWdpQ2VydCBTSEEyIFNlY3VyZSBTZXJ2ZXIgQ0EwHhcNMTQxMTEwMDAwMDAwWhcN\nMTcxMTE0MTIwMDAwWjBlMQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3Rv\nbjEQMA4GA1UEBxMHU2VhdHRsZTEbMBkGA1UEChMSQ2hlZiBTb2Z0d2FyZSwgSW5j\nMRIwEAYDVQQDDAkqLmNoZWYuaW8wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK\nAoIBAQC3xCIczkV10O5jTDpbd4YlPLC6kfnVoOkno2N/OOlcLQu3ulj/Lj1j4r6e\n2XthJLcFgTO+y+1/IKnnpLKDfkx1YngWEBXEBP+MrrpDUKKs053s45/bI9QBPISA\ntXgnYxMH9Glo6FWWd13TUq++OKGw1p1wazH64XK4MAf5y/lkmWXIWumNuO35ZqtB\nME3wJISwVHzHB2CQjlDklt+Mb0APEiIFIZflgu9JNBYzLdvUtxiz15FUZQI7SsYL\nTfXOD1KBNMWqN8snG2e5gRAzB2D161DFvAZt8OiYUe+3QurNlTYVzeHv1ok6UqgM\nZcLzg8m801rRip0D7FCGvMCU/ktdAgMBAAGjggHPMIIByzAfBgNVHSMEGDAWgBQP\ngGEcgjFh1S8o541GOLQs4cbZ4jAdBgNVHQ4EFgQUwldjw4Pb4HV+wxGZ7MSSRh+d\npm4wHQYDVR0RBBYwFIIJKi5jaGVmLmlvggdjaGVmLmlvMA4GA1UdDwEB/wQEAwIF\noDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwawYDVR0fBGQwYjAvoC2g\nK4YpaHR0cDovL2NybDMuZGlnaWNlcnQuY29tL3NzY2Etc2hhMi1nMy5jcmwwL6At\noCuGKWh0dHA6Ly9jcmw0LmRpZ2ljZXJ0LmNvbS9zc2NhLXNoYTItZzMuY3JsMEIG\nA1UdIAQ7MDkwNwYJYIZIAYb9bAEBMCowKAYIKwYBBQUHAgEWHGh0dHBzOi8vd3d3\nLmRpZ2ljZXJ0LmNvbS9DUFMwfAYIKwYBBQUHAQEEcDBuMCQGCCsGAQUFBzABhhho\ndHRwOi8vb2NzcC5kaWdpY2VydC5jb20wRgYIKwYBBQUHMAKGOmh0dHA6Ly9jYWNl\ncnRzLmRpZ2ljZXJ0LmNvbS9EaWdpQ2VydFNIQTJTZWN1cmVTZXJ2ZXJDQS5jcnQw\nDAYDVR0TAQH/BAIwADANBgkqhkiG9w0BAQsFAAOCAQEAvcTWenNuvvrhX2omm8LQ\nzWOuu8jqpoflACwD4lOSZ4TgOe4pQGCjXq8aRBD5k+goqQrPVf9lHnelUHFQac0Q\n5WT4YUmisUbF0S4uY5OGQymM52MvUWG4ODL4gaWhFvN+HAXrDPP/9iitsjV0QOnl\nCDq7Q4/XYRYW3opu5nLLbfW6v4QvF5yzZagEACGs7Vt32p6l391UcU8f6wiB3uMD\neioCvjpv/+2YOUNlDPCM3uBubjUhHOwO817wBxXkzdk1OSRe4jzcw/uX6wL7birt\nfbaSkpilvVX529pSzB2Lvi9xWOoGMM578dpQ0h3PwhmmvKhhCWP+pI05k3oSkYCP\nng==\n-----END CERTIFICATE-----\n"
  },
  {
    "path": "apis/chef/src/test/resources/client-no-pub-key.json",
    "content": "{ \"certificate\" : \"-----BEGIN CERTIFICATE-----\\nMIIClzCCAgCgAwIBAgIBATANBgkqhkiG9w0BAQUFADCBnjELMAkGA1UEBhMCVVMx\\nEzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxFjAUBgNVBAoM\\nDU9wc2NvZGUsIEluYy4xHDAaBgNVBAsME0NlcnRpZmljYXRlIFNlcnZpY2UxMjAw\\nBgNVBAMMKW9wc2NvZGUuY29tL2VtYWlsQWRkcmVzcz1hdXRoQG9wc2NvZGUuY29t\\nMB4XDTEwMDczMDIwNDEzMFoXDTIwMDcyNzIwNDEzMFowADCCASIwDQYJKoZIhvcN\\nAQEBBQADggEPADCCAQoCggEBAMm9mSSahptCikfvJ30CTbEnfhfbVzTFewnznFuo\\n7KrPBGYIlUdPYQ9SGDo+GKjNKiTjZYMoOMUVnsHUhu0Ez49ZSaVQInWvbF8tvpM8\\nmoGQNQJtDmXG6m+YaHiA4HF/ng2u/bNLtA6Jo3HzvRCobxywc/szPt0Kj0ZD1fJ2\\nE237Ph41c8zlOg9QdF0d/iD2WZdgJ1rNndKoZ0rR3A1L50VUND+PNmMDfVYHHjmb\\naT89AwihCeU8eUk7m/JNP87f1QDB0Gny0rkDC3drOGS7jmabTf/7gLE5sYq3qnd+\\n8/vGU3QWyfCxKSfogl7kn5uWlIe4sOqMb06GNgC+d/oytlECAwEAATANBgkqhkiG\\n9w0BAQUFAAOBgQBftzSZxstWw60GqRTDNN/F2GnrdtnKBoXzHww3r6jtGEylYq20\\n5KfKpEx+sPX0gyZuYJiXC2CkEjImAluWKcdN9ZF6VD541sheAjbiaU7q7ZsztTxF\\nWUH2tCvHeDXYKPKek3QzL7bYpUhLnCN/XxEv6ibeMDwtI7f5qpk2Aspzcw==\\n-----END CERTIFICATE-----\\n\",\n  \"clientname\" : \"adriancole-jcloudstest\",\n  \"name\" : \"adriancole-jcloudstest\",\n  \"orgname\" : \"jclouds\",\n  \"private_key\" : \"-----BEGIN RSA PRIVATE KEY-----\\nMIIEpQIBAAKCAQEAyb2ZJJqGm0KKR+8nfQJNsSd+F9tXNMV7CfOcW6jsqs8EZgiV\\nR09hD1IYOj4YqM0qJONlgyg4xRWewdSG7QTPj1lJpVAida9sXy2+kzyagZA1Am0O\\nZcbqb5hoeIDgcX+eDa79s0u0DomjcfO9EKhvHLBz+zM+3QqPRkPV8nYTbfs+HjVz\\nzOU6D1B0XR3+IPZZl2AnWs2d0qhnStHcDUvnRVQ0P482YwN9VgceOZtpPz0DCKEJ\\n5Tx5STub8k0/zt/VAMHQafLSuQMLd2s4ZLuOZptN//uAsTmxireqd37z+8ZTdBbJ\\n8LEpJ+iCXuSfm5aUh7iw6oxvToY2AL53+jK2UQIDAQABAoIBAQDA88B3i/xWn0vX\\nBVxFamCYoecuNjGwXXkSyZew616A+EOCu47bh4aTurdFbYL0YFaAtaWvzlaN2eHg\\nDb+HDuTefE29+WkcGk6SshPmiz5T0XOCAICWw6wSVDkHmGwS4jZvbAFm7W8nwGk9\\nYhxgxFiRngswJZFopOLoF5WXs2td8guIYNslMpo7tu50iFnBHwKO2ZsPAk8t9nnS\\nxlDavKruymEmqHCr3+dtio5eaenJcp3fjoXBQOKUk3ipII29XRB8NqeCVV/7Kxwq\\nckqOBEbRwBclckyIbD+RiAgKvOelORjEiE9R42vuqvxRA6k9kd9o7utlX0AUtpEn\\n3gZc6LepAoGBAP9ael5Y75+sK2JJUNOOhO8ae45cdsilp2yI0X+UBaSuQs2+dyPp\\nkpEHAxd4pmmSvn/8c9TlEZhr+qYbABXVPlDncxpIuw2Ajbk7s/S4XaSKsRqpXL57\\nzj/QOqLkRk8+OVV9q6lMeQNqLtEj1u6JPviX70Ro+FQtRttNOYbfdP/fAoGBAMpA\\nXjR5woV5sUb+REg9vEuYo8RSyOarxqKFCIXVUNsLOx+22+AK4+CQpbueWN7jotrl\\nYD6uT6svWi3AAC7kiY0UI/fjVPRCUi8tVoQUE0TaU5VLITaYOB+W/bBaDE4M9560\\n1NuDWO90baA5dfU44iuzva02rGJXK9+nS3o8nk/PAoGBALOL6djnDe4mwAaG6Jco\\ncd4xr8jkyPzCRZuyBCSBbwphIUXLc7hDprPky064ncJD1UDmwIdkXd/fpMkg2QmA\\n/CUk6LEFjMisqHojOaCL9gQZJPhLN5QUN2x1PJWGjs1vQh8Tkx0iUUCOa8bQPXNR\\n+34OTsW6TUna4CSZAycLfhffAoGBAIggVsefBCvuQkF0NeUhmDCRZfhnd8y55RHR\\n1HCvqKIlpv+rhcX/zmyBLuteopYyRJRsOiE2FW00i8+rIPRu4Z3Q5nybx7w3PzV9\\noHN5R5baE9OyI4KpZWztpYYitZF67NcnAvVULHHOvVJQGnKYfLHJYmrJF7GA1ojM\\nAuMdFbjFAoGAPxUhxwFy8gaqBahKUEZn4F81HFP5ihGhkT4QL6AFPO2e+JhIGjuR\\n27+85hcFqQ+HHVtFsm81b/a+R7P4UuCRgc8eCjxQMoJ1Xl4n7VbjPbHMnIN0Ryvd\\nO4ZpWDWYnCO021JTOUUOJ4J/y0416Bvkw0z59y7sNX7wDBBHHbK/XCc=\\n-----END RSA PRIVATE KEY-----\\n\",\n  \"uri\" : \"https://api.opscode.com/organizations/jclouds/clients/adriancole-jcloudstest\",\n  \"validator\" : false\n}\n"
  },
  {
    "path": "apis/chef/src/test/resources/client.json",
    "content": "{ \"certificate\" : \"-----BEGIN CERTIFICATE-----\\nMIIClzCCAgCgAwIBAgIBATANBgkqhkiG9w0BAQUFADCBnjELMAkGA1UEBhMCVVMx\\nEzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxFjAUBgNVBAoM\\nDU9wc2NvZGUsIEluYy4xHDAaBgNVBAsME0NlcnRpZmljYXRlIFNlcnZpY2UxMjAw\\nBgNVBAMMKW9wc2NvZGUuY29tL2VtYWlsQWRkcmVzcz1hdXRoQG9wc2NvZGUuY29t\\nMB4XDTEwMDczMDIwNDEzMFoXDTIwMDcyNzIwNDEzMFowADCCASIwDQYJKoZIhvcN\\nAQEBBQADggEPADCCAQoCggEBAMm9mSSahptCikfvJ30CTbEnfhfbVzTFewnznFuo\\n7KrPBGYIlUdPYQ9SGDo+GKjNKiTjZYMoOMUVnsHUhu0Ez49ZSaVQInWvbF8tvpM8\\nmoGQNQJtDmXG6m+YaHiA4HF/ng2u/bNLtA6Jo3HzvRCobxywc/szPt0Kj0ZD1fJ2\\nE237Ph41c8zlOg9QdF0d/iD2WZdgJ1rNndKoZ0rR3A1L50VUND+PNmMDfVYHHjmb\\naT89AwihCeU8eUk7m/JNP87f1QDB0Gny0rkDC3drOGS7jmabTf/7gLE5sYq3qnd+\\n8/vGU3QWyfCxKSfogl7kn5uWlIe4sOqMb06GNgC+d/oytlECAwEAATANBgkqhkiG\\n9w0BAQUFAAOBgQBftzSZxstWw60GqRTDNN/F2GnrdtnKBoXzHww3r6jtGEylYq20\\n5KfKpEx+sPX0gyZuYJiXC2CkEjImAluWKcdN9ZF6VD541sheAjbiaU7q7ZsztTxF\\nWUH2tCvHeDXYKPKek3QzL7bYpUhLnCN/XxEv6ibeMDwtI7f5qpk2Aspzcw==\\n-----END CERTIFICATE-----\\n\",\n  \"clientname\" : \"adriancole-jcloudstest\",\n  \"name\" : \"adriancole-jcloudstest\",\n  \"orgname\" : \"jclouds\",\n  \"private_key\" : \"-----BEGIN RSA PRIVATE KEY-----\\nMIIEpQIBAAKCAQEAyb2ZJJqGm0KKR+8nfQJNsSd+F9tXNMV7CfOcW6jsqs8EZgiV\\nR09hD1IYOj4YqM0qJONlgyg4xRWewdSG7QTPj1lJpVAida9sXy2+kzyagZA1Am0O\\nZcbqb5hoeIDgcX+eDa79s0u0DomjcfO9EKhvHLBz+zM+3QqPRkPV8nYTbfs+HjVz\\nzOU6D1B0XR3+IPZZl2AnWs2d0qhnStHcDUvnRVQ0P482YwN9VgceOZtpPz0DCKEJ\\n5Tx5STub8k0/zt/VAMHQafLSuQMLd2s4ZLuOZptN//uAsTmxireqd37z+8ZTdBbJ\\n8LEpJ+iCXuSfm5aUh7iw6oxvToY2AL53+jK2UQIDAQABAoIBAQDA88B3i/xWn0vX\\nBVxFamCYoecuNjGwXXkSyZew616A+EOCu47bh4aTurdFbYL0YFaAtaWvzlaN2eHg\\nDb+HDuTefE29+WkcGk6SshPmiz5T0XOCAICWw6wSVDkHmGwS4jZvbAFm7W8nwGk9\\nYhxgxFiRngswJZFopOLoF5WXs2td8guIYNslMpo7tu50iFnBHwKO2ZsPAk8t9nnS\\nxlDavKruymEmqHCr3+dtio5eaenJcp3fjoXBQOKUk3ipII29XRB8NqeCVV/7Kxwq\\nckqOBEbRwBclckyIbD+RiAgKvOelORjEiE9R42vuqvxRA6k9kd9o7utlX0AUtpEn\\n3gZc6LepAoGBAP9ael5Y75+sK2JJUNOOhO8ae45cdsilp2yI0X+UBaSuQs2+dyPp\\nkpEHAxd4pmmSvn/8c9TlEZhr+qYbABXVPlDncxpIuw2Ajbk7s/S4XaSKsRqpXL57\\nzj/QOqLkRk8+OVV9q6lMeQNqLtEj1u6JPviX70Ro+FQtRttNOYbfdP/fAoGBAMpA\\nXjR5woV5sUb+REg9vEuYo8RSyOarxqKFCIXVUNsLOx+22+AK4+CQpbueWN7jotrl\\nYD6uT6svWi3AAC7kiY0UI/fjVPRCUi8tVoQUE0TaU5VLITaYOB+W/bBaDE4M9560\\n1NuDWO90baA5dfU44iuzva02rGJXK9+nS3o8nk/PAoGBALOL6djnDe4mwAaG6Jco\\ncd4xr8jkyPzCRZuyBCSBbwphIUXLc7hDprPky064ncJD1UDmwIdkXd/fpMkg2QmA\\n/CUk6LEFjMisqHojOaCL9gQZJPhLN5QUN2x1PJWGjs1vQh8Tkx0iUUCOa8bQPXNR\\n+34OTsW6TUna4CSZAycLfhffAoGBAIggVsefBCvuQkF0NeUhmDCRZfhnd8y55RHR\\n1HCvqKIlpv+rhcX/zmyBLuteopYyRJRsOiE2FW00i8+rIPRu4Z3Q5nybx7w3PzV9\\noHN5R5baE9OyI4KpZWztpYYitZF67NcnAvVULHHOvVJQGnKYfLHJYmrJF7GA1ojM\\nAuMdFbjFAoGAPxUhxwFy8gaqBahKUEZn4F81HFP5ihGhkT4QL6AFPO2e+JhIGjuR\\n27+85hcFqQ+HHVtFsm81b/a+R7P4UuCRgc8eCjxQMoJ1Xl4n7VbjPbHMnIN0Ryvd\\nO4ZpWDWYnCO021JTOUUOJ4J/y0416Bvkw0z59y7sNX7wDBBHHbK/XCc=\\n-----END RSA PRIVATE KEY-----\\n\",\n  \"uri\" : \"https://api.opscode.com/organizations/jclouds/clients/adriancole-jcloudstest\",\n  \"validator\" : false,\n  \"public_key\" : \"-----BEGIN PUBLIC KEY-----\\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyb2ZJJqGm0KKR+8nfQJN\\nsSd+F9tXNMV7CfOcW6jsqs8EZgiVR09hD1IYOj4YqM0qJONlgyg4xRWewdSG7QTP\\nj1lJpVAida9sXy2+kzyagZA1Am0OZcbqb5hoeIDgcX+eDa79s0u0DomjcfO9EKhv\\nHLBz+zM+3QqPRkPV8nYTbfs+HjVzzOU6D1B0XR3+IPZZl2AnWs2d0qhnStHcDUvn\\nRVQ0P482YwN9VgceOZtpPz0DCKEJ5Tx5STub8k0/zt/VAMHQafLSuQMLd2s4ZLuO\\nZptN//uAsTmxireqd37z+8ZTdBbJ8LEpJ+iCXuSfm5aUh7iw6oxvToY2AL53+jK2\\nUQIDAQAB\\n-----END PUBLIC KEY-----\\n\"\n}\n"
  },
  {
    "path": "apis/chef/src/test/resources/clients_list.json",
    "content": "{\n  \"chef-webui\": \"http://localhost:4000/clients/chef-webui\",\n  \"chef-validator\": \"http://localhost:4000/clients/chef-validator\",\n  \"adam\": \"http://localhost:4000/clients/adam\"\n}\n"
  },
  {
    "path": "apis/chef/src/test/resources/data_list.json",
    "content": "{\n    \"users\": \"http://localhost:4000/data/users\",\n    \"applications\": \"http://localhost:4000/data/applications\"\n}\n"
  },
  {
    "path": "apis/chef/src/test/resources/env_cookbooks.json",
    "content": "{\n  \"apache2\" => {\n    \"url\" => \"http://localhost:4000/cookbooks/apache2\",\n    \"versions\" => [\n      {\"url\" => \"http://localhost:4000/cookbooks/apache2/5.1.0\",\n       \"version\" => \"5.1.0\"},\n      {\"url\" => \"http://localhost:4000/cookbooks/apache2/4.2.0\",\n       \"version\" => \"4.2.0\"}\n    ]\n  },\n  \"nginx\" => {\n    \"url\" => \"http://localhost:4000/cookbooks/nginx\",\n    \"versions\" => [\n      {\"url\" => \"http://localhost:4000/cookbooks/nginx/1.0.0\",\n       \"version\" => \"1.0.0\"},\n      {\"url\" => \"http://localhost:4000/cookbooks/nginx/0.3.0\",\n       \"version\" => \"0.3.0\"}\n    ]\n  }\n}\n"
  },
  {
    "path": "apis/chef/src/test/resources/environment_recipes.json",
    "content": "[\n  \"ant\",\n  \"apache2\",\n  \"apache2::mod_auth_openid\"\n]\n \n"
  },
  {
    "path": "apis/chef/src/test/resources/group-update.json",
    "content": "{\"groupname\":\"admins\",\"actors\":{\"clients\":[\"abiquo\"],\"groups\":[\"admins\"],\"users\":[\"nacx\"]}}"
  },
  {
    "path": "apis/chef/src/test/resources/group.json",
    "content": "{\n  \"actors\" : [ \"abiquo\",\n      \"nacx\",\n      \"pivotal\"\n    ],\n  \"clients\" : [ \"abiquo\" ],\n  \"groupname\" : \"admins\",\n  \"groups\" : [ \"billing-admins\" ],\n  \"name\" : \"admins\",\n  \"orgname\" : \"nacx\",\n  \"users\" : [ \"nacx\",\n      \"pivotal\"\n  ]\n}\n"
  },
  {
    "path": "apis/chef/src/test/resources/groups.json",
    "content": "{\n  \"965f2db33d302ed4625d172e0bc36920\" : \"https://api.opscode.com/organizations/nacx/groups/965f2db33d302ed4625d172e0bc36920\",\n  \"admins\" : \"https://api.opscode.com/organizations/nacx/groups/admins\",\n  \"billing-admins\" : \"https://api.opscode.com/organizations/nacx/groups/billing-admins\",\n  \"clients\" : \"https://api.opscode.com/organizations/nacx/groups/clients\",\n  \"users\" : \"https://api.opscode.com/organizations/nacx/groups/users\"\n}"
  },
  {
    "path": "apis/chef/src/test/resources/logback.xml",
    "content": "<?xml version=\"1.0\"?>\n<configuration scan=\"false\">\n    <appender name=\"FILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds.log</file>\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n    <appender name=\"WIREFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds-wire.log</file>\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <root>\n        <level value=\"warn\" />\n    </root>\n\n    <logger name=\"org.jclouds\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"FILE\" />\n    </logger>\n    <logger name=\"jclouds.wire\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n    <logger name=\"jclouds.headers\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n\n</configuration>\n"
  },
  {
    "path": "apis/chef/src/test/resources/mysql-cookbook.json",
    "content": "{ \"attributes\" : [ { \"checksum\" : \"548fa4bc548b8b59ac98fffee8e81f4a\",\n        \"name\" : \"server.rb\",\n        \"path\" : \"attributes/server.rb\",\n        \"specificity\" : \"default\",\n        \"url\" : \"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-548fa4bc548b8b59ac98fffee8e81f4a?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774082&Signature=MsgggSKS0T1q1Lc72nJpHORBQX0%3D\"\n      } ],\n  \"chef_type\" : \"cookbook_version\",\n  \"cookbook_name\" : \"mysql\",\n  \"definitions\" : [  ],\n  \"files\" : [  ],\n  \"json_class\" : \"Chef::CookbookVersion\",\n  \"libraries\" : [ { \"checksum\" : \"b2eb0760c07734be9c637dcffc86175a\",\n        \"name\" : \"database.rb\",\n        \"path\" : \"libraries/database.rb\",\n        \"specificity\" : \"default\",\n        \"url\" : \"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-b2eb0760c07734be9c637dcffc86175a?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774082&Signature=CvVbxzrA%2Fuxc59ZjLR5BsMozfxk%3D\"\n      } ],\n  \"metadata\" : { \"attributes\" : { \"mysql/bind_address\" : { \"calculated\" : false,\n              \"choice\" : [  ],\n              \"default\" : \"ipaddress\",\n              \"description\" : \"Address that mysqld should listen on\",\n              \"display_name\" : \"MySQL Bind Address\",\n              \"recipes\" : [  ],\n              \"required\" : \"optional\",\n              \"type\" : \"string\"\n            },\n          \"mysql/datadir\" : { \"calculated\" : false,\n              \"choice\" : [  ],\n              \"default\" : \"/var/lib/mysql\",\n              \"description\" : \"Location of mysql databases\",\n              \"display_name\" : \"MySQL Data Directory\",\n              \"recipes\" : [  ],\n              \"required\" : \"optional\",\n              \"type\" : \"string\"\n            },\n          \"mysql/ec2_path\" : { \"calculated\" : false,\n              \"choice\" : [  ],\n              \"default\" : \"/mnt/mysql\",\n              \"description\" : \"Location of mysql directory on EC2 instance EBS volumes\",\n              \"display_name\" : \"MySQL EC2 Path\",\n              \"recipes\" : [  ],\n              \"required\" : \"optional\",\n              \"type\" : \"string\"\n            },\n          \"mysql/server_root_password\" : { \"calculated\" : false,\n              \"choice\" : [  ],\n              \"default\" : \"randomly generated\",\n              \"description\" : \"Randomly generated password for the mysqld root user\",\n              \"display_name\" : \"MySQL Server Root Password\",\n              \"recipes\" : [  ],\n              \"required\" : \"optional\",\n              \"type\" : \"string\"\n            },\n          \"mysql/tunable\" : { \"calculated\" : false,\n              \"choice\" : [  ],\n              \"description\" : \"Hash of MySQL tunable attributes\",\n              \"display_name\" : \"MySQL Tunables\",\n              \"recipes\" : [  ],\n              \"required\" : \"optional\",\n              \"type\" : \"hash\"\n            },\n          \"mysql/tunable/back_log\" : { \"calculated\" : false,\n              \"choice\" : [  ],\n              \"default\" : \"128\",\n              \"display_name\" : \"MySQL Tunable Back Log\",\n              \"recipes\" : [  ],\n              \"required\" : \"optional\",\n              \"type\" : \"string\"\n            },\n          \"mysql/tunable/key_buffer\" : { \"calculated\" : false,\n              \"choice\" : [  ],\n              \"default\" : \"250M\",\n              \"display_name\" : \"MySQL Tuntable Key Buffer\",\n              \"recipes\" : [  ],\n              \"required\" : \"optional\",\n              \"type\" : \"string\"\n            },\n          \"mysql/tunable/max_connections\" : { \"calculated\" : false,\n              \"choice\" : [  ],\n              \"default\" : \"800\",\n              \"display_name\" : \"MySQL Tunable Max Connections\",\n              \"recipes\" : [  ],\n              \"required\" : \"optional\",\n              \"type\" : \"string\"\n            },\n          \"mysql/tunable/max_heap_table_size\" : { \"calculated\" : false,\n              \"choice\" : [  ],\n              \"default\" : \"32M\",\n              \"display_name\" : \"MySQL Tunable Max Heap Table Size\",\n              \"recipes\" : [  ],\n              \"required\" : \"optional\",\n              \"type\" : \"string\"\n            },\n          \"mysql/tunable/net_read_timeout\" : { \"calculated\" : false,\n              \"choice\" : [  ],\n              \"default\" : \"30\",\n              \"display_name\" : \"MySQL Tunable Net Read Timeout\",\n              \"recipes\" : [  ],\n              \"required\" : \"optional\",\n              \"type\" : \"string\"\n            },\n          \"mysql/tunable/net_write_timeout\" : { \"calculated\" : false,\n              \"choice\" : [  ],\n              \"default\" : \"30\",\n              \"display_name\" : \"MySQL Tunable Net Write Timeout\",\n              \"recipes\" : [  ],\n              \"required\" : \"optional\",\n              \"type\" : \"string\"\n            },\n          \"mysql/tunable/table_cache\" : { \"calculated\" : false,\n              \"choice\" : [  ],\n              \"default\" : \"128\",\n              \"display_name\" : \"MySQL Tunable Table Cache\",\n              \"recipes\" : [  ],\n              \"required\" : \"optional\",\n              \"type\" : \"string\"\n            },\n          \"mysql/tunable/wait_timeout\" : { \"calculated\" : false,\n              \"choice\" : [  ],\n              \"default\" : \"180\",\n              \"display_name\" : \"MySQL Tunable Wait Timeout\",\n              \"recipes\" : [  ],\n              \"required\" : \"optional\",\n              \"type\" : \"string\"\n            }\n        },\n      \"conflicting\" : {  },\n      \"dependencies\" : { \"openssl\" : \"\" },\n      \"description\" : \"Installs and configures mysql for client or server\",\n      \"groupings\" : {  },\n      \"license\" : \"Apache 2.0\",\n      \"long_description\" : \"= DESCRIPTION:\\n\\nInstalls and configures MySQL client or server.\\n\\n= REQUIREMENTS:\\n\\n== Platform:\\n\\nBest tested on Ubuntu 9.04,9.10. On EC2, requires platform that supports -o bind option for the 'mount' command.\\n\\n== Cookbooks:\\n\\nRequires Opscode's openssl cookbook for secure password generation.\\n\\n= ATTRIBUTES: \\n\\n* mysql[:server_root_password] - Set the server's root password with this, default is a randomly generated password with OpenSSL::Random.random_bytes.\\n* mysql[:server_repl_password] - Set the replication user 'repl' password with this, default is a randomly generated password with OpenSSL::Random.random_bytes.\\n* mysql[:server_debian_password] - Set the debian-sys-maint user password with this, default is a randomly generated password with OpenSSL::Random.random_bytes.\\n* mysql[:bind_address] - Listen address for MySQLd, default is node's ipaddress.\\n* mysql[:datadir] - Location for mysql data directory, default is \\\"/var/lib/mysql\\\" \\n* mysql[:ec2_path] - location of mysql datadir on EC2 nodes, default \\\"/mnt/mysql\\\" \\n\\nPerformance tuning attributes, each corresponds to the same-named parameter in my.cnf; default values listed\\n\\n* mysql[:tunable][:key_buffer]          = \\\"250M\\\"\\n* mysql[:tunable][:max_connections]     = \\\"800\\\" \\n* mysql[:tunable][:wait_timeout]        = \\\"180\\\" \\n* mysql[:tunable][:net_write_timeout]   = \\\"30\\\" \\n* mysql[:tunable][:net_write_timeout]   = \\\"30\\\" \\n* mysql[:tunable][:back_log]            = \\\"128\\\" \\n* mysql[:tunable][:table_cache]         = \\\"128\\\" \\n* mysql[:tunable][:max_heap_table_size] = \\\"32M\\\" \\n\\n= USAGE:\\n\\nOn client nodes,\\n\\n  include_recipe \\\"mysql::client\\\"\\n  \\nAs the common use case is on systems with Ruby, we also install the MySQL RubyGem. Because we may want to be able to use the gem within another Chef recipe, we make sure the mysql development package and gem are installed first. The key is this:\\n\\n  r = package ... do\\n    action :nothing\\n  end\\n  \\n  r.run_action(:install)\\n  \\nThis creates a resource object for the package and does the installation before other recipes are parsed. You'll need to have the C compiler and such (ie, build-essential on Ubuntu) before running the recipes, but we already do that when installing Chef :-). If you want to be able to access a MySQL database via Ruby within another recipe, you could do so, like so:\\n\\n  Gem.clear_paths # needed for Chef to find the gem...\\n  require 'mysql' # requires the mysql gem\\n\\n  execute \\\"create #{node[:railsapp][:db][:database]} database\\\" do\\n    command \\\"/usr/bin/mysqladmin -u root -p#{node[:mysql][:server_root_password]} create #{node[:railsapp][:db][:database]}\\\"\\n    not_if do\\n      m = Mysql.new(\\\"localhost\\\", \\\"root\\\", @node[:mysql][:server_root_password])\\n      m.list_dbs.include?(@node[:railsapp][:db][:database])\\n    end\\n  end\\n\\nOn server nodes, \\n\\n  include_recipe \\\"mysql::server\\\"\\n  \\nOn Debian/Ubuntu this will preseed the MySQL package with the randomly generated root password. You can of course change the password afterward, but this makes sure that there's a good password set. You can view it in the node data in the Chef Server webui. Sets a new password for debian-sys-maint user as well.\\n\\nAlso sets up 'repl' user grants for replication slaves.\\n\\nOn EC2 nodes,\\n\\n  include_recipe \\\"mysql::server_ec2\\\"\\n  \\nWhen the ec2_path doesn't exist we look for a mounted filesystem (eg, EBS) and move the datadir there.\\n\\nThe client recipe is already included by server and 'default' recipes.\\n\\n= LICENSE and AUTHOR:\\n      \\nAuthor:: Joshua Timberman (<joshua@opscode.com>)\\nAuthor:: AJ Christensen (<aj@opscode.com>)\\n\\nCopyright:: 2009, Opscode, Inc\\n\\nLicensed under the Apache License, Version 2.0 (the \\\"License\\\");\\nyou may not use this file except in compliance with the License.\\nYou may obtain a copy of the License at\\n\\n    http://www.apache.org/licenses/LICENSE-2.0\\n\\nUnless required by applicable law or agreed to in writing, software\\ndistributed under the License is distributed on an \\\"AS IS\\\" BASIS,\\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\\nSee the License for the specific language governing permissions and\\nlimitations under the License.\\n\",\n      \"maintainer\" : \"Opscode, Inc.\",\n      \"maintainer_email\" : \"cookbooks@opscode.com\",\n      \"name\" : \"mysql\",\n      \"platforms\" : { \"debian\" : \"\",\n          \"ubuntu\" : \"\"\n        },\n      \"providing\" : {  },\n      \"recipes\" : { \"mysql::client\" : \"Installs packages required for mysql clients using run_action magic\",\n          \"mysql::server\" : \"Installs packages required for mysql servers w/o manual intervention\",\n          \"mysql::server_ec2\" : \"Performs EC2-specific mountpoint manipulation\"\n        },\n      \"recommendations\" : {  },\n      \"replacing\" : {  },\n      \"suggestions\" : {  },\n      \"version\" : \"0.21.2\"\n    },\n  \"name\" : \"mysql-0.21.2\",\n  \"providers\" : [ { \"checksum\" : \"b994881a2aba60e32c4b6408ffba993d\",\n        \"name\" : \"database.rb\",\n        \"path\" : \"providers/database.rb\",\n        \"specificity\" : \"default\",\n        \"url\" : \"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-b994881a2aba60e32c4b6408ffba993d?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774082&Signature=2XMRbryCmEqirCWLCvrXoenYubw%3D\"\n      } ],\n  \"recipes\" : [ { \"checksum\" : \"f51bd8122b7dccc9f4656319fef3252a\",\n        \"name\" : \"server_ec2.rb\",\n        \"path\" : \"recipes/server_ec2.rb\",\n        \"specificity\" : \"default\",\n        \"url\" : \"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-f51bd8122b7dccc9f4656319fef3252a?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774082&Signature=BUR2mosCvmoOKq4Mkh3JUG0MY38%3D\"\n      },\n      { \"checksum\" : \"80daa897597560372d017c58c4df0e3c\",\n        \"name\" : \"server.rb\",\n        \"path\" : \"recipes/server.rb\",\n        \"specificity\" : \"default\",\n        \"url\" : \"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-80daa897597560372d017c58c4df0e3c?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774082&Signature=bU3j9Nw%2BnuIroXKrlJZe7tjaugA%3D\"\n      },\n      { \"checksum\" : \"bd3ba2d05dea6a8cf0dc2a45f540cc32\",\n        \"name\" : \"default.rb\",\n        \"path\" : \"recipes/default.rb\",\n        \"specificity\" : \"default\",\n        \"url\" : \"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-bd3ba2d05dea6a8cf0dc2a45f540cc32?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774082&Signature=7haumT5EtEM2h8l32efqV%2Fik%2BdY%3D\"\n      },\n      { \"checksum\" : \"a1d679c7480267cd9b69e3194c7e45ab\",\n        \"name\" : \"client.rb\",\n        \"path\" : \"recipes/client.rb\",\n        \"specificity\" : \"default\",\n        \"url\" : \"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-a1d679c7480267cd9b69e3194c7e45ab?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774082&Signature=ZhfTiwv1aXC7HZMnW8A7i4vkMCM%3D\"\n      }\n    ],\n  \"resources\" : [ { \"checksum\" : \"8aa8e2cafe54c2932c7aa65d62ec2695\",\n        \"name\" : \"database.rb\",\n        \"path\" : \"resources/database.rb\",\n        \"specificity\" : \"default\",\n        \"url\" : \"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-8aa8e2cafe54c2932c7aa65d62ec2695?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774082&Signature=6URS94f1HpRibHC%2FhBkr7Eg3dVA%3D\"\n      } ],\n  \"root_files\" : [ { \"checksum\" : \"e9278fc99fd668bdce33d72dc71fade9\",\n        \"name\" : \"README.rdoc\",\n        \"path\" : \"README.rdoc\",\n        \"specificity\" : \"default\",\n        \"url\" : \"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-e9278fc99fd668bdce33d72dc71fade9?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774082&Signature=KPgAGqShEO5SGzz8oRdwIInPUOc%3D\"\n      },\n      { \"checksum\" : \"8d2f9635f4817ff905a4124e09ec6c59\",\n        \"name\" : \"metadata.rb\",\n        \"path\" : \"metadata.rb\",\n        \"specificity\" : \"default\",\n        \"url\" : \"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-8d2f9635f4817ff905a4124e09ec6c59?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774082&Signature=fPF2iY7tNrq%2FuNrCjRLImP9vRbA%3D\"\n      },\n      { \"checksum\" : \"e6804b8f3e6dfdbbece9d319537ffea1\",\n        \"name\" : \"metadata.json\",\n        \"path\" : \"metadata.json\",\n        \"specificity\" : \"default\",\n        \"url\" : \"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-e6804b8f3e6dfdbbece9d319537ffea1?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774082&Signature=EVsALLreeAA41%2BiPAfPt%2FxFEIYI%3D\"\n      }\n    ],\n  \"templates\" : [ { \"checksum\" : \"689c1b6fbb242b6c508384e56646341d\",\n        \"name\" : \"my.cnf.erb\",\n        \"path\" : \"templates/ubuntu-9.10/my.cnf.erb\",\n        \"specificity\" : \"ubuntu-9.10\",\n        \"url\" : \"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-689c1b6fbb242b6c508384e56646341d?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774082&Signature=2ugp0XVvvUktYdBxfC9bCZBjOs4%3D\"\n      },\n      { \"checksum\" : \"16b036a0bb31957a77e9b825cf616cc5\",\n        \"name\" : \"mysql-server.seed.erb\",\n        \"path\" : \"templates/default/mysql-server.seed.erb\",\n        \"specificity\" : \"default\",\n        \"url\" : \"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-16b036a0bb31957a77e9b825cf616cc5?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774082&Signature=50bRvt6GQqFEcfYtaIsq1d4a4c8%3D\"\n      },\n      { \"checksum\" : \"932b51ddddcbd24ee10a76ecae33b8ba\",\n        \"name\" : \"grants.sql.erb\",\n        \"path\" : \"templates/default/grants.sql.erb\",\n        \"specificity\" : \"default\",\n        \"url\" : \"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-932b51ddddcbd24ee10a76ecae33b8ba?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774082&Signature=RHR0obLFcsN1M9tL28IH4Tcur5g%3D\"\n      },\n      { \"checksum\" : \"7746560b37ac8d4a0cf68befbecbd8a3\",\n        \"name\" : \"my.cnf.erb\",\n        \"path\" : \"templates/default/my.cnf.erb\",\n        \"specificity\" : \"default\",\n        \"url\" : \"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-7746560b37ac8d4a0cf68befbecbd8a3?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774082&Signature=W7Nqkvhw2TBrlDvcM2rlA4Oj5%2Bk%3D\"\n      },\n      { \"checksum\" : \"63bd67fae6d297e8f658e9c0ad01a411\",\n        \"name\" : \"my.cnf.erb\",\n        \"path\" : \"templates/centos/my.cnf.erb\",\n        \"specificity\" : \"centos\",\n        \"url\" : \"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-63bd67fae6d297e8f658e9c0ad01a411?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774082&Signature=oFcRya56f%2F4oJBGrIvk4XcWQFm4%3D\"\n      },\n      { \"checksum\" : \"689c1b6fbb242b6c508384e56646341d\",\n        \"name\" : \"my.cnf.erb\",\n        \"path\" : \"templates/ubuntu-10.04/my.cnf.erb\",\n        \"specificity\" : \"ubuntu-10.04\",\n        \"url\" : \"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-689c1b6fbb242b6c508384e56646341d?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774082&Signature=2ugp0XVvvUktYdBxfC9bCZBjOs4%3D\"\n      },\n      { \"checksum\" : \"63bd67fae6d297e8f658e9c0ad01a411\",\n        \"name\" : \"my.cnf.erb\",\n        \"path\" : \"templates/redhat/my.cnf.erb\",\n        \"specificity\" : \"redhat\",\n        \"url\" : \"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-63bd67fae6d297e8f658e9c0ad01a411?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774082&Signature=oFcRya56f%2F4oJBGrIvk4XcWQFm4%3D\"\n      },\n      { \"checksum\" : \"d2244150a145b3f658cd37c13269fafc\",\n        \"name\" : \"port_mysql.erb\",\n        \"path\" : \"templates/default/port_mysql.erb\",\n        \"specificity\" : \"default\",\n        \"url\" : \"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-d2244150a145b3f658cd37c13269fafc?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774082&Signature=23iHcjwpNOvlNf%2BlrKcV2pkU7uo%3D\"\n      },\n      { \"checksum\" : \"2e08553db526f5f80c28b343f6a616cb\",\n        \"name\" : \"debian.cnf.erb\",\n        \"path\" : \"templates/default/debian.cnf.erb\",\n        \"specificity\" : \"default\",\n        \"url\" : \"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-2e08553db526f5f80c28b343f6a616cb?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774082&Signature=VdcFYxnLUkj1tS3k8DovrzZEA7E%3D\"\n      },\n      { \"checksum\" : \"1e5068eec65b51f5a327580fb0af4677\",\n        \"name\" : \"my.cnf.erb\",\n        \"path\" : \"templates/ubuntu-8.04/my.cnf.erb\",\n        \"specificity\" : \"ubuntu-8.04\",\n        \"url\" : \"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-1e5068eec65b51f5a327580fb0af4677?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277774082&Signature=D5lPeu1UQvA9pEXZm5nVOwj3WIo%3D\"\n      }\n    ],\n  \"version\" : \"0.21.2\"\n}"
  },
  {
    "path": "apis/chef/src/test/resources/node.json",
    "content": "{ \"automatic\" : {  },\n  \"chef_environment\" : \"prod\",\n  \"chef_type\" : \"node\",\n  \"default\" : {  },\n  \"json_class\" : \"Chef::Node\",\n  \"name\" : \"adrian-jcloudstest\",\n  \"normal\" : { \"tomcat6\" : { \"ssl_port\" : 8433 } },\n  \"override\" : {  },\n  \"run_list\" : [ \"recipe[java]\" ]\n}"
  },
  {
    "path": "apis/chef/src/test/resources/nodes_list.json",
    "content": "{\n  \"blah\": \"https://api.opscode.com/org/directory/nodes/blah\",\n  \"boxer\": \"https://api.opscode.com/org/directory/nodes/boxer\",\n  \"blarrrrgh\": \"https://api.opscode.com/org/directory/nodes/blarrrrgh\"\n}\n"
  },
  {
    "path": "apis/chef/src/test/resources/privkey.txt",
    "content": "-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEA0ueqo76MXuP6XqZBILFziH/9AI7C6PaN5W0dSvkr9yInyGHS\nz/IR1+4tqvP2qlfKVKI4CP6BFH251Ft9qMUBuAsnlAVQ1z0exDtIFFOyQCdR7iXm\njBIWMSS4buBwRQXwDK7id1OxtU23qVJv+xwEV0IzaaSJmaGLIbvRBD+qatfUuQJB\nMU/04DdJIwvLtZBYdC2219m5dUBQaa4bimL+YN9EcsDzD9h9UxQo5ReK7b3cNMzJ\nBKJWLzFBcJuePMzAnLFktr/RufX4wpXe6XJxoVPaHo72GorLkwnQ0HYMTY8rehT4\nmDi1FI969LHCFFaFHSAaRnwdXaQkJmSfcxzCYQIDAQABAoIBAQCW3I4sKN5B9jOe\nxq/pkeWBq4OvhW8Ys1yW0zFT8t6nHbB1XrwscQygd8gE9BPqj3e0iIEqtdphbPmj\nVHqTYbC0FI6QDClifV7noTwTBjeIOlgZ0NSUN0/WgVzIOxUz2mZ2vBZUovKILPqG\nTOi7J7RXMoySMdcXpP1f+PgvYNcnKsT72UcWaSXEV8/zo+Zm/qdGPVWwJonri5Mp\nDVm5EQSENBiRyt028rU6ElXORNmoQpVjDVqZ1gipzXkifdjGyENw2rt4V/iKYD7V\n5iqXOsvP6Cemf4gbrjunAgDG08S00kiUgvVWcdXW+dlsR2nCvH4DOEe3AYYh/aH8\nDxEE7FbtAoGBAPcNO8fJ56mNw0ow4Qg38C+Zss/afhBOCfX4O/SZKv/roRn5+gRM\nKRJYSVXNnsjPI1plzqR4OCyOrjAhtuvL4a0DinDzf1+fiztyNohwYsW1vYmqn3ti\nEN0GhSgE7ppZjqvLQ3f3LUTxynhA0U+k9wflb4irIlViTUlCsOPkrNJDAoGBANqL\nQ+vvuGSsmRLU/Cenjy+Mjj6+QENg51dz34o8JKuVKIPKU8pNnyeLa5fat0qD2MHm\nOB9opeQOcw0dStodxr6DB3wi83bpjeU6BWUGITNiWEaZEBrQ0aiqNJJKrrHm8fAZ\n9o4l4oHc4hI0kYVYYDuxtKuVJrzZiEapTwoOcYiLAoGBAI/EWbeIHZIj9zOjgjEA\nLHvm25HtulLOtyk2jd1njQhlHNk7CW2azIPqcLLH99EwCYi/miNH+pijZ2aHGCXb\n/bZrSxM0ADmrZKDxdB6uGCyp+GS2sBxjEyEsfCyvwhJ8b3Q100tqwiNO+d5FCglp\nHICx2dgUjuRVUliBwOK93nx1AoGAUI8RhIEjOYkeDAESyhNMBr0LGjnLOosX+/as\nqiotYkpjWuFULbibOFp+WMW41vDvD9qrSXir3fstkeIAW5KqVkO6mJnRoT3Knnra\nzjiKOITCAZQeiaP8BO5o3pxE9TMqb9VCO3ffnPstIoTaN4syPg7tiGo8k1SklVeH\n2S8lzq0CgYAKG2fljIYWQvGH628rp4ZcXS4hWmYohOxsnl1YrszbJ+hzR+IQOhGl\nYlkUQYXhy9JixmUUKtH+NXkKX7Lyc8XYw5ETr7JBT3ifs+G7HruDjVG78EJVojbd\n8uLA+DdQm5mg4vd1GTiSK65q/3EeoBlUaVor3HhLFki+i9qpT8CBsg==\n-----END RSA PRIVATE KEY-----"
  },
  {
    "path": "apis/chef/src/test/resources/pubkey.txt",
    "content": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0ueqo76MXuP6XqZBILFz\niH/9AI7C6PaN5W0dSvkr9yInyGHSz/IR1+4tqvP2qlfKVKI4CP6BFH251Ft9qMUB\nuAsnlAVQ1z0exDtIFFOyQCdR7iXmjBIWMSS4buBwRQXwDK7id1OxtU23qVJv+xwE\nV0IzaaSJmaGLIbvRBD+qatfUuQJBMU/04DdJIwvLtZBYdC2219m5dUBQaa4bimL+\nYN9EcsDzD9h9UxQo5ReK7b3cNMzJBKJWLzFBcJuePMzAnLFktr/RufX4wpXe6XJx\noVPaHo72GorLkwnQ0HYMTY8rehT4mDi1FI969LHCFFaFHSAaRnwdXaQkJmSfcxzC\nYQIDAQAB\n-----END PUBLIC KEY-----"
  },
  {
    "path": "apis/chef/src/test/resources/roles_list.json",
    "content": "{\n    \"webserver\": \"http://localhost:4000/roles/webserver\",\n    \"smtpserver\": \"http://localhost:4000/roles/smtpserver\"\n}\n"
  },
  {
    "path": "apis/chef/src/test/resources/sandbox.json",
    "content": "{\n         \"_rev\": \"1-8c27b0ea4c2b7aaedbb44cfbdfcc11b2\",\n         \"json_class\": \"Chef::Sandbox\",\n         \"is_completed\": false,\n         \"create_time\": \"2010-07-07T03:36:00+00:00\",\n         \"chef_type\": \"sandbox\",\n         \"checksums\": [],\n         \"name\": \"f9d6d9b72bae465890aae87969f98a9c\",\n         \"guid\": \"f9d6d9b72bae465890aae87969f98a9c\"\n     }\n\n\n"
  },
  {
    "path": "apis/chef/src/test/resources/search_role.json",
    "content": "{\n    \"total\": 1,\n    \"start\": 0,\n    \"rows\": [\n        {\n            \"name\": \"webserver\",\n            \"description\": \"The base role for systems that serve HTTP traffic\",\n            \"json_class\": \"Chef::Role\",\n            \"default_attributes\": {\n                \"apache2\": {\n                    \"listen_ports\": [\n                        \"80\",\n                        \"443\"\n                    ]\n                }\n            },\n            \"override_attributes\": {\n                \"apache2\": {\n                    \"max_children\": \"50\"\n                }\n            },\n            \"chef_type\": \"role\",\n            \"run_list\": [],\n            \"env_run_lists\": {\n                \"prod\": [\n                    \"recipe[apache2]\"\n                ],\n                \"staging\": [\n                    \"recipe[apache2::staging]\"\n                ]\n            }\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/chef/src/test/resources/search_role_empty.json",
    "content": "{\n    \"total\": 0,\n    \"start\": 0,\n    \"rows\": []\n}\n"
  },
  {
    "path": "apis/chef/src/test/resources/tomcat-cookbook.json",
    "content": "{ \"attributes\" : [ { \"checksum\" : \"6e3fd0d16a87a55c569da108194ecb29\",\n        \"name\" : \"tomcat6.rb\",\n        \"path\" : \"attributes/tomcat6.rb\",\n        \"specificity\" : \"default\",\n        \"url\" : \"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-6e3fd0d16a87a55c569da108194ecb29?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277771874&Signature=zvYjsgUXIC7Xj3MT8Wd93esDGJM%3D\"\n      } ],\n  \"chef_type\" : \"cookbook_version\",\n  \"cookbook_name\" : \"tomcat6\",\n  \"definitions\" : [  ],\n  \"files\" : [ { \"checksum\" : \"18e534a72652f3d53b197ca4e5027009\",\n        \"name\" : \"org.apache.tomcat.tomcat6.plist\",\n        \"path\" : \"files/default/org.apache.tomcat.tomcat6.plist\",\n        \"specificity\" : \"default\",\n        \"url\" : \"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-18e534a72652f3d53b197ca4e5027009?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277771874&Signature=M3fBL4t7uuYVXVah2PyZ8eL1QCc%3D\"\n      },\n      { \"checksum\" : \"6a35ce92050296862ea63b784529d2e0\",\n        \"name\" : \"logging.properties\",\n        \"path\" : \"files/default/logging.properties\",\n        \"specificity\" : \"default\",\n        \"url\" : \"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-6a35ce92050296862ea63b784529d2e0?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277771874&Signature=vRlKoye2%2Fwz8mdQI%2F3Ht916sllE%3D\"\n      }\n    ],\n  \"json_class\" : \"Chef::CookbookVersion\",\n  \"libraries\" : [ { \"checksum\" : \"2b6f7847142bb36823c570899669c54b\",\n        \"name\" : \"tomcat_manager.rb\",\n        \"path\" : \"libraries/tomcat_manager.rb\",\n        \"specificity\" : \"default\",\n        \"url\" : \"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-2b6f7847142bb36823c570899669c54b?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277771874&Signature=zxIoUKcGYWo9ir6qf1tTy3wvKZ4%3D\"\n      },\n      { \"checksum\" : \"24db7b7dd6f04f8da5fa2b282910ac08\",\n        \"name\" : \"tomcat.rb\",\n        \"path\" : \"libraries/tomcat.rb\",\n        \"specificity\" : \"default\",\n        \"url\" : \"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-24db7b7dd6f04f8da5fa2b282910ac08?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277771874&Signature=c4Gbn5kX0ZaPbWvk5LAcR77sITg%3D\"\n      }\n    ],\n  \"metadata\" : { \"attributes\" : { \"tomcat6/with_native\" : { \"calculated\" : false,\n              \"choice\" : [  ],\n              \"default\" : \"false\",\n              \"description\" : \"works for centos, install tomcat-native libraries\",\n              \"display_name\" : \"Tomcat native support\",\n              \"recipes\" : [  ],\n              \"required\" : \"optional\",\n              \"type\" : \"string\"\n            } },\n      \"conflicting\" : {  },\n      \"dependencies\" : {  },\n      \"description\" : \"Installs and configures all aspects of tomcat6 using custom local installation\",\n      \"groupings\" : {  },\n      \"license\" : \"Apache 2.0\",\n      \"long_description\" : \"= DESCRIPTION:\\n\\nInstalls Tomcat6\\n\\n= REQUIREMENTS:\\n\\n== Platform and Application Environment:\\n\\nTested on Centos 5.2 8.10. May work on other platforms, esp Redhat.\\nNeeds Java at least Java 5\\n\\n== Cookbooks:\\n\\nOpscode cookbooks, http://github.com/opscode/cookbooks/tree/master:\\n\\n* java\\n\\n= ATTRIBUTES: \\n\\n= USAGE:\\n\\n\\n= LICENSE and AUTHOR:\\n      \\nAuthor:: Edmund Haselwanter (<edmund@haselwanter.com>)\\nCopyright:: 2009, Edmund Haselwanter\\n\\nLicensed under the Apache License, Version 2.0 (the \\\"License\\\");\\nyou may not use this file except in compliance with the License.\\nYou may obtain a copy of the License at\\n\\n    http://www.apache.org/licenses/LICENSE-2.0\\n\\nUnless required by applicable law or agreed to in writing, software\\ndistributed under the License is distributed on an \\\"AS IS\\\" BASIS,\\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\\nSee the License for the specific language governing permissions and\\nlimitations under the License.\\n\",\n      \"maintainer\" : \"Opscode, Inc.\",\n      \"maintainer_email\" : \"cookbooks@opscode.com\",\n      \"name\" : \"tomcat6\",\n      \"platforms\" : { \"centos\" : \"\",\n          \"debian\" : \"\",\n          \"redhat\" : \"\",\n          \"ubuntu\" : \"\"\n        },\n      \"providing\" : {  },\n      \"recipes\" : { \"tomcat6\" : \"Main Tomcat 6 configuration\" },\n      \"recommendations\" : {  },\n      \"replacing\" : {  },\n      \"suggestions\" : {  },\n      \"version\" : \"0.1.0\"\n    },\n  \"name\" : \"tomcat6-0.1.0\",\n  \"providers\" : [  ],\n  \"recipes\" : [ { \"checksum\" : \"d45661e4b50f9677de7b8684af26ff9d\",\n        \"name\" : \"default.rb\",\n        \"path\" : \"recipes/default.rb\",\n        \"specificity\" : \"default\",\n        \"url\" : \"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-d45661e4b50f9677de7b8684af26ff9d?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277771874&Signature=r3CvyVe7dcOzB%2F0fNAun5ldGwr8%3D\"\n      } ],\n  \"resources\" : [  ],\n  \"root_files\" : [ { \"checksum\" : \"14f6977f68c3674484e8289e361fb5a4\",\n        \"name\" : \"README.rdoc\",\n        \"path\" : \"README.rdoc\",\n        \"specificity\" : \"default\",\n        \"url\" : \"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-14f6977f68c3674484e8289e361fb5a4?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277771874&Signature=VNZxN%2B7CxO7ZbDHJOS%2FaTtpkPaE%3D\"\n      },\n      { \"checksum\" : \"abc416ffba9ea64ca71635191cb87af6\",\n        \"name\" : \"metadata.rb\",\n        \"path\" : \"metadata.rb\",\n        \"specificity\" : \"default\",\n        \"url\" : \"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-abc416ffba9ea64ca71635191cb87af6?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277771874&Signature=pemynt9Q1F%2BxlS26kLaz%2F4NDGO4%3D\"\n      },\n      { \"checksum\" : \"dd8473a8a7f2b446250ecdefb1882a5e\",\n        \"name\" : \"metadata.json\",\n        \"path\" : \"metadata.json\",\n        \"specificity\" : \"default\",\n        \"url\" : \"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-dd8473a8a7f2b446250ecdefb1882a5e?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277771874&Signature=sHpayqP%2Fe4Luv20EMa3q%2FaMN4ms%3D\"\n      }\n    ],\n  \"templates\" : [ { \"checksum\" : \"107263b81e4700cf0adad7af2a133bbd\",\n        \"name\" : \"tomcat-users.xml.erb\",\n        \"path\" : \"templates/default/tomcat-users.xml.erb\",\n        \"specificity\" : \"default\",\n        \"url\" : \"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-107263b81e4700cf0adad7af2a133bbd?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277771874&Signature=QC7MNIauR2ox5MVlohf2i73uM1s%3D\"\n      },\n      { \"checksum\" : \"fa4432b353fa57b9da26a4bff44285f2\",\n        \"name\" : \"sv-tomcat6-run.erb\",\n        \"path\" : \"templates/default/sv-tomcat6-run.erb\",\n        \"specificity\" : \"default\",\n        \"url\" : \"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-fa4432b353fa57b9da26a4bff44285f2?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277771874&Signature=q2rDeJFeh4oyhfv9ExMifGB0wxo%3D\"\n      },\n      { \"checksum\" : \"33fd6f63133e7ebe28bc62e58773c408\",\n        \"name\" : \"manager.xml.erb\",\n        \"path\" : \"templates/default/manager.xml.erb\",\n        \"specificity\" : \"default\",\n        \"url\" : \"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-33fd6f63133e7ebe28bc62e58773c408?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277771874&Signature=rIijEhwLPf5PWTJOg%2BElbOquPBM%3D\"\n      },\n      { \"checksum\" : \"09f2bf988663175cd1b7973198dfb5eb\",\n        \"name\" : \"sv-tomcat6-log-run.erb\",\n        \"path\" : \"templates/default/sv-tomcat6-log-run.erb\",\n        \"specificity\" : \"default\",\n        \"url\" : \"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/checksum-09f2bf988663175cd1b7973198dfb5eb?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277771874&Signature=UnfNDP4pDzPM3PoLcLWyTnTa%2FKI%3D\"\n      }\n    ],\n  \"version\" : \"0.1.0\"\n}"
  },
  {
    "path": "apis/chef/src/test/resources/upload-site.json",
    "content": "{\n    \"uri\": \"https://api.opscode.com/organizations/jclouds/sandboxes/d454f71e2a5f400c808d0c5d04c2c88c\",\n    \"checksums\": {\n        \"0c5ecd7788cf4f6c7de2a57193897a6c\": {\n            \"url\": \"https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/sandbox-d454f71e2a5f400c808d0c5d04c2c88c/checksum-0c5ecd7788cf4f6c7de2a57193897a6c?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277344702&Signature=FtKyqvYEjhhEKmRY%2B0M8aGPMM7g%3D\",\n            \"needs_upload\": true\n        }, \"0189e76ccc476701d6b374e5a1a27347\": {\n            \"needs_upload\": false\n        }, \"1dda05ed139664f1f89b9dec482b77c0\": {\n            \"needs_upload\": false\n        }\n    }, \"sandbox_id\": \"d454f71e2a5f400c808d0c5d04c2c88c\"\n}"
  },
  {
    "path": "apis/chef/src/test/resources/user.json",
    "content": "{\n  \"display_name\" : \"Ignasi Barrera\",\n  \"email\" : \"myemail@chef.org\",\n  \"first_name\" : \"Ignasi\",\n  \"last_name\" : \"Barrera\",\n  \"middle_name\" : \"\",\n  \"public_key\" : \"-----BEGIN RSA PUBLIC KEY-----\\nMIIBCgKCAQEAp0ytgXbPzqJwOOixn7bTa6VAiNvVIOn+yDPoWbyEfc0li93BHIwv\\n01KW/mn55IXnSbMw86rdxisvwPHFfb7URuKuTzME6yrphBiancmNjushZZeBWb8j\\nqJhnFIKbaaOqew0LZSyG9ycYODB/HDK/pWTV4Bd1OtLHBNFrnIf+r3HOjJsa4rmK\\nWXgSQIQO7be/iRHysApV9tfVH8lo1ETnA08JTrQwDgo9St9YNbydb5V0CiLiQsOa\\nIbY09buUK9lXthh/rrRVbGbSwQM6OYdXIEZTN2BFvQ0p5pH8AiTwFqb0ICO46a0S\\njfGcXNjC/QfHljAPY3T5xyIOODM8afHCnwIDAQAB\\n-----END RSA PUBLIC KEY-----\\n\",\n  \"username\" : \"nacx\"\n}"
  },
  {
    "path": "apis/cloudstack/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.cloudstack.*;version=\"${project.version}\";-noimport:=true"
  },
  {
    "path": "apis/cloudstack/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.api</groupId>\n  <artifactId>cloudstack</artifactId>\n  <name>jclouds cloudstack core</name>\n  <description>jclouds components to access cloudstack</description>\n  \n  <properties>\n    <test.cloudstack.endpoint>http://localhost:8080/client/api</test.cloudstack.endpoint>\n    <test.cloudstack.api-version>3.0.3</test.cloudstack.api-version>\n    <test.cloudstack.build-version />\n    <test.cloudstack.identity>FIXME_apiKey</test.cloudstack.identity>\n    <test.cloudstack.credential>FIXME_secretKey</test.cloudstack.credential>\n    <test.cloudstack.domainAdminIdentity />\n    <test.cloudstack.domainAdminCredential />\n    <test.cloudstack.globalAdminIdentity />\n    <test.cloudstack.globalAdminCredential />\n    <test.cloudstack.template>osFamily=CENTOS</test.cloudstack.template>\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-sshj</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-slf4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>ch.qos.logback</groupId>\n      <artifactId>logback-classic</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <!-- too many tasks seem to overload the server and make the test take longer -->\n                  <threadCount>2</threadCount>\n                  <systemPropertyVariables>\n                    <test.cloudstack.endpoint>${test.cloudstack.endpoint}</test.cloudstack.endpoint>\n                    <test.cloudstack.api-version>${test.cloudstack.api-version}</test.cloudstack.api-version>\n                    <test.cloudstack.build-version>${test.cloudstack.build-version}</test.cloudstack.build-version>\n                    <test.cloudstack.identity>${test.cloudstack.identity}</test.cloudstack.identity>\n                    <test.cloudstack.credential>${test.cloudstack.credential}</test.cloudstack.credential>\n                    <test.cloudstack.template>${test.cloudstack.template}</test.cloudstack.template>\n                    <test.cloudstack.domainAdminIdentity>${test.cloudstack.domainAdminIdentity}</test.cloudstack.domainAdminIdentity>\n                    <test.cloudstack.domainAdminCredential>${test.cloudstack.domainAdminCredential}</test.cloudstack.domainAdminCredential>\n                    <test.cloudstack.globalAdminIdentity>${test.cloudstack.globalAdminIdentity}</test.cloudstack.globalAdminIdentity>\n                    <test.cloudstack.globalAdminCredential>${test.cloudstack.globalAdminCredential}</test.cloudstack.globalAdminCredential>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/AsyncJobException.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack;\n\npublic class AsyncJobException extends RuntimeException {\n\n   public AsyncJobException() {\n   }\n\n   public AsyncJobException(String s) {\n      super(s);\n   }\n\n   public AsyncJobException(String s, Throwable throwable) {\n      super(s, throwable);\n   }\n\n   public AsyncJobException(Throwable throwable) {\n      super(throwable);\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/CloudStackApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack;\n\nimport java.io.Closeable;\n\nimport org.jclouds.cloudstack.features.AccountApi;\nimport org.jclouds.cloudstack.features.AddressApi;\nimport org.jclouds.cloudstack.features.AsyncJobApi;\nimport org.jclouds.cloudstack.features.ConfigurationApi;\nimport org.jclouds.cloudstack.features.EventApi;\nimport org.jclouds.cloudstack.features.FirewallApi;\nimport org.jclouds.cloudstack.features.GuestOSApi;\nimport org.jclouds.cloudstack.features.HypervisorApi;\nimport org.jclouds.cloudstack.features.ISOApi;\nimport org.jclouds.cloudstack.features.LimitApi;\nimport org.jclouds.cloudstack.features.LoadBalancerApi;\nimport org.jclouds.cloudstack.features.NATApi;\nimport org.jclouds.cloudstack.features.NetworkApi;\nimport org.jclouds.cloudstack.features.OfferingApi;\nimport org.jclouds.cloudstack.features.ProjectApi;\nimport org.jclouds.cloudstack.features.SSHKeyPairApi;\nimport org.jclouds.cloudstack.features.SecurityGroupApi;\nimport org.jclouds.cloudstack.features.SessionApi;\nimport org.jclouds.cloudstack.features.SnapshotApi;\nimport org.jclouds.cloudstack.features.TagApi;\nimport org.jclouds.cloudstack.features.TemplateApi;\nimport org.jclouds.cloudstack.features.VMGroupApi;\nimport org.jclouds.cloudstack.features.VirtualMachineApi;\nimport org.jclouds.cloudstack.features.VolumeApi;\nimport org.jclouds.cloudstack.features.ZoneApi;\nimport org.jclouds.rest.annotations.Delegate;\n\n/**\n * Provides synchronous access to CloudStack.\n * <p/>\n *\n * @see <a href=\"http://download.cloud.com/releases/2.2.0/api_2.2.12/TOC_User.html\" />\n */\npublic interface CloudStackApi extends Closeable {\n   /**\n    * Provides synchronous access to Zone features.\n    */\n   @Delegate\n   ZoneApi getZoneApi();\n\n   /**\n    * Provides synchronous access to Template features.\n    */\n   @Delegate\n   TemplateApi getTemplateApi();\n\n   /**\n    * Provides synchronous access to Service, Disk, and Network Offering\n    * features.\n    */\n   @Delegate\n   OfferingApi getOfferingApi();\n\n   /**\n    * Provides synchronous access to Network features.\n    */\n   @Delegate\n   NetworkApi getNetworkApi();\n\n   /**\n    * Provides synchronous access to VirtualMachine features.\n    */\n   @Delegate\n   VirtualMachineApi getVirtualMachineApi();\n\n   /**\n    * Provides synchronous access to SecurityGroup features.\n    */\n   @Delegate\n   SecurityGroupApi getSecurityGroupApi();\n\n   /**\n    * Provides synchronous access to AsyncJob features.\n    */\n   @Delegate\n   AsyncJobApi getAsyncJobApi();\n\n   /**\n    * Provides synchronous access to Address features.\n    */\n   @Delegate\n   AddressApi getAddressApi();\n\n   /**\n    * Provides synchronous access to NAT features.\n    */\n   @Delegate\n   NATApi getNATApi();\n\n   /**\n    * Provides synchronous access to Firewall features.\n    */\n   @Delegate\n   FirewallApi getFirewallApi();\n\n   /**\n    * Provides synchronous access to LoadBalancer features.\n    */\n   @Delegate\n   LoadBalancerApi getLoadBalancerApi();\n\n   /**\n    * Provides synchronous access to GuestOS features.\n    */\n   @Delegate\n   GuestOSApi getGuestOSApi();\n\n   /**\n    * Provides synchronous access to Hypervisor features.\n    */\n   @Delegate\n   HypervisorApi getHypervisorApi();\n\n   /**\n    * Provides synchronous access to Configuration features.\n    */\n   @Delegate\n   ConfigurationApi getConfigurationApi();\n\n   /**\n    * Provides synchronous access to Account features.\n    */\n   @Delegate\n   AccountApi getAccountApi();\n\n   /**\n    * Provides synchronous access to SSH Keypairs\n    */\n   @Delegate\n   SSHKeyPairApi getSSHKeyPairApi();\n\n   /**\n    * Provides synchronous access to VM groups\n    */\n   @Delegate\n   VMGroupApi getVMGroupApi();\n\n   /**\n    * Provides synchronous access to Events\n    */\n   @Delegate\n   EventApi getEventApi();\n\n   /**\n    * Provides synchronous access to Resource Limits\n    */\n   @Delegate\n   LimitApi getLimitApi();\n\n   /**\n    * Provides synchronous access to ISOs\n    */\n   @Delegate\n   ISOApi getISOApi();\n\n   /**\n    * Provides synchronous access to Volumes\n    */\n   @Delegate\n   VolumeApi getVolumeApi();\n\n   /**\n    * Provides synchronous access to Snapshots\n    */\n   @Delegate\n   SnapshotApi getSnapshotApi();\n\n   /**\n    * Provides synchronous access to Sessions\n    */\n   @Delegate\n   SessionApi getSessionApi();\n\n   /**\n    * Provides synchronous access to Projects\n    */\n   @Delegate\n   ProjectApi getProjectApi();\n\n   /**\n    * Provides synchronous access to Tags\n    */\n   @Delegate\n   TagApi getTagApi();\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/CloudStackApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack;\nimport static org.jclouds.cloudstack.config.CloudStackProperties.AUTO_GENERATE_KEYPAIRS;\nimport static org.jclouds.reflect.Reflection2.typeToken;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.cloudstack.compute.config.CloudStackComputeServiceContextModule;\nimport org.jclouds.cloudstack.config.CloudStackHttpApiModule;\nimport org.jclouds.cloudstack.config.CloudStackParserModule;\nimport org.jclouds.rest.internal.BaseHttpApiMetadata;\n\nimport com.google.auto.service.AutoService;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n/**\n * Implementation of {@link ApiMetadata} for Citrix/Apache CloudStack api.\n */\n@AutoService(ApiMetadata.class)\npublic class CloudStackApiMetadata extends BaseHttpApiMetadata<CloudStackApi> {\n   \n   @Override\n   public Builder toBuilder() {\n      return new Builder().fromApiMetadata(this);\n   }\n\n   public CloudStackApiMetadata() {\n      this(new Builder());\n   }\n\n   protected CloudStackApiMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = BaseHttpApiMetadata.defaultProperties();\n      properties.setProperty(\"jclouds.ssh.max-retries\", \"7\");\n      properties.setProperty(\"jclouds.ssh.retry-auth\", \"true\");\n      properties.setProperty(AUTO_GENERATE_KEYPAIRS, \"false\");\n      return properties;\n   }\n\n   public static class Builder extends BaseHttpApiMetadata.Builder<CloudStackApi, Builder> {\n\n      @SuppressWarnings(\"deprecation\")\n      protected Builder() {\n         id(\"cloudstack\")\n         .name(\"Citrix CloudStack API\")\n         .identityName(\"API Key\")\n         .credentialName(\"Secret Key\")\n         .documentation(URI.create(\"http://download.cloud.com/releases/2.2.0/api_2.2.12/TOC_User.html\"))\n         .defaultEndpoint(\"http://localhost:8080/client/api\")\n         .version(\"2.2\")\n         .view(typeToken(CloudStackContext.class))\n         .defaultProperties(CloudStackApiMetadata.defaultProperties())\n         .defaultModules(ImmutableSet.<Class<? extends Module>> builder()\n                                     .add(CloudStackParserModule.class)\n                                     .add(CloudStackHttpApiModule.class)\n                                     .add(CloudStackComputeServiceContextModule.class).build());\n      }\n      \n      @Override\n      public CloudStackApiMetadata build() {\n         return new CloudStackApiMetadata(this);\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/CloudStackContext.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack;\n\nimport org.jclouds.cloudstack.internal.CloudStackContextImpl;\nimport org.jclouds.compute.ComputeServiceContext;\n\nimport com.google.inject.ImplementedBy;\n\n@ImplementedBy(CloudStackContextImpl.class)\npublic interface CloudStackContext extends ComputeServiceContext {\n\n   CloudStackApi getApi();\n\n   CloudStackDomainApi getDomainApi();\n\n   CloudStackGlobalApi getGlobalApi();\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/CloudStackDomainApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack;\n\nimport org.jclouds.cloudstack.features.DomainAccountApi;\nimport org.jclouds.cloudstack.features.DomainDomainApi;\nimport org.jclouds.cloudstack.features.DomainLimitApi;\nimport org.jclouds.cloudstack.features.DomainUserApi;\nimport org.jclouds.rest.annotations.Delegate;\n\n/**\n * Provides synchronous access to CloudStack.\n * <p/>\n * \n * @see <a href=\n *      \"http://download.cloud.com/releases/2.2.0/api_2.2.12/TOC_Domain_Admin.html\"\n *      />\n */\npublic interface CloudStackDomainApi extends CloudStackApi {\n\n   /**\n    * Provides synchronous access to Resource Limits\n    */\n   @Delegate\n   @Override\n   DomainLimitApi getLimitApi();\n   \n   /**\n    * Provides synchronous access to Accounts\n    */\n   @Delegate\n   @Override\n   DomainAccountApi getAccountApi();\n\n   /**\n    * Provides synchronous access to Users\n    */\n   @Delegate\n   DomainUserApi getUserClient();\n\n   /**\n    * Provides synchronous access to Domains\n    */\n   @Delegate\n   DomainDomainApi getDomainClient();\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/CloudStackGlobalApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack;\n\nimport org.jclouds.cloudstack.features.GlobalAccountApi;\nimport org.jclouds.cloudstack.features.GlobalAlertApi;\nimport org.jclouds.cloudstack.features.GlobalCapacityApi;\nimport org.jclouds.cloudstack.features.GlobalConfigurationApi;\nimport org.jclouds.cloudstack.features.GlobalDomainApi;\nimport org.jclouds.cloudstack.features.GlobalHostApi;\nimport org.jclouds.cloudstack.features.GlobalOfferingApi;\nimport org.jclouds.cloudstack.features.GlobalPodApi;\nimport org.jclouds.cloudstack.features.GlobalStoragePoolApi;\nimport org.jclouds.cloudstack.features.GlobalUsageApi;\nimport org.jclouds.cloudstack.features.GlobalUserApi;\nimport org.jclouds.cloudstack.features.GlobalVlanApi;\nimport org.jclouds.cloudstack.features.GlobalZoneApi;\nimport org.jclouds.rest.annotations.Delegate;\n\n/**\n * Provides synchronous access to CloudStack.\n * <p/>\n * \n * @see <a href=\n *      \"http://download.cloud.com/releases/2.2.0/api_2.2.12/TOC_Global_Admin.html\"\n *      />\n */\npublic interface CloudStackGlobalApi extends CloudStackDomainApi {\n\n   /**\n    * Provides synchronous access to Accounts\n    */\n   @Delegate\n   @Override\n   GlobalAccountApi getAccountApi();\n\n   /**\n    * Provides synchronous access to Users\n    */\n   @Delegate\n   @Override\n   GlobalUserApi getUserClient();\n\n   /**\n    * Provides synchronous access to Alerts\n    */\n   @Delegate\n   GlobalAlertApi getAlertClient();\n\n   /**\n    * Provides synchronous access to Capacities\n    */\n   @Delegate\n   GlobalCapacityApi getCapacityClient();\n\n   /**\n    * Provides synchronous access to Offerings\n    */\n   @Delegate\n   @Override\n   GlobalOfferingApi getOfferingApi();\n\n   /**\n    * Provides synchronous access to Hosts\n    */\n   @Delegate\n   GlobalHostApi getHostClient();\n\n   /**\n    * Provides synchronous access to Storage Pools\n    */\n   @Delegate\n   GlobalStoragePoolApi getStoragePoolClient();\n\n   /**\n    * Provides synchronous access to Usage\n    */\n   @Delegate\n   GlobalUsageApi getUsageClient();\n\n   /**\n    * Provides synchronous access to Configuration\n    */\n   @Delegate\n   @Override\n   GlobalConfigurationApi getConfigurationApi();\n\n   /**\n    * Provides synchronous access to Domain\n    */\n   @Delegate\n   @Override\n   GlobalDomainApi getDomainClient();\n\n   /**\n    * Provides synchronous access to Zone\n    */\n   @Delegate\n   @Override\n   GlobalZoneApi getZoneApi();\n\n   /**\n    * Provides synchronous access to Pod\n    */\n   @Delegate\n   GlobalPodApi getPodClient();\n\n   /**\n    * Provides synchronous access to Vlan\n    */\n   @Delegate\n   GlobalVlanApi getVlanClient();\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/binders/BindAccountSecurityGroupPairsToIndexedQueryParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.http.Uris.uriBuilder;\nimport static org.jclouds.http.utils.Queries.queryParser;\n\nimport java.net.URI;\nimport java.util.Map.Entry;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableMultimap.Builder;\nimport com.google.common.collect.Multimap;\n\n@Singleton\npublic class BindAccountSecurityGroupPairsToIndexedQueryParams implements Binder {\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkArgument(input instanceof Multimap<?, ?>, \"this binder is only valid for Multimaps!\");\n      Multimap<String, String> pairs = (Multimap<String, String>) checkNotNull(input, \"account group pairs\");\n      checkArgument(!pairs.isEmpty(), \"you must specify at least one account, group pair\");\n\n      Multimap<String, String> existingParams = queryParser().apply(request.getEndpoint().getQuery());\n      Builder<String, String> map = ImmutableMultimap.<String, String> builder().putAll(existingParams);\n      int i = 0;\n      for (Entry<String, String> entry : pairs.entries())\n         map.put(String.format(\"usersecuritygrouplist[%d].account\", i), entry.getKey()).put(\n               String.format(\"usersecuritygrouplist[%d].group\", i++), entry.getValue());\n      URI endpoint = uriBuilder(request.getEndpoint()).query(map.build()).build();\n      return (R) request.toBuilder().endpoint(endpoint).build();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/binders/BindCIDRsToCommaDelimitedQueryParam.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\nimport com.google.common.base.Joiner;\nimport com.google.common.collect.Iterables;\n\n@Singleton\npublic class BindCIDRsToCommaDelimitedQueryParam implements Binder {\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkArgument(input instanceof Iterable<?>, \"this binder is only valid for Iterables!\");\n      Iterable<String> cidrs = (Iterable<String>) checkNotNull(input, \"cidr list\");\n      checkArgument(!Iterables.isEmpty(cidrs), \"you must specify at least one cidr range\");\n      return (R) request.toBuilder().replaceQueryParam(\"cidrlist\", Joiner.on(',').join(cidrs)).build();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/binders/BindIdListToCommaDelimitedQueryParam.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\nimport com.google.common.base.Joiner;\nimport com.google.common.collect.Iterables;\n\n@Singleton\npublic class BindIdListToCommaDelimitedQueryParam implements Binder {\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkArgument(input instanceof Iterable<?>, \"this binder is only valid for Iterables!\");\n      Iterable<Long> numbers = (Iterable<Long>) checkNotNull(input, \"list of Longs\");\n      checkArgument(!Iterables.isEmpty(numbers), \"you must specify at least one element\");\n      return (R) request.toBuilder().replaceQueryParam(\"ids\", Joiner.on(',').join(numbers)).build();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/binders/BindSnapshotPolicyScheduleToQueryParam.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.cloudstack.domain.SnapshotPolicySchedule;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableMultimap.Builder;\n\n@Singleton\npublic class BindSnapshotPolicyScheduleToQueryParam implements Binder {\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkArgument(input instanceof SnapshotPolicySchedule, \"this binder is only valid for SnapshotPolicySchedule\");\n      SnapshotPolicySchedule schedule = SnapshotPolicySchedule.class.cast(input);\n      Builder<String, String> builder = ImmutableMultimap.<String, String> builder();\n      builder.put(\"intervaltype\", schedule.getInterval().toString());\n      builder.put(\"schedule\", schedule.getTime().toString());\n      return (R) request.toBuilder().replaceQueryParams(builder.build()).build();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/binders/BindTemplateMetadataToQueryParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\n\nimport org.jclouds.cloudstack.domain.TemplateMetadata;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableMultimap.Builder;\n\npublic class BindTemplateMetadataToQueryParams implements Binder {\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkArgument(input instanceof TemplateMetadata, \"this binder is only valid for TemplateMetadata\");\n      TemplateMetadata metadata = (TemplateMetadata) input;\n      Builder<String, String> builder = ImmutableMultimap.<String, String>builder();\n      builder.put(\"name\", metadata.getName());\n      builder.put(\"ostypeid\", metadata.getOsTypeId());\n      builder.put(\"displaytext\", metadata.getDisplayText());\n      if (metadata.getSnapshotId() != null) {\n\t      builder.put(\"snapshotid\", metadata.getSnapshotId());\n      }\n      if (metadata.getVolumeId() != null) {\n\t      builder.put(\"volumeid\", metadata.getVolumeId());\n      }\n      if (metadata.getVirtualMachineId() != null) {\n\t      builder.put(\"virtualmachineid\", metadata.getVirtualMachineId());\n      }\n      if (metadata.isPasswordEnabled() != null) {\n\t      builder.put(\"passwordenabled\", metadata.isPasswordEnabled().toString());\n      }\n      return (R) request.toBuilder().replaceQueryParams(builder.build()).build();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/binders/ResourceLimitToQueryParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\n\nimport org.jclouds.cloudstack.domain.ResourceLimit;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableMultimap.Builder;\n\n/**\n * \n * @see <a href=\n *      \"http://download.cloud.com/releases/2.2.0/api_2.2.12/domain_admin/updateResourceLimit.html\"\n *      />\n */\npublic class ResourceLimitToQueryParams implements Binder {\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkArgument(input instanceof ResourceLimit, \"this binder is only valid for ResourceLimit\");\n      ResourceLimit limit = (ResourceLimit) input;\n      Builder<String, String> builder = ImmutableMultimap.<String, String> builder();\n      builder.put(\"resourcetype\", limit.getResourceType().getCode() + \"\");\n      builder.put(\"account\", limit.getAccount());\n      builder.put(\"domainid\", limit.getDomainId());\n      builder.put(\"max\", limit.getMax() + \"\");\n      return (R) request.toBuilder().replaceQueryParams(builder.build()).build();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/compute/CloudStackComputeService.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.compute;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.cloudstack.predicates.SshKeyPairPredicates.nameMatches;\nimport static org.jclouds.cloudstack.predicates.ZonePredicates.supportsSecurityGroups;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_RUNNING;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_SUSPENDED;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_TERMINATED;\n\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Provider;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Constants;\nimport org.jclouds.cloudstack.CloudStackApi;\nimport org.jclouds.cloudstack.compute.options.CloudStackTemplateOptions;\nimport org.jclouds.cloudstack.domain.SecurityGroup;\nimport org.jclouds.cloudstack.domain.SshKeyPair;\nimport org.jclouds.cloudstack.domain.Zone;\nimport org.jclouds.cloudstack.domain.ZoneAndName;\nimport org.jclouds.cloudstack.predicates.SecurityGroupPredicates;\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.compute.callables.RunScriptOnNode;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.TemplateBuilder;\nimport org.jclouds.compute.extensions.ImageExtension;\nimport org.jclouds.compute.extensions.SecurityGroupExtension;\nimport org.jclouds.compute.extensions.internal.DelegatingImageExtension;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.compute.internal.BaseComputeService;\nimport org.jclouds.compute.internal.PersistNodeCredentials;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.compute.strategy.CreateNodesInGroupThenAddToSet;\nimport org.jclouds.compute.strategy.DestroyNodeStrategy;\nimport org.jclouds.compute.strategy.GetImageStrategy;\nimport org.jclouds.compute.strategy.GetNodeMetadataStrategy;\nimport org.jclouds.compute.strategy.InitializeRunScriptOnNodeOrPlaceInBadMap;\nimport org.jclouds.compute.strategy.ListNodesStrategy;\nimport org.jclouds.compute.strategy.RebootNodeStrategy;\nimport org.jclouds.compute.strategy.ResumeNodeStrategy;\nimport org.jclouds.compute.strategy.SuspendNodeStrategy;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.domain.Location;\nimport org.jclouds.scriptbuilder.functions.InitAdminAccess;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Multimap;\nimport com.google.common.util.concurrent.ListeningExecutorService;\n\n@Singleton\npublic class CloudStackComputeService extends BaseComputeService {\n   protected final CloudStackApi client;\n   protected final LoadingCache<ZoneAndName, SecurityGroup> securityGroupMap;\n   protected final LoadingCache<String, SshKeyPair> keyPairCache;\n   protected final Function<Set<? extends NodeMetadata>, Multimap<String, String>> orphanedGroupsByZoneId;\n   protected final GroupNamingConvention.Factory namingConvention;\n   protected final Supplier<LoadingCache<String, Zone>> zoneIdToZone;\n\n   @Inject\n   protected CloudStackComputeService(ComputeServiceContext context, Map<String, Credentials> credentialStore,\n         @Memoized Supplier<Set<? extends Image>> images, @Memoized Supplier<Set<? extends Hardware>> sizes,\n         @Memoized Supplier<Set<? extends Location>> locations, ListNodesStrategy listNodesStrategy,\n         GetImageStrategy getImageStrategy, GetNodeMetadataStrategy getNodeMetadataStrategy,\n         CreateNodesInGroupThenAddToSet runNodesAndAddToSetStrategy, RebootNodeStrategy rebootNodeStrategy,\n         DestroyNodeStrategy destroyNodeStrategy, ResumeNodeStrategy startNodeStrategy,\n         SuspendNodeStrategy stopNodeStrategy, Provider<TemplateBuilder> templateBuilderProvider,\n         @Named(\"DEFAULT\") Provider<TemplateOptions> templateOptionsProvider,\n         @Named(TIMEOUT_NODE_RUNNING) Predicate<AtomicReference<NodeMetadata>> nodeRunning,\n         @Named(TIMEOUT_NODE_TERMINATED) Predicate<AtomicReference<NodeMetadata>> nodeTerminated,\n         @Named(TIMEOUT_NODE_SUSPENDED) Predicate<AtomicReference<NodeMetadata>> nodeSuspended,\n         InitializeRunScriptOnNodeOrPlaceInBadMap.Factory initScriptRunnerFactory,\n         RunScriptOnNode.Factory runScriptOnNodeFactory, InitAdminAccess initAdminAccess,\n         PersistNodeCredentials persistNodeCredentials,\n         @Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor, CloudStackApi client,\n         LoadingCache<ZoneAndName, SecurityGroup> securityGroupMap, LoadingCache<String, SshKeyPair> keyPairCache,\n         Function<Set<? extends NodeMetadata>, Multimap<String, String>> orphanedGroupsByZoneId,\n         GroupNamingConvention.Factory namingConvention, Supplier<LoadingCache<String, Zone>> zoneIdToZone,\n         Optional<ImageExtension> imageExtension, Optional<SecurityGroupExtension> securityGroupExtension,\n         DelegatingImageExtension.Factory delegatingImageExtension) {\n      super(context, credentialStore, images, sizes, locations, listNodesStrategy, getImageStrategy,\n            getNodeMetadataStrategy, runNodesAndAddToSetStrategy, rebootNodeStrategy, destroyNodeStrategy,\n            startNodeStrategy, stopNodeStrategy, templateBuilderProvider, templateOptionsProvider, nodeRunning,\n            nodeTerminated, nodeSuspended, initScriptRunnerFactory, initAdminAccess, runScriptOnNodeFactory,\n            persistNodeCredentials, userExecutor, imageExtension, securityGroupExtension, delegatingImageExtension);\n      this.zoneIdToZone = checkNotNull(zoneIdToZone, \"zoneIdToZone\");\n      this.client = checkNotNull(client, \"client\");\n      this.securityGroupMap = checkNotNull(securityGroupMap, \"securityGroupMap\");\n      this.keyPairCache = checkNotNull(keyPairCache, \"keyPairCache\");\n      this.orphanedGroupsByZoneId = checkNotNull(orphanedGroupsByZoneId, \"orphanedGroupsByZoneId\");\n      this.namingConvention = checkNotNull(namingConvention, \"namingConvention\");\n   }\n\n   @Override\n   protected void cleanUpIncidentalResourcesOfDeadNodes(Set<? extends NodeMetadata> deadNodes) {\n      Multimap<String, String> zoneToZoneAndGroupNames = orphanedGroupsByZoneId.apply(deadNodes);\n      for (String zoneId : zoneToZoneAndGroupNames.keySet()) {\n         cleanOrphanedGroupsInZone(ImmutableSet.copyOf(zoneToZoneAndGroupNames.get(zoneId)), zoneId);\n      }\n   }\n\n   protected void cleanOrphanedGroupsInZone(Set<String> groups, String zoneId) {\n      cleanupOrphanedSecurityGroupsInZone(groups, zoneId);\n      cleanupOrphanedKeyPairsInZone(groups, zoneId);\n   }\n\n   private void cleanupOrphanedSecurityGroupsInZone(Set<String> groups, String zoneId) {\n      Zone zone = zoneIdToZone.get().getUnchecked(zoneId);\n\n      if (supportsSecurityGroups().apply(zone)) {\n         for (String group : groups) {\n            for (SecurityGroup securityGroup : Iterables.filter(client.getSecurityGroupApi().listSecurityGroups(),\n                     SecurityGroupPredicates.nameMatches(namingConvention.create().containsGroup(group)))) {\n               ZoneAndName zoneAndName = ZoneAndName.fromZoneAndName(zoneId, securityGroup.getName());\n               logger.debug(\">> deleting securityGroup(%s)\", zoneAndName);\n               client.getSecurityGroupApi().deleteSecurityGroup(securityGroup.getId());\n               // TODO: test this clear happens\n               securityGroupMap.invalidate(zoneAndName);\n               logger.debug(\"<< deleted securityGroup(%s)\", zoneAndName);\n            }\n         }\n      }\n   }\n\n   private void cleanupOrphanedKeyPairsInZone(Set<String> groups, String zoneId) {\n      for (String group : groups) {\n         for (SshKeyPair pair : Iterables.filter(client.getSSHKeyPairApi().listSSHKeyPairs(),\n                                                 nameMatches(namingConvention.create().containsGroup(group)))) {\n            logger.debug(\">> deleting keypair(%s)\", pair.getName());\n            client.getSSHKeyPairApi().deleteSSHKeyPair(pair.getName());\n            // TODO: test this clear happens\n            keyPairCache.invalidate(pair.getName());\n            logger.debug(\"<< deleted keypair(%s)\", pair.getName());\n         }\n         keyPairCache.invalidate(namingConvention.create().sharedNameForGroup(group));\n      }\n   }\n\n   /**\n    * returns template options, as {@link CloudStackTemplateOptions}.\n    */\n   @Override\n   public CloudStackTemplateOptions templateOptions() {\n      return CloudStackTemplateOptions.class.cast(super.templateOptions());\n   }\n   \n   \n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/compute/config/CloudStackComputeServiceContextModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.compute.config;\n\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL;\nimport static org.jclouds.cloudstack.config.CloudStackProperties.AUTO_GENERATE_KEYPAIRS;\nimport static org.jclouds.util.Predicates2.retry;\n\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.cloudstack.CloudStackApi;\nimport org.jclouds.cloudstack.compute.extensions.CloudStackImageExtension;\nimport org.jclouds.cloudstack.compute.extensions.CloudStackSecurityGroupExtension;\nimport org.jclouds.cloudstack.compute.functions.CloudStackSecurityGroupToSecurityGroup;\nimport org.jclouds.cloudstack.compute.functions.IngressRuleToIpPermission;\nimport org.jclouds.cloudstack.compute.functions.OrphanedGroupsByZoneId;\nimport org.jclouds.cloudstack.compute.functions.ServiceOfferingToHardware;\nimport org.jclouds.cloudstack.compute.functions.TemplateToImage;\nimport org.jclouds.cloudstack.compute.functions.TemplateToOperatingSystem;\nimport org.jclouds.cloudstack.compute.functions.VirtualMachineToNodeMetadata;\nimport org.jclouds.cloudstack.compute.functions.ZoneToLocation;\nimport org.jclouds.cloudstack.compute.loaders.CreateUniqueKeyPair;\nimport org.jclouds.cloudstack.compute.loaders.FindSecurityGroupOrCreate;\nimport org.jclouds.cloudstack.compute.options.CloudStackTemplateOptions;\nimport org.jclouds.cloudstack.compute.strategy.AdvancedNetworkOptionsConverter;\nimport org.jclouds.cloudstack.compute.strategy.BasicNetworkOptionsConverter;\nimport org.jclouds.cloudstack.compute.strategy.CloudStackComputeServiceAdapter;\nimport org.jclouds.cloudstack.compute.strategy.OptionsConverter;\nimport org.jclouds.cloudstack.domain.FirewallRule;\nimport org.jclouds.cloudstack.domain.IPForwardingRule;\nimport org.jclouds.cloudstack.domain.IngressRule;\nimport org.jclouds.cloudstack.domain.Network;\nimport org.jclouds.cloudstack.domain.NetworkType;\nimport org.jclouds.cloudstack.domain.OSType;\nimport org.jclouds.cloudstack.domain.Project;\nimport org.jclouds.cloudstack.domain.SecurityGroup;\nimport org.jclouds.cloudstack.domain.ServiceOffering;\nimport org.jclouds.cloudstack.domain.SshKeyPair;\nimport org.jclouds.cloudstack.domain.Template;\nimport org.jclouds.cloudstack.domain.User;\nimport org.jclouds.cloudstack.domain.VirtualMachine;\nimport org.jclouds.cloudstack.domain.Zone;\nimport org.jclouds.cloudstack.domain.ZoneAndName;\nimport org.jclouds.cloudstack.domain.ZoneSecurityGroupNamePortsCidrs;\nimport org.jclouds.cloudstack.features.GuestOSApi;\nimport org.jclouds.cloudstack.functions.CreateSecurityGroupIfNeeded;\nimport org.jclouds.cloudstack.functions.GetFirewallRulesByVirtualMachine;\nimport org.jclouds.cloudstack.functions.GetIPForwardingRulesByVirtualMachine;\nimport org.jclouds.cloudstack.functions.StaticNATVirtualMachineInNetwork;\nimport org.jclouds.cloudstack.functions.ZoneIdToZone;\nimport org.jclouds.cloudstack.predicates.JobComplete;\nimport org.jclouds.cloudstack.suppliers.GetCurrentUser;\nimport org.jclouds.cloudstack.suppliers.NetworksForCurrentUser;\nimport org.jclouds.cloudstack.suppliers.ProjectsForCurrentUser;\nimport org.jclouds.cloudstack.suppliers.ZoneIdToZoneSupplier;\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.ComputeServiceAdapter;\nimport org.jclouds.compute.config.ComputeServiceAdapterContextModule;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.extensions.ImageExtension;\nimport org.jclouds.compute.extensions.SecurityGroupExtension;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.domain.Location;\nimport org.jclouds.net.domain.IpPermission;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.suppliers.MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Maps;\nimport com.google.common.collect.Multimap;\nimport com.google.inject.Injector;\nimport com.google.inject.Key;\nimport com.google.inject.Provides;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.assistedinject.FactoryModuleBuilder;\nimport com.google.inject.name.Names;\n\npublic class CloudStackComputeServiceContextModule extends\n         ComputeServiceAdapterContextModule<VirtualMachine, ServiceOffering, Template, Zone> {\n\n   @Override\n   protected void configure() {\n      super.configure();\n      bind(new TypeLiteral<ComputeServiceAdapter<VirtualMachine, ServiceOffering, Template, Zone>>() {\n      }).to(CloudStackComputeServiceAdapter.class);\n      bind(new TypeLiteral<Function<VirtualMachine, NodeMetadata>>() {\n      }).to(VirtualMachineToNodeMetadata.class);\n      bind(new TypeLiteral<Function<SecurityGroup, org.jclouds.compute.domain.SecurityGroup>>() {\n      }).to(CloudStackSecurityGroupToSecurityGroup.class);\n      bind(new TypeLiteral<Function<IngressRule, IpPermission>>() {\n      }).to(IngressRuleToIpPermission.class);\n      bind(new TypeLiteral<Function<Template, org.jclouds.compute.domain.Image>>() {\n      }).to(TemplateToImage.class);\n      bind(new TypeLiteral<Function<ServiceOffering, org.jclouds.compute.domain.Hardware>>() {\n      }).to(ServiceOfferingToHardware.class);\n      bind(new TypeLiteral<Function<Zone, Location>>() {\n      }).to(ZoneToLocation.class);\n      bind(TemplateOptions.class).to(CloudStackTemplateOptions.class);\n      bind(new TypeLiteral<Function<Template, OperatingSystem>>() {\n      }).to(TemplateToOperatingSystem.class);\n      install(new FactoryModuleBuilder().build(StaticNATVirtualMachineInNetwork.Factory.class));\n      bind(new TypeLiteral<CacheLoader<String, Set<IPForwardingRule>>>() {\n      }).to(GetIPForwardingRulesByVirtualMachine.class);\n      bind(new TypeLiteral<CacheLoader<String, Set<FirewallRule>>>() {\n      }).to(GetFirewallRulesByVirtualMachine.class);\n      bind(new TypeLiteral<CacheLoader<String, Zone>>() {\n      }).to(ZoneIdToZone.class);\n      bind(new TypeLiteral<CacheLoader<String, SshKeyPair>>() {\n      }).to(CreateUniqueKeyPair.class);\n      bind(new TypeLiteral<Supplier<LoadingCache<String, Zone>>>() {\n      }).to(ZoneIdToZoneSupplier.class);\n      bind(new TypeLiteral<Function<ZoneSecurityGroupNamePortsCidrs, SecurityGroup>>() {\n      }).to(CreateSecurityGroupIfNeeded.class);\n      bind(new TypeLiteral<CacheLoader<ZoneAndName, SecurityGroup>>() {\n      }).to(FindSecurityGroupOrCreate.class);\n      bind(new TypeLiteral<Function<Set<? extends NodeMetadata>,  Multimap<String, String>>>() {\n      }).to(OrphanedGroupsByZoneId.class);\n\n      bind(new TypeLiteral<ImageExtension>() {\n      }).to(CloudStackImageExtension.class);\n\n      bind(new TypeLiteral<SecurityGroupExtension>() {\n      }).to(CloudStackSecurityGroupExtension.class);\n\n      // to have the compute service adapter override default locations\n      install(new LocationsFromComputeServiceAdapterModule<VirtualMachine, ServiceOffering, Template, Zone>() {\n      });\n   }\n\n   @Override\n   protected TemplateOptions provideTemplateOptions(Injector injector, TemplateOptions options) {\n      return options.as(CloudStackTemplateOptions.class)\n         .generateKeyPair(injector.getInstance(\n                  Key.get(boolean.class, Names.named(AUTO_GENERATE_KEYPAIRS))));\n   }\n\n   @Provides\n   @Singleton\n   @Memoized\n   public final Supplier<Map<String, String>> listOSCategories(AtomicReference<AuthorizationException> authException, @Named(PROPERTY_SESSION_INTERVAL) long seconds,\n         final CloudStackApi client) {\n      return MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier.create(authException,\n            new Supplier<Map<String, String>>() {\n               @Override\n               public Map<String, String> get() {\n                  GuestOSApi guestOSClient = client.getGuestOSApi();\n                  return guestOSClient.listOSCategories();\n               }\n               @Override\n               public String toString() {\n                  return MoreObjects.toStringHelper(client.getGuestOSApi()).add(\"method\", \"listOSCategories\").toString();\n               }\n            }, seconds, TimeUnit.SECONDS);\n   }\n\n   @Provides\n   @Singleton\n   @Memoized\n   public final Supplier<Map<String, OSType>> listOSTypes(AtomicReference<AuthorizationException> authException, @Named(PROPERTY_SESSION_INTERVAL) long seconds,\n         final CloudStackApi client) {\n      return MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier.create(authException,\n            new Supplier<Map<String, OSType>>() {\n               @Override\n               public Map<String, OSType> get() {\n                  GuestOSApi guestOSClient = client.getGuestOSApi();\n                  return Maps.uniqueIndex(guestOSClient.listOSTypes(), new Function<OSType, String>() {\n\n                     @Override\n                     public String apply(OSType arg0) {\n                        return arg0.getId();\n                     }\n                  });\n               }\n               @Override\n               public String toString() {\n                  return MoreObjects.toStringHelper(client.getGuestOSApi()).add(\"method\", \"listOSTypes\").toString();\n               }\n            }, seconds, TimeUnit.SECONDS);\n   }\n\n   @Provides\n   @Singleton\n   @Memoized\n   public final Supplier<Map<String, Network>> listNetworks(AtomicReference<AuthorizationException> authException, @Named(PROPERTY_SESSION_INTERVAL) long seconds,\n         final NetworksForCurrentUser networksForCurrentUser) {\n      return MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier.create(authException, networksForCurrentUser,\n               seconds, TimeUnit.SECONDS);\n   }\n\n   @Provides\n   @Singleton\n   @Memoized\n   public final Supplier<Map<String, Project>> listProjects(AtomicReference<AuthorizationException> authException, @Named(PROPERTY_SESSION_INTERVAL) long seconds,\n                                                      final ProjectsForCurrentUser projectsForCurrentUser) {\n      return MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier.create(authException, projectsForCurrentUser,\n              seconds, TimeUnit.SECONDS);\n   }\n\n   @Provides\n   @Singleton\n   @Memoized\n   public final Supplier<User> getCurrentUser(AtomicReference<AuthorizationException> authException, @Named(PROPERTY_SESSION_INTERVAL) long seconds,\n         final GetCurrentUser getCurrentUser) {\n      return MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier.create(authException, getCurrentUser,\n               seconds, TimeUnit.SECONDS);\n   }\n\n   @Provides\n   @Singleton\n   protected final Predicate<String> jobComplete(JobComplete jobComplete) {\n      return retry(jobComplete, 1200, 1, 5, SECONDS);\n   }\n\n   @Provides\n   @Singleton\n   protected final LoadingCache<String, SshKeyPair> keyPairMap(\n         CacheLoader<String, SshKeyPair> in) {\n      return CacheBuilder.newBuilder().build(in);\n   }\n\n   @Provides\n   @Singleton\n   protected final LoadingCache<ZoneAndName, SecurityGroup> securityGroupMap(\n            CacheLoader<ZoneAndName, SecurityGroup> in) {\n      return CacheBuilder.newBuilder().build(in);\n   }\n\n   @Provides\n   @Singleton\n   protected final LoadingCache<String, Set<IPForwardingRule>> getIPForwardingRulesByVirtualMachine(\n      CacheLoader<String, Set<IPForwardingRule>> in) {\n      return CacheBuilder.newBuilder().build(in);\n   }\n\n\n   @Provides\n   @Singleton\n   protected final LoadingCache<String, Set<FirewallRule>> getFirewallRulesByVirtualMachine(\n      CacheLoader<String, Set<FirewallRule>> getFirewallRules) {\n      return CacheBuilder.newBuilder().build(getFirewallRules);\n   }\n\n   @Provides\n   @Singleton\n   public final Map<NetworkType, ? extends OptionsConverter> optionsConverters() {\n      return ImmutableMap.of(\n         NetworkType.ADVANCED, new AdvancedNetworkOptionsConverter(),\n         NetworkType.BASIC, new BasicNetworkOptionsConverter());\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/compute/extensions/CloudStackImageExtension.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.compute.extensions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.common.collect.Iterables.find;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_IMAGE_AVAILABLE;\nimport static org.jclouds.location.predicates.LocationPredicates.idEquals;\n\nimport java.util.NoSuchElementException;\nimport java.util.Set;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Constants;\nimport org.jclouds.cloudstack.CloudStackApi;\nimport org.jclouds.cloudstack.domain.AsyncCreateResponse;\nimport org.jclouds.cloudstack.domain.Template;\nimport org.jclouds.cloudstack.domain.TemplateMetadata;\nimport org.jclouds.cloudstack.domain.VirtualMachine;\nimport org.jclouds.cloudstack.domain.Volume;\nimport org.jclouds.cloudstack.options.CreateTemplateOptions;\nimport org.jclouds.cloudstack.options.ListVolumesOptions;\nimport org.jclouds.cloudstack.strategy.BlockUntilJobCompletesAndReturnResult;\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.domain.CloneImageTemplate;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.ImageBuilder;\nimport org.jclouds.compute.domain.ImageTemplate;\nimport org.jclouds.compute.domain.ImageTemplateBuilder;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.extensions.ImageExtension;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.domain.Location;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.Iterables;\nimport com.google.common.util.concurrent.Atomics;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.common.util.concurrent.UncheckedTimeoutException;\n\n/**\n * CloudStack implementation of {@link ImageExtension}\n */\n@Singleton\npublic class CloudStackImageExtension implements ImageExtension {\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   private final CloudStackApi client;\n   private final ListeningExecutorService userExecutor;\n   private final Supplier<Set<? extends Location>> locations;\n   private final Predicate<AtomicReference<Image>> imageAvailablePredicate;\n   private final BlockUntilJobCompletesAndReturnResult blockUntilJobCompletesAndReturnResult;\n   private final Predicate<String> jobComplete;\n\n   @Inject\n   public CloudStackImageExtension(CloudStackApi client,\n                                   @Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor,\n                                   @Memoized Supplier<Set<? extends Location>> locations,\n                                   @Named(TIMEOUT_IMAGE_AVAILABLE) Predicate<AtomicReference<Image>> imageAvailablePredicate,\n                                   BlockUntilJobCompletesAndReturnResult blockUntilJobCompletesAndReturnResult,\n                                   Predicate<String> jobComplete) {\n      this.client = checkNotNull(client, \"client\");\n      this.userExecutor = checkNotNull(userExecutor, \"userExecutor\");\n      this.locations = checkNotNull(locations, \"locations\");\n      this.imageAvailablePredicate = checkNotNull(imageAvailablePredicate, \"imageAvailablePredicate\");\n      this.blockUntilJobCompletesAndReturnResult = checkNotNull(blockUntilJobCompletesAndReturnResult,\n                                                                \"blockUntilJobCompletesAndReturnResult\");\n      this.jobComplete = checkNotNull(jobComplete, \"jobComplete\");\n   }\n\n   @Override\n   public ImageTemplate buildImageTemplateFromNode(String name, String id) {\n      VirtualMachine vm = client.getVirtualMachineApi().getVirtualMachine(id);\n      if (vm == null)\n         throw new NoSuchElementException(\"Cannot find vm with id: \" + id);\n      CloneImageTemplate template = new ImageTemplateBuilder.CloneImageTemplateBuilder().nodeId(id).name(name).build();\n      return template;\n   }\n\n   @Override\n   public ListenableFuture<Image> createImage(ImageTemplate template) {\n      checkState(template instanceof CloneImageTemplate,\n               \" cloudstack only currently supports creating images through cloning.\");\n      CloneImageTemplate cloneTemplate = (CloneImageTemplate) template;\n\n      VirtualMachine vm = client.getVirtualMachineApi().getVirtualMachine(cloneTemplate.getSourceNodeId());\n      String stopJob = client.getVirtualMachineApi().stopVirtualMachine(vm.getId());\n      jobComplete.apply(stopJob);\n\n      Set<Volume> volumes = client.getVolumeApi().listVolumes(ListVolumesOptions.Builder.virtualMachineId(vm.getId()));\n      Volume volume = Iterables.getOnlyElement(volumes);\n      \n      CreateTemplateOptions options = CreateTemplateOptions.Builder.volumeId(volume.getId());\n      AsyncCreateResponse templateJob = client.getTemplateApi().createTemplate(TemplateMetadata.builder()\n                                                                                  .name(cloneTemplate.getName())\n                                                                                  .osTypeId(vm.getGuestOSId())\n                                                                                  .displayText(cloneTemplate.getName())\n                                                                                  .build(), options);\n      Template newTemplate = blockUntilJobCompletesAndReturnResult.<Template>apply(templateJob);\n\n      logger.info(\">> Registered new template %s, waiting for it to become available.\", newTemplate.getId());\n\n      final AtomicReference<Image> image = Atomics.newReference(new ImageBuilder()\n                                                                .location(find(locations.get(), idEquals(vm.getZoneId())))\n                                                                .id(newTemplate.getId())\n                                                                .providerId(newTemplate.getId())\n                                                                .description(cloneTemplate.getName())\n                                                                .operatingSystem(OperatingSystem.builder().description(cloneTemplate.getName()).build())\n                                                                .status(Image.Status.PENDING).build());\n\n      return userExecutor.submit(new Callable<Image>() {\n         @Override\n         public Image call() throws Exception {\n            if (imageAvailablePredicate.apply(image))\n               return image.get();\n            // TODO: get rid of the expectation that the image will be available, as it is very brittle\n            throw new UncheckedTimeoutException(\"Image was not created within the time limit: \" + image.get());\n         }\n      });\n   }\n\n   @Override\n   public boolean deleteImage(String id) {\n      try {\n         AsyncCreateResponse deleteJob = client.getTemplateApi().deleteTemplate(id);\n         jobComplete.apply(deleteJob.getJobId());\n         return true;\n      } catch (Exception e) {\n         return false;\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/compute/extensions/CloudStackSecurityGroupExtension.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.compute.extensions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Predicates.notNull;\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.transform;\nimport static org.jclouds.cloudstack.predicates.SecurityGroupPredicates.ruleCidrMatches;\nimport static org.jclouds.cloudstack.predicates.SecurityGroupPredicates.ruleGroupMatches;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.cloudstack.CloudStackApi;\nimport org.jclouds.cloudstack.domain.IngressRule;\nimport org.jclouds.cloudstack.domain.ZoneAndName;\nimport org.jclouds.cloudstack.domain.ZoneSecurityGroupNamePortsCidrs;\nimport org.jclouds.cloudstack.options.ListSecurityGroupsOptions;\nimport org.jclouds.cloudstack.strategy.BlockUntilJobCompletesAndReturnResult;\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.domain.SecurityGroup;\nimport org.jclouds.compute.extensions.SecurityGroupExtension;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.domain.Location;\nimport org.jclouds.net.domain.IpPermission;\nimport org.jclouds.net.domain.IpProtocol;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Multimap;\n\n/**\n * An extension to compute service to allow for the manipulation of {@link org.jclouds.compute.domain.SecurityGroup}s. Implementation\n * is optional by providers.\n */\npublic class CloudStackSecurityGroupExtension implements SecurityGroupExtension {\n   protected final CloudStackApi api;\n   protected final Function<org.jclouds.cloudstack.domain.SecurityGroup, SecurityGroup> groupConverter;\n   protected final LoadingCache<ZoneAndName, org.jclouds.cloudstack.domain.SecurityGroup> groupCreator;\n   protected final GroupNamingConvention.Factory namingConvention;\n   protected final Supplier<Set<? extends Location>> locations;\n   protected final BlockUntilJobCompletesAndReturnResult blockUntilJobCompletesAndReturnResult;\n   protected final Predicate<String> jobComplete;\n\n   @Inject\n   public CloudStackSecurityGroupExtension(CloudStackApi api,\n                                           Function<org.jclouds.cloudstack.domain.SecurityGroup, SecurityGroup> groupConverter,\n                                           LoadingCache<ZoneAndName, org.jclouds.cloudstack.domain.SecurityGroup> groupCreator,\n                                           GroupNamingConvention.Factory namingConvention,\n                                           @Memoized Supplier<Set<? extends Location>> locations,\n                                           BlockUntilJobCompletesAndReturnResult blockUntilJobCompletesAndReturnResult,\n                                           Predicate<String> jobComplete) {\n      this.api = checkNotNull(api, \"api\");\n      this.groupConverter = checkNotNull(groupConverter, \"groupConverter\");\n      this.groupCreator = checkNotNull(groupCreator, \"groupCreator\");\n      this.namingConvention = checkNotNull(namingConvention, \"namingConvention\");\n      this.locations = checkNotNull(locations, \"locations\");\n      this.blockUntilJobCompletesAndReturnResult = checkNotNull(blockUntilJobCompletesAndReturnResult,\n              \"blockUntilJobCompletesAndReturnResult\");\n      this.jobComplete = checkNotNull(jobComplete, \"jobComplete\");\n   }\n\n   @Override\n   public Set<SecurityGroup> listSecurityGroups() {\n      Iterable<? extends org.jclouds.cloudstack.domain.SecurityGroup> rawGroups =\n              api.getSecurityGroupApi().listSecurityGroups();\n      Iterable<SecurityGroup> groups = transform(filter(rawGroups, notNull()),\n              groupConverter);\n      return ImmutableSet.copyOf(groups);\n   }\n\n   /**\n    * Note that for the time being, security groups are not scoped by location in\n    * CloudStack, so this will simply return listSecurityGroups().\n    *\n    * @param location\n    * @return security groups\n    */\n   @Override\n   public Set<SecurityGroup> listSecurityGroupsInLocation(final Location location) {\n      return listSecurityGroups();\n   }\n\n   @Override\n   public Set<SecurityGroup> listSecurityGroupsForNode(String id) {\n      checkNotNull(id, \"id\");\n\n      Iterable<? extends org.jclouds.cloudstack.domain.SecurityGroup> rawGroups =\n              api.getSecurityGroupApi().listSecurityGroups(ListSecurityGroupsOptions.Builder\n                      .virtualMachineId(id));\n\n      Iterable<SecurityGroup> groups = transform(filter(rawGroups, notNull()),\n              groupConverter);\n      return ImmutableSet.copyOf(groups);\n   }\n\n   @Override\n   public SecurityGroup getSecurityGroupById(String id) {\n      checkNotNull(id, \"id\");\n\n      org.jclouds.cloudstack.domain.SecurityGroup rawGroup\n              = api.getSecurityGroupApi().getSecurityGroup(id);\n\n      if (rawGroup == null) {\n         return null;\n      }\n\n      return groupConverter.apply(rawGroup);\n   }\n\n   @Override\n   public SecurityGroup createSecurityGroup(String name, Location location) {\n      checkNotNull(name, \"name\");\n      checkNotNull(location, \"location\");\n\n      String markerGroup = namingConvention.create().sharedNameForGroup(name);\n\n      ZoneSecurityGroupNamePortsCidrs zoneAndName = ZoneSecurityGroupNamePortsCidrs.builder()\n              .zone(location.getId())\n              .name(markerGroup)\n              .build();\n\n      return groupConverter.apply(groupCreator.getUnchecked(zoneAndName));\n   }\n\n   @Override\n   public boolean removeSecurityGroup(String id) {\n      checkNotNull(id, \"id\");\n\n      org.jclouds.cloudstack.domain.SecurityGroup group =\n              api.getSecurityGroupApi().getSecurityGroup(id);\n\n      if (group == null) {\n         invalidateCache(id);\n         return false;\n      }\n\n      for (IngressRule rule : group.getIngressRules()) {\n         jobComplete.apply(api.getSecurityGroupApi().revokeIngressRule(rule.getId()));\n      }\n\n      api.getSecurityGroupApi().deleteSecurityGroup(id);\n\n      invalidateCache(id);\n      return true;\n   }\n\n   private void invalidateCache(String id) {\n      for (Map.Entry<ZoneAndName, org.jclouds.cloudstack.domain.SecurityGroup> sg : groupCreator.asMap().entrySet()) {\n         if (id.equals(sg.getValue().getId())) {\n            groupCreator.invalidate(sg.getKey());\n            break;\n         }\n      }\n   }\n\n   @Override\n   public SecurityGroup addIpPermission(IpPermission ipPermission, SecurityGroup group) {\n      checkNotNull(group, \"group\");\n      checkNotNull(ipPermission, \"ipPermission\");\n      String id = checkNotNull(group.getId(), \"group.getId()\");\n\n      if (!ipPermission.getCidrBlocks().isEmpty()) {\n         jobComplete.apply(api.getSecurityGroupApi().authorizeIngressPortsToCIDRs(id,\n                 ipPermission.getIpProtocol().toString().toUpperCase(),\n                 ipPermission.getFromPort(),\n                 ipPermission.getToPort(),\n                 ipPermission.getCidrBlocks()));\n      }\n\n      if (!ipPermission.getTenantIdGroupNamePairs().isEmpty()) {\n         jobComplete.apply(api.getSecurityGroupApi().authorizeIngressPortsToSecurityGroups(id,\n                 ipPermission.getIpProtocol().toString().toUpperCase(),\n                 ipPermission.getFromPort(),\n                 ipPermission.getToPort(),\n                 ipPermission.getTenantIdGroupNamePairs()));\n      }\n\n      return getSecurityGroupById(id);\n   }\n\n   @Override\n   public SecurityGroup addIpPermission(IpProtocol protocol, int startPort, int endPort,\n                                        Multimap<String, String> tenantIdGroupNamePairs,\n                                        Iterable<String> ipRanges,\n                                        Iterable<String> groupIds, SecurityGroup group) {\n      IpPermission.Builder permBuilder = IpPermission.builder();\n      permBuilder.ipProtocol(protocol);\n      permBuilder.fromPort(startPort);\n      permBuilder.toPort(endPort);\n      permBuilder.tenantIdGroupNamePairs(tenantIdGroupNamePairs);\n      permBuilder.cidrBlocks(ipRanges);\n      permBuilder.groupIds(groupIds);\n\n      return addIpPermission(permBuilder.build(), group);\n   }\n\n   @Override\n   public SecurityGroup removeIpPermission(IpPermission ipPermission, SecurityGroup group) {\n      checkNotNull(group, \"group\");\n      checkNotNull(ipPermission, \"ipPermission\");\n      String id = checkNotNull(group.getId(), \"group.getId()\");\n\n      org.jclouds.cloudstack.domain.SecurityGroup rawGroup = api.getSecurityGroupApi()\n              .getSecurityGroup(id);\n\n      if (!ipPermission.getCidrBlocks().isEmpty()) {\n         for (IngressRule rule : filter(rawGroup.getIngressRules(),\n                 ruleCidrMatches(ipPermission.getIpProtocol().toString(),\n                         ipPermission.getFromPort(),\n                         ipPermission.getToPort(),\n                         ipPermission.getCidrBlocks()))) {\n             jobComplete.apply(api.getSecurityGroupApi().revokeIngressRule(rule.getId()));\n         }\n      }\n\n      if (!ipPermission.getTenantIdGroupNamePairs().isEmpty()) {\n         for (IngressRule rule : filter(rawGroup.getIngressRules(),\n                 ruleGroupMatches(ipPermission.getIpProtocol().toString(),\n                         ipPermission.getFromPort(),\n                         ipPermission.getToPort(),\n                         ipPermission.getTenantIdGroupNamePairs()))) {\n             jobComplete.apply(api.getSecurityGroupApi().revokeIngressRule(rule.getId()));\n         }\n      }\n\n      return getSecurityGroupById(id);\n   }\n\n   @Override\n   public SecurityGroup removeIpPermission(IpProtocol protocol, int startPort, int endPort,\n                                           Multimap<String, String> tenantIdGroupNamePairs,\n                                           Iterable<String> ipRanges,\n                                           Iterable<String> groupIds, SecurityGroup group) {\n      IpPermission.Builder permBuilder = IpPermission.builder();\n      permBuilder.ipProtocol(protocol);\n      permBuilder.fromPort(startPort);\n      permBuilder.toPort(endPort);\n      permBuilder.tenantIdGroupNamePairs(tenantIdGroupNamePairs);\n      permBuilder.cidrBlocks(ipRanges);\n      permBuilder.groupIds(groupIds);\n\n      return removeIpPermission(permBuilder.build(), group);\n   }\n\n   @Override\n   public boolean supportsTenantIdGroupNamePairs() {\n      return true;\n   }\n\n   @Override\n   public boolean supportsTenantIdGroupIdPairs() {\n      return false;\n   }\n\n   @Override\n   public boolean supportsGroupIds() {\n      return false;\n   }\n\n   @Override\n   public boolean supportsPortRangesForGroups() {\n      return false;\n   }\n\n   @Override\n   public boolean supportsExclusionCidrBlocks() {\n      return false;\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/compute/functions/CloudStackSecurityGroupToSecurityGroup.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.compute.functions;\n\nimport static com.google.common.collect.Iterables.transform;\n\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.domain.SecurityGroup;\nimport org.jclouds.compute.domain.SecurityGroupBuilder;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.net.domain.IpPermission;\nimport org.jclouds.cloudstack.domain.IngressRule;\n\nimport com.google.common.base.Function;\nimport com.google.inject.Inject;\n\n\n/**\n * A function for transforming a CloudStack-specific SecurityGroup into a generic\n * SecurityGroup object.\n */\n@Singleton\npublic class CloudStackSecurityGroupToSecurityGroup implements Function<org.jclouds.cloudstack.domain.SecurityGroup, SecurityGroup> {\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   protected final Function<IngressRule, IpPermission> ruleToPermission;\n   \n   @Inject\n   public CloudStackSecurityGroupToSecurityGroup(Function<IngressRule, IpPermission> ruleToPermission) {\n      this.ruleToPermission = ruleToPermission;\n   }\n\n   @Override\n   public SecurityGroup apply(org.jclouds.cloudstack.domain.SecurityGroup group) {\n      SecurityGroupBuilder builder = new SecurityGroupBuilder();\n      \n      builder.id(group.getId());\n      builder.providerId(group.getId());\n      builder.name(group.getName());\n      builder.ownerId(group.getAccount());\n      builder.ipPermissions(transform(group.getIngressRules(), ruleToPermission));\n      \n      return builder.build();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/compute/functions/IngressRuleToIpPermission.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.compute.functions;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\n\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.cloudstack.domain.IngressRule;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.net.domain.IpPermission;\nimport org.jclouds.net.domain.IpProtocol;\n\nimport com.google.common.base.Function;\n\n\n/**\n * A function for transforming a CloudStack-specific IngressRule into a generic\n * IpPermission object.\n */\npublic class IngressRuleToIpPermission implements Function<IngressRule, IpPermission> {\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n   \n   public IngressRuleToIpPermission() {\n   }\n\n   @Override\n   public IpPermission apply(IngressRule rule) {\n      IpPermission.Builder builder = IpPermission.builder();\n      builder.ipProtocol(IpProtocol.fromValue(rule.getProtocol()));\n      builder.fromPort(rule.getStartPort());\n      builder.toPort(rule.getEndPort());\n      if (rule.getCIDR() != null) {\n         builder.cidrBlock(rule.getCIDR());\n      }\n      if (rule.getSecurityGroupName() != null\n              && rule.getAccount() != null) {\n         builder.tenantIdGroupNamePair(rule.getAccount(), rule.getSecurityGroupName());\n      }\n      return builder.build();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/compute/functions/OrphanedGroupsByZoneId.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.compute.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.transform;\nimport static com.google.common.collect.Sets.filter;\n\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.compute.ComputeService;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.predicates.NodePredicates;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.cloudstack.compute.predicates.AllNodesInGroupTerminated;\nimport org.jclouds.cloudstack.domain.ZoneAndName;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Multimap;\nimport com.google.common.collect.Multimaps;\n\npublic class OrphanedGroupsByZoneId implements Function<Set<? extends NodeMetadata>, Multimap<String, String>> {\n   private final Predicate<ZoneAndName> allNodesInGroupTerminated;\n\n   @Inject\n   protected OrphanedGroupsByZoneId(ComputeService computeService) {\n      this(new AllNodesInGroupTerminated(checkNotNull(computeService, \"computeService\")));\n   }\n\n   @VisibleForTesting\n   OrphanedGroupsByZoneId(Predicate<ZoneAndName> allNodesInGroupTerminated) {\n      this.allNodesInGroupTerminated = checkNotNull(allNodesInGroupTerminated, \"allNodesInGroupTerminated\");\n   }\n\n   public Multimap<String, String> apply(Set<? extends NodeMetadata> deadNodes) {\n      Iterable<? extends NodeMetadata> nodesWithGroup = filter(deadNodes, NodePredicates.hasGroup());\n      Set<ZoneAndName> zoneAndGroupNames = ImmutableSet.copyOf(filter(transform(nodesWithGroup,\n               new Function<NodeMetadata, ZoneAndName>() {\n\n                  @Override\n                  public ZoneAndName apply(NodeMetadata input) {\n                     String zoneId = input.getLocation().getScope() == LocationScope.HOST ? input.getLocation()\n                              .getParent().getId() : input.getLocation().getId();\n                     return ZoneAndName.fromZoneAndName(zoneId, input.getGroup());\n                  }\n\n               }), allNodesInGroupTerminated));\n      Multimap<String, String> zoneToZoneAndGroupNames = Multimaps.transformValues(Multimaps.index(zoneAndGroupNames,\n               ZoneAndName.ZONE_FUNCTION), ZoneAndName.NAME_FUNCTION);\n      return zoneToZoneAndGroupNames;\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/compute/functions/ServiceOfferingToHardware.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.compute.functions;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.cloudstack.domain.ServiceOffering;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.HardwareBuilder;\nimport org.jclouds.compute.domain.Processor;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableList;\n\n@Singleton\npublic class ServiceOfferingToHardware implements Function<ServiceOffering, Hardware> {\n\n   @Override\n   public Hardware apply(ServiceOffering offering) {\n      return new HardwareBuilder()\n            .ids(offering.getId() + \"\")\n            .name(offering.getName())\n            .tags(offering.getTags())\n            .processors(ImmutableList.of(new Processor(offering.getCpuNumber(), offering.getCpuSpeed())))\n            .ram(offering.getMemory())//\n            // TODO: hypervisor probably from zone?\n            // TODO .volumes()\n            // displayText\n            // created\n            // haSupport\n            // storageType\n            // TODO where's the location of this?\n            .build();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/compute/functions/TemplateToImage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.compute.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.location.predicates.LocationPredicates.idEquals;\n\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.cloudstack.domain.Template;\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.Image.Status;\nimport org.jclouds.compute.domain.ImageBuilder;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.domain.Location;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.FluentIterable;\n\n@Singleton\npublic class TemplateToImage implements Function<Template, Image> {\n   private final Supplier<Set<? extends Location>> locations;\n   private final Function<Template, OperatingSystem> templateToOperatingSystem;\n\n   @Inject\n   public TemplateToImage(@Memoized Supplier<Set<? extends Location>> locations,\n         Function<Template, OperatingSystem> templateToOperatingSystem) {\n      this.locations = checkNotNull(locations, \"locations\");\n      this.templateToOperatingSystem = checkNotNull(templateToOperatingSystem, \"templateToOperatingSystem\");\n   }\n\n   @Override\n   public Image apply(Template template) {\n      checkNotNull(template, \"template\");\n\n      OperatingSystem os = templateToOperatingSystem.apply(template);\n\n      ImageBuilder builder = new ImageBuilder().ids(template.getId() + \"\").name(template.getName())\n            .description(template.getDisplayText()).operatingSystem(os);\n\n      if (!template.isCrossZones())\n         builder.location(FluentIterable.from(locations.get()).firstMatch(idEquals(template.getZoneId())).orNull());\n\n      //TODO: implement status mapping!!!\n      builder.status(Status.AVAILABLE);\n      return builder.build();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/compute/functions/TemplateToOperatingSystem.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.compute.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.cloudstack.domain.OSType;\nimport org.jclouds.cloudstack.domain.Template;\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.OperatingSystem.Builder;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.compute.util.ComputeServiceUtils;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\n\n@Singleton\npublic class TemplateToOperatingSystem implements Function<Template, OperatingSystem> {\n   // CentOS 5.2 (32-bit)\n   public static final Pattern DEFAULT_PATTERN = Pattern.compile(\".* ([0-9.]+) ?\\\\(.*\");\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   private final Supplier<Map<String, OSType>> osTypes;\n   private final Supplier<Map<String, String>> osCategories;\n   private final Map<OsFamily, Map<String, String>> osVersionMap;\n\n   @Inject\n   public TemplateToOperatingSystem(@Memoized Supplier<Map<String, OSType>> osTypes,\n         @Memoized Supplier<Map<String, String>> osCategories, Map<OsFamily, Map<String, String>> osVersionMap) {\n      this.osTypes = checkNotNull(osTypes, \"osTypes\");\n      this.osCategories = checkNotNull(osCategories, \"osCategories\");\n      this.osVersionMap = checkNotNull(osVersionMap, \"osVersionMap\");\n   }\n\n   public OperatingSystem apply(Template from) {\n      Builder builder = OperatingSystem.builder().description(from.getOSType());\n\n      OSType type = osTypes.get().get(from.getOSTypeId());\n      if (type == null) {\n         logger.warn(\"Template refers to OS type ID %s but this does not exist. Template=%s Known OS types=%s\", from.getOSTypeId(), from, osTypes.get());\n         return builder.build();\n      }\n      builder.description(type.getDescription());\n      builder.is64Bit(type.getDescription().indexOf(\"64-bit\") != -1);\n      String osCategory = osCategories.get().get(type.getOSCategoryId());\n      if (osCategory == null) {\n         logger.warn(\"OS type refers to OS category ID %s but this does not exist. OS type=%s Known OS categories=%s\", type.getOSCategoryId(), type, osCategories.get());\n         return builder.build();\n      }\n      builder.name(osCategory);\n      OsFamily family = OsFamily.fromValue(osCategory.toLowerCase());\n      builder.family(family);\n      Matcher matcher = DEFAULT_PATTERN.matcher(type.getDescription());\n      if (matcher.find()) {\n         builder.version(ComputeServiceUtils.parseVersionOrReturnEmptyString(family, matcher.group(1), osVersionMap));\n      }\n      return builder.build();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/compute/functions/VirtualMachineToNodeMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.compute.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Predicates.equalTo;\nimport static com.google.common.base.Predicates.not;\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.transform;\nimport static com.google.common.collect.Maps.filterValues;\nimport static com.google.common.collect.Sets.newHashSet;\nimport static org.jclouds.location.predicates.LocationPredicates.idEquals;\nimport static org.jclouds.util.InetAddresses2.isPrivateIPAddress;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\nimport java.util.Map;\nimport java.util.Set;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Throwables;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\nimport com.google.common.util.concurrent.UncheckedExecutionException;\nimport org.jclouds.cloudstack.domain.IPForwardingRule;\nimport org.jclouds.cloudstack.domain.NIC;\nimport org.jclouds.cloudstack.domain.Tag;\nimport org.jclouds.cloudstack.domain.VirtualMachine;\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.domain.HardwareBuilder;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadata.Status;\nimport org.jclouds.compute.domain.NodeMetadataBuilder;\nimport org.jclouds.compute.domain.Processor;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.domain.Location;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.jclouds.util.Throwables2;\n\n@Singleton\npublic class VirtualMachineToNodeMetadata implements Function<VirtualMachine, NodeMetadata> {\n\n   public static final Map<VirtualMachine.State, Status> vmStateToNodeStatus = ImmutableMap\n         .<VirtualMachine.State, Status> builder().put(VirtualMachine.State.STARTING, Status.PENDING)\n         .put(VirtualMachine.State.RUNNING, Status.RUNNING).put(VirtualMachine.State.STOPPING, Status.PENDING)\n         .put(VirtualMachine.State.STOPPED, Status.SUSPENDED)\n         .put(VirtualMachine.State.DESTROYED, Status.TERMINATED)\n         .put(VirtualMachine.State.EXPUNGING, Status.TERMINATED)\n         .put(VirtualMachine.State.MIGRATING, Status.PENDING).put(VirtualMachine.State.ERROR, Status.ERROR)\n         .put(VirtualMachine.State.UNKNOWN, Status.UNRECOGNIZED)\n         // TODO: is this really a state?\n         .put(VirtualMachine.State.SHUTDOWNED, Status.PENDING)\n         .put(VirtualMachine.State.UNRECOGNIZED, Status.UNRECOGNIZED).build();\n\n   private final Supplier<Set<? extends Location>> locations;\n   private final Supplier<Set<? extends Image>> images;\n   private final LoadingCache<String, Set<IPForwardingRule>> getIPForwardingRulesByVirtualMachine;\n   private final GroupNamingConvention nodeNamingConvention;\n\n   @Inject\n   VirtualMachineToNodeMetadata(@Memoized Supplier<Set<? extends Location>> locations,\n         @Memoized Supplier<Set<? extends Image>> images,\n         LoadingCache<String, Set<IPForwardingRule>> getIPForwardingRulesByVirtualMachine,\n         GroupNamingConvention.Factory namingConvention) {\n      this.nodeNamingConvention = checkNotNull(namingConvention, \"namingConvention\").createWithoutPrefix();\n      this.locations = checkNotNull(locations, \"locations\");\n      this.images = checkNotNull(images, \"images\");\n      this.getIPForwardingRulesByVirtualMachine = checkNotNull(getIPForwardingRulesByVirtualMachine,\n            \"getIPForwardingRulesByVirtualMachine\");\n   }\n\n   @Override\n   public NodeMetadata apply(final VirtualMachine from) {\n      // convert the result object to a jclouds NodeMetadata\n      NodeMetadataBuilder builder = new NodeMetadataBuilder();\n      builder.ids(from.getId() + \"\");\n      builder.name(from.getName());\n      // TODO: in cloudstack 2.2.12, when \"name\" was set fine on the backend,\n      // but wrong API response was returned to the user\n      // http://bugs.cloud.com/show_bug.cgi?id=11664\n      //\n      // we set displayName to the same value as name, but this could be wrong\n      // on hosts not started with jclouds\n      builder.hostname(from.getDisplayName());\n      builder.location(FluentIterable.from(locations.get()).firstMatch(idEquals(from.getZoneId())).orNull());\n      if (from.getGroup() != null) {\n         builder.group(from.getGroup());\n      } else if (from.getDisplayName() != null) {\n         builder.group(nodeNamingConvention.groupInUniqueNameOrNull(from.getDisplayName()));\n      }\n      Image image = FluentIterable.from(images.get()).firstMatch(new Predicate<Image>() {\n         @Override\n         public boolean apply(Image input) {\n            return input.getProviderId().equals(from.getTemplateId() + \"\")\n            // either location free image (location is null) or in the same zone as the VM\n                  && (input.getLocation() == null || input.getId().equals(from.getZoneId() + \"\"));\n         }\n      }).orNull();\n      if (image != null) {\n         builder.imageId(image.getId());\n         builder.operatingSystem(image.getOperatingSystem());\n      }\n\n      if (!from.getTags().isEmpty()) {\n         ImmutableMap.Builder<String, String> tagsBuilder = ImmutableMap.<String, String>builder();\n\n         for (Tag tag : from.getTags()) {\n            tagsBuilder.put(tag.getKey(), tag.getValue());\n         }\n\n         Map<String, String> tagMap = tagsBuilder.build();\n         builder.tags(filterValues(tagMap, equalTo(\"jclouds-empty-tag-placeholder\")).keySet())\n               .userMetadata(filterValues(tagMap, not(equalTo(\"jclouds-empty-tag-placeholder\"))));\n      }\n\n      builder.hardware(new HardwareBuilder()\n        .ids(from.getServiceOfferingId() + \"\")\n        .name(from.getServiceOfferingName() + \"\")\n        .processors(ImmutableList.of(new Processor(from.getCpuCount(), from.getCpuSpeed())))\n        .ram((int)from.getMemory())//\n        .hypervisor(from.getHypervisor())//\n        .build());\n\n      builder.status(vmStateToNodeStatus.get(from.getState()));\n\n      Set<String> publicAddresses = newHashSet();\n      Set<String> privateAddresses = newHashSet();\n      if (from.getIPAddress() != null) {\n         boolean isPrivate = isPrivateIPAddress(from.getIPAddress());\n         if (isPrivate) {\n            privateAddresses.add(from.getIPAddress());\n         } else {\n            publicAddresses.add(from.getIPAddress());\n         }\n      }\n      if (from.getPublicIP() != null) {\n          publicAddresses.add(from.getPublicIP());\n      }\n      for (NIC nic : from.getNICs()) {\n         if (nic.getIPAddress() != null) {\n            if (isPrivateIPAddress(nic.getIPAddress())) {\n               privateAddresses.add(nic.getIPAddress());\n            } else {\n               publicAddresses.add(nic.getIPAddress());\n            }\n         }\n      }\n      try {\n         /* Also add to the list of public IPs any public IP address that has a\n            forwarding rule that links to this machine */\n         Iterables.addAll(publicAddresses, transform(\n            filter(getIPForwardingRulesByVirtualMachine.getUnchecked(from.getId()),\n               new Predicate<IPForwardingRule>() {\n                  @Override\n                  public boolean apply(IPForwardingRule rule) {\n                     return !\"Deleting\".equals(rule.getState());\n                  }\n               }), new Function<IPForwardingRule, String>() {\n            @Override\n            public String apply(IPForwardingRule rule) {\n               return rule.getIPAddress();\n            }\n         }));\n      } catch (UncheckedExecutionException e) {\n         if (Throwables2.getFirstThrowableOfType(e, ResourceNotFoundException.class) == null) {\n            Throwables.propagateIfPossible(e.getCause());\n            throw e;\n         }\n      }\n      return builder.privateAddresses(privateAddresses).publicAddresses(publicAddresses).build();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/compute/functions/ZoneToLocation.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.compute.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.cloudstack.domain.Zone;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.location.suppliers.all.JustProvider;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\n\n/**\n * Converts an Zone into a Location.\n */\npublic class ZoneToLocation implements Function<Zone, Location> {\n   private final JustProvider provider;\n\n   // allow us to lazy discover the provider of a resource\n   @Inject\n   public ZoneToLocation(JustProvider provider) {\n      this.provider = checkNotNull(provider, \"provider\");\n   }\n\n   @Override\n   public Location apply(Zone zone) {\n      return new LocationBuilder().scope(LocationScope.ZONE).metadata(ImmutableMap.<String, Object> of())\n          .description(zone.getName()).id(zone.getId())\n            .parent(Iterables.getOnlyElement(provider.get())).build();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/compute/loaders/CreateUniqueKeyPair.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.compute.loaders;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.cloudstack.CloudStackApi;\nimport org.jclouds.cloudstack.domain.SshKeyPair;\n\nimport com.google.common.base.Throwables;\nimport com.google.common.cache.CacheLoader;\nimport com.google.inject.Inject;\n\n@Singleton\npublic class CreateUniqueKeyPair extends CacheLoader<String, SshKeyPair> {\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n   protected final CloudStackApi client;\n\n   @Inject\n   public CreateUniqueKeyPair(CloudStackApi client) {\n      this.client = checkNotNull(client, \"client\");\n   }\n\n   @Override\n   public SshKeyPair load(String input) {\n      SshKeyPair keyPair = null;\n      while (keyPair == null) {\n         try {\n            keyPair = client.getSSHKeyPairApi().createSSHKeyPair(input);\n            logger.debug(\">> creating SSH key pair with name %s\", input);\n         } catch (IllegalStateException e) {\n            logger.error(e, \"<< error creating SSH key pair with name %s: \",\n                         Throwables.getRootCause(e).getMessage());\n            throw Throwables.propagate(e);\n         }\n      }\n\n      logger.debug(\"<< created keyPair(%s)\", keyPair.getName());\n      return keyPair;\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/compute/loaders/FindSecurityGroupOrCreate.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.compute.loaders;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\n\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\n\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.cloudstack.CloudStackApi;\nimport org.jclouds.cloudstack.domain.SecurityGroup;\nimport org.jclouds.cloudstack.domain.ZoneAndName;\nimport org.jclouds.cloudstack.domain.ZoneSecurityGroupNamePortsCidrs;\n\nimport com.google.common.base.Function;\nimport com.google.common.cache.CacheLoader;\n\npublic class FindSecurityGroupOrCreate extends CacheLoader<ZoneAndName, SecurityGroup> {\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n   protected final CloudStackApi client;\n   protected final Function<ZoneSecurityGroupNamePortsCidrs, SecurityGroup> groupCreator;\n\n   @Inject\n   public FindSecurityGroupOrCreate(CloudStackApi client,\n                                    Function<ZoneSecurityGroupNamePortsCidrs, SecurityGroup> groupCreator) {\n      this.client = checkNotNull(client, \"client\");\n      this.groupCreator = checkNotNull(groupCreator, \"groupCreator\");\n   }\n\n   @Override\n   public SecurityGroup load(ZoneAndName in) {\n      SecurityGroup group = client.getSecurityGroupApi().getSecurityGroupByName(in.getName());\n      if (group != null) {\n         return group;\n      } else {\n         return createNewSecurityGroup(in);\n      }\n   }\n\n   private SecurityGroup createNewSecurityGroup(ZoneAndName in) {\n      checkState(\n               checkNotNull(in, \"ZoneSecurityGrioupNamePortsCidrs\") instanceof ZoneSecurityGroupNamePortsCidrs,\n               \"programming error: when issuing get to this cacheloader, you need to pass an instance of ZoneSecurityGroupNamePortsCidrs, not %s\",\n               in);\n      ZoneSecurityGroupNamePortsCidrs zoneSecurityGroupNamePortsCidrs = ZoneSecurityGroupNamePortsCidrs.class.cast(in);\n      return groupCreator.apply(zoneSecurityGroupNamePortsCidrs);\n   }\n\n   @Override\n   public String toString() {\n      return \"returnExistingSecurityGroupInZoneOrCreateAsNeeded()\";\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/compute/options/CloudStackTemplateOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.compute.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.io.IOException;\nimport java.net.URL;\nimport java.util.Arrays;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.scriptbuilder.domain.Statement;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.io.Resources;\n\n/**\n * Contains options supported by the\n * {@link ComputeService#createNodesInGroup(String, int, TemplateOptions)} and\n * {@link ComputeService#createNodesInGroup(String, int, TemplateOptions)}\n * operations on the <em>gogrid</em> provider.\n *\n * <h2>Usage</h2> The recommended way to instantiate a\n * {@link CloudStackTemplateOptions} object is to statically import\n * {@code CloudStackTemplateOptions.*} and invoke a static creation method\n * followed by an instance mutator (if needed):\n * <p>\n *\n * <pre>\n * import static org.jclouds.compute.options.CloudStackTemplateOptions.Builder.*;\n * ComputeService client = // get connection\n * templateBuilder.options(inboundPorts(22, 80, 8080, 443));\n * Set&lt;? extends NodeMetadata&gt; set = client.createNodesInGroup(tag, 2, templateBuilder.build());\n * </pre>\n */\npublic class CloudStackTemplateOptions extends TemplateOptions implements Cloneable {\n\n   private Set<String> securityGroupIds = ImmutableSet.of();\n   private Map<String, String> ipsToNetworks = ImmutableMap.of();\n   private String ipOnDefaultNetwork;\n   private String keyPair;\n   private boolean setupStaticNat = true;\n   private String account;\n   private String domainId;\n   private boolean generateKeyPair = false;\n   private boolean generateSecurityGroup = false;\n   private String diskOfferingId;\n   private int dataDiskSize;\n   private byte[] userData;\n\n   public CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds) {\n      this.securityGroupIds = ImmutableSet.copyOf(securityGroupIds);\n      return this;\n   }\n\n   public CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipsToNetworks) {\n      this.ipsToNetworks = ImmutableMap.copyOf(ipsToNetworks);\n      return this;\n   }\n\n   public CloudStackTemplateOptions ipOnDefaultNetwork(String ipOnDefaultNetwork) {\n      this.ipOnDefaultNetwork = ipOnDefaultNetwork;\n      return this;\n   }\n\n   public CloudStackTemplateOptions keyPair(String keyPair) {\n      this.keyPair = keyPair;\n      return this;\n   }\n\n   public CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat) {\n      this.setupStaticNat = setupStaticNat;\n      return this;\n   }\n\n   public CloudStackTemplateOptions account(String account) {\n      this.account = account;\n      return this;\n   }\n\n   public CloudStackTemplateOptions domainId(String domainId) {\n      this.domainId = domainId;\n      return this;\n   }\n\n   public CloudStackTemplateOptions generateKeyPair(boolean generateKeyPair) {\n      this.generateKeyPair = generateKeyPair;\n      return this;\n   }\n\n   public CloudStackTemplateOptions generateSecurityGroup(boolean generateSecurityGroup) {\n      this.generateSecurityGroup = generateSecurityGroup;\n      return this;\n   }\n\n   public CloudStackTemplateOptions diskOfferingId(String diskOfferingId) {\n      this.diskOfferingId = diskOfferingId;\n      return this;\n   }\n\n   public CloudStackTemplateOptions dataDiskSize(int dataDiskSize) {\n      this.dataDiskSize = dataDiskSize;\n      return this;\n   }\n\n   public CloudStackTemplateOptions userData(byte[] userData) {\n      this.userData = userData;\n      return this;\n   }\n\n   public CloudStackTemplateOptions userData(String userData) {\n      this.userData = checkNotNull(userData, \"userdata\").getBytes(Charsets.UTF_8);\n      return this;\n   }\n\n   public CloudStackTemplateOptions userData(URL userDataUrl) throws IOException {\n      this.userData = Resources.toString(checkNotNull(userDataUrl, \"userDataUrl\"), Charsets.UTF_8).getBytes(Charsets.UTF_8);\n      return this;\n   }\n\n   public Set<String> getSecurityGroupIds() {\n      return securityGroupIds;\n   }\n\n   public Map<String, String> getIpsToNetworks() {\n      return ipsToNetworks;\n   }\n\n   public String getIpOnDefaultNetwork() {\n      return ipOnDefaultNetwork;\n   }\n\n   public String getKeyPair() {\n      return keyPair;\n   }\n\n   public boolean shouldSetupStaticNat() {\n      return setupStaticNat;\n   }\n\n   public String getAccount() {\n      return account;\n   }\n\n   public String getDomainId() {\n      return domainId;\n   }\n\n   public boolean shouldGenerateKeyPair() {\n      return generateKeyPair;\n   }\n\n   public boolean shouldGenerateSecurityGroup() {\n      return generateSecurityGroup;\n   }\n\n   public String getDiskOfferingId() {\n      return diskOfferingId;\n   }\n\n   public int getDataDiskSize() {\n      return dataDiskSize;\n   }\n\n   public byte[] getUserData() {\n      return userData;\n   }\n\n   @Override\n   public CloudStackTemplateOptions clone() {\n      CloudStackTemplateOptions options = new CloudStackTemplateOptions();\n      copyTo(options);\n      return options;\n   }\n\n   @Override\n   public void copyTo(TemplateOptions to) {\n      super.copyTo(to);\n      if (to instanceof CloudStackTemplateOptions) {\n         CloudStackTemplateOptions eTo = CloudStackTemplateOptions.class.cast(to);\n         eTo.securityGroupIds(securityGroupIds);\n         eTo.ipsToNetworks(ipsToNetworks);\n         eTo.ipOnDefaultNetwork(ipOnDefaultNetwork);\n         eTo.keyPair(keyPair);\n         eTo.generateKeyPair(generateKeyPair);\n         eTo.generateSecurityGroup(generateSecurityGroup);\n         eTo.account(account);\n         eTo.domainId(domainId);\n         eTo.setupStaticNat(setupStaticNat);\n         eTo.diskOfferingId(diskOfferingId);\n         eTo.dataDiskSize(dataDiskSize);\n         eTo.userData(userData);\n      }\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o) return true;\n      if (!(o instanceof CloudStackTemplateOptions)) return false;\n      if (!super.equals(o)) return false;\n      CloudStackTemplateOptions that = (CloudStackTemplateOptions) o;\n      return setupStaticNat == that.setupStaticNat &&\n              generateKeyPair == that.generateKeyPair &&\n              generateSecurityGroup == that.generateSecurityGroup &&\n              dataDiskSize == that.dataDiskSize &&\n              Objects.equal(securityGroupIds, that.securityGroupIds) &&\n              Objects.equal(ipsToNetworks, that.ipsToNetworks) &&\n              Objects.equal(ipOnDefaultNetwork, that.ipOnDefaultNetwork) &&\n              Objects.equal(keyPair, that.keyPair) &&\n              Objects.equal(account, that.account) &&\n              Objects.equal(domainId, that.domainId) &&\n              Objects.equal(diskOfferingId, that.diskOfferingId) &&\n              Arrays.equals(userData, that.userData);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(super.hashCode(), securityGroupIds, ipsToNetworks, ipOnDefaultNetwork, keyPair, setupStaticNat, account, domainId, generateKeyPair, generateSecurityGroup, diskOfferingId, dataDiskSize, Arrays.hashCode(userData));\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this)\n              .add(\"securityGroupIds\", securityGroupIds)\n              .add(\"ipsToNetworks\", ipsToNetworks)\n              .add(\"ipOnDefaultNetwork\", ipOnDefaultNetwork)\n              .add(\"keyPair\", keyPair)\n              .add(\"setupStaticNat\", setupStaticNat)\n              .add(\"account\", account)\n              .add(\"domainId\", domainId)\n              .add(\"generateKeyPair\", generateKeyPair)\n              .add(\"generateSecurityGroup\", generateSecurityGroup)\n              .add(\"diskOfferingId\", diskOfferingId)\n              .add(\"dataDiskSize\", dataDiskSize)\n              .add(\"userData\", userData)\n              .toString();\n   }\n\n   public static class Builder {\n\n      /**\n       * @see CloudStackTemplateOptions#securityGroupIds\n       */\n      public static CloudStackTemplateOptions securityGroupIds(Iterable<String> securityGroupIds) {\n         CloudStackTemplateOptions options = new CloudStackTemplateOptions();\n         return options.securityGroupIds(securityGroupIds);\n      }\n\n      /**\n       * @see CloudStackTemplateOptions#ipsToNetworks\n       */\n      public static CloudStackTemplateOptions ipsToNetworks(Map<String, String> ipToNetworkMap) {\n         CloudStackTemplateOptions options = new CloudStackTemplateOptions();\n         return options.ipsToNetworks(ipToNetworkMap);\n      }\n\n      /**\n       * @see CloudStackTemplateOptions#ipOnDefaultNetwork\n       */\n      public static CloudStackTemplateOptions ipOnDefaultNetwork(String ipAddress) {\n         CloudStackTemplateOptions options = new CloudStackTemplateOptions();\n         return options.ipOnDefaultNetwork(ipAddress);\n      }\n\n      /**\n       * @see CloudStackTemplateOptions#keyPair\n       */\n      public static CloudStackTemplateOptions keyPair(String keyPair) {\n         CloudStackTemplateOptions options = new CloudStackTemplateOptions();\n         return options.keyPair(keyPair);\n      }\n\n      /**\n       * @see CloudStackTemplateOptions#setupStaticNat\n       */\n      public static CloudStackTemplateOptions setupStaticNat(boolean setupStaticNat) {\n         CloudStackTemplateOptions options = new CloudStackTemplateOptions();\n         return options.setupStaticNat(setupStaticNat);\n      }\n\n      /**\n       * @see CloudStackTemplateOptions#account\n       */\n      public static CloudStackTemplateOptions account(String account) {\n         CloudStackTemplateOptions options = new CloudStackTemplateOptions();\n         return options.account(account);\n      }\n\n      /**\n       * @see CloudStackTemplateOptions#domainId\n       */\n      public static CloudStackTemplateOptions domainId(String domainId) {\n         CloudStackTemplateOptions options = new CloudStackTemplateOptions();\n         return options.domainId(domainId);\n      }\n\n      /**\n       * @see CloudStackTemplateOptions#generateKeyPair(boolean)\n       */\n      public static CloudStackTemplateOptions generateKeyPair(boolean enable) {\n         return new CloudStackTemplateOptions().generateKeyPair(enable);\n      }\n\n      /**\n       * @see CloudStackTemplateOptions#generateSecurityGroup(boolean)\n       */\n      public static CloudStackTemplateOptions generateSecurityGroup(boolean enable) {\n         return new CloudStackTemplateOptions().generateSecurityGroup(enable);\n      }\n\n      /**\n       * @see CloudStackTemplateOptions#diskOfferingId\n       */\n      public static CloudStackTemplateOptions diskOfferingId(String diskOfferingId) {\n         CloudStackTemplateOptions options = new CloudStackTemplateOptions();\n         return options.diskOfferingId(diskOfferingId);\n      }\n\n      /**\n       * @see CloudStackTemplateOptions#dataDiskSize\n       */\n      public static CloudStackTemplateOptions dataDiskSize(int dataDiskSize) {\n         CloudStackTemplateOptions options = new CloudStackTemplateOptions();\n         return options.dataDiskSize(dataDiskSize);\n      }\n\n      /**\n       * @see CloudStackTemplateOptions#userData\n       */\n      public static CloudStackTemplateOptions userData(byte[] userData) {\n         CloudStackTemplateOptions options = new CloudStackTemplateOptions();\n         return options.userData(userData);\n      }\n\n   }\n\n   // methods that only facilitate returning the correct object type\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public CloudStackTemplateOptions blockOnPort(int port, int seconds) {\n      return CloudStackTemplateOptions.class.cast(super.blockOnPort(port, seconds));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public CloudStackTemplateOptions inboundPorts(int... ports) {\n      return CloudStackTemplateOptions.class.cast(super.inboundPorts(ports));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public CloudStackTemplateOptions authorizePublicKey(String publicKey) {\n      return CloudStackTemplateOptions.class.cast(super.authorizePublicKey(publicKey));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public CloudStackTemplateOptions installPrivateKey(String privateKey) {\n      return CloudStackTemplateOptions.class.cast(super.installPrivateKey(privateKey));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public CloudStackTemplateOptions blockUntilRunning(boolean blockUntilRunning) {\n      return CloudStackTemplateOptions.class.cast(super.blockUntilRunning(blockUntilRunning));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public CloudStackTemplateOptions dontAuthorizePublicKey() {\n      return CloudStackTemplateOptions.class.cast(super.dontAuthorizePublicKey());\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public CloudStackTemplateOptions nameTask(String name) {\n      return CloudStackTemplateOptions.class.cast(super.nameTask(name));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public CloudStackTemplateOptions runAsRoot(boolean runAsRoot) {\n      return CloudStackTemplateOptions.class.cast(super.runAsRoot(runAsRoot));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public CloudStackTemplateOptions runScript(Statement script) {\n      return CloudStackTemplateOptions.class.cast(super.runScript(script));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public CloudStackTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials) {\n      return CloudStackTemplateOptions.class.cast(super.overrideLoginCredentials(overridingCredentials));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public CloudStackTemplateOptions overrideLoginPassword(String password) {\n      return CloudStackTemplateOptions.class.cast(super.overrideLoginPassword(password));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public CloudStackTemplateOptions overrideLoginPrivateKey(String privateKey) {\n      return CloudStackTemplateOptions.class.cast(super.overrideLoginPrivateKey(privateKey));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public CloudStackTemplateOptions overrideLoginUser(String loginUser) {\n      return CloudStackTemplateOptions.class.cast(super.overrideLoginUser(loginUser));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public CloudStackTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo) {\n      return CloudStackTemplateOptions.class.cast(super.overrideAuthenticateSudo(authenticateSudo));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public CloudStackTemplateOptions userMetadata(Map<String, String> userMetadata) {\n      return CloudStackTemplateOptions.class.cast(super.userMetadata(userMetadata));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public CloudStackTemplateOptions userMetadata(String key, String value) {\n      return CloudStackTemplateOptions.class.cast(super.userMetadata(key, value));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public CloudStackTemplateOptions nodeNames(Iterable<String> nodeNames) {\n      return CloudStackTemplateOptions.class.cast(super.nodeNames(nodeNames));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public CloudStackTemplateOptions networks(Iterable<String> networks) {\n      return CloudStackTemplateOptions.class.cast(super.networks(networks));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/compute/predicates/AllNodesInGroupTerminated.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.compute.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.all;\nimport static org.jclouds.compute.predicates.NodePredicates.TERMINATED;\nimport static org.jclouds.compute.predicates.NodePredicates.inGroup;\nimport static org.jclouds.compute.predicates.NodePredicates.locationId;\nimport static org.jclouds.compute.predicates.NodePredicates.parentLocationId;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.compute.ComputeService;\nimport org.jclouds.compute.domain.ComputeMetadata;\nimport org.jclouds.cloudstack.domain.ZoneAndName;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Predicates;\n\npublic class AllNodesInGroupTerminated implements Predicate<ZoneAndName> {\n   private final ComputeService computeService;\n\n   \n   //TODO: TESTME\n   @Inject\n   public AllNodesInGroupTerminated(ComputeService computeService) {\n      this.computeService = checkNotNull(computeService, \"computeService\");\n   }\n\n   @Override\n   public boolean apply(ZoneAndName input) {\n      // new nodes can have the zone as their location, existing nodes, the parent is the\n      // location\n      return all(computeService.listNodesDetailsMatching(Predicates.<ComputeMetadata> or(locationId(input.getZone()),\n               parentLocationId(input.getZone()))), Predicates.and(inGroup(input.getName()), TERMINATED));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/compute/strategy/AdvancedNetworkOptionsConverter.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.compute.strategy;\n\nimport com.google.common.collect.Iterables;\nimport org.jclouds.cloudstack.compute.options.CloudStackTemplateOptions;\nimport org.jclouds.cloudstack.domain.Network;\nimport org.jclouds.cloudstack.options.DeployVirtualMachineOptions;\n\nimport java.util.Map;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Predicates.and;\nimport static com.google.common.collect.Iterables.filter;\nimport static org.jclouds.cloudstack.predicates.NetworkPredicates.defaultNetworkInZone;\nimport static org.jclouds.cloudstack.predicates.NetworkPredicates.isIsolatedNetwork;\nimport static org.jclouds.cloudstack.predicates.NetworkPredicates.supportsStaticNAT;\n\n/**\n * Convert template options into DeployVirtualMachineOptions, when the target zone has advanced networking.\n */\npublic class AdvancedNetworkOptionsConverter implements OptionsConverter {\n   @Override\n   public DeployVirtualMachineOptions apply(CloudStackTemplateOptions templateOptions, Map<String, Network> networks, String zoneId, DeployVirtualMachineOptions options) {\n      // security groups not allowed.\n      // at least one network must be given to CloudStack,\n      // but jclouds will try to autodetect an appropriate network if none given.\n      checkArgument(templateOptions.getSecurityGroupIds().isEmpty(), \"security groups cannot be specified for locations (zones) that use advanced networking\");\n      if (!templateOptions.getNetworks().isEmpty()) {\n         options.networkIds(templateOptions.getNetworks());\n      } else if (templateOptions.getIpsToNetworks().isEmpty()) {\n         checkArgument(!networks.isEmpty(), \"please setup a network for zone: \" + zoneId);\n         Network defaultNetworkInZone = Iterables.getFirst(filter(networks.values(), and(defaultNetworkInZone(zoneId), supportsStaticNAT())), null);\n         if (defaultNetworkInZone == null) {\n             defaultNetworkInZone = Iterables.getFirst(filter(networks.values(), isIsolatedNetwork()), null);\n         }\n         if (defaultNetworkInZone == null) {\n             throw new IllegalArgumentException(\"please choose a specific network in zone \" + zoneId + \": \" + networks);\n         } else {\n             options.networkId(defaultNetworkInZone.getId());\n         }\n      }\n      return options;\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/compute/strategy/BasicNetworkOptionsConverter.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.compute.strategy;\n\nimport org.jclouds.cloudstack.compute.options.CloudStackTemplateOptions;\nimport org.jclouds.cloudstack.domain.Network;\nimport org.jclouds.cloudstack.options.DeployVirtualMachineOptions;\n\nimport java.util.Map;\n\n/**\n * Convert template options into DeployVirtualMachineOptions, when the target zone has basic networking.\n */\npublic class BasicNetworkOptionsConverter implements OptionsConverter {\n   @Override\n   public DeployVirtualMachineOptions apply(CloudStackTemplateOptions templateOptions, Map<String, Network> networks, String zoneId, DeployVirtualMachineOptions options) {\n      // both security groups and networks are optional, and CloudStack will\n      // use the zone/user's default network/security group if none given\n      if (!templateOptions.getSecurityGroupIds().isEmpty()) {\n         options.securityGroupIds(templateOptions.getSecurityGroupIds());\n      }\n      if (!templateOptions.getNetworks().isEmpty()) {\n         options.networkIds(templateOptions.getNetworks());\n      }\n      return options;\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/compute/strategy/CloudStackComputeServiceAdapter.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.compute.strategy;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.common.collect.Iterables.contains;\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.get;\nimport static org.jclouds.cloudstack.options.DeployVirtualMachineOptions.Builder.displayName;\nimport static org.jclouds.cloudstack.options.ListTemplatesOptions.Builder.id;\nimport static org.jclouds.cloudstack.predicates.TemplatePredicates.isReady;\nimport static org.jclouds.cloudstack.predicates.ZonePredicates.supportsSecurityGroups;\nimport static org.jclouds.ssh.SshKeys.fingerprintPrivateKey;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Sets;\nimport com.google.common.primitives.Ints;\nimport org.jclouds.cloudstack.CloudStackApi;\nimport org.jclouds.cloudstack.compute.options.CloudStackTemplateOptions;\nimport org.jclouds.cloudstack.domain.AsyncCreateResponse;\nimport org.jclouds.cloudstack.domain.Capabilities;\nimport org.jclouds.cloudstack.domain.FirewallRule;\nimport org.jclouds.cloudstack.domain.IPForwardingRule;\nimport org.jclouds.cloudstack.domain.NIC;\nimport org.jclouds.cloudstack.domain.Network;\nimport org.jclouds.cloudstack.domain.NetworkType;\nimport org.jclouds.cloudstack.domain.Project;\nimport org.jclouds.cloudstack.domain.PublicIPAddress;\nimport org.jclouds.cloudstack.domain.SecurityGroup;\nimport org.jclouds.cloudstack.domain.ServiceOffering;\nimport org.jclouds.cloudstack.domain.SshKeyPair;\nimport org.jclouds.cloudstack.domain.Tag;\nimport org.jclouds.cloudstack.domain.Template;\nimport org.jclouds.cloudstack.domain.VirtualMachine;\nimport org.jclouds.cloudstack.domain.Zone;\nimport org.jclouds.cloudstack.domain.ZoneAndName;\nimport org.jclouds.cloudstack.domain.ZoneSecurityGroupNamePortsCidrs;\nimport org.jclouds.cloudstack.features.TemplateApi;\nimport org.jclouds.cloudstack.functions.CreateFirewallRulesForIP;\nimport org.jclouds.cloudstack.functions.CreatePortForwardingRulesForIP;\nimport org.jclouds.cloudstack.functions.StaticNATVirtualMachineInNetwork;\nimport org.jclouds.cloudstack.functions.StaticNATVirtualMachineInNetwork.Factory;\nimport org.jclouds.cloudstack.options.CreateTagsOptions;\nimport org.jclouds.cloudstack.options.DeployVirtualMachineOptions;\nimport org.jclouds.cloudstack.options.ListFirewallRulesOptions;\nimport org.jclouds.cloudstack.options.ListTemplatesOptions;\nimport org.jclouds.cloudstack.strategy.BlockUntilJobCompletesAndReturnResult;\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.ComputeServiceAdapter;\nimport org.jclouds.compute.config.GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNull;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.logging.Logger;\n\n/**\n * defines the connection between the {@link CloudStackApi} implementation\n * and the jclouds {@link ComputeService}\n */\n@Singleton\npublic class CloudStackComputeServiceAdapter implements\n   ComputeServiceAdapter<VirtualMachine, ServiceOffering, Template, Zone> {\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   private final CloudStackApi client;\n   private final Predicate<String> jobComplete;\n   private final Supplier<Map<String, Network>> networkSupplier;\n   private final Supplier<Map<String, Project>> projectSupplier;\n   private final BlockUntilJobCompletesAndReturnResult blockUntilJobCompletesAndReturnResult;\n   private final Factory staticNATVMInNetwork;\n   private final CreatePortForwardingRulesForIP setupPortForwardingRulesForIP;\n   private final CreateFirewallRulesForIP setupFirewallRulesForIP;\n   private final LoadingCache<String, Set<IPForwardingRule>> vmToRules;\n   private final Map<String, Credentials> credentialStore;\n   private final Map<NetworkType, ? extends OptionsConverter> optionsConverters;\n   private final Supplier<LoadingCache<String, Zone>> zoneIdToZone;\n   private final LoadingCache<ZoneAndName, SecurityGroup> securityGroupCache;\n   private final LoadingCache<String, SshKeyPair> keyPairCache;\n   private final GroupNamingConvention.Factory namingConvention;\n   private final GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNull credentialsProvider;\n\n   @Inject\n   public CloudStackComputeServiceAdapter(CloudStackApi client, Predicate<String> jobComplete,\n                                          @Memoized Supplier<Map<String, Network>> networkSupplier,\n                                          @Memoized Supplier<Map<String, Project>> projectSupplier,\n                                          BlockUntilJobCompletesAndReturnResult blockUntilJobCompletesAndReturnResult,\n                                          StaticNATVirtualMachineInNetwork.Factory staticNATVMInNetwork,\n                                          CreatePortForwardingRulesForIP setupPortForwardingRulesForIP,\n                                          CreateFirewallRulesForIP setupFirewallRulesForIP,\n                                          LoadingCache<String, Set<IPForwardingRule>> vmToRules,\n                                          Map<String, Credentials> credentialStore,\n                                          Map<NetworkType, ? extends OptionsConverter> optionsConverters,\n                                          Supplier<LoadingCache<String, Zone>> zoneIdToZone,\n                                          LoadingCache<ZoneAndName, SecurityGroup> securityGroupCache,\n                                          LoadingCache<String, SshKeyPair> keyPairCache,\n                                          GroupNamingConvention.Factory namingConvention,\n                                          GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNull credentialsProvider) {\n      this.client = checkNotNull(client, \"client\");\n      this.jobComplete = checkNotNull(jobComplete, \"jobComplete\");\n      this.networkSupplier = checkNotNull(networkSupplier, \"networkSupplier\");\n      this.projectSupplier = checkNotNull(projectSupplier, \"projectSupplier\");\n      this.blockUntilJobCompletesAndReturnResult = checkNotNull(blockUntilJobCompletesAndReturnResult,\n         \"blockUntilJobCompletesAndReturnResult\");\n      this.staticNATVMInNetwork = checkNotNull(staticNATVMInNetwork, \"staticNATVMInNetwork\");\n      this.setupPortForwardingRulesForIP = checkNotNull(setupPortForwardingRulesForIP, \"setupPortForwardingRulesForIP\");\n      this.setupFirewallRulesForIP = checkNotNull(setupFirewallRulesForIP, \"setupFirewallRulesForIP\");\n      this.vmToRules = checkNotNull(vmToRules, \"vmToRules\");\n      this.credentialStore = checkNotNull(credentialStore, \"credentialStore\");\n      this.securityGroupCache = checkNotNull(securityGroupCache, \"securityGroupCache\");\n      this.keyPairCache = checkNotNull(keyPairCache, \"keyPairCache\");\n      this.optionsConverters = optionsConverters;\n      this.zoneIdToZone = zoneIdToZone;\n      this.namingConvention = namingConvention;\n      this.credentialsProvider = credentialsProvider;\n   }\n\n   @Override\n   public NodeAndInitialCredentials<VirtualMachine> createNodeWithGroupEncodedIntoName(String group, String name,\n                                                                                       org.jclouds.compute.domain.Template template) {\n\n      checkNotNull(template, \"template was null\");\n      checkNotNull(template.getOptions(), \"template options was null\");\n      checkArgument(template.getOptions().getClass().isAssignableFrom(CloudStackTemplateOptions.class),\n         \"options class %s should have been assignable from CloudStackTemplateOptions\", template.getOptions()\n         .getClass());\n      Map<String, Network> networks = networkSupplier.get();\n\n      final String zoneId = template.getLocation().getId();\n      Zone zone = zoneIdToZone.get().getUnchecked(zoneId);\n\n      CloudStackTemplateOptions templateOptions = template.getOptions().as(CloudStackTemplateOptions.class);\n\n      checkState(optionsConverters.containsKey(zone.getNetworkType()), \"no options converter configured for network type %s\", zone.getNetworkType());\n      DeployVirtualMachineOptions options = displayName(name).name(name);\n      if (templateOptions.getAccount() != null) {\n          options.accountInDomain(templateOptions.getAccount(), templateOptions.getDomainId());\n      } else if (templateOptions.getDomainId() != null) {\n          options.domainId(templateOptions.getDomainId());\n      }\n\n      OptionsConverter optionsConverter = optionsConverters.get(zone.getNetworkType());\n      options = optionsConverter.apply(templateOptions, networks, zoneId, options);\n\n      options.group(group);\n\n      if (templateOptions.getIpOnDefaultNetwork() != null) {\n         options.ipOnDefaultNetwork(templateOptions.getIpOnDefaultNetwork());\n      }\n\n      if (!templateOptions.getIpsToNetworks().isEmpty()) {\n         options.ipsToNetworks(templateOptions.getIpsToNetworks());\n      }\n\n      if (templateOptions.getUserData() != null) {\n         options.userData(templateOptions.getUserData());\n      }\n\n      if (templateOptions.getKeyPair() != null) {\n         SshKeyPair keyPair = null;\n         if (templateOptions.getLoginPrivateKey() != null) {\n            String pem = templateOptions.getLoginPrivateKey();\n            keyPair = SshKeyPair.builder().name(templateOptions.getKeyPair())\n               .fingerprint(fingerprintPrivateKey(pem)).privateKey(pem).build();\n            keyPairCache.asMap().put(keyPair.getName(), keyPair);\n            options.keyPair(keyPair.getName());\n         } else if (client.getSSHKeyPairApi().getSSHKeyPair(templateOptions.getKeyPair()) != null) {\n            keyPair = client.getSSHKeyPairApi().getSSHKeyPair(templateOptions.getKeyPair());\n         }\n         if (keyPair != null) {\n            keyPairCache.asMap().put(keyPair.getName(), keyPair);\n            options.keyPair(keyPair.getName());\n         }\n      } else if (templateOptions.shouldGenerateKeyPair()) {\n         SshKeyPair keyPair = keyPairCache.getUnchecked(namingConvention.create().sharedNameForGroup(group));\n         keyPairCache.asMap().put(keyPair.getName(), keyPair);\n         templateOptions.keyPair(keyPair.getName());\n         options.keyPair(keyPair.getName());\n      }\n\n      if (templateOptions.getDiskOfferingId() != null) {\n         options.diskOfferingId(templateOptions.getDiskOfferingId());\n         if (templateOptions.getDataDiskSize() > 0) {\n            options.dataDiskSize(templateOptions.getDataDiskSize());\n         }\n      }\n\n      if (supportsSecurityGroups().apply(zone)) {\n         List<Integer> inboundPorts = Ints.asList(templateOptions.getInboundPorts());\n\n         if (templateOptions.getSecurityGroupIds().isEmpty()\n             && !inboundPorts.isEmpty()\n             && templateOptions.shouldGenerateSecurityGroup()) {\n            String securityGroupName = namingConvention.create().sharedNameForGroup(group);\n            SecurityGroup sg = securityGroupCache.getUnchecked(ZoneSecurityGroupNamePortsCidrs.builder()\n                                                               .zone(zone.getId())\n                                                               .name(securityGroupName)\n                                                               .ports(ImmutableSet.copyOf(inboundPorts))\n                                                               .cidrs(ImmutableSet.<String> of()).build());\n            options.securityGroupId(sg.getId());\n         }\n      }\n\n      String templateId = template.getImage().getId();\n      String serviceOfferingId = template.getHardware().getId();\n\n      logger.debug(\"serviceOfferingId %s, templateId %s, zoneId %s, options %s%n\", serviceOfferingId, templateId,\n         zoneId, options);\n      AsyncCreateResponse job = client.getVirtualMachineApi().deployVirtualMachineInZone(zoneId, serviceOfferingId,\n         templateId, options);\n      VirtualMachine vm = blockUntilJobCompletesAndReturnResult.<VirtualMachine>apply(job);\n      logger.debug(\"--- virtualmachine: %s\", vm);\n      LoginCredentials credentials = credentialsProvider.get();\n      if (credentials == null || credentials.getUser() == null) {\n         LoginCredentials.Builder credentialsBuilder = LoginCredentials.builder();\n         if (templateOptions.getKeyPair() != null) {\n            SshKeyPair keyPair = keyPairCache.getUnchecked(templateOptions.getKeyPair());\n            credentialsBuilder.privateKey(keyPair.getPrivateKey());\n         } else if (vm.isPasswordEnabled()) {\n            assert vm.getPassword() != null : vm;\n            credentialsBuilder.password(vm.getPassword());\n         }\n         credentials = credentialsBuilder.build();\n      }\n\n      try {\n         ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();\n         builder.putAll(template.getOptions().getUserMetadata());\n         for (String tag : template.getOptions().getTags())\n            builder.put(tag, \"jclouds-empty-tag-placeholder\");\n         Map<String, String> common = builder.build();\n\n         if (!common.isEmpty()) {\n            logger.debug(\">> adding tags %s to virtualmachine(%s)\", common, vm.getId());\n            CreateTagsOptions tagOptions = CreateTagsOptions.Builder.resourceIds(vm.getId())\n                  .resourceType(Tag.ResourceType.USER_VM)\n                  .tags(common);\n            AsyncCreateResponse tagJob = client.getTagApi().createTags(tagOptions);\n            awaitCompletion(tagJob.getJobId());\n            logger.debug(\"<< tags added\");\n            vm = client.getVirtualMachineApi().getVirtualMachine(vm.getId());\n         }\n         if (templateOptions.shouldSetupStaticNat()) {\n            Capabilities capabilities = client.getConfigurationApi().listCapabilities();\n\n            NIC nic = Iterables.find(vm.getNICs(), new Predicate<NIC>() {\n               @Override\n               public boolean apply(NIC input) {\n                  return (input == null) ? false : input.isDefault();\n               }\n            });\n            String networkId = nic.getNetworkId();\n\n            logger.debug(\">> creating static NAT for virtualMachine(%s) in network(%s)\", vm.getId(), networkId);\n            PublicIPAddress ip = staticNATVMInNetwork.create(networks.get(networkId)).apply(vm);\n            logger.trace(\"<< static NATed IPAddress(%s) to virtualMachine(%s)\", ip.getId(), vm.getId());\n            vm = client.getVirtualMachineApi().getVirtualMachine(vm.getId());\n            List<Integer> ports = Ints.asList(templateOptions.getInboundPorts());\n            if (capabilities.getCloudStackVersion().startsWith(\"2\")) {\n               logger.debug(\">> setting up IP forwarding for IPAddress(%s) rules(%s)\", ip.getId(), ports);\n               Set<IPForwardingRule> rules = setupPortForwardingRulesForIP.apply(ip, ports);\n               logger.trace(\"<< setup %d IP forwarding rules on IPAddress(%s)\", rules.size(), ip.getId());\n            } else {\n               logger.debug(\">> setting up firewall rules for IPAddress(%s) rules(%s)\", ip.getId(), ports);\n               Set<FirewallRule> rules = setupFirewallRulesForIP.apply(ip, ports);\n               logger.trace(\"<< setup %d firewall rules on IPAddress(%s)\", rules.size(), ip.getId());\n            }\n          }\n      } catch (RuntimeException re) {\n          logger.error(\"-- exception after node has been created, trying to destroy the created virtualMachine(%s)\", vm.getId());\n          try {\n              destroyNode(vm.getId());\n          } catch (RuntimeException re2) {\n              logger.debug(\"-- exception in exceptionHandler while executing destroyNode for virtualMachine(%s), ignoring and rethrowing original exception\", vm.getId());\n          }\n          throw re;\n      }\n      return new NodeAndInitialCredentials<VirtualMachine>(vm, vm.getId() + \"\", credentials);\n   }\n\n   @Override\n   public Iterable<ServiceOffering> listHardwareProfiles() {\n      // TODO: we may need to filter these\n      return client.getOfferingApi().listServiceOfferings();\n   }\n\n   @Override\n   public Iterable<Template> listImages() {\n      TemplateApi templateApi = client.getTemplateApi();\n      ImmutableSet.Builder<Template> templates = ImmutableSet.builder();\n      templates.addAll(templateApi.listTemplates());\n      for (String project : projectSupplier.get().keySet()) {\n         templates.addAll(templateApi.listTemplates(ListTemplatesOptions.Builder.projectId(project)));\n      }\n\n      return filter(templates.build(), isReady());\n   }\n\n   @Override\n   public Template getImage(String id) {\n      return get(client.getTemplateApi().listTemplates(id(id)), 0, null);\n   }\n\n   @Override\n   public Iterable<VirtualMachine> listNodes() {\n      return client.getVirtualMachineApi().listVirtualMachines();\n   }\n\n   @Override\n   public Iterable<VirtualMachine> listNodesByIds(final Iterable<String> ids) {\n      return filter(listNodes(), new Predicate<VirtualMachine>() {\n\n            @Override\n            public boolean apply(VirtualMachine vm) {\n               return contains(ids, vm.getId());\n            }\n         });\n   }\n\n   @Override\n   public Iterable<Zone> listLocations() {\n      // TODO: we may need to filter these\n      return client.getZoneApi().listZones();\n   }\n\n   @Override\n   public VirtualMachine getNode(String id) {\n      String virtualMachineId = id;\n      return client.getVirtualMachineApi().getVirtualMachine(virtualMachineId);\n   }\n\n   @Override\n   public void destroyNode(String id) {\n      String virtualMachineId = id;\n      // There was a bug in 2.2.12 release happening when static nat IP address\n      // was being released, and corresponding firewall rules were left behind.\n      // So next time the same IP is allocated, it might be not be static nat\n      // enabled, but there are still rules associated with it. And when you try\n      // to release this IP, the release will fail.\n      //\n      // The bug was fixed in 2.2.13 release only, and the current system wasn't\n      // updated yet.\n      //\n      // To avoid the issue, every time you release a static nat ip address, do\n      // the following:\n\n      // 1) Delete IP forwarding rules associated with IP.\n      Set<String> ipAddresses = deleteIPForwardingRulesForVMAndReturnDistinctIPs(virtualMachineId);\n\n      // 2) Delete firewall rules associated with IP.\n      ipAddresses.addAll(deleteFirewallRulesForVMAndReturnDistinctIPs(virtualMachineId));\n\n      // 3) Disable static nat rule for the IP.\n      disableStaticNATOnIPAddresses(ipAddresses);\n\n      // 4) Only after 1 and 2 release the IP address.\n      disassociateIPAddresses(ipAddresses);\n\n      destroyVirtualMachine(virtualMachineId);\n\n      vmToRules.invalidate(virtualMachineId);\n   }\n\n   public void disassociateIPAddresses(Set<String> ipAddresses) {\n      for (String ipAddress : ipAddresses) {\n         logger.debug(\">> disassociating IPAddress(%s)\", ipAddress);\n         client.getAddressApi().disassociateIPAddress(ipAddress);\n      }\n   }\n\n   public void destroyVirtualMachine(String virtualMachineId) {\n\n      String destroyVirtualMachine = client.getVirtualMachineApi().destroyVirtualMachine(virtualMachineId);\n      if (destroyVirtualMachine != null) {\n         logger.debug(\">> destroying virtualMachine(%s) job(%s)\", virtualMachineId, destroyVirtualMachine);\n         awaitCompletion(destroyVirtualMachine);\n      } else {\n         logger.trace(\"<< virtualMachine(%s) not found\", virtualMachineId);\n      }\n\n   }\n\n   public void disableStaticNATOnIPAddresses(Set<String> ipAddresses) {\n      Builder<String> jobsToTrack = ImmutableSet.builder();\n      for (String ipAddress : ipAddresses) {\n         String disableStaticNAT = client.getNATApi().disableStaticNATOnPublicIP(ipAddress);\n         if (disableStaticNAT != null) {\n            logger.debug(\">> disabling static NAT IPAddress(%s) job(%s)\", ipAddress, disableStaticNAT);\n            jobsToTrack.add(disableStaticNAT);\n         }\n      }\n      awaitCompletion(jobsToTrack.build());\n   }\n\n   public Set<String> deleteIPForwardingRulesForVMAndReturnDistinctIPs(String virtualMachineId) {\n      Builder<String> jobsToTrack = ImmutableSet.builder();\n\n      // immutable doesn't permit duplicates\n      Set<String> ipAddresses = Sets.newLinkedHashSet();\n\n      Set<IPForwardingRule> forwardingRules = client.getNATApi().getIPForwardingRulesForVirtualMachine(\n         virtualMachineId);\n      for (IPForwardingRule rule : forwardingRules) {\n         if (!\"Deleting\".equals(rule.getState())) {\n            ipAddresses.add(rule.getIPAddressId());\n            String deleteForwardingRule = client.getNATApi().deleteIPForwardingRule(rule.getId());\n            if (deleteForwardingRule != null) {\n               logger.debug(\">> deleting IPForwardingRule(%s) job(%s)\", rule.getId(), deleteForwardingRule);\n               jobsToTrack.add(deleteForwardingRule);\n            }\n         }\n      }\n      awaitCompletion(jobsToTrack.build());\n      return ipAddresses;\n   }\n\n   public Set<String> deleteFirewallRulesForVMAndReturnDistinctIPs(String virtualMachineId) {\n      // immutable doesn't permit duplicates\n      Set<String> ipAddresses = Sets.newLinkedHashSet();\n\n      String publicIpId = client.getVirtualMachineApi().getVirtualMachine(virtualMachineId).getPublicIPId();\n      if (publicIpId != null) {\n         Set<FirewallRule> firewallRules = client.getFirewallApi()\n            .listFirewallRules(ListFirewallRulesOptions.Builder.ipAddressId(client.getVirtualMachineApi().getVirtualMachine(virtualMachineId).getPublicIPId()));\n\n         for (FirewallRule rule : firewallRules) {\n            if (rule.getState() != FirewallRule.State.DELETING) {\n               ipAddresses.add(rule.getIpAddressId());\n               client.getFirewallApi().deleteFirewallRule(rule.getId());\n               logger.debug(\">> deleting FirewallRule(%s)\", rule.getId());\n            }\n         }\n      }\n      return ipAddresses;\n   }\n\n   public void awaitCompletion(Iterable<String> jobs) {\n      logger.debug(\">> awaiting completion of jobs(%s)\", jobs);\n      for (String job : jobs)\n         awaitCompletion(job);\n      logger.trace(\"<< completed jobs(%s)\", jobs);\n   }\n\n   public void awaitCompletion(String job) {\n      boolean completed = jobComplete.apply(job);\n      logger.trace(\"<< job(%s) complete(%s)\", job, completed);\n   }\n\n   @Override\n   public void rebootNode(String id) {\n      String virtualMachineId = id;\n      String job = client.getVirtualMachineApi().rebootVirtualMachine(virtualMachineId);\n      if (job != null) {\n         logger.debug(\">> rebooting virtualMachine(%s) job(%s)\", virtualMachineId, job);\n         awaitCompletion(job);\n      }\n   }\n\n   @Override\n   public void resumeNode(String id) {\n      String virtualMachineId = id;\n      String job = client.getVirtualMachineApi().startVirtualMachine(id);\n      if (job != null) {\n         logger.debug(\">> starting virtualMachine(%s) job(%s)\", virtualMachineId, job);\n         awaitCompletion(job);\n      }\n   }\n\n   @Override\n   public void suspendNode(String id) {\n      String virtualMachineId = id;\n      String job = client.getVirtualMachineApi().stopVirtualMachine(id);\n      if (job != null) {\n         logger.debug(\">> stopping virtualMachine(%s) job(%s)\", virtualMachineId, job);\n         awaitCompletion(job);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/compute/strategy/OptionsConverter.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.compute.strategy;\n\nimport java.util.Map;\n\nimport org.jclouds.cloudstack.compute.options.CloudStackTemplateOptions;\nimport org.jclouds.cloudstack.domain.Network;\nimport org.jclouds.cloudstack.options.DeployVirtualMachineOptions;\n\n/**\n * Convert template options into DeployVirtualMachineOptions. Expressed as an interface, because in\n * CloudStack different zone network types have different requirements when it comes to networks and\n * security groups.\n */\npublic interface OptionsConverter {\n\n   /**\n    * Convert a CloudStackTemplateOptions and apply to a DeployVirtualMachineOptions instance.\n    *\n    * @param templateOptions the input set of options\n    * @param networks the networks available\n    * @param zoneId the zone of the new virtual machine\n    * @param options where the resulting set of options will be applied\n    * @return same as \"options\" parameter\n    */\n   DeployVirtualMachineOptions apply(CloudStackTemplateOptions templateOptions, Map<String, Network> networks, String zoneId, DeployVirtualMachineOptions options);\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/config/CloudStackHttpApiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.config;\n\nimport static org.jclouds.rest.config.BinderUtils.bindHttpApi;\n\nimport java.util.concurrent.TimeUnit;\n\nimport org.jclouds.Constants;\nimport org.jclouds.cloudstack.CloudStackApi;\nimport org.jclouds.cloudstack.CloudStackDomainApi;\nimport org.jclouds.cloudstack.CloudStackGlobalApi;\nimport org.jclouds.cloudstack.domain.LoginResponse;\nimport org.jclouds.cloudstack.features.SessionApi;\nimport org.jclouds.cloudstack.filters.AddSessionKeyAndJSessionIdToRequest;\nimport org.jclouds.cloudstack.filters.AuthenticationFilter;\nimport org.jclouds.cloudstack.filters.QuerySigner;\nimport org.jclouds.cloudstack.handlers.CloudStackErrorHandler;\nimport org.jclouds.cloudstack.handlers.InvalidateSessionAndRetryOn401AndLogoutOnClose;\nimport org.jclouds.cloudstack.loaders.LoginWithPasswordCredentials;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpRetryHandler;\nimport org.jclouds.http.annotation.ClientError;\nimport org.jclouds.http.annotation.Redirection;\nimport org.jclouds.http.annotation.ServerError;\nimport org.jclouds.location.Provider;\nimport org.jclouds.location.suppliers.ImplicitLocationSupplier;\nimport org.jclouds.location.suppliers.implicit.OnlyLocationOrFirstZone;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.ApiContext;\nimport org.jclouds.rest.config.HttpApiModule;\nimport org.jclouds.rest.internal.ApiContextImpl;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.LoadingCache;\nimport com.google.inject.Inject;\nimport com.google.inject.Provides;\nimport com.google.inject.Scopes;\nimport com.google.inject.Singleton;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.name.Named;\n\n/**\n * Configures the cloudstack connection.\n */\n@ConfiguresHttpApi\npublic class CloudStackHttpApiModule extends HttpApiModule<CloudStackApi> {\n\n   @Override\n   protected void configure() {\n      bind(new TypeLiteral<ApiContext<CloudStackDomainApi>>() {\n      }).to(new TypeLiteral<ApiContextImpl<CloudStackDomainApi>>() {\n      });\n      bind(new TypeLiteral<ApiContext<CloudStackGlobalApi>>() {\n      }).to(new TypeLiteral<ApiContextImpl<CloudStackGlobalApi>>() {\n      });\n      bind(CredentialType.class).toProvider(CredentialTypeFromPropertyOrDefault.class);\n      // session client is used directly for filters and retry handlers, so let's bind it explicitly\n      bindHttpApi(binder(), SessionApi.class);\n      bindHttpApi(binder(), CloudStackDomainApi.class);\n      bindHttpApi(binder(), CloudStackGlobalApi.class);\n      bind(HttpRetryHandler.class).annotatedWith(ClientError.class).to(InvalidateSessionAndRetryOn401AndLogoutOnClose.class);\n      \n      super.configure();\n   }\n\n   @Override\n   protected void installLocations() {\n      super.installLocations();\n      bind(ImplicitLocationSupplier.class).to(OnlyLocationOrFirstZone.class).in(Scopes.SINGLETON);\n   }\n\n   @Override\n   protected void bindErrorHandlers() {\n      bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(CloudStackErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(CloudStackErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(CloudStackErrorHandler.class);\n   }\n\n   @Singleton\n   static class CredentialTypeFromPropertyOrDefault implements jakarta.inject.Provider<CredentialType> {\n      /**\n       * use optional injection to supply a default value for credential type. so that we don't have\n       * to set a default property.\n       */\n      @Inject(optional = true)\n      @Named(CloudStackProperties.CREDENTIAL_TYPE)\n      String credentialType = CredentialType.API_ACCESS_KEY_CREDENTIALS.toString();\n\n      @Override\n      public CredentialType get() {\n         return CredentialType.fromValue(credentialType);\n      }\n   }\n\n   /**\n    * we use the type of credentials specified at login to determine which way we want to filter the\n    * request. <br/>\n    * for ex, if we are getting passwords, we know we will need to login/logout. Otherwise we are\n    * signing requests.\n    */\n   @Provides\n   @Singleton\n   protected final AuthenticationFilter authenticationFilterForCredentialType(CredentialType credentialType,\n            AddSessionKeyAndJSessionIdToRequest addSessionKeyAndJSessionIdToRequest, QuerySigner querySigner) {\n      switch (credentialType) {\n         case PASSWORD_CREDENTIALS:\n            return addSessionKeyAndJSessionIdToRequest;\n         case API_ACCESS_KEY_CREDENTIALS:\n            return querySigner;\n         default:\n            throw new IllegalArgumentException(\"credential type not supported: \" + credentialType);\n      }\n   }\n\n   // PROPERTY_SESSION_INTERVAL is default to 60 seconds\n   @Provides\n   @Singleton\n   protected final LoadingCache<Credentials, LoginResponse> provideLoginResponseCache(\n            LoginWithPasswordCredentials getLoginResponse,\n            @Named(Constants.PROPERTY_SESSION_INTERVAL) int seconds) {\n      return CacheBuilder.newBuilder().expireAfterWrite(seconds, TimeUnit.SECONDS).build(getLoginResponse);\n   }\n\n   // Temporary conversion of a cache to a supplier until there is a single-element cache\n   // http://code.google.com/p/guava-libraries/issues/detail?id=872\n   @Provides\n   @Singleton\n   protected final Supplier<LoginResponse> provideLoginResponseSupplier(final LoadingCache<Credentials, LoginResponse> cache,\n         @Provider final Supplier<Credentials> creds) {\n      return new Supplier<LoginResponse>() {\n         @Override\n         public LoginResponse get() {\n            return cache.getUnchecked(creds.get());\n         }\n      };\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/config/CloudStackParserModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.config;\n\nimport java.io.IOException;\nimport java.util.Date;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.json.config.GsonModule.DateAdapter;\nimport org.jclouds.json.config.GsonModule.Iso8601DateAdapter;\nimport org.jclouds.json.internal.NullFilteringTypeAdapterFactories.IterableTypeAdapter;\nimport org.jclouds.json.internal.NullFilteringTypeAdapterFactories.IterableTypeAdapterFactory;\n\nimport com.google.common.base.Splitter;\nimport com.google.common.base.Strings;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.gson.TypeAdapter;\nimport com.google.gson.stream.JsonReader;\nimport com.google.gson.stream.JsonToken;\nimport com.google.gson.stream.JsonWriter;\nimport com.google.inject.AbstractModule;\n\npublic class CloudStackParserModule extends AbstractModule {\n\n   @Override\n   protected void configure() {\n      bind(DateAdapter.class).to(CloudStackDateAdapter.class);\n      bind(IterableTypeAdapterFactory.class).to(CommaDelimitedOKIterableTypeAdapterFactory.class);\n   }\n\n   /**\n    * Data adapter for the date formats used by CloudStack.\n    * \n    * Essentially this is a workaround for the CloudStack getUsage() API call returning a corrupted form of ISO-8601\n    * dates, which have an unexpected pair of apostrophes, like 2011-12-12'T'00:00:00+00:00\n    * \n    */\n   public static class CloudStackDateAdapter extends Iso8601DateAdapter {\n\n      @Inject\n      private CloudStackDateAdapter(DateService dateService) {\n         super(dateService);\n      }\n\n      public Date read(JsonReader reader) throws IOException {\n         return parseDate(reader.nextString().replaceAll(\"'T'\", \"T\"));\n      }\n\n   }\n\n   /**\n    * Handles types that were previously strings and now arrays (ex. tags)\n    * \n    */\n   public static class CommaDelimitedOKIterableTypeAdapterFactory extends IterableTypeAdapterFactory {\n\n      @Override\n      @SuppressWarnings(\"unchecked\")\n      protected <E, I> TypeAdapter<I> newAdapter(TypeAdapter<E> elementAdapter) {\n         return (TypeAdapter<I>) new Adapter<E>(elementAdapter);\n      }\n\n      public static final class Adapter<E> extends TypeAdapter<Iterable<E>> {\n\n         private final IterableTypeAdapter<E> delegate;\n\n         public Adapter(TypeAdapter<E> elementAdapter) {\n            this.delegate = new IterableTypeAdapter<E>(elementAdapter);\n            nullSafe();\n         }\n\n         public void write(JsonWriter out, Iterable<E> value) throws IOException {\n            this.delegate.write(out, value);\n         }\n\n         @SuppressWarnings(\"unchecked\")\n         @Override\n         public Iterable<E> read(JsonReader in) throws IOException {\n            // HACK as cloudstack changed a field from String to Set!\n            if (in.peek() == JsonToken.STRING) {\n               String val = Strings.emptyToNull(in.nextString());\n               return (Iterable<E>) (val != null ? Splitter.on(',').split(val) : ImmutableSet.of());\n            } else {\n               return delegate.read(in);\n            }\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/config/CloudStackProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.config;\n\n\n/**\n * Configuration properties and constants used in CloudStack connections.\n */\npublic final class CloudStackProperties {\n\n   /**\n    * Type of credentials specified during {@link ComputeServiceContextBuilder#overrides}. If\n    * {@link CredentialType#API_ACCESS_KEY_CREDENTIALS}, the request signing is used. If\n    * {@link CredentialType#PASSWORD_CREDENTIALS}, login will happen and a session will be\n    * persisted.\n    * \n    * <h3>valid values</h3>\n    * <ul>\n    * <li>apiAccessKeyCredentials</li>\n    * <li>passwordCredentials</li>\n    * </ul>\n    * \n    * @see CredentialType\n    * @see <a href=\"http://docs.cloud.com/CloudStack_Documentation/Customizing_the_CloudStack_UI#Cross_Site_Request_Forgery_%28CSRF%29\"\n    *      />\n    */\n   public static final String CREDENTIAL_TYPE = \"jclouds.cloudstack.credential-type\";\n\n   /**\n    * Whenever a node is created, automatically generate keypairs for groups, as needed, also\n    * delete the keypair(s) when the last node in the group is destroyed.\n    */\n   public static final String AUTO_GENERATE_KEYPAIRS = \"jclouds.cloudstack.auto-generate-keypairs\";\n\n   private CloudStackProperties() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/config/CredentialType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.config;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.CaseFormat;\n\n/**\n * Decides what type of credentials createContext is supplied with.\n */\npublic enum CredentialType {\n\n   API_ACCESS_KEY_CREDENTIALS,\n\n   PASSWORD_CREDENTIALS;\n\n   @Override\n   public String toString() {\n      return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, name());\n   }\n\n   public static CredentialType fromValue(String credentialType) {\n      return valueOf(CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, checkNotNull(credentialType,\n               \"credentialType\")));\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/Account.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.CaseFormat;\nimport com.google.common.base.Function;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ForwardingSet;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Maps;\n\n/**\n * Class Account\n */\npublic class Account extends ForwardingSet<User> {\n\n   /**\n    */\n   public static enum State {\n      ENABLED, DISABLED, LOCKED, UNRECOGNIZED;\n\n      @Override\n      public String toString() {\n         return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_HYPHEN, name());\n      }\n\n      public static State fromValue(String state) {\n         try {\n            return valueOf(CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_UNDERSCORE, checkNotNull(state, \"state\")));\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n\n   }\n\n   /**\n    */\n   public static enum Type {\n      /**\n       * API access for all the resources associated with their account. There\n       * may be many users in a domain, many domains in a deployment, and many\n       * users in a deployment. This is typically the end user\n       */\n      USER(0),\n      /**\n       * full API access. This is typically a service administrator or code that\n       * executes with complete trust in the service operator's environment.\n       */\n      ADMIN(1),\n      /**\n       * full API access within a domain. This is the most privileged user that\n       * a given customer has. This may be a reseller for the service provider.\n       */\n      DOMAIN_ADMIN(2), UNRECOGNIZED(Integer.MAX_VALUE);\n\n      private int code;\n\n      private static final Map<Integer, Type> INDEX = Maps.uniqueIndex(ImmutableSet.copyOf(Type.values()),\n            new Function<Type, Integer>() {\n\n               @Override\n               public Integer apply(Type input) {\n                  return input.code;\n               }\n\n            });\n\n      Type(int code) {\n         this.code = code;\n      }\n\n      @Override\n      public String toString() {\n         return \"\" + code;\n      }\n\n      public static Type fromValue(String type) {\n         Integer code = Integer.valueOf(checkNotNull(type, \"type\"));\n         return INDEX.containsKey(code) ? INDEX.get(code) : UNRECOGNIZED;\n      }\n\n   }\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromAccount(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String id;\n      protected Account.Type type;\n      protected String networkDomain;\n      protected String domain;\n      protected String domainId;\n      protected Long IPsAvailable;\n      protected Long IPLimit;\n      protected long IPs;\n      protected boolean cleanupRequired;\n      protected String name;\n      protected long receivedBytes;\n      protected long sentBytes;\n      protected Long snapshotsAvailable;\n      protected Long snapshotLimit;\n      protected long snapshots;\n      protected Account.State state;\n      protected Long templatesAvailable;\n      protected Long templateLimit;\n      protected long templates;\n      protected Long VMsAvailable;\n      protected Long VMLimit;\n      protected long VMsRunning;\n      protected long VMsStopped;\n      protected long VMs;\n      protected Long volumesAvailable;\n      protected Long volumeLimit;\n      protected long volumes;\n      protected Set<User> users = ImmutableSet.of();\n\n      /**\n       * @see Account#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see Account#getType()\n       */\n      public T type(Account.Type type) {\n         this.type = type;\n         return self();\n      }\n\n      /**\n       * @see Account#getNetworkDomain()\n       */\n      public T networkDomain(String networkDomain) {\n         this.networkDomain = networkDomain;\n         return self();\n      }\n\n      /**\n       * @see Account#getDomain()\n       */\n      public T domain(String domain) {\n         this.domain = domain;\n         return self();\n      }\n\n      /**\n       * @see Account#getDomainId()\n       */\n      public T domainId(String domainId) {\n         this.domainId = domainId;\n         return self();\n      }\n\n      /**\n       * @see Account#getIPsAvailable()\n       */\n      public T IPsAvailable(Long IPsAvailable) {\n         this.IPsAvailable = IPsAvailable;\n         return self();\n      }\n\n      /**\n       * @see Account#getIPLimit()\n       */\n      public T IPLimit(Long IPLimit) {\n         this.IPLimit = IPLimit;\n         return self();\n      }\n\n      /**\n       * @see Account#getIPs()\n       */\n      public T IPs(long IPs) {\n         this.IPs = IPs;\n         return self();\n      }\n\n      /**\n       * @see Account#isCleanupRequired()\n       */\n      public T cleanupRequired(boolean cleanupRequired) {\n         this.cleanupRequired = cleanupRequired;\n         return self();\n      }\n\n      /**\n       * @see Account#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /**\n       * @see Account#getReceivedBytes()\n       */\n      public T receivedBytes(long receivedBytes) {\n         this.receivedBytes = receivedBytes;\n         return self();\n      }\n\n      /**\n       * @see Account#getSentBytes()\n       */\n      public T sentBytes(long sentBytes) {\n         this.sentBytes = sentBytes;\n         return self();\n      }\n\n      /**\n       * @see Account#getSnapshotsAvailable()\n       */\n      public T snapshotsAvailable(Long snapshotsAvailable) {\n         this.snapshotsAvailable = snapshotsAvailable;\n         return self();\n      }\n\n      /**\n       * @see Account#getSnapshotLimit()\n       */\n      public T snapshotLimit(Long snapshotLimit) {\n         this.snapshotLimit = snapshotLimit;\n         return self();\n      }\n\n      /**\n       * @see Account#getSnapshots()\n       */\n      public T snapshots(long snapshots) {\n         this.snapshots = snapshots;\n         return self();\n      }\n\n      /**\n       * @see Account#getState()\n       */\n      public T state(Account.State state) {\n         this.state = state;\n         return self();\n      }\n\n      /**\n       * @see Account#getTemplatesAvailable()\n       */\n      public T templatesAvailable(Long templatesAvailable) {\n         this.templatesAvailable = templatesAvailable;\n         return self();\n      }\n\n      /**\n       * @see Account#getTemplateLimit()\n       */\n      public T templateLimit(Long templateLimit) {\n         this.templateLimit = templateLimit;\n         return self();\n      }\n\n      /**\n       * @see Account#getTemplates()\n       */\n      public T templates(long templates) {\n         this.templates = templates;\n         return self();\n      }\n\n      /**\n       * @see Account#getVMsAvailable()\n       */\n      public T VMsAvailable(Long VMsAvailable) {\n         this.VMsAvailable = VMsAvailable;\n         return self();\n      }\n\n      /**\n       * @see Account#getVMLimit()\n       */\n      public T VMLimit(Long VMLimit) {\n         this.VMLimit = VMLimit;\n         return self();\n      }\n\n      /**\n       * @see Account#getVMsRunning()\n       */\n      public T VMsRunning(long VMsRunning) {\n         this.VMsRunning = VMsRunning;\n         return self();\n      }\n\n      /**\n       * @see Account#getVMsStopped()\n       */\n      public T VMsStopped(long VMsStopped) {\n         this.VMsStopped = VMsStopped;\n         return self();\n      }\n\n      /**\n       * @see Account#getVMs()\n       */\n      public T VMs(long VMs) {\n         this.VMs = VMs;\n         return self();\n      }\n\n      /**\n       * @see Account#getVolumesAvailable()\n       */\n      public T volumesAvailable(Long volumesAvailable) {\n         this.volumesAvailable = volumesAvailable;\n         return self();\n      }\n\n      /**\n       * @see Account#getVolumeLimit()\n       */\n      public T volumeLimit(Long volumeLimit) {\n         this.volumeLimit = volumeLimit;\n         return self();\n      }\n\n      /**\n       * @see Account#getVolumes()\n       */\n      public T volumes(long volumes) {\n         this.volumes = volumes;\n         return self();\n      }\n\n      /**\n       * @see Account#getUsers()\n       */\n      public T users(Set<User> users) {\n         this.users = ImmutableSet.copyOf(checkNotNull(users, \"users\"));\n         return self();\n      }\n\n      public T users(User... in) {\n         return users(ImmutableSet.copyOf(in));\n      }\n\n      public Account build() {\n         return new Account(id, type, networkDomain, domain, domainId, IPsAvailable, IPLimit, IPs, cleanupRequired, name, receivedBytes, sentBytes, snapshotsAvailable, snapshotLimit, snapshots, state, templatesAvailable, templateLimit, templates, VMsAvailable, VMLimit, VMsRunning, VMsStopped, VMs, volumesAvailable, volumeLimit, volumes, users);\n      }\n\n      public T fromAccount(Account in) {\n         return this\n               .id(in.getId())\n               .type(in.getType())\n               .networkDomain(in.getNetworkDomain())\n               .domain(in.getDomain())\n               .domainId(in.getDomainId())\n               .IPsAvailable(in.getIPsAvailable())\n               .IPLimit(in.getIPLimit())\n               .IPs(in.getIPs())\n               .cleanupRequired(in.isCleanupRequired())\n               .name(in.getName())\n               .receivedBytes(in.getReceivedBytes())\n               .sentBytes(in.getSentBytes())\n               .snapshotsAvailable(in.getSnapshotsAvailable())\n               .snapshotLimit(in.getSnapshotLimit())\n               .snapshots(in.getSnapshots())\n               .state(in.getState())\n               .templatesAvailable(in.getTemplatesAvailable())\n               .templateLimit(in.getTemplateLimit())\n               .templates(in.getTemplates())\n               .VMsAvailable(in.getVMsAvailable())\n               .VMLimit(in.getVMLimit())\n               .VMsRunning(in.getVMsRunning())\n               .VMsStopped(in.getVMsStopped())\n               .VMs(in.getVMs())\n               .volumesAvailable(in.getVolumesAvailable())\n               .volumeLimit(in.getVolumeLimit())\n               .volumes(in.getVolumes())\n               .users(in.getUsers());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final Account.Type type;\n   private final String networkDomain;\n   private final String domain;\n   private final String domainId;\n   private final Long IPsAvailable;\n   private final Long IPLimit;\n   private final long IPs;\n   private final boolean cleanupRequired;\n   private final String name;\n   private final long receivedBytes;\n   private final long sentBytes;\n   private final Long snapshotsAvailable;\n   private final Long snapshotLimit;\n   private final long snapshots;\n   private final Account.State state;\n   private final Long templatesAvailable;\n   private final Long templateLimit;\n   private final long templates;\n   private final Long VMsAvailable;\n   private final Long VMLimit;\n   private final long VMsRunning;\n   private final long VMsStopped;\n   private final long VMs;\n   private final Long volumesAvailable;\n   private final Long volumeLimit;\n   private final long volumes;\n   private final Set<User> users;\n\n   @ConstructorProperties({\n         \"id\", \"accounttype\", \"networkdomain\", \"domain\", \"domainid\", \"ipavailable\", \"iplimit\", \"iptotal\", \"iscleanuprequired\",\n         \"name\", \"receivedbytes\", \"sentbytes\", \"snapshotavailable\", \"snapshotlimit\", \"snapshottotal\", \"state\", \"templateavailable\",\n         \"templatelimit\", \"templatetotal\", \"vmavailable\", \"vmlimit\", \"vmrunning\", \"vmstopped\", \"vmtotal\", \"volumeavailable\", \"volumelimit\",\n         \"volumetotal\", \"user\"\n   })\n   private Account(String id, @Nullable Type type, @Nullable String networkDomain, @Nullable String domain,\n                   @Nullable String domainId, @Nullable String IPsAvailable, @Nullable String IPLimit, long IPs,\n                   boolean cleanupRequired, @Nullable String name, long receivedBytes, long sentBytes,\n                   @Nullable String snapshotsAvailable, @Nullable String snapshotLimit, long snapshots,\n                   @Nullable State state, @Nullable String templatesAvailable, @Nullable String templateLimit,\n                   long templates, @Nullable String VMsAvailable, @Nullable String VMLimit, long VMsRunning,\n                   long VMsStopped, long VMs, @Nullable String volumesAvailable, @Nullable String volumeLimit,\n                   long volumes, @Nullable Set<User> users) {\n      this(id, type, networkDomain, domain, domainId, toLongNullIfUnlimited(IPsAvailable), toLongNullIfUnlimited(IPLimit), IPs,\n            cleanupRequired, name, receivedBytes, sentBytes, toLongNullIfUnlimited(snapshotsAvailable), toLongNullIfUnlimited(snapshotLimit),\n            snapshots, state, toLongNullIfUnlimited(templatesAvailable), toLongNullIfUnlimited(templateLimit), templates,\n            toLongNullIfUnlimited(VMsAvailable), toLongNullIfUnlimited(VMLimit), VMsRunning, VMsStopped, VMs,\n            toLongNullIfUnlimited(volumesAvailable), toLongNullIfUnlimited(volumeLimit), volumes, users);\n   }\n\n   private static Long toLongNullIfUnlimited(String in) {\n      return in == null || \"Unlimited\".equals(in) ? null : Long.valueOf(in);\n   }\n\n   protected Account(String id, @Nullable Account.Type type, @Nullable String networkDomain, @Nullable String domain,\n                     @Nullable String domainId, @Nullable Long IPsAvailable, @Nullable Long IPLimit, long IPs,\n                     boolean cleanupRequired, @Nullable String name, long receivedBytes, long sentBytes, @Nullable Long snapshotsAvailable,\n                     @Nullable Long snapshotLimit, long snapshots, @Nullable Account.State state, @Nullable Long templatesAvailable,\n                     @Nullable Long templateLimit, long templates, @Nullable Long VMsAvailable, @Nullable Long VMLimit, long VMsRunning,\n                     long VMsStopped, long VMs, @Nullable Long volumesAvailable, @Nullable Long volumeLimit, long volumes,\n                     @Nullable Set<User> users) {\n      this.id = checkNotNull(id, \"id\");\n      this.type = type;\n      this.networkDomain = networkDomain;\n      this.domain = domain;\n      this.domainId = domainId;\n      this.IPsAvailable = IPsAvailable;\n      this.IPLimit = IPLimit;\n      this.IPs = IPs;\n      this.cleanupRequired = cleanupRequired;\n      this.name = name;\n      this.receivedBytes = receivedBytes;\n      this.sentBytes = sentBytes;\n      this.snapshotsAvailable = snapshotsAvailable;\n      this.snapshotLimit = snapshotLimit;\n      this.snapshots = snapshots;\n      this.state = state;\n      this.templatesAvailable = templatesAvailable;\n      this.templateLimit = templateLimit;\n      this.templates = templates;\n      this.VMsAvailable = VMsAvailable;\n      this.VMLimit = VMLimit;\n      this.VMsRunning = VMsRunning;\n      this.VMsStopped = VMsStopped;\n      this.VMs = VMs;\n      this.volumesAvailable = volumesAvailable;\n      this.volumeLimit = volumeLimit;\n      this.volumes = volumes;\n      this.users = users == null ? ImmutableSet.<User>of() : ImmutableSet.copyOf(users);\n   }\n\n   /**\n    * @return the id of the account\n    */\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * @return account type (admin, domain-admin, user)\n    */\n   @Nullable\n   public Account.Type getType() {\n      return this.type;\n   }\n\n   /**\n    * @return the network domain\n    */\n   @Nullable\n   public String getNetworkDomain() {\n      return this.networkDomain;\n   }\n\n   /**\n    * @return name of the Domain the account belongs to\n    */\n   @Nullable\n   public String getDomain() {\n      return this.domain;\n   }\n\n   /**\n    * @return id of the Domain the account belongs to\n    */\n   @Nullable\n   public String getDomainId() {\n      return this.domainId;\n   }\n\n   /**\n    * @return the total number of public ip addresses available for this account\n    *         to acquire, or null if unlimited\n    */\n   @Nullable\n   public Long getIPsAvailable() {\n      return this.IPsAvailable;\n   }\n\n   /**\n    * @return the total number of public ip addresses this account can acquire,\n    *         or null if unlimited\n    */\n   @Nullable\n   public Long getIPLimit() {\n      return this.IPLimit;\n   }\n\n   /**\n    * @return the total number of public ip addresses allocated for this account\n    */\n   public long getIPs() {\n      return this.IPs;\n   }\n\n   /**\n    * @return true if the account requires cleanup\n    */\n   public boolean isCleanupRequired() {\n      return this.cleanupRequired;\n   }\n\n   /**\n    * @return the name of the account\n    */\n   @Nullable\n   public String getName() {\n      return this.name;\n   }\n\n   /**\n    * @return the total number of network traffic bytes received\n    */\n   public long getReceivedBytes() {\n      return this.receivedBytes;\n   }\n\n   /**\n    * @return the total number of network traffic bytes sent\n    */\n   public long getSentBytes() {\n      return this.sentBytes;\n   }\n\n   /**\n    * @return the total number of snapshots available for this account, or null\n    *         if unlimited\n    */\n   @Nullable\n   public Long getSnapshotsAvailable() {\n      return this.snapshotsAvailable;\n   }\n\n   /**\n    * @return the total number of snapshots which can be stored by this account,\n    *         or null if unlimited\n    */\n   @Nullable\n   public Long getSnapshotLimit() {\n      return this.snapshotLimit;\n   }\n\n   /**\n    * @return the total number of snapshots stored by this account\n    */\n   public long getSnapshots() {\n      return this.snapshots;\n   }\n\n   /**\n    * @return the state of the account\n    */\n   @Nullable\n   public State getState() {\n      return this.state;\n   }\n\n   /**\n    * @return the total number of templates available to be created by this\n    *         account, or null if unlimited\n    */\n   @Nullable\n   public Long getTemplatesAvailable() {\n      return this.templatesAvailable;\n   }\n\n   /**\n    * @return the total number of templates which can be created by this\n    *         account, or null if unlimited\n    */\n   @Nullable\n   public Long getTemplateLimit() {\n      return this.templateLimit;\n   }\n\n   /**\n    * @return the total number of templates which have been created by this\n    *         account\n    */\n   public long getTemplates() {\n      return this.templates;\n   }\n\n   /**\n    * @return the total number of virtual machines available for this account to\n    *         acquire, or null if unlimited\n    */\n   @Nullable\n   public Long getVMsAvailable() {\n      return this.VMsAvailable;\n   }\n\n   /**\n    * @return the total number of virtual machines that can be deployed by this\n    *         account, or null if unlimited\n    */\n   @Nullable\n   public Long getVMLimit() {\n      return this.VMLimit;\n   }\n\n   /**\n    * @return the total number of virtual machines running for this account\n    */\n   public long getVMsRunning() {\n      return this.VMsRunning;\n   }\n\n   /**\n    * @return the total number of virtual machines stopped for this account\n    */\n   public long getVMsStopped() {\n      return this.VMsStopped;\n   }\n\n   /**\n    * @return the total number of virtual machines deployed by this account\n    */\n   public long getVMs() {\n      return this.VMs;\n   }\n\n   /**\n    * @return the total volume available for this account, or null if unlimited\n    */\n   @Nullable\n   public Long getVolumesAvailable() {\n      return this.volumesAvailable;\n   }\n\n   /**\n    * @return the total volume which can be used by this account, or null if\n    *         unlimited\n    */\n   @Nullable\n   public Long getVolumeLimit() {\n      return this.volumeLimit;\n   }\n\n   /**\n    * @return the total volume being used by this account\n    */\n   public long getVolumes() {\n      return this.volumes;\n   }\n\n   /**\n    * @return the list of users associated with account\n    */\n   public Set<User> getUsers() {\n      return this.users;\n   }\n\n   @Override\n   protected Set<User> delegate() {\n      return this.users;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, type, networkDomain, domain, domainId, IPsAvailable, IPLimit, IPs, cleanupRequired, name, receivedBytes, sentBytes, snapshotsAvailable, snapshotLimit, snapshots, state, templatesAvailable, templateLimit, templates, VMsAvailable, VMLimit, VMsRunning, VMsStopped, VMs, volumesAvailable, volumeLimit, volumes, users);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Account that = Account.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n            && Objects.equal(this.type, that.type)\n            && Objects.equal(this.networkDomain, that.networkDomain)\n            && Objects.equal(this.domain, that.domain)\n            && Objects.equal(this.domainId, that.domainId)\n            && Objects.equal(this.IPsAvailable, that.IPsAvailable)\n            && Objects.equal(this.IPLimit, that.IPLimit)\n            && Objects.equal(this.IPs, that.IPs)\n            && Objects.equal(this.cleanupRequired, that.cleanupRequired)\n            && Objects.equal(this.name, that.name)\n            && Objects.equal(this.receivedBytes, that.receivedBytes)\n            && Objects.equal(this.sentBytes, that.sentBytes)\n            && Objects.equal(this.snapshotsAvailable, that.snapshotsAvailable)\n            && Objects.equal(this.snapshotLimit, that.snapshotLimit)\n            && Objects.equal(this.snapshots, that.snapshots)\n            && Objects.equal(this.state, that.state)\n            && Objects.equal(this.templatesAvailable, that.templatesAvailable)\n            && Objects.equal(this.templateLimit, that.templateLimit)\n            && Objects.equal(this.templates, that.templates)\n            && Objects.equal(this.VMsAvailable, that.VMsAvailable)\n            && Objects.equal(this.VMLimit, that.VMLimit)\n            && Objects.equal(this.VMsRunning, that.VMsRunning)\n            && Objects.equal(this.VMsStopped, that.VMsStopped)\n            && Objects.equal(this.VMs, that.VMs)\n            && Objects.equal(this.volumesAvailable, that.volumesAvailable)\n            && Objects.equal(this.volumeLimit, that.volumeLimit)\n            && Objects.equal(this.volumes, that.volumes)\n            && Objects.equal(this.users, that.users);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"type\", type).add(\"networkDomain\", networkDomain).add(\"domain\", domain).add(\"domainId\", domainId).add(\"IPsAvailable\", IPsAvailable).add(\"IPLimit\", IPLimit).add(\"IPs\", IPs).add(\"cleanupRequired\", cleanupRequired).add(\"name\", name).add(\"receivedBytes\", receivedBytes).add(\"sentBytes\", sentBytes).add(\"snapshotsAvailable\", snapshotsAvailable).add(\"snapshotLimit\", snapshotLimit).add(\"snapshots\", snapshots).add(\"state\", state).add(\"templatesAvailable\", templatesAvailable).add(\"templateLimit\", templateLimit).add(\"templates\", templates).add(\"VMsAvailable\", VMsAvailable).add(\"VMLimit\", VMLimit).add(\"VMsRunning\", VMsRunning).add(\"VMsStopped\", VMsStopped).add(\"VMs\", VMs).add(\"volumesAvailable\", volumesAvailable).add(\"volumeLimit\", volumeLimit).add(\"volumes\", volumes).add(\"users\", users);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/Alert.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Represents an alert issued by Cloudstack\n */\npublic class Alert {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromAlert(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String id;\n      protected String description;\n      protected Date sent;\n      protected String type;\n\n      /**\n       * @see Alert#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see Alert#getDescription()\n       */\n      public T description(String description) {\n         this.description = description;\n         return self();\n      }\n\n      /**\n       * @see Alert#getSent()\n       */\n      public T sent(Date sent) {\n         this.sent = sent;\n         return self();\n      }\n\n      /**\n       * @see Alert#getType()\n       */\n      public T type(String type) {\n         this.type = type;\n         return self();\n      }\n\n      public Alert build() {\n         return new Alert(id, description, sent, type);\n      }\n\n      public T fromAlert(Alert in) {\n         return this\n               .id(in.getId())\n               .description(in.getDescription())\n               .sent(in.getSent())\n               .type(in.getType());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final String description;\n   private final Date sent;\n   private final String type;\n\n   @ConstructorProperties({\n         \"id\", \"description\", \"sent\", \"type\"\n   })\n   protected Alert(String id, @Nullable String description, @Nullable Date sent, @Nullable String type) {\n      this.id = checkNotNull(id, \"id\");\n      this.description = description;\n      this.sent = sent;\n      this.type = type;\n   }\n\n   public String getId() {\n      return this.id;\n   }\n\n   @Nullable\n   public String getDescription() {\n      return this.description;\n   }\n\n   @Nullable\n   public Date getSent() {\n      return this.sent;\n   }\n\n   @Nullable\n   public String getType() {\n      return this.type;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, description, sent, type);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Alert that = Alert.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n            && Objects.equal(this.description, that.description)\n            && Objects.equal(this.sent, that.sent)\n            && Objects.equal(this.type, that.type);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"description\", description).add(\"sent\", sent).add(\"type\", type);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/AllocationState.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.CaseFormat.UPPER_CAMEL;\nimport static com.google.common.base.CaseFormat.UPPER_UNDERSCORE;\n\n/**\n * Represents the allocationstate field used in several CloudStack domain objects.\n */\npublic enum AllocationState {\n   DISABLED,\n   ENABLED,\n   UNKNOWN;\n\n   public static AllocationState fromValue(String value) {\n      try {\n         return valueOf(value.toUpperCase());\n      } catch (IllegalArgumentException e) {\n         return UNKNOWN;\n      }\n   }\n\n   @Override\n   public String toString() {\n      return UPPER_UNDERSCORE.to(UPPER_CAMEL, name());\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/ApiKeyPair.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Representation of the API keypair response\n */\npublic class ApiKeyPair {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromApiKeyPair(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String apiKey;\n      protected String secretKey;\n\n      /**\n       * @see ApiKeyPair#getApiKey()\n       */\n      public T apiKey(String apiKey) {\n         this.apiKey = apiKey;\n         return self();\n      }\n\n      /**\n       * @see ApiKeyPair#getSecretKey()\n       */\n      public T secretKey(String secretKey) {\n         this.secretKey = secretKey;\n         return self();\n      }\n\n      public ApiKeyPair build() {\n         return new ApiKeyPair(apiKey, secretKey);\n      }\n\n      public T fromApiKeyPair(ApiKeyPair in) {\n         return this\n               .apiKey(in.getApiKey())\n               .secretKey(in.getSecretKey());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String apiKey;\n   private final String secretKey;\n\n   @ConstructorProperties({\n         \"apikey\", \"secretkey\"\n   })\n   protected ApiKeyPair(@Nullable String apiKey, @Nullable String secretKey) {\n      this.apiKey = apiKey;\n      this.secretKey = secretKey;\n   }\n\n   @Nullable\n   public String getApiKey() {\n      return this.apiKey;\n   }\n\n   @Nullable\n   public String getSecretKey() {\n      return this.secretKey;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(apiKey, secretKey);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      ApiKeyPair that = ApiKeyPair.class.cast(obj);\n      return Objects.equal(this.apiKey, that.apiKey)\n            && Objects.equal(this.secretKey, that.secretKey);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"apiKey\", apiKey).add(\"secretKey\", secretKey);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/AsyncCreateResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Class AsyncCreateResponse\n */\npublic class AsyncCreateResponse {\n   public static final AsyncCreateResponse UNINITIALIZED = new AsyncCreateResponse(null, null);\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromAsyncCreateResponse(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String id;\n      protected String jobId;\n\n      /**\n       * @see AsyncCreateResponse#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see AsyncCreateResponse#getJobId()\n       */\n      public T jobId(String jobId) {\n         this.jobId = jobId;\n         return self();\n      }\n\n      public AsyncCreateResponse build() {\n         return new AsyncCreateResponse(id, jobId);\n      }\n\n      public T fromAsyncCreateResponse(AsyncCreateResponse in) {\n         return this\n               .id(in.getId())\n               .jobId(in.getJobId());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final String jobId;\n\n   @ConstructorProperties({\n         \"id\", \"jobid\"\n   })\n   protected AsyncCreateResponse(@Nullable String id, @Nullable String jobId) {\n      this.id = id;\n      this.jobId = jobId;\n   }\n\n   /**\n    * @return id of the resource being created\n    */\n   @Nullable\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * @return id of the job in progress\n    */\n   @Nullable\n   public String getJobId() {\n      return this.jobId;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, jobId);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      AsyncCreateResponse that = AsyncCreateResponse.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n            && Objects.equal(this.jobId, that.jobId);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"jobId\", jobId);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/AsyncJob.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Class AsyncJob\n */\npublic class AsyncJob<S> {\n\n   /**\n    * Valid job result codes\n    */\n   public static enum ResultCode {\n      SUCCESS(0),\n      FAIL(530),\n      UNKNOWN(-1);\n\n      private final int code;\n\n      private ResultCode(int code) {\n         this.code = code;\n      }\n\n      public int code() {\n         return this.code;\n      }\n\n      public static ResultCode fromValue(String value) {\n         try {\n            int resultCode = Integer.parseInt(value);\n            switch (resultCode) {\n               case 0:\n                  return SUCCESS;\n               case 530:\n                  return FAIL;\n               default:\n                  return UNKNOWN;\n            }\n         } catch (NumberFormatException e) {\n            return UNKNOWN;\n         }\n      }\n   }\n\n   /**\n    * Valid async job statuses\n    */\n   public static enum Status {\n      IN_PROGRESS(0),\n      SUCCEEDED(1),\n      FAILED(2),\n      UNKNOWN(-1);\n\n      private final int code;\n\n      private Status(int code) {\n         this.code = code;\n      }\n\n      public int code() {\n         return this.code;\n      }\n\n      public static Status fromValue(String value) {\n         try {\n            int statusCode = Integer.parseInt(value);\n            switch (statusCode) {\n               case 0:\n                  return IN_PROGRESS;\n               case 1:\n                  return SUCCEEDED;\n               case 2:\n                  return FAILED;\n               default:\n                  return UNKNOWN;\n            }\n         } catch (NumberFormatException e) {\n            return UNKNOWN;\n         }\n      }\n   }\n\n   public static <T> Builder<?, T> builder() {\n      return new ConcreteBuilder<T>();\n   }\n\n   public Builder toBuilder() {\n      return new ConcreteBuilder<S>().fromAsyncJob(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T, S>, S> {\n      protected abstract T self();\n\n      protected String accountId;\n      protected String cmd;\n      protected Date created;\n      protected String id;\n      protected String instanceId;\n      protected String instanceType;\n      protected int progress;\n      protected S result;\n      protected AsyncJob.ResultCode resultCode;\n      protected String resultType;\n      protected AsyncJob.Status status;\n      protected String userId;\n      protected AsyncJobError error;\n\n      /**\n       * @see AsyncJob#getAccountId()\n       */\n      public T accountId(String accountId) {\n         this.accountId = accountId;\n         return self();\n      }\n\n      /**\n       * @see AsyncJob#getCmd()\n       */\n      public T cmd(String cmd) {\n         this.cmd = cmd;\n         return self();\n      }\n\n      /**\n       * @see AsyncJob#getCreated()\n       */\n      public T created(Date created) {\n         this.created = created;\n         return self();\n      }\n\n      /**\n       * @see AsyncJob#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see AsyncJob#getInstanceId()\n       */\n      public T instanceId(String instanceId) {\n         this.instanceId = instanceId;\n         return self();\n      }\n\n      /**\n       * @see AsyncJob#getInstanceType()\n       */\n      public T instanceType(String instanceType) {\n         this.instanceType = instanceType;\n         return self();\n      }\n\n      /**\n       * @see AsyncJob#getProgress()\n       */\n      public T progress(int progress) {\n         this.progress = progress;\n         return self();\n      }\n\n      /**\n       * @see AsyncJob#getResult()\n       */\n      public T result(S result) {\n         this.result = result;\n         return self();\n      }\n\n      /**\n       * @see AsyncJob#getResultCode()\n       */\n      public T resultCode(AsyncJob.ResultCode resultCode) {\n         this.resultCode = resultCode;\n         return self();\n      }\n\n      /**\n       * @see AsyncJob#getResultType()\n       */\n      public T resultType(String resultType) {\n         this.resultType = resultType;\n         return self();\n      }\n\n      /**\n       * @see AsyncJob#getStatus()\n       */\n      public T status(AsyncJob.Status status) {\n         this.status = status;\n         return self();\n      }\n\n      /**\n       * @see AsyncJob#getUserId()\n       */\n      public T userId(String userId) {\n         this.userId = userId;\n         return self();\n      }\n\n      /**\n       * @see AsyncJob#getError()\n       */\n      public T error(AsyncJobError error) {\n         this.error = error;\n         return self();\n      }\n\n      public AsyncJob build() {\n         return new AsyncJob<S>(accountId, cmd, created, id, instanceId, instanceType, progress, result, resultCode,\n               resultType, status, userId, error);\n      }\n\n      public T fromAsyncJob(AsyncJob<S> in) {\n         return this\n               .accountId(in.getAccountId())\n               .cmd(in.getCmd())\n               .created(in.getCreated())\n               .id(in.getId())\n               .instanceId(in.getInstanceId())\n               .instanceType(in.getInstanceType())\n               .progress(in.getProgress())\n               .result(in.getResult())\n               .resultCode(in.getResultCode())\n               .resultType(in.getResultType())\n               .status(in.getStatus())\n               .userId(in.getUserId())\n               .error(in.getError());\n      }\n\n      public static Builder<?, Object> fromAsyncJobUntyped(AsyncJob<?> in) {\n         return new ConcreteBuilder().fromAsyncJob(in);\n      }\n   }\n\n   private static class ConcreteBuilder<T> extends Builder<ConcreteBuilder<T>, T> {\n      @Override\n      protected ConcreteBuilder<T> self() {\n         return this;\n      }\n   }\n\n   private final String accountId;\n   private final String cmd;\n   private final Date created;\n   private final String id;\n   private final String instanceId;\n   private final String instanceType;\n   private final int progress;\n   private final S result;\n   private final AsyncJob.ResultCode resultCode;\n   private final String resultType;\n   private final AsyncJob.Status status;\n   private final String userId;\n   private final AsyncJobError error;\n\n   @ConstructorProperties({\n         \"accountid\", \"cmd\", \"created\", \"jobid\", \"jobinstanceid\", \"jobinstancetype\", \"jobprocstatus\", \"jobresult\",\n         \"jobresultcode\", \"jobresulttype\", \"jobstatus\", \"userid\", \"error\"\n   })\n   protected AsyncJob(@Nullable String accountId, @Nullable String cmd, @Nullable Date created, String id,\n                      @Nullable String instanceId, @Nullable String instanceType, int progress, @Nullable S result,\n                      @Nullable AsyncJob.ResultCode resultCode, @Nullable String resultType, @Nullable AsyncJob.Status status,\n                      @Nullable String userId, @Nullable AsyncJobError error) {\n      this.accountId = accountId;\n      this.cmd = cmd;\n      this.created = created;\n      this.id = checkNotNull(id, \"id\");\n      this.instanceId = instanceId;\n      this.instanceType = instanceType;\n      this.progress = progress;\n      this.result = result;\n      this.resultCode = resultCode;\n      this.resultType = resultType;\n      this.status = status;\n      this.userId = userId;\n      this.error = error;\n   }\n\n   /**\n    * @return the account that executed the async command\n    */\n   @Nullable\n   public String getAccountId() {\n      return this.accountId;\n   }\n\n   /**\n    * @return the async command executed\n    */\n   @Nullable\n   public String getCmd() {\n      return this.cmd;\n   }\n\n   /**\n    * @return the created date of the job\n    */\n   @Nullable\n   public Date getCreated() {\n      return this.created;\n   }\n\n   /**\n    * @return async job ID\n    */\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * @return the unique ID of the instance/entity object related to the job\n    */\n   @Nullable\n   public String getInstanceId() {\n      return this.instanceId;\n   }\n\n   /**\n    * @return the instance/entity object related to the job\n    */\n   @Nullable\n   public String getInstanceType() {\n      return this.instanceType;\n   }\n\n   /**\n    * @return the progress information of the PENDING job\n    */\n   public int getProgress() {\n      return this.progress;\n   }\n\n   /**\n    * @return the result reason\n    */\n   @Nullable\n   public S getResult() {\n      return this.result;\n   }\n\n   /**\n    * @return the result code for the job\n    */\n   @Nullable\n   public AsyncJob.ResultCode getResultCode() {\n      return this.resultCode;\n   }\n\n   /**\n    * @return the result type\n    */\n   @Nullable\n   public String getResultType() {\n      return this.resultType;\n   }\n\n   /**\n    * @return the current job status-should be 0 for PENDING\n    */\n   @Nullable\n   public AsyncJob.Status getStatus() {\n      return this.status;\n   }\n\n   /**\n    * @return the user that executed the async command\n    */\n   @Nullable\n   public String getUserId() {\n      return this.userId;\n   }\n\n   /**\n    * @return the error related to this command, or null if no error or error\n    *         not yet encountered.\n    */\n   @Nullable\n   public AsyncJobError getError() {\n      return this.error;\n   }\n\n   public boolean hasFailed() {\n      return getError() != null || getResultCode() == ResultCode.FAIL || getStatus() == Status.FAILED;\n   }\n\n   public boolean hasSucceed() {\n      return getError() == null && getResultCode() == ResultCode.SUCCESS && getStatus() == Status.SUCCEEDED;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(accountId, cmd, created, id, instanceId, instanceType, progress, result, resultCode, resultType, status, userId, error);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      AsyncJob<?> that = AsyncJob.class.cast(obj);\n      return Objects.equal(this.accountId, that.accountId)\n            && Objects.equal(this.cmd, that.cmd)\n            && Objects.equal(this.created, that.created)\n            && Objects.equal(this.id, that.id)\n            && Objects.equal(this.instanceId, that.instanceId)\n            && Objects.equal(this.instanceType, that.instanceType)\n            && Objects.equal(this.progress, that.progress)\n            && Objects.equal(this.result, that.result)\n            && Objects.equal(this.resultCode, that.resultCode)\n            && Objects.equal(this.resultType, that.resultType)\n            && Objects.equal(this.status, that.status)\n            && Objects.equal(this.userId, that.userId)\n            && Objects.equal(this.error, that.error);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"accountId\", accountId).add(\"cmd\", cmd).add(\"created\", created).add(\"id\", id).add(\"instanceId\", instanceId)\n            .add(\"instanceType\", instanceType).add(\"progress\", progress).add(\"result\", result).add(\"resultCode\", resultCode)\n            .add(\"resultType\", resultType).add(\"status\", status).add(\"userId\", userId).add(\"error\", error);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/AsyncJobError.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\npublic class AsyncJobError {\n\n   /**\n    * Error codes for job errors\n    */\n   public static enum ErrorCode {\n      INTERNAL_ERROR(530),\n      ACCOUNT_ERROR(531),\n      ACCOUNT_RESOURCE_LIMIT_ERROR(532),\n      INSUFFICIENT_CAPACITY_ERROR(533),\n      RESOURCE_UNAVAILABLE_ERROR(534),\n      RESOURCE_ALLOCATION_ERROR(535),\n      RESOURCE_IN_USE_ERROR(536),\n      NETWORK_RULE_CONFLICT_ERROR(537),\n      UNKNOWN(-1);\n\n      private final int code;\n\n      private ErrorCode(int code) {\n         this.code = code;\n      }\n\n      public int code() {\n         return this.code;\n      }\n\n      public static ErrorCode fromValue(String value) {\n         try {\n            int errorCode = Integer.parseInt(value);\n            for (ErrorCode candidate : values()) {\n               if (candidate.code() == errorCode) {\n                  return candidate;\n               }\n            }\n            return UNKNOWN;\n\n         } catch (NumberFormatException e) {\n            return UNKNOWN;\n         }\n      }\n   }\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromAsyncJobError(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected AsyncJobError.ErrorCode errorCode;\n      protected String errorText;\n\n      /**\n       * @see AsyncJobError#getErrorCode()\n       */\n      public T errorCode(ErrorCode errorCode) {\n         this.errorCode = errorCode;\n         return self();\n      }\n\n      /**\n       * @see AsyncJobError#getErrorText()\n       */\n      public T errorText(String errorText) {\n         this.errorText = errorText;\n         return self();\n      }\n\n      public AsyncJobError build() {\n         return new AsyncJobError(errorCode, errorText);\n      }\n\n      public T fromAsyncJobError(AsyncJobError in) {\n         return this\n               .errorCode(in.getErrorCode())\n               .errorText(in.getErrorText());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final ErrorCode errorCode;\n   private final String errorText;\n\n   @ConstructorProperties({\n         \"errorcode\", \"errortext\"\n   })\n   protected AsyncJobError(@Nullable ErrorCode errorCode, @Nullable String errorText) {\n      this.errorCode = errorCode;\n      this.errorText = errorText;\n   }\n\n   @Nullable\n   public ErrorCode getErrorCode() {\n      return this.errorCode;\n   }\n\n   @Nullable\n   public String getErrorText() {\n      return this.errorText;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(errorCode, errorText);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      AsyncJobError that = AsyncJobError.class.cast(obj);\n      return Objects.equal(this.errorCode, that.errorCode)\n            && Objects.equal(this.errorText, that.errorText);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"errorCode\", errorCode).add(\"errorText\", errorText);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/Capabilities.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Class Capabilities\n */\npublic class Capabilities {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromCapabilities(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String cloudStackVersion;\n      protected boolean securityGroupsEnabled;\n      protected boolean canShareTemplates;\n      protected boolean firewallRuleUiEnabled;\n      protected boolean supportELB;\n\n      /**\n       * @see Capabilities#getCloudStackVersion()\n       */\n      public T cloudStackVersion(String cloudStackVersion) {\n         this.cloudStackVersion = cloudStackVersion;\n         return self();\n      }\n\n      /**\n       * @see Capabilities#isSecurityGroupsEnabled()\n       */\n      public T securityGroupsEnabled(boolean securityGroupsEnabled) {\n         this.securityGroupsEnabled = securityGroupsEnabled;\n         return self();\n      }\n\n      /**\n       * @see Capabilities#canShareTemplates()\n       */\n      public T canShareTemplates(boolean canShareTemplates) {\n         this.canShareTemplates = canShareTemplates;\n         return self();\n      }\n\n      /**\n       * @see Capabilities#isFirewallRuleUiEnabled()\n       */\n      public T firewallRuleUiEnabled(boolean firewallRuleUiEnabled) {\n         this.firewallRuleUiEnabled = firewallRuleUiEnabled;\n         return self();\n      }\n\n      /**\n       * @see Capabilities#isSupportELB()\n       */\n      public T supportELB(boolean supportELB) {\n         this.supportELB = supportELB;\n         return self();\n      }\n\n      public Capabilities build() {\n         return new Capabilities(cloudStackVersion, securityGroupsEnabled, canShareTemplates, firewallRuleUiEnabled, supportELB);\n      }\n\n      public T fromCapabilities(Capabilities in) {\n         return this\n               .cloudStackVersion(in.getCloudStackVersion())\n               .securityGroupsEnabled(in.isSecurityGroupsEnabled())\n               .canShareTemplates(in.canShareTemplates())\n               .firewallRuleUiEnabled(in.isFirewallRuleUiEnabled())\n               .supportELB(in.isSupportELB());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String cloudStackVersion;\n   private final boolean securityGroupsEnabled;\n   private final boolean canShareTemplates;\n   private final boolean firewallRuleUiEnabled;\n   private final boolean supportELB;\n\n   @ConstructorProperties({\n         \"cloudstackversion\", \"securitygroupsenabled\", \"userpublictemplateenabled\", \"firewallRuleUiEnabled\", \"supportELB\"\n   })\n   protected Capabilities(@Nullable String cloudStackVersion, boolean securityGroupsEnabled, boolean canShareTemplates,\n                          boolean firewallRuleUiEnabled, boolean supportELB) {\n      this.cloudStackVersion = cloudStackVersion;\n      this.securityGroupsEnabled = securityGroupsEnabled;\n      this.canShareTemplates = canShareTemplates;\n      this.firewallRuleUiEnabled = firewallRuleUiEnabled;\n      this.supportELB = supportELB;\n   }\n\n   /**\n    * @return version of the cloud stack\n    */\n   @Nullable\n   public String getCloudStackVersion() {\n      return this.cloudStackVersion;\n   }\n\n   /**\n    * @return true if security groups support is enabled, false otherwise\n    */\n   public boolean isSecurityGroupsEnabled() {\n      return this.securityGroupsEnabled;\n   }\n\n   public boolean canShareTemplates() {\n      return this.canShareTemplates;\n   }\n\n   /**\n    * @return true if the firewall rule UI is enabled\n    */\n   public boolean isFirewallRuleUiEnabled() {\n      return this.firewallRuleUiEnabled;\n   }\n\n   /**\n    * @return true if region supports elastic load balancer on basic zones\n    */\n   public boolean isSupportELB() {\n      return this.supportELB;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(cloudStackVersion, securityGroupsEnabled, canShareTemplates, firewallRuleUiEnabled, supportELB);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Capabilities that = Capabilities.class.cast(obj);\n      return Objects.equal(this.cloudStackVersion, that.cloudStackVersion)\n            && Objects.equal(this.securityGroupsEnabled, that.securityGroupsEnabled)\n            && Objects.equal(this.canShareTemplates, that.canShareTemplates)\n            && Objects.equal(this.firewallRuleUiEnabled, that.firewallRuleUiEnabled)\n            && Objects.equal(this.supportELB, that.supportELB);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"cloudStackVersion\", cloudStackVersion).add(\"securityGroupsEnabled\", securityGroupsEnabled).add(\"canShareTemplates\", canShareTemplates).add(\"firewallRuleUiEnabled\", firewallRuleUiEnabled).add(\"supportELB\", supportELB);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/Capacity.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Map;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Maps;\n\n/**\n * Information about a dimension of the capacity\n */\npublic class Capacity implements Comparable<Capacity> {\n\n   /**\n    */\n   public static enum Type {\n      MEMORY_ALLOCATED_BYTES(0),\n      CPU_ALLOCATED_MHZ(1),\n      PRIMARY_STORAGE_USED_BYTES(2),\n      PRIMARY_STORAGE_ALLOCATED_BYTES(3),\n      PUBLIC_IP_ADDRESSES(4),\n      PRIVATE_IP_ADDRESSES(5),\n      SECONDARY_STORAGE_USED_BYTES(6),\n      VLANS(7),\n      DIRECT_ATTACHED_PUBLIC_IP_ADDRESSES(8),\n      LOCAL_STORAGE_USED_BYTES(9),\n      UNRECOGNIZED(Integer.MAX_VALUE);\n\n      private int code;\n\n      private static final Map<Integer, Type> INDEX = Maps.uniqueIndex(ImmutableSet.copyOf(Type.values()),\n            new Function<Type, Integer>() {\n\n               @Override\n               public Integer apply(Type input) {\n                  return input.code;\n               }\n\n            });\n\n      Type(int code) {\n         this.code = code;\n      }\n\n      @Override\n      public String toString() {\n         return name();\n      }\n\n      public static Type fromValue(String type) {\n         Integer code = Integer.valueOf(checkNotNull(type, \"type\"));\n         return INDEX.containsKey(code) ? INDEX.get(code) : UNRECOGNIZED;\n      }\n   }\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromCapacity(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected long capacityTotal;\n      protected long capacityUsed;\n      protected double percentUsed;\n      protected String podId;\n      protected String podName;\n      protected Capacity.Type type;\n      protected String zoneId;\n      protected String zoneName;\n\n      /**\n       * @see Capacity#getCapacityTotal()\n       */\n      public T capacityTotal(long capacityTotal) {\n         this.capacityTotal = capacityTotal;\n         return self();\n      }\n\n      /**\n       * @see Capacity#getCapacityUsed()\n       */\n      public T capacityUsed(long capacityUsed) {\n         this.capacityUsed = capacityUsed;\n         return self();\n      }\n\n      /**\n       * @see Capacity#getPercentUsed()\n       */\n      public T percentUsed(double percentUsed) {\n         this.percentUsed = percentUsed;\n         return self();\n      }\n\n      /**\n       * @see Capacity#getPodId()\n       */\n      public T podId(String podId) {\n         this.podId = podId;\n         return self();\n      }\n\n      /**\n       * @see Capacity#getPodName()\n       */\n      public T podName(String podName) {\n         this.podName = podName;\n         return self();\n      }\n\n      /**\n       * @see Capacity#getType()\n       */\n      public T type(Capacity.Type type) {\n         this.type = type;\n         return self();\n      }\n\n      /**\n       * @see Capacity#getZoneId()\n       */\n      public T zoneId(String zoneId) {\n         this.zoneId = zoneId;\n         return self();\n      }\n\n      /**\n       * @see Capacity#getZoneName()\n       */\n      public T zoneName(String zoneName) {\n         this.zoneName = zoneName;\n         return self();\n      }\n\n      public Capacity build() {\n         return new Capacity(capacityTotal, capacityUsed, percentUsed, podId, podName, type, zoneId, zoneName);\n      }\n\n      public T fromCapacity(Capacity in) {\n         return this\n               .capacityTotal(in.getCapacityTotal())\n               .capacityUsed(in.getCapacityUsed())\n               .percentUsed(in.getPercentUsed())\n               .podId(in.getPodId())\n               .podName(in.getPodName())\n               .type(in.getType())\n               .zoneId(in.getZoneId())\n               .zoneName(in.getZoneName());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final long capacityTotal;\n   private final long capacityUsed;\n   private final double percentUsed;\n   private final String podId;\n   private final String podName;\n   private final Capacity.Type type;\n   private final String zoneId;\n   private final String zoneName;\n\n   @ConstructorProperties({\n         \"capacitytotal\", \"capacityused\", \"percentused\", \"podid\", \"podname\", \"type\", \"zoneid\", \"zonename\"\n   })\n   protected Capacity(long capacityTotal, long capacityUsed, double percentUsed, @Nullable String podId,\n                      @Nullable String podName, @Nullable Capacity.Type type, @Nullable String zoneId, @Nullable String zoneName) {\n      this.capacityTotal = capacityTotal;\n      this.capacityUsed = capacityUsed;\n      this.percentUsed = percentUsed;\n      this.podId = podId;\n      this.podName = podName;\n      this.type = type;\n      this.zoneId = zoneId;\n      this.zoneName = zoneName;\n   }\n\n   public long getCapacityTotal() {\n      return this.capacityTotal;\n   }\n\n   public long getCapacityUsed() {\n      return this.capacityUsed;\n   }\n\n   public double getPercentUsed() {\n      return this.percentUsed;\n   }\n\n   @Nullable\n   public String getPodId() {\n      return this.podId;\n   }\n\n   @Nullable\n   public String getPodName() {\n      return this.podName;\n   }\n\n   @Nullable\n   public Capacity.Type getType() {\n      return this.type;\n   }\n\n   @Nullable\n   public String getZoneId() {\n      return this.zoneId;\n   }\n\n   @Nullable\n   public String getZoneName() {\n      return this.zoneName;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(capacityTotal, capacityUsed, percentUsed, podId, podName, type, zoneId, zoneName);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Capacity that = Capacity.class.cast(obj);\n      return Objects.equal(this.capacityTotal, that.capacityTotal)\n            && Objects.equal(this.capacityUsed, that.capacityUsed)\n            && Objects.equal(this.percentUsed, that.percentUsed)\n            && Objects.equal(this.podId, that.podId)\n            && Objects.equal(this.podName, that.podName)\n            && Objects.equal(this.type, that.type)\n            && Objects.equal(this.zoneId, that.zoneId)\n            && Objects.equal(this.zoneName, that.zoneName);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"capacityTotal\", capacityTotal).add(\"capacityUsed\", capacityUsed).add(\"percentUsed\", percentUsed)\n            .add(\"podId\", podId).add(\"podName\", podName).add(\"type\", type).add(\"zoneId\", zoneId).add(\"zoneName\", zoneName);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int compareTo(Capacity other) {\n      int comparison = this.zoneId.compareTo(other.zoneId);\n      if (comparison == 0) comparison = this.podId.compareTo(other.podId);\n      if (comparison == 0) comparison = Integer.valueOf(this.type.code).compareTo(other.type.code);\n      return comparison;\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/Cluster.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.CaseFormat.UPPER_CAMEL;\nimport static com.google.common.base.CaseFormat.UPPER_UNDERSCORE;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Represents a CloudStack Cluster.\n */\npublic class Cluster implements Comparable<Cluster> {\n\n   /**\n    */\n   public static enum ManagedState {\n      MANAGED,\n      PREPARE_UNMANAGED,\n      UNMANAGED,\n      PREPARE_UNMANAGED_ERROR,\n      UNRECOGNIZED;\n\n      public static ManagedState fromValue(String value) {\n         try {\n            return valueOf(UPPER_CAMEL.to(UPPER_UNDERSCORE, value));\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n\n      @Override\n      public String toString() {\n         return UPPER_UNDERSCORE.to(UPPER_CAMEL, name());\n      }\n   }\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromCluster(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String id;\n      protected AllocationState allocationState;\n      protected Host.ClusterType clusterType;\n      protected String hypervisor;\n      protected Cluster.ManagedState managedState;\n      protected String name;\n      protected String podId;\n      protected String podName;\n      protected String zoneId;\n      protected String zoneName;\n\n      /**\n       * @see Cluster#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see Cluster#getAllocationState()\n       */\n      public T allocationState(AllocationState allocationState) {\n         this.allocationState = allocationState;\n         return self();\n      }\n\n      /**\n       * @see Cluster#getClusterType()\n       */\n      public T clusterType(Host.ClusterType clusterType) {\n         this.clusterType = clusterType;\n         return self();\n      }\n\n      /**\n       * @see Cluster#getHypervisor()\n       */\n      public T hypervisor(String hypervisor) {\n         this.hypervisor = hypervisor;\n         return self();\n      }\n\n      /**\n       * @see Cluster#getManagedState()\n       */\n      public T managedState(Cluster.ManagedState managedState) {\n         this.managedState = managedState;\n         return self();\n      }\n\n      /**\n       * @see Cluster#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /**\n       * @see Cluster#getPodId()\n       */\n      public T podId(String podId) {\n         this.podId = podId;\n         return self();\n      }\n\n      /**\n       * @see Cluster#getPodName()\n       */\n      public T podName(String podName) {\n         this.podName = podName;\n         return self();\n      }\n\n      /**\n       * @see Cluster#getZoneId()\n       */\n      public T zoneId(String zoneId) {\n         this.zoneId = zoneId;\n         return self();\n      }\n\n      /**\n       * @see Cluster#getZoneName()\n       */\n      public T zoneName(String zoneName) {\n         this.zoneName = zoneName;\n         return self();\n      }\n\n      public Cluster build() {\n         return new Cluster(id, allocationState, clusterType, hypervisor, managedState, name, podId, podName, zoneId, zoneName);\n      }\n\n      public T fromCluster(Cluster in) {\n         return this\n               .id(in.getId())\n               .allocationState(in.getAllocationState())\n               .clusterType(in.getClusterType())\n               .hypervisor(in.getHypervisor())\n               .managedState(in.getManagedState())\n               .name(in.getName())\n               .podId(in.getPodId())\n               .podName(in.getPodName())\n               .zoneId(in.getZoneId())\n               .zoneName(in.getZoneName());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final AllocationState allocationState;\n   private final Host.ClusterType clusterType;\n   private final String hypervisor;\n   private final Cluster.ManagedState managedState;\n   private final String name;\n   private final String podId;\n   private final String podName;\n   private final String zoneId;\n   private final String zoneName;\n\n   @ConstructorProperties({\n         \"id\", \"allocationstate\", \"clustertype\", \"hypervisortype\", \"managedstate\", \"name\", \"podid\", \"podname\", \"zoneid\", \"zonename\"\n   })\n   protected Cluster(String id, @Nullable AllocationState allocationState, @Nullable Host.ClusterType clusterType,\n                     @Nullable String hypervisor, @Nullable Cluster.ManagedState managedState, @Nullable String name,\n                     @Nullable String podId, @Nullable String podName, @Nullable String zoneId, @Nullable String zoneName) {\n      this.id = checkNotNull(id, \"id\");\n      this.allocationState = allocationState;\n      this.clusterType = clusterType;\n      this.hypervisor = hypervisor;\n      this.managedState = managedState;\n      this.name = name;\n      this.podId = podId;\n      this.podName = podName;\n      this.zoneId = zoneId;\n      this.zoneName = zoneName;\n   }\n\n   public String getId() {\n      return this.id;\n   }\n\n   @Nullable\n   public AllocationState getAllocationState() {\n      return this.allocationState;\n   }\n\n   @Nullable\n   public Host.ClusterType getClusterType() {\n      return this.clusterType;\n   }\n\n   @Nullable\n   public String getHypervisor() {\n      return this.hypervisor;\n   }\n\n   @Nullable\n   public Cluster.ManagedState getManagedState() {\n      return this.managedState;\n   }\n\n   @Nullable\n   public String getName() {\n      return this.name;\n   }\n\n   @Nullable\n   public String getPodId() {\n      return this.podId;\n   }\n\n   @Nullable\n   public String getPodName() {\n      return this.podName;\n   }\n\n   @Nullable\n   public String getZoneId() {\n      return this.zoneId;\n   }\n\n   @Nullable\n   public String getZoneName() {\n      return this.zoneName;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, allocationState, clusterType, hypervisor, managedState, name, podId, podName, zoneId, zoneName);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Cluster that = Cluster.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n            && Objects.equal(this.allocationState, that.allocationState)\n            && Objects.equal(this.clusterType, that.clusterType)\n            && Objects.equal(this.hypervisor, that.hypervisor)\n            && Objects.equal(this.managedState, that.managedState)\n            && Objects.equal(this.name, that.name)\n            && Objects.equal(this.podId, that.podId)\n            && Objects.equal(this.podName, that.podName)\n            && Objects.equal(this.zoneId, that.zoneId)\n            && Objects.equal(this.zoneName, that.zoneName);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"allocationState\", allocationState).add(\"clusterType\", clusterType).add(\"hypervisor\", hypervisor)\n            .add(\"managedState\", managedState).add(\"name\", name).add(\"podId\", podId).add(\"podName\", podName).add(\"zoneId\", zoneId).add(\"zoneName\", zoneName);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int compareTo(Cluster other) {\n      return this.id.compareTo(other.id);\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/ConfigurationEntry.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Representation of the API configuration entry response\n */\npublic class ConfigurationEntry implements Comparable<ConfigurationEntry> {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromConfigurationEntry(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String category;\n      protected String description;\n      protected String name;\n      protected String value;\n\n      /**\n       * @see ConfigurationEntry#getCategory()\n       */\n      public T category(String category) {\n         this.category = category;\n         return self();\n      }\n\n      /**\n       * @see ConfigurationEntry#getDescription()\n       */\n      public T description(String description) {\n         this.description = description;\n         return self();\n      }\n\n      /**\n       * @see ConfigurationEntry#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /**\n       * @see ConfigurationEntry#getValue()\n       */\n      public T value(String value) {\n         this.value = value;\n         return self();\n      }\n\n      public ConfigurationEntry build() {\n         return new ConfigurationEntry(category, description, name, value);\n      }\n\n      public T fromConfigurationEntry(ConfigurationEntry in) {\n         return this\n               .category(in.getCategory())\n               .description(in.getDescription())\n               .name(in.getName())\n               .value(in.getValue());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String category;\n   private final String description;\n   private final String name;\n   private final String value;\n\n   @ConstructorProperties({\n         \"category\", \"description\", \"name\", \"value\"\n   })\n   protected ConfigurationEntry(@Nullable String category, @Nullable String description, String name, @Nullable String value) {\n      this.category = category;\n      this.description = description;\n      this.name = checkNotNull(name, \"name\");\n      this.value = value;\n   }\n\n   @Nullable\n   public String getCategory() {\n      return this.category;\n   }\n\n   @Nullable\n   public String getDescription() {\n      return this.description;\n   }\n\n   public String getName() {\n      return this.name;\n   }\n\n   @Nullable\n   public String getValue() {\n      return this.value;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(category, description, name, value);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      ConfigurationEntry that = ConfigurationEntry.class.cast(obj);\n      return Objects.equal(this.category, that.category)\n            && Objects.equal(this.description, that.description)\n            && Objects.equal(this.name, that.name)\n            && Objects.equal(this.value, that.value);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"category\", category).add(\"description\", description).add(\"name\", name).add(\"value\", value);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int compareTo(ConfigurationEntry other) {\n      return name.compareTo(other.getName());\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/DiskOffering.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Class DiskOffering\n */\npublic class DiskOffering implements Comparable<DiskOffering> {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromDiskOffering(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String id;\n      protected String name;\n      protected String displayText;\n      protected Date created;\n      protected String domain;\n      protected String domainId;\n      protected int diskSize;\n      protected boolean customized;\n      protected ImmutableSet.Builder<String> tags = ImmutableSet.<String>builder();\n\n      /**\n       * @see DiskOffering#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see DiskOffering#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /**\n       * @see DiskOffering#getDisplayText()\n       */\n      public T displayText(String displayText) {\n         this.displayText = displayText;\n         return self();\n      }\n\n      /**\n       * @see DiskOffering#getCreated()\n       */\n      public T created(Date created) {\n         this.created = created;\n         return self();\n      }\n\n      /**\n       * @see DiskOffering#getDomain()\n       */\n      public T domain(String domain) {\n         this.domain = domain;\n         return self();\n      }\n\n      /**\n       * @see DiskOffering#getDomainId()\n       */\n      public T domainId(String domainId) {\n         this.domainId = domainId;\n         return self();\n      }\n\n      /**\n       * @see DiskOffering#getDiskSize()\n       */\n      public T diskSize(int diskSize) {\n         this.diskSize = diskSize;\n         return self();\n      }\n\n      /**\n       * @see DiskOffering#isCustomized()\n       */\n      public T customized(boolean customized) {\n         this.customized = customized;\n         return self();\n      }\n\n      /**\n       * @see DiskOffering#getTags()\n       */\n      public T tags(Iterable<String> tags) {\n         this.tags = ImmutableSet.<String>builder().addAll(tags);\n         return self();\n      }\n      \n      /**\n       * @see DiskOffering#getTags()\n       */\n      public T tag(String tag) {\n         this.tags.add(tag);\n         return self();\n      }\n      \n      public DiskOffering build() {\n         return new DiskOffering(id, name, displayText, created, domain, domainId, diskSize, customized, tags.build());\n      }\n\n      public T fromDiskOffering(DiskOffering in) {\n         return this\n               .id(in.getId())\n               .name(in.getName())\n               .displayText(in.getDisplayText())\n               .created(in.getCreated())\n               .domain(in.getDomain())\n               .domainId(in.getDomainId())\n               .diskSize(in.getDiskSize())\n               .customized(in.isCustomized())\n               .tags(in.getTags());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final String name;\n   private final String displayText;\n   private final Date created;\n   private final String domain;\n   private final String domainId;\n   private final int diskSize;\n   private final boolean customized;\n   private final Set<String> tags;\n\n   @ConstructorProperties({\n         \"id\", \"name\", \"displaytext\", \"created\", \"domain\", \"domainid\", \"disksize\", \"iscustomized\", \"tags\"\n   })\n   protected DiskOffering(String id, @Nullable String name, @Nullable String displayText, @Nullable Date created,\n                          @Nullable String domain, @Nullable String domainId, int diskSize, boolean customized,\n                          @Nullable Iterable<String> tags) {\n      this.id = checkNotNull(id, \"id\");\n      this.name = name;\n      this.displayText = displayText;\n      this.created = created;\n      this.domain = domain;\n      this.domainId = domainId;\n      this.diskSize = diskSize;\n      this.customized = customized;\n      this.tags = tags != null ? ImmutableSet.copyOf(tags) : ImmutableSet.<String> of();\n   }\n\n   /**\n    * @return the id of the disk offering\n    */\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * @return the name of the disk offering\n    */\n   @Nullable\n   public String getName() {\n      return this.name;\n   }\n\n   /**\n    * @return an alternate display text of the disk offering.\n    */\n   @Nullable\n   public String getDisplayText() {\n      return this.displayText;\n   }\n\n   /**\n    * @return the date this disk offering was created\n    */\n   @Nullable\n   public Date getCreated() {\n      return this.created;\n   }\n\n   /**\n    * @return Domain name for the offering\n    */\n   @Nullable\n   public String getDomain() {\n      return this.domain;\n   }\n\n   /**\n    * @return the domain id of the disk offering\n    */\n   @Nullable\n   public String getDomainId() {\n      return this.domainId;\n   }\n\n   /**\n    * @return the size of the disk offering in GB\n    */\n   public int getDiskSize() {\n      return this.diskSize;\n   }\n\n   /**\n    * @return the ha support in the disk offering\n    */\n   public boolean isCustomized() {\n      return this.customized;\n   }\n\n   /**\n    * @return the tags for the disk offering\n    */\n   public Set<String> getTags() {\n      return this.tags;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, name, displayText, created, domain, domainId, diskSize, customized, tags);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      DiskOffering that = DiskOffering.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n            && Objects.equal(this.name, that.name)\n            && Objects.equal(this.displayText, that.displayText)\n            && Objects.equal(this.created, that.created)\n            && Objects.equal(this.domain, that.domain)\n            && Objects.equal(this.domainId, that.domainId)\n            && Objects.equal(this.diskSize, that.diskSize)\n            && Objects.equal(this.customized, that.customized)\n            && Objects.equal(this.tags, that.tags);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"name\", name).add(\"displayText\", displayText).add(\"created\", created).add(\"domain\", domain)\n            .add(\"domainId\", domainId).add(\"diskSize\", diskSize).add(\"customized\", customized).add(\"tags\", tags);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int compareTo(DiskOffering other) {\n      return id.compareTo(other.getId());\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/Domain.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Representation of the API domain response\n */\npublic class Domain implements Comparable<Domain> {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromDomain(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String id;\n      protected boolean hasChild;\n      protected long level;\n      protected String name;\n      protected String networkDomain;\n      protected String parentDomainId;\n      protected String parentDomainName;\n\n      /**\n       * @see Domain#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see Domain#hasChild()\n       */\n      public T hasChild(boolean hasChild) {\n         this.hasChild = hasChild;\n         return self();\n      }\n\n      /**\n       * @see Domain#getLevel()\n       */\n      public T level(long level) {\n         this.level = level;\n         return self();\n      }\n\n      /**\n       * @see Domain#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /**\n       * @see Domain#getNetworkDomain()\n       */\n      public T networkDomain(String networkDomain) {\n         this.networkDomain = networkDomain;\n         return self();\n      }\n\n      /**\n       * @see Domain#getParentDomainId()\n       */\n      public T parentDomainId(String parentDomainId) {\n         this.parentDomainId = parentDomainId;\n         return self();\n      }\n\n      /**\n       * @see Domain#getParentDomainName()\n       */\n      public T parentDomainName(String parentDomainName) {\n         this.parentDomainName = parentDomainName;\n         return self();\n      }\n\n      public Domain build() {\n         return new Domain(id, hasChild, level, name, networkDomain, parentDomainId, parentDomainName);\n      }\n\n      public T fromDomain(Domain in) {\n         return this\n               .id(in.getId())\n               .hasChild(in.hasChild())\n               .level(in.getLevel())\n               .name(in.getName())\n               .networkDomain(in.getNetworkDomain())\n               .parentDomainId(in.getParentDomainId())\n               .parentDomainName(in.getParentDomainName());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final boolean hasChild;\n   private final long level;\n   private final String name;\n   private final String networkDomain;\n   private final String parentDomainId;\n   private final String parentDomainName;\n\n   @ConstructorProperties({\n         \"id\", \"haschild\", \"level\", \"name\", \"networkdomain\", \"parentdomainid\", \"parentdomainname\"\n   })\n   protected Domain(String id, boolean hasChild, long level, @Nullable String name, @Nullable String networkDomain,\n                    @Nullable String parentDomainId, @Nullable String parentDomainName) {\n      this.id = checkNotNull(id, \"id\");\n      this.hasChild = hasChild;\n      this.level = level;\n      this.name = name;\n      this.networkDomain = networkDomain;\n      this.parentDomainId = parentDomainId;\n      this.parentDomainName = parentDomainName;\n   }\n\n   public String getId() {\n      return this.id;\n   }\n\n   public boolean hasChild() {\n      return this.hasChild;\n   }\n\n   public long getLevel() {\n      return this.level;\n   }\n\n   @Nullable\n   public String getName() {\n      return this.name;\n   }\n\n   @Nullable\n   public String getNetworkDomain() {\n      return this.networkDomain;\n   }\n\n   @Nullable\n   public String getParentDomainId() {\n      return this.parentDomainId;\n   }\n\n   @Nullable\n   public String getParentDomainName() {\n      return this.parentDomainName;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, hasChild, level, name, networkDomain, parentDomainId, parentDomainName);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Domain that = Domain.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n            && Objects.equal(this.hasChild, that.hasChild)\n            && Objects.equal(this.level, that.level)\n            && Objects.equal(this.name, that.name)\n            && Objects.equal(this.networkDomain, that.networkDomain)\n            && Objects.equal(this.parentDomainId, that.parentDomainId)\n            && Objects.equal(this.parentDomainName, that.parentDomainName);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"hasChild\", hasChild).add(\"level\", level).add(\"name\", name).add(\"networkDomain\", networkDomain).add(\"parentDomainId\", parentDomainId).add(\"parentDomainName\", parentDomainName);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int compareTo(Domain other) {\n      return id.compareTo(other.getId());\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/EncryptedPasswordAndPrivateKey.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\npublic final class EncryptedPasswordAndPrivateKey {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().fromEncryptedPasswordAndPrivateKey(this);\n   }\n\n   public static final class Builder {\n\n      protected String encryptedPassword;\n      protected String privateKey;\n\n      /**\n       * @see EncryptedPasswordAndPrivateKey#getEncryptedPassword()\n       */\n      public Builder encryptedPassword(String encryptedPassword) {\n         this.encryptedPassword = encryptedPassword;\n         return this;\n      }\n\n      /**\n       * @see EncryptedPasswordAndPrivateKey#getPrivateKey()\n       */\n      public Builder privateKey(String privateKey) {\n         this.privateKey = privateKey;\n         return this;\n      }\n\n      public EncryptedPasswordAndPrivateKey build() {\n         return new EncryptedPasswordAndPrivateKey(encryptedPassword, privateKey);\n      }\n\n      public Builder fromEncryptedPasswordAndPrivateKey(EncryptedPasswordAndPrivateKey in) {\n         return encryptedPassword(in.getEncryptedPassword())\n               .privateKey(in.getPrivateKey());\n      }\n   }\n\n   private final String encryptedPassword;\n   private final String privateKey;\n\n   @ConstructorProperties({\n         \"encryptedPassword\", \"privateKey\"\n   })\n   public EncryptedPasswordAndPrivateKey(@Nullable String encryptedPassword, @Nullable String privateKey) {\n      this.encryptedPassword = encryptedPassword;\n      this.privateKey = privateKey;\n   }\n\n   /**\n    * @return the encrypted password String representation\n    */\n   @Nullable\n   public String getEncryptedPassword() {\n      return this.encryptedPassword;\n   }\n\n   /**\n    * @return get the string representation of the private key\n    */\n   @Nullable\n   public String getPrivateKey() {\n      return this.privateKey;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(encryptedPassword, privateKey);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      EncryptedPasswordAndPrivateKey that = EncryptedPasswordAndPrivateKey.class.cast(obj);\n      return Objects.equal(this.encryptedPassword, that.encryptedPassword)\n            && Objects.equal(this.privateKey, that.privateKey);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).omitNullValues()\n            .add(\"encryptedPassword\", encryptedPassword).add(\"privateKey\", privateKey).toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/Event.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Class Event\n */\npublic class Event implements Comparable<Event> {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromEvent(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String id;\n      protected String account;\n      protected String description;\n      protected Date created;\n      protected String domain;\n      protected String domainId;\n      protected String level;\n      protected String parentId;\n      protected String state;\n      protected String type;\n      protected String username;\n\n      /**\n       * @see Event#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see Event#getAccount()\n       */\n      public T account(String account) {\n         this.account = account;\n         return self();\n      }\n\n      /**\n       * @see Event#getDescription()\n       */\n      public T description(String description) {\n         this.description = description;\n         return self();\n      }\n\n      /**\n       * @see Event#getCreated()\n       */\n      public T created(Date created) {\n         this.created = created;\n         return self();\n      }\n\n      /**\n       * @see Event#getDomain()\n       */\n      public T domain(String domain) {\n         this.domain = domain;\n         return self();\n      }\n\n      /**\n       * @see Event#getDomainId()\n       */\n      public T domainId(String domainId) {\n         this.domainId = domainId;\n         return self();\n      }\n\n      /**\n       * @see Event#getLevel()\n       */\n      public T level(String level) {\n         this.level = level;\n         return self();\n      }\n\n      /**\n       * @see Event#getParentId()\n       */\n      public T parentId(String parentId) {\n         this.parentId = parentId;\n         return self();\n      }\n\n      /**\n       * @see Event#getState()\n       */\n      public T state(String state) {\n         this.state = state;\n         return self();\n      }\n\n      /**\n       * @see Event#getType()\n       */\n      public T type(String type) {\n         this.type = type;\n         return self();\n      }\n\n      /**\n       * @see Event#getUsername()\n       */\n      public T username(String username) {\n         this.username = username;\n         return self();\n      }\n\n      public Event build() {\n         return new Event(id, account, description, created, domain, domainId, level, parentId, state, type, username);\n      }\n\n      public T fromEvent(Event in) {\n         return this\n               .id(in.getId())\n               .account(in.getAccount())\n               .description(in.getDescription())\n               .created(in.getCreated())\n               .domain(in.getDomain())\n               .domainId(in.getDomainId())\n               .level(in.getLevel())\n               .parentId(in.getParentId())\n               .state(in.getState())\n               .type(in.getType())\n               .username(in.getUsername());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final String account;\n   private final String description;\n   private final Date created;\n   private final String domain;\n   private final String domainId;\n   private final String level;\n   private final String parentId;\n   private final String state;\n   private final String type;\n   private final String username;\n\n   @ConstructorProperties({\n         \"id\", \"account\", \"description\", \"created\", \"domain\", \"domainId\", \"level\", \"parentId\", \"state\", \"type\", \"username\"\n   })\n   protected Event(String id, @Nullable String account, @Nullable String description, @Nullable Date created,\n                   @Nullable String domain, @Nullable String domainId, @Nullable String level, @Nullable String parentId,\n                   @Nullable String state, @Nullable String type, @Nullable String username) {\n      this.id = checkNotNull(id, \"id\");\n      this.account = account;\n      this.description = description;\n      this.created = created;\n      this.domain = domain;\n      this.domainId = domainId;\n      this.level = level;\n      this.parentId = parentId;\n      this.state = state;\n      this.type = type;\n      this.username = username;\n   }\n\n   /**\n    * @return the ID of the event\n    */\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * @return the account name for the account that owns the object being acted on in the event\n    *         (e.g. the owner of the virtual machine, ip address, or security group)\n    */\n   @Nullable\n   public String getAccount() {\n      return this.account;\n   }\n\n   /**\n    * @return the description of the event\n    */\n   @Nullable\n   public String getDescription() {\n      return this.description;\n   }\n\n   /**\n    * @return the date the event was created\n    */\n   @Nullable\n   public Date getCreated() {\n      return this.created;\n   }\n\n   /**\n    * @return the name of the account's domain\n    */\n   @Nullable\n   public String getDomain() {\n      return this.domain;\n   }\n\n   /**\n    * @return the id of the account's domain\n    */\n   @Nullable\n   public String getDomainId() {\n      return this.domainId;\n   }\n\n   /**\n    * @return the event level (INFO, WARN, ERROR)\n    */\n   @Nullable\n   public String getLevel() {\n      return this.level;\n   }\n\n   /**\n    * @return whether the event is parented\n    */\n   @Nullable\n   public String getParentId() {\n      return this.parentId;\n   }\n\n   /**\n    * @return the state of the event\n    */\n   @Nullable\n   public String getState() {\n      return this.state;\n   }\n\n   /**\n    * @return the type of the event (see event types)\n    */\n   @Nullable\n   public String getType() {\n      return this.type;\n   }\n\n   /**\n    * @return the name of the user who performed the action (can be different from the account if\n    *         an admin is performing an action for a user, e.g. starting/stopping a user's virtual machine)\n    */\n   @Nullable\n   public String getUsername() {\n      return this.username;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, account, description, created, domain, domainId, level, parentId, state, type, username);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Event that = Event.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n            && Objects.equal(this.account, that.account)\n            && Objects.equal(this.description, that.description)\n            && Objects.equal(this.created, that.created)\n            && Objects.equal(this.domain, that.domain)\n            && Objects.equal(this.domainId, that.domainId)\n            && Objects.equal(this.level, that.level)\n            && Objects.equal(this.parentId, that.parentId)\n            && Objects.equal(this.state, that.state)\n            && Objects.equal(this.type, that.type)\n            && Objects.equal(this.username, that.username);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"account\", account).add(\"description\", description).add(\"created\", created)\n            .add(\"domain\", domain).add(\"domainId\", domainId).add(\"level\", level).add(\"parentId\", parentId)\n            .add(\"state\", state).add(\"type\", type).add(\"username\", username);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int compareTo(Event other) {\n      return id.compareTo(other.getId());\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/ExtractMode.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\npublic enum ExtractMode {\n\n   HTTP_DOWNLOAD, FTP_UPLOAD, UNRECOGNIZED;\n\n   public static ExtractMode fromValue(String format) {\n      try {\n         return valueOf(checkNotNull(format, \"format\"));\n      } catch (IllegalArgumentException e) {\n         return UNRECOGNIZED;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/FirewallRule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.CaseFormat;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Class FirewallRule\n */\npublic class FirewallRule implements Comparable<FirewallRule> {\n\n   /**\n    */\n   public static enum Protocol {\n      TCP,\n      UDP,\n      ICMP,\n      UNKNOWN;\n\n      public static Protocol fromValue(String value) {\n         try {\n            return valueOf(value.toUpperCase());\n         } catch (IllegalArgumentException e) {\n            return UNKNOWN;\n         }\n      }\n\n      @Override\n      public String toString() {\n         return name().toUpperCase();\n      }\n   }\n\n   public static enum State {\n      STAGED,     // Rule been created but has never got through network rule conflict detection.\n      // Rules in this state can not be sent to network elements.\n      ADD,        // Add means the rule has been created and has gone through network rule conflict detection.\n      ACTIVE,     // Rule has been sent to the network elements and reported to be active.\n      DELETING,   // Revoke means this rule has been revoked. If this rule has been sent to the\n      // network elements, the rule will be deleted from database.\n      UNKNOWN;\n\n      public static State fromValue(String value) {\n         try {\n            return valueOf(value.toUpperCase());\n         } catch (IllegalArgumentException e) {\n            return UNKNOWN;\n         }\n      }\n\n      @Override\n      public String toString() {\n         return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name());\n      }\n   }\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromFirewallRule(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String id;\n      protected Set<String> CIDRs = ImmutableSet.of();\n      protected int startPort;\n      protected int endPort;\n      protected String icmpCode;\n      protected String icmpType;\n      protected String ipAddress;\n      protected String ipAddressId;\n      protected FirewallRule.Protocol protocol;\n      protected FirewallRule.State state;\n      protected Set<Tag> tags = ImmutableSet.of();\n\n      /**\n       * @see FirewallRule#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see FirewallRule#getCIDRs()\n       */\n      public T CIDRs(Set<String> CIDRs) {\n         this.CIDRs = ImmutableSet.copyOf(checkNotNull(CIDRs, \"CIDRs\"));\n         return self();\n      }\n\n      public T CIDRs(String... in) {\n         return CIDRs(ImmutableSet.copyOf(in));\n      }\n\n      /**\n       * @see FirewallRule#getStartPort()\n       */\n      public T startPort(int startPort) {\n         this.startPort = startPort;\n         return self();\n      }\n\n      /**\n       * @see FirewallRule#getEndPort()\n       */\n      public T endPort(int endPort) {\n         this.endPort = endPort;\n         return self();\n      }\n\n      /**\n       * @see FirewallRule#getIcmpCode()\n       */\n      public T icmpCode(String icmpCode) {\n         this.icmpCode = icmpCode;\n         return self();\n      }\n\n      /**\n       * @see FirewallRule#getIcmpType()\n       */\n      public T icmpType(String icmpType) {\n         this.icmpType = icmpType;\n         return self();\n      }\n\n      /**\n       * @see FirewallRule#getIpAddress()\n       */\n      public T ipAddress(String ipAddress) {\n         this.ipAddress = ipAddress;\n         return self();\n      }\n\n      /**\n       * @see FirewallRule#getIpAddressId()\n       */\n      public T ipAddressId(String ipAddressId) {\n         this.ipAddressId = ipAddressId;\n         return self();\n      }\n\n      /**\n       * @see FirewallRule#getProtocol()\n       */\n      public T protocol(FirewallRule.Protocol protocol) {\n         this.protocol = protocol;\n         return self();\n      }\n\n      /**\n       * @see FirewallRule#getState()\n       */\n      public T state(FirewallRule.State state) {\n         this.state = state;\n         return self();\n      }\n\n      /**\n       * @see FirewallRule#getTags()\n       */\n      public T tags(Set<Tag> tags) {\n         this.tags = ImmutableSet.copyOf(checkNotNull(tags, \"tags\"));\n         return self();\n      }\n\n      public T tags(Tag... in) {\n         return tags(ImmutableSet.copyOf(in));\n      }\n\n      public FirewallRule build() {\n         return new FirewallRule(id, CIDRs, startPort, endPort, icmpCode, icmpType, ipAddress, ipAddressId, protocol, state, tags);\n      }\n\n      public T fromFirewallRule(FirewallRule in) {\n         return this\n               .id(in.getId())\n               .CIDRs(in.getCIDRs())\n               .startPort(in.getStartPort())\n               .endPort(in.getEndPort())\n               .icmpCode(in.getIcmpCode())\n               .icmpType(in.getIcmpType())\n               .ipAddress(in.getIpAddress())\n               .ipAddressId(in.getIpAddressId())\n               .protocol(in.getProtocol())\n               .state(in.getState())\n               .tags(in.getTags());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final Set<String> CIDRs;\n   private final int startPort;\n   private final int endPort;\n   private final String icmpCode;\n   private final String icmpType;\n   private final String ipAddress;\n   private final String ipAddressId;\n   private final FirewallRule.Protocol protocol;\n   private final FirewallRule.State state;\n   private final Set<Tag> tags;\n\n   @ConstructorProperties({\n         \"id\", \"cidrlist\", \"startport\", \"endport\", \"icmpcode\", \"icmptype\", \"ipaddress\", \"ipaddressid\", \"protocol\", \"state\", \"tags\"\n   })\n   private FirewallRule(String id, @Nullable String CIDRs, int startPort, int endPort, @Nullable String icmpCode,\n                        @Nullable String icmpType, @Nullable String ipAddress, @Nullable String ipAddressId,\n                        @Nullable Protocol protocol, @Nullable State state, @Nullable Set<Tag> tags) {\n      this(id, splitStringOnCommas(CIDRs), startPort, endPort, icmpCode, icmpType, ipAddress, ipAddressId, protocol, state, tags);\n   }\n\n   private static Set<String> splitStringOnCommas(String in) {\n      return in == null ? ImmutableSet.<String>of() : ImmutableSet.copyOf(in.split(\",\"));\n   }\n\n\n   protected FirewallRule(String id, @Nullable Iterable<String> CIDRs, int startPort, int endPort, @Nullable String icmpCode,\n                          @Nullable String icmpType, @Nullable String ipAddress, @Nullable String ipAddressId,\n                          @Nullable FirewallRule.Protocol protocol, @Nullable FirewallRule.State state, @Nullable Set<Tag> tags) {\n      this.id = checkNotNull(id, \"id\");\n      this.CIDRs = CIDRs == null ? ImmutableSet.<String>of() : ImmutableSet.copyOf(CIDRs);\n      this.startPort = startPort;\n      this.endPort = endPort;\n      this.icmpCode = icmpCode;\n      this.icmpType = icmpType;\n      this.ipAddress = ipAddress;\n      this.ipAddressId = ipAddressId;\n      this.protocol = protocol;\n      this.state = state;\n      this.tags = tags == null ? ImmutableSet.<Tag>of() : ImmutableSet.copyOf(tags);\n   }\n\n   public String getId() {\n      return this.id;\n   }\n\n   public Set<String> getCIDRs() {\n      return this.CIDRs;\n   }\n\n   public int getStartPort() {\n      return this.startPort;\n   }\n\n   public int getEndPort() {\n      return this.endPort;\n   }\n\n   @Nullable\n   public String getIcmpCode() {\n      return this.icmpCode;\n   }\n\n   @Nullable\n   public String getIcmpType() {\n      return this.icmpType;\n   }\n\n   @Nullable\n   public String getIpAddress() {\n      return this.ipAddress;\n   }\n\n   @Nullable\n   public String getIpAddressId() {\n      return this.ipAddressId;\n   }\n\n   @Nullable\n   public FirewallRule.Protocol getProtocol() {\n      return this.protocol;\n   }\n\n   @Nullable\n   public FirewallRule.State getState() {\n      return this.state;\n   }\n\n   @Nullable\n   public Set<Tag> getTags() {\n      return this.tags;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, CIDRs, startPort, endPort, icmpCode, icmpType, ipAddress, ipAddressId, protocol, state, tags);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      FirewallRule that = FirewallRule.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n            && Objects.equal(this.CIDRs, that.CIDRs)\n            && Objects.equal(this.startPort, that.startPort)\n            && Objects.equal(this.endPort, that.endPort)\n            && Objects.equal(this.icmpCode, that.icmpCode)\n            && Objects.equal(this.icmpType, that.icmpType)\n            && Objects.equal(this.ipAddress, that.ipAddress)\n            && Objects.equal(this.ipAddressId, that.ipAddressId)\n            && Objects.equal(this.protocol, that.protocol)\n            && Objects.equal(this.state, that.state)\n            && Objects.equal(this.tags, that.tags);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"CIDRs\", CIDRs).add(\"startPort\", startPort).add(\"endPort\", endPort).add(\"icmpCode\", icmpCode)\n            .add(\"icmpType\", icmpType).add(\"ipAddress\", ipAddress).add(\"ipAddressId\", ipAddressId).add(\"protocol\", protocol).add(\"state\", state)\n            .add(\"tags\", tags);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int compareTo(FirewallRule other) {\n      return id.compareTo(other.getId());\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/GuestIPType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.CaseFormat;\n\n/**\n * @see org.jclouds.cloudstack.features.OfferingApi#listNetworkOfferings\n */\npublic enum GuestIPType {\n\n   /**\n    * guest IP address will be issued by Dhcp server in the guest virtual\n    * network. Dhcp role is played by domain router.\n    */\n   VIRTUAL,\n\n   /**\n    * traffic directly to the network and VMs created here are assigned an IP\n    * directly from the network as configured\n    */\n   DIRECT,\n\n   /**\n    * TODO: add comments to explain the meaning (cs3 only)\n    */\n   SHARED,\n   ISOLATED,\n\n   UNRECOGNIZED;\n\n   @Override\n   public String toString() {\n      return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name());\n   }\n\n   public static GuestIPType fromValue(String type) {\n      try {\n         return valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, checkNotNull(type, \"type\")));\n      } catch (IllegalArgumentException e) {\n         return UNRECOGNIZED;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/Host.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.CaseFormat.UPPER_CAMEL;\nimport static com.google.common.base.CaseFormat.UPPER_UNDERSCORE;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Represents a host issued by Cloudstack\n */\npublic class Host implements Comparable<Host> {\n\n   public static enum ClusterType {\n      CLOUD_MANAGED,\n      EXTERNAL_MANAGED,\n      UNKNOWN;\n\n      public static ClusterType fromValue(String value) {\n         try {\n            return valueOf(UPPER_CAMEL.to(UPPER_UNDERSCORE, value));\n         } catch (IllegalArgumentException e) {\n            return UNKNOWN;\n         }\n      }\n\n      @Override\n      public String toString() {\n         return UPPER_UNDERSCORE.to(UPPER_CAMEL, name());\n      }\n   }\n\n   public static enum State {\n      CONNECTING,\n      UP,\n      DOWN,\n      DISCONNECTED,\n      UPDATING,\n      PREPARE_FOR_MAINTENANCE,\n      ERROR_IN_MAINTENANCE,\n      MAINTENANCE,\n      ALERT,\n      REMOVED,\n      REBALANCING,\n      UNKNOWN;\n\n      public static State fromValue(String value) {\n         try {\n            return valueOf(UPPER_CAMEL.to(UPPER_UNDERSCORE, value));\n         } catch (IllegalArgumentException e) {\n            return UNKNOWN;\n         }\n      }\n\n      @Override\n      public String toString() {\n         return UPPER_UNDERSCORE.to(UPPER_CAMEL, name());\n      }\n   }\n\n   public static enum Type {\n      STORAGE,\n      ROUTING,\n      SECONDARY_STORAGE,\n      SECONDARY_STORAGE_CMD_EXECUTOR,\n      CONSOLE_PROXY,\n      EXTERNAL_FIREWALL,\n      EXTERNAL_LOAD_BALANCER,\n      PXE_SERVER,\n      TRAFFIC_MONITOR,\n      EXTERNAL_DHCP,\n      SECONDARY_STORAGE_VM,\n      LOCAL_SECONDARY_STORAGE,\n      UNKNOWN;\n\n      public static Type fromValue(String value) {\n         try {\n            if (value.equals(\"SecondaryStorageVM\")) {\n               return SECONDARY_STORAGE_VM;\n            }\n            return valueOf(UPPER_CAMEL.to(UPPER_UNDERSCORE, value));\n\n         } catch (IllegalArgumentException e) {\n            return UNKNOWN;\n         }\n      }\n\n      @Override\n      public String toString() {\n         if (this == SECONDARY_STORAGE_VM) {\n            return \"SecondaryStorageVM\"; // note the inconsistency in VM naming\n         }\n         return UPPER_UNDERSCORE.to(UPPER_CAMEL, name());\n      }\n   }\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromHost(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String id;\n      protected AllocationState allocationState;\n      protected int averageLoad;\n      protected String capabilities;\n      protected String clusterId;\n      protected String clusterName;\n      protected Host.ClusterType clusterType;\n      protected String cpuAllocated;\n      protected int cpuNumber;\n      protected int cpuSpeed;\n      protected String cpuUsed;\n      protected float cpuWithOverProvisioning;\n      protected Date created;\n      protected Date disconnected;\n      protected long diskSizeAllocated;\n      protected long diskSizeTotal;\n      protected String events;\n      protected boolean hasEnoughCapacity;\n      protected ImmutableSet.Builder<String> tags = ImmutableSet.<String>builder();\n      protected String hypervisor;\n      protected String ipAddress;\n      protected boolean localStorageActive;\n      protected String jobId;\n      protected AsyncJob.Status jobStatus;\n      protected Date lastPinged;\n      protected String managementServerId;\n      protected long memoryAllocated;\n      protected long memoryTotal;\n      protected long memoryUsed;\n      protected String name;\n      protected long networkKbsRead;\n      protected long networkKbsWrite;\n      protected String osCategoryId;\n      protected String osCategoryName;\n      protected String podId;\n      protected String podName;\n      protected Date removed;\n      protected Host.State state;\n      protected Host.Type type;\n      protected String version;\n      protected String zoneId;\n      protected String zoneName;\n\n      /**\n       * @see Host#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see Host#getAllocationState()\n       */\n      public T allocationState(AllocationState allocationState) {\n         this.allocationState = allocationState;\n         return self();\n      }\n\n      /**\n       * @see Host#getAverageLoad()\n       */\n      public T averageLoad(int averageLoad) {\n         this.averageLoad = averageLoad;\n         return self();\n      }\n\n      /**\n       * @see Host#getCapabilities()\n       */\n      public T capabilities(String capabilities) {\n         this.capabilities = capabilities;\n         return self();\n      }\n\n      /**\n       * @see Host#getClusterId()\n       */\n      public T clusterId(String clusterId) {\n         this.clusterId = clusterId;\n         return self();\n      }\n\n      /**\n       * @see Host#getClusterName()\n       */\n      public T clusterName(String clusterName) {\n         this.clusterName = clusterName;\n         return self();\n      }\n\n      /**\n       * @see Host#getClusterType()\n       */\n      public T clusterType(Host.ClusterType clusterType) {\n         this.clusterType = clusterType;\n         return self();\n      }\n\n      /**\n       * @see Host#getCpuAllocated()\n       */\n      public T cpuAllocated(String cpuAllocated) {\n         this.cpuAllocated = cpuAllocated;\n         return self();\n      }\n\n      /**\n       * @see Host#getCpuNumber()\n       */\n      public T cpuNumber(int cpuNumber) {\n         this.cpuNumber = cpuNumber;\n         return self();\n      }\n\n      /**\n       * @see Host#getCpuSpeed()\n       */\n      public T cpuSpeed(int cpuSpeed) {\n         this.cpuSpeed = cpuSpeed;\n         return self();\n      }\n\n      /**\n       * @see Host#getCpuUsed()\n       */\n      public T cpuUsed(String cpuUsed) {\n         this.cpuUsed = cpuUsed;\n         return self();\n      }\n\n      /**\n       * @see Host#getCpuWithOverProvisioning()\n       */\n      public T cpuWithOverProvisioning(float cpuWithOverProvisioning) {\n         this.cpuWithOverProvisioning = cpuWithOverProvisioning;\n         return self();\n      }\n\n      /**\n       * @see Host#getCreated()\n       */\n      public T created(Date created) {\n         this.created = created;\n         return self();\n      }\n\n      /**\n       * @see Host#getDisconnected()\n       */\n      public T disconnected(Date disconnected) {\n         this.disconnected = disconnected;\n         return self();\n      }\n\n      /**\n       * @see Host#getDiskSizeAllocated()\n       */\n      public T diskSizeAllocated(long diskSizeAllocated) {\n         this.diskSizeAllocated = diskSizeAllocated;\n         return self();\n      }\n\n      /**\n       * @see Host#getDiskSizeTotal()\n       */\n      public T diskSizeTotal(long diskSizeTotal) {\n         this.diskSizeTotal = diskSizeTotal;\n         return self();\n      }\n\n      /**\n       * @see Host#getEvents()\n       */\n      public T events(String events) {\n         this.events = events;\n         return self();\n      }\n\n      /**\n       * @see Host#isHasEnoughCapacity()\n       */\n      public T hasEnoughCapacity(boolean hasEnoughCapacity) {\n         this.hasEnoughCapacity = hasEnoughCapacity;\n         return self();\n      }\n\n      /**\n       * @see Host#getTags()\n       */\n      public T tags(Iterable<String> tags) {\n         this.tags = ImmutableSet.<String>builder().addAll(tags);\n         return self();\n      }\n      \n      /**\n       * @see Host#getTags()\n       */\n      public T tag(String tag) {\n         this.tags.add(tag);\n         return self();\n      }\n      \n      /**\n       * @see Host#getHypervisor()\n       */\n      public T hypervisor(String hypervisor) {\n         this.hypervisor = hypervisor;\n         return self();\n      }\n\n      /**\n       * @see Host#getIpAddress()\n       */\n      public T ipAddress(String ipAddress) {\n         this.ipAddress = ipAddress;\n         return self();\n      }\n\n      /**\n       * @see Host#isLocalStorageActive()\n       */\n      public T localStorageActive(boolean localStorageActive) {\n         this.localStorageActive = localStorageActive;\n         return self();\n      }\n\n      /**\n       * @see Host#getJobId()\n       */\n      public T jobId(String jobId) {\n         this.jobId = jobId;\n         return self();\n      }\n\n      /**\n       * @see Host#getJobStatus()\n       */\n      public T jobStatus(AsyncJob.Status jobStatus) {\n         this.jobStatus = jobStatus;\n         return self();\n      }\n\n      /**\n       * @see Host#getLastPinged()\n       */\n      public T lastPinged(Date lastPinged) {\n         this.lastPinged = lastPinged;\n         return self();\n      }\n\n      /**\n       * @see Host#getManagementServerId()\n       */\n      public T managementServerId(String managementServerId) {\n         this.managementServerId = managementServerId;\n         return self();\n      }\n\n      /**\n       * @see Host#getMemoryAllocated()\n       */\n      public T memoryAllocated(long memoryAllocated) {\n         this.memoryAllocated = memoryAllocated;\n         return self();\n      }\n\n      /**\n       * @see Host#getMemoryTotal()\n       */\n      public T memoryTotal(long memoryTotal) {\n         this.memoryTotal = memoryTotal;\n         return self();\n      }\n\n      /**\n       * @see Host#getMemoryUsed()\n       */\n      public T memoryUsed(long memoryUsed) {\n         this.memoryUsed = memoryUsed;\n         return self();\n      }\n\n      /**\n       * @see Host#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /**\n       * @see Host#getNetworkKbsRead()\n       */\n      public T networkKbsRead(long networkKbsRead) {\n         this.networkKbsRead = networkKbsRead;\n         return self();\n      }\n\n      /**\n       * @see Host#getNetworkKbsWrite()\n       */\n      public T networkKbsWrite(long networkKbsWrite) {\n         this.networkKbsWrite = networkKbsWrite;\n         return self();\n      }\n\n      /**\n       * @see Host#getOsCategoryId()\n       */\n      public T osCategoryId(String osCategoryId) {\n         this.osCategoryId = osCategoryId;\n         return self();\n      }\n\n      /**\n       * @see Host#getOsCategoryName()\n       */\n      public T osCategoryName(String osCategoryName) {\n         this.osCategoryName = osCategoryName;\n         return self();\n      }\n\n      /**\n       * @see Host#getPodId()\n       */\n      public T podId(String podId) {\n         this.podId = podId;\n         return self();\n      }\n\n      /**\n       * @see Host#getPodName()\n       */\n      public T podName(String podName) {\n         this.podName = podName;\n         return self();\n      }\n\n      /**\n       * @see Host#getRemoved()\n       */\n      public T removed(Date removed) {\n         this.removed = removed;\n         return self();\n      }\n\n      /**\n       * @see Host#getState()\n       */\n      public T state(Host.State state) {\n         this.state = state;\n         return self();\n      }\n\n      /**\n       * @see Host#getType()\n       */\n      public T type(Host.Type type) {\n         this.type = type;\n         return self();\n      }\n\n      /**\n       * @see Host#getVersion()\n       */\n      public T version(String version) {\n         this.version = version;\n         return self();\n      }\n\n      /**\n       * @see Host#getZoneId()\n       */\n      public T zoneId(String zoneId) {\n         this.zoneId = zoneId;\n         return self();\n      }\n\n      /**\n       * @see Host#getZoneName()\n       */\n      public T zoneName(String zoneName) {\n         this.zoneName = zoneName;\n         return self();\n      }\n\n\n      public Host build() {\n         return new Host(id, allocationState, averageLoad, capabilities, clusterId, clusterName, clusterType, cpuAllocated, cpuNumber, cpuSpeed, cpuUsed, cpuWithOverProvisioning, created, disconnected, diskSizeAllocated, diskSizeTotal, events, hasEnoughCapacity, tags.build(), hypervisor, ipAddress, localStorageActive, jobId, jobStatus, lastPinged, managementServerId, memoryAllocated, memoryTotal, memoryUsed, name, networkKbsRead, networkKbsWrite, osCategoryId, osCategoryName, podId, podName, removed, state, type, version, zoneId, zoneName);\n      }\n\n      public T fromHost(Host in) {\n         return this\n               .id(in.getId())\n               .allocationState(in.getAllocationState())\n               .averageLoad(in.getAverageLoad())\n               .capabilities(in.getCapabilities())\n               .clusterId(in.getClusterId())\n               .clusterName(in.getClusterName())\n               .clusterType(in.getClusterType())\n               .cpuAllocated(in.getCpuAllocated())\n               .cpuNumber(in.getCpuNumber())\n               .cpuSpeed(in.getCpuSpeed())\n               .cpuUsed(in.getCpuUsed())\n               .cpuWithOverProvisioning(in.getCpuWithOverProvisioning())\n               .created(in.getCreated())\n               .disconnected(in.getDisconnected())\n               .diskSizeAllocated(in.getDiskSizeAllocated())\n               .diskSizeTotal(in.getDiskSizeTotal())\n               .events(in.getEvents())\n               .hasEnoughCapacity(in.isHasEnoughCapacity())\n               .tags(in.getTags())\n               .hypervisor(in.getHypervisor())\n               .ipAddress(in.getIpAddress())\n               .localStorageActive(in.isLocalStorageActive())\n               .jobId(in.getJobId())\n               .jobStatus(in.getJobStatus())\n               .lastPinged(in.getLastPinged())\n               .managementServerId(in.getManagementServerId())\n               .memoryAllocated(in.getMemoryAllocated())\n               .memoryTotal(in.getMemoryTotal())\n               .memoryUsed(in.getMemoryUsed())\n               .name(in.getName())\n               .networkKbsRead(in.getNetworkKbsRead())\n               .networkKbsWrite(in.getNetworkKbsWrite())\n               .osCategoryId(in.getOsCategoryId())\n               .osCategoryName(in.getOsCategoryName())\n               .podId(in.getPodId())\n               .podName(in.getPodName())\n               .removed(in.getRemoved())\n               .state(in.getState())\n               .type(in.getType())\n               .version(in.getVersion())\n               .zoneId(in.getZoneId())\n               .zoneName(in.getZoneName());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final AllocationState allocationState;\n   private final int averageLoad;\n   private final String capabilities;\n   private final String clusterId;\n   private final String clusterName;\n   private final Host.ClusterType clusterType;\n   private final String cpuAllocated;\n   private final int cpuNumber;\n   private final int cpuSpeed;\n   private final String cpuUsed;\n   private final float cpuWithOverProvisioning;\n   private final Date created;\n   private final Date disconnected;\n   private final long diskSizeAllocated;\n   private final long diskSizeTotal;\n   private final String events;\n   private final boolean hasEnoughCapacity;\n   private final Set<String> tags;\n   private final String hypervisor;\n   private final String ipAddress;\n   private final boolean localStorageActive;\n   private final String jobId;\n   private final AsyncJob.Status jobStatus;\n   private final Date lastPinged;\n   private final String managementServerId;\n   private final long memoryAllocated;\n   private final long memoryTotal;\n   private final long memoryUsed;\n   private final String name;\n   private final long networkKbsRead;\n   private final long networkKbsWrite;\n   private final String osCategoryId;\n   private final String osCategoryName;\n   private final String podId;\n   private final String podName;\n   private final Date removed;\n   private final Host.State state;\n   private final Host.Type type;\n   private final String version;\n   private final String zoneId;\n   private final String zoneName;\n\n   @ConstructorProperties({\n         \"id\", \"allocationstate\", \"averageload\", \"capabilities\", \"clusterid\", \"clustername\", \"clustertype\", \"cpuallocated\", \"cpunumber\", \"cpuspeed\", \"cpuused\", \"cpuwithoverprovisioning\", \"created\", \"disconnected\", \"disksizeallocated\", \"disksizetotal\", \"events\", \"hasenoughcapacity\", \"hosttags\", \"hypervisor\", \"ipaddress\", \"islocalstorageactive\", \"jobid\", \"jobstatus\", \"lastpinged\", \"managementserverid\", \"memoryallocated\", \"memorytotal\", \"memoryused\", \"name\", \"networkkbsread\", \"networkkbswrite\", \"oscategoryid\", \"oscategoryname\", \"podid\", \"podname\", \"removed\", \"state\", \"type\", \"version\", \"zoneid\", \"zonename\"\n   })\n   protected Host(String id, @Nullable AllocationState allocationState, int averageLoad, @Nullable String capabilities,\n                  @Nullable String clusterId, @Nullable String clusterName, @Nullable Host.ClusterType clusterType,\n                  @Nullable String cpuAllocated, int cpuNumber, int cpuSpeed, @Nullable String cpuUsed,\n                  float cpuWithOverProvisioning, @Nullable Date created, @Nullable Date disconnected, long diskSizeAllocated,\n                  long diskSizeTotal, @Nullable String events, boolean hasEnoughCapacity, @Nullable Iterable<String> tags,\n                  @Nullable String hypervisor, @Nullable String ipAddress, boolean localStorageActive, @Nullable String jobId,\n                  @Nullable AsyncJob.Status jobStatus, @Nullable Date lastPinged, @Nullable String managementServerId,\n                  long memoryAllocated, long memoryTotal, long memoryUsed, @Nullable String name, long networkKbsRead, long networkKbsWrite,\n                  @Nullable String osCategoryId, @Nullable String osCategoryName, @Nullable String podId, @Nullable String podName,\n                  @Nullable Date removed, @Nullable Host.State state, @Nullable Host.Type type, @Nullable String version, @Nullable String zoneId,\n                  @Nullable String zoneName) {\n      this.id = checkNotNull(id, \"id\");\n      this.allocationState = allocationState;\n      this.averageLoad = averageLoad;\n      this.capabilities = capabilities;\n      this.clusterId = clusterId;\n      this.clusterName = clusterName;\n      this.clusterType = clusterType;\n      this.cpuAllocated = cpuAllocated;\n      this.cpuNumber = cpuNumber;\n      this.cpuSpeed = cpuSpeed;\n      this.cpuUsed = cpuUsed;\n      this.cpuWithOverProvisioning = cpuWithOverProvisioning;\n      this.created = created;\n      this.disconnected = disconnected;\n      this.diskSizeAllocated = diskSizeAllocated;\n      this.diskSizeTotal = diskSizeTotal;\n      this.events = events;\n      this.hasEnoughCapacity = hasEnoughCapacity;\n      this.tags = tags != null ? ImmutableSet.copyOf(tags) : ImmutableSet.<String> of();\n      this.hypervisor = hypervisor;\n      this.ipAddress = ipAddress;\n      this.localStorageActive = localStorageActive;\n      this.jobId = jobId;\n      this.jobStatus = jobStatus;\n      this.lastPinged = lastPinged;\n      this.managementServerId = managementServerId;\n      this.memoryAllocated = memoryAllocated;\n      this.memoryTotal = memoryTotal;\n      this.memoryUsed = memoryUsed;\n      this.name = name;\n      this.networkKbsRead = networkKbsRead;\n      this.networkKbsWrite = networkKbsWrite;\n      this.osCategoryId = osCategoryId;\n      this.osCategoryName = osCategoryName;\n      this.podId = podId;\n      this.podName = podName;\n      this.removed = removed;\n      this.state = state;\n      this.type = type;\n      this.version = version;\n      this.zoneId = zoneId;\n      this.zoneName = zoneName;\n   }\n\n   public String getId() {\n      return this.id;\n   }\n\n   @Nullable\n   public AllocationState getAllocationState() {\n      return this.allocationState;\n   }\n\n   public int getAverageLoad() {\n      return this.averageLoad;\n   }\n\n   @Nullable\n   public String getCapabilities() {\n      return this.capabilities;\n   }\n\n   @Nullable\n   public String getClusterId() {\n      return this.clusterId;\n   }\n\n   @Nullable\n   public String getClusterName() {\n      return this.clusterName;\n   }\n\n   @Nullable\n   public Host.ClusterType getClusterType() {\n      return this.clusterType;\n   }\n\n   @Nullable\n   public String getCpuAllocated() {\n      return this.cpuAllocated;\n   }\n\n   public int getCpuNumber() {\n      return this.cpuNumber;\n   }\n\n   public int getCpuSpeed() {\n      return this.cpuSpeed;\n   }\n\n   @Nullable\n   public String getCpuUsed() {\n      return this.cpuUsed;\n   }\n\n   public float getCpuWithOverProvisioning() {\n      return this.cpuWithOverProvisioning;\n   }\n\n   @Nullable\n   public Date getCreated() {\n      return this.created;\n   }\n\n   @Nullable\n   public Date getDisconnected() {\n      return this.disconnected;\n   }\n\n   public long getDiskSizeAllocated() {\n      return this.diskSizeAllocated;\n   }\n\n   public long getDiskSizeTotal() {\n      return this.diskSizeTotal;\n   }\n\n   @Nullable\n   public String getEvents() {\n      return this.events;\n   }\n\n   public boolean isHasEnoughCapacity() {\n      return this.hasEnoughCapacity;\n   }\n\n   /**\n    * @return the tags for the host\n    */\n   public Set<String> getTags() {\n      return this.tags;\n   }\n\n\n   @Nullable\n   public String getHypervisor() {\n      return this.hypervisor;\n   }\n\n   @Nullable\n   public String getIpAddress() {\n      return this.ipAddress;\n   }\n\n   public boolean isLocalStorageActive() {\n      return this.localStorageActive;\n   }\n\n   @Nullable\n   public String getJobId() {\n      return this.jobId;\n   }\n\n   @Nullable\n   public AsyncJob.Status getJobStatus() {\n      return this.jobStatus;\n   }\n\n   @Nullable\n   public Date getLastPinged() {\n      return this.lastPinged;\n   }\n\n   @Nullable\n   public String getManagementServerId() {\n      return this.managementServerId;\n   }\n\n   public long getMemoryAllocated() {\n      return this.memoryAllocated;\n   }\n\n   public long getMemoryTotal() {\n      return this.memoryTotal;\n   }\n\n   public long getMemoryUsed() {\n      return this.memoryUsed;\n   }\n\n   @Nullable\n   public String getName() {\n      return this.name;\n   }\n\n   public long getNetworkKbsRead() {\n      return this.networkKbsRead;\n   }\n\n   public long getNetworkKbsWrite() {\n      return this.networkKbsWrite;\n   }\n\n   @Nullable\n   public String getOsCategoryId() {\n      return this.osCategoryId;\n   }\n\n   @Nullable\n   public String getOsCategoryName() {\n      return this.osCategoryName;\n   }\n\n   @Nullable\n   public String getPodId() {\n      return this.podId;\n   }\n\n   @Nullable\n   public String getPodName() {\n      return this.podName;\n   }\n\n   @Nullable\n   public Date getRemoved() {\n      return this.removed;\n   }\n\n   @Nullable\n   public Host.State getState() {\n      return this.state;\n   }\n\n   @Nullable\n   public Host.Type getType() {\n      return this.type;\n   }\n\n   @Nullable\n   public String getVersion() {\n      return this.version;\n   }\n\n   @Nullable\n   public String getZoneId() {\n      return this.zoneId;\n   }\n\n   @Nullable\n   public String getZoneName() {\n      return this.zoneName;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, allocationState, averageLoad, capabilities, clusterId, clusterName, clusterType, cpuAllocated, cpuNumber, cpuSpeed, cpuUsed, cpuWithOverProvisioning, created, disconnected, diskSizeAllocated, diskSizeTotal, events, hasEnoughCapacity, tags, hypervisor, ipAddress, localStorageActive, jobId, jobStatus, lastPinged, managementServerId, memoryAllocated, memoryTotal, memoryUsed, name, networkKbsRead, networkKbsWrite, osCategoryId, osCategoryName, podId, podName, removed, state, type, version, zoneId, zoneName);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Host that = Host.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n            && Objects.equal(this.allocationState, that.allocationState)\n            && Objects.equal(this.averageLoad, that.averageLoad)\n            && Objects.equal(this.capabilities, that.capabilities)\n            && Objects.equal(this.clusterId, that.clusterId)\n            && Objects.equal(this.clusterName, that.clusterName)\n            && Objects.equal(this.clusterType, that.clusterType)\n            && Objects.equal(this.cpuAllocated, that.cpuAllocated)\n            && Objects.equal(this.cpuNumber, that.cpuNumber)\n            && Objects.equal(this.cpuSpeed, that.cpuSpeed)\n            && Objects.equal(this.cpuUsed, that.cpuUsed)\n            && Objects.equal(this.cpuWithOverProvisioning, that.cpuWithOverProvisioning)\n            && Objects.equal(this.created, that.created)\n            && Objects.equal(this.disconnected, that.disconnected)\n            && Objects.equal(this.diskSizeAllocated, that.diskSizeAllocated)\n            && Objects.equal(this.diskSizeTotal, that.diskSizeTotal)\n            && Objects.equal(this.events, that.events)\n            && Objects.equal(this.hasEnoughCapacity, that.hasEnoughCapacity)\n            && Objects.equal(this.tags, that.tags)\n            && Objects.equal(this.hypervisor, that.hypervisor)\n            && Objects.equal(this.ipAddress, that.ipAddress)\n            && Objects.equal(this.localStorageActive, that.localStorageActive)\n            && Objects.equal(this.jobId, that.jobId)\n            && Objects.equal(this.jobStatus, that.jobStatus)\n            && Objects.equal(this.lastPinged, that.lastPinged)\n            && Objects.equal(this.managementServerId, that.managementServerId)\n            && Objects.equal(this.memoryAllocated, that.memoryAllocated)\n            && Objects.equal(this.memoryTotal, that.memoryTotal)\n            && Objects.equal(this.memoryUsed, that.memoryUsed)\n            && Objects.equal(this.name, that.name)\n            && Objects.equal(this.networkKbsRead, that.networkKbsRead)\n            && Objects.equal(this.networkKbsWrite, that.networkKbsWrite)\n            && Objects.equal(this.osCategoryId, that.osCategoryId)\n            && Objects.equal(this.osCategoryName, that.osCategoryName)\n            && Objects.equal(this.podId, that.podId)\n            && Objects.equal(this.podName, that.podName)\n            && Objects.equal(this.removed, that.removed)\n            && Objects.equal(this.state, that.state)\n            && Objects.equal(this.type, that.type)\n            && Objects.equal(this.version, that.version)\n            && Objects.equal(this.zoneId, that.zoneId)\n            && Objects.equal(this.zoneName, that.zoneName);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"allocationState\", allocationState).add(\"averageLoad\", averageLoad)\n            .add(\"capabilities\", capabilities).add(\"clusterId\", clusterId).add(\"clusterName\", clusterName)\n            .add(\"clusterType\", clusterType).add(\"cpuAllocated\", cpuAllocated).add(\"cpuNumber\", cpuNumber)\n            .add(\"cpuSpeed\", cpuSpeed).add(\"cpuUsed\", cpuUsed).add(\"cpuWithOverProvisioning\", cpuWithOverProvisioning)\n            .add(\"created\", created).add(\"disconnected\", disconnected).add(\"diskSizeAllocated\", diskSizeAllocated)\n            .add(\"diskSizeTotal\", diskSizeTotal).add(\"events\", events).add(\"hasEnoughCapacity\", hasEnoughCapacity)\n            .add(\"tags\", tags).add(\"hypervisor\", hypervisor).add(\"ipAddress\", ipAddress)\n            .add(\"localStorageActive\", localStorageActive).add(\"jobId\", jobId).add(\"jobStatus\", jobStatus)\n            .add(\"lastPinged\", lastPinged).add(\"managementServerId\", managementServerId).add(\"memoryAllocated\", memoryAllocated)\n            .add(\"memoryTotal\", memoryTotal).add(\"memoryUsed\", memoryUsed).add(\"name\", name).add(\"networkKbsRead\", networkKbsRead)\n            .add(\"networkKbsWrite\", networkKbsWrite).add(\"osCategoryId\", osCategoryId).add(\"osCategoryName\", osCategoryName)\n            .add(\"podId\", podId).add(\"podName\", podName).add(\"removed\", removed).add(\"state\", state).add(\"type\", type)\n            .add(\"version\", version).add(\"zoneId\", zoneId).add(\"zoneName\", zoneName);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int compareTo(Host other) {\n      return this.getId().compareTo(other.getId());\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/IPForwardingRule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Class IPForwardingRule\n */\npublic class IPForwardingRule implements Comparable<IPForwardingRule> {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromIPForwardingRule(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String id;\n      protected String IPAddress;\n      protected String IPAddressId;\n      protected int startPort;\n      protected String protocol;\n      protected int endPort;\n      protected String state;\n      protected String virtualMachineDisplayName;\n      protected String virtualMachineId;\n      protected String virtualMachineName;\n      protected int publicPort;\n      protected Set<String> CIDRs = ImmutableSet.of();\n      protected int privateEndPort;\n      protected int publicEndPort;\n      protected Set<Tag> tags = ImmutableSet.of();\n\n      /**\n       * @see IPForwardingRule#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see IPForwardingRule#getIPAddress()\n       */\n      public T IPAddress(String IPAddress) {\n         this.IPAddress = IPAddress;\n         return self();\n      }\n\n      /**\n       * @see IPForwardingRule#getIPAddressId()\n       */\n      public T IPAddressId(String IPAddressId) {\n         this.IPAddressId = IPAddressId;\n         return self();\n      }\n\n      /**\n       * @see IPForwardingRule#getStartPort()\n       */\n      public T startPort(int startPort) {\n         this.startPort = startPort;\n         return self();\n      }\n\n      /**\n       * @see IPForwardingRule#getProtocol()\n       */\n      public T protocol(String protocol) {\n         this.protocol = protocol;\n         return self();\n      }\n\n      /**\n       * @see IPForwardingRule#getEndPort()\n       */\n      public T endPort(int endPort) {\n         this.endPort = endPort;\n         return self();\n      }\n\n      /**\n       * @see IPForwardingRule#getState()\n       */\n      public T state(String state) {\n         this.state = state;\n         return self();\n      }\n\n      /**\n       * @see IPForwardingRule#getVirtualMachineDisplayName()\n       */\n      public T virtualMachineDisplayName(String virtualMachineDisplayName) {\n         this.virtualMachineDisplayName = virtualMachineDisplayName;\n         return self();\n      }\n\n      /**\n       * @see IPForwardingRule#getVirtualMachineId()\n       */\n      public T virtualMachineId(String virtualMachineId) {\n         this.virtualMachineId = virtualMachineId;\n         return self();\n      }\n\n      /**\n       * @see IPForwardingRule#getVirtualMachineName()\n       */\n      public T virtualMachineName(String virtualMachineName) {\n         this.virtualMachineName = virtualMachineName;\n         return self();\n      }\n\n      /**\n       * @see IPForwardingRule#getPublicPort()\n       */\n      public T publicPort(int publicPort) {\n         this.publicPort = publicPort;\n         return self();\n      }\n\n      /**\n       * @see IPForwardingRule#getCIDRs()\n       */\n      public T CIDRs(Set<String> CIDRs) {\n         this.CIDRs = ImmutableSet.copyOf(checkNotNull(CIDRs, \"CIDRs\"));\n         return self();\n      }\n\n      public T CIDRs(String... in) {\n         return CIDRs(ImmutableSet.copyOf(in));\n      }\n\n      /**\n       * @see IPForwardingRule#getPrivateEndPort()\n       */\n      public T privateEndPort(int privateEndPort) {\n         this.privateEndPort = privateEndPort;\n         return self();\n      }\n\n      /**\n       * @see IPForwardingRule#getPublicEndPort()\n       */\n      public T publicEndPort(int publicEndPort) {\n         this.publicEndPort = publicEndPort;\n         return self();\n      }\n\n      /**\n       * @see IPForwardingRule#getTags()\n       */\n      public T tags(Set<Tag> tags) {\n         this.tags = ImmutableSet.copyOf(checkNotNull(tags, \"tags\"));\n         return self();\n      }\n\n      public T tags(Tag... in) {\n         return tags(ImmutableSet.copyOf(in));\n      }\n\n      public IPForwardingRule build() {\n         return new IPForwardingRule(id, IPAddress, IPAddressId, startPort, protocol, endPort, state, virtualMachineDisplayName,\n               virtualMachineId, virtualMachineName, publicPort, CIDRs, privateEndPort, publicEndPort, tags);\n      }\n\n      public T fromIPForwardingRule(IPForwardingRule in) {\n         return this\n               .id(in.getId())\n               .IPAddress(in.getIPAddress())\n               .IPAddressId(in.getIPAddressId())\n               .startPort(in.getStartPort())\n               .protocol(in.getProtocol())\n               .endPort(in.getEndPort())\n               .state(in.getState())\n               .virtualMachineDisplayName(in.getVirtualMachineDisplayName())\n               .virtualMachineId(in.getVirtualMachineId())\n               .virtualMachineName(in.getVirtualMachineName())\n               .publicPort(in.getPublicPort())\n               .CIDRs(in.getCIDRs())\n               .privateEndPort(in.getPrivateEndPort())\n               .publicEndPort(in.getPublicEndPort())\n               .tags(in.getTags());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final String IPAddress;\n   private final String IPAddressId;\n   private final int startPort;\n   private final String protocol;\n   private final int endPort;\n   private final String state;\n   private final String virtualMachineDisplayName;\n   private final String virtualMachineId;\n   private final String virtualMachineName;\n   private final int publicPort;\n   private final Set<String> CIDRs;\n   private final int privateEndPort;\n   private final int publicEndPort;\n   private final Set<Tag> tags;\n\n   @ConstructorProperties({\n         \"id\", \"ipaddress\", \"ipaddressid\", \"startport\", \"protocol\", \"endport\", \"state\", \"virtualmachinedisplayname\",\n         \"virtualmachineid\", \"virtualmachinename\", \"publicport\", \"cidrlist\", \"privateendport\", \"publicendport\", \"tags\"\n   })\n   protected IPForwardingRule(String id, String IPAddress, String IPAddressId, int startPort, @Nullable String protocol,\n                              int endPort, @Nullable String state, @Nullable String virtualMachineDisplayName,\n                              @Nullable String virtualMachineId, @Nullable String virtualMachineName, int publicPort,\n                              @Nullable Set<String> CIDRs, int privateEndPort, int publicEndPort,\n                              @Nullable Set<Tag> tags) {\n      this.id = checkNotNull(id, \"id\");\n      this.IPAddress = IPAddress;\n      this.IPAddressId = IPAddressId;\n      this.startPort = startPort;\n      this.protocol = protocol;\n      this.endPort = endPort;\n      this.state = state;\n      this.virtualMachineDisplayName = virtualMachineDisplayName;\n      this.virtualMachineId = virtualMachineId;\n      this.virtualMachineName = virtualMachineName;\n      this.publicPort = publicPort;\n      this.CIDRs = CIDRs == null ? ImmutableSet.<String>of() : ImmutableSet.copyOf(CIDRs);\n      this.privateEndPort = privateEndPort;\n      this.publicEndPort = publicEndPort;\n      this.tags = tags == null ? ImmutableSet.<Tag>of() : ImmutableSet.copyOf(tags);\n   }\n\n   /**\n    * @return the ID of the ip forwarding rule\n    */\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * @return the public ip address for the ip forwarding rule\n    */\n   @Nullable\n   public String getIPAddress() {\n      return this.IPAddress;\n   }\n\n   /**\n    * @return the public ip address id for the ip forwarding rule\n    */\n   @Nullable\n   public String getIPAddressId() {\n      return this.IPAddressId;\n   }\n\n   /**\n    * @return the private port for the ip forwarding rule\n    */\n   public int getStartPort() {\n      return this.startPort;\n   }\n\n   /**\n    * @return the protocol of the ip forwarding rule\n    */\n   @Nullable\n   public String getProtocol() {\n      return this.protocol;\n   }\n\n   /**\n    * @return the public port for the ip forwarding rule\n    */\n   public int getEndPort() {\n      return this.endPort;\n   }\n\n   /**\n    * @return the state of the rule\n    */\n   @Nullable\n   public String getState() {\n      return this.state;\n   }\n\n   /**\n    * @return the VM display name for the ip forwarding rule\n    */\n   @Nullable\n   public String getVirtualMachineDisplayName() {\n      return this.virtualMachineDisplayName;\n   }\n\n   /**\n    * @return the VM ID for the ip forwarding rule\n    */\n   @Nullable\n   public String getVirtualMachineId() {\n      return this.virtualMachineId;\n   }\n\n   /**\n    * @return the VM name for the ip forwarding rule\n    */\n   @Nullable\n   public String getVirtualMachineName() {\n      return this.virtualMachineName;\n   }\n\n   /**\n    * @return the starting port of port forwarding rule's public port range\n    */\n   public int getPublicPort() {\n      return this.publicPort;\n   }\n\n   /**\n    * @return the cidr list to forward traffic from\n    */\n   public Set<String> getCIDRs() {\n      return this.CIDRs;\n   }\n\n   /**\n    * @return the ending port of port forwarding rule's private port range\n    */\n   public int getPrivateEndPort() {\n      return this.privateEndPort;\n   }\n\n   /**\n    * @return the ending port of port forwarding rule's private port range\n    */\n   public int getPublicEndPort() {\n      return this.publicEndPort;\n   }\n\n   /**\n    * @return Tags on this rule\n    */\n   @Nullable\n   public Set<Tag> getTags() {\n      return this.tags;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, IPAddress, IPAddressId, startPort, protocol, endPort, state, virtualMachineDisplayName, virtualMachineId, virtualMachineName, publicPort, CIDRs, privateEndPort, publicEndPort, tags);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      IPForwardingRule that = IPForwardingRule.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n            && Objects.equal(this.IPAddress, that.IPAddress)\n            && Objects.equal(this.IPAddressId, that.IPAddressId)\n            && Objects.equal(this.startPort, that.startPort)\n            && Objects.equal(this.protocol, that.protocol)\n            && Objects.equal(this.endPort, that.endPort)\n            && Objects.equal(this.state, that.state)\n            && Objects.equal(this.virtualMachineDisplayName, that.virtualMachineDisplayName)\n            && Objects.equal(this.virtualMachineId, that.virtualMachineId)\n            && Objects.equal(this.virtualMachineName, that.virtualMachineName)\n            && Objects.equal(this.publicPort, that.publicPort)\n            && Objects.equal(this.CIDRs, that.CIDRs)\n            && Objects.equal(this.privateEndPort, that.privateEndPort)\n            && Objects.equal(this.publicEndPort, that.publicEndPort)\n            && Objects.equal(this.tags, that.tags);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"IPAddress\", IPAddress).add(\"IPAddressId\", IPAddressId).add(\"startPort\", startPort)\n            .add(\"protocol\", protocol).add(\"endPort\", endPort).add(\"state\", state).add(\"virtualMachineDisplayName\", virtualMachineDisplayName)\n            .add(\"virtualMachineId\", virtualMachineId).add(\"virtualMachineName\", virtualMachineName).add(\"publicPort\", publicPort)\n            .add(\"CIDRs\", CIDRs).add(\"privateEndPort\", privateEndPort).add(\"publicEndPort\", publicEndPort)\n            .add(\"tags\", tags);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int compareTo(IPForwardingRule o) {\n      return id.compareTo(o.getId());\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/ISO.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\nimport java.util.Set;\n\nimport com.google.common.collect.ImmutableSet;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Class ISO\n */\npublic class ISO {\n\n   /**\n    */\n   public static enum ISOFilter {\n\n      featured, self, self_executable, executable, community, UNRECOGNIZED;\n\n      public static ISOFilter fromValue(String format) {\n         try {\n            return valueOf(checkNotNull(format, \"format\"));\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n   }\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromISO(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String id;\n      protected String account;\n      protected String accountId;\n      protected boolean bootable;\n      protected String checksum;\n      protected Date created;\n      protected boolean crossZones;\n      protected String displayText;\n      protected String domain;\n      protected String domainid;\n      protected String format;\n      protected String hostId;\n      protected String hostName;\n      protected String hypervisor;\n      protected boolean isExtractable;\n      protected boolean isFeatured;\n      protected boolean isPublic;\n      protected boolean isReady;\n      protected String jobId;\n      protected String jobStatus;\n      protected String name;\n      protected String osTypeId;\n      protected String osTypeName;\n      protected boolean passwordEnabled;\n      protected Date removed;\n      protected long size;\n      protected String sourceTemplateId;\n      protected String status;\n      protected String templateTag;\n      protected String templateType;\n      protected String zoneId;\n      protected String zoneName;\n      protected Set<Tag> tags = ImmutableSet.of();\n\n      /**\n       * @see ISO#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see ISO#getAccount()\n       */\n      public T account(String account) {\n         this.account = account;\n         return self();\n      }\n\n      /**\n       * @see ISO#getAccountId()\n       */\n      public T accountId(String accountId) {\n         this.accountId = accountId;\n         return self();\n      }\n\n      /**\n       * @see ISO#isBootable()\n       */\n      public T bootable(boolean bootable) {\n         this.bootable = bootable;\n         return self();\n      }\n\n      /**\n       * @see ISO#getChecksum()\n       */\n      public T checksum(String checksum) {\n         this.checksum = checksum;\n         return self();\n      }\n\n      /**\n       * @see ISO#getCreated()\n       */\n      public T created(Date created) {\n         this.created = created;\n         return self();\n      }\n\n      /**\n       * @see ISO#isCrossZones()\n       */\n      public T crossZones(boolean crossZones) {\n         this.crossZones = crossZones;\n         return self();\n      }\n\n      /**\n       * @see ISO#getDisplayText()\n       */\n      public T displayText(String displayText) {\n         this.displayText = displayText;\n         return self();\n      }\n\n      /**\n       * @see ISO#getDomain()\n       */\n      public T domain(String domain) {\n         this.domain = domain;\n         return self();\n      }\n\n      /**\n       * @see ISO#getDomainid()\n       */\n      public T domainid(String domainid) {\n         this.domainid = domainid;\n         return self();\n      }\n\n      /**\n       * @see ISO#getFormat()\n       */\n      public T format(String format) {\n         this.format = format;\n         return self();\n      }\n\n      /**\n       * @see ISO#getHostId()\n       */\n      public T hostId(String hostId) {\n         this.hostId = hostId;\n         return self();\n      }\n\n      /**\n       * @see ISO#getHostName()\n       */\n      public T hostName(String hostName) {\n         this.hostName = hostName;\n         return self();\n      }\n\n      /**\n       * @see ISO#getHypervisor()\n       */\n      public T hypervisor(String hypervisor) {\n         this.hypervisor = hypervisor;\n         return self();\n      }\n\n      /**\n       * @see ISO#isExtractable()\n       */\n      public T isExtractable(boolean isExtractable) {\n         this.isExtractable = isExtractable;\n         return self();\n      }\n\n      /**\n       * @see ISO#isFeatured()\n       */\n      public T isFeatured(boolean isFeatured) {\n         this.isFeatured = isFeatured;\n         return self();\n      }\n\n      /**\n       * @see ISO#isPublic()\n       */\n      public T isPublic(boolean isPublic) {\n         this.isPublic = isPublic;\n         return self();\n      }\n\n      /**\n       * @see ISO#isReady()\n       */\n      public T isReady(boolean isReady) {\n         this.isReady = isReady;\n         return self();\n      }\n\n      /**\n       * @see ISO#getJobId()\n       */\n      public T jobId(String jobId) {\n         this.jobId = jobId;\n         return self();\n      }\n\n      /**\n       * @see ISO#getJobStatus()\n       */\n      public T jobStatus(String jobStatus) {\n         this.jobStatus = jobStatus;\n         return self();\n      }\n\n      /**\n       * @see ISO#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /**\n       * @see ISO#getOsTypeId()\n       */\n      public T osTypeId(String osTypeId) {\n         this.osTypeId = osTypeId;\n         return self();\n      }\n\n      /**\n       * @see ISO#getOsTypeName()\n       */\n      public T osTypeName(String osTypeName) {\n         this.osTypeName = osTypeName;\n         return self();\n      }\n\n      /**\n       * @see ISO#isPasswordEnabled()\n       */\n      public T passwordEnabled(boolean passwordEnabled) {\n         this.passwordEnabled = passwordEnabled;\n         return self();\n      }\n\n      /**\n       * @see ISO#getRemoved()\n       */\n      public T removed(Date removed) {\n         this.removed = removed;\n         return self();\n      }\n\n      /**\n       * @see ISO#getSize()\n       */\n      public T size(long size) {\n         this.size = size;\n         return self();\n      }\n\n      /**\n       * @see ISO#getSourceTemplateId()\n       */\n      public T sourceTemplateId(String sourceTemplateId) {\n         this.sourceTemplateId = sourceTemplateId;\n         return self();\n      }\n\n      /**\n       * @see ISO#getStatus()\n       */\n      public T status(String status) {\n         this.status = status;\n         return self();\n      }\n\n      /**\n       * @see ISO#getTemplateTag()\n       */\n      public T templateTag(String templateTag) {\n         this.templateTag = templateTag;\n         return self();\n      }\n\n      /**\n       * @see ISO#getTemplateType()\n       */\n      public T templateType(String templateType) {\n         this.templateType = templateType;\n         return self();\n      }\n\n      /**\n       * @see ISO#getZoneId()\n       */\n      public T zoneId(String zoneId) {\n         this.zoneId = zoneId;\n         return self();\n      }\n\n      /**\n       * @see ISO#getZoneName()\n       */\n      public T zoneName(String zoneName) {\n         this.zoneName = zoneName;\n         return self();\n      }\n\n      /**\n       * @see ISO#getTags()\n       */\n      public T tags(Set<Tag> tags) {\n         this.tags = ImmutableSet.copyOf(checkNotNull(tags, \"tags\"));\n         return self();\n      }\n\n      public T tags(Tag... in) {\n         return tags(ImmutableSet.copyOf(in));\n      }\n\n      public ISO build() {\n         return new ISO(id, account, accountId, bootable, checksum, created, crossZones, displayText, domain, domainid,\n               format, hostId, hostName, hypervisor, isExtractable, isFeatured, isPublic, isReady, jobId, jobStatus, name,\n               osTypeId, osTypeName, passwordEnabled, removed, size, sourceTemplateId, status, templateTag, templateType,\n               zoneId, zoneName, tags);\n      }\n\n      public T fromISO(ISO in) {\n         return this\n               .id(in.getId())\n               .account(in.getAccount())\n               .accountId(in.getAccountId())\n               .bootable(in.isBootable())\n               .checksum(in.getChecksum())\n               .created(in.getCreated())\n               .crossZones(in.isCrossZones())\n               .displayText(in.getDisplayText())\n               .domain(in.getDomain())\n               .domainid(in.getDomainid())\n               .format(in.getFormat())\n               .hostId(in.getHostId())\n               .hostName(in.getHostName())\n               .hypervisor(in.getHypervisor())\n               .isExtractable(in.isExtractable())\n               .isFeatured(in.isFeatured())\n               .isPublic(in.isPublic())\n               .isReady(in.isReady())\n               .jobId(in.getJobId())\n               .jobStatus(in.getJobStatus())\n               .name(in.getName())\n               .osTypeId(in.getOsTypeId())\n               .osTypeName(in.getOsTypeName())\n               .passwordEnabled(in.isPasswordEnabled())\n               .removed(in.getRemoved())\n               .size(in.getSize())\n               .sourceTemplateId(in.getSourceTemplateId())\n               .status(in.getStatus())\n               .templateTag(in.getTemplateTag())\n               .templateType(in.getTemplateType())\n               .zoneId(in.getZoneId())\n               .zoneName(in.getZoneName())\n               .tags(in.getTags());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final String account;\n   private final String accountId;\n   private final boolean bootable;\n   private final String checksum;\n   private final Date created;\n   private final boolean crossZones;\n   private final String displayText;\n   private final String domain;\n   private final String domainid;\n   private final String format;\n   private final String hostId;\n   private final String hostName;\n   private final String hypervisor;\n   private final boolean isExtractable;\n   private final boolean isFeatured;\n   private final boolean isPublic;\n   private final boolean isReady;\n   private final String jobId;\n   private final String jobStatus;\n   private final String name;\n   private final String osTypeId;\n   private final String osTypeName;\n   private final boolean passwordEnabled;\n   private final Date removed;\n   private final long size;\n   private final String sourceTemplateId;\n   private final String status;\n   private final String templateTag;\n   private final String templateType;\n   private final String zoneId;\n   private final String zoneName;\n   private final Set<Tag> tags;\n\n   @ConstructorProperties({\n         \"id\", \"account\", \"accountid\", \"bootable\", \"checksum\", \"created\", \"crossZones\", \"displaytext\", \"domain\", \"domainid\", \"format\", \"hostid\", \"hostname\", \"hypervisor\", \"isextractable\", \"isfeatured\", \"ispublic\", \"isready\", \"jobid\", \"jobstatus\", \"name\", \"ostypeid\", \"ostypename\", \"passwordenabled\", \"removed\", \"size\", \"sourcetemplateid\", \"status\", \"templatetag\", \"templatetype\", \"zoneid\", \"zonename\", \"tags\"\n   })\n   protected ISO(String id, @Nullable String account, @Nullable String accountId, boolean bootable, @Nullable String checksum,\n                 @Nullable Date created, boolean crossZones, @Nullable String displayText, @Nullable String domain,\n                 @Nullable String domainid, @Nullable String format, @Nullable String hostId, @Nullable String hostName,\n                 @Nullable String hypervisor, boolean isExtractable, boolean isFeatured, boolean isPublic, boolean isReady,\n                 @Nullable String jobId, @Nullable String jobStatus, @Nullable String name, @Nullable String osTypeId,\n                 @Nullable String osTypeName, boolean passwordEnabled, @Nullable Date removed, long size, @Nullable String sourceTemplateId,\n                 @Nullable String status, @Nullable String templateTag, @Nullable String templateType, @Nullable String zoneId, @Nullable String zoneName,\n                 @Nullable Set<Tag> tags) {\n      this.id = checkNotNull(id, \"id\");\n      this.account = account;\n      this.accountId = accountId;\n      this.bootable = bootable;\n      this.checksum = checksum;\n      this.created = created;\n      this.crossZones = crossZones;\n      this.displayText = displayText;\n      this.domain = domain;\n      this.domainid = domainid;\n      this.format = format;\n      this.hostId = hostId;\n      this.hostName = hostName;\n      this.hypervisor = hypervisor;\n      this.isExtractable = isExtractable;\n      this.isFeatured = isFeatured;\n      this.isPublic = isPublic;\n      this.isReady = isReady;\n      this.jobId = jobId;\n      this.jobStatus = jobStatus;\n      this.name = name;\n      this.osTypeId = osTypeId;\n      this.osTypeName = osTypeName;\n      this.passwordEnabled = passwordEnabled;\n      this.removed = removed;\n      this.size = size;\n      this.sourceTemplateId = sourceTemplateId;\n      this.status = status;\n      this.templateTag = templateTag;\n      this.templateType = templateType;\n      this.zoneId = zoneId;\n      this.zoneName = zoneName;\n      this.tags = tags == null ? ImmutableSet.<Tag>of() : ImmutableSet.copyOf(tags);\n   }\n\n   /**\n    * @return the template ID\n    */\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * @return the account name to which the template belongs\n    */\n   @Nullable\n   public String getAccount() {\n      return this.account;\n   }\n\n   /**\n    * @return the account id to which the template belongs\n    */\n   @Nullable\n   public String getAccountId() {\n      return this.accountId;\n   }\n\n   public boolean isBootable() {\n      return this.bootable;\n   }\n\n   /**\n    * @return checksum of the template\n    */\n   @Nullable\n   public String getChecksum() {\n      return this.checksum;\n   }\n\n   /**\n    * @return the date this template was created\n    */\n   @Nullable\n   public Date getCreated() {\n      return this.created;\n   }\n\n   public boolean isCrossZones() {\n      return this.crossZones;\n   }\n\n   /**\n    * @return the template display text\n    */\n   @Nullable\n   public String getDisplayText() {\n      return this.displayText;\n   }\n\n   /**\n    * @return the name of the domain to which the template belongs\n    */\n   @Nullable\n   public String getDomain() {\n      return this.domain;\n   }\n\n   /**\n    * @return the ID of the domain to which the template belongs\n    */\n   @Nullable\n   public String getDomainid() {\n      return this.domainid;\n   }\n\n   /**\n    * @return the format of the template.\n    */\n   @Nullable\n   public String getFormat() {\n      return this.format;\n   }\n\n   /**\n    * @return the ID of the secondary storage host for the template\n    */\n   @Nullable\n   public String getHostId() {\n      return this.hostId;\n   }\n\n   /**\n    * @return the name of the secondary storage host for the template\n    */\n   @Nullable\n   public String getHostName() {\n      return this.hostName;\n   }\n\n   /**\n    * @return the hypervisor on which the template runs\n    */\n   @Nullable\n   public String getHypervisor() {\n      return this.hypervisor;\n   }\n\n   public boolean isExtractable() {\n      return this.isExtractable;\n   }\n\n   public boolean isFeatured() {\n      return this.isFeatured;\n   }\n\n   public boolean isPublic() {\n      return this.isPublic;\n   }\n\n   public boolean isReady() {\n      return this.isReady;\n   }\n\n   /**\n    * @return shows the current pending asynchronous job ID. This tag is not returned if no current pending jobs are acting on the template\n    */\n   @Nullable\n   public String getJobId() {\n      return this.jobId;\n   }\n\n   /**\n    * @return shows the current pending asynchronous job status\n    */\n   @Nullable\n   public String getJobStatus() {\n      return this.jobStatus;\n   }\n\n   /**\n    * @return the template name\n    */\n   @Nullable\n   public String getName() {\n      return this.name;\n   }\n\n   /**\n    * @return the ID of the OS type for this template.\n    */\n   @Nullable\n   public String getOsTypeId() {\n      return this.osTypeId;\n   }\n\n   /**\n    * @return the name of the OS type for this template.\n    */\n   @Nullable\n   public String getOsTypeName() {\n      return this.osTypeName;\n   }\n\n   public boolean isPasswordEnabled() {\n      return this.passwordEnabled;\n   }\n\n   /**\n    * @return the date this template was removed\n    */\n   @Nullable\n   public Date getRemoved() {\n      return this.removed;\n   }\n\n   /**\n    * @return the size of the template\n    */\n   public long getSize() {\n      return this.size;\n   }\n\n   /**\n    * @return the template ID of the parent template if present\n    */\n   @Nullable\n   public String getSourceTemplateId() {\n      return this.sourceTemplateId;\n   }\n\n   /**\n    * @return the status of the template\n    */\n   @Nullable\n   public String getStatus() {\n      return this.status;\n   }\n\n   /**\n    * @return the tag of this template\n    */\n   @Nullable\n   public String getTemplateTag() {\n      return this.templateTag;\n   }\n\n   /**\n    * @return the type of the template\n    */\n   @Nullable\n   public String getTemplateType() {\n      return this.templateType;\n   }\n\n   /**\n    * @return the ID of the zone for this template\n    */\n   @Nullable\n   public String getZoneId() {\n      return this.zoneId;\n   }\n\n   /**\n    * @return the name of the zone for this template\n    */\n   @Nullable\n   public String getZoneName() {\n      return this.zoneName;\n   }\n\n   /**\n    * @return Tags on this ISO\n    */\n   @Nullable\n   public Set<Tag> getTags() {\n      return this.tags;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, account, accountId, bootable, checksum, created, crossZones, displayText, domain,\n            domainid, format, hostId, hostName, hypervisor, isExtractable, isFeatured, isPublic, isReady, jobId, jobStatus,\n            name, osTypeId, osTypeName, passwordEnabled, removed, size, sourceTemplateId, status, templateTag, templateType, zoneId, zoneName,\n            tags);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      ISO that = ISO.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n            && Objects.equal(this.account, that.account)\n            && Objects.equal(this.accountId, that.accountId)\n            && Objects.equal(this.bootable, that.bootable)\n            && Objects.equal(this.checksum, that.checksum)\n            && Objects.equal(this.created, that.created)\n            && Objects.equal(this.crossZones, that.crossZones)\n            && Objects.equal(this.displayText, that.displayText)\n            && Objects.equal(this.domain, that.domain)\n            && Objects.equal(this.domainid, that.domainid)\n            && Objects.equal(this.format, that.format)\n            && Objects.equal(this.hostId, that.hostId)\n            && Objects.equal(this.hostName, that.hostName)\n            && Objects.equal(this.hypervisor, that.hypervisor)\n            && Objects.equal(this.isExtractable, that.isExtractable)\n            && Objects.equal(this.isFeatured, that.isFeatured)\n            && Objects.equal(this.isPublic, that.isPublic)\n            && Objects.equal(this.isReady, that.isReady)\n            && Objects.equal(this.jobId, that.jobId)\n            && Objects.equal(this.jobStatus, that.jobStatus)\n            && Objects.equal(this.name, that.name)\n            && Objects.equal(this.osTypeId, that.osTypeId)\n            && Objects.equal(this.osTypeName, that.osTypeName)\n            && Objects.equal(this.passwordEnabled, that.passwordEnabled)\n            && Objects.equal(this.removed, that.removed)\n            && Objects.equal(this.size, that.size)\n            && Objects.equal(this.sourceTemplateId, that.sourceTemplateId)\n            && Objects.equal(this.status, that.status)\n            && Objects.equal(this.templateTag, that.templateTag)\n            && Objects.equal(this.templateType, that.templateType)\n            && Objects.equal(this.zoneId, that.zoneId)\n            && Objects.equal(this.zoneName, that.zoneName)\n            && Objects.equal(this.tags, that.tags);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"account\", account).add(\"accountId\", accountId).add(\"bootable\", bootable)\n            .add(\"checksum\", checksum).add(\"created\", created).add(\"crossZones\", crossZones).add(\"displayText\", displayText)\n            .add(\"domain\", domain).add(\"domainid\", domainid).add(\"format\", format).add(\"hostId\", hostId).add(\"hostName\", hostName)\n            .add(\"hypervisor\", hypervisor).add(\"isExtractable\", isExtractable).add(\"isFeatured\", isFeatured).add(\"isPublic\", isPublic)\n            .add(\"isReady\", isReady).add(\"jobId\", jobId).add(\"jobStatus\", jobStatus).add(\"name\", name).add(\"osTypeId\", osTypeId)\n            .add(\"osTypeName\", osTypeName).add(\"passwordEnabled\", passwordEnabled).add(\"removed\", removed).add(\"size\", size)\n            .add(\"sourceTemplateId\", sourceTemplateId).add(\"status\", status).add(\"templateTag\", templateTag).add(\"templateType\", templateType)\n            .add(\"zoneId\", zoneId).add(\"zoneName\", zoneName).add(\"tags\", tags);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/ISOExtraction.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Class ISOExtraction\n */\npublic class ISOExtraction {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromISOExtraction(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String id;\n      protected String accountId;\n      protected Date created;\n      protected String extractId;\n      protected ExtractMode extractMode;\n      protected String name;\n      protected String state;\n      protected String status;\n      protected String storageType;\n      protected int uploadPercentage;\n      protected String url;\n      protected String zoneId;\n      protected String zoneName;\n\n      /**\n       * @see ISOExtraction#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see ISOExtraction#getAccountId()\n       */\n      public T accountId(String accountId) {\n         this.accountId = accountId;\n         return self();\n      }\n\n      /**\n       * @see ISOExtraction#getCreated()\n       */\n      public T created(Date created) {\n         this.created = created;\n         return self();\n      }\n\n      /**\n       * @see ISOExtraction#getExtractId()\n       */\n      public T extractId(String extractId) {\n         this.extractId = extractId;\n         return self();\n      }\n\n      /**\n       * @see ISOExtraction#getExtractMode()\n       */\n      public T extractMode(ExtractMode extractMode) {\n         this.extractMode = extractMode;\n         return self();\n      }\n\n      /**\n       * @see ISOExtraction#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /**\n       * @see ISOExtraction#getState()\n       */\n      public T state(String state) {\n         this.state = state;\n         return self();\n      }\n\n      /**\n       * @see ISOExtraction#getStatus()\n       */\n      public T status(String status) {\n         this.status = status;\n         return self();\n      }\n\n      /**\n       * @see ISOExtraction#getStorageType()\n       */\n      public T storageType(String storageType) {\n         this.storageType = storageType;\n         return self();\n      }\n\n      /**\n       * @see ISOExtraction#getUploadPercentage()\n       */\n      public T uploadPercentage(int uploadPercentage) {\n         this.uploadPercentage = uploadPercentage;\n         return self();\n      }\n\n      /**\n       * @see ISOExtraction#getUrl()\n       */\n      public T url(String url) {\n         this.url = url;\n         return self();\n      }\n\n      /**\n       * @see ISOExtraction#getZoneId()\n       */\n      public T zoneId(String zoneId) {\n         this.zoneId = zoneId;\n         return self();\n      }\n\n      /**\n       * @see ISOExtraction#getZoneName()\n       */\n      public T zoneName(String zoneName) {\n         this.zoneName = zoneName;\n         return self();\n      }\n\n      public ISOExtraction build() {\n         return new ISOExtraction(id, accountId, created, extractId, extractMode, name, state, status, storageType, uploadPercentage, url, zoneId, zoneName);\n      }\n\n      public T fromISOExtraction(ISOExtraction in) {\n         return this\n               .id(in.getId())\n               .accountId(in.getAccountId())\n               .created(in.getCreated())\n               .extractId(in.getExtractId())\n               .extractMode(in.getExtractMode())\n               .name(in.getName())\n               .state(in.getState())\n               .status(in.getStatus())\n               .storageType(in.getStorageType())\n               .uploadPercentage(in.getUploadPercentage())\n               .url(in.getUrl())\n               .zoneId(in.getZoneId())\n               .zoneName(in.getZoneName());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final String accountId;\n   private final Date created;\n   private final String extractId;\n   private final ExtractMode extractMode;\n   private final String name;\n   private final String state;\n   private final String status;\n   private final String storageType;\n   private final int uploadPercentage;\n   private final String url;\n   private final String zoneId;\n   private final String zoneName;\n\n   @ConstructorProperties({\n         \"id\", \"accountid\", \"created\", \"extractId\", \"extractMode\", \"name\", \"state\", \"status\", \"storagetype\", \"uploadpercentage\", \"url\", \"zoneid\", \"zonename\"\n   })\n   protected ISOExtraction(String id, @Nullable String accountId, @Nullable Date created, @Nullable String extractId,\n                           @Nullable ExtractMode extractMode, @Nullable String name, @Nullable String state, @Nullable String status,\n                           @Nullable String storageType, int uploadPercentage, @Nullable String url, @Nullable String zoneId,\n                           @Nullable String zoneName) {\n      this.id = checkNotNull(id, \"id\");\n      this.accountId = accountId;\n      this.created = created;\n      this.extractId = extractId;\n      this.extractMode = extractMode;\n      this.name = name;\n      this.state = state;\n      this.status = status;\n      this.storageType = storageType;\n      this.uploadPercentage = uploadPercentage;\n      this.url = url;\n      this.zoneId = zoneId;\n      this.zoneName = zoneName;\n   }\n\n   /**\n    * @return the id of extracted object\n    */\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * @return the account id to which the extracted object belongs\n    */\n   @Nullable\n   public String getAccountId() {\n      return this.accountId;\n   }\n\n   /**\n    * @return the time and date the object was created\n    */\n   @Nullable\n   public Date getCreated() {\n      return this.created;\n   }\n\n   /**\n    * @return the upload id of extracted object\n    */\n   @Nullable\n   public String getExtractId() {\n      return this.extractId;\n   }\n\n   /**\n    * @return the mode of extraction - upload or download\n    */\n   @Nullable\n   public ExtractMode getExtractMode() {\n      return this.extractMode;\n   }\n\n   /**\n    * @return the name of the extracted object\n    */\n   @Nullable\n   public String getName() {\n      return this.name;\n   }\n\n   /**\n    * @return the state of the extracted object\n    */\n   @Nullable\n   public String getState() {\n      return this.state;\n   }\n\n   /**\n    * @return the status of the extraction\n    */\n   @Nullable\n   public String getStatus() {\n      return this.status;\n   }\n\n   /**\n    * @return type of the storage\n    */\n   @Nullable\n   public String getStorageType() {\n      return this.storageType;\n   }\n\n   /**\n    * @return the percentage of the entity uploaded to the specified location\n    */\n   public int getUploadPercentage() {\n      return this.uploadPercentage;\n   }\n\n   /**\n    * @return if mode = upload then url of the uploaded entity. if mode = download the url from which the entity can be downloaded\n    */\n   @Nullable\n   public String getUrl() {\n      return this.url;\n   }\n\n   /**\n    * @return zone ID the object was extracted from\n    */\n   @Nullable\n   public String getZoneId() {\n      return this.zoneId;\n   }\n\n   /**\n    * @return zone name the object was extracted from\n    */\n   @Nullable\n   public String getZoneName() {\n      return this.zoneName;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, accountId, created, extractId, extractMode, name, state, status, storageType, uploadPercentage, url, zoneId, zoneName);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      ISOExtraction that = ISOExtraction.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n            && Objects.equal(this.accountId, that.accountId)\n            && Objects.equal(this.created, that.created)\n            && Objects.equal(this.extractId, that.extractId)\n            && Objects.equal(this.extractMode, that.extractMode)\n            && Objects.equal(this.name, that.name)\n            && Objects.equal(this.state, that.state)\n            && Objects.equal(this.status, that.status)\n            && Objects.equal(this.storageType, that.storageType)\n            && Objects.equal(this.uploadPercentage, that.uploadPercentage)\n            && Objects.equal(this.url, that.url)\n            && Objects.equal(this.zoneId, that.zoneId)\n            && Objects.equal(this.zoneName, that.zoneName);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"accountId\", accountId).add(\"created\", created).add(\"extractId\", extractId).add(\"extractMode\", extractMode)\n            .add(\"name\", name).add(\"state\", state).add(\"status\", status).add(\"storageType\", storageType).add(\"uploadPercentage\", uploadPercentage)\n            .add(\"url\", url).add(\"zoneId\", zoneId).add(\"zoneName\", zoneName);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/ISOPermissions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Class ISOPermissions\n */\npublic class ISOPermissions {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromISOPermissions(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String id;\n      protected Set<String> accounts = ImmutableSet.of();\n      protected String domainId;\n      protected boolean isPublic;\n\n      /**\n       * @see ISOPermissions#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see ISOPermissions#getAccounts()\n       */\n      public T accounts(Set<String> accounts) {\n         this.accounts = ImmutableSet.copyOf(checkNotNull(accounts, \"accounts\"));\n         return self();\n      }\n\n      public T accounts(String... in) {\n         return accounts(ImmutableSet.copyOf(in));\n      }\n\n      /**\n       * @see ISOPermissions#getDomainId()\n       */\n      public T domainId(String domainId) {\n         this.domainId = domainId;\n         return self();\n      }\n\n      /**\n       * @see ISOPermissions#isPublic()\n       */\n      public T isPublic(boolean isPublic) {\n         this.isPublic = isPublic;\n         return self();\n      }\n\n      public ISOPermissions build() {\n         return new ISOPermissions(id, accounts, domainId, isPublic);\n      }\n\n      public T fromISOPermissions(ISOPermissions in) {\n         return this\n               .id(in.getId())\n               .accounts(in.getAccounts())\n               .domainId(in.getDomainId())\n               .isPublic(in.isPublic());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final Set<String> accounts;\n   private final String domainId;\n   private final boolean isPublic;\n\n   @ConstructorProperties({\n         \"id\", \"account\", \"domainid\", \"ispublic\"\n   })\n   protected ISOPermissions(String id, @Nullable Set<String> accounts, @Nullable String domainId, boolean isPublic) {\n      this.id = checkNotNull(id, \"id\");\n      this.accounts = accounts == null ? ImmutableSet.<String>of() : ImmutableSet.copyOf(accounts);\n      this.domainId = domainId;\n      this.isPublic = isPublic;\n   }\n\n   /**\n    * @return the template ID\n    */\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * @return the list of accounts the template is available for\n    */\n   public Set<String> getAccounts() {\n      return this.accounts;\n   }\n\n   /**\n    * @return the ID of the domain to which the template belongs\n    */\n   @Nullable\n   public String getDomainId() {\n      return this.domainId;\n   }\n\n   /**\n    * @return true if this template is a public template, false otherwise\n    */\n   public boolean isPublic() {\n      return this.isPublic;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, accounts, domainId, isPublic);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      ISOPermissions that = ISOPermissions.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n            && Objects.equal(this.accounts, that.accounts)\n            && Objects.equal(this.domainId, that.domainId)\n            && Objects.equal(this.isPublic, that.isPublic);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"accounts\", accounts).add(\"domainId\", domainId).add(\"isPublic\", isPublic);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/IngressRule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableSet;\n\npublic class IngressRule implements Comparable<IngressRule> {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromIngressRule(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String account;\n      protected String CIDR;\n      protected int endPort;\n      protected int ICMPCode;\n      protected int ICMPType;\n      protected String protocol;\n      protected String id;\n      protected String securityGroupName;\n      protected int startPort;\n      protected Set<Tag> tags = ImmutableSet.of();\n\n      /**\n       * @see IngressRule#getAccount()\n       */\n      public T account(String account) {\n         this.account = account;\n         return self();\n      }\n\n      /**\n       * @see IngressRule#getCIDR()\n       */\n      public T CIDR(String CIDR) {\n         this.CIDR = CIDR;\n         return self();\n      }\n\n      /**\n       * @see IngressRule#getEndPort()\n       */\n      public T endPort(int endPort) {\n         this.endPort = endPort;\n         return self();\n      }\n\n      /**\n       * @see IngressRule#getICMPCode()\n       */\n      public T ICMPCode(int ICMPCode) {\n         this.ICMPCode = ICMPCode;\n         return self();\n      }\n\n      /**\n       * @see IngressRule#getICMPType()\n       */\n      public T ICMPType(int ICMPType) {\n         this.ICMPType = ICMPType;\n         return self();\n      }\n\n      /**\n       * @see IngressRule#getProtocol()\n       */\n      public T protocol(String protocol) {\n         this.protocol = protocol;\n         return self();\n      }\n\n      /**\n       * @see IngressRule#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see IngressRule#getSecurityGroupName()\n       */\n      public T securityGroupName(String securityGroupName) {\n         this.securityGroupName = securityGroupName;\n         return self();\n      }\n\n      /**\n       * @see IngressRule#getStartPort()\n       */\n      public T startPort(int startPort) {\n         this.startPort = startPort;\n         return self();\n      }\n\n      /**\n       * @see IngressRule#getTags()\n       */\n      public T tags(Set<Tag> tags) {\n         this.tags = ImmutableSet.copyOf(checkNotNull(tags, \"tags\"));\n         return self();\n      }\n\n      public T tags(Tag... in) {\n         return tags(ImmutableSet.copyOf(in));\n      }\n\n      public IngressRule build() {\n         return new IngressRule(account, CIDR, endPort, ICMPCode, ICMPType, protocol, id, securityGroupName, startPort, tags);\n      }\n\n      public T fromIngressRule(IngressRule in) {\n         return this\n               .account(in.getAccount())\n               .CIDR(in.getCIDR())\n               .endPort(in.getEndPort())\n               .ICMPCode(in.getICMPCode())\n               .ICMPType(in.getICMPType())\n               .protocol(in.getProtocol())\n               .id(in.getId())\n               .securityGroupName(in.getSecurityGroupName())\n               .startPort(in.getStartPort())\n               .tags(in.getTags());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String account;\n   private final String CIDR;\n   private final int endPort;\n   private final int ICMPCode;\n   private final int ICMPType;\n   private final String protocol;\n   private final String id;\n   private final String securityGroupName;\n   private final int startPort;\n   private final Set<Tag> tags;\n\n   @ConstructorProperties({\n         \"account\", \"cidr\", \"endport\", \"icmpcode\", \"icmptype\", \"protocol\", \"ruleid\", \"securitygroupname\", \"startport\", \"tags\"\n   })\n   protected IngressRule(@Nullable String account, @Nullable String CIDR, int endPort, int ICMPCode, int ICMPType,\n                         @Nullable String protocol, String id, @Nullable String securityGroupName, int startPort,\n                         @Nullable Set<Tag> tags) {\n      this.account = account;\n      this.CIDR = CIDR;\n      this.endPort = endPort;\n      this.ICMPCode = ICMPCode;\n      this.ICMPType = ICMPType;\n      this.protocol = protocol;\n      this.id = checkNotNull(id, \"id\");\n      this.securityGroupName = securityGroupName;\n      this.startPort = startPort;\n      this.tags = tags == null ? ImmutableSet.<Tag>of() : ImmutableSet.copyOf(tags);\n   }\n\n   /**\n    * @return account owning the ingress rule\n    */\n   @Nullable\n   public String getAccount() {\n      return this.account;\n   }\n\n   /**\n    * @return the CIDR notation for the base IP address of the ingress rule\n    */\n   @Nullable\n   public String getCIDR() {\n      return this.CIDR;\n   }\n\n   /**\n    * @return the ending IP of the ingress rule\n    */\n   public int getEndPort() {\n      return this.endPort;\n   }\n\n   /**\n    * @return the code for the ICMP message response\n    */\n   public int getICMPCode() {\n      return this.ICMPCode;\n   }\n\n   /**\n    * @return the type of the ICMP message response\n    */\n   public int getICMPType() {\n      return this.ICMPType;\n   }\n\n   /**\n    * @return the protocol of the ingress rule\n    */\n   @Nullable\n   public String getProtocol() {\n      return this.protocol;\n   }\n\n   /**\n    * @return the id of the ingress rule\n    */\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * @return security group name\n    */\n   @Nullable\n   public String getSecurityGroupName() {\n      return this.securityGroupName;\n   }\n\n   /**\n    * @return the starting IP of the ingress rule\n    */\n   public int getStartPort() {\n      return this.startPort;\n   }\n\n   /**\n    * @return Tags on this rule\n    */\n   @Nullable\n   public Set<Tag> getTags() {\n      return this.tags;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(account, CIDR, endPort, ICMPCode, ICMPType, protocol, id, securityGroupName, startPort, tags);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      IngressRule that = IngressRule.class.cast(obj);\n      return Objects.equal(this.account, that.account)\n            && Objects.equal(this.CIDR, that.CIDR)\n            && Objects.equal(this.endPort, that.endPort)\n            && Objects.equal(this.ICMPCode, that.ICMPCode)\n            && Objects.equal(this.ICMPType, that.ICMPType)\n            && Objects.equal(this.protocol, that.protocol)\n            && Objects.equal(this.id, that.id)\n            && Objects.equal(this.securityGroupName, that.securityGroupName)\n            && Objects.equal(this.startPort, that.startPort)\n            && Objects.equal(this.tags, that.tags);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"account\", account).add(\"CIDR\", CIDR).add(\"endPort\", endPort).add(\"ICMPCode\", ICMPCode)\n            .add(\"ICMPType\", ICMPType).add(\"protocol\", protocol).add(\"id\", id).add(\"securityGroupName\", securityGroupName).add(\"startPort\", startPort)\n            .add(\"tags\", tags);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int compareTo(IngressRule o) {\n      return id.compareTo(o.getId());\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/JobResult.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * The result of an operation.\n * <p/>\n * A handful of Cloudstack API calls return this structure when there is no domain model data to return - for example,\n * when deleting an object.\n */\npublic class JobResult {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromJobResult(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected boolean success;\n      protected String displayText;\n\n      /**\n       * @see JobResult#isSuccess()\n       */\n      public T success(boolean success) {\n         this.success = success;\n         return self();\n      }\n\n      /**\n       * @see JobResult#getDisplayText()\n       */\n      public T displayText(String displayText) {\n         this.displayText = displayText;\n         return self();\n      }\n\n      public JobResult build() {\n         return new JobResult(success, displayText);\n      }\n\n      public T fromJobResult(JobResult in) {\n         return this\n               .success(in.isSuccess())\n               .displayText(in.getDisplayText());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final boolean success;\n   private final String displayText;\n\n   @ConstructorProperties({\n         \"success\", \"displaytext\"\n   })\n   protected JobResult(boolean success, @Nullable String displayText) {\n      this.success = success;\n      this.displayText = displayText;\n   }\n\n   public boolean isSuccess() {\n      return this.success;\n   }\n\n   @Nullable\n   public String getDisplayText() {\n      return this.displayText;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(success, displayText);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      JobResult that = JobResult.class.cast(obj);\n      return Objects.equal(this.success, that.success)\n            && Objects.equal(this.displayText, that.displayText);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).add(\"success\", success).add(\"displayText\", displayText);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/LoadBalancerRule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.CaseFormat;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Class LoadBalancerRule\n */\npublic class LoadBalancerRule {\n\n   /**\n    */\n   public static enum State {\n      ADD, ACTIVE, UNRECOGNIZED;\n\n      @Override\n      public String toString() {\n         return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name());\n      }\n\n      public static State fromValue(String state) {\n         try {\n            return valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, checkNotNull(state, \"state\")));\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n\n   }\n\n   public static enum Algorithm {\n      SOURCE, ROUNDROBIN, LEASTCONN, UNRECOGNIZED;\n\n      @Override\n      public String toString() {\n         return name().toLowerCase();\n      }\n\n      public static Algorithm fromValue(String algorithm) {\n         try {\n            return Algorithm.valueOf(checkNotNull(algorithm, \"algorithm\").toUpperCase());\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n\n   }\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromLoadBalancerRule(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String id;\n      protected String account;\n      protected LoadBalancerRule.Algorithm algorithm;\n      protected String description;\n      protected String domain;\n      protected String domainId;\n      protected String name;\n      protected int privatePort;\n      protected String publicIP;\n      protected String publicIPId;\n      protected int publicPort;\n      protected LoadBalancerRule.State state;\n      protected Set<String> CIDRs = ImmutableSet.of();\n      protected String zoneId;\n\n      /**\n       * @see LoadBalancerRule#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see LoadBalancerRule#getAccount()\n       */\n      public T account(String account) {\n         this.account = account;\n         return self();\n      }\n\n      /**\n       * @see LoadBalancerRule#getAlgorithm()\n       */\n      public T algorithm(LoadBalancerRule.Algorithm algorithm) {\n         this.algorithm = algorithm;\n         return self();\n      }\n\n      /**\n       * @see LoadBalancerRule#getDescription()\n       */\n      public T description(String description) {\n         this.description = description;\n         return self();\n      }\n\n      /**\n       * @see LoadBalancerRule#getDomain()\n       */\n      public T domain(String domain) {\n         this.domain = domain;\n         return self();\n      }\n\n      /**\n       * @see LoadBalancerRule#getDomainId()\n       */\n      public T domainId(String domainId) {\n         this.domainId = domainId;\n         return self();\n      }\n\n      /**\n       * @see LoadBalancerRule#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /**\n       * @see LoadBalancerRule#getPrivatePort()\n       */\n      public T privatePort(int privatePort) {\n         this.privatePort = privatePort;\n         return self();\n      }\n\n      /**\n       * @see LoadBalancerRule#getPublicIP()\n       */\n      public T publicIP(String publicIP) {\n         this.publicIP = publicIP;\n         return self();\n      }\n\n      /**\n       * @see LoadBalancerRule#getPublicIPId()\n       */\n      public T publicIPId(String publicIPId) {\n         this.publicIPId = publicIPId;\n         return self();\n      }\n\n      /**\n       * @see LoadBalancerRule#getPublicPort()\n       */\n      public T publicPort(int publicPort) {\n         this.publicPort = publicPort;\n         return self();\n      }\n\n      /**\n       * @see LoadBalancerRule#getState()\n       */\n      public T state(LoadBalancerRule.State state) {\n         this.state = state;\n         return self();\n      }\n\n      /**\n       * @see LoadBalancerRule#getCIDRs()\n       */\n      public T CIDRs(Set<String> CIDRs) {\n         this.CIDRs = ImmutableSet.copyOf(checkNotNull(CIDRs, \"CIDRs\"));\n         return self();\n      }\n\n      public T CIDRs(String... in) {\n         return CIDRs(ImmutableSet.copyOf(in));\n      }\n\n      /**\n       * @see LoadBalancerRule#getZoneId()\n       */\n      public T zoneId(String zoneId) {\n         this.zoneId = zoneId;\n         return self();\n      }\n\n      public LoadBalancerRule build() {\n         return new LoadBalancerRule(id, account, algorithm, description, domain, domainId, name, privatePort, publicIP, publicIPId, publicPort, state, CIDRs, zoneId);\n      }\n\n      public T fromLoadBalancerRule(LoadBalancerRule in) {\n         return this\n               .id(in.getId())\n               .account(in.getAccount())\n               .algorithm(in.getAlgorithm())\n               .description(in.getDescription())\n               .domain(in.getDomain())\n               .domainId(in.getDomainId())\n               .name(in.getName())\n               .privatePort(in.getPrivatePort())\n               .publicIP(in.getPublicIP())\n               .publicIPId(in.getPublicIPId())\n               .publicPort(in.getPublicPort())\n               .state(in.getState())\n               .CIDRs(in.getCIDRs())\n               .zoneId(in.getZoneId());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final String account;\n   private final LoadBalancerRule.Algorithm algorithm;\n   private final String description;\n   private final String domain;\n   private final String domainId;\n   private final String name;\n   private final int privatePort;\n   private final String publicIP;\n   private final String publicIPId;\n   private final int publicPort;\n   private final LoadBalancerRule.State state;\n   private final Set<String> CIDRs;\n   private final String zoneId;\n\n\n   @ConstructorProperties({\n         \"id\", \"account\", \"algorithm\", \"description\", \"domain\", \"domainid\", \"name\", \"privateport\", \"publicip\",\n         \"publicipid\", \"publicport\", \"state\", \"cidrlist\", \"zoneId\"\n   })\n   private LoadBalancerRule(String id, @Nullable String account, @Nullable Algorithm algorithm,\n                            @Nullable String description, @Nullable String domain, @Nullable String domainId,\n                            @Nullable String name, int privatePort, @Nullable String publicIP,\n                            @Nullable String publicIPId, int publicPort, @Nullable State state,\n                            @Nullable String CIDRs, @Nullable String zoneId) {\n      this(id, account, algorithm, description, domain, domainId, name, privatePort, publicIP, publicIPId, publicPort, state,\n            splitStringOnCommas(CIDRs), zoneId);\n   }\n\n   private static Set<String> splitStringOnCommas(String in) {\n      return in == null ? ImmutableSet.<String>of() : ImmutableSet.copyOf(in.split(\",\"));\n   }\n\n   protected LoadBalancerRule(String id, @Nullable String account, @Nullable LoadBalancerRule.Algorithm algorithm,\n                              @Nullable String description, @Nullable String domain, @Nullable String domainId, @Nullable String name,\n                              int privatePort, @Nullable String publicIP, @Nullable String publicIPId, int publicPort,\n                              @Nullable LoadBalancerRule.State state, @Nullable Iterable<String> CIDRs, @Nullable String zoneId) {\n      this.id = checkNotNull(id, \"id\");\n      this.account = account;\n      this.algorithm = algorithm;\n      this.description = description;\n      this.domain = domain;\n      this.domainId = domainId;\n      this.name = name;\n      this.privatePort = privatePort;\n      this.publicIP = publicIP;\n      this.publicIPId = publicIPId;\n      this.publicPort = publicPort;\n      this.state = state;\n      this.CIDRs = CIDRs == null ? ImmutableSet.<String>of() : ImmutableSet.copyOf(CIDRs);\n      this.zoneId = zoneId;\n   }\n\n   /**\n    * @return the load balancer rule ID\n    */\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * @return the account of the load balancer rule\n    */\n   @Nullable\n   public String getAccount() {\n      return this.account;\n   }\n\n   /**\n    * @return the load balancer algorithm (source, roundrobin, leastconn)\n    */\n   @Nullable\n   public LoadBalancerRule.Algorithm getAlgorithm() {\n      return this.algorithm;\n   }\n\n   /**\n    * @return the description of the load balancer\n    */\n   @Nullable\n   public String getDescription() {\n      return this.description;\n   }\n\n   /**\n    * @return the domain of the load balancer rule\n    */\n   @Nullable\n   public String getDomain() {\n      return this.domain;\n   }\n\n   /**\n    * @return the domain ID of the load balancer rule\n    */\n   @Nullable\n   public String getDomainId() {\n      return this.domainId;\n   }\n\n   /**\n    * @return the name of the load balancer\n    */\n   @Nullable\n   public String getName() {\n      return this.name;\n   }\n\n   /**\n    * @return the private port\n    */\n   public int getPrivatePort() {\n      return this.privatePort;\n   }\n\n   /**\n    * @return the public ip address\n    */\n   @Nullable\n   public String getPublicIP() {\n      return this.publicIP;\n   }\n\n   /**\n    * @return the public ip address id\n    */\n   @Nullable\n   public String getPublicIPId() {\n      return this.publicIPId;\n   }\n\n   /**\n    * @return the public port\n    */\n   public int getPublicPort() {\n      return this.publicPort;\n   }\n\n   /**\n    * @return the state of the rule\n    */\n   @Nullable\n   public LoadBalancerRule.State getState() {\n      return this.state;\n   }\n\n   /**\n    * @return the cidr list to forward traffic from\n    */\n   public Set<String> getCIDRs() {\n      return this.CIDRs;\n   }\n\n   /**\n    * @return the id of the zone the rule beStrings to\n    */\n   @Nullable\n   public String getZoneId() {\n      return this.zoneId;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, account, algorithm, description, domain, domainId, name, privatePort, publicIP, publicIPId, publicPort, state, CIDRs, zoneId);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      LoadBalancerRule that = LoadBalancerRule.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n            && Objects.equal(this.account, that.account)\n            && Objects.equal(this.algorithm, that.algorithm)\n            && Objects.equal(this.description, that.description)\n            && Objects.equal(this.domain, that.domain)\n            && Objects.equal(this.domainId, that.domainId)\n            && Objects.equal(this.name, that.name)\n            && Objects.equal(this.privatePort, that.privatePort)\n            && Objects.equal(this.publicIP, that.publicIP)\n            && Objects.equal(this.publicIPId, that.publicIPId)\n            && Objects.equal(this.publicPort, that.publicPort)\n            && Objects.equal(this.state, that.state)\n            && Objects.equal(this.CIDRs, that.CIDRs)\n            && Objects.equal(this.zoneId, that.zoneId);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"account\", account).add(\"algorithm\", algorithm).add(\"description\", description).add(\"domain\", domain).add(\"domainId\", domainId).add(\"name\", name).add(\"privatePort\", privatePort).add(\"publicIP\", publicIP).add(\"publicIPId\", publicIPId).add(\"publicPort\", publicPort).add(\"state\", state).add(\"CIDRs\", CIDRs).add(\"zoneId\", zoneId);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/LoginResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Representation of the login API call response\n */\npublic class LoginResponse {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromLoginResponse(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String username;\n      protected String userId;\n      protected String password;\n      protected String domainId;\n      protected long timeout;\n      protected boolean registered;\n      protected String accountName;\n      protected String firstName;\n      protected String lastName;\n      protected Account.Type accountType;\n      protected String timezone;\n      protected String timezoneOffset;\n      protected String sessionKey;\n      protected String jSessionId;\n\n      /**\n       * @see LoginResponse#getUsername()\n       */\n      public T username(String username) {\n         this.username = username;\n         return self();\n      }\n\n      /**\n       * @see LoginResponse#getUserId()\n       */\n      public T userId(String userId) {\n         this.userId = userId;\n         return self();\n      }\n\n      /**\n       * @see LoginResponse#getPassword()\n       */\n      public T password(String password) {\n         this.password = password;\n         return self();\n      }\n\n      /**\n       * @see LoginResponse#getDomainId()\n       */\n      public T domainId(String domainId) {\n         this.domainId = domainId;\n         return self();\n      }\n\n      /**\n       * @see LoginResponse#getTimeout()\n       */\n      public T timeout(long timeout) {\n         this.timeout = timeout;\n         return self();\n      }\n\n      /**\n       * @see LoginResponse#isRegistered()\n       */\n      public T registered(boolean registered) {\n         this.registered = registered;\n         return self();\n      }\n\n      /**\n       * @see LoginResponse#getAccountName()\n       */\n      public T accountName(String accountName) {\n         this.accountName = accountName;\n         return self();\n      }\n\n      /**\n       * @see LoginResponse#getFirstName()\n       */\n      public T firstName(String firstName) {\n         this.firstName = firstName;\n         return self();\n      }\n\n      /**\n       * @see LoginResponse#getLastName()\n       */\n      public T lastName(String lastName) {\n         this.lastName = lastName;\n         return self();\n      }\n\n      /**\n       * @see LoginResponse#getAccountType()\n       */\n      public T accountType(Account.Type accountType) {\n         this.accountType = accountType;\n         return self();\n      }\n\n      /**\n       * @see LoginResponse#getTimezone()\n       */\n      public T timezone(String timezone) {\n         this.timezone = timezone;\n         return self();\n      }\n\n      /**\n       * @see LoginResponse#getTimezoneOffset()\n       */\n      public T timezoneOffset(String timezoneOffset) {\n         this.timezoneOffset = timezoneOffset;\n         return self();\n      }\n\n      /**\n       * @see LoginResponse#getSessionKey()\n       */\n      public T sessionKey(String sessionKey) {\n         this.sessionKey = sessionKey;\n         return self();\n      }\n\n      /**\n       * @see LoginResponse#getJSessionId()\n       */\n      public T jSessionId(String jSessionId) {\n         this.jSessionId = jSessionId;\n         return self();\n      }\n\n      public LoginResponse build() {\n         return new LoginResponse(username, userId, password, domainId, timeout, registered, accountName, firstName, lastName, accountType, timezone, timezoneOffset, sessionKey, jSessionId);\n      }\n\n      public T fromLoginResponse(LoginResponse in) {\n         return this\n               .username(in.getUsername())\n               .userId(in.getUserId())\n               .password(in.getPassword())\n               .domainId(in.getDomainId())\n               .timeout(in.getTimeout())\n               .registered(in.isRegistered())\n               .accountName(in.getAccountName())\n               .firstName(in.getFirstName())\n               .lastName(in.getLastName())\n               .accountType(in.getAccountType())\n               .timezone(in.getTimezone())\n               .timezoneOffset(in.getTimezoneOffset())\n               .sessionKey(in.getSessionKey())\n               .jSessionId(in.getJSessionId());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String username;\n   private final String userId;\n   private final String password;\n   private final String domainId;\n   private final long timeout;\n   private final boolean registered;\n   private final String accountName;\n   private final String firstName;\n   private final String lastName;\n   private final Account.Type accountType;\n   private final String timezone;\n   private final String timezoneOffset;\n   private final String sessionKey;\n   private final String jSessionId;\n\n   @ConstructorProperties({\n         \"username\", \"userid\", \"password\", \"domainid\", \"timeout\", \"registered\", \"account\", \"firstname\", \"lastname\", \"type\", \"timezone\", \"timezoneoffset\", \"sessionkey\", \"jSessionId\"\n   })\n   protected LoginResponse(@Nullable String username, @Nullable String userId, @Nullable String password, @Nullable String domainId, long timeout, boolean registered, @Nullable String accountName, @Nullable String firstName, @Nullable String lastName, @Nullable Account.Type accountType, @Nullable String timezone, @Nullable String timezoneOffset, @Nullable String sessionKey, @Nullable String jSessionId) {\n      this.username = username;\n      this.userId = userId;\n      this.password = password;\n      this.domainId = domainId;\n      this.timeout = timeout;\n      this.registered = registered;\n      this.accountName = accountName;\n      this.firstName = firstName;\n      this.lastName = lastName;\n      this.accountType = accountType;\n      this.timezone = timezone;\n      this.timezoneOffset = timezoneOffset;\n      this.sessionKey = sessionKey;\n      this.jSessionId = jSessionId;\n   }\n\n   @Nullable\n   public String getUsername() {\n      return this.username;\n   }\n\n   @Nullable\n   public String getUserId() {\n      return this.userId;\n   }\n\n   @Nullable\n   public String getPassword() {\n      return this.password;\n   }\n\n   @Nullable\n   public String getDomainId() {\n      return this.domainId;\n   }\n\n   public long getTimeout() {\n      return this.timeout;\n   }\n\n   public boolean isRegistered() {\n      return this.registered;\n   }\n\n   @Nullable\n   public String getAccountName() {\n      return this.accountName;\n   }\n\n   @Nullable\n   public String getFirstName() {\n      return this.firstName;\n   }\n\n   @Nullable\n   public String getLastName() {\n      return this.lastName;\n   }\n\n   @Nullable\n   public Account.Type getAccountType() {\n      return this.accountType;\n   }\n\n   @Nullable\n   public String getTimezone() {\n      return this.timezone;\n   }\n\n   @Nullable\n   public String getTimezoneOffset() {\n      return this.timezoneOffset;\n   }\n\n   @Nullable\n   public String getSessionKey() {\n      return this.sessionKey;\n   }\n\n   @Nullable\n   public String getJSessionId() {\n      return this.jSessionId;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(username, userId, password, domainId, timeout, registered, accountName, firstName, lastName, accountType, timezone, timezoneOffset, sessionKey, jSessionId);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      LoginResponse that = LoginResponse.class.cast(obj);\n      return Objects.equal(this.username, that.username)\n            && Objects.equal(this.userId, that.userId)\n            && Objects.equal(this.password, that.password)\n            && Objects.equal(this.domainId, that.domainId)\n            && Objects.equal(this.timeout, that.timeout)\n            && Objects.equal(this.registered, that.registered)\n            && Objects.equal(this.accountName, that.accountName)\n            && Objects.equal(this.firstName, that.firstName)\n            && Objects.equal(this.lastName, that.lastName)\n            && Objects.equal(this.accountType, that.accountType)\n            && Objects.equal(this.timezone, that.timezone)\n            && Objects.equal(this.timezoneOffset, that.timezoneOffset)\n            && Objects.equal(this.sessionKey, that.sessionKey)\n            && Objects.equal(this.jSessionId, that.jSessionId);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"username\", username).add(\"userId\", userId).add(\"password\", password).add(\"domainId\", domainId).add(\"timeout\", timeout).add(\"registered\", registered).add(\"accountName\", accountName).add(\"firstName\", firstName).add(\"lastName\", lastName).add(\"accountType\", accountType).add(\"timezone\", timezone).add(\"timezoneOffset\", timezoneOffset).add(\"sessionKey\", sessionKey).add(\"jSessionId\", jSessionId);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/NIC.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.net.URI;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Class NIC\n */\npublic class NIC {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromNIC(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String id;\n      protected URI broadcastURI;\n      protected String gateway;\n      protected String IPAddress;\n      protected boolean isDefault;\n      protected URI isolationURI;\n      protected String netmask;\n      protected String macAddress;\n      protected String networkId;\n      protected TrafficType trafficType;\n      protected GuestIPType guestIPType;\n\n      /**\n       * @see NIC#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see NIC#getBroadcastURI()\n       */\n      public T broadcastURI(URI broadcastURI) {\n         this.broadcastURI = broadcastURI;\n         return self();\n      }\n\n      /**\n       * @see NIC#getGateway()\n       */\n      public T gateway(String gateway) {\n         this.gateway = gateway;\n         return self();\n      }\n\n      /**\n       * @see NIC#getIPAddress()\n       */\n      public T IPAddress(String IPAddress) {\n         this.IPAddress = IPAddress;\n         return self();\n      }\n\n      /**\n       * @see NIC#isDefault()\n       */\n      public T isDefault(boolean isDefault) {\n         this.isDefault = isDefault;\n         return self();\n      }\n\n      /**\n       * @see NIC#getIsolationURI()\n       */\n      public T isolationURI(URI isolationURI) {\n         this.isolationURI = isolationURI;\n         return self();\n      }\n\n      /**\n       * @see NIC#getNetmask()\n       */\n      public T netmask(String netmask) {\n         this.netmask = netmask;\n         return self();\n      }\n\n      /**\n       * @see NIC#getMacAddress()\n       */\n      public T macAddress(String macAddress) {\n         this.macAddress = macAddress;\n         return self();\n      }\n\n      /**\n       * @see NIC#getNetworkId()\n       */\n      public T networkId(String networkId) {\n         this.networkId = networkId;\n         return self();\n      }\n\n      /**\n       * @see NIC#getTrafficType()\n       */\n      public T trafficType(TrafficType trafficType) {\n         this.trafficType = trafficType;\n         return self();\n      }\n\n      /**\n       * @see NIC#getGuestIPType()\n       */\n      public T guestIPType(GuestIPType guestIPType) {\n         this.guestIPType = guestIPType;\n         return self();\n      }\n\n      public NIC build() {\n         return new NIC(id, broadcastURI, gateway, IPAddress, isDefault, isolationURI, netmask, macAddress, networkId, trafficType, guestIPType);\n      }\n\n      public T fromNIC(NIC in) {\n         return this\n               .id(in.getId())\n               .broadcastURI(in.getBroadcastURI())\n               .gateway(in.getGateway())\n               .IPAddress(in.getIPAddress())\n               .isDefault(in.isDefault())\n               .isolationURI(in.getIsolationURI())\n               .netmask(in.getNetmask())\n               .macAddress(in.getMacAddress())\n               .networkId(in.getNetworkId())\n               .trafficType(in.getTrafficType())\n               .guestIPType(in.getGuestIPType());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final URI broadcastURI;\n   private final String gateway;\n   private final String IPAddress;\n   private final boolean isDefault;\n   private final URI isolationURI;\n   private final String netmask;\n   private final String macAddress;\n   private final String networkId;\n   private final TrafficType trafficType;\n   private final GuestIPType guestIPType;\n\n   @ConstructorProperties({\n         \"id\", \"broadcasturi\", \"gateway\", \"ipaddress\", \"isdefault\", \"isolationuri\", \"netmask\", \"macaddress\", \"networkid\", \"traffictype\", \"type\"\n   })\n   protected NIC(String id, @Nullable URI broadcastURI, @Nullable String gateway, @Nullable String IPAddress, boolean isDefault,\n                 @Nullable URI isolationURI, @Nullable String netmask, @Nullable String macAddress, @Nullable String networkId,\n                 @Nullable TrafficType trafficType, @Nullable GuestIPType guestIPType) {\n      this.id = checkNotNull(id, \"id\");\n      this.broadcastURI = broadcastURI;\n      this.gateway = gateway;\n      this.IPAddress = IPAddress;\n      this.isDefault = isDefault;\n      this.isolationURI = isolationURI;\n      this.netmask = netmask;\n      this.macAddress = macAddress;\n      this.networkId = networkId;\n      this.trafficType = trafficType;\n      this.guestIPType = guestIPType;\n   }\n\n   /**\n    * the ID of the nic\n    */\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * the broadcast uri of the nic\n    */\n   @Nullable\n   public URI getBroadcastURI() {\n      return this.broadcastURI;\n   }\n\n   /**\n    * the gateway of the nic\n    */\n   @Nullable\n   public String getGateway() {\n      return this.gateway;\n   }\n\n   /**\n    * the ip address of the nic\n    */\n   @Nullable\n   public String getIPAddress() {\n      return this.IPAddress;\n   }\n\n   /**\n    * true if nic is default, false otherwise\n    */\n   public boolean isDefault() {\n      return this.isDefault;\n   }\n\n   /**\n    * the isolation uri of the nic\n    */\n   @Nullable\n   public URI getIsolationURI() {\n      return this.isolationURI;\n   }\n\n   /**\n    * the netmask of the nic\n    */\n   @Nullable\n   public String getNetmask() {\n      return this.netmask;\n   }\n\n   /**\n    * the MAC Address of the NIC\n    */\n   @Nullable\n   public String getMacAddress() {\n      return this.macAddress;\n   }\n\n   /**\n    * the ID of the corresponding network\n    */\n   @Nullable\n   public String getNetworkId() {\n      return this.networkId;\n   }\n\n   /**\n    * the traffic type of the nic\n    */\n   @Nullable\n   public TrafficType getTrafficType() {\n      return this.trafficType;\n   }\n\n   /**\n    * the type of the nic\n    */\n   @Nullable\n   public GuestIPType getGuestIPType() {\n      return this.guestIPType;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, broadcastURI, gateway, IPAddress, isDefault, isolationURI, netmask, macAddress, networkId, trafficType, guestIPType);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      NIC that = NIC.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n            && Objects.equal(this.broadcastURI, that.broadcastURI)\n            && Objects.equal(this.gateway, that.gateway)\n            && Objects.equal(this.IPAddress, that.IPAddress)\n            && Objects.equal(this.isDefault, that.isDefault)\n            && Objects.equal(this.isolationURI, that.isolationURI)\n            && Objects.equal(this.netmask, that.netmask)\n            && Objects.equal(this.macAddress, that.macAddress)\n            && Objects.equal(this.networkId, that.networkId)\n            && Objects.equal(this.trafficType, that.trafficType)\n            && Objects.equal(this.guestIPType, that.guestIPType);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"broadcastURI\", broadcastURI).add(\"gateway\", gateway).add(\"IPAddress\", IPAddress)\n            .add(\"isDefault\", isDefault).add(\"isolationURI\", isolationURI).add(\"netmask\", netmask).add(\"macAddress\", macAddress)\n            .add(\"networkId\", networkId).add(\"trafficType\", trafficType).add(\"guestIPType\", guestIPType);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/Network.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.net.URI;\nimport java.util.List;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSortedSet;\n\n/**\n * Class Network\n */\npublic class Network {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromNetwork(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String id;\n      protected String account;\n      protected String broadcastDomainType;\n      protected URI broadcastURI;\n      protected String displayText;\n      protected String dns1;\n      protected String dns2;\n      protected String domain;\n      protected String domainId;\n      protected String endIP;\n      protected String gateway;\n      protected boolean isDefault;\n      protected boolean isShared;\n      protected boolean isSystem;\n      protected String netmask;\n      protected String networkDomain;\n      protected String networkOfferingAvailability;\n      protected String networkOfferingDisplayText;\n      protected String networkOfferingId;\n      protected String networkOfferingName;\n      protected String related;\n      protected String startIP;\n      protected String name;\n      protected String state;\n      protected GuestIPType guestIPType;\n      protected String vlan;\n      protected TrafficType trafficType;\n      protected String zoneId;\n      protected boolean securityGroupEnabled;\n      protected Set<? extends NetworkService> services = ImmutableSortedSet.of();\n      protected Set<Tag> tags = ImmutableSet.of();\n\n      /**\n       * @see Network#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see Network#getAccount()\n       */\n      public T account(String account) {\n         this.account = account;\n         return self();\n      }\n\n      /**\n       * @see Network#getBroadcastDomainType()\n       */\n      public T broadcastDomainType(String broadcastDomainType) {\n         this.broadcastDomainType = broadcastDomainType;\n         return self();\n      }\n\n      /**\n       * @see Network#getBroadcastURI()\n       */\n      public T broadcastURI(URI broadcastURI) {\n         this.broadcastURI = broadcastURI;\n         return self();\n      }\n\n      /**\n       * @see Network#getDisplayText()\n       */\n      public T displayText(String displayText) {\n         this.displayText = displayText;\n         return self();\n      }\n\n      /**\n       * @return the DNS for the Network\n       */\n      public T DNS(List<String> DNS) {\n         if (!DNS.isEmpty()) this.dns1 = DNS.get(0);\n         if (DNS.size() > 1) this.dns2 = DNS.get(1);\n         return self();\n      }\n\n      /**\n       * @see Network#getDomain()\n       */\n      public T domain(String domain) {\n         this.domain = domain;\n         return self();\n      }\n\n      /**\n       * @see Network#getDomainId()\n       */\n      public T domainId(String domainId) {\n         this.domainId = domainId;\n         return self();\n      }\n\n      /**\n       * @see Network#getEndIP()\n       */\n      public T endIP(String endIP) {\n         this.endIP = endIP;\n         return self();\n      }\n\n      /**\n       * @see Network#getGateway()\n       */\n      public T gateway(String gateway) {\n         this.gateway = gateway;\n         return self();\n      }\n\n      /**\n       * @see Network#isDefault()\n       */\n      public T isDefault(boolean isDefault) {\n         this.isDefault = isDefault;\n         return self();\n      }\n\n      /**\n       * @see Network#isShared()\n       */\n      public T isShared(boolean isShared) {\n         this.isShared = isShared;\n         return self();\n      }\n\n      /**\n       * @see Network#isSystem()\n       */\n      public T isSystem(boolean isSystem) {\n         this.isSystem = isSystem;\n         return self();\n      }\n\n      /**\n       * @see Network#getNetmask()\n       */\n      public T netmask(String netmask) {\n         this.netmask = netmask;\n         return self();\n      }\n\n      /**\n       * @see Network#getNetworkDomain()\n       */\n      public T networkDomain(String networkDomain) {\n         this.networkDomain = networkDomain;\n         return self();\n      }\n\n      /**\n       * @see Network#getNetworkOfferingAvailability()\n       */\n      public T networkOfferingAvailability(String networkOfferingAvailability) {\n         this.networkOfferingAvailability = networkOfferingAvailability;\n         return self();\n      }\n\n      /**\n       * @see Network#getNetworkOfferingDisplayText()\n       */\n      public T networkOfferingDisplayText(String networkOfferingDisplayText) {\n         this.networkOfferingDisplayText = networkOfferingDisplayText;\n         return self();\n      }\n\n      /**\n       * @see Network#getNetworkOfferingId()\n       */\n      public T networkOfferingId(String networkOfferingId) {\n         this.networkOfferingId = networkOfferingId;\n         return self();\n      }\n\n      /**\n       * @see Network#getNetworkOfferingName()\n       */\n      public T networkOfferingName(String networkOfferingName) {\n         this.networkOfferingName = networkOfferingName;\n         return self();\n      }\n\n      /**\n       * @see Network#getRelated()\n       */\n      public T related(String related) {\n         this.related = related;\n         return self();\n      }\n\n      /**\n       * @see Network#getStartIP()\n       */\n      public T startIP(String startIP) {\n         this.startIP = startIP;\n         return self();\n      }\n\n      /**\n       * @see Network#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /**\n       * @see Network#getState()\n       */\n      public T state(String state) {\n         this.state = state;\n         return self();\n      }\n\n      /**\n       * @see Network#getGuestIPType()\n       */\n      public T guestIPType(GuestIPType guestIPType) {\n         this.guestIPType = guestIPType;\n         return self();\n      }\n\n      /**\n       * @see Network#getVLAN()\n       */\n      public T VLAN(String vlan) {\n         this.vlan = vlan;\n         return self();\n      }\n\n      /**\n       * @see Network#getTrafficType()\n       */\n      public T trafficType(TrafficType trafficType) {\n         this.trafficType = trafficType;\n         return self();\n      }\n\n      /**\n       * @see Network#getZoneId()\n       */\n      public T zoneId(String zoneId) {\n         this.zoneId = zoneId;\n         return self();\n      }\n\n      /**\n       * @see Network#isSecurityGroupEnabled()\n       */\n      public T securityGroupEnabled(boolean securityGroupEnabled) {\n         this.securityGroupEnabled = securityGroupEnabled;\n         return self();\n      }\n\n      /**\n       * @see Network#getServices()\n       */\n      public T services(Set<? extends NetworkService> services) {\n         this.services = services;\n         return self();\n      }\n\n      /**\n       * @see Network#getTags()\n       */\n      public T tags(Set<Tag> tags) {\n         this.tags = ImmutableSet.copyOf(checkNotNull(tags, \"tags\"));\n         return self();\n      }\n\n      public T tags(Tag... in) {\n         return tags(ImmutableSet.copyOf(in));\n      }\n\n      public Network build() {\n         return new Network(id, account, broadcastDomainType, broadcastURI, displayText, dns1, dns2, domain, domainId, endIP, gateway, isDefault, isShared, isSystem, netmask, networkDomain, networkOfferingAvailability, networkOfferingDisplayText, networkOfferingId, networkOfferingName, related, startIP, name, state, guestIPType, vlan, trafficType, zoneId, tags, securityGroupEnabled, services);\n      }\n\n      public T fromNetwork(Network in) {\n         return this\n               .id(in.getId())\n               .account(in.getAccount())\n               .broadcastDomainType(in.getBroadcastDomainType())\n               .broadcastURI(in.getBroadcastURI())\n               .displayText(in.getDisplayText())\n               .DNS(in.getDNS())\n               .domain(in.getDomain())\n               .domainId(in.getDomainId())\n               .endIP(in.getEndIP())\n               .gateway(in.getGateway())\n               .isDefault(in.isDefault())\n               .isShared(in.isShared())\n               .isSystem(in.isSystem())\n               .netmask(in.getNetmask())\n               .networkDomain(in.getNetworkDomain())\n               .networkOfferingAvailability(in.getNetworkOfferingAvailability())\n               .networkOfferingDisplayText(in.getNetworkOfferingDisplayText())\n               .networkOfferingId(in.getNetworkOfferingId())\n               .networkOfferingName(in.getNetworkOfferingName())\n               .related(in.getRelated())\n               .startIP(in.getStartIP())\n               .name(in.getName())\n               .state(in.getState())\n               .guestIPType(in.getGuestIPType())\n               .VLAN(in.getVLAN())\n               .trafficType(in.getTrafficType())\n               .zoneId(in.getZoneId())\n               .securityGroupEnabled(in.isSecurityGroupEnabled())\n               .services(in.getServices())\n               .tags(in.getTags());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final String account;\n   private final String broadcastDomainType;\n   private final URI broadcastURI;\n   private final String displayText;\n   private final String dns1;\n   private final String dns2;\n   private final String domain;\n   private final String domainId;\n   private final String endIP;\n   private final String gateway;\n   private final boolean isDefault;\n   private final boolean isShared;\n   private final boolean isSystem;\n   private final String netmask;\n   private final String networkDomain;\n   private final String networkOfferingAvailability;\n   private final String networkOfferingDisplayText;\n   private final String networkOfferingId;\n   private final String networkOfferingName;\n   private final String related;\n   private final String startIP;\n   private final String name;\n   private final String state;\n   private final GuestIPType guestIPType;\n   private final String vlan;\n   private final TrafficType trafficType;\n   private final String zoneId;\n   private final Set<Tag> tags;\n   private final boolean securityGroupEnabled;\n   private final Set<? extends NetworkService> services;\n\n   @ConstructorProperties({\n         \"id\", \"account\", \"broadcastdomaintype\", \"broadcasturi\", \"displaytext\", \"dns1\", \"dns2\", \"domain\", \"domainid\", \"endip\", \"gateway\", \"isdefault\", \"isshared\", \"issystem\", \"netmask\", \"networkdomain\", \"networkofferingavailability\", \"networkofferingdisplaytext\", \"networkofferingid\", \"networkofferingname\", \"related\", \"startip\", \"name\", \"state\", \"type\", \"vlan\", \"traffictype\", \"zoneid\", \"tags\", \"securitygroupenabled\", \"service\"\n   })\n   protected Network(String id, @Nullable String account, @Nullable String broadcastDomainType, @Nullable URI broadcastURI,\n                     @Nullable String displayText, @Nullable String dns1, @Nullable String dns2, @Nullable String domain, @Nullable String domainId,\n                     @Nullable String endIP, @Nullable String gateway, boolean isDefault, boolean isShared, boolean isSystem,\n                     @Nullable String netmask, @Nullable String networkDomain, @Nullable String networkOfferingAvailability,\n                     @Nullable String networkOfferingDisplayText, @Nullable String networkOfferingId, @Nullable String networkOfferingName,\n                     @Nullable String related, @Nullable String startIP, @Nullable String name, @Nullable String state,\n                     @Nullable GuestIPType guestIPType, @Nullable String vlan, @Nullable TrafficType trafficType,\n                     @Nullable String zoneId, @Nullable Set<Tag> tags, boolean securityGroupEnabled, Set<? extends NetworkService> services) {\n      this.id = checkNotNull(id, \"id\");\n      this.account = account;\n      this.broadcastDomainType = broadcastDomainType;\n      this.broadcastURI = broadcastURI;\n      this.displayText = displayText;\n      this.dns1 = dns1;\n      this.dns2 = dns2;\n      this.domain = domain;\n      this.domainId = domainId;\n      this.endIP = endIP;\n      this.gateway = gateway;\n      this.isDefault = isDefault;\n      this.isShared = isShared;\n      this.isSystem = isSystem;\n      this.netmask = netmask;\n      this.networkDomain = networkDomain;\n      this.networkOfferingAvailability = networkOfferingAvailability;\n      this.networkOfferingDisplayText = networkOfferingDisplayText;\n      this.networkOfferingId = networkOfferingId;\n      this.networkOfferingName = networkOfferingName;\n      this.related = related;\n      this.startIP = startIP;\n      this.name = name;\n      this.state = state;\n      this.guestIPType = guestIPType;\n      this.vlan = vlan;\n      this.trafficType = trafficType;\n      this.zoneId = zoneId;\n      this.tags = tags != null ? ImmutableSet.copyOf(tags) : ImmutableSet.<Tag> of();\n      this.securityGroupEnabled = securityGroupEnabled;\n      this.services = ImmutableSortedSet.copyOf(services);\n   }\n\n   /**\n    * @return network id\n    */\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * @return the account associated with the network\n    */\n   @Nullable\n   public String getAccount() {\n      return this.account;\n   }\n\n   /**\n    * @return Broadcast domain type of the network\n    */\n   @Nullable\n   public String getBroadcastDomainType() {\n      return this.broadcastDomainType;\n   }\n\n   /**\n    * @return broadcast uri of the network\n    */\n   @Nullable\n   public URI getBroadcastURI() {\n      return this.broadcastURI;\n   }\n\n   /**\n    * @return the display text of the zone\n    */\n   @Nullable\n   public String getDisplayText() {\n      return this.displayText;\n   }\n\n   public List<String> getDNS() {\n      ImmutableList.Builder<String> builder = ImmutableList.builder();\n      if (dns1 != null && !\"\".equals(dns1))\n         builder.add(dns1);\n      if (dns2 != null && !\"\".equals(dns2))\n         builder.add(dns2);\n      return builder.build();\n   }\n\n   /**\n    * @return Domain name for the Network\n    */\n   @Nullable\n   public String getDomain() {\n      return this.domain;\n   }\n\n   /**\n    * @return the domain id of the Network\n    */\n   @Nullable\n   public String getDomainId() {\n      return this.domainId;\n   }\n\n   /**\n    * @return the end ip of the network\n    */\n   @Nullable\n   public String getEndIP() {\n      return this.endIP;\n   }\n\n   /**\n    * @return the network's gateway\n    */\n   @Nullable\n   public String getGateway() {\n      return this.gateway;\n   }\n\n   /**\n    * @return true if network offering is default, false otherwise\n    */\n   public boolean isDefault() {\n      return this.isDefault;\n   }\n\n   /**\n    * @return true if network offering is shared, false otherwise\n    */\n   public boolean isShared() {\n      return this.isShared;\n   }\n\n   /**\n    * @return true if network offering is system, false otherwise\n    */\n   public boolean isSystem() {\n      return this.isSystem;\n   }\n\n   /**\n    * @return the network's netmask\n    */\n   @Nullable\n   public String getNetmask() {\n      return this.netmask;\n   }\n\n   /**\n    * @return the network domain\n    */\n   @Nullable\n   public String getNetworkDomain() {\n      return this.networkDomain;\n   }\n\n   /**\n    * @return availability of the network offering the network is created from\n    */\n   @Nullable\n   public String getNetworkOfferingAvailability() {\n      return this.networkOfferingAvailability;\n   }\n\n   /**\n    * @return display text of the network offering the network is created from\n    */\n   @Nullable\n   public String getNetworkOfferingDisplayText() {\n      return this.networkOfferingDisplayText;\n   }\n\n   /**\n    * @return network offering id the network is created from\n    */\n   @Nullable\n   public String getNetworkOfferingId() {\n      return this.networkOfferingId;\n   }\n\n   /**\n    * @return name of the network offering the network is created from\n    */\n   @Nullable\n   public String getNetworkOfferingName() {\n      return this.networkOfferingName;\n   }\n\n   /**\n    * @return related to what other network configuration\n    */\n   @Nullable\n   public String getRelated() {\n      return this.related;\n   }\n\n   /**\n    * @return the start ip of the network\n    */\n   @Nullable\n   public String getStartIP() {\n      return this.startIP;\n   }\n\n   /**\n    * @return network name\n    */\n   @Nullable\n   public String getName() {\n      return this.name;\n   }\n\n   /**\n    * @return state of the network\n    */\n   @Nullable\n   public String getState() {\n      return this.state;\n   }\n\n   /**\n    * @return the GuestIPType of the network\n    */\n   public GuestIPType getGuestIPType() {\n      return this.guestIPType;\n   }\n\n   /**\n    * @return the vlan range of the zone\n    */\n   @Nullable\n   public String getVLAN() {\n      return this.vlan;\n   }\n\n   /**\n    * @return the traffic type for this network offering\n    */\n   @Nullable\n   public TrafficType getTrafficType() {\n      return this.trafficType;\n   }\n\n   /**\n    * @return zone id of the network\n    */\n   @Nullable\n   public String getZoneId() {\n      return this.zoneId;\n   }\n\n   /**\n    * @return the tags for the Network\n    */\n   public Set<Tag> getTags() {\n      return this.tags;\n   }\n\n   /**\n    * @return true if security group is enabled, false otherwise\n    */\n   public boolean isSecurityGroupEnabled() {\n      return this.securityGroupEnabled;\n   }\n\n   /**\n    * @return the list of services\n    */\n   public Set<? extends NetworkService> getServices() {\n      return this.services;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, account, broadcastDomainType, broadcastURI, displayText, dns1, dns2, domain, domainId, endIP, gateway, isDefault, isShared, isSystem, netmask, networkDomain, networkOfferingAvailability, networkOfferingDisplayText, networkOfferingId, networkOfferingName, related, startIP, name, state, guestIPType, vlan, trafficType, zoneId, tags, securityGroupEnabled, services);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Network that = Network.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n            && Objects.equal(this.account, that.account)\n            && Objects.equal(this.broadcastDomainType, that.broadcastDomainType)\n            && Objects.equal(this.broadcastURI, that.broadcastURI)\n            && Objects.equal(this.displayText, that.displayText)\n            && Objects.equal(this.dns1, that.dns1)\n            && Objects.equal(this.dns2, that.dns2)\n            && Objects.equal(this.domain, that.domain)\n            && Objects.equal(this.domainId, that.domainId)\n            && Objects.equal(this.endIP, that.endIP)\n            && Objects.equal(this.gateway, that.gateway)\n            && Objects.equal(this.isDefault, that.isDefault)\n            && Objects.equal(this.isShared, that.isShared)\n            && Objects.equal(this.isSystem, that.isSystem)\n            && Objects.equal(this.netmask, that.netmask)\n            && Objects.equal(this.networkDomain, that.networkDomain)\n            && Objects.equal(this.networkOfferingAvailability, that.networkOfferingAvailability)\n            && Objects.equal(this.networkOfferingDisplayText, that.networkOfferingDisplayText)\n            && Objects.equal(this.networkOfferingId, that.networkOfferingId)\n            && Objects.equal(this.networkOfferingName, that.networkOfferingName)\n            && Objects.equal(this.related, that.related)\n            && Objects.equal(this.startIP, that.startIP)\n            && Objects.equal(this.name, that.name)\n            && Objects.equal(this.state, that.state)\n            && Objects.equal(this.guestIPType, that.guestIPType)\n            && Objects.equal(this.vlan, that.vlan)\n            && Objects.equal(this.trafficType, that.trafficType)\n            && Objects.equal(this.zoneId, that.zoneId)\n            && Objects.equal(this.tags, that.tags)\n            && Objects.equal(this.securityGroupEnabled, that.securityGroupEnabled)\n            && Objects.equal(this.services, that.services);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"account\", account).add(\"broadcastDomainType\", broadcastDomainType).add(\"broadcastURI\", broadcastURI)\n            .add(\"displayText\", displayText).add(\"DNS1\", dns1).add(\"dns2\", dns2).add(\"domain\", domain).add(\"domainId\", domainId)\n            .add(\"endIP\", endIP).add(\"gateway\", gateway).add(\"isDefault\", isDefault).add(\"isShared\", isShared).add(\"isSystem\", isSystem)\n            .add(\"netmask\", netmask).add(\"networkDomain\", networkDomain).add(\"networkOfferingAvailability\", networkOfferingAvailability)\n            .add(\"networkOfferingDisplayText\", networkOfferingDisplayText).add(\"networkOfferingId\", networkOfferingId)\n            .add(\"networkOfferingName\", networkOfferingName).add(\"related\", related).add(\"startIP\", startIP).add(\"name\", name)\n            .add(\"state\", state).add(\"guestIPType\", guestIPType).add(\"VLAN\", vlan).add(\"trafficType\", trafficType)\n            .add(\"zoneId\", zoneId).add(\"tags\", tags).add(\"securityGroupEnabled\", securityGroupEnabled).add(\"services\", services);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/NetworkOffering.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Class NetworkOffering\n */\npublic class NetworkOffering implements Comparable<NetworkOffering> {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromNetworkOffering(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String id;\n      protected String name;\n      protected String displayText;\n      protected Date created;\n      protected NetworkOfferingAvailabilityType availability;\n      protected Integer maxConnections;\n      protected boolean isDefault;\n      protected boolean supportsVLAN;\n      protected TrafficType trafficType;\n      protected GuestIPType guestIPType;\n      protected int networkRate;\n      protected ImmutableSet.Builder<String> tags = ImmutableSet.<String>builder();\n\n      /**\n       * @see NetworkOffering#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see NetworkOffering#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /**\n       * @see NetworkOffering#getDisplayText()\n       */\n      public T displayText(String displayText) {\n         this.displayText = displayText;\n         return self();\n      }\n\n      /**\n       * @see NetworkOffering#getCreated()\n       */\n      public T created(Date created) {\n         this.created = created;\n         return self();\n      }\n\n      /**\n       * @see NetworkOffering#getAvailability()\n       */\n      public T availability(NetworkOfferingAvailabilityType availability) {\n         this.availability = availability;\n         return self();\n      }\n\n      /**\n       * @see NetworkOffering#getMaxConnections()\n       */\n      public T maxConnections(Integer maxConnections) {\n         this.maxConnections = maxConnections;\n         return self();\n      }\n\n      /**\n       * @see NetworkOffering#isDefault()\n       */\n      public T isDefault(boolean isDefault) {\n         this.isDefault = isDefault;\n         return self();\n      }\n\n      /**\n       * @see NetworkOffering#supportsVLAN()\n       */\n      public T supportsVLAN(boolean supportsVLAN) {\n         this.supportsVLAN = supportsVLAN;\n         return self();\n      }\n\n      /**\n       * @see NetworkOffering#getTrafficType()\n       */\n      public T trafficType(TrafficType trafficType) {\n         this.trafficType = trafficType;\n         return self();\n      }\n\n      /**\n       * @see NetworkOffering#getGuestIPType()\n       */\n      public T guestIPType(GuestIPType guestIPType) {\n         this.guestIPType = guestIPType;\n         return self();\n      }\n\n      /**\n       * @see NetworkOffering#getNetworkRate()\n       */\n      public T networkRate(int networkRate) {\n         this.networkRate = networkRate;\n         return self();\n      }\n      \n      /**\n       * @see NetworkOffering#getTags()\n       */\n      public T tags(Iterable<String> tags) {\n         this.tags = ImmutableSet.<String>builder().addAll(tags);\n         return self();\n      }\n      \n      /**\n       * @see NetworkOffering#getTags()\n       */\n      public T tag(String tag) {\n         this.tags.add(tag);\n         return self();\n      }\n      \n\n      public NetworkOffering build() {\n         return new NetworkOffering(id, name, displayText, created, availability, maxConnections, isDefault, supportsVLAN, trafficType, guestIPType, networkRate, tags.build());\n      }\n\n      public T fromNetworkOffering(NetworkOffering in) {\n         return this\n               .id(in.getId())\n               .name(in.getName())\n               .displayText(in.getDisplayText())\n               .created(in.getCreated())\n               .availability(in.getAvailability())\n               .maxConnections(in.getMaxConnections())\n               .isDefault(in.isDefault())\n               .supportsVLAN(in.supportsVLAN())\n               .trafficType(in.getTrafficType())\n               .guestIPType(in.getGuestIPType())\n               .networkRate(in.getNetworkRate())\n               .tags(in.getTags());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final String name;\n   private final String displayText;\n   private final Date created;\n   private final NetworkOfferingAvailabilityType availability;\n   private final Integer maxConnections;\n   private final boolean isDefault;\n   private final boolean supportsVLAN;\n   private final TrafficType trafficType;\n   private final GuestIPType guestIPType;\n   private final int networkRate;\n   private final Set<String> tags;\n\n   @ConstructorProperties({\n         \"id\", \"name\", \"displaytext\", \"created\", \"availability\", \"maxconnections\", \"isdefault\", \"specifyvlan\", \"traffictype\", \"guestiptype\", \"networkrate\", \"tags\"\n   })\n   protected NetworkOffering(String id, @Nullable String name, @Nullable String displayText, @Nullable Date created, @Nullable NetworkOfferingAvailabilityType availability, @Nullable Integer maxConnections, boolean isDefault, boolean supportsVLAN, @Nullable TrafficType trafficType, @Nullable GuestIPType guestIPType, int networkRate, @Nullable Iterable<String> tags) {\n      this.id = checkNotNull(id, \"id\");\n      this.name = name;\n      this.displayText = displayText;\n      this.created = created;\n      this.availability = availability;\n      this.maxConnections = maxConnections;\n      this.isDefault = isDefault;\n      this.supportsVLAN = supportsVLAN;\n      this.trafficType = trafficType;\n      this.guestIPType = guestIPType;\n      this.networkRate = networkRate;\n      this.tags = tags != null ? ImmutableSet.copyOf(tags) : ImmutableSet.<String> of();\n   }\n\n   /**\n    * @return the id of the network offering\n    */\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * @return the name of the network offering\n    */\n   @Nullable\n   public String getName() {\n      return this.name;\n   }\n\n   /**\n    * @return an alternate display text of the network offering.\n    */\n   @Nullable\n   public String getDisplayText() {\n      return this.displayText;\n   }\n\n   /**\n    * @return the date this network offering was created\n    */\n   @Nullable\n   public Date getCreated() {\n      return this.created;\n   }\n\n   /**\n    * @return Availability name for the offering\n    */\n   @Nullable\n   public NetworkOfferingAvailabilityType getAvailability() {\n      return this.availability;\n   }\n\n   /**\n    * @return the max number of concurrent connection the network offering\n    *         supports\n    */\n   @Nullable\n   public Integer getMaxConnections() {\n      return this.maxConnections;\n   }\n\n   /**\n    * @return true if network offering is default, false otherwise\n    */\n   public boolean isDefault() {\n      return this.isDefault;\n   }\n\n   /**\n    * @return true if network offering supports vlans, false otherwise\n    */\n   public boolean supportsVLAN() {\n      return this.supportsVLAN;\n   }\n\n   /**\n    * @return the traffic type for this network offering\n    */\n   @Nullable\n   public TrafficType getTrafficType() {\n      return this.trafficType;\n   }\n\n   /**\n    * @return the guest ip type for this network offering\n    */\n   @Nullable\n   public GuestIPType getGuestIPType() {\n      return this.guestIPType;\n   }\n\n   /**\n    * @return data transfer rate in megabits per second allowed.\n    */\n   public int getNetworkRate() {\n      return this.networkRate;\n   }\n\n   /**\n    * @return the tags for the network offering\n    */\n   public Set<String> getTags() {\n      return this.tags;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, name, displayText, created, availability, maxConnections, isDefault, supportsVLAN, trafficType, guestIPType, networkRate, tags);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      NetworkOffering that = NetworkOffering.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n            && Objects.equal(this.name, that.name)\n            && Objects.equal(this.displayText, that.displayText)\n            && Objects.equal(this.created, that.created)\n            && Objects.equal(this.availability, that.availability)\n            && Objects.equal(this.maxConnections, that.maxConnections)\n            && Objects.equal(this.isDefault, that.isDefault)\n            && Objects.equal(this.supportsVLAN, that.supportsVLAN)\n            && Objects.equal(this.trafficType, that.trafficType)\n            && Objects.equal(this.guestIPType, that.guestIPType)\n            && Objects.equal(this.networkRate, that.networkRate)\n            && Objects.equal(this.tags, that.tags);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"name\", name).add(\"displayText\", displayText).add(\"created\", created).add(\"availability\", availability).add(\"maxConnections\", maxConnections).add(\"isDefault\", isDefault).add(\"supportsVLAN\", supportsVLAN).add(\"trafficType\", trafficType).add(\"guestIPType\", guestIPType).add(\"networkRate\", networkRate).add(\"tags\", tags);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int compareTo(NetworkOffering o) {\n      return id.compareTo(o.getId());\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/NetworkOfferingAvailabilityType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.CaseFormat;\n\npublic enum NetworkOfferingAvailabilityType {\n\n   DEFAULT,\n\n   REQUIRED, /* default value for Guest Virtual network offering */\n\n   OPTIONAL, /* default value for Guest Direct network offering */\n\n   UNRECOGNIZED;\n\n   @Override\n   public String toString() {\n      return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name());\n   }\n\n   public static NetworkOfferingAvailabilityType fromValue(String type) {\n      try {\n         return valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, checkNotNull(type, \"type\")));\n      } catch (IllegalArgumentException e) {\n         return UNRECOGNIZED;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/NetworkService.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSortedMap;\nimport com.google.common.collect.ImmutableSortedSet;\nimport com.google.common.collect.Sets;\n\n/**\n * Class NetworkService\n */\npublic class NetworkService implements Comparable<NetworkService> {\n\n   public static class Capability implements Comparable<Capability> {\n\n      public static Builder<?> builder() {\n         return new ConcreteBuilder();\n      }\n\n      public Builder<?> toBuilder() {\n         return new ConcreteBuilder().fromCapability(this);\n      }\n\n      public abstract static class Builder<T extends Builder<T>> {\n         protected abstract T self();\n\n         protected String name;\n         protected String value;\n\n         /**\n          * @see Capability#getName()\n          */\n         public T name(String name) {\n            this.name = name;\n            return self();\n         }\n\n         /**\n          * @see Capability#getValue()\n          */\n         public T value(String value) {\n            this.value = value;\n            return self();\n         }\n\n         public Capability build() {\n            return new Capability(name, value);\n         }\n\n         public T fromCapability(Capability in) {\n            return this\n                  .name(in.getName())\n                  .value(in.getValue());\n         }\n\n      }\n\n      private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n         @Override\n         protected ConcreteBuilder self() {\n            return this;\n         }\n      }\n\n      private final String name;\n      private final String value;\n\n      @ConstructorProperties({\n            \"name\", \"value\"\n      })\n      protected Capability(String name, @Nullable String value) {\n         this.name = checkNotNull(name, \"name\");\n         this.value = value;\n      }\n\n      public String getName() {\n         return this.name;\n      }\n\n      @Nullable\n      public String getValue() {\n         return this.value;\n      }\n\n      @Override\n      public int hashCode() {\n         return Objects.hashCode(name, value);\n      }\n\n      @Override\n      public boolean equals(Object obj) {\n         if (this == obj) return true;\n         if (obj == null || getClass() != obj.getClass()) return false;\n         Capability that = Capability.class.cast(obj);\n         return Objects.equal(this.name, that.name)\n               && Objects.equal(this.value, that.value);\n      }\n\n      protected ToStringHelper string() {\n         return MoreObjects.toStringHelper(this)\n               .add(\"name\", name).add(\"value\", value);\n      }\n\n      @Override\n      public String toString() {\n         return string().toString();\n      }\n\n      @Override\n      public int compareTo(Capability o) {\n         return name.compareTo(o.getName());\n      }\n   }\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromNetworkService(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String name;\n      protected Set<Capability> capabilities = Sets.newHashSet();\n\n      /**\n       * @see NetworkService#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /**\n       * @see NetworkService#getCapabilities()\n       */\n      public T capabilities(Map<String, String> capabilities) {\n         for (Map.Entry<String, String> entry : capabilities.entrySet()) {\n            this.capabilities.add(Capability.builder().name(entry.getKey()).value(entry.getValue()).build());\n         }\n         return self();\n      }\n\n      public NetworkService build() {\n         return new NetworkService(name, capabilities);\n      }\n\n      public T fromNetworkService(NetworkService in) {\n         return this\n               .name(in.getName())\n               .capabilities(in.getCapabilities());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String name;\n   private final Set<Capability> capabilities;\n\n   @ConstructorProperties({\n         \"name\", \"capability\"\n   })\n   protected NetworkService(String name, @Nullable Set<Capability> capabilities) {\n      this.name = checkNotNull(name, \"name\");\n      this.capabilities = capabilities == null ? ImmutableSet.<Capability>of() : ImmutableSortedSet.copyOf(capabilities);\n   }\n\n   public String getName() {\n      return this.name;\n   }\n\n   public Map<String, String> getCapabilities() {\n      // so tests and serialization comes out expected\n      ImmutableSortedMap.Builder<String, String> returnVal = ImmutableSortedMap.naturalOrder();\n      for (Capability capability : capabilities) {\n         returnVal.put(capability.name, capability.value);\n      }\n      return returnVal.build();\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(name, capabilities);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      NetworkService that = NetworkService.class.cast(obj);\n      return Objects.equal(this.name, that.name)\n            && Objects.equal(this.capabilities, that.capabilities);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).add(\"name\", name).add(\"capabilities\", capabilities);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int compareTo(NetworkService o) {\n      return name.compareTo(o.getName());\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/NetworkType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.CaseFormat;\n\n/**\n * @see TemplateApi#listZones\n */\npublic enum NetworkType {\n   BASIC,\n\n   ADVANCED,\n\n   UNRECOGNIZED;\n\n   @Override\n   public String toString() {\n      return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name());\n   }\n\n   public static NetworkType fromValue(String type) {\n      try {\n         return valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, checkNotNull(type, \"type\")));\n      } catch (IllegalArgumentException e) {\n         return UNRECOGNIZED;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/OSType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Class OSType\n */\npublic class OSType implements Comparable<OSType> {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromOSType(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String id;\n      protected String OSCategoryId;\n      protected String description;\n\n      /**\n       * @see OSType#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see OSType#getOSCategoryId()\n       */\n      public T OSCategoryId(String OSCategoryId) {\n         this.OSCategoryId = OSCategoryId;\n         return self();\n      }\n\n      /**\n       * @see OSType#getDescription()\n       */\n      public T description(String description) {\n         this.description = description;\n         return self();\n      }\n\n      public OSType build() {\n         return new OSType(id, OSCategoryId, description);\n      }\n\n      public T fromOSType(OSType in) {\n         return this\n               .id(in.getId())\n               .OSCategoryId(in.getOSCategoryId())\n               .description(in.getDescription());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final String OSCategoryId;\n   private final String description;\n\n   @ConstructorProperties({\n         \"id\", \"oscategoryid\", \"description\"\n   })\n   protected OSType(String id, @Nullable String OSCategoryId, @Nullable String description) {\n      this.id = checkNotNull(id, \"id\");\n      this.OSCategoryId = OSCategoryId;\n      this.description = description;\n   }\n\n   /**\n    * @return the ID of the OS type\n    */\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * @return the ID of the OS category\n    */\n   @Nullable\n   public String getOSCategoryId() {\n      return this.OSCategoryId;\n   }\n\n   /**\n    * @return the name/description of the OS type\n    */\n   @Nullable\n   public String getDescription() {\n      return this.description;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, OSCategoryId, description);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      OSType that = OSType.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n            && Objects.equal(this.OSCategoryId, that.OSCategoryId)\n            && Objects.equal(this.description, that.description);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).add(\"id\", id).add(\"OSCategoryId\", OSCategoryId).add(\"description\", description);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int compareTo(OSType o) {\n      return id.compareTo(o.getId());\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/PermissionOperation.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\npublic enum PermissionOperation {\n\n   add, remove, reset, UNRECOGNIZED;\n\n   public static PermissionOperation fromValue(String format) {\n      try {\n         return valueOf(checkNotNull(format, \"format\"));\n      } catch (IllegalArgumentException e) {\n         return UNRECOGNIZED;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/Pod.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Represents a Pod in CloudStack.\n */\npublic class Pod implements Comparable<Pod> {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromPod(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String id;\n      protected String name;\n      protected String zoneId;\n      protected String zoneName;\n      protected String gateway;\n      protected String netmask;\n      protected String startIp;\n      protected String endIp;\n      protected AllocationState allocationState;\n\n      /**\n       * @see Pod#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see Pod#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /**\n       * @see Pod#getZoneId()\n       */\n      public T zoneId(String zoneId) {\n         this.zoneId = zoneId;\n         return self();\n      }\n\n      /**\n       * @see Pod#getZoneName()\n       */\n      public T zoneName(String zoneName) {\n         this.zoneName = zoneName;\n         return self();\n      }\n\n      /**\n       * @see Pod#getGateway()\n       */\n      public T gateway(String gateway) {\n         this.gateway = gateway;\n         return self();\n      }\n\n      /**\n       * @see Pod#getNetmask()\n       */\n      public T netmask(String netmask) {\n         this.netmask = netmask;\n         return self();\n      }\n\n      /**\n       * @see Pod#getStartIp()\n       */\n      public T startIp(String startIp) {\n         this.startIp = startIp;\n         return self();\n      }\n\n      /**\n       * @see Pod#getEndIp()\n       */\n      public T endIp(String endIp) {\n         this.endIp = endIp;\n         return self();\n      }\n\n      /**\n       * @see Pod#getAllocationState()\n       */\n      public T allocationState(AllocationState allocationState) {\n         this.allocationState = allocationState;\n         return self();\n      }\n\n      public Pod build() {\n         return new Pod(id, name, zoneId, zoneName, gateway, netmask, startIp, endIp, allocationState);\n      }\n\n      public T fromPod(Pod in) {\n         return this\n               .id(in.getId())\n               .name(in.getName())\n               .zoneId(in.getZoneId())\n               .zoneName(in.getZoneName())\n               .gateway(in.getGateway())\n               .netmask(in.getNetmask())\n               .startIp(in.getStartIp())\n               .endIp(in.getEndIp())\n               .allocationState(in.getAllocationState());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final String name;\n   private final String zoneId;\n   private final String zoneName;\n   private final String gateway;\n   private final String netmask;\n   private final String startIp;\n   private final String endIp;\n   private final AllocationState allocationState;\n\n   @ConstructorProperties({\n         \"id\", \"name\", \"zoneid\", \"zonename\", \"gateway\", \"netmask\", \"startip\", \"endip\", \"allocationstate\"\n   })\n   protected Pod(String id, @Nullable String name, @Nullable String zoneId, @Nullable String zoneName, @Nullable String gateway, @Nullable String netmask, @Nullable String startIp, @Nullable String endIp, @Nullable AllocationState allocationState) {\n      this.id = checkNotNull(id, \"id\");\n      this.name = name;\n      this.zoneId = zoneId;\n      this.zoneName = zoneName;\n      this.gateway = gateway;\n      this.netmask = netmask;\n      this.startIp = startIp;\n      this.endIp = endIp;\n      this.allocationState = allocationState;\n   }\n\n   /**\n    * @return id the ID of the Pod\n    */\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * @return name the name of the Pod\n    */\n   @Nullable\n   public String getName() {\n      return this.name;\n   }\n\n   /**\n    * @return zoneId the Zone ID of the Pod\n    */\n   @Nullable\n   public String getZoneId() {\n      return this.zoneId;\n   }\n\n   /**\n    * @return zoneName the Zone name of the Pod\n    */\n   @Nullable\n   public String getZoneName() {\n      return this.zoneName;\n   }\n\n   /**\n    * @return gateway the gateway of the Pod\n    */\n   @Nullable\n   public String getGateway() {\n      return this.gateway;\n   }\n\n   /**\n    * @return netmask the netmask of the Pod\n    */\n   @Nullable\n   public String getNetmask() {\n      return this.netmask;\n   }\n\n   /**\n    * @return startIp the starting IP for the Pod\n    */\n   @Nullable\n   public String getStartIp() {\n      return this.startIp;\n   }\n\n   /**\n    * @return endIp the ending IP for the Pod\n    */\n   @Nullable\n   public String getEndIp() {\n      return this.endIp;\n   }\n\n   /**\n    * @return the allocation state of the cluster\n    */\n   @Nullable\n   public AllocationState getAllocationState() {\n      return this.allocationState;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, name, zoneId, zoneName, gateway, netmask, startIp, endIp, allocationState);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Pod that = Pod.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n            && Objects.equal(this.name, that.name)\n            && Objects.equal(this.zoneId, that.zoneId)\n            && Objects.equal(this.zoneName, that.zoneName)\n            && Objects.equal(this.gateway, that.gateway)\n            && Objects.equal(this.netmask, that.netmask)\n            && Objects.equal(this.startIp, that.startIp)\n            && Objects.equal(this.endIp, that.endIp)\n            && Objects.equal(this.allocationState, that.allocationState);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"name\", name).add(\"zoneId\", zoneId).add(\"zoneName\", zoneName).add(\"gateway\", gateway).add(\"netmask\", netmask).add(\"startIp\", startIp).add(\"endIp\", endIp).add(\"allocationState\", allocationState);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int compareTo(Pod other) {\n      return this.id.compareTo(other.id);\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/PortForwardingRule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.CaseFormat;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Class PortForwardingRule\n */\npublic class PortForwardingRule implements Comparable<PortForwardingRule> {\n\n   public static enum Protocol {\n      TCP,\n      UDP,\n      ICMP,\n      UNKNOWN;\n\n      public static Protocol fromValue(String value) {\n         try {\n            return valueOf(value.toUpperCase());\n         } catch (IllegalArgumentException e) {\n            return UNKNOWN;\n         }\n      }\n\n      @Override\n      public String toString() {\n         return name().toLowerCase();\n      }\n   }\n\n   public static enum State {\n      STAGED,     // Rule been created but has never got through network rule conflict detection.\n      // Rules in this state can not be sent to network elements.\n      ADD,        // Add means the rule has been created and has gone through network rule conflict detection.\n      ACTIVE,     // Rule has been sent to the network elements and reported to be active.\n      DELETING,  // Revoke means this rule has been revoked. If this rule has been sent to the\n      // network elements, the rule will be deleted from database.\n      UNKNOWN;\n\n      public static State fromValue(String value) {\n         try {\n            return valueOf(value.toUpperCase());\n         } catch (IllegalArgumentException e) {\n            return UNKNOWN;\n         }\n      }\n\n      @Override\n      public String toString() {\n         return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name());\n      }\n   }\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromPortForwardingRule(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String id;\n      protected String IPAddress;\n      protected String IPAddressId;\n      protected int privatePort;\n      protected Protocol protocol;\n      protected int publicPort;\n      protected State state;\n      protected String virtualMachineDisplayName;\n      protected String virtualMachineId;\n      protected String virtualMachineName;\n      protected Set<String> CIDRs = ImmutableSet.of();\n      protected int privateEndPort;\n      protected int publicEndPort;\n      protected Set<Tag> tags = ImmutableSet.of();\n\n      /**\n       * @see PortForwardingRule#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see PortForwardingRule#getIPAddress()\n       */\n      public T IPAddress(String IPAddress) {\n         this.IPAddress = IPAddress;\n         return self();\n      }\n\n      /**\n       * @see PortForwardingRule#getIPAddressId()\n       */\n      public T IPAddressId(String IPAddressId) {\n         this.IPAddressId = IPAddressId;\n         return self();\n      }\n\n      /**\n       * @see PortForwardingRule#getPrivatePort()\n       */\n      public T privatePort(int privatePort) {\n         this.privatePort = privatePort;\n         return self();\n      }\n\n      /**\n       * @see PortForwardingRule#getProtocol()\n       */\n      public T protocol(Protocol protocol) {\n         this.protocol = protocol;\n         return self();\n      }\n\n      /**\n       * @see PortForwardingRule#getPublicPort()\n       */\n      public T publicPort(int publicPort) {\n         this.publicPort = publicPort;\n         return self();\n      }\n\n      /**\n       * @see PortForwardingRule#getState()\n       */\n      public T state(State state) {\n         this.state = state;\n         return self();\n      }\n\n      /**\n       * @see PortForwardingRule#getVirtualMachineDisplayName()\n       */\n      public T virtualMachineDisplayName(String virtualMachineDisplayName) {\n         this.virtualMachineDisplayName = virtualMachineDisplayName;\n         return self();\n      }\n\n      /**\n       * @see PortForwardingRule#getVirtualMachineId()\n       */\n      public T virtualMachineId(String virtualMachineId) {\n         this.virtualMachineId = virtualMachineId;\n         return self();\n      }\n\n      /**\n       * @see PortForwardingRule#getVirtualMachineName()\n       */\n      public T virtualMachineName(String virtualMachineName) {\n         this.virtualMachineName = virtualMachineName;\n         return self();\n      }\n\n      /**\n       * @see PortForwardingRule#getCIDRs()\n       */\n      public T CIDRs(Set<String> CIDRs) {\n         this.CIDRs = ImmutableSet.copyOf(checkNotNull(CIDRs, \"CIDRs\"));\n         return self();\n      }\n\n      public T CIDRs(String... in) {\n         return CIDRs(ImmutableSet.copyOf(in));\n      }\n\n      /**\n       * @see PortForwardingRule#getPrivateEndPort()\n       */\n      public T privateEndPort(int privateEndPort) {\n         this.privateEndPort = privateEndPort;\n         return self();\n      }\n\n      /**\n       * @see PortForwardingRule#getPublicEndPort()\n       */\n      public T publicEndPort(int publicEndPort) {\n         this.publicEndPort = publicEndPort;\n         return self();\n      }\n\n      /**\n       * @see PortForwardingRule#getTags()\n       */\n      public T tags(Set<Tag> tags) {\n         this.tags = ImmutableSet.copyOf(checkNotNull(tags, \"tags\"));\n         return self();\n      }\n\n      public T tags(Tag... in) {\n         return tags(ImmutableSet.copyOf(in));\n      }\n\n      public PortForwardingRule build() {\n         return new PortForwardingRule(id, IPAddress, IPAddressId, privatePort, protocol, publicPort, state, virtualMachineDisplayName,\n               virtualMachineId, virtualMachineName, CIDRs, privateEndPort, publicEndPort, tags);\n      }\n\n      public T fromPortForwardingRule(PortForwardingRule in) {\n         return this\n               .id(in.getId())\n               .IPAddress(in.getIPAddress())\n               .IPAddressId(in.getIPAddressId())\n               .privatePort(in.getPrivatePort())\n               .protocol(in.getProtocol())\n               .publicPort(in.getPublicPort())\n               .state(in.getState())\n               .virtualMachineDisplayName(in.getVirtualMachineDisplayName())\n               .virtualMachineId(in.getVirtualMachineId())\n               .virtualMachineName(in.getVirtualMachineName())\n               .CIDRs(in.getCIDRs())\n               .privateEndPort(in.getPrivateEndPort())\n               .publicEndPort(in.getPublicEndPort())\n               .tags(in.getTags());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final String IPAddress;\n   private final String IPAddressId;\n   private final int privatePort;\n   private final PortForwardingRule.Protocol protocol;\n   private final int publicPort;\n   private final PortForwardingRule.State state;\n   private final String virtualMachineDisplayName;\n   private final String virtualMachineId;\n   private final String virtualMachineName;\n   private final Set<String> CIDRs;\n   private final int privateEndPort;\n   private final int publicEndPort;\n   private final Set<Tag> tags;\n\n   @ConstructorProperties({\n         \"id\", \"ipaddress\", \"ipaddressid\", \"privateport\", \"protocol\", \"publicport\", \"state\", \"virtualmachinedisplayname\",\n         \"virtualmachineid\", \"virtualmachinename\", \"cidrlist\", \"privateendport\", \"publicendport\", \"tags\"\n   })\n   private PortForwardingRule(String id, @Nullable String IPAddress, @Nullable String IPAddressId, int privatePort,\n                              @Nullable Protocol protocol, int publicPort, @Nullable State state, @Nullable String virtualMachineDisplayName,\n                              @Nullable String virtualMachineId, @Nullable String virtualMachineName, @Nullable String CIDRs,\n                              int privateEndPort, int publicEndPort, @Nullable Set<Tag> tags) {\n      this(id, IPAddress, IPAddressId, privatePort, protocol, publicPort, state, virtualMachineDisplayName, virtualMachineId,\n            virtualMachineName, splitStringOnCommas(CIDRs), privateEndPort, publicEndPort, tags);\n   }\n\n   private static Set<String> splitStringOnCommas(String in) {\n      return in == null ? ImmutableSet.<String>of() : ImmutableSet.copyOf(in.split(\",\"));\n   }\n\n   protected PortForwardingRule(String id, @Nullable String IPAddress, @Nullable String IPAddressId, int privatePort,\n                                @Nullable Protocol protocol, int publicPort, @Nullable State state,\n                                @Nullable String virtualMachineDisplayName, @Nullable String virtualMachineId,\n                                @Nullable String virtualMachineName, @Nullable Set<String> CIDRs, int privateEndPort,\n                                int publicEndPort, @Nullable Set<Tag> tags) {\n      this.id = checkNotNull(id, \"id\");\n      this.IPAddress = IPAddress;\n      this.IPAddressId = IPAddressId;\n      this.privatePort = privatePort;\n      this.protocol = protocol;\n      this.publicPort = publicPort;\n      this.state = state;\n      this.virtualMachineDisplayName = virtualMachineDisplayName;\n      this.virtualMachineId = virtualMachineId;\n      this.virtualMachineName = virtualMachineName;\n      this.CIDRs = CIDRs == null ? ImmutableSet.<String>of() : ImmutableSet.copyOf(CIDRs);\n      this.privateEndPort = privateEndPort;\n      this.publicEndPort = publicEndPort;\n      this.tags = tags != null ? ImmutableSet.copyOf(tags) : ImmutableSet.<Tag> of();\n   }\n\n   /**\n    * @return the ID of the port forwarding rule\n    */\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * @return the public ip address for the port forwarding rule\n    */\n   @Nullable\n   public String getIPAddress() {\n      return this.IPAddress;\n   }\n\n   /**\n    * @return the public ip address id for the port forwarding rule\n    */\n   @Nullable\n   public String getIPAddressId() {\n      return this.IPAddressId;\n   }\n\n   /**\n    * @return the private port for the port forwarding rule\n    */\n   public int getPrivatePort() {\n      return this.privatePort;\n   }\n\n   /**\n    * @return the protocol of the port forwarding rule\n    */\n   @Nullable\n   public Protocol getProtocol() {\n      return this.protocol;\n   }\n\n   /**\n    * @return the public port for the port forwarding rule\n    */\n   public int getPublicPort() {\n      return this.publicPort;\n   }\n\n   /**\n    * @return the state of the rule\n    */\n   @Nullable\n   public State getState() {\n      return this.state;\n   }\n\n   /**\n    * @return the VM display name for the port forwarding rule\n    */\n   @Nullable\n   public String getVirtualMachineDisplayName() {\n      return this.virtualMachineDisplayName;\n   }\n\n   /**\n    * @return the VM ID for the port forwarding rule\n    */\n   @Nullable\n   public String getVirtualMachineId() {\n      return this.virtualMachineId;\n   }\n\n   /**\n    * @return the VM name for the port forwarding rule\n    */\n   @Nullable\n   public String getVirtualMachineName() {\n      return this.virtualMachineName;\n   }\n\n   /**\n    * @return the cidr list to forward traffic from\n    */\n   public Set<String> getCIDRs() {\n      return this.CIDRs;\n   }\n\n   /**\n    * @return the starting port of port forwarding rule's private port range\n    */\n   public int getPrivateEndPort() {\n      return this.privateEndPort;\n   }\n\n   /**\n    * @return the starting port of port forwarding rule's public port range\n    */\n   public int getPublicEndPort() {\n      return this.publicEndPort;\n   }\n\n   /**\n    * @return the tags for the rule\n    */\n   public Set<Tag> getTags() {\n      return this.tags;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, IPAddress, IPAddressId, privatePort, protocol, publicPort, state, virtualMachineDisplayName, virtualMachineId, virtualMachineName, CIDRs, privateEndPort, publicEndPort, tags);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      PortForwardingRule that = PortForwardingRule.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n            && Objects.equal(this.IPAddress, that.IPAddress)\n            && Objects.equal(this.IPAddressId, that.IPAddressId)\n            && Objects.equal(this.privatePort, that.privatePort)\n            && Objects.equal(this.protocol, that.protocol)\n            && Objects.equal(this.publicPort, that.publicPort)\n            && Objects.equal(this.state, that.state)\n            && Objects.equal(this.virtualMachineDisplayName, that.virtualMachineDisplayName)\n            && Objects.equal(this.virtualMachineId, that.virtualMachineId)\n            && Objects.equal(this.virtualMachineName, that.virtualMachineName)\n            && Objects.equal(this.CIDRs, that.CIDRs)\n            && Objects.equal(this.privateEndPort, that.privateEndPort)\n            && Objects.equal(this.publicEndPort, that.publicEndPort)\n            && Objects.equal(this.tags, that.tags);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"IPAddress\", IPAddress).add(\"IPAddressId\", IPAddressId).add(\"privatePort\", privatePort)\n            .add(\"protocol\", protocol).add(\"publicPort\", publicPort).add(\"state\", state).add(\"virtualMachineDisplayName\", virtualMachineDisplayName)\n            .add(\"virtualMachineId\", virtualMachineId).add(\"virtualMachineName\", virtualMachineName).add(\"CIDRs\", CIDRs)\n            .add(\"privateEndPort\", privateEndPort).add(\"publicEndPort\", publicEndPort).add(\"tags\", tags);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int compareTo(PortForwardingRule o) {\n      return id.compareTo(o.getId());\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/Project.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Set;\n\nimport com.google.common.collect.ImmutableSet;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.CaseFormat;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Representation of the API project response\n */\npublic class Project implements Comparable<Project> {\n\n   public static enum State {\n      ACTIVE, DISABLED, SUSPENDED, UNRECOGNIZED;\n\n      @Override\n      public String toString() {\n         return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_HYPHEN, name());\n      }\n\n      public static State fromValue(String state) {\n         try {\n            return valueOf(CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_UNDERSCORE, checkNotNull(state, \"state\")));\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n\n   }\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromDomain(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String id;\n      protected String account;\n      protected String displayText;\n      protected String domain;\n      protected String domainId;\n      protected String name;\n      protected State state;\n      protected Set<Tag> tags = ImmutableSet.of();\n\n      /**\n       * @see org.jclouds.cloudstack.domain.Project#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see org.jclouds.cloudstack.domain.Project#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /**\n       * @see org.jclouds.cloudstack.domain.Project#getDomainId()\n       */\n      public T domainId(String domainId) {\n         this.domainId = domainId;\n         return self();\n      }\n\n      /**\n       * @see org.jclouds.cloudstack.domain.Project#getDomain()\n       */\n      public T domain(String domain) {\n         this.domain = domain;\n         return self();\n      }\n\n      /**\n       * @see org.jclouds.cloudstack.domain.Project#getAccount()\n       */\n      public T account(String account) {\n         this.account = account;\n         return self();\n      }\n\n      /**\n       * @see org.jclouds.cloudstack.domain.Project#getDisplayText()\n       */\n      public T displayText(String displayText) {\n         this.displayText = displayText;\n         return self();\n      }\n\n      /**\n       * @see org.jclouds.cloudstack.domain.Project#getState()\n       */\n      public T state(State state) {\n         this.state = state;\n         return self();\n      }\n\n      /**\n       * @see Project#getTags()\n       */\n      public T tags(Set<Tag> tags) {\n         this.tags = ImmutableSet.copyOf(checkNotNull(tags, \"tags\"));\n         return self();\n      }\n\n      public T tags(Tag... in) {\n         return tags(ImmutableSet.copyOf(in));\n      }\n\n      public Project build() {\n         return new Project(id, account, displayText, domain, domainId, name, state, tags);\n      }\n\n      public T fromDomain(Project in) {\n         return this\n               .id(in.getId())\n               .account(in.getAccount())\n               .displayText(in.getDisplayText())\n               .domain(in.getDomain())\n               .domainId(in.getDomainId())\n               .name(in.getName())\n               .state(in.getState())\n               .tags(in.getTags());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final String account;\n   private final String displayText;\n   private final String domain;\n   private final String domainId;\n   private final String name;\n   private final State state;\n   private final Set<Tag> tags;\n\n   @ConstructorProperties({\n         \"id\", \"account\", \"displaytext\", \"domain\", \"domainid\", \"name\", \"state\", \"tags\"\n   })\n   protected Project(String id, String account, String displayText, String domain, String domainId,\n                     String name, State state, @Nullable Set<Tag> tags) {\n      this.id = checkNotNull(id, \"id\");\n      this.account = account;\n      this.displayText = displayText;\n      this.domain = domain;\n      this.domainId = domainId;\n      this.name = name;\n      this.state = checkNotNull(state, \"state\");\n      this.tags = tags != null ? ImmutableSet.copyOf(tags) : ImmutableSet.<Tag> of();\n   }\n\n   public String getId() {\n      return this.id;\n   }\n\n   @Nullable\n   public String getAccount() {\n      return this.account;\n   }\n\n   @Nullable\n   public String getDisplayText() {\n      return this.displayText;\n   }\n\n   @Nullable\n   public String getDomain() {\n      return this.domain;\n   }\n\n   @Nullable\n   public String getDomainId() {\n      return this.domainId;\n   }\n\n   @Nullable\n   public String getName() {\n      return this.name;\n   }\n\n   public State getState() {\n      return this.state;\n   }\n\n   /**\n    * @return the tags for the project\n    */\n   public Set<Tag> getTags() {\n      return this.tags;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, account, displayText, domain, domainId, name, state, tags);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Project that = Project.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n            && Objects.equal(this.account, that.account)\n            && Objects.equal(this.displayText, that.displayText)\n            && Objects.equal(this.domain, that.domain)\n            && Objects.equal(this.domainId, that.domainId)\n            && Objects.equal(this.name, that.name)\n            && Objects.equal(this.state, that.state)\n            && Objects.equal(this.tags, that.tags);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).omitNullValues()\n            .add(\"id\", id).add(\"account\", account).add(\"displayText\", displayText)\n            .add(\"domain\", domain).add(\"domainId\", domainId).add(\"name\", name).add(\"state\", state)\n            .add(\"tags\", tags);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int compareTo(Project other) {\n      return id.compareTo(other.getId());\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/PublicIPAddress.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\nimport java.util.Set;\n\nimport com.google.common.collect.ImmutableSet;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.CaseFormat;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Class PublicIPAddress\n */\npublic class PublicIPAddress {\n\n   /**\n    */\n   public static enum State {\n      ALLOCATING, ALLOCATED, RELEASING, UNRECOGNIZED;\n\n      @Override\n      public String toString() {\n         return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name());\n      }\n\n      public static State fromValue(String state) {\n         try {\n            return valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, checkNotNull(state, \"state\")));\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n\n   }\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromPublicIPAddress(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String id;\n      protected String account;\n      protected Date allocated;\n      protected String associatedNetworkId;\n      protected String domain;\n      protected String domainId;\n      protected boolean usesVirtualNetwork;\n      protected String IPAddress;\n      protected boolean isSourceNAT;\n      protected boolean isStaticNAT;\n      protected String networkId;\n      protected PublicIPAddress.State state;\n      protected String virtualMachineDisplayName;\n      protected String virtualMachineId;\n      protected String virtualMachineName;\n      protected String VLANId;\n      protected String VLANName;\n      protected String zoneId;\n      protected String zoneName;\n      protected String jobId;\n      protected Integer jobStatus;\n      protected Set<Tag> tags = ImmutableSet.of();\n\n      /**\n       * @see PublicIPAddress#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see PublicIPAddress#getAccount()\n       */\n      public T account(String account) {\n         this.account = account;\n         return self();\n      }\n\n      /**\n       * @see PublicIPAddress#getAllocated()\n       */\n      public T allocated(Date allocated) {\n         this.allocated = allocated;\n         return self();\n      }\n\n      /**\n       * @see PublicIPAddress#getAssociatedNetworkId()\n       */\n      public T associatedNetworkId(String associatedNetworkId) {\n         this.associatedNetworkId = associatedNetworkId;\n         return self();\n      }\n\n      /**\n       * @see PublicIPAddress#getDomain()\n       */\n      public T domain(String domain) {\n         this.domain = domain;\n         return self();\n      }\n\n      /**\n       * @see PublicIPAddress#getDomainId()\n       */\n      public T domainId(String domainId) {\n         this.domainId = domainId;\n         return self();\n      }\n\n      /**\n       * @see PublicIPAddress#isUsesVirtualNetwork()\n       */\n      public T usesVirtualNetwork(boolean usesVirtualNetwork) {\n         this.usesVirtualNetwork = usesVirtualNetwork;\n         return self();\n      }\n\n      /**\n       * @see PublicIPAddress#getIPAddress()\n       */\n      public T IPAddress(String IPAddress) {\n         this.IPAddress = IPAddress;\n         return self();\n      }\n\n      /**\n       * @see PublicIPAddress#isSourceNAT()\n       */\n      public T isSourceNAT(boolean isSourceNAT) {\n         this.isSourceNAT = isSourceNAT;\n         return self();\n      }\n\n      /**\n       * @see PublicIPAddress#isStaticNAT()\n       */\n      public T isStaticNAT(boolean isStaticNAT) {\n         this.isStaticNAT = isStaticNAT;\n         return self();\n      }\n\n      /**\n       * @see PublicIPAddress#getNetworkId()\n       */\n      public T networkId(String networkId) {\n         this.networkId = networkId;\n         return self();\n      }\n\n      /**\n       * @see PublicIPAddress#getState()\n       */\n      public T state(PublicIPAddress.State state) {\n         this.state = state;\n         return self();\n      }\n\n      /**\n       * @see PublicIPAddress#getVirtualMachineDisplayName()\n       */\n      public T virtualMachineDisplayName(String virtualMachineDisplayName) {\n         this.virtualMachineDisplayName = virtualMachineDisplayName;\n         return self();\n      }\n\n      /**\n       * @see PublicIPAddress#getVirtualMachineId()\n       */\n      public T virtualMachineId(String virtualMachineId) {\n         this.virtualMachineId = virtualMachineId;\n         return self();\n      }\n\n      /**\n       * @see PublicIPAddress#getVirtualMachineName()\n       */\n      public T virtualMachineName(String virtualMachineName) {\n         this.virtualMachineName = virtualMachineName;\n         return self();\n      }\n\n      /**\n       * @see PublicIPAddress#getVLANId()\n       */\n      public T VLANId(String VLANId) {\n         this.VLANId = VLANId;\n         return self();\n      }\n\n      /**\n       * @see PublicIPAddress#getVLANName()\n       */\n      public T VLANName(String VLANName) {\n         this.VLANName = VLANName;\n         return self();\n      }\n\n      /**\n       * @see PublicIPAddress#getZoneId()\n       */\n      public T zoneId(String zoneId) {\n         this.zoneId = zoneId;\n         return self();\n      }\n\n      /**\n       * @see PublicIPAddress#getZoneName()\n       */\n      public T zoneName(String zoneName) {\n         this.zoneName = zoneName;\n         return self();\n      }\n\n      /**\n       * @see PublicIPAddress#getJobId()\n       */\n      public T jobId(String jobId) {\n         this.jobId = jobId;\n         return self();\n      }\n\n      /**\n       * @see PublicIPAddress#getJobStatus()\n       */\n      public T jobStatus(Integer jobStatus) {\n         this.jobStatus = jobStatus;\n         return self();\n      }\n\n      /**\n       * @see PublicIPAddress#getTags()\n       */\n      public T tags(Set<Tag> tags) {\n         this.tags = ImmutableSet.copyOf(checkNotNull(tags, \"tags\"));\n         return self();\n      }\n\n      public T tags(Tag... in) {\n         return tags(ImmutableSet.copyOf(in));\n      }\n\n      public PublicIPAddress build() {\n         return new PublicIPAddress(id, account, allocated, associatedNetworkId, domain, domainId, usesVirtualNetwork, IPAddress, isSourceNAT, isStaticNAT, networkId, state, virtualMachineDisplayName, virtualMachineId, virtualMachineName, VLANId, VLANName, zoneId, zoneName, jobId, jobStatus, tags);\n      }\n\n      public T fromPublicIPAddress(PublicIPAddress in) {\n         return this\n               .id(in.getId())\n               .account(in.getAccount())\n               .allocated(in.getAllocated())\n               .associatedNetworkId(in.getAssociatedNetworkId())\n               .domain(in.getDomain())\n               .domainId(in.getDomainId())\n               .usesVirtualNetwork(in.isUsesVirtualNetwork())\n               .IPAddress(in.getIPAddress())\n               .isSourceNAT(in.isSourceNAT())\n               .isStaticNAT(in.isStaticNAT())\n               .networkId(in.getNetworkId())\n               .state(in.getState())\n               .virtualMachineDisplayName(in.getVirtualMachineDisplayName())\n               .virtualMachineId(in.getVirtualMachineId())\n               .virtualMachineName(in.getVirtualMachineName())\n               .VLANId(in.getVLANId())\n               .VLANName(in.getVLANName())\n               .zoneId(in.getZoneId())\n               .zoneName(in.getZoneName())\n               .jobId(in.getJobId())\n               .jobStatus(in.getJobStatus())\n               .tags(in.getTags());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final String account;\n   private final Date allocated;\n   private final String associatedNetworkId;\n   private final String domain;\n   private final String domainId;\n   private final boolean usesVirtualNetwork;\n   private final String IPAddress;\n   private final boolean isSourceNAT;\n   private final boolean isStaticNAT;\n   private final String networkId;\n   private final PublicIPAddress.State state;\n   private final String virtualMachineDisplayName;\n   private final String virtualMachineId;\n   private final String virtualMachineName;\n   private final String VLANId;\n   private final String VLANName;\n   private final String zoneId;\n   private final String zoneName;\n   private final String jobId;\n   private final Integer jobStatus;\n   private final Set<Tag> tags;\n\n   @ConstructorProperties({\n         \"id\", \"account\", \"allocated\", \"associatednetworkid\", \"domain\", \"domainid\", \"forvirtualnetwork\", \"ipaddress\", \"issourcenat\",\n         \"isstaticnat\", \"networkid\", \"state\", \"virtualmachinedisplayname\", \"virtualmachineid\", \"virtualmachinename\", \"VLANid\",\n         \"VLANname\", \"zoneid\", \"zonename\", \"jobid\", \"jobstatus\", \"tags\"\n   })\n   protected PublicIPAddress(String id, @Nullable String account, @Nullable Date allocated, @Nullable String associatedNetworkId,\n                             @Nullable String domain, @Nullable String domainId, boolean usesVirtualNetwork, @Nullable String IPAddress,\n                             boolean isSourceNAT, boolean isStaticNAT, @Nullable String networkId, @Nullable PublicIPAddress.State state,\n                             @Nullable String virtualMachineDisplayName, @Nullable String virtualMachineId, @Nullable String virtualMachineName,\n                             @Nullable String VLANId, @Nullable String VLANName, @Nullable String zoneId, @Nullable String zoneName,\n                             @Nullable String jobId, @Nullable Integer jobStatus, @Nullable Set<Tag> tags) {\n      this.id = checkNotNull(id, \"id\");\n      this.account = account;\n      this.allocated = allocated;\n      this.associatedNetworkId = associatedNetworkId;\n      this.domain = domain;\n      this.domainId = domainId;\n      this.usesVirtualNetwork = usesVirtualNetwork;\n      this.IPAddress = IPAddress;\n      this.isSourceNAT = isSourceNAT;\n      this.isStaticNAT = isStaticNAT;\n      this.networkId = networkId;\n      this.state = state;\n      this.virtualMachineDisplayName = virtualMachineDisplayName;\n      this.virtualMachineId = virtualMachineId;\n      this.virtualMachineName = virtualMachineName;\n      this.VLANId = VLANId;\n      this.VLANName = VLANName;\n      this.zoneId = zoneId;\n      this.zoneName = zoneName;\n      this.jobId = jobId;\n      this.jobStatus = jobStatus;\n      this.tags = tags != null ? ImmutableSet.copyOf(tags) : ImmutableSet.<Tag> of();\n   }\n\n   /**\n    * @return public IP address id\n    */\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * @return the account the public IP address is associated with\n    */\n   @Nullable\n   public String getAccount() {\n      return this.account;\n   }\n\n   /**\n    * @return date the public IP address was acquired\n    */\n   @Nullable\n   public Date getAllocated() {\n      return this.allocated;\n   }\n\n   /**\n    * @return the ID of the Network associated with the IP address\n    */\n   @Nullable\n   public String getAssociatedNetworkId() {\n      return this.associatedNetworkId;\n   }\n\n   /**\n    * @return the domain the public IP address is associated with\n    */\n   @Nullable\n   public String getDomain() {\n      return this.domain;\n   }\n\n   /**\n    * @return the domain ID the public IP address is associated with\n    */\n   @Nullable\n   public String getDomainId() {\n      return this.domainId;\n   }\n\n   /**\n    * @return uses virtual network\n    */\n   public boolean isUsesVirtualNetwork() {\n      return this.usesVirtualNetwork;\n   }\n\n   /**\n    * @return public IP address\n    */\n   @Nullable\n   public String getIPAddress() {\n      return this.IPAddress;\n   }\n\n   /**\n    * @return true if the IP address is a source nat address, false otherwise\n    */\n   public boolean isSourceNAT() {\n      return this.isSourceNAT;\n   }\n\n   /**\n    * @return true if this ip is for static nat, false otherwise\n    */\n   public boolean isStaticNAT() {\n      return this.isStaticNAT;\n   }\n\n   /**\n    * @return the ID of the Network where ip belongs to\n    */\n   @Nullable\n   public String getNetworkId() {\n      return this.networkId;\n   }\n\n   /**\n    * @return State of the ip address. Can be: Allocating, Allocated and\n    *         Releasing\n    */\n   @Nullable\n   public PublicIPAddress.State getState() {\n      return this.state;\n   }\n\n   /**\n    * @return virtual machine display name the ip address is assigned to (not\n    *         null only for static nat Ip)\n    */\n   @Nullable\n   public String getVirtualMachineDisplayName() {\n      return this.virtualMachineDisplayName;\n   }\n\n   /**\n    * @return virtual machine id the ip address is assigned to (not null only\n    *         for static nat Ip)\n    */\n   @Nullable\n   public String getVirtualMachineId() {\n      return this.virtualMachineId;\n   }\n\n   /**\n    * @return virtual machine name the ip address is assigned to (not null only\n    *         for static nat Ip)\n    */\n   @Nullable\n   public String getVirtualMachineName() {\n      return this.virtualMachineName;\n   }\n\n   /**\n    * @return the ID of the VLAN associated with the IP address\n    */\n   @Nullable\n   public String getVLANId() {\n      return this.VLANId;\n   }\n\n   /**\n    * @return the VLAN associated with the IP address\n    */\n   @Nullable\n   public String getVLANName() {\n      return this.VLANName;\n   }\n\n   /**\n    * @return the ID of the zone the public IP address belongs to\n    */\n   @Nullable\n   public String getZoneId() {\n      return this.zoneId;\n   }\n\n   /**\n    * @return the name of the zone the public IP address belongs to\n    */\n   @Nullable\n   public String getZoneName() {\n      return this.zoneName;\n   }\n\n   /**\n    * @return shows the current pending asynchronous job ID. This tag is not\n    *         returned if no current pending jobs are acting on the virtual\n    *         machine\n    */\n   @Nullable\n   public String getJobId() {\n      return this.jobId;\n   }\n\n   /**\n    * @return shows the current pending asynchronous job status\n    */\n   @Nullable\n   public Integer getJobStatus() {\n      return this.jobStatus;\n   }\n\n   /**\n    * @return the tags for the public IP address\n    */\n   public Set<Tag> getTags() {\n      return this.tags;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, account, allocated, associatedNetworkId, domain, domainId, usesVirtualNetwork, IPAddress, isSourceNAT, isStaticNAT, networkId, state, virtualMachineDisplayName, virtualMachineId, virtualMachineName, VLANId, VLANName, zoneId, zoneName, jobId, jobStatus, tags);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      PublicIPAddress that = PublicIPAddress.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n            && Objects.equal(this.account, that.account)\n            && Objects.equal(this.allocated, that.allocated)\n            && Objects.equal(this.associatedNetworkId, that.associatedNetworkId)\n            && Objects.equal(this.domain, that.domain)\n            && Objects.equal(this.domainId, that.domainId)\n            && Objects.equal(this.usesVirtualNetwork, that.usesVirtualNetwork)\n            && Objects.equal(this.IPAddress, that.IPAddress)\n            && Objects.equal(this.isSourceNAT, that.isSourceNAT)\n            && Objects.equal(this.isStaticNAT, that.isStaticNAT)\n            && Objects.equal(this.networkId, that.networkId)\n            && Objects.equal(this.state, that.state)\n            && Objects.equal(this.virtualMachineDisplayName, that.virtualMachineDisplayName)\n            && Objects.equal(this.virtualMachineId, that.virtualMachineId)\n            && Objects.equal(this.virtualMachineName, that.virtualMachineName)\n            && Objects.equal(this.VLANId, that.VLANId)\n            && Objects.equal(this.VLANName, that.VLANName)\n            && Objects.equal(this.zoneId, that.zoneId)\n            && Objects.equal(this.zoneName, that.zoneName)\n            && Objects.equal(this.jobId, that.jobId)\n            && Objects.equal(this.jobStatus, that.jobStatus)\n            && Objects.equal(this.tags, that.tags);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"account\", account).add(\"allocated\", allocated).add(\"associatedNetworkId\", associatedNetworkId)\n            .add(\"domain\", domain).add(\"domainId\", domainId).add(\"usesVirtualNetwork\", usesVirtualNetwork).add(\"IPAddress\", IPAddress)\n            .add(\"isSourceNAT\", isSourceNAT).add(\"isStaticNAT\", isStaticNAT).add(\"networkId\", networkId).add(\"state\", state)\n            .add(\"virtualMachineDisplayName\", virtualMachineDisplayName).add(\"virtualMachineId\", virtualMachineId)\n            .add(\"virtualMachineName\", virtualMachineName).add(\"VLANId\", VLANId).add(\"VLANName\", VLANName).add(\"zoneId\", zoneId)\n            .add(\"zoneName\", zoneName).add(\"jobId\", jobId).add(\"jobStatus\", jobStatus).add(\"tags\", tags);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/ResourceLimit.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Map;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Maps;\n\n/**\n * Class ResourceLimit\n */\npublic class ResourceLimit {\n\n   /**\n    * Type of resource to update.\n    */\n   public enum ResourceType {\n      /**\n       * 0 - Instance. Number of instances a user can create.\n       */\n      INSTANCE(0),\n      /**\n       * 1 - IP. Number of public IP addresses a user can own.\n       */\n      IP(1),\n      /**\n       * 2 - Volume. Number of disk volumes a user can create.\n       */\n      VOLUME(2),\n      /**\n       * 3 - Snapshot. Number of snapshots a user can create.\n       */\n      SNAPSHOT(3),\n      /**\n       * 4 - Template. Number of templates that a user can register/create.\n       */\n      TEMPLATE(4),\n      /**\n       * 5 - Projects.\n       */\n      PROJECT(5),\n      /**\n       * 6 - Networks.\n       */\n      NETWORK(6),\n      /**\n       * 7 - VPC. Number of VPC the user can own.\n       */\n      VPC(7),\n      /**\n       * 8 - CPU. The number of CPUs the user can allocate.\n       */\n      CPU(8),\n      /**\n       * 9 - Memory. The amount of memory the user can allocate.\n       */\n      MEMORY(9),\n      /**\n       * 10 - Primary storage.\n       */\n      PRIMARY_STORAGE(10),\n      /**\n       * 11 - Secondary storage.\n       */\n      SECONDARY_STORAGE(11),\n         \n      UNRECOGNIZED(Integer.MAX_VALUE);\n\n      private int code;\n\n      private static final Map<Integer, ResourceType> INDEX = Maps.uniqueIndex(ImmutableSet.copyOf(ResourceType.values()),\n            new Function<ResourceType, Integer>() {\n\n               @Override\n               public Integer apply(ResourceType input) {\n                  return input.code;\n               }\n\n            });\n\n      ResourceType(int code) {\n         this.code = code;\n      }\n\n      public int getCode() {\n         return code;\n      }\n\n      @Override\n      public String toString() {\n         return name();\n      }\n\n      public static ResourceType fromValue(String resourceType) {\n         Integer code = Integer.valueOf(checkNotNull(resourceType, \"resourcetype\"));\n         return INDEX.containsKey(code) ? INDEX.get(code) : UNRECOGNIZED;\n      }\n   }\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromResourceLimit(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String account;\n      protected String domain;\n      protected String domainId;\n      protected int max;\n      protected ResourceType resourceType;\n\n      /**\n       * @see ResourceLimit#getAccount()\n       */\n      public T account(String account) {\n         this.account = account;\n         return self();\n      }\n\n      /**\n       * @see ResourceLimit#getDomain()\n       */\n      public T domain(String domain) {\n         this.domain = domain;\n         return self();\n      }\n\n      /**\n       * @see ResourceLimit#getDomainId()\n       */\n      public T domainId(String domainId) {\n         this.domainId = domainId;\n         return self();\n      }\n\n      /**\n       * @see ResourceLimit#getMax()\n       */\n      public T max(int max) {\n         this.max = max;\n         return self();\n      }\n\n      /**\n       * @see ResourceLimit#getResourceType()\n       */\n      public T resourceType(ResourceType resourceType) {\n         this.resourceType = resourceType;\n         return self();\n      }\n\n      public ResourceLimit build() {\n         return new ResourceLimit(account, domain, domainId, max, resourceType);\n      }\n\n      public T fromResourceLimit(ResourceLimit in) {\n         return this\n               .account(in.getAccount())\n               .domain(in.getDomain())\n               .domainId(in.getDomainId())\n               .max(in.getMax())\n               .resourceType(in.getResourceType());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String account;\n   private final String domain;\n   private final String domainId;\n   private final int max;\n   private final ResourceLimit.ResourceType resourceType;\n\n   @ConstructorProperties({\n         \"account\", \"domain\", \"domainid\", \"max\", \"resourcetype\"\n   })\n   protected ResourceLimit(@Nullable String account, @Nullable String domain, @Nullable String domainId, int max,\n                           @Nullable ResourceType resourceType) {\n      this.account = account;\n      this.domain = domain;\n      this.domainId = domainId;\n      this.max = max;\n      this.resourceType = resourceType;\n   }\n\n   @Nullable\n   public String getAccount() {\n      return this.account;\n   }\n\n   @Nullable\n   public String getDomain() {\n      return this.domain;\n   }\n\n   @Nullable\n   public String getDomainId() {\n      return this.domainId;\n   }\n\n   public int getMax() {\n      return this.max;\n   }\n\n   @Nullable\n   public ResourceType getResourceType() {\n      return this.resourceType;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(account, domain, domainId, max, resourceType);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      ResourceLimit that = ResourceLimit.class.cast(obj);\n      return Objects.equal(this.account, that.account)\n            && Objects.equal(this.domain, that.domain)\n            && Objects.equal(this.domainId, that.domainId)\n            && Objects.equal(this.max, that.max)\n            && Objects.equal(this.resourceType, that.resourceType);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"account\", account).add(\"domain\", domain).add(\"domainId\", domainId).add(\"max\", max).add(\"resourceType\", resourceType);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/SecurityGroup.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSortedSet;\n\n/**\n * Class SecurityGroup\n */\npublic class SecurityGroup implements Comparable<SecurityGroup> {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromSecurityGroup(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String id;\n      protected String account;\n      protected String name;\n      protected String description;\n      protected String domain;\n      protected String domainId;\n      protected String jobId;\n      protected Integer jobStatus;\n      protected Set<IngressRule> ingressRules;\n      protected Set<Tag> tags = ImmutableSet.of();\n\n      /**\n       * @see SecurityGroup#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see SecurityGroup#getAccount()\n       */\n      public T account(String account) {\n         this.account = account;\n         return self();\n      }\n\n      /**\n       * @see SecurityGroup#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /**\n       * @see SecurityGroup#getDescription()\n       */\n      public T description(String description) {\n         this.description = description;\n         return self();\n      }\n\n      /**\n       * @see SecurityGroup#getDomain()\n       */\n      public T domain(String domain) {\n         this.domain = domain;\n         return self();\n      }\n\n      /**\n       * @see SecurityGroup#getDomainId()\n       */\n      public T domainId(String domainId) {\n         this.domainId = domainId;\n         return self();\n      }\n\n      /**\n       * @see SecurityGroup#getJobId()\n       */\n      public T jobId(String jobId) {\n         this.jobId = jobId;\n         return self();\n      }\n\n      /**\n       * @see SecurityGroup#getJobStatus()\n       */\n      public T jobStatus(Integer jobStatus) {\n         this.jobStatus = jobStatus;\n         return self();\n      }\n\n      /**\n       * @see SecurityGroup#getIngressRules()\n       */\n      public T ingressRules(Set<IngressRule> ingressRules) {\n         this.ingressRules = ingressRules;\n         return self();\n      }\n\n      /**\n       * @see SecurityGroup#getTags()\n       */\n      public T tags(Set<Tag> tags) {\n         this.tags = ImmutableSet.copyOf(checkNotNull(tags, \"tags\"));\n         return self();\n      }\n\n      public T tags(Tag... in) {\n         return tags(ImmutableSet.copyOf(in));\n      }\n\n      public SecurityGroup build() {\n         return new SecurityGroup(id, account, name, description, domain, domainId, jobId, jobStatus, ingressRules, tags);\n      }\n\n      public T fromSecurityGroup(SecurityGroup in) {\n         return this\n               .id(in.getId())\n               .account(in.getAccount())\n               .name(in.getName())\n               .description(in.getDescription())\n               .domain(in.getDomain())\n               .domainId(in.getDomainId())\n               .jobId(in.getJobId())\n               .jobStatus(in.getJobStatus())\n               .ingressRules(in.getIngressRules())\n               .tags(in.getTags());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final String account;\n   private final String name;\n   private final String description;\n   private final String domain;\n   private final String domainId;\n   private final String jobId;\n   private final Integer jobStatus;\n   private final Set<IngressRule> ingressRules;\n   private final Set<Tag> tags;\n\n   @ConstructorProperties({\n         \"id\", \"account\", \"name\", \"description\", \"domain\", \"domainid\", \"jobid\", \"jobstatus\", \"ingressrule\", \"tags\"\n   })\n   protected SecurityGroup(String id, @Nullable String account, @Nullable String name, @Nullable String description,\n                           @Nullable String domain, @Nullable String domainId, @Nullable String jobId, @Nullable Integer jobStatus,\n                           @Nullable Set<IngressRule> ingressRules, @Nullable Set<Tag> tags) {\n      this.id = checkNotNull(id, \"id\");\n      this.account = account;\n      this.name = name;\n      this.description = description;\n      this.domain = domain;\n      this.domainId = domainId;\n      this.jobId = jobId;\n      this.jobStatus = jobStatus;\n      this.ingressRules = ingressRules == null ? ImmutableSet.<IngressRule>of() : ImmutableSortedSet.copyOf(ingressRules);\n      this.tags = tags != null ? ImmutableSet.copyOf(tags) : ImmutableSet.<Tag> of();\n   }\n\n   /**\n    * @return the id of the security group\n    */\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * @return the account owning the security group\n    */\n   @Nullable\n   public String getAccount() {\n      return this.account;\n   }\n\n   /**\n    * @return the name of the security group\n    */\n   @Nullable\n   public String getName() {\n      return this.name;\n   }\n\n   /**\n    * @return an alternate display text of the security group.\n    */\n   @Nullable\n   public String getDescription() {\n      return this.description;\n   }\n\n   /**\n    * @return Domain name for the security group\n    */\n   @Nullable\n   public String getDomain() {\n      return this.domain;\n   }\n\n   /**\n    * @return the domain id of the security group\n    */\n   @Nullable\n   public String getDomainId() {\n      return this.domainId;\n   }\n\n   /**\n    * @return shows the current pending asynchronous job ID. This tag is not\n    *         returned if no current pending jobs are acting on the virtual\n    *         machine\n    */\n   @Nullable\n   public String getJobId() {\n      return this.jobId;\n   }\n\n   /**\n    * @return shows the current pending asynchronous job status\n    */\n   @Nullable\n   public Integer getJobStatus() {\n      return this.jobStatus;\n   }\n\n   /**\n    * @return the list of ingress rules associated with the security group\n    */\n   public Set<IngressRule> getIngressRules() {\n      return this.ingressRules;\n   }\n\n   /**\n    * @return the tags for the security group\n    */\n   public Set<Tag> getTags() {\n      return this.tags;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, account, name, description, domain, domainId, jobId, jobStatus, ingressRules, tags);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      SecurityGroup that = SecurityGroup.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n            && Objects.equal(this.account, that.account)\n            && Objects.equal(this.name, that.name)\n            && Objects.equal(this.description, that.description)\n            && Objects.equal(this.domain, that.domain)\n            && Objects.equal(this.domainId, that.domainId)\n            && Objects.equal(this.jobId, that.jobId)\n            && Objects.equal(this.jobStatus, that.jobStatus)\n            && Objects.equal(this.ingressRules, that.ingressRules)\n            && Objects.equal(this.tags, that.tags);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).add(\"id\", id).add(\"account\", account).add(\"name\", name).add(\"description\", description)\n            .add(\"domain\", domain).add(\"domainId\", domainId).add(\"jobId\", jobId).add(\"jobStatus\", jobStatus).add(\"ingressRules\", ingressRules)\n            .add(\"tags\", tags);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int compareTo(SecurityGroup o) {\n      return id.compareTo(o.getId());\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/ServiceOffering.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Class ServiceOffering\n */\npublic class ServiceOffering implements Comparable<ServiceOffering> {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromServiceOffering(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String id;\n      protected String name;\n      protected String displayText;\n      protected Date created;\n      protected String domain;\n      protected String domainId;\n      protected int cpuNumber;\n      protected int cpuSpeed;\n      protected int memory;\n      protected boolean haSupport;\n      protected StorageType storageType;\n      protected boolean defaultUse;\n      protected boolean systemOffering;\n      protected boolean cpuUseLimited;\n      protected long networkRate;\n      protected boolean systemVmType;\n      protected ImmutableSet.Builder<String> tags = ImmutableSet.<String>builder();\n\n      /**\n       * @see ServiceOffering#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see ServiceOffering#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /**\n       * @see ServiceOffering#getDisplayText()\n       */\n      public T displayText(String displayText) {\n         this.displayText = displayText;\n         return self();\n      }\n\n      /**\n       * @see ServiceOffering#getCreated()\n       */\n      public T created(Date created) {\n         this.created = created;\n         return self();\n      }\n\n      /**\n       * @see ServiceOffering#getDomain()\n       */\n      public T domain(String domain) {\n         this.domain = domain;\n         return self();\n      }\n\n      /**\n       * @see ServiceOffering#getDomainId()\n       */\n      public T domainId(String domainId) {\n         this.domainId = domainId;\n         return self();\n      }\n\n      /**\n       * @see ServiceOffering#getCpuNumber()\n       */\n      public T cpuNumber(int cpuNumber) {\n         this.cpuNumber = cpuNumber;\n         return self();\n      }\n\n      /**\n       * @see ServiceOffering#getCpuSpeed()\n       */\n      public T cpuSpeed(int cpuSpeed) {\n         this.cpuSpeed = cpuSpeed;\n         return self();\n      }\n\n      /**\n       * @see ServiceOffering#getMemory()\n       */\n      public T memory(int memory) {\n         this.memory = memory;\n         return self();\n      }\n\n      /**\n       * @see ServiceOffering#supportsHA()\n       */\n      public T supportsHA(boolean haSupport) {\n         this.haSupport = haSupport;\n         return self();\n      }\n\n      /**\n       * @see ServiceOffering#getStorageType()\n       */\n      public T storageType(StorageType storageType) {\n         this.storageType = storageType;\n         return self();\n      }\n\n      /**\n       * @see ServiceOffering#getTags()\n       */\n      public T tags(Iterable<String> tags) {\n         this.tags = ImmutableSet.<String>builder().addAll(tags);\n         return self();\n      }\n      \n      /**\n       * @see ServiceOffering#getTags()\n       */\n      public T tag(String tag) {\n         this.tags.add(tag);\n         return self();\n      }\n      \n      /**\n       * @see ServiceOffering#isDefaultUse()\n       */\n      public T defaultUse(boolean defaultUse) {\n         this.defaultUse = defaultUse;\n         return self();\n      }\n\n      /**\n       * @see ServiceOffering#isSystemOffering()\n       */\n      public T systemOffering(boolean systemOffering) {\n         this.systemOffering = systemOffering;\n         return self();\n      }\n\n      /**\n       * @see ServiceOffering#isCpuUseLimited()\n       */\n      public T cpuUseLimited(boolean cpuUseLimited) {\n         this.cpuUseLimited = cpuUseLimited;\n         return self();\n      }\n\n      /**\n       * @see ServiceOffering#getNetworkRate()\n       */\n      public T networkRate(long networkRate) {\n         this.networkRate = networkRate;\n         return self();\n      }\n\n      /**\n       * @see ServiceOffering#isSystemVmType()\n       */\n      public T systemVmType(boolean systemVmType) {\n         this.systemVmType = systemVmType;\n         return self();\n      }\n\n      public ServiceOffering build() {\n         return new ServiceOffering(id, name, displayText, created, domain, domainId, cpuNumber, cpuSpeed, memory, haSupport, storageType,\n               tags.build(), defaultUse, systemOffering, cpuUseLimited, networkRate, systemVmType);\n      }\n\n      public T fromServiceOffering(ServiceOffering in) {\n         return this\n               .id(in.getId())\n               .name(in.getName())\n               .displayText(in.getDisplayText())\n               .created(in.getCreated())\n               .domain(in.getDomain())\n               .domainId(in.getDomainId())\n               .cpuNumber(in.getCpuNumber())\n               .cpuSpeed(in.getCpuSpeed())\n               .memory(in.getMemory())\n               .supportsHA(in.supportsHA())\n               .storageType(in.getStorageType())\n               .tags(in.getTags())\n               .defaultUse(in.isDefaultUse())\n               .systemOffering(in.isSystemOffering())\n               .cpuUseLimited(in.isCpuUseLimited())\n               .networkRate(in.getNetworkRate())\n               .systemVmType(in.isSystemVmType());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final String name;\n   private final String displayText;\n   private final Date created;\n   private final String domain;\n   private final String domainId;\n   private final int cpuNumber;\n   private final int cpuSpeed;\n   private final int memory;\n   private final boolean haSupport;\n   private final StorageType storageType;\n   private final Set<String> tags;\n   private final boolean defaultUse;\n   private final boolean systemOffering;\n   private final boolean cpuUseLimited;\n   private final long networkRate;\n   private final boolean systemVmType;\n\n   @ConstructorProperties({\n         \"id\", \"name\", \"displaytext\", \"created\", \"domain\", \"domainid\", \"cpunumber\", \"cpuspeed\", \"memory\", \"offerha\", \"storagetype\", \"tags\", \"defaultuse\", \"issystem\", \"limitcpuuse\", \"networkrate\", \"systemvmtype\"\n   })\n   protected ServiceOffering(String id, @Nullable String name, @Nullable String displayText, @Nullable Date created,\n                             @Nullable String domain, @Nullable String domainId, int cpuNumber, int cpuSpeed, int memory,\n                             boolean haSupport, @Nullable StorageType storageType, @Nullable Iterable<String> tags, boolean defaultUse,\n                             boolean systemOffering, boolean cpuUseLimited, long networkRate, boolean systemVmType) {\n      this.id = checkNotNull(id, \"id\");\n      this.name = name;\n      this.displayText = displayText;\n      this.created = created;\n      this.domain = domain;\n      this.domainId = domainId;\n      this.cpuNumber = cpuNumber;\n      this.cpuSpeed = cpuSpeed;\n      this.memory = memory;\n      this.haSupport = haSupport;\n      this.storageType = storageType;\n      this.tags = tags != null ? ImmutableSet.copyOf(tags) : ImmutableSet.<String> of();\n      this.defaultUse = defaultUse;\n      this.systemOffering = systemOffering;\n      this.cpuUseLimited = cpuUseLimited;\n      this.networkRate = networkRate;\n      this.systemVmType = systemVmType;\n   }\n\n   /**\n    * @return the id of the service offering\n    */\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * @return the name of the service offering\n    */\n   public String getName() {\n      return this.name;\n   }\n\n   /**\n    * @return an alternate display text of the service offering.\n    */\n   @Nullable\n   public String getDisplayText() {\n      return this.displayText;\n   }\n\n   /**\n    * @return the date this service offering was created\n    */\n   @Nullable\n   public Date getCreated() {\n      return this.created;\n   }\n\n   /**\n    * @return Domain name for the offering\n    */\n   @Nullable\n   public String getDomain() {\n      return this.domain;\n   }\n\n   /**\n    * @return the domain id of the service offering\n    */\n   @Nullable\n   public String getDomainId() {\n      return this.domainId;\n   }\n\n   /**\n    * @return the number of CPU\n    */\n   public int getCpuNumber() {\n      return this.cpuNumber;\n   }\n\n   /**\n    * @return the clock rate CPU speed in Mhz\n    */\n   public int getCpuSpeed() {\n      return this.cpuSpeed;\n   }\n\n   /**\n    * @return the memory in MB\n    */\n   public int getMemory() {\n      return this.memory;\n   }\n\n   public boolean supportsHA() {\n      return this.haSupport;\n   }\n\n   /**\n    * @return the storage type for this service offering\n    */\n   @Nullable\n   public StorageType getStorageType() {\n      return this.storageType;\n   }\n\n   /**\n    * @return the tags for the service offering\n    */\n   public Set<String> getTags() {\n      return tags;\n   }\n\n   /**\n    * @return whether this is a default system vm offering\n    */\n   public boolean isDefaultUse() {\n      return this.defaultUse;\n   }\n\n   /**\n    * @return whether this is a system vm offering\n    */\n   public boolean isSystemOffering() {\n      return this.systemOffering;\n   }\n\n   /**\n    * @return whether restrict the CPU usage to committed service offering\n    */\n   public boolean isCpuUseLimited() {\n      return this.cpuUseLimited;\n   }\n\n   /**\n    * @return data transfer rate in megabits per second allowed.\n    */\n   public long getNetworkRate() {\n      return this.networkRate;\n   }\n\n   /**\n    * @return whether this is a the systemvm type for system vm offering\n    */\n   public boolean isSystemVmType() {\n      return this.systemVmType;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, name, displayText, created, domain, domainId, cpuNumber, cpuSpeed, memory, haSupport, storageType, tags, defaultUse, systemOffering, cpuUseLimited, networkRate, systemVmType);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      ServiceOffering that = ServiceOffering.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n            && Objects.equal(this.name, that.name)\n            && Objects.equal(this.displayText, that.displayText)\n            && Objects.equal(this.created, that.created)\n            && Objects.equal(this.domain, that.domain)\n            && Objects.equal(this.domainId, that.domainId)\n            && Objects.equal(this.cpuNumber, that.cpuNumber)\n            && Objects.equal(this.cpuSpeed, that.cpuSpeed)\n            && Objects.equal(this.memory, that.memory)\n            && Objects.equal(this.haSupport, that.haSupport)\n            && Objects.equal(this.storageType, that.storageType)\n            && Objects.equal(this.getTags(), that.getTags())\n            && Objects.equal(this.defaultUse, that.defaultUse)\n            && Objects.equal(this.systemOffering, that.systemOffering)\n            && Objects.equal(this.cpuUseLimited, that.cpuUseLimited)\n            && Objects.equal(this.networkRate, that.networkRate)\n            && Objects.equal(this.systemVmType, that.systemVmType);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"name\", name).add(\"displayText\", displayText).add(\"created\", created).add(\"domain\", domain)\n            .add(\"domainId\", domainId).add(\"cpuNumber\", cpuNumber).add(\"cpuSpeed\", cpuSpeed).add(\"memory\", memory)\n            .add(\"haSupport\", haSupport).add(\"storageType\", storageType).add(\"tags\", getTags()).add(\"defaultUse\", defaultUse)\n            .add(\"systemOffering\", systemOffering).add(\"cpuUseLimited\", cpuUseLimited)\n            .add(\"networkRate\", networkRate).add(\"systemVmType\", systemVmType);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int compareTo(ServiceOffering o) {\n      return id.compareTo(o.getId());\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/Snapshot.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\nimport java.util.Set;\n\nimport com.google.common.collect.ImmutableSet;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.CaseFormat;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Class Snapshot\n */\npublic class Snapshot {\n\n   /**\n    */\n   public static enum State {\n\n      BACKED_UP, CREATING, BACKING_UP, UNRECOGNIZED;\n\n      @Override\n      public String toString() {\n         return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name());\n      }\n\n      public static State fromValue(String state) {\n         try {\n            return valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, checkNotNull(state, \"state\")));\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n   }\n\n   /**\n    */\n   public static enum Type {\n\n      MANUAL, RECURRING, UNRECOGNIZED;\n\n      public static Type fromValue(String type) {\n         try {\n            return valueOf(checkNotNull(type, \"type\"));\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n   }\n\n   /**\n    */\n   public static enum Interval {\n\n      HOURLY, DAILY, WEEKLY, MONTHLY, template, none, UNRECOGNIZED;\n\n      public static Interval fromValue(String type) {\n         try {\n            return valueOf(checkNotNull(type, \"type\"));\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n   }\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromSnapshot(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String id;\n      protected String account;\n      protected Date created;\n      protected String domain;\n      protected String domainId;\n      protected Snapshot.Interval interval;\n      protected String jobId;\n      protected String jobStatus;\n      protected String name;\n      protected Snapshot.Type snapshotType;\n      protected Snapshot.State state;\n      protected String volumeId;\n      protected String volumeName;\n      protected Volume.Type volumeType;\n      protected Set<Tag> tags = ImmutableSet.of();\n\n      /**\n       * @see Snapshot#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see Snapshot#getAccount()\n       */\n      public T account(String account) {\n         this.account = account;\n         return self();\n      }\n\n      /**\n       * @see Snapshot#getCreated()\n       */\n      public T created(Date created) {\n         this.created = created;\n         return self();\n      }\n\n      /**\n       * @see Snapshot#getDomain()\n       */\n      public T domain(String domain) {\n         this.domain = domain;\n         return self();\n      }\n\n      /**\n       * @see Snapshot#getDomainId()\n       */\n      public T domainId(String domainId) {\n         this.domainId = domainId;\n         return self();\n      }\n\n      /**\n       * @see Snapshot#getInterval()\n       */\n      public T interval(Snapshot.Interval interval) {\n         this.interval = interval;\n         return self();\n      }\n\n      /**\n       * @see Snapshot#getJobId()\n       */\n      public T jobId(String jobId) {\n         this.jobId = jobId;\n         return self();\n      }\n\n      /**\n       * @see Snapshot#getJobStatus()\n       */\n      public T jobStatus(String jobStatus) {\n         this.jobStatus = jobStatus;\n         return self();\n      }\n\n      /**\n       * @see Snapshot#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /**\n       * @see Snapshot#getSnapshotType()\n       */\n      public T snapshotType(Snapshot.Type snapshotType) {\n         this.snapshotType = snapshotType;\n         return self();\n      }\n\n      /**\n       * @see Snapshot#getState()\n       */\n      public T state(Snapshot.State state) {\n         this.state = state;\n         return self();\n      }\n\n      /**\n       * @see Snapshot#getVolumeId()\n       */\n      public T volumeId(String volumeId) {\n         this.volumeId = volumeId;\n         return self();\n      }\n\n      /**\n       * @see Snapshot#getVolumeName()\n       */\n      public T volumeName(String volumeName) {\n         this.volumeName = volumeName;\n         return self();\n      }\n\n      /**\n       * @see Snapshot#getVolumeType()\n       */\n      public T volumeType(Volume.Type volumeType) {\n         this.volumeType = volumeType;\n         return self();\n      }\n\n      /**\n       * @see Snapshot#getTags()\n       */\n      public T tags(Set<Tag> tags) {\n         this.tags = ImmutableSet.copyOf(checkNotNull(tags, \"tags\"));\n         return self();\n      }\n\n      public T tags(Tag... in) {\n         return tags(ImmutableSet.copyOf(in));\n      }\n\n      public Snapshot build() {\n         return new Snapshot(id, account, created, domain, domainId, interval, jobId, jobStatus, name, snapshotType, state,\n               volumeId, volumeName, volumeType, tags);\n      }\n\n      public T fromSnapshot(Snapshot in) {\n         return this\n               .id(in.getId())\n               .account(in.getAccount())\n               .created(in.getCreated())\n               .domain(in.getDomain())\n               .domainId(in.getDomainId())\n               .interval(in.getInterval())\n               .jobId(in.getJobId())\n               .jobStatus(in.getJobStatus())\n               .name(in.getName())\n               .snapshotType(in.getSnapshotType())\n               .state(in.getState())\n               .volumeId(in.getVolumeId())\n               .volumeName(in.getVolumeName())\n               .volumeType(in.getVolumeType())\n               .tags(in.getTags());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final String account;\n   private final Date created;\n   private final String domain;\n   private final String domainId;\n   private final Snapshot.Interval interval;\n   private final String jobId;\n   private final String jobStatus;\n   private final String name;\n   private final Snapshot.Type snapshotType;\n   private final Snapshot.State state;\n   private final String volumeId;\n   private final String volumeName;\n   private final Volume.Type volumeType;\n   private final Set<Tag> tags;\n\n   @ConstructorProperties({\n         \"id\", \"account\", \"created\", \"domain\", \"domainid\", \"intervaltype\", \"jobid\", \"jobstatus\", \"name\", \"snapshottype\", \"state\", \"volumeid\", \"volumename\", \"volumetype\", \"tags\"\n   })\n   protected Snapshot(String id, @Nullable String account, @Nullable Date created, @Nullable String domain, @Nullable String domainId,\n                      @Nullable Snapshot.Interval interval, @Nullable String jobId, @Nullable String jobStatus, @Nullable String name,\n                      @Nullable Snapshot.Type snapshotType, @Nullable Snapshot.State state, @Nullable String volumeId, @Nullable String volumeName,\n                      @Nullable Volume.Type volumeType, @Nullable Set<Tag> tags) {\n      this.id = checkNotNull(id, \"id\");\n      this.account = account;\n      this.created = created;\n      this.domain = domain;\n      this.domainId = domainId;\n      this.interval = interval;\n      this.jobId = jobId;\n      this.jobStatus = jobStatus;\n      this.name = name;\n      this.snapshotType = snapshotType;\n      this.state = state;\n      this.volumeId = volumeId;\n      this.volumeName = volumeName;\n      this.volumeType = volumeType;\n      this.tags = tags != null ? ImmutableSet.copyOf(tags) : ImmutableSet.<Tag> of();\n   }\n\n   /**\n    * @return ID of the snapshot\n    */\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * @return the account associated with the snapshot\n    */\n   @Nullable\n   public String getAccount() {\n      return this.account;\n   }\n\n   /**\n    * @return the date the snapshot was created\n    */\n   @Nullable\n   public Date getCreated() {\n      return this.created;\n   }\n\n   /**\n    * @return the domain name of the snapshot's account\n    */\n   @Nullable\n   public String getDomain() {\n      return this.domain;\n   }\n\n   /**\n    * @return the domain ID of the snapshot's account\n    */\n   @Nullable\n   public String getDomainId() {\n      return this.domainId;\n   }\n\n   /**\n    * @return valid types are hourly, daily, weekly, monthly, template, and none.\n    */\n   @Nullable\n   public Snapshot.Interval getInterval() {\n      return this.interval;\n   }\n\n   /**\n    * @return the job ID associated with the snapshot. This is only displayed if the snapshot listed is part of a currently running asynchronous job.\n    */\n   @Nullable\n   public String getJobId() {\n      return this.jobId;\n   }\n\n   /**\n    * @return the job status associated with the snapshot. This is only displayed if the snapshot listed is part of a currently running asynchronous job.\n    */\n   @Nullable\n   public String getJobStatus() {\n      return this.jobStatus;\n   }\n\n   /**\n    * @return name of the snapshot\n    */\n   @Nullable\n   public String getName() {\n      return this.name;\n   }\n\n   /**\n    * @return the type of the snapshot\n    */\n   @Nullable\n   public Snapshot.Type getSnapshotType() {\n      return this.snapshotType;\n   }\n\n   /**\n    * @return the state of the snapshot. BackedUp means that snapshot is ready to be used; Creating - the snapshot is being allocated on the primary storage; BackingUp - the snapshot is being backed up on secondary storage\n    */\n   @Nullable\n   public Snapshot.State getState() {\n      return this.state;\n   }\n\n   /**\n    * @return ID of the disk volume\n    */\n   @Nullable\n   public String getVolumeId() {\n      return this.volumeId;\n   }\n\n   /**\n    * @return name of the disk volume\n    */\n   @Nullable\n   public String getVolumeName() {\n      return this.volumeName;\n   }\n\n   /**\n    * @return type of the disk volume\n    */\n   @Nullable\n   public Volume.Type getVolumeType() {\n      return this.volumeType;\n   }\n\n   /**\n    * @return the tags for the snapshot\n    */\n   public Set<Tag> getTags() {\n      return this.tags;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, account, created, domain, domainId, interval, jobId, jobStatus, name, snapshotType, state, volumeId, volumeName, volumeType, tags);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Snapshot that = Snapshot.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n            && Objects.equal(this.account, that.account)\n            && Objects.equal(this.created, that.created)\n            && Objects.equal(this.domain, that.domain)\n            && Objects.equal(this.domainId, that.domainId)\n            && Objects.equal(this.interval, that.interval)\n            && Objects.equal(this.jobId, that.jobId)\n            && Objects.equal(this.jobStatus, that.jobStatus)\n            && Objects.equal(this.name, that.name)\n            && Objects.equal(this.snapshotType, that.snapshotType)\n            && Objects.equal(this.state, that.state)\n            && Objects.equal(this.volumeId, that.volumeId)\n            && Objects.equal(this.volumeName, that.volumeName)\n            && Objects.equal(this.volumeType, that.volumeType)\n            && Objects.equal(this.tags, that.tags);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"account\", account).add(\"created\", created).add(\"domain\", domain).add(\"domainId\", domainId)\n            .add(\"interval\", interval).add(\"jobId\", jobId).add(\"jobStatus\", jobStatus).add(\"name\", name).add(\"snapshotType\", snapshotType)\n            .add(\"state\", state).add(\"volumeId\", volumeId).add(\"volumeName\", volumeName).add(\"volumeType\", volumeType)\n            .add(\"tags\", tags);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/SnapshotPolicy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Class SnapshotPolicy\n */\npublic class SnapshotPolicy {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromSnapshotPolicy(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String id;\n      protected Snapshot.Interval interval;\n      protected long numberToRetain;\n      protected String schedule;\n      protected String timezone;\n      protected String volumeId;\n\n      /**\n       * @see SnapshotPolicy#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see SnapshotPolicy#getInterval()\n       */\n      public T interval(Snapshot.Interval interval) {\n         this.interval = interval;\n         return self();\n      }\n\n      /**\n       * @see SnapshotPolicy#getNumberToRetain()\n       */\n      public T numberToRetain(long numberToRetain) {\n         this.numberToRetain = numberToRetain;\n         return self();\n      }\n\n      /**\n       * @see SnapshotPolicy#getSchedule()\n       */\n      public T schedule(String schedule) {\n         this.schedule = schedule;\n         return self();\n      }\n\n      /**\n       * @see SnapshotPolicy#getTimezone()\n       */\n      public T timezone(String timezone) {\n         this.timezone = timezone;\n         return self();\n      }\n\n      /**\n       * @see SnapshotPolicy#getVolumeId()\n       */\n      public T volumeId(String volumeId) {\n         this.volumeId = volumeId;\n         return self();\n      }\n\n      public SnapshotPolicy build() {\n         return new SnapshotPolicy(id, interval, numberToRetain, schedule, timezone, volumeId);\n      }\n\n      public T fromSnapshotPolicy(SnapshotPolicy in) {\n         return this\n               .id(in.getId())\n               .interval(in.getInterval())\n               .numberToRetain(in.getNumberToRetain())\n               .schedule(in.getSchedule())\n               .timezone(in.getTimezone())\n               .volumeId(in.getVolumeId());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final Snapshot.Interval interval;\n   private final long numberToRetain;\n   private final String schedule;\n   private final String timezone;\n   private final String volumeId;\n\n   @ConstructorProperties({\n         \"id\", \"intervaltype\", \"maxsnaps\", \"schedule\", \"timezone\", \"volumeid\"\n   })\n   protected SnapshotPolicy(String id, @Nullable Snapshot.Interval interval, long numberToRetain, @Nullable String schedule,\n                            @Nullable String timezone, @Nullable String volumeId) {\n      this.id = checkNotNull(id, \"id\");\n      this.interval = interval;\n      this.numberToRetain = numberToRetain;\n      this.schedule = schedule;\n      this.timezone = timezone;\n      this.volumeId = volumeId;\n   }\n\n   /**\n    * @return the ID of the snapshot policy\n    */\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * @return valid types are hourly, daily, weekly, monthly, template, and none.\n    */\n   @Nullable\n   public Snapshot.Interval getInterval() {\n      return this.interval;\n   }\n\n   /**\n    * @return maximum number of snapshots retained\n    */\n   public long getNumberToRetain() {\n      return this.numberToRetain;\n   }\n\n   /**\n    * @return time the snapshot is scheduled to be taken.\n    */\n   @Nullable\n   public String getSchedule() {\n      return this.schedule;\n   }\n\n   /**\n    * @return the time zone of the snapshot policy\n    */\n   @Nullable\n   public String getTimezone() {\n      return this.timezone;\n   }\n\n   /**\n    * @return ID of the disk volume\n    */\n   @Nullable\n   public String getVolumeId() {\n      return this.volumeId;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, interval, numberToRetain, schedule, timezone, volumeId);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      SnapshotPolicy that = SnapshotPolicy.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n            && Objects.equal(this.interval, that.interval)\n            && Objects.equal(this.numberToRetain, that.numberToRetain)\n            && Objects.equal(this.schedule, that.schedule)\n            && Objects.equal(this.timezone, that.timezone)\n            && Objects.equal(this.volumeId, that.volumeId);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"interval\", interval).add(\"numberToRetain\", numberToRetain).add(\"schedule\", schedule).add(\"timezone\", timezone)\n            .add(\"volumeId\", volumeId);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/SnapshotPolicySchedule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Describes the schedule of a snapshot policy.\n *\n * @see org.jclouds.cloudstack.util.SnapshotPolicySchedules\n */\npublic class SnapshotPolicySchedule {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromSnapshotPolicySchedule(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected Snapshot.Interval interval;\n      protected String time;\n\n      /**\n       * @see SnapshotPolicySchedule#getInterval()\n       */\n      public T interval(Snapshot.Interval interval) {\n         this.interval = interval;\n         return self();\n      }\n\n      /**\n       * @see SnapshotPolicySchedule#getTime()\n       */\n      public T time(String time) {\n         this.time = time;\n         return self();\n      }\n\n      public SnapshotPolicySchedule build() {\n         return new SnapshotPolicySchedule(interval, time);\n      }\n\n      public T fromSnapshotPolicySchedule(SnapshotPolicySchedule in) {\n         return this\n               .interval(in.getInterval())\n               .time(in.getTime());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final Snapshot.Interval interval;\n   private final String time;\n\n   @ConstructorProperties({\n         \"interval\", \"time\"\n   })\n   protected SnapshotPolicySchedule(@Nullable Snapshot.Interval interval, @Nullable String time) {\n      this.interval = interval;\n      this.time = time;\n   }\n\n   @Nullable\n   public Snapshot.Interval getInterval() {\n      return this.interval;\n   }\n\n   @Nullable\n   public String getTime() {\n      return this.time;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(interval, time);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      SnapshotPolicySchedule that = SnapshotPolicySchedule.class.cast(obj);\n      return Objects.equal(this.interval, that.interval)\n            && Objects.equal(this.time, that.time);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"interval\", interval).add(\"time\", time);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/SshKeyPair.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Class SshKeyPair\n */\npublic class SshKeyPair {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromSshKeyPair(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String fingerprint;\n      protected String name;\n      protected String privateKey;\n\n      /**\n       * @see SshKeyPair#getFingerprint()\n       */\n      public T fingerprint(String fingerprint) {\n         this.fingerprint = fingerprint;\n         return self();\n      }\n\n      /**\n       * @see SshKeyPair#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /**\n       * @see SshKeyPair#getPrivateKey()\n       */\n      public T privateKey(String privateKey) {\n         this.privateKey = privateKey;\n         return self();\n      }\n\n      public SshKeyPair build() {\n         return new SshKeyPair(fingerprint, name, privateKey);\n      }\n\n      public T fromSshKeyPair(SshKeyPair in) {\n         return this\n               .fingerprint(in.getFingerprint())\n               .name(in.getName())\n               .privateKey(in.getPrivateKey());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String fingerprint;\n   private final String name;\n   private final String privateKey;\n\n   @ConstructorProperties({\n         \"fingerprint\", \"name\", \"privatekey\"\n   })\n   protected SshKeyPair(@Nullable String fingerprint, String name, @Nullable String privateKey) {\n      this.fingerprint = fingerprint;\n      this.name = checkNotNull(name, \"name\");\n      this.privateKey = privateKey;\n   }\n\n   @Nullable\n   public String getFingerprint() {\n      return this.fingerprint;\n   }\n\n   public String getName() {\n      return this.name;\n   }\n\n   @Nullable\n   public String getPrivateKey() {\n      return this.privateKey;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(fingerprint, name, privateKey);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      SshKeyPair that = SshKeyPair.class.cast(obj);\n      return Objects.equal(this.fingerprint, that.fingerprint)\n            && Objects.equal(this.name, that.name)\n            && Objects.equal(this.privateKey, that.privateKey);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"fingerprint\", fingerprint).add(\"name\", name).add(\"privateKey\", privateKey);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/StoragePool.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.CaseFormat;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Represents a storage pool in CloudStack\n */\npublic class StoragePool implements Comparable<StoragePool> {\n\n   public enum State {\n      UP,\n      PREPARE_FOR_MAINTENANCE,\n      ERROR_IN_MAINTENANCE,\n      CANCEL_MAINTENANCE,\n      MAINTENANCE,\n      REMOVED,\n      UNRECOGNIZED;\n\n      @Override\n      public String toString() {\n         return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name());\n      }\n\n      public static State fromValue(String type) {\n         try {\n            return valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, checkNotNull(type, \"type\")));\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n   }\n\n   public enum Type {\n      FILESYSTEM,\n      NETWORK_FILESYSTEM,\n      ISCSI_LUN,\n      ISCSI,\n      ISO,\n      LVM,\n      CLVM,\n      SHARED_MOUNT_POINT,\n      VMFS,\n      PRE_SETUP,\n      EXT,\n      OCFS2,\n      UNRECOGNIZED;\n\n      @Override\n      public String toString() {\n         return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name());\n      }\n\n      public static Type fromValue(String type) {\n         try {\n            return valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, checkNotNull(type, \"type\")));\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n   }\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromStoragePool(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String id;\n      protected String name;\n      protected String path;\n      protected ImmutableSet.Builder<String> tags = ImmutableSet.<String>builder();\n      protected StoragePool.State state;\n      protected StoragePool.Type type;\n      protected String zoneId;\n      protected String zoneName;\n      protected String podId;\n      protected String podName;\n      protected String clusterId;\n      protected String clusterName;\n      protected Date created;\n      protected long diskSizeAllocated;\n      protected long diskSizeTotal;\n      protected String ipAddress;\n      protected String jobId;\n      protected String jobStatus;\n\n      /**\n       * @see StoragePool#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see StoragePool#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /**\n       * @see StoragePool#getPath()\n       */\n      public T path(String path) {\n         this.path = path;\n         return self();\n      }\n\n      /**\n       * @see DiskOffering#getTags()\n       */\n      public T tags(Iterable<String> tags) {\n         this.tags = ImmutableSet.<String>builder().addAll(tags);\n         return self();\n      }\n      \n      /**\n       * @see DiskOffering#getTags()\n       */\n      public T tag(String tag) {\n         this.tags.add(tag);\n         return self();\n      }\n\n      /**\n       * @see StoragePool#getState()\n       */\n      public T state(StoragePool.State state) {\n         this.state = state;\n         return self();\n      }\n\n      /**\n       * @see StoragePool#getType()\n       */\n      public T type(StoragePool.Type type) {\n         this.type = type;\n         return self();\n      }\n\n      /**\n       * @see StoragePool#getZoneId()\n       */\n      public T zoneId(String zoneId) {\n         this.zoneId = zoneId;\n         return self();\n      }\n\n      /**\n       * @see StoragePool#getZoneName()\n       */\n      public T zoneName(String zoneName) {\n         this.zoneName = zoneName;\n         return self();\n      }\n\n      /**\n       * @see StoragePool#getPodId()\n       */\n      public T podId(String podId) {\n         this.podId = podId;\n         return self();\n      }\n\n      /**\n       * @see StoragePool#getPodName()\n       */\n      public T podName(String podName) {\n         this.podName = podName;\n         return self();\n      }\n\n      /**\n       * @see StoragePool#getClusterId()\n       */\n      public T clusterId(String clusterId) {\n         this.clusterId = clusterId;\n         return self();\n      }\n\n      /**\n       * @see StoragePool#getClusterName()\n       */\n      public T clusterName(String clusterName) {\n         this.clusterName = clusterName;\n         return self();\n      }\n\n      /**\n       * @see StoragePool#getCreated()\n       */\n      public T created(Date created) {\n         this.created = created;\n         return self();\n      }\n\n      /**\n       * @see StoragePool#getDiskSizeAllocated()\n       */\n      public T diskSizeAllocated(long diskSizeAllocated) {\n         this.diskSizeAllocated = diskSizeAllocated;\n         return self();\n      }\n\n      /**\n       * @see StoragePool#getDiskSizeTotal()\n       */\n      public T diskSizeTotal(long diskSizeTotal) {\n         this.diskSizeTotal = diskSizeTotal;\n         return self();\n      }\n\n      /**\n       * @see StoragePool#getIpAddress()\n       */\n      public T ipAddress(String ipAddress) {\n         this.ipAddress = ipAddress;\n         return self();\n      }\n\n      /**\n       * @see StoragePool#getJobId()\n       */\n      public T jobId(String jobId) {\n         this.jobId = jobId;\n         return self();\n      }\n\n      /**\n       * @see StoragePool#getJobStatus()\n       */\n      public T jobStatus(String jobStatus) {\n         this.jobStatus = jobStatus;\n         return self();\n      }\n\n      public StoragePool build() {\n         return new StoragePool(id, name, path, tags.build(), state, type, zoneId, zoneName, podId, podName, clusterId, clusterName, created, diskSizeAllocated, diskSizeTotal, ipAddress, jobId, jobStatus);\n      }\n\n      public T fromStoragePool(StoragePool in) {\n         return this\n               .id(in.getId())\n               .name(in.getName())\n               .path(in.getPath())\n               .tags(in.getTags())\n               .state(in.getState())\n               .type(in.getType())\n               .zoneId(in.getZoneId())\n               .zoneName(in.getZoneName())\n               .podId(in.getPodId())\n               .podName(in.getPodName())\n               .clusterId(in.getClusterId())\n               .clusterName(in.getClusterName())\n               .created(in.getCreated())\n               .diskSizeAllocated(in.getDiskSizeAllocated())\n               .diskSizeTotal(in.getDiskSizeTotal())\n               .ipAddress(in.getIpAddress())\n               .jobId(in.getJobId())\n               .jobStatus(in.getJobStatus());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final String name;\n   private final String path;\n   private final Set<String> tags;\n   private final StoragePool.State state;\n   private final StoragePool.Type type;\n   private final String zoneId;\n   private final String zoneName;\n   private final String podId;\n   private final String podName;\n   private final String clusterId;\n   private final String clusterName;\n   private final Date created;\n   private final long diskSizeAllocated;\n   private final long diskSizeTotal;\n   private final String ipAddress;\n   private final String jobId;\n   private final String jobStatus;\n\n   @ConstructorProperties({\n         \"id\", \"name\", \"path\", \"tags\", \"state\", \"type\", \"zoneid\", \"zonename\", \"podid\", \"podname\", \"clusterid\", \"clustername\", \"created\", \"disksizeallocated\", \"disksizetotal\", \"ipaddress\", \"jobid\", \"jobstatus\"\n   })\n   protected StoragePool(String id, @Nullable String name, @Nullable String path, @Nullable Iterable<String> tags,\n            @Nullable StoragePool.State state, @Nullable StoragePool.Type type, @Nullable String zoneId,\n            @Nullable String zoneName, @Nullable String podId, @Nullable String podName, @Nullable String clusterId,\n            @Nullable String clusterName, @Nullable Date created, long diskSizeAllocated, long diskSizeTotal,\n            @Nullable String ipAddress, @Nullable String jobId, @Nullable String jobStatus) {\n      this.id = checkNotNull(id, \"id\");\n      this.name = name;\n      this.path = path;\n      this.tags = tags != null ? ImmutableSet.copyOf(tags) : ImmutableSet.<String> of();\n      this.state = state;\n      this.type = type;\n      this.zoneId = zoneId;\n      this.zoneName = zoneName;\n      this.podId = podId;\n      this.podName = podName;\n      this.clusterId = clusterId;\n      this.clusterName = clusterName;\n      this.created = created;\n      this.diskSizeAllocated = diskSizeAllocated;\n      this.diskSizeTotal = diskSizeTotal;\n      this.ipAddress = ipAddress;\n      this.jobId = jobId;\n      this.jobStatus = jobStatus;\n   }\n\n   public String getId() {\n      return this.id;\n   }\n\n   @Nullable\n   public String getName() {\n      return this.name;\n   }\n\n   @Nullable\n   public String getPath() {\n      return this.path;\n   }\n\n   public Set<String> getTags() {\n      return this.tags;\n   }\n\n   @Nullable\n   public StoragePool.State getState() {\n      return this.state;\n   }\n\n   @Nullable\n   public StoragePool.Type getType() {\n      return this.type;\n   }\n\n   @Nullable\n   public String getZoneId() {\n      return this.zoneId;\n   }\n\n   @Nullable\n   public String getZoneName() {\n      return this.zoneName;\n   }\n\n   @Nullable\n   public String getPodId() {\n      return this.podId;\n   }\n\n   @Nullable\n   public String getPodName() {\n      return this.podName;\n   }\n\n   @Nullable\n   public String getClusterId() {\n      return this.clusterId;\n   }\n\n   @Nullable\n   public String getClusterName() {\n      return this.clusterName;\n   }\n\n   @Nullable\n   public Date getCreated() {\n      return this.created;\n   }\n\n   public long getDiskSizeAllocated() {\n      return this.diskSizeAllocated;\n   }\n\n   public long getDiskSizeTotal() {\n      return this.diskSizeTotal;\n   }\n\n   @Nullable\n   public String getIpAddress() {\n      return this.ipAddress;\n   }\n\n   @Nullable\n   public String getJobId() {\n      return this.jobId;\n   }\n\n   @Nullable\n   public String getJobStatus() {\n      return this.jobStatus;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, name, path, tags, state, type, zoneId, zoneName, podId, podName, clusterId, clusterName, created, diskSizeAllocated, diskSizeTotal, ipAddress, jobId, jobStatus);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      StoragePool that = StoragePool.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n            && Objects.equal(this.name, that.name)\n            && Objects.equal(this.path, that.path)\n            && Objects.equal(this.tags, that.tags)\n            && Objects.equal(this.state, that.state)\n            && Objects.equal(this.type, that.type)\n            && Objects.equal(this.zoneId, that.zoneId)\n            && Objects.equal(this.zoneName, that.zoneName)\n            && Objects.equal(this.podId, that.podId)\n            && Objects.equal(this.podName, that.podName)\n            && Objects.equal(this.clusterId, that.clusterId)\n            && Objects.equal(this.clusterName, that.clusterName)\n            && Objects.equal(this.created, that.created)\n            && Objects.equal(this.diskSizeAllocated, that.diskSizeAllocated)\n            && Objects.equal(this.diskSizeTotal, that.diskSizeTotal)\n            && Objects.equal(this.ipAddress, that.ipAddress)\n            && Objects.equal(this.jobId, that.jobId)\n            && Objects.equal(this.jobStatus, that.jobStatus);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"name\", name).add(\"path\", path).add(\"tags\", tags).add(\"state\", state).add(\"type\", type).add(\"zoneId\", zoneId).add(\"zoneName\", zoneName).add(\"podId\", podId).add(\"podName\", podName).add(\"clusterId\", clusterId).add(\"clusterName\", clusterName).add(\"created\", created).add(\"diskSizeAllocated\", diskSizeAllocated).add(\"diskSizeTotal\", diskSizeTotal).add(\"ipAddress\", ipAddress).add(\"jobId\", jobId).add(\"jobStatus\", jobStatus);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int compareTo(StoragePool other) {\n      return this.id.compareTo(other.id);\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/StorageType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.CaseFormat;\n\n/**\n * @see OfferingApi#listServiceOfferings\n */\npublic enum StorageType {\n   LOCAL,\n\n   SHARED,\n\n   UNRECOGNIZED;\n\n   @Override\n   public String toString() {\n      return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, name());\n   }\n\n   public static StorageType fromValue(String type) {\n      try {\n         return valueOf(CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, checkNotNull(type, \"type\")));\n      } catch (IllegalArgumentException e) {\n         return UNRECOGNIZED;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/SystemVmType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.CaseFormat;\n\npublic enum SystemVmType {\n   DOMAIN_ROUTER,\n\n   CONSOLE_PROXY,\n\n   SECONDARY_STORAGE_VM,\n\n   UNRECOGNIZED;\n\n   @Override\n   public String toString() {\n      return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, name()).toLowerCase();\n   }\n\n   public static SystemVmType fromValue(String type) {\n      try {\n         return valueOf(CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, checkNotNull(type, \"type\")));\n      } catch (IllegalArgumentException e) {\n         return UNRECOGNIZED;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/Tag.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Map;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Maps;\n\n/**\n * Class Tag\n */\npublic class Tag {\n\n   /**\n    * Type of resource to update.\n    */\n   public enum ResourceType {\n      USER_VM(\"UserVm\"),\n      TEMPLATE(\"Template\"),\n      ISO(\"ISO\"),\n      VOLUME(\"Volume\"),\n      SNAPSHOT(\"Snapshot\"),\n      NETWORK(\"Network\"),\n      NIC(\"Nic\"),\n      LOAD_BALANCER(\"LoadBalancer\"),\n      PORT_FORWARDING_RULE(\"PortForwardingRule\"),\n      FIREWALL_RULE(\"FirewallRule\"),\n      SECURITY_GROUP(\"SecurityGroup\"),\n      PUBLIC_IP_ADDRESS(\"PublicIpAddress\"),\n      PROJECT(\"Project\"),\n      VPC(\"Vpc\"),\n      NETWORK_ACL(\"NetworkACL\"),\n      STATIC_ROUTE(\"StaticRoute\"),\n      VM_SNAPSHOT(\"VMSnapshot\"),\n      REMOTE_ACCESS_VPN(\"RemoteAccessVpn\"),\n      ZONE(\"Zone\"),\n      SERVICE_OFFERING(\"ServiceOffering\"),\n      STORAGE(\"Storage\"),\n      PRIVATE_GATEWAY(\"PrivateGateway\"),\n      NETWORK_ACL_LIST(\"NetworkACLList\"),\n      VPN_GATEWAY(\"VpnGateway\"),\n      CUSTOMER_GATEWAY(\"CustomerGateway\"),\n      VPN_CONNECTION(\"VpnConnection\"),\n      UNRECOGNIZED(\"\");\n\n      private String code;\n\n      private static final Map<String, ResourceType> INDEX = Maps.uniqueIndex(ImmutableSet.copyOf(ResourceType.values()),\n              new Function<ResourceType, String>() {\n\n                 @Override\n                 public String apply(ResourceType input) {\n                    return input.code;\n                 }\n\n              });\n\n      ResourceType(String code) {\n         this.code = code;\n      }\n\n      public String getCode() {\n         return code;\n      }\n\n      @Override\n      public String toString() {\n         return code;\n      }\n\n      public static ResourceType fromValue(String resourceType) {\n         String code = checkNotNull(resourceType, \"resourcetype\");\n         return INDEX.containsKey(code) ? INDEX.get(code) : UNRECOGNIZED;\n      }\n   }\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromTag(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String account;\n      protected String customer;\n      protected String domain;\n      protected String domainId;\n      protected String key;\n      protected String project;\n      protected String projectId;\n      protected String resourceId;\n      protected ResourceType resourceType;\n      protected String value;\n\n      /**\n       * @see Tag#getAccount()\n       */\n      public T account(String account) {\n         this.account = account;\n         return self();\n      }\n\n      /**\n       * @see Tag#getCustomer()\n       */\n      public T customer(String customer) {\n         this.customer = customer;\n         return self();\n      }\n\n      /**\n       * @see Tag#getDomain()\n       */\n      public T domain(String domain) {\n         this.domain = domain;\n         return self();\n      }\n\n      /**\n       * @see Tag#getDomainId()\n       */\n      public T domainId(String domainId) {\n         this.domainId = domainId;\n         return self();\n      }\n\n      /**\n       * @see Tag#getKey()\n       */\n      public T key(String key) {\n         this.key = key;\n         return self();\n      }\n\n      /**\n       * @see Tag#getProject()\n       */\n      public T project(String project) {\n         this.project = project;\n         return self();\n      }\n\n      /**\n       * @see Tag#getProjectId()\n       */\n      public T projectId(String projectId) {\n         this.projectId = projectId;\n         return self();\n      }\n\n      /**\n       * @see Tag#getResourceId()\n       */\n      public T resourceId(String resourceId) {\n         this.resourceId = resourceId;\n         return self();\n      }\n\n      /**\n       * @see Tag#getResourceType()\n       */\n      public T resourceType(ResourceType resourceType) {\n         this.resourceType = resourceType;\n         return self();\n      }\n\n      /**\n       * @see Tag#getValue()\n       */\n      public T value(String value) {\n         this.value = value;\n         return self();\n      }\n\n      public Tag build() {\n         return new Tag(account, customer, domain, domainId, key, project,\n                 projectId, resourceId, resourceType, value);\n      }\n\n      public T fromTag(Tag in) {\n         return this\n                 .account(in.getAccount())\n                 .customer(in.getCustomer())\n                 .domain(in.getDomain())\n                 .domainId(in.getDomainId())\n                 .key(in.getKey())\n                 .project(in.getProject())\n                 .projectId(in.getProjectId())\n                 .resourceId(in.getResourceId())\n                 .resourceType(in.getResourceType())\n                 .value(in.getValue());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String account;\n   private final String customer;\n   private final String domain;\n   private final String domainId;\n   private final String key;\n   private final String project;\n   private final String projectId;\n   private final String resourceId;\n   private final ResourceType resourceType;\n   private final String value;\n\n   @ConstructorProperties({\n           \"account\", \"customer\", \"domain\", \"domainid\", \"key\", \"project\", \"projectid\", \"resourceid\",\n            \"resourcetype\", \"value\"\n   })\n   protected Tag(@Nullable String account, @Nullable String customer, @Nullable String domain,\n                 @Nullable String domainId, @Nullable String key, @Nullable String project,\n                 @Nullable String projectId, @Nullable String resourceId,\n                 @Nullable ResourceType resourceType, @Nullable String value) {\n      this.account = account;\n      this.customer = customer;\n      this.domain = domain;\n      this.domainId = domainId;\n      this.key = key;\n      this.project = project;\n      this.projectId = projectId;\n      this.resourceId = resourceId;\n      this.resourceType = resourceType;\n      this.value = value;\n   }\n\n   @Nullable\n   public String getAccount() {\n      return this.account;\n   }\n\n   @Nullable\n   public String getCustomer() {\n      return this.customer;\n   }\n\n   @Nullable\n   public String getDomain() {\n      return this.domain;\n   }\n\n   @Nullable\n   public String getDomainId() {\n      return this.domainId;\n   }\n\n   @Nullable\n   public String getKey() {\n      return this.key;\n   }\n\n   @Nullable\n   public String getProject() {\n      return this.project;\n   }\n\n   @Nullable\n   public String getProjectId() {\n      return this.projectId;\n   }\n\n   @Nullable\n   public String getResourceId() {\n      return this.resourceId;\n   }\n\n   @Nullable\n   public ResourceType getResourceType() {\n      return this.resourceType;\n   }\n\n   @Nullable\n   public String getValue() {\n      return this.value;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(account, customer, domain, domainId, key, project, projectId,\n              resourceId, resourceType, value);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Tag that = Tag.class.cast(obj);\n      return Objects.equal(this.account, that.account)\n              && Objects.equal(this.customer, that.customer)\n              && Objects.equal(this.domain, that.domain)\n              && Objects.equal(this.domainId, that.domainId)\n              && Objects.equal(this.key, that.key)\n              && Objects.equal(this.project, that.project)\n              && Objects.equal(this.projectId, that.projectId)\n              && Objects.equal(this.resourceId, that.resourceId)\n              && Objects.equal(this.resourceType, that.resourceType)\n              && Objects.equal(this.value, that.value);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n              .add(\"account\", account)\n              .add(\"customer\", customer)\n              .add(\"domain\", domain)\n              .add(\"domainId\", domainId)\n              .add(\"key\", key)\n              .add(\"project\", project)\n              .add(\"projectId\", projectId)\n              .add(\"resourceId\", resourceId)\n              .add(\"resourceType\", resourceType)\n              .add(\"value\", value);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/Template.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.base.Strings;\nimport com.google.common.collect.ImmutableSet;\n\npublic class Template implements Comparable<Template> {\n   public enum Status {\n\n      /**\n       * status of download is not known. Example - When the job for downloading doesn't exist\n       * during progress check.\n       */\n      UNKNOWN,\n      /**\n       * the download has been cancelled/aborted.\n       */\n      ABANDONED,\n      /**\n       * the download has reached an error state. Example - there is not route to ssvm agent\n       */\n      DOWNLOAD_ERROR,\n      /**\n       * the download hasn't started.\n       */\n      NOT_DOWNLOADED,\n      /**\n       * the download is in progress\n       */\n      DOWNLOAD_IN_PROGRESS,\n      /**\n       * the resource has been downloaded on secondary storage.\n       */\n      DOWNLOADED,\n\n      // These states are specifically used for extraction of resources out of CS(ironically shown\n      // as download template in the UI, API - extractTemplate ). Some of the generic states (like\n      // abandoned, unknown) above are used for the extraction tasks as well.\n\n      /**\n       * the resource has been uploaded\n       */\n      UPLOADED,\n      /**\n       * the resource upload work hasn't started yet\n       */\n      NOT_UPLOADED,\n      /**\n       * the resource upload has reached error.\n       */\n      UPLOAD_ERROR,\n      /**\n       * the resource upload is in progress.\n       */\n      UPLOAD_IN_PROGRESS, UNRECOGNIZED;\n\n      public static Status fromValue(String state) {\n         // Statuses are in free text form. These are the ones in CloudStack 3.0.4 source\n         // https://github.com/CloudStack/CloudStack/blob/e2e76c70ec51bfb35d755371f6c33856cef8a277/server/src/com/cloud/api/ApiResponseHelper.java#L1968\n         if (Strings.isNullOrEmpty(state)) { return UNKNOWN; }\n         else if (state.equals(\"Processing\")) { return DOWNLOAD_IN_PROGRESS; }\n         else if (state.endsWith(\"% Downloaded\")) { return DOWNLOAD_IN_PROGRESS; }\n         else if (state.equals(\"Installing Template\")) { return DOWNLOAD_IN_PROGRESS; }\n         else if (state.equals(\"Installing ISO\")) { return DOWNLOAD_IN_PROGRESS; }\n         else if (state.equals(\"Download Complete\")) { return DOWNLOADED; }\n         try {\n            return valueOf(checkNotNull(state, \"state\"));\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n\n   }\n\n   public static enum Type {\n\n      USER, BUILTIN, UNRECOGNIZED;\n\n      //TODO do we need camel case routines (e.g. see enums in VirtualMachine) ?\n      public static Type fromValue(String type) {\n         try {\n            return valueOf(checkNotNull(type, \"type\"));\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n   }\n\n   public enum Format {\n\n      VHD, QCOW2, OVA, UNRECOGNIZED;\n\n      public static Format fromValue(String format) {\n         try {\n            return valueOf(checkNotNull(format, \"format\"));\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n   }\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromTemplate(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String id;\n      protected String displayText;\n      protected String domain;\n      protected String domainId;\n      protected String account;\n      protected String accountId;\n      protected String zone;\n      protected String zoneId;\n      protected String OSType;\n      protected String OSTypeId;\n      protected String name;\n      protected Template.Type type;\n      protected Template.Status status;\n      protected Template.Format format;\n      protected String hypervisor;\n      protected Long size;\n      protected Date created;\n      protected Date removed;\n      protected boolean crossZones;\n      protected boolean bootable;\n      protected boolean extractable;\n      protected boolean featured;\n      protected boolean isPublic;\n      protected boolean ready;\n      protected boolean passwordEnabled;\n      protected String jobId;\n      protected String jobStatus;\n      protected String checksum;\n      protected String hostId;\n      protected String hostName;\n      protected String sourceTemplateId;\n      protected String templateTag;\n      protected Set<Tag> tags = ImmutableSet.of();\n\n      /**\n       * @see Template#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see Template#getDisplayText()\n       */\n      public T displayText(String displayText) {\n         this.displayText = displayText;\n         return self();\n      }\n\n      /**\n       * @see Template#getDomain()\n       */\n      public T domain(String domain) {\n         this.domain = domain;\n         return self();\n      }\n\n      /**\n       * @see Template#getDomainId()\n       */\n      public T domainId(String domainId) {\n         this.domainId = domainId;\n         return self();\n      }\n\n      /**\n       * @see Template#getAccount()\n       */\n      public T account(String account) {\n         this.account = account;\n         return self();\n      }\n\n      /**\n       * @see Template#getAccountId()\n       */\n      public T accountId(String accountId) {\n         this.accountId = accountId;\n         return self();\n      }\n\n      /**\n       * @see Template#getZone()\n       */\n      public T zone(String zone) {\n         this.zone = zone;\n         return self();\n      }\n\n      /**\n       * @see Template#getZoneId()\n       */\n      public T zoneId(String zoneId) {\n         this.zoneId = zoneId;\n         return self();\n      }\n\n      /**\n       * @see Template#getOSType()\n       */\n      public T OSType(String OSType) {\n         this.OSType = OSType;\n         return self();\n      }\n\n      /**\n       * @see Template#getOSTypeId()\n       */\n      public T OSTypeId(String OSTypeId) {\n         this.OSTypeId = OSTypeId;\n         return self();\n      }\n\n      /**\n       * @see Template#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /**\n       * @see Template#getType()\n       */\n      public T type(Template.Type type) {\n         this.type = type;\n         return self();\n      }\n\n      /**\n       * @see Template#getStatus()\n       */\n      public T status(Template.Status status) {\n         this.status = status;\n         return self();\n      }\n\n      /**\n       * @see Template#getFormat()\n       */\n      public T format(Template.Format format) {\n         this.format = format;\n         return self();\n      }\n\n      /**\n       * @see Template#getHypervisor()\n       */\n      public T hypervisor(String hypervisor) {\n         this.hypervisor = hypervisor;\n         return self();\n      }\n\n      /**\n       * @see Template#getSize()\n       */\n      public T size(Long size) {\n         this.size = size;\n         return self();\n      }\n\n      /**\n       * @see Template#getCreated()\n       */\n      public T created(Date created) {\n         this.created = created;\n         return self();\n      }\n\n      /**\n       * @see Template#getRemoved()\n       */\n      public T removed(Date removed) {\n         this.removed = removed;\n         return self();\n      }\n\n      /**\n       * @see Template#isCrossZones()\n       */\n      public T crossZones(boolean crossZones) {\n         this.crossZones = crossZones;\n         return self();\n      }\n\n      /**\n       * @see Template#isBootable()\n       */\n      public T bootable(boolean bootable) {\n         this.bootable = bootable;\n         return self();\n      }\n\n      /**\n       * @see Template#isExtractable()\n       */\n      public T extractable(boolean extractable) {\n         this.extractable = extractable;\n         return self();\n      }\n\n      /**\n       * @see Template#isFeatured()\n       */\n      public T featured(boolean featured) {\n         this.featured = featured;\n         return self();\n      }\n\n      /**\n       * @see Template#ispublic()\n       */\n      public T isPublic(boolean isPublic) {\n         this.isPublic = isPublic;\n         return self();\n      }\n\n      /**\n       * @see Template#isReady()\n       */\n      public T ready(boolean ready) {\n         this.ready = ready;\n         return self();\n      }\n\n      /**\n       * @see Template#isPasswordEnabled()\n       */\n      public T passwordEnabled(boolean passwordEnabled) {\n         this.passwordEnabled = passwordEnabled;\n         return self();\n      }\n\n      /**\n       * @see Template#getJobId()\n       */\n      public T jobId(String jobId) {\n         this.jobId = jobId;\n         return self();\n      }\n\n      /**\n       * @see Template#getJobStatus()\n       */\n      public T jobStatus(String jobStatus) {\n         this.jobStatus = jobStatus;\n         return self();\n      }\n\n      /**\n       * @see Template#getChecksum()\n       */\n      public T checksum(String checksum) {\n         this.checksum = checksum;\n         return self();\n      }\n\n      /**\n       * @see Template#getHostId()\n       */\n      public T hostId(String hostId) {\n         this.hostId = hostId;\n         return self();\n      }\n\n      /**\n       * @see Template#getHostName()\n       */\n      public T hostName(String hostName) {\n         this.hostName = hostName;\n         return self();\n      }\n\n      /**\n       * @see Template#getSourceTemplateId()\n       */\n      public T sourceTemplateId(String sourceTemplateId) {\n         this.sourceTemplateId = sourceTemplateId;\n         return self();\n      }\n\n      /**\n       * @see Template#getTemplateTag()\n       */\n      public T templateTag(String templateTag) {\n         this.templateTag = templateTag;\n         return self();\n      }\n\n      /**\n       * @see Template#getTags()\n       */\n      public T tags(Set<Tag> tags) {\n         this.tags = ImmutableSet.copyOf(checkNotNull(tags, \"tags\"));\n         return self();\n      }\n\n      public T tags(Tag... in) {\n         return tags(ImmutableSet.copyOf(in));\n      }\n\n      public Template build() {\n         return new Template(id, displayText, domain, domainId, account, accountId, zone, zoneId, OSType, OSTypeId, name, type, status, format, hypervisor, size, created, removed, crossZones, bootable, extractable, featured, isPublic, ready, passwordEnabled, jobId, jobStatus, checksum, hostId, hostName, sourceTemplateId, templateTag, tags);\n      }\n\n      public T fromTemplate(Template in) {\n         return this\n               .id(in.getId())\n               .displayText(in.getDisplayText())\n               .domain(in.getDomain())\n               .domainId(in.getDomainId())\n               .account(in.getAccount())\n               .accountId(in.getAccountId())\n               .zone(in.getZone())\n               .zoneId(in.getZoneId())\n               .OSType(in.getOSType())\n               .OSTypeId(in.getOSTypeId())\n               .name(in.getName())\n               .type(in.getType())\n               .status(in.getStatus())\n               .format(in.getFormat())\n               .hypervisor(in.getHypervisor())\n               .size(in.getSize())\n               .created(in.getCreated())\n               .removed(in.getRemoved())\n               .crossZones(in.isCrossZones())\n               .bootable(in.isBootable())\n               .extractable(in.isExtractable())\n               .featured(in.isFeatured())\n               .isPublic(in.ispublic())\n               .ready(in.isReady())\n               .passwordEnabled(in.isPasswordEnabled())\n               .jobId(in.getJobId())\n               .jobStatus(in.getJobStatus())\n               .checksum(in.getChecksum())\n               .hostId(in.getHostId())\n               .hostName(in.getHostName())\n               .sourceTemplateId(in.getSourceTemplateId())\n               .templateTag(in.getTemplateTag())\n               .tags(in.getTags());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final String displayText;\n   private final String domain;\n   private final String domainId;\n   private final String account;\n   private final String accountId;\n   private final String zone;\n   private final String zoneId;\n   private final String OSType;\n   private final String OSTypeId;\n   private final String name;\n   private final Template.Type type;\n   private final Template.Status status;\n   private final Template.Format format;\n   private final String hypervisor;\n   private final Long size;\n   private final Date created;\n   private final Date removed;\n   private final boolean crossZones;\n   private final boolean bootable;\n   private final boolean extractable;\n   private final boolean featured;\n   private final boolean ispublic;\n   private final boolean ready;\n   private final boolean passwordEnabled;\n   private final String jobId;\n   private final String jobStatus;\n   private final String checksum;\n   private final String hostId;\n   private final String hostName;\n   private final String sourceTemplateId;\n   private final String templateTag;\n   private final Set<Tag> tags;\n\n   @ConstructorProperties({\n         \"id\", \"displaytext\", \"domain\", \"domainid\", \"account\", \"accountid\", \"zonename\", \"zoneid\", \"ostypename\", \"ostypeid\",\n         \"name\", \"templatetype\", \"status\", \"format\", \"hypervisor\", \"size\", \"created\", \"removed\", \"crossZones\", \"bootable\",\n         \"isextractable\", \"isfeatured\", \"ispublic\", \"isready\", \"passwordenabled\", \"jobid\", \"jobstatus\", \"checksum\", \"hostId\",\n         \"hostname\", \"sourcetemplateid\", \"templatetag\", \"tags\"\n   })\n   protected Template(String id, @Nullable String displayText, @Nullable String domain, @Nullable String domainId,\n                      @Nullable String account, @Nullable String accountId, @Nullable String zone, @Nullable String zoneId,\n                      @Nullable String OSType, @Nullable String OSTypeId, @Nullable String name, @Nullable Template.Type type,\n                      @Nullable Template.Status status, @Nullable Template.Format format, @Nullable String hypervisor,\n                      @Nullable Long size, @Nullable Date created, @Nullable Date removed, boolean crossZones,\n                      boolean bootable, boolean extractable, boolean featured, boolean ispublic, boolean ready, boolean passwordEnabled,\n                      @Nullable String jobId, @Nullable String jobStatus, @Nullable String checksum, @Nullable String hostId,\n                      @Nullable String hostName, @Nullable String sourceTemplateId, @Nullable String templateTag,\n                      @Nullable Set<Tag> tags) {\n      this.id = checkNotNull(id, \"id\");\n      this.displayText = displayText;\n      this.domain = domain;\n      this.domainId = domainId;\n      this.account = account;\n      this.accountId = accountId;\n      this.zone = zone;\n      this.zoneId = zoneId;\n      this.OSType = OSType;\n      this.OSTypeId = OSTypeId;\n      this.name = name;\n      this.type = type;\n      this.status = status;\n      this.format = format;\n      this.hypervisor = hypervisor;\n      this.size = size;\n      this.created = created;\n      this.removed = removed;\n      this.crossZones = crossZones;\n      this.bootable = bootable;\n      this.extractable = extractable;\n      this.featured = featured;\n      this.ispublic = ispublic;\n      this.ready = ready;\n      this.passwordEnabled = passwordEnabled;\n      this.jobId = jobId;\n      this.jobStatus = jobStatus;\n      this.checksum = checksum;\n      this.hostId = hostId;\n      this.hostName = hostName;\n      this.sourceTemplateId = sourceTemplateId;\n      this.templateTag = templateTag;\n      this.tags = tags == null ? ImmutableSet.<Tag>of() : ImmutableSet.copyOf(tags);\n   }\n\n   /**\n    * @return Template id\n    */\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * @return the display text of the template\n    */\n   @Nullable\n   public String getDisplayText() {\n      return this.displayText;\n   }\n\n   /**\n    * @return the name of the domain to which the template beLongs\n    */\n   @Nullable\n   public String getDomain() {\n      return this.domain;\n   }\n\n   /**\n    * @return the ID of the domain to which the template beLongs\n    */\n   @Nullable\n   public String getDomainId() {\n      return this.domainId;\n   }\n\n   /**\n    * @return the name of the account to which the template beLongs\n    */\n   @Nullable\n   public String getAccount() {\n      return this.account;\n   }\n\n   /**\n    * @return the ID of the account to which the template beLongs\n    */\n   @Nullable\n   public String getAccountId() {\n      return this.accountId;\n   }\n\n   /**\n    * @return the name of the zone to which the template beLongs\n    */\n   @Nullable\n   public String getZone() {\n      return this.zone;\n   }\n\n   /**\n    * @return the ID of the zone to which the template beLongs\n    */\n   @Nullable\n   public String getZoneId() {\n      return this.zoneId;\n   }\n\n   /**\n    * @return the name of the OS type to which the template beLongs\n    */\n   @Nullable\n   public String getOSType() {\n      return this.OSType;\n   }\n\n   /**\n    * @return the ID of the OS type to which the template beLongs\n    */\n   @Nullable\n   public String getOSTypeId() {\n      return this.OSTypeId;\n   }\n\n   /**\n    * @return Template name\n    */\n   @Nullable\n   public String getName() {\n      return this.name;\n   }\n\n   /**\n    * @return the type of the template\n    */\n   @Nullable\n   public Template.Type getType() {\n      return this.type;\n   }\n\n   /**\n    * Retrieve the status of the template.\n    *\n    * <p>Note that in CloudStack 2.2.x through to at least 3.0.4, the possible status values are\n    * not well defined by CloudStack. CloudStack returns a plain-text English string for UI\n    * display, which jclouds attempts to parse into an enumeration, but the mapping is incomplete.\n    * This method should be reliable for the common cases, but it is possible (particularly for\n    * error statuses) that this method will return UNRECOGNIZED.</p>\n    *\n    * @return status of the template\n    */\n   @Nullable\n   public Template.Status getStatus() {\n      return this.status;\n   }\n\n   /**\n    * @return the format of the template.\n    */\n   @Nullable\n   public Template.Format getFormat() {\n      return this.format;\n   }\n\n   /**\n    * @return the hypervisor on which the template runs\n    */\n   @Nullable\n   public String getHypervisor() {\n      return this.hypervisor;\n   }\n\n   /**\n    * @return the size of the template in kilobytes\n    */\n   @Nullable\n   public Long getSize() {\n      return this.size;\n   }\n\n   /**\n    * @return the date this template was created\n    */\n   @Nullable\n   public Date getCreated() {\n      return this.created;\n   }\n\n   /**\n    * @return the date this template was removed\n    */\n   @Nullable\n   public Date getRemoved() {\n      return this.removed;\n   }\n\n   /**\n    * @return true if the template is managed across all Zones, false otherwise\n    */\n   public boolean isCrossZones() {\n      return this.crossZones;\n   }\n\n   /**\n    * @return true if the ISO is bootable, false otherwise\n    */\n   public boolean isBootable() {\n      return this.bootable;\n   }\n\n   /**\n    * @return true if the template is extractable, false otherwise\n    */\n   public boolean isExtractable() {\n      return this.extractable;\n   }\n\n   /**\n    * @return true if this template is a featured template, false otherwise\n    */\n   public boolean isFeatured() {\n      return this.featured;\n   }\n\n   public boolean ispublic() {\n      return this.ispublic;\n   }\n\n   /**\n    * @return true if the template is ready to be deployed from, false otherwise\n    */\n   public boolean isReady() {\n      return this.ready;\n   }\n\n   /**\n    * @return true if the reset password feature is enabled, false otherwise\n    */\n   public boolean isPasswordEnabled() {\n      return this.passwordEnabled;\n   }\n\n   /**\n    * @return shows the current pending asynchronous job ID, or null if current\n    *         pending jobs are acting on the template\n    */\n   @Nullable\n   public String getJobId() {\n      return this.jobId;\n   }\n\n   /**\n    * @return shows the current pending asynchronous job status\n    */\n   @Nullable\n   public String getJobStatus() {\n      return this.jobStatus;\n   }\n\n   /**\n    * @return checksum of the template\n    */\n   @Nullable\n   public String getChecksum() {\n      return this.checksum;\n   }\n\n   /**\n    * @return the ID of the secondary storage host for the template\n    */\n   @Nullable\n   public String getHostId() {\n      return this.hostId;\n   }\n\n   /**\n    * @return the name of the secondary storage host for the template\n    */\n   @Nullable\n   public String getHostName() {\n      return this.hostName;\n   }\n\n   /**\n    * @return the template ID of the parent template if present\n    */\n   @Nullable\n   public String getSourceTemplateId() {\n      return this.sourceTemplateId;\n   }\n\n   /**\n    * @return the tag of this template\n    */\n   @Nullable\n   public String getTemplateTag() {\n      return this.templateTag;\n   }\n\n   /**\n    * @return the tags on this template\n    */\n   @Nullable\n   public Set<Tag> getTags() {\n      return this.tags;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, displayText, domain, domainId, account, accountId, zone, zoneId, OSType, OSTypeId, name, type, status, format, hypervisor, size, created, removed, crossZones, bootable, extractable, featured, ispublic, ready, passwordEnabled, jobId, jobStatus, checksum, hostId, hostName, sourceTemplateId, templateTag, tags);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Template that = Template.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n            && Objects.equal(this.displayText, that.displayText)\n            && Objects.equal(this.domain, that.domain)\n            && Objects.equal(this.domainId, that.domainId)\n            && Objects.equal(this.account, that.account)\n            && Objects.equal(this.accountId, that.accountId)\n            && Objects.equal(this.zone, that.zone)\n            && Objects.equal(this.zoneId, that.zoneId)\n            && Objects.equal(this.OSType, that.OSType)\n            && Objects.equal(this.OSTypeId, that.OSTypeId)\n            && Objects.equal(this.name, that.name)\n            && Objects.equal(this.type, that.type)\n            && Objects.equal(this.status, that.status)\n            && Objects.equal(this.format, that.format)\n            && Objects.equal(this.hypervisor, that.hypervisor)\n            && Objects.equal(this.size, that.size)\n            && Objects.equal(this.created, that.created)\n            && Objects.equal(this.removed, that.removed)\n            && Objects.equal(this.crossZones, that.crossZones)\n            && Objects.equal(this.bootable, that.bootable)\n            && Objects.equal(this.extractable, that.extractable)\n            && Objects.equal(this.featured, that.featured)\n            && Objects.equal(this.ispublic, that.ispublic)\n            && Objects.equal(this.ready, that.ready)\n            && Objects.equal(this.passwordEnabled, that.passwordEnabled)\n            && Objects.equal(this.jobId, that.jobId)\n            && Objects.equal(this.jobStatus, that.jobStatus)\n            && Objects.equal(this.checksum, that.checksum)\n            && Objects.equal(this.hostId, that.hostId)\n            && Objects.equal(this.hostName, that.hostName)\n            && Objects.equal(this.sourceTemplateId, that.sourceTemplateId)\n            && Objects.equal(this.templateTag, that.templateTag)\n            && Objects.equal(this.tags, that.tags);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"displayText\", displayText).add(\"domain\", domain).add(\"domainId\", domainId).add(\"account\", account).add(\"accountId\", accountId).add(\"zone\", zone).add(\"zoneId\", zoneId).add(\"OSType\", OSType).add(\"OSTypeId\", OSTypeId).add(\"name\", name).add(\"type\", type).add(\"status\", status).add(\"format\", format).add(\"hypervisor\", hypervisor).add(\"size\", size).add(\"created\", created).add(\"removed\", removed).add(\"crossZones\", crossZones).add(\"bootable\", bootable).add(\"extractable\", extractable).add(\"featured\", featured).add(\"ispublic\", ispublic).add(\"ready\", ready).add(\"passwordEnabled\", passwordEnabled).add(\"jobId\", jobId).add(\"jobStatus\", jobStatus).add(\"checksum\", checksum).add(\"hostId\", hostId).add(\"hostName\", hostName).add(\"sourceTemplateId\", sourceTemplateId).add(\"templateTag\", templateTag).add(\"tags\", tags);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n\n   @Override\n   public int compareTo(Template o) {\n      return id.compareTo(o.getId());\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/TemplateExtraction.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\npublic class TemplateExtraction implements Comparable<TemplateExtraction> {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromTemplateExtraction(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String id;\n      protected String accountId;\n      protected Date created;\n      protected String extractId;\n      protected ExtractMode extractMode;\n      protected String name;\n      protected String state;\n      protected String status;\n      protected String storageType;\n      protected int uploadPercentage;\n      protected String url;\n      protected String zoneId;\n      protected String zoneName;\n\n      /**\n       * @see TemplateExtraction#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see TemplateExtraction#getAccountId()\n       */\n      public T accountId(String accountId) {\n         this.accountId = accountId;\n         return self();\n      }\n\n      /**\n       * @see TemplateExtraction#getCreated()\n       */\n      public T created(Date created) {\n         this.created = created;\n         return self();\n      }\n\n      /**\n       * @see TemplateExtraction#getExtractId()\n       */\n      public T extractId(String extractId) {\n         this.extractId = extractId;\n         return self();\n      }\n\n      /**\n       * @see TemplateExtraction#getExtractMode()\n       */\n      public T extractMode(ExtractMode extractMode) {\n         this.extractMode = extractMode;\n         return self();\n      }\n\n      /**\n       * @see TemplateExtraction#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /**\n       * @see TemplateExtraction#getState()\n       */\n      public T state(String state) {\n         this.state = state;\n         return self();\n      }\n\n      /**\n       * @see TemplateExtraction#getStatus()\n       */\n      public T status(String status) {\n         this.status = status;\n         return self();\n      }\n\n      /**\n       * @see TemplateExtraction#getStorageType()\n       */\n      public T storageType(String storageType) {\n         this.storageType = storageType;\n         return self();\n      }\n\n      /**\n       * @see TemplateExtraction#getUploadPercentage()\n       */\n      public T uploadPercentage(int uploadPercentage) {\n         this.uploadPercentage = uploadPercentage;\n         return self();\n      }\n\n      /**\n       * @see TemplateExtraction#getUrl()\n       */\n      public T url(String url) {\n         this.url = url;\n         return self();\n      }\n\n      /**\n       * @see TemplateExtraction#getZoneId()\n       */\n      public T zoneId(String zoneId) {\n         this.zoneId = zoneId;\n         return self();\n      }\n\n      /**\n       * @see TemplateExtraction#getZoneName()\n       */\n      public T zoneName(String zoneName) {\n         this.zoneName = zoneName;\n         return self();\n      }\n\n      public TemplateExtraction build() {\n         return new TemplateExtraction(id, accountId, created, extractId, extractMode, name, state, status, storageType, uploadPercentage, url, zoneId, zoneName);\n      }\n\n      public T fromTemplateExtraction(TemplateExtraction in) {\n         return this\n               .id(in.getId())\n               .accountId(in.getAccountId())\n               .created(in.getCreated())\n               .extractId(in.getExtractId())\n               .extractMode(in.getExtractMode())\n               .name(in.getName())\n               .state(in.getState())\n               .status(in.getStatus())\n               .storageType(in.getStorageType())\n               .uploadPercentage(in.getUploadPercentage())\n               .url(in.getUrl())\n               .zoneId(in.getZoneId())\n               .zoneName(in.getZoneName());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final String accountId;\n   private final Date created;\n   private final String extractId;\n   private final ExtractMode extractMode;\n   private final String name;\n   private final String state;\n   private final String status;\n   private final String storageType;\n   private final int uploadPercentage;\n   private final String url;\n   private final String zoneId;\n   private final String zoneName;\n\n   @ConstructorProperties({\n         \"id\", \"accountid\", \"created\", \"extractId\", \"extractMode\", \"name\", \"state\", \"status\", \"storagetype\", \"uploadpercentage\", \"url\", \"zoneid\", \"zonename\"\n   })\n   protected TemplateExtraction(String id, @Nullable String accountId, @Nullable Date created, @Nullable String extractId,\n                                @Nullable ExtractMode extractMode, @Nullable String name, @Nullable String state, @Nullable String status,\n                                @Nullable String storageType, int uploadPercentage, @Nullable String url, @Nullable String zoneId,\n                                @Nullable String zoneName) {\n      this.id = checkNotNull(id, \"id\");\n      this.accountId = accountId;\n      this.created = created;\n      this.extractId = extractId;\n      this.extractMode = extractMode;\n      this.name = name;\n      this.state = state;\n      this.status = status;\n      this.storageType = storageType;\n      this.uploadPercentage = uploadPercentage;\n      this.url = url;\n      this.zoneId = zoneId;\n      this.zoneName = zoneName;\n   }\n\n   /**\n    * @return the id of extracted object\n    */\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * @return the account id to which the extracted object belongs\n    */\n   @Nullable\n   public String getAccountId() {\n      return this.accountId;\n   }\n\n   /**\n    * @return the time and date the object was created\n    */\n   @Nullable\n   public Date getCreated() {\n      return this.created;\n   }\n\n   /**\n    * @return the upload id of extracted object\n    */\n   @Nullable\n   public String getExtractId() {\n      return this.extractId;\n   }\n\n   /**\n    * @return the mode of extraction - upload or download\n    */\n   @Nullable\n   public ExtractMode getExtractMode() {\n      return this.extractMode;\n   }\n\n   /**\n    * @return the name of the extracted object\n    */\n   @Nullable\n   public String getName() {\n      return this.name;\n   }\n\n   /**\n    * @return the state of the extracted object\n    */\n   @Nullable\n   public String getState() {\n      return this.state;\n   }\n\n   /**\n    * @return the status of the extraction\n    */\n   @Nullable\n   public String getStatus() {\n      return this.status;\n   }\n\n   /**\n    * @return type of the storage\n    */\n   @Nullable\n   public String getStorageType() {\n      return this.storageType;\n   }\n\n   /**\n    * @return the percentage of the entity uploaded to the specified location\n    */\n   public int getUploadPercentage() {\n      return this.uploadPercentage;\n   }\n\n   /**\n    * @return if mode = upload then url of the uploaded entity. if mode = download the url from which the entity can be downloaded\n    */\n   @Nullable\n   public String getUrl() {\n      return this.url;\n   }\n\n   /**\n    * @return zone ID the object was extracted from\n    */\n   @Nullable\n   public String getZoneId() {\n      return this.zoneId;\n   }\n\n   /**\n    * @return zone name the object was extracted from\n    */\n   @Nullable\n   public String getZoneName() {\n      return this.zoneName;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, accountId, created, extractId, extractMode, name, state, status, storageType, uploadPercentage, url, zoneId, zoneName);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      TemplateExtraction that = TemplateExtraction.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n            && Objects.equal(this.accountId, that.accountId)\n            && Objects.equal(this.created, that.created)\n            && Objects.equal(this.extractId, that.extractId)\n            && Objects.equal(this.extractMode, that.extractMode)\n            && Objects.equal(this.name, that.name)\n            && Objects.equal(this.state, that.state)\n            && Objects.equal(this.status, that.status)\n            && Objects.equal(this.storageType, that.storageType)\n            && Objects.equal(this.uploadPercentage, that.uploadPercentage)\n            && Objects.equal(this.url, that.url)\n            && Objects.equal(this.zoneId, that.zoneId)\n            && Objects.equal(this.zoneName, that.zoneName);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"accountId\", accountId).add(\"created\", created).add(\"extractId\", extractId).add(\"extractMode\", extractMode).add(\"name\", name).add(\"state\", state).add(\"status\", status).add(\"storageType\", storageType).add(\"uploadPercentage\", uploadPercentage).add(\"url\", url).add(\"zoneId\", zoneId).add(\"zoneName\", zoneName);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int compareTo(TemplateExtraction other) {\n      return id.compareTo(other.id);\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/TemplateFilter.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport com.google.common.base.CaseFormat;\n\n/**\n * @see TemplateApi#listTemplates\n */\npublic enum TemplateFilter {\n   /**\n    * templates that are featured and are public\n    */\n   FEATURED,\n   /**\n    * templates that have been registered/created by the owner\n    */\n   SELF,\n   /**\n    * templates that have been registered/created by the owner that can be used\n    * to deploy a new VM\n    */\n   SELF_EXECUTABLE,\n   /**\n    * templates that have been registered/created by the owner that can be used\n    * to deploy a new VM - 3.x filter value.\n    */\n   SELFEXECUTABLE,\n   /**\n    * templates that have been granted to the calling user by another user\n    */\n   SHAREDEXECUTABLE,\n   /**\n    * all templates that can be used to deploy a new VM\n    */\n   EXECUTABLE,\n   /**\n    * templates that are public\n    */\n   COMMUNITY,\n   /**\n    * All templates\n    */\n   ALL;\n\n   @Override\n   public String toString() {\n      return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_HYPHEN, name());\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/TemplateMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Class TemplateMetadata\n */\npublic class TemplateMetadata {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromTemplateMetadata(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String name;\n      protected String osTypeId;\n      protected String displayText;\n      protected String snapshotId;\n      protected String volumeId;\n      protected String virtualMachineId;\n      protected Boolean passwordEnabled;\n\n      /**\n       * @see TemplateMetadata#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /**\n       * @see TemplateMetadata#getOsTypeId()\n       */\n      public T osTypeId(String osTypeId) {\n         this.osTypeId = osTypeId;\n         return self();\n      }\n\n      /**\n       * @see TemplateMetadata#getDisplayText()\n       */\n      public T displayText(String displayText) {\n         this.displayText = displayText;\n         return self();\n      }\n\n      /**\n       * @see TemplateMetadata#getSnapshotId()\n       */\n      public T snapshotId(String snapshotId) {\n         this.snapshotId = snapshotId;\n         return self();\n      }\n\n      /**\n       * @see TemplateMetadata#getVolumeId()\n       */\n      public T volumeId(String volumeId) {\n         this.volumeId = volumeId;\n         return self();\n      }\n\n      /**\n       * @see TemplateMetadata#getVirtualMachineId()\n       */\n      public T virtualMachineId(String virtualMachineId) {\n         this.virtualMachineId = virtualMachineId;\n         return self();\n      }\n\n      /**\n       * @see TemplateMetadata#isPasswordEnabled()\n       */\n      public T passwordEnabled(Boolean passwordEnabled) {\n         this.passwordEnabled = passwordEnabled;\n         return self();\n      }\n\n      public TemplateMetadata build() {\n         return new TemplateMetadata(name, osTypeId, displayText, snapshotId, volumeId, virtualMachineId, passwordEnabled);\n      }\n\n      public T fromTemplateMetadata(TemplateMetadata in) {\n         return this\n               .name(in.getName())\n               .osTypeId(in.getOsTypeId())\n               .displayText(in.getDisplayText())\n               .snapshotId(in.getSnapshotId())\n               .volumeId(in.getVolumeId())\n               .virtualMachineId(in.getVirtualMachineId())\n               .passwordEnabled(in.isPasswordEnabled());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String name;\n   private final String osTypeId;\n   private final String displayText;\n   private final String snapshotId;\n   private final String volumeId;\n   private final String virtualMachineId;\n   private final Boolean passwordEnabled;\n\n   @ConstructorProperties({\n         \"name\", \"osTypeId\", \"displayText\", \"snapshotId\", \"volumeId\", \"virtualMachineId\", \"passwordEnabled\"\n   })\n   protected TemplateMetadata(String name, @Nullable String osTypeId, @Nullable String displayText, @Nullable String snapshotId,\n                              @Nullable String volumeId, String virtualMachineId, Boolean passwordEnabled) {\n      this.name = checkNotNull(name, \"name\");\n      this.osTypeId = osTypeId;\n      this.displayText = displayText;\n      this.snapshotId = snapshotId;\n      this.volumeId = volumeId;\n      this.virtualMachineId = virtualMachineId;\n      this.passwordEnabled = passwordEnabled;\n   }\n\n   /**\n    * @return the name of the template\n    */\n   public String getName() {\n      return this.name;\n   }\n\n   /**\n    * @return the ID of the OS Type that best represents the OS of this template.\n    */\n   @Nullable\n   public String getOsTypeId() {\n      return this.osTypeId;\n   }\n\n   /**\n    * @return the display text of the template. This is usually used for display purposes.\n    */\n   @Nullable\n   public String getDisplayText() {\n      return this.displayText;\n   }\n\n   /**\n    * @return the ID of the snapshot the template is being created from\n    */\n   @Nullable\n   public String getSnapshotId() {\n      return this.snapshotId;\n   }\n\n   /**\n    * @return the ID of the disk volume the template is being created from\n    */\n   @Nullable\n   public String getVolumeId() {\n      return this.volumeId;\n   }\n\n   /**\n    * @return Optional, VM ID\n    */\n   @Nullable\n   public String getVirtualMachineId() {\n      return this.virtualMachineId;\n   }\n\n   @Nullable\n   public Boolean isPasswordEnabled() {\n      return this.passwordEnabled;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(name, osTypeId, displayText, snapshotId, volumeId, virtualMachineId, passwordEnabled);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      TemplateMetadata that = TemplateMetadata.class.cast(obj);\n      return Objects.equal(this.name, that.name)\n            && Objects.equal(this.osTypeId, that.osTypeId)\n            && Objects.equal(this.displayText, that.displayText)\n            && Objects.equal(this.snapshotId, that.snapshotId)\n            && Objects.equal(this.volumeId, that.volumeId)\n            && Objects.equal(this.virtualMachineId, that.virtualMachineId)\n            && Objects.equal(this.passwordEnabled, that.passwordEnabled);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"name\", name).add(\"osTypeId\", osTypeId).add(\"displayText\", displayText).add(\"snapshotId\", snapshotId)\n            .add(\"volumeId\", volumeId).add(\"virtualMachineId\", virtualMachineId).add(\"passwordEnabled\", passwordEnabled);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/TemplatePermission.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\npublic class TemplatePermission {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromTemplatePermission(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String id;\n      protected String account;\n      protected String domainId;\n      protected boolean isPublic;\n\n      /**\n       * @see TemplatePermission#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see TemplatePermission#getAccount()\n       */\n      public T account(String account) {\n         this.account = account;\n         return self();\n      }\n\n      /**\n       * @see TemplatePermission#getDomainId()\n       */\n      public T domainId(String domainId) {\n         this.domainId = domainId;\n         return self();\n      }\n\n      /**\n       * @see TemplatePermission#isPublic()\n       */\n      public T isPublic(boolean isPublic) {\n         this.isPublic = isPublic;\n         return self();\n      }\n\n      public TemplatePermission build() {\n         return new TemplatePermission(id, account, domainId, isPublic);\n      }\n\n      public T fromTemplatePermission(TemplatePermission in) {\n         return this\n               .id(in.getId())\n               .account(in.getAccount())\n               .domainId(in.getDomainId())\n               .isPublic(in.isPublic());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final String account;\n   private final String domainId;\n   private final boolean isPublic;\n\n   @ConstructorProperties({\n         \"id\", \"account\", \"domainid\", \"ispublic\"\n   })\n   protected TemplatePermission(String id, @Nullable String account, @Nullable String domainId, boolean isPublic) {\n      this.id = checkNotNull(id, \"id\");\n      this.account = account;\n      this.domainId = domainId;\n      this.isPublic = isPublic;\n   }\n\n   /**\n    * Gets the template ID\n    *\n    * @return the template ID\n    */\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * Gets the list of accounts the template is available for\n    *\n    * @return the list of accounts the template is available for\n    */\n   @Nullable\n   public String getAccount() {\n      return this.account;\n   }\n\n   /**\n    * Gets the ID of the domain to which the template belongs\n    *\n    * @return the ID of the domain to which the template belongs\n    */\n   @Nullable\n   public String getDomainId() {\n      return this.domainId;\n   }\n\n   /**\n    * Returns true if this template is a public template, false otherwise\n    *\n    * @return true if this template is a public template, false otherwise\n    */\n   public boolean isPublic() {\n      return this.isPublic;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, account, domainId, isPublic);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      TemplatePermission that = TemplatePermission.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n            && Objects.equal(this.account, that.account)\n            && Objects.equal(this.domainId, that.domainId)\n            && Objects.equal(this.isPublic, that.isPublic);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"account\", account).add(\"domainId\", domainId).add(\"isPublic\", isPublic);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/TrafficType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.CaseFormat;\n\n/**\n * @see NetworkOfferingApi#listNetworkOfferings\n */\npublic enum TrafficType {\n\n   /**\n    * traffic to the public internet\n    */\n   PUBLIC,\n   /**\n    * VM-to-VM traffic and VMs are assigned a virtual IP created by CloudStack\n    */\n   GUEST,\n   /**\n    * System network that only Admin can view, and only when isSystem is\n    * specified.\n    */\n   STORAGE,\n   /**\n    * System network that only Admin can view, and only when isSystem is\n    * specified.\n    */\n   MANAGEMENT,\n   /**\n    * System network that only Admin can view, and only when isSystem is\n    * specified.\n    */\n   CONTROL,\n\n   UNRECOGNIZED;\n\n   @Override\n   public String toString() {\n      return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name());\n   }\n\n   public static TrafficType fromValue(String type) {\n      try {\n         return valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, checkNotNull(type, \"type\")));\n      } catch (IllegalArgumentException e) {\n         return UNRECOGNIZED;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/UsageRecord.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\nimport java.util.Map;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Maps;\nimport java.util.Set;\n\n/**\n * Represents a usage record from CloudStack\n */\npublic class UsageRecord {\n\n   /**\n    */\n   public static enum UsageType {\n      RUNNING_VM(1),\n      ALLOCATED_VM(2),\n      IP_ADDRESS(3),\n      NETWORK_BYTES_SENT(4),\n      NETWORK_BYTES_RECEIVED(5),\n      VOLUME(6),\n      TEMPLATE(7),\n      ISO(8),\n      SNAPSHOT(9),\n      SECURITY_GROUP(10),\n      LOAD_BALANCER_POLICY(11),\n      PORT_FORWARDING_RULE(12),\n      NETWORK_OFFERING(13),\n      VPN_USERS(14),\n      VM_DISK_IO_READ(21),\n      VM_DISK_IO_WRITE(22),\n      VM_DISK_BYTES_READ(23),\n      VM_DISK_BYTES_WRITE(24),\n      VM_SNAPSHOT(25),\n      VOLUME_SECONDARY(26),\n      VM_SNAPSHOT_ON_PRIMARY(27),\n      UNRECOGNIZED(0);\n\n      private int code;\n\n      private static final Map<Integer, UsageType> INDEX = Maps.uniqueIndex(ImmutableSet.copyOf(UsageType.values()),\n            new Function<UsageType, Integer>() {\n\n               @Override\n               public Integer apply(UsageType input) {\n                  return input.code;\n               }\n\n            });\n\n      UsageType(int code) {\n         this.code = code;\n      }\n\n      @Override\n      public String toString() {\n         return \"\" + code;\n      }\n\n      public static UsageType fromValue(String usageType) {\n         Integer code = Integer.valueOf(checkNotNull(usageType, \"usageType\"));\n         return INDEX.containsKey(code) ? INDEX.get(code) : UNRECOGNIZED;\n      }\n\n   }\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromUsageRecord(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String id;\n      protected String description;\n      protected String accountId;\n      protected String accountName;\n      protected String domainId;\n      protected Date startDate;\n      protected Date endDate;\n      protected Date assignDate;\n      protected String releaseDate;\n      protected String zoneId;\n      protected String virtualMachineId;\n      protected String virtualMachineName;\n      protected String serviceOfferingId;\n      protected String templateId;\n      protected String ipAddress;\n      protected Boolean isSourceNAT;\n      protected double rawUsageHours;\n      protected String usage;\n      protected Long size;\n      protected String type;\n      protected UsageType usageType;\n      protected String project;\n      protected String projectId;\n      protected String domain;\n      protected Long virtualSize;\n      protected Long cpuNumber;\n      protected Long cpuSpeed;\n      protected Long memory;\n      protected Boolean isSystem;\n      protected String networkId;\n      protected Boolean isDefault;\n      protected Set<Tag> tags;\n\n      /**\n       * @see UsageRecord#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see UsageRecord#getDescription()\n       */\n      public T description(String description) {\n         this.description = description;\n         return self();\n      }\n\n      /**\n       * @see UsageRecord#getAccountId()\n       */\n      public T accountId(String accountId) {\n         this.accountId = accountId;\n         return self();\n      }\n\n      /**\n       * @see UsageRecord#getAccountName()\n       */\n      public T accountName(String accountName) {\n         this.accountName = accountName;\n         return self();\n      }\n\n      /**\n       * @see UsageRecord#getDomainId()\n       */\n      public T domainId(String domainId) {\n         this.domainId = domainId;\n         return self();\n      }\n\n      /**\n       * @see UsageRecord#getStartDate()\n       */\n      public T startDate(Date startDate) {\n         this.startDate = startDate;\n         return self();\n      }\n\n      /**\n       * @see UsageRecord#getEndDate()\n       */\n      public T endDate(Date endDate) {\n         this.endDate = endDate;\n         return self();\n      }\n\n      /**\n       * @see UsageRecord#getAssignDate()\n       */\n      public T assignDate(Date assignDate) {\n         this.assignDate = assignDate;\n         return self();\n      }\n\n      /**\n       * @see UsageRecord#getReleaseDate()\n       */\n      public T releaseDate(String releaseDate) {\n         this.releaseDate = releaseDate;\n         return self();\n      }\n\n      /**\n       * @see UsageRecord#getZoneId()\n       */\n      public T zoneId(String zoneId) {\n         this.zoneId = zoneId;\n         return self();\n      }\n\n      /**\n       * @see UsageRecord#getVirtualMachineId()\n       */\n      public T virtualMachineId(String virtualMachineId) {\n         this.virtualMachineId = virtualMachineId;\n         return self();\n      }\n\n      /**\n       * @see UsageRecord#getVirtualMachineName()\n       */\n      public T virtualMachineName(String virtualMachineName) {\n         this.virtualMachineName = virtualMachineName;\n         return self();\n      }\n\n      /**\n       * @see UsageRecord#getServiceOfferingId()\n       */\n      public T serviceOfferingId(String serviceOfferingId) {\n         this.serviceOfferingId = serviceOfferingId;\n         return self();\n      }\n\n      /**\n       * @see UsageRecord#getTemplateId()\n       */\n      public T templateId(String templateId) {\n         this.templateId = templateId;\n         return self();\n      }\n\n      /**\n       * @see UsageRecord#getIpAddress()\n       */\n      public T ipAddress(String ipAddress) {\n         this.ipAddress = ipAddress;\n         return self();\n      }\n\n      /**\n       * @see UsageRecord#isSourceNAT()\n       */\n      public T isSourceNAT(Boolean isSourceNAT) {\n         this.isSourceNAT = isSourceNAT;\n         return self();\n      }\n\n      /**\n       * @see UsageRecord#getRawUsageHours()\n       */\n      public T rawUsageHours(double rawUsageHours) {\n         this.rawUsageHours = rawUsageHours;\n         return self();\n      }\n\n      /**\n       * @see UsageRecord#getUsage()\n       */\n      public T usage(String usage) {\n         this.usage = usage;\n         return self();\n      }\n      \n      /**\n       * @see UsageRecord#getSize()\n       */\n      public T size(Long size) {\n         this.size = size;\n         return self();\n      }\n\n      /**\n       * @see UsageRecord#getType()\n       */\n      public T type(String type) {\n         this.type = type;\n         return self();\n      }\n\n      /**\n       * @see UsageRecord#getUsageType()\n       */\n      public T usageType(UsageType usageType) {\n         this.usageType = usageType;\n         return self();\n      }\n\n      /**\n       * @see UsageRecord#getProject()\n       */\n      public T project(String project) {\n         this.project = project;\n         return self();\n      }\n      \n      /**\n       * @see UsageRecord#getProjectId()\n       */\n      public T projectId(String projectId) {\n         this.projectId = projectId;\n         return self();\n      }\n      \n      /**\n       * @see UsageRecord#getDomain()\n       */\n      public T domain(String domain) {\n          this.domain = domain;\n          return self();\n      }\n      \n      /**\n       * @see UsageRecord#getVirtualSize()\n       */\n      public T virtualSize(Long virtualSize) {\n          this.virtualSize = virtualSize;\n          return self();\n      }\n      \n      /**\n       * @see UsageRecord#getCpuNumber()\n       */\n      public T cpuNumber(Long cpuNumber) {\n          this.cpuNumber = cpuNumber;\n          return self();\n      }\n    \n      /**\n       * @see UsageRecord#getCpuSpeed()\n       */\n      public T cpuSpeed(Long cpuSpeed) {\n          this.cpuSpeed = cpuSpeed;\n          return self();\n      }\n    \n      /**\n       * @see UsageRecord#getMemory()\n       */\n      public T memory(Long memory) {\n          this.memory = memory;\n          return self();\n      }\n      \n      /**\n       * @see UsageRecord#isSystem()\n       */\n      public T isSystem(Boolean isSystem) {\n          this.isSystem = isSystem;\n          return self();\n      }\n      \n      /**\n       * @see UsageRecord#getNetworkId()\n       */\n      public T networkId(String networkId) {\n          this.networkId = networkId;\n          return self();\n      }\n      \n      /**\n       * @see UsageRecord#isDefault()\n       */\n      public T isDefault(Boolean isDefault) {\n          this.isDefault = isDefault;\n          return self();\n      }\n      /**\n       * @see UsageRecord#getTags()\n       */\n      public T tags(Set<Tag> tags) {\n          this.tags = tags;\n          return self();\n      }\n      public UsageRecord build() {\n         return new UsageRecord(id, description, accountId, accountName, domainId, startDate, endDate, assignDate, releaseDate,\n               zoneId, virtualMachineId, virtualMachineName, serviceOfferingId, templateId, ipAddress, isSourceNAT, rawUsageHours,\n               usage, size, type, usageType, project, projectId, domain, virtualSize, cpuNumber, cpuSpeed, memory, isSystem,\n               networkId, isDefault, tags);\n      }\n\n      public T fromUsageRecord(UsageRecord in) {\n         return this\n               .id(in.getId())\n               .description(in.getDescription())\n               .accountId(in.getAccountId())\n               .accountName(in.getAccountName())\n               .domainId(in.getDomainId())\n               .startDate(in.getStartDate())\n               .endDate(in.getEndDate())\n               .assignDate(in.getAssignDate())\n               .releaseDate(in.getReleaseDate())\n               .zoneId(in.getZoneId())\n               .virtualMachineId(in.getVirtualMachineId())\n               .virtualMachineName(in.getVirtualMachineName())\n               .serviceOfferingId(in.getServiceOfferingId())\n               .templateId(in.getTemplateId())\n               .ipAddress(in.getIpAddress())\n               .isSourceNAT(in.isSourceNAT())\n               .rawUsageHours(in.getRawUsageHours())\n               .usage(in.getUsage())\n               .size(in.getSize())\n               .type(in.getType())\n               .usageType(in.getUsageType())\n               .project(in.getProject())\n               .projectId(in.getProjectId())\n               .domain(in.getDomain())\n               .virtualSize(in.getVirtualSize())\n               .cpuNumber(in.getCpuNumber())\n               .cpuSpeed(in.getCpuSpeed())\n               .memory(in.getMemory())\n               .isSystem(in.isSystem())\n               .networkId(in.getNetworkId())\n               .isDefault(in.isDefault())\n               .tags(in.getTags());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final String description;\n   private final String accountId;\n   private final String accountName;\n   private final String domainId;\n   private final Date startDate;\n   private final Date endDate;\n   private final Date assignDate;\n   private final String releaseDate;\n   private final String zoneId;\n   private final String virtualMachineId;\n   private final String virtualMachineName;\n   private final String serviceOfferingId;\n   private final String templateId;\n   private final String ipAddress;\n   private final Boolean isSourceNAT;\n   private final double rawUsageHours;\n   private final String usage;\n   private final Long size;\n   private final String type;\n   private final UsageType usageType;\n   private final String project;\n   private final String projectId;\n   private final String domain;\n   private final Long virtualSize;\n   private final Long cpuNumber;\n   private final Long cpuSpeed;\n   private final Long memory;\n   private final Boolean isSystem;\n   private final String networkId;\n   private final Boolean isDefault;\n   private final Set<Tag> tags;\n\n   @ConstructorProperties({\n         \"usageid\", \"description\", \"accountid\", \"account\", \"domainid\", \"startdate\", \"enddate\", \"assigndate\", \"releasedate\",\n         \"zoneid\", \"virtualmachineid\", \"name\", \"offeringid\", \"templateid\", \"ipaddress\", \"issourcenat\", \"rawusage\", \"usage\",\n         \"size\", \"type\", \"usagetype\", \"project\", \"projectid\", \"domain\", \"virtualsize\", \"cpunumber\", \"cpuspeed\", \"memory\",\n         \"issystem\", \"networkid\", \"isdefault\", \"tags\"\n   })\n   protected UsageRecord(String id, @Nullable String description, @Nullable String accountId, @Nullable String accountName,\n                         @Nullable String domainId, @Nullable Date startDate, @Nullable Date endDate, @Nullable Date assignDate,\n                         @Nullable String releaseDate, @Nullable String zoneId, @Nullable String virtualMachineId, @Nullable String virtualMachineName,\n                         @Nullable String serviceOfferingId, @Nullable String templateId, @Nullable String ipAddress,\n                         @Nullable Boolean isSourceNAT, double rawUsageHours, @Nullable String usage, @Nullable Long size,\n                         @Nullable String type, @Nullable UsageType usageType, @Nullable String project, @Nullable String projectId,\n                         @Nullable String domain, @Nullable Long virtualSize, @Nullable Long cpuNumber, @Nullable Long cpuSpeed, @Nullable Long memory, \n                         @Nullable Boolean isSystem, @Nullable String networkId, @Nullable Boolean isDefault, @Nullable Set<Tag> tags) {\n      this.id = id;\n      this.description = description;\n      this.accountId = accountId;\n      this.accountName = accountName;\n      this.domainId = domainId;\n      this.startDate = startDate;\n      this.endDate = endDate;\n      this.assignDate = assignDate;\n      this.releaseDate = releaseDate;\n      this.zoneId = zoneId;\n      this.virtualMachineId = virtualMachineId;\n      this.virtualMachineName = virtualMachineName;\n      this.serviceOfferingId = serviceOfferingId;\n      this.templateId = templateId;\n      this.ipAddress = ipAddress;\n      this.isSourceNAT = isSourceNAT;\n      this.rawUsageHours = rawUsageHours;\n      this.usage = usage;\n      this.size = size;\n      this.type = type;\n      this.usageType = usageType;\n      this.project = project;\n      this.projectId = projectId;\n      this.domain = domain;\n      this.virtualSize = virtualSize;\n      this.cpuNumber = cpuNumber;\n      this.cpuSpeed = cpuSpeed;\n      this.memory = memory;\n      this.isSystem = isSystem;\n      this.networkId = networkId;\n      this.isDefault = isDefault;\n      this.tags = tags == null ? ImmutableSet.<Tag>of() : ImmutableSet.copyOf(tags);\n   }\n\n   public String getId() {\n      return this.id;\n   }\n\n   @Nullable\n   public String getDescription() {\n      return this.description;\n   }\n\n   @Nullable\n   public String getAccountId() {\n      return this.accountId;\n   }\n\n   @Nullable\n   public String getAccountName() {\n      return this.accountName;\n   }\n\n   @Nullable\n   public String getDomainId() {\n      return this.domainId;\n   }\n\n   @Nullable\n   public Date getStartDate() {\n      return this.startDate;\n   }\n\n   @Nullable\n   public Date getEndDate() {\n      return this.endDate;\n   }\n\n   @Nullable\n   public Date getAssignDate() {\n      return this.assignDate;\n   }\n\n   @Nullable\n   public String getReleaseDate() {\n      return this.releaseDate;\n   }\n\n   @Nullable\n   public String getZoneId() {\n      return this.zoneId;\n   }\n\n   @Nullable\n   public String getVirtualMachineId() {\n      return this.virtualMachineId;\n   }\n\n   @Nullable\n   public String getVirtualMachineName() {\n      return this.virtualMachineName;\n   }\n\n   @Nullable\n   public String getServiceOfferingId() {\n      return this.serviceOfferingId;\n   }\n\n   @Nullable\n   public String getTemplateId() {\n      return this.templateId;\n   }\n\n   @Nullable\n   public String getIpAddress() {\n      return this.ipAddress;\n   }\n\n   @Nullable\n   public Boolean isSourceNAT() {\n      return this.isSourceNAT;\n   }\n\n   public double getRawUsageHours() {\n      return this.rawUsageHours;\n   }\n\n   @Nullable\n   public String getUsage() {\n      return this.usage;\n   }\n   \n   public Long getSize() {\n      return this.size;\n   }\n\n   @Nullable\n   public String getType() {\n      return this.type;\n   }\n\n   @Nullable\n   public UsageType getUsageType() {\n      return this.usageType;\n   }\n   \n   @Nullable\n   public String getProject() {\n      return this.project;\n   }\n   \n   @Nullable\n   public String getProjectId() {\n      return this.projectId;\n   }\n\n    @Nullable\n    public String getDomain() {\n        return domain;\n    }\n\n    @Nullable\n    public Long getVirtualSize() {\n        return virtualSize;\n    }\n\n    @Nullable\n    public Long getCpuNumber() {\n        return cpuNumber;\n    }\n\n    @Nullable\n    public Long getCpuSpeed() {\n        return cpuSpeed;\n    }\n\n    @Nullable\n    public Long getMemory() {\n        return memory;\n    }\n\n    @Nullable\n    public Boolean isSystem() {\n        return isSystem;\n    }\n\n    @Nullable\n    public String getNetworkId() {\n        return networkId;\n    }\n\n    @Nullable\n    public Boolean isDefault() {\n        return isDefault;\n    }\n   @Nullable\n    public Set<Tag> getTags() {\n        return tags;\n    }\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, description, accountId, accountName, domainId, startDate, endDate, assignDate, releaseDate,\n            zoneId, virtualMachineId, virtualMachineName, serviceOfferingId, templateId, ipAddress, isSourceNAT, rawUsageHours,\n            size, usage, type, usageType, project, projectId, domain, virtualSize, cpuNumber, cpuSpeed, memory, isSystem,\n            networkId, isDefault, tags);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      UsageRecord that = UsageRecord.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n            && Objects.equal(this.description, that.description)\n            && Objects.equal(this.accountId, that.accountId)\n            && Objects.equal(this.accountName, that.accountName)\n            && Objects.equal(this.domainId, that.domainId)\n            && Objects.equal(this.startDate, that.startDate)\n            && Objects.equal(this.endDate, that.endDate)\n            && Objects.equal(this.assignDate, that.assignDate)\n            && Objects.equal(this.releaseDate, that.releaseDate)\n            && Objects.equal(this.zoneId, that.zoneId)\n            && Objects.equal(this.virtualMachineId, that.virtualMachineId)\n            && Objects.equal(this.virtualMachineName, that.virtualMachineName)\n            && Objects.equal(this.serviceOfferingId, that.serviceOfferingId)\n            && Objects.equal(this.templateId, that.templateId)\n            && Objects.equal(this.ipAddress, that.ipAddress)\n            && Objects.equal(this.isSourceNAT, that.isSourceNAT)\n            && Objects.equal(this.rawUsageHours, that.rawUsageHours)\n            && Objects.equal(this.usage, that.usage)\n            && Objects.equal(this.size, that.size)\n            && Objects.equal(this.type, that.type)\n            && Objects.equal(this.usageType, that.usageType)\n            && Objects.equal(this.project, that.project)\n            && Objects.equal(this.domain, that.domain)\n            && Objects.equal(this.virtualSize, that.virtualSize)\n            && Objects.equal(this.cpuNumber, that.cpuNumber)\n            && Objects.equal(this.cpuSpeed, that.cpuSpeed)\n            && Objects.equal(this.memory, that.memory)\n            && Objects.equal(this.isSystem, that.isSystem)\n            && Objects.equal(this.networkId, that.networkId)\n            && Objects.equal(this.isDefault, that.isDefault)\n            && Objects.equal(this.tags, that.tags);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"description\", description).add(\"accountId\", accountId).add(\"accountName\", accountName)\n            .add(\"domainId\", domainId).add(\"startDate\", startDate).add(\"endDate\", endDate).add(\"assignDate\", assignDate)\n            .add(\"releaseDate\", releaseDate).add(\"zoneId\", zoneId).add(\"virtualMachineId\", virtualMachineId)\n            .add(\"virtualMachineName\", virtualMachineName).add(\"serviceOfferingId\", serviceOfferingId).add(\"templateId\", templateId)\n            .add(\"ipAddress\", ipAddress).add(\"isSourceNAT\", isSourceNAT).add(\"rawUsageHours\", rawUsageHours).add(\"usage\", usage)\n            .add(\"size\", size).add(\"type\", type).add(\"usageType\", usageType).add(\"project\", project).add(\"projectId\", projectId)\n            .add(\"domain\", domain).add(\"virtualSize\", virtualSize).add(\"cpuNumber\", cpuNumber).add(\"cpuSpeed\", cpuSpeed).add(\"memory\", memory)\n            .add(\"isSystem\", isSystem).add(\"networkId\", networkId).add(\"isDefault\", isDefault).add(\"tags\", tags);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/User.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Class User\n */\npublic class User {\n\n   /**\n    */\n   public static enum State {\n      ENABLED,\n      DISABLED,\n      UNKNOWN;\n\n      public static State fromValue(String value) {\n         try {\n            return valueOf(value.toUpperCase());\n         } catch (IllegalArgumentException e) {\n            return UNKNOWN;\n         }\n      }\n\n      @Override\n      public String toString() {\n         return name().toLowerCase();\n      }\n   }\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromUser(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String id;\n      protected String name;\n      protected String firstName;\n      protected String lastName;\n      protected String email;\n      protected Date created;\n      protected User.State state;\n      protected String account;\n      protected Account.Type accountType;\n      protected String domain;\n      protected String domainId;\n      protected String timeZone;\n      protected String apiKey;\n      protected String secretKey;\n\n      /**\n       * @see User#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see User#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /**\n       * @see User#getFirstName()\n       */\n      public T firstName(String firstName) {\n         this.firstName = firstName;\n         return self();\n      }\n\n      /**\n       * @see User#getLastName()\n       */\n      public T lastName(String lastName) {\n         this.lastName = lastName;\n         return self();\n      }\n\n      /**\n       * @see User#getEmail()\n       */\n      public T email(String email) {\n         this.email = email;\n         return self();\n      }\n\n      /**\n       * @see User#getCreated()\n       */\n      public T created(Date created) {\n         this.created = created;\n         return self();\n      }\n\n      /**\n       * @see User#getState()\n       */\n      public T state(User.State state) {\n         this.state = state;\n         return self();\n      }\n\n      /**\n       * @see User#getAccount()\n       */\n      public T account(String account) {\n         this.account = account;\n         return self();\n      }\n\n      /**\n       * @see User#getAccountType()\n       */\n      public T accountType(Account.Type accountType) {\n         this.accountType = accountType;\n         return self();\n      }\n\n      /**\n       * @see User#getDomain()\n       */\n      public T domain(String domain) {\n         this.domain = domain;\n         return self();\n      }\n\n      /**\n       * @see User#getDomainId()\n       */\n      public T domainId(String domainId) {\n         this.domainId = domainId;\n         return self();\n      }\n\n      /**\n       * @see User#getTimeZone()\n       */\n      public T timeZone(String timeZone) {\n         this.timeZone = timeZone;\n         return self();\n      }\n\n      /**\n       * @see User#getApiKey()\n       */\n      public T apiKey(String apiKey) {\n         this.apiKey = apiKey;\n         return self();\n      }\n\n      /**\n       * @see User#getSecretKey()\n       */\n      public T secretKey(String secretKey) {\n         this.secretKey = secretKey;\n         return self();\n      }\n\n      public User build() {\n         return new User(id, name, firstName, lastName, email, created, state, account, accountType, domain, domainId, timeZone, apiKey, secretKey);\n      }\n\n      public T fromUser(User in) {\n         return this\n               .id(in.getId())\n               .name(in.getName())\n               .firstName(in.getFirstName())\n               .lastName(in.getLastName())\n               .email(in.getEmail())\n               .created(in.getCreated())\n               .state(in.getState())\n               .account(in.getAccount())\n               .accountType(in.getAccountType())\n               .domain(in.getDomain())\n               .domainId(in.getDomainId())\n               .timeZone(in.getTimeZone())\n               .apiKey(in.getApiKey())\n               .secretKey(in.getSecretKey());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final String name;\n   private final String firstName;\n   private final String lastName;\n   private final String email;\n   private final Date created;\n   private final User.State state;\n   private final String account;\n   private final Account.Type accountType;\n   private final String domain;\n   private final String domainId;\n   private final String timeZone;\n   private final String apiKey;\n   private final String secretKey;\n\n   @ConstructorProperties({\n         \"id\", \"username\", \"firstname\", \"lastname\", \"email\", \"created\", \"state\", \"account\", \"accounttype\", \"domain\",\n         \"domainid\", \"timezone\", \"apikey\", \"secretkey\"\n   })\n   protected User(String id, @Nullable String name, @Nullable String firstName, @Nullable String lastName,\n                  @Nullable String email, @Nullable Date created, @Nullable User.State state, @Nullable String account,\n                  @Nullable Account.Type accountType, @Nullable String domain, @Nullable String domainId, @Nullable String timeZone,\n                  @Nullable String apiKey, @Nullable String secretKey) {\n      this.id = checkNotNull(id, \"id\");\n      this.name = name;\n      this.firstName = firstName;\n      this.lastName = lastName;\n      this.email = email;\n      this.created = created;\n      this.state = state;\n      this.account = account;\n      this.accountType = accountType;\n      this.domain = domain;\n      this.domainId = domainId;\n      this.timeZone = timeZone;\n      this.apiKey = apiKey;\n      this.secretKey = secretKey;\n   }\n\n   /**\n    * @return the user ID\n    */\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * @return the user name\n    */\n   @Nullable\n   public String getName() {\n      return this.name;\n   }\n\n   /**\n    * @return the user firstname\n    */\n   @Nullable\n   public String getFirstName() {\n      return this.firstName;\n   }\n\n   /**\n    * @return the user lastname\n    */\n   @Nullable\n   public String getLastName() {\n      return this.lastName;\n   }\n\n   /**\n    * @return the user email address\n    */\n   @Nullable\n   public String getEmail() {\n      return this.email;\n   }\n\n   /**\n    * @return the date and time the user account was created\n    */\n   @Nullable\n   public Date getCreated() {\n      return this.created;\n   }\n\n   /**\n    * @return the user state\n    */\n   @Nullable\n   public User.State getState() {\n      return this.state;\n   }\n\n   /**\n    * @return the account name of the user\n    */\n   @Nullable\n   public String getAccount() {\n      return this.account;\n   }\n\n   /**\n    * @return the account type of the user\n    */\n   @Nullable\n   public Account.Type getAccountType() {\n      return this.accountType;\n   }\n\n   /**\n    * @return the domain name of the user\n    */\n   @Nullable\n   public String getDomain() {\n      return this.domain;\n   }\n\n   /**\n    * @return the domain ID of the user\n    */\n   @Nullable\n   public String getDomainId() {\n      return this.domainId;\n   }\n\n   /**\n    * @return the timezone user was created in\n    */\n   @Nullable\n   public String getTimeZone() {\n      return this.timeZone;\n   }\n\n   /**\n    * @return the api key of the user\n    */\n   @Nullable\n   public String getApiKey() {\n      return this.apiKey;\n   }\n\n   /**\n    * @return the secret key of the user\n    */\n   @Nullable\n   public String getSecretKey() {\n      return this.secretKey;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, name, firstName, lastName, email, created, state, account, accountType, domain, domainId, timeZone, apiKey, secretKey);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      User that = User.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n            && Objects.equal(this.name, that.name)\n            && Objects.equal(this.firstName, that.firstName)\n            && Objects.equal(this.lastName, that.lastName)\n            && Objects.equal(this.email, that.email)\n            && Objects.equal(this.created, that.created)\n            && Objects.equal(this.state, that.state)\n            && Objects.equal(this.account, that.account)\n            && Objects.equal(this.accountType, that.accountType)\n            && Objects.equal(this.domain, that.domain)\n            && Objects.equal(this.domainId, that.domainId)\n            && Objects.equal(this.timeZone, that.timeZone)\n            && Objects.equal(this.apiKey, that.apiKey)\n            && Objects.equal(this.secretKey, that.secretKey);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"name\", name).add(\"firstName\", firstName).add(\"lastName\", lastName).add(\"email\", email)\n            .add(\"created\", created).add(\"state\", state).add(\"account\", account).add(\"accountType\", accountType).add(\"domain\", domain)\n            .add(\"domainId\", domainId).add(\"timeZone\", timeZone).add(\"apiKey\", apiKey).add(\"secretKey\", secretKey);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/VMGroup.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Class VMGroup\n */\npublic class VMGroup {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromVMGroup(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String id;\n      protected String account;\n      protected Date created;\n      protected String domain;\n      protected String domainId;\n      protected String name;\n\n      /**\n       * @see VMGroup#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see VMGroup#getAccount()\n       */\n      public T account(String account) {\n         this.account = account;\n         return self();\n      }\n\n      /**\n       * @see VMGroup#getCreated()\n       */\n      public T created(Date created) {\n         this.created = created;\n         return self();\n      }\n\n      /**\n       * @see VMGroup#getDomain()\n       */\n      public T domain(String domain) {\n         this.domain = domain;\n         return self();\n      }\n\n      /**\n       * @see VMGroup#getDomainId()\n       */\n      public T domainId(String domainId) {\n         this.domainId = domainId;\n         return self();\n      }\n\n      /**\n       * @see VMGroup#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      public VMGroup build() {\n         return new VMGroup(id, account, created, domain, domainId, name);\n      }\n\n      public T fromVMGroup(VMGroup in) {\n         return this\n               .id(in.getId())\n               .account(in.getAccount())\n               .created(in.getCreated())\n               .domain(in.getDomain())\n               .domainId(in.getDomainId())\n               .name(in.getName());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final String account;\n   private final Date created;\n   private final String domain;\n   private final String domainId;\n   private final String name;\n\n   @ConstructorProperties({\n         \"id\", \"account\", \"created\", \"domain\", \"domainid\", \"name\"\n   })\n   protected VMGroup(String id, @Nullable String account, @Nullable Date created, @Nullable String domain,\n                     @Nullable String domainId, @Nullable String name) {\n      this.id = checkNotNull(id, \"id\");\n      this.account = account;\n      this.created = created;\n      this.domain = domain;\n      this.domainId = domainId;\n      this.name = name;\n   }\n\n   /**\n    * @return the VMGroup's ID\n    */\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * @return the account that owns the VMGroup\n    */\n   @Nullable\n   public String getAccount() {\n      return this.account;\n   }\n\n   /**\n    * @return the VMGroup's creation timestamp\n    */\n   @Nullable\n   public Date getCreated() {\n      return this.created;\n   }\n\n   /**\n    * @return the domain that contains the VMGroup\n    */\n   @Nullable\n   public String getDomain() {\n      return this.domain;\n   }\n\n   /**\n    * @return the ID of the domain that contains the VMGroup\n    */\n   @Nullable\n   public String getDomainId() {\n      return this.domainId;\n   }\n\n   /**\n    * @return the name of the VMGroup\n    */\n   public String getName() {\n      return this.name;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, account, created, domain, domainId, name);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      VMGroup that = VMGroup.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n            && Objects.equal(this.account, that.account)\n            && Objects.equal(this.created, that.created)\n            && Objects.equal(this.domain, that.domain)\n            && Objects.equal(this.domainId, that.domainId)\n            && Objects.equal(this.name, that.name);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"account\", account).add(\"created\", created).add(\"domain\", domain).add(\"domainId\", domainId).add(\"name\", name);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/VirtualMachine.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.CaseFormat;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.base.Preconditions;\nimport com.google.common.base.Strings;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Class VirtualMachine\n */\npublic class VirtualMachine {\n\n   /**\n    */\n   public static enum State {\n      STARTING, RUNNING, STOPPING, STOPPED, DESTROYED, EXPUNGING, MIGRATING, ERROR, UNKNOWN, SHUTDOWNED, UNRECOGNIZED;\n\n      @Override\n      public String toString() {\n         return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name());\n      }\n\n      public static State fromValue(String state) {\n         try {\n            return valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, checkNotNull(state, \"state\")));\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n\n   }\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromVirtualMachine(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String id;\n      protected String account;\n      protected long cpuCount;\n      protected long cpuSpeed;\n      protected String cpuUsed;\n      protected String displayName;\n      protected Date created;\n      protected String domain;\n      protected String domainId;\n      protected boolean usesVirtualNetwork;\n      protected String group;\n      protected String groupId;\n      protected String guestOSId;\n      protected boolean HAEnabled;\n      protected String hostId;\n      protected String hostname;\n      protected String IPAddress;\n      protected String ISODisplayText;\n      protected String ISOId;\n      protected String ISOName;\n      protected String jobId;\n      protected Integer jobStatus;\n      protected long memory;\n      protected String name;\n      protected Long networkKbsRead;\n      protected Long networkKbsWrite;\n      protected String password;\n      protected boolean passwordEnabled;\n      protected String publicIP;\n      protected String publicIPId;\n      protected String rootDeviceId;\n      protected String rootDeviceType;\n      protected String serviceOfferingId;\n      protected String serviceOfferingName;\n      protected VirtualMachine.State state;\n      protected String templateDisplayText;\n      protected String templateId;\n      protected String templateName;\n      protected String zoneId;\n      protected String zoneName;\n      protected Set<NIC> nics = ImmutableSet.of();\n      protected String hypervisor;\n      protected Set<SecurityGroup> securityGroups = ImmutableSet.of();\n      protected Set<Tag> tags = ImmutableSet.of();\n\n      /**\n       * @see VirtualMachine#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see VirtualMachine#getAccount()\n       */\n      public T account(String account) {\n         this.account = account;\n         return self();\n      }\n\n      /**\n       * @see VirtualMachine#getCpuCount()\n       */\n      public T cpuCount(long cpuCount) {\n         this.cpuCount = cpuCount;\n         return self();\n      }\n\n      /**\n       * @see VirtualMachine#getCpuSpeed()\n       */\n      public T cpuSpeed(long cpuSpeed) {\n         this.cpuSpeed = cpuSpeed;\n         return self();\n      }\n\n      /**\n       * @see VirtualMachine#getCpuUsed()\n       */\n      public T cpuUsed(String cpuUsed) {\n         this.cpuUsed = cpuUsed;\n         return self();\n      }\n\n      /**\n       * @see VirtualMachine#getDisplayName()\n       */\n      public T displayName(String displayName) {\n         this.displayName = displayName;\n         return self();\n      }\n\n      /**\n       * @see VirtualMachine#getCreated()\n       */\n      public T created(Date created) {\n         this.created = created;\n         return self();\n      }\n\n      /**\n       * @see VirtualMachine#getDomain()\n       */\n      public T domain(String domain) {\n         this.domain = domain;\n         return self();\n      }\n\n      /**\n       * @see VirtualMachine#getDomainId()\n       */\n      public T domainId(String domainId) {\n         this.domainId = domainId;\n         return self();\n      }\n\n      /**\n       * @see VirtualMachine#usesVirtualNetwork()\n       */\n      public T usesVirtualNetwork(boolean usesVirtualNetwork) {\n         this.usesVirtualNetwork = usesVirtualNetwork;\n         return self();\n      }\n\n      /**\n       * @see VirtualMachine#getGroup()\n       */\n      public T group(String group) {\n         this.group = group;\n         return self();\n      }\n\n      /**\n       * @see VirtualMachine#getGroupId()\n       */\n      public T groupId(String groupId) {\n         this.groupId = groupId;\n         return self();\n      }\n\n      /**\n       * @see VirtualMachine#getGuestOSId()\n       */\n      public T guestOSId(String guestOSId) {\n         this.guestOSId = guestOSId;\n         return self();\n      }\n\n      /**\n       * @see VirtualMachine#isHAEnabled()\n       */\n      public T isHAEnabled(boolean HAEnabled) {\n         this.HAEnabled = HAEnabled;\n         return self();\n      }\n\n      /**\n       * @see VirtualMachine#getHostId()\n       */\n      public T hostId(String hostId) {\n         this.hostId = hostId;\n         return self();\n      }\n\n      /**\n       * @see VirtualMachine#getHostname()\n       */\n      public T hostname(String hostname) {\n         this.hostname = hostname;\n         return self();\n      }\n\n      /**\n       * @see VirtualMachine#getIPAddress()\n       */\n      public T IPAddress(String IPAddress) {\n         this.IPAddress = IPAddress;\n         return self();\n      }\n\n      /**\n       * @see VirtualMachine#getISODisplayText()\n       */\n      public T ISODisplayText(String ISODisplayText) {\n         this.ISODisplayText = ISODisplayText;\n         return self();\n      }\n\n      /**\n       * @see VirtualMachine#getISOId()\n       */\n      public T ISOId(String ISOId) {\n         this.ISOId = ISOId;\n         return self();\n      }\n\n      /**\n       * @see VirtualMachine#getISOName()\n       */\n      public T ISOName(String ISOName) {\n         this.ISOName = ISOName;\n         return self();\n      }\n\n      /**\n       * @see VirtualMachine#getJobId()\n       */\n      public T jobId(String jobId) {\n         this.jobId = jobId;\n         return self();\n      }\n\n      /**\n       * @see VirtualMachine#getJobStatus()\n       */\n      public T jobStatus(Integer jobStatus) {\n         this.jobStatus = jobStatus;\n         return self();\n      }\n\n      /**\n       * @see VirtualMachine#getMemory()\n       */\n      public T memory(long memory) {\n         this.memory = memory;\n         return self();\n      }\n\n      /**\n       * @see VirtualMachine#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /**\n       * @see VirtualMachine#getNetworkKbsRead()\n       */\n      public T networkKbsRead(Long networkKbsRead) {\n         this.networkKbsRead = networkKbsRead;\n         return self();\n      }\n\n      /**\n       * @see VirtualMachine#getNetworkKbsWrite()\n       */\n      public T networkKbsWrite(Long networkKbsWrite) {\n         this.networkKbsWrite = networkKbsWrite;\n         return self();\n      }\n\n      /**\n       * @see VirtualMachine#getPassword()\n       */\n      public T password(String password) {\n         this.password = password;\n         return self();\n      }\n\n      /**\n       * @see VirtualMachine#isPasswordEnabled()\n       */\n      public T passwordEnabled(boolean passwordEnabled) {\n         this.passwordEnabled = passwordEnabled;\n         return self();\n      }\n\n      /**\n       * @see VirtualMachine#getPublicIP()\n       */\n      public T publicIP(String publicIP) {\n         this.publicIP = publicIP;\n         return self();\n      }\n\n      /**\n       * @see VirtualMachine#getPublicIPId()\n       */\n      public T publicIPId(String publicIPId) {\n         this.publicIPId = publicIPId;\n         return self();\n      }\n\n      /**\n       * @see VirtualMachine#getRootDeviceId()\n       */\n      public T rootDeviceId(String rootDeviceId) {\n         this.rootDeviceId = rootDeviceId;\n         return self();\n      }\n\n      /**\n       * @see VirtualMachine#getRootDeviceType()\n       */\n      public T rootDeviceType(String rootDeviceType) {\n         this.rootDeviceType = rootDeviceType;\n         return self();\n      }\n\n      /**\n       * @see VirtualMachine#getServiceOfferingId()\n       */\n      public T serviceOfferingId(String serviceOfferingId) {\n         this.serviceOfferingId = serviceOfferingId;\n         return self();\n      }\n\n      /**\n       * @see VirtualMachine#getServiceOfferingName()\n       */\n      public T serviceOfferingName(String serviceOfferingName) {\n         this.serviceOfferingName = serviceOfferingName;\n         return self();\n      }\n\n      /**\n       * @see VirtualMachine#getState()\n       */\n      public T state(VirtualMachine.State state) {\n         this.state = state;\n         return self();\n      }\n\n      /**\n       * @see VirtualMachine#getTemplateDisplayText()\n       */\n      public T templateDisplayText(String templateDisplayText) {\n         this.templateDisplayText = templateDisplayText;\n         return self();\n      }\n\n      /**\n       * @see VirtualMachine#getTemplateId()\n       */\n      public T templateId(String templateId) {\n         this.templateId = templateId;\n         return self();\n      }\n\n      /**\n       * @see VirtualMachine#getTemplateName()\n       */\n      public T templateName(String templateName) {\n         this.templateName = templateName;\n         return self();\n      }\n\n      /**\n       * @see VirtualMachine#getZoneId()\n       */\n      public T zoneId(String zoneId) {\n         this.zoneId = zoneId;\n         return self();\n      }\n\n      /**\n       * @see VirtualMachine#getZoneName()\n       */\n      public T zoneName(String zoneName) {\n         this.zoneName = zoneName;\n         return self();\n      }\n\n      /**\n       * @see VirtualMachine#getNICs()\n       */\n      public T nics(Set<NIC> nics) {\n         this.nics = ImmutableSet.copyOf(checkNotNull(nics, \"nics\"));\n         return self();\n      }\n\n      public T nics(NIC... in) {\n         return nics(ImmutableSet.copyOf(in));\n      }\n\n      /**\n       * @see VirtualMachine#getHypervisor()\n       */\n      public T hypervisor(String hypervisor) {\n         this.hypervisor = hypervisor;\n         return self();\n      }\n\n      /**\n       * @see VirtualMachine#getSecurityGroups()\n       */\n      public T securityGroups(Set<SecurityGroup> securityGroups) {\n         this.securityGroups = ImmutableSet.copyOf(checkNotNull(securityGroups, \"securityGroups\"));\n         return self();\n      }\n\n      public T securityGroups(SecurityGroup... in) {\n         return securityGroups(ImmutableSet.copyOf(in));\n      }\n\n      /**\n       * @see VirtualMachine#getTags()\n       */\n      public T tags(Set<Tag> tags) {\n         this.tags = ImmutableSet.copyOf(checkNotNull(tags, \"tags\"));\n         return self();\n      }\n\n      public T tags(Tag... in) {\n         return tags(ImmutableSet.copyOf(in));\n      }\n\n      public VirtualMachine build() {\n         return new VirtualMachine(id, account, cpuCount, cpuSpeed, cpuUsed, displayName, created, domain, domainId,\n               usesVirtualNetwork, group, groupId, guestOSId, HAEnabled, hostId, hostname, IPAddress, ISODisplayText, ISOId,\n               ISOName, jobId, jobStatus, memory, name, networkKbsRead, networkKbsWrite, password, passwordEnabled, publicIP,\n               publicIPId, rootDeviceId, rootDeviceType, serviceOfferingId, serviceOfferingName, state, templateDisplayText,\n               templateId, templateName, zoneId, zoneName, nics, hypervisor, securityGroups, tags);\n      }\n\n      public T fromVirtualMachine(VirtualMachine in) {\n         return this\n               .id(in.getId())\n               .account(in.getAccount())\n               .cpuCount(in.getCpuCount())\n               .cpuSpeed(in.getCpuSpeed())\n               .cpuUsed(in.getCpuUsedAsString())\n               .displayName(in.getDisplayName())\n               .created(in.getCreated())\n               .domain(in.getDomain())\n               .domainId(in.getDomainId())\n               .usesVirtualNetwork(in.usesVirtualNetwork())\n               .group(in.getGroup())\n               .groupId(in.getGroupId())\n               .guestOSId(in.getGuestOSId())\n               .isHAEnabled(in.isHAEnabled())\n               .hostId(in.getHostId())\n               .hostname(in.getHostname())\n               .IPAddress(in.getIPAddress())\n               .ISODisplayText(in.getISODisplayText())\n               .ISOId(in.getISOId())\n               .ISOName(in.getISOName())\n               .jobId(in.getJobId())\n               .jobStatus(in.getJobStatus())\n               .memory(in.getMemory())\n               .name(in.getName())\n               .networkKbsRead(in.getNetworkKbsRead())\n               .networkKbsWrite(in.getNetworkKbsWrite())\n               .password(in.getPassword())\n               .passwordEnabled(in.isPasswordEnabled())\n               .publicIP(in.getPublicIP())\n               .publicIPId(in.getPublicIPId())\n               .rootDeviceId(in.getRootDeviceId())\n               .rootDeviceType(in.getRootDeviceType())\n               .serviceOfferingId(in.getServiceOfferingId())\n               .serviceOfferingName(in.getServiceOfferingName())\n               .state(in.getState())\n               .templateDisplayText(in.getTemplateDisplayText())\n               .templateId(in.getTemplateId())\n               .templateName(in.getTemplateName())\n               .zoneId(in.getZoneId())\n               .zoneName(in.getZoneName())\n               .nics(in.getNICs())\n               .hypervisor(in.getHypervisor())\n               .securityGroups(in.getSecurityGroups())\n               .tags(in.getTags());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final String account;\n   private final long cpuCount;\n   private final long cpuSpeed;\n   private final String cpuUsed;\n   private final String displayName;\n   private final Date created;\n   private final String domain;\n   private final String domainId;\n   private final boolean usesVirtualNetwork;\n   private final String group;\n   private final String groupId;\n   private final String guestOSId;\n   private final boolean HAEnabled;\n   private final String hostId;\n   private final String hostname;\n   private final String IPAddress;\n   private final String ISODisplayText;\n   private final String ISOId;\n   private final String ISOName;\n   private final String jobId;\n   private final Integer jobStatus;\n   private final long memory;\n   private final String name;\n   private final Long networkKbsRead;\n   private final Long networkKbsWrite;\n   private final String password;\n   private final boolean passwordEnabled;\n   private final String publicIP;\n   private final String publicIPId;\n   private final String rootDeviceId;\n   private final String rootDeviceType;\n   private final String serviceOfferingId;\n   private final String serviceOfferingName;\n   private final VirtualMachine.State state;\n   private final String templateDisplayText;\n   private final String templateId;\n   private final String templateName;\n   private final String zoneId;\n   private final String zoneName;\n   private final Set<NIC> nics;\n   private final String hypervisor;\n   private final Set<SecurityGroup> securityGroups;\n   private final Set<Tag> tags;\n\n   @ConstructorProperties({\n         \"id\", \"account\", \"cpunumber\", \"cpuspeed\", \"cpuused\", \"displayname\", \"created\", \"domain\", \"domainid\", \"forvirtualnetwork\", \"group\", \"groupid\", \"guestosid\", \"haenable\", \"hostid\", \"hostname\", \"ipaddress\", \"isodisplaytext\", \"isoid\", \"isoname\", \"jobid\", \"jobstatus\", \"memory\", \"name\", \"networkkbsread\", \"networkkbswrite\", \"password\", \"passwordenabled\", \"publicip\", \"publicipid\", \"rootdeviceid\", \"rootdevicetype\", \"serviceofferingid\", \"serviceofferingname\", \"state\", \"templatedisplaytext\", \"templateid\", \"templatename\", \"zoneid\", \"zonename\", \"nic\", \"hypervisor\", \"securitygroup\", \"tags\"\n   })\n   protected VirtualMachine(String id, @Nullable String account, long cpuCount, long cpuSpeed, @Nullable String cpuUsed,\n                            @Nullable String displayName, @Nullable Date created, @Nullable String domain, @Nullable String domainId,\n                            boolean usesVirtualNetwork, @Nullable String group, @Nullable String groupId, @Nullable String guestOSId,\n                            boolean HAEnabled, @Nullable String hostId, @Nullable String hostname, String IPAddress, String ISODisplayText,\n                            @Nullable String ISOId, @Nullable String ISOName, @Nullable String jobId, @Nullable Integer jobStatus,\n                            long memory, @Nullable String name, @Nullable Long networkKbsRead, @Nullable Long networkKbsWrite, @Nullable String password,\n                            boolean passwordEnabled, @Nullable String publicIP, @Nullable String publicIPId, @Nullable String rootDeviceId,\n                            @Nullable String rootDeviceType, @Nullable String serviceOfferingId, @Nullable String serviceOfferingName,\n                            @Nullable VirtualMachine.State state, @Nullable String templateDisplayText, @Nullable String templateId,\n                            @Nullable String templateName, @Nullable String zoneId, @Nullable String zoneName, @Nullable Set<NIC> nics,\n                            @Nullable String hypervisor, @Nullable Set<SecurityGroup> securityGroups, @Nullable Set<Tag> tags) {\n      Preconditions.checkArgument(Strings.isNullOrEmpty(cpuUsed) || cpuUsed.matches(\"^[0-9\\\\.|,\\\\-]+%$\"), \"cpuUsed value should be a decimal number followed by %\");\n      this.id = checkNotNull(id, \"id\");\n      this.account = account;\n      this.cpuCount = cpuCount;\n      this.cpuSpeed = cpuSpeed;\n      this.cpuUsed = cpuUsed;\n      this.displayName = displayName;\n      this.created = created;\n      this.domain = domain;\n      this.domainId = domainId;\n      this.usesVirtualNetwork = usesVirtualNetwork;\n      this.group = group;\n      this.groupId = groupId;\n      this.guestOSId = guestOSId;\n      this.HAEnabled = HAEnabled;\n      this.hostId = hostId;\n      this.hostname = hostname;\n      this.IPAddress = IPAddress;\n      this.ISODisplayText = ISODisplayText;\n      this.ISOId = ISOId;\n      this.ISOName = ISOName;\n      this.jobId = jobId;\n      this.jobStatus = jobStatus;\n      this.memory = memory;\n      this.name = name;\n      this.networkKbsRead = networkKbsRead;\n      this.networkKbsWrite = networkKbsWrite;\n      this.password = password;\n      this.passwordEnabled = passwordEnabled;\n      this.publicIP = publicIP;\n      this.publicIPId = publicIPId;\n      this.rootDeviceId = rootDeviceId;\n      this.rootDeviceType = rootDeviceType;\n      this.serviceOfferingId = serviceOfferingId;\n      this.serviceOfferingName = serviceOfferingName;\n      this.state = state;\n      this.templateDisplayText = templateDisplayText;\n      this.templateId = templateId;\n      this.templateName = templateName;\n      this.zoneId = zoneId;\n      this.zoneName = zoneName;\n      this.nics = nics == null ? ImmutableSet.<NIC>of() : ImmutableSet.copyOf(nics);\n      this.hypervisor = hypervisor;\n      this.securityGroups = securityGroups == null ? ImmutableSet.<SecurityGroup>of() : ImmutableSet.copyOf(securityGroups);\n      this.tags = tags != null ? ImmutableSet.copyOf(tags) : ImmutableSet.<Tag> of();\n   }\n\n   /**\n    * @return the ID of the virtual machine\n    */\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * @return the account associated with the virtual machine\n    */\n   @Nullable\n   public String getAccount() {\n      return this.account;\n   }\n\n   /**\n    * @return the number of cpu this virtual machine is running with\n    */\n   public long getCpuCount() {\n      return this.cpuCount;\n   }\n\n   /**\n    * @return the speed of each cpu\n    */\n   public long getCpuSpeed() {\n      return this.cpuSpeed;\n   }\n\n   /**\n    * @return the amount of the vm's CPU currently used\n    */\n   public float getCpuUsed() {\n      return cpuUsed != null ? Float.parseFloat(cpuUsed.substring(0, cpuUsed.length() - 1).replace(',', '.')) : 0.0f;\n   }\n\n   private String getCpuUsedAsString() {\n      return cpuUsed;\n   }\n\n   /**\n    * @return user generated name. The name of the virtual machine is returned\n    *         if no displayname exists.\n    */\n   @Nullable\n   public String getDisplayName() {\n      return this.displayName;\n   }\n\n   /**\n    * @return the date when this virtual machine was created\n    */\n   @Nullable\n   public Date getCreated() {\n      return this.created;\n   }\n\n   /**\n    * @return the name of the domain in which the virtual machine exists\n    */\n   @Nullable\n   public String getDomain() {\n      return this.domain;\n   }\n\n   /**\n    * @return the ID of the domain in which the virtual machine exists\n    */\n   @Nullable\n   public String getDomainId() {\n      return this.domainId;\n   }\n\n   /**\n    * @return the virtual network for the service offering\n    */\n   public boolean usesVirtualNetwork() {\n      return this.usesVirtualNetwork;\n   }\n\n   /**\n    * @return the group name of the virtual machine\n    */\n   @Nullable\n   public String getGroup() {\n      return this.group;\n   }\n\n   /**\n    * @return the group ID of the virtual machine\n    */\n   @Nullable\n   public String getGroupId() {\n      return this.groupId;\n   }\n\n   /**\n    * @return Os type ID of the virtual machine\n    */\n   @Nullable\n   public String getGuestOSId() {\n      return this.guestOSId;\n   }\n\n   /**\n    * @return true if high-availability is enabled, false otherwise\n    */\n   public boolean isHAEnabled() {\n      return this.HAEnabled;\n   }\n\n   /**\n    * @return the ID of the host for the virtual machine\n    */\n   @Nullable\n   public String getHostId() {\n      return this.hostId;\n   }\n\n   /**\n    * @return the name of the host for the virtual machine\n    */\n   @Nullable\n   public String getHostname() {\n      return this.hostname;\n   }\n\n   /**\n    * @return the ip address of the virtual machine\n    */\n   @Nullable\n   public String getIPAddress() {\n      return this.IPAddress;\n   }\n\n   /**\n    * @return an alternate display text of the ISO attached to the virtual\n    *         machine\n    */\n   @Nullable\n   public String getISODisplayText() {\n      return this.ISODisplayText;\n   }\n\n   /**\n    * @return the ID of the ISO attached to the virtual machine\n    */\n   @Nullable\n   public String getISOId() {\n      return this.ISOId;\n   }\n\n   /**\n    * @return the name of the ISO attached to the virtual machine\n    */\n   @Nullable\n   public String getISOName() {\n      return this.ISOName;\n   }\n\n   /**\n    * @return shows the current pending asynchronous job ID. This tag is not\n    *         returned if no current pending jobs are acting on the virtual\n    *         machine\n    */\n   @Nullable\n   public String getJobId() {\n      return this.jobId;\n   }\n\n   /**\n    * @return shows the current pending asynchronous job status\n    */\n   @Nullable\n   public Integer getJobStatus() {\n      return this.jobStatus;\n   }\n\n   /**\n    * @return the memory allocated for the virtual machine\n    */\n   public long getMemory() {\n      return this.memory;\n   }\n\n   /**\n    * @return the name of the virtual machine\n    */\n   @Nullable\n   public String getName() {\n      return this.name;\n   }\n\n   /**\n    * @return the incoming network traffic on the vm\n    */\n   @Nullable\n   public Long getNetworkKbsRead() {\n      return this.networkKbsRead;\n   }\n\n   /**\n    * @return the outgoing network traffic on the host\n    */\n   @Nullable\n   public Long getNetworkKbsWrite() {\n      return this.networkKbsWrite;\n   }\n\n   /**\n    * @return the password (if exists) of the virtual machine\n    */\n   @Nullable\n   public String getPassword() {\n      return this.password;\n   }\n\n   /**\n    * @return true if the password rest feature is enabled, false otherwise\n    */\n   public boolean isPasswordEnabled() {\n      return this.passwordEnabled;\n   }\n\n   /**\n    * @return public IP of this virtual machine\n    */\n   @Nullable\n   public String getPublicIP() {\n      return this.publicIP;\n   }\n\n   /**\n    * @return ID of the public IP of this virtual machine\n    */\n   @Nullable\n   public String getPublicIPId() {\n      return this.publicIPId;\n   }\n\n   /**\n    * @return device ID of the root volume\n    */\n   @Nullable\n   public String getRootDeviceId() {\n      return this.rootDeviceId;\n   }\n\n   /**\n    * @return device type of the root volume\n    */\n   @Nullable\n   public String getRootDeviceType() {\n      return this.rootDeviceType;\n   }\n\n   /**\n    * @return the ID of the service offering of the virtual machine\n    */\n   @Nullable\n   public String getServiceOfferingId() {\n      return this.serviceOfferingId;\n   }\n\n   /**\n    * @return the name of the service offering of the virtual machine\n    */\n   @Nullable\n   public String getServiceOfferingName() {\n      return this.serviceOfferingName;\n   }\n\n   /**\n    * @return the state of the virtual machine\n    */\n   @Nullable\n   public VirtualMachine.State getState() {\n      return this.state;\n   }\n\n   /**\n    * @return an alternate display text of the template for the virtual machine\n    */\n   @Nullable\n   public String getTemplateDisplayText() {\n      return this.templateDisplayText;\n   }\n\n   /**\n    * @return the ID of the template for the virtual machine. A -1 is returned\n    *         if the virtual machine was created from an ISO file.\n    */\n   @Nullable\n   public String getTemplateId() {\n      return this.templateId;\n   }\n\n   /**\n    * @return the name of the template for the virtual machine\n    */\n   @Nullable\n   public String getTemplateName() {\n      return this.templateName;\n   }\n\n   /**\n    * @return the ID of the availability zone for the virtual machine\n    */\n   @Nullable\n   public String getZoneId() {\n      return this.zoneId;\n   }\n\n   /**\n    * @return the name of the availability zone for the virtual machine\n    */\n   @Nullable\n   public String getZoneName() {\n      return this.zoneName;\n   }\n\n   public Set<NIC> getNICs() {\n      return this.nics;\n   }\n\n   /**\n    * @return type of the hypervisor\n    */\n   @Nullable\n   public String getHypervisor() {\n      return this.hypervisor;\n   }\n\n   /**\n    * @return list of security groups associated with the virtual machine\n    */\n   public Set<SecurityGroup> getSecurityGroups() {\n      return this.securityGroups;\n   }\n\n   /**\n    * @return the tags for the virtual machine\n    */\n   public Set<Tag> getTags() {\n      return this.tags;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, account, cpuCount, cpuSpeed, cpuUsed, displayName, created, domain, domainId, usesVirtualNetwork, group, groupId, guestOSId, HAEnabled, hostId, hostname, IPAddress, ISODisplayText, ISOId, ISOName, jobId, jobStatus, memory, name, networkKbsRead, networkKbsWrite, password, passwordEnabled, publicIP, publicIPId, rootDeviceId, rootDeviceType, serviceOfferingId, serviceOfferingName, state, templateDisplayText, templateId, templateName, zoneId, zoneName, nics, hypervisor, securityGroups, tags);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      VirtualMachine that = VirtualMachine.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n            && Objects.equal(this.account, that.account)\n            && Objects.equal(this.cpuCount, that.cpuCount)\n            && Objects.equal(this.cpuSpeed, that.cpuSpeed)\n            && Objects.equal(this.cpuUsed, that.cpuUsed)\n            && Objects.equal(this.displayName, that.displayName)\n            && Objects.equal(this.created, that.created)\n            && Objects.equal(this.domain, that.domain)\n            && Objects.equal(this.domainId, that.domainId)\n            && Objects.equal(this.usesVirtualNetwork, that.usesVirtualNetwork)\n            && Objects.equal(this.group, that.group)\n            && Objects.equal(this.groupId, that.groupId)\n            && Objects.equal(this.guestOSId, that.guestOSId)\n            && Objects.equal(this.HAEnabled, that.HAEnabled)\n            && Objects.equal(this.hostId, that.hostId)\n            && Objects.equal(this.hostname, that.hostname)\n            && Objects.equal(this.IPAddress, that.IPAddress)\n            && Objects.equal(this.ISODisplayText, that.ISODisplayText)\n            && Objects.equal(this.ISOId, that.ISOId)\n            && Objects.equal(this.ISOName, that.ISOName)\n            && Objects.equal(this.jobId, that.jobId)\n            && Objects.equal(this.jobStatus, that.jobStatus)\n            && Objects.equal(this.memory, that.memory)\n            && Objects.equal(this.name, that.name)\n            && Objects.equal(this.networkKbsRead, that.networkKbsRead)\n            && Objects.equal(this.networkKbsWrite, that.networkKbsWrite)\n            && Objects.equal(this.password, that.password)\n            && Objects.equal(this.passwordEnabled, that.passwordEnabled)\n            && Objects.equal(this.publicIP, that.publicIP)\n            && Objects.equal(this.publicIPId, that.publicIPId)\n            && Objects.equal(this.rootDeviceId, that.rootDeviceId)\n            && Objects.equal(this.rootDeviceType, that.rootDeviceType)\n            && Objects.equal(this.serviceOfferingId, that.serviceOfferingId)\n            && Objects.equal(this.serviceOfferingName, that.serviceOfferingName)\n            && Objects.equal(this.state, that.state)\n            && Objects.equal(this.templateDisplayText, that.templateDisplayText)\n            && Objects.equal(this.templateId, that.templateId)\n            && Objects.equal(this.templateName, that.templateName)\n            && Objects.equal(this.zoneId, that.zoneId)\n            && Objects.equal(this.zoneName, that.zoneName)\n            && Objects.equal(this.nics, that.nics)\n            && Objects.equal(this.hypervisor, that.hypervisor)\n            && Objects.equal(this.securityGroups, that.securityGroups)\n            && Objects.equal(this.tags, that.tags);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"account\", account).add(\"cpuCount\", cpuCount).add(\"cpuSpeed\", cpuSpeed).add(\"cpuUsed\", cpuUsed)\n            .add(\"displayName\", displayName).add(\"created\", created).add(\"domain\", domain).add(\"domainId\", domainId)\n            .add(\"usesVirtualNetwork\", usesVirtualNetwork).add(\"group\", group).add(\"groupId\", groupId).add(\"guestOSId\", guestOSId)\n            .add(\"HAEnabled\", HAEnabled).add(\"hostId\", hostId).add(\"hostname\", hostname).add(\"IPAddress\", IPAddress)\n            .add(\"ISODisplayText\", ISODisplayText).add(\"ISOId\", ISOId).add(\"ISOName\", ISOName).add(\"jobId\", jobId)\n            .add(\"jobStatus\", jobStatus).add(\"memory\", memory).add(\"name\", name).add(\"networkKbsRead\", networkKbsRead)\n            .add(\"networkKbsWrite\", networkKbsWrite).add(\"password\", password).add(\"passwordEnabled\", passwordEnabled)\n            .add(\"publicIP\", publicIP).add(\"publicIPId\", publicIPId).add(\"rootDeviceId\", rootDeviceId).add(\"rootDeviceType\", rootDeviceType)\n            .add(\"serviceOfferingId\", serviceOfferingId).add(\"serviceOfferingName\", serviceOfferingName).add(\"state\", state)\n            .add(\"templateDisplayText\", templateDisplayText).add(\"templateId\", templateId).add(\"templateName\", templateName)\n            .add(\"zoneId\", zoneId).add(\"zoneName\", zoneName).add(\"nics\", nics).add(\"hypervisor\", hypervisor).add(\"securityGroups\", securityGroups)\n            .add(\"tags\", tags);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/VlanIPRange.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Represents the data object used in CloudStack's \"Vlan\" API.\n */\npublic class VlanIPRange implements Comparable<VlanIPRange> {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromVlanIPRange(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String id;\n      protected String description;\n      protected boolean forVirtualNetwork;\n      protected String zoneId;\n      protected String vlan;\n      protected String account;\n      protected String domainId;\n      protected String domain;\n      protected String podId;\n      protected String podName;\n      protected String gateway;\n      protected String netmask;\n      protected String startIP;\n      protected String endIP;\n      protected String networkId;\n\n      /**\n       * @see VlanIPRange#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see VlanIPRange#getDescription()\n       */\n      public T description(String description) {\n         this.description = description;\n         return self();\n      }\n\n      /**\n       * @see VlanIPRange#isForVirtualNetwork()\n       */\n      public T forVirtualNetwork(boolean forVirtualNetwork) {\n         this.forVirtualNetwork = forVirtualNetwork;\n         return self();\n      }\n\n      /**\n       * @see VlanIPRange#getZoneId()\n       */\n      public T zoneId(String zoneId) {\n         this.zoneId = zoneId;\n         return self();\n      }\n\n      /**\n       * @see VlanIPRange#getVlan()\n       */\n      public T vlan(String vlan) {\n         this.vlan = vlan;\n         return self();\n      }\n\n      /**\n       * @see VlanIPRange#getAccount()\n       */\n      public T account(String account) {\n         this.account = account;\n         return self();\n      }\n\n      /**\n       * @see VlanIPRange#getDomainId()\n       */\n      public T domainId(String domainId) {\n         this.domainId = domainId;\n         return self();\n      }\n\n      /**\n       * @see VlanIPRange#getDomain()\n       */\n      public T domain(String domain) {\n         this.domain = domain;\n         return self();\n      }\n\n      /**\n       * @see VlanIPRange#getPodId()\n       */\n      public T podId(String podId) {\n         this.podId = podId;\n         return self();\n      }\n\n      /**\n       * @see VlanIPRange#getPodName()\n       */\n      public T podName(String podName) {\n         this.podName = podName;\n         return self();\n      }\n\n      /**\n       * @see VlanIPRange#getGateway()\n       */\n      public T gateway(String gateway) {\n         this.gateway = gateway;\n         return self();\n      }\n\n      /**\n       * @see VlanIPRange#getNetmask()\n       */\n      public T netmask(String netmask) {\n         this.netmask = netmask;\n         return self();\n      }\n\n      /**\n       * @see VlanIPRange#getStartIP()\n       */\n      public T startIP(String startIP) {\n         this.startIP = startIP;\n         return self();\n      }\n\n      /**\n       * @see VlanIPRange#getEndIP()\n       */\n      public T endIP(String endIP) {\n         this.endIP = endIP;\n         return self();\n      }\n\n      /**\n       * @see VlanIPRange#getNetworkId()\n       */\n      public T networkId(String networkId) {\n         this.networkId = networkId;\n         return self();\n      }\n\n      public VlanIPRange build() {\n         return new VlanIPRange(id, description, forVirtualNetwork, zoneId, vlan, account, domainId, domain, podId,\n               podName, gateway, netmask, startIP, endIP, networkId);\n      }\n\n      public T fromVlanIPRange(VlanIPRange in) {\n         return this\n               .id(in.getId())\n               .description(in.getDescription())\n               .forVirtualNetwork(in.isForVirtualNetwork())\n               .zoneId(in.getZoneId())\n               .vlan(in.getVlan())\n               .account(in.getAccount())\n               .domainId(in.getDomainId())\n               .domain(in.getDomain())\n               .podId(in.getPodId())\n               .podName(in.getPodName())\n               .gateway(in.getGateway())\n               .netmask(in.getNetmask())\n               .startIP(in.getStartIP())\n               .endIP(in.getEndIP())\n               .networkId(in.getNetworkId());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final String description;\n   private final boolean forVirtualNetwork;\n   private final String zoneId;\n   private final String vlan;\n   private final String account;\n   private final String domainId;\n   private final String domain;\n   private final String podId;\n   private final String podName;\n   private final String gateway;\n   private final String netmask;\n   private final String startIP;\n   private final String endIP;\n   private final String networkId;\n\n   @ConstructorProperties({\n         \"id\", \"description\", \"forvirtualnetwork\", \"zoneid\", \"vlan\", \"account\", \"domainid\", \"domain\", \"podid\", \"podname\",\n         \"gateway\", \"netmask\", \"startip\", \"endip\", \"networkid\"\n   })\n   protected VlanIPRange(String id, @Nullable String description, boolean forVirtualNetwork, @Nullable String zoneId,\n                         @Nullable String vlan, @Nullable String account, @Nullable String domainId, @Nullable String domain,\n                         @Nullable String podId, @Nullable String podName, @Nullable String gateway, @Nullable String netmask,\n                         @Nullable String startIP, @Nullable String endIP, @Nullable String networkId) {\n      this.id = checkNotNull(id, \"id\");\n      this.description = description;\n      this.forVirtualNetwork = forVirtualNetwork;\n      this.zoneId = zoneId;\n      this.vlan = vlan;\n      this.account = account;\n      this.domainId = domainId;\n      this.domain = domain;\n      this.podId = podId;\n      this.podName = podName;\n      this.gateway = gateway;\n      this.netmask = netmask;\n      this.startIP = startIP;\n      this.endIP = endIP;\n      this.networkId = networkId;\n   }\n\n   public String getId() {\n      return this.id;\n   }\n\n   @Nullable\n   public String getDescription() {\n      return this.description;\n   }\n\n   public boolean isForVirtualNetwork() {\n      return this.forVirtualNetwork;\n   }\n\n   @Nullable\n   public String getZoneId() {\n      return this.zoneId;\n   }\n\n   @Nullable\n   public String getVlan() {\n      return this.vlan;\n   }\n\n   @Nullable\n   public String getAccount() {\n      return this.account;\n   }\n\n   @Nullable\n   public String getDomainId() {\n      return this.domainId;\n   }\n\n   @Nullable\n   public String getDomain() {\n      return this.domain;\n   }\n\n   @Nullable\n   public String getPodId() {\n      return this.podId;\n   }\n\n   @Nullable\n   public String getPodName() {\n      return this.podName;\n   }\n\n   @Nullable\n   public String getGateway() {\n      return this.gateway;\n   }\n\n   @Nullable\n   public String getNetmask() {\n      return this.netmask;\n   }\n\n   @Nullable\n   public String getStartIP() {\n      return this.startIP;\n   }\n\n   @Nullable\n   public String getEndIP() {\n      return this.endIP;\n   }\n\n   @Nullable\n   public String getNetworkId() {\n      return this.networkId;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, description, forVirtualNetwork, zoneId, vlan, account, domainId, domain, podId, podName, gateway, netmask, startIP, endIP, networkId);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      VlanIPRange that = VlanIPRange.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n            && Objects.equal(this.description, that.description)\n            && Objects.equal(this.forVirtualNetwork, that.forVirtualNetwork)\n            && Objects.equal(this.zoneId, that.zoneId)\n            && Objects.equal(this.vlan, that.vlan)\n            && Objects.equal(this.account, that.account)\n            && Objects.equal(this.domainId, that.domainId)\n            && Objects.equal(this.domain, that.domain)\n            && Objects.equal(this.podId, that.podId)\n            && Objects.equal(this.podName, that.podName)\n            && Objects.equal(this.gateway, that.gateway)\n            && Objects.equal(this.netmask, that.netmask)\n            && Objects.equal(this.startIP, that.startIP)\n            && Objects.equal(this.endIP, that.endIP)\n            && Objects.equal(this.networkId, that.networkId);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"description\", description).add(\"forVirtualNetwork\", forVirtualNetwork).add(\"zoneId\", zoneId)\n            .add(\"vlan\", vlan).add(\"account\", account).add(\"domainId\", domainId).add(\"domain\", domain).add(\"podId\", podId)\n            .add(\"podName\", podName).add(\"gateway\", gateway).add(\"netmask\", netmask).add(\"startIP\", startIP).add(\"endIP\", endIP)\n            .add(\"networkId\", networkId);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int compareTo(VlanIPRange other) {\n      return this.id.compareTo(other.id);\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/Volume.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.CaseFormat;\nimport com.google.common.base.Function;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Maps;\n\npublic class Volume {\n\n   /**\n    */\n   public static enum State {\n\n      /**\n       * indicates that the volume record is created in the DB, but not on the backend\n       */\n      ALLOCATED,\n      /**\n       * the volume is being created on the backend\n       */\n      CREATING,\n      /**\n       * the volume is ready to be used\n       */\n      READY,\n      /**\n       * the volume is destroyed (either as a result of deleteVolume command for DataDisk or as a part of destroyVm)\n       */\n      DESTROYED,\n      /**\n       * the volume has failed somehow, e.g. during creation (in cloudstack development)\n       */\n      FAILED,\n\n      UNRECOGNIZED;\n\n      @Override\n      public String toString() {\n         return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name());\n      }\n\n      public static State fromValue(String state) {\n         try {\n            return valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, checkNotNull(state, \"state\")));\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n   }\n\n   /**\n    */\n   public static enum Type {\n      ROOT(0),\n      DATADISK(1),\n      UNRECOGNIZED(Integer.MAX_VALUE);\n\n      private int code;\n\n      private static final Map<Integer, Type> INDEX = Maps.uniqueIndex(ImmutableSet.copyOf(Type.values()),\n            new Function<Type, Integer>() {\n\n               @Override\n               public Integer apply(Type input) {\n                  return input.code;\n               }\n\n            });\n\n      Type(int code) {\n         this.code = code;\n      }\n\n      @Override\n      public String toString() {\n         return name().toLowerCase();\n      }\n\n      public static Type fromValue(String resourceType) {\n         Integer code = Integer.valueOf(checkNotNull(resourceType, \"resourcetype\"));\n         return INDEX.containsKey(code) ? INDEX.get(code) : UNRECOGNIZED;\n      }\n\n   }\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromVolume(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String id;\n      protected String account;\n      protected Date attached;\n      protected Date created;\n      protected boolean destroyed;\n      protected String deviceId;\n      protected String diskOfferingDisplayText;\n      protected String diskOfferingId;\n      protected String diskOfferingName;\n      protected String domain;\n      protected String domainId;\n      protected String hypervisor;\n      protected boolean isExtractable;\n      protected String jobId;\n      protected String jobStatus;\n      protected String name;\n      protected String serviceOfferingDisplayText;\n      protected String serviceOfferingId;\n      protected String serviceOfferingName;\n      protected long size;\n      protected String snapshotId;\n      protected Volume.State state;\n      protected String storage;\n      protected String storageType;\n      protected Volume.Type type;\n      protected String virtualMachineId;\n      protected String vmDisplayName;\n      protected String vmName;\n      protected VirtualMachine.State vmState;\n      protected String zoneId;\n      protected String zoneName;\n      protected Set<Tag> tags = ImmutableSet.of();\n\n      /**\n       * @see Volume#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see Volume#getAccount()\n       */\n      public T account(String account) {\n         this.account = account;\n         return self();\n      }\n\n      /**\n       * @see Volume#getAttached()\n       */\n      public T attached(Date attached) {\n         this.attached = attached;\n         return self();\n      }\n\n      /**\n       * @see Volume#getCreated()\n       */\n      public T created(Date created) {\n         this.created = created;\n         return self();\n      }\n\n      /**\n       * @see Volume#isDestroyed()\n       */\n      public T destroyed(boolean destroyed) {\n         this.destroyed = destroyed;\n         return self();\n      }\n\n      /**\n       * @see Volume#getDeviceId()\n       */\n      public T deviceId(String deviceId) {\n         this.deviceId = deviceId;\n         return self();\n      }\n\n      /**\n       * @see Volume#getDiskOfferingDisplayText()\n       */\n      public T diskOfferingDisplayText(String diskOfferingDisplayText) {\n         this.diskOfferingDisplayText = diskOfferingDisplayText;\n         return self();\n      }\n\n      /**\n       * @see Volume#getDiskOfferingId()\n       */\n      public T diskOfferingId(String diskOfferingId) {\n         this.diskOfferingId = diskOfferingId;\n         return self();\n      }\n\n      /**\n       * @see Volume#getDiskOfferingName()\n       */\n      public T diskOfferingName(String diskOfferingName) {\n         this.diskOfferingName = diskOfferingName;\n         return self();\n      }\n\n      /**\n       * @see Volume#getDomain()\n       */\n      public T domain(String domain) {\n         this.domain = domain;\n         return self();\n      }\n\n      /**\n       * @see Volume#getDomainId()\n       */\n      public T domainId(String domainId) {\n         this.domainId = domainId;\n         return self();\n      }\n\n      /**\n       * @see Volume#getHypervisor()\n       */\n      public T hypervisor(String hypervisor) {\n         this.hypervisor = hypervisor;\n         return self();\n      }\n\n      /**\n       * @see Volume#isExtractable()\n       */\n      public T isExtractable(boolean isExtractable) {\n         this.isExtractable = isExtractable;\n         return self();\n      }\n\n      /**\n       * @see Volume#getJobId()\n       */\n      public T jobId(String jobId) {\n         this.jobId = jobId;\n         return self();\n      }\n\n      /**\n       * @see Volume#getJobStatus()\n       */\n      public T jobStatus(String jobStatus) {\n         this.jobStatus = jobStatus;\n         return self();\n      }\n\n      /**\n       * @see Volume#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /**\n       * @see Volume#getServiceOfferingDisplayText()\n       */\n      public T serviceOfferingDisplayText(String serviceOfferingDisplayText) {\n         this.serviceOfferingDisplayText = serviceOfferingDisplayText;\n         return self();\n      }\n\n      /**\n       * @see Volume#getServiceOfferingId()\n       */\n      public T serviceOfferingId(String serviceOfferingId) {\n         this.serviceOfferingId = serviceOfferingId;\n         return self();\n      }\n\n      /**\n       * @see Volume#getServiceOfferingName()\n       */\n      public T serviceOfferingName(String serviceOfferingName) {\n         this.serviceOfferingName = serviceOfferingName;\n         return self();\n      }\n\n      /**\n       * @see Volume#getSize()\n       */\n      public T size(long size) {\n         this.size = size;\n         return self();\n      }\n\n      /**\n       * @see Volume#getSnapshotId()\n       */\n      public T snapshotId(String snapshotId) {\n         this.snapshotId = snapshotId;\n         return self();\n      }\n\n      /**\n       * @see Volume#getState()\n       */\n      public T state(Volume.State state) {\n         this.state = state;\n         return self();\n      }\n\n      /**\n       * @see Volume#getStorage()\n       */\n      public T storage(String storage) {\n         this.storage = storage;\n         return self();\n      }\n\n      /**\n       * @see Volume#getStorageType()\n       */\n      public T storageType(String storageType) {\n         this.storageType = storageType;\n         return self();\n      }\n\n      /**\n       * @see Volume#getType()\n       */\n      public T type(Volume.Type type) {\n         this.type = type;\n         return self();\n      }\n\n      /**\n       * @see Volume#getVirtualMachineId()\n       */\n      public T virtualMachineId(String virtualMachineId) {\n         this.virtualMachineId = virtualMachineId;\n         return self();\n      }\n\n      /**\n       * @see Volume#getVmDisplayName()\n       */\n      public T vmDisplayName(String vmDisplayName) {\n         this.vmDisplayName = vmDisplayName;\n         return self();\n      }\n\n      /**\n       * @see Volume#getVmName()\n       */\n      public T vmName(String vmName) {\n         this.vmName = vmName;\n         return self();\n      }\n\n      /**\n       * @see Volume#getVmState()\n       */\n      public T vmState(VirtualMachine.State vmState) {\n         this.vmState = vmState;\n         return self();\n      }\n\n      /**\n       * @see Volume#getZoneId()\n       */\n      public T zoneId(String zoneId) {\n         this.zoneId = zoneId;\n         return self();\n      }\n\n      /**\n       * @see Volume#getZoneName()\n       */\n      public T zoneName(String zoneName) {\n         this.zoneName = zoneName;\n         return self();\n      }\n\n      /**\n       * @see Volume#getTags()\n       */\n      public T tags(Set<Tag> tags) {\n         this.tags = ImmutableSet.copyOf(checkNotNull(tags, \"tags\"));\n         return self();\n      }\n\n      public T tags(Tag... in) {\n         return tags(ImmutableSet.copyOf(in));\n      }\n\n      public Volume build() {\n         return new Volume(id, account, attached, created, destroyed, deviceId, diskOfferingDisplayText, diskOfferingId, diskOfferingName, domain, domainId, hypervisor, isExtractable, jobId, jobStatus, name, serviceOfferingDisplayText, serviceOfferingId, serviceOfferingName, size, snapshotId, state, storage, storageType, type, virtualMachineId, vmDisplayName, vmName, vmState, zoneId, zoneName, tags);\n      }\n\n      public T fromVolume(Volume in) {\n         return this\n               .id(in.getId())\n               .account(in.getAccount())\n               .attached(in.getAttached())\n               .created(in.getCreated())\n               .destroyed(in.isDestroyed())\n               .deviceId(in.getDeviceId())\n               .diskOfferingDisplayText(in.getDiskOfferingDisplayText())\n               .diskOfferingId(in.getDiskOfferingId())\n               .diskOfferingName(in.getDiskOfferingName())\n               .domain(in.getDomain())\n               .domainId(in.getDomainId())\n               .hypervisor(in.getHypervisor())\n               .isExtractable(in.isExtractable())\n               .jobId(in.getJobId())\n               .jobStatus(in.getJobStatus())\n               .name(in.getName())\n               .serviceOfferingDisplayText(in.getServiceOfferingDisplayText())\n               .serviceOfferingId(in.getServiceOfferingId())\n               .serviceOfferingName(in.getServiceOfferingName())\n               .size(in.getSize())\n               .snapshotId(in.getSnapshotId())\n               .state(in.getState())\n               .storage(in.getStorage())\n               .storageType(in.getStorageType())\n               .type(in.getType())\n               .virtualMachineId(in.getVirtualMachineId())\n               .vmDisplayName(in.getVmDisplayName())\n               .vmName(in.getVmName())\n               .vmState(in.getVmState())\n               .zoneId(in.getZoneId())\n               .zoneName(in.getZoneName())\n               .tags(in.getTags());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final String account;\n   private final Date attached;\n   private final Date created;\n   private final boolean destroyed;\n   private final String deviceId;\n   private final String diskOfferingDisplayText;\n   private final String diskOfferingId;\n   private final String diskOfferingName;\n   private final String domain;\n   private final String domainId;\n   private final String hypervisor;\n   private final boolean isExtractable;\n   private final String jobId;\n   private final String jobStatus;\n   private final String name;\n   private final String serviceOfferingDisplayText;\n   private final String serviceOfferingId;\n   private final String serviceOfferingName;\n   private final long size;\n   private final String snapshotId;\n   private final Volume.State state;\n   private final String storage;\n   private final String storageType;\n   private final Volume.Type type;\n   private final String virtualMachineId;\n   private final String vmDisplayName;\n   private final String vmName;\n   private final VirtualMachine.State vmState;\n   private final String zoneId;\n   private final String zoneName;\n   private final Set<Tag> tags;\n\n   @ConstructorProperties({\n         \"id\", \"account\", \"attached\", \"created\", \"destroyed\", \"deviceid\", \"diskofferingdisplaytext\", \"diskofferingid\", \"diskofferingname\", \"domain\", \"domainid\", \"hypervisor\", \"isextractable\", \"jobid\", \"jobstatus\", \"name\", \"serviceofferingdisplaytext\", \"serviceofferingid\", \"serviceofferingname\", \"size\", \"snapshotid\", \"state\", \"storage\", \"storagetype\", \"type\", \"virtualmachineid\", \"vmdisplayname\", \"vmname\", \"vmstate\", \"zoneid\", \"zonename\", \"tags\"\n   })\n   protected Volume(String id, @Nullable String account, @Nullable Date attached, @Nullable Date created, boolean destroyed,\n                    @Nullable String deviceId, @Nullable String diskOfferingDisplayText, @Nullable String diskOfferingId,\n                    @Nullable String diskOfferingName, @Nullable String domain, @Nullable String domainId, @Nullable String hypervisor,\n                    boolean isExtractable, @Nullable String jobId, @Nullable String jobStatus, @Nullable String name,\n                    @Nullable String serviceOfferingDisplayText, @Nullable String serviceOfferingId, @Nullable String serviceOfferingName,\n                    long size, @Nullable String snapshotId, @Nullable Volume.State state, @Nullable String storage,\n                    @Nullable String storageType, @Nullable Volume.Type type, @Nullable String virtualMachineId,\n                    @Nullable String vmDisplayName, @Nullable String vmName, @Nullable VirtualMachine.State vmState,\n                    @Nullable String zoneId, @Nullable String zoneName, @Nullable Set<Tag> tags) {\n      this.id = checkNotNull(id, \"id\");\n      this.account = account;\n      this.attached = attached;\n      this.created = created;\n      this.destroyed = destroyed;\n      this.deviceId = deviceId;\n      this.diskOfferingDisplayText = diskOfferingDisplayText;\n      this.diskOfferingId = diskOfferingId;\n      this.diskOfferingName = diskOfferingName;\n      this.domain = domain;\n      this.domainId = domainId;\n      this.hypervisor = hypervisor;\n      this.isExtractable = isExtractable;\n      this.jobId = jobId;\n      this.jobStatus = jobStatus;\n      this.name = name;\n      this.serviceOfferingDisplayText = serviceOfferingDisplayText;\n      this.serviceOfferingId = serviceOfferingId;\n      this.serviceOfferingName = serviceOfferingName;\n      this.size = size;\n      this.snapshotId = snapshotId;\n      this.state = state;\n      this.storage = storage;\n      this.storageType = storageType;\n      this.type = type;\n      this.virtualMachineId = virtualMachineId;\n      this.vmDisplayName = vmDisplayName;\n      this.vmName = vmName;\n      this.vmState = vmState;\n      this.zoneId = zoneId;\n      this.zoneName = zoneName;\n      this.tags = tags != null ? ImmutableSet.copyOf(tags) : ImmutableSet.<Tag> of();\n   }\n\n   public String getId() {\n      return this.id;\n   }\n\n   @Nullable\n   public String getAccount() {\n      return this.account;\n   }\n\n   @Nullable\n   public Date getAttached() {\n      return this.attached;\n   }\n\n   @Nullable\n   public Date getCreated() {\n      return this.created;\n   }\n\n   public boolean isDestroyed() {\n      return this.destroyed;\n   }\n\n   @Nullable\n   public String getDeviceId() {\n      return this.deviceId;\n   }\n\n   @Nullable\n   public String getDiskOfferingDisplayText() {\n      return this.diskOfferingDisplayText;\n   }\n\n   @Nullable\n   public String getDiskOfferingId() {\n      return this.diskOfferingId;\n   }\n\n   @Nullable\n   public String getDiskOfferingName() {\n      return this.diskOfferingName;\n   }\n\n   @Nullable\n   public String getDomain() {\n      return this.domain;\n   }\n\n   @Nullable\n   public String getDomainId() {\n      return this.domainId;\n   }\n\n   @Nullable\n   public String getHypervisor() {\n      return this.hypervisor;\n   }\n\n   public boolean isExtractable() {\n      return this.isExtractable;\n   }\n\n   @Nullable\n   public String getJobId() {\n      return this.jobId;\n   }\n\n   @Nullable\n   public String getJobStatus() {\n      return this.jobStatus;\n   }\n\n   @Nullable\n   public String getName() {\n      return this.name;\n   }\n\n   @Nullable\n   public String getServiceOfferingDisplayText() {\n      return this.serviceOfferingDisplayText;\n   }\n\n   @Nullable\n   public String getServiceOfferingId() {\n      return this.serviceOfferingId;\n   }\n\n   @Nullable\n   public String getServiceOfferingName() {\n      return this.serviceOfferingName;\n   }\n\n   public long getSize() {\n      return this.size;\n   }\n\n   @Nullable\n   public String getSnapshotId() {\n      return this.snapshotId;\n   }\n\n   @Nullable\n   public Volume.State getState() {\n      return this.state;\n   }\n\n   @Nullable\n   public String getStorage() {\n      return this.storage;\n   }\n\n   @Nullable\n   public String getStorageType() {\n      return this.storageType;\n   }\n\n   @Nullable\n   public Volume.Type getType() {\n      return this.type;\n   }\n\n   @Nullable\n   public String getVirtualMachineId() {\n      return this.virtualMachineId;\n   }\n\n   @Nullable\n   public String getVmDisplayName() {\n      return this.vmDisplayName;\n   }\n\n   @Nullable\n   public String getVmName() {\n      return this.vmName;\n   }\n\n   @Nullable\n   public VirtualMachine.State getVmState() {\n      return this.vmState;\n   }\n\n   @Nullable\n   public String getZoneId() {\n      return this.zoneId;\n   }\n\n   @Nullable\n   public String getZoneName() {\n      return this.zoneName;\n   }\n\n   /**\n    * @return the tags for the volume\n    */\n   public Set<Tag> getTags() {\n      return this.tags;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, account, attached, created, destroyed, deviceId, diskOfferingDisplayText, diskOfferingId, diskOfferingName, domain, domainId, hypervisor, isExtractable, jobId, jobStatus, name, serviceOfferingDisplayText, serviceOfferingId, serviceOfferingName, size, snapshotId, state, storage, storageType, type, virtualMachineId, vmDisplayName, vmName, vmState, zoneId, zoneName, tags);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Volume that = Volume.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n            && Objects.equal(this.account, that.account)\n            && Objects.equal(this.attached, that.attached)\n            && Objects.equal(this.created, that.created)\n            && Objects.equal(this.destroyed, that.destroyed)\n            && Objects.equal(this.deviceId, that.deviceId)\n            && Objects.equal(this.diskOfferingDisplayText, that.diskOfferingDisplayText)\n            && Objects.equal(this.diskOfferingId, that.diskOfferingId)\n            && Objects.equal(this.diskOfferingName, that.diskOfferingName)\n            && Objects.equal(this.domain, that.domain)\n            && Objects.equal(this.domainId, that.domainId)\n            && Objects.equal(this.hypervisor, that.hypervisor)\n            && Objects.equal(this.isExtractable, that.isExtractable)\n            && Objects.equal(this.jobId, that.jobId)\n            && Objects.equal(this.jobStatus, that.jobStatus)\n            && Objects.equal(this.name, that.name)\n            && Objects.equal(this.serviceOfferingDisplayText, that.serviceOfferingDisplayText)\n            && Objects.equal(this.serviceOfferingId, that.serviceOfferingId)\n            && Objects.equal(this.serviceOfferingName, that.serviceOfferingName)\n            && Objects.equal(this.size, that.size)\n            && Objects.equal(this.snapshotId, that.snapshotId)\n            && Objects.equal(this.state, that.state)\n            && Objects.equal(this.storage, that.storage)\n            && Objects.equal(this.storageType, that.storageType)\n            && Objects.equal(this.type, that.type)\n            && Objects.equal(this.virtualMachineId, that.virtualMachineId)\n            && Objects.equal(this.vmDisplayName, that.vmDisplayName)\n            && Objects.equal(this.vmName, that.vmName)\n            && Objects.equal(this.vmState, that.vmState)\n            && Objects.equal(this.zoneId, that.zoneId)\n            && Objects.equal(this.zoneName, that.zoneName)\n            && Objects.equal(this.tags, that.tags);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"account\", account).add(\"attached\", attached).add(\"created\", created).add(\"destroyed\", destroyed)\n            .add(\"deviceId\", deviceId).add(\"diskOfferingDisplayText\", diskOfferingDisplayText).add(\"diskOfferingId\", diskOfferingId)\n            .add(\"diskOfferingName\", diskOfferingName).add(\"domain\", domain).add(\"domainId\", domainId).add(\"hypervisor\", hypervisor)\n            .add(\"isExtractable\", isExtractable).add(\"jobId\", jobId).add(\"jobStatus\", jobStatus).add(\"name\", name)\n            .add(\"serviceOfferingDisplayText\", serviceOfferingDisplayText).add(\"serviceOfferingId\", serviceOfferingId)\n            .add(\"serviceOfferingName\", serviceOfferingName).add(\"size\", size).add(\"snapshotId\", snapshotId).add(\"state\", state)\n            .add(\"storage\", storage).add(\"storageType\", storageType).add(\"type\", type).add(\"virtualMachineId\", virtualMachineId)\n            .add(\"vmDisplayName\", vmDisplayName).add(\"vmName\", vmName).add(\"vmState\", vmState).add(\"zoneId\", zoneId).add(\"zoneName\", zoneName)\n            .add(\"tags\", tags);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/Zone.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.List;\nimport java.util.Set;\n\nimport com.google.common.collect.ImmutableSet;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableList;\n\npublic class Zone implements Comparable<Zone> {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromZone(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String id;\n      protected String description;\n      protected String displayText;\n      protected String dns1;\n      protected String dns2;\n      protected String domain;\n      protected String domainId;\n      protected String guestCIDRAddress;\n      protected String internalDNS1;\n      protected String internalDNS2;\n      protected String name;\n      protected NetworkType networkType;\n      protected String vlan;\n      protected boolean securityGroupsEnabled;\n      protected AllocationState allocationState;\n      protected String dhcpProvider;\n      protected String zoneToken;\n      protected Set<Tag> tags = ImmutableSet.of();\n\n      /**\n       * @see Zone#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see Zone#getDescription()\n       */\n      public T description(String description) {\n         this.description = description;\n         return self();\n      }\n\n      /**\n       * @see Zone#getDisplayText()\n       */\n      public T displayText(String displayText) {\n         this.displayText = displayText;\n         return self();\n      }\n\n      /**\n       * @see Zone#getDNS()\n       */\n      public T DNS(List<String> DNS) {\n         if (!DNS.isEmpty()) this.dns1 = DNS.get(0);\n         if (DNS.size() > 1) this.dns2 = DNS.get(1);\n         return self();\n      }\n\n      /**\n       * @see Zone#getDomain()\n       */\n      public T domain(String domain) {\n         this.domain = domain;\n         return self();\n      }\n\n      /**\n       * @see Zone#getDomainId()\n       */\n      public T domainId(String domainId) {\n         this.domainId = domainId;\n         return self();\n      }\n\n      /**\n       * @see Zone#getGuestCIDRAddress()\n       */\n      public T guestCIDRAddress(String guestCIDRAddress) {\n         this.guestCIDRAddress = guestCIDRAddress;\n         return self();\n      }\n\n      /**\n       * @see Zone#getInternalDNS()\n       */\n      public T internalDNS(List<String> DNS) {\n         if (!DNS.isEmpty()) this.internalDNS1 = DNS.get(0);\n         if (DNS.size() > 1) this.internalDNS2 = DNS.get(1);\n         return self();\n      }\n\n      /**\n       * @see Zone#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /**\n       * @see Zone#getNetworkType()\n       */\n      public T networkType(NetworkType networkType) {\n         this.networkType = networkType;\n         return self();\n      }\n\n      /**\n       * @see Zone#getVLAN()\n       */\n      public T VLAN(String vlan) {\n         this.vlan = vlan;\n         return self();\n      }\n\n      /**\n       * @see Zone#isSecurityGroupsEnabled()\n       */\n      public T securityGroupsEnabled(boolean securityGroupsEnabled) {\n         this.securityGroupsEnabled = securityGroupsEnabled;\n         return self();\n      }\n\n      /**\n       * @see Zone#getAllocationState()\n       */\n      public T allocationState(AllocationState allocationState) {\n         this.allocationState = allocationState;\n         return self();\n      }\n\n      /**\n       * @see Zone#getDhcpProvider()\n       */\n      public T dhcpProvider(String dhcpProvider) {\n         this.dhcpProvider = dhcpProvider;\n         return self();\n      }\n\n      /**\n       * @see Zone#getZoneToken()\n       */\n      public T zoneToken(String zoneToken) {\n         this.zoneToken = zoneToken;\n         return self();\n      }\n\n      /**\n       * @see Zone#getTags()\n       */\n      public T tags(Set<Tag> tags) {\n         this.tags = ImmutableSet.copyOf(checkNotNull(tags, \"tags\"));\n         return self();\n      }\n\n      public T tags(Tag... in) {\n         return tags(ImmutableSet.copyOf(in));\n      }\n\n      public Zone build() {\n         return new Zone(id, description, displayText, dns1, dns2, domain, domainId, guestCIDRAddress, internalDNS1, internalDNS2,\n               name, networkType, vlan, securityGroupsEnabled, allocationState, dhcpProvider, zoneToken, tags);\n      }\n\n      public T fromZone(Zone in) {\n         return this\n               .id(in.getId())\n               .description(in.getDescription())\n               .displayText(in.getDisplayText())\n               .DNS(in.getDNS())\n               .domain(in.getDomain())\n               .domainId(in.getDomainId())\n               .guestCIDRAddress(in.getGuestCIDRAddress())\n               .internalDNS(in.getInternalDNS())\n               .name(in.getName())\n               .networkType(in.getNetworkType())\n               .VLAN(in.getVLAN())\n               .securityGroupsEnabled(in.isSecurityGroupsEnabled())\n               .allocationState(in.getAllocationState())\n               .dhcpProvider(in.getDhcpProvider())\n               .zoneToken(in.getZoneToken())\n               .tags(in.getTags());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final String description;\n   private final String displayText;\n   private final String dns1;\n   private final String dns2;\n   private final String domain;\n   private final String domainId;\n   private final String guestCIDRAddress;\n   private final String internalDNS1;\n   private final String internalDNS2;\n   private final String name;\n   private final NetworkType networkType;\n   private final String vlan;\n   private final boolean securityGroupsEnabled;\n   private final AllocationState allocationState;\n   private final String dhcpProvider;\n   private final String zoneToken;\n   private final Set<Tag> tags;\n\n   @ConstructorProperties({\n         \"id\", \"description\", \"displaytext\", \"dns1\", \"dns2\", \"domain\", \"domainid\", \"guestcidraddress\", \"internaldns1\", \"internaldns2\", \"name\", \"networktype\", \"vlan\", \"securitygroupsenabled\", \"allocationstate\", \"dhcpprovider\", \"zonetoken\", \"tags\"\n   })\n   protected Zone(String id, @Nullable String description, @Nullable String displayText, @Nullable String dns1, @Nullable String dns2,\n                  @Nullable String domain, @Nullable String domainId, @Nullable String guestCIDRAddress, @Nullable String internalDNS1,\n                  @Nullable String internalDNS2, @Nullable String name, @Nullable NetworkType networkType, @Nullable String vlan,\n                  boolean securityGroupsEnabled, @Nullable AllocationState allocationState, @Nullable String dhcpProvider,\n                  @Nullable String zoneToken, @Nullable Set<Tag> tags) {\n      this.id = checkNotNull(id, \"id\");\n      this.description = description;\n      this.displayText = displayText;\n      this.dns1 = dns1;\n      this.dns2 = dns2;\n      this.domain = domain;\n      this.domainId = domainId;\n      this.guestCIDRAddress = guestCIDRAddress;\n      this.internalDNS1 = internalDNS1;\n      this.internalDNS2 = internalDNS2;\n      this.name = name;\n      this.networkType = networkType;\n      this.vlan = vlan;\n      this.securityGroupsEnabled = securityGroupsEnabled;\n      this.allocationState = allocationState;\n      this.dhcpProvider = dhcpProvider;\n      this.zoneToken = zoneToken;\n      this.tags = tags != null ? ImmutableSet.copyOf(tags) : ImmutableSet.<Tag> of();\n   }\n\n   /**\n    * @return Zone id\n    */\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * @return Zone description\n    */\n   @Nullable\n   public String getDescription() {\n      return this.description;\n   }\n\n   /**\n    * @return the display text of the zone\n    */\n   @Nullable\n   public String getDisplayText() {\n      return this.displayText;\n   }\n\n   /**\n    * @return the external DNS for the Zone\n    */\n   public List<String> getDNS() {\n      ImmutableList.Builder<String> builder = ImmutableList.builder();\n      if (dns1 != null && !\"\".equals(dns1))\n         builder.add(dns1);\n      if (dns2 != null && !\"\".equals(dns2))\n         builder.add(dns2);\n      return builder.build();\n   }\n\n   /**\n    * @return Domain name for the Vms in the zone\n    */\n   @Nullable\n   public String getDomain() {\n      return this.domain;\n   }\n\n   /**\n    * @return the ID of the containing domain, null for public zones\n    */\n   @Nullable\n   public String getDomainId() {\n      return this.domainId;\n   }\n\n   /**\n    * @return the guest CIDR address for the Zone\n    */\n   @Nullable\n   public String getGuestCIDRAddress() {\n      return this.guestCIDRAddress;\n   }\n\n   /**\n    * @return the internal DNS for the Zone\n    */\n   public List<String> getInternalDNS() {\n      ImmutableList.Builder<String> builder = ImmutableList.builder();\n      if (internalDNS1 != null && !\"\".equals(internalDNS1))\n         builder.add(internalDNS1);\n      if (internalDNS2 != null && !\"\".equals(internalDNS2))\n         builder.add(internalDNS2);\n      return builder.build();\n   }\n\n   /**\n    * @return Zone name\n    */\n   @Nullable\n   public String getName() {\n      return this.name;\n   }\n\n   /**\n    * @return the network type of the zone; can be Basic or Advanced\n    */\n   @Nullable\n   public NetworkType getNetworkType() {\n      return this.networkType;\n   }\n\n   /**\n    * @return the vlan range of the zone\n    */\n   @Nullable\n   public String getVLAN() {\n      return this.vlan;\n   }\n\n   /**\n    * @return true if this zone has security groups enabled\n    */\n   public boolean isSecurityGroupsEnabled() {\n      return this.securityGroupsEnabled;\n   }\n\n   /**\n    * @return the allocation state of the cluster\n    */\n   @Nullable\n   public AllocationState getAllocationState() {\n      return this.allocationState;\n   }\n\n   /**\n    * @return the dhcp Provider for the Zone\n    */\n   @Nullable\n   public String getDhcpProvider() {\n      return this.dhcpProvider;\n   }\n\n   /**\n    * @return Zone Token\n    */\n   @Nullable\n   public String getZoneToken() {\n      return this.zoneToken;\n   }\n\n   /**\n    * @return the tags for the zone\n    */\n   public Set<Tag> getTags() {\n      return this.tags;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, description, displayText, dns1, dns2, domain, domainId, guestCIDRAddress, internalDNS1,\n            internalDNS2, name, networkType, vlan, securityGroupsEnabled, allocationState, dhcpProvider, zoneToken, tags);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Zone that = Zone.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n            && Objects.equal(this.description, that.description)\n            && Objects.equal(this.displayText, that.displayText)\n            && Objects.equal(this.dns1, that.dns1)\n            && Objects.equal(this.dns2, that.dns2)\n            && Objects.equal(this.domain, that.domain)\n            && Objects.equal(this.domainId, that.domainId)\n            && Objects.equal(this.guestCIDRAddress, that.guestCIDRAddress)\n            && Objects.equal(this.internalDNS1, that.internalDNS1)\n            && Objects.equal(this.internalDNS2, that.internalDNS2)\n            && Objects.equal(this.name, that.name)\n            && Objects.equal(this.networkType, that.networkType)\n            && Objects.equal(this.vlan, that.vlan)\n            && Objects.equal(this.securityGroupsEnabled, that.securityGroupsEnabled)\n            && Objects.equal(this.allocationState, that.allocationState)\n            && Objects.equal(this.dhcpProvider, that.dhcpProvider)\n            && Objects.equal(this.zoneToken, that.zoneToken)\n            && Objects.equal(this.tags, that.tags);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"description\", description).add(\"displayText\", displayText).add(\"DNS1\", dns1).add(\"DNS2\", dns2)\n            .add(\"domain\", domain).add(\"domainId\", domainId).add(\"guestCIDRAddress\", guestCIDRAddress).add(\"internalDNS1\", internalDNS1)\n            .add(\"internalDNS2\", internalDNS2).add(\"name\", name).add(\"networkType\", networkType).add(\"VLAN\", vlan)\n            .add(\"securityGroupsEnabled\", securityGroupsEnabled).add(\"allocationState\", allocationState).add(\"dhcpProvider\", dhcpProvider)\n            .add(\"zoneToken\", zoneToken).add(\"tags\", tags);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int compareTo(Zone o) {\n      return id.compareTo(o.getId());\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/ZoneAndName.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Helpful when looking for resources by zone and name\n */\npublic class ZoneAndName {\n   \n   public static final Function<ZoneAndName, String> NAME_FUNCTION = new Function<ZoneAndName, String>() {\n\n      @Override\n      public String apply(ZoneAndName input) {\n         return input.getName();\n      }\n      \n   };\n   \n   public static final Function<ZoneAndName, String> ZONE_FUNCTION = new Function<ZoneAndName, String>() {\n\n      @Override\n      public String apply(ZoneAndName input) {\n         return input.getZone();\n      }\n      \n   };\n\n   public static ZoneAndName fromZoneAndName(String zoneId, String name) {\n      return new ZoneAndName(zoneId, name);\n   }\n\n   protected final String zoneId;\n   protected final String name;\n\n   protected ZoneAndName(String zoneId, String name) {\n      this.zoneId = checkNotNull(zoneId, \"zoneId\");\n      this.name = checkNotNull(name, \"name\");\n   }\n\n   public String getZone() {\n      return zoneId;\n   }\n\n   public String getName() {\n      return name;\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o)\n         return true;\n      if (o == null || getClass() != o.getClass())\n         return false;\n      ZoneAndName that = ZoneAndName.class.cast(o);\n      return equal(this.zoneId, that.zoneId) && equal(this.name, that.name);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(zoneId, name);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(\"\").add(\"zoneId\", zoneId).add(\"name\", name);\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/ZoneSecurityGroupNamePortsCidrs.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Set;\n\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableSet;\n\npublic class ZoneSecurityGroupNamePortsCidrs extends ZoneAndName {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromZoneSecurityGroupNamePortsCidrs(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String zoneId;\n      protected String name;\n      protected Set<Integer> ports = ImmutableSet.of();\n      protected Set<String> cidrs = ImmutableSet.of();\n\n      /**\n       * @see ZoneSecurityGroupNamePortsCidrs#getZone()\n       */\n      public T zone(String zoneId) {\n         this.zoneId = zoneId;\n         return self();\n      }\n\n      /**\n       * @see ZoneSecurityGroupNamePortsCidrs#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n      \n      /**\n       * @see ZoneSecurityGroupNamePortsCidrs#getPorts()\n       */\n      public T ports(Set<Integer> ports) {\n         this.ports = ImmutableSet.copyOf(checkNotNull(ports, \"ports\"));\n         return self();\n      }\n\n      public T ports(Integer... in) {\n         return ports(ImmutableSet.copyOf(in));\n      }\n      \n      /**\n       * @see ZoneSecurityGroupNamePortsCidrs#getCidrs()\n       */\n      public T cidrs(Set<String> cidrs) {\n         this.cidrs = ImmutableSet.copyOf(checkNotNull(cidrs, \"cidrs\"));\n         return self();\n      }\n\n      public T cidrs(String... in) {\n         return cidrs(ImmutableSet.copyOf(in));\n      }\n\n      public ZoneSecurityGroupNamePortsCidrs build() {\n         return new ZoneSecurityGroupNamePortsCidrs(zoneId, name, ports, cidrs);\n      }\n\n      public T fromZoneSecurityGroupNamePortsCidrs(ZoneSecurityGroupNamePortsCidrs in) {\n         return this.zone(in.getZone())\n            .name(in.getName())\n            .ports(in.getPorts())\n            .cidrs(in.getCidrs());\n      }\n   }\n   \n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   \n   private final Set<Integer> ports;\n   private final Set<String> cidrs;\n\n   protected ZoneSecurityGroupNamePortsCidrs(String zoneId, String name, Set<Integer> ports,\n                                             Set<String> cidrs) {\n      super(zoneId, name);\n      this.ports = ports == null ? ImmutableSet.<Integer>of() : ImmutableSet.copyOf(ports);\n      this.cidrs = cidrs == null ? ImmutableSet.<String>of() : ImmutableSet.copyOf(cidrs);\n   }\n\n   /**\n    *\n    * @return the set of ports to open in the security group\n    */\n   public Set<Integer> getPorts() {\n      return ports;\n   }\n   \n   /**\n    *\n    * @return the set of cidrs to give access to the open ports in the security group\n    */\n   public Set<String> getCidrs() {\n      return cidrs;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(zoneId, name, ports, cidrs);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      ZoneSecurityGroupNamePortsCidrs that = ZoneSecurityGroupNamePortsCidrs.class.cast(obj);\n      return Objects.equal(this.zoneId, that.zoneId)\n         && Objects.equal(this.name, that.name)\n         && Objects.equal(this.ports, that.ports)\n         && Objects.equal(this.cidrs, that.cidrs);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n         .add(\"zoneId\", zoneId).add(\"name\", name).add(\"ports\", ports).add(\"cidrs\", cidrs);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/features/AccountApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.cloudstack.domain.Account;\nimport org.jclouds.cloudstack.filters.AuthenticationFilter;\nimport org.jclouds.cloudstack.options.ListAccountsOptions;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.OnlyElement;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\n/**\n * Provides synchronous access to cloudstack via their REST API.\n * <p/>\n * \n * @see <a href=\"http://download.cloud.com/releases/2.2.0/api_2.2.12/TOC_User.html\" />\n */\n@RequestFilters(AuthenticationFilter.class)\n@QueryParams(keys = \"response\", values = \"json\")\npublic interface AccountApi {\n   /**\n    * Lists Accounts\n    * \n    * @param options\n    *           if present, how to constrain the list.\n    * @return Accounts matching query, or empty set, if no Accounts are found\n    */\n   @Named(\"listAccounts\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listAccounts\", \"true\" })\n   @SelectJson(\"account\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<Account> listAccounts(ListAccountsOptions... options);\n\n   /**\n    * get a specific Account by id\n    * \n    * @param id\n    *           Account to get\n    * @return Account or null if not found\n    */\n   @Named(\"listAccounts\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listAccounts\", \"true\" })\n   @SelectJson(\"account\")\n   @OnlyElement\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   Account getAccount(@QueryParam(\"id\") String id);\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/features/AddressApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.cloudstack.domain.AsyncCreateResponse;\nimport org.jclouds.cloudstack.domain.PublicIPAddress;\nimport org.jclouds.cloudstack.filters.AuthenticationFilter;\nimport org.jclouds.cloudstack.functions.CloudStackFallbacks.VoidOnNotFoundOr404OrUnableToFindAccountOwner;\nimport org.jclouds.cloudstack.options.AssociateIPAddressOptions;\nimport org.jclouds.cloudstack.options.ListPublicIPAddressesOptions;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.OnlyElement;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.Unwrap;\n\n/**\n * Provides synchronous access to cloudstack via their REST API.\n * <p/>\n * \n * @see <a href=\"http://download.cloud.com/releases/2.2.0/api_2.2.12/TOC_User.html\" />\n */\n@RequestFilters(AuthenticationFilter.class)\n@QueryParams(keys = \"response\", values = \"json\")\npublic interface AddressApi {\n\n   /**\n    * Lists IPAddresses\n    * \n    * @param options\n    *           if present, how to constrain the list.\n    * @return IPAddresses matching query, or empty set, if no IPAddresses are\n    *         found\n    */\n   @Named(\"listPublicIpAddresses\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listPublicIpAddresses\", \"true\" })\n   @SelectJson(\"publicipaddress\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<PublicIPAddress> listPublicIPAddresses(ListPublicIPAddressesOptions... options);\n\n   /**\n    * get a specific IPAddress by id\n    * \n    * @param id\n    *           IPAddress to get\n    * @return IPAddress or null if not found\n    */\n   @Named(\"listPublicIpAddresses\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listPublicIpAddresses\", \"true\" })\n   @SelectJson(\"publicipaddress\")\n   @OnlyElement\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   PublicIPAddress getPublicIPAddress(@QueryParam(\"id\") String id);\n\n   /**\n    * Acquires and associates a public IP to an account.\n    * \n    * @param zoneId\n    *           the ID of the availability zone you want to acquire an public IP\n    *           address from\n    * @return IPAddress\n    */\n   @Named(\"associateIpAddress\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"associateIpAddress\")\n   @Unwrap\n   @Consumes(MediaType.APPLICATION_JSON)\n   AsyncCreateResponse associateIPAddressInZone(@QueryParam(\"zoneid\") String zoneId,\n         AssociateIPAddressOptions... options);\n\n   /**\n    * Disassociates an ip address from the account.\n    * \n    * @param id\n    *           the id of the public ip address to disassociate\n    */\n   @Named(\"disassociateIpAddress\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"disassociateIpAddress\")\n   @Fallback(VoidOnNotFoundOr404OrUnableToFindAccountOwner.class)\n   void disassociateIPAddress(@QueryParam(\"id\") String id);\n   \n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/features/AsyncJobApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.cloudstack.domain.AsyncJob;\nimport org.jclouds.cloudstack.filters.AuthenticationFilter;\nimport org.jclouds.cloudstack.functions.ParseAsyncJobFromHttpResponse;\nimport org.jclouds.cloudstack.functions.ParseAsyncJobsFromHttpResponse;\nimport org.jclouds.cloudstack.options.ListAsyncJobsOptions;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\n\n/**\n * Provides synchronous access to cloudstack via their REST API.\n * <p/>\n * \n * @see <a href=\"http://download.cloud.com/releases/2.2.0/api_2.2.12/TOC_User.html\" />\n */\n@RequestFilters(AuthenticationFilter.class)\n@QueryParams(keys = \"response\", values = \"json\")\npublic interface AsyncJobApi {\n\n   /**\n    * Lists asyncJobs\n    * \n    * @param options\n    *           if present, how to constrain the list.\n    * @return asyncJobs matching query, or empty set, if no asyncJobs are found\n    */\n   @Named(\"listAsyncJobs\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listAsyncJobs\", \"true\" })\n   @ResponseParser(ParseAsyncJobsFromHttpResponse.class)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<AsyncJob<?>> listAsyncJobs(ListAsyncJobsOptions... options);\n\n   /**\n    * get a specific asyncJob by id\n    * \n    * @param id\n    *           asyncJob to get\n    * @return asyncJob or null if not found\n    */\n   @Named(\"queryAsyncJobResult\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"queryAsyncJobResult\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @ResponseParser(ParseAsyncJobFromHttpResponse.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   <T> AsyncJob<T> getAsyncJob(@QueryParam(\"jobid\") String id);\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/features/ConfigurationApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.cloudstack.domain.Capabilities;\nimport org.jclouds.cloudstack.filters.AuthenticationFilter;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\n/**\n * Provides synchronous access to cloudstack via their REST API.\n * <p/>\n * \n * @see <a href=\"http://download.cloud.com/releases/2.2.0/api_2.2.12/TOC_User.html\" />\n */\n@RequestFilters(AuthenticationFilter.class)\n@QueryParams(keys = { \"response\", \"listAll\" }, values = { \"json\", \"true\" })\npublic interface ConfigurationApi {\n\n   /**\n    * Lists capabilities\n    * \n    * @return current capabilities of this cloud\n    * \n    */\n   @Named(\"listCapabilities\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"listCapabilities\")\n   @SelectJson(\"capability\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   Capabilities listCapabilities();\n   \n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/features/DomainAccountApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.cloudstack.domain.Account;\nimport org.jclouds.cloudstack.domain.AsyncCreateResponse;\nimport org.jclouds.cloudstack.filters.AuthenticationFilter;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.Unwrap;\n\n/**\n * Provides synchronous access to CloudStack Account features available to Domain\n * Admin users.\n *\n * @see <a href=\n *      \"http://download.cloud.com/releases/2.2.0/api_2.2.12/TOC_Domain_Admin.html\"\n *      />\n */\n@RequestFilters(AuthenticationFilter.class)\n@QueryParams(keys = \"response\", values = \"json\")\npublic interface DomainAccountApi extends AccountApi {\n\n   /**\n    * Enable an account\n    *\n    * @param accountName\n    *    the account name you are enabling\n    * @param domainId\n    *    the domain ID\n    */\n   @Named(\"enableAccount\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"enableAccount\")\n   @SelectJson(\"account\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   Account enableAccount(@QueryParam(\"account\") String accountName, @QueryParam(\"domainid\") String domainId);\n\n\n   /**\n    * Disable or lock an account\n    *\n    * @param accountName\n    *    the account name you are disabling\n    * @param domainId\n    *    the domain ID\n    * @param onlyLock\n    *    only lock if true disable otherwise\n    */\n   @Named(\"disableAccount\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"disableAccount\")\n   @Unwrap\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   AsyncCreateResponse disableAccount(@QueryParam(\"account\") String accountName,\n      @QueryParam(\"domainid\") String domainId, @QueryParam(\"lock\") boolean onlyLock);\n   \n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/features/DomainDomainApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.cloudstack.domain.Domain;\nimport org.jclouds.cloudstack.filters.AuthenticationFilter;\nimport org.jclouds.cloudstack.options.ListDomainChildrenOptions;\nimport org.jclouds.cloudstack.options.ListDomainsOptions;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.OnlyElement;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\n/**\n * Provides synchronous access to CloudStack Domain features available to Domain\n * Admin users.\n *\n * @see <a href=\n *      \"http://download.cloud.com/releases/2.2.0/api_2.2.12/TOC_Domain_Admin.html\"\n *      />\n */\n@RequestFilters(AuthenticationFilter.class)\n@QueryParams(keys = \"response\", values = \"json\")\npublic interface DomainDomainApi {\n\n   /**\n    * List domains with detailed information\n    *\n    * @param options\n    *          list filtering optional arguments\n    * @return\n    *          set of domain instances or empty\n    */\n   @Named(\"listDomains\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listDomains\", \"true\" })\n   @SelectJson(\"domain\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<Domain> listDomains(ListDomainsOptions... options);\n\n   /**\n    * Get a domain by ID\n    *\n    * @param domainId\n    *          domain ID\n    * @return\n    *          domain instance or null\n    */\n   @Named(\"listDomains\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listDomains\", \"true\" })\n   @SelectJson(\"domain\")\n   @OnlyElement\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   Domain getDomainById(@QueryParam(\"id\") String domainId);\n\n   /**\n    * Lists all children domains belonging to a specified domain\n    *\n    * @param options\n    *          list filtering optional arguments\n    * @return\n    *          set of domain instances or empty\n    */\n   @Named(\"listDomainChildren\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listDomainChildren\", \"true\" })\n   @SelectJson(\"domain\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<Domain> listDomainChildren(ListDomainChildrenOptions... options);\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/features/DomainLimitApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.cloudstack.binders.ResourceLimitToQueryParams;\nimport org.jclouds.cloudstack.domain.ResourceLimit;\nimport org.jclouds.cloudstack.filters.AuthenticationFilter;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\n/**\n * Provides synchronous access to CloudStack Limit features available to Domain\n * Admin users.\n * \n * @see <a href=\n *      \"http://download.cloud.com/releases/2.2.0/api_2.2.12/TOC_Domain_Admin.html\"\n *      />\n */\n@RequestFilters(AuthenticationFilter.class)\n@QueryParams(keys = \"response\", values = \"json\")\npublic interface DomainLimitApi extends LimitApi {\n   /**\n    * Updates resource limits for an account in a domain.\n    * \n    * @param limit\n    *           what you are updating\n    */\n   @Named(\"updateResourceLimit\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"updateResourceLimit\")\n   @SelectJson(\"resourcelimit\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   ResourceLimit updateResourceLimit(@BinderParam(ResourceLimitToQueryParams.class) ResourceLimit limit);\n   \n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/features/DomainUserApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.cloudstack.domain.AsyncCreateResponse;\nimport org.jclouds.cloudstack.domain.User;\nimport org.jclouds.cloudstack.filters.AuthenticationFilter;\nimport org.jclouds.cloudstack.options.ListUsersOptions;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.Unwrap;\n\n/**\n * Provides synchronous access to CloudStack User features available to Domain\n * Admin users.\n *\n * @see <a href=\n *      \"http://download.cloud.com/releases/2.2.0/api_2.2.12/TOC_Domain_Admin.html\"\n *      />\n */\n@RequestFilters(AuthenticationFilter.class)\n@QueryParams(keys = \"response\", values = \"json\")\npublic interface DomainUserApi {\n\n   /**\n    * Lists Users\n    *\n    * @param options\n    *           if present, how to constrain the list.\n    * @return Users matching query, or empty set, if no Accounts are found\n    */\n   @Named(\"listUsers\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"listUsers\")\n   @SelectJson(\"user\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<User> listUsers(ListUsersOptions... options);\n\n   /**\n    * Enable a user with a specific ID\n    *\n    * @param userId\n    *    the user ID to enable\n    */\n   @Named(\"enableUser\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"enableUser\")\n   @SelectJson(\"user\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   User enableUser(@QueryParam(\"id\") String userId);\n\n   /**\n    * Disable a user with a specific ID\n    */\n   @Named(\"disableUser\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"disableUser\")\n   @Unwrap\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   AsyncCreateResponse disableUser(@QueryParam(\"id\") String userId);\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/features/EventApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.cloudstack.domain.Event;\nimport org.jclouds.cloudstack.filters.AuthenticationFilter;\nimport org.jclouds.cloudstack.functions.ParseEventTypesFromHttpResponse;\nimport org.jclouds.cloudstack.options.ListEventsOptions;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\n\n/**\n * Provides synchronous access to cloudstack via their REST API.\n * <p/>\n *\n * @see <a href=\"http://download.cloud.com/releases/2.2.0/api_2.2.12/TOC_User.html\" />\n */\n@RequestFilters(AuthenticationFilter.class)\n@QueryParams(keys = { \"response\", \"listAll\" }, values = { \"json\", \"true\" })\npublic interface EventApi {\n   /**\n    * List Event Types\n    *\n    * @return event types or null if not found\n    */\n   @Named(\"listEventTypes\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"listEventTypes\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @ResponseParser(ParseEventTypesFromHttpResponse.class)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<String> listEventTypes();\n\n   /**\n    * List Events\n    *\n    * @return event list or null if not found\n    */\n   @Named(\"listEventTypes\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"listEvents\")\n   @SelectJson(\"event\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<Event> listEvents(ListEventsOptions...options);\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/features/FirewallApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.cloudstack.domain.AsyncCreateResponse;\nimport org.jclouds.cloudstack.domain.FirewallRule;\nimport org.jclouds.cloudstack.domain.PortForwardingRule;\nimport org.jclouds.cloudstack.filters.AuthenticationFilter;\nimport org.jclouds.cloudstack.options.CreateFirewallRuleOptions;\nimport org.jclouds.cloudstack.options.ListEgressFirewallRulesOptions;\nimport org.jclouds.cloudstack.options.ListFirewallRulesOptions;\nimport org.jclouds.cloudstack.options.ListPortForwardingRulesOptions;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.OnlyElement;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.Unwrap;\n\n/**\n * Provides synchronous access to cloudstack via their REST API.\n * <p/>\n *\n * @see <a href=\"http://download.cloud.com/releases/2.2.0/api_2.2.12/TOC_User.html\" />\n */\n@RequestFilters(AuthenticationFilter.class)\n@QueryParams(keys = \"response\", values = \"json\")\npublic interface FirewallApi {\n\n   /**\n    * @see FirewallApi#listFirewallRules\n    */\n   @Named(\"listFirewallRules\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listFirewallRules\", \"true\" })\n   @SelectJson(\"firewallrule\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<FirewallRule> listFirewallRules(ListFirewallRulesOptions... options);\n\n   /**\n    * @see FirewallApi#getFirewallRule\n    */\n   @Named(\"listFirewallRules\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listFirewallRules\", \"true\" })\n   @SelectJson(\"firewallrule\")\n   @OnlyElement\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   FirewallRule getFirewallRule(@QueryParam(\"id\") String id);\n\n   /**\n    * @see FirewallApi#createFirewallRuleForIpAndProtocol\n    */\n   @Named(\"createFirewallRule\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"createFirewallRule\")\n   @Unwrap\n   @Consumes(MediaType.APPLICATION_JSON)\n   AsyncCreateResponse createFirewallRuleForIpAndProtocol(@QueryParam(\"ipaddressid\") String ipAddressId,\n         @QueryParam(\"protocol\") FirewallRule.Protocol protocol, CreateFirewallRuleOptions... options);\n\n   /**\n    * @see FirewallApi#createFirewallRuleForIpProtocolAndPort\n    */\n   @Named(\"createFirewallRule\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"createFirewallRule\")\n   @Unwrap\n   @Consumes(MediaType.APPLICATION_JSON)\n   AsyncCreateResponse createFirewallRuleForIpProtocolAndPort(@QueryParam(\"ipaddressid\") String ipAddressId,\n                                                                            @QueryParam(\"protocol\") FirewallRule.Protocol protocol,\n                                                                            @QueryParam(\"startPort\") int startPort,\n                                                                                @QueryParam(\"endPort\") int endPort);\n                                                                            \n\n   /**\n    * @see FirewallApi#deleteFirewallRule\n    */\n   @Named(\"deleteFirewallRule\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"deleteFirewallRule\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void deleteFirewallRule(@QueryParam(\"id\") String id);\n\n   /**\n    * @see FirewallApi#listEgressFirewallRules\n    */\n   @Named(\"listEgressFirewallRules\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listEgressFirewallRules\", \"true\" })\n   @SelectJson(\"firewallrule\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<FirewallRule> listEgressFirewallRules(ListEgressFirewallRulesOptions... options);\n\n   /**\n    * @see FirewallApi#getEgressFirewallRule\n    */\n   @Named(\"listEgressFirewallRules\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listEgressFirewallRules\", \"true\" })\n   @SelectJson(\"firewallrule\")\n   @OnlyElement\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   FirewallRule getEgressFirewallRule(@QueryParam(\"id\") String id);\n\n   /**\n    * @see FirewallApi#createEgressFirewallRuleForNetworkAndProtocol\n    */\n   @Named(\"createEgressFirewallRule\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"createEgressFirewallRule\")\n   @Unwrap\n   @Consumes(MediaType.APPLICATION_JSON)\n   AsyncCreateResponse createEgressFirewallRuleForNetworkAndProtocol(@QueryParam(\"networkid\") String networkId,\n                                                                @QueryParam(\"protocol\") FirewallRule.Protocol protocol,\n                                                                CreateFirewallRuleOptions... options);\n\n   /**\n    * @see FirewallApi#createEgressFirewallRuleForNetworkProtocolAndPort\n    */\n   @Named(\"createEgressFirewallRule\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"createEgressFirewallRule\")\n   @Unwrap\n   @Consumes(MediaType.APPLICATION_JSON)\n   AsyncCreateResponse createEgressFirewallRuleForNetworkProtocolAndPort(@QueryParam(\"networkId\") String networkId,\n                                                                    @QueryParam(\"protocol\") FirewallRule.Protocol protocol,\n                                                                    @QueryParam(\"startPort\") int startPort,\n                                                                    @QueryParam(\"endPort\") int endPort);\n\n\n   /**\n    * @see FirewallApi#deleteEgressFirewallRule\n    */\n   @Named(\"deleteEgressFirewallRule\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"deleteEgressFirewallRule\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void deleteEgressFirewallRule(@QueryParam(\"id\") String id);\n\n   /**\n    * @see FirewallApi#listPortForwardingRules\n    */\n   @Named(\"listPortForwardingRules\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listPortForwardingRules\", \"true\" })\n   @SelectJson(\"portforwardingrule\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<PortForwardingRule> listPortForwardingRules(ListPortForwardingRulesOptions... options);\n\n   /**\n    * @see FirewallApi#getPortForwardingRule\n    */\n   @Named(\"listPortForwardingRules\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listPortForwardingRules\", \"true\" })\n   @SelectJson(\"portforwardingrule\")\n   @OnlyElement\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   PortForwardingRule getPortForwardingRule(@QueryParam(\"id\") String id);\n\n   /**\n    * @see FirewallApi#createPortForwardingRuleForVirtualMachine\n    */\n   @Named(\"createPortForwardingRule\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"createPortForwardingRule\")\n   @Unwrap\n   @Consumes(MediaType.APPLICATION_JSON)\n   AsyncCreateResponse createPortForwardingRuleForVirtualMachine(\n      @QueryParam(\"ipaddressid\") String ipAddressId, @QueryParam(\"protocol\") PortForwardingRule.Protocol protocol,\n      @QueryParam(\"publicport\") int publicPort, @QueryParam(\"virtualmachineid\") String virtualMachineId,\n      @QueryParam(\"privateport\") int privatePort);\n\n   /**\n    * @see FirewallApi#deletePortForwardingRule\n    */\n   @Named(\"deletePortForwardingRule\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"deletePortForwardingRule\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void deletePortForwardingRule(@QueryParam(\"id\") String id);\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/features/GlobalAccountApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.cloudstack.domain.Account;\nimport org.jclouds.cloudstack.filters.AuthenticationFilter;\nimport org.jclouds.cloudstack.options.CreateAccountOptions;\nimport org.jclouds.cloudstack.options.UpdateAccountOptions;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\n/**\n * Provides synchronous access to CloudStack Account features available to Global\n * Admin users.\n *\n * @see <a href=\n *      \"http://download.cloud.com/releases/2.2.0/api_2.2.12/TOC_Global_Admin.html\"\n *      />\n */\n@RequestFilters(AuthenticationFilter.class)\n@QueryParams(keys = \"response\", values = \"json\")\npublic interface GlobalAccountApi extends DomainAccountApi {\n\n   /**\n    * Create a new Cloudstack account\n    *\n    * @param userName unique username.\n    * @param accountType type of account\n    * @param email\n    * @param firstName\n    * @param lastName\n    * @param hashedPassword\n    *          Hashed password (Default is MD5). If you wish to use any other\n    *          hashing algorithm, you would need to write a custom authentication adapter See Docs section.\n    * @param options\n    *          optional parameters\n    * @return\n    */\n   @Named(\"createAccount\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"createAccount\")\n   @SelectJson(\"account\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   Account createAccount(@QueryParam(\"username\") String userName,\n      @QueryParam(\"accounttype\") Account.Type accountType, @QueryParam(\"email\") String email,\n      @QueryParam(\"firstname\") String firstName, @QueryParam(\"lastname\") String lastName,\n      @QueryParam(\"password\") String hashedPassword, CreateAccountOptions... options);\n\n   /**\n    * Update an existing account\n    *\n    * @param accountName the current account name\n    * @param domainId the ID of the domain were the account exists\n    * @param newName new name for the account\n    * @param options optional arguments\n    * @return\n    */\n   @Named(\"updateAccount\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"updateAccount\")\n   @SelectJson(\"account\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   Account updateAccount(@QueryParam(\"account\") String accountName,\n      @QueryParam(\"domainid\") String domainId, @QueryParam(\"newname\") String newName, UpdateAccountOptions... options);\n   \n   /**\n    * Delete an account with the specified ID\n    *\n    * @param accountId\n    * @return\n    */\n   @Named(\"deleteAccount\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"deleteAccount\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   void deleteAccount(@QueryParam(\"id\") String id);\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/features/GlobalAlertApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.cloudstack.domain.Alert;\nimport org.jclouds.cloudstack.filters.AuthenticationFilter;\nimport org.jclouds.cloudstack.options.ListAlertsOptions;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\n/**\n * Provides synchronous access to CloudStack Account features available to Global\n * Admin users.\n * \n * @see <a href=\n *      \"http://download.cloud.com/releases/2.2.0/api_2.2.12/TOC_Global_Admin.html\"\n *      />\n */\n@RequestFilters(AuthenticationFilter.class)\n@QueryParams(keys = \"response\", values = \"json\")\npublic interface GlobalAlertApi {\n   \n   /**\n    * List Alerts\n    *\n    * @return alert list or null if not found\n    */\n   @Named(\"listAlerts\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listAlerts\", \"true\" })\n   @SelectJson(\"alert\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<Alert> listAlerts(ListAlertsOptions...options);\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/features/GlobalCapacityApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.cloudstack.domain.Capacity;\nimport org.jclouds.cloudstack.filters.AuthenticationFilter;\nimport org.jclouds.cloudstack.options.ListCapacityOptions;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\n/**\n * Provides synchronous access to CloudStack Account features available to Global\n * Admin users.\n * \n * @see <a href=\n *      \"http://download.cloud.com/releases/2.2.0/api_2.2.12/TOC_Global_Admin.html\"\n *      />\n */\n@RequestFilters(AuthenticationFilter.class)\n@QueryParams(keys = \"response\", values = \"json\")\npublic interface GlobalCapacityApi {\n\n   /**\n    * List Capacities\n    *\n    * @return alert list or null if not found\n    */\n   @Named(\"listCapacity\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listCapacity\", \"true\" })\n   @SelectJson(\"capacity\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<Capacity> listCapacity(ListCapacityOptions...options);\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/features/GlobalConfigurationApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.cloudstack.domain.ConfigurationEntry;\nimport org.jclouds.cloudstack.filters.AuthenticationFilter;\nimport org.jclouds.cloudstack.options.ListConfigurationEntriesOptions;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\n/**\n * Provides synchronous access to CloudStack Configuration features available to Global\n * Admin users.\n *\n * @see <a href=\n *      \"http://download.cloud.com/releases/2.2.0/api_2.2.12/TOC_Global_Admin.html\"\n *      />\n */\n@RequestFilters(AuthenticationFilter.class)\n@QueryParams(keys = \"response\", values = \"json\")\npublic interface GlobalConfigurationApi extends ConfigurationApi {\n\n   /**\n    * List all configuration entries\n    *\n    * @param options\n    *          result set filtering options\n    * @return\n    *          a set of entries or empty\n    */\n   @Named(\"listConfigurations\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listConfigurations\", \"true\" })\n   @SelectJson(\"configuration\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<ConfigurationEntry> listConfigurationEntries(ListConfigurationEntriesOptions... options);\n\n   /**\n    * Update a configuration entry\n    *\n    * @param name\n    *          the name of the configuration\n    * @param value\n    *          the value of the configuration\n    * @return\n    *          the updated configuration value\n    */\n   @Named(\"updateConfiguration\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"updateConfiguration\")\n   @SelectJson(\"configuration\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   ConfigurationEntry updateConfigurationEntry(\n      @QueryParam(\"name\") String name, @QueryParam(\"value\") String value);\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/features/GlobalDomainApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.cloudstack.domain.Domain;\nimport org.jclouds.cloudstack.filters.AuthenticationFilter;\nimport org.jclouds.cloudstack.options.CreateDomainOptions;\nimport org.jclouds.cloudstack.options.UpdateDomainOptions;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\n/**\n * Provides synchronous access to CloudStack Domain features available to Global\n * Admin users.\n *\n * @see <a href=\n *      \"http://download.cloud.com/releases/2.2.0/api_2.2.12/TOC_Global_Admin.html\"\n *      />\n */\n@RequestFilters(AuthenticationFilter.class)\n@QueryParams(keys = \"response\", values = \"json\")\npublic interface GlobalDomainApi extends DomainDomainApi {\n\n   /**\n    * Create new Domain\n    *\n    * @param name\n    *       domain name\n    * @param options\n    *       optional arguments\n    * @return\n    *       domain instance\n    */\n   @Named(\"createDomain\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"createDomain\")\n   @SelectJson(\"domain\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   Domain createDomain(@QueryParam(\"name\") String name, CreateDomainOptions... options);\n\n   /**\n    * Update a domain\n    *\n    * @param domainId\n    *       the ID of the domain\n    * @param options\n    *       optional arguments\n    * @return\n    *       domain instance\n    */\n   @Named(\"updateDomain\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"updateDomain\")\n   @SelectJson(\"domain\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   Domain updateDomain(@QueryParam(\"id\") String domainId, UpdateDomainOptions... options);\n\n   /**\n    * Delete domain (without deleting attached resources)\n    *\n    * @param id\n    *    the domain ID\n    */\n   @Named(\"deleteDomain\")\n   @GET\n   @QueryParams(keys = {\"command\", \"cleanup\"}, values = {\"deleteDomain\", \"false\"})\n   @Fallback(VoidOnNotFoundOr404.class)\n   void deleteOnlyDomain(@QueryParam(\"id\") String id);\n\n   /**\n    * Delete domain and cleanup all attached resources\n    *\n    * @param id\n    *    the domain ID\n    */\n   @Named(\"deleteDomain\")\n   @GET\n   @QueryParams(keys = {\"command\", \"cleanup\"}, values = {\"deleteDomain\", \"true\"})\n   @Fallback(VoidOnNotFoundOr404.class)\n   void deleteDomainAndAttachedResources(@QueryParam(\"id\") String id);\n}\n\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/features/GlobalHostApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.cloudstack.domain.Cluster;\nimport org.jclouds.cloudstack.domain.Host;\nimport org.jclouds.cloudstack.filters.AuthenticationFilter;\nimport org.jclouds.cloudstack.options.AddClusterOptions;\nimport org.jclouds.cloudstack.options.AddHostOptions;\nimport org.jclouds.cloudstack.options.AddSecondaryStorageOptions;\nimport org.jclouds.cloudstack.options.DeleteHostOptions;\nimport org.jclouds.cloudstack.options.ListClustersOptions;\nimport org.jclouds.cloudstack.options.ListHostsOptions;\nimport org.jclouds.cloudstack.options.UpdateClusterOptions;\nimport org.jclouds.cloudstack.options.UpdateHostOptions;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\n/**\n * Provides synchronous access to cloudstack via their REST API.\n * <p/>\n *\n * @see <a href=\"http://download.cloud.com/releases/2.2.0/api_2.2.12/TOC_Global_Admin.html\" />\n */\n@RequestFilters(AuthenticationFilter.class)\n@QueryParams(keys = \"response\", values = \"json\")\npublic interface GlobalHostApi {\n\n   /**\n    * Lists hosts\n    *\n    * @param options\n    *           if present, how to constrain the list.\n    * @return hosts matching query, or empty set, if no service\n    *         offerings are found\n    */\n   @Named(\"listHosts\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listHosts\", \"true\" })\n   @SelectJson(\"host\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<Host> listHosts(ListHostsOptions... options);\n\n   /**\n    * Adds a new host.\n    *\n    * @param zoneId the Zone ID for the host\n    * @param url the host URL\n    * @param hypervisor hypervisor type of the host\n    * @param username the username for the host\n    * @param password the password for the host\n    * @param options optional arguments\n    * @return the new host.\n    */\n   @Named(\"addHost\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"addHost\")\n   @SelectJson(\"host\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   Host addHost(@QueryParam(\"zoneid\") String zoneId, @QueryParam(\"url\") String url, @QueryParam(\"hypervisor\") String hypervisor, @QueryParam(\"username\") String username, @QueryParam(\"password\") String password, AddHostOptions... options);\n\n   /**\n    * Updates a host.\n    *\n    * @param hostId the ID of the host to update\n    * @param options optional arguments\n    * @return the modified host.\n    */\n   @Named(\"updateHost\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"updateHost\")\n   @SelectJson(\"host\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   Host updateHost(@QueryParam(\"id\") String hostId, UpdateHostOptions... options);\n\n   /**\n    * Update password of a host on management server.\n    *\n    * @param hostId the host ID\n    * @param username the username for the host\n    * @param password the password for the host\n    */\n   @Named(\"updateHostPassword\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"updateHostPassword\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   void updateHostPassword(@QueryParam(\"hostid\") String hostId, @QueryParam(\"username\") String username, @QueryParam(\"password\") String password);\n\n   /**\n    * Deletes a host.\n    *\n    * @param hostId the host ID\n    * @param options optional arguments\n    */\n   @Named(\"deleteHost\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"deleteHost\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   void deleteHost(@QueryParam(\"id\") String hostId, DeleteHostOptions... options);\n\n   /**\n    * Prepares a host for maintenance.\n    *\n    * @param hostId the host ID\n    * @return a job reference number for tracking this asynchronous job.\n    */\n   @Named(\"prepareHostForMaintenance\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"prepareHostForMaintenance\")\n   @SelectJson(\"jobid\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   String prepareHostForMaintenance(@QueryParam(\"id\") String hostId);\n\n   /**\n    * Cancels host maintenance.\n    *\n    * @param hostId the host ID\n    * @return a job reference number for tracking this asynchronous job.\n    */\n   @Named(\"cancelHostMaintenance\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"cancelHostMaintenance\")\n   @SelectJson(\"jobid\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   String cancelHostMaintenance(@QueryParam(\"id\") String hostId);\n\n   /**\n    * Reconnects a host.\n    *\n    * @param hostId\n    * @return a job reference number for tracking this asynchronous job.\n    */\n   @Named(\"reconnectHost\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"reconnectHost\")\n   @SelectJson(\"jobid\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   String reconnectHost(@QueryParam(\"id\") String hostId);\n\n   /**\n    * Adds secondary storage.\n    *\n    * @param url the URL for the secondary storage\n    * @param options optional arguments\n    * @return the host of the storage.\n    */\n   @Named(\"addSecondaryStorage\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"addSecondaryStorage\")\n   @SelectJson(\"host\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   Host addSecondaryStorage(@QueryParam(\"url\") String url, AddSecondaryStorageOptions... options);\n\n   /**\n    * @see GlobalHostApi#listClusters\n    */\n   @Named(\"listClusters\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listClusters\", \"true\" })\n   @SelectJson(\"cluster\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<Cluster> listClusters(ListClustersOptions... options);\n\n   /**\n    * Adds a new cluster.\n    *\n    * @param zoneId the Zone ID for the cluster\n    * @param clusterName the cluster name\n    * @param clusterType type of the cluster\n    * @param hypervisor hypervisor type of the cluster\n    * @param options optional arguments\n    * @return the new cluster.\n    */\n   @Named(\"addCluster\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"addCluster\")\n   @SelectJson(\"cluster\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   Cluster addCluster(@QueryParam(\"zoneid\") String zoneId, @QueryParam(\"clustername\") String clusterName, @QueryParam(\"clustertype\") Host.ClusterType clusterType, @QueryParam(\"hypervisor\") String hypervisor, AddClusterOptions... options);\n\n   /**\n    * Updates an existing cluster.\n    *\n    * @param clusterId the ID of the cluster\n    * @param options optional arguments\n    * @return the modified cluster\n    */\n   @Named(\"updateCluster\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"updateCluster\")\n   @SelectJson(\"cluster\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   Cluster updateCluster(@QueryParam(\"id\") String clusterId, UpdateClusterOptions... options);\n\n   /**\n    * Update password of a cluster on management server.\n    *\n    * @param clusterId the cluster ID\n    * @param username the username for the cluster\n    * @param password the password for the cluster\n    */\n   @Named(\"updateHostPassword\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"updateHostPassword\")\n   @SelectJson(\"cluster\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   void updateClusterPassword(@QueryParam(\"clusterid\") String clusterId, @QueryParam(\"username\") String username, @QueryParam(\"password\") String password);\n\n   /**\n    * Deletes a cluster.\n    *\n    * @param clusterId the cluster ID\n    */\n   @Named(\"deleteCluster\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"deleteCluster\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   void deleteCluster(@QueryParam(\"id\") String clusterId);\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/features/GlobalOfferingApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.cloudstack.domain.DiskOffering;\nimport org.jclouds.cloudstack.domain.NetworkOffering;\nimport org.jclouds.cloudstack.domain.ServiceOffering;\nimport org.jclouds.cloudstack.filters.AuthenticationFilter;\nimport org.jclouds.cloudstack.options.CreateDiskOfferingOptions;\nimport org.jclouds.cloudstack.options.CreateServiceOfferingOptions;\nimport org.jclouds.cloudstack.options.UpdateDiskOfferingOptions;\nimport org.jclouds.cloudstack.options.UpdateNetworkOfferingOptions;\nimport org.jclouds.cloudstack.options.UpdateServiceOfferingOptions;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\n/**\n * Provides synchronous access to cloudstack via their REST API.\n * <p/>\n * \n * @see <a href=\"http://download.cloud.com/releases/2.2.0/api_2.2.12/TOC_Global_Admin.html\" />\n */\n@RequestFilters(AuthenticationFilter.class)\n@QueryParams(keys = \"response\", values = \"json\")\npublic interface GlobalOfferingApi extends OfferingApi {\n\n   /**\n    * Create a new service offering\n    *\n    * @param name\n    *          name of the service offering\n    * @param displayText\n    *          display name\n    * @param cpuNumber\n    *          number of CPUs\n    * @param cpuSpeedInMHz\n    *          CPU speed in MHz\n    * @param memoryInMB\n    *          the total memory of the service offering in MB\n    * @param options\n    *          optional arguments\n    * @return\n    *          service offering instance\n    */\n   @Named(\"createServiceOffering\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"createServiceOffering\")\n   @SelectJson(\"serviceoffering\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   ServiceOffering createServiceOffering(@QueryParam(\"name\") String name, @QueryParam(\"displaytext\") String displayText,\n         @QueryParam(\"cpunumber\") int cpuNumber, @QueryParam(\"cpuspeed\") int cpuSpeedInMHz, @QueryParam(\"memory\") int memoryInMB, CreateServiceOfferingOptions... options);\n\n\n   /**\n    * Update an existing service offering\n    *\n    * @param id\n    *          service offering ID\n    * @param options\n    *          optional arguments\n    * @return\n    *          service offering instance\n    */\n   @Named(\"updateServiceOffering\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"updateServiceOffering\")\n   @SelectJson(\"serviceoffering\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   ServiceOffering updateServiceOffering(@QueryParam(\"id\") String id, UpdateServiceOfferingOptions... options);\n\n   /**\n    * Delete service offering\n    *\n    * @param id\n    *       the ID of the service offering\n    */\n   @Named(\"deleteServiceOffering\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"deleteServiceOffering\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   void deleteServiceOffering(@QueryParam(\"id\") String id);\n\n   /**\n    * Create a new disk offering\n    *\n    * @param name\n    *          name of the disk offering\n    * @param displayText\n    *          display text for disk offering\n    * @param options\n    *          optional arguments\n    * @return\n    *          disk offering instance\n    */\n   @Named(\"createDiskOffering\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"createDiskOffering\")\n   @SelectJson(\"diskoffering\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   DiskOffering createDiskOffering(@QueryParam(\"name\") String name,\n         @QueryParam(\"displaytext\") String displayText, CreateDiskOfferingOptions... options);\n\n   /**\n    * Update a disk offering\n    *\n    * @param id\n    *          disk offering ID\n    * @param options\n    *          optional arguments\n    * @return\n    *          disk offering instance\n    */\n   @Named(\"updateDiskOffering\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"updateDiskOffering\")\n   @SelectJson(\"diskoffering\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   DiskOffering updateDiskOffering(@QueryParam(\"id\") String id, UpdateDiskOfferingOptions... options);\n\n   /**\n    * Delete disk offering\n    *\n    * @param id\n    *       the ID of the disk offering\n    */\n   @Named(\"deleteDiskOffering\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"deleteDiskOffering\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   void deleteDiskOffering(@QueryParam(\"id\") String id);\n\n   /**\n    * Update network offering\n    *\n    * @param id\n    *       the id of the network offering\n    * @param options\n    *       optional arguments\n    * @return\n    *       network offering instance\n    */\n   @Named(\"updateNetworkOffering\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"updateNetworkOffering\")\n   @SelectJson(\"networkoffering\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   NetworkOffering updateNetworkOffering(@QueryParam(\"id\") String id, UpdateNetworkOfferingOptions... options);\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/features/GlobalPodApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.cloudstack.domain.Pod;\nimport org.jclouds.cloudstack.filters.AuthenticationFilter;\nimport org.jclouds.cloudstack.options.CreatePodOptions;\nimport org.jclouds.cloudstack.options.ListPodsOptions;\nimport org.jclouds.cloudstack.options.UpdatePodOptions;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.OnlyElement;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\n/**\n * Provides synchronous access to CloudStack Pod features available to Global\n * Admin users.\n *\n * @see <a href=\n *      \"http://download.cloud.com/releases/2.2.0/api_2.2.12/TOC_Global_Admin.html\"\n *      />\n */\n@RequestFilters(AuthenticationFilter.class)\n@QueryParams(keys = \"response\", values = \"json\")\npublic interface GlobalPodApi {\n\n   /**\n    * Lists pods\n    *\n    * @param options\n    *           if present, how to constrain the list.\n    * @return pods matching query, or empty set, if no pods are found\n    */\n   @Named(\"listPods\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listPods\", \"true\" })\n   @SelectJson(\"pod\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<Pod> listPods(ListPodsOptions... options);\n\n   /**\n    * get a specific pod by id\n    *\n    * @param id\n    *           pod to get\n    * @return pod or null if not found\n    */\n   @Named(\"listPods\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listPods\", \"true\" })\n   @SelectJson(\"pod\")\n   @OnlyElement\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   Pod getPod(@QueryParam(\"id\") String id);\n\n   /**\n    * Creates a new Pod.\n    *\n    * @param name the name of the Pod\n    * @param zoneId the Zone ID in which the Pod will be created\n    * @param startIp the starting IP address for the Pod\n    * @param endIp the ending IP address for the Pod\n    * @param gateway the gateway for the Pod\n    * @param netmask the netmask for the Pod\n    * @param createPodOptions optional arguments\n    * @return the new Pod\n    */\n   @Named(\"createPod\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"createPod\")\n   @SelectJson(\"pod\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   Pod createPod(@QueryParam(\"name\") String name, @QueryParam(\"zoneid\") String zoneId, @QueryParam(\"startip\") String startIp, @QueryParam(\"endip\") String endIp, @QueryParam(\"gateway\") String gateway, @QueryParam(\"netmask\") String netmask, CreatePodOptions... createPodOptions);\n\n   /**\n    * Creates a new Pod.\n    *\n    * @param name the name of the Pod\n    * @param zoneId the Zone ID in which the Pod will be created\n    * @param startIp the starting IP address for the Pod\n    * @param gateway the gateway for the Pod\n    * @param netmask the netmask for the Pod\n    * @param createPodOptions optional arguments\n    * @return the new Pod\n    */\n   @Named(\"createPod\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"createPod\")\n   @SelectJson(\"pod\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   Pod createPod(@QueryParam(\"name\") String name, @QueryParam(\"zoneid\") String zoneId, @QueryParam(\"startip\") String startIp, @QueryParam(\"gateway\") String gateway, @QueryParam(\"netmask\") String netmask, CreatePodOptions... createPodOptions);\n\n   /**\n    * Deletes a Pod.\n    * @param id the ID of the Pod\n    */\n   @Named(\"deletePod\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"deletePod\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(VoidOnNotFoundOr404.class)\n   void deletePod(@QueryParam(\"id\") String id);\n\n   /**\n    * Updates a Pod.\n    * @param id the ID of the Pod\n    * @param updatePodOptions optional arguments\n    * @return the updated pod\n    */\n   @Named(\"updatePod\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"updatePod\")\n   @SelectJson(\"pod\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   Pod updatePod(@QueryParam(\"id\") String id, UpdatePodOptions... updatePodOptions);\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/features/GlobalStoragePoolApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.cloudstack.domain.StoragePool;\nimport org.jclouds.cloudstack.filters.AuthenticationFilter;\nimport org.jclouds.cloudstack.options.ListStoragePoolsOptions;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\n/**\n * Provides synchronous access to CloudStack storage pool features.\n * <p/>\n *\n * @see <a href=\"http://download.cloud.com/releases/2.2.0/api_2.2.12/TOC_Global_Admin.html\" />\n */\n@RequestFilters(AuthenticationFilter.class)\n@QueryParams(keys = \"response\", values = \"json\")\npublic interface GlobalStoragePoolApi {\n\n   @Named(\"listStoragePools\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listStoragePools\", \"true\" })\n   @SelectJson(\"storagepool\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   Set<StoragePool> listStoragePools(ListStoragePoolsOptions... options);\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/features/GlobalUsageApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport java.util.Date;\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.cloudstack.domain.JobResult;\nimport org.jclouds.cloudstack.domain.UsageRecord;\nimport org.jclouds.cloudstack.filters.AuthenticationFilter;\nimport org.jclouds.cloudstack.functions.DateToYyyyMmDd;\nimport org.jclouds.cloudstack.options.GenerateUsageRecordsOptions;\nimport org.jclouds.cloudstack.options.ListUsageRecordsOptions;\nimport org.jclouds.rest.annotations.ParamParser;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\n/**\n * Provides synchronous access to CloudStack usage features.\n * <p/>\n *\n * @see <a href=\"http://download.cloud.com/releases/2.2.0/api_2.2.12/TOC_Global_Admin.html\" />\n */\n@RequestFilters(AuthenticationFilter.class)\n@QueryParams(keys = \"response\", values = \"json\")\npublic interface GlobalUsageApi {\n\n   @Named(\"generateUsageRecords\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"generateUsageRecords\")\n   @SelectJson(\"generateusagerecordsresponse\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   JobResult generateUsageRecords(@QueryParam(\"startdate\") @ParamParser(DateToYyyyMmDd.class) Date start, @QueryParam(\"enddate\") @ParamParser(DateToYyyyMmDd.class) Date end, GenerateUsageRecordsOptions... options);\n\n   @Named(\"listUsageRecords\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listUsageRecords\", \"true\" })\n   @SelectJson(\"usagerecord\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   Set<UsageRecord> listUsageRecords(@QueryParam(\"startdate\") @ParamParser(DateToYyyyMmDd.class) Date start, @QueryParam(\"enddate\") @ParamParser(DateToYyyyMmDd.class) Date end, ListUsageRecordsOptions... options);\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/features/GlobalUserApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.cloudstack.domain.ApiKeyPair;\nimport org.jclouds.cloudstack.domain.User;\nimport org.jclouds.cloudstack.filters.AuthenticationFilter;\nimport org.jclouds.cloudstack.options.CreateUserOptions;\nimport org.jclouds.cloudstack.options.UpdateUserOptions;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\n/**\n * Provides synchronous access to CloudStack User features available to Global\n * Admin users.\n *\n * @see <a href=\n *      \"http://download.cloud.com/releases/2.2.0/api_2.2.12/TOC_Global_Admin.html\"\n *      />\n */\n@RequestFilters(AuthenticationFilter.class)\n@QueryParams(keys = \"response\", values = \"json\")\npublic interface GlobalUserApi extends DomainUserApi {\n\n   /**\n    * Create an user for an account that already exists\n    *\n    * @param userName unique user name\n    * @param accountName Creates the user under the specified account. If no\n    *    account is specified, the username will be used as the account name.\n    * @param email\n    * @param hashedPassword Hashed password (Default is MD5). If you wish to use\n    *    any other hashing algorithm, you would need to write a custom authentication\n    *    adapter See Docs section.\n    * @param firstName\n    * @param lastName\n    * @param options optional arguments\n    * @return\n    */\n   @Named(\"createUser\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"createUser\")\n   @SelectJson(\"user\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   User createUser(@QueryParam(\"username\") String userName, @QueryParam(\"account\") String accountName,\n      @QueryParam(\"email\") String email, @QueryParam(\"password\") String hashedPassword,\n      @QueryParam(\"firstname\") String firstName, @QueryParam(\"lastname\") String lastName, CreateUserOptions... options);\n\n   /**\n    * This command allows a user to register for the developer API, returning a\n    * secret key and an API key\n    *\n    * @param userId the ID of the user\n    * @return\n    */\n   @Named(\"registerUserKeys\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"registerUserKeys\")\n   @SelectJson(\"userkeys\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   ApiKeyPair registerUserKeys(@QueryParam(\"id\") String userId);\n\n   /**\n    * Update an user\n    *\n    * @param id the user ID\n    * @param options optional arguments\n    * @return\n    */\n   @Named(\"updateUser\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"updateUser\")\n   @SelectJson(\"user\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   User updateUser(@QueryParam(\"id\") String id, UpdateUserOptions... options);\n\n   /**\n    * Delete an user with the specified ID\n    *\n    * @param id  user ID\n    */\n   @Named(\"deleteUser\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"deleteUser\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   void deleteUser(@QueryParam(\"id\") String id);\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/features/GlobalVlanApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.cloudstack.domain.VlanIPRange;\nimport org.jclouds.cloudstack.filters.AuthenticationFilter;\nimport org.jclouds.cloudstack.options.CreateVlanIPRangeOptions;\nimport org.jclouds.cloudstack.options.ListVlanIPRangesOptions;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.OnlyElement;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\n/**\n * Provides synchronous access to cloudstack via their REST API.\n * <p/>\n *\n * @see <a href=\"http://download.cloud.com/releases/2.2.0/api_2.2.12/TOC_Global_Admin.html\" />\n */\n@RequestFilters(AuthenticationFilter.class)\n@QueryParams(keys = \"response\", values = \"json\")\npublic interface GlobalVlanApi {\n\n   /**\n    * Get the details of an IP range by its id.\n    * @param id the required IP range.\n    * @return the requested IP range.\n    */\n   @Named(\"listVlanIpRanges\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listVlanIpRanges\", \"true\" })\n   @SelectJson(\"vlaniprange\")\n   @OnlyElement\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   VlanIPRange getVlanIPRange(@QueryParam(\"id\") String id);\n\n   /**\n    * Lists all VLAN IP ranges.\n    *\n    * @param options optional arguments.\n    * @return the list of IP ranges that match the criteria.\n    */\n   @Named(\"listVlanIpRanges\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listVlanIpRanges\", \"true\" })\n   @SelectJson(\"vlaniprange\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<VlanIPRange> listVlanIPRanges(ListVlanIPRangesOptions... options);\n\n   /**\n    * Creates a VLAN IP range.\n    *\n    * @param startIP the beginning IP address in the VLAN IP range\n    * @param endIP the ending IP address in the VLAN IP range\n    * @param options optional arguments\n    * @return the newly-create IP range.\n    */\n   @Named(\"createVlanIpRange\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"createVlanIpRange\")\n   @SelectJson(\"vlaniprange\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   VlanIPRange createVlanIPRange(@QueryParam(\"startip\") String startIP, @QueryParam(\"endip\") String endIP, CreateVlanIPRangeOptions... options);\n\n   /**\n    * Deletes a VLAN IP range.\n    * @param rangeId the id of the VLAN IP range\n    * @return void\n    */\n   @Named(\"deleteVlanIpRange\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"deleteVlanIpRange\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(VoidOnNotFoundOr404.class)\n   void deleteVlanIPRange(@QueryParam(\"id\") String rangeId);\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/features/GlobalZoneApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.cloudstack.domain.NetworkType;\nimport org.jclouds.cloudstack.domain.Zone;\nimport org.jclouds.cloudstack.filters.AuthenticationFilter;\nimport org.jclouds.cloudstack.options.CreateZoneOptions;\nimport org.jclouds.cloudstack.options.UpdateZoneOptions;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\n/**\n * Provides synchronous access to CloudStack Account features available to Global\n * Admin users.\n *\n * @see <a href=\n *      \"http://download.cloud.com/releases/2.2.0/api_2.2.12/TOC_Global_Admin.html\"\n *      />\n */\n@RequestFilters(AuthenticationFilter.class)\n@QueryParams(keys = \"response\", values = \"json\")\npublic interface GlobalZoneApi extends ZoneApi {\n\n   /**\n    * Create a new Zone\n    *\n    * @param name\n    *          the name of the Zone\n    * @param networkType\n    *          network type of the zone, can be Basic or Advanced\n    * @param dns1\n    *          the first DNS for the Zone\n    * @param internalDns1\n    *          the first internal DNS for the Zone\n    * @param options\n    *          optional arguments\n    * @return\n    *          zone instance or null\n    */\n   @Named(\"createZone\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"createZone\")\n   @SelectJson(\"zone\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   Zone createZone(@QueryParam(\"name\") String name, @QueryParam(\"networktype\") NetworkType networkType,\n      @QueryParam(\"dns1\") String externalDns1, @QueryParam(\"internaldns1\") String internalDns1, CreateZoneOptions... options);\n\n   /**\n    * Update a zone\n    *\n    * @param id\n    *          the ID of the Zone\n    * @param options\n    *          optional arguments\n    * @return\n    */\n   @Named(\"updateZone\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"updateZone\")\n   @SelectJson(\"zone\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   Zone updateZone(@QueryParam(\"id\") String id, UpdateZoneOptions... options);\n\n   /**\n    * Delete a zone with a specific ID\n    *\n    * @param zoneId\n    *          the ID of the Zone\n    */\n   @Named(\"deleteZone\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"deleteZone\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(VoidOnNotFoundOr404.class)\n   void deleteZone(@QueryParam(\"id\") String id);\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/features/GuestOSApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.cloudstack.domain.OSType;\nimport org.jclouds.cloudstack.filters.AuthenticationFilter;\nimport org.jclouds.cloudstack.functions.ParseIdToNameEntryFromHttpResponse;\nimport org.jclouds.cloudstack.functions.ParseIdToNameFromHttpResponse;\nimport org.jclouds.cloudstack.options.ListOSTypesOptions;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.OnlyElement;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\n\n/**\n * Provides synchronous access to cloudstack via their REST API.\n * <p/>\n * \n * @see <a href=\"http://download.cloud.com/releases/2.2.0/api_2.2.12/TOC_User.html\" />\n */\n@RequestFilters(AuthenticationFilter.class)\n@QueryParams(keys = \"response\", values = \"json\")\npublic interface GuestOSApi {\n\n   /**\n    * Lists all supported OS types for this cloud.\n    * \n    * @param options\n    *           if present, how to constrain the list\n    * @return os types matching query, or empty set, if no types are found\n    */\n   @Named(\"listOsTypes\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listOsTypes\", \"true\" })\n   @SelectJson(\"ostype\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<OSType> listOSTypes(ListOSTypesOptions... options);\n\n   /**\n    * get a specific os type by id\n    * \n    * @param id\n    *           os type to get\n    * @return os type or null if not found\n    */\n   @Named(\"listOsTypes\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listOsTypes\", \"true\" })\n   @SelectJson(\"ostype\")\n   @OnlyElement\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   OSType getOSType(@QueryParam(\"id\") String id);\n\n   /**\n    * Lists all supported OS categories for this cloud.\n    * \n    * @return os categories matching query, or empty set, if no categories are\n    *         found\n    */\n   @Named(\"listOsCategories\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listOsCategories\", \"true\" })\n   @ResponseParser(ParseIdToNameFromHttpResponse.class)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Map<String, String> listOSCategories();\n\n   /**\n    * get a specific os category by id\n    * \n    * @param id\n    *           os category to get\n    * @return os category or null if not found\n    */\n   @Named(\"listOsCategories\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listOsCategories\", \"true\" })\n   @ResponseParser(ParseIdToNameEntryFromHttpResponse.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   Map.Entry<String, String> getOSCategory(@QueryParam(\"id\") String id);\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/features/HypervisorApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.QueryParam;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.cloudstack.filters.AuthenticationFilter;\nimport org.jclouds.cloudstack.functions.ParseNamesFromHttpResponse;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\n\n/**\n * Provides synchronous access to cloudstack via their REST API.\n * <p/>\n * \n * @see <a href=\"http://download.cloud.com/releases/2.2.0/api_2.2.12/TOC_User.html\" />\n */\n@RequestFilters(AuthenticationFilter.class)\n@QueryParams(keys = \"response\", values = \"json\")\npublic interface HypervisorApi {\n\n   /**\n    * @see HypervisorApi#listHypervisors\n    */\n   @Named(\"listHypervisors\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listHypervisors\", \"true\" })\n   @ResponseParser(ParseNamesFromHttpResponse.class)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<String> listHypervisors();\n\n   /**\n    * @see HypervisorApi#listHypervisorsInZone\n    */\n   @Named(\"listHypervisors\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listHypervisors\", \"true\" })\n   @ResponseParser(ParseNamesFromHttpResponse.class)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<String> listHypervisorsInZone(@QueryParam(\"zoneid\") String zoneId);\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/features/ISOApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.cloudstack.domain.AsyncCreateResponse;\nimport org.jclouds.cloudstack.domain.ExtractMode;\nimport org.jclouds.cloudstack.domain.ISO;\nimport org.jclouds.cloudstack.domain.ISOPermissions;\nimport org.jclouds.cloudstack.filters.AuthenticationFilter;\nimport org.jclouds.cloudstack.options.AccountInDomainOptions;\nimport org.jclouds.cloudstack.options.DeleteISOOptions;\nimport org.jclouds.cloudstack.options.ExtractISOOptions;\nimport org.jclouds.cloudstack.options.ListISOsOptions;\nimport org.jclouds.cloudstack.options.RegisterISOOptions;\nimport org.jclouds.cloudstack.options.UpdateISOOptions;\nimport org.jclouds.cloudstack.options.UpdateISOPermissionsOptions;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.OnlyElement;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.Unwrap;\n\n/**\n * \n * <p/>\n * \n * @see http://download.cloud.com/releases/2.2.12/api/TOC_User.html\n */\n@RequestFilters(AuthenticationFilter.class)\n@QueryParams(keys = \"response\", values = \"json\")\npublic interface ISOApi {\n\n   /**\n    * Attaches an ISO to a virtual machine.\n    *\n    * @param isoId the ID of the ISO file\n    * @param vmId the ID of the virtual machine\n    * @return an asynchronous job response.\n    */\n   @Named(\"attachIso\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @QueryParams(keys = \"command\", values = \"attachIso\")\n   @Unwrap\n   AsyncCreateResponse attachISO(@QueryParam(\"id\") String isoId, @QueryParam(\"virtualmachineid\") String vmId);\n\n   /**\n    * Detaches any ISO file (if any) currently attached to a virtual machine.\n    *\n    * @param vmId The ID of the virtual machine\n    * @return an asynchronous job response.\n    */\n   @Named(\"detachIso\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @QueryParams(keys = \"command\", values = \"detachIso\")\n   @Unwrap\n   AsyncCreateResponse detachISO(@QueryParam(\"virtualmachineid\") String vmId);\n\n   /**\n    * Gets information about an ISO by its ID.\n    *\n    * @param id the ID of the ISO file\n    * @return the ISO object matching the ID\n    */\n   @Named(\"listIsos\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listIsos\", \"true\" })\n   @SelectJson(\"iso\")\n   @OnlyElement\n   @Fallback(NullOnNotFoundOr404.class)\n   ISO getISO(@QueryParam(\"id\") String id);\n\n   /**\n    * Lists all available ISO files.\n    *\n    * @param options optional arguments\n    * @return a set of ISO objects the match the filter\n    */\n   @Named(\"listIsos\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listIsos\", \"true\" })\n   @SelectJson(\"iso\")\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<ISO> listISOs(ListISOsOptions... options);\n\n   /**\n    * Registers an existing ISO into the Cloud.com Cloud.\n    *\n    * @param name the name of the ISO\n    * @param displayText the display text of the ISO. This is usually used for display purposes.\n    * @param url the URL to where the ISO is currently being hosted\n    * @param zoneId the ID of the zone you wish to register the ISO to.\n    * @param options optional arguments\n    * @return the newly-added ISO\n    */\n   @Named(\"registerIso\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @QueryParams(keys = \"command\", values = \"registerIso\")\n   @SelectJson(\"iso\")\n   @OnlyElement\n   ISO registerISO(@QueryParam(\"name\") String name, @QueryParam(\"displaytext\") String displayText, @QueryParam(\"url\") String url, @QueryParam(\"zoneid\") String zoneId, RegisterISOOptions... options);\n\n   /**\n    * \n    *\n    * @param id the ID of the ISO file\n    * @param options optional arguments\n    * @return the ISO object matching the ID\n    */\n   @Named(\"updateIso\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @QueryParams(keys = \"command\", values = \"updateIso\")\n   @Unwrap\n   ISO updateISO(@QueryParam(\"id\") String id, UpdateISOOptions... options);\n\n   /**\n    * Deletes an ISO file.\n    *\n    * @param id the ID of the ISO file\n    * @param options optional arguments\n    * @return an asynchronous job response.\n    */\n   @Named(\"deleteIso\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @QueryParams(keys = \"command\", values = \"deleteIso\")\n   @Unwrap\n   AsyncCreateResponse deleteISO(@QueryParam(\"id\") String id, DeleteISOOptions... options);\n\n   /**\n    * Copies a template from one zone to another.\n    *\n    * @param isoId Template ID.\n    * @param sourceZoneId ID of the zone the template is currently hosted on.\n    * @param destZoneId ID of the zone the template is being copied to.\n    * @return an asynchronous job response.\n    */\n   @Named(\"copyIso\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @QueryParams(keys = \"command\", values = \"copyIso\")\n   @Unwrap\n   AsyncCreateResponse copyISO(@QueryParam(\"id\") String isoId, @QueryParam(\"sourcezoneid\") String sourceZoneId, @QueryParam(\"destzoneid\") String destZoneId);\n\n   /**\n    * Updates iso permissions\n    *\n    * @param id the template ID\n    * @param options optional arguments\n    * @return \n    */\n   @Named(\"updateIsoPermissions\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @QueryParams(keys = \"command\", values = \"updateIsoPermissions\")\n   @Unwrap\n   void updateISOPermissions(@QueryParam(\"id\") String id, UpdateISOPermissionsOptions... options);\n\n   /**\n    * List template visibility and all accounts that have permissions to view this template.\n    *\n    * @param id the template ID\n    * @param options optional arguments\n    * @return A set of the permissions on this ISO\n    */\n   @Named(\"listIsoPermissions\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listIsoPermissions\", \"true\" })\n   @SelectJson(\"templatepermission\")\n   ISOPermissions listISOPermissions(@QueryParam(\"id\") String id, AccountInDomainOptions... options);\n\n   /**\n    * Extracts an ISO\n    *\n    * @param id the ID of the ISO file\n    * @param mode the mode of extraction - HTTP_DOWNLOAD or FTP_UPLOAD\n    * @param zoneId the ID of the zone where the ISO is originally located\n    * @param options optional arguments\n    * @return an asynchronous job response.\n    */\n   @Named(\"extractIso\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @QueryParams(keys = \"command\", values = \"extractIso\")\n   @Unwrap\n   AsyncCreateResponse extractISO(@QueryParam(\"id\") String id, @QueryParam(\"mode\") ExtractMode mode, @QueryParam(\"zoneid\") String zoneId, ExtractISOOptions... options);\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/features/LimitApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.cloudstack.domain.ResourceLimit;\nimport org.jclouds.cloudstack.filters.AuthenticationFilter;\nimport org.jclouds.cloudstack.options.ListResourceLimitsOptions;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\n/**\n * Provides synchronous access to CloudStack SSHKeyPair features.\n *\n * @see <a\n *      href=\"http://download.cloud.com/releases/2.2.0/api_2.2.12/TOC_User.html\"\n *      />\n */\n@RequestFilters(AuthenticationFilter.class)\n@QueryParams(keys = \"response\", values = \"json\")\npublic interface LimitApi {\n   /**\n    * List the resource limits.\n    *\n    * @param options if present, how to constrain the list\n    */\n   @Named(\"listResourceLimits\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listResourceLimits\", \"true\" })\n   @SelectJson(\"resourcelimit\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<ResourceLimit> listResourceLimits(ListResourceLimitsOptions... options);\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/features/LoadBalancerApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.cloudstack.domain.LoadBalancerRule;\nimport org.jclouds.cloudstack.domain.LoadBalancerRule.Algorithm;\nimport org.jclouds.cloudstack.domain.VirtualMachine;\nimport org.jclouds.cloudstack.filters.AuthenticationFilter;\nimport org.jclouds.cloudstack.options.CreateLoadBalancerRuleOptions;\nimport org.jclouds.cloudstack.options.ListLoadBalancerRulesOptions;\nimport org.jclouds.cloudstack.options.UpdateLoadBalancerRuleOptions;\nimport org.jclouds.functions.JoinOnComma;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.OnlyElement;\nimport org.jclouds.rest.annotations.ParamParser;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\n/**\n * Provides synchronous access to cloudstack via their REST API.\n * <p/>\n * \n * @see <a href=\"http://download.cloud.com/releases/2.2.0/api_2.2.12/TOC_User.html\" />\n */\n@RequestFilters(AuthenticationFilter.class)\n@QueryParams(keys = \"response\", values = \"json\")\npublic interface LoadBalancerApi {\n\n   /**\n    * List the load balancer rules\n    * \n    * @param options\n    *           if present, how to constrain the list.\n    * @return load balancer rules matching query, or empty set, if no load\n    *         balancer rules are found\n    */\n   @Named(\"listLoadBalancerRules\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listLoadBalancerRules\", \"true\" })\n   @SelectJson(\"loadbalancerrule\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<LoadBalancerRule> listLoadBalancerRules(ListLoadBalancerRulesOptions... options);\n\n   /**\n    * get a specific LoadBalancerRule by id\n    * \n    * @param id\n    *           LoadBalancerRule to get\n    * @return LoadBalancerRule or null if not found\n    */\n   @Named(\"listLoadBalancerRules\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listLoadBalancerRules\", \"true\" })\n   @SelectJson(\"loadbalancerrule\")\n   @OnlyElement\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   LoadBalancerRule getLoadBalancerRule(@QueryParam(\"id\") String id);\n\n   /**\n    * Creates a load balancer rule.\n    * \n    * @param publicIPId\n    *           the public port from where the network traffic will be load\n    *           balanced from\n    * @param algorithm\n    *           load balancer algorithm (source, roundrobin, leastconn)\n    * @param name\n    *           name of the load balancer rule\n    * @param privatePort\n    *           the private port of the private ip address/virtual machine where\n    *           the network traffic will be load balanced to\n    * @param publicPort\n    *           public ip address id from where the network traffic will be load\n    *           balanced from\n    * @param options optional call arguments\n    * @return newly created rule\n    */\n   @Named(\"createLoadBalancerRule\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"createLoadBalancerRule\")\n   @SelectJson(\"jobid\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   String createLoadBalancerRuleForPublicIP(@QueryParam(\"publicipid\") String publicIPId,\n         @QueryParam(\"algorithm\") Algorithm algorithm, @QueryParam(\"name\") String name,\n         @QueryParam(\"privateport\") int privatePort, @QueryParam(\"publicport\") int publicPort,\n         CreateLoadBalancerRuleOptions... options);\n\n   /**\n    * Update a load balancer rule.\n    *\n    * @param id\n    *       rule id\n    * @param options\n    *       optional arguments\n    * @return updated rule\n    */\n   @Named(\"updateLoadBalancerRule\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"updateLoadBalancerRule\")\n   @SelectJson(\"loadbalancerrule\")\n   @OnlyElement\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   LoadBalancerRule updateLoadBalancerRule(@QueryParam(\"id\") String id, UpdateLoadBalancerRuleOptions... options);\n\n   /**\n    * \n    * deletes a loadbalancer rule\n    * \n    * @param id\n    *           id of the rule to delete\n    * @return async job id of the job completing or null, if the load balancer\n    *         rule was not found.\n    */\n   @Named(\"deleteLoadBalancerRule\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"deleteLoadBalancerRule\")\n   @SelectJson(\"jobid\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   String deleteLoadBalancerRule(@QueryParam(\"id\") String id);\n\n   /**\n    * Assigns virtual machine or a list of virtual machines to a load balancer\n    * rule.\n    * \n    * @param id\n    *           the ID of the load balancer rule\n    * @param virtualMachineIds\n    *           the list of IDs of the virtual machine that are being assigned\n    *           to the load balancer rule\n    * @return job id related to the operation\n    */\n   @Named(\"assignToLoadBalancerRule\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"assignToLoadBalancerRule\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @SelectJson(\"jobid\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   String assignVirtualMachinesToLoadBalancerRule(@QueryParam(\"id\") String id,\n         @QueryParam(\"virtualmachineids\") @ParamParser(JoinOnComma.class) Iterable<String> virtualMachineIds);\n\n   /**\n    * Assigns virtual machine or a list of virtual machines to a load balancer\n    * rule.\n    * \n    * @param id\n    *           the ID of the load balancer rule\n    * @param virtualMachineIds\n    *           the list of IDs of the virtual machine that are being assigned\n    *           to the load balancer rule\n    * @return job id related to the operation\n    */\n   @Named(\"assignToLoadBalancerRule\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"assignToLoadBalancerRule\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @SelectJson(\"jobid\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   String assignVirtualMachinesToLoadBalancerRule(@QueryParam(\"id\") String id,\n         @QueryParam(\"virtualmachineids\") @ParamParser(JoinOnComma.class) String... virtualMachineIds);\n\n   /**\n    * Removes a virtual machine or a list of virtual machines from a load\n    * balancer rule.\n    * \n    * @param id\n    *           the ID of the load balancer rule\n    * @param virtualMachineIds\n    *           the list of IDs of the virtual machine that are being removed\n    *           from the load balancer rule\n    * @return job id related to the operation\n    */\n   @Named(\"removeFromLoadBalancerRule\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"removeFromLoadBalancerRule\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @SelectJson(\"jobid\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   String removeVirtualMachinesFromLoadBalancerRule(@QueryParam(\"id\") String id,\n         @QueryParam(\"virtualmachineids\") @ParamParser(JoinOnComma.class) Iterable<String> virtualMachineIds);\n\n   /**\n    * Removes a virtual machine or a list of virtual machines from a load\n    * balancer rule.\n    * \n    * @param id\n    *           the ID of the load balancer rule\n    * @param virtualMachineIds\n    *           the list of IDs of the virtual machine that are being removed\n    *           from the load balancer rule\n    * @return job id related to the operation\n    */\n   @Named(\"removeFromLoadBalancerRule\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"removeFromLoadBalancerRule\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @SelectJson(\"jobid\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   String removeVirtualMachinesFromLoadBalancerRule(@QueryParam(\"id\") String id,\n         @QueryParam(\"virtualmachineids\") @ParamParser(JoinOnComma.class) String... virtualMachineIds);\n\n   /**\n    * List all virtual machine instances that are assigned to a load balancer\n    * rule.\n    * \n    * @param id\n    *           id of the rule\n    * @return VirtualMachines matching query, or empty set, if no\n    *         VirtualMachines are assigned\n    */\n   @Named(\"listLoadBalancerRuleInstances\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listLoadBalancerRuleInstances\", \"true\" })\n   @SelectJson(\"loadbalancerruleinstance\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<VirtualMachine> listVirtualMachinesAssignedToLoadBalancerRule(@QueryParam(\"id\") String id);\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/features/NATApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.cloudstack.domain.AsyncCreateResponse;\nimport org.jclouds.cloudstack.domain.IPForwardingRule;\nimport org.jclouds.cloudstack.filters.AuthenticationFilter;\nimport org.jclouds.cloudstack.options.CreateIPForwardingRuleOptions;\nimport org.jclouds.cloudstack.options.ListIPForwardingRulesOptions;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.OnlyElement;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.Unwrap;\n\n/**\n * Provides synchronous access to cloudstack via their REST API.\n * <p/>\n * \n * @see <a\n *      href=\"http://download.cloud.com/releases/2.2.0/api_2.2.12/TOC_User.html\"\n *      />\n */\n@RequestFilters(AuthenticationFilter.class)\n@QueryParams(keys = \"response\", values = \"json\")\npublic interface NATApi {\n\n   /**\n    * List the ip forwarding rules\n    * \n    * @param options\n    *           if present, how to constrain the list.\n    * @return IPForwardingRules matching query, or empty set, if no\n    *         IPForwardingRules are found\n    */\n   @Named(\"listIpForwardingRules\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listIpForwardingRules\", \"true\" })\n   @SelectJson(\"ipforwardingrule\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<IPForwardingRule> listIPForwardingRules(ListIPForwardingRulesOptions... options);\n\n   /**\n    * get a specific IPForwardingRule by id\n    * \n    * @param id\n    *           IPForwardingRule to get\n    * @return IPForwardingRule or null if not found\n    */\n   @Named(\"listIpForwardingRules\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listIpForwardingRules\", \"true\" })\n   @SelectJson(\"ipforwardingrule\")\n   @OnlyElement\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   IPForwardingRule getIPForwardingRule(@QueryParam(\"id\") String id);\n\n   /**\n    * get a set of IPForwardingRules by ipaddress id\n    * \n    * @param id\n    *           IPAddress of rule to get\n    * @return IPForwardingRule matching query or empty if not found\n    */\n   @Named(\"listIpForwardingRules\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listIpForwardingRules\", \"true\" })\n   @SelectJson(\"ipforwardingrule\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   Set<IPForwardingRule> getIPForwardingRulesForIPAddress(@QueryParam(\"ipaddressid\") String id);\n\n   /**\n    * get a set of IPForwardingRules by virtual machine id\n    * \n    * @param id\n    *           virtual machine of rule to get\n    * @return IPForwardingRule matching query or empty set if not found\n    */\n   @Named(\"listIpForwardingRules\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listIpForwardingRules\", \"true\" })\n   @SelectJson(\"ipforwardingrule\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   Set<IPForwardingRule> getIPForwardingRulesForVirtualMachine(@QueryParam(\"virtualmachineid\") String id);\n\n   /**\n    * Creates an ip forwarding rule\n    * \n    * @param IPAddressId\n    *           the public IP address id of the forwarding rule, already\n    *           associated via associateIp\n    * @param protocol\n    *           the protocol for the rule. Valid values are TCP or UDP.\n    * @param startPort\n    *           the start port for the rule\n    * @return response used to track creation\n    */\n   @Named(\"createIpForwardingRule\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"createIpForwardingRule\")\n   @Unwrap\n   @Consumes(MediaType.APPLICATION_JSON)\n   AsyncCreateResponse createIPForwardingRule(@QueryParam(\"ipaddressid\") String IPAddressId,\n         @QueryParam(\"protocol\") String protocol, @QueryParam(\"startport\") int startPort,\n         CreateIPForwardingRuleOptions... options);\n\n   @Named(\"enableStaticNat\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"enableStaticNat\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   void enableStaticNATForVirtualMachine(\n         @QueryParam(\"virtualmachineid\") String virtualMachineId, @QueryParam(\"ipaddressid\") String IPAddressId);\n\n   /**\n    * Deletes an ip forwarding rule\n    * \n    * @param id\n    *           the id of the forwarding rule\n    */\n   @Named(\"deleteIpForwardingRule\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"deleteIpForwardingRule\")\n   @SelectJson(\"jobid\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   String deleteIPForwardingRule(@QueryParam(\"id\") String id);\n\n   /**\n    * Disables static rule for given ip address\n    * \n    * @param IPAddressId\n    *           the public IP address id for which static nat feature is being\n    *           disabled\n    */\n   @Named(\"disableStaticNat\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"disableStaticNat\")\n   @SelectJson(\"jobid\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   String disableStaticNATOnPublicIP(@QueryParam(\"ipaddressid\") String IPAddressId);\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/features/NetworkApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.cloudstack.domain.Network;\nimport org.jclouds.cloudstack.filters.AuthenticationFilter;\nimport org.jclouds.cloudstack.options.CreateNetworkOptions;\nimport org.jclouds.cloudstack.options.ListNetworksOptions;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.OnlyElement;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\n/**\n * Provides synchronous access to cloudstack via their REST API.\n * <p/>\n * \n * @see <a href=\"http://download.cloud.com/releases/2.2.0/api_2.2.12/TOC_User.html\" />\n */\n@RequestFilters(AuthenticationFilter.class)\n@QueryParams(keys = \"response\", values = \"json\")\npublic interface NetworkApi {\n\n   /**\n    * Lists networks\n    * \n    * @param options\n    *           if present, how to constrain the list.\n    * @return networks matching query, or empty set, if no networks are found\n    */\n   @Named(\"listNetworks\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listNetworks\", \"true\" })\n   @SelectJson(\"network\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<Network> listNetworks(ListNetworksOptions... options);\n\n   /**\n    * get a specific network by id\n    * \n    * @param id\n    *           network to get\n    * @return network or null if not found\n    */\n   @Named(\"listNetworks\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listNetworks\", \"true\" })\n   @SelectJson(\"network\")\n   @OnlyElement\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   Network getNetwork(@QueryParam(\"id\") String id);\n\n   /**\n    * Creates a network\n    * \n    * @param zoneId\n    *           the Zone ID for the Vlan ip range\n    * @param networkOfferingId\n    *           the network offering id\n    * @param name\n    *           the name of the network\n    * @param displayText\n    *           the display text of the network\n    * @param options\n    *           optional parameters\n    * @return newly created network\n    */\n   @Named(\"createNetwork\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"createNetwork\")\n   @SelectJson(\"network\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   Network createNetworkInZone(@QueryParam(\"zoneid\") String zoneId,\n         @QueryParam(\"networkofferingid\") String networkOfferingId, @QueryParam(\"name\") String name,\n         @QueryParam(\"displaytext\") String displayText, CreateNetworkOptions... options);\n\n   /**\n    * Deletes a network\n    * \n    * @param id\n    *           the ID of the network\n    * @return job id related to destroying the network, or null if resource was\n    *         not found\n    */\n   @Named(\"deleteNetwork\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"deleteNetwork\")\n   @SelectJson(\"jobid\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   String deleteNetwork(@QueryParam(\"id\") String id);\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/features/OfferingApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.cloudstack.domain.DiskOffering;\nimport org.jclouds.cloudstack.domain.NetworkOffering;\nimport org.jclouds.cloudstack.domain.ServiceOffering;\nimport org.jclouds.cloudstack.filters.AuthenticationFilter;\nimport org.jclouds.cloudstack.options.ListDiskOfferingsOptions;\nimport org.jclouds.cloudstack.options.ListNetworkOfferingsOptions;\nimport org.jclouds.cloudstack.options.ListServiceOfferingsOptions;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.OnlyElement;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\n/**\n * Provides synchronous access to cloudstack via their REST API.\n * <p/>\n * \n * @see <a href=\"http://download.cloud.com/releases/2.2.0/api_2.2.12/TOC_User.html\" />\n */\n@RequestFilters(AuthenticationFilter.class)\n@QueryParams(keys = \"response\", values = \"json\")\npublic interface OfferingApi {\n\n   /**\n    * Lists service offerings\n    * \n    * @param options\n    *           if present, how to constrain the list.\n    * @return service offerings matching query, or empty set, if no service\n    *         offerings are found\n    */\n   @Named(\"listServiceOfferings\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listServiceOfferings\", \"true\" })\n   @SelectJson(\"serviceoffering\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<ServiceOffering> listServiceOfferings(ListServiceOfferingsOptions... options);\n\n   /**\n    * get a specific service offering by id\n    * \n    * @param id\n    *           offering to get\n    * @return service offering or null if not found\n    */\n   @Named(\"listServiceOfferings\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listServiceOfferings\", \"true\" })\n   @SelectJson(\"serviceoffering\")\n   @OnlyElement\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   ServiceOffering getServiceOffering(@QueryParam(\"id\") String id);\n\n   /**\n    * Lists disk offerings\n    * \n    * @param options\n    *           if present, how to constrain the list.\n    * @return disk offerings matching query, or empty set, if no disk offerings\n    *         are found\n    */\n   @Named(\"listDiskOfferings\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listDiskOfferings\", \"true\" })\n   @SelectJson(\"diskoffering\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<DiskOffering> listDiskOfferings(ListDiskOfferingsOptions... options);\n\n   /**\n    * get a specific disk offering by id\n    * \n    * @param id\n    *           offering to get\n    * @return disk offering or null if not found\n    */\n   @Named(\"listDiskOfferings\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listDiskOfferings\", \"true\" })\n   @SelectJson(\"diskoffering\")\n   @OnlyElement\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   DiskOffering getDiskOffering(@QueryParam(\"id\") String id);\n\n   /**\n    * Lists service offerings\n    * \n    * @param options\n    *           if present, how to constrain the list.\n    * @return service offerings matching query, or empty set, if no service\n    *         offerings are found\n    */\n   @Named(\"listNetworkOfferings\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listNetworkOfferings\", \"true\" })\n   @SelectJson(\"networkoffering\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<NetworkOffering> listNetworkOfferings(ListNetworkOfferingsOptions... options);\n\n   /**\n    * get a specific service offering by id\n    * \n    * @param id\n    *           offering to get\n    * @return service offering or null if not found\n    */\n   @Named(\"listNetworkOfferings\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listNetworkOfferings\", \"true\" })\n   @SelectJson(\"networkoffering\")\n   @OnlyElement\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   NetworkOffering getNetworkOffering(@QueryParam(\"id\") String id);\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/features/ProjectApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.cloudstack.domain.Project;\nimport org.jclouds.cloudstack.filters.AuthenticationFilter;\nimport org.jclouds.cloudstack.options.ListProjectsOptions;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.OnlyElement;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\n/**\n * Provides synchronous access to CloudStack project features.\n *\n * @see <a\n *      href=\"http://download.cloud.com/releases/3.0.6/api_3.0.6/TOC_Root_Admin.html\"\n *      />\n */\n@RequestFilters(AuthenticationFilter.class)\n@QueryParams(keys = \"response\", values = \"json\")\npublic interface ProjectApi {\n   /**\n    * Lists the projects this account has access to.\n    *\n    * @param options if present, how to constrain the list\n    */\n   @Named(\"listProjects\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listProjects\", \"true\" })\n   @SelectJson(\"project\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<Project> listProjects(ListProjectsOptions... options);\n\n   /**\n    * gets a specific Project by id\n    *\n    * @param id\n    *           Project to get\n    * @return Project or null if not found    */\n   @Named(\"listProjects\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listProjects\", \"true\" })\n   @SelectJson(\"project\")\n   @OnlyElement\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   Project getProject(@QueryParam(\"id\") String id);\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/features/SSHKeyPairApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.cloudstack.domain.SshKeyPair;\nimport org.jclouds.cloudstack.filters.AuthenticationFilter;\nimport org.jclouds.cloudstack.options.ListSSHKeyPairsOptions;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.OnlyElement;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\n/**\n * Provides synchronous access to CloudStack SSHKeyPair features.\n *\n * @see <a\n *      href=\"http://download.cloud.com/releases/2.2.0/api_2.2.8/TOC_User.html\"\n *      />\n */\n@RequestFilters(AuthenticationFilter.class)\n@QueryParams(keys = \"response\", values = \"json\")\npublic interface SSHKeyPairApi {\n   /**\n    * Returns a list of {@link SshKeyPair}s registered by current user.\n    *\n    * @param options if present, how to constrain the list\n    * @return Set of {@link SshKeyPair}s matching the current constrains or\n    *         empty set if no SshKeyPairs found.\n    */\n   @Named(\"listSSHKeyPairs\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listSSHKeyPairs\", \"true\" })\n   @SelectJson(\"sshkeypair\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<SshKeyPair> listSSHKeyPairs(ListSSHKeyPairsOptions... options);\n\n   /**\n    * Registers a {@link SshKeyPair} with the given name and  public kay material.\n    *\n    * @param name      of the keypair\n    * @param publicKey Public key material of the keypair\n    * @return Created SshKeyPair.\n    */\n   @Named(\"registerSSHKeyPair\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"registerSSHKeyPair\")\n   @SelectJson(\"keypair\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   SshKeyPair registerSSHKeyPair(@QueryParam(\"name\") String name, @QueryParam(\"publickey\") String publicKey);\n\n   /**\n    * Creates a {@link SshKeyPair} with specified name.\n    *\n    * @param name of the SshKeyPair.\n    * @return Created SshKeyPair.\n    */\n   @Named(\"createSSHKeyPair\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"createSSHKeyPair\")\n   @SelectJson(\"keypair\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   SshKeyPair createSSHKeyPair(@QueryParam(\"name\") String name);\n\n   /**\n    * Retrieves the {@link SSHKeyPairApi} with given name.\n    *\n    * @param name name of the key pair\n    * @return SSH Key pair or null if not found.\n    */\n   @Named(\"listSSHKeyPairs\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listSSHKeyPairs\", \"true\" })\n   @SelectJson(\"sshkeypair\")\n   @OnlyElement()\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   SshKeyPair getSSHKeyPair(@QueryParam(\"name\") String name);\n\n   /**\n    * Deletes the {@link SSHKeyPairApi} with given name.\n    *\n    * @param name name of the key pair\n    * @return\n    */\n   @Named(\"deleteSSHKeyPair\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"deleteSSHKeyPair\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void deleteSSHKeyPair(@QueryParam(\"name\") String name);\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/features/SecurityGroupApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.cloudstack.binders.BindAccountSecurityGroupPairsToIndexedQueryParams;\nimport org.jclouds.cloudstack.binders.BindCIDRsToCommaDelimitedQueryParam;\nimport org.jclouds.cloudstack.domain.SecurityGroup;\nimport org.jclouds.cloudstack.filters.AuthenticationFilter;\nimport org.jclouds.cloudstack.options.AccountInDomainOptions;\nimport org.jclouds.cloudstack.options.ListSecurityGroupsOptions;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.OnlyElement;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\nimport com.google.common.collect.Multimap;\n/**\n * Provides synchronous access to cloudstack via their REST API.\n * <p/>\n * \n * @see <a href=\"http://download.cloud.com/releases/2.2.0/api_2.2.12/TOC_User.html\" />\n */\n@RequestFilters(AuthenticationFilter.class)\n@QueryParams(keys = \"response\", values = \"json\")\npublic interface SecurityGroupApi {\n\n   /**\n    * Lists security groups\n    * \n    * @param options\n    *           if present, how to constrain the list.\n    * @return security groups matching query, or empty set, if no security\n    *         groups are found\n    */\n   @Named(\"listSecurityGroups\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listSecurityGroups\", \"true\" })\n   @SelectJson(\"securitygroup\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<SecurityGroup> listSecurityGroups(ListSecurityGroupsOptions... options);\n\n   /**\n    * get a specific security group by id\n    * \n    * @param id\n    *           group to get\n    * @return security group or null if not found\n    */\n   @Named(\"listSecurityGroups\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listSecurityGroups\", \"true\" })\n   @SelectJson(\"securitygroup\")\n   @OnlyElement\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   SecurityGroup getSecurityGroup(@QueryParam(\"id\") String id);\n\n   /**\n    * get a specific security group by name\n    * \n    * @param securityGroupName\n    *           group to get\n    * @return security group or null if not found\n    */\n   @Named(\"listSecurityGroups\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listSecurityGroups\", \"true\" })\n   @SelectJson(\"securitygroup\")\n   @OnlyElement\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   SecurityGroup getSecurityGroupByName(@QueryParam(\"securitygroupname\") String securityGroupName);\n\n   /**\n    * Creates a security group\n    * \n    * @param name\n    *           name of the security group\n    * @return security group\n    */\n   @Named(\"createSecurityGroup\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"createSecurityGroup\")\n   @SelectJson(\"securitygroup\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   SecurityGroup createSecurityGroup(@QueryParam(\"name\") String name);\n\n   /**\n    * Authorizes a particular TCP or UDP ingress rule for this security group\n    * \n    * @param securityGroupId\n    *           The ID of the security group\n    * @param protocol\n    *           tcp or udp\n    * @param startPort\n    *           start port for this ingress rule\n    * @param endPort\n    *           end port for this ingress rule\n    * @param cidrList\n    *           the cidr list associated\n    * @return response relating to the creation of this ingress rule\n    */\n   @Named(\"authorizeSecurityGroupIngress\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"authorizeSecurityGroupIngress\")\n   @SelectJson(\"jobid\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   String authorizeIngressPortsToCIDRs(@QueryParam(\"securitygroupid\") String securityGroupId,\n         @QueryParam(\"protocol\") String protocol, @QueryParam(\"startport\") int startPort,\n         @QueryParam(\"endport\") int endPort,\n         @BinderParam(BindCIDRsToCommaDelimitedQueryParam.class) Iterable<String> cidrList,\n         AccountInDomainOptions... options);\n\n   /**\n    * Authorizes a particular TCP or UDP ingress rule for this security group\n    * \n    * @param securityGroupId\n    *           The ID of the security group\n    * @param protocol\n    *           tcp or udp\n    * @param startPort\n    *           start port for this ingress rule\n    * @param endPort\n    *           end port for this ingress rule\n    * @param accountToGroup\n    *           mapping of account names to security groups you wish to\n    *           authorize\n    * @return response relating to the creation of this ingress rule\n    */\n   @Named(\"authorizeSecurityGroupIngress\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"authorizeSecurityGroupIngress\")\n   @SelectJson(\"jobid\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   String authorizeIngressPortsToSecurityGroups(@QueryParam(\"securitygroupid\") String securityGroupId,\n         @QueryParam(\"protocol\") String protocol, @QueryParam(\"startport\") int startPort,\n         @QueryParam(\"endport\") int endPort,\n         @BinderParam(BindAccountSecurityGroupPairsToIndexedQueryParams.class) Multimap<String, String> accountToGroup,\n         AccountInDomainOptions... options);\n\n   /**\n    * Authorizes a particular ICMP ingress rule for this security group\n    * \n    * @param securityGroupId\n    *           The ID of the security group\n    * @param ICMPCode\n    *           type of the icmp message being sent\n    * @param ICMPType\n    *           error code for this icmp message\n    * @param cidrList\n    *           the cidr list associated\n    * @return response relating to the creation of this ingress rule\n    */\n   @Named(\"authorizeSecurityGroupIngress\")\n   @GET\n   @QueryParams(keys = { \"command\", \"protocol\" }, values = { \"authorizeSecurityGroupIngress\", \"ICMP\" })\n   @SelectJson(\"jobid\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   String authorizeIngressICMPToCIDRs(@QueryParam(\"securitygroupid\") String securityGroupId,\n         @QueryParam(\"icmpcode\") int ICMPCode, @QueryParam(\"icmptype\") int ICMPType,\n         @BinderParam(BindCIDRsToCommaDelimitedQueryParam.class) Iterable<String> cidrList,\n         AccountInDomainOptions... options);\n\n   /**\n    * Authorizes a particular ICMP ingress rule for this security group\n    * \n    * @param securityGroupId\n    *           The ID of the security group\n    * @param ICMPCode\n    *           type of the icmp message being sent\n    * @param ICMPType\n    *           error code for this icmp message\n    * @param accountToGroup\n    *           mapping of account names to security groups you wish to\n    *           authorize\n    * @return response relating to the creation of this ingress rule\n    */\n   @Named(\"authorizeSecurityGroupIngress\")\n   @GET\n   @QueryParams(keys = { \"command\", \"protocol\" }, values = { \"authorizeSecurityGroupIngress\", \"ICMP\" })\n   @SelectJson(\"jobid\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   String authorizeIngressICMPToSecurityGroups(@QueryParam(\"securitygroupid\") String securityGroupId,\n         @QueryParam(\"icmpcode\") int ICMPCode, @QueryParam(\"icmptype\") int ICMPType,\n         @BinderParam(BindAccountSecurityGroupPairsToIndexedQueryParams.class) Multimap<String, String> accountToGroup,\n         AccountInDomainOptions... options);\n\n   /**\n    * Deletes a particular ingress rule from this security group\n    * \n    * @param id\n    *           The ID of the ingress rule\n    * @param options\n    *           scope of the rule.\n    */\n   @Named(\"revokeSecurityGroupIngress\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"revokeSecurityGroupIngress\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   @SelectJson(\"jobid\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   String revokeIngressRule(@QueryParam(\"id\") String id, AccountInDomainOptions... options);\n\n   /**\n    * delete a specific security group by id\n    * \n    * @param id\n    *           group to delete\n    */\n   @Named(\"deleteSecurityGroup\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"deleteSecurityGroup\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(VoidOnNotFoundOr404.class)\n   void deleteSecurityGroup(@QueryParam(\"id\") String id);\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/features/SessionApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.cloudstack.domain.LoginResponse;\nimport org.jclouds.cloudstack.functions.ParseLoginResponseFromHttpResponse;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.ResponseParser;\n\n/**\n * Provides synchronous access to Cloudstack Sessions\n * <p/>\n * \n * @see <a href=\"http://download.cloud.com/releases/2.2.0/api_2.2.12/TOC_User.html\" />\n */\n@QueryParams(keys = \"response\", values = \"json\")\npublic interface SessionApi {\n\n   /**\n    * Logs a user into Cloudstack.  A successful login attempt will generate a JSESSIONID\n    * cookie value that can be passed in subsequent Query command calls until the \"logout\"\n    * command has been issued or the session has expired.\n    *\n    *\n    *\n    * @param userName\n    *          user account name\n    * @param domain\n    *          domain name, if empty defaults to ROOT\n    * @param hashedPassword\n    *          hashed password (by default MD5)\n    * @return\n    *          login response with session key or null\n    */\n   @Named(\"login\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"login\")\n   @ResponseParser(ParseLoginResponseFromHttpResponse.class)\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   LoginResponse loginUserInDomainWithHashOfPassword(@QueryParam(\"username\") String userName,\n      @QueryParam(\"domain\") String domain, @QueryParam(\"password\") String hashedPassword);\n\n   /**\n    * Logs out the user by invalidating the session key\n    *\n    * @param sessionKey\n    *          user session key\n    */\n   @Named(\"logout\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"logout\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void logoutUser(@QueryParam(\"sessionkey\") String sessionKey);\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/features/SnapshotApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.cloudstack.binders.BindIdListToCommaDelimitedQueryParam;\nimport org.jclouds.cloudstack.binders.BindSnapshotPolicyScheduleToQueryParam;\nimport org.jclouds.cloudstack.domain.AsyncCreateResponse;\nimport org.jclouds.cloudstack.domain.Snapshot;\nimport org.jclouds.cloudstack.domain.SnapshotPolicy;\nimport org.jclouds.cloudstack.domain.SnapshotPolicySchedule;\nimport org.jclouds.cloudstack.filters.AuthenticationFilter;\nimport org.jclouds.cloudstack.options.CreateSnapshotOptions;\nimport org.jclouds.cloudstack.options.ListSnapshotPoliciesOptions;\nimport org.jclouds.cloudstack.options.ListSnapshotsOptions;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.OnlyElement;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.Unwrap;\n\n/**\n * Provides synchronous access to CloudStack Snapshot features.\n * <p/>\n * \n * @see http://download.cloud.com/releases/2.2.0/api/TOC_User.html\n */\n@RequestFilters(AuthenticationFilter.class)\n@QueryParams(keys = \"response\", values = \"json\")\npublic interface SnapshotApi {\n\n   /**\n    * Creates an instant snapshot of a volume.\n    *\n    * @param volumeId The ID of the disk volume\n    * @param options optional arguments\n    * @return an asynchronous job structure\n    */\n   @Named(\"createSnapshot\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @QueryParams(keys = \"command\", values = \"createSnapshot\")\n   @Unwrap\n   AsyncCreateResponse createSnapshot(@QueryParam(\"volumeid\") String volumeId, CreateSnapshotOptions... options);\n\n   /**\n    * Lists all available snapshots for the account, matching the query described by the options.\n    *\n    * @param options optional arguments\n    * @return the snapshots matching the query\n    */\n   @Named(\"listSnapshots\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listSnapshots\", \"true\" })\n   @SelectJson(\"snapshot\")\n   @Unwrap\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<Snapshot> listSnapshots(ListSnapshotsOptions... options);\n\n   /**\n    * Gets a snapshot by its ID.\n    *\n    * @param id the snapshot ID\n    * @return the snapshot with the requested ID\n    */\n   @Named(\"listSnapshots\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listSnapshots\", \"true\" })\n   @SelectJson(\"snapshot\")\n   @OnlyElement\n   @Fallback(NullOnNotFoundOr404.class)\n   Snapshot getSnapshot(@QueryParam(\"id\") String id);\n\n   /**\n    * Deletes a snapshot of a disk volume.\n    *\n    * @param id The ID of the snapshot\n    * @return an asynchronous job structure\n    */\n   @Named(\"deleteSnapshot\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @QueryParams(keys = \"command\", values = \"deleteSnapshot\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void deleteSnapshot(@QueryParam(\"id\") String id);\n\n   /**\n    * Creates a snapshot policy for the account.\n    *\n    * @param schedule how to schedule snapshots\n    * @param numberToRetain maximum number of snapshots to retain\n    * @param timezone Specifies a timezone for this command. For more information on the timezone parameter, see Time Zone Format.\n    * @param volumeId the ID of the disk volume\n    * @return the newly-created snapshot policy\n    */\n   @Named(\"createSnapshotPolicy\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Unwrap\n   @QueryParams(keys = \"command\", values = \"createSnapshotPolicy\")\n   SnapshotPolicy createSnapshotPolicy(@BinderParam(BindSnapshotPolicyScheduleToQueryParam.class) SnapshotPolicySchedule schedule, @QueryParam(\"maxsnaps\") String numberToRetain, @QueryParam(\"timezone\") String timezone, @QueryParam(\"volumeid\") String volumeId);\n\n   /**\n    * Deletes a snapshot policy for the account.\n    *\n    * @param id The ID of the snapshot policy\n    * @return\n    */\n   @Named(\"deleteSnapshotPolicies\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @QueryParams(keys = \"command\", values = \"deleteSnapshotPolicies\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void deleteSnapshotPolicy(@QueryParam(\"id\") String id);\n\n   /**\n    * Deletes snapshot policies for the account.\n    *\n    * @param id IDs of snapshot policies\n    * @return\n    */\n   @Named(\"deleteSnapshotPolicies\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @QueryParams(keys = \"command\", values = \"deleteSnapshotPolicies\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void deleteSnapshotPolicies(@BinderParam(BindIdListToCommaDelimitedQueryParam.class) Iterable<String> id);\n\n   /**\n    * Lists snapshot policies.\n    *\n    * @param volumeId the ID of the disk volume\n    * @param options optional arguments\n    * @return the snapshot policies matching the query\n    */\n   @Named(\"listSnapshotPolicies\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listSnapshotPolicies\", \"true\" })\n   @Unwrap\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<SnapshotPolicy> listSnapshotPolicies(@QueryParam(\"volumeid\") String volumeId, ListSnapshotPoliciesOptions... options);\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/features/TagApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.core.MediaType;\nimport java.util.Set;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.cloudstack.domain.AsyncCreateResponse;\nimport org.jclouds.cloudstack.domain.Tag;\nimport org.jclouds.cloudstack.filters.AuthenticationFilter;\nimport org.jclouds.cloudstack.options.CreateTagsOptions;\nimport org.jclouds.cloudstack.options.DeleteTagsOptions;\nimport org.jclouds.cloudstack.options.ListTagsOptions;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.Unwrap;\n\n/**\n * Provides synchronous access to cloudstack via their REST API.\n * <p/>\n * \n * @see <a href=\"http://cloudstack.apache.org/docs/api/apidocs-4.3/TOC_Root_Admin.html\" />\n */\n@RequestFilters(AuthenticationFilter.class)\n@QueryParams(keys = \"response\", values = \"json\")\npublic interface TagApi {\n\n   /**\n    * Lists tags\n    * \n    * @param options\n    *           if present, how to constrain the list.\n    * @return tags matching query, or empty set, if no tags are found\n    */\n   @Named(\"listTags\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listTags\", \"true\" })\n   @SelectJson(\"tag\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<Tag> listTags(ListTagsOptions... options);\n\n   /**\n    * Creates one or more tags on the specified resources.\n    *\n    * @param options arguments\n    * @return an asynchronous job structure\n    */\n   @Named(\"createTags\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @QueryParams(keys = \"command\", values = \"createTags\")\n   @Unwrap\n   AsyncCreateResponse createTags(CreateTagsOptions options);\n\n   /**\n    * Deletes one or more tags from the specified resources.\n    *\n    * @param options arguments\n    * @return an asynchronous job structure\n    */\n   @Named(\"deleteTags\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @QueryParams(keys = \"command\", values = \"deleteTags\")\n   @Unwrap\n   AsyncCreateResponse deleteTags(DeleteTagsOptions options);\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/features/TemplateApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.cloudstack.binders.BindTemplateMetadataToQueryParams;\nimport org.jclouds.cloudstack.domain.AsyncCreateResponse;\nimport org.jclouds.cloudstack.domain.ExtractMode;\nimport org.jclouds.cloudstack.domain.Template;\nimport org.jclouds.cloudstack.domain.TemplateMetadata;\nimport org.jclouds.cloudstack.domain.TemplatePermission;\nimport org.jclouds.cloudstack.filters.AuthenticationFilter;\nimport org.jclouds.cloudstack.options.AccountInDomainOptions;\nimport org.jclouds.cloudstack.options.CreateTemplateOptions;\nimport org.jclouds.cloudstack.options.DeleteTemplateOptions;\nimport org.jclouds.cloudstack.options.ExtractTemplateOptions;\nimport org.jclouds.cloudstack.options.ListTemplatesOptions;\nimport org.jclouds.cloudstack.options.RegisterTemplateOptions;\nimport org.jclouds.cloudstack.options.UpdateTemplateOptions;\nimport org.jclouds.cloudstack.options.UpdateTemplatePermissionsOptions;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.OnlyElement;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.Unwrap;\n\n/**\n * Provides synchronous access to cloudstack via their REST API.\n * <p/>\n * \n * @see <a\n *      href=\"http://download.cloud.com/releases/2.2.0/api_2.2.12/TOC_User.html\"\n *      />\n */\n@RequestFilters(AuthenticationFilter.class)\n@QueryParams(keys = \"response\", values = \"json\")\npublic interface TemplateApi {\n\n   /**\n    * Creates a template of a virtual machine. The virtual machine must be in a\n    * STOPPED state. A template created from this command is automatically\n    * designated as a private template visible to the account that created it.\n    * \n    * @see http\n    *      ://download.cloud.com/releases/2.2.0/api_2.2.8/user/createTemplate\n    *      .html\n    * @param templateMetadata\n    *           overall description of the template\n    * @param options\n    *           optional arguments\n    * @return an asynchronous job response\n    */\n   @Named(\"createTemplate\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"createTemplate\")\n   @Unwrap\n   @Consumes(MediaType.APPLICATION_JSON)\n   AsyncCreateResponse createTemplate(\n         @BinderParam(BindTemplateMetadataToQueryParams.class) TemplateMetadata templateMetadata,\n         CreateTemplateOptions... options);\n\n   /**\n    * Registers an existing template into the Cloud.com cloud.\n    * \n    * @see http \n    *      ://download.cloud.com/releases/2.2.0/api_2.2.8/user/registerTemplate\n    *      .html\n    * @param templateMetadata\n    *           overall description of the template\n    * @param format\n    *           the format for the template. Possible values include QCOW2, RAW,\n    *           and VHD.\n    * \n    * @param url\n    *           the URL of where the template is hosted. Possible URL include\n    *           http:// and https://\n    * @param zoneId\n    *           the ID of the zone the template is to be hosted on\n    * @param options\n    *           optional arguments\n    * @return data about the newly-registered template\n    */\n   @Named(\"registerTemplate\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"registerTemplate\")\n   @SelectJson(\"template\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   Set<Template> registerTemplate(\n         @BinderParam(BindTemplateMetadataToQueryParams.class) TemplateMetadata templateMetadata,\n         @QueryParam(\"format\") String format, @QueryParam(\"hypervisor\") String hypervisor,\n         @QueryParam(\"url\") String url, @QueryParam(\"zoneid\") String zoneId, RegisterTemplateOptions... options);\n\n   /**\n    * Updates attributes of a template.\n    * \n    * @see http\n    *      ://download.cloud.com/releases/2.2.0/api_2.2.8/user/updateTemplate\n    *      .html\n    * @param id\n    *           the ID of the image file\n    * @param options\n    *           optional arguments\n    * @return updated data about the template\n    */\n   @Named(\"updateTemplate\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"updateTemplate\")\n   @SelectJson(\"template\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   Template updateTemplate(@QueryParam(\"id\") String id, UpdateTemplateOptions... options);\n\n   /**\n    * Copies a template from one zone to another.\n    * \n    * @see http \n    *      ://download.cloud.com/releases/2.2.0/api_2.2.8/user/copyTemplate.html\n    * @param id\n    *           Template ID.\n    * @param sourceZoneId\n    *           ID of the zone the template is currently hosted on.\n    * @param destZoneId\n    *           ID of the zone the template is being copied to.\n    * @return an asynchronous job response\n    */\n   @Named(\"copyTemplate\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"copyTemplate\")\n   @Unwrap\n   @Consumes(MediaType.APPLICATION_JSON)\n   AsyncCreateResponse copyTemplateToZone(@QueryParam(\"id\") String id,\n         @QueryParam(\"sourcezoneid\") String sourceZoneId, @QueryParam(\"destzoneid\") String destZoneId);\n\n   /**\n    * Deletes a template from the system. All virtual machines using the deleted\n    * template will not be affected.\n    * \n    * @see http\n    *      ://download.cloud.com/releases/2.2.0/api_2.2.8/user/deleteTemplate\n    *      .html\n    * @param id\n    *           the ID of the template\n    * @param options\n    *           optional arguments\n    */\n   @Named(\"deleteTemplate\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"deleteTemplate\")\n   @Unwrap\n   @Consumes(MediaType.APPLICATION_JSON)\n   AsyncCreateResponse deleteTemplate(@QueryParam(\"id\") String id, DeleteTemplateOptions... options);\n\n   /**\n    * List all executable templates.\n    * \n    * @see http\n    *      ://download.cloud.com/releases/2.2.0/api_2.2.8/user/listTemplates.\n    *      html\n    * @return all executable templates, or empty set, if no templates are found\n    */\n   @Named(\"listTemplates\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\", \"templatefilter\" }, values = { \"listTemplates\", \"true\", \"executable\" })\n   @SelectJson(\"template\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<Template> listTemplates();\n\n   /**\n    * List all public, private, and privileged templates.\n    * \n    * @see http\n    *      ://download.cloud.com/releases/2.2.0/api_2.2.8/user/listTemplates.\n    *      html\n    * @param options\n    *           if present, how to constrain the list, defaults to all\n    *           executable templates\n    * @return templates matching query, or empty set, if no templates are found\n    * @see TemplateFilter\n    */\n   @Named(\"listTemplates\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listTemplates\", \"true\" })\n   @SelectJson(\"template\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<Template> listTemplates(ListTemplatesOptions options);\n\n   /**\n    * get a specific template by id\n    * \n    * \n    * @param templateId\n    * @param zoneId\n    *           zone template is defined in\n    * @return template or null if not found\n    */\n   @Named(\"listTemplates\")\n   @GET\n   // templatefilter required in at least 2.2.8 version\n   @QueryParams(keys = { \"command\", \"listAll\", \"templatefilter\" }, values = { \"listTemplates\", \"true\", \"executable\" })\n   @SelectJson(\"template\")\n   @OnlyElement\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   Template getTemplateInZone(@QueryParam(\"id\") String templateId, @QueryParam(\"zoneid\") String zoneId);\n\n   /**\n    * Updates a template visibility permissions. A public template is visible to\n    * all accounts within the same domain. A private template is visible only to\n    * the owner of the template. A privileged template is a private template\n    * with account permissions added. Only accounts specified under the template\n    * permissions are visible to them.\n    * \n    * @see http://download.cloud.com/releases/2.2.0/api_2.2.8/user/\n    *      updateTemplatePermissions.html\n    * @param id\n    *           the template ID\n    * @param options\n    *           optional arguments\n    */\n   @Named(\"updateTemplatePermissions\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"updateTemplatePermissions\")\n   void updateTemplatePermissions(@QueryParam(\"id\") String id,\n         UpdateTemplatePermissionsOptions... options);\n\n   /**\n    * List template visibility and all accounts that have permissions to view\n    * this template.\n    * \n    * @see http://download.cloud.com/releases/2.2.0/api_2.2.8/user/\n    *      listTemplatePermissions.html\n    * @param id\n    *           the template ID\n    * @param options\n    *           optional arguments\n    * @return the list of permissions that apply to the template\n    */\n   @Named(\"listTemplatePermissions\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listTemplatePermissions\", \"true\" })\n   @Unwrap\n   @Consumes(MediaType.APPLICATION_JSON)\n   Set<TemplatePermission> listTemplatePermissions(@QueryParam(\"id\") String id,\n         AccountInDomainOptions... options);\n\n   /**\n    * \n    * @see http \n    *      ://download.cloud.com/releases/2.2.0/api_2.2.8/user/extractTemplate\n    *      .html\n    * @param id\n    *           the ID of the template\n    * @param mode\n    *           FIXME the mode of extraction - HTTP_DOWNLOAD or FTP_UPLOAD\n    * @param zoneId\n    *           the ID of the zone where the ISO is originally located\n    * @param options\n    *           optional arguments\n    * @return an asynchronous job response\n    */\n   @Named(\"extractTemplate\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"extractTemplate\")\n   @Unwrap\n   @Consumes(MediaType.APPLICATION_JSON)\n   AsyncCreateResponse extractTemplate(@QueryParam(\"id\") String id,\n         @QueryParam(\"mode\") ExtractMode mode, @QueryParam(\"zoneid\") String zoneId, ExtractTemplateOptions... options);\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/features/VMGroupApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.cloudstack.domain.VMGroup;\nimport org.jclouds.cloudstack.filters.AuthenticationFilter;\nimport org.jclouds.cloudstack.options.CreateVMGroupOptions;\nimport org.jclouds.cloudstack.options.ListVMGroupsOptions;\nimport org.jclouds.cloudstack.options.UpdateVMGroupOptions;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.OnlyElement;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\n/**\n * Provides synchronous access to CloudStack VM group features.\n * <p/>\n *\n * @see <a href=\"http://download.cloud.com/releases/2.2.0/api_2.2.12/TOC_User.html\" />\n */\n@RequestFilters(AuthenticationFilter.class)\n@QueryParams(keys = \"response\", values = \"json\")\npublic interface VMGroupApi {\n   /**\n    * Lists VM groups\n    *\n    * @param options if present, how to constrain the list.\n    * @return VM groups matching query, or empty set, if no zones are found\n    */\n   @Named(\"listInstanceGroups\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listInstanceGroups\", \"true\" })\n   @SelectJson(\"instancegroup\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<VMGroup> listInstanceGroups(ListVMGroupsOptions... options);\n\n   /**\n    * @see VMGroupApi#getInstanceGroup\n    */\n   @Named(\"listInstanceGroups\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listInstanceGroups\", \"true\" })\n   @SelectJson(\"instancegroup\")\n   @OnlyElement\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   VMGroup getInstanceGroup(@QueryParam(\"id\") String id);\n\n   /**\n    * Creates a VM group\n    *\n    * @param name    the name of the VM group\n    * @param options optional parameters\n    * @return the new VMGroup\n    */\n   @Named(\"createInstanceGroup\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"createInstanceGroup\")\n   @SelectJson(\"instancegroup\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   VMGroup createInstanceGroup(@QueryParam(\"name\") String name, CreateVMGroupOptions... options);\n\n   /**\n    * Modify a VM group\n    *\n    * @param name the new name of the group\n    * @return the modified VMGroup\n    */\n   @Named(\"updateInstanceGroup\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"updateInstanceGroup\")\n   @SelectJson(\"instancegroup\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   VMGroup updateInstanceGroup(@QueryParam(\"id\") String id, UpdateVMGroupOptions... options);\n\n   /**\n    * Delete a VM group\n    *\n    * @param id the ID of the VM group\n    * @return a future with a void data type\n    */\n   @Named(\"deleteInstanceGroup\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"deleteInstanceGroup\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void deleteInstanceGroup(@QueryParam(\"id\") String id);\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/features/VirtualMachineApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.cloudstack.domain.AsyncCreateResponse;\nimport org.jclouds.cloudstack.domain.VirtualMachine;\nimport org.jclouds.cloudstack.filters.AuthenticationFilter;\nimport org.jclouds.cloudstack.options.AssignVirtualMachineOptions;\nimport org.jclouds.cloudstack.options.DeployVirtualMachineOptions;\nimport org.jclouds.cloudstack.options.ListVirtualMachinesOptions;\nimport org.jclouds.cloudstack.options.UpdateVirtualMachineOptions;\nimport org.jclouds.cloudstack.options.StopVirtualMachineOptions;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.OnlyElement;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\n/**\n * Provides synchronous access to cloudstack via their REST API.\n * <p/>\n * \n * @see <a href=\"http://download.cloud.com/releases/2.2.0/api_2.2.12/TOC_User.html\" />\n */\n@RequestFilters(AuthenticationFilter.class)\n@QueryParams(keys = \"response\", values = \"json\")\npublic interface VirtualMachineApi {\n\n   /**\n    * Lists VirtualMachines\n    * \n    * @param options\n    *           if present, how to constrain the list.\n    * @return VirtualMachines matching query, or empty set, if no\n    *         VirtualMachines are found\n    */\n   @Named(\"listVirtualMachines\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listVirtualMachines\", \"true\" })\n   @SelectJson(\"virtualmachine\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<VirtualMachine> listVirtualMachines(ListVirtualMachinesOptions... options);\n\n   /**\n    * get a specific VirtualMachine by id\n    * \n    * @param id\n    *           VirtualMachine to get\n    * @return VirtualMachine or null if not found\n    */\n   @Named(\"listVirtualMachines\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listVirtualMachines\", \"true\" })\n   @SelectJson(\"virtualmachine\")\n   @OnlyElement\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   VirtualMachine getVirtualMachine(@QueryParam(\"id\") String id);\n\n   /**\n    * Creates and automatically starts a virtual machine based on a service\n    * offering, disk offering, and template.\n    * \n    * @param zoneId\n    *           availability zone for the virtual machine\n    * @param serviceOfferingId\n    *           the ID of the service offering for the virtual machine\n    * @param templateId\n    *           the ID of the template for the virtual machine\n    * \n    * @return virtual machine\n    */\n   @Named(\"deployVirtualMachine\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"deployVirtualMachine\")\n   @SelectJson({ \"deployvirtualmachine\", \"deployvirtualmachineresponse\" })\n   @Consumes(MediaType.APPLICATION_JSON)\n   AsyncCreateResponse deployVirtualMachineInZone(@QueryParam(\"zoneid\") String zoneId,\n         @QueryParam(\"serviceofferingid\") String serviceOfferingId, @QueryParam(\"templateid\") String templateId,\n         DeployVirtualMachineOptions... options);\n\n   /**\n    * Reboots a virtual machine.\n    * \n    * @param id\n    *           The ID of the virtual machine\n    * @return job id related to destroying the VM\n    */\n   @Named(\"rebootVirtualMachine\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"rebootVirtualMachine\")\n   @SelectJson(\"jobid\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   String rebootVirtualMachine(@QueryParam(\"id\") String id);\n\n   /**\n    * Starts a virtual machine.\n    * \n    * @param id\n    *           The ID of the virtual machine\n    * @return job id related to destroying the VM\n    */\n   @Named(\"startVirtualMachine\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"startVirtualMachine\")\n   @SelectJson(\"jobid\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   String startVirtualMachine(@QueryParam(\"id\") String id);\n\n   /**\n    * Stops a virtual machine.\n    * \n    * @param id\n    *           The ID of the virtual machine\n    * @return job id related to destroying the VM\n    */\n   @Named(\"stopVirtualMachine\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"stopVirtualMachine\")\n   @SelectJson(\"jobid\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   String stopVirtualMachine(@QueryParam(\"id\") String id);\n\n   /**\n    * Stops a virtual machine.\n    * \n    * @param id\n    *           The ID of the virtual machine\n    * @param options\n    *           If present, whether to force stop.\n    * @return job id related to destroying the VM\n    */\n   @GET\n   @QueryParams(keys = \"command\", values = \"stopVirtualMachine\")\n   @SelectJson(\"jobid\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   String stopVirtualMachine(@QueryParam(\"id\") String id,\n                                               StopVirtualMachineOptions options);\n\n   /**\n    * Resets the password for virtual machine. The virtual machine must be in a\n    * \"Stopped\" state and the template must already support this feature for\n    * this command to take effect.\n    * \n    * @param id\n    *           The ID of the virtual machine\n    * @return job id related to destroying the VM\n    */\n   @Named(\"resetPasswordForVirtualMachine\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"resetPasswordForVirtualMachine\")\n   @SelectJson(\"jobid\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   String resetPasswordForVirtualMachine(@QueryParam(\"id\") String id);\n\n   /**\n    * Return an encrypted password for the virtual machine. The command\n    * is asynchronous.\n    *\n    * @param id\n    *          the ID of the virtual machine\n    * @return encrypted password\n    */\n   @Named(\"getVMPassword\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"getVMPassword\")\n   @SelectJson(\"encryptedpassword\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   String getEncryptedPasswordForVirtualMachine(@QueryParam(\"id\") String id);\n\n   /**\n    * Changes the service offering for a virtual machine. The virtual machine\n    * must be in a \"Stopped\" state for this command to take effect.\n    * \n    * @param id\n    *           The ID of the virtual machine\n    * @param serviceOfferingId\n    *           The service offering ID to apply to the virtual machine\n    * @return job id related to destroying the VM\n    */\n   @Named(\"changeServiceForVirtualMachine\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"changeServiceForVirtualMachine\")\n   @SelectJson(\"jobid\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   String changeServiceForVirtualMachine(@QueryParam(\"id\") String id,\n                                         @QueryParam(\"serviceofferingid\") String serviceOfferingId);\n\n   /**\n    * Updates parameters of a virtual machine.\n    * \n    * @param id\n    *           The ID of the virtual machine\n    * @return job id related to destroying the VM\n    */\n   @Named(\"updateVirtualMachine\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"updateVirtualMachine\")\n   @SelectJson(\"jobid\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   String updateVirtualMachine(@QueryParam(\"id\") String id,\n                               UpdateVirtualMachineOptions options);\n\n   /**\n    * Destroys a virtual machine. Once destroyed, only the administrator can\n    * recover it.\n    * \n    * @param id\n    *           vm to destroy\n    * @return job id related to destroying the VM, or null if resource was not\n    *         found\n    */\n   @Named(\"destroyVirtualMachine\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"destroyVirtualMachine\")\n   @SelectJson(\"jobid\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   String destroyVirtualMachine(@QueryParam(\"id\") String id);\n\n   /**\n    * Re-assign a virtual machine to a different account/domain.\n    * \n    * @param virtualMachineId\n    *           VirtualMachine to re-assign\n    * @param options\n    *           AssignVirtualMachineOptions specifying account and domain to transfer to, and optional network and security group IDs.\n    * @return VirtualMachine or null if not found\n    */\n   @Named(\"assignVirtualMachine\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"assignVirtualMachine\")\n   @SelectJson(\"jobid\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   VirtualMachine assignVirtualMachine(@QueryParam(\"virtualmachineid\") String virtualMachineId,\n                                                         AssignVirtualMachineOptions... options);\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/features/VolumeApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.cloudstack.domain.AsyncCreateResponse;\nimport org.jclouds.cloudstack.domain.Volume;\nimport org.jclouds.cloudstack.filters.AuthenticationFilter;\nimport org.jclouds.cloudstack.options.ListVolumesOptions;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.OnlyElement;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.Unwrap;\n\n/**\n * Provides synchronous access to cloudstack via their REST API.\n * <p/>\n *\n * @see <a href=\"http://download.cloud.com/releases/2.2.0/api_2.2.12/TOC_User.html\" />\n */\n@RequestFilters(AuthenticationFilter.class)\n@QueryParams(keys = \"response\", values = \"json\")\npublic interface VolumeApi {\n   /**\n    * List volumes\n    *\n    * @return volume list, empty if not found\n    */\n   @Named(\"listVolumes\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listVolumes\", \"true\" })\n   @SelectJson(\"volume\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<Volume> listVolumes(ListVolumesOptions... options);\n\n   /**\n    * Get volume by id\n    *\n    * @param id the volume id to retrieve\n    * @return volume or null if not found\n    */\n   @Named(\"listVolumes\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listVolumes\", \"true\" })\n   @SelectJson(\"volume\")\n   @OnlyElement\n   @Fallback(NullOnNotFoundOr404.class)\n   Volume getVolume(@QueryParam(\"id\") String id);\n\n\n   /**\n    * Create a volume with given name and diskOfferingId\n    *\n    * @param name           name of the volume\n    * @param diskOfferingId the ID of the disk offering.\n    * @param zoneId         the ID of the availability zone\n    * @return AsyncCreateResponse job response used to track creation\n    */\n   @Named(\"createVolume\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"createVolume\")\n   @Unwrap\n   @Consumes(MediaType.APPLICATION_JSON)\n   AsyncCreateResponse createVolumeFromDiskOfferingInZone(@QueryParam(\"name\") String name,\n                                                                            @QueryParam(\"diskofferingid\") String diskOfferingId,\n                                                                            @QueryParam(\"zoneid\") String zoneId);\n\n   /**\n    * Create a volume with given name, size and diskOfferingId\n    *\n    * @param name           name of the volume\n    * @param diskOfferingId the ID of the disk offering (the offering should have the custom disk size flag set)\n    * @param zoneId         the ID of the availability zone\n    * @param size           the size of volume required (in GB)\n    * @return AsyncCreateResponse job response used to track creation\n    */\n   @GET\n   @QueryParams(keys = \"command\", values = \"createVolume\")\n   @Unwrap\n   @Consumes(MediaType.APPLICATION_JSON)\n   AsyncCreateResponse createVolumeFromCustomDiskOfferingInZone(@QueryParam(\"name\") String name,\n                                                                            @QueryParam(\"diskofferingid\") String diskOfferingId,\n                                                                            @QueryParam(\"zoneid\") String zoneId,\n                                                                            @QueryParam(\"size\") int size);\n\n   /**\n    * Create a volume with given name and snapshotId\n    *\n    * @param name       name of the volume\n    * @param snapshotId Snapshot id to be used while creating the volume\n    * @param zoneId     the ID of the availability zone\n    * @return AsyncCreateResponse job response used to track creation\n    */\n   @Named(\"createVolume\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"createVolume\")\n   @Unwrap\n   @Consumes(MediaType.APPLICATION_JSON)\n   AsyncCreateResponse createVolumeFromSnapshotInZone(@QueryParam(\"name\") String name,\n                                                                        @QueryParam(\"snapshotid\") String snapshotId,\n                                                                        @QueryParam(\"zoneid\") String zoneId);\n\n   /**\n    * Attaches a disk volume to a virtual machine.\n    *\n    * @param volumeId         the ID of the disk volume\n    * @param virtualMachineId the ID of the virtual machine\n    * @return AsyncCreateResponse job response used to track creation\n    */\n   @Named(\"attachVolume\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"attachVolume\")\n   @Unwrap\n   @Consumes(MediaType.APPLICATION_JSON)\n   AsyncCreateResponse attachVolume(@QueryParam(\"id\") String volumeId,\n                                                      @QueryParam(\"virtualmachineid\") String virtualMachineId);\n\n   /**\n    * Detaches a disk volume from a virtual machine.\n    *\n    * @param volumeId         the ID of the disk volume\n    * @return AsyncCreateResponse job response used to track creation\n    */\n   @Named(\"detachVolume\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"detachVolume\")\n   @Unwrap\n   @Consumes(MediaType.APPLICATION_JSON)\n   AsyncCreateResponse detachVolume(@QueryParam(\"id\") String volumeId);\n\n   /**\n    * Deletes a detached disk volume\n    *\n    * @param id id of the volume\n    */\n   @Named(\"deleteVolume\")\n   @GET\n   @QueryParams(keys = \"command\", values = \"deleteVolume\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void deleteVolume(@QueryParam(\"id\") String id);\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/features/ZoneApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.cloudstack.domain.Zone;\nimport org.jclouds.cloudstack.filters.AuthenticationFilter;\nimport org.jclouds.cloudstack.options.ListZonesOptions;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.OnlyElement;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\n/**\n * Provides synchronous access to cloudstack via their REST API.\n * <p/>\n * \n * @see <a href=\"http://download.cloud.com/releases/2.2.0/api_2.2.12/TOC_User.html\" />\n */\n@RequestFilters(AuthenticationFilter.class)\n@QueryParams(keys = \"response\", values = \"json\")\npublic interface ZoneApi {\n\n   /**\n    * Lists zones\n    * \n    * @param options\n    *           if present, how to constrain the list.\n    * @return zones matching query, or empty set, if no zones are found\n    */\n   @Named(\"listZones\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listZones\", \"true\" })\n   @SelectJson(\"zone\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<Zone> listZones(ListZonesOptions... options);\n\n   /**\n    * get a specific zone by id\n    * \n    * @param id\n    *           zone to get\n    * @return zone or null if not found\n    */\n   @Named(\"listZones\")\n   @GET\n   @QueryParams(keys = { \"command\", \"listAll\" }, values = { \"listZones\", \"true\" })\n   @SelectJson(\"zone\")\n   @OnlyElement\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   Zone getZone(@QueryParam(\"id\") String id);\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/filters/AddSessionKeyAndJSessionIdToRequest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.filters;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.cloudstack.domain.LoginResponse;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpRequest.Builder;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.net.HttpHeaders;\n\n/**\n * \n * @see <a href=\"http://docs.cloud.com/CloudStack_Documentation/Customizing_the_CloudStack_UI#Cross_Site_Request_Forgery_%28CSRF%29\"\n *      />\n */\n@Singleton\npublic class AddSessionKeyAndJSessionIdToRequest implements AuthenticationFilter {\n\n   private final Supplier<LoginResponse> loginResponseSupplier;\n\n   @Inject\n   public AddSessionKeyAndJSessionIdToRequest(Supplier<LoginResponse> loginResponseSupplier) {\n      this.loginResponseSupplier = loginResponseSupplier;\n   }\n\n   @Override\n   public HttpRequest filter(HttpRequest request) throws HttpException {\n      LoginResponse loginResponse = loginResponseSupplier.get();\n      Builder<?> builder = request.toBuilder();\n      builder.replaceHeader(HttpHeaders.COOKIE, \"JSESSIONID=\" + loginResponse.getJSessionId());\n      builder.replaceQueryParam(\"sessionkey\", loginResponse.getSessionKey());\n      return builder.build();\n\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/filters/AuthenticationFilter.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.filters;\n\nimport org.jclouds.http.HttpRequestFilter;\n\nimport com.google.inject.ImplementedBy;\n\n/**\n * Marker interface that determines how we authenticate http requests in cloudstack. default to sign\n * requests as opposed to login.\n */\n@ImplementedBy(QuerySigner.class)\npublic interface AuthenticationFilter extends HttpRequestFilter {\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/filters/QuerySigner.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.filters;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Throwables.propagate;\nimport static com.google.common.io.BaseEncoding.base64;\nimport static com.google.common.io.ByteStreams.readBytes;\nimport static org.jclouds.Constants.LOGGER_SIGNATURE;\nimport static org.jclouds.crypto.Macs.asByteProcessor;\nimport static org.jclouds.http.Uris.uriBuilder;\nimport static org.jclouds.http.utils.Queries.queryParser;\nimport static org.jclouds.util.Strings2.toInputStream;\n\nimport java.io.IOException;\nimport java.security.InvalidKeyException;\nimport java.util.Map;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport com.google.common.base.Joiner;\nimport org.jclouds.crypto.Crypto;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpUtils;\nimport org.jclouds.http.internal.SignatureWire;\nimport org.jclouds.location.Provider;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.rest.RequestSigner;\nimport org.jclouds.util.Strings2;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSortedSet;\nimport com.google.common.collect.Multimap;\nimport com.google.common.io.ByteProcessor;\n\n/**\n * \n * @see <a href= \"http://download.cloud.com/releases/2.2.0/api/user/2.2api_security_details.html\" />\n */\n@Singleton\npublic class QuerySigner implements AuthenticationFilter, RequestSigner {\n\n   private final SignatureWire signatureWire;\n   private final Supplier<Credentials> creds;\n   private final Crypto crypto;\n   private final HttpUtils utils;\n\n   @Resource\n   @Named(LOGGER_SIGNATURE)\n   private Logger signatureLog = Logger.NULL;\n\n   @Inject\n   public QuerySigner(SignatureWire signatureWire, @Provider Supplier<Credentials> creds, Crypto crypto, HttpUtils utils) {\n      this.signatureWire = signatureWire;\n      this.creds = creds;\n      this.crypto = crypto;\n      this.utils = utils;\n   }\n\n   public HttpRequest filter(HttpRequest request) throws HttpException {\n      checkNotNull(request, \"request must be present\");\n      Multimap<String, String> decodedParams = queryParser().apply(request.getEndpoint().getRawQuery());\n      addSigningParams(decodedParams);\n      String stringToSign = createStringToSign(request, decodedParams);\n      String signature = sign(stringToSign);\n      addSignature(decodedParams, signature);\n      request = request.toBuilder().endpoint(uriBuilder(request.getEndpoint()).query(decodedParams).build()).build();\n      utils.logRequest(signatureLog, request, \"<<\");\n      return request;\n   }\n\n   @VisibleForTesting\n   void addSignature(Multimap<String, String> params, String signature) {\n      params.replaceValues(\"signature\", ImmutableList.of(signature));\n   }\n\n   @VisibleForTesting\n   public String sign(String toSign) {\n      String signature;\n      try {\n         ByteProcessor<byte[]> hmacSHA1 = asByteProcessor(crypto.hmacSHA1(creds.get().credential.getBytes()));\n         signature = base64().encode(readBytes(toInputStream(toSign), hmacSHA1));\n         if (signatureWire.enabled())\n            signatureWire.input(toInputStream(signature));\n         return signature;\n      } catch (InvalidKeyException e) {\n         throw propagate(e);\n      } catch (IOException e) {\n         throw propagate(e);\n      }\n   }\n\n   @VisibleForTesting\n   public String createStringToSign(HttpRequest request, Multimap<String, String> decodedParams) {\n      utils.logRequest(signatureLog, request, \">>\");\n      // encode each parameter value first,\n      ImmutableSortedSet.Builder<String> builder = ImmutableSortedSet.naturalOrder();\n      for (Map.Entry<String, String> entry : decodedParams.entries())\n         builder.add(entry.getKey() + \"=\" + Strings2.urlEncode(entry.getValue()));\n      // then, lower case the entire query string\n      String stringToSign = Joiner.on('&').join(builder.build()).toLowerCase();\n      if (signatureWire.enabled())\n         signatureWire.output(stringToSign);\n\n      return stringToSign;\n   }\n\n   @VisibleForTesting\n   void addSigningParams(Multimap<String, String> params) {\n      params.replaceValues(\"apiKey\", ImmutableList.of(creds.get().identity));\n      params.removeAll(\"signature\");\n   }\n\n   public String createStringToSign(HttpRequest input) {\n      Multimap<String, String> decodedParams = queryParser().apply(input.getEndpoint().getQuery());\n      addSigningParams(decodedParams);\n      return createStringToSign(input, decodedParams);\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/functions/CloudStackFallbacks.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.Fallbacks.valOnNotFoundOr404;\nimport static org.jclouds.util.Throwables2.getFirstThrowableOfType;\n\nimport org.jclouds.Fallback;\n\npublic final class CloudStackFallbacks {\n   private CloudStackFallbacks() {\n   }\n\n   /**\n    * CloudStack is currently sending 431 errors with the text \"Unable to find account owner for ip \". In this case, we\n    * have to ignore as there's no means for us to avoid the problem, or action to take.\n    */\n   public static final class VoidOnNotFoundOr404OrUnableToFindAccountOwner implements Fallback<Void> {\n      @Override\n      public Void createOrPropagate(Throwable t) throws Exception {\n         IllegalStateException e = getFirstThrowableOfType(checkNotNull(t, \"throwable\"), IllegalStateException.class);\n         if (e != null && e.getMessage().indexOf(\"Unable to find account owner for\") != -1) {\n            return null;\n         } else {\n            return valOnNotFoundOr404(null, t);\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/functions/CreateFirewallRulesForIP.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\n\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.cloudstack.CloudStackApi;\nimport org.jclouds.cloudstack.domain.AsyncCreateResponse;\nimport org.jclouds.cloudstack.domain.FirewallRule;\nimport org.jclouds.cloudstack.domain.PublicIPAddress;\nimport org.jclouds.cloudstack.options.CreateFirewallRuleOptions;\nimport org.jclouds.cloudstack.strategy.BlockUntilJobCompletesAndReturnResult;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.ImmutableSet.Builder;\n\n@Singleton\npublic class CreateFirewallRulesForIP {\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   private final CloudStackApi client;\n   private final BlockUntilJobCompletesAndReturnResult blockUntilJobCompletesAndReturnResult;\n   private final LoadingCache<String, Set<FirewallRule>> getFirewallRulesByVirtualMachine;\n\n   @Inject\n   public CreateFirewallRulesForIP(CloudStackApi client,\n         BlockUntilJobCompletesAndReturnResult blockUntilJobCompletesAndReturnResult,\n         LoadingCache<String, Set<FirewallRule>> getFirewallRulesByVirtualMachine) {\n      this.client = checkNotNull(client, \"client\");\n      this.blockUntilJobCompletesAndReturnResult = checkNotNull(blockUntilJobCompletesAndReturnResult,\n            \"blockUntilJobCompletesAndReturnResult\");\n      this.getFirewallRulesByVirtualMachine = checkNotNull(getFirewallRulesByVirtualMachine,\n            \"getFirewallRulesByVirtualMachine\");\n   }\n\n   public Set<FirewallRule> apply(PublicIPAddress ip, Iterable<Integer> ports) {\n      return apply(ip, \"tcp\", ports);\n   }\n\n   public Set<FirewallRule> apply(PublicIPAddress ip, String protocol, Iterable<Integer> ports) {\n      checkState(ip.getVirtualMachineId() != null,\n            \"ip %s should be static NATed to a virtual machine before applying rules\", ip);\n      if (Iterables.isEmpty(ports))\n         return ImmutableSet.<FirewallRule> of();\n      Builder<AsyncCreateResponse> responses = ImmutableSet.builder();\n      for (int port : ports) {\n          AsyncCreateResponse response = client.getFirewallApi().createFirewallRuleForIpAndProtocol(ip.getId(), FirewallRule.Protocol.fromValue(protocol),\n                                                                                                       CreateFirewallRuleOptions.Builder.startPort(port).endPort(port));\n         logger.debug(\">> creating firewall rule IPAddress(%s) for protocol(%s), port(%s); response(%s)\",\n               ip.getId(), protocol, port, response);\n         responses.add(response);\n      }\n      Builder<FirewallRule> rules = ImmutableSet.builder();\n      for (AsyncCreateResponse response : responses.build()) {\n         FirewallRule rule = blockUntilJobCompletesAndReturnResult.<FirewallRule> apply(response);\n         rules.add(rule);\n         getFirewallRulesByVirtualMachine.asMap().put(ip.getVirtualMachineId(), ImmutableSet.of(rule));\n      }\n      return rules.build();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/functions/CreatePortForwardingRulesForIP.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\n\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.cloudstack.CloudStackApi;\nimport org.jclouds.cloudstack.domain.AsyncCreateResponse;\nimport org.jclouds.cloudstack.domain.IPForwardingRule;\nimport org.jclouds.cloudstack.domain.PublicIPAddress;\nimport org.jclouds.cloudstack.strategy.BlockUntilJobCompletesAndReturnResult;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.ImmutableSet.Builder;\n\n@Singleton\npublic class CreatePortForwardingRulesForIP {\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   private final CloudStackApi client;\n   private final BlockUntilJobCompletesAndReturnResult blockUntilJobCompletesAndReturnResult;\n   private final LoadingCache<String, Set<IPForwardingRule>> getIPForwardingRulesByVirtualMachine;\n\n   @Inject\n   public CreatePortForwardingRulesForIP(CloudStackApi client,\n         BlockUntilJobCompletesAndReturnResult blockUntilJobCompletesAndReturnResult,\n         LoadingCache<String, Set<IPForwardingRule>> getIPForwardingRulesByVirtualMachine) {\n      this.client = checkNotNull(client, \"client\");\n      this.blockUntilJobCompletesAndReturnResult = checkNotNull(blockUntilJobCompletesAndReturnResult,\n            \"blockUntilJobCompletesAndReturnResult\");\n      this.getIPForwardingRulesByVirtualMachine = checkNotNull(getIPForwardingRulesByVirtualMachine,\n            \"getIPForwardingRulesByVirtualMachine\");\n   }\n\n   public Set<IPForwardingRule> apply(PublicIPAddress ip, Iterable<Integer> ports) {\n      return apply(ip, \"tcp\", ports);\n   }\n\n   public Set<IPForwardingRule> apply(PublicIPAddress ip, String protocol, Iterable<Integer> ports) {\n      checkState(ip.getVirtualMachineId() != null,\n            \"ip %s should be static NATed to a virtual machine before applying rules\", ip);\n      if (Iterables.isEmpty(ports))\n         return ImmutableSet.<IPForwardingRule> of();\n      Builder<AsyncCreateResponse> responses = ImmutableSet.builder();\n      for (int port : ports) {\n         AsyncCreateResponse response = client.getNATApi().createIPForwardingRule(ip.getId(), protocol, port);\n         logger.debug(\">> creating IP forwarding rule IPAddress(%s) for protocol(%s), port(%s); response(%s)\",\n               ip.getId(), protocol, port, response);\n         responses.add(response);\n      }\n      Builder<IPForwardingRule> rules = ImmutableSet.builder();\n      for (AsyncCreateResponse response : responses.build()) {\n         IPForwardingRule rule = blockUntilJobCompletesAndReturnResult.<IPForwardingRule> apply(response);\n         rules.add(rule);\n         getIPForwardingRulesByVirtualMachine.asMap().put(ip.getVirtualMachineId(), ImmutableSet.of(rule));\n      }\n      return rules.build();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/functions/CreateSecurityGroupIfNeeded.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.functions;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.cloudstack.predicates.SecurityGroupPredicates.portInRangeForCidr;\nimport static org.jclouds.cloudstack.predicates.ZonePredicates.supportsSecurityGroups;\n\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.cloudstack.CloudStackApi;\nimport org.jclouds.cloudstack.domain.SecurityGroup;\nimport org.jclouds.cloudstack.domain.Zone;\nimport org.jclouds.cloudstack.domain.ZoneSecurityGroupNamePortsCidrs;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableSet;\n\n@Singleton\npublic class CreateSecurityGroupIfNeeded implements Function<ZoneSecurityGroupNamePortsCidrs, SecurityGroup> {\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n   protected final CloudStackApi client;\n   protected final Supplier<LoadingCache<String, Zone>> zoneIdToZone;\n   protected final Predicate<String> jobComplete;\n\n   @Inject\n   public CreateSecurityGroupIfNeeded(CloudStackApi client,\n                                      Predicate<String> jobComplete,\n                                      Supplier<LoadingCache<String, Zone>> zoneIdToZone) {\n      this.client = checkNotNull(client, \"client\");\n      this.jobComplete = checkNotNull(jobComplete, \"jobComplete\");\n      this.zoneIdToZone = zoneIdToZone;\n   }\n\n   @Override\n   public SecurityGroup apply(ZoneSecurityGroupNamePortsCidrs input) {\n      checkNotNull(input, \"input\");\n\n      String zoneId = input.getZone();\n      Zone zone = zoneIdToZone.get().getUnchecked(zoneId);\n\n      checkArgument(supportsSecurityGroups().apply(zone),\n                    \"Security groups are required, but the zone %s does not support security groups\", zoneId);\n      logger.debug(\">> creating securityGroup %s\", input);\n      try {\n\n         SecurityGroup securityGroup = client.getSecurityGroupApi().createSecurityGroup(input.getName());\n\n         logger.debug(\"<< created securityGroup(%s)\", securityGroup);\n         ImmutableSet<String> cidrs;\n         if (!input.getCidrs().isEmpty()) {\n            cidrs = ImmutableSet.copyOf(input.getCidrs());\n         } else {\n            cidrs = ImmutableSet.of(\"0.0.0.0/0\");\n         }\n         for (int port : input.getPorts()) {\n            authorizeGroupToItselfAndToTCPPortAndCidr(client, securityGroup, port, cidrs);\n         }\n         return securityGroup;\n      } catch (IllegalStateException e) {\n         logger.trace(\"<< trying to find securityGroup(%s): %s\", input, e.getMessage());\n         SecurityGroup group = client.getSecurityGroupApi().getSecurityGroupByName(input.getName());\n         logger.debug(\"<< reused securityGroup(%s)\", group.getId());\n         return group;\n      }\n   }\n\n   private void authorizeGroupToItselfAndToTCPPortAndCidr(CloudStackApi client,\n                                                          SecurityGroup securityGroup,\n                                                          int port,\n                                                          Set<String> cidrs) {\n      for (String cidr : cidrs) {\n         logger.debug(\">> authorizing securityGroup(%s) permission to %s on port %d\", securityGroup, cidr, port);\n         if (!portInRangeForCidr(port, cidr).apply(securityGroup)) {\n            jobComplete.apply(client.getSecurityGroupApi().authorizeIngressPortsToCIDRs(securityGroup.getId(),\n                                                                                           \"TCP\",\n                                                                                           port,\n                                                                                           port,\n                                                                                           ImmutableSet.of(cidr)));\n            logger.debug(\"<< authorized securityGroup(%s) permission to %s on port %d\", securityGroup, cidr, port);\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/functions/DateToYyyyMmDd.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.functions;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\n\nimport com.google.common.base.Function;\n\n/**\n * Convert a Date object into a \"yyyy-MM-dd\" String\n */\npublic class DateToYyyyMmDd implements Function<Object, String> {\n\n   public String apply(Object input) {\n      checkNotNull(input, \"input cannot be null\");\n      checkArgument(input instanceof Date, \"input must be a Date\");\n\n      return new SimpleDateFormat(\"yyyy-MM-dd\").format((Date)input);\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/functions/GetFirewallRulesByVirtualMachine.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.collect.ImmutableSet;\nimport java.util.Set;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\nimport org.jclouds.cloudstack.CloudStackApi;\nimport org.jclouds.cloudstack.domain.FirewallRule;\nimport org.jclouds.cloudstack.options.ListFirewallRulesOptions;\n\n@Singleton\npublic class GetFirewallRulesByVirtualMachine extends CacheLoader<String, Set<FirewallRule>> {\n   private final CloudStackApi client;\n\n   @Inject\n   public GetFirewallRulesByVirtualMachine(CloudStackApi client) {\n      this.client = checkNotNull(client, \"client\");\n   }\n\n   /**\n    * @throws org.jclouds.rest.ResourceNotFoundException\n    *          when there is no ip forwarding rule available for the VM\n    */\n   @Override\n   public Set<FirewallRule> load(String input) {\n      String publicIPId = client.getVirtualMachineApi().getVirtualMachine(input).getPublicIPId();\n      Set<FirewallRule> rules = client.getFirewallApi()\n         .listFirewallRules(ListFirewallRulesOptions.Builder.ipAddressId(publicIPId));\n      return rules != null ? rules : ImmutableSet.<FirewallRule>of();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/functions/GetIPForwardingRulesByVirtualMachine.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.cloudstack.CloudStackApi;\nimport org.jclouds.cloudstack.domain.IPForwardingRule;\n\nimport com.google.common.cache.CacheLoader;\n\n@Singleton\npublic class GetIPForwardingRulesByVirtualMachine extends CacheLoader<String, Set<IPForwardingRule>> {\n   private final CloudStackApi client;\n\n   @Inject\n   public GetIPForwardingRulesByVirtualMachine(CloudStackApi client) {\n      this.client = checkNotNull(client, \"client\");\n   }\n\n   /**\n    * @throws org.jclouds.rest.ResourceNotFoundException\n    *          when there is no ip forwarding rule available for the VM\n    */\n   @Override\n   public Set<IPForwardingRule> load(String input) {\n      return client.getNATApi().getIPForwardingRulesForVirtualMachine(input);\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/functions/ParseAsyncJobFromHttpResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.cloudstack.domain.AsyncJob;\nimport org.jclouds.domain.JsonBall;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.UnwrapOnlyJsonValue;\n\nimport com.google.common.base.Function;\nimport com.google.inject.Inject;\n\n@Singleton\npublic class ParseAsyncJobFromHttpResponse implements Function<HttpResponse, AsyncJob<?>> {\n   private final UnwrapOnlyJsonValue<AsyncJob<Map<String, JsonBall>>> parser;\n   private final ParseTypedAsyncJob parseTyped;\n\n   @Inject\n   public ParseAsyncJobFromHttpResponse(ParseTypedAsyncJob parseTyped,\n         UnwrapOnlyJsonValue<AsyncJob<Map<String, JsonBall>>> parser) {\n      this.parseTyped = checkNotNull(parseTyped, \"parseTyped\");\n      this.parser = checkNotNull(parser, \"parser\");\n   }\n\n   public AsyncJob<?> apply(HttpResponse response) {\n      checkNotNull(response, \"response\");\n      AsyncJob<Map<String, JsonBall>> toParse = parser.apply(response);\n      checkNotNull(toParse, \"parsed result from %s\", response);\n      return parseTyped.apply(toParse);\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/functions/ParseAsyncJobsFromHttpResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.cloudstack.domain.AsyncJob;\nimport org.jclouds.domain.JsonBall;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseFirstJsonValueNamed;\nimport org.jclouds.json.internal.GsonWrapper;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.inject.Inject;\nimport com.google.inject.TypeLiteral;\n\n@Singleton\npublic class ParseAsyncJobsFromHttpResponse implements Function<HttpResponse, Set<AsyncJob<?>>> {\n   private final ParseFirstJsonValueNamed<Set<AsyncJob<Map<String, JsonBall>>>> parser;\n   private final ParseTypedAsyncJob parseTyped;\n\n   @Inject\n   public ParseAsyncJobsFromHttpResponse(ParseTypedAsyncJob parseTyped, GsonWrapper gsonView) {\n      this.parseTyped = checkNotNull(parseTyped, \"parseTyped\");\n      this.parser = new ParseFirstJsonValueNamed<Set<AsyncJob<Map<String, JsonBall>>>>(\n         checkNotNull(gsonView, \"gsonView\"),\n         new TypeLiteral<Set<AsyncJob<Map<String, JsonBall>>>>() { },\n         \"asyncjobs\");\n   }\n\n   public Set<AsyncJob<?>> apply(HttpResponse response) {\n      checkNotNull(response, \"response\");\n      Set<AsyncJob<Map<String, JsonBall>>> toParse = parser.apply(response);\n      checkNotNull(toParse, \"parsed result from %s\", response);\n      return ImmutableSet.copyOf(Iterables.transform(toParse, parseTyped));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/functions/ParseEventTypesFromHttpResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Set;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseFirstJsonValueNamed;\nimport org.jclouds.json.internal.GsonWrapper;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\nimport com.google.inject.Inject;\nimport com.google.inject.TypeLiteral;\n\n@Singleton\npublic class ParseEventTypesFromHttpResponse implements Function<HttpResponse, Set<String>> {\n   private final ParseFirstJsonValueNamed<Set<EventType>> parser;\n\n   private static class EventType {\n      private String name;\n\n       @Override\n       public boolean equals(Object o) {\n           if (this == o) return true;\n           if (o == null || getClass() != o.getClass()) return false;\n           \n           EventType that = (EventType) o;\n           \n           if (!Objects.equal(name, that.name)) return false;\n           \n           return true;\n       }\n       \n       @Override\n       public int hashCode() {\n           return Objects.hashCode(name);\n       }\n   }\n\n   @Inject\n   public ParseEventTypesFromHttpResponse(GsonWrapper gsonView) {\n      this.parser = new ParseFirstJsonValueNamed<Set<EventType>>(checkNotNull(gsonView, \"gsonView\"),\n            new TypeLiteral<Set<EventType>>() {\n            }, \"eventtype\");\n   }\n\n   public Set<String> apply(HttpResponse response) {\n      checkNotNull(response, \"response\");\n      Set<EventType> toParse = parser.apply(response);\n      checkNotNull(toParse, \"parsed result from %s\", response);\n      Builder<String> builder = ImmutableSet.builder();\n      for (EventType entry : toParse)\n         builder.add(entry.name);\n      return builder.build();\n   }\n}\n\n\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/functions/ParseIdToNameEntryFromHttpResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpResponse;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.Iterables;\nimport com.google.inject.Inject;\n\n@Singleton\npublic class ParseIdToNameEntryFromHttpResponse implements Function<HttpResponse, Map.Entry<String, String>> {\n   private final ParseIdToNameFromHttpResponse parser;\n\n   @Inject\n   public ParseIdToNameEntryFromHttpResponse(ParseIdToNameFromHttpResponse parser) {\n      this.parser = checkNotNull(parser, \"parser\");\n   }\n\n   public Map.Entry<String, String> apply(HttpResponse response) {\n      checkNotNull(response, \"response\");\n      Map<String, String> toParse = parser.apply(response);\n      checkNotNull(toParse, \"parsed result from %s\", response);\n      return Iterables.getFirst(toParse.entrySet(), null);\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/functions/ParseIdToNameFromHttpResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseFirstJsonValueNamed;\nimport org.jclouds.json.internal.GsonWrapper;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ImmutableSortedMap;\nimport com.google.common.collect.ImmutableMap.Builder;\nimport com.google.inject.Inject;\nimport com.google.inject.TypeLiteral;\n\n@Singleton\npublic class ParseIdToNameFromHttpResponse implements Function<HttpResponse, Map<String, String>> {\n   private final ParseFirstJsonValueNamed<Set<IdName>> parser;\n\n   private static class IdName {\n      private String id;\n      private String name;\n\n       @Override\n       public boolean equals(Object o) {\n           if (this == o) return true;\n           if (o == null || getClass() != o.getClass()) return false;\n           \n           IdName that = (IdName) o;\n           \n           if (!Objects.equal(id, that.id)) return false;\n           if (!Objects.equal(name, that.name)) return false;\n           \n           return true;\n       }\n       \n       @Override\n       public int hashCode() {\n           return Objects.hashCode(id, name);\n       }\n   }\n\n   @Inject\n   public ParseIdToNameFromHttpResponse(GsonWrapper gsonView) {\n      this.parser = new ParseFirstJsonValueNamed<Set<IdName>>(checkNotNull(gsonView, \"gsonView\"),\n            new TypeLiteral<Set<IdName>>() {\n            }, \"oscategory\");\n   }\n\n   public Map<String, String> apply(HttpResponse response) {\n      checkNotNull(response, \"response\");\n      Set<IdName> toParse = parser.apply(response);\n      checkNotNull(toParse, \"parsed result from %s\", response);\n      Builder<String, String> builder = ImmutableSortedMap.naturalOrder();\n      for (IdName entry : toParse)\n         builder.put(entry.id, entry.name);\n      return builder.build();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/functions/ParseLoginResponseFromHttpResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.get;\nimport static com.google.common.collect.Iterables.getOnlyElement;\n\nimport org.jclouds.cloudstack.domain.LoginResponse;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseFirstJsonValueNamed;\nimport org.jclouds.json.internal.GsonWrapper;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Splitter;\nimport com.google.inject.Inject;\nimport com.google.inject.TypeLiteral;\n\npublic class ParseLoginResponseFromHttpResponse implements Function<HttpResponse, LoginResponse> {\n\n   private ParseFirstJsonValueNamed<LoginResponse> parser;\n\n   @Inject\n   ParseLoginResponseFromHttpResponse(GsonWrapper gson) {\n      this.parser = new ParseFirstJsonValueNamed<LoginResponse>(checkNotNull(gson, \"gsonView\"),\n         new TypeLiteral<LoginResponse>(){}, \"loginresponse\");\n   }\n\n   @Override\n   public LoginResponse apply(HttpResponse response) {\n      checkNotNull(response, \"response\");\n\n      LoginResponse login =  parser.apply(response);\n      checkNotNull(login, \"loginResponse\");\n\n      String jSessionId = get(Splitter.on(\"=\").split(get(Splitter.on(\";\").trimResults().split(\n         getOnlyElement(response.getHeaders().get(\"Set-Cookie\"))), 0)), 1);\n      \n      return LoginResponse.builder().fromLoginResponse(login).jSessionId(jSessionId).build();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/functions/ParseNamesFromHttpResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Set;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseFirstJsonValueNamed;\nimport org.jclouds.json.internal.GsonWrapper;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\nimport com.google.inject.Inject;\nimport com.google.inject.TypeLiteral;\n\n@Singleton\npublic class ParseNamesFromHttpResponse implements Function<HttpResponse, Set<String>> {\n   private final ParseFirstJsonValueNamed<Set<Name>> parser;\n\n   private static class Name {\n      private String name;\n\n       @Override\n       public boolean equals(Object o) {\n           if (this == o) return true;\n           if (o == null || getClass() != o.getClass()) return false;\n           \n           Name that = (Name) o;\n           \n           if (!Objects.equal(name, that.name)) return false;\n           \n           return true;\n       }\n       \n       @Override\n       public int hashCode() {\n           return Objects.hashCode(name);\n       }\n   }\n\n   @Inject\n   public ParseNamesFromHttpResponse(GsonWrapper gsonView) {\n      this.parser = new ParseFirstJsonValueNamed<Set<Name>>(checkNotNull(gsonView, \"gsonView\"),\n            new TypeLiteral<Set<Name>>() {\n            }, \"hypervisor\");\n   }\n\n   public Set<String> apply(HttpResponse response) {\n      checkNotNull(response, \"response\");\n      Set<Name> toParse = parser.apply(response);\n      checkNotNull(toParse, \"parsed result from %s\", response);\n      Builder<String> builder = ImmutableSet.builder();\n      for (Name entry : toParse)\n         builder.add(entry.name);\n      return builder.build();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/functions/ParseTypedAsyncJob.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\nimport java.util.Map.Entry;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.cloudstack.domain.Account;\nimport org.jclouds.cloudstack.domain.AsyncJob;\nimport org.jclouds.cloudstack.domain.AsyncJobError;\nimport org.jclouds.cloudstack.domain.FirewallRule;\nimport org.jclouds.cloudstack.domain.IPForwardingRule;\nimport org.jclouds.cloudstack.domain.LoadBalancerRule;\nimport org.jclouds.cloudstack.domain.Network;\nimport org.jclouds.cloudstack.domain.PortForwardingRule;\nimport org.jclouds.cloudstack.domain.PublicIPAddress;\nimport org.jclouds.cloudstack.domain.SecurityGroup;\nimport org.jclouds.cloudstack.domain.Snapshot;\nimport org.jclouds.cloudstack.domain.Template;\nimport org.jclouds.cloudstack.domain.TemplateExtraction;\nimport org.jclouds.cloudstack.domain.User;\nimport org.jclouds.cloudstack.domain.VirtualMachine;\nimport org.jclouds.cloudstack.domain.Volume;\nimport org.jclouds.cloudstack.domain.AsyncJob.Builder;\nimport org.jclouds.cloudstack.domain.AsyncJobError.ErrorCode;\nimport org.jclouds.domain.JsonBall;\nimport org.jclouds.json.Json;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Function;\nimport com.google.common.base.Strings;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\nimport com.google.inject.Inject;\n\n@Singleton\npublic class ParseTypedAsyncJob implements Function<AsyncJob<Map<String, JsonBall>>, AsyncJob<?>> {\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   @Inject(optional = true)\n   @VisibleForTesting\n   @Named(\"jclouds.cloudstack.jobresult-type-map\")\n   Map<String, Class<?>> typeMap = ImmutableMap.<String, Class<?>>builder()\n      .put(\"user\", User.class)\n      .put(\"account\", Account.class)\n      .put(\"securitygroup\", SecurityGroup.class)\n      .put(\"portforwardingrule\", PortForwardingRule.class)\n      .put(\"ipforwardingrule\", IPForwardingRule.class)\n      .put(\"firewallrule\", FirewallRule.class)\n      .put(\"network\", Network.class)\n      .put(\"ipaddress\", PublicIPAddress.class)\n      .put(\"virtualmachine\", VirtualMachine.class)\n      .put(\"loadbalancer\", LoadBalancerRule.class)\n      .put(\"snapshot\", Snapshot.class)\n      .put(\"template\", Template.class)\n      .put(\"volume\", Volume.class).build();\n   private final Json json;\n\n   @Inject\n   public ParseTypedAsyncJob(Json json) {\n      this.json = checkNotNull(json, \"json\");\n   }\n\n   public AsyncJob<?> apply(AsyncJob<Map<String, JsonBall>> toParse) {\n      AsyncJob<?> result = toParse;\n      if (toParse.getResult() != null) {\n         if (toParse.getResult().size() == 1) {\n            @SuppressWarnings({\"unchecked\", \"rawtypes\"})\n            Builder<?, Object> builder = AsyncJob.Builder.fromAsyncJobUntyped((AsyncJob) toParse);\n            if (toParse.getResult().containsKey(\"success\")) {\n               builder.result(null);\n            } else {\n               Entry<String, JsonBall> entry = Iterables.get(toParse.getResult().entrySet(), 0);\n               if (\"template\".equals(entry.getKey())) {\n                  // Sometimes Cloudstack will say 'template' and the payload is a Template object.\n                  // Sometimes Cloudstack will say 'template' and the payload is a TemplateExtraction object.\n                  // The 'state' field only exists on TemplateExtraction, so we can test this to work out what we have actually been given.\n                  Template template = json.fromJson(entry.getValue().toString(), Template.class);\n                  TemplateExtraction templateExtraction = json.fromJson(entry.getValue().toString(), TemplateExtraction.class);\n                  boolean isTemplate = Strings.isNullOrEmpty(templateExtraction.getState());\n                  builder.result(isTemplate ? template : templateExtraction);\n               } else if (typeMap.containsKey(entry.getKey())) {\n                  builder.result(json.fromJson(entry.getValue().toString(), typeMap.get(entry.getKey())));\n               } else {\n                  logger.warn(\n                     \"type key %s not configured.  please override default for Map<String, Class<?>> bound to name jclouds.cloudstack.jobresult-type-map\",\n                     entry.getKey());\n                  builder.result(entry.getValue().toString());\n               }\n            }\n            result = builder.build();\n         } else if (toParse.getResult().containsKey(\"errorcode\")) {\n            @SuppressWarnings({\"unchecked\", \"rawtypes\"})\n            Builder<?, Object> builder = AsyncJob.Builder.fromAsyncJobUntyped((AsyncJob) toParse);\n            builder.result(null);  // avoid classcastexceptions\n            builder.error(AsyncJobError.builder().errorCode(ErrorCode.fromValue(toParse.getResult().get(\"errorcode\").toString()))\n                  .errorText(toParse.getResult().containsKey(\"errortext\") ? toParse.getResult().get(\"errortext\").toString().replace(\"\\\"\", \"\") : null)\n                  .build());\n            result = builder.build();\n         } else if (toParse.getResult().size() > 1) {\n            logger.warn(\"unexpected size of async job result; expecting a map with a single element\",\n               toParse.getResult());\n         }\n      }\n      return result;\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/functions/ReuseOrAssociateNewPublicIPAddress.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Predicates.and;\nimport static com.google.common.collect.Iterables.find;\nimport static org.jclouds.cloudstack.options.AssociateIPAddressOptions.Builder.networkId;\nimport static org.jclouds.cloudstack.options.ListPublicIPAddressesOptions.Builder.allocatedOnly;\nimport static org.jclouds.cloudstack.predicates.PublicIPAddressPredicates.associatedWithNetwork;\nimport static org.jclouds.cloudstack.predicates.PublicIPAddressPredicates.available;\nimport static org.jclouds.compute.reference.ComputeServiceConstants.COMPUTE_LOGGER;\n\nimport java.util.NoSuchElementException;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.cloudstack.CloudStackApi;\nimport org.jclouds.cloudstack.domain.AsyncCreateResponse;\nimport org.jclouds.cloudstack.domain.Network;\nimport org.jclouds.cloudstack.domain.PublicIPAddress;\nimport org.jclouds.cloudstack.features.AddressApi;\nimport org.jclouds.cloudstack.strategy.BlockUntilJobCompletesAndReturnResult;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class ReuseOrAssociateNewPublicIPAddress implements Function<Network, PublicIPAddress> {\n   private final CloudStackApi client;\n   private final BlockUntilJobCompletesAndReturnResult blockUntilJobCompletesAndReturnResult;\n   @Resource\n   @Named(COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   @Inject\n   public ReuseOrAssociateNewPublicIPAddress(CloudStackApi client,\n         BlockUntilJobCompletesAndReturnResult blockUntilJobCompletesAndReturnResult) {\n      this.client = checkNotNull(client, \"client\");\n      this.blockUntilJobCompletesAndReturnResult = checkNotNull(blockUntilJobCompletesAndReturnResult,\n            \"blockUntilJobCompletesAndReturnResult\");\n   }\n\n   /**\n    * Finds existing addresses who are ready for use and not assigned to a\n    * machine.\n    * \n    * @param networkId\n    *           network id to search\n    * @param client\n    *           address client\n    * @return address to use\n    * @throws NoSuchElementException\n    *            if there's no existing ip address that is free for use\n    */\n   public static PublicIPAddress findAvailableAndAssociatedWithNetwork(String networkId, AddressApi client) {\n      return find(client.listPublicIPAddresses(allocatedOnly(true).networkId(networkId)),\n            and(associatedWithNetwork(networkId), available()));\n   }\n\n   public static PublicIPAddress associateIPAddressInNetwork(Network network, CloudStackApi client,\n         BlockUntilJobCompletesAndReturnResult blockUntilJobCompletesAndReturnResult) {\n      AsyncCreateResponse job = client.getAddressApi().associateIPAddressInZone(network.getZoneId(),\n            networkId(network.getId()));\n      PublicIPAddress ip = blockUntilJobCompletesAndReturnResult.<PublicIPAddress> apply(job);\n      assert ip.getZoneId().equals(network.getZoneId());\n      return ip;\n   }\n\n   @Override\n   public PublicIPAddress apply(Network input) {\n      try {\n         logger.debug(\">> looking for existing address in network(%s)\", input.getId());\n         PublicIPAddress returnVal = findAvailableAndAssociatedWithNetwork(input.getId(), client.getAddressApi());\n         logger.debug(\"<< reused address(%s)\", returnVal.getId());\n         return returnVal;\n      } catch (NoSuchElementException e) {\n         logger.debug(\">> associating new address in network(%s)\", input.getId());\n         PublicIPAddress returnVal = associateIPAddressInNetwork(input, client, blockUntilJobCompletesAndReturnResult);\n         logger.debug(\"<< associated address(%s)\", returnVal.getId());\n         return returnVal;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/functions/StaticNATVirtualMachineInNetwork.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\n\nimport org.jclouds.cloudstack.CloudStackApi;\nimport org.jclouds.cloudstack.domain.Network;\nimport org.jclouds.cloudstack.domain.PublicIPAddress;\nimport org.jclouds.cloudstack.domain.VirtualMachine;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Objects;\nimport com.google.inject.assistedinject.Assisted;\n\npublic class StaticNATVirtualMachineInNetwork implements Function<VirtualMachine, PublicIPAddress> {\n   public interface Factory {\n      StaticNATVirtualMachineInNetwork create(Network in);\n   }\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   private final CloudStackApi client;\n   private final ReuseOrAssociateNewPublicIPAddress reuseOrAssociate;\n   private final Network network;\n\n   @Inject\n   public StaticNATVirtualMachineInNetwork(CloudStackApi client,\n         ReuseOrAssociateNewPublicIPAddress reuseOrAssociate, @Assisted Network network) {\n      this.client = checkNotNull(client, \"client\");\n      this.reuseOrAssociate = checkNotNull(reuseOrAssociate, \"reuseOrAssociate\");\n      this.network = checkNotNull(network, \"network\");\n   }\n\n   public PublicIPAddress apply(VirtualMachine vm) {\n      PublicIPAddress ip;\n      for (ip = reuseOrAssociate.apply(network);\n            !ip.isStaticNAT() || !Objects.equal(ip.getVirtualMachineId(), vm.getId());\n            ip = reuseOrAssociate .apply(network)) {\n         // check to see if someone already grabbed this ip\n         if (ip.getVirtualMachineId() != null && !ip.getVirtualMachineId().equals(vm.getId()))\n            continue;\n         try {\n            logger.debug(\">> static NATing IPAddress(%s) to virtualMachine(%s)\", ip.getId(), vm.getId());\n            client.getNATApi().enableStaticNATForVirtualMachine(vm.getId(), ip.getId());\n            ip = client.getAddressApi().getPublicIPAddress(ip.getId());\n            if (ip.isStaticNAT() && ip.getVirtualMachineId().equals(vm.getId()))\n               break;\n         } catch (IllegalStateException e) {\n            // very likely an ip conflict, so retry;\n         }\n         return ip;\n      }\n      return ip;\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/functions/WindowsLoginCredentialsFromEncryptedData.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.functions;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.io.BaseEncoding.base64;\n\nimport java.security.KeyFactory;\nimport java.security.PrivateKey;\nimport java.security.spec.KeySpec;\nimport java.util.regex.Pattern;\n\nimport javax.crypto.Cipher;\n\nimport org.jclouds.cloudstack.domain.EncryptedPasswordAndPrivateKey;\nimport org.jclouds.crypto.Crypto;\nimport org.jclouds.crypto.Pems;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Throwables;\nimport com.google.inject.Inject;\nimport com.google.inject.Singleton;\n\n/**\n * Given an encrypted Windows Administrator password and the decryption key, return a LoginCredentials instance.\n */\n@Singleton\npublic class WindowsLoginCredentialsFromEncryptedData implements Function<EncryptedPasswordAndPrivateKey, LoginCredentials> {\n\n   private final Crypto crypto;\n\n   @Inject\n   public WindowsLoginCredentialsFromEncryptedData(Crypto crypto) {\n      this.crypto = crypto;\n   }\n   \n   private static final Pattern whitespace = Pattern.compile(\"\\\\s\");\n   \n   @Override\n   public LoginCredentials apply(@Nullable EncryptedPasswordAndPrivateKey dataAndKey) {\n      if (dataAndKey == null)\n         return null;\n      try {\n         KeySpec keySpec = Pems.privateKeySpec(dataAndKey.getPrivateKey());\n         KeyFactory kf = crypto.rsaKeyFactory();\n         PrivateKey privKey = kf.generatePrivate(keySpec);\n\n         Cipher cipher = crypto.cipher(\"RSA\");\n         cipher.init(Cipher.DECRYPT_MODE, privKey);\n         byte[] cipherText = base64().decode(whitespace.matcher(dataAndKey.getEncryptedPassword()).replaceAll(\"\"));\n         byte[] plainText = cipher.doFinal(cipherText);\n         String password = new String(plainText, UTF_8);\n\n         return LoginCredentials.builder()\n            .user(\"Administrator\")\n            .password(password)\n            .noPrivateKey()\n            .build();\n\n      } catch (Exception e) {\n         throw Throwables.propagate(e);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/functions/ZoneIdToZone.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.cloudstack.CloudStackApi;\nimport org.jclouds.cloudstack.domain.Zone;\nimport org.jclouds.cloudstack.features.ZoneApi;\n\nimport com.google.common.cache.CacheLoader;\nimport com.google.inject.Inject;\n\n/**\n * Defines a cache that allows a zone to be looked up by its ID.\n */\npublic class ZoneIdToZone extends CacheLoader<String, Zone> {\n\n   private final ZoneApi zoneClient;\n\n   @Inject\n   public ZoneIdToZone(CloudStackApi client) {\n      checkNotNull(client, \"client\");\n      this.zoneClient = client.getZoneApi();\n   }\n\n   @Override\n   public Zone load(String zoneId) throws Exception {\n      checkNotNull(zoneId, \"zoneId\");\n      return zoneClient.getZone(zoneId);\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/handlers/CloudStackErrorHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.handlers;\n\nimport java.io.IOException;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.InsufficientResourcesException;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.jclouds.util.Closeables2;\nimport org.jclouds.util.Strings2;\n\nimport com.google.common.base.Throwables;\n\n@Singleton\npublic class CloudStackErrorHandler implements HttpErrorHandler {\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   public void handleError(HttpCommand command, HttpResponse response) {\n      // it is important to always read fully and close streams\n      String message = parseMessage(response);\n      Exception exception = message != null ? new HttpResponseException(command, response, message)\n            : new HttpResponseException(command, response);\n      try {\n         message = message != null ? message : String.format(\"%s -> %s\", command.getCurrentRequest().getRequestLine(),\n               response.getStatusLine());\n         switch (response.getStatusCode()) {\n         case 400:\n            exception = new IllegalArgumentException(message, exception);\n            break;\n         case 531:\n         case 401:\n            exception = new AuthorizationException(message, exception);\n            break;\n         case 404:\n            if (!command.getCurrentRequest().getMethod().equals(\"DELETE\")) {\n               exception = new ResourceNotFoundException(message, exception);\n            }\n            break;\n         case 405:\n            exception = new IllegalArgumentException(message, exception);\n            break;\n         case 409:\n         case 431:\n            if (message.contains(\"does not exist\")) {\n               exception = new ResourceNotFoundException(message, exception);\n            } else {\n               exception = new IllegalStateException(message, exception);\n            }\n            break;\n         case 534:\n            if (message.contains(\"Maximum number of resources of type\")) {\n               exception = new InsufficientResourcesException(message, exception);\n            }\n            break;\n         case 537:\n            exception = new IllegalStateException(message, exception);\n            break;\n         }\n      } finally {\n         Closeables2.closeQuietly(response.getPayload());\n         command.setException(exception);\n      }\n   }\n\n   public String parseMessage(HttpResponse response) {\n      if (response.getPayload() == null)\n         return null;\n      try {\n         return Strings2.toStringAndClose(response.getPayload().openStream());\n      } catch (IOException e) {\n         throw new RuntimeException(e);\n      } finally {\n         try {\n            response.getPayload().getInput().close();\n         } catch (IOException e) {\n            Throwables.propagate(e);\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/handlers/InvalidateSessionAndRetryOn401AndLogoutOnClose.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.handlers;\n\nimport static org.jclouds.http.HttpUtils.releasePayload;\n\nimport jakarta.annotation.PreDestroy;\n\nimport org.jclouds.cloudstack.domain.LoginResponse;\nimport org.jclouds.cloudstack.features.SessionApi;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.handlers.BackoffLimitedRetryHandler;\n\nimport com.google.common.cache.LoadingCache;\nimport com.google.inject.Inject;\nimport com.google.inject.Singleton;\n\n/**\n * This will parse and set an appropriate exception on the command object.\n */\n@Singleton\npublic class InvalidateSessionAndRetryOn401AndLogoutOnClose extends BackoffLimitedRetryHandler {\n   private final LoadingCache<Credentials, LoginResponse> authenticationResponseCache;\n   private final SessionApi sessionClient;\n\n   @Inject\n   protected InvalidateSessionAndRetryOn401AndLogoutOnClose(LoadingCache<Credentials, LoginResponse> authenticationResponseCache,\n                                                            SessionApi sessionClient) {\n      this.authenticationResponseCache = authenticationResponseCache;\n      this.sessionClient = sessionClient;\n   }\n\n   @Override\n   public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) {\n      try {\n         switch (response.getStatusCode()) {\n            case 401:\n               authenticationResponseCache.invalidateAll();\n               return super.shouldRetryRequest(command, response);\n         }\n         return false;\n\n      } finally {\n         releasePayload(response);\n      }\n   }\n\n   /**\n    * it is important that we close any sessions on close to help the server not become overloaded.\n    */\n   @PreDestroy\n   public void logoutOnClose() {\n      for (LoginResponse s : authenticationResponseCache.asMap().values()) {\n         try {\n            sessionClient.logoutUser(s.getSessionKey());\n         } catch (Exception e) {\n            logger.error(e, \"error logging out session %s\", s.getSessionKey());\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/internal/CloudStackContextImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.internal;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Context;\nimport org.jclouds.cloudstack.CloudStackApi;\nimport org.jclouds.cloudstack.CloudStackContext;\nimport org.jclouds.cloudstack.CloudStackDomainApi;\nimport org.jclouds.cloudstack.CloudStackGlobalApi;\nimport org.jclouds.compute.ComputeService;\nimport org.jclouds.compute.Utils;\nimport org.jclouds.compute.internal.ComputeServiceContextImpl;\nimport org.jclouds.location.Provider;\nimport org.jclouds.rest.ApiContext;\n\nimport com.google.common.reflect.TypeToken;\n\n@Singleton\npublic class CloudStackContextImpl extends ComputeServiceContextImpl implements CloudStackContext {\n   private final CloudStackApi client;\n   private final ApiContext<CloudStackDomainApi> domainContext;\n   private final ApiContext<CloudStackGlobalApi> globalContext;\n\n   @Inject\n   CloudStackContextImpl(@Provider Context backend, @Provider TypeToken<? extends Context> backendType,\n         ComputeService computeService, Utils utils, CloudStackApi client,\n         ApiContext<CloudStackDomainApi> domainContext,\n         ApiContext<CloudStackGlobalApi> globalContext) {\n      super(backend, backendType, computeService, utils);\n      this.client = client;\n      this.domainContext = domainContext;\n      this.globalContext = globalContext;\n   }\n\n   @Override\n   public CloudStackApi getApi() {\n      return client;\n   }\n\n   @Override\n   public CloudStackDomainApi getDomainApi() {\n      return domainContext.getApi();\n   }\n\n   @Override\n   public CloudStackGlobalApi getGlobalApi() {\n      return globalContext.getApi();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/loaders/LoginWithPasswordCredentials.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.loaders;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.hash.Hashing.md5;\nimport static com.google.common.io.BaseEncoding.base16;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.cloudstack.domain.LoginResponse;\nimport org.jclouds.cloudstack.features.SessionApi;\nimport org.jclouds.domain.Credentials;\n\nimport com.google.common.cache.CacheLoader;\n\n@Singleton\npublic class LoginWithPasswordCredentials extends CacheLoader<Credentials, LoginResponse> {\n   private final SessionApi client;\n\n   @Inject\n   public LoginWithPasswordCredentials(SessionApi client) {\n      this.client = client;\n   }\n\n   @Override\n   public LoginResponse load(Credentials input) {\n      String username = input.identity;\n      String domain = \"\";  // empty = ROOT domain\n\n      // domain may be present\n      if (username.indexOf('/') != -1) {\n         // username may not end with slash!\n         domain = username.substring(0, username.lastIndexOf('/'));\n         username = username.substring(username.lastIndexOf('/') + 1, username.length());\n      }\n      String hashedPassword = base16().lowerCase().encode(md5().hashString(input.credential, UTF_8).asBytes());\n      return client.loginUserInDomainWithHashOfPassword(username, domain, hashedPassword);\n   }\n\n   @Override\n   public String toString() {\n      return \"loginWithPasswordCredentials()\";\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/AccountInDomainOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options for services that apply to accounts in domains\n * \n * @see <a href=\"http://download.cloud.com/releases/2.2.0/api_2.2.12/TOC_User.html\" />\n */\npublic class AccountInDomainOptions extends BaseHttpRequestOptions {\n\n   public static final AccountInDomainOptions NONE = new AccountInDomainOptions();\n\n   /**\n    * \n    * @param account\n    *           an optional account for the resource\n    * @param domain\n    *           domain id\n    */\n   public AccountInDomainOptions accountInDomain(String account, String domain) {\n      this.queryParameters.replaceValues(\"account\", ImmutableSet.of(account));\n      this.queryParameters.replaceValues(\"domainid\", ImmutableSet.of(domain + \"\"));\n      return this;\n   }\n\n   /**\n    * @param domainId\n    *           The domain for the resource\n    */\n   public AccountInDomainOptions domainId(String domainId) {\n      this.queryParameters.replaceValues(\"domainid\", ImmutableSet.of(domainId + \"\"));\n      return this;\n\n   }\n\n   public static class Builder {\n      /**\n       * @see AccountInDomainOptions#accountInDomain\n       */\n      public static AccountInDomainOptions accountInDomain(String account, String domain) {\n         AccountInDomainOptions options = new AccountInDomainOptions();\n         return options.accountInDomain(account, domain);\n      }\n\n      /**\n       * @see AccountInDomainOptions#domainId\n       */\n      public static AccountInDomainOptions domainId(String domainId) {\n         AccountInDomainOptions options = new AccountInDomainOptions();\n         return options.domainId(domainId);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/AddClusterOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.cloudstack.domain.AllocationState;\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options to the GlobalHostApi.addHost() API call\n */\npublic class AddClusterOptions extends BaseHttpRequestOptions {\n\n   public static final AddClusterOptions NONE = new AddClusterOptions();\n\n   /**\n    * @param allocationState Allocation state of this Host for allocation of new resources\n    */\n   public AddClusterOptions allocationState(AllocationState allocationState) {\n      this.queryParameters.replaceValues(\"allocationstate\", ImmutableSet.of(allocationState.toString()));\n      return this;\n   }\n\n   /**\n    * @param password the password for the host\n    */\n   public AddClusterOptions password(String password) {\n      this.queryParameters.replaceValues(\"password\", ImmutableSet.of(password));\n      return this;\n   }\n\n   /**\n    * @param podId the Pod ID for the host\n    */\n   public AddClusterOptions podId(String podId) {\n      this.queryParameters.replaceValues(\"podid\", ImmutableSet.of(podId + \"\"));\n      return this;\n   }\n\n   /**\n    * @param url the URL\n    */\n   public AddClusterOptions url(String url) {\n      this.queryParameters.replaceValues(\"url\", ImmutableSet.of(url));\n      return this;\n   }\n\n   /**\n    * @param username the username for the cluster\n    */\n   public AddClusterOptions username(String username) {\n      this.queryParameters.replaceValues(\"username\", ImmutableSet.of(username));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @param allocationState Allocation state of this Host for allocation of new resources\n       */\n      public static AddClusterOptions allocationState(AllocationState allocationState) {\n         return new AddClusterOptions().allocationState(allocationState);\n      }\n\n      /**\n       * @param password the password for the host\n       */\n      public static AddClusterOptions password(String password) {\n         return new AddClusterOptions().password(password);\n      }\n\n      /**\n       * @param podId the Pod ID for the host\n       */\n      public static AddClusterOptions podId(String podId) {\n         return new AddClusterOptions().podId(podId);\n      }\n\n      /**\n       * @param url the URL\n       */\n      public static AddClusterOptions url(String url) {\n         return new AddClusterOptions().url(url);\n      }\n\n      /**\n       * @param username the username for the cluster\n       */\n      public static AddClusterOptions username(String username) {\n         return new AddClusterOptions().username(username);\n      }\n\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/AddHostOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.AllocationState;\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.base.Joiner;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options to the GlobalHostApi.addHost() API call\n */\npublic class AddHostOptions extends BaseHttpRequestOptions {\n\n   public static final AddHostOptions NONE = new AddHostOptions();\n\n   /**\n    * @param allocationState Allocation state of this Host for allocation of new resources\n    */\n   public AddHostOptions allocationState(AllocationState allocationState) {\n      this.queryParameters.replaceValues(\"allocationstate\", ImmutableSet.of(allocationState.toString()));\n      return this;\n   }\n\n   /**\n    * @param clusterId the cluster ID for the host\n    */\n   public AddHostOptions clusterId(String clusterId) {\n      this.queryParameters.replaceValues(\"clusterid\", ImmutableSet.of(clusterId + \"\"));\n      return this;\n   }\n\n   /**\n    * @param clusterName the cluster name for the host\n    */\n   public AddHostOptions clusterName(String clusterName) {\n      this.queryParameters.replaceValues(\"clustername\", ImmutableSet.of(clusterName));\n      return this;\n   }\n\n   /**\n    * @param hostTags list of tags to be added to the host\n    */\n   public AddHostOptions hostTags(Set<String> hostTags) {\n      this.queryParameters.replaceValues(\"hosttags\", ImmutableSet.of(Joiner.on(',').join(hostTags)));\n      return this;\n   }\n\n   /**\n    * @param podId the Pod ID for the host\n    */\n   public AddHostOptions podId(String podId) {\n      this.queryParameters.replaceValues(\"podid\", ImmutableSet.of(podId + \"\"));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @param allocationState Allocation state of this Host for allocation of new resources\n       */\n      public static AddHostOptions allocationState(AllocationState allocationState) {\n         return new AddHostOptions().allocationState(allocationState);\n      }\n\n      /**\n       * @param clusterId the cluster ID for the host\n       */\n      public static AddHostOptions clusterId(String clusterId) {\n         return new AddHostOptions().clusterId(clusterId);\n      }\n\n      /**\n       * @param clusterName the cluster name for the host\n       */\n      public static AddHostOptions clusterName(String clusterName) {\n         return new AddHostOptions().clusterName(clusterName);\n      }\n\n      /**\n       * @param hostTags list of tags to be added to the host\n       */\n      public static AddHostOptions hostTags(Set<String> hostTags) {\n         return new AddHostOptions().hostTags(hostTags);\n      }\n\n      /**\n       * @param podId the Pod ID for the host\n       */\n      public static AddHostOptions podId(String podId) {\n         return new AddHostOptions().podId(podId);\n      }\n\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/AddSecondaryStorageOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options for the GlobalHostApi.addSecondaryStorage() API call\n */\npublic class AddSecondaryStorageOptions extends BaseHttpRequestOptions {\n   \n   public static final AddSecondaryStorageOptions NONE = new AddSecondaryStorageOptions();\n\n   /**\n    * @param zoneId\n    *           the ID of the zone\n    */\n   public AddSecondaryStorageOptions zoneId(String zoneId) {\n      this.queryParameters.replaceValues(\"zoneid\", ImmutableSet.of(zoneId + \"\"));\n      return this;\n   }\n   \n   public static class Builder {\n\n      /**\n       * @param zoneId\n       *           the ID of the zone\n       */\n      public static AddSecondaryStorageOptions zoneId(String zoneId) {\n         return new AddSecondaryStorageOptions().zoneId(zoneId);\n      }\n\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/AssignVirtualMachineOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Joiner;\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\n\n/**\n * Options used to control what disk offerings are returned\n * \n * @see <a href=\n *      \"http://download.cloud.com/releases/3.0.3/api_3.0.3/root_admin/assignVirtualMachine.html\"\n *      />\n */\npublic class AssignVirtualMachineOptions extends AccountInDomainOptions {\n\n   public static final AssignVirtualMachineOptions NONE = new AssignVirtualMachineOptions();\n\n   /**\n    * @param networkId\n    *           network id used by virtual machine\n    */\n   public AssignVirtualMachineOptions networkId(String networkId) {\n      this.queryParameters.replaceValues(\"networkids\", ImmutableSet.of(networkId + \"\"));\n      return this;\n   }\n\n   /**\n    * @param networkIds\n    *           network ids used by virtual machine\n    */\n   public AssignVirtualMachineOptions networkIds(Iterable<String> networkIds) {\n      this.queryParameters.replaceValues(\"networkids\", ImmutableSet.of(Joiner.on(',').join(networkIds)));\n      return this;\n   }\n\n   public Iterable<String> getNetworkIds() {\n      if (queryParameters.get(\"networkids\").size() == 1) {\n         return Iterables.transform(\n               Splitter.on(\",\").split(Iterables.getOnlyElement(queryParameters.get(\"networkids\"))),\n               new Function<String, String>() {\n\n                  @Override\n                  public String apply(String arg0) {\n                     return arg0;\n                  }\n\n               });\n      } else {\n         return ImmutableSet.<String> of();\n      }\n   }\n\n   /**\n    * @param securityGroupId\n    *           security group applied to the virtual machine. Should be passed\n    *           only when vm is created from a zone with Basic Network support\n    */\n   public AssignVirtualMachineOptions securityGroupId(String securityGroupId) {\n      this.queryParameters.replaceValues(\"securitygroupids\", ImmutableSet.of(securityGroupId + \"\"));\n      return this;\n   }\n\n   /**\n    * @param securityGroupIds\n    *           security groups applied to the virtual machine. Should be passed\n    *           only when vm is created from a zone with Basic Network support\n    */\n   public AssignVirtualMachineOptions securityGroupIds(Iterable<String> securityGroupIds) {\n      this.queryParameters.replaceValues(\"securitygroupids\", ImmutableSet.of(Joiner.on(',').join(securityGroupIds)));\n      return this;\n   }\n\n   public static class Builder {\n      /**\n       * @see AssignVirtualMachineOptions#networkId\n       */\n      public static AssignVirtualMachineOptions networkId(String id) {\n         AssignVirtualMachineOptions options = new AssignVirtualMachineOptions();\n         return options.networkId(id);\n      }\n\n      /**\n       * @see AssignVirtualMachineOptions#networkIds\n       */\n      public static AssignVirtualMachineOptions networkIds(Iterable<String> networkIds) {\n         AssignVirtualMachineOptions options = new AssignVirtualMachineOptions();\n         return options.networkIds(networkIds);\n      }\n\n      /**\n       * @see AssignVirtualMachineOptions#securityGroupId\n       */\n      public static AssignVirtualMachineOptions securityGroupId(String id) {\n         AssignVirtualMachineOptions options = new AssignVirtualMachineOptions();\n         return options.securityGroupId(id);\n      }\n\n      /**\n       * @see AssignVirtualMachineOptions#securityGroupIds\n       */\n      public static AssignVirtualMachineOptions securityGroupIds(Iterable<String> securityGroupIds) {\n         AssignVirtualMachineOptions options = new AssignVirtualMachineOptions();\n         return options.securityGroupIds(securityGroupIds);\n      }\n\n      /**\n       * @see AssignVirtualMachineOptions#accountInDomain\n       */\n      public static AssignVirtualMachineOptions accountInDomain(String account, String domain) {\n         AssignVirtualMachineOptions options = new AssignVirtualMachineOptions();\n         return options.accountInDomain(account, domain);\n      }\n\n      /**\n       * @see AssignVirtualMachineOptions#domainId\n       */\n      public static AssignVirtualMachineOptions domainId(String domainId) {\n         AssignVirtualMachineOptions options = new AssignVirtualMachineOptions();\n         return options.domainId(domainId);\n      }\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public AssignVirtualMachineOptions accountInDomain(String account, String domain) {\n      return AssignVirtualMachineOptions.class.cast(super.accountInDomain(account, domain));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public AssignVirtualMachineOptions domainId(String domainId) {\n      return AssignVirtualMachineOptions.class.cast(super.domainId(domainId));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/AssociateIPAddressOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options used to acquire and associate a public IP to an account.\n * \n * @see <a href=\n *      \"http://download.cloud.com/releases/2.2.0/api/user/associateIpAddress.html\"\n *      />\n */\npublic class AssociateIPAddressOptions extends AccountInDomainOptions {\n\n   public static final AssociateIPAddressOptions NONE = new AssociateIPAddressOptions();\n\n   /**\n    * @param networkId\n    *           The network this ip address should be associated to.\n    */\n   public AssociateIPAddressOptions networkId(String networkId) {\n      this.queryParameters.replaceValues(\"networkid\", ImmutableSet.of(networkId + \"\"));\n      return this;\n\n   }\n\n   /**\n    * @param projectId\n    *          Project for the IP\n    */\n   public AssociateIPAddressOptions projectId(String projectId) {\n      this.queryParameters.replaceValues(\"projectid\", ImmutableSet.of(projectId + \"\"));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see AssociateIPAddressOptions#networkId\n       */\n      public static AssociateIPAddressOptions networkId(String networkId) {\n         AssociateIPAddressOptions options = new AssociateIPAddressOptions();\n         return options.networkId(networkId);\n      }\n\n      /**\n       * @see AssociateIPAddressOptions#accountInDomain\n       */\n      public static AssociateIPAddressOptions accountInDomain(String account, String domain) {\n         AssociateIPAddressOptions options = new AssociateIPAddressOptions();\n         return options.accountInDomain(account, domain);\n      }\n\n      /**\n       * @see AssociateIPAddressOptions#domainId\n       */\n      public static AssociateIPAddressOptions domainId(String domainId) {\n         AssociateIPAddressOptions options = new AssociateIPAddressOptions();\n         return options.domainId(domainId);\n      }\n\n      /**\n       * @see AssociateIPAddressOptions#projectId(String)\n       */\n      public static AssociateIPAddressOptions projectId(String projectId) {\n         AssociateIPAddressOptions options = new AssociateIPAddressOptions();\n         return options.projectId(projectId);\n      }\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public AssociateIPAddressOptions accountInDomain(String account, String domain) {\n      return AssociateIPAddressOptions.class.cast(super.accountInDomain(account, domain));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public AssociateIPAddressOptions domainId(String domainId) {\n      return AssociateIPAddressOptions.class.cast(super.domainId(domainId));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/CreateAccountOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Optional fields for account creation\n *\n * @see <a\n *      href=\"http://download.cloud.com/releases/2.2.0/api_2.2.12/global_admin/createAccount.html\"\n *      />\n */\npublic class CreateAccountOptions extends BaseHttpRequestOptions {\n\n   public static final CreateAccountOptions NONE = new CreateAccountOptions();\n\n   /**\n    * @param networkDomain network domain\n    */\n   public CreateAccountOptions networkDomain(String networkDomain) {\n      this.queryParameters.replaceValues(\"networkdomain\", ImmutableSet.of(networkDomain));\n      return this;\n   }\n\n   /**\n    * @param account an optional account for the resource\n    */\n   public CreateAccountOptions account(String account) {\n      this.queryParameters.replaceValues(\"account\", ImmutableSet.of(account));\n      return this;\n   }\n\n   /**\n    * @param domainId The domain for the resource\n    */\n   public CreateAccountOptions domainId(String domainId) {\n      this.queryParameters.replaceValues(\"domainid\", ImmutableSet.of(domainId + \"\"));\n      return this;\n\n   }\n\n   public static class Builder {\n\n      /**\n       * @see CreateAccountOptions#networkDomain\n       */\n      public static CreateAccountOptions networkDomain(String networkDomain) {\n         CreateAccountOptions options = new CreateAccountOptions();\n         return options.networkDomain(networkDomain);\n      }\n\n      /**\n       * @see CreateAccountOptions#account\n       */\n      public static CreateAccountOptions account(String account) {\n         CreateAccountOptions options = new CreateAccountOptions();\n         return options.account(account);\n      }\n\n      /**\n       * @see CreateAccountOptions#domainId\n       */\n      public static CreateAccountOptions domainId(String domainId) {\n         CreateAccountOptions options = new CreateAccountOptions();\n         return options.domainId(domainId);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/CreateDiskOfferingOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport java.util.Set;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options to control how disk offerings are created\n * \n * @see <a\n *      href=\"http://download.cloud.com/releases/2.2.0/api_2.2.12/global_admin/createDiskOffering.html\"\n *      />\n */\npublic class CreateDiskOfferingOptions extends AccountInDomainOptions {\n\n   public static final CreateDiskOfferingOptions NONE = new CreateDiskOfferingOptions();\n\n   /**\n    * @param customized\n    *          whether disk offering is custom or not\n    */\n   public CreateDiskOfferingOptions customized(boolean customized) {\n      this.queryParameters.replaceValues(\"customized\", ImmutableSet.<String>of(customized + \"\"));\n      return this;\n   }\n\n   /**\n    * @param diskSizeInGB\n    *          size of the disk offering in GB\n    */\n   public CreateDiskOfferingOptions diskSizeInGB(int diskSizeInGB) {\n      this.queryParameters.replaceValues(\"disksize\", ImmutableSet.<String>of(diskSizeInGB + \"\"));\n      return this;\n   }\n\n   /**\n    * @param tags\n    *          the tags for this service offering\n    */\n   public CreateDiskOfferingOptions tags(Set<String> tags) {\n      this.queryParameters.replaceValues(\"tags\", ImmutableSet.copyOf(tags));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see CreateDiskOfferingOptions#customized\n       */\n      public static CreateDiskOfferingOptions customized(boolean customized) {\n         CreateDiskOfferingOptions options = new CreateDiskOfferingOptions();\n         return options.customized(customized);\n      }\n\n      /**\n       * @see CreateDiskOfferingOptions#diskSizeInGB\n       */\n      public static CreateDiskOfferingOptions diskSizeInGB(int diskSizeInGB) {\n         CreateDiskOfferingOptions options = new CreateDiskOfferingOptions();\n         return options.diskSizeInGB(diskSizeInGB);\n      }\n\n      /**\n       * @see CreateDiskOfferingOptions#tags\n       */\n      public static CreateDiskOfferingOptions tags(Set<String> tags) {\n         CreateDiskOfferingOptions options = new CreateDiskOfferingOptions();\n         return options.tags(tags);\n      }\n\n      /**\n       * @see CreateDiskOfferingOptions#accountInDomain\n       */\n      public static CreateDiskOfferingOptions accountInDomain(String account, String domain) {\n         CreateDiskOfferingOptions options = new CreateDiskOfferingOptions();\n         return options.accountInDomain(account, domain);\n      }\n\n      /**\n       * @see CreateDiskOfferingOptions#domainId\n       */\n      public static CreateDiskOfferingOptions domainId(String domainId) {\n         CreateDiskOfferingOptions options = new CreateDiskOfferingOptions();\n         return options.domainId(domainId);\n      }\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public CreateDiskOfferingOptions accountInDomain(String account, String domain) {\n      return CreateDiskOfferingOptions.class.cast(super.accountInDomain(account, domain));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public CreateDiskOfferingOptions domainId(String domainId) {\n      return CreateDiskOfferingOptions.class.cast(super.domainId(domainId));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/CreateDomainOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options used to control how a domain is created\n * \n * @see <a href=\n *      \"http://download.cloud.com/releases/2.2.0/api_2.2.12/global_admin/createDomain.html\"\n *      />\n */\npublic class CreateDomainOptions extends BaseHttpRequestOptions {\n\n   public static final CreateDomainOptions NONE = new CreateDomainOptions();\n\n   /**\n    * @param networkDomain\n    *       network domain for networks in the domain\n    */\n   public CreateDomainOptions networkDomain(String networkDomain) {\n      this.queryParameters.replaceValues(\"networkdomain\", ImmutableSet.of(networkDomain));\n      return this;\n   }\n\n   /**\n    * @param parentDomainId\n    *       the ID of the parent domain\n    */\n   public CreateDomainOptions parentDomainId(String parentDomainId) {\n      this.queryParameters.replaceValues(\"parentdomainid\", ImmutableSet.of(parentDomainId + \"\"));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see CreateDomainOptions#networkDomain\n       */\n      public static CreateDomainOptions networkDomain(String networkDomain) {\n         CreateDomainOptions options = new CreateDomainOptions();\n         return options.networkDomain(networkDomain);\n      }\n\n      /**\n       * @see CreateDomainOptions#parentDomainId\n       */\n      public static CreateDomainOptions parentDomainId(String parentDomainId) {\n         CreateDomainOptions options = new CreateDomainOptions();\n         return options.parentDomainId(parentDomainId);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/CreateFirewallRuleOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport java.util.Set;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.base.Joiner;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options used to control how a firewall rule is created\n * \n * @see <a href=\n *      \"http://download.cloud.com/releases/2.2.0/api_2.2.12/global_admin/createFirewallRule.html\"\n *      />\n */\npublic class CreateFirewallRuleOptions extends BaseHttpRequestOptions {\n\n   public static final CreateFirewallRuleOptions NONE = new CreateFirewallRuleOptions();\n\n   /**\n    * @param CIDRs\n    *       the list of CIDRs to forward traffic from\n    */\n   public CreateFirewallRuleOptions CIDRs(Set<String> CIDRs) {\n      this.queryParameters.replaceValues(\"cidrlist\", ImmutableSet.of(Joiner.on(\",\").join(CIDRs)));\n      return this;\n   }\n\n   /**\n    * @param startPort\n    *       the starting port of firewall rule\n    */\n   public CreateFirewallRuleOptions startPort(int startPort) {\n      this.queryParameters.replaceValues(\"startport\", ImmutableSet.of(startPort + \"\"));\n      return this;\n   }\n\n   /**\n    * @param endPort\n    *       the ending port of firewall rule\n    */\n   public CreateFirewallRuleOptions endPort(int endPort) {\n      this.queryParameters.replaceValues(\"endport\", ImmutableSet.of(endPort + \"\"));\n      return this;\n   }\n\n   /**\n    * @param icmpCode\n    *       error code for this icmp message\n    */\n   public CreateFirewallRuleOptions icmpCode(String icmpCode) {\n      this.queryParameters.replaceValues(\"icmpcode\", ImmutableSet.of(icmpCode));\n      return this;\n   }\n\n   /**\n    * @param icmpType\n    *       type of the icmp message being sent\n    */\n   public CreateFirewallRuleOptions icmpType(String icmpType) {\n      this.queryParameters.replaceValues(\"icmptype\", ImmutableSet.of(icmpType));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see CreateFirewallRuleOptions#CIDRs\n       */\n      public static CreateFirewallRuleOptions CIDRs(Set<String> CIDRs) {\n         CreateFirewallRuleOptions options = new CreateFirewallRuleOptions();\n         return options.CIDRs(CIDRs);\n      }\n\n      /**\n       * @see CreateFirewallRuleOptions#startPort\n       */\n      public static CreateFirewallRuleOptions startPort(int startPort) {\n         CreateFirewallRuleOptions options = new CreateFirewallRuleOptions();\n         return options.startPort(startPort);\n      }\n\n      /**\n       * @see CreateFirewallRuleOptions#endPort\n       */\n      public static CreateFirewallRuleOptions endPort(int endPort) {\n         CreateFirewallRuleOptions options = new CreateFirewallRuleOptions();\n         return options.endPort(endPort);\n      }\n\n      /**\n       * @see CreateFirewallRuleOptions#icmpCode\n       */\n      public static CreateFirewallRuleOptions icmpCode(String icmpCode) {\n         CreateFirewallRuleOptions options = new CreateFirewallRuleOptions();\n         return options.icmpCode(icmpCode);\n      }\n\n      /**\n       * @see CreateFirewallRuleOptions#icmpType\n       */\n      public static CreateFirewallRuleOptions icmpType(String icmpType) {\n         CreateFirewallRuleOptions options = new CreateFirewallRuleOptions();\n         return options.icmpType(icmpType);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/CreateIPForwardingRuleOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options used to create an ip forwarding rule\n * \n * @see <a href=\n *      \"http://download.cloud.com/releases/2.2.0/api/user/createIpForwardingRule.html\"\n *      />\n */\npublic class CreateIPForwardingRuleOptions extends BaseHttpRequestOptions {\n\n   public static final CreateIPForwardingRuleOptions NONE = new CreateIPForwardingRuleOptions();\n\n   /**\n    * @param endPort\n    *           the end port for the rule\n    */\n   public CreateIPForwardingRuleOptions endPort(int endPort) {\n      this.queryParameters.replaceValues(\"endport\", ImmutableSet.of(endPort + \"\"));\n      return this;\n\n   }\n\n   public static class Builder {\n\n      /**\n       * @see CreatePortForwardingRuleOptions#endPort\n       */\n      public static CreateIPForwardingRuleOptions endPort(int endPort) {\n         CreateIPForwardingRuleOptions options = new CreateIPForwardingRuleOptions();\n         return options.endPort(endPort);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/CreateLoadBalancerRuleOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport java.util.Set;\n\nimport com.google.common.base.Joiner;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options used to control what load balancer rules are returned\n *\n * @see <a href=\n *      \"http://download.cloud.com/releases/2.2.0/api_2.2.12/user/createLoadBalancerRule.html\"\n *      />\n */\npublic class CreateLoadBalancerRuleOptions extends AccountInDomainOptions {\n\n   public static final CreateLoadBalancerRuleOptions NONE = new CreateLoadBalancerRuleOptions();\n\n   /**\n    * @param allowedSourceCIRDs the cidr list to forward traffic from\n    */\n   public CreateLoadBalancerRuleOptions allowedSourceCIDRs(Set<String> allowedSourceCIRDs) {\n      this.queryParameters.replaceValues(\"cidrlist\",\n         ImmutableSet.of(Joiner.on(\",\").join(allowedSourceCIRDs)));\n      return this;\n   }\n\n   /**\n    * @param description the description of the load balancer rule\n    */\n   public CreateLoadBalancerRuleOptions description(String description) {\n      this.queryParameters.replaceValues(\"description\", ImmutableSet.of(description));\n      return this;\n   }\n\n   /**\n    * @param openFirewall if true, firewall rule for source/end pubic port is automatically\n    *    created; if false - firewall rule has to be created explicitly. Has value true by default\n    */\n   public CreateLoadBalancerRuleOptions openFirewall(boolean openFirewall) {\n      this.queryParameters.replaceValues(\"openfirewall\", ImmutableSet.of(openFirewall + \"\"));\n      return this;\n   }\n\n   /**\n    * @param zoneId the availability zone ID\n    */\n   public CreateLoadBalancerRuleOptions zoneId(String zoneId) {\n      this.queryParameters.replaceValues(\"zoneid\", ImmutableSet.of(zoneId + \"\"));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see CreateLoadBalancerRuleOptions#allowedSourceCIDRs\n       */\n      public static CreateLoadBalancerRuleOptions allowedSourceCIDRs(Set<String> allowedSourceCIDRs) {\n         CreateLoadBalancerRuleOptions options = new CreateLoadBalancerRuleOptions();\n         return options.allowedSourceCIDRs(allowedSourceCIDRs);\n      }\n\n      /**\n       * @see CreateLoadBalancerRuleOptions#description\n       */\n      public static CreateLoadBalancerRuleOptions description(String description) {\n         CreateLoadBalancerRuleOptions options = new CreateLoadBalancerRuleOptions();\n         return options.description(description);\n      }\n\n      /**\n       * @see CreateLoadBalancerRuleOptions#openFirewall\n       */\n      public static CreateLoadBalancerRuleOptions openFirewall(boolean openFirewall) {\n         CreateLoadBalancerRuleOptions options = new CreateLoadBalancerRuleOptions();\n         return options.openFirewall(openFirewall);\n      }\n\n      /**\n       * @see CreateLoadBalancerRuleOptions#zoneId\n       */\n      public static CreateLoadBalancerRuleOptions zoneId(String zoneId) {\n         CreateLoadBalancerRuleOptions options = new CreateLoadBalancerRuleOptions();\n         return options.zoneId(zoneId);\n      }\n\n      /**\n       * @see CreateLoadBalancerRuleOptions#accountInDomain\n       */\n      public static CreateLoadBalancerRuleOptions accountInDomain(String account, String domain) {\n         CreateLoadBalancerRuleOptions options = new CreateLoadBalancerRuleOptions();\n         return options.accountInDomain(account, domain);\n      }\n\n      /**\n       * @see CreateLoadBalancerRuleOptions#domainId\n       */\n      public static CreateLoadBalancerRuleOptions domainId(String id) {\n         CreateLoadBalancerRuleOptions options = new CreateLoadBalancerRuleOptions();\n         return options.domainId(id);\n      }\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public CreateLoadBalancerRuleOptions accountInDomain(String account, String domain) {\n      return CreateLoadBalancerRuleOptions.class.cast(super.accountInDomain(account, domain));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public CreateLoadBalancerRuleOptions domainId(String domainId) {\n      return CreateLoadBalancerRuleOptions.class.cast(super.domainId(domainId));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/CreateNetworkOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Optional fields for network creation\n * \n * @see <a\n *      href=\"http://download.cloud.com/releases/2.2.0/api_2.2.12/user/createNetwork.html\"\n *      />\n */\npublic class CreateNetworkOptions extends AccountInDomainOptions {\n\n   public static final CreateNetworkOptions NONE = new CreateNetworkOptions();\n\n   /**\n    * @param isDefault\n    *           true if network is default, false otherwise\n    */\n   public CreateNetworkOptions isDefault(boolean isDefault) {\n      this.queryParameters.replaceValues(\"isdefault\", ImmutableSet.of(isDefault + \"\"));\n      return this;\n   }\n\n   /**\n    * @param isShared\n    *           true if network is shared across accounts in the Zone\n    */\n   public CreateNetworkOptions isShared(boolean isShared) {\n      this.queryParameters.replaceValues(\"isshared\", ImmutableSet.of(isShared + \"\"));\n      return this;\n   }\n\n   /**\n    * @param startIP\n    *           the beginning IP address in the VLAN IP range\n    */\n   public CreateNetworkOptions startIP(String startIP) {\n      this.queryParameters.replaceValues(\"startip\", ImmutableSet.of(startIP));\n      return this;\n   }\n\n   /**\n    * @param endIP\n    *           the ending IP address in the network IP range. If not specified, will be defaulted to startIP\n    */\n   public CreateNetworkOptions endIP(String endIP) {\n      this.queryParameters.replaceValues(\"endip\", ImmutableSet.of(endIP));\n      return this;\n   }\n\n   /**\n    * @param gateway\n    *           the gateway of the VLAN IP range\n    */\n   public CreateNetworkOptions gateway(String gateway) {\n      this.queryParameters.replaceValues(\"gateway\", ImmutableSet.of(gateway));\n      return this;\n   }\n\n   /**\n    * @param netmask\n    *           the netmask of the VLAN IP range\n    */\n   public CreateNetworkOptions netmask(String netmask) {\n      this.queryParameters.replaceValues(\"netmask\", ImmutableSet.of(netmask));\n      return this;\n   }\n\n   /**\n    * @param networkDomain\n    *           network domain\n    */\n   public CreateNetworkOptions networkDomain(String networkDomain) {\n      this.queryParameters.replaceValues(\"networkdomain\", ImmutableSet.of(networkDomain));\n      return this;\n   }\n\n   /**\n    * @param vlan\n    *           the ID or VID of the VLAN. Default is an \"untagged\" VLAN.\n    */\n   public CreateNetworkOptions vlan(String vlan) {\n      this.queryParameters.replaceValues(\"vlan\", ImmutableSet.of(vlan));\n      return this;\n   }\n\n   /**\n    * @param projectId\n    *          the project this network will be in.\n    */\n   public CreateNetworkOptions projectId(String projectId) {\n      this.queryParameters.replaceValues(\"projectid\", ImmutableSet.of(projectId + \"\"));\n      return this;\n   }\n\n   public static class Builder {\n      /**\n       * @see CreateNetworkOptions#isDefault\n       */\n      public static CreateNetworkOptions isDefault(boolean isDefault) {\n         CreateNetworkOptions options = new CreateNetworkOptions();\n         return options.isDefault(isDefault);\n      }\n\n      /**\n       * @see CreateNetworkOptions#isShared\n       */\n      public static CreateNetworkOptions isShared(boolean isShared) {\n         CreateNetworkOptions options = new CreateNetworkOptions();\n         return options.isShared(isShared);\n      }\n\n      /**\n       * @see CreateNetworkOptions#startIP(String)\n       */\n      public static CreateNetworkOptions startIP(String startIP) {\n         CreateNetworkOptions options = new CreateNetworkOptions();\n         return options.startIP(startIP);\n      }\n\n      /**\n       * @see CreateNetworkOptions#endIP(String)\n       */\n      public static CreateNetworkOptions endIP(String endIP) {\n         CreateNetworkOptions options = new CreateNetworkOptions();\n         return options.endIP(endIP);\n      }\n\n      /**\n       * @see CreateNetworkOptions#gateway(String)\n       */\n      public static CreateNetworkOptions gateway(String gateway) {\n         CreateNetworkOptions options = new CreateNetworkOptions();\n         return options.gateway(gateway);\n      }\n\n      /**\n       * @see CreateNetworkOptions#netmask(String)\n       */\n      public static CreateNetworkOptions netmask(String netmask) {\n         CreateNetworkOptions options = new CreateNetworkOptions();\n         return options.netmask(netmask);\n      }\n\n      /**\n       * @see CreateNetworkOptions#networkDomain(String)\n       */\n      public static CreateNetworkOptions networkDomain(String networkDomain) {\n         CreateNetworkOptions options = new CreateNetworkOptions();\n         return options.networkDomain(networkDomain);\n      }\n\n      /**\n       * @see CreateNetworkOptions#vlan(String)\n       */\n      public static CreateNetworkOptions vlan(String vlan) {\n         CreateNetworkOptions options = new CreateNetworkOptions();\n         return options.vlan(vlan);\n      }\n\n      /**\n       * @see CreateNetworkOptions#accountInDomain\n       */\n      public static CreateNetworkOptions accountInDomain(String account, String domain) {\n         CreateNetworkOptions options = new CreateNetworkOptions();\n         return options.accountInDomain(account, domain);\n      }\n\n      /**\n       * @see CreateNetworkOptions#domainId\n       */\n      public static CreateNetworkOptions domainId(String domainId) {\n         CreateNetworkOptions options = new CreateNetworkOptions();\n         return options.domainId(domainId);\n      }\n\n      /**\n       * @see CreateNetworkOptions#projectId(String)\n       */\n      public static CreateNetworkOptions projectId(String projectId) {\n         CreateNetworkOptions options = new CreateNetworkOptions();\n         return options.projectId(projectId);\n      }\n   }\n\n   /**\n    * Specify the account that will own the network. This can be run by a privileged user to be\n    * able to set advanced network properties, such as the VLAN tag, and then to immediately pass\n    * ownership of the network to an unprivileged user.\n    *\n    * Note that the unprivileged user will be able to delete the network later, since they are it's owner.\n    *\n    * @param account\n    *           account name\n    * @param domain\n    *           domain ID\n    */\n   @Override\n   public CreateNetworkOptions accountInDomain(String account, String domain) {\n      return CreateNetworkOptions.class.cast(super.accountInDomain(account, domain));\n   }\n\n   /**\n    * Specify the domain that will own the network. Any user in the domain can then use this\n    * network.\n    *\n    * CloudStack requires that when using this option, you also specify isShared(true).\n    *\n    * Changes or deletions to this network must be done by a domain admin in the same domain, or a\n    * global admin.\n    * \n    * @param domainId\n    *           domain ID\n    */\n   @Override\n   public CreateNetworkOptions domainId(String domainId) {\n      return CreateNetworkOptions.class.cast(super.domainId(domainId));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/CreatePodOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.cloudstack.domain.AllocationState;\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options to the GlobalPodApi.createPod API call.\n */\npublic class CreatePodOptions extends BaseHttpRequestOptions {\n\n   public static final CreatePodOptions NONE = new CreatePodOptions();\n   \n   public static class Builder {\n\n      public static CreatePodOptions allocationState(AllocationState allocationState) {\n         return new CreatePodOptions().allocationState(allocationState);\n      }\n\n   }\n\n   public CreatePodOptions allocationState(AllocationState allocationState) {\n      this.queryParameters.replaceValues(\"allocationstate\", ImmutableSet.of(allocationState.toString()));\n      return this;\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/CreateServiceOfferingOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.StorageType;\nimport org.jclouds.cloudstack.domain.SystemVmType;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options to control how service offerings are created\n * \n * @see <a\n *      href=\"http://download.cloud.com/releases/2.2.0/api_2.2.12/global_admin/createServiceOffering.html\"\n *      />\n */\npublic class CreateServiceOfferingOptions extends AccountInDomainOptions {\n\n   public static final CreateServiceOfferingOptions NONE = new CreateServiceOfferingOptions();\n\n   /**\n    * @param hostTags\n    *          the host tag for this service offering\n    */\n   public CreateServiceOfferingOptions hostTags(Set<String> hostTags) {\n      this.queryParameters.replaceValues(\"hosttags\", ImmutableSet.copyOf(hostTags));\n      return this;\n   }\n\n   /**\n    * @param isSystem\n    *          is this a system vm offering\n    */\n   public CreateServiceOfferingOptions isSystem(boolean isSystem) {\n      this.queryParameters.replaceValues(\"issystem\", ImmutableSet.<String>of(isSystem + \"\"));\n      return this;\n   }\n\n   /**\n    * @param limitCpuUse\n    *          restrict the CPU usage to committed service offering\n    */\n   public CreateServiceOfferingOptions limitCpuUse(boolean limitCpuUse) {\n      this.queryParameters.replaceValues(\"limitcpuuse\", ImmutableSet.<String>of(limitCpuUse + \"\"));\n      return this;\n   }\n\n   /**\n    * @param networkRateInMb\n    *          data transfer rate in megabits per second allowed. Supported only\n    *          for non-System offering and system offerings having \"domainrouter\"\n    *          systemvmtype\n    */\n   public CreateServiceOfferingOptions networkRateInMb(int networkRateInMb) {\n      this.queryParameters.replaceValues(\"networkrate\", ImmutableSet.<String>of(networkRateInMb + \"\"));\n      return this;\n   }\n\n   /**\n    * @param highlyAvailable\n    *          the HA for the service offering\n    */\n   public CreateServiceOfferingOptions highlyAvailable(boolean highlyAvailable) {\n      this.queryParameters.replaceValues(\"offerha\", ImmutableSet.<String>of(highlyAvailable + \"\"));\n      return this;\n   }\n\n   /**\n    * @param storageType\n    *          the storage type of the service offering\n    */\n   public CreateServiceOfferingOptions storageType(StorageType storageType) {\n      this.queryParameters.replaceValues(\"storagetype\", ImmutableSet.<String>of(storageType.toString()));\n      return this;\n   }\n\n   /**\n    * @param systemVmType\n    *          the system VM type. Possible types are \"domainrouter\", \"consoleproxy\" and \"secondarystoragevm\"\n    */\n   public CreateServiceOfferingOptions systemVmType(SystemVmType systemVmType) {\n      this.queryParameters.replaceValues(\"systemvmtype\", ImmutableSet.<String>of(systemVmType.toString()));\n      return this;\n   }\n\n   /**\n    * @param tags\n    *          the tags for this service offering\n    */\n   public CreateServiceOfferingOptions tags(Set<String> tags) {\n      this.queryParameters.replaceValues(\"tags\", ImmutableSet.copyOf(tags));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see CreateServiceOfferingOptions#hostTags\n       */\n      public static CreateServiceOfferingOptions hostTags(Set<String> hostTags) {\n         CreateServiceOfferingOptions options = new CreateServiceOfferingOptions();\n         return options.hostTags(hostTags);\n      }\n\n      /**\n       * @see CreateServiceOfferingOptions#isSystem\n       */\n      public static CreateServiceOfferingOptions isSystem(boolean isSystem) {\n         CreateServiceOfferingOptions options = new CreateServiceOfferingOptions();\n         return options.isSystem(isSystem);\n      }\n\n      /**\n       * @see CreateServiceOfferingOptions#limitCpuUse\n       */\n      public static CreateServiceOfferingOptions limitCpuUse(boolean limitCpuUse) {\n         CreateServiceOfferingOptions options = new CreateServiceOfferingOptions();\n         return options.limitCpuUse(limitCpuUse);\n      }\n\n      /**\n       * @see CreateServiceOfferingOptions#networkRateInMb\n       */\n      public static CreateServiceOfferingOptions networkRateInMb(int networkRate) {\n         CreateServiceOfferingOptions options = new CreateServiceOfferingOptions();\n         return options.networkRateInMb(networkRate);\n      }\n\n      /**\n       * @see CreateServiceOfferingOptions#highlyAvailable\n       */\n      public static CreateServiceOfferingOptions highlyAvailable(boolean highlyAvailable) {\n         CreateServiceOfferingOptions options = new CreateServiceOfferingOptions();\n         return options.highlyAvailable(highlyAvailable);\n      }\n\n      /**\n       * @see CreateServiceOfferingOptions#storageType\n       */\n      public static CreateServiceOfferingOptions storageType(StorageType storageType) {\n         CreateServiceOfferingOptions options = new CreateServiceOfferingOptions();\n         return options.storageType(storageType);\n      }\n\n      /**\n       * @see CreateServiceOfferingOptions#systemVmType\n       */\n      public static CreateServiceOfferingOptions systemVmType(SystemVmType systemVmType) {\n         CreateServiceOfferingOptions options = new CreateServiceOfferingOptions();\n         return options.systemVmType(systemVmType);\n      }\n\n      /**\n       * @see CreateServiceOfferingOptions#tags\n       */\n      public static CreateServiceOfferingOptions tags(Set<String> tags) {\n         CreateServiceOfferingOptions options = new CreateServiceOfferingOptions();\n         return options.tags(tags);\n      }\n\n      /**\n       * @see CreateServiceOfferingOptions#accountInDomain\n       */\n      public static CreateServiceOfferingOptions accountInDomain(String account, String domain) {\n         CreateServiceOfferingOptions options = new CreateServiceOfferingOptions();\n         return options.accountInDomain(account, domain);\n      }\n\n      /**\n       * @see CreateServiceOfferingOptions#domainId\n       */\n      public static CreateServiceOfferingOptions domainId(String domainId) {\n         CreateServiceOfferingOptions options = new CreateServiceOfferingOptions();\n         return options.domainId(domainId);\n      }\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public CreateServiceOfferingOptions accountInDomain(String account, String domain) {\n      return CreateServiceOfferingOptions.class.cast(super.accountInDomain(account, domain));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public CreateServiceOfferingOptions domainId(String domainId) {\n      return CreateServiceOfferingOptions.class.cast(super.domainId(domainId));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/CreateSnapshotOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options for the Snapshot createSnapshot method.\n *\n * @see org.jclouds.cloudstack.features.SnapshotApi#createSnapshot\n * @see org.jclouds.cloudstack.features.SnapshotApi#createSnapshot\n */\npublic class CreateSnapshotOptions extends AccountInDomainOptions {\n\n   public static final CreateSnapshotOptions NONE = new CreateSnapshotOptions(); \n\n   /**\n    * @param policyId policy id of the snapshot, if this is null, then use MANUAL_POLICY.\n    */\n   public CreateSnapshotOptions policyId(String policyId) {\n      this.queryParameters.replaceValues(\"policyid\", ImmutableSet.of(policyId + \"\"));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @param account The account of the snapshot.\n       * @param domainId The domain ID of the snapshot.\n       */\n      public static CreateSnapshotOptions accountInDomain(String account, String domainId) {\n         return (CreateSnapshotOptions) new CreateSnapshotOptions().accountInDomain(account, domainId);\n      }\n\n      /**\n       * @param domainId The domain ID of the snapshot.\n       */\n      public static CreateSnapshotOptions domainId(String domainId) {\n         return (CreateSnapshotOptions) new CreateSnapshotOptions().domainId(domainId);\n      }\n\n      /**\n       * @param policyId policy id of the snapshot, if this is null, then use MANUAL_POLICY.\n       */\n      public static CreateSnapshotOptions policyId(String policyId) {\n         return new CreateSnapshotOptions().policyId(policyId);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/CreateTagsOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport com.google.common.base.Joiner;\nimport com.google.common.collect.ImmutableSet;\nimport org.jclouds.cloudstack.domain.Tag;\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\n/**\n * Options used to control how tags are created.\n *\n * @see <a\n *      href=\"http://cloudstack.apache.org/docs/api/apidocs-4.3/root_admin/createTags.html\"\n *      />\n */\npublic class CreateTagsOptions extends BaseHttpRequestOptions {\n\n   public static final CreateTagsOptions NONE = new CreateTagsOptions();\n\n   /**\n    * Customer - optional\n    */\n   public CreateTagsOptions customer(String customer) {\n      this.queryParameters.replaceValues(\"customer\", ImmutableSet.of(customer));\n      return this;\n   }\n\n   /**\n    * Resource ID(s) to tag\n    */\n   public CreateTagsOptions resourceIds(Set<String> resourceIds) {\n      this.queryParameters.replaceValues(\"resourceids\", ImmutableSet.of(Joiner.on(\",\").join(resourceIds)));\n      return this;\n   }\n\n   /**\n    * Resource ID(s) to tag\n    */\n   public CreateTagsOptions resourceIds(String... resourceIds) {\n      this.queryParameters.replaceValues(\"resourceids\", ImmutableSet.of(Joiner.on(\",\").join(resourceIds)));\n      return this;\n   }\n\n   /**\n    * Resource type\n    */\n   public CreateTagsOptions resourceType(String resourceType) {\n      this.queryParameters.replaceValues(\"resourcetype\", ImmutableSet.of(resourceType));\n      return this;\n   }\n\n   /**\n    * Resource type\n    */\n   public CreateTagsOptions resourceType(Tag.ResourceType resourceType) {\n      this.queryParameters.replaceValues(\"resourcetype\", ImmutableSet.of(resourceType.toString()));\n      return this;\n   }\n\n   /**\n    * Tags to create\n    */\n   public CreateTagsOptions tags(Map<String, String> tags) {\n      int count = 0;\n      for (Map.Entry<String, String> entry : tags.entrySet()) {\n         this.queryParameters.replaceValues(String.format(\"tags[%d].key\", count), ImmutableSet.of(entry.getKey()));\n         this.queryParameters.replaceValues(String.format(\"tags[%d].value\", count),\n               ImmutableSet.of(entry.getValue()));\n         count += 1;\n      }\n      return this;\n   }\n\n   public static class Builder {\n\n      public static CreateTagsOptions customer(String customer) {\n         CreateTagsOptions options = new CreateTagsOptions();\n         return options.customer(customer);\n      }\n\n      public static CreateTagsOptions resourceIds(Set<String> resourceIds) {\n         CreateTagsOptions options = new CreateTagsOptions();\n         return options.resourceIds(resourceIds);\n      }\n\n      public static CreateTagsOptions resourceIds(String... resourceIds) {\n         CreateTagsOptions options = new CreateTagsOptions();\n         return options.resourceIds(resourceIds);\n      }\n\n      public static CreateTagsOptions resourceType(String resourceType) {\n         CreateTagsOptions options = new CreateTagsOptions();\n         return options.resourceType(resourceType);\n      }\n\n      public static CreateTagsOptions resourceType(Tag.ResourceType resourceType) {\n         CreateTagsOptions options = new CreateTagsOptions();\n         return options.resourceType(resourceType);\n      }\n\n      public static CreateTagsOptions tags(Map<String, String> tags) {\n         CreateTagsOptions options = new CreateTagsOptions();\n         return options.tags(tags);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/CreateTemplateOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options used to control how a template is created.\n *\n * @see <a\n *      href=\"http://download.cloud.com/releases/2.2.8/api/user/createTemplate.html\"\n *      />\n */\npublic class CreateTemplateOptions extends BaseHttpRequestOptions {\n\n   public static final CreateTemplateOptions NONE = new CreateTemplateOptions();\n\n   /**\n    * 32 or 64 bit\n    */\n   public CreateTemplateOptions bits(int bits) {\n      this.queryParameters.replaceValues(\"bits\", ImmutableSet.of(bits + \"\"));\n      return this;\n   }\n\n   /**\n    * true if this template is a featured template, false otherwise\n    */\n   public CreateTemplateOptions isFeatured(boolean isFeatured) {\n      this.queryParameters.replaceValues(\"isfeatured\", ImmutableSet.of(isFeatured + \"\"));\n      return this;\n   }\n\n   /**\n    * true if this template is a public template, false otherwise\n    */\n   public CreateTemplateOptions isPublic(boolean isPublic) {\n      this.queryParameters.replaceValues(\"ispublic\", ImmutableSet.of(isPublic + \"\"));\n      return this;\n   }\n\n   /**\n    * true if the template supports the password reset feature; default is false\n    */\n   public CreateTemplateOptions passwordEnabled(boolean passwordEnabled) {\n      this.queryParameters.replaceValues(\"passwordenabled\", ImmutableSet.of(passwordEnabled + \"\"));\n      return this;\n   }\n\n   /**\n    * true if the template requires HVM, false otherwise\n    */\n   public CreateTemplateOptions requiresHVM(boolean requiresHVM) {\n      this.queryParameters.replaceValues(\"requireshvm\", ImmutableSet.of(requiresHVM + \"\"));\n      return this;\n   }\n\n   /**\n    * the ID of the snapshot the template is being created from. Either this parameter, or volumeId has to be passed in\n    */\n   public CreateTemplateOptions snapshotId(String snapshotId) {\n      this.queryParameters.replaceValues(\"snapshotid\", ImmutableSet.of(snapshotId + \"\"));\n      return this;\n   }\n\n   /**\n    * the ID of the disk volume the template is being created from. Either this parameter, or snapshotId has to be passed in\n    */\n   public CreateTemplateOptions volumeId(String volumeId) {\n      this.queryParameters.replaceValues(\"volumeid\", ImmutableSet.of(volumeId + \"\"));\n      return this;\n   }\n   \n   public static class Builder {\n\n      public static CreateTemplateOptions bits(int bits) {\n         CreateTemplateOptions options = new CreateTemplateOptions();\n         return options.bits(bits);\n      }\n\n      public static CreateTemplateOptions isFeatured(boolean isFeatured) {\n         CreateTemplateOptions options = new CreateTemplateOptions();\n         return options.isFeatured(isFeatured);\n      }\n\n      public static CreateTemplateOptions isPublic(boolean isPublic) {\n         CreateTemplateOptions options = new CreateTemplateOptions();\n         return options.isPublic(isPublic);\n      }\n\n      public static CreateTemplateOptions passwordEnabled(boolean passwordEnabled) {\n         CreateTemplateOptions options = new CreateTemplateOptions();\n         return options.passwordEnabled(passwordEnabled);\n      }\n\n      public static CreateTemplateOptions requiresHVM(boolean requiresHVM) {\n         CreateTemplateOptions options = new CreateTemplateOptions();\n         return options.requiresHVM(requiresHVM);\n      }\n\n      public static CreateTemplateOptions snapshotId(String snapshotId) {\n         CreateTemplateOptions options = new CreateTemplateOptions();\n         return options.snapshotId(snapshotId);\n      }\n\n      public static CreateTemplateOptions volumeId(String volumeId) {\n         CreateTemplateOptions options = new CreateTemplateOptions();\n         return options.volumeId(volumeId);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/CreateUserOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Optional fields for user creation\n *\n * @see <a\n *      href=\"http://download.cloud.com/releases/2.2.0/api_2.2.12/global_admin/createUser.html\"\n *      />\n */\npublic class CreateUserOptions extends BaseHttpRequestOptions {\n\n   public static final CreateUserOptions NONE = new CreateUserOptions();\n\n   /**\n    * @param domainId The domain for the resource\n    */\n   public CreateUserOptions domainId(String domainId) {\n      this.queryParameters.replaceValues(\"domainid\", ImmutableSet.of(domainId + \"\"));\n      return this;\n\n   }\n\n   /**\n    * @param timezone Specifies a timezone for this command. For more information\n    *    on the timezone parameter, see Time Zone Format.\n    */\n   public CreateUserOptions timezone(String timezone) {\n      this.queryParameters.replaceValues(\"timezone\", ImmutableSet.of(timezone));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see CreateUserOptions#domainId\n       */\n      public static CreateUserOptions domainId(String domainId) {\n         CreateUserOptions options = new CreateUserOptions();\n         return options.domainId(domainId);\n      }\n\n      /**\n       * @see CreateUserOptions#timezone\n       */\n      public static CreateUserOptions timezone(String timezone) {\n         CreateUserOptions options = new CreateUserOptions();\n         return options.timezone(timezone);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/CreateVMGroupOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options used to control options for creating a VM group\n *\n * @see <a\n *      href=\"http://download.cloud.com/releases/2.2.8/api/user/createInstanceGroup.html\"\n *      />\n */\npublic class CreateVMGroupOptions extends BaseHttpRequestOptions {\n\n   public static final CreateVMGroupOptions NONE = new CreateVMGroupOptions();\n\n   /**\n    * @param account account who owns the VMGroup\n    */\n   public CreateVMGroupOptions account(String account) {\n      this.queryParameters.replaceValues(\"account\", ImmutableSet.of(account));\n      return this;\n   }\n\n   /**\n    * @param domainId domain ID of the account owning the VMGroup\n    */\n   public CreateVMGroupOptions domainId(String domainId) {\n      this.queryParameters.replaceValues(\"domainid\", ImmutableSet.of(domainId + \"\"));\n      return this;\n   }\n\n   /**\n    * @param projectId the project the vm group will be in\n    */\n   public CreateVMGroupOptions projectId(String projectId) {\n      this.queryParameters.replaceValues(\"projectid\", ImmutableSet.of(projectId + \"\"));\n      return this;\n   }\n\n   public static class Builder {\n      /**\n       * @see org.jclouds.cloudstack.options.CreateVMGroupOptions#account\n       */\n      public static CreateVMGroupOptions account(String account) {\n         CreateVMGroupOptions options = new CreateVMGroupOptions();\n         return options.account(account);\n      }\n\n      /**\n       * @see org.jclouds.cloudstack.options.CreateVMGroupOptions#domainId\n       */\n      public static CreateVMGroupOptions domainId(String id) {\n         CreateVMGroupOptions options = new CreateVMGroupOptions();\n         return options.domainId(id);\n      }\n\n      /**\n       * @see org.jclouds.cloudstack.options.CreateVMGroupOptions#projectId(String)\n       */\n      public static CreateVMGroupOptions projectId(String id) {\n         CreateVMGroupOptions options = new CreateVMGroupOptions();\n         return options.projectId(id);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/CreateVlanIPRangeOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options to the createVlanIPRange API call.\n */\npublic class CreateVlanIPRangeOptions extends AccountInDomainOptions {\n\n   public static class Builder {\n\n      public static CreateVlanIPRangeOptions accountInDomain(String account, String domain) {\n         return new CreateVlanIPRangeOptions().accountInDomain(account, domain);\n      }\n\n      public static CreateVlanIPRangeOptions domainId(String domainId) {\n         return new CreateVlanIPRangeOptions().domainId(domainId);\n      }\n\n      public static CreateVlanIPRangeOptions forVirtualNetwork(boolean forVirtualNetwork) {\n         return new CreateVlanIPRangeOptions().forVirtualNetwork(forVirtualNetwork);\n      }\n\n      public static CreateVlanIPRangeOptions zoneId(String zoneId) {\n         return new CreateVlanIPRangeOptions().zoneId(zoneId);\n      }\n\n      public static CreateVlanIPRangeOptions vlan(long vlan) {\n         return new CreateVlanIPRangeOptions().vlan(vlan);\n      }\n\n      public static CreateVlanIPRangeOptions vlan(String vlan) {\n         return new CreateVlanIPRangeOptions().vlan(vlan);\n      }\n\n      public static CreateVlanIPRangeOptions podId(String podId) {\n         return new CreateVlanIPRangeOptions().podId(podId);\n      }\n\n      public static CreateVlanIPRangeOptions gateway(String gateway) {\n         return new CreateVlanIPRangeOptions().gateway(gateway);\n      }\n\n      public static CreateVlanIPRangeOptions netmask(String netmask) {\n         return new CreateVlanIPRangeOptions().netmask(netmask);\n      }\n\n      public static CreateVlanIPRangeOptions networkId(String networkId) {\n         return new CreateVlanIPRangeOptions().networkId(networkId);\n      }\n\n      public static CreateVlanIPRangeOptions projectId(String projectId) {\n         return new CreateVlanIPRangeOptions().projectId(projectId);\n      }\n\n   }\n\n   @Override\n   public CreateVlanIPRangeOptions accountInDomain(String account, String domain) {\n      return (CreateVlanIPRangeOptions) super.accountInDomain(account, domain);\n   }\n\n   @Override\n   public CreateVlanIPRangeOptions domainId(String domainId) {\n      return (CreateVlanIPRangeOptions) super.domainId(domainId);\n   }\n\n   public CreateVlanIPRangeOptions forVirtualNetwork(boolean forVirtualNetwork) {\n      this.queryParameters.replaceValues(\"forvirtualnetwork\", ImmutableSet.of(forVirtualNetwork + \"\"));\n      return this;\n   }\n\n   public CreateVlanIPRangeOptions zoneId(String zoneId) {\n      this.queryParameters.replaceValues(\"zoneid\", ImmutableSet.of(zoneId + \"\"));\n      return this;\n   }\n\n   public CreateVlanIPRangeOptions vlan(long vlan) {\n      this.queryParameters.replaceValues(\"vlan\", ImmutableSet.of(vlan + \"\"));\n      return this;\n   }\n\n   public CreateVlanIPRangeOptions vlan(String vlan) {\n      this.queryParameters.replaceValues(\"vlan\", ImmutableSet.of(vlan));\n      return this;\n   }\n\n   public CreateVlanIPRangeOptions podId(String podId) {\n      this.queryParameters.replaceValues(\"podid\", ImmutableSet.of(podId + \"\"));\n      return this;\n   }\n\n   public CreateVlanIPRangeOptions gateway(String gateway) {\n      this.queryParameters.replaceValues(\"gateway\", ImmutableSet.of(gateway));\n      return this;\n   }\n\n   public CreateVlanIPRangeOptions netmask(String netmask) {\n      this.queryParameters.replaceValues(\"netmask\", ImmutableSet.of(netmask));\n      return this;\n   }\n\n   public CreateVlanIPRangeOptions networkId(String networkId) {\n      this.queryParameters.replaceValues(\"networkid\", ImmutableSet.of(networkId + \"\"));\n      return this;\n   }\n\n   public CreateVlanIPRangeOptions projectId(String projectId) {\n      this.queryParameters.replaceValues(\"projectid\", ImmutableSet.of(projectId + \"\"));\n      return this;\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/CreateZoneOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.cloudstack.domain.AllocationState;\nimport org.jclouds.http.options.BaseHttpRequestOptions;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options used to control how a zone is created\n * \n * @see <a href=\n *      \"http://download.cloud.com/releases/2.2.0/api_2.2.12/global_admin/createZone.html\"\n *      />\n */\npublic class CreateZoneOptions extends BaseHttpRequestOptions {\n\n   public static final CreateZoneOptions NONE = new CreateZoneOptions();\n\n   /**\n    * @param allocationState\n    *    allocation state of this Zone for allocation of new resources\n    */\n   public CreateZoneOptions allocationState(AllocationState allocationState) {\n      this.queryParameters.replaceValues(\"allocationstate\", ImmutableSet.of(allocationState.toString()));\n      return this;\n   }\n\n   /**\n    * @param dns2\n    *    the second DNS for the Zone\n    */\n   public CreateZoneOptions dns2(String dns2) {\n      this.queryParameters.replaceValues(\"dns2\", ImmutableSet.of(dns2));\n      return this;\n   }\n\n   /**\n    * @param internalDns2\n    *    the second internal DNS for the Zone\n    */\n   public CreateZoneOptions internalDns2(String internalDns2) {\n      this.queryParameters.replaceValues(\"internaldns2\", ImmutableSet.of(internalDns2));\n      return this;\n   }\n\n   /**\n    * @param domainName\n    *    network domain name for the networks in zone\n    */\n   public CreateZoneOptions domainName(String domainName) {\n      this.queryParameters.replaceValues(\"domain\", ImmutableSet.of(domainName));\n      return this;\n   }\n\n   /**\n    * @param domainId\n    *    the ID of the containing domain; null for public zones\n    */\n   public CreateZoneOptions domainId(@Nullable String domainId) {\n      this.queryParameters.replaceValues(\"domainid\", ImmutableSet.of(domainId + \"\"));\n      return this;\n   }\n\n   /**\n    * @param guestCIDRAddress\n    *    the guest CIDR address for the Zone\n    */\n   public CreateZoneOptions guestCIDRAddress(String guestCIDRAddress) {\n      this.queryParameters.replaceValues(\"guestcidraddress\", ImmutableSet.of(guestCIDRAddress));\n      return this;\n   }\n\n   /**\n    * @param securityGroupEnabled\n    *    true if network is security group enabled, false otherwise\n    */\n   public CreateZoneOptions securityGroupEnabled(boolean securityGroupEnabled) {\n      this.queryParameters.replaceValues(\"securitygroupenabled\", ImmutableSet.of(securityGroupEnabled + \"\"));\n      return this;\n   }\n\n   /**\n    * @param vlan\n    *    the VLAN for the Zone\n    */\n   public CreateZoneOptions vlan(String vlan) {\n      this.queryParameters.replaceValues(\"vlan\", ImmutableSet.of(vlan));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see CreateZoneOptions#allocationState\n       */\n      public static CreateZoneOptions allocationState(AllocationState allocationState) {\n         CreateZoneOptions options = new CreateZoneOptions();\n         return options.allocationState(allocationState);\n      }\n\n      /**\n       * @see CreateZoneOptions#dns2\n       */\n      public static CreateZoneOptions dns2(String dns2) {\n         CreateZoneOptions options = new CreateZoneOptions();\n         return options.dns2(dns2);\n      }\n\n      /**\n       * @see CreateZoneOptions#internalDns2\n       */\n      public static CreateZoneOptions internalDns2(String internalDns2) {\n         CreateZoneOptions options = new CreateZoneOptions();\n         return options.internalDns2(internalDns2);\n      }\n\n      /**\n       * @see CreateZoneOptions#domainName\n       */\n      public static CreateZoneOptions domainName(String domainName) {\n         CreateZoneOptions options = new CreateZoneOptions();\n         return options.domainName(domainName);\n      }\n\n      /**\n       * @see CreateZoneOptions#domainId\n       */\n      public static CreateZoneOptions domainId(@Nullable String domainId) {\n         CreateZoneOptions options = new CreateZoneOptions();\n         return options.domainId(domainId);\n      }\n\n      /**\n       * @see CreateZoneOptions#guestCIDRAddress\n       */\n      public static CreateZoneOptions guestCIDRAddress(String guestCIDRAddress) {\n         CreateZoneOptions options = new CreateZoneOptions();\n         return options.guestCIDRAddress(guestCIDRAddress);\n      }\n\n      /**\n       * @see CreateZoneOptions#securityGroupEnabled\n       */\n      public static CreateZoneOptions securityGroupEnabled(boolean securityGroupEnabled) {\n         CreateZoneOptions options = new CreateZoneOptions();\n         return options.securityGroupEnabled(securityGroupEnabled);\n      }\n\n      /**\n       * @see CreateZoneOptions#vlan\n       */\n      public static CreateZoneOptions vlan(String vlan) {\n         CreateZoneOptions options = new CreateZoneOptions();\n         return options.vlan(vlan);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/DeleteHostOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options to the GlobalHostApi.deleteHost() API call\n */\npublic class DeleteHostOptions extends BaseHttpRequestOptions {\n\n   public static final DeleteHostOptions NONE = new DeleteHostOptions();\n\n   /**\n    * @param forced Force delete the host. All HA enabled vms running on the host will be put to HA; HA disabled ones will be stopped\n    */\n   public DeleteHostOptions forced(boolean forced) {\n      this.queryParameters.replaceValues(\"forced\", ImmutableSet.of(forced + \"\"));\n      return this;\n   }\n\n   /**\n    * @param forceDestroyLocalStorage Force destroy local storage on this host. All VMs created on this local storage will be destroyed\n    */\n   public DeleteHostOptions forceDestroyLocalStorage(boolean forceDestroyLocalStorage) {\n      this.queryParameters.replaceValues(\"forcedestroylocalstorage\", ImmutableSet.of(forceDestroyLocalStorage + \"\"));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @param forced Force delete the host. All HA enabled vms running on the host will be put to HA; HA disabled ones will be stopped\n       */\n      public static DeleteHostOptions forced(boolean forced) {\n         return new DeleteHostOptions().forced(forced);\n      }\n\n      /**\n       * @param forceDestroyLocalStorage Force destroy local storage on this host. All VMs created on this local storage will be destroyed\n       */\n      public static DeleteHostOptions forceDestroyLocalStorage(boolean forceDestroyLocalStorage) {\n         return new DeleteHostOptions().forceDestroyLocalStorage(forceDestroyLocalStorage);\n      }\n\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/DeleteISOOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options for the ISO deleteISO method.\n *\n * @see org.jclouds.cloudstack.features.ISOApi#deleteISO\n * @see org.jclouds.cloudstack.features.ISOApi#deleteISO\n */\npublic class DeleteISOOptions extends BaseHttpRequestOptions {\n\n   public static final DeleteISOOptions NONE = new DeleteISOOptions();\n\n   /**\n    * @param zoneId the ID of the zone of the ISO file. If not specified, the ISO will be deleted from all the zones\n    */\n   public DeleteISOOptions zoneId(String zoneId) {\n      this.queryParameters.replaceValues(\"zoneid\", ImmutableSet.of(zoneId + \"\"));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @param zoneId the ID of the zone of the ISO file. If not specified, the ISO will be deleted from all the zones\n       */\n      public static DeleteISOOptions zoneId(String zoneId) {\n         return new DeleteISOOptions().zoneId(zoneId);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/DeleteTagsOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport com.google.common.base.Joiner;\nimport com.google.common.collect.ImmutableSet;\nimport org.jclouds.cloudstack.domain.Tag;\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\n/**\n * Options used to control how tags are created.\n *\n * @see <a\n *      href=\"http://cloudstack.apache.org/docs/api/apidocs-4.3/root_admin/createTags.html\"\n *      />\n */\npublic class DeleteTagsOptions extends BaseHttpRequestOptions {\n\n   public static final DeleteTagsOptions NONE = new DeleteTagsOptions();\n\n   /**\n    * Resource ID(s) to un-tag\n    */\n   public DeleteTagsOptions resourceIds(Set<String> resourceIds) {\n      this.queryParameters.replaceValues(\"resourceids\", ImmutableSet.of(Joiner.on(\",\").join(resourceIds)));\n      return this;\n   }\n\n   /**\n    * Resource ID(s) to un-tag\n    */\n   public DeleteTagsOptions resourceIds(String... resourceIds) {\n      this.queryParameters.replaceValues(\"resourceids\", ImmutableSet.of(Joiner.on(\",\").join(resourceIds)));\n      return this;\n   }\n\n   /**\n    * Resource type\n    */\n   public DeleteTagsOptions resourceType(String resourceType) {\n      this.queryParameters.replaceValues(\"resourcetype\", ImmutableSet.of(resourceType));\n      return this;\n   }\n\n   /**\n    * Resource type\n    */\n   public DeleteTagsOptions resourceType(Tag.ResourceType resourceType) {\n      this.queryParameters.replaceValues(\"resourcetype\", ImmutableSet.of(resourceType.toString()));\n      return this;\n   }\n\n   /**\n    * Tags to delete\n    */\n   public DeleteTagsOptions tags(Map<String, String> tags) {\n      int count = 0;\n      for (Map.Entry<String, String> entry : tags.entrySet()) {\n         this.queryParameters.replaceValues(String.format(\"tags[%d].key\", count), ImmutableSet.of(entry.getKey()));\n         this.queryParameters.replaceValues(String.format(\"tags[%d].value\", count),\n               ImmutableSet.of(entry.getValue()));\n         count += 1;\n      }\n      return this;\n   }\n\n   public static class Builder {\n\n      public static DeleteTagsOptions resourceIds(Set<String> resourceIds) {\n         DeleteTagsOptions options = new DeleteTagsOptions();\n         return options.resourceIds(resourceIds);\n      }\n\n      public static DeleteTagsOptions resourceIds(String... resourceIds) {\n         DeleteTagsOptions options = new DeleteTagsOptions();\n         return options.resourceIds(resourceIds);\n      }\n\n      public static DeleteTagsOptions resourceType(String resourceType) {\n         DeleteTagsOptions options = new DeleteTagsOptions();\n         return options.resourceType(resourceType);\n      }\n\n      public static DeleteTagsOptions resourceType(Tag.ResourceType resourceType) {\n         DeleteTagsOptions options = new DeleteTagsOptions();\n         return options.resourceType(resourceType);\n      }\n\n      public static DeleteTagsOptions tags(Map<String, String> tags) {\n         DeleteTagsOptions options = new DeleteTagsOptions();\n         return options.tags(tags);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/DeleteTemplateOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options used to control how a template is created.\n *\n * @see <a\n *      href=\"http://download.cloud.com/releases/2.2.8/api/user/createTemplate.html\"\n *      />\n */\npublic class DeleteTemplateOptions extends BaseHttpRequestOptions {\n\n   public static final DeleteTemplateOptions NONE = new DeleteTemplateOptions();\n\n   /**\n    * @param zoneId selects the template's zoneId.\n    */\n   public DeleteTemplateOptions zoneId(String zoneId) {\n      this.queryParameters.replaceValues(\"zoneid\", ImmutableSet.of(zoneId + \"\"));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see DeleteTemplateOptions#zoneId\n       */\n      public static DeleteTemplateOptions zoneId(String id) {\n         DeleteTemplateOptions options = new DeleteTemplateOptions();\n         return options.zoneId(id);\n      }\n\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/DeployVirtualMachineOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.io.BaseEncoding.base64;\n\nimport java.util.Map;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Joiner;\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\n\n/**\n * Options used to control what disk offerings are returned\n * \n * @see <a href=\n *      \"http://download.cloud.com/releases/2.2.0/api/user/deployVirtualMachine.html\"\n *      />\n */\npublic class DeployVirtualMachineOptions extends AccountInDomainOptions {\n\n   public static final DeployVirtualMachineOptions NONE = new DeployVirtualMachineOptions();\n\n   /**\n    * the ID of the disk offering for the virtual machine. If the template is of\n    * ISO format, the diskOfferingId is for the root disk volume. Otherwise this\n    * parameter is used to dinidcate the offering for the data disk volume. If\n    * the templateId parameter passed is from a Template object, the\n    * diskOfferingId refers to a DATA Disk Volume created. If the templateId\n    * parameter passed is from an ISO object, the diskOfferingId refers to a\n    * ROOT Disk Volume created.\n    * \n    * @param diskofferingid\n    *           the ID of the disk offering\n    */\n   public DeployVirtualMachineOptions diskOfferingId(String diskofferingid) {\n      checkArgument(!queryParameters.containsKey(\"size\"), \"Mutually exclusive with size\");\n      this.queryParameters.replaceValues(\"diskofferingid\", ImmutableSet.of(diskofferingid + \"\"));\n      return this;\n   }\n\n   /**\n    * sets the displayName - just for display purposes. We don't pass this\n    * parameter to the backend.\n    * \n    * @param displayName\n    *           an optional user generated name for the virtual machine\n    */\n   public DeployVirtualMachineOptions displayName(String displayName) {\n      this.queryParameters.replaceValues(\"displayname\", ImmutableSet.of(displayName));\n      return this;\n   }\n\n   /**\n    * @param group\n    *           an optional group for the virtual machine\n    */\n   public DeployVirtualMachineOptions group(String group) {\n      this.queryParameters.replaceValues(\"group\", ImmutableSet.of(group));\n      return this;\n   }\n\n   /**\n    * @param hypervisor\n    *           the hypervisor on which to deploy the virtual machine\n    */\n   public DeployVirtualMachineOptions hypervisor(String hypervisor) {\n      this.queryParameters.replaceValues(\"hypervisor\", ImmutableSet.of(hypervisor));\n      return this;\n   }\n\n   /**\n    * @param keyPair\n    *           name of the ssh key pair used to login to the virtual machine\n    */\n   public DeployVirtualMachineOptions keyPair(String keyPair) {\n      this.queryParameters.replaceValues(\"keypair\", ImmutableSet.of(keyPair));\n      return this;\n   }\n\n   /**\n    * sets the hostName, it will be propagated down to the backend and set on\n    * the user vm. If this parameter is not passed it, it will be defaulted to\n    * our usual \"i-x-y'\n    * \n    * @param name\n    *           host name for the virtual machine\n    */\n   public DeployVirtualMachineOptions name(String name) {\n      this.queryParameters.replaceValues(\"name\", ImmutableSet.of(name));\n      return this;\n   }\n\n   /**\n    * @param ipOnDefaultNetwork\n    *           the requested ip address (2.2.12 only option)\n    */\n   public DeployVirtualMachineOptions ipOnDefaultNetwork(String ipOnDefaultNetwork) {\n      this.queryParameters.replaceValues(\"ipaddress\", ImmutableSet.of(ipOnDefaultNetwork));\n      return this;\n   }\n\n   /**\n    * @param ipsToNetworks\n    *           mapping ip addresses to network ids (2.2.12 only option)\n    */\n   public DeployVirtualMachineOptions ipsToNetworks(Map<String, String> ipsToNetworks) {\n      int count = 0;\n      for (Map.Entry<String, String> entry : ipsToNetworks.entrySet()) {\n         this.queryParameters.replaceValues(String.format(\"iptonetworklist[%d].ip\", count), ImmutableSet.of(entry.getKey()));\n         this.queryParameters.replaceValues(String.format(\"iptonetworklist[%d].networkid\", count),\n               ImmutableSet.of(entry.getValue()));\n         count += 1;\n      }\n      return this;\n   }\n\n   /**\n    * @param networkId\n    *           network id used by virtual machine\n    */\n   public DeployVirtualMachineOptions networkId(String networkId) {\n      this.queryParameters.replaceValues(\"networkids\", ImmutableSet.of(networkId + \"\"));\n      return this;\n   }\n\n   /**\n    * @param networkIds\n    *           network ids used by virtual machine\n    */\n   public DeployVirtualMachineOptions networkIds(Iterable<String> networkIds) {\n      this.queryParameters.replaceValues(\"networkids\", ImmutableSet.of(Joiner.on(',').join(networkIds)));\n      return this;\n   }\n\n   public Iterable<String> getNetworkIds() {\n      if (queryParameters.get(\"networkids\").size() == 1) {\n         return Iterables.transform(\n               Splitter.on(\",\").split(Iterables.getOnlyElement(queryParameters.get(\"networkids\"))),\n               new Function<String, String>() {\n\n                  @Override\n                  public String apply(String arg0) {\n                     return arg0;\n                  }\n\n               });\n      } else {\n         return ImmutableSet.<String> of();\n      }\n   }\n\n   /**\n    * @param projectId  The project this VM will be in.\n    */\n   public DeployVirtualMachineOptions projectId(String projectId) {\n      this.queryParameters.replaceValues(\"projectid\", ImmutableSet.of(projectId + \"\"));\n      return this;\n   }\n\n   /**\n    * @param securityGroupId\n    *           security group applied to the virtual machine. Should be passed\n    *           only when vm is created from a zone with Basic Network support\n    */\n   public DeployVirtualMachineOptions securityGroupId(String securityGroupId) {\n      this.queryParameters.replaceValues(\"securitygroupids\", ImmutableSet.of(securityGroupId + \"\"));\n      return this;\n   }\n\n   /**\n    * @param securityGroupIds\n    *           security groups applied to the virtual machine. Should be passed\n    *           only when vm is created from a zone with Basic Network support\n    */\n   public DeployVirtualMachineOptions securityGroupIds(Iterable<String> securityGroupIds) {\n      this.queryParameters.replaceValues(\"securitygroupids\", ImmutableSet.of(Joiner.on(',').join(securityGroupIds)));\n      return this;\n   }\n\n   /**\n    * @param dataDiskSize\n    *           the arbitrary size for the DATADISK volume.\n    */\n   public DeployVirtualMachineOptions dataDiskSize(long dataDiskSize) {\n      this.queryParameters.replaceValues(\"size\", ImmutableSet.of(dataDiskSize + \"\"));\n      return this;\n   }\n\n   /**\n    * @param unencodedData\n    *           an optional binary data that can be sent to the virtual machine\n    *           upon a successful deployment. This binary data must be base64\n    *           encoded before adding it to the request. Currently only HTTP GET\n    *           is supported. Using HTTP GET (via querystring), you can send up\n    *           to 2KB of data after base64 encoding.\n    */\n   public DeployVirtualMachineOptions userData(byte[] unencodedData) {\n      int length = checkNotNull(unencodedData, \"unencodedData\").length;\n      checkArgument(length > 0, \"userData cannot be empty\");\n      checkArgument(length <= 2 * 1024, \"userData cannot be larger than 2kb\");\n      this.queryParameters.replaceValues(\"userdata\", ImmutableSet.of(base64().encode(unencodedData)));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see DeployVirtualMachineOptions#diskOfferingId\n       */\n      public static DeployVirtualMachineOptions diskOfferingId(String diskOfferingId) {\n         DeployVirtualMachineOptions options = new DeployVirtualMachineOptions();\n         return options.diskOfferingId(diskOfferingId);\n      }\n\n      /**\n       * @see DeployVirtualMachineOptions#displayName\n       */\n      public static DeployVirtualMachineOptions displayName(String displayName) {\n         DeployVirtualMachineOptions options = new DeployVirtualMachineOptions();\n         return options.displayName(displayName);\n      }\n\n      /**\n       * @see DeployVirtualMachineOptions#group\n       */\n      public static DeployVirtualMachineOptions group(String group) {\n         DeployVirtualMachineOptions options = new DeployVirtualMachineOptions();\n         return options.group(group);\n      }\n\n      /**\n       * @see DeployVirtualMachineOptions#hypervisor\n       */\n      public static DeployVirtualMachineOptions hypervisor(String hypervisor) {\n         DeployVirtualMachineOptions options = new DeployVirtualMachineOptions();\n         return options.hypervisor(hypervisor);\n      }\n\n      /**\n       * @see DeployVirtualMachineOptions#keyPair\n       */\n      public static DeployVirtualMachineOptions keyPair(String keyPair) {\n         DeployVirtualMachineOptions options = new DeployVirtualMachineOptions();\n         return options.keyPair(keyPair);\n      }\n\n      /**\n       * @see DeployVirtualMachineOptions#name\n       */\n      public static DeployVirtualMachineOptions name(String name) {\n         DeployVirtualMachineOptions options = new DeployVirtualMachineOptions();\n         return options.name(name);\n      }\n\n      /**\n       * @see DeployVirtualMachineOptions#ipOnDefaultNetwork\n       */\n      public static DeployVirtualMachineOptions ipOnDefaultNetwork(String ipOnDefaultNetwork) {\n         DeployVirtualMachineOptions options = new DeployVirtualMachineOptions();\n         return options.ipOnDefaultNetwork(ipOnDefaultNetwork);\n      }\n\n      /**\n       * @see DeployVirtualMachineOptions#ipsToNetworks\n       */\n      public static DeployVirtualMachineOptions ipsToNetworks(Map<String, String> ipsToNetworks) {\n         DeployVirtualMachineOptions options = new DeployVirtualMachineOptions();\n         return options.ipsToNetworks(ipsToNetworks);\n      }\n\n      /**\n       * @see DeployVirtualMachineOptions#networkId\n       */\n      public static DeployVirtualMachineOptions networkId(String id) {\n         DeployVirtualMachineOptions options = new DeployVirtualMachineOptions();\n         return options.networkId(id);\n      }\n\n      /**\n       * @see DeployVirtualMachineOptions#networkIds\n       */\n      public static DeployVirtualMachineOptions networkIds(Iterable<String> networkIds) {\n         DeployVirtualMachineOptions options = new DeployVirtualMachineOptions();\n         return options.networkIds(networkIds);\n      }\n\n      /**\n       * @see DeployVirtualMachineOptions#projectId(String)\n       */\n      public static DeployVirtualMachineOptions projectId(String id) {\n         DeployVirtualMachineOptions options = new DeployVirtualMachineOptions();\n         return options.projectId(id);\n      }\n\n      /**\n       * @see DeployVirtualMachineOptions#securityGroupId\n       */\n      public static DeployVirtualMachineOptions securityGroupId(String id) {\n         DeployVirtualMachineOptions options = new DeployVirtualMachineOptions();\n         return options.securityGroupId(id);\n      }\n\n      /**\n       * @see DeployVirtualMachineOptions#securityGroupIds\n       */\n      public static DeployVirtualMachineOptions securityGroupIds(Iterable<String> securityGroupIds) {\n         DeployVirtualMachineOptions options = new DeployVirtualMachineOptions();\n         return options.securityGroupIds(securityGroupIds);\n      }\n\n      /**\n       * @see DeployVirtualMachineOptions#dataDiskSize\n       */\n      public static DeployVirtualMachineOptions dataDiskSize(long id) {\n         DeployVirtualMachineOptions options = new DeployVirtualMachineOptions();\n         return options.dataDiskSize(id);\n      }\n\n      /**\n       * @see DeployVirtualMachineOptions#userData\n       */\n      public static DeployVirtualMachineOptions userData(byte[] unencodedData) {\n         DeployVirtualMachineOptions options = new DeployVirtualMachineOptions();\n         return options.userData(unencodedData);\n      }\n\n      /**\n       * @see DeployVirtualMachineOptions#accountInDomain\n       */\n      public static DeployVirtualMachineOptions accountInDomain(String account, String domain) {\n         DeployVirtualMachineOptions options = new DeployVirtualMachineOptions();\n         return options.accountInDomain(account, domain);\n      }\n\n      /**\n       * @see DeployVirtualMachineOptions#domainId\n       */\n      public static DeployVirtualMachineOptions domainId(String domainId) {\n         DeployVirtualMachineOptions options = new DeployVirtualMachineOptions();\n         return options.domainId(domainId);\n      }\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public DeployVirtualMachineOptions accountInDomain(String account, String domain) {\n      return DeployVirtualMachineOptions.class.cast(super.accountInDomain(account, domain));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public DeployVirtualMachineOptions domainId(String domainId) {\n      return DeployVirtualMachineOptions.class.cast(super.domainId(domainId));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/ExtractISOOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options for the ISO extractISO method.\n *\n * @see org.jclouds.cloudstack.features.ISOApi#extractISO\n * @see org.jclouds.cloudstack.features.ISOApi#extractISO\n */\npublic class ExtractISOOptions extends BaseHttpRequestOptions {\n\n   public static final ExtractISOOptions NONE = new ExtractISOOptions();\n\n   /**\n    * @param url the url to which the ISO would be extracted\n    */\n   public ExtractISOOptions url(String url) {\n      this.queryParameters.replaceValues(\"url\", ImmutableSet.of(url + \"\"));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @param url the url to which the ISO would be extracted\n       */\n      public static ExtractISOOptions url(String url) {\n         return new ExtractISOOptions().url(url);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/ExtractTemplateOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\npublic class ExtractTemplateOptions extends BaseHttpRequestOptions {\n\n   public static final ExtractTemplateOptions NONE = new ExtractTemplateOptions();\n\n   /**\n    * the url to which the ISO would be extracted\n    */\n   public ExtractTemplateOptions url(String url) {\n      this.queryParameters.replaceValues(\"url\", ImmutableSet.of(url));\n      return this;\n   }\n\n   public static class Builder {\n\n      public static ExtractTemplateOptions url(String url) {\n         ExtractTemplateOptions options = new ExtractTemplateOptions();\n         return options.url(url);\n      }\n\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/GenerateUsageRecordsOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options to the GlobalUsageApi.generateUsageOptions() API call\n */\npublic class GenerateUsageRecordsOptions extends BaseHttpRequestOptions {\n\n   public static final GenerateUsageRecordsOptions NONE = new GenerateUsageRecordsOptions();\n\n   public static class Builder {\n      public static GenerateUsageRecordsOptions domainId(String domainId) {\n         GenerateUsageRecordsOptions options = new GenerateUsageRecordsOptions();\n         return options.domainId(domainId);\n      }\n   }\n\n   public GenerateUsageRecordsOptions domainId(String domainId) {\n      this.queryParameters.replaceValues(\"domainid\", ImmutableSet.of(domainId + \"\"));\n      return this;\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/ListAccountsOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options used to control what account information is returned\n * \n * @see <a\n *      href=\"http://download.cloud.com/releases/2.2.0/api/user/listAccounts.html\"\n *      />\n */\npublic class ListAccountsOptions extends AccountInDomainOptions {\n\n   public static final ListAccountsOptions NONE = new ListAccountsOptions();\n\n   /**\n    * @param id\n    *           list account by account ID\n    */\n   public ListAccountsOptions id(String id) {\n      this.queryParameters.replaceValues(\"id\", ImmutableSet.of(id + \"\"));\n      return this;\n   }\n\n   /**\n    * @param name\n    *           list account by account name\n    */\n   public ListAccountsOptions name(String name) {\n      this.queryParameters.replaceValues(\"name\", ImmutableSet.of(name));\n      return this;\n   }\n\n   /**\n    * @param state\n    *           list accounts by state. Valid states are enabled, disabled, and\n    *           locked.\n    */\n   public ListAccountsOptions state(String state) {\n      this.queryParameters.replaceValues(\"state\", ImmutableSet.of(state));\n      return this;\n   }\n\n   /**\n    * @param cleanupRequired\n    *           list accounts by cleanuprequred attribute\n    */\n   public ListAccountsOptions cleanupRequired(boolean cleanupRequired) {\n      this.queryParameters.replaceValues(\"iscleanuprequired\", ImmutableSet.of(cleanupRequired + \"\"));\n      return this;\n   }\n\n   /**\n    * @param recursive\n    *           defaults to false, but if true, lists all accounts from the\n    *           parent specified by the domain id till leaves.\n    */\n   public ListAccountsOptions recursive(boolean recursive) {\n      this.queryParameters.replaceValues(\"isrecursive\", ImmutableSet.of(recursive + \"\"));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see ListAccountsOptions#accountInDomain\n       */\n      public static ListAccountsOptions accountInDomain(String account, String domain) {\n         ListAccountsOptions options = new ListAccountsOptions();\n         return options.accountInDomain(account, domain);\n      }\n\n      /**\n       * @see ListAccountsOptions#domainId\n       */\n      public static ListAccountsOptions domainId(String id) {\n         ListAccountsOptions options = new ListAccountsOptions();\n         return options.domainId(id);\n      }\n\n      /**\n       * @see ListAccountsOptions#id\n       */\n      public static ListAccountsOptions id(String id) {\n         ListAccountsOptions options = new ListAccountsOptions();\n         return options.id(id);\n      }\n\n      /**\n       * @see ListAccountsOptions#name\n       */\n      public static ListAccountsOptions name(String name) {\n         ListAccountsOptions options = new ListAccountsOptions();\n         return options.name(name);\n      }\n\n      /**\n       * @see ListAccountsOptions#state\n       */\n      public static ListAccountsOptions state(String state) {\n         ListAccountsOptions options = new ListAccountsOptions();\n         return options.state(state);\n      }\n\n      /**\n       * @see ListAccountsOptions#cleanupRequired\n       */\n      public static ListAccountsOptions cleanupRequired(boolean cleanupRequired) {\n         ListAccountsOptions options = new ListAccountsOptions();\n         return options.cleanupRequired(cleanupRequired);\n      }\n\n      /**\n       * @see ListAccountsOptions#recursive\n       */\n      public static ListAccountsOptions recursive(boolean recursive) {\n         ListAccountsOptions options = new ListAccountsOptions();\n         return options.recursive(recursive);\n      }\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ListAccountsOptions accountInDomain(String account, String domain) {\n      return ListAccountsOptions.class.cast(super.accountInDomain(account, domain));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ListAccountsOptions domainId(String domainId) {\n      return ListAccountsOptions.class.cast(super.domainId(domainId));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/ListAlertsOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options to the listAlerts command.\n */\npublic class ListAlertsOptions extends BaseHttpRequestOptions {\n\n   public static final ListAlertsOptions NONE = new ListAlertsOptions();\n\n   public ListAlertsOptions id(String id) {\n      this.queryParameters.replaceValues(\"id\", ImmutableSet.of(id + \"\"));\n      return this;\n   }\n\n   public ListAlertsOptions keyword(String keyword) {\n      this.queryParameters.replaceValues(\"keyword\", ImmutableSet.of(keyword));\n      return this;\n   }\n\n   public ListAlertsOptions type(String type) {\n      this.queryParameters.replaceValues(\"type\", ImmutableSet.of(type));\n      return this;\n   }\n\n   public static class Builder {\n\n      public static ListAlertsOptions id(String id) {\n         final ListAlertsOptions options = new ListAlertsOptions();\n         return options.id(id);\n      }\n\n      public static ListAlertsOptions keyword(String keyword) {\n         final ListAlertsOptions options = new ListAlertsOptions();\n         return options.keyword(keyword);\n      }\n\n      public static ListAlertsOptions type(String type) {\n         final ListAlertsOptions options = new ListAlertsOptions();\n         return options.type(type);\n      }\n\n   }\n\n}\n\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/ListAsyncJobsOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Date;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options used to control what asyncJobs information is returned\n * \n * @see <a\n *      href=\"http://download.cloud.com/releases/2.2.0/api/user/listAsyncJobs.html\"\n *      />\n */\npublic class ListAsyncJobsOptions extends AccountInDomainOptions {\n   private static final DateService dateService = new SimpleDateFormatDateService();\n\n   public static final ListAsyncJobsOptions NONE = new ListAsyncJobsOptions();\n\n   /**\n    * @param startDate\n    *           the start date of the async job\n    */\n   public ListAsyncJobsOptions startDate(Date startDate) {\n      this.queryParameters.replaceValues(\"startdate\",\n            ImmutableSet.of(dateService.iso8601SecondsDateFormat(checkNotNull(startDate, \"startDate\"))));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see ListAsyncJobsOptions#startDate\n       */\n      public static ListAsyncJobsOptions startDate(Date startDate) {\n         ListAsyncJobsOptions options = new ListAsyncJobsOptions();\n         return options.startDate(startDate);\n      }\n\n      /**\n       * @see ListAsyncJobsOptions#domainId\n       */\n      public static ListAsyncJobsOptions domainId(String id) {\n         ListAsyncJobsOptions options = new ListAsyncJobsOptions();\n         return options.domainId(id);\n      }\n\n      /**\n       * @see ListAsyncJobsOptions#accountInDomain\n       */\n      public static ListAsyncJobsOptions accountInDomain(String account, String domain) {\n         ListAsyncJobsOptions options = new ListAsyncJobsOptions();\n         return options.accountInDomain(account, domain);\n      }\n\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ListAsyncJobsOptions accountInDomain(String account, String domain) {\n      return ListAsyncJobsOptions.class.cast(super.accountInDomain(account, domain));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ListAsyncJobsOptions domainId(String domainId) {\n      return ListAsyncJobsOptions.class.cast(super.domainId(domainId));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/ListCapacityOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.cloudstack.domain.Capacity;\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options to the listCapacity command.\n */\npublic class ListCapacityOptions extends BaseHttpRequestOptions {\n\n   public static final ListCapacityOptions NONE = new ListCapacityOptions();\n\n   public ListCapacityOptions hostId(String hostId) {\n      this.queryParameters.replaceValues(\"hostid\", ImmutableSet.of(hostId + \"\"));\n      return this;\n   }\n\n   public ListCapacityOptions keyword(String keyword) {\n      this.queryParameters.replaceValues(\"keyword\", ImmutableSet.of(keyword));\n      return this;\n   }\n\n   public ListCapacityOptions podId(String podId) {\n      this.queryParameters.replaceValues(\"podid\", ImmutableSet.of(podId + \"\"));\n      return this;\n   }\n\n   public ListCapacityOptions type(Capacity.Type type) {\n      this.queryParameters.replaceValues(\"type\", ImmutableSet.of(type.ordinal() + \"\"));\n      return this;\n   }\n\n   public ListCapacityOptions zoneId(String zoneId) {\n      this.queryParameters.replaceValues(\"zoneid\", ImmutableSet.of(zoneId + \"\"));\n      return this;\n   }\n\n   public static class Builder {\n\n      public static ListCapacityOptions hostId(String hostId) {\n         final ListCapacityOptions options = new ListCapacityOptions();\n         return options.hostId(hostId);\n      }\n\n      public static ListCapacityOptions keyword(String keyword) {\n         final ListCapacityOptions options = new ListCapacityOptions();\n         return options.keyword(keyword);\n      }\n\n      public static ListCapacityOptions podId(String podId) {\n         final ListCapacityOptions options = new ListCapacityOptions();\n         return options.podId(podId);\n      }\n\n      public static ListCapacityOptions type(Capacity.Type type) {\n         final ListCapacityOptions options = new ListCapacityOptions();\n         return options.type(type);\n      }\n\n      public static ListCapacityOptions zoneId(String zoneId) {\n         final ListCapacityOptions options = new ListCapacityOptions();\n         return options.zoneId(zoneId);\n      }\n\n   }\n\n}\n\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/ListClustersOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.cloudstack.domain.AllocationState;\nimport org.jclouds.cloudstack.domain.Cluster;\nimport org.jclouds.cloudstack.domain.Host;\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options used to control what cluster information is returned\n *\n * @see <a\n *      href=\"http://download.cloud.com/releases/2.2.0/api_2.2.12/global_admin/listClusters.html\"\n *      />\n */\npublic class ListClustersOptions extends BaseHttpRequestOptions {\n\n   public static final ListHostsOptions NONE = new ListHostsOptions();\n\n   public ListClustersOptions allocationState(AllocationState allocationState) {\n      this.queryParameters.replaceValues(\"allocationstate\", ImmutableSet.of(allocationState.toString()));\n      return this;\n   }\n\n   public ListClustersOptions clusterType(Host.ClusterType clusterType) {\n      this.queryParameters.replaceValues(\"clustertype\", ImmutableSet.of(clusterType.toString()));\n      return this;\n   }\n\n   public ListClustersOptions hypervisor(String hypervisor) {\n      this.queryParameters.replaceValues(\"hypervisor\", ImmutableSet.of(hypervisor));\n      return this;\n   }\n\n   public ListClustersOptions id(String id) {\n      this.queryParameters.replaceValues(\"id\", ImmutableSet.of(id + \"\"));\n      return this;\n   }\n\n   public ListClustersOptions keyword(String keyword) {\n      this.queryParameters.replaceValues(\"keyword\", ImmutableSet.of(keyword));\n      return this;\n   }\n\n   public ListClustersOptions managedState(Cluster.ManagedState managedState) {\n      this.queryParameters.replaceValues(\"managedstate\", ImmutableSet.of(managedState.toString()));\n      return this;\n   }\n\n   public ListClustersOptions name(String name) {\n      this.queryParameters.replaceValues(\"name\", ImmutableSet.of(name));\n      return this;\n   }\n\n   public ListClustersOptions podId(String podId) {\n      this.queryParameters.replaceValues(\"podid\", ImmutableSet.of(podId + \"\"));\n      return this;\n   }\n\n   public ListClustersOptions zoneId(String zoneId) {\n      this.queryParameters.replaceValues(\"zoneid\", ImmutableSet.of(zoneId + \"\"));\n      return this;\n   }\n\n   public static class Builder {\n\n      public static ListClustersOptions allocationState(AllocationState allocationState) {\n         return new ListClustersOptions().allocationState(allocationState);\n      }\n\n      public static ListClustersOptions clusterType(Host.ClusterType clusterType) {\n         return new ListClustersOptions().clusterType(clusterType);\n      }\n\n      public static ListClustersOptions hypervisor(String hypervisor) {\n         return new ListClustersOptions().hypervisor(hypervisor);\n      }\n\n      public static ListClustersOptions id(String id) {\n         return new ListClustersOptions().id(id);\n      }\n\n      public static ListClustersOptions keyword(String keyword) {\n         return new ListClustersOptions().keyword(keyword);\n      }\n\n      public static ListClustersOptions managedState(Cluster.ManagedState managedState) {\n         return new ListClustersOptions().managedState(managedState);\n      }\n\n      public static ListClustersOptions name(String name) {\n         return new ListClustersOptions().name(name);\n      }\n\n      public static ListClustersOptions podId(String podId) {\n         return new ListClustersOptions().podId(podId);\n      }\n\n      public static ListClustersOptions zoneId(String zoneId) {\n         return new ListClustersOptions().zoneId(zoneId);\n      }\n\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/ListConfigurationEntriesOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options used to control what configuration entries are returned\n * \n * @see <a href=\n *      \"http://download.cloud.com/releases/2.2.0/api_2.2.12/global_admin/listConfigurations.html\"\n *      />\n */\npublic class ListConfigurationEntriesOptions extends BaseHttpRequestOptions {\n\n   public static final ListConfigurationEntriesOptions NONE = new ListConfigurationEntriesOptions();\n\n   /**\n    * @param category\n    *    list by category name\n    */\n   public ListConfigurationEntriesOptions category(String category) {\n      this.queryParameters.replaceValues(\"category\", ImmutableSet.of(category));\n      return this;\n   }\n\n   /**\n    * @param keyword\n    *    list by keyword\n    */\n   public ListConfigurationEntriesOptions keyword(String keyword) {\n      this.queryParameters.replaceValues(\"keyword\", ImmutableSet.of(keyword));\n      return this;\n   }\n\n   /**\n    * @param name\n    *    list by entry name\n    */\n   public ListConfigurationEntriesOptions name(String name) {\n      this.queryParameters.replaceValues(\"name\", ImmutableSet.of(name));\n      return this;\n   }\n\n   public ListConfigurationEntriesOptions page(long page) {\n      this.queryParameters.replaceValues(\"page\", ImmutableSet.of(page + \"\"));\n      return this;\n   }\n\n   public ListConfigurationEntriesOptions pageSize(long pageSize) {\n      this.queryParameters.replaceValues(\"pagesize\", ImmutableSet.of(pageSize + \"\"));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see ListConfigurationEntriesOptions#category\n       */\n      public static ListConfigurationEntriesOptions category(String category) {\n         ListConfigurationEntriesOptions options = new ListConfigurationEntriesOptions();\n         return options.category(category);\n      }\n\n      /**\n       * @see ListConfigurationEntriesOptions#keyword\n       */\n      public static ListConfigurationEntriesOptions keyword(String keyword) {\n         ListConfigurationEntriesOptions options = new ListConfigurationEntriesOptions();\n         return options.keyword(keyword);\n      }\n\n      /**\n       * @see ListConfigurationEntriesOptions#name\n       */\n      public static ListConfigurationEntriesOptions name(String name) {\n         ListConfigurationEntriesOptions options = new ListConfigurationEntriesOptions();\n         return options.name(name);\n      }\n\n      /**\n       * @see ListConfigurationEntriesOptions#page\n       */\n      public static ListConfigurationEntriesOptions page(long page) {\n         ListConfigurationEntriesOptions options = new ListConfigurationEntriesOptions();\n         return options.page(page);\n      }\n\n      /**\n       * @see ListConfigurationEntriesOptions#pageSize\n       */\n      public static ListConfigurationEntriesOptions pageSize(long pageSize) {\n         ListConfigurationEntriesOptions options = new ListConfigurationEntriesOptions();\n         return options.pageSize(pageSize);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/ListDiskOfferingsOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options used to control what disk offerings are returned\n * \n * @see <a href=\n *      \"http://download.cloud.com/releases/2.2.0/api/user/listDiskOfferings.html\"\n *      />\n */\npublic class ListDiskOfferingsOptions extends BaseHttpRequestOptions {\n\n   public static final ListDiskOfferingsOptions NONE = new ListDiskOfferingsOptions();\n\n   /**\n    * @param id\n    *           the ID of the disk offering\n    */\n   public ListDiskOfferingsOptions id(String id) {\n      this.queryParameters.replaceValues(\"id\", ImmutableSet.of(id + \"\"));\n      return this;\n   }\n\n   /**\n    * @param domainId\n    *           the ID of the domain associated with the disk offering\n    */\n   public ListDiskOfferingsOptions domainId(String domainId) {\n      this.queryParameters.replaceValues(\"domainid\", ImmutableSet.of(domainId + \"\"));\n      return this;\n\n   }\n\n   /**\n    * @param name\n    *           the disk offering name\n    */\n   public ListDiskOfferingsOptions name(String name) {\n      this.queryParameters.replaceValues(\"name\", ImmutableSet.of(name));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see ListDiskOfferingsOptions#name\n       */\n      public static ListDiskOfferingsOptions name(String name) {\n         ListDiskOfferingsOptions options = new ListDiskOfferingsOptions();\n         return options.name(name);\n      }\n\n      /**\n       * @see ListDiskOfferingsOptions#domainId\n       */\n      public static ListDiskOfferingsOptions domainId(String id) {\n         ListDiskOfferingsOptions options = new ListDiskOfferingsOptions();\n         return options.domainId(id);\n      }\n\n      /**\n       * @see ListDiskOfferingsOptions#id\n       */\n      public static ListDiskOfferingsOptions id(String id) {\n         ListDiskOfferingsOptions options = new ListDiskOfferingsOptions();\n         return options.id(id);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/ListDomainChildrenOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options used to control what domain children are returned\n * \n * @see <a href=\n *      \"http://download.cloud.com/releases/2.2.0/api_2.2.12/domain_admin/listDomains.html\"\n *      />\n */\npublic class ListDomainChildrenOptions extends BaseHttpRequestOptions {\n\n   public static final ListDomainChildrenOptions NONE = new ListDomainChildrenOptions();\n\n   /**\n    * @param parentDomainId\n    *    firewall rule ID\n    */\n   public ListDomainChildrenOptions parentDomainId(String parentDomainId) {\n      this.queryParameters.replaceValues(\"id\", ImmutableSet.of(parentDomainId + \"\"));\n      return this;\n   }\n\n   /**\n    * @param isRecursive\n    *    to return the entire tree, use the value \"true\". To return\n    *    the first level children, use the value \"false\".\n    */\n   public ListDomainChildrenOptions isRecursive(boolean isRecursive) {\n      this.queryParameters.replaceValues(\"isrecursive\", ImmutableSet.of(isRecursive + \"\"));\n      return this;\n   }\n\n   /**\n    * @param keyword\n    *    list by keyword\n    */\n   public ListDomainChildrenOptions keyword(String keyword) {\n      this.queryParameters.replaceValues(\"keyword\", ImmutableSet.of(keyword));\n      return this;\n   }\n\n   /**\n    * @param name\n    *    list by domain name\n    */\n   public ListDomainChildrenOptions name(String name) {\n      this.queryParameters.replaceValues(\"name\", ImmutableSet.of(name));\n      return this;\n   }\n\n   public ListDomainChildrenOptions page(long page) {\n      this.queryParameters.replaceValues(\"page\", ImmutableSet.of(page + \"\"));\n      return this;\n   }\n\n   public ListDomainChildrenOptions pageSize(long pageSize) {\n      this.queryParameters.replaceValues(\"pagesize\", ImmutableSet.of(pageSize + \"\"));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see ListDomainChildrenOptions#parentDomainId\n       */\n      public static ListDomainChildrenOptions parentDomainId(String parentDomainId) {\n         ListDomainChildrenOptions options = new ListDomainChildrenOptions();\n         return options.parentDomainId(parentDomainId);\n      }\n\n      /**\n       * @see ListDomainChildrenOptions#isRecursive\n       */\n      public static ListDomainChildrenOptions isRecursive(boolean isRecursive) {\n         ListDomainChildrenOptions options = new ListDomainChildrenOptions();\n         return options.isRecursive(isRecursive);\n      }\n\n      /**\n       * @see ListDomainChildrenOptions#keyword\n       */\n      public static ListDomainChildrenOptions keyword(String keyword) {\n         ListDomainChildrenOptions options = new ListDomainChildrenOptions();\n         return options.keyword(keyword);\n      }\n\n      /**\n       * @see ListDomainChildrenOptions#name\n       */\n      public static ListDomainChildrenOptions name(String name) {\n         ListDomainChildrenOptions options = new ListDomainChildrenOptions();\n         return options.name(name);\n      }\n\n      /**\n       * @see ListDomainChildrenOptions#page\n       */\n      public static ListDomainChildrenOptions page(long page) {\n         ListDomainChildrenOptions options = new ListDomainChildrenOptions();\n         return options.page(page);\n      }\n\n      /**\n       * @see ListDomainChildrenOptions#pageSize\n       */\n      public static ListDomainChildrenOptions pageSize(long pageSize) {\n         ListDomainChildrenOptions options = new ListDomainChildrenOptions();\n         return options.pageSize(pageSize);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/ListDomainsOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options used to control what domains are returned\n * \n * @see <a href=\n *      \"http://download.cloud.com/releases/2.2.0/api_2.2.12/domain_admin/listDomains.html\"\n *      />\n */\npublic class ListDomainsOptions extends BaseHttpRequestOptions {\n\n   public static final ListDomainsOptions NONE = new ListDomainsOptions();\n\n   /**\n    * @param id\n    *    firewall rule ID\n    */\n   public ListDomainsOptions id(String id) {\n      this.queryParameters.replaceValues(\"id\", ImmutableSet.of(id + \"\"));\n      return this;\n   }\n\n   /**\n    * @param keyword\n    *    list by keyword\n    */\n   public ListDomainsOptions keyword(String keyword) {\n      this.queryParameters.replaceValues(\"keyword\", ImmutableSet.of(keyword));\n      return this;\n   }\n\n   /**\n    * @param level\n    *    list by domain level\n    */\n   public ListDomainsOptions level(long level) {\n      this.queryParameters.replaceValues(\"level\", ImmutableSet.of(level + \"\"));\n      return this;\n   }\n\n   /**\n    * @param name\n    *    list by domain name\n    */\n   public ListDomainsOptions name(String name) {\n      this.queryParameters.replaceValues(\"name\", ImmutableSet.of(name));\n      return this;\n   }\n\n   public ListDomainsOptions page(long page) {\n      this.queryParameters.replaceValues(\"page\", ImmutableSet.of(page + \"\"));\n      return this;\n   }\n\n   public ListDomainsOptions pageSize(long pageSize) {\n      this.queryParameters.replaceValues(\"pagesize\", ImmutableSet.of(pageSize + \"\"));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see ListDomainsOptions#id\n       */\n      public static ListDomainsOptions id(String id) {\n         ListDomainsOptions options = new ListDomainsOptions();\n         return options.id(id);\n      }\n\n      /**\n       * @see ListDomainsOptions#keyword\n       */\n      public static ListDomainsOptions keyword(String keyword) {\n         ListDomainsOptions options = new ListDomainsOptions();\n         return options.keyword(keyword);\n      }\n\n      /**\n       * @see ListDomainsOptions#level\n       */\n      public static ListDomainsOptions level(long level) {\n         ListDomainsOptions options = new ListDomainsOptions();\n         return options.level(level);\n      }\n\n      /**\n       * @see ListDomainsOptions#name\n       */\n      public static ListDomainsOptions name(String name) {\n         ListDomainsOptions options = new ListDomainsOptions();\n         return options.name(name);\n      }\n\n      /**\n       * @see ListDomainsOptions#page\n       */\n      public static ListDomainsOptions page(long page) {\n         ListDomainsOptions options = new ListDomainsOptions();\n         return options.page(page);\n      }\n\n      /**\n       * @see ListDomainsOptions#pageSize\n       */\n      public static ListDomainsOptions pageSize(long pageSize) {\n         ListDomainsOptions options = new ListDomainsOptions();\n         return options.pageSize(pageSize);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/ListEgressFirewallRulesOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport java.util.Map;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options used to control what egress firewall rules are returned\n * \n * @see <a href=\n *      \"http://download.cloud.com/releases/3.0.6/api_3.0.6/root_admin/listEgressFirewallRules.html\"\n *      />\n */\npublic class ListEgressFirewallRulesOptions extends AccountInDomainOptions {\n\n   public static final ListEgressFirewallRulesOptions NONE = new ListEgressFirewallRulesOptions();\n\n   /**\n    * @param id\n    *    firewall rule ID\n    */\n   public ListEgressFirewallRulesOptions id(String id) {\n      this.queryParameters.replaceValues(\"id\", ImmutableSet.of(id + \"\"));\n      return this;\n   }\n\n   /**\n    * @param networkId\n    *    the id of network of the firewall services\n    */\n   public ListEgressFirewallRulesOptions networkId(String networkId) {\n      this.queryParameters.replaceValues(\"networkid\", ImmutableSet.of(networkId + \"\"));\n      return this;\n   }\n\n   /**\n    * @param ipAddressId\n    *    the id of IP address of the firewall services\n    */\n   public ListEgressFirewallRulesOptions ipAddressId(String ipAddressId) {\n      this.queryParameters.replaceValues(\"ipaddressid\", ImmutableSet.of(ipAddressId + \"\"));\n      return this;\n   }\n\n   /**\n    * @param projectId\n    *    List firewall rules in this project.\n    */\n   public ListEgressFirewallRulesOptions projectId(String projectId) {\n      this.queryParameters.replaceValues(\"projectid\", ImmutableSet.of(projectId + \"\"));\n      return this;\n   }\n\n   /**\n    * @param keyword\n    *    list by keyword\n    */\n   public ListEgressFirewallRulesOptions keyword(String keyword) {\n      this.queryParameters.replaceValues(\"keyword\", ImmutableSet.of(keyword));\n      return this;\n   }\n\n   public ListEgressFirewallRulesOptions page(long page) {\n      this.queryParameters.replaceValues(\"page\", ImmutableSet.of(page + \"\"));\n      return this;\n   }\n\n   public ListEgressFirewallRulesOptions pageSize(long pageSize) {\n      this.queryParameters.replaceValues(\"pagesize\", ImmutableSet.of(pageSize + \"\"));\n      return this;\n   }\n\n   /**\n    * @param tags\n    *           Key/value pairs for tags that need to be matched.\n    */\n   public ListEgressFirewallRulesOptions tags(Map<String, String> tags) {\n      int count = 0;\n      for (Map.Entry<String, String> entry : tags.entrySet()) {\n         this.queryParameters.replaceValues(String.format(\"tags[%d].key\", count), ImmutableSet.of(entry.getKey()));\n         this.queryParameters.replaceValues(String.format(\"tags[%d].value\", count),\n               ImmutableSet.of(entry.getValue()));\n         count += 1;\n      }\n      return this;\n   }\n\n\n   public static class Builder {\n\n      /**\n       * @see ListEgressFirewallRulesOptions#id\n       */\n      public static ListEgressFirewallRulesOptions id(String id) {\n         ListEgressFirewallRulesOptions options = new ListEgressFirewallRulesOptions();\n         return options.id(id);\n      }\n\n      /**\n       * @see ListEgressFirewallRulesOptions#networkId\n       */\n      public static ListEgressFirewallRulesOptions networkId(String networkId) {\n         ListEgressFirewallRulesOptions options = new ListEgressFirewallRulesOptions();\n         return options.networkId(networkId);\n      }\n\n      /**\n       * @see ListEgressFirewallRulesOptions#ipAddressId\n       */\n      public static ListEgressFirewallRulesOptions ipAddressId(String ipAddressId) {\n         ListEgressFirewallRulesOptions options = new ListEgressFirewallRulesOptions();\n         return options.ipAddressId(ipAddressId);\n      }\n\n      /**\n       * @see ListEgressFirewallRulesOptions#projectId(String)\n       */\n      public static ListEgressFirewallRulesOptions projectId(String projectId) {\n         ListEgressFirewallRulesOptions options = new ListEgressFirewallRulesOptions();\n         return options.projectId(projectId);\n      }\n\n      /**\n       * @see ListEgressFirewallRulesOptions#keyword\n       */\n      public static ListEgressFirewallRulesOptions keyword(String keyword) {\n         ListEgressFirewallRulesOptions options = new ListEgressFirewallRulesOptions();\n         return options.keyword(keyword);\n      }\n\n      /**\n       * @see ListEgressFirewallRulesOptions#page\n       */\n      public static ListEgressFirewallRulesOptions page(long page) {\n         ListEgressFirewallRulesOptions options = new ListEgressFirewallRulesOptions();\n         return options.page(page);\n      }\n\n      /**\n       * @see ListEgressFirewallRulesOptions#pageSize\n       */\n      public static ListEgressFirewallRulesOptions pageSize(long pageSize) {\n         ListEgressFirewallRulesOptions options = new ListEgressFirewallRulesOptions();\n         return options.pageSize(pageSize);\n      }\n\n      /**\n       * @see ListEgressFirewallRulesOptions#accountInDomain\n       */\n      public static ListEgressFirewallRulesOptions accountInDomain(String account, String domain) {\n         ListEgressFirewallRulesOptions options = new ListEgressFirewallRulesOptions();\n         return options.accountInDomain(account, domain);\n      }\n\n      /**\n       * @see ListEgressFirewallRulesOptions#domainId\n       */\n      public static ListEgressFirewallRulesOptions domainId(String id) {\n         ListEgressFirewallRulesOptions options = new ListEgressFirewallRulesOptions();\n         return options.domainId(id);\n      }\n\n      /**\n       * @see ListEgressFirewallRulesOptions#tags\n       */\n      public static ListEgressFirewallRulesOptions tags(Map<String, String> tags) {\n         ListEgressFirewallRulesOptions options = new ListEgressFirewallRulesOptions();\n         return options.tags(tags);\n      }\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ListEgressFirewallRulesOptions accountInDomain(String account, String domain) {\n      return ListEgressFirewallRulesOptions.class.cast(super.accountInDomain(account, domain));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ListEgressFirewallRulesOptions domainId(String domainId) {\n      return ListEgressFirewallRulesOptions.class.cast(super.domainId(domainId));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/ListEventsOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport java.util.Date;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options used to control what events are returned\n *\n * @see <a href=\n *      \"http://download.cloud.com/releases/2.2.0/api_2.2.12/user/listEvents.html\"\n *      />\n */\npublic class ListEventsOptions extends BaseHttpRequestOptions {\n   public static final ListEventsOptions NONE = new ListEventsOptions();\n\n   public ListEventsOptions account(String account) {\n      this.queryParameters.replaceValues(\"account\", ImmutableSet.of(account));\n      return this;\n   }\n\n   public ListEventsOptions domainId(String domainId) {\n      this.queryParameters.replaceValues(\"domainid\", ImmutableSet.of(domainId + \"\"));\n      return this;\n   }\n\n   public ListEventsOptions duration(String duration) {\n      this.queryParameters.replaceValues(\"duration\", ImmutableSet.of(duration));\n      return this;\n   }\n\n   public ListEventsOptions endDate(Date enddate) {\n      this.queryParameters.replaceValues(\"enddate\", ImmutableSet.of(enddate + \"\"));\n      return this;\n   }\n\n   public ListEventsOptions entryTime(Date entrytime) {\n      this.queryParameters.replaceValues(\"entrytime\", ImmutableSet.of(entrytime + \"\"));\n      return this;\n   }\n\n   public ListEventsOptions id(String id) {\n      this.queryParameters.replaceValues(\"id\", ImmutableSet.of(id));\n      return this;\n   }\n\n   public ListEventsOptions projectId(String projectId) {\n      this.queryParameters.replaceValues(\"projectid\", ImmutableSet.of(projectId + \"\"));\n      return this;\n   }\n\n   public ListEventsOptions keyword(String keyword) {\n      this.queryParameters.replaceValues(\"keyword\", ImmutableSet.of(keyword));\n      return this;\n   }\n\n   public ListEventsOptions level(String level) {\n      this.queryParameters.replaceValues(\"level\", ImmutableSet.of(level));\n      return this;\n   }\n\n   public ListEventsOptions type(String type) {\n      this.queryParameters.replaceValues(\"type\", ImmutableSet.of(type));\n      return this;\n   }\n\n\n   public static class Builder {\n      public static ListEventsOptions account(String account) {\n         final ListEventsOptions options = new ListEventsOptions();\n         return options.account(account);\n      }\n\n      public static ListEventsOptions domainId(String domainId) {\n         final ListEventsOptions options = new ListEventsOptions();\n         return options.domainId(domainId);\n      }\n\n      public static ListEventsOptions duration(String duration) {\n         final ListEventsOptions options = new ListEventsOptions();\n         return options.duration(duration);\n      }\n\n      public static ListEventsOptions endDate(Date enddate) {\n         final ListEventsOptions options = new ListEventsOptions();\n         return options.endDate(enddate);\n      }\n\n      public static ListEventsOptions entryTime(Date entrytime) {\n         final ListEventsOptions options = new ListEventsOptions();\n         return options.entryTime(entrytime);\n      }\n\n      public static ListEventsOptions id(String id) {\n         final ListEventsOptions options = new ListEventsOptions();\n         return options.id(id);\n      }\n\n      public static ListEventsOptions projectId(String projectId) {\n         final ListEventsOptions options = new ListEventsOptions();\n         return options.projectId(projectId);\n      }\n\n      public static ListEventsOptions keyword(String keyword) {\n         final ListEventsOptions options = new ListEventsOptions();\n         return options.keyword(keyword);\n      }\n\n      public static ListEventsOptions level(String level) {\n         final ListEventsOptions options = new ListEventsOptions();\n         return options.level(level);\n      }\n\n      public static ListEventsOptions type(String type) {\n         final ListEventsOptions options = new ListEventsOptions();\n         return options.type(type);\n      }\n\n   }\n\n}\n\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/ListFirewallRulesOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport java.util.Map;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options used to control what firewall rules are returned\n * \n * @see <a href=\n *      \"http://download.cloud.com/releases/2.2.0/api_2.2.12/global_admin/listFirewallRules.html\"\n *      />\n */\npublic class ListFirewallRulesOptions extends AccountInDomainOptions {\n\n   public static final ListFirewallRulesOptions NONE = new ListFirewallRulesOptions();\n\n   /**\n    * @param id\n    *    firewall rule ID\n    */\n   public ListFirewallRulesOptions id(String id) {\n      this.queryParameters.replaceValues(\"id\", ImmutableSet.of(id + \"\"));\n      return this;\n   }\n\n   /**\n    * @param ipAddressId\n    *    the id of IP address of the firewall services\n    */\n   public ListFirewallRulesOptions ipAddressId(String ipAddressId) {\n      this.queryParameters.replaceValues(\"ipaddressid\", ImmutableSet.of(ipAddressId + \"\"));\n      return this;\n   }\n\n   /**\n    * @param projectId\n    *    List firewall rules in this project.\n    */\n   public ListFirewallRulesOptions projectId(String projectId) {\n      this.queryParameters.replaceValues(\"projectid\", ImmutableSet.of(projectId + \"\"));\n      return this;\n   }\n\n   /**\n    * @param keyword\n    *    list by keyword\n    */\n   public ListFirewallRulesOptions keyword(String keyword) {\n      this.queryParameters.replaceValues(\"keyword\", ImmutableSet.of(keyword));\n      return this;\n   }\n\n   public ListFirewallRulesOptions page(long page) {\n      this.queryParameters.replaceValues(\"page\", ImmutableSet.of(page + \"\"));\n      return this;\n   }\n\n   public ListFirewallRulesOptions pageSize(long pageSize) {\n      this.queryParameters.replaceValues(\"pagesize\", ImmutableSet.of(pageSize + \"\"));\n      return this;\n   }\n\n   /**\n    * @param tags\n    *           Key/value pairs for tags that need to be matched.\n    */\n   public ListFirewallRulesOptions tags(Map<String, String> tags) {\n      int count = 0;\n      for (Map.Entry<String, String> entry : tags.entrySet()) {\n         this.queryParameters.replaceValues(String.format(\"tags[%d].key\", count), ImmutableSet.of(entry.getKey()));\n         this.queryParameters.replaceValues(String.format(\"tags[%d].value\", count),\n               ImmutableSet.of(entry.getValue()));\n         count += 1;\n      }\n      return this;\n   }\n\n\n   public static class Builder {\n\n      /**\n       * @see ListFirewallRulesOptions#id\n       */\n      public static ListFirewallRulesOptions id(String id) {\n         ListFirewallRulesOptions options = new ListFirewallRulesOptions();\n         return options.id(id);\n      }\n\n      /**\n       * @see ListFirewallRulesOptions#ipAddressId\n       */\n      public static ListFirewallRulesOptions ipAddressId(String ipAddressId) {\n         ListFirewallRulesOptions options = new ListFirewallRulesOptions();\n         return options.ipAddressId(ipAddressId);\n      }\n\n      /**\n       * @see ListFirewallRulesOptions#projectId(String)\n       */\n      public static ListFirewallRulesOptions projectId(String projectId) {\n         ListFirewallRulesOptions options = new ListFirewallRulesOptions();\n         return options.projectId(projectId);\n      }\n\n      /**\n       * @see ListFirewallRulesOptions#keyword\n       */\n      public static ListFirewallRulesOptions keyword(String keyword) {\n         ListFirewallRulesOptions options = new ListFirewallRulesOptions();\n         return options.keyword(keyword);\n      }\n\n      /**\n       * @see ListFirewallRulesOptions#page\n       */\n      public static ListFirewallRulesOptions page(long page) {\n         ListFirewallRulesOptions options = new ListFirewallRulesOptions();\n         return options.page(page);\n      }\n\n      /**\n       * @see ListFirewallRulesOptions#pageSize\n       */\n      public static ListFirewallRulesOptions pageSize(long pageSize) {\n         ListFirewallRulesOptions options = new ListFirewallRulesOptions();\n         return options.pageSize(pageSize);\n      }\n\n      /**\n       * @see ListFirewallRulesOptions#accountInDomain\n       */\n      public static ListFirewallRulesOptions accountInDomain(String account, String domain) {\n         ListFirewallRulesOptions options = new ListFirewallRulesOptions();\n         return options.accountInDomain(account, domain);\n      }\n\n      /**\n       * @see ListFirewallRulesOptions#domainId\n       */\n      public static ListFirewallRulesOptions domainId(String id) {\n         ListFirewallRulesOptions options = new ListFirewallRulesOptions();\n         return options.domainId(id);\n      }\n\n      /**\n       * @see ListFirewallRulesOptions#tags\n       */\n      public static ListFirewallRulesOptions tags(Map<String, String> tags) {\n         ListFirewallRulesOptions options = new ListFirewallRulesOptions();\n         return options.tags(tags);\n      }\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ListFirewallRulesOptions accountInDomain(String account, String domain) {\n      return ListFirewallRulesOptions.class.cast(super.accountInDomain(account, domain));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ListFirewallRulesOptions domainId(String domainId) {\n      return ListFirewallRulesOptions.class.cast(super.domainId(domainId));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/ListHostsOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.cloudstack.domain.AllocationState;\nimport org.jclouds.cloudstack.domain.Host;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options used to control what hosts information is returned\n *\n * @see <a\n *      href=\"http://download.cloud.com/releases/2.2.0/api_2.2.12/global_admin/listHosts.html\"\n *      />\n */\npublic class ListHostsOptions extends AccountInDomainOptions {\n\n   public static final ListHostsOptions NONE = new ListHostsOptions();\n\n   /**\n    * @param id the id of the host\n    */\n   public ListHostsOptions id(String id) {\n      this.queryParameters.replaceValues(\"id\", ImmutableSet.of(id + \"\"));\n      return this;\n   }\n\n   /**\n    * @param allocationState list hosts by allocation state\n    */\n   public ListHostsOptions allocationState(AllocationState allocationState) {\n      this.queryParameters.replaceValues(\"allocationstate\", ImmutableSet.of(allocationState.toString()));\n      return this;\n   }\n\n   /**\n    * @param clusterId lists hosts existing in particular cluster\n    */\n   public ListHostsOptions clusterId(String clusterId) {\n      this.queryParameters.replaceValues(\"clusterid\", ImmutableSet.of(clusterId + \"\"));\n      return this;\n   }\n\n   /**\n    * @param keyword List by keyword\n    */\n   public ListHostsOptions keyword(String keyword) {\n      this.queryParameters.replaceValues(\"keyword\", ImmutableSet.of(keyword));\n      return this;\n   }\n\n   /**\n    * @param name List by name\n    */\n   public ListHostsOptions name(String name) {\n      this.queryParameters.replaceValues(\"name\", ImmutableSet.of(name));\n      return this;\n   }\n\n   /**\n    * @param page\n    */\n   public ListHostsOptions page(long page) {\n      this.queryParameters.replaceValues(\"page\", ImmutableSet.of(page + \"\"));\n      return this;\n   }\n\n   /**\n    * @param pageSize the page size\n    */\n   public ListHostsOptions pageSize(long pageSize) {\n      this.queryParameters.replaceValues(\"pagesize\", ImmutableSet.of(pageSize + \"\"));\n      return this;\n   }\n\n   /**\n    * @param podId the Pod ID for the host\n    */\n   public ListHostsOptions podId(String podId) {\n      this.queryParameters.replaceValues(\"podid\", ImmutableSet.of(podId + \"\"));\n      return this;\n   }\n\n   /**\n    * @param state the state of the host\n    */\n   public ListHostsOptions state(String state) {\n      this.queryParameters.replaceValues(\"state\", ImmutableSet.of(state));\n      return this;\n   }\n\n   /**\n    * @param type the type of the host\n    */\n   public ListHostsOptions type(Host.Type type) {\n      this.queryParameters.replaceValues(\"type\", ImmutableSet.of(type.toString()));\n      return this;\n   }\n\n   /**\n    * @param virtualMachineId lists hosts in the same cluster as this VM and flag hosts with\n    *                         enough CPU/RAm to host this VM\n    */\n   public ListHostsOptions virtualMachineId(String virtualMachineId) {\n      this.queryParameters.replaceValues(\"virtualmachineid\", ImmutableSet.of(virtualMachineId + \"\"));\n      return this;\n   }\n\n   /**\n    * @param zoneId the Zone ID for the host\n    */\n   public ListHostsOptions zoneId(String zoneId) {\n      this.queryParameters.replaceValues(\"zoneid\", ImmutableSet.of(zoneId + \"\"));\n      return this;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ListHostsOptions accountInDomain(String account, String domain) {\n      return ListHostsOptions.class.cast(super.accountInDomain(account, domain));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ListHostsOptions domainId(String domainId) {\n      return ListHostsOptions.class.cast(super.domainId(domainId));\n   }\n\n   public static class Builder {\n      /**\n       * @see ListHostsOptions#id\n       */\n      public static ListHostsOptions id(String id) {\n         ListHostsOptions options = new ListHostsOptions();\n         return options.id(id);\n      }\n\n      /**\n       * @see ListHostsOptions#allocationState\n       */\n      public static ListHostsOptions allocationState(AllocationState allocationState) {\n         ListHostsOptions options = new ListHostsOptions();\n         return options.allocationState(allocationState);\n      }\n\n      /**\n       * @see ListHostsOptions#clusterId\n       */\n      public static ListHostsOptions clusterId(String clusterId) {\n         ListHostsOptions options = new ListHostsOptions();\n         return options.clusterId(clusterId);\n      }\n\n      /**\n       * @see ListHostsOptions#keyword(String)\n       */\n      public static ListHostsOptions keyword(String keyword) {\n         ListHostsOptions options = new ListHostsOptions();\n         return options.keyword(keyword);\n      }\n\n      /**\n       * @see ListHostsOptions#name(String)\n       */\n      public static ListHostsOptions name(String name) {\n         ListHostsOptions options = new ListHostsOptions();\n         return options.name(name);\n      }\n\n      /**\n       * @see ListHostsOptions#page\n       */\n      public static ListHostsOptions page(long page) {\n         ListHostsOptions options = new ListHostsOptions();\n         return options.page(page);\n      }\n\n      /**\n       * @see ListHostsOptions#pageSize\n       */\n      public static ListHostsOptions pageSize(long pageSize) {\n         ListHostsOptions options = new ListHostsOptions();\n         return options.pageSize(pageSize);\n      }\n\n      /**\n       * @see ListHostsOptions#podId\n       */\n      public static ListHostsOptions podId(String podId) {\n         ListHostsOptions options = new ListHostsOptions();\n         return options.podId(podId);\n      }\n\n      /**\n       * @see ListHostsOptions#state\n       */\n      public static ListHostsOptions state(String state) {\n         ListHostsOptions options = new ListHostsOptions();\n         return options.state(state);\n      }\n\n      /**\n       * @see ListHostsOptions#type\n       */\n      public static ListHostsOptions type(Host.Type type) {\n         ListHostsOptions options = new ListHostsOptions();\n         return options.type(type);\n      }\n\n      /**\n       * @see ListHostsOptions#virtualMachineId\n       */\n      public static ListHostsOptions virtualMachineId(String virtualMachineId) {\n         ListHostsOptions options = new ListHostsOptions();\n         return options.virtualMachineId(virtualMachineId);\n      }\n\n      /**\n       * @see ListHostsOptions#zoneId\n       */\n      public static ListHostsOptions zoneId(String zoneId) {\n         ListHostsOptions options = new ListHostsOptions();\n         return options.zoneId(zoneId);\n      }\n\n      /**\n       * @see ListHostsOptions#accountInDomain\n       */\n      public static ListHostsOptions accountInDomain(String account, String domain) {\n         ListHostsOptions options = new ListHostsOptions();\n         return options.accountInDomain(account, domain);\n      }\n\n      /**\n       * @see ListHostsOptions#domainId\n       */\n      public static ListHostsOptions domainId(String domainId) {\n         ListHostsOptions options = new ListHostsOptions();\n         return options.domainId(domainId);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/ListIPForwardingRulesOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport java.util.Map;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options used to control what ip forwarding rules are returned\n * \n * @see <a href=\n *      \"http://download.cloud.com/releases/2.2.0/api/user/listIpForwardingRules.html\"\n *      />\n */\npublic class ListIPForwardingRulesOptions extends AccountInDomainOptions {\n\n   public static final ListIPForwardingRulesOptions NONE = new ListIPForwardingRulesOptions();\n\n   /**\n    * @param id\n    *           Lists rule with the specified ID.\n    */\n   public ListIPForwardingRulesOptions id(String id) {\n      this.queryParameters.replaceValues(\"id\", ImmutableSet.of(id + \"\"));\n      return this;\n   }\n\n   /**\n    * @param IPAddressId\n    *           list the rule belonging to this public ip address\n    */\n   public ListIPForwardingRulesOptions IPAddressId(String IPAddressId) {\n      this.queryParameters.replaceValues(\"ipaddressid\", ImmutableSet.of(IPAddressId + \"\"));\n      return this;\n\n   }\n\n   /**\n    * @param virtualMachineId\n    *           Lists all rules applied to the specified Vm.\n    */\n   public ListIPForwardingRulesOptions virtualMachineId(String virtualMachineId) {\n      this.queryParameters.replaceValues(\"virtualmachineid\", ImmutableSet.of(virtualMachineId + \"\"));\n      return this;\n\n   }\n\n   /**\n    * @param projectId\n    *           Lists all rules applied to VMs in the given project.\n    */\n   public ListIPForwardingRulesOptions projectId(String projectId) {\n      this.queryParameters.replaceValues(\"projectid\", ImmutableSet.of(projectId + \"\"));\n      return this;\n\n   }\n\n   /**\n    * @param tags\n    *           Key/value pairs for tags that need to be matched.\n    */\n   public ListIPForwardingRulesOptions tags(Map<String, String> tags) {\n      int count = 0;\n      for (Map.Entry<String, String> entry : tags.entrySet()) {\n         this.queryParameters.replaceValues(String.format(\"tags[%d].key\", count), ImmutableSet.of(entry.getKey()));\n         this.queryParameters.replaceValues(String.format(\"tags[%d].value\", count),\n               ImmutableSet.of(entry.getValue()));\n         count += 1;\n      }\n      return this;\n   }\n\n\n   public static class Builder {\n\n      /**\n       * @see ListIPForwardingRulesOptions#accountInDomain\n       */\n      public static ListIPForwardingRulesOptions accountInDomain(String account, String domain) {\n         ListIPForwardingRulesOptions options = new ListIPForwardingRulesOptions();\n         return options.accountInDomain(account, domain);\n      }\n\n      /**\n       * @see ListIPForwardingRulesOptions#IPAddressId\n       */\n      public static ListIPForwardingRulesOptions IPAddressId(String IPAddressId) {\n         ListIPForwardingRulesOptions options = new ListIPForwardingRulesOptions();\n         return options.IPAddressId(IPAddressId);\n      }\n\n      /**\n       * @see ListIPForwardingRulesOptions#domainId\n       */\n      public static ListIPForwardingRulesOptions domainId(String id) {\n         ListIPForwardingRulesOptions options = new ListIPForwardingRulesOptions();\n         return options.domainId(id);\n      }\n\n      /**\n       * @see ListIPForwardingRulesOptions#id\n       */\n      public static ListIPForwardingRulesOptions id(String id) {\n         ListIPForwardingRulesOptions options = new ListIPForwardingRulesOptions();\n         return options.id(id);\n      }\n\n      /**\n       * @see ListIPForwardingRulesOptions#virtualMachineId\n       */\n      public static ListIPForwardingRulesOptions virtualMachineId(String virtualMachineId) {\n         ListIPForwardingRulesOptions options = new ListIPForwardingRulesOptions();\n         return options.virtualMachineId(virtualMachineId);\n      }\n\n      /**\n       * @see ListIPForwardingRulesOptions#projectId(String)\n       */\n      public static ListIPForwardingRulesOptions projectId(String projectId) {\n         ListIPForwardingRulesOptions options = new ListIPForwardingRulesOptions();\n         return options.projectId(projectId);\n      }\n\n      /**\n       * @see ListIPForwardingRulesOptions#tags\n       */\n      public static ListIPForwardingRulesOptions tags(Map<String, String> tags) {\n         ListIPForwardingRulesOptions options = new ListIPForwardingRulesOptions();\n         return options.tags(tags);\n      }\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ListIPForwardingRulesOptions accountInDomain(String account, String domain) {\n      return ListIPForwardingRulesOptions.class.cast(super.accountInDomain(account, domain));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ListIPForwardingRulesOptions domainId(String domainId) {\n      return ListIPForwardingRulesOptions.class.cast(super.domainId(domainId));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/ListISOsOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.ISO;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options for the ISO listISOs method.\n *\n * @see org.jclouds.cloudstack.features.ISOApi#listISOs\n * @see org.jclouds.cloudstack.features.ISOApi#listISOs\n */\npublic class ListISOsOptions extends AccountInDomainOptions {\n   public static final ListISOsOptions NONE = new ListISOsOptions();\n\n   private static final Set<String> TRUE = ImmutableSet.of(Boolean.toString(true));\n   private static final Set<String> FALSE = ImmutableSet.of(Boolean.toString(false));\n\n   /**\n    * the ISO is bootable\n    */\n   public ListISOsOptions bootable() {\n      this.queryParameters.replaceValues(\"bootable\", TRUE);\n      return this;\n   }\n\n   /**\n    * the ISO is bootable\n    */\n   public ListISOsOptions notBootable() {\n      this.queryParameters.replaceValues(\"bootable\", FALSE);\n      return this;\n   }\n\n   /**\n    * @param hypervisor the hypervisor for which to restrict the search\n    */\n   public ListISOsOptions hypervisor(String hypervisor) {\n      this.queryParameters.replaceValues(\"hypervisor\", ImmutableSet.of(hypervisor));\n      return this;\n   }\n\n   /**\n    * @param id list all isos by id\n    */\n   public ListISOsOptions id(String id) {\n      this.queryParameters.replaceValues(\"id\", ImmutableSet.of(id));\n      return this;\n   }\n\n   /**\n    * @param projectId list ISOs in the given project\n    */\n   public ListISOsOptions projectId(String projectId) {\n      this.queryParameters.replaceValues(\"projectid\", ImmutableSet.of(projectId + \"\"));\n      return this;\n   }\n\n   /**\n    * @param isoFilter possible values are \"featured\", \"self\", \"self-executable\",\"executable\", and \"community\".\n    */\n   public ListISOsOptions isoFilter(ISO.ISOFilter isoFilter) {\n      this.queryParameters.replaceValues(\"isofilter\", ImmutableSet.of(isoFilter.name()));\n      return this;\n   }\n\n   /**\n    * the ISO is publicly available to all users\n    */\n   public ListISOsOptions isPublic() {\n      this.queryParameters.replaceValues(\"ispublic\", TRUE);\n      return this;\n   }\n\n   /**\n    * the ISO is not publicly available to all users\n    */\n   public ListISOsOptions isPrivate() {\n      this.queryParameters.replaceValues(\"ispublic\", FALSE);\n      return this;\n   }\n\n   /**\n    * this ISO is ready to be deployed\n    */\n   public ListISOsOptions isReady() {\n      this.queryParameters.replaceValues(\"isready\", TRUE);\n      return this;\n   }\n\n   /**\n    * this ISO is not ready to be deployed\n    */\n   public ListISOsOptions isNotReady() {\n      this.queryParameters.replaceValues(\"isready\", FALSE);\n      return this;\n   }\n\n   /**\n    * @param keyword List by keyword\n    */\n   public ListISOsOptions keyword(String keyword) {\n      this.queryParameters.replaceValues(\"keyword\", ImmutableSet.of(keyword));\n      return this;\n   }\n\n   /**\n    * @param name list all isos by name\n    */\n   public ListISOsOptions name(String name) {\n      this.queryParameters.replaceValues(\"name\", ImmutableSet.of(name));\n      return this;\n   }\n\n   /**\n    * @param zoneId the ID of the zone\n    */\n   public ListISOsOptions zoneId(String zoneId) {\n      this.queryParameters.replaceValues(\"zoneid\", ImmutableSet.of(zoneId));\n      return this;\n   }\n\n   /**\n    * @param tags\n    *           Key/value pairs for tags that need to be matched.\n    */\n   public ListISOsOptions tags(Map<String, String> tags) {\n      int count = 0;\n      for (Map.Entry<String, String> entry : tags.entrySet()) {\n         this.queryParameters.replaceValues(String.format(\"tags[%d].key\", count), ImmutableSet.of(entry.getKey()));\n         this.queryParameters.replaceValues(String.format(\"tags[%d].value\", count),\n               ImmutableSet.of(entry.getValue()));\n         count += 1;\n      }\n      return this;\n   }\n\n   public static class Builder {\n      /**\n       * @param account the account of the ISO file. Must be used with the domainId parameter.\n       */\n      public static ListISOsOptions accountInDomain(String account, String domainId) {\n         return (ListISOsOptions) new ListISOsOptions().accountInDomain(account, domainId);\n      }\n\n      /**\n       * the ISO is bootable\n       */\n      public static ListISOsOptions bootable() {\n         return new ListISOsOptions().bootable();\n      }\n\n      /**\n       * the ISO is bootable\n       */\n      public static ListISOsOptions notBootable() {\n         return new ListISOsOptions().notBootable();\n      }\n\n      /**\n       * @param domainId lists all available ISO files by ID of a domain. If used with the account parameter, lists all available ISO files for the account in the ID of a domain.\n       */\n      public static ListISOsOptions domainId(String domainId) {\n         return (ListISOsOptions) new ListISOsOptions().domainId(domainId);\n      }\n\n      /**\n       * @param hypervisor the hypervisor for which to restrict the search\n       */\n      public static ListISOsOptions hypervisor(String hypervisor) {\n         return new ListISOsOptions().hypervisor(hypervisor);\n      }\n\n      /**\n       * @param id list all isos by id\n       */\n      public static ListISOsOptions id(String id) {\n         return new ListISOsOptions().id(id);\n      }\n\n      /**\n       * @param projectId list ISOs in project\n       */\n      public static ListISOsOptions projectId(String projectId) {\n         return new ListISOsOptions().projectId(projectId);\n      }\n\n      /**\n       * @param isoFilter possible values are \"featured\", \"self\", \"self-executable\",\"executable\", and \"community\".\n       */\n      public static ListISOsOptions isoFilter(ISO.ISOFilter isoFilter) {\n         return new ListISOsOptions().isoFilter(isoFilter);\n      }\n\n      /**\n       * the ISO is publicly available to all users\n       */\n      public static ListISOsOptions isPublic() {\n         return new ListISOsOptions().isPublic();\n      }\n\n      /**\n       * the ISO is not publicly available to all users\n       */\n      public static ListISOsOptions isPrivate() {\n         return new ListISOsOptions().isPrivate();\n      }\n\n      /**\n       * this ISO is ready to be deployed\n       */\n      public static ListISOsOptions isReady() {\n         return new ListISOsOptions().isReady();\n      }\n\n      /**\n       * this ISO is not ready to be deployed\n       */\n      public static ListISOsOptions isNotReady() {\n         return new ListISOsOptions().isNotReady();\n      }\n\n      /**\n       * @param keyword List by keyword\n       */\n      public static ListISOsOptions keyword(String keyword) {\n         return new ListISOsOptions().keyword(keyword);\n      }\n\n      /**\n       * @param name list all isos by name\n       */\n      public static ListISOsOptions name(String name) {\n         return new ListISOsOptions().name(name);\n      }\n\n      /**\n       * @param zoneId the ID of the zone\n       */\n      public static ListISOsOptions zoneId(String zoneId) {\n         return new ListISOsOptions().zoneId(zoneId);\n      }\n\n      /**\n       * @param tags\n       */\n      public static ListISOsOptions tags(Map<String, String> tags) {\n         return new ListISOsOptions().tags(tags);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/ListLoadBalancerRulesOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options used to control what load balancer rules are returned\n * \n * @see <a href=\n *      \"http://download.cloud.com/releases/2.2.0/api/user/listLoadBalancerRules.html\"\n *      />\n */\npublic class ListLoadBalancerRulesOptions extends AccountInDomainOptions {\n\n   public static final ListLoadBalancerRulesOptions NONE = new ListLoadBalancerRulesOptions();\n\n   /**\n    * @param id\n    *           Lists rule with the specified ID.\n    */\n   public ListLoadBalancerRulesOptions id(String id) {\n      this.queryParameters.replaceValues(\"id\", ImmutableSet.of(id + \"\"));\n      return this;\n   }\n\n   /**\n    * @param name\n    *           the name of the load balancer rule\n    */\n   public ListLoadBalancerRulesOptions name(String name) {\n      this.queryParameters.replaceValues(\"name\", ImmutableSet.of(name));\n      return this;\n   }\n\n   /**\n    * @param publicIPId\n    *           the public IP address id of the load balancer rule\n    */\n   public ListLoadBalancerRulesOptions publicIPId(String publicIPId) {\n      this.queryParameters.replaceValues(\"publicipid\", ImmutableSet.of(publicIPId + \"\"));\n      return this;\n   }\n\n   /**\n    * @param virtualMachineId\n    *           the ID of the virtual machine of the load balancer rule\n    */\n   public ListLoadBalancerRulesOptions virtualMachineId(String virtualMachineId) {\n      this.queryParameters.replaceValues(\"virtualmachineid\", ImmutableSet.of(virtualMachineId + \"\"));\n      return this;\n   }\n\n   /**\n    * @param zoneId the availability zone ID\n    */\n   public ListLoadBalancerRulesOptions zoneId(String zoneId) {\n      this.queryParameters.replaceValues(\"zoneid\", ImmutableSet.of(zoneId + \"\"));\n      return this;\n   }\n\n   /**\n    * @param projectId the project ID\n    */\n   public ListLoadBalancerRulesOptions projectId(String projectId) {\n      this.queryParameters.replaceValues(\"projectid\", ImmutableSet.of(projectId + \"\"));\n      return this;\n   }\n\n   /**\n    * @param page the number of the page\n    */\n   public ListLoadBalancerRulesOptions page(long page) {\n      this.queryParameters.replaceValues(\"page\", ImmutableSet.of(page + \"\"));\n      return this;\n   }\n\n   /**\n    * @param pageSize\n    */\n   public ListLoadBalancerRulesOptions pageSize(long pageSize) {\n      this.queryParameters.replaceValues(\"pagesize\", ImmutableSet.of(pageSize + \"\"));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see ListLoadBalancerRulesOptions#accountInDomain\n       */\n      public static ListLoadBalancerRulesOptions accountInDomain(String account, String domain) {\n         ListLoadBalancerRulesOptions options = new ListLoadBalancerRulesOptions();\n         return options.accountInDomain(account, domain);\n      }\n\n      /**\n       * @see ListLoadBalancerRulesOptions#publicIPId\n       */\n      public static ListLoadBalancerRulesOptions publicIPId(String publicIPId) {\n         ListLoadBalancerRulesOptions options = new ListLoadBalancerRulesOptions();\n         return options.publicIPId(publicIPId);\n      }\n\n      /**\n       * @see ListLoadBalancerRulesOptions#domainId\n       */\n      public static ListLoadBalancerRulesOptions domainId(String id) {\n         ListLoadBalancerRulesOptions options = new ListLoadBalancerRulesOptions();\n         return options.domainId(id);\n      }\n\n      /**\n       * @see ListLoadBalancerRulesOptions#name\n       */\n      public static ListLoadBalancerRulesOptions name(String name) {\n         ListLoadBalancerRulesOptions options = new ListLoadBalancerRulesOptions();\n         return options.name(name);\n      }\n\n      /**\n       * @see ListLoadBalancerRulesOptions#id\n       */\n      public static ListLoadBalancerRulesOptions id(String id) {\n         ListLoadBalancerRulesOptions options = new ListLoadBalancerRulesOptions();\n         return options.id(id);\n      }\n\n      /**\n       * @see ListLoadBalancerRulesOptions#virtualMachineId\n       */\n      public static ListLoadBalancerRulesOptions virtualMachineId(String virtualMachineId) {\n         ListLoadBalancerRulesOptions options = new ListLoadBalancerRulesOptions();\n         return options.virtualMachineId(virtualMachineId);\n      }\n\n      /**\n       * @see ListLoadBalancerRulesOptions#zoneId\n       */\n      public static ListLoadBalancerRulesOptions zoneId(String zoneId) {\n         ListLoadBalancerRulesOptions options = new ListLoadBalancerRulesOptions();\n         return options.zoneId(zoneId);\n      }\n\n      /**\n       * @see ListLoadBalancerRulesOptions#projectId(String)\n       */\n      public static ListLoadBalancerRulesOptions projectId(String projectId) {\n         ListLoadBalancerRulesOptions options = new ListLoadBalancerRulesOptions();\n         return options.projectId(projectId);\n      }\n\n      /**\n       * @see ListLoadBalancerRulesOptions#page\n       */\n      public static ListLoadBalancerRulesOptions page(long page) {\n         ListLoadBalancerRulesOptions options = new ListLoadBalancerRulesOptions();\n         return options.page(page);\n      }\n\n      /**\n       * @see ListLoadBalancerRulesOptions#pageSize\n       */\n      public static ListLoadBalancerRulesOptions pageSize(long pageSize) {\n         ListLoadBalancerRulesOptions options = new ListLoadBalancerRulesOptions();\n         return options.pageSize(pageSize);\n      }\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ListLoadBalancerRulesOptions accountInDomain(String account, String domain) {\n      return ListLoadBalancerRulesOptions.class.cast(super.accountInDomain(account, domain));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ListLoadBalancerRulesOptions domainId(String domainId) {\n      return ListLoadBalancerRulesOptions.class.cast(super.domainId(domainId));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/ListNetworkOfferingsOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.cloudstack.domain.NetworkOfferingAvailabilityType;\nimport org.jclouds.cloudstack.domain.TrafficType;\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options used to control what network offerings are returned\n * \n * @see <a href=\n *      \"http://download.cloud.com/releases/2.2.0/api_2.2.12/user/listNetworkOfferings.html\"\n *      />\n */\npublic class ListNetworkOfferingsOptions extends BaseHttpRequestOptions {\n\n   public static final ListNetworkOfferingsOptions NONE = new ListNetworkOfferingsOptions();\n\n   /**\n    * @param zoneId\n    *           list network offerings available for network creation in specific zone\n    */\n   public ListNetworkOfferingsOptions zoneId(String zoneId) {\n      this.queryParameters.replaceValues(\"zoneid\", ImmutableSet.of(zoneId + \"\"));\n      return this;\n   }\n   \n   /**\n    * @param id\n    *           the ID of the network offering\n    */\n   public ListNetworkOfferingsOptions id(String id) {\n      this.queryParameters.replaceValues(\"id\", ImmutableSet.of(id + \"\"));\n      return this;\n   }\n   \n   /**\n    * @param name\n    *           the network offering name\n    */\n   public ListNetworkOfferingsOptions name(String name) {\n      this.queryParameters.replaceValues(\"name\", ImmutableSet.of(name));\n      return this;\n   }\n\n   /**\n    * @param displayText\n    *           network offerings by display text\n    */\n   public ListNetworkOfferingsOptions displayText(String displayText) {\n      this.queryParameters.replaceValues(\"displaytext\", ImmutableSet.of(displayText));\n      return this;\n   }\n\n   /**\n    * @param availability\n    *           the availability of network offering. Default value is Required\n    */\n   public ListNetworkOfferingsOptions availability(NetworkOfferingAvailabilityType availability) {\n      this.queryParameters.replaceValues(\"availability\", ImmutableSet.of(availability.toString()));\n      return this;\n   }\n\n   /**\n    * @param isDefault\n    *           true if network offering is default, false otherwise\n    */\n   public ListNetworkOfferingsOptions isDefault(boolean isDefault) {\n      this.queryParameters.replaceValues(\"isdefault\", ImmutableSet.of(isDefault + \"\"));\n      return this;\n   }\n\n   /**\n    * @param isShared\n    *           true if network offering is shared, false otherwise\n    */\n   public ListNetworkOfferingsOptions isShared(boolean isShared) {\n      this.queryParameters.replaceValues(\"isshared\", ImmutableSet.of(isShared + \"\"));\n      return this;\n   }\n\n   /**\n    * @param specifyVLAN\n    *           True if we allow the network supports vlan, false otherwise. If\n    *           you create network using this offering, you must specify vlan.\n    */\n   public ListNetworkOfferingsOptions specifyVLAN(boolean specifyVLAN) {\n      this.queryParameters.replaceValues(\"specifyvlan\", ImmutableSet.of(specifyVLAN + \"\"));\n      return this;\n   }\n\n   /**\n    * @param trafficType\n    *           type of the traffic\n    */\n   public ListNetworkOfferingsOptions trafficType(TrafficType trafficType) {\n      this.queryParameters.replaceValues(\"traffictype\", ImmutableSet.of(trafficType.toString()));\n      return this;\n   }\n\n   public static class Builder {\n      /**\n       * @see ListNetworkOfferingsOptions#specifyVLAN\n       */\n      public static ListNetworkOfferingsOptions specifyVLAN(boolean specifyVLAN) {\n         ListNetworkOfferingsOptions options = new ListNetworkOfferingsOptions();\n         return options.specifyVLAN(specifyVLAN);\n      }\n\n      /**\n       * @see ListNetworkOfferingsOptions#isDefault\n       */\n      public static ListNetworkOfferingsOptions isDefault(boolean isDefault) {\n         ListNetworkOfferingsOptions options = new ListNetworkOfferingsOptions();\n         return options.isDefault(isDefault);\n      }\n\n      /**\n       * @see ListNetworkOfferingsOptions#isShared\n       */\n      public static ListNetworkOfferingsOptions isShared(boolean isShared) {\n         ListNetworkOfferingsOptions options = new ListNetworkOfferingsOptions();\n         return options.isShared(isShared);\n      }\n\n      /**\n       * @see ListNetworkOfferingsOptions#displayText\n       */\n      public static ListNetworkOfferingsOptions displayText(String displayText) {\n         ListNetworkOfferingsOptions options = new ListNetworkOfferingsOptions();\n         return options.displayText(displayText);\n      }\n\n      /**\n       * @see ListNetworkOfferingsOptions#name\n       */\n      public static ListNetworkOfferingsOptions name(String name) {\n         ListNetworkOfferingsOptions options = new ListNetworkOfferingsOptions();\n         return options.name(name);\n      }\n\n      /**\n       * @see ListNetworkOfferingsOptions#availability\n       */\n      public static ListNetworkOfferingsOptions availability(NetworkOfferingAvailabilityType availability) {\n         ListNetworkOfferingsOptions options = new ListNetworkOfferingsOptions();\n         return options.availability(availability);\n      }\n\n      /**\n       * @see ListNetworkOfferingsOptions#id\n       */\n      public static ListNetworkOfferingsOptions id(String id) {\n         ListNetworkOfferingsOptions options = new ListNetworkOfferingsOptions();\n         return options.id(id);\n      }\n\n      /**\n       * @see ListNetworkOfferingsOptions#zoneId\n       */\n      public static ListNetworkOfferingsOptions zoneId(String zoneId) {\n         ListNetworkOfferingsOptions options = new ListNetworkOfferingsOptions();\n         return options.zoneId(zoneId);\n      }\n\n      /**\n       * @see ListNetworkOfferingsOptions#trafficType\n       */\n      public static ListNetworkOfferingsOptions trafficType(TrafficType trafficType) {\n         ListNetworkOfferingsOptions options = new ListNetworkOfferingsOptions();\n         return options.trafficType(trafficType);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/ListNetworksOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport java.util.Map;\n\nimport org.jclouds.cloudstack.domain.NetworkType;\nimport org.jclouds.cloudstack.domain.TrafficType;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options used to control what networks information is returned\n * \n * @see <a\n *      href=\"http://download.cloud.com/releases/2.2.0/api/user/listNetworks.html\"\n *      />\n */\npublic class ListNetworksOptions extends AccountInDomainOptions {\n\n   public static final ListNetworksOptions NONE = new ListNetworksOptions();\n\n   /**\n    * @param isDefault true if network is default, false otherwise\n    */\n   public ListNetworksOptions isDefault(boolean isDefault) {\n      this.queryParameters.replaceValues(\"isdefault\", ImmutableSet.of(isDefault + \"\"));\n      return this;\n   }\n\n   /**\n    * @param isShared true if network is shared, false otherwise\n    */\n   public ListNetworksOptions isShared(boolean isShared) {\n      this.queryParameters.replaceValues(\"isshared\", ImmutableSet.of(isShared + \"\"));\n      return this;\n   }\n\n   /**\n    * @param isSystem true if network is system, false otherwise\n    */\n   public ListNetworksOptions isSystem(boolean isSystem) {\n      this.queryParameters.replaceValues(\"issystem\", ImmutableSet.of(isSystem + \"\"));\n      return this;\n   }\n\n   /**\n    * @param type the type of the network\n    */\n   public ListNetworksOptions type(NetworkType type) {\n      this.queryParameters.replaceValues(\"type\", ImmutableSet.of(type.toString()));\n      return this;\n   }\n\n   /**\n    * @param id list networks by id\n    */\n   public ListNetworksOptions id(String id) {\n      this.queryParameters.replaceValues(\"id\", ImmutableSet.of(id + \"\"));\n      return this;\n   }\n\n   /**\n    * @param zoneId the Zone ID of the network\n    */\n   public ListNetworksOptions zoneId(String zoneId) {\n      this.queryParameters.replaceValues(\"zoneid\", ImmutableSet.of(zoneId + \"\"));\n      return this;\n\n   }\n\n   /**\n    * @param projectId the project ID of the network\n    */\n   public ListNetworksOptions projectId(String projectId) {\n      this.queryParameters.replaceValues(\"projectid\", ImmutableSet.of(projectId + \"\"));\n      return this;\n\n   }\n\n   /**\n    * @param trafficType type of the traffic\n    */\n   public ListNetworksOptions trafficType(TrafficType trafficType) {\n      this.queryParameters.replaceValues(\"traffictype\", ImmutableSet.of(trafficType.toString()));\n      return this;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ListNetworksOptions accountInDomain(String account, String domain) {\n      return ListNetworksOptions.class.cast(super.accountInDomain(account, domain));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ListNetworksOptions domainId(String domainId) {\n      return ListNetworksOptions.class.cast(super.domainId(domainId));\n   }\n\n   /**\n    * @param tags\n    *           Key/value pairs for tags that need to be matched.\n    */\n   public ListNetworksOptions tags(Map<String, String> tags) {\n      int count = 0;\n      for (Map.Entry<String, String> entry : tags.entrySet()) {\n         this.queryParameters.replaceValues(String.format(\"tags[%d].key\", count), ImmutableSet.of(entry.getKey()));\n         this.queryParameters.replaceValues(String.format(\"tags[%d].value\", count),\n               ImmutableSet.of(entry.getValue()));\n         count += 1;\n      }\n      return this;\n   }\n\n   public static class Builder {\n      /**\n       * @see ListNetworksOptions#isDefault\n       */\n      public static ListNetworksOptions isDefault(boolean isDefault) {\n         ListNetworksOptions options = new ListNetworksOptions();\n         return options.isDefault(isDefault);\n      }\n\n      /**\n       * @see ListNetworksOptions#isShared\n       */\n      public static ListNetworksOptions isShared(boolean isShared) {\n         ListNetworksOptions options = new ListNetworksOptions();\n         return options.isShared(isShared);\n      }\n\n      /**\n       * @see ListNetworksOptions#isSystem\n       */\n      public static ListNetworksOptions isSystem(boolean isSystem) {\n         ListNetworksOptions options = new ListNetworksOptions();\n         return options.isSystem(isSystem);\n      }\n\n      /**\n       * @see ListNetworksOptions#type\n       */\n      public static ListNetworksOptions type(NetworkType type) {\n         ListNetworksOptions options = new ListNetworksOptions();\n         return options.type(type);\n      }\n\n      /**\n       * @see ListNetworksOptions#id\n       */\n      public static ListNetworksOptions id(String id) {\n         ListNetworksOptions options = new ListNetworksOptions();\n         return options.id(id);\n      }\n\n      /**\n       * @see ListNetworksOptions#zoneId\n       */\n      public static ListNetworksOptions zoneId(String id) {\n         ListNetworksOptions options = new ListNetworksOptions();\n         return options.zoneId(id);\n      }\n\n      /**\n       * @see ListNetworksOptions#projectId(String)\n       */\n      public static ListNetworksOptions projectId(String id) {\n         ListNetworksOptions options = new ListNetworksOptions();\n         return options.projectId(id);\n      }\n\n      /**\n       * @see ListNetworksOptions#trafficType\n       */\n      public static ListNetworksOptions trafficType(TrafficType trafficType) {\n         ListNetworksOptions options = new ListNetworksOptions();\n         return options.trafficType(trafficType);\n      }\n\n      /**\n       * @see ListNetworksOptions#accountInDomain\n       */\n      public static ListNetworksOptions accountInDomain(String account, String domain) {\n         ListNetworksOptions options = new ListNetworksOptions();\n         return options.accountInDomain(account, domain);\n      }\n\n      /**\n       * @see ListNetworksOptions#domainId\n       */\n      public static ListNetworksOptions domainId(String domainId) {\n         ListNetworksOptions options = new ListNetworksOptions();\n         return options.domainId(domainId);\n      }\n\n      /**\n       * @see ListNetworksOptions#tags\n       */\n      public static ListNetworksOptions tags(Map<String, String> tags) {\n         ListNetworksOptions options = new ListNetworksOptions();\n         return options.tags(tags);\n      }\n   }\n}\n\n\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/ListOSTypesOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options used to control what OSType information is returned\n * \n * @see <a\n *      href=\"http://download.cloud.com/releases/2.2.0/api/user/listOsTypes.html\"\n *      />\n */\npublic class ListOSTypesOptions extends BaseHttpRequestOptions {\n\n   public static final ListOSTypesOptions NONE = new ListOSTypesOptions();\n\n   /**\n    * @param id\n    *           list by Os type Id\n    */\n   public ListOSTypesOptions id(String id) {\n      this.queryParameters.replaceValues(\"id\", ImmutableSet.of(id + \"\"));\n      return this;\n   }\n\n   /**\n    * @param OSCategoryId\n    *           list by Os Category id\n    */\n   public ListOSTypesOptions OSCategoryId(String OSCategoryId) {\n      this.queryParameters.replaceValues(\"oscategoryid\", ImmutableSet.of(OSCategoryId + \"\"));\n      return this;\n   }\n\n   public static class Builder {\n      /**\n       * @see ListOSTypesOptions#id\n       */\n      public static ListOSTypesOptions id(String id) {\n         ListOSTypesOptions options = new ListOSTypesOptions();\n         return options.id(id);\n      }\n\n      /**\n       * @see ListOSTypesOptions#OSCategoryId\n       */\n      public static ListOSTypesOptions OSCategoryId(String id) {\n         ListOSTypesOptions options = new ListOSTypesOptions();\n         return options.OSCategoryId(id);\n      }\n\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/ListPodsOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.cloudstack.domain.AllocationState;\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options to the GlobalPodApi.listPods API call.\n */\npublic class ListPodsOptions extends BaseHttpRequestOptions {\n\n   public static final ListPodsOptions NONE = new ListPodsOptions();\n   \n   public static class Builder {\n\n      public static ListPodsOptions allocationState(AllocationState allocationState) {\n         return new ListPodsOptions().allocationState(allocationState);\n      }\n\n      public static ListPodsOptions id(String id) {\n         return new ListPodsOptions().id(id);\n      }\n\n      public static ListPodsOptions keyword(String keyword) {\n         return new ListPodsOptions().keyword(keyword);\n      }\n\n      public static ListPodsOptions name(String name) {\n         return new ListPodsOptions().name(name);\n      }\n\n      public static ListPodsOptions zoneId(String zoneId) {\n         return new ListPodsOptions().zoneId(zoneId);\n      }\n\n   }\n\n   public ListPodsOptions allocationState(AllocationState allocationState) {\n      this.queryParameters.replaceValues(\"allocationstate\", ImmutableSet.of(allocationState.toString()));\n      return this;\n   }\n\n   public ListPodsOptions id(String id) {\n      this.queryParameters.replaceValues(\"id\", ImmutableSet.of(id + \"\"));\n      return this;\n   }\n\n   public ListPodsOptions keyword(String keyword) {\n      this.queryParameters.replaceValues(\"keyword\", ImmutableSet.of(keyword));\n      return this;\n   }\n\n   public ListPodsOptions name(String name) {\n      this.queryParameters.replaceValues(\"name\", ImmutableSet.of(name));\n      return this;\n   }\n\n   public ListPodsOptions zoneId(String zoneId) {\n      this.queryParameters.replaceValues(\"zoneid\", ImmutableSet.of(zoneId + \"\"));\n      return this;\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/ListPortForwardingRulesOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport java.util.Map;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options used to control what port forwarding rules are returned\n *\n * @see <a href=\n *      \"http://download.cloud.com/releases/2.2.0/api_2.2.12/global_admin/listPortForwardingRules.html\"\n *      />\n */\npublic class ListPortForwardingRulesOptions extends AccountInDomainOptions {\n\n   public static final ListPortForwardingRulesOptions NONE = new ListPortForwardingRulesOptions();\n\n   /**\n    * @param id\n    *       lists rule with the specified ID\n    */\n   public ListPortForwardingRulesOptions id(String id) {\n      this.queryParameters.replaceValues(\"id\", ImmutableSet.of(id + \"\"));\n      return this;\n   }\n\n   /**\n    * @param IPAddressId\n    *       list the rule belonging to this public ip address\n    */\n   public ListPortForwardingRulesOptions ipAddressId(String IPAddressId) {\n      this.queryParameters.replaceValues(\"ipaddressid\", ImmutableSet.of(IPAddressId + \"\"));\n      return this;\n\n   }\n\n   /**\n    * @param projectId\n    *       list the rules in this project\n    */\n   public ListPortForwardingRulesOptions projectId(String projectId) {\n      this.queryParameters.replaceValues(\"projectid\", ImmutableSet.of(projectId + \"\"));\n      return this;\n\n   }\n\n   /**\n    * @param tags\n    *           Key/value pairs for tags that need to be matched.\n    */\n   public ListPortForwardingRulesOptions tags(Map<String, String> tags) {\n      int count = 0;\n      for (Map.Entry<String, String> entry : tags.entrySet()) {\n         this.queryParameters.replaceValues(String.format(\"tags[%d].key\", count), ImmutableSet.of(entry.getKey()));\n         this.queryParameters.replaceValues(String.format(\"tags[%d].value\", count),\n               ImmutableSet.of(entry.getValue()));\n         count += 1;\n      }\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see ListPortForwardingRulesOptions#id\n       */\n      public static ListPortForwardingRulesOptions id(String id) {\n         ListPortForwardingRulesOptions options = new ListPortForwardingRulesOptions();\n         return options.id(id);\n      }\n\n      /**\n       * @see ListPortForwardingRulesOptions#ipAddressId\n       */\n      public static ListPortForwardingRulesOptions ipAddressId(String ipAddressId) {\n         ListPortForwardingRulesOptions options = new ListPortForwardingRulesOptions();\n         return options.ipAddressId(ipAddressId);\n      }\n\n      /**\n       * @see ListPortForwardingRulesOptions#projectId(String)\n       */\n      public static ListPortForwardingRulesOptions projectId(String projectId) {\n         ListPortForwardingRulesOptions options = new ListPortForwardingRulesOptions();\n         return options.projectId(projectId);\n      }\n\n      /**\n       * @see ListPortForwardingRulesOptions#accountInDomain\n       */\n      public static ListPortForwardingRulesOptions accountInDomain(String account, String domain) {\n         ListPortForwardingRulesOptions options = new ListPortForwardingRulesOptions();\n         return options.accountInDomain(account, domain);\n      }\n\n      /**\n       * @see ListPortForwardingRulesOptions#domainId\n       */\n      public static ListPortForwardingRulesOptions domainId(String id) {\n         ListPortForwardingRulesOptions options = new ListPortForwardingRulesOptions();\n         return options.domainId(id);\n      }\n\n      /**\n       * @see ListPortForwardingRulesOptions#tags\n       */\n      public static ListPortForwardingRulesOptions tags(Map<String, String> tags) {\n         ListPortForwardingRulesOptions options = new ListPortForwardingRulesOptions();\n         return options.tags(tags);\n      }\n   }\n\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ListPortForwardingRulesOptions accountInDomain(String account, String domain) {\n      return ListPortForwardingRulesOptions.class.cast(super.accountInDomain(account, domain));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ListPortForwardingRulesOptions domainId(String domainId) {\n      return ListPortForwardingRulesOptions.class.cast(super.domainId(domainId));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/ListProjectsOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport java.util.Map;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options used to control what account information is returned\n * \n * @see <a\n *      href=\"http://download.cloud.com/releases/3.0.6/api_3.0.6/root_admin/listProjects.html\"\n *      />\n */\npublic class ListProjectsOptions extends AccountInDomainOptions {\n\n   public static final ListProjectsOptions NONE = new ListProjectsOptions();\n\n   /**\n    * @param id\n    *           list projects by project ID\n    */\n   public ListProjectsOptions id(String id) {\n      this.queryParameters.replaceValues(\"id\", ImmutableSet.of(id));\n      return this;\n   }\n\n   /**\n    * @param name\n    *           list project by project name\n    */\n   public ListProjectsOptions name(String name) {\n      this.queryParameters.replaceValues(\"name\", ImmutableSet.of(name));\n      return this;\n   }\n\n   /**\n    * @param state\n    *           list projects by state. Valid states are enabled, disabled, and\n    *           locked.\n    */\n   public ListProjectsOptions state(String state) {\n      this.queryParameters.replaceValues(\"state\", ImmutableSet.of(state));\n      return this;\n   }\n\n   /**\n    * @param displayText\n    *           list projects by displayText.\n    */\n   public ListProjectsOptions displayText(String displayText) {\n      this.queryParameters.replaceValues(\"displaytext\", ImmutableSet.of(displayText));\n      return this;\n   }\n\n   /**\n    * @param keyword\n    *           list projects by keyword.\n    */\n   public ListProjectsOptions keyword(String keyword) {\n      this.queryParameters.replaceValues(\"keyword\", ImmutableSet.of(keyword));\n      return this;\n   }\n\n   /**\n    * @param recursive\n    *           defaults to false, but if true, lists all projects from the\n    *           parent specified by the domain id till leaves.\n    */\n   public ListProjectsOptions recursive(boolean recursive) {\n      this.queryParameters.replaceValues(\"isrecursive\", ImmutableSet.of(recursive + \"\"));\n      return this;\n   }\n\n   /**\n    * @param tags\n    *           Key/value pairs for tags that need to be matched.\n    */\n   public ListProjectsOptions tags(Map<String, String> tags) {\n      int count = 0;\n      for (Map.Entry<String, String> entry : tags.entrySet()) {\n         this.queryParameters.replaceValues(String.format(\"tags[%d].key\", count), ImmutableSet.of(entry.getKey()));\n         this.queryParameters.replaceValues(String.format(\"tags[%d].value\", count),\n               ImmutableSet.of(entry.getValue()));\n         count += 1;\n      }\n      return this;\n   }\n   \n   public ListProjectsOptions page(Long page) {\n      this.queryParameters.replaceValues(\"page\", ImmutableSet.of(page + \"\"));\n      return this;\n   }\n   \n   public ListProjectsOptions pageSize(Long pageSize) {\n      this.queryParameters.replaceValues(\"pagesize\", ImmutableSet.of(pageSize + \"\"));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see org.jclouds.cloudstack.options.ListProjectsOptions#accountInDomain(String, String)\n       */\n      public static ListProjectsOptions accountInDomain(String project, String domain) {\n         ListProjectsOptions options = new ListProjectsOptions();\n         return options.accountInDomain(project, domain);\n      }\n\n      /**\n       * @see org.jclouds.cloudstack.options.ListProjectsOptions#domainId\n       */\n      public static ListProjectsOptions domainId(String domainId) {\n         ListProjectsOptions options = new ListProjectsOptions();\n         return options.domainId(domainId);\n      }\n\n      /**\n       * @see org.jclouds.cloudstack.options.ListProjectsOptions#id\n       */\n      public static ListProjectsOptions id(String id) {\n         ListProjectsOptions options = new ListProjectsOptions();\n         return options.id(id);\n      }\n\n      /**\n       * @see org.jclouds.cloudstack.options.ListProjectsOptions#name\n       */\n      public static ListProjectsOptions name(String name) {\n         ListProjectsOptions options = new ListProjectsOptions();\n         return options.name(name);\n      }\n\n      /**\n       * @see org.jclouds.cloudstack.options.ListProjectsOptions#state\n       */\n      public static ListProjectsOptions state(String state) {\n         ListProjectsOptions options = new ListProjectsOptions();\n         return options.state(state);\n      }\n\n      /**\n       * @see org.jclouds.cloudstack.options.ListProjectsOptions#displayText(String)\n       */\n      public static ListProjectsOptions displayText(String displayText) {\n         ListProjectsOptions options = new ListProjectsOptions();\n         return options.displayText(displayText);\n      }\n\n      /**\n       * @see org.jclouds.cloudstack.options.ListProjectsOptions#keyword(String)\n       */\n      public static ListProjectsOptions keyword(String keyword) {\n         ListProjectsOptions options = new ListProjectsOptions();\n         return options.keyword(keyword);\n      }\n\n      /**\n       * @see org.jclouds.cloudstack.options.ListProjectsOptions#recursive\n       */\n      public static ListProjectsOptions recursive(boolean recursive) {\n         ListProjectsOptions options = new ListProjectsOptions();\n         return options.recursive(recursive);\n      }\n\n      /**\n       * @see org.jclouds.cloudstack.options.ListProjectsOptions#tags\n       */\n      public static ListProjectsOptions tags(Map<String, String> tags) {\n         ListProjectsOptions options = new ListProjectsOptions();\n         return options.tags(tags);\n      }\n      \n      /**\n       * @see org.jclouds.cloudstack.options.ListProjectsOptions#page\n       */\n      public static ListProjectsOptions page(Long page) {\n         ListProjectsOptions options = new ListProjectsOptions();\n         return options.page(page);\n      }\n      \n      /**\n       * @see org.jclouds.cloudstack.options.ListProjectsOptions#pageSize\n       */\n      public static ListProjectsOptions pageSize(Long pageSize) {\n         ListProjectsOptions options = new ListProjectsOptions();\n         return options.pageSize(pageSize);\n      }\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ListProjectsOptions accountInDomain(String account, String domain) {\n      return ListProjectsOptions.class.cast(super.accountInDomain(account, domain));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ListProjectsOptions domainId(String domainId) {\n      return ListProjectsOptions.class.cast(super.domainId(domainId));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/ListPublicIPAddressesOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport java.util.Map;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options used to control what ip addresss information is returned\n * \n * @see <a href=\n *      \"http://download.cloud.com/releases/2.2.0/api/user/listIPAddresses.html\"\n *      />\n */\npublic class ListPublicIPAddressesOptions extends AccountInDomainOptions {\n\n   public static final ListPublicIPAddressesOptions NONE = new ListPublicIPAddressesOptions();\n\n   /**\n    * @param id\n    *           lists ip address by id\n    */\n   public ListPublicIPAddressesOptions id(String id) {\n      this.queryParameters.replaceValues(\"id\", ImmutableSet.of(id + \"\"));\n      return this;\n   }\n\n   /**\n    * @param allocatedOnly\n    *           limits search results to allocated public IP addresses\n    */\n   public ListPublicIPAddressesOptions allocatedOnly(boolean allocatedOnly) {\n      this.queryParameters.replaceValues(\"allocatedonly\", ImmutableSet.of(allocatedOnly + \"\"));\n      return this;\n\n   }\n\n   /**\n    * @param networkId\n    *           list ip addresss by networkId.\n    */\n   public ListPublicIPAddressesOptions networkId(String networkId) {\n      this.queryParameters.replaceValues(\"networkid\", ImmutableSet.of(networkId + \"\"));\n      return this;\n\n   }\n\n   /**\n    * @param projectId\n    *           list ip addresss by project.\n    */\n   public ListPublicIPAddressesOptions projectId(String projectId) {\n      this.queryParameters.replaceValues(\"projectid\", ImmutableSet.of(projectId + \"\"));\n      return this;\n\n   }\n\n   /**\n    * @param VLANId\n    *           lists all public IP addresses by VLAN ID\n    */\n   public ListPublicIPAddressesOptions VLANId(String VLANId) {\n      this.queryParameters.replaceValues(\"vlanid\", ImmutableSet.of(VLANId + \"\"));\n      return this;\n\n   }\n\n   /**\n    * @param IPAddress\n    *           lists the specified IP address\n    */\n   public ListPublicIPAddressesOptions IPAddress(String IPAddress) {\n      this.queryParameters.replaceValues(\"ipaddress\", ImmutableSet.of(IPAddress));\n      return this;\n   }\n\n   /**\n    * @param zoneId\n    *           lists all public IP addresses by Zone ID\n    */\n   public ListPublicIPAddressesOptions zoneId(String zoneId) {\n      this.queryParameters.replaceValues(\"zoneid\", ImmutableSet.of(zoneId + \"\"));\n      return this;\n\n   }\n\n   /**\n    * @param usesVirtualNetwork\n    *           the virtual network for the IP address\n    */\n   public ListPublicIPAddressesOptions usesVirtualNetwork(boolean usesVirtualNetwork) {\n      this.queryParameters.replaceValues(\"forvirtualnetwork\", ImmutableSet.of(usesVirtualNetwork + \"\"));\n      return this;\n   }\n\n   /**\n    * @param tags\n    *           Key/value pairs for tags that need to be matched.\n    */\n   public ListPublicIPAddressesOptions tags(Map<String, String> tags) {\n      int count = 0;\n      for (Map.Entry<String, String> entry : tags.entrySet()) {\n         this.queryParameters.replaceValues(String.format(\"tags[%d].key\", count), ImmutableSet.of(entry.getKey()));\n         this.queryParameters.replaceValues(String.format(\"tags[%d].value\", count),\n               ImmutableSet.of(entry.getValue()));\n         count += 1;\n      }\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see ListPublicIPAddressesOptions#accountInDomain\n       */\n      public static ListPublicIPAddressesOptions accountInDomain(String account, String domain) {\n         ListPublicIPAddressesOptions options = new ListPublicIPAddressesOptions();\n         return options.accountInDomain(account, domain);\n      }\n\n      /**\n       * @see ListPublicIPAddressesOptions#IPAddress\n       */\n      public static ListPublicIPAddressesOptions IPAddress(String IPAddress) {\n         ListPublicIPAddressesOptions options = new ListPublicIPAddressesOptions();\n         return options.IPAddress(IPAddress);\n      }\n\n      /**\n       * @see ListPublicIPAddressesOptions#domainId\n       */\n      public static ListPublicIPAddressesOptions domainId(String id) {\n         ListPublicIPAddressesOptions options = new ListPublicIPAddressesOptions();\n         return options.domainId(id);\n      }\n\n      /**\n       * @see ListPublicIPAddressesOptions#id\n       */\n      public static ListPublicIPAddressesOptions id(String id) {\n         ListPublicIPAddressesOptions options = new ListPublicIPAddressesOptions();\n         return options.id(id);\n      }\n\n      /**\n       * @see ListPublicIPAddressesOptions#allocatedOnly\n       */\n      public static ListPublicIPAddressesOptions allocatedOnly(boolean allocatedOnly) {\n         ListPublicIPAddressesOptions options = new ListPublicIPAddressesOptions();\n         return options.allocatedOnly(allocatedOnly);\n      }\n\n      /**\n       * @see ListPublicIPAddressesOptions#networkId\n       */\n      public static ListPublicIPAddressesOptions networkId(String id) {\n         ListPublicIPAddressesOptions options = new ListPublicIPAddressesOptions();\n         return options.networkId(id);\n      }\n\n      /**\n       * @see ListPublicIPAddressesOptions#projectId(String)\n       */\n      public static ListPublicIPAddressesOptions projectId(String id) {\n         ListPublicIPAddressesOptions options = new ListPublicIPAddressesOptions();\n         return options.projectId(id);\n      }\n\n      /**\n       * @see ListPublicIPAddressesOptions#VLANId\n       */\n      public static ListPublicIPAddressesOptions VLANId(String id) {\n         ListPublicIPAddressesOptions options = new ListPublicIPAddressesOptions();\n         return options.VLANId(id);\n      }\n\n      /**\n       * @see ListPublicIPAddressesOptions#zoneId\n       */\n      public static ListPublicIPAddressesOptions zoneId(String id) {\n         ListPublicIPAddressesOptions options = new ListPublicIPAddressesOptions();\n         return options.zoneId(id);\n      }\n\n      /**\n       * @see ListPublicIPAddressesOptions#usesVirtualNetwork\n       */\n      public static ListPublicIPAddressesOptions usesVirtualNetwork(boolean usesVirtualNetwork) {\n         ListPublicIPAddressesOptions options = new ListPublicIPAddressesOptions();\n         return options.usesVirtualNetwork(usesVirtualNetwork);\n      }\n\n      /**\n       * @see ListPublicIPAddressesOptions#tags\n       */\n      public static ListPublicIPAddressesOptions tags(Map<String, String> tags) {\n         ListPublicIPAddressesOptions options = new ListPublicIPAddressesOptions();\n         return options.tags(tags);\n      }\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ListPublicIPAddressesOptions accountInDomain(String account, String domain) {\n      return ListPublicIPAddressesOptions.class.cast(super.accountInDomain(account, domain));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ListPublicIPAddressesOptions domainId(String domainId) {\n      return ListPublicIPAddressesOptions.class.cast(super.domainId(domainId));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/ListResourceLimitsOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\npublic class ListResourceLimitsOptions extends BaseHttpRequestOptions {\n   public static final ListResourceLimitsOptions NONE = new ListResourceLimitsOptions();\n\n   /**\n    * Lists resource limits by account. Must be used with the domainId parameter.\n    *\n    * @param account - the account for which the resource limits are retrieved for.\n    * @return ListResourceLimitsOptions\n    */\n   public ListResourceLimitsOptions account(String account, String domainId) {\n      this.queryParameters.replaceValues(\"account\", ImmutableSet.of(account));\n      this.queryParameters.replaceValues(\"domainid\", ImmutableSet.of(String.valueOf(domainId)));\n      return this;\n   }\n\n   /**\n    * Lists resource limits by domain ID. If used with the account parameter,\n    * lists resource limits for a specified account in a specified domain.\n    *\n    * @param domainId\n    * @return ListResourceLimitsOptions\n    */\n   public ListResourceLimitsOptions domainId(String domainId) {\n      this.queryParameters.replaceValues(\"domainid\", ImmutableSet.of(String.valueOf(domainId)));\n      return this;\n   }\n\n   /**\n    * Lists resource limits by ID.\n    *\n    * @param id of the resource limit.\n    * @return ListResourceLimitsOptions\n    */\n   public ListResourceLimitsOptions id(String id) {\n      this.queryParameters.replaceValues(\"account\", ImmutableSet.of(String.valueOf(id)));\n      return this;\n   }\n\n   /**\n    * Lists resource limits by project.\n    *\n    * @param projectId the project\n    * @return ListResourceLimitsOptions\n    */\n   public ListResourceLimitsOptions projectId(String projectId) {\n      this.queryParameters.replaceValues(\"projectid\", ImmutableSet.of(String.valueOf(projectId + \"\")));\n      return this;\n   }\n\n   /**\n    * List by keyword\n    *\n    * @param keyword\n    * @return ListResourceLimitsOptions\n    */\n   public ListResourceLimitsOptions keyword(String keyword) {\n      this.queryParameters.replaceValues(\"keyword\", ImmutableSet.of(keyword));\n      return this;\n   }\n\n   /**\n    * Type of resource to update. Values are 0, 1, 2, 3, and 4.\n    * <ul>\n    * <li>0 - Instance. Number of instances a user can create.</li>\n    * <li>1 - IP. Number of public IP addresses a user can own.</li>\n    * <li>2 - Volume. Number of disk volumes a user can create.</li>\n    * <li>3 - Snapshot. Number of snapshots a user can create.</li>\n    * <li>4 - Template. Number of templates that a user can register/create.</li>\n    * </ul>\n    *\n    * @param resourceType type of the resource to query for\n    * @return ListResourceLimitsOptions\n    */\n   public ListResourceLimitsOptions resourceType(int resourceType) {\n      this.queryParameters.replaceValues(\"resourcetype\", ImmutableSet.of(String.valueOf(resourceType)));\n      return this;\n   }\n\n\n   public static class Builder {\n      /**\n       * @see ListResourceLimitsOptions#account(String, String)\n       */\n      public static ListResourceLimitsOptions account(String account, String domainId) {\n         ListResourceLimitsOptions options = new ListResourceLimitsOptions();\n         return options.account(account, domainId);\n      }\n\n      /**\n       * @see ListResourceLimitsOptions#domainId(String)\n       */\n      public static ListResourceLimitsOptions domainId(String domainId) {\n         ListResourceLimitsOptions options = new ListResourceLimitsOptions();\n         return options.domainId(domainId);\n      }\n\n      /**\n       * @see ListResourceLimitsOptions#id(String)\n       */\n      public static ListResourceLimitsOptions id(String id) {\n         ListResourceLimitsOptions options = new ListResourceLimitsOptions();\n         return options.id(id);\n      }\n\n      /**\n       * @see ListResourceLimitsOptions#projectId(String)\n       */\n      public static ListResourceLimitsOptions projectId(String projectId) {\n         ListResourceLimitsOptions options = new ListResourceLimitsOptions();\n         return options.projectId(projectId);\n      }\n\n      /**\n       * @see ListResourceLimitsOptions#keyword(String)\n       */\n      public static ListResourceLimitsOptions keyword(String keyword) {\n         ListResourceLimitsOptions options = new ListResourceLimitsOptions();\n         return options.keyword(keyword);\n      }\n\n      /**\n       * @see ListResourceLimitsOptions#resourceType(int)\n       */\n      public static ListResourceLimitsOptions resourceType(int resourceType) {\n         ListResourceLimitsOptions options = new ListResourceLimitsOptions();\n         return options.resourceType(resourceType);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/ListSSHKeyPairsOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\npublic class ListSSHKeyPairsOptions extends BaseHttpRequestOptions {\n\n   public static final ListSSHKeyPairsOptions NONE = new ListSSHKeyPairsOptions();\n\n   /**\n    * @param name\n    *           the SSHKeyPair name\n    */\n   public ListSSHKeyPairsOptions name(String name) {\n      this.queryParameters.replaceValues(\"name\", ImmutableSet.of(name));\n      return this;\n   }\n\n   /**\n    * @param projectId\n    *           the project to list in\n    */\n   public ListSSHKeyPairsOptions projectId(String projectId) {\n      this.queryParameters.replaceValues(\"projectId\", ImmutableSet.of(projectId + \"\"));\n      return this;\n   }\n\n   public static class Builder {\n      /**\n       * @see ListSSHKeyPairsOptions#name\n       */\n      public static ListSSHKeyPairsOptions name(String name) {\n         ListSSHKeyPairsOptions options = new ListSSHKeyPairsOptions();\n         return options.name(name);\n      }\n\n      /**\n       * @see ListSSHKeyPairsOptions#projectId(String)\n       */\n      public static ListSSHKeyPairsOptions projectId(String projectId) {\n         ListSSHKeyPairsOptions options = new ListSSHKeyPairsOptions();\n         return options.projectId(projectId);\n      }\n\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/ListSecurityGroupsOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport java.util.Map;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options used to control what security groups are returned\n * \n * @see <a href=\n *      \"http://download.cloud.com/releases/2.2.0/api/user/listSecurityGroups.html\"\n *      />\n */\npublic class ListSecurityGroupsOptions extends AssociateIPAddressOptions {\n\n   public static final ListSecurityGroupsOptions NONE = new ListSecurityGroupsOptions();\n\n   /**\n    * @param id\n    *           the ID of the security group\n    */\n   public ListSecurityGroupsOptions id(String id) {\n      this.queryParameters.replaceValues(\"id\", ImmutableSet.of(id + \"\"));\n      return this;\n   }\n\n   /**\n    * @param securityGroupName\n    *           lists security groups by name\n    */\n   public ListSecurityGroupsOptions named(String securityGroupName) {\n      this.queryParameters.replaceValues(\"securitygroupname\", ImmutableSet.of(securityGroupName));\n      return this;\n   }\n\n   /**\n    * @param virtualMachineId\n    *           the ID of the virtual machine. Pass this in if you want to see\n    *           the available service offering that a virtual machine can be\n    *           changed to.\n    */\n   public ListSecurityGroupsOptions virtualMachineId(String virtualMachineId) {\n      this.queryParameters.replaceValues(\"virtualmachineid\", ImmutableSet.of(virtualMachineId + \"\"));\n      return this;\n\n   }\n\n   /**\n    * @param projectId\n    *           the ID of the project to search in.\n    */\n   public ListSecurityGroupsOptions projectId(String projectId) {\n      this.queryParameters.replaceValues(\"projectid\", ImmutableSet.of(projectId + \"\"));\n      return this;\n   }\n\n   /**\n    * @param tags\n    *           Key/value pairs for tags that need to be matched.\n    */\n   public ListSecurityGroupsOptions tags(Map<String, String> tags) {\n      int count = 0;\n      for (Map.Entry<String, String> entry : tags.entrySet()) {\n         this.queryParameters.replaceValues(String.format(\"tags[%d].key\", count), ImmutableSet.of(entry.getKey()));\n         this.queryParameters.replaceValues(String.format(\"tags[%d].value\", count),\n               ImmutableSet.of(entry.getValue()));\n         count += 1;\n      }\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see ListSecurityGroupsOptions#named\n       */\n      public static ListSecurityGroupsOptions named(String securityGroupName) {\n         ListSecurityGroupsOptions options = new ListSecurityGroupsOptions();\n         return options.named(securityGroupName);\n      }\n\n      /**\n       * @see ListSecurityGroupsOptions#id\n       */\n      public static ListSecurityGroupsOptions id(String id) {\n         ListSecurityGroupsOptions options = new ListSecurityGroupsOptions();\n         return options.id(id);\n      }\n\n      /**\n       * @see ListSecurityGroupsOptions#virtualMachineId\n       */\n      public static ListSecurityGroupsOptions virtualMachineId(String virtualMachineId) {\n         ListSecurityGroupsOptions options = new ListSecurityGroupsOptions();\n         return options.virtualMachineId(virtualMachineId);\n      }\n\n      /**\n       * @see ListSecurityGroupsOptions#projectId(String)\n       */\n      public static ListSecurityGroupsOptions projectId(String projectId) {\n         ListSecurityGroupsOptions options = new ListSecurityGroupsOptions();\n         return options.projectId(projectId);\n      }\n\n      /**\n       * @see ListSecurityGroupsOptions#accountInDomain\n       */\n      public static ListSecurityGroupsOptions accountInDomain(String account, String domain) {\n         ListSecurityGroupsOptions options = new ListSecurityGroupsOptions();\n         return options.accountInDomain(account, domain);\n      }\n\n      /**\n       * @see ListSecurityGroupsOptions#domainId\n       */\n      public static ListSecurityGroupsOptions domainId(String domainId) {\n         ListSecurityGroupsOptions options = new ListSecurityGroupsOptions();\n         return options.domainId(domainId);\n      }\n\n      /**\n       * @see ListSecurityGroupsOptions#tags\n       */\n      public static ListSecurityGroupsOptions tags(Map<String, String> tags) {\n         ListSecurityGroupsOptions options = new ListSecurityGroupsOptions();\n         return options.tags(tags);\n      }\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ListSecurityGroupsOptions accountInDomain(String account, String domain) {\n      return ListSecurityGroupsOptions.class.cast(super.accountInDomain(account, domain));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ListSecurityGroupsOptions domainId(String domainId) {\n      return ListSecurityGroupsOptions.class.cast(super.domainId(domainId));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/ListServiceOfferingsOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options used to control what service offerings are returned\n * \n * @see <a href=\n *      \"http://download.cloud.com/releases/2.2.0/api/user/listServiceOfferings.html\"\n *      />\n */\npublic class ListServiceOfferingsOptions extends BaseHttpRequestOptions {\n\n   public static final ListServiceOfferingsOptions NONE = new ListServiceOfferingsOptions();\n\n   /**\n    * @param id\n    *           the ID of the service offering\n    */\n   public ListServiceOfferingsOptions id(String id) {\n      this.queryParameters.replaceValues(\"id\", ImmutableSet.of(id + \"\"));\n      return this;\n   }\n\n   /**\n    * @param domainId\n    *           the ID of the domain associated with the service offering\n    */\n   public ListServiceOfferingsOptions domainId(String domainId) {\n      this.queryParameters.replaceValues(\"domainid\", ImmutableSet.of(domainId + \"\"));\n      return this;\n\n   }\n\n   /**\n    * @param name\n    *           the service offering name\n    */\n   public ListServiceOfferingsOptions name(String name) {\n      this.queryParameters.replaceValues(\"name\", ImmutableSet.of(name));\n      return this;\n   }\n\n   /**\n    * @param virtualMachineId\n    *           the ID of the virtual machine. Pass this in if you want to see\n    *           the available service offering that a virtual machine can be\n    *           changed to.\n    */\n   public ListServiceOfferingsOptions virtualMachineId(String virtualMachineId) {\n      this.queryParameters.replaceValues(\"virtualmachineid\", ImmutableSet.of(virtualMachineId + \"\"));\n      return this;\n\n   }\n\n   public static class Builder {\n\n      /**\n       * @see ListServiceOfferingsOptions#name\n       */\n      public static ListServiceOfferingsOptions name(String name) {\n         ListServiceOfferingsOptions options = new ListServiceOfferingsOptions();\n         return options.name(name);\n      }\n\n      /**\n       * @see ListServiceOfferingsOptions#domainId\n       */\n      public static ListServiceOfferingsOptions domainId(String id) {\n         ListServiceOfferingsOptions options = new ListServiceOfferingsOptions();\n         return options.domainId(id);\n      }\n\n      /**\n       * @see ListServiceOfferingsOptions#id\n       */\n      public static ListServiceOfferingsOptions id(String id) {\n         ListServiceOfferingsOptions options = new ListServiceOfferingsOptions();\n         return options.id(id);\n      }\n\n      /**\n       * @see ListServiceOfferingsOptions#virtualMachineId\n       */\n      public static ListServiceOfferingsOptions virtualMachineId(String virtualMachineId) {\n         ListServiceOfferingsOptions options = new ListServiceOfferingsOptions();\n         return options.virtualMachineId(virtualMachineId);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/ListSnapshotPoliciesOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options for the Snapshot listSnapshotPolicies method.\n *\n * @see org.jclouds.cloudstack.features.SnapshotApi#listSnapshotPolicies\n * @see org.jclouds.cloudstack.features.SnapshotApi#listSnapshotPolicies\n */\npublic class ListSnapshotPoliciesOptions extends AccountInDomainOptions {\n\n   public static final ListSnapshotPoliciesOptions NONE = new ListSnapshotPoliciesOptions(); \n\n   /**\n    * @param keyword List by keyword\n    */\n   public ListSnapshotPoliciesOptions keyword(String keyword) {\n      this.queryParameters.replaceValues(\"keyword\", ImmutableSet.of(keyword + \"\"));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @param account lists snapshot policies for the specified account.\n       */\n      public static ListSnapshotPoliciesOptions accountInDomain(String account, String domainId) {\n         return (ListSnapshotPoliciesOptions) new ListSnapshotPoliciesOptions().accountInDomain(account, domainId);\n      }\n\n      /**\n       * @param domainId the domain ID.\n       */\n      public static ListSnapshotPoliciesOptions domainId(String domainId) {\n         return (ListSnapshotPoliciesOptions) new ListSnapshotPoliciesOptions().domainId(domainId);\n      }\n\n      /**\n       * @param keyword List by keyword\n       */\n      public static ListSnapshotPoliciesOptions keyword(String keyword) {\n         return new ListSnapshotPoliciesOptions().keyword(keyword);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/ListSnapshotsOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport java.util.Map;\n\nimport org.jclouds.cloudstack.domain.Snapshot;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options for the Snapshot listSnapshots method.\n *\n * @see org.jclouds.cloudstack.features.SnapshotApi#listSnapshots\n * @see org.jclouds.cloudstack.features.SnapshotApi#listSnapshots\n */\npublic class ListSnapshotsOptions extends AccountInDomainOptions {\n\n   public static final ListSnapshotsOptions NONE = new ListSnapshotsOptions(); \n\n   /**\n    * @param id lists snapshot by snapshot ID\n    */\n   public ListSnapshotsOptions id(String id) {\n      this.queryParameters.replaceValues(\"id\", ImmutableSet.of(id + \"\"));\n      return this;\n   }\n\n   /**\n    * @param interval valid values are HOURLY, DAILY, WEEKLY, and MONTHLY.\n    */\n   public ListSnapshotsOptions interval(Snapshot.Interval interval) {\n      this.queryParameters.replaceValues(\"intervaltype\", ImmutableSet.of(interval + \"\"));\n      return this;\n   }\n\n   /**\n    * @param isRecursive defaults to false, but if true, lists all snapshots from the parent specified by the domain id till leaves.\n    */\n   public ListSnapshotsOptions isRecursive(boolean isRecursive) {\n      this.queryParameters.replaceValues(\"isrecursive\", ImmutableSet.of(isRecursive + \"\"));\n      return this;\n   }\n\n   /**\n    * @param keyword List by keyword\n    */\n   public ListSnapshotsOptions keyword(String keyword) {\n      this.queryParameters.replaceValues(\"keyword\", ImmutableSet.of(keyword + \"\"));\n      return this;\n   }\n\n   /**\n    * @param name lists snapshot by snapshot name\n    */\n   public ListSnapshotsOptions name(String name) {\n      this.queryParameters.replaceValues(\"name\", ImmutableSet.of(name + \"\"));\n      return this;\n   }\n\n   /**\n    * @param snapshotType valid values are MANUAL or RECURRING.\n    */\n   public ListSnapshotsOptions snapshotType(Snapshot.Type snapshotType) {\n      this.queryParameters.replaceValues(\"snapshottype\", ImmutableSet.of(snapshotType + \"\"));\n      return this;\n   }\n\n   /**\n    * @param volumeId the ID of the disk volume\n    */\n   public ListSnapshotsOptions volumeId(String volumeId) {\n      this.queryParameters.replaceValues(\"volumeid\", ImmutableSet.of(volumeId + \"\"));\n      return this;\n   }\n\n   /**\n    * @param projectId the project to list in\n    */\n   public ListSnapshotsOptions projectId(String projectId) {\n      this.queryParameters.replaceValues(\"projectid\", ImmutableSet.of(projectId + \"\"));\n      return this;\n   }\n\n   /**\n    * @param tags\n    *           Key/value pairs for tags that need to be matched.\n    */\n   public ListSnapshotsOptions tags(Map<String, String> tags) {\n      int count = 0;\n      for (Map.Entry<String, String> entry : tags.entrySet()) {\n         this.queryParameters.replaceValues(String.format(\"tags[%d].key\", count), ImmutableSet.of(entry.getKey()));\n         this.queryParameters.replaceValues(String.format(\"tags[%d].value\", count),\n               ImmutableSet.of(entry.getValue()));\n         count += 1;\n      }\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @param account lists snapshot belonging to the specified account.\n       * @param domainId The domain ID.\n       */\n      public static ListSnapshotsOptions accountInDomain(String account, String domainId) {\n         return (ListSnapshotsOptions) new ListSnapshotsOptions().accountInDomain(account, domainId);\n      }\n\n      /**\n       * @param domainId the domain ID.\n       */\n      public static ListSnapshotsOptions domainId(String domainId) {\n         return (ListSnapshotsOptions) new ListSnapshotsOptions().domainId(domainId);\n      }\n\n      /**\n       * @param id lists snapshot by snapshot ID\n       */\n      public static ListSnapshotsOptions id(String id) {\n         return new ListSnapshotsOptions().id(id);\n      }\n\n      /**\n       * @param interval valid values are HOURLY, DAILY, WEEKLY, and MONTHLY.\n       */\n      public static ListSnapshotsOptions interval(Snapshot.Interval interval) {\n         return new ListSnapshotsOptions().interval(interval);\n      }\n\n      /**\n       * @param isRecursive defaults to false, but if true, lists all snapshots from the parent specified by the domain id till leaves.\n       */\n      public static ListSnapshotsOptions isRecursive(boolean isRecursive) {\n         return new ListSnapshotsOptions().isRecursive(isRecursive);\n      }\n\n      /**\n       * @param keyword List by keyword\n       */\n      public static ListSnapshotsOptions keyword(String keyword) {\n         return new ListSnapshotsOptions().keyword(keyword);\n      }\n\n      /**\n       * @param name lists snapshot by snapshot name\n       */\n      public static ListSnapshotsOptions name(String name) {\n         return new ListSnapshotsOptions().name(name);\n      }\n\n      /**\n       * @param snapshotType valid values are MANUAL or RECURRING.\n       */\n      public static ListSnapshotsOptions snapshotType(Snapshot.Type snapshotType) {\n         return new ListSnapshotsOptions().snapshotType(snapshotType);\n      }\n\n      /**\n       * @param volumeId the ID of the disk volume\n       */\n      public static ListSnapshotsOptions volumeId(String volumeId) {\n         return new ListSnapshotsOptions().volumeId(volumeId);\n      }\n\n      /**\n       * @param projectId the project to list in\n       */\n      public static ListSnapshotsOptions projectId(String projectId) {\n         return new ListSnapshotsOptions().projectId(projectId);\n      }\n\n      /**\n       * @see org.jclouds.cloudstack.options.ListSnapshotsOptions#tags(java.util.Map)\n       */\n      public static ListSnapshotsOptions tags(Map<String, String> tags) {\n         return new ListSnapshotsOptions().tags(tags);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/ListStoragePoolsOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options to the GlobalStoragePools[Async]Client.listStoragePools API call\n */\npublic class ListStoragePoolsOptions extends BaseHttpRequestOptions {\n\n   public static final ListStoragePoolsOptions NONE = new ListStoragePoolsOptions();\n   \n   public static class Builder {\n\n      private Builder() {}\n      \n      public static ListStoragePoolsOptions clusterId(String clusterId) {\n         ListStoragePoolsOptions options = new ListStoragePoolsOptions();\n         return options.clusterId(clusterId);\n      }\n\n      public static ListStoragePoolsOptions id(String id) {\n         ListStoragePoolsOptions options = new ListStoragePoolsOptions();\n         return options.id(id);\n      }\n\n      public static ListStoragePoolsOptions ipAddress(String ipAddress) {\n         ListStoragePoolsOptions options = new ListStoragePoolsOptions();\n         return options.ipAddress(ipAddress);\n      }\n\n      public static ListStoragePoolsOptions keyword(String keyword) {\n         ListStoragePoolsOptions options = new ListStoragePoolsOptions();\n         return options.keyword(keyword);\n      }\n\n      public static ListStoragePoolsOptions name(String name) {\n         ListStoragePoolsOptions options = new ListStoragePoolsOptions();\n         return options.name(name);\n      }\n\n      public static ListStoragePoolsOptions path(String path) {\n         ListStoragePoolsOptions options = new ListStoragePoolsOptions();\n         return options.path(path);\n      }\n\n      public static ListStoragePoolsOptions podId(String podId) {\n         ListStoragePoolsOptions options = new ListStoragePoolsOptions();\n         return options.podId(podId);\n      }\n\n      public static ListStoragePoolsOptions zoneId(String zoneId) {\n         ListStoragePoolsOptions options = new ListStoragePoolsOptions();\n         return options.zoneId(zoneId);\n      }\n   }\n\n   ListStoragePoolsOptions() {}\n   \n   public ListStoragePoolsOptions clusterId(String clusterId) {\n      this.queryParameters.replaceValues(\"clusterid\", ImmutableSet.of(clusterId + \"\"));\n      return this;\n   }\n\n   public ListStoragePoolsOptions id(String id) {\n      this.queryParameters.replaceValues(\"id\", ImmutableSet.of(id + \"\"));\n      return this;\n   }\n\n   public ListStoragePoolsOptions ipAddress(String ipAddress) {\n      this.queryParameters.replaceValues(\"ipaddress\", ImmutableSet.of(ipAddress));\n      return this;\n   }\n\n   public ListStoragePoolsOptions keyword(String keyword) {\n      this.queryParameters.replaceValues(\"keyword\", ImmutableSet.of(keyword));\n      return this;\n   }\n\n   public ListStoragePoolsOptions name(String name) {\n      this.queryParameters.replaceValues(\"name\", ImmutableSet.of(name));\n      return this;\n   }\n   public ListStoragePoolsOptions path(String path) {\n      this.queryParameters.replaceValues(\"path\", ImmutableSet.of(path));\n      return this;\n   }\n\n   public ListStoragePoolsOptions podId(String podId) {\n      this.queryParameters.replaceValues(\"podid\", ImmutableSet.of(podId + \"\"));\n      return this;\n   }\n\n   public ListStoragePoolsOptions zoneId(String zoneId) {\n      this.queryParameters.replaceValues(\"zoneid\", ImmutableSet.of(zoneId + \"\"));\n      return this;\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/ListTagsOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport com.google.common.collect.ImmutableSet;\nimport org.jclouds.cloudstack.domain.Tag;\n\n/**\n * Options used to control what tags are returned\n * \n * @see <a href=\n *      \"http://cloudstack.apache.org/docs/api/apidocs-4.3/root_admin/listTags.html\"\n *      />\n */\npublic class ListTagsOptions extends AccountInDomainOptions {\n\n   public static final ListTagsOptions NONE = new ListTagsOptions();\n\n   /**\n    * @param customer\n    *    list by customer\n    */\n   public ListTagsOptions customer(String customer) {\n      this.queryParameters.replaceValues(\"customer\", ImmutableSet.of(customer));\n      return this;\n   }\n\n   /**\n    * @param isRecursive\n    *           Should we recurse on this search?\n    */\n   public ListTagsOptions isRecursive(boolean isRecursive) {\n      this.queryParameters.replaceValues(\"isrecursive\", ImmutableSet.of(isRecursive + \"\"));\n      return this;\n   }\n\n   /**\n    * @param key\n    *    list by key\n    */\n   public ListTagsOptions key(String key) {\n      this.queryParameters.replaceValues(\"key\", ImmutableSet.of(key));\n      return this;\n   }\n\n   /**\n    * @param keyword\n    *    list by keyword\n    */\n   public ListTagsOptions keyword(String keyword) {\n      this.queryParameters.replaceValues(\"keyword\", ImmutableSet.of(keyword));\n      return this;\n   }\n\n   /**\n    * @param projectId\n    *    list by project\n    */\n   public ListTagsOptions projectId(String projectId) {\n      this.queryParameters.replaceValues(\"projectid\", ImmutableSet.of(projectId));\n      return this;\n   }\n\n   /**\n    * @param resourceId\n    *    list by resource ID\n    */\n   public ListTagsOptions resourceId(String resourceId) {\n      this.queryParameters.replaceValues(\"resourceid\", ImmutableSet.of(resourceId));\n      return this;\n   }\n\n   /**\n    * @param resourceType\n    *    list by resource type\n    */\n   public ListTagsOptions resourceType(String resourceType) {\n      this.queryParameters.replaceValues(\"resourcetype\", ImmutableSet.of(resourceType));\n      return this;\n   }\n\n   /**\n    * @param resourceType\n    *    list by resource type\n    */\n   public ListTagsOptions resourceType(Tag.ResourceType resourceType) {\n      this.queryParameters.replaceValues(\"resourcetype\", ImmutableSet.of(resourceType.toString()));\n      return this;\n   }\n\n   /**\n    * @param value\n    *    list by value\n    */\n   public ListTagsOptions value(String value) {\n      this.queryParameters.replaceValues(\"value\", ImmutableSet.of(value));\n      return this;\n   }\n\n   public ListTagsOptions page(long page) {\n      this.queryParameters.replaceValues(\"page\", ImmutableSet.of(page + \"\"));\n      return this;\n   }\n\n   public ListTagsOptions pageSize(long pageSize) {\n      this.queryParameters.replaceValues(\"pagesize\", ImmutableSet.of(pageSize + \"\"));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see org.jclouds.cloudstack.options.ListTagsOptions#accountInDomain(String, String)\n       */\n      public static ListTagsOptions accountInDomain(String account, String domain) {\n         ListTagsOptions options = new ListTagsOptions();\n         return options.accountInDomain(account, domain);\n      }\n\n      /**\n       * @see org.jclouds.cloudstack.options.ListTagsOptions#accountInDomain(String, String)\n       */\n      public static ListTagsOptions domainId(String domainId) {\n         ListTagsOptions options = new ListTagsOptions();\n         return options.domainId(domainId);\n      }\n\n      /**\n       * @see org.jclouds.cloudstack.options.ListTagsOptions#customer(String)\n       */\n      public static ListTagsOptions customer(String customer) {\n         ListTagsOptions options = new ListTagsOptions();\n         return options.customer(customer);\n      }\n\n      /**\n       * @see org.jclouds.cloudstack.options.ListTagsOptions#isRecursive(boolean)\n       */\n      public static ListTagsOptions isRecursive(boolean isRecursive) {\n         ListTagsOptions options = new ListTagsOptions();\n         return options.isRecursive(isRecursive);\n      }\n\n      /**\n       * @see org.jclouds.cloudstack.options.ListTagsOptions#key(String)\n       */\n      public static ListTagsOptions key(String key) {\n         ListTagsOptions options = new ListTagsOptions();\n         return options.key(key);\n      }\n\n      /**\n       * @see org.jclouds.cloudstack.options.ListTagsOptions#keyword\n       */\n      public static ListTagsOptions keyword(String keyword) {\n         ListTagsOptions options = new ListTagsOptions();\n         return options.keyword(keyword);\n      }\n\n      /**\n       * @see org.jclouds.cloudstack.options.ListTagsOptions#projectId(String)\n       */\n      public static ListTagsOptions projectId(String projectId) {\n         ListTagsOptions options = new ListTagsOptions();\n         return options.projectId(projectId);\n      }\n\n      /**\n       * @see org.jclouds.cloudstack.options.ListTagsOptions#resourceId(String)\n       */\n      public static ListTagsOptions resourceId(String resourceId) {\n         ListTagsOptions options = new ListTagsOptions();\n         return options.resourceId(resourceId);\n      }\n\n      /**\n       * @see org.jclouds.cloudstack.options.ListTagsOptions#resourceType(String)\n       */\n      public static ListTagsOptions resourceType(String resourceType) {\n         ListTagsOptions options = new ListTagsOptions();\n         return options.resourceType(resourceType);\n      }\n\n      /**\n       * @see org.jclouds.cloudstack.options.ListTagsOptions#resourceType(org.jclouds.cloudstack.domain.Tag.ResourceType)\n       */\n      public static ListTagsOptions resourceType(Tag.ResourceType resourceType) {\n         ListTagsOptions options = new ListTagsOptions();\n         return options.resourceType(resourceType);\n      }\n\n      /**\n       * @see org.jclouds.cloudstack.options.ListTagsOptions#value(String)\n       */\n      public static ListTagsOptions value(String value) {\n         ListTagsOptions options = new ListTagsOptions();\n         return options.value(value);\n      }\n\n      /**\n       * @see org.jclouds.cloudstack.options.ListTagsOptions#page\n       */\n      public static ListTagsOptions page(long page) {\n         ListTagsOptions options = new ListTagsOptions();\n         return options.page(page);\n      }\n\n      /**\n       * @see org.jclouds.cloudstack.options.ListTagsOptions#pageSize\n       */\n      public static ListTagsOptions pageSize(long pageSize) {\n         ListTagsOptions options = new ListTagsOptions();\n         return options.pageSize(pageSize);\n      }\n   }\n\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ListTagsOptions accountInDomain(String account, String domain) {\n      return ListTagsOptions.class.cast(super.accountInDomain(account, domain));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ListTagsOptions domainId(String domainId) {\n      return ListTagsOptions.class.cast(super.domainId(domainId));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/ListTemplatesOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport java.util.Map;\n\nimport org.jclouds.cloudstack.domain.TemplateFilter;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options used to control what templates information is returned\n * \n * @see <a\n *      href=\"http://download.cloud.com/releases/2.2.0/api/user/listTemplates.html\"\n *      />\n */\npublic class ListTemplatesOptions extends AccountInDomainOptions {\n   public ListTemplatesOptions() {\n      filter(TemplateFilter.EXECUTABLE);\n   }\n\n   public static final ListTemplatesOptions NONE = new ListTemplatesOptions();\n\n   /**\n    * @param filter\n    *           how to constrain the list\n    */\n   public ListTemplatesOptions filter(TemplateFilter filter) {\n      this.queryParameters.replaceValues(\"templatefilter\", ImmutableSet.of(filter.toString()));\n      return this;\n   }\n\n   /**\n    * @param id\n    *           the template ID\n    */\n   public ListTemplatesOptions id(String id) {\n      this.queryParameters.replaceValues(\"id\", ImmutableSet.of(id + \"\"));\n      return this;\n   }\n\n   /**\n    * @param name\n    *           the template name\n    */\n   public ListTemplatesOptions name(String name) {\n      this.queryParameters.replaceValues(\"name\", ImmutableSet.of(name));\n      return this;\n   }\n\n   /**\n    * @param zoneId\n    *           list templates by zoneId.\n    */\n   public ListTemplatesOptions zoneId(String zoneId) {\n      this.queryParameters.replaceValues(\"zoneid\", ImmutableSet.of(zoneId + \"\"));\n      return this;\n\n   }\n\n   /**\n    * @param projectId\n    *           list templates by projectId.\n    */\n   public ListTemplatesOptions projectId(String projectId) {\n      this.queryParameters.replaceValues(\"projectid\", ImmutableSet.of(projectId + \"\"));\n      return this;\n\n   }\n\n   /**\n    * @param hypervisor\n    *           the hypervisor for which to restrict the search\n    */\n   public ListTemplatesOptions hypervisor(String hypervisor) {\n      this.queryParameters.replaceValues(\"hypervisor\", ImmutableSet.of(hypervisor));\n      return this;\n   }\n\n   /**\n    * @param tags\n    *           Key/value pairs for tags that need to be matched.\n    */\n   public ListTemplatesOptions tags(Map<String, String> tags) {\n      int count = 0;\n      for (Map.Entry<String, String> entry : tags.entrySet()) {\n         this.queryParameters.replaceValues(String.format(\"tags[%d].key\", count), ImmutableSet.of(entry.getKey()));\n         this.queryParameters.replaceValues(String.format(\"tags[%d].value\", count),\n               ImmutableSet.of(entry.getValue()));\n         count += 1;\n      }\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see ListTemplatesOptions#filter\n       */\n      public static ListTemplatesOptions filter(TemplateFilter filter) {\n         ListTemplatesOptions options = new ListTemplatesOptions();\n         return options.filter(filter);\n      }\n\n      /**\n       * @see ListTemplatesOptions#domainId\n       */\n      public static ListTemplatesOptions domainId(String id) {\n         ListTemplatesOptions options = new ListTemplatesOptions();\n         return options.domainId(id);\n      }\n\n      /**\n       * @see ListTemplatesOptions#accountInDomain\n       */\n      public static ListTemplatesOptions accountInDomain(String account, String domain) {\n         ListTemplatesOptions options = new ListTemplatesOptions();\n         return options.accountInDomain(account, domain);\n      }\n\n      /**\n       * @see ListTemplatesOptions#id\n       */\n      public static ListTemplatesOptions id(String id) {\n         ListTemplatesOptions options = new ListTemplatesOptions();\n         return options.id(id);\n      }\n\n      /**\n       * @see ListTemplatesOptions#name\n       */\n      public static ListTemplatesOptions name(String name) {\n         ListTemplatesOptions options = new ListTemplatesOptions();\n         return options.name(name);\n      }\n\n      /**\n       * @see ListTemplatesOptions#zoneId\n       */\n      public static ListTemplatesOptions zoneId(String id) {\n         ListTemplatesOptions options = new ListTemplatesOptions();\n         return options.zoneId(id);\n      }\n\n      /**\n       * @see ListTemplatesOptions#projectId(String)\n       */\n      public static ListTemplatesOptions projectId(String projectId) {\n         ListTemplatesOptions options = new ListTemplatesOptions();\n         return options.projectId(projectId);\n      }\n\n      /**\n       * @see ListTemplatesOptions#hypervisor\n       */\n      public static ListTemplatesOptions hypervisor(String hypervisor) {\n         ListTemplatesOptions options = new ListTemplatesOptions();\n         return options.hypervisor(hypervisor);\n      }\n\n      /**\n       * @see ListTemplatesOptions#tags\n       */\n      public static ListTemplatesOptions tags(Map<String, String> tags) {\n         ListTemplatesOptions options = new ListTemplatesOptions();\n         return options.tags(tags);\n      }\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ListTemplatesOptions accountInDomain(String account, String domain) {\n      return ListTemplatesOptions.class.cast(super.accountInDomain(account, domain));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ListTemplatesOptions domainId(String domainId) {\n      return ListTemplatesOptions.class.cast(super.domainId(domainId));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/ListUsageRecordsOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options to the GlobalUsageApi.listUsageOptions() API call\n */\npublic class ListUsageRecordsOptions extends AccountInDomainOptions {\n\n   public static final ListUsageRecordsOptions NONE = new ListUsageRecordsOptions();\n\n   public static class Builder {\n      public static ListUsageRecordsOptions accountInDomain(String account, String domainId) {\n         ListUsageRecordsOptions options = new ListUsageRecordsOptions();\n         return options.accountInDomain(account, domainId);\n      }\n\n      public static ListUsageRecordsOptions domainId(String domainId) {\n         ListUsageRecordsOptions options = new ListUsageRecordsOptions();\n         return options.domainId(domainId);\n      }\n\n      public static ListUsageRecordsOptions accountId(String accountId) {\n         ListUsageRecordsOptions options = new ListUsageRecordsOptions();\n         return options.accountId(accountId);\n      }\n\n      public static ListUsageRecordsOptions projectId(String projectId) {\n         ListUsageRecordsOptions options = new ListUsageRecordsOptions();\n         return options.projectId(projectId);\n      }\n\n      public static ListUsageRecordsOptions keyword(String keyword) {\n         ListUsageRecordsOptions options = new ListUsageRecordsOptions();\n         return options.keyword(keyword);\n      }\n\t  \n      public static ListUsageRecordsOptions type(String type) {\n         ListUsageRecordsOptions options = new ListUsageRecordsOptions();\n         return options.type(type);\n      }\n      \n      public static ListUsageRecordsOptions page(String page) {\n         ListUsageRecordsOptions options = new ListUsageRecordsOptions();\n         return options.page(page);\n      }\n      \n      public static ListUsageRecordsOptions pageSize(String pageSize) {\n         ListUsageRecordsOptions options = new ListUsageRecordsOptions();\n         return options.pageSize(pageSize);\n      }\n      \n      public static ListUsageRecordsOptions includeTags(boolean includeTags) {\n         ListUsageRecordsOptions options = new ListUsageRecordsOptions();\n         return options.includeTags(includeTags);\n      }\n\n   }\n\n   @Override\n   public ListUsageRecordsOptions accountInDomain(String account, String domain) {\n      return (ListUsageRecordsOptions) super.accountInDomain(account, domain);\n   }\n\n   @Override\n   public ListUsageRecordsOptions domainId(String domainId) {\n      return (ListUsageRecordsOptions) super.domainId(domainId);\n   }\n\n   public ListUsageRecordsOptions accountId(String accountId) {\n      this.queryParameters.replaceValues(\"accountid\", ImmutableSet.of(accountId + \"\"));\n      return this;\n   }\n\n   public ListUsageRecordsOptions projectId(String projectId) {\n      this.queryParameters.replaceValues(\"projectid\", ImmutableSet.of(projectId + \"\"));\n      return this;\n   }\n\n   public ListUsageRecordsOptions keyword(String keyword) {\n      this.queryParameters.replaceValues(\"keyword\", ImmutableSet.of(keyword));\n      return this;\n   }\n   \n   public ListUsageRecordsOptions type(String type) {\n      this.queryParameters.replaceValues(\"type\", ImmutableSet.of(type));\n      return this;\n   }\n   \n   public ListUsageRecordsOptions page(String page) {\n      this.queryParameters.replaceValues(\"page\", ImmutableSet.of(page));\n      return this;\n   }\n   \n   public ListUsageRecordsOptions pageSize(String pageSize) {\n      this.queryParameters.replaceValues(\"pagesize\", ImmutableSet.of(pageSize));\n      return this;\n   }\n   \n   public ListUsageRecordsOptions includeTags(boolean includeTags) {\n      this.queryParameters.replaceValues(\"includetags\", ImmutableSet.of(includeTags + \"\"));\n      return this;\n   } \n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/ListUsersOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.cloudstack.domain.User;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options used to control what user information is returned\n * \n * @see <a\n *      href=\"http://download.cloud.com/releases/2.2.0/api_2.2.12/domain_admin/listUsers.html\"\n *      />\n */\npublic class ListUsersOptions extends AccountInDomainOptions {\n\n   public static final ListUsersOptions NONE = new ListUsersOptions();\n\n   /**\n    * @param id\n    *           list account by account ID\n    */\n   public ListUsersOptions id(String id) {\n      this.queryParameters.replaceValues(\"id\", ImmutableSet.of(id + \"\"));\n      return this;\n   }\n\n   /**\n    * @param userName\n    *           retrieve user by name\n    */\n   public ListUsersOptions userName(String userName) {\n      this.queryParameters.replaceValues(\"name\", ImmutableSet.of(userName));\n      return this;\n   }\n\n   /**\n    * @param state\n    *           list accounts by state. Valid states are enabled, disabled, and\n    *           locked.\n    */\n   public ListUsersOptions state(User.State state) {\n      this.queryParameters.replaceValues(\"state\", ImmutableSet.of(state.toString()));\n      return this;\n   }\n\n   /**\n    * @param accountType\n    *             List users by account type. Valid types include admin,\n    *             domain-admin, read-only-admin, or user.\n    */\n   public ListUsersOptions accountType(String accountType) {\n      this.queryParameters.replaceValues(\"accounttype\", ImmutableSet.of(accountType));\n      return this;\n   }\n\n   /**\n    * @param keyword\n    */\n   public ListUsersOptions keyword(String keyword) {\n      this.queryParameters.replaceValues(\"keyword\", ImmutableSet.of(keyword));\n      return this;\n   }\n\n   /**\n    * @param page\n    *          the page number\n    */\n   public ListUsersOptions page(long page) {\n      this.queryParameters.replaceValues(\"page\", ImmutableSet.of(page + \"\"));\n      return this;\n   }\n\n   /**\n    * @param pageSize\n    *          the number of items per page\n    */\n   public ListUsersOptions pageSize(long pageSize) {\n      this.queryParameters.replaceValues(\"pagesize\", ImmutableSet.of(pageSize + \"\"));\n      return this;\n   }\n\n\n   public static class Builder {\n      /**\n       * @see ListUsersOptions#id\n       */\n      public static ListUsersOptions id(String id) {\n         ListUsersOptions options = new ListUsersOptions();\n         return options.id(id);\n      }\n\n      /**\n       * @see ListUsersOptions#userName(String)\n       */\n      public static ListUsersOptions userName(String name) {\n         ListUsersOptions options = new ListUsersOptions();\n         return options.userName(name);\n      }\n\n      /**\n       * @see ListUsersOptions#state\n       */\n      public static ListUsersOptions state(User.State state) {\n         ListUsersOptions options = new ListUsersOptions();\n         return options.state(state);\n      }\n\n      /**\n       * @see ListUsersOptions#accountType\n       */\n      public static ListUsersOptions accountType(String accountType) {\n         ListUsersOptions options = new ListUsersOptions();\n         return options.accountType(accountType);\n      }\n\n      /**\n       * @see ListUsersOptions#keyword\n       */\n      public static ListUsersOptions keyword(String keyword) {\n         ListUsersOptions options = new ListUsersOptions();\n         return options.keyword(keyword);\n      }\n\n      /**\n       * @see ListUsersOptions#page\n       */\n      public static ListUsersOptions page(long page) {\n         ListUsersOptions options = new ListUsersOptions();\n         return options.page(page);\n      }\n\n      /**\n       * @see ListUsersOptions#pageSize\n       */\n      public static ListUsersOptions pageSize(long pageSize) {\n         ListUsersOptions options = new ListUsersOptions();\n         return options.pageSize(pageSize);\n      }\n\n      /**\n       * @see ListUsersOptions#accountInDomain\n       */\n      public static ListUsersOptions accountInDomain(String account, String domain) {\n         ListUsersOptions options = new ListUsersOptions();\n         return options.accountInDomain(account, domain);\n      }\n\n      /**\n       * @see ListUsersOptions#domainId\n       */\n      public static ListUsersOptions domainId(String id) {\n         ListUsersOptions options = new ListUsersOptions();\n         return options.domainId(id);\n      }\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ListUsersOptions accountInDomain(String account, String domain) {\n      return ListUsersOptions.class.cast(super.accountInDomain(account, domain));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ListUsersOptions domainId(String domainId) {\n      return ListUsersOptions.class.cast(super.domainId(domainId));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/ListVMGroupsOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options used to control what VMGroups information is returned\n *\n * @see <a\n *      href=\"http://download.cloud.com/releases/2.2.8/api/user/listInstanceGroups.html\"\n *      />\n */\npublic class ListVMGroupsOptions extends BaseHttpRequestOptions {\n\n   public static final ListVMGroupsOptions NONE = new ListVMGroupsOptions();\n\n   /**\n    * @param id list VMGroups by id\n    */\n   public ListVMGroupsOptions id(String id) {\n      this.queryParameters.replaceValues(\"id\", ImmutableSet.of(id + \"\"));\n      return this;\n   }\n\n   /**\n    * @param account account who owns the VMGroups\n    */\n   public ListVMGroupsOptions account(String account) {\n      this.queryParameters.replaceValues(\"account\", ImmutableSet.of(account));\n      return this;\n   }\n\n   /**\n    * @param domainId domain ID of the account owning the VMGroups\n    */\n   public ListVMGroupsOptions domainId(String domainId) {\n      this.queryParameters.replaceValues(\"domainid\", ImmutableSet.of(domainId + \"\"));\n      return this;\n   }\n\n   /**\n    * @param projectId id of the project the vm group is in\n    */\n   public ListVMGroupsOptions projectId(String projectId) {\n      this.queryParameters.replaceValues(\"projectid\", ImmutableSet.of(projectId + \"\"));\n      return this;\n   }\n\n   /**\n    * @param keyword keyword to search on\n    */\n   public ListVMGroupsOptions keyword(String keyword) {\n      this.queryParameters.replaceValues(\"keyword\", ImmutableSet.of(keyword));\n      return this;\n   }\n\n   /**\n    * @param name find a VMGroup by its name\n    */\n   public ListVMGroupsOptions name(String name) {\n      this.queryParameters.replaceValues(\"name\", ImmutableSet.of(name));\n      return this;\n   }\n\n   public static class Builder {\n      /**\n       * @see org.jclouds.cloudstack.options.ListVMGroupsOptions#id\n       */\n      public static ListVMGroupsOptions id(String id) {\n         ListVMGroupsOptions options = new ListVMGroupsOptions();\n         return options.id(id);\n      }\n\n      /**\n       * @see org.jclouds.cloudstack.options.ListVMGroupsOptions#account\n       */\n      public static ListVMGroupsOptions account(String account) {\n         ListVMGroupsOptions options = new ListVMGroupsOptions();\n         return options.account(account);\n      }\n\n      /**\n       * @see org.jclouds.cloudstack.options.ListVMGroupsOptions#domainId\n       */\n      public static ListVMGroupsOptions domainId(String id) {\n         ListVMGroupsOptions options = new ListVMGroupsOptions();\n         return options.domainId(id);\n      }\n\n      /**\n       * @see org.jclouds.cloudstack.options.ListVMGroupsOptions#projectId(String)\n       */\n      public static ListVMGroupsOptions projectId(String id) {\n         ListVMGroupsOptions options = new ListVMGroupsOptions();\n         return options.projectId(id);\n      }\n\n      /**\n       * @see org.jclouds.cloudstack.options.ListVMGroupsOptions#keyword\n       */\n      public static ListVMGroupsOptions keyword(String keyword) {\n         ListVMGroupsOptions options = new ListVMGroupsOptions();\n         return options.keyword(keyword);\n      }\n\n      /**\n       * @see org.jclouds.cloudstack.options.ListVMGroupsOptions#account\n       */\n      public static ListVMGroupsOptions name(String name) {\n         ListVMGroupsOptions options = new ListVMGroupsOptions();\n         return options.name(name);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/ListVirtualMachinesOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport java.util.Map;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options used to control what virtual machines information is returned\n * \n * @see <a href=\n *      \"http://download.cloud.com/releases/2.2.0/api/user/listVirtualMachines.html\"\n *      />\n */\npublic class ListVirtualMachinesOptions extends AccountInDomainOptions {\n\n   public static final ListVirtualMachinesOptions NONE = new ListVirtualMachinesOptions();\n\n   /**\n    * @param id\n    *           the ID of the virtual machine\n    */\n   public ListVirtualMachinesOptions id(String id) {\n      this.queryParameters.replaceValues(\"id\", ImmutableSet.of(id + \"\"));\n      return this;\n   }\n\n   /**\n    * @param name\n    *           the virtual machine name\n    */\n   public ListVirtualMachinesOptions name(String name) {\n      this.queryParameters.replaceValues(\"name\", ImmutableSet.of(name));\n      return this;\n   }\n\n   /**\n    * @param state\n    *           state of the virtual machine\n    */\n   public ListVirtualMachinesOptions state(String state) {\n      this.queryParameters.replaceValues(\"state\", ImmutableSet.of(state));\n      return this;\n   }\n\n   /**\n    * @param groupId\n    *           list virtual machines by groupId.\n    */\n   public ListVirtualMachinesOptions groupId(String groupId) {\n      this.queryParameters.replaceValues(\"groupid\", ImmutableSet.of(groupId + \"\"));\n      return this;\n\n   }\n\n   /**\n    * @param hostId\n    *           list virtual machines by hostId.\n    */\n   public ListVirtualMachinesOptions hostId(String hostId) {\n      this.queryParameters.replaceValues(\"hostid\", ImmutableSet.of(hostId + \"\"));\n      return this;\n\n   }\n\n   /**\n    * @param networkId\n    *           list virtual machines by networkId.\n    */\n   public ListVirtualMachinesOptions networkId(String networkId) {\n      this.queryParameters.replaceValues(\"networkid\", ImmutableSet.of(networkId + \"\"));\n      return this;\n\n   }\n\n   /**\n    * @param podId\n    *           list virtual machines by podId.\n    */\n   public ListVirtualMachinesOptions podId(String podId) {\n      this.queryParameters.replaceValues(\"podid\", ImmutableSet.of(podId + \"\"));\n      return this;\n\n   }\n\n   /**\n    * @param projectId\n    *           list virtual machines by projectId.\n    */\n   public ListVirtualMachinesOptions projectId(String projectId) {\n      this.queryParameters.replaceValues(\"projectid\", ImmutableSet.of(projectId + \"\"));\n      return this;\n\n   }\n\n   /**\n    * @param zoneId\n    *           list virtual machines by zoneId.\n    */\n   public ListVirtualMachinesOptions zoneId(String zoneId) {\n      this.queryParameters.replaceValues(\"zoneid\", ImmutableSet.of(zoneId + \"\"));\n      return this;\n\n   }\n\n   /**\n    * @param usesVirtualNetwork\n    *           list by network type; true if need to list vms using Virtual\n    *           Network, false otherwise\n    */\n   public ListVirtualMachinesOptions usesVirtualNetwork(boolean usesVirtualNetwork) {\n      this.queryParameters.replaceValues(\"forvirtualnetwork\", ImmutableSet.of(usesVirtualNetwork + \"\"));\n      return this;\n   }\n\n   /**\n    * @param tags\n    *           Key/value pairs for tags that need to be matched.\n    */\n   public ListVirtualMachinesOptions tags(Map<String, String> tags) {\n      int count = 0;\n      for (Map.Entry<String, String> entry : tags.entrySet()) {\n         this.queryParameters.replaceValues(String.format(\"tags[%d].key\", count), ImmutableSet.of(entry.getKey()));\n         this.queryParameters.replaceValues(String.format(\"tags[%d].value\", count),\n               ImmutableSet.of(entry.getValue()));\n         count += 1;\n      }\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see ListVirtualMachinesOptions#accountInDomain\n       */\n      public static ListVirtualMachinesOptions accountInDomain(String account, String domain) {\n         ListVirtualMachinesOptions options = new ListVirtualMachinesOptions();\n         return options.accountInDomain(account, domain);\n      }\n\n      /**\n       * @see ListVirtualMachinesOptions#domainId\n       */\n      public static ListVirtualMachinesOptions domainId(String id) {\n         ListVirtualMachinesOptions options = new ListVirtualMachinesOptions();\n         return options.domainId(id);\n      }\n\n      /**\n       * @see ListVirtualMachinesOptions#id\n       */\n      public static ListVirtualMachinesOptions id(String id) {\n         ListVirtualMachinesOptions options = new ListVirtualMachinesOptions();\n         return options.id(id);\n      }\n\n      /**\n       * @see ListVirtualMachinesOptions#name\n       */\n      public static ListVirtualMachinesOptions name(String name) {\n         ListVirtualMachinesOptions options = new ListVirtualMachinesOptions();\n         return options.name(name);\n      }\n\n      /**\n       * @see ListVirtualMachinesOptions#state\n       */\n      public static ListVirtualMachinesOptions state(String state) {\n         ListVirtualMachinesOptions options = new ListVirtualMachinesOptions();\n         return options.state(state);\n      }\n\n      /**\n       * @see ListVirtualMachinesOptions#groupId\n       */\n      public static ListVirtualMachinesOptions groupId(String id) {\n         ListVirtualMachinesOptions options = new ListVirtualMachinesOptions();\n         return options.groupId(id);\n      }\n\n      /**\n       * @see ListVirtualMachinesOptions#hostId\n       */\n      public static ListVirtualMachinesOptions hostId(String id) {\n         ListVirtualMachinesOptions options = new ListVirtualMachinesOptions();\n         return options.hostId(id);\n      }\n\n      /**\n       * @see ListVirtualMachinesOptions#networkId\n       */\n      public static ListVirtualMachinesOptions networkId(String id) {\n         ListVirtualMachinesOptions options = new ListVirtualMachinesOptions();\n         return options.networkId(id);\n      }\n\n      /**\n       * @see ListVirtualMachinesOptions#podId\n       */\n      public static ListVirtualMachinesOptions podId(String id) {\n         ListVirtualMachinesOptions options = new ListVirtualMachinesOptions();\n         return options.podId(id);\n      }\n\n      /**\n       * @see ListVirtualMachinesOptions#projectId(String)\n       */\n      public static ListVirtualMachinesOptions projectId(String id) {\n         ListVirtualMachinesOptions options = new ListVirtualMachinesOptions();\n         return options.projectId(id);\n      }\n\n      /**\n       * @see ListVirtualMachinesOptions#zoneId\n       */\n      public static ListVirtualMachinesOptions zoneId(String id) {\n         ListVirtualMachinesOptions options = new ListVirtualMachinesOptions();\n         return options.zoneId(id);\n      }\n\n      /**\n       * @see ListVirtualMachinesOptions#usesVirtualNetwork\n       */\n      public static ListVirtualMachinesOptions usesVirtualNetwork(boolean usesVirtualNetwork) {\n         ListVirtualMachinesOptions options = new ListVirtualMachinesOptions();\n         return options.usesVirtualNetwork(usesVirtualNetwork);\n      }\n\n      /**\n       * @see ListVirtualMachinesOptions#tags\n       */\n      public static ListVirtualMachinesOptions tags(Map<String, String> tags) {\n         ListVirtualMachinesOptions options = new ListVirtualMachinesOptions();\n         return options.tags(tags);\n      }\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ListVirtualMachinesOptions accountInDomain(String account, String domain) {\n      return ListVirtualMachinesOptions.class.cast(super.accountInDomain(account, domain));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ListVirtualMachinesOptions domainId(String domainId) {\n      return ListVirtualMachinesOptions.class.cast(super.domainId(domainId));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/ListVlanIPRangesOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options to the listVLANIPRanges() API call\n */\npublic class ListVlanIPRangesOptions extends AccountInDomainOptions {\n\n   public static class Builder {\n\n      public static ListVlanIPRangesOptions accountInDomain(String account, String domainId) {\n         return new ListVlanIPRangesOptions().accountInDomain(account, domainId);\n      }\n\n      public static ListVlanIPRangesOptions domainId(String domainId) {\n         return new ListVlanIPRangesOptions().domainId(domainId);\n      }\n\n      public static ListVlanIPRangesOptions forVirtualNetwork(boolean forVirtualNetwork) {\n         return new ListVlanIPRangesOptions().forVirtualNetwork(forVirtualNetwork);\n      }\n\n      public static ListVlanIPRangesOptions id(String id) {\n         return new ListVlanIPRangesOptions().id(id);\n      }\n\n      public static ListVlanIPRangesOptions keyword(String keyword) {\n         return new ListVlanIPRangesOptions().keyword(keyword);\n      }\n\n      public static ListVlanIPRangesOptions networkId(String networkId) {\n         return new ListVlanIPRangesOptions().networkId(networkId);\n      }\n\n      public static ListVlanIPRangesOptions podId(String podId) {\n         return new ListVlanIPRangesOptions().podId(podId);\n      }\n\n      public static ListVlanIPRangesOptions projectId(String projectId) {\n         return new ListVlanIPRangesOptions().projectId(projectId);\n      }\n\n      public static ListVlanIPRangesOptions vlan(long vlan) {\n         return new ListVlanIPRangesOptions().vlan(vlan);\n      }\n\n      public static ListVlanIPRangesOptions vlan(String vlan) {\n         return new ListVlanIPRangesOptions().vlan(vlan + \"\");\n      }\n\n      public static ListVlanIPRangesOptions zoneId(String zoneId) {\n         return new ListVlanIPRangesOptions().zoneId(zoneId);\n      }\n   }\n\n   @Override\n   public ListVlanIPRangesOptions accountInDomain(String account, String domainId) {\n      return (ListVlanIPRangesOptions) super.accountInDomain(account, domainId);\n   }\n\n   @Override\n   public ListVlanIPRangesOptions domainId(String domainId) {\n      return (ListVlanIPRangesOptions) super.domainId(domainId);\n   }\n\n   public ListVlanIPRangesOptions forVirtualNetwork(boolean forVirtualNetwork) {\n      this.queryParameters.replaceValues(\"forvirtualnetwork\", ImmutableSet.of(forVirtualNetwork + \"\"));\n      return this;\n   }\n\n   public ListVlanIPRangesOptions id(String id) {\n      this.queryParameters.replaceValues(\"id\", ImmutableSet.of(id + \"\"));\n      return this;\n   }\n\n   public ListVlanIPRangesOptions keyword(String keyword) {\n      this.queryParameters.replaceValues(\"keyword\", ImmutableSet.of(keyword));\n      return this;\n   }\n\n   public ListVlanIPRangesOptions networkId(String networkId) {\n      this.queryParameters.replaceValues(\"networkid\", ImmutableSet.of(networkId + \"\"));\n      return this;\n   }\n\n   public ListVlanIPRangesOptions podId(String podId) {\n      this.queryParameters.replaceValues(\"podid\", ImmutableSet.of(podId + \"\"));\n      return this;\n   }\n\n   public ListVlanIPRangesOptions projectId(String projectId) {\n      this.queryParameters.replaceValues(\"projectid\", ImmutableSet.of(projectId + \"\"));\n      return this;\n   }\n\n   public ListVlanIPRangesOptions vlan(String vlan) {\n      this.queryParameters.replaceValues(\"vlan\", ImmutableSet.of(vlan));\n      return this;\n   }\n\n   public ListVlanIPRangesOptions vlan(long vlan) {\n      this.queryParameters.replaceValues(\"vlan\", ImmutableSet.of(vlan + \"\"));\n      return this;\n   }\n\n   public ListVlanIPRangesOptions zoneId(String zoneId) {\n      this.queryParameters.replaceValues(\"zoneid\", ImmutableSet.of(zoneId + \"\"));\n      return this;\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/ListVolumesOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport java.util.Map;\n\nimport org.jclouds.cloudstack.domain.Volume;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options used to control what volume\n */\npublic class ListVolumesOptions extends AccountInDomainOptions {\n\n   public static final ListVolumesOptions NONE = new ListVolumesOptions();\n\n   /**\n    * List volumes on specified host\n    *\n    * @param hostId hostId.\n    */\n   public ListVolumesOptions hostId(String hostId) {\n      this.queryParameters.replaceValues(\"hostid\", ImmutableSet.of(hostId + \"\"));\n      return this;\n   }\n\n   /**\n    * @param id the ID of the volume\n    */\n   public ListVolumesOptions id(String id) {\n      this.queryParameters.replaceValues(\"id\", ImmutableSet.of(id + \"\"));\n      return this;\n   }\n\n   /**\n    * @param recursive defaults to false, but if true, lists all volumes from the parent specified by the domain id till leaves.\n    */\n   public ListVolumesOptions isRecursive(boolean recursive) {\n      this.queryParameters.replaceValues(\"isrecursive\", ImmutableSet.of(String.valueOf(recursive)));\n      return this;\n   }\n\n\n   /**\n    * @param keyword List by keyword\n    */\n   public ListVolumesOptions keyword(String keyword) {\n      this.queryParameters.replaceValues(\"keyword\", ImmutableSet.of(keyword));\n      return this;\n   }\n\n   /**\n    * @param name the name of the disk volume\n    */\n   public ListVolumesOptions name(String name) {\n      this.queryParameters.replaceValues(\"name\", ImmutableSet.of(name));\n      return this;\n   }\n\n   /**\n    * @param podId the pod id the disk volume belongs to\n    */\n   public ListVolumesOptions podId(String podId) {\n      this.queryParameters.replaceValues(\"podid\", ImmutableSet.of(podId + \"\"));\n      return this;\n\n   }\n\n   /**\n    * @param type the type of the disk volume\n    */\n   public ListVolumesOptions type(Volume.Type type) {\n      this.queryParameters.replaceValues(\"type\", ImmutableSet.of(type .toString()));\n      return this;\n   }\n\n   /**\n    * @param virtualMachineId list volumes by id virtual machine.\n    */\n   public ListVolumesOptions virtualMachineId(String virtualMachineId) {\n      this.queryParameters.replaceValues(\"virtualmachineid\", ImmutableSet.of(virtualMachineId + \"\"));\n      return this;\n\n   }\n\n   /**\n    * @param zoneId list volumes  by zoneId.\n    */\n   public ListVolumesOptions zoneId(String zoneId) {\n      this.queryParameters.replaceValues(\"zoneid\", ImmutableSet.of(zoneId + \"\"));\n      return this;\n\n   }\n\n   /**\n    * @param projectId list volumes  by projectId.\n    */\n   public ListVolumesOptions projectId(String projectId) {\n      this.queryParameters.replaceValues(\"projectid\", ImmutableSet.of(projectId + \"\"));\n      return this;\n\n   }\n\n   /**\n    * @param tags\n    *           Key/value pairs for tags that need to be matched.\n    */\n   public ListVolumesOptions tags(Map<String, String> tags) {\n      int count = 0;\n      for (Map.Entry<String, String> entry : tags.entrySet()) {\n         this.queryParameters.replaceValues(String.format(\"tags[%d].key\", count), ImmutableSet.of(entry.getKey()));\n         this.queryParameters.replaceValues(String.format(\"tags[%d].value\", count),\n               ImmutableSet.of(entry.getValue()));\n         count += 1;\n      }\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see ListVolumesOptions#accountInDomain\n       */\n      public static ListVolumesOptions accountInDomain(String account, String domain) {\n         ListVolumesOptions options = new ListVolumesOptions();\n         return options.accountInDomain(account, domain);\n      }\n\n      /**\n       * @see ListVolumesOptions#domainId\n       */\n      public static ListVolumesOptions domainId(String id) {\n         ListVolumesOptions options = new ListVolumesOptions();\n         return options.domainId(id);\n      }\n\n      /**\n       * @see ListVolumesOptions#hostId\n       */\n      public static ListVolumesOptions hostId(String id) {\n         ListVolumesOptions options = new ListVolumesOptions();\n         return options.hostId(id);\n      }\n\n      /**\n       * @see ListVolumesOptions#id\n       */\n      public static ListVolumesOptions id(String id) {\n         ListVolumesOptions options = new ListVolumesOptions();\n         return options.id(id);\n      }\n\n      /**\n       * @see ListVolumesOptions#isRecursive(boolean)\n       */\n      public static ListVolumesOptions isRecursive(boolean recursive) {\n         ListVolumesOptions options = new ListVolumesOptions();\n         return options.isRecursive(recursive);\n      }\n\n      /**\n       * @see ListVolumesOptions#name\n       */\n      public static ListVolumesOptions keyword(String keyword) {\n         ListVolumesOptions options = new ListVolumesOptions();\n         return options.keyword(keyword);\n      }\n\n      /**\n       * @see ListVolumesOptions#name\n       */\n      public static ListVolumesOptions name(String name) {\n         ListVolumesOptions options = new ListVolumesOptions();\n         return options.name(name);\n      }\n\n\n      /**\n       * @see ListVolumesOptions#podId\n       */\n      public static ListVolumesOptions podId(String id) {\n         ListVolumesOptions options = new ListVolumesOptions();\n         return options.podId(id);\n      }\n\n      /**\n       * @see ListVolumesOptions#type\n       */\n      public static ListVolumesOptions type(Volume.Type type) {\n         ListVolumesOptions options = new ListVolumesOptions();\n         return options.type(type);\n      }\n\n      /**\n       * @see ListVolumesOptions#virtualMachineId(String)\n       */\n      public static ListVolumesOptions virtualMachineId(String virtualMachineId) {\n         ListVolumesOptions options = new ListVolumesOptions();\n         return options.virtualMachineId(virtualMachineId);\n      }\n\n      /**\n       * @see ListVolumesOptions#zoneId\n       */\n      public static ListVolumesOptions zoneId(String id) {\n         ListVolumesOptions options = new ListVolumesOptions();\n         return options.zoneId(id);\n      }\n\n      /**\n       * @see ListVolumesOptions#projectId(String)\n       */\n      public static ListVolumesOptions projectId(String id) {\n         ListVolumesOptions options = new ListVolumesOptions();\n         return options.projectId(id);\n      }\n\n      /**\n       * @see ListVolumesOptions#tags\n       */\n      public static ListVolumesOptions tags(Map<String, String> tags) {\n         ListVolumesOptions options = new ListVolumesOptions();\n         return options.tags(tags);\n      }\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ListVolumesOptions accountInDomain(String account, String domain) {\n      return ListVolumesOptions.class.cast(super.accountInDomain(account, domain));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ListVolumesOptions domainId(String domainId) {\n      return ListVolumesOptions.class.cast(super.domainId(domainId));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/ListZonesOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport java.util.Map;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options used to control what zones information is returned\n * \n * @see <a\n *      href=\"http://download.cloud.com/releases/2.2.0/api/user/listZones.html\"\n *      />\n */\npublic class ListZonesOptions extends BaseHttpRequestOptions {\n\n   public static final ListZonesOptions NONE = new ListZonesOptions();\n\n   /**\n    * @param id\n    *           the ID of the zone\n    */\n   public ListZonesOptions id(String id) {\n      this.queryParameters.replaceValues(\"id\", ImmutableSet.of(id + \"\"));\n      return this;\n   }\n\n   /**\n    * @param domainId\n    *           the ID of the domain associated with the zone\n    */\n   public ListZonesOptions domainId(String domainId) {\n      this.queryParameters.replaceValues(\"domainid\", ImmutableSet.of(domainId + \"\"));\n      return this;\n\n   }\n\n   /**\n    * @param available\n    *           true if you want to retrieve all available Zones. False if you\n    *           only want to return the Zones from which you have at least one\n    *           VM. Default is false.\n    */\n   public ListZonesOptions available(boolean available) {\n      this.queryParameters.replaceValues(\"available\", ImmutableSet.of(available + \"\"));\n      return this;\n   }\n\n   /**\n    * @param tags\n    *           Key/value pairs for tags that need to be matched.\n    */\n   public ListZonesOptions tags(Map<String, String> tags) {\n      int count = 0;\n      for (Map.Entry<String, String> entry : tags.entrySet()) {\n         this.queryParameters.replaceValues(String.format(\"tags[%d].key\", count), ImmutableSet.of(entry.getKey()));\n         this.queryParameters.replaceValues(String.format(\"tags[%d].value\", count),\n               ImmutableSet.of(entry.getValue()));\n         count += 1;\n      }\n      return this;\n   }\n   public static class Builder {\n\n      /**\n       * @see ListZonesOptions#available\n       */\n      public static ListZonesOptions available(boolean available) {\n         ListZonesOptions options = new ListZonesOptions();\n         return options.available(available);\n      }\n\n      /**\n       * @see ListZonesOptions#domainId\n       */\n      public static ListZonesOptions domainId(String id) {\n         ListZonesOptions options = new ListZonesOptions();\n         return options.domainId(id);\n      }\n\n      /**\n       * @see ListZonesOptions#id\n       */\n      public static ListZonesOptions id(String id) {\n         ListZonesOptions options = new ListZonesOptions();\n         return options.id(id);\n      }\n\n      /**\n       * @see ListZonesOptions#tags\n       */\n      public static ListZonesOptions tags(Map<String, String> tags) {\n         ListZonesOptions options = new ListZonesOptions();\n         return options.tags(tags);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/RegisterISOOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options for the ISO registerISO method.\n *\n * @see org.jclouds.cloudstack.features.ISOApi#registerISO\n * @see org.jclouds.cloudstack.features.ISOApi#registerISO\n */\npublic class RegisterISOOptions extends AccountInDomainOptions {\n\n   public static final RegisterISOOptions NONE = new RegisterISOOptions();\n\n   /**\n    * @param bootable true if this ISO is bootable\n    */\n   public RegisterISOOptions bootable(boolean bootable) {\n      this.queryParameters.replaceValues(\"bootable\", ImmutableSet.of(bootable + \"\"));\n      return this;\n   }\n\n   /**\n    * @param isExtractable true if the iso or its derivatives are extractable; default is false\n    */\n   public RegisterISOOptions isExtractable(boolean isExtractable) {\n      this.queryParameters.replaceValues(\"isextractable\", ImmutableSet.of(isExtractable + \"\"));\n      return this;\n   }\n\n   /**\n    * @param isFeatured true if you want this ISO to be featured\n    */\n   public RegisterISOOptions isFeatured(boolean isFeatured) {\n      this.queryParameters.replaceValues(\"isfeatured\", ImmutableSet.of(isFeatured + \"\"));\n      return this;\n   }\n\n   /**\n    * @param isPublic true if you want to register the ISO to be publicly available to all users, false otherwise.\n    */\n   public RegisterISOOptions isPublic(boolean isPublic) {\n      this.queryParameters.replaceValues(\"ispublic\", ImmutableSet.of(isPublic + \"\"));\n      return this;\n   }\n\n   /**\n    * @param osTypeId the ID of the OS Type that best represents the OS of this ISO\n    */\n   public RegisterISOOptions osTypeId(String osTypeId) {\n      this.queryParameters.replaceValues(\"ostypeid\", ImmutableSet.of(osTypeId + \"\"));\n      return this;\n   }\n\n   /**\n    * @param projectId the project this ISO will be in.\n    */\n   public RegisterISOOptions projectId(String projectId) {\n      this.queryParameters.replaceValues(\"projectid\", ImmutableSet.of(projectId + \"\"));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @param account an optional account name. Must be used with domainId.\n       */\n      public static RegisterISOOptions accountInDomain(String account, String domainId) {\n         return (RegisterISOOptions) new RegisterISOOptions().accountInDomain(account, domainId);\n      }\n\n      /**\n       * @param bootable true if this ISO is bootable\n       */\n      public static RegisterISOOptions bootable(boolean bootable) {\n         return new RegisterISOOptions().bootable(bootable);\n      }\n\n      /**\n       * @param domainId an optional domainId. If the account parameter is used, domainId must also be used.\n       */\n      public static RegisterISOOptions domainId(String domainId) {\n         return (RegisterISOOptions) new RegisterISOOptions().domainId(domainId);\n      }\n\n      /**\n       * @param isExtractable true if the iso or its derivatives are extractable; default is false\n       */\n      public static RegisterISOOptions isExtractable(boolean isExtractable) {\n         return new RegisterISOOptions().isExtractable(isExtractable);\n      }\n\n      /**\n       * @param isFeatured true if you want this ISO to be featured\n       */\n      public static RegisterISOOptions isFeatured(boolean isFeatured) {\n         return new RegisterISOOptions().isFeatured(isFeatured);\n      }\n\n      /**\n       * @param isPublic true if you want to register the ISO to be publicly available to all users, false otherwise.\n       */\n      public static RegisterISOOptions isPublic(boolean isPublic) {\n         return new RegisterISOOptions().isPublic(isPublic);\n      }\n\n      /**\n       * @param osTypeId the ID of the OS Type that best represents the OS of this ISO\n       */\n      public static RegisterISOOptions osTypeId(String osTypeId) {\n         return new RegisterISOOptions().osTypeId(osTypeId);\n      }\n\n      /**\n       * @param projectId the project this ISO will be in.\n       */\n      public static RegisterISOOptions projectId(String projectId) {\n         return new RegisterISOOptions().projectId(projectId);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/RegisterTemplateOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options used to control how a template is registered.\n *\n * @see <a\n *      href=\"http://download.cloud.com/releases/2.2.8/api/user/registerTemplate.html\"\n *      />\n */\npublic class RegisterTemplateOptions extends AccountInDomainOptions {\n\n   public static final RegisterTemplateOptions NONE = new RegisterTemplateOptions();\n\n   /**\n    * 32 or 64 bits support. 64 by default\n    */\n   public RegisterTemplateOptions bits(int bits) {\n      this.queryParameters.replaceValues(\"bits\", ImmutableSet.of(bits + \"\"));\n      return this;\n   }\n\n   /**\n    * the MD5 checksum value of this template\n    */\n   public RegisterTemplateOptions checksum(String checksum) {\n      this.queryParameters.replaceValues(\"checksum\", ImmutableSet.of(checksum));\n      return this;\n   }\n\n   /**\n    * the project for this template.\n    */\n   public RegisterTemplateOptions projectId(String projectId) {\n      this.queryParameters.replaceValues(\"projectid\", ImmutableSet.of(projectId + \"\"));\n      return this;\n   }\n\n   /**\n    * true if the template or its derivatives are extractable; default is true\n    */\n   public RegisterTemplateOptions isExtractable(boolean isExtractable) {\n      this.queryParameters.replaceValues(\"isextractable\", ImmutableSet.of(isExtractable + \"\"));\n      return this;\n   }\n\n   /**\n    * true if this template is a featured template, false otherwise\n    */\n   public RegisterTemplateOptions isFeatured(boolean isFeatured) {\n      this.queryParameters.replaceValues(\"isfeatured\", ImmutableSet.of(isFeatured + \"\"));\n      return this;\n   }\n\n   /**\n    * true if the template is available to all accounts; default is true\n    */\n   public RegisterTemplateOptions isPublic(boolean isPublic) {\n      this.queryParameters.replaceValues(\"ispublic\", ImmutableSet.of(isPublic + \"\"));\n      return this;\n   }\n\n   /**\n    * true if the template supports the password reset feature; default is false\n    */\n   public RegisterTemplateOptions passwordEnabled(boolean passwordEnabled) {\n      this.queryParameters.replaceValues(\"passwordenabled\", ImmutableSet.of(passwordEnabled + \"\"));\n      return this;\n   }\n\n   /**\n    * true if this template requires HVM\n    */\n   public RegisterTemplateOptions requiresHVM(boolean requiresHVM) {\n      this.queryParameters.replaceValues(\"requireshvm\", ImmutableSet.of(requiresHVM + \"\"));\n      return this;\n   }\n\n   public static class Builder {\n\n      public static RegisterTemplateOptions bits(int bits) {\n         RegisterTemplateOptions options = new RegisterTemplateOptions();\n         return options.bits(bits);\n      }\n\n      public static RegisterTemplateOptions checksum(String checksum) {\n         RegisterTemplateOptions options = new RegisterTemplateOptions();\n         return options.checksum(checksum);\n      }\n\n      public static RegisterTemplateOptions projectId(String projectId) {\n         RegisterTemplateOptions options = new RegisterTemplateOptions();\n         return options.projectId(projectId);\n      }\n\n      public static RegisterTemplateOptions isExtractable(boolean isExtractable) {\n         RegisterTemplateOptions options = new RegisterTemplateOptions();\n         return options.isExtractable(isExtractable);\n      }\n\n      public static RegisterTemplateOptions isFeatured(boolean isFeatured) {\n         RegisterTemplateOptions options = new RegisterTemplateOptions();\n         return options.isFeatured(isFeatured);\n      }\n\n      public static RegisterTemplateOptions isPublic(boolean isPublic) {\n         RegisterTemplateOptions options = new RegisterTemplateOptions();\n         return options.isPublic(isPublic);\n      }\n\n      public static RegisterTemplateOptions passwordEnabled(boolean passwordEnabled) {\n         RegisterTemplateOptions options = new RegisterTemplateOptions();\n         return options.passwordEnabled(passwordEnabled);\n      }\n\n      public static RegisterTemplateOptions requiresHVM(boolean requiresHVM) {\n         RegisterTemplateOptions options = new RegisterTemplateOptions();\n         return options.requiresHVM(requiresHVM);\n      }\n\n      /**\n       * @see AccountInDomainOptions#accountInDomain\n       */\n      public static RegisterTemplateOptions accountInDomain(String account, String domain) {\n         RegisterTemplateOptions options = new RegisterTemplateOptions();\n         return (RegisterTemplateOptions)options.accountInDomain(account, domain);\n      }\n\n      /**\n       * @see AccountInDomainOptions#domainId\n       */\n      public static RegisterTemplateOptions domainId(String domainId) {\n         RegisterTemplateOptions options = new RegisterTemplateOptions();\n         return (RegisterTemplateOptions)options.domainId(domainId);\n      }\n   }\n   \n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/StopVirtualMachineOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options for stopping virtual machines.\n * \n * @see <a\n *      href=\"http://download.cloud.com/releases/3.0.3/api_3.0.3/root_admin/stopVirtualMachine.html\"\n *      />\n */\npublic class StopVirtualMachineOptions extends BaseHttpRequestOptions {\n\n   public static final StopVirtualMachineOptions NONE = new StopVirtualMachineOptions();\n\n   /**\n    * @param forced\n    *           Whether to force stop the virtual machine. Defaults to false.\n    */\n   public StopVirtualMachineOptions forced(boolean forced) {\n      this.queryParameters.replaceValues(\"forced\", ImmutableSet.of(forced + \"\"));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see StopVirtualMachineOptions#forced\n       */\n      public static StopVirtualMachineOptions forced(boolean forced) {\n         StopVirtualMachineOptions options = new StopVirtualMachineOptions();\n         return options.forced(forced);\n      }\n\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/UpdateAccountOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Optional arguments for updating an Account\n * \n * @see <a\n *      href=\"http://download.cloud.com/releases/2.2.0/api_2.2.12/global_admin/updateAccount.html\"\n *      />\n */\npublic class UpdateAccountOptions extends BaseHttpRequestOptions {\n\n   public static final UpdateAccountOptions NONE = new UpdateAccountOptions();\n\n   /**\n    * @param networkDomain\n    *       network domain for the account's networks\n    */\n   public UpdateAccountOptions networkDomain(String networkDomain) {\n      this.queryParameters.replaceValues(\"networkdomain\", ImmutableSet.<String>of(networkDomain));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see UpdateAccountOptions#networkDomain\n       */\n      public static UpdateAccountOptions networkDomain(String networkDomain) {\n         UpdateAccountOptions options = new UpdateAccountOptions();\n         return options.networkDomain(networkDomain);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/UpdateClusterOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.cloudstack.domain.AllocationState;\nimport org.jclouds.cloudstack.domain.Cluster;\nimport org.jclouds.cloudstack.domain.Host;\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options for the GlobalHostApi.updateCluster() API call.\n */\npublic class UpdateClusterOptions extends BaseHttpRequestOptions {\n\n   public static final UpdateClusterOptions NONE = new UpdateClusterOptions();\n\n   /**\n    * @param allocationState Allocation state of this cluster for allocation of new resources\n    */\n   public UpdateClusterOptions allocationState(AllocationState allocationState) {\n      this.queryParameters.replaceValues(\"allocationstate\", ImmutableSet.<String>of(allocationState.toString()));\n      return this;\n   }\n\n   /**\n    * @param clusterName the cluster name\n    */\n   public UpdateClusterOptions clusterName(String clusterName) {\n      this.queryParameters.replaceValues(\"clustername\", ImmutableSet.<String>of(clusterName));\n      return this;\n   }\n\n   /**\n    * @param clusterType type of the cluster\n    */\n   public UpdateClusterOptions clusterType(Host.ClusterType clusterType) {\n      this.queryParameters.replaceValues(\"clustertype\", ImmutableSet.<String>of(clusterType.toString()));\n      return this;\n   }\n\n   /**\n    * @param hypervisor hypervisor type of the cluster\n    */\n   public UpdateClusterOptions hypervisor(String hypervisor) {\n      this.queryParameters.replaceValues(\"hypervisor\", ImmutableSet.<String>of(hypervisor));\n      return this;\n   }\n\n   /**\n    * @param managedState whether this cluster is managed by cloudstack\n    */\n   public UpdateClusterOptions managedState(Cluster.ManagedState managedState) {\n      this.queryParameters.replaceValues(\"managedstate\", ImmutableSet.<String>of(managedState.toString()));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @param allocationState Allocation state of this cluster for allocation of new resources\n       */\n      public static UpdateClusterOptions allocationState(AllocationState allocationState) {\n         return new UpdateClusterOptions().allocationState(allocationState);\n      }\n\n      /**\n       * @param clusterName the cluster name\n       */\n      public static UpdateClusterOptions clusterName(String clusterName) {\n         return new UpdateClusterOptions().clusterName(clusterName);\n      }\n\n      /**\n       * @param clusterType type of the cluster\n       */\n      public static UpdateClusterOptions clusterType(Host.ClusterType clusterType) {\n         return new UpdateClusterOptions().clusterType(clusterType);\n      }\n\n      /**\n       * @param hypervisor hypervisor type of the cluster\n       */\n      public static UpdateClusterOptions hypervisor(String hypervisor) {\n         return new UpdateClusterOptions().hypervisor(hypervisor);\n      }\n\n      /**\n       * @param managedState whether this cluster is managed by cloudstack\n       */\n      public static UpdateClusterOptions managedState(Cluster.ManagedState managedState) {\n         return new UpdateClusterOptions().managedState(managedState);\n      }\n\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/UpdateDiskOfferingOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options to control how disk offerings are created\n * \n * @see <a\n *      href=\"http://download.cloud.com/releases/2.2.0/api_2.2.12/global_admin/updateDiskOffering.html\"\n *      />\n */\npublic class UpdateDiskOfferingOptions extends AccountInDomainOptions {\n\n   public static final UpdateDiskOfferingOptions NONE = new UpdateDiskOfferingOptions();\n\n   /**\n    * @param name\n    *       service offering name\n    */\n   public UpdateDiskOfferingOptions name(String name) {\n      this.queryParameters.replaceValues(\"name\", ImmutableSet.<String>of(name));\n      return this;\n   }\n\n   /**\n    * @param displayText\n    *       service offering display text\n    */\n   public UpdateDiskOfferingOptions displayText(String displayText) {\n      this.queryParameters.replaceValues(\"displaytext\", ImmutableSet.<String>of(displayText));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see org.jclouds.cloudstack.options.UpdateDiskOfferingOptions#name\n       */\n      public static UpdateDiskOfferingOptions name(String name) {\n         UpdateDiskOfferingOptions options = new UpdateDiskOfferingOptions();\n         return options.name(name);\n      }\n\n      /**\n       * @see org.jclouds.cloudstack.options.UpdateDiskOfferingOptions#displayText\n       */\n      public static UpdateDiskOfferingOptions displayText(String displayText) {\n         UpdateDiskOfferingOptions options = new UpdateDiskOfferingOptions();\n         return options.displayText(displayText);\n      }\n\n      /**\n       * @see org.jclouds.cloudstack.options.UpdateDiskOfferingOptions#accountInDomain\n       */\n      public static UpdateDiskOfferingOptions accountInDomain(String account, String domain) {\n         UpdateDiskOfferingOptions options = new UpdateDiskOfferingOptions();\n         return options.accountInDomain(account, domain);\n      }\n\n      /**\n       * @see org.jclouds.cloudstack.options.UpdateDiskOfferingOptions#domainId\n       */\n      public static UpdateDiskOfferingOptions domainId(String domainId) {\n         UpdateDiskOfferingOptions options = new UpdateDiskOfferingOptions();\n         return options.domainId(domainId);\n      }\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public UpdateDiskOfferingOptions accountInDomain(String account, String domain) {\n      return UpdateDiskOfferingOptions.class.cast(super.accountInDomain(account, domain));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public UpdateDiskOfferingOptions domainId(String domainId) {\n      return UpdateDiskOfferingOptions.class.cast(super.domainId(domainId));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/UpdateDomainOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options used to control how a domain is created\n * \n * @see <a href=\n *      \"http://download.cloud.com/releases/2.2.0/api_2.2.12/global_admin/createDomain.html\"\n *      />\n */\npublic class UpdateDomainOptions extends BaseHttpRequestOptions {\n\n   public static final UpdateDomainOptions NONE = new UpdateDomainOptions();\n\n   /**\n    * @param name\n    *       the new name for this domain\n    */\n   public UpdateDomainOptions name(String name) {\n      this.queryParameters.replaceValues(\"name\", ImmutableSet.of(name));\n      return this;\n   }\n\n   /**\n    * @param networkDomain\n    *       network domain for networks in the domain\n    */\n   public UpdateDomainOptions networkDomain(String networkDomain) {\n      this.queryParameters.replaceValues(\"networkdomain\", ImmutableSet.of(networkDomain));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see UpdateDomainOptions#name\n       */\n      public static UpdateDomainOptions name(String name) {\n         UpdateDomainOptions options = new UpdateDomainOptions();\n         return options.name(name);\n      }\n\n      /**\n       * @see UpdateDomainOptions#networkDomain\n       */\n      public static UpdateDomainOptions networkDomain(String networkDomain) {\n         UpdateDomainOptions options = new UpdateDomainOptions();\n         return options.networkDomain(networkDomain);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/UpdateHostOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.AllocationState;\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.base.Joiner;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options to the GlobalHostApi.addHost() API call\n */\npublic class UpdateHostOptions extends BaseHttpRequestOptions {\n\n\n   public static final UpdateHostOptions NONE = new UpdateHostOptions();\n\n   /**\n    * @param allocationState Allocation state of this Host for allocation of new resources\n    */\n   public UpdateHostOptions allocationState(AllocationState allocationState) {\n      this.queryParameters.replaceValues(\"allocationstate\", ImmutableSet.of(allocationState.toString()));\n      return this;\n   }\n\n   /**\n    * @param hostTags list of tags to be added to the host\n    */\n   public UpdateHostOptions hostTags(Set<String> hostTags) {\n      this.queryParameters.replaceValues(\"hosttags\", ImmutableSet.of(Joiner.on(',').join(hostTags)));\n      return this;\n   }\n\n   /**\n    * @param osCategoryId the id of Os category to update the host with\n    */\n   public UpdateHostOptions osCategoryId(String osCategoryId) {\n      this.queryParameters.replaceValues(\"oscategoryid\", ImmutableSet.of(osCategoryId + \"\"));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @param allocationState Allocation state of this Host for allocation of new resources\n       */\n      public static UpdateHostOptions allocationState(AllocationState allocationState) {\n         return new UpdateHostOptions().allocationState(allocationState);\n      }\n\n      /**\n       * @param hostTags list of tags to be added to the host\n       */\n      public static UpdateHostOptions hostTags(Set<String> hostTags) {\n         return new UpdateHostOptions().hostTags(hostTags);\n      }\n\n      /**\n       * @param podId the Pod ID for the host\n       */\n      public static UpdateHostOptions osCategoryId(String osCategoryId) {\n         return new UpdateHostOptions().osCategoryId(osCategoryId);\n      }\n\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/UpdateISOOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options for the ISO updateISO method.\n *\n * @see org.jclouds.cloudstack.features.ISOApi#updateISO\n * @see org.jclouds.cloudstack.features.ISOApi#updateISO\n */\npublic class UpdateISOOptions extends BaseHttpRequestOptions {\n\n   public static final UpdateISOOptions NONE = new UpdateISOOptions();\n\n   /**\n    * @param bootable true if image is bootable, false otherwise\n    */\n   public UpdateISOOptions bootable(boolean bootable) {\n      this.queryParameters.replaceValues(\"bootable\", ImmutableSet.of(bootable + \"\"));\n      return this;\n   }\n\n   /**\n    * @param displayText the display text of the image\n    */\n   public UpdateISOOptions displayText(String displayText) {\n      this.queryParameters.replaceValues(\"displaytext\", ImmutableSet.of(displayText + \"\"));\n      return this;\n   }\n\n   /**\n    * @param format the format for the image\n    */\n   public UpdateISOOptions format(String format) {\n      this.queryParameters.replaceValues(\"format\", ImmutableSet.of(format + \"\"));\n      return this;\n   }\n\n   /**\n    * @param name the name of the image file\n    */\n   public UpdateISOOptions name(String name) {\n      this.queryParameters.replaceValues(\"name\", ImmutableSet.of(name + \"\"));\n      return this;\n   }\n\n   /**\n    * @param osTypeId the ID of the OS type that best represents the OS of this image.\n    */\n   public UpdateISOOptions osTypeId(String osTypeId) {\n      this.queryParameters.replaceValues(\"ostypeid\", ImmutableSet.of(osTypeId + \"\"));\n      return this;\n   }\n\n   /**\n    * @param passwordEnabled true if the image supports the password reset feature; default is false\n    */\n   public UpdateISOOptions passwordEnabled(boolean passwordEnabled) {\n      this.queryParameters.replaceValues(\"passwordenabled\", ImmutableSet.of(passwordEnabled + \"\"));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @param bootable true if image is bootable, false otherwise\n       */\n      public static UpdateISOOptions bootable(boolean bootable) {\n         return new UpdateISOOptions().bootable(bootable);\n      }\n\n      /**\n       * @param displayText the display text of the image\n       */\n      public static UpdateISOOptions displayText(String displayText) {\n         return new UpdateISOOptions().displayText(displayText);\n      }\n\n      /**\n       * @param format the format for the image\n       */\n      public static UpdateISOOptions format(String format) {\n         return new UpdateISOOptions().format(format);\n      }\n\n      /**\n       * @param name the name of the image file\n       */\n      public static UpdateISOOptions name(String name) {\n         return new UpdateISOOptions().name(name);\n      }\n\n      /**\n       * @param osTypeId the ID of the OS type that best represents the OS of this image.\n       */\n      public static UpdateISOOptions osTypeId(String osTypeId) {\n         return new UpdateISOOptions().osTypeId(osTypeId);\n      }\n\n      /**\n       * @param passwordEnabled true if the image supports the password reset feature; default is false\n       */\n      public static UpdateISOOptions passwordEnabled(boolean passwordEnabled) {\n         return new UpdateISOOptions().passwordEnabled(passwordEnabled);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/UpdateISOPermissionsOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.cloudstack.domain.PermissionOperation;\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.base.Joiner;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options for the ISO updateISOPermissions method.\n *\n * @see org.jclouds.cloudstack.features.ISOApi#updateISOPermissions\n * @see org.jclouds.cloudstack.features.ISOApi#updateISOPermissions\n */\npublic class UpdateISOPermissionsOptions extends BaseHttpRequestOptions {\n\n   public static final UpdateISOPermissionsOptions NONE = new UpdateISOPermissionsOptions();\n\n   /**\n    * @param accounts a comma delimited list of accounts. If specified, \"op\" parameter has to be passed in.\n    */\n   public UpdateISOPermissionsOptions accounts(Iterable<String> accounts) {\n      this.queryParameters.replaceValues(\"accounts\", ImmutableSet.of(Joiner.on(',').join(accounts)));\n      return this;\n   }\n\n   /**\n    * @param isExtractable true if the template/iso is extractable, false other wise. Can be set only by root admin\n    */\n   public UpdateISOPermissionsOptions isExtractable(boolean isExtractable) {\n      this.queryParameters.replaceValues(\"isextractable\", ImmutableSet.of(isExtractable + \"\"));\n      return this;\n   }\n\n   /**\n    * @param isFeatured true for featured template/iso, false otherwise\n    */\n   public UpdateISOPermissionsOptions isFeatured(boolean isFeatured) {\n      this.queryParameters.replaceValues(\"isfeatured\", ImmutableSet.of(isFeatured + \"\"));\n      return this;\n   }\n\n   /**\n    * @param isPublic true for public template/iso, false for private templates/isos\n    */\n   public UpdateISOPermissionsOptions isPublic(boolean isPublic) {\n      this.queryParameters.replaceValues(\"ispublic\", ImmutableSet.of(isPublic + \"\"));\n      return this;\n   }\n\n   /**\n    * @param operation permission operator (add, remove, reset)\n    */\n   public UpdateISOPermissionsOptions operation(PermissionOperation operation) {\n      this.queryParameters.replaceValues(\"op\", ImmutableSet.of(operation + \"\"));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @param accounts a comma delimited list of accounts. If specified, \"op\" parameter has to be passed in.\n       */\n      public static UpdateISOPermissionsOptions accounts(Iterable<String> accounts) {\n         return new UpdateISOPermissionsOptions().accounts(accounts);\n      }\n\n      /**\n       * @param isExtractable true if the template/iso is extractable, false other wise. Can be set only by root admin\n       */\n      public static UpdateISOPermissionsOptions isExtractable(boolean isExtractable) {\n         return new UpdateISOPermissionsOptions().isExtractable(isExtractable);\n      }\n\n      /**\n       * @param isFeatured true for featured template/iso, false otherwise\n       */\n      public static UpdateISOPermissionsOptions isFeatured(boolean isFeatured) {\n         return new UpdateISOPermissionsOptions().isFeatured(isFeatured);\n      }\n\n      /**\n       * @param isPublic true for public template/iso, false for private templates/isos\n       */\n      public static UpdateISOPermissionsOptions isPublic(boolean isPublic) {\n         return new UpdateISOPermissionsOptions().isPublic(isPublic);\n      }\n\n      /**\n       * @param operation permission operator (add, remove, reset)\n       */\n      public static UpdateISOPermissionsOptions operation(PermissionOperation operation) {\n         return new UpdateISOPermissionsOptions().operation(operation);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/UpdateLoadBalancerRuleOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.cloudstack.domain.LoadBalancerRule;\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options used to control how a load balancer rule is updated\n *\n * @see <a href=\n *      \"http://download.cloud.com/releases/2.2.0/api_2.2.12/user/updateLoadBalancerRule.html\"\n *      />\n */\npublic class UpdateLoadBalancerRuleOptions extends BaseHttpRequestOptions {\n\n   public static final UpdateLoadBalancerRuleOptions NONE = new UpdateLoadBalancerRuleOptions();\n\n   /**\n    * @param algorithm load balancer algorithm (source, roundrobin, leastconn)\n    */\n   public UpdateLoadBalancerRuleOptions algorithm(LoadBalancerRule.Algorithm algorithm) {\n      this.queryParameters.replaceValues(\"algorithm\", ImmutableSet.of(algorithm.toString()));\n      return this;\n   }\n\n   /**\n    * @param description the description of the load balancer rule\n    */\n   public UpdateLoadBalancerRuleOptions description(String description) {\n      this.queryParameters.replaceValues(\"description\", ImmutableSet.of(description));\n      return this;\n   }\n\n   /**\n    * @param name the name of the load balancer rule\n    */\n   public UpdateLoadBalancerRuleOptions name(String name) {\n      this.queryParameters.replaceValues(\"name\", ImmutableSet.of(name));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see UpdateLoadBalancerRuleOptions#algorithm\n       */\n      public static UpdateLoadBalancerRuleOptions algorithm(LoadBalancerRule.Algorithm algorithm) {\n         UpdateLoadBalancerRuleOptions options = new UpdateLoadBalancerRuleOptions();\n         return options.algorithm(algorithm);\n      }\n\n      /**\n       * @see UpdateLoadBalancerRuleOptions#description\n       */\n      public static UpdateLoadBalancerRuleOptions description(String description) {\n         UpdateLoadBalancerRuleOptions options = new UpdateLoadBalancerRuleOptions();\n         return options.description(description);\n      }\n\n      /**\n       * @see UpdateLoadBalancerRuleOptions#name\n       */\n      public static UpdateLoadBalancerRuleOptions name(String name) {\n         UpdateLoadBalancerRuleOptions options = new UpdateLoadBalancerRuleOptions();\n         return options.name(name);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/UpdateNetworkOfferingOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.cloudstack.domain.NetworkOfferingAvailabilityType;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options to control how network offerings are created\n * \n * @see <a\n *      href=\"http://download.cloud.com/releases/2.2.0/api_2.2.12/global_admin/updateNetworkOffering.html\"\n *      />\n */\npublic class UpdateNetworkOfferingOptions extends AccountInDomainOptions {\n\n   public static final UpdateNetworkOfferingOptions NONE = new UpdateNetworkOfferingOptions();\n\n   /**\n    * @param name\n    *       service offering name\n    */\n   public UpdateNetworkOfferingOptions name(String name) {\n      this.queryParameters.replaceValues(\"name\", ImmutableSet.<String>of(name));\n      return this;\n   }\n\n   /**\n    * @param displayText\n    *       service offering display text\n    */\n   public UpdateNetworkOfferingOptions displayText(String displayText) {\n      this.queryParameters.replaceValues(\"displaytext\", ImmutableSet.<String>of(displayText));\n      return this;\n   }\n\n   /**\n    * @param availability\n    *       the availability of network offering. Default value is Required for Guest\n    *       Virtual network offering; Optional for Guest Direct network offering\n    */\n   public UpdateNetworkOfferingOptions availability(NetworkOfferingAvailabilityType availability) {\n      this.queryParameters.replaceValues(\"availability\", ImmutableSet.<String>of(availability.toString()));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see UpdateNetworkOfferingOptions#name\n       */\n      public static UpdateNetworkOfferingOptions name(String name) {\n         UpdateNetworkOfferingOptions options = new UpdateNetworkOfferingOptions();\n         return options.name(name);\n      }\n\n      /**\n       * @see UpdateNetworkOfferingOptions#displayText\n       */\n      public static UpdateNetworkOfferingOptions displayText(String displayText) {\n         UpdateNetworkOfferingOptions options = new UpdateNetworkOfferingOptions();\n         return options.displayText(displayText);\n      }\n\n      /**\n       * @see UpdateNetworkOfferingOptions#availability\n       */\n      public static UpdateNetworkOfferingOptions availability(NetworkOfferingAvailabilityType availability) {\n         UpdateNetworkOfferingOptions options = new UpdateNetworkOfferingOptions();\n         return options.availability(availability);\n      }\n\n      /**\n       * @see UpdateNetworkOfferingOptions#accountInDomain\n       */\n      public static UpdateNetworkOfferingOptions accountInDomain(String account, String domain) {\n         UpdateNetworkOfferingOptions options = new UpdateNetworkOfferingOptions();\n         return options.accountInDomain(account, domain);\n      }\n\n      /**\n       * @see UpdateNetworkOfferingOptions#domainId\n       */\n      public static UpdateNetworkOfferingOptions domainId(String domainId) {\n         UpdateNetworkOfferingOptions options = new UpdateNetworkOfferingOptions();\n         return options.domainId(domainId);\n      }\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public UpdateNetworkOfferingOptions accountInDomain(String account, String domain) {\n      return UpdateNetworkOfferingOptions.class.cast(super.accountInDomain(account, domain));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public UpdateNetworkOfferingOptions domainId(String domainId) {\n      return UpdateNetworkOfferingOptions.class.cast(super.domainId(domainId));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/UpdatePodOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.cloudstack.domain.AllocationState;\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options to the GlobalPodApi.updatePod API call.\n */\npublic class UpdatePodOptions extends BaseHttpRequestOptions {\n\n   public static final UpdatePodOptions NONE = new UpdatePodOptions();\n   \n   public static class Builder {\n\n      public static UpdatePodOptions name(String name) {\n         return new UpdatePodOptions().name(name);\n      }\n\n      public static UpdatePodOptions startIp(String startIp) {\n         return new UpdatePodOptions().startIp(startIp);\n      }\n\n      public static UpdatePodOptions endIp(String endIp) {\n         return new UpdatePodOptions().endIp(endIp);\n      }\n\n      public static UpdatePodOptions gateway(String gateway) {\n         return new UpdatePodOptions().gateway(gateway);\n      }\n\n      public static UpdatePodOptions netmask(String netmask) {\n         return new UpdatePodOptions().netmask(netmask);\n      }\n\n      public static UpdatePodOptions allocationState(AllocationState allocationState) {\n         return new UpdatePodOptions().allocationState(allocationState);\n      }\n\n   }\n\n   public UpdatePodOptions name(String name) {\n      this.queryParameters.replaceValues(\"name\", ImmutableSet.<String>of(name));\n      return this;\n   }\n\n   public UpdatePodOptions startIp(String startIp) {\n      this.queryParameters.replaceValues(\"startip\", ImmutableSet.<String>of(startIp));\n      return this;\n   }\n\n   public UpdatePodOptions endIp(String endIp) {\n      this.queryParameters.replaceValues(\"endip\", ImmutableSet.<String>of(endIp));\n      return this;\n   }\n\n   public UpdatePodOptions gateway(String gateway) {\n      this.queryParameters.replaceValues(\"gateway\", ImmutableSet.<String>of(gateway));\n      return this;\n   }\n\n   public UpdatePodOptions netmask(String netmask) {\n      this.queryParameters.replaceValues(\"netmask\", ImmutableSet.<String>of(netmask));\n      return this;\n   }\n\n   public UpdatePodOptions allocationState(AllocationState allocationState) {\n      this.queryParameters.replaceValues(\"allocationstate\", ImmutableSet.of(allocationState.toString()));\n      return this;\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/UpdateServiceOfferingOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options to control how service offerings are created\n * \n * @see <a\n *      href=\"http://download.cloud.com/releases/2.2.0/api_2.2.12/global_admin/createServiceOffering.html\"\n *      />\n */\npublic class UpdateServiceOfferingOptions extends AccountInDomainOptions {\n\n   public static final UpdateServiceOfferingOptions NONE = new UpdateServiceOfferingOptions();\n\n   /**\n    * @param name\n    *       service offering name\n    */\n   public UpdateServiceOfferingOptions name(String name) {\n      this.queryParameters.replaceValues(\"name\", ImmutableSet.<String>of(name));\n      return this;\n   }\n\n   /**\n    * @param displayText\n    *       service offering display text\n    */\n   public UpdateServiceOfferingOptions displayText(String displayText) {\n      this.queryParameters.replaceValues(\"displaytext\", ImmutableSet.<String>of(displayText));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see UpdateServiceOfferingOptions#name\n       */\n      public static UpdateServiceOfferingOptions name(String name) {\n         UpdateServiceOfferingOptions options = new UpdateServiceOfferingOptions();\n         return options.name(name);\n      }\n\n      /**\n       * @see UpdateServiceOfferingOptions#displayText\n       */\n      public static UpdateServiceOfferingOptions displayText(String displayText) {\n         UpdateServiceOfferingOptions options = new UpdateServiceOfferingOptions();\n         return options.displayText(displayText);\n      }\n\n      /**\n       * @see UpdateServiceOfferingOptions#accountInDomain\n       */\n      public static UpdateServiceOfferingOptions accountInDomain(String account, String domain) {\n         UpdateServiceOfferingOptions options = new UpdateServiceOfferingOptions();\n         return options.accountInDomain(account, domain);\n      }\n\n      /**\n       * @see UpdateServiceOfferingOptions#domainId\n       */\n      public static UpdateServiceOfferingOptions domainId(String domainId) {\n         UpdateServiceOfferingOptions options = new UpdateServiceOfferingOptions();\n         return options.domainId(domainId);\n      }\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public UpdateServiceOfferingOptions accountInDomain(String account, String domain) {\n      return UpdateServiceOfferingOptions.class.cast(super.accountInDomain(account, domain));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public UpdateServiceOfferingOptions domainId(String domainId) {\n      return UpdateServiceOfferingOptions.class.cast(super.domainId(domainId));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/UpdateTemplateOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.cloudstack.domain.Template;\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options used to control how a template should be updated.\n *\n * @see <a\n *      href=\"http://download.cloud.com/releases/2.2.8/api/user/updateTemplate.html\"\n *      />\n */\npublic class UpdateTemplateOptions extends BaseHttpRequestOptions {\n\n   /**\n    * true if image is bootable, false otherwise\n    */\n   public UpdateTemplateOptions bootable(boolean bootable) {\n      this.queryParameters.replaceValues(\"bootable\", ImmutableSet.of(bootable + \"\"));\n      return this;\n   }\n\n   /**\n    * the display text of the image\n    */\n   public UpdateTemplateOptions displayText(String displayText) {\n      this.queryParameters.replaceValues(\"displaytext\", ImmutableSet.of(displayText));\n      return this;\n   }\n\n   /**\n    * the format for the image\n    */\n   public UpdateTemplateOptions format(Template.Format format) {\n      this.queryParameters.replaceValues(\"format\", ImmutableSet.of(format + \"\"));\n      return this;\n   }\n\n   /**\n    * the name of the image file\n    */\n   public UpdateTemplateOptions name(String name) {\n      this.queryParameters.replaceValues(\"name\", ImmutableSet.of(name));\n      return this;\n   }\n\n   /**\n    * the ID of the OS type that best represents the OS of this image.\n    */\n   public UpdateTemplateOptions osTypeId(String osTypeId) {\n      this.queryParameters.replaceValues(\"ostypeid\", ImmutableSet.of(osTypeId + \"\"));\n      return this;\n   }\n\n   /**\n    * true if the image supports the password reset feature; default is false\n    */\n   public UpdateTemplateOptions passwordEnabled(boolean passwordEnabled) {\n      this.queryParameters.replaceValues(\"passwordenabled\", ImmutableSet.of(passwordEnabled + \"\"));\n      return this;\n   }\n\n   public static class Builder {\n\n      public static UpdateTemplateOptions bootable(boolean bootable) {\n         UpdateTemplateOptions options = new UpdateTemplateOptions();\n         return options.bootable(bootable);\n      }\n\n      public static UpdateTemplateOptions displayText(String displayText) {\n         UpdateTemplateOptions options = new UpdateTemplateOptions();\n         return options.displayText(displayText);\n      }\n\n      public static UpdateTemplateOptions format(Template.Format format) {\n         UpdateTemplateOptions options = new UpdateTemplateOptions();\n         return options.format(format);\n      }\n\n      public static UpdateTemplateOptions name(String name) {\n         UpdateTemplateOptions options = new UpdateTemplateOptions();\n         return options.name(name);\n      }\n\n      public static UpdateTemplateOptions osTypeId(String osTypeId) {\n         UpdateTemplateOptions options = new UpdateTemplateOptions();\n         return options.osTypeId(osTypeId);\n      }\n\n      public static UpdateTemplateOptions passwordEnabled(boolean passwordEnabled) {\n         UpdateTemplateOptions options = new UpdateTemplateOptions();\n         return options.passwordEnabled(passwordEnabled);\n      }\n   }\n   \n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/UpdateTemplatePermissionsOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.base.Joiner;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options used to control how a template should be updated.\n *\n * @see <a\n *      href=\"http://download.cloud.com/releases/2.2.8/api/user/updateTemplate.html\"\n *      />\n */\npublic class UpdateTemplatePermissionsOptions extends BaseHttpRequestOptions {\n\n   /**\n    * a list of accounts. If specified, \"op\" parameter has to be passed in.\n    */\n   public UpdateTemplatePermissionsOptions accounts(Iterable<String> accounts) {\n      this.queryParameters.replaceValues(\"accounts\", ImmutableSet.of(Joiner.on(',').join(accounts)));\n      return this;\n   }\n\n   /**\n    * a list of projects. If specified, \"op\" parameter has to be passed in.\n    */\n   public UpdateTemplatePermissionsOptions projectIds(Iterable<String> projectIds) {\n      this.queryParameters.replaceValues(\"projectids\", ImmutableSet.of(Joiner.on(',').join(projectIds)));\n      return this;\n   }\n\n   /**\n    * true if the template/iso is extractable, false other wise. Can be set only by root admin\n    */\n   public UpdateTemplatePermissionsOptions isExtractable(boolean isExtractable) {\n      this.queryParameters.replaceValues(\"isextractable\", ImmutableSet.of(isExtractable + \"\"));\n      return this;\n   }\n\n   /**\n    * true for featured template/iso, false otherwise\n    */\n   public UpdateTemplatePermissionsOptions isFeatured(boolean isFeatured) {\n      this.queryParameters.replaceValues(\"isfeatured\", ImmutableSet.of(isFeatured + \"\"));\n      return this;\n   }\n\n   /**\n    * true for public template/iso, false for private templates/isos\n    */\n   public UpdateTemplatePermissionsOptions isPublic(boolean isPublic) {\n      this.queryParameters.replaceValues(\"ispublic\", ImmutableSet.of(isPublic + \"\"));\n      return this;\n   }\n\n   /**\n    * permission operator (add, remove, reset)\n    */\n   public UpdateTemplatePermissionsOptions op(Operation op) {\n      this.queryParameters.replaceValues(\"op\", ImmutableSet.of(op + \"\"));\n      return this;\n   }\n\n   public enum Operation {\n      add, remove, reset\n   }\n\n   public static class Builder {\n\n      public static UpdateTemplatePermissionsOptions accounts(Iterable<String> accounts) {\n         UpdateTemplatePermissionsOptions options = new UpdateTemplatePermissionsOptions();\n         return options.accounts(accounts);\n      }\n\n      public static UpdateTemplatePermissionsOptions projectIds(Iterable<String> projectIds) {\n         UpdateTemplatePermissionsOptions options = new UpdateTemplatePermissionsOptions();\n         return options.projectIds(projectIds);\n      }\n\n      public static UpdateTemplatePermissionsOptions isExtractable(boolean isExtractable) {\n         UpdateTemplatePermissionsOptions options = new UpdateTemplatePermissionsOptions();\n         return options.isExtractable(isExtractable);\n      }\n\n      public static UpdateTemplatePermissionsOptions isFeatured(boolean isFeatured) {\n         UpdateTemplatePermissionsOptions options = new UpdateTemplatePermissionsOptions();\n         return options.isFeatured(isFeatured);\n      }\n\n      public static UpdateTemplatePermissionsOptions isPublic(boolean isPublic) {\n         UpdateTemplatePermissionsOptions options = new UpdateTemplatePermissionsOptions();\n         return options.isPublic(isPublic);\n      }\n\n      public static UpdateTemplatePermissionsOptions op(Operation op) {\n         UpdateTemplatePermissionsOptions options = new UpdateTemplatePermissionsOptions();\n         return options.op(op);\n      }\n   }\n   \n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/UpdateUserOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Optional arguments for updating an User\n *\n * @see <a\n *      href=\"http://download.cloud.com/releases/2.2.0/api_2.2.12/global_admin/updateUser.html\"\n *      />\n */\npublic class UpdateUserOptions extends BaseHttpRequestOptions {\n\n   public static final UpdateUserOptions NONE = new UpdateUserOptions();\n\n   /**\n    * @param email user email address\n    */\n   public UpdateUserOptions email(String email) {\n      this.queryParameters.replaceValues(\"email\", ImmutableSet.of(email));\n      return this;\n   }\n\n   /**\n    * @param firstName user account first name\n    */\n   public UpdateUserOptions firstName(String firstName) {\n      this.queryParameters.replaceValues(\"firstname\", ImmutableSet.of(firstName));\n      return this;\n   }\n\n   /**\n    * @param lastName user account last name\n    */\n   public UpdateUserOptions lastName(String lastName) {\n      this.queryParameters.replaceValues(\"lastname\", ImmutableSet.of(lastName));\n      return this;\n   }\n\n   /**\n    * @param hashedPassword hashed password (default is MD5). If you wish to use any other\n    *                       hashing algorithm, you would need to write a custom authentication adapter\n    */\n   public UpdateUserOptions hashedPassword(String hashedPassword) {\n      this.queryParameters.replaceValues(\"password\", ImmutableSet.of(hashedPassword));\n      return this;\n   }\n\n   /**\n    * @param timezone specifies a timezone for this command. For more information on\n    *                 the timezone parameter, see Time Zone Format.\n    */\n   public UpdateUserOptions timezone(String timezone) {\n      this.queryParameters.replaceValues(\"timezone\", ImmutableSet.of(timezone));\n      return this;\n   }\n\n   /**\n    * @param userApiKey\n    */\n   public UpdateUserOptions userApiKey(String userApiKey) {\n      this.queryParameters.replaceValues(\"userapikey\", ImmutableSet.of(userApiKey));\n      return this;\n   }\n\n   /**\n    * @param userSecretKey\n    */\n   public UpdateUserOptions userSecretKey(String userSecretKey) {\n      this.queryParameters.replaceValues(\"usersecretkey\", ImmutableSet.of(userSecretKey));\n      return this;\n   }\n\n   /**\n    * @param userName unique user name\n    */\n   public UpdateUserOptions userName(String userName) {\n      this.queryParameters.replaceValues(\"username\", ImmutableSet.of(userName));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see UpdateUserOptions#email\n       */\n      public static UpdateUserOptions email(String email) {\n         UpdateUserOptions options = new UpdateUserOptions();\n         return options.email(email);\n      }\n\n      /**\n       * @see UpdateUserOptions#firstName\n       */\n      public static UpdateUserOptions firstName(String firstName) {\n         UpdateUserOptions options = new UpdateUserOptions();\n         return options.firstName(firstName);\n      }\n\n      /**\n       * @see UpdateUserOptions#lastName\n       */\n      public static UpdateUserOptions lastName(String lastName) {\n         UpdateUserOptions options = new UpdateUserOptions();\n         return options.lastName(lastName);\n      }\n\n      /**\n       * @see UpdateUserOptions#hashedPassword\n       */\n      public static UpdateUserOptions hashedPassword(String hashedPassword) {\n         UpdateUserOptions options = new UpdateUserOptions();\n         return options.hashedPassword(hashedPassword);\n      }\n\n      /**\n       * @see UpdateUserOptions#timezone\n       */\n      public static UpdateUserOptions timezone(String timezone) {\n         UpdateUserOptions options = new UpdateUserOptions();\n         return options.timezone(timezone);\n      }\n\n      /**\n       * @see UpdateUserOptions#userApiKey\n       */\n      public static UpdateUserOptions userApiKey(String userApiKey) {\n         UpdateUserOptions options = new UpdateUserOptions();\n         return options.userApiKey(userApiKey);\n      }\n\n      /**\n       * @see UpdateUserOptions#userSecretKey\n       */\n      public static UpdateUserOptions userSecretKey(String userSecretKey) {\n         UpdateUserOptions options = new UpdateUserOptions();\n         return options.userSecretKey(userSecretKey);\n      }\n\n      /**\n       * @see UpdateUserOptions#userName\n       */\n      public static UpdateUserOptions userName(String userName) {\n         UpdateUserOptions options = new UpdateUserOptions();\n         return options.userName(userName);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/UpdateVMGroupOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options used to control updates to VMGroups\n *\n * @see <a\n *      href=\"http://download.cloud.com/releases/2.2.0/api/user/updateInstanceGroup.html\"\n *      />\n */\npublic class UpdateVMGroupOptions extends BaseHttpRequestOptions {\n\n   public static final UpdateVMGroupOptions NONE = new UpdateVMGroupOptions();\n\n   /**\n    * @param name new name of the VMGroup\n    */\n   public UpdateVMGroupOptions name(String name) {\n      this.queryParameters.replaceValues(\"name\", ImmutableSet.of(name));\n      return this;\n   }\n\n   public static class Builder {\n      /**\n       * @see org.jclouds.cloudstack.options.UpdateVMGroupOptions#name\n       */\n      public static UpdateVMGroupOptions name(String name) {\n         UpdateVMGroupOptions options = new UpdateVMGroupOptions();\n         return options.name(name);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/UpdateVirtualMachineOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport com.google.common.collect.ImmutableSet;\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.io.BaseEncoding.base64;\n\n/**\n * Options for updating virtual machines.\n *\n * @see <a\n *      href=\"http://download.cloud.com/releases/3.0.3/api_3.0.3/root_admin/updateVirtualMachine.html\"\n *      />\n */\npublic class UpdateVirtualMachineOptions extends BaseHttpRequestOptions {\n\n    public static final UpdateVirtualMachineOptions NONE = new UpdateVirtualMachineOptions();\n\n    /**\n     * sets the displayName - just for display purposes. We don't pass this\n     * parameter to the backend.\n     *\n     * @param displayName an optional user generated name for the virtual machine\n     */\n    public UpdateVirtualMachineOptions displayName(String displayName) {\n        this.queryParameters.replaceValues(\"displayname\", ImmutableSet.of(displayName));\n        return this;\n    }\n\n    /**\n     * @param group an optional group for the virtual machine\n     */\n    public UpdateVirtualMachineOptions group(String group) {\n        this.queryParameters.replaceValues(\"group\", ImmutableSet.of(group));\n        return this;\n    }\n\n    /**\n     * @param haEnable true if high-availability is enabled for the virtual machine, false otherwise\n     */\n    public UpdateVirtualMachineOptions haEnable(boolean haEnable) {\n        this.queryParameters.replaceValues(\"haenable\", ImmutableSet.of(String.valueOf(haEnable)));\n        return this;\n    }\n\n    /**\n     * @param osTypeId the ID of the OS type that best represents this VM.\n     */\n    public UpdateVirtualMachineOptions osTypeId(String osTypeId) {\n        this.queryParameters.replaceValues(\"ostypeid\", ImmutableSet.of(String.valueOf(osTypeId)));\n        return this;\n    }\n\n    /**\n     * @param unencodedData an optional binary data that can be sent to the virtual machine\n     *                      upon a successful deployment. This binary data must be base64\n     *                      encoded before adding it to the request. Currently only HTTP GET\n     *                      is supported. Using HTTP GET (via querystring), you can send up\n     *                      to 2KB of data after base64 encoding.\n     */\n    public UpdateVirtualMachineOptions userData(byte[] unencodedData) {\n        int length = checkNotNull(unencodedData, \"unencodedData\").length;\n        checkArgument(length > 0, \"userData cannot be empty\");\n        checkArgument(length <= 2 * 1024, \"userData cannot be larger than 2kb\");\n        this.queryParameters.replaceValues(\"userdata\", ImmutableSet.of(base64().encode(unencodedData)));\n        return this;\n    }\n\n\n    public static class Builder {\n\n        /**\n         * @see UpdateVirtualMachineOptions#displayName\n         */\n        public static UpdateVirtualMachineOptions displayName(String displayName) {\n            UpdateVirtualMachineOptions options = new UpdateVirtualMachineOptions();\n            return options.displayName(displayName);\n        }\n\n        /**\n         * @see UpdateVirtualMachineOptions#group\n         */\n        public static UpdateVirtualMachineOptions group(String group) {\n            UpdateVirtualMachineOptions options = new UpdateVirtualMachineOptions();\n            return options.group(group);\n        }\n\n        /**\n         * @see UpdateVirtualMachineOptions#haEnable\n         */\n        public static UpdateVirtualMachineOptions haEnable(boolean haEnable) {\n            UpdateVirtualMachineOptions options = new UpdateVirtualMachineOptions();\n            return options.haEnable(haEnable);\n        }\n\n        /**\n         * @see UpdateVirtualMachineOptions#osTypeId\n         */\n        public static UpdateVirtualMachineOptions osTypeId(String osTypeId) {\n            UpdateVirtualMachineOptions options = new UpdateVirtualMachineOptions();\n            return options.osTypeId(osTypeId);\n        }\n\n        /**\n         * @see UpdateVirtualMachineOptions#userData\n         */\n        public static UpdateVirtualMachineOptions userData(byte[] unencodedData) {\n            UpdateVirtualMachineOptions options = new UpdateVirtualMachineOptions();\n            return options.userData(unencodedData);\n        }\n    }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/UpdateZoneOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static com.google.common.base.Preconditions.checkArgument;\n\nimport java.util.List;\n\nimport org.jclouds.cloudstack.domain.AllocationState;\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options used to control how a zone is updated\n * \n * @see <a href=\n *      \"http://download.cloud.com/releases/2.2.0/api_2.2.12/global_admin/updateZone.html\"\n *      />\n */\npublic class UpdateZoneOptions extends BaseHttpRequestOptions {\n\n   public static final UpdateZoneOptions NONE = new UpdateZoneOptions();\n\n   /**\n    * @param allocationState\n    *    allocation state of this Zone for allocation of new resources\n    */\n   public UpdateZoneOptions allocationState(AllocationState allocationState) {\n      this.queryParameters.replaceValues(\"allocationstate\", ImmutableSet.of(allocationState.toString()));\n      return this;\n   }\n\n   /**\n    * @param details\n    *    the details for the Zone\n    */\n   public UpdateZoneOptions details(String details) {\n      this.queryParameters.replaceValues(\"details\", ImmutableSet.of(details));\n      return this;\n   }\n\n   /**\n    * @param dhcpProvider\n    *    the dhcp Provider for the Zone\n    */\n   public UpdateZoneOptions dhcpProvider(String dhcpProvider) {\n      this.queryParameters.replaceValues(\"dhcpprovider\", ImmutableSet.of(dhcpProvider));\n      return this;\n   }\n\n   /**\n    * @param externalDnsServers\n    *    the list of external DNS servers\n    */\n   public UpdateZoneOptions externalDns(List<String> externalDnsServers) {\n      checkArgument(externalDnsServers.size() == 1 || externalDnsServers.size() == 2,\n         \"The list of DNS servers should have 1 or 2 elements\");\n      this.queryParameters.replaceValues(\"dns1\",\n         ImmutableSet.of(externalDnsServers.get(0)));\n      if (externalDnsServers.size() == 2) {\n         this.queryParameters.replaceValues(\"dns2\",\n            ImmutableSet.of(externalDnsServers.get(1)));\n      }\n      return this;\n   }\n\n   /**\n    * @param internalDnsServers\n    *    the list of internal DNS for the Zone\n    */\n   public UpdateZoneOptions internalDns(List<String> internalDnsServers) {\n      checkArgument(internalDnsServers.size() == 1 || internalDnsServers.size() == 2,\n         \"The list of internal DNS servers should have 1 or 2 elements\");\n      this.queryParameters.replaceValues(\"internaldns1\",\n         ImmutableSet.of(internalDnsServers.get(0)));\n      if (internalDnsServers.size() == 2) {\n         this.queryParameters.replaceValues(\"internaldns2\",\n            ImmutableSet.of(internalDnsServers.get(1)));\n      }\n      return this;\n   }\n\n   /**\n    * @param dnsSearchOrder\n    *    the dns search order list\n    */\n   public UpdateZoneOptions dnsSearchOrder(String dnsSearchOrder) {\n      this.queryParameters.replaceValues(\"dnssearchorder\", ImmutableSet.of(dnsSearchOrder));\n      return this;\n   }\n\n   /**\n    * @param domainName\n    *    network domain name for the networks in zone\n    */\n   public UpdateZoneOptions domainName(String domainName) {\n      this.queryParameters.replaceValues(\"domain\", ImmutableSet.of(domainName));\n      return this;\n   }\n\n   /**\n    * @param guestCIDRAddress\n    *    the guest CIDR address for the Zone\n    */\n   public UpdateZoneOptions guestCIDRAddress(String guestCIDRAddress) {\n      this.queryParameters.replaceValues(\"guestcidraddress\", ImmutableSet.of(guestCIDRAddress));\n      return this;\n   }\n\n   /**\n    * @param securityGroupEnabled\n    *    true if network is security group enabled, false otherwise\n    */\n   public UpdateZoneOptions securityGroupEnabled(boolean securityGroupEnabled) {\n      this.queryParameters.replaceValues(\"securitygroupenabled\", ImmutableSet.of(securityGroupEnabled + \"\"));\n      return this;\n   }\n\n   /**\n    * You can only make a private Zone public, not the other way around\n    */\n   public UpdateZoneOptions makePublic() {\n      this.queryParameters.replaceValues(\"ispublic\", ImmutableSet.of(\"true\"));\n      return this;\n   }\n\n   /**\n    * @param name\n    *    the name of the Zone\n    */\n   public UpdateZoneOptions name(String name) {\n      this.queryParameters.replaceValues(\"name\", ImmutableSet.of(name));\n      return this;\n   }\n\n   /**\n    * @param vlan\n    *    the VLAN for the Zone\n    */\n   public UpdateZoneOptions vlan(String vlan) {\n      this.queryParameters.replaceValues(\"vlan\", ImmutableSet.of(vlan));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see UpdateZoneOptions#allocationState\n       */\n      public static UpdateZoneOptions allocationState(AllocationState allocationState) {\n         UpdateZoneOptions options = new UpdateZoneOptions();\n         return options.allocationState(allocationState);\n      }\n\n      /**\n       * @see UpdateZoneOptions#details\n       */\n      public static UpdateZoneOptions details(String details) {\n         UpdateZoneOptions options = new UpdateZoneOptions();\n         return options.details(details);\n      }\n\n      /**\n       * @see UpdateZoneOptions#dhcpProvider\n       */\n      public static UpdateZoneOptions dhcpProvider(String dhcpProvider) {\n         UpdateZoneOptions options = new UpdateZoneOptions();\n         return options.dhcpProvider(dhcpProvider);\n      }\n\n      /**\n       * @see UpdateZoneOptions#externalDns\n       */\n      public static UpdateZoneOptions externalDns(List<String> externalDnsServers) {\n         UpdateZoneOptions options = new UpdateZoneOptions();\n         return options.externalDns(externalDnsServers);\n      }\n\n      /**\n       * @see UpdateZoneOptions#internalDns\n       */\n      public static UpdateZoneOptions internalDns(List<String> internalDnsServers) {\n         UpdateZoneOptions options = new UpdateZoneOptions();\n         return options.internalDns(internalDnsServers);\n      }\n\n      /**\n       * @see UpdateZoneOptions#dnsSearchOrder\n       */\n      public static UpdateZoneOptions dnsSearchOrder(String dnsSearchOrder) {\n         UpdateZoneOptions options = new UpdateZoneOptions();\n         return options.dnsSearchOrder(dnsSearchOrder);\n      }\n\n      /**\n       * @see UpdateZoneOptions#domainName\n       */\n      public static UpdateZoneOptions domainName(String domainName) {\n         UpdateZoneOptions options = new UpdateZoneOptions();\n         return options.domainName(domainName);\n      }\n\n      /**\n       * @see UpdateZoneOptions#guestCIDRAddress\n       */\n      public static UpdateZoneOptions guestCIDRAddress(String guestCIDRAddress) {\n         UpdateZoneOptions options = new UpdateZoneOptions();\n         return options.guestCIDRAddress(guestCIDRAddress);\n      }\n\n      /**\n       * @see UpdateZoneOptions#securityGroupEnabled\n       */\n      public static UpdateZoneOptions securityGroupEnabled(boolean securityGroupEnabled) {\n         UpdateZoneOptions options = new UpdateZoneOptions();\n         return options.securityGroupEnabled(securityGroupEnabled);\n      }\n\n      /**\n       * @see UpdateZoneOptions#makePublic\n       */\n      public static UpdateZoneOptions makePublic() {\n         UpdateZoneOptions options = new UpdateZoneOptions();\n         return options.makePublic();\n      }\n\n      /**\n       * @see UpdateZoneOptions#name\n       */\n      public static UpdateZoneOptions name(String name) {\n         UpdateZoneOptions options = new UpdateZoneOptions();\n         return options.name(name);\n      }\n\n      /**\n       * @see UpdateZoneOptions#vlan\n       */\n      public static UpdateZoneOptions vlan(String vlan) {\n         UpdateZoneOptions options = new UpdateZoneOptions();\n         return options.vlan(vlan);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/predicates/CorrectHypervisorForZone.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.cloudstack.CloudStackApi;\nimport org.jclouds.cloudstack.domain.Template;\nimport org.jclouds.cloudstack.domain.Zone;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Predicates;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMap.Builder;\n\n/**\n * Templates can be present in a zone, and available, but not valid for launch\n * as their hypervisor isn't installed.\n */\n@Singleton\npublic class CorrectHypervisorForZone implements Function<String, Predicate<Template>> {\n   private final Supplier<Map<String, Set<String>>> hypervisorsSupplier;\n\n   @Inject\n   public CorrectHypervisorForZone(CloudStackApi client) {\n      this(Suppliers.ofInstance(new CloudStackApiToZoneToHypervisors().apply(checkNotNull(client, \"client\"))));\n   }\n\n   public CorrectHypervisorForZone(Supplier<Map<String, Set<String>>> hypervisorsSupplier) {\n      this.hypervisorsSupplier = checkNotNull(hypervisorsSupplier, \"hypervisorsSupplier\");\n   }\n\n   private static class CloudStackApiToZoneToHypervisors implements\n         Function<CloudStackApi, Map<String, Set<String>>> {\n\n      @Override\n      public Map<String, Set<String>> apply(CloudStackApi client) {\n         checkNotNull(client, \"client\");\n         Builder<String, Set<String>> builder = ImmutableMap.builder();\n         for (Zone zone : client.getZoneApi().listZones()) {\n            builder.put(zone.getId(), client.getHypervisorApi().listHypervisorsInZone(zone.getId()));\n         }\n         return builder.build();\n      }\n   }\n\n   @Override\n   public Predicate<Template> apply(final String zoneId) {\n\n      final Set<String> acceptableHypervisorsInZone;\n      try {\n         acceptableHypervisorsInZone = this.hypervisorsSupplier.get().get(zoneId);\n      } catch (NullPointerException e) {\n         throw new IllegalArgumentException(\"unknown zone: \" + zoneId);\n      }\n      if (acceptableHypervisorsInZone.isEmpty())\n         return Predicates.alwaysFalse();\n      return new Predicate<Template>() {\n\n         @Override\n         public boolean apply(Template input) {\n            return Predicates.in(acceptableHypervisorsInZone).apply(input.getHypervisor());\n         }\n\n         @Override\n         public String toString() {\n            return \"hypervisorsInZone(\" + zoneId + \", \" + acceptableHypervisorsInZone + \")\";\n         }\n      };\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/predicates/JobComplete.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.cloudstack.AsyncJobException;\nimport org.jclouds.cloudstack.CloudStackApi;\nimport org.jclouds.cloudstack.domain.AsyncJob;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Predicate;\nimport com.google.inject.Inject;\n\n/**\n * \n * Tests to see if a job is in progress.\n */\n@Singleton\npublic class JobComplete implements Predicate<String> {\n\n   private final CloudStackApi client;\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   @Inject\n   public JobComplete(CloudStackApi client) {\n      this.client = client;\n   }\n\n   public boolean apply(String jobId) {\n      logger.trace(\">> looking for status on job %s\", checkNotNull(jobId, \"jobId\"));\n      AsyncJob<?> job = refresh(jobId);\n      if (job == null) {\n         return false;\n      }\n      logger.trace(\"%s: looking for job status %s: currently: %s\", job.getId(), 1, job.getStatus());\n      if (job.hasFailed()) {\n\n         throw new AsyncJobException(String.format(\"job %s failed with exception %s\",\n            job.toString(), job.getError().toString()));\n      }\n      return job.hasSucceed();\n   }\n\n   private AsyncJob<?> refresh(String jobId) {\n      return client.getAsyncJobApi().getAsyncJob(jobId);\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/predicates/LoadBalancerRuleActive.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.cloudstack.CloudStackApi;\nimport org.jclouds.cloudstack.domain.LoadBalancerRule;\nimport org.jclouds.cloudstack.domain.LoadBalancerRule.State;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Predicate;\n\n/**\n * \n * Tests to see if a LoadBalancerRule is active\n */\n@Singleton\npublic class LoadBalancerRuleActive implements Predicate<LoadBalancerRule> {\n\n   private final CloudStackApi client;\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   @Inject\n   public LoadBalancerRuleActive(CloudStackApi client) {\n      this.client = client;\n   }\n\n   public boolean apply(LoadBalancerRule rule) {\n      logger.trace(\"looking for state on rule %s\", checkNotNull(rule, \"rule\"));\n      rule = refresh(rule);\n      if (rule == null)\n         return false;\n      logger.trace(\"%s: looking for rule state %s: currently: %s\", rule.getId(), State.ACTIVE, rule.getState());\n      return rule.getState() == State.ACTIVE;\n   }\n\n   private LoadBalancerRule refresh(LoadBalancerRule rule) {\n      return client.getLoadBalancerApi().getLoadBalancerRule(rule.getId());\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/predicates/NetworkOfferingPredicates.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.predicates;\n\nimport static com.google.common.base.Predicates.alwaysTrue;\n\nimport org.jclouds.cloudstack.domain.GuestIPType;\nimport org.jclouds.cloudstack.domain.NetworkOffering;\nimport org.jclouds.cloudstack.domain.TrafficType;\n\nimport com.google.common.base.Predicate;\n\npublic class NetworkOfferingPredicates {\n\n   /**\n    * \n    * @return true, if the offering supports creation of GuestVirtual Networks\n    */\n   public static Predicate<NetworkOffering> supportsGuestVirtualNetworks() {\n      return new Predicate<NetworkOffering>() {\n\n         @Override\n         public boolean apply(NetworkOffering arg0) {\n            return arg0.getTrafficType() == TrafficType.GUEST && arg0.getGuestIPType() == GuestIPType.VIRTUAL;\n         }\n\n         @Override\n         public String toString() {\n            return \"supportsGuestVirtualNetworks()\";\n         }\n      };\n   }\n\n   /**\n    * \n    * @return always returns true.\n    */\n   public static Predicate<NetworkOffering> any() {\n      return alwaysTrue();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/predicates/NetworkPredicates.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.cloudstack.domain.GuestIPType;\nimport org.jclouds.cloudstack.domain.Network;\nimport org.jclouds.cloudstack.domain.NetworkService;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Predicates;\nimport com.google.common.collect.Iterables;\n\npublic class NetworkPredicates {\n\n   public static enum HasFirewallServiceWhichSupportsStaticNAT implements Predicate<Network> {\n      INSTANCE;\n\n      @Override\n      public boolean apply(Network arg0) {\n         return Iterables.any(checkNotNull(arg0, \"network\").getServices(), supportsStaticNAT);\n      }\n\n      @Override\n      public String toString() {\n         return supportsStaticNAT.toString();\n      }\n   }\n\n   public static enum HasFirewallServiceWhichSupportsPortForwarding implements Predicate<Network> {\n      INSTANCE;\n\n      @Override\n      public boolean apply(Network arg0) {\n         return Iterables.any(checkNotNull(arg0, \"network\").getServices(), supportsPortForwarding);\n      }\n\n      @Override\n      public String toString() {\n         return supportsPortForwarding.toString();\n      }\n   }\n\n   public static enum HasLoadBalancerService implements Predicate<Network> {\n      INSTANCE;\n\n      @Override\n      public boolean apply(Network arg0) {\n         return Iterables.any(checkNotNull(arg0, \"network\").getServices(), isLoadBalancerService);\n      }\n\n      @Override\n      public String toString() {\n         return isLoadBalancerService.toString();\n      }\n   }\n\n   public static enum IsVirtualNetwork implements Predicate<Network> {\n      INSTANCE;\n\n      @Override\n      public boolean apply(Network arg0) {\n         boolean network = isVirtualNetwork.apply(checkNotNull(arg0, \"network\").getGuestIPType());\n         return network;\n      }\n\n      @Override\n      public String toString() {\n         return isVirtualNetwork.toString();\n      }\n   }\n    \n   public static enum IsSharedNetwork implements Predicate<Network> {\n      INSTANCE;\n\n      @Override\n      public boolean apply(Network arg0) {\n         boolean network = isSharedNetwork.apply(checkNotNull(arg0, \"network\").getGuestIPType());\n         return network;\n      }\n\n      @Override\n      public String toString() {\n         return isSharedNetwork.toString();\n      }\n   }\n\n   public static enum IsIsolatedNetwork implements Predicate<Network> {\n      INSTANCE;\n\n      @Override\n      public boolean apply(Network arg0) {\n         boolean network = isIsolatedNetwork.apply(checkNotNull(arg0, \"network\").getGuestIPType());\n         return network;\n      }\n\n      @Override\n      public String toString() {\n         return isIsolatedNetwork.toString();\n      }\n   }\n\n    \n   private static class DefaultNetworkInZone implements Predicate<Network> {\n      private final String zoneId;\n\n      public DefaultNetworkInZone(String zoneId) {\n         this.zoneId = zoneId;\n      }\n\n      @Override\n      public boolean apply(Network network) {\n         return network.getZoneId().equals(zoneId) && network.isDefault();\n      }\n   }\n\n   public static class NetworkServiceNamed implements Predicate<NetworkService> {\n      private final String name;\n\n      public NetworkServiceNamed(String name) {\n         this.name = checkNotNull(name, \"name\");\n      }\n\n      @Override\n      public boolean apply(NetworkService input) {\n         return name.equals(checkNotNull(input, \"networkService\").getName());\n      }\n\n      @Override\n      public String toString() {\n         return \"networkServiceNamed(\" + name + \")\";\n      }\n   }\n\n   public static class GuestIPTypeIs implements Predicate<GuestIPType> {\n      private final GuestIPType guestIPType;\n\n      public GuestIPTypeIs(GuestIPType guestIPType) {\n         this.guestIPType = guestIPType;\n      }\n\n      @Override\n      public boolean apply(GuestIPType guestIPType) {\n         return guestIPType == this.guestIPType;\n      }\n\n      @Override\n      public String toString() {\n         return \"guestIPTypeIs(\" + guestIPType + ')';\n      }\n   }\n   \n   public static class CapabilitiesInclude implements Predicate<NetworkService> {\n      private final String capability;\n\n      public CapabilitiesInclude(String capability) {\n         this.capability = checkNotNull(capability, \"capability\");\n      }\n\n      @Override\n      public boolean apply(NetworkService input) {\n         return \"true\".equals(input.getCapabilities().get(capability));\n      }\n\n      @Override\n      public String toString() {\n         return \"capabilitiesInclude(\" + capability + \")\";\n      }\n   }\n\n   public static final Predicate<NetworkService> supportsStaticNAT = Predicates.and(new NetworkServiceNamed(\"Firewall\"),\n         new CapabilitiesInclude(\"StaticNat\"));\n\n   public static final Predicate<NetworkService> supportsPortForwarding = Predicates.and(new NetworkServiceNamed(\"Firewall\"),\n         new CapabilitiesInclude(\"PortForwarding\"));\n\n   public static final Predicate<NetworkService> isLoadBalancerService = new NetworkServiceNamed(\"Lb\");\n\n   public static final Predicate<GuestIPType> isVirtualNetwork = new GuestIPTypeIs(GuestIPType.VIRTUAL);\n\n   public static final Predicate<GuestIPType> isIsolatedNetwork = new GuestIPTypeIs(GuestIPType.ISOLATED);\n\n   public static final Predicate<GuestIPType> isSharedNetwork = new GuestIPTypeIs(GuestIPType.SHARED);\n\n   /**\n    * \n    * @return true, if the network supports static NAT.\n    */\n   public static Predicate<Network> supportsStaticNAT() {\n      return HasFirewallServiceWhichSupportsStaticNAT.INSTANCE;\n   }\n\n   /**\n    * \n    * @return true, if the network supports port forwarding.\n    */\n   public static Predicate<Network> supportsPortForwarding() {\n      return HasFirewallServiceWhichSupportsPortForwarding.INSTANCE;\n   }\n\n   /**\n    *\n    * @return true, if the network supports load balancing.\n    */\n   public static Predicate<Network> hasLoadBalancerService() {\n      return HasLoadBalancerService.INSTANCE;\n   }\n\n   /**\n    *\n    * @return true, if the network is a virtual network.\n    */\n   public static Predicate<Network> isVirtualNetwork() {\n      return IsVirtualNetwork.INSTANCE;\n   }\n\n   /**\n    *\n    * @return true, if the network is an isolated network.\n    */\n   public static Predicate<Network> isIsolatedNetwork() {\n      return IsIsolatedNetwork.INSTANCE;\n   }\n\n   /**\n    *\n    * @return true, if the network is a shared network.\n    */\n   public static Predicate<Network> isSharedNetwork() {\n      return IsSharedNetwork.INSTANCE;\n   }\n\n   /**\n    * Filters for default networks in a specific zone.\n    *\n    * @param zoneId the ID of the required zone.\n    * @return networks in the zone that have the default flag set.\n    */\n   public static Predicate<Network> defaultNetworkInZone(final String zoneId) {\n      return new DefaultNetworkInZone(zoneId);\n   }\n\n   /**\n    * \n    * @return always returns true.\n    */\n   public static Predicate<Network> any() {\n      return Predicates.alwaysTrue();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/predicates/OSCategoryIn.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.cloudstack.CloudStackApi;\nimport org.jclouds.cloudstack.domain.OSType;\nimport org.jclouds.cloudstack.domain.Template;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Predicates;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.Maps;\n\n@Singleton\npublic class OSCategoryIn implements Function<Set<String>, Predicate<Template>> {\n   private final Supplier<Map<String, String>> categoriesSupplier;\n   private final Supplier<Set<OSType>> osTypesSupplier;\n\n   @Inject\n   public OSCategoryIn(CloudStackApi client) {\n      this(Suppliers.ofInstance(checkNotNull(client, \"client\").getGuestOSApi().listOSCategories()), Suppliers\n            .ofInstance(client.getGuestOSApi().listOSTypes()));\n   }\n\n   public OSCategoryIn(Supplier<Map<String, String>> categoriesSupplier, Supplier<Set<OSType>> osTypesSupplier) {\n      this.categoriesSupplier = checkNotNull(categoriesSupplier, \"categoriesSupplier\");\n      this.osTypesSupplier = checkNotNull(osTypesSupplier, \"osTypesSupplier\");\n   }\n\n   @Override\n   public Predicate<Template> apply(final Set<String> acceptableCategories) {\n      final Map<String, String> categories = categoriesSupplier.get();\n      final Set<String> acceptableOSTypeIds = Maps.filterValues(\n            Maps.transformValues(Maps.uniqueIndex(osTypesSupplier.get(), new Function<OSType, String>() {\n\n               @Override\n               public String apply(OSType input) {\n                  return input.getId();\n               }\n\n            }), new Function<OSType, String>() {\n\n               @Override\n               public String apply(OSType input) {\n                  return categories.get(input.getOSCategoryId());\n               }\n\n            }), Predicates.in(acceptableCategories)).keySet();\n      return new Predicate<Template>() {\n\n         @Override\n         public boolean apply(Template input) {\n            return Predicates.in(acceptableOSTypeIds).apply(input.getOSTypeId());\n         }\n\n         @Override\n         public String toString() {\n            return \"OSCategoryIn(\" + acceptableCategories + \")\";\n         }\n      };\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/predicates/PublicIPAddressPredicates.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.cloudstack.domain.PublicIPAddress;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Predicates;\n\npublic class PublicIPAddressPredicates {\n\n   public static final class AssociatedWithNetwork implements Predicate<PublicIPAddress> {\n      private final String networkId;\n\n      public AssociatedWithNetwork(String networkId) {\n         this.networkId = checkNotNull(networkId, \"networkId\");\n      }\n\n      @Override\n      public boolean apply(PublicIPAddress input) {\n         return networkId.equals(checkNotNull(input, \"ipaddress\").getAssociatedNetworkId());\n      }\n\n      @Override\n      public String toString() {\n         return \"associatedWithNetwork(\" + networkId + \")\";\n      }\n   }\n\n   public static enum Available implements Predicate<PublicIPAddress> {\n      INSTANCE;\n\n      @Override\n      public boolean apply(PublicIPAddress arg0) {\n         return !checkNotNull(arg0, \"ipaddress\").isSourceNAT() && !arg0.isStaticNAT()\n               && arg0.getVirtualMachineId() == null && arg0.getState() == PublicIPAddress.State.ALLOCATED;\n      }\n\n      @Override\n      public String toString() {\n         return \"available()\";\n      }\n   }\n\n   /**\n    * \n    * @return true, if the public ip address is not assigned to a VM or NAT rule\n    */\n   public static Predicate<PublicIPAddress> available() {\n      return Available.INSTANCE;\n   }\n\n   /**\n    * \n    * @return true, if the public ip address is associated with the specified\n    *         network\n    */\n   public static Predicate<PublicIPAddress> associatedWithNetwork(final String networkId) {\n      return new AssociatedWithNetwork(networkId);\n   }\n\n   /**\n    * \n    * @return always returns true.\n    */\n   public static Predicate<PublicIPAddress> any() {\n      return Predicates.alwaysTrue();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/predicates/SecurityGroupPredicates.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Predicates.alwaysTrue;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.IngressRule;\nimport org.jclouds.cloudstack.domain.SecurityGroup;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Multimap;\n\npublic class SecurityGroupPredicates {\n   /**\n    * \n    * @return true, if the security group contains an ingress rule with the given port in the port range\n    */\n   public static Predicate<SecurityGroup> portInRange(final int port) {\n      return new Predicate<SecurityGroup>() {\n\n         @Override\n         public boolean apply(SecurityGroup group) {\n            return Iterables.any(group.getIngressRules(), new Predicate<IngressRule>() {\n                  @Override\n                  public boolean apply(IngressRule rule) {\n                     return rule.getStartPort() <= port && rule.getEndPort() >= port;\n                  }\n               });\n         }\n\n         @Override\n         public String toString() {\n            return \"portInRange(\" + port + \")\";\n         }\n      };\n   }\n\n   /**\n    * \n    * @return true, if the security group contains an ingress rule with the given cidr\n    */\n   public static Predicate<SecurityGroup> hasCidr(final String cidr) {\n      return new Predicate<SecurityGroup>() {\n\n         @Override\n         public boolean apply(SecurityGroup group) {\n            return Iterables.any(group.getIngressRules(), new Predicate<IngressRule>() {\n                  @Override\n                  public boolean apply(IngressRule rule) {\n                     return rule.getCIDR() != null\n                        && rule.getCIDR().equals(cidr);\n                  }\n               });\n         }\n\n         @Override\n         public String toString() {\n            return \"hasCidr(\" + cidr + \")\";\n         }\n      };\n   }\n\n   /**\n    * \n    * @return true, if the security group contains an ingress rule with the given cidr and the given port in range\n    */\n   public static Predicate<SecurityGroup> portInRangeForCidr(final int port, final String cidr) {\n      return new Predicate<SecurityGroup>() {\n\n         @Override\n         public boolean apply(SecurityGroup group) {\n            return Iterables.any(group.getIngressRules(), new Predicate<IngressRule>() {\n                  @Override\n                  public boolean apply(IngressRule rule) {\n                     return rule.getCIDR() != null\n                        && rule.getCIDR().equals(cidr)\n                        && rule.getStartPort() <= port\n                        && rule.getEndPort() >= port;\n                  }\n               });\n         }\n\n         @Override\n         public String toString() {\n            return \"portInRangeForCidr(\" + port + \", \" + cidr + \")\";\n         }\n      };\n   }\n\n   /**\n    * \n    * @return always returns true.\n    */\n   public static Predicate<SecurityGroup> any() {\n      return alwaysTrue();\n   }\n\n   /**\n    * matches name of the given security group\n    * \n    * @param name\n    * @return predicate that matches name\n    */\n   public static Predicate<SecurityGroup> nameEquals(final String name) {\n      checkNotNull(name, \"name must be defined\");\n\n      return new Predicate<SecurityGroup>() {\n         @Override\n         public boolean apply(SecurityGroup ext) {\n            return name.equals(ext.getName());\n         }\n\n         @Override\n         public String toString() {\n            return \"nameEquals(\" + name + \")\";\n         }\n      };\n   }\n\n\n   /**\n    * matches name of the given security group\n    * \n    * @param name\n    * @return predicate that matches name\n    */\n   public static Predicate<SecurityGroup> nameMatches(final Predicate<String> name) {\n      checkNotNull(name, \"name must be defined\");\n\n      return new Predicate<SecurityGroup>() {\n         @Override\n         public boolean apply(SecurityGroup ext) {\n            return name.apply(ext.getName());\n         }\n\n         @Override\n         public String toString() {\n            return \"nameMatches(\" + name + \")\";\n         }\n      };\n   }\n\n   /**\n    * matches IngressRules with the given protocol, start and end port, and\n    * any of the given CIDRs.\n    *\n    * @param protocol\n    * @param startPort\n    * @param endPort\n    * @param cidrs\n    *\n    * @return predicate that matches as described\n    */\n   public static Predicate<IngressRule> ruleCidrMatches(final String protocol,\n                                                        final int startPort,\n                                                        final int endPort,\n                                                        final Set<String> cidrs) {\n      checkNotNull(protocol, \"protocol\");\n      checkNotNull(cidrs, \"cidrs\");\n\n      return new Predicate<IngressRule>() {\n         @Override\n         public boolean apply(IngressRule rule) {\n            return protocol.equals(rule.getProtocol())\n                    && startPort == rule.getStartPort()\n                    && endPort == rule.getEndPort()\n                    && cidrs.contains(rule.getCIDR());\n         }\n\n         @Override\n         public String toString() {\n            return \"ruleCidrMatches(protocol:\" + protocol\n                    + \",startPort:\" + startPort\n                    + \",endPort:\" + endPort\n                    + \",cidrs:[\" + cidrs\n                    + \"])\";\n         }\n      };\n   }\n\n   /**\n    * matches IngressRules with the given protocol, start and end port, and\n    * any of the given account/security group name pairs.\n    *\n    * @param protocol\n    * @param startPort\n    * @param endPort\n    * @param accountGroupNames\n    *\n    * @return predicate that matches as described\n    */\n   public static Predicate<IngressRule> ruleGroupMatches(final String protocol,\n                                                         final int startPort,\n                                                         final int endPort,\n                                                         final Multimap<String, String> accountGroupNames) {\n      checkNotNull(protocol, \"protocol\");\n      checkNotNull(accountGroupNames, \"accountGroupNames\");\n\n      return new Predicate<IngressRule>() {\n         @Override\n         public boolean apply(IngressRule rule) {\n            return protocol.equals(rule.getProtocol())\n                    && startPort == rule.getStartPort()\n                    && endPort == rule.getEndPort()\n                    && accountGroupNames.containsEntry(rule.getAccount(), rule.getSecurityGroupName());\n         }\n\n         @Override\n         public String toString() {\n            return \"ruleGroupMatches(protocol:\" + protocol\n                    + \",startPort:\" + startPort\n                    + \",endPort:\" + endPort\n                    + \",accountGroupNames:[\" + accountGroupNames\n                    + \"])\";\n         }\n      };\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/predicates/SshKeyPairPredicates.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.cloudstack.domain.SshKeyPair;\n\nimport com.google.common.base.Predicate;\n\n/**\n * Predicates handy when working with SshKeyPairs\n */\n\npublic class SshKeyPairPredicates {\n\n\n   /**\n    * matches name of the given key pair\n    * \n    * @param name\n    * @return predicate that matches name\n    */\n   public static Predicate<SshKeyPair> nameMatches(final Predicate<String> name) {\n      checkNotNull(name, \"name must be defined\");\n\n      return new Predicate<SshKeyPair>() {\n         @Override\n         public boolean apply(SshKeyPair ext) {\n            return name.apply(ext.getName());\n         }\n\n         @Override\n         public String toString() {\n            return \"nameMatches(\" + name + \")\";\n         }\n      };\n   }\n   \n   /**\n    * matches name of the given keypair starts with the specified prefix\n    *\n    * @param name the prefix you are looking for\n    * @return the predicate\n    */\n   public static Predicate<SshKeyPair> nameEquals(final String name) {\n      checkNotNull(name, \"name must be defined\");\n\n      return new Predicate<SshKeyPair>() {\n         @Override\n         public boolean apply(SshKeyPair ext) {\n            return ext.getName() != null && ext.getName().equals(name);\n         }\n\n         @Override\n         public String toString() {\n            return \"nameEquals(\" + name + \")\";\n         }\n      };\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/predicates/TemplatePredicates.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.predicates;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.cloudstack.domain.Template;\n\nimport com.google.common.base.Predicate;\n\n@Singleton\npublic class TemplatePredicates {\n   public static Predicate<Template> isReady() {\n      return Ready.INSTANCE;\n   }\n\n   public enum Ready implements Predicate<Template> {\n      INSTANCE;\n      @Override\n      public boolean apply(Template arg0) {\n         return arg0.isReady();\n      }\n\n      @Override\n      public String toString() {\n         return \"isReady()\";\n      }\n   }\n\n   public static enum PasswordEnabled implements Predicate<Template> {\n      INSTANCE;\n\n      @Override\n      public boolean apply(Template arg0) {\n         return arg0.isPasswordEnabled();\n      }\n\n      @Override\n      public String toString() {\n         return \"isPasswordEnabled()\";\n      }\n   }\n\n   public static Predicate<Template> isPasswordEnabled() {\n      return PasswordEnabled.INSTANCE;\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/predicates/UserPredicates.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.cloudstack.domain.Account;\nimport org.jclouds.cloudstack.domain.User;\nimport org.jclouds.cloudstack.domain.Account.Type;\n\nimport com.google.common.base.Predicate;\n\npublic class UserPredicates {\n\n   public static class ApiKeyEquals implements Predicate<User> {\n      private final String apiKey;\n\n      public ApiKeyEquals(String apiKey) {\n         this.apiKey = checkNotNull(apiKey, \"apiKey\");\n      }\n\n      @Override\n      public boolean apply(User input) {\n         return apiKey.equals(checkNotNull(input, \"user\").getApiKey());\n      }\n\n      @Override\n      public String toString() {\n         return \"apiKeyEquals(\" + apiKey + \")\";\n      }\n   }\n\n   /**\n    * \n    * @return true, if the user's apiKey is the following\n    */\n   public static Predicate<User> apiKeyEquals(String apiKey) {\n      return new ApiKeyEquals(apiKey);\n   }\n\n   /**\n    * \n    * @return true, if the user's account type is the following\n    */\n   public static Predicate<User> accountTypeEquals(Account.Type type) {\n      return new AccountTypeEquals(type);\n   }\n\n   public static class AccountTypeEquals implements Predicate<User> {\n      public AccountTypeEquals(Type type) {\n         this.type = checkNotNull(type, \"type\");\n      }\n\n      private final Account.Type type;\n\n      @Override\n      public boolean apply(User input) {\n         return checkNotNull(input, \"user\").getAccountType() == type;\n      }\n\n      @Override\n      public String toString() {\n         return \"accountTypeEquals(\" + type + \")\";\n      }\n   }\n\n   /**\n    *\n    * @return true, if the account has user privileges\n    */\n   public static Predicate<User> isUserAccount() {\n      return accountTypeEquals(Account.Type.USER);\n   }\n\n   /**\n    * @return true, is the user is a domain admin\n    */\n   public static Predicate<User> isDomainAdminAccount() {\n      return accountTypeEquals(Type.DOMAIN_ADMIN);\n   }\n\n   /**\n    * \n    * @return true, if the user is a global admin\n    */\n   public static Predicate<User> isAdminAccount() {\n      return accountTypeEquals(Account.Type.ADMIN);\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/predicates/VirtualMachineDestroyed.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.cloudstack.CloudStackApi;\nimport org.jclouds.cloudstack.domain.VirtualMachine;\nimport org.jclouds.cloudstack.domain.VirtualMachine.State;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Predicate;\nimport com.google.inject.Inject;\n\n/**\n * \n * Tests to see if a virtualMachine is running\n */\n@Singleton\npublic class VirtualMachineDestroyed implements Predicate<VirtualMachine> {\n\n   private final CloudStackApi client;\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   @Inject\n   public VirtualMachineDestroyed(CloudStackApi client) {\n      this.client = client;\n   }\n\n   public boolean apply(VirtualMachine virtualMachine) {\n      logger.trace(\"looking for state on virtualMachine %s\", checkNotNull(virtualMachine, \"virtualMachine\"));\n      virtualMachine = refresh(virtualMachine);\n      if (virtualMachine == null)\n         return true;\n      logger.trace(\"%s: looking for virtualMachine state %s: currently: %s\", virtualMachine.getId(), State.DESTROYED,\n            virtualMachine.getState());\n      return virtualMachine.getState() == State.DESTROYED;\n   }\n\n   private VirtualMachine refresh(VirtualMachine virtualMachine) {\n      return client.getVirtualMachineApi().getVirtualMachine(virtualMachine.getId());\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/predicates/VirtualMachineExpunged.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.cloudstack.CloudStackApi;\nimport org.jclouds.cloudstack.domain.VirtualMachine;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Predicate;\nimport com.google.inject.Inject;\n\n/**\n * \n * Tests to see if a virtualMachine is expunged from the system\n */\n@Singleton\npublic class VirtualMachineExpunged implements Predicate<VirtualMachine> {\n\n   private final CloudStackApi client;\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   @Inject\n   public VirtualMachineExpunged(CloudStackApi client) {\n      this.client = client;\n   }\n\n   public boolean apply(VirtualMachine virtualMachine) {\n      logger.trace(\"looking for state on virtualMachine %s\", checkNotNull(virtualMachine, \"virtualMachine\"));\n      return refresh(virtualMachine) == null;\n   }\n\n   private VirtualMachine refresh(VirtualMachine virtualMachine) {\n      return client.getVirtualMachineApi().getVirtualMachine(virtualMachine.getId());\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/predicates/VirtualMachineRunning.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.cloudstack.CloudStackApi;\nimport org.jclouds.cloudstack.domain.VirtualMachine;\nimport org.jclouds.cloudstack.domain.VirtualMachine.State;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Predicate;\nimport com.google.inject.Inject;\n\n/**\n * \n * Tests to see if a virtualMachine is running\n */\n@Singleton\npublic class VirtualMachineRunning implements Predicate<VirtualMachine> {\n\n   private final CloudStackApi client;\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   @Inject\n   public VirtualMachineRunning(CloudStackApi client) {\n      this.client = client;\n   }\n\n   public boolean apply(VirtualMachine virtualMachine) {\n      logger.trace(\"looking for state on virtualMachine %s\", checkNotNull(virtualMachine, \"virtualMachine\"));\n      virtualMachine = refresh(virtualMachine);\n      if (virtualMachine == null)\n         return false;\n      logger.trace(\"%s: looking for virtualMachine state %s: currently: %s\", virtualMachine.getId(), State.RUNNING,\n            virtualMachine.getState());\n      if (virtualMachine.getState() == State.ERROR)\n         throw new IllegalStateException(\"virtualMachine in error state: \" + virtualMachine);\n      return virtualMachine.getState() == State.RUNNING;\n   }\n\n   private VirtualMachine refresh(VirtualMachine virtualMachine) {\n      return client.getVirtualMachineApi().getVirtualMachine(virtualMachine.getId());\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/predicates/ZonePredicates.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Predicates.alwaysTrue;\n\nimport org.jclouds.cloudstack.domain.NetworkType;\nimport org.jclouds.cloudstack.domain.Zone;\n\nimport com.google.common.base.Predicate;\n\npublic class ZonePredicates {\n   /**\n    * \n    * @return true, if the zone supports {@link NetworkType.ADVANCED}\n    */\n   public static Predicate<Zone> supportsAdvancedNetworks() {\n      return new Predicate<Zone>() {\n\n         @Override\n         public boolean apply(Zone zone) {\n            return NetworkType.ADVANCED.equals(checkNotNull(zone, \"zone\").getNetworkType());\n         }\n\n         @Override\n         public String toString() {\n            return \"supportsAdvancedNetworks()\";\n         }\n      };\n   }\n\n   /**\n    * \n    * @return true, if the zone supports security groups\n    */\n   public static Predicate<Zone> supportsSecurityGroups() {\n      return new Predicate<Zone>() {\n\n         @Override\n         public boolean apply(Zone input) {\n            return input.isSecurityGroupsEnabled();\n         }\n\n         @Override\n         public String toString() {\n            return \"supportsSecurityGroups()\";\n         }\n      };\n   }\n\n   /**\n    * \n    * @return always returns true.\n    */\n   public static Predicate<Zone> any() {\n      return alwaysTrue();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/strategy/BlockUntilJobCompletesAndReturnResult.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.strategy;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.cloudstack.CloudStackApi;\nimport org.jclouds.cloudstack.domain.AsyncCreateResponse;\nimport org.jclouds.cloudstack.domain.AsyncJob;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.util.concurrent.UncheckedExecutionException;\n\n@Singleton\npublic class BlockUntilJobCompletesAndReturnResult {\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n   \n   private final CloudStackApi client;\n   private final Predicate<String> jobComplete;\n\n   @Inject\n   public BlockUntilJobCompletesAndReturnResult(CloudStackApi client, Predicate<String> jobComplete) {\n      this.client = checkNotNull(client, \"client\");\n      this.jobComplete = checkNotNull(jobComplete, \"jobComplete\");\n   }\n\n   /**\n    * \n    * @param job\n    * @return result of the job's execution\n    * @throws ExecutionException\n    *            if the job contained an error\n    */\n   public <T> T apply(AsyncCreateResponse job) {\n      boolean completed = jobComplete.apply(job.getJobId());\n      logger.trace(\"<< job(%s) complete(%s)\", job, completed);\n      AsyncJob<T> jobWithResult = client.getAsyncJobApi().<T> getAsyncJob(job.getJobId());\n      checkState(completed, \"job %s failed to complete in time %s\", job.getJobId(), jobWithResult);\n      if (jobWithResult.getError() != null)\n         throw new UncheckedExecutionException(String.format(\"job %s failed with exception %s\", job.getJobId(),\n               jobWithResult.getError().toString())) {\n         };\n      return jobWithResult.getResult();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/suppliers/GetCurrentUser.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.suppliers;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.NoSuchElementException;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\n\nimport org.jclouds.cloudstack.CloudStackApi;\nimport org.jclouds.cloudstack.domain.User;\nimport org.jclouds.cloudstack.predicates.UserPredicates;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.location.Provider;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.Iterables;\n\npublic class GetCurrentUser implements Supplier<User> {\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   private final CloudStackApi client;\n   private final Supplier<Credentials> creds;\n\n   @Inject\n   public GetCurrentUser(CloudStackApi client, @Provider Supplier<Credentials> creds) {\n      this.client = checkNotNull(client, \"client\");\n      this.creds = checkNotNull(creds, \"creds\");\n   }\n\n   @Override\n   public User get() {\n      Iterable<User> users = Iterables.concat(client.getAccountApi().listAccounts());\n      Predicate<User> apiKeyMatches = UserPredicates.apiKeyEquals(creds.get().identity);\n      User currentUser = null;\n      try {\n         currentUser = Iterables.find(users, apiKeyMatches);\n      } catch (NoSuchElementException e) {\n         throw new NoSuchElementException(String.format(\"none of the following users match %s: %s\", apiKeyMatches,\n               users));\n      }\n\n      return currentUser;\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/suppliers/NetworksForCurrentUser.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.suppliers;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.cloudstack.options.ListNetworksOptions.Builder.accountInDomain;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.cloudstack.CloudStackApi;\nimport org.jclouds.cloudstack.domain.Network;\nimport org.jclouds.cloudstack.domain.User;\nimport org.jclouds.cloudstack.features.NetworkApi;\nimport org.jclouds.collect.Memoized;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.Maps;\n\npublic class NetworksForCurrentUser implements Supplier<Map<String, Network>> {\n   private final CloudStackApi client;\n   private final Supplier<User> currentUserSupplier;\n\n   @Inject\n   public NetworksForCurrentUser(CloudStackApi client, @Memoized Supplier<User> currentUserSupplier) {\n      this.client = checkNotNull(client, \"client\");\n      this.currentUserSupplier = checkNotNull(currentUserSupplier, \"currentUserSupplier\");\n   }\n\n   @Override\n   public Map<String, Network> get() {\n      User currentUser = currentUserSupplier.get();\n      NetworkApi networkClient = client.getNetworkApi();\n      return Maps.uniqueIndex(\n            networkClient.listNetworks(accountInDomain(currentUser.getAccount(), currentUser.getDomainId())),\n            new Function<Network, String>() {\n\n               @Override\n               public String apply(Network arg0) {\n                  return arg0.getId();\n               }\n            });\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/suppliers/ProjectsForCurrentUser.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.suppliers;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.cloudstack.options.ListProjectsOptions.Builder.accountInDomain;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.cloudstack.CloudStackApi;\nimport org.jclouds.cloudstack.domain.Project;\nimport org.jclouds.cloudstack.domain.User;\nimport org.jclouds.cloudstack.features.ProjectApi;\nimport org.jclouds.collect.Memoized;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.Maps;\n\npublic class ProjectsForCurrentUser implements Supplier<Map<String, Project>> {\n   private final CloudStackApi api;\n   private final Supplier<User> currentUserSupplier;\n\n   @Inject\n   public ProjectsForCurrentUser(CloudStackApi api, @Memoized Supplier<User> currentUserSupplier) {\n      this.api = checkNotNull(api, \"api\");\n      this.currentUserSupplier = checkNotNull(currentUserSupplier, \"currentUserSupplier\");\n   }\n\n   @Override\n   public Map<String, Project> get() {\n      User currentUser = currentUserSupplier.get();\n      ProjectApi projectApi = api.getProjectApi();\n      return Maps.uniqueIndex(\n            projectApi.listProjects(accountInDomain(currentUser.getAccount(), currentUser.getDomainId())),\n            new Function<Project, String>() {\n\n               @Override\n               public String apply(Project arg0) {\n                  return arg0.getId();\n               }\n            });\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/suppliers/ZoneIdToZoneSupplier.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.suppliers;\n\nimport static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL;\n\nimport java.util.concurrent.TimeUnit;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.cloudstack.domain.Zone;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.inject.Inject;\n\n/**\n * Supplies a cache that maps from zone IDs to zones.\n */\npublic class ZoneIdToZoneSupplier implements Supplier<LoadingCache<String, Zone>> {\n   private final LoadingCache<String, Zone> cache;\n\n   @Inject\n   public ZoneIdToZoneSupplier(CacheLoader<String, Zone> zoneIdToZone, @Named(PROPERTY_SESSION_INTERVAL) long expirationSecs) {\n      cache = CacheBuilder.newBuilder().expireAfterWrite(expirationSecs, TimeUnit.SECONDS).build(zoneIdToZone);\n   }\n\n   @Override\n   public LoadingCache<String, Zone> get() {\n      return cache;\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/util/ApiKeyPairs.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.util;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.net.URI;\nimport java.util.NoSuchElementException;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport org.jclouds.Constants;\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.cloudstack.CloudStackApiMetadata;\nimport org.jclouds.cloudstack.CloudStackApi;\nimport org.jclouds.cloudstack.CloudStackContext;\nimport org.jclouds.cloudstack.domain.Account;\nimport org.jclouds.cloudstack.domain.ApiKeyPair;\nimport org.jclouds.cloudstack.domain.User;\n\npublic class ApiKeyPairs {\n\n   /**\n    * Retrieve the API key pair for a given CloudStack user\n    *\n    * @param endpoint\n    *          CloudStack API endpoint (e.g. http://72.52.126.25/client/api/)\n    * @param username\n    *          User account name\n    * @param password\n    *          User password\n    * @param domain\n    *          Domain name. If empty defaults to ROOT\n    * @throws NoSuchElementException, AuthorizationException\n    * @return\n    */\n   public static ApiKeyPair loginToEndpointAsUsernameInDomainWithPasswordAndReturnApiKeyPair(\n         URI endpoint, String username, String password, String domain) {\n      CloudStackContext context = null;\n      try {\n         Properties overrides = new Properties();\n         overrides.put(Constants.PROPERTY_TRUST_ALL_CERTS, \"true\");\n         overrides.put(Constants.PROPERTY_RELAX_HOSTNAME, \"true\");\n         overrides.put(\"jclouds.cloudstack.credential-type\", \"passwordCredentials\");\n         \n         context =  ContextBuilder.newBuilder(new CloudStackApiMetadata())\n               .endpoint(checkNotNull(endpoint, \"endpoint\").toASCIIString())\n               .credentials(String.format(\"%s/%s\", checkNotNull(domain, \"domain\"), checkNotNull(username, \"username\")), password)\n               .overrides(overrides).build(CloudStackContext.class);\n\n         CloudStackApi client = context.getApi();\n         Set<Account> listOfAccounts = client.getAccountApi().listAccounts();\n\n         domain = (domain.equals(\"\") || domain.equals(\"/\")) ? \"ROOT\" : domain;\n         for (Account account : listOfAccounts) {\n            for (User user : account.getUsers()) {\n               if (user.getName().equals(username) && user.getDomain().equals(domain)) {\n                  return ApiKeyPair.builder().apiKey(user.getApiKey())\n                     .secretKey(user.getSecretKey()).build();\n               }\n            }\n         }\n         throw new NoSuchElementException(\"Unable to find API keypair for user \" + username);\n\n      } finally {\n         if (context != null)\n            context.close();\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/main/java/org/jclouds/cloudstack/util/SnapshotPolicySchedules.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.util;\n\nimport org.jclouds.cloudstack.domain.Snapshot;\nimport org.jclouds.cloudstack.domain.SnapshotPolicySchedule;\n\n/**\n * Methods to create SnapshotPolicySchedule objects in the format required by Cloudstack.\n */\npublic class SnapshotPolicySchedules {\n   public static SnapshotPolicySchedule hourly(int minute) {\n      return SnapshotPolicySchedule.builder().interval(Snapshot.Interval.HOURLY).time(String.format(\"%02d\", minute)).build();\n   }\n\n   public static SnapshotPolicySchedule daily(int hour, int minute) {\n      return SnapshotPolicySchedule.builder().interval(Snapshot.Interval.DAILY).time(String.format(\"%02d:%02d\", minute, hour)).build();\n   }\n\n   public static SnapshotPolicySchedule weekly(int day, int hour, int minute) {\n      return SnapshotPolicySchedule.builder().interval(Snapshot.Interval.WEEKLY).time(String.format(\"%02d:%02d:%02d\", minute, hour, day)).build();\n   }\n\n   public static SnapshotPolicySchedule monthly(int day, int hour, int minute) {\n      return SnapshotPolicySchedule.builder().interval(Snapshot.Interval.MONTHLY).time(String.format(\"%02d:%02d:%02d\", minute, hour, day)).build();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/CloudStackApiMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack;\n\nimport org.jclouds.compute.internal.BaseComputeServiceApiMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"CloudStackApiMetadataTest\")\npublic class CloudStackApiMetadataTest extends BaseComputeServiceApiMetadataTest {\n\n   public CloudStackApiMetadataTest() {\n      super(new CloudStackApiMetadata());\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/CloudStackContextBuilderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack;\n\nimport static org.jclouds.reflect.Reflection2.typeToken;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.View;\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"CloudStackContextBuilderTest\")\npublic class CloudStackContextBuilderTest {\n\n   public void testAssignability() {\n      View view = ContextBuilder.newBuilder(new CloudStackApiMetadata()).credentials(\"foo\", \"bar\")\n              .buildView(typeToken(ComputeServiceContext.class));\n      view.unwrapApi(CloudStackApi.class);\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/PasswordAuthenticationExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack;\n\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.Properties;\n\nimport org.jclouds.cloudstack.features.AccountApi;\nimport org.jclouds.cloudstack.internal.BaseCloudStackExpectTest;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.Test;\n\nimport com.google.common.net.HttpHeaders;\n\n/**\n * \n * @see CloudStackProperties#CREDENTIAL_TYPE\n */\n@Test(groups = \"unit\", testName = \"PasswordAuthenticationExpectTest\")\npublic class PasswordAuthenticationExpectTest extends BaseCloudStackExpectTest<AccountApi> {\n\n   /**\n    * this reflects the properties that a user would pass to createContext\n    */\n   @Override\n   protected Properties setupProperties() {\n      Properties contextProperties = super.setupProperties();\n      contextProperties.setProperty(\"jclouds.cloudstack.credential-type\", \"passwordCredentials\");\n      return contextProperties;\n   }\n\n   public void testLoginWithPasswordSetsSessionKeyAndCookie() {\n      \n      AccountApi client = requestsSendResponses(\n               login, loginResponse, \n         HttpRequest.builder()\n            .method(\"GET\")\n            .endpoint(\"http://localhost:8080/client/api?response=json&command=listAccounts&listAll=true&sessionkey=\" + Strings2.urlEncode(sessionKey, '/'))\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(HttpHeaders.COOKIE, \"JSESSIONID=\" + jSessionId)\n            .build(),\n         HttpResponse.builder()\n            .statusCode(200)\n            .payload(payloadFromResource(\"/listaccountsresponse.json\"))\n            .build(),\n            logout, logoutResponse);\n      \n      assertNotNull(client.listAccounts());\n   }\n\n   @Override\n   protected AccountApi clientFrom(CloudStackContext context) {\n      return context.getApi().getAccountApi();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/compute/CloudStackComputeServiceAdapterExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.compute;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.util.Map;\n\nimport org.jclouds.cloudstack.CloudStackContext;\nimport org.jclouds.cloudstack.compute.options.CloudStackTemplateOptions;\nimport org.jclouds.cloudstack.compute.strategy.CloudStackComputeServiceAdapter;\nimport org.jclouds.cloudstack.domain.VirtualMachine;\nimport org.jclouds.cloudstack.internal.BaseCloudStackComputeServiceContextExpectTest;\nimport org.jclouds.compute.ComputeServiceAdapter.NodeAndInitialCredentials;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.domain.TemplateBuilder;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.inject.Injector;\n\n/**\n * Tests the compute service abstraction of the cloudstack api.\n */\n@Test(groups = \"unit\")\npublic class CloudStackComputeServiceAdapterExpectTest extends BaseCloudStackComputeServiceContextExpectTest<Injector> {\n   HttpResponse deployVMResponse = HttpResponse.builder().statusCode(200)\n         .payload(payloadFromResource(\"/deployvirtualmachineresponse.json\"))\n         .build();\n  \n   HttpRequest queryAsyncJobResult = HttpRequest.builder().method(\"GET\")\n        .endpoint(\"http://localhost:8080/client/api\")\n        .addQueryParam(\"response\", \"json\")\n        .addQueryParam(\"command\", \"queryAsyncJobResult\")\n        .addQueryParam(\"jobid\", \"50006\")\n        .addQueryParam(\"apiKey\", \"APIKEY\")\n        .addQueryParam(\"signature\", \"v8BWKMxd+IzHIuTaZ9sNSzCWqFI=\")\n        .addHeader(\"Accept\", \"application/json\")\n        .build();\n\n   HttpResponse queryAsyncJobResultResponse = HttpResponse.builder().statusCode(200)\n        .payload(payloadFromResource(\"/queryasyncjobresultresponse-virtualmachine.json\"))\n        .build();\n\n   HttpResponse queryAsyncJobResultSecurityGroupResponse = HttpResponse.builder().statusCode(200)\n        .payload(payloadFromResource(\"/queryasyncjobresultresponse-virtualmachine-securitygroup.json\"))\n        .build();\n\n   HttpRequest queryAsyncJobResultAuthorizeIngress = HttpRequest.builder().method(\"GET\")\n        .endpoint(\"http://localhost:8080/client/api\")\n        .addQueryParam(\"response\", \"json\")\n        .addQueryParam(\"command\", \"queryAsyncJobResult\")\n        .addQueryParam(\"jobid\", \"13330fc9-8b3e-4582-aa3e-90883c041010\")\n        .addQueryParam(\"apiKey\", \"APIKEY\")\n        .addQueryParam(\"signature\", \"y4gk3ckWAMPDNZM26LUK0gAhfiE=\")\n        .addHeader(\"Accept\", \"application/json\")\n        .build();\n\n   HttpResponse queryAsyncJobResultAuthorizeIngressResponse = HttpResponse.builder().statusCode(200)\n        .payload(payloadFromResource(\"/queryasyncjobresultresponse-authorizeingress.json\"))\n        .build();\n   \n   HttpRequest listCapabilitiesNotListAll = HttpRequest.builder().method(\"GET\")\n     .endpoint(\"http://localhost:8080/client/api\")\n     .addQueryParam(\"response\", \"json\")\n     .addQueryParam(\"command\", \"listCapabilities\")\n     .addQueryParam(\"apiKey\", \"APIKEY\")\n     .addQueryParam(\"signature\", \"l3PVoJnKK2G2gHk3HPHtpwWjlW4=\")\n     .addHeader(\"Accept\", \"application/json\")\n     .build();\n\n   public void testCreateNodeWithGroupEncodedIntoName() {\n      HttpRequest deployVM = HttpRequest.builder().method(\"GET\")\n              .endpoint(\"http://localhost:8080/client/api\")\n              .addQueryParam(\"response\", \"json\")\n              .addQueryParam(\"command\", \"deployVirtualMachine\")\n              .addQueryParam(\"zoneid\", \"1\")\n              .addQueryParam(\"serviceofferingid\", \"1\")\n              .addQueryParam(\"templateid\", \"4\")\n              .addQueryParam(\"displayname\", \"test-e92\")\n              .addQueryParam(\"name\", \"test-e92\")\n              .addQueryParam(\"networkids\", \"204\")\n              .addQueryParam(\"group\", \"test\")\n              .addQueryParam(\"apiKey\", \"APIKEY\")\n              .addQueryParam(\"signature\", \"M2Wx0CgOeH9vYHhbcbblwziqpwI=\")\n              .addHeader(\"Accept\", \"application/json\")\n              .build();\n  \n      Map<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder()\n              .put(listProjects, listProjectsResponse)\n              .put(listTemplates, listTemplatesResponse)\n              .put(listOsTypes, listOsTypesResponse)\n              .put(listOsCategories, listOsCategoriesResponse)\n              .put(listZones, listZonesResponse)\n              .put(listServiceOfferings, listServiceOfferingsResponse)\n              .put(listAccounts, listAccountsResponse)\n              .put(listNetworks, listNetworksResponse)\n              .put(getZone, getZoneResponse)\n              .put(deployVM, deployVMResponse)\n              .put(queryAsyncJobResult, queryAsyncJobResultResponse)\n              .build();\n\n      Injector forNode = requestsSendResponses(requestResponseMap);\n\n      Template template = forNode.getInstance(TemplateBuilder.class).osFamily(OsFamily.CENTOS).build();\n      template.getOptions().as(CloudStackTemplateOptions.class).setupStaticNat(false);\n\n      CloudStackComputeServiceAdapter adapter = forNode.getInstance(CloudStackComputeServiceAdapter.class);\n\n      NodeAndInitialCredentials<VirtualMachine> server = adapter.createNodeWithGroupEncodedIntoName(\"test\", \"test-e92\",\n            template);\n      assertNotNull(server);\n      assertEquals(server.getCredentials(), LoginCredentials.builder().password(\"dD7jwajkh\").build());\n   }\n\n   public void testCreateNodeWithGroupEncodedIntoNameWithKeyPair() throws IOException {\n      HttpRequest deployVM = HttpRequest.builder().method(\"GET\")\n              .endpoint(\"http://localhost:8080/client/api\")\n              .addQueryParam(\"response\", \"json\")\n              .addQueryParam(\"command\", \"deployVirtualMachine\")\n              .addQueryParam(\"zoneid\", \"1\")\n              .addQueryParam(\"serviceofferingid\", \"1\")\n              .addQueryParam(\"templateid\", \"4\")\n              .addQueryParam(\"displayname\", \"test-e92\")\n              .addQueryParam(\"name\", \"test-e92\")\n              .addQueryParam(\"networkids\", \"204\")\n              .addQueryParam(\"group\", \"test\")\n              .addQueryParam(\"keypair\", \"mykeypair\")\n              .addQueryParam(\"apiKey\", \"APIKEY\")\n              .addQueryParam(\"signature\", \"D3qQlTNjxrBXeG82C7YPrwU1jMc=\")\n              .addHeader(\"Accept\", \"application/json\")\n              .build();\n  \n      Map<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder()\n              .put(listProjects, listProjectsResponse)\n              .put(listTemplates, listTemplatesResponse)\n              .put(listOsTypes, listOsTypesResponse)\n              .put(listOsCategories, listOsCategoriesResponse)\n              .put(listZones, listZonesResponse)\n              .put(listServiceOfferings, listServiceOfferingsResponse)\n              .put(listAccounts, listAccountsResponse)\n              .put(listNetworks, listNetworksResponse)\n              .put(getZone, getZoneResponse)\n              .put(deployVM, deployVMResponse)\n              .put(queryAsyncJobResult, queryAsyncJobResultResponse)\n              .build();\n\n      Injector forKeyPair = requestsSendResponses(requestResponseMap);\n\n      String privKey = Strings2.toStringAndClose(getClass().getResourceAsStream(\"/test\"));\n      Template template = forKeyPair.getInstance(TemplateBuilder.class).osFamily(OsFamily.CENTOS).build();\n      template.getOptions().as(CloudStackTemplateOptions.class).keyPair(\"mykeypair\")\n         .setupStaticNat(false)\n         .overrideLoginPrivateKey(privKey);\n\n      CloudStackComputeServiceAdapter adapter = forKeyPair.getInstance(CloudStackComputeServiceAdapter.class);\n\n      NodeAndInitialCredentials<VirtualMachine> server = adapter.createNodeWithGroupEncodedIntoName(\"test\", \"test-e92\",\n            template);\n      assertNotNull(server);\n      assertEquals(server.getCredentials().getOptionalPrivateKey().get(), privKey);\n   }\n\n   public void testCreateNodeWithGroupEncodedIntoNameWithGenerateKeyPair() throws IOException {\n      HttpRequest deployVM = HttpRequest.builder().method(\"GET\")\n              .endpoint(\"http://localhost:8080/client/api\")\n              .addQueryParam(\"response\", \"json\")\n              .addQueryParam(\"command\", \"deployVirtualMachine\")\n              .addQueryParam(\"zoneid\", \"1\")\n              .addQueryParam(\"serviceofferingid\", \"1\")\n              .addQueryParam(\"templateid\", \"4\")\n              .addQueryParam(\"displayname\", \"test-e92\")\n              .addQueryParam(\"name\", \"test-e92\")\n              .addQueryParam(\"networkids\", \"204\")\n              .addQueryParam(\"group\", \"test\")\n              .addQueryParam(\"keypair\", \"jclouds-test\")\n              .addQueryParam(\"apiKey\", \"APIKEY\")\n              .addQueryParam(\"signature\", \"kfU/J/REa4DdYj0b/pSjuB3h3Qc=\")\n              .addHeader(\"Accept\", \"application/json\")\n              .build();\n  \n      Map<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder()\n              .put(listProjects, listProjectsResponse)\n              .put(listTemplates, listTemplatesResponse)\n              .put(listOsTypes, listOsTypesResponse)\n              .put(listOsCategories, listOsCategoriesResponse)\n              .put(listZones, listZonesResponse)\n              .put(listServiceOfferings, listServiceOfferingsResponse)\n              .put(listAccounts, listAccountsResponse)\n              .put(listNetworks, listNetworksResponse)\n              .put(getZone, getZoneResponse)\n              .put(deployVM, deployVMResponse)\n              .put(createSSHKeyPair, createSSHKeyPairResponse)\n              .put(queryAsyncJobResult, queryAsyncJobResultResponse)\n              .build();\n\n      Injector forKeyPair = requestsSendResponses(requestResponseMap);\n\n      Template template = forKeyPair.getInstance(TemplateBuilder.class).osFamily(OsFamily.CENTOS).build();\n      template.getOptions().as(CloudStackTemplateOptions.class).generateKeyPair(true)\n         .setupStaticNat(false);\n\n      CloudStackComputeServiceAdapter adapter = forKeyPair.getInstance(CloudStackComputeServiceAdapter.class);\n\n      NodeAndInitialCredentials<VirtualMachine> server = adapter.createNodeWithGroupEncodedIntoName(\"test\", \"test-e92\",\n            template);\n      assertNotNull(server);\n      assertTrue(server.getCredentials().getOptionalPrivateKey().isPresent());\n   }\n   \n   public void testCreateNodeWithGroupEncodedIntoNameWithKeyPairDefaultSecurityGroup() throws IOException {\n      HttpRequest deployVM = HttpRequest.builder().method(\"GET\")\n              .endpoint(\"http://localhost:8080/client/api\")\n              .addQueryParam(\"response\", \"json\")\n              .addQueryParam(\"command\", \"deployVirtualMachine\")\n              .addQueryParam(\"zoneid\", \"2\")\n              .addQueryParam(\"serviceofferingid\", \"1\")\n              .addQueryParam(\"templateid\", \"241\")\n              .addQueryParam(\"displayname\", \"test-e92\")\n              .addQueryParam(\"name\", \"test-e92\")\n              .addQueryParam(\"networkids\", \"204\")\n              .addQueryParam(\"group\", \"test\")\n              .addQueryParam(\"keypair\", \"mykeypair\")\n              .addQueryParam(\"apiKey\", \"APIKEY\")\n              .addQueryParam(\"signature\", \"5qkUSGh0y+P/t04/j3+EN9PAeFI=\")\n              .addHeader(\"Accept\", \"application/json\")\n              .build();\n  \n      Map<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder()\n              .put(listProjects, listProjectsResponse)\n              .put(listTemplates, listTemplatesResponse)\n              .put(listOsTypes, listOsTypesResponse)\n              .put(listOsCategories, listOsCategoriesResponse)\n              .put(listZones, listZonesResponse)\n              .put(listServiceOfferings, listServiceOfferingsResponse)\n              .put(listAccounts, listAccountsResponse)\n              .put(listNetworks, listNetworksWithSecurityGroupsResponse)\n              .put(getZoneWithSecurityGroups, getZoneWithSecurityGroupsResponse)\n              .put(deployVM, deployVMResponse)\n              .put(queryAsyncJobResult, queryAsyncJobResultResponse)\n              .build();\n\n      Injector forKeyPair = requestsSendResponses(requestResponseMap);\n\n      String privKey = Strings2.toStringAndClose(getClass().getResourceAsStream(\"/test\"));\n      Template template = forKeyPair.getInstance(TemplateBuilder.class)\n         .osFamily(OsFamily.CENTOS)\n         .locationId(\"2\")\n         .build();\n      template.getOptions().as(CloudStackTemplateOptions.class).keyPair(\"mykeypair\")\n         .setupStaticNat(false)\n         .overrideLoginPrivateKey(privKey);\n\n      CloudStackComputeServiceAdapter adapter = forKeyPair.getInstance(CloudStackComputeServiceAdapter.class);\n\n      NodeAndInitialCredentials<VirtualMachine> server = adapter.createNodeWithGroupEncodedIntoName(\"test\", \"test-e92\",\n            template);\n      assertNotNull(server);\n      assertEquals(server.getCredentials().getOptionalPrivateKey().get(), privKey);\n   }\n\n   public void testCreateNodeWithGroupEncodedIntoNameWithKeyPairDefaultSecurityGroupAndDisk() throws IOException {\n      HttpRequest deployVM = HttpRequest.builder().method(\"GET\")\n              .endpoint(\"http://localhost:8080/client/api\")\n              .addQueryParam(\"response\", \"json\")\n              .addQueryParam(\"command\", \"deployVirtualMachine\")\n              .addQueryParam(\"zoneid\", \"2\")\n              .addQueryParam(\"serviceofferingid\", \"1\")\n              .addQueryParam(\"templateid\", \"241\")\n              .addQueryParam(\"displayname\", \"test-e92\")\n              .addQueryParam(\"name\", \"test-e92\")\n              .addQueryParam(\"networkids\", \"204\")\n              .addQueryParam(\"group\", \"test\")\n              .addQueryParam(\"keypair\", \"mykeypair\")\n              .addQueryParam(\"diskofferingid\", \"5678\")\n              .addQueryParam(\"size\", \"10\")\n              .addQueryParam(\"apiKey\", \"APIKEY\")\n              .addQueryParam(\"signature\", \"lDzBXtVKCktueskyI/haID9ohJU=\")\n              .addHeader(\"Accept\", \"application/json\")\n              .build();\n\n      Map<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder()\n              .put(listProjects, listProjectsResponse)\n              .put(listTemplates, listTemplatesResponse)\n              .put(listOsTypes, listOsTypesResponse)\n              .put(listOsCategories, listOsCategoriesResponse)\n              .put(listZones, listZonesResponse)\n              .put(listServiceOfferings, listServiceOfferingsResponse)\n              .put(listAccounts, listAccountsResponse)\n              .put(listNetworks, listNetworksWithSecurityGroupsResponse)\n              .put(getZoneWithSecurityGroups, getZoneWithSecurityGroupsResponse)\n              .put(deployVM, deployVMResponse)\n              .put(queryAsyncJobResult, queryAsyncJobResultResponse)\n              .build();\n\n      Injector forKeyPair = requestsSendResponses(requestResponseMap);\n\n      String privKey = Strings2.toStringAndClose(getClass().getResourceAsStream(\"/test\"));\n      Template template = forKeyPair.getInstance(TemplateBuilder.class)\n              .osFamily(OsFamily.CENTOS)\n              .locationId(\"2\")\n              .build();\n      template.getOptions().as(CloudStackTemplateOptions.class).keyPair(\"mykeypair\")\n              .diskOfferingId(\"5678\")\n              .dataDiskSize(10)\n              .setupStaticNat(false)\n              .overrideLoginPrivateKey(privKey);\n\n\n      CloudStackComputeServiceAdapter adapter = forKeyPair.getInstance(CloudStackComputeServiceAdapter.class);\n\n      NodeAndInitialCredentials<VirtualMachine> server = adapter.createNodeWithGroupEncodedIntoName(\"test\", \"test-e92\",\n              template);\n      assertNotNull(server);\n      assertEquals(server.getCredentials().getOptionalPrivateKey().get(), privKey);\n   }\n\n   public void testCreateNodeWithGroupEncodedIntoNameWithKeyPairGenerateSecurityGroup() throws IOException {\n      HttpRequest deployVM = HttpRequest.builder().method(\"GET\")\n              .endpoint(\"http://localhost:8080/client/api\")\n              .addQueryParam(\"response\", \"json\")\n              .addQueryParam(\"command\", \"deployVirtualMachine\")\n              .addQueryParam(\"zoneid\", \"2\")\n              .addQueryParam(\"serviceofferingid\", \"1\")\n              .addQueryParam(\"templateid\", \"241\")\n              .addQueryParam(\"displayname\", \"test-e92\")\n              .addQueryParam(\"name\", \"test-e92\")\n              .addQueryParam(\"networkids\", \"204\")\n              .addQueryParam(\"group\", \"test\")\n              .addQueryParam(\"keypair\", \"mykeypair\")\n              .addQueryParam(\"securitygroupids\", \"30\")\n              .addQueryParam(\"apiKey\", \"APIKEY\")\n              .addQueryParam(\"signature\", \"rz8V/tMk/UbxUhNqp7Bq3CrSg/k=\")\n              .addHeader(\"Accept\", \"application/json\")\n              .build();\n  \n      Map<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder()\n              .put(listProjects, listProjectsResponse)\n              .put(listTemplates, listTemplatesResponse)\n              .put(listOsTypes, listOsTypesResponse)\n              .put(listOsCategories, listOsCategoriesResponse)\n              .put(listZones, listZonesResponse)\n              .put(listServiceOfferings, listServiceOfferingsResponse)\n              .put(listAccounts, listAccountsResponse)\n              .put(listNetworks, listNetworksWithSecurityGroupsResponse)\n              .put(getZoneWithSecurityGroups, getZoneWithSecurityGroupsResponse)\n              .put(deployVM, deployVMResponse)\n              .put(queryAsyncJobResult, queryAsyncJobResultSecurityGroupResponse)\n              .put(queryAsyncJobResultAuthorizeIngress, queryAsyncJobResultAuthorizeIngressResponse)\n              .put(getSecurityGroup, getSecurityGroupResponse)\n              .put(createSecurityGroup, createSecurityGroupResponse)\n              .put(authorizeIngress, authorizeIngressResponse)\n              .build();\n\n      Injector forKeyPair = requestsSendResponses(requestResponseMap);\n\n      String privKey = Strings2.toStringAndClose(getClass().getResourceAsStream(\"/test\"));\n      Template template = forKeyPair.getInstance(TemplateBuilder.class)\n         .osFamily(OsFamily.CENTOS)\n         .locationId(\"2\")\n         .build();\n      template.getOptions().as(CloudStackTemplateOptions.class).keyPair(\"mykeypair\")\n         .setupStaticNat(false)\n         .generateSecurityGroup(true)\n         .overrideLoginPrivateKey(privKey);\n\n      CloudStackComputeServiceAdapter adapter = forKeyPair.getInstance(CloudStackComputeServiceAdapter.class);\n      CloudStackContext context = forKeyPair.getInstance(CloudStackContext.class);\n\n      NodeAndInitialCredentials<VirtualMachine> server = adapter.createNodeWithGroupEncodedIntoName(\"test\", \"test-e92\",\n            template);\n      assertNotNull(server);\n      assertEquals(server.getCredentials().getOptionalPrivateKey().get(), privKey);\n   }\n\n   public void testCreateNodeWithGroupEncodedIntoNameWithKeyPairAssignedToAccountAndDomain() throws IOException {\n      HttpRequest deployVM = HttpRequest.builder().method(\"GET\")\n              .endpoint(\"http://localhost:8080/client/api\")\n              .addQueryParam(\"response\", \"json\")\n              .addQueryParam(\"command\", \"deployVirtualMachine\")\n              .addQueryParam(\"zoneid\", \"1\")\n              .addQueryParam(\"serviceofferingid\", \"1\")\n              .addQueryParam(\"templateid\", \"4\")\n              .addQueryParam(\"displayname\", \"test-e92\")\n              .addQueryParam(\"name\", \"test-e92\")\n              .addQueryParam(\"account\", \"account\") //\n              .addQueryParam(\"domainid\", \"domainId\") //\n              .addQueryParam(\"networkids\", \"204\")\n              .addQueryParam(\"group\", \"test\")\n              .addQueryParam(\"keypair\", \"mykeypair\")\n              .addQueryParam(\"apiKey\", \"APIKEY\")\n              .addQueryParam(\"signature\", \"hGV6gZZakwvNKhTJurkm48+zgso=\")\n              .addHeader(\"Accept\", \"application/json\")\n              .build();\n\n      Map<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder()\n              .put(listProjects, listProjectsResponse)\n              .put(listTemplates, listTemplatesResponse)\n              .put(listOsTypes, listOsTypesResponse)\n              .put(listOsCategories, listOsCategoriesResponse)\n              .put(listZones, listZonesResponse)\n              .put(listServiceOfferings, listServiceOfferingsResponse)\n              .put(listAccounts, listAccountsResponse)\n              .put(listNetworks, listNetworksResponse)\n              .put(getZone, getZoneResponse)\n              .put(deployVM, deployVMResponse)\n              .put(queryAsyncJobResult, queryAsyncJobResultResponse)\n              .build();\n\n      Injector forKeyPair = requestsSendResponses(requestResponseMap);\n\n      String privKey = Strings2.toStringAndClose(getClass().getResourceAsStream(\"/test\"));\n      Template template = forKeyPair.getInstance(TemplateBuilder.class).osFamily(OsFamily.CENTOS).build();\n      template.getOptions().as(CloudStackTemplateOptions.class).keyPair(\"mykeypair\")\n         .account(\"account\")\n         .domainId(\"domainId\")\n         .setupStaticNat(false)\n         .overrideLoginPrivateKey(privKey);\n\n      CloudStackComputeServiceAdapter adapter = forKeyPair.getInstance(CloudStackComputeServiceAdapter.class);\n      CloudStackContext context = forKeyPair.getInstance(CloudStackContext.class);\n\n      NodeAndInitialCredentials<VirtualMachine> server = adapter.createNodeWithGroupEncodedIntoName(\"test\", \"test-e92\",\n            template);\n      assertNotNull(server);\n      assertEquals(server.getCredentials().getOptionalPrivateKey().get(), privKey);\n   }   \n   \n   @Override\n   protected Injector clientFrom(CloudStackContext context) {\n      return context.utils().injector();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/compute/CloudStackComputeServiceAdapterLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.compute;\nimport static com.google.common.collect.Iterables.getFirst;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\n\nimport java.util.Map;\nimport java.util.Random;\n\n\nimport org.jclouds.cloudstack.compute.options.CloudStackTemplateOptions;\nimport org.jclouds.cloudstack.compute.strategy.CloudStackComputeServiceAdapter;\nimport org.jclouds.cloudstack.domain.IPForwardingRule;\nimport org.jclouds.cloudstack.domain.ServiceOffering;\nimport org.jclouds.cloudstack.domain.VirtualMachine;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest;\nimport org.jclouds.cloudstack.predicates.TemplatePredicates;\nimport org.jclouds.compute.ComputeServiceAdapter.NodeAndInitialCredentials;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.functions.DefaultCredentialsFromImageOrOverridingCredentials;\nimport org.jclouds.compute.strategy.PrioritizeCredentialsFromTemplate;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.ssh.SshKeys;\nimport org.testng.annotations.AfterGroups;\nimport org.testng.annotations.BeforeGroups;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Maps;\nimport com.google.common.net.HostAndPort;\nimport com.google.common.net.InetAddresses;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"CloudStackComputeServiceAdapterLiveTest\")\npublic class CloudStackComputeServiceAdapterLiveTest extends BaseCloudStackApiLiveTest {\n\n   private CloudStackComputeServiceAdapter adapter;\n   private NodeAndInitialCredentials<VirtualMachine> vm;\n\n   private String keyPairName;\n   private Map<String, String> keyPair;\n   Map<String, Credentials> credentialStore = Maps.newLinkedHashMap();\n\n   @BeforeGroups(groups = { \"live\" })\n   public void setupContext() {\n      super.setupContext();\n\n      adapter = context.utils().injector().getInstance(\n            CloudStackComputeServiceAdapter.class);\n\n      keyPairName = prefix + \"-adapter-test-keypair\";\n      keyPair = SshKeys.generate();\n\n      client.getSSHKeyPairApi().deleteSSHKeyPair(keyPairName);\n      client.getSSHKeyPairApi().registerSSHKeyPair(keyPairName, keyPair.get(\"public\"));\n   }\n\n   @Test\n   public void testListLocations() {\n      assertFalse(Iterables.isEmpty(adapter.listLocations()));\n   }\n\n   private static final PrioritizeCredentialsFromTemplate prioritizeCredentialsFromTemplate = new PrioritizeCredentialsFromTemplate(\n         new DefaultCredentialsFromImageOrOverridingCredentials());\n\n   @Test\n   public void testCreateNodeWithGroupEncodedIntoName() {\n      String group = prefix + \"-foo\";\n      String name = group + \"-node-\" + new Random().nextInt();\n      Template template = view.getComputeService().templateBuilder().build();\n\n      if (!client\n            .getTemplateApi()\n            .getTemplateInZone(template.getImage().getId(),\n                  template.getLocation().getId()).isPasswordEnabled()) {\n\n         // TODO: look at SecurityGroupApiLiveTest for how to do this\n         template.getOptions().as(CloudStackTemplateOptions.class).keyPair(keyPairName);\n      }\n      vm = adapter.createNodeWithGroupEncodedIntoName(group, name, template);\n\n      assertEquals(vm.getNode().getDisplayName(), name);\n      // check to see if we setup a NAT rule (conceding we could check this from\n      // cache)\n      IPForwardingRule rule = getFirst(\n         client.getNATApi().getIPForwardingRulesForVirtualMachine(vm.getNode().getId()), null);\n\n      String address = rule != null ? rule.getIPAddress() : vm.getNode().getIPAddress();\n\n      loginCredentials = prioritizeCredentialsFromTemplate.apply(template, vm.getCredentials());\n\n      assert InetAddresses.isInetAddress(address) : vm;\n      HostAndPort socket = HostAndPort.fromParts(address, 22);\n      checkSSH(socket);\n   }\n\n   @Test\n   public void testListHardwareProfiles() {\n      Iterable<ServiceOffering> profiles = adapter.listHardwareProfiles();\n      assertFalse(Iterables.isEmpty(profiles));\n\n      for (ServiceOffering profile : profiles) {\n         // TODO: check that the results are valid\n      }\n   }\n\n   @Test\n   public void testListImages() {\n      Iterable<org.jclouds.cloudstack.domain.Template> templates = adapter.listImages();\n      assertFalse(Iterables.isEmpty(templates));\n\n      for (org.jclouds.cloudstack.domain.Template template : templates) {\n         assert TemplatePredicates.isReady().apply(template) : template;\n      }\n   }\n\n   @AfterGroups(groups = \"live\")\n   @Override\n   protected void tearDownContext() {\n      if (vm != null)\n         adapter.destroyNode(vm.getNodeId());\n      super.tearDownContext();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/compute/CloudStackComputeServiceLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.compute;\n\nimport com.google.inject.Module;\nimport org.jclouds.compute.internal.BaseComputeServiceLiveTest;\nimport org.jclouds.sshj.config.SshjSshClientModule;\nimport org.testng.annotations.Test;\n\n/**\n * \n * Generally disabled, as it incurs higher fees.\n */\n@Test(groups = \"live\", enabled = true, singleThreaded = true)\npublic class CloudStackComputeServiceLiveTest extends BaseComputeServiceLiveTest {\n   public CloudStackComputeServiceLiveTest() {\n      provider = \"cloudstack\";\n   }\n\n   @Override\n   protected Module getSshModule() {\n      return new SshjSshClientModule();\n   }\n\n   @Override\n   public void testOptionToNotBlock() {\n      // start call blocks until we static nat, which is long enough to reach\n      // running state\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/compute/CloudStackExperimentLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.compute;\n\nimport org.jclouds.cloudstack.compute.options.CloudStackTemplateOptions;\nimport org.jclouds.cloudstack.domain.Network;\nimport org.jclouds.cloudstack.domain.TrafficType;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest;\nimport org.jclouds.cloudstack.options.ListNetworksOptions;\nimport org.jclouds.compute.RunNodesException;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.predicates.NodePredicates;\nimport org.testng.annotations.Test;\n\nimport java.net.URI;\nimport java.util.Set;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\n\nimport static com.google.common.collect.Iterables.concat;\nimport static com.google.common.collect.Iterables.get;\nimport static com.google.common.collect.Sets.newTreeSet;\nimport static org.jclouds.cloudstack.options.CreateNetworkOptions.Builder.vlan;\nimport static org.jclouds.cloudstack.options.ListNetworkOfferingsOptions.Builder.specifyVLAN;\n\n@Test(groups = \"live\", testName = \"CloudStackExperimentLiveTest\")\npublic class CloudStackExperimentLiveTest extends BaseCloudStackApiLiveTest {\n\n   public CloudStackExperimentLiveTest() {\n      provider = \"cloudstack\";\n   }\n\n   protected void deleteNetworksInZoneWithVlanId(String zoneId, String vlanId) {\n      Set<Network> networks = domainAdminClient.getNetworkApi().listNetworks(\n         ListNetworksOptions.Builder\n            .isDefault(false)\n            .isSystem(false)\n            .zoneId(zoneId)\n            .trafficType(TrafficType.GUEST)\n      );\n\n      // Warning: the vlan id is not set in the response - using an workaround\n      URI broadcastUri = URI.create(\"vlan://\" + vlanId);\n      for (Network net : networks) {\n         if (broadcastUri.equals(net.getBroadcastURI())) {\n            String jobId = domainAdminClient.getNetworkApi().deleteNetwork(net.getId());\n            adminJobComplete.apply(jobId);\n         }\n      }\n   }\n\n   @Test\n   public void testAndExperiment() {\n      if (!domainAdminEnabled) {\n         Logger.getAnonymousLogger().log(Level.SEVERE, \"domainAdmin credentials not present, skipping test\");\n         return;\n      }\n\n      String group = prefix + \"-vlan\";\n      String vlanId = \"2\";\n      Network network = null;\n      Set<? extends NodeMetadata> nodes = null;\n      try {\n         assert !view.getComputeService().listAssignableLocations().isEmpty();\n\n         Template template = view.getComputeService().templateBuilder().build();\n\n         // get the zone we are launching into\n         String zoneId = template.getLocation().getId();\n\n         // cleanup before running the test\n         deleteNetworksInZoneWithVlanId(zoneId, vlanId);\n\n         // find a network offering that supports vlans in our zone\n         String offeringId = get(\n            cloudStackContext.getApi().getOfferingApi().listNetworkOfferings(specifyVLAN(true).zoneId(zoneId)), 0).getId();\n\n         // create an arbitrary network\n         network = domainAdminClient\n            .getNetworkApi()\n               // startIP/endIP/netmask/gateway must be specified together\n            .createNetworkInZone(zoneId, offeringId, group, group,\n               vlan(vlanId).startIP(\"192.168.1.2\").netmask(\"255.255.255.0\").gateway(\"192.168.1.1\"));\n\n         // set options to specify this network id\n         template.getOptions().as(CloudStackTemplateOptions.class).networks(network.getId());\n\n         // launch the VM\n         nodes = view.getComputeService().createNodesInGroup(group, 1, template);\n\n         assert !nodes.isEmpty();\n\n      } catch (RunNodesException e) {\n         Logger.getAnonymousLogger().log(Level.SEVERE, \"error creating nodes\", e);\n         nodes = newTreeSet(concat(e.getSuccessfulNodes(), e.getNodeErrors().keySet()));\n      } finally {\n         if (nodes != null)\n            view.getComputeService().destroyNodesMatching(NodePredicates.inGroup(group));\n         if (network != null)\n            domainAdminClient.getNetworkApi().deleteNetwork(network.getId());\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/compute/extensions/CloudStackImageExtensionExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.compute.extensions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Map;\nimport java.util.Properties;\n\nimport org.jclouds.cloudstack.CloudStackContext;\nimport org.jclouds.cloudstack.internal.BaseCloudStackComputeServiceContextExpectTest;\nimport org.jclouds.compute.ComputeService;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.ImageTemplate;\nimport org.jclouds.compute.extensions.ImageExtension;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.util.concurrent.Futures;\nimport com.google.inject.Module;\n\n@Test(groups = \"unit\", testName = \"CloudStackImageExtensionExpectTest\")\npublic class CloudStackImageExtensionExpectTest extends BaseCloudStackComputeServiceContextExpectTest<ComputeService> {\n\n   @Override\n   protected Properties setupProperties() {\n      Properties overrides = super.setupProperties();\n      overrides.setProperty(\"jclouds.zones\", \"MTV-Zone1\");\n      return overrides;\n   }\n   \n   public void testCreateImage() {\n      HttpRequest listVM = HttpRequest.builder().method(\"GET\")\n         .endpoint(\"http://localhost:8080/client/api\")\n         .addQueryParam(\"response\", \"json\")\n         .addQueryParam(\"command\", \"listVirtualMachines\")\n         .addQueryParam(\"listAll\", \"true\")\n         .addQueryParam(\"id\", \"3239ade9-fd25-405c-8eda-59f0313a3fb0\")\n         .addQueryParam(\"apiKey\", \"APIKEY\")\n         .addQueryParam(\"signature\", \"Qq7Br3qNsyr5ifWZHIrLAslhwm0=\")\n         .addHeader(\"Accept\", \"application/json\")\n         .build();\n\n      HttpResponse listVMResponse = HttpResponse.builder().statusCode(200)\n         .payload(payloadFromResource(\"/listvirtualmachinesresponse-imageextension.json\"))\n         .build();\n\n      HttpRequest stopVM = HttpRequest.builder().method(\"GET\")\n         .endpoint(\"http://localhost:8080/client/api\")\n         .addQueryParam(\"response\", \"json\")\n         .addQueryParam(\"command\", \"stopVirtualMachine\")\n         .addQueryParam(\"id\", \"3239ade9-fd25-405c-8eda-59f0313a3fb0\")\n         .addQueryParam(\"apiKey\", \"APIKEY\")\n         .addQueryParam(\"signature\", \"y9vxRK61K8sDoWtvSJHIx5WO9AE=\")\n         .addHeader(\"Accept\", \"application/json\")\n         .build();\n\n      HttpResponse stopVMResponse = HttpResponse.builder().statusCode(200)\n         .payload(payloadFromResource(\"/stopvirtualmachineresponse-imageextension.json\"))\n         .build();\n\n      HttpRequest stopAsyncJobResult = HttpRequest.builder().method(\"GET\")\n         .endpoint(\"http://localhost:8080/client/api\")\n         .addQueryParam(\"response\", \"json\")\n         .addQueryParam(\"command\", \"queryAsyncJobResult\")\n         .addQueryParam(\"jobid\", \"a7d5127b-24a2-4a44-a4a7-25a6d057b453\")\n         .addQueryParam(\"apiKey\", \"APIKEY\")\n         .addQueryParam(\"signature\", \"CVpnN/Sbx/MCOOyj/oVAt3bn684=\")\n         .addHeader(\"Accept\", \"application/json\")\n         .build();\n\n      HttpResponse stopAsyncJobResultResponse = HttpResponse.builder().statusCode(200)\n         .payload(payloadFromResource(\"/queryasyncjobresultresponse-stopvirtualmachine-imageextension.json\"))\n         .build();\n\n      HttpRequest listVolumes = HttpRequest.builder().method(\"GET\")\n         .endpoint(\"http://localhost:8080/client/api\")\n         .addQueryParam(\"response\", \"json\")\n         .addQueryParam(\"command\", \"listVolumes\")\n         .addQueryParam(\"listAll\", \"true\")\n         .addQueryParam(\"virtualmachineid\", \"3239ade9-fd25-405c-8eda-59f0313a3fb0\")\n         .addQueryParam(\"apiKey\", \"APIKEY\")\n         .addQueryParam(\"signature\", \"drLPf9NE9ROZPOfeDkASiKa50t8=\")\n         .addHeader(\"Accept\", \"application/json\")\n         .build();\n\n      HttpResponse listVolumesResponse = HttpResponse.builder().statusCode(200)\n         .payload(payloadFromResource(\"/listvolumesresponse-imageextension.json\"))\n         .build();\n\n\n      HttpRequest createTemplate = HttpRequest.builder().method(\"GET\")\n         .endpoint(\"http://localhost:8080/client/api\")\n         .addQueryParam(\"response\", \"json\")\n         .addQueryParam(\"command\", \"createTemplate\")\n         .addQueryParam(\"volumeid\", \"fe1ada16-57a0-40ae-b577-01a153690fb4\")\n         .addQueryParam(\"name\", \"temp-template-ignore\")\n         .addQueryParam(\"ostypeid\", \"45de18f1-87c6-4646-8099-95c61f2a300a\")\n         .addQueryParam(\"displaytext\", \"temp-template-ignore\")\n         .addQueryParam(\"apiKey\", \"APIKEY\")\n         .addQueryParam(\"signature\", \"madHsBgxjYbM6JnZKYWajOlfPlY=\")\n         .addHeader(\"Accept\", \"application/json\")\n         .build();\n\n      HttpResponse createTemplateResponse = HttpResponse.builder().statusCode(200)\n         .payload(payloadFromResource(\"/createtemplateresponse-imageextension.json\"))\n         .build();\n\n      HttpRequest createAsyncJobResult = HttpRequest.builder().method(\"GET\")\n         .endpoint(\"http://localhost:8080/client/api\")\n         .addQueryParam(\"response\", \"json\")\n         .addQueryParam(\"command\", \"queryAsyncJobResult\")\n         .addQueryParam(\"jobid\", \"4e345230-8fcc-48a3-8a37-c5fe960df671\")\n         .addQueryParam(\"apiKey\", \"APIKEY\")\n         .addQueryParam(\"signature\", \"6mTKL9fjz7bn6C7tOaZBzKdZwHs=\")\n         .addHeader(\"Accept\", \"application/json\")\n         .build();\n\n      HttpResponse createAsyncJobResultResponse = HttpResponse.builder().statusCode(200)\n         .payload(payloadFromResource(\"/queryasyncjobresultresponse-createtemplate-imageextension.json\"))\n         .build();\n\n      HttpRequest getTemplate = HttpRequest.builder().method(\"GET\")\n         .endpoint(\"http://localhost:8080/client/api\")\n         .addQueryParam(\"response\", \"json\")\n         .addQueryParam(\"command\", \"listTemplates\")\n         .addQueryParam(\"listAll\", \"true\")\n         .addQueryParam(\"templatefilter\", \"executable\")\n         .addQueryParam(\"id\", \"3dc6ce25-a6cf-4d60-a664-3499993b511b\")\n         .addQueryParam(\"apiKey\", \"APIKEY\")\n         .addQueryParam(\"signature\", \"dXv+l04EDd7hmrWv5CdW8v298RE=\")\n         .addHeader(\"Accept\", \"application/json\")\n         .build();\n\n      HttpResponse getTemplateResponse = HttpResponse.builder().statusCode(200)\n         .payload(payloadFromResource(\"/listtemplatesresponse-imageextension.json\"))\n         .build();\n\n      Map<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder()\n            .put(listTemplates, listTemplatesResponse)\n            .put(listOsTypes, listOsTypesResponse)\n            .put(listOsCategories, listOsCategoriesResponse)\n            .put(listZones, listZonesResponse)\n            .put(listServiceOfferings, listServiceOfferingsResponse)\n            .put(listAccounts, listAccountsResponse)\n            .put(listNetworks, listNetworksResponse)\n            .put(getZone, getZoneResponse)\n            .put(listVM, listVMResponse)\n            .put(stopVM, stopVMResponse)\n            .put(stopAsyncJobResult, stopAsyncJobResultResponse)\n            .put(listVolumes, listVolumesResponse)\n            .put(createTemplate, createTemplateResponse)\n            .put(createAsyncJobResult, createAsyncJobResultResponse)\n            .put(getTemplate, getTemplateResponse)\n            .build();\n\n      ImageExtension apiThatCreatesImage = requestsSendResponses(requestResponseMap).getImageExtension().get();\n      \n      ImageTemplate newImageTemplate = apiThatCreatesImage.buildImageTemplateFromNode(\"temp-template-ignore\", \"3239ade9-fd25-405c-8eda-59f0313a3fb0\");\n      \n      Image image = Futures.getUnchecked(apiThatCreatesImage.createImage(newImageTemplate));\n      assertEquals(image.getId(), \"3dc6ce25-a6cf-4d60-a664-3499993b511b\");\n   }\n\n   @Override\n   public ComputeService createClient(Function<HttpRequest, HttpResponse> fn, Module module, Properties props) {\n      return clientFrom(createInjector(fn, module, props).getInstance(CloudStackContext.class));\n   }\n\n   @Override\n   protected ComputeService clientFrom(CloudStackContext context) {\n      return context.getComputeService();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/compute/extensions/CloudStackImageExtensionLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.compute.extensions;\n\nimport org.jclouds.compute.extensions.internal.BaseImageExtensionLiveTest;\nimport org.jclouds.sshj.config.SshjSshClientModule;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Module;\n\n/**\n * Live test for CloudStack {@link ImageExtension} implementation.\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"CloudStackImageExtensionLiveTest\")\npublic class CloudStackImageExtensionLiveTest extends BaseImageExtensionLiveTest {\n\n   public CloudStackImageExtensionLiveTest() {\n      provider = \"cloudstack\";\n   }\n\n   @Override\n   protected Module getSshModule() {\n      return new SshjSshClientModule();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/compute/extensions/CloudStackSecurityGroupExtensionExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.compute.extensions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.CloudStackContext;\nimport org.jclouds.cloudstack.compute.functions.ZoneToLocationTest;\nimport org.jclouds.cloudstack.internal.BaseCloudStackComputeServiceContextExpectTest;\nimport org.jclouds.compute.ComputeService;\nimport org.jclouds.compute.domain.SecurityGroup;\nimport org.jclouds.compute.domain.SecurityGroupBuilder;\nimport org.jclouds.compute.extensions.SecurityGroupExtension;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.net.domain.IpPermission;\nimport org.jclouds.net.domain.IpProtocol;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.LinkedHashMultimap;\nimport com.google.common.collect.Multimap;\nimport com.google.common.collect.Sets;\nimport com.google.common.util.concurrent.UncheckedExecutionException;\nimport com.google.inject.Module;\n\n@Test(groups = \"unit\", testName = \"CloudStackSecurityGroupExtensionExpectTest\")\npublic class CloudStackSecurityGroupExtensionExpectTest extends BaseCloudStackComputeServiceContextExpectTest<ComputeService> {\n\n   protected final HttpResponse addRuleResponse = HttpResponse.builder().statusCode(200)\n           .payload(payloadFromResource(\"/authorizesecuritygroupingressresponse.json\"))\n           .build();\n\n   protected final HttpResponse revokeRuleResponse = HttpResponse.builder().statusCode(200)\n           .payload(payloadFromResource(\"/revokesecuritygroupingressresponse.json\"))\n           .build();\n\n   protected final HttpRequest queryAsyncJobResultAuthorizeIngress = HttpRequest.builder().method(\"GET\")\n           .endpoint(\"http://localhost:8080/client/api\")\n           .addQueryParam(\"response\", \"json\")\n           .addQueryParam(\"command\", \"queryAsyncJobResult\")\n           .addQueryParam(\"jobid\", \"13330fc9-8b3e-4582-aa3e-90883c041010\")\n           .addQueryParam(\"apiKey\", \"APIKEY\")\n           .addQueryParam(\"signature\", \"y4gk3ckWAMPDNZM26LUK0gAhfiE=\")\n           .addHeader(\"Accept\", \"application/json\")\n           .build();\n\n   protected final HttpResponse queryAsyncJobResultAuthorizeIngressResponse = HttpResponse.builder().statusCode(200)\n           .payload(payloadFromResource(\"/queryasyncjobresultresponse-authorizeingress.json\"))\n           .build();\n\n   protected final HttpRequest getWithRule = HttpRequest.builder().method(\"GET\")\n           .endpoint(\"http://localhost:8080/client/api\")\n           .addQueryParam(\"response\", \"json\")\n           .addQueryParam(\"command\", \"listSecurityGroups\")\n           .addQueryParam(\"listAll\", \"true\")\n           .addQueryParam(\"id\", \"13\")\n           .addQueryParam(\"apiKey\", \"APIKEY\")\n           .addQueryParam(\"signature\", \"TmlGaO2ICM+iXQr88+ZCyWUniSw=\")\n           .addHeader(\"Accept\", \"application/json\")\n           .build();\n\n   protected final HttpResponse getEmptyResponse = HttpResponse.builder().statusCode(200)\n           .payload(payloadFromResource(\"/getsecuritygroupresponse_extension_byid_empty.json\"))\n           .build();\n\n   @Override\n   protected Properties setupProperties() {\n      Properties overrides = super.setupProperties();\n      overrides.setProperty(\"jclouds.zones\", \"MTV-Zone1\");\n      return overrides;\n   }\n\n   public void testListSecurityGroups() {\n      HttpRequest listSecurityGroups = HttpRequest.builder().method(\"GET\")\n              .endpoint(\"http://localhost:8080/client/api\")\n              .addQueryParam(\"response\", \"json\")\n              .addQueryParam(\"command\", \"listSecurityGroups\")\n              .addQueryParam(\"listAll\", \"true\")\n              .addQueryParam(\"apiKey\", \"APIKEY\")\n              .addQueryParam(\"signature\", \"o+d8xxWT1Pa+I57SG2caFAblBYA=\")\n              .addHeader(\"Accept\", \"application/json\")\n              .build();\n\n      HttpResponse listSecurityGroupsResponse = HttpResponse.builder().statusCode(200)\n              .payload(payloadFromResource(\"/listsecuritygroupsresponse.json\"))\n              .build();\n\n      Map<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder()\n              .put(listTemplates, listTemplatesResponse)\n              .put(listOsTypes, listOsTypesResponse)\n              .put(listOsCategories, listOsCategoriesResponse)\n              .put(listZones, listZonesResponse)\n              .put(listServiceOfferings, listServiceOfferingsResponse)\n              .put(listAccounts, listAccountsResponse)\n              .put(listNetworks, listNetworksResponse)\n              .put(getZone, getZoneResponse)\n              .put(listSecurityGroups, listSecurityGroupsResponse)\n              .build();\n\n      SecurityGroupExtension extension = requestsSendResponses(requestResponseMap).getSecurityGroupExtension().get();\n\n      Set<SecurityGroup> groups = extension.listSecurityGroups();\n      assertEquals(groups.size(), 5);\n   }\n\n   public void testListSecurityGroupsForNode() {\n      HttpRequest listSecurityGroups = HttpRequest.builder().method(\"GET\")\n              .endpoint(\"http://localhost:8080/client/api\")\n              .addQueryParam(\"response\", \"json\")\n              .addQueryParam(\"command\", \"listSecurityGroups\")\n              .addQueryParam(\"listAll\", \"true\")\n              .addQueryParam(\"virtualmachineid\", \"some-node\")\n              .addQueryParam(\"apiKey\", \"APIKEY\")\n              .addQueryParam(\"signature\", \"x4f9fGMjIHXl5biaaFK5oOEONcg=\")\n              .addHeader(\"Accept\", \"application/json\")\n              .build();\n\n      HttpResponse listSecurityGroupsResponse = HttpResponse.builder().statusCode(200)\n              .payload(payloadFromResource(\"/listsecuritygroupsresponse.json\"))\n              .build();\n\n      Map<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder()\n              .put(listTemplates, listTemplatesResponse)\n              .put(listOsTypes, listOsTypesResponse)\n              .put(listOsCategories, listOsCategoriesResponse)\n              .put(listZones, listZonesResponse)\n              .put(listServiceOfferings, listServiceOfferingsResponse)\n              .put(listAccounts, listAccountsResponse)\n              .put(listNetworks, listNetworksResponse)\n              .put(getZone, getZoneResponse)\n              .put(listSecurityGroups, listSecurityGroupsResponse)\n              .build();\n\n      SecurityGroupExtension extension = requestsSendResponses(requestResponseMap).getSecurityGroupExtension().get();\n\n      Set<SecurityGroup> groups = extension.listSecurityGroupsForNode(\"some-node\");\n      assertEquals(groups.size(), 5);\n   }\n\n   public void testGetSecurityGroupById() {\n      HttpRequest listSecurityGroups = HttpRequest.builder().method(\"GET\")\n              .endpoint(\"http://localhost:8080/client/api\")\n              .addQueryParam(\"response\", \"json\")\n              .addQueryParam(\"command\", \"listSecurityGroups\")\n              .addQueryParam(\"listAll\", \"true\")\n              .addQueryParam(\"id\", \"13\")\n              .addQueryParam(\"apiKey\", \"APIKEY\")\n              .addQueryParam(\"signature\", \"TmlGaO2ICM+iXQr88+ZCyWUniSw=\")\n              .addHeader(\"Accept\", \"application/json\")\n              .build();\n\n      HttpResponse listSecurityGroupsResponse = HttpResponse.builder().statusCode(200)\n              .payload(payloadFromResource(\"/getsecuritygroupresponse_extension_byid.json\"))\n              .build();\n\n      Map<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder()\n              .put(listTemplates, listTemplatesResponse)\n              .put(listOsTypes, listOsTypesResponse)\n              .put(listOsCategories, listOsCategoriesResponse)\n              .put(listZones, listZonesResponse)\n              .put(listServiceOfferings, listServiceOfferingsResponse)\n              .put(listAccounts, listAccountsResponse)\n              .put(listNetworks, listNetworksResponse)\n              .put(getZone, getZoneResponse)\n              .put(listSecurityGroups, listSecurityGroupsResponse)\n              .build();\n\n      SecurityGroupExtension extension = requestsSendResponses(requestResponseMap).getSecurityGroupExtension().get();\n\n      SecurityGroup group = extension.getSecurityGroupById(\"13\");\n      assertEquals(group.getId(), \"13\");\n      assertEquals(group.getIpPermissions().size(), 2);\n   }\n\n   public void testCreateSecurityGroup() {\n      HttpRequest listSecurityGroups = HttpRequest.builder().method(\"GET\")\n              .endpoint(\"http://localhost:8080/client/api\")\n              .addQueryParam(\"response\", \"json\")\n              .addQueryParam(\"command\", \"listSecurityGroups\")\n              .addQueryParam(\"listAll\", \"true\")\n              .addQueryParam(\"securitygroupname\", \"jclouds-test\")\n              .addQueryParam(\"apiKey\", \"APIKEY\")\n              .addQueryParam(\"signature\", \"zGp2rfHY6fBIGkgODRxyNzFfPFI=\")\n              .addHeader(\"Accept\", \"application/json\")\n              .build();\n\n      HttpResponse listSecurityGroupsResponse = HttpResponse.builder().statusCode(200)\n              .payload(payloadFromResource(\"/getsecuritygroupresponse.json\"))\n              .build();\n\n      Map<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder()\n              .put(listTemplates, listTemplatesResponse)\n              .put(listOsTypes, listOsTypesResponse)\n              .put(listOsCategories, listOsCategoriesResponse)\n              .put(listZones, listZonesResponse)\n              .put(listServiceOfferings, listServiceOfferingsResponse)\n              .put(listAccounts, listAccountsResponse)\n              .put(listNetworks, listNetworksResponse)\n              .put(getZoneWithSecurityGroups, getZoneWithSecurityGroupsResponse)\n              .put(listSecurityGroups, listSecurityGroupsResponse)\n              .put(createSecurityGroup, createSecurityGroupResponse)\n              .build();\n\n      SecurityGroupExtension extension = requestsSendResponses(requestResponseMap).getSecurityGroupExtension().get();\n\n      SecurityGroup group = extension.createSecurityGroup(\"test\", ZoneToLocationTest.two);\n      assertEquals(group.getId(), \"30\");\n      assertEquals(group.getIpPermissions().size(), 0);\n   }\n\n   @Test(expectedExceptions = UncheckedExecutionException.class,\n           expectedExceptionsMessageRegExp = \"java.lang.IllegalArgumentException: .* does not support security groups\")\n   public void testCreateSecurityGroupBadZone() {\n      HttpRequest listSecurityGroups = HttpRequest.builder().method(\"GET\")\n              .endpoint(\"http://localhost:8080/client/api\")\n              .addQueryParam(\"response\", \"json\")\n              .addQueryParam(\"command\", \"listSecurityGroups\")\n              .addQueryParam(\"listAll\", \"true\")\n              .addQueryParam(\"securitygroupname\", \"jclouds-test\")\n              .addQueryParam(\"apiKey\", \"APIKEY\")\n              .addQueryParam(\"signature\", \"zGp2rfHY6fBIGkgODRxyNzFfPFI=\")\n              .addHeader(\"Accept\", \"application/json\")\n              .build();\n\n      HttpResponse listSecurityGroupsResponse = HttpResponse.builder().statusCode(200)\n              .payload(payloadFromResource(\"/getsecuritygroupresponse.json\"))\n              .build();\n\n      Map<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder()\n              .put(listTemplates, listTemplatesResponse)\n              .put(listOsTypes, listOsTypesResponse)\n              .put(listOsCategories, listOsCategoriesResponse)\n              .put(listZones, listZonesResponse)\n              .put(listServiceOfferings, listServiceOfferingsResponse)\n              .put(listAccounts, listAccountsResponse)\n              .put(listNetworks, listNetworksResponse)\n              .put(getZone, getZoneResponse)\n              .put(listSecurityGroups, listSecurityGroupsResponse)\n              .put(createSecurityGroup, createSecurityGroupResponse)\n              .build();\n\n      SecurityGroupExtension extension = requestsSendResponses(requestResponseMap).getSecurityGroupExtension().get();\n\n      SecurityGroup group = extension.createSecurityGroup(\"test\", ZoneToLocationTest.one);\n      assertEquals(group.getId(), \"30\");\n      assertEquals(group.getIpPermissions().size(), 0);\n   }\n\n   public void testRemoveSecurityGroup() {\n      HttpRequest listSecurityGroups = HttpRequest.builder().method(\"GET\")\n              .endpoint(\"http://localhost:8080/client/api\")\n              .addQueryParam(\"response\", \"json\")\n              .addQueryParam(\"command\", \"listSecurityGroups\")\n              .addQueryParam(\"listAll\", \"true\")\n              .addQueryParam(\"id\", \"13\")\n              .addQueryParam(\"apiKey\", \"APIKEY\")\n              .addQueryParam(\"signature\", \"TmlGaO2ICM+iXQr88+ZCyWUniSw=\")\n              .addHeader(\"Accept\", \"application/json\")\n              .build();\n\n      HttpResponse listSecurityGroupsResponse = HttpResponse.builder().statusCode(200)\n              .payload(payloadFromResource(\"/getsecuritygroupresponse_extension_byid_empty.json\"))\n              .build();\n\n      HttpRequest deleteSecurityGroup = HttpRequest.builder().method(\"GET\")\n              .endpoint(\"http://localhost:8080/client/api\")\n              .addQueryParam(\"response\", \"json\")\n              .addQueryParam(\"command\", \"deleteSecurityGroup\")\n              .addQueryParam(\"id\", \"13\")\n              .addQueryParam(\"apiKey\", \"APIKEY\")\n              .addQueryParam(\"signature\", \"S1A2lYR/ibf4+HGFxVLdZvXZujQ=\")\n              .addHeader(\"Accept\", \"application/json\")\n              .build();\n\n      HttpResponse deleteSecurityGroupResponse = HttpResponse.builder()\n              .statusCode(200)\n              .payload(payloadFromResource(\"/deletesecuritygroupresponse.json\"))\n              .build();\n\n      Map<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder()\n              .put(listTemplates, listTemplatesResponse)\n              .put(listOsTypes, listOsTypesResponse)\n              .put(listOsCategories, listOsCategoriesResponse)\n              .put(listZones, listZonesResponse)\n              .put(listServiceOfferings, listServiceOfferingsResponse)\n              .put(listAccounts, listAccountsResponse)\n              .put(listNetworks, listNetworksResponse)\n              .put(listSecurityGroups, listSecurityGroupsResponse)\n              .put(deleteSecurityGroup, deleteSecurityGroupResponse)\n              .build();\n\n      SecurityGroupExtension extension = requestsSendResponses(requestResponseMap).getSecurityGroupExtension().get();\n\n      assertTrue(extension.removeSecurityGroup(\"13\"), \"Did not remove security group\");\n   }\n\n   public void testRemoveSecurityGroupDoesNotExist() {\n      HttpRequest listSecurityGroups = HttpRequest.builder().method(\"GET\")\n              .endpoint(\"http://localhost:8080/client/api\")\n              .addQueryParam(\"response\", \"json\")\n              .addQueryParam(\"command\", \"listSecurityGroups\")\n              .addQueryParam(\"listAll\", \"true\")\n              .addQueryParam(\"id\", \"14\")\n              .addQueryParam(\"apiKey\", \"APIKEY\")\n              .addQueryParam(\"signature\", \"pWQ30A6l5qh4eaNypGwM9FoLnUM=\")\n              .addHeader(\"Accept\", \"application/json\")\n              .build();\n\n      HttpResponse listSecurityGroupsResponse = HttpResponse.builder().statusCode(200)\n              .payload(payloadFromResource(\"/getsecuritygroupresponse.json\"))\n              .build();\n\n      Map<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder()\n              .put(listTemplates, listTemplatesResponse)\n              .put(listOsTypes, listOsTypesResponse)\n              .put(listOsCategories, listOsCategoriesResponse)\n              .put(listZones, listZonesResponse)\n              .put(listServiceOfferings, listServiceOfferingsResponse)\n              .put(listAccounts, listAccountsResponse)\n              .put(listNetworks, listNetworksResponse)\n              .put(listSecurityGroups, listSecurityGroupsResponse)\n              .build();\n\n      SecurityGroupExtension extension = requestsSendResponses(requestResponseMap).getSecurityGroupExtension().get();\n\n      assertFalse(extension.removeSecurityGroup(\"14\"), \"Should not have found security group to remove\");\n   }\n\n   public void testAddIpPermissionCidrFromIpPermission() {\n      HttpRequest addRule = HttpRequest.builder().method(\"GET\")\n              .endpoint(\"http://localhost:8080/client/api\")\n              .addQueryParam(\"response\", \"json\")\n              .addQueryParam(\"command\", \"authorizeSecurityGroupIngress\")\n              .addQueryParam(\"securitygroupid\", \"13\")\n              .addQueryParam(\"protocol\", \"UDP\")\n              .addQueryParam(\"startport\", \"11\")\n              .addQueryParam(\"endport\", \"11\")\n              .addQueryParam(\"cidrlist\", \"1.1.1.1/24\")\n              .addQueryParam(\"apiKey\", \"APIKEY\")\n              .addQueryParam(\"signature\", \"XyokGNutHwcyU7KQVFZOTHvc4RY=\")\n              .addHeader(\"Accept\", \"application/json\")\n              .build();\n\n      HttpResponse getWithRuleResponse = HttpResponse.builder().statusCode(200)\n              .payload(payloadFromResource(\"/getsecuritygroupresponse_extension_byid_with_cidr.json\"))\n              .build();\n\n      SecurityGroupExtension extension = orderedRequestsSendResponses(\n              ImmutableList.of(addRule, queryAsyncJobResultAuthorizeIngress, getWithRule),\n              ImmutableList.of(addRuleResponse, queryAsyncJobResultAuthorizeIngressResponse, getWithRuleResponse)\n      ).getSecurityGroupExtension().get();\n\n      IpPermission.Builder builder = IpPermission.builder();\n\n      builder.ipProtocol(IpProtocol.UDP);\n      builder.fromPort(11);\n      builder.toPort(11);\n      builder.cidrBlock(\"1.1.1.1/24\");\n\n      IpPermission perm = builder.build();\n\n      SecurityGroup origGroup = new SecurityGroupBuilder().id(\"13\").build();\n\n      SecurityGroup newGroup = extension.addIpPermission(perm, origGroup);\n\n      assertEquals(1, newGroup.getIpPermissions().size());\n\n      IpPermission newPerm = Iterables.getOnlyElement(newGroup.getIpPermissions());\n\n      assertNotNull(newPerm);\n      assertEquals(newPerm.getIpProtocol(), IpProtocol.UDP);\n      assertEquals(newPerm.getFromPort(), 11);\n      assertEquals(newPerm.getToPort(), 11);\n      assertEquals(newPerm.getCidrBlocks().size(), 1);\n      assertTrue(newPerm.getCidrBlocks().contains(\"1.1.1.1/24\"));\n   }\n\n   public void testAddIpPermissionCidrFromParams() {\n      HttpRequest addRule = HttpRequest.builder().method(\"GET\")\n              .endpoint(\"http://localhost:8080/client/api\")\n              .addQueryParam(\"response\", \"json\")\n              .addQueryParam(\"command\", \"authorizeSecurityGroupIngress\")\n              .addQueryParam(\"securitygroupid\", \"13\")\n              .addQueryParam(\"protocol\", \"UDP\")\n              .addQueryParam(\"startport\", \"11\")\n              .addQueryParam(\"endport\", \"11\")\n              .addQueryParam(\"cidrlist\", \"1.1.1.1/24\")\n              .addQueryParam(\"apiKey\", \"APIKEY\")\n              .addQueryParam(\"signature\", \"XyokGNutHwcyU7KQVFZOTHvc4RY=\")\n              .addHeader(\"Accept\", \"application/json\")\n              .build();\n\n      HttpResponse getWithRuleResponse = HttpResponse.builder().statusCode(200)\n              .payload(payloadFromResource(\"/getsecuritygroupresponse_extension_byid_with_cidr.json\"))\n              .build();\n\n      SecurityGroupExtension extension = orderedRequestsSendResponses(\n              ImmutableList.of(addRule, queryAsyncJobResultAuthorizeIngress, getWithRule),\n              ImmutableList.of(addRuleResponse, queryAsyncJobResultAuthorizeIngressResponse, getWithRuleResponse)\n      ).getSecurityGroupExtension().get();\n\n      SecurityGroup origGroup = new SecurityGroupBuilder().id(\"13\").build();\n\n      SecurityGroup newGroup = extension.addIpPermission(IpProtocol.UDP, 11, 11, emptyMultimap(),\n              ImmutableSet.of(\"1.1.1.1/24\"), emptyStringSet(), origGroup);\n\n      assertEquals(1, newGroup.getIpPermissions().size());\n\n      IpPermission newPerm = Iterables.getOnlyElement(newGroup.getIpPermissions());\n\n      assertNotNull(newPerm);\n      assertEquals(newPerm.getIpProtocol(), IpProtocol.UDP);\n      assertEquals(newPerm.getFromPort(), 11);\n      assertEquals(newPerm.getToPort(), 11);\n      assertEquals(newPerm.getCidrBlocks().size(), 1);\n      assertTrue(newPerm.getCidrBlocks().contains(\"1.1.1.1/24\"));\n   }\n\n   public void testAddIpPermissionGroupFromIpPermission() {\n      HttpRequest addRule = HttpRequest.builder().method(\"GET\")\n              .endpoint(\"http://localhost:8080/client/api\")\n              .addQueryParam(\"response\", \"json\")\n              .addQueryParam(\"command\", \"authorizeSecurityGroupIngress\")\n              .addQueryParam(\"securitygroupid\", \"13\")\n              .addQueryParam(\"protocol\", \"TCP\")\n              .addQueryParam(\"startport\", \"22\")\n              .addQueryParam(\"endport\", \"22\")\n              .addQueryParam(\"usersecuritygrouplist[0].account\", \"adrian\")\n              .addQueryParam(\"usersecuritygrouplist[0].group\", \"adriancole\")\n              .addQueryParam(\"apiKey\", \"APIKEY\")\n              .addQueryParam(\"signature\", \"v2OgKc2IftwX9pfKq2Pw/Z2xh9w=\")\n              .addHeader(\"Accept\", \"application/json\")\n              .build();\n\n\n      HttpResponse getWithRuleResponse = HttpResponse.builder().statusCode(200)\n              .payload(payloadFromResource(\"/getsecuritygroupresponse_extension_byid_with_group.json\"))\n              .build();\n\n      SecurityGroupExtension extension = orderedRequestsSendResponses(\n              ImmutableList.of(addRule, queryAsyncJobResultAuthorizeIngress, getWithRule),\n              ImmutableList.of(addRuleResponse, queryAsyncJobResultAuthorizeIngressResponse, getWithRuleResponse)\n      ).getSecurityGroupExtension().get();\n\n      IpPermission.Builder builder = IpPermission.builder();\n\n      builder.ipProtocol(IpProtocol.TCP);\n      builder.fromPort(22);\n      builder.toPort(22);\n      builder.tenantIdGroupNamePair(\"adrian\", \"adriancole\");\n\n      IpPermission perm = builder.build();\n\n      SecurityGroup origGroup = new SecurityGroupBuilder().id(\"13\").build();\n\n      SecurityGroup newGroup = extension.addIpPermission(perm, origGroup);\n\n      assertEquals(1, newGroup.getIpPermissions().size());\n\n      IpPermission newPerm = Iterables.getOnlyElement(newGroup.getIpPermissions());\n\n      assertNotNull(newPerm);\n      assertEquals(newPerm.getIpProtocol(), IpProtocol.TCP);\n      assertEquals(newPerm.getFromPort(), 22);\n      assertEquals(newPerm.getToPort(), 22);\n      assertEquals(newPerm.getCidrBlocks().size(), 0);\n      assertEquals(newPerm.getTenantIdGroupNamePairs().size(), 1);\n      assertTrue(newPerm.getTenantIdGroupNamePairs().containsEntry(\"adrian\", \"adriancole\"));\n   }\n\n   public void testAddIpPermissionGroupFromParams() {\n      HttpRequest addRule = HttpRequest.builder().method(\"GET\")\n              .endpoint(\"http://localhost:8080/client/api\")\n              .addQueryParam(\"response\", \"json\")\n              .addQueryParam(\"command\", \"authorizeSecurityGroupIngress\")\n              .addQueryParam(\"securitygroupid\", \"13\")\n              .addQueryParam(\"protocol\", \"TCP\")\n              .addQueryParam(\"startport\", \"22\")\n              .addQueryParam(\"endport\", \"22\")\n              .addQueryParam(\"usersecuritygrouplist[0].account\", \"adrian\")\n              .addQueryParam(\"usersecuritygrouplist[0].group\", \"adriancole\")\n              .addQueryParam(\"apiKey\", \"APIKEY\")\n              .addQueryParam(\"signature\", \"v2OgKc2IftwX9pfKq2Pw/Z2xh9w=\")\n              .addHeader(\"Accept\", \"application/json\")\n              .build();\n\n\n      HttpResponse getWithRuleResponse = HttpResponse.builder().statusCode(200)\n              .payload(payloadFromResource(\"/getsecuritygroupresponse_extension_byid_with_group.json\"))\n              .build();\n\n      SecurityGroupExtension extension = orderedRequestsSendResponses(\n              ImmutableList.of(addRule, queryAsyncJobResultAuthorizeIngress, getWithRule),\n              ImmutableList.of(addRuleResponse, queryAsyncJobResultAuthorizeIngressResponse, getWithRuleResponse)\n      ).getSecurityGroupExtension().get();\n\n      ImmutableMultimap.Builder<String, String> permBuilder = ImmutableMultimap.builder();\n      permBuilder.put(\"adrian\", \"adriancole\");\n\n      SecurityGroup origGroup = new SecurityGroupBuilder().id(\"13\").build();\n\n      SecurityGroup newGroup = extension.addIpPermission(IpProtocol.TCP, 22, 22,\n              permBuilder.build(), emptyStringSet(), emptyStringSet(), origGroup);\n\n      assertEquals(1, newGroup.getIpPermissions().size());\n\n      IpPermission newPerm = Iterables.getOnlyElement(newGroup.getIpPermissions());\n\n      assertNotNull(newPerm);\n      assertEquals(newPerm.getIpProtocol(), IpProtocol.TCP);\n      assertEquals(newPerm.getFromPort(), 22);\n      assertEquals(newPerm.getToPort(), 22);\n      assertEquals(newPerm.getCidrBlocks().size(), 0);\n      assertEquals(newPerm.getTenantIdGroupNamePairs().size(), 1);\n      assertTrue(newPerm.getTenantIdGroupNamePairs().containsEntry(\"adrian\", \"adriancole\"));\n   }\n\n   public void testRemoveIpPermissionCidrFromIpPermission() {\n      HttpRequest revokeRule = HttpRequest.builder().method(\"GET\")\n              .endpoint(\"http://localhost:8080/client/api\")\n              .addQueryParam(\"response\", \"json\")\n              .addQueryParam(\"command\", \"revokeSecurityGroupIngress\")\n              .addQueryParam(\"id\", \"6\")\n              .addQueryParam(\"apiKey\", \"APIKEY\")\n              .addQueryParam(\"signature\", \"H7cY/MEYGN7df1hiz0mMAFVBfa8=\")\n              .addHeader(\"Accept\", \"application/json\")\n              .build();\n\n      HttpResponse getWithRuleResponse = HttpResponse.builder().statusCode(200)\n              .payload(payloadFromResource(\"/getsecuritygroupresponse_extension_byid_with_cidr.json\"))\n              .build();\n\n      SecurityGroupExtension extension = orderedRequestsSendResponses(\n              ImmutableList.of(getWithRule, revokeRule, queryAsyncJobResultAuthorizeIngress, getWithRule),\n              ImmutableList.of(getWithRuleResponse, revokeRuleResponse,\n                      queryAsyncJobResultAuthorizeIngressResponse, getEmptyResponse)\n      ).getSecurityGroupExtension().get();\n\n      IpPermission.Builder builder = IpPermission.builder();\n\n      builder.ipProtocol(IpProtocol.UDP);\n      builder.fromPort(11);\n      builder.toPort(11);\n      builder.cidrBlock(\"1.1.1.1/24\");\n\n      IpPermission perm = builder.build();\n\n      SecurityGroup origGroup = new SecurityGroupBuilder().id(\"13\").build();\n\n      SecurityGroup newGroup = extension.removeIpPermission(perm, origGroup);\n\n      assertEquals(newGroup.getIpPermissions().size(), 0);\n   }\n\n   public void testRemoveIpPermissionCidrFromParams() {\n      HttpRequest revokeRule = HttpRequest.builder().method(\"GET\")\n              .endpoint(\"http://localhost:8080/client/api\")\n              .addQueryParam(\"response\", \"json\")\n              .addQueryParam(\"command\", \"revokeSecurityGroupIngress\")\n              .addQueryParam(\"id\", \"6\")\n              .addQueryParam(\"apiKey\", \"APIKEY\")\n              .addQueryParam(\"signature\", \"H7cY/MEYGN7df1hiz0mMAFVBfa8=\")\n              .addHeader(\"Accept\", \"application/json\")\n              .build();\n\n      HttpResponse getWithRuleResponse = HttpResponse.builder().statusCode(200)\n              .payload(payloadFromResource(\"/getsecuritygroupresponse_extension_byid_with_cidr.json\"))\n              .build();\n\n      SecurityGroupExtension extension = orderedRequestsSendResponses(\n              ImmutableList.of(getWithRule, revokeRule, queryAsyncJobResultAuthorizeIngress, getWithRule),\n              ImmutableList.of(getWithRuleResponse, revokeRuleResponse,\n                      queryAsyncJobResultAuthorizeIngressResponse, getEmptyResponse)\n      ).getSecurityGroupExtension().get();\n\n\n      SecurityGroup origGroup = new SecurityGroupBuilder().id(\"13\").build();\n\n      SecurityGroup newGroup = extension.removeIpPermission(IpProtocol.UDP, 11, 11, emptyMultimap(),\n              ImmutableSet.of(\"1.1.1.1/24\"), emptyStringSet(), origGroup);\n\n      assertEquals(newGroup.getIpPermissions().size(), 0);\n   }\n\n   public void testRemoveIpPermissionGroupFromIpPermission() {\n      HttpRequest revokeRule = HttpRequest.builder().method(\"GET\")\n              .endpoint(\"http://localhost:8080/client/api\")\n              .addQueryParam(\"response\", \"json\")\n              .addQueryParam(\"command\", \"revokeSecurityGroupIngress\")\n              .addQueryParam(\"id\", \"5\")\n              .addQueryParam(\"apiKey\", \"APIKEY\")\n              .addQueryParam(\"signature\", \"bEzvrLtO7aEWkIqJgUeTnd+0XbY=\")\n              .addHeader(\"Accept\", \"application/json\")\n              .build();\n\n      HttpResponse getWithRuleResponse = HttpResponse.builder().statusCode(200)\n              .payload(payloadFromResource(\"/getsecuritygroupresponse_extension_byid_with_group.json\"))\n              .build();\n\n      SecurityGroupExtension extension = orderedRequestsSendResponses(\n              ImmutableList.of(getWithRule, revokeRule, queryAsyncJobResultAuthorizeIngress, getWithRule),\n              ImmutableList.of(getWithRuleResponse, revokeRuleResponse,\n                      queryAsyncJobResultAuthorizeIngressResponse, getEmptyResponse)\n      ).getSecurityGroupExtension().get();\n\n      IpPermission.Builder builder = IpPermission.builder();\n\n      builder.ipProtocol(IpProtocol.TCP);\n      builder.fromPort(22);\n      builder.toPort(22);\n      builder.tenantIdGroupNamePair(\"adrian\", \"adriancole\");\n\n      IpPermission perm = builder.build();\n\n      SecurityGroup origGroup = new SecurityGroupBuilder().id(\"13\").build();\n\n      SecurityGroup newGroup = extension.removeIpPermission(perm, origGroup);\n\n      assertEquals(newGroup.getIpPermissions().size(), 0);\n   }\n\n   public void testRemoveIpPermissionGroupFromParams() {\n      HttpRequest revokeRule = HttpRequest.builder().method(\"GET\")\n              .endpoint(\"http://localhost:8080/client/api\")\n              .addQueryParam(\"response\", \"json\")\n              .addQueryParam(\"command\", \"revokeSecurityGroupIngress\")\n              .addQueryParam(\"id\", \"5\")\n              .addQueryParam(\"apiKey\", \"APIKEY\")\n              .addQueryParam(\"signature\", \"bEzvrLtO7aEWkIqJgUeTnd+0XbY=\")\n              .addHeader(\"Accept\", \"application/json\")\n              .build();\n\n      HttpResponse getWithRuleResponse = HttpResponse.builder().statusCode(200)\n              .payload(payloadFromResource(\"/getsecuritygroupresponse_extension_byid_with_group.json\"))\n              .build();\n\n      SecurityGroupExtension extension = orderedRequestsSendResponses(\n              ImmutableList.of(getWithRule, revokeRule, queryAsyncJobResultAuthorizeIngress, getWithRule),\n              ImmutableList.of(getWithRuleResponse, revokeRuleResponse,\n                      queryAsyncJobResultAuthorizeIngressResponse, getEmptyResponse)\n      ).getSecurityGroupExtension().get();\n\n      ImmutableMultimap.Builder<String, String> permBuilder = ImmutableMultimap.builder();\n      permBuilder.put(\"adrian\", \"adriancole\");\n\n      SecurityGroup origGroup = new SecurityGroupBuilder().id(\"13\").build();\n\n      SecurityGroup newGroup = extension.removeIpPermission(IpProtocol.TCP, 22, 22,\n              permBuilder.build(), emptyStringSet(), emptyStringSet(), origGroup);\n\n      assertEquals(newGroup.getIpPermissions().size(), 0);\n   }\n\n   @Override\n   public ComputeService createClient(Function<HttpRequest, HttpResponse> fn, Module module, Properties props) {\n      return clientFrom(createInjector(fn, module, props).getInstance(CloudStackContext.class));\n   }\n\n   @Override\n   protected ComputeService clientFrom(CloudStackContext context) {\n      return context.getComputeService();\n   }\n\n   private Multimap<String, String> emptyMultimap() {\n      return LinkedHashMultimap.create();\n   }\n\n   private Set<String> emptyStringSet() {\n      return Sets.newLinkedHashSet();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/compute/extensions/CloudStackSecurityGroupExtensionLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.compute.extensions;\n\nimport org.jclouds.cloudstack.CloudStackApi;\nimport org.jclouds.cloudstack.domain.Zone;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.extensions.internal.BaseSecurityGroupExtensionLiveTest;\nimport org.jclouds.sshj.config.SshjSshClientModule;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Module;\n\n/**\n * Live test for CloudStack {@link org.jclouds.compute.extensions.SecurityGroupExtension} implementation.\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"CloudStackSecurityGroupExtensionLiveTest\")\npublic class CloudStackSecurityGroupExtensionLiveTest extends BaseSecurityGroupExtensionLiveTest {\n\n   protected Zone zone;\n\n   public CloudStackSecurityGroupExtensionLiveTest() {\n      provider = \"cloudstack\";\n   }\n\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   public void setupContext() {\n      super.setupContext();\n\n      CloudStackApi api = view.unwrapApi(CloudStackApi.class);\n      for (Zone z : api.getZoneApi().listZones()) {\n         if (z.isSecurityGroupsEnabled()) {\n            zone = z;\n            break;\n         }\n      }\n\n      if (zone == null)\n         securityGroupsSupported = false;\n   }\n\n   protected Module getSshModule() {\n      return new SshjSshClientModule();\n   }\n\n   @Override\n   public Template getNodeTemplate() {\n      return view.getComputeService().templateBuilder().locationId(zone.getId()).build();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/compute/functions/CloudStackSecurityGroupToSecurityGroupTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.compute.functions;\n\nimport static com.google.common.collect.Iterables.transform;\nimport static org.testng.Assert.assertEquals;\n\n\nimport org.jclouds.compute.domain.SecurityGroup;\nimport org.jclouds.net.domain.IpProtocol;\nimport org.jclouds.cloudstack.domain.IngressRule;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\", testName = \"CloudStackSecurityGroupToSecurityGroupTest\")\npublic class CloudStackSecurityGroupToSecurityGroupTest {\n\n   private static final IngressRuleToIpPermission ruleConverter = new IngressRuleToIpPermission();\n   \n   @Test\n   public void testApply() {\n      IngressRule ruleToConvert = IngressRule.builder()\n         .id(\"some-id\")\n         .account(\"some-account\")\n         .securityGroupName(\"some-group-name\")\n         .protocol(IpProtocol.TCP.toString())\n         .startPort(10)\n         .endPort(20)\n         .CIDR(\"0.0.0.0/0\")\n         .build();\n\n      org.jclouds.cloudstack.domain.SecurityGroup origGroup = org.jclouds.cloudstack.domain.SecurityGroup.builder()\n         .id(\"some-id\")\n         .name(\"some-group\")\n         .description(\"some-description\")\n         .account(\"some-account\")\n         .ingressRules(ImmutableSet.of(ruleToConvert))\n         .build();\n\n      CloudStackSecurityGroupToSecurityGroup parser = createGroupParser();\n\n      SecurityGroup group = parser.apply(origGroup);\n      \n      assertEquals(group.getId(), origGroup.getId());\n      assertEquals(group.getProviderId(), origGroup.getId());\n      assertEquals(group.getName(), origGroup.getName());\n      assertEquals(group.getOwnerId(), origGroup.getAccount());\n      assertEquals(group.getIpPermissions(), ImmutableSet.copyOf(transform(origGroup.getIngressRules(), ruleConverter)));\n   }\n\n   private CloudStackSecurityGroupToSecurityGroup createGroupParser() {\n      CloudStackSecurityGroupToSecurityGroup parser = new CloudStackSecurityGroupToSecurityGroup(ruleConverter);\n\n      return parser;\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/compute/functions/IngressRuleToIpPermissionTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.compute.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.cloudstack.domain.IngressRule;\nimport org.jclouds.net.domain.IpPermission;\nimport org.jclouds.net.domain.IpProtocol;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n\n/**\n * Tests for the function for transforming a cloudstack specific IngressRule into a generic\n * IpPermission object.\n */\npublic class IngressRuleToIpPermissionTest {\n\n   @Test\n   public void testApplyWithTCP() {\n      IngressRule ruleToConvert = IngressRule.builder()\n         .id(\"some-id\")\n         .account(\"some-account\")\n         .securityGroupName(\"some-group-name\")\n         .protocol(IpProtocol.TCP.toString())\n         .startPort(10)\n         .endPort(20)\n         .CIDR(\"0.0.0.0/0\")\n         .build();\n\n      IngressRuleToIpPermission converter = new IngressRuleToIpPermission();\n\n      IpPermission convertedPerm = converter.apply(ruleToConvert);\n\n      assertEquals(convertedPerm.getIpProtocol(), IpProtocol.fromValue(ruleToConvert.getProtocol()));\n      assertEquals(convertedPerm.getFromPort(), ruleToConvert.getStartPort());\n      assertEquals(convertedPerm.getToPort(), ruleToConvert.getEndPort());\n      assertEquals(convertedPerm.getCidrBlocks(), ImmutableSet.of(\"0.0.0.0/0\"));\n      assertEquals(convertedPerm.getTenantIdGroupNamePairs().size(), 1);\n      assertEquals(convertedPerm.getGroupIds().size(), 0);\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/compute/functions/ServiceOfferingToHardwareTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.compute.functions;\n\nimport static org.testng.AssertJUnit.assertEquals;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.ServiceOffering;\nimport org.jclouds.cloudstack.parse.ListServiceOfferingsResponseTest;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.HardwareBuilder;\nimport org.jclouds.compute.domain.Processor;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\n\n/**\n * Tests {@code ServiceOfferingToHardware}\n */\n@Test(groups = \"unit\")\npublic class ServiceOfferingToHardwareTest {\n\n   static ServiceOfferingToHardware function = new ServiceOfferingToHardware();\n   static Hardware one = new HardwareBuilder().ids(\"1\").name(\"Small Instance\")\n         .processors(ImmutableList.of(new Processor(1, 500))).ram(512).build();\n   static Hardware two = new HardwareBuilder().ids(\"2\").name(\"Medium Instance\")\n         .processors(ImmutableList.of(new Processor(1, 1000))).ram(1024).build();\n\n   @Test\n   public void test() {\n\n      Set<Hardware> expected = ImmutableSet.of(one, two);\n\n      Set<ServiceOffering> offerings = new ListServiceOfferingsResponseTest().expected();\n\n      Iterable<Hardware> profiles = Iterables.transform(offerings, function);\n\n      assertEquals(profiles.toString(), expected.toString());\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/compute/functions/TemplateToImageTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.compute.functions;\n\nimport static org.testng.AssertJUnit.assertEquals;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.Template;\nimport org.jclouds.cloudstack.parse.ListTemplatesResponseTest;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.Image.Status;\nimport org.jclouds.compute.domain.ImageBuilder;\nimport org.jclouds.domain.Location;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\n\n/**\n * Tests {@code TemplateToImage}\n */\n@Test(groups = \"unit\")\npublic class TemplateToImageTest {\n   static Supplier<Set<? extends Location>> locationSupplier = Suppliers\n         .<Set<? extends Location>> ofInstance(ImmutableSet.<Location> of(ZoneToLocationTest.one,\n               ZoneToLocationTest.two));\n\n   static TemplateToImage function = new TemplateToImage(locationSupplier, TemplateToOperatingSystemTest.function);\n\n   // location free image\n   static Image one = new ImageBuilder().id(\"2\").providerId(\"2\").name(\"CentOS 5.3(64-bit) no GUI (XenServer)\")\n         .operatingSystem(TemplateToOperatingSystemTest.one).description(\"CentOS 5.3(64-bit) no GUI (XenServer)\")\n         .status(Status.AVAILABLE).build();\n   // location free image\n   static Image two = new ImageBuilder().id(\"4\").providerId(\"4\").name(\"CentOS 5.5(64-bit) no GUI (KVM)\")\n         .operatingSystem(TemplateToOperatingSystemTest.two).description(\"CentOS 5.5(64-bit) no GUI (KVM)\")\n         .status(Status.AVAILABLE).build();\n   static Image three = new ImageBuilder().id(\"203\").providerId(\"203\").name(\"Windows 7 KVM\")\n         .operatingSystem(TemplateToOperatingSystemTest.three).description(\"Windows 7 KVM\")\n         .location(ZoneToLocationTest.two).status(Status.AVAILABLE).build();\n   // location free image\n   static Image four = new ImageBuilder().id(\"7\").providerId(\"7\").name(\"CentOS 5.3(64-bit) no GUI (vSphere)\")\n         .operatingSystem(TemplateToOperatingSystemTest.four).description(\"CentOS 5.3(64-bit) no GUI (vSphere)\")\n         .status(Status.AVAILABLE).build();\n   static Image five = new ImageBuilder().id(\"241\").providerId(\"241\").name(\"kvmdev4\")\n         .operatingSystem(TemplateToOperatingSystemTest.five).description(\"v5.6.28_Dev4\")\n         .location(ZoneToLocationTest.two).status(Status.AVAILABLE).build();\n\n   @Test\n   public void test() {\n\n      Set<Image> expected = ImmutableSet.of(one, two, three, four, five);\n\n      Set<Template> offerings = new ListTemplatesResponseTest().expected();\n\n      Iterable<Image> profiles = Iterables.transform(offerings, function);\n\n      assertEquals(profiles.toString(), expected.toString());\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/compute/functions/TemplateToOperatingSystemTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.compute.functions;\n\nimport static org.testng.AssertJUnit.assertEquals;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.OSType;\nimport org.jclouds.cloudstack.domain.Template;\nimport org.jclouds.cloudstack.parse.ListOSCategoriesResponseTest;\nimport org.jclouds.cloudstack.parse.ListOSTypesResponseTest;\nimport org.jclouds.cloudstack.parse.ListTemplatesResponseTest;\nimport org.jclouds.compute.config.BaseComputeServiceContextModule;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.json.Json;\nimport org.jclouds.json.config.GsonModule;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Maps;\nimport com.google.inject.Guice;\n\n/**\n * Tests {@code TemplateToOperatingSystem}\n */\n@Test(groups = \"unit\")\npublic class TemplateToOperatingSystemTest {\n   static Map<String, OSType> ostypes = Maps.<String, OSType> uniqueIndex(new ListOSTypesResponseTest().expected(),\n         new Function<OSType, String>() {\n\n            @Override\n            public String apply(OSType arg0) {\n               return arg0.getId();\n            }\n         });\n\n   static TemplateToOperatingSystem function = new TemplateToOperatingSystem(Suppliers.ofInstance(ostypes),\n         Suppliers.ofInstance(new ListOSCategoriesResponseTest().expected()), new BaseComputeServiceContextModule() {\n         }.provideOsVersionMap(new ComputeServiceConstants.ReferenceData(), Guice.createInjector(new GsonModule())\n               .getInstance(Json.class)));\n\n   static OperatingSystem one = OperatingSystem.builder().name(\"CentOS\").family(OsFamily.CENTOS).is64Bit(false)\n         .version(\"5.3\").description(\"CentOS 5.3 (32-bit)\").build();\n   static OperatingSystem two = OperatingSystem.builder().name(\"CentOS\").family(OsFamily.CENTOS).is64Bit(true)\n         .version(\"5.5\").description(\"CentOS 5.5 (64-bit)\").build();\n   static OperatingSystem three = OperatingSystem.builder().name(\"Windows\").family(OsFamily.WINDOWS).is64Bit(false)\n         .version(\"7\").description(\"Windows 7 (32-bit)\").build();\n   static OperatingSystem four = OperatingSystem.builder().name(\"CentOS\").family(OsFamily.CENTOS).is64Bit(true)\n         .version(\"5.3\").description(\"CentOS 5.3 (64-bit)\").build();\n   static OperatingSystem five = OperatingSystem.builder().name(\"CentOS\").family(OsFamily.CENTOS).is64Bit(true)\n         .version(\"5.4\").description(\"CentOS 5.4 (64-bit)\").build();\n\n   @Test\n   public void test() {\n\n      Set<OperatingSystem> expected = ImmutableSet.of(one, two, three, four, five);\n\n      Set<Template> offerings = new ListTemplatesResponseTest().expected();\n\n      Iterable<OperatingSystem> profiles = Iterables.transform(offerings, function);\n\n      assertEquals(profiles.toString(), expected.toString());\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/compute/functions/VirtualMachineToNodeMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.compute.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.UnknownHostException;\nimport java.util.Set;\n\nimport com.google.common.collect.ImmutableMap;\nimport org.jclouds.cloudstack.domain.GuestIPType;\nimport org.jclouds.cloudstack.domain.IPForwardingRule;\nimport org.jclouds.cloudstack.domain.NIC;\nimport org.jclouds.cloudstack.domain.TrafficType;\nimport org.jclouds.cloudstack.domain.VirtualMachine;\nimport org.jclouds.cloudstack.parse.ListVirtualMachinesResponseTest;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.HardwareBuilder;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadata.Status;\nimport org.jclouds.compute.domain.NodeMetadataBuilder;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.domain.Location;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.inject.Guice;\n\n@Test(groups = \"unit\", testName = \"VirtualMachineToNodeMetadataTest\")\npublic class VirtualMachineToNodeMetadataTest {\n\n   GroupNamingConvention.Factory namingConvention = Guice.createInjector().getInstance(GroupNamingConvention.Factory.class);\n\n   @Test\n   public void testApplyWhereVirtualMachineWithIPForwardingRule() throws UnknownHostException {\n\n      Supplier<Set<? extends Location>> locationSupplier = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n         .<Location>of(ZoneToLocationTest.one, ZoneToLocationTest.two));\n\n      Supplier<Set<? extends Image>> imageSupplier = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet\n         .<Image>of(TemplateToImageTest.one, TemplateToImageTest.two));\n      VirtualMachineToNodeMetadata parser = new VirtualMachineToNodeMetadata(locationSupplier, imageSupplier,\n            CacheBuilder.newBuilder().<String, Set<IPForwardingRule>> build(\n                  new CacheLoader<String, Set<IPForwardingRule>>() {\n                     @Override\n                     public Set<IPForwardingRule> load(String arg0) throws Exception {\n                        return ImmutableSet.of(IPForwardingRule.builder().id(\"1234l\").IPAddress(\"1.1.1.1\").build());\n                     }\n                  }), namingConvention);\n\n      // notice if we've already parsed this properly here, we can rely on it.\n      VirtualMachine guest = Iterables.get(new ListVirtualMachinesResponseTest().expected(), 0);\n\n      NodeMetadata node = parser.apply(guest);\n\n      assertEquals(\n            node.toString(),\n            new NodeMetadataBuilder().id(\"54\").providerId(\"54\").name(\"i-3-54-VM\").group(\"i-3-54\")\n                  .location(ZoneToLocationTest.one).status(Status.PENDING).hostname(\"i-3-54-VM\")\n                  .privateAddresses(ImmutableSet.of(\"10.1.1.18\")).publicAddresses(ImmutableSet.of(\"1.1.1.1\"))\n                  .hardware(addHypervisor(ServiceOfferingToHardwareTest.one, \"XenServer\"))\n                  .imageId(TemplateToImageTest.one.getId())\n                  .operatingSystem(TemplateToImageTest.one.getOperatingSystem())\n                  .tags(ImmutableSet.of(\"another-tag\"))\n                  .userMetadata(ImmutableMap.of(\"some-tag\", \"some-value\"))\n                  .build().toString()\n      );\n\n   }\n\n   @Test\n   public void testApplyWhereVirtualMachineHasNoIpForwardingRuleAndAPublicIP() throws UnknownHostException {\n\n      Supplier<Set<? extends Location>> locationSupplier = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n         .<Location>of(ZoneToLocationTest.one, ZoneToLocationTest.two));\n\n      Supplier<Set<? extends Image>> imageSupplier = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet\n         .<Image>of(TemplateToImageTest.one, TemplateToImageTest.two));\n\n      VirtualMachineToNodeMetadata parser = new VirtualMachineToNodeMetadata(locationSupplier, imageSupplier,\n            CacheBuilder.newBuilder().<String, Set<IPForwardingRule>> build(\n                  new CacheLoader<String, Set<IPForwardingRule>>() {\n                     @Override\n                     public Set<IPForwardingRule> load(String arg0) throws Exception {\n                        return ImmutableSet.of();\n                     }\n                  }), namingConvention);\n\n      VirtualMachine guest = VirtualMachine.builder()\n         .id(\"54\")\n         .name(\"i-3-54-VM\")\n         .displayName(\"i-3-54-VM\")\n         .account(\"adrian\")\n         .domainId(\"1\")\n         .domain(\"ROOT\")\n         .created(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2011-02-16T14:28:37-0800\"))\n         .state(VirtualMachine.State.STARTING)\n         .isHAEnabled(false)\n         .zoneId(\"1\")\n         .zoneName(\"San Jose 1\")\n         .templateId(\"2\")\n         .templateName(\"CentOS 5.3(64-bit) no GUI (XenServer)\")\n         .templateDisplayText(\"CentOS 5.3(64-bit) no GUI (XenServer)\")\n         .passwordEnabled(false)\n         .serviceOfferingId(\"1\")\n         .serviceOfferingName(\"Small Instance\")\n         .cpuCount(1)\n         .cpuSpeed(500)\n         .memory(512)\n         .guestOSId(\"11\")\n         .rootDeviceId(\"0\")\n         .rootDeviceType(\"NetworkFilesystem\")\n         .jobId(\"63l\")\n         .jobStatus(0)\n         .nics(ImmutableSet.of(NIC.builder().id(\"72\").networkId(\"204\").netmask(\"255.255.255.0\").gateway(\"1.1.1.1\")\n            .IPAddress(\"1.1.1.5\").trafficType(TrafficType.GUEST).guestIPType(GuestIPType.VIRTUAL)\n            .isDefault(true).build())).hypervisor(\"XenServer\").build();\n\n      NodeMetadata node = parser.apply(guest);\n\n      assertEquals(\n         node.toString(),\n         new NodeMetadataBuilder().id(\"54\").providerId(\"54\").name(\"i-3-54-VM\").group(\"i-3-54\")\n            .location(ZoneToLocationTest.one).status(Status.PENDING).hostname(\"i-3-54-VM\")\n            .privateAddresses(ImmutableSet.<String>of())\n            .publicAddresses(ImmutableSet.<String>of(\"1.1.1.5\"))\n            .hardware(addHypervisor(ServiceOfferingToHardwareTest.one, \"XenServer\"))\n            .imageId(TemplateToImageTest.one.getId())\n            .operatingSystem(TemplateToImageTest.one.getOperatingSystem()).build().toString());\n   }\n\n   @Test\n   public void testApplyWhereVirtualMachineWithNoPassword() throws UnknownHostException {\n\n      Supplier<Set<? extends Location>> locationSupplier = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n         .<Location>of(ZoneToLocationTest.one, ZoneToLocationTest.two));\n\n      Supplier<Set<? extends Image>> imageSupplier = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet\n         .<Image>of(TemplateToImageTest.one, TemplateToImageTest.two));\n      VirtualMachineToNodeMetadata parser = new VirtualMachineToNodeMetadata(locationSupplier, imageSupplier,\n            CacheBuilder.newBuilder().<String, Set<IPForwardingRule>> build(\n                  new CacheLoader<String, Set<IPForwardingRule>>() {\n\n                     @Override\n                     public Set<IPForwardingRule> load(String arg0) throws Exception {\n                        throw new ResourceNotFoundException(\"no ip forwarding rule for: \" + arg0);\n                     }\n\n                  }), namingConvention);\n\n      // notice if we've already parsed this properly here, we can rely on it.\n      VirtualMachine guest = Iterables.get(new ListVirtualMachinesResponseTest().expected(), 0);\n\n      NodeMetadata node = parser.apply(guest);\n\n      assertEquals(\n            node.toString(),\n            new NodeMetadataBuilder().id(\"54\").providerId(\"54\").name(\"i-3-54-VM\").group(\"i-3-54\")\n                  .location(ZoneToLocationTest.one).status(Status.PENDING).hostname(\"i-3-54-VM\")\n                  .privateAddresses(ImmutableSet.of(\"10.1.1.18\"))\n                  .hardware(addHypervisor(ServiceOfferingToHardwareTest.one, \"XenServer\"))\n                  .imageId(TemplateToImageTest.one.getId())\n                  .operatingSystem(TemplateToImageTest.one.getOperatingSystem())\n                  .tags(ImmutableSet.of(\"another-tag\"))\n                  .userMetadata(ImmutableMap.of(\"some-tag\", \"some-value\"))\n                  .build().toString());\n   }\n\n   protected Hardware addHypervisor(Hardware in, String hypervisor) {\n      return HardwareBuilder.fromHardware(in).hypervisor(hypervisor).build();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/compute/functions/ZoneToLocationTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.compute.functions;\n\nimport static org.testng.AssertJUnit.assertEquals;\n\nimport java.net.URI;\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.Zone;\nimport org.jclouds.cloudstack.parse.ListZonesResponseTest;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.location.suppliers.all.JustProvider;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\n\n/**\n * Tests {@code ZoneToLocation}\n */\n@Test(singleThreaded = true, groups = \"unit\")\npublic class ZoneToLocationTest {\n\n   public static final JustProvider justProvider = new JustProvider(\"cloudstack\", Suppliers.ofInstance(URI.create(\"foo\")),\n            ImmutableSet.<String> of());\n   public static final ZoneToLocation function = new ZoneToLocation(justProvider);\n   public static final Location one = new LocationBuilder().parent(Iterables.get(justProvider.get(), 0)).scope(LocationScope.ZONE)\n         .description(\"San Jose 1\").id(\"1\").build();\n   public static final Location two = new LocationBuilder().parent(Iterables.get(justProvider.get(), 0)).scope(LocationScope.ZONE)\n         .description(\"Chicago\").id(\"2\").build();\n\n   @Test\n   public void test() {\n\n      Set<Location> expected = ImmutableSet.of(one, two);\n\n      Set<Zone> zones = new ListZonesResponseTest().expected();\n\n      Iterable<Location> locations = Iterables.transform(zones, function);\n\n      assertEquals(locations.toString(), expected.toString());\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/compute/loaders/CreateUniqueKeyPairTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.compute.loaders;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.UnknownHostException;\n\nimport org.jclouds.cloudstack.CloudStackApi;\nimport org.jclouds.cloudstack.domain.SshKeyPair;\nimport org.jclouds.cloudstack.features.SSHKeyPairApi;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.TypeLiteral;\n\n@Test(groups = \"unit\", testName = \"CreateUniqueKeyPairTest\")\npublic class CreateUniqueKeyPairTest {\n\n   @Test\n   public void testLoad() throws UnknownHostException {\n      final CloudStackApi client = createMock(CloudStackApi.class);\n      SSHKeyPairApi keyClient = createMock(SSHKeyPairApi.class);\n\n      SshKeyPair pair = createMock(SshKeyPair.class);\n\n      expect(client.getSSHKeyPairApi()).andReturn(keyClient);\n      expect(keyClient.createSSHKeyPair(\"group-1\")).andReturn(pair);\n\n      replay(client, keyClient);\n\n      CreateUniqueKeyPair parser = Guice.createInjector(new AbstractModule() {\n\n         @Override\n         protected void configure() {\n            bind(new TypeLiteral<Supplier<String>>() {\n            }).toInstance(Suppliers.ofInstance(\"1\"));\n            bind(CloudStackApi.class).toInstance(client);\n         }\n\n      }).getInstance(CreateUniqueKeyPair.class);\n\n      assertEquals(parser.load(\"group-1\"), pair);\n\n      verify(client, keyClient);\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/compute/loaders/FindSecurityGroupOrCreateTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.compute.loaders;\n\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL;\nimport static org.jclouds.util.Predicates2.retry;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.UnknownHostException;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.cloudstack.CloudStackApi;\nimport org.jclouds.cloudstack.domain.IngressRule;\nimport org.jclouds.cloudstack.domain.SecurityGroup;\nimport org.jclouds.cloudstack.domain.Zone;\nimport org.jclouds.cloudstack.domain.ZoneAndName;\nimport org.jclouds.cloudstack.domain.ZoneSecurityGroupNamePortsCidrs;\nimport org.jclouds.cloudstack.features.AsyncJobApi;\nimport org.jclouds.cloudstack.features.SecurityGroupApi;\nimport org.jclouds.cloudstack.features.ZoneApi;\nimport org.jclouds.cloudstack.functions.CreateSecurityGroupIfNeeded;\nimport org.jclouds.cloudstack.functions.ZoneIdToZone;\nimport org.jclouds.cloudstack.predicates.JobComplete;\nimport org.jclouds.cloudstack.suppliers.ZoneIdToZoneSupplier;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Provides;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.name.Names;\n\n@Test(groups = \"unit\", testName = \"FindSecurityGroupOrCreateTest\")\npublic class FindSecurityGroupOrCreateTest {\n\n   @Test\n   public void testLoad() throws UnknownHostException {\n      final CloudStackApi client = createMock(CloudStackApi.class);\n      SecurityGroupApi secClient = createMock(SecurityGroupApi.class);\n      ZoneApi zoneClient = createMock(ZoneApi.class);\n      AsyncJobApi jobClient = createMock(AsyncJobApi.class);\n      \n      SecurityGroup group = createMock(SecurityGroup.class);\n      \n      Zone zone = createMock(Zone.class);\n\n      expect(group.getIngressRules()).andReturn(ImmutableSet.<IngressRule> of());\n      expect(group.getId()).andReturn(\"sec-1234\").anyTimes();\n      expect(zone.isSecurityGroupsEnabled()).andReturn(true);\n      \n      expect(client.getSecurityGroupApi()).andReturn(secClient)\n         .anyTimes();\n      expect(client.getZoneApi()).andReturn(zoneClient);\n      expect(client.getAsyncJobApi()).andReturn(jobClient).anyTimes();\n\n      expect(zoneClient.getZone(\"zone-1\")).andReturn(zone);\n      expect(secClient.getSecurityGroupByName(\"group-1\")).andReturn(null);\n      expect(secClient.createSecurityGroup(\"group-1\")).andReturn(group);\n      expect(secClient.authorizeIngressPortsToCIDRs(\"sec-1234\",\n                                                    \"TCP\",\n                                                    22,\n                                                    22,\n                                                    ImmutableSet.of(\"0.0.0.0/0\"))).andReturn(\"job-1234\");\n\n      replay(client, secClient, zoneClient, zone, group);\n\n      ZoneSecurityGroupNamePortsCidrs input = ZoneSecurityGroupNamePortsCidrs.builder()\n         .zone(\"zone-1\")\n         .name(\"group-1\")\n         .ports(ImmutableSet.of(22))\n         .cidrs(ImmutableSet.<String> of()).build();\n      \n      FindSecurityGroupOrCreate parser = Guice.createInjector(new AbstractModule() {\n            \n            @Override\n            protected void configure() {\n               bind(new TypeLiteral<Supplier<String>>() {\n                  }).toInstance(Suppliers.ofInstance(\"1\"));\n               bind(CloudStackApi.class).toInstance(client);\n               bind(new TypeLiteral<CacheLoader<String, Zone>>() {}).\n                  to(ZoneIdToZone.class);\n               bind(new TypeLiteral<Supplier<LoadingCache<String, Zone>>>() {}).\n                  to(ZoneIdToZoneSupplier.class);\n               bind(String.class).annotatedWith(Names.named(PROPERTY_SESSION_INTERVAL)).toInstance(\"60\");\n\n               bind(new TypeLiteral<Function<ZoneSecurityGroupNamePortsCidrs, SecurityGroup>>() {\n                  }).to(CreateSecurityGroupIfNeeded.class);\n               \n               bind(new TypeLiteral<CacheLoader<ZoneAndName, SecurityGroup>>() {\n                  }).to(FindSecurityGroupOrCreate.class);\n            }\n            \n            @Provides\n            @Singleton\n            protected Predicate<String> jobComplete(JobComplete jobComplete) {\n               return retry(jobComplete, 1200, 1, 5, SECONDS);\n            }\n\n      }).getInstance(FindSecurityGroupOrCreate.class);\n\n      assertEquals(parser.load(input), group);\n\n      verify(client, secClient, zoneClient, zone, group);\n   }\n\n   \n   @Test\n   public void testLoadAlreadyExists() throws UnknownHostException {\n      final CloudStackApi client = createMock(CloudStackApi.class);\n      SecurityGroupApi secClient = createMock(SecurityGroupApi.class);\n      ZoneApi zoneClient = createMock(ZoneApi.class);\n      AsyncJobApi jobClient = createMock(AsyncJobApi.class);\n      \n      SecurityGroup group = createMock(SecurityGroup.class);\n      \n      Zone zone = createMock(Zone.class);\n\n      expect(group.getId()).andReturn(\"sec-1234\").anyTimes();\n      \n      expect(client.getSecurityGroupApi()).andReturn(secClient)\n         .anyTimes();\n      expect(client.getZoneApi()).andReturn(zoneClient);\n      expect(client.getAsyncJobApi()).andReturn(jobClient).anyTimes();\n\n      expect(secClient.getSecurityGroupByName(\"group-1\")).andReturn(group);\n\n      replay(client, secClient, zoneClient, zone, group);\n\n      ZoneSecurityGroupNamePortsCidrs input = ZoneSecurityGroupNamePortsCidrs.builder()\n         .zone(\"zone-1\")\n         .name(\"group-1\")\n         .ports(ImmutableSet.of(22))\n         .cidrs(ImmutableSet.<String> of()).build();\n      \n      FindSecurityGroupOrCreate parser = Guice.createInjector(new AbstractModule() {\n            \n            @Override\n            protected void configure() {\n               bind(new TypeLiteral<Supplier<String>>() {\n                  }).toInstance(Suppliers.ofInstance(\"1\"));\n               bind(CloudStackApi.class).toInstance(client);\n               bind(new TypeLiteral<CacheLoader<String, Zone>>() {}).\n                  to(ZoneIdToZone.class);\n               bind(new TypeLiteral<Supplier<LoadingCache<String, Zone>>>() {}).\n                  to(ZoneIdToZoneSupplier.class);\n               bind(String.class).annotatedWith(Names.named(PROPERTY_SESSION_INTERVAL)).toInstance(\"60\");\n\n               bind(new TypeLiteral<Function<ZoneSecurityGroupNamePortsCidrs, SecurityGroup>>() {\n                  }).to(CreateSecurityGroupIfNeeded.class);\n               \n               bind(new TypeLiteral<CacheLoader<ZoneAndName, SecurityGroup>>() {\n                  }).to(FindSecurityGroupOrCreate.class);\n            }\n            \n            @Provides\n            @Singleton\n            protected Predicate<String> jobComplete(JobComplete jobComplete) {\n               return retry(jobComplete, 1200, 1, 5, SECONDS);\n            }\n\n      }).getInstance(FindSecurityGroupOrCreate.class);\n\n      assertEquals(parser.load(input), group);\n\n      verify(client, secClient, zoneClient, zone, group);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testLoadZoneNoSecurityGroups() throws UnknownHostException {\n      final CloudStackApi client = createMock(CloudStackApi.class);\n      SecurityGroupApi secClient = createMock(SecurityGroupApi.class);\n      ZoneApi zoneClient = createMock(ZoneApi.class);\n      AsyncJobApi jobClient = createMock(AsyncJobApi.class);\n      \n      SecurityGroup group = createMock(SecurityGroup.class);\n      \n      Zone zone = createMock(Zone.class);\n\n      expect(zone.isSecurityGroupsEnabled()).andReturn(false);\n      \n      expect(client.getSecurityGroupApi()).andReturn(secClient)\n         .anyTimes();\n      expect(client.getZoneApi()).andReturn(zoneClient);\n      expect(client.getAsyncJobApi()).andReturn(jobClient).anyTimes();\n\n      expect(zoneClient.getZone(\"zone-1\")).andReturn(zone);\n      expect(secClient.getSecurityGroupByName(\"group-1\")).andReturn(null);\n\n      replay(client, secClient, zoneClient, zone, group);\n\n      ZoneSecurityGroupNamePortsCidrs input = ZoneSecurityGroupNamePortsCidrs.builder()\n         .zone(\"zone-1\")\n         .name(\"group-1\")\n         .ports(ImmutableSet.of(22))\n         .cidrs(ImmutableSet.<String> of()).build();\n      \n      FindSecurityGroupOrCreate parser = Guice.createInjector(new AbstractModule() {\n            \n            @Override\n            protected void configure() {\n               bind(new TypeLiteral<Supplier<String>>() {\n                  }).toInstance(Suppliers.ofInstance(\"1\"));\n               bind(CloudStackApi.class).toInstance(client);\n               bind(new TypeLiteral<CacheLoader<String, Zone>>() {}).\n                  to(ZoneIdToZone.class);\n               bind(new TypeLiteral<Supplier<LoadingCache<String, Zone>>>() {}).\n                  to(ZoneIdToZoneSupplier.class);\n               bind(String.class).annotatedWith(Names.named(PROPERTY_SESSION_INTERVAL)).toInstance(\"60\");\n\n               bind(new TypeLiteral<Function<ZoneSecurityGroupNamePortsCidrs, SecurityGroup>>() {\n                  }).to(CreateSecurityGroupIfNeeded.class);\n               \n               bind(new TypeLiteral<CacheLoader<ZoneAndName, SecurityGroup>>() {\n                  }).to(FindSecurityGroupOrCreate.class);\n            }\n            \n            @Provides\n            @Singleton\n            protected Predicate<String> jobComplete(JobComplete jobComplete) {\n               return retry(jobComplete, 1200, 1, 5, SECONDS);\n            }\n\n      }).getInstance(FindSecurityGroupOrCreate.class);\n\n      assertEquals(parser.load(input), group);\n\n      verify(client, secClient, zoneClient, zone, group);\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/compute/options/CloudStackTemplateOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.compute.options;\n\nimport static org.jclouds.cloudstack.compute.options.CloudStackTemplateOptions.Builder.account;\nimport static org.jclouds.cloudstack.compute.options.CloudStackTemplateOptions.Builder.dataDiskSize;\nimport static org.jclouds.cloudstack.compute.options.CloudStackTemplateOptions.Builder.diskOfferingId;\nimport static org.jclouds.cloudstack.compute.options.CloudStackTemplateOptions.Builder.domainId;\nimport static org.jclouds.cloudstack.compute.options.CloudStackTemplateOptions.Builder.generateKeyPair;\nimport static org.jclouds.cloudstack.compute.options.CloudStackTemplateOptions.Builder.generateSecurityGroup;\nimport static org.jclouds.cloudstack.compute.options.CloudStackTemplateOptions.Builder.ipOnDefaultNetwork;\nimport static org.jclouds.cloudstack.compute.options.CloudStackTemplateOptions.Builder.ipsToNetworks;\nimport static org.jclouds.cloudstack.compute.options.CloudStackTemplateOptions.Builder.keyPair;\nimport static org.jclouds.cloudstack.compute.options.CloudStackTemplateOptions.Builder.securityGroupIds;\nimport static org.jclouds.cloudstack.compute.options.CloudStackTemplateOptions.Builder.setupStaticNat;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Map;\n\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.testng.annotations.Test;\nimport org.testng.collections.Maps;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests possible uses of {@code CloudStackTemplateOptions} and\n * {@code CloudStackTemplateOptions.Builder.*}.\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"CloudStackTemplateOptionsTest\")\npublic class CloudStackTemplateOptionsTest {\n   //TODO: test clone();\n\n   @Test\n   public void testAs() {\n      TemplateOptions options = new CloudStackTemplateOptions();\n      assertEquals(options.as(CloudStackTemplateOptions.class), options);\n   }\n\n   @Test\n   public void testDefaultSecurityGroupIds() {\n      TemplateOptions options = new CloudStackTemplateOptions();\n      assertEquals(options.as(CloudStackTemplateOptions.class).getSecurityGroupIds(), ImmutableSet.of());\n   }\n\n   @Test\n   public void testSecurityGroupIds() {\n      TemplateOptions options = new CloudStackTemplateOptions().securityGroupIds(ImmutableSet.of(\"3\"));\n      assertEquals(options.as(CloudStackTemplateOptions.class).getSecurityGroupIds(), ImmutableSet.of(\"3\"));\n   }\n\n   @Test\n   public void testSecurityGroupIdsStatic() {\n      TemplateOptions options = securityGroupIds(ImmutableSet.of(\"3\"));\n      assertEquals(options.as(CloudStackTemplateOptions.class).getSecurityGroupIds(), ImmutableSet.of(\"3\"));\n   }\n\n   @Test\n   public void testGenerateSecurityGroupDefaultsFalse() {\n      TemplateOptions options = new CloudStackTemplateOptions();\n      assertFalse(options.as(CloudStackTemplateOptions.class)\n         .shouldGenerateSecurityGroup());\n   }\n\n   @Test\n   public void testGenerateSecurityGroup() {\n      TemplateOptions options = new CloudStackTemplateOptions().generateSecurityGroup(true);\n      assertTrue(options.as(CloudStackTemplateOptions.class)\n         .shouldGenerateSecurityGroup());\n   }\n\n   @Test\n   public void testGenerateSecurityGroupStatic() {\n      TemplateOptions options = generateSecurityGroup(true);\n      assertTrue(options.as(CloudStackTemplateOptions.class)\n         .shouldGenerateSecurityGroup());\n   }\n\n   @Test\n   public void testDefaultNetworkIds() {\n      TemplateOptions options = new CloudStackTemplateOptions();\n      assertEquals(options.as(CloudStackTemplateOptions.class).getNetworks(), ImmutableSet.of());\n   }\n\n   @Test\n   public void testNetworkId() {\n      TemplateOptions options = new CloudStackTemplateOptions().networks(\"3\");\n      assertEquals(options.as(CloudStackTemplateOptions.class).getNetworks(), ImmutableSet.of(\"3\"));\n   }\n\n   @Test\n   public void testIpOnDefaultNetwork() {\n      TemplateOptions options = new CloudStackTemplateOptions().ipOnDefaultNetwork(\"10.0.0.1\");\n      assertEquals(options.as(CloudStackTemplateOptions.class).getIpOnDefaultNetwork(), \"10.0.0.1\");\n   }\n\n   @Test\n   public void testIpOnDefaultNetworkStatic() {\n      TemplateOptions options = ipOnDefaultNetwork(\"10.0.0.1\");\n      assertEquals(options.as(CloudStackTemplateOptions.class).getIpOnDefaultNetwork(), \"10.0.0.1\");\n   }\n\n   @Test\n   public void testIpsToNetwork() {\n      Map<String, String> ipsToNetworks = Maps.newHashMap();\n      ipsToNetworks.put(\"10.0.0.1\", \"5\");\n\n      TemplateOptions options = new CloudStackTemplateOptions().ipsToNetworks(ipsToNetworks);\n      assertEquals(options.as(CloudStackTemplateOptions.class)\n         .getIpsToNetworks().get(\"10.0.0.1\"), \"5\");\n   }\n\n   @Test\n   public void testIpsToNetworkStatic() {\n      Map<String, String> ipsToNetworks = Maps.newHashMap();\n      ipsToNetworks.put(\"10.0.0.1\", \"5\");\n\n      TemplateOptions options = ipsToNetworks(ipsToNetworks);\n      assertEquals(options.as(CloudStackTemplateOptions.class)\n         .getIpsToNetworks().get(\"10.0.0.1\"), \"5\");\n   }\n\n   @Test\n   public void testSetupStaticNatDefaultsTrue() {\n      TemplateOptions options = new CloudStackTemplateOptions();\n      assertTrue(options.as(CloudStackTemplateOptions.class)\n         .shouldSetupStaticNat());\n   }\n\n   @Test\n   public void testSetupStaticNat() {\n      TemplateOptions options = new CloudStackTemplateOptions().setupStaticNat(false);\n      assertFalse(options.as(CloudStackTemplateOptions.class)\n         .shouldSetupStaticNat());\n   }\n\n   @Test\n   public void testSetupStaticNatStatic() {\n      TemplateOptions options = setupStaticNat(false);\n      assertFalse(options.as(CloudStackTemplateOptions.class)\n         .shouldSetupStaticNat());\n   }\n\n   @Test\n   public void testGenerateKeyPairDefaultsFalse() {\n      TemplateOptions options = new CloudStackTemplateOptions();\n      assertFalse(options.as(CloudStackTemplateOptions.class)\n         .shouldGenerateKeyPair());\n   }\n\n   @Test\n   public void testGenerateKeyPair() {\n      TemplateOptions options = new CloudStackTemplateOptions().generateKeyPair(true);\n      assertTrue(options.as(CloudStackTemplateOptions.class)\n         .shouldGenerateKeyPair());\n   }\n\n   @Test\n   public void testGenerateKeyPairStatic() {\n      TemplateOptions options = generateKeyPair(true);\n      assertTrue(options.as(CloudStackTemplateOptions.class)\n         .shouldGenerateKeyPair());\n   }\n\n   @Test\n   public void testKeyPair() {\n      TemplateOptions options = keyPair(\"test\");\n      assertEquals(options.as(CloudStackTemplateOptions.class).getKeyPair(), \"test\");\n   }\n\n   @Test\n   public void testDiskOfferingId() {\n      TemplateOptions options = diskOfferingId(\"test\");\n      assertEquals(options.as(CloudStackTemplateOptions.class).getDiskOfferingId(), \"test\");\n   }\n\n   @Test\n   public void testDataDiskSizeDefault() {\n      TemplateOptions options = new CloudStackTemplateOptions();\n      assertEquals(options.as(CloudStackTemplateOptions.class).getDataDiskSize(), 0);\n   }\n\n   @Test\n   public void testDataDiskSize() {\n      TemplateOptions options = dataDiskSize(10);\n      assertEquals(options.as(CloudStackTemplateOptions.class).getDataDiskSize(), 10);\n   }\n\n   @Test\n   public void testAccount() {\n      TemplateOptions options = account(\"test\");\n      assertEquals(options.as(CloudStackTemplateOptions.class).getAccount(), \"test\");\n   }\n\n   @Test\n   public void testDomainId() {\n      TemplateOptions options = domainId(\"test\");\n      assertEquals(options.as(CloudStackTemplateOptions.class).getDomainId(), \"test\");\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/compute/strategy/OptionsConverterTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.compute.strategy;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Map;\n\nimport org.jclouds.cloudstack.compute.options.CloudStackTemplateOptions;\nimport org.jclouds.cloudstack.domain.Network;\nimport org.jclouds.cloudstack.domain.NetworkService;\nimport org.jclouds.cloudstack.options.DeployVirtualMachineOptions;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(singleThreaded = true, testName = \"OptionsConverterTest\")\npublic class OptionsConverterTest {\n\n   private static final Map<String, Network> EMPTY_NETWORKS_MAP = ImmutableMap.<String, Network>of();\n   private static final String ZONE_ID = \"2\";\n   private final NetworkService firewallServiceWithStaticNat\n      = NetworkService.builder().name(\"Firewall\").capabilities(ImmutableMap.of(\"StaticNat\", \"true\")).build();\n\n   @Test\n   public void testBasicNetworkOptionsConverter() {\n      BasicNetworkOptionsConverter converter = new BasicNetworkOptionsConverter();\n\n      CloudStackTemplateOptions optionsIn = CloudStackTemplateOptions.Builder.securityGroupIds(ImmutableList.of(\"42\")).networks(ImmutableList.of(\"46\"));\n      DeployVirtualMachineOptions optionsOut = new DeployVirtualMachineOptions();\n\n      DeployVirtualMachineOptions optionsOut2 = converter.apply(optionsIn, EMPTY_NETWORKS_MAP, ZONE_ID, optionsOut);\n      assertEquals(optionsOut, optionsOut2);\n\n      DeployVirtualMachineOptions optionsExpected = DeployVirtualMachineOptions.Builder.securityGroupId(\"42\").networkId(\"46\");\n      assertEquals(optionsOut, optionsExpected);\n   }\n\n   @Test\n   public void testAdvancedSecurityGroupsNotAllowed() {\n      boolean exceptionThrown = false;\n      AdvancedNetworkOptionsConverter converter = new AdvancedNetworkOptionsConverter();\n      CloudStackTemplateOptions optionsIn = CloudStackTemplateOptions.Builder.securityGroupIds(ImmutableList.of(\"42\"));\n\n      try {\n         converter.apply(optionsIn, EMPTY_NETWORKS_MAP, ZONE_ID, DeployVirtualMachineOptions.NONE);\n      } catch (IllegalArgumentException e) {\n         exceptionThrown = true;\n      }\n\n      assertTrue(exceptionThrown, \"IllegalArgumentException should have been thrown\");\n   }\n\n   @Test\n   public void testAdvancedExplicitNetworkSelection() {\n      AdvancedNetworkOptionsConverter converter = new AdvancedNetworkOptionsConverter();\n      DeployVirtualMachineOptions optionsActual = converter.apply(new CloudStackTemplateOptions().networks(ImmutableList.of(\"42\")),\n         EMPTY_NETWORKS_MAP, ZONE_ID, DeployVirtualMachineOptions.NONE);\n      DeployVirtualMachineOptions optionsExpected = DeployVirtualMachineOptions.Builder.networkId(\"42\");\n      assertEquals(optionsActual, optionsExpected);\n   }\n\n   @Test\n   public void testAdvancedAutoDetectNetwork() {\n      AdvancedNetworkOptionsConverter converter = new AdvancedNetworkOptionsConverter();\n\n      Network eligibleNetwork = Network.builder()\n         .id(\"25\").zoneId(ZONE_ID).isDefault(true).services(ImmutableSet.of(firewallServiceWithStaticNat))\n         .build();\n      DeployVirtualMachineOptions optionsActual = converter.apply(new CloudStackTemplateOptions(),\n         ImmutableMap.of(eligibleNetwork.getId(), eligibleNetwork), ZONE_ID, DeployVirtualMachineOptions.NONE);\n      DeployVirtualMachineOptions optionsExpected = DeployVirtualMachineOptions.Builder.networkId(\"25\");\n      assertEquals(optionsActual, optionsExpected);\n   }\n\n   @Test\n   public void testAdvancedWhenNoNetworkGiven() {\n      AdvancedNetworkOptionsConverter converter = new AdvancedNetworkOptionsConverter();\n      boolean exceptionThrown = false;\n      try {\n         converter.apply(new CloudStackTemplateOptions(), EMPTY_NETWORKS_MAP, ZONE_ID, DeployVirtualMachineOptions.NONE);\n      } catch (IllegalArgumentException e) {\n         exceptionThrown = true;\n      }\n      assertTrue(exceptionThrown);\n   }\n\n   @Test\n   public void testAdvancedWhenNoNetworkEligible() {\n      AdvancedNetworkOptionsConverter converter = new AdvancedNetworkOptionsConverter();\n      Network unsuitableNetwork = Network.builder()\n         .id(\"25\").zoneId(ZONE_ID)\n         .build();\n\n      boolean exceptionThrown = false;\n      try {\n         converter.apply(new CloudStackTemplateOptions(), ImmutableMap.of(unsuitableNetwork.getId(), unsuitableNetwork), ZONE_ID, DeployVirtualMachineOptions.NONE);\n      } catch (IllegalArgumentException e) {\n         exceptionThrown = true;\n      }\n      assertTrue(exceptionThrown);\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/domain/VirtualMachineTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.domain;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.fail;\n\nimport org.testng.annotations.Test;\n\n/**\n * Tests for the VirtualMachine class.\n */\n@Test(groups = \"unit\", testName = \"VirtualMachineTest\")\npublic class VirtualMachineTest {\n\n   @Test(groups = \"unit\", enabled = true)\n   public void testCpuUsed() {\n      // Class under test should detect if the % is missing off the end\n      try { \n         VirtualMachine.builder().id(\"1\").cpuUsed(\"23.4\").build();\n         fail(\"Should have thrown an exception due to % being missing!\");\n      } catch (Exception e) { \n      }\n\n      // If CpuUsed is not specified at all, that's OK\n      VirtualMachine vm = VirtualMachine.builder().id(\"2\").build();\n      assertEquals(vm.getCpuUsed(), 0.0f);\n\n      // Retrieving CpuUsed should just give us a straightforward float\n      vm = VirtualMachine.builder().id(\"3\").cpuUsed(\"23.4%\").build();\n      assertEquals(vm.getCpuUsed(), 23.4, 0.01);\n      \n      //Allow ',' as decimal separator\n      vm = VirtualMachine.builder().id(\"4\").cpuUsed(\"23,4%\").build();\n      assertEquals(vm.getCpuUsed(), 23.4, 0.01);\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/AccountApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.CloudStackContext;\nimport org.jclouds.cloudstack.domain.Account;\nimport org.jclouds.cloudstack.domain.User;\nimport org.jclouds.cloudstack.internal.BaseCloudStackExpectTest;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Test the CloudStack AccountApi\n */\n@Test(groups = \"unit\", testName = \"AccountApiExpectTest\")\npublic class AccountApiExpectTest extends BaseCloudStackExpectTest<AccountApi> {\n\n\n   public void testListAccountsWhenResponseIs2xx() {\n\n      AccountApi client = requestSendsResponse(\n         HttpRequest.builder()\n            .method(\"GET\")\n            .endpoint(\"http://localhost:8080/client/api?response=json&command=listAccounts&listAll=true&apiKey=identity&signature=yMZYMZxzFlaUsbfxtuppMwNhpXI%3D\")\n            .addHeader(\"Accept\", \"application/json\")\n            .build(),\n         HttpResponse.builder()\n            .statusCode(200)\n            .payload(payloadFromResource(\"/listaccountsresponse.json\"))\n            .build());\n\n      Set<User> users = ImmutableSet.of(\n         User.builder()\n            .id(\"505\")\n            .name(\"jclouds\")\n            .firstName(\"Adrian\")\n            .lastName(\"Cole\")\n            .email(\"adrian@jclouds.org\")\n            .created(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2011-04-19T01:57:24+0000\"))\n            .state(User.State.ENABLED)\n            .account(\"jclouds\")\n            .accountType(Account.Type.USER)\n            .domainId(\"457\")\n            .domain(\"AA000062-jclouds-dev\")\n            .apiKey(\"APIKEY\")\n            .secretKey(\"SECRETKEY\").build());\n\n      assertEquals(client.listAccounts(),\n         ImmutableSet.of(Account.builder()\n            .id(\"505\")\n            .name(\"jclouds\")\n            .type(Account.Type.USER)\n            .domainId(\"457\")\n            .domain(\"AA000062-jclouds-dev\")\n            .receivedBytes(318900216)\n            .sentBytes(23189677)\n            .VMLimit(15L)\n            .VMs(1)\n            .IPsAvailable(14L)\n            .IPLimit(15L)\n            .IPs(0)\n            .IPsAvailable(15L)\n            .volumeLimit(90L)\n            .volumes(2)\n            .volumesAvailable(88L)\n            .snapshotLimit(250L)\n            .snapshots(0)\n            .snapshotsAvailable(250L)\n            .templateLimit(15L)\n            .templates(0)\n            .templatesAvailable(15L)\n            .VMsAvailable(14L)\n            .VMsStopped(0)\n            .VMsRunning(1)\n            .state(Account.State.ENABLED)\n            .users(users).build()));\n   }\n\n   @Override\n   protected AccountApi clientFrom(CloudStackContext context) {\n      return context.getApi().getAccountApi();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/AccountApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.cloudstack.domain.Account;\nimport org.jclouds.cloudstack.domain.User;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code AccountApi}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"AccountApiLiveTest\")\npublic class AccountApiLiveTest extends BaseCloudStackApiLiveTest {\n\n   @Test\n   public void testListAccounts() throws Exception {\n      for (Account securityAccount : client.getAccountApi().listAccounts())\n         checkAccount(securityAccount);\n   }\n\n   protected void checkAccount(Account account) {\n      assert account.getId() != null : account;\n      assertEquals(account.toString(), client.getAccountApi().getAccount(account.getId()).toString());\n      assert account.getName() != null : account;\n      assert account.getType() != null && account.getType() != Account.Type.UNRECOGNIZED : account;\n      assert account.getDomain() != null : account;\n      assert account.getDomainId() != null : account;\n      assert account.getUsers() != null : account;\n      for (User user : account.getUsers()) {\n         assert user.getName() != null : user;\n         assert user.getAccountType().equals(account.getType()) : user;\n         assert user.getDomain().equals(account.getDomain()) : user;\n         assert user.getDomainId().equals(account.getDomainId()) : user;\n         assert user.getCreated() != null : user;\n         assert user.getEmail() != null : user;\n         assert user.getLastName() != null : user;\n         assert user.getFirstName() != null : user;\n         assert user.getId() != null : user;\n         assert user.getState() != null : user;\n      }\n      assert account.getIPsAvailable() == null || account.getIPsAvailable() >= 0 : account;\n      assert account.getIPLimit() == null || account.getIPLimit() >= 0 : account;\n      assert account.getIPs() >= 0 : account;\n      assert account.getReceivedBytes() >= 0 : account;\n      assert account.getSentBytes() >= 0 : account;\n      assert account.getSnapshotsAvailable() == null || account.getSnapshotsAvailable() >= 0 : account;\n      assert account.getSnapshotLimit() == null || account.getSnapshotLimit() >= 0 : account;\n      assert account.getSnapshots() >= 0 : account;\n      assert account.getState() != null && account.getState() != Account.State.UNRECOGNIZED : account;\n      assert account.getTemplatesAvailable() == null || account.getTemplatesAvailable() >= 0 : account;\n      assert account.getTemplateLimit() == null || account.getTemplateLimit() >= 0 : account;\n      assert account.getTemplates() >= 0 : account;\n      assert account.getVMsAvailable() == null || account.getVMsAvailable() >= 0 : account;\n      assert account.getVMLimit() == null || account.getVMLimit() >= 0 : account;\n      assert account.getVMsRunning() >= 0 : account;\n      assert account.getVMsStopped() >= 0 : account;\n      assert account.getVMs() >= 0 : account;\n      assert account.getVolumesAvailable() == null || account.getVolumesAvailable() >= 0 : account;\n      assert account.getVolumeLimit() == null || account.getVolumeLimit() >= 0 : account;\n      assert account.getVolumes() >= 0 : account;\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/AccountApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport java.io.IOException;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiTest;\nimport org.jclouds.cloudstack.options.ListAccountsOptions;\nimport org.jclouds.functions.IdentityFunction;\nimport org.jclouds.http.functions.ParseFirstJsonValueNamed;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Functions;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.reflect.Invokable;\n\n/**\n * Tests behavior of {@code AccountApi}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"AccountApiTest\")\npublic class AccountApiTest extends BaseCloudStackApiTest<AccountApi> {\n\n   public void testListAccounts() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AccountApi.class, \"listAccounts\", ListAccountsOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listAccounts&listAll=true HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testListAccountsOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AccountApi.class, \"listAccounts\", ListAccountsOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\n            ListAccountsOptions.Builder.accountInDomain(\"jclouds\", \"123\")));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listAccounts&listAll=true&account=jclouds&domainid=123 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testGetAccount() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AccountApi.class, \"getAccount\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"3\"));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listAccounts&listAll=true&id=3 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest,\n            Functions.compose(IdentityFunction.INSTANCE, IdentityFunction.INSTANCE).getClass());\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/AddressApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.AsyncCreateResponse;\nimport org.jclouds.cloudstack.domain.PublicIPAddress;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest;\nimport org.jclouds.cloudstack.options.ListPublicIPAddressesOptions;\nimport org.testng.annotations.AfterGroups;\nimport org.testng.annotations.BeforeGroups;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Iterables;\n\n/**\n * Tests behavior of {@code AddressApi}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"AddressApiLiveTest\")\npublic class AddressApiLiveTest extends BaseCloudStackApiLiveTest {\n   private boolean networksEnabled;\n\n   @BeforeGroups(groups = \"live\")\n   void networksEnabled() {\n      networksEnabled = !client.getNetworkApi().listNetworks().isEmpty();\n   }\n\n   private PublicIPAddress ip = null;\n\n   public void testAssociateDisassociatePublicIPAddress() throws Exception {\n      if (!networksEnabled)\n         return;\n      AsyncCreateResponse job = client.getAddressApi().associateIPAddressInZone(\n            Iterables.get(client.getNetworkApi().listNetworks(), 0).getZoneId());\n      checkState(jobComplete.apply(job.getJobId()), \"job %s failed to complete\", job.getJobId());\n      ip = client.getAsyncJobApi().<PublicIPAddress> getAsyncJob(job.getJobId()).getResult();\n      checkIP(ip);\n   }\n\n   @AfterGroups(groups = \"live\")\n   @Override\n   protected void tearDownContext() {\n      if (ip != null) {\n         client.getAddressApi().disassociateIPAddress(ip.getId());\n      }\n      super.tearDownContext();\n   }\n\n   public void testListPublicIPAddresss() throws Exception {\n      if (!networksEnabled)\n         return;\n      Set<PublicIPAddress> response = client.getAddressApi().listPublicIPAddresses();\n      assert null != response;\n      assertTrue(response.size() > 0);\n      for (PublicIPAddress ip : response) {\n         PublicIPAddress newDetails = getOnlyElement(client.getAddressApi().listPublicIPAddresses(\n               ListPublicIPAddressesOptions.Builder.id(ip.getId())));\n         assertEquals(ip.getId(), newDetails.getId());\n         checkIP(ip);\n      }\n   }\n\n   protected void checkIP(PublicIPAddress ip) {\n      assertEquals(ip.getId(), client.getAddressApi().getPublicIPAddress(ip.getId()).getId());\n      assert ip.getId() != null : ip;\n      assert ip.getAccount() != null : ip;\n      assert ip.getDomain() != null : ip;\n      assert ip.getDomainId() != null : ip;\n      assert ip.getState() != null : ip;\n      assert ip.getZoneId() != null : ip;\n      assert ip.getZoneName() != null : ip;\n\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/AddressApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport java.io.IOException;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.cloudstack.functions.CloudStackFallbacks.VoidOnNotFoundOr404OrUnableToFindAccountOwner;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiTest;\nimport org.jclouds.cloudstack.options.AssociateIPAddressOptions;\nimport org.jclouds.cloudstack.options.ListPublicIPAddressesOptions;\nimport org.jclouds.fallbacks.MapHttp4xxCodesToExceptions;\nimport org.jclouds.functions.IdentityFunction;\nimport org.jclouds.http.functions.ParseFirstJsonValueNamed;\nimport org.jclouds.http.functions.ReleasePayloadAndReturn;\nimport org.jclouds.http.functions.UnwrapOnlyJsonValue;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Functions;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.reflect.Invokable;\n/**\n * Tests behavior of {@code AddressApi}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"AddressApiTest\")\npublic class AddressApiTest extends BaseCloudStackApiTest<AddressApi> {\n   public void testListPublicIPAddresses() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AddressApi.class, \"listPublicIPAddresses\", ListPublicIPAddressesOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listPublicIpAddresses&listAll=true HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testListPublicIPAddressesOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AddressApi.class, \"listPublicIPAddresses\", ListPublicIPAddressesOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\n            ListPublicIPAddressesOptions.Builder.accountInDomain(\"adrian\", \"6\").usesVirtualNetwork(true)));\n\n      assertRequestLineEquals(\n            httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listPublicIpAddresses&listAll=true&account=adrian&domainid=6&forvirtualnetwork=true HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testGetPublicIPAddress() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AddressApi.class, \"getPublicIPAddress\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(5));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listPublicIpAddresses&listAll=true&id=5 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest,\n            Functions.compose(IdentityFunction.INSTANCE, IdentityFunction.INSTANCE).getClass());\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testAssociateIPAddressInZone() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AddressApi.class, \"associateIPAddressInZone\", String.class,\n            AssociateIPAddressOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(6));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=associateIpAddress&zoneid=6 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testDisassociateIPAddress() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AddressApi.class, \"disassociateIPAddress\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(5));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=disassociateIpAddress&id=5 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, VoidOnNotFoundOr404OrUnableToFindAccountOwner.class);\n\n      checkFilters(httpRequest);\n\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/AsyncJobApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.AsyncJob;\nimport org.jclouds.cloudstack.domain.AsyncJob.ResultCode;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code AsyncJobApiLiveTest}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"AsyncJobApiLiveTest\")\npublic class AsyncJobApiLiveTest extends BaseCloudStackApiLiveTest {\n\n   @Test(enabled = true)\n   public void testListAsyncJobs() throws Exception {\n      Set<AsyncJob<?>> response = client.getAsyncJobApi().listAsyncJobs();\n      assert null != response;\n\n      long asyncJobCount = response.size();\n      assertTrue(asyncJobCount >= 0);\n\n      for (AsyncJob<?> asyncJob : response) {\n         assert asyncJob.getCmd() != null : asyncJob;\n         assert asyncJob.getUserId() != null : asyncJob;\n         checkJob(asyncJob);\n\n         AsyncJob<?> query = client.getAsyncJobApi().getAsyncJob(asyncJob.getId());\n         assertEquals(query.getId(), asyncJob.getId());\n\n         assert query.getResultType() != null : query;\n         checkJob(query);\n      }\n   }\n\n   private void checkJob(AsyncJob<?> query) {\n      assert query.getStatus().code() >= 0 : query;\n      assert query.getResultCode().code() >= 0 : query;\n      assert query.getProgress() >= 0 : query;\n      if (query.getResultCode() == ResultCode.SUCCESS) {\n         if (query.getResult() != null) {\n            assertEquals(query.getResult().getClass().getPackage(), AsyncJob.class.getPackage());\n         }\n      } else if (query.getResultCode() == ResultCode.FAIL) {\n         assert query.getResult() == null : query;\n         assert query.getError() != null : query;\n      } else {\n         assert query.getResult() == null : query;\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/AsyncJobApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport java.io.IOException;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.cloudstack.functions.ParseAsyncJobFromHttpResponse;\nimport org.jclouds.cloudstack.functions.ParseAsyncJobsFromHttpResponse;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiTest;\nimport org.jclouds.cloudstack.options.ListAsyncJobsOptions;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.reflect.Invokable;\n\n/**\n * Tests behavior of {@code AsyncJobApi}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"AsyncJobApiTest\")\npublic class AsyncJobApiTest extends BaseCloudStackApiTest<AsyncJobApi> {\n\n   public void testGetAsyncJob() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AsyncJobApi.class, \"getAsyncJob\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(11L));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=queryAsyncJobResult&jobid=11 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseAsyncJobFromHttpResponse.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testListAsyncJobs() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AsyncJobApi.class, \"listAsyncJobs\", ListAsyncJobsOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listAsyncJobs&listAll=true HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseAsyncJobsFromHttpResponse.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testListAsyncJobsOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AsyncJobApi.class, \"listAsyncJobs\", ListAsyncJobsOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\n            ListAsyncJobsOptions.Builder.accountInDomain(\"adrian\", \"5\")));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listAsyncJobs&listAll=true&account=adrian&domainid=5 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseAsyncJobsFromHttpResponse.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/ConfigurationApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport org.jclouds.cloudstack.domain.Capabilities;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code ConfigurationApiLiveTest}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"ConfigurationApiLiveTest\")\npublic class ConfigurationApiLiveTest extends BaseCloudStackApiLiveTest {\n\n   public void testListCapabilities() throws Exception {\n      Capabilities response = client.getConfigurationApi().listCapabilities();\n      assert null != response;\n      assert null != response.getCloudStackVersion();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/ConfigurationApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport java.io.IOException;\n\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiTest;\nimport org.jclouds.fallbacks.MapHttp4xxCodesToExceptions;\nimport org.jclouds.http.functions.ParseFirstJsonValueNamed;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.reflect.Invokable;\n/**\n * Tests behavior of {@code ConfigurationApi}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"ConfigurationApiTest\")\npublic class ConfigurationApiTest extends BaseCloudStackApiTest<ConfigurationApi> {\n\n   public void testListCapabilities() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ConfigurationApi.class, \"listCapabilities\");\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&listAll=true&command=listCapabilities HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/DomainAccountApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.jclouds.cloudstack.features.GlobalAccountApiLiveTest.createTestAccount;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.cloudstack.domain.Account;\nimport org.jclouds.cloudstack.domain.AsyncCreateResponse;\nimport org.jclouds.cloudstack.domain.AsyncJob;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code DomainAccountApi}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"DomainAccountApiLiveTest\")\npublic class DomainAccountApiLiveTest extends BaseCloudStackApiLiveTest {\n\n   @Test\n   public void testEnableDisableAccount() {\n      skipIfNotGlobalAdmin();\n\n      Account testAccount = null;\n      try {\n         testAccount = createTestAccount(globalAdminClient, prefix);\n         \n         AsyncCreateResponse response = domainAdminClient.getAccountApi()\n            .disableAccount(testAccount.getName(), testAccount.getDomainId(), false);\n         assertNotNull(response);\n         assertTrue(adminJobComplete.apply(response.getJobId()));\n\n         AsyncJob<Account> job = domainAdminClient.getAsyncJobApi().getAsyncJob(response.getJobId());\n         assertEquals(job.getResult().getState(), Account.State.DISABLED);\n\n         Account updated = domainAdminClient.getAccountApi()\n            .enableAccount(testAccount.getName(), testAccount.getDomainId());\n         assertNotNull(updated);\n         assertEquals(updated.getState(), Account.State.ENABLED);\n\n      } finally {\n         if (testAccount != null) {\n            globalAdminClient.getAccountApi().deleteAccount(testAccount.getId());\n         }\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/DomainAccountApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiTest;\nimport org.jclouds.http.functions.ParseFirstJsonValueNamed;\nimport org.jclouds.http.functions.UnwrapOnlyJsonValue;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.reflect.Invokable;\n/**\n * Tests behavior of {@code DomainAccountApi}\n */\n@Test(groups = \"unit\", testName = \"DomainAccountApiTest\")\npublic class DomainAccountApiTest extends BaseCloudStackApiTest<DomainAccountApi> {\n\n   public void testEnableAccount() throws Exception {\n      Invokable<?, ?> method = method(DomainAccountApi.class, \"enableAccount\", String.class, String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"goo\", \"2\"));\n\n      assertRequestLineEquals(httpRequest,\n         \"GET http://localhost:8080/client/api?response=json&command=enableAccount&account=goo&domainid=2 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testDisableAccount() throws Exception {\n      Invokable<?, ?> method = method(DomainAccountApi.class, \"disableAccount\", String.class, String.class, boolean.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"1\", \"2\", true));\n\n      assertRequestLineEquals(httpRequest,\n         \"GET http://localhost:8080/client/api?response=json&command=disableAccount&account=1&domainid=2&lock=true HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/DomainDomainApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.jclouds.cloudstack.options.ListDomainChildrenOptions.Builder.parentDomainId;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\n\nimport java.net.URI;\n\nimport org.jclouds.cloudstack.CloudStackContext;\nimport org.jclouds.cloudstack.domain.Domain;\nimport org.jclouds.cloudstack.internal.BaseCloudStackExpectTest;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Test the CloudStack DomainDomainApi\n */\n@Test(groups = \"unit\", testName = \"DomainDomainApiExpectTest\")\npublic class DomainDomainApiExpectTest extends BaseCloudStackExpectTest<DomainDomainApi> {\n\n   public void testListDomainsWhenResponseIs2xx() {\n      DomainDomainApi client = requestSendsResponse(\n         HttpRequest.builder()\n            .method(\"GET\")\n            .endpoint(\n               URI.create(\"http://localhost:8080/client/api?response=json&\" +\n                          \"command=listDomains&listAll=true&apiKey=identity&signature=sVFaGTu0DNSTVtWy3wtRt7KTx0w%3D\"))\n            .addHeader(\"Accept\", \"application/json\")\n            .build(),\n         HttpResponse.builder()\n            .statusCode(200)\n            .payload(payloadFromResource(\"/listdomainsresponse.json\"))\n            .build());\n\n      assertEquals(client.listDomains(),\n         ImmutableSet.of(\n            Domain.builder().id(\"1\").name(\"ROOT\").level(0).hasChild(true).build(),\n            Domain.builder().id(\"2\").name(\"jclouds1\").level(1).parentDomainId(\"1\")\n               .parentDomainName(\"ROOT\").hasChild(false).build()\n         ));\n   }\n\n   public void testListDomainsWhenResponseIs404() {\n      DomainDomainApi client = requestSendsResponse(\n         HttpRequest.builder()\n            .method(\"GET\")\n            .endpoint(\n               URI.create(\"http://localhost:8080/client/api?response=json&\" +\n                          \"command=listDomains&listAll=true&apiKey=identity&signature=sVFaGTu0DNSTVtWy3wtRt7KTx0w%3D\"))\n            .addHeader(\"Accept\", \"application/json\")\n            .build(),\n         HttpResponse.builder()\n            .statusCode(404)\n            .build());\n\n      assertEquals(client.listDomains(), ImmutableSet.of());\n   }\n\n   public void testGetDomainWhenResponseIs2xx() {\n      DomainDomainApi client = requestSendsResponse(\n         HttpRequest.builder()\n            .method(\"GET\")\n            .endpoint(\n               URI.create(\"http://localhost:8080/client/api?response=json&\" +\n                          \"command=listDomains&listAll=true&id=1&apiKey=identity&signature=M16YxHWKST/cIRUHvWhfWovJugU%3D\"))\n            .addHeader(\"Accept\", \"application/json\")\n            .build(),\n         HttpResponse.builder()\n            .statusCode(200)\n            .payload(payloadFromResource(\"/getdomainresponse.json\"))\n            .build());\n\n      assertEquals(client.getDomainById(\"1\"),\n         Domain.builder().id(\"1\").name(\"ROOT\").level(0).hasChild(true).build());\n   }\n\n   public void testGetDomainWhenResponseIs404() {\n      DomainDomainApi client = requestSendsResponse(\n         HttpRequest.builder()\n            .method(\"GET\")\n            .endpoint(\n               URI.create(\"http://localhost:8080/client/api?response=json&\" +\n                          \"command=listDomains&listAll=true&id=1&apiKey=identity&signature=M16YxHWKST/cIRUHvWhfWovJugU%3D\"))\n            .addHeader(\"Accept\", \"application/json\")\n            .build(),\n         HttpResponse.builder()\n            .statusCode(404)\n            .build());\n\n      assertNull(client.getDomainById(\"1\"));\n   }\n\n   public void testListDomainChildrenWhenResponseIs2xx() {\n      DomainDomainApi client = requestSendsResponse(\n         HttpRequest.builder()\n            .method(\"GET\")\n            .endpoint(\n               URI.create(\"http://localhost:8080/client/api?response=json&\" +\n                          \"command=listDomainChildren&listAll=true&id=1&isrecursive=true&apiKey=identity&signature=Jn6kFkloRvfaaivlJiHd0F5J3Jk%3D\"))\n            .addHeader(\"Accept\", \"application/json\")\n            .build(),\n         HttpResponse.builder()\n            .statusCode(200)\n            .payload(payloadFromResource(\"/listdomainchildrenresponse.json\"))\n            .build());\n\n      assertEquals(client.listDomainChildren(parentDomainId(\"1\").isRecursive(true)),\n         ImmutableSet.of(\n            Domain.builder().id(\"2\").name(\"jclouds1\").level(1).parentDomainId(\"1\")\n               .parentDomainName(\"ROOT\").hasChild(false).build(),\n            Domain.builder().id(\"3\").name(\"jclouds2\").level(1).parentDomainId(\"1\")\n               .parentDomainName(\"ROOT\").hasChild(false).build()\n         ));\n   }\n\n   public void testListDomainChildrenWhenResponseIs404() {\n      DomainDomainApi client = requestSendsResponse(\n         HttpRequest.builder()\n            .method(\"GET\")\n            .endpoint(\n               URI.create(\"http://localhost:8080/client/api?response=json&\" +\n                  \"command=listDomainChildren&listAll=true&id=1&isrecursive=true&apiKey=identity&\" +\n                          \"signature=Jn6kFkloRvfaaivlJiHd0F5J3Jk%3D\"))\n            .addHeader(\"Accept\", \"application/json\")\n            .build(),\n         HttpResponse.builder()\n            .statusCode(404)\n            .build());\n\n      assertEquals(client.listDomainChildren(parentDomainId(\"1\").isRecursive(true)), ImmutableSet.of());\n   }\n\n   @Override\n   protected DomainDomainApi clientFrom(CloudStackContext context) {\n      return context.getDomainApi().getDomainClient();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/DomainDomainApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static com.google.common.collect.Sets.newHashSet;\nimport static org.jclouds.cloudstack.options.ListDomainChildrenOptions.Builder.parentDomainId;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.NoSuchElementException;\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.Domain;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Sets;\n\n/**\n * Tests behavior of {@code DomainDomainApi}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"DomainDomainApiLiveTest\")\npublic class DomainDomainApiLiveTest extends BaseCloudStackApiLiveTest {\n\n   @Test\n   public void testListDomains() {\n      skipIfNotDomainAdmin();\n\n      Set<Domain> domains = domainAdminClient.getDomainClient().listDomains();\n      for (Domain candidate : domains) {\n         checkDomain(candidate);\n      }\n   }\n\n   private void checkDomain(Domain domain) {\n      assertNotNull(domain.getId());\n      if (domain.getLevel() == 0 /* global ROOT */) {\n         assertNull(domain.getParentDomainName());\n         assertNull(domain.getParentDomainId());\n      } else {\n         assertNotNull(domain.getParentDomainName());\n         assertNotNull(domain.getParentDomainId());\n      }\n   }\n\n   @Test\n   public void testListDomainChildren() {\n      skipIfNotDomainAdmin();\n\n      Set<Domain> domains = domainAdminClient.getDomainClient().listDomains();\n      Domain root = findRootOfVisibleTree(domains);\n      if (domains.size() > 1) {\n         assertTrue(root.hasChild());\n      }\n\n      Set<Domain> children = domainAdminClient.getDomainClient()\n         .listDomainChildren(parentDomainId(root.getId()).isRecursive(true));\n      assertEquals(domains.size() - 1, children.size());\n      assertTrue(Sets.difference(domains, children).contains(root));\n   }\n\n   private Domain findRootOfVisibleTree(Set<Domain> domains) {\n      final Set<String> names = newHashSet(Iterables.transform(domains,\n         new Function<Domain, String>() {\n            @Override\n            public String apply(Domain domain) {\n               return domain.getName();\n            }\n         }));\n\n      for (Domain candidate : domains) {\n         if (candidate.getParentDomainId() == null ||\n            !names.contains(candidate.getParentDomainName())) {\n            return candidate;\n         }\n      }\n      throw new NoSuchElementException(\"No root node found in this tree\");\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/DomainLimitApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code DomainLimitApi}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"DomainLimitApiLiveTest\")\npublic class DomainLimitApiLiveTest extends BaseCloudStackApiLiveTest {\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/DomainLimitApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport java.io.IOException;\n\nimport org.jclouds.cloudstack.domain.ResourceLimit;\nimport org.jclouds.cloudstack.domain.ResourceLimit.ResourceType;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiTest;\nimport org.jclouds.fallbacks.MapHttp4xxCodesToExceptions;\nimport org.jclouds.http.functions.ParseFirstJsonValueNamed;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.reflect.Invokable;\n/**\n * Tests behavior of {@code DomainLimitApi}\n */\n@Test(groups = \"unit\", testName = \"DomainLimitApiTest\")\npublic class DomainLimitApiTest extends BaseCloudStackApiTest<DomainLimitApi> {\n\n   public void testUpdateResourceLimit() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(DomainLimitApi.class, \"updateResourceLimit\", ResourceLimit.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\n            ResourceLimit.builder().resourceType(ResourceType.SNAPSHOT).account(\"foo\").domainId(\"100\").max(101).build()));\n\n      assertRequestLineEquals(\n            httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=updateResourceLimit&resourcetype=3&account=foo&domainid=100&max=101 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/DomainUserApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.jclouds.cloudstack.features.GlobalAccountApiLiveTest.createTestAccount;\nimport static org.jclouds.cloudstack.features.GlobalUserApiLiveTest.createTestUser;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.Account;\nimport org.jclouds.cloudstack.domain.AsyncCreateResponse;\nimport org.jclouds.cloudstack.domain.AsyncJob;\nimport org.jclouds.cloudstack.domain.User;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code DomainUserApi}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"DomainUserApiLiveTest\")\npublic class DomainUserApiLiveTest extends BaseCloudStackApiLiveTest {\n\n   @Test\n   public void testListUsers() {\n      skipIfNotDomainAdmin();\n\n      Set<User> users = domainAdminClient.getUserClient().listUsers();\n\n      assert !users.isEmpty();\n      assert users.contains(user); // contains the current user\n\n      for (User user : users) {\n         checkUser(user);\n      }\n   }\n\n   private void checkUser(User user) {\n      assert user.getId() != null;\n      assert user.getAccount() != null;\n      assert user.getDomain() != null;\n   }\n\n   @Test\n   public void testEnableDisableUser() {\n      skipIfNotGlobalAdmin();\n\n      Account testAccount = null;\n      User testUser = null;\n      try {\n         testAccount = createTestAccount(globalAdminClient, prefix);\n         testUser = createTestUser(globalAdminClient, testAccount, prefix);\n\n         AsyncCreateResponse response = domainAdminClient.getUserClient().disableUser(testUser.getId());\n         assertNotNull(response);\n         assertTrue(adminJobComplete.apply(response.getJobId()));\n\n         AsyncJob<User> job = domainAdminClient.getAsyncJobApi().getAsyncJob(response.getJobId());\n         assertNotNull(job);\n         assertEquals(job.getResult().getState(), User.State.DISABLED);\n\n         User updated = domainAdminClient.getUserClient().enableUser(testUser.getId());\n         assertNotNull(updated);\n         assertEquals(updated.getState(), User.State.ENABLED);\n\n      } finally {\n         if (testUser != null) {\n            globalAdminClient.getUserClient().deleteUser(testUser.getId());\n         }\n         if (testAccount != null) {\n            globalAdminClient.getAccountApi().deleteAccount(testAccount.getId());\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/EventApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.Event;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code EventApi}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"EventApiLiveTest\")\npublic class EventApiLiveTest extends BaseCloudStackApiLiveTest {\n\n   public void testlistEventTypes() throws Exception {\n      final Set<String> response = client.getEventApi().listEventTypes();\n      assert null != response;\n      assertTrue(response.size() > 0);\n      for (String type : response) {\n         checkEventType(type);\n      }\n   }\n\n   public void testlistEvents() throws Exception {\n      final Set<Event> response = client.getEventApi().listEvents();\n      assert null != response;\n      assertTrue(response.size() > 0);\n      for (Event event : response) {\n         checkEvent(event);\n      }\n   }\n\n   private void checkEvent(Event event) {\n      assert event.getAccount() != null : event;\n      assert event.getCreated() != null : event;\n      assert event.getDescription() != null : event;\n      assert event.getDomain() != null : event;\n      assert event.getId() != null : event;\n      assert event.getLevel() != null : event;\n      assert event.getState() != null : event;\n      assert event.getType() != null : event;\n      assert event.getUsername() != null : event;\n   }\n\n   protected void checkEventType(String eventType) {\n      assert eventType != null : eventType;\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/EventApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport java.io.IOException;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.cloudstack.functions.ParseEventTypesFromHttpResponse;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiTest;\nimport org.jclouds.cloudstack.options.ListEventsOptions;\nimport org.jclouds.http.functions.ParseFirstJsonValueNamed;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.reflect.Invokable;\n/**\n * Tests behavior of {@code EventApi}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"EventApiTest\")\npublic class EventApiTest extends BaseCloudStackApiTest<EventApi> {\n\n   public void testListEventTypes() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(EventApi.class, \"listEventTypes\");\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&listAll=true&command=listEventTypes HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseEventTypesFromHttpResponse.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testListEvents() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(EventApi.class, \"listEvents\", ListEventsOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&listAll=true&command=listEvents HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testEventsListOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(EventApi.class, \"listEvents\", ListEventsOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(ListEventsOptions.Builder.account(\"jclouds\")));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&listAll=true&command=listEvents&account=jclouds HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/FirewallApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\n\nimport java.util.Set;\n\nimport com.google.common.collect.ImmutableSet;\nimport org.jclouds.cloudstack.CloudStackContext;\nimport org.jclouds.cloudstack.domain.AsyncCreateResponse;\nimport org.jclouds.cloudstack.domain.FirewallRule;\nimport org.jclouds.cloudstack.domain.PortForwardingRule;\nimport org.jclouds.cloudstack.domain.Tag;\nimport org.jclouds.cloudstack.internal.BaseCloudStackExpectTest;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.Test;\n\n/**\n * Test the CloudStack FirewallApi\n */\n@Test(groups = \"unit\", testName = \"FirewallApiExpectTest\")\npublic class FirewallApiExpectTest extends BaseCloudStackExpectTest<FirewallApi> {\n\n   public void testListFirewallRulesWhenResponseIs2xx() {\n      FirewallApi client = requestSendsResponse(\n            HttpRequest.builder()\n                  .method(\"GET\")\n                  .endpoint(\"http://localhost:8080/client/api\")\n                  .addQueryParam(\"response\", \"json\")\n                  .addQueryParam(\"command\", \"listFirewallRules\")\n                  .addQueryParam(\"listAll\", \"true\")\n                  .addQueryParam(\"apiKey\", \"identity\")\n                  .addQueryParam(\"signature\", \"9+tdTXe2uYLzAexPNgrMy5Tq8hE=\")\n                  .addHeader(\"Accept\", \"application/json\")\n                  .build(),\n            HttpResponse.builder()\n                  .statusCode(200)\n                  .payload(payloadFromResource(\"/listfirewallrulesresponse.json\"))\n                  .build());\n\n      Set<String> CIDRs  = ImmutableSet.of(\"0.0.0.0/0\");\n      assertEquals(client.listFirewallRules(),\n         ImmutableSet.of(\n            FirewallRule.builder().id(\"2017\").protocol(FirewallRule.Protocol.TCP).startPort(30)\n               .endPort(35).ipAddressId(\"2\").ipAddress(\"10.27.27.51\").state(FirewallRule.State.ACTIVE)\n               .CIDRs(CIDRs).build(),\n            FirewallRule.builder().id(\"2016\").protocol(FirewallRule.Protocol.TCP).startPort(22)\n               .endPort(22).ipAddressId(\"2\").ipAddress(\"10.27.27.51\").state(FirewallRule.State.ACTIVE)\n               .CIDRs(CIDRs).build(),\n            FirewallRule.builder().id(\"10\").protocol(FirewallRule.Protocol.TCP).startPort(22)\n            .endPort(22).ipAddressId(\"8\").ipAddress(\"10.27.27.57\").state(FirewallRule.State.ACTIVE)\n               .CIDRs(CIDRs).tags(Tag.builder().account(\"1\").domain(\"ROOT\").domainId(\"1\").key(\"some-tag\").resourceId(\"10\")\n                  .resourceType(Tag.ResourceType.FIREWALL_RULE).value(\"some-value\").build()).build()\n         ));\n   }\n\n   public void testListFirewallRulesWhenReponseIs404() {\n      FirewallApi client = requestSendsResponse(\n         HttpRequest.builder()\n               .method(\"GET\")\n               .endpoint(\"http://localhost:8080/client/api\")\n               .addQueryParam(\"response\", \"json\")\n               .addQueryParam(\"command\", \"listFirewallRules\")\n               .addQueryParam(\"listAll\", \"true\")\n               .addQueryParam(\"apiKey\", \"identity\")\n               .addQueryParam(\"signature\", \"9+tdTXe2uYLzAexPNgrMy5Tq8hE=\")\n               .addHeader(\"Accept\", \"application/json\")\n               .build(),\n         HttpResponse.builder()\n               .statusCode(404)\n               .build());\n\n      assertEquals(client.listFirewallRules(), ImmutableSet.of());\n   }\n\n   public void testGetFirewallRuleWhenResponseIs2xx() {\n      FirewallApi client = requestSendsResponse(\n         HttpRequest.builder()\n               .method(\"GET\")\n               .endpoint(\"http://localhost:8080/client/api\")\n               .addQueryParam(\"response\", \"json\")\n               .addQueryParam(\"command\", \"listFirewallRules\")\n               .addQueryParam(\"listAll\", \"true\")\n               .addQueryParam(\"id\", \"2017\")\n               .addQueryParam(\"apiKey\", \"identity\")\n               .addQueryParam(\"signature\", \"6coh9Qdwla94TN1Dl008WlhzZUY=\")\n               .addHeader(\"Accept\", \"application/json\")\n               .build(),\n         HttpResponse.builder()\n               .statusCode(200)\n               .payload(payloadFromResource(\"/getfirewallrulesresponse.json\"))\n               .build());\n\n      assertEquals(client.getFirewallRule(\"2017\"),\n         FirewallRule.builder().id(\"2017\").protocol(FirewallRule.Protocol.TCP).startPort(30)\n            .endPort(35).ipAddressId(\"2\").ipAddress(\"10.27.27.51\").state(FirewallRule.State.ACTIVE)\n            .CIDRs(ImmutableSet.of(\"0.0.0.0/0\")).build()\n      );\n   }\n\n   public void testGetFirewallRuleWhenResponseIs404() {\n      FirewallApi client = requestSendsResponse(\n         HttpRequest.builder()\n               .method(\"GET\")\n               .endpoint(\"http://localhost:8080/client/api\")\n               .addQueryParam(\"response\", \"json\")\n               .addQueryParam(\"command\", \"listFirewallRules\")\n               .addQueryParam(\"listAll\", \"true\")\n               .addQueryParam(\"id\", \"4\")\n               .addQueryParam(\"apiKey\", \"identity\")\n               .addQueryParam(\"signature\", \"rYd8gr7ptdSZlIehBEMQEKsm07Q=\")\n               .addHeader(\"Accept\", \"application/json\")\n               .build(),\n         HttpResponse.builder()\n               .statusCode(404)\n               .build());\n\n      assertNull(client.getFirewallRule(\"4\"));\n   }\n\n   public void testCreateFirewallRuleForIpAndProtocol() {\n      FirewallApi client = requestSendsResponse(\n         HttpRequest.builder()\n               .method(\"GET\")\n               .endpoint(\"http://localhost:8080/client/api\")\n               .addQueryParam(\"response\", \"json\")\n               .addQueryParam(\"command\", \"createFirewallRule\")\n               .addQueryParam(\"ipaddressid\", \"2\")\n               .addQueryParam(\"protocol\", \"TCP\")\n               .addQueryParam(\"apiKey\", \"identity\")\n               .addQueryParam(\"signature\", \"d0MZ/yhQPAaV+YQmfZsQtQL2C28=\")\n               .addHeader(\"Accept\", \"application/json\")\n               .build(),\n         HttpResponse.builder()\n               .statusCode(200)\n               .payload(payloadFromResource(\"/createfirewallrulesresponse.json\"))\n               .build());\n\n      AsyncCreateResponse response = client.createFirewallRuleForIpAndProtocol(\"2\", FirewallRule.Protocol.TCP);\n      assertEquals(response.getJobId(), \"2036\");\n      assertEquals(response.getId(), \"2017\");\n   }\n\n   public void testDeleteFirewallRule() {\n      FirewallApi client = requestSendsResponse(\n         HttpRequest.builder()\n               .method(\"GET\")\n               .endpoint(\"http://localhost:8080/client/api\")\n               .addQueryParam(\"response\", \"json\")\n               .addQueryParam(\"command\", \"deleteFirewallRule\")\n               .addQueryParam(\"id\", \"2015\")\n               .addQueryParam(\"apiKey\", \"identity\").\n               addQueryParam(\"signature\", \"/T5FAO2yGPctaPmg7TEtIEFW3EU=\")\n               .build(),\n         HttpResponse.builder()\n               .statusCode(200)\n               .payload(payloadFromResource(\"/deletefirewallrulesresponse.json\"))\n               .build());\n\n      client.deleteFirewallRule(\"2015\");\n   }\n\n   public void testListPortForwardingRulesWhenResponseIs2xx() {\n      FirewallApi client = requestSendsResponse(\n         HttpRequest.builder()\n               .method(\"GET\")\n               .endpoint(\"http://localhost:8080/client/api\")\n               .addQueryParam(\"response\", \"json\")\n               .addQueryParam(\"command\", \"listPortForwardingRules\")\n               .addQueryParam(\"listAll\", \"true\")\n               .addQueryParam(\"apiKey\", \"identity\")\n               .addQueryParam(\"signature\", \"8SXGJZWdcJfVz4V90Pyod12x9dM=\")\n               .addHeader(\"Accept\", \"application/json\")\n               .build(),\n         HttpResponse.builder()\n               .statusCode(200)\n               .payload(payloadFromResource(\"/listportforwardingrulesresponse.json\"))\n               .build());\n\n      Set<String> cidrs = ImmutableSet.of(\"0.0.0.0/1\", \"128.0.0.0/1\");\n\n      assertEquals(client.listPortForwardingRules(),\n            ImmutableSet.<PortForwardingRule>of(\n                  PortForwardingRule.builder().id(\"18\").privatePort(22).protocol(PortForwardingRule.Protocol.TCP)\n                        .publicPort(22).virtualMachineId(\"89\").virtualMachineName(\"i-3-89-VM\").IPAddressId(\"34\")\n                        .IPAddress(\"72.52.126.63\").state(PortForwardingRule.State.ACTIVE).build(),\n                  PortForwardingRule.builder().id(\"15\").privatePort(22).protocol(PortForwardingRule.Protocol.TCP)\n                        .publicPort(2022).virtualMachineId(\"3\").virtualMachineName(\"i-3-3-VM\").IPAddressId(\"3\")\n                        .IPAddress(\"72.52.126.32\").state(PortForwardingRule.State.ACTIVE)\n                        .CIDRs(cidrs).tags(Tag.builder().account(\"1\").domain(\"ROOT\").domainId(\"1\").key(\"some-tag\").resourceId(\"15\")\n                        .resourceType(Tag.ResourceType.PORT_FORWARDING_RULE).value(\"some-value\").build()).build()\n                  )\n      );\n   }\n\n   public void testListPortForwardingRulesWhenReponseIs404() {\n      FirewallApi client = requestSendsResponse(\n         HttpRequest.builder()\n               .method(\"GET\")\n               .endpoint(\"http://localhost:8080/client/api\")\n               .addQueryParam(\"response\", \"json\")\n               .addQueryParam(\"command\", \"listPortForwardingRules\")\n               .addQueryParam(\"listAll\", \"true\")\n               .addQueryParam(\"apiKey\", \"identity\")\n               .addQueryParam(\"signature\", \"8SXGJZWdcJfVz4V90Pyod12x9dM=\")\n               .addHeader(\"Accept\", \"application/json\")\n               .build(),\n         HttpResponse.builder()\n               .statusCode(404)\n               .build());\n\n      assertEquals(client.listPortForwardingRules(), ImmutableSet.of());\n   }\n\n   public void testGetPortForwardingRuleWhenResponseIs2xx() {\n      FirewallApi client = requestSendsResponse(\n         HttpRequest.builder()\n               .method(\"GET\")\n               .endpoint(\"http://localhost:8080/client/api\").addQueryParam(\"response\", \"json\")\n               .addQueryParam(\"command\", \"listPortForwardingRules\")\n               .addQueryParam(\"listAll\", \"true\")\n               .addQueryParam(\"id\", \"15\")\n               .addQueryParam(\"apiKey\", \"identity\")\n               .addQueryParam(\"signature\", \"JL63p6cJzbb9vaffeV4u60IGlWE=\")\n               .addHeader(\"Accept\", \"application/json\")\n               .build(),\n         HttpResponse.builder()\n               .statusCode(200)\n               .payload(payloadFromResource(\"/getportforwardingrulesresponse.json\"))\n               .build());\n\n      Set<String> cidrs = ImmutableSet.of(\"0.0.0.0/1\", \"128.0.0.0/1\");\n\n      assertEquals(client.getPortForwardingRule(\"15\"),\n            PortForwardingRule.builder().id(\"15\").privatePort(22).protocol(PortForwardingRule.Protocol.TCP)\n                  .publicPort(2022).virtualMachineId(\"3\").virtualMachineName(\"i-3-3-VM\").IPAddressId(\"3\")\n                  .IPAddress(\"72.52.126.32\").state(PortForwardingRule.State.ACTIVE)\n                  .CIDRs(cidrs).tags(Tag.builder().account(\"1\").domain(\"ROOT\").domainId(\"1\").key(\"some-tag\").resourceId(\"15\")\n                  .resourceType(Tag.ResourceType.PORT_FORWARDING_RULE).value(\"some-value\").build()).build());\n   }\n\n   public void testGetPortForwardingRuleWhenResponseIs404() {\n      FirewallApi client = requestSendsResponse(\n         HttpRequest.builder()\n               .method(\"GET\")\n               .endpoint(\"http://localhost:8080/client/api\").addQueryParam(\"response\", \"json\")\n               .addQueryParam(\"command\", \"listPortForwardingRules\")\n               .addQueryParam(\"listAll\", \"true\")\n               .addQueryParam(\"id\", \"4\")\n               .addQueryParam(\"apiKey\", \"identity\")\n               .addQueryParam(\"signature\", \"4blbBVn2+ZfF8HwoglbmtYoDAjs=\")\n               .addHeader(\"Accept\", \"application/json\")\n               .build(),\n         HttpResponse.builder()\n               .statusCode(404)\n               .build());\n\n      assertNull(client.getPortForwardingRule(\"4\"));\n   }\n\n   public void testCreatePortForwardingRuleForVirtualMachine() {\n      FirewallApi client = requestSendsResponse(\n         HttpRequest.builder().method(\"GET\")\n               .endpoint(\"http://localhost:8080/client/api\")\n               .addQueryParam(\"response\", \"json\")\n               .addQueryParam(\"command\", \"createPortForwardingRule\")\n               .addQueryParam(\"ipaddressid\", \"2\")\n               .addQueryParam(\"protocol\", \"tcp\")\n               .addQueryParam(\"publicport\", \"22\")\n               .addQueryParam(\"virtualmachineid\", \"1234\")\n               .addQueryParam(\"privateport\", \"22\")\n               .addQueryParam(\"apiKey\", \"identity\")\n               .addQueryParam(\"signature\", \"84dtGzQp0G6k3z3Gkc3F/HBNS2Y=\")\n               .addHeader(\"Accept\", \"application/json\")\n               .build(),\n         HttpResponse.builder()\n               .statusCode(200)\n               .payload(payloadFromResource(\"/createportforwardingrulesresponse.json\"))\n               .build());\n\n      AsyncCreateResponse response = client.createPortForwardingRuleForVirtualMachine(\n         \"2\", PortForwardingRule.Protocol.TCP, 22, \"1234\", 22);\n      assertEquals(response.getJobId(), \"2035\");\n      assertEquals(response.getId(), \"2015\");\n   }\n\n   public void testDeletePortForwardingRule() {\n      FirewallApi client = requestSendsResponse(\n         HttpRequest.builder()\n               .method(\"GET\")\n               .endpoint(\"http://localhost:8080/client/api\")\n               .addQueryParam(\"response\", \"json\")\n               .addQueryParam(\"command\", \"deletePortForwardingRule\")\n               .addQueryParam(\"id\", \"2015\")\n               .addQueryParam(\"apiKey\", \"identity\")\n               .addQueryParam(\"signature\", \"2UE7KB3wm5ocmR+GMNFKPKfiDo8=\")\n               .build(),\n         HttpResponse.builder()\n               .statusCode(200)\n               .payload(payloadFromResource(\"/deleteportforwardingrulesresponse.json\"))\n               .build());\n\n      client.deletePortForwardingRule(\"2015\");\n   }\n\n   public void testListEgressFirewallRulesWhenResponseIs2xx() {\n      FirewallApi client = requestSendsResponse(\n              HttpRequest.builder()\n                    .method(\"GET\")\n                    .endpoint(\"http://localhost:8080/client/api\")\n                    .addQueryParam(\"response\", \"json\")\n                    .addQueryParam(\"command\", \"listEgressFirewallRules\")\n                    .addQueryParam(\"listAll\", \"true\")\n                    .addQueryParam(\"apiKey\", \"identity\")\n                    .addQueryParam(\"signature\", \"j3OpRXs7mEwVKs9KIb4ncRKVO9A=\")\n                    .addHeader(\"Accept\", \"application/json\")\n                    .build(),\n              HttpResponse.builder()\n                    .statusCode(200)\n                    .payload(payloadFromResource(\"/listegressfirewallrulesresponse.json\"))\n                    .build());\n\n      Set<String> CIDRs  = ImmutableSet.of(\"0.0.0.0/0\");\n      assertEquals(client.listEgressFirewallRules(),\n              ImmutableSet.of(\n                    FirewallRule.builder().id(\"2017\").protocol(FirewallRule.Protocol.TCP).startPort(30)\n                          .endPort(35).ipAddressId(\"2\").ipAddress(\"10.27.27.51\").state(FirewallRule.State.ACTIVE)\n                          .CIDRs(CIDRs).build(),\n                    FirewallRule.builder().id(\"2016\").protocol(FirewallRule.Protocol.TCP).startPort(22)\n                          .endPort(22).ipAddressId(\"2\").ipAddress(\"10.27.27.51\").state(FirewallRule.State.ACTIVE)\n                          .CIDRs(CIDRs).build(),\n                    FirewallRule.builder().id(\"10\").protocol(FirewallRule.Protocol.TCP).startPort(22)\n                          .endPort(22).ipAddressId(\"8\").ipAddress(\"10.27.27.57\").state(FirewallRule.State.ACTIVE)\n                          .CIDRs(CIDRs).tags(Tag.builder().account(\"1\").domain(\"ROOT\").domainId(\"1\").key(\"some-tag\").resourceId(\"10\")\n                          .resourceType(Tag.ResourceType.FIREWALL_RULE).value(\"some-value\").build()).build()\n              ));\n   }\n\n   public void testListEgressFirewallRulesWhenReponseIs404() {\n      FirewallApi client = requestSendsResponse(\n              HttpRequest.builder()\n                    .method(\"GET\")\n                    .endpoint(\"http://localhost:8080/client/api\")\n                    .addQueryParam(\"response\", \"json\")\n                    .addQueryParam(\"command\", \"listEgressFirewallRules\")\n                    .addQueryParam(\"listAll\", \"true\")\n                    .addQueryParam(\"apiKey\", \"identity\")\n                    .addQueryParam(\"signature\", \"j3OpRXs7mEwVKs9KIb4ncRKVO9A=\")\n                    .addHeader(\"Accept\", \"application/json\")\n                    .build(),\n              HttpResponse.builder()\n                    .statusCode(404)\n                    .build());\n\n      assertEquals(client.listEgressFirewallRules(), ImmutableSet.of());\n   }\n\n   public void testGetEgressFirewallRuleWhenResponseIs2xx() {\n      FirewallApi client = requestSendsResponse(\n              HttpRequest.builder()\n                    .method(\"GET\")\n                    .endpoint(\"http://localhost:8080/client/api\")\n                    .addQueryParam(\"response\", \"json\")\n                    .addQueryParam(\"command\", \"listEgressFirewallRules\")\n                    .addQueryParam(\"listAll\", \"true\")\n                    .addQueryParam(\"id\", \"2017\")\n                    .addQueryParam(\"apiKey\", \"identity\")\n                    .addQueryParam(\"signature\", \"Hi1K5VA3yd3mk0AmgJ2F6y+VzMo=\")\n                    .addHeader(\"Accept\", \"application/json\")\n                    .build(),\n              HttpResponse.builder()\n                    .statusCode(200)\n                    .payload(payloadFromResource(\"/getegressfirewallrulesresponse.json\"))\n                    .build());\n\n      assertEquals(client.getEgressFirewallRule(\"2017\"),\n              FirewallRule.builder().id(\"2017\").protocol(FirewallRule.Protocol.TCP).startPort(30)\n                      .endPort(35).ipAddressId(\"2\").ipAddress(\"10.27.27.51\").state(FirewallRule.State.ACTIVE)\n                      .CIDRs(ImmutableSet.of(\"0.0.0.0/0\")).build()\n      );\n   }\n\n   public void testGetEgressFirewallRuleWhenResponseIs404() {\n      FirewallApi client = requestSendsResponse(\n              HttpRequest.builder()\n                    .method(\"GET\")\n                    .endpoint(\"http://localhost:8080/client/api\")\n                    .addQueryParam(\"response\", \"json\")\n                    .addQueryParam(\"command\", \"listEgressFirewallRules\")\n                    .addQueryParam(\"listAll\", \"true\")\n                    .addQueryParam(\"id\", \"4\")\n                    .addQueryParam(\"apiKey\", \"identity\")\n                    .addQueryParam(\"signature\", \"dzb5azKxXZsuGrNRJbRHfna7FMo=\")\n                    .addHeader(\"Accept\", \"application/json\")\n                    .build(),\n              HttpResponse.builder()\n                    .statusCode(404)\n                    .build());\n\n      assertNull(client.getEgressFirewallRule(\"4\"));\n   }\n\n   public void testCreateEgressFirewallRuleForNetworkAndProtocol() {\n      FirewallApi client = requestSendsResponse(\n              HttpRequest.builder()\n                    .method(\"GET\")\n                    .endpoint(\"http://localhost:8080/client/api\")\n                    .addQueryParam(\"response\", \"json\")\n                    .addQueryParam(\"command\", \"createEgressFirewallRule\")\n                    .addQueryParam(\"networkid\", \"2\")\n                    .addQueryParam(\"protocol\", \"TCP\")\n                    .addQueryParam(\"apiKey\", \"identity\")\n                    .addQueryParam(\"signature\", \"I/OJEqiLp8ZHlZskKUiT5uTRE3M=\")\n                    .addHeader(\"Accept\", \"application/json\")\n                    .build(),\n              HttpResponse.builder()\n                    .statusCode(200)\n                    .payload(payloadFromResource(\"/createegressfirewallrulesresponse.json\"))\n                    .build());\n\n      AsyncCreateResponse response = client.createEgressFirewallRuleForNetworkAndProtocol(\"2\", FirewallRule.Protocol.TCP);\n      assertEquals(response.getJobId(), \"2036\");\n      assertEquals(response.getId(), \"2017\");\n   }\n\n   public void testDeleteEgressFirewallRule() {\n      FirewallApi client = requestSendsResponse(\n              HttpRequest.builder()\n                    .method(\"GET\")\n                    .endpoint(\"http://localhost:8080/client/api\")\n                    .addQueryParam(\"response\", \"json\")\n                    .addQueryParam(\"command\", \"deleteEgressFirewallRule\")\n                    .addQueryParam(\"id\", \"2015\")\n                    .addQueryParam(\"apiKey\", \"identity\")\n                    .addQueryParam(\"signature\", \"S119WNmamKwc5d9qvvkIJznXytg=\")\n                    .build(),\n              HttpResponse.builder()\n                    .statusCode(200)\n                    .payload(payloadFromResource(\"/deleteegressfirewallrulesresponse.json\"))\n                    .build());\n\n      client.deleteEgressFirewallRule(\"2015\");\n   }\n   @Override\n   protected FirewallApi clientFrom(CloudStackContext context) {\n      return context.getApi().getFirewallApi();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/FirewallApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static com.google.common.collect.Iterables.find;\nimport static org.jclouds.cloudstack.predicates.NetworkPredicates.supportsPortForwarding;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.NoSuchElementException;\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.AsyncCreateResponse;\nimport org.jclouds.cloudstack.domain.FirewallRule;\nimport org.jclouds.cloudstack.domain.Network;\nimport org.jclouds.cloudstack.domain.PortForwardingRule;\nimport org.jclouds.cloudstack.domain.PublicIPAddress;\nimport org.jclouds.cloudstack.domain.VirtualMachine;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest;\nimport org.jclouds.cloudstack.options.CreateFirewallRuleOptions;\nimport org.jclouds.logging.Logger;\nimport org.testng.annotations.AfterGroups;\nimport org.testng.annotations.BeforeGroups;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Predicates;\nimport com.google.common.net.HostAndPort;\n\n/**\n * Tests behavior of {@code FirewallApiLiveTest}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"FirewallApiLiveTest\")\npublic class FirewallApiLiveTest extends BaseCloudStackApiLiveTest {\n   private PublicIPAddress ip = null;\n   private VirtualMachine vm;\n\n   private FirewallRule firewallRule;\n   private FirewallRule egressFirewallRule;\n   private PortForwardingRule portForwardingRule;\n\n   private Network network;\n   private boolean networksDisabled;\n\n   @BeforeGroups(groups = \"live\")\n   public void setupContext() {\n      super.setupContext();\n      prefix += \"rule\";\n      try {\n         network = find(client.getNetworkApi().listNetworks(), Predicates.and(supportsPortForwarding(),\n            new Predicate<Network>() {\n               @Override\n               public boolean apply(Network network) {\n                  return network.isDefault()\n                     && !network.isSecurityGroupEnabled()\n                     && network.getAccount().equals(user.getAccount());\n               }\n            }));\n\n         String defaultTemplate = templateBuilderSpec != null ? templateBuilderSpec.getImageId() : null;\n\n         vm = VirtualMachineApiLiveTest.createVirtualMachineInNetwork(network,\n            defaultTemplateOrPreferredInZone(defaultTemplate, client, network.getZoneId()),\n            client, jobComplete, virtualMachineRunning);\n\n         if (vm.getPassword() != null && !loginCredentials.getOptionalPassword().isPresent())\n            loginCredentials = loginCredentials.toBuilder().password(vm.getPassword()).build();\n\n      } catch (NoSuchElementException e) {\n         networksDisabled = true;\n      }\n   }\n\n   public void testCreatePortForwardingRule() throws Exception {\n      if (networksDisabled)\n         return;\n      while (portForwardingRule == null) {\n         ip = reuseOrAssociate.apply(network);\n         try {\n            AsyncCreateResponse job = client.getFirewallApi()\n               .createPortForwardingRuleForVirtualMachine(ip.getId(), PortForwardingRule.Protocol.TCP, 22, vm.getId(), 22);\n            assertTrue(jobComplete.apply(job.getJobId()));\n            portForwardingRule = client.getFirewallApi().getPortForwardingRule(job.getId());\n\n         } catch (IllegalStateException e) {\n            Logger.CONSOLE.error(\"Failed while trying to allocate ip: \" + e);\n            // very likely an ip conflict, so retry;\n         }\n      }\n\n      assertEquals(portForwardingRule.getIPAddressId(), ip.getId());\n      assertEquals(portForwardingRule.getVirtualMachineId(), vm.getId());\n      assertEquals(portForwardingRule.getPublicPort(), 22);\n      assertEquals(portForwardingRule.getProtocol(), PortForwardingRule.Protocol.TCP);\n\n      checkPortForwardingRule(portForwardingRule);\n      checkSSH(HostAndPort.fromParts(ip.getIPAddress(), 22));\n   }\n\n   @Test(dependsOnMethods = \"testCreatePortForwardingRule\")\n   public void testListPortForwardingRules() throws Exception {\n      Set<PortForwardingRule> response = client.getFirewallApi().listPortForwardingRules();\n      assert null != response;\n      assertTrue(response.size() > 0);\n      for (final PortForwardingRule rule : response) {\n         checkPortForwardingRule(rule);\n      }\n   }\n\n   @Test(dependsOnMethods = \"testCreatePortForwardingRule\")\n   public void testCreateFirewallRule() {\n      if (networksDisabled)\n         return;\n\n      AsyncCreateResponse job = client.getFirewallApi().createFirewallRuleForIpAndProtocol(\n         ip.getId(), FirewallRule.Protocol.TCP, CreateFirewallRuleOptions.Builder.startPort(30).endPort(35));\n      assertTrue(jobComplete.apply(job.getJobId()));\n      firewallRule = client.getFirewallApi().getFirewallRule(job.getId());\n\n      assertEquals(firewallRule.getStartPort(), 30);\n      assertEquals(firewallRule.getEndPort(), 35);\n      assertEquals(firewallRule.getProtocol(), FirewallRule.Protocol.TCP);\n\n      checkFirewallRule(firewallRule);\n   }\n\n   @Test(dependsOnMethods = \"testCreateFirewallRule\")\n   public void testListFirewallRules() {\n      Set<FirewallRule> rules = client.getFirewallApi().listFirewallRules();\n\n      assert rules != null;\n      assertTrue(!rules.isEmpty());\n\n      for (FirewallRule rule : rules) {\n         checkFirewallRule(rule);\n      }\n   }\n\n   @Test(dependsOnMethods = \"testCreatePortForwardingRule\")\n   public void testCreateEgressFirewallRule() {\n      if (networksDisabled)\n         return;\n\n      AsyncCreateResponse job = client.getFirewallApi().createEgressFirewallRuleForNetworkAndProtocol(\n              network.getId(), FirewallRule.Protocol.TCP, CreateFirewallRuleOptions.Builder.startPort(30).endPort(35));\n      assertTrue(jobComplete.apply(job.getJobId()));\n      egressFirewallRule = client.getFirewallApi().getEgressFirewallRule(job.getId());\n\n      assertEquals(egressFirewallRule.getStartPort(), 30);\n      assertEquals(egressFirewallRule.getEndPort(), 35);\n      assertEquals(egressFirewallRule.getProtocol(), FirewallRule.Protocol.TCP);\n\n      checkEgressFirewallRule(egressFirewallRule);\n   }\n\n   @Test(dependsOnMethods = \"testCreateEgressFirewallRule\")\n   public void testListEgressFirewallRules() {\n      Set<FirewallRule> rules = client.getFirewallApi().listEgressFirewallRules();\n\n      assert rules != null;\n      assertTrue(!rules.isEmpty());\n\n      for (FirewallRule rule : rules) {\n         checkEgressFirewallRule(rule);\n      }\n   }\n   @AfterGroups(groups = \"live\")\n   @Override\n   protected void tearDownContext() {\n      if (firewallRule != null) {\n         client.getFirewallApi().deleteFirewallRule(firewallRule.getId());\n      }\n      if (egressFirewallRule != null) {\n         client.getFirewallApi().deleteEgressFirewallRule(egressFirewallRule.getId());\n      }\n      if (portForwardingRule != null) {\n         client.getFirewallApi().deletePortForwardingRule(portForwardingRule.getId());\n      }\n      if (vm != null) {\n         jobComplete.apply(client.getVirtualMachineApi().destroyVirtualMachine(vm.getId()));\n      }\n      if (ip != null) {\n         client.getAddressApi().disassociateIPAddress(ip.getId());\n      }\n      super.tearDownContext();\n   }\n\n   protected void checkFirewallRule(FirewallRule rule) {\n      assertEquals(rule,\n         client.getFirewallApi().getFirewallRule(rule.getId()));\n      assert rule.getId() != null : rule;\n      assert rule.getStartPort() > 0 : rule;\n      assert rule.getEndPort() >= rule.getStartPort() : rule;\n      assert rule.getProtocol() != null;\n   }\n\n   protected void checkEgressFirewallRule(FirewallRule rule) {\n      assertEquals(rule,\n              client.getFirewallApi().getEgressFirewallRule(rule.getId()));\n      assert rule.getId() != null : rule;\n      assert rule.getStartPort() > 0 : rule;\n      assert rule.getEndPort() >= rule.getStartPort() : rule;\n      assert rule.getProtocol() != null;\n   }\n\n   protected void checkPortForwardingRule(PortForwardingRule rule) {\n      assertEquals(rule,\n         client.getFirewallApi().getPortForwardingRule(rule.getId()));\n      assert rule.getId() != null : rule;\n      assert rule.getIPAddress() != null : rule;\n      assert rule.getIPAddressId() != null : rule;\n      assert rule.getPrivatePort() > 0 : rule;\n      assert rule.getProtocol() != null : rule;\n      assert rule.getPublicPort() > 0 : rule;\n      assert rule.getState() != null : rule;\n      assert rule.getVirtualMachineId() != null : rule;\n      assert rule.getVirtualMachineName() != null : rule;\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/FirewallApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport java.io.IOException;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.cloudstack.domain.PortForwardingRule;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiTest;\nimport org.jclouds.cloudstack.options.ListPortForwardingRulesOptions;\nimport org.jclouds.fallbacks.MapHttp4xxCodesToExceptions;\nimport org.jclouds.http.functions.ParseFirstJsonValueNamed;\nimport org.jclouds.http.functions.ReleasePayloadAndReturn;\nimport org.jclouds.http.functions.UnwrapOnlyJsonValue;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.reflect.Invokable;\n/**\n * Tests behavior of {@code FirewallApi}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"FirewallApiTest\")\npublic class FirewallApiTest extends BaseCloudStackApiTest<FirewallApi> {\n   public void testListPortForwardingRules() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(FirewallApi.class, \"listPortForwardingRules\",\n            ListPortForwardingRulesOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listPortForwardingRules&listAll=true HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testListPortForwardingRulesOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(FirewallApi.class, \"listPortForwardingRules\",\n            ListPortForwardingRulesOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(ListPortForwardingRulesOptions.Builder.ipAddressId(\"3\")));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listPortForwardingRules&listAll=true&ipaddressid=3 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testCreatePortForwardingRuleForVirtualMachine() throws SecurityException, NoSuchMethodException,\n         IOException {\n      Invokable<?, ?> method = method(FirewallApi.class, \"createPortForwardingRuleForVirtualMachine\", String.class,\n            PortForwardingRule.Protocol.class, int.class, String.class, int.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"6\", PortForwardingRule.Protocol.TCP, 22, \"7\", 22));\n\n      assertRequestLineEquals(\n            httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=createPortForwardingRule&ipaddressid=6&protocol=tcp&publicport=22&virtualmachineid=7&privateport=22 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testDeletePortForwardingRule() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(FirewallApi.class, \"deletePortForwardingRule\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(5));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=deletePortForwardingRule&id=5 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, VoidOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/GlobalAccountApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.hash.Hashing.md5;\nimport static com.google.common.io.BaseEncoding.base16;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport org.jclouds.cloudstack.CloudStackGlobalApi;\nimport org.jclouds.cloudstack.domain.Account;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code GlobalAccountApi}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"GlobalAccountApiLiveTest\")\npublic class GlobalAccountApiLiveTest extends BaseCloudStackApiLiveTest {\n\n   public static Account createTestAccount(CloudStackGlobalApi client, String prefix) {\n      return client.getAccountApi().createAccount(prefix + \"-account\", Account.Type.USER, \"dummy@example.com\",\n            \"First\", \"Last\", base16().lowerCase().encode(md5().hashString(\"password\", UTF_8).asBytes()));\n   }\n\n   @Test\n   public void testCreateAndRemoveAccount() {\n      skipIfNotGlobalAdmin();\n\n      Account account = null;\n      try {\n         account = createTestAccount(globalAdminClient, prefix);\n\n         assertNotNull(account);\n         assertEquals(account.getName(), prefix + \"-account\");\n         assertEquals(account.getType(), Account.Type.USER);\n\n         Account updated = globalAdminClient.getAccountApi().updateAccount(\n            account.getName(), account.getDomainId(), prefix + \"-account-2\");\n\n         assertNotNull(updated);\n         assertEquals(updated.getName(), prefix + \"-account-2\");\n\n      } finally {\n         if (account != null) {\n            globalAdminClient.getAccountApi().deleteAccount(account.getId());\n         }\n      }\n\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/GlobalAccountApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.cloudstack.domain.Account;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiTest;\nimport org.jclouds.cloudstack.options.CreateAccountOptions;\nimport org.jclouds.cloudstack.options.UpdateAccountOptions;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.functions.ParseFirstJsonValueNamed;\nimport org.jclouds.http.functions.ReleasePayloadAndReturn;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.reflect.Invokable;\n/**\n * Tests behavior of {@code GlobalAccountApi}\n */\n@Test(groups = \"unit\", testName = \"GlobalAccountApiTest\")\npublic class GlobalAccountApiTest extends BaseCloudStackApiTest<GlobalAccountApi> {\n\n   HttpRequest create = HttpRequest.builder().method(\"GET\")\n                                   .endpoint(\"http://localhost:8080/client/api\")\n                                   .addQueryParam(\"response\", \"json\")\n                                   .addQueryParam(\"command\", \"createAccount\")\n                                   .addQueryParam(\"username\", \"user\")\n                                   .addQueryParam(\"accounttype\", \"0\")\n                                   .addQueryParam(\"email\", \"email@example.com\")\n                                   .addQueryParam(\"firstname\", \"FirstName\")\n                                   .addQueryParam(\"lastname\", \"LastName\")\n                                   .addQueryParam(\"password\", \"hashed-password\")\n                                   .build();\n\n   public void testCreateAccount() throws Exception {\n      Invokable<?, ?> method = method(GlobalAccountApi.class, \"createAccount\", String.class, Account.Type.class,\n         String.class, String.class, String.class, String.class, CreateAccountOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"user\", Account.Type.USER, \"email@example.com\",\n         \"FirstName\", \"LastName\", \"hashed-password\"));\n\n      assertRequestLineEquals(httpRequest, create.getRequestLine());\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n   }\n\n   HttpRequest update = HttpRequest.builder().method(\"GET\")\n                                   .endpoint(\"http://localhost:8080/client/api\")\n                                   .addQueryParam(\"response\", \"json\")\n                                   .addQueryParam(\"command\", \"updateAccount\")\n                                   .addQueryParam(\"account\", \"account\")\n                                   .addQueryParam(\"domainid\", \"42\")\n                                   .addQueryParam(\"newname\", \"new-account-name\")\n                                   .build();\n\n   public void testUpdateAccount() throws Exception {\n      Invokable<?, ?> method = method(GlobalAccountApi.class, \"updateAccount\", String.class, String.class,\n         String.class, UpdateAccountOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"account\", 42L, \"new-account-name\"));\n\n      assertRequestLineEquals(httpRequest, update.getRequestLine());\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testDeleteAccount() throws Exception {\n      Invokable<?, ?> method = method(GlobalAccountApi.class, \"deleteAccount\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(42L));\n\n      assertRequestLineEquals(httpRequest,\n         \"GET http://localhost:8080/client/api?response=json&command=deleteAccount&id=42 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/GlobalAlertApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNotSame;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.Alert;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code GlobalAlertsClient}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"GlobalAlertApiLiveTest\")\npublic class GlobalAlertApiLiveTest extends BaseCloudStackApiLiveTest {\n\n   @Test(groups = \"live\", enabled = true)\n   public void testListAlerts() throws Exception {\n      skipIfNotGlobalAdmin();\n\n      final Set<Alert> response = globalAdminClient.getAlertClient().listAlerts();\n      assert null != response;\n      assertTrue(response.size() > 0);\n      int count = 0;\n      for (Alert alert : response) {\n         assertNotNull(alert.getDescription());\n         assertNotSame(alert.getId(), 0);\n         assertNotNull(alert.getType());\n         assertNotNull(alert.getSent());\n         count++;\n      }\n      assertTrue(count > 0, \"No alerts were returned, so I couldn't test\");\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/GlobalAlertApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport java.io.IOException;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiTest;\nimport org.jclouds.cloudstack.options.ListAlertsOptions;\nimport org.jclouds.http.functions.ParseFirstJsonValueNamed;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.reflect.Invokable;\n/**\n * Tests behavior of {@code GlobalAlertsClient}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"GlobalAlertApiTest\")\npublic class GlobalAlertApiTest extends BaseCloudStackApiTest<GlobalAlertApi> {\n\n   public void testListAlerts() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(GlobalAlertApi.class, \"listAlerts\", ListAlertsOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listAlerts&listAll=true HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testListAlertsOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(GlobalAlertApi.class, \"listAlerts\", ListAlertsOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(ListAlertsOptions.Builder.id(\"42\").keyword(\"jclouds\").type(\"TEMPLATE\")));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listAlerts&listAll=true&id=42&keyword=jclouds&type=TEMPLATE HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/GlobalCapacityApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.testng.Assert.assertNotEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.Capacity;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code GlobalCapacityApi}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"GlobalCapacityApiLiveTest\")\npublic class GlobalCapacityApiLiveTest extends BaseCloudStackApiLiveTest {\n\n   @Test(groups = \"live\", enabled = true)\n   public void testListCapacity() throws Exception {\n      skipIfNotGlobalAdmin();\n\n      final Set<Capacity> response = globalAdminClient.getCapacityClient().listCapacity();\n      assertNotNull(response);\n      assertNotEquals(0, response.size());\n      int count = 0;\n      for (Capacity capacity : response) {\n         assertTrue(capacity.getCapacityTotal() >= 0);\n         assertTrue(capacity.getCapacityUsed() >= 0);\n         assertTrue(capacity.getPercentUsed() >= 0);\n         assertNotEquals(Capacity.Type.UNRECOGNIZED, capacity.getType());\n         assertNotNull(capacity.getZoneName());\n         count++;\n      }\n      assertTrue(count > 0, \"No capacities were returned, so I couldn't test\");\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/GlobalCapacityApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport java.io.IOException;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.cloudstack.domain.Capacity;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiTest;\nimport org.jclouds.cloudstack.options.ListCapacityOptions;\nimport org.jclouds.http.functions.ParseFirstJsonValueNamed;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.reflect.Invokable;\n/**\n * Tests behavior of {@code GlobalCapacityApi}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"GlobalCapacityApiTest\")\npublic class GlobalCapacityApiTest extends BaseCloudStackApiTest<GlobalCapacityApi> {\n\n   public void testListCapacity() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(GlobalCapacityApi.class, \"listCapacity\", ListCapacityOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listCapacity&listAll=true HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testListCapacityOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(GlobalCapacityApi.class, \"listCapacity\", ListCapacityOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(ListCapacityOptions.Builder.hostId(\"3\").keyword(\"fred\").podId(\"4\").type(Capacity.Type.CPU_ALLOCATED_MHZ).zoneId(\"6\")));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listCapacity&listAll=true&hostid=3&keyword=fred&podid=4&type=1&zoneid=6 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/GlobalConfigurationApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\n\nimport java.net.URI;\n\nimport org.jclouds.cloudstack.CloudStackContext;\nimport org.jclouds.cloudstack.domain.ConfigurationEntry;\nimport org.jclouds.cloudstack.internal.BaseCloudStackExpectTest;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Test the CloudStack GlobalConfigurationApi\n */\n@Test(groups = \"unit\", testName = \"GlobalConfigurationApiExpectTest\")\npublic class GlobalConfigurationApiExpectTest extends BaseCloudStackExpectTest<GlobalConfigurationApi> {\n\n   @Test\n   public void testListConfigurationEntriesWhenResponseIs2xx() {\n      GlobalConfigurationApi client = requestSendsResponse(\n         HttpRequest.builder()\n            .method(\"GET\")\n            .endpoint(\n               URI.create(\"http://localhost:8080/client/api?response=json&\" +\n                  \"command=listConfigurations&listAll=true&apiKey=identity&signature=%2BJ9mTuw%2BZXaumzMAJAXgZQaO2cc%3D\"))\n            .addHeader(\"Accept\", \"application/json\")\n            .build(),\n         HttpResponse.builder()\n            .statusCode(200)\n            .payload(payloadFromResource(\"/listconfigurationsresponse.json\"))\n            .build());\n\n      assertEquals(client.listConfigurationEntries(),\n         ImmutableSet.of(\n            ConfigurationEntry.builder().category(\"Advanced\").name(\"account.cleanup.interval\").value(\"86400\")\n               .description(\"The interval (in seconds) between cleanup for removed accounts\").build(),\n            ConfigurationEntry.builder().category(\"Advanced\").name(\"agent.lb.enabled\").value(\"true\")\n               .description(\"If agent load balancing enabled in cluster setup\").build()\n         ));\n   }\n\n   @Test\n   public void testListConfigurationEntriesEmptyOn404() {\n      GlobalConfigurationApi client = requestSendsResponse(\n         HttpRequest.builder()\n            .method(\"GET\")\n            .endpoint(\n               URI.create(\"http://localhost:8080/client/api?response=json&\" +\n                  \"command=listConfigurations&listAll=true&apiKey=identity&signature=%2BJ9mTuw%2BZXaumzMAJAXgZQaO2cc%3D\"))\n            .addHeader(\"Accept\", \"application/json\")\n            .build(),\n         HttpResponse.builder()\n            .statusCode(404)\n            .build());\n\n      assertEquals(client.listConfigurationEntries(), ImmutableSet.of());\n   }\n\n   @Test\n   public void testUpdateConfigurationEntryWhenResponseIs2xx() {\n      GlobalConfigurationApi client = requestSendsResponse(\n         HttpRequest.builder()\n            .method(\"GET\")\n            .endpoint(\n               URI.create(\"http://localhost:8080/client/api?response=json&\" +\n                  \"command=updateConfiguration&name=expunge.delay&value=11&\" +\n                  \"apiKey=identity&signature=I2yG35EhfgIXYObeLfU3cvf%2BPeE%3D\"))\n            .addHeader(\"Accept\", \"application/json\")\n            .build(),\n         HttpResponse.builder()\n            .statusCode(200)\n            .payload(payloadFromResource(\"/updateconfigurationsresponse.json\"))\n            .build());\n\n      assertEquals(client.updateConfigurationEntry(\"expunge.delay\", \"11\"),\n         ConfigurationEntry.builder().category(\"Advanced\").name(\"expunge.delay\").value(\"11\")\n            .description(\"Determines how long (in seconds) to wait before actually expunging \" +\n               \"destroyed vm. The default value = the default value of expunge.interval\").build()\n      );\n   }\n\n   @Test\n   public void testUpdateConfigurationEntryNullOn404() {\n      GlobalConfigurationApi client = requestSendsResponse(\n         HttpRequest.builder()\n            .method(\"GET\")\n            .endpoint(\n               URI.create(\"http://localhost:8080/client/api?response=json&\" +\n                  \"command=updateConfiguration&name=expunge.delay&value=11&\" +\n                  \"apiKey=identity&signature=I2yG35EhfgIXYObeLfU3cvf%2BPeE%3D\"))\n            .addHeader(\"Accept\", \"application/json\")\n            .build(),\n         HttpResponse.builder()\n            .statusCode(404)\n            .build());\n\n      assertNull(client.updateConfigurationEntry(\"expunge.delay\", \"11\"));\n   }\n\n   @Override\n   protected GlobalConfigurationApi clientFrom(CloudStackContext context) {\n      return context.getGlobalApi().getConfigurationApi();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/GlobalConfigurationApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static org.jclouds.cloudstack.options.ListConfigurationEntriesOptions.Builder.name;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.ConfigurationEntry;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest;\nimport org.testng.annotations.Test;\nimport org.testng.collections.Sets;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\n\n/**\n * Tests behavior of {@code GlobalConfigurationApi}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"GlobalConfigurationApiLiveTest\")\npublic class GlobalConfigurationApiLiveTest extends BaseCloudStackApiLiveTest {\n\n   @Test\n   public void testListConfigurationEntries() {\n      skipIfNotGlobalAdmin();\n\n      Set<ConfigurationEntry> entries = globalAdminClient\n         .getConfigurationApi().listConfigurationEntries();\n\n      Set<String> categories = Sets.newHashSet();\n      for (ConfigurationEntry entry : entries) {\n         checkConfigurationEntry(entry);\n         categories.add(entry.getCategory());\n      }\n\n      assert categories.containsAll(ImmutableSet.<Object>of(\"Network\", \"Advanced\",\n         \"Storage\", \"Usage\", \"Snapshots\", \"Account Defaults\", \"Console Proxy\", \"Alert\"));\n   }\n\n   @Test\n   public void testUpdateConfigurationEntry() {\n      skipIfNotGlobalAdmin();\n\n      Set<ConfigurationEntry> entries = globalAdminClient\n         .getConfigurationApi().listConfigurationEntries();\n\n      long expungeDelay = Long.parseLong(getValueByName(entries, \"expunge.delay\"));\n      assert expungeDelay > 0;\n\n      globalAdminClient.getConfigurationApi()\n         .updateConfigurationEntry(\"expunge.delay\", \"\" + (expungeDelay + 1));\n\n      long newDelay = Long.parseLong(getOnlyElement(globalAdminClient.getConfigurationApi()\n         .listConfigurationEntries(name(\"expunge.delay\"))).getValue());\n      assertEquals(newDelay, expungeDelay + 1);\n\n      globalAdminClient.getConfigurationApi()\n         .updateConfigurationEntry(\"expunge.delay\", \"\" + expungeDelay);\n   }\n\n   private void checkConfigurationEntry(ConfigurationEntry entry) {\n      assertEquals(entry, getEntryByName(globalAdminClient.getConfigurationApi()\n         .listConfigurationEntries(name(entry.getName())), entry.getName()));\n      assert entry.getCategory() != null : entry;\n      // Description apparently can be null, so ... assert entry.getDescription() != null : entry;\n      assert entry.getName() != null : entry;\n   }\n\n   private String getValueByName(Set<ConfigurationEntry> entries, String name) {\n      return getEntryByName(entries, name).getValue();\n   }\n\n   private ConfigurationEntry getEntryByName(Set<ConfigurationEntry> entries, final String name) {\n      return Iterables.find(entries, new Predicate<ConfigurationEntry>() {\n         @Override\n         public boolean apply(ConfigurationEntry entry) {\n            return entry != null && Objects.equal(name, entry.getName());\n         }\n      });\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/GlobalDomainApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.jclouds.cloudstack.options.UpdateDomainOptions.Builder.name;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\n\nimport java.net.URI;\n\nimport org.jclouds.cloudstack.CloudStackContext;\nimport org.jclouds.cloudstack.domain.Domain;\nimport org.jclouds.cloudstack.internal.BaseCloudStackExpectTest;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.Test;\n\n/**\n * Test the CloudStack GlobalDomainApi\n */\n@Test(groups = \"unit\", testName = \"GlobalDomainApiExpectTest\")\npublic class GlobalDomainApiExpectTest extends BaseCloudStackExpectTest<GlobalDomainApi> {\n\n   public void testCreateDomainWhenResponseIs2xx() {\n      GlobalDomainApi client = requestSendsResponse(\n         HttpRequest.builder()\n            .method(\"GET\")\n            .endpoint(\n               URI.create(\"http://localhost:8080/client/api?response=json&command=createDomain&\" +\n                  \"name=test&apiKey=identity&signature=6cxzEo7h63G0hgTTMLm4lGsSDK8%3D\"))\n            .addHeader(\"Accept\", \"application/json\")\n            .build(),\n         HttpResponse.builder()\n            .statusCode(200)\n            .payload(payloadFromResource(\"/createdomainresponse.json\"))\n            .build());\n\n      assertEquals(client.createDomain(\"test\"),\n         Domain.builder().id(\"10\").name(\"test\").level(1).parentDomainId(\"1\")\n            .parentDomainName(\"ROOT\").hasChild(false).build());\n   }\n\n   public void testCreateDomainWhenResponseIs404() {\n      GlobalDomainApi client = requestSendsResponse(\n         HttpRequest.builder()\n            .method(\"GET\")\n            .endpoint(\n               URI.create(\"http://localhost:8080/client/api?response=json&command=createDomain&\" +\n                  \"name=test&apiKey=identity&signature=6cxzEo7h63G0hgTTMLm4lGsSDK8%3D\"))\n            .addHeader(\"Accept\", \"application/json\")\n            .build(),\n         HttpResponse.builder()\n            .statusCode(404)\n            .build());\n\n      assertNull(client.createDomain(\"test\"));\n   }\n\n   public void testUpdateDomainWhenResponseIs2xx() {\n      GlobalDomainApi client = requestSendsResponse(\n         HttpRequest.builder()\n            .method(\"GET\")\n            .endpoint(\n               URI.create(\"http://localhost:8080/client/api?response=json&\" +\n                  \"command=updateDomain&id=10&name=test-2&apiKey=identity&signature=5t1eUf2Eyf/aB6qt%2BqIj%2BmcwFIo%3D\"))\n            .addHeader(\"Accept\", \"application/json\")\n            .build(),\n         HttpResponse.builder()\n            .statusCode(200)\n            .payload(payloadFromResource(\"/updatedomainresponse.json\"))\n            .build());\n\n      assertEquals(client.updateDomain(\"10\", name(\"test-2\")),\n         Domain.builder().id(\"10\").name(\"test-2\").level(1).parentDomainId(\"1\")\n            .parentDomainName(\"ROOT\").hasChild(false).build());\n   }\n\n   public void testUpdateDomainWhenResponseIs404() {\n      GlobalDomainApi client = requestSendsResponse(\n         HttpRequest.builder()\n            .method(\"GET\")\n            .endpoint(\n               URI.create(\"http://localhost:8080/client/api?response=json&\" +\n                  \"command=updateDomain&id=10&name=test-2&apiKey=identity&signature=5t1eUf2Eyf/aB6qt%2BqIj%2BmcwFIo%3D\"))\n            .addHeader(\"Accept\", \"application/json\")\n            .build(),\n         HttpResponse.builder()\n            .statusCode(404)\n            .build());\n\n      assertNull(client.updateDomain(\"10\", name(\"test-2\")));\n   }\n\n   public void testDeleteOnlyDomain() {\n      GlobalDomainApi client = requestSendsResponse(\n         HttpRequest.builder()\n            .method(\"GET\")\n            .endpoint(\n               URI.create(\"http://localhost:8080/client/api?response=json&\" +\n                  \"command=deleteDomain&cleanup=false&id=1&apiKey=identity&signature=/5aLbigg612t9IrZi0JZO7CyiOU%3D\"))\n            .build(),\n         HttpResponse.builder()\n            .statusCode(200)\n            .payload(payloadFromResource(\"/deletedomainresponse.json\"))\n            .build());\n\n      client.deleteOnlyDomain(\"1\");\n   }\n\n   public void testDeleteDomainAndAttachedResources() {\n      GlobalDomainApi client = requestSendsResponse(\n         HttpRequest.builder()\n            .method(\"GET\")\n            .endpoint(\n               URI.create(\"http://localhost:8080/client/api?response=json&\" +\n                  \"command=deleteDomain&cleanup=true&id=1&apiKey=identity&signature=grL7JStvtYUT89Jr0D8FgwMyJpU%3D\"))\n            .build(),\n         HttpResponse.builder()\n            .statusCode(200)\n            .payload(payloadFromResource(\"/deletedomainresponse.json\"))\n            .build());\n\n      client.deleteDomainAndAttachedResources(\"1\");\n   }\n\n   @Override\n   protected GlobalDomainApi clientFrom(CloudStackContext context) {\n      return context.getGlobalApi().getDomainClient();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/GlobalDomainApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static com.google.common.collect.Iterables.find;\nimport static org.jclouds.cloudstack.options.UpdateDomainOptions.Builder.name;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\n\nimport org.jclouds.cloudstack.domain.Domain;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest;\nimport org.testng.annotations.BeforeMethod;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\n\n/**\n * Tests behavior of {@code GlobalDomainApi}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"GlobalDomainApiLiveTest\")\npublic class GlobalDomainApiLiveTest extends BaseCloudStackApiLiveTest {\n\n   private GlobalDomainApi domainClient;\n   private Domain rootDomain;\n\n   @BeforeMethod\n   public void before() {\n      domainClient = globalAdminClient.getDomainClient();\n      rootDomain = find(domainClient.listDomains(), new Predicate<Domain>() {\n         @Override\n         public boolean apply(Domain domain) {\n            return domain != null && domain.getName().equals(\"ROOT\");\n         }\n      });\n   }\n\n   @Test(expectedExceptions = IllegalStateException.class)\n   public void testCreateUpdateDeleteDomain() throws InterruptedException {\n      skipIfNotDomainAdmin();\n\n      Domain domain = null;\n      try {\n         domain = domainClient.createDomain(prefix + \"-domain\");\n         checkDomain(domain, rootDomain, prefix + \"-domain\");\n\n         Domain updated = domainClient.updateDomain(domain.getId(), name(prefix + \"-domain-2\"));\n         checkDomain(updated, rootDomain, prefix + \"-domain-2\");\n         assertEquals(updated.getId(), domain.getId());\n\n      } finally {\n         if (domain != null) {\n            domainClient.deleteDomainAndAttachedResources(domain.getId());\n         }\n      }\n      Thread.sleep(5000);\n      assertNull(domainClient.getDomainById(domain.getId()));\n   }\n\n   private void checkDomain(Domain domain, Domain rootDomain, String expectedName) {\n      assertEquals(domain.getParentDomainId(), rootDomain.getId());\n      assertEquals(domain.getName(), expectedName);\n      assertEquals(domain.getParentDomainName(), rootDomain.getName());\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/GlobalHostApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Calendar;\nimport java.util.Date;\nimport java.util.Set;\nimport java.util.TimeZone;\n\nimport org.jclouds.cloudstack.CloudStackContext;\nimport org.jclouds.cloudstack.domain.AllocationState;\nimport org.jclouds.cloudstack.domain.Cluster;\nimport org.jclouds.cloudstack.domain.Host;\nimport org.jclouds.cloudstack.internal.BaseCloudStackExpectTest;\nimport org.jclouds.cloudstack.options.AddClusterOptions;\nimport org.jclouds.cloudstack.options.AddHostOptions;\nimport org.jclouds.cloudstack.options.AddSecondaryStorageOptions;\nimport org.jclouds.cloudstack.options.DeleteHostOptions;\nimport org.jclouds.cloudstack.options.UpdateClusterOptions;\nimport org.jclouds.cloudstack.options.UpdateHostOptions;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Test the CloudStack GlobalHostApi\n */\n@Test(groups = \"unit\", testName = \"GlobalConfigurationApiExpectTest\")\npublic class GlobalHostApiExpectTest extends BaseCloudStackExpectTest<GlobalHostApi> {\n\n   @Test\n   public void testListHostsWhenResponseIs2xx() {\n      HttpRequest request = HttpRequest.builder()\n         .method(\"GET\")\n         .endpoint(\"http://localhost:8080/client/api?response=json&command=listHosts&listAll=true&apiKey=identity&signature=NnYyyEy30G3V2dcIt7w4WZ68AU8%3D\")\n         .addHeader(\"Accept\", \"application/json\").build();\n      HttpResponse response = HttpResponse.builder()\n         .payload(payloadFromResource(\"/listhostsresponse.json\"))\n         .statusCode(200).build();\n\n      Set<Host> actual = requestSendsResponse(request, response).listHosts();\n\n      Date lastPinged = makeDate(1970, Calendar.JANUARY, 16, 0, 54, 43, \"GMT+02:00\");\n      Date created = makeDate(2011, Calendar.NOVEMBER, 26, 23, 28, 36, \"GMT+02:00\");\n      Host host1 = Host.builder().id(\"1\").name(\"cs2-xevsrv.alucloud.local\").state(Host.State.UP).type(Host.Type.ROUTING).ipAddress(\"10.26.26.107\").zoneId(\"1\").zoneName(\"Dev Zone 1\").podId(\"1\").podName(\"Dev Pod 1\").version(\"2.2.12.20110928142833\").hypervisor(\"XenServer\").cpuNumber(24).cpuSpeed(2266).cpuAllocated(\"2.76%\").cpuUsed(\"0.1%\").cpuWithOverProvisioning(54384.0F).networkKbsRead(4443).networkKbsWrite(15048).memoryTotal(100549733760L).memoryAllocated(3623878656L).memoryUsed(3623878656L).capabilities(\"xen-3.0-x86_64 , xen-3.0-x86_32p , hvm-3.0-x86_32 , hvm-3.0-x86_32p , hvm-3.0-x86_64\").lastPinged(lastPinged).managementServerId(\"223098941760041\").clusterId(\"1\").clusterName(\"Xen Clust 1\").clusterType(Host.ClusterType.CLOUD_MANAGED).localStorageActive(false).created(created).events(\"PrepareUnmanaged; HypervisorVersionChanged; ManagementServerDown; PingTimeout; AgentDisconnected; MaintenanceRequested; HostDown; AgentConnected; StartAgentRebalance; ShutdownRequested; Ping\").hasEnoughCapacity(false).allocationState(AllocationState.ENABLED).build();\n\n      Date disconnected = makeDate(2011, Calendar.NOVEMBER, 26, 23, 33, 38, \"GMT+02:00\");\n      lastPinged = makeDate(1970, Calendar.JANUARY, 16, 0, 42, 30, \"GMT+02:00\");\n      created = makeDate(2011, Calendar.NOVEMBER, 26, 23, 33, 38, \"GMT+02:00\");\n      Host host2 = Host.builder().id(\"2\").name(\"nfs://10.26.26.165/mnt/nfs/cs_sec\").state(Host.State.ALERT).disconnected(disconnected).type(Host.Type.SECONDARY_STORAGE).ipAddress(\"nfs\").zoneId(\"1\").zoneName(\"Dev Zone 1\").version(\"2.2.12.20110928142833\").hypervisor(\"None\").lastPinged(lastPinged).localStorageActive(false).created(created).events(\"ManagementServerDown; AgentDisconnected; Remove; MaintenanceRequested; AgentConnected; Ping\").hasEnoughCapacity(false).allocationState(AllocationState.ENABLED).build();\n\n      lastPinged = makeDate(1970, Calendar.JANUARY, 16, 0, 54, 43, \"GMT+02:00\");\n      created = makeDate(2011, Calendar.NOVEMBER, 26, 23, 35, 51, \"GMT+02:00\");\n      Host host3 = Host.builder().id(\"3\").name(\"s-1-VM\").state(Host.State.UP).type(Host.Type.SECONDARY_STORAGE_VM).ipAddress(\"10.26.26.81\").zoneId(\"1\").zoneName(\"Dev Zone 1\").podId(\"1\").podName(\"Dev Pod 1\").version(\"2.2.12.20110928142833\").lastPinged(lastPinged).managementServerId(\"223098941760041\").localStorageActive(false).created(created).events(\"PrepareUnmanaged; HypervisorVersionChanged; ManagementServerDown; PingTimeout; AgentDisconnected; MaintenanceRequested; HostDown; AgentConnected; StartAgentRebalance; ShutdownRequested; Ping\").hasEnoughCapacity(false).allocationState(AllocationState.ENABLED).build();\n\n      lastPinged = makeDate(1970, Calendar.JANUARY, 16, 0, 54, 43, \"GMT+02:00\");\n      created = makeDate(2011, Calendar.NOVEMBER, 26, 23, 36, 46, \"GMT+02:00\");\n      Host host4 = Host.builder().id(\"4\").name(\"v-2-VM\").state(Host.State.UP).type(Host.Type.CONSOLE_PROXY).ipAddress(\"10.26.26.96\").zoneId(\"1\").zoneName(\"Dev Zone 1\").podId(\"1\").podName(\"Dev Pod 1\").version(\"2.2.12.20110928142833\").lastPinged(lastPinged).managementServerId(\"223098941760041\").localStorageActive(false).created(created).events(\"PrepareUnmanaged; HypervisorVersionChanged; ManagementServerDown; PingTimeout; AgentDisconnected; MaintenanceRequested; HostDown; AgentConnected; StartAgentRebalance; ShutdownRequested; Ping\").hasEnoughCapacity(false).allocationState(AllocationState.ENABLED).build();\n\n      Set<Host> expected = ImmutableSet.of(host1, host2, host3, host4);\n\n      assertEquals(actual, expected);\n   }\n\n   @Test\n   public void testListHostsEmptyOn404() {\n      HttpRequest request = HttpRequest.builder()\n         .method(\"GET\")\n         .endpoint(\"http://localhost:8080/client/api?response=json&command=listHosts&listAll=true&apiKey=identity&signature=NnYyyEy30G3V2dcIt7w4WZ68AU8%3D\")\n         .addHeader(\"Accept\", \"application/json\").build();\n      HttpResponse response = HttpResponse.builder().statusCode(404).build();\n      GlobalHostApi client = requestSendsResponse(request, response);\n\n      assertEquals(client.listHosts(), ImmutableSet.of());\n   }\n\n   HttpRequest addHost = HttpRequest.builder().method(\"GET\")\n                                    .endpoint(\"http://localhost:8080/client/api\")\n                                    .addQueryParam(\"response\", \"json\")\n                                    .addQueryParam(\"command\", \"addHost\")\n                                    .addQueryParam(\"zoneid\", \"1\")\n                                    .addQueryParam(\"url\", \"http://example.com\")\n                                    .addQueryParam(\"hypervisor\", \"XenServer\")\n                                    .addQueryParam(\"username\", \"fred\")\n                                    .addQueryParam(\"password\", \"sekrit\")\n                                    .addQueryParam(\"hosttags\", \"\")\n                                    .addQueryParam(\"allocationstate\", \"Enabled\")\n                                    .addQueryParam(\"clusterid\", \"1\")\n                                    .addQueryParam(\"clustername\", \"Xen Clust 1\")\n                                    .addQueryParam(\"podid\", \"1\")\n                                    .addQueryParam(\"apiKey\", \"identity\")\n                                    .addQueryParam(\"signature\", \"ExGaljKKQIlVbWk5hd0BnnjmBzs=\")\n                                    .addHeader(\"Accept\", \"application/json\").build();\n\n   @Test\n   public void testAddHostWhenResponseIs2xx() {\n      HttpResponse response = HttpResponse.builder()\n         .payload(payloadFromResource(\"/addhostresponse.json\"))\n         .statusCode(200).build();\n\n      Date lastPinged = makeDate(1970, Calendar.JANUARY, 16, 0, 54, 43, \"GMT+02:00\");\n      Date created = makeDate(2011, Calendar.NOVEMBER, 26, 23, 28, 36, \"GMT+02:00\");\n      Host expected = Host.builder().id(\"1\").name(\"cs2-xevsrv.alucloud.local\").state(Host.State.UP).type(Host.Type.ROUTING).ipAddress(\"10.26.26.107\").zoneId(\"1\").zoneName(\"Dev Zone 1\").podId(\"1\").podName(\"Dev Pod 1\").version(\"2.2.12.20110928142833\").hypervisor(\"XenServer\").cpuNumber(24).cpuSpeed(2266).cpuAllocated(\"2.76%\").cpuUsed(\"0.1%\").cpuWithOverProvisioning(54384.0F).networkKbsRead(4443).networkKbsWrite(15048).memoryTotal(100549733760L).memoryAllocated(3623878656L).memoryUsed(3623878656L).capabilities(\"xen-3.0-x86_64 , xen-3.0-x86_32p , hvm-3.0-x86_32 , hvm-3.0-x86_32p , hvm-3.0-x86_64\").lastPinged(lastPinged).managementServerId(\"223098941760041\").clusterId(\"1\").clusterName(\"Xen Clust 1\").clusterType(Host.ClusterType.CLOUD_MANAGED).localStorageActive(false).created(created).events(\"PrepareUnmanaged; HypervisorVersionChanged; ManagementServerDown; PingTimeout; AgentDisconnected; MaintenanceRequested; HostDown; AgentConnected; StartAgentRebalance; ShutdownRequested; Ping\").hasEnoughCapacity(false).allocationState(AllocationState.ENABLED).build();\n\n      Host actual = requestSendsResponse(addHost, response).addHost(\"1\", \"http://example.com\", \"XenServer\", \"fred\", \"sekrit\",\n         AddHostOptions.Builder.hostTags(ImmutableSet.<String>of()).allocationState(AllocationState.ENABLED).clusterId(\"1\").clusterName(\"Xen Clust 1\").podId(\"1\"));\n\n      assertEquals(actual, expected);\n   }\n\n   @Test\n   public void testUpdateHostWhenResponseIs2xx() {\n      HttpRequest request = HttpRequest.builder()\n         .method(\"GET\")\n         .endpoint(\"http://localhost:8080/client/api?response=json&command=updateHost&id=1&allocationstate=Enabled&hosttags=&oscategoryid=5&apiKey=identity&signature=qTxNq9yQG8S108giqS/ROFzgev8%3D\")\n         .addHeader(\"Accept\", \"application/json\").build();\n      HttpResponse response = HttpResponse.builder()\n         .payload(payloadFromResource(\"/updatehostresponse.json\"))\n         .statusCode(200).build();\n\n      Date lastPinged = makeDate(1970, Calendar.JANUARY, 16, 0, 54, 43, \"GMT+02:00\");\n      Date created = makeDate(2011, Calendar.NOVEMBER, 26, 23, 28, 36, \"GMT+02:00\");\n      Host expected = Host.builder().id(\"1\").name(\"cs2-xevsrv.alucloud.local\").state(Host.State.UP).type(Host.Type.ROUTING).ipAddress(\"10.26.26.107\").zoneId(\"1\").zoneName(\"Dev Zone 1\").podId(\"1\").podName(\"Dev Pod 1\").version(\"2.2.12.20110928142833\").hypervisor(\"XenServer\").cpuNumber(24).cpuSpeed(2266).cpuAllocated(\"2.76%\").cpuUsed(\"0.1%\").cpuWithOverProvisioning(54384.0F).networkKbsRead(4443).networkKbsWrite(15048).memoryTotal(100549733760L).memoryAllocated(3623878656L).memoryUsed(3623878656L).capabilities(\"xen-3.0-x86_64 , xen-3.0-x86_32p , hvm-3.0-x86_32 , hvm-3.0-x86_32p , hvm-3.0-x86_64\").lastPinged(lastPinged).managementServerId(\"223098941760041\").clusterId(\"1\").clusterName(\"Xen Clust 1\").clusterType(Host.ClusterType.CLOUD_MANAGED).localStorageActive(false).created(created).events(\"PrepareUnmanaged; HypervisorVersionChanged; ManagementServerDown; PingTimeout; AgentDisconnected; MaintenanceRequested; HostDown; AgentConnected; StartAgentRebalance; ShutdownRequested; Ping\").hasEnoughCapacity(false).allocationState(AllocationState.ENABLED).build();\n\n      Host actual = requestSendsResponse(request, response).updateHost(\"1\", UpdateHostOptions.Builder.allocationState(AllocationState.ENABLED).hostTags(ImmutableSet.<String>of()).osCategoryId(\"5\"));\n\n      assertEquals(actual, expected);\n   }\n\n   HttpRequest updateHostPassword = HttpRequest.builder().method(\"GET\")\n                                               .endpoint(\"http://localhost:8080/client/api\")\n                                               .addQueryParam(\"response\", \"json\")\n                                               .addQueryParam(\"command\", \"updateHostPassword\")\n                                               .addQueryParam(\"hostid\", \"1\")\n                                               .addQueryParam(\"username\", \"fred\")\n                                               .addQueryParam(\"password\", \"sekrit\")\n                                               .addQueryParam(\"apiKey\", \"identity\")\n                                               .addQueryParam(\"signature\", \"g9nMKDWoiU72y0HhaRFekZCgfJc=\")\n                                               .addHeader(\"Accept\", \"application/json\").build();\n\n   @Test\n   public void testUpdateHostPasswordWhenResponseIs2xx() {\n      HttpResponse response = HttpResponse.builder()\n         .statusCode(200).build();\n      requestSendsResponse(updateHostPassword, response).updateHostPassword(\"1\", \"fred\", \"sekrit\");\n   }\n\n   @Test\n   public void testDeleteHostWhenResponseIs2xx() {\n      HttpRequest request = HttpRequest.builder()\n         .method(\"GET\")\n         .endpoint(\"http://localhost:8080/client/api?response=json&command=deleteHost&id=1&forced=true&forcedestroylocalstorage=true&apiKey=identity&signature=ZdvO1BWBkdPiDAjsVlKtqDe6N7k%3D\")\n         .addHeader(\"Accept\", \"application/json\")\n         .build();\n      HttpResponse response = HttpResponse.builder()\n         .statusCode(200).build();\n\n      requestSendsResponse(request, response).deleteHost(\"1\", DeleteHostOptions.Builder.forced(true).forceDestroyLocalStorage(true));\n   }\n\n   @Test\n   public void testPrepareHostForMaintenanceWhenResponseIs2xx() {\n      HttpRequest request = HttpRequest.builder()\n         .method(\"GET\")\n         .endpoint(\"http://localhost:8080/client/api?response=json&command=prepareHostForMaintenance&id=1&apiKey=identity&signature=9tDwdox/xAKmZr9kVrR6Ttnxf3U%3D\")\n         .addHeader(\"Accept\", \"application/json\").build();\n      HttpResponse response = HttpResponse.builder()\n         .payload(payloadFromResource(\"/preparehostformaintenanceresponse.json\"))\n         .statusCode(200).build();\n\n      String actual = requestSendsResponse(request, response).prepareHostForMaintenance(\"1\");\n      assertEquals(actual, \"2036\");\n   }\n\n   @Test\n   public void testCancelHostMaintenanceWhenResponseIs2xx() {\n      HttpRequest request = HttpRequest.builder()\n         .method(\"GET\")\n         .endpoint(\"http://localhost:8080/client/api?response=json&command=cancelHostMaintenance&id=1&apiKey=identity&signature=9RduzuBoyRZKNTzAoVqUo9gRTfk%3D\")\n         .addHeader(\"Accept\", \"application/json\").build();\n      HttpResponse response = HttpResponse.builder()\n         .payload(payloadFromResource(\"/cancelhostmaintenanceresponse.json\"))\n         .statusCode(200).build();\n\n      String actual = requestSendsResponse(request, response).cancelHostMaintenance(\"1\");\n      assertEquals(actual, \"2036\");\n   }\n\n   @Test\n   public void testReconnectHostWhenResponseIs2xx() {\n      HttpRequest request = HttpRequest.builder()\n         .method(\"GET\")\n         .endpoint(\"http://localhost:8080/client/api?response=json&command=reconnectHost&id=1&apiKey=identity&signature=wJEF02vwdyOnJOTa%2BWMMK906aRU%3D\")\n         .addHeader(\"Accept\", \"application/json\").build();\n      HttpResponse response = HttpResponse.builder()\n         .payload(payloadFromResource(\"/reconnecthostresponse.json\"))\n         .statusCode(200).build();\n\n      String actual = requestSendsResponse(request, response).reconnectHost(\"1\");\n      assertEquals(actual, \"2036\");\n   }\n\n   @Test\n   public void testAddSecondaryStorageWhenResponseIs2xx() {\n      HttpRequest request = HttpRequest.builder()\n         .method(\"GET\")\n         .endpoint(\"http://localhost:8080/client/api?response=json&command=addSecondaryStorage&url=nfs%3A//10.26.26.165/mnt/nfs/cs_sec&zoneid=1&apiKey=identity&signature=MccRKx1yPP43ImiO70WlhVDlAIA%3D\")\n         .addHeader(\"Accept\", \"application/json\").build();\n      HttpResponse response = HttpResponse.builder()\n         .payload(payloadFromResource(\"/addsecondarystorageresponse.json\"))\n         .statusCode(200).build();\n\n      Date disconnected = makeDate(2011, Calendar.NOVEMBER, 26, 23, 33, 38, \"GMT+02:00\");\n      Date lastPinged = makeDate(1970, Calendar.JANUARY, 16, 0, 42, 30, \"GMT+02:00\");\n      Date created = makeDate(2011, Calendar.NOVEMBER, 26, 23, 33, 38, \"GMT+02:00\");\n      Host expected = Host.builder().id(\"2\").name(\"nfs://10.26.26.165/mnt/nfs/cs_sec\").state(Host.State.ALERT).disconnected(disconnected).type(Host.Type.SECONDARY_STORAGE).ipAddress(\"nfs\").zoneId(\"1\").zoneName(\"Dev Zone 1\").version(\"2.2.12.20110928142833\").hypervisor(\"None\").lastPinged(lastPinged).localStorageActive(false).created(created).events(\"ManagementServerDown; AgentDisconnected; Remove; MaintenanceRequested; AgentConnected; Ping\").hasEnoughCapacity(false).allocationState(AllocationState.ENABLED).build();\n\n      Host actual = requestSendsResponse(request, response).addSecondaryStorage(\"nfs://10.26.26.165/mnt/nfs/cs_sec\", AddSecondaryStorageOptions.Builder.zoneId(\"1\"));\n\n      assertEquals(actual, expected);\n   }\n\n   @Test\n   public void testListClustersWhenResponseIs2xx() {\n      HttpRequest request = HttpRequest.builder()\n         .method(\"GET\")\n         .endpoint(\"http://localhost:8080/client/api?response=json&command=listClusters&listAll=true&apiKey=identity&signature=lbimqg0OKIq8sgQBpNmi4oQNFog%3D\")\n         .addHeader(\"Accept\", \"application/json\").build();\n      HttpResponse response = HttpResponse.builder()\n         .payload(payloadFromResource(\"/listclustersresponse.json\"))\n         .statusCode(200).build();\n\n      Set<Cluster> actual = requestSendsResponse(request, response).listClusters();\n\n      Cluster cluster1 = Cluster.builder().id(\"1\").name(\"Xen Clust 1\").podId(\"1\").podName(\"Dev Pod 1\").zoneId(\"1\").zoneName(\"Dev Zone 1\").hypervisor(\"XenServer\").clusterType(Host.ClusterType.CLOUD_MANAGED).allocationState(AllocationState.ENABLED).managedState(Cluster.ManagedState.MANAGED).build();\n      Cluster cluster2 = Cluster.builder().id(\"2\").name(\"Xen Clust 1\").podId(\"2\").podName(\"Dev Pod 2\").zoneId(\"2\").zoneName(\"Dev Zone 2\").hypervisor(\"XenServer\").clusterType(Host.ClusterType.CLOUD_MANAGED).allocationState(AllocationState.ENABLED).managedState(Cluster.ManagedState.MANAGED).build();\n      ImmutableSet<Cluster> expected = ImmutableSet.of(cluster1, cluster2);\n\n      assertEquals(actual, expected);\n   }\n\n   @Test\n   public void testListClustersEmptyOn404() {\n      HttpRequest request = HttpRequest.builder()\n         .method(\"GET\")\n         .endpoint(\"http://localhost:8080/client/api?response=json&command=listClusters&listAll=true&apiKey=identity&signature=lbimqg0OKIq8sgQBpNmi4oQNFog%3D\")\n         .addHeader(\"Accept\", \"application/json\").build();\n      HttpResponse response = HttpResponse.builder().statusCode(404).build();\n      GlobalHostApi client = requestSendsResponse(request, response);\n\n      assertEquals(client.listClusters(), ImmutableSet.of());\n   }\n\n   HttpRequest addCluster = HttpRequest.builder().method(\"GET\")\n                                       .endpoint(\"http://localhost:8080/client/api\")\n                                       .addQueryParam(\"response\", \"json\")\n                                       .addQueryParam(\"command\", \"addCluster\")\n                                       .addQueryParam(\"zoneid\", \"1\")\n                                       .addQueryParam(\"clustername\", \"Xen Clust 1\")\n                                       .addQueryParam(\"clustertype\", \"CloudManaged\")\n                                       .addQueryParam(\"hypervisor\", \"XenServer\")\n                                       .addQueryParam(\"allocationstate\", \"Enabled\")\n                                       .addQueryParam(\"podid\", \"1\")\n                                       .addQueryParam(\"url\", \"http://example.com/cluster\")\n                                       .addQueryParam(\"username\", \"fred\")\n                                       .addQueryParam(\"password\", \"sekrit\")\n                                       .addQueryParam(\"apiKey\", \"identity\")\n                                       .addQueryParam(\"signature\", \"2uIQ5qF0bVycXK111wxvogWp1Yw=\")\n                                       .addHeader(\"Accept\", \"application/json\").build();\n\n   @Test\n   public void testAddClusterWhenResponseIs2xx() {\n      HttpResponse response = HttpResponse.builder()\n         .payload(payloadFromResource(\"/addclusterresponse.json\"))\n         .statusCode(200).build();\n\n      Cluster expected = Cluster.builder().id(\"1\").name(\"Xen Clust 1\").podId(\"1\").podName(\"Dev Pod 1\").zoneId(\"1\").zoneName(\"Dev Zone 1\").hypervisor(\"XenServer\").clusterType(Host.ClusterType.CLOUD_MANAGED).allocationState(AllocationState.ENABLED).managedState(Cluster.ManagedState.MANAGED).build();\n\n      Cluster actual = requestSendsResponse(addCluster, response).addCluster(\"1\", \"Xen Clust 1\", Host.ClusterType.CLOUD_MANAGED, \"XenServer\", AddClusterOptions.Builder.allocationState(AllocationState.ENABLED).podId(\"1\").url(\"http://example.com/cluster\").username(\"fred\").password(\"sekrit\"));\n\n      assertEquals(actual, expected);\n   }\n\n   HttpRequest updateCluster = HttpRequest.builder().method(\"GET\")\n                                       .endpoint(\"http://localhost:8080/client/api\")\n                                       .addQueryParam(\"response\", \"json\")\n                                       .addQueryParam(\"command\", \"updateCluster\")\n                                       .addQueryParam(\"id\", \"1\")\n                                       .addQueryParam(\"allocationstate\", \"Enabled\")\n                                       .addQueryParam(\"clustername\", \"Xen Clust 1\")\n                                       .addQueryParam(\"clustertype\", \"CloudManaged\")\n                                       .addQueryParam(\"hypervisor\", \"XenServer\")\n                                       .addQueryParam(\"managedstate\", \"Managed\")\n                                       .addQueryParam(\"apiKey\", \"identity\")\n                                       .addQueryParam(\"signature\", \"/wbuYKwInciSXWkUf05lEfJZShQ=\")\n                                       .addHeader(\"Accept\", \"application/json\").build();\n\n   @Test\n   public void testUpdateClusterWhenResponseIs2xx() {\n      HttpResponse response = HttpResponse.builder()\n         .payload(payloadFromResource(\"/updateclusterresponse.json\"))\n         .statusCode(200).build();\n\n      Cluster expected = Cluster.builder().id(\"1\").name(\"Xen Clust 1\").podId(\"1\").podName(\"Dev Pod 1\").zoneId(\"1\").zoneName(\"Dev Zone 1\").hypervisor(\"XenServer\").clusterType(Host.ClusterType.CLOUD_MANAGED).allocationState(AllocationState.ENABLED).managedState(Cluster.ManagedState.MANAGED).build();\n\n      Cluster actual = requestSendsResponse(updateCluster, response).updateCluster(\"1\", UpdateClusterOptions.Builder.allocationState(AllocationState.ENABLED).clusterName(\"Xen Clust 1\").clusterType(Host.ClusterType.CLOUD_MANAGED).hypervisor(\"XenServer\").managedState(Cluster.ManagedState.MANAGED));\n\n      assertEquals(actual, expected);\n   }\n\n   HttpRequest updateClusterPassword = HttpRequest.builder().method(\"GET\")\n                                                  .endpoint(\"http://localhost:8080/client/api\")\n                                                  .addQueryParam(\"response\", \"json\")\n                                                  .addQueryParam(\"command\", \"updateHostPassword\")\n                                                  .addQueryParam(\"clusterid\", \"1\")\n                                                  .addQueryParam(\"username\", \"fred\")\n                                                  .addQueryParam(\"password\", \"sekrit\")\n                                                  .addQueryParam(\"apiKey\", \"identity\")\n                                                  .addQueryParam(\"signature\", \"xwc83+oYK0cuAiFQAlg/7/1IVHE=\")\n                                                  .addHeader(\"Accept\", \"application/json\").build();\n\n   @Test\n   public void testUpdateClusterPasswordWhenResponseIs2xx() {\n      HttpResponse response = HttpResponse.builder()\n         .statusCode(200).build();\n      requestSendsResponse(updateClusterPassword, response).updateClusterPassword(\"1\", \"fred\", \"sekrit\");\n   }\n\n   @Test\n   public void testDeleteClusterWhenResponseIs2xx() {\n      HttpRequest request = HttpRequest.builder()\n         .method(\"GET\")\n         .endpoint(\"http://localhost:8080/client/api?response=json&command=deleteCluster&id=1&apiKey=identity&signature=CKH26MFgKGY7Sosd17LjBMNa3AI%3D\")\n         .addHeader(\"Accept\", \"application/json\").build();\n      HttpResponse response = HttpResponse.builder()\n         .statusCode(200).build();\n\n      requestSendsResponse(request, response).deleteCluster(\"1\");\n   }\n\n   private Date makeDate(int year, int month, int date, int hour, int minute, int second, String timeZoneName) {\n      Calendar cal = Calendar.getInstance(TimeZone.getTimeZone(timeZoneName));\n      cal.set(Calendar.YEAR, year);\n      cal.set(Calendar.MONTH, month);\n      cal.set(Calendar.DATE, date);\n      cal.set(Calendar.HOUR_OF_DAY, hour);\n      cal.set(Calendar.MINUTE, minute);\n      cal.set(Calendar.SECOND, second);\n      cal.set(Calendar.MILLISECOND, 0);\n      return cal.getTime();\n   }\n\n   @Override\n   protected GlobalHostApi clientFrom(CloudStackContext context) {\n      return context.getGlobalApi().getHostClient();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/GlobalHostApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.AllocationState;\nimport org.jclouds.cloudstack.domain.Cluster;\nimport org.jclouds.cloudstack.domain.Host;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Strings;\n\n/**\n * Tests behavior of {@code GlobalHostApi}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"GlobalHostApiLiveTest\")\npublic class GlobalHostApiLiveTest extends BaseCloudStackApiLiveTest {\n\n   @Test(groups = \"live\", enabled = true)\n   public void testListHosts() throws Exception {\n      skipIfNotGlobalAdmin();\n\n      Set<Host> hosts = globalAdminClient.getHostClient().listHosts();\n      assert !hosts.isEmpty() : hosts;\n\n      for (Host host : hosts) {\n         checkHost(host);\n      }\n   }\n\n   private void checkHost(Host host) {\n      if (host.getType() == Host.Type.ROUTING) {\n         assert host.getCpuNumber() > 0;\n         assert host.getAverageLoad() >= 0;\n         assert host.getHypervisor() != null;\n      }\n      assert host.getEvents() != null;\n      if (host.getType() == Host.Type.SECONDARY_STORAGE_VM) {\n         assert host.getName().startsWith(\"s-\");\n      }\n      if (host.getType() == Host.Type.CONSOLE_PROXY) {\n         assert host.getName().startsWith(\"v-\");\n      }\n   }\n\n   @Test(groups = \"live\", enabled = true)\n   public void testListClusters() throws Exception {\n      skipIfNotGlobalAdmin();\n\n      Set<Cluster> clusters = globalAdminClient.getHostClient().listClusters();\n      assert !clusters.isEmpty() : clusters;\n\n      for (Cluster cluster : clusters) {\n         checkCluster(cluster);\n      }\n   }\n\n   private void checkCluster(Cluster cluster) {\n      assertNotNull(cluster.getId());\n      assertFalse(Strings.isNullOrEmpty(cluster.getName()));\n      assertNotEquals(AllocationState.UNKNOWN, cluster.getAllocationState());\n      assertNotEquals(Host.ClusterType.UNKNOWN, cluster.getClusterType());\n      assertFalse(Strings.isNullOrEmpty(cluster.getHypervisor()));\n      assertNotEquals(Cluster.ManagedState.UNRECOGNIZED, cluster.getManagedState());\n      assertNotNull(cluster.getPodId());\n      assertFalse(Strings.isNullOrEmpty(cluster.getPodName()));\n      assertNotNull(cluster.getZoneId());\n      assertFalse(Strings.isNullOrEmpty(cluster.getZoneName()));\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/GlobalHostApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiTest;\nimport org.jclouds.cloudstack.options.ListHostsOptions;\nimport org.jclouds.http.functions.ParseFirstJsonValueNamed;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.reflect.Invokable;\n/**\n * Tests behavior of {@code GlobalHostApi}\n */\n@Test(groups = \"unit\", testName = \"GlobalHostApiTest\")\npublic class GlobalHostApiTest extends BaseCloudStackApiTest<GlobalHostApi> {\n\n   public void testListHosts() throws Exception {\n      Invokable<?, ?> method = method(GlobalHostApi.class, \"listHosts\", ListHostsOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(httpRequest,\n         \"GET http://localhost:8080/client/api?response=json&command=listHosts&listAll=true HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/GlobalOfferingApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static com.google.common.collect.Iterables.getFirst;\nimport static org.jclouds.cloudstack.domain.NetworkOfferingAvailabilityType.OPTIONAL;\nimport static org.jclouds.cloudstack.domain.NetworkOfferingAvailabilityType.REQUIRED;\nimport static org.jclouds.cloudstack.options.CreateDiskOfferingOptions.Builder.diskSizeInGB;\nimport static org.jclouds.cloudstack.options.CreateServiceOfferingOptions.Builder.highlyAvailable;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.cloudstack.domain.DiskOffering;\nimport org.jclouds.cloudstack.domain.NetworkOffering;\nimport org.jclouds.cloudstack.domain.NetworkOfferingAvailabilityType;\nimport org.jclouds.cloudstack.domain.ServiceOffering;\nimport org.jclouds.cloudstack.domain.StorageType;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest;\nimport org.jclouds.cloudstack.options.UpdateDiskOfferingOptions;\nimport org.jclouds.cloudstack.options.UpdateNetworkOfferingOptions;\nimport org.jclouds.cloudstack.options.UpdateServiceOfferingOptions;\nimport org.jclouds.logging.Logger;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code GlobalOfferingApi}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"GlobalOfferingApiLiveTest\")\npublic class GlobalOfferingApiLiveTest extends BaseCloudStackApiLiveTest {\n\n   @Test(groups = \"live\", enabled = true)\n   public void testCreateServiceOffering() throws Exception {\n      skipIfNotGlobalAdmin();\n\n      String name = prefix + \"-test-create-service-offering\";\n      String displayText = name + \"-display\";\n      ServiceOffering offering = null;\n      try {\n         offering = globalAdminClient.getOfferingApi().\n            createServiceOffering(name, displayText, 2, 1024, 2048, highlyAvailable(true).storageType(StorageType.LOCAL));\n         Logger.CONSOLE.info(\"Created Service Offering: \" + offering);\n\n         assertEquals(offering.getName(), name);\n         assertEquals(offering.getDisplayText(), displayText);\n         checkServiceOffering(offering);\n\n         offering = globalAdminClient.getOfferingApi()\n            .updateServiceOffering(offering.getId(),\n               UpdateServiceOfferingOptions.Builder.name(name + \"-2\").displayText(displayText + \"-2\"));\n\n         assertEquals(offering.getName(), name + \"-2\");\n         assertEquals(offering.getDisplayText(), displayText + \"-2\");\n         checkServiceOffering(offering);\n\n      } finally {\n         if (offering != null) {\n            globalAdminClient.getOfferingApi().deleteServiceOffering(offering.getId());\n         }\n      }\n   }\n\n   private void checkServiceOffering(ServiceOffering offering) {\n      assertNotNull(offering.getId());\n      assertEquals(offering.getCpuNumber(), 2);\n      assertEquals(offering.getCpuSpeed(), 1024);\n      assertEquals(offering.getMemory(), 2048);\n      assertTrue(offering.supportsHA());\n      assertEquals(offering.getStorageType(), StorageType.LOCAL);\n   }\n\n   @Test(groups = \"live\", enabled = true)\n   public void testCreateDiskOffering() throws Exception {\n      skipIfNotGlobalAdmin();\n\n      String name = prefix + \"-test-create-disk-offering\";\n      String displayText = name + \"-display\";\n      DiskOffering offering = null;\n      try {\n         offering = globalAdminClient.getOfferingApi().\n            createDiskOffering(name, displayText,\n               diskSizeInGB(100).customized(true).tags(ImmutableSet.<String>of(\"dummy-tag\")));\n\n         assertEquals(offering.getName(), name);\n         assertEquals(offering.getDisplayText(), displayText);\n         checkDiskOffering(offering);\n\n         offering = globalAdminClient.getOfferingApi().\n            updateDiskOffering(offering.getId(),\n               UpdateDiskOfferingOptions.Builder.name(name + \"-2\").displayText(displayText + \"-2\"));\n\n         assertEquals(offering.getName(), name + \"-2\");\n         assertEquals(offering.getDisplayText(), displayText + \"-2\");\n         checkDiskOffering(offering);\n\n      } finally {\n         if (offering != null) {\n            globalAdminClient.getOfferingApi().deleteDiskOffering(offering.getId());\n         }\n      }\n   }\n\n   private void checkDiskOffering(DiskOffering offering) {\n      assertTrue(offering.isCustomized());\n      assertEquals(offering.getDiskSize(), 100);\n      assertTrue(offering.getTags().contains(\"dummy-tag\"));\n   }\n\n   @Test(groups = \"live\", enabled = true)\n   public void testUpdateNetworkOffering() throws Exception {\n      skipIfNotGlobalAdmin();\n\n      NetworkOffering offering = getFirst(globalAdminClient.getOfferingApi().listNetworkOfferings(), null);\n      assertNotNull(offering, \"Unable to test, no network offering found.\");\n\n      String name = offering.getName();\n      NetworkOfferingAvailabilityType availability = offering.getAvailability();\n\n      try {\n         NetworkOfferingAvailabilityType newValue = OPTIONAL;\n         if (availability == OPTIONAL) {\n            newValue = REQUIRED;\n         }\n         NetworkOffering updated = globalAdminClient.getOfferingApi().updateNetworkOffering(offering.getId(),\n            UpdateNetworkOfferingOptions.Builder.name(prefix + name).availability(newValue));\n\n         assertEquals(updated.getName(), prefix + name);\n         assertEquals(updated.getAvailability(), newValue);\n\n      } finally {\n         globalAdminClient.getOfferingApi().updateNetworkOffering(offering.getId(),\n            UpdateNetworkOfferingOptions.Builder.name(name).availability(availability));\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/GlobalOfferingApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiTest;\nimport org.jclouds.cloudstack.options.CreateDiskOfferingOptions;\nimport org.jclouds.cloudstack.options.CreateServiceOfferingOptions;\nimport org.jclouds.cloudstack.options.UpdateDiskOfferingOptions;\nimport org.jclouds.cloudstack.options.UpdateNetworkOfferingOptions;\nimport org.jclouds.cloudstack.options.UpdateServiceOfferingOptions;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.functions.ParseFirstJsonValueNamed;\nimport org.jclouds.http.functions.ReleasePayloadAndReturn;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.reflect.Invokable;\n\n/**\n * Tests behavior of {@code GlobalOfferingApi}\n */\n@Test(groups = \"unit\", testName = \"GlobalOfferingApiTest\")\npublic class GlobalOfferingApiTest extends BaseCloudStackApiTest<GlobalOfferingApi> {\n\n   HttpRequest createServiceOffering = HttpRequest.builder().method(\"GET\")\n                                                  .endpoint(\"http://localhost:8080/client/api\")\n                                                  .addQueryParam(\"response\", \"json\")\n                                                  .addQueryParam(\"command\", \"createServiceOffering\")\n                                                  .addQueryParam(\"name\", \"name\")\n                                                  .addQueryParam(\"displaytext\", \"displayText\")\n                                                  .addQueryParam(\"cpunumber\", \"1\")\n                                                  .addQueryParam(\"cpuspeed\", \"2\")\n                                                  .addQueryParam(\"memory\", \"3\").build();\n\n   public void testCreateServiceOffering() throws Exception {\n      Invokable<?, ?> method = method(GlobalOfferingApi.class, \"createServiceOffering\",\n         String.class, String.class, int.class, int.class, int.class, CreateServiceOfferingOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"name\", \"displayText\", 1, 2, 3));\n\n      assertRequestLineEquals(httpRequest, createServiceOffering.getRequestLine());\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testUpdateServiceOffering() throws Exception {\n      Invokable<?, ?> method = method(GlobalOfferingApi.class, \"updateServiceOffering\",\n         String.class, UpdateServiceOfferingOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(1L));\n\n      assertRequestLineEquals(httpRequest,\n         \"GET http://localhost:8080/client/api?response=json&command=updateServiceOffering&id=1 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testDeleteServiceOffering() throws Exception {\n      Invokable<?, ?> method = method(GlobalOfferingApi.class, \"deleteServiceOffering\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(1L));\n\n      assertRequestLineEquals(httpRequest,\n         \"GET http://localhost:8080/client/api?response=json&command=deleteServiceOffering&id=1 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testCreateDiskOffering() throws Exception {\n      Invokable<?, ?> method = method(GlobalOfferingApi.class, \"createDiskOffering\",\n         String.class, String.class, CreateDiskOfferingOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"name\", \"displayText\"));\n\n      assertRequestLineEquals(httpRequest,\n         \"GET http://localhost:8080/client/api?response=json&command=createDiskOffering&name=name&displaytext=displayText HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testUpdateDiskOffering() throws Exception {\n      Invokable<?, ?> method = method(GlobalOfferingApi.class, \"updateDiskOffering\",\n         String.class, UpdateDiskOfferingOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(1L));\n\n      assertRequestLineEquals(httpRequest,\n         \"GET http://localhost:8080/client/api?response=json&command=updateDiskOffering&id=1 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testDeleteDiskOffering() throws Exception {\n      Invokable<?, ?> method = method(GlobalOfferingApi.class, \"deleteDiskOffering\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(1L));\n\n      assertRequestLineEquals(httpRequest,\n         \"GET http://localhost:8080/client/api?response=json&command=deleteDiskOffering&id=1 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testUpdateNetworkOffering() throws Exception {\n      Invokable<?, ?> method = method(GlobalOfferingApi.class, \"updateNetworkOffering\",\n         String.class, UpdateNetworkOfferingOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(1L));\n\n      assertRequestLineEquals(httpRequest,\n         \"GET http://localhost:8080/client/api?response=json&command=updateNetworkOffering&id=1 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/GlobalPodApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\n\nimport org.jclouds.cloudstack.CloudStackContext;\nimport org.jclouds.cloudstack.domain.AllocationState;\nimport org.jclouds.cloudstack.domain.Pod;\nimport org.jclouds.cloudstack.internal.BaseCloudStackExpectTest;\nimport org.jclouds.cloudstack.options.CreatePodOptions;\nimport org.jclouds.cloudstack.options.UpdatePodOptions;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Test the CloudStack PodClient\n */\n@Test(groups = \"unit\", testName = \"GlobalPodApiExpectTest\")\npublic class GlobalPodApiExpectTest extends BaseCloudStackExpectTest<GlobalPodApi> {\n\n   public void testListPodsWhenResponseIs2xx() {\n      GlobalPodApi client = requestSendsResponse(\n         HttpRequest.builder()\n            .method(\"GET\")\n            .endpoint(\n               URI.create(\"http://localhost:8080/client/api?response=json&\" +\n                  \"command=listPods&listAll=true&apiKey=identity&signature=MuowIOuZqOpKTPVQOfrDZEmpepw%3D\"))\n            .headers(\n               ImmutableMultimap.<String, String>builder()\n                  .put(\"Accept\", \"application/json\")\n                  .build())\n            .build(),\n         HttpResponse.builder()\n            .statusCode(200)\n            .payload(payloadFromResource(\"/listpodsresponse.json\"))\n            .build());\n\n      Pod pod1 = Pod.builder()\n         .id(\"1\")\n         .name(\"Dev Pod 1\")\n         .zoneId(\"1\")\n         .zoneName(\"Dev Zone 1\")\n         .gateway(\"10.26.26.254\")\n         .netmask(\"255.255.255.0\")\n         .startIp(\"10.26.26.50\")\n         .endIp(\"10.26.26.100\")\n         .allocationState(AllocationState.ENABLED)\n         .build();\n      Pod pod2 = Pod.builder()\n         .id(\"2\")\n         .name(\"Dev Pod 2\")\n         .zoneId(\"2\")\n         .zoneName(\"Dev Zone 2\")\n         .gateway(\"10.22.22.254\")\n         .netmask(\"255.255.255.0\")\n         .startIp(\"10.22.22.25\")\n         .endIp(\"10.22.22.50\")\n         .allocationState(AllocationState.ENABLED)\n         .build();\n\n      assertEquals(client.listPods(), ImmutableSet.of(pod1, pod2));\n   }\n\n   public void testListPodsWhenResponseIs404() {\n      GlobalPodApi client = requestSendsResponse(\n         HttpRequest.builder()\n            .method(\"GET\")\n            .endpoint(\n               URI.create(\"http://localhost:8080/client/api?response=json&\" +\n                  \"command=listPods&listAll=true&apiKey=identity&signature=MuowIOuZqOpKTPVQOfrDZEmpepw%3D\"))\n            .headers(\n               ImmutableMultimap.<String, String>builder()\n                  .put(\"Accept\", \"application/json\")\n                  .build())\n            .build(),\n         HttpResponse.builder()\n            .statusCode(404)\n            .build());\n\n      assertEquals(client.listPods(), ImmutableSet.of());\n   }\n\n   HttpRequest createPod = HttpRequest.builder().method(\"GET\")\n                                      .endpoint(\"http://localhost:8080/client/api\")\n                                      .addQueryParam(\"response\", \"json\")\n                                      .addQueryParam(\"command\", \"createPod\")\n                                      .addQueryParam(\"name\", \"richard-pod\")\n                                      .addQueryParam(\"zoneid\", \"10\")\n                                      .addQueryParam(\"startip\", \"172.20.0.1\")\n                                      .addQueryParam(\"endip\", \"172.20.0.250\")\n                                      .addQueryParam(\"gateway\", \"172.20.0.254\")\n                                      .addQueryParam(\"netmask\", \"255.255.255.0\")\n                                      .addQueryParam(\"allocationstate\", \"Enabled\")\n                                      .addQueryParam(\"apiKey\", \"identity\")\n                                      .addQueryParam(\"signature\", \"fwsoQ77BmNQWfuqv4nVlPcKvKbU=\")\n                                      .addHeader(\"Accept\", \"application/json\").build();\n\n   public void testCreatePodWhenResponseIs2xx() {\n      GlobalPodApi client = requestSendsResponse(createPod,\n         HttpResponse.builder()\n            .statusCode(200)\n            .payload(payloadFromResource(\"/createpodresponse.json\"))\n            .build());\n\n      Pod expected = Pod.builder()\n         .id(\"6\")\n         .name(\"richard-pod\")\n         .zoneId(\"10\")\n         .zoneName(\"richard-zone\")\n         .gateway(\"172.20.0.254\")\n         .netmask(\"255.255.255.0\")\n         .startIp(\"172.20.0.1\")\n         .endIp(\"172.20.0.250\")\n         .allocationState(AllocationState.ENABLED)\n         .build();\n\n      Pod actual = client.createPod(\"richard-pod\", \"10\", \"172.20.0.1\", \"172.20.0.250\", \"172.20.0.254\", \"255.255.255.0\",\n         CreatePodOptions.Builder.allocationState(AllocationState.ENABLED));\n\n      assertEquals(actual, expected);\n   }\n\n   public void testUpdatePodWhenResponseIs2xx() {\n      GlobalPodApi client = requestSendsResponse(\n         HttpRequest.builder()\n            .method(\"GET\")\n            .endpoint(\n               URI.create(\"http://localhost:8080/client/api?response=json&command=updatePod&id=7&netmask=255.255.255.128&name=richard-updatepod&startip=172.21.0.129&endip=172.21.0.250&gateway=172.21.0.254&allocationstate=Disabled&apiKey=identity&signature=QpdbRyyF/xJ78ioJWhPKXEWhthY%3D\"))\n            .headers(\n               ImmutableMultimap.<String, String>builder()\n                  .put(\"Accept\", \"application/json\")\n                  .build())\n            .build(),\n         HttpResponse.builder()\n            .statusCode(200)\n            .payload(payloadFromResource(\"/updatepodresponse.json\"))\n            .build());\n\n      Pod expected = Pod.builder()\n         .id(\"7\")\n         .name(\"richard-updatedpod\")\n         .zoneId(\"11\")\n         .zoneName(\"richard-zone\")\n         .gateway(\"172.21.0.254\")\n         .netmask(\"255.255.255.128\")\n         .startIp(\"172.21.0.129\")\n         .endIp(\"172.21.0.250\")\n         .allocationState(AllocationState.DISABLED)\n         .build();\n\n      Pod actual = client.updatePod(\"7\", UpdatePodOptions.Builder\n         .netmask(\"255.255.255.128\")\n         .name(\"richard-updatepod\")\n         .startIp(\"172.21.0.129\")\n         .endIp(\"172.21.0.250\")\n         .gateway(\"172.21.0.254\")\n         .allocationState(AllocationState.DISABLED)\n      );\n\n      assertEquals(actual, expected);\n   }\n\n   public void testDeletePodWhenResponseIs2xx() {\n      GlobalPodApi client = requestSendsResponse(\n         HttpRequest.builder()\n            .method(\"GET\")\n            .endpoint(\n               URI.create(\"http://localhost:8080/client/api?response=json&command=deletePod&id=3&apiKey=identity&signature=rm4ItuAL1Ztnj%2BHFFvBFzvHAIog%3D\"))\n            .headers(\n               ImmutableMultimap.<String, String>builder()\n                  .put(\"Accept\", \"application/json\")\n                  .build())\n            .build(),\n         HttpResponse.builder()\n            .statusCode(200)\n            .build());\n\n      client.deletePod(\"3\");\n   }\n\n   @Override\n   protected GlobalPodApi clientFrom(CloudStackContext context) {\n      return context.getGlobalApi().getPodClient();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/GlobalPodApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.AllocationState;\nimport org.jclouds.cloudstack.domain.NetworkType;\nimport org.jclouds.cloudstack.domain.Pod;\nimport org.jclouds.cloudstack.domain.Zone;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest;\nimport org.jclouds.cloudstack.options.CreatePodOptions;\nimport org.jclouds.cloudstack.options.ListPodsOptions;\nimport org.jclouds.cloudstack.options.UpdatePodOptions;\nimport org.testng.annotations.AfterGroups;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Strings;\nimport com.google.common.collect.Iterables;\n\n/**\n * Tests behavior of {@code GlobalPodApi}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"GlobalPodApiLiveTest\")\npublic class GlobalPodApiLiveTest extends BaseCloudStackApiLiveTest {\n\n   private Zone zone;\n   private Pod pod;\n\n   public void testListPods() throws Exception {\n      skipIfNotGlobalAdmin();\n\n      Set<Pod> response = globalAdminClient.getPodClient().listPods();\n      assert null != response;\n      long podCount = response.size();\n      assertTrue(podCount >= 0);\n\n      for (Pod pod : response) {\n         Pod newDetails = Iterables.getOnlyElement(globalAdminClient.getPodClient().listPods(\n            ListPodsOptions.Builder.id(pod.getId())));\n         assertEquals(pod, newDetails);\n         assertEquals(pod, globalAdminClient.getPodClient().getPod(pod.getId()));\n         assertNotNull(pod.getId());\n         assertFalse(Strings.isNullOrEmpty(pod.getName()));\n         assertNotNull(pod.getZoneId());\n         assertFalse(Strings.isNullOrEmpty(pod.getZoneName()));\n         assertFalse(Strings.isNullOrEmpty(pod.getGateway()));\n         assertFalse(Strings.isNullOrEmpty(pod.getNetmask()));\n         assertFalse(Strings.isNullOrEmpty(pod.getStartIp()));\n         assertFalse(Strings.isNullOrEmpty(pod.getEndIp()));\n         assertNotEquals(pod.getAllocationState(), AllocationState.UNKNOWN);\n      }\n   }\n\n   @Test\n   public void testCreatePod() {\n      skipIfNotGlobalAdmin();\n\n      zone = globalAdminClient.getZoneApi().createZone(prefix + \"-zone-for-pod\", NetworkType.BASIC, \"8.8.8.8\", \"10.10.10.10\");\n      pod = globalAdminClient.getPodClient().createPod(prefix + \"-pod\", zone.getId(), \"172.20.0.1\", \"172.20.0.250\", \"172.20.0.254\", \"255.255.255.0\",\n      CreatePodOptions.Builder.allocationState(AllocationState.ENABLED));\n\n      assertNotNull(pod);\n      assertEquals(pod.getName(), prefix + \"-pod\");\n      assertEquals(pod.getZoneId(), zone.getId());\n      assertEquals(pod.getZoneName(), prefix + \"-zone-for-pod\");\n      assertEquals(pod.getStartIp(), \"172.20.0.1\");\n      assertEquals(pod.getEndIp(), \"172.20.0.250\");\n      assertEquals(pod.getGateway(), \"172.20.0.254\");\n      assertEquals(pod.getNetmask(), \"255.255.255.0\");\n      assertEquals(pod.getAllocationState(), AllocationState.ENABLED);\n   }\n\n   @Test(dependsOnMethods = \"testCreatePod\")\n   public void testUpdatePod() {\n      Pod updated = globalAdminClient.getPodClient().updatePod(pod.getId(), UpdatePodOptions.Builder\n         .name(prefix + \"-updatedpod\")\n         .startIp(\"172.21.0.129\")\n         .endIp(\"172.21.0.250\")\n         .gateway(\"172.21.0.254\")\n         .netmask(\"255.255.255.128\")\n         .allocationState(AllocationState.DISABLED)\n      );\n\n      assertNotNull(updated);\n      assertEquals(updated.getName(), prefix + \"-updatedpod\");\n      assertEquals(updated.getZoneId(), zone.getId());\n      assertEquals(updated.getZoneName(), prefix + \"-zone-for-pod\");\n      assertEquals(updated.getStartIp(), \"172.21.0.129\");\n      assertEquals(updated.getEndIp(), \"172.21.0.250\");\n      assertEquals(updated.getGateway(), \"172.21.0.254\");\n      assertEquals(updated.getNetmask(), \"255.255.255.128\");\n      assertEquals(updated.getAllocationState(), AllocationState.DISABLED);\n   }\n\n   @AfterGroups(groups = \"live\")\n   @Override\n   protected void tearDownContext() {\n      if (pod != null) {\n         globalAdminClient.getPodClient().deletePod(pod.getId());\n         pod = null;\n      }\n      if (zone != null) {\n         globalAdminClient.getZoneApi().deleteZone(zone.getId());\n         zone = null;\n      }\n      super.tearDownContext();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/GlobalStoragePoolApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.StoragePool;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Strings;\n\n/**\n * Tests behavior of {@code GlobalStoragePoolApi}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"GlobalStoragePoolApiLiveTest\")\npublic class GlobalStoragePoolApiLiveTest extends BaseCloudStackApiLiveTest {\n\n   @Test(groups = \"live\", enabled = true)\n   public void testListStoragePools() throws Exception {\n      skipIfNotGlobalAdmin();\n\n      Set<StoragePool> result = globalAdminClient.getStoragePoolClient().listStoragePools();\n      assertNotNull(result);\n      assertTrue(!result.isEmpty());\n      for (StoragePool pool : result) {\n         assertNotNull(pool.getId());\n         assertFalse(Strings.isNullOrEmpty(pool.getName()));\n         assertFalse(Strings.isNullOrEmpty(pool.getPath()));\n         assertNotNull(pool.getTags());\n         assertNotEquals(StoragePool.State.UNRECOGNIZED, pool.getState());\n         assertNotEquals(StoragePool.Type.UNRECOGNIZED, pool.getType());\n         assertNotNull(pool.getZoneId());\n         assertFalse(Strings.isNullOrEmpty(pool.getZoneName()));\n         assertNotNull(pool.getPodId());\n         assertFalse(Strings.isNullOrEmpty(pool.getPodName()));\n         assertNotNull(pool.getClusterId());\n         assertFalse(Strings.isNullOrEmpty(pool.getClusterName()));\n         assertNotNull(pool.getCreated());\n         assertTrue(pool.getDiskSizeTotal() > 0);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/GlobalStoragePoolApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiTest;\nimport org.jclouds.cloudstack.options.ListStoragePoolsOptions;\nimport org.jclouds.fallbacks.MapHttp4xxCodesToExceptions;\nimport org.jclouds.http.functions.ParseFirstJsonValueNamed;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.reflect.Invokable;\n/**\n * Tests behavior of {@code GlobalStoragePoolApi}\n */\n@Test(groups = \"unit\", testName = \"GlobalStoragePoolApiTest\")\npublic class GlobalStoragePoolApiTest extends BaseCloudStackApiTest<GlobalStoragePoolApi> {\n\n   public void testListStoragePools() throws NoSuchMethodException {\n      Invokable<?, ?> method = method(GlobalStoragePoolApi.class, \"listStoragePools\", ListStoragePoolsOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(httpRequest,\n         \"GET http://localhost:8080/client/api?response=json&command=listStoragePools&listAll=true HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testListStoragePoolsOptions() throws NoSuchMethodException {\n      Invokable<?, ?> method = method(GlobalStoragePoolApi.class, \"listStoragePools\", ListStoragePoolsOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(ListStoragePoolsOptions.Builder.clusterId(\"3\").id(\"4\").ipAddress(\"192.168.42.42\").keyword(\"fred\").name(\"bob\").path(\"/mnt/store42\").podId(\"4\").zoneId(\"5\")));\n\n      assertRequestLineEquals(httpRequest,\n         \"GET http://localhost:8080/client/api?response=json&command=listStoragePools&listAll=true&clusterid=3&id=4&ipaddress=192.168.42.42&keyword=fred&name=bob&path=/mnt/store42&podid=4&zoneid=5 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/GlobalUsageApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Calendar;\nimport java.util.Date;\nimport java.util.Set;\nimport java.util.TimeZone;\n\nimport org.jclouds.cloudstack.domain.JobResult;\nimport org.jclouds.cloudstack.domain.UsageRecord;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest;\nimport org.jclouds.cloudstack.options.GenerateUsageRecordsOptions;\nimport org.jclouds.cloudstack.options.ListUsageRecordsOptions;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code GlobalUsageApi}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"GlobalUsageApiLiveTest\")\npublic class GlobalUsageApiLiveTest extends BaseCloudStackApiLiveTest {\n\n   @Test(groups = \"live\", enabled = true)\n   public void testListUsage() {\n      skipIfNotGlobalAdmin();\n\n      Calendar c = Calendar.getInstance(TimeZone.getTimeZone(\"GMT\"));\n      Date end = c.getTime();\n      c.add(Calendar.MONTH, -1);\n      Date start = c.getTime();\n\n      JobResult result = globalAdminClient.getUsageClient().generateUsageRecords(start, end, GenerateUsageRecordsOptions.NONE);\n      assertNotNull(result);\n      assertTrue(result.isSuccess(), result.getDisplayText());\n\n      Set<UsageRecord> records = globalAdminClient.getUsageClient().listUsageRecords(start, end, ListUsageRecordsOptions.NONE);\n      assertNotNull(records);\n      assertTrue(records.size() > 0);\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/GlobalUsageApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport java.util.Calendar;\nimport java.util.Date;\n\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiTest;\nimport org.jclouds.cloudstack.options.GenerateUsageRecordsOptions;\nimport org.jclouds.cloudstack.options.ListUsageRecordsOptions;\nimport org.jclouds.fallbacks.MapHttp4xxCodesToExceptions;\nimport org.jclouds.http.functions.ParseFirstJsonValueNamed;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.reflect.Invokable;\n/**\n * Tests behavior of {@code GlobalUsageApi}\n */\n@Test(groups = \"unit\", testName = \"GlobalUsageApiTest\")\npublic class GlobalUsageApiTest extends BaseCloudStackApiTest<GlobalUsageApi> {\n\n   public void testGenerateUsageRecords() throws Exception {\n      Calendar c = Calendar.getInstance();\n      c.set(Calendar.YEAR, 2012);\n      c.set(Calendar.MONTH, Calendar.JANUARY);\n      c.set(Calendar.DAY_OF_MONTH, 1);\n      Date start = c.getTime();\n      c.set(Calendar.DAY_OF_MONTH, 31);\n      Date end = c.getTime();\n\n      Invokable<?, ?> method = method(GlobalUsageApi.class, \"generateUsageRecords\",\n         Date.class, Date.class, GenerateUsageRecordsOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(start, end));\n\n      assertRequestLineEquals(httpRequest,\n         \"GET http://localhost:8080/client/api?response=json&command=generateUsageRecords&startdate=2012-01-01&enddate=2012-01-31 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testGenerateUsageRecordsOptions() throws Exception {\n      Calendar c = Calendar.getInstance();\n      c.set(Calendar.YEAR, 2012);\n      c.set(Calendar.MONTH, Calendar.JANUARY);\n      c.set(Calendar.DAY_OF_MONTH, 1);\n      Date start = c.getTime();\n      c.set(Calendar.DAY_OF_MONTH, 31);\n      Date end = c.getTime();\n\n      Invokable<?, ?> method = method(GlobalUsageApi.class, \"generateUsageRecords\",\n         Date.class, Date.class, GenerateUsageRecordsOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(start, end, GenerateUsageRecordsOptions.Builder.domainId(\"42\")));\n\n      assertRequestLineEquals(httpRequest,\n         \"GET http://localhost:8080/client/api?response=json&command=generateUsageRecords&startdate=2012-01-01&enddate=2012-01-31&domainid=42 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testListUsageRecords() throws Exception {\n      Calendar c = Calendar.getInstance();\n      c.set(Calendar.YEAR, 2012);\n      c.set(Calendar.MONTH, Calendar.JANUARY);\n      c.set(Calendar.DAY_OF_MONTH, 1);\n      Date start = c.getTime();\n      c.set(Calendar.DAY_OF_MONTH, 31);\n      Date end = c.getTime();\n\n      Invokable<?, ?> method = method(GlobalUsageApi.class, \"listUsageRecords\",\n         Date.class, Date.class, ListUsageRecordsOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(start, end));\n\n      assertRequestLineEquals(httpRequest,\n         \"GET http://localhost:8080/client/api?response=json&command=listUsageRecords&listAll=true&startdate=2012-01-01&enddate=2012-01-31 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testListUsageRecordsOptions() throws Exception {\n      Calendar c = Calendar.getInstance();\n      c.set(Calendar.YEAR, 2012);\n      c.set(Calendar.MONTH, Calendar.JANUARY);\n      c.set(Calendar.DAY_OF_MONTH, 1);\n      Date start = c.getTime();\n      c.set(Calendar.DAY_OF_MONTH, 31);\n      Date end = c.getTime();\n\n      Invokable<?, ?> method = method(GlobalUsageApi.class, \"listUsageRecords\",\n         Date.class, Date.class, ListUsageRecordsOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(start, end, ListUsageRecordsOptions.Builder.accountInDomain(\"fred\", \"42\").accountId(\"41\").keyword(\"bob\")));\n\n      assertRequestLineEquals(httpRequest,\n         \"GET http://localhost:8080/client/api?response=json&command=listUsageRecords&listAll=true&startdate=2012-01-01&enddate=2012-01-31&account=fred&domainid=42&accountid=41&keyword=bob HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/GlobalUserApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.hash.Hashing.md5;\nimport static com.google.common.io.BaseEncoding.base16;\nimport static org.jclouds.cloudstack.features.GlobalAccountApiLiveTest.createTestAccount;\nimport static org.jclouds.cloudstack.options.UpdateUserOptions.Builder.userName;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.Properties;\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.CloudStackApi;\nimport org.jclouds.cloudstack.CloudStackContext;\nimport org.jclouds.cloudstack.CloudStackGlobalApi;\nimport org.jclouds.cloudstack.domain.Account;\nimport org.jclouds.cloudstack.domain.ApiKeyPair;\nimport org.jclouds.cloudstack.domain.User;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code GlobaUserClient}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"GlobalUserApiLiveTest\")\npublic class GlobalUserApiLiveTest extends BaseCloudStackApiLiveTest {\n\n   public static User createTestUser(CloudStackGlobalApi client, Account account, String prefix) {\n      return client.getUserClient().createUser(prefix + \"-user\", account.getName(), \"dummy2@example.com\",\n            base16().lowerCase().encode(md5().hashString(\"password\", UTF_8).asBytes()), \"First\", \"Last\");\n   }\n\n   @Test\n   public void testCreateUser() {\n      skipIfNotGlobalAdmin();\n\n      Account testAccount = createTestAccount(globalAdminClient, prefix);\n      User testUser = null;\n      try {\n         testUser = createTestUser(globalAdminClient, testAccount, prefix);\n\n         assertNotNull(testUser);\n         assertEquals(testUser.getName(), prefix + \"-user\");\n         assertEquals(testUser.getAccount(), prefix + \"-account\");\n\n         User updatedUser = globalAdminClient.getUserClient()\n            .updateUser(testUser.getId(), userName(prefix + \"-user-2\"));\n\n         assertNotNull(updatedUser);\n         assertEquals(updatedUser.getName(), prefix + \"-user-2\");\n\n         ApiKeyPair apiKeys = globalAdminClient.getUserClient()\n            .registerUserKeys(updatedUser.getId());\n\n         assertNotNull(apiKeys.getApiKey());\n         assertNotNull(apiKeys.getSecretKey());\n\n         checkAuthAsUser(apiKeys);\n\n      } finally {\n         if (testUser != null) {\n            globalAdminClient.getUserClient().deleteUser(testUser.getId());\n         }\n         globalAdminClient.getAccountApi().deleteAccount(testAccount.getId());\n      }\n   }\n\n   private void checkAuthAsUser(ApiKeyPair keyPair) {\n      CloudStackContext context = createView(credentialsAsProperties(keyPair), setupModules());\n\n      CloudStackApi client = context.getApi();\n      Set<Account> accounts = client.getAccountApi().listAccounts();\n\n      assert !accounts.isEmpty();\n\n      context.close();\n   }\n\n   private Properties credentialsAsProperties(ApiKeyPair keyPair) {\n      Properties overrides = setupProperties();\n      overrides.put(provider + \".identity\", checkNotNull(keyPair.getApiKey()));\n      overrides.put(provider + \".credential\", checkNotNull(keyPair.getSecretKey()));\n      return overrides;\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/GlobalUserApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiTest;\nimport org.jclouds.cloudstack.options.CreateUserOptions;\nimport org.jclouds.cloudstack.options.UpdateUserOptions;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.functions.ParseFirstJsonValueNamed;\nimport org.jclouds.http.functions.ReleasePayloadAndReturn;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.reflect.Invokable;\n/**\n * Tests behavior of {@code GlobalUserApi}\n */\n@Test(groups = \"unit\", testName = \"GlobalUserApiTest\")\npublic class GlobalUserApiTest extends BaseCloudStackApiTest<GlobalUserApi> {\n\n   HttpRequest createUser = HttpRequest.builder().method(\"GET\")\n                                       .endpoint(\"http://localhost:8080/client/api\")\n                                       .addQueryParam(\"response\", \"json\")\n                                       .addQueryParam(\"command\", \"createUser\")\n                                       .addQueryParam(\"username\", \"user\")\n                                       .addQueryParam(\"account\", \"account\")\n                                       .addQueryParam(\"email\", \"email@example.com\")\n                                       .addQueryParam(\"password\", \"hashed-password\")\n                                       .addQueryParam(\"firstname\", \"FirstName\")\n                                       .addQueryParam(\"lastname\", \"LastName\").build();\n\n   public void testCreateAccount() throws Exception {\n      Invokable<?, ?> method = method(GlobalUserApi.class, \"createUser\", String.class, String.class,\n         String.class, String.class, String.class, String.class, CreateUserOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"user\", \"account\", \"email@example.com\",\n         \"hashed-password\", \"FirstName\", \"LastName\"));\n\n      assertRequestLineEquals(httpRequest, createUser.getRequestLine());\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testUpdateUser() throws Exception {\n      Invokable<?, ?> method = method(GlobalUserApi.class, \"updateUser\", String.class, UpdateUserOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(42L));\n\n      assertRequestLineEquals(httpRequest,\n         \"GET http://localhost:8080/client/api?response=json&command=updateUser&id=42 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testDeleteUser() throws Exception {\n      Invokable<?, ?> method = method(GlobalUserApi.class, \"deleteUser\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(42L));\n\n      assertRequestLineEquals(httpRequest,\n         \"GET http://localhost:8080/client/api?response=json&command=deleteUser&id=42 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/GlobalVlanApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\n\nimport org.jclouds.cloudstack.CloudStackContext;\nimport org.jclouds.cloudstack.domain.VlanIPRange;\nimport org.jclouds.cloudstack.internal.BaseCloudStackExpectTest;\nimport org.jclouds.cloudstack.options.CreateVlanIPRangeOptions;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Test the CloudStack VlanClient\n */\n@Test(groups = \"unit\", testName = \"GlobalVlanApiExpectTest\")\npublic class GlobalVlanApiExpectTest extends BaseCloudStackExpectTest<GlobalVlanApi> {\n\n   public void testListVlanIpRangesWhenResponseIs2xx() {\n      GlobalVlanApi client = requestSendsResponse(\n         HttpRequest.builder()\n            .method(\"GET\")\n            .endpoint(\n               URI.create(\"http://localhost:8080/client/api?response=json&\" +\n                  \"command=listVlanIpRanges&listAll=true&apiKey=identity&signature=xPwCeAcMp9kDGbD5oPgztLtSdnU%3D\"))\n            .addHeader(\"Accept\", \"application/json\")\n            .build(),\n         HttpResponse.builder()\n            .statusCode(200)\n            .payload(payloadFromResource(\"/listvlaniprangesresponse.json\"))\n            .build());\n\n      VlanIPRange range1 = VlanIPRange.builder()\n         .id(\"1\")\n         .forVirtualNetwork(true)\n         .zoneId(\"1\")\n         .vlan(\"127\")\n         .account(\"system\")\n         .domainId(\"1\")\n         .domain(\"ROOT\")\n         .gateway(\"10.27.27.254\")\n         .netmask(\"255.255.255.0\")\n         .startIP(\"10.27.27.50\")\n         .endIP(\"10.27.27.100\")\n         .networkId(\"200\")\n         .build();\n\n      VlanIPRange range2 = VlanIPRange.builder()\n         .id(\"2\")\n         .forVirtualNetwork(false)\n         .zoneId(\"2\")\n         .vlan(\"untagged\")\n         .account(\"system\")\n         .domainId(\"1\")\n         .domain(\"ROOT\")\n         .podId(\"2\")\n         .podName(\"Dev Pod 2\")\n         .gateway(\"10.22.22.254\")\n         .netmask(\"255.255.255.0\")\n         .startIP(\"10.22.22.51\")\n         .endIP(\"10.22.22.100\")\n         .networkId(\"209\")\n         .build();\n\n      assertEquals(client.listVlanIPRanges(), ImmutableSet.of(range1, range2));\n   }\n\n   public void testListVlanIpRangesWhenResponseIs404() {\n      GlobalVlanApi client = requestSendsResponse(\n         HttpRequest.builder()\n            .method(\"GET\")\n            .endpoint(\n               URI.create(\"http://localhost:8080/client/api?response=json&\" +\n                  \"command=listVlanIpRanges&listAll=true&apiKey=identity&signature=xPwCeAcMp9kDGbD5oPgztLtSdnU%3D\"))\n            .addHeader(\"Accept\", \"application/json\")\n            .build(),\n         HttpResponse.builder()\n            .statusCode(404)\n            .build());\n\n      assertEquals(client.listVlanIPRanges(), ImmutableSet.of());\n   }\n\n   public void testCreateVlanIpRangeWhenResponseIs2xx() {\n      GlobalVlanApi client = requestSendsResponse(\n         HttpRequest.builder()\n            .method(\"GET\")\n            .endpoint(\n               URI.create(\"http://localhost:8080/client/api?response=json&\" +\n                  \"command=createVlanIpRange&startip=10.22.22.51&endip=10.22.22.100&forvirtualnetwork=false&zoneid=2&vlan=untagged&account=system&domainid=1&podid=2&gateway=10.22.22.254&netmask=255.255.255.0&networkid=209&apiKey=identity&signature=XgDjPYAQNLMVCuSMGRA6QjV8mOY%3D\"))\n            .addHeader(\"Accept\", \"application/json\")\n            .build(),\n         HttpResponse.builder()\n            .statusCode(200)\n            .payload(payloadFromResource(\"/createvlaniprangeresponse.json\"))\n            .build());\n\n      VlanIPRange actual = client.createVlanIPRange(\"10.22.22.51\", \"10.22.22.100\", new CreateVlanIPRangeOptions()\n         .forVirtualNetwork(false)\n         .zoneId(\"2\")\n         .vlan(\"untagged\")\n         .accountInDomain(\"system\", \"1\")\n         .podId(\"2\")\n         .gateway(\"10.22.22.254\")\n         .netmask(\"255.255.255.0\")\n         .networkId(\"209\"));\n\n      VlanIPRange expected = VlanIPRange.builder()\n         .id(\"2\")\n         .forVirtualNetwork(false)\n         .zoneId(\"2\")\n         .vlan(\"untagged\")\n         .account(\"system\")\n         .domainId(\"1\")\n         .domain(\"ROOT\")\n         .podId(\"2\")\n         .podName(\"Dev Pod 2\")\n         .gateway(\"10.22.22.254\")\n         .netmask(\"255.255.255.0\")\n         .startIP(\"10.22.22.51\")\n         .endIP(\"10.22.22.100\")\n         .networkId(\"209\")\n         .build();\n\n      assertEquals(actual, expected);\n   }\n\n   public void testDeleteVlanIpRangeWhenResponseIs2xx() {\n      GlobalVlanApi client = requestSendsResponse(\n         HttpRequest.builder()\n            .method(\"GET\")\n            .endpoint(\n               URI.create(\"http://localhost:8080/client/api?response=json&\" +\n                  \"command=deleteVlanIpRange&id=1&apiKey=identity&signature=tTBbpdCndgHXdR397fbbJaN1RZU%3D\"))\n            .addHeader(\"Accept\", \"application/json\")\n            .build(),\n         HttpResponse.builder()\n            .statusCode(200)\n            .payload(payloadFromResource(\"/createvlaniprangeresponse.json\"))\n            .build());\n\n      client.deleteVlanIPRange(\"1\");\n   }\n\n   @Override\n   protected GlobalVlanApi clientFrom(CloudStackContext context) {\n      return context.getGlobalApi().getVlanClient();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/GlobalVlanApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.jclouds.cloudstack.options.ListNetworksOptions.Builder.zoneId;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.Network;\nimport org.jclouds.cloudstack.domain.NetworkOffering;\nimport org.jclouds.cloudstack.domain.TrafficType;\nimport org.jclouds.cloudstack.domain.VlanIPRange;\nimport org.jclouds.cloudstack.domain.Zone;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest;\nimport org.jclouds.cloudstack.options.CreateVlanIPRangeOptions;\nimport org.jclouds.cloudstack.options.ListVlanIPRangesOptions;\nimport org.jclouds.cloudstack.predicates.NetworkOfferingPredicates;\nimport org.jclouds.cloudstack.predicates.ZonePredicates;\nimport org.testng.annotations.AfterGroups;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Strings;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Sets;\n\n/**\n * Tests behavior of {@code GlobalVlanApi}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"GlobalVlanApiLiveTest\")\npublic class GlobalVlanApiLiveTest extends BaseCloudStackApiLiveTest {\n\n   private Network network;\n   private boolean usingExistingNetwork;\n\n   private VlanIPRange range;\n\n   @Test\n   public void testListVlanIPRanges() throws Exception {\n      skipIfNotGlobalAdmin();\n\n      Set<VlanIPRange> response = globalAdminClient.getVlanClient().listVlanIPRanges();\n      assert null != response;\n      long rangeCount = response.size();\n      assertTrue(rangeCount >= 0);\n\n      for (VlanIPRange range : response) {\n         VlanIPRange newDetails = Iterables.getOnlyElement(globalAdminClient.getVlanClient().listVlanIPRanges(\n            ListVlanIPRangesOptions.Builder.id(range.getId())));\n         assertEquals(range, newDetails);\n         assertEquals(range, globalAdminClient.getVlanClient().getVlanIPRange(range.getId()));\n         assertNull(range.getId());\n         assertNull(range.getZoneId());\n         assertFalse(Strings.isNullOrEmpty(range.getVlan()));\n         assertFalse(Strings.isNullOrEmpty(range.getAccount()));\n         assertNull(range.getDomainId());\n         assertFalse(Strings.isNullOrEmpty(range.getDomain()));\n         assertFalse(Strings.isNullOrEmpty(range.getGateway()));\n         assertFalse(Strings.isNullOrEmpty(range.getNetmask()));\n         assertFalse(Strings.isNullOrEmpty(range.getStartIP()));\n         assertFalse(Strings.isNullOrEmpty(range.getEndIP()));\n         assertNull(range.getNetworkId());\n      }\n   }\n\n   @Test\n   public void testCreateVlanIPRange() {\n      skipIfNotGlobalAdmin();\n\n      final Zone zone = Iterables.find(client.getZoneApi().listZones(), ZonePredicates.supportsAdvancedNetworks());\n      final NetworkOffering offering = Iterables.tryFind(client.getOfferingApi().listNetworkOfferings(),\n                                                         NetworkOfferingPredicates.supportsGuestVirtualNetworks()).orNull();\n\n      if (offering != null) {\n         Set<Network> suitableNetworks = Sets.filter(client.getNetworkApi().listNetworks(\n                                                                                         zoneId(zone.getId()).isSystem(false).trafficType(TrafficType.GUEST)),\n                                                     new Predicate<Network>() {\n                                                        @Override\n                                                        public boolean apply(Network network) {\n                                                           return network.getNetworkOfferingId().equals(offering.getId());\n                                                        }\n                                                     });\n\n         if (!suitableNetworks.isEmpty()) {\n            network = Iterables.get(suitableNetworks, 0);\n            usingExistingNetwork = true;\n\n         } else if (network == null) {\n            network = client.getNetworkApi().createNetworkInZone(zone.getId(),\n                                                                 offering.getId(), \"net-\" + prefix, \"jclouds test \" + prefix);\n            usingExistingNetwork = false;\n         }\n\n         range = globalAdminClient.getVlanClient().createVlanIPRange(\"172.19.1.1\", \"172.19.1.199\", CreateVlanIPRangeOptions.Builder\n                                                                     .accountInDomain(user.getAccount(), user.getDomainId())\n                                                                     .forVirtualNetwork(true)\n                                                                     .vlan(1001)\n                                                                     .networkId(network.getId())\n                                                                     );\n      }\n   }\n\n   @AfterGroups(groups = \"live\")\n   @Override\n   protected void tearDownContext() {\n      if (range != null) {\n         globalAdminClient.getVlanClient().deleteVlanIPRange(range.getId());\n         range = null;\n      }\n      if (network != null && !usingExistingNetwork) {\n         client.getNetworkApi().deleteNetwork(network.getId());\n         network = null;\n      }\n      super.tearDownContext();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/GlobalZoneApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.jclouds.cloudstack.options.UpdateZoneOptions.Builder.name;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\n\nimport org.jclouds.cloudstack.CloudStackContext;\nimport org.jclouds.cloudstack.domain.AllocationState;\nimport org.jclouds.cloudstack.domain.NetworkType;\nimport org.jclouds.cloudstack.domain.Zone;\nimport org.jclouds.cloudstack.internal.BaseCloudStackExpectTest;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMultimap;\n\n/**\n * Test the CloudStack GlobalZoneApi\n */\n@Test(groups = \"unit\", testName = \"GlobalZoneApiExpectTest\")\npublic class GlobalZoneApiExpectTest extends BaseCloudStackExpectTest<GlobalZoneApi> {\n\n   HttpRequest createZone = HttpRequest.builder().method(\"GET\")\n                                       .endpoint(\"http://localhost:8080/client/api\")\n                                       .addQueryParam(\"response\", \"json\")\n                                       .addQueryParam(\"command\", \"createZone\")\n                                       .addQueryParam(\"name\", \"test-zone\")\n                                       .addQueryParam(\"networktype\", \"Basic\")\n                                       .addQueryParam(\"dns1\", \"8.8.8.8\")\n                                       .addQueryParam(\"internaldns1\", \"10.10.10.10\")\n                                       .addQueryParam(\"apiKey\", \"identity\")\n                                       .addQueryParam(\"signature\", \"hWNmM2+Tsfb5DelQa/GJLN5DVWE=\")\n                                       .addHeader(\"Accept\", \"application/json\").build();\n   \n   public void testCreateZoneWhenResponseIs2xxAnd404() {\n      GlobalZoneApi client = requestSendsResponse(createZone,\n         HttpResponse.builder()\n            .statusCode(200)\n            .payload(payloadFromResource(\"/createzoneresponse.json\"))\n            .build());\n\n      assertEquals(client.createZone(\"test-zone\", NetworkType.BASIC, \"8.8.8.8\", \"10.10.10.10\"),\n         Zone.builder()\n            .id(\"6\")\n            .name(\"test-zone\")\n            .DNS(ImmutableList.of(\"8.8.8.8\"))\n            .internalDNS(ImmutableList.of(\"10.10.10.10\"))\n            .networkType(NetworkType.BASIC)\n            .securityGroupsEnabled(true)\n            .allocationState(AllocationState.ENABLED)\n            .zoneToken(\"7b6e27df-30a6-3024-9d8b-7971a3127f64\")\n            .dhcpProvider(\"DhcpServer\").build());\n\n      client = requestSendsResponse(createZone, HttpResponse.builder().statusCode(404).build());\n      assertNull(client.createZone(\"test-zone\", NetworkType.BASIC, \"8.8.8.8\", \"10.10.10.10\"));\n   }\n\n   public void testUpdateZoneWhenResponseIs2xxAnd404() {\n      HttpRequest request = HttpRequest.builder()\n            .method(\"GET\")\n            .endpoint(\"http://localhost:8080/client/api\")\n            .addQueryParam(\"response\", \"json\")\n            .addQueryParam(\"command\", \"updateZone\")\n            .addQueryParam(\"id\", \"6\")\n            .addQueryParam(\"name\", \"test-zone\")\n            .addQueryParam(\"dns1\", \"8.8.8.8\")\n            .addQueryParam(\"apiKey\", \"identity\")\n            .addQueryParam(\"signature\", \"v19FdHKHztdT0IRloYFFn0eNbWM=\")\n            .headers(ImmutableMultimap.<String, String>builder().put(\"Accept\", \"application/json\").build())\n            .build();\n\n      GlobalZoneApi client = requestSendsResponse(request,\n         HttpResponse.builder()\n            .statusCode(200)\n            .payload(payloadFromResource(\"/updatezoneresponse.json\"))\n            .build());\n\n      assertEquals(client.updateZone(\"6\", name(\"test-zone\").externalDns(ImmutableList.of(\"8.8.8.8\"))),\n         Zone.builder()\n            .id(\"6\")\n            .name(\"test-zone\")\n            .DNS(ImmutableList.of(\"8.8.8.8\"))\n            .internalDNS(ImmutableList.of(\"10.10.10.10\"))\n            .networkType(NetworkType.BASIC)\n            .securityGroupsEnabled(true)\n            .allocationState(AllocationState.ENABLED)\n            .zoneToken(\"7b6e27df-30a6-3024-9d8b-7971a3127f64\")\n            .dhcpProvider(\"DhcpServer\").build());\n\n      client = requestSendsResponse(request, HttpResponse.builder().statusCode(404).build());\n      assertNull(client.updateZone(\"6\", name(\"test-zone\").externalDns(ImmutableList.of(\"8.8.8.8\"))));\n   }\n\n   public void testDeleteZone() {\n      GlobalZoneApi client = requestSendsResponse(\n         HttpRequest.builder()\n               .method(\"GET\")\n               .endpoint(\"http://localhost:8080/client/api\")\n               .addQueryParam(\"response\", \"json\")\n               .addQueryParam(\"command\", \"deleteZone\")\n               .addQueryParam(\"id\", \"6\")\n               .addQueryParam(\"apiKey\", \"identity\")\n               .addQueryParam(\"signature\", \"TfkzSIK8kzGJnIYo3DofECyuOII=\")\n               .addHeader(\"Accept\", \"application/json\")\n               .build(),\n         HttpResponse.builder()\n               .statusCode(200)\n               .payload(payloadFromResource(\"/deletezoneresponse.json\"))\n               .build());\n\n      client.deleteZone(\"6\");\n   }\n\n   @Override\n   protected GlobalZoneApi clientFrom(CloudStackContext context) {\n      return context.getGlobalApi().getZoneApi();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/GlobalZoneApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.jclouds.cloudstack.options.UpdateZoneOptions.Builder.name;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport org.jclouds.cloudstack.domain.NetworkType;\nimport org.jclouds.cloudstack.domain.Zone;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tests behavior of {@code GlobalZoneApi}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"GlobalZoneApiLiveTest\")\npublic class GlobalZoneApiLiveTest extends BaseCloudStackApiLiveTest {\n\n   @Test\n   public void testCreateUpdateDeleteZone() {\n      skipIfNotGlobalAdmin();\n\n      Zone zone = null;\n      String zoneName = prefix + \"-zone\";\n      try {\n         zone = globalAdminClient.getZoneApi().createZone(zoneName,\n            NetworkType.BASIC, \"8.8.8.8\", \"10.10.10.10\");\n\n         assertNotNull(zone);\n         assertEquals(zone, globalAdminClient.getZoneApi().getZone(zone.getId()));\n         assertEquals(zone.getNetworkType(), NetworkType.BASIC);\n         assertEquals(zone.getDNS(), ImmutableList.of(\"8.8.8.8\"));\n         assertEquals(zone.getInternalDNS(), ImmutableList.of(\"10.10.10.10\"));\n\n         Zone updated = globalAdminClient.getZoneApi().updateZone(zone.getId(),\n            name(zoneName + \"-2\").externalDns(ImmutableList.of(\"8.8.4.4\")));\n         assertEquals(updated.getId(), zone.getId());\n         assertEquals(updated.getDNS(), ImmutableList.of(\"8.8.4.4\"));\n\n      } finally {\n         if (zone != null) {\n            globalAdminClient.getZoneApi().deleteZone(zone.getId());\n         }\n      }\n\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/GuestOSApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.OSType;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest;\nimport org.jclouds.cloudstack.options.ListOSTypesOptions;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code GuestOSApiLiveTest}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"GuestOSApiLiveTest\")\npublic class GuestOSApiLiveTest extends BaseCloudStackApiLiveTest {\n\n   public void testListOSTypes() throws Exception {\n      Set<OSType> response = client.getGuestOSApi().listOSTypes();\n      assert null != response;\n      assertTrue(response.size() > 0);\n      for (OSType type : response) {\n         OSType newDetails = getOnlyElement(client.getGuestOSApi().listOSTypes(\n               ListOSTypesOptions.Builder.id(type.getId())));\n         assertEquals(type.getId(), newDetails.getId());\n         checkOSType(type);\n      }\n   }\n\n   public void testListOSCategories() throws Exception {\n      Map<String, String> response = client.getGuestOSApi().listOSCategories();\n      assert null != response;\n      assertTrue(response.size() > 0);\n      for (Entry<String, String> category : response.entrySet()) {\n         checkOSCategory(category);\n      }\n   }\n\n   protected void checkOSCategory(Entry<String, String> category) {\n      assertEquals(category, client.getGuestOSApi().getOSCategory(category.getKey()));\n      assert category.getKey() != null : category;\n      assert category.getValue() != null : category;\n   }\n\n   protected void checkOSType(OSType type) {\n      assertEquals(type.getId(), client.getGuestOSApi().getOSType(type.getId()).getId());\n      assert type.getId() != null : type;\n      assert type.getOSCategoryId() != null : type;\n      assert type.getDescription() != null : type;\n\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/GuestOSApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport java.io.IOException;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.cloudstack.functions.ParseIdToNameEntryFromHttpResponse;\nimport org.jclouds.cloudstack.functions.ParseIdToNameFromHttpResponse;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiTest;\nimport org.jclouds.cloudstack.options.ListOSTypesOptions;\nimport org.jclouds.functions.IdentityFunction;\nimport org.jclouds.http.functions.ParseFirstJsonValueNamed;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Functions;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.reflect.Invokable;\n/**\n * Tests behavior of {@code GuestOSApi}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"GuestOSApiTest\")\npublic class GuestOSApiTest extends BaseCloudStackApiTest<GuestOSApi> {\n\n   public void testGetOSCategory() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(GuestOSApi.class, \"getOSCategory\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(11L));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listOsCategories&listAll=true&id=11 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseIdToNameEntryFromHttpResponse.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testListOSCategories() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(GuestOSApi.class, \"listOSCategories\");\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listOsCategories&listAll=true HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseIdToNameFromHttpResponse.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testGetOSType() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(GuestOSApi.class, \"getOSType\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(11L));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listOsTypes&listAll=true&id=11 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest,\n            Functions.compose(IdentityFunction.INSTANCE, IdentityFunction.INSTANCE).getClass());\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testListOSTypes() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(GuestOSApi.class, \"listOSTypes\", ListOSTypesOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listOsTypes&listAll=true HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testListOSTypesOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(GuestOSApi.class, \"listOSTypes\", ListOSTypesOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(ListOSTypesOptions.Builder.OSCategoryId(\"11\")));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listOsTypes&listAll=true&oscategoryid=11 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/HypervisorApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.Zone;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code HypervisorApiLiveTest}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"HypervisorApiLiveTest\")\npublic class HypervisorApiLiveTest extends BaseCloudStackApiLiveTest {\n\n   public void testListHypervisors() throws Exception {\n      Set<String> response = client.getHypervisorApi().listHypervisors();\n      assert null != response;\n      assertTrue(response.size() > 0);\n      for (Zone zone : client.getZoneApi().listZones()) {\n         Set<String> zoneHype = client.getHypervisorApi().listHypervisorsInZone(zone.getId());\n         assert response.containsAll(zoneHype);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/HypervisorApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport java.io.IOException;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.cloudstack.functions.ParseNamesFromHttpResponse;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiTest;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.reflect.Invokable;\n/**\n * Tests behavior of {@code HypervisorApi}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"HypervisorApiTest\")\npublic class HypervisorApiTest extends BaseCloudStackApiTest<HypervisorApi> {\n\n   public void testListHypervisors() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(HypervisorApi.class, \"listHypervisors\");\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listHypervisors&listAll=true HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseNamesFromHttpResponse.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testListHypervisorsInZon() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(HypervisorApi.class, \"listHypervisorsInZone\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(11));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listHypervisors&listAll=true&zoneid=11 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseNamesFromHttpResponse.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/ISOApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.jclouds.cloudstack.options.ListISOsOptions.Builder.accountInDomain;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\n\nimport org.jclouds.cloudstack.CloudStackContext;\nimport org.jclouds.cloudstack.domain.ISO;\nimport org.jclouds.cloudstack.internal.BaseCloudStackExpectTest;\nimport org.jclouds.cloudstack.options.RegisterISOOptions;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Test the CloudStack ISOApi\n */\n@Test(groups = \"unit\", testName = \"ISOApiExpectTest\")\npublic class ISOApiExpectTest extends BaseCloudStackExpectTest<ISOApi> {\n   \n   private static final ISO iso1 = ISO.builder()\n                                      .id(\"018e0928-8205-4d8e-9329-f731a9ccd488\")\n                                      .name(\"xs-tools.iso\")\n                                      .displayText(\"xen-pv-drv-iso\")\n                                      .isPublic(true)\n                                      .created(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2012-08-21T15:45:01+0530\"))\n                                      .isReady(true)\n                                      .passwordEnabled(false)\n                                      .bootable(false)\n                                      .isFeatured(true)\n                                      .crossZones(false)\n                                      .account(\"system\")\n                                      .domain(\"ROOT\")\n                                      .domainid(\"9d189ea2-097e-4b2b-9bae-d885f5430d69\")\n                                      .isExtractable(false).build();\n   \n   private static final ISO iso2 = ISO.builder()\n                                      .id(\"1e29244b-9cf0-4ff2-9978-677eb83f6bfb\")\n                                      .name(\"vmware-tools.iso\")\n                                      .displayText(\"VMware Tools Installer ISO\")\n                                      .isPublic(true)\n                                      .created(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2012-08-21T15:45:01+0530\"))\n                                      .isReady(true)\n                                      .passwordEnabled(false)\n                                      .bootable(false)\n                                      .isFeatured(true)\n                                      .crossZones(false)\n                                      .account(\"system\")\n                                      .domain(\"ROOT\")\n                                      .domainid(\"9d189ea2-097e-4b2b-9bae-d885f5430d69\")\n                                      .isExtractable(false).build();\n\n   HttpRequest listIsos = HttpRequest.builder().method(\"GET\")\n                                     .endpoint(\"http://localhost:8080/client/api\")\n                                     .addQueryParam(\"response\", \"json\")\n                                     .addQueryParam(\"command\", \"listIsos\")\n                                     .addQueryParam(\"listAll\", \"true\")\n                                     .addQueryParam(\"apiKey\", \"identity\")\n                                     .addQueryParam(\"signature\", \"qUUF6hCDc57Bc/nHriS9umbZBKA=\")\n                                     .addHeader(\"Accept\", \"application/json\")\n                                     .build();\n   \n   public void testListISOsWhenResponseIs2xx() {\n      ISOApi client = requestSendsResponse(listIsos,\n         HttpResponse.builder()\n                     .statusCode(200)\n                     .payload(payloadFromResource(\"/listisosresponse.json\"))\n                     .build());\n\n      assertEquals(client.listISOs().toString(), ImmutableSet.of(iso1, iso2).toString());\n   }\n\n   public void testListISOsWhenResponseIs404() {\n      ISOApi client = requestSendsResponse(listIsos,\n         HttpResponse.builder()\n            .statusCode(404)\n            .build());\n\n      assertEquals(client.listISOs(), ImmutableSet.of());\n   }\n   \n   HttpRequest listIsosOptions = HttpRequest.builder().method(\"GET\")\n                                            .endpoint(\"http://localhost:8080/client/api\")\n                                            .addQueryParam(\"response\", \"json\")\n                                            .addQueryParam(\"command\", \"listIsos\")\n                                            .addQueryParam(\"listAll\", \"true\")\n                                            .addQueryParam(\"account\", \"fred\")\n                                            .addQueryParam(\"domainid\", \"5\")\n                                            .addQueryParam(\"bootable\", \"true\")\n                                            .addQueryParam(\"hypervisor\", \"xen\")\n                                            .addQueryParam(\"id\", \"3\")\n                                            .addQueryParam(\"isofilter\", \"featured\")\n                                            .addQueryParam(\"ispublic\", \"true\")\n                                            .addQueryParam(\"isready\", \"true\")\n                                            .addQueryParam(\"keyword\", \"bob\")\n                                            .addQueryParam(\"name\", \"bob's iso\")\n                                            .addQueryParam(\"zoneid\", \"7\")\n                                            .addQueryParam(\"apiKey\", \"identity\")\n                                            .addQueryParam(\"signature\", \"4S5ustbaBErEnpymWLSj1rEJ/nk=\")\n                                            .addHeader(\"Accept\", \"application/json\")\n                                            .build();\n   \n   public void testListISOsOptionsWhenResponseIs2xx() {\n      ISOApi client = requestSendsResponse(listIsosOptions,\n         HttpResponse.builder()\n                     .statusCode(200)\n                     .payload(payloadFromResource(\"/listisosresponse.json\"))\n                     .build());\n\n      assertEquals(client.listISOs(accountInDomain(\"fred\", \"5\").bootable().hypervisor(\"xen\").id(\"3\").isoFilter(ISO.ISOFilter.featured).isPublic().isReady().keyword(\"bob\").name(\"bob's iso\").zoneId(\"7\")).toString(), ImmutableSet.of(iso1, iso2).toString());\n   }\n\n   HttpRequest getIso = HttpRequest.builder().method(\"GET\")\n                                     .endpoint(\"http://localhost:8080/client/api\")\n                                     .addQueryParam(\"response\", \"json\")\n                                     .addQueryParam(\"command\", \"listIsos\")\n                                     .addQueryParam(\"listAll\", \"true\")\n                                     .addQueryParam(\"id\", \"018e0928-8205-4d8e-9329-f731a9ccd488\")\n                                     .addQueryParam(\"apiKey\", \"identity\")\n                                     .addQueryParam(\"signature\", \"uZyPUJt6ThMDcQSDa+Ev5LMs+2U=\")\n                                     .addHeader(\"Accept\", \"application/json\")\n                                     .build();\n   \n   public void testGetISOWhenResponseIs2xx() {\n      ISOApi client = requestSendsResponse(getIso,\n         HttpResponse.builder()\n                     .statusCode(200)\n                     .payload(payloadFromResource(\"/getisoresponse.json\"))\n                     .build());\n\n      assertEquals(client.getISO(\"018e0928-8205-4d8e-9329-f731a9ccd488\").toString(), iso1.toString());\n   }\n\n   public void testGetISOWhenResponseIs404() {\n      ISOApi client = requestSendsResponse(getIso,\n         HttpResponse.builder()\n            .statusCode(404)\n            .build());\n\n      assertNull(client.getISO(\"018e0928-8205-4d8e-9329-f731a9ccd488\"));\n   }\n\n   HttpRequest registerIso = HttpRequest.builder().method(\"GET\")\n                                        .endpoint(\"http://localhost:8080/client/api\")\n                                        .addQueryParam(\"response\", \"json\")\n                                        .addQueryParam(\"command\", \"registerIso\")\n                                        .addQueryParam(\"name\", \"ubuntu10.10\")\n                                        .addQueryParam(\"displaytext\", \"ubuntu 10.10 (32 bit)\")\n                                        .addQueryParam(\"url\", \"http://ubuntu/ubuntu-10.10.iso\")\n                                        .addQueryParam(\"zoneid\", \"1e0335d9-b6cc-4805-bddf-0828e66a0d01\")\n                                        .addQueryParam(\"account\", \"root\")\n                                        .addQueryParam(\"domainid\", \"99f4159b-c698-4bd9-b8c5-5ac462f101eb\")\n                                        .addQueryParam(\"bootable\", \"true\")\n                                        .addQueryParam(\"isextractable\", \"true\")\n                                        .addQueryParam(\"isfeatured\", \"true\")\n                                        .addQueryParam(\"ispublic\", \"true\")\n                                        .addQueryParam(\"ostypeid\", \"1234-abcd\")\n                                        .addQueryParam(\"apiKey\", \"identity\")\n                                        .addQueryParam(\"signature\", \"YpFMYUUu0daLgwxNFubVfkV0Nw8=\")\n                                        .addHeader(\"Accept\", \"application/json\")\n                                        .build();\n   \n   RegisterISOOptions registerISOOptions = RegisterISOOptions.Builder\n           .accountInDomain(\"root\", \"99f4159b-c698-4bd9-b8c5-5ac462f101eb\")\n           .bootable(true).isExtractable(true).isFeatured(true).isPublic(true).osTypeId(\"1234-abcd\");\n   \n   @Test\n   public void testRegisterISOsWhenResponseIs2xx() {\n      ISOApi client = requestSendsResponse(\n         registerIso,\n         HttpResponse.builder()\n            .statusCode(200)\n            .payload(payloadFromResource(\"/registerisoresponse.json\"))\n            .build());\n\n      assertEquals(client.registerISO(\"ubuntu10.10\", \"ubuntu 10.10 (32 bit)\", \"http://ubuntu/ubuntu-10.10.iso\", \"1e0335d9-b6cc-4805-bddf-0828e66a0d01\",\n              registerISOOptions),\n            ISO.builder().id(\"b52c509d-c6e2-452c-b6ec-aa00720ed6cd\").name(\"ubuntu10.10\").displayText(\"ubuntu 10.10 (32 bit)\").isPublic(true)\n                .isReady(false).bootable(true).isFeatured(false).crossZones(false).osTypeId(\"0e0335d9-b6cc-4808-bddf-0828e66a0d03\")\n                .created(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2012-08-21T15:45:01+0530\"))\n                .osTypeName(\"Ubuntu 10.10 (32-bit)\").account(\"root\").domain(\"ROOT\").domainid(\"99f4159b-c698-4bd9-b8c5-5ac462f101eb\").status(\"\")\n                .account(\"admin\").zoneId(\"6f9a2921-b22a-4149-8b71-6ffc275a2177\").zoneName(\"Basic1\")\n                .isExtractable(false).build());\n   }\n   \n   @Test(expectedExceptions = ResourceNotFoundException.class)\n   public void testRegisterISOWhenResponseIs404() {\n       ISOApi client = requestSendsResponse(registerIso,\n          HttpResponse.builder()\n             .statusCode(404)\n             .build());\n\n       assertNull(client.registerISO(\"ubuntu10.10\", \"ubuntu 10.10 (32 bit)\", \"http://ubuntu/ubuntu-10.10.iso\", \"1e0335d9-b6cc-4805-bddf-0828e66a0d01\",\n               registerISOOptions));\n    }\n   \n   @Override\n   protected ISOApi clientFrom(CloudStackContext context) {\n      return context.getApi().getISOApi();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/ISOApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.jclouds.cloudstack.options.ListZonesOptions.Builder.available;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.ISO;\nimport org.jclouds.cloudstack.domain.ISOPermissions;\nimport org.jclouds.cloudstack.domain.OSType;\nimport org.jclouds.cloudstack.domain.Zone;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest;\nimport org.jclouds.cloudstack.options.DeleteISOOptions;\nimport org.jclouds.cloudstack.options.ListISOsOptions;\nimport org.jclouds.cloudstack.options.RegisterISOOptions;\nimport org.testng.SkipException;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicates;\nimport com.google.common.collect.Iterables;\n\n/**\n * Tests behavior of {@link ISOApi} and {@link ISOApi}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"ISOApiLiveTest\")\npublic class ISOApiLiveTest extends BaseCloudStackApiLiveTest {\n    \n   private static final String isoName = \"jcloudsTestISO\";\n   private static final String url = System.getProperty(\"test.cloudstack.iso-url\", \"http://archive.ubuntu.com/ubuntu/dists/maverick/main/installer-i386/current/images/netboot/mini.iso\");\n\n   public void testListPublicISOs() throws Exception {\n      Set<ISO> response = client.getISOApi().listISOs(ListISOsOptions.Builder.isPublic());\n      assertNotNull(response);\n      assertFalse(response.isEmpty());\n      long isoCount = response.size();\n      assertTrue(isoCount >= 0);\n\n      for (ISO iso : response) {\n         ISO query = client.getISOApi().getISO(iso.getId());\n         assertEquals(query.getId(), iso.getId());\n      }\n   }\n\n   public void testListISOPermissions() throws Exception {\n      Set<ISO> response = client.getISOApi().listISOs(ListISOsOptions.Builder.isPublic());\n      assertNotNull(response);\n      assertFalse(response.isEmpty());\n      long isoCount = response.size();\n      assertTrue(isoCount >= 0);\n\n      for (ISO iso : response) {\n         ISOPermissions perms = client.getISOApi().listISOPermissions(iso.getId());\n         assertNotNull(perms);\n      }\n   }\n   \n   public void testRegisterISO() throws Exception {\n      Optional<OSType> guestOSTypeOptional = Iterables.tryFind(client.getGuestOSApi().listOSTypes(), Predicates.notNull());\n      Optional<Zone> zoneOptional = Iterables.tryFind(client.getZoneApi().listZones(available(true)), Predicates.notNull());\n      if (guestOSTypeOptional.isPresent() && zoneOptional.isPresent()) {\n         String osTypeId = guestOSTypeOptional.get().getId();\n         String zoneId = zoneOptional.get().getId();\n         ISO iso = client.getISOApi().registerISO(isoName, \"\", url, zoneId, RegisterISOOptions.Builder.isPublic(true).osTypeId(osTypeId));\n             assertNotNull(iso);\n             assertNotNull(iso.getId());\n             assertEquals(iso.getName(), isoName);\n      } else {\n         String skipMessage = String.format(\"Cannot register the iso with url: %s\", url);\n         if (zoneOptional.isPresent())\n             skipMessage += \" without a valid zone\";\n         else\n             skipMessage += \" without a valid guest OS type\";\n         throw new SkipException(skipMessage);\n      }\n   }\n\n   @AfterClass\n   @Override\n   protected void tearDownContext() {\n       Set<ISO> isos = client.getISOApi().listISOs(ListISOsOptions.Builder.name(isoName));\n       for (ISO iso : isos) {\n           client.getISOApi().deleteISO(iso.getId(), DeleteISOOptions.NONE);\n       }\n       super.tearDownContext();\n   }\n  \n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/ISOApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport org.jclouds.cloudstack.domain.ExtractMode;\nimport org.jclouds.cloudstack.domain.PermissionOperation;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiTest;\nimport org.jclouds.cloudstack.options.AccountInDomainOptions;\nimport org.jclouds.cloudstack.options.DeleteISOOptions;\nimport org.jclouds.cloudstack.options.ExtractISOOptions;\nimport org.jclouds.cloudstack.options.UpdateISOOptions;\nimport org.jclouds.cloudstack.options.UpdateISOPermissionsOptions;\nimport org.jclouds.fallbacks.MapHttp4xxCodesToExceptions;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.functions.ParseFirstJsonValueNamed;\nimport org.jclouds.http.functions.ReleasePayloadAndReturn;\nimport org.jclouds.http.functions.UnwrapOnlyJsonValue;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.reflect.Invokable;\n/**\n * Tests the behaviour of ISOApi.\n * \n * @see ISOApi\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"ISOApiTest\")\npublic class ISOApiTest extends BaseCloudStackApiTest<ISOApi> {\n\n   public void testAttachISO() throws NoSuchMethodException {\n      Invokable<?, ?> method = method(ISOApi.class, \"attachISO\", String.class, String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"3\", \"5\"));\n\n      assertRequestLineEquals(httpRequest,\n         \"GET http://localhost:8080/client/api?response=json&command=attachIso&id=3&virtualmachineid=5 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testDetachISO() throws NoSuchMethodException {\n      Invokable<?, ?> method = method(ISOApi.class, \"detachISO\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(3));\n\n      assertRequestLineEquals(httpRequest,\n         \"GET http://localhost:8080/client/api?response=json&command=detachIso&virtualmachineid=3 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testUpdateISO() throws NoSuchMethodException {\n      Invokable<?, ?> method = method(ISOApi.class, \"updateISO\", String.class, UpdateISOOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(3));\n\n      assertRequestLineEquals(httpRequest,\n         \"GET http://localhost:8080/client/api?response=json&command=updateIso&id=3 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testUpdateISOOptions() throws NoSuchMethodException {\n      Invokable<?, ?> method = method(ISOApi.class, \"updateISO\", String.class, UpdateISOOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(3, UpdateISOOptions.Builder.bootable(true).displayText(\"robert\").format(\"format\").name(\"bob\").osTypeId(\"9\").passwordEnabled(true)));\n\n      assertRequestLineEquals(httpRequest,\n         \"GET http://localhost:8080/client/api?response=json&command=updateIso&id=3&bootable=true&displaytext=robert&format=format&name=bob&ostypeid=9&passwordenabled=true HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testDeleteISO() throws NoSuchMethodException {\n      Invokable<?, ?> method = method(ISOApi.class, \"deleteISO\", String.class, DeleteISOOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(3));\n\n      assertRequestLineEquals(httpRequest,\n         \"GET http://localhost:8080/client/api?response=json&command=deleteIso&id=3 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testDeleteISOOptions() throws NoSuchMethodException {\n      Invokable<?, ?> method = method(ISOApi.class, \"deleteISO\", String.class, DeleteISOOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(3, DeleteISOOptions.Builder.zoneId(\"5\")));\n\n      assertRequestLineEquals(httpRequest,\n         \"GET http://localhost:8080/client/api?response=json&command=deleteIso&id=3&zoneid=5 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n   }\n\n   HttpRequest copyIso = HttpRequest.builder().method(\"GET\")\n                                    .endpoint(\"http://localhost:8080/client/api\")\n                                    .addQueryParam(\"response\", \"json\")\n                                    .addQueryParam(\"command\", \"copyIso\")\n                                    .addQueryParam(\"id\", \"3\")\n                                    .addQueryParam(\"sourcezoneid\", \"5\")\n                                    .addQueryParam(\"destzoneid\", \"7\")\n                                    .build();\n\n   public void testCopyISO() throws NoSuchMethodException {\n      Invokable<?, ?> method = method(ISOApi.class, \"copyISO\", String.class, String.class, String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(3, 5, 7));\n\n      assertRequestLineEquals(httpRequest, copyIso.getRequestLine());\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testUpdateISOPermissions() throws NoSuchMethodException {\n      Invokable<?, ?> method = method(ISOApi.class, \"updateISOPermissions\", String.class, UpdateISOPermissionsOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(3));\n\n      assertRequestLineEquals(httpRequest,\n         \"GET http://localhost:8080/client/api?response=json&command=updateIsoPermissions&id=3 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testUpdateISOPermissionsOptions() throws NoSuchMethodException {\n      Invokable<?, ?> method = method(ISOApi.class, \"updateISOPermissions\", String.class, UpdateISOPermissionsOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(3, UpdateISOPermissionsOptions.Builder.accounts(ImmutableSet.<String>of(\"fred\", \"bob\")).isExtractable(true).isFeatured(true).isPublic(true).operation(PermissionOperation.add)));\n\n      assertRequestLineEquals(httpRequest,\n         \"GET http://localhost:8080/client/api?response=json&command=updateIsoPermissions&id=3&accounts=fred,bob&isextractable=true&isfeatured=true&ispublic=true&op=add HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testListISOPermissions() throws NoSuchMethodException {\n      Invokable<?, ?> method = method(ISOApi.class, \"listISOPermissions\", String.class, AccountInDomainOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(3));\n\n      assertRequestLineEquals(httpRequest,\n         \"GET http://localhost:8080/client/api?response=json&command=listIsoPermissions&listAll=true&id=3 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testListISOPermissionsOptions() throws NoSuchMethodException {\n      Invokable<?, ?> method = method(ISOApi.class, \"listISOPermissions\", String.class, AccountInDomainOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(3, AccountInDomainOptions.Builder.accountInDomain(\"fred\", \"5\")));\n\n      assertRequestLineEquals(httpRequest,\n         \"GET http://localhost:8080/client/api?response=json&command=listIsoPermissions&listAll=true&id=3&account=fred&domainid=5 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n   }\n\n   HttpRequest extractIso = HttpRequest.builder().method(\"GET\")\n                                       .endpoint(\"http://localhost:8080/client/api\")\n                                       .addQueryParam(\"response\", \"json\")\n                                       .addQueryParam(\"command\", \"extractIso\")\n                                       .addQueryParam(\"id\", \"3\")\n                                       .addQueryParam(\"mode\", \"HTTP_DOWNLOAD\")\n                                       .addQueryParam(\"zoneid\", \"5\")\n                                       .build();\n\n   public void testExtractISO() throws NoSuchMethodException {\n      Invokable<?, ?> method = method(ISOApi.class, \"extractISO\", String.class, ExtractMode.class, String.class, ExtractISOOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(3, ExtractMode.HTTP_DOWNLOAD, 5));\n\n      assertRequestLineEquals(httpRequest, extractIso.getRequestLine());\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n   }\n\n   HttpRequest extractIsoOptions = HttpRequest.builder().method(\"GET\")\n                                              .endpoint(\"http://localhost:8080/client/api\")\n                                              .addQueryParam(\"response\", \"json\")\n                                              .addQueryParam(\"command\", \"extractIso\")\n                                              .addQueryParam(\"id\", \"3\")\n                                              .addQueryParam(\"mode\", \"HTTP_DOWNLOAD\")\n                                              .addQueryParam(\"zoneid\", \"5\")\n                                              .addQueryParam(\"url\", \"http://example.com/\")\n                                              .build();\n\n   public void testExtractISOOptions() throws NoSuchMethodException {\n      Invokable<?, ?> method = method(ISOApi.class, \"extractISO\", String.class, ExtractMode.class, String.class, ExtractISOOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(3, ExtractMode.HTTP_DOWNLOAD, 5, ExtractISOOptions.Builder.url(\"http://example.com/\")));\n\n      assertRequestLineEquals(httpRequest, extractIsoOptions.getRequestLine());\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/LimitApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.ResourceLimit;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code LimitApi}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"LimitApiLiveTest\")\npublic class LimitApiLiveTest extends BaseCloudStackApiLiveTest {\n\n   public void testListResourceLimits() {\n      final Set<ResourceLimit> resourceLimits = client.getLimitApi().listResourceLimits();\n\n      for (ResourceLimit resourceLimit : resourceLimits) {\n         checkResourceLimit(resourceLimit);\n      }\n   }\n\n   private void checkResourceLimit(ResourceLimit resourceLimit) {\n      assert resourceLimit.getAccount() != null : resourceLimit;\n      assert resourceLimit.getDomain() != null : resourceLimit;\n      assert resourceLimit.getResourceType() != ResourceLimit.ResourceType.UNRECOGNIZED : resourceLimit;\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/LimitApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport java.io.IOException;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiTest;\nimport org.jclouds.cloudstack.options.ListResourceLimitsOptions;\nimport org.jclouds.http.functions.ParseFirstJsonValueNamed;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.reflect.Invokable;\n\n/**\n * Tests behavior of {@code LimitApi}\n */\n@Test(groups = \"unit\", testName = \"LimitApiTest\")\npublic class LimitApiTest extends BaseCloudStackApiTest<LimitApi> {\n\n   public void testListResourceLimits() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(LimitApi.class, \"listResourceLimits\", ListResourceLimitsOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listResourceLimits&listAll=true HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testListResourceLimitsOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(LimitApi.class, \"listResourceLimits\", ListResourceLimitsOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(ListResourceLimitsOptions.Builder.account(\"jclouds\", \"23\")));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listResourceLimits&listAll=true&account=jclouds&domainid=23 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/LoadBalancerApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static com.google.common.collect.Iterables.find;\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static org.jclouds.cloudstack.predicates.NetworkPredicates.hasLoadBalancerService;\nimport static org.jclouds.cloudstack.predicates.NetworkPredicates.isVirtualNetwork;\nimport static org.jclouds.util.Predicates2.retry;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.util.NoSuchElementException;\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.AsyncJob;\nimport org.jclouds.cloudstack.domain.JobResult;\nimport org.jclouds.cloudstack.domain.LoadBalancerRule;\nimport org.jclouds.cloudstack.domain.LoadBalancerRule.Algorithm;\nimport org.jclouds.cloudstack.domain.LoadBalancerRule.State;\nimport org.jclouds.cloudstack.domain.Network;\nimport org.jclouds.cloudstack.domain.PublicIPAddress;\nimport org.jclouds.cloudstack.domain.VirtualMachine;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest;\nimport org.jclouds.cloudstack.predicates.LoadBalancerRuleActive;\nimport org.jclouds.ssh.SshException;\nimport org.testng.annotations.AfterGroups;\nimport org.testng.annotations.BeforeGroups;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Predicates;\nimport com.google.common.net.HostAndPort;\n\n/**\n * Tests behavior of {@code LoadBalancerApiLiveTest}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"LoadBalancerApiLiveTest\")\npublic class LoadBalancerApiLiveTest extends BaseCloudStackApiLiveTest {\n   private PublicIPAddress ip = null;\n   private VirtualMachine vm;\n   private LoadBalancerRule rule;\n   private Predicate<LoadBalancerRule> loadBalancerRuleActive;\n   private Network network;\n   private boolean networksDisabled;\n\n   @BeforeGroups(groups = \"live\")\n   public void setupContext() {\n      super.setupContext();\n      loadBalancerRuleActive = retry(new LoadBalancerRuleActive(client), 60, 1, 1, SECONDS);\n      prefix += \"rule\";\n      try {\n         network = find(client.getNetworkApi().listNetworks(),\n               Predicates.and(hasLoadBalancerService(), isVirtualNetwork(),\n                  new Predicate<Network>() {\n                     @Override\n                     public boolean apply(Network network) {\n                        return network.isDefault()\n                           && !network.isSecurityGroupEnabled()\n                           && !network.isSystem()\n                           && network.getAccount().equals(user.getName());\n                     }\n                  }));\n      } catch (NoSuchElementException e) {\n         networksDisabled = true;\n      }\n   }\n\n   public void testCreateVm() {\n      if (networksDisabled)\n         return;\n      String defaultTemplate = templateBuilderSpec != null ? templateBuilderSpec.getImageId() : null;\n      vm = VirtualMachineApiLiveTest.createVirtualMachineInNetwork(network,\n            defaultTemplateOrPreferredInZone(defaultTemplate, client, network.getZoneId()),\n            client, jobComplete, virtualMachineRunning);\n      if (vm.getPassword() != null && !loginCredentials.getOptionalPassword().isPresent())\n         loginCredentials = loginCredentials.toBuilder().password(vm.getPassword()).build();\n   }\n\n   @Test(dependsOnMethods = \"testCreateVm\")\n   public void testCreateLoadBalancerRule() throws Exception {\n      if (networksDisabled)\n         return;\n      int attempts = 0;\n      while (rule == null && attempts < 10) {\n         ip = reuseOrAssociate.apply(network);\n         try {\n            String jobId = client.getLoadBalancerApi().createLoadBalancerRuleForPublicIP(ip.getId(),\n                  Algorithm.LEASTCONN, prefix, 22, 22);\n            assertTrue(jobComplete.apply(jobId));\n            AsyncJob<LoadBalancerRule> asyncJob = client.getAsyncJobApi().getAsyncJob(jobId);\n            LoadBalancerRule result = asyncJob.getResult();\n            rule = result;\n         } catch (IllegalStateException e) {\n            // very likely an ip conflict, so retry;\n            attempts++;\n         }\n      }\n      assertNotNull(rule, \"Failed to get a load balancer rule after \" + attempts + \" attempts\");\n      assertEquals(rule.getPublicIPId(), ip.getId());\n      assertEquals(rule.getPublicPort(), 22);\n      assertEquals(rule.getPrivatePort(), 22);\n      assertEquals(rule.getAlgorithm(), Algorithm.LEASTCONN);\n      assertEquals(rule.getName(), prefix);\n      assertEquals(rule.getState(), State.ADD);\n      assertEquals(client.getLoadBalancerApi().listVirtualMachinesAssignedToLoadBalancerRule(rule.getId()).size(), 0);\n      checkRule(rule);\n\n   }\n\n   @Test(dependsOnMethods = \"testCreateLoadBalancerRule\")\n   public void testAssignToLoadBalancerRule() throws Exception {\n      if (networksDisabled)\n         return;\n      String jobId = client.getLoadBalancerApi().assignVirtualMachinesToLoadBalancerRule(rule.getId(), vm.getId());\n      assertTrue(jobComplete.apply(jobId));\n      AsyncJob<JobResult> result = client.getAsyncJobApi().getAsyncJob(jobId);\n      assertTrue(result.hasSucceed());\n      Set<VirtualMachine> machines = client.getLoadBalancerApi().listVirtualMachinesAssignedToLoadBalancerRule(\n            rule.getId());\n      assertEquals(machines.size(), 1);\n      assertTrue(loadBalancerRuleActive.apply(rule), rule.toString());\n   }\n\n   @Test(dependsOnMethods = \"testAssignToLoadBalancerRule\")\n   public void testCanSshInThroughNewLoadBalancerRule() throws Exception {\n      loopAndCheckSSH();\n   }\n\n   // note that when in LB mode, there's a chance you'll have a connection\n   // failure\n   private void loopAndCheckSSH() throws IOException {\n      for (int i = 0; i < 5; i++) {// retry loop TODO replace with predicate.\n         try {\n            checkSSH(HostAndPort.fromParts(ip.getIPAddress(), 22));\n            return;\n         } catch (SshException e) {\n            e.printStackTrace();\n            try {\n               Thread.sleep(10 * 1000);\n            } catch (InterruptedException e1) {\n            }\n            continue;\n         }\n      }\n   }\n\n   @Test(dependsOnMethods = \"testAssignToLoadBalancerRule\", expectedExceptions = SshException.class)\n   public void testRemoveFromLoadBalancerRule() throws Exception {\n      if (networksDisabled)\n         throw new SshException();\n      assertTrue(jobComplete.apply(client.getLoadBalancerApi().removeVirtualMachinesFromLoadBalancerRule(\n            rule.getId(), vm.getId())));\n      assertEquals(client.getLoadBalancerApi().listVirtualMachinesAssignedToLoadBalancerRule(rule.getId()).size(), 0);\n      assertEquals(rule.getState(), State.ADD);\n      checkSSH(HostAndPort.fromParts(ip.getIPAddress(), 22));\n   }\n\n   @AfterGroups(groups = \"live\")\n   @Override\n   protected void tearDownContext() {\n      if (rule != null) {\n         assertTrue(jobComplete.apply(client.getLoadBalancerApi().deleteLoadBalancerRule(rule.getId())));\n      }\n      if (vm != null) {\n         assertTrue(jobComplete.apply(client.getVirtualMachineApi().destroyVirtualMachine(vm.getId())));\n      }\n      if (ip != null) {\n         client.getAddressApi().disassociateIPAddress(ip.getId());\n      }\n      super.tearDownContext();\n   }\n\n   public void testListLoadBalancerRules() throws Exception {\n      Set<LoadBalancerRule> response = client.getLoadBalancerApi().listLoadBalancerRules();\n      assert null != response;\n      assertTrue(response.size() > 0);\n      for (LoadBalancerRule rule : response) {\n         LoadBalancerRule newDetails = findRuleWithId(rule.getId());\n         assertEquals(rule.getId(), newDetails.getId());\n         checkRule(rule);\n      }\n   }\n\n   private LoadBalancerRule findRuleWithId(final String id) {\n      return find(client.getLoadBalancerApi().listLoadBalancerRules(), new Predicate<LoadBalancerRule>() {\n\n         @Override\n         public boolean apply(LoadBalancerRule arg0) {\n            return Objects.equal(arg0.getId(), id);\n         }\n\n      });\n   }\n\n   protected void checkRule(LoadBalancerRule rule) {\n      assertEquals(rule.getId(), findRuleWithId(rule.getId()).getId());\n      assert rule.getId() != null : rule;\n      assert rule.getAccount() != null : rule;\n      assert rule.getAlgorithm() != null : rule;\n      assert rule.getPrivatePort() > 0 : rule;\n      assert rule.getPublicPort() > 0 : rule;\n      assert rule.getDomain() != null : rule;\n      assert rule.getDomainId() != null : rule;\n      assert rule.getState() != null : rule;\n      assert rule.getName() != null : rule;\n      assert rule.getPublicIP() != null : rule;\n      assert rule.getPublicIPId() != null : rule;\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/LoadBalancerApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport java.io.IOException;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.cloudstack.domain.LoadBalancerRule.Algorithm;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiTest;\nimport org.jclouds.cloudstack.options.CreateLoadBalancerRuleOptions;\nimport org.jclouds.cloudstack.options.ListLoadBalancerRulesOptions;\nimport org.jclouds.cloudstack.options.UpdateLoadBalancerRuleOptions;\nimport org.jclouds.fallbacks.MapHttp4xxCodesToExceptions;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.functions.ParseFirstJsonValueNamed;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.reflect.Invokable;\n/**\n * Tests behavior of {@code LoadBalancerApi}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"LoadBalancerApiTest\")\npublic class LoadBalancerApiTest extends BaseCloudStackApiTest<LoadBalancerApi> {\n   public void testListLoadBalancerRules() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(LoadBalancerApi.class, \"listLoadBalancerRules\",\n            ListLoadBalancerRulesOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listLoadBalancerRules&listAll=true HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testListLoadBalancerRulesOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(LoadBalancerApi.class, \"listLoadBalancerRules\",\n            ListLoadBalancerRulesOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(ListLoadBalancerRulesOptions.Builder.publicIPId(\"3\")));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listLoadBalancerRules&listAll=true&publicipid=3 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   HttpRequest createLoadBalancerRule = HttpRequest.builder().method(\"GET\")\n                                                   .endpoint(\"http://localhost:8080/client/api\")\n                                                   .addQueryParam(\"response\", \"json\")\n                                                   .addQueryParam(\"command\", \"createLoadBalancerRule\")\n                                                   .addQueryParam(\"publicipid\", \"6\")\n                                                   .addQueryParam(\"algorithm\", \"leastconn\")\n                                                   .addQueryParam(\"name\", \"tcp\")\n                                                   .addQueryParam(\"privateport\", \"22\")\n                                                   .addQueryParam(\"publicport\", \"22\").build();\n\n   public void testCreateLoadBalancerRuleForPublicIP() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(LoadBalancerApi.class, \"createLoadBalancerRuleForPublicIP\", String.class,\n            Algorithm.class, String.class, int.class, int.class, CreateLoadBalancerRuleOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(6, Algorithm.LEASTCONN, \"tcp\", 22, 22));\n\n      assertRequestLineEquals(httpRequest, createLoadBalancerRule.getRequestLine());\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testUpdateLoadBalancerRule() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(LoadBalancerApi.class, \"updateLoadBalancerRule\", String.class, UpdateLoadBalancerRuleOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(5));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=updateLoadBalancerRule&id=5 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testDeleteLoadBalancerRule() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(LoadBalancerApi.class, \"deleteLoadBalancerRule\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(5));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=deleteLoadBalancerRule&id=5 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testListVirtualMachinesAssignedToLoadBalancerRule() throws SecurityException, NoSuchMethodException,\n         IOException {\n      Invokable<?, ?> method = method(LoadBalancerApi.class, \"listVirtualMachinesAssignedToLoadBalancerRule\",\n            String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(5));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listLoadBalancerRuleInstances&listAll=true&id=5 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/NATApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.IPForwardingRule;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest;\nimport org.jclouds.cloudstack.options.ListIPForwardingRulesOptions;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code NATApiLiveTest}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"NATApiLiveTest\")\npublic class NATApiLiveTest extends BaseCloudStackApiLiveTest {\n\n   @Test(enabled = false)\n   // takes too long\n   public void testListIPForwardingRules() throws Exception {\n      Set<IPForwardingRule> response = client.getNATApi().listIPForwardingRules();\n      assert null != response;\n      assertTrue(response.size() > 0);\n      for (IPForwardingRule rule : response) {\n         IPForwardingRule newDetails = getOnlyElement(client.getNATApi().listIPForwardingRules(\n               ListIPForwardingRulesOptions.Builder.id(rule.getId())));\n         assertEquals(rule.getId(), newDetails.getId());\n         checkRule(rule);\n      }\n   }\n\n   protected void checkRule(IPForwardingRule rule) {\n      assertEquals(rule.getId(), client.getNATApi().getIPForwardingRule(rule.getId()).getId());\n      assert rule.getId() != null : rule;\n      assert rule.getIPAddress() != null : rule;\n      assert rule.getIPAddressId() != null : rule;\n      assert rule.getStartPort() > 0 : rule;\n      assert rule.getProtocol() != null : rule;\n      assert rule.getEndPort() > 0 : rule;\n      assert rule.getState() != null : rule;\n      assert rule.getVirtualMachineId() != null : rule;\n      assert rule.getVirtualMachineName() != null : rule;\n\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/NATApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport java.io.IOException;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiTest;\nimport org.jclouds.cloudstack.options.CreateIPForwardingRuleOptions;\nimport org.jclouds.cloudstack.options.ListIPForwardingRulesOptions;\nimport org.jclouds.fallbacks.MapHttp4xxCodesToExceptions;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.functions.ParseFirstJsonValueNamed;\nimport org.jclouds.http.functions.ReleasePayloadAndReturn;\nimport org.jclouds.http.functions.UnwrapOnlyJsonValue;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.reflect.Invokable;\n/**\n * Tests behavior of {@code NATApi}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"NATApiTest\")\npublic class NATApiTest extends BaseCloudStackApiTest<NATApi> {\n   public void testListIPForwardingRules() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(NATApi.class, \"listIPForwardingRules\", ListIPForwardingRulesOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listIpForwardingRules&listAll=true HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testListIPForwardingRulesOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(NATApi.class, \"listIPForwardingRules\", ListIPForwardingRulesOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\n            ListIPForwardingRulesOptions.Builder.virtualMachineId(\"3\")));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listIpForwardingRules&listAll=true&virtualmachineid=3 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testGetIPForwardingRule() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(NATApi.class, \"getIPForwardingRule\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(5));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listIpForwardingRules&listAll=true&id=5 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   HttpRequest createIpForwardingRule = HttpRequest.builder().method(\"GET\")\n                                                             .endpoint(\"http://localhost:8080/client/api\")\n                                                             .addQueryParam(\"response\", \"json\")\n                                                             .addQueryParam(\"command\", \"createIpForwardingRule\")\n                                                             .addQueryParam(\"ipaddressid\", \"7\")\n                                                             .addQueryParam(\"protocol\", \"tcp\")\n                                                             .addQueryParam(\"startport\", \"22\").build();\n\n   public void testCreateIPForwardingRuleForVirtualMachine() throws SecurityException, NoSuchMethodException,\n         IOException {\n      Invokable<?, ?> method = method(NATApi.class, \"createIPForwardingRule\", String.class, String.class, int.class,\n            CreateIPForwardingRuleOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(7, \"tcp\", 22));\n\n      assertRequestLineEquals(httpRequest, createIpForwardingRule.getRequestLine());\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   HttpRequest createIpForwardingRuleOptions = HttpRequest.builder().method(\"GET\")\n                                                          .endpoint(\"http://localhost:8080/client/api\")\n                                                          .addQueryParam(\"response\", \"json\")\n                                                          .addQueryParam(\"command\", \"createIpForwardingRule\")\n                                                          .addQueryParam(\"ipaddressid\", \"7\")\n                                                          .addQueryParam(\"protocol\", \"tcp\")\n                                                          .addQueryParam(\"startport\", \"22\")\n                                                          .addQueryParam(\"endport\", \"22\").build();\n\n   public void testCreateIPForwardingRuleForVirtualMachineOptions() throws SecurityException, NoSuchMethodException,\n         IOException {\n      Invokable<?, ?> method = method(NATApi.class, \"createIPForwardingRule\", String.class, String.class, int.class,\n            CreateIPForwardingRuleOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(7, \"tcp\", 22,\n            CreateIPForwardingRuleOptions.Builder.endPort(22)));\n\n      assertRequestLineEquals(httpRequest, createIpForwardingRuleOptions.getRequestLine());\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testEnableStaticNATForVirtualMachine() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(NATApi.class, \"enableStaticNATForVirtualMachine\", String.class, String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(5, 6));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=enableStaticNat&virtualmachineid=5&ipaddressid=6 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testDisableStaticNATOnPublicIP() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(NATApi.class, \"disableStaticNATOnPublicIP\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(5));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=disableStaticNat&ipaddressid=5 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testDeleteIPForwardingRule() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(NATApi.class, \"deleteIPForwardingRule\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(5));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=deleteIpForwardingRule&id=5 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/NetworkApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static com.google.common.collect.Iterables.find;\nimport static com.google.common.collect.Iterables.get;\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static org.jclouds.cloudstack.options.CreateNetworkOptions.Builder.vlan;\nimport static org.jclouds.cloudstack.options.ListNetworkOfferingsOptions.Builder.specifyVLAN;\nimport static org.jclouds.cloudstack.options.ListNetworksOptions.Builder.accountInDomain;\nimport static org.jclouds.cloudstack.options.ListNetworksOptions.Builder.id;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.NoSuchElementException;\nimport java.util.Set;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\n\nimport org.jclouds.cloudstack.domain.GuestIPType;\nimport org.jclouds.cloudstack.domain.Network;\nimport org.jclouds.cloudstack.domain.NetworkOffering;\nimport org.jclouds.cloudstack.domain.Zone;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest;\nimport org.jclouds.cloudstack.predicates.NetworkOfferingPredicates;\nimport org.jclouds.cloudstack.predicates.ZonePredicates;\nimport org.testng.annotations.BeforeGroups;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code NetworkApiLiveTest}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"NetworkApiLiveTest\")\npublic class NetworkApiLiveTest extends BaseCloudStackApiLiveTest {\n\n   private boolean networksSupported;\n   private Zone zone;\n\n   @BeforeGroups(groups = \"live\")\n   public void setupContext() {\n      super.setupContext();\n\n      try {\n         zone = find(client.getZoneApi().listZones(), ZonePredicates.supportsAdvancedNetworks());\n         networksSupported = true;\n      } catch (NoSuchElementException e) {\n      }\n   }\n\n   @Test\n   public void testCreateGuestVirtualNetwork() {\n      if (!networksSupported)\n         return;\n      final NetworkOffering offering;\n      try {\n         offering = find(client.getOfferingApi().listNetworkOfferings(),\n               NetworkOfferingPredicates.supportsGuestVirtualNetworks());\n\n      } catch (NoSuchElementException e) {\n         Logger.getAnonymousLogger().log(Level.SEVERE, \"guest networks not supported, skipping test\");\n         return;\n      }\n      String name = prefix + \"-virtual\";\n\n      Network network = null;\n      try {\n         network = client.getNetworkApi().createNetworkInZone(zone.getId(), offering.getId(), name, name);\n         checkNetwork(network);\n      } catch (IllegalStateException e) {\n         Logger.getAnonymousLogger().log(Level.SEVERE, \"couldn't create a network, skipping test\", e);\n      } finally {\n         if (network != null) {\n            String jobId = client.getNetworkApi().deleteNetwork(network.getId());\n            if (jobId != null)\n               jobComplete.apply(jobId);\n         }\n      }\n   }\n\n   @Test\n   public void testCreateVLANNetwork() {\n      skipIfNotDomainAdmin();\n      if (!networksSupported)\n         return;\n\n      final NetworkOffering offering;\n      try {\n         offering = get(\n               cloudStackContext.getApi().getOfferingApi().listNetworkOfferings(specifyVLAN(true).zoneId(zone.getId())), 0);\n      } catch (NoSuchElementException e) {\n         Logger.getAnonymousLogger().log(Level.SEVERE, \"VLAN networks not supported, skipping test\");\n         return;\n      }\n      String name = prefix + \"-vlan\";\n\n      Network network = null;\n      try {\n         network = domainAdminClient\n               .getNetworkApi()\n               // startIP/endIP/netmask/gateway must be specified together\n               .createNetworkInZone(zone.getId(), offering.getId(), name, name,\n                     vlan(\"65\").startIP(\"192.168.1.2\").netmask(\"255.255.255.0\").gateway(\"192.168.1.1\"));\n         checkNetwork(network);\n      } catch (IllegalStateException e) {\n         Logger.getAnonymousLogger().log(Level.SEVERE, \"couldn't create a network, skipping test\", e);\n      } finally {\n         if (network != null) {\n            String jobId = adminClient.getNetworkApi().deleteNetwork(network.getId());\n            if (jobId != null)\n               adminJobComplete.apply(jobId);\n         }\n      }\n   }\n\n   @Test\n   public void testListNetworks() throws Exception {\n      if (!networksSupported)\n         return;\n      Set<Network> response = client.getNetworkApi().listNetworks(\n            accountInDomain(user.getAccount(), user.getDomainId()));\n      assert null != response;\n      long networkCount = response.size();\n      assertTrue(networkCount >= 0);\n      for (Network network : response) {\n         Network newDetails = getOnlyElement(client.getNetworkApi().listNetworks(id(network.getId())));\n         assertEquals(network, newDetails);\n         assertEquals(network, client.getNetworkApi().getNetwork(network.getId()));\n         checkNetwork(network);\n      }\n   }\n\n   private void checkNetwork(Network network) {\n      assert network.getId() != null : network;\n      assert network.getName() != null : network;\n      assert network.getDNS().size() != 0 : network;\n      assert network.getGuestIPType() != null && network.getGuestIPType() != GuestIPType.UNRECOGNIZED : network;\n      assert network.getBroadcastDomainType() != null : network;\n      assert network.getDisplayText() != null : network;\n      // Network domain can be null sometimes\n      // assert network.getNetworkDomain() != null : network;\n      assert network.getNetworkOfferingAvailability() != null : network;\n      assert network.getNetworkOfferingDisplayText() != null : network;\n      assert network.getNetworkOfferingId() != null : network;\n      assert network.getNetworkOfferingName() != null : network;\n      assert network.getRelated() != null : network;\n      assert network.getServices().size() != 0 : network;\n      assert network.getState() != null : network;\n      assert network.getTrafficType() != null : network;\n      assert network.getZoneId() != null : network;\n      assert network.getDomain() != null : network;\n      switch (network.getGuestIPType()) {\n      case VIRTUAL:\n         assert network.getNetmask() == null : network;\n         assert network.getGateway() == null : network;\n         assert network.getVLAN() == null : network;\n         assert network.getStartIP() == null : network;\n         assert network.getEndIP() == null : network;\n         break;\n      case DIRECT:\n         // TODO: I've found a network that doesn't have a netmask associated\n         assert network.getNetmask() != null : network;\n         assert network.getGateway() != null : network;\n         assert network.getVLAN() != null : network;\n         assertEquals(network.getBroadcastURI(), URI.create(\"vlan://\" + network.getVLAN()));\n         assert network.getStartIP() != null : network;\n         assert network.getEndIP() != null : network;\n         break;\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/NetworkApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport java.io.IOException;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.cloudstack.domain.NetworkType;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiTest;\nimport org.jclouds.cloudstack.options.CreateNetworkOptions;\nimport org.jclouds.cloudstack.options.ListNetworksOptions;\nimport org.jclouds.fallbacks.MapHttp4xxCodesToExceptions;\nimport org.jclouds.functions.IdentityFunction;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.functions.ParseFirstJsonValueNamed;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Functions;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.reflect.Invokable;\n/**\n * Tests behavior of {@code NetworkApi}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"NetworkApiTest\")\npublic class NetworkApiTest extends BaseCloudStackApiTest<NetworkApi> {\n   public void testListNetworks() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(NetworkApi.class, \"listNetworks\", ListNetworksOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listNetworks&listAll=true HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testListNetworksOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(NetworkApi.class, \"listNetworks\", ListNetworksOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(ListNetworksOptions.Builder.type(NetworkType.ADVANCED)\n            .domainId(\"6\").id(\"5\")));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listNetworks&listAll=true&type=Advanced&domainid=6&id=5 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testGetNetwork() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(NetworkApi.class, \"getNetwork\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"id\"));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listNetworks&listAll=true&id=id HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest,\n            Functions.compose(IdentityFunction.INSTANCE, IdentityFunction.INSTANCE).getClass());\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   HttpRequest createNetwork = HttpRequest.builder().method(\"GET\")\n                                          .endpoint(\"http://localhost:8080/client/api\")\n                                          .addQueryParam(\"response\", \"json\")\n                                          .addQueryParam(\"command\", \"createNetwork\")\n                                          .addQueryParam(\"zoneid\", \"1\")\n                                          .addQueryParam(\"networkofferingid\", \"2\")\n                                          .addQueryParam(\"name\", \"named\")\n                                          .addQueryParam(\"displaytext\", \"lovely\").build();\n\n   public void testCreateNetworkInZone() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(NetworkApi.class, \"createNetworkInZone\", String.class, String.class, String.class,\n            String.class, CreateNetworkOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(1, 2, \"named\", \"lovely\"));\n\n      assertRequestLineEquals(httpRequest, createNetwork.getRequestLine());\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   HttpRequest createNetworkOptions = HttpRequest.builder().method(\"GET\")\n                                                 .endpoint(\"http://localhost:8080/client/api\")\n                                                 .addQueryParam(\"response\", \"json\")\n                                                 .addQueryParam(\"command\", \"createNetwork\")\n                                                 .addQueryParam(\"zoneid\", \"1\")\n                                                 .addQueryParam(\"networkofferingid\", \"2\")\n                                                 .addQueryParam(\"name\", \"named\")\n                                                 .addQueryParam(\"displaytext\", \"lovely\")\n                                                 .addQueryParam(\"netmask\", \"255.255.255.0\")\n                                                 .addQueryParam(\"domainid\", \"6\").build();\n\n   public void testCreateNetworkInZoneOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(NetworkApi.class, \"createNetworkInZone\", String.class, String.class, String.class,\n            String.class, CreateNetworkOptions[].class);\n\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(1, 2, \"named\", \"lovely\", CreateNetworkOptions.Builder\n            .netmask(\"255.255.255.0\").domainId(\"6\")));\n\n      assertRequestLineEquals(httpRequest, createNetworkOptions.getRequestLine());\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testDeleteNetwork() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(NetworkApi.class, \"deleteNetwork\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(5));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=deleteNetwork&id=5 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/OfferingApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.NoSuchElementException;\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.DiskOffering;\nimport org.jclouds.cloudstack.domain.NetworkOffering;\nimport org.jclouds.cloudstack.domain.ServiceOffering;\nimport org.jclouds.cloudstack.domain.StorageType;\nimport org.jclouds.cloudstack.domain.TrafficType;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest;\nimport org.jclouds.cloudstack.options.ListDiskOfferingsOptions;\nimport org.jclouds.cloudstack.options.ListNetworkOfferingsOptions;\nimport org.jclouds.cloudstack.options.ListServiceOfferingsOptions;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicates;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\n\n/**\n * Tests behavior of {@code OfferingApi}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"OfferingApiLiveTest\")\npublic class OfferingApiLiveTest extends BaseCloudStackApiLiveTest {\n\n   public void testListDiskOfferings() throws Exception {\n      Set<DiskOffering> response = client.getOfferingApi().listDiskOfferings();\n      assert null != response;\n      long offeringCount = response.size();\n      assertTrue(offeringCount >= 0);\n      for (DiskOffering offering : response) {\n         try {\n           DiskOffering newDetails = Iterables.getOnlyElement(client.getOfferingApi().listDiskOfferings(\n               ListDiskOfferingsOptions.Builder.id(offering.getId())));\n           assertEquals(offering, newDetails);\n           assertEquals(offering, client.getOfferingApi().getDiskOffering(offering.getId()));\n           assert offering.getId() != null : offering;\n           assert offering.getName() != null : offering;\n           assert offering.getCreated() != null : offering;\n           assert offering.getDisplayText() != null : offering;\n           assert offering.getDiskSize() > 0 || (offering.getDiskSize() == 0 && offering.isCustomized()) : offering;\n           assert offering.getTags() != null : offering;\n\n         } catch (NoSuchElementException e) {\n            // This bug is present both in 2.2.8 and 2.2.12\n            assertTrue(Predicates.in(ImmutableSet.of(\"2.2.8\", \"2.2.12\")).apply(apiVersion));\n         }\n      }\n   }\n\n   public void testListServiceOfferings() throws Exception {\n      Set<ServiceOffering> response = client.getOfferingApi().listServiceOfferings();\n      assert null != response;\n      long offeringCount = response.size();\n      assertTrue(offeringCount >= 0);\n      for (ServiceOffering offering : response) {\n         ServiceOffering newDetails = Iterables.getOnlyElement(client.getOfferingApi().listServiceOfferings(\n               ListServiceOfferingsOptions.Builder.id(offering.getId())));\n         assertEquals(offering, newDetails);\n\n         assert offering.getId() != null : offering;\n         assert offering.getName() != null : offering;\n         assert offering.getDisplayText() != null : offering;\n         assert offering.getCpuNumber() > 0 : offering;\n         assert offering.getCpuSpeed() > 0 : offering;\n         assert offering.getMemory() > 0 : offering;\n         assert offering.getStorageType() != null && StorageType.UNRECOGNIZED != offering.getStorageType() : offering;\n         assert offering.getTags() != null : offering;\n      }\n   }\n\n   public void testListNetworkOfferings() throws Exception {\n      Set<NetworkOffering> response = client.getOfferingApi().listNetworkOfferings();\n      assert null != response;\n      long offeringCount = response.size();\n      assertTrue(offeringCount >= 0);\n      for (NetworkOffering offering : response) {\n         NetworkOffering newDetails = Iterables.getOnlyElement(client.getOfferingApi().listNetworkOfferings(\n               ListNetworkOfferingsOptions.Builder.id(offering.getId())));\n         assertEquals(offering, newDetails);\n         assertEquals(offering, client.getOfferingApi().getNetworkOffering(offering.getId()));\n         assert offering.getId() != null : offering;\n         assert offering.getName() != null : offering;\n         assert offering.getDisplayText() != null : offering;\n         assert offering.getMaxConnections() == null || offering.getMaxConnections() > 0 : offering;\n         assert offering.getTrafficType() != null && TrafficType.UNRECOGNIZED != offering.getTrafficType() : offering;\n         assert offering.getTags() != null : offering;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/OfferingApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.jclouds.cloudstack.domain.NetworkOfferingAvailabilityType.DEFAULT;\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport java.io.IOException;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiTest;\nimport org.jclouds.cloudstack.options.ListDiskOfferingsOptions;\nimport org.jclouds.cloudstack.options.ListNetworkOfferingsOptions;\nimport org.jclouds.cloudstack.options.ListServiceOfferingsOptions;\nimport org.jclouds.functions.IdentityFunction;\nimport org.jclouds.http.functions.ParseFirstJsonValueNamed;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Functions;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.reflect.Invokable;\n/**\n * Tests behavior of {@code OfferingApi}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"OfferingApiTest\")\npublic class OfferingApiTest extends BaseCloudStackApiTest<OfferingApi> {\n   public void testListDiskOfferings() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(OfferingApi.class, \"listDiskOfferings\", ListDiskOfferingsOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listDiskOfferings&listAll=true HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testListDiskOfferingsOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(OfferingApi.class, \"listDiskOfferings\", ListDiskOfferingsOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(ListDiskOfferingsOptions.Builder.domainId(\"6\").id(\"5\")));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listDiskOfferings&listAll=true&domainid=6&id=5 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testGetDiskOffering() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(OfferingApi.class, \"getDiskOffering\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"5\"));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listDiskOfferings&listAll=true&id=5 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest,\n            Functions.compose(IdentityFunction.INSTANCE, IdentityFunction.INSTANCE).getClass());\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testListNetworkOfferings() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(OfferingApi.class, \"listNetworkOfferings\", ListNetworkOfferingsOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listNetworkOfferings&listAll=true HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testListNetworkOfferingsOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(OfferingApi.class, \"listNetworkOfferings\", ListNetworkOfferingsOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\n         ListNetworkOfferingsOptions.Builder.availability(DEFAULT).isShared(true).id(\"6\")));\n\n      assertRequestLineEquals(\n            httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listNetworkOfferings&listAll=true&availability=Default&isshared=true&id=6 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testGetNetworkOffering() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(OfferingApi.class, \"getNetworkOffering\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"5\"));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listNetworkOfferings&listAll=true&id=5 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest,\n            Functions.compose(IdentityFunction.INSTANCE, IdentityFunction.INSTANCE).getClass());\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testListServiceOfferings() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(OfferingApi.class, \"listServiceOfferings\", ListServiceOfferingsOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listServiceOfferings&listAll=true HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testListServiceOfferingsOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(OfferingApi.class, \"listServiceOfferings\", ListServiceOfferingsOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(ListServiceOfferingsOptions.Builder.virtualMachineId(\"4\")\n            .domainId(\"5\").id(\"6\")));\n\n      assertRequestLineEquals(\n            httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listServiceOfferings&listAll=true&virtualmachineid=4&domainid=5&id=6 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testGetServiceOffering() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(OfferingApi.class, \"getServiceOffering\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"5\"));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listServiceOfferings&listAll=true&id=5 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest,\n            Functions.compose(IdentityFunction.INSTANCE, IdentityFunction.INSTANCE).getClass());\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/ProjectApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.CloudStackContext;\nimport org.jclouds.cloudstack.domain.Project;\nimport org.jclouds.cloudstack.domain.Tag;\nimport org.jclouds.cloudstack.internal.BaseCloudStackExpectTest;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Test the CloudStack ProjectApi\n */\n@Test(groups = \"unit\", testName = \"ProjectApiExpectTest\")\npublic class ProjectApiExpectTest extends BaseCloudStackExpectTest<ProjectApi> {\n\n\n   public void testListProjectsWhenResponseIs2xx() {\n\n      ProjectApi client = requestSendsResponse(\n         HttpRequest.builder()\n            .method(\"GET\")\n            .endpoint(\"http://localhost:8080/client/api?response=json&command=listProjects&listAll=true&apiKey=identity&signature=vtCqaYXfXttr6mD18Es0e22QBIQ%3D\")\n            .addHeader(\"Accept\", \"application/json\")\n            .build(),\n         HttpResponse.builder()\n            .statusCode(200)\n            .payload(payloadFromResource(\"/listprojectsresponse.json\"))\n            .build());\n\n      Set<Project> projects = ImmutableSet.of(\n            Project.builder()\n                  .id(\"489da162-0b77-489d-b044-ce39aa018b1f\")\n                  .account(\"thyde\")\n                  .displayText(\"\")\n                  .domain(\"ROOT\")\n                  .domainId(\"41a4917b-7952-499d-ba7f-4c57464d3dc8\")\n                  .name(\"NN-HA-T1\")\n                  .state(Project.State.ACTIVE).build(),\n            Project.builder()\n                  .id(\"1c11f22c-15ac-4fa7-b833-4d748df317b7\")\n                  .account(\"prasadm\")\n                  .displayText(\"Hive\")\n                  .domain(\"ROOT\")\n                  .domainId(\"41a4917b-7952-499d-ba7f-4c57464d3dc8\")\n                  .name(\"hive\")\n                  .state(Project.State.ACTIVE)\n                  .tags(Tag.builder()\n                        .account(\"prasadm\")\n                        .domain(\"ROOT\")\n                        .domainId(\"41a4917b-7952-499d-ba7f-4c57464d3dc8\")\n                        .key(\"some-tag\")\n                        .resourceId(\"1c11f22c-15ac-4fa7-b833-4d748df317b7\")\n                        .resourceType(Tag.ResourceType.PROJECT)\n                        .value(\"some-value\")\n                        .build())\n                  .build());\n\n      assertEquals(client.listProjects(), projects);\n   }\n\n   @Override\n   protected ProjectApi clientFrom(CloudStackContext context) {\n      return context.getApi().getProjectApi();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/ProjectApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport org.jclouds.cloudstack.domain.Project;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code ProjectApi}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"ProjectApiLiveTest\")\npublic class ProjectApiLiveTest extends BaseCloudStackApiLiveTest {\n\n   @Test\n   public void testListAccounts() throws Exception {\n      for (Project project : client.getProjectApi().listProjects())\n         checkProject(project);\n   }\n\n   protected void checkProject(Project project) {\n      assertNotNull(project.getId());\n      assertEquals(project.toString(), client.getProjectApi().getProject(project.getId()).toString());\n      assertNotNull(project.getState());\n      assertNotEquals(project.getState(), Project.State.UNRECOGNIZED);\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/ProjectApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport java.io.IOException;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiTest;\nimport org.jclouds.cloudstack.options.ListProjectsOptions;\nimport org.jclouds.functions.IdentityFunction;\nimport org.jclouds.http.functions.ParseFirstJsonValueNamed;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Functions;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.reflect.Invokable;\n\n/**\n * Tests behavior of {@code ProjectApi}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"ProjectApiTest\")\npublic class ProjectApiTest extends BaseCloudStackApiTest<ProjectApi> {\n\n   public void testListProjects() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ProjectApi.class, \"listProjects\", ListProjectsOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listProjects&listAll=true HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testListProjectsOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ProjectApi.class, \"listProjects\", ListProjectsOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\n            ListProjectsOptions.Builder.accountInDomain(\"jclouds\", \"123\")));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listProjects&listAll=true&account=jclouds&domainid=123 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testGetAccount() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ProjectApi.class, \"getProject\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"3\"));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listProjects&listAll=true&id=3 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest,\n            Functions.compose(IdentityFunction.INSTANCE, IdentityFunction.INSTANCE).getClass());\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/SSHKeyPairApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.UnsupportedEncodingException;\nimport java.net.URI;\n\nimport org.jclouds.cloudstack.CloudStackContext;\nimport org.jclouds.cloudstack.domain.SshKeyPair;\nimport org.jclouds.cloudstack.internal.BaseCloudStackExpectTest;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.ssh.SshKeys;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Test the CloudStack SSHKeyPairApi\n */\n@Test(groups = \"unit\", testName = \"SSHKeyPairApiExpectTest\")\npublic class SSHKeyPairApiExpectTest extends BaseCloudStackExpectTest<SSHKeyPairApi> {\n\n   @Test\n   public void testListAndGetSSHKeyPairsWhenResponseIs2xx() {\n      HttpResponse response = HttpResponse.builder()\n         .statusCode(200)\n         .payload(payloadFromResource(\"/listsshkeypairsresponse.json\"))\n         .build();\n\n      SSHKeyPairApi client = requestSendsResponse(HttpRequest.builder()\n         .method(\"GET\")\n         .endpoint(\n            URI.create(\"http://localhost:8080/client/api?response=json&\" +\n               \"command=listSSHKeyPairs&listAll=true&apiKey=identity&signature=5d2J9u%2BdKpkQsadDbl9i9OcUSLQ%3D\"))\n            .addHeader(\"Accept\", \"application/json\")\n         .build(), response);\n\n      assertEquals(client.listSSHKeyPairs(), ImmutableSet.of(\n         SshKeyPair.builder().name(\"jclouds-keypair\")\n            .fingerprint(\"1c:06:74:52:3b:99:1c:95:5c:04:c2:f4:ba:77:6e:7b\").build()));\n\n      client = requestSendsResponse(HttpRequest.builder()\n         .method(\"GET\")\n         .endpoint(\n            URI.create(\"http://localhost:8080/client/api?response=json&command=listSSHKeyPairs&listAll=true&\" +\n               \"name=jclouds-keypair&apiKey=identity&signature=hJIVCFOHhdOww3aq19tFHpeD2HI%3D\"))\n            .addHeader(\"Accept\", \"application/json\")\n         .build(), response);\n\n      assertEquals(client.getSSHKeyPair(\"jclouds-keypair\"),\n         SshKeyPair.builder().name(\"jclouds-keypair\")\n            .fingerprint(\"1c:06:74:52:3b:99:1c:95:5c:04:c2:f4:ba:77:6e:7b\").build());\n   }\n\n   @Test\n   public void testCreateSSHKeyPairsWhenResponseIs2xx() {\n      SSHKeyPairApi client = requestSendsResponse(\n         HttpRequest.builder()\n            .method(\"GET\")\n            .endpoint(\n               URI.create(\"http://localhost:8080/client/api?response=json&command=createSSHKeyPair&\" +\n                  \"name=jclouds-keypair&apiKey=identity&signature=8wk32PZF44jrBLH2HLel22%2BqMC4%3D\"))\n            .addHeader(\"Accept\", \"application/json\")\n            .build(),\n         HttpResponse.builder()\n            .statusCode(200)\n            .payload(payloadFromResource(\"/createsshkeypairresponse.json\"))\n            .build());\n\n      SshKeyPair actual = client.createSSHKeyPair(\"jclouds-keypair\");\n      SshKeyPair expected = SshKeyPair.builder().name(\"jclouds-keypair\")\n         .fingerprint(\"1c:06:74:52:3b:99:1c:95:5c:04:c2:f4:ba:77:6e:7b\")\n         .privateKey(\"-----BEGIN RSA PRIVATE KEY-----\\n\" +\n            \"MIICXgIBAAKBgQDZo/EF4Ew1uEW0raz7vCs28lBwy0UKV2Xr606gaEgxO7h9mSXZ\\n\" +\n            \"4x2K/KQ1NMnrbjppxGycLh9EKPWAO3ezFULAyuOZW4Fy+xRS8+3MAijxBJY/KBgl\\n\" +\n            \"x5rJm2ILumRkTNkMlLGCSBb9SOqYRN1VpOy7kn3StzU9LdJ/snKVE2JLHQIDAQAB\\n\" +\n            \"AoGBAMnL5okKRd9xcsBqYIAxIuiZmNhcwTErhEdRMOAukPGFbDSYsa3rldLvGdpz\\n\" +\n            \"jd2LoQG8rO/LHBZ429kASqZzyiV+NvcgH+tFNJSVAigjSICfhEKF9PY2TiAkrg7S\\n\" +\n            \"GyJgAjpPWQc2sQh0dE8EPEtBiq4ibXfMTDmbs1d/vnfdwtQJAkEA+AX5Y+xgWj74\\n\" +\n            \"dYETmNLyLhNZpftLizEfIYj7lCVhsbFwVb8jbM1m8n8bxwGjls1w/ico1CWcQna+\\n\" +\n            \"UnAfA8kJvwJBAOCj0YgDKpYd0OLQhvI3212J9QcQpJEkDOTYiMwXNHCNMKRpoF47\\n\" +\n            \"MPPX+GG8YzUiQAi9/OG4pDKCjzQWE/ebiiMCQQCssnQ5WICqtggIwYykr9VDseON\\n\" +\n            \"SFIMpHJ5xkjumazRrqx6eDGxc8BH/6uWwRRoT7pqrVeniFyqhsX03u8pkpU/AkBj\\n\" +\n            \"WfCcwBHArNUqy2EzlWKuvwogosq16oTNXbs60HR/5uIBhTnJE1K2NemDiGc0I77A\\n\" +\n            \"Xw6N4jS0piuhtLYGB8OTAkEA50abdbduXWcr62Z6E8G/6LNFaNg0uBuVgwSHtJMd\\n\" +\n            \"dNeUtVDHQCHSf3tvxXTAtaB9PCnGOfgm/dyYWEMf3rMoHQ==\\n\" +\n            \"-----END RSA PRIVATE KEY-----\\n\")\n         .build();\n\n      assertEquals(actual, expected);\n      assertEquals(SshKeys.fingerprintPrivateKey(actual.getPrivateKey()), expected.getFingerprint());\n   }\n\n   @Test\n   public void testRegisterSSHKeyPairWhenResponseIs2xx() throws UnsupportedEncodingException {\n      String publicKey = \"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCc903twxU2zcQnIJdXv61RwZNZW94uId9qz08fgsBJsCOnHNIC4+L9kDOA2IHV9cUfEDBm1Be5TbpadWwSbS/05E+FARH2/MCO932UgcKUq5PGymS0249fLCBPci5zoLiG5vIym+1ij1hL/nHvkK99NIwe7io+Lmp9OcF3PTsm3Rgh5T09cRHGX9horp0VoAVa9vKJx6C1/IEHVnG8p0YPPa1lmemvx5kNBEiyoNQNYa34EiFkcJfP6rqNgvY8h/j4nE9SXoUCC/g6frhMFMOL0tzYqvz0Lczqm1Oh4RnSn3O9X4R934p28qqAobe337hmlLUdb6H5zuf+NwCh0HdZ\";\n\n      String privateKey = \"-----BEGIN RSA PRIVATE KEY-----\\n\" +\n         \"MIIEpQIBAAKCAQEAnPdN7cMVNs3EJyCXV7+tUcGTWVveLiHfas9PH4LASbAjpxzS\\n\" +\n         \"AuPi/ZAzgNiB1fXFHxAwZtQXuU26WnVsEm0v9ORPhQER9vzAjvd9lIHClKuTxspk\\n\" +\n         \"tNuPXywgT3Iuc6C4hubyMpvtYo9YS/5x75CvfTSMHu4qPi5qfTnBdz07Jt0YIeU9\\n\" +\n         \"PXERxl/YaK6dFaAFWvbyicegtfyBB1ZxvKdGDz2tZZnpr8eZDQRIsqDUDWGt+BIh\\n\" +\n         \"ZHCXz+q6jYL2PIf4+JxPUl6FAgv4On64TBTDi9Lc2Kr89C3M6ptToeEZ0p9zvV+E\\n\" +\n         \"fd+KdvKqgKG3t9+4ZpS1HW+h+c7n/jcAodB3WQIDAQABAoIBAQCX+iKr2LzLiUMo\\n\" +\n         \"lzexsFbB1+kxFe/zPryxD/QOEGzZa/+5KAB25+q5k0sqr3ZWkVXAk84pYaVut0F9\\n\" +\n         \"oD95P9q1A/GyV6zrNSHDywD+Lv0VMWMtkH0dV5Bjl7fY9DbhoXXIuAc81Rhs21mk\\n\" +\n         \"isIKME6Zra0VrYedGRfmE2usZc7F+rrnJeWs2edk1Q/lBLIe/v+NfRrO0fpHPu8S\\n\" +\n         \"9/kbVM3fUwHXxVTbvzZjjerQcLyEr4nT53DcSQJcm3e2DGsdRr5FBxkOXlcWElew\\n\" +\n         \"pbGM+RiF7RJvPW8lrmGj4y7Eo7TmfW8Yc5MM5A/PcvvxuRTRurmqOA5Wl1Bsp8/o\\n\" +\n         \"PEU/p9G5AoGBANcBOz0vSj+NOFip9gbc2WPVFpaoCT51DBQsT9R4kxe34Ltbwqaj\\n\" +\n         \"QXMiBjgereSM/KXTriA/Lhkj09YI5OAgk64PXcmDc2urMiFlewqxld79GDLAFwqn\\n\" +\n         \"nsEm1YTjY8wujw2J5Fbp7BZFHCrfld5L8xhgSb135YEa1/4LGOg+o6FDAoGBALrl\\n\" +\n         \"GL/v8ZDc2l/GpGsOA7360s9lRUhCTlQ86am8Lw/AdMSdpi9Is3yCdZx1NWDpUEKz\\n\" +\n         \"MBQTfiEEzpYlujvdUQNyQ4JGuhU/J7JEqEP2rfXaXjn0PIThkWFuNRkyK6Pz0rsT\\n\" +\n         \"4YJQouI7PCDE3BZxY4WYZ4uBZpCf3YC5SZiwtl0zAoGBAJGNnNwD+sDhSscDcLIe\\n\" +\n         \"qvDh3iPp6DAnLyEtCnItmm7RJcvRCAqltPZLj2hIpLJ4G8XrcxMTkpKkZZGdfcyZ\\n\" +\n         \"YUDR2E1Gt0mpoQto1w5bQLmwH8SjtDWbWmcqchw/kF03G9MviaypOhGtga8opB3U\\n\" +\n         \"zuKutN0WoQFw+c5bFuaLGV1fAoGABdFLy+20H0ZApeqRA6QUCb3dAges+GrX9VdQ\\n\" +\n         \"DrCE5oCfId+mZKJms+F7t7sORk386ZaaUIWqz2xO4e2atnJVKz5LS6rX8AFfQvVQ\\n\" +\n         \"J41uLND3TeaEW76Jv/amQHqHUTstvBUKV/waleAyJvL5xtkQt//eeUE16BqR0ofx\\n\" +\n         \"+obFpnECgYEAuDT1vH9JcGhD/iX4qLhS1xS1fXJh4IYvt8bg8oLRyRBqF6x9uhx3\\n\" +\n         \"6v+WQaKHyGvebWRN+SKAsKQHsh8a7Iy7xZdZmQ8v9j4DcYwJMb7ksV//R2kXAPGL\\n\" +\n         \"BTfRj1MSI+6AsuVY/YF1O2AfGneP+Zn5bQwYzQkxOYjzF9bhZz3IniE=\\n\" +\n         \"-----END RSA PRIVATE KEY-----\\n\";\n\n      // Compute the fingerprint by using the following command:  ssh-keygen -lf key.pub\n      String expectedFingerprint = \"8f:f1:91:2d:b1:a8:51:f1:79:cf:c4:31:c4:14:9d:81\";\n      \n      assertTrue(SshKeys.privateKeyMatchesPublicKey(privateKey, publicKey));\n      assertEquals(SshKeys.fingerprintPublicKey(publicKey), expectedFingerprint);\n      assertEquals(SshKeys.fingerprintPrivateKey(privateKey), expectedFingerprint);\n      \n      SSHKeyPairApi client = requestSendsResponse(\n         HttpRequest.builder()\n            .method(\"GET\")\n            .endpoint(\n               URI.create(\"http://localhost:8080/client/api?response=json&command=registerSSHKeyPair&\" +\n                  \"name=jclouds-keypair&publickey=\" + Strings2.urlEncode(publicKey, '/') +\n                  \"&apiKey=identity&signature=g/6BXLnnvOMlKQBp1yM7GKlvfus%3D\"))\n            .headers(\n               ImmutableMultimap.<String, String>builder()\n                  .put(\"Accept\", \"application/json\")\n                  .build())\n            .build(),\n         HttpResponse.builder()\n            .statusCode(200)\n            .payload(payloadFromResource(\"/registersshkeypairresponse.json\"))\n            .build());\n\n      SshKeyPair actual = client.registerSSHKeyPair(\"jclouds-keypair\", publicKey);\n      SshKeyPair expected = SshKeyPair.builder().name(\"jclouds-keypair\")\n         .fingerprint(expectedFingerprint).build();\n\n      assertEquals(actual, expected);\n      assertEquals(expectedFingerprint, expected.getFingerprint());\n   }\n\n   @Override\n   protected SSHKeyPairApi clientFrom(CloudStackContext context) {\n      return context.getApi().getSSHKeyPairApi();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/SSHKeyPairApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.SshKeyPair;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest;\nimport org.jclouds.ssh.SshKeys;\nimport org.testng.annotations.AfterMethod;\nimport org.testng.annotations.BeforeMethod;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code SSHKeyPairApi}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"SSHKeyPairApiLiveTest\")\npublic class SSHKeyPairApiLiveTest extends BaseCloudStackApiLiveTest {\n\n   protected String prefix = System.getProperty(\"user.name\");\n   private String keyPairName = prefix + \"-jclouds-keypair\";\n   private SshKeyPair sshKeyPair;\n\n   @BeforeMethod\n   @AfterMethod\n   public void removeExistingKey() {\n      client.getSSHKeyPairApi().deleteSSHKeyPair(keyPairName);\n   }\n\n   @Test\n   public void testListSSHKeyPairs() {\n      final Set<SshKeyPair> sshKeyPairs = client.getSSHKeyPairApi().listSSHKeyPairs();\n      for (SshKeyPair sshKeyPair : sshKeyPairs) {\n         checkSSHKeyPair(sshKeyPair);\n      }\n   }\n\n   @Test\n   public void testCreateDeleteSSHKeyPair() {\n      sshKeyPair = client.getSSHKeyPairApi().createSSHKeyPair(keyPairName);\n      assertNotNull(sshKeyPair.getPrivateKey());\n      checkSSHKeyPair(sshKeyPair);\n      client.getSSHKeyPairApi().deleteSSHKeyPair(sshKeyPair.getName());\n\n      assertEquals(client.getSSHKeyPairApi().getSSHKeyPair(sshKeyPair.getName()), null);\n      assertEquals(SshKeys.fingerprintPrivateKey(sshKeyPair.getPrivateKey()), sshKeyPair.getFingerprint());\n\n      sshKeyPair = null;\n   }\n\n   @Test\n   public void testRegisterDeleteSSHKeyPair() {\n      final Map<String, String> sshKey = SshKeys.generate();\n      final String publicKey = sshKey.get(\"public\");\n\n      sshKeyPair = client.getSSHKeyPairApi().registerSSHKeyPair(keyPairName, publicKey);\n      assertNull(sshKeyPair.getPrivateKey());\n      checkSSHKeyPair(sshKeyPair);\n      client.getSSHKeyPairApi().deleteSSHKeyPair(keyPairName);\n\n      assertEquals(client.getSSHKeyPairApi().getSSHKeyPair(sshKeyPair.getName()), null);\n      assertEquals(SshKeys.fingerprintPublicKey(publicKey), sshKeyPair.getFingerprint());\n\n      sshKeyPair = null;\n   }\n\n   protected void checkSSHKeyPair(SshKeyPair pair) {\n      assert pair.getName() != null : pair;\n      assertEquals(pair.getFingerprint(),\n         client.getSSHKeyPairApi().getSSHKeyPair(pair.getName()).getFingerprint());\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/SSHKeyPairApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.jclouds.reflect.Reflection2.method;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.cloudstack.filters.QuerySigner;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiTest;\nimport org.jclouds.cloudstack.options.ListSSHKeyPairsOptions;\nimport org.jclouds.fallbacks.MapHttp4xxCodesToExceptions;\nimport org.jclouds.functions.IdentityFunction;\nimport org.jclouds.http.functions.ParseFirstJsonValueNamed;\nimport org.jclouds.http.functions.ReleasePayloadAndReturn;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.jclouds.ssh.SshKeys;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Functions;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.reflect.Invokable;\n/**\n * Tests behavior of {@code SSHKeyPairApi}\n */\n@Test(groups = \"unit\", testName = \"SSHKeyPairApiTest\")\npublic class SSHKeyPairApiTest extends BaseCloudStackApiTest<SSHKeyPairApi> {\n\n   public void testListSSHKeyPairs() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(SSHKeyPairApi.class, \"listSSHKeyPairs\", ListSSHKeyPairsOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listSSHKeyPairs&listAll=true HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testListSSHKeyPairsOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(SSHKeyPairApi.class, \"listSSHKeyPairs\", ListSSHKeyPairsOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(ListSSHKeyPairsOptions.Builder.name(\"jclouds\")));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listSSHKeyPairs&listAll=true&name=jclouds HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testGetSSHKeyPair() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(SSHKeyPairApi.class, \"getSSHKeyPair\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"jclouds-keypair\"));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listSSHKeyPairs&listAll=true&name=jclouds-keypair HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest,\n            Functions.compose(IdentityFunction.INSTANCE, IdentityFunction.INSTANCE).getClass());\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testRegisterSSHKeyPair() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(SSHKeyPairApi.class, \"registerSSHKeyPair\", String.class, String.class);\n      String publicKey = SshKeys.generate().get(\"public\");\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"jclouds-keypair\", publicKey));\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=registerSSHKeyPair&name=jclouds-keypair&publickey=\"\n                  + Strings2.urlEncode(publicKey, '/')\n                  + \" HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      assertEquals(httpRequest.getFilters().size(), 1);\n      assertEquals(httpRequest.getFilters().get(0).getClass(), QuerySigner.class);\n   }\n\n\n   public void testDeleteSSHKeyPair() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(SSHKeyPairApi.class, \"deleteSSHKeyPair\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"jclouds-keypair\"));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=deleteSSHKeyPair&name=jclouds-keypair HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, VoidOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/SecurityGroupApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.Assert.fail;\n\nimport java.io.IOException;\nimport java.net.HttpURLConnection;\nimport java.net.URL;\nimport java.util.NoSuchElementException;\n\nimport org.jclouds.cloudstack.domain.IngressRule;\nimport org.jclouds.cloudstack.domain.SecurityGroup;\nimport org.jclouds.cloudstack.domain.VirtualMachine;\nimport org.jclouds.cloudstack.domain.Zone;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest;\nimport org.jclouds.cloudstack.options.AccountInDomainOptions;\nimport org.jclouds.cloudstack.options.DeployVirtualMachineOptions;\nimport org.jclouds.cloudstack.options.ListSecurityGroupsOptions;\nimport org.jclouds.util.Strings2;\nimport org.testng.SkipException;\nimport org.testng.annotations.AfterGroups;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.net.HostAndPort;\n\n/**\n * Tests behavior of {@code SecurityGroupApi}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"SecurityGroupApiLiveTest\")\npublic class SecurityGroupApiLiveTest extends BaseCloudStackApiLiveTest {\n   public SecurityGroupApiLiveTest() {\n      prefix += \"2\";\n   }\n\n   private SecurityGroup group;\n   private boolean securityGroupsSupported;\n   private VirtualMachine vm;\n   private Zone zone;\n\n   @Test\n   public void testCreateDestroySecurityGroup() {\n      try {\n         zone = Iterables.find(client.getZoneApi().listZones(), new Predicate<Zone>() {\n\n            @Override\n            public boolean apply(Zone arg0) {\n               return arg0.isSecurityGroupsEnabled();\n            }\n\n         });\n         securityGroupsSupported = true;\n         for (SecurityGroup securityGroup : client.getSecurityGroupApi().listSecurityGroups(\n               ListSecurityGroupsOptions.Builder.named(prefix))) {\n            for (IngressRule rule : securityGroup.getIngressRules())\n               assertTrue(jobComplete.apply(client.getSecurityGroupApi().revokeIngressRule(rule.getId())), rule.toString());\n            client.getSecurityGroupApi().deleteSecurityGroup(securityGroup.getId());\n         }\n         group = client.getSecurityGroupApi().createSecurityGroup(prefix);\n         assertEquals(group.getName(), prefix);\n         checkGroup(group);\n         try {\n            client.getSecurityGroupApi().createSecurityGroup(prefix);\n            fail(\"Expected IllegalStateException\");\n         } catch (IllegalStateException e) {\n\n         }\n      } catch (NoSuchElementException e) {\n         e.printStackTrace();\n      }\n   }\n\n   public static String getCurrentCIDR() throws IOException {\n      URL url = new URL(\"http://checkip.amazonaws.com/\");\n      HttpURLConnection connection = (HttpURLConnection) url.openConnection();\n      connection.connect();\n      return Strings2.toStringAndClose(connection.getInputStream()).trim() + \"/32\";\n   }\n   \n   protected void skipIfSecurityGroupsNotSupported() {\n      if (!securityGroupsSupported) {\n         throw new SkipException(\"Test cannot run without security groups supported in a zone\");\n      }\n   }\n   \n   @Test(dependsOnMethods = \"testCreateDestroySecurityGroup\")\n   public void testCreateIngress() throws Exception {\n      skipIfSecurityGroupsNotSupported();\n      String cidr = getCurrentCIDR();\n      ImmutableSet<String> cidrs = ImmutableSet.of(cidr);\n      assertTrue(jobComplete.apply(client.getSecurityGroupApi().authorizeIngressICMPToCIDRs(group.getId(), 0, 8, cidrs)), group.toString());\n      assertTrue(jobComplete.apply(client.getSecurityGroupApi().authorizeIngressPortsToCIDRs(group.getId(), \"TCP\", 22,\n            22, cidrs)), group.toString());\n\n      AccountInDomainOptions.Builder.accountInDomain(group.getAccount(), group.getDomainId());\n\n      // replace with get once bug is fixed where getGroup returns only one\n      // ingress rule\n      group = Iterables.find(client.getSecurityGroupApi().listSecurityGroups(), new Predicate<SecurityGroup>() {\n\n         @Override\n         public boolean apply(SecurityGroup input) {\n            return Objects.equal(input.getId(), group.getId());\n         }\n\n      });\n\n      IngressRule ICMPPingRule = Iterables.find(group.getIngressRules(), new Predicate<IngressRule>() {\n\n         @Override\n         public boolean apply(IngressRule input) {\n            return \"icmp\".equals(input.getProtocol());\n         }\n\n      });\n\n      assert ICMPPingRule.getId() != null : ICMPPingRule;\n      assert \"icmp\".equals(ICMPPingRule.getProtocol()) : ICMPPingRule;\n      assert ICMPPingRule.getStartPort() == -1 : ICMPPingRule;\n      assert ICMPPingRule.getEndPort() == -1 : ICMPPingRule;\n      assert ICMPPingRule.getICMPCode() == 0 : ICMPPingRule;\n      assert ICMPPingRule.getICMPType() == 8 : ICMPPingRule;\n      assert ICMPPingRule.getAccount() == null : ICMPPingRule;\n      assert ICMPPingRule.getSecurityGroupName() == null : ICMPPingRule;\n      assert cidr.equals(ICMPPingRule.getCIDR()) : ICMPPingRule;\n\n      IngressRule SSHRule = Iterables.find(group.getIngressRules(), new Predicate<IngressRule>() {\n\n         @Override\n         public boolean apply(IngressRule input) {\n            return \"tcp\".equals(input.getProtocol());\n         }\n\n      });\n\n      assert SSHRule.getId() != null : SSHRule;\n      assert \"tcp\".equals(SSHRule.getProtocol()) : SSHRule;\n      assert SSHRule.getStartPort() == 22 : SSHRule;\n      assert SSHRule.getEndPort() == 22 : SSHRule;\n      assert SSHRule.getICMPCode() == -1 : SSHRule;\n      assert SSHRule.getICMPType() == -1 : SSHRule;\n      assert SSHRule.getAccount() == null : SSHRule;\n      assert SSHRule.getSecurityGroupName() == null : SSHRule;\n      assert cidr.equals(SSHRule.getCIDR()) : SSHRule;\n\n   }\n\n   public void testListSecurityGroup() throws Exception {\n      skipIfSecurityGroupsNotSupported();\n      for (SecurityGroup securityGroup : client.getSecurityGroupApi().listSecurityGroups())\n         checkGroup(securityGroup);\n   }\n\n   @Test(dependsOnMethods = \"testCreateIngress\")\n   public void testCreateVMInSecurityGroup() throws Exception {\n      skipIfSecurityGroupsNotSupported();\n      String defaultTemplate = templateBuilderSpec != null ? templateBuilderSpec.getImageId() : null;\n      vm = VirtualMachineApiLiveTest.createVirtualMachineWithSecurityGroupInZone(zone.getId(),\n            defaultTemplateOrPreferredInZone(defaultTemplate, client, zone.getId()), group.getId(), client,\n            jobComplete, virtualMachineRunning);\n      if (vm.getPassword() != null && !loginCredentials.getOptionalPassword().isPresent())\n         loginCredentials = loginCredentials.toBuilder().password(vm.getPassword()).build();\n      // ingress port 22\n      checkSSH(HostAndPort.fromParts(vm.getIPAddress(), 22));\n      // ingress icmp disabled as this is platform dependent and may actually\n      // just try tcp port 7\n      // assert InetAddress.getByName(vm.getIPAddress()).isReachable(1000) : vm;\n   }\n\n   protected void checkGroup(SecurityGroup group) {\n      // http://bugs.cloud.com/show_bug.cgi?id=8968\n      if (group.getIngressRules().size() <= 1) {\n         assertEquals(group, client.getSecurityGroupApi().getSecurityGroup(group.getId()));\n         assertEquals(group, client.getSecurityGroupApi().getSecurityGroupByName(group.getName()));\n      }\n      assert group.getId() != null : group;\n      assert group.getName() != null : group;\n      assert group.getAccount() != null : group;\n      assert group.getDomain() != null : group;\n      assert group.getDomainId() != null : group;\n      assert group.getIngressRules() != null : group;\n   }\n\n   @Test\n   public void testCreateVMWithoutSecurityGroupAssignsDefault() throws Exception {\n      skipIfSecurityGroupsNotSupported();\n      String defaultTemplate = templateBuilderSpec != null ? templateBuilderSpec.getImageId() : null;\n      VirtualMachine newVm = VirtualMachineApiLiveTest.createVirtualMachineWithOptionsInZone(DeployVirtualMachineOptions.NONE,\n            zone.getId(), defaultTemplateOrPreferredInZone(defaultTemplate, client, zone.getId()), client,\n            jobComplete, virtualMachineRunning);\n      try {\n         VirtualMachine runningVm = client.getVirtualMachineApi().getVirtualMachine(newVm.getId());\n         assertEquals(1, runningVm.getSecurityGroups().size());\n         assertEquals(Iterables.getOnlyElement(runningVm.getSecurityGroups()).getName(), \"default\");\n      } finally {\n         assertTrue(jobComplete.apply(client.getVirtualMachineApi().destroyVirtualMachine(newVm.getId())));\n      }\n   }\n\n   @AfterGroups(groups = \"live\")\n   @Override\n   protected void tearDownContext() {\n      if (vm != null) {\n         assertTrue(jobComplete.apply(client.getVirtualMachineApi().destroyVirtualMachine(vm.getId())));\n      }\n      if (group != null) {\n         for (IngressRule rule : group.getIngressRules())\n            assertTrue(jobComplete.apply(client.getSecurityGroupApi().revokeIngressRule(rule.getId())), rule.toString());\n         client.getSecurityGroupApi().deleteSecurityGroup(group.getId());\n         assertEquals(client.getSecurityGroupApi().getSecurityGroup(group.getId()), null);\n      }\n      super.tearDownContext();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/SecurityGroupApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport java.io.IOException;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiTest;\nimport org.jclouds.cloudstack.options.AccountInDomainOptions;\nimport org.jclouds.cloudstack.options.ListSecurityGroupsOptions;\nimport org.jclouds.fallbacks.MapHttp4xxCodesToExceptions;\nimport org.jclouds.functions.IdentityFunction;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.functions.ParseFirstJsonValueNamed;\nimport org.jclouds.http.functions.ReleasePayloadAndReturn;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Functions;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Multimap;\nimport com.google.common.reflect.Invokable;\n/**\n * Tests behavior of {@code SecurityGroupApi}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"SecurityGroupApiTest\")\npublic class SecurityGroupApiTest extends BaseCloudStackApiTest<SecurityGroupApi> {\n\n   public void testListSecurityGroups() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(SecurityGroupApi.class, \"listSecurityGroups\", ListSecurityGroupsOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listSecurityGroups&listAll=true HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testListSecurityGroupsOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(SecurityGroupApi.class, \"listSecurityGroups\", ListSecurityGroupsOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(ListSecurityGroupsOptions.Builder.virtualMachineId(\"4\")\n            .domainId(\"5\").id(\"6\")));\n\n      assertRequestLineEquals(\n            httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listSecurityGroups&listAll=true&virtualmachineid=4&domainid=5&id=6 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testGetSecurityGroup() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(SecurityGroupApi.class, \"getSecurityGroup\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(5));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listSecurityGroups&listAll=true&id=5 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest,\n            Functions.compose(IdentityFunction.INSTANCE, IdentityFunction.INSTANCE).getClass());\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testGetSecurityGroupByName() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(SecurityGroupApi.class, \"getSecurityGroupByName\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"some-name\"));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listSecurityGroups&listAll=true&securitygroupname=some-name HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest,\n            Functions.compose(IdentityFunction.INSTANCE, IdentityFunction.INSTANCE).getClass());\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testCreateSecurityGroup() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(SecurityGroupApi.class, \"createSecurityGroup\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"goo\"));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=createSecurityGroup&name=goo HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   HttpRequest authorizeSecurityGroupIngress3 = HttpRequest.builder().method(\"GET\")\n                                                           .endpoint(\"http://localhost:8080/client/api\")\n                                                           .addQueryParam(\"response\", \"json\")\n                                                           .addQueryParam(\"command\", \"authorizeSecurityGroupIngress\")\n                                                           .addQueryParam(\"securitygroupid\", \"2\")\n                                                           .addQueryParam(\"protocol\", \"tcp\")\n                                                           .addQueryParam(\"startport\", \"22\")\n                                                           .addQueryParam(\"endport\", \"22\")\n                                                           .addQueryParam(\"cidrlist\", \"1.1.1.1/24,1.2.2.2/16\").build();\n\n   public void testAuthorizeIngressPortsToCIDRs() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(SecurityGroupApi.class, \"authorizeIngressPortsToCIDRs\", String.class,\n            String.class, int.class, int.class, Iterable.class, AccountInDomainOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(2, \"tcp\", 22, 22,\n            ImmutableSet.of(\"1.1.1.1/24\", \"1.2.2.2/16\")));\n\n      assertRequestLineEquals(httpRequest, authorizeSecurityGroupIngress3.getRequestLine());\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   HttpRequest authorizeSecurityGroupIngress4 = HttpRequest.builder().method(\"GET\")\n                                                           .endpoint(\"http://localhost:8080/client/api\")\n                                                           .addQueryParam(\"response\", \"json\")\n                                                           .addQueryParam(\"command\", \"authorizeSecurityGroupIngress\")\n                                                           .addQueryParam(\"securitygroupid\", \"2\")\n                                                           .addQueryParam(\"protocol\", \"tcp\")\n                                                           .addQueryParam(\"startport\", \"22\")\n                                                           .addQueryParam(\"endport\", \"22\")\n                                                           .addQueryParam(\"usersecuritygrouplist[0].account\", \"adrian\")\n                                                           .addQueryParam(\"usersecuritygrouplist[0].group\", \"group1\")\n                                                           .addQueryParam(\"usersecuritygrouplist[1].account\", \"adrian\")\n                                                           .addQueryParam(\"usersecuritygrouplist[1].group\", \"group2\")\n                                                           .addQueryParam(\"usersecuritygrouplist[2].account\", \"bob\")\n                                                           .addQueryParam(\"usersecuritygrouplist[2].group\", \"group1\").build();\n\n   public void testAuthorizeIngressPortsToSecurityGroups() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(SecurityGroupApi.class, \"authorizeIngressPortsToSecurityGroups\", String.class,\n            String.class, int.class, int.class, Multimap.class, AccountInDomainOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(2, \"tcp\", 22, 22,\n            ImmutableMultimap.of(\"adrian\", \"group1\", \"adrian\", \"group2\", \"bob\", \"group1\")));\n\n      assertRequestLineEquals(httpRequest, authorizeSecurityGroupIngress4.getRequestLine());\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   HttpRequest authorizeSecurityGroupIngress1 = HttpRequest.builder().method(\"GET\")\n                                                           .endpoint(\"http://localhost:8080/client/api\")\n                                                           .addQueryParam(\"response\", \"json\")\n                                                           .addQueryParam(\"command\", \"authorizeSecurityGroupIngress\")\n                                                           .addQueryParam(\"protocol\", \"ICMP\")\n                                                           .addQueryParam(\"securitygroupid\", \"2\")\n                                                           .addQueryParam(\"icmpcode\", \"22\")\n                                                           .addQueryParam(\"icmptype\", \"22\")\n                                                           .addQueryParam(\"cidrlist\", \"1.1.1.1/24,1.2.2.2/16\").build();\n\n   public void testAuthorizeIngressICMPToCIDRs() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(SecurityGroupApi.class, \"authorizeIngressICMPToCIDRs\", String.class, int.class,\n            int.class, Iterable.class, AccountInDomainOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(2, 22, 22, ImmutableSet.of(\"1.1.1.1/24\", \"1.2.2.2/16\")));\n\n      assertRequestLineEquals(httpRequest, authorizeSecurityGroupIngress1.getRequestLine());\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   HttpRequest authorizeSecurityGroupIngress2 = HttpRequest.builder().method(\"GET\")\n                                                           .endpoint(\"http://localhost:8080/client/api\")\n                                                           .addQueryParam(\"response\", \"json\")\n                                                           .addQueryParam(\"command\", \"authorizeSecurityGroupIngress\")\n                                                           .addQueryParam(\"protocol\", \"ICMP\")\n                                                           .addQueryParam(\"securitygroupid\", \"2\")\n                                                           .addQueryParam(\"icmpcode\", \"22\")\n                                                           .addQueryParam(\"icmptype\", \"22\")\n                                                           .addQueryParam(\"usersecuritygrouplist[0].account\", \"adrian\")\n                                                           .addQueryParam(\"usersecuritygrouplist[0].group\", \"group1\")\n                                                           .addQueryParam(\"usersecuritygrouplist[1].account\", \"adrian\")\n                                                           .addQueryParam(\"usersecuritygrouplist[1].group\", \"group2\")\n                                                           .addQueryParam(\"usersecuritygrouplist[2].account\", \"bob\")\n                                                           .addQueryParam(\"usersecuritygrouplist[2].group\", \"group1\").build();\n\n   public void testAuthorizeIngressICMPToSecurityGroups() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(SecurityGroupApi.class, \"authorizeIngressICMPToSecurityGroups\", String.class,\n            int.class, int.class, Multimap.class, AccountInDomainOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(2, 22, 22,\n            ImmutableMultimap.of(\"adrian\", \"group1\", \"adrian\", \"group2\", \"bob\", \"group1\")));\n\n      assertRequestLineEquals(httpRequest, authorizeSecurityGroupIngress2.getRequestLine());\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testRevokeIngressRule() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(SecurityGroupApi.class, \"revokeIngressRule\", String.class,\n            AccountInDomainOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(5,\n            AccountInDomainOptions.Builder.accountInDomain(\"adrian\", \"1\")));\n\n      assertRequestLineEquals(\n            httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=revokeSecurityGroupIngress&id=5&account=adrian&domainid=1 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, VoidOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testDeleteSecurityGroup() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(SecurityGroupApi.class, \"deleteSecurityGroup\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(5));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=deleteSecurityGroup&id=5 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, VoidOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/SessionApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.hash.Hashing.md5;\nimport static com.google.common.io.BaseEncoding.base16;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.net.URI;\n\nimport org.jclouds.cloudstack.CloudStackContext;\nimport org.jclouds.cloudstack.domain.Account;\nimport org.jclouds.cloudstack.domain.LoginResponse;\nimport org.jclouds.cloudstack.internal.BaseCloudStackExpectTest;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMultimap;\n\n/**\n * Tests behavior of {@code SessionApi}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"SessionApiExpectTest\")\npublic class SessionApiExpectTest extends BaseCloudStackExpectTest<SessionApi> {\n\n   HttpRequest login = HttpRequest.builder().method(\"GET\")\n                                  .endpoint(\"http://localhost:8080/client/api\")\n                                  .addQueryParam(\"response\", \"json\")\n                                  .addQueryParam(\"command\", \"login\")\n                                  .addQueryParam(\"username\", \"jclouds\")\n                                  .addQueryParam(\"domain\", \"Partners/jclouds\")\n                                  .addQueryParam(\"password\", \"30e14b3727225d833aad2206acea1275\")\n                                  .addHeader(\"Accept\", \"application/json\").build();\n\n   public void testLoginWhenResponseIs2xxIncludesJSessionId() throws IOException {\n      String domain = \"Partners/jclouds\";\n      String user = \"jclouds\";\n      String password = \"jcl0ud\";\n      String md5password = base16().lowerCase().encode(md5().hashString(password, UTF_8).asBytes());\n\n      String jSessionId = \"90DD65D13AEAA590ECCA312D150B9F6D\";\n      SessionApi client = requestSendsResponse(login,\n         HttpResponse.builder()\n            .statusCode(200)\n            .headers(\n               ImmutableMultimap.<String, String>builder()\n                  .put(\"Set-Cookie\", \"JSESSIONID=\" + jSessionId + \"; Path=/client\")\n                  .build())\n            .payload(payloadFromResource(\"/loginresponse.json\"))\n            .build());\n\n      assertEquals(client.loginUserInDomainWithHashOfPassword(user, domain, md5password).toString(),\n         LoginResponse.builder().timeout(1800).lastName(\"Kiran\").registered(false).username(\"jclouds\").firstName(\"Vijay\")\n            .domainId(\"11\").accountType(Account.Type.DOMAIN_ADMIN).userId(\"19\").sessionKey(\n            \"uYT4/MNiglgAKiZRQkvV8QP8gn0=\").jSessionId(jSessionId).accountName(\"jclouds\").build().toString());\n   }\n\n   public void testLogout() throws IOException {\n      HttpRequest request = HttpRequest.builder()\n         .method(\"GET\")\n         .endpoint(\n            URI.create(\"http://localhost:8080/client/api?response=json&command=logout&sessionkey=dummy-session-key\"))\n         .build();\n\n      SessionApi client = requestSendsResponse(request,\n         HttpResponse.builder()\n            .statusCode(200)\n            .payload(payloadFromResource(\"/logoutresponse.json\"))\n            .build());\n\n      client.logoutUser(\"dummy-session-key\");\n   }\n\n   @Override\n   protected SessionApi clientFrom(CloudStackContext context) {\n      return context.getApi().getSessionApi();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/SessionApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.hash.Hashing.md5;\nimport static com.google.common.io.BaseEncoding.base16;\nimport static org.jclouds.cloudstack.features.GlobalAccountApiLiveTest.createTestAccount;\nimport static org.jclouds.cloudstack.features.GlobalUserApiLiveTest.createTestUser;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.net.URI;\n\nimport org.jclouds.cloudstack.domain.Account;\nimport org.jclouds.cloudstack.domain.ApiKeyPair;\nimport org.jclouds.cloudstack.domain.LoginResponse;\nimport org.jclouds.cloudstack.domain.User;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest;\nimport org.jclouds.cloudstack.util.ApiKeyPairs;\nimport org.jclouds.rest.AuthorizationException;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code SessionApi}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"SessionApiLiveTest\")\npublic class SessionApiLiveTest extends BaseCloudStackApiLiveTest {\n\n   @Test\n   public void testCreateContextUsingUserAndPasswordAuthentication() {\n      skipIfNotGlobalAdmin();\n\n      Account testAccount = null;\n      User testUser = null;\n\n      String prefix = this.prefix + \"-session\";\n      try {\n         testAccount = createTestAccount(globalAdminClient, prefix);\n         testUser = createTestUser(globalAdminClient, testAccount, prefix);\n\n         String expectedUsername = prefix + \"-user\";\n         assertEquals(testUser.getName(), expectedUsername);\n\n         checkLoginAsTheNewUser(expectedUsername);\n\n         ApiKeyPair expected = globalAdminClient.getUserClient().registerUserKeys(testUser.getId());\n         ApiKeyPair actual = ApiKeyPairs.loginToEndpointAsUsernameInDomainWithPasswordAndReturnApiKeyPair(\n            URI.create(endpoint), prefix + \"-user\", \"password\", \"\");\n\n         assertEquals(actual, expected);\n\n      } finally {\n         if (testUser != null)\n            globalAdminClient.getUserClient().deleteUser(testUser.getId());\n         if (testAccount != null)\n            globalAdminClient.getAccountApi().deleteAccount(testAccount.getId());\n      }\n   }\n\n   @Test(expectedExceptions = AuthorizationException.class)\n   public void testTryToGetApiKeypairWithWrongCredentials() {\n      ApiKeyPairs.loginToEndpointAsUsernameInDomainWithPasswordAndReturnApiKeyPair(\n         URI.create(endpoint), \"dummy-missing-user\", \"with-a-wrong-password\", \"\");\n   }\n\n   private void checkLoginAsTheNewUser(String expectedUsername) {\n      LoginResponse response = globalAdminClient.getSessionApi().loginUserInDomainWithHashOfPassword(\n            expectedUsername, \"\", base16().lowerCase().encode(md5().hashString(\"password\", UTF_8).asBytes()));\n\n      assertNotNull(response);\n      assertNotNull(response.getSessionKey());\n      assertNotNull(response.getJSessionId());\n\n      client.getSessionApi().logoutUser(response.getSessionKey());\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/SnapshotApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static com.google.common.collect.Iterables.find;\nimport static org.testng.AssertJUnit.assertEquals;\nimport static org.testng.AssertJUnit.assertFalse;\nimport static org.testng.AssertJUnit.assertNotNull;\nimport static org.testng.AssertJUnit.assertNotSame;\nimport static org.testng.AssertJUnit.assertNull;\nimport static org.testng.AssertJUnit.assertTrue;\n\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\n\nimport org.jclouds.cloudstack.domain.AsyncCreateResponse;\nimport org.jclouds.cloudstack.domain.Snapshot;\nimport org.jclouds.cloudstack.domain.Volume;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest;\nimport org.jclouds.cloudstack.options.ListSnapshotsOptions;\nimport org.jclouds.logging.Logger;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Iterables;\n\n/**\n * Tests behavior of {@code SnapshotApi}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"SnapshotApiLiveTest\")\npublic class SnapshotApiLiveTest extends BaseCloudStackApiLiveTest {\n\n   @Resource Logger logger = Logger.NULL;\n   \n   public void testListSnapshots() {\n      Set<Snapshot> snapshots = client.getSnapshotApi().listSnapshots();\n      assertNotNull(snapshots);\n      assertFalse(snapshots.isEmpty());\n\n      for (Snapshot snapshot : snapshots) {\n         checkSnapshot(snapshot);\n      }\n   }\n\n   public void testListSnapshotsById() {\n      Iterable<String> snapshotIds = Iterables.transform(client.getSnapshotApi().listSnapshots(), new Function<Snapshot, String>() {\n          public String apply(Snapshot input) {\n              return input.getId();\n          }\n      });\n      assertNotNull(snapshotIds);\n      assertFalse(Iterables.isEmpty(snapshotIds));\n\n      for (String id : snapshotIds) {\n         Set<Snapshot> found = client.getSnapshotApi().listSnapshots(ListSnapshotsOptions.Builder.id(id));\n         assertNotNull(found);\n         assertEquals(1, found.size());\n         Snapshot snapshot = Iterables.getOnlyElement(found);\n         assertEquals(id, snapshot.getId());\n         checkSnapshot(snapshot);\n      }\n   }\n\n   public void testListSnapshotsNonexistantId() {\n      Set<Snapshot> found = client.getSnapshotApi().listSnapshots(ListSnapshotsOptions.Builder.id(\"foo\"));\n      assertNotNull(found);\n      assertTrue(found.isEmpty());\n   }\n\n   public void testGetSnapshotById() {\n      Iterable<String> snapshotIds = Iterables.transform(client.getSnapshotApi().listSnapshots(), new Function<Snapshot, String>() {\n          public String apply(Snapshot input) {\n              return input.getId();\n          }\n      });\n      assertNotNull(snapshotIds);\n      assertFalse(Iterables.isEmpty(snapshotIds));\n\n      for (String id : snapshotIds) {\n         Snapshot found = client.getSnapshotApi().getSnapshot(id);\n         assertNotNull(found);\n         assertEquals(id, found.getId());\n         checkSnapshot(found);\n      }\n   }\n\n   public void testGetSnapshotNonexistantId() {\n      Snapshot found = client.getSnapshotApi().getSnapshot(\"foo\");\n      assertNull(found);\n   }\n\n   protected Volume getPreferredVolume() {\n      for (Volume candidate : client.getVolumeApi().listVolumes()) {\n         if (candidate.getState() == Volume.State.READY)\n            return candidate;\n      }\n      throw new AssertionError(\"No suitable Volume found.\");\n   }\n\n   public void testCreateSnapshotFromVolume() {\n      final Volume volume = getPreferredVolume();  //fail fast if none\n      logger.info(\"creating snapshot from volume %s\", volume);\n      AsyncCreateResponse job = client.getSnapshotApi().createSnapshot(volume.getId());\n      assertTrue(jobComplete.apply(job.getJobId()));\n      Snapshot snapshot = findSnapshotWithId(job.getId());\n      logger.info(\"created snapshot %s from volume %s\", snapshot, volume);\n      checkSnapshot(snapshot);\n      client.getSnapshotApi().deleteSnapshot(snapshot.getId());\n   }\n\n   private void checkSnapshot(final Snapshot snapshot) {\n      assertNotNull(snapshot.getId());\n      assertNotNull(snapshot.getName());\n      assertNotSame(Snapshot.Type.UNRECOGNIZED, snapshot.getSnapshotType());\n   }\n\n   private Snapshot findSnapshotWithId(final String id) {\n      return find(client.getSnapshotApi().listSnapshots(), new Predicate<Snapshot>() {\n         @Override\n         public boolean apply(Snapshot arg0) {\n            return arg0.getId().equals(id);\n         }\n      });\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/SnapshotApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.cloudstack.domain.Snapshot;\nimport org.jclouds.cloudstack.domain.SnapshotPolicySchedule;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiTest;\nimport org.jclouds.cloudstack.options.CreateSnapshotOptions;\nimport org.jclouds.cloudstack.options.ListSnapshotPoliciesOptions;\nimport org.jclouds.cloudstack.options.ListSnapshotsOptions;\nimport org.jclouds.cloudstack.util.SnapshotPolicySchedules;\nimport org.jclouds.fallbacks.MapHttp4xxCodesToExceptions;\nimport org.jclouds.functions.IdentityFunction;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.functions.ParseFirstJsonValueNamed;\nimport org.jclouds.http.functions.ReleasePayloadAndReturn;\nimport org.jclouds.http.functions.UnwrapOnlyJsonValue;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Functions;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.reflect.Invokable;\n/**\n * Tests the behaviour of SnapshotApi.\n * \n * @see SnapshotApi\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"SnapshotApiTest\")\npublic class SnapshotApiTest extends BaseCloudStackApiTest<SnapshotApi> {\n\n   public void testCreateSnapshot() throws NoSuchMethodException {\n      Invokable<?, ?> method = method(SnapshotApi.class, \"createSnapshot\", String.class, CreateSnapshotOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(5));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=createSnapshot&volumeid=5 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testCreateSnapshotOptions() throws NoSuchMethodException {\n      Invokable<?, ?> method = method(SnapshotApi.class, \"createSnapshot\", String.class, CreateSnapshotOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(5, CreateSnapshotOptions.Builder.accountInDomain(\"acc\", \"7\").policyId(\"9\")));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=createSnapshot&volumeid=5&account=acc&domainid=7&policyid=9 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testListSnapshots() throws NoSuchMethodException {\n      Invokable<?, ?> method = method(SnapshotApi.class, \"listSnapshots\", ListSnapshotsOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listSnapshots&listAll=true HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testGetSnapshot() throws NoSuchMethodException {\n      Invokable<?, ?> method = method(SnapshotApi.class, \"getSnapshot\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(5));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listSnapshots&listAll=true&id=5 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest,\n            Functions.compose(IdentityFunction.INSTANCE, IdentityFunction.INSTANCE).getClass());\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testListSnapshotsOptions() throws NoSuchMethodException {\n      Invokable<?, ?> method = method(SnapshotApi.class, \"listSnapshots\", ListSnapshotsOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method,\n            ImmutableList.<Object> of(ListSnapshotsOptions.Builder.accountInDomain(\"acc\", \"7\")\n                  .id(\"5\")\n                  .interval(Snapshot.Interval.MONTHLY)\n                  .isRecursive(true)\n                  .keyword(\"fred\")\n                  .name(\"fred's snapshot\")\n                  .snapshotType(Snapshot.Type.RECURRING)\n                  .volumeId(\"11\")));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listSnapshots&listAll=true&account=acc&domainid=7&id=5&intervaltype=MONTHLY&isrecursive=true&keyword=fred&name=fred%27s%20snapshot&snapshottype=RECURRING&volumeid=11 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testDeleteSnapshot() throws NoSuchMethodException {\n      Invokable<?, ?> method = method(SnapshotApi.class, \"deleteSnapshot\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(14));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=deleteSnapshot&id=14 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, VoidOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n   }\n\n   HttpRequest extractIso = HttpRequest.builder().method(\"GET\")\n                                       .endpoint(\"http://localhost:8080/client/api\")\n                                       .addQueryParam(\"response\", \"json\")\n                                       .addQueryParam(\"command\", \"createSnapshotPolicy\")\n                                       .addQueryParam(\"maxsnaps\", \"10\")\n                                       .addQueryParam(\"timezone\", \"UTC\")\n                                       .addQueryParam(\"volumeid\", \"12\")\n                                       .addQueryParam(\"intervaltype\", \"MONTHLY\")\n                                       .addQueryParam(\"schedule\", \"07:06:05\").build();\n\n   public void testCreateSnapshotPolicy() throws NoSuchMethodException {\n      Invokable<?, ?> method = method(SnapshotApi.class, \"createSnapshotPolicy\", SnapshotPolicySchedule.class, String.class, String.class, String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(SnapshotPolicySchedules.monthly(5, 6, 7), 10, \"UTC\", 12));\n\n      assertRequestLineEquals(httpRequest, extractIso.getRequestLine());\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testDeleteSnapshotPolicy() throws NoSuchMethodException {\n      Invokable<?, ?> method = method(SnapshotApi.class, \"deleteSnapshotPolicy\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(7));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=deleteSnapshotPolicies&id=7 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, VoidOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testDeleteSnapshotPolicies() throws NoSuchMethodException {\n      Invokable<?, ?> method = method(SnapshotApi.class, \"deleteSnapshotPolicies\", Iterable.class);\n      Iterable<String> ids = ImmutableSet.of(\"3\", \"5\", \"7\");\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(ids));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=deleteSnapshotPolicies&ids=3,5,7 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, VoidOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testListSnapshotPolicies() throws NoSuchMethodException {\n      Invokable<?, ?> method = method(SnapshotApi.class, \"listSnapshotPolicies\", String.class, ListSnapshotPoliciesOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(10));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listSnapshotPolicies&listAll=true&volumeid=10 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testListSnapshotPoliciesOptions() throws NoSuchMethodException {\n      Invokable<?, ?> method = method(SnapshotApi.class, \"listSnapshotPolicies\", String.class, ListSnapshotPoliciesOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(10, ListSnapshotPoliciesOptions.Builder.accountInDomain(\"fred\", \"4\").keyword(\"bob\")));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listSnapshotPolicies&listAll=true&volumeid=10&account=fred&domainid=4&keyword=bob HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/TagApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.testng.Assert.assertEquals;\n\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport org.jclouds.cloudstack.CloudStackContext;\nimport org.jclouds.cloudstack.domain.AsyncCreateResponse;\nimport org.jclouds.cloudstack.domain.Tag;\nimport org.jclouds.cloudstack.internal.BaseCloudStackExpectTest;\nimport org.jclouds.cloudstack.options.CreateTagsOptions;\nimport org.jclouds.cloudstack.options.DeleteTagsOptions;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.Test;\n\n/**\n * Test the CloudStack TagApi\n */\n@Test(groups = \"unit\", testName = \"TagApiExpectTest\")\npublic class TagApiExpectTest extends BaseCloudStackExpectTest<TagApi> {\n\n\n   public void testListTagsWhenResponseIs2xx() {\n      TagApi client = requestSendsResponse(\n            HttpRequest.builder().method(\"GET\")\n                  .endpoint(\"http://localhost:8080/client/api\")\n                  .addQueryParam(\"response\", \"json\")\n                  .addQueryParam(\"command\", \"listTags\")\n                  .addQueryParam(\"listAll\", \"true\")\n                  .addQueryParam(\"apiKey\", \"identity\")\n                  .addQueryParam(\"signature\", \"amvtC2a0VHzzDF5SUAIOZpXHd0A=\")\n                  .addHeader(\"Accept\", \"application/json\")\n                  .build(),\n            HttpResponse.builder()\n                  .statusCode(200)\n                  .payload(payloadFromResource(\"/listtagsresponse.json\"))\n                  .build()\n      );\n\n      assertEquals(client.listTags(),\n            ImmutableSet.<Tag>of(\n                  Tag.builder()\n                        .account(\"admin\")\n                        .domain(\"ROOT\")\n                        .domainId(\"79dc06c4-4432-11e4-b70d-000c29e19aa0\")\n                        .key(\"test-tag\")\n                        .resourceId(\"54fe1d53-5d73-4184-8b62-948b9d8e08fb\")\n                        .resourceType(Tag.ResourceType.TEMPLATE)\n                        .value(\"true\").build()\n            )\n      );\n   }\n\n   public void testListTagsWhenResponseIs404() {\n      TagApi client = requestSendsResponse(\n            HttpRequest.builder()\n                  .method(\"GET\")\n                  .endpoint(\"http://localhost:8080/client/api\")\n                  .addQueryParam(\"response\", \"json\")\n                  .addQueryParam(\"command\", \"listTags\")\n                  .addQueryParam(\"listAll\", \"true\")\n                  .addQueryParam(\"apiKey\", \"identity\")\n                  .addQueryParam(\"signature\", \"amvtC2a0VHzzDF5SUAIOZpXHd0A=\")\n                  .addHeader(\"Accept\", \"application/json\")\n                  .build(),\n            HttpResponse.builder()\n                  .statusCode(404)\n                  .build());\n\n      assertEquals(client.listTags(), ImmutableSet.of());\n   }\n\n   public void testCreateTagsWhenResponseIs2xx() {\n      TagApi client = requestSendsResponse(\n            HttpRequest.builder().method(\"GET\")\n                  .endpoint(\"http://localhost:8080/client/api\")\n                  .addQueryParam(\"response\", \"json\")\n                  .addQueryParam(\"command\", \"createTags\")\n                  .addQueryParam(\"resourcetype\", \"Template\")\n                  .addQueryParam(\"resourceids\", \"52d89d5d-6070-4fd4-8131-c6c9ca4b062e\")\n                  .addQueryParam(\"tags[0].key\", \"some-tag\")\n                  .addQueryParam(\"tags[0].value\", \"some-value\")\n                  .addQueryParam(\"apiKey\", \"identity\")\n                  .addQueryParam(\"signature\", \"HDGTKGG9kONEwh5xlLe9R72z+9Q=\")\n                  .addHeader(\"Accept\", \"application/json\")\n                  .build(),\n            HttpResponse.builder()\n                  .statusCode(200)\n                  .payload(payloadFromResource(\"/createtagsresponse.json\"))\n                  .build()\n      );\n\n      AsyncCreateResponse async = client.createTags(CreateTagsOptions.Builder.resourceType(\"Template\")\n            .resourceIds(\"52d89d5d-6070-4fd4-8131-c6c9ca4b062e\")\n            .tags(ImmutableMap.of(\"some-tag\", \"some-value\")));\n\n      assertEquals(\n            async,\n            AsyncCreateResponse.builder().jobId(\"32cfab73-f221-4b2b-a728-a73e924ac95d\").build());\n   }\n\n   public void testDeleteTagsWhenResponseIs2xx() {\n      TagApi client = requestSendsResponse(\n            HttpRequest.builder().method(\"GET\")\n                  .endpoint(\"http://localhost:8080/client/api\")\n                  .addQueryParam(\"response\", \"json\")\n                  .addQueryParam(\"command\", \"deleteTags\")\n                  .addQueryParam(\"resourcetype\", \"Template\")\n                  .addQueryParam(\"resourceids\", \"52d89d5d-6070-4fd4-8131-c6c9ca4b062e\")\n                  .addQueryParam(\"tags[0].key\", \"some-tag\")\n                  .addQueryParam(\"tags[0].value\", \"some-value\")\n                  .addQueryParam(\"apiKey\", \"identity\")\n                  .addQueryParam(\"signature\", \"inAqWH/GkkGipkZFG5Wfmxa8vOE=\")\n                  .addHeader(\"Accept\", \"application/json\")\n                  .build(),\n            HttpResponse.builder()\n                  .statusCode(200)\n                  .payload(payloadFromResource(\"/deletetagsresponse.json\"))\n                  .build()\n      );\n\n      AsyncCreateResponse async = client.deleteTags(DeleteTagsOptions.Builder.resourceType(\"Template\")\n            .resourceIds(\"52d89d5d-6070-4fd4-8131-c6c9ca4b062e\")\n            .tags(ImmutableMap.of(\"some-tag\", \"some-value\")));\n\n      assertEquals(\n            async,\n            AsyncCreateResponse.builder().jobId(\"32cfab73-f221-4b2b-a728-a73e924ac95d\").build());\n   }\n\n   @Override\n   protected TagApi clientFrom(CloudStackContext context) {\n      return context.getApi().getTagApi();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/TagApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.testng.AssertJUnit.assertEquals;\nimport static org.testng.AssertJUnit.assertFalse;\nimport static org.testng.AssertJUnit.assertNotNull;\nimport static org.testng.AssertJUnit.assertTrue;\n\nimport jakarta.annotation.Resource;\nimport java.util.Set;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\nimport org.jclouds.cloudstack.domain.AsyncCreateResponse;\nimport org.jclouds.cloudstack.domain.DiskOffering;\nimport org.jclouds.cloudstack.domain.Tag;\nimport org.jclouds.cloudstack.domain.Volume;\nimport org.jclouds.cloudstack.domain.Zone;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest;\nimport org.jclouds.cloudstack.options.CreateTagsOptions;\nimport org.jclouds.cloudstack.options.DeleteTagsOptions;\nimport org.jclouds.cloudstack.options.ListTagsOptions;\nimport org.jclouds.cloudstack.options.ListVolumesOptions;\nimport org.jclouds.logging.Logger;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeMethod;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code TagApi}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"TagApiLiveTest\")\npublic class TagApiLiveTest extends BaseCloudStackApiLiveTest {\n\n   @Resource Logger logger = Logger.NULL;\n\n   protected String prefix = System.getProperty(\"user.name\") + \"-\" + getClass().getSimpleName();\n   protected String volumeToDelete;\n   private String zoneId;\n\n   @BeforeMethod(groups = \"live\")\n   public void setZoneId() {\n      Set<Zone> zones = client.getZoneApi().listZones();\n      assertNotNull(zones);\n      assertFalse(zones.isEmpty());\n      zoneId = Iterables.get(zones, 0).getId();\n   }\n\n   public void testCreateTags() {\n      createVolumeToTag();\n\n      AsyncCreateResponse job = client.getTagApi().createTags(CreateTagsOptions.Builder.resourceType(\"Volume\")\n            .resourceIds(volumeToDelete)\n            .tags(ImmutableMap.of(prefix + \"-first-tag\", \"first-tag-value\",\n                  prefix + \"-second-tag\", \"second-tag-value\")));\n      assertTrue(jobComplete.apply(job.getJobId()));\n   }\n\n   @Test(dependsOnMethods = \"testCreateTags\")\n   public void testListTags() {\n      Set<Tag> tags = client.getTagApi().listTags();\n      assertNotNull(tags);\n      assertFalse(tags.isEmpty());\n\n      for (Tag tag : tags) {\n         checkTag(tag);\n      }\n   }\n\n   @Test(dependsOnMethods = \"testListTags\")\n   public void testListSingleTag() {\n      Set<Tag> tags = client.getTagApi().listTags(ListTagsOptions.Builder.key(prefix + \"-second-tag\"));\n      assertNotNull(tags);\n      assertFalse(tags.isEmpty());\n      assertEquals(1, tags.size());\n      for (Tag tag : tags) {\n         assertEquals(volumeToDelete, tag.getResourceId());\n         checkTag(tag);\n      }\n   }\n\n   @Test(dependsOnMethods = \"testListSingleTag\")\n   public void testListResourceByTag() {\n      Set<Volume> volumes = client.getVolumeApi().listVolumes(ListVolumesOptions.Builder.tags(ImmutableMap.of(prefix + \"-second-tag\", \"second-tag-value\")));\n      assertNotNull(volumes);\n      assertFalse(volumes.isEmpty());\n      assertEquals(1, volumes.size());\n   }\n\n   @Test(dependsOnMethods = \"testListResourceByTag\")\n   public void testDeleteTags() {\n      AsyncCreateResponse job = client.getTagApi().deleteTags(DeleteTagsOptions.Builder.resourceType(\"Volume\")\n            .resourceIds(volumeToDelete)\n            .tags(ImmutableMap.of(prefix + \"-first-tag\", \"first-tag-value\",\n                  prefix + \"-second-tag\", \"second-tag-value\")));\n      assertTrue(jobComplete.apply(job.getJobId()));\n   }\n\n   static void checkTag(final Tag tag) {\n      assertNotNull(tag.getAccount());\n      assertNotNull(tag.getResourceId());\n   }\n\n   protected DiskOffering getPreferredDiskOffering() {\n      for (DiskOffering candidate : client.getOfferingApi().listDiskOfferings()) {\n         if (!candidate.isCustomized()) {\n            return candidate;\n         }\n      }\n      throw new AssertionError(\"No suitable DiskOffering found.\");\n   }\n\n   protected void createVolumeToTag() {\n      AsyncCreateResponse job = client.getVolumeApi().createVolumeFromDiskOfferingInZone(prefix + \"-jclouds-volume\",\n            getPreferredDiskOffering().getId(), zoneId);\n      assertTrue(jobComplete.apply(job.getJobId()));\n      logger.info(\"created volume \" + job.getId());\n      volumeToDelete = job.getId();\n   }\n\n   @Override\n   @AfterClass(groups = \"live\")\n   protected void tearDownContext() {\n      try {\n         client.getVolumeApi().deleteVolume(volumeToDelete);\n      } catch (Exception e) {\n         // Don't really care if there's an exception here\n      }\n      super.tearDownContext();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/TagApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.jclouds.reflect.Reflection2.method;\nimport static org.jclouds.util.Strings2.urlEncode;\n\nimport java.io.IOException;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.reflect.Invokable;\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.cloudstack.domain.Tag;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiTest;\nimport org.jclouds.cloudstack.options.CreateTagsOptions;\nimport org.jclouds.cloudstack.options.DeleteTagsOptions;\nimport org.jclouds.cloudstack.options.ListTagsOptions;\nimport org.jclouds.fallbacks.MapHttp4xxCodesToExceptions;\nimport org.jclouds.http.functions.ParseFirstJsonValueNamed;\nimport org.jclouds.http.functions.UnwrapOnlyJsonValue;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code TagApi}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"TagApiTest\")\npublic class TagApiTest extends BaseCloudStackApiTest<TagApi> {\n   public void testListTags() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(TagApi.class, \"listTags\", ListTagsOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listTags&listAll=true HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testListTagsOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(TagApi.class, \"listTags\", ListTagsOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\n            ListTagsOptions.Builder.accountInDomain(\"adrian\", \"6\").resourceType(Tag.ResourceType.TEMPLATE)));\n\n      assertRequestLineEquals(\n            httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listTags&listAll=true&account=adrian&domainid=6&resourcetype=Template HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testCreateTags() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(TagApi.class, \"createTags\", CreateTagsOptions.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\n            CreateTagsOptions.Builder.resourceIds(\"1\")\n                  .resourceType(Tag.ResourceType.TEMPLATE)\n                  .tags(ImmutableMap.of(\"some-tag\", \"some-value\"))\n      ));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=createTags&resourceids=1&resourcetype=Template&\"\n                  + urlEncode(\"tags[0].key\") + \"=some-tag&\" + urlEncode(\"tags[0].value\") + \"=some-value HTTP/1.1\");\n                  assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testDeleteTags() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(TagApi.class, \"deleteTags\", DeleteTagsOptions.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\n            DeleteTagsOptions.Builder.resourceIds(\"1\")\n                  .resourceType(Tag.ResourceType.TEMPLATE)\n                  .tags(ImmutableMap.of(\"some-tag\", \"some-value\"))\n      ));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=deleteTags&resourceids=1&resourcetype=Template&\"\n                  + urlEncode(\"tags[0].key\") + \"=some-tag&\" + urlEncode(\"tags[0].value\") + \"=some-value HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/TemplateApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.jclouds.cloudstack.options.ListTemplatesOptions.Builder.zoneId;\nimport static org.jclouds.util.Predicates2.retry;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.net.URLDecoder;\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.AsyncCreateResponse;\nimport org.jclouds.cloudstack.domain.AsyncJob;\nimport org.jclouds.cloudstack.domain.ExtractMode;\nimport org.jclouds.cloudstack.domain.Network;\nimport org.jclouds.cloudstack.domain.OSType;\nimport org.jclouds.cloudstack.domain.Template;\nimport org.jclouds.cloudstack.domain.TemplateExtraction;\nimport org.jclouds.cloudstack.domain.TemplateMetadata;\nimport org.jclouds.cloudstack.domain.VirtualMachine;\nimport org.jclouds.cloudstack.domain.Volume;\nimport org.jclouds.cloudstack.domain.Zone;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest;\nimport org.jclouds.cloudstack.options.CreateTemplateOptions;\nimport org.jclouds.cloudstack.options.ListNetworksOptions;\nimport org.jclouds.cloudstack.options.ListVolumesOptions;\nimport org.jclouds.cloudstack.options.RegisterTemplateOptions;\nimport org.jclouds.logging.Logger;\nimport org.testng.annotations.AfterGroups;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Iterables;\n\n/**\n * Tests behavior of {@code TemplateApi}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"TemplateApiLiveTest\")\npublic class TemplateApiLiveTest extends BaseCloudStackApiLiveTest {\n\n   private static final String IMPORT_VHD_URL = \"http://www.frontiertown.co.uk/jclouds/empty.vhd\";\n   private VirtualMachine vmForCreation;\n   private VirtualMachine vmForRegistration;\n   private Template createdTemplate;\n   private Template registeredTemplate;\n\n   @Test\n   public void testListTemplates() throws Exception {\n      Set<Template> response = client.getTemplateApi().listTemplates();\n      assert null != response;\n      long templateCount = response.size();\n      assertTrue(templateCount >= 0);\n      for (Template template : response) {\n         Template newDetails = Iterables.getOnlyElement(client.getTemplateApi().listTemplates(\n               zoneId(template.getZoneId()).id(template.getId())));\n         Logger.CONSOLE.info(\"Checking template: \" + template);\n\n         assertEquals(template, newDetails);\n         assertEquals(template, client.getTemplateApi().getTemplateInZone(template.getId(), template.getZoneId()));\n         assert template.getId() != null : template;\n         assert template.getName() != null : template;\n         assert template.getDisplayText() != null : template;\n         assert template.getCreated() != null : template;\n         assert template.getFormat() != null && template.getFormat() != Template.Format.UNRECOGNIZED : template;\n         assert template.getOSType() != null : template;\n         assert template.getOSTypeId() != null : template;\n         assert template.getAccount() != null : template;\n         assert template.getZone() != null : template;\n         assert template.getZoneId() != null : template;\n         assert template.getStatus() == null ||\n            template.getStatus() == Template.Status.DOWNLOADED : template;\n         assert template.getType() != null && template.getType() != Template.Type.UNRECOGNIZED : template;\n         assert template.getHypervisor() != null : template;\n         assert template.getDomain() != null : template;\n         assert template.getDomainId() != null : template;\n         assert template.getSize() > 0 : template;\n      }\n   }\n\n   @Test(enabled = true)\n   public void testCreateTemplate() throws Exception {\n      Zone zone = Iterables.getFirst(client.getZoneApi().listZones(), null);\n      assertNotNull(zone);\n      Iterable<Network> networks = client.getNetworkApi().listNetworks(ListNetworksOptions.Builder.zoneId(zone.getId()).isDefault(true));\n      networks = Iterables.filter(networks, new Predicate<Network>() {\n         @Override\n         public boolean apply(Network network) {\n            return network != null && network.getState().equals(\"Implemented\");\n         }\n      });\n      assertTrue(Iterables.size(networks) >= 1);\n      Network network = Iterables.get(networks, 0);\n      assertNotNull(network);\n\n      // Create a VM and stop it\n      String defaultTemplate = templateBuilderSpec != null ? templateBuilderSpec.getImageId() : null;\n      vmForCreation = VirtualMachineApiLiveTest.createVirtualMachineInNetwork(network, defaultTemplate, client, jobComplete, virtualMachineRunning);\n      assertTrue(jobComplete.apply(client.getVirtualMachineApi().stopVirtualMachine(vmForCreation.getId())), vmForCreation.toString());\n\n      // Work out the VM's volume\n      Set<Volume> volumes = client.getVolumeApi().listVolumes(ListVolumesOptions.Builder.virtualMachineId(vmForCreation.getId()));\n      assertEquals(volumes.size(), 1);\n      Volume volume = Iterables.getOnlyElement(volumes);\n\n      // Create a template\n      CreateTemplateOptions options = CreateTemplateOptions.Builder.volumeId(volume.getId());\n      AsyncCreateResponse response = client.getTemplateApi().createTemplate(TemplateMetadata.builder().name(prefix + \"-createTemplate\").osTypeId(vmForCreation.getGuestOSId()).displayText(\"jclouds live testCreateTemplate\").build(), options);\n      assertTrue(jobComplete.apply(response.getJobId()), vmForCreation.toString());\n      createdTemplate = client.getTemplateApi().getTemplateInZone(response.getId(), vmForCreation.getZoneId());\n\n      // Assertions\n      assertNotNull(createdTemplate);\n   }\n\n   @Test(enabled = true, dependsOnMethods = \"testRegisterTemplate\")\n   public void testExtractTemplate() throws Exception {\n      // Initiate the extraction and wait for it to complete\n      AsyncCreateResponse response = client.getTemplateApi().extractTemplate(registeredTemplate.getId(), ExtractMode.HTTP_DOWNLOAD, registeredTemplate.getZoneId());\n      assertTrue(jobComplete.apply(response.getJobId()), registeredTemplate.toString());\n\n      // Get the result\n      AsyncJob<TemplateExtraction> asyncJob = client.getAsyncJobApi().getAsyncJob(response.getJobId());\n      TemplateExtraction extract = asyncJob.getResult();\n      assertNotNull(extract);\n\n      // Check that the URL can be retrieved\n      String extractUrl = extract.getUrl();\n      assertNotNull(extractUrl);\n      URI uri = new URI(URLDecoder.decode(extractUrl, \"utf-8\"));\n      assertTrue(cloudStackContext.utils().http().exists(uri), \"does not exist: \" + uri);\n   }\n\n   @Test(enabled = true)\n   public void testRegisterTemplate() throws Exception {\n      Zone zone = Iterables.getFirst(client.getZoneApi().listZones(), null);\n      assertNotNull(zone);\n      Iterable<Network> networks = client.getNetworkApi().listNetworks(ListNetworksOptions.Builder.zoneId(zone.getId()).isDefault(true));\n      networks = Iterables.filter(networks, new Predicate<Network>() {\n         @Override\n         public boolean apply(Network network) {\n            return network != null && network.getName().equals(\"Virtual Network\");\n         }\n      });\n      assertEquals(Iterables.size(networks), 1);\n      Network network = Iterables.getOnlyElement(networks, null);\n      assertNotNull(network);\n      Set<OSType> osTypes = client.getGuestOSApi().listOSTypes();\n      OSType osType = Iterables.getFirst(osTypes, null);\n\n      // Register a template\n      RegisterTemplateOptions options = RegisterTemplateOptions.Builder.bits(32).isExtractable(true);\n      TemplateMetadata templateMetadata = TemplateMetadata.builder().name(prefix + \"-registerTemplate\").osTypeId(osType.getId()).displayText(\"jclouds live testRegisterTemplate\").build();\n      Set<Template> templates = client.getTemplateApi().registerTemplate(templateMetadata, \"VHD\", \"XenServer\", IMPORT_VHD_URL, zone.getId(), options);\n      registeredTemplate = Iterables.getOnlyElement(templates, null);\n      assertNotNull(registeredTemplate);\n\n      // Ensure it is available\n      final String zoneId = zone.getId();\n      Predicate<Template> templateReadyPredicate = new Predicate<Template>() {\n         @Override\n         public boolean apply(Template template) {\n            if (template == null) return false;\n            Template t2 = client.getTemplateApi().getTemplateInZone(template.getId(), zoneId);\n            Logger.CONSOLE.info(\"%s\", t2.getStatus());\n            return t2.getStatus() == Template.Status.DOWNLOADED;\n         }\n      };\n      assertTrue(retry(templateReadyPredicate, 60000).apply(registeredTemplate));\n\n      // Create a VM that uses this template\n      vmForRegistration = VirtualMachineApiLiveTest.createVirtualMachineInNetwork(network, registeredTemplate.getId(), client, jobComplete, virtualMachineRunning);\n      assertNotNull(vmForRegistration);\n   }\n\n\n   @AfterGroups(groups = \"live\")\n   @Override\n   protected void tearDownContext() {\n      if (vmForCreation != null) {\n         assertTrue(jobComplete.apply(client.getVirtualMachineApi().stopVirtualMachine(vmForCreation.getId())), vmForCreation.toString());\n         assertTrue(jobComplete.apply(client.getVirtualMachineApi().destroyVirtualMachine(vmForCreation.getId())), vmForCreation.toString());\n         assertTrue(virtualMachineDestroyed.apply(vmForCreation));\n      }\n      if (vmForRegistration != null) {\n         assertTrue(jobComplete.apply(client.getVirtualMachineApi().stopVirtualMachine(vmForRegistration.getId())), vmForRegistration.toString());\n         assertTrue(jobComplete.apply(client.getVirtualMachineApi().destroyVirtualMachine(vmForRegistration.getId())), vmForRegistration.toString());\n         assert virtualMachineDestroyed.apply(vmForRegistration);\n      }\n      if (createdTemplate != null) {\n         AsyncCreateResponse deleteJob = client.getTemplateApi().deleteTemplate(createdTemplate.getId());\n         assertTrue(jobComplete.apply(deleteJob.getJobId()));\n      }\n      if (registeredTemplate != null) {\n         AsyncCreateResponse deleteJob = client.getTemplateApi().deleteTemplate(registeredTemplate.getId());\n         assertTrue(jobComplete.apply(deleteJob.getJobId()));\n      }\n      super.tearDownContext();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/TemplateApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport java.io.IOException;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.cloudstack.domain.ExtractMode;\nimport org.jclouds.cloudstack.domain.Template;\nimport org.jclouds.cloudstack.domain.TemplateFilter;\nimport org.jclouds.cloudstack.domain.TemplateMetadata;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiTest;\nimport org.jclouds.cloudstack.options.AccountInDomainOptions;\nimport org.jclouds.cloudstack.options.CreateTemplateOptions;\nimport org.jclouds.cloudstack.options.DeleteTemplateOptions;\nimport org.jclouds.cloudstack.options.ExtractTemplateOptions;\nimport org.jclouds.cloudstack.options.ListTemplatesOptions;\nimport org.jclouds.cloudstack.options.RegisterTemplateOptions;\nimport org.jclouds.cloudstack.options.UpdateTemplateOptions;\nimport org.jclouds.cloudstack.options.UpdateTemplatePermissionsOptions;\nimport org.jclouds.fallbacks.MapHttp4xxCodesToExceptions;\nimport org.jclouds.functions.IdentityFunction;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.functions.ParseFirstJsonValueNamed;\nimport org.jclouds.http.functions.ReleasePayloadAndReturn;\nimport org.jclouds.http.functions.UnwrapOnlyJsonValue;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Functions;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.reflect.Invokable;\n/**\n * Tests behavior of {@code TemplateApi}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"TemplateApiTest\")\npublic class TemplateApiTest extends BaseCloudStackApiTest<TemplateApi> {\n\n   public void testCreateTemplate() throws NoSuchMethodException {\n      Invokable<?, ?> method = method(TemplateApi.class, \"createTemplate\", TemplateMetadata.class, CreateTemplateOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(TemplateMetadata.builder().name(\"thename\").osTypeId(\"10\").displayText(\"description\").build()));\n\n      assertRequestLineEquals(httpRequest, \"GET http://localhost:8080/client/api?response=json&command=createTemplate&name=thename&ostypeid=10&displaytext=description HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testCreateTemplateOptions() throws NoSuchMethodException {\n      Invokable<?, ?> method = method(TemplateApi.class, \"createTemplate\", TemplateMetadata.class, CreateTemplateOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(TemplateMetadata.builder().name(\"thename\").osTypeId(\"10\").displayText(\"description\").build(), CreateTemplateOptions.Builder.bits(32).isFeatured(true).isPublic(true).passwordEnabled(true).requiresHVM(true).snapshotId(\"11\").volumeId(\"12\")));\n\n      assertRequestLineEquals(httpRequest, \"GET http://localhost:8080/client/api?response=json&command=createTemplate&bits=32&isfeatured=true&ispublic=true&passwordenabled=true&requireshvm=true&snapshotid=11&volumeid=12&name=thename&ostypeid=10&displaytext=description HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n   }\n\n   HttpRequest registerTemplate = HttpRequest.builder().method(\"GET\")\n                                             .endpoint(\"http://localhost:8080/client/api\")\n                                             .addQueryParam(\"response\", \"json\")\n                                             .addQueryParam(\"command\", \"registerTemplate\")\n                                             .addQueryParam(\"format\", \"QCOW2\")\n                                             .addQueryParam(\"hypervisor\", \"xen\")\n                                             .addQueryParam(\"url\", \"http://example.com/\")\n                                             .addQueryParam(\"zoneid\", \"20\")\n                                             .addQueryParam(\"name\", \"thename\")\n                                             .addQueryParam(\"ostypeid\", \"10\")\n                                             .addQueryParam(\"displaytext\", \"description\").build();\n\n   public void testRegisterTemplate() throws NoSuchMethodException {\n      Invokable<?, ?> method = method(TemplateApi.class, \"registerTemplate\", TemplateMetadata.class, String.class, String.class, String.class, String.class, RegisterTemplateOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(TemplateMetadata.builder().name(\"thename\").osTypeId(\"10\").displayText(\"description\").build(), Template.Format.QCOW2, \"xen\", \"http://example.com/\", 20));\n\n      assertRequestLineEquals(httpRequest, registerTemplate.getRequestLine());\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n   }\n\n   HttpRequest registerTemplateOptions = HttpRequest.builder().method(\"GET\")\n                                                    .endpoint(\"http://localhost:8080/client/api\")\n                                                    .addQueryParam(\"response\", \"json\")\n                                                    .addQueryParam(\"command\", \"registerTemplate\")\n                                                    .addQueryParam(\"format\", \"QCOW2\")\n                                                    .addQueryParam(\"hypervisor\", \"xen\")\n                                                    .addQueryParam(\"url\", \"http://example.com/\")\n                                                    .addQueryParam(\"zoneid\", \"20\")\n                                                    .addQueryParam(\"account\", \"mydomain\")\n                                                    .addQueryParam(\"domainid\", \"3\")\n                                                    .addQueryParam(\"bits\", \"32\")\n                                                    .addQueryParam(\"checksum\", \"ABC\")\n                                                    .addQueryParam(\"isextractable\", \"true\")\n                                                    .addQueryParam(\"isfeatured\", \"true\")\n                                                    .addQueryParam(\"ispublic\", \"true\")\n                                                    .addQueryParam(\"passwordenabled\", \"true\")\n                                                    .addQueryParam(\"requireshvm\", \"true\")\n                                                    .addQueryParam(\"name\", \"thename\")\n                                                    .addQueryParam(\"ostypeid\", \"10\")\n                                                    .addQueryParam(\"displaytext\", \"description\").build();\n\n   public void testRegisterTemplateOptions() throws NoSuchMethodException {\n      Invokable<?, ?> method = method(TemplateApi.class, \"registerTemplate\", TemplateMetadata.class, String.class, String.class, String.class, String.class, RegisterTemplateOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(TemplateMetadata.builder().name(\"thename\").osTypeId(\"10\").displayText(\"description\").build(), Template.Format.QCOW2, \"xen\", \"http://example.com/\", 20,\n         RegisterTemplateOptions.Builder.accountInDomain(\"mydomain\", \"3\").bits(32).checksum(\"ABC\").isExtractable(true).isFeatured(true).isPublic(true).passwordEnabled(true).requiresHVM(true)));\n\n      assertRequestLineEquals(httpRequest, registerTemplateOptions.getRequestLine());\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testUpdateTemplate() throws NoSuchMethodException {\n      Invokable<?, ?> method = method(TemplateApi.class, \"updateTemplate\", String.class, UpdateTemplateOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(17));\n\n      assertRequestLineEquals(httpRequest, \"GET http://localhost:8080/client/api?response=json&command=updateTemplate&id=17 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testUpdateTemplateOptions() throws NoSuchMethodException {\n      Invokable<?, ?> method = method(TemplateApi.class, \"updateTemplate\", String.class, UpdateTemplateOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(17, UpdateTemplateOptions.Builder.bootable(true).displayText(\"description\").format(Template.Format.VHD).name(\"thename\").osTypeId(\"12\").passwordEnabled(true)));\n\n      assertRequestLineEquals(httpRequest, \"GET http://localhost:8080/client/api?response=json&command=updateTemplate&id=17&bootable=true&displaytext=description&format=VHD&name=thename&ostypeid=12&passwordenabled=true HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n   }\n\n   HttpRequest copyTemplate = HttpRequest.builder().method(\"GET\")\n                                         .endpoint(\"http://localhost:8080/client/api\")\n                                         .addQueryParam(\"response\", \"json\")\n                                         .addQueryParam(\"command\", \"copyTemplate\")\n                                         .addQueryParam(\"id\", \"17\")\n                                         .addQueryParam(\"sourcezoneid\", \"18\")\n                                         .addQueryParam(\"destzoneid\", \"19\").build();\n\n   public void testCopyTemplate() throws NoSuchMethodException {\n      Invokable<?, ?> method = method(TemplateApi.class, \"copyTemplateToZone\", String.class, String.class, String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(17, 18, 19));\n\n      assertRequestLineEquals(httpRequest, copyTemplate.getRequestLine());\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testDeleteTemplate() throws NoSuchMethodException {\n      Invokable<?, ?> method = method(TemplateApi.class, \"deleteTemplate\", String.class, DeleteTemplateOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(17));\n\n      assertRequestLineEquals(httpRequest, \"GET http://localhost:8080/client/api?response=json&command=deleteTemplate&id=17 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testDeleteTemplateOptions() throws NoSuchMethodException {\n      Invokable<?, ?> method = method(TemplateApi.class, \"deleteTemplate\", String.class, DeleteTemplateOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(17, DeleteTemplateOptions.Builder.zoneId(\"8\")));\n\n      assertRequestLineEquals(httpRequest, \"GET http://localhost:8080/client/api?response=json&command=deleteTemplate&id=17&zoneid=8 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testListTemplates() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(TemplateApi.class, \"listTemplates\");\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listTemplates&listAll=true&templatefilter=executable HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testListTemplatesOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(TemplateApi.class, \"listTemplates\", ListTemplatesOptions.class);\n      GeneratedHttpRequest httpRequest = processor\n            .createRequest(\n                  method, ImmutableList.<Object> of(\n                  ListTemplatesOptions.Builder.accountInDomain(\"adrian\", \"6\").hypervisor(\"xen\")\n                        .filter(TemplateFilter.FEATURED)));\n\n      assertRequestLineEquals(\n            httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listTemplates&listAll=true&account=adrian&domainid=6&hypervisor=xen&templatefilter=featured HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testGetTemplate() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(TemplateApi.class, \"getTemplateInZone\", String.class, String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(5, 1));\n\n      assertRequestLineEquals(\n            httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listTemplates&listAll=true&templatefilter=executable&id=5&zoneid=1 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest,\n            Functions.compose(IdentityFunction.INSTANCE, IdentityFunction.INSTANCE).getClass());\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testUpdateTemplatePermissions() throws NoSuchMethodException {\n      Invokable<?, ?> method = method(TemplateApi.class, \"updateTemplatePermissions\", String.class, UpdateTemplatePermissionsOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(17));\n\n      assertRequestLineEquals(httpRequest, \"GET http://localhost:8080/client/api?response=json&command=updateTemplatePermissions&id=17 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testUpdateTemplatePermissionsOptions() throws NoSuchMethodException {\n      Invokable<?, ?> method = method(TemplateApi.class, \"updateTemplatePermissions\", String.class, UpdateTemplatePermissionsOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(17, UpdateTemplatePermissionsOptions.Builder.accounts(ImmutableSet.of(\"5\", \"6\")).isExtractable(true).isFeatured(true).isPublic(true).op(UpdateTemplatePermissionsOptions.Operation.add)));\n\n      assertRequestLineEquals(httpRequest, \"GET http://localhost:8080/client/api?response=json&command=updateTemplatePermissions&id=17&accounts=5,6&isextractable=true&isfeatured=true&ispublic=true&op=add HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testListTemplatePermissions() throws NoSuchMethodException {\n      Invokable<?, ?> method = method(TemplateApi.class, \"listTemplatePermissions\", String.class, AccountInDomainOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(17));\n\n      assertRequestLineEquals(httpRequest, \"GET http://localhost:8080/client/api?response=json&command=listTemplatePermissions&listAll=true&id=17 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testListTemplatePermissionsOptions() throws NoSuchMethodException {\n      Invokable<?, ?> method = method(TemplateApi.class, \"listTemplatePermissions\", String.class, AccountInDomainOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(17, AccountInDomainOptions.Builder.accountInDomain(\"fred\", \"8\")));\n\n      assertRequestLineEquals(httpRequest, \"GET http://localhost:8080/client/api?response=json&command=listTemplatePermissions&listAll=true&id=17&account=fred&domainid=8 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n   }\n\n   HttpRequest extractTemplate = HttpRequest.builder().method(\"GET\")\n                                            .endpoint(\"http://localhost:8080/client/api\")\n                                            .addQueryParam(\"response\", \"json\")\n                                            .addQueryParam(\"command\", \"extractTemplate\")\n                                            .addQueryParam(\"id\", \"3\")\n                                            .addQueryParam(\"mode\", \"HTTP_DOWNLOAD\")\n                                            .addQueryParam(\"zoneid\", \"5\").build();\n\n   public void testExtractTemplate() throws NoSuchMethodException {\n      Invokable<?, ?> method = method(TemplateApi.class, \"extractTemplate\", String.class, ExtractMode.class, String.class, ExtractTemplateOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(3, ExtractMode.HTTP_DOWNLOAD, 5));\n\n      assertRequestLineEquals(httpRequest, extractTemplate.getRequestLine());\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n   }\n\n   HttpRequest extractTemplateOptions = HttpRequest.builder().method(\"GET\")\n                                                   .endpoint(\"http://localhost:8080/client/api\")\n                                                   .addQueryParam(\"response\", \"json\")\n                                                   .addQueryParam(\"command\", \"extractTemplate\")\n                                                   .addQueryParam(\"id\", \"3\")\n                                                   .addQueryParam(\"mode\", \"HTTP_DOWNLOAD\")\n                                                   .addQueryParam(\"zoneid\", \"5\")\n                                                   .addQueryParam(\"url\", \"http://example.com/\").build();\n\n   public void testExtractTemplateOptions() throws NoSuchMethodException {\n      Invokable<?, ?> method = method(TemplateApi.class, \"extractTemplate\", String.class, ExtractMode.class, String.class, ExtractTemplateOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(3, ExtractMode.HTTP_DOWNLOAD, 5, ExtractTemplateOptions.Builder.url(\"http://example.com/\")));\n\n      assertRequestLineEquals(httpRequest, extractTemplateOptions.getRequestLine());\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/VMGroupApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Random;\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.VMGroup;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest;\nimport org.jclouds.cloudstack.options.ListVMGroupsOptions;\nimport org.testng.annotations.AfterGroups;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Iterables;\n\n/**\n * Tests behavior of {@code VMGroupApi}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"VMGroupApiLiveTest\")\npublic class VMGroupApiLiveTest extends BaseCloudStackApiLiveTest {\n\n   private VMGroup groupCreated;\n\n   public VMGroupApiLiveTest() {\n      prefix += \"2\";\n   }\n\n   @Test\n   public void testCreateListDestroyVMGroup() {\n      VMGroupApi vmGroupClient = client.getVMGroupApi();\n      String name = \"jclouds-test-\" + (Integer.toHexString(new Random().nextInt()));\n      groupCreated = vmGroupClient.createInstanceGroup(name);\n      assertEquals(groupCreated.getName(), name);\n\n      Set<VMGroup> search = vmGroupClient.listInstanceGroups(ListVMGroupsOptions.Builder.name(name));\n      assertEquals(1, search.size());\n      VMGroup groupFound = Iterables.getOnlyElement(search);\n      assertEquals(groupFound, groupCreated);\n\n      vmGroupClient.deleteInstanceGroup(groupCreated.getId());\n      groupCreated = null;\n   }\n\n   @AfterGroups(groups = \"live\")\n   @Override\n   protected void tearDownContext() {\n      if (groupCreated != null) {\n         client.getVMGroupApi().deleteInstanceGroup(groupCreated.getId());\n      }\n      super.tearDownContext();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/VMGroupApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport java.io.IOException;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiTest;\nimport org.jclouds.cloudstack.options.CreateVMGroupOptions;\nimport org.jclouds.cloudstack.options.ListVMGroupsOptions;\nimport org.jclouds.cloudstack.options.UpdateVMGroupOptions;\nimport org.jclouds.fallbacks.MapHttp4xxCodesToExceptions;\nimport org.jclouds.functions.IdentityFunction;\nimport org.jclouds.http.functions.ParseFirstJsonValueNamed;\nimport org.jclouds.http.functions.ReleasePayloadAndReturn;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Functions;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.reflect.Invokable;\n/**\n * Tests behavior of {@code VMGroupApi}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"VMGroupApiTest\")\npublic class VMGroupApiTest extends BaseCloudStackApiTest<VMGroupApi> {\n\n   public void testListVMGroups() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(VMGroupApi.class, \"listInstanceGroups\", ListVMGroupsOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(httpRequest,\n         \"GET http://localhost:8080/client/api?response=json&command=listInstanceGroups&listAll=true HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testListVMGroupsOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(VMGroupApi.class, \"listInstanceGroups\", ListVMGroupsOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(ListVMGroupsOptions.Builder.account(\"fred\")\n         .domainId(\"5\").id(\"6\")));\n\n      assertRequestLineEquals(\n         httpRequest,\n         \"GET http://localhost:8080/client/api?response=json&command=listInstanceGroups&listAll=true&account=fred&domainid=5&id=6 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testGetVMGroup() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(VMGroupApi.class, \"getInstanceGroup\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(5));\n\n      assertRequestLineEquals(httpRequest,\n         \"GET http://localhost:8080/client/api?response=json&command=listInstanceGroups&listAll=true&id=5 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest,\n         Functions.compose(IdentityFunction.INSTANCE, IdentityFunction.INSTANCE).getClass());\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testCreateVMGroup() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(VMGroupApi.class, \"createInstanceGroup\", String.class, CreateVMGroupOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"goo\"));\n\n      assertRequestLineEquals(httpRequest,\n         \"GET http://localhost:8080/client/api?response=json&command=createInstanceGroup&name=goo HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testCreateVMGroupOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(VMGroupApi.class, \"createInstanceGroup\", String.class, CreateVMGroupOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"goo\", CreateVMGroupOptions.Builder.account(\"foo\").domainId(\"42\")));\n\n      assertRequestLineEquals(httpRequest,\n         \"GET http://localhost:8080/client/api?response=json&command=createInstanceGroup&name=goo&account=foo&domainid=42 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testUpdateVMGroup() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(VMGroupApi.class, \"updateInstanceGroup\", String.class, UpdateVMGroupOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(5, UpdateVMGroupOptions.Builder.name(\"fred\")));\n\n      assertRequestLineEquals(httpRequest,\n         \"GET http://localhost:8080/client/api?response=json&command=updateInstanceGroup&id=5&name=fred HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testDeleteVMGroup() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(VMGroupApi.class, \"deleteInstanceGroup\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(5));\n\n      assertRequestLineEquals(httpRequest,\n         \"GET http://localhost:8080/client/api?response=json&command=deleteInstanceGroup&id=5 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, VoidOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/VirtualMachineApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.security.NoSuchAlgorithmException;\nimport java.security.cert.CertificateException;\n\nimport org.jclouds.cloudstack.CloudStackContext;\nimport org.jclouds.cloudstack.domain.AsyncCreateResponse;\nimport org.jclouds.cloudstack.domain.EncryptedPasswordAndPrivateKey;\nimport org.jclouds.cloudstack.functions.WindowsLoginCredentialsFromEncryptedData;\nimport org.jclouds.cloudstack.internal.BaseCloudStackExpectTest;\nimport org.jclouds.encryption.internal.JCECrypto;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.Test;\n\n/**\n * Test the CloudStack VirtualMachineApiClient\n */\n@Test(groups = \"unit\", testName = \"VirtualMachineApiExpectTest\")\npublic class VirtualMachineApiExpectTest extends BaseCloudStackExpectTest<VirtualMachineApi> {\n\n   public void testGetPasswordForVirtualMachineWhenResponseIs2xx() throws NoSuchAlgorithmException, CertificateException {\n      String privateKey = \"-----BEGIN RSA PRIVATE KEY-----\\n\" +\n         \"MIICXgIBAAKBgQDnaPKhTNgw7qPJVp3qsT+7XhhAbip25a0AnUgq8Fb9LPcZk00p\\n\" +\n         \"jm+m4JrKmDWKZWrHMNBhCNHMzvV9KrAXUMzL4s7mdEicbxTKratTYoyJM7a87bcZ\\n\" +\n         \"xr+Gtoq4tm031Cix3LKyJUB0iSVU5V/Zx4QcaF5+FWcYMVI26x2Eaz+O7wIDAQAB\\n\" +\n         \"AoGBAOI8sDkSL6pnJKmKjQkOEQjVjVAwZEOpd+HJ4uxX3DPY6huO7zlZj77Oh4ba\\n\" +\n         \"GD4duK7VAmRbgwGAtHCSc2XYEN7ICnfkQrm+3Q8nS824Sz21WlzdCxKDFkDcC1wK\\n\" +\n         \"RjE7SwXN1Kj8Xq8Vpf+z6OzHatSRZD85JM3u0/QCksOJTVIBAkEA9OpycYTuUYjC\\n\" +\n         \"2pLrO5kkl0nIHbNPvFNZyle19AsHH0z/ClV8DiFtGQpwhqwCoWT0cTmSACPD/quA\\n\" +\n         \"hdc2mvV+4QJBAPHiBi/7qDpJldLLvK5ALbn1yRaPSDXLccvFV4FkSS9b/2+mOM2a\\n\" +\n         \"8JkolVCzImxAm0ZZDZeAGKJj1RZDsMIP188CQCfZKWus7DWZ4dI8S0e0IA75czTZ\\n\" +\n         \"4uRKT3arlLAzRyJhnbFpvThzWdPULgDLZdYqndb6PfYF27LI5q1gGcNWpCECQQCB\\n\" +\n         \"r8/ldiZyafW8eaQGQT7DD7brM5Nh1FyFBp+uLljW3ZqNADBAfKw3Uf0MsZ7pL5KR\\n\" +\n         \"GzogWnvaxXAAafahdeEdAkEAzBT+UcxFmcPUO33PnuuiX5KIqThc6aHjjH5O7yzO\\n\" +\n         \"m4Et9JwQiSgcPBmNY5NKPgmcpvUi9jDylSUV0VUu436RpQ==\\n\" +\n         \"-----END RSA PRIVATE KEY-----\";\n\n      VirtualMachineApi client = requestSendsResponse(\n         HttpRequest.builder().method(\"GET\")\n               .endpoint(\"http://localhost:8080/client/api\")\n               .addQueryParam(\"response\", \"json\")\n               .addQueryParam(\"command\", \"getVMPassword\")\n               .addQueryParam(\"id\", \"1\")\n               .addQueryParam(\"apiKey\", \"identity\")\n               .addQueryParam(\"signature\", \"SVA2r1KRj4yG03rATMLPZWS+Knw=\")\n               .addHeader(\"Accept\", \"application/json\")\n               .build(),\n         HttpResponse.builder()\n               .statusCode(200)\n               .payload(payloadFromResource(\"/getvmpasswordresponse.json\"))\n               .build());\n\n      String actual = client.getEncryptedPasswordForVirtualMachine(\"1\");\n      String expected = \"EFOwm8icZ4sEib4y6ntVHUKHZJQrGBdyPkL1L9lpFHYhs3JfAtL5E5bxBP5Er27bJyOZPjKFcInX\\r\\n\" +\n         \"pQ0LZlQBZDd5/ac0NSoM6tAX3H30pYxNw4t2f9u8aJ48oOEvufgGxTTHnM9qHXD04lt+Ouql6i2q\\r\\n\" +\n         \"HxBqCxFkMZEla3LFieE=\\r\\n\";\n\n      assertEquals(actual, expected);\n\n      WindowsLoginCredentialsFromEncryptedData passwordDecrypt = new WindowsLoginCredentialsFromEncryptedData(new JCECrypto());\n\n      assertEquals(passwordDecrypt.apply(\n         EncryptedPasswordAndPrivateKey.builder().encryptedPassword(actual).privateKey(privateKey).build()).getOptionalPassword().get(), \"bX7vvptvw\");\n   }\n   \n   HttpRequest deployVirtualMachineInZone =  HttpRequest.builder().method(\"GET\")\n      .endpoint(\"http://localhost:8080/client/api\")\n      .addQueryParam(\"response\", \"json\")\n      .addQueryParam(\"command\", \"deployVirtualMachine\")\n      .addQueryParam(\"zoneid\", \"zone1\")\n      .addQueryParam(\"serviceofferingid\", \"serviceOffering1\")\n      .addQueryParam(\"templateid\", \"template1\")\n      .addQueryParam(\"apiKey\", \"identity\")\n      .addQueryParam(\"signature\", \"pBjjnTq7/ezN94Uj0gpy2T//cJQ=\")\n      .addHeader(\"Accept\", \"application/json\")\n      .build();\n\n   public void testDeployVirtualMachineIs2xxVersion3x() {\n      HttpResponse deployVirtualMachineInZoneResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResource(\"/deployvirtualmachineresponse.json\")).build();\n      VirtualMachineApi client = requestSendsResponse(deployVirtualMachineInZone, deployVirtualMachineInZoneResponse);\n\n      AsyncCreateResponse async = client.deployVirtualMachineInZone(\"zone1\", \"serviceOffering1\", \"template1\");\n\n      assertEquals(async, AsyncCreateResponse.builder().id(\"1234\").jobId(\"50006\").build());\n   }\n\n   public void testDeployVirtualMachineIs2xxVersion4x() {\n      HttpResponse deployVirtualMachineInZoneResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResource(\"/deployvirtualmachineresponse4x.json\")).build();\n      VirtualMachineApi client = requestSendsResponse(deployVirtualMachineInZone, deployVirtualMachineInZoneResponse);\n\n      AsyncCreateResponse async = client.deployVirtualMachineInZone(\"zone1\", \"serviceOffering1\", \"template1\");\n\n      assertEquals(\n            async,\n            AsyncCreateResponse.builder().id(\"1cce6cb7-2268-47ff-9696-d9e610f6619a\")\n                  .jobId(\"13330fc9-8b3e-4582-aa3e-90883c041ff0\").build());\n   }\n\n   @Override\n   protected VirtualMachineApi clientFrom(CloudStackContext context) {\n      return context.getApi().getVirtualMachineApi();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/VirtualMachineApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Predicates.in;\nimport static com.google.common.collect.Iterables.find;\nimport static com.google.common.collect.Iterables.get;\nimport static com.google.common.collect.Iterables.getFirst;\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static com.google.common.collect.Sets.filter;\nimport static org.jclouds.cloudstack.options.ListNetworksOptions.Builder.isDefault;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.ExecutionException;\nimport java.util.logging.Logger;\n\nimport org.jclouds.cloudstack.CloudStackApi;\nimport org.jclouds.cloudstack.domain.AsyncCreateResponse;\nimport org.jclouds.cloudstack.domain.AsyncJob;\nimport org.jclouds.cloudstack.domain.GuestIPType;\nimport org.jclouds.cloudstack.domain.NIC;\nimport org.jclouds.cloudstack.domain.Network;\nimport org.jclouds.cloudstack.domain.NetworkOffering;\nimport org.jclouds.cloudstack.domain.ServiceOffering;\nimport org.jclouds.cloudstack.domain.Template;\nimport org.jclouds.cloudstack.domain.VirtualMachine;\nimport org.jclouds.cloudstack.domain.Zone;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest;\nimport org.jclouds.cloudstack.options.CreateNetworkOptions;\nimport org.jclouds.cloudstack.options.DeployVirtualMachineOptions;\nimport org.jclouds.cloudstack.options.UpdateVirtualMachineOptions;\nimport org.jclouds.cloudstack.options.ListNetworkOfferingsOptions;\nimport org.jclouds.cloudstack.options.ListNetworksOptions;\nimport org.jclouds.cloudstack.options.ListTemplatesOptions;\nimport org.jclouds.cloudstack.options.ListVirtualMachinesOptions;\nimport org.jclouds.util.InetAddresses2;\nimport org.testng.annotations.AfterGroups;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Objects;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Throwables;\nimport com.google.common.collect.ComparisonChain;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Maps;\nimport com.google.common.collect.Ordering;\nimport com.google.common.net.HostAndPort;\nimport com.google.common.net.HostSpecifier;\n\n/**\n * Tests behavior of {@code VirtualMachineApiLiveTest}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"VirtualMachineApiLiveTest\")\npublic class VirtualMachineApiLiveTest extends BaseCloudStackApiLiveTest {\n   private static final Logger logger = Logger.getAnonymousLogger();\n\n   private VirtualMachine vm = null;\n\n   static final Ordering<ServiceOffering> DEFAULT_SIZE_ORDERING = new Ordering<ServiceOffering>() {\n      public int compare(ServiceOffering left, ServiceOffering right) {\n         return ComparisonChain.start().compare(left.getCpuNumber(), right.getCpuNumber())\n               .compare(left.getMemory(), right.getMemory()).result();\n      }\n   };\n\n   public static VirtualMachine createVirtualMachine(CloudStackApi client, String defaultTemplate,\n         Predicate<String> jobComplete, Predicate<VirtualMachine> virtualMachineRunning) {\n      Set<Network> networks = client.getNetworkApi().listNetworks(isDefault(true));\n      if (!networks.isEmpty()) {\n         Network network = get(filter(networks, new Predicate<Network>() {\n            @Override\n            public boolean apply(Network network) {\n               return network != null && network.getState().equals(\"Implemented\");\n            }\n         }), 0);\n         return createVirtualMachineInNetwork(network,\n               defaultTemplateOrPreferredInZone(defaultTemplate, client, network.getZoneId()), client, jobComplete,\n               virtualMachineRunning);\n      } else {\n         String zoneId = find(client.getZoneApi().listZones(), new Predicate<Zone>() {\n\n            @Override\n            public boolean apply(Zone arg0) {\n               return arg0.isSecurityGroupsEnabled();\n            }\n\n         }).getId();\n         return createVirtualMachineWithSecurityGroupInZone(zoneId,\n               defaultTemplateOrPreferredInZone(defaultTemplate, client, zoneId),\n               get(client.getSecurityGroupApi().listSecurityGroups(), 0).getId(), client, jobComplete,\n               virtualMachineRunning);\n      }\n   }\n\n   public static VirtualMachine createVirtualMachineWithSecurityGroupInZone(String zoneId, String templateId, String groupId,\n         CloudStackApi client, Predicate<String> jobComplete,\n         Predicate<VirtualMachine> virtualMachineRunning) {\n      return createVirtualMachineWithOptionsInZone(new DeployVirtualMachineOptions().securityGroupId(groupId), zoneId,\n            templateId, client, jobComplete, virtualMachineRunning);\n   }\n\n   public static VirtualMachine createVirtualMachineInNetwork(Network network, String templateId,\n         CloudStackApi client, Predicate<String> jobComplete,\n         Predicate<VirtualMachine> virtualMachineRunning) {\n      DeployVirtualMachineOptions options = new DeployVirtualMachineOptions();\n      String zoneId = network.getZoneId();\n      options.networkId(network.getId());\n      return createVirtualMachineWithOptionsInZone(options, zoneId, templateId, client, jobComplete,\n            virtualMachineRunning);\n   }\n\n   public static VirtualMachine createVirtualMachineInNetworkWithIp(\n         CloudStackApi client, String templateId, Set<Network> networks, Map<String, String> ipToNetwork,\n         Predicate<String> jobComplete, Predicate<VirtualMachine> virtualMachineRunning) {\n\n      DeployVirtualMachineOptions options = new DeployVirtualMachineOptions();\n\n      String zoneId = getFirst(networks, null).getZoneId();\n      options.networkIds(Iterables.transform(networks, new Function<Network, String>() {\n         @Override\n         public String apply(Network network) {\n            return network.getId();\n         }\n      }));\n      options.ipsToNetworks(ipToNetwork);\n\n      return createVirtualMachineWithOptionsInZone(options, zoneId, templateId,\n         client, jobComplete, virtualMachineRunning);\n   }\n\n   public static VirtualMachine createVirtualMachineWithOptionsInZone(DeployVirtualMachineOptions options, String zoneId,\n         String templateId, CloudStackApi client, Predicate<String> jobComplete,\n         Predicate<VirtualMachine> virtualMachineRunning) {\n      String serviceOfferingId = DEFAULT_SIZE_ORDERING.min(client.getOfferingApi().listServiceOfferings()).getId();\n\n      System.out.printf(\"serviceOfferingId %s, templateId %s, zoneId %s, options %s%n\", serviceOfferingId, templateId,\n            zoneId, options);\n      AsyncCreateResponse job = client.getVirtualMachineApi().deployVirtualMachineInZone(zoneId, serviceOfferingId,\n            templateId, options);\n      assertTrue(jobComplete.apply(job.getJobId()));\n      AsyncJob<VirtualMachine> jobWithResult = client.getAsyncJobApi().<VirtualMachine> getAsyncJob(job.getJobId());\n      if (jobWithResult.getError() != null)\n         Throwables.propagate(new ExecutionException(String.format(\"job %s failed with exception %s\", job.getId(),\n               jobWithResult.getError().toString())) {\n         });\n      VirtualMachine vm = jobWithResult.getResult();\n      if (vm.isPasswordEnabled()) {\n         assert vm.getPassword() != null : vm;\n      }\n      assertTrue(virtualMachineRunning.apply(vm));\n      assertEquals(vm.getServiceOfferingId(), serviceOfferingId);\n      assertEquals(vm.getTemplateId(), templateId);\n      assertEquals(vm.getZoneId(), zoneId);\n      return vm;\n   }\n\n   @Test\n   public void testCreateVirtualMachine() throws Exception {\n      String defaultTemplate = templateBuilderSpec != null ? templateBuilderSpec.getImageId() : null;\n      vm = createVirtualMachine(client, defaultTemplate, jobComplete, virtualMachineRunning);\n      if (vm.getPassword() != null) {\n         conditionallyCheckSSH();\n      }\n      assert in(ImmutableSet.of(\"ROOT\", \"NetworkFilesystem\", \"IscsiLUN\", \"VMFS\", \"PreSetup\"))\n         .apply(vm.getRootDeviceType()) : vm;\n      checkVm(vm);\n   }\n\n   @Test\n   public void testCreateVirtualMachineWithSpecificIp() throws Exception {\n      skipIfNotGlobalAdmin();\n\n      String defaultTemplate = templateBuilderSpec != null ? templateBuilderSpec.getImageId() : null;\n      Network network = null;\n\n      try {\n         Template template = getOnlyElement(\n            client.getTemplateApi().listTemplates(ListTemplatesOptions.Builder.id(defaultTemplate)));\n         logger.info(\"Using template: \" + template);\n\n         Set<Network> allSafeNetworksInZone = adminClient.getNetworkApi().listNetworks(\n            ListNetworksOptions.Builder.zoneId(template.getZoneId()).isSystem(false));\n         for (Network net : allSafeNetworksInZone) {\n            if (net.getName().equals(prefix + \"-ip-network\")) {\n               logger.info(\"Deleting VMs in network: \" + net);\n\n               Set<VirtualMachine> machinesInNetwork = adminClient.getVirtualMachineApi().listVirtualMachines(\n                  ListVirtualMachinesOptions.Builder.networkId(net.getId()));\n\n               for (VirtualMachine machine : machinesInNetwork) {\n                  if (machine.getState().equals(VirtualMachine.State.RUNNING)) {\n                     logger.info(\"Deleting VM: \" + machine);\n                     destroyMachine(machine);\n                  }\n               }\n\n               assertTrue(adminJobComplete.apply(\n                  adminClient.getNetworkApi().deleteNetwork(net.getId())), net.toString());\n            }\n         }\n\n         NetworkOffering offering = getFirst(\n            client.getOfferingApi().listNetworkOfferings(\n               ListNetworkOfferingsOptions.Builder.zoneId(template.getZoneId()).specifyVLAN(true)), null);\n         checkNotNull(offering, \"No network offering found\");\n         logger.info(\"Using network offering: \" + offering);\n\n         network = adminClient.getNetworkApi().createNetworkInZone(\n            template.getZoneId(), offering.getId(), prefix + \"-ip-network\", \"\",\n            CreateNetworkOptions.Builder.startIP(\"192.168.0.1\").endIP(\"192.168.0.5\")\n               .netmask(\"255.255.255.0\").gateway(\"192.168.0.1\").vlan(\"21\"));\n         logger.info(\"Created network: \" + network);\n\n         Network requiredNetwork = getOnlyElement(filter(adminClient.getNetworkApi().listNetworks(\n            ListNetworksOptions.Builder.zoneId(template.getZoneId())), new Predicate<Network>() {\n            @Override\n            public boolean apply(Network network) {\n               return network.isDefault() &&\n                  network.getGuestIPType() == GuestIPType.VIRTUAL;\n            }\n         }));\n         logger.info(\"Required network: \" + requiredNetwork);\n\n         String ipAddress = \"192.168.0.4\";\n\n         Map<String, String> ipsToNetworks = Maps.newHashMap();\n         ipsToNetworks.put(ipAddress, network.getId());\n\n         vm = createVirtualMachineInNetworkWithIp(\n            adminClient, defaultTemplate, ImmutableSet.of(requiredNetwork, network),\n            ipsToNetworks, adminJobComplete, adminVirtualMachineRunning);\n         logger.info(\"Created VM: \" + vm);\n\n         boolean hasStaticIpNic = false;\n         for (NIC nic : vm.getNICs()) {\n            if (Objects.equal(nic.getNetworkId(), network.getId())) {\n               hasStaticIpNic = true;\n               assertEquals(nic.getIPAddress(), ipAddress);\n            }\n         }\n         assert hasStaticIpNic;\n         checkVm(vm);\n\n      } finally {\n         if (vm != null) {\n            destroyMachine(vm);\n            vm = null;\n         }\n         if (network != null) {\n            String jobId = adminClient.getNetworkApi().deleteNetwork(network.getId());\n            adminJobComplete.apply(jobId);\n            network = null;\n         }\n      }\n   }\n\n   private void destroyMachine(VirtualMachine virtualMachine) {\n      assertTrue(adminJobComplete.apply(\n         adminClient.getVirtualMachineApi().destroyVirtualMachine(virtualMachine.getId())), virtualMachine.toString());\n      assertTrue(adminVirtualMachineDestroyed.apply(virtualMachine));\n   }\n\n   private void conditionallyCheckSSH() {\n      if (vm.getPassword() != null && !loginCredentials.getOptionalPassword().isPresent())\n         loginCredentials = loginCredentials.toBuilder().password(vm.getPassword()).build();\n      assert HostSpecifier.isValid(vm.getIPAddress());\n      if (!InetAddresses2.isPrivateIPAddress(vm.getIPAddress())) {\n         // not sure if the network is public or not, so we have to test\n         HostAndPort socket = HostAndPort.fromParts(vm.getIPAddress(), 22);\n         System.err.printf(\"testing socket %s%n\", socket);\n         System.err.printf(\"testing ssh %s%n\", socket);\n         checkSSH(socket);\n      } else {\n         System.err.printf(\"skipping ssh %s, as private%n\", vm.getIPAddress());\n      }\n   }\n\n   @Test(dependsOnMethods = \"testCreateVirtualMachine\")\n   public void testLifeCycle() throws Exception {\n      String job = client.getVirtualMachineApi().stopVirtualMachine(vm.getId());\n      assertTrue(jobComplete.apply(job));\n      vm = client.getVirtualMachineApi().getVirtualMachine(vm.getId());\n      assertEquals(vm.getState(), VirtualMachine.State.STOPPED);\n\n      if (vm.isPasswordEnabled()) {\n         job = client.getVirtualMachineApi().resetPasswordForVirtualMachine(vm.getId());\n         assertTrue(jobComplete.apply(job));\n         vm = client.getAsyncJobApi().<VirtualMachine> getAsyncJob(job).getResult();\n         if (vm.getPassword() != null) {\n            conditionallyCheckSSH();\n         }\n      }\n\n      job = client.getVirtualMachineApi().startVirtualMachine(vm.getId());\n      assertTrue(jobComplete.apply(job));\n      vm = client.getVirtualMachineApi().getVirtualMachine(vm.getId());\n      assertEquals(vm.getState(), VirtualMachine.State.RUNNING);\n\n      job = client.getVirtualMachineApi().rebootVirtualMachine(vm.getId());\n      assertTrue(jobComplete.apply(job));\n      vm = client.getVirtualMachineApi().getVirtualMachine(vm.getId());\n      assertEquals(vm.getState(), VirtualMachine.State.RUNNING);\n   }\n\n   @Test(dependsOnMethods = \"testCreateVirtualMachine\")\n   public void testVirtualMachineUpdate() throws Exception {\n      UpdateVirtualMachineOptions options = UpdateVirtualMachineOptions.Builder.displayName(\"updated-name\");\n      String job = client.getVirtualMachineApi().updateVirtualMachine(vm.getId(), options);\n      assertTrue(jobComplete.apply(job));\n      vm = client.getVirtualMachineApi().getVirtualMachine(vm.getId());\n      assertEquals(vm.getDisplayName(), \"updated-name\");\n   }\n\n   @AfterGroups(groups = \"live\")\n   @Override\n   protected void tearDownContext() {\n      if (vm != null) {\n         destroyMachine(vm);\n         vm = null;\n      }\n      super.tearDownContext();\n   }\n\n   @Test\n   public void testListVirtualMachines() throws Exception {\n      Set<VirtualMachine> response = client.getVirtualMachineApi().listVirtualMachines();\n      assert null != response;\n      assertTrue(response.size() > 0);\n      for (VirtualMachine vm : response) {\n         VirtualMachine newDetails = getOnlyElement(client.getVirtualMachineApi().listVirtualMachines(\n               ListVirtualMachinesOptions.Builder.id(vm.getId())));\n         assertEquals(vm.getId(), newDetails.getId());\n         checkVm(vm);\n      }\n   }\n\n   protected void checkVm(VirtualMachine vm) {\n      assertEquals(vm.getId(), client.getVirtualMachineApi().getVirtualMachine(vm.getId()).getId());\n      assert vm.getId() != null : vm;\n      assert vm.getName() != null : vm;\n      // vm.getDisplayName() can be null, so skip that check.\n      assert vm.getAccount() != null : vm;\n      assert vm.getDomain() != null : vm;\n      assert vm.getDomainId() != null : vm;\n      assert vm.getCreated() != null : vm;\n      assert vm.getState() != null : vm;\n      assert vm.getZoneId() != null : vm;\n      assert vm.getZoneName() != null : vm;\n      assert vm.getTemplateId() != null : vm;\n      assert vm.getTemplateName() != null : vm;\n      assert vm.getServiceOfferingId() != null : vm;\n      assert vm.getServiceOfferingName() != null : vm;\n      assert vm.getCpuCount() > 0 : vm;\n      assert vm.getCpuSpeed() > 0 : vm;\n      assert vm.getMemory() > 0 : vm;\n      assert vm.getGuestOSId() != null : vm;\n      assert vm.getRootDeviceId() != null : vm;\n      // assert vm.getRootDeviceType() != null : vm;\n      if (vm.getJobId() != null)\n         assert vm.getJobStatus() != null : vm;\n      assert vm.getNICs() != null && !vm.getNICs().isEmpty() : vm;\n      for (NIC nic : vm.getNICs()) {\n         assert nic.getId() != null : vm;\n         assert nic.getNetworkId() != null : vm;\n         assert nic.getTrafficType() != null : vm;\n         assert nic.getGuestIPType() != null : vm;\n         switch (vm.getState()) {\n         case RUNNING:\n            assert nic.getNetmask() != null : vm;\n            assert nic.getGateway() != null : vm;\n            assert nic.getIPAddress() != null : vm;\n            break;\n         case STARTING:\n            assert nic.getNetmask() == null : vm;\n            assert nic.getGateway() == null : vm;\n            assert nic.getIPAddress() == null : vm;\n            break;\n         default:\n            assert nic.getNetmask() != null : vm;\n            assert nic.getGateway() != null : vm;\n            assert nic.getIPAddress() != null : vm;\n         }\n\n      }\n      assert vm.getSecurityGroups() != null && vm.getSecurityGroups().size() > 0 : vm;\n      assert vm.getHypervisor() != null : vm;\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/VirtualMachineApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport java.io.IOException;\nimport java.net.URLEncoder;\nimport java.nio.charset.Charset;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.cloudstack.options.UpdateVirtualMachineOptions;\nimport org.jclouds.fallbacks.MapHttp4xxCodesToExceptions;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiTest;\nimport org.jclouds.cloudstack.options.AssignVirtualMachineOptions;\nimport org.jclouds.cloudstack.options.ListVirtualMachinesOptions;\nimport org.jclouds.cloudstack.options.StopVirtualMachineOptions;\nimport org.jclouds.functions.IdentityFunction;\nimport org.jclouds.http.functions.ParseFirstJsonValueNamed;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Functions;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.reflect.Invokable;\nimport static com.google.common.io.BaseEncoding.base64;\n/**\n * Tests behavior of {@code VirtualMachineApi}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"VirtualMachineApiTest\")\npublic class VirtualMachineApiTest extends BaseCloudStackApiTest<VirtualMachineApi> {\n   public void testListVirtualMachines() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(VirtualMachineApi.class, \"listVirtualMachines\",\n            ListVirtualMachinesOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listVirtualMachines&listAll=true HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testListVirtualMachinesOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(VirtualMachineApi.class, \"listVirtualMachines\",\n            ListVirtualMachinesOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\n            ListVirtualMachinesOptions.Builder.accountInDomain(\"adrian\", \"6\").usesVirtualNetwork(true)));\n\n      assertRequestLineEquals(\n            httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listVirtualMachines&listAll=true&account=adrian&domainid=6&forvirtualnetwork=true HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testGetVirtualMachine() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(VirtualMachineApi.class, \"getVirtualMachine\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(5));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listVirtualMachines&listAll=true&id=5 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest,\n            Functions.compose(IdentityFunction.INSTANCE, IdentityFunction.INSTANCE).getClass());\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testRebootVirtualMachine() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(VirtualMachineApi.class, \"rebootVirtualMachine\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(5));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=rebootVirtualMachine&id=5 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testStartVirtualMachine() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(VirtualMachineApi.class, \"startVirtualMachine\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(5));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=startVirtualMachine&id=5 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testStopVirtualMachine() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(VirtualMachineApi.class, \"stopVirtualMachine\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"5\"));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=stopVirtualMachine&id=5 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testStopVirtualMachineForced() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(VirtualMachineApi.class, \"stopVirtualMachine\", String.class,\n                                                                StopVirtualMachineOptions.class);\n\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"5\",\n                                                        StopVirtualMachineOptions.Builder.forced(true)));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=stopVirtualMachine&id=5&forced=true HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testResetPasswordForVirtualMachine() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(VirtualMachineApi.class, \"resetPasswordForVirtualMachine\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(5));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=resetPasswordForVirtualMachine&id=5 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testChangeServiceForVirtualMachine() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(VirtualMachineApi.class, \"changeServiceForVirtualMachine\", String.class, String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(5, 6));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=changeServiceForVirtualMachine&id=5&serviceofferingid=6 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testUpdateVirtualMachine() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(VirtualMachineApi.class, \"updateVirtualMachine\", String.class,\n              UpdateVirtualMachineOptions.class);\n      byte[] unencodedData = \"userData\".getBytes(Charset.forName(\"utf-8\"));\n      UpdateVirtualMachineOptions options = UpdateVirtualMachineOptions.Builder\n            .displayName(\"disp\").group(\"test\").haEnable(true).osTypeId(\"osid\").userData(unencodedData);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"5\",\n            options));\n\n\n      String base64UrlEncodedData =  URLEncoder.encode(base64().encode(unencodedData), \"utf-8\");\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=updateVirtualMachine\" +\n                  \"&id=5&displayname=disp&group=test&haenable=true&ostypeid=osid&userdata=\" +\n                  base64UrlEncodedData + \" HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testDestroyVirtualMachine() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(VirtualMachineApi.class, \"destroyVirtualMachine\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(5));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=destroyVirtualMachine&id=5 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n   \n   public void testAssignVirtualMachine() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(VirtualMachineApi.class, \"assignVirtualMachine\", String.class,\n            AssignVirtualMachineOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"abcd\",\n            AssignVirtualMachineOptions.Builder.accountInDomain(\"adrian\", \"6\")));\n\n      assertRequestLineEquals(\n            httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=assignVirtualMachine&virtualmachineid=abcd&account=adrian&domainid=6 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/VolumeApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport org.jclouds.cloudstack.CloudStackContext;\nimport org.jclouds.cloudstack.domain.AsyncCreateResponse;\nimport org.jclouds.cloudstack.internal.BaseCloudStackExpectTest;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.Test;\n\nimport java.net.URI;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.cert.CertificateException;\n\nimport static org.testng.Assert.assertNotNull;\n\n/**\n* Test the CloudStack VolumeApi\n*\n*/\n@Test(groups = \"unit\", testName = \"VolumeApiExpectTest\")\npublic class VolumeApiExpectTest extends BaseCloudStackExpectTest<VolumeApi> {\n\n   public void testCreateVolumeFromCustomDiskOffering() throws NoSuchAlgorithmException, CertificateException {\n      VolumeApi client = requestSendsResponse(\n              HttpRequest.builder()\n                      .method(\"GET\")\n                      .endpoint(\n                              URI.create(\"http://localhost:8080/client/api?response=json&\" +\n                                      \"command=createVolume&name=VolumeApiExpectTest-jclouds-volume&diskofferingid=0473f5dd-bca5-4af4-a9b6-db9e8a88a2f6&zoneid=6f9a2921-b22a-4149-8b71-6ffc275a2177&size=1&apiKey=identity&signature=%2BoEjGobVFLr58k19LeAE81bZkKM%3D\"))\n                      .addHeader(\"Accept\", \"application/json\")\n                      .build(),\n              HttpResponse.builder()\n                      .statusCode(200)\n                      .payload(payloadFromResource(\"/queryasyncjobresultresponse-createvolume.json\"))\n                      .build());\n      \n      AsyncCreateResponse response = client.createVolumeFromCustomDiskOfferingInZone(\"VolumeApiExpectTest-jclouds-volume\", \"0473f5dd-bca5-4af4-a9b6-db9e8a88a2f6\", \"6f9a2921-b22a-4149-8b71-6ffc275a2177\", 1);\n      assertNotNull(response);\n   }\n\n   @Override\n   protected VolumeApi clientFrom(CloudStackContext context) {\n      return context.getApi().getVolumeApi();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/VolumeApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.testng.AssertJUnit.assertEquals;\nimport static org.testng.AssertJUnit.assertFalse;\nimport static org.testng.AssertJUnit.assertNotNull;\nimport static org.testng.AssertJUnit.assertNotSame;\nimport static org.testng.AssertJUnit.assertNull;\nimport static org.testng.AssertJUnit.assertTrue;\n\nimport java.util.NoSuchElementException;\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\n\nimport org.jclouds.cloudstack.CloudStackApi;\nimport org.jclouds.cloudstack.domain.AsyncCreateResponse;\nimport org.jclouds.cloudstack.domain.DiskOffering;\nimport org.jclouds.cloudstack.domain.Snapshot;\nimport org.jclouds.cloudstack.domain.VirtualMachine;\nimport org.jclouds.cloudstack.domain.Volume;\nimport org.jclouds.cloudstack.domain.Zone;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest;\nimport org.jclouds.cloudstack.options.ListVolumesOptions;\nimport org.jclouds.logging.Logger;\nimport org.testng.annotations.BeforeMethod;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.Iterables;\n\n/**\n * Tests behavior of {@code VolumeApi}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"VolumeApiLiveTest\")\npublic class VolumeApiLiveTest extends BaseCloudStackApiLiveTest {\n\n   @Resource Logger logger = Logger.NULL;\n\n   protected String prefix = System.getProperty(\"user.name\") + \"-\" + getClass().getSimpleName();\n\n   private String zoneId;\n\n   @BeforeMethod(groups = \"live\")\n   public void setZoneId() {\n      Set<Zone> zones = client.getZoneApi().listZones();\n      assertNotNull(zones);\n      assertFalse(zones.isEmpty());\n      zoneId = Iterables.get(zones, 0).getId();\n   }\n\n   public void testListVolumes() {\n      Set<Volume> volumes = client.getVolumeApi().listVolumes();\n      assertNotNull(volumes);\n      assertFalse(volumes.isEmpty());\n\n      for (Volume volume : volumes) {\n         checkVolume(volume);\n      }\n   }\n\n   public void testListVolumesById() {\n      Iterable<String> volumeIds = Iterables.transform(client.getVolumeApi().listVolumes(), new Function<Volume, String>() {\n         public String apply(Volume input) {\n            return input.getId();\n         }\n      });\n      assertNotNull(volumeIds);\n      assertFalse(Iterables.isEmpty(volumeIds));\n\n      for (String id : volumeIds) {\n         Set<Volume> found = client.getVolumeApi().listVolumes(ListVolumesOptions.Builder.id(id));\n         assertNotNull(found);\n         assertEquals(1, found.size());\n         Volume volume = Iterables.getOnlyElement(found);\n         assertEquals(id, volume.getId());\n         checkVolume(volume);\n      }\n   }\n\n   public void testListVolumesNonexistantId() {\n      Set<Volume> found = client.getVolumeApi().listVolumes(ListVolumesOptions.Builder.id(\"foo\"));\n      assertNotNull(found);\n      assertTrue(found.isEmpty());\n   }\n\n   public void testGetVolumeById() {\n      Iterable<String> volumeIds = Iterables.transform(client.getVolumeApi().listVolumes(), new Function<Volume, String>() {\n         public String apply(Volume input) {\n            return input.getId();\n         }\n      });\n      assertNotNull(volumeIds);\n      assertFalse(Iterables.isEmpty(volumeIds));\n\n      for (String id : volumeIds) {\n         Volume found = client.getVolumeApi().getVolume(id);\n         assertNotNull(found);\n         assertEquals(id, found.getId());\n         checkVolume(found);\n      }\n   }\n\n   public void testGetVolumeNonexistantId() {\n      Volume found = client.getVolumeApi().getVolume(\"foo\");\n      assertNull(found);\n   }\n\n   protected DiskOffering getPreferredDiskOffering() {\n      for (DiskOffering candidate : client.getOfferingApi().listDiskOfferings()) {\n         //any will do\n         return candidate;\n      }\n      throw new AssertionError(\"No suitable DiskOffering found.\");\n   }\n   protected Snapshot getPreferredSnapshot() {\n      for (Snapshot candidate : client.getSnapshotApi().listSnapshots()) {\n         if (candidate.getState() == Snapshot.State.BACKED_UP)\n            return candidate;\n      }\n      throw new AssertionError(\"No suitable Snapshot found.\");\n   }\n\n   protected VirtualMachine getPreferredVirtualMachine() {\n      for (VirtualMachine candidate : client.getVirtualMachineApi().listVirtualMachines()) {\n//         this is a guess::\n         if (candidate.getState() == VirtualMachine.State.RUNNING || candidate.getState() == VirtualMachine.State.STOPPED)\n            return candidate;\n      }\n      throw new AssertionError(\"No suitable VirtualMachine found.\");\n   }\n\n   protected Volume createPreferredVolumeFromDisk() {\n      AsyncCreateResponse job = client.getVolumeApi().createVolumeFromDiskOfferingInZone(prefix + \"-jclouds-volume\",\n            getPreferredDiskOffering().getId(), zoneId);\n      assertTrue(jobComplete.apply(job.getJobId()));\n      logger.info(\"created volume \" + job.getId());\n      return findVolumeWithId(job.getId());\n   }\n\n   public void testCreateVolumeFromDiskofferingInZoneAndDeleteVolume() {\n      logger.info(\"testCreateVolumeFromDiskofferingInZoneAndDeleteVolume\");\n      Volume volume = createPreferredVolumeFromDisk();\n      checkVolume(volume);\n      client.getVolumeApi().deleteVolume(volume.getId());\n   }\n\n   /** Test requires a custom disk offering to be available */\n   public void testCreateVolumeFromCustomDiskOffering() {\n      final int size = 1;\n      DiskOffering offering = null;\n      for (DiskOffering candidate : client.getOfferingApi().listDiskOfferings()) {\n         if (candidate.isCustomized()) {\n            offering = candidate;\n            break;\n         }\n      }\n      \n      assertNotNull(\"No custom disk offering found!\", offering);\n      \n      AsyncCreateResponse job = client.getVolumeApi().createVolumeFromCustomDiskOfferingInZone(\n                prefix + \"-jclouds-volume\", offering.getId(), zoneId, size);\n      assertTrue(jobComplete.apply(job.getJobId()));\n      logger.info(\"created volume \" + job.getId());\n      \n      Volume volume = findVolumeWithId(job.getId());\n      try {\n         checkVolume(volume);\n         assertEquals(volume.getSize(), size * 1024 * 1024 * 1024);\n      } finally {\n         client.getVolumeApi().deleteVolume(volume.getId());\n      }\n   }\n\n   /** test requires that a VM exist */\n   public void testCreateVolumeFromDiskofferingInZoneAndAttachVolumeToVirtualMachineAndDetachAndDelete() {\n      logger.info(\"testCreateVolumeFromDiskofferingInZoneAndAttachVolumeToVirtualMachineAndDetachAndDelete\");\n      final Volume volume = createPreferredVolumeFromDisk();\n      try {\n\n         checkVolume(volume);\n\n         VirtualMachine virtualMachine = getPreferredVirtualMachine();\n\n         logger.info(\"attaching volume %s to vm %s\", volume, virtualMachine);\n         AsyncCreateResponse job = client.getVolumeApi().attachVolume(volume.getId(), virtualMachine.getId());\n         assertTrue(jobComplete.apply(job.getJobId()));\n         Volume attachedVolume = findVolumeWithId(volume.getId());\n\n         checkVolume(attachedVolume);\n         assertEquals(virtualMachine.getId(), attachedVolume.getVirtualMachineId());\n         assertNotNull(attachedVolume.getAttached());\n\n         logger.info(\"detaching volume %s from vm %s\", volume, virtualMachine);\n         job = client.getVolumeApi().detachVolume(volume.getId());\n         assertTrue(jobComplete.apply(job.getJobId()));\n         Volume detachedVolume = findVolumeWithId(volume.getId());\n\n         checkVolume(detachedVolume);\n         assertNull(detachedVolume.getAttached());\n\n      } finally {\n         client.getVolumeApi().deleteVolume(volume.getId());\n      }\n   }\n\n   public void testCreateVolumeFromSnapshotInZoneAndDeleteVolume() {\n      logger.info(\"testCreateVolumeFromSnapshotInZoneAndDeleteVolume (takes ~3m)\");\n      assertNotNull(getPreferredSnapshot());\n\n      AsyncCreateResponse job = client.getVolumeApi().createVolumeFromSnapshotInZone(prefix + \"-jclouds-volume\",\n            getPreferredSnapshot().getId(), zoneId);\n      assertTrue(jobComplete.apply(job.getJobId()));\n      Volume volume = findVolumeWithId(job.getId());\n\n      checkVolume(volume);\n      client.getVolumeApi().deleteVolume(volume.getId());\n   }\n\n   static void checkVolume(final Volume volume) {\n      assertNotNull(volume.getId());\n      assertNotNull(volume.getName());\n      assertNotSame(Volume.Type.UNRECOGNIZED, volume.getType());\n   }\n\n   Volume findVolumeWithId(final String id) {\n      return findVolumeWithId(client, id);\n   }\n\n   static Volume findVolumeWithId(final CloudStackApi client, final String id) {\n      for (Volume v : client.getVolumeApi().listVolumes())\n         if (v.getId().equals(id)) return v;\n      throw new NoSuchElementException(\"no volume with id \" + id);\n   }\n\n//   //uncomment to force a cleanup of volumes (since test failures can leave messes) \n//   public void deleteAllWeUsed() {\n//      for (Volume v: client.getVolumeApi().listVolumes()) {\n//         if (v.getName().startsWith(prefix)) {\n//            logger.warn(\"found apparent detritus, deleting: %s\", v);\n//            try {\n//               client.getVolumeApi().deleteVolume(v.getId());\n//            } catch (Exception e) {\n//               logger.warn(e, \"failed to delete %s: %s\", v, e);\n//            }\n//         }\n//       }\n//   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/VolumeApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport java.io.IOException;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiTest;\nimport org.jclouds.cloudstack.options.ListVolumesOptions;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.reflect.Invokable;\n/**\n * Tests behavior of {@code EventApi}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"VolumeApiTest\")\npublic class VolumeApiTest extends BaseCloudStackApiTest<VolumeApi> {\n\n   public void testListVolumes() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(VolumeApi.class, \"listVolumes\", ListVolumesOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listVolumes&listAll=true HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testGetVolume() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(VolumeApi.class, \"getVolume\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(111L));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listVolumes&listAll=true&id=111 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   HttpRequest createVolumeFromSnapshot = HttpRequest.builder().method(\"GET\")\n                                                     .endpoint(\"http://localhost:8080/client/api\")\n                                                     .addQueryParam(\"response\", \"json\")\n                                                     .addQueryParam(\"command\", \"createVolume\")\n                                                     .addQueryParam(\"name\", \"jclouds-volume\")\n                                                     .addQueryParam(\"snapshotid\", \"999\")\n                                                     .addQueryParam(\"zoneid\", \"111\").build();\n\n   public void testCreateVolumeWithSnapshot() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(VolumeApi.class, \"createVolumeFromSnapshotInZone\", String.class, String.class,\n            String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"jclouds-volume\", 999L, 111L));\n\n      assertRequestLineEquals(httpRequest, createVolumeFromSnapshot.getRequestLine());\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertSaxResponseParserClassEquals(method, null);\n      checkFilters(httpRequest);\n\n   }\n\n   HttpRequest createVolumeFromDiskOffering = HttpRequest.builder().method(\"GET\")\n                                                         .endpoint(\"http://localhost:8080/client/api\")\n                                                         .addQueryParam(\"response\", \"json\")\n                                                         .addQueryParam(\"command\", \"createVolume\")\n                                                         .addQueryParam(\"name\", \"jclouds-volume\")\n                                                         .addQueryParam(\"diskofferingid\", \"999\")\n                                                         .addQueryParam(\"zoneid\", \"111\").build();\n\n   public void testCreateVolumeFromDiskOffering() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(VolumeApi.class, \"createVolumeFromDiskOfferingInZone\", String.class, String.class,\n            String.class);\n\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"jclouds-volume\", 999L, 111L));\n\n      assertRequestLineEquals(httpRequest, createVolumeFromDiskOffering.getRequestLine());\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertSaxResponseParserClassEquals(method, null);\n      checkFilters(httpRequest);\n\n   }\n\n   public void testAttachVolume() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(VolumeApi.class, \"attachVolume\", String.class, String.class);\n\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(111L, 999L));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=attachVolume&id=111&virtualmachineid=999 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertSaxResponseParserClassEquals(method, null);\n      checkFilters(httpRequest);\n\n   }\n\n   public void testDetachVolume() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(VolumeApi.class, \"detachVolume\", String.class);\n\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(111L));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=detachVolume&id=111 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertSaxResponseParserClassEquals(method, null);\n      checkFilters(httpRequest);\n\n   }\n\n   public void testDeleteVolume() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(VolumeApi.class, \"deleteVolume\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(111L));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=deleteVolume&id=111 HTTP/1.1\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, VoidOnNotFoundOr404.class);\n      checkFilters(httpRequest);\n\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/ZoneApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.cloudstack.CloudStackContext;\nimport org.jclouds.cloudstack.domain.NetworkType;\nimport org.jclouds.cloudstack.domain.Tag;\nimport org.jclouds.cloudstack.domain.Zone;\nimport org.jclouds.cloudstack.internal.BaseCloudStackExpectTest;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Test the CloudStack ZoneApi\n */\n@Test(groups = \"unit\", testName = \"ZoneApiExpectTest\")\npublic class ZoneApiExpectTest extends BaseCloudStackExpectTest<ZoneApi> {\n\n\n   public void testListZonesWhenResponseIs2xx() {\n      ZoneApi client = requestSendsResponse(\n         HttpRequest.builder().method(\"GET\")\n                    .endpoint(\"http://localhost:8080/client/api\")\n                    .addQueryParam(\"response\", \"json\")\n                    .addQueryParam(\"command\", \"listZones\")\n                    .addQueryParam(\"listAll\", \"true\")\n                    .addQueryParam(\"apiKey\", \"identity\")\n                    .addQueryParam(\"signature\", \"8iHCtck0qfxFTqJ8reyAObRf31I=\")\n                    .addHeader(\"Accept\", \"application/json\")\n                    .build(),\n         HttpResponse.builder()\n                     .statusCode(200)\n                     .payload(payloadFromResource(\"/listzonesresponse.json\"))\n                     .build());\n\n      assertEquals(client.listZones(),\n         ImmutableSet.of(\n            Zone.builder()\n               .id(\"1\")\n               .name(\"San Jose 1\")\n               .networkType(NetworkType.ADVANCED)\n               .securityGroupsEnabled(false).build(),\n            Zone.builder()\n                  .id(\"2\")\n                  .name(\"Chicago\")\n                  .networkType(NetworkType.ADVANCED)\n                  .securityGroupsEnabled(true)\n                  .tags(Tag.builder()\n                        .account(\"1\")\n                        .domain(\"ROOT\")\n                        .domainId(\"1\")\n                        .key(\"some-tag\")\n                        .resourceId(\"2\")\n                        .resourceType(Tag.ResourceType.ZONE)\n                        .value(\"some-value\")\n                        .build())\n                  .build()));\n   }\n\n   public void testListZonesWhenResponseIs404() {\n      ZoneApi client = requestSendsResponse(\n            HttpRequest.builder()\n                  .method(\"GET\")\n                  .endpoint(\"http://localhost:8080/client/api\")\n                  .addQueryParam(\"response\", \"json\")\n                  .addQueryParam(\"command\", \"listZones\")\n                  .addQueryParam(\"listAll\", \"true\")\n                  .addQueryParam(\"apiKey\", \"identity\")\n                  .addQueryParam(\"signature\", \"8iHCtck0qfxFTqJ8reyAObRf31I=\")\n                  .addHeader(\"Accept\", \"application/json\")\n            .build(),\n         HttpResponse.builder()\n            .statusCode(404)\n            .build());\n\n      assertEquals(client.listZones(), ImmutableSet.of());\n   }\n\n   @Override\n   protected ZoneApi clientFrom(CloudStackContext context) {\n      return context.getApi().getZoneApi();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/ZoneApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.NetworkType;\nimport org.jclouds.cloudstack.domain.Zone;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiLiveTest;\nimport org.jclouds.cloudstack.options.ListZonesOptions;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Iterables;\n\n/**\n * Tests behavior of {@code ZoneApiLiveTest}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"ZoneApiLiveTest\")\npublic class ZoneApiLiveTest extends BaseCloudStackApiLiveTest {\n\n   public void testListZones() throws Exception {\n      Set<Zone> response = client.getZoneApi().listZones();\n      assert null != response;\n      long zoneCount = response.size();\n      assertTrue(zoneCount >= 0);\n      for (Zone zone : response) {\n         Zone newDetails = Iterables.getOnlyElement(client.getZoneApi().listZones(\n               ListZonesOptions.Builder.id(zone.getId())));\n         assertEquals(zone, newDetails);\n         assertEquals(zone, client.getZoneApi().getZone(zone.getId()));\n         assert zone.getId() != null : zone;\n         assert zone.getName() != null : zone;\n         assert zone.getNetworkType() != null && zone.getNetworkType() != NetworkType.UNRECOGNIZED : zone;\n         switch (zone.getNetworkType()) {\n         case ADVANCED:\n            // TODO\n            // assert zone.getVLAN() != null : zone;\n            // assert zone.getDomain() == null : zone;\n            // assert zone.getDomainId() == null : zone;\n            // assert zone.getGuestCIDRAddress() != null : zone;\n            break;\n         case BASIC:\n            assert zone.getVLAN() == null : zone;\n            assert zone.getDNS().size() > 0 : zone;\n            assert zone.getInternalDNS().size() > 0 : zone;\n            assert zone.getDomain() == null : zone;\n            assert zone.getDomainId() == null : zone;\n            assert zone.getGuestCIDRAddress() == null : zone;\n            break;\n         }\n\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/ZoneApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.features;\n\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport java.io.IOException;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.cloudstack.internal.BaseCloudStackApiTest;\nimport org.jclouds.cloudstack.options.ListZonesOptions;\nimport org.jclouds.functions.IdentityFunction;\nimport org.jclouds.http.functions.ParseFirstJsonValueNamed;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Functions;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Iterables;\nimport com.google.common.reflect.Invokable;\n/**\n * Tests behavior of {@code ZoneApi}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"ZoneApiTest\")\npublic class ZoneApiTest extends BaseCloudStackApiTest<ZoneApi> {\n   public void testListZones() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ZoneApi.class, \"listZones\", ListZonesOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listZones&listAll=true HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      // now make sure request filters apply by replaying\n      httpRequest = (GeneratedHttpRequest) Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);\n      httpRequest = (GeneratedHttpRequest) Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);\n\n      assertRequestLineEquals(\n            httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listZones&listAll=true&apiKey=identity&signature=8iHCtck0qfxFTqJ8reyAObRf31I%3D HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testListZonesOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ZoneApi.class, \"listZones\", ListZonesOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(ListZonesOptions.Builder.available(true).domainId(\"5\")\n            .id(\"6\")));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listZones&listAll=true&available=true&domainid=5&id=6 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testGetZone() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ZoneApi.class, \"getZone\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(6));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET http://localhost:8080/client/api?response=json&command=listZones&listAll=true&id=6 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/json\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest,\n            Functions.compose(IdentityFunction.INSTANCE, IdentityFunction.INSTANCE).getClass());\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/filters/QuerySignerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.filters;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.IntegrationTestClient;\nimport org.jclouds.logging.config.NullLoggingModule;\nimport org.jclouds.providers.AnonymousProviderMetadata;\nimport org.jclouds.rest.internal.BaseRestApiTest.MockModule;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.inject.Injector;\nimport com.google.inject.Module;\n\n/**\n * Tests behavior of {@code QuerySigner}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"QuerySignerTest\")\npublic class QuerySignerTest {\n   public static final Injector INJECTOR = ContextBuilder\n         .newBuilder(\n               AnonymousProviderMetadata.forApiOnEndpoint(IntegrationTestClient.class,\n                     \"http://localhost:8080/client/api\"))\n         .credentials(\"apiKey\", \"secretKey\")\n         .apiVersion(\"2.2\")\n         .modules(ImmutableList.<Module> of(new MockModule(), new NullLoggingModule())).buildInjector();\n\n\n   @Test\n   void testCreateStringToSign() {\n      QuerySigner filter = INJECTOR.getInstance(QuerySigner.class);\n\n      assertEquals(\n            filter.createStringToSign(HttpRequest.builder().method(\"GET\")\n                  .endpoint(\"http://localhost:8080/client/api?command=listZones\").build()),\n            \"apikey=apikey&command=listzones\");\n   }\n\n   @Test\n   void testCreateStringToSignWithBrackets() {\n      // This test asserts that key *names* are not URL-encoded - only values\n      // should be encoded, according to \"CloudStack API Developer’s Guide\".\n      QuerySigner filter = INJECTOR.getInstance(QuerySigner.class);\n\n      assertEquals(\n            filter.createStringToSign(HttpRequest.builder().method(\"GET\")\n                  .endpoint(\"http://localhost:8080/client/api?command=deployVirtualMachine&iptonetworklist[0].ip=127.0.0.1&iptonetworklist[0].networkid=1\").build()),\n            \"apikey=apikey&command=deployvirtualmachine&iptonetworklist[0].ip=127.0.0.1&iptonetworklist[0].networkid=1\");\n   }\n\n   @Test\n   void testFilter() {\n      QuerySigner filter = INJECTOR.getInstance(QuerySigner.class);\n\n      assertEquals(\n               filter.filter(\n                        HttpRequest.builder().method(\"GET\")\n                                 .endpoint(\"http://localhost:8080/client/api?command=listZones\").build())\n                        .getRequestLine(),\n               \"GET http://localhost:8080/client/api?command=listZones&apiKey=apiKey&signature=2UG8AcnMaozL3BINdjgkJ%2BRzjEY%3D HTTP/1.1\");\n   }\n\n   @Test\n   void testFilterTwice() {\n      QuerySigner filter = INJECTOR.getInstance(QuerySigner.class);\n      HttpRequest request = HttpRequest.builder().method(\"GET\")\n               .endpoint(\"http://localhost:8080/client/api?command=listZones\").build();\n      for (int i = 0; i < 2; i++) {\n         request = filter.filter(request);\n         assertEquals(\n               request.getRequestLine(),\n               \"GET http://localhost:8080/client/api?command=listZones&apiKey=apiKey&signature=2UG8AcnMaozL3BINdjgkJ%2BRzjEY%3D HTTP/1.1\");\n      }\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/functions/BlockUntilJobCompletesAndReturnResultTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.functions;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.cloudstack.CloudStackApi;\nimport org.jclouds.cloudstack.domain.AsyncCreateResponse;\nimport org.jclouds.cloudstack.domain.AsyncJob;\nimport org.jclouds.cloudstack.domain.AsyncJobError;\nimport org.jclouds.cloudstack.domain.AsyncJobError.ErrorCode;\nimport org.jclouds.cloudstack.features.AsyncJobApi;\nimport org.jclouds.cloudstack.strategy.BlockUntilJobCompletesAndReturnResult;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Predicates;\nimport com.google.common.util.concurrent.UncheckedExecutionException;\n\n@Test(groups = \"unit\", testName = \"BlockUntilJobCompletesAndReturnResultTest\")\npublic class BlockUntilJobCompletesAndReturnResultTest {\n\n   public void testApply() {\n      String id = \"1\";\n      String jobId = \"2\";\n\n      CloudStackApi client = createMock(CloudStackApi.class);\n      Predicate<String> jobComplete = Predicates.alwaysTrue();\n      AsyncJobApi jobClient = createMock(AsyncJobApi.class);\n\n      expect(client.getAsyncJobApi()).andReturn(jobClient).atLeastOnce();\n      expect(jobClient.getAsyncJob(jobId)).andReturn(AsyncJob.builder().id(jobId).result(\"foo\").build()).atLeastOnce();\n\n      replay(client);\n      replay(jobClient);\n\n      assertEquals(\n            new BlockUntilJobCompletesAndReturnResult(client, jobComplete).<String>apply(AsyncCreateResponse.builder().id(id).jobId(\n                  jobId).build()), \"foo\");\n\n      verify(client);\n      verify(jobClient);\n\n   }\n\n   @Test(expectedExceptions = IllegalStateException.class)\n   public void testJobDoesntCompleteThrowsIllegalStateException() {\n      String id = \"1\";\n      String jobId = \"2\";\n\n      CloudStackApi client = createMock(CloudStackApi.class);\n      // the alwaysfalse predicate should blow up with IllegalStateException\n      Predicate<String> jobComplete = Predicates.alwaysFalse();\n      AsyncJobApi jobClient = createMock(AsyncJobApi.class);\n\n      expect(client.getAsyncJobApi()).andReturn(jobClient).atLeastOnce();\n      expect(jobClient.getAsyncJob(jobId)).andReturn(AsyncJob.builder().id(jobId).result(\"foo\").build()).atLeastOnce();\n\n      replay(client);\n      replay(jobClient);\n\n      assertEquals(\n            new BlockUntilJobCompletesAndReturnResult(client, jobComplete).<String>apply(\n                  AsyncCreateResponse.builder().id(id).jobId(jobId).build()), \"foo\");\n\n      verify(client);\n      verify(jobClient);\n\n   }\n\n   @Test(expectedExceptions = UncheckedExecutionException.class)\n   public void testJobWithErrorThrowsUncheckedExecutionException() {\n      String id = \"1\";\n      String jobId = \"2\";\n\n      CloudStackApi client = createMock(CloudStackApi.class);\n      Predicate<String> jobComplete = Predicates.alwaysTrue();\n      AsyncJobApi jobClient = createMock(AsyncJobApi.class);\n\n      expect(client.getAsyncJobApi()).andReturn(jobClient).atLeastOnce();\n      expect(jobClient.getAsyncJob(jobId)).andReturn(\n            AsyncJob.builder().id(jobId)\n                  .error(AsyncJobError.builder().errorCode(ErrorCode.INTERNAL_ERROR).errorText(\"ERRROR\").build())\n                  .result(\"foo\").build())\n            .atLeastOnce();\n\n      replay(client);\n      replay(jobClient);\n\n      assertEquals(\n            new BlockUntilJobCompletesAndReturnResult(client, jobComplete).<String>apply(\n                  AsyncCreateResponse.builder().id(id).jobId(jobId).build()), \"foo\");\n\n      verify(client);\n      verify(jobClient);\n\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/functions/CreateSecurityGroupIfNeededTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.functions;\n\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL;\nimport static org.jclouds.util.Predicates2.retry;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.UnknownHostException;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.cloudstack.CloudStackApi;\nimport org.jclouds.cloudstack.domain.IngressRule;\nimport org.jclouds.cloudstack.domain.SecurityGroup;\nimport org.jclouds.cloudstack.domain.Zone;\nimport org.jclouds.cloudstack.domain.ZoneSecurityGroupNamePortsCidrs;\nimport org.jclouds.cloudstack.features.AsyncJobApi;\nimport org.jclouds.cloudstack.features.SecurityGroupApi;\nimport org.jclouds.cloudstack.features.ZoneApi;\nimport org.jclouds.cloudstack.predicates.JobComplete;\nimport org.jclouds.cloudstack.suppliers.ZoneIdToZoneSupplier;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Provides;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.name.Names;\n\n@Test(groups = \"unit\", testName = \"CreateSecurityGroupIfNeededTest\")\npublic class CreateSecurityGroupIfNeededTest {\n\n   @Test\n   public void testApply() throws UnknownHostException {\n      final CloudStackApi client = createMock(CloudStackApi.class);\n      SecurityGroupApi secClient = createMock(SecurityGroupApi.class);\n      ZoneApi zoneClient = createMock(ZoneApi.class);\n      AsyncJobApi jobClient = createMock(AsyncJobApi.class);\n      \n      SecurityGroup group = createMock(SecurityGroup.class);\n      \n      Zone zone = createMock(Zone.class);\n\n      expect(group.getIngressRules()).andReturn(ImmutableSet.<IngressRule> of());\n      expect(group.getId()).andReturn(\"sec-1234\").anyTimes();\n      expect(zone.isSecurityGroupsEnabled()).andReturn(true);\n      \n      expect(client.getSecurityGroupApi()).andReturn(secClient)\n         .anyTimes();\n      expect(client.getZoneApi()).andReturn(zoneClient);\n      expect(client.getAsyncJobApi()).andReturn(jobClient).anyTimes();\n\n      expect(zoneClient.getZone(\"zone-abc1\")).andReturn(zone);\n      expect(secClient.createSecurityGroup(\"group-1\")).andReturn(group);\n      expect(secClient.authorizeIngressPortsToCIDRs(\"sec-1234\",\n                                                    \"TCP\",\n                                                    22,\n                                                    22,\n                                                    ImmutableSet.of(\"0.0.0.0/0\"))).andReturn(\"job-1234\");\n\n      replay(client, secClient, zoneClient, zone, group);\n\n      ZoneSecurityGroupNamePortsCidrs input = ZoneSecurityGroupNamePortsCidrs.builder()\n         .zone(\"zone-abc1\")\n         .name(\"group-1\")\n         .ports(ImmutableSet.of(22))\n         .cidrs(ImmutableSet.<String> of()).build();\n      \n      CreateSecurityGroupIfNeeded parser = Guice.createInjector(new AbstractModule() {\n\n            @Override\n            protected void configure() {\n               bind(new TypeLiteral<Supplier<String>>() {\n                  }).toInstance(Suppliers.ofInstance(\"1\"));\n               bind(CloudStackApi.class).toInstance(client);\n               bind(new TypeLiteral<CacheLoader<String, Zone>>() {}).\n                  to(ZoneIdToZone.class);\n               bind(new TypeLiteral<Supplier<LoadingCache<String, Zone>>>() {}).\n                  to(ZoneIdToZoneSupplier.class);\n               bind(String.class).annotatedWith(Names.named(PROPERTY_SESSION_INTERVAL)).toInstance(\"60\");\n            }\n            \n            @Provides\n            @Singleton\n            protected Predicate<String> jobComplete(JobComplete jobComplete) {\n               return retry(jobComplete, 1200, 1, 5, SECONDS);\n            }\n            \n         }).getInstance(CreateSecurityGroupIfNeeded.class);\n      \n      assertEquals(parser.apply(input), group);\n\n      verify(client, secClient, zoneClient, zone, group);\n   }\n\n   \n   @Test\n   public void testApplyGroupAlreadyExists() throws UnknownHostException {\n      final CloudStackApi client = createMock(CloudStackApi.class);\n      SecurityGroupApi secClient = createMock(SecurityGroupApi.class);\n      ZoneApi zoneClient = createMock(ZoneApi.class);\n      AsyncJobApi jobClient = createMock(AsyncJobApi.class);\n      \n      SecurityGroup group = createMock(SecurityGroup.class);\n      \n      Zone zone = createMock(Zone.class);\n\n      expect(group.getId()).andReturn(\"sec-1234\").anyTimes();\n      expect(zone.isSecurityGroupsEnabled()).andReturn(true);\n      \n      expect(client.getSecurityGroupApi()).andReturn(secClient)\n         .anyTimes();\n      expect(client.getZoneApi()).andReturn(zoneClient);\n      expect(client.getAsyncJobApi()).andReturn(jobClient).anyTimes();\n\n      expect(zoneClient.getZone(\"zone-abc2\")).andReturn(zone);\n      expect(secClient.createSecurityGroup(\"group-1\")).andThrow(new IllegalStateException());\n      expect(secClient.getSecurityGroupByName(\"group-1\")).andReturn(group);\n\n      replay(client, secClient, zoneClient, zone, group);\n\n      ZoneSecurityGroupNamePortsCidrs input = ZoneSecurityGroupNamePortsCidrs.builder()\n         .zone(\"zone-abc2\")\n         .name(\"group-1\")\n         .ports(ImmutableSet.of(22))\n         .cidrs(ImmutableSet.<String> of()).build();\n      \n      CreateSecurityGroupIfNeeded parser = Guice.createInjector(new AbstractModule() {\n\n            @Override\n            protected void configure() {\n               bind(new TypeLiteral<Supplier<String>>() {\n                  }).toInstance(Suppliers.ofInstance(\"1\"));\n               bind(CloudStackApi.class).toInstance(client);\n               bind(new TypeLiteral<CacheLoader<String, Zone>>() {}).\n                  to(ZoneIdToZone.class);\n               bind(new TypeLiteral<Supplier<LoadingCache<String, Zone>>>() {}).\n                  to(ZoneIdToZoneSupplier.class);\n               bind(String.class).annotatedWith(Names.named(PROPERTY_SESSION_INTERVAL)).toInstance(\"60\");\n            }\n            \n            @Provides\n            @Singleton\n            protected Predicate<String> jobComplete(JobComplete jobComplete) {\n               return retry(jobComplete, 1200, 1, 5, SECONDS);\n            }\n            \n         }).getInstance(CreateSecurityGroupIfNeeded.class);\n      \n      assertEquals(parser.apply(input), group);\n\n      verify(client, secClient, zoneClient, zone, group);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testApplyZoneNoSecurityGroups() throws UnknownHostException {\n      final CloudStackApi client = createMock(CloudStackApi.class);\n      SecurityGroupApi secClient = createMock(SecurityGroupApi.class);\n      ZoneApi zoneClient = createMock(ZoneApi.class);\n      AsyncJobApi jobClient = createMock(AsyncJobApi.class);\n      \n      SecurityGroup group = createMock(SecurityGroup.class);\n      \n      Zone zone = createMock(Zone.class);\n\n      expect(zone.isSecurityGroupsEnabled()).andReturn(false);\n      \n      expect(client.getZoneApi()).andReturn(zoneClient);\n\n      expect(zoneClient.getZone(\"zone-abc3\")).andReturn(zone);\n\n      replay(client, zoneClient, zone);\n\n      ZoneSecurityGroupNamePortsCidrs input = ZoneSecurityGroupNamePortsCidrs.builder()\n         .zone(\"zone-abc3\")\n         .name(\"group-1\")\n         .ports(ImmutableSet.of(22))\n         .cidrs(ImmutableSet.<String> of()).build();\n      \n      CreateSecurityGroupIfNeeded parser = Guice.createInjector(new AbstractModule() {\n\n            @Override\n            protected void configure() {\n               bind(new TypeLiteral<Supplier<String>>() {\n                  }).toInstance(Suppliers.ofInstance(\"1\"));\n               bind(CloudStackApi.class).toInstance(client);\n               bind(new TypeLiteral<CacheLoader<String, Zone>>() {}).\n                  to(ZoneIdToZone.class);\n               bind(new TypeLiteral<Supplier<LoadingCache<String, Zone>>>() {}).\n                  to(ZoneIdToZoneSupplier.class);\n               bind(String.class).annotatedWith(Names.named(PROPERTY_SESSION_INTERVAL)).toInstance(\"60\");\n            }\n            \n            @Provides\n            @Singleton\n            protected Predicate<String> jobComplete(JobComplete jobComplete) {\n               return retry(jobComplete, 1200, 1, 5, SECONDS);\n            }\n            \n         }).getInstance(CreateSecurityGroupIfNeeded.class);\n\n      assertEquals(parser.apply(input), group);\n\n      verify(client, zoneClient, zone);\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/functions/ParseAsyncJobFromHttpResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.functions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.InputStream;\n\nimport org.jclouds.cloudstack.domain.AsyncJob;\nimport org.jclouds.cloudstack.domain.AsyncJob.ResultCode;\nimport org.jclouds.cloudstack.domain.AsyncJob.Status;\nimport org.jclouds.cloudstack.domain.AsyncJobError;\nimport org.jclouds.cloudstack.domain.AsyncJobError.ErrorCode;\nimport org.jclouds.cloudstack.domain.IPForwardingRule;\nimport org.jclouds.cloudstack.domain.PublicIPAddress;\nimport org.jclouds.cloudstack.domain.Template;\nimport org.jclouds.cloudstack.domain.TemplateExtraction;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.domain.JsonBall;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.json.config.GsonModule;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\")\npublic class ParseAsyncJobFromHttpResponseTest {\n\n   Injector i = Guice.createInjector(new GsonModule() {\n\n      @Override\n      protected void configure() {\n         bind(DateAdapter.class).to(Iso8601DateAdapter.class);\n         super.configure();\n      }\n\n   });\n\n   public void testWithNoResult() {\n      String input = \"{ \\\"queryasyncjobresultresponse\\\" : {\\\"jobid\\\":860,\\\"jobstatus\\\":0,\\\"jobprocstatus\\\":0,\\\"jobresultcode\\\":0} }\";\n\n      AsyncJob<PublicIPAddress> expects = AsyncJob.<PublicIPAddress>builder()\n         .id(\"860\")\n         .status(Status.IN_PROGRESS)\n         .progress(0)\n         .resultCode(ResultCode.SUCCESS).build();\n\n      ParseAsyncJobFromHttpResponse parser = i.getInstance(ParseAsyncJobFromHttpResponse.class);\n      @SuppressWarnings(\"unchecked\")\n      AsyncJob<PublicIPAddress> response = (AsyncJob<PublicIPAddress>) parser.apply(HttpResponse.builder()\n                                                                                                .statusCode(200).message(\"ok\")\n                                                                                                .payload(input).build());\n\n      assertEquals(response, expects);\n   }\n\n   public void testWithSuccessTrueResultSetsNullResult() {\n      String input = \"{ \\\"queryasyncjobresultresponse\\\" : {\\\"jobid\\\":1138,\\\"jobstatus\\\":1,\\\"jobprocstatus\\\":0,\\\"jobresultcode\\\":0,\\\"jobresulttype\\\":\\\"object\\\",\\\"jobresult\\\":{\\\"success\\\":true}} }\";\n\n      AsyncJob<PublicIPAddress> expects = AsyncJob.<PublicIPAddress>builder()\n         .id(\"1138\")\n         .status(Status.SUCCEEDED)\n         .progress(0)\n         .resultType(\"object\")\n         .resultCode(ResultCode.SUCCESS).build();\n\n      ParseAsyncJobFromHttpResponse parser = i.getInstance(ParseAsyncJobFromHttpResponse.class);\n      @SuppressWarnings(\"unchecked\")\n      AsyncJob<PublicIPAddress> response = (AsyncJob<PublicIPAddress>) parser.apply(HttpResponse.builder()\n                                                                                                .statusCode(200).message(\"ok\")\n                                                                                                .payload(input).build());\n      assertEquals(response, expects);\n   }\n\n   public void testWithErrorSetsResultNullSoToAvoidClassCastExceptions() {\n      String input = \"{ \\\"queryasyncjobresultresponse\\\" : {\\\"jobid\\\":1103,\\\"jobstatus\\\":2,\\\"jobprocstatus\\\":0,\\\"jobresultcode\\\":530,\\\"jobresulttype\\\":\\\"object\\\",\\\"jobresult\\\":{\\\"errorcode\\\":530,\\\"errortext\\\":\\\"Internal error executing command, please contact your system administrator\\\"}} }\";\n\n      AsyncJob<PublicIPAddress> expects = AsyncJob\n         .<PublicIPAddress>builder()\n         .id(\"1103\")\n         .status(Status.FAILED)\n         .progress(0)\n         .resultType(\"object\")\n         .error(AsyncJobError.builder().errorCode(ErrorCode.INTERNAL_ERROR).errorText(\"Internal error executing \" +\n            \"command, please contact your system administrator\").build())\n         .resultCode(ResultCode.FAIL).build();\n\n      ParseAsyncJobFromHttpResponse parser = i.getInstance(ParseAsyncJobFromHttpResponse.class);\n      @SuppressWarnings(\"unchecked\")\n      AsyncJob<PublicIPAddress> response = (AsyncJob<PublicIPAddress>) parser.apply(HttpResponse.builder()\n                                                                                                .statusCode(200).message(\"ok\")\n                                                                                                .payload(input).build());\n      assertEquals(response, expects);\n   }\n\n   public void testWithUnknownResultReturnsStringifiedJson() {\n      String input = \"{ \\\"queryasyncjobresultresponse\\\" : {\\\"jobid\\\":860,\\\"jobstatus\\\":0,\\\"jobprocstatus\\\":0,\\\"jobresultcode\\\":0,\\\"jobresult\\\":{\\\"foo\\\":{\\\"bar\\\":1}}}}\";\n\n      AsyncJob<?> expects = AsyncJob.builder()\n         .id(\"860\")\n         .status(Status.IN_PROGRESS)\n         .progress(0)\n         .resultCode(ResultCode.SUCCESS)\n         .result(\"{\\\"bar\\\":1}\")\n         .build();\n\n      ParseAsyncJobFromHttpResponse parser = i.getInstance(ParseAsyncJobFromHttpResponse.class);\n      @SuppressWarnings(\"unchecked\")\n      AsyncJob<PublicIPAddress> response = (AsyncJob<PublicIPAddress>) parser.apply(HttpResponse.builder()\n                                                                                                .statusCode(200).message(\"ok\")\n                                                                                                .payload(input).build());\n      assertEquals(response, expects);\n   }\n\n   public void testWithBadResultReturnsMap() {\n      // Not the best result object, but this is an unexpected error case.\n      // Cloud.com have verified\n      // that this case will not happen. This code is only here to prevent\n      // exceptions from being\n      // thrown in case they change their minds.\n      String input = \"{ \\\"queryasyncjobresultresponse\\\" : {\\\"jobid\\\":860,\\\"jobstatus\\\":0,\\\"jobprocstatus\\\":0,\\\"jobresultcode\\\":0,\\\"jobresult\\\":{\\\"foo\\\":{\\\"bar\\\":1},\\\"foo2\\\":{\\\"bar2\\\":2}}}}\";\n\n      AsyncJob<?> expects = AsyncJob.builder()\n         .id(\"860\")\n         .status(Status.IN_PROGRESS)\n         .progress(0)\n         .resultCode(ResultCode.SUCCESS)\n         .result(ImmutableMap.of(\"foo\", new JsonBall(\"{\\\"bar\\\":1}\"), \"foo2\", new JsonBall(\"{\\\"bar2\\\":2}\"))).build();\n\n      ParseAsyncJobFromHttpResponse parser = i.getInstance(ParseAsyncJobFromHttpResponse.class);\n      @SuppressWarnings(\"unchecked\")\n      AsyncJob<PublicIPAddress> response = (AsyncJob<PublicIPAddress>) parser.apply(HttpResponse.builder()\n                                                                                                .statusCode(200).message(\"ok\")\n                                                                                                .payload(input).build());\n      assertEquals(response, expects);\n   }\n\n   public void testPublicIPAddress() {\n      InputStream is = getClass().getResourceAsStream(\"/queryasyncjobresultresponse-ipaddress.json\");\n      AsyncJob<PublicIPAddress> expects = AsyncJob\n         .<PublicIPAddress>builder()\n         .id(\"860\")\n         .status(Status.SUCCEEDED)\n         .progress(0)\n         .resultType(\"object\")\n         .resultCode(ResultCode.SUCCESS)\n         .result(\n            PublicIPAddress\n               .builder()\n               .id(\"6\")\n               .IPAddress(\"72.52.126.35\")\n               .allocated(\n                  new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2011-02-23T20:15:01-0800\"))\n               .zoneId(\"1\").zoneName(\"San Jose 1\").isSourceNAT(false).account(\"adrian\").domainId(\"1\")\n               .domain(\"ROOT\").usesVirtualNetwork(true).isStaticNAT(false).associatedNetworkId(\"204\")\n               .networkId(\"200\").state(PublicIPAddress.State.ALLOCATING).build()\n\n         ).build();\n\n      ParseAsyncJobFromHttpResponse parser = i.getInstance(ParseAsyncJobFromHttpResponse.class);\n      @SuppressWarnings(\"unchecked\")\n      AsyncJob<PublicIPAddress> response = (AsyncJob<PublicIPAddress>) parser.apply(HttpResponse.builder()\n                                                                                                .statusCode(200).message(\"ok\")\n                                                                                                .payload(is).build());\n      assertEquals(response, expects);\n   }\n\n   public void testIPForwardingRule() {\n      InputStream is = getClass().getResourceAsStream(\"/queryasyncjobresultresponse-ipforwardingrule.json\");\n      AsyncJob<IPForwardingRule> expects = AsyncJob\n         .<IPForwardingRule>builder()\n         .id(\"1133\")\n         .status(Status.SUCCEEDED)\n         .progress(0)\n         .resultType(\"object\")\n         .resultCode(ResultCode.SUCCESS)\n         .result(\n            IPForwardingRule.builder().id(\"109\").protocol(\"tcp\").virtualMachineId(\"226\")\n               .virtualMachineName(\"i-3-226-VM\").IPAddressId(\"36\").IPAddress(\"72.52.126.65\").startPort(22)\n               .endPort(22).state(\"Active\").build()).build();\n\n      ParseAsyncJobFromHttpResponse parser = i.getInstance(ParseAsyncJobFromHttpResponse.class);\n      @SuppressWarnings(\"unchecked\")\n      AsyncJob<IPForwardingRule> response = (AsyncJob<IPForwardingRule>) parser.apply(HttpResponse.builder()\n                                                                                                .statusCode(200).message(\"ok\")\n                                                                                                .payload(is).build());\n      assertEquals(response, expects);\n   }\n\n   public void testOverloadedKeyName() {\n      InputStream is = getClass().getResourceAsStream(\"/queryasyncjobresultresponse-createtemplate.json\");\n      ParseAsyncJobFromHttpResponse parser = i.getInstance(ParseAsyncJobFromHttpResponse.class);\n      AsyncJob<?> response = parser.apply(HttpResponse.builder().statusCode(200).message(\"ok\").payload(is).build());\n      assertTrue(response.getResult() instanceof Template, \"response expected to be Template, actually is \" + response.getResult().getClass());\n\n      is = getClass().getResourceAsStream(\"/queryasyncjobresultresponse-extracttemplate.json\");\n      response = parser.apply(HttpResponse.builder().statusCode(200).message(\"ok\").payload(is).build());\n      assertTrue(response.getResult() instanceof TemplateExtraction, \"response expected to be TemplateExtraction, actually is \" + response.getResult().getClass());\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/functions/ParseAsyncJobsFromHttpResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.AsyncJob;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.json.config.GsonModule;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\")\npublic class ParseAsyncJobsFromHttpResponseTest {\n\n   Injector injector = Guice.createInjector(new GsonModule() {\n\n      @Override\n      protected void configure() {\n         bind(DateAdapter.class).to(Iso8601DateAdapter.class);\n         super.configure();\n      }\n\n   });\n\n   public void testCanParse() {\n      InputStream is = getClass().getResourceAsStream(\"/listasyncjobsresponse.json\");\n\n      ParseAsyncJobsFromHttpResponse parser = injector.getInstance(ParseAsyncJobsFromHttpResponse.class);\n      Set<AsyncJob<?>> response = parser.apply(HttpResponse.builder().statusCode(200).message(\"ok\").payload(is).build());\n\n      assertEquals(response.size(), 77);\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/functions/ReuseOrAssociateNewPublicIPAddressTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.functions;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.jclouds.cloudstack.options.AssociateIPAddressOptions.Builder.networkId;\nimport static org.jclouds.cloudstack.options.ListPublicIPAddressesOptions.Builder.allocatedOnly;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.cloudstack.CloudStackApi;\nimport org.jclouds.cloudstack.domain.AsyncCreateResponse;\nimport org.jclouds.cloudstack.domain.Network;\nimport org.jclouds.cloudstack.domain.PublicIPAddress;\nimport org.jclouds.cloudstack.features.AddressApi;\nimport org.jclouds.cloudstack.strategy.BlockUntilJobCompletesAndReturnResult;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\")\npublic class ReuseOrAssociateNewPublicIPAddressTest {\n   String networkId = \"99l\";\n   String zoneId = \"100l\";\n   // note that it is associated network, not networkId\n   PublicIPAddress address = PublicIPAddress.builder().id(\"200\").state(PublicIPAddress.State.ALLOCATED)\n         .associatedNetworkId(networkId).zoneId(zoneId).build();\n\n   public void testReuseWorks() throws SecurityException, NoSuchMethodException {\n\n      // create mocks\n      CloudStackApi client = createMock(CloudStackApi.class);\n      BlockUntilJobCompletesAndReturnResult blockUntilJobCompletesAndReturnResult = createMock(BlockUntilJobCompletesAndReturnResult.class);\n      AddressApi addressClient = createMock(AddressApi.class);\n      expect(client.getAddressApi()).andReturn(addressClient).atLeastOnce();\n\n      // an address is available\n      expect(addressClient.listPublicIPAddresses(allocatedOnly(true).networkId(networkId))).andReturn(\n            ImmutableSet.<PublicIPAddress> of(address));\n\n      replay(client);\n      replay(blockUntilJobCompletesAndReturnResult);\n      replay(addressClient);\n\n      assertEquals(\n            new ReuseOrAssociateNewPublicIPAddress(client, blockUntilJobCompletesAndReturnResult).apply(Network\n                  .builder().id(networkId).zoneId(zoneId).build()), address);\n\n      verify(client);\n      verify(blockUntilJobCompletesAndReturnResult);\n      verify(addressClient);\n\n   }\n\n   public void testAssociateWorks() throws SecurityException, NoSuchMethodException {\n\n      // create mocks\n      CloudStackApi client = createMock(CloudStackApi.class);\n      BlockUntilJobCompletesAndReturnResult blockUntilJobCompletesAndReturnResult = createMock(BlockUntilJobCompletesAndReturnResult.class);\n      AddressApi addressClient = createMock(AddressApi.class);\n      expect(client.getAddressApi()).andReturn(addressClient).atLeastOnce();\n\n      // no ip addresses available\n      expect(addressClient.listPublicIPAddresses(allocatedOnly(true).networkId(networkId))).andReturn(\n            ImmutableSet.<PublicIPAddress> of());\n\n      AsyncCreateResponse job = AsyncCreateResponse.builder().id(\"1\").jobId(\"2\").build();\n      // make sure we created the job relating to a new ip\n      expect(addressClient.associateIPAddressInZone(zoneId, networkId(networkId))).andReturn(job);\n\n      expect(blockUntilJobCompletesAndReturnResult.apply(job)).andReturn(address);\n\n      replay(client);\n      replay(addressClient);\n      replay(blockUntilJobCompletesAndReturnResult);\n\n      assertEquals(\n            new ReuseOrAssociateNewPublicIPAddress(client, blockUntilJobCompletesAndReturnResult).apply(Network\n                  .builder().id(networkId).zoneId(zoneId).build()), address);\n\n      verify(client);\n      verify(addressClient);\n      verify(blockUntilJobCompletesAndReturnResult);\n\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/functions/StaticNATVirtualMachineInNetworkLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.functions;\n\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.find;\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.NoSuchElementException;\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.IPForwardingRule;\nimport org.jclouds.cloudstack.domain.Network;\nimport org.jclouds.cloudstack.domain.PublicIPAddress;\nimport org.jclouds.cloudstack.domain.VirtualMachine;\nimport org.jclouds.cloudstack.features.NATApiLiveTest;\nimport org.jclouds.cloudstack.features.VirtualMachineApiLiveTest;\nimport org.jclouds.cloudstack.predicates.NetworkPredicates;\nimport org.jclouds.cloudstack.strategy.BlockUntilJobCompletesAndReturnResult;\nimport org.testng.annotations.AfterGroups;\nimport org.testng.annotations.BeforeGroups;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.net.HostAndPort;\n\n/**\n * Tests behavior of {@code StaticNATVirtualMachineInNetwork}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"StaticNATVirtualMachineInNetworkLiveTest\")\npublic class StaticNATVirtualMachineInNetworkLiveTest extends NATApiLiveTest {\n   private PublicIPAddress ip = null;\n   private VirtualMachine vm;\n   private IPForwardingRule rule;\n   private Network network;\n   private boolean networksDisabled;\n\n   @BeforeGroups(groups = \"live\")\n   public void setupClient() {\n      super.setupContext();\n      prefix += \"nat\";\n      try {\n         network = find(client.getNetworkApi().listNetworks(), NetworkPredicates.supportsStaticNAT());\n         String defaultTemplate = templateBuilderSpec != null ? templateBuilderSpec.getImageId() : null;\n         vm = VirtualMachineApiLiveTest.createVirtualMachineInNetwork(network,\n               defaultTemplateOrPreferredInZone(defaultTemplate, client, network.getZoneId()), client, jobComplete,\n               virtualMachineRunning);\n         if (vm.getPassword() != null && !loginCredentials.getOptionalPassword().isPresent())\n            loginCredentials = loginCredentials.toBuilder().password(vm.getPassword()).build();\n      } catch (NoSuchElementException e) {\n         networksDisabled = true;\n      }\n   }\n\n   public void testCreateIPForwardingRule() throws Exception {\n      if (networksDisabled)\n         return;\n      BlockUntilJobCompletesAndReturnResult blocker = new BlockUntilJobCompletesAndReturnResult(client, jobComplete);\n      StaticNATVirtualMachineInNetwork fn = new StaticNATVirtualMachineInNetwork(client, reuseOrAssociate, network);\n      CreatePortForwardingRulesForIP createPortForwardingRulesForIP = new CreatePortForwardingRulesForIP(client,\n            blocker, CacheBuilder.newBuilder().<String, Set<IPForwardingRule>> build(\n                  new GetIPForwardingRulesByVirtualMachine(client)));\n\n      // logger\n      injector.injectMembers(blocker);\n      injector.injectMembers(fn);\n      injector.injectMembers(createPortForwardingRulesForIP);\n\n      ip = fn.apply(vm);\n\n      createPortForwardingRulesForIP.apply(ip, ImmutableSet.of(22));\n\n      rule = getOnlyElement(filter(client.getNATApi().getIPForwardingRulesForIPAddress(ip.getId()),\n            new Predicate<IPForwardingRule>() {\n               @Override\n               public boolean apply(IPForwardingRule rule) {\n                  return rule != null && rule.getStartPort() == 22;\n               }\n            }));\n      assertEquals(rule.getIPAddressId(), ip.getId());\n      assertEquals(rule.getVirtualMachineId(), vm.getId());\n      assertEquals(rule.getStartPort(), 22);\n      assertEquals(rule.getProtocol(), \"tcp\");\n      checkRule(rule);\n      HostAndPort socket = HostAndPort.fromParts(ip.getIPAddress(), 22);\n      checkSSH(socket);\n   }\n\n   @AfterGroups(groups = \"live\")\n   @Override\n   protected void tearDownContext() {\n      if (rule != null) {\n         client.getNATApi().deleteIPForwardingRule(rule.getId());\n      }\n      if (vm != null) {\n         jobComplete.apply(client.getVirtualMachineApi().destroyVirtualMachine(vm.getId()));\n      }\n      if (ip != null) {\n         client.getAddressApi().disassociateIPAddress(ip.getId());\n      }\n      super.tearDownContext();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/functions/WindowsLoginCredentialsFromEncryptedDataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.functions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\n\nimport org.jclouds.cloudstack.domain.EncryptedPasswordAndPrivateKey;\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.encryption.internal.JCECrypto;\nimport org.testng.annotations.Test;\n\npublic class WindowsLoginCredentialsFromEncryptedDataTest {\n\n   private static final String PRIVATE_KEY = \"-----BEGIN RSA PRIVATE KEY-----\\n\" +\n      \"MIIEowIBAAKCAQEAmN6GOSMnyGNWN19ETBh11tJB5OGs3Dps8kPWqAhF9RyL/mKwkW26vH+h/5Z5\\n\" +\n      \"cA5T80pK72kNnXObFaMHNoX3lavrc6yXF+8F3f1tlFX2Z+iB1pYXz1oBPqT6oOmc2XzcsJuJRakd\\n\" +\n      \"zwRwHDaqljpaW7+TZlxhMa1DmUkD/HHMxDCK8jbUIZDc6BZSrnj2uPwHwW737NRE4aC3fcu4LMwf\\n\" +\n      \"b2VotbNGNiAnNmrb/vtIIGkFE8NYEMpiz0WYTWX4eVKpJImv1PR6G1fMLSvudJs0ARObuLDvuonn\\n\" +\n      \"SCFFdkibrwMKYbHVGGh6FoY1Vy0sqI55dgQU1kSNouiDgOGxgx+TIwIDAQABAoIBAHCS/nk5QGS7\\n\" +\n      \"cpRYXa1EHhNSxx/MaUXM6MoH1x3q6cm1egqdlrWh/vAtdZkIsOkqQ/xX65Me493dcomegwNN6KOZ\\n\" +\n      \"9Uw7/xCq/sEZjga8vzaJ7IOgCGy0NVJyn/a70rv+zW5pO8/G2KLI+95rC3iSBFSoYd3xjcnNdIh/\\n\" +\n      \"UqYnD8oxYpKmf7418pMPsBrkglkFlbVBPiDXdpoSziqSN6uWQG4Yh0WR87aElhM9JJW50Hh6h7g5\\n\" +\n      \"OvgCBzS8G+KXCjqimk108+/ed5Nl6VhPAf79yCVZUueKBhaf2r0Kkyxg7M/Y+LJwcoUusIP7Cv7G\\n\" +\n      \"xyzG2vi21prWRCm2sVCUDyQy5qECgYEA92jGVAaB3OGEUIXn7eVE3U3FQH37XcJMGsHqBIzDG13p\\n\" +\n      \"C97HdN21rwRkz+G2eAsIxA+p9BsO7dSmtKC60kl6iMRgltS3W7xoC37N9BtjhpciHcLg8c70oyDx\\n\" +\n      \"qHiLKuDi90mZ1FPmWupO4FJnGEB3evHUKZSpTrVVMzt+tyEn/psCgYEAni1hrYoMkQgN3sEC3CKB\\n\" +\n      \"0jQkrOMvY219B8Tdf9LXSuP6z9POagDBDhkeT3xn8rAOmOfVGHYdO0CvPqmAkmXhf+g+OREdecQa\\n\" +\n      \"uY0FmvcTt+Dx0c6pRZmm5AhvUVXFXqONsSg79iviXbUy5Hik0k5HTs5E6B4obrh5W+xfMTUXghkC\\n\" +\n      \"gYBn92uAW8uumkYT4HF6EuJBbTD6zPYYjFGW3O4OQ2ip02jfSBrhDVoP1fTXNq6K+3gPi9WLcuNv\\n\" +\n      \"JfF37iMTwzTuzDcaqwDyV9YRHpRFhEzqfhAkGYSVmLZM5scmWKGCv0YhTJiMFUWz5sqGkZopIs4S\\n\" +\n      \"qBTT9FjBbooDIXk6U4CPCQKBgFdVBxEhnz6UC9RpDIMuKi88yuMJrChhUx7u+ryQVH3s0ZXdg6HT\\n\" +\n      \"OMPn6mxIa7v6qJSTq3wN+qW0WQ1n2Kz7wz0zpOctI/EO7RJ1YhrlP+XONLV6PMtIwnQ0lAF8MbTG\\n\" +\n      \"6HxfknugTyMd4DN0yMu0nHpOOI1P2VMIVzkBkK1CevBBAoGBALROGR7a+eijHdp0/A0chfUoBmud\\n\" +\n      \"/TsUt+0g/vf1p69rMt6DqEGMgMtp2jIRnwvLElS7gVqnCTEclxNU/0rCXR+V7ImJm8J4f0ff8m0Y\\n\" +\n      \"Fir9nfCYStszo25NvLFfynS9d/aoBuvqGJaiQyNXiyBJ4MaxxFYagzAWTnDX+kzTlkZ2\\n\" +\n      \"-----END RSA PRIVATE KEY-----\";\n   private static final String ENCRYPTED_PASSWORD = \"gO1oMoIjjIifv2iqcfIKiQD7ziOTVXsuaBJFEQrZdb8uJH/LsAiJXZeGKEeXlHl/oMoR3HEIoYuHxl+p5iHdrpP889RmxWBDGOWC5iTUzK6CRa5mFmF1I5Lpt7v2YeVoQWihSM8B19BEdBdY1svQp9nyhPB4AqLDrY28x/OrmRh/qYq953i6Y4Z8c76OHqqGcUYM4ePysRlcizSgQjdkEDmKC10Ak3OFRRx3/LqYsFIMiOHeg47APg+UANNTyRiTIia5FDhSeHJzaeYCBRQ7UYH0z2rg4cX3YjOz/MoznjHiaaN4MO+5N3v84VawnqwKOvlwPyI2bmz0+9Tr6DKzqA==\";\n\n   protected final DateService dateService = new SimpleDateFormatDateService();\n\n   @Test\n   public void testApply() throws Exception {\n      WindowsLoginCredentialsFromEncryptedData f = new WindowsLoginCredentialsFromEncryptedData(new JCECrypto());\n\n      LoginCredentials credentials = f.apply(new EncryptedPasswordAndPrivateKey(ENCRYPTED_PASSWORD, PRIVATE_KEY));\n\n      assertEquals(credentials.getUser(), \"Administrator\");\n      assertEquals(credentials.getOptionalPassword().get(), \"u4.y9mb;nR.\");\n      assertFalse(credentials.getOptionalPrivateKey().isPresent());\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/handlers/CloudStackErrorHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.handlers;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.reportMatcher;\nimport static org.easymock.EasyMock.verify;\n\nimport java.net.URI;\n\nimport org.easymock.IArgumentMatcher;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.InsufficientResourcesException;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Guice;\n\n@Test(groups = {\"unit\"})\npublic class CloudStackErrorHandlerTest {\n\n   @Test\n   public void test400MakesIllegalArgumentException() {\n      assertCodeMakes(\"GET\", URI.create(\"https://cloudstack.com/foo\"), 400, \"\", \"Bad Request\",\n         IllegalArgumentException.class);\n   }\n\n   @Test\n   public void test401MakesAuthorizationException() {\n      assertCodeMakes(\"GET\", URI.create(\"https://cloudstack.com/foo\"), 401, \"\", \"Unauthorized\",\n         AuthorizationException.class);\n   }\n\n   @Test\n   public void test404MakesResourceNotFoundException() {\n      assertCodeMakes(\"GET\", URI.create(\"https://cloudstack.com/foo\"), 404, \"\", \"Not Found\",\n         ResourceNotFoundException.class);\n   }\n\n   @Test\n   public void test405MakesIllegalArgumentException() {\n      assertCodeMakes(\"GET\", URI.create(\"https://cloudstack.com/foo\"), 405, \"\", \"Method Not Allowed\",\n         IllegalArgumentException.class);\n   }\n\n   @Test\n   public void test431MakesIllegalStateException() {\n      assertCodeMakes(\"GET\", URI.create(\"https://cloudstack.com/foo\"), 431, \"\", \"Method Not Allowed\",\n         IllegalStateException.class);\n   }\n\n   @Test\n   public void test431MakesResourceNotFoundExceptionOnDelete() {\n      assertCodeMakes(\n         \"GET\",\n         URI.create(\"https://api.ninefold.com/compute/v1.0/?response=json&command=deleteSSHKeyPair\"),\n         431,\n         \"\",\n         \"{ \\\"deletekeypairresponse\\\" : {\\\"errorcode\\\" : 431, \\\"errortext\\\" : \\\"A key pair with name 'adriancole-adapter-test-keypair' does not exist for account jclouds in domain id=457\\\"}  }\",\n         ResourceNotFoundException.class);\n   }\n\n   @Test\n   public void test409MakesIllegalStateException() {\n      assertCodeMakes(\"GET\", URI.create(\"https://cloudstack.com/foo\"), 409, \"\", \"Conflict\", IllegalStateException.class);\n   }\n\n   @Test\n   public void test531MakesAuthorizationException() {\n      assertCodeMakes(\"GET\", URI.create(\"https://cloudstack.com/foo\"), 531, \"\", \"Unauthorized\",\n         AuthorizationException.class);\n   }\n\n   @Test\n   void test534WithMaximumResourcesMakesInsufficientResourcesException() {\n      assertCodeMakes(\n         \"GET\",\n         URI.create(\"http://10.26.26.155:8080/client/api?response=json&command=deployVirtualMachine&zoneid=7dbc4787-ec2f-498d-95f0-848c8c81e5da&templateid=240937c8-d695-419c-9908-5c7b2a07e6f1&serviceofferingid=c376102e-b683-4d43-b583-4eeab4627e65&displayname=bousa-4&name=bousa-4\"),\n         534,\n         \"\",\n         \"{ \\\"createipforwardingruleresponse\\\" : {\\\"errorcode\\\" : 534, \\\"errortext\\\" : \\\"Maximum number of resources of type 'volume' for account name=jarcec in domain id=1 has been exceeded.\\\"}  }\",\n         InsufficientResourcesException.class);\n   }\n\n   @Test\n   void test537MakesIllegalStateException() {\n      assertCodeMakes(\n         \"GET\",\n         URI.create(\"http://10.26.26.155:8080/client/api?response=json&command=createIpForwardingRule&ipaddressid=37&startport=22&protocol=tcp\"),\n         537,\n         \"\",\n         \"{ \\\"createipforwardingruleresponse\\\" : {\\\"errorcode\\\" : 537, \\\"errortext\\\" : \\\"There is already firewall rule specified for the ip address id=37\\\"}  }\",\n         IllegalStateException.class);\n   }\n\n   private void assertCodeMakes(String method, URI uri, int statusCode, String message, String content,\n                                Class<? extends Exception> expected) {\n      assertCodeMakes(method, uri, statusCode, message, \"text/xml\", content, expected);\n   }\n\n   private void assertCodeMakes(String method, URI uri, int statusCode, String message, String contentType,\n                                String content, Class<? extends Exception> expected) {\n\n      CloudStackErrorHandler function = Guice.createInjector().getInstance(CloudStackErrorHandler.class);\n\n      HttpCommand command = createMock(HttpCommand.class);\n      HttpRequest request = HttpRequest.builder().method(method).endpoint(uri).build();\n      HttpResponse response = HttpResponse.builder().statusCode(statusCode).message(message).payload(content).build();\n      response.getPayload().getContentMetadata().setContentType(contentType);\n\n      expect(command.getCurrentRequest()).andReturn(request).atLeastOnce();\n      command.setException(classEq(expected));\n\n      replay(command);\n\n      function.handleError(command, response);\n\n      verify(command);\n   }\n\n   public static Exception classEq(final Class<? extends Exception> in) {\n      reportMatcher(new IArgumentMatcher() {\n\n         @Override\n         public void appendTo(StringBuffer buffer) {\n            buffer.append(\"classEq(\");\n            buffer.append(in);\n            buffer.append(\")\");\n         }\n\n         @Override\n         public boolean matches(Object arg) {\n            return arg.getClass() == in;\n         }\n\n      });\n      return null;\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/handlers/InvalidateSessionAndRetryOn401AndLogoutOnCloseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.handlers;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.expectLastCall;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.concurrent.atomic.AtomicInteger;\n\nimport org.easymock.IAnswer;\nimport org.jclouds.cloudstack.domain.LoginResponse;\nimport org.jclouds.cloudstack.features.SessionApi;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.io.Payloads;\nimport org.testng.annotations.Test;\n\nimport com.google.common.cache.LoadingCache;\n\n/**\n * Tests behavior of {@code InvalidateSessionAndRetryOn401AndLogoutOnClose} handler\n */\n@Test(groups = \"unit\", testName = \"InvalidateSessionAndRetryOn401AndLogoutOnCloseTest\")\npublic class InvalidateSessionAndRetryOn401AndLogoutOnCloseTest {\n\n   @SuppressWarnings(\"unchecked\")\n   @Test\n   public void test401ShouldRetryAndFailAfterFiveAttempts() {\n      HttpCommand command = createMock(HttpCommand.class);\n      SessionApi sessionClient = createMock(SessionApi.class);\n      LoadingCache<Credentials, LoginResponse> cache = createMock(LoadingCache.class);\n\n      cache.invalidateAll();\n      expectLastCall().anyTimes();\n\n      final AtomicInteger counter = new AtomicInteger();\n      expect(command.incrementFailureCount()).andAnswer(new IAnswer<Integer>() {\n         @Override\n         public Integer answer() throws Throwable {\n            return counter.incrementAndGet();\n         }\n      }).anyTimes();\n      expect(command.isReplayable()).andReturn(true).anyTimes();\n      expect(command.getFailureCount()).andAnswer(new IAnswer<Integer>() {\n         @Override\n         public Integer answer() throws Throwable {\n            return counter.get();\n         }\n      }).anyTimes();\n\n      replay(cache, command);\n\n      HttpResponse response = HttpResponse.builder().payload(\n         Payloads.newStringPayload(\"Not relevant\")).statusCode(401).build();\n\n      InvalidateSessionAndRetryOn401AndLogoutOnClose retry =\n         new InvalidateSessionAndRetryOn401AndLogoutOnClose(cache, sessionClient);\n\n      for (int i = 0; i < 5; i++) {\n         assertTrue(retry.shouldRetryRequest(command, response));\n      }\n      assertFalse(retry.shouldRetryRequest(command, response));\n\n      verify(cache, command);\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/internal/BaseCloudStackApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.internal;\n\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.get;\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static org.jclouds.cloudstack.domain.Account.Type.ADMIN;\nimport static org.jclouds.cloudstack.domain.Account.Type.DOMAIN_ADMIN;\nimport static org.jclouds.cloudstack.domain.Account.Type.USER;\nimport static org.jclouds.reflect.Reflection2.typeToken;\nimport static org.jclouds.util.Predicates2.retry;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.NoSuchElementException;\nimport java.util.Properties;\nimport java.util.Set;\nimport java.util.logging.Logger;\n\nimport org.jclouds.cloudstack.CloudStackApi;\nimport org.jclouds.cloudstack.CloudStackContext;\nimport org.jclouds.cloudstack.CloudStackDomainApi;\nimport org.jclouds.cloudstack.CloudStackGlobalApi;\nimport org.jclouds.cloudstack.domain.Account;\nimport org.jclouds.cloudstack.domain.Template;\nimport org.jclouds.cloudstack.domain.User;\nimport org.jclouds.cloudstack.domain.VirtualMachine;\nimport org.jclouds.cloudstack.features.AccountApi;\nimport org.jclouds.cloudstack.functions.ReuseOrAssociateNewPublicIPAddress;\nimport org.jclouds.cloudstack.options.ListTemplatesOptions;\nimport org.jclouds.cloudstack.predicates.CorrectHypervisorForZone;\nimport org.jclouds.cloudstack.predicates.JobComplete;\nimport org.jclouds.cloudstack.predicates.OSCategoryIn;\nimport org.jclouds.cloudstack.predicates.TemplatePredicates;\nimport org.jclouds.cloudstack.predicates.UserPredicates;\nimport org.jclouds.cloudstack.predicates.VirtualMachineDestroyed;\nimport org.jclouds.cloudstack.predicates.VirtualMachineRunning;\nimport org.jclouds.cloudstack.strategy.BlockUntilJobCompletesAndReturnResult;\nimport org.jclouds.compute.ComputeService;\nimport org.jclouds.compute.domain.ExecResponse;\nimport org.jclouds.compute.internal.BaseGenericComputeServiceContextLiveTest;\nimport org.jclouds.predicates.SocketOpen;\nimport org.jclouds.ssh.SshClient;\nimport org.jclouds.sshj.config.SshjSshClientModule;\nimport org.testng.SkipException;\nimport org.testng.annotations.BeforeGroups;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Predicates;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.net.HostAndPort;\nimport com.google.common.reflect.TypeToken;\nimport com.google.inject.Injector;\nimport com.google.inject.Module;\n\npublic class BaseCloudStackApiLiveTest extends BaseGenericComputeServiceContextLiveTest<CloudStackContext> {\n   protected String domainAdminIdentity;\n   protected String domainAdminCredential;\n   protected String globalAdminIdentity;\n   protected String globalAdminCredential;\n\n   public BaseCloudStackApiLiveTest() {\n      provider = \"cloudstack\";\n   }\n   \n   @Override\n   protected TypeToken<CloudStackContext> viewType() {\n      return typeToken(CloudStackContext.class);\n   }\n   \n   @Override\n   protected Properties setupProperties() {\n      Properties overrides = super.setupProperties();\n      domainAdminIdentity = setIfTestSystemPropertyPresent(overrides, provider + \".domainAdminIdentity\");\n      domainAdminCredential = setIfTestSystemPropertyPresent(overrides, provider + \".domainAdminCredential\");\n      globalAdminIdentity = setIfTestSystemPropertyPresent(overrides, provider + \".globalAdminIdentity\");\n      globalAdminCredential = setIfTestSystemPropertyPresent(overrides,  provider + \".globalAdminCredential\");\n      return overrides;\n   }\n\n   protected Properties setupDomainAdminProperties() {\n      if (domainAdminIdentity != null && domainAdminCredential != null) {\n         Properties overrides = setupProperties();\n         overrides.setProperty(provider + \".identity\", domainAdminIdentity);\n         overrides.setProperty(provider + \".credential\", domainAdminCredential);\n         return overrides;\n      } else {\n         return null;\n      }\n   }\n\n   protected Properties setupGlobalAdminProperties() {\n      if (globalAdminIdentity != null && globalAdminCredential != null) {\n         Properties overrides = setupProperties();\n         overrides.setProperty(provider + \".identity\", globalAdminIdentity);\n         overrides.setProperty(provider + \".credential\", globalAdminCredential);\n         return overrides;\n      } else {\n         return null;\n      }\n   }\n\n   public static String defaultTemplateOrPreferredInZone(String defaultTemplate, CloudStackApi client, String zoneId) {\n      String templateId = defaultTemplate != null ? defaultTemplate : getTemplateForZone(client, zoneId);\n      return templateId;\n   }\n\n   public static String getTemplateForZone(CloudStackApi client, String zoneId) {\n      // TODO enum, as this is way too easy to mess up.\n      Set<String> acceptableCategories = ImmutableSet.of(\"Ubuntu\", \"CentOS\");\n\n      final Predicate<Template> hypervisorPredicate = new CorrectHypervisorForZone(client).apply(zoneId);\n      final Predicate<Template> osTypePredicate = new OSCategoryIn(client).apply(acceptableCategories);\n\n      @SuppressWarnings(\"unchecked\")\n      Predicate<Template> templatePredicate = Predicates.<Template> and(TemplatePredicates.isReady(),\n            hypervisorPredicate, osTypePredicate);\n      Iterable<Template> templates = filter(\n            client.getTemplateApi().listTemplates(ListTemplatesOptions.Builder.zoneId(zoneId)), templatePredicate);\n      if (Iterables.any(templates, TemplatePredicates.isPasswordEnabled())) {\n         templates = filter(templates, TemplatePredicates.isPasswordEnabled());\n      }\n      if (Iterables.size(templates) == 0) {\n         throw new NoSuchElementException(templatePredicate.toString());\n      }\n      String templateId = get(templates, 0).getId();\n      return templateId;\n   }\n\n   protected String prefix = System.getProperty(\"user.name\");\n\n   protected ComputeService computeClient;\n   protected CloudStackContext cloudStackContext;\n   protected CloudStackApi client;\n   protected CloudStackApi adminClient;\n   protected User user;\n\n   protected Predicate<HostAndPort> socketTester;\n   protected Predicate<String> jobComplete;\n   protected Predicate<String> adminJobComplete;\n   protected Predicate<VirtualMachine> virtualMachineRunning;\n   protected Predicate<VirtualMachine> adminVirtualMachineRunning;\n   protected Predicate<VirtualMachine> virtualMachineDestroyed;\n   protected Predicate<VirtualMachine> adminVirtualMachineDestroyed;\n   protected SshClient.Factory sshFactory;\n\n   protected Injector injector;\n\n   protected ReuseOrAssociateNewPublicIPAddress reuseOrAssociate;\n\n   protected boolean domainAdminEnabled;\n   protected CloudStackContext domainAdminComputeContext;\n   protected CloudStackDomainApi domainAdminClient;\n   protected User domainAdminUser;\n\n   protected boolean globalAdminEnabled;\n   protected CloudStackContext globalAdminComputeContext;\n   protected CloudStackGlobalApi globalAdminClient;\n   protected User globalAdminUser;\n   \n   protected void checkSSH(HostAndPort socket) {\n      socketTester.apply(socket);\n      SshClient client = sshFactory.create(socket, loginCredentials);\n      try {\n         client.connect();\n         ExecResponse exec = client.exec(\"echo hello\");\n         System.out.println(exec);\n         assertEquals(exec.getOutput().trim(), \"hello\");\n      } finally {\n         if (client != null)\n            client.disconnect();\n      }\n   }\n\n   @BeforeGroups(groups = { \"integration\", \"live\" })\n   @Override\n   public void setupContext() {\n      super.setupContext();\n      computeClient = view.getComputeService();\n      cloudStackContext = CloudStackContext.class.cast(view);\n      client = cloudStackContext.getApi();\n      user = verifyCurrentUserIsOfType(identity, client.getAccountApi(), USER);\n\n      domainAdminEnabled = setupDomainAdminProperties() != null;\n      if (domainAdminEnabled) {\n         domainAdminComputeContext = createView(setupDomainAdminProperties(), setupModules());\n         domainAdminClient = domainAdminComputeContext.getDomainApi();\n         domainAdminUser = verifyCurrentUserIsOfType(domainAdminIdentity, domainAdminClient.getAccountApi(),\n               DOMAIN_ADMIN);\n         adminClient = domainAdminClient;\n      }\n\n      globalAdminEnabled = setupGlobalAdminProperties() != null;\n      if (globalAdminEnabled) {\n         globalAdminComputeContext = createView(setupGlobalAdminProperties(), setupModules());\n         globalAdminClient = globalAdminComputeContext.getGlobalApi();\n         globalAdminUser = verifyCurrentUserIsOfType(globalAdminIdentity, globalAdminClient.getAccountApi(), ADMIN);\n         adminClient = globalAdminClient;\n      }\n\n      injector = cloudStackContext.utils().injector();\n      sshFactory = injector.getInstance(SshClient.Factory.class);\n      SocketOpen socketOpen = context.utils().injector().getInstance(SocketOpen.class);\n      socketTester = retry(socketOpen, 180, 1, 1, SECONDS);\n      injector.injectMembers(socketTester);\n\n      jobComplete = retry(new JobComplete(client), 1200, 1, 5, SECONDS);\n      injector.injectMembers(jobComplete);\n      adminJobComplete = retry(new JobComplete(adminClient), 1200, 1, 5, SECONDS);\n      injector.injectMembers(adminJobComplete);\n      virtualMachineRunning = retry(new VirtualMachineRunning(client), 600, 5, 5, SECONDS);\n      injector.injectMembers(virtualMachineRunning);\n      adminVirtualMachineRunning = retry(new VirtualMachineRunning(adminClient), 600, 5, 5, SECONDS);\n      injector.injectMembers(adminVirtualMachineRunning);\n      virtualMachineDestroyed = retry(new VirtualMachineDestroyed(client), 600, 5, 5, SECONDS);\n      injector.injectMembers(virtualMachineDestroyed);\n      adminVirtualMachineDestroyed = retry(new VirtualMachineDestroyed(adminClient), 600, 5, 5, SECONDS);\n      injector.injectMembers(adminVirtualMachineDestroyed);\n      reuseOrAssociate = new ReuseOrAssociateNewPublicIPAddress(client, new BlockUntilJobCompletesAndReturnResult(\n            client, jobComplete));\n      injector.injectMembers(reuseOrAssociate);\n   }\n\n   @Override\n   protected Module getSshModule() {\n      return new SshjSshClientModule();\n   }\n   \n   private static User verifyCurrentUserIsOfType(String identity, AccountApi accountClient, Account.Type type) {\n      Iterable<User> users = Iterables.concat(accountClient.listAccounts());\n      Predicate<User> apiKeyMatches = UserPredicates.apiKeyEquals(identity);\n      User currentUser;\n      try {\n         currentUser = Iterables.find(users, apiKeyMatches);\n      } catch (NoSuchElementException e) {\n         throw new NoSuchElementException(String.format(\"none of the following users match %s: %s\", apiKeyMatches,\n               users));\n      }\n\n      if (currentUser.getAccountType() != type) {\n         Logger.getAnonymousLogger().warning(\n               String.format(\"Expecting an user with type %s. Got: %s\", type.toString(), currentUser.toString()));\n      }\n      return currentUser;\n   }\n\n   protected void skipIfNotDomainAdmin() {\n      if (!domainAdminEnabled) {\n         throw new SkipException(\"Test cannot run without domain admin identity and credentials\");\n      }\n   }\n\n   protected void skipIfNotGlobalAdmin() {\n      if (!globalAdminEnabled) {\n         throw new SkipException(\"Test cannot run without global admin identity and credentials\");\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/internal/BaseCloudStackApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.internal;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.cloudstack.CloudStackApiMetadata;\nimport org.jclouds.cloudstack.config.CloudStackHttpApiModule;\nimport org.jclouds.cloudstack.filters.QuerySigner;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.providers.AnonymousProviderMetadata;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.internal.BaseRestAnnotationProcessingTest;\n\nimport com.google.inject.Module;\n\npublic abstract class BaseCloudStackApiTest<T> extends BaseRestAnnotationProcessingTest<T> {\n\n   @ConfiguresHttpApi\n   public static class CloudStackHttpApiModuleExtension extends CloudStackHttpApiModule {\n\n   }\n\n   @Override\n   protected void checkFilters(HttpRequest request) {\n      assertEquals(request.getFilters().size(), 1);\n      assertEquals(request.getFilters().get(0).getClass(), QuerySigner.class);\n   }\n\n   @Override\n   protected Module createModule() {\n      return new CloudStackHttpApiModuleExtension();\n   }\n\n   @Override\n   protected ProviderMetadata createProviderMetadata() {\n      return  AnonymousProviderMetadata.forApiWithEndpoint(new CloudStackApiMetadata(),\n            \"http://localhost:8080/client/api\");\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/internal/BaseCloudStackComputeServiceContextExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.internal;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\n\n\n/**\n * Base class for writing CloudStack Expect tests with the ComputeService\n * abstraction\n */\npublic abstract class BaseCloudStackComputeServiceContextExpectTest<T> extends BaseCloudStackExpectTest<T> {\n   \n   public BaseCloudStackComputeServiceContextExpectTest() {\n      // to match the api key name in listaccountsresponse.json\n      identity = \"APIKEY\";\n   }\n   \n   protected final HttpRequest listTemplates = HttpRequest.builder().method(\"GET\")\n      .endpoint(\"http://localhost:8080/client/api\")\n      .addQueryParam(\"response\", \"json\")\n      .addQueryParam(\"command\", \"listTemplates\")\n      .addQueryParam(\"listAll\", \"true\")\n      .addQueryParam(\"templatefilter\", \"executable\")\n      .addQueryParam(\"apiKey\", \"APIKEY\")\n      .addQueryParam(\"signature\", \"Xk6lF/v3SbhrxTKqaC2IWoBPKHo=\")\n      .addHeader(\"Accept\", \"application/json\")\n      .build();\n\n   //TODO: update or add new resource files to have more recent data, ex. ubuntu template\n   protected final HttpResponse listTemplatesResponse = HttpResponse.builder().statusCode(200)\n      .payload(payloadFromResource(\"/listtemplatesresponse.json\"))\n      .build();\n\n   protected final HttpRequest listProjects = HttpRequest.builder().method(\"GET\")\n           .endpoint(\"http://localhost:8080/client/api\")\n           .addQueryParam(\"response\", \"json\")\n           .addQueryParam(\"command\", \"listProjects\")\n           .addQueryParam(\"listAll\", \"true\")\n           .addQueryParam(\"account\", \"jclouds\")\n           .addQueryParam(\"domainid\", \"457\")\n           .addQueryParam(\"apiKey\", \"APIKEY\")\n           .addQueryParam(\"signature\", \"yAx1XbtjeEhdBQCNP0OLyWWAFCw=\")\n           .addHeader(\"Accept\", \"application/json\")\n           .build();\n\n   protected final HttpResponse listProjectsResponse = HttpResponse.builder().statusCode(200)\n           .build();\n\n   protected final HttpRequest listOsTypes = HttpRequest.builder().method(\"GET\")\n      .endpoint(\"http://localhost:8080/client/api\")\n      .addQueryParam(\"response\", \"json\")\n      .addQueryParam(\"command\", \"listOsTypes\")\n      .addQueryParam(\"listAll\", \"true\")\n      .addQueryParam(\"apiKey\", \"APIKEY\")\n      .addQueryParam(\"signature\", \"8BsE8MsOAhUzo1Q4Y3UD/e96u84=\")\n      .addHeader(\"Accept\", \"application/json\")\n      .build();\n\n   protected final HttpResponse listOsTypesResponse = HttpResponse.builder().statusCode(200)\n      .payload(payloadFromResource(\"/listostypesresponse.json\"))\n      .build();\n   \n   protected final HttpRequest listOsCategories = HttpRequest.builder().method(\"GET\")\n      .endpoint(\"http://localhost:8080/client/api\")\n      .addQueryParam(\"response\", \"json\")\n      .addQueryParam(\"command\", \"listOsCategories\")\n      .addQueryParam(\"listAll\", \"true\")\n      .addQueryParam(\"apiKey\", \"APIKEY\")\n      .addQueryParam(\"signature\", \"OojW4ssh/RQ3CubAzXue4svlofM=\")\n//      .addHeader(\"Accept\", \"application/json\") //TODO: why are we not passing this?\n      .build();\n\n   protected final HttpResponse listOsCategoriesResponse = HttpResponse.builder().statusCode(200)\n      .payload(payloadFromResource(\"/listoscategoriesresponse.json\"))\n      .build();\n   \n   protected final HttpRequest listZones = HttpRequest.builder().method(\"GET\")\n      .endpoint(\"http://localhost:8080/client/api\")\n      .addQueryParam(\"response\", \"json\")\n      .addQueryParam(\"command\", \"listZones\")\n      .addQueryParam(\"listAll\", \"true\")\n      .addQueryParam(\"apiKey\", \"APIKEY\")\n      .addQueryParam(\"signature\", \"GTUgn/LHDioJRq48kurOdCAYueo=\")\n      .addHeader(\"Accept\", \"application/json\")\n      .build();\n\n   protected final HttpResponse listZonesResponse = HttpResponse.builder().statusCode(200)\n      .payload(payloadFromResource(\"/listzonesresponse.json\"))\n      .build();\n\n   protected final HttpRequest listServiceOfferings = HttpRequest.builder().method(\"GET\")\n      .endpoint(\"http://localhost:8080/client/api\")\n      .addQueryParam(\"response\", \"json\")\n      .addQueryParam(\"command\", \"listServiceOfferings\")\n      .addQueryParam(\"listAll\", \"true\")\n      .addQueryParam(\"apiKey\", \"APIKEY\")\n      .addQueryParam(\"signature\", \"jUien8oeEan7bjKKQbBlzvFuMjw=\")\n      .addHeader(\"Accept\", \"application/json\")\n      .build();\n\n   protected final HttpResponse listServiceOfferingsResponse = HttpResponse.builder().statusCode(200)\n      .payload(payloadFromResource(\"/listserviceofferingsresponse.json\"))\n      .build();\n\n   protected final HttpRequest listAccounts = HttpRequest.builder().method(\"GET\")\n      .endpoint(\"http://localhost:8080/client/api\")\n      .addQueryParam(\"response\", \"json\")\n      .addQueryParam(\"command\", \"listAccounts\")\n      .addQueryParam(\"listAll\", \"true\")\n      .addQueryParam(\"apiKey\", \"APIKEY\")\n      .addQueryParam(\"signature\", \"E4wuKXCkioaNIiL8hL8FD9K5K2c=\")\n      .addHeader(\"Accept\", \"application/json\")\n      .build();\n\n   protected final HttpResponse listAccountsResponse = HttpResponse.builder().statusCode(200)\n      .payload(payloadFromResource(\"/listaccountsresponse.json\"))\n      .build();\n   \n   protected final HttpRequest listNetworks = HttpRequest.builder().method(\"GET\")\n      .endpoint(\"http://localhost:8080/client/api\")\n      .addQueryParam(\"response\", \"json\")\n      .addQueryParam(\"command\", \"listNetworks\")\n      .addQueryParam(\"listAll\", \"true\")\n      .addQueryParam(\"account\", \"jclouds\") // account and domain came from above\n      .addQueryParam(\"domainid\", \"457\")\n      .addQueryParam(\"apiKey\", \"APIKEY\")\n      .addQueryParam(\"signature\", \"FDiGGBiG/sVj0k6DmZIgMNU8SqI=\")\n      .addHeader(\"Accept\", \"application/json\")\n      .build();\n\n   protected final HttpResponse listNetworksResponse = HttpResponse.builder().statusCode(200)\n      .payload(payloadFromResource(\"/listnetworksresponse.json\"))\n      .build();   \n   \n   protected final HttpResponse listNetworksWithSecurityGroupsResponse = HttpResponse.builder().statusCode(200)\n      .payload(payloadFromResource(\"/listnetworksresponse-2.json\"))\n      .build();   \n\n   protected final HttpRequest getZone = HttpRequest.builder().method(\"GET\")\n      .endpoint(\"http://localhost:8080/client/api\")\n      .addQueryParam(\"response\", \"json\")\n      .addQueryParam(\"command\", \"listZones\")\n      .addQueryParam(\"listAll\", \"true\")\n      .addQueryParam(\"id\", \"1\")\n      .addQueryParam(\"apiKey\", \"APIKEY\")\n      .addQueryParam(\"signature\", \"q5GMO9iUYIFs5S58DdAuYAy8yu0=\")\n      .addHeader(\"Accept\", \"application/json\")\n      .build();\n\n   protected final HttpResponse getZoneResponse = HttpResponse.builder().statusCode(200)\n      .payload(payloadFromResource(\"/getzoneresponse.json\"))\n      .build();\n\n   protected final HttpRequest getZoneWithSecurityGroups = HttpRequest.builder().method(\"GET\")\n      .endpoint(\"http://localhost:8080/client/api\")\n      .addQueryParam(\"response\", \"json\")\n      .addQueryParam(\"command\", \"listZones\")\n      .addQueryParam(\"listAll\", \"true\")\n      .addQueryParam(\"id\", \"2\")\n      .addQueryParam(\"apiKey\", \"APIKEY\")\n      .addQueryParam(\"signature\", \"FnYX25207fVLLRz5GhOfRrWuUek=\")\n      .addHeader(\"Accept\", \"application/json\")\n      .build();\n\n   protected final HttpResponse getZoneWithSecurityGroupsResponse = HttpResponse.builder().statusCode(200)\n      .payload(payloadFromResource(\"/getzoneresponse-2.json\"))\n      .build();\n   \n   protected final HttpRequest listCapabilities = HttpRequest.builder().method(\"GET\")\n      .endpoint(\"http://localhost:8080/client/api\")\n      .addQueryParam(\"response\", \"json\")\n      .addQueryParam(\"listAll\", \"true\")\n      .addQueryParam(\"command\", \"listCapabilities\")\n      .addQueryParam(\"apiKey\", \"APIKEY\")\n      .addQueryParam(\"signature\", \"vVdhtet/zG59FXgkYkAzEQQ4q1o=\")\n      .addHeader(\"Accept\", \"application/json\")\n      .build();\n\n   protected final HttpResponse listCapabilitiesResponse = HttpResponse.builder().statusCode(200)\n      .payload(payloadFromResource(\"/listcapabilitiesresponse.json\"))\n      .build();   \n         \n   protected final HttpRequest getSecurityGroup = HttpRequest.builder().method(\"GET\")\n      .endpoint(\"http://localhost:8080/client/api\")\n      .addQueryParam(\"response\", \"json\")\n      .addQueryParam(\"command\", \"listSecurityGroups\")\n      .addQueryParam(\"listAll\", \"true\")\n      .addQueryParam(\"securitygroupname\", \"jclouds-test\")\n      .addQueryParam(\"apiKey\", \"APIKEY\")\n      .addQueryParam(\"signature\", \"zGp2rfHY6fBIGkgODRxyNzFfPFI=\")\n      .addHeader(\"Accept\", \"application/json\")\n      .build();\n\n   protected final HttpResponse getSecurityGroupResponse = HttpResponse.builder().statusCode(200)\n      .payload(payloadFromResource(\"/getsecuritygroupresponse.json\"))\n      .build();   \n\n   protected final HttpRequest createSecurityGroup = HttpRequest.builder().method(\"GET\")\n      .endpoint(\"http://localhost:8080/client/api\")\n      .addQueryParam(\"response\", \"json\")\n      .addQueryParam(\"command\", \"createSecurityGroup\")\n      .addQueryParam(\"name\", \"jclouds-test\")\n      .addQueryParam(\"apiKey\", \"APIKEY\")\n      .addQueryParam(\"signature\", \"BdgmqGsvjPmP4PxsEKEpq6buwuA=\")\n      .addHeader(\"Accept\", \"application/json\")\n      .build();\n\n   protected final HttpResponse createSecurityGroupResponse = HttpResponse.builder().statusCode(200)\n      .payload(payloadFromResource(\"/createsecuritygroupresponse.json\"))\n      .build();   \n\n   protected final HttpRequest authorizeIngress = HttpRequest.builder().method(\"GET\")\n      .endpoint(\"http://localhost:8080/client/api\")\n      .addQueryParam(\"response\", \"json\")\n      .addQueryParam(\"command\", \"authorizeSecurityGroupIngress\")\n      .addQueryParam(\"securitygroupid\", \"30\")\n      .addQueryParam(\"protocol\", \"TCP\")\n      .addQueryParam(\"startport\", \"22\")\n      .addQueryParam(\"endport\", \"22\")\n      .addQueryParam(\"cidrlist\", \"0.0.0.0/0\")\n      .addQueryParam(\"apiKey\", \"APIKEY\")\n      .addQueryParam(\"signature\", \"GVtXzAl/Q7z4wnvKEHtdV0lxv2o=\")\n      .addHeader(\"Accept\", \"application/json\")\n      .build();\n\n   protected final HttpResponse authorizeIngressResponse = HttpResponse.builder().statusCode(200)\n      .payload(payloadFromResource(\"/authorizesecuritygroupingressresponse.json\"))\n      .build();   \n\n   protected final HttpRequest createSSHKeyPair = HttpRequest.builder().method(\"GET\")\n      .endpoint(\"http://localhost:8080/client/api\")\n      .addQueryParam(\"response\", \"json\")\n      .addQueryParam(\"command\", \"createSSHKeyPair\")\n      .addQueryParam(\"name\", \"jclouds-test\")\n      .addQueryParam(\"apiKey\", \"APIKEY\")\n      .addQueryParam(\"signature\", \"er6YjvUjPFwxy/x/aAVNW9Z8yo8=\")\n      .addHeader(\"Accept\", \"application/json\")\n      .build();\n\n   protected final HttpResponse createSSHKeyPairResponse = HttpResponse.builder().statusCode(200)\n      .payload(payloadFromResource(\"/createsshkeypairresponse-2.json\"))\n      .build();   \n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/internal/BaseCloudStackExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.internal;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.hash.Hashing.md5;\nimport static com.google.common.io.BaseEncoding.base16;\nimport static org.jclouds.util.Strings2.urlEncode;\n\nimport java.util.Properties;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.cloudstack.CloudStackApiMetadata;\nimport org.jclouds.cloudstack.CloudStackContext;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rest.internal.BaseRestApiExpectTest;\n\nimport com.google.common.base.Function;\nimport com.google.inject.Module;\n\n/**\n * Base class for writing CloudStack Rest Client Expect tests\n */\npublic abstract class BaseCloudStackExpectTest<S> extends BaseRestApiExpectTest<S> {\n\n   public BaseCloudStackExpectTest() {\n      provider = \"cloudstack\";\n   }\n   \n   @Override\n   protected ApiMetadata createApiMetadata() {\n      return new CloudStackApiMetadata();\n   }\n\n   @Override\n   public S createClient(Function<HttpRequest, HttpResponse> fn, Module module, Properties props) {\n      return clientFrom(createInjector(fn, module, props).getInstance(CloudStackContext.class));\n   }\n\n   protected abstract S clientFrom(CloudStackContext context);\n\n   protected final HttpRequest login = HttpRequest.builder().method(\"GET\")\n      .endpoint(\"http://localhost:8080/client/api\")\n      .addQueryParam(\"response\", \"json\")\n      .addQueryParam(\"command\", \"login\")\n      .addQueryParam(\"username\", \"identity\")\n      .addQueryParam(\"domain\", \"\")\n      .addQueryParam(\"password\", base16().lowerCase().encode(md5().hashString(\"credential\", UTF_8).asBytes()))\n      .addHeader(\"Accept\", \"application/json\")\n      .build();\n\n   protected final String jSessionId = \"90DD65D13AEAA590ECCA312D150B9F6D\";\n   protected final String sessionKey = \"uYT4/MNiglgAKiZRQkvV8QP8gn0=\";\n   \n   protected final HttpResponse loginResponse = HttpResponse.builder().statusCode(200)\n      .addHeader(\"Set-Cookie\", \"JSESSIONID=\" + jSessionId + \"; Path=/client\")\n      .payload(payloadFromResource(\"/loginresponse.json\"))\n      .build();\n\n   protected final HttpRequest logout = HttpRequest.builder().method(\"GET\")\n      .endpoint(\"http://localhost:8080/client/api\")\n      .addQueryParam(\"response\", \"json\")\n      .addQueryParam(\"command\", \"logout\")\n      .addQueryParam(\"sessionkey\", urlEncode(sessionKey))\n      .build();\n   \n   protected final HttpResponse logoutResponse = HttpResponse.builder().statusCode(200).build();\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/loaders/LoginWithPasswordCredentialsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.loaders;\n\nimport static org.easymock.EasyMock.anyObject;\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.eq;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\n\nimport org.jclouds.cloudstack.domain.LoginResponse;\nimport org.jclouds.cloudstack.features.SessionApi;\nimport org.jclouds.domain.Credentials;\nimport org.testng.annotations.Test;\n\npublic class LoginWithPasswordCredentialsTest {\n\n   /**\n    * This test is different from the single domainname test as it included testing on how the \n    * domainname is rebuild. It is here to prove that this particular test fails on systems\n    * with a different path separator.\n    */\n   @Test\n   public void testWithDoubleDomainname() {\n      LoginResponse response = createMock(LoginResponse.class);\n      SessionApi client = createMock(SessionApi.class);\n\n      expect(client.loginUserInDomainWithHashOfPassword(eq(\"User\"), eq(\"Test/Domain\"), (String) anyObject())).andReturn(response);\n      replay(client);\n\n      LoginWithPasswordCredentials obj = new LoginWithPasswordCredentials(client);\n      Credentials cred = new Credentials(\"Test/Domain/User\", \"koffiedik\");\n\n      obj.load(cred);\n   }\n\n   @Test\n   public void testWithSingleDomainname() {\n      LoginResponse response = createMock(LoginResponse.class);\n      SessionApi client = createMock(SessionApi.class);\n\n      expect(client.loginUserInDomainWithHashOfPassword(eq(\"User\"), eq(\"Domain\"), (String) anyObject())).andReturn(response);\n      replay(client);\n\n      LoginWithPasswordCredentials obj = new LoginWithPasswordCredentials(client);\n      Credentials cred = new Credentials(\"Domain/User\", \"koffiedik\");\n\n      obj.load(cred);\n   }\n\n   @Test\n   public void testWithNoDomainname() {\n       LoginResponse response = createMock(LoginResponse.class);\n       SessionApi client = createMock(SessionApi.class);\n\n       expect(client.loginUserInDomainWithHashOfPassword(eq(\"User\"), eq(\"\"), (String) anyObject())).andReturn(response);\n       replay(client);\n\n       LoginWithPasswordCredentials obj = new LoginWithPasswordCredentials(client);\n       Credentials cred = new Credentials(\"User\", \"koffiedik\");\n\n       obj.load(cred);\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/AddClusterOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.AddClusterOptions.Builder.allocationState;\nimport static org.jclouds.cloudstack.options.AddClusterOptions.Builder.password;\nimport static org.jclouds.cloudstack.options.AddClusterOptions.Builder.podId;\nimport static org.jclouds.cloudstack.options.AddClusterOptions.Builder.url;\nimport static org.jclouds.cloudstack.options.AddClusterOptions.Builder.username;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.cloudstack.domain.AllocationState;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tests behavior of {@code AddClusterOptions}\n */\n@Test(groups = \"unit\")\npublic class AddClusterOptionsTest {\n\n   public void testAllocationState() {\n      AddClusterOptions options = new AddClusterOptions().allocationState(AllocationState.ENABLED);\n      assertEquals(ImmutableList.of(\"Enabled\"), options.buildQueryParameters().get(\"allocationstate\"));\n   }\n\n   public void testAllocationStateStatic() {\n      AddClusterOptions options = allocationState(AllocationState.ENABLED);\n      assertEquals(ImmutableList.of(\"Enabled\"), options.buildQueryParameters().get(\"allocationstate\"));\n   }\n\n   public void testPassword() {\n      AddClusterOptions options = new AddClusterOptions().password(\"sekrit\");\n      assertEquals(ImmutableList.of(\"sekrit\"), options.buildQueryParameters().get(\"password\"));\n   }\n\n   public void testPasswordStatic() {\n      AddClusterOptions options = password(\"sekrit\");\n      assertEquals(ImmutableList.of(\"sekrit\"), options.buildQueryParameters().get(\"password\"));\n   }\n\n   public void testPodId() {\n      AddClusterOptions options = new AddClusterOptions().podId(\"42\");\n      assertEquals(ImmutableList.of(\"42\"), options.buildQueryParameters().get(\"podid\"));\n   }\n\n   public void testPodIdStatic() {\n      AddClusterOptions options = podId(\"42\");\n      assertEquals(ImmutableList.of(\"42\"), options.buildQueryParameters().get(\"podid\"));\n   }\n\n   public void testUrl() {\n      AddClusterOptions options = new AddClusterOptions().url(\"http://example.com\");\n      assertEquals(ImmutableList.of(\"http://example.com\"), options.buildQueryParameters().get(\"url\"));\n   }\n\n   public void testUrlStatic() {\n      AddClusterOptions options = url(\"http://example.com\");\n      assertEquals(ImmutableList.of(\"http://example.com\"), options.buildQueryParameters().get(\"url\"));\n   }\n\n   public void testUsername() {\n      AddClusterOptions options = new AddClusterOptions().username(\"fred\");\n      assertEquals(ImmutableList.of(\"fred\"), options.buildQueryParameters().get(\"username\"));\n   }\n\n   public void testUsernameStatic() {\n      AddClusterOptions options = username(\"fred\");\n      assertEquals(ImmutableList.of(\"fred\"), options.buildQueryParameters().get(\"username\"));\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/AddHostOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.AddHostOptions.Builder.allocationState;\nimport static org.jclouds.cloudstack.options.AddHostOptions.Builder.clusterId;\nimport static org.jclouds.cloudstack.options.AddHostOptions.Builder.clusterName;\nimport static org.jclouds.cloudstack.options.AddHostOptions.Builder.hostTags;\nimport static org.jclouds.cloudstack.options.AddHostOptions.Builder.podId;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.cloudstack.domain.AllocationState;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code AddHostOptions}\n */\n@Test(groups = \"unit\")\npublic class AddHostOptionsTest {\n\n   public void testAllocationState() {\n      AddHostOptions options = new AddHostOptions().allocationState(AllocationState.ENABLED);\n      assertEquals(ImmutableList.of(\"Enabled\"), options.buildQueryParameters().get(\"allocationstate\"));\n   }\n\n   public void testAllocationStateStatic() {\n      AddHostOptions options = allocationState(AllocationState.ENABLED);\n      assertEquals(ImmutableList.of(\"Enabled\"), options.buildQueryParameters().get(\"allocationstate\"));\n   }\n\n   public void testClusterId() {\n      AddHostOptions options = new AddHostOptions().clusterId(\"42\");\n      assertEquals(ImmutableList.of(\"42\"), options.buildQueryParameters().get(\"clusterid\"));\n   }\n\n   public void testClusterIdStatic() {\n      AddHostOptions options = clusterId(\"42\");\n      assertEquals(ImmutableList.of(\"42\"), options.buildQueryParameters().get(\"clusterid\"));\n   }\n\n   public void testClusterName() {\n      AddHostOptions options = new AddHostOptions().clusterName(\"Cluster Name\");\n      assertEquals(ImmutableList.of(\"Cluster Name\"), options.buildQueryParameters().get(\"clustername\"));\n   }\n\n   public void testClusterNameStatic() {\n      AddHostOptions options = clusterName(\"Cluster Name\");\n      assertEquals(ImmutableList.of(\"Cluster Name\"), options.buildQueryParameters().get(\"clustername\"));\n   }\n\n   public void testHostTags() {\n      AddHostOptions options = new AddHostOptions().hostTags(ImmutableSet.<String>of(\"foo\", \"bar\", \"baz\"));\n      assertEquals(ImmutableList.of(\"foo,bar,baz\"), options.buildQueryParameters().get(\"hosttags\"));\n   }\n\n   public void testHostTagsStatic() {\n      AddHostOptions options = hostTags(ImmutableSet.<String>of(\"foo\", \"bar\", \"baz\"));\n      assertEquals(ImmutableList.of(\"foo,bar,baz\"), options.buildQueryParameters().get(\"hosttags\"));\n   }\n\n   public void testPodId() {\n      AddHostOptions options = new AddHostOptions().podId(\"42\");\n      assertEquals(ImmutableList.of(\"42\"), options.buildQueryParameters().get(\"podid\"));\n   }\n\n   public void testPodIdStatic() {\n      AddHostOptions options = podId(\"42\");\n      assertEquals(ImmutableList.of(\"42\"), options.buildQueryParameters().get(\"podid\"));\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/AddSecondaryStorageOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.AddSecondaryStorageOptions.Builder.zoneId;\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tests behavior of {@code AddSecondaryStorageOptions}\n */\n@Test(groups = \"unit\")\npublic class AddSecondaryStorageOptionsTest {\n\n   public void testZoneId() {\n      AddSecondaryStorageOptions options = new AddSecondaryStorageOptions().zoneId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"zoneid\"));\n   }\n\n   public void testZoneIdStatic() {\n      AddSecondaryStorageOptions options = zoneId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"zoneid\"));\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/AssociateIPAddressOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.AssociateIPAddressOptions.Builder.accountInDomain;\nimport static org.jclouds.cloudstack.options.AssociateIPAddressOptions.Builder.networkId;\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tests behavior of {@code AssociateIPAddressOptions}\n */\n@Test(groups = \"unit\")\npublic class AssociateIPAddressOptionsTest {\n\n   public void testAccountInDomainId() {\n      AssociateIPAddressOptions options = new AssociateIPAddressOptions().accountInDomain(\"adrian\", \"6\");\n      assertEquals(ImmutableList.of(\"adrian\"), options.buildQueryParameters().get(\"account\"));\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testAccountInDomainIdStatic() {\n      AssociateIPAddressOptions options = accountInDomain(\"adrian\", \"6\");\n      assertEquals(ImmutableList.of(\"adrian\"), options.buildQueryParameters().get(\"account\"));\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testNetworkId() {\n      AssociateIPAddressOptions options = new AssociateIPAddressOptions().networkId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"networkid\"));\n   }\n\n   public void testNetworkIdStatic() {\n      AssociateIPAddressOptions options = networkId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"networkid\"));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/CreateAccountOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.CreateAccountOptions.Builder.account;\nimport static org.jclouds.cloudstack.options.CreateAccountOptions.Builder.domainId;\nimport static org.jclouds.cloudstack.options.CreateAccountOptions.Builder.networkDomain;\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code CreateAccountOptions}\n */\n@Test(groups = \"unit\")\npublic class CreateAccountOptionsTest {\n\n   public void testNetworkDomain() {\n      CreateAccountOptions options = new CreateAccountOptions().networkDomain(\"net\");\n      assertEquals(ImmutableSet.of(\"net\"), options.buildQueryParameters().get(\"networkdomain\"));\n   }\n\n   public void testNetworkDomainStatic() {\n      CreateAccountOptions options = networkDomain(\"net\");\n      assertEquals(ImmutableSet.of(\"net\"), options.buildQueryParameters().get(\"networkdomain\"));\n   }\n\n   public void testAccount() {\n      CreateAccountOptions options = new CreateAccountOptions().account(\"accountName\");\n      assertEquals(ImmutableSet.of(\"accountName\"), options.buildQueryParameters().get(\"account\"));\n   }\n\n   public void testAccountStatic() {\n      CreateAccountOptions options = account(\"accountName\");\n      assertEquals(ImmutableSet.of(\"accountName\"), options.buildQueryParameters().get(\"account\"));\n   }\n\n   public void testAccountDomain() {\n      CreateAccountOptions options = new CreateAccountOptions().domainId(\"6\");\n      assertEquals(ImmutableSet.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testDomainIdStatic() {\n      CreateAccountOptions options = domainId(\"6\");\n      assertEquals(ImmutableSet.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/CreateDiskOfferingOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.CreateDiskOfferingOptions.Builder.customized;\nimport static org.jclouds.cloudstack.options.CreateDiskOfferingOptions.Builder.diskSizeInGB;\nimport static org.jclouds.cloudstack.options.CreateDiskOfferingOptions.Builder.tags;\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code CreateDiskOfferingOptions}\n */\n@Test(groups = \"unit\")\npublic class CreateDiskOfferingOptionsTest {\n\n   public void testTags() {\n      CreateDiskOfferingOptions options =\n         new CreateDiskOfferingOptions().tags(ImmutableSet.<String>of(\"tag1\", \"tag2\"));\n      assertEquals(ImmutableSet.of(\"tag1\", \"tag2\"), options.buildQueryParameters().get(\"tags\"));\n   }\n\n   public void testTagsStatic() {\n      CreateDiskOfferingOptions options = tags(ImmutableSet.<String>of(\"tag1\", \"tag2\"));\n      assertEquals(ImmutableSet.of(\"tag1\", \"tag2\"), options.buildQueryParameters().get(\"tags\"));\n   }\n\n   public void testCustomized() {\n      CreateDiskOfferingOptions options =\n         new CreateDiskOfferingOptions().customized(true);\n      assertEquals(ImmutableSet.of(\"true\"), options.buildQueryParameters().get(\"customized\"));\n   }\n\n   public void testCustomizedStatic() {\n      CreateDiskOfferingOptions options = customized(true);\n      assertEquals(ImmutableSet.of(\"true\"), options.buildQueryParameters().get(\"customized\"));\n   }\n\n   public void testDiskSizeInGB() {\n      CreateDiskOfferingOptions options =\n         new CreateDiskOfferingOptions().diskSizeInGB(100);\n      assertEquals(ImmutableSet.of(\"100\"), options.buildQueryParameters().get(\"disksize\"));\n   }\n\n   public void testDiskSizeInGBStatic() {\n      CreateDiskOfferingOptions options = diskSizeInGB(100);\n      assertEquals(ImmutableSet.of(\"100\"), options.buildQueryParameters().get(\"disksize\"));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/CreateIPForwardingRuleOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.CreateIPForwardingRuleOptions.Builder.endPort;\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tests behavior of {@code CreateIPForwardingRuleOptions}\n */\n@Test(groups = \"unit\")\npublic class CreateIPForwardingRuleOptionsTest {\n\n   public void testNetworkId() {\n      CreateIPForwardingRuleOptions options = new CreateIPForwardingRuleOptions().endPort(6);\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"endport\"));\n   }\n\n   public void testNetworkIdStatic() {\n      CreateIPForwardingRuleOptions options = endPort(6);\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"endport\"));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/CreateNetworkOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.CreateNetworkOptions.Builder.accountInDomain;\nimport static org.jclouds.cloudstack.options.CreateNetworkOptions.Builder.endIP;\nimport static org.jclouds.cloudstack.options.CreateNetworkOptions.Builder.gateway;\nimport static org.jclouds.cloudstack.options.CreateNetworkOptions.Builder.isDefault;\nimport static org.jclouds.cloudstack.options.CreateNetworkOptions.Builder.isShared;\nimport static org.jclouds.cloudstack.options.CreateNetworkOptions.Builder.netmask;\nimport static org.jclouds.cloudstack.options.CreateNetworkOptions.Builder.networkDomain;\nimport static org.jclouds.cloudstack.options.CreateNetworkOptions.Builder.startIP;\nimport static org.jclouds.cloudstack.options.CreateNetworkOptions.Builder.vlan;\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tests behavior of {@code CreateNetworkOptions}\n */\n@Test(groups = \"unit\")\npublic class CreateNetworkOptionsTest {\n\n   public void testAccountInDomainId() {\n      CreateNetworkOptions options = new CreateNetworkOptions().accountInDomain(\"adrian\", \"6\");\n      assertEquals(ImmutableList.of(\"adrian\"), options.buildQueryParameters().get(\"account\"));\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testAccountInDomainIdStatic() {\n      CreateNetworkOptions options = accountInDomain(\"adrian\", \"6\");\n      assertEquals(ImmutableList.of(\"adrian\"), options.buildQueryParameters().get(\"account\"));\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testIsDefault() {\n      CreateNetworkOptions options = new CreateNetworkOptions().isDefault(true);\n      assertEquals(ImmutableList.of(\"true\"), options.buildQueryParameters().get(\"isdefault\"));\n   }\n\n   public void testIsDefaultStatic() {\n      CreateNetworkOptions options = isDefault(true);\n      assertEquals(ImmutableList.of(\"true\"), options.buildQueryParameters().get(\"isdefault\"));\n   }\n\n   public void testIsShared() {\n      CreateNetworkOptions options = new CreateNetworkOptions().isShared(true);\n      assertEquals(ImmutableList.of(\"true\"), options.buildQueryParameters().get(\"isshared\"));\n   }\n\n   public void testIsSharedStatic() {\n      CreateNetworkOptions options = isShared(true);\n      assertEquals(ImmutableList.of(\"true\"), options.buildQueryParameters().get(\"isshared\"));\n   }\n\n   public void testStartIP() {\n      CreateNetworkOptions options = new CreateNetworkOptions().startIP(\"1.1.1.1\");\n      assertEquals(ImmutableList.of(\"1.1.1.1\"), options.buildQueryParameters().get(\"startip\"));\n   }\n\n   public void testStartIPStatic() {\n      CreateNetworkOptions options = startIP(\"1.1.1.1\");\n      assertEquals(ImmutableList.of(\"1.1.1.1\"), options.buildQueryParameters().get(\"startip\"));\n   }\n\n   public void testEndIP() {\n      CreateNetworkOptions options = new CreateNetworkOptions().endIP(\"1.1.1.1\");\n      assertEquals(ImmutableList.of(\"1.1.1.1\"), options.buildQueryParameters().get(\"endip\"));\n   }\n\n   public void testEndIPStatic() {\n      CreateNetworkOptions options = endIP(\"1.1.1.1\");\n      assertEquals(ImmutableList.of(\"1.1.1.1\"), options.buildQueryParameters().get(\"endip\"));\n   }\n\n   public void testGateway() {\n      CreateNetworkOptions options = new CreateNetworkOptions().gateway(\"1.1.1.1\");\n      assertEquals(ImmutableList.of(\"1.1.1.1\"), options.buildQueryParameters().get(\"gateway\"));\n   }\n\n   public void testGatewayStatic() {\n      CreateNetworkOptions options = gateway(\"1.1.1.1\");\n      assertEquals(ImmutableList.of(\"1.1.1.1\"), options.buildQueryParameters().get(\"gateway\"));\n   }\n\n   public void testNetmask() {\n      CreateNetworkOptions options = new CreateNetworkOptions().netmask(\"1.1.1.1\");\n      assertEquals(ImmutableList.of(\"1.1.1.1\"), options.buildQueryParameters().get(\"netmask\"));\n   }\n\n   public void testNetmaskStatic() {\n      CreateNetworkOptions options = netmask(\"1.1.1.1\");\n      assertEquals(ImmutableList.of(\"1.1.1.1\"), options.buildQueryParameters().get(\"netmask\"));\n   }\n\n   public void testNetworkDomain() {\n      CreateNetworkOptions options = new CreateNetworkOptions().networkDomain(\"network.com\");\n      assertEquals(ImmutableList.of(\"network.com\"), options.buildQueryParameters().get(\"networkdomain\"));\n   }\n\n   public void testNetworkDomainStatic() {\n      CreateNetworkOptions options = networkDomain(\"network.com\");\n      assertEquals(ImmutableList.of(\"network.com\"), options.buildQueryParameters().get(\"networkdomain\"));\n   }\n\n   public void testVlan() {\n      CreateNetworkOptions options = new CreateNetworkOptions().vlan(\"tag\");\n      assertEquals(ImmutableList.of(\"tag\"), options.buildQueryParameters().get(\"vlan\"));\n   }\n\n   public void testVlanStatic() {\n      CreateNetworkOptions options = vlan(\"tag\");\n      assertEquals(ImmutableList.of(\"tag\"), options.buildQueryParameters().get(\"vlan\"));\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/CreatePodOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.CreatePodOptions.Builder.allocationState;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.cloudstack.domain.AllocationState;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tests behavior of {@code CreatePodOptions}\n */\n@Test(groups = \"unit\")\npublic class CreatePodOptionsTest {\n\n   public void testAllocationState() {\n      CreatePodOptions options = new CreatePodOptions().allocationState(AllocationState.ENABLED);\n      assertEquals(ImmutableList.of(\"Enabled\"), options.buildQueryParameters().get(\"allocationstate\"));\n   }\n\n   public void testAllocationStateStatic() {\n      CreatePodOptions options = allocationState(AllocationState.ENABLED);\n      assertEquals(ImmutableList.of(\"Enabled\"), options.buildQueryParameters().get(\"allocationstate\"));\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/CreateServiceOfferingOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.CreateServiceOfferingOptions.Builder.highlyAvailable;\nimport static org.jclouds.cloudstack.options.CreateServiceOfferingOptions.Builder.hostTags;\nimport static org.jclouds.cloudstack.options.CreateServiceOfferingOptions.Builder.isSystem;\nimport static org.jclouds.cloudstack.options.CreateServiceOfferingOptions.Builder.limitCpuUse;\nimport static org.jclouds.cloudstack.options.CreateServiceOfferingOptions.Builder.networkRateInMb;\nimport static org.jclouds.cloudstack.options.CreateServiceOfferingOptions.Builder.storageType;\nimport static org.jclouds.cloudstack.options.CreateServiceOfferingOptions.Builder.systemVmType;\nimport static org.jclouds.cloudstack.options.CreateServiceOfferingOptions.Builder.tags;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.cloudstack.domain.StorageType;\nimport org.jclouds.cloudstack.domain.SystemVmType;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code CreateServiceOfferingOptions}\n */\n@Test(groups = \"unit\")\npublic class CreateServiceOfferingOptionsTest {\n\n   public void testHostTags() {\n      CreateServiceOfferingOptions options =\n         new CreateServiceOfferingOptions().hostTags(ImmutableSet.of(\"tag1\", \"tag2\"));\n      assertEquals(ImmutableSet.of(\"tag1\", \"tag2\"), options.buildQueryParameters().get(\"hosttags\"));\n   }\n\n   public void testHostTagsStatic() {\n      CreateServiceOfferingOptions options = hostTags(ImmutableSet.of(\"tag1\", \"tag2\"));\n      assertEquals(ImmutableSet.of(\"tag1\", \"tag2\"), options.buildQueryParameters().get(\"hosttags\"));\n   }\n\n   public void testIsSystem() {\n      CreateServiceOfferingOptions options = new CreateServiceOfferingOptions().isSystem(true);\n      assertEquals(ImmutableSet.of(\"true\"), options.buildQueryParameters().get(\"issystem\"));\n   }\n\n   public void testIsSystemStatic() {\n      CreateServiceOfferingOptions options = isSystem(true);\n      assertEquals(ImmutableSet.of(\"true\"), options.buildQueryParameters().get(\"issystem\"));\n   }\n\n   public void testLimitCpuUse() {\n      CreateServiceOfferingOptions options = new CreateServiceOfferingOptions().limitCpuUse(true);\n      assertEquals(ImmutableSet.of(\"true\"), options.buildQueryParameters().get(\"limitcpuuse\"));\n   }\n\n   public void testLimitCpuUseStatic() {\n      CreateServiceOfferingOptions options = limitCpuUse(true);\n      assertEquals(ImmutableSet.of(\"true\"), options.buildQueryParameters().get(\"limitcpuuse\"));\n   }\n\n   public void testNetworkRate() {\n      CreateServiceOfferingOptions options = new CreateServiceOfferingOptions().networkRateInMb(200);\n      assertEquals(ImmutableSet.of(\"200\"), options.buildQueryParameters().get(\"networkrate\"));\n   }\n\n   public void testNetworkRateStatic() {\n      CreateServiceOfferingOptions options = networkRateInMb(200);\n      assertEquals(ImmutableSet.of(\"200\"), options.buildQueryParameters().get(\"networkrate\"));\n   }\n\n   public void testHighlyAvailable() {\n      CreateServiceOfferingOptions options = new CreateServiceOfferingOptions().highlyAvailable(true);\n      assertEquals(ImmutableSet.of(\"true\"), options.buildQueryParameters().get(\"offerha\"));\n   }\n\n   public void testHighlyAvailableStatic() {\n      CreateServiceOfferingOptions options = highlyAvailable(true);\n      assertEquals(ImmutableSet.of(\"true\"), options.buildQueryParameters().get(\"offerha\"));\n   }\n\n   public void testStorageType() {\n      CreateServiceOfferingOptions options = new CreateServiceOfferingOptions().storageType(StorageType.LOCAL);\n      assertEquals(ImmutableSet.of(\"local\"), options.buildQueryParameters().get(\"storagetype\"));\n   }\n\n   public void testStorageTypeStatic() {\n      CreateServiceOfferingOptions options = storageType(StorageType.LOCAL);\n      assertEquals(ImmutableSet.of(\"local\"), options.buildQueryParameters().get(\"storagetype\"));\n   }\n\n   public void testSystemVmType() {\n      CreateServiceOfferingOptions options =\n         new CreateServiceOfferingOptions().systemVmType(SystemVmType.DOMAIN_ROUTER);\n      assertEquals(ImmutableSet.of(\"domainrouter\"), options.buildQueryParameters().get(\"systemvmtype\"));\n   }\n\n   public void testSystemVmTypeStatic() {\n      CreateServiceOfferingOptions options = systemVmType(SystemVmType.DOMAIN_ROUTER);\n      assertEquals(ImmutableSet.of(\"domainrouter\"), options.buildQueryParameters().get(\"systemvmtype\"));\n   }\n\n   public void testTags() {\n      CreateServiceOfferingOptions options =\n         new CreateServiceOfferingOptions().tags(ImmutableSet.<String>of(\"tag1\", \"tag2\"));\n      assertEquals(ImmutableSet.of(\"tag1\", \"tag2\"), options.buildQueryParameters().get(\"tags\"));\n   }\n\n   public void testTagsStatic() {\n      CreateServiceOfferingOptions options = tags(ImmutableSet.<String>of(\"tag1\", \"tag2\"));\n      assertEquals(ImmutableSet.of(\"tag1\", \"tag2\"), options.buildQueryParameters().get(\"tags\"));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/CreateTagsOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.CreateTagsOptions.Builder.customer;\nimport static org.jclouds.cloudstack.options.CreateTagsOptions.Builder.resourceIds;\nimport static org.jclouds.cloudstack.options.CreateTagsOptions.Builder.resourceType;\nimport static org.jclouds.cloudstack.options.CreateTagsOptions.Builder.tags;\nimport static org.testng.Assert.assertEquals;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport org.jclouds.cloudstack.domain.Tag;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code CreateTagsOptions}\n */\n@Test(groups = \"unit\")\npublic class CreateTagsOptionsTest {\n\n   public void testCustomer() {\n      CreateTagsOptions options = new CreateTagsOptions().customer(\"some-customer\");\n      assertEquals(ImmutableList.of(\"some-customer\"), options.buildQueryParameters().get(\"customer\"));\n   }\n\n   public void testCustomerStatic() {\n      CreateTagsOptions options = customer(\"some-customer\");\n      assertEquals(ImmutableList.of(\"some-customer\"), options.buildQueryParameters().get(\"customer\"));\n   }\n\n   public void testResourceIds() {\n      CreateTagsOptions options = new CreateTagsOptions().resourceIds(\"1\", \"2\", \"3\");\n      assertEquals(ImmutableList.of(\"1,2,3\"), options.buildQueryParameters().get(\"resourceids\"));\n   }\n\n   public void testResourceIdsStatic() {\n      CreateTagsOptions options = resourceIds(\"1\", \"2\", \"3\");\n      assertEquals(ImmutableList.of(\"1,2,3\"), options.buildQueryParameters().get(\"resourceids\"));\n   }\n\n   public void testResourceIdsAsSet() {\n      CreateTagsOptions options = new CreateTagsOptions().resourceIds(ImmutableSet.of(\"1\", \"2\", \"3\"));\n      assertEquals(ImmutableList.of(\"1,2,3\"), options.buildQueryParameters().get(\"resourceids\"));\n   }\n\n   public void testResourceIdsAsSetStatic() {\n      CreateTagsOptions options = resourceIds(ImmutableSet.of(\"1\", \"2\", \"3\"));\n      assertEquals(ImmutableList.of(\"1,2,3\"), options.buildQueryParameters().get(\"resourceids\"));\n   }\n\n   public void testResourceType() {\n      CreateTagsOptions options = new CreateTagsOptions().resourceType(Tag.ResourceType.TEMPLATE);\n      assertEquals(ImmutableList.of(\"Template\"), options.buildQueryParameters().get(\"resourcetype\"));\n   }\n\n   public void testResourceTypeStatic() {\n      CreateTagsOptions options = resourceType(Tag.ResourceType.TEMPLATE);\n      assertEquals(ImmutableList.of(\"Template\"), options.buildQueryParameters().get(\"resourcetype\"));\n   }\n\n   public void testResourceTypeAsString() {\n      CreateTagsOptions options = new CreateTagsOptions().resourceType(\"Template\");\n      assertEquals(ImmutableList.of(\"Template\"), options.buildQueryParameters().get(\"resourcetype\"));\n   }\n\n   public void testResourceTypeAsStringStatic() {\n      CreateTagsOptions options = resourceType(\"Template\");\n      assertEquals(ImmutableList.of(\"Template\"), options.buildQueryParameters().get(\"resourcetype\"));\n   }\n\n   public void testTags() {\n      CreateTagsOptions options = new CreateTagsOptions().tags(ImmutableMap.of(\"tag1\", \"val1\", \"tag2\", \"val2\"));\n      assertEquals(ImmutableList.of(\"tag1\"), options.buildQueryParameters().get(\"tags[0].key\"));\n      assertEquals(ImmutableList.of(\"tag2\"), options.buildQueryParameters().get(\"tags[1].key\"));\n      assertEquals(ImmutableList.of(\"val1\"), options.buildQueryParameters().get(\"tags[0].value\"));\n      assertEquals(ImmutableList.of(\"val2\"), options.buildQueryParameters().get(\"tags[1].value\"));\n   }\n\n   public void testTagsStatic() {\n      CreateTagsOptions options = tags(ImmutableMap.of(\"tag1\", \"val1\", \"tag2\", \"val2\"));\n      assertEquals(ImmutableList.of(\"tag1\"), options.buildQueryParameters().get(\"tags[0].key\"));\n      assertEquals(ImmutableList.of(\"tag2\"), options.buildQueryParameters().get(\"tags[1].key\"));\n      assertEquals(ImmutableList.of(\"val1\"), options.buildQueryParameters().get(\"tags[0].value\"));\n      assertEquals(ImmutableList.of(\"val2\"), options.buildQueryParameters().get(\"tags[1].value\"));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/CreateUserOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.CreateUserOptions.Builder.domainId;\nimport static org.jclouds.cloudstack.options.CreateUserOptions.Builder.timezone;\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code CreateUserOptions}\n */\n@Test(groups = \"unit\")\npublic class CreateUserOptionsTest {\n\n   public void testDomainId() {\n      CreateUserOptions options = new CreateUserOptions().domainId(\"6\");\n      assertEquals(ImmutableSet.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testDomainIdStatic() {\n      CreateUserOptions options = domainId(\"6\");\n      assertEquals(ImmutableSet.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testTimezone() {\n      CreateUserOptions options = new CreateUserOptions().timezone(\"something\");\n      assertEquals(ImmutableSet.of(\"something\"), options.buildQueryParameters().get(\"timezone\"));\n   }\n\n   public void testTimezoneStatic() {\n      CreateUserOptions options = timezone(\"something\");\n      assertEquals(ImmutableSet.of(\"something\"), options.buildQueryParameters().get(\"timezone\"));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/CreateVlanIPRangeOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.CreateVlanIPRangeOptions.Builder.accountInDomain;\nimport static org.jclouds.cloudstack.options.CreateVlanIPRangeOptions.Builder.domainId;\nimport static org.jclouds.cloudstack.options.CreateVlanIPRangeOptions.Builder.forVirtualNetwork;\nimport static org.jclouds.cloudstack.options.CreateVlanIPRangeOptions.Builder.gateway;\nimport static org.jclouds.cloudstack.options.CreateVlanIPRangeOptions.Builder.netmask;\nimport static org.jclouds.cloudstack.options.CreateVlanIPRangeOptions.Builder.networkId;\nimport static org.jclouds.cloudstack.options.CreateVlanIPRangeOptions.Builder.podId;\nimport static org.jclouds.cloudstack.options.CreateVlanIPRangeOptions.Builder.vlan;\nimport static org.jclouds.cloudstack.options.CreateVlanIPRangeOptions.Builder.zoneId;\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code CreateVlanIPRangeOptions}\n */\n@Test(groups = \"unit\")\npublic class CreateVlanIPRangeOptionsTest {\n\n   public void testAccountInDomain() {\n      CreateVlanIPRangeOptions options = new CreateVlanIPRangeOptions().accountInDomain(\"fred\", \"6\");\n      assertEquals(ImmutableSet.of(\"fred\"), options.buildQueryParameters().get(\"account\"));\n      assertEquals(ImmutableSet.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testAccountInDomainStatic() {\n      CreateVlanIPRangeOptions options = accountInDomain(\"fred\", \"6\");\n      assertEquals(ImmutableSet.of(\"fred\"), options.buildQueryParameters().get(\"account\"));\n      assertEquals(ImmutableSet.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testDomainId() {\n      CreateVlanIPRangeOptions options = new CreateVlanIPRangeOptions().domainId(\"6\");\n      assertEquals(ImmutableSet.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testDomainIdStatic() {\n      CreateVlanIPRangeOptions options = domainId(\"6\");\n      assertEquals(ImmutableSet.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testForVirtualNetwork() {\n      CreateVlanIPRangeOptions options = new CreateVlanIPRangeOptions().forVirtualNetwork(true);\n      assertEquals(ImmutableSet.of(\"true\"), options.buildQueryParameters().get(\"forvirtualnetwork\"));\n   }\n\n   public void testForVirtualNetworkStatic() {\n      CreateVlanIPRangeOptions options = forVirtualNetwork(true);\n      assertEquals(ImmutableSet.of(\"true\"), options.buildQueryParameters().get(\"forvirtualnetwork\"));\n   }\n\n   public void testGateway() {\n      CreateVlanIPRangeOptions options = new CreateVlanIPRangeOptions().gateway(\"192.168.42.24\");\n      assertEquals(ImmutableSet.of(\"192.168.42.24\"), options.buildQueryParameters().get(\"gateway\"));\n   }\n\n   public void testGatewayStatic() {\n      CreateVlanIPRangeOptions options = gateway(\"192.168.42.24\");\n      assertEquals(ImmutableSet.of(\"192.168.42.24\"), options.buildQueryParameters().get(\"gateway\"));\n   }\n\n   public void testNetmask() {\n      CreateVlanIPRangeOptions options = new CreateVlanIPRangeOptions().netmask(\"255.255.255.240\");\n      assertEquals(ImmutableSet.of(\"255.255.255.240\"), options.buildQueryParameters().get(\"netmask\"));\n   }\n\n   public void testNetmaskStatic() {\n      CreateVlanIPRangeOptions options = netmask(\"255.255.255.240\");\n      assertEquals(ImmutableSet.of(\"255.255.255.240\"), options.buildQueryParameters().get(\"netmask\"));\n   }\n\n   public void testNetworkId() {\n      CreateVlanIPRangeOptions options = new CreateVlanIPRangeOptions().networkId(\"9\");\n      assertEquals(ImmutableSet.of(\"9\"), options.buildQueryParameters().get(\"networkid\"));\n   }\n\n   public void testNetworkIdStatic() {\n      CreateVlanIPRangeOptions options = networkId(\"9\");\n      assertEquals(ImmutableSet.of(\"9\"), options.buildQueryParameters().get(\"networkid\"));\n   }\n\n   public void testPodId() {\n      CreateVlanIPRangeOptions options = new CreateVlanIPRangeOptions().podId(\"8\");\n      assertEquals(ImmutableSet.of(\"8\"), options.buildQueryParameters().get(\"podid\"));\n   }\n\n   public void testPodIdStatic() {\n      CreateVlanIPRangeOptions options = podId(\"8\");\n      assertEquals(ImmutableSet.of(\"8\"), options.buildQueryParameters().get(\"podid\"));\n   }\n\n   public void testVlan() {\n      CreateVlanIPRangeOptions options = new CreateVlanIPRangeOptions().vlan(1001);\n      assertEquals(ImmutableSet.of(\"1001\"), options.buildQueryParameters().get(\"vlan\"));\n   }\n\n   public void testVlanStatic() {\n      CreateVlanIPRangeOptions options = vlan(1001);\n      assertEquals(ImmutableSet.of(\"1001\"), options.buildQueryParameters().get(\"vlan\"));\n   }\n\n   public void testZoneId() {\n      CreateVlanIPRangeOptions options = new CreateVlanIPRangeOptions().zoneId(\"7\");\n      assertEquals(ImmutableSet.of(\"7\"), options.buildQueryParameters().get(\"zoneid\"));\n   }\n\n   public void testZoneIdStatic() {\n      CreateVlanIPRangeOptions options = zoneId(\"7\");\n      assertEquals(ImmutableSet.of(\"7\"), options.buildQueryParameters().get(\"zoneid\"));\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/DeleteHostOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.DeleteHostOptions.Builder.forceDestroyLocalStorage;\nimport static org.jclouds.cloudstack.options.DeleteHostOptions.Builder.forced;\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tests behavior of {@code DeleteHostOptions}\n */\n@Test(groups = \"unit\")\npublic class DeleteHostOptionsTest {\n\n   public void testForced() {\n      DeleteHostOptions options = new DeleteHostOptions().forced(true);\n      assertEquals(ImmutableList.of(\"true\"), options.buildQueryParameters().get(\"forced\"));\n   }\n\n   public void testForcedStatic() {\n      DeleteHostOptions options = forced(true);\n      assertEquals(ImmutableList.of(\"true\"), options.buildQueryParameters().get(\"forced\"));\n   }\n\n   public void testForceDestroyLocalStorage() {\n      DeleteHostOptions options = new DeleteHostOptions().forceDestroyLocalStorage(true);\n      assertEquals(ImmutableList.of(\"true\"), options.buildQueryParameters().get(\"forcedestroylocalstorage\"));\n   }\n\n   public void testForceDestroyLocalStorageStatic() {\n      DeleteHostOptions options = forceDestroyLocalStorage(true);\n      assertEquals(ImmutableList.of(\"true\"), options.buildQueryParameters().get(\"forcedestroylocalstorage\"));\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/DeleteTagsOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.DeleteTagsOptions.Builder.resourceIds;\nimport static org.jclouds.cloudstack.options.DeleteTagsOptions.Builder.resourceType;\nimport static org.jclouds.cloudstack.options.DeleteTagsOptions.Builder.tags;\nimport static org.testng.Assert.assertEquals;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport org.jclouds.cloudstack.domain.Tag;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code DeleteTagsOptions}\n */\n@Test(groups = \"unit\")\npublic class DeleteTagsOptionsTest {\n\n   public void testResourceIds() {\n      DeleteTagsOptions options = new DeleteTagsOptions().resourceIds(\"1\", \"2\", \"3\");\n      assertEquals(ImmutableList.of(\"1,2,3\"), options.buildQueryParameters().get(\"resourceids\"));\n   }\n\n   public void testResourceIdsStatic() {\n      DeleteTagsOptions options = resourceIds(\"1\", \"2\", \"3\");\n      assertEquals(ImmutableList.of(\"1,2,3\"), options.buildQueryParameters().get(\"resourceids\"));\n   }\n\n   public void testResourceIdsAsSet() {\n      DeleteTagsOptions options = new DeleteTagsOptions().resourceIds(ImmutableSet.of(\"1\", \"2\", \"3\"));\n      assertEquals(ImmutableList.of(\"1,2,3\"), options.buildQueryParameters().get(\"resourceids\"));\n   }\n\n   public void testResourceIdsAsSetStatic() {\n      DeleteTagsOptions options = resourceIds(ImmutableSet.of(\"1\", \"2\", \"3\"));\n      assertEquals(ImmutableList.of(\"1,2,3\"), options.buildQueryParameters().get(\"resourceids\"));\n   }\n\n   public void testResourceType() {\n      DeleteTagsOptions options = new DeleteTagsOptions().resourceType(Tag.ResourceType.TEMPLATE);\n      assertEquals(ImmutableList.of(\"Template\"), options.buildQueryParameters().get(\"resourcetype\"));\n   }\n\n   public void testResourceTypeStatic() {\n      DeleteTagsOptions options = resourceType(Tag.ResourceType.TEMPLATE);\n      assertEquals(ImmutableList.of(\"Template\"), options.buildQueryParameters().get(\"resourcetype\"));\n   }\n\n   public void testResourceTypeAsString() {\n      DeleteTagsOptions options = new DeleteTagsOptions().resourceType(\"Template\");\n      assertEquals(ImmutableList.of(\"Template\"), options.buildQueryParameters().get(\"resourcetype\"));\n   }\n\n   public void testResourceTypeAsStringStatic() {\n      DeleteTagsOptions options = resourceType(\"Template\");\n      assertEquals(ImmutableList.of(\"Template\"), options.buildQueryParameters().get(\"resourcetype\"));\n   }\n\n   public void testTags() {\n      DeleteTagsOptions options = new DeleteTagsOptions().tags(ImmutableMap.of(\"tag1\", \"val1\", \"tag2\", \"val2\"));\n      assertEquals(ImmutableList.of(\"tag1\"), options.buildQueryParameters().get(\"tags[0].key\"));\n      assertEquals(ImmutableList.of(\"tag2\"), options.buildQueryParameters().get(\"tags[1].key\"));\n      assertEquals(ImmutableList.of(\"val1\"), options.buildQueryParameters().get(\"tags[0].value\"));\n      assertEquals(ImmutableList.of(\"val2\"), options.buildQueryParameters().get(\"tags[1].value\"));\n   }\n\n   public void testTagsStatic() {\n      DeleteTagsOptions options = tags(ImmutableMap.of(\"tag1\", \"val1\", \"tag2\", \"val2\"));\n      assertEquals(ImmutableList.of(\"tag1\"), options.buildQueryParameters().get(\"tags[0].key\"));\n      assertEquals(ImmutableList.of(\"tag2\"), options.buildQueryParameters().get(\"tags[1].key\"));\n      assertEquals(ImmutableList.of(\"val1\"), options.buildQueryParameters().get(\"tags[0].value\"));\n      assertEquals(ImmutableList.of(\"val2\"), options.buildQueryParameters().get(\"tags[1].value\"));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/GenerateUsageRecordsOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.GenerateUsageRecordsOptions.Builder.domainId;\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code GenerateUsageRecordsOptions}\n */\n@Test(groups = \"unit\")\npublic class GenerateUsageRecordsOptionsTest {\n\n   public void testDomainId() {\n      GenerateUsageRecordsOptions options = new GenerateUsageRecordsOptions().domainId(\"42\");\n      assertEquals(ImmutableSet.of(\"42\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testDomainIdStatic() {\n      GenerateUsageRecordsOptions options = domainId(\"42\");\n      assertEquals(ImmutableSet.of(\"42\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/ListAccountsOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.ListAccountsOptions.Builder.accountInDomain;\nimport static org.jclouds.cloudstack.options.ListAccountsOptions.Builder.cleanupRequired;\nimport static org.jclouds.cloudstack.options.ListAccountsOptions.Builder.domainId;\nimport static org.jclouds.cloudstack.options.ListAccountsOptions.Builder.id;\nimport static org.jclouds.cloudstack.options.ListAccountsOptions.Builder.recursive;\nimport static org.jclouds.cloudstack.options.ListAccountsOptions.Builder.state;\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tests behavior of {@code ListAccountsOptions}\n */\n@Test(groups = \"unit\")\npublic class ListAccountsOptionsTest {\n\n   public void testAccountInDomainId() {\n      ListAccountsOptions options = new ListAccountsOptions().accountInDomain(\"adrian\", \"6\");\n      assertEquals(ImmutableList.of(\"adrian\"), options.buildQueryParameters().get(\"account\"));\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testAccountInDomainIdStatic() {\n      ListAccountsOptions options = accountInDomain(\"adrian\", \"6\");\n      assertEquals(ImmutableList.of(\"adrian\"), options.buildQueryParameters().get(\"account\"));\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testName() {\n      ListAccountsOptions options = new ListAccountsOptions().id(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testNameStatic() {\n      ListAccountsOptions options = id(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testRecursive() {\n      ListAccountsOptions options = new ListAccountsOptions().recursive(true);\n      assertEquals(ImmutableList.of(\"true\"), options.buildQueryParameters().get(\"isrecursive\"));\n   }\n\n   public void testRecursiveStatic() {\n      ListAccountsOptions options = recursive(true);\n      assertEquals(ImmutableList.of(\"true\"), options.buildQueryParameters().get(\"isrecursive\"));\n   }\n\n   public void testState() {\n      ListAccountsOptions options = new ListAccountsOptions().state(\"state\");\n      assertEquals(ImmutableList.of(\"state\"), options.buildQueryParameters().get(\"state\"));\n   }\n\n   public void testStateStatic() {\n      ListAccountsOptions options = state(\"state\");\n      assertEquals(ImmutableList.of(\"state\"), options.buildQueryParameters().get(\"state\"));\n   }\n\n   public void testCleanupRequired() {\n      ListAccountsOptions options = new ListAccountsOptions().cleanupRequired(true);\n      assertEquals(ImmutableList.of(\"true\"), options.buildQueryParameters().get(\"iscleanuprequired\"));\n   }\n\n   public void testCleanupRequiredStatic() {\n      ListAccountsOptions options = cleanupRequired(true);\n      assertEquals(ImmutableList.of(\"true\"), options.buildQueryParameters().get(\"iscleanuprequired\"));\n   }\n\n   public void testId() {\n      ListAccountsOptions options = new ListAccountsOptions().id(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testDomainId() {\n      ListAccountsOptions options = new ListAccountsOptions().domainId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testIdStatic() {\n      ListAccountsOptions options = id(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testDomainIdStatic() {\n      ListAccountsOptions options = domainId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/ListAlertsOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.ListAlertsOptions.Builder.id;\nimport static org.jclouds.cloudstack.options.ListAlertsOptions.Builder.keyword;\nimport static org.jclouds.cloudstack.options.ListAlertsOptions.Builder.type;\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tests behavior of {@code ListAlertsOptions}\n */\n@Test(groups = \"unit\")\npublic class ListAlertsOptionsTest {\n\n   public void testId() {\n      ListAlertsOptions options = new ListAlertsOptions().id(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testIdStatic() {\n      ListAlertsOptions options = id(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testKeyword() {\n      ListAlertsOptions options = new ListAlertsOptions().keyword(\"fred\");\n      assertEquals(ImmutableList.of(\"fred\"), options.buildQueryParameters().get(\"keyword\"));\n   }\n\n   public void testKeywordStatic() {\n      ListAlertsOptions options = keyword(\"fred\");\n      assertEquals(ImmutableList.of(\"fred\"), options.buildQueryParameters().get(\"keyword\"));\n   }\n\n   public void testType() {\n      ListAlertsOptions options = new ListAlertsOptions().type(\"42\");\n      assertEquals(ImmutableList.of(\"42\"), options.buildQueryParameters().get(\"type\"));\n   }\n\n   public void testTypeStatic() {\n      ListAlertsOptions options = type(\"42\");\n      assertEquals(ImmutableList.of(\"42\"), options.buildQueryParameters().get(\"type\"));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/ListAsyncJobsOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.ListAsyncJobsOptions.Builder.accountInDomain;\nimport static org.jclouds.cloudstack.options.ListAsyncJobsOptions.Builder.domainId;\nimport static org.jclouds.cloudstack.options.ListAsyncJobsOptions.Builder.startDate;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Date;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tests behavior of {@code ListAsyncJobsOptions}\n */\n@Test(groups = \"unit\")\npublic class ListAsyncJobsOptionsTest {\n   public void testAccountInDomainId() {\n      ListAsyncJobsOptions options = new ListAsyncJobsOptions().accountInDomain(\"adrian\", \"6\");\n      assertEquals(ImmutableList.of(\"adrian\"), options.buildQueryParameters().get(\"account\"));\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testAccountInDomainIdStatic() {\n      ListAsyncJobsOptions options = accountInDomain(\"adrian\", \"6\");\n      assertEquals(ImmutableList.of(\"adrian\"), options.buildQueryParameters().get(\"account\"));\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testStartDate() {\n      ListAsyncJobsOptions options = new ListAsyncJobsOptions().startDate(new Date(100000));\n      assertEquals(ImmutableList.of(\"1970-01-01T00:01:40Z\"), options.buildQueryParameters().get(\"startdate\"));\n   }\n\n   public void testDomainId() {\n      ListAsyncJobsOptions options = new ListAsyncJobsOptions().domainId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testStartDateStatic() {\n      ListAsyncJobsOptions options = startDate(new Date(100000));\n      assertEquals(ImmutableList.of(\"1970-01-01T00:01:40Z\"), options.buildQueryParameters().get(\"startdate\"));\n   }\n\n   public void testDomainIdStatic() {\n      ListAsyncJobsOptions options = domainId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/ListCapacityOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.ListCapacityOptions.Builder.hostId;\nimport static org.jclouds.cloudstack.options.ListCapacityOptions.Builder.keyword;\nimport static org.jclouds.cloudstack.options.ListCapacityOptions.Builder.podId;\nimport static org.jclouds.cloudstack.options.ListCapacityOptions.Builder.type;\nimport static org.jclouds.cloudstack.options.ListCapacityOptions.Builder.zoneId;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.cloudstack.domain.Capacity;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tests behavior of {@code ListCapacityOptions}\n */\n@Test(groups = \"unit\")\npublic class ListCapacityOptionsTest {\n\n   public void testHostId() {\n      ListCapacityOptions options = new ListCapacityOptions().hostId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"hostid\"));\n   }\n\n   public void testHostIdStatic() {\n      ListCapacityOptions options = hostId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"hostid\"));\n   }\n\n   public void testKeyword() {\n      ListCapacityOptions options = new ListCapacityOptions().keyword(\"fred\");\n      assertEquals(ImmutableList.of(\"fred\"), options.buildQueryParameters().get(\"keyword\"));\n   }\n\n   public void testKeywordStatic() {\n      ListCapacityOptions options = keyword(\"fred\");\n      assertEquals(ImmutableList.of(\"fred\"), options.buildQueryParameters().get(\"keyword\"));\n   }\n\n   public void testPodId() {\n      ListCapacityOptions options = new ListCapacityOptions().podId(\"5\");\n      assertEquals(ImmutableList.of(\"5\"), options.buildQueryParameters().get(\"podid\"));\n   }\n\n   public void testPodIdStatic() {\n      ListCapacityOptions options = podId(\"5\");\n      assertEquals(ImmutableList.of(\"5\"), options.buildQueryParameters().get(\"podid\"));\n   }\n\n   public void testType() {\n      ListCapacityOptions options = new ListCapacityOptions().type(Capacity.Type.PUBLIC_IP_ADDRESSES);\n      assertEquals(ImmutableList.of(\"4\"), options.buildQueryParameters().get(\"type\"));\n   }\n\n   public void testTypeStatic() {\n      ListCapacityOptions options = type(Capacity.Type.PUBLIC_IP_ADDRESSES);\n      assertEquals(ImmutableList.of(\"4\"), options.buildQueryParameters().get(\"type\"));\n   }\n\n   public void testZoneId() {\n      ListCapacityOptions options = new ListCapacityOptions().zoneId(\"4\");\n      assertEquals(ImmutableList.of(\"4\"), options.buildQueryParameters().get(\"zoneid\"));\n   }\n\n   public void testZoneIdStatic() {\n      ListCapacityOptions options = zoneId(\"4\");\n      assertEquals(ImmutableList.of(\"4\"), options.buildQueryParameters().get(\"zoneid\"));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/ListClustersOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.ListClustersOptions.Builder.allocationState;\nimport static org.jclouds.cloudstack.options.ListClustersOptions.Builder.clusterType;\nimport static org.jclouds.cloudstack.options.ListClustersOptions.Builder.hypervisor;\nimport static org.jclouds.cloudstack.options.ListClustersOptions.Builder.id;\nimport static org.jclouds.cloudstack.options.ListClustersOptions.Builder.keyword;\nimport static org.jclouds.cloudstack.options.ListClustersOptions.Builder.managedState;\nimport static org.jclouds.cloudstack.options.ListClustersOptions.Builder.name;\nimport static org.jclouds.cloudstack.options.ListClustersOptions.Builder.podId;\nimport static org.jclouds.cloudstack.options.ListClustersOptions.Builder.zoneId;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.cloudstack.domain.AllocationState;\nimport org.jclouds.cloudstack.domain.Cluster;\nimport org.jclouds.cloudstack.domain.Host;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tests behavior of {@code ListClustersOptions}\n */\n@Test(groups = \"unit\")\npublic class ListClustersOptionsTest {\n\n   public void testAllocationState() {\n      ListClustersOptions options = new ListClustersOptions().allocationState(AllocationState.ENABLED);\n      assertEquals(ImmutableList.of(\"Enabled\"), options.buildQueryParameters().get(\"allocationstate\"));\n   }\n\n   public void testAllocationStateStatic() {\n      ListClustersOptions options = allocationState(AllocationState.ENABLED);\n      assertEquals(ImmutableList.of(\"Enabled\"), options.buildQueryParameters().get(\"allocationstate\"));\n   }\n\n   public void testClusterType() {\n      ListClustersOptions options = new ListClustersOptions().clusterType(Host.ClusterType.CLOUD_MANAGED);\n      assertEquals(ImmutableList.of(\"CloudManaged\"), options.buildQueryParameters().get(\"clustertype\"));\n   }\n\n   public void testClusterTypeStatic() {\n      ListClustersOptions options = clusterType(Host.ClusterType.CLOUD_MANAGED);\n      assertEquals(ImmutableList.of(\"CloudManaged\"), options.buildQueryParameters().get(\"clustertype\"));\n   }\n\n   public void testHypervisor() {\n      ListClustersOptions options = new ListClustersOptions().hypervisor(\"XenServer\");\n      assertEquals(ImmutableList.of(\"XenServer\"), options.buildQueryParameters().get(\"hypervisor\"));\n   }\n\n   public void testHypervisorStatic() {\n      ListClustersOptions options = hypervisor(\"XenServer\");\n      assertEquals(ImmutableList.of(\"XenServer\"), options.buildQueryParameters().get(\"hypervisor\"));\n   }\n\n   public void testId() {\n      ListClustersOptions options = new ListClustersOptions().id(\"42\");\n      assertEquals(ImmutableList.of(\"42\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testIdStatic() {\n      ListClustersOptions options = id(\"42\");\n      assertEquals(ImmutableList.of(\"42\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testKeyword() {\n      ListClustersOptions options = new ListClustersOptions().keyword(\"Enabled\");\n      assertEquals(ImmutableList.of(\"Enabled\"), options.buildQueryParameters().get(\"keyword\"));\n   }\n\n   public void testKeywordStatic() {\n      ListClustersOptions options = keyword(\"Enabled\");\n      assertEquals(ImmutableList.of(\"Enabled\"), options.buildQueryParameters().get(\"keyword\"));\n   }\n\n   public void testManagedState() {\n      ListClustersOptions options = new ListClustersOptions().managedState(Cluster.ManagedState.PREPARE_UNMANAGED);\n      assertEquals(ImmutableList.of(\"PrepareUnmanaged\"), options.buildQueryParameters().get(\"managedstate\"));\n   }\n\n   public void testManagedStateStatic() {\n      ListClustersOptions options = managedState(Cluster.ManagedState.PREPARE_UNMANAGED);\n      assertEquals(ImmutableList.of(\"PrepareUnmanaged\"), options.buildQueryParameters().get(\"managedstate\"));\n   }\n\n   public void testName() {\n      ListClustersOptions options = new ListClustersOptions().name(\"Host Name\");\n      assertEquals(ImmutableList.of(\"Host Name\"), options.buildQueryParameters().get(\"name\"));\n   }\n\n   public void testNameStatic() {\n      ListClustersOptions options = name(\"Host Name\");\n      assertEquals(ImmutableList.of(\"Host Name\"), options.buildQueryParameters().get(\"name\"));\n   }\n\n   public void testPodId() {\n      ListClustersOptions options = new ListClustersOptions().podId(\"42\");\n      assertEquals(ImmutableList.of(\"42\"), options.buildQueryParameters().get(\"podid\"));\n   }\n\n   public void testPodIdStatic() {\n      ListClustersOptions options = podId(\"42\");\n      assertEquals(ImmutableList.of(\"42\"), options.buildQueryParameters().get(\"podid\"));\n   }\n\n   public void testZoneId() {\n      ListClustersOptions options = new ListClustersOptions().zoneId(\"42\");\n      assertEquals(ImmutableList.of(\"42\"), options.buildQueryParameters().get(\"zoneid\"));\n   }\n\n   public void testZoneIdStatic() {\n      ListClustersOptions options = zoneId(\"42\");\n      assertEquals(ImmutableList.of(\"42\"), options.buildQueryParameters().get(\"zoneid\"));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/ListDiskOfferingsOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.ListDiskOfferingsOptions.Builder.domainId;\nimport static org.jclouds.cloudstack.options.ListDiskOfferingsOptions.Builder.id;\nimport static org.jclouds.cloudstack.options.ListDiskOfferingsOptions.Builder.name;\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tests behavior of {@code ListDiskOfferingsOptions}\n */\n@Test(groups = \"unit\")\npublic class ListDiskOfferingsOptionsTest {\n\n   public void testId() {\n      ListDiskOfferingsOptions options = new ListDiskOfferingsOptions().id(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testIdStatic() {\n      ListDiskOfferingsOptions options = id(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testName() {\n      ListDiskOfferingsOptions options = new ListDiskOfferingsOptions().name(\"foo\");\n      assertEquals(ImmutableList.of(\"foo\"), options.buildQueryParameters().get(\"name\"));\n   }\n\n   public void testNameStatic() {\n      ListDiskOfferingsOptions options = name(\"foo\");\n      assertEquals(ImmutableList.of(\"foo\"), options.buildQueryParameters().get(\"name\"));\n   }\n\n   public void testDomainId() {\n      ListDiskOfferingsOptions options = new ListDiskOfferingsOptions().domainId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testDomainIdStatic() {\n      ListDiskOfferingsOptions options = domainId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/ListHostsOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.ListHostsOptions.Builder.allocationState;\nimport static org.jclouds.cloudstack.options.ListHostsOptions.Builder.clusterId;\nimport static org.jclouds.cloudstack.options.ListHostsOptions.Builder.id;\nimport static org.jclouds.cloudstack.options.ListHostsOptions.Builder.keyword;\nimport static org.jclouds.cloudstack.options.ListHostsOptions.Builder.name;\nimport static org.jclouds.cloudstack.options.ListHostsOptions.Builder.page;\nimport static org.jclouds.cloudstack.options.ListHostsOptions.Builder.pageSize;\nimport static org.jclouds.cloudstack.options.ListHostsOptions.Builder.podId;\nimport static org.jclouds.cloudstack.options.ListHostsOptions.Builder.state;\nimport static org.jclouds.cloudstack.options.ListHostsOptions.Builder.type;\nimport static org.jclouds.cloudstack.options.ListHostsOptions.Builder.virtualMachineId;\nimport static org.jclouds.cloudstack.options.ListHostsOptions.Builder.zoneId;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.cloudstack.domain.AllocationState;\nimport org.jclouds.cloudstack.domain.Host;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tests behavior of {@code ListHostsOptions}\n */\n@Test(groups = \"unit\")\npublic class ListHostsOptionsTest {\n\n   public void testId() {\n      ListHostsOptions options = new ListHostsOptions().id(\"42\");\n      assertEquals(ImmutableList.of(\"42\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testIdStatic() {\n      ListHostsOptions options = id(\"42\");\n      assertEquals(ImmutableList.of(\"42\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testAllocationState() {\n      ListHostsOptions options = new ListHostsOptions().allocationState(AllocationState.ENABLED);\n      assertEquals(ImmutableList.of(\"Enabled\"), options.buildQueryParameters().get(\"allocationstate\"));\n   }\n\n   public void testAllocationStateStatic() {\n      ListHostsOptions options = allocationState(AllocationState.ENABLED);\n      assertEquals(ImmutableList.of(\"Enabled\"), options.buildQueryParameters().get(\"allocationstate\"));\n   }\n\n   public void testClusterId() {\n      ListHostsOptions options = new ListHostsOptions().clusterId(\"42\");\n      assertEquals(ImmutableList.of(\"42\"), options.buildQueryParameters().get(\"clusterid\"));\n   }\n\n   public void testClusterIdStatic() {\n      ListHostsOptions options = clusterId(\"42\");\n      assertEquals(ImmutableList.of(\"42\"), options.buildQueryParameters().get(\"clusterid\"));\n   }\n\n   public void testKeyword() {\n      ListHostsOptions options = new ListHostsOptions().keyword(\"Enabled\");\n      assertEquals(ImmutableList.of(\"Enabled\"), options.buildQueryParameters().get(\"keyword\"));\n   }\n\n   public void testKeywordStatic() {\n      ListHostsOptions options = keyword(\"Enabled\");\n      assertEquals(ImmutableList.of(\"Enabled\"), options.buildQueryParameters().get(\"keyword\"));\n   }\n\n   public void testName() {\n      ListHostsOptions options = new ListHostsOptions().name(\"Host Name\");\n      assertEquals(ImmutableList.of(\"Host Name\"), options.buildQueryParameters().get(\"name\"));\n   }\n\n   public void testNameStatic() {\n      ListHostsOptions options = name(\"Host Name\");\n      assertEquals(ImmutableList.of(\"Host Name\"), options.buildQueryParameters().get(\"name\"));\n   }\n\n   public void testPage() {\n      ListHostsOptions options = new ListHostsOptions().page(42L);\n      assertEquals(ImmutableList.of(\"42\"), options.buildQueryParameters().get(\"page\"));\n   }\n\n   public void testPageStatic() {\n      ListHostsOptions options = page(42L);\n      assertEquals(ImmutableList.of(\"42\"), options.buildQueryParameters().get(\"page\"));\n   }\n\n   public void testPageSize() {\n       ListHostsOptions options = new ListHostsOptions().pageSize(42L);\n      assertEquals(ImmutableList.of(\"42\"), options.buildQueryParameters().get(\"pagesize\"));\n   }\n\n   public void testPageSizeStatic() {\n      ListHostsOptions options = pageSize(42L);\n      assertEquals(ImmutableList.of(\"42\"), options.buildQueryParameters().get(\"pagesize\"));\n   }\n\n   public void testPodId() {\n      ListHostsOptions options = new ListHostsOptions().podId(\"42\");\n      assertEquals(ImmutableList.of(\"42\"), options.buildQueryParameters().get(\"podid\"));\n   }\n\n   public void testPodIdStatic() {\n      ListHostsOptions options = podId(\"42\");\n      assertEquals(ImmutableList.of(\"42\"), options.buildQueryParameters().get(\"podid\"));\n   }\n\n   public void testState() {\n      ListHostsOptions options = new ListHostsOptions().state(\"Up\");\n      assertEquals(ImmutableList.of(\"Up\"), options.buildQueryParameters().get(\"state\"));\n   }\n\n   public void testStateStatic() {\n      ListHostsOptions options = state(\"Up\");\n      assertEquals(ImmutableList.of(\"Up\"), options.buildQueryParameters().get(\"state\"));\n   }\n\n   public void testType() {\n      ListHostsOptions options = new ListHostsOptions().type(Host.Type.ROUTING);\n      assertEquals(ImmutableList.of(\"Routing\"), options.buildQueryParameters().get(\"type\"));\n   }\n\n   public void testTypeStatic() {\n      ListHostsOptions options = type(Host.Type.ROUTING);\n      assertEquals(ImmutableList.of(\"Routing\"), options.buildQueryParameters().get(\"type\"));\n   }\n\n   public void testVirtualMachineId() {\n      ListHostsOptions options = new ListHostsOptions().virtualMachineId(\"42\");\n      assertEquals(ImmutableList.of(\"42\"), options.buildQueryParameters().get(\"virtualmachineid\"));\n   }\n\n   public void testVirtualMachineIdStatic() {\n      ListHostsOptions options = virtualMachineId(\"42\");\n      assertEquals(ImmutableList.of(\"42\"), options.buildQueryParameters().get(\"virtualmachineid\"));\n   }\n\n   public void testZoneId() {\n      ListHostsOptions options = new ListHostsOptions().zoneId(\"42\");\n      assertEquals(ImmutableList.of(\"42\"), options.buildQueryParameters().get(\"zoneid\"));\n   }\n\n   public void testZoneIdStatic() {\n      ListHostsOptions options = zoneId(\"42\");\n      assertEquals(ImmutableList.of(\"42\"), options.buildQueryParameters().get(\"zoneid\"));\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/ListIPForwardingRulesOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.ListIPForwardingRulesOptions.Builder.tags;\nimport static org.jclouds.cloudstack.options.ListIPForwardingRulesOptions.Builder.IPAddressId;\nimport static org.jclouds.cloudstack.options.ListIPForwardingRulesOptions.Builder.accountInDomain;\nimport static org.jclouds.cloudstack.options.ListIPForwardingRulesOptions.Builder.domainId;\nimport static org.jclouds.cloudstack.options.ListIPForwardingRulesOptions.Builder.id;\nimport static org.jclouds.cloudstack.options.ListIPForwardingRulesOptions.Builder.virtualMachineId;\nimport static org.testng.Assert.assertEquals;\n\nimport com.google.common.collect.ImmutableMap;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tests behavior of {@code ListIPForwardingRulesOptions}\n */\n@Test(groups = \"unit\")\npublic class ListIPForwardingRulesOptionsTest {\n\n   public void testId() {\n      ListIPForwardingRulesOptions options = new ListIPForwardingRulesOptions().id(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testIdStatic() {\n      ListIPForwardingRulesOptions options = id(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testAccount() {\n      ListIPForwardingRulesOptions options = new ListIPForwardingRulesOptions().accountInDomain(\"account\", \"6\");\n      assertEquals(ImmutableList.of(\"account\"), options.buildQueryParameters().get(\"account\"));\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testAccountStatic() {\n      ListIPForwardingRulesOptions options = accountInDomain(\"account\", \"6\");\n      assertEquals(ImmutableList.of(\"account\"), options.buildQueryParameters().get(\"account\"));\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testName() {\n      ListIPForwardingRulesOptions options = new ListIPForwardingRulesOptions().IPAddressId(\"9\");\n      assertEquals(ImmutableList.of(\"9\"), options.buildQueryParameters().get(\"ipaddressid\"));\n   }\n\n   public void testNameStatic() {\n      ListIPForwardingRulesOptions options = IPAddressId(\"9\");\n      assertEquals(ImmutableList.of(\"9\"), options.buildQueryParameters().get(\"ipaddressid\"));\n   }\n\n   public void testDomainId() {\n      ListIPForwardingRulesOptions options = new ListIPForwardingRulesOptions().domainId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testDomainIdStatic() {\n      ListIPForwardingRulesOptions options = domainId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testVirtualMachineId() {\n      ListIPForwardingRulesOptions options = new ListIPForwardingRulesOptions().virtualMachineId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"virtualmachineid\"));\n   }\n\n   public void testVirtualMachineIdStatic() {\n      ListIPForwardingRulesOptions options = virtualMachineId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"virtualmachineid\"));\n   }\n\n   public void testTags() {\n      ListIPForwardingRulesOptions options = new ListIPForwardingRulesOptions().tags(ImmutableMap.of(\"tag1\", \"val1\", \"tag2\", \"val2\"));\n      assertEquals(ImmutableList.of(\"tag1\"), options.buildQueryParameters().get(\"tags[0].key\"));\n      assertEquals(ImmutableList.of(\"tag2\"), options.buildQueryParameters().get(\"tags[1].key\"));\n      assertEquals(ImmutableList.of(\"val1\"), options.buildQueryParameters().get(\"tags[0].value\"));\n      assertEquals(ImmutableList.of(\"val2\"), options.buildQueryParameters().get(\"tags[1].value\"));\n   }\n\n   public void testTagsStatic() {\n      ListIPForwardingRulesOptions options = tags(ImmutableMap.of(\"tag1\", \"val1\", \"tag2\", \"val2\"));\n      assertEquals(ImmutableList.of(\"tag1\"), options.buildQueryParameters().get(\"tags[0].key\"));\n      assertEquals(ImmutableList.of(\"tag2\"), options.buildQueryParameters().get(\"tags[1].key\"));\n      assertEquals(ImmutableList.of(\"val1\"), options.buildQueryParameters().get(\"tags[0].value\"));\n      assertEquals(ImmutableList.of(\"val2\"), options.buildQueryParameters().get(\"tags[1].value\"));\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/ListISOsOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.ListISOsOptions.Builder.tags;\nimport static org.jclouds.cloudstack.options.ListISOsOptions.Builder.bootable;\nimport static org.jclouds.cloudstack.options.ListISOsOptions.Builder.hypervisor;\nimport static org.jclouds.cloudstack.options.ListISOsOptions.Builder.id;\nimport static org.jclouds.cloudstack.options.ListISOsOptions.Builder.isNotReady;\nimport static org.jclouds.cloudstack.options.ListISOsOptions.Builder.isPrivate;\nimport static org.jclouds.cloudstack.options.ListISOsOptions.Builder.isPublic;\nimport static org.jclouds.cloudstack.options.ListISOsOptions.Builder.isReady;\nimport static org.jclouds.cloudstack.options.ListISOsOptions.Builder.isoFilter;\nimport static org.jclouds.cloudstack.options.ListISOsOptions.Builder.keyword;\nimport static org.jclouds.cloudstack.options.ListISOsOptions.Builder.name;\nimport static org.jclouds.cloudstack.options.ListISOsOptions.Builder.notBootable;\nimport static org.jclouds.cloudstack.options.ListISOsOptions.Builder.zoneId;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Set;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport org.jclouds.cloudstack.domain.ISO;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@link ListISOsOptions}\n */\n@Test(groups = \"unit\")\npublic class ListISOsOptionsTest {\n   private static final Set<String> TRUE = ImmutableSet.of(Boolean.toString(true));\n   private static final Set<String> FALSE = ImmutableSet.of(Boolean.toString(false));\n\n   public void testBootable() {\n      ListISOsOptions options = new ListISOsOptions().bootable();\n      assertEquals(options.buildQueryParameters().get(\"bootable\"), TRUE);\n   }\n\n   public void testBootableStatic() {\n      ListISOsOptions options = bootable();\n      assertEquals(options.buildQueryParameters().get(\"bootable\"), TRUE);\n   }\n\n   public void testNotBootable() {\n      ListISOsOptions options = new ListISOsOptions().notBootable();\n      assertEquals(options.buildQueryParameters().get(\"bootable\"), FALSE);\n   }\n\n   public void testNotBootableStatic() {\n      ListISOsOptions options = notBootable();\n      assertEquals(options.buildQueryParameters().get(\"bootable\"), FALSE);\n   }\n\n   public void testHypervisor() {\n      ListISOsOptions options = new ListISOsOptions().hypervisor(\"KVM\");\n      assertEquals(options.buildQueryParameters().get(\"hypervisor\"), ImmutableSet.of(\"KVM\"));\n   }\n\n   public void testHypervisorStatic() {\n      ListISOsOptions options = hypervisor(\"KVM\");\n      assertEquals(options.buildQueryParameters().get(\"hypervisor\"), ImmutableSet.of(\"KVM\"));\n   }\n\n   public void testId() {\n      ListISOsOptions options = new ListISOsOptions().id(\"6\");\n      assertEquals(options.buildQueryParameters().get(\"id\"), ImmutableSet.of(\"6\"));\n   }\n\n   public void testIdStatic() {\n      ListISOsOptions options = id(\"6\");\n      assertEquals(options.buildQueryParameters().get(\"id\"), ImmutableSet.of(\"6\"));\n   }\n\n   public void testISOFilter() {\n      ListISOsOptions options = new ListISOsOptions().isoFilter(ISO.ISOFilter.community);\n      assertEquals(options.buildQueryParameters().get(\"isofilter\"), ImmutableSet.of(ISO.ISOFilter.community.name()));\n   }\n\n   public void testISOFilterStatic() {\n      ListISOsOptions options = isoFilter(ISO.ISOFilter.community);\n      assertEquals(options.buildQueryParameters().get(\"isofilter\"), ImmutableSet.of(ISO.ISOFilter.community.name()));\n   }\n\n   public void testIsPublic() {\n      ListISOsOptions options = new ListISOsOptions().isPublic();\n      assertEquals(options.buildQueryParameters().get(\"ispublic\"), TRUE);\n   }\n\n   public void testIsPublicStatic() {\n      ListISOsOptions options = isPublic();\n      assertEquals(options.buildQueryParameters().get(\"ispublic\"), TRUE);\n   }\n\n   public void testIsPrivate() {\n      ListISOsOptions options = new ListISOsOptions().isPrivate();\n      assertEquals(options.buildQueryParameters().get(\"ispublic\"), FALSE);\n   }\n\n   public void testIsPrivateStatic() {\n      ListISOsOptions options = isPrivate();\n      assertEquals(options.buildQueryParameters().get(\"ispublic\"), FALSE);\n   }\n\n   public void testIsReady() {\n      ListISOsOptions options = new ListISOsOptions().isReady();\n      assertEquals(options.buildQueryParameters().get(\"isready\"), TRUE);\n   }\n\n   public void testIsReadyStatic() {\n      ListISOsOptions options = isReady();\n      assertEquals(options.buildQueryParameters().get(\"isready\"), TRUE);\n   }\n\n   public void testIsNotReady() {\n      ListISOsOptions options = new ListISOsOptions().isNotReady();\n      assertEquals(options.buildQueryParameters().get(\"isready\"), FALSE);\n   }\n\n   public void testIsNotReadyStatic() {\n      ListISOsOptions options = isNotReady();\n      assertEquals(options.buildQueryParameters().get(\"isready\"), FALSE);\n   }\n\n   public void testKeyword() {\n      ListISOsOptions options = new ListISOsOptions().keyword(\"text\");\n      assertEquals(options.buildQueryParameters().get(\"keyword\"), ImmutableSet.of(\"text\"));\n   }\n\n   public void testKeywordStatic() {\n      ListISOsOptions options = keyword(\"text\");\n      assertEquals(options.buildQueryParameters().get(\"keyword\"), ImmutableSet.of(\"text\"));\n   }\n\n   public void testName() {\n      ListISOsOptions options = new ListISOsOptions().name(\"text\");\n      assertEquals(options.buildQueryParameters().get(\"name\"), ImmutableSet.of(\"text\"));\n   }\n\n   public void testNameStatic() {\n      ListISOsOptions options = name(\"text\");\n      assertEquals(options.buildQueryParameters().get(\"name\"), ImmutableSet.of(\"text\"));\n   }\n\n   public void testZoneId() {\n      ListISOsOptions options = new ListISOsOptions().zoneId(\"6\");\n      assertEquals(ImmutableSet.of(\"6\"), options.buildQueryParameters().get(\"zoneid\"));\n   }\n\n   public void testZoneIdStatic() {\n      ListISOsOptions options = zoneId(\"6\");\n      assertEquals(ImmutableSet.of(\"6\"), options.buildQueryParameters().get(\"zoneid\"));\n   }\n\n   public void testTags() {\n      ListISOsOptions options = new ListISOsOptions().tags(ImmutableMap.of(\"tag1\", \"val1\", \"tag2\", \"val2\"));\n      assertEquals(ImmutableList.of(\"tag1\"), options.buildQueryParameters().get(\"tags[0].key\"));\n      assertEquals(ImmutableList.of(\"tag2\"), options.buildQueryParameters().get(\"tags[1].key\"));\n      assertEquals(ImmutableList.of(\"val1\"), options.buildQueryParameters().get(\"tags[0].value\"));\n      assertEquals(ImmutableList.of(\"val2\"), options.buildQueryParameters().get(\"tags[1].value\"));\n   }\n\n   public void testTagsStatic() {\n      ListISOsOptions options = tags(ImmutableMap.of(\"tag1\", \"val1\", \"tag2\", \"val2\"));\n      assertEquals(ImmutableList.of(\"tag1\"), options.buildQueryParameters().get(\"tags[0].key\"));\n      assertEquals(ImmutableList.of(\"tag2\"), options.buildQueryParameters().get(\"tags[1].key\"));\n      assertEquals(ImmutableList.of(\"val1\"), options.buildQueryParameters().get(\"tags[0].value\"));\n      assertEquals(ImmutableList.of(\"val2\"), options.buildQueryParameters().get(\"tags[1].value\"));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/ListLoadBalancerRulesOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.ListLoadBalancerRulesOptions.Builder.accountInDomain;\nimport static org.jclouds.cloudstack.options.ListLoadBalancerRulesOptions.Builder.domainId;\nimport static org.jclouds.cloudstack.options.ListLoadBalancerRulesOptions.Builder.id;\nimport static org.jclouds.cloudstack.options.ListLoadBalancerRulesOptions.Builder.name;\nimport static org.jclouds.cloudstack.options.ListLoadBalancerRulesOptions.Builder.page;\nimport static org.jclouds.cloudstack.options.ListLoadBalancerRulesOptions.Builder.pageSize;\nimport static org.jclouds.cloudstack.options.ListLoadBalancerRulesOptions.Builder.publicIPId;\nimport static org.jclouds.cloudstack.options.ListLoadBalancerRulesOptions.Builder.virtualMachineId;\nimport static org.jclouds.cloudstack.options.ListLoadBalancerRulesOptions.Builder.zoneId;\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tests behavior of {@code ListLoadBalancerRulesOptions}\n */\n@Test(groups = \"unit\")\npublic class ListLoadBalancerRulesOptionsTest {\n\n   public void testId() {\n      ListLoadBalancerRulesOptions options = new ListLoadBalancerRulesOptions().id(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testIdStatic() {\n      ListLoadBalancerRulesOptions options = id(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testAccount() {\n      ListLoadBalancerRulesOptions options = new ListLoadBalancerRulesOptions().accountInDomain(\"account\", \"6\");\n      assertEquals(ImmutableList.of(\"account\"), options.buildQueryParameters().get(\"account\"));\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testAccountStatic() {\n      ListLoadBalancerRulesOptions options = accountInDomain(\"account\", \"6\");\n      assertEquals(ImmutableList.of(\"account\"), options.buildQueryParameters().get(\"account\"));\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testName() {\n      ListLoadBalancerRulesOptions options = new ListLoadBalancerRulesOptions().name(\"name\");\n      assertEquals(ImmutableList.of(\"name\"), options.buildQueryParameters().get(\"name\"));\n   }\n\n   public void testNameStatic() {\n      ListLoadBalancerRulesOptions options = name(\"name\");\n      assertEquals(ImmutableList.of(\"name\"), options.buildQueryParameters().get(\"name\"));\n   }\n\n   public void testPublicIPId() {\n      ListLoadBalancerRulesOptions options = new ListLoadBalancerRulesOptions().publicIPId(\"9\");\n      assertEquals(ImmutableList.of(\"9\"), options.buildQueryParameters().get(\"publicipid\"));\n   }\n\n   public void testPublicIPIdStatic() {\n      ListLoadBalancerRulesOptions options = publicIPId(\"9\");\n      assertEquals(ImmutableList.of(\"9\"), options.buildQueryParameters().get(\"publicipid\"));\n   }\n\n   public void testDomainId() {\n      ListLoadBalancerRulesOptions options = new ListLoadBalancerRulesOptions().domainId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testDomainIdStatic() {\n      ListLoadBalancerRulesOptions options = domainId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testVirtualMachineId() {\n      ListLoadBalancerRulesOptions options = new ListLoadBalancerRulesOptions().virtualMachineId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"virtualmachineid\"));\n   }\n\n   public void testVirtualMachineIdStatic() {\n      ListLoadBalancerRulesOptions options = virtualMachineId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"virtualmachineid\"));\n   }\n\n   public void testZoneId() {\n      ListLoadBalancerRulesOptions options = new ListLoadBalancerRulesOptions().zoneId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"zoneid\"));\n   }\n\n   public void testZoneIdStatic() {\n      ListLoadBalancerRulesOptions options = zoneId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"zoneid\"));\n   }\n\n   public void testPage() {\n      ListLoadBalancerRulesOptions options = new ListLoadBalancerRulesOptions().page(6);\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"page\"));\n   }\n\n   public void testPageStatic() {\n      ListLoadBalancerRulesOptions options = page(6);\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"page\"));\n   }\n\n   public void testPageSize() {\n      ListLoadBalancerRulesOptions options = new ListLoadBalancerRulesOptions().pageSize(6);\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"pagesize\"));\n   }\n\n   public void testPageSizeStatic() {\n      ListLoadBalancerRulesOptions options = pageSize(6);\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"pagesize\"));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/ListNetworkOfferingsOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.ListNetworkOfferingsOptions.Builder.availability;\nimport static org.jclouds.cloudstack.options.ListNetworkOfferingsOptions.Builder.displayText;\nimport static org.jclouds.cloudstack.options.ListNetworkOfferingsOptions.Builder.id;\nimport static org.jclouds.cloudstack.options.ListNetworkOfferingsOptions.Builder.isDefault;\nimport static org.jclouds.cloudstack.options.ListNetworkOfferingsOptions.Builder.isShared;\nimport static org.jclouds.cloudstack.options.ListNetworkOfferingsOptions.Builder.specifyVLAN;\nimport static org.jclouds.cloudstack.options.ListNetworkOfferingsOptions.Builder.trafficType;\nimport static org.jclouds.cloudstack.options.ListNetworkOfferingsOptions.Builder.zoneId;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.cloudstack.domain.NetworkOfferingAvailabilityType;\nimport org.jclouds.cloudstack.domain.TrafficType;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tests behavior of {@code ListNetworkOfferingsOptions}\n */\n@Test(groups = \"unit\")\npublic class ListNetworkOfferingsOptionsTest {\n\n   public void testIsDefault() {\n      ListNetworkOfferingsOptions options = new ListNetworkOfferingsOptions().isDefault(true);\n      assertEquals(ImmutableList.of(\"true\"), options.buildQueryParameters().get(\"isdefault\"));\n   }\n\n   public void testIsDefaultStatic() {\n      ListNetworkOfferingsOptions options = isDefault(true);\n      assertEquals(ImmutableList.of(\"true\"), options.buildQueryParameters().get(\"isdefault\"));\n   }\n\n   public void testIsShared() {\n      ListNetworkOfferingsOptions options = new ListNetworkOfferingsOptions().isShared(true);\n      assertEquals(ImmutableList.of(\"true\"), options.buildQueryParameters().get(\"isshared\"));\n   }\n\n   public void testIsSharedStatic() {\n      ListNetworkOfferingsOptions options = isShared(true);\n      assertEquals(ImmutableList.of(\"true\"), options.buildQueryParameters().get(\"isshared\"));\n   }\n\n   public void testId() {\n      ListNetworkOfferingsOptions options = new ListNetworkOfferingsOptions().id(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testIdStatic() {\n      ListNetworkOfferingsOptions options = id(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testZoneId() {\n      ListNetworkOfferingsOptions options = new ListNetworkOfferingsOptions().zoneId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"zoneid\"));\n   }\n\n   public void testZoneIdStatic() {\n      ListNetworkOfferingsOptions options = zoneId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"zoneid\"));\n   }\n\n   public void testSpecifyVLAN() {\n      ListNetworkOfferingsOptions options = new ListNetworkOfferingsOptions().specifyVLAN(true);\n      assertEquals(ImmutableList.of(\"true\"), options.buildQueryParameters().get(\"specifyvlan\"));\n   }\n\n   public void testSpecifyVLANStatic() {\n      ListNetworkOfferingsOptions options = specifyVLAN(true);\n      assertEquals(ImmutableList.of(\"true\"), options.buildQueryParameters().get(\"specifyvlan\"));\n   }\n\n   public void testAvailability() {\n      ListNetworkOfferingsOptions options =\n         new ListNetworkOfferingsOptions().availability(NetworkOfferingAvailabilityType.REQUIRED);\n      assertEquals(ImmutableList.of(\"Required\"), options.buildQueryParameters().get(\"availability\"));\n   }\n\n   public void testAvailabilityStatic() {\n      ListNetworkOfferingsOptions options = availability(NetworkOfferingAvailabilityType.REQUIRED);\n      assertEquals(ImmutableList.of(\"Required\"), options.buildQueryParameters().get(\"availability\"));\n   }\n\n   public void testTrafficType() {\n      ListNetworkOfferingsOptions options = new ListNetworkOfferingsOptions().trafficType(TrafficType.GUEST);\n      assertEquals(ImmutableList.of(\"Guest\"), options.buildQueryParameters().get(\"traffictype\"));\n   }\n\n   public void testTrafficTypeStatic() {\n      ListNetworkOfferingsOptions options = trafficType(TrafficType.GUEST);\n      assertEquals(ImmutableList.of(\"Guest\"), options.buildQueryParameters().get(\"traffictype\"));\n   }\n\n   public void testName() {\n      ListNetworkOfferingsOptions options = new ListNetworkOfferingsOptions().id(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testNameStatic() {\n      ListNetworkOfferingsOptions options = id(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testDisplayText() {\n      ListNetworkOfferingsOptions options = new ListNetworkOfferingsOptions().displayText(\"text\");\n      assertEquals(ImmutableList.of(\"text\"), options.buildQueryParameters().get(\"displaytext\"));\n   }\n\n   public void testDisplayTextStatic() {\n      ListNetworkOfferingsOptions options = displayText(\"text\");\n      assertEquals(ImmutableList.of(\"text\"), options.buildQueryParameters().get(\"displaytext\"));\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/ListNetworksOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.ListNetworksOptions.Builder.tags;\nimport static org.jclouds.cloudstack.options.ListNetworksOptions.Builder.accountInDomain;\nimport static org.jclouds.cloudstack.options.ListNetworksOptions.Builder.domainId;\nimport static org.jclouds.cloudstack.options.ListNetworksOptions.Builder.id;\nimport static org.jclouds.cloudstack.options.ListNetworksOptions.Builder.isDefault;\nimport static org.jclouds.cloudstack.options.ListNetworksOptions.Builder.isShared;\nimport static org.jclouds.cloudstack.options.ListNetworksOptions.Builder.isSystem;\nimport static org.jclouds.cloudstack.options.ListNetworksOptions.Builder.trafficType;\nimport static org.jclouds.cloudstack.options.ListNetworksOptions.Builder.type;\nimport static org.jclouds.cloudstack.options.ListNetworksOptions.Builder.zoneId;\nimport static org.testng.Assert.assertEquals;\n\nimport com.google.common.collect.ImmutableMap;\nimport org.jclouds.cloudstack.domain.NetworkType;\nimport org.jclouds.cloudstack.domain.TrafficType;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tests behavior of {@code ListNetworksOptions}\n */\n@Test(groups = \"unit\")\npublic class ListNetworksOptionsTest {\n\n   public void testIsDefault() {\n      ListNetworksOptions options = new ListNetworksOptions().isDefault(true);\n      assertEquals(ImmutableList.of(\"true\"), options.buildQueryParameters().get(\"isdefault\"));\n   }\n\n   public void testIsDefaultStatic() {\n      ListNetworksOptions options = isDefault(true);\n      assertEquals(ImmutableList.of(\"true\"), options.buildQueryParameters().get(\"isdefault\"));\n   }\n\n   public void testIsSystem() {\n      ListNetworksOptions options = new ListNetworksOptions().isSystem(true);\n      assertEquals(ImmutableList.of(\"true\"), options.buildQueryParameters().get(\"issystem\"));\n   }\n\n   public void testIsSystemStatic() {\n      ListNetworksOptions options = isSystem(true);\n      assertEquals(ImmutableList.of(\"true\"), options.buildQueryParameters().get(\"issystem\"));\n   }\n\n   public void testIsShared() {\n      ListNetworksOptions options = new ListNetworksOptions().isShared(true);\n      assertEquals(ImmutableList.of(\"true\"), options.buildQueryParameters().get(\"isshared\"));\n   }\n\n   public void testIsSharedStatic() {\n      ListNetworksOptions options = isShared(true);\n      assertEquals(ImmutableList.of(\"true\"), options.buildQueryParameters().get(\"isshared\"));\n   }\n\n   public void testId() {\n      ListNetworksOptions options = new ListNetworksOptions().id(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testIdStatic() {\n      ListNetworksOptions options = id(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testDomainId() {\n      ListNetworksOptions options = new ListNetworksOptions().domainId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testDomainIdStatic() {\n      ListNetworksOptions options = domainId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testAccountId() {\n      ListNetworksOptions options = new ListNetworksOptions().accountInDomain(\"moo\", \"1\");\n      assertEquals(ImmutableList.of(\"1\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testAccountIdStatic() {\n      ListNetworksOptions options = accountInDomain(\"moo\", \"1\");\n      assertEquals(ImmutableList.of(\"moo\"), options.buildQueryParameters().get(\"account\"));\n      assertEquals(ImmutableList.of(\"1\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testTrafficType() {\n      ListNetworksOptions options = new ListNetworksOptions().trafficType(TrafficType.GUEST);\n      assertEquals(ImmutableList.of(\"Guest\"), options.buildQueryParameters().get(\"traffictype\"));\n   }\n\n   public void testTrafficTypeStatic() {\n      ListNetworksOptions options = trafficType(TrafficType.GUEST);\n      assertEquals(ImmutableList.of(\"Guest\"), options.buildQueryParameters().get(\"traffictype\"));\n   }\n\n   public void testName() {\n      ListNetworksOptions options = new ListNetworksOptions().id(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testNameStatic() {\n      ListNetworksOptions options = id(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testZoneId() {\n      ListNetworksOptions options = new ListNetworksOptions().zoneId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"zoneid\"));\n   }\n\n   public void testZoneIdStatic() {\n      ListNetworksOptions options = zoneId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"zoneid\"));\n   }\n\n   public void testType() {\n      ListNetworksOptions options = new ListNetworksOptions().type(NetworkType.ADVANCED);\n      assertEquals(ImmutableList.of(\"Advanced\"), options.buildQueryParameters().get(\"type\"));\n   }\n\n   public void testTypeStatic() {\n      ListNetworksOptions options = type(NetworkType.ADVANCED);\n      assertEquals(ImmutableList.of(\"Advanced\"), options.buildQueryParameters().get(\"type\"));\n   }\n\n   public void testTags() {\n      ListNetworksOptions options = new ListNetworksOptions().tags(ImmutableMap.of(\"tag1\", \"val1\", \"tag2\", \"val2\"));\n      assertEquals(ImmutableList.of(\"tag1\"), options.buildQueryParameters().get(\"tags[0].key\"));\n      assertEquals(ImmutableList.of(\"tag2\"), options.buildQueryParameters().get(\"tags[1].key\"));\n      assertEquals(ImmutableList.of(\"val1\"), options.buildQueryParameters().get(\"tags[0].value\"));\n      assertEquals(ImmutableList.of(\"val2\"), options.buildQueryParameters().get(\"tags[1].value\"));\n   }\n\n   public void testTagsStatic() {\n      ListNetworksOptions options = tags(ImmutableMap.of(\"tag1\", \"val1\", \"tag2\", \"val2\"));\n      assertEquals(ImmutableList.of(\"tag1\"), options.buildQueryParameters().get(\"tags[0].key\"));\n      assertEquals(ImmutableList.of(\"tag2\"), options.buildQueryParameters().get(\"tags[1].key\"));\n      assertEquals(ImmutableList.of(\"val1\"), options.buildQueryParameters().get(\"tags[0].value\"));\n      assertEquals(ImmutableList.of(\"val2\"), options.buildQueryParameters().get(\"tags[1].value\"));\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/ListOSTypesOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.ListOSTypesOptions.Builder.OSCategoryId;\nimport static org.jclouds.cloudstack.options.ListOSTypesOptions.Builder.id;\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tests behavior of {@code ListOSTypesOptions}\n */\n@Test(groups = \"unit\")\npublic class ListOSTypesOptionsTest {\n\n   public void testId() {\n      ListOSTypesOptions options = new ListOSTypesOptions().id(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testIdStatic() {\n      ListOSTypesOptions options = id(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testOSCategoryId() {\n      ListOSTypesOptions options = new ListOSTypesOptions().OSCategoryId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"oscategoryid\"));\n   }\n\n   public void testOSCategoryIdStatic() {\n      ListOSTypesOptions options = OSCategoryId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"oscategoryid\"));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/ListPodsOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.ListPodsOptions.Builder.allocationState;\nimport static org.jclouds.cloudstack.options.ListPodsOptions.Builder.id;\nimport static org.jclouds.cloudstack.options.ListPodsOptions.Builder.keyword;\nimport static org.jclouds.cloudstack.options.ListPodsOptions.Builder.name;\nimport static org.jclouds.cloudstack.options.ListPodsOptions.Builder.zoneId;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.cloudstack.domain.AllocationState;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tests behavior of {@code ListPodsOptions}\n */\n@Test(groups = \"unit\")\npublic class ListPodsOptionsTest {\n\n   public void testId() {\n      ListPodsOptions options = new ListPodsOptions().id(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testIdStatic() {\n      ListPodsOptions options = id(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testAllocationState() {\n      ListPodsOptions options = new ListPodsOptions().allocationState(AllocationState.ENABLED);\n      assertEquals(ImmutableList.of(\"Enabled\"), options.buildQueryParameters().get(\"allocationstate\"));\n   }\n\n   public void testAllocationStateStatic() {\n      ListPodsOptions options = allocationState(AllocationState.ENABLED);\n      assertEquals(ImmutableList.of(\"Enabled\"), options.buildQueryParameters().get(\"allocationstate\"));\n   }\n\n   public void testKeyword() {\n      ListPodsOptions options = new ListPodsOptions().keyword(\"fred\");\n      assertEquals(ImmutableList.of(\"fred\"), options.buildQueryParameters().get(\"keyword\"));\n   }\n\n   public void testKeywordStatic() {\n      ListPodsOptions options = keyword(\"fred\");\n      assertEquals(ImmutableList.of(\"fred\"), options.buildQueryParameters().get(\"keyword\"));\n   }\n\n   public void testName() {\n      ListPodsOptions options = new ListPodsOptions().name(\"bob\");\n      assertEquals(ImmutableList.of(\"bob\"), options.buildQueryParameters().get(\"name\"));\n   }\n\n   public void testNameStatic() {\n      ListPodsOptions options = name(\"bob\");\n      assertEquals(ImmutableList.of(\"bob\"), options.buildQueryParameters().get(\"name\"));\n   }\n\n   public void testZoneId() {\n      ListPodsOptions options = new ListPodsOptions().zoneId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"zoneid\"));\n   }\n\n   public void testZoneIdStatic() {\n      ListPodsOptions options = zoneId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"zoneid\"));\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/ListPortForwardingRulesOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.ListPortForwardingRulesOptions.Builder.tags;\nimport static org.jclouds.cloudstack.options.ListPortForwardingRulesOptions.Builder.accountInDomain;\nimport static org.jclouds.cloudstack.options.ListPortForwardingRulesOptions.Builder.domainId;\nimport static org.jclouds.cloudstack.options.ListPortForwardingRulesOptions.Builder.ipAddressId;\nimport static org.testng.Assert.assertEquals;\n\nimport com.google.common.collect.ImmutableMap;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tests behavior of {@code ListPortForwardingRulesOptions}\n */\n@Test(groups = \"unit\")\npublic class ListPortForwardingRulesOptionsTest {\n\n   public void testAccount() {\n      ListPortForwardingRulesOptions options = new ListPortForwardingRulesOptions().accountInDomain(\"account\", \"6\");\n      assertEquals(ImmutableList.of(\"account\"), options.buildQueryParameters().get(\"account\"));\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testAccountStatic() {\n      ListPortForwardingRulesOptions options = accountInDomain(\"account\", \"6\");\n      assertEquals(ImmutableList.of(\"account\"), options.buildQueryParameters().get(\"account\"));\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testName() {\n      ListPortForwardingRulesOptions options = new ListPortForwardingRulesOptions().ipAddressId(\"9\");\n      assertEquals(ImmutableList.of(\"9\"), options.buildQueryParameters().get(\"ipaddressid\"));\n   }\n\n   public void testNameStatic() {\n      ListPortForwardingRulesOptions options = ipAddressId(\"9\");\n      assertEquals(ImmutableList.of(\"9\"), options.buildQueryParameters().get(\"ipaddressid\"));\n   }\n\n   public void testDomainId() {\n      ListPortForwardingRulesOptions options = new ListPortForwardingRulesOptions().domainId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testDomainIdStatic() {\n      ListPortForwardingRulesOptions options = domainId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testTags() {\n      ListPortForwardingRulesOptions options = new ListPortForwardingRulesOptions().tags(ImmutableMap.of(\"tag1\", \"val1\", \"tag2\", \"val2\"));\n      assertEquals(ImmutableList.of(\"tag1\"), options.buildQueryParameters().get(\"tags[0].key\"));\n      assertEquals(ImmutableList.of(\"tag2\"), options.buildQueryParameters().get(\"tags[1].key\"));\n      assertEquals(ImmutableList.of(\"val1\"), options.buildQueryParameters().get(\"tags[0].value\"));\n      assertEquals(ImmutableList.of(\"val2\"), options.buildQueryParameters().get(\"tags[1].value\"));\n   }\n\n   public void testTagsStatic() {\n      ListPortForwardingRulesOptions options = tags(ImmutableMap.of(\"tag1\", \"val1\", \"tag2\", \"val2\"));\n      assertEquals(ImmutableList.of(\"tag1\"), options.buildQueryParameters().get(\"tags[0].key\"));\n      assertEquals(ImmutableList.of(\"tag2\"), options.buildQueryParameters().get(\"tags[1].key\"));\n      assertEquals(ImmutableList.of(\"val1\"), options.buildQueryParameters().get(\"tags[0].value\"));\n      assertEquals(ImmutableList.of(\"val2\"), options.buildQueryParameters().get(\"tags[1].value\"));\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/ListProjectsOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\n\nimport static org.testng.Assert.assertEquals;\n\nimport static org.jclouds.cloudstack.options.ListProjectsOptions.Builder.displayText;\nimport static org.jclouds.cloudstack.options.ListProjectsOptions.Builder.domainId;\nimport static org.jclouds.cloudstack.options.ListProjectsOptions.Builder.id;\nimport static org.jclouds.cloudstack.options.ListProjectsOptions.Builder.keyword;\nimport static org.jclouds.cloudstack.options.ListProjectsOptions.Builder.name;\nimport static org.jclouds.cloudstack.options.ListProjectsOptions.Builder.page;\nimport static org.jclouds.cloudstack.options.ListProjectsOptions.Builder.pageSize;\nimport static org.jclouds.cloudstack.options.ListProjectsOptions.Builder.state;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n\n\n/**\n * Tests behavior of {@code ListProjectsOptions}\n */\n@Test(groups = \"unit\")\npublic class ListProjectsOptionsTest {\n\n   public void testId() {\n      ListProjectsOptions options = new ListProjectsOptions().id(\"42\");\n      assertEquals(ImmutableList.of(\"42\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testIdStatic() {\n      ListProjectsOptions options = id(\"42\");\n      assertEquals(ImmutableList.of(\"42\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testKeyword() {\n      ListProjectsOptions options = new ListProjectsOptions().keyword(\"Enabled\");\n      assertEquals(ImmutableList.of(\"Enabled\"), options.buildQueryParameters().get(\"keyword\"));\n   }\n\n   public void testKeywordStatic() {\n      ListProjectsOptions options = keyword(\"Enabled\");\n      assertEquals(ImmutableList.of(\"Enabled\"), options.buildQueryParameters().get(\"keyword\"));\n   }\n\n   public void testName() {\n      ListProjectsOptions options = new ListProjectsOptions().name(\"Project Name\");\n      assertEquals(ImmutableList.of(\"Project Name\"), options.buildQueryParameters().get(\"name\"));\n   }\n\n   public void testNameStatic() {\n      ListProjectsOptions options = name(\"Project Name\");\n      assertEquals(ImmutableList.of(\"Project Name\"), options.buildQueryParameters().get(\"name\"));\n   }\n\n   public void testPage() {\n      ListProjectsOptions options = new ListProjectsOptions().page(42L);\n      assertEquals(ImmutableList.of(\"42\"), options.buildQueryParameters().get(\"page\"));\n   }\n\n   public void testPageStatic() {\n      ListProjectsOptions options = page(42L);\n      assertEquals(ImmutableList.of(\"42\"), options.buildQueryParameters().get(\"page\"));\n   }\n\n   public void testPageSize() {\n      ListProjectsOptions options = new ListProjectsOptions().pageSize(42L);\n      assertEquals(ImmutableList.of(\"42\"), options.buildQueryParameters().get(\"pagesize\"));\n   }\n\n   public void testPageSizeStatic() {\n      ListProjectsOptions options = pageSize(42L);\n      assertEquals(ImmutableList.of(\"42\"), options.buildQueryParameters().get(\"pagesize\"));\n   }\n\n   public void testState() {\n      ListProjectsOptions options = new ListProjectsOptions().state(\"Up\");\n      assertEquals(ImmutableList.of(\"Up\"), options.buildQueryParameters().get(\"state\"));\n   }\n\n   public void testStateStatic() {\n      ListProjectsOptions options = state(\"Up\");\n      assertEquals(ImmutableList.of(\"Up\"), options.buildQueryParameters().get(\"state\"));\n   }\n   \n   public void testDisplayText() {\n      ListProjectsOptions options = new ListProjectsOptions().displayText(\"My Project\");\n      assertEquals(ImmutableList.of(\"My Project\"), options.buildQueryParameters().get(\"displaytext\"));\n   }\n\n   public void testDisplayTextStatic() {\n      ListProjectsOptions options = displayText(\"My Project\");\n      assertEquals(ImmutableList.of(\"My Project\"), options.buildQueryParameters().get(\"displaytext\"));\n   }\n           \n   public void testDomainId() {\n      ListProjectsOptions options = new ListProjectsOptions().domainId(\"111-111-111\");\n      assertEquals(ImmutableList.of(\"111-111-111\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testDomainIdStatic() {\n      ListProjectsOptions options = domainId(\"111-111-111\");\n      assertEquals(ImmutableList.of(\"111-111-111\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/ListPublicIPAddressesOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.ListPublicIPAddressesOptions.Builder.tags;\nimport static org.jclouds.cloudstack.options.ListPublicIPAddressesOptions.Builder.IPAddress;\nimport static org.jclouds.cloudstack.options.ListPublicIPAddressesOptions.Builder.VLANId;\nimport static org.jclouds.cloudstack.options.ListPublicIPAddressesOptions.Builder.accountInDomain;\nimport static org.jclouds.cloudstack.options.ListPublicIPAddressesOptions.Builder.allocatedOnly;\nimport static org.jclouds.cloudstack.options.ListPublicIPAddressesOptions.Builder.domainId;\nimport static org.jclouds.cloudstack.options.ListPublicIPAddressesOptions.Builder.id;\nimport static org.jclouds.cloudstack.options.ListPublicIPAddressesOptions.Builder.networkId;\nimport static org.jclouds.cloudstack.options.ListPublicIPAddressesOptions.Builder.usesVirtualNetwork;\nimport static org.jclouds.cloudstack.options.ListPublicIPAddressesOptions.Builder.zoneId;\nimport static org.testng.Assert.assertEquals;\n\nimport com.google.common.collect.ImmutableMap;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tests behavior of {@code ListIPAddressesOptions}\n */\n@Test(groups = \"unit\")\npublic class ListPublicIPAddressesOptionsTest {\n\n   public void testAllocatedOnly() {\n      ListPublicIPAddressesOptions options = new ListPublicIPAddressesOptions().allocatedOnly(true);\n      assertEquals(ImmutableList.of(\"true\"), options.buildQueryParameters().get(\"allocatedonly\"));\n   }\n\n   public void testAllocatedOnlyStatic() {\n      ListPublicIPAddressesOptions options = allocatedOnly(true);\n      assertEquals(ImmutableList.of(\"true\"), options.buildQueryParameters().get(\"allocatedonly\"));\n   }\n\n   public void testVLANId() {\n      ListPublicIPAddressesOptions options = new ListPublicIPAddressesOptions().VLANId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"vlanid\"));\n   }\n\n   public void testVLANIdStatic() {\n      ListPublicIPAddressesOptions options = VLANId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"vlanid\"));\n   }\n\n   public void testNetworkId() {\n      ListPublicIPAddressesOptions options = new ListPublicIPAddressesOptions().networkId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"networkid\"));\n   }\n\n   public void testNetworkIdStatic() {\n      ListPublicIPAddressesOptions options = networkId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"networkid\"));\n   }\n\n   public void testIPAddress() {\n      ListPublicIPAddressesOptions options = new ListPublicIPAddressesOptions().IPAddress(\"10.1.1.1\");\n      assertEquals(ImmutableList.of(\"10.1.1.1\"), options.buildQueryParameters().get(\"ipaddress\"));\n   }\n\n   public void testIPAddressStatic() {\n      ListPublicIPAddressesOptions options = IPAddress(\"10.1.1.1\");\n      assertEquals(ImmutableList.of(\"10.1.1.1\"), options.buildQueryParameters().get(\"ipaddress\"));\n   }\n\n   public void testAccountInDomainId() {\n      ListPublicIPAddressesOptions options = new ListPublicIPAddressesOptions().accountInDomain(\"adrian\", \"6\");\n      assertEquals(ImmutableList.of(\"adrian\"), options.buildQueryParameters().get(\"account\"));\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testAccountInDomainIdStatic() {\n      ListPublicIPAddressesOptions options = accountInDomain(\"adrian\", \"6\");\n      assertEquals(ImmutableList.of(\"adrian\"), options.buildQueryParameters().get(\"account\"));\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testZoneId() {\n      ListPublicIPAddressesOptions options = new ListPublicIPAddressesOptions().zoneId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"zoneid\"));\n   }\n\n   public void testZoneIdStatic() {\n      ListPublicIPAddressesOptions options = zoneId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"zoneid\"));\n   }\n\n   public void testUsingVirtualNetwork() {\n      ListPublicIPAddressesOptions options = new ListPublicIPAddressesOptions().usesVirtualNetwork(true);\n      assertEquals(ImmutableList.of(\"true\"), options.buildQueryParameters().get(\"forvirtualnetwork\"));\n   }\n\n   public void testUsingVirtualNetworkStatic() {\n      ListPublicIPAddressesOptions options = usesVirtualNetwork(true);\n      assertEquals(ImmutableList.of(\"true\"), options.buildQueryParameters().get(\"forvirtualnetwork\"));\n   }\n\n   public void testId() {\n      ListPublicIPAddressesOptions options = new ListPublicIPAddressesOptions().id(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testDomainId() {\n      ListPublicIPAddressesOptions options = new ListPublicIPAddressesOptions().domainId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testIdStatic() {\n      ListPublicIPAddressesOptions options = id(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testDomainIdStatic() {\n      ListPublicIPAddressesOptions options = domainId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testTags() {\n      ListPublicIPAddressesOptions options = new ListPublicIPAddressesOptions().tags(ImmutableMap.of(\"tag1\", \"val1\", \"tag2\", \"val2\"));\n      assertEquals(ImmutableList.of(\"tag1\"), options.buildQueryParameters().get(\"tags[0].key\"));\n      assertEquals(ImmutableList.of(\"tag2\"), options.buildQueryParameters().get(\"tags[1].key\"));\n      assertEquals(ImmutableList.of(\"val1\"), options.buildQueryParameters().get(\"tags[0].value\"));\n      assertEquals(ImmutableList.of(\"val2\"), options.buildQueryParameters().get(\"tags[1].value\"));\n   }\n\n   public void testTagsStatic() {\n      ListPublicIPAddressesOptions options = tags(ImmutableMap.of(\"tag1\", \"val1\", \"tag2\", \"val2\"));\n      assertEquals(ImmutableList.of(\"tag1\"), options.buildQueryParameters().get(\"tags[0].key\"));\n      assertEquals(ImmutableList.of(\"tag2\"), options.buildQueryParameters().get(\"tags[1].key\"));\n      assertEquals(ImmutableList.of(\"val1\"), options.buildQueryParameters().get(\"tags[0].value\"));\n      assertEquals(ImmutableList.of(\"val2\"), options.buildQueryParameters().get(\"tags[1].value\"));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/ListSecurityGroupsOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.ListSecurityGroupsOptions.Builder.tags;\nimport static org.jclouds.cloudstack.options.ListSecurityGroupsOptions.Builder.accountInDomain;\nimport static org.jclouds.cloudstack.options.ListSecurityGroupsOptions.Builder.domainId;\nimport static org.jclouds.cloudstack.options.ListSecurityGroupsOptions.Builder.id;\nimport static org.jclouds.cloudstack.options.ListSecurityGroupsOptions.Builder.named;\nimport static org.jclouds.cloudstack.options.ListSecurityGroupsOptions.Builder.virtualMachineId;\nimport static org.testng.Assert.assertEquals;\n\nimport com.google.common.collect.ImmutableMap;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tests behavior of {@code ListSecurityGroupsOptions}\n */\n@Test(groups = \"unit\")\npublic class ListSecurityGroupsOptionsTest {\n\n   public void testId() {\n      ListSecurityGroupsOptions options = new ListSecurityGroupsOptions().id(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testIdStatic() {\n      ListSecurityGroupsOptions options = id(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testAccount() {\n      ListSecurityGroupsOptions options = new ListSecurityGroupsOptions().accountInDomain(\"account\", \"1\");\n      assertEquals(ImmutableList.of(\"account\"), options.buildQueryParameters().get(\"account\"));\n   }\n\n   public void testAccountStatic() {\n      ListSecurityGroupsOptions options = accountInDomain(\"account\", \"1\");\n      assertEquals(ImmutableList.of(\"account\"), options.buildQueryParameters().get(\"account\"));\n   }\n\n   public void testName() {\n      ListSecurityGroupsOptions options = new ListSecurityGroupsOptions().named(\"securityGroupName\");\n      assertEquals(ImmutableList.of(\"securityGroupName\"), options.buildQueryParameters().get(\"securitygroupname\"));\n   }\n\n   public void testNameStatic() {\n      ListSecurityGroupsOptions options = named(\"securityGroupName\");\n      assertEquals(ImmutableList.of(\"securityGroupName\"), options.buildQueryParameters().get(\"securitygroupname\"));\n   }\n\n   public void testDomainId() {\n      ListSecurityGroupsOptions options = new ListSecurityGroupsOptions().domainId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testDomainIdStatic() {\n      ListSecurityGroupsOptions options = domainId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testVirtualMachineId() {\n      ListSecurityGroupsOptions options = new ListSecurityGroupsOptions().virtualMachineId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"virtualmachineid\"));\n   }\n\n   public void testVirtualMachineIdStatic() {\n      ListSecurityGroupsOptions options = virtualMachineId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"virtualmachineid\"));\n   }\n\n   public void testTags() {\n      ListSecurityGroupsOptions options = new ListSecurityGroupsOptions().tags(ImmutableMap.of(\"tag1\", \"val1\", \"tag2\", \"val2\"));\n      assertEquals(ImmutableList.of(\"tag1\"), options.buildQueryParameters().get(\"tags[0].key\"));\n      assertEquals(ImmutableList.of(\"tag2\"), options.buildQueryParameters().get(\"tags[1].key\"));\n      assertEquals(ImmutableList.of(\"val1\"), options.buildQueryParameters().get(\"tags[0].value\"));\n      assertEquals(ImmutableList.of(\"val2\"), options.buildQueryParameters().get(\"tags[1].value\"));\n   }\n\n   public void testTagsStatic() {\n      ListSecurityGroupsOptions options = tags(ImmutableMap.of(\"tag1\", \"val1\", \"tag2\", \"val2\"));\n      assertEquals(ImmutableList.of(\"tag1\"), options.buildQueryParameters().get(\"tags[0].key\"));\n      assertEquals(ImmutableList.of(\"tag2\"), options.buildQueryParameters().get(\"tags[1].key\"));\n      assertEquals(ImmutableList.of(\"val1\"), options.buildQueryParameters().get(\"tags[0].value\"));\n      assertEquals(ImmutableList.of(\"val2\"), options.buildQueryParameters().get(\"tags[1].value\"));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/ListServiceOfferingsOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.ListServiceOfferingsOptions.Builder.domainId;\nimport static org.jclouds.cloudstack.options.ListServiceOfferingsOptions.Builder.id;\nimport static org.jclouds.cloudstack.options.ListServiceOfferingsOptions.Builder.name;\nimport static org.jclouds.cloudstack.options.ListServiceOfferingsOptions.Builder.virtualMachineId;\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tests behavior of {@code ListServiceOfferingsOptions}\n */\n@Test(groups = \"unit\")\npublic class ListServiceOfferingsOptionsTest {\n\n   public void testId() {\n      ListServiceOfferingsOptions options = new ListServiceOfferingsOptions().id(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testIdStatic() {\n      ListServiceOfferingsOptions options = id(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testName() {\n      ListServiceOfferingsOptions options = new ListServiceOfferingsOptions().name(\"name\");\n      assertEquals(ImmutableList.of(\"name\"), options.buildQueryParameters().get(\"name\"));\n   }\n\n   public void testNameStatic() {\n      ListServiceOfferingsOptions options = name(\"name\");\n      assertEquals(ImmutableList.of(\"name\"), options.buildQueryParameters().get(\"name\"));\n   }\n\n   public void testDomainId() {\n      ListServiceOfferingsOptions options = new ListServiceOfferingsOptions().domainId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testDomainIdStatic() {\n      ListServiceOfferingsOptions options = domainId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testVirtualMachineId() {\n      ListServiceOfferingsOptions options = new ListServiceOfferingsOptions().virtualMachineId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"virtualmachineid\"));\n   }\n\n   public void testVirtualMachineIdStatic() {\n      ListServiceOfferingsOptions options = virtualMachineId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"virtualmachineid\"));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/ListStoragePoolsOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.ListStoragePoolsOptions.Builder.clusterId;\nimport static org.jclouds.cloudstack.options.ListStoragePoolsOptions.Builder.id;\nimport static org.jclouds.cloudstack.options.ListStoragePoolsOptions.Builder.ipAddress;\nimport static org.jclouds.cloudstack.options.ListStoragePoolsOptions.Builder.keyword;\nimport static org.jclouds.cloudstack.options.ListStoragePoolsOptions.Builder.name;\nimport static org.jclouds.cloudstack.options.ListStoragePoolsOptions.Builder.path;\nimport static org.jclouds.cloudstack.options.ListStoragePoolsOptions.Builder.podId;\nimport static org.jclouds.cloudstack.options.ListStoragePoolsOptions.Builder.zoneId;\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Test for the ListStoragePoolsOptions class.\n */\n@Test(groups = \"unit\")\npublic class ListStoragePoolsOptionsTest {\n\n   public void testClusterId() {\n      ListStoragePoolsOptions options = new ListStoragePoolsOptions().clusterId(\"14\");\n      assertEquals(ImmutableList.of(14 + \"\"), options.buildQueryParameters().get(\"clusterid\"));\n   }\n\n   public void testClusterIdStatic() {\n      ListStoragePoolsOptions options = clusterId(\"14\");\n      assertEquals(ImmutableList.of(14 + \"\"), options.buildQueryParameters().get(\"clusterid\"));\n   }\n\n   public void testId() {\n      ListStoragePoolsOptions options = new ListStoragePoolsOptions().id(\"15\");\n      assertEquals(ImmutableList.of(15 + \"\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testIdStatic() {\n      ListStoragePoolsOptions options = id(\"15\");\n      assertEquals(ImmutableList.of(15 + \"\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testIpAddress() {\n      ListStoragePoolsOptions options = new ListStoragePoolsOptions().ipAddress(\"192.168.42.42\");\n      assertEquals(ImmutableList.of(\"192.168.42.42\"), options.buildQueryParameters().get(\"ipaddress\"));\n   }\n\n   public void testIpAddressStatic() {\n      ListStoragePoolsOptions options = ipAddress(\"192.168.42.42\");\n      assertEquals(ImmutableList.of(\"192.168.42.42\"), options.buildQueryParameters().get(\"ipaddress\"));\n   }\n\n   public void testKeyword() {\n      ListStoragePoolsOptions options = new ListStoragePoolsOptions().keyword(\"fred\");\n      assertEquals(ImmutableList.of(\"fred\"), options.buildQueryParameters().get(\"keyword\"));\n   }\n\n   public void testKeywordStatic() {\n      ListStoragePoolsOptions options = keyword(\"fred\");\n      assertEquals(ImmutableList.of(\"fred\"), options.buildQueryParameters().get(\"keyword\"));\n   }\n\n   public void testName() {\n      ListStoragePoolsOptions options = new ListStoragePoolsOptions().name(\"bob\");\n      assertEquals(ImmutableList.of(\"bob\"), options.buildQueryParameters().get(\"name\"));\n   }\n\n   public void testNameStatic() {\n      ListStoragePoolsOptions options = name(\"bob\");\n      assertEquals(ImmutableList.of(\"bob\"), options.buildQueryParameters().get(\"name\"));\n   }\n\n   public void testPath() {\n      ListStoragePoolsOptions options = new ListStoragePoolsOptions().path(\"/foo/bar\");\n      assertEquals(ImmutableList.of(\"/foo/bar\"), options.buildQueryParameters().get(\"path\"));\n   }\n\n   public void testPathStatic() {\n      ListStoragePoolsOptions options = path(\"/foo/bar\");\n      assertEquals(ImmutableList.of(\"/foo/bar\"), options.buildQueryParameters().get(\"path\"));\n   }\n\n   public void testPodId() {\n      ListStoragePoolsOptions options = new ListStoragePoolsOptions().podId(\"16\");\n      assertEquals(ImmutableList.of(16 + \"\"), options.buildQueryParameters().get(\"podid\"));\n   }\n\n   public void testPodIdStatic() {\n      ListStoragePoolsOptions options = podId(\"16\");\n      assertEquals(ImmutableList.of(16 + \"\"), options.buildQueryParameters().get(\"podid\"));\n   }\n\n   public void testZoneId() {\n      ListStoragePoolsOptions options = new ListStoragePoolsOptions().zoneId(\"17\");\n      assertEquals(ImmutableList.of(17 + \"\"), options.buildQueryParameters().get(\"zoneid\"));\n   }\n\n   public void testZoneIdStatic() {\n      ListStoragePoolsOptions options = zoneId(\"17\");\n      assertEquals(ImmutableList.of(17 + \"\"), options.buildQueryParameters().get(\"zoneid\"));\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/ListTagsOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.ListTagsOptions.Builder.accountInDomain;\nimport static org.jclouds.cloudstack.options.ListTagsOptions.Builder.customer;\nimport static org.jclouds.cloudstack.options.ListTagsOptions.Builder.domainId;\nimport static org.jclouds.cloudstack.options.ListTagsOptions.Builder.isRecursive;\nimport static org.jclouds.cloudstack.options.ListTagsOptions.Builder.key;\nimport static org.jclouds.cloudstack.options.ListTagsOptions.Builder.keyword;\nimport static org.jclouds.cloudstack.options.ListTagsOptions.Builder.projectId;\nimport static org.jclouds.cloudstack.options.ListTagsOptions.Builder.resourceId;\nimport static org.jclouds.cloudstack.options.ListTagsOptions.Builder.resourceType;\nimport static org.jclouds.cloudstack.options.ListTagsOptions.Builder.value;\nimport static org.testng.Assert.assertEquals;\n\nimport com.google.common.collect.ImmutableList;\nimport org.jclouds.cloudstack.domain.Tag;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code ListTagsOptions}\n */\n@Test(groups = \"unit\")\npublic class ListTagsOptionsTest {\n\n   public void testCustomer() {\n      ListTagsOptions options = new ListTagsOptions().customer(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"customer\"));\n   }\n\n   public void testCustomerStatic() {\n      ListTagsOptions options = customer(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"customer\"));\n   }\n\n   public void testDomainId() {\n      ListTagsOptions options = new ListTagsOptions().domainId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testDomainIdStatic() {\n      ListTagsOptions options = domainId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testAccountInDomainId() {\n      ListTagsOptions options = new ListTagsOptions().accountInDomain(\"adrian\", \"6\");\n      assertEquals(ImmutableList.of(\"adrian\"), options.buildQueryParameters().get(\"account\"));\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testAccountInDomainIdStatic() {\n      ListTagsOptions options = accountInDomain(\"adrian\", \"6\");\n      assertEquals(ImmutableList.of(\"adrian\"), options.buildQueryParameters().get(\"account\"));\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testIsRecursive() {\n      ListTagsOptions options = new ListTagsOptions().isRecursive(true);\n      assertEquals(ImmutableList.of(\"true\"), options.buildQueryParameters().get(\"isrecursive\"));\n   }\n\n   public void testIsRecursiveStatic() {\n      ListTagsOptions options = isRecursive(true);\n      assertEquals(ImmutableList.of(\"true\"), options.buildQueryParameters().get(\"isrecursive\"));\n   }\n\n   public void testKey() {\n      ListTagsOptions options = new ListTagsOptions().key(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"key\"));\n   }\n\n   public void testKeyStatic() {\n      ListTagsOptions options = key(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"key\"));\n   }\n\n   public void testKeyword() {\n      ListTagsOptions options = new ListTagsOptions().keyword(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"keyword\"));\n   }\n\n   public void testKeywordStatic() {\n      ListTagsOptions options = keyword(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"keyword\"));\n   }\n\n   public void testProjectId() {\n      ListTagsOptions options = new ListTagsOptions().projectId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"projectid\"));\n   }\n\n   public void testProjectIdStatic() {\n      ListTagsOptions options = projectId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"projectid\"));\n   }\n\n   public void testResourceId() {\n      ListTagsOptions options = new ListTagsOptions().resourceId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"resourceid\"));\n   }\n\n   public void testResourceIdStatic() {\n      ListTagsOptions options = resourceId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"resourceid\"));\n   }\n\n   public void testResourceType() {\n      ListTagsOptions options = new ListTagsOptions().resourceType(Tag.ResourceType.TEMPLATE);\n      assertEquals(ImmutableList.of(\"Template\"), options.buildQueryParameters().get(\"resourcetype\"));\n   }\n\n   public void testResourceTypeStatic() {\n      ListTagsOptions options = resourceType(Tag.ResourceType.TEMPLATE);\n      assertEquals(ImmutableList.of(\"Template\"), options.buildQueryParameters().get(\"resourcetype\"));\n   }\n\n   public void testResourceTypeAsString() {\n      ListTagsOptions options = new ListTagsOptions().resourceType(\"Template\");\n      assertEquals(ImmutableList.of(\"Template\"), options.buildQueryParameters().get(\"resourcetype\"));\n   }\n\n   public void testResourceTypeAsStringStatic() {\n      ListTagsOptions options = resourceType(\"Template\");\n      assertEquals(ImmutableList.of(\"Template\"), options.buildQueryParameters().get(\"resourcetype\"));\n   }\n\n   public void testValue() {\n      ListTagsOptions options = new ListTagsOptions().value(\"some-value\");\n      assertEquals(ImmutableList.of(\"some-value\"), options.buildQueryParameters().get(\"value\"));\n   }\n\n   public void testValueStatic() {\n      ListTagsOptions options = value(\"some-value\");\n      assertEquals(ImmutableList.of(\"some-value\"), options.buildQueryParameters().get(\"value\"));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/ListTemplatesOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.ListTemplatesOptions.Builder.tags;\nimport static org.jclouds.cloudstack.options.ListTemplatesOptions.Builder.accountInDomain;\nimport static org.jclouds.cloudstack.options.ListTemplatesOptions.Builder.domainId;\nimport static org.jclouds.cloudstack.options.ListTemplatesOptions.Builder.filter;\nimport static org.jclouds.cloudstack.options.ListTemplatesOptions.Builder.hypervisor;\nimport static org.jclouds.cloudstack.options.ListTemplatesOptions.Builder.id;\nimport static org.jclouds.cloudstack.options.ListTemplatesOptions.Builder.zoneId;\nimport static org.testng.Assert.assertEquals;\n\nimport com.google.common.collect.ImmutableMap;\nimport org.jclouds.cloudstack.domain.TemplateFilter;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tests behavior of {@code ListTemplatesOptions}\n */\n@Test(groups = \"unit\")\npublic class ListTemplatesOptionsTest {\n\n   public void testId() {\n      ListTemplatesOptions options = new ListTemplatesOptions().id(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testIdStatic() {\n      ListTemplatesOptions options = id(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testDomainId() {\n      ListTemplatesOptions options = new ListTemplatesOptions().domainId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testDomainIdStatic() {\n      ListTemplatesOptions options = domainId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testAccountInDomainId() {\n      ListTemplatesOptions options = new ListTemplatesOptions().accountInDomain(\"adrian\", \"6\");\n      assertEquals(ImmutableList.of(\"adrian\"), options.buildQueryParameters().get(\"account\"));\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testAccountInDomainIdStatic() {\n      ListTemplatesOptions options = accountInDomain(\"adrian\", \"6\");\n      assertEquals(ImmutableList.of(\"adrian\"), options.buildQueryParameters().get(\"account\"));\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testHypervisor() {\n      ListTemplatesOptions options = new ListTemplatesOptions().hypervisor(\"KVM\");\n      assertEquals(ImmutableList.of(\"KVM\"), options.buildQueryParameters().get(\"hypervisor\"));\n   }\n\n   public void testHypervisorStatic() {\n      ListTemplatesOptions options = hypervisor(\"KVM\");\n      assertEquals(ImmutableList.of(\"KVM\"), options.buildQueryParameters().get(\"hypervisor\"));\n   }\n\n   public void testName() {\n      ListTemplatesOptions options = new ListTemplatesOptions().id(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testNameStatic() {\n      ListTemplatesOptions options = id(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testZoneId() {\n      ListTemplatesOptions options = new ListTemplatesOptions().zoneId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"zoneid\"));\n   }\n\n   public void testZoneIdStatic() {\n      ListTemplatesOptions options = zoneId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"zoneid\"));\n   }\n\n   public void testFilterDefault() {\n      assertEquals(ImmutableList.of(\"executable\"),\n            new ListTemplatesOptions().buildQueryParameters().get(\"templatefilter\"));\n   }\n\n   public void testFilter() {\n      ListTemplatesOptions options = new ListTemplatesOptions().filter(TemplateFilter.SELF_EXECUTABLE);\n      assertEquals(ImmutableList.of(\"self-executable\"), options.buildQueryParameters().get(\"templatefilter\"));\n   }\n\n   public void testFilterStatic() {\n      ListTemplatesOptions options = filter(TemplateFilter.SELF_EXECUTABLE);\n      assertEquals(ImmutableList.of(\"self-executable\"), options.buildQueryParameters().get(\"templatefilter\"));\n   }\n\n   public void testTags() {\n      ListTemplatesOptions options = new ListTemplatesOptions().tags(ImmutableMap.of(\"tag1\", \"val1\", \"tag2\", \"val2\"));\n      assertEquals(ImmutableList.of(\"tag1\"), options.buildQueryParameters().get(\"tags[0].key\"));\n      assertEquals(ImmutableList.of(\"tag2\"), options.buildQueryParameters().get(\"tags[1].key\"));\n      assertEquals(ImmutableList.of(\"val1\"), options.buildQueryParameters().get(\"tags[0].value\"));\n      assertEquals(ImmutableList.of(\"val2\"), options.buildQueryParameters().get(\"tags[1].value\"));\n   }\n\n   public void testTagsStatic() {\n      ListTemplatesOptions options = tags(ImmutableMap.of(\"tag1\", \"val1\", \"tag2\", \"val2\"));\n      assertEquals(ImmutableList.of(\"tag1\"), options.buildQueryParameters().get(\"tags[0].key\"));\n      assertEquals(ImmutableList.of(\"tag2\"), options.buildQueryParameters().get(\"tags[1].key\"));\n      assertEquals(ImmutableList.of(\"val1\"), options.buildQueryParameters().get(\"tags[0].value\"));\n      assertEquals(ImmutableList.of(\"val2\"), options.buildQueryParameters().get(\"tags[1].value\"));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/ListUsageRecordsOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.ListUsageRecordsOptions.Builder.accountId;\nimport static org.jclouds.cloudstack.options.ListUsageRecordsOptions.Builder.accountInDomain;\nimport static org.jclouds.cloudstack.options.ListUsageRecordsOptions.Builder.domainId;\nimport static org.jclouds.cloudstack.options.ListUsageRecordsOptions.Builder.keyword;\nimport static org.jclouds.cloudstack.options.ListUsageRecordsOptions.Builder.includeTags;\nimport static org.jclouds.cloudstack.options.ListUsageRecordsOptions.Builder.page;\nimport static org.jclouds.cloudstack.options.ListUsageRecordsOptions.Builder.pageSize;\nimport static org.jclouds.cloudstack.options.ListUsageRecordsOptions.Builder.type;\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options to the GlobalUsageApi.listUsageOptions() API call\n */\n@Test(groups = \"unit\")\npublic class ListUsageRecordsOptionsTest {\n\n   public void testAccountInDomain() {\n      ListUsageRecordsOptions options = new ListUsageRecordsOptions().accountInDomain(\"fred\", \"42\");\n      assertEquals(ImmutableSet.of(\"fred\"), options.buildQueryParameters().get(\"account\"));\n      assertEquals(ImmutableSet.of(\"42\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testAccountInDomainStatic() {\n      ListUsageRecordsOptions options = accountInDomain(\"fred\", \"42\");\n      assertEquals(ImmutableSet.of(\"fred\"), options.buildQueryParameters().get(\"account\"));\n      assertEquals(ImmutableSet.of(\"42\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testDomainId() {\n      ListUsageRecordsOptions options = new ListUsageRecordsOptions().domainId(\"42\");\n      assertEquals(ImmutableSet.of(\"42\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testDomainIdStatic() {\n      ListUsageRecordsOptions options = domainId(\"42\");\n      assertEquals(ImmutableSet.of(\"42\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testAccountId() {\n      ListUsageRecordsOptions options = new ListUsageRecordsOptions().accountId(\"41\");\n      assertEquals(ImmutableSet.of(\"41\"), options.buildQueryParameters().get(\"accountid\"));\n   }\n\n   public void testAccountIdStatic() {\n      ListUsageRecordsOptions options = accountId(\"41\");\n      assertEquals(ImmutableSet.of(\"41\"), options.buildQueryParameters().get(\"accountid\"));\n   }\n\n   public void testKeyword() {\n      ListUsageRecordsOptions options = new ListUsageRecordsOptions().keyword(\"bob\");\n      assertEquals(ImmutableSet.of(\"bob\"), options.buildQueryParameters().get(\"keyword\"));\n   }\n\n   public void testKeywordStatic() {\n      ListUsageRecordsOptions options = keyword(\"bob\");\n      assertEquals(ImmutableSet.of(\"bob\"), options.buildQueryParameters().get(\"keyword\"));\n   }\n   \n       public void testTypeStatic() {\n        ListUsageRecordsOptions options = type(\"3\");\n        assertEquals(ImmutableSet.of(\"3\"), options.buildQueryParameters().get(\"type\"));\n    }\n\n    public void testPageStatic() {\n        ListUsageRecordsOptions options = page(\"1\");\n        assertEquals(ImmutableSet.of(\"1\"), options.buildQueryParameters().get(\"page\"));\n    }\n\n    public void testPageSizeStatic() {\n        ListUsageRecordsOptions options = pageSize(\"500\");\n        assertEquals(ImmutableSet.of(\"500\"), options.buildQueryParameters().get(\"pagesize\"));\n    }\n    \n    public void testIncludeTags() {\n        ListUsageRecordsOptions options = new ListUsageRecordsOptions().includeTags(true);\n        assertEquals(ImmutableSet.of(\"true\"), options.buildQueryParameters().get(\"includetags\"));\n    }\n\n    public void testIncludeTagsStatic() {\n        ListUsageRecordsOptions options = includeTags(true);\n        assertEquals(ImmutableSet.of(\"true\"), options.buildQueryParameters().get(\"includetags\"));\n    }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/ListUsersOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.ListUsersOptions.Builder.accountInDomain;\nimport static org.jclouds.cloudstack.options.ListUsersOptions.Builder.accountType;\nimport static org.jclouds.cloudstack.options.ListUsersOptions.Builder.domainId;\nimport static org.jclouds.cloudstack.options.ListUsersOptions.Builder.id;\nimport static org.jclouds.cloudstack.options.ListUsersOptions.Builder.keyword;\nimport static org.jclouds.cloudstack.options.ListUsersOptions.Builder.page;\nimport static org.jclouds.cloudstack.options.ListUsersOptions.Builder.pageSize;\nimport static org.jclouds.cloudstack.options.ListUsersOptions.Builder.state;\nimport static org.jclouds.cloudstack.options.ListUsersOptions.Builder.userName;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.cloudstack.domain.User;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code ListUsersOptions}\n */\n@Test(groups = \"unit\")\npublic class ListUsersOptionsTest {\n\n\n   public void testId() {\n      ListUsersOptions options = new ListUsersOptions().id(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testIdStatic() {\n      ListUsersOptions options = id(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testUserName() {\n      ListUsersOptions options = new ListUsersOptions().userName(\"andrei\");\n      assertEquals(ImmutableSet.of(\"andrei\"), options.buildQueryParameters().get(\"name\"));\n   }\n\n   public void testUserNameStatic() {\n      ListUsersOptions options = userName(\"andrei\");\n      assertEquals(ImmutableSet.of(\"andrei\"), options.buildQueryParameters().get(\"name\"));\n   }\n\n   public void testState() {\n      ListUsersOptions options = new ListUsersOptions().state(User.State.ENABLED);\n      assertEquals(ImmutableList.of(\"enabled\"), options.buildQueryParameters().get(\"state\"));\n   }\n\n   public void testStateStatic() {\n      ListUsersOptions options = state(User.State.ENABLED);\n      assertEquals(ImmutableList.of(\"enabled\"), options.buildQueryParameters().get(\"state\"));\n   }\n\n   public void testAccountType() {\n      ListUsersOptions options = new ListUsersOptions().accountType(\"user\");\n      assertEquals(ImmutableList.of(\"user\"), options.buildQueryParameters().get(\"accounttype\"));\n   }\n\n   public void testAccountTypeStatic() {\n      ListUsersOptions options = accountType(\"user\");\n      assertEquals(ImmutableList.of(\"user\"), options.buildQueryParameters().get(\"accounttype\"));\n   }\n\n   public void testKeyword() {\n      ListUsersOptions options = new ListUsersOptions().keyword(\"key\");\n      assertEquals(ImmutableList.of(\"key\"), options.buildQueryParameters().get(\"keyword\"));\n   }\n\n   public void testKeywordStatic() {\n      ListUsersOptions options = keyword(\"key\");\n      assertEquals(ImmutableList.of(\"key\"), options.buildQueryParameters().get(\"keyword\"));\n   }\n\n   public void testPage() {\n      ListUsersOptions options = new ListUsersOptions().page(6);\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"page\"));\n   }\n\n   public void testPageStatic() {\n      ListUsersOptions options = page(6);\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"page\"));\n   }\n\n   public void testPageSize() {\n      ListUsersOptions options = new ListUsersOptions().pageSize(6);\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"pagesize\"));\n   }\n\n   public void testPageSizeStatic() {\n      ListUsersOptions options = pageSize(6);\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"pagesize\"));\n   }\n\n   public void testAccountInDomainId() {\n      ListUsersOptions options = new ListUsersOptions().accountInDomain(\"adrian\", \"6\");\n      assertEquals(ImmutableList.of(\"adrian\"), options.buildQueryParameters().get(\"account\"));\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testAccountInDomainIdStatic() {\n      ListUsersOptions options = accountInDomain(\"adrian\", \"6\");\n      assertEquals(ImmutableList.of(\"adrian\"), options.buildQueryParameters().get(\"account\"));\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testDomainIdStatic() {\n      ListUsersOptions options = domainId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/ListVirtualMachinesOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.ListVirtualMachinesOptions.Builder.tags;\nimport static org.jclouds.cloudstack.options.ListVirtualMachinesOptions.Builder.accountInDomain;\nimport static org.jclouds.cloudstack.options.ListVirtualMachinesOptions.Builder.domainId;\nimport static org.jclouds.cloudstack.options.ListVirtualMachinesOptions.Builder.groupId;\nimport static org.jclouds.cloudstack.options.ListVirtualMachinesOptions.Builder.hostId;\nimport static org.jclouds.cloudstack.options.ListVirtualMachinesOptions.Builder.id;\nimport static org.jclouds.cloudstack.options.ListVirtualMachinesOptions.Builder.networkId;\nimport static org.jclouds.cloudstack.options.ListVirtualMachinesOptions.Builder.podId;\nimport static org.jclouds.cloudstack.options.ListVirtualMachinesOptions.Builder.state;\nimport static org.jclouds.cloudstack.options.ListVirtualMachinesOptions.Builder.usesVirtualNetwork;\nimport static org.jclouds.cloudstack.options.ListVirtualMachinesOptions.Builder.zoneId;\nimport static org.testng.Assert.assertEquals;\n\nimport com.google.common.collect.ImmutableMap;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tests behavior of {@code ListVirtualMachinesOptions}\n */\n@Test(groups = \"unit\")\npublic class ListVirtualMachinesOptionsTest {\n\n   public void testHostId() {\n      ListVirtualMachinesOptions options = new ListVirtualMachinesOptions().hostId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"hostid\"));\n   }\n\n   public void testHostIdStatic() {\n      ListVirtualMachinesOptions options = hostId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"hostid\"));\n   }\n\n   public void testPodId() {\n      ListVirtualMachinesOptions options = new ListVirtualMachinesOptions().podId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"podid\"));\n   }\n\n   public void testPodIdStatic() {\n      ListVirtualMachinesOptions options = podId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"podid\"));\n   }\n\n   public void testNetworkId() {\n      ListVirtualMachinesOptions options = new ListVirtualMachinesOptions().networkId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"networkid\"));\n   }\n\n   public void testNetworkIdStatic() {\n      ListVirtualMachinesOptions options = networkId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"networkid\"));\n   }\n\n   public void testGroupId() {\n      ListVirtualMachinesOptions options = new ListVirtualMachinesOptions().groupId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"groupid\"));\n   }\n\n   public void testGroupIdStatic() {\n      ListVirtualMachinesOptions options = groupId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"groupid\"));\n   }\n\n   public void testAccountInDomainId() {\n      ListVirtualMachinesOptions options = new ListVirtualMachinesOptions().accountInDomain(\"adrian\", \"6\");\n      assertEquals(ImmutableList.of(\"adrian\"), options.buildQueryParameters().get(\"account\"));\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testAccountInDomainIdStatic() {\n      ListVirtualMachinesOptions options = accountInDomain(\"adrian\", \"6\");\n      assertEquals(ImmutableList.of(\"adrian\"), options.buildQueryParameters().get(\"account\"));\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testName() {\n      ListVirtualMachinesOptions options = new ListVirtualMachinesOptions().id(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testNameStatic() {\n      ListVirtualMachinesOptions options = id(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testZoneId() {\n      ListVirtualMachinesOptions options = new ListVirtualMachinesOptions().zoneId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"zoneid\"));\n   }\n\n   public void testZoneIdStatic() {\n      ListVirtualMachinesOptions options = zoneId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"zoneid\"));\n   }\n\n   public void testState() {\n      ListVirtualMachinesOptions options = new ListVirtualMachinesOptions().state(\"state\");\n      assertEquals(ImmutableList.of(\"state\"), options.buildQueryParameters().get(\"state\"));\n   }\n\n   public void testStateStatic() {\n      ListVirtualMachinesOptions options = state(\"state\");\n      assertEquals(ImmutableList.of(\"state\"), options.buildQueryParameters().get(\"state\"));\n   }\n\n   public void testUsingVirtualNetwork() {\n      ListVirtualMachinesOptions options = new ListVirtualMachinesOptions().usesVirtualNetwork(true);\n      assertEquals(ImmutableList.of(\"true\"), options.buildQueryParameters().get(\"forvirtualnetwork\"));\n   }\n\n   public void testUsingVirtualNetworkStatic() {\n      ListVirtualMachinesOptions options = usesVirtualNetwork(true);\n      assertEquals(ImmutableList.of(\"true\"), options.buildQueryParameters().get(\"forvirtualnetwork\"));\n   }\n\n   public void testId() {\n      ListVirtualMachinesOptions options = new ListVirtualMachinesOptions().id(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testDomainId() {\n      ListVirtualMachinesOptions options = new ListVirtualMachinesOptions().domainId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testIdStatic() {\n      ListVirtualMachinesOptions options = id(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testDomainIdStatic() {\n      ListVirtualMachinesOptions options = domainId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testTags() {\n      ListVirtualMachinesOptions options = new ListVirtualMachinesOptions().tags(ImmutableMap.of(\"tag1\", \"val1\", \"tag2\", \"val2\"));\n      assertEquals(ImmutableList.of(\"tag1\"), options.buildQueryParameters().get(\"tags[0].key\"));\n      assertEquals(ImmutableList.of(\"tag2\"), options.buildQueryParameters().get(\"tags[1].key\"));\n      assertEquals(ImmutableList.of(\"val1\"), options.buildQueryParameters().get(\"tags[0].value\"));\n      assertEquals(ImmutableList.of(\"val2\"), options.buildQueryParameters().get(\"tags[1].value\"));\n   }\n\n   public void testTagsStatic() {\n      ListVirtualMachinesOptions options = tags(ImmutableMap.of(\"tag1\", \"val1\", \"tag2\", \"val2\"));\n      assertEquals(ImmutableList.of(\"tag1\"), options.buildQueryParameters().get(\"tags[0].key\"));\n      assertEquals(ImmutableList.of(\"tag2\"), options.buildQueryParameters().get(\"tags[1].key\"));\n      assertEquals(ImmutableList.of(\"val1\"), options.buildQueryParameters().get(\"tags[0].value\"));\n      assertEquals(ImmutableList.of(\"val2\"), options.buildQueryParameters().get(\"tags[1].value\"));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/ListVlanIPRangesOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.ListVlanIPRangesOptions.Builder.accountInDomain;\nimport static org.jclouds.cloudstack.options.ListVlanIPRangesOptions.Builder.domainId;\nimport static org.jclouds.cloudstack.options.ListVlanIPRangesOptions.Builder.forVirtualNetwork;\nimport static org.jclouds.cloudstack.options.ListVlanIPRangesOptions.Builder.id;\nimport static org.jclouds.cloudstack.options.ListVlanIPRangesOptions.Builder.keyword;\nimport static org.jclouds.cloudstack.options.ListVlanIPRangesOptions.Builder.networkId;\nimport static org.jclouds.cloudstack.options.ListVlanIPRangesOptions.Builder.podId;\nimport static org.jclouds.cloudstack.options.ListVlanIPRangesOptions.Builder.vlan;\nimport static org.jclouds.cloudstack.options.ListVlanIPRangesOptions.Builder.zoneId;\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tests behavior of {@code ListVlanIPRangesOptions}\n */\n@Test(groups = \"unit\")\npublic class ListVlanIPRangesOptionsTest {\n\n   public void testAccountInDomain() {\n      ListVlanIPRangesOptions options = new ListVlanIPRangesOptions().accountInDomain(\"fred\", \"19\");\n      assertEquals(ImmutableList.of(\"fred\"), options.buildQueryParameters().get(\"account\"));\n      assertEquals(ImmutableList.of(\"19\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testAccountInDomainStatic() {\n      ListVlanIPRangesOptions options = accountInDomain(\"fred\", \"19\");\n      assertEquals(ImmutableList.of(\"fred\"), options.buildQueryParameters().get(\"account\"));\n      assertEquals(ImmutableList.of(\"19\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testDomainId() {\n      ListVlanIPRangesOptions options = new ListVlanIPRangesOptions().domainId(\"19\");\n      assertEquals(ImmutableList.of(\"19\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testDomainIdStatic() {\n      ListVlanIPRangesOptions options = domainId(\"19\");\n      assertEquals(ImmutableList.of(\"19\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testForVirtualNetwork() {\n      ListVlanIPRangesOptions options = new ListVlanIPRangesOptions().forVirtualNetwork(true);\n      assertEquals(ImmutableList.of(\"true\"), options.buildQueryParameters().get(\"forvirtualnetwork\"));\n   }\n\n   public void testForVirtualNetworkStatic() {\n      ListVlanIPRangesOptions options = forVirtualNetwork(true);\n      assertEquals(ImmutableList.of(\"true\"), options.buildQueryParameters().get(\"forvirtualnetwork\"));\n   }\n\n   public void testId() {\n      ListVlanIPRangesOptions options = new ListVlanIPRangesOptions().id(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testIdStatic() {\n      ListVlanIPRangesOptions options = id(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testKeyword() {\n      ListVlanIPRangesOptions options = new ListVlanIPRangesOptions().keyword(\"fred\");\n      assertEquals(ImmutableList.of(\"fred\"), options.buildQueryParameters().get(\"keyword\"));\n   }\n\n   public void testKeywordStatic() {\n      ListVlanIPRangesOptions options = keyword(\"fred\");\n      assertEquals(ImmutableList.of(\"fred\"), options.buildQueryParameters().get(\"keyword\"));\n   }\n\n   public void testNetworkId() {\n      ListVlanIPRangesOptions options = new ListVlanIPRangesOptions().networkId(\"209\");\n      assertEquals(ImmutableList.of(\"209\"), options.buildQueryParameters().get(\"networkid\"));\n   }\n\n   public void testNetworkIdStatic() {\n      ListVlanIPRangesOptions options = networkId(\"209\");\n      assertEquals(ImmutableList.of(\"209\"), options.buildQueryParameters().get(\"networkid\"));\n   }\n\n   public void testPodId() {\n      ListVlanIPRangesOptions options = new ListVlanIPRangesOptions().podId(\"13\");\n      assertEquals(ImmutableList.of(\"13\"), options.buildQueryParameters().get(\"podid\"));\n   }\n\n   public void testPodIdStatic() {\n      ListVlanIPRangesOptions options = podId(\"13\");\n      assertEquals(ImmutableList.of(\"13\"), options.buildQueryParameters().get(\"podid\"));\n   }\n\n   public void testVlan() {\n      ListVlanIPRangesOptions options = new ListVlanIPRangesOptions().vlan(1001);\n      assertEquals(ImmutableList.of(\"1001\"), options.buildQueryParameters().get(\"vlan\"));\n   }\n\n   public void testVlanStatic() {\n      ListVlanIPRangesOptions options = vlan(1001);\n      assertEquals(ImmutableList.of(\"1001\"), options.buildQueryParameters().get(\"vlan\"));\n   }\n\n   public void testZoneId() {\n      ListVlanIPRangesOptions options = new ListVlanIPRangesOptions().zoneId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"zoneid\"));\n   }\n\n   public void testZoneIdStatic() {\n      ListVlanIPRangesOptions options = zoneId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"zoneid\"));\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/ListZonesOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.ListZonesOptions.Builder.tags;\nimport static org.jclouds.cloudstack.options.ListZonesOptions.Builder.available;\nimport static org.jclouds.cloudstack.options.ListZonesOptions.Builder.domainId;\nimport static org.jclouds.cloudstack.options.ListZonesOptions.Builder.id;\nimport static org.testng.Assert.assertEquals;\n\nimport com.google.common.collect.ImmutableMap;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tests behavior of {@code ListZonesOptions}\n */\n@Test(groups = \"unit\")\npublic class ListZonesOptionsTest {\n\n   public void testId() {\n      ListZonesOptions options = new ListZonesOptions().id(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testAvailable() {\n      ListZonesOptions options = new ListZonesOptions().available(true);\n      assertEquals(ImmutableList.of(\"true\"), options.buildQueryParameters().get(\"available\"));\n   }\n\n   public void testDomainId() {\n      ListZonesOptions options = new ListZonesOptions().domainId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testIdStatic() {\n      ListZonesOptions options = id(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"id\"));\n   }\n\n   public void testAvailableStatic() {\n      ListZonesOptions options = available(true);\n      assertEquals(ImmutableList.of(\"true\"), options.buildQueryParameters().get(\"available\"));\n   }\n\n   public void testDomainIdStatic() {\n      ListZonesOptions options = domainId(\"6\");\n      assertEquals(ImmutableList.of(\"6\"), options.buildQueryParameters().get(\"domainid\"));\n   }\n\n   public void testTags() {\n      ListZonesOptions options = new ListZonesOptions().tags(ImmutableMap.of(\"tag1\", \"val1\", \"tag2\", \"val2\"));\n      assertEquals(ImmutableList.of(\"tag1\"), options.buildQueryParameters().get(\"tags[0].key\"));\n      assertEquals(ImmutableList.of(\"tag2\"), options.buildQueryParameters().get(\"tags[1].key\"));\n      assertEquals(ImmutableList.of(\"val1\"), options.buildQueryParameters().get(\"tags[0].value\"));\n      assertEquals(ImmutableList.of(\"val2\"), options.buildQueryParameters().get(\"tags[1].value\"));\n   }\n\n   public void testTagsStatic() {\n      ListZonesOptions options = tags(ImmutableMap.of(\"tag1\", \"val1\", \"tag2\", \"val2\"));\n      assertEquals(ImmutableList.of(\"tag1\"), options.buildQueryParameters().get(\"tags[0].key\"));\n      assertEquals(ImmutableList.of(\"tag2\"), options.buildQueryParameters().get(\"tags[1].key\"));\n      assertEquals(ImmutableList.of(\"val1\"), options.buildQueryParameters().get(\"tags[0].value\"));\n      assertEquals(ImmutableList.of(\"val2\"), options.buildQueryParameters().get(\"tags[1].value\"));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/UpdateAccountOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.UpdateAccountOptions.Builder.networkDomain;\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code UpdateAccountOptions}\n */\n@Test(groups = \"unit\")\npublic class UpdateAccountOptionsTest {\n\n   public void testNetworkDomain() {\n      UpdateAccountOptions options = new UpdateAccountOptions().networkDomain(\"net\");\n      assertEquals(ImmutableSet.of(\"net\"), options.buildQueryParameters().get(\"networkdomain\"));\n   }\n\n   public void testNameStatic() {\n      UpdateAccountOptions options = networkDomain(\"net\");\n      assertEquals(ImmutableSet.of(\"net\"), options.buildQueryParameters().get(\"networkdomain\"));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/UpdateClusterOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.UpdateClusterOptions.Builder.allocationState;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.cloudstack.domain.AllocationState;\nimport org.jclouds.cloudstack.domain.Cluster;\nimport org.jclouds.cloudstack.domain.Host;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tests behavior of {@code UpdateClusterOptions}\n */\n@Test(groups = \"unit\")\npublic class UpdateClusterOptionsTest {\n\n   public void testAllocationState() {\n      UpdateClusterOptions options = new UpdateClusterOptions().allocationState(AllocationState.ENABLED);\n      assertEquals(ImmutableList.of(\"Enabled\"), options.buildQueryParameters().get(\"allocationstate\"));\n   }\n\n   public void testAllocationStateStatic() {\n      UpdateClusterOptions options = allocationState(AllocationState.ENABLED);\n      assertEquals(ImmutableList.of(\"Enabled\"), options.buildQueryParameters().get(\"allocationstate\"));\n   }\n\n   public void testClusterName() {\n      UpdateClusterOptions options = new UpdateClusterOptions().clusterName(\"My Cluster\");\n      assertEquals(ImmutableList.of(\"My Cluster\"), options.buildQueryParameters().get(\"clustername\"));\n   }\n\n   public void testClusterType() {\n      UpdateClusterOptions options = new UpdateClusterOptions().clusterType(Host.ClusterType.CLOUD_MANAGED);\n      assertEquals(ImmutableList.of(\"CloudManaged\"), options.buildQueryParameters().get(\"clustertype\"));\n   }\n\n   public void testHypervisor() {\n      UpdateClusterOptions options = new UpdateClusterOptions().hypervisor(\"XenServer\");\n      assertEquals(ImmutableList.of(\"XenServer\"), options.buildQueryParameters().get(\"hypervisor\"));\n   }\n\n   public void testManagedState() {\n      UpdateClusterOptions options = new UpdateClusterOptions().managedState(Cluster.ManagedState.PREPARE_UNMANAGED);\n      assertEquals(ImmutableList.of(\"PrepareUnmanaged\"), options.buildQueryParameters().get(\"managedstate\"));\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/UpdateDiskOfferingOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.UpdateDiskOfferingOptions.Builder.displayText;\nimport static org.jclouds.cloudstack.options.UpdateDiskOfferingOptions.Builder.name;\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code UpdateDiskOfferingOptions}\n */\n@Test(groups = \"unit\")\npublic class UpdateDiskOfferingOptionsTest {\n\n   public void testName() {\n      UpdateDiskOfferingOptions options = new UpdateDiskOfferingOptions().name(\"test-name\");\n      assertEquals(ImmutableSet.of(\"test-name\"), options.buildQueryParameters().get(\"name\"));\n   }\n\n   public void testNameStatic() {\n      UpdateDiskOfferingOptions options = name(\"test-name\");\n      assertEquals(ImmutableSet.of(\"test-name\"), options.buildQueryParameters().get(\"name\"));\n   }\n\n   public void testDisplayText() {\n      UpdateDiskOfferingOptions options = new UpdateDiskOfferingOptions().displayText(\"test-display-text\");\n      assertEquals(ImmutableSet.of(\"test-display-text\"), options.buildQueryParameters().get(\"displaytext\"));\n   }\n\n   public void testDisplayTextStatic() {\n      UpdateDiskOfferingOptions options = displayText(\"test-display-text\");\n      assertEquals(ImmutableSet.of(\"test-display-text\"), options.buildQueryParameters().get(\"displaytext\"));\n   }\n\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/UpdateHostOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.UpdateHostOptions.Builder.allocationState;\nimport static org.jclouds.cloudstack.options.UpdateHostOptions.Builder.hostTags;\nimport static org.jclouds.cloudstack.options.UpdateHostOptions.Builder.osCategoryId;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.cloudstack.domain.AllocationState;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code UpdateHostOptions}\n */\n@Test(groups = \"unit\")\npublic class UpdateHostOptionsTest {\n\n   public void testAllocationState() {\n      UpdateHostOptions options = new UpdateHostOptions().allocationState(AllocationState.ENABLED);\n      assertEquals(ImmutableList.of(\"Enabled\"), options.buildQueryParameters().get(\"allocationstate\"));\n   }\n\n   public void testAllocationStateStatic() {\n      UpdateHostOptions options = allocationState(AllocationState.ENABLED);\n      assertEquals(ImmutableList.of(\"Enabled\"), options.buildQueryParameters().get(\"allocationstate\"));\n   }\n\n   public void testHostTags() {\n      UpdateHostOptions options = new UpdateHostOptions().hostTags(ImmutableSet.<String>of(\"foo\", \"bar\", \"baz\"));\n      assertEquals(ImmutableList.of(\"foo,bar,baz\"), options.buildQueryParameters().get(\"hosttags\"));\n   }\n\n   public void testHostTagsStatic() {\n      UpdateHostOptions options = hostTags(ImmutableSet.<String>of(\"foo\", \"bar\", \"baz\"));\n      assertEquals(ImmutableList.of(\"foo,bar,baz\"), options.buildQueryParameters().get(\"hosttags\"));\n   }\n\n   public void testOsCategoryId() {\n      UpdateHostOptions options = new UpdateHostOptions().osCategoryId(\"42\");\n      assertEquals(ImmutableList.of(\"42\"), options.buildQueryParameters().get(\"oscategoryid\"));\n   }\n\n   public void testOsCategoryIdStatic() {\n      UpdateHostOptions options = osCategoryId(\"42\");\n      assertEquals(ImmutableList.of(\"42\"), options.buildQueryParameters().get(\"oscategoryid\"));\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/UpdateNetworkOfferingOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.domain.NetworkOfferingAvailabilityType.OPTIONAL;\nimport static org.jclouds.cloudstack.options.UpdateNetworkOfferingOptions.Builder.availability;\nimport static org.jclouds.cloudstack.options.UpdateNetworkOfferingOptions.Builder.displayText;\nimport static org.jclouds.cloudstack.options.UpdateNetworkOfferingOptions.Builder.name;\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code UpdateNetworkOfferingOptions}\n */\n@Test(groups = \"unit\")\npublic class UpdateNetworkOfferingOptionsTest {\n\n   public void testName() {\n      UpdateNetworkOfferingOptions options = new UpdateNetworkOfferingOptions().name(\"test-name\");\n      assertEquals(ImmutableSet.of(\"test-name\"), options.buildQueryParameters().get(\"name\"));\n   }\n\n   public void testNameStatic() {\n      UpdateNetworkOfferingOptions options = name(\"test-name\");\n      assertEquals(ImmutableSet.of(\"test-name\"), options.buildQueryParameters().get(\"name\"));\n   }\n\n   public void testDisplayText() {\n      UpdateNetworkOfferingOptions options = new UpdateNetworkOfferingOptions().displayText(\"test-display-text\");\n      assertEquals(ImmutableSet.of(\"test-display-text\"), options.buildQueryParameters().get(\"displaytext\"));\n   }\n\n   public void testDisplayTextStatic() {\n      UpdateNetworkOfferingOptions options = displayText(\"test-display-text\");\n      assertEquals(ImmutableSet.of(\"test-display-text\"), options.buildQueryParameters().get(\"displaytext\"));\n   }\n\n   public void testAvailability() {\n      UpdateNetworkOfferingOptions options = new UpdateNetworkOfferingOptions().availability(OPTIONAL);\n      assertEquals(ImmutableSet.of(\"Optional\"), options.buildQueryParameters().get(\"availability\"));\n   }\n\n   public void testAvailabilityStatic() {\n      UpdateNetworkOfferingOptions options = availability(OPTIONAL);\n      assertEquals(ImmutableSet.of(\"Optional\"), options.buildQueryParameters().get(\"availability\"));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/UpdatePodOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.UpdatePodOptions.Builder.allocationState;\nimport static org.jclouds.cloudstack.options.UpdatePodOptions.Builder.endIp;\nimport static org.jclouds.cloudstack.options.UpdatePodOptions.Builder.gateway;\nimport static org.jclouds.cloudstack.options.UpdatePodOptions.Builder.name;\nimport static org.jclouds.cloudstack.options.UpdatePodOptions.Builder.netmask;\nimport static org.jclouds.cloudstack.options.UpdatePodOptions.Builder.startIp;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.cloudstack.domain.AllocationState;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tests behavior of {@code UpdatePodOptions}\n */\n@Test(groups = \"unit\")\npublic class UpdatePodOptionsTest {\n\n   public void testName() {\n      UpdatePodOptions options = new UpdatePodOptions().name(\"fred\");\n      assertEquals(ImmutableList.of(\"fred\"), options.buildQueryParameters().get(\"name\"));\n   }\n\n   public void testNameStatic() {\n      UpdatePodOptions options = name(\"fred\");\n      assertEquals(ImmutableList.of(\"fred\"), options.buildQueryParameters().get(\"name\"));\n   }\n\n   public void testStartIp() {\n      UpdatePodOptions options = new UpdatePodOptions().startIp(\"192.168.42.42\");\n      assertEquals(ImmutableList.of(\"192.168.42.42\"), options.buildQueryParameters().get(\"startip\"));\n   }\n\n   public void testStartIpStatic() {\n      UpdatePodOptions options = startIp(\"192.168.42.42\");\n      assertEquals(ImmutableList.of(\"192.168.42.42\"), options.buildQueryParameters().get(\"startip\"));\n   }\n\n   public void testEndIp() {\n      UpdatePodOptions options = new UpdatePodOptions().endIp(\"192.168.42.52\");\n      assertEquals(ImmutableList.of(\"192.168.42.52\"), options.buildQueryParameters().get(\"endip\"));\n   }\n\n   public void testEndIpStatic() {\n      UpdatePodOptions options = endIp(\"192.168.42.52\");\n      assertEquals(ImmutableList.of(\"192.168.42.52\"), options.buildQueryParameters().get(\"endip\"));\n   }\n\n   public void testGateway() {\n      UpdatePodOptions options = new UpdatePodOptions().gateway(\"192.168.42.62\");\n      assertEquals(ImmutableList.of(\"192.168.42.62\"), options.buildQueryParameters().get(\"gateway\"));\n   }\n\n   public void testGatewayStatic() {\n      UpdatePodOptions options = gateway(\"192.168.42.62\");\n      assertEquals(ImmutableList.of(\"192.168.42.62\"), options.buildQueryParameters().get(\"gateway\"));\n   }\n\n   public void testNetmask() {\n      UpdatePodOptions options = new UpdatePodOptions().netmask(\"255.255.240.0\");\n      assertEquals(ImmutableList.of(\"255.255.240.0\"), options.buildQueryParameters().get(\"netmask\"));\n   }\n\n   public void testNetmaskStatic() {\n      UpdatePodOptions options = netmask(\"255.255.240.0\");\n      assertEquals(ImmutableList.of(\"255.255.240.0\"), options.buildQueryParameters().get(\"netmask\"));\n   }\n\n   public void testAllocationState() {\n      UpdatePodOptions options = new UpdatePodOptions().allocationState(AllocationState.ENABLED);\n      assertEquals(ImmutableList.of(\"Enabled\"), options.buildQueryParameters().get(\"allocationstate\"));\n   }\n\n   public void testAllocationStateStatic() {\n      UpdatePodOptions options = allocationState(AllocationState.ENABLED);\n      assertEquals(ImmutableList.of(\"Enabled\"), options.buildQueryParameters().get(\"allocationstate\"));\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/UpdateServiceOfferingOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.UpdateServiceOfferingOptions.Builder.displayText;\nimport static org.jclouds.cloudstack.options.UpdateServiceOfferingOptions.Builder.name;\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code UpdateServiceOfferingOptions}\n */\n@Test(groups = \"unit\")\npublic class UpdateServiceOfferingOptionsTest {\n\n   public void testName() {\n      UpdateServiceOfferingOptions options = new UpdateServiceOfferingOptions().name(\"test-name\");\n      assertEquals(ImmutableSet.of(\"test-name\"), options.buildQueryParameters().get(\"name\"));\n   }\n\n   public void testNameStatic() {\n      UpdateServiceOfferingOptions options = name(\"test-name\");\n      assertEquals(ImmutableSet.of(\"test-name\"), options.buildQueryParameters().get(\"name\"));\n   }\n\n   public void testDisplayText() {\n      UpdateServiceOfferingOptions options = new UpdateServiceOfferingOptions().displayText(\"test-display-text\");\n      assertEquals(ImmutableSet.of(\"test-display-text\"), options.buildQueryParameters().get(\"displaytext\"));\n   }\n\n   public void testDisplayTextStatic() {\n      UpdateServiceOfferingOptions options = displayText(\"test-display-text\");\n      assertEquals(ImmutableSet.of(\"test-display-text\"), options.buildQueryParameters().get(\"displaytext\"));\n   }\n\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/UpdateUserOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.options;\n\nimport static org.jclouds.cloudstack.options.UpdateUserOptions.Builder.email;\nimport static org.jclouds.cloudstack.options.UpdateUserOptions.Builder.firstName;\nimport static org.jclouds.cloudstack.options.UpdateUserOptions.Builder.lastName;\nimport static org.jclouds.cloudstack.options.UpdateUserOptions.Builder.timezone;\nimport static org.jclouds.cloudstack.options.UpdateUserOptions.Builder.userApiKey;\nimport static org.jclouds.cloudstack.options.UpdateUserOptions.Builder.userName;\nimport static org.jclouds.cloudstack.options.UpdateUserOptions.Builder.userSecretKey;\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code UpdateUserOptions}\n */\n@Test(groups = \"unit\")\npublic class UpdateUserOptionsTest {\n\n   public void testEmail() {\n      UpdateUserOptions options = new UpdateUserOptions().email(\"andrei@example.com\");\n      assertEquals(ImmutableSet.of(\"andrei@example.com\"), options.buildQueryParameters().get(\"email\"));\n   }\n\n   public void testEmailStatic() {\n      UpdateUserOptions options = email(\"andrei@example.com\");\n      assertEquals(ImmutableSet.of(\"andrei@example.com\"), options.buildQueryParameters().get(\"email\"));\n   }\n\n   public void testFirstName() {\n      UpdateUserOptions options = new UpdateUserOptions().firstName(\"First\");\n      assertEquals(ImmutableSet.of(\"First\"), options.buildQueryParameters().get(\"firstname\"));\n   }\n\n   public void testFirstStatic() {\n      UpdateUserOptions options = firstName(\"First\");\n      assertEquals(ImmutableSet.of(\"First\"), options.buildQueryParameters().get(\"firstname\"));\n   }\n\n   public void testLastName() {\n      UpdateUserOptions options = new UpdateUserOptions().lastName(\"Last\");\n      assertEquals(ImmutableSet.of(\"Last\"), options.buildQueryParameters().get(\"lastname\"));\n   }\n\n   public void testLastNameStatic() {\n      UpdateUserOptions options = lastName(\"Last\");\n      assertEquals(ImmutableSet.of(\"Last\"), options.buildQueryParameters().get(\"lastname\"));\n   }\n\n   public void testTimezone() {\n      UpdateUserOptions options = new UpdateUserOptions().timezone(\"timez\");\n      assertEquals(ImmutableSet.of(\"timez\"), options.buildQueryParameters().get(\"timezone\"));\n   }\n\n   public void testTimezoneStatic() {\n      UpdateUserOptions options = timezone(\"timez\");\n      assertEquals(ImmutableSet.of(\"timez\"), options.buildQueryParameters().get(\"timezone\"));\n   }\n\n   public void testUserApiKey() {\n      UpdateUserOptions options = new UpdateUserOptions().userApiKey(\"sdfoasdjfo\");\n      assertEquals(ImmutableSet.of(\"sdfoasdjfo\"), options.buildQueryParameters().get(\"userapikey\"));\n   }\n\n   public void testUserApiKeyStatic() {\n      UpdateUserOptions options = userApiKey(\"sdfoasdjfo\");\n      assertEquals(ImmutableSet.of(\"sdfoasdjfo\"), options.buildQueryParameters().get(\"userapikey\"));\n   }\n\n   public void testUserSecretKey() {\n      UpdateUserOptions options = new UpdateUserOptions().userSecretKey(\"sdfoasdjfo\");\n      assertEquals(ImmutableSet.of(\"sdfoasdjfo\"), options.buildQueryParameters().get(\"usersecretkey\"));\n   }\n\n   public void testUserSecretKeyStatic() {\n      UpdateUserOptions options = userSecretKey(\"sdfoasdjfo\");\n      assertEquals(ImmutableSet.of(\"sdfoasdjfo\"), options.buildQueryParameters().get(\"usersecretkey\"));\n   }\n   \n   public void testUserName() {\n      UpdateUserOptions options = new UpdateUserOptions().userName(\"andrei\");\n      assertEquals(ImmutableSet.of(\"andrei\"), options.buildQueryParameters().get(\"username\"));\n   }\n\n   public void testUserNameStatic() {\n      UpdateUserOptions options = userName(\"andrei\");\n      assertEquals(ImmutableSet.of(\"andrei\"), options.buildQueryParameters().get(\"username\"));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/DeleteIPForwardingRuleResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.parse;\n\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"DeleteIPForwardingRuleResponseTest\")\npublic class DeleteIPForwardingRuleResponseTest extends BaseItemParserTest<Long> {\n\n   @Override\n   public String resource() {\n      return \"/deleteipforwardingruleresponse.json\";\n   }\n\n   @Override\n   @SelectJson(\"jobid\")\n   public Long expected() {\n      return 50005L;\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/DeleteNetworkResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.parse;\n\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"DeleteNetworkResponseTest\")\npublic class DeleteNetworkResponseTest extends BaseItemParserTest<Long> {\n\n   @Override\n   public String resource() {\n      return \"/deletenetworkresponse.json\";\n   }\n\n   @Override\n   @SelectJson(\"jobid\")\n   public Long expected() {\n      return 45612L;\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/DeployVirtualMachineResponse3xTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.parse;\n\nimport org.jclouds.cloudstack.domain.AsyncCreateResponse;\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"DeployVirtualMachineResponse3xTest\")\npublic class DeployVirtualMachineResponse3xTest extends BaseItemParserTest<AsyncCreateResponse> {\n\n   @Override\n   public String resource() {\n      return \"/deployvirtualmachineresponse.json\";\n   }\n\n   @Override\n   @SelectJson({ \"deployvirtualmachine\", \"deployvirtualmachineresponse\" })\n   public AsyncCreateResponse expected() {\n      return AsyncCreateResponse.builder().id(\"1234\").jobId(\"50006\").build();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/DeployVirtualMachineResponse4xTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.parse;\n\nimport org.jclouds.cloudstack.domain.AsyncCreateResponse;\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"DeployVirtualMachineResponse3xTest\")\npublic class DeployVirtualMachineResponse4xTest extends BaseItemParserTest<AsyncCreateResponse> {\n\n   @Override\n   public String resource() {\n      return \"/deployvirtualmachineresponse4x.json\";\n   }\n\n   @Override\n   @SelectJson({ \"deployvirtualmachine\", \"deployvirtualmachineresponse\" })\n   public AsyncCreateResponse expected() {\n      return AsyncCreateResponse.builder().id(\"1cce6cb7-2268-47ff-9696-d9e610f6619a\")\n            .jobId(\"13330fc9-8b3e-4582-aa3e-90883c041ff0\").build();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/DisableStaticNATResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.parse;\n\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"DisableStaticNATResponseTest\")\npublic class DisableStaticNATResponseTest extends BaseItemParserTest<Long> {\n\n   @Override\n   public String resource() {\n      return \"/disablestaticnatresponse.json\";\n   }\n\n   @Override\n   @SelectJson(\"jobid\")\n   public Long expected() {\n      return 50006L;\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/EnableStaticNATResponseWhereResponseDoesntHaveJobTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.parse;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.cloudstack.domain.AsyncCreateResponse;\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.rest.annotations.Unwrap;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"EnableStaticNATResponseWhereResponseDoesntHaveJobTest\")\npublic class EnableStaticNATResponseWhereResponseDoesntHaveJobTest extends BaseItemParserTest<AsyncCreateResponse> {\n\n   @Override\n   public String resource() {\n      return \"/enablestaticnatresponse-withoutjob.json\";\n   }\n\n   @Override\n   @Unwrap\n   @Consumes(MediaType.APPLICATION_JSON)\n   public AsyncCreateResponse expected() {\n      return AsyncCreateResponse.UNINITIALIZED;\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/JobResultResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.parse;\n\nimport org.jclouds.cloudstack.domain.JobResult;\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"DeleteNetworkResponseTest\")\npublic class JobResultResponseTest extends BaseItemParserTest<JobResult> {\n\n   @Override\n   public String resource() {\n      return \"/deletetemplateresponse.json\";\n   }\n\n   @Override\n   @SelectJson(\"jobresult\")\n   public JobResult expected() {\n      return JobResult.builder().success(true).build();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/ListAccountsResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.parse;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.Account;\nimport org.jclouds.cloudstack.domain.User;\nimport org.jclouds.cloudstack.domain.Account.State;\nimport org.jclouds.cloudstack.domain.Account.Type;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.json.BaseSetParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\")\npublic class ListAccountsResponseTest extends BaseSetParserTest<Account> {\n\n   @Override\n   protected Injector injector() {\n      return Guice.createInjector(new GsonModule() {\n\n         @Override\n         protected void configure() {\n            bind(DateAdapter.class).to(Iso8601DateAdapter.class);\n            super.configure();\n         }\n\n      });\n\n   }\n\n   @Override\n   public String resource() {\n      return \"/listaccountsresponse.json\";\n   }\n\n   @Override\n   @SelectJson(\"account\")\n   public Set<Account> expected() {\n      return ImmutableSet.<Account> of(Account\n            .builder()\n            .id(\"505\")\n            .name(\"jclouds\")\n            .type(Type.USER)\n            .domainId(\"457\")\n            .domain(\"AA000062-jclouds-dev\")\n            .receivedBytes(318900216)\n            .sentBytes(23189677)\n            .VMLimit(15L)\n            .VMs(1)\n            .IPsAvailable(14L)\n            .IPLimit(15L)\n            .IPs(0)\n            .IPsAvailable(15L)\n            .volumeLimit(90L)\n            .volumes(2)\n            .volumesAvailable(88L)\n            .snapshotLimit(250L)\n            .snapshots(0)\n            .snapshotsAvailable(250L)\n            .templateLimit(15L)\n            .templates(0)\n            .templatesAvailable(15L)\n            .VMsAvailable(14L)\n            .VMsStopped(0)\n            .VMsRunning(1)\n            .state(State.ENABLED)\n            .users(\n                  ImmutableSet.of(User.builder().id(\"505\").name(\"jclouds\").firstName(\"Adrian\").lastName(\"Cole\")\n                        .email(\"adrian@jclouds.org\")\n                        .created(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2011-04-19T01:57:24+0000\"))\n                        .state(User.State.ENABLED).account(\"jclouds\").accountType(Type.USER).domainId(\"457\")\n                        .domain(\"AA000062-jclouds-dev\").apiKey(\"APIKEY\").secretKey(\"SECRETKEY\").build())).build());\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/ListAlertsResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.parse;\n\nimport java.util.Calendar;\nimport java.util.Set;\nimport java.util.TimeZone;\n\nimport org.jclouds.cloudstack.domain.Alert;\nimport org.jclouds.json.BaseSetParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\")\npublic class ListAlertsResponseTest extends BaseSetParserTest<Alert> {\n\n   @Override\n   protected Injector injector() {\n      return Guice.createInjector(new GsonModule() {\n\n         @Override\n         protected void configure() {\n            bind(DateAdapter.class).to(Iso8601DateAdapter.class);\n            super.configure();\n         }\n\n      });\n\n   }\n\n   @Override\n   public String resource() {\n      return \"/listalertsresponse.json\";\n   }\n\n   @Override\n   @SelectJson(\"alert\")\n   public Set<Alert> expected() {\n      Calendar c = Calendar.getInstance(TimeZone.getTimeZone(\"GMT+02:00\"));\n      c.set(Calendar.YEAR, 2011);\n      c.set(Calendar.MONTH, Calendar.DECEMBER);\n      c.set(Calendar.DAY_OF_MONTH, 4);\n      c.set(Calendar.HOUR_OF_DAY, 10);\n      c.set(Calendar.MINUTE, 5);\n      c.set(Calendar.SECOND, 2);\n      return ImmutableSet.of(Alert.builder()\n         .id(\"20\").description(\"Failed to deploy Vm with Id: 52\").sent(c.getTime()).type(\"7\").build());\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/ListCapabilitiesResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.parse;\n\nimport org.jclouds.cloudstack.domain.Capabilities;\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class ListCapabilitiesResponseTest extends BaseItemParserTest<Capabilities> {\n\n   @Override\n   public String resource() {\n      return \"/listcapabilitiesresponse.json\";\n   }\n\n   @Override\n   @SelectJson(\"capability\")\n   public Capabilities expected() {\n      return Capabilities.builder().securityGroupsEnabled(true).canShareTemplates(true).cloudStackVersion(\"2.2\")\n            .build();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/ListCapacityResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.parse;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.Capacity;\nimport org.jclouds.json.BaseSetParserTest;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\")\npublic class ListCapacityResponseTest extends BaseSetParserTest<Capacity> {\n\n   @Override\n   public String resource() {\n      return \"/listcapacityresponse.json\";\n   }\n\n   @Override\n   @SelectJson(\"capacity\")\n   public Set<Capacity> expected() {\n      Capacity a = Capacity.builder().type(Capacity.Type.PRIMARY_STORAGE_ALLOCATED_BYTES)\n         .zoneId(\"1\").zoneName(\"Dev Zone 1\").podId(\"null\").podName(\"All\")\n         .capacityUsed(34057748480L).capacityTotal(1796712955904L).percentUsed(1.9).build();\n      Capacity b = Capacity.builder().type(Capacity.Type.PRIMARY_STORAGE_ALLOCATED_BYTES)\n         .zoneId(\"1\").zoneName(\"Dev Zone 1\").podId(\"1\").podName(\"Dev Pod 1\")\n         .capacityUsed(34057748480L).capacityTotal(1796712955904L).percentUsed(1.9).build();\n      return ImmutableSet.of(a, b);\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/ListClustersResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.parse;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.AllocationState;\nimport org.jclouds.cloudstack.domain.Cluster;\nimport org.jclouds.cloudstack.domain.Host;\nimport org.jclouds.json.BaseSetParserTest;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\")\npublic class ListClustersResponseTest extends BaseSetParserTest<Cluster> {\n\n   @Override\n   public String resource() {\n      return \"/listclustersresponse.json\";\n   }\n\n   @Override\n   @SelectJson(\"cluster\")\n   public Set<Cluster> expected() {\n      Cluster cluster1 = Cluster.builder()\n         .id(\"1\")\n         .name(\"Xen Clust 1\")\n         .podId(\"1\").podName(\"Dev Pod 1\")\n         .zoneId(\"1\").zoneName(\"Dev Zone 1\")\n         .hypervisor(\"XenServer\")\n         .clusterType(Host.ClusterType.CLOUD_MANAGED)\n         .allocationState(AllocationState.ENABLED)\n         .managedState(Cluster.ManagedState.MANAGED)\n         .build();\n      Cluster cluster2 = Cluster.builder()\n         .id(\"2\")\n         .name(\"Xen Clust 1\")\n         .podId(\"2\").podName(\"Dev Pod 2\")\n         .zoneId(\"2\").zoneName(\"Dev Zone 2\")\n         .hypervisor(\"XenServer\")\n         .clusterType(Host.ClusterType.CLOUD_MANAGED)\n         .allocationState(AllocationState.ENABLED)\n         .managedState(Cluster.ManagedState.MANAGED)\n         .build();\n\n      return ImmutableSet.of(cluster1, cluster2);\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/ListConfigurationEntriesResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.parse;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.ConfigurationEntry;\nimport org.jclouds.json.BaseSetParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\")\npublic class ListConfigurationEntriesResponseTest extends BaseSetParserTest<ConfigurationEntry> {\n\n   @Override\n   protected Injector injector() {\n      return Guice.createInjector(new GsonModule() {\n\n         @Override\n         protected void configure() {\n            bind(DateAdapter.class).to(Iso8601DateAdapter.class);\n            super.configure();\n         }\n\n      });\n   }\n\n   @Override\n   public String resource() {\n      return \"/listconfigurationsresponse.json\";\n   }\n\n   @Override\n   @SelectJson(\"configuration\")\n   public Set<ConfigurationEntry> expected() {\n      return ImmutableSet.of(\n         ConfigurationEntry.builder().category(\"Advanced\").name(\"account.cleanup.interval\").value(\"86400\")\n            .description(\"The interval (in seconds) between cleanup for removed accounts\").build(),\n         ConfigurationEntry.builder().category(\"Advanced\").name(\"agent.lb.enabled\").value(\"true\")\n            .description(\"If agent load balancing enabled in cluster setup\").build()\n      );\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/ListDiskOfferingsResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.parse;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.DiskOffering;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.json.BaseSetParserTest;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\")\npublic class ListDiskOfferingsResponseTest extends BaseSetParserTest<DiskOffering> {\n\n   @Override\n   public String resource() {\n      return \"/listdiskofferingsresponse.json\";\n   }\n\n   @Override\n   @SelectJson(\"diskoffering\")\n   public Set<DiskOffering> expected() {\n      return ImmutableSet.<DiskOffering> of(\n            DiskOffering.builder().id(\"3\").domainId(\"1\").domain(\"ROOT\").name(\"Small\").displayText(\"Small Disk, 5 GB\")\n                  .diskSize(5)\n                  .created(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2011-02-11T15:22:32-0800\"))\n                  .customized(false).build(),\n            DiskOffering.builder().id(\"4\").domainId(\"1\").domain(\"ROOT\").name(\"Medium\").displayText(\"Medium Disk, 20 GB\")\n                  .diskSize(20)\n                  .created(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2011-02-11T15:22:32-0800\"))\n                  .customized(false).build(),\n            DiskOffering.builder().id(\"5\").domainId(\"1\").domain(\"ROOT\").name(\"Large\").displayText(\"Large Disk, 100 GB\")\n                  .diskSize(100)\n                  .created(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2011-02-11T15:22:32-0800\"))\n                  .customized(false).build());\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/ListDomainsResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.parse;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.Domain;\nimport org.jclouds.json.BaseSetParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\")\npublic class ListDomainsResponseTest extends BaseSetParserTest<Domain> {\n\n   @Override\n   protected Injector injector() {\n      return Guice.createInjector(new GsonModule() {\n         @Override\n         protected void configure() {\n            bind(DateAdapter.class).to(Iso8601DateAdapter.class);\n            super.configure();\n         }\n      });\n   }\n\n   @Override\n   public String resource() {\n      return \"/listdomainsresponse.json\";\n   }\n\n   @Override\n   @SelectJson(\"domain\")\n   public Set<Domain> expected() {\n      return ImmutableSet.of(\n         Domain.builder().id(\"1\").name(\"ROOT\").level(0).hasChild(true).build(),\n         Domain.builder().id(\"2\").name(\"jclouds1\").level(1).parentDomainId(\"1\")\n            .parentDomainName(\"ROOT\").hasChild(false).build()\n      );\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/ListFirewallRulesResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.parse;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.FirewallRule;\nimport org.jclouds.cloudstack.domain.Tag;\nimport org.jclouds.json.BaseSetParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\")\npublic class ListFirewallRulesResponseTest extends BaseSetParserTest<FirewallRule> {\n\n   @Override\n   protected Injector injector() {\n      return Guice.createInjector(new GsonModule() {\n\n         @Override\n         protected void configure() {\n            bind(DateAdapter.class).to(Iso8601DateAdapter.class);\n            super.configure();\n         }\n\n      });\n   }\n\n   @Override\n   public String resource() {\n      return \"/listfirewallrulesresponse.json\";\n   }\n\n   @Override\n   @SelectJson(\"firewallrule\")\n   public Set<FirewallRule> expected() {\n      Set<String> CIDRs = ImmutableSet.of(\"0.0.0.0/0\");\n      return ImmutableSet.of(\n         FirewallRule.builder().id(\"2017\").protocol(FirewallRule.Protocol.TCP).startPort(30)\n            .endPort(35).ipAddressId(\"2\").ipAddress(\"10.27.27.51\").state(FirewallRule.State.ACTIVE).CIDRs(CIDRs).build(),\n         FirewallRule.builder().id(\"2016\").protocol(FirewallRule.Protocol.TCP).startPort(22)\n            .endPort(22).ipAddressId(\"2\").ipAddress(\"10.27.27.51\").state(FirewallRule.State.ACTIVE).CIDRs(CIDRs).build(),\n         FirewallRule.builder().id(\"10\").protocol(FirewallRule.Protocol.TCP).startPort(22)\n            .endPort(22).ipAddressId(\"8\").ipAddress(\"10.27.27.57\").state(FirewallRule.State.ACTIVE).CIDRs(CIDRs)\n            .tags(Tag.builder().account(\"1\").domain(\"ROOT\").domainId(\"1\").key(\"some-tag\").resourceId(\"10\")\n                        .resourceType(Tag.ResourceType.FIREWALL_RULE).value(\"some-value\").build()).build()\n               );\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/ListHostsResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.parse;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.config.CloudStackParserModule;\nimport org.jclouds.cloudstack.domain.AllocationState;\nimport org.jclouds.cloudstack.domain.Host;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.json.BaseParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\")\npublic class ListHostsResponseTest extends BaseParserTest<Set<Host>, Set<Host>> {\n\n   @Override\n   @Test(enabled = false)\n   public void compare(Set<Host> expects, Set<Host> response) {\n      assertEquals(response.toString(), expects.toString());\n   }\n\n   @Override\n   protected Injector injector() {\n      return Guice.createInjector(new GsonModule(), new CloudStackParserModule());\n   }\n\n   @Override\n   public String resource() {\n      return \"/listhostsresponse.json\";\n   }\n\n   @Override\n   @SelectJson(\"host\")\n   public Set<Host> expected() {\n      return ImmutableSet.of(\n\n         Host.builder()\n            .id(\"1\")\n            .name(\"cs2-xevsrv.alucloud.local\")\n            .state(Host.State.UP)\n            .type(Host.Type.ROUTING)\n            .ipAddress(\"10.26.26.107\")\n            .zoneId(\"1\")\n            .zoneName(\"Dev Zone 1\")\n            .podId(\"1\")\n            .podName(\"Dev Pod 1\")\n            .version(\"2.2.12.20110928142833\")\n            .hypervisor(\"XenServer\")\n            .cpuNumber(24)\n            .cpuSpeed(2266)\n            .cpuAllocated(\"2.76%\")\n            .cpuUsed(\"0.1%\")\n            .cpuWithOverProvisioning(54384.0f)\n            .networkKbsRead(4443L)\n            .networkKbsWrite(15048L)\n            .memoryTotal(100549733760L)\n            .memoryAllocated(3623878656L)\n            .memoryUsed(3623878656L)\n            .capabilities(\"xen-3.0-x86_64 , xen-3.0-x86_32p , hvm-3.0-x86_32 , hvm-3.0-x86_32p , hvm-3.0-x86_64\")\n            .lastPinged(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"1970-01-16T00:54:43+0200\"))\n            .managementServerId(\"223098941760041\")\n            .clusterId(\"1\")\n            .clusterName(\"Xen Clust 1\")\n            .clusterType(Host.ClusterType.CLOUD_MANAGED)\n            .localStorageActive(false)\n            .created(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2011-11-26T23:28:36+0200\"))\n            .events(\"PrepareUnmanaged; HypervisorVersionChanged; ManagementServerDown; PingTimeout; \" +\n               \"AgentDisconnected; MaintenanceRequested; HostDown; AgentConnected; StartAgentRebalance; ShutdownRequested; Ping\")\n            .hasEnoughCapacity(false)\n            .allocationState(AllocationState.ENABLED).build(),\n\n         Host.builder()\n            .id(\"2\")\n            .name(\"nfs://10.26.26.165/mnt/nfs/cs_sec\")\n            .state(Host.State.ALERT)\n            .disconnected(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2011-11-26T23:33:38+0200\"))\n            .type(Host.Type.SECONDARY_STORAGE)\n            .ipAddress(\"nfs\")\n            .zoneId(\"1\")\n            .zoneName(\"Dev Zone 1\")\n            .version(\"2.2.12.20110928142833\")\n            .hypervisor(\"None\")\n            .lastPinged(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"1970-01-16T00:42:30+0200\"))\n            .localStorageActive(false)\n            .created(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2011-11-26T23:33:38+0200\"))\n            .events(\"ManagementServerDown; AgentDisconnected; Remove; MaintenanceRequested; AgentConnected; Ping\")\n            .hasEnoughCapacity(false)\n            .allocationState(AllocationState.ENABLED).build(),\n\n         Host.builder()\n            .id(\"3\")\n            .name(\"s-1-VM\")\n            .state(Host.State.UP)\n            .type(Host.Type.SECONDARY_STORAGE_VM)\n            .ipAddress(\"10.26.26.81\")\n            .zoneId(\"1\")\n            .zoneName(\"Dev Zone 1\")\n            .podId(\"1\")\n            .podName(\"Dev Pod 1\")\n            .version(\"2.2.12.20110928142833\")\n            .lastPinged(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"1970-01-16T00:54:43+0200\"))\n            .managementServerId(\"223098941760041\")\n            .localStorageActive(false)\n            .created(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2011-11-26T23:35:51+0200\"))\n            .events(\"PrepareUnmanaged; HypervisorVersionChanged; ManagementServerDown; PingTimeout; \" +\n               \"AgentDisconnected; MaintenanceRequested; HostDown; AgentConnected; StartAgentRebalance; ShutdownRequested; Ping\")\n            .hasEnoughCapacity(false)\n            .allocationState(AllocationState.ENABLED).build(),\n\n         Host.builder()\n            .id(\"4\")\n            .name(\"v-2-VM\")\n            .state(Host.State.UP)\n            .type(Host.Type.CONSOLE_PROXY)\n            .ipAddress(\"10.26.26.96\")\n            .zoneId(\"1\")\n            .zoneName(\"Dev Zone 1\")\n            .podId(\"1\")\n            .podName(\"Dev Pod 1\")\n            .version(\"2.2.12.20110928142833\")\n            .lastPinged(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"1970-01-16T00:54:43+0200\"))\n            .managementServerId(\"223098941760041\")\n            .localStorageActive(false)\n            .created(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2011-11-26T23:36:46+0200\"))\n            .events(\"PrepareUnmanaged; HypervisorVersionChanged; ManagementServerDown; PingTimeout; \" +\n               \"AgentDisconnected; MaintenanceRequested; HostDown; AgentConnected; StartAgentRebalance; ShutdownRequested; Ping\")\n            .hasEnoughCapacity(false)\n            .allocationState(AllocationState.ENABLED).build()\n      );\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/ListHypervisorsResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.parse;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.functions.ParseNamesFromHttpResponse;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.json.BaseSetParserTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\")\npublic class ListHypervisorsResponseTest extends BaseSetParserTest<String> {\n\n   @Override\n   public String resource() {\n      return \"/listhypervisorsresponse.json\";\n   }\n\n   @Override\n   public Set<String> expected() {\n      return ImmutableSet.<String> of(\"XenServer\", \"KVM\", \"VMware\");\n   }\n\n   @Override\n   protected Function<HttpResponse, Set<String>> parser(Injector injector) {\n      return injector.getInstance(ParseNamesFromHttpResponse.class);\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/ListIPForwardingRulesResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.parse;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.IPForwardingRule;\nimport org.jclouds.cloudstack.domain.Tag;\nimport org.jclouds.json.BaseSetParserTest;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\")\npublic class ListIPForwardingRulesResponseTest extends BaseSetParserTest<IPForwardingRule> {\n\n   @Override\n   public String resource() {\n      return \"/listipforwardingrulesresponse.json\";\n   }\n\n   @Override\n   @SelectJson(\"ipforwardingrule\")\n   public Set<IPForwardingRule> expected() {\n      return ImmutableSet.<IPForwardingRule> of(\n            IPForwardingRule.builder().id(\"66\").protocol(\"tcp\").startPort(22).endPort(22).virtualMachineId(\"58\")\n                  .virtualMachineDisplayName(\"i-4-58-VM\").virtualMachineName(\"i-4-58-VM\")\n                  .IPAddressId(\"15\").IPAddress(\"10.27.27.64\").state(\"Active\")\n                  .tags(Tag.builder().account(\"1\").domain(\"ROOT\").domainId(\"1\").key(\"some-tag\").resourceId(\"66\")\n                        .resourceType(Tag.ResourceType.PORT_FORWARDING_RULE).value(\"some-value\").build()).build());\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/ListLoadBalancerRulesResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.parse;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.LoadBalancerRule;\nimport org.jclouds.json.BaseSetParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\nimport org.testng.collections.Sets;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\")\npublic class ListLoadBalancerRulesResponseTest extends BaseSetParserTest<LoadBalancerRule> {\n\n   @Override\n   protected Injector injector() {\n      return Guice.createInjector(new GsonModule() {\n\n         @Override\n         protected void configure() {\n            bind(DateAdapter.class).to(Iso8601DateAdapter.class);\n            super.configure();\n         }\n\n      });\n   }\n\n   @Override\n   public String resource() {\n      return \"/listloadbalancerrulesresponse.json\";\n   }\n\n   @Override\n   @SelectJson(\"loadbalancerrule\")\n   public Set<LoadBalancerRule> expected() {\n      return ImmutableSet.<LoadBalancerRule> of(LoadBalancerRule.builder()\n         .id(\"93\").account(\"admin\").algorithm(LoadBalancerRule.Algorithm.ROUNDROBIN)\n         .description(\"null\").domain(\"ROOT\").domainId(\"1\").name(\"Ranny\").privatePort(80)\n         .publicIP(\"10.27.27.59\").publicIPId(\"10\").publicPort(80).state(LoadBalancerRule.State.ADD)\n         .CIDRs(Sets.<String>newHashSet()).zoneId(null)\n         .build());\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/ListNetworkOfferingsResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.parse;\n\nimport static org.jclouds.cloudstack.domain.NetworkOfferingAvailabilityType.REQUIRED;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.NetworkOffering;\nimport org.jclouds.cloudstack.domain.TrafficType;\nimport org.jclouds.json.BaseSetParserTest;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\")\npublic class ListNetworkOfferingsResponseTest extends BaseSetParserTest<NetworkOffering> {\n\n   @Override\n   public String resource() {\n      return \"/listnetworkofferingsresponse.json\";\n   }\n\n   @Override\n   @SelectJson(\"networkoffering\")\n   public Set<NetworkOffering> expected() {\n      return ImmutableSet.<NetworkOffering>of(\n         NetworkOffering.builder().id(\"7\").name(\"DefaultDirectNetworkOffering\").displayText(\"Direct\")\n            .trafficType(TrafficType.PUBLIC).isDefault(true).supportsVLAN(false).availability(REQUIRED)\n            .networkRate(200).build(), NetworkOffering.builder().id(\"6\").name(\"DefaultVirtualizedNetworkOffering\")\n            .displayText(\"Virtual Vlan\").trafficType(TrafficType.GUEST).isDefault(true).supportsVLAN(false)\n            .availability(REQUIRED).networkRate(200).build());\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/ListNetworksResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.parse;\n\nimport java.net.URI;\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.GuestIPType;\nimport org.jclouds.cloudstack.domain.Network;\nimport org.jclouds.cloudstack.domain.NetworkService;\nimport org.jclouds.cloudstack.domain.Tag;\nimport org.jclouds.cloudstack.domain.TrafficType;\nimport org.jclouds.json.BaseSetParserTest;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSortedMap;\nimport com.google.common.collect.ImmutableSortedSet;\n\n@Test(groups = \"unit\")\npublic class ListNetworksResponseTest extends BaseSetParserTest<Network> {\n\n   @Override\n   public String resource() {\n      return \"/listnetworksresponse.json\";\n   }\n\n   @Override\n   @SelectJson(\"network\")\n   public Set<Network> expected() {\n      return ImmutableSet\n            .<Network> of(Network\n                  .builder()\n                  .id(\"204\")\n                  .account(\"adrian\")\n                  .name(\"Virtual Network\")\n                  .displayText(\n                        \"A dedicated virtualized network for your account.  The broadcast domain is contained within a VLAN and all public network access is routed out by a virtual router.\")\n                  .broadcastDomainType(\"Vlan\")\n                  .trafficType(TrafficType.GUEST)\n                  .zoneId(\"1\")\n                  .networkOfferingId(\"6\")\n                  .networkOfferingName(\"DefaultVirtualizedNetworkOffering\")\n                  .networkOfferingDisplayText(\"Virtual Vlan\")\n                  .networkOfferingAvailability(\"Required\")\n                  .isShared(false)\n                  .isSystem(false)\n                  .state(\"Implemented\")\n                  .related(\"204\")\n                  .broadcastURI(URI.create(\"vlan://240\"))\n                  .DNS(ImmutableList.of(\"8.8.8.8\"))\n                  .guestIPType(GuestIPType.VIRTUAL)\n                  .domain(\"ROOT\")\n                  .domainId(\"1\")\n                  .isDefault(true)\n                  .services(\n                        ImmutableSortedSet.of(\n                              NetworkService.builder().name(\"Vpn\").capabilities(ImmutableMap.of(\"SupportedVpnTypes\", \"pptp,l2tp,ipsec\")).build(),\n                              NetworkService.builder().name(\"Gateway\").build(),\n                              NetworkService.builder().name(\"UserData\").build(),\n                              NetworkService.builder().name(\"Dhcp\").build(),\n                              NetworkService.builder().name(\"Firewall\").capabilities(ImmutableSortedMap.<String, String>naturalOrder()\n                                    .put(\"SupportedSourceNatTypes\", \"per account\").put(\"StaticNat\", \"true\")\n                                    .put(\"TrafficStatistics\", \"per public ip\").put(\"PortForwarding\", \"true\")\n                                    .put(\"MultipleIps\", \"true\").put(\"SupportedProtocols\", \"tcp,udp\").build()).build(),\n                              NetworkService.builder().name(\"Dns\").build(),\n                              NetworkService.builder().name(\"Lb\").capabilities(ImmutableMap.of(\"SupportedLbAlgorithms\",\n                                    \"roundrobin,leastconn,source\", \"SupportedProtocols\", \"tcp, udp\")).build()\n                        )\n                  )\n                  .networkDomain(\"cs3cloud.internal\")\n                  .tags(Tag.builder().account(\"1\").domain(\"ROOT\").domainId(\"1\").key(\"some-tag\").resourceId(\"204\")\n                        .resourceType(Tag.ResourceType.NETWORK).value(\"some-value\").build()).build());\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/ListOSCategoriesResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.parse;\n\nimport java.util.Map;\n\nimport org.jclouds.cloudstack.functions.ParseIdToNameFromHttpResponse;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.json.BaseItemParserTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\")\npublic class ListOSCategoriesResponseTest extends BaseItemParserTest<Map<String, String>> {\n\n   @Override\n   public String resource() {\n      return \"/listoscategoriesresponse.json\";\n   }\n\n   @Override\n   public Map<String, String> expected() {\n       return ImmutableMap.<String, String> builder().put(\"1\", \"CentOS\").put(\"10\", \"Ubuntu\").put(\"2\", \"Debian\").put(\"3\", \"Oracle\")\n            .put(\"4\", \"RedHat\").put(\"5\", \"SUSE\").put(\"6\", \"Windows\").put(\"7\", \"Other\").put(\"8\", \"Novel\").put(\"9\", \"Unix\")\n            .build();\n   }\n\n   @Override\n   protected Function<HttpResponse, Map<String, String>> parser(Injector injector) {\n      return injector.getInstance(ParseIdToNameFromHttpResponse.class);\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/ListOSTypesResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.parse;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.OSType;\nimport org.jclouds.json.BaseSetParserTest;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\")\npublic class ListOSTypesResponseTest extends BaseSetParserTest<OSType> {\n\n   @Override\n   public String resource() {\n      return \"/listostypesresponse.json\";\n   }\n\n   @Override\n   @SelectJson(\"ostype\")\n   public Set<OSType> expected() {\n      return ImmutableSet\n            .<OSType> builder()\n            .add(OSType.builder().id(\"69\").OSCategoryId(\"7\").description(\"Asianux 3(32-bit)\").build())\n            .add(OSType.builder().id(\"70\").OSCategoryId(\"7\").description(\"Asianux 3(64-bit)\").build())\n            .add(OSType.builder().id(\"1\").OSCategoryId(\"1\").description(\"CentOS 4.5 (32-bit)\").build())\n            .add(OSType.builder().id(\"2\").OSCategoryId(\"1\").description(\"CentOS 4.6 (32-bit)\").build())\n            .add(OSType.builder().id(\"3\").OSCategoryId(\"1\").description(\"CentOS 4.7 (32-bit)\").build())\n            .add(OSType.builder().id(\"4\").OSCategoryId(\"1\").description(\"CentOS 4.8 (32-bit)\").build())\n            .add(OSType.builder().id(\"5\").OSCategoryId(\"1\").description(\"CentOS 5.0 (32-bit)\").build())\n            .add(OSType.builder().id(\"6\").OSCategoryId(\"1\").description(\"CentOS 5.0 (64-bit)\").build())\n            .add(OSType.builder().id(\"7\").OSCategoryId(\"1\").description(\"CentOS 5.1 (32-bit)\").build())\n            .add(OSType.builder().id(\"8\").OSCategoryId(\"1\").description(\"CentOS 5.1 (64-bit)\").build())\n            .add(OSType.builder().id(\"9\").OSCategoryId(\"1\").description(\"CentOS 5.2 (32-bit)\").build())\n            .add(OSType.builder().id(\"10\").OSCategoryId(\"1\").description(\"CentOS 5.2 (64-bit)\").build())\n            .add(OSType.builder().id(\"11\").OSCategoryId(\"1\").description(\"CentOS 5.3 (32-bit)\").build())\n            .add(OSType.builder().id(\"12\").OSCategoryId(\"1\").description(\"CentOS 5.3 (64-bit)\").build())\n            .add(OSType.builder().id(\"13\").OSCategoryId(\"1\").description(\"CentOS 5.4 (32-bit)\").build())\n            .add(OSType.builder().id(\"14\").OSCategoryId(\"1\").description(\"CentOS 5.4 (64-bit)\").build())\n            .add(OSType.builder().id(\"111\").OSCategoryId(\"1\").description(\"CentOS 5.5 (32-bit)\").build())\n            .add(OSType.builder().id(\"112\").OSCategoryId(\"1\").description(\"CentOS 5.5 (64-bit)\").build())\n            .add(OSType.builder().id(\"73\").OSCategoryId(\"2\").description(\"Debian GNU/Linux 4(32-bit)\").build())\n            .add(OSType.builder().id(\"74\").OSCategoryId(\"2\").description(\"Debian GNU/Linux 4(64-bit)\").build())\n            .add(OSType.builder().id(\"72\").OSCategoryId(\"2\").description(\"Debian GNU/Linux 5(64-bit)\").build())\n            .add(OSType.builder().id(\"15\").OSCategoryId(\"2\").description(\"Debian GNU/Linux 5.0 (32-bit)\").build())\n            .add(OSType.builder().id(\"132\").OSCategoryId(\"2\").description(\"Debian GNU/Linux 6(32-bit)\").build())\n            .add(OSType.builder().id(\"133\").OSCategoryId(\"2\").description(\"Debian GNU/Linux 6(64-bit)\").build())\n            .add(OSType.builder().id(\"102\").OSCategoryId(\"6\").description(\"DOS\").build())\n            .add(OSType.builder().id(\"118\").OSCategoryId(\"4\").description(\"Fedora 10\").build())\n            .add(OSType.builder().id(\"117\").OSCategoryId(\"4\").description(\"Fedora 11\").build())\n            .add(OSType.builder().id(\"116\").OSCategoryId(\"4\").description(\"Fedora 12\").build())\n            .add(OSType.builder().id(\"115\").OSCategoryId(\"4\").description(\"Fedora 13\").build())\n            .add(OSType.builder().id(\"120\").OSCategoryId(\"4\").description(\"Fedora 8\").build())\n            .add(OSType.builder().id(\"119\").OSCategoryId(\"4\").description(\"Fedora 9\").build())\n            .add(OSType.builder().id(\"83\").OSCategoryId(\"9\").description(\"FreeBSD (32-bit)\").build())\n            .add(OSType.builder().id(\"84\").OSCategoryId(\"9\").description(\"FreeBSD (64-bit)\").build())\n            .add(OSType.builder().id(\"92\").OSCategoryId(\"6\").description(\"Microsoft Small Bussiness Server 2003\").build())\n            .add(OSType.builder().id(\"78\").OSCategoryId(\"8\").description(\"Novell Netware 5.1\").build())\n            .add(OSType.builder().id(\"77\").OSCategoryId(\"8\").description(\"Novell Netware 6.x\").build())\n            .add(OSType.builder().id(\"68\").OSCategoryId(\"7\").description(\"Open Enterprise Server\").build())\n            .add(OSType.builder().id(\"16\").OSCategoryId(\"3\").description(\"Oracle Enterprise Linux 5.0 (32-bit)\").build())\n            .add(OSType.builder().id(\"17\").OSCategoryId(\"3\").description(\"Oracle Enterprise Linux 5.0 (64-bit)\").build())\n            .add(OSType.builder().id(\"18\").OSCategoryId(\"3\").description(\"Oracle Enterprise Linux 5.1 (32-bit)\").build())\n            .add(OSType.builder().id(\"19\").OSCategoryId(\"3\").description(\"Oracle Enterprise Linux 5.1 (64-bit)\").build())\n            .add(OSType.builder().id(\"20\").OSCategoryId(\"3\").description(\"Oracle Enterprise Linux 5.2 (32-bit)\").build())\n            .add(OSType.builder().id(\"21\").OSCategoryId(\"3\").description(\"Oracle Enterprise Linux 5.2 (64-bit)\").build())\n            .add(OSType.builder().id(\"22\").OSCategoryId(\"3\").description(\"Oracle Enterprise Linux 5.3 (32-bit)\").build())\n            .add(OSType.builder().id(\"23\").OSCategoryId(\"3\").description(\"Oracle Enterprise Linux 5.3 (64-bit)\").build())\n            .add(OSType.builder().id(\"24\").OSCategoryId(\"3\").description(\"Oracle Enterprise Linux 5.4 (32-bit)\").build())\n            .add(OSType.builder().id(\"25\").OSCategoryId(\"3\").description(\"Oracle Enterprise Linux 5.4 (64-bit)\").build())\n            .add(OSType.builder().id(\"134\").OSCategoryId(\"3\").description(\"Oracle Enterprise Linux 5.5 (32-bit)\").build())\n            .add(OSType.builder().id(\"135\").OSCategoryId(\"3\").description(\"Oracle Enterprise Linux 5.5 (64-bit)\").build())\n            .add(OSType.builder().id(\"104\").OSCategoryId(\"7\").description(\"OS/2\").build())\n            .add(OSType.builder().id(\"60\").OSCategoryId(\"7\").description(\"Other (32-bit)\").build())\n            .add(OSType.builder().id(\"103\").OSCategoryId(\"7\").description(\"Other (64-bit)\").build())\n            .add(OSType.builder().id(\"75\").OSCategoryId(\"7\").description(\"Other 2.6x Linux (32-bit)\").build())\n            .add(OSType.builder().id(\"76\").OSCategoryId(\"7\").description(\"Other 2.6x Linux (64-bit)\").build())\n            .add(OSType.builder().id(\"98\").OSCategoryId(\"7\").description(\"Other Linux (32-bit)\").build())\n            .add(OSType.builder().id(\"99\").OSCategoryId(\"7\").description(\"Other Linux (64-bit)\").build())\n            .add(OSType.builder().id(\"59\").OSCategoryId(\"10\").description(\"Other Ubuntu (32-bit)\").build())\n            .add(OSType.builder().id(\"100\").OSCategoryId(\"10\").description(\"Other Ubuntu (64-bit)\").build())\n            .add(OSType.builder().id(\"131\").OSCategoryId(\"10\").description(\"Red Hat Enterprise Linux 2\").build())\n            .add(OSType.builder().id(\"66\").OSCategoryId(\"4\").description(\"Red Hat Enterprise Linux 3(32-bit)\").build())\n            .add(OSType.builder().id(\"67\").OSCategoryId(\"4\").description(\"Red Hat Enterprise Linux 3(64-bit)\").build())\n            .add(OSType.builder().id(\"106\").OSCategoryId(\"4\").description(\"Red Hat Enterprise Linux 4(64-bit)\").build())\n            .add(OSType.builder().id(\"26\").OSCategoryId(\"4\").description(\"Red Hat Enterprise Linux 4.5 (32-bit)\").build())\n            .add(OSType.builder().id(\"27\").OSCategoryId(\"4\").description(\"Red Hat Enterprise Linux 4.6 (32-bit)\").build())\n            .add(OSType.builder().id(\"28\").OSCategoryId(\"4\").description(\"Red Hat Enterprise Linux 4.7 (32-bit)\").build())\n            .add(OSType.builder().id(\"29\").OSCategoryId(\"4\").description(\"Red Hat Enterprise Linux 4.8 (32-bit)\").build())\n            .add(OSType.builder().id(\"30\").OSCategoryId(\"4\").description(\"Red Hat Enterprise Linux 5.0 (32-bit)\").build())\n            .add(OSType.builder().id(\"31\").OSCategoryId(\"4\").description(\"Red Hat Enterprise Linux 5.0 (64-bit)\").build())\n            .add(OSType.builder().id(\"32\").OSCategoryId(\"4\").description(\"Red Hat Enterprise Linux 5.1 (32-bit)\").build())\n            .add(OSType.builder().id(\"33\").OSCategoryId(\"4\").description(\"Red Hat Enterprise Linux 5.1 (64-bit)\").build())\n            .add(OSType.builder().id(\"34\").OSCategoryId(\"4\").description(\"Red Hat Enterprise Linux 5.2 (32-bit)\").build())\n            .add(OSType.builder().id(\"35\").OSCategoryId(\"4\").description(\"Red Hat Enterprise Linux 5.2 (64-bit)\").build())\n            .add(OSType.builder().id(\"36\").OSCategoryId(\"4\").description(\"Red Hat Enterprise Linux 5.3 (32-bit)\").build())\n            .add(OSType.builder().id(\"37\").OSCategoryId(\"4\").description(\"Red Hat Enterprise Linux 5.3 (64-bit)\").build())\n            .add(OSType.builder().id(\"38\").OSCategoryId(\"4\").description(\"Red Hat Enterprise Linux 5.4 (32-bit)\").build())\n            .add(OSType.builder().id(\"39\").OSCategoryId(\"4\").description(\"Red Hat Enterprise Linux 5.4 (64-bit)\").build())\n            .add(OSType.builder().id(\"113\").OSCategoryId(\"4\").description(\"Red Hat Enterprise Linux 5.5 (32-bit)\").build())\n            .add(OSType.builder().id(\"114\").OSCategoryId(\"4\").description(\"Red Hat Enterprise Linux 5.5 (64-bit)\").build())\n            .add(OSType.builder().id(\"136\").OSCategoryId(\"4\").description(\"Red Hat Enterprise Linux 6.0 (32-bit)\").build())\n            .add(OSType.builder().id(\"137\").OSCategoryId(\"4\").description(\"Red Hat Enterprise Linux 6.0 (64-bit)\").build())\n            .add(OSType.builder().id(\"85\").OSCategoryId(\"9\").description(\"SCO OpenServer 5\").build())\n            .add(OSType.builder().id(\"86\").OSCategoryId(\"9\").description(\"SCO UnixWare 7\").build())\n            .add(OSType.builder().id(\"79\").OSCategoryId(\"9\").description(\"Sun Solaris 10(32-bit)\").build())\n            .add(OSType.builder().id(\"80\").OSCategoryId(\"9\").description(\"Sun Solaris 10(64-bit)\").build())\n            .add(OSType.builder().id(\"82\").OSCategoryId(\"9\").description(\"Sun Solaris 8(Experimental)\").build())\n            .add(OSType.builder().id(\"81\").OSCategoryId(\"9\").description(\"Sun Solaris 9(Experimental)\").build())\n            .add(OSType.builder().id(\"109\").OSCategoryId(\"5\").description(\"SUSE Linux Enterprise 10(32-bit)\").build())\n            .add(OSType.builder().id(\"110\").OSCategoryId(\"5\").description(\"SUSE Linux Enterprise 10(64-bit)\").build())\n            .add(OSType.builder().id(\"96\").OSCategoryId(\"5\").description(\"SUSE Linux Enterprise 8(32-bit)\").build())\n            .add(OSType.builder().id(\"97\").OSCategoryId(\"5\").description(\"SUSE Linux Enterprise 8(64-bit)\").build())\n            .add(OSType.builder().id(\"107\").OSCategoryId(\"5\").description(\"SUSE Linux Enterprise 9(32-bit)\").build())\n            .add(OSType.builder().id(\"108\").OSCategoryId(\"5\").description(\"SUSE Linux Enterprise 9(64-bit)\").build())\n            .add(OSType.builder().id(\"41\").OSCategoryId(\"5\").description(\"SUSE Linux Enterprise Server 10 SP1 (32-bit)\")\n                  .build())\n            .add(OSType.builder().id(\"42\").OSCategoryId(\"5\").description(\"SUSE Linux Enterprise Server 10 SP1 (64-bit)\")\n                  .build())\n            .add(OSType.builder().id(\"43\").OSCategoryId(\"5\").description(\"SUSE Linux Enterprise Server 10 SP2 (32-bit)\")\n                  .build())\n            .add(OSType.builder().id(\"44\").OSCategoryId(\"5\").description(\"SUSE Linux Enterprise Server 10 SP2 (64-bit)\")\n                  .build())\n            .add(OSType.builder().id(\"45\").OSCategoryId(\"5\").description(\"SUSE Linux Enterprise Server 10 SP3 (64-bit)\")\n                  .build())\n            .add(OSType.builder().id(\"46\").OSCategoryId(\"5\").description(\"SUSE Linux Enterprise Server 11 (32-bit)\")\n                  .build())\n            .add(OSType.builder().id(\"47\").OSCategoryId(\"5\").description(\"SUSE Linux Enterprise Server 11 (64-bit)\")\n                  .build())\n            .add(OSType.builder().id(\"40\").OSCategoryId(\"5\").description(\"SUSE Linux Enterprise Server 9 SP4 (32-bit)\")\n                  .build())\n            .add(OSType.builder().id(\"121\").OSCategoryId(\"10\").description(\"Ubuntu 10.04 (32-bit)\").build())\n            .add(OSType.builder().id(\"126\").OSCategoryId(\"10\").description(\"Ubuntu 10.04 (64-bit)\").build())\n            .add(OSType.builder().id(\"125\").OSCategoryId(\"10\").description(\"Ubuntu 8.04 (32-bit)\").build())\n            .add(OSType.builder().id(\"130\").OSCategoryId(\"10\").description(\"Ubuntu 8.04 (64-bit)\").build())\n            .add(OSType.builder().id(\"124\").OSCategoryId(\"10\").description(\"Ubuntu 8.10 (32-bit)\").build())\n            .add(OSType.builder().id(\"129\").OSCategoryId(\"10\").description(\"Ubuntu 8.10 (64-bit)\").build())\n            .add(OSType.builder().id(\"123\").OSCategoryId(\"10\").description(\"Ubuntu 9.04 (32-bit)\").build())\n            .add(OSType.builder().id(\"128\").OSCategoryId(\"10\").description(\"Ubuntu 9.04 (64-bit)\").build())\n            .add(OSType.builder().id(\"122\").OSCategoryId(\"10\").description(\"Ubuntu 9.10 (32-bit)\").build())\n            .add(OSType.builder().id(\"127\").OSCategoryId(\"10\").description(\"Ubuntu 9.10 (64-bit)\").build())\n            .add(OSType.builder().id(\"95\").OSCategoryId(\"6\").description(\"Windows 2000 Advanced Server\").build())\n            .add(OSType.builder().id(\"105\").OSCategoryId(\"6\").description(\"Windows 2000 Professional\").build())\n            .add(OSType.builder().id(\"61\").OSCategoryId(\"6\").description(\"Windows 2000 Server\").build())\n            .add(OSType.builder().id(\"55\").OSCategoryId(\"6\").description(\"Windows 2000 Server SP4 (32-bit)\").build())\n            .add(OSType.builder().id(\"65\").OSCategoryId(\"6\").description(\"Windows 3.1\").build())\n            .add(OSType.builder().id(\"48\").OSCategoryId(\"6\").description(\"Windows 7 (32-bit)\").build())\n            .add(OSType.builder().id(\"49\").OSCategoryId(\"6\").description(\"Windows 7 (64-bit)\").build())\n            .add(OSType.builder().id(\"63\").OSCategoryId(\"6\").description(\"Windows 95\").build())\n            .add(OSType.builder().id(\"62\").OSCategoryId(\"6\").description(\"Windows 98\").build())\n            .add(OSType.builder().id(\"64\").OSCategoryId(\"6\").description(\"Windows NT 4\").build())\n            .add(OSType.builder().id(\"87\").OSCategoryId(\"6\").description(\"Windows Server 2003 DataCenter Edition(32-bit)\")\n                  .build())\n            .add(OSType.builder().id(\"88\").OSCategoryId(\"6\").description(\"Windows Server 2003 DataCenter Edition(64-bit)\")\n                  .build())\n            .add(OSType.builder().id(\"50\").OSCategoryId(\"6\").description(\"Windows Server 2003 Enterprise Edition(32-bit)\")\n                  .build())\n            .add(OSType.builder().id(\"51\").OSCategoryId(\"6\").description(\"Windows Server 2003 Enterprise Edition(64-bit)\")\n                  .build())\n            .add(OSType.builder().id(\"89\").OSCategoryId(\"6\").description(\"Windows Server 2003 Standard Edition(32-bit)\")\n                  .build())\n            .add(OSType.builder().id(\"90\").OSCategoryId(\"6\").description(\"Windows Server 2003 Standard Edition(64-bit)\")\n                  .build())\n            .add(OSType.builder().id(\"91\").OSCategoryId(\"6\").description(\"Windows Server 2003 Web Edition\").build())\n            .add(OSType.builder().id(\"52\").OSCategoryId(\"6\").description(\"Windows Server 2008 (32-bit)\").build())\n            .add(OSType.builder().id(\"53\").OSCategoryId(\"6\").description(\"Windows Server 2008 (64-bit)\").build())\n            .add(OSType.builder().id(\"54\").OSCategoryId(\"6\").description(\"Windows Server 2008 R2 (64-bit)\").build())\n            .add(OSType.builder().id(\"56\").OSCategoryId(\"6\").description(\"Windows Vista (32-bit)\").build())\n            .add(OSType.builder().id(\"101\").OSCategoryId(\"6\").description(\"Windows Vista (64-bit)\").build())\n            .add(OSType.builder().id(\"93\").OSCategoryId(\"6\").description(\"Windows XP (32-bit)\").build())\n            .add(OSType.builder().id(\"94\").OSCategoryId(\"6\").description(\"Windows XP (64-bit)\").build())\n            .add(OSType.builder().id(\"57\").OSCategoryId(\"6\").description(\"Windows XP SP2 (32-bit)\").build())\n            .add(OSType.builder().id(\"58\").OSCategoryId(\"6\").description(\"Windows XP SP3 (32-bit)\").build()).build();\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/ListPodsResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.parse;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.AllocationState;\nimport org.jclouds.cloudstack.domain.Pod;\nimport org.jclouds.json.BaseSetParserTest;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\")\npublic class ListPodsResponseTest extends BaseSetParserTest<Pod> {\n\n   @Override\n   public String resource() {\n      return \"/listpodsresponse.json\";\n   }\n\n   @Override\n   @SelectJson(\"pod\")\n   public Set<Pod> expected() {\n      Pod pod1 = Pod.builder()\n         .id(\"1\")\n         .name(\"Dev Pod 1\")\n         .zoneId(\"1\")\n         .zoneName(\"Dev Zone 1\")\n         .gateway(\"10.26.26.254\")\n         .netmask(\"255.255.255.0\")\n         .startIp(\"10.26.26.50\")\n         .endIp(\"10.26.26.100\")\n         .allocationState(AllocationState.ENABLED)\n         .build();\n      Pod pod2 = Pod.builder()\n         .id(\"2\")\n         .name(\"Dev Pod 2\")\n         .zoneId(\"2\")\n         .zoneName(\"Dev Zone 2\")\n         .gateway(\"10.22.22.254\")\n         .netmask(\"255.255.255.0\")\n         .startIp(\"10.22.22.25\")\n         .endIp(\"10.22.22.50\")\n         .allocationState(AllocationState.ENABLED)\n         .build();\n      return ImmutableSet.of(pod1, pod2);\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/ListPortForwardingRulesResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.parse;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.PortForwardingRule;\nimport org.jclouds.cloudstack.domain.Tag;\nimport org.jclouds.json.BaseSetParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\")\npublic class ListPortForwardingRulesResponseTest extends BaseSetParserTest<PortForwardingRule> {\n\n   @Override\n   protected Injector injector() {\n      return Guice.createInjector(new GsonModule() {\n\n         @Override\n         protected void configure() {\n            bind(DateAdapter.class).to(Iso8601DateAdapter.class);\n            super.configure();\n         }\n\n      });\n   }\n\n   @Override\n   public String resource() {\n      return \"/listportforwardingrulesresponse.json\";\n   }\n\n   @Override\n   @SelectJson(\"portforwardingrule\")\n   public Set<PortForwardingRule> expected() {\n      Set<String> cidrs = ImmutableSet.of(\"0.0.0.0/1\", \"128.0.0.0/1\");\n      return ImmutableSet.<PortForwardingRule> of(\n            PortForwardingRule.builder().id(\"15\").privatePort(22).protocol(PortForwardingRule.Protocol.TCP)\n                  .publicPort(2022).virtualMachineId(\"3\").virtualMachineName(\"i-3-3-VM\").IPAddressId(\"3\")\n                  .IPAddress(\"72.52.126.32\").state(PortForwardingRule.State.ACTIVE)\n                  .CIDRs(cidrs).tags(Tag.builder().account(\"1\").domain(\"ROOT\").domainId(\"1\").key(\"some-tag\").resourceId(\"15\")\n                  .resourceType(Tag.ResourceType.PORT_FORWARDING_RULE).value(\"some-value\").build()).build(),\n            PortForwardingRule.builder().id(\"18\").privatePort(22).protocol(PortForwardingRule.Protocol.TCP)\n                  .publicPort(22).virtualMachineId(\"89\").virtualMachineName(\"i-3-89-VM\").IPAddressId(\"34\")\n                  .IPAddress(\"72.52.126.63\").state(PortForwardingRule.State.ACTIVE).build());\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/ListPublicIPAddressesResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.parse;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.PublicIPAddress;\nimport org.jclouds.cloudstack.domain.Tag;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.json.BaseSetParserTest;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\")\npublic class ListPublicIPAddressesResponseTest extends BaseSetParserTest<PublicIPAddress> {\n\n   @Override\n   public String resource() {\n      return \"/listpublicipaddressesresponse.json\";\n   }\n\n   @Override\n   @SelectJson(\"publicipaddress\")\n   public Set<PublicIPAddress> expected() {\n      return ImmutableSet.of(PublicIPAddress.builder().id(\"30\").IPAddress(\"72.52.126.59\")\n            .allocated(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2011-02-19T21:15:01-0800\")).zoneId(\"1\")\n            .zoneName(\"San Jose 1\").isSourceNAT(false).account(\"adrian\").domainId(\"1\").domain(\"ROOT\")\n            .usesVirtualNetwork(true).isStaticNAT(false).associatedNetworkId(\"204\").networkId(\"200\")\n            .state(PublicIPAddress.State.ALLOCATED)\n            .tags(Tag.builder()\n                  .account(\"adrian\")\n                  .domain(\"ROOT\")\n                  .domainId(\"1\")\n                  .key(\"some-tag\")\n                  .resourceId(\"30\")\n                  .resourceType(Tag.ResourceType.PUBLIC_IP_ADDRESS)\n                  .value(\"some-value\")\n                  .build())\n            .build());\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/ListSSHKeyPairsResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.parse;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.SshKeyPair;\nimport org.jclouds.json.BaseSetParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\")\npublic class ListSSHKeyPairsResponseTest extends BaseSetParserTest<SshKeyPair> {\n\n   @Override\n   protected Injector injector() {\n      return Guice.createInjector(new GsonModule() {\n\n         @Override\n         protected void configure() {\n            bind(DateAdapter.class).to(Iso8601DateAdapter.class);\n            super.configure();\n         }\n\n      });\n\n   }\n\n   @Override\n   public String resource() {\n      return \"/listsshkeypairsresponse.json\";\n   }\n\n   @Override\n   @SelectJson(\"sshkeypair\")\n   public Set<SshKeyPair> expected() {\n      return ImmutableSet.<SshKeyPair> of(SshKeyPair.builder().name(\"jclouds-keypair\")\n            .fingerprint(\"1c:06:74:52:3b:99:1c:95:5c:04:c2:f4:ba:77:6e:7b\").build());\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/ListSecurityGroupsResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.parse;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.IngressRule;\nimport org.jclouds.cloudstack.domain.SecurityGroup;\nimport org.jclouds.cloudstack.domain.Tag;\nimport org.jclouds.json.BaseSetParserTest;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\")\npublic class ListSecurityGroupsResponseTest extends BaseSetParserTest<SecurityGroup> {\n\n   @Override\n   public String resource() {\n      return \"/listsecuritygroupsresponse.json\";\n   }\n\n   @Override\n   @SelectJson(\"securitygroup\")\n   public Set<SecurityGroup> expected() {\n      return ImmutableSet\n            .<SecurityGroup> builder()\n            .add(SecurityGroup\n                  .builder()\n                  .id(\"13\")\n                  .name(\"default\")\n                  .description(\"description\")\n                  .account(\"adrian\")\n                  .domainId(\"1\")\n                  .domain(\"ROOT\")\n                  .ingressRules(\n                        ImmutableSet.of(\n\n                              IngressRule.builder().id(\"5\").protocol(\"tcp\").startPort(22).endPort(22)\n                                    .securityGroupName(\"adriancole\").account(\"adrian\").build(),\n\n                              IngressRule.builder().id(\"6\").protocol(\"udp\").startPort(11).endPort(11).CIDR(\"1.1.1.1/24\")\n                                    .build()\n                        )\n                  ).build())\n            .add(SecurityGroup.builder().id(\"12\").name(\"adriancole\").account(\"adrian\").domainId(\"1\").domain(\"ROOT\").build())\n            .add(SecurityGroup.builder().id(\"15\").name(\"2\").description(\"description\").account(\"adrian\").domainId(\"1\")\n                  .domain(\"ROOT\").build())\n\n            .add(SecurityGroup.builder().id(\"14\").name(\"1\").description(\"description\").account(\"adrian\").domainId(\"1\")\n                  .domain(\"ROOT\").ingressRules(ImmutableSet.of(\n\n                        IngressRule.builder().id(\"7\").protocol(\"tcp\").startPort(10).endPort(10).CIDR(\"1.1.1.1/24\").build(),\n\n                        IngressRule.builder().id(\"8\").protocol(\"tcp\").startPort(10).endPort(10).CIDR(\"2.2.2.2/16\").build()))\n                  .build())\n            .add(SecurityGroup\n                  .builder()\n                  .id(\"16\")\n                  .name(\"with1and2\")\n                  .description(\"description\")\n                  .account(\"adrian\")\n                  .domainId(\"1\")\n                  .domain(\"ROOT\")\n                  .ingressRules(\n                        ImmutableSet.of(IngressRule.builder().id(\"9\").protocol(\"icmp\").ICMPType(-1).ICMPCode(-1)\n                                    .securityGroupName(\"1\").account(\"adrian\").build(),\n\n                              IngressRule.builder().id(\"10\").protocol(\"tcp\").startPort(22).endPort(22).securityGroupName(\"1\")\n                                    .account(\"adrian\").build(),\n\n                              IngressRule.builder().id(\"11\").protocol(\"tcp\").startPort(22).endPort(22).securityGroupName(\"2\")\n                                    .account(\"adrian\").build()\n                        )\n                  )\n                  .tags(Tag.builder()\n                        .account(\"adrian\")\n                        .domain(\"ROOT\")\n                        .domainId(\"1\")\n                        .key(\"some-tag\")\n                        .resourceId(\"16\")\n                        .resourceType(Tag.ResourceType.SECURITY_GROUP)\n                        .value(\"some-value\")\n                        .build())\n                  .build()).build();\n\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/ListServiceOfferingsResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.parse;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.ServiceOffering;\nimport org.jclouds.cloudstack.domain.StorageType;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.json.BaseSetParserTest;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\")\npublic class ListServiceOfferingsResponseTest extends BaseSetParserTest<ServiceOffering> {\n\n   @Override\n   public String resource() {\n      return \"/listserviceofferingsresponse.json\";\n   }\n\n   @Override\n   @SelectJson(\"serviceoffering\")\n   public Set<ServiceOffering> expected() {\n      return ImmutableSet.<ServiceOffering> of(\n            ServiceOffering.builder().id(\"1\").name(\"Small Instance\")\n                  .displayText(\"Small Instance - 500 MhZ CPU, 512 MB RAM - $0.05 per hour\").cpuNumber(1).cpuSpeed(500)\n                  .memory(512)\n                  .created(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2011-02-11T15:22:32-0800\"))\n                  .storageType(StorageType.SHARED).supportsHA(false).build(),\n            ServiceOffering.builder().id(\"2\").name(\"Medium Instance\")\n                  .displayText(\"Medium Instance, 1 GhZ CPU,  1 GB RAM - $0.10 per hour\").cpuNumber(1).cpuSpeed(1000)\n                  .memory(1024)\n                  .created(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2011-02-11T15:22:32-0800\"))\n                  .storageType(StorageType.SHARED).supportsHA(false).build());\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/ListStoragePoolsResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.parse;\n\nimport java.util.Calendar;\nimport java.util.Date;\nimport java.util.Set;\nimport java.util.TimeZone;\n\nimport org.jclouds.cloudstack.config.CloudStackParserModule;\nimport org.jclouds.cloudstack.domain.StoragePool;\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\", testName = \"ListStoragePoolsResponseTest\")\npublic class ListStoragePoolsResponseTest extends BaseItemParserTest<Set<StoragePool>> {\n\n   @Override\n   public String resource() {\n      return \"/liststoragepoolsresponse.json\";\n   }\n\n   @Override\n   @SelectJson(\"storagepool\")\n   public Set<StoragePool> expected() {\n      Calendar c = Calendar.getInstance(TimeZone.getTimeZone(\"GMT+02:00\"));\n      c.set(Calendar.YEAR, 2011);\n      c.set(Calendar.MONTH, Calendar.NOVEMBER);\n      c.set(Calendar.DAY_OF_MONTH, 26);\n      c.set(Calendar.HOUR_OF_DAY, 23);\n      c.set(Calendar.MINUTE, 33);\n      c.set(Calendar.SECOND, 6);\n      Date created = c.getTime();\n\n      StoragePool storagePool = StoragePool.builder().id(\"201\").zoneId(\"1\").zoneName(\"Dev Zone 1\").podId(\"1\")\n               .podName(\"Dev Pod 1\").name(\"NFS Pri 1\").ipAddress(\"10.26.26.165\").path(\"/mnt/nfs/cs_pri\")\n               .created(created).type(StoragePool.Type.NETWORK_FILESYSTEM).clusterId(\"1\").clusterName(\"Xen Clust 1\")\n               .diskSizeTotal(898356445184L).diskSizeAllocated(18276679680L).tag(\"tag1\").state(StoragePool.State.UP)\n               .build();\n      return ImmutableSet.of(storagePool);\n   }\n   \n   @Override\n   protected Injector injector() {\n      return Guice.createInjector(new GsonModule(), new CloudStackParserModule());\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/ListTagsResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.parse;\n\nimport java.util.Set;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport org.jclouds.cloudstack.domain.Tag;\nimport org.jclouds.json.BaseSetParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class ListTagsResponseTest extends BaseSetParserTest<Tag> {\n\n   @Override\n   protected Injector injector() {\n      return Guice.createInjector(new GsonModule() {\n\n         @Override\n         protected void configure() {\n            bind(DateAdapter.class).to(Iso8601DateAdapter.class);\n            super.configure();\n         }\n\n      });\n   }\n\n   @Override\n   public String resource() {\n      return \"/listtagsresponse.json\";\n   }\n\n   @Override\n   @SelectJson(\"tag\")\n   public Set<Tag> expected() {\n      return ImmutableSet.<Tag>of(\n            Tag.builder()\n                  .account(\"admin\")\n                  .domain(\"ROOT\")\n                  .domainId(\"79dc06c4-4432-11e4-b70d-000c29e19aa0\")\n                  .key(\"test-tag\")\n                  .resourceId(\"54fe1d53-5d73-4184-8b62-948b9d8e08fb\")\n                  .resourceType(Tag.ResourceType.TEMPLATE)\n                  .value(\"true\").build()\n      );\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/ListTemplatesResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.parse;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.Tag;\nimport org.jclouds.cloudstack.domain.Template;\nimport org.jclouds.cloudstack.domain.Template.Format;\nimport org.jclouds.cloudstack.domain.Template.Type;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.json.BaseSetParserTest;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\")\npublic class ListTemplatesResponseTest extends BaseSetParserTest<Template> {\n\n   @Override\n   public String resource() {\n      // grep listtemplatesresponse ./target/test-data/jclouds-wire.log|tail\n      // -1|sed -e 's/.*<< \"//g' -e 's/\"$//g'\n      return \"/listtemplatesresponse.json\";\n   }\n\n   @Override\n   @SelectJson(\"template\")\n   public Set<Template> expected() {\n      return ImmutableSet.of(\n            Template.builder().id(\"2\").name(\"CentOS 5.3(64-bit) no GUI (XenServer)\")\n                  .displayText(\"CentOS 5.3(64-bit) no GUI (XenServer)\").isPublic(true)\n                  .created(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2011-03-20T19:17:48-0700\"))\n                  .ready(false).passwordEnabled(false).format(Format.VHD).featured(true).crossZones(true).OSTypeId(\"11\")\n                  .OSType(\"CentOS 5.3 (32-bit)\").account(\"system\").zoneId(\"2\").zone(\"Chicago\").type(Type.BUILTIN)\n                  .hypervisor(\"XenServer\").domain(\"ROOT\").domainId(\"1\").extractable(true).build(),\n            Template.builder().id(\"4\").name(\"CentOS 5.5(64-bit) no GUI (KVM)\")\n                  .displayText(\"CentOS 5.5(64-bit) no GUI (KVM)\").isPublic(true)\n                  .created(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2011-03-20T19:17:48-0700\"))\n                  .ready(true).passwordEnabled(false).format(Format.QCOW2).featured(true).crossZones(true)\n                  .OSTypeId(\"112\").OSType(\"CentOS 5.5 (64-bit)\").account(\"system\").zoneId(\"2\").zone(\"Chicago\")\n                  .size(8589934592L).type(Type.BUILTIN).hypervisor(\"KVM\").domain(\"ROOT\").domainId(\"1\").extractable(true)\n                  .build(),\n            Template.builder().id(\"203\").name(\"Windows 7 KVM\").displayText(\"Windows 7 KVM\").isPublic(true)\n                  .created(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2011-03-20T22:02:18-0700\"))\n                  .ready(true).passwordEnabled(false).format(Format.QCOW2).featured(true).crossZones(false)\n                  .OSTypeId(\"48\").OSType(\"Windows 7 (32-bit)\").account(\"admin\").zoneId(\"2\").zone(\"Chicago\")\n                  .size(17179869184L).type(Type.USER).hypervisor(\"KVM\").domain(\"ROOT\").domainId(\"1\").extractable(false)\n                  .build(),\n            Template.builder().id(\"7\").name(\"CentOS 5.3(64-bit) no GUI (vSphere)\")\n                  .displayText(\"CentOS 5.3(64-bit) no GUI (vSphere)\").isPublic(true)\n                  .created(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2011-03-20T19:17:48-0700\"))\n                  .ready(false).passwordEnabled(false).format(Format.OVA).featured(true).crossZones(true).OSTypeId(\"12\")\n                  .OSType(\"CentOS 5.3 (64-bit)\").account(\"system\").zoneId(\"2\").zone(\"Chicago\").type(Type.BUILTIN)\n                  .hypervisor(\"VMware\").domain(\"ROOT\").domainId(\"1\").extractable(true).build(),\n            Template.builder().id(\"241\").name(\"kvmdev4\").displayText(\"v5.6.28_Dev4\").isPublic(true)\n                  .created(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2011-04-21T09:43:25-0700\"))\n                  .ready(true).passwordEnabled(false).format(Format.QCOW2).featured(false).crossZones(false)\n                  .OSTypeId(\"14\").OSType(\"CentOS 5.4 (64-bit)\").account(\"rs3\").zoneId(\"2\").zone(\"Chicago\")\n                  .size(10737418240L).type(Type.USER).hypervisor(\"KVM\").domain(\"ROOT\").domainId(\"1\").extractable(false)\n                  .tags(ImmutableSet.of(Tag.builder().account(\"rs3\").domain(\"ROOT\").domainId(\"1\").key(\"some-tag\")\n                        .resourceId(\"241\").resourceType(Tag.ResourceType.TEMPLATE).value(\"some-value\").build()))\n                  .build());\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/ListUsageRecordsResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.parse;\n\nimport java.util.Calendar;\nimport java.util.Date;\nimport java.util.Set;\nimport java.util.TimeZone;\n\nimport org.jclouds.cloudstack.config.CloudStackParserModule;\nimport org.jclouds.cloudstack.domain.UsageRecord;\nimport org.jclouds.json.BaseSetParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport org.jclouds.cloudstack.domain.Tag;\n\n@Test(groups = \"unit\")\npublic class ListUsageRecordsResponseTest extends BaseSetParserTest<UsageRecord> {\n\n   @Override\n   public String resource() {\n      return \"/listusagerecordsresponse.json\";\n   }\n\n   @Override\n   @SelectJson(\"usagerecord\")\n   public Set<UsageRecord> expected() {\n      Calendar c = Calendar.getInstance(TimeZone.getTimeZone(\"GMT\"));\n      c.set(Calendar.YEAR, 2011);\n      c.set(Calendar.MONTH, Calendar.DECEMBER);\n      c.set(Calendar.DAY_OF_MONTH, 15);\n      c.set(Calendar.HOUR_OF_DAY, 0);\n      c.set(Calendar.MINUTE, 0);\n      c.set(Calendar.SECOND, 0);\n      c.set(Calendar.MILLISECOND, 0);\n      Date start = c.getTime();\n      c.add(Calendar.DAY_OF_MONTH, 1);\n      c.add(Calendar.SECOND, -1);\n      Date end = c.getTime();\n\n      return ImmutableSet.of(UsageRecord.builder()\n               .accountName(\"admin\").accountId(\"2\").domainId(\"1\").zoneId(\"1\")\n               .description(\"Template Id:203 Size:3117171712\")\n               .usage(\"24 Hrs\").usageType(UsageRecord.UsageType.TEMPLATE).rawUsageHours(24)\n               .size(3117171712L).templateId(\"0\").id(\"203\").project(\"project1\").projectId(\"1\")\n               .startDate(start).endDate(end).domain(\"myDomain\").virtualSize(3117171712L)\n               .cpuNumber(2L).cpuSpeed(1024L).memory(512L).isSystem(false).isDefault(false)\n               .tags(ImmutableSet.of(Tag.builder().key(\"env\").value(\"dev\").build())).build());\n\n   }\n   \n   @Override\n   protected Injector injector() {\n      return Guice.createInjector(new GsonModule(), new CloudStackParserModule());\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/ListVirtualMachinesResponse3xTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.parse;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.GuestIPType;\nimport org.jclouds.cloudstack.domain.NIC;\nimport org.jclouds.cloudstack.domain.Tag;\nimport org.jclouds.cloudstack.domain.TrafficType;\nimport org.jclouds.cloudstack.domain.VirtualMachine;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.json.BaseSetParserTest;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\")\npublic class ListVirtualMachinesResponse3xTest extends BaseSetParserTest<VirtualMachine> {\n\n   @Override\n   public String resource() {\n      return \"/listvirtualmachinesresponse3x.json\";\n   }\n\n   @Override\n   @SelectJson(\"virtualmachine\")\n   public Set<VirtualMachine> expected() {\n      return ImmutableSet.of(VirtualMachine\n            .builder()\n            .id(\"fee2ccb3-c1f2-4e7b-8465-42b390e10dff\")\n            .name(\"cloudstack-r-611\")\n            .displayName(\"cloudstack-r-611\")\n            .account(\"jcloud2\")\n            .domainId(\"ea66e3a5-d007-42e8-a0de-ec5ce778a1d7\")\n            .domain(\"jCloud\")\n            .created(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2012-05-22T09:18:28-0700\"))\n            .state(VirtualMachine.State.RUNNING)\n            .isHAEnabled(false)\n            .zoneId(\"1\")\n            .zoneName(\"Santa Clara Zone\")\n            .templateId(\"5c65f152-a4bc-4405-a756-fd10841a9aa7\")\n                             .templateName(\"jclouds-6d4bdc29\")\n            .templateDisplayText(\"jclouds live testCreateTemplate\")\n            .passwordEnabled(false)\n            .serviceOfferingId(\"5305750d-df71-4da9-8cd0-e23c2236a6e2\")\n            .serviceOfferingName(\"Micro Instance\")\n            .cpuCount(1)\n            .cpuSpeed(500)\n            .memory(256)\n            .guestOSId(\"6dcd58ce-1ec6-432c-af0b-9ab4ca9207d9\")\n            .rootDeviceId(\"0\")\n            .rootDeviceType(\"IscsiLUN\")\n                             .publicIP(\"72.52.126.110\")\n                             .publicIPId(\"e202aafb-ab41-4dc0-80e9-9fcd64fbf45c\")\n            .nics(ImmutableSet.of(NIC.builder().id(\"48640c5e-90f3-45bd-abd2-a108ca8957ac\").\n                  networkId(\"c0d5db5b-f7d5-44e1-b854-21ecd1a09dbf\").netmask(\"255.255.255.0\").gateway(\"10.1.1.1\")\n                  .IPAddress(\"10.1.1.227\").trafficType(TrafficType.GUEST).guestIPType(GuestIPType.ISOLATED)\n                  .isDefault(true).build()))\n            .tags(Tag.builder()\n                  .account(\"jcloud2\")\n                  .domain(\"jCloud\")\n                  .domainId(\"ea66e3a5-d007-42e8-a0de-ec5ce778a1d7\")\n                  .key(\"some-tag\")\n                  .resourceId(\"fee2ccb3-c1f2-4e7b-8465-42b390e10dff\")\n                  .resourceType(Tag.ResourceType.USER_VM)\n                  .value(\"some-value\")\n                  .build())\n            .build());\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/ListVirtualMachinesResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.parse;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.GuestIPType;\nimport org.jclouds.cloudstack.domain.NIC;\nimport org.jclouds.cloudstack.domain.Tag;\nimport org.jclouds.cloudstack.domain.TrafficType;\nimport org.jclouds.cloudstack.domain.VirtualMachine;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.json.BaseSetParserTest;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\")\npublic class ListVirtualMachinesResponseTest extends BaseSetParserTest<VirtualMachine> {\n\n   @Override\n   public String resource() {\n      return \"/listvirtualmachinesresponse.json\";\n   }\n\n   @Override\n   @SelectJson(\"virtualmachine\")\n   public Set<VirtualMachine> expected() {\n      return ImmutableSet.of(VirtualMachine\n            .builder()\n            .id(\"54\")\n            .name(\"i-3-54-VM\")\n            .displayName(\"i-3-54-VM\")\n            .account(\"adrian\")\n            .domainId(\"1\")\n            .domain(\"ROOT\")\n            .created(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2011-02-16T14:28:37-0800\"))\n            .state(VirtualMachine.State.STARTING)\n            .isHAEnabled(false)\n            .zoneId(\"1\")\n            .zoneName(\"San Jose 1\")\n            .templateId(\"2\")\n            .templateName(\"CentOS 5.3(64-bit) no GUI (XenServer)\")\n            .templateDisplayText(\"CentOS 5.3(64-bit) no GUI (XenServer)\")\n            .passwordEnabled(false)\n            .serviceOfferingId(\"1\")\n            .serviceOfferingName(\"Small Instance\")\n            .cpuCount(1)\n            .cpuSpeed(500)\n            .memory(512)\n            .guestOSId(\"11\")\n            .rootDeviceId(\"0\")\n            .rootDeviceType(\"NetworkFilesystem\")\n            .jobId(\"63\")\n            .jobStatus(0)\n            .nics(ImmutableSet.of(NIC.builder().id(\"72\").networkId(\"204\").netmask(\"255.255.255.0\").gateway(\"10.1.1.1\")\n                  .IPAddress(\"10.1.1.18\").trafficType(TrafficType.GUEST).guestIPType(GuestIPType.VIRTUAL)\n                  .isDefault(true).build()))\n            .hypervisor(\"XenServer\")\n            .tags(ImmutableSet.of(\n                  Tag.builder().account(\"adrian\")\n                        .resourceId(\"54\")\n                        .resourceType(Tag.ResourceType.USER_VM)\n                        .key(\"some-tag\")\n                        .value(\"some-value\")\n                        .domain(\"ROOT\")\n                        .domainId(\"1\")\n                        .build(),\n                  Tag.builder().account(\"adrian\")\n                        .resourceId(\"54\")\n                        .resourceType(Tag.ResourceType.USER_VM)\n                        .key(\"another-tag\")\n                        .value(\"jclouds-empty-tag-placeholder\")\n                        .domain(\"ROOT\")\n                        .domainId(\"1\")\n                        .build()))\n            .build());\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/ListVlanIPRangesResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.parse;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.VlanIPRange;\nimport org.jclouds.json.BaseSetParserTest;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\")\npublic class ListVlanIPRangesResponseTest extends BaseSetParserTest<VlanIPRange> {\n\n   @Override\n   public String resource() {\n      return \"/listvlaniprangesresponse.json\";\n   }\n\n   @Override\n   @SelectJson(\"vlaniprange\")\n   public Set<VlanIPRange> expected() {\n      VlanIPRange range1 = VlanIPRange.builder()\n         .id(\"1\")\n         .forVirtualNetwork(true)\n         .zoneId(\"1\")\n         .vlan(\"127\")\n         .account(\"system\")\n         .domainId(\"1\")\n         .domain(\"ROOT\")\n         .gateway(\"10.27.27.254\")\n         .netmask(\"255.255.255.0\")\n         .startIP(\"10.27.27.50\")\n         .endIP(\"10.27.27.100\")\n         .networkId(\"200\")\n         .build();\n      VlanIPRange range2 = VlanIPRange.builder()\n         .id(\"2\")\n         .forVirtualNetwork(false)\n         .zoneId(\"2\")\n         .vlan(\"untagged\")\n         .account(\"system\")\n         .domainId(\"1\")\n         .domain(\"ROOT\")\n         .podId(\"2\")\n         .podName(\"Dev Pod 2\")\n         .gateway(\"10.22.22.254\")\n         .netmask(\"255.255.255.0\")\n         .startIP(\"10.22.22.51\")\n         .endIP(\"10.22.22.100\")\n         .networkId(\"209\")\n         .build();\n      return ImmutableSet.of(range1, range2);\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/ListZonesResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.parse;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.domain.NetworkType;\nimport org.jclouds.cloudstack.domain.Tag;\nimport org.jclouds.cloudstack.domain.Zone;\nimport org.jclouds.json.BaseSetParserTest;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\")\npublic class ListZonesResponseTest extends BaseSetParserTest<Zone> {\n\n   @Override\n   public String resource() {\n      return \"/listzonesresponse.json\";\n   }\n\n   @Override\n   @SelectJson(\"zone\")\n   public Set<Zone> expected() {\n      return          ImmutableSet.of(\n            Zone.builder()\n                  .id(\"1\")\n                  .name(\"San Jose 1\")\n                  .networkType(NetworkType.ADVANCED)\n                  .securityGroupsEnabled(false).build(),\n            Zone.builder()\n                  .id(\"2\")\n                  .name(\"Chicago\")\n                  .networkType(NetworkType.ADVANCED)\n                  .securityGroupsEnabled(true)\n                  .tags(Tag.builder()\n                        .account(\"1\")\n                        .domain(\"ROOT\")\n                        .domainId(\"1\")\n                        .key(\"some-tag\")\n                        .resourceId(\"2\")\n                        .resourceType(Tag.ResourceType.ZONE)\n                        .value(\"some-value\")\n                        .build())\n                  .build());\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/RegisterUserKeysResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.parse;\n\nimport org.jclouds.cloudstack.domain.ApiKeyPair;\nimport org.jclouds.json.BaseParserTest;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class RegisterUserKeysResponseTest extends BaseParserTest<ApiKeyPair, Object> {\n\n   @Override\n   public String resource() {\n      return \"/registeruserkeysresponse.json\";\n   }\n\n   @Override\n   @SelectJson(\"userkeys\")\n   public ApiKeyPair expected() {\n      return ApiKeyPair.builder()\n            .apiKey(\"5nn6IAQ-0BYuAKTu45rf49VsyX0rg9t48TpY8NKsduE5t-_1_g_AU8ZjP3OJvVdlzWKL3Lgfa6_nkC9hU6NyQQ\")\n            .secretKey(\"GSCDYzj65CiSkxzCJxlFvcF52qglM7HbuG6QL7zYVeWVhVO8GnW85wGTBBuZ3xpzEN_UfKnsORvrNszYQ1ofAw\").build();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/predicates/JobCompleteTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.predicates;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.Assert.fail;\n\nimport org.jclouds.cloudstack.AsyncJobException;\nimport org.jclouds.cloudstack.CloudStackApi;\nimport org.jclouds.cloudstack.domain.AsyncJob;\nimport org.jclouds.cloudstack.domain.AsyncJobError;\nimport org.jclouds.cloudstack.domain.AsyncJob.ResultCode;\nimport org.jclouds.cloudstack.domain.AsyncJob.Status;\nimport org.jclouds.cloudstack.domain.AsyncJobError.ErrorCode;\nimport org.jclouds.cloudstack.features.AsyncJobApi;\nimport org.testng.annotations.BeforeMethod;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", singleThreaded = true)\npublic class JobCompleteTest {\n\n   CloudStackApi client;\n   AsyncJobApi asyncJobClient;\n\n   @BeforeMethod\n   public void setUp() {\n      client = createMock(CloudStackApi.class);\n      asyncJobClient = createMock(AsyncJobApi.class);\n\n      expect(client.getAsyncJobApi()).andReturn(asyncJobClient);\n   }\n\n   @Test\n   public void testJobComplete() {\n      AsyncJob<?> job = AsyncJob.builder().id(\"100\")\n         .status(Status.SUCCEEDED).resultCode(ResultCode.SUCCESS).build();\n      expect((Object) asyncJobClient.getAsyncJob(job.getId())).andReturn(job);\n\n      replay(client, asyncJobClient);\n      assertTrue(new JobComplete(client).apply(job.getId()));\n      verify(client, asyncJobClient);\n   }\n\n   @Test\n   public void testFailedJobComplete() {\n      AsyncJob<?> job = AsyncJob.builder().id(\"100\")\n         .status(Status.FAILED).resultCode(ResultCode.FAIL)\n         .error(AsyncJobError.builder().errorCode(ErrorCode.INTERNAL_ERROR).errorText(\"Dummy test error\").build()).build();\n      expect((Object) asyncJobClient.getAsyncJob(job.getId())).andReturn(job);\n\n      replay(client, asyncJobClient);\n      try {\n         new JobComplete(client).apply(job.getId());\n         fail(\"No exception thrown\");\n\n      } catch (AsyncJobException e) {\n         assertTrue(e.toString().contains(\"Dummy test error\"));\n      }\n      verify(client, asyncJobClient);\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/predicates/NetworkPredicatesTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.predicates;\n\nimport static org.jclouds.cloudstack.predicates.NetworkPredicates.defaultNetworkInZone;\nimport static org.jclouds.cloudstack.predicates.NetworkPredicates.hasLoadBalancerService;\nimport static org.jclouds.cloudstack.predicates.NetworkPredicates.supportsPortForwarding;\nimport static org.jclouds.cloudstack.predicates.NetworkPredicates.supportsStaticNAT;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.cloudstack.domain.Network;\nimport org.jclouds.cloudstack.domain.NetworkService;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Predicates;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\")\npublic class NetworkPredicatesTest {\n\n   public void testHasLoadBalancerService() {\n      Network network = Network.builder().id(\"204\").services(ImmutableSet.of(NetworkService.builder().name(\"Lb\").build())).build();\n\n      assert hasLoadBalancerService().apply(network);\n      assert !supportsStaticNAT().apply(network);\n      assert !supportsPortForwarding().apply(network);\n\n   }\n\n   public void testSupportsStaticNATFindsWhenFirewallHasStaticNatFeature() {\n      Network network = Network\n            .builder()\n            .id(\"204\")\n            .services(\n                  ImmutableSet.of(NetworkService.builder().name(\"Firewall\").capabilities(\n                        ImmutableMap.<String, String> of(\"StaticNat\", \"true\")).build()))\n            .build();\n\n      assert !hasLoadBalancerService().apply(network);\n      assert supportsStaticNAT().apply(network);\n      assert !supportsPortForwarding().apply(network);\n   }\n\n   public void testNoSupport() {\n      Network network = Network.builder().id(\"204\")\n            .services(ImmutableSet.of(NetworkService.builder().name(\"Firewall\").capabilities(\n                  ImmutableMap.<String, String> of()).build())).build();\n\n      assert !hasLoadBalancerService().apply(network);\n      assert !supportsStaticNAT().apply(network);\n      assert !supportsPortForwarding().apply(network);\n   }\n\n   public void testSupportsPortForwardingFindsWhenFirewallHasPortForwardingFeature() {\n      Network network = Network\n            .builder()\n            .id(\"204\")\n            .services(\n                  ImmutableSet.of(NetworkService.builder().name(\"Firewall\").capabilities(\n                        ImmutableMap.<String, String> of(\"PortForwarding\", \"true\")).build())).build();\n\n      assert !hasLoadBalancerService().apply(network);\n      assert !supportsStaticNAT().apply(network);\n      assert supportsPortForwarding().apply(network);\n   }\n\n   public void testSupportsPortForwardingAndStaticNATWhenFirewallHasFeatures() {\n      Network network = Network\n            .builder()\n            .id(\"204\")\n            .services(\n                  ImmutableSet.of(NetworkService.builder().name(\"Firewall\").capabilities(\n                        ImmutableMap.<String, String> of(\"StaticNat\", \"true\", \"PortForwarding\", \"true\")).build())).build();\n\n      assert Predicates.and(supportsPortForwarding(), supportsStaticNAT()).apply(network);\n      assert !hasLoadBalancerService().apply(network);\n\n   }\n\n   public void testDefaultNetworkInZone() {\n      Network defaultInZone = Network.builder().id(\"42-1\").isDefault(true).zoneId(\"42\").build();\n      Network defaultNotInZone = Network.builder().id(\"200-1\").isDefault(true).zoneId(\"200\").build();\n      Network notDefaultInZone = Network.builder().id(\"42-2\").isDefault(false).zoneId(\"42\").build();\n      Network notDefaultNotInZone = Network.builder().id(\"200-2\").isDefault(false).zoneId(\"200\").build();\n\n      Predicate<Network> predicate = defaultNetworkInZone(\"42\");\n      assertTrue(predicate.apply(defaultInZone));\n      assertFalse(predicate.apply(defaultNotInZone));\n      assertFalse(predicate.apply(notDefaultInZone));\n      assertFalse(predicate.apply(notDefaultNotInZone));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/predicates/OSCategoryInTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.predicates;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.cloudstack.CloudStackApi;\nimport org.jclouds.cloudstack.domain.OSType;\nimport org.jclouds.cloudstack.domain.Template;\nimport org.jclouds.cloudstack.features.GuestOSApi;\nimport org.testng.annotations.BeforeMethod;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Maps;\n\n@Test(groups = \"unit\", singleThreaded = true)\npublic class OSCategoryInTest {\n\n   private CloudStackApi client;\n   private GuestOSApi guestOSClient;\n   private Set<String> acceptableCategories = ImmutableSet.<String>of(\"Ubuntu\");\n\n   @BeforeMethod\n   public void setUp() {\n      client = createMock(CloudStackApi.class);\n      guestOSClient = createMock(GuestOSApi.class);\n\n      expect(client.getGuestOSApi()).andReturn(guestOSClient).times(2);\n\n      Map<String, String> osCategories = Maps.newHashMap();\n      osCategories.put(\"1\", \"Ubuntu\");\n      osCategories.put(\"2\", \"CentOS\");\n      osCategories.put(\"3\", \"RHEL\");\n\n      expect(guestOSClient.listOSCategories()).andReturn(osCategories);\n\n      Set<OSType> osTypes = ImmutableSet.of(\n         OSType.builder().id(\"10\").OSCategoryId(\"1\").description(\"Ubuntu 10.04 LTS\").build(),\n         OSType.builder().id(\"20\").OSCategoryId(\"2\").description(\"CentOS 5.4\").build(),\n         OSType.builder().id(\"30\").OSCategoryId(\"3\").description(\"RHEL 6\").build()\n      );\n\n      expect(guestOSClient.listOSTypes()).andReturn(osTypes);\n      replay(client, guestOSClient);\n   }\n\n   @Test\n   public void testTemplateInAcceptableCategory() {\n      assertTrue(new OSCategoryIn(client).apply(acceptableCategories).apply(\n         Template.builder().id(\"1\").OSTypeId(\"10\").build()\n      ));\n      verify(client, guestOSClient);\n   }\n\n   @Test\n   public void testTemplateNotInAcceptableCategory() {\n      assertFalse(new OSCategoryIn(client).apply(acceptableCategories).apply(\n         Template.builder().id(\"2\").OSTypeId(\"30\").build()\n      ));\n      verify(client, guestOSClient);\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/predicates/PublicIPAddressPredicatesTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.predicates;\n\nimport static org.jclouds.cloudstack.predicates.PublicIPAddressPredicates.available;\n\nimport org.jclouds.cloudstack.domain.PublicIPAddress;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class PublicIPAddressPredicatesTest {\n\n   public void testIsAvailableWhenAllocated() {\n      PublicIPAddress address = PublicIPAddress.builder().state(PublicIPAddress.State.ALLOCATED).id(\"204\").build();\n\n      assert available().apply(address);\n\n   }\n\n   public void testIsNotAvailableWhenNotAllocated() {\n      PublicIPAddress address = PublicIPAddress.builder().state(PublicIPAddress.State.ALLOCATING).id(\"204\").build();\n\n      assert !available().apply(address);\n\n   }\n\n   public void testIsNotAvailableWhenAssignedToVM() {\n      PublicIPAddress address = PublicIPAddress.builder().state(PublicIPAddress.State.ALLOCATED).virtualMachineId(\"1\")\n            .id(\"204\").build();\n\n      assert !available().apply(address);\n\n   }\n\n   public void testIsNotAvailableWhenSourceNAT() {\n      PublicIPAddress address = PublicIPAddress.builder().state(PublicIPAddress.State.ALLOCATED).isSourceNAT(true)\n            .id(\"204\").build();\n\n      assert !available().apply(address);\n\n   }\n\n   public void testIsNotAvailableWhenStaticNAT() {\n      PublicIPAddress address = PublicIPAddress.builder().state(PublicIPAddress.State.ALLOCATED).isStaticNAT(true)\n            .id(\"204\").build();\n\n      assert !available().apply(address);\n\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/predicates/SecurityGroupPredicatesTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.predicates;\n\nimport static org.jclouds.cloudstack.predicates.SecurityGroupPredicates.hasCidr;\nimport static org.jclouds.cloudstack.predicates.SecurityGroupPredicates.nameEquals;\nimport static org.jclouds.cloudstack.predicates.SecurityGroupPredicates.portInRange;\nimport static org.jclouds.cloudstack.predicates.SecurityGroupPredicates.portInRangeForCidr;\nimport static org.jclouds.cloudstack.predicates.SecurityGroupPredicates.ruleCidrMatches;\nimport static org.jclouds.cloudstack.predicates.SecurityGroupPredicates.ruleGroupMatches;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.cloudstack.domain.IngressRule;\nimport org.jclouds.cloudstack.domain.SecurityGroup;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\n\n@Test(groups = \"unit\")\npublic class SecurityGroupPredicatesTest {\n\n   public SecurityGroup group() {\n      return SecurityGroup\n         .builder()\n         .id(\"13\")\n         .name(\"default\")\n         .description(\"description\")\n         .account(\"adrian\")\n         .domainId(\"1\")\n         .domain(\"ROOT\")\n         .ingressRules(\n                       ImmutableSet.of(\n                                       \n                                       IngressRule.builder().id(\"5\").protocol(\"tcp\").startPort(22).endPort(22)\n                                       .securityGroupName(\"adriancole\").account(\"adrian\").build(),\n                                       IngressRule.builder().id(\"6\").protocol(\"udp\").startPort(11).endPort(11).CIDR(\"1.1.1.1/24\").build(),\n                                       IngressRule.builder().id(\"7\").protocol(\"tcp\").startPort(40).endPort(50).CIDR(\"1.1.1.1/24\").build(),\n                                       IngressRule.builder().id(\"8\").protocol(\"tcp\").startPort(60).endPort(60).CIDR(\"2.2.2.2/16\").build()\n                                       )).build();\n   }\n\n   @Test\n   public void testPortInRange() {\n      assertTrue(portInRange(22).apply(group()));\n      assertTrue(portInRange(45).apply(group()));\n      assertFalse(portInRange(100).apply(group()));\n   }\n\n   @Test\n   public void testHasCidr() {\n      assertTrue(hasCidr(\"1.1.1.1/24\").apply(group()));\n      assertFalse(hasCidr(\"3.3.3.3/25\").apply(group()));\n   }\n\n   @Test\n   public void testPortInRangeForCidr() {\n      assertTrue(portInRangeForCidr(11, \"1.1.1.1/24\").apply(group()));\n      assertTrue(portInRangeForCidr(45, \"1.1.1.1/24\").apply(group()));\n      assertFalse(portInRangeForCidr(45, \"2.2.2.2/16\").apply(group()));\n      assertFalse(portInRangeForCidr(11, \"2.2.2.2/16\").apply(group()));\n      assertFalse(portInRangeForCidr(11, \"3.3.3.3/25\").apply(group()));\n   }\n   \n   @Test\n   public void testNameEquals() {\n      assertTrue(nameEquals(\"default\").apply(group()));\n      assertFalse(nameEquals(\"not-default\").apply(group()));\n   }\n\n   @Test\n   public void testRuleCidrMatches() {\n      assertTrue(Iterables.any(group().getIngressRules(),\n              ruleCidrMatches(\"tcp\", 40, 50, ImmutableSet.of(\"1.1.1.1/24\"))));\n      assertFalse(Iterables.any(group().getIngressRules(),\n              ruleCidrMatches(\"tcp\", 40, 50, ImmutableSet.of(\"2.2.2.2/24\"))));\n   }\n\n   @Test\n   public void testRuleGroupMatches() {\n      assertTrue(Iterables.any(group().getIngressRules(),\n              ruleGroupMatches(\"tcp\", 22, 22,\n                      ImmutableMultimap.<String, String>builder().put(\"adrian\", \"adriancole\").build())));\n      assertFalse(Iterables.any(group().getIngressRules(),\n              ruleGroupMatches(\"tcp\", 22, 22,\n                      ImmutableMultimap.<String, String>builder().put(\"adrian\", \"somegroup\").build())));\n      assertFalse(Iterables.any(group().getIngressRules(),\n              ruleGroupMatches(\"tcp\", 22, 22,\n                      ImmutableMultimap.<String, String>builder().put(\"someuser\", \"adriancole\").build())));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/predicates/TemplatePredicatesTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.predicates;\n\nimport static org.jclouds.cloudstack.predicates.TemplatePredicates.isPasswordEnabled;\nimport static org.jclouds.cloudstack.predicates.TemplatePredicates.isReady;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.cloudstack.domain.Template;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class TemplatePredicatesTest {\n\n   @Test\n   public void testTemplateIsReady() {\n      assertTrue(isReady().apply(\n         Template.builder().id(\"a\").ready(true).build()\n      ));\n      assertFalse(isReady().apply(\n         Template.builder().id(\"b\").ready(false).build()\n      ));\n   }\n\n   @Test\n   public void testTemplateIsPasswordEnabled() {\n      assertTrue(isPasswordEnabled().apply(\n         Template.builder().id(\"anid\").passwordEnabled(true).build()\n      ));\n      assertFalse(isPasswordEnabled().apply(\n         Template.builder().id(\"someid\").passwordEnabled(false).build()\n      ));\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/predicates/UserPredicatesTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.predicates;\n\nimport static org.jclouds.cloudstack.predicates.UserPredicates.apiKeyEquals;\nimport static org.jclouds.cloudstack.predicates.UserPredicates.isAdminAccount;\nimport static org.jclouds.cloudstack.predicates.UserPredicates.isDomainAdminAccount;\nimport static org.jclouds.cloudstack.predicates.UserPredicates.isUserAccount;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.cloudstack.domain.Account;\nimport org.jclouds.cloudstack.domain.User;\nimport org.testng.annotations.DataProvider;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class UserPredicatesTest {\n\n   @Test\n   public void testMatchApiKey() {\n      assertTrue(apiKeyEquals(\"random-text\").apply(\n         User.builder().id(\"random-id\").apiKey(\"random-text\").build()\n      ));\n      assertFalse(apiKeyEquals(\"something-different\").apply(\n         User.builder().id(\"random-id\").apiKey(\"random-text\").build()\n      ));\n   }\n\n   @DataProvider(name = \"accountType\")\n   public Object[][] getAccountTypes() {\n      return new Object[][] {\n         /* Type ID, isUser, isDomainAdmin, isAdmin */\n         {Account.Type.USER, true, false, false},\n         {Account.Type.DOMAIN_ADMIN, false, true, false},\n         {Account.Type.ADMIN, false, false, true},\n         {Account.Type.UNRECOGNIZED, false, false, false}\n      };\n   }\n\n   @Test(dataProvider = \"accountType\")\n   public void testAccountType(Account.Type type, boolean isUser, boolean isDomainAdmin, boolean isAdmin) {\n      User testUser = User.builder().id(\"someid\").accountType(type).build();\n      assertEquals(isUserAccount().apply(testUser), isUser);\n      assertEquals(isDomainAdminAccount().apply(testUser), isDomainAdmin);\n      assertEquals(isAdminAccount().apply(testUser), isAdmin);\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/predicates/VirtualMachineDestroyedTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.predicates;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.cloudstack.CloudStackApi;\nimport org.jclouds.cloudstack.domain.VirtualMachine;\nimport org.jclouds.cloudstack.features.VirtualMachineApi;\nimport org.testng.annotations.BeforeMethod;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", singleThreaded = true, testName = \"VirtualMachineDestroyedTest\")\npublic class VirtualMachineDestroyedTest {\n\n   CloudStackApi client;\n   VirtualMachineApi virtualMachineClient;\n\n   @BeforeMethod\n   public void setUp() {\n      client = createMock(CloudStackApi.class);\n      virtualMachineClient = createMock(VirtualMachineApi.class);\n      expect(client.getVirtualMachineApi()).andReturn(virtualMachineClient);\n   }\n\n   @Test\n   public void testIsDestroyed() {\n      VirtualMachine virtualMachine = VirtualMachine.builder().\n         id(\"229\").state(VirtualMachine.State.DESTROYED).build();\n\n      expect(virtualMachineClient.getVirtualMachine(virtualMachine.getId())).andReturn(virtualMachine);\n\n      replay(client, virtualMachineClient);\n      assertTrue(new VirtualMachineDestroyed(client).apply(virtualMachine));\n      verify(client, virtualMachineClient);\n   }\n\n   @Test\n   public void testStillRunning() {\n      VirtualMachine virtualMachine = VirtualMachine.builder().\n         id(\"229\").state(VirtualMachine.State.RUNNING).build();\n\n      expect(virtualMachineClient.getVirtualMachine(virtualMachine.getId())).andReturn(virtualMachine);\n\n      replay(client, virtualMachineClient);\n      assertFalse(new VirtualMachineDestroyed(client).apply(virtualMachine));\n      verify(client, virtualMachineClient);\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/predicates/VirtualMachineExpungedTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.predicates;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.cloudstack.CloudStackApi;\nimport org.jclouds.cloudstack.domain.VirtualMachine;\nimport org.jclouds.cloudstack.features.VirtualMachineApi;\nimport org.testng.annotations.BeforeMethod;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", singleThreaded = true, testName = \"VirtualMachineExpungedTest\")\npublic class VirtualMachineExpungedTest {\n\n   CloudStackApi client;\n   VirtualMachineApi virtualMachineClient;\n\n   @BeforeMethod\n   public void setUp() {\n      client = createMock(CloudStackApi.class);\n      virtualMachineClient = createMock(VirtualMachineApi.class);\n      expect(client.getVirtualMachineApi()).andReturn(virtualMachineClient);\n   }\n\n   @Test\n   public void testWaitForVirtualMachineToBeExpunged() {\n      VirtualMachine virtualMachine = VirtualMachine.builder().id(\"229\").build();\n      expect(virtualMachineClient.getVirtualMachine(virtualMachine.getId())).andReturn(null);\n\n      replay(client, virtualMachineClient);\n      assertTrue(new VirtualMachineExpunged(client).apply(virtualMachine));\n      verify(client, virtualMachineClient);\n   }\n\n   @Test\n   public void testNoRemovedYet() {\n      VirtualMachine virtualMachine = VirtualMachine.builder().id(\"229\").build();\n      expect(virtualMachineClient.getVirtualMachine(virtualMachine.getId())).andReturn(virtualMachine);\n\n      replay(client, virtualMachineClient);\n      assertFalse(new VirtualMachineExpunged(client).apply(virtualMachine));\n      verify(client, virtualMachineClient);\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/predicates/VirtualMachineRunningTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.predicates;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.cloudstack.CloudStackApi;\nimport org.jclouds.cloudstack.domain.VirtualMachine;\nimport org.jclouds.cloudstack.domain.VirtualMachine.State;\nimport org.jclouds.cloudstack.features.VirtualMachineApi;\nimport org.testng.annotations.BeforeMethod;\nimport org.testng.annotations.DataProvider;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", singleThreaded = true, testName = \"VirtualMachineRunningTest\")\npublic class VirtualMachineRunningTest {\n\n   CloudStackApi client;\n   VirtualMachineApi virtualMachineClient;\n\n   @BeforeMethod\n   public void setUp() {\n      client = createMock(CloudStackApi.class);\n      virtualMachineClient = createMock(VirtualMachineApi.class);\n\n      expect(client.getVirtualMachineApi()).andReturn(virtualMachineClient);\n   }\n\n   @DataProvider(name = \"virtualMachineStates\")\n   public Object[][] virtualMachineStates() {\n      return new Object[][] {\n         {State.RUNNING, true},\n         {State.STARTING, false},\n         {State.STOPPING, false},\n         {State.STOPPED, false},\n         {State.SHUTDOWNED, false},\n         {State.DESTROYED, false},\n         {State.EXPUNGING, false},\n         {State.MIGRATING, false}\n      };\n   }\n\n   @Test(dataProvider = \"virtualMachineStates\")\n   public void testWaitForVirtualMachineToBeRunning(State state, boolean expected) {\n      assertPredicateResult(state, expected);\n   }\n\n   @Test(expectedExceptions = IllegalStateException.class)\n   public void testThrowExceptionOnErrorState() {\n      assertPredicateResult(State.ERROR, true);\n   }\n\n   private void assertPredicateResult(State state, boolean expected) {\n      String virtualMachineId = \"229\";\n      VirtualMachine virtualMachine = VirtualMachine.builder().\n         id(virtualMachineId).state(state).build();\n\n      expect(virtualMachineClient.getVirtualMachine(virtualMachineId)).andReturn(virtualMachine);\n      replay(client, virtualMachineClient);\n\n      assertEquals(new VirtualMachineRunning(client).apply(virtualMachine), expected);\n      verify(client, virtualMachineClient);\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/java/org/jclouds/cloudstack/predicates/ZonePredicatesTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudstack.predicates;\n\nimport static org.jclouds.cloudstack.predicates.ZonePredicates.supportsAdvancedNetworks;\nimport static org.jclouds.cloudstack.predicates.ZonePredicates.supportsSecurityGroups;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.cloudstack.domain.NetworkType;\nimport org.jclouds.cloudstack.domain.Zone;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class ZonePredicatesTest {\n\n   @Test\n   public void testSupportsAdvancedNetworks() {\n      assertTrue(supportsAdvancedNetworks().apply(\n         Zone.builder().id(\"41\").networkType(NetworkType.ADVANCED).build()\n      ));\n      assertFalse(supportsAdvancedNetworks().apply(\n         Zone.builder().id(\"42\").networkType(NetworkType.BASIC).build()\n      ));\n   }\n\n   @Test\n   public void testSupportsSecurityGroups() {\n      assertTrue(supportsSecurityGroups().apply(\n         Zone.builder().id(\"43\").securityGroupsEnabled(true).build()\n      ));\n      assertFalse(supportsSecurityGroups().apply(\n         Zone.builder().id(\"44\").securityGroupsEnabled(false).build()\n      ));\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/resources/addclusterresponse.json",
    "content": "{ \"addclusterresponse\" : { \"cluster\" : {\"warning\":\"this test data is fabricated\",\"id\":1,\"name\":\"Xen Clust 1\",\"podid\":1,\"podname\":\"Dev Pod 1\",\"zoneid\":1,\"zonename\":\"Dev Zone 1\",\"hypervisortype\":\"XenServer\",\"clustertype\":\"CloudManaged\",\"allocationstate\":\"Enabled\",\"managedstate\":\"Managed\"} } }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/addhostresponse.json",
    "content": "{ \"addhostresponse\" : { \"host\" :\n    {\"warning\":\"This test data is fabricated\",\"id\":1,\"name\":\"cs2-xevsrv.alucloud.local\",\"state\":\"Up\",\"type\":\"Routing\",\"ipaddress\":\"10.26.26.107\",\"zoneid\":1,\"zonename\":\"Dev Zone 1\",\"podid\":1,\"podname\":\"Dev Pod 1\",\"version\":\"2.2.12.20110928142833\",\"hypervisor\":\"XenServer\",\"cpunumber\":24,\"cpuspeed\":2266,\"cpuallocated\":\"2.76%\",\"cpuused\":\"0.1%\",\"cpuwithoverprovisioning\":\"54384.0\",\"networkkbsread\":4443,\"networkkbswrite\":15048,\"memorytotal\":100549733760,\"memoryallocated\":3623878656,\"memoryused\":3623878656,\"capabilities\":\"xen-3.0-x86_64 , xen-3.0-x86_32p , hvm-3.0-x86_32 , hvm-3.0-x86_32p , hvm-3.0-x86_64\",\"lastpinged\":\"1970-01-16T00:54:43+0200\",\"managementserverid\":223098941760041,\"clusterid\":1,\"clustername\":\"Xen Clust 1\",\"clustertype\":\"CloudManaged\",\"islocalstorageactive\":false,\"created\":\"2011-11-26T23:28:36+0200\",\"events\":\"PrepareUnmanaged; HypervisorVersionChanged; ManagementServerDown; PingTimeout; AgentDisconnected; MaintenanceRequested; HostDown; AgentConnected; StartAgentRebalance; ShutdownRequested; Ping\",\"hosttags\":\"\",\"hasEnoughCapacity\":false,\"allocationstate\":\"Enabled\"} } }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/addsecondarystorageresponse.json",
    "content": "{ \"addsecondarystorageresponse\" : { \"host\" :\n    {\"warning\":\"this test data is fabricated\",\"id\":2,\"name\":\"nfs://10.26.26.165/mnt/nfs/cs_sec\",\"state\":\"Alert\",\"disconnected\":\"2011-11-26T23:33:38+0200\",\"type\":\"SecondaryStorage\",\"ipaddress\":\"nfs\",\"zoneid\":1,\"zonename\":\"Dev Zone 1\",\"version\":\"2.2.12.20110928142833\",\"hypervisor\":\"None\",\"lastpinged\":\"1970-01-16T00:42:30+0200\",\"islocalstorageactive\":false,\"created\":\"2011-11-26T23:33:38+0200\",\"events\":\"ManagementServerDown; AgentDisconnected; Remove; MaintenanceRequested; AgentConnected; Ping\",\"hasEnoughCapacity\":false,\"allocationstate\":\"Enabled\"},\n} }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/authorizesecuritygroupingressresponse.json",
    "content": " { \"authorizesecuritygroupingressresponse\" :\n {\"jobid\":\"13330fc9-8b3e-4582-aa3e-90883c041010\"} }\n"
  },
  {
    "path": "apis/cloudstack/src/test/resources/cancelhostmaintenanceresponse.json",
    "content": "{ \"cancelhostmaintenanceresponse\" : {\"warning\":\"this test data is fabricated\",\"jobid\":2036,\"id\":2017} }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/createdomainresponse.json",
    "content": "{ \"createdomainresponse\" :  { \"domain\" :\n    {\"id\":10,\"name\":\"test\",\"level\":1,\"parentdomainid\":1,\"parentdomainname\":\"ROOT\",\"haschild\":false} }  }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/createegressfirewallrulesresponse.json",
    "content": "{ \"createegressfirewallruleresponse\" : {\"jobid\":2036,\"id\":2017} }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/createfirewallrulesresponse.json",
    "content": "{ \"createfirewallruleresponse\" : {\"jobid\":2036,\"id\":2017} }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/createkeypairresponse.json",
    "content": "{ \"createkeypairresponse\" :  { \"keypair\" : {\"name\":\"vijay2-test\",\"fingerprint\":\"80:61:58:5b:92:4c:1f:5a:4f:fc:1d:39:ea:28:06:c7\",\"privatekey\":\"-----BEGIN RSA PRIVATE KEY-----\\nMIICXAIBAAKBgQDTMxvFfEC+SAq4JD1sYx/EAtvzdKt1XY3yBFZ4iRRDCM30fK76\\nQ5um9H+PhxzeGj5PVKPF409nq17BiNjM64qnmoHFVn2J+NFaiyo/oo2wohDDWUyn\\noh7ifGd+AUfhaISnuAmEfhlgHxBhrTXsKmGe/x7lgwiyg25t84XYR38QiQIDAQAB\\nAoGAGk5cYC3I1qqcgzEoYW67TyvX/6wBiz3a51E5AAx69JqNJK2/EbcIFTSRCuyW\\nYOe96R2uxIA6rLwAsnR8JJIWE+5DdlSjp+Vrgp3p10YXU6FHdmX0Uwq+Gi9Ofg2E\\nX1qGBJTVmV0BRCJCZcufNk+XPSUp7QQpstqd0Nxnc6dcEnECQQDzZ7PnP+7EKmk4\\nNT0kN2V56dartYOookA20V6YMa2mcOmDw0Mhh3B3GlOjwkfVLtGfdxdz4gtcGtzz\\nEpwjrRA1AkEA3iDKxmSyWQSl80KfVQQK2QZ52jHIJbuT5UlvCSvgb2XXxJ+gxjSh\\n/V805IIZ+WMzWNkRQ1g786dhI1BUCv2xhQJBAKngB3vub8pyuwqihXCARQ9H9y3R\\nufh4fI6FoxpfGY2fIip2naSJ7SECu7r/vbh4O46qxDB5Y2o9yVTP+S8g+r0CQDKA\\nWhnJAxNiDyjDWN5HUQAOjN2iu9J4VyOmEmyPYTNygB/f+vmVNc8ZOjlJqwYcG6xz\\njY02HktDHr6coL7u9tECQE8hJ04UbS2O4ruafhDUHNJ9/4ERzFyn1GWhcipK6ACE\\nF4MrwQImqtsUvGjtA3X0s+lEj3+iLJfJr02pfYpCyf8=\\n-----END RSA PRIVATE KEY-----\\n\"} }  }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/createpodresponse.json",
    "content": "{ \"createpodresponse\" :  { \"pod\" : {\"id\":6,\"name\":\"richard-pod\",\"zoneid\":10,\"zonename\":\"richard-zone\",\"gateway\":\"172.20.0.254\",\"netmask\":\"255.255.255.0\",\"startip\":\"172.20.0.1\",\"endip\":\"172.20.0.250\",\"allocationstate\":\"Enabled\"} }  }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/createportforwardingrulesresponse.json",
    "content": "{ \"createportforwardingruleresponse\" : {\"jobid\":2035,\"id\":2015} }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/createsecuritygroupresponse.json",
    "content": "{ \"listsecuritygroupsresponse\" : { \"securitygroup\" : \n{\"id\":30,\"name\":\"jclouds-test\",\"account\":\"adrian\",\"domainid\":1,\"domain\":\"ROOT\"}\n } }\n"
  },
  {
    "path": "apis/cloudstack/src/test/resources/createsshkeypairresponse-2.json",
    "content": "{ \"createsshkeypairresponse\" :  { \"keypair\" : {\n   \"name\":\"jclouds-test\",\n   \"fingerprint\":\"1c:06:74:52:3b:99:1c:95:5c:04:c2:f4:ba:77:6e:7b\",\n   \"privatekey\":\"-----BEGIN RSA PRIVATE KEY-----\\nMIICXgIBAAKBgQDZo/EF4Ew1uEW0raz7vCs28lBwy0UKV2Xr606gaEgxO7h9mSXZ\\n4x2K/KQ1NMnrbjppxGycLh9EKPWAO3ezFULAyuOZW4Fy+xRS8+3MAijxBJY/KBgl\\nx5rJm2ILumRkTNkMlLGCSBb9SOqYRN1VpOy7kn3StzU9LdJ/snKVE2JLHQIDAQAB\\nAoGBAMnL5okKRd9xcsBqYIAxIuiZmNhcwTErhEdRMOAukPGFbDSYsa3rldLvGdpz\\njd2LoQG8rO/LHBZ429kASqZzyiV+NvcgH+tFNJSVAigjSICfhEKF9PY2TiAkrg7S\\nGyJgAjpPWQc2sQh0dE8EPEtBiq4ibXfMTDmbs1d/vnfdwtQJAkEA+AX5Y+xgWj74\\ndYETmNLyLhNZpftLizEfIYj7lCVhsbFwVb8jbM1m8n8bxwGjls1w/ico1CWcQna+\\nUnAfA8kJvwJBAOCj0YgDKpYd0OLQhvI3212J9QcQpJEkDOTYiMwXNHCNMKRpoF47\\nMPPX+GG8YzUiQAi9/OG4pDKCjzQWE/ebiiMCQQCssnQ5WICqtggIwYykr9VDseON\\nSFIMpHJ5xkjumazRrqx6eDGxc8BH/6uWwRRoT7pqrVeniFyqhsX03u8pkpU/AkBj\\nWfCcwBHArNUqy2EzlWKuvwogosq16oTNXbs60HR/5uIBhTnJE1K2NemDiGc0I77A\\nXw6N4jS0piuhtLYGB8OTAkEA50abdbduXWcr62Z6E8G/6LNFaNg0uBuVgwSHtJMd\\ndNeUtVDHQCHSf3tvxXTAtaB9PCnGOfgm/dyYWEMf3rMoHQ==\\n-----END RSA PRIVATE KEY-----\\n\"} }  }\n"
  },
  {
    "path": "apis/cloudstack/src/test/resources/createsshkeypairresponse.json",
    "content": "{ \"createsshkeypairresponse\" :  { \"keypair\" : {\n   \"name\":\"jclouds-keypair\",\n   \"fingerprint\":\"1c:06:74:52:3b:99:1c:95:5c:04:c2:f4:ba:77:6e:7b\",\n   \"privatekey\":\"-----BEGIN RSA PRIVATE KEY-----\\nMIICXgIBAAKBgQDZo/EF4Ew1uEW0raz7vCs28lBwy0UKV2Xr606gaEgxO7h9mSXZ\\n4x2K/KQ1NMnrbjppxGycLh9EKPWAO3ezFULAyuOZW4Fy+xRS8+3MAijxBJY/KBgl\\nx5rJm2ILumRkTNkMlLGCSBb9SOqYRN1VpOy7kn3StzU9LdJ/snKVE2JLHQIDAQAB\\nAoGBAMnL5okKRd9xcsBqYIAxIuiZmNhcwTErhEdRMOAukPGFbDSYsa3rldLvGdpz\\njd2LoQG8rO/LHBZ429kASqZzyiV+NvcgH+tFNJSVAigjSICfhEKF9PY2TiAkrg7S\\nGyJgAjpPWQc2sQh0dE8EPEtBiq4ibXfMTDmbs1d/vnfdwtQJAkEA+AX5Y+xgWj74\\ndYETmNLyLhNZpftLizEfIYj7lCVhsbFwVb8jbM1m8n8bxwGjls1w/ico1CWcQna+\\nUnAfA8kJvwJBAOCj0YgDKpYd0OLQhvI3212J9QcQpJEkDOTYiMwXNHCNMKRpoF47\\nMPPX+GG8YzUiQAi9/OG4pDKCjzQWE/ebiiMCQQCssnQ5WICqtggIwYykr9VDseON\\nSFIMpHJ5xkjumazRrqx6eDGxc8BH/6uWwRRoT7pqrVeniFyqhsX03u8pkpU/AkBj\\nWfCcwBHArNUqy2EzlWKuvwogosq16oTNXbs60HR/5uIBhTnJE1K2NemDiGc0I77A\\nXw6N4jS0piuhtLYGB8OTAkEA50abdbduXWcr62Z6E8G/6LNFaNg0uBuVgwSHtJMd\\ndNeUtVDHQCHSf3tvxXTAtaB9PCnGOfgm/dyYWEMf3rMoHQ==\\n-----END RSA PRIVATE KEY-----\\n\"} }  }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/createtagsresponse.json",
    "content": "{ \"createtagsresponse\" : {\"jobid\":\"32cfab73-f221-4b2b-a728-a73e924ac95d\"} }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/createtemplateresponse-imageextension.json",
    "content": "{ \"createtemplateresponse\" : {\"id\":\"3dc6ce25-a6cf-4d60-a664-3499993b511b\",\"jobid\":\"4e345230-8fcc-48a3-8a37-c5fe960df671\"} }\n"
  },
  {
    "path": "apis/cloudstack/src/test/resources/createtemplateresponse.json",
    "content": "{ \"createtemplateresponse\" : {\"id\":\"3dc6ce25-a6cf-4d60-a664-3499993b511b\",\"jobid\":\"4e345230-8fcc-48a3-8a37-c5fe960df671\"} }\n"
  },
  {
    "path": "apis/cloudstack/src/test/resources/createvlaniprangeresponse.json",
    "content": "{ \"createvlaniprangeresponse\" : { \"vlaniprange\" : {\"id\":2,\"forvirtualnetwork\":false,\"zoneid\":2,\"vlan\":\"untagged\",\"account\":\"system\",\"domainid\":1,\"domain\":\"ROOT\",\"podid\":2,\"podname\":\"Dev Pod 2\",\"gateway\":\"10.22.22.254\",\"netmask\":\"255.255.255.0\",\"startip\":\"10.22.22.51\",\"endip\":\"10.22.22.100\",\"networkid\":209} } }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/createzoneresponse.json",
    "content": "{ \"createzoneresponse\" :  { \"zone\" :\n    {\"id\":6,\"name\":\"test-zone\",\"dns1\":\"8.8.8.8\",\"internaldns1\":\"10.10.10.10\",\"networktype\":\"Basic\",\n        \"securitygroupsenabled\":true,\"allocationstate\":\"Enabled\",\"zonetoken\":\"7b6e27df-30a6-3024-9d8b-7971a3127f64\",\n        \"dhcpprovider\":\"DhcpServer\"} }  }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/deletedomainresponse.json",
    "content": "{ \"deletedomainresponse\" : {\"jobid\":2413} }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/deleteegressfirewallrulesresponse.json",
    "content": "{ \"deleteegressfirewallruleresponse\" : {\"jobid\":2037} }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/deletefirewallrulesresponse.json",
    "content": "{ \"deletefirewallruleresponse\" : {\"jobid\":2037} }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/deleteipforwardingruleresponse.json",
    "content": "{ \"deleteipforwardingruleresponse\" : {\"jobid\":50005} }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/deletenetworkresponse.json",
    "content": "{ \"deletenetworkresponse\" : {\"jobid\":45612} }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/deleteportforwardingrulesresponse.json",
    "content": "{ \"deleteportforwardingruleresponse\" : {\"jobid\":2038} }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/deletesecuritygroupresponse.json",
    "content": "{ \"deletesecuritygroupresponse\" : { \"success\" : \"true\"}  }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/deletetagsresponse.json",
    "content": "{ \"deletetagsresponse\" : {\"jobid\":\"32cfab73-f221-4b2b-a728-a73e924ac95d\"} }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/deletetemplateresponse.json",
    "content": "{ \"queryasyncjobresultresponse\" : {\"jobid\":118,\"jobstatus\":1,\"jobprocstatus\":0,\"jobresultcode\":0,\"jobresulttype\":\"object\",\"jobresult\":{\"success\":true}} }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/deletezoneresponse.json",
    "content": "{ \"deletezoneresponse\" : { \"success\" : \"true\"}  }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/deployvirtualmachineresponse.json",
    "content": "{ \"deployvirtualmachine\" : {\"id\":1234, \"jobid\":50006} }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/deployvirtualmachineresponse4x.json",
    "content": " { \"deployvirtualmachineresponse\" : {\"id\":\"1cce6cb7-2268-47ff-9696-d9e610f6619a\",\"jobid\":\"13330fc9-8b3e-4582-aa3e-90883c041ff0\"}, \"cloudstack-version\": \"4.1.0-SNAPSHOT\" }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/disablestaticnatresponse.json",
    "content": "{ \"disablestaticnatresponse\" : {\"jobid\":50006} }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/enablestaticnatresponse-withoutjob.json",
    "content": "{ \"enablestaticnatresponse\" : { \"success\" : \"true\"}  }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/getdomainresponse.json",
    "content": "{ \"listdomainsresponse\" : { \"count\":1 ,\"domain\" : [\n    {\"id\":1,\"name\":\"ROOT\",\"level\":0,\"haschild\":true} ] } }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/getegressfirewallrulesresponse.json",
    "content": "{ \"listegressfirewallrulesresponse\" : { \"count\":1 ,\"firewallrule\" : [\n    {\"id\":2017,\"protocol\":\"tcp\",\"startport\":\"30\",\"endport\":\"35\",\"ipaddressid\":2,\"ipaddress\":\"10.27.27.51\",\"state\":\"Active\",\"cidrlist\":\"0.0.0.0/0\"} ] } }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/getfirewallrulesresponse.json",
    "content": "{ \"listfirewallrulesresponse\" : { \"count\":1 ,\"firewallrule\" : [\n    {\"id\":2017,\"protocol\":\"tcp\",\"startport\":\"30\",\"endport\":\"35\",\"ipaddressid\":2,\"ipaddress\":\"10.27.27.51\",\"state\":\"Active\",\"cidrlist\":\"0.0.0.0/0\"} ] } }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/getisoresponse.json",
    "content": "{ \"listisosresponse\" : { \"count\":1 ,\"iso\" : [ {\"id\":\"018e0928-8205-4d8e-9329-f731a9ccd488\",\"name\":\"xs-tools.iso\",\"displaytext\":\"xen-pv-drv-iso\",\"ispublic\":true,\"created\":\"2012-08-21T15:45:01+0530\",\"isready\":true,\"passwordenabled\":false,\"bootable\":false,\"isfeatured\":true,\"crossZones\":false,\"account\":\"system\",\"domain\":\"ROOT\",\"domainid\":\"9d189ea2-097e-4b2b-9bae-d885f5430d69\",\"isextractable\":false,\"tags\":[]} ] } }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/getportforwardingrulesresponse.json",
    "content": "{ \"listportforwardingrulesresponse\": {\n    \"portforwardingrule\": [\n        {\n            \"id\": 15,\n            \"privateport\": \"22\",\n            \"protocol\": \"tcp\",\n            \"publicport\": \"2022\",\n            \"virtualmachineid\": 3,\n            \"virtualmachinename\": \"i-3-3-VM\",\n            \"ipaddressid\": 3,\n            \"ipaddress\": \"72.52.126.32\",\n            \"state\": \"Active\",\n            \"cidrlist\": \"0.0.0.0/1,128.0.0.0/1\",\n            \"tags\":[{\"account\":1,\"domain\":\"ROOT\",\"domainid\":1,\"key\":\"some-tag\",\"resourceid\":15, \"resourcetype\":\"PortForwardingRule\", \"value\":\"some-value\"}]\n        }\n    ]\n} }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/getsecuritygroupresponse.json",
    "content": "{ \"listsecuritygroupsresponse\" : { count: 0, \"securitygroup\" : [ { } ] } }\n"
  },
  {
    "path": "apis/cloudstack/src/test/resources/getsecuritygroupresponse_extension_byid.json",
    "content": "{ \"listsecuritygroupsresponse\" : { \"securitygroup\" : [  {\"id\":13,\"name\":\"default\",\"description\":\"description\",\"account\":\"adrian\",\"domainid\":1,\"domain\":\"ROOT\",\"ingressrule\":[{\"ruleid\":5,\"protocol\":\"tcp\",\"startport\":22,\"endport\":22,\"securitygroupname\":\"adriancole\",\"account\":\"adrian\"},{\"ruleid\":6,\"protocol\":\"udp\",\"startport\":11,\"endport\":11,\"cidr\":\"1.1.1.1/24\"}]} ] } }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/getsecuritygroupresponse_extension_byid_empty.json",
    "content": "{ \"listsecuritygroupsresponse\" : { \"securitygroup\" : [  {\"id\":13,\"name\":\"default\",\"description\":\"description\",\"account\":\"adrian\",\"domainid\":1,\"domain\":\"ROOT\"} ] } }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/getsecuritygroupresponse_extension_byid_with_cidr.json",
    "content": "{ \"listsecuritygroupsresponse\" : { \"securitygroup\" : [  {\"id\":13,\"name\":\"default\",\"description\":\"description\",\"account\":\"adrian\",\"domainid\":1,\"domain\":\"ROOT\",\"ingressrule\":[{\"ruleid\":6,\"protocol\":\"udp\",\"startport\":11,\"endport\":11,\"cidr\":\"1.1.1.1/24\"}]} ] } }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/getsecuritygroupresponse_extension_byid_with_group.json",
    "content": "{ \"listsecuritygroupsresponse\" : { \"securitygroup\" : [  {\"id\":13,\"name\":\"default\",\"description\":\"description\",\"account\":\"adrian\",\"domainid\":1,\"domain\":\"ROOT\",\"ingressrule\":[{\"ruleid\":5,\"protocol\":\"tcp\",\"startport\":22,\"endport\":22,\"securitygroupname\":\"adriancole\",\"account\":\"adrian\"}] }] }}"
  },
  {
    "path": "apis/cloudstack/src/test/resources/getvmpasswordresponse.json",
    "content": "{ \"getvmpasswordresponse\" :  { \"password\" :\n   {\"encryptedpassword\":\"EFOwm8icZ4sEib4y6ntVHUKHZJQrGBdyPkL1L9lpFHYhs3JfAtL5E5bxBP5Er27bJyOZPjKFcInX\\r\\npQ0LZlQBZDd5/ac0NSoM6tAX3H30pYxNw4t2f9u8aJ48oOEvufgGxTTHnM9qHXD04lt+Ouql6i2q\\r\\nHxBqCxFkMZEla3LFieE=\\r\\n\"} }  }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/getzoneresponse-2.json",
    "content": "{ \"listzonesresponse\" : { \"zone\" : [  {\"id\":2,\"name\":\"Chicago\",\"networktype\":\"Advanced\",\"securitygroupsenabled\":true} ] } }\n"
  },
  {
    "path": "apis/cloudstack/src/test/resources/getzoneresponse.json",
    "content": "{ \"listzonesresponse\" : { \"zone\" : [  {\"id\":1,\"name\":\"San Jose 1\",\"networktype\":\"Advanced\",\"securitygroupsenabled\":false} ] } }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/listaccountsresponse.json",
    "content": "{ \"listaccountsresponse\" : { \"count\":1 ,\"account\" : [  {\"id\":505,\"name\":\"jclouds\",\"accounttype\":0,\"domainid\":457,\"domain\":\"AA000062-jclouds-dev\",\"receivedbytes\":318900216,\"sentbytes\":23189677,\"vmlimit\":\"15\",\"vmtotal\":1,\"vmavailable\":\"14\",\"iplimit\":\"15\",\"iptotal\":0,\"ipavailable\":\"15\",\"volumelimit\":\"90\",\"volumetotal\":2,\"volumeavailable\":\"88\",\"snapshotlimit\":\"250\",\"snapshottotal\":0,\"snapshotavailable\":\"250\",\"templatelimit\":\"15\",\"templatetotal\":0,\"templateavailable\":\"15\",\"vmstopped\":0,\"vmrunning\":1,\"state\":\"enabled\",\"user\":[{\"id\":505,\"username\":\"jclouds\",\"firstname\":\"Adrian\",\"lastname\":\"Cole\",\"email\":\"adrian@jclouds.org\",\"created\":\"2011-04-19T01:57:24+0000\",\"state\":\"enabled\",\"account\":\"jclouds\",\"accounttype\":0,\"domainid\":457,\"domain\":\"AA000062-jclouds-dev\",\"apikey\":\"APIKEY\",\"secretkey\":\"SECRETKEY\"}]} ] } }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/listalertsresponse.json",
    "content": "{ \"listalertsresponse\" : { \"count\":1 ,\"alert\" : [  {\"id\":20,\"type\":7,\"description\":\"Failed to deploy Vm with Id: 52\",\"sent\":\"2011-12-04T10:05:02+0200\"} ] } }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/listasyncjobsresponse.json",
    "content": "{\n    \"listasyncjobsresponse\": {\n        \"count\": 77,\n        \"asyncjobs\": [{\n            \"jobid\": 1084,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.DeployVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 218,\n                    \"name\": \"i-3-218-VM\",\n                    \"displayname\": \"i-3-218-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T08:39:10-0800\",\n                    \"state\": \"Running\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"password\": \"dD7jwajkh\",\n                    \"nic\": [{\n                        \"id\": 250,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.195\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T08:39:10-0800\"\n        }, {\n            \"jobid\": 1085,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.DeployVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 219,\n                    \"name\": \"i-3-219-VM\",\n                    \"displayname\": \"i-3-219-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T08:40:33-0800\",\n                    \"state\": \"Running\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"password\": \"eJ9zqwtsk\",\n                    \"nic\": [{\n                        \"id\": 251,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.118\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T08:40:34-0800\"\n        }, {\n            \"jobid\": 1086,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.DeployVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 220,\n                    \"name\": \"i-3-220-VM\",\n                    \"displayname\": \"i-3-220-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T08:46:23-0800\",\n                    \"state\": \"Running\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"password\": \"yD3vwdcic\",\n                    \"nic\": [{\n                        \"id\": 252,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.78\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T08:46:23-0800\"\n        }, {\n            \"jobid\": 1087,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.StopVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 220,\n                    \"name\": \"i-3-220-VM\",\n                    \"displayname\": \"i-3-220-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T08:46:23-0800\",\n                    \"state\": \"Stopped\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"cpuused\": \"3.96%\",\n                    \"networkkbsread\": 2,\n                    \"networkkbswrite\": 10,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"nic\": [{\n                        \"id\": 252,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.78\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T08:49:42-0800\"\n        }, {\n            \"jobid\": 1088,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.ResetVMPasswordCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 220,\n                    \"name\": \"i-3-220-VM\",\n                    \"displayname\": \"i-3-220-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T08:46:23-0800\",\n                    \"state\": \"Stopped\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"cpuused\": \"3.96%\",\n                    \"networkkbsread\": 2,\n                    \"networkkbswrite\": 10,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"password\": \"fR3aipcsa\",\n                    \"nic\": [{\n                        \"id\": 252,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.78\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T08:50:24-0800\"\n        }, {\n            \"jobid\": 1089,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.StopVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 220,\n                    \"name\": \"i-3-220-VM\",\n                    \"displayname\": \"i-3-220-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T08:46:23-0800\",\n                    \"state\": \"Stopped\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"cpuused\": \"3.96%\",\n                    \"networkkbsread\": 2,\n                    \"networkkbswrite\": 10,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"nic\": [{\n                        \"id\": 252,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.78\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T08:52:58-0800\"\n        }, {\n            \"jobid\": 1090,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.StartVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 220,\n                    \"name\": \"i-3-220-VM\",\n                    \"displayname\": \"i-3-220-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T08:46:23-0800\",\n                    \"state\": \"Running\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"cpuused\": \"3.96%\",\n                    \"networkkbsread\": 2,\n                    \"networkkbswrite\": 10,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"nic\": [{\n                        \"id\": 252,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.78\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T08:53:27-0800\"\n        }, {\n            \"jobid\": 1091,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.RebootVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 220,\n                    \"name\": \"i-3-220-VM\",\n                    \"displayname\": \"i-3-220-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T08:46:23-0800\",\n                    \"state\": \"Running\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"cpuused\": \"3.96%\",\n                    \"networkkbsread\": 2,\n                    \"networkkbswrite\": 10,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"nic\": [{\n                        \"id\": 252,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.78\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T08:53:43-0800\"\n        }, {\n            \"jobid\": 1092,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.DestroyVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 220,\n                    \"name\": \"i-3-220-VM\",\n                    \"displayname\": \"i-3-220-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T08:46:23-0800\",\n                    \"state\": \"Destroyed\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"cpuused\": \"3.96%\",\n                    \"networkkbsread\": 2,\n                    \"networkkbswrite\": 10,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"nic\": [{\n                        \"id\": 252,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.78\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T08:54:04-0800\"\n        }, {\n            \"jobid\": 1093,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.DestroyVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 220,\n                    \"name\": \"i-3-220-VM\",\n                    \"displayname\": \"i-3-220-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T08:46:23-0800\",\n                    \"state\": \"Destroyed\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"cpuused\": \"3.96%\",\n                    \"networkkbsread\": 2,\n                    \"networkkbswrite\": 10,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"nic\": [{\n                        \"id\": 252,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.78\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T08:55:42-0800\"\n        }, {\n            \"jobid\": 1094,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.RebootVMCmd\",\n            \"jobstatus\": 2,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 530,\n            \"jobresult\": {\n                \"errorcode\": 530,\n                \"errortext\": \"Internal error executing command, please contact your system administrator\"\n            },\n            \"created\": \"2011-02-27T08:56:59-0800\"\n        }, {\n            \"jobid\": 1095,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.StartVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 220,\n                    \"name\": \"i-3-220-VM\",\n                    \"displayname\": \"i-3-220-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T08:46:23-0800\",\n                    \"state\": \"Destroyed\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"cpuused\": \"3.96%\",\n                    \"networkkbsread\": 2,\n                    \"networkkbswrite\": 10,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"nic\": [{\n                        \"id\": 252,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.78\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T08:58:53-0800\"\n        }, {\n            \"jobid\": 1096,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.StartVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 220,\n                    \"name\": \"i-3-220-VM\",\n                    \"displayname\": \"i-3-220-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T08:46:23-0800\",\n                    \"state\": \"Destroyed\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"cpuused\": \"3.96%\",\n                    \"networkkbsread\": 2,\n                    \"networkkbswrite\": 10,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"nic\": [{\n                        \"id\": 252,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.78\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T09:00:19-0800\"\n        }, {\n            \"jobid\": 1098,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.DeployVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 221,\n                    \"name\": \"i-3-221-VM\",\n                    \"displayname\": \"i-3-221-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T09:08:02-0800\",\n                    \"state\": \"Running\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"password\": \"uT4gfgmxn\",\n                    \"nic\": [{\n                        \"id\": 253,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.133\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T09:08:02-0800\"\n        }, {\n            \"jobid\": 1099,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.StopVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 221,\n                    \"name\": \"i-3-221-VM\",\n                    \"displayname\": \"i-3-221-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T09:08:02-0800\",\n                    \"state\": \"Stopped\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"nic\": [{\n                        \"id\": 253,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.133\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T09:08:20-0800\"\n        }, {\n            \"jobid\": 1100,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.ResetVMPasswordCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 221,\n                    \"name\": \"i-3-221-VM\",\n                    \"displayname\": \"i-3-221-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T09:08:02-0800\",\n                    \"state\": \"Stopped\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"password\": \"sX8mwzrwp\",\n                    \"nic\": [{\n                        \"id\": 253,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.133\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T09:09:02-0800\"\n        }, {\n            \"jobid\": 1101,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.StartVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 221,\n                    \"name\": \"i-3-221-VM\",\n                    \"displayname\": \"i-3-221-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T09:08:02-0800\",\n                    \"state\": \"Running\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"nic\": [{\n                        \"id\": 253,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.133\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T09:09:03-0800\"\n        }, {\n            \"jobid\": 1102,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.RebootVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 221,\n                    \"name\": \"i-3-221-VM\",\n                    \"displayname\": \"i-3-221-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T09:08:02-0800\",\n                    \"state\": \"Running\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"nic\": [{\n                        \"id\": 253,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.133\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T09:09:19-0800\"\n        }, {\n            \"jobid\": 1103,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.DestroyVMCmd\",\n            \"jobstatus\": 2,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 530,\n            \"jobresult\": {\n                \"errorcode\": 530,\n                \"errortext\": \"Internal error executing command, please contact your system administrator\"\n            },\n            \"created\": \"2011-02-27T09:09:38-0800\"\n        }, {\n            \"jobid\": 1104,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.StopVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 221,\n                    \"name\": \"i-3-221-VM\",\n                    \"displayname\": \"i-3-221-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T09:08:02-0800\",\n                    \"state\": \"Stopping\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"cpuused\": \"0%\",\n                    \"networkkbsread\": 0,\n                    \"networkkbswrite\": 0,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"nic\": [{\n                        \"id\": 253,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.133\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T09:11:19-0800\"\n        }, {\n            \"jobid\": 1105,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.DeployVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 222,\n                    \"name\": \"i-3-222-VM\",\n                    \"displayname\": \"i-3-222-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T09:11:33-0800\",\n                    \"state\": \"Running\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"password\": \"kH6qvmvpz\",\n                    \"nic\": [{\n                        \"id\": 254,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.249\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T09:11:33-0800\"\n        }, {\n            \"jobid\": 1106,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.RebootVMCmd\",\n            \"jobstatus\": 2,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 530,\n            \"jobresult\": {\n                \"errorcode\": 530,\n                \"errortext\": \"Internal error executing command, please contact your system administrator\"\n            },\n            \"created\": \"2011-02-27T09:13:59-0800\"\n        }, {\n            \"jobid\": 1107,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.RebootVMCmd\",\n            \"jobstatus\": 2,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 530,\n            \"jobresult\": {\n                \"errorcode\": 530,\n                \"errortext\": \"Internal error executing command, please contact your system administrator\"\n            },\n            \"created\": \"2011-02-27T09:15:09-0800\"\n        }, {\n            \"jobid\": 1108,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.DestroyVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 221,\n                    \"name\": \"i-3-221-VM\",\n                    \"displayname\": \"i-3-221-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T09:08:02-0800\",\n                    \"state\": \"Destroyed\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"cpuused\": \"0%\",\n                    \"networkkbsread\": 0,\n                    \"networkkbswrite\": 0,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"nic\": [{\n                        \"id\": 253,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.133\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T09:16:44-0800\"\n        }, {\n            \"jobid\": 1109,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.StartVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 221,\n                    \"name\": \"i-3-221-VM\",\n                    \"displayname\": \"i-3-221-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T09:08:02-0800\",\n                    \"state\": \"Destroyed\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"cpuused\": \"0%\",\n                    \"networkkbsread\": 0,\n                    \"networkkbswrite\": 0,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"nic\": [{\n                        \"id\": 253,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.133\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T09:21:52-0800\"\n        }, {\n            \"jobid\": 1110,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.ResetVMPasswordCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 221,\n                    \"name\": \"i-3-221-VM\",\n                    \"displayname\": \"i-3-221-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T09:08:02-0800\",\n                    \"state\": \"Destroyed\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"cpuused\": \"0%\",\n                    \"networkkbsread\": 0,\n                    \"networkkbswrite\": 0,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"nic\": [{\n                        \"id\": 253,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.133\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T09:22:15-0800\"\n        }, {\n            \"jobid\": 1111,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.DeployVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 223,\n                    \"name\": \"i-3-223-VM\",\n                    \"displayname\": \"i-3-223-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T09:28:23-0800\",\n                    \"state\": \"Running\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"password\": \"mN8ymgqtz\",\n                    \"nic\": [{\n                        \"id\": 255,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.32\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T09:28:23-0800\"\n        }, {\n            \"jobid\": 1112,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.StopVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 223,\n                    \"name\": \"i-3-223-VM\",\n                    \"displayname\": \"i-3-223-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T09:28:23-0800\",\n                    \"state\": \"Stopped\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"nic\": [{\n                        \"id\": 255,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.32\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T09:28:41-0800\"\n        }, {\n            \"jobid\": 1113,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.ResetVMPasswordCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 223,\n                    \"name\": \"i-3-223-VM\",\n                    \"displayname\": \"i-3-223-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T09:28:23-0800\",\n                    \"state\": \"Stopped\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"password\": \"pP5vkjkeu\",\n                    \"nic\": [{\n                        \"id\": 255,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.32\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T09:29:22-0800\"\n        }, {\n            \"jobid\": 1114,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.StartVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 223,\n                    \"name\": \"i-3-223-VM\",\n                    \"displayname\": \"i-3-223-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T09:28:23-0800\",\n                    \"state\": \"Running\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"nic\": [{\n                        \"id\": 255,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.32\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T09:29:23-0800\"\n        }, {\n            \"jobid\": 1115,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.RebootVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 223,\n                    \"name\": \"i-3-223-VM\",\n                    \"displayname\": \"i-3-223-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T09:28:23-0800\",\n                    \"state\": \"Running\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"cpuused\": \"0%\",\n                    \"networkkbsread\": 0,\n                    \"networkkbswrite\": 0,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"nic\": [{\n                        \"id\": 255,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.32\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T09:29:41-0800\"\n        }, {\n            \"jobid\": 1116,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.DeployVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 224,\n                    \"name\": \"i-3-224-VM\",\n                    \"displayname\": \"i-3-224-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T09:29:47-0800\",\n                    \"state\": \"Running\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"password\": \"jN9jgsmcg\",\n                    \"nic\": [{\n                        \"id\": 256,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.162\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T09:29:47-0800\"\n        }, {\n            \"jobid\": 1117,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.DestroyVMCmd\",\n            \"jobstatus\": 2,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 530,\n            \"jobresult\": {\n                \"errorcode\": 530,\n                \"errortext\": \"Internal error executing command, please contact your system administrator\"\n            },\n            \"created\": \"2011-02-27T09:30:05-0800\"\n        }, {\n            \"jobid\": 1118,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.StopVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 223,\n                    \"name\": \"i-3-223-VM\",\n                    \"displayname\": \"i-3-223-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T09:28:23-0800\",\n                    \"state\": \"Stopping\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"cpuused\": \"0%\",\n                    \"networkkbsread\": 0,\n                    \"networkkbswrite\": 0,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"nic\": [{\n                        \"id\": 255,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.32\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T09:30:40-0800\"\n        }, {\n            \"jobid\": 1119,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.RebootVMCmd\",\n            \"jobstatus\": 2,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 530,\n            \"jobresult\": {\n                \"errorcode\": 530,\n                \"errortext\": \"Internal error executing command, please contact your system administrator\"\n            },\n            \"created\": \"2011-02-27T09:31:31-0800\"\n        }, {\n            \"jobid\": 1120,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.DestroyVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 223,\n                    \"name\": \"i-3-223-VM\",\n                    \"displayname\": \"i-3-223-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T09:28:23-0800\",\n                    \"state\": \"Destroyed\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"cpuused\": \"0%\",\n                    \"networkkbsread\": 0,\n                    \"networkkbswrite\": 0,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"nic\": [{\n                        \"id\": 255,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.32\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T09:31:35-0800\"\n        }, {\n            \"jobid\": 1121,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.StartVMCmd\",\n            \"jobstatus\": 2,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 530,\n            \"jobresult\": {\n                \"errorcode\": 530,\n                \"errortext\": \"Internal error executing command, please contact your system administrator\"\n            },\n            \"created\": \"2011-02-27T09:37:20-0800\"\n        }, {\n            \"jobid\": 1122,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.ResetVMPasswordCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 223,\n                    \"name\": \"i-3-223-VM\",\n                    \"displayname\": \"i-3-223-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T09:28:23-0800\",\n                    \"state\": \"Stopping\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"cpuused\": \"0%\",\n                    \"networkkbsread\": 0,\n                    \"networkkbswrite\": 0,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"nic\": [{\n                        \"id\": 255,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.32\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T09:37:55-0800\"\n        }, {\n            \"jobid\": 1123,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.ResetVMPasswordCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 223,\n                    \"name\": \"i-3-223-VM\",\n                    \"displayname\": \"i-3-223-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T09:28:23-0800\",\n                    \"state\": \"Stopping\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"cpuused\": \"0%\",\n                    \"networkkbsread\": 0,\n                    \"networkkbswrite\": 0,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"nic\": [{\n                        \"id\": 255,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.32\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T09:38:32-0800\"\n        }, {\n            \"jobid\": 1124,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.StartVMCmd\",\n            \"jobstatus\": 2,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 530,\n            \"jobresult\": {\n                \"errorcode\": 530,\n                \"errortext\": \"Internal error executing command, please contact your system administrator\"\n            },\n            \"created\": \"2011-02-27T09:39:12-0800\"\n        }, {\n            \"jobid\": 1126,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.AssociateIPAddrCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"ipaddress\": {\n                    \"id\": 36,\n                    \"ipaddress\": \"72.52.126.65\",\n                    \"allocated\": \"2011-02-27T10:15:06-0800\",\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"issourcenat\": false,\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"forvirtualnetwork\": true,\n                    \"isstaticnat\": false,\n                    \"associatednetworkid\": 204,\n                    \"networkid\": 200,\n                    \"state\": \"Allocating\"\n                }\n            },\n            \"created\": \"2011-02-27T10:15:06-0800\"\n        }, {\n            \"jobid\": 1127,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.AssociateIPAddrCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"ipaddress\": {\n                    \"id\": 37,\n                    \"ipaddress\": \"72.52.126.66\",\n                    \"allocated\": \"2011-02-27T10:15:07-0800\",\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"issourcenat\": false,\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"forvirtualnetwork\": true,\n                    \"isstaticnat\": false,\n                    \"associatednetworkid\": 204,\n                    \"networkid\": 200,\n                    \"state\": \"Allocating\"\n                }\n            },\n            \"created\": \"2011-02-27T10:15:07-0800\"\n        }, {\n            \"jobid\": 1128,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.DeployVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 225,\n                    \"name\": \"i-3-225-VM\",\n                    \"displayname\": \"i-3-225-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T10:15:07-0800\",\n                    \"state\": \"Running\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"password\": \"hM3yhakcf\",\n                    \"nic\": [{\n                        \"id\": 257,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.199\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T10:15:07-0800\"\n        }, {\n            \"jobid\": 1129,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.AssociateIPAddrCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"ipaddress\": {\n                    \"id\": 39,\n                    \"ipaddress\": \"72.52.126.68\",\n                    \"allocated\": \"2011-02-27T10:15:08-0800\",\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"issourcenat\": false,\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"forvirtualnetwork\": true,\n                    \"isstaticnat\": false,\n                    \"associatednetworkid\": 204,\n                    \"networkid\": 200,\n                    \"state\": \"Allocated\"\n                }\n            },\n            \"created\": \"2011-02-27T10:15:08-0800\"\n        }, {\n            \"jobid\": 1130,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.DeployVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 226,\n                    \"name\": \"i-3-226-VM\",\n                    \"displayname\": \"i-3-226-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T10:15:22-0800\",\n                    \"state\": \"Running\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"password\": \"pU6tpixty\",\n                    \"nic\": [{\n                        \"id\": 258,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.165\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T10:15:22-0800\"\n        }, {\n            \"jobid\": 1131,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.StopVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 225,\n                    \"name\": \"i-3-225-VM\",\n                    \"displayname\": \"i-3-225-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T10:15:07-0800\",\n                    \"state\": \"Stopping\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"nic\": [{\n                        \"id\": 257,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.199\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T10:15:23-0800\"\n        }, {\n            \"jobid\": 1132,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.AssociateIPAddrCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"ipaddress\": {\n                    \"id\": 14,\n                    \"ipaddress\": \"72.52.126.43\",\n                    \"allocated\": \"2011-02-27T10:15:26-0800\",\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"issourcenat\": false,\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"forvirtualnetwork\": true,\n                    \"isstaticnat\": false,\n                    \"associatednetworkid\": 204,\n                    \"networkid\": 200,\n                    \"state\": \"Allocated\"\n                }\n            },\n            \"created\": \"2011-02-27T10:15:26-0800\"\n        }, {\n            \"jobid\": 1133,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.CreateIpForwardingRuleCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"ipforwardingrule\": {\n                    \"id\": 109,\n                    \"protocol\": \"tcp\",\n                    \"virtualmachineid\": 226,\n                    \"virtualmachinename\": \"i-3-226-VM\",\n                    \"ipaddressid\": 36,\n                    \"ipaddress\": \"72.52.126.65\",\n                    \"startport\": 22,\n                    \"endport\": 22,\n                    \"state\": \"Active\"\n                }\n            },\n            \"created\": \"2011-02-27T10:15:39-0800\"\n        }, {\n            \"jobid\": 1134,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.DeployVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 227,\n                    \"name\": \"i-3-227-VM\",\n                    \"displayname\": \"i-3-227-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T10:15:49-0800\",\n                    \"state\": \"Running\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"password\": \"aV5iybwch\",\n                    \"nic\": [{\n                        \"id\": 259,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.176\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T10:15:49-0800\"\n        }, {\n            \"jobid\": 1135,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.DeployVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 228,\n                    \"name\": \"i-3-228-VM\",\n                    \"displayname\": \"i-3-228-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T10:15:50-0800\",\n                    \"state\": \"Running\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"password\": \"cN7rmnqzc\",\n                    \"nic\": [{\n                        \"id\": 260,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.95\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T10:15:50-0800\"\n        }, {\n            \"jobid\": 1136,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.DestroyVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 226,\n                    \"name\": \"i-3-226-VM\",\n                    \"displayname\": \"i-3-226-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T10:15:22-0800\",\n                    \"state\": \"Destroyed\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"cpuused\": \"0%\",\n                    \"networkkbsread\": 0,\n                    \"networkkbswrite\": 0,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"nic\": [{\n                        \"id\": 258,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.165\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T10:16:00-0800\"\n        }, {\n            \"jobid\": 1137,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.CreatePortForwardingRuleCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"portforwardingrule\": {\n                    \"id\": 110,\n                    \"privateport\": \"22\",\n                    \"protocol\": \"tcp\",\n                    \"publicport\": \"22\",\n                    \"virtualmachineid\": 227,\n                    \"virtualmachinename\": \"i-3-227-VM\",\n                    \"ipaddressid\": 37,\n                    \"ipaddress\": \"72.52.126.66\",\n                    \"state\": \"Active\"\n                }\n            },\n            \"created\": \"2011-02-27T10:16:05-0800\"\n        }, {\n            \"jobid\": 1138,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.AssignToLoadBalancerRuleCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"success\": true\n            },\n            \"created\": \"2011-02-27T10:16:34-0800\"\n        }, {\n            \"jobid\": 1139,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.DeletePortForwardingRuleCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"success\": true\n            },\n            \"created\": \"2011-02-27T10:16:45-0800\"\n        }, {\n            \"jobid\": 1140,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.DestroyVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 227,\n                    \"name\": \"i-3-227-VM\",\n                    \"displayname\": \"i-3-227-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T10:15:49-0800\",\n                    \"state\": \"Destroyed\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"cpuused\": \"0%\",\n                    \"networkkbsread\": 0,\n                    \"networkkbswrite\": 0,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"nic\": [{\n                        \"id\": 259,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.176\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T10:16:55-0800\"\n        }, {\n            \"jobid\": 1141,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.DestroyVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 226,\n                    \"name\": \"i-3-226-VM\",\n                    \"displayname\": \"i-3-226-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T10:15:22-0800\",\n                    \"state\": \"Destroyed\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"cpuused\": \"0%\",\n                    \"networkkbsread\": 0,\n                    \"networkkbswrite\": 0,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"nic\": [{\n                        \"id\": 258,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.165\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T10:18:04-0800\"\n        }, {\n            \"jobid\": 1142,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.AssociateIPAddrCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"ipaddress\": {\n                    \"id\": 36,\n                    \"ipaddress\": \"72.52.126.65\",\n                    \"allocated\": \"2011-02-27T10:18:11-0800\",\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"issourcenat\": false,\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"forvirtualnetwork\": true,\n                    \"isstaticnat\": false,\n                    \"associatednetworkid\": 204,\n                    \"networkid\": 200,\n                    \"state\": \"Allocating\"\n                }\n            },\n            \"created\": \"2011-02-27T10:18:11-0800\"\n        }, {\n            \"jobid\": 1143,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.DeployVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 229,\n                    \"name\": \"i-3-229-VM\",\n                    \"displayname\": \"i-3-229-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T10:18:39-0800\",\n                    \"state\": \"Running\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"password\": \"zW6ekdrgu\",\n                    \"nic\": [{\n                        \"id\": 261,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.98\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T10:18:39-0800\"\n        }, {\n            \"jobid\": 1144,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.AssignToLoadBalancerRuleCmd\",\n            \"jobstatus\": 2,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 530,\n            \"jobresult\": {\n                \"errorcode\": 431,\n                \"errortext\": \"VM 228 is already mapped to load balancer.\"\n            },\n            \"created\": \"2011-02-27T10:19:33-0800\"\n        }, {\n            \"jobid\": 1145,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.StopVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 225,\n                    \"name\": \"i-3-225-VM\",\n                    \"displayname\": \"i-3-225-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T10:15:07-0800\",\n                    \"state\": \"Stopping\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"nic\": [{\n                        \"id\": 257,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.199\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T10:19:51-0800\"\n        }, {\n            \"jobid\": 1146,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.DestroyVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 227,\n                    \"name\": \"i-3-227-VM\",\n                    \"displayname\": \"i-3-227-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T10:15:49-0800\",\n                    \"state\": \"Destroyed\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"cpuused\": \"0%\",\n                    \"networkkbsread\": 0,\n                    \"networkkbswrite\": 0,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"nic\": [{\n                        \"id\": 259,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.176\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T10:20:19-0800\"\n        }, {\n            \"jobid\": 1147,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.StopVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 225,\n                    \"name\": \"i-3-225-VM\",\n                    \"displayname\": \"i-3-225-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T10:15:07-0800\",\n                    \"state\": \"Stopped\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"nic\": [{\n                        \"id\": 257,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.199\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T10:20:37-0800\"\n        }, {\n            \"jobid\": 1148,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.AssociateIPAddrCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"ipaddress\": {\n                    \"id\": 36,\n                    \"ipaddress\": \"72.52.126.65\",\n                    \"allocated\": \"2011-02-27T10:24:16-0800\",\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"issourcenat\": false,\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"forvirtualnetwork\": true,\n                    \"isstaticnat\": false,\n                    \"associatednetworkid\": 204,\n                    \"networkid\": 200,\n                    \"state\": \"Allocating\"\n                }\n            },\n            \"created\": \"2011-02-27T10:24:16-0800\"\n        }, {\n            \"jobid\": 1149,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.AssociateIPAddrCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"ipaddress\": {\n                    \"id\": 37,\n                    \"ipaddress\": \"72.52.126.66\",\n                    \"allocated\": \"2011-02-27T10:24:16-0800\",\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"issourcenat\": false,\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"forvirtualnetwork\": true,\n                    \"isstaticnat\": false,\n                    \"associatednetworkid\": 204,\n                    \"networkid\": 200,\n                    \"state\": \"Allocating\"\n                }\n            },\n            \"created\": \"2011-02-27T10:24:16-0800\"\n        }, {\n            \"jobid\": 1150,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.AssociateIPAddrCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"ipaddress\": {\n                    \"id\": 14,\n                    \"ipaddress\": \"72.52.126.43\",\n                    \"allocated\": \"2011-02-27T10:24:16-0800\",\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"issourcenat\": false,\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"forvirtualnetwork\": true,\n                    \"isstaticnat\": false,\n                    \"associatednetworkid\": 204,\n                    \"networkid\": 200,\n                    \"state\": \"Allocated\"\n                }\n            },\n            \"created\": \"2011-02-27T10:24:16-0800\"\n        }, {\n            \"jobid\": 1151,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.DeployVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 230,\n                    \"name\": \"i-3-230-VM\",\n                    \"displayname\": \"i-3-230-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T10:24:16-0800\",\n                    \"state\": \"Running\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"password\": \"bW4exzqrz\",\n                    \"nic\": [{\n                        \"id\": 262,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.177\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T10:24:16-0800\"\n        }, {\n            \"jobid\": 1152,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.AssociateIPAddrCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"ipaddress\": {\n                    \"id\": 15,\n                    \"ipaddress\": \"72.52.126.44\",\n                    \"allocated\": \"2011-02-27T10:24:17-0800\",\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"issourcenat\": false,\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"forvirtualnetwork\": true,\n                    \"isstaticnat\": false,\n                    \"associatednetworkid\": 204,\n                    \"networkid\": 200,\n                    \"state\": \"Allocated\"\n                }\n            },\n            \"created\": \"2011-02-27T10:24:17-0800\"\n        }, {\n            \"jobid\": 1153,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.DeployVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 231,\n                    \"name\": \"i-3-231-VM\",\n                    \"displayname\": \"i-3-231-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T10:24:32-0800\",\n                    \"state\": \"Running\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"password\": \"xJ9xncviv\",\n                    \"nic\": [{\n                        \"id\": 263,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.216\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T10:24:32-0800\"\n        }, {\n            \"jobid\": 1154,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.StopVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 230,\n                    \"name\": \"i-3-230-VM\",\n                    \"displayname\": \"i-3-230-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T10:24:16-0800\",\n                    \"state\": \"Stopping\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"nic\": [{\n                        \"id\": 262,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.177\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T10:24:33-0800\"\n        }, {\n            \"jobid\": 1155,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.DeployVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 232,\n                    \"name\": \"i-3-232-VM\",\n                    \"displayname\": \"i-3-232-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T10:24:57-0800\",\n                    \"state\": \"Running\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"password\": \"eD6debaqf\",\n                    \"nic\": [{\n                        \"id\": 264,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.2\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T10:24:57-0800\"\n        }, {\n            \"jobid\": 1156,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.DeployVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 233,\n                    \"name\": \"i-3-233-VM\",\n                    \"displayname\": \"i-3-233-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T10:25:40-0800\",\n                    \"state\": \"Running\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"password\": \"dT6ysfbmr\",\n                    \"nic\": [{\n                        \"id\": 265,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.75\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T10:25:40-0800\"\n        }, {\n            \"jobid\": 1158,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.AssociateIPAddrCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"ipaddress\": {\n                    \"id\": 15,\n                    \"ipaddress\": \"72.52.126.44\",\n                    \"allocated\": \"2011-02-27T10:28:52-0800\",\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"issourcenat\": false,\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"forvirtualnetwork\": true,\n                    \"isstaticnat\": false,\n                    \"associatednetworkid\": 204,\n                    \"networkid\": 200,\n                    \"state\": \"Allocating\"\n                }\n            },\n            \"created\": \"2011-02-27T10:28:52-0800\"\n        }, {\n            \"jobid\": 1159,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.StopVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 230,\n                    \"name\": \"i-3-230-VM\",\n                    \"displayname\": \"i-3-230-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T10:24:16-0800\",\n                    \"state\": \"Stopping\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"nic\": [{\n                        \"id\": 262,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.177\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T10:28:52-0800\"\n        }, {\n            \"jobid\": 1160,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.DeployVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 234,\n                    \"name\": \"i-3-234-VM\",\n                    \"displayname\": \"i-3-234-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T10:28:54-0800\",\n                    \"state\": \"Running\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"password\": \"cB6eqqxgt\",\n                    \"nic\": [{\n                        \"id\": 266,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.96\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T10:28:54-0800\"\n        }, {\n            \"jobid\": 1161,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.DeployVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 235,\n                    \"name\": \"i-3-235-VM\",\n                    \"displayname\": \"i-3-235-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T10:28:56-0800\",\n                    \"state\": \"Running\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"password\": \"zM5ydnmvx\",\n                    \"nic\": [{\n                        \"id\": 267,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.61\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T10:28:56-0800\"\n        }, {\n            \"jobid\": 1162,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.StopVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 230,\n                    \"name\": \"i-3-230-VM\",\n                    \"displayname\": \"i-3-230-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T10:24:16-0800\",\n                    \"state\": \"Stopped\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"nic\": [{\n                        \"id\": 262,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.177\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T10:29:01-0800\"\n        }, {\n            \"jobid\": 1163,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.AssociateIPAddrCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"ipaddress\": {\n                    \"id\": 22,\n                    \"ipaddress\": \"72.52.126.51\",\n                    \"allocated\": \"2011-02-27T10:29:26-0800\",\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"issourcenat\": false,\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"forvirtualnetwork\": true,\n                    \"isstaticnat\": false,\n                    \"associatednetworkid\": 204,\n                    \"networkid\": 200,\n                    \"state\": \"Allocating\"\n                }\n            },\n            \"created\": \"2011-02-27T10:29:26-0800\"\n        }]\n    }\n}"
  },
  {
    "path": "apis/cloudstack/src/test/resources/listcapabilitiesresponse.json",
    "content": "{ \"listcapabilitiesresponse\" :  { \"capability\" : {\"securitygroupsenabled\":true,\"cloudstackversion\":\"2.2\",\"userpublictemplateenabled\":true} }  }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/listcapacityresponse.json",
    "content": "{ \"listcapacityresponse\" : { \"count\":2 ,\"capacity\" : [  {\"type\":3,\"zoneid\":1,\"zonename\":\"Dev Zone 1\",\"podid\":\"null\",\"podname\":\"All\",\"capacityused\":34057748480,\"capacitytotal\":1796712955904,\"percentused\":\"1.9\"}, {\"type\":3,\"zoneid\":1,\"zonename\":\"Dev Zone 1\",\"podid\":1,\"podname\":\"Dev Pod 1\",\"capacityused\":34057748480,\"capacitytotal\":1796712955904,\"percentused\":\"1.9\"} ] } }\n"
  },
  {
    "path": "apis/cloudstack/src/test/resources/listclustersresponse.json",
    "content": "{ \"listclustersresponse\" : { \"count\":2 ,\"cluster\" : [  {\"id\":1,\"name\":\"Xen Clust 1\",\"podid\":1,\"podname\":\"Dev Pod 1\",\"zoneid\":1,\"zonename\":\"Dev Zone 1\",\"hypervisortype\":\"XenServer\",\"clustertype\":\"CloudManaged\",\"allocationstate\":\"Enabled\",\"managedstate\":\"Managed\"}, {\"id\":2,\"name\":\"Xen Clust 1\",\"podid\":2,\"podname\":\"Dev Pod 2\",\"zoneid\":2,\"zonename\":\"Dev Zone 2\",\"hypervisortype\":\"XenServer\",\"clustertype\":\"CloudManaged\",\"allocationstate\":\"Enabled\",\"managedstate\":\"Managed\"} ] } }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/listconfigurationsresponse.json",
    "content": "{ \"listconfigurationsresponse\" : { \"count\":2 ,\"configuration\" : [\n    {\"category\":\"Advanced\",\"name\":\"account.cleanup.interval\",\"value\":\"86400\",\"description\":\"The interval (in seconds) between cleanup for removed accounts\"},\n    {\"category\":\"Advanced\",\"name\":\"agent.lb.enabled\",\"value\":\"true\",\"description\":\"If agent load balancing enabled in cluster setup\"}]\n}}"
  },
  {
    "path": "apis/cloudstack/src/test/resources/listdiskofferingsresponse.json",
    "content": "{ \"listdiskofferingsresponse\" : { \"diskoffering\" : [  {\"id\":3,\"domainid\":1,\"domain\":\"ROOT\",\"name\":\"Small\",\"displaytext\":\"Small Disk, 5 GB\",\"disksize\":5,\"created\":\"2011-02-11T15:22:32-0800\",\"iscustomized\":false}, {\"id\":4,\"domainid\":1,\"domain\":\"ROOT\",\"name\":\"Medium\",\"displaytext\":\"Medium Disk, 20 GB\",\"disksize\":20,\"created\":\"2011-02-11T15:22:32-0800\",\"iscustomized\":false}, {\"id\":5,\"domainid\":1,\"domain\":\"ROOT\",\"name\":\"Large\",\"displaytext\":\"Large Disk, 100 GB\",\"disksize\":100,\"created\":\"2011-02-11T15:22:32-0800\",\"iscustomized\":false} ] } }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/listdomainchildrenresponse.json",
    "content": "{ \"listdomainchildrenresponse\" : { \"count\":2 ,\"domain\" : [\n    {\"id\":2,\"name\":\"jclouds1\",\"level\":1,\"parentdomainid\":1,\"parentdomainname\":\"ROOT\",\"haschild\":false},\n    {\"id\":3,\"name\":\"jclouds2\",\"level\":1,\"parentdomainid\":1,\"parentdomainname\":\"ROOT\",\"haschild\":false} ] } }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/listdomainsresponse.json",
    "content": "{ \"listdomainsresponse\" : { \"count\":2 ,\"domain\" : [\n    {\"id\":1,\"name\":\"ROOT\",\"level\":0,\"haschild\":true},\n    {\"id\":2,\"name\":\"jclouds1\",\"level\":1,\"parentdomainid\":1,\"parentdomainname\":\"ROOT\",\"haschild\":false} ] } }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/listegressfirewallrulesresponse.json",
    "content": "{ \"listegressfirewallrulesresponse\" : { \"count\":3 ,\"firewallrule\" : [\n    {\"id\":2017,\"protocol\":\"tcp\",\"startport\":\"30\",\"endport\":\"35\",\"ipaddressid\":2,\"ipaddress\":\"10.27.27.51\",\"state\":\"Active\",\"cidrlist\":\"0.0.0.0/0\", \"tags\":[]},\n    {\"id\":2016,\"protocol\":\"tcp\",\"startport\":\"22\",\"endport\":\"22\",\"ipaddressid\":2,\"ipaddress\":\"10.27.27.51\",\"state\":\"Active\",\"cidrlist\":\"0.0.0.0/0\"},\n    {\"id\":10,\"protocol\":\"tcp\",\"startport\":\"22\",\"endport\":\"22\",\"ipaddressid\":8,\"ipaddress\":\"10.27.27.57\",\"state\":\"Active\",\"cidrlist\":\"0.0.0.0/0\",\n        \"tags\":[{\"account\":1,\"domain\":\"ROOT\",\"domainid\":1,\"key\":\"some-tag\",\"resourceid\":10, \"resourcetype\":\"FirewallRule\", \"value\":\"some-value\"}]} ] } }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/listeventtypesresponse.json",
    "content": "{ \"listeventtypesresponse\" : { \"count\":123 ,\"eventtype\" : [  {\"name\":\"VM.CREATE\"}, {\"name\":\"VM.DESTROY\"}, {\"name\":\"VM.START\"}, {\"name\":\"VM.STOP\"}, {\"name\":\"VM.REBOOT\"}, {\"name\":\"VM.UPDATE\"}, {\"name\":\"VM.UPGRADE\"}, {\"name\":\"VM.RESETPASSWORD\"}, {\"name\":\"VM.MIGRATE\"}, {\"name\":\"ROUTER.CREATE\"}, {\"name\":\"ROUTER.DESTROY\"}, {\"name\":\"ROUTER.START\"}, {\"name\":\"ROUTER.STOP\"}, {\"name\":\"ROUTER.REBOOT\"}, {\"name\":\"ROUTER.HA\"}, {\"name\":\"ROUTER.UPGRADE\"}, {\"name\":\"PROXY.CREATE\"}, {\"name\":\"PROXY.DESTROY\"}, {\"name\":\"PROXY.START\"}, {\"name\":\"PROXY.STOP\"}, {\"name\":\"PROXY.REBOOT\"}, {\"name\":\"PROXY.HA\"}, {\"name\":\"VNC.CONNECT\"}, {\"name\":\"VNC.DISCONNECT\"}, {\"name\":\"NET.IPASSIGN\"}, {\"name\":\"NET.IPRELEASE\"}, {\"name\":\"NET.RULEADD\"}, {\"name\":\"NET.RULEDELETE\"}, {\"name\":\"NET.RULEMODIFY\"}, {\"name\":\"NETWORK.CREATE\"}, {\"name\":\"NETWORK.DELETE\"}, {\"name\":\"NETWORK.UPDATE\"}, {\"name\":\"LB.ASSIGN.TO.RULE\"}, {\"name\":\"LB.REMOVE.FROM.RULE\"}, {\"name\":\"LB.CREATE\"}, {\"name\":\"LB.DELETE\"}, {\"name\":\"LB.UPDATE\"}, {\"name\":\"ACCOUNT.DISABLE\"}, {\"name\":\"ACCOUNT.CREATE\"}, {\"name\":\"ACCOUNT.DELETE\"}, {\"name\":\"USER.LOGIN\"}, {\"name\":\"USER.LOGOUT\"}, {\"name\":\"USER.CREATE\"}, {\"name\":\"USER.DELETE\"}, {\"name\":\"USER.DISABLE\"}, {\"name\":\"USER.UPDATE\"}, {\"name\":\"USER.ENABLE\"}, {\"name\":\"TEMPLATE.CREATE\"}, {\"name\":\"TEMPLATE.DELETE\"}, {\"name\":\"TEMPLATE.UPDATE\"}, {\"name\":\"TEMPLATE.DOWNLOAD.START\"}, {\"name\":\"TEMPLATE.DOWNLOAD.SUCCESS\"}, {\"name\":\"TEMPLATE.DOWNLOAD.FAILED\"}, {\"name\":\"TEMPLATE.COPY\"}, {\"name\":\"TEMPLATE.EXTRACT\"}, {\"name\":\"TEMPLATE.UPLOAD\"}, {\"name\":\"TEMPLATE.CLEANUP\"}, {\"name\":\"VOLUME.CREATE\"}, {\"name\":\"VOLUME.DELETE\"}, {\"name\":\"VOLUME.ATTACH\"}, {\"name\":\"VOLUME.DETACH\"}, {\"name\":\"VOLUME.EXTRACT\"}, {\"name\":\"VOLUME.UPLOAD\"}, {\"name\":\"DOMAIN.CREATE\"}, {\"name\":\"DOMAIN.DELETE\"}, {\"name\":\"DOMAIN.UPDATE\"}, {\"name\":\"SNAPSHOT.CREATE\"}, {\"name\":\"SNAPSHOT.DELETE\"}, {\"name\":\"SNAPSHOTPOLICY.CREATE\"}, {\"name\":\"SNAPSHOTPOLICY.UPDATE\"}, {\"name\":\"SNAPSHOTPOLICY.DELETE\"}, {\"name\":\"ISO.CREATE\"}, {\"name\":\"ISO.DELETE\"}, {\"name\":\"ISO.COPY\"}, {\"name\":\"ISO.ATTACH\"}, {\"name\":\"ISO.DETACH\"}, {\"name\":\"ISO.EXTRACT\"}, {\"name\":\"ISO.UPLOAD\"}, {\"name\":\"SSVM.CREATE\"}, {\"name\":\"SSVM.DESTROY\"}, {\"name\":\"SSVM.START\"}, {\"name\":\"SSVM.STOP\"}, {\"name\":\"SSVM.REBOOT\"}, {\"name\":\"SSVM.HA\"}, {\"name\":\"SERVICE.OFFERING.CREATE\"}, {\"name\":\"SERVICE.OFFERING.EDIT\"}, {\"name\":\"SERVICE.OFFERING.DELETE\"}, {\"name\":\"DISK.OFFERING.CREATE\"}, {\"name\":\"DISK.OFFERING.EDIT\"}, {\"name\":\"DISK.OFFERING.DELETE\"}, {\"name\":\"NETWORK.OFFERING.CREATE\"}, {\"name\":\"NETWORK.OFFERING.ASSIGN\"}, {\"name\":\"NETWORK.OFFERING.EDIT\"}, {\"name\":\"NETWORK.OFFERING.REMOVE\"}, {\"name\":\"NETWORK.OFFERING.DELETE\"}, {\"name\":\"POD.CREATE\"}, {\"name\":\"POD.EDIT\"}, {\"name\":\"POD.DELETE\"}, {\"name\":\"ZONE.CREATE\"}, {\"name\":\"ZONE.EDIT\"}, {\"name\":\"ZONE.DELETE\"}, {\"name\":\"VLAN.IP.RANGE.CREATE\"}, {\"name\":\"VLAN.IP.RANGE.DELETE\"}, {\"name\":\"CONFIGURATION.VALUE.EDIT\"}, {\"name\":\"SG.AUTH.INGRESS\"}, {\"name\":\"SG.REVOKE.INGRESS\"}, {\"name\":\"SG.CREATE\"}, {\"name\":\"SG.DELETE\"}, {\"name\":\"HOST.RECONNECT\"}, {\"name\":\"MAINT.CANCEL\"}, {\"name\":\"MAINT.CANCEL.PS\"}, {\"name\":\"MAINT.PREPARE\"}, {\"name\":\"MAINT.PREPARE.PS\"}, {\"name\":\"VPN.REMOTE.ACCESS.CREATE\"}, {\"name\":\"VPN.REMOTE.ACCESS.DESTROY\"}, {\"name\":\"VPN.USER.ADD\"}, {\"name\":\"VPN.USER.REMOVE\"}, {\"name\":\"NETWORK.RESTART\"}, {\"name\":\"UPLOAD.CUSTOM.CERTIFICATE\"}, {\"name\":\"STATICNAT.ENABLE\"}, {\"name\":\"STATICNAT.DISABLE\"}, {\"name\":\"ZONE.VLAN.ASSIGN\"}, {\"name\":\"ZONE.VLAN.RELEASE\"} ] } }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/listfirewallrulesresponse.json",
    "content": "{ \"listfirewallrulesresponse\" : { \"count\":3 ,\"firewallrule\" : [\n    {\"id\":2017,\"protocol\":\"tcp\",\"startport\":\"30\",\"endport\":\"35\",\"ipaddressid\":2,\"ipaddress\":\"10.27.27.51\",\"state\":\"Active\",\"cidrlist\":\"0.0.0.0/0\", \"tags\":[]},\n    {\"id\":2016,\"protocol\":\"tcp\",\"startport\":\"22\",\"endport\":\"22\",\"ipaddressid\":2,\"ipaddress\":\"10.27.27.51\",\"state\":\"Active\",\"cidrlist\":\"0.0.0.0/0\"},\n    {\"id\":10,\"protocol\":\"tcp\",\"startport\":\"22\",\"endport\":\"22\",\"ipaddressid\":8,\"ipaddress\":\"10.27.27.57\",\"state\":\"Active\",\"cidrlist\":\"0.0.0.0/0\",\n        \"tags\":[{\"account\":1,\"domain\":\"ROOT\",\"domainid\":1,\"key\":\"some-tag\",\"resourceid\":10, \"resourcetype\":\"FirewallRule\", \"value\":\"some-value\"}]} ] } }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/listhostsresponse.json",
    "content": "{ \"listhostsresponse\" : { \"count\":4 ,\"host\" : [\n    {\"id\":1,\"name\":\"cs2-xevsrv.alucloud.local\",\"state\":\"Up\",\"type\":\"Routing\",\"ipaddress\":\"10.26.26.107\",\"zoneid\":1,\"zonename\":\"Dev Zone 1\",\"podid\":1,\"podname\":\"Dev Pod 1\",\"version\":\"2.2.12.20110928142833\",\"hypervisor\":\"XenServer\",\"cpunumber\":24,\"cpuspeed\":2266,\"cpuallocated\":\"2.76%\",\"cpuused\":\"0.1%\",\"cpuwithoverprovisioning\":\"54384.0\",\"networkkbsread\":4443,\"networkkbswrite\":15048,\"memorytotal\":100549733760,\"memoryallocated\":3623878656,\"memoryused\":3623878656,\"capabilities\":\"xen-3.0-x86_64 , xen-3.0-x86_32p , hvm-3.0-x86_32 , hvm-3.0-x86_32p , hvm-3.0-x86_64\",\"lastpinged\":\"1970-01-16T00:54:43+0200\",\"managementserverid\":223098941760041,\"clusterid\":1,\"clustername\":\"Xen Clust 1\",\"clustertype\":\"CloudManaged\",\"islocalstorageactive\":false,\"created\":\"2011-11-26T23:28:36+0200\",\"events\":\"PrepareUnmanaged; HypervisorVersionChanged; ManagementServerDown; PingTimeout; AgentDisconnected; MaintenanceRequested; HostDown; AgentConnected; StartAgentRebalance; ShutdownRequested; Ping\",\"hosttags\":\"\",\"hasEnoughCapacity\":false,\"allocationstate\":\"Enabled\"},\n    {\"id\":2,\"name\":\"nfs://10.26.26.165/mnt/nfs/cs_sec\",\"state\":\"Alert\",\"disconnected\":\"2011-11-26T23:33:38+0200\",\"type\":\"SecondaryStorage\",\"ipaddress\":\"nfs\",\"zoneid\":1,\"zonename\":\"Dev Zone 1\",\"version\":\"2.2.12.20110928142833\",\"hypervisor\":\"None\",\"lastpinged\":\"1970-01-16T00:42:30+0200\",\"islocalstorageactive\":false,\"created\":\"2011-11-26T23:33:38+0200\",\"events\":\"ManagementServerDown; AgentDisconnected; Remove; MaintenanceRequested; AgentConnected; Ping\",\"hasEnoughCapacity\":false,\"allocationstate\":\"Enabled\"},\n    {\"id\":3,\"name\":\"s-1-VM\",\"state\":\"Up\",\"type\":\"SecondaryStorageVM\",\"ipaddress\":\"10.26.26.81\",\"zoneid\":1,\"zonename\":\"Dev Zone 1\",\"podid\":1,\"podname\":\"Dev Pod 1\",\"version\":\"2.2.12.20110928142833\",\"lastpinged\":\"1970-01-16T00:54:43+0200\",\"managementserverid\":223098941760041,\"islocalstorageactive\":false,\"created\":\"2011-11-26T23:35:51+0200\",\"events\":\"PrepareUnmanaged; HypervisorVersionChanged; ManagementServerDown; PingTimeout; AgentDisconnected; MaintenanceRequested; HostDown; AgentConnected; StartAgentRebalance; ShutdownRequested; Ping\",\"hasEnoughCapacity\":false,\"allocationstate\":\"Enabled\"},\n    {\"id\":4,\"name\":\"v-2-VM\",\"state\":\"Up\",\"type\":\"ConsoleProxy\",\"ipaddress\":\"10.26.26.96\",\"zoneid\":1,\"zonename\":\"Dev Zone 1\",\"podid\":1,\"podname\":\"Dev Pod 1\",\"version\":\"2.2.12.20110928142833\",\"lastpinged\":\"1970-01-16T00:54:43+0200\",\"managementserverid\":223098941760041,\"islocalstorageactive\":false,\"created\":\"2011-11-26T23:36:46+0200\",\"events\":\"PrepareUnmanaged; HypervisorVersionChanged; ManagementServerDown; PingTimeout; AgentDisconnected; MaintenanceRequested; HostDown; AgentConnected; StartAgentRebalance; ShutdownRequested; Ping\",\"hasEnoughCapacity\":false,\"allocationstate\":\"Enabled\"} ] } }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/listhypervisorsresponse.json",
    "content": "{ \"listhypervisorsresponse\" : { \"hypervisor\" : [  {\"name\":\"KVM\"}, {\"name\":\"VMware\"}, {\"name\":\"XenServer\"} ] } }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/listipforwardingrulesresponse.json",
    "content": "{\n    \"listipforwardingrulesresponse\": {\n        \"count\": 1,\n        \"ipforwardingrule\": [{\n            \"id\": 66,\n            \"protocol\": \"tcp\",\n            \"virtualmachineid\": 58,\n            \"virtualmachinename\": \"i-4-58-VM\",\n            \"virtualmachinedisplayname\": \"i-4-58-VM\",\n            \"ipaddressid\": 15,\n            \"ipaddress\": \"10.27.27.64\",\n            \"startport\": 22,\n            \"endport\": 22,\n            \"state\": \"Active\",\n            \"tags\":[{\"account\":1,\"domain\":\"ROOT\",\"domainid\":1,\"key\":\"some-tag\",\"resourceid\":66, \"resourcetype\":\"PortForwardingRule\", \"value\":\"some-value\"}]\n        }]\n    }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/resources/listisosresponse.json",
    "content": "{ \"listisosresponse\" : { \"count\":2 ,\"iso\" : [ {\"id\":\"018e0928-8205-4d8e-9329-f731a9ccd488\",\"name\":\"xs-tools.iso\",\"displaytext\":\"xen-pv-drv-iso\",\"ispublic\":true,\"created\":\"2012-08-21T15:45:01+0530\",\"isready\":true,\"passwordenabled\":false,\"bootable\":false,\"isfeatured\":true,\"crossZones\":false,\"account\":\"system\",\"domain\":\"ROOT\",\"domainid\":\"9d189ea2-097e-4b2b-9bae-d885f5430d69\",\"isextractable\":false,\"tags\":[]}, {\"id\":\"1e29244b-9cf0-4ff2-9978-677eb83f6bfb\",\"name\":\"vmware-tools.iso\",\"displaytext\":\"VMware Tools Installer ISO\",\"ispublic\":true,\"created\":\"2012-08-21T15:45:01+0530\",\"isready\":true,\"passwordenabled\":false,\"bootable\":false,\"isfeatured\":true,\"crossZones\":false,\"account\":\"system\",\"domain\":\"ROOT\",\"domainid\":\"9d189ea2-097e-4b2b-9bae-d885f5430d69\",\"isextractable\":false,\"tags\":[]} ] } }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/listloadbalancerrulesresponse.json",
    "content": "{ \"listloadbalancerrulesresponse\" : { \"count\":1 ,\"loadbalancerrule\" : [\n    {\"id\":93,\"name\":\"Ranny\",\"publicipid\":10,\"publicip\":\"10.27.27.59\",\"publicport\":\"80\",\"privateport\":\"80\",\"algorithm\":\"roundrobin\",\"cidrlist\":\"\",\"account\":\"admin\",\"domainid\":1,\"domain\":\"ROOT\",\"state\":\"Add\",\"zoneid\":1} ] } }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/listnetworkofferingsresponse.json",
    "content": "{ \"listnetworkofferingsresponse\" : { \"networkoffering\" : [  {\"id\":6,\"name\":\"DefaultVirtualizedNetworkOffering\",\"displaytext\":\"Virtual Vlan\",\"traffictype\":\"Guest\",\"isdefault\":true,\"specifyvlan\":false,\"availability\":\"Required\",\"networkrate\":200}, {\"id\":7,\"name\":\"DefaultDirectNetworkOffering\",\"displaytext\":\"Direct\",\"traffictype\":\"Public\",\"isdefault\":true,\"specifyvlan\":false,\"availability\":\"Required\",\"networkrate\":200} ] } }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/listnetworksresponse-2.json",
    "content": "{ \"listnetworksresponse\" : { \"network\" : [  {\"id\":204,\"name\":\"Virtual Network\",\"displaytext\":\"A dedicated virtualized network for your account.  The broadcast domain is contained within a VLAN and all public network access is routed out by a virtual router.\",\"broadcastdomaintype\":\"Vlan\",\"traffictype\":\"Guest\",\"zoneid\":2,\"networkofferingid\":6,\"networkofferingname\":\"DefaultVirtualizedNetworkOffering\",\"networkofferingdisplaytext\":\"Virtual Vlan\",\"networkofferingavailability\":\"Required\",\"isshared\":false,\"issystem\":false,\"state\":\"Implemented\",\"related\":204,\"broadcasturi\":\"vlan://240\",\"dns1\":\"8.8.8.8\",\"type\":\"Virtual\",\"account\":\"adrian\",\"domainid\":1,\"domain\":\"ROOT\",\"isdefault\":true,\"service\":[{\"name\":\"Vpn\",\"capability\":[{\"name\":\"SupportedVpnTypes\",\"value\":\"pptp,l2tp,ipsec\"}]},{\"name\":\"Gateway\"},{\"name\":\"UserData\"},{\"name\":\"Dhcp\"},{\"name\":\"Firewall\",\"capability\":[{\"name\":\"SupportedSourceNatTypes\",\"value\":\"per account\"},{\"name\":\"StaticNat\",\"value\":\"true\"},{\"name\":\"TrafficStatistics\",\"value\":\"per public ip\"},{\"name\":\"PortForwarding\",\"value\":\"true\"},{\"name\":\"MultipleIps\",\"value\":\"true\"},{\"name\":\"SupportedProtocols\",\"value\":\"tcp,udp\"}]},{\"name\":\"Dns\"},{\"name\":\"Lb\",\"capability\":[{\"name\":\"SupportedLbAlgorithms\",\"value\":\"roundrobin,leastconn,source\"},{\"name\":\"SupportedProtocols\",\"value\":\"tcp, udp\"}]}],\"networkdomain\":\"cs3cloud.internal\"} ] } }\n"
  },
  {
    "path": "apis/cloudstack/src/test/resources/listnetworksresponse.json",
    "content": "{ \"listnetworksresponse\": {\n    \"network\": [\n        {\n            \"id\": 204,\n            \"name\": \"Virtual Network\",\n            \"displaytext\": \"A dedicated virtualized network for your account.  The broadcast domain is contained within a VLAN and all public network access is routed out by a virtual router.\",\n            \"broadcastdomaintype\": \"Vlan\",\n            \"traffictype\": \"Guest\",\n            \"zoneid\": 1,\n            \"networkofferingid\": 6,\n            \"networkofferingname\": \"DefaultVirtualizedNetworkOffering\",\n            \"networkofferingdisplaytext\": \"Virtual Vlan\",\n            \"networkofferingavailability\": \"Required\",\n            \"isshared\": false,\n            \"issystem\": false,\n            \"state\": \"Implemented\",\n            \"related\": 204,\n            \"broadcasturi\": \"vlan://240\",\n            \"dns1\": \"8.8.8.8\",\n            \"type\": \"Virtual\",\n            \"account\": \"adrian\",\n            \"domainid\": 1,\n            \"domain\": \"ROOT\",\n            \"isdefault\": true,\n            \"service\": [\n                {\n                    \"name\": \"Vpn\",\n                    \"capability\": [\n                        {\n                            \"name\": \"SupportedVpnTypes\",\n                            \"value\": \"pptp,l2tp,ipsec\"\n                        }\n                    ]\n                },\n                {\n                    \"name\": \"Gateway\"\n                },\n                {\n                    \"name\": \"UserData\"\n                },\n                {\n                    \"name\": \"Dhcp\"\n                },\n                {\n                    \"name\": \"Firewall\",\n                    \"capability\": [\n                        {\n                            \"name\": \"SupportedSourceNatTypes\",\n                            \"value\": \"per account\"\n                        },\n                        {\n                            \"name\": \"StaticNat\",\n                            \"value\": \"true\"\n                        },\n                        {\n                            \"name\": \"TrafficStatistics\",\n                            \"value\": \"per public ip\"\n                        },\n                        {\n                            \"name\": \"PortForwarding\",\n                            \"value\": \"true\"\n                        },\n                        {\n                            \"name\": \"MultipleIps\",\n                            \"value\": \"true\"\n                        },\n                        {\n                            \"name\": \"SupportedProtocols\",\n                            \"value\": \"tcp,udp\"\n                        }\n                    ]\n                },\n                {\n                    \"name\": \"Dns\"\n                },\n                {\n                    \"name\": \"Lb\",\n                    \"capability\": [\n                        {\n                            \"name\": \"SupportedLbAlgorithms\",\n                            \"value\": \"roundrobin,leastconn,source\"\n                        },\n                        {\n                            \"name\": \"SupportedProtocols\",\n                            \"value\": \"tcp, udp\"\n                        }\n                    ]\n                }\n            ],\n            \"networkdomain\": \"cs3cloud.internal\",\n            \"tags\":[{\"account\":1,\"domain\":\"ROOT\",\"domainid\":1,\"key\":\"some-tag\",\"resourceid\":204, \"resourcetype\":\"Network\", \"value\":\"some-value\"}]\n\n        }\n    ]\n} }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/listoscategoriesresponse.json",
    "content": "{ \"listoscategoriesresponse\" : { \"oscategory\" : [  {\"id\":1,\"name\":\"CentOS\"}, {\"id\":2,\"name\":\"Debian\"}, {\"id\":3,\"name\":\"Oracle\"}, {\"id\":4,\"name\":\"RedHat\"}, {\"id\":5,\"name\":\"SUSE\"}, {\"id\":6,\"name\":\"Windows\"}, {\"id\":7,\"name\":\"Other\"}, {\"id\":8,\"name\":\"Novel\"}, {\"id\":9,\"name\":\"Unix\"}, {\"id\":10,\"name\":\"Ubuntu\"} ] } }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/listostypesresponse.json",
    "content": "{ \"listostypesresponse\" : { \"ostype\" : [  {\"id\":69,\"oscategoryid\":7,\"description\":\"Asianux 3(32-bit)\"}, {\"id\":70,\"oscategoryid\":7,\"description\":\"Asianux 3(64-bit)\"}, {\"id\":1,\"oscategoryid\":1,\"description\":\"CentOS 4.5 (32-bit)\"}, {\"id\":2,\"oscategoryid\":1,\"description\":\"CentOS 4.6 (32-bit)\"}, {\"id\":3,\"oscategoryid\":1,\"description\":\"CentOS 4.7 (32-bit)\"}, {\"id\":4,\"oscategoryid\":1,\"description\":\"CentOS 4.8 (32-bit)\"}, {\"id\":5,\"oscategoryid\":1,\"description\":\"CentOS 5.0 (32-bit)\"}, {\"id\":6,\"oscategoryid\":1,\"description\":\"CentOS 5.0 (64-bit)\"}, {\"id\":7,\"oscategoryid\":1,\"description\":\"CentOS 5.1 (32-bit)\"}, {\"id\":8,\"oscategoryid\":1,\"description\":\"CentOS 5.1 (64-bit)\"}, {\"id\":9,\"oscategoryid\":1,\"description\":\"CentOS 5.2 (32-bit)\"}, {\"id\":10,\"oscategoryid\":1,\"description\":\"CentOS 5.2 (64-bit)\"}, {\"id\":11,\"oscategoryid\":1,\"description\":\"CentOS 5.3 (32-bit)\"}, {\"id\":12,\"oscategoryid\":1,\"description\":\"CentOS 5.3 (64-bit)\"}, {\"id\":13,\"oscategoryid\":1,\"description\":\"CentOS 5.4 (32-bit)\"}, {\"id\":14,\"oscategoryid\":1,\"description\":\"CentOS 5.4 (64-bit)\"}, {\"id\":111,\"oscategoryid\":1,\"description\":\"CentOS 5.5 (32-bit)\"}, {\"id\":112,\"oscategoryid\":1,\"description\":\"CentOS 5.5 (64-bit)\"}, {\"id\":73,\"oscategoryid\":2,\"description\":\"Debian GNU/Linux 4(32-bit)\"}, {\"id\":74,\"oscategoryid\":2,\"description\":\"Debian GNU/Linux 4(64-bit)\"}, {\"id\":72,\"oscategoryid\":2,\"description\":\"Debian GNU/Linux 5(64-bit)\"}, {\"id\":15,\"oscategoryid\":2,\"description\":\"Debian GNU/Linux 5.0 (32-bit)\"}, {\"id\":132,\"oscategoryid\":2,\"description\":\"Debian GNU/Linux 6(32-bit)\"}, {\"id\":133,\"oscategoryid\":2,\"description\":\"Debian GNU/Linux 6(64-bit)\"}, {\"id\":102,\"oscategoryid\":6,\"description\":\"DOS\"}, {\"id\":118,\"oscategoryid\":4,\"description\":\"Fedora 10\"}, {\"id\":117,\"oscategoryid\":4,\"description\":\"Fedora 11\"}, {\"id\":116,\"oscategoryid\":4,\"description\":\"Fedora 12\"}, {\"id\":115,\"oscategoryid\":4,\"description\":\"Fedora 13\"}, {\"id\":120,\"oscategoryid\":4,\"description\":\"Fedora 8\"}, {\"id\":119,\"oscategoryid\":4,\"description\":\"Fedora 9\"}, {\"id\":83,\"oscategoryid\":9,\"description\":\"FreeBSD (32-bit)\"}, {\"id\":84,\"oscategoryid\":9,\"description\":\"FreeBSD (64-bit)\"}, {\"id\":92,\"oscategoryid\":6,\"description\":\"Microsoft Small Bussiness Server 2003\"}, {\"id\":78,\"oscategoryid\":8,\"description\":\"Novell Netware 5.1\"}, {\"id\":77,\"oscategoryid\":8,\"description\":\"Novell Netware 6.x\"}, {\"id\":68,\"oscategoryid\":7,\"description\":\"Open Enterprise Server\"}, {\"id\":16,\"oscategoryid\":3,\"description\":\"Oracle Enterprise Linux 5.0 (32-bit)\"}, {\"id\":17,\"oscategoryid\":3,\"description\":\"Oracle Enterprise Linux 5.0 (64-bit)\"}, {\"id\":18,\"oscategoryid\":3,\"description\":\"Oracle Enterprise Linux 5.1 (32-bit)\"}, {\"id\":19,\"oscategoryid\":3,\"description\":\"Oracle Enterprise Linux 5.1 (64-bit)\"}, {\"id\":20,\"oscategoryid\":3,\"description\":\"Oracle Enterprise Linux 5.2 (32-bit)\"}, {\"id\":21,\"oscategoryid\":3,\"description\":\"Oracle Enterprise Linux 5.2 (64-bit)\"}, {\"id\":22,\"oscategoryid\":3,\"description\":\"Oracle Enterprise Linux 5.3 (32-bit)\"}, {\"id\":23,\"oscategoryid\":3,\"description\":\"Oracle Enterprise Linux 5.3 (64-bit)\"}, {\"id\":24,\"oscategoryid\":3,\"description\":\"Oracle Enterprise Linux 5.4 (32-bit)\"}, {\"id\":25,\"oscategoryid\":3,\"description\":\"Oracle Enterprise Linux 5.4 (64-bit)\"}, {\"id\":134,\"oscategoryid\":3,\"description\":\"Oracle Enterprise Linux 5.5 (32-bit)\"}, {\"id\":135,\"oscategoryid\":3,\"description\":\"Oracle Enterprise Linux 5.5 (64-bit)\"}, {\"id\":104,\"oscategoryid\":7,\"description\":\"OS/2\"}, {\"id\":60,\"oscategoryid\":7,\"description\":\"Other (32-bit)\"}, {\"id\":103,\"oscategoryid\":7,\"description\":\"Other (64-bit)\"}, {\"id\":75,\"oscategoryid\":7,\"description\":\"Other 2.6x Linux (32-bit)\"}, {\"id\":76,\"oscategoryid\":7,\"description\":\"Other 2.6x Linux (64-bit)\"}, {\"id\":98,\"oscategoryid\":7,\"description\":\"Other Linux (32-bit)\"}, {\"id\":99,\"oscategoryid\":7,\"description\":\"Other Linux (64-bit)\"}, {\"id\":59,\"oscategoryid\":10,\"description\":\"Other Ubuntu (32-bit)\"}, {\"id\":100,\"oscategoryid\":10,\"description\":\"Other Ubuntu (64-bit)\"}, {\"id\":131,\"oscategoryid\":10,\"description\":\"Red Hat Enterprise Linux 2\"}, {\"id\":66,\"oscategoryid\":4,\"description\":\"Red Hat Enterprise Linux 3(32-bit)\"}, {\"id\":67,\"oscategoryid\":4,\"description\":\"Red Hat Enterprise Linux 3(64-bit)\"}, {\"id\":106,\"oscategoryid\":4,\"description\":\"Red Hat Enterprise Linux 4(64-bit)\"}, {\"id\":26,\"oscategoryid\":4,\"description\":\"Red Hat Enterprise Linux 4.5 (32-bit)\"}, {\"id\":27,\"oscategoryid\":4,\"description\":\"Red Hat Enterprise Linux 4.6 (32-bit)\"}, {\"id\":28,\"oscategoryid\":4,\"description\":\"Red Hat Enterprise Linux 4.7 (32-bit)\"}, {\"id\":29,\"oscategoryid\":4,\"description\":\"Red Hat Enterprise Linux 4.8 (32-bit)\"}, {\"id\":30,\"oscategoryid\":4,\"description\":\"Red Hat Enterprise Linux 5.0 (32-bit)\"}, {\"id\":31,\"oscategoryid\":4,\"description\":\"Red Hat Enterprise Linux 5.0 (64-bit)\"}, {\"id\":32,\"oscategoryid\":4,\"description\":\"Red Hat Enterprise Linux 5.1 (32-bit)\"}, {\"id\":33,\"oscategoryid\":4,\"description\":\"Red Hat Enterprise Linux 5.1 (64-bit)\"}, {\"id\":34,\"oscategoryid\":4,\"description\":\"Red Hat Enterprise Linux 5.2 (32-bit)\"}, {\"id\":35,\"oscategoryid\":4,\"description\":\"Red Hat Enterprise Linux 5.2 (64-bit)\"}, {\"id\":36,\"oscategoryid\":4,\"description\":\"Red Hat Enterprise Linux 5.3 (32-bit)\"}, {\"id\":37,\"oscategoryid\":4,\"description\":\"Red Hat Enterprise Linux 5.3 (64-bit)\"}, {\"id\":38,\"oscategoryid\":4,\"description\":\"Red Hat Enterprise Linux 5.4 (32-bit)\"}, {\"id\":39,\"oscategoryid\":4,\"description\":\"Red Hat Enterprise Linux 5.4 (64-bit)\"}, {\"id\":113,\"oscategoryid\":4,\"description\":\"Red Hat Enterprise Linux 5.5 (32-bit)\"}, {\"id\":114,\"oscategoryid\":4,\"description\":\"Red Hat Enterprise Linux 5.5 (64-bit)\"}, {\"id\":136,\"oscategoryid\":4,\"description\":\"Red Hat Enterprise Linux 6.0 (32-bit)\"}, {\"id\":137,\"oscategoryid\":4,\"description\":\"Red Hat Enterprise Linux 6.0 (64-bit)\"}, {\"id\":85,\"oscategoryid\":9,\"description\":\"SCO OpenServer 5\"}, {\"id\":86,\"oscategoryid\":9,\"description\":\"SCO UnixWare 7\"}, {\"id\":79,\"oscategoryid\":9,\"description\":\"Sun Solaris 10(32-bit)\"}, {\"id\":80,\"oscategoryid\":9,\"description\":\"Sun Solaris 10(64-bit)\"}, {\"id\":82,\"oscategoryid\":9,\"description\":\"Sun Solaris 8(Experimental)\"}, {\"id\":81,\"oscategoryid\":9,\"description\":\"Sun Solaris 9(Experimental)\"}, {\"id\":109,\"oscategoryid\":5,\"description\":\"SUSE Linux Enterprise 10(32-bit)\"}, {\"id\":110,\"oscategoryid\":5,\"description\":\"SUSE Linux Enterprise 10(64-bit)\"}, {\"id\":96,\"oscategoryid\":5,\"description\":\"SUSE Linux Enterprise 8(32-bit)\"}, {\"id\":97,\"oscategoryid\":5,\"description\":\"SUSE Linux Enterprise 8(64-bit)\"}, {\"id\":107,\"oscategoryid\":5,\"description\":\"SUSE Linux Enterprise 9(32-bit)\"}, {\"id\":108,\"oscategoryid\":5,\"description\":\"SUSE Linux Enterprise 9(64-bit)\"}, {\"id\":41,\"oscategoryid\":5,\"description\":\"SUSE Linux Enterprise Server 10 SP1 (32-bit)\"}, {\"id\":42,\"oscategoryid\":5,\"description\":\"SUSE Linux Enterprise Server 10 SP1 (64-bit)\"}, {\"id\":43,\"oscategoryid\":5,\"description\":\"SUSE Linux Enterprise Server 10 SP2 (32-bit)\"}, {\"id\":44,\"oscategoryid\":5,\"description\":\"SUSE Linux Enterprise Server 10 SP2 (64-bit)\"}, {\"id\":45,\"oscategoryid\":5,\"description\":\"SUSE Linux Enterprise Server 10 SP3 (64-bit)\"}, {\"id\":46,\"oscategoryid\":5,\"description\":\"SUSE Linux Enterprise Server 11 (32-bit)\"}, {\"id\":47,\"oscategoryid\":5,\"description\":\"SUSE Linux Enterprise Server 11 (64-bit)\"}, {\"id\":40,\"oscategoryid\":5,\"description\":\"SUSE Linux Enterprise Server 9 SP4 (32-bit)\"}, {\"id\":121,\"oscategoryid\":10,\"description\":\"Ubuntu 10.04 (32-bit)\"}, {\"id\":126,\"oscategoryid\":10,\"description\":\"Ubuntu 10.04 (64-bit)\"}, {\"id\":125,\"oscategoryid\":10,\"description\":\"Ubuntu 8.04 (32-bit)\"}, {\"id\":130,\"oscategoryid\":10,\"description\":\"Ubuntu 8.04 (64-bit)\"}, {\"id\":124,\"oscategoryid\":10,\"description\":\"Ubuntu 8.10 (32-bit)\"}, {\"id\":129,\"oscategoryid\":10,\"description\":\"Ubuntu 8.10 (64-bit)\"}, {\"id\":123,\"oscategoryid\":10,\"description\":\"Ubuntu 9.04 (32-bit)\"}, {\"id\":128,\"oscategoryid\":10,\"description\":\"Ubuntu 9.04 (64-bit)\"}, {\"id\":122,\"oscategoryid\":10,\"description\":\"Ubuntu 9.10 (32-bit)\"}, {\"id\":127,\"oscategoryid\":10,\"description\":\"Ubuntu 9.10 (64-bit)\"}, {\"id\":95,\"oscategoryid\":6,\"description\":\"Windows 2000 Advanced Server\"}, {\"id\":105,\"oscategoryid\":6,\"description\":\"Windows 2000 Professional\"}, {\"id\":61,\"oscategoryid\":6,\"description\":\"Windows 2000 Server\"}, {\"id\":55,\"oscategoryid\":6,\"description\":\"Windows 2000 Server SP4 (32-bit)\"}, {\"id\":65,\"oscategoryid\":6,\"description\":\"Windows 3.1\"}, {\"id\":48,\"oscategoryid\":6,\"description\":\"Windows 7 (32-bit)\"}, {\"id\":49,\"oscategoryid\":6,\"description\":\"Windows 7 (64-bit)\"}, {\"id\":63,\"oscategoryid\":6,\"description\":\"Windows 95\"}, {\"id\":62,\"oscategoryid\":6,\"description\":\"Windows 98\"}, {\"id\":64,\"oscategoryid\":6,\"description\":\"Windows NT 4\"}, {\"id\":87,\"oscategoryid\":6,\"description\":\"Windows Server 2003 DataCenter Edition(32-bit)\"}, {\"id\":88,\"oscategoryid\":6,\"description\":\"Windows Server 2003 DataCenter Edition(64-bit)\"}, {\"id\":50,\"oscategoryid\":6,\"description\":\"Windows Server 2003 Enterprise Edition(32-bit)\"}, {\"id\":51,\"oscategoryid\":6,\"description\":\"Windows Server 2003 Enterprise Edition(64-bit)\"}, {\"id\":89,\"oscategoryid\":6,\"description\":\"Windows Server 2003 Standard Edition(32-bit)\"}, {\"id\":90,\"oscategoryid\":6,\"description\":\"Windows Server 2003 Standard Edition(64-bit)\"}, {\"id\":91,\"oscategoryid\":6,\"description\":\"Windows Server 2003 Web Edition\"}, {\"id\":52,\"oscategoryid\":6,\"description\":\"Windows Server 2008 (32-bit)\"}, {\"id\":53,\"oscategoryid\":6,\"description\":\"Windows Server 2008 (64-bit)\"}, {\"id\":54,\"oscategoryid\":6,\"description\":\"Windows Server 2008 R2 (64-bit)\"}, {\"id\":56,\"oscategoryid\":6,\"description\":\"Windows Vista (32-bit)\"}, {\"id\":101,\"oscategoryid\":6,\"description\":\"Windows Vista (64-bit)\"}, {\"id\":93,\"oscategoryid\":6,\"description\":\"Windows XP (32-bit)\"}, {\"id\":94,\"oscategoryid\":6,\"description\":\"Windows XP (64-bit)\"}, {\"id\":57,\"oscategoryid\":6,\"description\":\"Windows XP SP2 (32-bit)\"}, {\"id\":58,\"oscategoryid\":6,\"description\":\"Windows XP SP3 (32-bit)\"} ] } }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/listpodsresponse.json",
    "content": "{ \"listpodsresponse\" : { \"count\":2 ,\"pod\" : [  {\"id\":1,\"name\":\"Dev Pod 1\",\"zoneid\":1,\"zonename\":\"Dev Zone 1\",\"gateway\":\"10.26.26.254\",\"netmask\":\"255.255.255.0\",\"startip\":\"10.26.26.50\",\"endip\":\"10.26.26.100\",\"allocationstate\":\"Enabled\"}, {\"id\":2,\"name\":\"Dev Pod 2\",\"zoneid\":2,\"zonename\":\"Dev Zone 2\",\"gateway\":\"10.22.22.254\",\"netmask\":\"255.255.255.0\",\"startip\":\"10.22.22.25\",\"endip\":\"10.22.22.50\",\"allocationstate\":\"Enabled\"} ] } }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/listportforwardingrulesresponse.json",
    "content": "{ \"listportforwardingrulesresponse\": {\n    \"portforwardingrule\": [\n        {\n            \"id\": 18,\n            \"privateport\": \"22\",\n            \"protocol\": \"tcp\",\n            \"publicport\": \"22\",\n            \"virtualmachineid\": 89,\n            \"virtualmachinename\": \"i-3-89-VM\",\n            \"ipaddressid\": 34,\n            \"ipaddress\": \"72.52.126.63\",\n            \"state\": \"Active\",\n            \"tags\": []\n        },\n        {\n            \"id\": 15,\n            \"privateport\": \"22\",\n            \"protocol\": \"tcp\",\n            \"publicport\": \"2022\",\n            \"virtualmachineid\": 3,\n            \"virtualmachinename\": \"i-3-3-VM\",\n            \"ipaddressid\": 3,\n            \"ipaddress\": \"72.52.126.32\",\n            \"state\": \"Active\",\n            \"cidrlist\": \"0.0.0.0/1,128.0.0.0/1\",\n            \"tags\":[{\"account\":1,\"domain\":\"ROOT\",\"domainid\":1,\"key\":\"some-tag\",\"resourceid\":15, \"resourcetype\":\"PortForwardingRule\", \"value\":\"some-value\"}]\n        }\n    ]\n} }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/listprojectsresponse.json",
    "content": "{ \"listprojectsresponse\": {\n    \"count\": 2,\n    \"project\": [\n        {\n            \"id\": \"489da162-0b77-489d-b044-ce39aa018b1f\",\n            \"name\": \"NN-HA-T1\",\n            \"displaytext\": \"\",\n            \"domainid\": \"41a4917b-7952-499d-ba7f-4c57464d3dc8\",\n            \"domain\": \"ROOT\",\n            \"account\": \"thyde\",\n            \"state\": \"Active\",\n            \"tags\": []\n        },\n        {\n            \"id\": \"1c11f22c-15ac-4fa7-b833-4d748df317b7\",\n            \"name\": \"hive\",\n            \"displaytext\": \"Hive\",\n            \"domainid\": \"41a4917b-7952-499d-ba7f-4c57464d3dc8\",\n            \"domain\": \"ROOT\",\n            \"account\": \"prasadm\",\n            \"state\": \"Active\",\n            \"tags\": [\n                {\n                    \"account\": \"prasadm\",\n                    \"domain\": \"ROOT\",\n                    \"domainid\": \"41a4917b-7952-499d-ba7f-4c57464d3dc8\",\n                    \"key\": \"some-tag\",\n                    \"resourceid\": \"1c11f22c-15ac-4fa7-b833-4d748df317b7\",\n                    \"resourcetype\": \"Project\",\n                    \"value\": \"some-value\"\n                }\n            ]\n        }\n    ]\n} }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/listpublicipaddressesresponse.json",
    "content": "{ \"listpublicipaddressesresponse\": {\n    \"publicipaddress\": [\n        {\n            \"id\": 30,\n            \"ipaddress\": \"72.52.126.59\",\n            \"allocated\": \"2011-02-19T21:15:01-0800\",\n            \"zoneid\": 1,\n            \"zonename\": \"San Jose 1\",\n            \"issourcenat\": false,\n            \"account\": \"adrian\",\n            \"domainid\": 1,\n            \"domain\": \"ROOT\",\n            \"forvirtualnetwork\": true,\n            \"isstaticnat\": false,\n            \"associatednetworkid\": 204,\n            \"networkid\": 200,\n            \"state\": \"Allocated\",\n            \"tags\": [\n                {\n                    \"account\": \"adrian\",\n                    \"domain\": \"ROOT\",\n                    \"domainid\": 1,\n                    \"key\": \"some-tag\",\n                    \"resourceid\": 30,\n                    \"resourcetype\": \"PublicIpAddress\",\n                    \"value\": \"some-value\"\n                }\n            ]\n        }\n    ]\n} }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/listresourcelimitsresponse.json",
    "content": "{ \"listresourcelimitsresponse\" : { \"count\":8 ,\"resourcelimit\" : [\n{\"account\":\"jclouds\",\"domainid\":457,\"domain\":\"AA000062-jclouds-dev\",\"resourcetype\":\"0\",\"max\":-1},\n{\"account\":\"jclouds\",\"domainid\":457,\"domain\":\"AA000062-jclouds-dev\",\"resourcetype\":\"1\",\"max\":-1},\n{\"account\":\"jclouds\",\"domainid\":457,\"domain\":\"AA000062-jclouds-dev\",\"resourcetype\":\"2\",\"max\":-1},\n{\"account\":\"jclouds\",\"domainid\":457,\"domain\":\"AA000062-jclouds-dev\",\"resourcetype\":\"3\",\"max\":-1},\n{\"account\":\"jclouds\",\"domainid\":457,\"domain\":\"AA000062-jclouds-dev\",\"resourcetype\":\"4\",\"max\":-1},\n{\"account\":\"jclouds\",\"domainid\":457,\"domain\":\"AA000062-jclouds-dev\",\"resourcetype\":\"7\",\"max\":-1},\n{\"account\":\"jclouds\",\"domainid\":457,\"domain\":\"AA000062-jclouds-dev\",\"resourcetype\":\"8\",\"max\":-1},\n{\"account\":\"jclouds\",\"domainid\":457,\"domain\":\"AA000062-jclouds-dev\",\"resourcetype\":\"9\",\"max\":-1}] } }\n"
  },
  {
    "path": "apis/cloudstack/src/test/resources/listsecuritygroupsresponse.json",
    "content": "{ \"listsecuritygroupsresponse\": {\n    \"securitygroup\": [\n        {\n            \"id\": 12,\n            \"name\": \"adriancole\",\n            \"account\": \"adrian\",\n            \"domainid\": 1,\n            \"domain\": \"ROOT\",\n            \"tags\":[]\n        },\n        {\n            \"id\": 13,\n            \"name\": \"default\",\n            \"description\": \"description\",\n            \"account\": \"adrian\",\n            \"domainid\": 1,\n            \"domain\": \"ROOT\",\n            \"ingressrule\": [\n                {\n                    \"ruleid\": 5,\n                    \"protocol\": \"tcp\",\n                    \"startport\": 22,\n                    \"endport\": 22,\n                    \"securitygroupname\": \"adriancole\",\n                    \"account\": \"adrian\"\n                },\n                {\n                    \"ruleid\": 6,\n                    \"protocol\": \"udp\",\n                    \"startport\": 11,\n                    \"endport\": 11,\n                    \"cidr\": \"1.1.1.1/24\"\n                }\n            ],\n            \"tags\": []\n        },\n        {\n            \"id\": 14,\n            \"name\": \"1\",\n            \"description\": \"description\",\n            \"account\": \"adrian\",\n            \"domainid\": 1,\n            \"domain\": \"ROOT\",\n            \"ingressrule\": [\n                {\n                    \"ruleid\": 7,\n                    \"protocol\": \"tcp\",\n                    \"startport\": 10,\n                    \"endport\": 10,\n                    \"cidr\": \"1.1.1.1/24\"\n                },\n                {\n                    \"ruleid\": 8,\n                    \"protocol\": \"tcp\",\n                    \"startport\": 10,\n                    \"endport\": 10,\n                    \"cidr\": \"2.2.2.2/16\"\n                }\n            ],\n            \"tags\": []\n        },\n        {\n            \"id\": 15,\n            \"name\": \"2\",\n            \"description\": \"description\",\n            \"account\": \"adrian\",\n            \"domainid\": 1,\n            \"domain\": \"ROOT\",\n            \"tags\": []\n        },\n        {\n            \"id\": 16,\n            \"name\": \"with1and2\",\n            \"description\": \"description\",\n            \"account\": \"adrian\",\n            \"domainid\": 1,\n            \"domain\": \"ROOT\",\n            \"ingressrule\": [\n                {\n                    \"ruleid\": 9,\n                    \"protocol\": \"icmp\",\n                    \"icmptype\": -1,\n                    \"icmpcode\": -1,\n                    \"securitygroupname\": \"1\",\n                    \"account\": \"adrian\"\n                },\n                {\n                    \"ruleid\": 10,\n                    \"protocol\": \"tcp\",\n                    \"startport\": 22,\n                    \"endport\": 22,\n                    \"securitygroupname\": \"1\",\n                    \"account\": \"adrian\"\n                },\n                {\n                    \"ruleid\": 11,\n                    \"protocol\": \"tcp\",\n                    \"startport\": 22,\n                    \"endport\": 22,\n                    \"securitygroupname\": \"2\",\n                    \"account\": \"adrian\"\n                }\n            ],\n            \"tags\": [\n                {\n                    \"account\": \"adrian\",\n                    \"domain\": \"ROOT\",\n                    \"domainid\": 1,\n                    \"key\": \"some-tag\",\n                    \"resourceid\": 16,\n                    \"resourcetype\": \"SecurityGroup\",\n                    \"value\": \"some-value\"\n                }\n            ]\n        }\n    ]\n} }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/listserviceofferingsresponse.json",
    "content": "{ \"listserviceofferingsresponse\" : { \"serviceoffering\" : [  {\"id\":1,\"name\":\"Small Instance\",\"displaytext\":\"Small Instance - 500 MhZ CPU, 512 MB RAM - $0.05 per hour\",\"cpunumber\":1,\"cpuspeed\":500,\"memory\":512,\"created\":\"2011-02-11T15:22:32-0800\",\"storagetype\":\"shared\",\"offerha\":false}, {\"id\":2,\"name\":\"Medium Instance\",\"displaytext\":\"Medium Instance, 1 GhZ CPU,  1 GB RAM - $0.10 per hour\",\"cpunumber\":1,\"cpuspeed\":1000,\"memory\":1024,\"created\":\"2011-02-11T15:22:32-0800\",\"storagetype\":\"shared\",\"offerha\":false} ] } }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/listsshkeypairsresponse.json",
    "content": "{ \"listsshkeypairsresponse\" : { \"count\":1 ,\"sshkeypair\" : [\n   {\"name\":\"jclouds-keypair\",\"fingerprint\":\"1c:06:74:52:3b:99:1c:95:5c:04:c2:f4:ba:77:6e:7b\"} ] } }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/liststoragepoolsresponse.json",
    "content": "{ \"liststoragepoolsresponse\" : { \"count\":1 ,\"storagepool\" : [  {\"id\":201,\"zoneid\":1,\"zonename\":\"Dev Zone 1\",\"podid\":1,\"podname\":\"Dev Pod 1\",\"name\":\"NFS Pri 1\",\"ipaddress\":\"10.26.26.165\",\"path\":\"/mnt/nfs/cs_pri\",\"created\":\"2011-11-26T23:33:06+0200\",\"type\":\"NetworkFilesystem\",\"clusterid\":1,\"clustername\":\"Xen Clust 1\",\"disksizetotal\":898356445184,\"disksizeallocated\":18276679680,\"tags\":\"tag1\",\"state\":\"Up\"} ] } }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/listtagsresponse.json",
    "content": "{\n    \"listtagsresponse\": {\n        \"count\": 1,\n        \"tag\": [\n            {\n                \"key\": \"test-tag\",\n                \"value\": \"true\",\n                \"resourcetype\": \"Template\",\n                \"resourceid\": \"54fe1d53-5d73-4184-8b62-948b9d8e08fb\",\n                \"account\": \"admin\",\n                \"domainid\": \"79dc06c4-4432-11e4-b70d-000c29e19aa0\",\n                \"domain\": \"ROOT\"\n            }\n        ]\n    }\n}"
  },
  {
    "path": "apis/cloudstack/src/test/resources/listtemplatesresponse-imageextension.json",
    "content": "{ \"listtemplatesresponse\" : { \"count\":1 ,\"template\" : [  {\"id\":\"3dc6ce25-a6cf-4d60-a664-3499993b511b\",\"name\":\"temp-template-ignore\",\"displaytext\":\"sometext\",\"ispublic\":false,\"created\":\"2013-06-21T12:37:01-0700\",\"isready\":true,\"passwordenabled\":false,\"format\":\"QCOW2\",\"isfeatured\":false,\"crossZones\":false,\"ostypeid\":\"be820210-c741-4c36-9ba1-f38363bd37d5\",\"ostypename\":\"CentOS 5.6 (32-bit)\",\"account\":\"andrew\",\"zoneid\":\"1\",\"zonename\":\"San Jose 1\",\"status\":\"Download Complete\",\"size\":26843545600,\"templatetype\":\"USER\",\"hypervisor\":\"KVM\",\"domain\":\"ROOT\",\"domainid\":\"41a4917b-7952-499d-ba7f-4c57464d3dc8\",\"isextractable\":false,\"checksum\":\"6dd5d7f073ff951b033a8cadb877bde2\",\"sourcetemplateid\":\"9d597afb-4d3d-4a69-bf45-f95b0d1ee160\"} ] } }\n"
  },
  {
    "path": "apis/cloudstack/src/test/resources/listtemplatesresponse.json",
    "content": "{ \"listtemplatesresponse\": {\n    \"template\": [\n        {\n            \"id\": 2,\n            \"name\": \"CentOS 5.3(64-bit) no GUI (XenServer)\",\n            \"displaytext\": \"CentOS 5.3(64-bit) no GUI (XenServer)\",\n            \"ispublic\": true,\n            \"created\": \"2011-03-20T19:17:48-0700\",\n            \"isready\": false,\n            \"passwordenabled\": false,\n            \"format\": \"VHD\",\n            \"isfeatured\": true,\n            \"crossZones\": true,\n            \"ostypeid\": 11,\n            \"ostypename\": \"CentOS 5.3 (32-bit)\",\n            \"account\": \"system\",\n            \"zoneid\": 2,\n            \"zonename\": \"Chicago\",\n            \"templatetype\": \"BUILTIN\",\n            \"hypervisor\": \"XenServer\",\n            \"domain\": \"ROOT\",\n            \"domainid\": 1,\n            \"isextractable\": true,\n            \"tags\": []\n        },\n        {\n            \"id\": 4,\n            \"name\": \"CentOS 5.5(64-bit) no GUI (KVM)\",\n            \"displaytext\": \"CentOS 5.5(64-bit) no GUI (KVM)\",\n            \"ispublic\": true,\n            \"created\": \"2011-03-20T19:17:48-0700\",\n            \"isready\": true,\n            \"passwordenabled\": false,\n            \"format\": \"QCOW2\",\n            \"isfeatured\": true,\n            \"crossZones\": true,\n            \"ostypeid\": 112,\n            \"ostypename\": \"CentOS 5.5 (64-bit)\",\n            \"account\": \"system\",\n            \"zoneid\": 2,\n            \"zonename\": \"Chicago\",\n            \"size\": 8589934592,\n            \"templatetype\": \"BUILTIN\",\n            \"hypervisor\": \"KVM\",\n            \"domain\": \"ROOT\",\n            \"domainid\": 1,\n            \"isextractable\": true\n        },\n        {\n            \"id\": 203,\n            \"name\": \"Windows 7 KVM\",\n            \"displaytext\": \"Windows 7 KVM\",\n            \"ispublic\": true,\n            \"created\": \"2011-03-20T22:02:18-0700\",\n            \"isready\": true,\n            \"passwordenabled\": false,\n            \"format\": \"QCOW2\",\n            \"isfeatured\": true,\n            \"crossZones\": false,\n            \"ostypeid\": 48,\n            \"ostypename\": \"Windows 7 (32-bit)\",\n            \"account\": \"admin\",\n            \"zoneid\": 2,\n            \"zonename\": \"Chicago\",\n            \"size\": 17179869184,\n            \"templatetype\": \"USER\",\n            \"hypervisor\": \"KVM\",\n            \"domain\": \"ROOT\",\n            \"domainid\": 1,\n            \"isextractable\": false\n        },\n        {\n            \"id\": 7,\n            \"name\": \"CentOS 5.3(64-bit) no GUI (vSphere)\",\n            \"displaytext\": \"CentOS 5.3(64-bit) no GUI (vSphere)\",\n            \"ispublic\": true,\n            \"created\": \"2011-03-20T19:17:48-0700\",\n            \"isready\": false,\n            \"passwordenabled\": false,\n            \"format\": \"OVA\",\n            \"isfeatured\": true,\n            \"crossZones\": true,\n            \"ostypeid\": 12,\n            \"ostypename\": \"CentOS 5.3 (64-bit)\",\n            \"account\": \"system\",\n            \"zoneid\": 2,\n            \"zonename\": \"Chicago\",\n            \"templatetype\": \"BUILTIN\",\n            \"hypervisor\": \"VMware\",\n            \"domain\": \"ROOT\",\n            \"domainid\": 1,\n            \"isextractable\": true\n        },\n        {\n            \"id\": 241,\n            \"name\": \"kvmdev4\",\n            \"displaytext\": \"v5.6.28_Dev4\",\n            \"ispublic\": true,\n            \"created\": \"2011-04-21T09:43:25-0700\",\n            \"isready\": true,\n            \"passwordenabled\": false,\n            \"format\": \"QCOW2\",\n            \"isfeatured\": false,\n            \"crossZones\": false,\n            \"ostypeid\": 14,\n            \"ostypename\": \"CentOS 5.4 (64-bit)\",\n            \"account\": \"rs3\",\n            \"zoneid\": 2,\n            \"zonename\": \"Chicago\",\n            \"size\": 10737418240,\n            \"templatetype\": \"USER\",\n            \"hypervisor\": \"KVM\",\n            \"domain\": \"ROOT\",\n            \"domainid\": 1,\n            \"isextractable\": false,\n            \"tags\": [\n                {\n                    \"account\": \"rs3\",\n                    \"domain\": \"ROOT\",\n                    \"domainid\": 1,\n                    \"key\": \"some-tag\",\n                    \"resourceid\": 241,\n                    \"resourcetype\": \"Template\",\n                    \"value\": \"some-value\"\n                }\n            ]\n        }\n    ]\n} }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/listusagerecordsresponse.json",
    "content": "{ \"listusagerecordsresponse\" : { \"count\":1 ,\"usagerecord\" : [  {\"account\":\"admin\",\"accountid\":2,\"domainid\":1,\"zoneid\":1,\"description\":\"Template Id:203 Size:3117171712\",\"usage\":\"24 Hrs\",\"usagetype\":7,\"rawusage\":\"24\",\"templateid\":0,\"usageid\":203,\"size\":3117171712,\"project\":\"project1\",\"projectid\":1,\"startdate\":\"2011-12-15'T'00:00:00+00:00\",\"enddate\":\"2011-12-15'T'23:59:59+00:00\",\"domain\":\"myDomain\",\"virtualsize\":3117171712,\"cpunumber\":2,\"cpuspeed\":1024,\"memory\":512,\"issystem\":false,\"isdefault\":false,tags:[ { \"key\":\"env\",\"value\":\"dev\" } ] } ] } }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/listvirtualmachinesresponse-imageextension.json",
    "content": "{ \"listvirtualmachinesresponse\" : { \"count\":1 ,\"virtualmachine\" : [\n{\"id\":\"3239ade9-fd25-405c-8eda-59f0313a3fb0\",\"name\":\"apb-cent32-bld\",\"displayname\":\"apb-cent32-bld\",\"account\":\"andrew\",\"domainid\":\"41a4917b-7952-499d-ba7f-4c57464d3dc8\",\"domain\":\"ROOT\",\"created\":\"2013-04-16T16:25:57-0700\",\"state\":\"Stopped\",\"haenable\":false,\"zoneid\":\"1\",\"zonename\":\"San Jose 1\",\"hostid\":\"0\",\"templateid\":\"9d597afb-4d3d-4a69-bf45-f95b0d1ee160\",\"templatename\":\"centos-6.2-x32-template\",\"templatedisplaytext\":\"CentOS 6.2 x32 Template\",\"passwordenabled\":false,\"serviceofferingid\":\"7cc4f8c3-7c56-4155-9916-9f42072ea712\",\"serviceofferingname\":\"Tiny\",\"cpunumber\":1,\"cpuspeed\":1600,\"memory\":1024,\"cpuused\":\"0.01%\",\"networkkbsread\":319420,\"networkkbswrite\":3,\"guestosid\":\"45de18f1-87c6-4646-8099-95c61f2a300a\",\"rootdeviceid\":0,\"rootdevicetype\":\"Filesystem\",\"securitygroup\":[{\"id\":\"50288900-28eb-4d7f-9c33-e4c26e3b66d2\",\"name\":\"default\",\"description\":\"Default Security Group\"}],\"nic\":[{\"id\":\"fd65b6fd-2c3e-4c8a-a0bc-6a5db4e8007a\",\"networkid\":\"0c82cd9f-ca64-4df4-9300-b33d81562403\",\"netmask\":\"255.255.254.0\",\"gateway\":\"10.20.92.3\",\"ipaddress\":\"10.20.92.96\",\"traffictype\":\"Guest\",\"type\":\"Shared\",\"isdefault\":true,\"macaddress\":\"06:ec:68:00:0f:04\"}],\"hypervisor\":\"KVM\",\"instancename\":\"i-4-69942-VM\"} ] } }\n"
  },
  {
    "path": "apis/cloudstack/src/test/resources/listvirtualmachinesresponse.json",
    "content": "{ \"listvirtualmachinesresponse\": {\n    \"virtualmachine\": [\n        {\n            \"id\": 54,\n            \"name\": \"i-3-54-VM\",\n            \"displayname\": \"i-3-54-VM\",\n            \"account\": \"adrian\",\n            \"domainid\": 1,\n            \"domain\": \"ROOT\",\n            \"created\": \"2011-02-16T14:28:37-0800\",\n            \"state\": \"Starting\",\n            \"haenable\": false,\n            \"zoneid\": 1,\n            \"zonename\": \"San Jose 1\",\n            \"templateid\": 2,\n            \"templatename\": \"CentOS 5.3(64-bit) no GUI (XenServer)\",\n            \"templatedisplaytext\": \"CentOS 5.3(64-bit) no GUI (XenServer)\",\n            \"passwordenabled\": false,\n            \"serviceofferingid\": 1,\n            \"serviceofferingname\": \"Small Instance\",\n            \"cpunumber\": 1,\n            \"cpuspeed\": 500,\n            \"memory\": 512,\n            \"guestosid\": 11,\n            \"rootdeviceid\": 0,\n            \"rootdevicetype\": \"NetworkFilesystem\",\n            \"securitygroup\": [],\n            \"jobid\": 63,\n            \"jobstatus\": 0,\n            \"nic\": [\n                {\n                    \"id\": 72,\n                    \"networkid\": 204,\n                    \"netmask\": \"255.255.255.0\",\n                    \"gateway\": \"10.1.1.1\",\n                    \"ipaddress\": \"10.1.1.18\",\n                    \"traffictype\": \"Guest\",\n                    \"type\": \"Virtual\",\n                    \"isdefault\": true\n                }\n            ],\n            \"hypervisor\": \"XenServer\",\n            \"tags\": [\n                {\n                    \"account\": \"adrian\",\n                    \"domain\": \"ROOT\",\n                    \"domainid\": \"1\",\n                    \"key\": \"some-tag\",\n                    \"resourceid\": \"54\",\n                    \"resourcetype\": \"UserVm\",\n                    \"value\": \"some-value\"\n                },\n                {\n                    \"account\": \"adrian\",\n                    \"domain\": \"ROOT\",\n                    \"domainid\": \"1\",\n                    \"key\": \"another-tag\",\n                    \"resourceid\": \"54\",\n                    \"resourcetype\": \"UserVm\",\n                    \"value\": \"jclouds-empty-tag-placeholder\"\n                }\n\n            ]\n        }\n    ]\n} }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/listvirtualmachinesresponse3x.json",
    "content": "{ \"listvirtualmachinesresponse\": {\n    \"count\": 1,\n    \"virtualmachine\": [\n        {\n            \"id\": \"fee2ccb3-c1f2-4e7b-8465-42b390e10dff\",\n            \"name\": \"cloudstack-r-611\",\n            \"displayname\": \"cloudstack-r-611\",\n            \"account\": \"jcloud2\",\n            \"domainid\": \"ea66e3a5-d007-42e8-a0de-ec5ce778a1d7\",\n            \"domain\": \"jCloud\",\n            \"created\": \"2012-05-22T09:18:28-0700\",\n            \"state\": \"Running\",\n            \"haenable\": false,\n            \"zoneid\": \"1\",\n            \"zonename\": \"Santa Clara Zone\",\n            \"templateid\": \"5c65f152-a4bc-4405-a756-fd10841a9aa7\",\n            \"templatename\": \"jclouds-6d4bdc29\",\n            \"templatedisplaytext\": \"jclouds live testCreateTemplate\",\n            \"passwordenabled\": false,\n            \"serviceofferingid\": \"5305750d-df71-4da9-8cd0-e23c2236a6e2\",\n            \"serviceofferingname\": \"Micro Instance\",\n            \"cpunumber\": 1,\n            \"cpuspeed\": 500,\n            \"memory\": 256,\n            \"guestosid\": \"6dcd58ce-1ec6-432c-af0b-9ab4ca9207d9\",\n            \"rootdeviceid\": 0,\n            \"rootdevicetype\": \"IscsiLUN\",\n            \"securitygroup\": [],\n            \"nic\": [\n                {\n                    \"id\": \"48640c5e-90f3-45bd-abd2-a108ca8957ac\",\n                    \"networkid\": \"c0d5db5b-f7d5-44e1-b854-21ecd1a09dbf\",\n                    \"netmask\": \"255.255.255.0\",\n                    \"gateway\": \"10.1.1.1\",\n                    \"ipaddress\": \"10.1.1.227\",\n                    \"traffictype\": \"Guest\",\n                    \"type\": \"Isolated\",\n                    \"isdefault\": true\n                }\n            ],\n            \"publicipid\": \"e202aafb-ab41-4dc0-80e9-9fcd64fbf45c\",\n            \"publicip\": \"72.52.126.110\",\n            \"tags\": [\n                {\n                    \"account\": \"jcloud2\",\n                    \"domain\": \"jCloud\",\n                    \"domainid\": \"ea66e3a5-d007-42e8-a0de-ec5ce778a1d7\",\n                    \"key\": \"some-tag\",\n                    \"resourceid\": \"fee2ccb3-c1f2-4e7b-8465-42b390e10dff\",\n                    \"resourcetype\": \"UserVm\",\n                    \"value\": \"some-value\"\n                }\n            ]\n        }\n    ]\n} }\n"
  },
  {
    "path": "apis/cloudstack/src/test/resources/listvlaniprangesresponse.json",
    "content": "{ \"listvlaniprangesresponse\" : { \"count\":2 ,\"vlaniprange\" : [  {\"id\":1,\"forvirtualnetwork\":true,\"zoneid\":1,\"vlan\":\"127\",\"account\":\"system\",\"domainid\":1,\"domain\":\"ROOT\",\"gateway\":\"10.27.27.254\",\"netmask\":\"255.255.255.0\",\"startip\":\"10.27.27.50\",\"endip\":\"10.27.27.100\",\"networkid\":200}, {\"id\":2,\"forvirtualnetwork\":false,\"zoneid\":2,\"vlan\":\"untagged\",\"account\":\"system\",\"domainid\":1,\"domain\":\"ROOT\",\"podid\":2,\"podname\":\"Dev Pod 2\",\"gateway\":\"10.22.22.254\",\"netmask\":\"255.255.255.0\",\"startip\":\"10.22.22.51\",\"endip\":\"10.22.22.100\",\"networkid\":209} ] } }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/listvolumesresponse-imageextension.json",
    "content": "{ \"listvolumesresponse\" : { \"count\":1 ,\"volume\" : [  {\"id\":\"fe1ada16-57a0-40ae-b577-01a153690fb4\",\"name\":\"ROOT-69942\",\"zoneid\":\"7dbc4787-ec2f-498d-95f0-848c8c81e5da\",\"zonename\":\"MTV-Zone1\",\"type\":\"ROOT\",\"deviceid\":0,\"virtualmachineid\":\"3239ade9-fd25-405c-8eda-59f0313a3fb0\",\"vmname\":\"apb-cent32-bld\",\"vmdisplayname\":\"apb-cent32-bld\",\"vmstate\":\"Stopped\",\"size\":139264,\"created\":\"2013-04-16T16:25:57-0700\",\"state\":\"Ready\",\"account\":\"andrew\",\"domainid\":\"41a4917b-7952-499d-ba7f-4c57464d3dc8\",\"domain\":\"ROOT\",\"storagetype\":\"local\",\"hypervisor\":\"KVM\",\"storage\":\"c2422.halxg.cloudera.com\",\"destroyed\":false,\"serviceofferingid\":\"7cc4f8c3-7c56-4155-9916-9f42072ea712\",\"serviceofferingname\":\"Tiny\",\"serviceofferingdisplaytext\":\"Tiny (1 core, 1GB RAM)\",\"isextractable\":false} ] } }\n"
  },
  {
    "path": "apis/cloudstack/src/test/resources/listzonesresponse.json",
    "content": "{ \"listzonesresponse\": {\n    \"zone\": [\n        {\n            \"id\": 1,\n            \"name\": \"San Jose 1\",\n            \"networktype\": \"Advanced\",\n            \"securitygroupsenabled\": false,\n            \"tags\": []\n        },\n        {\n            \"id\": 2,\n            \"name\": \"Chicago\",\n            \"networktype\": \"Advanced\",\n            \"securitygroupsenabled\": true,\n            \"tags\": [\n                {\n                    \"account\": 1,\n                    \"domain\": \"ROOT\",\n                    \"domainid\": 1,\n                    \"key\": \"some-tag\",\n                    \"resourceid\": 2,\n                    \"resourcetype\": \"Zone\",\n                    \"value\": \"some-value\"\n                }\n            ]\n\n        }\n    ]\n} }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/listzonesresponse_single.json",
    "content": "{ \"listzonesresponse\" : { \"zone\" : [  {\"id\":2,\"name\":\"Chicago\",\"networktype\":\"Advanced\",\"securitygroupsenabled\":true} ] } }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/loginresponse.json",
    "content": "{ \"loginresponse\" : { \"timeout\" : \"1800\", \"lastname\" : \"Kiran\", \"registered\" : \"false\", \"username\" : \"jclouds\", \"firstname\" : \"Vijay\", \"domainid\" : \"11\", \"type\" : \"2\", \"userid\" : \"19\", \"sessionkey\" : \"uYT4/MNiglgAKiZRQkvV8QP8gn0=\", \"account\" : \"jclouds\" } }\n"
  },
  {
    "path": "apis/cloudstack/src/test/resources/logoutresponse.json",
    "content": "{ \"logoutresponse\" : { \"description\" : \"success\" } }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/preparehostformaintenanceresponse.json",
    "content": "{ \"preparehostformaintenanceresponse\" : {\"warning\":\"this test data is fabricated\",\"jobid\":2036,\"id\":2017} }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/queryasyncjobresultresponse-authorizeingress.json",
    "content": "{\n    \"queryasyncjobresultresponse\": {\n        \"accountid\": 3,\n        \"userid\": 3,\n        \"cmd\": \"com.cloud.api.commands.AuthorizeSecurityGroupIngressCmd\",\n        \"jobstatus\": 1,\n        \"jobprocstatus\": 0,\n        \"jobresultcode\": 0,\n        \"jobresulttype\": \"object\",\n        \"jobresult\": {\n            \"securitygroup\": {\n                \"id\": \"30\",\n                \"name\": \"jclouds-test\",\n                \"account\": \"adrian\",\n                \"domainid\": \"1\",\n                \"domain\": \"ROOT\",\n                \"ingressrule\": [\n                    {\n                        \"ruleid\": \"35bb2ad4-e0cb-48a0-9534-fc4a067b5665\",\n                        \"protocol\": \"tcp\",\n                        \"startport\": 22,\n                        \"endport\": 22,\n                        \"cidr\": \"0.0.0.0/0\"\n                    }\n                ],\n                \"egressrule\": [\n                    \n                ]\n            }\n        },\n        \"jobid\": \"13330fc9-8b3e-4582-aa3e-90883c041010\",\n        \"created\": \"2013-06-04T14:37:26-0700\"\n    }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/resources/queryasyncjobresultresponse-createtemplate-imageextension.json",
    "content": "{ \"queryasyncjobresultresponse\" :\n{\"accountid\":\"ee092437-d681-499e-b78b-f4e449128247\",\"userid\":\"0c9608c8-188c-47df-a934-d66dc96b96e3\",\"cmd\":\"com.cloud.api.commands.CreateTemplateCmd\",\"jobstatus\":1,\"jobprocstatus\":0,\"jobresultcode\":0,\"jobresulttype\":\"object\",\"jobresult\":{\"template\":{\"id\":\"3dc6ce25-a6cf-4d60-a664-3499993b511b\",\"name\":\"temp-template-ignore\",\"displaytext\":\"temp-template-ignore\",\"ispublic\":false,\"created\":\"2013-06-21T12:37:01-0700\",\"isready\":true,\"passwordenabled\":false,\"format\":\"QCOW2\",\"isfeatured\":false,\"crossZones\":false,\"ostypeid\":\"be820210-c741-4c36-9ba1-f38363bd37d5\",\"ostypename\":\"CentOS 5.6 (32-bit)\",\"account\":\"andrew\",\"zoneid\":\"1\",\"zonename\":\"San Jose 1\",\"status\":\"Download Complete\",\"size\":26843545600,\"templatetype\":\"USER\",\"hypervisor\":\"KVM\",\"domain\":\"ROOT\",\"domainid\":\"41a4917b-7952-499d-ba7f-4c57464d3dc8\",\"isextractable\":false,\"checksum\":\"6dd5d7f073ff951b033a8cadb877bde2\",\"sourcetemplateid\":\"9d597afb-4d3d-4a69-bf45-f95b0d1ee160\"}},\"created\":\"2013-06-21T12:31:33-0700\",\"jobid\":\"4e345230-8fcc-48a3-8a37-c5fe960df671\"} }\n"
  },
  {
    "path": "apis/cloudstack/src/test/resources/queryasyncjobresultresponse-createtemplate.json",
    "content": "{ \"queryasyncjobresultresponse\" : {\"jobid\":2716,\"jobstatus\":1,\"jobprocstatus\":0,\"jobresultcode\":0,\"jobresulttype\":\"object\",\"jobresult\":{\"template\":{\"id\":249,\"name\":\"jclouds-c5c7dce0\",\"displaytext\":\"jclouds live testCreateTemplate\",\"ispublic\":false,\"created\":\"2011-11-16T06:43:00-0800\",\"isready\":true,\"passwordenabled\":false,\"format\":\"VHD\",\"isfeatured\":false,\"crossZones\":false,\"ostypeid\":12,\"ostypename\":\"CentOS 5.3 (64-bit)\",\"account\":\"jcloud2\",\"zoneid\":1,\"zonename\":\"Demo5\",\"status\":\"Download Complete\",\"size\":8589934592,\"templatetype\":\"USER\",\"hypervisor\":\"XenServer\",\"domain\":\"jCloud\",\"domainid\":11,\"isextractable\":true,\"checksum\":\"bdc1c2c49b747694f97be5042323a1fa\",\"sourcetemplateid\":202}}} }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/queryasyncjobresultresponse-createvolume.json",
    "content": "{\n   \"queryasyncjobresultresponse\" : \n      {\"accountid\":\"43e3d66f-c8a3-43b2-a3d0-3bbc2416da14\",\n      \"userid\":\"99458e63-725b-48ec-aedc-f8ccc11f5231\",\n      \"cmd\":\"com.cloud.api.commands.CreateVolumeCmd\",\n      \"jobstatus\":1,\n      \"jobprocstatus\":0,\n      \"jobresultcode\":0,\n      \"jobresulttype\":\"object\",\n      \"jobresult\":{\n         \"volume\":{\n            \"id\":\"f947c7b3-e079-4e7d-aacc-1509d1ae387a\",\n            \"name\":\"VolumeApiExpectTest-jclouds-volume\",\n            \"zoneid\":\"6f9a2921-b22a-4149-8b71-6ffc275a2177\",\n            \"zonename\":\"Basic1\",\n            \"type\":\"DATADISK\",\n            \"size\":1073741824,\n            \"created\":\"2013-02-05T13:41:14+0200\",\n            \"state\":\"Allocated\",\n            \"account\":\"admin\",\n            \"domainid\":\"99f4159b-c698-4bd9-b8c5-5ac462f101eb\",\n            \"domain\":\"ROOT\",\n            \"storagetype\":\"shared\",\n            \"hypervisor\":\"None\",\n            \"diskofferingid\":\"0473f5dd-bca5-4af4-a9b6-db9e8a88a2f6\",\n            \"diskofferingname\":\"Custom\",\n            \"diskofferingdisplaytext\":\"Custom Disk\",\n            \"storage\":\"none\",\"destroyed\":false,\n            \"isextractable\":true,\n            \"tags\":[]\n         }\n      },\n      \"created\":\"2013-02-05T13:41:14+0200\",\n      \"jobid\":\"4ec82395-365a-4dad-8bd7-238c4f388702\"\n   }\n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/resources/queryasyncjobresultresponse-extracttemplate.json",
    "content": "{ \"queryasyncjobresultresponse\" : {\"jobid\":2720,\"jobstatus\":1,\"jobprocstatus\":0,\"jobresultcode\":0,\"jobresulttype\":\"object\",\"jobresult\":{\"template\":{\"id\":249,\"name\":\"jclouds-c5c7dce0\",\"extractId\":6,\"accountid\":19,\"state\":\"DOWNLOAD_URL_CREATED\",\"zoneid\":1,\"zonename\":\"Demo5\",\"extractMode\":\"HTTP_DOWNLOAD\",\"url\":\"https:%2F%2F72-52-126-96.realhostip.com%2Fuserdata%2Ff52f8e7d-7c89-4cf7-8e5a-b5ea17366d73.vhd\"}}} }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/queryasyncjobresultresponse-ipaddress.json",
    "content": "{ \"queryasyncjobresultresponse\" : {\"jobid\":860,\"jobstatus\":1,\"jobprocstatus\":0,\"jobresultcode\":0,\"jobresulttype\":\"object\",\"jobresult\":{\"ipaddress\":{\"id\":6,\"ipaddress\":\"72.52.126.35\",\"allocated\":\"2011-02-23T20:15:01-0800\",\"zoneid\":1,\"zonename\":\"San Jose 1\",\"issourcenat\":false,\"account\":\"adrian\",\"domainid\":1,\"domain\":\"ROOT\",\"forvirtualnetwork\":true,\"isstaticnat\":false,\"associatednetworkid\":204,\"networkid\":200,\"state\":\"Allocating\"}}} }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/queryasyncjobresultresponse-ipforwardingrule.json",
    "content": "{ \"queryasyncjobresultresponse\" : {\"jobid\":1133,\"jobstatus\":1,\"jobprocstatus\":0,\"jobresultcode\":0,\"jobresulttype\":\"object\",\"jobresult\":{\"ipforwardingrule\":{\"id\":109,\"protocol\":\"tcp\",\"virtualmachineid\":226,\"virtualmachinename\":\"i-3-226-VM\",\"ipaddressid\":36,\"ipaddress\":\"72.52.126.65\",\"startport\":22,\"endport\":22,\"state\":\"Active\"}}} }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/queryasyncjobresultresponse-stopvirtualmachine-imageextension.json",
    "content": "{ \"queryasyncjobresultresponse\" :\n{\"accountid\":\"ee092437-d681-499e-b78b-f4e449128247\",\"userid\":\"0c9608c8-188c-47df-a934-d66dc96b96e3\",\"cmd\":\"com.cloud.api.commands.StopVMCmd\",\"jobstatus\":1,\"jobprocstatus\":0,\"jobresultcode\":0,\"jobresulttype\":\"object\",\"jobresult\":{\"virtualmachine\":{\"id\":\"3239ade9-fd25-405c-8eda-59f0313a3fb0\",\"name\":\"apb-cent32-bld\",\"displayname\":\"apb-cent32-bld\",\"account\":\"andrew\",\"domainid\":\"41a4917b-7952-499d-ba7f-4c57464d3dc8\",\"domain\":\"ROOT\",\"created\":\"2013-04-16T16:25:57-0700\",\"state\":\"Stopped\",\"haenable\":false,\"zoneid\":\"1\",\"zonename\":\"San Jose 1\",\"hostid\":\"0\",\"templateid\":\"9d597afb-4d3d-4a69-bf45-f95b0d1ee160\",\"templatename\":\"centos-6.2-x32-template\",\"templatedisplaytext\":\"CentOS 6.2 x32 Template\",\"passwordenabled\":false,\"serviceofferingid\":\"7cc4f8c3-7c56-4155-9916-9f42072ea712\",\"serviceofferingname\":\"Tiny\",\"cpunumber\":1,\"cpuspeed\":1600,\"memory\":1024,\"cpuused\":\"-65.18%\",\"networkkbsread\":319420,\"networkkbswrite\":3,\"guestosid\":\"45de18f1-87c6-4646-8099-95c61f2a300a\",\"rootdeviceid\":0,\"rootdevicetype\":\"Filesystem\",\"securitygroup\":[{\"id\":\"50288900-28eb-4d7f-9c33-e4c26e3b66d2\",\"name\":\"default\",\"description\":\"Default Security Group\"}],\"nic\":[{\"id\":\"fd65b6fd-2c3e-4c8a-a0bc-6a5db4e8007a\",\"networkid\":\"0c82cd9f-ca64-4df4-9300-b33d81562403\",\"netmask\":\"255.255.254.0\",\"gateway\":\"10.20.92.3\",\"ipaddress\":\"10.20.92.96\",\"traffictype\":\"Guest\",\"type\":\"Shared\",\"isdefault\":true,\"macaddress\":\"06:ec:68:00:0f:04\"}],\"hypervisor\":\"KVM\",\"instancename\":\"i-4-69942-VM\"}},\"created\":\"2013-06-21T12:49:59-0700\",\"jobid\":\"a7d5127b-24a2-4a44-a4a7-25a6d057b453\"} }\n"
  },
  {
    "path": "apis/cloudstack/src/test/resources/queryasyncjobresultresponse-virtualmachine-securitygroup.json",
    "content": "{\n    \"queryasyncjobresultresponse\": {\n            \"jobid\": 50006,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.DeployVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 1234,\n                    \"name\": \"i-3-218-VM\",\n                    \"displayname\": \"i-3-218-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T08:39:10-0800\",\n                    \"state\": \"Running\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [\n                        {\n                            \"id\": \"30\",\n                            \"name\": \"jclouds-test\",\n                            \"account\": \"adrian\",\n                            \"domainid\": \"1\",\n                            \"domain\": \"ROOT\",\n                            \"ingressrule\": [\n                                {\n                                    \"ruleid\": \"35bb2ad4-e0cb-48a0-9534-fc4a067b5665\",\n                                    \"protocol\": \"tcp\",\n                                    \"startport\": 22,\n                                    \"endport\": 22,\n                                    \"cidr\": \"0.0.0.0/0\"\n                                }\n                            ],\n                            \"egressrule\": [\n                                \n                            ]\n                        }\n                    ],\n                    \"password\": \"dD7jwajkh\",\n                    \"nic\": [{\n                        \"id\": 250,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.195\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T08:39:10-0800\"\n        }\n    \n}\n"
  },
  {
    "path": "apis/cloudstack/src/test/resources/queryasyncjobresultresponse-virtualmachine.json",
    "content": "{\n    \"queryasyncjobresultresponse\": {\n            \"jobid\": 50006,\n            \"accountid\": 3,\n            \"userid\": 3,\n            \"cmd\": \"com.cloud.api.commands.DeployVMCmd\",\n            \"jobstatus\": 1,\n            \"jobprocstatus\": 0,\n            \"jobresultcode\": 0,\n            \"jobresult\": {\n                \"virtualmachine\": {\n                    \"id\": 1234,\n                    \"name\": \"i-3-218-VM\",\n                    \"displayname\": \"i-3-218-VM\",\n                    \"account\": \"adrian\",\n                    \"domainid\": 1,\n                    \"domain\": \"ROOT\",\n                    \"created\": \"2011-02-27T08:39:10-0800\",\n                    \"state\": \"Running\",\n                    \"haenable\": false,\n                    \"zoneid\": 1,\n                    \"zonename\": \"San Jose 1\",\n                    \"templateid\": 203,\n                    \"templatename\": \"Centos 5.3 Password Managed\",\n                    \"templatedisplaytext\": \"Centos 5.3 Password Managed\",\n                    \"passwordenabled\": true,\n                    \"serviceofferingid\": 1,\n                    \"serviceofferingname\": \"Small Instance\",\n                    \"cpunumber\": 1,\n                    \"cpuspeed\": 500,\n                    \"memory\": 512,\n                    \"guestosid\": 12,\n                    \"rootdeviceid\": 0,\n                    \"rootdevicetype\": \"NetworkFilesystem\",\n                    \"securitygroup\": [],\n                    \"password\": \"dD7jwajkh\",\n                    \"nic\": [{\n                        \"id\": 250,\n                        \"networkid\": 204,\n                        \"netmask\": \"255.255.255.0\",\n                        \"gateway\": \"10.1.1.1\",\n                        \"ipaddress\": \"10.1.1.195\",\n                        \"traffictype\": \"Guest\",\n                        \"type\": \"Virtual\",\n                        \"isdefault\": true\n                    }],\n                    \"hypervisor\": \"XenServer\"\n                }\n            },\n            \"created\": \"2011-02-27T08:39:10-0800\"\n        }\n    \n}"
  },
  {
    "path": "apis/cloudstack/src/test/resources/reconnecthostresponse.json",
    "content": "{ \"reconnecthostresponse\" : {\"warning\":\"this test data is fabricated\",\"jobid\":2036,\"id\":2017} }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/registerisoresponse.json",
    "content": "{ \"registerisoresponse\" : { \"count\":1 ,\"iso\" : [  \n{\"id\":\"b52c509d-c6e2-452c-b6ec-aa00720ed6cd\",\"name\":\"ubuntu10.10\",\"displaytext\":\"ubuntu 10.10 (32 bit)\",\"ispublic\":true,\"created\":\"2012-08-21T15:45:01+0530\",\"isready\":false,\"bootable\":true,\"isfeatured\":false,\"crossZones\":false,\"ostypeid\":\"0e0335d9-b6cc-4808-bddf-0828e66a0d03\",\"ostypename\":\"Ubuntu 10.10 (32-bit)\",\"account\":\"admin\",\"zoneid\":\"6f9a2921-b22a-4149-8b71-6ffc275a2177\",\"zonename\":\"Basic1\",\"status\":\"\",\"domain\":\"ROOT\",\"domainid\":\"99f4159b-c698-4bd9-b8c5-5ac462f101eb\",\"isextractable\":false} ] \n}}\n"
  },
  {
    "path": "apis/cloudstack/src/test/resources/registersshkeypairresponse.json",
    "content": "{ \"registersshkeypairresponse\" :  { \"keypair\" :\n   {\"name\":\"jclouds-keypair\",\"fingerprint\":\"8f:f1:91:2d:b1:a8:51:f1:79:cf:c4:31:c4:14:9d:81\"} }  }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/registeruserkeysresponse.json",
    "content": "{ \"registeruserkeysresponse\" :  { \"userkeys\" : {\"apikey\":\"5nn6IAQ-0BYuAKTu45rf49VsyX0rg9t48TpY8NKsduE5t-_1_g_AU8ZjP3OJvVdlzWKL3Lgfa6_nkC9hU6NyQQ\",\"secretkey\":\"GSCDYzj65CiSkxzCJxlFvcF52qglM7HbuG6QL7zYVeWVhVO8GnW85wGTBBuZ3xpzEN_UfKnsORvrNszYQ1ofAw\"} }  }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/revokesecuritygroupingressresponse.json",
    "content": " { \"revokesecuritygroupingressresponse\" :\n {\"jobid\":\"13330fc9-8b3e-4582-aa3e-90883c041010\"} }\n"
  },
  {
    "path": "apis/cloudstack/src/test/resources/stopvirtualmachineresponse-imageextension.json",
    "content": "{ \"stopvirtualmachineresponse\" : {\"jobid\":\"a7d5127b-24a2-4a44-a4a7-25a6d057b453\"} }\n"
  },
  {
    "path": "apis/cloudstack/src/test/resources/updateclusterresponse.json",
    "content": "{ \"updateclusterresponse\" : { \"cluster\" : {\"warning\":\"this test data is fabricated\",\"id\":1,\"name\":\"Xen Clust 1\",\"podid\":1,\"podname\":\"Dev Pod 1\",\"zoneid\":1,\"zonename\":\"Dev Zone 1\",\"hypervisortype\":\"XenServer\",\"clustertype\":\"CloudManaged\",\"allocationstate\":\"Enabled\",\"managedstate\":\"Managed\"} } }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/updateconfigurationsresponse.json",
    "content": "{ \"updateconfigurationresponse\" :  { \"configuration\" :\n    {\"category\":\"Advanced\",\"name\":\"expunge.delay\",\"value\":\"11\",\"description\":\"Determines how long (in seconds) to wait before actually expunging destroyed vm. The default value = the default value of expunge.interval\"} }  }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/updatedomainresponse.json",
    "content": "{ \"updatedomainresponse\" :  { \"domain\" :\n    {\"id\":10,\"name\":\"test-2\",\"level\":1,\"parentdomainid\":1,\"parentdomainname\":\"ROOT\",\"haschild\":false} }  }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/updatehostresponse.json",
    "content": "{ \"updatehostresponse\" : { \"host\" :\n    {\"warning\":\"This test data is fabricated\",\"id\":1,\"name\":\"cs2-xevsrv.alucloud.local\",\"state\":\"Up\",\"type\":\"Routing\",\"ipaddress\":\"10.26.26.107\",\"zoneid\":1,\"zonename\":\"Dev Zone 1\",\"podid\":1,\"podname\":\"Dev Pod 1\",\"version\":\"2.2.12.20110928142833\",\"hypervisor\":\"XenServer\",\"cpunumber\":24,\"cpuspeed\":2266,\"cpuallocated\":\"2.76%\",\"cpuused\":\"0.1%\",\"cpuwithoverprovisioning\":\"54384.0\",\"networkkbsread\":4443,\"networkkbswrite\":15048,\"memorytotal\":100549733760,\"memoryallocated\":3623878656,\"memoryused\":3623878656,\"capabilities\":\"xen-3.0-x86_64 , xen-3.0-x86_32p , hvm-3.0-x86_32 , hvm-3.0-x86_32p , hvm-3.0-x86_64\",\"lastpinged\":\"1970-01-16T00:54:43+0200\",\"managementserverid\":223098941760041,\"clusterid\":1,\"clustername\":\"Xen Clust 1\",\"clustertype\":\"CloudManaged\",\"islocalstorageactive\":false,\"created\":\"2011-11-26T23:28:36+0200\",\"events\":\"PrepareUnmanaged; HypervisorVersionChanged; ManagementServerDown; PingTimeout; AgentDisconnected; MaintenanceRequested; HostDown; AgentConnected; StartAgentRebalance; ShutdownRequested; Ping\",\"hosttags\":\"\",\"hasEnoughCapacity\":false,\"allocationstate\":\"Enabled\"} } }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/updatepodresponse.json",
    "content": "{ \"updatepodresponse\" :  { \"pod\" : {\"id\":7,\"name\":\"richard-updatedpod\",\"zoneid\":11,\"zonename\":\"richard-zone\",\"gateway\":\"172.21.0.254\",\"netmask\":\"255.255.255.128\",\"startip\":\"172.21.0.129\",\"endip\":\"172.21.0.250\",\"allocationstate\":\"Disabled\"} }  }"
  },
  {
    "path": "apis/cloudstack/src/test/resources/updatezoneresponse.json",
    "content": "{ \"updatezoneresponse\" :  { \"zone\" :\n    {\"id\":6,\"name\":\"test-zone\",\"dns1\":\"8.8.8.8\",\"internaldns1\":\"10.10.10.10\",\"networktype\":\"Basic\",\n        \"securitygroupsenabled\":true,\"allocationstate\":\"Enabled\",\"zonetoken\":\"7b6e27df-30a6-3024-9d8b-7971a3127f64\",\n        \"dhcpprovider\":\"DhcpServer\"} }  }"
  },
  {
    "path": "apis/cloudwatch/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.cloudwatch.*;version=\"${project.version}\";-noimport:=true"
  },
  {
    "path": "apis/cloudwatch/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.api</groupId>\n  <artifactId>cloudwatch</artifactId>\n  <name>jclouds cloudwatch api</name>\n  <description>jclouds components to access an implementation of CloudWatch</description>\n\n  <properties>\n    <test.cloudwatch.endpoint>https://monitoring.us-east-1.amazonaws.com</test.cloudwatch.endpoint>\n    <test.cloudwatch.api-version>2010-08-01</test.cloudwatch.api-version>\n    <test.cloudwatch.build-version />\n    <test.cloudwatch.identity>${test.aws.identity}</test.cloudwatch.identity>\n    <test.cloudwatch.credential>${test.aws.credential}</test.cloudwatch.credential>\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>sts</artifactId>\n      <version>${project.version}</version>\n      <type>jar</type>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-log4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.logging.log4j</groupId>\n      <artifactId>log4j-core</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.cloudwatch.endpoint>${test.cloudwatch.endpoint}</test.cloudwatch.endpoint>\n                    <test.cloudwatch.api-version>${test.cloudwatch.api-version}</test.cloudwatch.api-version>\n                    <test.cloudwatch.build-version>${test.cloudwatch.build-version}</test.cloudwatch.build-version>\n                    <test.cloudwatch.identity>${test.cloudwatch.identity}</test.cloudwatch.identity>\n                    <test.cloudwatch.credential>${test.cloudwatch.credential}</test.cloudwatch.credential>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/CloudWatch.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch;\n\nimport java.util.List;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.Iterables;\nimport org.jclouds.cloudwatch.domain.Metric;\nimport org.jclouds.cloudwatch.domain.MetricDatum;\nimport org.jclouds.cloudwatch.features.MetricApi;\nimport org.jclouds.cloudwatch.options.ListMetricsOptions;\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.PagedIterables;\n\n/**\n * Utilities for using CloudWatch.\n */\npublic class CloudWatch {\n\n   /**\n    * List metrics based on the criteria in the {@link ListMetricsOptions} passed in.\n    *\n    * @param metricApi the {@link MetricApi} to use for the request\n    * @param options the {@link ListMetricsOptions} describing the ListMetrics request\n    *\n    * @return iterable of metrics fitting the criteria\n    */\n   public static Iterable<Metric> listMetrics(final MetricApi metricApi, final ListMetricsOptions options) {\n      return Iterables.concat(PagedIterables.advance(metricApi.list(options),\n               new Function<Object, IterableWithMarker<Metric>>() {\n\n                  @Override\n                  public IterableWithMarker<Metric> apply(Object input) {\n                     return metricApi.list(options.clone().afterMarker(input));\n                  }\n\n                  @Override\n                  public String toString() {\n                     return \"listMetrics(\" + options + \")\";\n                  }\n               }));\n   }\n\n   /**\n    * List metrics based on the criteria in the {@link ListMetricsOptions} passed in.\n    *\n    * @param cloudWatchApi the {@link CloudWatchApi} to use for the request\n    * @param region the region to list metrics in\n    * @param options the options describing the ListMetrics request\n    *\n    * @return iterable of metrics fitting the criteria\n    */\n   public static Iterable<Metric> listMetrics(CloudWatchApi cloudWatchApi, String region,\n            final ListMetricsOptions options) {\n      return listMetrics(cloudWatchApi.getMetricApiForRegion(region), options);\n   }\n\n   /**\n    * Pushes metrics to CloudWatch.\n    *\n    * @param cloudWatchApi the {@link CloudWatchApi} to use for the request\n    * @param region the region to put the metrics in\n    * @param metrics the metrics to publish\n    * @param namespace the namespace to publish the metrics in\n    */\n   public static void putMetricData(CloudWatchApi cloudWatchApi, String region, Iterable<MetricDatum> metrics,\n            String namespace) {\n      MetricApi metricApi = cloudWatchApi.getMetricApiForRegion(region);\n\n      for (List<MetricDatum> slice : Iterables.partition(metrics, 10)) {\n         metricApi.putMetricsInNamespace(slice, namespace);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/CloudWatchApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch;\n\nimport java.io.Closeable;\nimport java.util.Set;\n\nimport com.google.inject.Provides;\nimport org.jclouds.cloudwatch.features.AlarmApi;\nimport org.jclouds.cloudwatch.features.MetricApi;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.location.Region;\nimport org.jclouds.location.functions.RegionToEndpointOrProviderIfNull;\nimport org.jclouds.rest.annotations.Delegate;\nimport org.jclouds.rest.annotations.EndpointParam;\n/**\n * Provides access to Amazon CloudWatch via the Query API\n * <p/>\n * \n * @see <a\n *      href=\"http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference\"\n *      />\n */\npublic interface CloudWatchApi extends Closeable {\n   /**\n    * \n    * @return the Region codes configured\n    */\n   @Provides\n   @Region\n   Set<String> getConfiguredRegions();\n\n   /**\n    * Provides synchronous access to Metric features.\n    */\n   @Delegate\n   MetricApi getMetricApi();\n   \n   /**\n    * Provides synchronous access to Metric features.\n    */\n   @Delegate\n   MetricApi getMetricApiForRegion(@EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region);\n\n   /**\n    * Provides synchronous access to Alarm features.\n    */\n   @Delegate\n   AlarmApi getAlarmApi();\n\n   /**\n    * Provides synchronous access to Alarm features.\n    */\n   @Delegate\n   AlarmApi getAlarmApiForRegion(@EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region);\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/CloudWatchApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch;\n\nimport static org.jclouds.aws.reference.AWSConstants.PROPERTY_AUTH_TAG;\nimport static org.jclouds.aws.reference.AWSConstants.PROPERTY_HEADER_TAG;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.cloudwatch.config.CloudWatchHttpApiModule;\nimport org.jclouds.rest.internal.BaseHttpApiMetadata;\n\nimport com.google.auto.service.AutoService;\n\n/**\n * Implementation of {@link ApiMetadata} for Amazon's CloudWatch api.\n */\n@AutoService(ApiMetadata.class)\npublic class CloudWatchApiMetadata extends BaseHttpApiMetadata {\n\n\n   @Override\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromApiMetadata(this);\n   }\n\n   public CloudWatchApiMetadata() {\n      this(new ConcreteBuilder());\n   }\n\n   protected CloudWatchApiMetadata(Builder<?> builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = BaseHttpApiMetadata.defaultProperties();\n      properties.setProperty(PROPERTY_AUTH_TAG, \"AWS\");\n      properties.setProperty(PROPERTY_HEADER_TAG, \"amz\");\n      return properties;\n   }\n\n   public abstract static class Builder<T extends Builder<T>> extends BaseHttpApiMetadata.Builder<CloudWatchApi, T> {\n\n      protected Builder() {\n         id(\"cloudwatch\")\n         .name(\"Amazon CloudWatch Api\")\n         .identityName(\"Access Key ID\")\n         .credentialName(\"Secret Access Key\")\n         .version(\"2010-08-01\")\n         .documentation(URI.create(\"http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference/\"))\n         .defaultEndpoint(\"https://monitoring.us-east-1.amazonaws.com\")\n         .defaultProperties(CloudWatchApiMetadata.defaultProperties())\n         .defaultModule(CloudWatchHttpApiModule.class);\n      }\n\n      @Override\n      public CloudWatchApiMetadata build() {\n         return new CloudWatchApiMetadata(this);\n      }\n      \n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/binders/AlarmNamesBinder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.binders;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.collect.ImmutableMultimap;\nimport org.jclouds.http.HttpRequest;\n\n/**\n * Binds the alarm names request to the http request\n */\n@Beta\npublic class AlarmNamesBinder implements org.jclouds.rest.Binder {\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      Iterable<String> alarmNames = (Iterable<String>) checkNotNull(input, \"alarm names must be set\");\n      ImmutableMultimap.Builder<String, String> formParameters = ImmutableMultimap.builder();\n      int alarmNameIndex = 1;\n\n      for (String alarmName : alarmNames) {\n         formParameters.put(\"AlarmNames.member.\" + alarmNameIndex, alarmName);\n         alarmNameIndex++;\n      }\n\n      return (R) request.toBuilder().replaceFormParams(formParameters.build()).build();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/binders/GetMetricStatisticsBinder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.binders;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.cloudwatch.domain.Dimension;\nimport org.jclouds.cloudwatch.domain.GetMetricStatistics;\nimport org.jclouds.cloudwatch.domain.Statistics;\nimport org.jclouds.date.DateService;\nimport org.jclouds.http.HttpRequest;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.collect.ImmutableMultimap;\n\n/**\n * Binds the metrics request to the http request\n * \n * @see <a href=\"http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference/API_GetMetricStatistics.html\"\n *      />\n */\n@Beta\npublic class GetMetricStatisticsBinder implements org.jclouds.rest.Binder {\n\n   private final DateService dateService;\n   \n   @Inject\n   protected GetMetricStatisticsBinder(DateService dateService) {\n      this.dateService = dateService;\n   }\n   \n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object payload) {\n      GetMetricStatistics getRequest = GetMetricStatistics.class.cast(checkNotNull(payload,\n               \"GetMetricStatistics must be set!\"));\n      int dimensionIndex = 1;\n      int statisticIndex = 1;\n      ImmutableMultimap.Builder<String, String> formParameters = ImmutableMultimap.builder();\n\n      for (Dimension dimension : getRequest.getDimensions()) {\n         formParameters.put(\"Dimensions.member.\" + dimensionIndex + \".Name\", dimension.getName());\n         formParameters.put(\"Dimensions.member.\" + dimensionIndex + \".Value\", dimension.getValue());\n         dimensionIndex++;\n      }\n\n      if (getRequest.getEndTime().isPresent()) {\n         formParameters.put(\"EndTime\", dateService.iso8601SecondsDateFormat(getRequest.getEndTime().get()));\n      }\n      formParameters.put(\"MetricName\", getRequest.getMetricName());\n      formParameters.put(\"Namespace\", getRequest.getNamespace());\n      formParameters.put(\"Period\", Integer.toString(getRequest.getPeriod()));\n      if (getRequest.getStartTime().isPresent()) {\n         formParameters.put(\"StartTime\", dateService.iso8601SecondsDateFormat(getRequest\n                  .getStartTime().get()));\n      }\n      \n      for (Statistics statistic : getRequest.getStatistics()) {\n         formParameters.put(\"Statistics.member.\" + statisticIndex, statistic.toString());\n         statisticIndex++;\n      }\n\n      if (getRequest.getUnit().isPresent()) {\n         formParameters.put(\"Unit\", getRequest.getUnit().get().toString());\n      }\n\n      return (R) request.toBuilder().replaceFormParams(formParameters.build()).build();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/binders/MetricDataBinder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.binders;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.cloudwatch.domain.Dimension;\nimport org.jclouds.cloudwatch.domain.MetricDatum;\nimport org.jclouds.cloudwatch.domain.StatisticValues;\nimport org.jclouds.date.DateService;\nimport org.jclouds.http.HttpRequest;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.inject.Inject;\n\n/**\n * Binds the metrics request to the http request\n *\n * @see <a href=\"http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference/API_PutMetricData.html\" />\n */\n@Beta\npublic class MetricDataBinder implements org.jclouds.rest.Binder {\n\n   private final DateService dateService;\n\n   @Inject\n   protected MetricDataBinder(DateService dateService) {\n      this.dateService = dateService;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      Iterable<MetricDatum> metrics = (Iterable<MetricDatum>) checkNotNull(input, \"metrics must be set!\");\n      \n      ImmutableMultimap.Builder<String, String> formParameters = ImmutableMultimap.builder();\n      int metricDatumIndex = 1;\n\n      for (MetricDatum metricDatum : metrics) {\n         int dimensionIndex = 1;\n\n         for (Dimension dimension : metricDatum.getDimensions()) {\n            formParameters.put(\"MetricData.member.\" + metricDatumIndex + \".Dimensions.member.\" + dimensionIndex +\n                                     \".Name\", dimension.getName());\n            formParameters.put(\"MetricData.member.\" + metricDatumIndex + \".Dimensions.member.\" + dimensionIndex +\n                                     \".Value\", dimension.getValue());\n            dimensionIndex++;\n         }\n\n         formParameters.put(\"MetricData.member.\" + metricDatumIndex + \".MetricName\", metricDatum.getMetricName());\n\n\n         if (metricDatum.getStatisticValues().isPresent()) {\n            StatisticValues statisticValues = metricDatum.getStatisticValues().get();\n\n            formParameters.put(\"MetricData.member.\" + metricDatumIndex + \".StatisticValues.Maximum\",\n                               String.valueOf(statisticValues.getMaximum()));\n            formParameters.put(\"MetricData.member.\" + metricDatumIndex + \".StatisticValues.Minimum\",\n                               String.valueOf(statisticValues.getMinimum()));\n            formParameters.put(\"MetricData.member.\" + metricDatumIndex + \".StatisticValues.SampleCount\",\n                               String.valueOf(statisticValues.getSampleCount()));\n            formParameters.put(\"MetricData.member.\" + metricDatumIndex + \".StatisticValues.Sum\",\n                               String.valueOf(statisticValues.getSum()));\n         }\n         \n         if (metricDatum.getTimestamp().isPresent()) {\n            formParameters.put(\"MetricData.member.\" + metricDatumIndex + \".Timestamp\",\n                               dateService.iso8601SecondsDateFormat(metricDatum.getTimestamp().get()));\n         }\n\n         formParameters.put(\"MetricData.member.\" + metricDatumIndex + \".Unit\",\n                            String.valueOf(metricDatum.getUnit()));\n\n         if (metricDatum.getValue().isPresent()) {\n            formParameters.put(\"MetricData.member.\" + metricDatumIndex + \".Value\",\n                     String.valueOf(metricDatum.getValue().get()));\n         }\n\n         metricDatumIndex++;\n      }\n\n      return (R) request.toBuilder().replaceFormParams(formParameters.build()).build();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/config/CloudWatchHttpApiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.config;\n\nimport org.jclouds.aws.config.FormSigningHttpApiModule;\nimport org.jclouds.cloudwatch.CloudWatchApi;\nimport org.jclouds.cloudwatch.handlers.CloudWatchErrorHandler;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.annotation.ClientError;\nimport org.jclouds.http.annotation.ServerError;\nimport org.jclouds.rest.ConfiguresHttpApi;\n\n\n\n/**\n * Configures the Monitoring connection.\n */\n@ConfiguresHttpApi\npublic class CloudWatchHttpApiModule extends FormSigningHttpApiModule<CloudWatchApi> {\n   public CloudWatchHttpApiModule() {\n      super(CloudWatchApi.class);\n   }\n\n   @Override\n   protected void bindErrorHandlers() {\n      bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(CloudWatchErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(CloudWatchErrorHandler.class);\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/Alarm.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Date;\nimport java.util.Set;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Objects;\nimport com.google.common.base.Optional;\n\n/**\n * @see <a href=\"http://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_MetricAlarm.html\" />\n */\n@Beta\npublic class Alarm {\n\n   public static enum State {\n      ALARM,\n      INSUFFICIENT_DATA,\n      OK,\n      UNRECOGNIZED;\n\n      public static State fromValue(String value) {\n         try {\n            return State.valueOf(checkNotNull(value, \"value\"));\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n   }\n\n   private final boolean areActionsEnabled;\n   private final Set<String> alarmActions;\n   private final String alarmARN;\n   private final Date alarmConfigurationUpdatedTimestamp;\n   private final String alarmDescription;\n   private final String alarmName;\n   private final ComparisonOperator comparisonOperator;\n   private final Set<Dimension> dimensions;\n   private final int evaluationPeriods;\n   private final Set<String> insufficientDataActions;\n   private final String metricName;\n   private final String namespace;\n   private final Set<String> okActions;\n   private final int period;\n   private final String stateReason;\n   private final Optional<String> stateReasonData;\n   private final Date stateUpdatedTimestamp;\n   private final State state;\n   private final Statistics statistic;\n   private final double threshold;\n   private final Optional<Unit> unit;\n\n   public Alarm(boolean areActionsEnabled, Set<String> alarmActions, String alarmARN,\n                Date alarmConfigurationUpdatedTimestamp, String alarmDescription, String alarmName,\n                ComparisonOperator comparisonOperator, Set<Dimension> dimensions, int evaluationPeriods,\n                Set<String> insufficientDataActions, String metricName, String namespace, Set<String> okActions,\n                int period, String stateReason, Optional<String> stateReasonData, Date stateUpdatedTimestamp,\n                State state, Statistics statistic, double threshold, Optional<Unit> unit) {\n      this.alarmName = checkNotNull(alarmName, \"alarmName\");\n      this.areActionsEnabled = areActionsEnabled;\n      this.alarmActions = checkNotNull(alarmActions, \"alarmActions for %s\", alarmName);\n      this.alarmARN = checkNotNull(alarmARN, \"alarmArn for %s\", alarmName);\n      this.alarmConfigurationUpdatedTimestamp = checkNotNull(alarmConfigurationUpdatedTimestamp,\n                                                             \"alarmConfigurationUpdatedTimestamp for %s\", alarmName);\n      this.alarmDescription = checkNotNull(alarmDescription, \"alarmDescription for %s\", alarmName);\n      this.comparisonOperator = checkNotNull(comparisonOperator, \"comparisonOperator for %s\", alarmName);\n      checkArgument(comparisonOperator != ComparisonOperator.UNRECOGNIZED, \"comparisonOperator unrecognized\");\n      this.dimensions = checkNotNull(dimensions, \"dimensions for %s\", alarmName);\n      this.evaluationPeriods = evaluationPeriods;\n      this.insufficientDataActions = checkNotNull(insufficientDataActions, \"insufficientDataActions for %s\", alarmName);\n      this.metricName = checkNotNull(metricName, \"metricName for %s\", alarmName);\n      this.namespace = checkNotNull(namespace, \"namespace for %s\", alarmName);\n      this.okActions = checkNotNull(okActions, \"okActions for %s\", alarmName);\n      this.period = period;\n      this.stateReason = checkNotNull(stateReason, \"stateReason for %s\", alarmName);\n      this.stateReasonData = checkNotNull(stateReasonData, \"stateReasonData for %s\", alarmName);\n      this.stateUpdatedTimestamp = checkNotNull(stateUpdatedTimestamp, \"stateUpdatedTimestamp for %s\", alarmName);\n      this.state = checkNotNull(state, \"state for %s\", alarmName);\n      checkArgument(state != State.UNRECOGNIZED, \"state unrecognized\");\n      this.statistic = checkNotNull(statistic, \"statistic for %s\", alarmName);\n      checkArgument(statistic != Statistics.UNRECOGNIZED, \"statistic unrecognized\");\n      this.threshold = threshold;\n      this.unit = checkNotNull(unit, \"unit for %s\", alarmName);\n      if (unit.isPresent()) {\n         checkArgument(unit.get() != Unit.UNRECOGNIZED, \"unit unrecognized\");\n      }\n   }\n\n   /**\n    * return whether actions are enabled if the alarm state changes\n    */\n   public boolean areActionsEnabled() {\n      return areActionsEnabled;\n   }\n\n   /**\n    * return list of actions to perform when the alarm state changes to {@link org.jclouds.cloudwatch.domain.Alarm.State#ALARM} from any other state\n    */\n   public Set<String> getAlarmActions() {\n      return alarmActions;\n   }\n\n   /**\n    * return the Amazon Resource Name (ARN) of the alarm\n    */\n   public String getAlarmARN() {\n      return alarmARN;\n   }\n\n   /**\n    * return the date timestamp of when the alarm was last updated\n    */\n   public Date getAlarmConfigurationUpdatedTimestamp() {\n      return alarmConfigurationUpdatedTimestamp;\n   }\n\n   /**\n    * return the description of the alarm\n    */\n   public String getAlarmDescription() {\n      return alarmDescription;\n   }\n\n   /**\n    * return the name of the alarm\n    */\n   public String getAlarmName() {\n      return alarmName;\n   }\n\n   /**\n    * return the arithmetic operation to use when comparing the specified statistic and threshold\n    */\n   public ComparisonOperator getComparisonOperator() {\n      return comparisonOperator;\n   }\n\n   /**\n    * return the list of dimensions associated with the alarm's associated metric\n    */\n   public Set<Dimension> getDimensions() {\n      return dimensions;\n   }\n\n   /**\n    * return the number of periods over which data is compared to the specified threshold\n    */\n   public int getEvaluationPeriods() {\n      return evaluationPeriods;\n   }\n\n   /**\n    * return the list of actions to execute when this alarm transitions into an {@link org.jclouds.cloudwatch.domain.Alarm.State#INSUFFICIENT_DATA} state\n    * from any other state\n    */\n   public Set<String> getInsufficientDataActions() {\n      return insufficientDataActions;\n   }\n\n   /**\n    * return the name of the alarm's metric\n    */\n   public String getMetricName() {\n      return metricName;\n   }\n\n   /**\n    * return the namespace of alarm's associated metric\n    */\n   public String getNamespace() {\n      return namespace;\n   }\n\n   /**\n    * return the list of actions to execute when this alarm transitions into an {@link org.jclouds.cloudwatch.domain.Alarm.State#OK} state from any other\n    * state\n    */\n   public Set<String> getOkActions() {\n      return okActions;\n   }\n\n   /**\n    * return the period in seconds over which the statistic is applied\n    */\n   public int getPeriod() {\n      return period;\n   }\n\n   /**\n    * return the human-readable explanation for the alarm's state\n    */\n   public String getStateReason() {\n      return stateReason;\n   }\n\n   /**\n    * return the explanation for the alarm's state in machine-readable JSON format\n    */\n   public Optional<String> getStateReasonData() {\n      return stateReasonData;\n   }\n\n   /**\n    * return the time stamp of the last update to the alarm's state\n    */\n   public Date getStateUpdatedTimestamp() {\n      return stateUpdatedTimestamp;\n   }\n\n   /**\n    * return the state value for the alarm\n    */\n   public State getState() {\n      return state;\n   }\n\n   /**\n    * return the statistic to apply to the alarm's associated metric\n    */\n   public Statistics getStatistic() {\n      return statistic;\n   }\n\n   /**\n    * return the value against which the specified statistic is compared\n    */\n   public double getThreshold() {\n      return threshold;\n   }\n\n   /**\n    * return the unit of the alarm's associated metric\n    */\n   public Optional<Unit> getUnit() {\n      return unit;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(alarmActions, alarmARN, alarmConfigurationUpdatedTimestamp, alarmDescription, alarmName,\n                              areActionsEnabled, comparisonOperator, dimensions, evaluationPeriods,\n                              insufficientDataActions, metricName, namespace, okActions, period, stateReason,\n                              stateReasonData, stateUpdatedTimestamp, state, statistic, threshold, unit);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      Alarm other = (Alarm) obj;\n      return equal(this.alarmActions, other.alarmActions) &&\n            equal(this.alarmARN, other.alarmARN) &&\n            equal(this.alarmConfigurationUpdatedTimestamp, other.alarmConfigurationUpdatedTimestamp) &&\n            equal(this.alarmDescription, other.alarmDescription) &&\n            equal(this.alarmName, other.alarmName) &&\n            equal(this.areActionsEnabled, other.areActionsEnabled) &&\n            equal(this.comparisonOperator, other.comparisonOperator) &&\n            equal(this.dimensions, other.dimensions) &&\n            equal(this.evaluationPeriods, other.evaluationPeriods) &&\n            equal(this.insufficientDataActions, other.insufficientDataActions) &&\n            equal(this.metricName, other.metricName) &&\n            equal(this.namespace, other.namespace) &&\n            equal(this.okActions, other.okActions) &&\n            equal(this.period, other.period) &&\n            equal(this.stateReason, other.stateReason) &&\n            equal(this.stateReasonData, other.stateReasonData) &&\n            equal(this.stateUpdatedTimestamp, other.stateUpdatedTimestamp) &&\n            equal(this.state, other.state) &&\n            equal(this.statistic, other.statistic) &&\n            equal(this.threshold, other.threshold) &&\n            equal(this.unit, other.unit);\n   }\n\n   @Override\n   public String toString() {\n      return toStringHelper(this)\n                    .add(\"alarmActions\", alarmActions)\n                    .add(\"alarmARN\", alarmARN)\n                    .add(\"alarmConfigurationUpdateTimestamp\", alarmConfigurationUpdatedTimestamp)\n                    .add(\"alarmDescription\", alarmDescription)\n                    .add(\"alarmName\", alarmName)\n                    .add(\"areActionsEnabled\", areActionsEnabled)\n                    .add(\"comparisonOperator\", comparisonOperator)\n                    .add(\"dimensions\", dimensions)\n                    .add(\"evaluationPeriods\", evaluationPeriods)\n                    .add(\"insufficientDataActions\", insufficientDataActions)\n                    .add(\"metricName\", metricName)\n                    .add(\"namespace\", namespace)\n                    .add(\"okActions\", okActions)\n                    .add(\"period\", period)\n                    .add(\"stateReason\", stateReason)\n                    .add(\"stateReasonData\", stateReasonData.orNull())\n                    .add(\"stateUpdatedTimestamp\", stateUpdatedTimestamp)\n                    .add(\"state\", state)\n                    .add(\"statistic\", statistic)\n                    .add(\"threshold\", threshold)\n                    .add(\"unit\", unit.orNull()).toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/AlarmHistoryItem.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Date;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Objects;\n\n/**\n * @see <a href=\"http://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_AlarmHistoryItem.html\" />\n */\n@Beta\npublic class AlarmHistoryItem {\n\n   private final String alarmName;\n   private final String historyData;\n   private final HistoryItemType historyItemType;\n   private final String historySummary;\n   private final Date timestamp;\n\n   public AlarmHistoryItem(String alarmName, String historyData, HistoryItemType historyItemType,\n                           String historySummary, Date timestamp) {\n      this.alarmName = checkNotNull(alarmName, \"alarmName\");\n      this.historyData = checkNotNull(historyData, \"historyData for %s\", alarmName);\n      this.historyItemType = checkNotNull(historyItemType, \"historyItemType for %s\", alarmName);\n      this.historySummary = checkNotNull(historySummary, \"historySummary for %s\", alarmName);\n      this.timestamp = checkNotNull(timestamp, \"timestamp for %s\", alarmName);\n   }\n\n   /**\n    * return the descriptive name for the alarm\n    */\n   public String getAlarmName() {\n      return alarmName;\n   }\n\n   /**\n    * return the machine-readable data about the alarm in JSON format\n    */\n   public String getHistoryData() {\n      return historyData;\n   }\n\n   /**\n    * return the type of alarm history item\n    */\n   public HistoryItemType getHistoryItemType() {\n      return historyItemType;\n   }\n\n   /**\n    * return the human-readable summary of the alarm history\n    */\n   public String getHistorySummary() {\n      return historySummary;\n   }\n\n   /**\n    * return the time stamp for the alarm history item\n    */\n   public Date getTimestamp() {\n      return timestamp;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(alarmName, historyData, historyItemType, historySummary, timestamp);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      AlarmHistoryItem other = (AlarmHistoryItem) obj;\n      return equal(this.alarmName, other.alarmName) &&\n            equal(this.historyData, other.historyData) &&\n            equal(this.historyItemType, other.historyItemType) &&\n            equal(this.historySummary, other.historySummary) &&\n            equal(this.timestamp, other.timestamp);\n   }\n\n   @Override\n   public String toString() {\n      return toStringHelper(this)\n            .add(\"alarmName\", alarmName)\n            .add(\"historyData\", historyData)\n            .add(\"historyItemType\", historyItemType)\n            .add(\"historySummary\", historySummary)\n            .add(\"timestamp\", timestamp).toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/AutoScalingConstants.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.domain;\n\n/**\n * Constants interface for the AWS AutoScaling dimensions and metric names as of 2012-04-24.\n *\n * @see <a href=\"http://docs.amazonwebservices.com/AmazonCloudWatch/latest/DeveloperGuide/CW_Support_For_AWS.html#as-metricscollected\" />\n */\npublic final class AutoScalingConstants {\n\n   public static class Dimension {\n\n      public static final String AUTO_SCALING_GROUP_NAME = \"AutoScalingGroupName\";\n\n   }\n\n   public static class MetricName {\n\n      public static final String GROUP_DESIRED_CAPACITY = \"GroupDesiredCapacity\";\n      public static final String GROUP_IN_SERVICE_INSTANCES = \"GroupInServiceInstances\";\n      public static final String GROUP_MAX_SIZE = \"GroupMaxSize\";\n      public static final String GROUP_MIN_SIZE = \"GroupMinSize\";\n      public static final String GROUP_PENDING_INSTANCES = \"GroupPendingInstances\";\n      public static final String GROUP_TERMINATING_INSTANCES = \"GroupTerminatingInstances\";\n      public static final String GROUP_TOTAL_INSTANCES = \"GroupTotalInstances\";\n\n   }\n\n   private AutoScalingConstants() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/ComparisonOperator.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.CaseFormat;\n\n/**\n * @see <a href=\"http://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_MetricAlarm.html\" />\n */\n@Beta\npublic enum ComparisonOperator {\n\n   GREATER_THAN_OR_EQUAL_TO_THRESHOLD,\n   GREATER_THAN_THRESHOLD,\n   LESS_THAN_THRESHOLD,\n   LESS_THAN_OR_EQUAL_TO_THRESHOLD,\n   UNRECOGNIZED;\n\n   public String value() {\n      return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name());\n   }\n\n   @Override\n   public String toString() {\n      return value();\n   }\n\n   public static ComparisonOperator fromValue(String value) {\n      try {\n         return valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, checkNotNull(value, \"value\")));\n\n      } catch (IllegalArgumentException e) {\n         return UNRECOGNIZED;\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/Datapoint.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.domain;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport java.util.Date;\n\n/**\n * @see <a href=\"http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference?DT_Datapoint.html\"\n *      />\n */\npublic class Datapoint {\n\n   private final Double average;\n   private final Double maximum;\n   private final Double minimum;\n   private final Date timestamp;\n   private final Double samples;\n   private final Double sum;\n   private final Unit unit;\n   private final String customUnit;\n\n   public Datapoint(@Nullable Double average, @Nullable Double maximum, @Nullable Double minimum,\n            @Nullable Date timestamp, @Nullable Double samples, @Nullable Double sum, @Nullable Unit unit,\n            @Nullable String customUnit) {\n      this.average = average;\n      this.maximum = maximum;\n      this.minimum = minimum;\n      this.timestamp = timestamp;\n      this.samples = samples;\n      this.sum = sum;\n      this.unit = unit;\n      this.customUnit = customUnit;\n   }\n\n   /**\n    * return Average of samples for the datapoint.\n    */\n   @Nullable\n   public Double getAverage() {\n      return average;\n   }\n\n   /**\n    * return Maximum of the samples used for the datapoint.\n    */\n   @Nullable\n   public Double getMaximum() {\n      return maximum;\n   }\n\n   /**\n    * return Minimum of samples for the datapoint.\n    */\n   @Nullable\n   public Double getMinimum() {\n      return minimum;\n   }\n\n   /**\n    * return Indicates the beginning of the time aggregation for this value and samples.\n    */\n   @Nullable\n   public Date getTimestamp() {\n      return timestamp;\n   }\n\n   /**\n    * return The number of Measurements that contributed to the aggregate value of this datapoint.\n    */\n   @Nullable\n   public Double getSamples() {\n      return samples;\n   }\n\n   /**\n    * return Sum of samples for the datapoint.\n    */\n   @Nullable\n   public Double getSum() {\n      return sum;\n   }\n\n   /**\n    * return Standard unit used for the datapoint.\n    */\n   @Nullable\n   public Unit getUnit() {\n      return unit;\n   }\n\n   /**\n    * return CustomUnit defined for the datapoint.\n    */\n   @Nullable\n   public String getCustomUnit() {\n      return customUnit;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(average, customUnit, maximum, minimum, samples, sum, timestamp, unit);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      Datapoint other = (Datapoint) obj;\n      return Objects.equal(this.average, other.average) &&\n             Objects.equal(this.customUnit, other.customUnit) &&\n             Objects.equal(this.maximum, other.maximum) &&\n             Objects.equal(this.minimum, other.minimum) &&\n             Objects.equal(this.samples, other.samples) &&\n             Objects.equal(this.sum, other.sum) &&\n             Objects.equal(this.timestamp, other.timestamp) &&\n             Objects.equal(this.unit, other.unit);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this)\n                    .add(\"timestamp\", timestamp)\n                    .add(\"customUnit\", customUnit)\n                    .add(\"maximum\", maximum)\n                    .add(\"minimum\", minimum)\n                    .add(\"average\", average)\n                    .add(\"sum\", sum)\n                    .add(\"samples\", samples)\n                    .add(\"unit\", unit).toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/Dimension.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.domain;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\n/**\n * @see <a href=\"http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference/API_Dimension.html\" />\n */\npublic class Dimension {\n\n   private final String name;\n   private final String value;\n\n   public Dimension(String name, String value) {\n      this.name = name;\n      this.value = value;\n   }\n\n   /**\n    * return the dimension name.\n    */\n   public String getName() {\n      return name;\n   }\n\n   /**\n    * return the dimension value.\n    */\n   public String getValue() {\n      return value;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(name, value);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      Dimension other = (Dimension)obj;\n      return Objects.equal(this.name, other.name) &&\n             Objects.equal(this.value, other.value);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this)\n                    .add(\"name\", name)\n                    .add(\"value\", value).toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/DynamoDBConstants.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.domain;\n\n/**\n * Constants interface for the AWS AutoScaling dimensions and metric names as of 2012-04-24.\n *\n * @see <a href=\"http://docs.amazonwebservices.com/AmazonCloudWatch/latest/DeveloperGuide/CW_Support_For_AWS.html#dynamo-metricscollected\" />\n */\npublic final class DynamoDBConstants {\n\n   public static class Dimension {\n\n      public static final String OPERATION = \"Operation\";\n      public static final String TABLE_NAME = \"TableName\";\n\n   }\n\n   public static class MetricName {\n\n      public static final String CONSUMED_READ_CAPACITY_UNITS = \"ConsumedReadCapacityUnits\";\n      public static final String CONSUMED_WRITE_CAPACITY_UNITS = \"ConsumedWriteCapacityUnits\";\n      public static final String SUCCESSFUL_REQUEST_LATENCY = \"SuccessfulRequestLatency\";\n      public static final String RETURNED_ITEM_COUNT = \"ReturnedItemCount\";\n      public static final String SYSTEM_ERRORS = \"SystemErrors\";\n      public static final String THROTTLED_REQUESTS = \"ThrottledRequests\";\n      public static final String USER_ERRORS = \"UserErrors\";\n\n   }\n\n   private DynamoDBConstants() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/EBSConstants.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.domain;\n\n/**\n * Constants interface for the AWS AutoScaling dimensions and metric names as of 2012-04-24.\n *\n * @see <a href=\"http://docs.amazonwebservices.com/AmazonCloudWatch/latest/DeveloperGuide/CW_Support_For_AWS.html#ebs-metricscollected\" />\n */\npublic final class EBSConstants {\n\n   public static class Dimension {\n\n      public static final String VOLUME_ID = \"VolumeId\";\n\n   }\n\n   public static class MetricName {\n\n      public static final String VOLUME_IDLE_TIME = \"VolumeIdleTime\";\n      public static final String VOLUME_QUEUE_LENGTH = \"VolumeQueueLength\";\n      public static final String VOLUME_READ_BYTES = \"VolumeReadBytes\";\n      public static final String VOLUME_READ_OPS = \"VolumeReadOps\";\n      public static final String VOLUME_TOTAL_READ_TIME = \"VolumeTotalReadTime\";\n      public static final String VOLUME_TOTAL_WRITE_TIME = \"VolumeTotalWriteTime\";\n      public static final String VOLUME_WRITE_BYTES = \"VolumeWriteBytes\";\n      public static final String VOLUME_WRITE_OPS = \"VolumeWriteOps\";\n\n   }\n\n   private EBSConstants() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/EC2Constants.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.domain;\n\n/**\n * Constants interface for the AWS AutoScaling dimensions and metric names as of 2012-04-24.\n *\n * @see <a href=\"http://docs.amazonwebservices.com/AmazonCloudWatch/latest/DeveloperGuide/CW_Support_For_AWS.html#ec2-metricscollected\" />\n */\npublic final class EC2Constants {\n\n   public static class Dimension {\n\n      public static final String AUTO_SCALING_GROUP_NAME = \"AutoScalingGroupName\";\n      public static final String IMAGE_ID = \"ImageId\";\n      public static final String INSTANCE_ID = \"InstanceId\";\n      public static final String INSTANCE_TYPE = \"InstanceType\";\n\n   }\n\n   public static class MetricName {\n\n      public static final String CPU_UTILIZATION = \"CPUUtilization\";\n      public static final String DISK_READ_BYTES = \"DiskReadBytes\";\n      public static final String DISK_READ_OPS = \"DiskReadOps\";\n      public static final String DISK_WRITE_BYTES = \"DiskWriteBytes\";\n      public static final String DISK_WRITE_OPS = \"DiskWriteOps\";\n      public static final String NETWORK_IN = \"NetworkIn\";\n      public static final String NETWORK_OUT = \"NetworkOut\";\n\n   }\n\n   private EC2Constants() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/ELBConstants.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.domain;\n\n/**\n * Constants interface for the AWS AutoScaling dimensions and metric names as of 2012-04-24.\n *\n * @see <a href=\"http://docs.amazonwebservices.com/AmazonCloudWatch/latest/DeveloperGuide/CW_Support_For_AWS.html#elb-metricscollected\" />\n */\npublic final class ELBConstants {\n\n   public static class Dimension {\n\n      public static final String AVAILABILITY_ZONE = \"AvailabilityZone\";\n      public static final String LOAD_BALANCER_NAME = \"LoadBalancerName\";\n\n   }\n\n   public static class MetricName {\n\n      public static final String HEALTHY_HOST_COUNT = \"HealthyHostCount\";\n      public static final String HTTP_CODE_BACKEND_2XX = \"HTTPCode_Backend_2XX\";\n      public static final String HTTP_CODE_BACKEND_3XX = \"HTTPCode_Backend_3XX\";\n      public static final String HTTP_CODE_BACKEND_4XX = \"HTTPCode_Backend_4XX\";\n      public static final String HTTP_CODE_BACKEND_5XX = \"HTTPCode_Backend_5XX\";\n      public static final String HTTP_CODE_ELB_4XX = \"HTTPCode_ELB_4XX\";\n      public static final String HTTP_CODE_ELB_5XX = \"HTTPCode_ELB_5XX\";\n      public static final String LATENCY = \"Latency\";\n      public static final String REQUEST_COUNT = \"RequestCount\";\n      public static final String UNHEALTHY_HOST_COUNT = \"UnHealthyHostCount\";\n\n   }\n\n   private ELBConstants() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/EMRConstants.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.domain;\n\n/**\n * Constants interface for the AWS AutoScaling dimensions and metric names as of 2012-04-24.\n *\n * @see <a href=\"http://docs.amazonwebservices.com/AmazonCloudWatch/latest/DeveloperGuide/CW_Support_For_AWS.html#emr-metricscollected\" />\n */\npublic final class EMRConstants {\n\n   public static class Dimension {\n\n      public static final String JOB_FLOW_ID = \"JobFlowId\";\n      public static final String JOB_ID = \"JobId\";\n\n   }\n\n   public static class MetricName {\n\n      public static final String CORE_NODES_PENDING = \"CoreNodesPending\";\n      public static final String CORE_NODES_RUNNING = \"CoreNodesRunning\";\n      public static final String HDFS_BYTES_READ = \"HDFSBytesRead\";\n      public static final String HDFS_BYTES_WRITTEN = \"HDFSBytesWritten\";\n      public static final String HDFS_UTILIZATION = \"HDFSUtilization\";\n      public static final String IS_IDLE = \"IsIdle\";\n      public static final String JOBS_FAILED = \"JobsFailed\";\n      public static final String JOBS_RUNNING = \"JobsRunning\";\n      public static final String LIVE_DATA_NODES = \"LiveDataNodes\";\n      public static final String LIVE_TASK_TRACKERS = \"LiveTaskTrackers\";\n      public static final String MAP_SLOTS_OPEN = \"MapSlotsOpen\";\n      public static final String MISSING_BLOCKS = \"MissingBlocks\";\n      public static final String REDUCE_SLOTS_OPEN = \"ReduceSlotsOpen\";\n      public static final String REMAINING_MAP_TASKS = \"RemainingMapTasks\";\n      public static final String REMAINING_MAP_TASKS_PER_SLOT = \"RemainingMapTasksPerSlot\";\n      public static final String REMAINING_REDUCE_TASKS = \"RemainingReduceTasks\";\n      public static final String RUNNING_MAP_TASKS = \"RunningMapTasks\";\n      public static final String RUNNING_REDUCE_TASKS = \"RunningReduceTasks\";\n      public static final String S3_BYTES_READ = \"S3BytesRead\";\n      public static final String S3_BYTES_WRITTEN = \"S3BytesWritten\";\n      public static final String TASK_NODES_PENDING = \"TaskNodesPending\";\n      public static final String TASK_NODES_RUNNING = \"TaskNodesRunning\";\n      public static final String TOTAL_LOAD = \"TotalLoad\";\n\n   }\n\n   private EMRConstants() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/GetMetricStatistics.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Date;\nimport java.util.Set;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Sets;\n\n/**\n * Options use to get statistics for the specified metric.\n *\n * @see <a href=\"http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference/API_GetMetricStatistics.html\" />\n */\n@Beta\npublic class GetMetricStatistics {\n\n   private final Set<Dimension> dimensions;\n   private final Optional<Date> endTime;\n   private final String metricName;\n   private final String namespace;\n   private final int period;\n   private final Optional<Date> startTime;\n   private final Set<Statistics> statistics;\n   private final Optional<Unit> unit;\n\n   /**\n    * Private constructor to enforce using {@link Builder}.\n    */\n   protected GetMetricStatistics(Set<Dimension> dimensions, Date endTime, String metricName, String namespace, int period,\n                               Date startTime, Set<Statistics> statistics, Unit unit) {\n      this.dimensions = ImmutableSet.<Dimension>copyOf(checkNotNull(dimensions, \"dimensions\"));\n      this.endTime = Optional.fromNullable(endTime);\n      this.metricName = checkNotNull(metricName, \"metricName\");\n      this.namespace = checkNotNull(namespace, \"namespace\");\n      this.period = period;\n      this.startTime = Optional.fromNullable(startTime);\n      this.statistics = ImmutableSet.<Statistics>copyOf(checkNotNull(statistics, \"statistics\"));\n      this.unit = Optional.fromNullable(unit);\n   }\n\n   /**\n    * return the set of dimensions for this request\n    */\n   public Set<Dimension> getDimensions() {\n      return dimensions;\n   }\n\n   /**\n    * return the end time for this request\n    */\n   public Optional<Date> getEndTime() {\n      return endTime;\n   }\n\n   /**\n    * return the metric name for this request\n    */\n   public String getMetricName() {\n      return metricName;\n   }\n\n   /**\n    * return the namespace for this request\n    */\n   public String getNamespace() {\n      return namespace;\n   }\n\n   /**\n    * return the period for this request\n    */\n   public int getPeriod() {\n      return period;\n   }\n\n   /**\n    * return the start time for this request\n    */\n   public Optional<Date> getStartTime() {\n      return startTime;\n   }\n\n   /**\n    * return the statistics for this request\n    */\n   public Set<Statistics> getStatistics() {\n      return statistics;\n   }\n\n   /**\n    * return the unit for this request\n    */\n   public Optional<Unit> getUnit() {\n      return unit;\n   }\n\n   /**\n    * Returns a new builder. The generated builder is equivalent to the builder\n    * created by the {@link Builder} constructor.\n    */\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n\n      // this builder is set to be additive on dimension calls, so make this mutable\n      private Set<Dimension> dimensions = Sets.newLinkedHashSet();\n      private Date endTime;\n      private String metricName;\n      private String namespace;\n      private int period = 60;\n      private Date startTime;\n      // this builder is set to be additive on dimension calls, so make this mutable\n      private Set<Statistics> statistics = Sets.newLinkedHashSet();\n      private Unit unit;\n\n      /**\n       * Creates a new builder. The returned builder is equivalent to the builder\n       * generated by {@link ListMetricsOptions#builder}.\n       */\n      public Builder() {}\n\n      /**\n       * A list of dimensions describing qualities of the metric.\n       *\n       * @param dimensions the dimensions describing the qualities of the metric\n       *\n       * @return this {@code Builder} object\n       */\n      public Builder dimensions(Set<Dimension> dimensions) {\n         this.dimensions.addAll(checkNotNull(dimensions, \"dimensions\"));\n         return this;\n      }\n\n      /**\n       * A dimension describing qualities of the metric.\n       *\n       * @param dimension the dimension describing the qualities of the metric\n       *\n       * @return this {@code Builder} object\n       */\n      public Builder dimension(Dimension dimension) {\n         this.dimensions.add(checkNotNull(dimension, \"dimension\"));\n         return this;\n      }\n\n      /**\n       * The time stamp to use for determining the last datapoint to return. The value specified is exclusive so\n       * results will include datapoints up to the time stamp specified.\n       *\n       * @param endTime the timestamp to use for determining the last datapoint to return\n       *\n       * @return this {@code Builder} object\n       */\n      public Builder endTime(Date endTime) {\n         this.endTime = endTime;\n         return this;\n      }\n\n      /**\n       * The name of the metric.\n       *\n       * @param metricName the metric name to filter against\n       *\n       * @return this {@code Builder} object\n       */\n      public Builder metricName(String metricName) {\n         this.metricName = metricName;\n         return this;\n      }\n\n      /**\n       * The namespace of the metric.\n       *\n       * @param namespace the namespace to filter against\n       *\n       * @return this {@code Builder} object\n       */\n      public Builder namespace(String namespace) {\n         this.namespace = namespace;\n         return this;\n      }\n\n      /**\n       * The granularity, in seconds, of the returned datapoints.\n       *\n       * @param period the granularity, in seconds, of the returned datapoints\n       *\n       * @return this {@code Builder} object\n       */\n      public Builder period(int period) {\n         this.period = period;\n         return this;\n      }\n\n      /**\n       * The time stamp to use for determining the first datapoint to return. The value specified is inclusive so\n       * results include datapoints with the time stamp specified.\n       *\n       * @param startTime The time stamp to use for determining the first datapoint to return\n       *\n       * @return this {@code Builder} object\n       */\n      public Builder startTime(Date startTime) {\n         this.startTime = startTime;\n         return this;\n      }\n\n      /**\n       * The metric statistics to return.\n       *\n       * @param statistics the metric statistics to return.\n       *\n       * @return this {@code Builder} object\n       */\n      public Builder statistics(Set<Statistics> statistics) {\n         this.statistics.addAll(checkNotNull(statistics, \"statistics\"));\n         return this;\n      }\n\n      /**\n       * The metric statistic to return.  (Can be called multiple times up to a maximum of 5 times.)\n       *\n       * @param statistic the metric statistic to return\n       *\n       * @return this {@code Builder} object\n       */\n      public Builder statistic(Statistics statistic) {\n         this.statistics.add(checkNotNull(statistic, \"statistic\"));\n         return this;\n      }\n\n       /**\n        * The unit for the metric.\n        *\n        * @param unit the unit for the metric\n        *\n        * @return this {@code Builder} object\n        */\n      public Builder unit(Unit unit) {\n         this.unit = unit;\n         return this;\n      }\n\n      /**\n       * Returns a newly-created {@code GetMetricStatisticsOptionsV2} based on the contents of\n       * the {@code Builder}.\n       */\n      public GetMetricStatistics build() {\n         return new GetMetricStatistics(dimensions, endTime, metricName, namespace, period, startTime,  statistics,\n                                        unit);\n      }\n\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/GetMetricStatisticsResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.domain;\n\nimport java.util.Iterator;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n *  the list of {@link Datapoint} for the metric\n *  \n * @see <a href=\"http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference/API_GetMetricStatistics.html\" />\n */\npublic class GetMetricStatisticsResponse extends FluentIterable<Datapoint> {\n\n   private final Iterable<Datapoint> datapoints;\n   private final String label;\n\n   public GetMetricStatisticsResponse(@Nullable Iterable<Datapoint> datapoints, String label) {\n      // Default to an empty set\n      if (datapoints == null) {\n         this.datapoints = ImmutableSet.<Datapoint>of();\n      } else {\n         this.datapoints = ImmutableSet.<Datapoint>copyOf(datapoints);\n      }\n      this.label = label;\n   }\n\n   /**\n    * return the label describing the specified metric\n    */\n   public String getLabel() {\n      return label;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(datapoints, label);\n   }\n\n    /**\n    * {@inheritDoc}\n    */\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      GetMetricStatisticsResponse other = (GetMetricStatisticsResponse)obj;\n      return Objects.equal(this.datapoints, other.datapoints) &&\n             Objects.equal(this.label, other.label);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this)\n                    .add(\"label\", label)\n                    .add(\"datapoints\", datapoints).toString();\n   }\n\n   @Override\n   public Iterator<Datapoint> iterator() {\n      return datapoints.iterator();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/HistoryItemType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.CaseFormat;\n\n/**\n * @see <a href=\"http://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_AlarmHistoryItem.html\" />\n */\n@Beta\npublic enum HistoryItemType {\n\n   CONFIGURATION_UPDATE,\n   STATE_UPDATE,\n   ACTION,\n   UNRECOGNIZED;\n\n   public String value() {\n      return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name());\n   }\n\n   @Override\n   public String toString() {\n      return value();\n   }\n\n   public static HistoryItemType fromValue(String value) {\n      try {\n         return valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, checkNotNull(value, \"value\")));\n      } catch (IllegalArgumentException e) {\n         return UNRECOGNIZED;\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/ListMetricsResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.domain;\n\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ForwardingSet;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * list of {@link Metric}\n * @see <a href=\"http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference/API_ListMetrics.html\" />\n */\npublic class ListMetricsResponse extends ForwardingSet<Metric> {\n\n   private final Set<Metric> metrics;\n   private final String nextToken;\n\n   public ListMetricsResponse(@Nullable Set<Metric> metrics, @Nullable String nextToken) {\n      // Default to an empty set\n      if (metrics == null) {\n         this.metrics = ImmutableSet.<Metric>of();\n      } else {\n         this.metrics = ImmutableSet.<Metric>copyOf(metrics);\n      }\n      this.nextToken = nextToken;\n   }\n\n   /**\n    * return the next token or null if there is none.\n    */\n   @Nullable\n   public String getNextToken() {\n      return nextToken;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(metrics, nextToken);\n   }\n\n    /**\n    * {@inheritDoc}\n    */\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      ListMetricsResponse other = (ListMetricsResponse)obj;\n      return Objects.equal(this.metrics, other.metrics) &&\n             Objects.equal(this.nextToken, other.nextToken);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this)\n                    .add(\"metrics\", metrics)\n                    .add(\"nextToken\", nextToken).toString();\n   }\n\n   @Override\n   protected Set<Metric> delegate() {\n      return metrics;\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/Metric.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.domain;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.collect.Sets;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport java.util.Set;\n\n/**\n * @see <a href=\"http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference/API_Metric.html\" />\n */\npublic class Metric {\n\n   private final Set<Dimension> dimensions;\n   private final String metricName;\n   private final String namespace;\n\n   public Metric (String metricName, String namespace, @Nullable Set<Dimension> dimensions) {\n      // Default to an empty set\n      if (dimensions == null) {\n         this.dimensions = Sets.newLinkedHashSet();\n      } else {\n         this.dimensions = dimensions;\n      }\n\n      this.metricName = metricName;\n      this.namespace = namespace;\n   }\n\n   /**\n    * return the metric name for the metric.\n    */\n   public String getMetricName() {\n      return metricName;\n   }\n\n   /**\n    * return the namespace for the metric\n    */\n   public String getNamespace() {\n      return namespace;\n   }\n\n   /**\n    * return the available dimensions for the metric\n    */\n   @Nullable\n   public Set<Dimension> getDimensions() {\n      return dimensions;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(dimensions, metricName, namespace);\n   }\n\n    /**\n    * {@inheritDoc}\n    */\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      Metric other = (Metric)obj;\n      return Objects.equal(this.dimensions, other.dimensions) &&\n             Objects.equal(this.metricName, other.metricName) &&\n             Objects.equal(this.namespace, other.namespace);\n  }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this)\n                    .add(\"namespace\", namespace)\n                    .add(\"metricName\", metricName)\n                    .add(\"dimension\", dimensions).toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/MetricDatum.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Date;\nimport java.util.Set;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * @see <a href=\n *      \"http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference/API_MetricDatum.html\"\n *      />\n */\npublic class MetricDatum {\n\n   private final Set<Dimension> dimensions;\n   private final String metricName;\n   private final Optional<StatisticValues> statisticValues;\n   private final Optional<Date> timestamp;\n   private final Unit unit;\n   private final Optional<Double> value;\n\n   /**\n    * Private constructor to enforce using {@link Builder}.\n    */\n   protected MetricDatum(Iterable<Dimension> dimensions, String metricName, Optional<StatisticValues> statisticValues,\n            Optional<Date> timestamp, Unit unit, Optional<Double> value) {\n      this.dimensions = ImmutableSet.<Dimension> copyOf(checkNotNull(dimensions, \"dimensions\"));\n      this.metricName = checkNotNull(metricName, \"metricName\");\n      this.statisticValues = checkNotNull(statisticValues, \"statisticValues\");\n      this.timestamp = checkNotNull(timestamp, \"timestamp\");\n      this.unit = checkNotNull(unit, \"unit\");\n      this.value = checkNotNull(value, \"value\");\n   }\n\n   /**\n    * return the list of dimensions describing the the metric.\n    */\n   public Set<Dimension> getDimensions() {\n      return dimensions;\n   }\n\n   /**\n    * return the metric name for the metric.\n    */\n   public String getMetricName() {\n      return metricName;\n   }\n\n   /**\n    * return the object describing the set of statistical values for the metric\n    */\n   public Optional<StatisticValues> getStatisticValues() {\n      return statisticValues;\n   }\n\n   /**\n    * return the time stamp used for the metric\n    */\n   public Optional<Date> getTimestamp() {\n      return timestamp;\n   }\n\n   /**\n    * return Standard unit used for the metric.\n    */\n   public Unit getUnit() {\n      return unit;\n   }\n\n   /**\n    * return the actual value of the metric\n    */\n   public Optional<Double> getValue() {\n      return value;\n   }\n\n   /**\n    * Returns a new builder. The generated builder is equivalent to the builder created by the\n    * {@link Builder} constructor.\n    */\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n\n      // this builder is set to be additive on dimension calls, so make this mutable\n      private ImmutableList.Builder<Dimension> dimensions = ImmutableList.<Dimension> builder();\n      private String metricName;\n      private Optional<StatisticValues> statisticValues = Optional.absent();\n      private Optional<Date> timestamp = Optional.absent();\n      private Unit unit = Unit.NONE;\n      private Optional<Double> value = Optional.absent();\n\n      /**\n       * Creates a new builder. The returned builder is equivalent to the builder generated by\n       * {@link org.jclouds.cloudwatch.domain.MetricDatum#builder}.\n       */\n      public Builder() {\n      }\n\n      /**\n       * A list of dimensions describing qualities of the metric.\n       * \n       * @param dimensions\n       *           the dimensions describing the qualities of the metric\n       * \n       * @return this {@code Builder} object\n       */\n      public Builder dimensions(Iterable<Dimension> dimensions) {\n         this.dimensions.addAll(checkNotNull(dimensions, \"dimensions\"));\n         return this;\n      }\n\n      /**\n       * A dimension describing qualities of the metric.\n       * \n       * @param dimension\n       *           the dimension describing the qualities of the metric\n       * \n       * @return this {@code Builder} object\n       */\n      public Builder dimension(Dimension dimension) {\n         this.dimensions.add(checkNotNull(dimension, \"dimension\"));\n         return this;\n      }\n\n      /**\n       * The name of the metric.\n       * \n       * @param metricName\n       *           the metric name\n       * \n       * @return this {@code Builder} object\n       */\n      public Builder metricName(String metricName) {\n         this.metricName = metricName;\n         return this;\n      }\n\n      /**\n       * The object describing the set of statistical values describing the metric.\n       * \n       * @param statisticValues\n       *           the object describing the set of statistical values for the metric\n       * \n       * @return this {@code Builder} object\n       */\n      public Builder statisticValues(StatisticValues statisticValues) {\n         this.statisticValues = Optional.fromNullable(statisticValues);\n         return this;\n      }\n\n      /**\n       * The time stamp used for the metric. If not specified, the default value is set to the time\n       * the metric data was received.\n       * \n       * @param timestamp\n       *           the time stamp used for the metric\n       * \n       * @return this {@code Builder} object\n       */\n      public Builder timestamp(Date timestamp) {\n         this.timestamp = Optional.fromNullable(timestamp);\n         return this;\n      }\n\n      /**\n       * The unit for the metric.\n       * \n       * @param unit\n       *           the unit for the metric\n       * \n       * @return this {@code Builder} object\n       */\n      public Builder unit(Unit unit) {\n         this.unit = unit;\n         return this;\n      }\n\n      /**\n       * The value for the metric.\n       * \n       * @param value\n       *           the value for the metric\n       * \n       * @return this {@code Builder} object\n       */\n      public Builder value(Double value) {\n         this.value = Optional.fromNullable(value);\n         return this;\n      }\n\n      /**\n       * Returns a newly-created {@code MetricDatum} based on the contents of the {@code Builder}.\n       */\n      public MetricDatum build() {\n         return new MetricDatum(dimensions.build(), metricName, statisticValues, timestamp, unit, value);\n      }\n\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o)\n         return true;\n      if (o == null || getClass() != o.getClass())\n         return false;\n      MetricDatum that = MetricDatum.class.cast(o);\n      return equal(this.dimensions, that.dimensions) && equal(this.metricName, that.metricName)\n               && equal(this.statisticValues, that.statisticValues) && equal(this.timestamp, that.timestamp)\n               && equal(this.unit, that.unit) && equal(this.value, that.value);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(dimensions, metricName, statisticValues, timestamp, unit, value);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(\"\").omitNullValues().add(\"dimensions\", dimensions).add(\"metricName\", metricName)\n               .add(\"statisticValues\", statisticValues.orNull()).add(\"timestamp\", timestamp.orNull()).add(\"unit\", unit)\n               .add(\"value\", value.orNull());\n   }\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/Namespaces.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.domain;\n\n/**\n * Constants interface for the AWS provided namespaces as of 2012-04-24.\n *\n * @see <a href=\"http://docs.amazonwebservices.com/AmazonCloudWatch/latest/DeveloperGuide/CW_Support_For_AWS.html#aws-namespaces\" />\n */\npublic final class Namespaces {\n\n   public static final String AUTO_SCALING = \"AWS/AutoScaling\";\n   public static final String DYNAMODB = \"AWS/DynamoDB\";\n   public static final String EBS = \"AWS/EBS\";\n   public static final String EC2 = \"AWS/EC2\";\n   public static final String ELB = \"AWS/ELB\";\n   public static final String EMR = \"AWS/EMR\";\n   public static final String RDS = \"AWS/RDS\";\n   public static final String SNS = \"AWS/SNS\";\n   public static final String SQS = \"AWS/SQS\";\n   public static final String STORAGE_GATEWAY = \"AWS/StorageGateway\";\n\n   private Namespaces() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/RDSConstants.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.domain;\n\n/**\n * Constants interface for the AWS AutoScaling dimensions and metric names as of 2012-04-24.\n *\n * @see <a href=\"http://docs.amazonwebservices.com/AmazonCloudWatch/latest/DeveloperGuide/CW_Support_For_AWS.html#rds-metricscollected\" />\n */\npublic final class RDSConstants {\n\n   public static class Dimension {\n\n      public static final String DB_INSTANCE_IDENTIFIER = \"DBInstanceIdentifier\";\n      public static final String DATABASE_CLASS = \"DatabaseClass\";\n      public static final String ENGINE_NAME = \"EngineName\";\n\n   }\n\n   public static class MetricName {\n\n      public static final String BIN_LOG_DISK_USAGE = \"BinLogDiskUsage\";\n      public static final String CPU_UTILIZATION = \"CPUUtilization\";\n      public static final String DATABASE_CONNECTIONS = \"DatabaseConnections\";\n      public static final String FREEABLE_MEMORY = \"FreeableMemory\";\n      public static final String FREE_STORAGE_SPACE = \"FreeStorageSpace\";\n      public static final String REPLICA_LAG = \"ReplicaLag\";\n      public static final String READ_IO_OPS = \"ReadIOPS\";\n      public static final String READ_LATENCY = \"ReadLatency\";\n      public static final String READ_THROUGHPUT = \"ReadThroughput\";\n      public static final String SWAP_USAGE = \"SwapUsage\";\n      public static final String WRITE_IO_OPS = \"WriteIOPS\";\n      public static final String WRITE_LATENCY = \"WriteLtency\";\n      public static final String WRITE_THROUGHPUT = \"WriteThroughput\";\n\n   }\n\n   private RDSConstants() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/SNSConstants.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.domain;\n\n/**\n * Constants interface for the AWS AutoScaling dimensions and metric names as of 2012-04-24.\n *\n * @see <a href=\"http://docs.amazonwebservices.com/AmazonCloudWatch/latest/DeveloperGuide/CW_Support_For_AWS.html#sns-metricscollected\" />\n */\npublic final class SNSConstants {\n\n   public static class Dimension {\n\n      public static final String TOPIC_NAME = \"TopicName\";\n\n   }\n\n   public static class MetricName {\n\n      public static final String NUMBER_OF_MESSAGES_PUBLISHED = \"NumberOfMessagesPublished\";\n      public static final String NUMBER_OF_NOTIFICATIONS_DELIVERED = \"NumberOfNotificationsDelivered\";\n      public static final String NUMBER_OF_NOTIFICATIONS_FAILED = \"NumberOfNotificationsFailed\";\n      public static final String PUBLISH_SIZE = \"PublishSize\";\n\n   }\n\n   private SNSConstants() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/SQSConstants.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.domain;\n\n/**\n * Constants interface for the AWS AutoScaling dimensions and metric names as of 2012-04-24.\n *\n * @see <a href=\"http://docs.amazonwebservices.com/AmazonCloudWatch/latest/DeveloperGuide/CW_Support_For_AWS.html#sqs-metricscollected\" />\n */\npublic final class SQSConstants {\n\n   public static class Dimension {\n\n      public static final String QUEUE_NAME = \"QueueName\";\n\n   }\n\n   public static class MetricName {\n\n      public static final String APPROXIMATE_NUMBER_OF_MESSAGES_DELAYED = \"ApproximateNumberOfMessagesDelayed\";\n      public static final String APPROXIMATE_NUMBER_OF_MESSAGES_NOT_VISIBLE = \"ApproximateNumberOfMessagesNotVisible\";\n      public static final String APPROXIMATE_NUMBER_OF_MESSAGES_VISIBLE = \"ApproximateNumberOfMessagesVisible\";\n      public static final String NUMBER_OF_EMPTY_RECEIVES = \"NumberOfEmptyReceives\";\n      public static final String NUMBER_OF_MESSAGES_DELETED = \"NumberOfMessagesDeleted\";\n      public static final String NUMBER_OF_MESSAGES_RECEIVED = \"NumberOfMessagesReceived\";\n      public static final String NUMBER_OF_MESSAGES_SENT = \"NumberOfMessagesSent\";\n      public static final String SENT_MESSAGES_SIZE = \"SentMessageSize\";\n\n   }\n\n   private SQSConstants() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/StatisticValues.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.domain;\n\n/**\n * @see <a href=\"http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference/API_StatisticSet.html\" />\n */\npublic class StatisticValues {\n\n   private final double maximum;\n   private final double minimum;\n   private final double sampleCount;\n   private final double sum;\n\n   public StatisticValues(double maximum, double minimum, double sampleCount, double sum) {\n      this.maximum = maximum;\n      this.minimum = minimum;\n      this.sampleCount = sampleCount;\n      this.sum = sum;\n   }\n\n   /**\n    * return the maximum value of the sample set\n    */\n   public double getMaximum() {\n      return maximum;\n   }\n\n   /**\n    * return the minimum value of the sample set\n    */\n   public double getMinimum() {\n      return minimum;\n   }\n\n   /**\n    * return the number of samples used for the statistic set\n    */\n   public double getSampleCount() {\n      return sampleCount;\n   }\n\n   /**\n    * return the sum of values for the sample set\n    */\n   public double getSum() {\n      return sum;\n   }\n\n   /**\n    * Returns a new builder. The generated builder is equivalent to the builder\n    * created by the {@link Builder} constructor.\n    */\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n\n      private double maximum;\n      private double minimum;\n      private double sampleCount;\n      private double sum;\n\n      /**\n       * Creates a new builder. The returned builder is equivalent to the builder\n       * generated by {@link org.jclouds.cloudwatch.domain.StatisticValues#builder}.\n       */\n      public Builder() {}\n\n      /**\n       * The maximum value of the sample set.\n       *\n       * @param maximum the maximum value of the sample set\n       *\n       * @return this {@code Builder} object\n       */\n      public Builder maximum(double maximum) {\n         this.maximum = maximum;\n         return this;\n      }\n\n      /**\n       * The minimum value of the sample set.\n       *\n       * @param minimum the minimum value of the sample set\n       *\n       * @return this {@code Builder} object\n       */\n      public Builder minimum(double minimum) {\n         this.minimum = minimum;\n         return this;\n      }\n\n      /**\n       * The the number of samples used for the statistic set.\n       *\n       * @param sampleCount the number of samples used for the statistic set\n       *\n       * @return this {@code Builder} object\n       */\n      public Builder sampleCount(double sampleCount) {\n         this.sampleCount = sampleCount;\n         return this;\n      }\n\n      /**\n       * The sum of values for the sample set.\n       *\n       * @param sum the sum of values for the sample set\n       *\n       * @return this {@code Builder} object\n       */\n      public Builder sum(double sum) {\n         this.sum = sum;\n         return this;\n      }\n\n      /**\n       * Returns a newly-created {@code StatisticSet} based on the contents of the {@code Builder}.\n       */\n      public StatisticValues build() {\n         return new StatisticValues(maximum, minimum, sampleCount, sum);\n      }\n\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/Statistics.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.CaseFormat;\n\n/**\n * @see <a href=\"http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference/API_GetMetricStatistics.html?r=5424\"/>\n */\npublic enum Statistics {\n   AVERAGE,\n   SUM,\n   SAMPLE_COUNT,\n   MAXIMUM,\n   MINIMUM,\n   UNRECOGNIZED;\n\n   public String value() {\n      return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name());\n   }\n\n   @Override\n   public String toString() {\n      return value();\n   }\n\n   public static Statistics fromValue(String value) {\n      try {\n         return valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, checkNotNull(value, \"value\")));\n\n      } catch (IllegalArgumentException e) {\n         return UNRECOGNIZED;\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/StorageGatewayConstants.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.domain;\n\n/**\n * Constants interface for the AWS AutoScaling dimensions and metric names as of 2012-04-24.\n *\n * @see <a href=\"http://docs.amazonwebservices.com/AmazonCloudWatch/latest/DeveloperGuide/CW_Support_For_AWS.html#awssg-metricscollected\" />\n */\npublic final class StorageGatewayConstants {\n\n   public static class Dimension {\n\n      public static final String GATEWAY_ID = \"GatewayId\";\n      public static final String GATEWAY_NAME = \"GatewayName\";\n      public static final String VOLUME_ID = \"VolumeId\";\n\n   }\n\n   public static class MetricName {\n\n      // Applicable for all Dimensions\n      public static final String QUEUED_WRITES = \"QueuedWrites\";\n      public static final String READ_BYTES = \"ReadBytes\";\n      public static final String READ_TIME = \"ReadTime\";\n      public static final String WRITE_BYTES = \"WriteBytes\";\n      public static final String WRITE_TIME = \"WriteTime\";\n\n      // Applicable for only GatewayId and GatewayName Dimensions\n      public static final String CLOUD_BYTES_DOWNLOADED = \"CloudBytesDownloaded\";\n      public static final String CLOUD_BYTES_UPLOADED = \"CloudBytesUploaded\";\n      public static final String CLOUD_DOWNLOAD_LATENCY = \"CloudDownloadLatency\";\n      public static final String WORKING_STORAGE_FREE = \"WorkingStorageFree\";\n      public static final String WORKING_STORAGE_PERCENT_USED = \"WorkingStoragePercentUsed\";\n      public static final String WORKING_STORAGE_USED = \"WorkingStorageUsed\";\n\n   }\n\n   private StorageGatewayConstants() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/Unit.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.CaseFormat;\n\n/**\n * @see <a href=\"http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference/API_GetMetricStatistics.html?r=5424\"/>\n */\npublic enum Unit {\n   SECONDS,\n   MICROSECONDS,\n   MILLISECONDS,\n   BYTES,\n   KILOBYTES,\n   MEGABYTES,\n   GIGABYTES,\n   TERABYTES,\n   BITS,\n   KILOBITS,\n   MEGABITS,\n   GIGABITS,\n   TERABITS,\n   PERCENT,\n   COUNT,\n   BYTES_PER_SECOND,\n   KILOBYTES_PER_SECOND,\n   MEGABYTES_PER_SECOND,\n   GIGABYTES_PER_SECOND,\n   TERABYTES_PER_SECOND,\n   BITS_PER_SECOND,\n   KILOBITS_PER_SECOND,\n   MEGABITS_PER_SECOND,\n   GIGABITS_PER_SECOND,\n   TERABITS_PER_SECOND,\n   COUNT_PER_SECOND,\n   NONE,\n   UNRECOGNIZED;\n\n   public String value() {\n      return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name()).replace(\"PerSecond\", \"/Second\");\n   }\n\n   @Override\n   public String toString() {\n      return value();\n   }\n\n   public static Unit fromValue(String value) {\n      try {\n         return valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, checkNotNull(value, \"value\").replace(\n                  \"/\", \"Per\")));\n      } catch (IllegalArgumentException e) {\n         return UNRECOGNIZED;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/features/AlarmApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.FormParam;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.collect.FluentIterable;\nimport org.jclouds.Fallbacks;\nimport org.jclouds.aws.filters.FormSigner;\nimport org.jclouds.cloudwatch.binders.AlarmNamesBinder;\nimport org.jclouds.cloudwatch.domain.Alarm;\nimport org.jclouds.cloudwatch.domain.AlarmHistoryItem;\nimport org.jclouds.cloudwatch.functions.ListAlarmsToPagedIterable;\nimport org.jclouds.cloudwatch.options.ListAlarmHistoryOptions;\nimport org.jclouds.cloudwatch.options.ListAlarmsForMetric;\nimport org.jclouds.cloudwatch.options.ListAlarmsOptions;\nimport org.jclouds.cloudwatch.options.SaveAlarmOptions;\nimport org.jclouds.cloudwatch.xml.ListAlarmHistoryResponseHandler;\nimport org.jclouds.cloudwatch.xml.ListAlarmsForMetricResponseHandler;\nimport org.jclouds.cloudwatch.xml.ListAlarmsResponseHandler;\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.PagedIterable;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.FormParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.Transform;\nimport org.jclouds.rest.annotations.VirtualHost;\nimport org.jclouds.rest.annotations.XMLResponseParser;\n\n/**\n * Provides access to Amazon CloudWatch via the Query API\n * <p/>\n *\n * @see <a href=\"http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference\" />\n */\n@RequestFilters(FormSigner.class)\n@VirtualHost\n@Beta\npublic interface AlarmApi {\n\n   /**\n    * Deletes all specified alarms.\n    *\n    * <p/>\n    * <h3>Note</h3> In the event of an error, no alarms are deleted.\n    *\n    * @param alarmNames the list of alarms to delete\n    */\n   @Named(\"DeleteAlarms\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = \"Action\", values = \"DeleteAlarms\")\n   void delete(@BinderParam(AlarmNamesBinder.class) Iterable<String> alarmNames);\n\n   /**\n    * Return all history for all alarms.\n    *\n    * @return the response object\n    */\n   @Named(\"DescribeAlarmHistory\")\n   @POST\n   @Path(\"/\")\n   @XMLResponseParser(ListAlarmHistoryResponseHandler.class)\n   @FormParams(keys = \"Action\", values = \"DescribeAlarmHistory\")\n   @Transform(ListAlarmsToPagedIterable.class)\n   @Fallback(Fallbacks.EmptyIterableWithMarkerOnNotFoundOr404.class)\n   PagedIterable<AlarmHistoryItem> listHistory();\n\n   /**\n    * Return all history based on the options query\n    *\n    * @return the response object\n    */\n   @Named(\"DescribeAlarmHistory\")\n   @POST\n   @Path(\"/\")\n   @XMLResponseParser(ListAlarmHistoryResponseHandler.class)\n   @FormParams(keys = \"Action\", values = \"DescribeAlarmHistory\")\n   @Transform(ListAlarmsToPagedIterable.class)\n   @Fallback(Fallbacks.EmptyIterableWithMarkerOnNotFoundOr404.class)\n   PagedIterable<AlarmHistoryItem> listHistory(ListAlarmHistoryOptions options);\n\n   /**\n    * Return a single page of history for the specified alarm.\n    *\n    * @param nextToken the token corresponding with the data you want to get\n    *\n    * @return the response object\n    */\n   @Named(\"DescribeAlarmHistory\")\n   @POST\n   @Path(\"/\")\n   @XMLResponseParser(ListAlarmHistoryResponseHandler.class)\n   @FormParams(keys = \"Action\", values = \"DescribeAlarmHistory\")\n   @Fallback(Fallbacks.EmptyIterableWithMarkerOnNotFoundOr404.class)\n   IterableWithMarker<AlarmHistoryItem> listHistoryAt(@FormParam(\"NextToken\")\n                                                                                        String nextToken);\n\n   /**\n    * Return all alarms.\n    *\n    * @return the response object\n    */\n   @Named(\"DescribeAlarms\")\n   @POST\n   @Path(\"/\")\n   @XMLResponseParser(ListAlarmsResponseHandler.class)\n   @FormParams(keys = \"Action\", values = \"DescribeAlarms\")\n   @Transform(ListAlarmsToPagedIterable.class)\n   @Fallback(Fallbacks.EmptyIterableWithMarkerOnNotFoundOr404.class)\n   PagedIterable<Alarm> list();\n\n   /**\n    * Return all alarms based on the options query\n    *\n    * @param options the options describing the alarms query\n    *\n    * @return the response object\n    */\n   @Named(\"DescribeAlarms\")\n   @POST\n   @Path(\"/\")\n   @XMLResponseParser(ListAlarmsResponseHandler.class)\n   @FormParams(keys = \"Action\", values = \"DescribeAlarms\")\n   @Transform(ListAlarmsToPagedIterable.class)\n   @Fallback(Fallbacks.EmptyIterableWithMarkerOnNotFoundOr404.class)\n   PagedIterable<Alarm> list(ListAlarmsOptions options);\n\n   /**\n    * Return a single page of alarms based on the options query\n    *\n    * @param nextToken the token corresponding with the data you want to get\n    *\n    * @return the response object\n    */\n   @Named(\"DescribeAlarms\")\n   @POST\n   @Path(\"/\")\n   @XMLResponseParser(ListAlarmsResponseHandler.class)\n   @FormParams(keys = \"Action\", values = \"DescribeAlarms\")\n   @Fallback(Fallbacks.EmptyIterableWithMarkerOnNotFoundOr404.class)\n   IterableWithMarker<Alarm> listAt(@FormParam(\"NextToken\") String nextToken);\n\n   /**\n    * Return alarms all alarms for a single metric.\n    *\n    * @param options the options describing the alarms for metric query\n    *\n    * @return the response object\n    */\n   @Named(\"DescribeAlarmsForMetric\")\n   @POST\n   @Path(\"/\")\n   @XMLResponseParser(ListAlarmsForMetricResponseHandler.class)\n   @FormParams(keys = \"Action\", values = \"DescribeAlarmsForMetric\")\n   @Fallback(Fallbacks.EmptyIterableWithMarkerOnNotFoundOr404.class)\n   FluentIterable<Alarm> listForMetric(ListAlarmsForMetric options);\n\n   /**\n    * Disables actions for the specified alarms.\n    *\n    * @param alarmNames the list of alarms to disable\n    */\n   @Named(\"DisableAlarmActions\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = \"Action\", values = \"DisableAlarmActions\")\n   void disable(@BinderParam(AlarmNamesBinder.class) Iterable<String> alarmNames);\n\n   /**\n    * Enables actions for the specified alarms.\n    *\n    * @param alarmNames the list of alarms to enable\n    */\n   @Named(\"EnableAlarmActions\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = \"Action\", values = \"EnableAlarmActions\")\n   void enable(@BinderParam(AlarmNamesBinder.class) Iterable<String> alarmNames);\n\n   /**\n    * Creates or updates an alarm and associates it with the specified Amazon CloudWatch metric.\n    *\n    * @param options the options describing the metric alarm to create/update\n    */\n   @Named(\"PutMetricAlarm\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = \"Action\", values = \"PutMetricAlarm\")\n   void save(SaveAlarmOptions options);\n\n   /**\n    * Temporarily sets the state of an alarm.\n    *\n    * @param alarmName the descriptive name for the alarm\n    * @param stateReason the reason that this alarm is set to this specific state (in human-readable text format)\n    * @param stateReasonData the reason that this alarm is set to this specific state (in machine-readable JSON format)\n    * @param state the value of the state\n    */\n   @Named(\"SetAlarmState\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = \"Action\", values = \"SetAlarmState\")\n   void setState(@FormParam(\"AlarmName\") String alarmName,\n                                   @FormParam(\"StateReason\") String stateReason,\n                                   @FormParam(\"StateReasonData\") @Nullable String stateReasonData,\n                                   @FormParam(\"StateValue\") Alarm.State state);\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/features/MetricApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.FormParam;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\n\nimport org.jclouds.Fallbacks.EmptyIterableWithMarkerOnNotFoundOr404;\nimport org.jclouds.Fallbacks.EmptyPagedIterableOnNotFoundOr404;\nimport org.jclouds.aws.filters.FormSigner;\nimport org.jclouds.cloudwatch.binders.GetMetricStatisticsBinder;\nimport org.jclouds.cloudwatch.binders.MetricDataBinder;\nimport org.jclouds.cloudwatch.domain.GetMetricStatistics;\nimport org.jclouds.cloudwatch.domain.GetMetricStatisticsResponse;\nimport org.jclouds.cloudwatch.domain.Metric;\nimport org.jclouds.cloudwatch.domain.MetricDatum;\nimport org.jclouds.cloudwatch.functions.MetricsToPagedIterable;\nimport org.jclouds.cloudwatch.options.GetMetricStatisticsOptions;\nimport org.jclouds.cloudwatch.options.ListMetricsOptions;\nimport org.jclouds.cloudwatch.xml.GetMetricStatisticsResponseHandlerV2;\nimport org.jclouds.cloudwatch.xml.ListMetricsResponseHandler;\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.PagedIterable;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.FormParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.Transform;\nimport org.jclouds.rest.annotations.VirtualHost;\nimport org.jclouds.rest.annotations.XMLResponseParser;\n\n/**\n * Provides access to Amazon CloudWatch via the Query API\n * <p/>\n * \n * @see <a href=\"http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference\" />\n */\n@RequestFilters(FormSigner.class)\n@VirtualHost\npublic interface MetricApi {\n\n   /**\n    * Returns a list of valid metrics stored for the AWS account owner.\n    * \n    * <p/>\n    * <h3>Note</h3> Up to 500 results are returned for any one call. To retrieve further results,\n    * use returned NextToken (\n    * {@link org.jclouds.cloudwatch.domain.ListMetricsResponse#getNextToken()}) value with\n    * subsequent calls .To retrieve all available metrics with one call, use\n    * {@link org.jclouds.cloudwatch.CloudWatch#listMetrics(MetricApi,\n    * org.jclouds.cloudwatch.options.ListMetricsOptions)}\n    * \n    * @param options the options describing the metrics query\n    * \n    * @return the response object\n    */\n   @Named(\"ListMetrics\")\n   @POST\n   @Path(\"/\")\n   @XMLResponseParser(ListMetricsResponseHandler.class)\n   @FormParams(keys = \"Action\", values = \"ListMetrics\")\n   @Fallback(EmptyIterableWithMarkerOnNotFoundOr404.class)\n   IterableWithMarker<Metric> list(ListMetricsOptions options);\n\n   @Named(\"ListMetrics\")\n   @POST\n   @Path(\"/\")\n   @XMLResponseParser(ListMetricsResponseHandler.class)\n   @Transform(MetricsToPagedIterable.class)\n   @FormParams(keys = \"Action\", values = \"ListMetrics\")\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   PagedIterable<Metric> list();\n\n   /**\n    * Gets statistics for the specified metric.\n    * \n    * @param statistics the statistics to gather\n    * @param options the options describing the metric statistics query\n    * \n    * @return the response object\n    */\n   @Named(\"GetMetricStatistics\")\n   @POST\n   @Path(\"/\")\n   @XMLResponseParser(GetMetricStatisticsResponseHandlerV2.class)\n   @FormParams(keys = \"Action\", values = \"GetMetricStatistics\")\n   GetMetricStatisticsResponse getMetricStatistics(\n            @BinderParam(GetMetricStatisticsBinder.class) GetMetricStatistics statistics,\n            GetMetricStatisticsOptions options);\n\n   @Named(\"GetMetricStatistics\")\n   @POST\n   @Path(\"/\")\n   @XMLResponseParser(GetMetricStatisticsResponseHandlerV2.class)\n   @FormParams(keys = \"Action\", values = \"GetMetricStatistics\")\n   GetMetricStatisticsResponse getMetricStatistics(\n            @BinderParam(GetMetricStatisticsBinder.class) GetMetricStatistics statistics);\n\n   /**\n    * Publishes metric data points to Amazon CloudWatch.\n    *\n    * @param metrics the metrics to publish\n    * @param namespace the namespace to publish the metrics to\n    */\n   @Named(\"PutMetricData\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = \"Action\", values = \"PutMetricData\")\n   void putMetricsInNamespace(@BinderParam(MetricDataBinder.class) Iterable<MetricDatum> metrics,\n                                        @FormParam(\"Namespace\") String namespace);\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/functions/ISO8601Format.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.functions;\n\nimport static com.google.common.base.Preconditions.checkArgument;\n\nimport java.util.Date;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.date.DateService;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class ISO8601Format implements Function<Object, String> {\n\n   private final DateService dateService;\n\n   @Inject\n   ISO8601Format(DateService dateService) {\n      this.dateService = dateService;\n   }\n\n   @Override\n   public String apply(Object from) {\n      checkArgument(from instanceof Date, \"this binder is only valid for Date!\");\n      return dateService.iso8601SecondsDateFormat(Date.class.cast(from));\n   }\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/functions/ListAlarmHistoryToPagedIterable.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Function;\nimport com.google.inject.Inject;\nimport org.jclouds.cloudwatch.CloudWatchApi;\nimport org.jclouds.cloudwatch.domain.AlarmHistoryItem;\nimport org.jclouds.cloudwatch.features.AlarmApi;\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.internal.CallerArg0ToPagedIterable;\n\n@Beta\npublic class ListAlarmHistoryToPagedIterable\n      extends CallerArg0ToPagedIterable<AlarmHistoryItem, ListAlarmHistoryToPagedIterable> {\n\n   private final CloudWatchApi api;\n\n   @Inject\n   ListAlarmHistoryToPagedIterable(CloudWatchApi api) {\n      this.api = checkNotNull(api, \"api\");\n   }\n\n   @Override\n   protected Function<Object, IterableWithMarker<AlarmHistoryItem>> markerToNextForCallingArg0(final String arg0) {\n      final AlarmApi alarmApi = api.getAlarmApiForRegion(arg0);\n      return new Function<Object, IterableWithMarker<AlarmHistoryItem>>() {\n\n         @Override\n         public IterableWithMarker<AlarmHistoryItem> apply(Object input) {\n            return alarmApi.listHistoryAt(input.toString());\n         }\n\n         @Override\n         public String toString() {\n            return \"listHistory(\" + arg0 + \")\";\n         }\n      };\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/functions/ListAlarmsToPagedIterable.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Function;\nimport com.google.inject.Inject;\nimport org.jclouds.cloudwatch.CloudWatchApi;\nimport org.jclouds.cloudwatch.domain.Alarm;\nimport org.jclouds.cloudwatch.features.AlarmApi;\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.internal.CallerArg0ToPagedIterable;\n\n@Beta\npublic class ListAlarmsToPagedIterable\n      extends CallerArg0ToPagedIterable<Alarm, ListAlarmsToPagedIterable> {\n\n   private final CloudWatchApi api;\n\n   @Inject\n   ListAlarmsToPagedIterable(CloudWatchApi api) {\n      this.api = checkNotNull(api, \"api\");\n   }\n\n   @Override\n   protected Function<Object, IterableWithMarker<Alarm>> markerToNextForCallingArg0(final String arg0) {\n      final AlarmApi alarmApi = api.getAlarmApiForRegion(arg0);\n      return new Function<Object, IterableWithMarker<Alarm>>() {\n\n         @Override\n         public IterableWithMarker<Alarm> apply(Object input) {\n            return alarmApi.listAt(input.toString());\n         }\n\n         @Override\n         public String toString() {\n            return \"listAlarms(\" + arg0 + \")\";\n         }\n      };\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/functions/MetricsToPagedIterable.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.cloudwatch.CloudWatchApi;\nimport org.jclouds.cloudwatch.domain.Metric;\nimport org.jclouds.cloudwatch.features.MetricApi;\nimport org.jclouds.cloudwatch.options.ListMetricsOptions;\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.internal.CallerArg0ToPagedIterable;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Function;\n\n@Beta\npublic class MetricsToPagedIterable extends CallerArg0ToPagedIterable<Metric, MetricsToPagedIterable> {\n\n   private final CloudWatchApi api;\n\n   @Inject\n   protected MetricsToPagedIterable(CloudWatchApi api) {\n      this.api = checkNotNull(api, \"api\");\n   }\n\n   @Override\n   protected Function<Object, IterableWithMarker<Metric>> markerToNextForCallingArg0(final String arg0) {\n      final MetricApi metricApi = api.getMetricApiForRegion(arg0);\n      return new Function<Object, IterableWithMarker<Metric>>() {\n\n         @Override\n         public IterableWithMarker<Metric> apply(Object input) {\n            return metricApi.list(ListMetricsOptions.Builder.afterMarker(input.toString()));\n         }\n\n         @Override\n         public String toString() {\n            return \"listMetricsInRegion(\" + arg0 + \")\";\n         }\n      };\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/handlers/CloudWatchErrorHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.handlers;\n\nimport static org.jclouds.http.HttpUtils.closeClientButKeepContentStream;\nimport static org.jclouds.http.HttpUtils.releasePayload;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Provider;\nimport jakarta.inject.Singleton;\n\nimport com.google.common.annotations.Beta;\nimport org.jclouds.aws.AWSResponseException;\nimport org.jclouds.aws.domain.AWSError;\nimport org.jclouds.aws.xml.ErrorHandler;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.rest.InsufficientResourcesException;\n\n@Beta\n@Singleton\npublic class CloudWatchErrorHandler implements HttpErrorHandler {\n\n   private final ParseSax.Factory factory;\n   private final Provider<ErrorHandler> handlers;\n\n   @Inject\n   CloudWatchErrorHandler(ParseSax.Factory factory, Provider<ErrorHandler> handlers) {\n      this.factory = factory;\n      this.handlers = handlers;\n   }\n\n   @Override\n   public void handleError(HttpCommand command, HttpResponse response) {\n      Exception exception = new HttpResponseException(command, response);\n      try {\n         if (response.getPayload() != null) {\n            AWSError error = factory.create(handlers.get())\n                                    .parse(new String(closeClientButKeepContentStream(response)));\n            exception = refineException(new AWSResponseException(command, response, error));\n         }\n      } finally {\n         releasePayload(response);\n         command.setException(exception);\n      }\n   }\n\n   private Exception refineException(AWSResponseException in) {\n      int statusCode = in.getResponse().getStatusCode();\n      String errorCode = in.getError().getCode();\n      String message = in.getError().getMessage();\n\n      if (statusCode == 400) {\n         if (\"LimitExceeded\".equals(errorCode)) {\n            return new InsufficientResourcesException(message, in);\n         } else if (\"InvalidFormat\".equals(errorCode)) {\n            return new IllegalArgumentException(message, in);\n         }\n      }\n\n      return in;\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/options/GetMetricStatisticsOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.options;\n\nimport com.google.common.collect.Multimap;\nimport com.google.common.collect.Sets;\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.cloudwatch.domain.Dimension;\nimport org.jclouds.cloudwatch.domain.Unit;\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport java.util.Set;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\n/**\n * Options used to control metric statistics are returned\n * \n * @see <a\n *      href=\"http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference/index.html?API_GetMetricStatistics.html\"\n *      />\n */\npublic class GetMetricStatisticsOptions extends BaseHttpRequestOptions {\n\n   private Set<Dimension> dimensions;\n   \n   /**\n    * A dimension describing qualities of the metric.\n    *\n    * @param dimension the dimension describing the qualities of the metric\n    *\n    * @return this {@code Builder} object\n    */\n   public GetMetricStatisticsOptions dimension(Dimension dimension) {\n      if (dimensions == null) {\n         dimensions = Sets.newLinkedHashSet();\n      }\n      this.dimensions.add(dimension);\n      return this;\n   }\n   \n   /**\n    * A list of dimensions describing qualities of the metric.\n    *\n    * @param dimensions the dimensions describing the qualities of the metric\n    *\n    * @return this {@code Builder} object\n    */\n   public GetMetricStatisticsOptions dimensions(Set<Dimension> dimensions) {\n      this.dimensions = dimensions;\n      return this;\n   }\n   \n   /**\n    * @param instanceId\n    *           filter metrics by instance Id\n    */\n   public GetMetricStatisticsOptions instanceId(String instanceId) {\n      String[] parts = AWSUtils.parseHandle(instanceId);\n      this.formParameters.put(\"Dimensions.member.1.Name\", \"InstanceId\");\n      this.formParameters.put(\"Dimensions.member.1.Value\", checkNotNull(parts[1]));\n      return this;\n   }\n\n   /**\n    * @param unit\n    *          the unit of the metric\n    */\n   public GetMetricStatisticsOptions unit(Unit unit) {\n      this.formParameters.put(\"Unit\", unit.toString());\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see GetMetricStatisticsOptions#instanceId\n       */\n      public static GetMetricStatisticsOptions instanceId(String instanceId) {\n         GetMetricStatisticsOptions options = new GetMetricStatisticsOptions();\n         return options.instanceId(instanceId);\n      }\n\n      /**\n       * @see GetMetricStatisticsOptions#unit\n       */\n      public static GetMetricStatisticsOptions unit(Unit unit) {\n         GetMetricStatisticsOptions options = new GetMetricStatisticsOptions();\n         return options.unit(unit);\n      }\n      \n      /**\n       * @see GetMetricStatisticsOptions#dimension\n       */\n      public static GetMetricStatisticsOptions dimension(Dimension dimension) {\n         GetMetricStatisticsOptions options = new GetMetricStatisticsOptions();\n         return options.dimension(dimension);\n      }\n      \n      /**\n       * @see GetMetricStatisticsOptions#dimensions\n       */\n      public static GetMetricStatisticsOptions dimensions(Set<Dimension> dimensions) {\n         GetMetricStatisticsOptions options = new GetMetricStatisticsOptions();\n         return options.dimensions(dimensions);\n      }\n    }\n\n   @Override\n   public Multimap<String, String> buildFormParameters() {\n      Multimap<String, String> formParameters = super.buildFormParameters();\n      int dimensionIndex = 1;\n      if (dimensions != null) {\n         for (Dimension dimension : dimensions) {\n            formParameters.put(\"Dimensions.member.\" + dimensionIndex + \".Name\", dimension.getName());\n            formParameters.put(\"Dimensions.member.\" + dimensionIndex + \".Value\", dimension.getValue());\n            dimensionIndex++;\n         }\n      }\n      return formParameters;\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/options/ListAlarmHistoryOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.options;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Date;\n\nimport com.google.common.annotations.Beta;\nimport org.jclouds.cloudwatch.domain.HistoryItemType;\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\n/**\n * Options used to describe alarm history.\n *\n * @see <a href=\"http://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_DescribeAlarmHistory.html\" />\n */\n@Beta\npublic class ListAlarmHistoryOptions extends BaseHttpRequestOptions {\n\n   private static final DateService dateService = new SimpleDateFormatDateService();\n\n   /**\n    * The name of the alarm you want to filter against.\n    *\n    * @param alarmName the name of the alarm you want to filter against\n    *\n    * @return this {@code ListAlarmHistoryOptions} object\n    */\n   public ListAlarmHistoryOptions alarmName(String alarmName) {\n      checkNotNull(alarmName, \"alarmName\");\n      checkArgument(alarmName.length() <= 255, \"alarmName must be between 1 and 255 characters in length\");\n      formParameters.put(\"AlarmName\", alarmName);\n      return this;\n   }\n\n   /**\n    * The ending date to retrieve alarm history.\n    *\n    * @param endDate the ending date to retrieve alarm history\n    *\n    * @return this {@code ListAlarmHistoryOptions} object\n    */\n   public ListAlarmHistoryOptions endDate(Date endDate) {\n      formParameters.put(\"EndDate\", dateService.iso8601DateFormat(checkNotNull(endDate, \"endDate\")));\n      return this;\n   }\n\n   /**\n    * The type of alarm histories to retrieve.\n    *\n    * @param historyItemType type of alarm histories to retrieve\n    *\n    * @return this {@code ListAlarmHistoryOptions} object\n    */\n   public ListAlarmHistoryOptions historyItemType(HistoryItemType historyItemType) {\n      checkNotNull(historyItemType, \"historyItemType\");\n      checkArgument(historyItemType != HistoryItemType.UNRECOGNIZED, \"historyItemType unrecognized\");\n      formParameters.put(\"HistoryItemType\", historyItemType.toString());\n      return this;\n   }\n\n   /**\n    * The maximum number of alarm history records to retrieve.\n    *\n    * @param maxRecords maximum number of alarm history records to retrieve\n    *\n    * @return this {@code ListAlarmHistoryOptions} object\n    */\n   public ListAlarmHistoryOptions maxRecords(int maxRecords) {\n      formParameters.put(\"MaxRecords\", String.valueOf(maxRecords));\n      return this;\n   }\n\n   /**\n    * The starting date to retrieve alarm history.\n    *\n    * @param startDate the starting date to retrieve alarm history\n    *\n    * @return this {@code ListAlarmHistoryOptions} object\n    */\n   public ListAlarmHistoryOptions startDate(Date startDate) {\n      formParameters.put(\"StartDate\", dateService.iso8601DateFormat(checkNotNull(startDate, \"startDate\")));\n      return this;\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/options/ListAlarmsForMetric.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.options;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Set;\n\nimport com.google.common.annotations.Beta;\nimport org.jclouds.cloudwatch.domain.Dimension;\nimport org.jclouds.cloudwatch.domain.Statistics;\nimport org.jclouds.cloudwatch.domain.Unit;\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\n/**\n * Options used to describe alarms for metric.\n *\n * @see <a href=\"http://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_DescribeAlarmsForMetric.html\" />\n */\n@Beta\npublic class ListAlarmsForMetric extends BaseHttpRequestOptions {\n\n   int dimensionIndex = 1;\n\n   /**\n    * The list of dimensions associated with the metric.\n    *\n    * @param dimensions the list of dimensions associated with the metric\n    *\n    * @return this {@code ListAlarmsForMetric} object\n    */\n   public ListAlarmsForMetric dimensions(Set<Dimension> dimensions) {\n      for (Dimension dimension : checkNotNull(dimensions, \"dimensions\")) {\n         dimension(dimension);\n      }\n      return this;\n   }\n\n   /**\n    * The dimension associated with the metric.\n    *\n    * @param dimension the dimension associated with the metric\n    *\n    * @return this {@code ListAlarmsForMetric} object\n    */\n   public ListAlarmsForMetric dimension(Dimension dimension) {\n      checkNotNull(dimension, \"dimension\");\n      checkArgument(dimensionIndex <= 10, \"maximum number of dimensions is 10\");\n      formParameters.put(\"Dimensions.member.\" + dimensionIndex + \".Name\", dimension.getName());\n      formParameters.put(\"Dimensions.member.\" + dimensionIndex + \".Value\", dimension.getValue());\n      dimensionIndex++;\n      return this;\n   }\n\n   /**\n    * The name of the metric.\n    *\n    * @param metricName the name of the metric\n    *\n    * @return this {@code ListAlarmsForMetric} object\n    */\n   public ListAlarmsForMetric metricName(String metricName) {\n      checkNotNull(metricName, \"metricName\");\n      checkArgument(metricName.length() <= 255, \"metricName must be between 1 and 255 characters in length\");\n      formParameters.put(\"MetricName\", metricName);\n      return this;\n   }\n\n   /**\n    * The namespace of the metric.\n    *\n    * @param namespace namespace of the metric\n    *\n    * @return this {@code ListAlarmsForMetric} object\n    */\n   public ListAlarmsForMetric namespace(String namespace) {\n      checkNotNull(namespace, \"namespace\");\n      checkArgument(namespace.length() <= 255, \"namespace must be between 1 and 255 characters in length\");\n      formParameters.put(\"Namespace\", namespace);\n      return this;\n   }\n\n   /**\n    * The period in seconds over which the statistic is applied.\n    *\n    * @param period period in seconds over which the statistic is applied\n    *\n    * @return this {@code ListAlarmsForMetric} object\n    */\n   public ListAlarmsForMetric period(int period) {\n      formParameters.put(\"Period\", String.valueOf(period));\n      return this;\n   }\n\n   /**\n    * The statistic for the metric.\n    *\n    * @param statistic statistic for the metric\n    *\n    * @return this {@code ListAlarmsForMetric} object\n    */\n   public ListAlarmsForMetric statistic(Statistics statistic) {\n      checkNotNull(statistic, \"statistic\");\n      checkArgument(statistic != Statistics.UNRECOGNIZED, \"statistic unrecognized\");\n      formParameters.put(\"Statistic\", statistic.toString());\n      return this;\n   }\n\n   /**\n    * The unit for the metric.\n    *\n    * @param unit unit for the metric\n    *\n    * @return this {@code ListAlarmsForMetric} object\n    */\n   public ListAlarmsForMetric unit(Unit unit) {\n      checkNotNull(unit, \"unit\");\n      checkArgument(unit != Unit.UNRECOGNIZED, \"unit unrecognized\");\n      formParameters.put(\"Unit\", unit.toString());\n      return this;\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/options/ListAlarmsOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.options;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudwatch.domain.Alarm;\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\n/**\n * Options used to describe alarms.\n *\n * @see <a href=\"http://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_DescribeAlarms.html\" />\n */\npublic class ListAlarmsOptions extends BaseHttpRequestOptions {\n\n   int alarmIndex = 1;\n\n   /**\n    * The action name prefix.\n    *\n    * @param actionPrefix the action name prefix\n    *\n    * @return this {@code ListAlarmsOptions} object\n    */\n   public ListAlarmsOptions actionPrefix(String actionPrefix) {\n      checkNotNull(actionPrefix, \"actionPrefix\");\n      checkArgument(actionPrefix.length() <= 1024, \"actionPrefix must be between 1 and 1024 characters in length\");\n      formParameters.put(\"ActionPrefix\", actionPrefix);\n      return this;\n   }\n\n   /**\n    * The alarm name prefix.\n    *\n    * @param alarmNamePrefix the alarm name prefix\n    *\n    * @return this {@code ListAlarmsOptions} object\n    */\n   public ListAlarmsOptions alarmNamePrefix(String alarmNamePrefix) {\n      checkNotNull(alarmNamePrefix, \"alarmNamePrefix\");\n      checkArgument(alarmNamePrefix.length() <= 255, \"actionPrefix must be between 1 and 255 characters in length\");\n      formParameters.put(\"AlarmNamePrefix\", alarmNamePrefix);\n      return this;\n   }\n\n   /**\n    * The list of alarm names to retrieve information for.\n    *\n    * @param alarmNames the alarm names\n    *\n    * @return this {@code ListAlarmsOptions} object\n    */\n   public ListAlarmsOptions alarmNames(Set<String> alarmNames) {\n      for (String alarmName : checkNotNull(alarmNames, \"alarmNames\")) {\n         alarmName(alarmName);\n      }\n      return this;\n   }\n\n   /**\n    * The alarm name to retrieve information for.\n    *\n    * @param alarmName the alarm name\n    *\n    * @return this {@code ListAlarmsOptions} object\n    */\n   public ListAlarmsOptions alarmName(String alarmName) {\n      checkArgument(alarmIndex <= 100, \"maximum number of alarm names is 100\");\n      formParameters.put(\"AlarmNames.member.\" + alarmIndex, checkNotNull(alarmName, \"alarmName\"));\n      alarmIndex++;\n      return this;\n   }\n\n   /**\n    * The maximum number of alarm descriptions to retrieve.\n    *\n    * @param maxRecords  maximum number of alarm descriptions to retrieve\n    *\n    * @return this {@code ListAlarmsOptions} object\n    */\n   public ListAlarmsOptions maxRecords(int maxRecords) {\n      formParameters.put(\"MaxRecords\", String.valueOf(maxRecords));\n      return this;\n   }\n\n   /**\n    * The state value to be used in matching alarms.\n    *\n    * @param state state value to be used in matching alarms\n    *\n    * @return this {@code ListAlarmsOptions} object\n    */\n   public ListAlarmsOptions state(Alarm.State state) {\n      checkNotNull(state, \"state\");\n      checkArgument(state != Alarm.State.UNRECOGNIZED, \"state unrecognized\");\n      formParameters.put(\"StateValue\", state.toString());\n      return this;\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/options/ListMetricsOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.options;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudwatch.domain.Dimension;\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Multimap;\nimport com.google.common.collect.Sets;\n\n/**\n * Options used to list available metrics.\n *\n * @see <a href=\"http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference/API_ListMetrics.html\" />\n */\npublic class ListMetricsOptions extends BaseHttpRequestOptions implements Cloneable {\n\n   private Set<Dimension> dimensions = Sets.newLinkedHashSet();\n   private String metricName;\n   private String namespace;\n   private Object afterMarker;\n\n   /**\n    * The namespace to filter against.\n    *\n    * @param namespace the namespace to filter against\n    *\n    * @return this {@code Builder} object\n    */\n   public ListMetricsOptions namespace(String namespace) {\n      this.namespace = namespace;\n      return this;\n   }\n\n   /**\n    * The name of the metric to filter against.\n    *\n    * @param metricName the metric name to filter against\n    *\n    * @return this {@code Builder} object\n    */\n   public ListMetricsOptions metricName(String metricName) {\n      this.metricName = metricName;\n      return this;\n   }\n\n   /**\n    * A list of dimensions to filter against.\n    *\n    * @param dimensions the dimensions to filter against\n    *\n    * @return this {@code Builder} object\n    */\n   public ListMetricsOptions dimensions(Iterable<Dimension> dimensions) {\n      Iterables.addAll(this.dimensions, dimensions);\n      return this;\n   }\n\n   /**\n    * A dimension to filter the available metrics by.\n    *\n    * @param dimension a dimension to filter the returned metrics by\n    *\n    * @return this {@code Builder} object\n    */\n   public ListMetricsOptions dimension(Dimension dimension) {\n      this.dimensions.add(dimension);\n      return this;\n   }\n\n   /**\n    * The token returned by a previous call to indicate that there is more data available.\n    *\n    * @param afterMarker the next token indicating that there is more data available\n    *\n    * @return this {@code Builder} object\n    */\n   public ListMetricsOptions afterMarker(Object afterMarker) {\n      this.afterMarker = afterMarker;\n      return this;\n   }\n\n   /**\n    * Returns a newly-created {@code ListMetricsOptions} based on the contents of\n    * the {@code Builder}.\n    */\n   @Override\n   public Multimap<String, String> buildFormParameters() {\n      ImmutableMultimap.Builder<String, String> formParameters = ImmutableMultimap.<String, String>builder();\n      int dimensionIndex = 1;\n\n      // If namespace isn't specified, don't include it\n      if (namespace != null) {\n         formParameters.put(\"Namespace\", namespace);\n      }\n      // If metricName isn't specified, don't include it\n      if (metricName != null) {\n         formParameters.put(\"MetricName\", metricName);\n      }\n\n      // If dimensions isn't specified, don't include it\n      if (dimensions != null) {\n         for (Dimension dimension : dimensions) {\n            formParameters.put(\"Dimensions.member.\" + dimensionIndex + \".Name\", dimension.getName());\n            formParameters.put(\"Dimensions.member.\" + dimensionIndex + \".Value\", dimension.getValue());\n            dimensionIndex++;\n         }\n      }\n\n      // If afterMarker isn't specified, don't include it\n      if (afterMarker != null) {\n         formParameters.put(\"NextToken\", afterMarker.toString());\n      }\n\n      return formParameters.build();\n   }\n   \n   @Override\n   public ListMetricsOptions clone() {\n      return Builder.namespace(namespace).metricName(metricName).dimensions(dimensions).afterMarker(afterMarker);\n   }\n   \n   public static class Builder {\n\n      /**\n       * @see ListMetricsOptions#namespace(String)\n       */\n      public static ListMetricsOptions namespace(String namespace) {\n         return new ListMetricsOptions().namespace(namespace);\n      }\n\n      /**\n       * @see ListMetricsOptions#metricName(String)\n       */\n      public static ListMetricsOptions metricName(String metricName) {\n         return new ListMetricsOptions().metricName(metricName);\n      }\n\n      /**\n       * @see ListMetricsOptions#dimensions(Iterable)\n       */\n      public static ListMetricsOptions dimensions(Iterable<Dimension> dimensions) {\n         return new ListMetricsOptions().dimensions(dimensions);\n      }\n\n      /**\n       * @see ListMetricsOptions#dimension(Dimension)\n       */\n      public static ListMetricsOptions dimension(Dimension dimension) {\n         return new ListMetricsOptions().dimension(dimension);\n      }\n\n      /**\n       * @see ListMetricsOptions#afterMarker(Object)\n       */\n      public static ListMetricsOptions afterMarker(Object afterMarker) {\n         return new ListMetricsOptions().afterMarker(afterMarker);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/options/SaveAlarmOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.options;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Set;\n\nimport com.google.common.annotations.Beta;\nimport org.jclouds.cloudwatch.domain.ComparisonOperator;\nimport org.jclouds.cloudwatch.domain.Dimension;\nimport org.jclouds.cloudwatch.domain.Statistics;\nimport org.jclouds.cloudwatch.domain.Unit;\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\n/**\n * Options used to create/update an alarm.\n *\n * @see <a href=\"http://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_PutMetricAlarm.html\" />\n */\n@Beta\npublic class SaveAlarmOptions extends BaseHttpRequestOptions {\n\n   int alarmActionIndex = 1;\n   int dimensionIndex = 1;\n   int insufficientDataActionsIndex = 1;\n   int okActionsIndex = 1;\n\n   /**\n    * Indicates whether or not actions should be executed during any changes to the alarm's state.\n    *\n    * @param actionsEnabled indicates whether or not actions should be executed during any changes to the alarm's state\n    *\n    * @return this {@code SaveAlarmOptions} object\n    */\n   public SaveAlarmOptions actionsEnabled(boolean actionsEnabled) {\n      formParameters.put(\"ActionsEnabled\", String.valueOf(actionsEnabled));\n      return this;\n   }\n\n   /**\n    * The list of actions to execute when this alarm transitions into an ALARM state from any other state.\n    *\n    * @param alarmActions the list of actions to execute when this alarm transitions into an ALARM state from any other\n    *                     state\n    *\n    * @return this {@code SaveAlarmOptions} object\n    */\n   public SaveAlarmOptions alarmActions(Set<String> alarmActions) {\n      for (String alarmAction : checkNotNull(alarmActions, \"alarmActions\")) {\n         alarmAction(alarmAction);\n      }\n      return this;\n   }\n\n   /**\n    * The action to execute when this alarm transitions into an ALARM state from any other state.\n    *\n    * @param alarmAction the actions to execute when this alarm transitions into an ALARM state from any other state\n    *\n    * @return this {@code SaveAlarmOptions} object\n    */\n   public SaveAlarmOptions alarmAction(String alarmAction) {\n      checkArgument(alarmActionIndex <= 5, \"maximum number of alarm actions is 5\");\n      formParameters.put(\"AlarmActions.member.\" + alarmActionIndex, checkNotNull(alarmAction, \"alarmAction\"));\n      alarmActionIndex++;\n      return this;\n   }\n\n   /**\n    * The description of the alarm.\n    *\n    * @param alarmDescription the description of the alarm\n    *\n    * @return this {@code SaveAlarmOptions} object\n    */\n   public SaveAlarmOptions alarmDescription(String alarmDescription) {\n      formParameters.put(\"AlarmDescription\", checkNotNull(alarmDescription, \"alarmDescription\"));\n      return this;\n   }\n\n   /**\n    * The name of the alarm.\n    *\n    * @param alarmName the name of the alarm\n    *\n    * @return this {@code SaveAlarmOptions} object\n    */\n   public SaveAlarmOptions alarmName(String alarmName) {\n      formParameters.put(\"AlarmName\", checkNotNull(alarmName, \"alarmName\"));\n      return this;\n   }\n\n   /**\n    * The arithmetic operation to use when comparing the specified statistic and threshold.\n    *\n    * @param comparisonOperator the arithmetic operation to use when comparing the specified statistic and threshold\n    *\n    * @return this {@code SaveAlarmOptions} object\n    */\n   public SaveAlarmOptions comparisonOperator(ComparisonOperator comparisonOperator) {\n      checkNotNull(comparisonOperator, \"comparisonOperator\");\n      checkArgument(comparisonOperator != ComparisonOperator.UNRECOGNIZED, \"comparisonOperator unrecognized\");\n      formParameters.put(\"ComparisonOperator\", comparisonOperator.toString());\n      return this;\n   }\n\n   /**\n    * The dimensions for the alarm's associated metric.\n    *\n    * @param dimensions the dimensions for the alarm's associated metric\n    *\n    * @return this {@code SaveAlarmOptions} object\n    */\n   public SaveAlarmOptions dimensions(Set<Dimension> dimensions) {\n      for (Dimension dimension : checkNotNull(dimensions, \"dimensions\")) {\n         dimension(dimension);\n      }\n      return this;\n   }\n\n   /**\n    * The dimension for the alarm's associated metric.\n    *\n    * @param dimension the dimension for the alarm's associated metric\n    *\n    * @return this {@code SaveAlarmOptions} object\n    */\n   public SaveAlarmOptions dimension(Dimension dimension) {\n      checkNotNull(dimension, \"dimension\");\n      checkArgument(dimensionIndex <= 10, \"maximum number of dimensions is 10\");\n      formParameters.put(\"Dimensions.member.\" + dimensionIndex + \".Name\", dimension.getName());\n      formParameters.put(\"Dimensions.member.\" + dimensionIndex + \".Value\", dimension.getValue());\n      dimensionIndex++;\n      return this;\n   }\n\n   /**\n    * The number of periods over which data is compared to the specified threshold.\n    *\n    * @param evaluationPeriods the number of periods over which data is compared to the specified threshold\n    *\n    * @return this {@code SaveAlarmOptions} object\n    */\n   public SaveAlarmOptions evaluationPeriods(int evaluationPeriods) {\n      formParameters.put(\"EvaluationPeriods\", String.valueOf(evaluationPeriods));\n      return this;\n   }\n\n   /**\n    * The list of actions to execute when this alarm transitions into an INSUFFICIENT_DATA state from any other state.\n    *\n    * @param insufficientDataActions the list of actions to execute when this alarm transitions into an\n    *                                INSUFFICIENT_DATA state from any other state\n    *\n    * @return this {@code SaveAlarmOptions} object\n    */\n   public SaveAlarmOptions insufficientDataActions(Set<String> insufficientDataActions) {\n      for (String insufficientDataAction : checkNotNull(insufficientDataActions)) {\n         insufficientDataAction(insufficientDataAction);\n      }\n      return this;\n   }\n\n   /**\n    * The actions to execute when this alarm transitions into an INSUFFICIENT_DATA state from any other state.\n    *\n    * @param insufficientDataAction the action to execute when this alarm transitions into an INSUFFICIENT_DATA state\n    *                               from any other state\n    *\n    * @return this {@code SaveAlarmOptions} object\n    */\n   public SaveAlarmOptions insufficientDataAction(String insufficientDataAction) {\n      checkNotNull(insufficientDataAction, \"insufficientDataAction\");\n      checkArgument(insufficientDataActionsIndex <= 5, \"maximum number of insufficient data actions is 5\");\n      formParameters.put(\"InsufficientDataActions.member.\" + insufficientDataActionsIndex, insufficientDataAction);\n      insufficientDataActionsIndex++;\n      return this;\n   }\n\n   /**\n    * The name for the alarm's associated metric.\n    *\n    * @param metricName the name for the alarm's associated metric\n    *\n    * @return this {@code SaveAlarmOptions} object\n    */\n   public SaveAlarmOptions metricName(String metricName) {\n      formParameters.put(\"MetricName\", checkNotNull(metricName, \"metricName\"));\n      return this;\n   }\n\n   /**\n    * The namespace for the alarm's associated metric.\n    *\n    * @param namespace the namespace for the alarm's associated metric\n    *\n    * @return this {@code SaveAlarmOptions} object\n    */\n   public SaveAlarmOptions namespace(String namespace) {\n      formParameters.put(\"Namespace\", checkNotNull(namespace));\n      return this;\n   }\n\n   /**\n    * The list of actions to execute when this alarm transitions into an OK state from any other state.\n    *\n    * @param okActions the list of actions to execute when this alarm transitions into an OK state from any other state\n    *\n    * @return this {@code SaveAlarmOptions} object\n    */\n   public SaveAlarmOptions okActions(Set<String> okActions) {\n      for (String okAction : checkNotNull(okActions, \"okActions\")) {\n         okAction(okAction);\n      }\n      return this;\n   }\n\n   /**\n    * The action to execute when this alarm transitions into an OK state from any other state.\n    *\n    * @param okAction the action to execute when this alarm transitions into an OK state from any other state\n    *\n    * @return this {@code SaveAlarmOptions} object\n    */\n   public SaveAlarmOptions okAction(String okAction) {\n      checkNotNull(okAction, \"okAction\");\n      checkArgument(okActionsIndex <= 5, \"maximum number of ok actions is 5\");\n      formParameters.put(\"OKActions.member.\" + okActionsIndex, okAction);\n      okActionsIndex++;\n      return this;\n   }\n\n   /**\n    * The period in seconds over which the specified statistic is applied.\n    *\n    * @param period the period in seconds over which the specified statistic is applied\n    *\n    * @return this {@code SaveAlarmOptions} object\n    */\n   public SaveAlarmOptions period(int period) {\n      formParameters.put(\"Period\", String.valueOf(period));\n      return this;\n   }\n\n   /**\n    * The statistic to apply to the alarm's associated metric.\n    *\n    * @param statistic the statistic to apply to the alarm's associated metric\n    *\n    * @return this {@code SaveAlarmOptions} object\n    */\n   public SaveAlarmOptions statistic(Statistics statistic) {\n      checkNotNull(statistic, \"statistic\");\n      checkArgument(statistic != Statistics.UNRECOGNIZED, \"statistic unrecognized\");\n      formParameters.put(\"Statistic\", statistic.toString());\n      return this;\n   }\n\n   /**\n    * The value against which the specified statistic is compared.\n    *\n    * @param threshold the value against which the specified statistic is compared\n    *\n    * @return this {@code SaveAlarmOptions} object\n    */\n   public SaveAlarmOptions threshold(double threshold) {\n      formParameters.put(\"Threshold\", String.valueOf(threshold));\n      return this;\n   }\n\n   /**\n    * The unit for the alarm's associated metric.\n    *\n    * @param unit the unit for the alarm's associated metric\n    *\n    * @return this {@code SaveAlarmOptions} object\n    */\n   public SaveAlarmOptions unit(Unit unit) {\n      checkNotNull(unit, \"unit\");\n      checkArgument(unit != Unit.UNRECOGNIZED, \"unit unrecognized\");\n      formParameters.put(\"Unit\", unit.toString());\n      return this;\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/xml/AlarmHistoryItemHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.xml;\n\nimport jakarta.inject.Inject;\nimport java.util.Date;\n\nimport com.google.common.annotations.Beta;\nimport org.jclouds.cloudwatch.domain.AlarmHistoryItem;\nimport org.jclouds.cloudwatch.domain.HistoryItemType;\nimport org.jclouds.date.DateService;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.util.SaxUtils;\nimport org.xml.sax.SAXException;\n\n/**\n * @see <a href=\"http://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_AlarmHistoryItem.html\" />\n */\n@Beta\npublic class AlarmHistoryItemHandler extends ParseSax.HandlerForGeneratedRequestWithResult<AlarmHistoryItem> {\n\n   protected final DateService dateService;\n\n   private StringBuilder currentText = new StringBuilder();\n   private String alarmName;\n   private String historyData;\n   private HistoryItemType historyItemType;\n   private String historySummary;\n   private Date timestamp;\n\n   @Inject\n   public AlarmHistoryItemHandler(DateService dateService) {\n      this.dateService = dateService;\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) throws SAXException {\n      if (qName.equals(\"AlarmName\")) {\n         alarmName = SaxUtils.currentOrNull(currentText);\n      } else if (qName.equals(\"HistoryData\")) {\n         String rawJson = SaxUtils.currentOrNull(currentText);\n\n         if (rawJson != null) {\n            historyData = rawJson.trim();\n         }\n      } else if (qName.equals(\"HistoryItemType\")) {\n         historyItemType = HistoryItemType.fromValue(SaxUtils.currentOrNull(currentText));\n      } else if (qName.equals(\"HistorySummary\")) {\n         historySummary = SaxUtils.currentOrNull(currentText);\n      } else if (qName.equals(\"Timestamp\")) {\n         timestamp = dateService.iso8601DateParse(currentText.toString().trim());\n      }\n\n      currentText.setLength(0);\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n\n   @Override\n   public AlarmHistoryItem getResult() {\n      AlarmHistoryItem result = new AlarmHistoryItem(alarmName, historyData, historyItemType, historySummary,\n                                                     timestamp);\n\n      alarmName = null;\n      historyData = null;\n      historyItemType = null;\n      historySummary = null;\n      timestamp = null;\n\n      return result;\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/xml/DatapointHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.xml;\n\nimport org.jclouds.cloudwatch.domain.Datapoint;\nimport org.jclouds.cloudwatch.domain.Unit;\nimport org.jclouds.date.DateService;\nimport org.jclouds.http.functions.ParseSax;\n\nimport jakarta.inject.Inject;\nimport java.util.Date;\n\npublic class DatapointHandler extends ParseSax.HandlerForGeneratedRequestWithResult<Datapoint> {\n   private StringBuilder currentText = new StringBuilder();\n\n   protected final DateService dateService;\n   private Double average;\n   private Double maximum;\n   private Double minimum;\n   private Date timestamp;\n   private Double samples;\n   private Double sum;\n   private Unit unit;\n   private String customUnit;\n\n   @Inject\n   public DatapointHandler(DateService dateService) {\n      this.dateService = dateService;\n   }\n\n   public Datapoint getResult() {\n      Datapoint datapoint = new Datapoint(average, maximum, minimum, timestamp, samples, sum, unit, customUnit);\n      this.average = null;\n      this.maximum = null;\n      this.minimum = null;\n      this.timestamp = null;\n      this.samples = null;\n      this.sum = null;\n      this.unit = null;\n      this.customUnit = null;\n      return datapoint;\n   }\n\n   public void endElement(String uri, String name, String qName) {\n      if (qName.equals(\"Average\")) {\n         average = doubleOrNull();\n      } else if (qName.equals(\"Maximum\")) {\n         maximum = doubleOrNull();\n      } else if (qName.equals(\"Minimum\")) {\n         minimum = doubleOrNull();\n      } else if (qName.equals(\"Timestamp\")) {\n         timestamp = dateService.iso8601SecondsDateParse(currentText.toString().trim());\n      } else if (qName.equals(\"SampleCount\")) {\n         samples = doubleOrNull();\n      } else if (qName.equals(\"Sum\")) {\n         sum = doubleOrNull();\n      } else if (qName.equals(\"Unit\")) {\n         unit = Unit.fromValue(currentText.toString().trim());\n      } else if (qName.equals(\"CustomUnit\")) {\n         customUnit = currentText.toString().trim();\n      }\n      currentText.setLength(0);\n   }\n\n   private Double doubleOrNull() {\n      String string = currentText.toString().trim();\n      if (!string.equals(\"\")) {\n         return Double.valueOf(string);\n      }\n      return null;\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/xml/DimensionHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.xml;\n\nimport org.jclouds.cloudwatch.domain.Dimension;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.util.SaxUtils;\nimport org.xml.sax.SAXException;\n\n/**\n * @see <a href=\"http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference/API_Dimension.html\" />\n */\npublic class DimensionHandler extends ParseSax.HandlerForGeneratedRequestWithResult<Dimension> {\n\n   private StringBuilder currentText = new StringBuilder();\n   private String name;\n   private String value;\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Dimension getResult() {\n      Dimension dimension = new Dimension(name, value);\n\n      // Reset since this handler is created once but produces N results\n      name = null;\n      value = null;\n\n      return dimension;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void endElement(String uri, String name, String qName) throws SAXException {\n      if (qName.equals(\"Name\")) {\n         this.name = SaxUtils.currentOrNull(currentText);\n      } else if (qName.equals(\"Value\")) {\n         value = SaxUtils.currentOrNull(currentText);\n      }\n      currentText.setLength(0);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/xml/GetMetricStatisticsResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.xml;\n\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.cloudwatch.domain.Datapoint;\nimport org.jclouds.http.functions.ParseSax;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\n\nimport com.google.common.collect.Sets;\n\npublic class GetMetricStatisticsResponseHandler extends ParseSax.HandlerWithResult<Set<Datapoint>> {\n\n   private Set<Datapoint> datapoints = Sets.newLinkedHashSet();\n   private final DatapointHandler datapointHandler;\n\n   @Inject\n   public GetMetricStatisticsResponseHandler(DatapointHandler datapointHandler) {\n      this.datapointHandler = datapointHandler;\n   }\n\n   public Set<Datapoint> getResult() {\n      return datapoints;\n   }\n\n   @Override\n   public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {\n      datapointHandler.startElement(uri, localName, qName, attributes);\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) throws SAXException {\n      datapointHandler.endElement(uri, localName, qName);\n      if (qName.equals(\"member\")) {\n         this.datapoints.add(datapointHandler.getResult());\n      }\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      datapointHandler.characters(ch, start, length);\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/xml/GetMetricStatisticsResponseHandlerV2.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.xml;\n\nimport com.google.common.collect.Sets;\nimport org.jclouds.cloudwatch.domain.Datapoint;\nimport org.jclouds.cloudwatch.domain.GetMetricStatisticsResponse;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.util.SaxUtils;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\n\nimport jakarta.inject.Inject;\nimport java.util.Set;\n\n/**\n * @see <a href=\"http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference/API_GetMetricStatistics.html\" />\n */\npublic class GetMetricStatisticsResponseHandlerV2 extends ParseSax.HandlerWithResult<GetMetricStatisticsResponse> {\n\n   private StringBuilder currentText = new StringBuilder();\n   private Set<Datapoint> datapoints = Sets.newLinkedHashSet();\n   private String label;\n   private final DatapointHandler datapointHandler;\n   private boolean inDatapoints;\n\n   @Inject\n   public GetMetricStatisticsResponseHandlerV2(DatapointHandler datapointHandler) {\n      this.datapointHandler = datapointHandler;\n   }\n\n   public GetMetricStatisticsResponse getResult() {\n      return new GetMetricStatisticsResponse(datapoints, label);\n   }\n\n   @Override\n   public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {\n      if (qName.equals(\"Datapoints\")) {\n         inDatapoints = true;\n      }\n      if (inDatapoints) {\n         datapointHandler.startElement(uri, localName, qName, attributes);\n      }\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) throws SAXException {\n      if (inDatapoints) {\n         if (qName.equals(\"Datapoints\")) {\n            inDatapoints = false;\n         } else {\n            datapointHandler.endElement(uri, localName, qName);\n            if (qName.equals(\"member\")) {\n               this.datapoints.add(datapointHandler.getResult());\n            }\n         }\n      } else if (qName.equals(\"Label\")) {\n         label = SaxUtils.currentOrNull(currentText);\n      }\n\n      currentText.setLength(0);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      if (inDatapoints) {\n         datapointHandler.characters(ch, start, length);\n      } else {\n         currentText.append(ch, start, length);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/xml/ListAlarmHistoryResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.xml;\n\nimport java.util.Set;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.collect.Sets;\nimport com.google.inject.Inject;\nimport org.jclouds.cloudwatch.domain.AlarmHistoryItem;\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.IterableWithMarkers;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.util.SaxUtils;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\n\n/**\n * @see <a href=\"http://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_DescribeAlarmHistory.html\" />\n */\n@Beta\npublic class ListAlarmHistoryResponseHandler\n      extends ParseSax.HandlerForGeneratedRequestWithResult<IterableWithMarker<AlarmHistoryItem>> {\n\n   private final AlarmHistoryItemHandler alarmHistoryItemHandler;\n\n   private StringBuilder currentText = new StringBuilder();\n   private Set<AlarmHistoryItem> alarmHistoryItems = Sets.newLinkedHashSet();\n   private String nextToken;\n   private boolean inAlarmHistoryItems;\n\n   @Inject\n   public ListAlarmHistoryResponseHandler(AlarmHistoryItemHandler alarmHistoryItemHandler) {\n      this.alarmHistoryItemHandler = alarmHistoryItemHandler;\n   }\n\n   @Override\n   public void startElement(String url, String name, String qName, Attributes attributes) throws SAXException {\n      if (SaxUtils.equalsOrSuffix(qName, \"AlarmHistoryItems\")) {\n         inAlarmHistoryItems = true;\n      }\n      if (inAlarmHistoryItems) {\n         alarmHistoryItemHandler.startElement(url, name, qName, attributes);\n      }\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) throws SAXException {\n      if (inAlarmHistoryItems) {\n         if (qName.equals(\"AlarmHistoryItems\")) {\n            inAlarmHistoryItems = false;\n         } else if (qName.equals(\"member\")) {\n            alarmHistoryItems.add(alarmHistoryItemHandler.getResult());\n         } else {\n            alarmHistoryItemHandler.endElement(uri, name, qName);\n         }\n      } else if (qName.equals(\"NextToken\")) {\n         nextToken = SaxUtils.currentOrNull(currentText);\n      }\n\n      currentText.setLength(0);\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      if (inAlarmHistoryItems) {\n         alarmHistoryItemHandler.characters(ch, start, length);\n      } else {\n         currentText.append(ch, start, length);\n      }\n   }\n\n   @Override\n   public IterableWithMarker<AlarmHistoryItem> getResult() {\n      IterableWithMarker<AlarmHistoryItem> result = IterableWithMarkers.from(alarmHistoryItems, nextToken);\n\n      alarmHistoryItems = Sets.newLinkedHashSet();\n      nextToken = null;\n\n      return result;\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/xml/ListAlarmsForMetricResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.xml;\n\nimport java.util.Set;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.Sets;\nimport com.google.inject.Inject;\nimport org.jclouds.cloudwatch.domain.Alarm;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.util.SaxUtils;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\n\n/**\n * @see <a href=\"http://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_DescribeAlarmsForMetric.html\" />\n */\n@Beta\npublic class ListAlarmsForMetricResponseHandler\n      extends ParseSax.HandlerForGeneratedRequestWithResult<Iterable<Alarm>> {\n\n   private final MetricAlarmHandler metricAlarmHandler;\n\n   private StringBuilder currentText = new StringBuilder();\n   private Set<Alarm> alarms = Sets.newLinkedHashSet();\n   private boolean inMetricAlarms;\n\n   @Inject\n   public ListAlarmsForMetricResponseHandler(MetricAlarmHandler metricAlarmHandler) {\n      this.metricAlarmHandler = metricAlarmHandler;\n   }\n\n   @Override\n   public void startElement(String url, String name, String qName, Attributes attributes) throws SAXException {\n      if (SaxUtils.equalsOrSuffix(qName, \"MetricAlarms\")) {\n         inMetricAlarms = true;\n      }\n      if (inMetricAlarms) {\n         metricAlarmHandler.startElement(url, name, qName, attributes);\n      }\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) throws SAXException {\n      if (inMetricAlarms) {\n         if (qName.equals(\"MetricAlarms\")) {\n            inMetricAlarms = false;\n         } else if (qName.equals(\"member\") && !metricAlarmHandler.shouldHandleMemberTag()) {\n            alarms.add(metricAlarmHandler.getResult());\n         } else {\n            metricAlarmHandler.endElement(uri, name, qName);\n         }\n      }\n\n      currentText.setLength(0);\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      if (inMetricAlarms) {\n         metricAlarmHandler.characters(ch, start, length);\n      } else {\n         currentText.append(ch, start, length);\n      }\n   }\n\n   @Override\n   public FluentIterable<Alarm> getResult() {\n      FluentIterable<Alarm> result = FluentIterable.from(alarms);\n\n      alarms = Sets.newLinkedHashSet();\n\n      return result;\n   }\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/xml/ListAlarmsResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.xml;\n\nimport java.util.Set;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.collect.Sets;\nimport com.google.inject.Inject;\nimport org.jclouds.cloudwatch.domain.Alarm;\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.IterableWithMarkers;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.util.SaxUtils;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\n\n/**\n * @see <a href=\"http://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_DescribeAlarms.html\" />\n */\n@Beta\npublic class ListAlarmsResponseHandler\n      extends ParseSax.HandlerForGeneratedRequestWithResult<IterableWithMarker<Alarm>> {\n\n   private final MetricAlarmHandler metricAlarmHandler;\n\n   private StringBuilder currentText = new StringBuilder();\n   private Set<Alarm> alarms = Sets.newLinkedHashSet();\n   private String nextToken;\n   private boolean inMetricAlarms;\n\n   @Inject\n   public ListAlarmsResponseHandler(MetricAlarmHandler metricAlarmHandler) {\n      this.metricAlarmHandler = metricAlarmHandler;\n   }\n\n   @Override\n   public void startElement(String url, String name, String qName, Attributes attributes) throws SAXException {\n      if (SaxUtils.equalsOrSuffix(qName, \"MetricAlarms\")) {\n         inMetricAlarms = true;\n      }\n      if (inMetricAlarms) {\n         metricAlarmHandler.startElement(url, name, qName, attributes);\n      }\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) throws SAXException {\n      if (inMetricAlarms) {\n         if (qName.equals(\"MetricAlarms\")) {\n            inMetricAlarms = false;\n         } else if (qName.equals(\"member\") && !metricAlarmHandler.shouldHandleMemberTag()) {\n            alarms.add(metricAlarmHandler.getResult());\n         } else {\n            metricAlarmHandler.endElement(uri, name, qName);\n         }\n      } else if (qName.equals(\"NextToken\")) {\n         nextToken = SaxUtils.currentOrNull(currentText);\n      }\n\n      currentText.setLength(0);\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      if (inMetricAlarms) {\n         metricAlarmHandler.characters(ch, start, length);\n      } else {\n         currentText.append(ch, start, length);\n      }\n   }\n\n   @Override\n   public IterableWithMarker<Alarm> getResult() {\n      IterableWithMarker<Alarm> result = IterableWithMarkers.from(alarms, nextToken);\n\n      alarms = Sets.newLinkedHashSet();\n      nextToken = null;\n\n      return result;\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/xml/ListMetricsResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.xml;\n\nimport java.util.Set;\n\nimport org.jclouds.cloudwatch.domain.Metric;\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.IterableWithMarkers;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.util.SaxUtils;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\n\nimport com.google.common.collect.Sets;\nimport com.google.inject.Inject;\n\n/**\n * @see <a href=\"http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference/API_ListMetrics.html\" />\n */\npublic class ListMetricsResponseHandler extends ParseSax.HandlerForGeneratedRequestWithResult<IterableWithMarker<Metric>> {\n\n   private final MetricHandler metricHandler;\n\n   private StringBuilder currentText = new StringBuilder();\n   private Set<Metric> metrics = Sets.newLinkedHashSet();\n   private boolean inMetrics;\n   private String nextToken;\n\n   @Inject\n   public ListMetricsResponseHandler(MetricHandler metricHandler) {\n      this.metricHandler = metricHandler;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public IterableWithMarker<Metric> getResult() {\n      return IterableWithMarkers.from(metrics, nextToken);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void startElement(String url, String name, String qName, Attributes attributes) throws SAXException {\n      if (SaxUtils.equalsOrSuffix(qName, \"Metrics\")) {\n         inMetrics = true;\n      }\n      if (inMetrics) {\n         metricHandler.startElement(url, name, qName, attributes);\n      }\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void endElement(String uri, String name, String qName) throws SAXException {\n      if (inMetrics) {\n         if (qName.equals(\"Metrics\")) {\n            inMetrics = false;\n         } else if (qName.equals(\"member\") && !metricHandler.inDimensions()) {\n            metrics.add(metricHandler.getResult());\n         } else {\n            metricHandler.endElement(uri, name, qName);\n         }\n      } else if (qName.equals(\"NextToken\")) {\n         nextToken = SaxUtils.currentOrNull(currentText);\n      }\n\n      currentText.setLength(0);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      if (inMetrics) {\n         metricHandler.characters(ch, start, length);\n      } else {\n         currentText.append(ch, start, length);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/xml/MetricAlarmHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.xml;\n\nimport java.util.Date;\nimport java.util.Set;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.Sets;\nimport com.google.inject.Inject;\nimport org.jclouds.cloudwatch.domain.Alarm;\nimport org.jclouds.cloudwatch.domain.ComparisonOperator;\nimport org.jclouds.cloudwatch.domain.Dimension;\nimport org.jclouds.cloudwatch.domain.Statistics;\nimport org.jclouds.cloudwatch.domain.Unit;\nimport org.jclouds.date.DateService;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.util.SaxUtils;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\n\n/**\n * @see <a href=\"http://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_MetricAlarm.html\" />\n */\n@Beta\npublic class MetricAlarmHandler extends ParseSax.HandlerForGeneratedRequestWithResult<Alarm> {\n\n   protected final DateService dateService;\n   protected final DimensionHandler dimensionHandler;\n\n   private StringBuilder currentText = new StringBuilder();\n   private Set<String> alarmActions = Sets.newLinkedHashSet();\n   private Set<Dimension> dimensions = Sets.newLinkedHashSet();\n   private Set<String> insufficientDataActions = Sets.newLinkedHashSet();\n   private Set<String> okActions = Sets.newLinkedHashSet();\n   private boolean inAlarmActions = false;\n   private boolean inDimensions = false;\n   private boolean inInsufficientDataActions = false;\n   private boolean inOkActions = false;\n   private boolean actionsEnabled;\n   private String alarmARN;\n   private Date alarmConfigurationUpdatedTimestamp;\n   private String alarmDescription;\n   private String alarmName;\n   private ComparisonOperator comparisonOperator;\n   private int evaluationPeriods;\n   private String metricName;\n   private String namespace;\n   private int period;\n   private String stateReason;\n   private String stateReasonData;\n   private Date stateUpdatedTimestamp;\n   private Alarm.State state;\n   private Statistics statistic;\n   private double threshold;\n   private Unit unit;\n\n   @Inject\n   public MetricAlarmHandler(DateService dateService, DimensionHandler dimensionHandler) {\n      this.dateService = dateService;\n      this.dimensionHandler = dimensionHandler;\n   }\n\n   public boolean shouldHandleMemberTag() {\n      return inAlarmActions || inDimensions || inInsufficientDataActions || inOkActions;\n   }\n\n   @Override\n   public void startElement(String url, String name, String qName, Attributes attributes) throws SAXException {\n      if (SaxUtils.equalsOrSuffix(qName, \"AlarmActions\")) {\n         inAlarmActions = true;\n      } else if (SaxUtils.equalsOrSuffix(qName, \"Dimensions\")) {\n         inDimensions = true;\n      } else if (SaxUtils.equalsOrSuffix(qName, \"InsufficientDataActions\") ||\n            SaxUtils.equalsOrSuffix(qName, \"UnknownActions\")) {\n         inInsufficientDataActions = true;\n      } else if (SaxUtils.equalsOrSuffix(qName, \"OKActions\")) {\n         inOkActions = true;\n      }\n      if (inDimensions) {\n         dimensionHandler.startElement(url, name, qName, attributes);\n      }\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) throws SAXException {\n      if (inAlarmActions) {\n         if (qName.equals(\"AlarmActions\")) {\n            inAlarmActions = false;\n         } else if (qName.equals(\"member\")) {\n            alarmActions.add(SaxUtils.currentOrNull(currentText));\n         }\n      } else if (inDimensions) {\n         if (qName.equals(\"Dimensions\")) {\n            inDimensions = false;\n         } else if (qName.equals(\"member\")) {\n            dimensions.add(dimensionHandler.getResult());\n         } else {\n            dimensionHandler.endElement(uri, name, qName);\n         }\n      } else if (inInsufficientDataActions) {\n         if (qName.equals(\"InsufficientDataActions\") || qName.equals(\"UnknownActions\")) {\n            inInsufficientDataActions = false;\n         } else if (qName.equals(\"member\")) {\n            insufficientDataActions.add(SaxUtils.currentOrNull(currentText));\n         }\n      } else if (inOkActions) {\n         if (qName.equals(\"OKActions\")) {\n            inOkActions = false;\n         } else if (qName.equals(\"member\")) {\n            okActions.add(SaxUtils.currentOrNull(currentText));\n         }\n      } else if (qName.equals(\"ActionsEnabled\")) {\n         actionsEnabled = Boolean.valueOf(SaxUtils.currentOrNull(currentText));\n      } else if (qName.equals(\"AlarmArn\")) {\n         alarmARN = SaxUtils.currentOrNull(currentText);\n      } else if (qName.equals(\"AlarmConfigurationUpdatedTimestamp\")) {\n         alarmConfigurationUpdatedTimestamp = dateService.iso8601DateParse(currentText.toString().trim());\n      } else if (qName.equals(\"AlarmDescription\")) {\n         alarmDescription = SaxUtils.currentOrNull(currentText);\n      } else if (qName.equals(\"AlarmName\")) {\n         alarmName = SaxUtils.currentOrNull(currentText);\n      } else if (qName.equals(\"ComparisonOperator\")) {\n         comparisonOperator = ComparisonOperator.fromValue(SaxUtils.currentOrNull(currentText));\n      } else if (qName.equals(\"EvaluationPeriods\")) {\n         evaluationPeriods = Integer.parseInt(SaxUtils.currentOrNull(currentText));\n      } else if (qName.equals(\"MetricName\")) {\n         metricName = SaxUtils.currentOrNull(currentText);\n      } else if (qName.equals(\"Namespace\")) {\n         namespace = SaxUtils.currentOrNull(currentText);\n      } else if (qName.equals(\"Period\")) {\n         period = Integer.parseInt(SaxUtils.currentOrNull(currentText));\n      } else if (qName.equals(\"StateReason\")) {\n         stateReason = SaxUtils.currentOrNull(currentText);\n      } else if (qName.equals(\"StateReasonData\")) {\n         String rawJson = SaxUtils.currentOrNull(currentText);\n\n         if (rawJson != null) {\n            stateReasonData = rawJson.trim();\n         }\n      } else if (qName.equals(\"StateUpdatedTimestamp\")) {\n         stateUpdatedTimestamp = dateService.iso8601DateParse(currentText.toString().trim());\n      } else if (qName.equals(\"StateValue\")) {\n         state = Alarm.State.fromValue(SaxUtils.currentOrNull(currentText));\n      } else if (qName.equals(\"Statistic\")) {\n         statistic = Statistics.fromValue(SaxUtils.currentOrNull(currentText));\n      } else if (qName.equals(\"Threshold\")) {\n         threshold = Double.valueOf(SaxUtils.currentOrNull(currentText));\n      } else if (qName.equals(\"Unit\")) {\n         unit = Unit.fromValue(SaxUtils.currentOrNull(currentText));\n      }\n\n      currentText.setLength(0);\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      if (inDimensions) {\n         dimensionHandler.characters(ch, start, length);\n      } else {\n         currentText.append(ch, start, length);\n      }\n   }\n\n   @Override\n   public Alarm getResult() {\n      Alarm result = new Alarm(actionsEnabled, alarmActions, alarmARN, alarmConfigurationUpdatedTimestamp,\n                                           alarmDescription, alarmName, comparisonOperator, dimensions,\n                                           evaluationPeriods, insufficientDataActions, metricName, namespace, okActions,\n                                           period, stateReason, Optional.fromNullable(stateReasonData),\n                                           stateUpdatedTimestamp, state, statistic, threshold,\n                                           Optional.fromNullable(unit));\n\n      actionsEnabled = false;\n      alarmActions = Sets.newLinkedHashSet();\n      alarmARN = null;\n      alarmConfigurationUpdatedTimestamp = null;\n      alarmDescription = null;\n      alarmName = null;\n      comparisonOperator = null;\n      dimensions = Sets.newLinkedHashSet();\n      evaluationPeriods = 0;\n      insufficientDataActions = Sets.newLinkedHashSet();\n      metricName = null;\n      namespace = null;\n      okActions = Sets.newLinkedHashSet();\n      period = 0;\n      stateReason = null;\n      stateReasonData = null;\n      stateUpdatedTimestamp = null;\n      state = null;\n      statistic = null;\n      threshold = 0.0;\n      unit = null;\n\n      return result;\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/xml/MetricHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.xml;\n\nimport com.google.common.collect.Sets;\nimport com.google.inject.Inject;\nimport org.jclouds.cloudwatch.domain.Dimension;\nimport org.jclouds.cloudwatch.domain.Metric;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.util.SaxUtils;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\n\nimport java.util.Set;\n\n/**\n * @see <a href=\"http://docs.amazonwebservices.com/AmazonCloudWatch/latest/APIReference/API_Metric.html\" />\n */\npublic class MetricHandler extends ParseSax.HandlerForGeneratedRequestWithResult<Metric> {\n\n   private final DimensionHandler dimensionHandler;\n\n   private StringBuilder currentText = new StringBuilder();\n   private Set<Dimension> dimensions = Sets.newLinkedHashSet();\n   private boolean inDimensions;\n   private String metricName;\n   private String namespace;\n\n   @Inject\n   public MetricHandler(DimensionHandler dimensionHandler) {\n      this.dimensionHandler = dimensionHandler;\n   }\n\n    public boolean inDimensions() {\n        return inDimensions;\n    }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Metric getResult() {\n      Metric metric = new Metric(metricName, namespace, dimensions);\n\n      // Reset since this handler is created once but produces N results\n      dimensions = Sets.newLinkedHashSet();\n      metricName = null;\n      namespace = null;\n\n      return metric;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void startElement(String url, String name, String qName, Attributes attributes) throws SAXException {\n      if (!inDimensions && SaxUtils.equalsOrSuffix(qName, \"member\")) {\n         inDimensions = true;\n      }\n      if (inDimensions) {\n         dimensionHandler.startElement(url, name, qName, attributes);\n      }\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void endElement(String uri, String name, String qName) throws SAXException {\n      if (inDimensions) {\n         if (qName.equals(\"Dimensions\")) {\n            inDimensions = false;\n         } else if (qName.equals(\"member\")) {\n            dimensions.add(dimensionHandler.getResult());\n         } else {\n            dimensionHandler.endElement(uri, name, qName);\n         }\n      } else if (qName.equals(\"MetricName\")) {\n         metricName = SaxUtils.currentOrNull(currentText);\n      } else if (qName.equals(\"Namespace\")) {\n         namespace = SaxUtils.currentOrNull(currentText);\n      }\n\n      currentText.setLength(0);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      if (inDimensions) {\n         dimensionHandler.characters(ch, start, length);\n      } else {\n         currentText.append(ch, start, length);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/CloudWatchApiMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch;\n\nimport org.jclouds.View;\nimport org.jclouds.rest.internal.BaseHttpApiMetadataTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.reflect.TypeToken;\n\n@Test(groups = \"unit\", testName = \"CloudWatchApiMetadataTest\")\npublic class CloudWatchApiMetadataTest extends BaseHttpApiMetadataTest {\n\n   // no monitoring abstraction, yet\n   public CloudWatchApiMetadataTest() {\n      super(new CloudWatchApiMetadata(), ImmutableSet.<TypeToken<? extends View>> of());\n   }\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/CloudWatchLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch;\n\nimport static java.util.concurrent.TimeUnit.MINUTES;\nimport static org.jclouds.util.Predicates2.retry;\n\nimport java.util.Date;\nimport java.util.Set;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Sets;\nimport org.jclouds.cloudwatch.domain.Dimension;\nimport org.jclouds.cloudwatch.domain.MetricDatum;\nimport org.jclouds.cloudwatch.domain.Unit;\nimport org.jclouds.cloudwatch.internal.BaseCloudWatchApiLiveTest;\nimport org.jclouds.cloudwatch.options.ListMetricsOptions;\nimport org.testng.Assert;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code CloudWatch}.\n */\npublic class CloudWatchLiveTest extends BaseCloudWatchApiLiveTest {\n\n   public CloudWatchLiveTest() {\n      provider = \"cloudwatch\";\n   }\n\n   @Test\n   protected void testCloudWatch() {\n      String metricName = \"TestMetricName\" + System.currentTimeMillis();\n      String namespace = \"JCLOUDS/Test\";\n      Date metricTimestamp = new Date();\n      Set<MetricDatum> metrics = Sets.newLinkedHashSet();\n\n      for (int i = 0; i < 11; i++) {\n         metrics.add(MetricDatum.builder()\n                                .metricName(metricName + \"_\" + i)\n                                .dimension(new Dimension(\"BaseMetricName\", metricName))\n                                .unit(Unit.COUNT)\n                                .timestamp(metricTimestamp)\n                                .value((double) i)\n                                .build());\n      }\n\n      CloudWatch.putMetricData(api, null, metrics, namespace);\n\n      ListMetricsOptions lmo = ListMetricsOptions.Builder.namespace(namespace)\n                                                 .dimension(new Dimension(\"BaseMetricName\", metricName));\n      boolean success = retry(new Predicate<ListMetricsOptions>() {\n         public boolean apply(ListMetricsOptions options) {\n            return Iterables.size(CloudWatch.listMetrics(api, null, options)) == 11;\n         }\n      }, 20, 1, MINUTES).apply(lmo);\n\n      if (!success) {\n         Assert.fail(\"Unable to gather the created CloudWatch data within the time (20m) allotted.\");\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/CloudWatchTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch;\n\nimport static org.easymock.EasyMock.anyObject;\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\n\nimport java.util.List;\nimport java.util.Set;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Sets;\nimport org.easymock.EasyMock;\nimport org.jclouds.cloudwatch.domain.Metric;\nimport org.jclouds.cloudwatch.domain.MetricDatum;\nimport org.jclouds.cloudwatch.features.MetricApi;\nimport org.jclouds.cloudwatch.options.ListMetricsOptions;\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.IterableWithMarkers;\nimport org.testng.Assert;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code CloudWatch}.\n */\n@Test(testName = \"CloudWatchTest\")\npublic class CloudWatchTest {\n\n   /**\n    * Tests {@link CloudWatch#listMetrics(CloudWatchApi, String, org.jclouds.cloudwatch.options.ListMetricsOptions)}\n    * where a single response returns all results.\n    *\n    * @throws Exception if anything goes wrong\n    */\n   @Test\n   public void testSinglePageResult() throws Exception {\n      CloudWatchApi api = createMock(CloudWatchApi.class);\n      MetricApi metricApi = createMock(MetricApi.class);\n      ListMetricsOptions options = new ListMetricsOptions();\n      IterableWithMarker<Metric> response = IterableWithMarkers.from(ImmutableSet.of(createMock(Metric.class)), null);\n      \n      expect(api.getMetricApiForRegion(null))\n            .andReturn(metricApi)\n            .atLeastOnce();\n\n      expect(metricApi.list(options))\n            .andReturn(response)\n            .once();\n\n      EasyMock.replay(api, metricApi);\n\n      Assert.assertEquals(1, Iterables.size(CloudWatch.listMetrics(api, null, options)));\n   }\n\n   /**\n    * Tests {@link CloudWatch#listMetrics(CloudWatchApi, String, org.jclouds.cloudwatch.options.ListMetricsOptions)}\n    * where retrieving all results requires multiple requests.\n    *\n    * @throws Exception if anything goes wrong\n    */\n   @Test\n   public void testMultiPageResult() throws Exception {\n      CloudWatchApi api = createMock(CloudWatchApi.class);\n      MetricApi metricApi = createMock(MetricApi.class);\n      ListMetricsOptions options = new ListMetricsOptions();\n      IterableWithMarker<Metric> response1 = IterableWithMarkers.from(ImmutableSet.of(createMock(Metric.class)), \"NEXTTOKEN\");\n      IterableWithMarker<Metric> response2 = IterableWithMarkers.from(ImmutableSet.of(createMock(Metric.class)), null);\n\n      // Using EasyMock.eq(\"\") because EasyMock makes it impossible to pass null as a String value here\n      expect(api.getMetricApiForRegion(EasyMock.eq(\"\")))\n            .andReturn(metricApi)\n            .atLeastOnce();\n      \n      expect(metricApi.list(anyObject(ListMetricsOptions.class)))\n            .andReturn(response1)\n            .once();\n      expect(metricApi.list(anyObject(ListMetricsOptions.class)))\n            .andReturn(response2)\n            .once();\n\n      EasyMock.replay(api, metricApi);\n\n      Assert.assertEquals(2, Iterables.size(CloudWatch.listMetrics(api, \"\", options)));\n   }\n\n   /**\n    * Tests {@link CloudWatch#putMetricData(CloudWatchApi, String, Iterable, String)} where the set of metrics is\n    * greater than 10.\n    *\n    * @throws Exception if anything goes wrong\n    */\n   @Test\n   public void testPutMetricData() throws Exception {\n      CloudWatchApi api = createMock(CloudWatchApi.class);\n      MetricApi metricApi = createMock(MetricApi.class);\n      Set<MetricDatum> metrics = Sets.newLinkedHashSet();\n      String namespace = \"JCLOUDS/Test\";\n\n      for (int i = 0; i < 11; i++) {\n         metrics.add(MetricDatum.builder().metricName(\"foo\").build());\n      }\n\n      // Using EasyMock.eq(\"\") because EasyMock makes it impossible to pass null as a String value here\n      expect(api.getMetricApiForRegion(EasyMock.eq(\"\")))\n            .andReturn(metricApi)\n            .atLeastOnce();\n      \n      for (List<MetricDatum> slice : Iterables.partition(metrics, 10)) {\n         metricApi.putMetricsInNamespace(slice, namespace);\n      }\n\n      EasyMock.replay(api, metricApi);\n\n      CloudWatch.putMetricData(api, \"\", metrics, namespace);\n\n      EasyMock.verify(metricApi);\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/binders/AlarmNamesBinderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.binders;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport org.jclouds.http.HttpRequest;\nimport org.testng.Assert;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@link AlarmNamesBinder}.\n */\n@Test(groups = \"unit\", testName = \"AlarmNamesBinderTest\")\npublic class AlarmNamesBinderTest {\n\n   Injector injector = Guice.createInjector();\n   AlarmNamesBinder binder = injector.getInstance(AlarmNamesBinder.class);\n\n   HttpRequest request() {\n      return HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n   }\n\n   public void testAlarmNamesBinder() throws Exception {\n      HttpRequest request = binder.bindToRequest(request(), ImmutableSet.of(\"TestAlarmName1\", \"TestAlarmName2\"));\n\n      Assert.assertEquals(request.getPayload().getRawContent(),\n                          \"AlarmNames.member.1=TestAlarmName1&AlarmNames.member.2=TestAlarmName2\");\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/binders/MetricDataBinderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.binders;\n\nimport java.util.Date;\n\nimport org.jclouds.cloudwatch.domain.Dimension;\nimport org.jclouds.cloudwatch.domain.MetricDatum;\nimport org.jclouds.cloudwatch.domain.StatisticValues;\nimport org.jclouds.cloudwatch.domain.Unit;\nimport org.jclouds.http.HttpRequest;\nimport org.testng.Assert;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n/**\n * Tests behavior of {@link MetricDataBinder}.\n */\n@Test(groups = \"unit\", testName = \"MetricDataBinderTest\")\npublic class MetricDataBinderTest {\n\n   Injector injector = Guice.createInjector();\n   MetricDataBinder binder = injector.getInstance(MetricDataBinder.class);\n   \n   HttpRequest request() {\n      return HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n   }\n\n   public void testMetricWithoutTimestamp() throws Exception {\n      StatisticValues ss = StatisticValues.builder()\n                                    .maximum(4.0)\n                                    .minimum(1.0)\n                                    .sampleCount(4.0)\n                                    .sum(10.0)\n                                    .build();\n      \n      MetricDatum metricDatum = MetricDatum.builder()\n                                           .metricName(\"TestMetricName\")\n                                           .statisticValues(ss)\n                                           .dimension(new Dimension(\"TestDimension\", \"FAKE\"))\n                                           .unit(Unit.COUNT)\n                                           .build();\n\n      HttpRequest request = binder.bindToRequest(request(), ImmutableSet.of(metricDatum));\n\n      Assert.assertEquals(request.getPayload().getRawContent(),\n                          \"MetricData.member.1.Dimensions.member.1.Name=TestDimension\" +\n                                \"&MetricData.member.1.Dimensions.member.1.Value=FAKE\" +\n                                \"&MetricData.member.1.MetricName=TestMetricName\" +\n                                \"&MetricData.member.1.StatisticValues.Maximum=4.0\" +\n                                \"&MetricData.member.1.StatisticValues.Minimum=1.0\" +\n                                \"&MetricData.member.1.StatisticValues.SampleCount=4.0\" +\n                                \"&MetricData.member.1.StatisticValues.Sum=10.0\" +\n                                \"&MetricData.member.1.Unit=\" + Unit.COUNT.toString());\n   }\n\n   public void testMetricWithMultipleDimensions() throws Exception {\n      MetricDatum metricDatum = MetricDatum.builder()\n                                           .metricName(\"TestMetricName\")\n                                           .dimension(new Dimension(\"TestDimension\", \"FAKE\"))\n                                           .dimension(new Dimension(\"TestDimension2\", \"FAKE2\"))\n                                           .unit(Unit.COUNT)\n                                           .timestamp(new Date(10000000L))\n                                           .value(5.0)\n                                           .build();\n\n      HttpRequest request = binder.bindToRequest(request(), ImmutableSet.of(metricDatum));\n\n      Assert.assertEquals(request.getPayload().getRawContent(),\n                          \"MetricData.member.1.Dimensions.member.1.Name=TestDimension\" +\n                                \"&MetricData.member.1.Dimensions.member.1.Value=FAKE\" +\n                                \"&MetricData.member.1.Dimensions.member.2.Name=TestDimension2\" +\n                                \"&MetricData.member.1.Dimensions.member.2.Value=FAKE2\" +\n                                \"&MetricData.member.1.MetricName=TestMetricName\" +\n                                \"&MetricData.member.1.Timestamp=1970-01-01T02%3A46%3A40Z\" +\n                                \"&MetricData.member.1.Unit=\" + Unit.COUNT.toString() +\n                                \"&MetricData.member.1.Value=5.0\");\n   }\n\n   public void testMetricWithMultipleDatum() throws Exception {\n      StatisticValues ss = StatisticValues.builder()\n                                    .maximum(4.0)\n                                    .minimum(1.0)\n                                    .sampleCount(4.0)\n                                    .sum(10.0)\n                                    .build();\n      MetricDatum metricDatum = MetricDatum.builder()\n                                           .metricName(\"TestMetricName\")\n                                           .statisticValues(ss)\n                                           .dimension(new Dimension(\"TestDimension\", \"FAKE\"))\n                                           .dimension(new Dimension(\"TestDimension2\", \"FAKE2\"))\n                                           .unit(Unit.COUNT)\n                                           .timestamp(new Date(10000000L))\n                                           .value(2.0)\n                                           .build();\n      MetricDatum metricDatum2 = MetricDatum.builder()\n                                           .metricName(\"TestMetricName\")\n                                           .dimension(new Dimension(\"TestDimension\", \"FAKE\"))\n                                           .unit(Unit.COUNT)\n                                           .timestamp(new Date(10000000L))\n                                           .value(5.0)\n                                           .build();\n\n      HttpRequest request = binder.bindToRequest(request(), ImmutableSet.of(metricDatum, metricDatum2));\n\n      Assert.assertEquals(request.getPayload().getRawContent(),\n                          \"MetricData.member.1.Dimensions.member.1.Name=TestDimension\" +\n                                \"&MetricData.member.1.Dimensions.member.1.Value=FAKE\" +\n                                \"&MetricData.member.1.Dimensions.member.2.Name=TestDimension2\" +\n                                \"&MetricData.member.1.Dimensions.member.2.Value=FAKE2\" +\n                                \"&MetricData.member.1.MetricName=TestMetricName\" +\n                                \"&MetricData.member.1.StatisticValues.Maximum=4.0\" +\n                                \"&MetricData.member.1.StatisticValues.Minimum=1.0\" +\n                                \"&MetricData.member.1.StatisticValues.SampleCount=4.0\" +\n                                \"&MetricData.member.1.StatisticValues.Sum=10.0\" +\n                                \"&MetricData.member.1.Timestamp=1970-01-01T02%3A46%3A40Z\" +\n                                \"&MetricData.member.1.Unit=\" + Unit.COUNT.toString() +\n                                \"&MetricData.member.1.Value=2.0\" +\n                                \"&MetricData.member.2.Dimensions.member.1.Name=TestDimension\" +\n                                \"&MetricData.member.2.Dimensions.member.1.Value=FAKE\" +\n                                \"&MetricData.member.2.MetricName=TestMetricName\" +\n                                \"&MetricData.member.2.Timestamp=1970-01-01T02%3A46%3A40Z\" +\n                                \"&MetricData.member.2.Unit=\" + Unit.COUNT.toString() +\n                                \"&MetricData.member.2.Value=5.0\");\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/features/AlarmApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.features;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.TimeZone;\n\nimport com.google.common.base.Joiner;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Maps;\nimport org.jclouds.cloudwatch.CloudWatchApi;\nimport org.jclouds.cloudwatch.domain.Alarm;\nimport org.jclouds.cloudwatch.domain.ComparisonOperator;\nimport org.jclouds.cloudwatch.domain.Dimension;\nimport org.jclouds.cloudwatch.domain.HistoryItemType;\nimport org.jclouds.cloudwatch.domain.Namespaces;\nimport org.jclouds.cloudwatch.domain.Statistics;\nimport org.jclouds.cloudwatch.domain.Unit;\nimport org.jclouds.cloudwatch.internal.BaseCloudWatchApiExpectTest;\nimport org.jclouds.cloudwatch.options.ListAlarmHistoryOptions;\nimport org.jclouds.cloudwatch.options.ListAlarmsForMetric;\nimport org.jclouds.cloudwatch.options.ListAlarmsOptions;\nimport org.jclouds.cloudwatch.options.SaveAlarmOptions;\nimport org.jclouds.cloudwatch.xml.ListAlarmHistoryResponseHandlerTest;\nimport org.jclouds.cloudwatch.xml.ListAlarmsForMetricResponseHandlerTest;\nimport org.jclouds.cloudwatch.xml.ListAlarmsResponseHandlerTest;\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.io.Payload;\nimport org.jclouds.rest.InsufficientResourcesException;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"AlarmApiExpectTest\")\npublic class AlarmApiExpectTest extends BaseCloudWatchApiExpectTest {\n\n   private DateService dateService = new SimpleDateFormatDateService();\n   private HttpRequest deleteAlarmsRequest = alarmRequest(ImmutableMap.of(\n         \"Action\", \"DeleteAlarms\",\n         \"AlarmNames.member.1\", \"TestAlarmName1\",\n         \"AlarmNames.member.2\", \"TestAlarmName2\",\n         \"Signature\", \"w9dhEBQCsmOhYKDp9Ht7/Ra6/xZcgAzhF0Bgtj8vpwQ%3D\"\n   ));\n   private HttpRequest putMetricAlarmRequest = alarmRequest(\n         ImmutableMap.<String, String>builder()\n                     .put(\"Action\", \"PutMetricAlarm\")\n                     .put(\"ActionsEnabled\", \"true\")\n                     .put(\"AlarmActions.member.1\", \"TestAlarmAction1\")\n                     .put(\"AlarmActions.member.2\", \"TestAlarmAction2\")\n                     .put(\"AlarmDescription\", \"Test%20alarm%20description.\")\n                     .put(\"AlarmName\", \"TestAlarmName\")\n                     .put(\"ComparisonOperator\", ComparisonOperator.GREATER_THAN_THRESHOLD.toString())\n                     .put(\"Dimensions.member.1.Name\", \"TestDimensionName1\")\n                     .put(\"Dimensions.member.1.Value\", \"TestDimensionValue1\")\n                     .put(\"Dimensions.member.2.Name\", \"TestDimensionName2\")\n                     .put(\"Dimensions.member.2.Value\", \"TestDimensionValue2\")\n                     .put(\"EvaluationPeriods\", \"60\")\n                     .put(\"InsufficientDataActions.member.1\", \"TestAlarmAction1\")\n                     .put(\"InsufficientDataActions.member.2\", \"TestAlarmAction2\")\n                     .put(\"MetricName\", \"TestMetricName\")\n                     .put(\"Namespace\", Namespaces.EBS)\n                     .put(\"OKActions.member.1\", \"TestAlarmAction1\")\n                     .put(\"OKActions.member.2\", \"TestAlarmAction2\")\n                     .put(\"Period\", \"60\")\n                     .put(\"Statistic\", Statistics.SAMPLE_COUNT.toString())\n                     .put(\"Threshold\", \"1.0\")\n                     .put(\"Unit\", Unit.GIGABYTES_PER_SECOND.toString())\n                     .put(\"Signature\", \"6RXD%2Bp1393a0maPdMLn%2Bv%2BbIcOJnAViAtbMgcA%2BogWs%3D\").build()\n   );\n   private SaveAlarmOptions saveAlarmOptions = new SaveAlarmOptions()\n         .alarmActions(ImmutableSet.of(\"TestAlarmAction1\", \"TestAlarmAction2\"))\n         .alarmDescription(\"Test alarm description.\")\n         .alarmName(\"TestAlarmName\")\n         .metricName(\"TestMetricName\")\n         .actionsEnabled(true)\n         .comparisonOperator(ComparisonOperator.GREATER_THAN_THRESHOLD)\n         .dimensions(ImmutableSet.of(\n               new Dimension(\"TestDimensionName1\",\n                             \"TestDimensionValue1\"),\n               new Dimension(\"TestDimensionName2\",\n                             \"TestDimensionValue2\")\n         ))\n         .evaluationPeriods(60)\n         .insufficientDataActions(ImmutableSet.of(\"TestAlarmAction1\", \"TestAlarmAction2\"))\n         .namespace(Namespaces.EBS)\n         .okActions(ImmutableSet.of(\"TestAlarmAction1\", \"TestAlarmAction2\"))\n         .period(60)\n         .statistic(Statistics.SAMPLE_COUNT)\n         .threshold(1.0)\n         .unit(Unit.GIGABYTES_PER_SECOND);\n   private HttpRequest setAlarmStateRequest = alarmRequest(\n         ImmutableMap.<String, String>builder()\n                     .put(\"Action\", \"SetAlarmState\")\n                     .put(\"AlarmName\", \"TestAlarmName\")\n                     .put(\"StateReason\", \"TestStateReason\")\n                     .put(\"StateReasonData\", \"%7B%22reason%22%3A%20%22Some%20reason%22%7D\")\n                     .put(\"StateValue\", Alarm.State.OK.toString())\n                     .put(\"Signature\", \"W3juJzJEoSTPfYnrK7s/Pbj4uA/PGNF7eoxa7NhByqU%3D\").build()\n   );\n\n   public AlarmApiExpectTest() {\n      TimeZone.setDefault(TimeZone.getTimeZone(\"America/Los_Angeles\"));\n   }\n\n   public void testSetAlarmStateIs2xx() throws Exception {\n      Payload payload = payloadFromResourceWithContentType(\"/VoidResponse.xml\", \"text/xml\");\n      CloudWatchApi cloudWatchApi = requestSendsResponse(setAlarmStateRequest,\n                                                         HttpResponse.builder()\n                                                                     .payload(payload)\n                                                                     .statusCode(200)\n                                                                     .build());\n\n      // Ensure there is no error returned\n      cloudWatchApi.getAlarmApiForRegion(null).setState(\"TestAlarmName\", \"TestStateReason\",\n                                                        \"{\\\"reason\\\": \\\"Some reason\\\"}\",\n                                                        Alarm.State.OK);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testSetAlarmStateIs400() throws Exception {\n      Payload payload = payloadFromResourceWithContentType(\"/InvalidFormatResponse.xml\", \"text/xml\");\n      CloudWatchApi cloudWatchApi = requestSendsResponse(setAlarmStateRequest,\n                                                         HttpResponse.builder()\n                                                                     .payload(payload)\n                                                                     .statusCode(400)\n                                                                     .build());\n\n      // Ensure an IllegalArgumentException is thrown\n      cloudWatchApi.getAlarmApiForRegion(null).setState(\"TestAlarmName\", \"TestStateReason\",\n                                                        \"{\\\"reason\\\": \\\"Some reason\\\"}\",\n                                                        Alarm.State.OK);\n   }\n\n   public void testPutMetricAlarmIs2xx() throws Exception {\n      Payload payload = payloadFromResourceWithContentType(\"/VoidResponse.xml\", \"text/xml\");\n      CloudWatchApi cloudWatchApi = requestSendsResponse(putMetricAlarmRequest,\n                                                         HttpResponse.builder()\n                                                                     .statusCode(200)\n                                                                     .payload(payload)\n                                                                     .build());\n\n      // Ensure there is no error returned\n      cloudWatchApi.getAlarmApiForRegion(null).save(saveAlarmOptions);\n   }\n\n   @Test(expectedExceptions = InsufficientResourcesException.class)\n   public void testPutMetricAlarmIs400() throws Exception {\n      Payload payload = payloadFromResourceWithContentType(\"/LimitExceededResponse.xml\", \"text/xml\");\n      CloudWatchApi cloudWatchApi = requestSendsResponse(putMetricAlarmRequest,\n                                                         HttpResponse.builder()\n                                                                     .payload(payload)\n                                                                     .statusCode(400)\n                                                                     .build());\n\n      // Ensure an InsufficientResourcesException is thrown\n      cloudWatchApi.getAlarmApiForRegion(null).save(saveAlarmOptions);\n   }\n\n   public void testEnableAlarmActions() throws Exception {\n      CloudWatchApi cloudWatchApi = requestSendsResponse(alarmRequest(ImmutableMap.of(\n            \"Action\", \"EnableAlarmActions\",\n            \"AlarmNames.member.1\", \"TestAlarmName1\",\n            \"AlarmNames.member.2\", \"TestAlarmName2\",\n            \"Signature\", \"Q1VemnXpc57PKMs9NVCX6R%2B/TSDgsGzQwpOHQ70aJuU%3D\"\n      )), HttpResponse.builder()\n                      .statusCode(200)\n                      .payload(payloadFromResourceWithContentType(\"/VoidResponse.xml\", \"text/xml\"))\n                      .build());\n\n      // Ensure there is no error returned\n      cloudWatchApi.getAlarmApiForRegion(null).enable(ImmutableSet.of(\n            \"TestAlarmName1\",\n            \"TestAlarmName2\"\n      ));\n   }\n\n   public void testDisableAlarmActions() throws Exception {\n      CloudWatchApi cloudWatchApi = requestSendsResponse(alarmRequest(ImmutableMap.of(\n            \"Action\", \"DisableAlarmActions\",\n            \"AlarmNames.member.1\", \"TestAlarmName1\",\n            \"AlarmNames.member.2\", \"TestAlarmName2\",\n            \"Signature\", \"tvSfJ%2BgcrHowwUECSniV0TQP2OObpWCuba0S5dd723Y%3D\"\n      )), HttpResponse.builder()\n                      .statusCode(200)\n                      .payload(payloadFromResourceWithContentType(\"/VoidResponse.xml\", \"text/xml\"))\n                      .build());\n\n      // Ensure there is no error returned\n      cloudWatchApi.getAlarmApiForRegion(null).disable(ImmutableSet.of(\n            \"TestAlarmName1\",\n            \"TestAlarmName2\"\n      ));\n   }\n\n   public void testDescribeAlarmsForMetric() throws Exception {\n      String metricName = \"TestMetricName\";\n      String namespace = Namespaces.EC2;\n      int period = 60;\n      Statistics statistics = Statistics.SAMPLE_COUNT;\n      Unit unit = Unit.SECONDS;\n      CloudWatchApi cloudWatchApi = requestSendsResponse(\n            alarmRequest(ImmutableMap.<String, String>builder()\n                                     .put(\"Action\", \"DescribeAlarmsForMetric\")\n                                     .put(\"Dimensions.member.1.Name\", \"TestDimensionName1\")\n                                     .put(\"Dimensions.member.1.Value\", \"TestDimensionValue1\")\n                                     .put(\"Dimensions.member.2.Name\", \"TestDimensionName2\")\n                                     .put(\"Dimensions.member.2.Value\", \"TestDimensionValue2\")\n                                     .put(\"MetricName\", metricName)\n                                     .put(\"Namespace\", namespace)\n                                     .put(\"Period\", Integer.toString(period))\n                                     .put(\"Statistic\", statistics.toString())\n                                     .put(\"Unit\", unit.toString())\n                                     .put(\"Signature\", \"y%2BpU0Lp6AAO2QSrNld1VQY4DhKVHcyn44dIfnrmJhpg%3D\")\n                                     .build()),\n            HttpResponse.builder()\n                        .statusCode(200)\n                        .payload(payloadFromResourceWithContentType(\"/DescribeAlarmsForMetricResponse.xml\", \"text/xml\"))\n                        .build()\n      );\n\n      assertEquals(new ListAlarmsForMetricResponseHandlerTest().expected().toString(),\n                   cloudWatchApi.getAlarmApiForRegion(null)\n                                .listForMetric(new ListAlarmsForMetric()\n                                                     .dimensions(ImmutableSet.of(\n                                                           new Dimension(\"TestDimensionName1\",\n                                                                         \"TestDimensionValue1\"),\n                                                           new Dimension(\"TestDimensionName2\",\n                                                                         \"TestDimensionValue2\")\n                                                     ))\n                                                     .metricName(metricName)\n                                                     .namespace(namespace)\n                                                     .period(period)\n                                                     .statistic(statistics)\n                                                     .unit(unit)\n                                ).toString());\n   }\n\n   public void testDescribeAlarms() throws Exception {\n      String actionPrefix = \"TestActionPrefix\";\n      String alarmNamePrefix = \"TestAlarmNamePrefix\";\n      Set<String> alarmNames = ImmutableSet.of(\"TestAlarmName1\", \"TestAlarmName2\");\n      int maxRecords = 10;\n      Alarm.State state = Alarm.State.ALARM;\n      CloudWatchApi cloudWatchApi = requestSendsResponse(\n            alarmRequest(ImmutableMap.<String, String>builder()\n                                     .put(\"Action\", \"DescribeAlarms\")\n                                     .put(\"ActionPrefix\", actionPrefix)\n                                     .put(\"AlarmNamePrefix\", alarmNamePrefix)\n                                     .put(\"AlarmNames.member.1\", \"TestAlarmName1\")\n                                     .put(\"AlarmNames.member.2\", \"TestAlarmName2\")\n                                     .put(\"MaxRecords\", Integer.toString(maxRecords))\n                                     .put(\"StateValue\", state.toString())\n                                     .put(\"Signature\", \"jPP1enbHPfOphIZv796W0KN4/EsLdPp6nK1qpbt5Dog%3D\")\n                                     .build()),\n            HttpResponse.builder()\n                        .statusCode(200)\n                        .payload(payloadFromResourceWithContentType(\"/DescribeAlarmsResponse.xml\", \"text/xml\"))\n                        .build()\n            );\n\n      assertEquals(new ListAlarmsResponseHandlerTest().expected().toString(),\n                   cloudWatchApi.getAlarmApiForRegion(null)\n                                .list(new ListAlarmsOptions()\n                                              .actionPrefix(actionPrefix)\n                                              .alarmNamePrefix(alarmNamePrefix)\n                                              .alarmNames(alarmNames)\n                                              .maxRecords(maxRecords)\n                                              .state(state)\n                                ).get(0).toString());\n   }\n\n   public void testDescribeAlarmHistory() throws Exception {\n      String alarmName = \"TestAlarmName\";\n      HistoryItemType historyItemType = HistoryItemType.ACTION;\n      int maxRecords = 10;\n      String endDateStr = \"2013-01-02T00:00:00.000Z\";\n      String startDateStr = \"2013-01-01T00:00:00.000Z\";\n      CloudWatchApi cloudWatchApi = requestSendsResponse(\n            alarmRequest(ImmutableMap.<String, String> builder()\n                                     .put(\"Action\", \"DescribeAlarmHistory\")\n                                     .put(\"AlarmName\", alarmName)\n                                     .put(\"EndDate\", \"2013-01-02T00%3A00%3A00.000Z\")\n                                     .put(\"HistoryItemType\", historyItemType.toString())\n                                     .put(\"MaxRecords\", Integer.toString(maxRecords))\n                                     .put(\"StartDate\", \"2013-01-01T00%3A00%3A00.000Z\")\n                                     .put(\"Signature\", \"O2u9yIQvCuVpKdUeUDJcswri0YD0sD4%2B/SR5TtYbPeQ%3D\")\n                                     .build()),\n            HttpResponse.builder()\n                        .statusCode(200)\n                        .payload(payloadFromResourceWithContentType(\"/DescribeAlarmHistoryResponse.xml\", \"text/xml\"))\n                        .build());\n\n      assertEquals(new ListAlarmHistoryResponseHandlerTest().expected().toString(),\n                   cloudWatchApi.getAlarmApiForRegion(null)\n                                .listHistory(new ListAlarmHistoryOptions()\n                                                   .alarmName(\"TestAlarmName\")\n                                                   .endDate(dateService.iso8601DateParse(endDateStr))\n                                                   .historyItemType(HistoryItemType.ACTION)\n                                                   .maxRecords(maxRecords)\n                                                   .startDate(dateService.iso8601DateParse(startDateStr))\n                                ).get(0).toString());\n   }\n\n   @Test(expectedExceptions = ResourceNotFoundException.class)\n   public void testDeleteAlarmsIs404() throws Exception {\n      CloudWatchApi cloudWatchApi = requestSendsResponse(deleteAlarmsRequest,\n                                                         HttpResponse.builder().statusCode(404).build());\n\n      // Ensure a ResourceNotFoundException is thrown\n      cloudWatchApi.getAlarmApiForRegion(null).delete(ImmutableSet.of(\n            \"TestAlarmName1\",\n            \"TestAlarmName2\"\n      ));\n   }\n\n   public void testDeleteAlarmsIs2xx() throws Exception {\n      Payload payload = payloadFromResourceWithContentType(\"/VoidResponse.xml\", \"text/xml\");\n      CloudWatchApi cloudWatchApi = requestSendsResponse(deleteAlarmsRequest,\n                                                         HttpResponse.builder()\n                                                                     .statusCode(200)\n                                                                     .payload(payload)\n                                                                     .build());\n\n      // Ensure there is no error returned\n      cloudWatchApi.getAlarmApiForRegion(null).delete(ImmutableSet.of(\n            \"TestAlarmName1\",\n            \"TestAlarmName2\"\n      ));\n   }\n\n   private HttpRequest alarmRequest(Map<String, String> arguments) {\n      Map<String, String> sortedArguments = Maps.newTreeMap();\n      Map<String, String> defaultArguments =\n            ImmutableMap.<String, String> builder()\n                        .put(\"SignatureMethod\", \"HmacSHA256\")\n                        .put(\"SignatureVersion\", \"2\")\n                        .put(\"Timestamp\", \"2009-11-08T15%3A54%3A08.897Z\")\n                        .put(\"Version\", \"2010-08-01\")\n                        .build();\n\n      sortedArguments.putAll(arguments);\n\n      for (Map.Entry<String, String> defaultArgument : defaultArguments.entrySet()) {\n         if (!sortedArguments.containsKey(defaultArgument.getKey())) {\n            sortedArguments.put(defaultArgument.getKey(), defaultArgument.getValue());\n         }\n      }\n\n      Map<String, String> realArguments = Maps.newLinkedHashMap(sortedArguments);\n\n      realArguments.put(\"AWSAccessKeyId\", \"identity\");\n\n      return HttpRequest.builder()\n                        .method(\"POST\")\n                        .endpoint(\"https://monitoring.us-east-1.amazonaws.com/\")\n                        .addHeader(\"Host\", \"monitoring.us-east-1.amazonaws.com\")\n                        .payload(payloadFromStringWithContentType(Joiner.on(\"&\")\n                                                                        .withKeyValueSeparator(\"=\")\n                                                                        .join(realArguments).trim(),\n                                                                  \"application/x-www-form-urlencoded\"))\n                        .build();\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/features/AlarmApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.features;\n\nimport static java.util.concurrent.TimeUnit.MINUTES;\nimport static org.jclouds.util.Predicates2.retry;\n\nimport java.util.Date;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.gson.JsonObject;\nimport com.google.gson.JsonParser;\nimport org.jclouds.cloudwatch.domain.Alarm;\nimport org.jclouds.cloudwatch.domain.AlarmHistoryItem;\nimport org.jclouds.cloudwatch.domain.ComparisonOperator;\nimport org.jclouds.cloudwatch.domain.Dimension;\nimport org.jclouds.cloudwatch.domain.Metric;\nimport org.jclouds.cloudwatch.domain.MetricDatum;\nimport org.jclouds.cloudwatch.domain.StatisticValues;\nimport org.jclouds.cloudwatch.domain.Statistics;\nimport org.jclouds.cloudwatch.domain.Unit;\nimport org.jclouds.cloudwatch.internal.BaseCloudWatchApiLiveTest;\nimport org.jclouds.cloudwatch.options.ListAlarmHistoryOptions;\nimport org.jclouds.cloudwatch.options.ListAlarmsForMetric;\nimport org.jclouds.cloudwatch.options.ListAlarmsOptions;\nimport org.jclouds.cloudwatch.options.ListMetricsOptions;\nimport org.jclouds.cloudwatch.options.SaveAlarmOptions;\nimport org.jclouds.collect.IterableWithMarker;\nimport org.testng.Assert;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"AlarmApiLiveTest\")\npublic class AlarmApiLiveTest extends BaseCloudWatchApiLiveTest {\n\n   private String alarmName = \"TestAlarmName\" + System.currentTimeMillis();\n   private String metricName = \"TestMetricForAlarms\";\n   private String namespace = \"JCLOUDS/Test\";\n\n   @BeforeClass\n   protected void beforeClass() throws Exception {\n      IterableWithMarker<Metric> metrics = metricApi().list(new ListMetricsOptions().metricName(metricName));\n\n      if (Iterables.isEmpty(metrics)) {\n         metricApi().putMetricsInNamespace(ImmutableSet.of(\n               MetricDatum.builder()\n                          .metricName(metricName)\n                          .statisticValues(StatisticValues.builder()\n                                                          .maximum(4.0)\n                                                          .minimum(1.0)\n                                                          .sampleCount(4.0)\n                                                          .sum(10.0)\n                                                          .build())\n                          .dimension(new Dimension(\"BaseMetricName\", metricName))\n                          .dimension(new Dimension(\"TestDimension2\", \"TEST2\"))\n                          .unit(Unit.COUNT)\n                          .timestamp(new Date())\n                          .build()\n         ), namespace);\n\n         ListMetricsOptions lmo = ListMetricsOptions.Builder.namespace(namespace)\n                                                    .metricName(metricName);\n         boolean success = retry(new Predicate<ListMetricsOptions>() {\n            public boolean apply(ListMetricsOptions options) {\n               return Iterables.size(metricApi().list(options)) == 1;\n            }\n         }, 5, 1, MINUTES).apply(lmo);\n\n         if (!success) {\n            Assert.fail(\"Unable to create the test CloudWatch metric within the time (5m) allotted.\");\n         }\n      }\n   }\n\n   @AfterClass\n   protected void afterClass() throws Exception {\n      IterableWithMarker<Alarm> alarms = api().list(new ListAlarmsOptions().alarmName(alarmName)).get(0);\n      if (!Iterables.isEmpty(alarms)) {\n         api().delete(ImmutableSet.of(alarmName));\n      }\n   }\n\n   @Test\n   protected void testAlarmCRUD() throws Exception {\n      // Create new alarm\n      api().save(new SaveAlarmOptions()\n                       .actionsEnabled(true)\n                       .alarmDescription(\"This is a test alarm for jclouds.\")\n                       .alarmName(alarmName)\n                       .comparisonOperator(ComparisonOperator.GREATER_THAN_THRESHOLD)\n                       .evaluationPeriods(5)\n                       .metricName(metricName)\n                       .namespace(namespace)\n                       .period(60)\n                       .statistic(Statistics.SAMPLE_COUNT)\n                       .threshold(1.0));\n\n      // Poll alarms until alarm is found\n      ListAlarmsOptions dmo = new ListAlarmsOptions().alarmName(alarmName);\n      boolean success = retry(new Predicate<ListAlarmsOptions>() {\n         public boolean apply(ListAlarmsOptions options) {\n            return Iterables.size(api().list(options).get(0)) == 1;\n         }\n      }, 5, 1, MINUTES).apply(dmo);\n\n      if (!success) {\n         Assert.fail(\"Unable to create the test CloudWatch alarm within the time (5m) allotted.\");\n      }\n\n      // Poll all alarms until alarm is found\n      success = retry(new Predicate<Void>() {\n         public boolean apply(Void arg) {\n            for (IterableWithMarker<Alarm> page : api().list()) {\n               for (Alarm alarm : page) {\n                  if (alarm.getAlarmName().equals(alarmName)) {\n                     return true;\n                  }\n               }\n            }\n            return false;\n         }\n      }, 5, 1, MINUTES).apply(null);\n\n      if (!success) {\n         Assert.fail(\"Unable to create the test CloudWatch alarm within the time (5m) allotted.\");\n      }\n\n      // Poll for alarms for metric until alarm is found\n      ListAlarmsForMetric dafmo = new ListAlarmsForMetric()\n            .metricName(metricName)\n            .namespace(namespace);\n      success = retry(new Predicate<ListAlarmsForMetric>() {\n         public boolean apply(ListAlarmsForMetric options) {\n            for (Alarm alarm : api().listForMetric(options)) {\n               if (alarm.getAlarmName().equals(alarmName)) {\n                  return true;\n               }\n            }\n            return false;\n         }\n      }, 5, 1, MINUTES).apply(dafmo);\n\n      if (!success) {\n         Assert.fail(\"Unable to create the test CloudWatch alarm history item within the time (5m) allotted.\");\n      }\n\n      // Create history item by changing its state\n      api().setState(alarmName, \"Updating the state.\", null, Alarm.State.OK);\n\n      // Poll for alarm history\n      ListAlarmHistoryOptions daho = new ListAlarmHistoryOptions().alarmName(alarmName);\n      success = retry(new Predicate<ListAlarmHistoryOptions>() {\n         public boolean apply(ListAlarmHistoryOptions options) {\n            for (IterableWithMarker<AlarmHistoryItem> page : api().listHistory(options)) {\n               for (AlarmHistoryItem alarmHistoryItem : page) {\n                  if (alarmHistoryItem.getAlarmName().equals(alarmName)) {\n                     JsonObject historyData = new JsonParser().parse(alarmHistoryItem.getHistoryData())\n                                                              .getAsJsonObject();\n\n                     if (historyData.has(\"newState\") && historyData.getAsJsonObject(\"newState\").has(\"stateReason\") &&\n                           historyData.getAsJsonObject(\"newState\").get(\"stateReason\").getAsString()\n                                      .equals(\"Updating the state.\")) {\n                        return true;\n                     }\n                  }\n               }\n            }\n            return false;\n         }\n      }, 5, 1, MINUTES).apply(daho);\n\n      if (!success) {\n         Assert.fail(\"Unable to create the test CloudWatch alarm history item within the time (5m) allotted.\");\n      }\n\n      success = retry(new Predicate<Void>() {\n         public boolean apply(Void arg) {\n            for (IterableWithMarker<AlarmHistoryItem> page : api().listHistory()) {\n               for (AlarmHistoryItem alarmHistoryItem : page) {\n                  if (alarmHistoryItem.getAlarmName().equals(alarmName)) {\n                     JsonObject historyData = new JsonParser().parse(alarmHistoryItem.getHistoryData())\n                                                              .getAsJsonObject();\n\n                     if (historyData.has(\"newState\") && historyData.getAsJsonObject(\"newState\").has(\"stateReason\") &&\n                           historyData.getAsJsonObject(\"newState\").get(\"stateReason\").getAsString()\n                                      .equals(\"Updating the state.\")) {\n                        return true;\n                     }\n                  }\n               }\n            }\n            return false;\n         }\n      }, 5, 1, MINUTES).apply(null);\n\n      if (!success) {\n         Assert.fail(\"Unable to create the test CloudWatch alarm history item within the time (5m) allotted.\");\n      }\n\n      // Disable alarm actions\n      api().disable(ImmutableSet.of(alarmName));\n\n      // Validate\n      success = retry(new Predicate<ListAlarmsOptions>() {\n         public boolean apply(ListAlarmsOptions options) {\n            Iterable<Alarm> alarms = api().list(options).get(0);\n            return Iterables.size(alarms) == 1 && !alarms.iterator().next().areActionsEnabled();\n         }\n      }, 5, 1, MINUTES).apply(dmo);\n\n      if (!success) {\n         Assert.fail(\"Unable to validate the test CloudWatch alarm disablement within the time (5m) allotted.\");\n      }\n\n      // Enable alarm actions\n      api().enable(ImmutableSet.of(alarmName));\n\n      // Validate\n      success = retry(new Predicate<ListAlarmsOptions>() {\n         public boolean apply(ListAlarmsOptions options) {\n            IterableWithMarker<Alarm> alarms = api().list(options).get(0);\n            return Iterables.size(alarms) == 1 && alarms.iterator().next().areActionsEnabled();\n         }\n      }, 5, 1, MINUTES).apply(dmo);\n\n      if (!success) {\n         Assert.fail(\"Unable to validate the test CloudWatch alarm enablement within the time (5m) allotted.\");\n      }\n\n      // Delete the alarm\n      api().delete(ImmutableSet.of(alarmName));\n\n      success = retry(new Predicate<ListAlarmsOptions>() {\n         public boolean apply(ListAlarmsOptions options) {\n            return Iterables.isEmpty(api().list(options).get(0));\n         }\n      }, 5, 1, MINUTES).apply(dmo);\n\n      if (!success) {\n         Assert.fail(\"Unable to delete the test CloudWatch alarm within the time (5m) allotted.\");\n      }\n   }\n\n   protected AlarmApi api() {\n      return api.getAlarmApiForRegion(null);\n   }\n\n   protected MetricApi metricApi() {\n      return api.getMetricApiForRegion(null);\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/features/MetricApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.features;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Date;\nimport java.util.TimeZone;\n\nimport org.jclouds.cloudwatch.CloudWatchApi;\nimport org.jclouds.cloudwatch.domain.Dimension;\nimport org.jclouds.cloudwatch.domain.EC2Constants;\nimport org.jclouds.cloudwatch.domain.GetMetricStatistics;\nimport org.jclouds.cloudwatch.domain.Namespaces;\nimport org.jclouds.cloudwatch.domain.Statistics;\nimport org.jclouds.cloudwatch.domain.Unit;\nimport org.jclouds.cloudwatch.internal.BaseCloudWatchApiExpectTest;\nimport org.jclouds.cloudwatch.options.GetMetricStatisticsOptions;\nimport org.jclouds.cloudwatch.options.ListMetricsOptions;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\", testName = \"MetricApiExpectTest\")\npublic class MetricApiExpectTest extends BaseCloudWatchApiExpectTest {\n\n   public MetricApiExpectTest() {\n      TimeZone.setDefault(TimeZone.getTimeZone(\"America/Los_Angeles\"));\n   }\n\n   HttpRequest listMetrics = HttpRequest.builder()\n                                       .method(\"POST\")\n                                       .endpoint(\"https://monitoring.us-east-1.amazonaws.com/\")\n                                       .addHeader(\"Host\", \"monitoring.us-east-1.amazonaws.com\")\n                                       .payload(\n                                          payloadFromStringWithContentType(\n                                                \"Action=ListMetrics\" +\n                                                      \"&Signature=KSh9oQydCR0HMAV6QPYwDzqwQIpxs8I/ig7brYgHVZU%3D\" +\n                                                      \"&SignatureMethod=HmacSHA256\" +\n                                                      \"&SignatureVersion=2\" +\n                                                      \"&Timestamp=2009-11-08T15%3A54%3A08.897Z\" +\n                                                      \"&Version=2010-08-01\" +\n                                                      \"&AWSAccessKeyId=identity\",\n                                                \"application/x-www-form-urlencoded\"))\n                                       .build();\n   \n   public void testListMetricsWhenResponseIs2xx() throws Exception {\n\n      HttpResponse listMetricsResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResourceWithContentType(\"/list_metrics.xml\", \"text/xml\")).build();\n\n      CloudWatchApi apiWhenMetricsExist = requestSendsResponse(\n            listMetrics, listMetricsResponse);\n\n      assertEquals(apiWhenMetricsExist.getMetricApiForRegion(null).list().get(0).toString(),\n            \"[Metric{namespace=AWS/EC2, metricName=CPUUtilization, dimension=[Dimension{name=InstanceId, value=i-689fcf0f}]}]\");\n   }\n\n   public void testListMetricsWhenResponseIs404() throws Exception {\n\n      HttpResponse listMetricsResponse = HttpResponse.builder().statusCode(404).build();\n\n      CloudWatchApi apiWhenMetricsDontExist = requestSendsResponse(\n            listMetrics, listMetricsResponse);\n\n      assertEquals(apiWhenMetricsDontExist.getMetricApiForRegion(null).list().get(0).toSet(), ImmutableSet.of());\n   }\n   \n   public void testListMetrics2PagesWhenResponseIs2xx() throws Exception {\n\n      HttpResponse listMetricsResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResourceWithContentType(\"/list_metrics_marker.xml\", \"text/xml\")).build();\n      \n      HttpRequest listMetrics2 = HttpRequest.builder()\n               .method(\"POST\")\n               .endpoint(\"https://monitoring.us-east-1.amazonaws.com/\")\n               .addHeader(\"Host\", \"monitoring.us-east-1.amazonaws.com\")\n               .payload(\n                  payloadFromStringWithContentType(\n                        \"Action=ListMetrics\" +\n                              \"&NextToken=MARKER\" +\n                              \"&Signature=RpBdQydXD1jQhEUnXoqT60NEuCP/ZgdvO6Hf3uf/wy0%3D\" +\n                              \"&SignatureMethod=HmacSHA256\" +\n                              \"&SignatureVersion=2\" +\n                              \"&Timestamp=2009-11-08T15%3A54%3A08.897Z\" +\n                              \"&Version=2010-08-01\" +\n                              \"&AWSAccessKeyId=identity\",\n                        \"application/x-www-form-urlencoded\"))\n               .build();\n\n      HttpResponse listMetrics2Response = HttpResponse.builder().statusCode(200)\n               .payload(payloadFromResourceWithContentType(\"/list_metrics.xml\", \"text/xml\")).build();\n\n      CloudWatchApi apiWhenMetricsExist = requestsSendResponses(\n            listMetrics, listMetricsResponse, listMetrics2, listMetrics2Response);\n\n      assertEquals(apiWhenMetricsExist.getMetricApiForRegion(null).list().concat().toString(),\n            \"[Metric{namespace=AWS/EC2, metricName=CPUUtilization, dimension=[Dimension{name=InstanceId, value=i-689fcf0f}]}, Metric{namespace=AWS/EC2, metricName=CPUUtilization, dimension=[Dimension{name=InstanceId, value=i-689fcf0f}]}]\");\n   }\n\n   \n   public void testListMetricsWithOptionsWhenResponseIs2xx() throws Exception {\n      HttpRequest listMetricsWithOptions =\n            HttpRequest.builder()\n                       .method(\"POST\")\n                       .endpoint(\"https://monitoring.us-east-1.amazonaws.com/\")\n                       .addHeader(\"Host\", \"monitoring.us-east-1.amazonaws.com\")\n                       .payload(payloadFromStringWithContentType(\n                             \"Action=ListMetrics\" +\n                                   \"&Dimensions.member.1.Name=InstanceId\" +\n                                   \"&Dimensions.member.1.Value=SOMEINSTANCEID\" +\n                                   \"&MetricName=CPUUtilization\" +\n                                   \"&Namespace=SOMENEXTTOKEN\" +\n                                   \"&NextToken=AWS/EC2\" +\n                                   \"&Signature=G05HKEx9FJpGZBk02OVYwt3u4g/ilAY9nU5hJI9LDXA%3D\" +\n                                   \"&SignatureMethod=HmacSHA256\" +\n                                   \"&SignatureVersion=2\" +\n                                   \"&Timestamp=2009-11-08T15%3A54%3A08.897Z\" +\n                                   \"&Version=2010-08-01\" +\n                                   \"&AWSAccessKeyId=identity\",\n                             \"application/x-www-form-urlencoded\"))\n                       .build();\n      \n      HttpResponse listMetricsWithOptionsResponse = HttpResponse.builder().statusCode(200)\n               .payload(payloadFromResourceWithContentType(\"/list_metrics.xml\", \"text/xml\")).build();\n\n      CloudWatchApi apiWhenMetricsWithOptionsExist = requestSendsResponse(listMetricsWithOptions,\n               listMetricsWithOptionsResponse);\n\n      assertEquals(\n               apiWhenMetricsWithOptionsExist.getMetricApiForRegion(null).list(\n                        ListMetricsOptions.Builder\n                                          .dimension(new Dimension(EC2Constants.Dimension.INSTANCE_ID,\n                                                                   \"SOMEINSTANCEID\"))\n                                          .metricName(EC2Constants.MetricName.CPU_UTILIZATION)\n                                          .namespace(\"SOMENEXTTOKEN\")\n                                          .afterMarker(Namespaces.EC2)).toString(),\n         \"[Metric{namespace=AWS/EC2, metricName=CPUUtilization, dimension=[Dimension{name=InstanceId, value=i-689fcf0f}]}]\");\n   }\n\n   GetMetricStatistics stats = GetMetricStatistics.builder()\n                                                  .endTime(new Date(10000000L))\n                                                  .metricName(EC2Constants.MetricName.CPU_UTILIZATION)\n                                                  .namespace(Namespaces.EC2)\n                                                  .period(60)\n                                                  .startTime(new Date(10000000L))\n                                                  .statistic(Statistics.MAXIMUM)\n                                                  .statistic(Statistics.MINIMUM)\n                                                  .unit(Unit.PERCENT).build();\n   \n   HttpRequest getMetricStatistics = HttpRequest.builder()\n                                       .method(\"POST\")\n                                       .endpoint(\"https://monitoring.us-east-1.amazonaws.com/\")\n                                       .addHeader(\"Host\", \"monitoring.us-east-1.amazonaws.com\")\n                                       .payload(\n                                          payloadFromStringWithContentType(\n                                                \"Action=GetMetricStatistics\" +\n                                                      \"&EndTime=1970-01-01T02%3A46%3A40Z\" +\n                                                      \"&MetricName=CPUUtilization\" +\n                                                      \"&Namespace=AWS/EC2\" +\n                                                      \"&Period=60\" +\n                                                      \"&Signature=rmg8%2Ba7w4ycy/KfO8rnuj6rDL0jNE96m8GKfjh3SWcw%3D\" +\n                                                      \"&SignatureMethod=HmacSHA256\" +\n                                                      \"&SignatureVersion=2\" +\n                                                      \"&StartTime=1970-01-01T02%3A46%3A40Z\" +\n                                                      \"&Statistics.member.1=Maximum\" +\n                                                      \"&Statistics.member.2=Minimum\" +\n                                                      \"&Timestamp=2009-11-08T15%3A54%3A08.897Z\" +\n                                                      \"&Unit=Percent\" +\n                                                      \"&Version=2010-08-01\" +\n                                                      \"&AWSAccessKeyId=identity\",\n                                                \"application/x-www-form-urlencoded\"))\n                                       .build();\n   \n   public void testGetMetricStatisticsWhenResponseIs2xx() throws Exception {\n\n      HttpResponse getMetricStatisticsResponse = HttpResponse.builder().statusCode(200).payload(\n               payloadFromResourceWithContentType(\"/get_metric_statistics.xml\", \"text/xml\")).build();\n\n      CloudWatchApi apiWhenMetricsExist = requestSendsResponse(getMetricStatistics, getMetricStatisticsResponse);\n\n      assertEquals(\n               apiWhenMetricsExist.getMetricApiForRegion(null).getMetricStatistics(stats).toString(),\n               // TODO: make an object for this\n               \"GetMetricStatisticsResponse{label=CPUUtilization, \" +\n                     \"datapoints=[Datapoint{timestamp=Thu Jan 15 16:00:00 PST 2009, customUnit=null, maximum=null, \" +\n                     \"minimum=null, average=0.17777777777777778, sum=null, samples=9.0, unit=Percent}, \" +\n                     \"Datapoint{timestamp=Thu Jan 15 16:01:00 PST 2009, customUnit=null, maximum=null, minimum=null, \" +\n                     \"average=0.1, sum=null, samples=8.0, unit=Percent}]}\");\n   }\n\n   // TODO: this should really be an empty set\n   @Test(expectedExceptions = ResourceNotFoundException.class)\n   public void testGetMetricStatisticsWhenResponseIs404() throws Exception {\n\n      HttpResponse getMetricStatisticsResponse = HttpResponse.builder().statusCode(404).build();\n\n      CloudWatchApi apiWhenMetricsDontExist = requestSendsResponse(getMetricStatistics, getMetricStatisticsResponse);\n\n      apiWhenMetricsDontExist.getMetricApiForRegion(null).getMetricStatistics(stats);\n   }\n   \n   public void testGetMetricStatisticsWithOptionsWhenResponseIs2xx() throws Exception {\n      HttpRequest getMetricStatistics =\n            HttpRequest.builder()\n                       .method(\"POST\")\n                       .endpoint(\"https://monitoring.us-east-1.amazonaws.com/\")\n                       .addHeader(\"Host\", \"monitoring.us-east-1.amazonaws.com\")\n                       .payload(payloadFromStringWithContentType(\n                             \"Action=GetMetricStatistics\" +\n                                   \"&Dimensions.member.1.Name=InstanceId\" +\n                                   \"&Dimensions.member.1.Value=SOMEINSTANCEID\" +\n                                   \"&Dimensions.member.2.Name=InstanceType\" +\n                                   \"&Dimensions.member.2.Value=t1.micro\" +\n                                   \"&EndTime=1970-01-01T02%3A46%3A40Z\" +\n                                   \"&MetricName=CPUUtilization\" +\n                                   \"&Namespace=AWS/EC2\" +\n                                   \"&Period=60\" +\n                                   \"&Signature=e0WyI/Nm4hN2%2BMEm1mjRUzsvgvMCdFXbVJWi4ORpwic%3D\" +\n                                   \"&SignatureMethod=HmacSHA256\" +\n                                   \"&SignatureVersion=2\" +\n                                   \"&StartTime=1970-01-01T02%3A46%3A40Z\" +\n                                   \"&Statistics.member.1=Maximum\" +\n                                   \"&Statistics.member.2=Minimum\" +\n                                   \"&Timestamp=2009-11-08T15%3A54%3A08.897Z\" +\n                                   \"&Unit=Percent\" +\n                                   \"&Version=2010-08-01\" +\n                                   \"&AWSAccessKeyId=identity\",\n                             \"application/x-www-form-urlencoded\"))\n                       .build();\n\n      HttpResponse getMetricStatisticsResponse = HttpResponse.builder().statusCode(200).payload(\n               payloadFromResourceWithContentType(\"/get_metric_statistics.xml\", \"text/xml\")).build();\n\n      CloudWatchApi apiWhenMetricsExist = requestSendsResponse(getMetricStatistics, getMetricStatisticsResponse);\n\n      Dimension dimension1 = new Dimension(EC2Constants.Dimension.INSTANCE_ID, \"SOMEINSTANCEID\");\n      Dimension dimension2 = new Dimension(EC2Constants.Dimension.INSTANCE_TYPE, \"t1.micro\");\n\n      assertEquals(\n               apiWhenMetricsExist.getMetricApiForRegion(null).getMetricStatistics(stats,\n                        GetMetricStatisticsOptions.Builder.dimension(dimension1).dimension(dimension2)).toString(),\n               // TODO: make an object for this\n               \"GetMetricStatisticsResponse{label=CPUUtilization, \" +\n                     \"datapoints=[Datapoint{timestamp=Thu Jan 15 16:00:00 PST 2009, customUnit=null, maximum=null, \" +\n                     \"minimum=null, average=0.17777777777777778, sum=null, samples=9.0, unit=Percent}, \" +\n                     \"Datapoint{timestamp=Thu Jan 15 16:01:00 PST 2009, customUnit=null, maximum=null, minimum=null, \" +\n                     \"average=0.1, sum=null, samples=8.0, unit=Percent}]}\");\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/features/MetricApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.features;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static java.util.concurrent.TimeUnit.MINUTES;\nimport static org.jclouds.util.Predicates2.retry;\n\nimport java.util.Calendar;\nimport java.util.Date;\nimport java.util.Set;\n\nimport org.jclouds.cloudwatch.domain.Datapoint;\nimport org.jclouds.cloudwatch.domain.Dimension;\nimport org.jclouds.cloudwatch.domain.EC2Constants;\nimport org.jclouds.cloudwatch.domain.GetMetricStatistics;\nimport org.jclouds.cloudwatch.domain.GetMetricStatisticsResponse;\nimport org.jclouds.cloudwatch.domain.Metric;\nimport org.jclouds.cloudwatch.domain.MetricDatum;\nimport org.jclouds.cloudwatch.domain.Namespaces;\nimport org.jclouds.cloudwatch.domain.StatisticValues;\nimport org.jclouds.cloudwatch.domain.Statistics;\nimport org.jclouds.cloudwatch.domain.Unit;\nimport org.jclouds.cloudwatch.internal.BaseCloudWatchApiLiveTest;\nimport org.jclouds.cloudwatch.options.ListMetricsOptions;\nimport org.jclouds.collect.IterableWithMarker;\nimport org.testng.Assert;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\n\n@Test(groups = \"live\", testName = \"MetricApiLiveTest\")\npublic class MetricApiLiveTest extends BaseCloudWatchApiLiveTest {\n\n   @Test\n   protected void testPutMetricData() throws Exception {\n      String metricName = \"TestMetricName\" + System.currentTimeMillis();\n      String namespace = \"JCLOUDS/Test\";\n      Date metricTimestamp = new Date();\n      // CloudWatch rounds metric timestamps down to the closest minute\n      Date metricTimestampInCloudWatch =\n            new Date(metricTimestamp.getTime() - (metricTimestamp.getTime() % (60 * 1000)));\n      StatisticValues ss = StatisticValues.builder()\n                                    .maximum(4.0)\n                                    .minimum(1.0)\n                                    .sampleCount(4.0)\n                                    .sum(10.0)\n                                    .build();\n      MetricDatum metricDatum = MetricDatum.builder()\n                                           .metricName(metricName + \"_1\")\n                                           .statisticValues(ss)\n                                           .dimension(new Dimension(\"BaseMetricName\", metricName))\n                                           .dimension(new Dimension(\"TestDimension2\", \"TEST2\"))\n                                           .unit(Unit.COUNT)\n                                           .timestamp(metricTimestamp)\n                                           .build();\n      MetricDatum metricDatum2 = MetricDatum.builder()\n                                           .metricName(metricName + \"_2\")\n                                           .dimension(new Dimension(\"BaseMetricName\", metricName))\n                                           .unit(Unit.COUNT)\n                                           .timestamp(metricTimestamp)\n                                           .value(10.0)\n                                           .build();\n\n      api().putMetricsInNamespace(ImmutableSet.of(metricDatum, metricDatum2), namespace);\n\n      ListMetricsOptions lmo = ListMetricsOptions.Builder.namespace(namespace)\n                                                 .dimension(new Dimension(\"BaseMetricName\", metricName));\n      boolean success = retry(new Predicate<ListMetricsOptions>() {\n         public boolean apply(ListMetricsOptions options) {\n            return Iterables.size(api().list(options)) == 2;\n         }\n      }, 20, 1, MINUTES).apply(lmo);\n\n      if (!success) {\n         Assert.fail(\"Unable to gather the created CloudWatch data within the time (20m) allotted.\");\n      }\n\n      IterableWithMarker<Metric> lmr = api().list(lmo);\n      Date endTime = new Date(metricTimestampInCloudWatch.getTime() + (60 * 1000)); // Pad a minute just in case\n      Date startTime = new Date(metricTimestampInCloudWatch.getTime() - (60 * 1000)); // Pad a minute just in case\n\n      for (Metric m : lmr) {\n         GetMetricStatistics gms = GetMetricStatistics.builder()\n                                                      .dimensions(m.getDimensions())\n                                                      .namespace(namespace)\n                                                      .metricName(m.getMetricName())\n                                                      .endTime(endTime)\n                                                      .statistic(Statistics.MAXIMUM)\n                                                      .statistic(Statistics.MINIMUM)\n                                                      .statistic(Statistics.SAMPLE_COUNT)\n                                                      .statistic(Statistics.SUM)\n                                                      .period(60)\n                                                      .startTime(startTime)\n                                                      .unit(Unit.COUNT)\n                                                      .build();\n         GetMetricStatisticsResponse gmr = api().getMetricStatistics(gms);\n\n         Assert.assertEquals(1, Iterables.size(gmr));\n\n         Datapoint datapoint = gmr.iterator().next();\n\n         Assert.assertEquals(datapoint.getTimestamp(), metricTimestampInCloudWatch);\n         Assert.assertNull(datapoint.getCustomUnit());\n         Assert.assertEquals(Unit.COUNT, datapoint.getUnit());\n         Assert.assertNull(datapoint.getAverage());\n\n         if (m.getDimensions().size() == 1) {\n            Assert.assertEquals(10.0, datapoint.getMaximum());\n            Assert.assertEquals(10.0, datapoint.getMinimum());\n            Assert.assertEquals(10.0, datapoint.getSum());\n            Assert.assertEquals(1.0, datapoint.getSamples());\n         } else {\n            Assert.assertEquals(4.0, datapoint.getMaximum());\n            Assert.assertEquals(1.0, datapoint.getMinimum());\n            Assert.assertEquals(10.0, datapoint.getSum());\n            Assert.assertEquals(4.0, datapoint.getSamples());\n         }\n      }\n   }\n\n   // TODO: change this test to retrieve pre-seeded custom metrics\n   @Test\n   protected void testGetMetricStatistics() {\n      IterableWithMarker<Metric> metricsResponse = api().list(new ListMetricsOptions());\n\n      // Walk through all datapoints in all metrics until we find a metric datapoint that returns statistics\n      if (Iterables.size(metricsResponse) > 0) {\n         for (Metric metric : metricsResponse) {\n            Set<Dimension> dimensions = metric.getDimensions();\n            boolean testRan = false;\n\n            for (Dimension dimension : dimensions) {\n               Date endTime = new Date();\n               Calendar cal = Calendar.getInstance();\n\n               cal.add(Calendar.MINUTE, -60 * 24); // 24 hours\n\n               GetMetricStatistics options =\n                     GetMetricStatistics.builder()\n                                                 .dimension(dimension)\n                                                 .endTime(endTime)\n                                                 .metricName(metric.getMetricName())\n                                                 .namespace(metric.getNamespace())\n                                                 .period(300)\n                                                 .startTime(cal.getTime())\n                                                 .statistics(ImmutableSet.of(Statistics.MAXIMUM,\n                                                                             Statistics.MINIMUM))\n                                                 .unit(Unit.PERCENT).build();\n               GetMetricStatisticsResponse response = api().getMetricStatistics(options);\n\n               if (!response.isEmpty()) {\n                  checkNotNull(response.getLabel());\n\n                  for (Datapoint datapoint : response) {\n                     checkArgument(datapoint.getAverage() == null);\n                     checkNotNull(datapoint.getMaximum());\n                     checkNotNull(datapoint.getMinimum());\n                  }\n\n                  testRan = true;\n                  break;\n                }\n            }\n\n            if (testRan) {\n               break;\n            }\n         }\n      }\n   }\n\n   @Test\n   protected void testListMetrics() {\n      IterableWithMarker<Metric> response;\n      String testNamespace = Namespaces.EC2;\n      String testMetricName = EC2Constants.MetricName.CPU_UTILIZATION;\n      String testDimensionName = EC2Constants.Dimension.INSTANCE_TYPE;\n      String testDimensionValue = \"t1.micro\";\n\n      // Test an empty request (pulls all stored metric options across all products)\n      response = api().list(new ListMetricsOptions());\n\n      performDefaultMetricsTests(response);\n\n      if (!Iterables.isEmpty(response)) {\n         Metric metric = response.iterator().next();\n\n         testMetricName = metric.getMetricName();\n         testNamespace = metric.getNamespace();\n\n         if (!metric.getDimensions().isEmpty()) {\n            Dimension dimension = metric.getDimensions().iterator().next();\n\n            testDimensionName = dimension.getName();\n            testDimensionValue = dimension.getValue();\n         }\n\n         if (testDimensionName == null) {\n            for (Metric metric1 : response) {\n               Set<Dimension> dimensions = metric1.getDimensions();\n\n               if (!dimensions.isEmpty()) {\n                  Dimension dimension = metric.getDimensions().iterator().next();\n\n                  testDimensionName = dimension.getName();\n                  testDimensionValue = dimension.getValue();\n\n                  break;\n               }\n            }\n         }\n      }\n\n      // Test with a NextToken, even if it's null\n      response = api().list(ListMetricsOptions.Builder.afterMarker(response.nextMarker().orNull()));\n\n      performDefaultMetricsTests(response);\n\n      // Test with a Namespace\n      response = api().list(ListMetricsOptions.Builder.namespace(testNamespace));\n\n      performDefaultMetricsTests(response);\n\n      for (Metric metric : response) {\n         checkArgument(metric.getNamespace().equals(testNamespace),\n                       \"All metrics should have the \" + testNamespace + \" Namespace.\");\n      }\n\n      // Test with a MetricName\n      response = api().list(ListMetricsOptions.Builder.metricName(testMetricName));\n\n      performDefaultMetricsTests(response);\n\n      for (Metric metric : response) {\n         checkArgument(metric.getMetricName().equals(testMetricName),\n                       \"All metrics should have the \" + testMetricName + \" MetricName.\");\n      }\n\n      // Test with a Dimension\n      if (testDimensionName != null) {\n         Dimension testDimension = new Dimension(testDimensionName, testDimensionValue);\n\n         response = api().list(ListMetricsOptions.Builder.dimension(testDimension));\n\n         performDefaultMetricsTests(response);\n\n         for (Metric metric : response) {\n            Set<Dimension> dimensions = metric.getDimensions();\n            boolean dimensionFound = false;\n\n            for (Dimension dimension : dimensions) {\n               if (dimension.getName().equals(testDimensionName)) {\n                  dimensionFound = true;\n                  break;\n               }\n            }\n\n            checkArgument(dimensionFound, \"All metrics should have the \" + testDimensionName + \" Dimension.Name.\");\n         }\n      }\n   }\n\n   private void performDefaultMetricsTests(IterableWithMarker<Metric> response) {\n      // If there are less than 500 metrics, NextToken should be null\n      if (Iterables.size(response) < 500) {\n         checkArgument(!response.nextMarker().isPresent(),\n                       \"NextToken should be null for response with fewer than 500 metrics.\");\n      }\n\n      for (Metric metric : response) {\n         Set<Dimension> dimensions = metric.getDimensions();\n\n         checkArgument(dimensions.size() <= 10, \"Dimensions set cannot be greater than 10 items.\");\n\n         for (Dimension dimension : dimensions) {\n            checkNotNull(dimension.getName(), \"Name cannot be null for a Dimension.\");\n            checkNotNull(dimension.getValue(), \"Value cannot be null for a Dimension.\");\n         }\n\n         checkNotNull(metric.getMetricName(), \"MetricName cannot be null for a Metric.\");\n         checkNotNull(metric.getNamespace(), \"Namespace cannot be null for a Metric.\");\n      }\n   }\n\n   protected MetricApi api() {\n      return api.getMetricApiForRegion(null);\n   }\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/internal/BaseCloudWatchApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.internal;\n\nimport org.jclouds.cloudwatch.CloudWatchApi;\n\npublic class BaseCloudWatchApiExpectTest extends BaseCloudWatchExpectTest<CloudWatchApi> {\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/internal/BaseCloudWatchApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.internal;\n\nimport org.jclouds.apis.BaseApiLiveTest;\nimport org.jclouds.cloudwatch.CloudWatchApi;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\")\npublic class BaseCloudWatchApiLiveTest extends BaseApiLiveTest<CloudWatchApi> {\n\n   public BaseCloudWatchApiLiveTest() {\n      provider = \"cloudwatch\";\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/internal/BaseCloudWatchExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.internal;\n\nimport static com.google.common.collect.Maps.transformValues;\n\nimport java.net.URI;\nimport java.util.Map;\n\nimport org.jclouds.aws.domain.Region;\nimport org.jclouds.cloudwatch.config.CloudWatchHttpApiModule;\nimport org.jclouds.date.DateService;\nimport org.jclouds.location.config.LocationModule;\nimport org.jclouds.location.suppliers.RegionIdToURISupplier;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.internal.BaseRestApiExpectTest;\nimport org.jclouds.util.Suppliers2;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.inject.Module;\n\npublic class BaseCloudWatchExpectTest<T> extends BaseRestApiExpectTest<T> {\n\n   public BaseCloudWatchExpectTest() {\n      provider = \"cloudwatch\";\n   }\n   \n   @ConfiguresHttpApi\n   private static final class TestMonitoringHttpApiModule extends CloudWatchHttpApiModule {\n\n      @Override\n      protected void installLocations() {\n         install(new LocationModule());\n         bind(RegionIdToURISupplier.class).toInstance(new RegionIdToURISupplier() {\n\n            @Override\n            public Map<String, Supplier<URI>> get() {\n               return transformValues(ImmutableMap.<String, URI> of(Region.EU_WEST_1, URI\n                        .create(\"https://ec2.eu-west-1.amazonaws.com\"), Region.US_EAST_1, URI\n                        .create(\"https://ec2.us-east-1.amazonaws.com\"), Region.US_WEST_1, URI\n                        .create(\"https://ec2.us-west-1.amazonaws.com\")), Suppliers2.<URI> ofInstanceFunction());\n            }\n\n         });\n      }\n\n      @Override\n      protected String provideTimeStamp(final DateService dateService) {\n         return \"2009-11-08T15:54:08.897Z\";\n      }\n   }\n\n   @Override\n   protected Module createModule() {\n      return new TestMonitoringHttpApiModule();\n   }\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/options/GetMetricStatisticsOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.options;\n\nimport static org.jclouds.cloudwatch.options.GetMetricStatisticsOptions.Builder.instanceId;\nimport static org.jclouds.cloudwatch.options.GetMetricStatisticsOptions.Builder.unit;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.cloudwatch.domain.Unit;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code GetMetricStatisticsOptions}\n */\n@Test(groups = \"unit\")\npublic class GetMetricStatisticsOptionsTest {\n\n   public void testInstanceId() {\n      GetMetricStatisticsOptions options = new GetMetricStatisticsOptions().instanceId(\"us-east-1/i-123\");\n      assertEquals(ImmutableSet.of(\"InstanceId\"), options.buildFormParameters().get(\"Dimensions.member.1.Name\"));\n      assertEquals(ImmutableSet.of(\"i-123\"), options.buildFormParameters().get(\"Dimensions.member.1.Value\"));\n   }\n\n   public void testInstanceIdStatic() {\n      GetMetricStatisticsOptions options = instanceId(\"us-east-1/i-123\");\n      assertEquals(ImmutableSet.of(\"InstanceId\"), options.buildFormParameters().get(\"Dimensions.member.1.Name\"));\n      assertEquals(ImmutableSet.of(\"i-123\"), options.buildFormParameters().get(\"Dimensions.member.1.Value\"));\n   }\n\n   public void testUnit() {\n      GetMetricStatisticsOptions options = new GetMetricStatisticsOptions().unit(Unit.GIGABYTES_PER_SECOND);\n      assertEquals(ImmutableSet.of(\"Gigabytes/Second\"), options.buildFormParameters().get(\"Unit\"));\n   }\n\n   public void testUnitStatic() {\n      GetMetricStatisticsOptions options = unit(Unit.GIGABYTES_PER_SECOND);\n      assertEquals(ImmutableSet.of(\"Gigabytes/Second\"), options.buildFormParameters().get(\"Unit\"));\n   }\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/options/ListAlarmHistoryOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.options;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\n\nimport java.util.Date;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Multimap;\nimport org.jclouds.cloudwatch.domain.HistoryItemType;\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code ListAlarmHistoryOptions}.\n */\n@Test(groups = \"unit\")\npublic class ListAlarmHistoryOptionsTest {\n\n   private DateService dateService = new SimpleDateFormatDateService();\n\n   public void testEmptyOptions() throws Exception {\n      Multimap<String, String> formParameters = new ListAlarmHistoryOptions().buildFormParameters();\n\n      assertFalse(formParameters.containsKey(\"AlarmName\"));\n      assertFalse(formParameters.containsKey(\"EndDate\"));\n      assertFalse(formParameters.containsKey(\"HistoryItemType\"));\n      assertFalse(formParameters.containsKey(\"MaxRecords\"));\n      assertFalse(formParameters.containsKey(\"NextToken\"));\n      assertFalse(formParameters.containsKey(\"StartDate\"));\n   }\n\n   public void testPopulatedOptions() throws Exception {\n      String alarmName = \"TestAlarmName\";\n      Date endDate = new Date(new Date().getTime() + 5000);\n      HistoryItemType historyItemType = HistoryItemType.ACTION;\n      int maxRecords = 5;\n      Date startDate = new Date();\n      Multimap<String, String> formParameters = new ListAlarmHistoryOptions()\n            .alarmName(alarmName)\n            .endDate(endDate)\n            .historyItemType(historyItemType)\n            .maxRecords(maxRecords)\n            .startDate(startDate)\n            .buildFormParameters();\n\n      assertEquals(formParameters.get(\"AlarmName\"), ImmutableSet.of(alarmName));\n      assertEquals(formParameters.get(\"EndDate\"), ImmutableSet.of(dateService.iso8601DateFormat(endDate)));\n      assertEquals(formParameters.get(\"HistoryItemType\"), ImmutableSet.of(historyItemType.toString()));\n      assertEquals(formParameters.get(\"MaxRecords\"), ImmutableSet.of(Integer.toString(maxRecords)));\n      assertEquals(formParameters.get(\"StartDate\"), ImmutableSet.of(dateService.iso8601DateFormat(startDate)));\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/options/ListAlarmsForMetricTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.options;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\n\nimport java.util.Set;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Multimap;\nimport org.jclouds.cloudwatch.domain.Dimension;\nimport org.jclouds.cloudwatch.domain.Namespaces;\nimport org.jclouds.cloudwatch.domain.Statistics;\nimport org.jclouds.cloudwatch.domain.Unit;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code ListAlarmsForMetric}.\n */\n@Test(groups = \"unit\")\npublic class ListAlarmsForMetricTest {\n\n   public void testEmptyOptions() throws Exception {\n      Multimap<String, String> formParameters = new ListAlarmsForMetric().buildFormParameters();\n\n      assertFalse(formParameters.containsKey(\"Dimensions.member.1.Name\"));\n      assertFalse(formParameters.containsKey(\"Dimensions.member.1.Value\"));\n      assertFalse(formParameters.containsKey(\"MetricName\"));\n      assertFalse(formParameters.containsKey(\"Namespace\"));\n      assertFalse(formParameters.containsKey(\"Period\"));\n      assertFalse(formParameters.containsKey(\"Statistic\"));\n      assertFalse(formParameters.containsKey(\"Unit\"));\n   }\n\n   public void testPopulatedOptions() throws Exception {\n      Set<Dimension> dimensions = ImmutableSet.of(\n         new Dimension(\"TestDimension1\", \"TestValue1\"),\n         new Dimension(\"TestDimension2\", \"TestValue2\")\n      );\n      String metricName = \"TestMetricName\";\n      String namespace = Namespaces.EC2;\n      int period = 60;\n      Statistics statistic = Statistics.AVERAGE;\n      Unit unit = Unit.COUNT;\n      Multimap<String, String> formParameters = new ListAlarmsForMetric()\n            .dimensions(dimensions)\n            .metricName(metricName)\n            .namespace(namespace)\n            .period(period)\n            .statistic(statistic)\n            .unit(unit)\n            .buildFormParameters();\n      int dimensionIndex = 1;\n\n      for (Dimension dimension : dimensions) {\n         assertEquals(formParameters.get(\"Dimensions.member.\" + dimensionIndex + \".Name\"),\n                      ImmutableSet.of(dimension.getName()));\n         assertEquals(formParameters.get(\"Dimensions.member.\" + dimensionIndex + \".Value\"),\n                      ImmutableSet.of(dimension.getValue()));\n         dimensionIndex++;\n      }\n\n      assertEquals(formParameters.get(\"MetricName\"), ImmutableSet.of(metricName));\n      assertEquals(formParameters.get(\"Namespace\"), ImmutableSet.of(namespace));\n      assertEquals(formParameters.get(\"Period\"), ImmutableSet.of(Integer.toString(period)));\n      assertEquals(formParameters.get(\"Statistic\"), ImmutableSet.of(statistic.toString()));\n      assertEquals(formParameters.get(\"Unit\"), ImmutableSet.of(unit.toString()));\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/options/ListAlarmsOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.options;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\n\nimport java.util.Set;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Multimap;\nimport org.jclouds.cloudwatch.domain.Alarm;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code ListAlarmsOptions}.\n */\n@Test(groups = \"unit\")\npublic class ListAlarmsOptionsTest {\n\n   public void testEmptyOptions() throws Exception {\n      Multimap<String, String> formParameters = new ListAlarmsOptions().buildFormParameters();\n\n      assertFalse(formParameters.containsKey(\"ActionPrefix\"));\n      assertFalse(formParameters.containsKey(\"AlarmNamePrefix\"));\n      assertFalse(formParameters.containsKey(\"AlarmNames.member.1\"));\n      assertFalse(formParameters.containsKey(\"MaxRecords\"));\n      assertFalse(formParameters.containsKey(\"NextToken\"));\n      assertFalse(formParameters.containsKey(\"StateValue\"));\n   }\n\n   public void testPopulatedOptions() throws Exception {\n      String actionPrefix = \"TestActionPrefix\";\n      String alarmNamePrefix = \"TestAlarmNamePrefix\";\n      Set<String> alarmNames = ImmutableSet.of(\n            \"TestAlarmName1\",\n            \"TestAlarmName2\"\n      );\n      int maxRecords = 5;\n      Alarm.State state = Alarm.State.ALARM;\n      int alarmNameIndex = 1;\n      Multimap<String, String> formParameters = new ListAlarmsOptions()\n            .actionPrefix(actionPrefix)\n            .alarmNamePrefix(alarmNamePrefix)\n            .alarmNames(alarmNames)\n            .maxRecords(maxRecords)\n            .state(state)\n            .buildFormParameters();\n\n      assertEquals(formParameters.get(\"ActionPrefix\"), ImmutableSet.of(actionPrefix));\n      assertEquals(formParameters.get(\"AlarmNamePrefix\"), ImmutableSet.of(alarmNamePrefix));\n      assertEquals(formParameters.get(\"MaxRecords\"), ImmutableSet.of(Integer.toString(maxRecords)));\n      assertEquals(formParameters.get(\"StateValue\"), ImmutableSet.of(state.toString()));\n\n      for (String alarmName : alarmNames) {\n         assertEquals(formParameters.get(\"AlarmNames.member.\" + alarmNameIndex), ImmutableSet.of(alarmName));\n         alarmNameIndex++;\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/options/SaveAlarmOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.options;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\n\nimport java.util.Set;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Multimap;\nimport org.jclouds.cloudwatch.domain.ComparisonOperator;\nimport org.jclouds.cloudwatch.domain.Dimension;\nimport org.jclouds.cloudwatch.domain.Namespaces;\nimport org.jclouds.cloudwatch.domain.Statistics;\nimport org.jclouds.cloudwatch.domain.Unit;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code SaveAlarmOptions}.\n */\n@Test(groups = \"unit\")\npublic class SaveAlarmOptionsTest {\n\n   public void testEmptyOptions() throws Exception {\n      Multimap<String, String> formParameters = new SaveAlarmOptions().buildFormParameters();\n\n      assertFalse(formParameters.containsKey(\"ActionsEnabled\"));\n      assertFalse(formParameters.containsKey(\"AlarmActions.member.1\"));\n      assertFalse(formParameters.containsKey(\"AlarmDescription\"));\n      assertFalse(formParameters.containsKey(\"AlarmName\"));\n      assertFalse(formParameters.containsKey(\"ComparisonOperator\"));\n      assertFalse(formParameters.containsKey(\"Dimensions.member.1.Name\"));\n      assertFalse(formParameters.containsKey(\"Dimensions.member.1.Value\"));\n      assertFalse(formParameters.containsKey(\"EvaluationPeriods\"));\n      assertFalse(formParameters.containsKey(\"InsufficientDataActions.member.1\"));\n      assertFalse(formParameters.containsKey(\"MetricName\"));\n      assertFalse(formParameters.containsKey(\"Namespace\"));\n      assertFalse(formParameters.containsKey(\"OKActions.member.1\"));\n      assertFalse(formParameters.containsKey(\"Period\"));\n      assertFalse(formParameters.containsKey(\"Statistic\"));\n      assertFalse(formParameters.containsKey(\"Threshold\"));\n      assertFalse(formParameters.containsKey(\"Unit\"));\n   }\n\n   public void testPopulatedOptions() throws Exception {\n      boolean actionsEnabled = false;\n      Set<String> alarmActions = ImmutableSet.of(\n            \"TestAlarmAction1\",\n            \"TestAlarmAction2\"\n      );\n      String alarmDescription = \"TestAlarmDescription\";\n      String alarmName = \"TestAlarmName\";\n      ComparisonOperator comparisonOperator = ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD;\n      Set<Dimension> dimensions = ImmutableSet.of(\n            new Dimension(\"TestDimension1\", \"TestValue1\"),\n            new Dimension(\"TestDimension2\", \"TestValue2\")\n      );\n      int evaluationPeriods = 360;\n      Set<String> insufficientDataActions = ImmutableSet.of(\n            \"TestInsufficientDataAction1\",\n            \"TestInsufficientDataAction2\"\n      );\n      String metricName = \"TestMetricName\";\n      String namespace = Namespaces.AUTO_SCALING;\n      Set<String> okActions = ImmutableSet.of(\n            \"TestOKAction1\",\n            \"TestOKAction2\"\n      );\n      int period = 300;\n      Statistics statistic = Statistics.SAMPLE_COUNT;\n      double threshold = 1.0;\n      Unit unit = Unit.BITS;\n      Multimap<String, String> formParameters = new SaveAlarmOptions()\n            .actionsEnabled(actionsEnabled)\n            .alarmActions(alarmActions)\n            .alarmDescription(alarmDescription)\n            .alarmName(alarmName)\n            .comparisonOperator(comparisonOperator)\n            .dimensions(dimensions)\n            .evaluationPeriods(evaluationPeriods)\n            .insufficientDataActions(insufficientDataActions)\n            .metricName(metricName)\n            .namespace(namespace)\n            .okActions(okActions)\n            .period(period)\n            .statistic(statistic)\n            .threshold(threshold)\n            .unit(unit)\n            .buildFormParameters();\n      int alarmActionIndex = 1;\n      int dimensionIndex = 1;\n      int insufficientDataActionIndex = 1;\n      int okActionIndex = 1;\n\n      for (String alarmAction : alarmActions) {\n         assertEquals(formParameters.get(\"AlarmActions.member.\" + alarmActionIndex), ImmutableSet.of(alarmAction));\n         alarmActionIndex++;\n      }\n\n      for (Dimension dimension : dimensions) {\n         assertEquals(formParameters.get(\"Dimensions.member.\" + dimensionIndex + \".Name\"),\n                      ImmutableSet.of(dimension.getName()));\n         assertEquals(formParameters.get(\"Dimensions.member.\" + dimensionIndex + \".Value\"),\n                      ImmutableSet.of(dimension.getValue()));\n         dimensionIndex++;\n      }\n\n      for (String insufficientDataAction : insufficientDataActions) {\n         assertEquals(formParameters.get(\"InsufficientDataActions.member.\" + insufficientDataActionIndex),\n                      ImmutableSet.of(insufficientDataAction));\n         insufficientDataActionIndex++;\n      }\n\n      for (String okAction : okActions) {\n         assertEquals(formParameters.get(\"OKActions.member.\" + okActionIndex), ImmutableSet.of(okAction));\n         okActionIndex++;\n      }\n\n      assertEquals(formParameters.get(\"ActionsEnabled\"), ImmutableSet.of(Boolean.toString(actionsEnabled)));\n      assertEquals(formParameters.get(\"AlarmDescription\"), ImmutableSet.of(alarmDescription));\n      assertEquals(formParameters.get(\"AlarmName\"), ImmutableSet.of(alarmName));\n      assertEquals(formParameters.get(\"ComparisonOperator\"), ImmutableSet.of(comparisonOperator.toString()));\n      assertEquals(formParameters.get(\"EvaluationPeriods\"), ImmutableSet.of(Integer.toString(evaluationPeriods)));\n      assertEquals(formParameters.get(\"MetricName\"), ImmutableSet.of(metricName));\n      assertEquals(formParameters.get(\"Namespace\"), ImmutableSet.of(namespace));\n      assertEquals(formParameters.get(\"Period\"), ImmutableSet.of(Integer.toString(period)));\n      assertEquals(formParameters.get(\"Statistic\"), ImmutableSet.of(statistic.toString()));\n      assertEquals(formParameters.get(\"Threshold\"), ImmutableSet.of(Double.toString(threshold)));\n      assertEquals(formParameters.get(\"Unit\"), ImmutableSet.of(unit.toString()));\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/xml/GetMetricStatisticsResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.xml;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\nimport java.util.Set;\n\nimport org.jclouds.cloudwatch.domain.Datapoint;\nimport org.jclouds.cloudwatch.domain.Unit;\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code GetMetricStatisticsResponseHandler}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"GetMetricStatisticsResponseHandlerTest\")\npublic class GetMetricStatisticsResponseHandlerTest extends BaseHandlerTest {\n   public void testApplyInputStream() {\n      InputStream is = getClass().getResourceAsStream(\"/get_metric_statistics.xml\");\n\n      Set<Datapoint> expected = expected();\n\n      GetMetricStatisticsResponseHandler handler = injector.getInstance(GetMetricStatisticsResponseHandler.class);\n      Set<Datapoint> result = factory.create(handler).parse(is);\n\n      assertEquals(result, expected);\n   }\n\n   DateService dateService = new SimpleDateFormatDateService();\n\n   public Set<Datapoint> expected() {\n\n      Set<Datapoint> expected = ImmutableSet.of(new Datapoint(0.17777777777777778, null, null, dateService\n               .iso8601SecondsDateParse(\"2009-01-16T00:00:00Z\"), 9.0, null, Unit.PERCENT, null), new Datapoint(0.1,\n               null, null, dateService.iso8601SecondsDateParse(\"2009-01-16T00:01:00Z\"), 8.0, null, Unit.PERCENT, null));\n      return expected;\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/xml/ListAlarmHistoryResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.xml;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\n\nimport java.util.Set;\n\nimport com.google.common.collect.Sets;\nimport org.jclouds.cloudwatch.domain.AlarmHistoryItem;\nimport org.jclouds.cloudwatch.domain.HistoryItemType;\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.IterableWithMarkers;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code ListAlarmHistoryResponseHandler}.  Implicitly tests behavior of\n * {@code MetricAlarmHandler}.\n */\n// NOTE: Without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"ListAlarmHistoryResponseHandlerTest\")\npublic class ListAlarmHistoryResponseHandlerTest extends BaseHandlerTest {\n\n   /**\n    * Tests parsing all possible XML elements that could be encountered by {@link ListAlarmHistoryResponseHandler}.\n    *\n    * @throws Exception if something goes wrong\n    */\n   public void testParseFullResponse() throws Exception {\n      IterableWithMarker<AlarmHistoryItem> alarmHistoryItems =\n            factory.create(injector.getInstance(ListAlarmHistoryResponseHandler.class))\n                   .parse(getClass().getResourceAsStream(\"/DescribeAlarmHistoryResponse.xml\"));\n\n      assertEquals(alarmHistoryItems.toString(), expected().toString());\n      assertFalse(alarmHistoryItems.nextMarker().isPresent());\n   }\n\n   public IterableWithMarker<AlarmHistoryItem> expected() {\n      Set<AlarmHistoryItem> alarmHistoryItems = Sets.newLinkedHashSet();\n\n      for (int i = 1; i <= 2; i++) {\n         alarmHistoryItems.add(new AlarmHistoryItem(\n               \"TestAlarmName\" + i,\n               \"{\\\"reason\\\": \\\"\" + i + \"\\\"}\",\n               i == 1 ?\n                     HistoryItemType.ACTION :\n                     HistoryItemType.CONFIGURATION_UPDATE,\n               \"This is test \" + i + \".\",\n               new SimpleDateFormatDateService()\n                     .iso8601SecondsDateParse(\"2013-01-0\" + i + \"T00:00:00Z\")\n         ));\n      }\n\n      return IterableWithMarkers.from(alarmHistoryItems);\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/xml/ListAlarmsForMetricResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.xml;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Set;\n\nimport com.beust.jcommander.internal.Sets;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableSet;\nimport org.jclouds.cloudwatch.domain.Alarm;\nimport org.jclouds.cloudwatch.domain.ComparisonOperator;\nimport org.jclouds.cloudwatch.domain.Dimension;\nimport org.jclouds.cloudwatch.domain.Namespaces;\nimport org.jclouds.cloudwatch.domain.Statistics;\nimport org.jclouds.cloudwatch.domain.Unit;\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code ListAlarmsForMetricResponseHandler}.  Implicitly tests behavior of\n * {@code MetricAlarmHandler}.\n */\n// NOTE: Without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"ListAlarmsForMetricResponseHandlerTest\")\npublic class ListAlarmsForMetricResponseHandlerTest extends BaseHandlerTest {\n\n   private final DateService dateService = new SimpleDateFormatDateService();\n\n   /**\n    * Tests parsing all possible XML elements that could be encountered by {@link ListAlarmsForMetricResponseHandler}.\n    *\n    * @throws Exception if something goes wrong\n    */\n   public void testParseFullResponse() throws Exception {\n      Iterable<Alarm> metricAlarms =\n            factory.create(injector.getInstance(ListAlarmsForMetricResponseHandler.class))\n                   .parse(getClass().getResourceAsStream(\"/DescribeAlarmsForMetricResponse.xml\"));\n\n      assertEquals(metricAlarms.toString(), expected().toString());\n   }\n\n   public Iterable<Alarm> expected() {\n      Set<Alarm> alarms = Sets.newLinkedHashSet();\n\n      for (int i = 1; i <= 2; i++) {\n         alarms.add(new Alarm(\n               i == 1,\n               ImmutableSet.of(\"TestAction1\", \"TestAction2\"),\n               \"TestAlarmARN\" + i,\n               dateService.iso8601SecondsDateParse(\"2013-01-0\" + i + \"T00:00:00Z\"),\n               \"This is test alarm \" + i + \".\",\n               \"TestAlarmName\" + i,\n               i == 1 ?\n                     ComparisonOperator.GREATER_THAN_THRESHOLD :\n                     ComparisonOperator.LESS_THAN_THRESHOLD,\n               ImmutableSet.of(\n                     new Dimension(\"TestDimensionName1\", \"TestDimensionValue1\"),\n                     new Dimension(\"TestDimensionName2\", \"TestDimensionValue2\")\n               ),\n               60 * i,\n               ImmutableSet.of(\"TestAction1\", \"TestAction2\"),\n               \"TestMetricName\" + i,\n               Namespaces.EC2,\n               ImmutableSet.of(\"TestAction1\", \"TestAction2\"),\n               60 * i,\n               \"This is state reason \" + i + \".\",\n               Optional.of(\"{\\\"reason\\\": \\\"\" + i + \"\\\"}\"),\n               dateService.iso8601SecondsDateParse(\"2013-01-0\" + i + \"T00:00:00Z\"),\n               i == 1 ?\n                     Alarm.State.INSUFFICIENT_DATA :\n                     Alarm.State.OK,\n               i == 1 ?\n                     Statistics.SAMPLE_COUNT :\n                     Statistics.AVERAGE,\n               Double.valueOf(Integer.toString(i)),\n               i == 1 ?\n                     Optional.of(Unit.SECONDS) :\n                     Optional.of(Unit.COUNT_PER_SECOND)\n         ));\n      }\n\n      return alarms;\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/xml/ListAlarmsResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cloudwatch.xml;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\n\nimport java.util.Set;\n\nimport com.beust.jcommander.internal.Sets;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableSet;\nimport org.jclouds.cloudwatch.domain.Alarm;\nimport org.jclouds.cloudwatch.domain.ComparisonOperator;\nimport org.jclouds.cloudwatch.domain.Dimension;\nimport org.jclouds.cloudwatch.domain.Namespaces;\nimport org.jclouds.cloudwatch.domain.Statistics;\nimport org.jclouds.cloudwatch.domain.Unit;\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.IterableWithMarkers;\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code ListAlarmsResponseHandler}.  Implicitly tests behavior of {@code MetricAlarmHandler}.\n */\n// NOTE: Without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"ListAlarmsResponseHandlerTest\")\npublic class ListAlarmsResponseHandlerTest extends BaseHandlerTest {\n\n   private final DateService dateService = new SimpleDateFormatDateService();\n\n   /**\n    * Tests parsing all possible XML elements that could be encountered by {@link ListAlarmsResponseHandler}.\n    *\n    * @throws Exception if something goes wrong\n    */\n   public void testParseFullResponse() throws Exception {\n      IterableWithMarker<Alarm> metricAlarms =\n            factory.create(injector.getInstance(ListAlarmsResponseHandler.class))\n                   .parse(getClass().getResourceAsStream(\"/DescribeAlarmsResponse.xml\"));\n\n      assertEquals(metricAlarms.toString(), expected().toString());\n      assertFalse(metricAlarms.nextMarker().isPresent());\n   }\n\n   public IterableWithMarker<Alarm> expected() {\n      Set<Alarm> alarms = Sets.newLinkedHashSet();\n\n      for (int i = 1; i <= 2; i++) {\n         alarms.add(new Alarm(\n               i == 1,\n               ImmutableSet.of(\"TestAction1\", \"TestAction2\"),\n               \"TestAlarmARN\" + i,\n               dateService.iso8601SecondsDateParse(\"2013-01-0\" + i + \"T00:00:00Z\"),\n               \"This is test alarm \" + i + \".\",\n               \"TestAlarmName\" + i,\n               i == 1 ?\n                     ComparisonOperator.GREATER_THAN_THRESHOLD :\n                     ComparisonOperator.LESS_THAN_THRESHOLD,\n               ImmutableSet.of(\n                     new Dimension(\"TestDimensionName1\", \"TestDimensionValue1\"),\n                     new Dimension(\"TestDimensionName2\", \"TestDimensionValue2\")\n               ),\n               60 * i,\n               ImmutableSet.of(\"TestAction1\", \"TestAction2\"),\n               \"TestMetricName\" + i,\n               i == 1 ?\n                     Namespaces.EC2 :\n                     Namespaces.EBS,\n               ImmutableSet.of(\"TestAction1\", \"TestAction2\"),\n               60 * i,\n               \"This is state reason \" + i + \".\",\n               Optional.of(\"{\\\"reason\\\": \\\"\" + i + \"\\\"}\"),\n               dateService.iso8601SecondsDateParse(\"2013-01-0\" + i + \"T00:00:00Z\"),\n               i == 1 ?\n                     Alarm.State.OK :\n                     Alarm.State.ALARM,\n               i == 1 ?\n                     Statistics.SAMPLE_COUNT :\n                     Statistics.AVERAGE,\n               Double.valueOf(Integer.toString(i)),\n               i == 1 ?\n                     Optional.of(Unit.SECONDS) :\n                     Optional.of(Unit.COUNT_PER_SECOND)\n         ));\n      }\n\n      return IterableWithMarkers.from(alarms);\n   }\n\n}\n"
  },
  {
    "path": "apis/cloudwatch/src/test/resources/DescribeAlarmHistoryResponse.xml",
    "content": "<DescribeAlarmHistoryResponse xmlns=\"http://monitoring.amazonaws.com/doc/2010-08-01/\">\n  <DescribeAlarmHistoryResult>\n    <AlarmHistoryItems>\n      <member>\n        <AlarmName>TestAlarmName1</AlarmName>\n        <HistoryData>{&quot;reason&quot;: &quot;1&quot;}</HistoryData>\n        <HistoryItemType>Action</HistoryItemType>\n        <HistorySummary>This is test 1.</HistorySummary>\n        <Timestamp>2013-01-01T00:00:00.000+0000</Timestamp>\n      </member>\n      <member>\n        <AlarmName>TestAlarmName2</AlarmName>\n        <HistoryData>{&quot;reason&quot;: &quot;2&quot;}</HistoryData>\n        <HistoryItemType>ConfigurationUpdate</HistoryItemType>\n        <HistorySummary>This is test 2.</HistorySummary>\n        <Timestamp>2013-01-02T00:00:00.000+0000</Timestamp>\n      </member>\n    </AlarmHistoryItems>\n  </DescribeAlarmHistoryResult>\n</DescribeAlarmHistoryResponse>"
  },
  {
    "path": "apis/cloudwatch/src/test/resources/DescribeAlarmsForMetricResponse.xml",
    "content": "<DescribeAlarmsForMetricResponse xmlns=\"http://monitoring.amazonaws.com/doc/2010-08-01/\">\n  <DescribeAlarmsForMetricResult>\n    <MetricAlarms>\n      <member>\n        <ActionsEnabled>true</ActionsEnabled>\n        <AlarmActions>\n          <member>TestAction1</member>\n          <member>TestAction2</member>\n        </AlarmActions>\n        <AlarmArn>TestAlarmARN1</AlarmArn>\n        <AlarmConfigurationUpdatedTimestamp>2013-01-01T00:00:00.000+0000</AlarmConfigurationUpdatedTimestamp>\n        <AlarmDescription>This is test alarm 1.</AlarmDescription>\n        <AlarmName>TestAlarmName1</AlarmName>\n        <ComparisonOperator>GreaterThanThreshold</ComparisonOperator>\n        <Dimensions>\n          <member>\n            <Name>TestDimensionName1</Name>\n            <Value>TestDimensionValue1</Value>\n          </member>\n          <member>\n            <Name>TestDimensionName2</Name>\n            <Value>TestDimensionValue2</Value>\n          </member>\n        </Dimensions>\n        <EvaluationPeriods>60</EvaluationPeriods>\n        <UnknownActions>\n          <member>TestAction1</member>\n          <member>TestAction2</member>\n        </UnknownActions>\n        <MetricName>TestMetricName1</MetricName>\n        <Namespace>AWS/EC2</Namespace>\n        <OKActions>\n          <member>TestAction1</member>\n          <member>TestAction2</member>\n        </OKActions>\n        <Period>60</Period>\n        <StateReason>This is state reason 1.</StateReason>\n        <StateReasonData>{&quot;reason&quot;: &quot;1&quot;}</StateReasonData>\n        <StateUpdatedTimestamp>2013-01-01T00:00:00.000+0000</StateUpdatedTimestamp>\n        <StateValue>INSUFFICIENT_DATA</StateValue>\n        <Statistic>SampleCount</Statistic>\n        <Threshold>1.0</Threshold>\n        <Unit>Seconds</Unit>\n      </member>\n      <member>\n        <ActionsEnabled>false</ActionsEnabled>\n        <AlarmActions>\n          <member>TestAction1</member>\n          <member>TestAction2</member>\n        </AlarmActions>\n        <AlarmArn>TestAlarmARN2</AlarmArn>\n        <AlarmConfigurationUpdatedTimestamp>2013-01-02T00:00:00.000+0000</AlarmConfigurationUpdatedTimestamp>\n        <AlarmDescription>This is test alarm 2.</AlarmDescription>\n        <AlarmName>TestAlarmName2</AlarmName>\n        <ComparisonOperator>LessThanThreshold</ComparisonOperator>\n        <Dimensions>\n          <member>\n            <Name>TestDimensionName1</Name>\n            <Value>TestDimensionValue1</Value>\n          </member>\n          <member>\n            <Name>TestDimensionName2</Name>\n            <Value>TestDimensionValue2</Value>\n          </member>\n        </Dimensions>\n        <EvaluationPeriods>120</EvaluationPeriods>\n        <UnknownActions>\n          <member>TestAction1</member>\n          <member>TestAction2</member>\n        </UnknownActions>\n        <MetricName>TestMetricName2</MetricName>\n        <Namespace>AWS/EC2</Namespace>\n        <OKActions>\n          <member>TestAction1</member>\n          <member>TestAction2</member>\n        </OKActions>\n        <Period>120</Period>\n        <StateReason>This is state reason 2.</StateReason>\n        <StateReasonData>{&quot;reason&quot;: &quot;2&quot;}</StateReasonData>\n        <StateUpdatedTimestamp>2013-01-02T00:00:00.000+0000</StateUpdatedTimestamp>\n        <StateValue>OK</StateValue>\n        <Statistic>Average</Statistic>\n        <Threshold>2.0</Threshold>\n        <Unit>Count/Second</Unit>\n      </member>\n    </MetricAlarms>\n  </DescribeAlarmsForMetricResult>\n</DescribeAlarmsForMetricResponse>"
  },
  {
    "path": "apis/cloudwatch/src/test/resources/DescribeAlarmsResponse.xml",
    "content": "<DescribeAlarmsResponse xmlns=\"http://monitoring.amazonaws.com/doc/2010-08-01/\">\n  <DescribeAlarmsResult>\n    <MetricAlarms>\n      <member>\n          <ActionsEnabled>true</ActionsEnabled>\n          <AlarmActions>\n            <member>TestAction1</member>\n            <member>TestAction2</member>\n          </AlarmActions>\n          <AlarmArn>TestAlarmARN1</AlarmArn>\n          <AlarmConfigurationUpdatedTimestamp>2013-01-01T00:00:00.000+0000</AlarmConfigurationUpdatedTimestamp>\n          <AlarmDescription>This is test alarm 1.</AlarmDescription>\n          <AlarmName>TestAlarmName1</AlarmName>\n          <ComparisonOperator>GreaterThanThreshold</ComparisonOperator>\n          <Dimensions>\n            <member>\n              <Name>TestDimensionName1</Name>\n              <Value>TestDimensionValue1</Value>\n            </member>\n            <member>\n              <Name>TestDimensionName2</Name>\n              <Value>TestDimensionValue2</Value>\n            </member>\n          </Dimensions>\n          <EvaluationPeriods>60</EvaluationPeriods>\n          <UnknownActions>\n            <member>TestAction1</member>\n            <member>TestAction2</member>\n          </UnknownActions>\n          <MetricName>TestMetricName1</MetricName>\n          <Namespace>AWS/EC2</Namespace>\n          <OKActions>\n            <member>TestAction1</member>\n            <member>TestAction2</member>\n          </OKActions>\n          <Period>60</Period>\n          <StateReason>This is state reason 1.</StateReason>\n          <StateReasonData>{&quot;reason&quot;: &quot;1&quot;}</StateReasonData>\n          <StateUpdatedTimestamp>2013-01-01T00:00:00.000+0000</StateUpdatedTimestamp>\n          <StateValue>OK</StateValue>\n          <Statistic>SampleCount</Statistic>\n          <Threshold>1.0</Threshold>\n        <Unit>Seconds</Unit>\n      </member>\n      <member>\n        <ActionsEnabled>false</ActionsEnabled>\n        <AlarmActions>\n          <member>TestAction1</member>\n          <member>TestAction2</member>\n        </AlarmActions>\n        <AlarmArn>TestAlarmARN2</AlarmArn>\n        <AlarmConfigurationUpdatedTimestamp>2013-01-02T00:00:00.000+0000</AlarmConfigurationUpdatedTimestamp>\n        <AlarmDescription>This is test alarm 2.</AlarmDescription>\n        <AlarmName>TestAlarmName2</AlarmName>\n        <ComparisonOperator>LessThanThreshold</ComparisonOperator>\n        <Dimensions>\n          <member>\n            <Name>TestDimensionName1</Name>\n            <Value>TestDimensionValue1</Value>\n          </member>\n          <member>\n            <Name>TestDimensionName2</Name>\n            <Value>TestDimensionValue2</Value>\n          </member>\n        </Dimensions>\n        <EvaluationPeriods>120</EvaluationPeriods>\n        <UnknownActions>\n          <member>TestAction1</member>\n          <member>TestAction2</member>\n        </UnknownActions>\n        <MetricName>TestMetricName2</MetricName>\n        <Namespace>AWS/EBS</Namespace>\n        <OKActions>\n          <member>TestAction1</member>\n          <member>TestAction2</member>\n        </OKActions>\n        <Period>120</Period>\n        <StateReason>This is state reason 2.</StateReason>\n        <StateReasonData>{&quot;reason&quot;: &quot;2&quot;}</StateReasonData>\n        <StateUpdatedTimestamp>2013-01-02T00:00:00.000+0000</StateUpdatedTimestamp>\n        <StateValue>ALARM</StateValue>\n        <Statistic>Average</Statistic>\n        <Threshold>2.0</Threshold>\n        <Unit>Count/Second</Unit>\n      </member>\n    </MetricAlarms>\n  </DescribeAlarmsResult>\n</DescribeAlarmsResponse>"
  },
  {
    "path": "apis/cloudwatch/src/test/resources/InvalidFormatResponse.xml",
    "content": "<ErrorResponse>\n  <Errors>\n    <Error>\n      <Code>InvalidFormat</Code>\n      <Message>Data was not syntactically valid JSON.</Message>\n    </Error>\n  </Errors>\n  <RequestID>a9f8f3a3-e40f-11dd-af0f-cf11f65ec49d</RequestID>\n</ErrorResponse>"
  },
  {
    "path": "apis/cloudwatch/src/test/resources/LimitExceededResponse.xml",
    "content": "<ErrorResponse>\n  <Errors>\n    <Error>\n      <Code>LimitExceeded</Code>\n      <Message>The quota for alarms for this customer has already been reached.</Message>\n    </Error>\n  </Errors>\n  <RequestID>a9f8f3a3-e40f-11dd-af0f-cf11f65ec49d</RequestID>\n</ErrorResponse>"
  },
  {
    "path": "apis/cloudwatch/src/test/resources/VoidResponse.xml",
    "content": "<VoidResponse xmlns=\"http://monitoring.amazonaws.com/doc/2010-08-01/\">\n  <ResponseMetadata>\n    <RequestId>a9f8f3a3-e40f-11dd-af0f-cf11f65ec49d</RequestId>\n  </ResponseMetadata>\n</VoidResponse>"
  },
  {
    "path": "apis/cloudwatch/src/test/resources/get_metric_statistics.xml",
    "content": "<GetMetricStatisticsResponse>\n  <GetMetricStatisticsResult>\n    <Datapoints>\n      <member>\n        <Timestamp>2009-01-16T00:00:00Z</Timestamp>\n        <Unit>Percent</Unit>\n        <SampleCount>9.0</SampleCount>\n        <Average>0.17777777777777778</Average>\n      </member>\n      <member>\n        <Timestamp>2009-01-16T00:01:00Z</Timestamp>\n        <Unit>Percent</Unit>\n        <SampleCount>8.0</SampleCount>\n        <Average>0.1</Average>\n      </member>\n    </Datapoints>\n    <Label>CPUUtilization</Label>\n  </GetMetricStatisticsResult>\n  <ResponseMetadata>\n    <RequestId>a9f8f3a3-e40f-11dd-af0f-cf11f65ec49d</RequestId>\n  </ResponseMetadata>\n</GetMetricStatisticsResponse>"
  },
  {
    "path": "apis/cloudwatch/src/test/resources/list_metrics.xml",
    "content": "<ListMetricsResponse xmlns=\"http://monitoring.amazonaws.com/doc/2010-08-01/\">\n  <ListMetricsResult>\n    <Metrics>\n      <member>\n        <Dimensions>\n          <member>\n            <Name>InstanceId</Name>\n            <Value>i-689fcf0f</Value>\n          </member>\n        </Dimensions>\n        <MetricName>CPUUtilization</MetricName>\n        <Namespace>AWS/EC2</Namespace>\n      </member>\n    </Metrics>\n  </ListMetricsResult>\n</ListMetricsResponse>"
  },
  {
    "path": "apis/cloudwatch/src/test/resources/list_metrics_marker.xml",
    "content": "<ListMetricsResponse xmlns=\"http://monitoring.amazonaws.com/doc/2010-08-01/\">\n  <ListMetricsResult>\n    <Metrics>\n      <member>\n        <Dimensions>\n          <member>\n            <Name>InstanceId</Name>\n            <Value>i-689fcf0f</Value>\n          </member>\n        </Dimensions>\n        <MetricName>CPUUtilization</MetricName>\n        <Namespace>AWS/EC2</Namespace>\n      </member>\n    </Metrics>\n    <NextToken>MARKER</NextToken>\n  </ListMetricsResult>\n</ListMetricsResponse>"
  },
  {
    "path": "apis/cloudwatch/src/test/resources/log4j.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE log4j:configuration SYSTEM \"log4j.dtd\">\n\n    <!--\n        For more configuration infromation and examples see the Apache\n        Log4j website: http://logging.apache.org/log4j/\n    -->\n<log4j:configuration xmlns:log4j=\"http://jakarta.apache.org/log4j/\"\n    debug=\"false\">\n\n    <!-- A time/date based rolling appender -->\n    <appender name=\"WIREFILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds-wire.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n\n    <!-- A time/date based rolling appender -->\n    <appender name=\"FILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n\n    <!-- A time/date based rolling appender -->\n    <appender name=\"COMPUTEFILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds-compute.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n\n    <!-- A time/date based rolling appender -->\n    <appender name=\"SSHFILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds-ssh.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n\n    <appender name=\"ASYNCCOMPUTE\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"COMPUTEFILE\" />\n    </appender>\n\n    <appender name=\"ASYNCSSH\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"SSHFILE\" />\n    </appender>\n\n    <appender name=\"ASYNC\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"FILE\" />\n    </appender>\n\n    <appender name=\"ASYNCWIRE\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"WIREFILE\" />\n    </appender>\n\n    <!-- ================ -->\n    <!-- Limit categories -->\n    <!-- ================ -->\n\n    <category name=\"org.jclouds\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNC\" />\n    </category>\n\n    <category name=\"jclouds.headers\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNCWIRE\" />\n    </category>\n\n    <category name=\"jclouds.ssh\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNCSSH\" />\n    </category>\n    <category name=\"jclouds.wire\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNCWIRE\" />\n    </category>\n    <category name=\"jclouds.compute\">\n        <priority value=\"TRACE\" />\n        <appender-ref ref=\"ASYNCCOMPUTE\" />\n    </category>\n    <!-- ======================= -->\n    <!-- Setup the Root category -->\n    <!-- ======================= -->\n\n    <root>\n        <priority value=\"WARN\" />\n    </root>\n\n</log4j:configuration>\n"
  },
  {
    "path": "apis/docker/README.md",
    "content": "# Docker as a local cloud provider\n\njclouds-docker is a local cloud provider modelled on [docker](http://www.docker.io). Similar to other jclouds supported\nproviders, it supports the same portable abstractions offered by jclouds.\n\n## Setup\n\nPlease follow these steps to configure your workstation for jclouds-docker:\n\n- install the latest Docker release (please visit https://docs.docker.com/installation/)\n- [enable remote access](https://docs.docker.com/engine/quickstart/#bind-docker-to-another-host-port-or-a-unix-socket) to Docker\n\n### Sample configuration for Linux systems using systemd\n\nRun following commands on a machine where is the Docker Engine installed.\nIt enables remote access (plain TCP - only for loopback address 127.0.0.1)\non standard port `2375`.\n\n```bash\n# switch to root account\nsudo su -\n\n# create override for docker start-script\nmkdir /etc/systemd/system/docker.service.d\ncat << EOT > /etc/systemd/system/docker.service.d/allow-tcp.conf\n[Service]\nExecStart=\nExecStart=/usr/bin/docker daemon -H fd:// -H tcp://\nEOT\n\n# reload configuration and restart docker daemon\nsystemctl daemon-reload\nsystemctl restart docker\n\n# close the 'root' session\nexit\n```\n\nIf the `-H fd://` Docker daemon parameter doesn't work on your Linux (e.g. Fedora),\nthen replace it by `-H unix:///var/run/docker.sock`\n\nFind more details in [Control and configure Docker with systemd](https://docs.docker.com/engine/admin/systemd/) guide.\n\n### Running live tests\n\nThe `DOCKER_HOST` environment variable has to be configured as it's used as a value for `test.docker.endpoint` system property.\n\n```\nexport DOCKER_HOST=\"http://localhost:2375/\"\nmvn -Plive integration-test\n```\n\nNotice, if you are using [Docker for Mac](https://docs.docker.com/engine/installation/mac/), Docker Remote API may not be available over HTTP. \nIn the [Known issue]{https://docs.docker.com/docker-for-mac/troubleshoot/#known-issues) Docker team recommend to use [socat](http://www.dest-unreach.org/socat/)\nto expose `docker.sock` over tcp. You may find useful the following simple commands:\n\n```\ndocker run -d -v /var/run/docker.sock:/var/run/docker.sock -p 127.0.0.1:1234:1234 bobrik/socat TCP-LISTEN:1234,fork UNIX-CONNECT:/var/run/docker.sock\n```\n\nand then \n\n```\nexport DOCKER_HOST=http://localhost:1234\nmvn -Plive integration-test\n```\n\n# How it works\n\n\n                                               ---------------   -------------\n                                              |   Image(s)    | |   Node(s)   |\n                                              ---------------   -------------\n     ---------    docker remote api           ----------------------------------------\n    | jclouds | ---------------------------> |              DOCKER_HOST              |\n     ---------                               ----------------------------------------\n\n## Components\n\n- jclouds \\- acts as a java client to access to docker features\n- DOCKER_HOST \\- hosts Docker API, NB: jclouds-docker assumes that the latest Docker is installed\n- Image \\- it is a docker image that can be started.\n- Node \\- is a docker container\n\n## Assumptions\n\n- jclouds-docker assumes that the images specified using the template are ssh'able.\n\n--------------\n\n# Notes:\n- report any issues you find at [jclouds issues](https://issues.apache.org/jira/browse/JCLOUDS)\n- jclouds-docker has been tested on Mac OSX and Linux. However, it has never been tried on Windows.\n\n--------------\n\n# Troubleshooting\n\nAs jclouds docker support is quite new, issues may occasionally arise. \nYou can try to remove all containers to get things going again:\n\n```bash\ndocker rm -f `docker ps -aq`\n```\n"
  },
  {
    "path": "apis/docker/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.docker.*;version=\"${project.version}\";-noimport:=true"
  },
  {
    "path": "apis/docker/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n         xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n\n  <groupId>org.apache.jclouds.api</groupId>\n  <artifactId>docker</artifactId>\n  <name>jclouds docker API</name>\n  <description>ComputeService binding to the Docker API</description>\n\n  <properties>\n    <test.docker.api-version>1.21</test.docker.api-version>\n    <test.docker.identity>${env.DOCKER_CERT_PATH}/cert.pem</test.docker.identity>\n    <test.docker.credential>${env.DOCKER_CERT_PATH}/key.pem</test.docker.credential>\n    <test.docker.cacert.path>${env.DOCKER_CERT_PATH}/ca.pem</test.docker.cacert.path>\n    <test.docker.endpoint>${env.DOCKER_HOST}</test.docker.endpoint>\n    <test.jclouds.trust-all-certs>false</test.jclouds.trust-all-certs>\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <scope>provided</scope>\n      <optional>true</optional>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.value</groupId>\n      <artifactId>auto-value</artifactId>\n      <scope>provided</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-sshj</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-bouncycastle</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-okhttp</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-slf4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>ch.qos.logback</groupId>\n      <artifactId>logback-classic</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.squareup.okhttp3</groupId>\n      <artifactId>mockwebserver</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.squareup.okhttp3</groupId>\n      <artifactId>okhttp-tls</artifactId>\n      <scope>test</scope>\n      <exclusions>\n        <exclusion>\n          <groupId>org.bouncycastle</groupId>\n          <artifactId>bcprov-jdk15on</artifactId>\n        </exclusion>\n      </exclusions>\n    </dependency>\n    <dependency>\n      <groupId>org.jboss.shrinkwrap</groupId>\n      <artifactId>shrinkwrap-depchain</artifactId>\n      <version>1.2.2</version>\n      <type>pom</type>\n      <scope>test</scope>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.codehaus.mojo</groupId>\n            <artifactId>build-helper-maven-plugin</artifactId>\n            <version>1.9.1</version>\n            <executions>\n              <execution>\n                <id>regex-property</id>\n                <goals>\n                  <goal>regex-property</goal>\n                </goals>\n                <configuration>\n                  <name>test.docker.endpoint</name>\n                  <value>${test.docker.endpoint}</value>\n                  <regex>tcp</regex>\n                  <replacement>https</replacement>\n                  <failIfNoMatch>false</failIfNoMatch>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <threadCount>1</threadCount>\n                  <systemPropertyVariables>\n                    <test.docker.endpoint>${test.docker.endpoint}</test.docker.endpoint>\n                    <test.docker.api-version>${test.docker.api-version}</test.docker.api-version>\n                    <test.docker.identity>${test.docker.identity}</test.docker.identity>\n                    <test.docker.credential>${test.docker.credential}</test.docker.credential>\n                    <test.docker.cacert.path>${test.docker.cacert.path}</test.docker.cacert.path>\n                    <test.jclouds.trust-all-certs>${test.jclouds.trust-all-certs}</test.jclouds.trust-all-certs>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/DockerApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker;\n\nimport java.io.Closeable;\n\nimport org.jclouds.docker.features.ContainerApi;\nimport org.jclouds.docker.features.ImageApi;\nimport org.jclouds.docker.features.MiscApi;\nimport org.jclouds.docker.features.NetworkApi;\nimport org.jclouds.rest.annotations.Delegate;\n\npublic interface DockerApi extends Closeable {\n\n   @Delegate\n   MiscApi getMiscApi();\n\n   @Delegate\n   ContainerApi getContainerApi();\n\n   @Delegate\n   ImageApi getImageApi();\n\n   @Delegate\n   NetworkApi getNetworkApi();\n\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/DockerApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker;\n\nimport static org.jclouds.compute.config.ComputeServiceProperties.TEMPLATE;\nimport static org.jclouds.reflect.Reflection2.typeToken;\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.Constants;\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.compute.config.ComputeServiceProperties;\nimport org.jclouds.docker.compute.config.DockerComputeServiceContextModule;\nimport org.jclouds.docker.config.DockerHttpApiModule;\nimport org.jclouds.docker.config.DockerParserModule;\nimport org.jclouds.rest.internal.BaseHttpApiMetadata;\n\nimport com.google.auto.service.AutoService;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n@AutoService(ApiMetadata.class)\npublic class DockerApiMetadata extends BaseHttpApiMetadata<DockerApi> {\n\n    public static final String DOCKER_CA_CERT_PATH = \"docker.cacert.path\";\n    public static final String DOCKER_CA_CERT_DATA = \"docker.cacert.data\";\n\n   @Override\n   public Builder toBuilder() {\n      return new Builder().fromApiMetadata(this);\n   }\n\n   public DockerApiMetadata() {\n      this(new Builder());\n   }\n\n   protected DockerApiMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = BaseHttpApiMetadata.defaultProperties();\n      properties.setProperty(Constants.PROPERTY_CONNECTION_TIMEOUT, \"1200000\"); // 15 minutes\n      properties.setProperty(ComputeServiceProperties.IMAGE_LOGIN_USER, \"root:password\");\n      properties.setProperty(TEMPLATE, \"osFamily=UBUNTU,os64Bit=true\");\n      properties.setProperty(DOCKER_CA_CERT_PATH, \"\");\n      properties.setProperty(DOCKER_CA_CERT_DATA, \"\");\n      return properties;\n   }\n\n   public static class Builder extends BaseHttpApiMetadata.Builder<DockerApi, Builder> {\n\n      protected Builder() {\n         super(DockerApi.class);\n         id(\"docker\")\n                 .name(\"Docker API\")\n                 .identityName(\"Path or data for certificate .pem file\")\n                 .credentialName(\"Path or data for key .pem file\")\n                 .documentation(URI.create(\"https://docs.docker.com/reference/api/docker_remote_api/\"))\n                 .version(\"1.21\")\n                 .defaultEndpoint(\"https://127.0.0.1:2376\")\n                 .defaultProperties(DockerApiMetadata.defaultProperties())\n                 .view(typeToken(ComputeServiceContext.class))\n                 .defaultModules(ImmutableSet.<Class<? extends Module>>of(\n                         DockerParserModule.class,\n                         DockerHttpApiModule.class,\n                         DockerComputeServiceContextModule.class));\n      }\n\n      @Override\n      public DockerApiMetadata build() {\n         return new DockerApiMetadata(this);\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n\n      @Override\n      public Builder fromApiMetadata(ApiMetadata in) {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/compute/config/DockerComputeServiceContextModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.compute.config;\n\nimport org.jclouds.compute.ComputeServiceAdapter;\nimport org.jclouds.compute.config.ComputeServiceAdapterContextModule;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.docker.compute.functions.ContainerToNodeMetadata;\nimport org.jclouds.docker.compute.functions.ImageToImage;\nimport org.jclouds.docker.compute.functions.StateToStatus;\nimport org.jclouds.docker.compute.options.DockerTemplateOptions;\nimport org.jclouds.docker.compute.strategy.DockerComputeServiceAdapter;\nimport org.jclouds.docker.domain.Container;\nimport org.jclouds.docker.domain.Image;\nimport org.jclouds.docker.domain.State;\nimport org.jclouds.domain.Location;\nimport org.jclouds.functions.IdentityFunction;\n\nimport com.google.common.base.Function;\nimport com.google.inject.TypeLiteral;\n\npublic class DockerComputeServiceContextModule extends\n      ComputeServiceAdapterContextModule<Container, Hardware, Image, Location> {\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   protected void configure() {\n      super.configure();\n      bind(new TypeLiteral<ComputeServiceAdapter<Container, Hardware, Image, Location>>() {\n      }).to(DockerComputeServiceAdapter.class);\n      bind(new TypeLiteral<Function<Container, NodeMetadata>>() {\n      }).to(ContainerToNodeMetadata.class);\n      bind(new TypeLiteral<Function<Image, org.jclouds.compute.domain.Image>>() {\n      }).to(ImageToImage.class);\n      bind(new TypeLiteral<Function<Hardware, Hardware>>() {\n      }).to(Class.class.cast(IdentityFunction.class));\n      bind(new TypeLiteral<Function<Location, Location>>() {\n      }).to(Class.class.cast(IdentityFunction.class));\n      bind(new TypeLiteral<Function<State, NodeMetadata.Status>>() {\n      }).to(StateToStatus.class);\n      bind(TemplateOptions.class).to(DockerTemplateOptions.class);\n\n      install(new LoginPortLookupModule());\n   }\n\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/compute/config/LoginPortLookupModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.compute.config;\n\nimport org.jclouds.docker.compute.functions.LoginPortForContainer;\n\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Binder;\nimport com.google.inject.multibindings.MapBinder;\n\npublic class LoginPortLookupModule extends AbstractModule {\n\n   @Override\n   protected void configure() {\n      // Declare it to initialize the binder allowing duplicates. Users may\n      // provide different functions for the same image in different modules, or\n      // we could provide predefined functions for known images. This allows\n      // users to set their own ones too.\n      loginPortLookupBinder(binder());\n   }\n\n   public static MapBinder<String, LoginPortForContainer> loginPortLookupBinder(Binder binder) {\n      return MapBinder.newMapBinder(binder, String.class, LoginPortForContainer.class).permitDuplicates();\n   }\n\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/compute/functions/ContainerToNodeMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.compute.functions;\n\nimport java.net.URI;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.domain.HardwareBuilder;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadataBuilder;\nimport org.jclouds.compute.domain.Processor;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.docker.domain.Container;\nimport org.jclouds.docker.domain.NetworkSettings;\nimport org.jclouds.docker.domain.State;\nimport org.jclouds.domain.Location;\nimport org.jclouds.providers.ProviderMetadata;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.inject.Singleton;\n\n@Singleton\npublic class ContainerToNodeMetadata implements Function<Container, NodeMetadata> {\n\n   /**\n    * This value is used when a container does not have an accessible\n    * login port (i.e. the SSH daemon is not running) due to being\n    * started outside jclouds. Client code should check for this value\n    * when accessing NodeMetadata from Docker.\n    */\n   private static final Integer NO_LOGIN_PORT = Integer.valueOf(-1);\n\n   private final ProviderMetadata providerMetadata;\n   private final Function<State, NodeMetadata.Status> toPortableStatus;\n   private final GroupNamingConvention nodeNamingConvention;\n   private final Supplier<Map<String, ? extends Image>> images;\n   private final Supplier<Set<? extends Location>> locations;\n   private final LoginPortForContainer loginPortForContainer;\n\n   @Inject\n   ContainerToNodeMetadata(ProviderMetadata providerMetadata,\n                           Function<State, NodeMetadata.Status> toPortableStatus, GroupNamingConvention.Factory namingConvention,\n                           Supplier<Map<String, ? extends Image>> images, @Memoized Supplier<Set<? extends Location>> locations,\n                           LoginPortForContainer loginPortForContainer) {\n      this.providerMetadata = providerMetadata;\n      this.toPortableStatus = toPortableStatus;\n      this.nodeNamingConvention = namingConvention.createWithoutPrefix();\n      this.images = images;\n      this.locations = locations;\n      this.loginPortForContainer = loginPortForContainer;\n   }\n\n   @Override\n   public NodeMetadata apply(Container container) {\n      String name = cleanUpName(container.name());\n      String group = nodeNamingConvention.extractGroup(name);\n      NodeMetadataBuilder builder = new NodeMetadataBuilder();\n      builder.ids(container.id())\n              .name(name)\n              .group(group)\n              .hostname(container.config().hostname())\n              // TODO Set up hardware\n              .hardware(new HardwareBuilder()\n                      .id(\"\")\n                      .ram(container.config().memory())\n                      .processor(new Processor(container.config().cpuShares(), container.config().cpuShares()))\n                      .build());\n      builder.status(toPortableStatus.apply(container.state()));\n      builder.loginPort(loginPortForContainer.apply(container).or(NO_LOGIN_PORT));\n      builder.publicAddresses(getPublicIpAddresses(container));\n      builder.privateAddresses(getPrivateIpAddresses(container));\n      builder.location(Iterables.getOnlyElement(locations.get()));\n      String imageId = container.image();\n      builder.imageId(imageId);\n      if (images.get().containsKey(imageId)) {\n         Image image = images.get().get(imageId);\n         builder.operatingSystem(image.getOperatingSystem());\n      }\n      return builder.build();\n   }\n\n   private String cleanUpName(String name) {\n      return name.startsWith(\"/\") ? name.substring(1) : name;\n   }\n\n   private Iterable<String> getPrivateIpAddresses(Container container) {\n      // A container can be attached to multiple networks. It can therefore have multiple private\n      // IPs. The NetworkSettings.ipAddress might in fact be blank, with the only IP being on\n      // network objects.\n      if (container.networkSettings() == null) return ImmutableList.of();\n      ImmutableSet.Builder<String> builder = ImmutableSet.<String>builder();\n      NetworkSettings settings = container.networkSettings();\n      if (settings.ipAddress() != null && settings.ipAddress().length() > 0) {\n         builder.add(settings.ipAddress());\n      }\n      if (settings.networks() != null) {\n         for (Map.Entry<String, NetworkSettings.Details> entry : settings.networks().entrySet()) {\n            String ipAddress = entry.getValue().ipAddress();\n            if (ipAddress != null && ipAddress.length() > 0) {\n               builder.add(ipAddress);\n            }\n         }\n      }\n      return builder.build();\n   }\n\n   private List<String> getPublicIpAddresses(Container container) {\n      String dockerIpAddress;\n      if (container.node().isPresent()) {\n         dockerIpAddress = container.node().get().ip();\n      } else {\n         dockerIpAddress = URI.create(providerMetadata.getEndpoint()).getHost();\n      }\n      return ImmutableList.of(dockerIpAddress);\n   }\n\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/compute/functions/CustomLoginPortFromImage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.compute.functions;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.docker.domain.Container;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Maps;\n\n@Beta\npublic class CustomLoginPortFromImage implements LoginPortForContainer {\n\n   private final Map<String, Set<LoginPortForContainer>> imageToPortLookup;\n\n   @Inject\n   CustomLoginPortFromImage(Map<String, Set<LoginPortForContainer>> imageToPortLookup) {\n      this.imageToPortLookup = imageToPortLookup;\n   }\n\n   @Override\n   public Optional<Integer> apply(final Container container) {\n      Map<String, Set<LoginPortForContainer>> matchingFunctions = Maps.filterKeys(imageToPortLookup,\n            new Predicate<String>() {\n               @Override\n               public boolean apply(String input) {\n                  return container.config().image().matches(input);\n               }\n            });\n\n      // We allow to provide several forms in the image-to-function map:\n      // - redis\n      // - redis:12\n      // - owner/redis:12\n      // - registry:5000/owner/redis:12\n      // We consider the longest match first, as it is the more accurate one\n      List<String> sortedImages = new ArrayList<String>(matchingFunctions.keySet());\n      Collections.sort(sortedImages, LongestStringFirst);\n\n      for (String currentImage : sortedImages) {\n         Set<LoginPortForContainer> functions = matchingFunctions.get(currentImage);\n         for (LoginPortForContainer function : functions) {\n            Optional<Integer> port = function.apply(container);\n            if (port.isPresent()) {\n               return port;\n            }\n         }\n      }\n\n      return Optional.absent();\n   }\n\n   private static final Comparator<String> LongestStringFirst = new Comparator<String>() {\n      @Override\n      public int compare(String s1, String s2) {\n         return s2.length() - s1.length();\n      }\n   };\n\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/compute/functions/ImageToImage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.compute.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\n\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.ImageBuilder;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.Iterables;\n\npublic class ImageToImage implements Function<org.jclouds.docker.domain.Image, org.jclouds.compute.domain.Image> {\n\n   private static final String CENTOS = \"centos\";\n   private static final String UBUNTU = \"ubuntu\";\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   @Override\n   public Image apply(org.jclouds.docker.domain.Image from) {\n      checkNotNull(from, \"image\");\n\n      String firstRepoTag = Iterables.getFirst(from.repoTags(), \"<none>\");\n      final int versionSeparatorPos = firstRepoTag.lastIndexOf(':');\n\n      final String name;\n      final String osVersion;\n      if (versionSeparatorPos > -1) {\n         name = firstRepoTag.substring(0, versionSeparatorPos);\n         osVersion = firstRepoTag.substring(versionSeparatorPos + 1);\n      } else {\n         name = firstRepoTag;\n         osVersion = firstRepoTag;\n      }\n      logger.debug(\"os version for item: %s is %s\", firstRepoTag, osVersion);\n\n      OsFamily osFamily = osFamily().apply(firstRepoTag);\n\n      OperatingSystem os = OperatingSystem.builder()\n              .description(firstRepoTag)\n              .family(osFamily)\n              .version(osVersion)\n              .is64Bit(is64bit(from))\n              .build();\n\n      return new ImageBuilder()\n              .ids(from.id())\n              .name(name)\n              .description(firstRepoTag)\n              .operatingSystem(os)\n              .status(Image.Status.AVAILABLE)\n              .build();\n   }\n\n   private boolean is64bit(org.jclouds.docker.domain.Image inspectedImage) {\n      if (inspectedImage.architecture() == null) return true;\n      return inspectedImage.architecture().matches(\"x86_64|amd64\");\n   }\n\n   /**\n    * Parses the item description to determine the OSFamily\n    *\n    * @return the @see OsFamily or OsFamily.UNRECOGNIZED\n    */\n   private Function<String, OsFamily> osFamily() {\n      return new Function<String, OsFamily>() {\n\n         @Override\n         public OsFamily apply(final String description) {\n            if (description != null) {\n               if (description.contains(CENTOS)) return OsFamily.CENTOS;\n               else if (description.contains(UBUNTU)) return OsFamily.UBUNTU;\n            }\n            return OsFamily.UNRECOGNIZED;\n         }\n      };\n   }\n\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/compute/functions/LoginPortForContainer.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.compute.functions;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.docker.compute.functions.LoginPortForContainer.LoginPortLookupChain;\nimport org.jclouds.docker.domain.Container;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.inject.ImplementedBy;\n\n@Beta\n@ImplementedBy(LoginPortLookupChain.class)\npublic interface LoginPortForContainer extends Function<Container, Optional<Integer>> {\n\n   @Beta\n   static final class LoginPortLookupChain implements LoginPortForContainer {\n      private final PublicPortForContainerPort publicPortForContainerPort;\n      private final CustomLoginPortFromImage customLoginPortFromImage;\n\n      @Inject\n      LoginPortLookupChain(CustomLoginPortFromImage customLoginPortFromImage) {\n         this.publicPortForContainerPort = new PublicPortForContainerPort(22);\n         this.customLoginPortFromImage = customLoginPortFromImage;\n      }\n\n      @Override\n      public Optional<Integer> apply(Container input) {\n         Optional<Integer> loginPort = publicPortForContainerPort.apply(input);\n         return loginPort.isPresent() ? loginPort : customLoginPortFromImage.apply(input);\n      }\n\n   }\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/compute/functions/PublicPortForContainerPort.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.compute.functions;\n\nimport static com.google.common.collect.Iterables.getOnlyElement;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.docker.domain.Container;\nimport org.jclouds.docker.domain.Port;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Optional;\n\n@Beta\npublic class PublicPortForContainerPort implements LoginPortForContainer {\n\n   private final int containerPort;\n\n   public PublicPortForContainerPort(int containerPort) {\n      this.containerPort = containerPort;\n   }\n\n   @Override\n   public Optional<Integer> apply(Container container) {\n      if (container.networkSettings() != null) {\n         Map<String, List<Map<String, String>>> ports = container.networkSettings().ports();\n         if (ports != null && ports.containsKey(containerPort + \"/tcp\")) {\n            return Optional.of(Integer.parseInt(getOnlyElement(ports.get(containerPort + \"/tcp\")).get(\"HostPort\")));\n         }\n         // this is needed in case the container list is coming from\n         // listContainers\n      } else if (container.ports() != null) {\n         for (Port port : container.ports()) {\n            if (port.privatePort() == containerPort) {\n               return Optional.of(port.publicPort());\n            }\n         }\n      }\n      return Optional.absent();\n   }\n\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/compute/functions/StateToStatus.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.compute.functions;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.domain.NodeMetadata.Status;\nimport org.jclouds.docker.domain.State;\n\nimport com.google.common.base.Function;\n\n/**\n * Transforms an {@link org.jclouds.docker.domain.Container} to the jclouds portable model.\n */\n@Singleton\npublic class StateToStatus implements Function<State, Status> {\n\n   @Override\n   public Status apply(final State state) {\n      if (state == null) return Status.UNRECOGNIZED;\n      return state.running() ? Status.RUNNING : Status.TERMINATED;\n   }\n\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/compute/options/DockerTemplateOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.compute.options;\n\nimport static com.google.common.base.Objects.equal;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\n\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.docker.domain.Config;\nimport org.jclouds.docker.internal.NullSafeCopies;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.scriptbuilder.domain.Statement;\n\n/**\n * Contains options supported by the\n * {@link org.jclouds.compute.ComputeService#createNodesInGroup(String, int, TemplateOptions)\n * createNodes} operation on the <em>docker</em> provider.\n *\n * <h2>Usage</h2>\n *\n * The recommended way to instantiate a DockerTemplateOptions object is to\n * statically import {@code DockerTemplateOptions.Builder.*} and invoke one of\n * the static creation methods, followed by an instance mutator if needed.\n *\n * <pre>\n * {@code import static org.jclouds.docker.compute.options.DockerTemplateOptions.Builder.*;\n *\n * ComputeService api = // get connection\n * templateBuilder.options(inboundPorts(22, 80, 8080, 443));\n * Set<? extends NodeMetadata> set = api.createNodesInGroup(tag, 2, templateBuilder.build());}\n * </pre>\n *\n * <h2>Advanced Usage</h2>\n * <p>\n * In addition to basic configuration through its methods, this class also\n * provides possibility to work directly with Docker API configuration object (\n * {@link Config.Builder}). When the\n * {@link #configBuilder(org.jclouds.docker.domain.Config.Builder)} is used to\n * configure not-<code>null</code> configBuilder, then this configuration object\n * takes precedence over the other configuration in this class (i.e. the other\n * config entries are not used)\n * </p>\n * <p>\n * Note: The {@code image} property in the provided {@link Config.Builder} is rewritten by a placeholder value.\n * The real value is configured by ComputeServiceAdapter.\n * </p>\n *\n * <pre>\n * {@code import static org.jclouds.docker.compute.options.DockerTemplateOptions.Builder.*;\n *\n * ComputeService api = // get connection\n * DockerTemplateOptions options = DockerTemplateOptions.Builder\n *       .configBuilder(\n *                Config.builder().env(ImmutableList.<String> of(\"SSH_PORT=8822\"))\n *                      .hostConfig(HostConfig.builder().networkMode(\"host\").build()));\n * templateBuilder.options(options);\n * Set<? extends NodeMetadata> set = api.createNodesInGroup(\"sample-group\", 1, templateBuilder.build());}\n * </pre>\n */\npublic class DockerTemplateOptions extends TemplateOptions implements Cloneable {\n\n   private static final String NO_IMAGE = \"jclouds-placeholder-for-image\";\n\n   protected List<String> dns = ImmutableList.of();\n   @Nullable protected String hostname;\n   @Nullable protected Integer memory;\n   @Nullable protected Integer cpuShares;\n   @Nullable List<String> entrypoint;\n   @Nullable List<String> commands;\n   protected Map<String, String> volumes = ImmutableMap.of();\n   @Nullable protected List<String> env;\n   protected Map<Integer, Integer> portBindings = ImmutableMap.of();\n   @Nullable protected String networkMode;\n   protected Map<String, String> extraHosts = ImmutableMap.of();\n   protected List<String> volumesFrom = ImmutableList.of();\n   protected boolean privileged;\n   protected boolean openStdin;\n   protected Config.Builder configBuilder;\n\n   @Override\n   public DockerTemplateOptions clone() {\n      DockerTemplateOptions options = new DockerTemplateOptions();\n      copyTo(options);\n      return options;\n   }\n\n   @Override\n   public void copyTo(TemplateOptions to) {\n      super.copyTo(to);\n      if (to instanceof DockerTemplateOptions) {\n         DockerTemplateOptions eTo = DockerTemplateOptions.class.cast(to);\n         eTo.volumes(volumes);\n         eTo.hostname(hostname);\n         eTo.dns(dns);\n         eTo.memory(memory);\n         eTo.cpuShares(cpuShares);\n         eTo.entrypoint(entrypoint);\n         eTo.commands(commands);\n         eTo.env(env);\n         eTo.portBindings(portBindings);\n         eTo.networkMode(networkMode);\n         eTo.extraHosts(extraHosts);\n         eTo.volumesFrom(volumesFrom);\n         eTo.privileged(privileged);\n         eTo.openStdin(openStdin);\n         eTo.configBuilder(configBuilder);\n      }\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o)\n         return true;\n      if (o == null || getClass() != o.getClass())\n         return false;\n      DockerTemplateOptions that = DockerTemplateOptions.class.cast(o);\n      return super.equals(that) &&\n              equal(this.volumes, that.volumes) &&\n              equal(this.hostname, that.hostname) &&\n              equal(this.dns, that.dns) &&\n              equal(this.memory, that.memory) &&\n              equal(this.cpuShares, that.cpuShares) &&\n              equal(this.entrypoint, that.entrypoint) &&\n              equal(this.commands, that.commands) &&\n              equal(this.env, that.env) &&\n              equal(this.portBindings, that.portBindings) &&\n              equal(this.networkMode, that.networkMode) &&\n              equal(this.extraHosts, that.extraHosts) &&\n              equal(this.volumesFrom, that.volumesFrom) &&\n              equal(this.privileged, that.privileged) &&\n              equal(this.openStdin, that.openStdin) &&\n              buildersEqual(this.configBuilder, that.configBuilder);\n   }\n\n\n   /**\n    * Compares two Config.Builder instances.\n    */\n   private boolean buildersEqual(Config.Builder b1, Config.Builder b2) {\n      return b1 == b2 || (b1 != null && b2 != null && b1.build().equals(b2.build()));\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(super.hashCode(), volumes, hostname, dns, memory, entrypoint, commands, cpuShares, env,\n            portBindings, networkMode, extraHosts, volumesFrom, privileged, openStdin, configBuilder);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this)\n              .add(\"volumes\", volumes)\n              .add(\"hostname\", hostname)\n              .add(\"dns\", dns)\n              .add(\"memory\", memory)\n              .add(\"cpuShares\", cpuShares)\n              .add(\"entrypoint\", entrypoint)\n              .add(\"commands\", commands)\n              .add(\"env\", env)\n              .add(\"portBindings\", portBindings)\n              .add(\"networkMode\", networkMode)\n              .add(\"extraHosts\", extraHosts)\n              .add(\"volumesFrom\", volumesFrom)\n              .add(\"privileged\", privileged)\n              .add(\"openStdin\", openStdin)\n              .add(\"configBuilder\", configBuilder)\n              .toString();\n   }\n\n   public DockerTemplateOptions volumes(Map<String, String> volumes) {\n      this.volumes = NullSafeCopies.copyOf(volumes);\n      return this;\n   }\n\n   public DockerTemplateOptions dns(Iterable<String> dns) {\n      this.dns = NullSafeCopies.copyOf(dns);\n      return this;\n   }\n\n   public DockerTemplateOptions dns(String...dns) {\n      this.dns = NullSafeCopies.copyOf(dns);\n      return this;\n   }\n\n   public DockerTemplateOptions hostname(@Nullable String hostname) {\n      this.hostname = hostname;\n      return this;\n   }\n\n   public DockerTemplateOptions memory(@Nullable Integer memory) {\n      this.memory = memory;\n      return this;\n   }\n\n   public DockerTemplateOptions entrypoint(Iterable<String> entrypoint) {\n      this.entrypoint = NullSafeCopies.copyWithNullOf(entrypoint);\n      return this;\n   }\n\n   public DockerTemplateOptions entrypoint(String... entrypoint) {\n      this.entrypoint = NullSafeCopies.copyWithNullOf(entrypoint);\n      return this;\n   }\n\n   public DockerTemplateOptions commands(Iterable<String> commands) {\n      this.commands = NullSafeCopies.copyWithNullOf(commands);\n      return this;\n   }\n\n   public DockerTemplateOptions commands(String...commands) {\n      this.commands = NullSafeCopies.copyWithNullOf(commands);\n      return this;\n   }\n\n   public DockerTemplateOptions cpuShares(@Nullable Integer cpuShares) {\n      this.cpuShares = cpuShares;\n      return this;\n   }\n\n   public DockerTemplateOptions env(Iterable<String> env) {\n      this.env = NullSafeCopies.copyWithNullOf(env);\n      return this;\n   }\n\n   public DockerTemplateOptions env(String...env) {\n      this.env = NullSafeCopies.copyWithNullOf(env);\n      return this;\n   }\n\n   /**\n    * Set port bindings between the Docker host and a container.\n    * <p>\n    * The {@link Map} keys are host ports number, and the value for an entry is the\n    * container port number. This is the same order as the arguments for the\n    * {@code --publish} command-line option to {@code docker run} which is\n    * {@code hostPort:containerPort}.\n    *\n    * @param portBindings the map of host to container port bindings\n    */\n   public DockerTemplateOptions portBindings(Map<Integer, Integer> portBindings) {\n      this.portBindings = NullSafeCopies.copyOf(portBindings);\n      return this;\n   }\n\n   /**\n    * Sets the networking mode for the container.\n    * <p>\n    * Supported values are: {@code bridge}, {@code none}, {@code host},\n    * {@code networkname}, {@code networkid} or {@code container:[name|id]}\n    *\n    * @param networkMode\n    * @return this instance\n    */\n   public DockerTemplateOptions networkMode(@Nullable String networkMode) {\n      this.networkMode = networkMode;\n      return this;\n   }\n\n   /**\n    * Set extra hosts file entries for a container.\n    * <p>\n    * The {@link Map} keys are host names, and the value is an IP address that\n    * can be accessed by the container. This is the same order as the arguments for the\n    * {@code --add-host} command-line option to {@code docker run}.\n    *\n    * @param extraHosts the map of host names to IP addresses\n    */\n   public DockerTemplateOptions extraHosts(Map<String, String> extraHosts) {\n      this.extraHosts = NullSafeCopies.copyOf(extraHosts);\n      return this;\n   }\n\n   /**\n    * Set list of containers to mount volumes from onto this container.\n    *\n    * @param volumesFrom the list of container names\n    */\n   public DockerTemplateOptions volumesFrom(Iterable<String> volumesFrom) {\n      this.volumesFrom = NullSafeCopies.copyOf(volumesFrom);\n      return this;\n   }\n\n   /**\n    * By default, Docker containers are unprivileged and cannot execute privileged operations or access certain\n    * host devices.\n    *\n    * @param privileged Whether the container should run in privileged mode or not\n    * @return this instance\n    */\n   public DockerTemplateOptions privileged(boolean privileged) {\n      this.privileged = privileged;\n      return this;\n   }\n\n   /**\n    * Keep {@code STDIN} open when running interactive workloads in the container.\n    *\n    * @param openStdin Whether the container should keep STDIN open\n    * @return this instance\n    */\n   public DockerTemplateOptions openStdin(boolean openStdin) {\n      this.openStdin = openStdin;\n      return this;\n   }\n\n   /**\n    * This method sets Config.Builder configuration object, which can be used as\n    * a replacement for all the other settings from this class. Some values in\n    * the provided Config.Builder instance (the image name for instance) can be\n    * ignored or their value can be changed.\n    *\n    * @param configBuilder\n    *           Config.Builder instance. This instance can be changed in this\n    *           method!\n    */\n   public DockerTemplateOptions configBuilder(Config.Builder configBuilder) {\n      this.configBuilder = configBuilder != null\n            ? Config.builder().fromConfig(configBuilder.image(NO_IMAGE).build())\n            : null;\n      return this;\n   }\n\n   public Map<String, String> getVolumes() { return volumes; }\n\n   public List<String> getDns() { return dns; }\n\n   public List<String> getVolumesFrom() { return volumesFrom; }\n\n   public String getHostname() { return hostname; }\n\n   public Integer getMemory() { return memory; }\n\n   public List<String> getEntrypoint() { return entrypoint; }\n\n   public List<String> getCommands() { return commands; }\n\n   public Integer getCpuShares() { return cpuShares; }\n\n   public List<String> getEnv() { return env; }\n\n   public Map<Integer, Integer> getPortBindings() { return portBindings; }\n\n   public String getNetworkMode() { return networkMode; }\n\n   public Map<String, String> getExtraHosts() { return extraHosts; }\n\n   public boolean getPrivileged() { return privileged; }\n\n   public boolean getOpenStdin() { return openStdin; }\n\n   public Config.Builder getConfigBuilder() { return configBuilder; }\n\n   public static class Builder {\n\n      /**\n       * @see DockerTemplateOptions#volumes(Map)\n       */\n      public static DockerTemplateOptions volumes(Map<String, String> volumes) {\n         DockerTemplateOptions options = new DockerTemplateOptions();\n         return options.volumes(volumes);\n      }\n\n      /**\n       * @see DockerTemplateOptions#dns(String...)\n       */\n      public static DockerTemplateOptions dns(String...dns) {\n         DockerTemplateOptions options = new DockerTemplateOptions();\n         return options.dns(dns);\n      }\n\n      /**\n       * @see DockerTemplateOptions#dns(List)\n       */\n      public static DockerTemplateOptions dns(Iterable<String> dns) {\n         DockerTemplateOptions options = new DockerTemplateOptions();\n         return options.dns(dns);\n      }\n\n      /**\n       * @see DockerTemplateOptions#hostname(String)\n       */\n      public static DockerTemplateOptions hostname(@Nullable String hostname) {\n         DockerTemplateOptions options = new DockerTemplateOptions();\n         return options.hostname(hostname);\n      }\n\n      /**\n       * @see DockerTemplateOptions#memory(Integer)\n       */\n      public static DockerTemplateOptions memory(@Nullable Integer memory) {\n         DockerTemplateOptions options = new DockerTemplateOptions();\n         return options.memory(memory);\n      }\n\n      /**\n       * @see DockerTemplateOptions#entrypoint(String...)\n       */\n      public static DockerTemplateOptions entrypoint(String...entrypoint) {\n         DockerTemplateOptions options = new DockerTemplateOptions();\n         return options.entrypoint(entrypoint);\n      }\n\n      /**\n       * @see DockerTemplateOptions#entrypoint(Iterable)\n       */\n      public static DockerTemplateOptions entrypoint(Iterable<String> entrypoint) {\n         DockerTemplateOptions options = new DockerTemplateOptions();\n         return options.entrypoint(entrypoint);\n      }\n\n      /**\n       * @see DockerTemplateOptions#commands(String...)\n       */\n      public static DockerTemplateOptions commands(String...commands) {\n         DockerTemplateOptions options = new DockerTemplateOptions();\n         return options.commands(commands);\n      }\n\n      /**\n       * @see DockerTemplateOptions#commands(Iterable)\n       */\n      public static DockerTemplateOptions commands(Iterable<String> commands) {\n         DockerTemplateOptions options = new DockerTemplateOptions();\n         return options.commands(commands);\n      }\n\n      /**\n       * @see DockerTemplateOptions#cpuShares(Integer)\n       */\n      public static DockerTemplateOptions cpuShares(@Nullable Integer cpuShares) {\n         DockerTemplateOptions options = new DockerTemplateOptions();\n         return options.cpuShares(cpuShares);\n      }\n\n      /**\n       * @see DockerTemplateOptions#env(String...)\n       */\n      public static DockerTemplateOptions env(String...env) {\n         DockerTemplateOptions options = new DockerTemplateOptions();\n         return options.env(env);\n      }\n\n      /**\n       * @see DockerTemplateOptions#env(Iterable)\n       */\n      public static DockerTemplateOptions env(Iterable<String> env) {\n         DockerTemplateOptions options = new DockerTemplateOptions();\n         return options.env(env);\n      }\n\n      /**\n       * @see DockerTemplateOptions#portBindings(Map)\n       */\n      public static DockerTemplateOptions portBindings(Map<Integer, Integer> portBindings) {\n         DockerTemplateOptions options = new DockerTemplateOptions();\n         return options.portBindings(portBindings);\n      }\n\n      /**\n       * @see DockerTemplateOptions#networkMode(String)\n       */\n      public static DockerTemplateOptions networkMode(@Nullable String networkMode) {\n         DockerTemplateOptions options = new DockerTemplateOptions();\n         return options.networkMode(networkMode);\n      }\n\n      /**\n       * @see DockerTemplateOptions#extraHosts(Map)\n       */\n      public static DockerTemplateOptions extraHosts(Map<String, String> extraHosts) {\n         DockerTemplateOptions options = new DockerTemplateOptions();\n         return options.extraHosts(extraHosts);\n      }\n\n      /**\n       * @see DockerTemplateOptions#privileged(boolean)\n       */\n      public static DockerTemplateOptions privileged(boolean privileged) {\n         DockerTemplateOptions options = new DockerTemplateOptions();\n         return options.privileged(privileged);\n      }\n\n      /**\n       * @see DockerTemplateOptions#openStdin(boolean)\n       */\n      public static DockerTemplateOptions openStdin(boolean openStdin) {\n         DockerTemplateOptions options = new DockerTemplateOptions();\n         return options.openStdin(openStdin);\n      }\n\n      /**\n       * @see DockerTemplateOptions#configBuilder(Config.Builder)\n       */\n      public static DockerTemplateOptions configBuilder(Config.Builder configBuilder) {\n         DockerTemplateOptions options = new DockerTemplateOptions();\n         return options.configBuilder(configBuilder);\n      }\n\n      /**\n       * @see DockerTemplateOptions#volumesFrom(Iterable)\n       */\n      public static DockerTemplateOptions volumesFrom(Iterable<String> volumesFrom) {\n         DockerTemplateOptions options = new DockerTemplateOptions();\n         return options.volumesFrom(volumesFrom);\n      }\n\n      /**\n       * @see TemplateOptions#inboundPorts(int...)\n       */\n      public static DockerTemplateOptions inboundPorts(int... ports) {\n         DockerTemplateOptions options = new DockerTemplateOptions();\n         return options.inboundPorts(ports);\n      }\n\n      /**\n       * @see TemplateOptions#blockOnPort(int, int)\n       */\n      public static DockerTemplateOptions blockOnPort(int port, int seconds) {\n         DockerTemplateOptions options = new DockerTemplateOptions();\n         return options.blockOnPort(port, seconds);\n      }\n\n      /**\n       * @see TemplateOptions#installPrivateKey(String)\n       */\n      public static DockerTemplateOptions installPrivateKey(String rsaKey) {\n         DockerTemplateOptions options = new DockerTemplateOptions();\n         return options.installPrivateKey(rsaKey);\n      }\n\n      /**\n       * @see TemplateOptions#authorizePublicKey(String)\n       */\n      public static DockerTemplateOptions authorizePublicKey(String rsaKey) {\n         DockerTemplateOptions options = new DockerTemplateOptions();\n         return options.authorizePublicKey(rsaKey);\n      }\n\n      /**\n       * @see TemplateOptions#userMetadata(Map)\n       */\n      public static DockerTemplateOptions userMetadata(Map<String, String> userMetadata) {\n         DockerTemplateOptions options = new DockerTemplateOptions();\n         return options.userMetadata(userMetadata);\n      }\n\n      /**\n       * @see TemplateOptions#nodeNames(Iterable)\n       */\n      public static DockerTemplateOptions nodeNames(Iterable<String> nodeNames) {\n         DockerTemplateOptions options = new DockerTemplateOptions();\n         return options.nodeNames(nodeNames);\n      }\n\n      /**\n       * @see TemplateOptions#networks(Iterable)\n       */\n      public static DockerTemplateOptions networks(Iterable<String> networks) {\n         DockerTemplateOptions options = new DockerTemplateOptions();\n         return options.networks(networks);\n      }\n\n      /**\n       * @see TemplateOptions#overrideLoginUser(String)\n       */\n      public static DockerTemplateOptions overrideLoginUser(String user) {\n         DockerTemplateOptions options = new DockerTemplateOptions();\n         return options.overrideLoginUser(user);\n      }\n\n      /**\n       * @see TemplateOptions#overrideLoginPassword(String)\n       */\n      public static DockerTemplateOptions overrideLoginPassword(String password) {\n         DockerTemplateOptions options = new DockerTemplateOptions();\n         return options.overrideLoginPassword(password);\n      }\n\n      /**\n       * @see TemplateOptions#overrideLoginPrivateKey(String)\n       */\n      public static DockerTemplateOptions overrideLoginPrivateKey(String privateKey) {\n         DockerTemplateOptions options = new DockerTemplateOptions();\n         return options.overrideLoginPrivateKey(privateKey);\n      }\n\n      /**\n       * @see TemplateOptions#overrideAuthenticateSudo(boolean)\n       */\n      public static DockerTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo) {\n         DockerTemplateOptions options = new DockerTemplateOptions();\n         return options.overrideAuthenticateSudo(authenticateSudo);\n      }\n\n      /**\n       * @see TemplateOptions#overrideLoginCredentials(LoginCredentials)\n       */\n      public static DockerTemplateOptions overrideLoginCredentials(LoginCredentials credentials) {\n         DockerTemplateOptions options = new DockerTemplateOptions();\n         return options.overrideLoginCredentials(credentials);\n      }\n\n      /**\n       * @see TemplateOptions#blockUntilRunning(boolean)\n       */\n      public static DockerTemplateOptions blockUntilRunning(boolean blockUntilRunning) {\n         DockerTemplateOptions options = new DockerTemplateOptions();\n         return options.blockUntilRunning(blockUntilRunning);\n      }\n\n   }\n\n   // methods that only facilitate returning the correct object type\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public DockerTemplateOptions blockOnPort(int port, int seconds) {\n      return DockerTemplateOptions.class.cast(super.blockOnPort(port, seconds));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public DockerTemplateOptions inboundPorts(int... ports) {\n      return DockerTemplateOptions.class.cast(super.inboundPorts(ports));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public DockerTemplateOptions authorizePublicKey(String publicKey) {\n      return DockerTemplateOptions.class.cast(super.authorizePublicKey(publicKey));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public DockerTemplateOptions installPrivateKey(String privateKey) {\n      return DockerTemplateOptions.class.cast(super.installPrivateKey(privateKey));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public DockerTemplateOptions blockUntilRunning(boolean blockUntilRunning) {\n      return DockerTemplateOptions.class.cast(super.blockUntilRunning(blockUntilRunning));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public DockerTemplateOptions dontAuthorizePublicKey() {\n      return DockerTemplateOptions.class.cast(super.dontAuthorizePublicKey());\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public DockerTemplateOptions nameTask(String name) {\n      return DockerTemplateOptions.class.cast(super.nameTask(name));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public DockerTemplateOptions runAsRoot(boolean runAsRoot) {\n      return DockerTemplateOptions.class.cast(super.runAsRoot(runAsRoot));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public DockerTemplateOptions runScript(Statement script) {\n      return DockerTemplateOptions.class.cast(super.runScript(script));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public DockerTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials) {\n      return DockerTemplateOptions.class.cast(super.overrideLoginCredentials(overridingCredentials));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public DockerTemplateOptions overrideLoginPassword(String password) {\n      return DockerTemplateOptions.class.cast(super.overrideLoginPassword(password));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public DockerTemplateOptions overrideLoginPrivateKey(String privateKey) {\n      return DockerTemplateOptions.class.cast(super.overrideLoginPrivateKey(privateKey));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public DockerTemplateOptions overrideLoginUser(String loginUser) {\n      return DockerTemplateOptions.class.cast(super.overrideLoginUser(loginUser));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public DockerTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo) {\n      return DockerTemplateOptions.class.cast(super.overrideAuthenticateSudo(authenticateSudo));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public DockerTemplateOptions userMetadata(Map<String, String> userMetadata) {\n      return DockerTemplateOptions.class.cast(super.userMetadata(userMetadata));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public DockerTemplateOptions userMetadata(String key, String value) {\n      return DockerTemplateOptions.class.cast(super.userMetadata(key, value));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public DockerTemplateOptions nodeNames(Iterable<String> nodeNames) {\n      return DockerTemplateOptions.class.cast(super.nodeNames(nodeNames));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public DockerTemplateOptions networks(Iterable<String> networks) {\n      return DockerTemplateOptions.class.cast(super.networks(networks));\n   }\n\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/compute/strategy/DockerComputeServiceAdapter.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.compute.strategy;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.find;\n\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.regex.Pattern;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Lists;\nimport com.google.common.collect.Maps;\nimport com.google.common.collect.Sets;\n\nimport org.jclouds.compute.ComputeServiceAdapter;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.HardwareBuilder;\nimport org.jclouds.compute.domain.Processor;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.docker.DockerApi;\nimport org.jclouds.docker.compute.options.DockerTemplateOptions;\nimport org.jclouds.docker.domain.Config;\nimport org.jclouds.docker.domain.Container;\nimport org.jclouds.docker.domain.ContainerSummary;\nimport org.jclouds.docker.domain.HostConfig;\nimport org.jclouds.docker.domain.Image;\nimport org.jclouds.docker.domain.ImageSummary;\nimport org.jclouds.docker.options.AttachOptions;\nimport org.jclouds.docker.options.CreateImageOptions;\nimport org.jclouds.docker.options.ListContainerOptions;\nimport org.jclouds.docker.options.RemoveContainerOptions;\nimport org.jclouds.docker.util.DockerInputStream;\nimport org.jclouds.docker.util.StdStreamData;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.util.Closeables2;\n\n/**\n * defines the connection between the {@link org.jclouds.docker.DockerApi} implementation and\n * the jclouds {@link org.jclouds.compute.ComputeService}\n */\n@Singleton\npublic class DockerComputeServiceAdapter implements\n        ComputeServiceAdapter<Container, Hardware, Image, Location> {\n\n\n   /**\n    * Some Docker versions returns host prefix even for images from Docker hub in repoTags field. We use this constant\n    * to correctly identify requested image name.\n    */\n   public static final String PREFIX_DOCKER_HUB_HOST = \"docker.io/\";\n\n   /**\n    * (Optional) Suffix used, when image version is not used during searching images.\n    */\n   public static final String SUFFIX_LATEST_VERSION = \":latest\";\n\n   private static final String PATTERN_IMAGE_PREFIX = \"^(\" + Pattern.quote(PREFIX_DOCKER_HUB_HOST) + \")?\";\n   private static final String PATTERN_IMAGE_SUFFIX = \"(\" + Pattern.quote(SUFFIX_LATEST_VERSION) + \")?$\";\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   private final DockerApi api;\n\n   @Inject\n   public DockerComputeServiceAdapter(DockerApi api) {\n      this.api = checkNotNull(api, \"api\");\n   }\n\n   @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n   @Override\n   public NodeAndInitialCredentials<Container> createNodeWithGroupEncodedIntoName(String group, String name,\n                                                                                  Template template) {\n      checkNotNull(template, \"template was null\");\n      TemplateOptions options = template.getOptions();\n      checkNotNull(options, \"template options was null\");\n\n      String imageId = checkNotNull(template.getImage().getId(), \"template image id must not be null\");\n      String loginUser = template.getImage().getDefaultCredentials().getUser();\n      String loginUserPassword = template.getImage().getDefaultCredentials().getOptionalPassword().or(\"password\");\n\n      DockerTemplateOptions templateOptions = DockerTemplateOptions.class.cast(options);\n\n      Config containerConfig = null;\n      Config.Builder containerConfigBuilder = templateOptions.getConfigBuilder();\n      if (containerConfigBuilder == null) {\n         containerConfigBuilder = Config.builder().image(imageId);\n\n         containerConfigBuilder.entrypoint(templateOptions.getEntrypoint());\n         containerConfigBuilder.cmd(templateOptions.getCommands());\n         containerConfigBuilder.memory(templateOptions.getMemory());\n         containerConfigBuilder.hostname(templateOptions.getHostname());\n         containerConfigBuilder.cpuShares(templateOptions.getCpuShares());\n         containerConfigBuilder.openStdin(templateOptions.getOpenStdin());\n         containerConfigBuilder.env(templateOptions.getEnv());\n\n         if (!templateOptions.getVolumes().isEmpty()) {\n            Map<String, Object> volumes = Maps.newLinkedHashMap();\n            for (String containerDir : templateOptions.getVolumes().values()) {\n               volumes.put(containerDir, Maps.newHashMap());\n            }\n            containerConfigBuilder.volumes(volumes);\n         }\n\n         HostConfig.Builder hostConfigBuilder = HostConfig.builder()\n               .publishAllPorts(true)\n               .privileged(templateOptions.getPrivileged());\n\n         if (!templateOptions.getPortBindings().isEmpty()) {\n            Map<String, List<Map<String, String>>> portBindings = Maps.newHashMap();\n            for (Map.Entry<Integer, Integer> entry : templateOptions.getPortBindings().entrySet()) {\n               portBindings.put(entry.getValue() + \"/tcp\",\n                     Lists.<Map<String, String>>newArrayList(ImmutableMap.of(\"HostIp\", \"0.0.0.0\", \"HostPort\", Integer.toString(entry.getKey()))));\n            }\n            hostConfigBuilder.portBindings(portBindings);\n         }\n\n         if (!templateOptions.getDns().isEmpty()) {\n            hostConfigBuilder.dns(templateOptions.getDns());\n         }\n\n         if (!templateOptions.getExtraHosts().isEmpty()) {\n            List<String> extraHosts = Lists.newArrayList();\n            for (Map.Entry<String, String> entry : templateOptions.getExtraHosts().entrySet()) {\n               extraHosts.add(entry.getKey() + \":\" + entry.getValue());\n            }\n            hostConfigBuilder.extraHosts(extraHosts);\n         }\n\n         if (!templateOptions.getVolumes().isEmpty()) {\n            List<String> binds = Lists.newArrayList();\n            for (Map.Entry<String, String> entry : templateOptions.getVolumes().entrySet()) {\n               binds.add(entry.getKey() + \":\" + entry.getValue());\n            }\n            hostConfigBuilder.binds(ImmutableList.copyOf(binds));\n         }\n\n         if (!templateOptions.getVolumesFrom().isEmpty()) {\n            hostConfigBuilder.volumesFrom(templateOptions.getVolumesFrom());\n         }\n\n         hostConfigBuilder.networkMode(templateOptions.getNetworkMode());\n\n         containerConfigBuilder.hostConfig(hostConfigBuilder.build());\n\n         // add the inbound ports into exposed ports map\n         containerConfig = containerConfigBuilder.build();\n         Map<String, Object> exposedPorts = Maps.newHashMap();\n         if (containerConfig.exposedPorts() == null) {\n            exposedPorts.putAll(containerConfig.exposedPorts());\n         }\n         for (int inboundPort : templateOptions.getInboundPorts()) {\n            String portKey = inboundPort + \"/tcp\";\n            if (!exposedPorts.containsKey(portKey)) {\n               exposedPorts.put(portKey, Maps.newHashMap());\n            }\n         }\n         containerConfigBuilder.exposedPorts(exposedPorts);\n\n         // build once more after setting inboundPorts\n         containerConfig = containerConfigBuilder.build();\n\n         // finally update port bindings\n         Map<String, List<Map<String, String>>> portBindings = Maps.newHashMap();\n         Map<String, List<Map<String, String>>> existingBindings = containerConfig.hostConfig().portBindings();\n         if (existingBindings != null) {\n            portBindings.putAll(existingBindings);\n         }\n         for (String exposedPort : containerConfig.exposedPorts().keySet()) {\n            if (!portBindings.containsKey(exposedPort)) {\n               portBindings.put(exposedPort, Lists.<Map<String, String>>newArrayList(ImmutableMap.of(\"HostIp\", \"0.0.0.0\")));\n            }\n         }\n         hostConfigBuilder = HostConfig.builder().fromHostConfig(containerConfig.hostConfig());\n         hostConfigBuilder.portBindings(portBindings);\n         containerConfigBuilder.hostConfig(hostConfigBuilder.build());\n      } else {\n         containerConfigBuilder.image(imageId);\n      }\n\n      containerConfig = containerConfigBuilder.build();\n\n      logger.debug(\">> creating new container with containerConfig(%s)\", containerConfig);\n      Container container = api.getContainerApi().createContainer(name, containerConfig);\n      logger.trace(\"<< container(%s)\", container.id());\n\n      if (templateOptions.getNetworks() != null) {\n          logger.debug(\">> connecting container(%s) to networks(%s)\", container.id(), Iterables.toString(templateOptions.getNetworks()));\n          for (String networkIdOrName : templateOptions.getNetworks()) {\n              api.getNetworkApi().connectContainerToNetwork(networkIdOrName, container.id());\n          }\n          logger.trace(\"<< connected(%s)\", container.id());\n      }\n\n      HostConfig hostConfig = containerConfig.hostConfig();\n\n      logger.debug(\">> starting container(%s) with hostConfig(%s)\", container.id(), hostConfig);\n      api.getContainerApi().startContainer(container.id(), hostConfig);\n      logger.trace(\"<< started(%s)\", container.id());\n\n      container = api.getContainerApi().inspectContainer(container.id());\n      return new NodeAndInitialCredentials(container, container.id(),\n              LoginCredentials.builder().user(loginUser).password(loginUserPassword).build());\n   }\n\n   @Override\n   public Iterable<Hardware> listHardwareProfiles() {\n      Set<Hardware> hardware = Sets.newLinkedHashSet();\n      // todo they are only placeholders at the moment\n      hardware.add(new HardwareBuilder().ids(\"micro\").hypervisor(\"lxc\").name(\"micro\").processor(new Processor(1, 1)).ram(512).build());\n      hardware.add(new HardwareBuilder().ids(\"small\").hypervisor(\"lxc\").name(\"small\").processor(new Processor(1, 1)).ram(1024).build());\n      hardware.add(new HardwareBuilder().ids(\"medium\").hypervisor(\"lxc\").name(\"medium\").processor(new Processor(2, 1)).ram(2048).build());\n      hardware.add(new HardwareBuilder().ids(\"large\").hypervisor(\"lxc\").name(\"large\").processor(new Processor(2, 1)).ram(3072).build());\n      return hardware;\n   }\n\n   /**\n    * Method based on {@link org.jclouds.docker.features.ImageApi#listImages()}. It retrieves additional\n    * information by inspecting each image.\n    *\n    * @see org.jclouds.compute.ComputeServiceAdapter#listImages()\n    */\n   @Override\n   public Set<Image> listImages() {\n      Set<Image> images = Sets.newHashSet();\n      for (ImageSummary imageSummary : api.getImageApi().listImages()) {\n         // less efficient than just listImages but returns richer json that needs repoTags coming from listImages\n         Image inspected = api.getImageApi().inspectImage(imageSummary.id());\n         inspected = Image.create(inspected.id(), inspected.author(), inspected.comment(), inspected.config(),\n                    inspected.containerConfig(), inspected.parent(), inspected.created(), inspected.container(),\n                 inspected.dockerVersion(), inspected.architecture(), inspected.os(), inspected.size(),\n                    inspected.virtualSize(), imageSummary.repoTags());\n         images.add(inspected);\n      }\n      return images;\n   }\n\n   @Override\n   public Image getImage(final String imageIdOrName) {\n      checkNotNull(imageIdOrName);\n      if (imageIdOrName.startsWith(\"sha256\")) {\n         // less efficient than just inspectImage but listImages return repoTags\n         return find(listImages(), new Predicate<Image>() {\n            @Override\n            public boolean apply(Image input) {\n               // Only attempt match on id as we should try to pull again anyway if using name\n               return input.id().equals(imageIdOrName);\n            }\n         }, null);\n      }\n\n      // Image is not cached or getting image by name so try to pull it\n      api.getImageApi().createImage(CreateImageOptions.Builder.fromImage(imageIdOrName));\n\n      // as above this ensure repotags are returned\n      return find(listImages(), createPredicateMatchingRepoTags(imageIdOrName), null);\n   }\n\n   @Override\n   public Iterable<Container> listNodes() {\n      Set<Container> containers = Sets.newHashSet();\n      for (ContainerSummary containerSummary : api.getContainerApi().listContainers(ListContainerOptions.Builder.all(true))) {\n         // less efficient than just listNodes but returns richer json\n         containers.add(api.getContainerApi().inspectContainer(containerSummary.id()));\n      }\n      return containers;\n   }\n\n   @Override\n   public Iterable<Container> listNodesByIds(final Iterable<String> ids) {\n      Set<Container> containers = Sets.newHashSet();\n      for (String id : ids) {\n         containers.add(api.getContainerApi().inspectContainer(id));\n      }\n      return containers;\n   }\n\n   @Override\n   public Iterable<Location> listLocations() {\n      return ImmutableSet.of();\n   }\n\n   @Override\n   public Container getNode(String id) {\n      return api.getContainerApi().inspectContainer(id);\n   }\n\n   @Override\n   public void destroyNode(String id) {\n      traceContainerLogs(id);\n      api.getContainerApi().removeContainer(id, RemoveContainerOptions.Builder.force(true));\n   }\n\n   @Override\n   public void rebootNode(String id) {\n      api.getContainerApi().stopContainer(id);\n      api.getContainerApi().startContainer(id);\n   }\n\n   @Override\n   public void resumeNode(String id) {\n      api.getContainerApi().unpause(id);\n   }\n\n   @Override\n   public void suspendNode(String id) {\n      api.getContainerApi().pause(id);\n   }\n\n   protected static Predicate<Image> createPredicateMatchingRepoTags(final String imageIdOrName) {\n      final Pattern imgPattern = Pattern\n            .compile(PATTERN_IMAGE_PREFIX + Pattern.quote(imageIdOrName) + PATTERN_IMAGE_SUFFIX);\n      return new Predicate<Image>() {\n         @Override\n         public boolean apply(Image input) {\n            for (String tag : input.repoTags()) {\n               if (imgPattern.matcher(tag).matches()) {\n                  return true;\n               }\n            }\n            return false;\n         }\n      };\n   }\n\n   /**\n    * If log level TRACE (or finer), then logs from the given container are\n    * written to JClouds log.\n    *\n    * @param containerId\n    *           Id of the container to retrieve logs for.\n    */\n   private void traceContainerLogs(final String containerId) {\n      if (logger.isTraceEnabled()) {\n         DockerInputStream dis = null;\n         try {\n            dis = new DockerInputStream(api.getContainerApi().attach(containerId,\n                  AttachOptions.Builder.logs(true).stderr(true).stdout(true)));\n            String idToLog = containerId;\n            if (idToLog.length() > 8) {\n               idToLog = idToLog.substring(0, 8);\n            }\n            StdStreamData data = null;\n            while (null != (data = dis.readStdStreamData())) {\n               final byte[] bytePayload = data.getPayload();\n               final String payload = bytePayload != null ? new String(bytePayload, Charsets.UTF_8) : \"\";\n               switch (data.getType()) {\n                  case OUT:\n                     logger.trace(\"Container [%s] StdOut: %s\", idToLog, payload);\n                     break;\n                  case ERR:\n                     logger.trace(\"Container [%s] StdErr: %s\", idToLog, payload);\n                     break;\n                  default:\n                     logger.trace(\"Container [%s] - Unexpected STD stream type: %s\", idToLog, data.getType());\n                     break;\n               }\n            }\n         } catch (Exception e) {\n            logger.trace(\"Retrieving container log failed\", e);\n         } finally {\n            Closeables2.closeQuietly(dis);\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/config/DockerHttpApiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.config;\n\nimport com.google.common.base.Supplier;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.name.Names;\nimport com.google.inject.util.Modules;\nimport org.jclouds.docker.DockerApi;\nimport org.jclouds.docker.handlers.DockerErrorHandler;\nimport org.jclouds.docker.suppliers.DockerUntrustedSSLContextSupplier;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.annotation.ClientError;\nimport org.jclouds.http.annotation.Redirection;\nimport org.jclouds.http.annotation.ServerError;\nimport org.jclouds.http.config.ConfiguresHttpCommandExecutorService;\nimport org.jclouds.http.okhttp.OkHttpClientSupplier;\nimport org.jclouds.http.okhttp.config.OkHttpCommandExecutorServiceModule;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.config.HttpApiModule;\n\nimport javax.net.ssl.SSLContext;\n\n/**\n * Configures the Docker connection.\n */\n@ConfiguresHttpApi\n@ConfiguresHttpCommandExecutorService\npublic class DockerHttpApiModule extends HttpApiModule<DockerApi> {\n\n   @Override\n   protected void bindErrorHandlers() {\n      bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(DockerErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(DockerErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(DockerErrorHandler.class);\n   }\n\n   /**\n    * This configures SSL certificate authentication when the Docker daemon is set to use an encrypted TCP socket\n    */\n   @Override\n   protected void configure() {\n      super.configure();\n      install(Modules.override(new OkHttpCommandExecutorServiceModule()).with(new AbstractModule() {\n         @Override\n         protected void configure() {\n            bind(new TypeLiteral<Supplier<SSLContext>>() {}).annotatedWith(Names.named(\"untrusted\")).to(DockerUntrustedSSLContextSupplier.class);\n         }\n      }));\n      bind(OkHttpClientSupplier.class).to(DockerOkHttpClientSupplier.class);\n\n   }\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/config/DockerOkHttpClientSupplier.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.config;\n\nimport java.io.File;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport okhttp3.ConnectionSpec;\nimport okhttp3.OkHttpClient;\nimport okhttp3.TlsVersion;\n\nimport org.jclouds.docker.suppliers.DockerSSLContextSupplier;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.okhttp.OkHttpClientSupplier;\nimport org.jclouds.location.Provider;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableList;\n\n\n@Singleton\npublic class DockerOkHttpClientSupplier implements OkHttpClientSupplier {\n\n    private final DockerSSLContextSupplier dockerSSLContextSupplier;\n    private final Supplier<Credentials> creds;\n\n    @Inject\n    DockerOkHttpClientSupplier(DockerSSLContextSupplier dockerSSLContextSupplier, @Provider Supplier<Credentials> creds) {\n        this.dockerSSLContextSupplier = dockerSSLContextSupplier;\n        this.creds = creds;\n    }\n\n    @Override\n    public OkHttpClient get() {\n        OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();\n        ConnectionSpec tlsSpec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)\n                .tlsVersions(TlsVersion.TLS_1_0, TlsVersion.TLS_1_1, TlsVersion.TLS_1_2)\n                .build();\n        ConnectionSpec cleartextSpec = new ConnectionSpec.Builder(ConnectionSpec.CLEARTEXT)\n                .build();\n        clientBuilder.connectionSpecs(ImmutableList.of(tlsSpec, cleartextSpec));\n        // check if identity and credential are files, to set up sslContext\n        if (new File(creds.get().identity).isFile() && new File(creds.get().credential).isFile()) {\n           clientBuilder.sslSocketFactory(dockerSSLContextSupplier.get().getSocketFactory());\n        }\n        return clientBuilder.build();\n    }\n\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/config/DockerParserModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.config;\n\nimport org.jclouds.json.config.GsonModule;\n\nimport com.google.inject.AbstractModule;\n\npublic class DockerParserModule extends AbstractModule {\n\n   @Override protected void configure() {\n      bind(GsonModule.DateAdapter.class).to(GsonModule.Iso8601DateAdapter.class);\n   }\n\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/domain/Config.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.docker.internal.NullSafeCopies.copyOf;\nimport static org.jclouds.docker.internal.NullSafeCopies.copyWithNullOf;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.Lists;\nimport com.google.common.collect.Maps;\n\n@AutoValue\npublic abstract class Config {\n   @Nullable public abstract String hostname();\n\n   @Nullable public abstract String domainname();\n\n   @Nullable public abstract String user();\n\n   public abstract int memory();\n\n   public abstract int memorySwap();\n\n   public abstract int cpuShares();\n\n   public abstract boolean attachStdin();\n\n   public abstract boolean attachStdout();\n\n   public abstract boolean attachStderr();\n\n   public abstract boolean tty();\n\n   public abstract boolean openStdin();\n\n   public abstract boolean stdinOnce();\n\n   @Nullable public abstract List<String> env();\n\n   @Nullable public abstract List<String> cmd();\n\n   @Nullable public abstract List<String> entrypoint();\n\n   public abstract String image();\n\n   @Nullable public abstract Map<String, ?> volumes();\n\n   @Nullable public abstract String workingDir();\n\n   public abstract boolean networkDisabled();\n\n   public abstract Map<String, ?> exposedPorts();\n\n   public abstract List<String> securityOpts();\n\n   @Nullable public abstract HostConfig hostConfig();\n\n   Config() {\n   }\n\n   @SerializedNames(\n         {\n                 \"Hostname\", \"Domainname\", \"User\", \"Memory\", \"MemorySwap\", \"CpuShares\", \"AttachStdin\", \"AttachStdout\",\n                 \"AttachStderr\", \"Tty\", \"OpenStdin\", \"StdinOnce\", \"Env\", \"Cmd\", \"Entrypoint\", \"Image\", \"Volumes\",\n                 \"WorkingDir\", \"NetworkDisabled\", \"ExposedPorts\", \"SecurityOpts\", \"HostConfig\"\n         })\n   public static Config create(String hostname, String domainname, String user, int memory, int memorySwap,\n         int cpuShares, boolean attachStdin, boolean attachStdout, boolean attachStderr, boolean tty,\n         boolean openStdin, boolean stdinOnce, List<String> env, List<String> cmd, List<String> entrypoint,\n         String image, Map<String, ?> volumes, String workingDir, boolean networkDisabled,\n         Map<String, ?> exposedPorts, List<String> securityOpts, HostConfig hostConfig) {\n      return new AutoValue_Config(hostname, domainname, user, memory, memorySwap, cpuShares, attachStdin,\n              attachStdout, attachStderr, tty, openStdin, stdinOnce, copyWithNullOf(env), copyWithNullOf(cmd),\n              copyWithNullOf(entrypoint), image, copyWithNullOf(volumes), workingDir, networkDisabled,\n              copyOf(exposedPorts), copyOf(securityOpts), hostConfig);\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().fromConfig(this);\n   }\n\n   public static final class Builder {\n      private String hostname;\n      private String domainname;\n      private String user;\n      private int memory;\n      private int memorySwap;\n      private int cpuShares;\n      private boolean attachStdin;\n      private boolean attachStdout;\n      private boolean attachStderr;\n      private boolean tty;\n      private boolean openStdin;\n      private boolean stdinOnce;\n      private List<String> env;\n      private List<String> cmd;\n      private List<String> entrypoint;\n      private String image;\n      private Map<String, ?> volumes;\n      private String workingDir;\n      private boolean networkDisabled;\n      private Map<String, ?> exposedPorts = Maps.newHashMap();\n      private List<String> securityOpts = Lists.newArrayList();\n      private HostConfig hostConfig;\n\n      public Builder hostname(String hostname) {\n         this.hostname = hostname;\n         return this;\n      }\n\n      public Builder domainname(String domainname) {\n         this.domainname = domainname;\n         return this;\n      }\n\n      public Builder user(String user) {\n         this.user = user;\n         return this;\n      }\n\n      public Builder memory(Integer memory) {\n         if (memory != null) {\n            this.memory = memory;\n         }\n         return this;\n      }\n\n      public Builder memorySwap(Integer memorySwap) {\n         if (memorySwap != null) {\n            this.memorySwap = memorySwap;\n         }\n         return this;\n      }\n\n      public Builder cpuShares(Integer cpuShares) {\n         if (cpuShares != null) {\n            this.cpuShares = cpuShares;\n         }\n         return this;\n      }\n\n      public Builder attachStdin(boolean attachStdin) {\n         this.attachStdin = attachStdin;\n         return this;\n      }\n\n      public Builder attachStdout(boolean attachStdout) {\n         this.attachStdout = attachStdout;\n         return this;\n      }\n\n      public Builder attachStderr(boolean attachStderr) {\n         this.attachStderr = attachStderr;\n         return this;\n      }\n\n      public Builder tty(boolean tty) {\n         this.tty = tty;\n         return this;\n      }\n\n      public Builder openStdin(boolean openStdin) {\n         this.openStdin = openStdin;\n         return this;\n      }\n\n      public Builder stdinOnce(boolean stdinOnce) {\n         this.stdinOnce = stdinOnce;\n         return this;\n      }\n\n      public Builder env(List<String> env) {\n         this.env = env;\n         return this;\n      }\n\n      public Builder cmd(List<String> cmd) {\n         this.cmd = cmd;\n         return this;\n      }\n\n      public Builder entrypoint(List<String> entrypoint) {\n         this.entrypoint = entrypoint;\n         return this;\n      }\n\n      public Builder image(String image) {\n         this.image = checkNotNull(image, \"image\");\n         return this;\n      }\n\n      public Builder volumes(Map<String, ?> volumes) {\n         this.volumes = volumes;\n         return this;\n      }\n\n      public Builder workingDir(String workingDir) {\n         this.workingDir = workingDir;\n         return this;\n      }\n\n      public Builder networkDisabled(boolean networkDisabled) {\n         this.networkDisabled = networkDisabled;\n         return this;\n      }\n\n      public Builder exposedPorts(Map<String, ?> exposedPorts) {\n         this.exposedPorts = exposedPorts;\n         return this;\n      }\n\n      public Builder securityOpts(List<String> securityOpts) {\n         this.securityOpts = securityOpts;\n         return this;\n      }\n\n      public Builder hostConfig(HostConfig hostConfig) {\n         this.hostConfig = hostConfig;\n         return this;\n      }\n\n      public Config build() {\n         return Config.create(hostname, domainname, user, memory, memorySwap, cpuShares, attachStdin, attachStdout,\n                 attachStderr, tty, openStdin, stdinOnce, env, cmd, entrypoint, image, volumes, workingDir,\n                 networkDisabled, exposedPorts, securityOpts, hostConfig);\n      }\n\n      public Builder fromConfig(Config in) {\n         return hostname(in.hostname()).domainname(in.domainname()).user(in.user()).memory(in.memory())\n                 .memorySwap(in.memorySwap()).cpuShares(in.cpuShares()).attachStdin(in.attachStdin())\n                 .attachStdout(in.attachStdout()).attachStderr(in.attachStderr()).tty(in.tty())\n                 .openStdin(in.openStdin()).stdinOnce(in.stdinOnce()).env(in.env()).cmd(in.cmd())\n                 .entrypoint(in.entrypoint()).image(in.image()).volumes(in.volumes()).workingDir(in.workingDir())\n                 .networkDisabled(in.networkDisabled()).exposedPorts(in.exposedPorts())\n                 .securityOpts(in.securityOpts()).hostConfig(in.hostConfig());\n      }\n\n   }\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/domain/Container.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.domain;\n\nimport static org.jclouds.docker.internal.NullSafeCopies.copyOf;\n\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\n\n@AutoValue\npublic abstract class Container {\n   public abstract String id();\n\n   @Nullable public abstract Date created();\n\n   @Nullable public abstract String path();\n\n   @Nullable public abstract String name();\n\n   public abstract List<String> args();\n\n   @Nullable public abstract Config config();\n\n   @Nullable public abstract State state();\n\n   @Nullable public abstract String image();\n\n   @Nullable public abstract NetworkSettings networkSettings();\n\n   @Nullable public abstract String sysInitPath();\n\n   @Nullable public abstract String resolvConfPath();\n\n   public abstract Map<String, String> volumes();\n\n   @Nullable public abstract HostConfig hostConfig();\n\n   @Nullable public abstract String driver();\n\n   @Nullable public abstract String execDriver();\n\n   public abstract Map<String, Boolean> volumesRW();\n\n   @Nullable public abstract String command();\n\n   @Nullable public abstract String status();\n\n   public abstract List<Port> ports();\n\n   @Nullable public abstract String hostnamePath();\n\n   @Nullable public abstract String hostsPath();\n\n   @Nullable public abstract String mountLabel();\n\n   @Nullable public abstract String processLabel();\n\n   public abstract Optional<Node> node();\n\n   Container() {\n   }\n\n   @SerializedNames(\n         {\n                 \"Id\", \"Created\", \"Path\", \"Name\", \"Args\", \"Config\", \"State\", \"Image\", \"NetworkSettings\", \"SysInitPath\",\n                 \"ResolvConfPath\", \"Volumes\", \"HostConfig\", \"Driver\", \"ExecDriver\", \"VolumesRW\", \"Command\", \"Status\",\n                 \"Ports\", \"HostnamePath\", \"HostsPath\", \"MountLabel\", \"ProcessLabel\", \"Node\"\n         })\n   public static Container create(String id, Date created, String path, String name, List<String> args, Config config,\n                                  State state, String image, NetworkSettings networkSettings, String sysInitPath,\n                                  String resolvConfPath, Map<String, String> volumes, HostConfig hostConfig,\n                                  String driver, String execDriver, Map<String, Boolean> volumesRW, String command,\n                                  String status, List<Port> ports, String hostnamePath, String hostsPath,\n                                  String mountLabel, String processLabel, Optional<Node> node) {\n      return new AutoValue_Container(id, created, path, name, copyOf(args), config, state, image, networkSettings,\n              sysInitPath, resolvConfPath, copyOf(volumes), hostConfig, driver, execDriver, copyOf(volumesRW), command,\n              status, copyOf(ports), hostnamePath, hostsPath, mountLabel, processLabel, node);\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().fromContainer(this);\n   }\n\n   public static final class Builder {\n\n      private String id;\n      private Date created;\n      private String path;\n      private String name;\n      private List<String> args;\n      private Config config;\n      private State state;\n      private String image;\n      private NetworkSettings networkSettings;\n      private String sysInitPath;\n      private String resolvConfPath;\n      private Map<String, String> volumes = ImmutableMap.of();\n      private HostConfig hostConfig;\n      private String driver;\n      private String execDriver;\n      private Map<String, Boolean> volumesRW = ImmutableMap.of();\n      private String command;\n      private String status;\n      private List<Port> ports = ImmutableList.of();\n      private String hostnamePath;\n      private String hostsPath;\n      private String mountLabel;\n      private String processLabel;\n      private Optional<Node> node = Optional.absent();\n\n      public Builder id(String id) {\n         this.id = id;\n         return this;\n      }\n\n      public Builder created(Date created) {\n         this.created = created;\n         return this;\n      }\n\n      public Builder path(String path) {\n         this.path = path;\n         return this;\n      }\n\n      public Builder name(String name) {\n         this.name = name;\n         return this;\n      }\n\n      public Builder args(List<String> args) {\n         this.args = args;\n         return this;\n      }\n\n      public Builder config(Config config) {\n         this.config = config;\n         return this;\n      }\n\n      public Builder state(State state) {\n         this.state = state;\n         return this;\n      }\n\n      public Builder image(String imageName) {\n         this.image = imageName;\n         return this;\n      }\n\n      public Builder networkSettings(NetworkSettings networkSettings) {\n         this.networkSettings = networkSettings;\n         return this;\n      }\n\n      public Builder sysInitPath(String sysInitPath) {\n         this.sysInitPath = sysInitPath;\n         return this;\n      }\n\n      public Builder resolvConfPath(String resolvConfPath) {\n         this.resolvConfPath = resolvConfPath;\n         return this;\n      }\n\n      public Builder volumes(Map<String, String> volumes) {\n         this.volumes = volumes;\n         return this;\n      }\n\n      public Builder hostConfig(HostConfig hostConfig) {\n         this.hostConfig = hostConfig;\n         return this;\n      }\n\n      public Builder driver(String driver) {\n         this.driver = driver;\n         return this;\n      }\n\n      public Builder execDriver(String execDriver) {\n         this.execDriver = execDriver;\n         return this;\n      }\n\n      public Builder volumesRW(Map<String, Boolean> volumesRW) {\n         this.volumesRW = volumesRW;\n         return this;\n      }\n\n      public Builder command(String command) {\n         this.command = command;\n         return this;\n      }\n\n      public Builder status(String status) {\n         this.status = status;\n         return this;\n      }\n\n      public Builder ports(List<Port> ports) {\n         this.ports = ports;\n         return this;\n      }\n\n      public Builder hostnamePath(String hostnamePath) {\n         this.hostnamePath = hostnamePath;\n         return this;\n      }\n\n      public Builder hostsPath(String hostsPath) {\n         this.hostsPath = hostsPath;\n         return this;\n      }\n\n      public Builder mountLabel(String mountLabel) {\n         this.mountLabel = mountLabel;\n         return this;\n      }\n\n      public Builder processLabel(String processLabel) {\n         this.processLabel = processLabel;\n         return this;\n      }\n\n      public Builder node(Node node) {\n         this.node = Optional.fromNullable(node);\n         return this;\n      }\n\n      public Container build() {\n         return Container.create(id, created, path, name, args, config, state, image, networkSettings,\n                 sysInitPath, resolvConfPath, volumes, hostConfig, driver, execDriver, volumesRW, command, status,\n                 ports, hostnamePath, hostsPath, mountLabel, processLabel, node);\n      }\n\n      public Builder fromContainer(Container in) {\n         return this.id(in.id()).name(in.name()).created(in.created()).path(in.path()).args(in.args())\n                 .config(in.config()).state(in.state()).image(in.image()).networkSettings(in.networkSettings())\n                 .sysInitPath(in.sysInitPath()).resolvConfPath(in.resolvConfPath()).driver(in.driver())\n                 .execDriver(in.execDriver()).volumes(in.volumes()).hostConfig(in.hostConfig()).volumesRW(in.volumesRW())\n                 .command(in.command()).status(in.status()).ports(in.ports()).hostnamePath(in.hostnamePath())\n                 .hostsPath(in.hostsPath()).mountLabel(in.mountLabel()).processLabel(in.processLabel()).node(in.node().orNull());\n      }\n   }\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/domain/ContainerSummary.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.domain;\n\nimport static org.jclouds.docker.internal.NullSafeCopies.copyOf;\nimport java.util.List;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n// TODO it may be redundant (we already have Container value class)\n@AutoValue\npublic abstract class ContainerSummary {\n\n   public abstract String id();\n\n   public abstract List<String> names();\n\n   public abstract String created();\n\n   public abstract String image();\n\n   public abstract String command();\n\n   public abstract List<Port> ports();\n\n   public abstract String status();\n\n   ContainerSummary() {\n   }\n\n   @SerializedNames({\"Id\", \"Names\", \"Created\", \"Image\", \"Command\", \"Ports\", \"Status\"})\n   public static ContainerSummary create(String id, List<String> names, String created, String image, String command, List<Port> ports, String status) {\n      return new AutoValue_ContainerSummary(id, copyOf(names), created, image, command, copyOf(ports), status);\n   }\n\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/domain/Exec.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.domain;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n/**\n * Represents a response from Exec Create call (<code>POST /containers/(id)/exec</code>).\n */\n@AutoValue\npublic abstract class Exec {\n\n   public abstract String id();\n\n   @SerializedNames({ \"Id\"})\n   public static Exec create(String id) {\n      return new AutoValue_Exec(id);\n   }\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/domain/ExecCreateParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.domain;\n\nimport static org.jclouds.docker.internal.NullSafeCopies.copyOf;\n\nimport java.util.List;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n/**\n * Json Parameters (some of them) of Exec Create call.\n */\n@AutoValue\npublic abstract class ExecCreateParams {\n\n   public abstract boolean attachStdout();\n\n   public abstract boolean attachStderr();\n\n   public abstract List<String> cmd();\n\n   @SerializedNames({ \"AttachStdout\", \"AttachStderr\", \"Cmd\" })\n   private static ExecCreateParams create(boolean attachStdout, boolean attachStderr, List<String> cmd) {\n      return builder().attachStdout(attachStdout).attachStderr(attachStderr).cmd(cmd).build();\n   }\n\n   /**\n    * Creates builder for {@link ExecCreateParams}, it sets\n    * {@link #attachStderr()} and {@link #attachStdout()} to true as a default.\n    *\n    * @return new {@link ExecCreateParams.Builder} instance\n    */\n   public static Builder builder() {\n      return new AutoValue_ExecCreateParams.Builder().attachStderr(true).attachStdout(true);\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n\n      public abstract Builder attachStdout(boolean b);\n\n      public abstract Builder attachStderr(boolean b);\n\n      public abstract Builder cmd(List<String> cmd);\n\n      abstract List<String> cmd();\n\n      abstract ExecCreateParams autoBuild();\n\n      public ExecCreateParams build() {\n         cmd(copyOf(cmd()));\n         return autoBuild();\n      }\n   }\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/domain/ExecInspect.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.domain;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n/**\n * Represents a response (part of it) from Exec Inspect call (\n * <code>GET /exec/(id)/json</code>).\n */\n@AutoValue\npublic abstract class ExecInspect {\n\n   public abstract String id();\n\n   public abstract boolean running();\n\n   public abstract int exitCode();\n\n   @SerializedNames({ \"ID\", \"Running\", \"ExitCode\"})\n   public static ExecInspect create(String id, boolean running, int exitCode) {\n      return new AutoValue_ExecInspect(id, running, exitCode);\n   }\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/domain/ExecStartParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.domain;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n/**\n * Json Parameter(s) (some of them) of Exec Start call.\n */\n@AutoValue\npublic abstract class ExecStartParams {\n\n   public abstract boolean detach();\n\n   @SerializedNames({ \"Detach\" })\n   public static ExecStartParams create(boolean detach) {\n      return builder().detach(detach).build();\n   }\n\n   public static Builder builder() {\n      return new AutoValue_ExecStartParams.Builder().detach(false);\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n\n      public abstract Builder detach(boolean b);\n\n      public abstract ExecStartParams build();\n   }\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/domain/ExposedPorts.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.domain;\n\nimport static org.jclouds.docker.internal.NullSafeCopies.copyOf;\n\nimport java.util.List;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class ExposedPorts {\n   public abstract String portAndProtocol();\n\n   public abstract List<String> hostPorts();\n\n   ExposedPorts() {\n   }\n\n   @SerializedNames({ \"PortAndProtocol\", \"HostPorts\" })\n   public static ExposedPorts create(String portAndProtocol, List<String> hostPorts) {\n      return new AutoValue_ExposedPorts(portAndProtocol, copyOf(hostPorts));\n   }\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/domain/HostConfig.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.domain;\n\nimport static org.jclouds.docker.internal.NullSafeCopies.copyOf;\nimport static org.jclouds.docker.internal.NullSafeCopies.copyWithNullOf;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.Lists;\nimport com.google.common.collect.Maps;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\n@AutoValue\npublic abstract class HostConfig {\n   @Nullable public abstract String containerIDFile();\n\n   @Nullable public abstract List<String> binds();\n\n   public abstract List<Map<String, String>> lxcConf();\n\n   public abstract boolean privileged();\n\n   @Nullable public abstract List<String> dns();\n\n   @Nullable public abstract List<String> dnsSearch();\n\n   public abstract Map<String, List<Map<String, String>>> portBindings();\n\n   @Nullable public abstract List<String> links();\n\n   @Nullable public abstract List<String> extraHosts();\n\n   public abstract boolean publishAllPorts();\n\n   @Nullable public abstract List<String> volumesFrom();\n\n   @Nullable public abstract String networkMode();\n\n   @Nullable public abstract List<String> securityOpt();\n\n   @Nullable public abstract List<String> capAdd();\n\n   @Nullable public abstract List<String> capDrop();\n\n   public abstract Map<String, String> restartPolicy();\n\n\n\n   HostConfig() {\n   }\n\n   @SerializedNames({ \"ContainerIDFile\", \"Binds\", \"LxcConf\", \"Privileged\", \"Dns\", \"DnsSearch\", \"PortBindings\",\n         \"Links\", \"ExtraHosts\", \"PublishAllPorts\", \"VolumesFrom\", \"NetworkMode\", \"SecurityOpt\",\n         \"CapAdd\", \"CapDrop\", \"RestartPolicy\" })\n   public static HostConfig create(String containerIDFile, List<String> binds, List<Map<String, String>> lxcConf,\n         boolean privileged, List<String> dns, List<String> dnsSearch, Map<String, List<Map<String, String>>> portBindings,\n         List<String> links, List<String> extraHosts, boolean publishAllPorts, List<String> volumesFrom, String networkMode, \n         List<String> securityOpt, List<String> capAdd, List<String> capDrop, Map<String, String> restartPolicy) {\n      return new AutoValue_HostConfig(containerIDFile, copyWithNullOf(binds), copyOf(lxcConf), privileged, copyWithNullOf(dns), copyWithNullOf(dnsSearch),\n            copyOf(portBindings), copyWithNullOf(links), copyWithNullOf(extraHosts), publishAllPorts, copyWithNullOf(volumesFrom), networkMode,\n            copyOf(securityOpt), copyWithNullOf(capAdd), copyWithNullOf(capDrop), copyOf(restartPolicy));\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().fromHostConfig(this);\n   }\n\n   public static final class Builder {\n\n      private String containerIDFile;\n      private List<String> binds;\n      private List<Map<String, String>> lxcConf = Lists.newArrayList();\n      private boolean privileged;\n      private List<String> dns;\n      private List<String> dnsSearch;\n      private Map<String, List<Map<String, String>>> portBindings = Maps.newLinkedHashMap();\n      private List<String> links;\n      private List<String> extraHosts;\n      private boolean publishAllPorts;\n      private List<String> volumesFrom;\n      private String networkMode;\n      private List<String> securityOpt = Lists.newArrayList();\n      private List<String> capAdd;\n      private List<String> capDrop;\n      private Map<String, String> restartPolicy = Maps.newHashMap();\n      \n      public Builder containerIDFile(String containerIDFile) {\n         this.containerIDFile = containerIDFile;\n         return this;\n      }\n\n      public Builder binds(List<String> binds) {\n         this.binds = binds;\n         return this;\n      }\n\n      public Builder lxcConf(List<Map<String, String>> lxcConf) {\n         this.lxcConf = lxcConf;\n         return this;\n      }\n\n      public Builder privileged(boolean privileged) {\n         this.privileged = privileged;\n         return this;\n      }\n\n      public Builder dns(List<String> dns) {\n         this.dns = dns;\n         return this;\n      }\n\n      public Builder dnsSearch(List<String> dnsSearch) {\n         this.dnsSearch = dnsSearch;\n         return this;\n      }\n\n      public Builder links(List<String> links) {\n         this.links = links;\n         return this;\n      }\n\n      public Builder extraHosts(List<String> extraHosts) {\n         this.extraHosts = extraHosts;\n         return this;\n      }\n\n      public Builder portBindings(Map<String, List<Map<String, String>>> portBindings) {\n         this.portBindings = portBindings;\n         return this;\n      }\n\n      public Builder publishAllPorts(boolean publishAllPorts) {\n         this.publishAllPorts = publishAllPorts;\n         return this;\n      }\n\n      public Builder volumesFrom(List<String> volumesFrom) {\n         this.volumesFrom = volumesFrom;\n         return this;\n      }\n\n      public Builder networkMode(String networkMode) {\n         this.networkMode = networkMode;\n         return this;\n      }\n\n      public Builder securityOpt(List<String> securityOpt) {\n         this.securityOpt = securityOpt;\n         return this;\n      }\n\n      public Builder capAdd(List<String> capAdd) {\n         this.capAdd = capAdd;\n         return this;\n      }\n\n      public Builder capDrop(List<String> capDrop) {\n         this.capDrop = capDrop;\n         return this;\n      }\n\n      public Builder restartPolicy(Map<String, String> restartPolicy) {\n         this.restartPolicy = restartPolicy;\n         return this;\n      }\n      \n      public HostConfig build() {\n         return HostConfig.create(containerIDFile, binds, lxcConf, privileged, dns, dnsSearch, portBindings, links,\n               extraHosts, publishAllPorts, volumesFrom, networkMode, securityOpt, capAdd, capDrop, restartPolicy);\n      }\n\n      public Builder fromHostConfig(HostConfig in) {\n         return this.containerIDFile(in.containerIDFile()).binds(in.binds()).lxcConf(in.lxcConf())\n               .privileged(in.privileged()).dns(in.dns()).dnsSearch(in.dnsSearch()).links(in.links())\n               .extraHosts(in.extraHosts()).portBindings(in.portBindings()).publishAllPorts(in.publishAllPorts())\n               .volumesFrom(in.volumesFrom()).networkMode(in.networkMode()).securityOpt(in.securityOpt())\n               .capAdd(in.capAdd()).capDrop(in.capDrop()).restartPolicy(in.restartPolicy());\n      }\n   }\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/domain/Image.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.domain;\n\nimport static org.jclouds.docker.internal.NullSafeCopies.copyOf;\n\nimport java.util.Date;\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n/**\n * Represents a response from Docker \"Inspect an image\" call (<code>GET /images/(name)/json</code>).\n */\n@AutoValue\npublic abstract class Image {\n\n   public abstract String id();\n\n   @Nullable public abstract String author();\n\n   @Nullable public abstract String comment();\n\n   @Nullable public abstract Config config();\n\n   @Nullable public abstract Config containerConfig();\n\n   public abstract String parent();\n\n   public abstract Date created();\n\n   public abstract String container();\n\n   public abstract String dockerVersion();\n\n   public abstract String architecture();\n\n   public abstract String os();\n\n   public abstract long size();\n\n   public abstract long virtualSize();\n\n   /**\n    * Tags of the image. The value is <code>null</code> when the instance comes\n    * from {@link org.jclouds.docker.features.ImageApi#inspectImage(String)}.\n    * Other methods can populate the content (e.g.\n    * {@link org.jclouds.docker.compute.strategy.DockerComputeServiceAdapter#listImages()}\n    * call.\n    * <p>\n    * The tags are in form \"ubuntu:12.10\", \"docker.io/busybox:1.23.2\", ...\n    * </p>\n    * @return list of tags or <code>null</code>\n    */\n   @Nullable public abstract List<String> repoTags();\n\n   Image() {\n   }\n\n   @SerializedNames({ \"Id\", \"Author\", \"Comment\", \"Config\", \"ContainerConfig\", \"Parent\", \"Created\",\n           \"Container\", \"DockerVersion\", \"Architecture\", \"Os\", \"Size\", \"VirtualSize\", \"RepoTags\" })\n   public static Image create(String id, String author, String comment, Config config, Config containerConfig, String parent, Date created, String container, String dockerVersion, String architecture, String os, long size, long virtualSize, List<String> repoTags) {\n      return new AutoValue_Image(id, author, comment, config, containerConfig, parent, created, container,\n              dockerVersion, architecture, os, size, virtualSize, copyOf(repoTags));\n   }\n\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/domain/ImageHistory.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.domain;\n\nimport static org.jclouds.docker.internal.NullSafeCopies.copyOf;\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class ImageHistory {\n\n   public abstract String id();\n\n   public abstract long created();\n\n   public abstract String createdBy();\n\n   @Nullable public abstract List<String> tags();\n\n   public abstract long size();\n\n   public abstract String comment();\n\n\n   ImageHistory() {\n   }\n\n   @SerializedNames({\"Id\", \"Created\", \"CreatedBy\", \"Tags\", \"Size\", \"Comment\"})\n   public static ImageHistory create(String id, long created, String createdBy, List<String> tags, long size, String comment) {\n      return new AutoValue_ImageHistory(id, created, createdBy, copyOf(tags), size, comment);\n   }\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/domain/ImageSummary.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.domain;\n\nimport static org.jclouds.docker.internal.NullSafeCopies.copyOf;\nimport java.util.List;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n// TODO it may be redundant (we already have Image value class)\n@AutoValue\npublic abstract class ImageSummary {\n\n   public abstract String id();\n\n   public abstract long created();\n\n   public abstract String parentId();\n\n   public abstract long size();\n\n   public abstract long virtualSize();\n\n   public abstract List<String> repoTags();\n\n   ImageSummary() {\n   }\n\n   @SerializedNames({\"Id\", \"Created\", \"ParentId\", \"Size\", \"VirtualSize\", \"RepoTags\"})\n   public static ImageSummary create(String id, long created, String parentId, long size, long virtualSize,\n                                     List<String> repoTags) {\n      return new AutoValue_ImageSummary(id, created, parentId, size, virtualSize, copyOf(repoTags));\n   }\n\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/domain/Info.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.domain;\n\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class Info {\n\n   public abstract int containers();\n\n   public abstract boolean debug();\n\n   public abstract String driver();\n\n   public abstract List<List<String>> driverStatus();\n\n   public abstract String executionDriver();\n\n   public abstract boolean iPv4Forwarding();\n\n   public abstract int images();\n\n   public abstract String indexServerAddress();\n\n   @Nullable public abstract String initPath();\n\n   @Nullable public abstract String initSha1();\n\n   public abstract String kernelVersion();\n\n   public abstract boolean memoryLimit();\n\n   public abstract int nEventsListener();\n\n   public abstract int nFd();\n\n   public abstract int nGoroutines();\n\n   public abstract String operatingSystem();\n\n   public abstract boolean swapLimit();\n\n   public abstract String dockerRootDir();\n\n   /**\n    * @return a list of daemon labels\n    */\n   @Nullable public abstract List<String> labels();\n\n   /**\n    * @return total memory available\n    */\n   public abstract long memTotal();\n\n   /**\n    * @return the number of CPUs available on the machine\n    */\n   public abstract int ncpu();\n\n   /**\n    * @return a unique ID identifying the daemon\n    */\n   public abstract String id();\n\n   /**\n    * @return a user-friendly name describing the running Docker daemon\n    */\n   public abstract String name();\n\n   Info() {\n   }\n\n   @SerializedNames({\n                   \"Containers\", \"Debug\", \"Driver\", \"DriverStatus\", \"ExecutionDriver\", \"IPv4Forwarding\", \"Images\",\n                   \"IndexServerAddress\", \"InitPath\", \"InitSha1\", \"KernelVersion\", \"MemoryLimit\", \"NEventsListener\",\n                   \"NFd\", \"NGoroutines\", \"OperatingSystem\", \"SwapLimit\", \"DockerRootDir\", \"Labels\", \"MemTotal\", \"NCPU\",\n                   \"ID\", \"Name\"\n   })\n   public static Info create(int containers, boolean debug, String driver, List<List<String>> driverStatus,\n                             String executionDriver, boolean iPv4Forwarding, int images, String indexServerAddress,\n                             String initPath, String initSha1, String kernelVersion, boolean memoryLimit,\n                             int nEventsListener, int nFd, int nGoroutines, String operatingSystem, boolean swapLimit,\n                             String dockerRootDir, List<String> labels, long memTotal, int ncpu, String id, String name) {\n      return new AutoValue_Info(containers, debug, driver, driverStatus, executionDriver, iPv4Forwarding, images,\n              indexServerAddress, initPath, initSha1, kernelVersion, memoryLimit, nEventsListener, nFd, nGoroutines,\n              operatingSystem, swapLimit, dockerRootDir, labels, memTotal, ncpu, id, name);\n   }\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/domain/Network.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.domain;\n\nimport static org.jclouds.docker.internal.NullSafeCopies.copyOf;\nimport static org.jclouds.docker.internal.NullSafeCopies.copyWithNullOf;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport com.google.auto.value.AutoValue;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\n@AutoValue\npublic abstract class Network {\n\n   @AutoValue\n   public abstract static class IPAM {\n\n      IPAM() { }\n\n      @Nullable public abstract String driver();\n\n      public abstract List<Config> config();\n\n      @SerializedNames({\"Driver\", \"Config\"})\n      public static IPAM create(@Nullable String driver, List<Config> config) {\n         return builder()\n               .driver(driver)\n               .config(config)\n               .build();\n      }\n\n      public static Builder builder() {\n         return new AutoValue_Network_IPAM.Builder();\n      }\n\n      @AutoValue.Builder\n      public abstract static class Builder {\n\n         public abstract Builder driver(@Nullable String driver);\n\n         public abstract Builder config(List<Config> config);\n\n         abstract List<Config> config();\n\n         abstract IPAM autoBuild();\n\n         public IPAM build() {\n            return config(copyOf(config()))\n                  .autoBuild();\n         }\n      }\n\n      @AutoValue\n      public abstract static class Config {\n\n         Config() { }\n\n         public abstract String subnet();\n\n         @Nullable public abstract String ipRange();\n\n         @Nullable public abstract String gateway();\n\n         @SerializedNames({\"Subnet\", \"IPRange\", \"Gateway\"})\n         public static Config create(String subnet, @Nullable String ipRange, @Nullable String gateway) {\n            return builder()\n                  .subnet(subnet)\n                  .ipRange(ipRange)\n                  .gateway(gateway)\n                  .build();\n         }\n\n         public static Builder builder() {\n            return new AutoValue_Network_IPAM_Config.Builder();\n         }\n\n         @AutoValue.Builder\n         public abstract static class Builder {\n\n            public abstract Builder subnet(String subnet);\n\n            public abstract Builder ipRange(@Nullable String ipRange);\n\n            public abstract Builder gateway(@Nullable String gateway);\n\n            abstract Config build();\n         }\n      }\n   }\n\n   @AutoValue\n   public abstract static class Details {\n\n      Details() { }\n\n      public abstract String endpoint();\n\n      public abstract String macAddress();\n\n      public abstract String ipv4address();\n\n      public abstract String ipv6address();\n\n      @SerializedNames({ \"EndpointID\", \"MacAddress\", \"IPv4Address\", \"IPv6Address\" })\n      public static Details create(String endpoint, String macAddress, String ipv4address, String ipv6address) {\n         return builder()\n               .endpoint(endpoint)\n               .macAddress(macAddress)\n               .ipv4address(ipv4address)\n               .ipv6address(ipv6address)\n               .build();\n      }\n\n      public static Builder builder() {\n         return new AutoValue_Network_Details.Builder();\n      }\n\n      @AutoValue.Builder\n      public abstract static class Builder {\n\n         public abstract Builder endpoint(String endpoint);\n\n         public abstract Builder macAddress(String macAddress);\n\n         public abstract Builder ipv4address(String ipv4address);\n\n         public abstract Builder ipv6address(String ipv6address);\n\n         abstract Details build();\n      }\n   }\n\n   @Nullable public abstract String name();\n\n   @Nullable public abstract String id();\n\n   @Nullable public abstract String scope();\n\n   @Nullable public abstract String driver();\n\n   @Nullable public abstract IPAM ipam();\n\n   @Nullable public abstract Map<String, Details> containers();\n\n   @Nullable public abstract Map<String, String> options();\n\n   Network() { }\n\n   @SerializedNames({ \"Name\", \"Id\", \"Scope\", \"Driver\", \"IPAM\", \"Containers\", \"Options\" })\n   public static Network create(@Nullable String name, @Nullable String id, @Nullable String scope,\n         @Nullable String driver, @Nullable IPAM ipam, @Nullable Map<String, Details> containers,\n         @Nullable Map<String, String> options) {\n      return builder()\n            .name(name)\n            .id(id)\n            .scope(scope)\n            .driver(driver)\n            .ipam(ipam)\n            .containers(containers)\n            .options(options)\n            .build();\n   }\n\n   public static Builder builder() {\n      return new AutoValue_Network.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n\n      public abstract Builder name(@Nullable String name);\n\n      public abstract Builder id(@Nullable String id);\n\n      public abstract Builder scope(@Nullable String scope);\n\n      public abstract Builder driver(@Nullable String driver);\n\n      public abstract Builder ipam(@Nullable IPAM ipam);\n\n      public abstract Builder containers(@Nullable Map<String, Details> containers);\n\n      public abstract Builder options(@Nullable Map<String, String> options);\n\n      abstract Map<String, Details> containers();\n\n      abstract Map<String, String> options();\n\n      abstract Network autoBuild();\n\n      public Network build() {\n         return containers(copyWithNullOf(containers()))\n               .options(copyOf(options()))\n               .autoBuild();\n      }\n   }\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/domain/NetworkSettings.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.domain;\n\nimport static org.jclouds.docker.internal.NullSafeCopies.copyOf;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.docker.internal.NullSafeCopies;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.Lists;\nimport com.google.common.collect.Maps;\n\n@AutoValue\npublic abstract class NetworkSettings {\n\n   @AutoValue\n   public abstract static class Details {\n\n      Details() {} // For AutoValue only!\n\n      public abstract String endpoint();\n\n      public abstract String gateway();\n\n      public abstract String ipAddress();\n\n      public abstract int ipPrefixLen();\n\n      public abstract String ipv6Gateway();\n\n      public abstract String globalIPv6Address();\n\n      public abstract int globalIPv6PrefixLen();\n\n      public abstract String macAddress();\n\n      @SerializedNames({ \"EndpointID\", \"Gateway\", \"IPAddress\", \"IPPrefixLen\", \"IPv6Gateway\", \"GlobalIPv6Address\", \"GlobalIPv6PrefixLen\", \"MacAddress\" })\n      public static Details create(String endpointId, String gateway, String ipAddress, int ipPrefixLen, String ipv6Gateway, String globalIPv6Address,\n                                   int globalIPv6PrefixLen, String macAddress) {\n         return builder().endpoint(endpointId).gateway(gateway).ipAddress(ipAddress).ipPrefixLen(ipPrefixLen)\n               .ipv6Gateway(ipv6Gateway).globalIPv6Address(globalIPv6Address)\n               .globalIPv6PrefixLen(globalIPv6PrefixLen).macAddress(macAddress)\n               .build();\n      }\n      \n      public abstract Builder toBuilder();\n\n      public static Builder builder() {\n         return new AutoValue_NetworkSettings_Details.Builder();\n      }\n\n      @AutoValue.Builder\n      public abstract static class Builder {\n         public abstract Builder endpoint(String value);\n         public abstract Builder gateway(String value);\n         public abstract Builder ipAddress(String value);\n         public abstract Builder ipPrefixLen(int value);\n         public abstract Builder ipv6Gateway(String value);\n         public abstract Builder globalIPv6Address(String value);\n         public abstract Builder globalIPv6PrefixLen(int value);\n         public abstract Builder macAddress(String value);\n\n         public abstract Details build();\n      }\n   }\n\n   public abstract String bridge();\n\n   @Nullable public abstract String sandboxId();\n\n   public abstract boolean hairpinMode();\n\n   @Nullable public abstract String linkLocalIPv6Address();\n\n   public abstract int linkLocalIPv6PrefixLen();\n\n   @Nullable public abstract Map<String, List<Map<String, String>>> ports();\n\n   @Nullable public abstract String sandboxKey();\n\n   public abstract List<String> secondaryIPAddresses();\n\n   public abstract List<String> secondaryIPv6Addresses();\n\n   @Nullable public abstract String endpointId();\n\n   public abstract String gateway();\n\n   @Nullable public abstract String globalIPv6Address();\n\n   public abstract int globalIPv6PrefixLen();\n\n   public abstract String ipAddress();\n\n   public abstract int ipPrefixLen();\n\n   @Nullable public abstract String ipv6Gateway();\n\n   @Nullable public abstract String macAddress();\n\n   public abstract Map<String, Details> networks();\n\n   @Nullable public abstract String portMapping();\n\n   NetworkSettings() {\n   }\n\n   @SerializedNames({ \"Bridge\", \"SandboxID\", \"HairpinMode\", \"LinkLocalIPv6Address\",\n           \"LinkLocalIPv6PrefixLen\", \"Ports\", \"SandboxKey\", \"SecondaryIPAddresses\",\n           \"SecondaryIPv6Addresses\", \"EndpointID\", \"Gateway\", \"GlobalIPv6Address\",\n           \"GlobalIPv6PrefixLen\", \"IPAddress\", \"IPPrefixLen\", \"IPv6Gateway\",\n           \"MacAddress\", \"Networks\", \"PortMapping\" })\n   public static NetworkSettings create(String bridge, String sandboxId, boolean hairpinMode, String linkLocalIPv6Address,\n                                        int linkLocalIPv6PrefixLen, Map<String, List<Map<String, String>>> ports, String sandboxKey, List<String> secondaryIPAddresses,\n                                        List<String> secondaryIPv6Addresses, String endpointId, String gateway, String globalIPv6Address,\n                                        int globalIPv6PrefixLen, String ipAddress, int ipPrefixLen, String ipv6Gateway,\n                                        String macAddress, Map<String, Details> networks, String portMapping) {\n      return new AutoValue_NetworkSettings(\n              bridge, sandboxId, hairpinMode, linkLocalIPv6Address,\n              linkLocalIPv6PrefixLen, ports, sandboxKey, copyOf(secondaryIPAddresses), copyOf(secondaryIPv6Addresses),\n              endpointId, gateway, globalIPv6Address, globalIPv6PrefixLen,\n              ipAddress, ipPrefixLen, ipv6Gateway,\n              macAddress, copyOf(networks), portMapping);\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().fromNetworkSettings(this);\n   }\n\n   public static final class Builder {\n\n      private String ipAddress;\n      private int ipPrefixLen;\n      private String gateway;\n      private String bridge;\n      private String portMapping;\n      private Map<String, List<Map<String, String>>> ports;\n      private String sandboxId;\n      private boolean hairpinMode;\n      private String linkLocalIPv6Address;\n      private int linkLocalIPv6PrefixLen;\n      private String sandboxKey;\n      private List<String> secondaryIPAddresses = Lists.newArrayList();\n      private List<String> secondaryIPv6Addresses = Lists.newArrayList();\n      private String endpointId;\n      private String globalIPv6Address;\n      private int globalIPv6PrefixLen;\n      private String ipv6Gateway;\n      private String macAddress;\n      private Map<String, Details> networks = Maps.newHashMap();\n\n      public Builder ipAddress(String ipAddress) {\n         this.ipAddress = ipAddress;\n         return this;\n      }\n\n      public Builder ipPrefixLen(int ipPrefixLen) {\n         this.ipPrefixLen = ipPrefixLen;\n         return this;\n      }\n\n      public Builder gateway(String gateway) {\n         this.gateway = gateway;\n         return this;\n      }\n\n      public Builder bridge(String bridge) {\n         this.bridge = bridge;\n         return this;\n      }\n\n      public Builder portMapping(String portMapping) {\n         this.portMapping = portMapping;\n         return this;\n      }\n\n      public Builder ports(Map<String, List<Map<String, String>>> ports) {\n         this.ports = NullSafeCopies.copyWithNullOf(ports);\n         return this;\n      }\n\n      public Builder sandboxId(String sandboxId) {\n         this.sandboxId = sandboxId;\n         return this;\n      }\n\n      public Builder hairpinMode(boolean hairpinMode) {\n         this.hairpinMode = hairpinMode;\n         return this;\n      }\n\n      public Builder linkLocalIPv6Address(String linkLocalIPv6Address) {\n         this.linkLocalIPv6Address = linkLocalIPv6Address;\n         return this;\n      }\n\n      public Builder linkLocalIPv6PrefixLen(int linkLocalIPv6PrefixLen) {\n         this.linkLocalIPv6PrefixLen = linkLocalIPv6PrefixLen;\n         return this;\n      }\n\n      public Builder sandboxKey(String sandboxKey) {\n         this.sandboxKey = sandboxKey;\n         return this;\n      }\n\n      public Builder secondaryIPAddresses(List<String> secondaryIPAddresses) {\n         this.secondaryIPAddresses = secondaryIPAddresses;\n         return this;\n      }\n\n      public Builder secondaryIPv6Addresses(List<String> secondaryIPv6Addresses) {\n         this.secondaryIPv6Addresses = secondaryIPv6Addresses;\n         return this;\n      }\n\n      public Builder endpointId(String endpointId) {\n         this.endpointId = endpointId;\n         return this;\n      }\n\n      public Builder globalIPv6Address(String globalIPv6Address) {\n         this.globalIPv6Address = globalIPv6Address;\n         return this;\n      }\n\n      public Builder globalIPv6PrefixLen(int globalIPv6PrefixLen) {\n         this.globalIPv6PrefixLen = globalIPv6PrefixLen;\n         return this;\n      }\n\n      public Builder ipv6Gateway(String ipv6Gateway) {\n         this.ipv6Gateway = ipv6Gateway;\n         return this;\n      }\n\n      public Builder macAddress(String macAddress) {\n         this.macAddress = macAddress;\n         return this;\n      }\n\n      public Builder networks(Map<String, Details> networks) {\n         this.networks.putAll(networks);\n         return this;\n      }\n\n      public NetworkSettings build() {\n         return NetworkSettings.create(bridge, sandboxId, hairpinMode, linkLocalIPv6Address, linkLocalIPv6PrefixLen, ports,\n                 sandboxKey, secondaryIPAddresses, secondaryIPv6Addresses, endpointId, gateway,\n                 globalIPv6Address, globalIPv6PrefixLen, ipAddress, ipPrefixLen, ipv6Gateway, macAddress, networks, portMapping);\n      }\n\n      public Builder fromNetworkSettings(NetworkSettings in) {\n         return this.ipAddress(in.ipAddress()).ipPrefixLen(in.ipPrefixLen()).gateway(in.gateway()).bridge(in.bridge())\n               .portMapping(in.portMapping()).ports(in.ports()).sandboxId(in.sandboxId()).hairpinMode(in.hairpinMode()).linkLocalIPv6Address(in\n                         .linkLocalIPv6Address()).linkLocalIPv6PrefixLen(in.linkLocalIPv6PrefixLen()).sandboxKey(in.sandboxKey()).secondaryIPAddresses(in\n                         .secondaryIPAddresses()).secondaryIPv6Addresses(in.secondaryIPv6Addresses()).endpointId(in.endpointId()).globalIPv6Address(in\n                         .globalIPv6Address()).globalIPv6PrefixLen(in.globalIPv6PrefixLen()).ipv6Gateway(in.ipv6Gateway()).macAddress(in.macAddress())\n                 .networks(in.networks());\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/domain/Node.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.domain;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class Node {\n\n   Node() {\n   }\n\n   @SerializedNames({\"IP\"})\n   public static Node create(String ip) {\n      return new AutoValue_Node(ip);\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Nullable\n   public abstract String ip();\n\n   public Builder toBuilder() {\n      return builder().fromNode(this);\n   }\n\n   public static final class Builder {\n\n      private String ip;\n\n      public Builder ip(String ip) {\n         this.ip = ip;\n         return this;\n      }\n\n      public Node build() {\n         return Node.create(this.ip);\n      }\n\n      public Builder fromNode(Node in) {\n         return this.ip(in.ip());\n      }\n   }\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/domain/Port.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.domain;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class Port {\n   @Nullable public abstract String ip();\n\n   public abstract int privatePort();\n\n   @Nullable public abstract Integer publicPort();\n\n   public abstract String type();\n\n   Port() {\n   }\n\n   @SerializedNames({ \"IP\", \"PrivatePort\", \"PublicPort\", \"Type\" })\n   public static Port create(String ip, int privatePort, Integer publicPort, String type) {\n      return new AutoValue_Port(ip, privatePort, publicPort, type);\n   }\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/domain/Resource.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.domain;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class Resource {\n\n   public abstract String resource();\n\n   Resource() {\n   }\n\n   @SerializedNames({ \"Resource\" })\n   public static Resource create(String resource) {\n      return new AutoValue_Resource(resource);\n   }\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/domain/State.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.domain;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class State {\n\n\n   public abstract int pid();\n\n   public abstract boolean running();\n\n   public abstract int exitCode();\n\n   public abstract String startedAt();\n\n   public abstract String finishedAt();\n\n   public abstract boolean paused();\n\n   public abstract boolean restarting();\n\n   @Nullable public abstract String status();\n\n   public abstract boolean oomKilled();\n\n   public abstract boolean dead();\n\n   @Nullable public abstract String error();\n\n   State() {\n   }\n\n   @SerializedNames({ \"Pid\", \"Running\", \"ExitCode\", \"StartedAt\", \"FinishedAt\", \"Paused\", \"Restarting\", \"Status\", \"OOMKilled\", \"Dead\", \"Error\" })\n   public static State create(int pid, boolean running, int exitCode, String startedAt, String finishedAt,\n         boolean paused, boolean restarting, String status, boolean oomKilled, boolean dead, String error) {\n      return new AutoValue_State(pid, running, exitCode, startedAt, finishedAt, paused, restarting, status, oomKilled, dead, error);\n   }\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/domain/StatusCode.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.domain;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class StatusCode {\n\n   public abstract int statusCode();\n\n   StatusCode() {\n   }\n\n   @SerializedNames({ \"StatusCode\" })\n   public static StatusCode create(int statusCode) {\n      return new AutoValue_StatusCode(statusCode);\n   }\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/domain/Version.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.domain;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class Version {\n\n   public abstract String apiVersion();\n\n   public abstract String arch();\n\n   public abstract String gitCommit();\n\n   public abstract String goVersion();\n\n   public abstract String kernelVersion();\n\n   public abstract String os();\n\n   public abstract String version();\n\n   Version() {\n   }\n\n   @SerializedNames({ \"ApiVersion\", \"Arch\", \"GitCommit\", \"GoVersion\", \"KernelVersion\", \"Os\", \"Version\" })\n   public static Version create(String apiVersion, String arch, String gitCommit, String goVersion,\n                                String kernelVersion, String os, String version) {\n      return new AutoValue_Version(apiVersion, arch, gitCommit, goVersion, kernelVersion, os, version);\n   }\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/features/ContainerApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.features;\n\nimport java.io.InputStream;\nimport java.util.List;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyListOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.docker.domain.Config;\nimport org.jclouds.docker.domain.Container;\nimport org.jclouds.docker.domain.ContainerSummary;\nimport org.jclouds.docker.domain.HostConfig;\nimport org.jclouds.docker.domain.Image;\nimport org.jclouds.docker.domain.Resource;\nimport org.jclouds.docker.domain.StatusCode;\nimport org.jclouds.docker.options.AttachOptions;\nimport org.jclouds.docker.options.CommitOptions;\nimport org.jclouds.docker.options.ListContainerOptions;\nimport org.jclouds.docker.options.RemoveContainerOptions;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\n@Consumes(MediaType.APPLICATION_JSON)\n@Path(\"/v{jclouds.api-version}\")\npublic interface ContainerApi {\n\n   /**\n    * @return a set of containers\n    */\n   @Named(\"containers:list\")\n   @GET\n   @Path(\"/containers/json\")\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   List<ContainerSummary> listContainers();\n\n   /**\n    * @param options the options to list the containers (@see ListContainerOptions)\n    * @return a set of containers\n    */\n   @Named(\"containers:list\")\n   @GET\n   @Path(\"/containers/json\")\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   List<ContainerSummary> listContainers(ListContainerOptions options);\n\n   /**\n    * @param name the name for the new container. Must match /?[a-zA-Z0-9_-]+.\n    * @param config the container’s configuration (@see BindToJsonPayload)\n    * @return a new container\n    */\n   @Named(\"container:create\")\n   @POST\n   @Path(\"/containers/create\")\n   Container createContainer(@QueryParam(\"name\") String name, @BinderParam(BindToJsonPayload.class) Config config);\n\n   /**\n    * Return low-level information on the container id\n    * @param containerId  The id of the container to get.\n    * @return The details of the container or <code>null</code> if the container with the given id doesn't exist.\n    */\n   @Named(\"container:inspect\")\n   @GET\n   @Path(\"/containers/{id}/json\")\n   @Fallback(NullOnNotFoundOr404.class)\n   Container inspectContainer(@PathParam(\"id\") String containerId);\n\n   /**\n    * @param containerId The id of the container to be removed.\n    */\n   @Named(\"container:delete\")\n   @DELETE\n   @Path(\"/containers/{id}\")\n   void removeContainer(@PathParam(\"id\") String containerId);\n\n   /**\n    * @param containerId The id of the container to be removed.\n    * @param options the operation’s configuration (@see RemoveContainerOptions)\n    */\n   @Named(\"container:delete\")\n   @DELETE\n   @Path(\"/containers/{id}\")\n   void removeContainer(@PathParam(\"id\") String containerId, RemoveContainerOptions options);\n\n   /**\n    * @param containerId The id of the container to be started.\n    */\n   @Named(\"container:start\")\n   @POST\n   @Path(\"/containers/{id}/start\")\n   void startContainer(@PathParam(\"id\") String containerId);\n\n   /**\n    * @param containerId The id of the container to be started.\n    * @param hostConfig the container’s host configuration\n    */\n   @Named(\"container:start\")\n   @POST\n   @Path(\"/containers/{id}/start\")\n   void startContainer(@PathParam(\"id\") String containerId, @BinderParam(BindToJsonPayload.class) HostConfig hostConfig);\n\n   /**\n    * @param containerId The id of the container to be stopped.\n    */\n   @Named(\"container:stop\")\n   @POST\n   @Path(\"/containers/{id}/stop\")\n   void stopContainer(@PathParam(\"id\") String containerId);\n\n   @Named(\"container:stop\")\n   @POST\n   @Path(\"/containers/{id}/stop\")\n   void stopContainer(@PathParam(\"id\") String containerId, @QueryParam(\"t\") int secondsToWait);\n\n   /**\n    * Create a new image from a container’s changes\n    *\n    * @return a new image created from the current container's status.\n    */\n   @Named(\"container:commit\")\n   @POST\n   @Path(\"/commit\")\n   Image commit();\n\n   /**\n    * Create a new image from a container’s changes\n    *\n    * @param options the commit’s configuration (@see CommitOptions)\n    * @return a new image created from the current container's status.\n    */\n   @Named(\"container:commit\")\n   @POST\n   @Path(\"/commit\")\n   Image commit(CommitOptions options);\n\n   /**\n    * @param containerId The id of the container to be paused.\n    */\n   @Named(\"container:pause\")\n   @POST\n   @Path(\"/containers/{id}/pause\")\n   void pause(@PathParam(\"id\") String containerId);\n\n   /**\n    * @param containerId The id of the container to be unpaused.\n    */\n   @Named(\"container:unpause\")\n   @POST\n   @Path(\"/containers/{id}/unpause\")\n   void unpause(@PathParam(\"id\") String containerId);\n\n   /**\n    * @param containerId The id of the container to be attached.\n    */\n   @Named(\"container:attach\")\n   @POST\n   @Path(\"/containers/{id}/attach\")\n   InputStream attach(@PathParam(\"id\") String containerId);\n\n   /**\n    * @param containerId The id of the container to be attached.\n    * @param options the attach options @see org.jclouds.docker.options.AttachOptions\n    *\n    */\n   @Named(\"container:attach\")\n   @POST\n   @Path(\"/containers/{id}/attach\")\n   InputStream attach(@PathParam(\"id\") String containerId, AttachOptions options);\n\n   /**\n    * Block until container @param containerId stops, then returns the exit code\n    */\n   @Named(\"container:wait\")\n   @POST\n   @Path(\"/containers/{id}/wait\")\n   StatusCode wait(@PathParam(\"id\") String containerId);\n\n   /**\n    * @param containerId restarts\n    */\n   @Named(\"container:restart\")\n   @POST\n   @Path(\"/containers/{id}/restart\")\n   void restart(@PathParam(\"id\") String containerId);\n\n   @Named(\"container:restart\")\n   @POST\n   @Path(\"/containers/{id}/restart\")\n   void restart(@PathParam(\"id\") String containerId, @QueryParam(\"t\") int secondsToWait);\n\n\n   /**\n    * @param containerId to be killed\n    */\n   @Named(\"container:kill\")\n   @POST\n   @Path(\"/containers/{id}/kill\")\n   void kill(@PathParam(\"id\") String containerId);\n\n   /**\n    * @param containerId to be killed\n    * @param signal Signal to send to the container. When not set, SIGKILL is assumed and the call will waits for the\n    *               container to exit.\n    */\n   @Named(\"container:kill\")\n   @POST\n   @Path(\"/containers/{id}/kill\")\n   void kill(@PathParam(\"id\") String containerId, @QueryParam(\"signal\") int signal);\n\n   /**\n    * @param containerId to be killed\n    * @param signal Signal string like \"SIGINT\" to send to the container. When not set, SIGKILL is assumed and the call will waits for\n    *               the container to exit.\n    */\n   @Named(\"container:kill\")\n   @POST\n   @Path(\"/containers/{id}/kill\")\n   void kill(@PathParam(\"id\") String containerId, @QueryParam(\"signal\") String signal);\n\n   /**\n    * @param containerId id of the container to copy files from\n    */\n   @Named(\"container:copy\")\n   @POST\n   @Path(\"/containers/{id}/copy\")\n   InputStream copy(@PathParam(\"id\") String containerId, @BinderParam(BindToJsonPayload.class) Resource resource);\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/features/ImageApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.features;\n\nimport java.io.InputStream;\nimport java.util.List;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyListOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.docker.domain.Image;\nimport org.jclouds.docker.domain.ImageHistory;\nimport org.jclouds.docker.domain.ImageSummary;\nimport org.jclouds.docker.options.CreateImageOptions;\nimport org.jclouds.docker.options.DeleteImageOptions;\nimport org.jclouds.docker.options.ListImageOptions;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.rest.annotations.Fallback;\n\n@Consumes(MediaType.APPLICATION_JSON)\n@Path(\"/v{jclouds.api-version}\")\npublic interface ImageApi {\n\n   /**\n    * @return the images available.\n    */\n   @Named(\"images:list\")\n   @GET\n   @Path(\"/images/json\")\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   List<ImageSummary> listImages();\n\n   /**\n    * @param options the configuration to list images (@see ListImageOptions)\n    * @return the images available.\n    */\n   @Named(\"images:list\")\n   @GET\n   @Path(\"/images/json\")\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   List<ImageSummary> listImages(ListImageOptions options);\n\n   /**\n    * Return low-level information on the image with given name. Not all fields from the returned {@link Image} instance\n    * are populated by this method (e.g. {@link Image#repoTags()}).\n    *\n    * @param imageName The id of the image to inspect.\n    * @return low-level information on the image name\n    */\n   @Named(\"image:inspect\")\n   @GET\n   @Path(\"/images/{name}/json\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Image inspectImage(@PathParam(\"name\") String imageName);\n\n   /**\n    * Create an image, either by pull it from the registry or by importing it\n    *\n    * @param options the configuration to create an image (@see CreateImageOptions)\n    * @return a stream of the image creation.\n    */\n   @Named(\"image:create\")\n   @POST\n   @Path(\"/images/create\")\n   InputStream createImage(CreateImageOptions options);\n\n   /**\n    * @param name the image name to be deleted\n    * @return the stream of the deletion execution.\n    */\n   @Named(\"image:delete\")\n   @DELETE\n   @Path(\"/images/{name}\")\n   InputStream deleteImage(@PathParam(\"name\") String name);\n\n   /**\n    * @param name the name of the image to be removed\n    * @param options the image deletion's options (@see DeleteImageOptions)\n    * @return the stream of the deletion execution.\n    */\n   @Named(\"image:delete\")\n   @DELETE\n   @Path(\"/images/{name}\")\n   InputStream deleteImage(@PathParam(\"name\") String name, DeleteImageOptions options);\n\n   /**\n    * Tag the image name into a repository.\n    *\n    * @param name\n    *           the name of the image to be tagged\n    * @param repoName\n    *           the repository to tag in\n    * @param tag\n    *           the new tag name\n    * @param force\n    *           force create if tag already exists\n    */\n   @Named(\"image:tag\")\n   @POST\n   @Path(\"/images/{name}/tag\")\n   void tagImage(@PathParam(\"name\") String name, @QueryParam(\"repo\") String repoName,\n         @QueryParam(\"tag\") String tag, @QueryParam(\"force\") boolean force);\n\n   /**\n    * Return the history of the image with given {@code name}.\n    *\n    * @param name\n    *           the name of the image for which the history is retrieved\n    */\n   @Named(\"image:history\")\n   @GET\n   @Path(\"/images/{name}/history\")\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   List<ImageHistory> getHistory(@PathParam(\"name\") String name);\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/features/MiscApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.features;\n\nimport java.io.InputStream;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.docker.domain.Exec;\nimport org.jclouds.docker.domain.ExecCreateParams;\nimport org.jclouds.docker.domain.ExecInspect;\nimport org.jclouds.docker.domain.ExecStartParams;\nimport org.jclouds.docker.domain.Info;\nimport org.jclouds.docker.domain.Version;\nimport org.jclouds.docker.options.BuildOptions;\nimport org.jclouds.docker.util.DockerInputStream;\nimport org.jclouds.io.Payload;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Headers;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\n@Consumes(MediaType.APPLICATION_JSON)\n@Path(\"/v{jclouds.api-version}\")\npublic interface MiscApi {\n\n   /**\n    * Get the information of the current docker version.\n    *\n    * @return The information of the current docker version.\n    */\n   @Named(\"version\")\n   @GET\n   @Path(\"/version\")\n   Version getVersion();\n\n   /**\n    * Get the information of the current docker version.\n    *\n    * @return The information of the current docker version.\n    */\n   @Named(\"info\")\n   @GET\n   @Path(\"/info\")\n   Info getInfo();\n\n   /**\n    * Build an image from Dockerfile via stdin\n    *\n    * @param inputStream The stream must be a tar archive compressed with one of the following algorithms: identity\n    *                    (no compression), gzip, bzip2, xz.\n    * @return a stream of the build execution\n    */\n   @Named(\"image:build\")\n   @POST\n   @Path(\"/build\")\n   @Headers(keys = { \"Content-Type\", \"Connection\" }, values = { \"application/tar\", \"close\" })\n   InputStream build(Payload inputStream);\n\n   /**\n    * Build an image from Dockerfile via stdin\n    *\n    * @param inputStream The stream must be a tar archive compressed with one of the following algorithms: identity\n    *                    (no compression), gzip, bzip2, xz.\n    * @param options the image build's options (@see BuildOptions)\n    * @return a stream of the build execution\n    */\n   @Named(\"image:build\")\n   @POST\n   @Path(\"/build\")\n   @Headers(keys = { \"Content-Type\", \"Connection\" }, values = { \"application/tar\", \"close\" })\n   InputStream build(Payload inputStream, BuildOptions options);\n\n   /**\n    * Sets up an exec instance in a running container with given Id.\n    *\n    * @param containerId\n    *           container Id\n    * @param execCreateParams\n    *           exec parameters\n    * @return an instance which holds exec identifier\n    */\n   @Named(\"container:exec\")\n   @POST\n   @Path(\"/containers/{id}/exec\")\n   Exec execCreate(@PathParam(\"id\") String containerId,\n         @BinderParam(BindToJsonPayload.class) ExecCreateParams execCreateParams);\n\n   /**\n    * Starts a previously set up exec instance id. If\n    * {@link ExecStartParams#detach()} is true, this API returns after starting\n    * the exec command. Otherwise, this API sets up an interactive session with\n    * the exec command.\n    *\n    * @param execId\n    *           exec instance id\n    * @param execStartParams\n    *           start parameters\n    * @return raw docker stream which can be wrapped to\n    *         {@link DockerInputStream}\n    * @see #execCreate(String, ExecCreateParams)\n    * @see DockerInputStream\n    */\n   @Named(\"exec:start\")\n   @POST\n   @Path(\"/exec/{id}/start\")\n   InputStream execStart(@PathParam(\"id\") String execId,\n         @BinderParam(BindToJsonPayload.class) ExecStartParams execStartParams);\n\n   /**\n    * Returns low-level information about the exec command id.\n    * \n    * @param execId\n    *           exec instance id\n    * @return details about exec instance\n    */\n   @Named(\"exec:inspect\")\n   @GET\n   @Path(\"/exec/{id}/json\")\n   ExecInspect execInspect(@PathParam(\"id\") String execId);\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/features/NetworkApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.features;\n\nimport java.util.List;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyListOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.docker.domain.Network;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.Headers;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\n@Consumes(MediaType.APPLICATION_JSON)\n@Path(\"/v{jclouds.api-version}/networks\")\npublic interface NetworkApi {\n\n   /**\n    * @return a set of networks\n    */\n   @Named(\"networks:list\")\n   @GET\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   List<Network> listNetworks();\n\n   /**\n    * @param network the network’s configuration (@see BindToJsonPayload)\n    * @return a new network\n    */\n   @Named(\"network:create\")\n   @POST\n   @Path(\"/create\")\n   Network createNetwork(@BinderParam(BindToJsonPayload.class) Network network);\n\n   /**\n    * Return low-level information on the network id\n    * @param networkIdOrName  The id or name of the network to get.\n    * @return The details of the network or <code>null</code> if the network with the given id doesn't exist.\n    */\n   @Named(\"network:inspect\")\n   @GET\n   @Path(\"/{idOrName}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   Network inspectNetwork(@PathParam(\"idOrName\") String networkIdOrName);\n\n   /**\n    * @param networkIdOrName The id or name of the network to be removed.\n    */\n   @Named(\"network:delete\")\n   @DELETE\n   @Path(\"/{idOrName}\")\n   void removeNetwork(@PathParam(\"idOrName\") String networkIdOrName);\n\n   /**\n    * @param networkIdOrName The id or name of the network where the container will be attached.\n    */\n   @Named(\"network:connectContainer\")\n   @POST\n   @Path(\"/{idOrName}/connect\")\n   @Payload(\"%7B\\\"Container\\\":\\\"{containerIdOrName}\\\"%7D\")\n   @Headers(keys = \"Content-Type\", values = \"application/json\")\n   void connectContainerToNetwork(@PathParam(\"idOrName\") String networkIdOrName, @PayloadParam(\"containerIdOrName\") String containerIdOrName);\n\n   /**\n    * @param networkIdOrName The id or name of the network where the container was attached.\n    */\n   @Named(\"network:disconnectContainer\")\n   @POST\n   @Path(\"/{idOrName}/disconnect\")\n   @Payload(\"%7B\\\"Container\\\":\\\"{containerIdOrName}\\\"%7D\")\n   @Headers(keys = \"Content-Type\", values = \"application/json\")\n   void disconnectContainerFromNetwork(@PathParam(\"idOrName\") String networkIdOrName, @PayloadParam(\"containerIdOrName\") String containerIdOrName);\n\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/handlers/DockerErrorHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.handlers;\n\nimport static org.jclouds.util.Closeables2.closeQuietly;\n\nimport java.io.IOException;\n\nimport jakarta.annotation.Resource;\n\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.jclouds.util.Strings2;\n\nimport com.google.common.base.Throwables;\n\n/**\n * This will parse and set an appropriate exception on the command object.\n * <p/>\n * <p/>\n * Errors are returned with an appropriate HTTP status code, an X-Elastic- Error header specifying\n * the error type, and a text description in the HTTP body.\n */\npublic class DockerErrorHandler implements HttpErrorHandler {\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   public void handleError(HttpCommand command, HttpResponse response) {\n      // it is important to always read fully and close streams\n      String message = parseMessage(response);\n      Exception exception = message != null ? new HttpResponseException(command, response, message)\n              : new HttpResponseException(command, response);\n      try {\n         message = message != null ? message : String.format(\"%s -> %s\", command.getCurrentRequest().getRequestLine(),\n                 response.getStatusLine());\n         switch (response.getStatusCode()) {\n            case 400:\n               if ((command.getCurrentRequest().getEndpoint().getPath().endsWith(\"/info\"))\n                       || (message != null && message.indexOf(\"could not be found\") != -1))\n                  exception = new ResourceNotFoundException(message, exception);\n               else if (message != null && message.indexOf(\"currently in use\") != -1)\n                  exception = new IllegalStateException(message, exception);\n               else\n                  exception = new IllegalArgumentException(message, exception);\n               break;\n            case 401:\n               exception = new AuthorizationException(message, exception);\n               break;\n            case 402:\n               exception = new IllegalStateException(message, exception);\n               break;\n            case 404:\n               if (!command.getCurrentRequest().getMethod().equals(\"DELETE\")) {\n                  exception = new ResourceNotFoundException(message, exception);\n               }\n               break;\n            case 405:\n               exception = new IllegalArgumentException(message, exception);\n               break;\n            case 409:\n               exception = new IllegalStateException(message, exception);\n               break;\n         }\n      } finally {\n         closeQuietly(response.getPayload());\n         command.setException(exception);\n      }\n   }\n\n   public String parseMessage(HttpResponse response) {\n      if (response.getPayload() == null)\n         return null;\n      try {\n         return Strings2.toStringAndClose(response.getPayload().openStream());\n      } catch (IOException e) {\n         throw Throwables.propagate(e);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/internal/NullSafeCopies.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.internal;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\n\npublic class NullSafeCopies {\n\n   public static <K, V> Map<K, V> copyOf(@Nullable Map<K, V> map) {\n      return map != null ? ImmutableMap.copyOf(map) : ImmutableMap.<K, V> of();\n   }\n\n   public static <E> List<E> copyOf(@Nullable List<E> list) {\n      return list != null ? ImmutableList.copyOf(list) : ImmutableList.<E> of();\n   }\n\n   public static <E> List<E> copyOf(@Nullable Iterable<E> list) {\n      return list != null ? ImmutableList.copyOf(list) : ImmutableList.<E> of();\n   }\n\n   public static <E> List<E> copyOf(@Nullable E[] array) {\n      return array != null ? ImmutableList.copyOf(array) : ImmutableList.<E> of();\n   }\n\n   /**\n    * Copies given List with keeping null value if provided.\n    *\n    * @param list\n    *           instance to copy (maybe <code>null</code>)\n    * @return if the parameter is not-<code>null</code> then immutable copy;\n    *         <code>null</code> otherwise\n    */\n   public static <E> List<E> copyWithNullOf(@Nullable List<E> list) {\n      return list != null ? ImmutableList.copyOf(list) : null;\n   }\n\n   /**\n    * Copies given Map with keeping null value if provided.\n    *\n    * @param map\n    *           instance to copy (maybe <code>null</code>)\n    * @return if the parameter is not-<code>null</code> then immutable copy;\n    *         <code>null</code> otherwise\n    */\n   public static <K, V> Map<K, V> copyWithNullOf(@Nullable Map<K, V> map) {\n      return map != null ? ImmutableMap.copyOf(map) : null;\n   }\n\n   /**\n    * Copies given {@link Iterable} into immutable {@link List} with keeping null value if provided.\n    *\n    * @param iterable\n    *           instance to copy (maybe <code>null</code>)\n    * @return if the parameter is not-<code>null</code> then immutable copy;\n    *         <code>null</code> otherwise\n    */\n   public static <E> List<E> copyWithNullOf(@Nullable Iterable<E> iterable) {\n      return iterable != null ? ImmutableList.copyOf(iterable) : null;\n   }\n\n   /**\n    * Copies given array into immutable {@link List} with keeping null value if provided.\n    *\n    * @param array\n    *           instance to copy (maybe <code>null</code>)\n    * @return if the parameter is not-<code>null</code> then immutable copy;\n    *         <code>null</code> otherwise\n    */\n   public static <E> List<E> copyWithNullOf(@Nullable E[] array) {\n      return array != null ? ImmutableList.copyOf(array) : null;\n   }\n\n   private NullSafeCopies() {\n   }\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/options/AttachOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\npublic class AttachOptions extends BaseHttpRequestOptions {\n\n   /**\n    * @param stream When TTY is enabled, the stream is the raw data from the process PTY and client's stdin.\n    *               When TTY is disabled, the stream is multiplexed to separate stdout and stderr.\n    * @return AttachOptions\n    */\n   public AttachOptions stream(boolean stream) {\n      this.queryParameters.put(\"stream\", String.valueOf(stream));\n      return this;\n   }\n\n   /**\n    * @param logs require logs to be attached. Default false.\n    * @return AttachOptions\n    */\n   public AttachOptions logs(boolean logs) {\n      this.queryParameters.put(\"logs\", String.valueOf(logs));\n      return this;\n   }\n\n   /**\n    * @param stdin if stream=true, attach to stdin. Default false\n    * @return AttachOptions\n    */\n   public AttachOptions stdin(boolean stdin) {\n      this.queryParameters.put(\"stdin\", String.valueOf(stdin));\n      return this;\n   }\n\n   /**\n    * @param stdout if logs=true, return stdout log, if stream=true, attach to stdout. Default false\n    * @return\n    */\n   public AttachOptions stdout(boolean stdout) {\n      this.queryParameters.put(\"stdout\", String.valueOf(stdout));\n      return this;\n   }\n\n   /**\n    *\n    * @param stderr if logs=true, return stderr log, if stream=true, attach to stderr. Default false\n    * @return\n    */\n   public AttachOptions stderr(boolean stderr) {\n      this.queryParameters.put(\"stderr\", String.valueOf(stderr));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see org.jclouds.docker.options.AttachOptions#stream\n       */\n      public static AttachOptions stream(boolean stream) {\n         AttachOptions options = new AttachOptions();\n         return options.stream(stream);\n      }\n\n      /**\n       * @see org.jclouds.docker.options.AttachOptions#logs(Boolean)\n       */\n      public static AttachOptions logs(boolean logs) {\n         AttachOptions options = new AttachOptions();\n         return options.logs(logs);\n      }\n\n      /**\n       * @see org.jclouds.docker.options.AttachOptions#stdin(Boolean)\n       */\n      public static AttachOptions stdin(boolean stdin) {\n         AttachOptions options = new AttachOptions();\n         return options.stdin(stdin);\n      }\n\n      /**\n       * @see org.jclouds.docker.options.AttachOptions#stdout(Boolean)\n       */\n      public static AttachOptions stdout(boolean stdout) {\n         AttachOptions options = new AttachOptions();\n         return options.stdout(stdout);\n      }\n\n      /**\n       * @see org.jclouds.docker.options.AttachOptions#stderr(Boolean)\n       */\n      public static AttachOptions stderr(boolean stderr) {\n         AttachOptions options = new AttachOptions();\n         return options.stderr(stderr);\n      }\n\n   }\n\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/options/BuildOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\npublic class BuildOptions extends BaseHttpRequestOptions {\n\n   public BuildOptions tag(String tag) {\n      this.queryParameters.put(\"t\", tag);\n      return this;\n   }\n\n   public BuildOptions verbose(boolean verbose) {\n      this.queryParameters.put(\"verbose\", String.valueOf(verbose));\n      return this;\n   }\n\n   public BuildOptions nocache(boolean nocache) {\n      this.queryParameters.put(\"nocache\", String.valueOf(nocache));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see BuildOptions#tag\n       */\n      public static BuildOptions tag(String tag) {\n         BuildOptions options = new BuildOptions();\n         return options.tag(tag);\n      }\n\n      /**\n       * @see BuildOptions#verbose(Boolean)\n       */\n      public static BuildOptions verbose(boolean verbose) {\n         BuildOptions options = new BuildOptions();\n         return options.verbose(verbose);\n      }\n\n      /**\n       * @see BuildOptions#nocache(Boolean)\n       */\n      public static BuildOptions nocache(boolean nocache) {\n         BuildOptions options = new BuildOptions();\n         return options.nocache(nocache);\n      }\n\n   }\n\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/options/CommitOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\npublic class CommitOptions extends BaseHttpRequestOptions {\n\n   public CommitOptions containerId(String containerId) {\n      this.queryParameters.put(\"containerId\", containerId);\n      return this;\n   }\n\n   public CommitOptions repository(String repository) {\n      this.queryParameters.put(\"repository\", repository);\n      return this;\n   }\n\n   public CommitOptions tag(String tag) {\n      this.queryParameters.put(\"tag\", tag);\n      return this;\n   }\n\n   public CommitOptions message(String message) {\n      this.queryParameters.put(\"message\", message);\n      return this;\n   }\n\n   public CommitOptions author(String author) {\n      this.queryParameters.put(\"author\", author);\n      return this;\n   }\n\n   public CommitOptions run(String run) {\n      this.queryParameters.put(\"run\", run);\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see CommitOptions#containerId\n       */\n      public static CommitOptions containerId(String containerId) {\n         CommitOptions options = new CommitOptions();\n         return options.containerId(containerId);\n      }\n\n      /**\n       * @see CommitOptions#repository\n       */\n      public static CommitOptions repository(String repository) {\n         CommitOptions options = new CommitOptions();\n         return options.repository(repository);\n      }\n\n      /**\n       * @see CommitOptions#tag\n       */\n      public static CommitOptions tag(String tag) {\n         CommitOptions options = new CommitOptions();\n         return options.tag(tag);\n      }\n\n      /**\n       * @see CommitOptions#message\n       */\n      public static CommitOptions message(String message) {\n         CommitOptions options = new CommitOptions();\n         return options.message(message);\n      }\n\n      /**\n       * @see CommitOptions#author\n       */\n      public static CommitOptions author(String author) {\n         CommitOptions options = new CommitOptions();\n         return options.author(author);\n      }\n\n      /**\n       * @see CommitOptions#run\n       */\n      public static CommitOptions run(String run) {\n         CommitOptions options = new CommitOptions();\n         return options.run(run);\n      }\n\n   }\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/options/CreateImageOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\npublic class CreateImageOptions extends BaseHttpRequestOptions {\n\n   public CreateImageOptions fromImage(String fromImage) {\n      this.queryParameters.put(\"fromImage\", fromImage);\n      return this;\n   }\n\n   public CreateImageOptions fromSrc(String fromSrc) {\n      this.queryParameters.put(\"fromSrc\", fromSrc);\n      return this;\n   }\n\n   public CreateImageOptions repo(String repo) {\n      this.queryParameters.put(\"repo\", repo);\n      return this;\n   }\n\n   public CreateImageOptions tag(String tag) {\n      this.queryParameters.put(\"tag\", tag);\n      return this;\n   }\n\n   public CreateImageOptions registry(String registry) {\n      this.queryParameters.put(\"registry\", registry);\n      return this;\n   }\n\n   public static class Builder {\n      /**\n       * @see CreateImageOptions#fromImage\n       */\n      public static CreateImageOptions fromImage(String fromImage) {\n         CreateImageOptions options = new CreateImageOptions();\n         return options.fromImage(fromImage);\n      }\n\n      /**\n       * @see CreateImageOptions#fromSrc\n       */\n      public static CreateImageOptions fromSrc(String fromSrc) {\n         CreateImageOptions options = new CreateImageOptions();\n         return options.fromSrc(fromSrc);\n      }\n\n      /**\n       * @see CreateImageOptions#repo\n       */\n      public static CreateImageOptions repo(String repo) {\n         CreateImageOptions options = new CreateImageOptions();\n         return options.repo(repo);\n      }\n\n      /**\n       * @see CreateImageOptions#tag\n       */\n      public static CreateImageOptions tag(String tag) {\n         CreateImageOptions options = new CreateImageOptions();\n         return options.tag(tag);\n      }\n\n      /**\n       * @see CreateImageOptions#registry\n       */\n      public static CreateImageOptions registry(String registry) {\n         CreateImageOptions options = new CreateImageOptions();\n         return options.registry(registry);\n      }\n\n   }\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/options/DeleteImageOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\npublic class DeleteImageOptions extends BaseHttpRequestOptions {\n\n   public DeleteImageOptions force(boolean force) {\n      this.queryParameters.put(\"force\", String.valueOf(force));\n      return this;\n   }\n\n   public DeleteImageOptions noPrune(boolean noPrune) {\n      this.queryParameters.put(\"noPrune\", String.valueOf(noPrune));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see DeleteImageOptions#force\n       */\n      public static DeleteImageOptions force(boolean force) {\n         DeleteImageOptions options = new DeleteImageOptions();\n         return options.force(force);\n      }\n\n      /**\n       * @see DeleteImageOptions#noPrune\n       */\n      public static DeleteImageOptions noPrune(boolean noPrune) {\n         DeleteImageOptions options = new DeleteImageOptions();\n         return options.noPrune(noPrune);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/options/ListContainerOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\npublic class ListContainerOptions extends BaseHttpRequestOptions {\n\n   public ListContainerOptions all(boolean all) {\n      this.queryParameters.put(\"all\", String.valueOf(all));\n      return this;\n   }\n\n   public ListContainerOptions limit(Integer limit) {\n      this.queryParameters.put(\"limit\", limit.toString());\n      return this;\n   }\n\n   public ListContainerOptions since(Integer since) {\n      this.queryParameters.put(\"since\", since.toString());\n      return this;\n   }\n\n   public ListContainerOptions before(Integer before) {\n      this.queryParameters.put(\"before\", before.toString());\n      return this;\n   }\n\n   public ListContainerOptions size(Integer size) {\n      this.queryParameters.put(\"size\", size.toString());\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see ListContainerOptions#all\n       */\n      public static ListContainerOptions all(boolean all) {\n         ListContainerOptions options = new ListContainerOptions();\n         return options.all(all);\n      }\n\n      /**\n       * @see ListContainerOptions#limit(Integer)\n       */\n      public static ListContainerOptions limit(Integer limit) {\n         ListContainerOptions options = new ListContainerOptions();\n         return options.limit(limit);\n      }\n\n      /**\n       * @see ListContainerOptions#since(Integer)\n       */\n      public static ListContainerOptions since(Integer since) {\n         ListContainerOptions options = new ListContainerOptions();\n         return options.since(since);\n      }\n\n      /**\n       * @see ListContainerOptions#before(Integer)\n       */\n      public static ListContainerOptions before(Integer before) {\n         ListContainerOptions options = new ListContainerOptions();\n         return options.before(before);\n      }\n\n      /**\n       * @see ListContainerOptions#limit(Integer)\n       */\n      public static ListContainerOptions size(Integer size) {\n         ListContainerOptions options = new ListContainerOptions();\n         return options.size(size);\n      }\n\n   }\n\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/options/ListImageOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\npublic class ListImageOptions extends BaseHttpRequestOptions {\n\n   public ListImageOptions all(boolean all) {\n      this.queryParameters.put(\"all\", String.valueOf(all));\n      return this;\n   }\n\n   public static class Builder {\n      /**\n       * @see ListImageOptions#all\n       */\n      public static ListImageOptions all(boolean all) {\n         ListImageOptions options = new ListImageOptions();\n         return options.all(all);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/options/RemoveContainerOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\npublic class RemoveContainerOptions extends BaseHttpRequestOptions {\n\n   public RemoveContainerOptions verbose(boolean verbose) {\n      this.queryParameters.put(\"verbose\", String.valueOf(verbose));\n      return this;\n   }\n\n   public RemoveContainerOptions force(boolean force) {\n      this.queryParameters.put(\"force\", String.valueOf(force));\n      return this;\n   }\n   \n   /**\n    * Remove the volumes associated to the container\n    * \n    * @param volume If set to true the volume associated to the container will be removed. \n    * Otherwise it will not be removed.\n    */\n   public RemoveContainerOptions volume(boolean volume) {\n       this.queryParameters.put(\"v\", String.valueOf(volume));\n       return this;\n    }\n\n   public static class Builder {\n      /**\n       * @see RemoveContainerOptions#verbose\n       */\n      public static RemoveContainerOptions verbose(boolean verbose) {\n         RemoveContainerOptions options = new RemoveContainerOptions();\n         return options.verbose(verbose);\n      }\n\n      /**\n       * @see RemoveContainerOptions#force\n       */\n      public static RemoveContainerOptions force(boolean force) {\n         RemoveContainerOptions options = new RemoveContainerOptions();\n         return options.force(force);\n      }\n      \n      /**\n       * @see RemoveContainerOptions#volume\n       */\n      public static RemoveContainerOptions volume(boolean volume) {\n         RemoveContainerOptions options = new RemoveContainerOptions();\n         return options.volume(volume);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/suppliers/DockerSSLContextSupplier.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.suppliers;\n\nimport com.google.common.base.Strings;\nimport com.google.common.base.Supplier;\n\nimport org.jclouds.docker.DockerApiMetadata;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.location.Provider;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\nimport javax.net.ssl.SSLContext;\n\nimport java.io.IOException;\nimport java.security.GeneralSecurityException;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Throwables.propagate;\nimport static org.jclouds.docker.suppliers.SSLContextBuilder.isClientKeyAndCertificateData;\n\n@Singleton\npublic class DockerSSLContextSupplier implements Supplier<SSLContext> {\n   private final Supplier<Credentials> creds;\n   private final String caCertPath;\n   private final String caCertData;\n\n   @Inject\n   DockerSSLContextSupplier(@Provider Supplier<Credentials> creds, @Named(DockerApiMetadata.DOCKER_CA_CERT_PATH) String caCertPath, @Named(DockerApiMetadata.DOCKER_CA_CERT_DATA) String caCertData) {\n      this.creds = creds;\n      this.caCertPath = caCertPath;\n      this.caCertData = caCertData;\n   }\n\n   @Override\n   public SSLContext get() {\n      Credentials currentCreds = checkNotNull(creds.get(), \"credential supplier returned null\");\n      try {\n         SSLContextBuilder builder = new SSLContextBuilder();\n         if (isClientKeyAndCertificateData(currentCreds.credential, currentCreds.identity)) {\n             builder.clientKeyAndCertificateData(currentCreds.credential, currentCreds.identity);\n         } else {\n             builder.clientKeyAndCertificatePaths(currentCreds.credential, currentCreds.identity);\n         }\n         if (!Strings.isNullOrEmpty(caCertPath)) {\n            builder.caCertificatePath(caCertPath);\n         } else if (!Strings.isNullOrEmpty(caCertData)) {\n            builder.caCertificateData(caCertData);\n         }\n         return builder.build();\n      } catch (GeneralSecurityException e) {\n         throw propagate(e);\n      } catch (IOException e) {\n         throw propagate(e);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/suppliers/DockerUntrustedSSLContextSupplier.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.suppliers;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.Supplier;\n\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.config.SSLModule;\nimport org.jclouds.location.Provider;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\nimport javax.net.ssl.SSLContext;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.security.GeneralSecurityException;\n\nimport static com.google.common.base.Throwables.propagate;\nimport static org.jclouds.docker.suppliers.SSLContextBuilder.isClientKeyAndCertificateData;\n\n@Singleton\npublic class DockerUntrustedSSLContextSupplier implements Supplier<SSLContext> {\n   private final Supplier<Credentials> creds;\n   private final SSLModule.TrustAllCerts insecureTrustManager;\n\n   @Inject\n   DockerUntrustedSSLContextSupplier(@Provider Supplier<Credentials> creds,\n         SSLModule.TrustAllCerts insecureTrustManager) {\n      this.creds = creds;\n      this.insecureTrustManager = insecureTrustManager;\n   }\n\n   @Override\n   public SSLContext get() {\n      Credentials currentCreds = checkNotNull(creds.get(), \"credential supplier returned null\");\n      try {\n         SSLContextBuilder builder = new SSLContextBuilder();\n         if (isClientKeyAndCertificateData(currentCreds.credential, currentCreds.identity)) {\n            builder.clientKeyAndCertificateData(currentCreds.credential, currentCreds.identity);\n         } else if (new File(currentCreds.identity).isFile() && new File(currentCreds.credential).isFile()) {\n            builder.clientKeyAndCertificatePaths(currentCreds.credential, currentCreds.identity);\n         }\n         builder.trustManager(insecureTrustManager);\n         return builder.build();\n      } catch (GeneralSecurityException e) {\n         throw propagate(e);\n      } catch (IOException e) {\n         throw propagate(e);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/suppliers/SSLContextBuilder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.suppliers;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.io.Files;\n\nimport org.bouncycastle.jce.provider.BouncyCastleProvider;\nimport org.bouncycastle.openssl.PEMKeyPair;\nimport org.bouncycastle.openssl.PEMParser;\nimport org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;\n\nimport org.jclouds.crypto.Pems;\nimport org.jclouds.util.Closeables2;\n\nimport javax.net.ssl.KeyManager;\nimport javax.net.ssl.SSLContext;\nimport javax.net.ssl.TrustManager;\nimport javax.net.ssl.TrustManagerFactory;\nimport javax.net.ssl.X509ExtendedKeyManager;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.StringReader;\nimport java.net.Socket;\nimport java.security.GeneralSecurityException;\nimport java.security.KeyManagementException;\nimport java.security.KeyPair;\nimport java.security.KeyStore;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.Principal;\nimport java.security.PrivateKey;\nimport java.security.SecureRandom;\nimport java.security.Security;\nimport java.security.cert.CertificateException;\nimport java.security.cert.CertificateFactory;\nimport java.security.cert.X509Certificate;\n\nimport static com.google.common.base.Throwables.propagate;\n\npublic class SSLContextBuilder {\n\n    private KeyManager[] keyManagers;\n    private TrustManager[] trustManagers;\n\n    public static final boolean isClientKeyAndCertificateData(String key, String cert) {\n        return (key.startsWith(Pems.PRIVATE_PKCS1_MARKER) || key.startsWith(Pems.PRIVATE_PKCS8_MARKER)) &&\n                cert.startsWith(Pems.CERTIFICATE_X509_MARKER);\n    }\n\n    public SSLContextBuilder() { }\n\n    public SSLContextBuilder clientKeyAndCertificatePaths(String keyPath, String certPath) throws IOException, CertificateException {\n        X509Certificate certificate = getCertificate(loadFile(certPath));\n        PrivateKey privateKey = getKey(loadFile(keyPath));\n        keyManager(new InMemoryKeyManager(certificate, privateKey));\n        return this;\n    }\n\n    public SSLContextBuilder clientKeyAndCertificateData(String keyData, String certData) throws CertificateException {\n        X509Certificate certificate = getCertificate(certData);\n        PrivateKey privateKey = getKey(keyData);\n        keyManager(new InMemoryKeyManager(certificate, privateKey));\n        return this;\n    }\n\n    public SSLContextBuilder caCertificatePath(String caCertPath) {\n        try {\n            trustManagers = getTrustManagerWithCaCert(loadFile(caCertPath));\n        } catch (IOException e) {\n            throw propagate(e);\n        }\n        return this;\n    }\n\n    public SSLContextBuilder caCertificateData(String caCertPath) {\n        trustManagers = getTrustManagerWithCaCert(caCertPath);\n        return this;\n    }\n\n    public SSLContextBuilder keyManager(KeyManager keyManager) {\n        keyManagers = new KeyManager[] { keyManager };\n        return this;\n    }\n\n    public SSLContextBuilder trustManager(TrustManager trustManager) {\n        trustManagers = new TrustManager[] { trustManager };\n        return this;\n    }\n\n    public SSLContext build() throws NoSuchAlgorithmException, KeyManagementException {\n        SSLContext sslContext = SSLContext.getInstance(\"TLS\");\n        sslContext.init(keyManagers, trustManagers, new SecureRandom());\n        return sslContext;\n    }\n\n    private TrustManager[] getTrustManagerWithCaCert(String caCertData) {\n        try {\n            X509Certificate caCert = getCertificate(caCertData);\n            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());\n            trustStore.load(null, null);\n            trustStore.setCertificateEntry(\"ca\", caCert);\n            TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());\n            tmf.init(trustStore);\n            return tmf.getTrustManagers();\n        } catch (GeneralSecurityException e) {\n            throw propagate(e);\n        } catch (IOException e) {\n            throw propagate(e);\n        }\n    }\n\n    private static X509Certificate getCertificate(String certificate) {\n        try {\n            return (X509Certificate) CertificateFactory.getInstance(\"X.509\").generateCertificate(\n                    new ByteArrayInputStream(certificate.getBytes(Charsets.UTF_8)));\n        } catch (CertificateException ex) {\n            throw new RuntimeException(\"Invalid certificate\", ex);\n        }\n    }\n\n    private static PrivateKey getKey(String privateKey) {\n        PEMParser pemParser = new PEMParser(new StringReader(privateKey));\n        try {\n            Object object = pemParser.readObject();\n            if (Security.getProvider(\"BC\") == null) {\n                Security.addProvider(new BouncyCastleProvider());\n            }\n            JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider(\"BC\");\n            KeyPair keyPair = converter.getKeyPair((PEMKeyPair) object);\n            return keyPair.getPrivate();\n        } catch (IOException ex) {\n            throw new RuntimeException(\"Invalid private key\", ex);\n        } finally {\n            Closeables2.closeQuietly(pemParser);\n        }\n    }\n\n    private static String loadFile(final String filePath) throws IOException {\n        return Files.toString(new File(filePath), Charsets.UTF_8);\n    }\n\n    private static class InMemoryKeyManager extends X509ExtendedKeyManager {\n        private static final String DEFAULT_ALIAS = \"docker\";\n\n        private final X509Certificate certificate;\n\n        private final PrivateKey privateKey;\n\n        public InMemoryKeyManager(final X509Certificate certificate, final PrivateKey privateKey) throws CertificateException {\n            this.certificate = certificate;\n            this.privateKey = privateKey;\n        }\n\n        @Override\n        public String chooseClientAlias(final String[] keyType, final Principal[] issuers, final Socket socket) {\n            return DEFAULT_ALIAS;\n        }\n\n        @Override\n        public String chooseServerAlias(final String keyType, final Principal[] issuers, final Socket socket) {\n            return DEFAULT_ALIAS;\n        }\n\n        @Override\n        public X509Certificate[] getCertificateChain(final String alias) {\n            return new X509Certificate[] { certificate };\n        }\n\n        @Override\n        public String[] getClientAliases(final String keyType, final Principal[] issuers) {\n            return new String[] { DEFAULT_ALIAS };\n        }\n\n        @Override\n        public PrivateKey getPrivateKey(final String alias) {\n            return privateKey;\n        }\n\n        @Override\n        public String[] getServerAliases(final String keyType, final Principal[] issuers) {\n            return new String[] { DEFAULT_ALIAS };\n        }\n    }\n\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/util/DockerInputStream.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.docker.util;\n\nimport java.io.DataInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\n\n/**\n * Extension to {@link DataInputStream} which adds method\n * {@link #readStdStreamData()} to allow read multiplexed standard streams.\n */\npublic final class DockerInputStream extends DataInputStream {\n\n   /**\n    * Ctor from superclass.\n    *\n    * @param in\n    * @see DataInputStream#DataInputStream(InputStream)\n    */\n   public DockerInputStream(InputStream in) {\n      super(in);\n   }\n\n   /**\n    * @return {@link StdStreamData} instance read from the input stream or\n    *         <code>null</code> if we reached end of the stream.\n    * @throws IOException\n    */\n   public StdStreamData readStdStreamData() throws IOException {\n      byte[] header = new byte[8];\n      // try to read first byte from the message header - just to check if we\n      // are at the end\n      // of stream\n      if (-1 == read(header, 0, 1)) {\n         return null;\n      }\n      // read the rest of the header\n      readFully(header, 1, 7);\n      // decode size as an unsigned int\n      long size = (long) (header[4] & 0xFF) << 24 | (header[5] & 0xFF) << 16 | (header[6] & 0xFF) << 8\n            | (header[7] & 0xFF);\n\n      byte[] payload;\n      // The size from the header is an unsigned int so it can happen the byte\n      // array has not a sufficient size and we'll have to truncate the frame\n      payload = new byte[(int) Math.min(Integer.MAX_VALUE, size)];\n      readFully(payload);\n      boolean truncated = false;\n      if (size > Integer.MAX_VALUE) {\n         truncated = true;\n         // skip the rest\n         readFully(new byte[(int) (size - Integer.MAX_VALUE)]);\n      }\n      return new StdStreamData(header[0], payload, truncated);\n   }\n\n}\n"
  },
  {
    "path": "apis/docker/src/main/java/org/jclouds/docker/util/StdStreamData.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.docker.util;\n\nimport java.util.Arrays;\n\n/**\n * Representation of single message from docker-raw-stream. It holds stream\n * type, data (payload) and flag which says if the payload was truncated. The\n * truncation can occur when the frame size is greater than\n * {@link Integer#MAX_VALUE}.\n */\npublic final class StdStreamData {\n\n   private final StdStreamType type;\n   private final byte[] payload;\n   private final boolean truncated;\n\n   /**\n    * Ctor.\n    *\n    * @param streamTypeId\n    *           standard stream type (0=stdIn, 1=stdOut, 2=stdErr)\n    * @param payload\n    *           message data - must not be <code>null</code>\n    * @param truncated\n    * @throws ArrayIndexOutOfBoundsException\n    *            if streamTypeId is not an index in {@link StdStreamType} enum.\n    * @throws NullPointerException\n    *            if provided payload is <code>null</code>\n    */\n   StdStreamData(byte streamTypeId, byte[] payload, boolean truncated)\n         throws ArrayIndexOutOfBoundsException, NullPointerException {\n      this.type = StdStreamType.values()[streamTypeId];\n      this.payload = Arrays.copyOf(payload, payload.length);\n      this.truncated = truncated;\n   }\n\n   /**\n    * Type of stream.\n    *\n    * @return\n    */\n   public StdStreamType getType() {\n      return type;\n   }\n\n   /**\n    * Data from this message.\n    *\n    * @return payload.\n    */\n   public byte[] getPayload() {\n      return payload;\n   }\n\n   /**\n    * Flag which says if the payload was truncated (because of size).\n    *\n    * @return true if truncated\n    */\n   public boolean isTruncated() {\n      return truncated;\n   }\n\n   /**\n    * Standard streams enum. The order of entries is important!\n    */\n   public static enum StdStreamType {\n      IN, OUT, ERR;\n   }\n}\n"
  },
  {
    "path": "apis/docker/src/test/java/org/jclouds/docker/DockerApiMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.apis.Apis;\nimport org.jclouds.compute.internal.BaseComputeServiceApiMetadataTest;\nimport org.testng.annotations.Test;\n\n/**\n * Unit tests for the {@link DockerApiMetadata} class.\n */\n@Test(groups = \"unit\", testName = \"AbiquoApiMetadataTest\")\npublic class DockerApiMetadataTest extends BaseComputeServiceApiMetadataTest {\n\n   public DockerApiMetadataTest() {\n      super(new DockerApiMetadata());\n   }\n\n   public void testDockerApiRegistered() {\n      ApiMetadata api = Apis.withId(\"docker\");\n\n      assertNotNull(api);\n      assertTrue(api instanceof DockerApiMetadata);\n      assertEquals(api.getId(), \"docker\");\n   }\n\n}\n\n"
  },
  {
    "path": "apis/docker/src/test/java/org/jclouds/docker/compute/BaseDockerApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.compute;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static org.jclouds.util.Closeables2.closeQuietly;\n\nimport java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.util.Properties;\n\nimport org.jboss.shrinkwrap.api.GenericArchive;\nimport org.jboss.shrinkwrap.api.ShrinkWrap;\nimport org.jboss.shrinkwrap.api.asset.ClassLoaderAsset;\nimport org.jboss.shrinkwrap.api.exporter.TarExporter;\nimport org.jclouds.Constants;\nimport org.jclouds.apis.BaseApiLiveTest;\nimport org.jclouds.compute.config.ComputeServiceProperties;\nimport org.jclouds.docker.DockerApi;\nimport org.jclouds.docker.internal.DockerTestUtils;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.sshj.config.SshjSshClientModule;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.io.CharStreams;\nimport com.google.inject.Module;\n\n@Test(groups = \"live\")\npublic class BaseDockerApiLiveTest extends BaseApiLiveTest<DockerApi> {\n\n   protected static final String DEFAULT_IMAGE = \"alpine\";\n   protected static final String DEFAULT_TAG = \"3.3\";\n   protected static final String ALPINE_IMAGE_TAG = String.format(\"%s:%s\", DEFAULT_IMAGE, DEFAULT_TAG);\n\n\n   public BaseDockerApiLiveTest() {\n      provider = \"docker\";\n   }\n\n   /**\n    * Removes Docker image if it's present on the Docker host.\n    *\n    * @param imageName\n    *           image to be deleted (must be not-<code>null</code>)\n    * @see DockerTestUtils#removeImageIfExists(DockerApi, String)\n    */\n   protected void removeImageIfExists(String imageName) {\n      DockerTestUtils.removeImageIfExists(api, imageName);\n   }\n\n   @Override\n   protected Iterable<Module> setupModules() {\n      return ImmutableSet.<Module>of(getLoggingModule(), new SshjSshClientModule());\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties overrides = super.setupProperties();\n      overrides.setProperty(ComputeServiceProperties.IMAGE_LOGIN_USER, \"root:password\");\n      setIfTestSystemPropertyPresent(overrides,  provider + \".cacert.path\");\n      setIfTestSystemPropertyPresent(overrides, Constants.PROPERTY_TRUST_ALL_CERTS);\n      return overrides;\n   }\n\n   protected String consumeStream(InputStream stream) {\n      try {\n         return CharStreams.toString(new InputStreamReader(stream, UTF_8));\n      } catch (IOException e) {\n         throw new AssertionError(e);\n      } finally {\n         closeQuietly(stream);\n      }\n   }\n\n   public static Payload tarredDockerfile() throws IOException {\n      ByteArrayOutputStream bytes = new ByteArrayOutputStream();\n      ShrinkWrap.create(GenericArchive.class, \"archive.tar\")\n            .add(new ClassLoaderAsset(\"Dockerfile\"), \"Dockerfile\")\n            .as(TarExporter.class).exportTo(bytes);\n\n      return Payloads.newByteArrayPayload(bytes.toByteArray());\n   }\n}\n"
  },
  {
    "path": "apis/docker/src/test/java/org/jclouds/docker/compute/DockerComputeServiceAdapterLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.compute;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\n\nimport java.util.Properties;\nimport java.util.Random;\n\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.inject.Injector;\nimport com.google.inject.Module;\n\nimport org.jclouds.compute.ComputeServiceAdapter.NodeAndInitialCredentials;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.domain.TemplateBuilder;\nimport org.jclouds.docker.DockerApi;\nimport org.jclouds.docker.compute.options.DockerTemplateOptions;\nimport org.jclouds.docker.compute.strategy.DockerComputeServiceAdapter;\nimport org.jclouds.docker.domain.Container;\nimport org.jclouds.docker.domain.Image;\nimport org.jclouds.docker.domain.Network;\nimport org.jclouds.docker.features.NetworkApi;\nimport org.jclouds.sshj.config.SshjSshClientModule;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"DockerComputeServiceAdapterLiveTest\")\npublic class DockerComputeServiceAdapterLiveTest extends BaseDockerApiLiveTest {\n\n   private static final String SSHABLE_IMAGE = \"kwart/alpine-ext\";\n   private static final String SSHABLE_IMAGE_TAG = \"3.3-ssh\";\n   private Image defaultImage;\n   private Network network1;\n   private Network network2;\n\n   private DockerComputeServiceAdapter adapter;\n   private TemplateBuilder templateBuilder;\n   private NodeAndInitialCredentials<Container> guest;\n   private static final String CHUANWEN_COWSAY = \"chuanwen/cowsay\";\n\n   @BeforeClass\n   protected void init() {\n      super.initialize();\n      String imageName = SSHABLE_IMAGE + \":\" + SSHABLE_IMAGE_TAG;\n      defaultImage = adapter.getImage(imageName);\n      network1 = createAndInspectNetwork(\"network1\");\n      network2 = createAndInspectNetwork(\"network2\");\n      assertNotNull(defaultImage);\n   }\n\n   @AfterClass(alwaysRun = true)\n   protected void tearDown() {\n      if (guest != null) {\n         adapter.destroyNode(guest.getNode().id() + \"\");\n      }\n      if (api.getImageApi().inspectImage(CHUANWEN_COWSAY) != null) {\n         api.getImageApi().deleteImage(CHUANWEN_COWSAY);\n      }\n      if (api.getNetworkApi().inspectNetwork(\"network1\") != null) {\n         api.getNetworkApi().removeNetwork(\"network1\");\n      }\n      if (api.getNetworkApi().inspectNetwork(\"network2\") != null) {\n         api.getNetworkApi().removeNetwork(\"network2\");\n      }\n      super.tearDown();\n   }\n\n   @Override\n   protected DockerApi create(Properties props, Iterable<Module> modules) {\n      Injector injector = newBuilder().modules(modules).overrides(props).buildInjector();\n      adapter = injector.getInstance(DockerComputeServiceAdapter.class);\n      templateBuilder = injector.getInstance(TemplateBuilder.class);\n      return injector.getInstance(DockerApi.class);\n   }\n\n   public void testCreateNodeWithGroupEncodedIntoNameThenStoreCredentials() {\n      String name = \"container\" + new Random().nextInt();\n      Template template = templateBuilder.imageId(defaultImage.id()).build();\n      DockerTemplateOptions options = template.getOptions().as(DockerTemplateOptions.class);\n      options.env(ImmutableList.of(\"ROOT_PASSWORD=password\"));\n      guest = adapter.createNodeWithGroupEncodedIntoName(\"test\", name, template);\n      assertEquals(guest.getNodeId(), guest.getNode().id());\n   }\n\n   public void testListHardwareProfiles() {\n      Iterable<Hardware> profiles = adapter.listHardwareProfiles();\n      assertFalse(Iterables.isEmpty(profiles));\n\n      for (Hardware profile : profiles) {\n         assertNotNull(profile);\n      }\n   }\n\n   public void testGetImageNotHiddenByCache() {\n      // Ensure image to be tested is unknown to jclouds and docker and that\n      // cache is warm\n      assertNull(findImageFromListImages(CHUANWEN_COWSAY));\n      assertNull(api.getImageApi().inspectImage(CHUANWEN_COWSAY));\n\n      // Get new image\n      adapter.getImage(CHUANWEN_COWSAY);\n\n      assertNotNull(findImageFromListImages(CHUANWEN_COWSAY),\n            \"New image is not available from listImages presumably due to caching\");\n   }\n\n   public void testCreateNodeWithMultipleNetworks() {\n      String name = \"container\" + new Random().nextInt();\n      Template template = templateBuilder.imageId(defaultImage.id()).build();\n      DockerTemplateOptions options = template.getOptions().as(DockerTemplateOptions.class);\n      options.env(ImmutableList.of(\"ROOT_PASSWORD=password\"));\n      options.networkMode(\"bridge\");\n      options.networks(network1.name(), network2.name());\n      guest = adapter.createNodeWithGroupEncodedIntoName(\"test\", name, template);\n\n      assertTrue(guest.getNode().networkSettings().networks().containsKey(\"network1\"));\n      assertTrue(guest.getNode().networkSettings().networks().containsKey(\"network2\"));\n      assertEquals(guest.getNode().networkSettings().networks().size(), 3);\n   }\n\n   private Image findImageFromListImages(final String image) {\n      return Iterables.find(adapter.listImages(), new Predicate<Image>() {\n         @Override\n         public boolean apply(Image input) {\n            for (String tag : input.repoTags()) {\n               if (tag.equals(CHUANWEN_COWSAY + DockerComputeServiceAdapter.SUFFIX_LATEST_VERSION)\n                     || tag.equals(DockerComputeServiceAdapter.PREFIX_DOCKER_HUB_HOST + CHUANWEN_COWSAY\n                           + DockerComputeServiceAdapter.SUFFIX_LATEST_VERSION)) {\n                  return true;\n               }\n            }\n            return false;\n         }\n      }, null);\n   }\n\n   @Override\n   protected Iterable<Module> setupModules() {\n      return ImmutableSet.<Module> of(getLoggingModule(), new SshjSshClientModule());\n   }\n\n   /**\n    * Creates network (driver=\"bridge\") with given name and then inspects it to\n    * fully populate the returned {@link Network} object.\n    *\n    * @param networkName\n    */\n   private Network createAndInspectNetwork(final String networkName) {\n      final NetworkApi networkApi = api.getNetworkApi();\n      Network network = networkApi.createNetwork(Network.builder().name(networkName).driver(\"bridge\").build());\n      return networkApi.inspectNetwork(network.id());\n   }\n}\n"
  },
  {
    "path": "apis/docker/src/test/java/org/jclouds/docker/compute/DockerComputeServiceLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.compute;\n\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static java.lang.String.format;\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static java.util.logging.Logger.getAnonymousLogger;\nimport static org.jclouds.compute.options.RunScriptOptions.Builder.nameTask;\nimport static org.jclouds.compute.options.TemplateOptions.Builder.runAsRoot;\nimport static org.jclouds.util.Predicates2.retry;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.List;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\nimport java.util.concurrent.TimeUnit;\n\nimport org.jclouds.compute.ComputeService;\nimport org.jclouds.compute.JettyStatements;\nimport org.jclouds.compute.RunNodesException;\nimport org.jclouds.compute.domain.ExecResponse;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.domain.TemplateBuilder;\nimport org.jclouds.compute.internal.BaseComputeServiceContextLiveTest;\nimport org.jclouds.compute.util.OpenSocketFinder;\nimport org.jclouds.docker.DockerApi;\nimport org.jclouds.docker.compute.options.DockerTemplateOptions;\nimport org.jclouds.docker.domain.Container;\nimport org.jclouds.docker.features.ImageApi;\nimport org.jclouds.docker.options.CreateImageOptions;\nimport org.jclouds.docker.options.DeleteImageOptions;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.predicates.SocketOpen;\nimport org.jclouds.scriptbuilder.domain.Statement;\nimport org.jclouds.scriptbuilder.domain.Statements;\nimport org.jclouds.sshj.config.SshjSshClientModule;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeGroups;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Stopwatch;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.net.HostAndPort;\nimport com.google.inject.Module;\n\n/**\n * Live tests for the {@link org.jclouds.compute.ComputeService} integration.\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"DockerComputeServiceLiveTest\")\npublic class DockerComputeServiceLiveTest extends BaseComputeServiceContextLiveTest {\n\n   private static final String SSHABLE_IMAGE = \"tutum/ubuntu\";\n   private static final String SSHABLE_IMAGE_TAG = \"trusty\";\n   private Image defaultImage;\n   protected Template template;\n   protected Predicate<HostAndPort> socketTester;\n   protected OpenSocketFinder openSocketFinder;\n\n   protected ComputeService client;\n\n   public DockerComputeServiceLiveTest() {\n      provider = \"docker\";\n   }\n\n   @Override\n   protected Module getSshModule() {\n      return new SshjSshClientModule();\n   }\n\n   @BeforeGroups(groups = { \"integration\", \"live\" })\n   @Override\n   public void setupContext() {\n      super.setupContext();\n      buildSocketTester();\n   }\n\n   @Override\n   protected void initializeContext() {\n      super.initializeContext();\n      client = view.getComputeService();\n\n      String imageName = SSHABLE_IMAGE + \":\" + SSHABLE_IMAGE_TAG;\n      defaultImage = client.getImage(imageName);\n      assertNotNull(defaultImage);\n   }\n\n   @AfterClass\n   @Override\n   protected void tearDownContext() {\n      super.tearDownContext();\n      if (defaultImage != null) {\n         imageApi().deleteImage(SSHABLE_IMAGE + \":\" + SSHABLE_IMAGE_TAG, DeleteImageOptions.Builder.force(true));\n      }\n   }\n\n   private ImageApi imageApi() {\n      return client.getContext().unwrapApi(DockerApi.class).getImageApi();\n   }\n\n   protected Template buildTemplate(TemplateBuilder templateBuilder) {\n\n      String imageName = SSHABLE_IMAGE + \":\" + SSHABLE_IMAGE_TAG;\n      org.jclouds.docker.domain.Image image = imageApi().inspectImage(imageName);\n      if (image == null) {\n         CreateImageOptions options = CreateImageOptions.Builder.fromImage(SSHABLE_IMAGE).tag(SSHABLE_IMAGE_TAG);\n         imageApi().createImage(options);\n      }\n      image = imageApi().inspectImage(imageName);\n      defaultImage = client.getImage(image.id());\n\n\n      DockerTemplateOptions options = new DockerTemplateOptions();\n      options.env(ImmutableList.of(\"ROOT_PASS=password\"));\n      options.overrideLoginCredentials(LoginCredentials.builder().identity(\"root\").credential(\"password\").build());\n      template = templateBuilder.imageId(defaultImage.getId()).options(options).build();\n      return template;\n   }\n\n   protected void createAndRunAServiceInGroup(String group) throws RunNodesException {\n      // note that some cloud providers do not support mixed case tag names\n      ImmutableMap<String, String> userMetadata = ImmutableMap.of(\"test\", group);\n      ImmutableSet<String> tags = ImmutableSet.of(group);\n      Stopwatch watch = Stopwatch.createStarted();\n      template = buildTemplate(client.templateBuilder());\n      template.getOptions().inboundPorts(22, 8080).blockOnPort(22, 300).userMetadata(userMetadata).tags(tags);\n      NodeMetadata node = getOnlyElement(client.createNodesInGroup(group, 1, template));\n      long createSeconds = watch.elapsed(TimeUnit.SECONDS);\n      final String nodeId = node.getId();\n      //checkUserMetadataContains(node, userMetadata);\n      //checkTagsInNodeEquals(node, tags);\n      getAnonymousLogger().info(\n              format(\"<< available node(%s) os(%s) in %ss\", node.getId(), node.getOperatingSystem(), createSeconds));\n      watch.reset().start();\n      client.runScriptOnNode(nodeId, JettyStatements.install(), nameTask(\"configure-jetty\"));\n      long configureSeconds = watch.elapsed(TimeUnit.SECONDS);\n      getAnonymousLogger().info(\n              format(\n                      \"<< configured node(%s) with %s and jetty %s in %ss\",\n                      nodeId,\n                      exec(nodeId, \"java -fullversion\"),\n                      exec(nodeId, JettyStatements.version()), configureSeconds));\n      trackProcessOnNode(JettyStatements.start(), \"start jetty\", node);\n      client.runScriptOnNode(nodeId, JettyStatements.stop(), runAsRoot(false).wrapInInitScript(false));\n      trackProcessOnNode(JettyStatements.start(), \"start jetty\", node);\n   }\n\n   protected void trackProcessOnNode(Statement process, String processName, NodeMetadata node) {\n      ServiceStats stats = new ServiceStats();\n      Stopwatch watch = Stopwatch.createStarted();\n      ExecResponse exec = client.runScriptOnNode(node.getId(), process, runAsRoot(false).wrapInInitScript(false));\n      stats.backgroundProcessMilliseconds = watch.elapsed(TimeUnit.MILLISECONDS);\n\n      Container container = client.getContext().unwrapApi(DockerApi.class).getContainerApi().inspectContainer(node.getId());\n      Map<String, List<Map<String, String>>> ports = container.networkSettings().ports();\n      int port = Integer.parseInt(getOnlyElement(ports.get(\"8080/tcp\")).get(\"HostPort\"));\n\n      watch.reset().start();\n      HostAndPort socket;\n      try {\n         socket = openSocketFinder.findOpenSocketOnNode(node, port, 600, TimeUnit.SECONDS);\n      } catch (NoSuchElementException e) {\n         throw new NoSuchElementException(format(\"%s%n%s%s\", e.getMessage(), exec.getOutput(), exec.getError()));\n      }\n      stats.socketOpenMilliseconds = watch.elapsed(TimeUnit.MILLISECONDS);\n      getAnonymousLogger().info(format(\"<< %s on node(%s)[%s] %s\", processName, node.getId(), socket, stats));\n   }\n\n   static class ServiceStats {\n      long backgroundProcessMilliseconds;\n      long socketOpenMilliseconds;\n\n      @Override\n      public String toString() {\n         return format(\"[backgroundProcessMilliseconds=%s, socketOpenMilliseconds=%s]\",\n                 backgroundProcessMilliseconds, socketOpenMilliseconds);\n      }\n   }\n\n   protected String exec(final String nodeId, String command) {\n      return exec(nodeId, Statements.exec(command));\n   }\n\n   protected String exec(final String nodeId, Statement command) {\n      return client.runScriptOnNode(nodeId, command, runAsRoot(false).wrapInInitScript(false)).getOutput().trim();\n   }\n\n   protected void buildSocketTester() {\n      SocketOpen socketOpen = view.utils().injector().getInstance(SocketOpen.class);\n      socketTester = retry(socketOpen, 60, 1, SECONDS);\n      // wait a maximum of 60 seconds for port 8080 to open.\n      openSocketFinder = context.utils().injector().getInstance(OpenSocketFinder.class);\n   }\n\n}\n"
  },
  {
    "path": "apis/docker/src/test/java/org/jclouds/docker/compute/SshToCustomPortLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.compute;\n\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.jclouds.compute.options.RunScriptOptions.Builder.wrapInInitScript;\nimport static org.jclouds.docker.internal.DockerTestUtils.consumeStreamSilently;\nimport static org.jclouds.docker.internal.DockerTestUtils.removeImageIfExists;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.compute.RunNodesException;\nimport org.jclouds.compute.domain.ExecResponse;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.internal.BaseComputeServiceContextLiveTest;\nimport org.jclouds.docker.DockerApi;\nimport org.jclouds.docker.compute.functions.LoginPortForContainer;\nimport org.jclouds.docker.compute.options.DockerTemplateOptions;\nimport org.jclouds.docker.domain.Config;\nimport org.jclouds.docker.domain.Container;\nimport org.jclouds.docker.domain.HostConfig;\nimport org.jclouds.docker.domain.Image;\nimport org.jclouds.docker.domain.ImageSummary;\nimport org.jclouds.docker.options.BuildOptions;\nimport org.jclouds.sshj.config.SshjSshClientModule;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Lists;\nimport com.google.common.collect.Maps;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Module;\n\n/**\n * This class tests configuring custom SSH port for Docker images.\n */\n@Test(groups = \"live\", testName = \"SshToCustomPortLiveTest\", singleThreaded = true)\npublic class SshToCustomPortLiveTest extends BaseComputeServiceContextLiveTest {\n\n   private static final int SSH_PORT = 8822;\n   private static final int SSH_PORT_BRIDGE = 18822;\n   private static final String IMAGE_REPOSITORY = \"jclouds/testrepo\";\n   private static final String IMAGE_TAG_1 = \"testtag\";\n   private static final String IMAGE_TAG_2 = \"second\";\n\n   private Image image;\n\n   public SshToCustomPortLiveTest() {\n      provider = \"docker\";\n   }\n\n   /**\n    * Asserts that the new image exists and tags were created successfully in\n    * the test preparation phase ({@link #setupContext()} method).\n    */\n   @Test\n   public void testImageCreated() {\n      assertNotNull(image);\n\n      final String imageId = image.id();\n      assertNotNull(imageId);\n\n      List<ImageSummary> listImages = api().getImageApi().listImages();\n      assertNotNull(listImages);\n      ImageSummary testImage = Iterables.find(listImages, new Predicate<ImageSummary>() {\n         @Override\n         public boolean apply(ImageSummary input) {\n            return imageId.equals(input.id());\n         }\n      });\n\n      assertEquals(testImage.repoTags().size(), 2, \"Unexpected number of tags on the image.\");\n      assertThat(testImage.repoTags()).contains(toTag(IMAGE_REPOSITORY, IMAGE_TAG_1),\n            toTag(IMAGE_REPOSITORY, IMAGE_TAG_2));\n   }\n\n   /**\n    * Start a node from the newly created image. The dropbear SSH server running\n    * on custom port ( {@value #SSH_PORT}). The Docker networkMode used is\n    * \"host\". Execute a command through the SSH connection and check the result.\n    * Destroy the node when finished.\n    * \n    * @throws RunNodesException\n    */\n   @Test(dependsOnMethods = \"testImageCreated\")\n   public void testCustomPortSsh() throws RunNodesException {\n      final DockerTemplateOptions options = DockerTemplateOptions.Builder\n            .env(\"SSH_PORT=\" + SSH_PORT, \"ROOT_PASSWORD=screencast\")\n            .overrideLoginUser(\"root\").overrideLoginPassword(\"screencast\")\n            .blockOnPort(SSH_PORT, 30).networkMode(\"host\");\n\n      final Template template = view.getComputeService().templateBuilder().imageId(image.id()).options(options).build();\n\n      String nodeId = null;\n      try {\n         NodeMetadata node = Iterables\n               .getOnlyElement(view.getComputeService().createNodesInGroup(\"ssh-net-host\", 1, template));\n\n         nodeId = node.getId();\n         ExecResponse response = view.getComputeService().runScriptOnNode(nodeId, \"sh -c 'echo hello && sleep 0.2'\", wrapInInitScript(false));\n         assertThat(response.getOutput().trim()).endsWith(\"hello\");\n      } finally {\n         if (nodeId != null)\n            view.getComputeService().destroyNode(nodeId);\n      }\n   }\n\n\n   @Test(dependsOnMethods = \"testImageCreated\")\n   public void testAdvancedConfig() throws RunNodesException {\n      final String portId = SSH_PORT + \"/tcp\";\n      final DockerTemplateOptions options = DockerTemplateOptions.Builder\n            .configBuilder(\n                  Config.builder().env(ImmutableList.<String> of(\"SSH_PORT=\" + SSH_PORT, \"ROOT_PASSWORD=jcloudsRulez\"))\n                        .exposedPorts(ImmutableMap.<String, Object> of(portId, Maps.newHashMap()))\n                        .hostConfig(HostConfig.builder().networkMode(\"bridge\")\n                              .portBindings(ImmutableMap.<String, List<Map<String, String>>> of(portId,\n                                    Lists.<Map<String, String>>newArrayList(ImmutableMap.of(\"HostPort\", String.valueOf(SSH_PORT_BRIDGE)))))\n                              .build())\n                        .image(\"test-if-this-value-is-correctly-overriden\"))\n            .overrideLoginUser(\"root\").overrideLoginPassword(\"jcloudsRulez\").blockOnPort(SSH_PORT_BRIDGE, 30);\n\n      final Template template = view.getComputeService().templateBuilder().imageId(image.id()).options(options).build();\n\n      String nodeId = null;\n      try {\n         NodeMetadata node = Iterables\n               .getOnlyElement(view.getComputeService().createNodesInGroup(\"ssh-net-bridge\", 1, template));\n\n         nodeId = node.getId();\n         ExecResponse response = view.getComputeService().runScriptOnNode(nodeId, \"sh -c 'true'\",\n               wrapInInitScript(false));\n         assertEquals(response.getExitStatus(), 0);\n      } finally {\n         if (nodeId != null)\n            view.getComputeService().destroyNode(nodeId);\n      }\n   }\n   \n   /**\n    * Build a new image with 2 tags on it in the test preparation phase.\n    * \n    * @see org.jclouds.apis.BaseContextLiveTest#setupContext()\n    */\n   @Override\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   public void setupContext() {\n      super.setupContext();\n      final String tag = toTag(IMAGE_REPOSITORY, IMAGE_TAG_1);\n\n      removeImageIfExists(api(), tag);\n      removeImageIfExists(api(), toTag(IMAGE_REPOSITORY, IMAGE_TAG_2));\n\n      BuildOptions options = BuildOptions.Builder.tag(tag).verbose(false).nocache(false);\n      InputStream buildImageStream;\n      try {\n         buildImageStream = api().getMiscApi().build(BaseDockerApiLiveTest.tarredDockerfile(), options);\n         consumeStreamSilently(buildImageStream);\n      } catch (IOException e) {\n         throw new RuntimeException(\"Error occured during building Docker image.\", e);\n      }\n      image = api().getImageApi().inspectImage(tag);\n      api().getImageApi().tagImage(image.id(), IMAGE_REPOSITORY, IMAGE_TAG_2, true);\n   }\n\n   /**\n    * After the test remove created image (with all tags).\n    * \n    * @see #setupContext()\n    */\n   @AfterClass(alwaysRun = true)\n   protected void tearDown() {\n      removeImageIfExists(api(), toTag(IMAGE_REPOSITORY, IMAGE_TAG_1));\n      removeImageIfExists(api(), toTag(IMAGE_REPOSITORY, IMAGE_TAG_2));\n   }\n\n   /**\n    * Configure used modules. A custom {@link LoginPortForContainer} binding is\n    * added among logging and SSH module.\n    * \n    * @see org.jclouds.compute.internal.BaseGenericComputeServiceContextLiveTest#setupModules()\n    */\n   @Override\n   protected Iterable<Module> setupModules() {\n      return ImmutableSet.<Module> of(getLoggingModule(), new SshjSshClientModule(), new AbstractModule() {\n         @Override\n         protected void configure() {\n            bind(LoginPortForContainer.class).toInstance(new LoginPortForContainer() {\n               @Override\n               public Optional<Integer> apply(Container container) {\n                  return Optional.of(container.name().contains(\"ssh-net-bridge\") ? SSH_PORT_BRIDGE : SSH_PORT);\n               }\n            });\n         }\n      });\n   }\n\n   /**\n    * Return DockerApi for current Context.\n    * \n    * @return\n    */\n   private DockerApi api() {\n      return view.unwrapApi(DockerApi.class);\n   }\n\n   /**\n    * Concatenate repository and tag name (if provided) in Docker format.\n    * \n    * @param repo\n    * @param tag\n    * @return\n    */\n   private static String toTag(String repo, String tag) {\n      return repo + (tag != null ? \":\" + tag : \"\");\n   }\n\n}\n"
  },
  {
    "path": "apis/docker/src/test/java/org/jclouds/docker/compute/functions/ContainerToNodeMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.compute.functions;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.easymock.EasyMock;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.ImageBuilder;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.docker.domain.Config;\nimport org.jclouds.docker.domain.Container;\nimport org.jclouds.docker.domain.HostConfig;\nimport org.jclouds.docker.domain.NetworkSettings;\nimport org.jclouds.docker.domain.Port;\nimport org.jclouds.docker.domain.State;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.testng.annotations.BeforeMethod;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\n\n/**\n * Unit tests for the {@link org.jclouds.docker.compute.functions.ContainerToNodeMetadata} class.\n */\n@Test(groups = \"unit\", testName = \"ContainerToNodeMetadataTest\")\npublic class ContainerToNodeMetadataTest {\n\n   private ContainerToNodeMetadata function;\n\n   private Container container;\n\n   @BeforeMethod\n   public void setup() {\n      Config containerConfig = Config.builder()\n              .hostname(\"6d35806c1bd2\")\n              .domainname(\"\")\n              .user(\"\")\n              .memory(0)\n              .memorySwap(0)\n              .cpuShares(0)\n              .attachStdin(false)\n              .attachStdout(false)\n              .attachStderr(false)\n              .exposedPorts(ImmutableMap.of(\"22/tcp\", ImmutableMap.of()))\n              .tty(false)\n              .openStdin(false)\n              .stdinOnce(false)\n              .env(null)\n              .cmd(ImmutableList.of(\"/usr/sbin/sshd\", \"-D\"))\n              .image(\"jclouds/ubuntu\")\n              .workingDir(\"\")\n              .entrypoint(null)\n              .networkDisabled(false)\n              .build();\n      State state = State.create( //\n            3626, // pid\n            true, // running\n            0, // exitCode\n            \"2014-03-24T20:28:37.537659054Z\", // startedAt\n            \"0001-01-01T00:00:00Z\", // finishedAt\n            false, // paused\n            false,  // restarting\n            \"running\", // Status\n            false, // OOMKilled\n            false, // Dead\n            \"\"     // Error\n      );\n      container = Container.builder()\n              .id(\"6d35806c1bd2b25cd92bba2d2c2c5169dc2156f53ab45c2b62d76e2d2fee14a9\")\n              .name(\"/hopeful_mclean\")\n              .created(new SimpleDateFormatDateService().iso8601DateParse(\"2014-03-22T07:16:45.784120972Z\"))\n              .path(\"/usr/sbin/sshd\")\n              .args(Arrays.asList(\"-D\"))\n              .config(containerConfig)\n              .state(state)\n              .image(\"af0f59f1c19eef9471c3b8c8d587c39b8f130560b54f3766931b37d76d5de4b6\")\n              .networkSettings(NetworkSettings.builder()\n                      .ipAddress(\"172.17.0.2\")\n                      .ipPrefixLen(16)\n                      .gateway(\"172.17.42.1\")\n                      .bridge(\"docker0\")\n                      .ports(ImmutableMap.<String, List<Map<String, String>>>of(\"22/tcp\",\n                              ImmutableList.<Map<String, String>>of(ImmutableMap.of(\"HostIp\", \"0.0.0.0\", \"HostPort\",\n                                      \"49199\"))))\n                      .build())\n              .resolvConfPath(\"/etc/resolv.conf\")\n              .driver(\"aufs\")\n              .execDriver(\"native-0.1\")\n              .volumes(ImmutableMap.<String, String>of())\n              .volumesRW(ImmutableMap.<String, Boolean>of())\n              .command(\"\")\n              .status(\"\")\n              .hostConfig(HostConfig.builder().publishAllPorts(true).build())\n              .ports(ImmutableList.<Port>of())\n              .node(null)\n              .build();\n      ProviderMetadata providerMetadata = EasyMock.createMock(ProviderMetadata.class);\n      expect(providerMetadata.getEndpoint()).andReturn(\"http://127.0.0.1:4243\").atLeastOnce();\n      replay(providerMetadata);\n\n      GroupNamingConvention.Factory namingConvention = Guice.createInjector().getInstance(GroupNamingConvention.Factory.class);\n\n      Supplier<Map<String, ? extends Image>> images = new Supplier<Map<String, ? extends Image>>() {\n         @Override\n         public Map<String, ? extends Image> get() {\n            OperatingSystem os = OperatingSystem.builder()\n                    .description(\"Ubuntu 12.04 64bit\")\n                    .family(OsFamily.UBUNTU)\n                    .version(\"12.04\")\n                    .is64Bit(true)\n                    .build();\n\n            return ImmutableMap.of(\"af0f59f1c19eef9471c3b8c8d587c39b8f130560b54f3766931b37d76d5de4b6\",\n                    new ImageBuilder()\n                            .ids(\"af0f59f1c19eef9471c3b8c8d587c39b8f130560b54f3766931b37d76d5de4b6\")\n                            .name(\"ubuntu\")\n                            .description(\"Ubuntu 12.04 64bit\")\n                            .operatingSystem(os)\n                            .status(Image.Status.AVAILABLE)\n                            .build());\n         }\n      };\n\n      Supplier<Set<? extends Location>> locations = new Supplier<Set< ? extends Location>>() {\n         @Override\n         public Set<? extends Location> get() {\n\n            return ImmutableSet.of(\n                    new LocationBuilder()\n                            .id(\"docker\")\n                            .description(\"http://localhost:2375\")\n                            .scope(LocationScope.PROVIDER)\n                            .build()\n            );\n         }\n      };\n\n      function = new ContainerToNodeMetadata(providerMetadata, new StateToStatus(), namingConvention, images, locations,\n            new LoginPortForContainer.LoginPortLookupChain(null));\n   }\n\n   public void testVirtualMachineToNodeMetadata() {\n      NodeMetadata node = function.apply(container);\n\n      assertEquals(node.getId(), \"6d35806c1bd2b25cd92bba2d2c2c5169dc2156f53ab45c2b62d76e2d2fee14a9\");\n      assertEquals(node.getGroup(), \"hopeful_mclean\");\n      assertEquals(node.getImageId(), \"af0f59f1c19eef9471c3b8c8d587c39b8f130560b54f3766931b37d76d5de4b6\");\n      assertEquals(node.getLoginPort(), 49199);\n      assertEquals(node.getStatus(), NodeMetadata.Status.RUNNING);\n      assertEquals(node.getImageId(), \"af0f59f1c19eef9471c3b8c8d587c39b8f130560b54f3766931b37d76d5de4b6\");\n      assertEquals(node.getPrivateAddresses(), ImmutableSet.of(\"172.17.0.2\"));\n      assertEquals(node.getPublicAddresses(), ImmutableSet.of(\"127.0.0.1\"));\n   }\n\n   public void testVirtualMachineWithNetworksToNodeMetadata() {\n      // Example networks taken from container.json\n      Container containerWithNetwork = container.toBuilder()\n            .networkSettings(container.networkSettings().toBuilder()\n                    .networks(ImmutableMap.<String, NetworkSettings.Details>builder()\n                          .put(\"JCLOUDS_NETWORK\", NetworkSettings.Details.builder()\n                                   .endpoint(\"1a10519f808faf1181cfdf3d1d6dd93e19ede2d1c8fed82562a4c17c297c4db3\")\n                                   .gateway(\"172.19.0.1\")\n                                   .ipAddress(\"172.19.0.2\")\n                                   .ipPrefixLen(16)\n                                   .ipv6Gateway(\"\")\n                                   .globalIPv6Address(\"\")\n                                   .globalIPv6PrefixLen(0)\n                                   .macAddress(\"02:42:ac:13:00:02\")\n                                   .build())\n                          .put(\"bridge\", NetworkSettings.Details.builder()\n                                .endpoint(\"9e8dcc0c8288938a923018fee0728cee8e6de7c01a5150738ee6e51c1caf8cf6\")\n                                .gateway(\"172.17.0.1\")\n                                .ipAddress(\"172.17.0.2\")\n                                .ipPrefixLen(16)\n                                .ipv6Gateway(\"\")\n                                .globalIPv6Address(\"\")\n                                .globalIPv6PrefixLen(0)\n                                .macAddress(\"02:42:ac:11:00:02\")\n                                .build())\n                          .build())\n                    .build())\n            .build();\n\n      NodeMetadata node = function.apply(containerWithNetwork);\n\n      // Only asserting network-related aspects; the rest is covered by testVirtualMachineToNodeMetadata\n      assertEquals(node.getLoginPort(), 49199);\n      assertEquals(node.getPrivateAddresses(), ImmutableSet.of(\"172.17.0.2\", \"172.19.0.2\"));\n      assertEquals(node.getPublicAddresses(), ImmutableSet.of(\"127.0.0.1\"));\n   }\n}\n"
  },
  {
    "path": "apis/docker/src/test/java/org/jclouds/docker/compute/functions/CustomLoginPortFromImageTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.compute.functions;\n\nimport static org.jclouds.docker.compute.config.LoginPortLookupModule.loginPortLookupBinder;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.docker.compute.config.LoginPortLookupModule;\nimport org.jclouds.docker.domain.Config;\nimport org.jclouds.docker.domain.Container;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Iterables;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport com.google.inject.multibindings.MapBinder;\n\n@Test(groups = \"unit\")\npublic class CustomLoginPortFromImageTest {\n\n   private CustomLoginPortFromImage customLoginPortFromImage;\n\n   @BeforeClass\n   public void setup() {\n      Injector i = Guice.createInjector(new LoginPortLookupModule(), new AbstractModule() {\n         @Override\n         protected void configure() {\n            MapBinder<String, LoginPortForContainer> imageToFunction = loginPortLookupBinder(binder());\n            imageToFunction.addBinding(\".*alpine-ext.*\").toInstance(LoginPortFromEnvVar);\n            imageToFunction.addBinding(\".*ubuntu.*\").toInstance(AlwaysPort22);\n            imageToFunction.addBinding(\".*ubuntu:12\\\\.04.*\").toInstance(AlwaysPort8080);\n         }\n      });\n      customLoginPortFromImage = i.getInstance(CustomLoginPortFromImage.class);\n   }\n\n   public void testPortFromEnvironmentVariables() {\n      Config config = Config.builder().image(\"alpine-ext:3.2\").env(ImmutableList.of(\"FOO=bar\", \"SSH_PORT=2345\"))\n            .build();\n      Container container = Container.builder().id(\"id\").config(config).build();\n\n      assertEquals(customLoginPortFromImage.apply(container).get().intValue(), 2345);\n   }\n\n   public void testMostSpecificImageIsPicked() {\n      Config config = Config.builder().image(\"ubuntu:12.04\").build();\n      Container container = Container.builder().id(\"id\").config(config).build();\n\n      assertEquals(customLoginPortFromImage.apply(container).get().intValue(), 8080);\n   }\n\n   public void testNoImageFoundInMap() {\n      Config config = Config.builder().image(\"unexisting\").build();\n      Container container = Container.builder().id(\"id\").config(config).build();\n\n      assertEquals(customLoginPortFromImage.apply(container), Optional.absent());\n   }\n\n   private static final LoginPortForContainer LoginPortFromEnvVar = new LoginPortForContainer() {\n      @Override\n      public Optional<Integer> apply(Container input) {\n         Optional<String> portVariable = Iterables.tryFind(input.config().env(), new Predicate<String>() {\n            @Override\n            public boolean apply(String input) {\n               String[] var = input.split(\"=\");\n               return var[0].equals(\"SSH_PORT\");\n            }\n         });\n         return portVariable.isPresent() ? Optional.of(Integer.valueOf(portVariable.get().split(\"=\")[1])) : Optional\n               .<Integer> absent();\n      }\n   };\n\n   private static final LoginPortForContainer AlwaysPort22 = new LoginPortForContainer() {\n      @Override\n      public Optional<Integer> apply(Container input) {\n         return Optional.of(22);\n      }\n   };\n\n   private static final LoginPortForContainer AlwaysPort8080 = new LoginPortForContainer() {\n      @Override\n      public Optional<Integer> apply(Container input) {\n         return Optional.of(8080);\n      }\n   };\n}\n"
  },
  {
    "path": "apis/docker/src/test/java/org/jclouds/docker/compute/functions/ImageToImageTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.compute.functions;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Date;\n\nimport org.easymock.EasyMock;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.docker.domain.Config;\nimport org.testng.annotations.BeforeMethod;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Unit tests for the {@link org.jclouds.docker.compute.functions.ImageToImage} class.\n */\n@Test(groups = \"unit\", testName = \"ImageToImageTest\")\npublic class ImageToImageTest {\n\n   private static final org.jclouds.docker.domain.Image IMAGE_EMPTY_REPOTAGS = org.jclouds.docker.domain.Image.create(\n         \"id\", // id\n         \"author\",\n         \"comment\",\n         Config.builder()\n         .image(\"imageId\")\n         .build(),\n         Config.builder()\n         .image(\"imageId\")\n         .build(),\n         \"parent\", // parent\n         new Date(), // created\n         \"containerId\", // container\n         \"1.3.1\", // dockerVersion\n         \"x86_64\", // architecture\n         \"os\", // os\n         0L, // size\n         0L, // virtualSize\n         ImmutableList.<String> of() // repoTags\n         );\n\n   private static final org.jclouds.docker.domain.Image IMAGE_REPOTAG_WITH_PORT = org.jclouds.docker.domain.Image.create(\n         \"id\", // id\n         \"author\",\n         \"comment\",\n         Config.builder()\n         .image(\"imageId\")\n         .build(),\n         Config.builder()\n         .image(\"imageId\")\n         .build(),\n         \"parent\", // parent\n         new Date(), // created\n         \"containerId\", // container\n         \"1.3.1\", // dockerVersion\n         \"x86_64\", // architecture\n         \"os\", // os\n         0L, // size\n         0L, // virtualSize\n         ImmutableList.of(\"registry.company.example:8888/a/b/c/d:latest\") // repoTags\n         );\n\n   private ImageToImage function;\n\n   private org.jclouds.docker.domain.Image image;\n\n   @BeforeMethod\n   public void setup() {\n      image = org.jclouds.docker.domain.Image.create(\n              \"id\", // id\n              \"author\",\n              \"comment\",\n              Config.builder()\n                      .image(\"imageId\")\n                      .build(),\n              Config.builder()\n                      .image(\"imageId\")\n                      .build(),\n              \"parent\", // parent\n              new Date(), // created\n              \"containerId\", // container\n              \"1.3.1\", // dockerVersion\n              \"x86_64\", // architecture\n              \"os\", // os\n              0L, // size\n              0L, // virtualSize\n              ImmutableList.of(\"repoTag1:version\") // repoTags\n      );\n      function = new ImageToImage();\n   }\n\n   public void testImageToImage() {\n      org.jclouds.docker.domain.Image mockImage = mockImage();\n\n      Image image = function.apply(mockImage);\n\n      verify(mockImage);\n\n      assertEquals(mockImage.id(), image.getId().toString());\n   }\n\n   public void testEmptyRepoTags() {\n      Image image = function.apply(IMAGE_EMPTY_REPOTAGS);\n\n      assertEquals(image.getId(), \"id\");\n      assertEquals(image.getDescription(), \"<none>\");\n      assertEquals(image.getOperatingSystem().getVersion(), \"<none>\");\n      assertEquals(image.getName(), \"<none>\");\n   }\n\n   public void testRepoTagWithHostPort() {\n      Image image = function.apply(IMAGE_REPOTAG_WITH_PORT);\n\n      assertEquals(image.getDescription(), \"registry.company.example:8888/a/b/c/d:latest\");\n      assertEquals(image.getOperatingSystem().getVersion(), \"latest\");\n      assertEquals(image.getName(), \"registry.company.example:8888/a/b/c/d\");\n   }\n\n   private org.jclouds.docker.domain.Image mockImage() {\n      org.jclouds.docker.domain.Image mockImage = EasyMock.createMock(org.jclouds.docker.domain.Image.class);\n\n      expect(mockImage.id()).andReturn(image.id()).anyTimes();\n      expect(mockImage.repoTags()).andReturn(image.repoTags()).anyTimes();\n      expect(mockImage.architecture()).andReturn(image.architecture()).anyTimes();\n      replay(mockImage);\n\n      return mockImage;\n   }\n}\n"
  },
  {
    "path": "apis/docker/src/test/java/org/jclouds/docker/compute/functions/StateToStatusTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.compute.functions;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertEquals;\n\nimport org.easymock.EasyMock;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.docker.domain.State;\nimport org.testng.annotations.BeforeMethod;\nimport org.testng.annotations.Test;\n\n/**\n * Unit tests for the {@link StateToStatus} class.\n */\n@Test(groups = \"unit\", testName = \"StateToStatusTest\")\npublic class StateToStatusTest {\n   private StateToStatus function;\n\n   @BeforeMethod\n   public void setup() {\n      function = new StateToStatus();\n   }\n\n   public void testStateRunningToStatusRunning() {\n      State mockState = mockStateRunning();\n\n      NodeMetadata.Status status = function.apply(mockState);\n\n      verify(mockState);\n\n      assertEquals(mockState.running(), true);\n      assertEquals(status, NodeMetadata.Status.RUNNING);\n   }\n\n   public void testStateNotRunningToStatusTerminated() {\n      State mockState = mockStateNotRunning();\n\n      NodeMetadata.Status status = function.apply(mockState);\n\n      verify(mockState);\n\n      assertEquals(mockState.running(), false);\n      assertEquals(status, NodeMetadata.Status.TERMINATED);\n   }\n\n   private State mockStateRunning() {\n      State mockState = EasyMock.createMock(State.class);\n\n      expect(mockState.running()).andReturn(true).anyTimes();\n      replay(mockState);\n\n      return mockState;\n   }\n\n   private State mockStateNotRunning() {\n      State mockState = EasyMock.createMock(State.class);\n\n      expect(mockState.running()).andReturn(false).anyTimes();\n      replay(mockState);\n\n      return mockState;\n   }\n}\n"
  },
  {
    "path": "apis/docker/src/test/java/org/jclouds/docker/compute/options/DockerTemplateOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.compute.options;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.docker.domain.Config;\nimport org.jclouds.docker.domain.Config.Builder;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Unit tests for the {@link DockerTemplateOptions} class.\n */\n@Test(groups = \"unit\", testName = \"DockerTemplateOptionsTest\")\npublic class DockerTemplateOptionsTest {\n\n   @Test\n   public void testHostname() {\n      TemplateOptions options = DockerTemplateOptions.Builder.hostname(\"hostname\");\n      assertEquals(options.as(DockerTemplateOptions.class).getHostname(), \"hostname\");\n   }\n\n   @Test\n   public void testMemory() {\n      TemplateOptions options = DockerTemplateOptions.Builder.memory(1024);\n      assertEquals(options.as(DockerTemplateOptions.class).getMemory(), Integer.valueOf(1024));\n   }\n\n   @Test\n   public void testCpuShares() {\n      TemplateOptions options = DockerTemplateOptions.Builder.cpuShares(2);\n      assertEquals(options.as(DockerTemplateOptions.class).getCpuShares(), Integer.valueOf(2));\n   }\n\n   @Test\n   public void testVolumes() {\n      TemplateOptions options = DockerTemplateOptions.Builder.volumes(ImmutableMap.of(\"/tmp\", \"/tmp\"));\n      assertEquals(options.as(DockerTemplateOptions.class).getVolumes(), ImmutableMap.of(\"/tmp\", \"/tmp\"));\n   }\n\n   @Test\n   public void testDns() {\n      TemplateOptions options = DockerTemplateOptions.Builder.dns(\"8.8.8.8\", \"8.8.4.4\");\n      assertEquals(options.as(DockerTemplateOptions.class).getDns(), ImmutableList.of(\"8.8.8.8\", \"8.8.4.4\"));\n   }\n\n   @Test\n   public void testEntrypoint() {\n      TemplateOptions options = DockerTemplateOptions.Builder.entrypoint(\"/bin/sh\", \"-c\");\n      assertEquals(options.as(DockerTemplateOptions.class).getEntrypoint(), ImmutableList.of(\"/bin/sh\", \"-c\"));\n   }\n\n   @Test\n   public void testCommands() {\n      TemplateOptions options = DockerTemplateOptions.Builder.commands(\"chmod 666 /etc/*\", \"rm -rf /var/run\");\n      assertEquals(options.as(DockerTemplateOptions.class).getCommands(), ImmutableList.of(\"chmod 666 /etc/*\", \"rm -rf /var/run\"));\n   }\n\n   @Test\n   public void testEnv() {\n      TemplateOptions options = DockerTemplateOptions.Builder.env(ImmutableList.of(\"HOST=abc\", \"PORT=1234\"));\n      assertEquals(options.as(DockerTemplateOptions.class).getEnv(), ImmutableList.of(\"HOST=abc\", \"PORT=1234\"));\n   }\n\n   @Test\n   public void testPortBindings() {\n      TemplateOptions options = DockerTemplateOptions.Builder.portBindings(ImmutableMap.<Integer, Integer>builder().put(8443,  443).put(8080, 80).build());\n      assertEquals(options.as(DockerTemplateOptions.class).getPortBindings(), ImmutableMap.<Integer, Integer>builder().put(8443,  443).put(8080, 80).build());\n   }\n\n\n   @Test\n   public void testNetworkMode() {\n      TemplateOptions options = DockerTemplateOptions.Builder.networkMode(\"host\");\n      assertEquals(options.as(DockerTemplateOptions.class).getNetworkMode(), \"host\");\n   }\n\n   @Test\n   public void testPrivilegedDefaultFalse() {\n      TemplateOptions options = DockerTemplateOptions.Builder.memory(2);\n      assertEquals(options.as(DockerTemplateOptions.class).getPrivileged(), false);\n   }\n\n   @Test\n   public void testPrivileged() {\n      TemplateOptions options = DockerTemplateOptions.Builder.privileged(true);\n      assertEquals(options.as(DockerTemplateOptions.class).getPrivileged(), true);\n   }\n\n   @Test\n   public void testConfigBuilder() {\n      Builder builder = Config.builder().memory(1024)\n            .cpuShares(100).cmd(ImmutableList.<String> of(\"/opt/jboss/wildfly/bin/standalone.sh\", \"-b\", \"0.0.0.0\"))\n            .env(ImmutableList.<String> of(\"JAVA_HOME=/opt/jdk-1.8\", \"MGMT_USER=admin\",\n                  \"MGMT_PASSWORD=Schroedinger's Cat\"));\n      TemplateOptions options = DockerTemplateOptions.Builder.configBuilder(builder);\n      Builder builderInOpts = options.as(DockerTemplateOptions.class).getConfigBuilder();\n      assertNotNull(builderInOpts);\n      Config configFromOptions = builderInOpts.build();\n      assertEquals(configFromOptions, builder.build());\n      assertEquals(configFromOptions.env(), ImmutableList.<String> of(\"JAVA_HOME=/opt/jdk-1.8\", \"MGMT_USER=admin\",\n                  \"MGMT_PASSWORD=Schroedinger's Cat\"));\n   }\n\n   @Test\n   public void testNonDockerOptions() {\n      TemplateOptions options = DockerTemplateOptions.Builder.userMetadata(ImmutableMap.of(\"key\", \"value\")).cpuShares(1);\n      assertEquals(options.as(DockerTemplateOptions.class).getUserMetadata(), ImmutableMap.of(\"key\", \"value\"));\n      assertEquals(options.as(DockerTemplateOptions.class).getCpuShares(), Integer.valueOf(1));\n   }\n\n   @Test\n   public void testMultipleOptions() {\n      TemplateOptions options = DockerTemplateOptions.Builder.memory(512).cpuShares(4);\n      assertEquals(options.as(DockerTemplateOptions.class).getMemory(), Integer.valueOf(512));\n      assertEquals(options.as(DockerTemplateOptions.class).getCpuShares(), Integer.valueOf(4));\n   }\n\n   @Test\n   public void testCopyTo() {\n      DockerTemplateOptions options = DockerTemplateOptions.Builder\n            .memory(512)\n            .cpuShares(4)\n            .entrypoint(\"entry\", \"point\")\n            .commands(\"test\", \"abc\")\n            .portBindings(\n                  ImmutableMap.<Integer, Integer> builder()\n                        .put(8443, 443).build())\n            .hostname(\"hostname\")\n            .networkMode(\"host\")\n            .userMetadata(ImmutableMap.of(\"key\", \"value\"))\n            .env(ImmutableList.of(\"HOST=abc\", \"PORT=1234\"))\n            .dns(\"8.8.8.8\", \"8.8.4.4\")\n            .volumes(ImmutableMap.of(\"/tmp\", \"/tmp\"));\n      DockerTemplateOptions optionsCopy = new DockerTemplateOptions();\n      options.copyTo(optionsCopy);\n      assertEquals(optionsCopy, options);\n   }\n\n}\n"
  },
  {
    "path": "apis/docker/src/test/java/org/jclouds/docker/compute/strategy/PredicateLocateImageByNameTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.compute.strategy;\n\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Date;\n\nimport org.jclouds.docker.domain.Config;\nimport org.jclouds.docker.domain.Image;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Unit tests for finding images logic used in\n * {@link DockerComputeServiceAdapter#getImage(String)} method. It's mainly a\n * regression test for issue\n * <a href=\"https://issues.apache.org/jira/browse/JCLOUDS-1158\">JCLOUDS-1158</a>\n * .\n */\n@Test(groups = \"unit\", testName = \"PredicateLocateImageByNameTest\")\npublic class PredicateLocateImageByNameTest {\n\n   private static final Image IMAGE_REPO_TAGS_MULTI = Image.create(\"id\", // id\n         \"author\", \"comment\", Config.builder().image(\"imageId\").build(), Config.builder().image(\"imageId\").build(),\n         \"parent\", // parent\n         new Date(), // created\n         \"containerId\", // container\n         \"1.3.1\", // dockerVersion\n         \"x86_64\", // architecture\n         \"os\", // os\n         0L, // size\n         0L, // virtualSize\n         ImmutableList.<String> of(\"kwart/alpine-ext:3.3-ssh\", \"kwart/alpine-ext:latest\", \"my-tag:latestdock\") // repoTags\n   );\n\n   private static final Image IMAGE_REPO_TAGS_EMPTY = Image.create(\"id\", // id\n         \"author\", \"comment\", Config.builder().image(\"imageId\").build(), Config.builder().image(\"imageId\").build(),\n         \"parent\", // parent\n         new Date(), // created\n         \"containerId\", // container\n         \"1.3.1\", // dockerVersion\n         \"x86_64\", // architecture\n         \"os\", // os\n         0L, // size\n         0L, // virtualSize\n         ImmutableList.<String> of() // repoTags\n   );\n\n   private static final Image IMAGE_REPO_TAGS_WITH_HOST = Image.create(\"id\", // id\n         \"author\", \"comment\", Config.builder().image(\"imageId\").build(), Config.builder().image(\"imageId\").build(),\n         \"parent\", // parent\n         new Date(), // created\n         \"containerId\", // container\n         \"1.3.1\", // dockerVersion\n         \"x86_64\", // architecture\n         \"os\", // os\n         0L, // size\n         0L, // virtualSize\n         ImmutableList.<String> of(\"docker.io/kwart/alpine-ext:3.3-ssh\", \"docker.io/kwart/alpine-ext:latest\") // repoTags\n   );\n\n   public void testRepoTagVersion() {\n      final Predicate<Image> predicate = DockerComputeServiceAdapter\n            .createPredicateMatchingRepoTags(\"kwart/alpine-ext:3.3-ssh\");\n      assertTrue(predicate.apply(IMAGE_REPO_TAGS_MULTI));\n      assertFalse(predicate.apply(IMAGE_REPO_TAGS_EMPTY));\n      assertTrue(predicate.apply(IMAGE_REPO_TAGS_WITH_HOST));\n   }\n\n   public void testRepoTagLatest() {\n      final Predicate<Image> predicate = DockerComputeServiceAdapter.createPredicateMatchingRepoTags(\"kwart/alpine-ext\");\n      assertTrue(predicate.apply(IMAGE_REPO_TAGS_MULTI));\n      assertFalse(predicate.apply(IMAGE_REPO_TAGS_EMPTY));\n      assertTrue(predicate.apply(IMAGE_REPO_TAGS_WITH_HOST));\n   }\n\n   public void testRepoTagVersionWithHost() {\n      final Predicate<Image> predicate = DockerComputeServiceAdapter\n            .createPredicateMatchingRepoTags(\"docker.io/kwart/alpine-ext:3.3-ssh\");\n      assertFalse(predicate.apply(IMAGE_REPO_TAGS_MULTI));\n      assertFalse(predicate.apply(IMAGE_REPO_TAGS_EMPTY));\n      assertTrue(predicate.apply(IMAGE_REPO_TAGS_WITH_HOST));\n   }\n\n   public void testRepoTagLatestWithHost() {\n      final Predicate<Image> predicate = DockerComputeServiceAdapter\n            .createPredicateMatchingRepoTags(\"docker.io/kwart/alpine-ext\");\n      assertFalse(predicate.apply(IMAGE_REPO_TAGS_MULTI));\n      assertFalse(predicate.apply(IMAGE_REPO_TAGS_EMPTY));\n      assertTrue(predicate.apply(IMAGE_REPO_TAGS_WITH_HOST));\n   }\n\n}\n"
  },
  {
    "path": "apis/docker/src/test/java/org/jclouds/docker/config/DockerParserModuleTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.config;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.docker.domain.Container;\nimport org.jclouds.docker.domain.NetworkSettings;\nimport org.jclouds.docker.domain.Port;\nimport org.jclouds.json.Json;\nimport org.jclouds.json.config.GsonModule;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.inject.Guice;\n\n/**\n * Unit tests for the {@link org.jclouds.docker.config.DockerParserModule} class.\n */\n@Test(groups = \"unit\", testName = \"DockerParserModuleTest\")\npublic class DockerParserModuleTest {\n\n   private Json json = Guice.createInjector(new GsonModule(), new DockerParserModule()).getInstance(Json.class);\n\n   public void testContainerWithVolumesNull() {\n      Container container = json.fromJson(\"{ \\\"Id\\\": \\\"foo\\\", \\\"Volumes\\\": null }\", Container.class);\n      assertNotNull(container);\n      assertEquals(container.id(), \"foo\");\n      assertEquals(container.volumes(), ImmutableMap.of());\n   }\n\n   public void port() {\n      // Note IP, not Ip\n      String text = \"{\\\"IP\\\":\\\"0.0.0.0\\\",\\\"PrivatePort\\\":4567,\\\"PublicPort\\\":49155,\\\"Type\\\":\\\"tcp\\\"}\";\n      Port port = Port.create(\"0.0.0.0\", 4567, 49155, \"tcp\");\n      assertEquals(json.fromJson(text, Port.class), port);\n      assertEquals(json.toJson(port), text);\n   }\n\n   public void networkSettings() {\n      String text = \"{\" +\n              \"\\\"Bridge\\\":\\\"\\\",\" +\n              \"\\\"SandboxID\\\":\\\"3ef128b055eb9ef62a6a2c281d97a2dfde5f47947d490f1dd2a81612611d961f\\\",\" +\n              \"\\\"HairpinMode\\\":false,\" +\n              \"\\\"LinkLocalIPv6Address\\\":\\\"\\\",\" +\n              \"\\\"LinkLocalIPv6PrefixLen\\\":0,\" +\n              \"\\\"Ports\\\":{},\" +\n              \"\\\"SandboxKey\\\":\\\"/var/run/docker/netns/3ef128b055eb\\\",\" +\n              \"\\\"SecondaryIPAddresses\\\":[],\" +\n              \"\\\"SecondaryIPv6Addresses\\\":[],\" +\n              \"\\\"EndpointID\\\":\\\"9e8dcc0c8288938a923018fee0728cee8e6de7c01a5150738ee6e51c1caf8cf6\\\",\" +\n              \"\\\"Gateway\\\":\\\"172.17.0.1\\\",\" +\n              \"\\\"GlobalIPv6Address\\\":\\\"\\\",\" +\n              \"\\\"GlobalIPv6PrefixLen\\\":0,\" +\n              \"\\\"IPAddress\\\":\\\"172.17.0.2\\\",\" +\n              \"\\\"IPPrefixLen\\\":16,\" +\n              \"\\\"IPv6Gateway\\\":\\\"\\\",\" +\n              \"\\\"MacAddress\\\":\\\"02:42:ac:11:00:02\\\",\" +\n              \"\\\"Networks\\\":{\" +\n              \"\\\"bridge\\\":{\" +\n              \"\\\"EndpointID\\\":\\\"9e8dcc0c8288938a923018fee0728cee8e6de7c01a5150738ee6e51c1caf8cf6\\\",\" +\n              \"\\\"Gateway\\\":\\\"172.17.0.1\\\",\" +\n              \"\\\"IPAddress\\\":\\\"172.17.0.2\\\",\" +\n              \"\\\"IPPrefixLen\\\":16,\" +\n              \"\\\"IPv6Gateway\\\":\\\"\\\",\" +\n              \"\\\"GlobalIPv6Address\\\":\\\"\\\",\" +\n              \"\\\"GlobalIPv6PrefixLen\\\":0,\" +\n              \"\\\"MacAddress\\\":\\\"02:42:ac:11:00:02\\\"\" +\n              \"}\" +\n              \"}\" +\n              \"}\";\n      NetworkSettings settings = NetworkSettings.create(\n              \"\", // Bridge\n              \"3ef128b055eb9ef62a6a2c281d97a2dfde5f47947d490f1dd2a81612611d961f\", // SandboxID\n              false, // HairpinMode\n              \"\", // LinkLocalIPv6Address\n              0, // LinkLocalIPv6PrefixLen\n              ImmutableMap.<String, List<Map<String, String>>> of(), // Ports\n              \"/var/run/docker/netns/3ef128b055eb\", // SandboxKey\n              null, // SecondaryIPAddresses\n              null, // SecondaryIPv6Addresses\n              \"9e8dcc0c8288938a923018fee0728cee8e6de7c01a5150738ee6e51c1caf8cf6\", // EndpointID\n              \"172.17.0.1\", // Gateway\n              \"\", // GlobalIPv6Address\n              0, // GlobalIPv6PrefixLen\n              \"172.17.0.2\", // IPAddress\n              16, // IPPrefixLen\n              \"\", // IPv6Gateway\n              \"02:42:ac:11:00:02\", // MacAddress\n              ImmutableMap.of(\n                      \"bridge\", NetworkSettings.Details.create(\n                              \"9e8dcc0c8288938a923018fee0728cee8e6de7c01a5150738ee6e51c1caf8cf6\", // EndpointID\n                              \"172.17.0.1\", // Gateway\n                              \"172.17.0.2\", // IPAddress\n                              16, // IPPrefixLen\n                              \"\", // IPv6Gateway\n                              \"\", // GlobalIPv6Address\n                              0, // GlobalIPv6PrefixLen\n                              \"02:42:ac:11:00:02\" // MacAddress\n                     )\n              ),\n              null // PortMapping\n      );\n\n      assertEquals(json.fromJson(text, NetworkSettings.class), settings);\n      assertEquals(json.toJson(settings), text);\n   }\n}\n"
  },
  {
    "path": "apis/docker/src/test/java/org/jclouds/docker/domain/ConfigTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.domain;\n\nimport static org.assertj.core.api.Assertions.assertThat;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\n\n@Test(groups = \"unit\", testName = \"ConfigTest\")\npublic class ConfigTest {\n\n   @Test\n   public void testFromConfig() {\n      Config origConfig = Config.builder()\n         .hostname(\"6c9932f478bd\")\n         .env(ImmutableList.of(\"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\"))\n         .image(\"57e570db16baba1e8c0d6f3c15868ddb400f64ff76ec948e65c3ca3f15fb3587\")\n         .domainname(\"\")\n         .user(\"\")\n         .cmd(ImmutableList.of(\"-name\", \"7a:63:a2:39:7b:0f\"))\n         .entrypoint(ImmutableList.of(\"/home/weave/weaver\", \"-iface\", \"ethwe\", \"-wait\", \"5\"))\n         .image(\"zettio/weave\")\n         .workingDir(\"/home/weave\")\n         .exposedPorts(ImmutableMap.of(\"6783/tcp\", ImmutableMap.of(), \"6783/udp\", ImmutableMap.of()))\n         .build();\n      Config newConfig = Config.builder().fromConfig(origConfig).build();\n      assertThat(origConfig).isEqualTo(newConfig);\n   }\n\n\n   @Test\n   public void testNullValuesPropagation() {\n      Config config = Config.builder()\n      .image(\"zettio/weave\")\n      .build();\n\n      assertThat(config.cmd()).isNull();\n      assertThat(config.entrypoint()).isNull();\n      assertThat(config.env()).isNull();\n      assertThat(config.hostname()).isNull();\n      assertThat(config.domainname()).isNull();\n      assertThat(config.workingDir()).isNull();\n      assertThat(config.hostConfig()).isNull();\n   }\n}\n"
  },
  {
    "path": "apis/docker/src/test/java/org/jclouds/docker/domain/ContainerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.domain;\n\nimport static org.assertj.core.api.Assertions.assertThat;\n\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ContainerTest\")\npublic class ContainerTest {\n\n   @Test\n   public void testFromContainer() {\n      Container testContainer = Container.builder()\n              .id(\"testcontainer\")\n              .build();\n\n\n      Container newTestContainer = testContainer.toBuilder().build();\n      assertThat(newTestContainer).isEqualTo(testContainer);\n   }\n}\n\n"
  },
  {
    "path": "apis/docker/src/test/java/org/jclouds/docker/features/ContainerApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.features;\n\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.List;\n\nimport org.jclouds.docker.compute.BaseDockerApiLiveTest;\nimport org.jclouds.docker.domain.Config;\nimport org.jclouds.docker.domain.Container;\nimport org.jclouds.docker.domain.ContainerSummary;\nimport org.jclouds.docker.domain.Image;\nimport org.jclouds.docker.domain.Resource;\nimport org.jclouds.docker.options.AttachOptions;\nimport org.jclouds.docker.options.CreateImageOptions;\nimport org.jclouds.docker.options.ListContainerOptions;\nimport org.jclouds.docker.options.RemoveContainerOptions;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"live\", testName = \"RemoteApiLiveTest\", singleThreaded = true)\npublic class ContainerApiLiveTest extends BaseDockerApiLiveTest {\n\n   private Container container = null;\n   protected Image image = null;\n\n   @BeforeClass\n   protected void init() {\n      if (api.getImageApi().inspectImage(ALPINE_IMAGE_TAG) == null) {\n         CreateImageOptions options = CreateImageOptions.Builder.fromImage(ALPINE_IMAGE_TAG);\n         InputStream createImageStream = api.getImageApi().createImage(options);\n         consumeStream(createImageStream);\n      }\n      image = api.getImageApi().inspectImage(ALPINE_IMAGE_TAG);\n      assertNotNull(image);\n   }\n\n   @AfterClass\n   protected void tearDown() {\n      if (container != null) {\n         if (api.getContainerApi().inspectContainer(container.id()) != null) {\n            api.getContainerApi().removeContainer(container.id(), RemoveContainerOptions.Builder.force(true));\n         }\n      }\n   }\n\n   public void testCreateContainer() throws IOException, InterruptedException {\n      Config containerConfig = Config.builder().image(image.id())\n              .cmd(ImmutableList.of(\"/bin/sh\", \"-c\", \"touch hello; while true; do echo hello world; sleep 1; done\"))\n              .build();\n      container = api().createContainer(\"testCreateContainer\", containerConfig);\n      assertNotNull(container);\n      assertNotNull(container.id());\n   }\n\n   @Test(dependsOnMethods = \"testCreateContainer\")\n   public void testStartContainer() throws IOException, InterruptedException {\n      api().startContainer(container.id());\n      assertTrue(api().inspectContainer(container.id()).state().running());\n   }\n\n   @Test(dependsOnMethods = \"testStartContainer\")\n   public void testAttachContainer() throws InterruptedException {\n      // wait 2 seconds - give a container chance to echo the string\n      Thread.sleep(2000L);\n      \n      InputStream attachStream = api().attach(container.id(), AttachOptions.Builder.logs(true).stream(false).stdout(true));\n      String stream = consumeStream(attachStream);\n      assertThat(stream.trim()).contains(\"hello world\");\n   }\n\n   @Test(dependsOnMethods = \"testAttachContainer\")\n   public void testCopyFileFromContainer() {\n      InputStream tarredStream = api().copy(container.id(), Resource.create(\"hello\"));\n      assertNotNull(consumeStream(tarredStream));\n   }\n\n   @Test(dependsOnMethods = \"testCopyFileFromContainer\")\n   public void testPauseContainer() {\n      api().pause(container.id());\n      assertTrue(api().inspectContainer(container.id()).state().paused());\n   }\n\n   @Test(dependsOnMethods = \"testPauseContainer\")\n   public void testUnpauseContainer() {\n      api().unpause(container.id());\n      assertFalse(api().inspectContainer(container.id()).state().paused());\n   }\n\n   @Test(dependsOnMethods = \"testUnpauseContainer\")\n   public void testStopContainer() {\n      api().stopContainer(container.id());\n      assertFalse(api().inspectContainer(container.id()).state().running());\n   }\n\n   @Test(dependsOnMethods = \"testStopContainer\")\n   public void testRestartContainer() {\n      api().restart(container.id());\n      assertTrue(api().inspectContainer(container.id()).state().running());\n   }\n\n   @Test(dependsOnMethods = \"testRestartContainer\")\n   public void testWaitContainer() {\n      api().stopContainer(container.id(), 1);\n      assertEquals(api().wait(container.id()).statusCode(), 137);\n   }\n\n   @Test(dependsOnMethods = \"testWaitContainer\")\n   public void testRemoveContainer() {\n      api().removeContainer(container.id());\n      assertNull(api().inspectContainer(container.id()));\n   }\n\n   @Test\n   public void testListContainers() {\n      List<ContainerSummary> containerSummaries = api().listContainers(ListContainerOptions.Builder.all(true));\n      for (ContainerSummary containerSummary : containerSummaries) {\n         assertNotNull(containerSummary.id());\n         assertNotNull(containerSummary.image());\n         assertFalse(containerSummary.names().isEmpty());\n      }\n   }\n\n   private ContainerApi api() {\n      return api.getContainerApi();\n   }\n}\n"
  },
  {
    "path": "apis/docker/src/test/java/org/jclouds/docker/features/ContainerApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.features;\n\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\n\nimport org.jclouds.docker.DockerApi;\nimport org.jclouds.docker.config.DockerParserModule;\nimport org.jclouds.docker.domain.Config;\nimport org.jclouds.docker.domain.Container;\nimport org.jclouds.docker.domain.Resource;\nimport org.jclouds.docker.internal.BaseDockerMockTest;\nimport org.jclouds.docker.options.ListContainerOptions;\nimport org.jclouds.docker.parse.ContainerParseTest;\nimport org.jclouds.docker.parse.ContainersParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n\n/**\n * Mock tests for the {@link org.jclouds.docker.features.ContainerApi} class.\n */\n@Test(groups = \"unit\", testName = \"ContainerApiMockTest\")\npublic class ContainerApiMockTest extends BaseDockerMockTest {\n\n   public void testListContainers() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(payloadFromResource(\"/containers.json\")));\n      ContainerApi api = api(DockerApi.class, server.url(\"/\").toString()).getContainerApi();\n      try {\n         assertEquals(api.listContainers(), new ContainersParseTest().expected());\n         assertSent(server, \"GET\", \"/containers/json\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testListNonexistentContainers() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(404));\n      ContainerApi api = api(DockerApi.class, server.url(\"/\").toString()).getContainerApi();\n      try {\n         assertEquals(api.listContainers(), ImmutableList.of());\n         assertSent(server, \"GET\", \"/containers/json\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   @Test(timeOut = 10000L)\n   public void testListAllContainers() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(payloadFromResource(\"/containers.json\")));\n      ContainerApi api = api(DockerApi.class, server.url(\"/\").toString()).getContainerApi();\n      try {\n         assertEquals(api.listContainers(ListContainerOptions.Builder.all(true)), new ContainersParseTest().expected());\n         assertSent(server, \"GET\", \"/containers/json?all=true\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGetContainer() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(payloadFromResource(\"/container.json\")));\n      ContainerApi api = api(DockerApi.class, server.url(\"/\").toString(), new DockerParserModule()).getContainerApi();\n      String containerId = \"e475abdf3e139a5e1e158b38b6cb290a1bec856d39d5a951f015dfb8fcba7331\";\n      try {\n         assertEquals(api.inspectContainer(containerId), new ContainerParseTest().expected());\n         assertSent(server, \"GET\", \"/containers/\" + containerId + \"/json\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testCreateContainer() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(payloadFromResource(\"/container-creation.json\")));\n      ContainerApi api = api(DockerApi.class, server.url(\"/\").toString()).getContainerApi();\n      Config containerConfig = Config.builder()\n              .cmd(ImmutableList.of(\"date\"))\n              .attachStdin(false)\n              .attachStderr(true)\n              .attachStdout(true)\n              .tty(false)\n              .image(\"base\")\n              .build();\n      try {\n         Container container = api.createContainer(\"test\", containerConfig);\n         assertSent(server, \"POST\", \"/containers/create?name=test\");\n         assertNotNull(container);\n         assertThat(container.id()).isEqualTo(\"c6c74153ae4b1d1633d68890a68d89c40aa5e284a1ea016cbc6ef0e634ee37b2\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testRemoveContainer() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(204));\n      ContainerApi api = api(DockerApi.class, server.url(\"/\").toString()).getContainerApi();\n      String containerId = \"6d35806c1bd2b25cd92bba2d2c2c5169dc2156f53ab45c2b62d76e2d2fee14a9\";\n\n      try {\n         api.removeContainer(containerId);\n         assertSent(server, \"DELETE\", \"/containers/\" + containerId);\n\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testStartContainer() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(200));\n      ContainerApi api = api(DockerApi.class, server.url(\"/\").toString()).getContainerApi();\n      try {\n         api.startContainer(\"1\");\n         assertSent(server, \"POST\", \"/containers/1/start\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testStopContainer() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(200));\n      ContainerApi api = api(DockerApi.class, server.url(\"/\").toString()).getContainerApi();\n      try {\n         api.stopContainer(\"1\");\n         assertSent(server, \"POST\", \"/containers/1/stop\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n\n   public void testCommitContainer() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(201));\n      ContainerApi api = api(DockerApi.class, server.url(\"/\").toString()).getContainerApi();\n      try {\n         api.commit();\n         assertSent(server, \"POST\", \"/commit\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testPauseContainer() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(204));\n      ContainerApi api = api(DockerApi.class, server.url(\"/\").toString()).getContainerApi();\n      try {\n         api.pause(\"1\");\n         assertSent(server, \"POST\", \"/containers/1/pause\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testUnpauseContainer() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(204));\n      ContainerApi api = api(DockerApi.class, server.url(\"/\").toString()).getContainerApi();\n      try {\n         api.unpause(\"1\");\n         assertSent(server, \"POST\", \"/containers/1/unpause\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testAttachContainer() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(200));\n      ContainerApi api = api(DockerApi.class, server.url(\"/\").toString()).getContainerApi();\n      try {\n         api.attach(\"1\");\n         assertSent(server, \"POST\", \"/containers/1/attach\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testWaitContainer() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(200));\n      ContainerApi api = api(DockerApi.class, server.url(\"/\").toString()).getContainerApi();\n      try {\n         api.wait(\"1\");\n         assertSent(server, \"POST\", \"/containers/1/wait\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testRestartContainer() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(204));\n      ContainerApi api = api(DockerApi.class, server.url(\"/\").toString()).getContainerApi();\n      try {\n         api.restart(\"1\");\n         assertSent(server, \"POST\", \"/containers/1/restart\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testKillContainer() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(204));\n      ContainerApi api = api(DockerApi.class, server.url(\"/\").toString()).getContainerApi();\n      try {\n         api.kill(\"1\");\n         assertSent(server, \"POST\", \"/containers/1/kill\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testCopyFileFromContainer() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(204));\n      ContainerApi api = api(DockerApi.class, server.url(\"/\").toString()).getContainerApi();\n      try {\n         api.copy(\"1\", Resource.create(\"test\"));\n         assertSent(server, \"POST\", \"/containers/1/copy\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/docker/src/test/java/org/jclouds/docker/features/ImageApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.features;\n\nimport static org.assertj.guava.api.Assertions.assertThat;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\n\nimport java.io.InputStream;\nimport java.util.List;\n\nimport org.jclouds.docker.compute.BaseDockerApiLiveTest;\nimport org.jclouds.docker.domain.Image;\nimport org.jclouds.docker.domain.ImageSummary;\nimport org.jclouds.docker.options.CreateImageOptions;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Iterables;\n\n@Test(groups = \"live\", testName = \"ImageApiLiveTest\", singleThreaded = true)\npublic class ImageApiLiveTest extends BaseDockerApiLiveTest {\n\n   private Image image;\n\n   @Test\n   public void testCreateImage() {\n      InputStream createImageStream = api().createImage(CreateImageOptions.Builder.fromImage(DEFAULT_IMAGE).tag(DEFAULT_TAG));\n      consumeStream(createImageStream);\n   }\n\n   @Test(dependsOnMethods = \"testCreateImage\")\n   public void testInspectImage() {\n      image = api.getImageApi().inspectImage(String.format(\"%s:%s\", DEFAULT_IMAGE, DEFAULT_TAG));\n      assertNotNull(image);\n   }\n\n   @Test(dependsOnMethods = \"testInspectImage\")\n   public void testTagImage() {\n      api.getImageApi().tagImage(image.id(), \"jclouds\", \"testTag\", true);\n      Image taggedImage = api.getImageApi().inspectImage(\"jclouds:testTag\");\n      assertEquals(taggedImage.id(), image.id(), \"Newly added image tag should point to the same image ID.\");\n   }\n\n   @Test(dependsOnMethods = \"testTagImage\")\n   public void testListImages() {\n      List<ImageSummary> listImages = api().listImages();\n      assertNotNull(listImages);\n\n      Optional<ImageSummary> summary = Iterables.tryFind(listImages, new Predicate<ImageSummary>() {\n         @Override\n         public boolean apply(ImageSummary input) {\n            return input.repoTags().contains(\"jclouds:testTag\");\n         }\n      });\n      assertThat(summary).isPresent();\n   }\n\n   @Test(dependsOnMethods = \"testListImages\", alwaysRun = true)\n   public void testDeleteImage() {\n      consumeStream(api().deleteImage(String.format(\"%s:%s\", DEFAULT_IMAGE, DEFAULT_TAG)));\n      assertNull(api().inspectImage(String.format(\"%s:%s\", DEFAULT_IMAGE, DEFAULT_TAG)));\n\n      assertNotNull(api().inspectImage(image.id()), \"Image should should still exist after removing original tag. There is a newly added tag referencing it.\");\n      consumeStream(api().deleteImage(\"jclouds:testTag\"));\n      assertNull(api().inspectImage(\"jclouds:testTag\"));\n   }\n\n   private ImageApi api() {\n      return api.getImageApi();\n   }\n\n}\n"
  },
  {
    "path": "apis/docker/src/test/java/org/jclouds/docker/features/ImageApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.List;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\n\nimport org.jclouds.docker.DockerApi;\nimport org.jclouds.docker.config.DockerParserModule;\nimport org.jclouds.docker.domain.ImageHistory;\nimport org.jclouds.docker.internal.BaseDockerMockTest;\nimport org.jclouds.docker.options.CreateImageOptions;\nimport org.jclouds.docker.parse.HistoryParseTest;\nimport org.jclouds.docker.parse.ImageParseTest;\nimport org.jclouds.docker.parse.ImagesParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n\n/**\n * Mock tests for the {@link org.jclouds.docker.features.ImageApi} class.\n */\n@Test(groups = \"unit\", testName = \"ImageApiMockTest\")\npublic class ImageApiMockTest extends BaseDockerMockTest {\n\n   public void testCreateImage() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(200));\n      ImageApi api = api(DockerApi.class, server.url(\"/\").toString()).getImageApi();\n      try {\n         api.createImage(CreateImageOptions.Builder.fromImage(\"base\"));\n         assertSent(server, \"POST\", \"/images/create?fromImage=base\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGetImage() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(payloadFromResource(\"/image.json\")));\n      ImageApi api = api(DockerApi.class, server.url(\"/\").toString(), new DockerParserModule()).getImageApi();\n      try {\n         String imageId = \"cbba6639a342646deed70d7ea6162fa2a0acea9300f911f4e014555fe37d3456\";\n         assertEquals(api.inspectImage(imageId), new ImageParseTest().expected());\n         assertSent(server, \"GET\", \"/images/\" + imageId + \"/json\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testListImages() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(payloadFromResource(\"/images.json\")));\n      ImageApi api = api(DockerApi.class, server.url(\"/\").toString()).getImageApi();\n      try {\n         assertEquals(api.listImages(), new ImagesParseTest().expected());\n         assertSent(server, \"GET\", \"/images/json\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testTagImage() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(201));\n      ImageApi api = api(DockerApi.class, server.url(\"/\").toString()).getImageApi();\n      try {\n         api.tagImage(\"633fcd11259e8d6bccfbb59a4086b95b0d0fb44edfc3912000ef1f70e8a7bfc6\", \"jclouds\", \"testTag\", true);\n         assertSent(server, \"POST\",\n               \"/images/633fcd11259e8d6bccfbb59a4086b95b0d0fb44edfc3912000ef1f70e8a7bfc6/tag?repo=jclouds&tag=testTag&force=true\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testDeleteImage() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(204));\n      ImageApi api = api(DockerApi.class, server.url(\"/\").toString()).getImageApi();\n      try {\n         api.deleteImage(\"1\");\n         assertSent(server, \"DELETE\", \"/images/1\");\n\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGetHistory() throws Exception {\n      MockWebServer server = mockWebServer(\n            new MockResponse().setBody(payloadFromResource(\"/history.json\")),\n            new MockResponse().setBody(payloadFromResource(\"/history-apiver22.json\")),\n            new MockResponse().setResponseCode(404));\n      ImageApi api = api(DockerApi.class, server.url(\"/\").toString()).getImageApi();\n      try {\n         assertEquals(api.getHistory(\"ubuntu\"), new HistoryParseTest().expected());\n         assertSent(server, \"GET\", \"/images/ubuntu/history\");\n\n         // Docker Engine 1.10 (REST API ver 22) doesn't return parent layer IDs\n         assertEquals(api.getHistory(\"fcf9d588ee9ab46c5a888e67f892fac66e6396eb195a743e50c0c5f9a4710e66\"), \n               ImmutableList.of(\n               ImageHistory.create(\"sha256:fcf9d588ee9ab46c5a888e67f892fac66e6396eb195a743e50c0c5f9a4710e66\",\n                     1456304238,\n                     \"\",\n                     ImmutableList.of(\"registry.acme.com:8888/jboss-eap-test/eap-test:1.0-3\"),\n                     188605160,\n                     \"\"),\n               ImageHistory.create(\"<missing>\",\n                     1455838658,\n                     \"\",\n                     null,\n                     195019519,\n                     \"\"),\n               ImageHistory.create(\"<missing>\",\n                     1455812978,\n                     \"\",\n                     null,\n                     203250948,\n                     \"Imported from -\")\n               ));\n         assertSent(server, \"GET\", \"/images/fcf9d588ee9ab46c5a888e67f892fac66e6396eb195a743e50c0c5f9a4710e66/history\");\n\n         // check also if  empty list is returned if the image is not found\n         List<ImageHistory> historyList = api.getHistory(\"missing-image\");\n         assertNotNull(historyList);\n         assertTrue(historyList.isEmpty());\n      } finally {\n         server.shutdown();\n      }\n   }\n}\n"
  },
  {
    "path": "apis/docker/src/test/java/org/jclouds/docker/features/MiscApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.net.URISyntaxException;\n\nimport org.assertj.core.api.Fail;\nimport org.jclouds.docker.compute.BaseDockerApiLiveTest;\nimport org.jclouds.docker.domain.Config;\nimport org.jclouds.docker.domain.Container;\nimport org.jclouds.docker.domain.Exec;\nimport org.jclouds.docker.domain.ExecCreateParams;\nimport org.jclouds.docker.domain.ExecInspect;\nimport org.jclouds.docker.domain.ExecStartParams;\nimport org.jclouds.docker.domain.Image;\nimport org.jclouds.docker.options.BuildOptions;\nimport org.jclouds.docker.options.CreateImageOptions;\nimport org.jclouds.docker.options.RemoveContainerOptions;\nimport org.jclouds.docker.util.DockerInputStream;\nimport org.jclouds.docker.util.StdStreamData;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Iterables;\n\n@Test(groups = \"live\", testName = \"MiscApiLiveTest\", singleThreaded = true)\npublic class MiscApiLiveTest extends BaseDockerApiLiveTest {\n\n   private static final String IMAGE_TEST_TAG = \"jclouds-test-test-build-image\";\n\n   private static String imageId;\n\n   private Container container = null;\n   private Image image = null;\n   private Exec exec = null;\n\n   @BeforeClass\n   protected void init() {\n      if (api.getImageApi().inspectImage(ALPINE_IMAGE_TAG) == null) {\n         CreateImageOptions options = CreateImageOptions.Builder.fromImage(ALPINE_IMAGE_TAG);\n         InputStream createImageStream = api.getImageApi().createImage(options);\n         consumeStream(createImageStream);\n      }\n      image = api.getImageApi().inspectImage(ALPINE_IMAGE_TAG);\n      assertNotNull(image);\n      Config containerConfig = Config.builder().image(image.id())\n            .cmd(ImmutableList.of(\"/bin/sh\", \"-c\", \"touch hello; while true; do echo hello world; sleep 1; done\"))\n            .build();\n      container = api.getContainerApi().createContainer(\"miscApiTest\", containerConfig);\n      assertNotNull(container);\n      api.getContainerApi().startContainer(container.id());\n      assertTrue(api.getContainerApi().inspectContainer(container.id()).state().running());\n   }\n\n   @AfterClass\n   protected void tearDown() {\n      if (container != null) {\n         if (api.getContainerApi().inspectContainer(container.id()) != null) {\n            api.getContainerApi().removeContainer(container.id(), RemoveContainerOptions.Builder.force(true));\n         }\n      }\n      if (image != null) {\n         api.getImageApi().deleteImage(ALPINE_IMAGE_TAG);\n      }\n   }\n\n   @Test\n   public void testVersion() {\n      assertNotNull(api().getVersion().apiVersion());\n      assertNotNull(api().getVersion().version());\n      assertNotNull(api().getVersion().gitCommit());\n      assertNotNull(api().getVersion().goVersion());\n      assertNotNull(api().getVersion().kernelVersion());\n      assertNotNull(api().getVersion().arch());\n      assertNotNull(api().getVersion().os());\n   }\n\n   @Test\n   public void testInfo() {\n      assertNotNull(api().getInfo());\n   }\n\n   @Test\n   public void testBuildImageFromDockerfile() throws IOException, InterruptedException, URISyntaxException {\n      removeImageIfExists(IMAGE_TEST_TAG);\n      BuildOptions options = BuildOptions.Builder.tag(IMAGE_TEST_TAG).verbose(false).nocache(true);\n      InputStream buildImageStream = api().build(tarredDockerfile(), options);\n      String buildStream = consumeStream(buildImageStream);\n      try {\n         Iterable<String> splitted = Splitter.on(\"\\n\").split(buildStream.replace(\"\\r\", \"\").trim());\n         String lastStreamedLine = Iterables.getLast(splitted).trim();\n         String rawImageId = Iterables.getLast(Splitter.on(\"Successfully built \").split(lastStreamedLine));\n         imageId = rawImageId.substring(0, 11);\n         assertNotNull(imageId);\n      } finally {\n         removeImageIfExists(IMAGE_TEST_TAG);\n      }\n   }\n\n   @Test\n   public void testExecCreate() {\n      exec = api().execCreate(container.id(),\n            ExecCreateParams.builder()\n                  .cmd(ImmutableList.<String> of(\"/bin/sh\", \"-c\",\n                        \"echo -n Standard >&1 && echo -n Error >&2 && exit 2\"))\n                  .attachStderr(true).attachStdout(true).build());\n      assertNotNull(exec);\n      assertNotNull(exec.id());\n   }\n\n   @Test(dependsOnMethods = \"testExecCreate\")\n   public void testExecStart() throws IOException {\n      final ExecStartParams startParams = ExecStartParams.builder().detach(false).build();\n      DockerInputStream inputStream = null;\n      try {\n         inputStream = new DockerInputStream(api().execStart(exec.id(), startParams));\n         assertNotNull(inputStream);\n         ByteArrayOutputStream baosOut = new ByteArrayOutputStream();\n         ByteArrayOutputStream baosErr = new ByteArrayOutputStream();\n         StdStreamData data = null;\n         while (null != (data = inputStream.readStdStreamData())) {\n            assertFalse(data.isTruncated());\n            switch (data.getType()) {\n               case OUT:\n                  baosOut.write(data.getPayload());\n                  break;\n               case ERR:\n                  baosErr.write(data.getPayload());\n                  break;\n               default:\n                  Fail.fail(\"Unexpected Stream type\");\n                  break;\n            }\n         }\n         assertEquals(baosOut.toString(), \"Standard\");\n         assertEquals(baosErr.toString(), \"Error\");\n      } finally {\n         if (inputStream != null) {\n            inputStream.close();\n         }\n      }\n   }\n\n   @Test(dependsOnMethods = \"testExecStart\")\n   public void testExecInspect() throws IOException {\n      ExecInspect execInspect = api().execInspect(exec.id());\n      assertNotNull(execInspect);\n      assertEquals(execInspect.id(), exec.id());\n      assertEquals(execInspect.running(), false);\n      assertEquals(execInspect.exitCode(), 2);\n   }\n\n   private MiscApi api() {\n      return api.getMiscApi();\n   }\n\n}\n"
  },
  {
    "path": "apis/docker/src/test/java/org/jclouds/docker/features/MiscApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.features;\n\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.jclouds.docker.compute.BaseDockerApiLiveTest.tarredDockerfile;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.IOException;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Files;\n\nimport jakarta.ws.rs.core.HttpHeaders;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\nimport okhttp3.mockwebserver.RecordedRequest;\n\nimport org.jclouds.docker.DockerApi;\nimport org.jclouds.docker.config.DockerParserModule;\nimport org.jclouds.docker.domain.Exec;\nimport org.jclouds.docker.domain.ExecCreateParams;\nimport org.jclouds.docker.domain.ExecInspect;\nimport org.jclouds.docker.domain.ExecStartParams;\nimport org.jclouds.docker.internal.BaseDockerMockTest;\nimport org.jclouds.docker.parse.InfoParseTest;\nimport org.jclouds.docker.parse.VersionParseTest;\nimport org.jclouds.docker.util.DockerInputStream;\nimport org.jclouds.docker.util.StdStreamData;\nimport org.jclouds.docker.util.StdStreamData.StdStreamType;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n\n/**\n * Mock tests for the {@link org.jclouds.docker.features.MiscApi} class.\n */\n@Test(groups = \"unit\", testName = \"MiscApiMockTest\")\npublic class MiscApiMockTest extends BaseDockerMockTest {\n\n   public void testGetVersion() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(payloadFromResource(\"/version.json\")));\n      MiscApi api = api(DockerApi.class, server.url(\"/\").toString()).getMiscApi();\n      try {\n         assertEquals(api.getVersion(), new VersionParseTest().expected());\n         assertSent(server, \"GET\", \"/version\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGetInfo() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(payloadFromResource(\"/info.json\")));\n      MiscApi api = api(DockerApi.class, server.url(\"/\").toString()).getMiscApi();\n      try {\n         assertEquals(api.getInfo(), new InfoParseTest().expected());\n         assertSent(server, \"GET\", \"/info\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testBuildContainer() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(200));\n      MiscApi api = api(DockerApi.class, server.url(\"/\").toString()).getMiscApi();\n      try {\n         api.build(tarredDockerfile());\n         RecordedRequest request = assertSent(server, \"POST\", \"/build\");\n         assertDockerBuildHttpHeaders(request);\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testBuildContainerUsingPayload() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(200));\n      MiscApi api = api(DockerApi.class, server.url(\"/\").toString()).getMiscApi();\n      File file = Files.createTempFile(\"docker\", \"tmp\").toFile();\n      FileInputStream data = new FileInputStream(file);\n      Payload payload = Payloads.newInputStreamPayload(data);\n      payload.getContentMetadata().setContentLength(file.length());\n      try {\n         api.build(payload);\n         RecordedRequest request = assertSent(server, \"POST\", \"/build\");\n         assertDockerBuildHttpHeaders(request);\n      } finally {\n         server.shutdown();\n      }\n   }\n\n\n   public void testExecCreate() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(payloadFromResource(\"/exec.json\")));\n      MiscApi api = api(DockerApi.class, server.url(\"/\").toString(), new DockerParserModule()).getMiscApi();\n      try {\n         final String containerId = \"a40d212a0a379de00426a1da2a8fd3fd20d5f74fd7c2dd42f6c93a6b1b0e6974\";\n         final ExecCreateParams execParams = ExecCreateParams.builder()\n               .cmd(ImmutableList.<String> of(\"/bin/sh\", \"-c\", \"echo -n Standard >&1 && echo -n Error >&2\"))\n               .attachStderr(true).attachStdout(true).build();\n         final Exec expectedExec = Exec.create(\"dbf45d296388032ebb9872edb75847f6655a72b4e9ab0d99ae1c75589c4ca957\");\n         assertEquals(api.execCreate(containerId, execParams), expectedExec);\n         assertSent(server, \"POST\", \"/containers/\" + containerId + \"/exec\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testExecStart() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(payloadFromResource(\"/exec.start\")));\n      MiscApi api = api(DockerApi.class, server.url(\"/\").toString(), new DockerParserModule()).getMiscApi();\n      DockerInputStream dis = null;\n      try {\n         final String execId = \"dbf45d296388032ebb9872edb75847f6655a72b4e9ab0d99ae1c75589c4ca957\";\n         final ExecStartParams startParams = ExecStartParams.builder().detach(false).build();\n         dis = new DockerInputStream(api.execStart(execId, startParams));\n\n         final StdStreamData msg1 = dis.readStdStreamData();\n         assertFalse(msg1.isTruncated());\n         assertEquals(msg1.getPayload(), \"Standard\".getBytes(StandardCharsets.UTF_8));\n         assertEquals(msg1.getType(), StdStreamType.OUT);\n\n         final StdStreamData msg2 = dis.readStdStreamData();\n         assertFalse(msg2.isTruncated());\n         assertEquals(msg2.getPayload(), \"Error\".getBytes(StandardCharsets.UTF_8));\n         assertEquals(msg2.getType(), StdStreamType.ERR);\n\n         assertNull(dis.readStdStreamData());\n         assertSent(server, \"POST\", \"/exec/\" + execId + \"/start\");\n      } finally {\n         if (dis != null) {\n            dis.close();\n         }\n         server.shutdown();\n      }\n   }\n\n   public void testExecInspect() throws IOException, InterruptedException {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(payloadFromResource(\"/execInspect.json\")));\n      MiscApi api = api(DockerApi.class, server.url(\"/\").toString(), new DockerParserModule()).getMiscApi();\n      final String expectedExecId = \"fda1cf8064863fc0667c691c69793fdb7d0bd4a1fabb8250536abe5203e4208a\";\n      ExecInspect execInspect = api.execInspect(expectedExecId);\n      assertNotNull(execInspect);\n      assertEquals(execInspect.id(), expectedExecId);\n      assertEquals(execInspect.running(), false);\n      assertEquals(execInspect.exitCode(), 2);\n      assertSent(server, \"GET\", \"/exec/\" + expectedExecId + \"/json\");\n   }\n\n   /**\n    * Asserts that correct values of HTTP headers are used in Docker build REST\n    * API calls.\n    *\n    * @param request\n    */\n   private void assertDockerBuildHttpHeaders(RecordedRequest request) {\n      assertThat(request.getHeader(\"Connection\")).isEqualTo(\"close\");\n      assertThat(request.getHeader(HttpHeaders.CONTENT_TYPE)).isEqualTo(\"application/tar\");\n   }\n\n}\n"
  },
  {
    "path": "apis/docker/src/test/java/org/jclouds/docker/features/NetworkApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.features;\n\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.List;\n\nimport org.jclouds.docker.compute.BaseDockerApiLiveTest;\nimport org.jclouds.docker.domain.Config;\nimport org.jclouds.docker.domain.Container;\nimport org.jclouds.docker.domain.Image;\nimport org.jclouds.docker.domain.Network;\nimport org.jclouds.docker.options.CreateImageOptions;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicates;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\n\n@Test(groups = \"live\", testName = \"NetworkApiLiveTest\", singleThreaded = true)\npublic class NetworkApiLiveTest extends BaseDockerApiLiveTest {\n\n   private static final String NETWORK_NAME = \"JCLOUDS_NETWORK\";\n\n   private Network network = null;\n   protected Image image = null;\n   private Container container;\n\n   @BeforeClass\n   protected void init() {\n\n      if (api.getImageApi().inspectImage(ALPINE_IMAGE_TAG) == null) {\n         CreateImageOptions options = CreateImageOptions.Builder.fromImage(ALPINE_IMAGE_TAG);\n         InputStream createImageStream = api.getImageApi().createImage(options);\n         consumeStream(createImageStream);\n      }\n      image = api.getImageApi().inspectImage(ALPINE_IMAGE_TAG);\n      assertNotNull(image);\n\n      Config containerConfig = Config.builder().image(image.id())\n              .cmd(ImmutableList.of(\"sh\", \"-c\", \"touch hello; while true; do echo hello world; sleep 1; done\"))\n              .build();\n      container = api.getContainerApi().createContainer(\"jclouds-test-network\", containerConfig);\n      api.getContainerApi().startContainer(container.id());\n      container = api.getContainerApi().inspectContainer(container.id());\n   }\n\n   @AfterClass(alwaysRun = true)\n   protected void tearDown() {\n      if (container != null) {\n         api.getContainerApi().stopContainer(container.id());\n         api.getContainerApi().removeContainer(container.id());\n      }\n      if (network != null) {\n         api().removeNetwork(network.id());\n      }\n   }\n\n   public void testCreateNetwork() throws IOException, InterruptedException {\n      network = api().createNetwork(Network.create(NETWORK_NAME, null, null, null, null, ImmutableMap.<String, Network.Details> of(), ImmutableMap.<String, String> of()));\n      assertNotNull(network);\n      assertNotNull(network.id());\n   }\n\n   @Test(dependsOnMethods = \"testCreateNetwork\")\n   public void testGetNetwork() {\n      network = api().inspectNetwork(network.id());\n      assertNotNull(network);\n   }\n\n   @Test(dependsOnMethods = \"testGetNetwork\")\n   public void testAttachContainerToNetwork() {\n      api().connectContainerToNetwork(network.id(), container.id());\n      container = api.getContainerApi().inspectContainer(container.id());\n      assertTrue(Iterables.any(container.networkSettings().networks().keySet(), Predicates.equalTo(network.name())));\n   }\n\n   @Test(dependsOnMethods = \"testAttachContainerToNetwork\")\n   public void testDisconnectContainerFromNetwork() {\n      api().disconnectContainerFromNetwork(network.id(), container.id());\n      container = api.getContainerApi().inspectContainer(container.id());\n      assertFalse(Iterables.any(container.networkSettings().networks().keySet(), Predicates.equalTo(network.name())));\n   }\n\n   @Test(dependsOnMethods = \"testCreateNetwork\")\n   public void testListNetworks() {\n      List<Network> networks = api().listNetworks();\n      for (Network network : networks) {\n         assertNotNull(network.id());\n      }\n   }\n\n   @Test(dependsOnMethods = \"testDisconnectContainerFromNetwork\")\n   public void testRemoveNetwork() {\n      api().removeNetwork(network.id());\n      assertNull(api().inspectNetwork(network.id()));\n      network = null;\n   }\n\n   private NetworkApi api() {\n      return api.getNetworkApi();\n   }\n}\n"
  },
  {
    "path": "apis/docker/src/test/java/org/jclouds/docker/features/NetworkApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.features;\n\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport java.util.Map;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\n\nimport org.jclouds.docker.DockerApi;\nimport org.jclouds.docker.config.DockerParserModule;\nimport org.jclouds.docker.domain.Network;\nimport org.jclouds.docker.internal.BaseDockerMockTest;\nimport org.jclouds.docker.parse.NetworkParseTest;\nimport org.jclouds.docker.parse.NetworksParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\n\n\n/**\n * Mock tests for the {@link NetworkApi} class.\n */\n@Test(groups = \"unit\", testName = \"NetworkApiMockTest\")\npublic class NetworkApiMockTest extends BaseDockerMockTest {\n\n   public void testListNetworks() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(payloadFromResource(\"/networks.json\")));\n      NetworkApi api = api(DockerApi.class, server.url(\"/\").toString()).getNetworkApi();\n      try {\n         assertEquals(api.listNetworks(), new NetworksParseTest().expected());\n         assertSent(server, \"GET\", \"/networks\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testListNonexistentNetworks() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(404));\n      NetworkApi api = api(DockerApi.class, server.url(\"/\").toString()).getNetworkApi();\n      try {\n         assertEquals(api.listNetworks(), ImmutableList.of());\n         assertSent(server, \"GET\", \"/networks\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGetNetwork() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(payloadFromResource(\"/network.json\")));\n      NetworkApi api = api(DockerApi.class, server.url(\"/\").toString(), new DockerParserModule()).getNetworkApi();\n      String networkId = \"b03d4cd15b76f8876110615cdeed15eadf77c9beb408d62f1687dcc69192cd6d\";\n      try {\n         assertEquals(api.inspectNetwork(networkId), new NetworkParseTest().expected());\n         assertSent(server, \"GET\", \"/networks/\" + networkId);\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testCreateNetwork() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(payloadFromResource(\"/network-creation.json\")));\n      NetworkApi api = api(DockerApi.class, server.url(\"/\").toString()).getNetworkApi();\n\n      Map<String, String> options = ImmutableMap.<String, String> builder()\n              .put(\"com.docker.network.bridge.default_bridge\", \"true\")\n              .put(\"com.docker.network.bridge.enable_icc\", \"true\")\n              .put(\"com.docker.network.bridge.enable_ip_masquerade\", \"true\")\n              .put(\"com.docker.network.bridge.host_binding_ipv4\", \"0.0.0.0\")\n              .put(\"com.docker.network.bridge.name\", \"docker0\")\n              .put(\"com.docker.network.driver.mtu\", \"1500\")\n              .build();\n\n      Network network = Network.create(\n              \"isolated_nw\", // Name\n              null, // Id\n              \"bridge\", // Driver\n              null, // Scope\n              Network.IPAM.create(\n                      \"default\", // driver\n                      ImmutableList.of(Network.IPAM.Config.create(\"172.17.0.0/16\", null, null)) // config\n              ),\n              ImmutableMap.of(\"39b69226f9d79f5634485fb236a23b2fe4e96a0a94128390a7fbbcc167065867\",\n                      Network.Details.create(\n                              \"ed2419a97c1d9954d05b46e462e7002ea552f216e9b136b80a7db8d98b442eda\", //endpointId\n                              \"02:42:ac:11:00:02\", // MAC\n                              \"172.17.0.2/16\", // ipv4address\n                              \"\" // ipv6address\n                      )\n              ),\n              options);\n\n      try {\n         Network created = api.createNetwork(network);\n         assertNotNull(created);\n         assertThat(created.id()).isEqualTo(\"22be93d5babb089c5aab8dbc369042fad48ff791584ca2da2100db837a1c7c30\");\n         assertSent(server, \"POST\", \"/networks/create\", \"{\\\"Name\\\":\\\"isolated_nw\\\",\\\"Scope\\\":\\\"bridge\\\",\\\"IPAM\\\":{\\\"Driver\\\":\\\"default\\\",\\\"Config\\\":[{\\\"Subnet\\\":\\\"172.17.0.0/16\\\"}]},\\\"Containers\\\":{\\\"39b69226f9d79f5634485fb236a23b2fe4e96a0a94128390a7fbbcc167065867\\\":{\\\"EndpointID\\\":\\\"ed2419a97c1d9954d05b46e462e7002ea552f216e9b136b80a7db8d98b442eda\\\",\\\"MacAddress\\\":\\\"02:42:ac:11:00:02\\\",\\\"IPv4Address\\\":\\\"172.17.0.2/16\\\",\\\"IPv6Address\\\":\\\"\\\"}},\\\"Options\\\":{\\\"com.docker.network.bridge.default_bridge\\\":\\\"true\\\",\\\"com.docker.network.bridge.enable_icc\\\":\\\"true\\\",\\\"com.docker.network.bridge.enable_ip_masquerade\\\":\\\"true\\\",\\\"com.docker.network.bridge.host_binding_ipv4\\\":\\\"0.0.0.0\\\",\\\"com.docker.network.bridge.name\\\":\\\"docker0\\\",\\\"com.docker.network.driver.mtu\\\":\\\"1500\\\"}}\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testRemoveNetwork() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(204));\n      NetworkApi api = api(DockerApi.class, server.url(\"/\").toString()).getNetworkApi();\n      String networkId = \"6d35806c1bd2b25cd92bba2d2c2c5169dc2156f53ab45c2b62d76e2d2fee14a9\";\n      try {\n         api.removeNetwork(networkId);\n         assertSent(server, \"DELETE\", \"/networks/\" + networkId);\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testConnectContainerToNetwork() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(200));\n      NetworkApi api = api(DockerApi.class, server.url(\"/\").toString()).getNetworkApi();\n      try {\n         api.connectContainerToNetwork(\"123456789\", \"containerName\");\n         assertSent(server, \"POST\", \"/networks/123456789/connect\", \"{ \\\"Container\\\": \\\"containerName\\\" }\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testDisconnectContainerFromNetwork() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(200));\n      NetworkApi api = api(DockerApi.class, server.url(\"/\").toString()).getNetworkApi();\n      try {\n         api.disconnectContainerFromNetwork(\"123456789\", \"containerName\");\n         assertSent(server, \"POST\", \"/networks/123456789/disconnect\", \"{ \\\"Container\\\": \\\"containerName\\\" }\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/docker/src/test/java/org/jclouds/docker/internal/BaseDockerMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.internal;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.jclouds.util.Strings2.toStringAndClose;\nimport static org.testng.Assert.assertEquals;\nimport java.io.IOException;\nimport java.util.Properties;\n\nimport jakarta.ws.rs.core.HttpHeaders;\nimport jakarta.ws.rs.core.MediaType;\n\nimport okhttp3.mockwebserver.MockWebServer;\nimport okhttp3.mockwebserver.RecordedRequest;\n\nimport org.jclouds.http.BaseMockWebServerTest;\nimport org.jclouds.http.okhttp.config.OkHttpCommandExecutorServiceModule;\n\nimport com.google.common.base.Throwables;\nimport com.google.gson.JsonParser;\nimport com.google.inject.Module;\n\n\n/**\n * Base class for all Docker mock tests.\n */\npublic class BaseDockerMockTest extends BaseMockWebServerTest {\n\n   protected static final String API_VERSION = \"1.15\";\n\n   @Override\n   protected void addOverrideProperties(Properties properties) {\n      properties.setProperty(\"jclouds.api-version\", API_VERSION);\n   }\n\n   @Override\n   protected Module createConnectionModule() {\n      return new OkHttpCommandExecutorServiceModule();\n   }\n\n   public String payloadFromResource(String resource) {\n      try {\n         return toStringAndClose(getClass().getResourceAsStream(resource));\n      } catch (IOException e) {\n         throw Throwables.propagate(e);\n      }\n   }\n\n   protected RecordedRequest assertSent(MockWebServer server, String method, String path) throws InterruptedException {\n      RecordedRequest request = server.takeRequest();\n      assertThat(request.getMethod()).isEqualTo(method);\n      assertThat(request.getPath()).isEqualTo(\"/v\" + API_VERSION + path);\n      assertThat(request.getHeader(HttpHeaders.ACCEPT)).isEqualTo(MediaType.APPLICATION_JSON);\n      return request;\n   }\n\n   protected RecordedRequest assertSent(MockWebServer server, String method, String path, String json)\n           throws InterruptedException {\n      RecordedRequest request = assertSent(server, method, path);\n      assertEquals(request.getHeader(\"Content-Type\"), APPLICATION_JSON);\n      assertEquals(parser.parse(request.getBody().readUtf8()), parser.parse(json));\n      return request;\n   }\n\n   /** So that we can ignore formatting. */\n   private final JsonParser parser = new JsonParser();\n\n}\n"
  },
  {
    "path": "apis/docker/src/test/java/org/jclouds/docker/internal/BaseDockerParseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.internal;\n\nimport org.jclouds.docker.config.DockerParserModule;\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.json.config.GsonModule;\n\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\npublic abstract class BaseDockerParseTest<T>  extends BaseItemParserTest<T> {\n\n   @Override\n   protected Injector injector() {\n      return Guice.createInjector(new GsonModule(), new DockerParserModule());\n   }\n\n}\n"
  },
  {
    "path": "apis/docker/src/test/java/org/jclouds/docker/internal/DockerTestUtils.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.internal;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.util.logging.Level;\n\nimport org.jclouds.docker.DockerApi;\nimport org.jclouds.docker.features.ImageApi;\nimport org.jclouds.docker.options.DeleteImageOptions;\n\nimport com.google.common.base.Preconditions;\n\n/**\n * Utility methods shared by Docker tests.\n */\npublic class DockerTestUtils {\n\n   /**\n    * Read all data from given {@link InputStream} and throw away all the bits.\n    * If an {@link IOException} occurs, it's not propagated to user. The given InputStream is closed after the read.\n    * \n    * @param is InputStream instance (may be null)\n    */\n   public static void consumeStreamSilently(InputStream is) {\n      if (is == null) {\n         return;\n      }\n      char[] tmpBuff = new char[8 * 1024];\n      // throw everything away\n      InputStreamReader isr = new InputStreamReader(is);\n      try {\n         try {\n            while (isr.read(tmpBuff) > -1) {\n               // empty\n            }\n         } finally {\n            isr.close();\n         }\n      } catch (IOException e) {\n         java.util.logging.Logger.getAnonymousLogger().log(Level.WARNING, \"Error ocured during reading InputStream.\", e);\n      }\n   }\n\n   /**\n    * Removes Docker image if it's present on the Docker host. Docker Image API\n    * is used to inspect and remove image (({@link ImageApi#deleteImage(String)}\n    * method).\n    *\n    * @param dockerApi\n    *           DockerApi instance (must be not-<code>null</code>)\n    * @param imageName\n    *           image to be deleted (must be not-<code>null</code>)\n    */\n   public static void removeImageIfExists(DockerApi dockerApi, String imageName) {\n      Preconditions.checkNotNull(dockerApi, \"DockerApi instance has to be provided\");\n      Preconditions.checkNotNull(imageName, \"Docker image name has to be provided\");\n      final ImageApi imageApi = dockerApi.getImageApi();\n      if (null != imageApi.inspectImage(imageName)) {\n         consumeStreamSilently(imageApi.deleteImage(imageName, DeleteImageOptions.Builder.force(true)));\n      }\n   }\n}\n"
  },
  {
    "path": "apis/docker/src/test/java/org/jclouds/docker/parse/ContainerParseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.parse;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.docker.domain.Config;\nimport org.jclouds.docker.domain.Container;\nimport org.jclouds.docker.domain.HostConfig;\nimport org.jclouds.docker.domain.NetworkSettings;\nimport org.jclouds.docker.domain.Node;\nimport org.jclouds.docker.domain.State;\nimport org.jclouds.docker.internal.BaseDockerParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\n\n@Test(groups = \"unit\")\npublic class ContainerParseTest extends BaseDockerParseTest<Container> {\n\n   @Override\n   public String resource() {\n      return \"/container.json\";\n   }\n\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Container expected() {\n      return Container.builder()\n              .id(\"6c9932f478bd761f32ddb54ed28ab42ab6fac6f2a279f561ea31503ee9d39524\")\n              .created(new SimpleDateFormatDateService().iso8601DateParse(\"2014-10-31T17:00:21.544197943Z\"))\n              .path(\"/home/weave/weaver\")\n              .name(\"/weave\")\n              .args(ImmutableList.of(\"-iface\", \"ethwe\", \"-wait\", \"5\", \"-name\", \"7a:63:a2:39:7b:0f\"))\n              .config(Config.builder()\n                      .hostname(\"6c9932f478bd\")\n                      .env(ImmutableList.of(\"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\"))\n                      .image(\"zettio/weave\")\n                      .domainname(\"\")\n                      .user(\"\")\n                      .cmd(ImmutableList.of(\"-name\", \"7a:63:a2:39:7b:0f\"))\n                      .entrypoint(ImmutableList.of(\"/home/weave/weaver\", \"-iface\", \"ethwe\", \"-wait\", \"5\"))\n                      .workingDir(\"/home/weave\")\n                      .exposedPorts(ImmutableMap.of(\"6783/tcp\", ImmutableMap.of(), \"6783/udp\", ImmutableMap.of()))\n                      .build())\n              .state(State.create(10357, true, 0, \"2015-11-10T09:33:21.68146124Z\", \"0001-01-01T00:00:00Z\", false, false, \"running\", false, false, \"\"))\n              .image(\"57e570db16baba1e8c0d6f3c15868ddb400f64ff76ec948e65c3ca3f15fb3587\")\n              .networkSettings(NetworkSettings.builder()\n                      .sandboxId(\"3ef128b055eb9ef62a6a2c281d97a2dfde5f47947d490f1dd2a81612611d961f\")\n                      .hairpinMode(false)\n                      .linkLocalIPv6Address(\"\")\n                      .linkLocalIPv6PrefixLen(0)\n                      .globalIPv6Address(\"\")\n                      .globalIPv6PrefixLen(0)\n                      .ipv6Gateway(\"\")\n                      .sandboxKey(\"/var/run/docker/netns/3ef128b055eb\")\n                      .endpointId(\"9e8dcc0c8288938a923018fee0728cee8e6de7c01a5150738ee6e51c1caf8cf6\")\n                      .ipAddress(\"172.17.0.2\")\n                      .ipPrefixLen(16)\n                      .gateway(\"172.17.0.1\")\n                      .bridge(\"\")\n                      .ports(ImmutableMap.<String, List<Map<String, String>>>of())\n                      .macAddress(\"02:42:ac:11:00:02\")\n                      .networks(ImmutableMap.of(\n                              \"JCLOUDS_NETWORK\", NetworkSettings.Details.create(\n                                      \"04268fbb4dc368b5a53bb1c3f89294a4f0c72095deb944db3c4efc6d6a439304\",\n                                      \"172.19.0.1\",\n                                      \"172.19.0.2\",\n                                      16,\n                                      \"\",\n                                      \"\",\n                                      0,\n                                      \"02:42:ac:13:00:02\"\n                              ),\n                              \"bridge\", NetworkSettings.Details.create(\n                                      \"9e8dcc0c8288938a923018fee0728cee8e6de7c01a5150738ee6e51c1caf8cf6\",\n                                      \"172.17.0.1\",\n                                      \"172.17.0.2\",\n                                      16,\n                                      \"\",\n                                      \"\",\n                                      0,\n                                      \"02:42:ac:11:00:02\"\n                              )\n                      ))\n                      .build())\n              .resolvConfPath(\"/var/lib/docker/containers/6c9932f478bd761f32ddb54ed28ab42ab6fac6f2a279f561ea31503ee9d39524/resolv.conf\")\n              .hostConfig(HostConfig.builder()\n                      .containerIDFile(\"\")\n                      .portBindings(ImmutableMap.<String, List<Map<String, String>>>of(\n                                      \"6783/tcp\", ImmutableList.<Map<String, String>>of(ImmutableMap.of(\"HostIp\", \"\", \"HostPort\", \"6783\")),\n                                      \"6783/udp\", ImmutableList.<Map<String, String>>of(ImmutableMap.of(\"HostIp\", \"\", \"HostPort\", \"6783\")))\n                      )\n                      .capAdd(ImmutableList.of(\"NET_ADMIN\"))\n                      .capDrop(ImmutableList.of(\"MKNOD\"))\n                      .dns(ImmutableList.of(\"8.8.8.8\", \"8.8.4.4\"))\n                      .extraHosts(ImmutableList.<String>of(\"extra:169.254.0.1\"))\n                      .privileged(true)\n                      .networkMode(\"bridge\")\n                      .restartPolicy(ImmutableMap.<String, String> of(\"MaximumRetryCount\", \"0\", \"Name\", \"\"))\n                      .build())\n              .driver(\"aufs\")\n              .execDriver(\"native-0.2\")\n              .hostnamePath(\"/var/lib/docker/containers/6c9932f478bd761f32ddb54ed28ab42ab6fac6f2a279f561ea31503ee9d39524/hostname\")\n              .hostsPath(\"/var/lib/docker/containers/6c9932f478bd761f32ddb54ed28ab42ab6fac6f2a279f561ea31503ee9d39524/hosts\")\n              .mountLabel(\"\")\n              .processLabel(\"\")\n              .node(Node.builder().\n                      ip(\"10.10.10.10\").build())\n              .build();\n   }\n}\n"
  },
  {
    "path": "apis/docker/src/test/java/org/jclouds/docker/parse/ContainerVersionMajor1Minor21.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.parse;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.docker.domain.Config;\nimport org.jclouds.docker.domain.Container;\nimport org.jclouds.docker.domain.HostConfig;\nimport org.jclouds.docker.domain.NetworkSettings;\nimport org.jclouds.docker.domain.State;\nimport org.jclouds.docker.internal.BaseDockerParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * This class tests Containers and Config parsing for Docker API in version 1.21. The input JSON comes from examples in \n * <a href=\"https://docs.docker.com/engine/reference/api/docker_remote_api_v1.21/\">Docker Remote API documentation 1.21</a>.\n * <p>\n * Two modifications were made in the \"/container-1.21-create.json\" due to incompatible types \n * <ul>\n * <li>the Entrypoint field value was changed from String to List<li>\n * <li>the LxcConf field value was changed from Map to List</li>\n * <ul>\n */\npublic class ContainerVersionMajor1Minor21 {\n\n   @Test(groups = \"unit\")\n   public static class CreateTest  extends BaseDockerParseTest<Config> {\n      @Override\n      public String resource() {\n         return \"/container-1.21-create.json\";\n      }\n\n      @Override\n      @Consumes(MediaType.APPLICATION_JSON)\n      public Config expected() {\n         return Config.builder()\n                     .hostname(\"\")\n                     .domainname(\"\")\n                     .user(\"\")\n                     .attachStdin(false)\n                     .attachStdout(true)\n                     .attachStderr(true)\n                     .tty(false)\n                     .openStdin(false)\n                     .stdinOnce(false)\n                     .env(ImmutableList.of(\"FOO=bar\", \"BAZ=quux\"))\n                     .cmd(ImmutableList.of(\"date\"))\n                     //original value of the \"Entrypoint\" in JSON doesn't contain List but String! \n                     //Both types are allowed by docker Remote API, but we are not able to parse both.\n                     .entrypoint(ImmutableList.of(\"\"))\n                     .image(\"ubuntu\")\n//                     \"Labels\": {\n//                        \"com.example.vendor\": \"Acme\",\n//                        \"com.example.license\": \"GPL\",\n//                        \"com.example.version\": \"1.0\"\n//                      },\n                     .volumes(ImmutableMap.of(\"/volumes/data\", ImmutableMap.of()))\n                     .workingDir(\"\")\n                     .networkDisabled(false)\n//                     \"MacAddress\": \"12:34:56:78:9a:bc\",\n                     .exposedPorts(ImmutableMap.of(\"22/tcp\", ImmutableMap.of()))\n//                     \"StopSignal\": \"SIGTERM\",\n                     .hostConfig(HostConfig.builder()\n                           .binds(ImmutableList.of(\"/tmp:/tmp\"))\n                           .links(ImmutableList.of(\"redis3:redis\"))\n                           //The LxcConf causes the type mismatch too (Map vs List<Map>)\n                           .lxcConf(ImmutableList.<Map<String, String>> of(\n                                 ImmutableMap.<String, String> of(\"lxc.utsname\", \"docker\")))\n//                           \"Memory\": 0,\n//                           \"MemorySwap\": 0,\n//                           \"MemoryReservation\": 0,\n//                           \"KernelMemory\": 0,\n//                           \"CpuShares\": 512,\n//                           \"CpuPeriod\": 100000,\n//                           \"CpuQuota\": 50000,\n//                           \"CpusetCpus\": \"0,1\",\n//                           \"CpusetMems\": \"0,1\",\n//                           \"BlkioWeight\": 300,\n//                           \"MemorySwappiness\": 60,\n//                           \"OomKillDisable\": false,\n                           .portBindings(ImmutableMap.<String, List<Map<String, String>>> of(\n                                 \"22/tcp\", ImmutableList.<Map<String, String>> of(ImmutableMap.of(\"HostPort\", \"11022\"))))\n                           .publishAllPorts(false)\n                           .privileged(false)\n//                           \"ReadonlyRootfs\": false,\n                           .dns(ImmutableList.of(\"8.8.8.8\"))\n//                           \"DnsOptions\": [\"\"],\n                           .dnsSearch(ImmutableList.of(\"\"))\n                           .extraHosts(null)\n                           .volumesFrom(ImmutableList.of(\"parent\", \"other:ro\"))\n                           .capAdd(ImmutableList.of(\"NET_ADMIN\"))\n                           .capDrop(ImmutableList.of(\"MKNOD\"))\n//                           \"GroupAdd\": [\"newgroup\"],\n                           .restartPolicy(ImmutableMap.of(\"Name\", \"\", \"MaximumRetryCount\", \"0\"))\n                           .networkMode(\"bridge\")\n//                           \"Devices\": [],\n//                           \"Ulimits\": [{}],                           \n//                           \"LogConfig\": { \"Type\": \"json-file\", \"Config\": {} },\n                           .securityOpt(ImmutableList.<String>of())\n//                           \"CgroupParent\": \"\",\n//                           \"VolumeDriver\": \"\"\n                           .build()\n      )\n                     .build();\n      }\n   }\n   \n   @Test(groups = \"unit\")\n   public static class InspectTest  extends BaseDockerParseTest<Container> {\n      @Override\n      public String resource() {\n         return \"/container-1.21-inspect.json\";\n      }\n\n      @Override\n      @Consumes(MediaType.APPLICATION_JSON)\n      public Container expected() {\n         return Container.builder()\n//            \"AppArmorProfile\": \"\",\n               .args(ImmutableList.<String>of(\"-c\", \"exit 9\"))\n               .config(Config.builder()\n                     .attachStderr(true)\n                     .attachStdin(false)\n                     .attachStdout(true)\n                     .cmd(ImmutableList.<String> of(\"/bin/sh\", \"-c\", \"exit 9\"))\n                     .domainname(\"\")\n                     .entrypoint(null)\n                     .env(ImmutableList.<String> of(\"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\"))\n                     .exposedPorts(null)\n                     .hostname(\"ba033ac44011\")\n                     .image(\"ubuntu\")                    \n//                \"Labels\": {\n//                    \"com.example.vendor\": \"Acme\",\n//                    \"com.example.license\": \"GPL\",\n//                    \"com.example.version\": \"1.0\"\n//                },\n//                \"MacAddress\": \"\",\n                     .networkDisabled(false)\n//                \"OnBuild\": null,\n                     .openStdin(false)\n                     .stdinOnce(false)\n                     .tty(false)\n                     .user(\"\")\n                     .volumes(null)\n                     .workingDir(\"\")\n//                \"StopSignal\": \"SIGTERM\"\n                     .build())\n               .created(new SimpleDateFormatDateService().iso8601DateParse(\"2015-01-06T15:47:31.485331387Z\"))\n               .driver(\"devicemapper\")\n               .execDriver(\"native-0.2\")\n//            \"ExecIDs\": null,\n               .hostConfig(HostConfig.builder()\n                     .binds(null)\n//                \"BlkioWeight\": 0,\n                     .capAdd(null)\n                     .capDrop(null)\n                     .containerIDFile(\"\")\n//                \"CpusetCpus\": \"\",\n//                \"CpusetMems\": \"\",\n//                \"CpuShares\": 0,\n//                \"CpuPeriod\": 100000,\n//                \"Devices\": [],\n                     .dns(null)\n//                \"DnsOptions\": null,\n                     .dnsSearch(null)\n                     .extraHosts(null)\n//                \"IpcMode\": \"\",\n                     .links(null)\n                     .lxcConf(ImmutableList.<Map<String, String>> of())\n//                \"Memory\": 0,\n//                \"MemorySwap\": 0,\n//                \"MemoryReservation\": 0,\n//                \"KernelMemory\": 0,\n//                \"OomKillDisable\": false,\n                     .networkMode(\"bridge\")\n                     .portBindings(ImmutableMap.<String, List<Map<String, String>>> of())\n                     .privileged(false)\n//                \"ReadonlyRootfs\": false,\n                     .publishAllPorts(false)\n                     .restartPolicy(ImmutableMap.<String, String> of(\"MaximumRetryCount\", \"2\", \"Name\", \"on-failure\"))\n//                \"LogConfig\": {\n//                    \"Config\": null,\n//                    \"Type\": \"json-file\"\n//                },\n                     .securityOpt(null)\n                     .volumesFrom(null)\n//                \"Ulimits\": [{}],\n//                \"VolumeDriver\": \"\"\n                     .build())\n               .hostnamePath(\"/var/lib/docker/containers/ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39/hostname\")\n               .hostsPath(\"/var/lib/docker/containers/ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39/hosts\")\n//            \"LogPath\": \"/var/lib/docker/containers/1eb5fabf5a03807136561b3c00adcd2992b535d624d5e18b6cdc6a6844d9767b/1eb5fabf5a03807136561b3c00adcd2992b535d624d5e18b6cdc6a6844d9767b-json.log\",\n               .id(\"ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39\")\n               .image(\"04c5d3b7b0656168630d3ba35d8889bd0e9caafcaeb3004d2bfbc47e7c5d35d2\")\n               .mountLabel(\"\")\n               .name(\"/boring_euclid\")\n               .networkSettings(NetworkSettings.builder()\n                     .bridge(\"\")\n                     .sandboxId(\"\")\n                     .hairpinMode(false)\n                     .linkLocalIPv6Address(\"\")\n                     .linkLocalIPv6PrefixLen(0)\n                     .ports(null)\n                     .sandboxKey(\"\")\n                     .secondaryIPAddresses(null)\n                     .secondaryIPv6Addresses(null)\n                     .endpointId(\"\")\n                     .gateway(\"\")\n                     .globalIPv6Address(\"\")\n                     .globalIPv6PrefixLen(0)\n                     .ipAddress(\"\")\n                     .ipPrefixLen(0)\n                     .ipv6Gateway(\"\")\n                     .macAddress(\"\")\n                     .networks(ImmutableMap.<String, NetworkSettings.Details> of(\n                           \"bridge\", NetworkSettings.Details.create(\"\", \"\", \"\", 0, \"\", \"\", 0, \"\")))\n                     .build())\n               .path(\"/bin/sh\")\n               .node(null)\n               .processLabel(\"\")\n               .resolvConfPath(\"/var/lib/docker/containers/ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39/resolv.conf\")\n//            \"RestartCount\": 1,\n               .state(State.create(0, true, 9, \"2015-01-06T15:47:32.072697474Z\", \"2015-01-06T15:47:32.080254511Z\", false, false, \"running\", false,\n                     // We don't have the \"Dead\" field in this API version! \n                     false, \n                     \"\"\n//                \"Paused\": false,\n//                \"Running\": true,\n                     ))\n//            \"Mounts\": [\n//                {\n//                    \"Source\": \"/data\",\n//                    \"Destination\": \"/data\",\n//                    \"Mode\": \"ro,Z\",\n//                    \"RW\": false\n//                }\n               .build();\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/docker/src/test/java/org/jclouds/docker/parse/ContainersParseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.parse;\n\nimport java.util.List;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.docker.domain.ContainerSummary;\nimport org.jclouds.docker.domain.Port;\nimport org.jclouds.docker.internal.BaseDockerParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\")\npublic class ContainersParseTest extends BaseDockerParseTest<List<ContainerSummary>> {\n\n   @Override\n   public String resource() {\n      return \"/containers.json\";\n   }\n\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   public List<ContainerSummary> expected() {\n      return ImmutableList.of(ContainerSummary.create(\n            \"6d35806c1bd2b25cd92bba2d2c2c5169dc2156f53ab45c2b62d76e2d2fee14a9\", ImmutableList.of(\"/hopeful_mclean\"),\n            \"1395472605\", \"jclouds/ubuntu:latest\", \"/usr/sbin/sshd -D\",\n            ImmutableList.of(Port.create(\"0.0.0.0\", 22, 49231, \"tcp\")), \"Up 55 seconds\"), ContainerSummary.create(\n            \"6d35806c1bd2b25cd92bba2d2c2c5169dc2156f53ab45c2b62d76e2d2fee14a2\", ImmutableList.of(\"/hopeful_mclean\"),\n            \"1395472605\", \"jclouds/ubuntu:latest\", \"/usr/sbin/sshd -D\",\n            ImmutableList.of(Port.create(null, 22, null, \"tcp\")), \"Up 55 seconds\"));\n   }\n\n}\n"
  },
  {
    "path": "apis/docker/src/test/java/org/jclouds/docker/parse/HistoryParseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.parse;\n\nimport java.util.List;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.docker.domain.ImageHistory;\nimport org.jclouds.docker.internal.BaseDockerParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\")\npublic class HistoryParseTest extends BaseDockerParseTest<List<ImageHistory>> {\n\n   @Override\n   public String resource() {\n      return \"/history.json\";\n   }\n\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   public List<ImageHistory> expected() {\n      return ImmutableList.of(\n            ImageHistory.create(\"3db9c44f45209632d6050b35958829c3a2aa256d81b9a7be45b362ff85c54710\",\n                  1398108230,\n                  \"/bin/sh -c #(nop) ADD file:eb15dbd63394e063b805a3c32ca7bf0266ef64676d5a6fab4801f2e81e2a5148 in /\",\n                  ImmutableList.of(\"ubuntu:lucid\", \"ubuntu:10.04\"),\n                  182964289,\n                  \"\"),\n            ImageHistory.create(\"6cfa4d1f33fb861d4d114f43b25abd0ac737509268065cdfd69d544a59c85ab8\",\n                  1398108222,\n                  \"/bin/sh -c #(nop) MAINTAINER Tianon Gravi <admwiggin@gmail.com> - mkimage-debootstrap.sh -i iproute,iputils-ping,ubuntu-minimal -t lucid.tar.xz lucid http://archive.ubuntu.com/ubuntu/\",\n                  null,\n                  0,\n                  \"\"),\n            ImageHistory.create(\"511136ea3c5a64f264b78b5433614aec563103b4d4702f3ba7d4d2698e22c158\",\n                  1371157430,\n                  \"\",\n                  ImmutableList.of(\"scratch12:latest\", \"scratch:latest\"),\n                  0,\n                  \"Imported from -\")\n            );\n   }\n\n}\n"
  },
  {
    "path": "apis/docker/src/test/java/org/jclouds/docker/parse/ImageParseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.parse;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.docker.domain.Config;\nimport org.jclouds.docker.domain.Image;\nimport org.jclouds.docker.internal.BaseDockerParseTest;\nimport org.testng.annotations.Test;\n\nimport com.beust.jcommander.internal.Maps;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\n\n@Test(groups = \"unit\")\npublic class ImageParseTest extends BaseDockerParseTest<Image> {\n\n   @Override\n   public String resource() {\n      return \"/image.json\";\n   }\n\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Image expected() {\n      return Image.create(\"cbba6639a342646deed70d7ea6162fa2a0acea9300f911f4e014555fe37d3456\",\n              \"author\",\n              \"comment\",\n              Config.builder().cmd(ImmutableList.of(\"/bin/sh\", \"-c\", \"echo hello world\"))\n                      .env(ImmutableList.of(\n                                      \"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\",\n                                      \"HOME=/root\",\n                                      \"JAVA_HOME=/usr/lib/jvm/java-7-openjdk-amd64\"\n                              )\n                      )\n                      .exposedPorts(ImmutableMap.of(\"8081/tcp\", Maps.newHashMap()))\n                      .hostname(\"f22711318734\")\n                      .domainname(\"\")\n                      .user(\"user\")\n                      .image(\"05794515afd5724df1cdf0e674ae932455fce7dea3c70a94d77119ad1fa954ba\")\n                      .workingDir(\"/home/user\")\n                      .build(),\n              Config.builder().cmd(ImmutableList.of(\"/bin/sh\", \"-c\", \"echo hello world\"))\n                      .env(ImmutableList.of(\n                                      \"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\",\n                                      \"HOME=/root\",\n                                      \"JAVA_HOME=/usr/lib/jvm/java-7-openjdk-amd64\")\n                      )\n                      .exposedPorts(ImmutableMap.of(\"8081/tcp\", Maps.newHashMap()))\n                      .hostname(\"f22711318734\")\n                      .domainname(\"\")\n                      .user(\"user\")\n                      .image(\"05794515afd5724df1cdf0e674ae932455fce7dea3c70a94d77119ad1fa954ba\")\n                      .workingDir(\"/home/user\")\n                      .build(),\n              \"05794515afd5724df1cdf0e674ae932455fce7dea3c70a94d77119ad1fa954ba\",\n              new SimpleDateFormatDateService().iso8601DateParse(\"2014-11-24T11:09:20.310023104Z\"),\n              \"0d14967353dbbd2ee78abe209f026f71654da49692fa2b044296ec3c810027b3\",\n              \"1.3.1\",\n              \"amd64\",\n              \"linux\",\n              0,\n              808709069,\n              null);\n   }\n}\n"
  },
  {
    "path": "apis/docker/src/test/java/org/jclouds/docker/parse/ImagesParseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.parse;\n\nimport java.util.List;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.docker.domain.ImageSummary;\nimport org.jclouds.docker.internal.BaseDockerParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\")\npublic class ImagesParseTest extends BaseDockerParseTest<List<ImageSummary>> {\n\n   @Override\n   public String resource() {\n      return \"/images.json\";\n   }\n\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   public List<ImageSummary> expected() {\n      return ImmutableList.of(\n            ImageSummary.create(\"d7057cb020844f245031d27b76cb18af05db1cc3a96a29fa7777af75f5ac91a3\",\n                  1442866547,\n                  \"cfa753dfea5e68a24366dfba16e6edf573daa447abf65bc11619c1a98a3aff54\",\n                  0,\n                  1095501,\n                  ImmutableList.of(\"docker.io/busybox:1.23.2\", \"docker.io/busybox:latest\")),\n            ImageSummary.create(\"633fcd11259e8d6bccfbb59a4086b95b0d0fb44edfc3912000ef1f70e8a7bfc6\",\n                  1442598293,\n                  \"b65c936b5fb601d680ed656b1ccf8ab857c0e5cb521043a005405c194e9a69f3\",\n                  0,\n                  5607885,\n                  ImmutableList.of(\"docker.io/busybox:ubuntu-14.04\", \"jclouds:testTag\")),\n            ImageSummary.create(\"f4fddc471ec22fc1f7d37768132f1753bc171121e30ac2af7fcb0302588197c0\",\n                  1442260874,\n                  \"\",\n                  5244426,\n                  5244426,\n                  ImmutableList.of(\"docker.io/alpine:3.2\")),\n            ImageSummary.create(\"91e54dfb11794fad694460162bf0cb0a4fa710cfa3f60979c177d920813e267c\",\n                  1440102075,\n                  \"d74508fb6632491cea586a1fd7d748dfc5274cd6fdfedee309ecdcbc2bf5cb82\",\n                  0,\n                  188333286,\n                  ImmutableList.of(\"docker.io/ubuntu:14.04\", \"docker.io/ubuntu:latest\"))\n      );\n   }\n\n}\n"
  },
  {
    "path": "apis/docker/src/test/java/org/jclouds/docker/parse/Info2ParseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.parse;\n\nimport java.util.List;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.docker.domain.Info;\nimport org.jclouds.docker.internal.BaseDockerParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\")\npublic class Info2ParseTest extends BaseDockerParseTest<Info> {\n\n   @Override\n   public String resource() {\n      return \"/info2.json\";\n   }\n\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Info expected() {\n      return Info.create(\n              0, // containers\n              false, // debug\n              \"aufs\", // driver\n              ImmutableList.<List<String>>of(\n                      ImmutableList.of(\"Root Dir\", \"/var/lib/docker/aufs\"),\n                      ImmutableList.of(\"Backing Filesystem\", \"extfs\"),\n                      ImmutableList.of(\"Dirs\", \"117\"),\n                      ImmutableList.of( \"Dirperm1 Supported\", \"true\")\n              ), // driverStatus\n              \"\", // ExecutionDriver\n              true, // IPv4Forwarding\n              39, // Images\n              \"https://index.docker.io/v1/\", // IndexServerAddress\n              null, // InitPath\n              null, // InitSha1\n              \"4.4.0-22-generic\", // KernelVersion\n              true, // MemoryLimit\n              0, // NEventsListener\n              33, // NFd\n              83, // NGoroutines\n              \"Ubuntu 16.04 LTS\", // OperatingSystem\n              false, // SwapLimit\n              \"/var/lib/docker\", // DockerRootDir\n              null, // Labels\n              8248356864L, // MemTotal\n              4, // NCPU\n              \"KFWR:PMVY:BEWE:TD52:5WEU:NXF4:I6S3:WDIE:GCRD:L3YA:VWC4:ZRYZ\", // ID\n              \"test\" // name\n      );\n   }\n}\n"
  },
  {
    "path": "apis/docker/src/test/java/org/jclouds/docker/parse/InfoParseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.parse;\n\nimport java.util.List;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.docker.domain.Info;\nimport org.jclouds.docker.internal.BaseDockerParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\")\npublic class InfoParseTest extends BaseDockerParseTest<Info> {\n\n   @Override\n   public String resource() {\n      return \"/info.json\";\n   }\n\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Info expected() {\n      return Info.create(\n              0, // containers\n              true, // debug\n              \"aufs\", // driver\n              ImmutableList.<List<String>>of(\n                      ImmutableList.of(\"Root Dir\", \"/mnt/sda1/var/lib/docker/aufs\"),\n                      ImmutableList.of(\"Dirs\", \"46\")\n              ), // driverStatus\n              \"native-0.2\", // ExecutionDriver\n              true, // IPv4Forwarding\n              46, // Images\n              \"https://index.docker.io/v1/\", // IndexServerAddress\n              \"/usr/local/bin/docker\", // InitPath\n              \"\", // InitSha1\n              \"3.16.7-tinycore64\", // KernelVersion\n              true, // MemoryLimit\n              0, // NEventsListener\n              10, // NFd\n              11, // NGoroutines\n              \"Boot2Docker 1.4.1 (TCL 5.4); master : 86f7ec8 - Tue Dec 16 23:11:29 UTC 2014\", // OperatingSystem\n              true, // SwapLimit\n              \"/mnt/sda1/var/lib/docker\", // DockerRootDir\n              null, // Labels\n              2105585664, // MemTotal\n              8, // NCPU\n              \"7V5Y:IQ2M:HWIL:AZJV:HKRD:Q7OZ:3EQA:ZHMO:4LAD:OSIY:YBAA:BSX6\", // ID\n              \"boot2docker\" // name\n      );\n   }\n}\n"
  },
  {
    "path": "apis/docker/src/test/java/org/jclouds/docker/parse/NetworkParseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.parse;\n\nimport java.util.Map;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.docker.domain.Network;\nimport org.jclouds.docker.internal.BaseDockerParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\n\n@Test(groups = \"unit\")\npublic class NetworkParseTest extends BaseDockerParseTest<Network> {\n\n   @Override\n   public String resource() {\n      return \"/network.json\";\n   }\n\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Network expected() {\n\n      Map<String, String> options = ImmutableMap.<String, String> builder()\n              .put(\"com.docker.network.bridge.default_bridge\", \"true\")\n              .put(\"com.docker.network.bridge.enable_icc\", \"true\")\n              .put(\"com.docker.network.bridge.enable_ip_masquerade\", \"true\")\n              .put(\"com.docker.network.bridge.host_binding_ipv4\", \"0.0.0.0\")\n              .put(\"com.docker.network.bridge.name\", \"docker0\")\n              .put(\"com.docker.network.driver.mtu\", \"1500\")\n              .build();\n\n      return Network.create(\n              \"bridge\", // Name\n              \"f2de39df4171b0dc801e8002d1d999b77256983dfc63041c0f34030aa3977566\", // Id\n              \"local\", // Scope\n              \"bridge\", // Driver\n              Network.IPAM.create(\n                      \"default\", // driver\n                      ImmutableList.of(Network.IPAM.Config.create(\"172.17.0.0/16\", null, null)) // config\n              ),\n              ImmutableMap.of(\"39b69226f9d79f5634485fb236a23b2fe4e96a0a94128390a7fbbcc167065867\",\n                      Network.Details.create(\n                      \"ed2419a97c1d9954d05b46e462e7002ea552f216e9b136b80a7db8d98b442eda\", //endpointId\n                      \"02:42:ac:11:00:02\", // MAC\n                      \"172.17.0.2/16\", // ipv4address\n                      \"\" // ipv6address\n                      )\n              ),\n              options);\n   }\n}\n"
  },
  {
    "path": "apis/docker/src/test/java/org/jclouds/docker/parse/NetworksParseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.parse;\n\nimport java.util.List;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.docker.domain.Network;\nimport org.jclouds.docker.internal.BaseDockerParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\n\n@Test(groups = \"unit\")\npublic class NetworksParseTest extends BaseDockerParseTest<List<Network>> {\n\n   @Override\n   public String resource() {\n      return \"/networks.json\";\n   }\n\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   public List<Network> expected() {\n      return ImmutableList.of(\n\n              Network.create(\n                      \"bridge\", // Name\n                      \"f2de39df4171b0dc801e8002d1d999b77256983dfc63041c0f34030aa3977566\", // Id\n                      \"local\", // Scope\n                      \"bridge\", // Driver\n                      Network.IPAM.create(\n                              \"default\", // driver\n                              ImmutableList.of(Network.IPAM.Config.create(\"172.17.0.0/16\", null, null)) // config\n                      ),\n                      ImmutableMap.of(\"39b69226f9d79f5634485fb236a23b2fe4e96a0a94128390a7fbbcc167065867\",\n                              Network.Details.create(\n                                      \"ed2419a97c1d9954d05b46e462e7002ea552f216e9b136b80a7db8d98b442eda\", //endpointId\n                                      \"02:42:ac:11:00:02\", // MAC\n                                      \"172.17.0.2/16\", // ipv4address\n                                      \"\" // ipv6address\n                              )\n                      ),\n                      ImmutableMap.<String, String> builder()\n                              .put(\"com.docker.network.bridge.default_bridge\", \"true\")\n                              .put(\"com.docker.network.bridge.enable_icc\", \"true\")\n                              .put(\"com.docker.network.bridge.enable_ip_masquerade\", \"true\")\n                              .put(\"com.docker.network.bridge.host_binding_ipv4\", \"0.0.0.0\")\n                              .put(\"com.docker.network.bridge.name\", \"docker0\")\n                              .put(\"com.docker.network.driver.mtu\", \"1500\")\n                              .build()\n              ),\n              Network.create(\n                      \"none\", // Name\n                      \"e086a3893b05ab69242d3c44e49483a3bbbd3a26b46baa8f61ab797c1088d794\", // Id\n                      \"local\", // Scope\n                      \"null\", // Driver\n                      Network.IPAM.create(\n                              \"default\", // driver\n                              ImmutableList.<Network.IPAM.Config>of() // config\n                      ),\n                      ImmutableMap.<String, Network.Details> of(),\n                      ImmutableMap.<String, String> of()\n              ),\n              Network.create(\n                      \"host\", // Name\n                      \"13e871235c677f196c4e1ecebb9dc733b9b2d2ab589e30c539efeda84a24215e\", // Id\n                      \"local\", // Scope\n                      \"host\", // Driver\n                      Network.IPAM.create(\n                              \"default\", // driver\n                              ImmutableList.<Network.IPAM.Config>of() // config\n                      ),\n                      ImmutableMap.<String, Network.Details> of(),\n                      ImmutableMap.<String, String> of()\n              )\n      );\n   }\n\n}\n"
  },
  {
    "path": "apis/docker/src/test/java/org/jclouds/docker/parse/VersionParseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.docker.parse;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.docker.domain.Version;\nimport org.jclouds.docker.internal.BaseDockerParseTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class VersionParseTest extends BaseDockerParseTest<Version> {\n\n   @Override\n   public String resource() {\n      return \"/version.json\";\n   }\n\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Version expected() {\n      return Version.create(\n              \"1.15\",\n              \"amd64\",\n              \"c78088f\",\n              \"go1.3.3\",\n              \"3.16.4-tinycore64\",\n              \"linux\",\n              \"1.3.0\");\n   }\n}\n"
  },
  {
    "path": "apis/docker/src/test/resources/Dockerfile",
    "content": "#\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements.  See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License.  You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\nFROM kwart/alpine-ext:3.3-ssh\nMAINTAINER JClouds Dev <dev@jclouds.apache.org>\n"
  },
  {
    "path": "apis/docker/src/test/resources/SimpleDockerfile",
    "content": "#\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements.  See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License.  You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nFROM scratch"
  },
  {
    "path": "apis/docker/src/test/resources/cert.pem",
    "content": "-----BEGIN CERTIFICATE-----\nMIIDtTCCAp2gAwIBAgIJAL/TuOknjSR5MA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV\nBAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBX\naWRnaXRzIFB0eSBMdGQwHhcNMTQxMjEyMTYwMDEyWhcNMjQxMjA5MTYwMDEyWjBF\nMQswCQYDVQQGEwJBVTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50\nZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\nCgKCAQEAuUQcWlhrMXmzLSLiHUADdF98IHKRde7I1eDT91NndOtx4pKfvVc3WPei\nREIMksrU8F1r4A086h5++xxDf27LxR4EC9ry0Q6GgJ9Un9RB9clCWRhLw8awHAS7\nHgAEN8YOSCeF3qP+78muxyMkIKQbYn3TqqOzRZcK576hX+a6URNJDhbHHAzq2fxm\nrOSRVdPXzKLl48ABfmqJ6+KiXc6e7mQSgmwBLfh51zxmJNNwZ5e+6sfZ8oz4yM4y\nKzek53GRSFj+VFNp5nS/x2072fUak2i6DGut5LibFfh1kqskIm+Iq5WwO15RbojZ\nCR6fkktCl5QOtea5p8SETZpwWfaddQIDAQABo4GnMIGkMB0GA1UdDgQWBBQtOc1g\n1gxisDQ7VTmRYI1U9WHVMDB1BgNVHSMEbjBsgBQtOc1g1gxisDQ7VTmRYI1U9WHV\nMKFJpEcwRTELMAkGA1UEBhMCQVUxEzARBgNVBAgTClNvbWUtU3RhdGUxITAfBgNV\nBAoTGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZIIJAL/TuOknjSR5MAwGA1UdEwQF\nMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBABxYn5JdJYC8FUITqymJeNZ72/a2GVf8\n+gGlWH+DuiyviEAGMGpv7O4GXfS/6UiUBO7zMe2z15fUvNgd5RQBh4T+l5bA9aS0\n5JhENIpEApiIcEII4ISIk6pTLmAZjWvqq2kStiiFPNvdKFclYqFuKHv847EA8kGz\n9u6MuUyFrJipWZ3g8zeYiwLWaAzvimbHomO7HU4pcvYaCSl7O5BQTToKwLfHcx5y\nUG6uRf+0auC5QbotiXpYNdXhIbSD/2xXbjxGwYy4yRWHINcbwfK8iVRhR4eSvtBC\nWvF3Vp8xLJxp6ujBd+a27AOWEiE1XM8oAoUpEzdIINY1GtUSbXzNboc=\n-----END CERTIFICATE-----\n"
  },
  {
    "path": "apis/docker/src/test/resources/container-1.21-create.json",
    "content": "{\n       \"Hostname\": \"\",\n       \"Domainname\": \"\",\n       \"User\": \"\",\n       \"AttachStdin\": false,\n       \"AttachStdout\": true,\n       \"AttachStderr\": true,\n       \"Tty\": false,\n       \"OpenStdin\": false,\n       \"StdinOnce\": false,\n       \"Env\": [\n               \"FOO=bar\",\n               \"BAZ=quux\"\n       ],\n       \"Cmd\": [\n               \"date\"\n       ],\n       \"Entrypoint\": [\"\"],\n       \"Image\": \"ubuntu\",\n       \"Labels\": {\n               \"com.example.vendor\": \"Acme\",\n               \"com.example.license\": \"GPL\",\n               \"com.example.version\": \"1.0\"\n       },\n       \"Volumes\": {\n         \"/volumes/data\": {}\n       },\n       \"WorkingDir\": \"\",\n       \"NetworkDisabled\": false,\n       \"MacAddress\": \"12:34:56:78:9a:bc\",\n       \"ExposedPorts\": {\n               \"22/tcp\": {}\n       },\n       \"StopSignal\": \"SIGTERM\",\n       \"HostConfig\": {\n         \"Binds\": [\"/tmp:/tmp\"],\n         \"Links\": [\"redis3:redis\"],\n         \"LxcConf\": [{\"lxc.utsname\":\"docker\"}],\n         \"Memory\": 0,\n         \"MemorySwap\": 0,\n         \"MemoryReservation\": 0,\n         \"KernelMemory\": 0,\n         \"CpuShares\": 512,\n         \"CpuPeriod\": 100000,\n         \"CpuQuota\": 50000,\n         \"CpusetCpus\": \"0,1\",\n         \"CpusetMems\": \"0,1\",\n         \"BlkioWeight\": 300,\n         \"MemorySwappiness\": 60,\n         \"OomKillDisable\": false,\n         \"PortBindings\": { \"22/tcp\": [{ \"HostPort\": \"11022\" }] },\n         \"PublishAllPorts\": false,\n         \"Privileged\": false,\n         \"ReadonlyRootfs\": false,\n         \"Dns\": [\"8.8.8.8\"],\n         \"DnsOptions\": [\"\"],\n         \"DnsSearch\": [\"\"],\n         \"ExtraHosts\": null,\n         \"VolumesFrom\": [\"parent\", \"other:ro\"],\n         \"CapAdd\": [\"NET_ADMIN\"],\n         \"CapDrop\": [\"MKNOD\"],\n         \"GroupAdd\": [\"newgroup\"],\n         \"RestartPolicy\": { \"Name\": \"\", \"MaximumRetryCount\": 0 },\n         \"NetworkMode\": \"bridge\",\n         \"Devices\": [],\n         \"Ulimits\": [{}],\n         \"LogConfig\": { \"Type\": \"json-file\", \"Config\": {} },\n         \"SecurityOpt\": [],\n         \"CgroupParent\": \"\",\n         \"VolumeDriver\": \"\"\n      }\n  }"
  },
  {
    "path": "apis/docker/src/test/resources/container-1.21-inspect.json",
    "content": "{\n    \"AppArmorProfile\": \"\",\n    \"Args\": [\n        \"-c\",\n        \"exit 9\"\n    ],\n    \"Config\": {\n        \"AttachStderr\": true,\n        \"AttachStdin\": false,\n        \"AttachStdout\": true,\n        \"Cmd\": [\n            \"/bin/sh\",\n            \"-c\",\n            \"exit 9\"\n        ],\n        \"Domainname\": \"\",\n        \"Entrypoint\": null,\n        \"Env\": [\n            \"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\"\n        ],\n        \"ExposedPorts\": null,\n        \"Hostname\": \"ba033ac44011\",\n        \"Image\": \"ubuntu\",\n        \"Labels\": {\n            \"com.example.vendor\": \"Acme\",\n            \"com.example.license\": \"GPL\",\n            \"com.example.version\": \"1.0\"\n        },\n        \"MacAddress\": \"\",\n        \"NetworkDisabled\": false,\n        \"OnBuild\": null,\n        \"OpenStdin\": false,\n        \"StdinOnce\": false,\n        \"Tty\": false,\n        \"User\": \"\",\n        \"Volumes\": null,\n        \"WorkingDir\": \"\",\n        \"StopSignal\": \"SIGTERM\"\n    },\n    \"Created\": \"2015-01-06T15:47:31.485331387Z\",\n    \"Driver\": \"devicemapper\",\n    \"ExecDriver\": \"native-0.2\",\n    \"ExecIDs\": null,\n    \"HostConfig\": {\n        \"Binds\": null,\n        \"BlkioWeight\": 0,\n        \"CapAdd\": null,\n        \"CapDrop\": null,\n        \"ContainerIDFile\": \"\",\n        \"CpusetCpus\": \"\",\n        \"CpusetMems\": \"\",\n        \"CpuShares\": 0,\n        \"CpuPeriod\": 100000,\n        \"Devices\": [],\n        \"Dns\": null,\n        \"DnsOptions\": null,\n        \"DnsSearch\": null,\n        \"ExtraHosts\": null,\n        \"IpcMode\": \"\",\n        \"Links\": null,\n        \"LxcConf\": [],\n        \"Memory\": 0,\n        \"MemorySwap\": 0,\n        \"MemoryReservation\": 0,\n        \"KernelMemory\": 0,\n        \"OomKillDisable\": false,\n        \"NetworkMode\": \"bridge\",\n        \"PortBindings\": {},\n        \"Privileged\": false,\n        \"ReadonlyRootfs\": false,\n        \"PublishAllPorts\": false,\n        \"RestartPolicy\": {\n            \"MaximumRetryCount\": 2,\n            \"Name\": \"on-failure\"\n        },\n        \"LogConfig\": {\n            \"Config\": null,\n            \"Type\": \"json-file\"\n        },\n        \"SecurityOpt\": null,\n        \"VolumesFrom\": null,\n        \"Ulimits\": [{}],\n        \"VolumeDriver\": \"\"\n    },\n    \"HostnamePath\": \"/var/lib/docker/containers/ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39/hostname\",\n    \"HostsPath\": \"/var/lib/docker/containers/ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39/hosts\",\n    \"LogPath\": \"/var/lib/docker/containers/1eb5fabf5a03807136561b3c00adcd2992b535d624d5e18b6cdc6a6844d9767b/1eb5fabf5a03807136561b3c00adcd2992b535d624d5e18b6cdc6a6844d9767b-json.log\",\n    \"Id\": \"ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39\",\n    \"Image\": \"04c5d3b7b0656168630d3ba35d8889bd0e9caafcaeb3004d2bfbc47e7c5d35d2\",\n    \"MountLabel\": \"\",\n    \"Name\": \"/boring_euclid\",\n    \"NetworkSettings\": {\n        \"Bridge\": \"\",\n        \"SandboxID\": \"\",\n        \"HairpinMode\": false,\n        \"LinkLocalIPv6Address\": \"\",\n        \"LinkLocalIPv6PrefixLen\": 0,\n        \"Ports\": null,\n        \"SandboxKey\": \"\",\n        \"SecondaryIPAddresses\": null,\n        \"SecondaryIPv6Addresses\": null,\n        \"EndpointID\": \"\",\n        \"Gateway\": \"\",\n        \"GlobalIPv6Address\": \"\",\n        \"GlobalIPv6PrefixLen\": 0,\n        \"IPAddress\": \"\",\n        \"IPPrefixLen\": 0,\n        \"IPv6Gateway\": \"\",\n        \"MacAddress\": \"\",\n        \"Networks\": {\n            \"bridge\": {\n                \"EndpointID\": \"\",\n                \"Gateway\": \"\",\n                \"IPAddress\": \"\",\n                \"IPPrefixLen\": 0,\n                \"IPv6Gateway\": \"\",\n                \"GlobalIPv6Address\": \"\",\n                \"GlobalIPv6PrefixLen\": 0,\n                \"MacAddress\": \"\"\n            }\n        }\n    },\n    \"Path\": \"/bin/sh\",\n    \"ProcessLabel\": \"\",\n    \"ResolvConfPath\": \"/var/lib/docker/containers/ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39/resolv.conf\",\n    \"RestartCount\": 1,\n    \"State\": {\n        \"Error\": \"\",\n        \"ExitCode\": 9,\n        \"FinishedAt\": \"2015-01-06T15:47:32.080254511Z\",\n        \"OOMKilled\": false,\n        \"Paused\": false,\n        \"Pid\": 0,\n        \"Restarting\": false,\n        \"Running\": true,\n        \"StartedAt\": \"2015-01-06T15:47:32.072697474Z\",\n        \"Status\": \"running\"\n    },\n    \"Mounts\": [\n        {\n            \"Source\": \"/data\",\n            \"Destination\": \"/data\",\n            \"Mode\": \"ro,Z\",\n            \"RW\": false\n        }\n    ]\n}"
  },
  {
    "path": "apis/docker/src/test/resources/container-creation.json",
    "content": "{\"Id\":\"c6c74153ae4b1d1633d68890a68d89c40aa5e284a1ea016cbc6ef0e634ee37b2\",\"Warnings\":null}"
  },
  {
    "path": "apis/docker/src/test/resources/container.json",
    "content": "{\n  \"Args\": [\n    \"-iface\",\n    \"ethwe\",\n    \"-wait\",\n    \"5\",\n    \"-name\",\n    \"7a:63:a2:39:7b:0f\"\n  ],\n  \"Config\": {\n    \"AttachStderr\": false,\n    \"AttachStdin\": false,\n    \"AttachStdout\": false,\n    \"Cmd\": [\n      \"-name\",\n      \"7a:63:a2:39:7b:0f\"\n    ],\n    \"CpuShares\": 0,\n    \"Cpuset\": \"\",\n    \"Domainname\": \"\",\n    \"Entrypoint\": [\n      \"/home/weave/weaver\",\n      \"-iface\",\n      \"ethwe\",\n      \"-wait\",\n      \"5\"\n    ],\n    \"Env\": [\n      \"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\"\n    ],\n    \"ExposedPorts\": {\n      \"6783/tcp\": {},\n      \"6783/udp\": {}\n    },\n    \"Hostname\": \"6c9932f478bd\",\n    \"Image\": \"zettio/weave\",\n    \"Memory\": 0,\n    \"MemorySwap\": 0,\n    \"NetworkDisabled\": false,\n    \"OnBuild\": null,\n    \"OpenStdin\": false,\n    \"PortSpecs\": null,\n    \"SecurityOpts\": null,\n    \"StdinOnce\": false,\n    \"Tty\": false,\n    \"User\": \"\",\n    \"Volumes\": null,\n    \"WorkingDir\": \"/home/weave\"\n  },\n  \"Created\": \"2014-10-31T17:00:21.544197943Z\",\n  \"Driver\": \"aufs\",\n  \"ExecDriver\": \"native-0.2\",\n  \"HostConfig\": {\n    \"Binds\": null,\n    \"CapAdd\": [\"NET_ADMIN\"],\n    \"CapDrop\": [\"MKNOD\"],\n    \"ContainerIDFile\": \"\",\n    \"Devices\": [],\n    \"Dns\": [\n      \"8.8.8.8\",\n      \"8.8.4.4\"\n    ],\n    \"DnsSearch\": null,\n    \"ExtraHosts\": [\"extra:169.254.0.1\"],\n    \"Links\": null,\n    \"LxcConf\": [],\n    \"NetworkMode\": \"bridge\",\n    \"PortBindings\": {\n      \"6783/tcp\": [\n        {\n          \"HostIp\": \"\",\n          \"HostPort\": \"6783\"\n        }\n      ],\n      \"6783/udp\": [\n        {\n          \"HostIp\": \"\",\n          \"HostPort\": \"6783\"\n        }\n      ]\n    },\n    \"Privileged\": true,\n    \"PublishAllPorts\": false,\n    \"RestartPolicy\": {\n      \"MaximumRetryCount\": 0,\n      \"Name\": \"\"\n    },\n    \"VolumesFrom\": null\n  },\n  \"HostnamePath\": \"/var/lib/docker/containers/6c9932f478bd761f32ddb54ed28ab42ab6fac6f2a279f561ea31503ee9d39524/hostname\",\n  \"HostsPath\": \"/var/lib/docker/containers/6c9932f478bd761f32ddb54ed28ab42ab6fac6f2a279f561ea31503ee9d39524/hosts\",\n  \"Id\": \"6c9932f478bd761f32ddb54ed28ab42ab6fac6f2a279f561ea31503ee9d39524\",\n  \"Image\": \"57e570db16baba1e8c0d6f3c15868ddb400f64ff76ec948e65c3ca3f15fb3587\",\n  \"MountLabel\": \"\",\n  \"Name\": \"/weave\",\n  \"NetworkSettings\": {\n    \"Bridge\": \"\",\n    \"SandboxID\": \"3ef128b055eb9ef62a6a2c281d97a2dfde5f47947d490f1dd2a81612611d961f\",\n    \"HairpinMode\": false,\n    \"LinkLocalIPv6Address\": \"\",\n    \"LinkLocalIPv6PrefixLen\": 0,\n    \"Ports\": {},\n    \"SandboxKey\": \"/var/run/docker/netns/3ef128b055eb\",\n    \"SecondaryIPAddresses\": null,\n    \"SecondaryIPv6Addresses\": null,\n    \"EndpointID\": \"9e8dcc0c8288938a923018fee0728cee8e6de7c01a5150738ee6e51c1caf8cf6\",\n    \"Gateway\": \"172.17.0.1\",\n    \"GlobalIPv6Address\": \"\",\n    \"GlobalIPv6PrefixLen\": 0,\n    \"IPAddress\": \"172.17.0.2\",\n    \"IPPrefixLen\": 16,\n    \"IPv6Gateway\": \"\",\n    \"MacAddress\": \"02:42:ac:11:00:02\",\n    \"Networks\": {\n      \"JCLOUDS_NETWORK\": {\n        \"EndpointID\": \"04268fbb4dc368b5a53bb1c3f89294a4f0c72095deb944db3c4efc6d6a439304\",\n        \"Gateway\": \"172.19.0.1\",\n        \"IPAddress\": \"172.19.0.2\",\n        \"IPPrefixLen\": 16,\n        \"IPv6Gateway\": \"\",\n        \"GlobalIPv6Address\": \"\",\n        \"GlobalIPv6PrefixLen\": 0,\n        \"MacAddress\": \"02:42:ac:13:00:02\"\n      },\n      \"bridge\": {\n        \"EndpointID\": \"9e8dcc0c8288938a923018fee0728cee8e6de7c01a5150738ee6e51c1caf8cf6\",\n        \"Gateway\": \"172.17.0.1\",\n        \"IPAddress\": \"172.17.0.2\",\n        \"IPPrefixLen\": 16,\n        \"IPv6Gateway\": \"\",\n        \"GlobalIPv6Address\": \"\",\n        \"GlobalIPv6PrefixLen\": 0,\n        \"MacAddress\": \"02:42:ac:11:00:02\"\n      }\n    }\n  },\n  \"Node\": {\n    \"IP\": \"10.10.10.10\"\n  },\n  \"Path\": \"/home/weave/weaver\",\n  \"ProcessLabel\": \"\",\n  \"ResolvConfPath\": \"/var/lib/docker/containers/6c9932f478bd761f32ddb54ed28ab42ab6fac6f2a279f561ea31503ee9d39524/resolv.conf\",\n  \"SecurityOpt\": [],\n  \"State\": {\n    \"Status\": \"running\",\n    \"Running\": true,\n    \"Paused\": false,\n    \"Restarting\": false,\n    \"OOMKilled\": false,\n    \"Dead\": false,\n    \"Pid\": 10357,\n    \"ExitCode\": 0,\n    \"Error\": \"\",\n    \"StartedAt\": \"2015-11-10T09:33:21.68146124Z\",\n    \"FinishedAt\": \"0001-01-01T00:00:00Z\"\n  },\n  \"Volumes\": {},\n  \"VolumesRW\": {}\n}"
  },
  {
    "path": "apis/docker/src/test/resources/containers.json",
    "content": "[\n  {\n    \"Command\": \"/usr/sbin/sshd -D\",\n    \"Created\": 1395472605,\n    \"Id\": \"6d35806c1bd2b25cd92bba2d2c2c5169dc2156f53ab45c2b62d76e2d2fee14a9\",\n    \"Image\": \"jclouds/ubuntu:latest\",\n    \"Names\": [\n      \"/hopeful_mclean\"\n    ],\n    \"Ports\": [\n      {\n        \"IP\": \"0.0.0.0\",\n        \"PrivatePort\": 22,\n        \"PublicPort\": 49231,\n        \"Type\": \"tcp\"\n      }\n    ],\n    \"Status\": \"Up 55 seconds\"\n  },\n  {\n    \"Command\": \"/usr/sbin/sshd -D\",\n    \"Created\": 1395472605,\n    \"Id\": \"6d35806c1bd2b25cd92bba2d2c2c5169dc2156f53ab45c2b62d76e2d2fee14a2\",\n    \"Image\": \"jclouds/ubuntu:latest\",\n    \"Names\": [\n      \"/hopeful_mclean\"\n    ],\n    \"Ports\": [\n      {\n        \"PrivatePort\": 22,\n        \"Type\": \"tcp\"\n      }\n    ],\n    \"Status\": \"Up 55 seconds\"\n  }\n]"
  },
  {
    "path": "apis/docker/src/test/resources/exec.json",
    "content": "{\"Id\":\"dbf45d296388032ebb9872edb75847f6655a72b4e9ab0d99ae1c75589c4ca957\"}\n"
  },
  {
    "path": "apis/docker/src/test/resources/execInspect.json",
    "content": "{\"ID\":\"fda1cf8064863fc0667c691c69793fdb7d0bd4a1fabb8250536abe5203e4208a\",\"Running\":false,\"ExitCode\":2,\"ProcessConfig\":{\"privileged\":false,\"user\":\"\",\"tty\":false,\"entrypoint\":\"/bin/sh\",\"arguments\":[\"-c\",\"echo -n Standard \\u003e\\u00261 \\u0026\\u0026 echo -n Error \\u003e\\u00262 \\u0026\\u0026 exit 2\"]},\"OpenStdin\":false,\"OpenStderr\":true,\"OpenStdout\":true,\"Container\":{\"State\":{\"Running\":true,\"Paused\":false,\"Restarting\":false,\"OOMKilled\":false,\"Dead\":false,\"Pid\":1561,\"ExitCode\":0,\"Error\":\"\",\"StartedAt\":\"2015-09-29T12:36:21.011469908Z\",\"FinishedAt\":\"0001-01-01T00:00:00Z\"},\"ID\":\"07695c5170a1cbf3402552202fd28d2beb81fce5958a244e9ad7c8cb0ded936e\",\"Created\":\"2015-09-29T12:36:19.829846377Z\",\"Path\":\"/bin/sh\",\"Args\":[\"-c\",\"touch hello; while true; do echo hello world; sleep 1; done\"],\"Config\":{\"Hostname\":\"07695c5170a1\",\"Domainname\":\"\",\"User\":\"\",\"AttachStdin\":false,\"AttachStdout\":false,\"AttachStderr\":false,\"PortSpecs\":null,\"ExposedPorts\":null,\"Tty\":false,\"OpenStdin\":false,\"StdinOnce\":false,\"Env\":null,\"Cmd\":[\"/bin/sh\",\"-c\",\"touch hello; while true; do echo hello world; sleep 1; done\"],\"Image\":\"ff8f955d1fed83a6239675b9a767fc9502db9934922a2f69ac6bf4cad8a7d7be\",\"Volumes\":null,\"VolumeDriver\":\"\",\"WorkingDir\":\"\",\"Entrypoint\":null,\"NetworkDisabled\":false,\"MacAddress\":\"\",\"OnBuild\":null,\"Labels\":{},\"Init\":\"\"},\"Image\":\"ff8f955d1fed83a6239675b9a767fc9502db9934922a2f69ac6bf4cad8a7d7be\",\"NetworkSettings\":{\"Bridge\":\"\",\"EndpointID\":\"78d38a6f4d63966b16ca824a533b70f0a3a00490586688a188f67ec0bb07e68f\",\"Gateway\":\"172.17.42.1\",\"GlobalIPv6Address\":\"\",\"GlobalIPv6PrefixLen\":0,\"HairpinMode\":false,\"IPAddress\":\"172.17.0.3\",\"IPPrefixLen\":16,\"IPv6Gateway\":\"\",\"LinkLocalIPv6Address\":\"\",\"LinkLocalIPv6PrefixLen\":0,\"MacAddress\":\"02:42:ac:11:00:03\",\"NetworkID\":\"880f733909fa4ad45c8fbc95b80c83e22a7b46f8cd7fb23dea62b0996ef1c8c6\",\"PortMapping\":null,\"Ports\":{},\"SandboxKey\":\"/var/run/docker/netns/07695c5170a1\",\"SecondaryIPAddresses\":null,\"SecondaryIPv6Addresses\":null},\"ResolvConfPath\":\"/var/lib/docker/containers/07695c5170a1cbf3402552202fd28d2beb81fce5958a244e9ad7c8cb0ded936e/resolv.conf\",\"HostnamePath\":\"/var/lib/docker/containers/07695c5170a1cbf3402552202fd28d2beb81fce5958a244e9ad7c8cb0ded936e/hostname\",\"HostsPath\":\"/var/lib/docker/containers/07695c5170a1cbf3402552202fd28d2beb81fce5958a244e9ad7c8cb0ded936e/hosts\",\"LogPath\":\"/var/lib/docker/containers/07695c5170a1cbf3402552202fd28d2beb81fce5958a244e9ad7c8cb0ded936e/07695c5170a1cbf3402552202fd28d2beb81fce5958a244e9ad7c8cb0ded936e-json.log\",\"Name\":\"/miscApiTest\",\"Driver\":\"devicemapper\",\"ExecDriver\":\"native-0.2\",\"MountLabel\":\"\",\"ProcessLabel\":\"\",\"RestartCount\":0,\"UpdateDns\":false,\"MountPoints\":{},\"Volumes\":{},\"VolumesRW\":{},\"Init\":\"\",\"AppArmorProfile\":\"\"}}\n"
  },
  {
    "path": "apis/docker/src/test/resources/history-apiver22.json",
    "content": "[\n    {\n        \"Comment\": \"\",\n        \"Created\": 1456304238,\n        \"CreatedBy\": \"\",\n        \"Id\": \"sha256:fcf9d588ee9ab46c5a888e67f892fac66e6396eb195a743e50c0c5f9a4710e66\",\n        \"Size\": 188605160,\n        \"Tags\": [\n            \"registry.acme.com:8888/jboss-eap-test/eap-test:1.0-3\"\n        ]\n    },\n    {\n        \"Comment\": \"\",\n        \"Created\": 1455838658,\n        \"CreatedBy\": \"\",\n        \"Id\": \"<missing>\",\n        \"Size\": 195019519,\n        \"Tags\": null\n    },\n    {\n        \"Comment\": \"Imported from -\",\n        \"Created\": 1455812978,\n        \"CreatedBy\": \"\",\n        \"Id\": \"<missing>\",\n        \"Size\": 203250948,\n        \"Tags\": null\n    }\n]"
  },
  {
    "path": "apis/docker/src/test/resources/history.json",
    "content": "[\n    {\n        \"Id\": \"3db9c44f45209632d6050b35958829c3a2aa256d81b9a7be45b362ff85c54710\",\n        \"Created\": 1398108230,\n        \"CreatedBy\": \"/bin/sh -c #(nop) ADD file:eb15dbd63394e063b805a3c32ca7bf0266ef64676d5a6fab4801f2e81e2a5148 in /\",\n        \"Tags\": [\n            \"ubuntu:lucid\",\n            \"ubuntu:10.04\"\n        ],\n        \"Size\": 182964289,\n        \"Comment\": \"\"\n    },\n    {\n        \"Id\": \"6cfa4d1f33fb861d4d114f43b25abd0ac737509268065cdfd69d544a59c85ab8\",\n        \"Created\": 1398108222,\n        \"CreatedBy\": \"/bin/sh -c #(nop) MAINTAINER Tianon Gravi <admwiggin@gmail.com> - mkimage-debootstrap.sh -i iproute,iputils-ping,ubuntu-minimal -t lucid.tar.xz lucid http://archive.ubuntu.com/ubuntu/\",\n        \"Tags\": null,\n        \"Size\": 0,\n        \"Comment\": \"\"\n    },\n    {\n        \"Id\": \"511136ea3c5a64f264b78b5433614aec563103b4d4702f3ba7d4d2698e22c158\",\n        \"Created\": 1371157430,\n        \"CreatedBy\": \"\",\n        \"Tags\": [\n            \"scratch12:latest\",\n            \"scratch:latest\"\n        ],\n        \"Size\": 0,\n        \"Comment\": \"Imported from -\"\n    }\n]"
  },
  {
    "path": "apis/docker/src/test/resources/image.json",
    "content": "{\n  \"Architecture\": \"amd64\",\n  \"Author\": \"author\",\n  \"Comment\": \"comment\",\n  \"Config\": {\n    \"AttachStderr\": false,\n    \"AttachStdin\": false,\n    \"AttachStdout\": false,\n    \"Cmd\": [\n      \"/bin/sh\",\n      \"-c\",\n      \"echo hello world\"\n    ],\n    \"CpuShares\": 0,\n    \"Cpuset\": \"\",\n    \"Domainname\": \"\",\n    \"Entrypoint\": null,\n    \"Env\": [\n      \"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\",\n      \"HOME=/root\",\n      \"JAVA_HOME=/usr/lib/jvm/java-7-openjdk-amd64\"\n    ],\n    \"ExposedPorts\": {\n      \"8081/tcp\": {}\n    },\n    \"Hostname\": \"f22711318734\",\n    \"Image\": \"05794515afd5724df1cdf0e674ae932455fce7dea3c70a94d77119ad1fa954ba\",\n    \"Memory\": 0,\n    \"MemorySwap\": 0,\n    \"NetworkDisabled\": false,\n    \"OnBuild\": [],\n    \"OpenStdin\": false,\n    \"PortSpecs\": null,\n    \"StdinOnce\": false,\n    \"Tty\": false,\n    \"User\": \"user\",\n    \"Volumes\": null,\n    \"WorkingDir\": \"/home/user\"\n  },\n  \"Container\": \"0d14967353dbbd2ee78abe209f026f71654da49692fa2b044296ec3c810027b3\",\n  \"ContainerConfig\": {\n    \"AttachStderr\": false,\n    \"AttachStdin\": false,\n    \"AttachStdout\": false,\n    \"Cmd\": [\n      \"/bin/sh\",\n      \"-c\",\n      \"echo hello world\"\n    ],\n    \"CpuShares\": 0,\n    \"Cpuset\": \"\",\n    \"Domainname\": \"\",\n    \"Entrypoint\": null,\n    \"Env\": [\n      \"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\",\n      \"HOME=/root\",\n      \"JAVA_HOME=/usr/lib/jvm/java-7-openjdk-amd64\"\n    ],\n    \"ExposedPorts\": {\n      \"8081/tcp\": {}\n    },\n    \"Hostname\": \"f22711318734\",\n    \"Image\": \"05794515afd5724df1cdf0e674ae932455fce7dea3c70a94d77119ad1fa954ba\",\n    \"Memory\": 0,\n    \"MemorySwap\": 0,\n    \"NetworkDisabled\": false,\n    \"OnBuild\": [],\n    \"OpenStdin\": false,\n    \"PortSpecs\": null,\n    \"StdinOnce\": false,\n    \"Tty\": false,\n    \"User\": \"user\",\n    \"Volumes\": null,\n    \"WorkingDir\": \"/home/user\"\n  },\n  \"Created\": \"2014-11-24T11:09:20.310023104Z\",\n  \"DockerVersion\": \"1.3.1\",\n  \"Id\": \"cbba6639a342646deed70d7ea6162fa2a0acea9300f911f4e014555fe37d3456\",\n  \"Os\": \"linux\",\n  \"Parent\": \"05794515afd5724df1cdf0e674ae932455fce7dea3c70a94d77119ad1fa954ba\",\n  \"Size\": 0,\n  \"VirtualSize\": 808709069\n}"
  },
  {
    "path": "apis/docker/src/test/resources/images.json",
    "content": "[\n    {\n        \"Created\": 1442866547,\n        \"Id\": \"d7057cb020844f245031d27b76cb18af05db1cc3a96a29fa7777af75f5ac91a3\",\n        \"Labels\": null,\n        \"ParentId\": \"cfa753dfea5e68a24366dfba16e6edf573daa447abf65bc11619c1a98a3aff54\",\n        \"RepoDigests\": [],\n        \"RepoTags\": [\n            \"docker.io/busybox:1.23.2\",\n            \"docker.io/busybox:latest\"\n        ],\n        \"Size\": 0,\n        \"VirtualSize\": 1095501\n    },\n    {\n        \"Created\": 1442598293,\n        \"Id\": \"633fcd11259e8d6bccfbb59a4086b95b0d0fb44edfc3912000ef1f70e8a7bfc6\",\n        \"Labels\": null,\n        \"ParentId\": \"b65c936b5fb601d680ed656b1ccf8ab857c0e5cb521043a005405c194e9a69f3\",\n        \"RepoDigests\": [],\n        \"RepoTags\": [\n            \"docker.io/busybox:ubuntu-14.04\",\n            \"jclouds:testTag\"\n        ],\n        \"Size\": 0,\n        \"VirtualSize\": 5607885\n    },\n    {\n        \"Created\": 1442260874,\n        \"Id\": \"f4fddc471ec22fc1f7d37768132f1753bc171121e30ac2af7fcb0302588197c0\",\n        \"Labels\": null,\n        \"ParentId\": \"\",\n        \"RepoDigests\": [],\n        \"RepoTags\": [\n            \"docker.io/alpine:3.2\"\n        ],\n        \"Size\": 5244426,\n        \"VirtualSize\": 5244426\n    },\n    {\n        \"Created\": 1440102075,\n        \"Id\": \"91e54dfb11794fad694460162bf0cb0a4fa710cfa3f60979c177d920813e267c\",\n        \"Labels\": {},\n        \"ParentId\": \"d74508fb6632491cea586a1fd7d748dfc5274cd6fdfedee309ecdcbc2bf5cb82\",\n        \"RepoDigests\": [],\n        \"RepoTags\": [\n            \"docker.io/ubuntu:14.04\",\n            \"docker.io/ubuntu:latest\"\n        ],\n        \"Size\": 0,\n        \"VirtualSize\": 188333286\n    }\n]"
  },
  {
    "path": "apis/docker/src/test/resources/info.json",
    "content": "{\n    \"Containers\": 0,\n    \"Debug\": true,\n    \"DockerRootDir\": \"/mnt/sda1/var/lib/docker\",\n    \"Driver\": \"aufs\",\n    \"DriverStatus\": [\n        [\n            \"Root Dir\",\n            \"/mnt/sda1/var/lib/docker/aufs\"\n        ],\n        [\n            \"Dirs\",\n            \"46\"\n        ]\n    ],\n    \"ExecutionDriver\": \"native-0.2\",\n    \"ID\": \"7V5Y:IQ2M:HWIL:AZJV:HKRD:Q7OZ:3EQA:ZHMO:4LAD:OSIY:YBAA:BSX6\",\n    \"IPv4Forwarding\": true,\n    \"Images\": 46,\n    \"IndexServerAddress\": \"https://index.docker.io/v1/\",\n    \"InitPath\": \"/usr/local/bin/docker\",\n    \"InitSha1\": \"\",\n    \"KernelVersion\": \"3.16.7-tinycore64\",\n    \"Labels\": null,\n    \"MemTotal\": 2105585664,\n    \"MemoryLimit\": true,\n    \"NCPU\": 8,\n    \"NEventsListener\": 0,\n    \"NFd\": 10,\n    \"NGoroutines\": 11,\n    \"Name\": \"boot2docker\",\n    \"OperatingSystem\": \"Boot2Docker 1.4.1 (TCL 5.4); master : 86f7ec8 - Tue Dec 16 23:11:29 UTC 2014\",\n    \"SwapLimit\": true\n}"
  },
  {
    "path": "apis/docker/src/test/resources/info2.json",
    "content": "{\n    \"Architecture\": \"x86_64\",\n    \"BridgeNfIp6tables\": true,\n    \"BridgeNfIptables\": true,\n    \"CPUSet\": true,\n    \"CPUShares\": true,\n    \"CgroupDriver\": \"cgroupfs\",\n    \"ClusterAdvertise\": \"\",\n    \"ClusterStore\": \"\",\n    \"Containers\": 0,\n    \"ContainersPaused\": 0,\n    \"ContainersRunning\": 0,\n    \"ContainersStopped\": 0,\n    \"CpuCfsPeriod\": true,\n    \"CpuCfsQuota\": true,\n    \"Debug\": false,\n    \"DockerRootDir\": \"/var/lib/docker\",\n    \"Driver\": \"aufs\",\n    \"DriverStatus\": [\n        [\n            \"Root Dir\",\n            \"/var/lib/docker/aufs\"\n        ],\n        [\n            \"Backing Filesystem\",\n            \"extfs\"\n        ],\n        [\n            \"Dirs\",\n            \"117\"\n        ],\n        [\n            \"Dirperm1 Supported\",\n            \"true\"\n        ]\n    ],\n    \"ExecutionDriver\": \"\",\n    \"ExperimentalBuild\": false,\n    \"HttpProxy\": \"\",\n    \"HttpsProxy\": \"\",\n    \"ID\": \"KFWR:PMVY:BEWE:TD52:5WEU:NXF4:I6S3:WDIE:GCRD:L3YA:VWC4:ZRYZ\",\n    \"IPv4Forwarding\": true,\n    \"Images\": 39,\n    \"IndexServerAddress\": \"https://index.docker.io/v1/\",\n    \"KernelMemory\": true,\n    \"KernelVersion\": \"4.4.0-22-generic\",\n    \"Labels\": null,\n    \"LoggingDriver\": \"json-file\",\n    \"MemTotal\": 8248356864,\n    \"MemoryLimit\": true,\n    \"NCPU\": 4,\n    \"NEventsListener\": 0,\n    \"NFd\": 33,\n    \"NGoroutines\": 83,\n    \"Name\": \"test\",\n    \"NoProxy\": \"\",\n    \"OSType\": \"linux\",\n    \"OomKillDisable\": true,\n    \"OperatingSystem\": \"Ubuntu 16.04 LTS\",\n    \"Plugins\": {\n        \"Authorization\": null,\n        \"Network\": [\n            \"bridge\",\n            \"null\",\n            \"host\"\n        ],\n        \"Volume\": [\n            \"local\"\n        ]\n    },\n    \"RegistryConfig\": {\n        \"IndexConfigs\": {\n            \"docker.io\": {\n                \"Mirrors\": null,\n                \"Name\": \"docker.io\",\n                \"Official\": true,\n                \"Secure\": true\n            }\n        },\n        \"InsecureRegistryCIDRs\": [\n            \"0.0.0.0/0\",\n            \"127.0.0.0/8\"\n        ],\n        \"Mirrors\": null\n    },\n    \"ServerVersion\": \"1.11.1\",\n    \"SwapLimit\": false,\n    \"SystemStatus\": null,\n    \"SystemTime\": \"2016-05-24T15:20:15.407969411+02:00\"\n}\n"
  },
  {
    "path": "apis/docker/src/test/resources/key.pem",
    "content": "-----BEGIN RSA PRIVATE KEY-----\nMIIEogIBAAKCAQEAuUQcWlhrMXmzLSLiHUADdF98IHKRde7I1eDT91NndOtx4pKf\nvVc3WPeiREIMksrU8F1r4A086h5++xxDf27LxR4EC9ry0Q6GgJ9Un9RB9clCWRhL\nw8awHAS7HgAEN8YOSCeF3qP+78muxyMkIKQbYn3TqqOzRZcK576hX+a6URNJDhbH\nHAzq2fxmrOSRVdPXzKLl48ABfmqJ6+KiXc6e7mQSgmwBLfh51zxmJNNwZ5e+6sfZ\n8oz4yM4yKzek53GRSFj+VFNp5nS/x2072fUak2i6DGut5LibFfh1kqskIm+Iq5Ww\nO15RbojZCR6fkktCl5QOtea5p8SETZpwWfaddQIDAQABAoIBAAoj2zVqr3tGwPLQ\nfPXC4i2FaGLSQnnk9uMV6iQYUYpJtLME+W9Ajcv1ydDYmJ2UMnFxe40IzHO39ZVC\n58LaypZgXTJU6oNcuynhDp2s3WtZd6MuvD7b6hmufJtYvuJamb+DQkV8TmDLdiB6\nIOkUcldCscoeKZq+eJ9UhLqeA0aaosVUa2cfxJM2seGhF6iJmrJChvaKlc0xfqxG\nl3Y+w01YNQgFBT7vxMzfXHZkVjY8jrrsxhhfyVKiheyaBZ0G3hQCZkBywR6h2bns\n2rWM2mOcaWL7+lJiMB0d9el58HzTxFVxuPENbE2Li1SqTG1pn+Fif0VwG3Te0lPo\nxz7EL8UCgYEA3wJLL2nfVqS73yf5k2w1+uiBHK4RVHaJeQgxv1QlgeunCwOWZ0dp\nMDPQVi9CfWhEQUZKYr118V3ikecOYh+o8ruStz9fNTeA+7IXtBaE1cAbqU9ZgeS2\nvcAIfEzQmN9JtSiFsywJKLON4/aDYXGR1NZDSaXouFQ7T0F/SaL/CUsCgYEA1Kxu\n1QjOwFC1tdB/2MF9Fn7X+YWBQsdE66a5HO30FTlMmLb/ecmngB5OxvdvpfMRMQeD\nmhifSzAfnTBAzBcuz9/il6sKygfhQX6PyxtTJ5o4XlwOArkaBew8H0gBXwfAL33G\n816rNF2kCfgDJisj9iPrl+QAgrg3sJsfIwk5fD8CgYAx075eyqYHIumDM9hUsyHg\nfOCUOuROXenbbBRJbpCu1atOD7AkRVVgWsNa7lZJ1OkjOIRYSYK3ukVsWhbhn7dM\n/NIMNZGdP1iHZERdjYaCh9jmXH9gQWz/Oo/qzfLxpTo/yt0MqnMlb/DtFWBHfmua\nBYGlS/eSb+eMjtLU7iFTvwKBgDiGuFKhK6rMCPARQdnP27p97lOg23FvW28y+iKp\nUGXPu/8fLJonMgEIjTGvFJrMFzar45uyjaxDVzPFXoOgac3QmP5s9Mor/AAXboqy\ncZCmGfNijkrE/hiy6Gv8DHlAqyE0Ugvfjqu1c+M+az/a2Y0TkQvnCwezhQHIySbb\nzc6rAoGAcg9GZnYk64V2c4uzaeTekkLkZhPTv4F7xFWb0JmTurL5BR//TDDk9Oy8\npd5VoiBnKyCRTo2oC8J8COobxJXbl5qUxEeapjtKlQeBiROWE51K2DHacD2SDgKu\nnzn5qonnU2659Aw95bfv+rGljttOu8ySZXVhs4UUKgrQvXErXhU=\n-----END RSA PRIVATE KEY-----\n"
  },
  {
    "path": "apis/docker/src/test/resources/logback.xml",
    "content": "<?xml version=\"1.0\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<configuration>\n    <appender name=\"STDOUT\" class=\"ch.qos.logback.core.ConsoleAppender\">\n        <encoder>\n            <pattern>- %msg%n</pattern>\n        </encoder>\n    </appender>\n    <root level=\"info\">\n        <appender-ref ref=\"STDOUT\"/>\n    </root>\n    <logger name=\"jclouds.compute\" level=\"debug\"/>\n    <logger name=\"net.schmizz\" level=\"warn\"/>\n    <logger name=\"jclouds.wire\" level=\"debug\"/>\n    <logger name=\"jclouds.headers\" level=\"debug\"/>\n    <logger name=\"jclouds.ssh\" level=\"debug\"/>\n</configuration>\n"
  },
  {
    "path": "apis/docker/src/test/resources/network-creation.json",
    "content": "{\n  \"Id\": \"22be93d5babb089c5aab8dbc369042fad48ff791584ca2da2100db837a1c7c30\",\n  \"Warning\": \"\"\n}"
  },
  {
    "path": "apis/docker/src/test/resources/network.json",
    "content": "{\n  \"Name\": \"bridge\",\n  \"Id\": \"f2de39df4171b0dc801e8002d1d999b77256983dfc63041c0f34030aa3977566\",\n  \"Scope\": \"local\",\n  \"Driver\": \"bridge\",\n  \"IPAM\": {\n    \"Driver\": \"default\",\n    \"Config\": [\n      {\n        \"Subnet\": \"172.17.0.0/16\"\n      }\n    ]\n  },\n  \"Containers\": {\n    \"39b69226f9d79f5634485fb236a23b2fe4e96a0a94128390a7fbbcc167065867\": {\n      \"EndpointID\": \"ed2419a97c1d9954d05b46e462e7002ea552f216e9b136b80a7db8d98b442eda\",\n      \"MacAddress\": \"02:42:ac:11:00:02\",\n      \"IPv4Address\": \"172.17.0.2/16\",\n      \"IPv6Address\": \"\"\n    }\n  },\n  \"Options\": {\n    \"com.docker.network.bridge.default_bridge\": \"true\",\n    \"com.docker.network.bridge.enable_icc\": \"true\",\n    \"com.docker.network.bridge.enable_ip_masquerade\": \"true\",\n    \"com.docker.network.bridge.host_binding_ipv4\": \"0.0.0.0\",\n    \"com.docker.network.bridge.name\": \"docker0\",\n    \"com.docker.network.driver.mtu\": \"1500\"\n  }\n}\n"
  },
  {
    "path": "apis/docker/src/test/resources/networks.json",
    "content": "[\n  {\n    \"Name\": \"bridge\",\n    \"Id\": \"f2de39df4171b0dc801e8002d1d999b77256983dfc63041c0f34030aa3977566\",\n    \"Scope\": \"local\",\n    \"Driver\": \"bridge\",\n    \"IPAM\": {\n      \"Driver\": \"default\",\n      \"Config\": [\n        {\n          \"Subnet\": \"172.17.0.0/16\"\n        }\n      ]\n    },\n    \"Containers\": {\n      \"39b69226f9d79f5634485fb236a23b2fe4e96a0a94128390a7fbbcc167065867\": {\n        \"EndpointID\": \"ed2419a97c1d9954d05b46e462e7002ea552f216e9b136b80a7db8d98b442eda\",\n        \"MacAddress\": \"02:42:ac:11:00:02\",\n        \"IPv4Address\": \"172.17.0.2/16\",\n        \"IPv6Address\": \"\"\n      }\n    },\n    \"Options\": {\n      \"com.docker.network.bridge.default_bridge\": \"true\",\n      \"com.docker.network.bridge.enable_icc\": \"true\",\n      \"com.docker.network.bridge.enable_ip_masquerade\": \"true\",\n      \"com.docker.network.bridge.host_binding_ipv4\": \"0.0.0.0\",\n      \"com.docker.network.bridge.name\": \"docker0\",\n      \"com.docker.network.driver.mtu\": \"1500\"\n    }\n  },\n  {\n    \"Name\": \"none\",\n    \"Id\": \"e086a3893b05ab69242d3c44e49483a3bbbd3a26b46baa8f61ab797c1088d794\",\n    \"Scope\": \"local\",\n    \"Driver\": \"null\",\n    \"IPAM\": {\n      \"Driver\": \"default\",\n      \"Config\": []\n    },\n    \"Containers\": {},\n    \"Options\": {}\n  },\n  {\n    \"Name\": \"host\",\n    \"Id\": \"13e871235c677f196c4e1ecebb9dc733b9b2d2ab589e30c539efeda84a24215e\",\n    \"Scope\": \"local\",\n    \"Driver\": \"host\",\n    \"IPAM\": {\n      \"Driver\": \"default\",\n      \"Config\": []\n    },\n    \"Containers\": {},\n    \"Options\": {}\n  }\n]"
  },
  {
    "path": "apis/docker/src/test/resources/version.json",
    "content": "{\n    \"ApiVersion\": \"1.15\",\n    \"Arch\": \"amd64\",\n    \"GitCommit\": \"c78088f\",\n    \"GoVersion\": \"go1.3.3\",\n    \"KernelVersion\": \"3.16.4-tinycore64\",\n    \"Os\": \"linux\",\n    \"Version\": \"1.3.0\"\n}"
  },
  {
    "path": "apis/ec2/README.txt",
    "content": "#\n# The jclouds API for Amazon's EC2 service (http://aws.amazon.com/ec2/).\n#\n# TODO: Implementation status.\n# TODO: Supported features.\n# TODO: Usage example.\n\nNOTE: The live tests in apis/ec2 will *not* work against AWS EC2 with AWS accounts created\nfrom December 04, 2013 and onward, due to those accounts only supporting VPC, and VPC requiring\ndifferent parameters (ID rather than name) for referring to and acting on security groups.\n\nTo run the EC2 live tests against AWS, go to providers/aws-ec2.\n\napis/ec2 will retain the older security group name usage to support EC2 API shims,\nsuch as OpenStack, CloudStack, etc."
  },
  {
    "path": "apis/ec2/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.ec2.*;version=\"${project.version}\";-noimport:=true"
  },
  {
    "path": "apis/ec2/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.api</groupId>\n  <artifactId>ec2</artifactId>\n  <name>jclouds ec2 api</name>\n  <description>jclouds components to access an implementation of EC2</description>\n\n  <properties>\n    <test.ec2.endpoint>https://ec2.us-east-1.amazonaws.com</test.ec2.endpoint>\n    <test.ec2.api-version>2010-08-31</test.ec2.api-version>\n    <test.ec2.build-version />\n    <test.ec2.identity>${test.aws.identity}</test.ec2.identity>\n    <test.ec2.credential>${test.aws.credential}</test.ec2.credential>\n    <!-- default template pattern gets a problematic Ubuntu 10.04 AMI -->\n    <test.ec2.template>hardwareId=m1.small,imageId=us-east-1/ami-1ab3ce73</test.ec2.template>\n    <!-- Active EBS template as of 9/25/2013 -->\n    <test.ec2.ebs-template>hardwareId=m1.small,imageId=us-east-1/ami-53b1ff3a</test.ec2.ebs-template>\n    <!-- Windows_Server-2008-R2 with WinRM enabled (setup instructions at http://www.frontiertown.co.uk/2011/12/overthere-control-windows-from-java/) -->\n    <test.ec2.windows-template>hardwareId=m1.small,imageId=us-east-1/ami-0cb76d65</test.ec2.windows-template>\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>sts</artifactId>\n      <version>${project.version}</version>\n      <type>jar</type>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n      <type>jar</type>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-log4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-sshj</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.squareup.okhttp3</groupId>\n      <artifactId>mockwebserver</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.ec2.endpoint>${test.ec2.endpoint}</test.ec2.endpoint>\n                    <test.ec2.api-version>${test.ec2.api-version}</test.ec2.api-version>\n                    <test.ec2.build-version>${test.ec2.build-version}</test.ec2.build-version>\n                    <test.ec2.identity>${test.ec2.identity}</test.ec2.identity>\n                    <test.ec2.credential>${test.ec2.credential}</test.ec2.credential>\n                    <test.ec2.template>${test.ec2.template}</test.ec2.template>\n                    <test.ec2.ebs-template>${test.ec2.ebs-template}</test.ec2.ebs-template>\n                    <test.ec2.windows-template>${test.ec2.windows-template}</test.ec2.windows-template>\n                    <test.ec2.windows-owner>${test.ec2.windows-owner}</test.ec2.windows-owner>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/EC2Api.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2;\n\nimport java.io.Closeable;\nimport java.util.Set;\nimport org.jclouds.ec2.features.SubnetApi;\nimport org.jclouds.ec2.features.TagApi;\nimport org.jclouds.ec2.features.WindowsApi;\nimport org.jclouds.ec2.features.AMIApi;\nimport org.jclouds.ec2.features.AvailabilityZoneAndRegionApi;\nimport org.jclouds.ec2.features.ElasticBlockStoreApi;\nimport org.jclouds.ec2.features.ElasticIPAddressApi;\nimport org.jclouds.ec2.features.InstanceApi;\nimport org.jclouds.ec2.features.KeyPairApi;\nimport org.jclouds.ec2.features.SecurityGroupApi;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.location.Region;\nimport org.jclouds.location.functions.RegionToEndpointOrProviderIfNull;\nimport org.jclouds.rest.annotations.Delegate;\nimport org.jclouds.rest.annotations.EndpointParam;\n\nimport com.google.common.base.Optional;\nimport com.google.inject.Provides;\n\n/**\n * Provides access to EC2 features, broken up by feature group. Use of the\n * {@link Optional} type allows you to check to see if the underlying\n * implementation supports a particular feature before attempting to use it.\n * This is useful in clones like OpenStack, CloudStack, or Eucalyptus, which\n * track the api, but are always behind Amazon's service. In the case of Amazon\n * ({@code aws-ec2}), you can expect all features to be present.\n * \n * \n * Example\n * \n * <pre>\n * Optional&lt;? extends WindowsApi&gt; windowsOption = ec2Api.getWindowsApi();\n * checkState(windowsOption.isPresent(), &quot;windows feature required, but not present&quot;);\n * </pre>\n */\npublic interface EC2Api extends Closeable {\n   /**\n    * \n    * @return the Region codes configured\n    */\n   @Provides\n   @Region\n   Set<String> getConfiguredRegions();\n\n   /**\n    * Provides synchronous access to Windows features.\n    */\n   @Delegate\n   Optional<? extends WindowsApi> getWindowsApi();\n\n   @Delegate\n   Optional<? extends WindowsApi> getWindowsApiForRegion(\n         @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region);\n   \n   /**\n    * Provides synchronous access to Tag features.\n    */\n   @Delegate\n   Optional<? extends TagApi> getTagApi();\n\n   @Delegate\n   Optional<? extends TagApi> getTagApiForRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region);\n\n   /**\n    * Provides synchronous access to Subnet features.\n    */\n   @Delegate\n   Optional<? extends SubnetApi> getSubnetApi();\n\n   @Delegate\n   Optional<? extends SubnetApi> getSubnetApiForRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region);\n\n   /**\n    * Provides synchronous access to AMI services.\n    */\n   @Delegate\n   Optional<? extends AMIApi> getAMIApi();\n\n   @Delegate\n   Optional<? extends AMIApi> getAMIApiForRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region);\n\n\n   /**\n    * Provides synchronous access to Elastic IP Address services.\n    */\n   @Delegate\n   Optional<? extends ElasticIPAddressApi> getElasticIPAddressApi();\n\n   @Delegate\n   Optional<? extends ElasticIPAddressApi> getElasticIPAddressApiForRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region);\n\n   /**\n    * Provides synchronous access to Instance services.\n    */\n   @Delegate\n   Optional<? extends InstanceApi> getInstanceApi();\n\n   @Delegate\n   Optional<? extends InstanceApi> getInstanceApiForRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region);\n\n   /**\n    * Provides synchronous access to KeyPair services.\n    */\n   @Delegate\n   Optional<? extends KeyPairApi> getKeyPairApi();\n   \n   @Delegate\n   Optional<? extends KeyPairApi> getKeyPairApiForRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region);\n\n   /**\n    * Provides synchronous access to SecurityGroup services.\n    */\n   @Delegate\n   Optional<? extends SecurityGroupApi> getSecurityGroupApi();\n\n   @Delegate\n   Optional<? extends SecurityGroupApi> getSecurityGroupApiForRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region);\n\n   /**\n    * Provides synchronous access to Availability Zones and Regions services.\n    */\n   @Delegate\n   Optional<? extends AvailabilityZoneAndRegionApi> getAvailabilityZoneAndRegionApi();\n\n   @Delegate\n   Optional<? extends AvailabilityZoneAndRegionApi> getAvailabilityZoneAndRegionApiForRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region);\n\n   /**\n    * Provides synchronous access to Elastic Block Store services.\n    */\n   @Delegate\n   Optional<? extends ElasticBlockStoreApi> getElasticBlockStoreApi();\n\n   @Delegate\n   Optional<? extends ElasticBlockStoreApi> getElasticBlockStoreApiForRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region);\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/EC2ApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2;\n\nimport static org.jclouds.aws.reference.AWSConstants.PROPERTY_AUTH_TAG;\nimport static org.jclouds.aws.reference.AWSConstants.PROPERTY_HEADER_TAG;\nimport static org.jclouds.compute.config.ComputeServiceProperties.RESOURCENAME_DELIMITER;\nimport static org.jclouds.ec2.reference.EC2Constants.PROPERTY_EC2_AMI_OWNERS;\nimport static org.jclouds.ec2.reference.EC2Constants.PROPERTY_EC2_AUTO_ALLOCATE_ELASTIC_IPS;\nimport static org.jclouds.ec2.reference.EC2Constants.PROPERTY_EC2_GENERATE_INSTANCE_NAMES;\nimport static org.jclouds.ec2.reference.EC2Constants.PROPERTY_EC2_TIMEOUT_SECURITYGROUP_PRESENT;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.ec2.compute.EC2ComputeServiceContext;\nimport org.jclouds.ec2.compute.config.EC2ComputeServiceContextModule;\nimport org.jclouds.ec2.compute.config.EC2ResolveImagesModule;\nimport org.jclouds.ec2.config.EC2HttpApiModule;\nimport org.jclouds.rest.internal.BaseHttpApiMetadata;\n\nimport com.google.auto.service.AutoService;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n@AutoService(ApiMetadata.class)\npublic final class EC2ApiMetadata extends BaseHttpApiMetadata<EC2Api> {\n\n   @Override\n   public Builder toBuilder() {\n      return new Builder().fromApiMetadata(this);\n   }\n\n   public EC2ApiMetadata() {\n      super(new Builder());\n   }\n\n   protected EC2ApiMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = BaseHttpApiMetadata.defaultProperties();\n      properties.setProperty(PROPERTY_AUTH_TAG, \"AWS\");\n      properties.setProperty(PROPERTY_HEADER_TAG, \"amz\");\n      properties.setProperty(PROPERTY_EC2_AMI_OWNERS, \"*\");\n      properties.setProperty(PROPERTY_EC2_TIMEOUT_SECURITYGROUP_PRESENT, \"500\");\n      properties.setProperty(PROPERTY_EC2_AUTO_ALLOCATE_ELASTIC_IPS, \"false\");\n      properties.setProperty(RESOURCENAME_DELIMITER, \"#\");\n      properties.setProperty(PROPERTY_EC2_GENERATE_INSTANCE_NAMES, \"true\");\n      return properties;\n   }\n\n   public static final class Builder extends BaseHttpApiMetadata.Builder<EC2Api, Builder> {\n      public Builder() {\n         id(\"ec2\")\n         .name(\"Amazon Elastic Compute Cloud (EC2) API\")\n         .identityName(\"Access Key ID\")\n         .credentialName(\"Secret Access Key\")\n         .defaultEndpoint(\"https://ec2.us-east-1.amazonaws.com\")\n         .documentation(URI.create(\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference\"))\n         .version(\"2010-08-31\")\n         .defaultProperties(EC2ApiMetadata.defaultProperties())\n         .view(EC2ComputeServiceContext.class)\n         .defaultModules(ImmutableSet.<Class<? extends Module>>of(EC2HttpApiModule.class, EC2ResolveImagesModule.class, EC2ComputeServiceContextModule.class));\n      }\n\n      @Override\n      public ApiMetadata build() {\n         return new EC2ApiMetadata(this);\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/EC2Fallbacks.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Throwables.propagate;\n\nimport org.jclouds.Fallback;\nimport org.jclouds.aws.AWSResponseException;\n\nimport com.google.common.base.Predicates;\nimport com.google.common.collect.ImmutableSet;\n\npublic final class EC2Fallbacks {\n   private EC2Fallbacks() {\n   }\n\n   public static final class VoidOnVolumeAvailable implements Fallback<Void> {\n      @Override\n      public Void createOrPropagate(Throwable t) throws Exception {\n         if (checkNotNull(t, \"throwable\") instanceof AWSResponseException) {\n            AWSResponseException e = AWSResponseException.class.cast(t);\n            if (Predicates.in(ImmutableSet.of(\"IncorrectState\", \"available\")).apply(e.getError().getCode()))\n               return null;\n         }\n         throw propagate(t);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/binders/BindBlockDeviceMappingToIndexedFormParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static java.lang.String.format;\nimport static org.jclouds.http.utils.Queries.queryParser;\nimport static org.jclouds.io.Payloads.newUrlEncodedFormPayload;\n\nimport java.util.Map;\nimport java.util.Map.Entry;\n\nimport org.jclouds.ec2.domain.BlockDevice;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.Multimap;\n\npublic class BindBlockDeviceMappingToIndexedFormParams implements Binder {\n\n   private static final String deviceNamePattern = \"BlockDeviceMapping.%d.DeviceName\";\n   private static final String deleteOnTerminationPattern = \"BlockDeviceMapping.%d.Ebs.DeleteOnTermination\";\n   private static final String volumeIdPattern = \"BlockDeviceMapping.%d.Ebs.VolumeId\";\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkArgument(checkNotNull(input, \"input\") instanceof Map, \"this binder is only valid for Map\");\n      Map<String, BlockDevice> blockDeviceMapping = (Map<String, BlockDevice>) input;\n      Multimap<String, String> original = queryParser().apply(request.getPayload().getRawContent().toString());\n      ImmutableMultimap.Builder<String, String> builder = ImmutableMultimap.builder();\n      builder.putAll(\"Action\", \"ModifyInstanceAttribute\");\n      int amazonOneBasedIndex = 1; // according to docs, counters must start with 1\n      for (Entry<String, BlockDevice> ebsBlockDeviceName : blockDeviceMapping.entrySet()) {\n         // not null by contract\n         builder.put(format(deviceNamePattern, amazonOneBasedIndex), ebsBlockDeviceName.getKey());\n         builder.put(format(deleteOnTerminationPattern, amazonOneBasedIndex),\n               String.valueOf(ebsBlockDeviceName.getValue().isDeleteOnTermination()));\n         builder.put(format(volumeIdPattern, amazonOneBasedIndex), ebsBlockDeviceName.getValue().getVolumeId());\n         amazonOneBasedIndex++;\n      }\n      builder.putAll(\"InstanceId\", original.get(\"InstanceId\"));\n      request.setPayload(newUrlEncodedFormPayload(builder.build()));\n      return request;\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/binders/BindBundleIdsToIndexedFormParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.binders;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\n/**\n * Binds the String [] to form parameters named with BundleId.index\n */\n@Singleton\npublic class BindBundleIdsToIndexedFormParams implements Binder {\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      return AWSUtils.indexStringArrayToFormValuesWithPrefix(request, \"BundleId\", input);\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/binders/BindFiltersToIndexedFormParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\nimport com.google.common.collect.Multimap;\n\n/**\n * Binds the Multimap to form parameters for filtering.\n * \n * <pre>\n * https://ec2.amazonaws.com/?Action=DescribeTags\n * &Filter.1.Name=resource-type\n * &Filter.1.Value.1=instance\n * &Filter.2.Name=key\n * &Filter.2.Value.1=stack\n * &Filter.3.Name=value\n * &Filter.3.Value.1=Test\n * &Filter.3.Value.2=Production\n * &AUTHPARAMS\n * </pre>\n */\n@Singleton\npublic class BindFiltersToIndexedFormParams implements Binder {\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkArgument(checkNotNull(input, \"input\") instanceof Multimap, \"this binder is only valid for Multimap\");\n      @SuppressWarnings(\"unchecked\")\n      Multimap<String, String> filters = (Multimap<String, String>) input;\n      return AWSUtils.indexMultimapToFormValuesWithPrefix(request, \"Filter\", \"Name\", \"Value\", filters);\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/binders/BindGroupIdsToIndexedFormParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.binders;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\n/**\n * Binds the String [] to query parameters named with GroupId.index\n */\n@Singleton\npublic class BindGroupIdsToIndexedFormParams implements Binder {\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      return AWSUtils.indexStringArrayToFormValuesWithPrefix(request, \"GroupId\", input);\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/binders/BindGroupNamesToIndexedFormParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.binders;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\n/**\n * Binds the String [] to query parameters named with GroupName.index\n */\n@Singleton\npublic class BindGroupNamesToIndexedFormParams implements Binder {\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      return AWSUtils.indexStringArrayToFormValuesWithPrefix(request, \"GroupName\", input);\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/binders/BindInstanceIdsToIndexedFormParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.binders;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\n/**\n * Binds the String [] to form parameters named with InstanceId.index\n */\n@Singleton\npublic class BindInstanceIdsToIndexedFormParams implements Binder {\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      return AWSUtils.indexStringArrayToFormValuesWithPrefix(request, \"InstanceId\", input);\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/binders/BindIpPermissionToIndexedFormParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.ec2.util.IpPermissions;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.net.domain.IpPermission;\nimport org.jclouds.rest.Binder;\n\npublic class BindIpPermissionToIndexedFormParams implements Binder {\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkArgument(checkNotNull(input, \"input\") instanceof IpPermission, \"this binder is only valid for IpPermission\");\n      IpPermission perm = (IpPermission) input;\n      return (R) request.toBuilder().replaceFormParams(IpPermissions.buildFormParametersForIndex(0, perm)).build();\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/binders/BindIpPermissionsToIndexedFormParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.ec2.util.IpPermissions;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.net.domain.IpPermission;\nimport org.jclouds.rest.Binder;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableMultimap.Builder;\n\npublic class BindIpPermissionsToIndexedFormParams implements Binder {\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkArgument(checkNotNull(input, \"input\") instanceof Iterable,\n            \"this binder is only valid for Iterable<IpPermission>\");\n      Builder<String, String> formBuilder = ImmutableMultimap.builder();\n      int index = 0;\n      for (IpPermission perm : (Iterable<IpPermission>) input)\n         formBuilder.putAll(IpPermissions.buildFormParametersForIndex(index++, perm));\n      ImmutableMultimap<String, String> forms = formBuilder.build();\n      return forms.isEmpty() ? request : (R) request.toBuilder().replaceFormParams(forms).build();\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/binders/BindKeyNamesToIndexedFormParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.binders;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\n/**\n * Binds the String [] to query parameters named with KeyName.index\n */\n@Singleton\npublic class BindKeyNamesToIndexedFormParams implements Binder {\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      return AWSUtils.indexStringArrayToFormValuesWithPrefix(request, \"KeyName\", input);\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/binders/BindProductCodesToIndexedFormParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.binders;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\n/**\n * Binds the Iterable to form parameters named with ProductCode.index\n */\n@Singleton\npublic class BindProductCodesToIndexedFormParams implements Binder {\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      return AWSUtils.indexIterableToFormValuesWithPrefix(request, \"ProductCode\", input);\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/binders/BindPublicIpsToIndexedFormParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\n/**\n * Binds the String [] to form parameters named with InstanceId.index\n */\n@Singleton\npublic class BindPublicIpsToIndexedFormParams implements Binder {\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkArgument(checkNotNull(input, \"input\") instanceof String[], \"this binder is only valid for String[] : \"\n            + input.getClass());\n      String[] addressStrings = (String[]) input;\n      return AWSUtils.indexStringArrayToFormValuesWithPrefix(request, \"PublicIp\", addressStrings);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/binders/BindResourceIdsToIndexedFormParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\n/**\n * Binds Ids to query parameters named with ResourceId.index\n */\n@Singleton\npublic class BindResourceIdsToIndexedFormParams implements Binder {\n    @Override\n    public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n        checkArgument(checkNotNull(input, \"input\") instanceof Iterable, \"this binder is only valid for Iterable<String>\");\n        return AWSUtils.indexIterableToFormValuesWithPrefix(request, \"ResourceId\", input);\n    }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/binders/BindS3UploadPolicyAndSignature.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.binders;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.io.BaseEncoding.base64;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.aws.filters.FormSigner.FormSignerV2;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableMultimap.Builder;\n\n// TODO: see if this still exists in V4\npublic class BindS3UploadPolicyAndSignature implements Binder {\n   private final FormSignerV2 signer;\n\n   @Inject\n   BindS3UploadPolicyAndSignature(FormSignerV2 signer) {\n      this.signer = signer;\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      String encodedJson = base64().encode(checkNotNull(input, \"json\").toString().getBytes(UTF_8));\n      Builder<String, String> builder = ImmutableMultimap.builder();\n      builder.put(\"Storage.S3.UploadPolicy\", encodedJson);\n      String signature = signer.sign(encodedJson);\n      builder.put(\"Storage.S3.UploadPolicySignature\", signature);\n      return (R) request.toBuilder().replaceFormParams(builder.build()).build();\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/binders/BindSubnetIdsToIndexedFormParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.binders;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\n/**\n * Binds the String [] to query parameters named with SubnetId.index\n */\n@Singleton\npublic class BindSubnetIdsToIndexedFormParams implements Binder {\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      return AWSUtils.indexStringArrayToFormValuesWithPrefix(request, \"SubnetId\", input);\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/binders/BindTagKeysToIndexedFormParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\nimport com.google.common.collect.Iterables;\n\n/**\n * Binds the Iterable<String> to form parameters named with Tag.index.Key\n */\n@Singleton\npublic class BindTagKeysToIndexedFormParams implements Binder {\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkArgument(checkNotNull(input, \"input\") instanceof Iterable, \"This binder is only valid for Iterable<String>\");\n      @SuppressWarnings(\"unchecked\")\n      Iterable<String> keys = (Iterable<String>) input;\n      return AWSUtils.indexStringArrayToFormValuesWithStringFormat(request, \"Tag.%s.Key\",\n            Iterables.toArray(keys, String.class));\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/binders/BindTagsToIndexedFormParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.binders;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.aws.util.AWSUtils.indexMapToFormValuesWithPrefix;\n\nimport java.util.Map;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMap.Builder;\n\npublic class BindTagsToIndexedFormParams implements Binder {\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkNotNull(input, \"tags\");\n      Map<String, String> tagValues;\n      if (input instanceof Iterable) {\n         Builder<String, String> builder = ImmutableMap.<String, String> builder();\n         for (String key : (Iterable<String>) input) {\n            builder.put(key, \"\");\n         }\n         tagValues = builder.build();\n      } else if (input instanceof Map) {\n         tagValues = Map.class.cast(input);\n      } else {\n         throw new IllegalArgumentException(\"This binder is only valid for Map<String,String> or Iterable<String>\");\n      }\n      return indexMapToFormValuesWithPrefix(request, \"Tag\", \"Key\", \"Value\", tagValues);\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/binders/BindUserGroupsToIndexedFormParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\nimport com.google.common.collect.Iterables;\n\n/**\n * Binds the Iterable to query parameters named with UserGroup.index\n */\n@Singleton\npublic class BindUserGroupsToIndexedFormParams implements Binder {\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkArgument(checkNotNull(input, \"input\") instanceof Iterable<?>, \"this binder is only valid for Iterable<?>: \"\n            + input.getClass());\n      checkValidUserGroup(input);\n      return AWSUtils.indexIterableToFormValuesWithPrefix(request, \"UserGroup\", input);\n   }\n\n   private void checkValidUserGroup(Object input) {\n      Iterable<?> values = (Iterable<?>) input;\n      long size = Iterables.size(values);\n      checkArgument(size == 0 || (size == 1 && Iterables.getOnlyElement(values).equals(\"all\")),\n            \"only supported UserGroup is 'all'\");\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/binders/BindUserIdGroupPairToSourceSecurityGroupFormParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.ec2.domain.UserIdGroupPair;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableMultimap.Builder;\n\n/**\n * Binds the String [] to query parameters named with GroupName.index\n */\n@Singleton\npublic class BindUserIdGroupPairToSourceSecurityGroupFormParams implements Binder {\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkArgument(checkNotNull(input, \"input\") instanceof UserIdGroupPair,\n            \"this binder is only valid for UserIdGroupPair!\");\n      UserIdGroupPair pair = (UserIdGroupPair) input;\n      Builder<String, String> builder = ImmutableMultimap.builder();\n      builder.put(\"SourceSecurityGroupOwnerId\", pair.getUserId());\n      builder.put(\"SourceSecurityGroupName\", pair.getGroupName());\n      return (R) request.toBuilder().replaceFormParams(builder.build()).build();\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/binders/BindUserIdsToIndexedFormParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.binders;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\n/**\n * Binds the Iterable to form parameters named with UserId.index\n */\n@Singleton\npublic class BindUserIdsToIndexedFormParams implements Binder {\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      return AWSUtils.indexIterableToFormValuesWithPrefix(request, \"UserId\", input);\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/binders/BindVolumeIdsToIndexedFormParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.binders;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\n/**\n * Binds the String [] to form parameters named with VolumeId.index\n */\n@Singleton\npublic class BindVolumeIdsToIndexedFormParams implements Binder {\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      return AWSUtils.indexStringArrayToFormValuesWithPrefix(request, \"VolumeId\", input);\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/binders/IfNotNullBindAvailabilityZoneToFormParam.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\n/**\n * Binds the AvailabilityZone to a form parameter if set.\n */\n@Singleton\npublic class IfNotNullBindAvailabilityZoneToFormParam implements Binder {\n   private final String param;\n\n   @Inject\n   protected IfNotNullBindAvailabilityZoneToFormParam() {\n      this(\"Placement.AvailabilityZone\");\n   }\n\n   protected IfNotNullBindAvailabilityZoneToFormParam(String param) {\n      this.param = param;\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      if (input != null) {\n         checkArgument(input instanceof String, \"this binder is only valid for String!\");\n         return (R) request.toBuilder().replaceFormParam(param, String.class.cast(input)).build();\n      }\n      return request;\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/EC2ComputeService.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Strings.emptyToNull;\nimport static com.google.common.collect.Iterables.concat;\nimport static com.google.common.collect.Iterables.transform;\nimport static com.google.common.collect.Lists.newArrayList;\nimport static java.util.concurrent.TimeUnit.MILLISECONDS;\nimport static org.jclouds.compute.config.ComputeServiceProperties.RESOURCENAME_DELIMITER;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_RUNNING;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_SUSPENDED;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_TERMINATED;\nimport static org.jclouds.compute.util.ComputeServiceUtils.addMetadataAndParseTagsFromValuesOfEmptyString;\nimport static org.jclouds.compute.util.ComputeServiceUtils.metadataAndTagsAsValuesOfEmptyString;\nimport static org.jclouds.ec2.reference.EC2Constants.PROPERTY_EC2_GENERATE_INSTANCE_NAMES;\nimport static org.jclouds.ec2.util.Tags.resourceToTagsAsMap;\nimport static org.jclouds.util.Predicates2.retry;\n\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentMap;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport jakarta.inject.Named;\nimport jakarta.inject.Provider;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Constants;\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.compute.RunNodesException;\nimport org.jclouds.compute.callables.RunScriptOnNode;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadataBuilder;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.domain.TemplateBuilder;\nimport org.jclouds.compute.extensions.ImageExtension;\nimport org.jclouds.compute.extensions.SecurityGroupExtension;\nimport org.jclouds.compute.extensions.internal.DelegatingImageExtension;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.compute.functions.GroupNamingConvention.Factory;\nimport org.jclouds.compute.internal.BaseComputeService;\nimport org.jclouds.compute.internal.PersistNodeCredentials;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.compute.reference.ComputeServiceConstants.Timeouts;\nimport org.jclouds.compute.strategy.CreateNodesInGroupThenAddToSet;\nimport org.jclouds.compute.strategy.DestroyNodeStrategy;\nimport org.jclouds.compute.strategy.GetImageStrategy;\nimport org.jclouds.compute.strategy.GetNodeMetadataStrategy;\nimport org.jclouds.compute.strategy.InitializeRunScriptOnNodeOrPlaceInBadMap;\nimport org.jclouds.compute.strategy.ListNodesStrategy;\nimport org.jclouds.compute.strategy.RebootNodeStrategy;\nimport org.jclouds.compute.strategy.ResumeNodeStrategy;\nimport org.jclouds.compute.strategy.SuspendNodeStrategy;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.domain.Location;\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.compute.domain.RegionNameAndIngressRules;\nimport org.jclouds.ec2.compute.options.EC2TemplateOptions;\nimport org.jclouds.ec2.domain.InstanceState;\nimport org.jclouds.ec2.domain.KeyPair;\nimport org.jclouds.ec2.domain.RunningInstance;\nimport org.jclouds.ec2.domain.SecurityGroup;\nimport org.jclouds.ec2.domain.Tag;\nimport org.jclouds.ec2.util.TagFilterBuilder;\nimport org.jclouds.scriptbuilder.functions.InitAdminAccess;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableMultimap.Builder;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Maps;\nimport com.google.common.collect.Multimap;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.inject.Inject;\n\n@Singleton\npublic class EC2ComputeService extends BaseComputeService {\n   private final EC2Api client;\n   private final ConcurrentMap<RegionAndName, KeyPair> credentialsMap;\n   private final LoadingCache<RegionAndName, String> securityGroupMap;\n   private final Factory namingConvention;\n   private final boolean generateInstanceNames;\n   private final Timeouts timeouts;\n\n   @Inject\n   protected EC2ComputeService(ComputeServiceContext context, Map<String, Credentials> credentialStore,\n         @Memoized Supplier<Set<? extends Image>> images, @Memoized Supplier<Set<? extends Hardware>> sizes,\n         @Memoized Supplier<Set<? extends Location>> locations, ListNodesStrategy listNodesStrategy,\n         GetImageStrategy getImageStrategy, GetNodeMetadataStrategy getNodeMetadataStrategy,\n         CreateNodesInGroupThenAddToSet runNodesAndAddToSetStrategy, RebootNodeStrategy rebootNodeStrategy,\n         DestroyNodeStrategy destroyNodeStrategy, ResumeNodeStrategy startNodeStrategy,\n         SuspendNodeStrategy stopNodeStrategy, Provider<TemplateBuilder> templateBuilderProvider,\n         @Named(\"DEFAULT\") Provider<TemplateOptions> templateOptionsProvider,\n         @Named(TIMEOUT_NODE_RUNNING) Predicate<AtomicReference<NodeMetadata>> nodeRunning,\n         @Named(TIMEOUT_NODE_TERMINATED) Predicate<AtomicReference<NodeMetadata>> nodeTerminated,\n         @Named(TIMEOUT_NODE_SUSPENDED) Predicate<AtomicReference<NodeMetadata>> nodeSuspended,\n         InitializeRunScriptOnNodeOrPlaceInBadMap.Factory initScriptRunnerFactory,\n         RunScriptOnNode.Factory runScriptOnNodeFactory, InitAdminAccess initAdminAccess,\n         PersistNodeCredentials persistNodeCredentials, Timeouts timeouts,\n         @Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor, EC2Api client,\n         ConcurrentMap<RegionAndName, KeyPair> credentialsMap,\n         @Named(\"SECURITY\") LoadingCache<RegionAndName, String> securityGroupMap,\n         Optional<ImageExtension> imageExtension, GroupNamingConvention.Factory namingConvention,\n         @Named(PROPERTY_EC2_GENERATE_INSTANCE_NAMES) boolean generateInstanceNames,\n         Optional<SecurityGroupExtension> securityGroupExtension,\n         DelegatingImageExtension.Factory delegatingImageExtension) {\n      super(context, credentialStore, images, sizes, locations, listNodesStrategy, getImageStrategy,\n            getNodeMetadataStrategy, runNodesAndAddToSetStrategy, rebootNodeStrategy, destroyNodeStrategy,\n            startNodeStrategy, stopNodeStrategy, templateBuilderProvider, templateOptionsProvider, nodeRunning,\n            nodeTerminated, nodeSuspended, initScriptRunnerFactory, initAdminAccess, runScriptOnNodeFactory,\n            persistNodeCredentials, userExecutor, imageExtension, securityGroupExtension, delegatingImageExtension);\n      this.client = client;\n      this.credentialsMap = credentialsMap;\n      this.securityGroupMap = securityGroupMap;\n      this.namingConvention = namingConvention;\n      this.generateInstanceNames = generateInstanceNames;\n      this.timeouts = timeouts;\n   }\n\n   @Override\n   public Set<? extends NodeMetadata> createNodesInGroup(String group, int count, final Template template)\n            throws RunNodesException {\n      Set<? extends NodeMetadata> nodes = super.createNodesInGroup(group, count, template);\n      String region = AWSUtils.getRegionFromLocationOrNull(template.getLocation());\n\n      if (client.getTagApiForRegion(region).isPresent()) {\n         Map<String, String> common = metadataAndTagsAsValuesOfEmptyString(template.getOptions());\n         if (generateInstanceNames || !common.isEmpty() || !template.getOptions().getNodeNames().isEmpty()) {\n            return addTagsAndNamesToInstancesInRegion(common, template.getOptions().getNodeNames(),\n                    nodes, region, group);\n         }\n      }\n      return nodes;\n   }\n\n   private static final Function<NodeMetadata, String> instanceId = new Function<NodeMetadata, String>() {\n      @Override\n      public String apply(NodeMetadata in) {\n         return in.getProviderId();\n      }\n   };\n\n   private Set<NodeMetadata> addTagsAndNamesToInstancesInRegion(Map<String, String> common, Set<String> nodeNames,\n                                                                Set<? extends NodeMetadata> input, String region,\n                                                                String group) {\n      Map<String, ? extends NodeMetadata> instancesById = Maps.uniqueIndex(input, instanceId);\n      ImmutableSet.Builder<NodeMetadata> builder = ImmutableSet.<NodeMetadata> builder();\n\n      List<String> namesToUse = newArrayList(nodeNames);\n      if (generateInstanceNames && !common.containsKey(\"Name\")) {\n         for (Map.Entry<String, ? extends NodeMetadata> entry : instancesById.entrySet()) {\n            String id = entry.getKey();\n            String name;\n            if (!namesToUse.isEmpty()) {\n               name = namesToUse.remove(0);\n            } else {\n               name = id.replaceAll(\".*-\", group + \"-\");\n            }\n            Map<String, String> tags = ImmutableMap.<String, String> builder().putAll(common)\n                  .put(\"Name\", name).build();\n            logger.debug(\">> applying tags %s to instance %s in region %s\", tags, id, region);\n            client.getTagApiForRegion(region).get().applyToResources(tags, ImmutableSet.of(id));\n            builder.add(addTagsForInstance(tags, instancesById.get(id)));\n         }\n      } else {\n         Iterable<String> ids = instancesById.keySet();\n         logger.debug(\">> applying tags %s to instances %s in region %s\", common, ids, region);\n         client.getTagApiForRegion(region).get().applyToResources(common, ids);\n         for (NodeMetadata in : input)\n            builder.add(addTagsForInstance(common, in));\n      }\n      if (logger.isDebugEnabled()) {\n         Multimap<String, String> filter = new TagFilterBuilder().resourceIds(instancesById.keySet()).build();\n         FluentIterable<Tag> tags = client.getTagApiForRegion(region).get().filter(filter);\n         logger.debug(\"<< applied tags in region %s: %s\", region, resourceToTagsAsMap(tags));\n      }\n      return builder.build();\n   }\n\n   private static NodeMetadata addTagsForInstance(Map<String, String> tags, NodeMetadata input) {\n      NodeMetadataBuilder builder = NodeMetadataBuilder.fromNodeMetadata(input).name(tags.get(\"Name\"));\n      return addMetadataAndParseTagsFromValuesOfEmptyString(builder, tags).build();\n   }\n\n   @Inject(optional = true)\n   @Named(RESOURCENAME_DELIMITER)\n   char delimiter = '#';\n\n   /**\n    * @throws IllegalStateException If the security group was in use\n    */\n   @VisibleForTesting\n   void deleteSecurityGroup(String region, String group) {\n      checkNotNull(emptyToNull(region), \"region must be defined\");\n      checkNotNull(emptyToNull(group), \"group must be defined\");\n      String groupName = namingConvention.create().sharedNameForGroup(group);\n\n      Multimap<String, String> securityGroupFilterByName = ImmutableMultimap.of(\"group-name\", groupName);\n      Set<SecurityGroup> securityGroupsToDelete = client.getSecurityGroupApi().get()\n              .describeSecurityGroupsInRegionWithFilter(region, securityGroupFilterByName);\n      if (securityGroupsToDelete.size() > 1) {\n         logger.warn(\"When trying to delete security group %s found more than one matching the name. Will delete all - %s.\",\n                 group, securityGroupsToDelete);\n      }\n      for (SecurityGroup securityGroup : securityGroupsToDelete) {\n         logger.debug(\">> deleting securityGroup(%s)\", groupName);\n         client.getSecurityGroupApi().get().deleteSecurityGroupInRegionById(region, securityGroup.getId());\n         securityGroupMap.invalidate(new RegionNameAndIngressRules(region, groupName, null, false, null));\n         logger.debug(\"<< deleted securityGroup(%s)\", groupName);\n      }\n   }\n\n   @VisibleForTesting\n   void deleteKeyPair(String region, String group) {\n      for (KeyPair keyPair : client.getKeyPairApi().get().describeKeyPairsInRegionWithFilter(region,\n              ImmutableMultimap.<String, String>builder()\n                      .put(\"key-name\", String.format(\"jclouds#%s#*\", group).replace('#', delimiter))\n                      .build())) {\n         String keyName = keyPair.getKeyName();\n         Predicate<String> keyNameMatcher = namingConvention.create().containsGroup(group);\n         String oldKeyNameRegex = String.format(\"jclouds#%s#%s#%s\", group, region, \"[0-9a-f]+\").replace('#', delimiter);\n         // old keypair pattern too verbose as it has an unnecessary region qualifier\n\n         if (keyNameMatcher.apply(keyName) || keyName.matches(oldKeyNameRegex)) {\n            Set<String> instancesUsingKeyPair = extractIdsFromInstances(concat(client.getInstanceApi().get()\n                  .describeInstancesInRegionWithFilter(region, ImmutableMultimap.<String, String>builder()\n                          .put(\"instance-state-name\", InstanceState.TERMINATED.toString())\n                          .put(\"instance-state-name\", InstanceState.SHUTTING_DOWN.toString())\n                          .put(\"key-name\", keyPair.getKeyName()).build())));\n\n            if (!instancesUsingKeyPair.isEmpty()) {\n               logger.debug(\"<< inUse keyPair(%s), by (%s)\", keyPair.getKeyName(), instancesUsingKeyPair);\n            } else {\n               logger.debug(\">> deleting keyPair(%s)\", keyPair.getKeyName());\n               client.getKeyPairApi().get().deleteKeyPairInRegion(region, keyPair.getKeyName());\n               // TODO: test this clear happens\n               credentialsMap.remove(new RegionAndName(region, keyPair.getKeyName()));\n               credentialsMap.remove(new RegionAndName(region, group));\n               logger.debug(\"<< deleted keyPair(%s)\", keyPair.getKeyName());\n            }\n         }\n      }\n   }\n\n   protected ImmutableSet<String> extractIdsFromInstances(Iterable<? extends RunningInstance> deadOnes) {\n      return ImmutableSet.copyOf(transform(deadOnes, new Function<RunningInstance, String>() {\n\n         @Override\n         public String apply(RunningInstance input) {\n            return input.getId();\n         }\n\n      }));\n   }\n\n   /**\n    * Cleans implicit keypairs and security groups.\n    */\n   @Override\n   protected void cleanUpIncidentalResourcesOfDeadNodes(Set<? extends NodeMetadata> deadNodes) {\n      Builder<String, String> regionGroups = ImmutableMultimap.builder();\n      for (NodeMetadata nodeMetadata : deadNodes) {\n         if (nodeMetadata.getGroup() != null)\n            regionGroups.put(AWSUtils.parseHandle(nodeMetadata.getId())[0], nodeMetadata.getGroup());\n         }\n      for (Entry<String, String> regionGroup : regionGroups.build().entries()) {\n         cleanUpIncidentalResources(regionGroup.getKey(), regionGroup.getValue());\n      }\n   }\n\n   protected void cleanUpIncidentalResources(final String region, final String group) {\n      // For issue #445, tries to delete security groups first: ec2 throws exception if in use, but\n      // deleting a key pair does not.\n      // This is \"belt-and-braces\" because deleteKeyPair also does extractIdsFromInstances & usingKeyPairAndNotDead\n      // for us to check if any instances are using the key-pair before we delete it.\n      // There is (probably?) still a race if someone is creating instances at the same time as deleting them:\n      // we may delete the key-pair just when the node-being-created was about to rely on the incidental\n      // resources existing.\n\n      // Also in #445, in aws-ec2 the deleteSecurityGroup sometimes fails after terminating the final VM using a\n      // given security group, if called very soon after the VM's state reports terminated. Empirically, it seems that\n      // waiting a small time (e.g. enabling logging or debugging!) then the tests pass. We therefore retry.\n      // TODO: this could be moved to a config module, also the narrative above made more concise\n      long timeout = timeouts.cleanupIncidentalResources;\n      retry(new Predicate<RegionAndName>() {\n         public boolean apply(RegionAndName input) {\n            try {\n               logger.debug(\">> deleting incidentalResources(%s)\", input);\n               deleteSecurityGroup(input.getRegion(), input.getName());\n               deleteKeyPair(input.getRegion(), input.getName()); // not executed if securityGroup was in use\n               logger.debug(\"<< deleted incidentalResources(%s)\", input);\n               return true;\n            } catch (IllegalStateException e) {\n               logger.debug(\"<< inUse incidentalResources(%s)\", input);\n               return false;\n            }\n         }\n      }, timeout, 50, 1000, MILLISECONDS).apply(new RegionAndName(region, group));\n   }\n\n   /**\n    * returns template options, except of type {@link EC2TemplateOptions}.\n    */\n   @Override\n   public EC2TemplateOptions templateOptions() {\n      return EC2TemplateOptions.class.cast(super.templateOptions());\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/EC2ComputeServiceContext.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute;\n\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.ec2.compute.internal.EC2ComputeServiceContextImpl;\n\nimport com.google.inject.ImplementedBy;\n\n@ImplementedBy(EC2ComputeServiceContextImpl.class)\npublic interface EC2ComputeServiceContext extends ComputeServiceContext {\n\n   @Override\n   EC2ComputeService getComputeService();\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/config/EC2BindComputeStrategiesByClass.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.config;\n\nimport org.jclouds.compute.config.BindComputeStrategiesByClass;\nimport org.jclouds.compute.strategy.CreateNodeWithGroupEncodedIntoName;\nimport org.jclouds.compute.strategy.CreateNodesInGroupThenAddToSet;\nimport org.jclouds.compute.strategy.DestroyNodeStrategy;\nimport org.jclouds.compute.strategy.GetImageStrategy;\nimport org.jclouds.compute.strategy.GetNodeMetadataStrategy;\nimport org.jclouds.compute.strategy.ListNodesStrategy;\nimport org.jclouds.compute.strategy.RebootNodeStrategy;\nimport org.jclouds.compute.strategy.ResumeNodeStrategy;\nimport org.jclouds.compute.strategy.SuspendNodeStrategy;\nimport org.jclouds.ec2.compute.strategy.EC2CreateNodesInGroupThenAddToSet;\nimport org.jclouds.ec2.compute.strategy.EC2DestroyNodeStrategy;\nimport org.jclouds.ec2.compute.strategy.EC2GetImageStrategy;\nimport org.jclouds.ec2.compute.strategy.EC2GetNodeMetadataStrategy;\nimport org.jclouds.ec2.compute.strategy.EC2ListNodesStrategy;\nimport org.jclouds.ec2.compute.strategy.EC2RebootNodeStrategy;\nimport org.jclouds.ec2.compute.strategy.EC2ResumeNodeStrategy;\nimport org.jclouds.ec2.compute.strategy.EC2SuspendNodeStrategy;\n\npublic class EC2BindComputeStrategiesByClass extends BindComputeStrategiesByClass {\n   @Override\n   protected Class<? extends CreateNodesInGroupThenAddToSet> defineRunNodesAndAddToSetStrategy() {\n      return EC2CreateNodesInGroupThenAddToSet.class;\n   }\n\n   /**\n    * not needed, as {@link EC2CreateNodesInGroupThenAddToSet} is used and is already set-based.\n    */\n   @Override\n   protected Class<? extends CreateNodeWithGroupEncodedIntoName> defineAddNodeWithTagStrategy() {\n      return null;\n   }\n\n   /**\n    * not needed, as {@link EC2CreateNodesInGroupThenAddToSet} is used and is already set-based.\n    */\n   @Override\n   protected void bindAddNodeWithTagStrategy(Class<? extends CreateNodeWithGroupEncodedIntoName> clazz) {\n   }\n\n   @Override\n   protected Class<? extends DestroyNodeStrategy> defineDestroyNodeStrategy() {\n      return EC2DestroyNodeStrategy.class;\n   }\n\n   @Override\n   protected Class<? extends GetNodeMetadataStrategy> defineGetNodeMetadataStrategy() {\n      return EC2GetNodeMetadataStrategy.class;\n   }\n\n   @Override\n   protected Class<? extends GetImageStrategy> defineGetImageStrategy() {\n      return EC2GetImageStrategy.class;\n   }\n\n   @Override\n   protected Class<? extends ListNodesStrategy> defineListNodesStrategy() {\n      return EC2ListNodesStrategy.class;\n   }\n\n   @Override\n   protected Class<? extends RebootNodeStrategy> defineRebootNodeStrategy() {\n      return EC2RebootNodeStrategy.class;\n   }\n\n   @Override\n   protected Class<? extends ResumeNodeStrategy> defineStartNodeStrategy() {\n      return EC2ResumeNodeStrategy.class;\n   }\n\n   @Override\n   protected Class<? extends SuspendNodeStrategy> defineStopNodeStrategy() {\n      return EC2SuspendNodeStrategy.class;\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/config/EC2BindComputeSuppliersByClass.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.config;\n\nimport java.util.Set;\n\nimport org.jclouds.compute.config.BindComputeSuppliersByClass;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.ec2.compute.suppliers.EC2HardwareSupplier;\nimport org.jclouds.ec2.compute.suppliers.EC2ImageSupplier;\n\nimport com.google.common.base.Supplier;\npublic class EC2BindComputeSuppliersByClass extends BindComputeSuppliersByClass {\n   @Override\n   protected Class<? extends Supplier<Set<? extends Hardware>>> defineHardwareSupplier() {\n      return EC2HardwareSupplier.class;\n   }\n\n   @Override\n   protected Class<? extends Supplier<Set<? extends Image>>> defineImageSupplier() {\n      return EC2ImageSupplier.class;\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/config/EC2ComputeServiceContextModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.config;\n\nimport static com.google.common.collect.Iterables.toArray;\nimport static org.jclouds.ec2.reference.EC2Constants.PROPERTY_EC2_AMI_OWNERS;\n\nimport java.util.Set;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.compute.config.BaseComputeServiceContextModule;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.ec2.compute.EC2ComputeService;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.compute.loaders.RegionAndIdToImage;\nimport org.jclouds.ec2.compute.suppliers.RegionAndNameToImageSupplier;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.suppliers.SetAndThrowAuthorizationExceptionSupplier;\n\nimport com.google.common.base.Splitter;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.base.Throwables;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.util.concurrent.Atomics;\nimport com.google.inject.Injector;\nimport com.google.inject.Key;\nimport com.google.inject.Provides;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.name.Names;\n\n/**\n * Configures the {@link ComputeServiceContext}; requires {@link EC2ComputeService} bound.\n */\npublic class EC2ComputeServiceContextModule extends BaseComputeServiceContextModule {\n   @Override\n   protected void configure() {\n      installDependencies();\n      install(new EC2BindComputeStrategiesByClass());\n      install(new EC2BindComputeSuppliersByClass());\n      super.configure();\n   }\n\n   protected void installDependencies() {\n      install(new EC2ComputeServiceDependenciesModule());\n   }\n\n   @Override\n   protected boolean shouldEagerlyParseImages(Injector injector) {\n      // If no owners to query, then will never lookup all images\n      String[] amiOwners = injector.getInstance(Key.get(String[].class, Names.named(PROPERTY_EC2_AMI_OWNERS)));\n      return amiOwners.length > 0;\n   }\n\n   @Override\n   protected Supplier<Set<? extends Image>> supplyNonParsingImages(final Supplier<Set<? extends Image>> imageSupplier,\n         Injector injector) {\n      final Supplier<LoadingCache<RegionAndName, ? extends Image>> cache = injector.getInstance(Key.get(new TypeLiteral<Supplier<LoadingCache<RegionAndName, ? extends Image>>>() {}));\n      return new Supplier<Set<? extends Image>>() {\n         @Override\n         public Set<? extends Image> get() {\n            return ImmutableSet.copyOf(cache.get().asMap().values());\n         }\n      };\n   }\n\n   @Provides\n   @Singleton\n   protected final Supplier<LoadingCache<RegionAndName, ? extends Image>> provideRegionAndNameToImageSupplierCache(\n            final RegionAndNameToImageSupplier supplier) {\n      return supplier;\n   }\n\n   @Provides\n   @Singleton\n   protected final Supplier<CacheLoader<RegionAndName, Image>> guiceProvideRegionAndNameToImageSupplierCacheLoader(\n           final RegionAndIdToImage delegate) {\n      return provideRegionAndNameToImageSupplierCacheLoader(delegate);\n   }\n\n   protected Supplier<CacheLoader<RegionAndName, Image>> provideRegionAndNameToImageSupplierCacheLoader(\n            final RegionAndIdToImage delegate) {\n      return Suppliers.<CacheLoader<RegionAndName, Image>>ofInstance(new CacheLoader<RegionAndName, Image>() {\n         private final AtomicReference<AuthorizationException> authException = Atomics.newReference();\n\n         @Override\n         public Image load(final RegionAndName key) throws Exception {\n            // raw lookup of an image\n            Supplier<Image> rawSupplier = new Supplier<Image>() {\n               @Override public Image get() {\n                  try {\n                     return delegate.load(key);\n                  } catch (ExecutionException e) {\n                     throw Throwables.propagate(e);\n                  }\n               }\n            };\n            return new SetAndThrowAuthorizationExceptionSupplier<Image>(rawSupplier, authException).get();\n         }\n\n      });\n   }\n\n   @Provides\n   @Singleton\n   @Named(PROPERTY_EC2_AMI_OWNERS)\n   final String[] amiOwners(@Named(PROPERTY_EC2_AMI_OWNERS) String amiOwners) {\n      if (amiOwners.trim().equals(\"\"))\n         return new String[] {};\n      return toArray(Splitter.on(',').split(amiOwners), String.class);\n   }\n}\n\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/config/EC2ComputeServiceDependenciesModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.config;\n\nimport static java.util.concurrent.TimeUnit.MILLISECONDS;\nimport static org.jclouds.ec2.reference.EC2Constants.PROPERTY_EC2_TIMEOUT_SECURITYGROUP_PRESENT;\nimport static org.jclouds.util.Predicates2.retry;\n\nimport java.util.Map;\nimport java.util.concurrent.ConcurrentMap;\n\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.ComputeService;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadata.Status;\nimport org.jclouds.compute.domain.SecurityGroup;\nimport org.jclouds.compute.domain.TemplateBuilder;\nimport org.jclouds.compute.extensions.ImageExtension;\nimport org.jclouds.compute.extensions.SecurityGroupExtension;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.ec2.compute.EC2ComputeService;\nimport org.jclouds.ec2.compute.domain.PasswordDataAndPrivateKey;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.compute.extensions.EC2ImageExtension;\nimport org.jclouds.ec2.compute.extensions.EC2SecurityGroupExtension;\nimport org.jclouds.ec2.compute.functions.AddElasticIpsToNodemetadata;\nimport org.jclouds.ec2.compute.functions.CreateUniqueKeyPair;\nimport org.jclouds.ec2.compute.functions.CredentialsForInstance;\nimport org.jclouds.ec2.compute.functions.EC2ImageParser;\nimport org.jclouds.ec2.compute.functions.EC2SecurityGroupIdFromName;\nimport org.jclouds.ec2.compute.functions.EC2SecurityGroupToSecurityGroup;\nimport org.jclouds.ec2.compute.functions.PasswordCredentialsFromWindowsInstance;\nimport org.jclouds.ec2.compute.functions.RunningInstanceToNodeMetadata;\nimport org.jclouds.ec2.compute.functions.WindowsLoginCredentialsFromEncryptedData;\nimport org.jclouds.ec2.compute.internal.EC2TemplateBuilderImpl;\nimport org.jclouds.ec2.compute.loaders.CreateSecurityGroupIfNeeded;\nimport org.jclouds.ec2.compute.loaders.LoadPublicIpForInstanceOrNull;\nimport org.jclouds.ec2.compute.loaders.RegionAndIdToImage;\nimport org.jclouds.ec2.compute.options.EC2TemplateOptions;\nimport org.jclouds.ec2.compute.predicates.SecurityGroupPresent;\nimport org.jclouds.ec2.domain.Image.ImageState;\nimport org.jclouds.ec2.domain.InstanceState;\nimport org.jclouds.ec2.domain.KeyPair;\nimport org.jclouds.ec2.domain.RunningInstance;\nimport org.jclouds.ec2.reference.EC2Constants;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Function;\nimport com.google.common.base.Functions;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Maps;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Injector;\nimport com.google.inject.Provides;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.name.Names;\n\npublic class EC2ComputeServiceDependenciesModule extends AbstractModule {\n\n   public static final Map<InstanceState, Status> toPortableNodeStatus = ImmutableMap\n            .<InstanceState, Status> builder()\n            .put(InstanceState.PENDING, Status.PENDING)\n            .put(InstanceState.RUNNING, Status.RUNNING)\n            .put(InstanceState.SHUTTING_DOWN, Status.PENDING)\n            .put(InstanceState.TERMINATED, Status.TERMINATED)\n            .put(InstanceState.STOPPING, Status.PENDING)\n            .put(InstanceState.STOPPED, Status.SUSPENDED)\n            .put(InstanceState.UNRECOGNIZED, Status.UNRECOGNIZED)\n            .build();\n   \n   @Singleton\n   @Provides\n   protected final Map<InstanceState, NodeMetadata.Status> toPortableNodeStatus() {\n      return toPortableNodeStatus;\n   }\n   \n   @VisibleForTesting\n   public static final Map<ImageState, Image.Status> toPortableImageStatus = ImmutableMap\n            .<ImageState, Image.Status> builder()\n            .put(ImageState.AVAILABLE, Image.Status.AVAILABLE)\n            .put(ImageState.DEREGISTERED, Image.Status.DELETED)\n            .put(ImageState.UNRECOGNIZED, Image.Status.UNRECOGNIZED).build();\n\n   @Singleton\n   @Provides\n   protected final Map<ImageState, Image.Status> toPortableImageStatus() {\n      return toPortableImageStatus;\n   }\n   \n   @Override\n   protected void configure() {\n      bind(TemplateBuilder.class).to(EC2TemplateBuilderImpl.class);\n      bind(TemplateOptions.class).to(EC2TemplateOptions.class);\n      bind(ComputeService.class).to(EC2ComputeService.class);\n      bind(new TypeLiteral<CacheLoader<RunningInstance, Optional<LoginCredentials>>>() {\n      }).to(CredentialsForInstance.class);\n      bind(new TypeLiteral<Function<RegionAndName, KeyPair>>() {\n      }).to(CreateUniqueKeyPair.class);\n      bind(new TypeLiteral<CacheLoader<RegionAndName, Image>>() {\n      }).to(RegionAndIdToImage.class);\n      bind(new TypeLiteral<CacheLoader<RegionAndName, String>>() {\n      }).annotatedWith(Names.named(\"SECURITY\")).to(CreateSecurityGroupIfNeeded.class);\n      bind(new TypeLiteral<CacheLoader<RegionAndName, String>>() {\n      }).annotatedWith(Names.named(\"ELASTICIP\")).to(LoadPublicIpForInstanceOrNull.class);\n      bind(new TypeLiteral<Function<String, String>>() {\n      }).annotatedWith(Names.named(\"SECGROUP_NAME_TO_ID\")).to(EC2SecurityGroupIdFromName.class);\n      bind(new TypeLiteral<Function<PasswordDataAndPrivateKey, LoginCredentials>>() {\n      }).to(WindowsLoginCredentialsFromEncryptedData.class);\n      bind(new TypeLiteral<Function<RunningInstance, LoginCredentials>>() {\n      }).to(PasswordCredentialsFromWindowsInstance.class);\n      bind(new TypeLiteral<Function<org.jclouds.ec2.domain.Image, Image>>() {\n      }).to(EC2ImageParser.class);\n      bind(new TypeLiteral<Function<org.jclouds.ec2.domain.SecurityGroup, SecurityGroup>>() {\n      }).to(EC2SecurityGroupToSecurityGroup.class);\n      bind(new TypeLiteral<ImageExtension>() {\n      }).to(EC2ImageExtension.class);\n      bind(new TypeLiteral<SecurityGroupExtension>() {\n      }).to(EC2SecurityGroupExtension.class);\n   }\n\n   /**\n    * only add the overhead of looking up ips when we have enabled the auto-allocate functionality\n    */\n   @Provides\n   @Singleton\n   public final Function<RunningInstance, NodeMetadata> bindNodeConverter(RunningInstanceToNodeMetadata baseConverter,\n              AddElasticIpsToNodemetadata addElasticIpsToNodemetadata,\n            @Named(EC2Constants.PROPERTY_EC2_AUTO_ALLOCATE_ELASTIC_IPS) boolean autoAllocateElasticIps) {\n      if (!autoAllocateElasticIps)\n         return baseConverter;\n      return Functions.compose(addElasticIpsToNodemetadata, baseConverter);\n   }\n\n   @Provides\n   @Singleton\n   protected final LoadingCache<RunningInstance, Optional<LoginCredentials>> credentialsMap(CacheLoader<RunningInstance, Optional<LoginCredentials>> in) {\n      return CacheBuilder.newBuilder().build(in);\n   }\n\n   @Provides\n   @Singleton\n   protected final ConcurrentMap<RegionAndName, KeyPair> keypairMap(Injector i) {\n      return Maps.newConcurrentMap();\n   }\n\n   @Provides\n   @Singleton\n   @Named(\"SECURITY\")\n   protected final LoadingCache<RegionAndName, String> securityGroupMap(\n            @Named(\"SECURITY\") CacheLoader<RegionAndName, String> in) {\n      return CacheBuilder.newBuilder().build(in);\n   }\n\n   @Provides\n   @Singleton\n   @Named(\"ELASTICIP\")\n   protected final LoadingCache<RegionAndName, String> instanceToElasticIp(\n            @Named(\"ELASTICIP\") CacheLoader<RegionAndName, String> in) {\n      return CacheBuilder.newBuilder().build(in);\n   }\n\n   @Provides\n   @Singleton\n   @Named(\"SECURITY\")\n   protected final Predicate<RegionAndName> securityGroupEventualConsistencyDelay(SecurityGroupPresent in,\n         @Named(PROPERTY_EC2_TIMEOUT_SECURITYGROUP_PRESENT) long msDelay) {\n      return retry(in, msDelay, 100L, MILLISECONDS);\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/config/EC2ResolveImagesModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.config;\n\nimport org.jclouds.compute.config.ResolvesImages;\nimport org.jclouds.compute.strategy.PopulateDefaultLoginCredentialsForImageStrategy;\nimport org.jclouds.ec2.compute.strategy.EC2PopulateDefaultLoginCredentialsForImageStrategy;\n\nimport com.google.inject.AbstractModule;\n\n@ResolvesImages\npublic class EC2ResolveImagesModule extends AbstractModule {\n    \n    @Override\n    protected void configure() {\n        bind(PopulateDefaultLoginCredentialsForImageStrategy.class).to(EC2PopulateDefaultLoginCredentialsForImageStrategy.class);\n    }\n    \n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/domain/EC2HardwareBuilder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Predicates.not;\nimport static org.jclouds.compute.domain.Volume.Type.LOCAL;\nimport static org.jclouds.compute.predicates.ImagePredicates.any;\nimport static org.jclouds.compute.predicates.ImagePredicates.idIn;\n\nimport java.net.URI;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.HardwareBuilder;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.Processor;\nimport org.jclouds.compute.domain.Volume;\nimport org.jclouds.compute.domain.VolumeBuilder;\nimport org.jclouds.compute.predicates.ImagePredicates;\nimport org.jclouds.domain.Location;\nimport org.jclouds.ec2.domain.InstanceType;\nimport org.jclouds.ec2.domain.RootDeviceType;\nimport org.jclouds.ec2.domain.VirtualizationType;\n\nimport com.google.common.base.Preconditions;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Predicates;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableList.Builder;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Lists;\n\n/**\n * \n * @see <a href=\n *      \"http://docs.amazonwebservices.com/AWSEC2/latest/UserGuide/index.html?instance-types.html\"\n *      />\n * \n * and <a href=\n *      \"http://aws.amazon.com/amazon-linux-ami/instance-type-matrix/\"\n *      />.\n *      \n * Also note Windows only supports HVM, as per\n *     <a href=\n *     \"http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/virtualization_types.html\"\n *     />.\n *     On Windows you may have to constrain hardware appropriately.\n */\npublic class EC2HardwareBuilder extends HardwareBuilder {\n   private Predicate<Image> rootDeviceType = any();\n   private Predicate<Image> virtualizationType = null; \n   private Predicate<Image> imageIds = any();\n   private Predicate<Image> is64Bit = any();\n\n   public EC2HardwareBuilder() {\n      this.supportsImage = null;\n   }\n\n   /**\n    * evaluates true if the Image has the following rootDeviceType\n    * \n    * @param type\n    *           rootDeviceType of the image\n    * @return predicate\n    */\n   public static class RequiresRootDeviceType implements Predicate<Image> {\n      final RootDeviceType type;\n\n      public RequiresRootDeviceType(final RootDeviceType type) {\n         this.type = checkNotNull(type, \"type must be defined\");\n      }\n\n      @Override\n      public boolean apply(Image image) {\n         return image.getUserMetadata().containsKey(\"rootDeviceType\")\n               && type == RootDeviceType.fromValue(image.getUserMetadata().get(\"rootDeviceType\"));\n      }\n\n      @Override\n      public String toString() {\n         return \"requiresRootDeviceType(\" + type + \")\";\n      }\n\n   }\n\n   /**\n    * evaluates true if the Image requires the following virtualizationType\n    * \n    * @param type\n    *           virtualizationType of the image\n    * @return predicate\n    */\n   public static class RequiresVirtualizationType implements Predicate<Image> {\n      final VirtualizationType type;\n\n      public RequiresVirtualizationType(final VirtualizationType type) {\n         this.type = checkNotNull(type, \"type must be defined\");\n      }\n\n      @Override\n      public boolean apply(Image image) {\n         return image.getOperatingSystem() != null && image.getOperatingSystem().getArch() != null\n               && type == VirtualizationType.fromValue(image.getOperatingSystem().getArch());\n      }\n\n      @Override\n      public String toString() {\n         return \"requiresVirtualizationType(\" + type + \")\";\n      }\n\n   }\n\n   public EC2HardwareBuilder(String instanceType) {\n      ids(instanceType);\n   }\n\n   public EC2HardwareBuilder virtualizationType(VirtualizationType virtualizationType) {\n      this.virtualizationType = new RequiresVirtualizationType(virtualizationType);\n      return this;\n   }\n\n   public EC2HardwareBuilder virtualizationTypes(VirtualizationType ...virtualizationTypes) {\n      Preconditions.checkNotNull(virtualizationTypes, \"virtualizationTypes\");\n      Preconditions.checkArgument(virtualizationTypes.length > 0, \"At least one virtualization type is required.\");\n      if (virtualizationTypes.length == 1) {\n         this.virtualizationType = new RequiresVirtualizationType(virtualizationTypes[0]);\n      } else {\n         List<RequiresVirtualizationType> supportedVirtualizationTypes = Lists.newArrayList();\n         for (VirtualizationType virtualizationType : virtualizationTypes) {\n            supportedVirtualizationTypes.add(new RequiresVirtualizationType(\n                  Preconditions.checkNotNull(virtualizationType, \"virtualizationType\")));\n         }\n         this.virtualizationType = Predicates.or(supportedVirtualizationTypes);\n      }\n      return this;\n   }\n\n   public EC2HardwareBuilder rootDeviceType(RootDeviceType rootDeviceType) {\n      this.rootDeviceType = new RequiresRootDeviceType(rootDeviceType);\n      return this;\n   }\n\n   public EC2HardwareBuilder supportsImageIds(Iterable<String> ids) {\n      this.imageIds = idIn(ids);\n      return this;\n   }\n\n   public EC2HardwareBuilder ids(String id) {\n      return EC2HardwareBuilder.class.cast(super.ids(id));\n   }\n\n   public EC2HardwareBuilder ram(int ram) {\n      return EC2HardwareBuilder.class.cast(super.ram(ram));\n   }\n\n   public EC2HardwareBuilder processors(List<Processor> processors) {\n      return EC2HardwareBuilder.class.cast(super.processors(processors));\n   }\n\n   public EC2HardwareBuilder volumes(List<Volume> volumes) {\n      return EC2HardwareBuilder.class.cast(super.volumes(volumes));\n   }\n\n   public EC2HardwareBuilder supportsImage(Predicate<Image> supportsImage) {\n      return EC2HardwareBuilder.class.cast(super.supportsImage(supportsImage));\n   }\n\n   public EC2HardwareBuilder is64Bit(boolean is64Bit) {\n      this.is64Bit = is64Bit ? ImagePredicates.is64Bit() : not(ImagePredicates.is64Bit());\n      return this;\n   }\n\n   public EC2HardwareBuilder id(String id) {\n      return EC2HardwareBuilder.class.cast(super.id(id));\n   }\n\n   @Override\n   public EC2HardwareBuilder providerId(String providerId) {\n      return EC2HardwareBuilder.class.cast(super.providerId(providerId));\n   }\n\n   @Override\n   public EC2HardwareBuilder name(String name) {\n      return EC2HardwareBuilder.class.cast(super.name(name));\n   }\n\n   @Override\n   public EC2HardwareBuilder location(Location location) {\n      return EC2HardwareBuilder.class.cast(super.location(location));\n   }\n\n   @Override\n   public EC2HardwareBuilder uri(URI uri) {\n      return EC2HardwareBuilder.class.cast(super.uri(uri));\n   }\n\n   @Override\n   public EC2HardwareBuilder userMetadata(Map<String, String> userMetadata) {\n      return EC2HardwareBuilder.class.cast(super.userMetadata(userMetadata));\n   }\n\n   private EC2HardwareBuilder t2() {\n      virtualizationTypes(VirtualizationType.HVM);\n      \n      // TODO T2 is not deprecated, but it requires that you are using a VPC\n      // until we have a way for hardware instances to be filtered based on network\n      // we do NOT want T2 selected automatically.\n      // You get: org.jclouds.aws.AWSResponseException: request POST https://ec2.eu-west-1.amazonaws.com/ HTTP/1.1 failed with code 400, error: AWSError{requestId='2300b99e-ddc0-42ab-b1ed-9d628a161be4', requestToken='null', code='VPCResourceNotSpecified', message='The specified instance type can only be used in a VPC. A subnet ID or network interface ID is required to carry out the request.', context='{Response=, Errors=}'}\n      // A user can explicitly request a t2.micro if they are also setting up a VPC,\n      // but the small default will now be m3.medium which supports VPC and \"classic\".\n      deprecated();\n      \n      return this;\n   }\n\n   private EC2HardwareBuilder t3() {\n      virtualizationType(VirtualizationType.HVM);\n\n      return this;\n   }\n\n   private EC2HardwareBuilder m3() {\n      virtualizationTypes(VirtualizationType.HVM, VirtualizationType.PARAVIRTUAL);\n      return this;\n   }\n\n   private EC2HardwareBuilder m4() {\n      virtualizationTypes(VirtualizationType.HVM);\n      return this;\n   }\n\n   private EC2HardwareBuilder m5() {\n      virtualizationTypes(VirtualizationType.HVM);\n      return this;\n   }\n\n   private EC2HardwareBuilder c3() {\n      virtualizationTypes(VirtualizationType.HVM, VirtualizationType.PARAVIRTUAL);\n      return this;\n   }\n   \n   private EC2HardwareBuilder c4() {\n      virtualizationTypes(VirtualizationType.HVM, VirtualizationType.PARAVIRTUAL);\n      return this;\n   }\n   \n   private EC2HardwareBuilder c5() {\n      virtualizationTypes(VirtualizationType.HVM, VirtualizationType.PARAVIRTUAL);\n      return this;\n   }\n   \n   // TODO include D2 (dense) types?\n   private EC2HardwareBuilder d2() {\n      virtualizationTypes(VirtualizationType.HVM);\n      return this;\n   }\n   \n   private EC2HardwareBuilder r3() {\n      virtualizationTypes(VirtualizationType.HVM);\n      return this;\n   }\n   \n   private EC2HardwareBuilder r4() {\n      virtualizationTypes(VirtualizationType.HVM);\n      rootDeviceType(RootDeviceType.EBS);\n      return this;\n   }\n   \n   private EC2HardwareBuilder g2() {\n      virtualizationTypes(VirtualizationType.HVM);\n      return this;\n   }\n   \n   private EC2HardwareBuilder i2() {\n      virtualizationTypes(VirtualizationType.HVM);\n      return this;\n   }\n   \n   private EC2HardwareBuilder hs1() {\n      virtualizationTypes(VirtualizationType.HVM, VirtualizationType.PARAVIRTUAL);\n      return this;\n   }\n   \n   private EC2HardwareBuilder x1() {\n\t      virtualizationTypes(VirtualizationType.HVM);\n\t      \n\t      // TODO X1 is not deprecated, but it requires that you are using a VPC\n\t      // until we have a way for hardware instances to be filtered based on network\n\t      // we do NOT want X1 selected automatically.\n\t      // You get: org.jclouds.aws.AWSResponseException: request POST https://ec2.eu-west-1.amazonaws.com/ HTTP/1.1 failed with code 400, error: AWSError{requestId='2300b99e-ddc0-42ab-b1ed-9d628a161be4', requestToken='null', code='VPCResourceNotSpecified', message='The specified instance type can only be used in a VPC. A subnet ID or network interface ID is required to carry out the request.', context='{Response=, Errors=}'}\n\t      // A user can explicitly request a x1 if they are also setting up a VPC.\n\t      deprecated();\n\t      \n\t      return this;\n   }\n\n   // TODO below this line are previous generation, discouraged\n   // http://aws.amazon.com/ec2/previous-generation/\n   private EC2HardwareBuilder m1() {\n      virtualizationTypes(VirtualizationType.PARAVIRTUAL);\n      deprecated();\n      return this;\n   }\n   \n   private EC2HardwareBuilder c1() {\n      virtualizationTypes(VirtualizationType.PARAVIRTUAL);\n      deprecated();\n      return this;\n   }\n   \n   private EC2HardwareBuilder cc2() {\n      virtualizationTypes(VirtualizationType.HVM);\n      deprecated();\n      return this;\n   }\n   \n   private EC2HardwareBuilder m2() {\n      virtualizationTypes(VirtualizationType.PARAVIRTUAL);\n      deprecated();\n      return this;\n   }\n   \n   // cr1 never included in jclouds, so skipped here\n   \n   private EC2HardwareBuilder hi1() {\n      virtualizationTypes(VirtualizationType.HVM, VirtualizationType.PARAVIRTUAL);\n      deprecated();\n      return this;\n   }\n   \n   private EC2HardwareBuilder t1() {\n      virtualizationTypes(VirtualizationType.PARAVIRTUAL);\n      deprecated();\n      return this;\n   }\n   \n   private EC2HardwareBuilder cg1() {\n      virtualizationTypes(VirtualizationType.HVM);\n      deprecated();\n      return this;\n   }\n   \n   private EC2HardwareBuilder cc1() {\n      // often no longer available - not adding capacity (use cc2)\n      virtualizationTypes(VirtualizationType.HVM);\n      deprecated();\n      return this;\n   }\n   \n\n   /**\n    * @see InstanceType#M1_SMALL\n    */\n   public static EC2HardwareBuilder m1_small() {\n      return new EC2HardwareBuilder(InstanceType.M1_SMALL).m1()\n            .ram(1740)\n            .processors(ImmutableList.of(new Processor(1.0, 1.0)))\n            .volumes(ImmutableList.<Volume> of(\n                  new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(150.0f).device(\"/dev/sda2\").bootDevice(false).durable(false).build()));\n   }\n\n   /**\n    * @see InstanceType#M1_MEDIUM\n    */\n   public static EC2HardwareBuilder m1_medium() {\n      return new EC2HardwareBuilder(InstanceType.M1_MEDIUM).m1()\n            .ram(3750)\n            .processors(ImmutableList.of(new Processor(1.0, 2.0)))\n            .volumes(ImmutableList.<Volume> of(\n                  new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(420.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(420.0f).device(\"/dev/sdc\").bootDevice(false).durable(false).build()));\n   }\n\n\n   /**\n    * @see InstanceType#T1_MICRO\n    */\n   public static EC2HardwareBuilder t1_micro() {\n      return new EC2HardwareBuilder(InstanceType.T1_MICRO).t1()\n            .ram(630)\n            .processors(ImmutableList.of(new Processor(1.0, 1.0))).rootDeviceType(RootDeviceType.EBS);\n   }\n\n   /**\n    * @see InstanceType#T2_NANO\n    */\n   public static EC2HardwareBuilder t2_nano() {\n      return new EC2HardwareBuilder(InstanceType.T2_NANO).t2()\n              .ram(512)\n              .processors(ImmutableList.of(new Processor(1.0, 3.3))).rootDeviceType(RootDeviceType.EBS);\n   }\n\n   /**\n    * @see InstanceType#T2_MICRO\n    */\n   public static EC2HardwareBuilder t2_micro() {\n      return new EC2HardwareBuilder(InstanceType.T2_MICRO).t2()\n            .ram(1024)\n            .processors(ImmutableList.of(new Processor(1.0, 3.3))).rootDeviceType(RootDeviceType.EBS);\n   }\n\n   /**\n    * @see InstanceType#T2_SMALL\n    */\n   public static EC2HardwareBuilder t2_small() {\n      return new EC2HardwareBuilder(InstanceType.T2_SMALL).t2()\n            .ram(2048)\n            .processors(ImmutableList.of(new Processor(1.0, 3.3))).rootDeviceType(RootDeviceType.EBS);\n   }\n\n   /**\n    * @see InstanceType#T2_MEDIUM\n    */\n   public static EC2HardwareBuilder t2_medium() {\n      return new EC2HardwareBuilder(InstanceType.T2_MEDIUM).t2()\n            .ram(4096)\n            .processors(ImmutableList.of(new Processor(2.0, 3.3))).rootDeviceType(RootDeviceType.EBS);\n   }\n\n   /**\n    * @see InstanceType#T2_LARGE\n    */\n   public static EC2HardwareBuilder t2_large() {\n      return new EC2HardwareBuilder(InstanceType.T2_LARGE).t2()\n            .ram(8192)\n            .processors(ImmutableList.of(new Processor(2.0, 3.0))).rootDeviceType(RootDeviceType.EBS);\n   }\n\n   /**\n    * @see InstanceType#T2_XLARGE\n    */\n   public static EC2HardwareBuilder t2_xlarge() {\n      return new EC2HardwareBuilder(InstanceType.T2_XLARGE).t2()\n              .ram(16384)\n              .processors(ImmutableList.of(new Processor(4.0, 3.0))).rootDeviceType(RootDeviceType.EBS);\n   }\n\n   /**\n    * @see InstanceType#T2_2XLARGE\n    */\n   public static EC2HardwareBuilder t2_2xlarge() {\n      return new EC2HardwareBuilder(InstanceType.T2_2XLARGE).t2()\n              .ram(32768)\n              .processors(ImmutableList.of(new Processor(8.0, 3.0))).rootDeviceType(RootDeviceType.EBS);\n   }\n\n   /**\n    * @see InstanceType#T3_NANO\n    */\n   public static EC2HardwareBuilder t3_nano() {\n      return new EC2HardwareBuilder(InstanceType.T3_NANO).t3()\n              .ram(512)\n              .processors(ImmutableList.of(new Processor(2.0, 2.5))).rootDeviceType(RootDeviceType.EBS);\n   }\n\n   /**\n    * @see InstanceType#T3_MICRO\n    */\n   public static EC2HardwareBuilder t3_micro() {\n      return new EC2HardwareBuilder(InstanceType.T3_MICRO).t3()\n              .ram(1024)\n              .processors(ImmutableList.of(new Processor(2.0, 2.5))).rootDeviceType(RootDeviceType.EBS);\n   }\n\n   /**\n    * @see InstanceType#T3_SMALL\n    */\n   public static EC2HardwareBuilder t3_small() {\n      return new EC2HardwareBuilder(InstanceType.T3_SMALL).t3()\n              .ram(2048)\n              .processors(ImmutableList.of(new Processor(2.0, 2.5))).rootDeviceType(RootDeviceType.EBS);\n   }\n\n   /**\n    * @see InstanceType#T3_MEDIUM\n    */\n   public static EC2HardwareBuilder t3_medium() {\n      return new EC2HardwareBuilder(InstanceType.T3_MEDIUM).t3()\n              .ram(4096)\n              .processors(ImmutableList.of(new Processor(2.0, 2.5))).rootDeviceType(RootDeviceType.EBS);\n   }\n\n   /**\n    * @see InstanceType#T3_LARGE\n    */\n   public static EC2HardwareBuilder t3_large() {\n      return new EC2HardwareBuilder(InstanceType.T3_LARGE).t3()\n              .ram(8192)\n              .processors(ImmutableList.of(new Processor(2.0, 2.5))).rootDeviceType(RootDeviceType.EBS);\n   }\n\n   /**\n    * @see InstanceType#T3_XLARGE\n    */\n   public static EC2HardwareBuilder t3_xlarge() {\n      return new EC2HardwareBuilder(InstanceType.T3_XLARGE).t3()\n              .ram(16384)\n              .processors(ImmutableList.of(new Processor(4.0, 2.5))).rootDeviceType(RootDeviceType.EBS);\n   }\n\n   /**\n    * @see InstanceType#T3_2XLARGE\n    */\n   public static EC2HardwareBuilder t3_2xlarge() {\n      return new EC2HardwareBuilder(InstanceType.T3_2XLARGE).t3()\n              .ram(32768)\n              .processors(ImmutableList.of(new Processor(8.0, 2.5))).rootDeviceType(RootDeviceType.EBS);\n   }\n\n\n\n   /**\n    * @see InstanceType#M1_LARGE\n    */\n   public static EC2HardwareBuilder m1_large() {\n      return new EC2HardwareBuilder(InstanceType.M1_LARGE).m1()\n            .ram(7680)\n            .processors(ImmutableList.of(new Processor(2.0, 2.0)))\n            .volumes(ImmutableList.<Volume> of(\n                  new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(420.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(420.0f).device(\"/dev/sdc\").bootDevice(false).durable(false).build()))\n            .is64Bit(true);\n   }\n\n   /**\n    * @see InstanceType#M1_XLARGE\n    */\n   public static EC2HardwareBuilder m1_xlarge() {\n      return new EC2HardwareBuilder(InstanceType.M1_XLARGE).m1()\n            .ram(15360)\n            .processors(ImmutableList.of(new Processor(4.0, 2.0)))\n            .volumes(ImmutableList.<Volume> of(\n                  new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(420.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(420.0f).device(\"/dev/sdc\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(420.0f).device(\"/dev/sdd\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(420.0f).device(\"/dev/sde\").bootDevice(false).durable(false).build()))\n            .is64Bit(true);\n   }\n\n   /**\n    * @see InstanceType#M2_XLARGE\n    */\n   public static EC2HardwareBuilder m2_xlarge() {\n      return new EC2HardwareBuilder(InstanceType.M2_XLARGE).m2()\n            .ram(17510)\n            .processors(ImmutableList.of(new Processor(2.0, 3.25)))\n            .volumes(ImmutableList.<Volume> of(\n                  new VolumeBuilder().type(LOCAL).size(420.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build()))\n            .is64Bit(true);\n   }\n\n   /**\n    * @see InstanceType#M2_2XLARGE\n    */\n   public static EC2HardwareBuilder m2_2xlarge() {\n      return new EC2HardwareBuilder(InstanceType.M2_2XLARGE).m2()\n            .ram(35020)\n            .processors(ImmutableList.of(new Processor(4.0, 3.25)))\n            .volumes(ImmutableList.<Volume> of(\n                  new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(840.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build()))\n            .is64Bit(true);\n   }\n\n   /**\n    * @see InstanceType#M2_4XLARGE\n    */\n   public static EC2HardwareBuilder m2_4xlarge() {\n      return new EC2HardwareBuilder(InstanceType.M2_4XLARGE).m2()\n            .ram(70041)\n            .processors(ImmutableList.of(new Processor(8.0, 3.25)))\n            .volumes(ImmutableList.<Volume> of(\n                  new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(840.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(840.0f).device(\"/dev/sdc\").bootDevice(false).durable(false).build()))\n            .is64Bit(true);\n   }\n   \n   /**\n    * @see InstanceType#M3_MEDIUM\n    */\n   public static EC2HardwareBuilder m3_medium() {\n      return new EC2HardwareBuilder(InstanceType.M3_MEDIUM).m3()\n            .ram(3840)\n            .processors(ImmutableList.of(new Processor(1.0, 3.0)))\n            .volumes(ImmutableList.<Volume> of(\n                  new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(4.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build()));\n   }\n\n   /**\n    * @see InstanceType#M3_LARGE\n    */\n   public static EC2HardwareBuilder m3_large() {\n      return new EC2HardwareBuilder(InstanceType.M3_LARGE).m3()\n            .ram(7680)\n            .processors(ImmutableList.of(new Processor(2.0, 3.25)))\n            .volumes(ImmutableList.<Volume> of(\n                  new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(32.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build()));\n   }\n\n   /**\n    * @see InstanceType#M3_XLARGE\n    */\n   public static EC2HardwareBuilder m3_xlarge() {\n      return new EC2HardwareBuilder(InstanceType.M3_XLARGE).m3()\n              .ram(15360)\n              .processors(ImmutableList.of(new Processor(4.0, 3.25)))\n              .is64Bit(true)\n              .volumes(ImmutableList.<Volume>of(\n                    new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                    new VolumeBuilder().type(LOCAL).size(40.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build(),\n                    new VolumeBuilder().type(LOCAL).size(40.0f).device(\"/dev/sdc\").bootDevice(false).durable(false).build()));\n   }\n\n   /**\n    * @see InstanceType#M3_2XLARGE\n    */\n   public static EC2HardwareBuilder m3_2xlarge() {\n      return new EC2HardwareBuilder(InstanceType.M3_2XLARGE).m3()\n              .ram(30720)\n              .processors(ImmutableList.of(new Processor(8.0, 3.25)))\n              .is64Bit(true)\n              .volumes(ImmutableList.<Volume> of(\n                      new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                      new VolumeBuilder().type(LOCAL).size(80.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build(),\n                      new VolumeBuilder().type(LOCAL).size(80.0f).device(\"/dev/sdc\").bootDevice(false).durable(false).build()));\n   }\n\n   /**\n    * @see InstanceType#M4_XLARGE\n    */\n   public static EC2HardwareBuilder m4_xlarge() {\n      return new EC2HardwareBuilder(InstanceType.M4_XLARGE).m4()\n            .ram(16384)\n            .processors(ImmutableList.of(new Processor(4, 3.25)))\n            .is64Bit(true)\n            .rootDeviceType(RootDeviceType.EBS);\n   }\n\n   /**\n    * @see InstanceType#M4_LARGE\n    */\n   public static EC2HardwareBuilder m4_large() {\n      return new EC2HardwareBuilder(InstanceType.M4_LARGE).m4()\n            .ram(8192)\n            .processors(ImmutableList.of(new Processor(2, 3.25)))\n            .is64Bit(true)\n            .rootDeviceType(RootDeviceType.EBS);\n   }\n\n   /**\n    * @see InstanceType#M4_2XLARGE\n    */\n   public static EC2HardwareBuilder m4_2xlarge() {\n      return new EC2HardwareBuilder(InstanceType.M4_2XLARGE).m4()\n            .ram(32768)\n            .processors(ImmutableList.of(new Processor(8, 3.25)))\n            .is64Bit(true)\n            .rootDeviceType(RootDeviceType.EBS);\n   }\n\n   /**\n    * @see InstanceType#M4_4XLARGE\n    */\n   public static EC2HardwareBuilder m4_4xlarge() {\n      return new EC2HardwareBuilder(InstanceType.M4_4XLARGE).m4()\n            .ram(65536)\n            .processors(ImmutableList.of(new Processor(16, 3.34375)))\n            .is64Bit(true)\n            .rootDeviceType(RootDeviceType.EBS);\n   }\n\n   /**\n    * @see InstanceType#M4_10XLARGE\n    */\n   public static EC2HardwareBuilder m4_10xlarge() {\n      return new EC2HardwareBuilder(InstanceType.M4_10XLARGE).m4()\n            .ram(163840)\n            .processors(ImmutableList.of(new Processor(40.0, 3.1125)))\n            .is64Bit(true)\n            .rootDeviceType(RootDeviceType.EBS);\n   }\n\n   /**\n    * @see InstanceType#M4_16XLARGE\n    */\n   public static EC2HardwareBuilder m4_16xlarge() {\n      return new EC2HardwareBuilder(InstanceType.M4_16XLARGE).m4()\n              .ram(262144)\n              .processors(ImmutableList.of(new Processor(64.0, 3.1125)))\n              .is64Bit(true)\n              .rootDeviceType(RootDeviceType.EBS);\n   }\n\n   /**\n    * @see InstanceType#M5_LARGE\n    */\n   public static EC2HardwareBuilder m5_large() {\n      return new EC2HardwareBuilder(InstanceType.M5_LARGE).m5()\n            .ram(8192)\n            .processors(ImmutableList.of(new Processor(2, 2.5)))\n            .is64Bit(true)\n            .rootDeviceType(RootDeviceType.EBS);\n   }\n\n   /**\n    * @see InstanceType#M5_XLARGE\n    */\n   public static EC2HardwareBuilder m5_xlarge() {\n      return new EC2HardwareBuilder(InstanceType.M5_XLARGE).m5()\n            .ram(16384)\n            .processors(ImmutableList.of(new Processor(4, 2.5)))\n            .is64Bit(true)\n            .rootDeviceType(RootDeviceType.EBS);\n   }\n\n   /**\n    * @see InstanceType#M5_2XLARGE\n    */\n   public static EC2HardwareBuilder m5_2xlarge() {\n      return new EC2HardwareBuilder(InstanceType.M5_2XLARGE).m5()\n            .ram(32768)\n            .processors(ImmutableList.of(new Processor(8, 2.5)))\n            .is64Bit(true)\n            .rootDeviceType(RootDeviceType.EBS);\n   }\n\n   /**\n    * @see InstanceType#M5_4XLARGE\n    */\n   public static EC2HardwareBuilder m5_4xlarge() {\n      return new EC2HardwareBuilder(InstanceType.M5_4XLARGE).m5()\n            .ram(65536)\n            .processors(ImmutableList.of(new Processor(16, 2.5)))\n            .is64Bit(true)\n            .rootDeviceType(RootDeviceType.EBS);\n   }\n\n   /**\n    * @see InstanceType#M5_12XLARGE\n    */\n   public static EC2HardwareBuilder m5_12xlarge() {\n      return new EC2HardwareBuilder(InstanceType.M5_12XLARGE).m5()\n            .ram(196608)\n            .processors(ImmutableList.of(new Processor(48.0, 2.5)))\n            .is64Bit(true)\n            .rootDeviceType(RootDeviceType.EBS);\n   }\n\n   /**\n    * @see InstanceType#M5_24XLARGE\n    */\n   public static EC2HardwareBuilder m5_24xlarge() {\n      return new EC2HardwareBuilder(InstanceType.M5_24XLARGE).m5()\n            .ram(393216)\n            .processors(ImmutableList.of(new Processor(96.0, 2.5)))\n            .is64Bit(true)\n            .rootDeviceType(RootDeviceType.EBS);\n   }\n\n   /**\n    * @see InstanceType#M5D_LARGE\n    */\n   public static EC2HardwareBuilder m5d_large() {\n      return new EC2HardwareBuilder(InstanceType.M5D_LARGE).m5()\n            .ram(8192)\n            .processors(ImmutableList.of(new Processor(2, 2.5)))\n            .volumes(ImmutableList.<Volume>of(\n                    new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                    new VolumeBuilder().type(LOCAL).size(75.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build()))\n            .is64Bit(true);\n   }\n\n   /**\n    * @see InstanceType#M5D_XLARGE\n    */\n   public static EC2HardwareBuilder m5d_xlarge() {\n      return new EC2HardwareBuilder(InstanceType.M5D_XLARGE).m5()\n            .ram(16384)\n            .processors(ImmutableList.of(new Processor(4, 2.5)))\n            .volumes(ImmutableList.<Volume>of(\n                    new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                    new VolumeBuilder().type(LOCAL).size(150.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build()))\n            .is64Bit(true);\n   }\n\n   /**\n    * @see InstanceType#M5D_2XLARGE\n    */\n   public static EC2HardwareBuilder m5d_2xlarge() {\n      return new EC2HardwareBuilder(InstanceType.M5D_2XLARGE).m5()\n            .ram(32768)\n            .processors(ImmutableList.of(new Processor(8, 2.5)))\n            .volumes(ImmutableList.<Volume>of(\n                    new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                    new VolumeBuilder().type(LOCAL).size(300.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build()))\n            .is64Bit(true);\n   }\n\n   /**\n    * @see InstanceType#M5D_4XLARGE\n    */\n   public static EC2HardwareBuilder m5d_4xlarge() {\n      return new EC2HardwareBuilder(InstanceType.M5D_4XLARGE).m5()\n            .ram(65536)\n            .processors(ImmutableList.of(new Processor(16, 2.5)))\n            .volumes(ImmutableList.<Volume>of(\n                    new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                    new VolumeBuilder().type(LOCAL).size(300.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build(),\n                    new VolumeBuilder().type(LOCAL).size(300.0f).device(\"/dev/sdc\").bootDevice(false).durable(false).build()))\n            .is64Bit(true);\n   }\n\n   /**\n    * @see InstanceType#M5D_12XLARGE\n    */\n   public static EC2HardwareBuilder m5d_12xlarge() {\n      return new EC2HardwareBuilder(InstanceType.M5D_12XLARGE).m5()\n            .ram(196608)\n            .processors(ImmutableList.of(new Processor(48.0, 2.5)))\n            .volumes(ImmutableList.<Volume>of(\n                    new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                    new VolumeBuilder().type(LOCAL).size(900.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build(),\n                    new VolumeBuilder().type(LOCAL).size(900.0f).device(\"/dev/sdc\").bootDevice(false).durable(false).build()))\n            .is64Bit(true);\n   }\n\n   /**\n    * @see InstanceType#M5D_24XLARGE\n    */\n   public static EC2HardwareBuilder m5d_24xlarge() {\n      return new EC2HardwareBuilder(InstanceType.M5D_24XLARGE).m5()\n            .ram(393216)\n            .processors(ImmutableList.of(new Processor(96.0, 2.5)))\n            .volumes(ImmutableList.<Volume>of(\n                    new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                    new VolumeBuilder().type(LOCAL).size(900.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build(),\n                    new VolumeBuilder().type(LOCAL).size(900.0f).device(\"/dev/sdc\").bootDevice(false).durable(false).build(),\n                    new VolumeBuilder().type(LOCAL).size(900.0f).device(\"/dev/sdd\").bootDevice(false).durable(false).build(),\n                    new VolumeBuilder().type(LOCAL).size(900.0f).device(\"/dev/sde\").bootDevice(false).durable(false).build()))\n            .is64Bit(true);\n   }\n   \n   /**\n    * @see InstanceType#C1_MEDIUM\n    */\n   public static EC2HardwareBuilder c1_medium() {\n      return new EC2HardwareBuilder(InstanceType.C1_MEDIUM).c1()\n            .ram(1740)\n            .processors(ImmutableList.of(new Processor(2.0, 2.5)))\n            .volumes(ImmutableList.<Volume>of(\n                  new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(340.0f).device(\"/dev/sda2\").bootDevice(false).durable(false).build()));\n   }\n\n   /**\n    * @see InstanceType#C1_XLARGE\n    */\n   public static EC2HardwareBuilder c1_xlarge() {\n      return new EC2HardwareBuilder(InstanceType.C1_XLARGE).c1()\n            .ram(7168)\n            .processors(ImmutableList.of(new Processor(8.0, 2.5)))\n            .volumes(ImmutableList.<Volume>of(\n                  new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(420.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(420.0f).device(\"/dev/sdc\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(420.0f).device(\"/dev/sdd\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(420.0f).device(\"/dev/sde\").bootDevice(false).durable(false).build()))\n            .is64Bit(true);\n   }\n\n   /**\n    * @see InstanceType#C3_LARGE\n    */\n   public static EC2HardwareBuilder c3_large() {\n      return new EC2HardwareBuilder(InstanceType.C3_LARGE).c3()\n              .ram(3750)\n              .processors(ImmutableList.of(new Processor(2.0, 3.5)))\n              .volumes(ImmutableList.<Volume>of(\n                    new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                    new VolumeBuilder().type(LOCAL).size(16.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build(),\n                    new VolumeBuilder().type(LOCAL).size(16.0f).device(\"/dev/sdc\").bootDevice(false).durable(false).build()))\n              .is64Bit(true);\n   }\n\n   /**\n    * @see InstanceType#C3_XLARGE\n    */\n   public static EC2HardwareBuilder c3_xlarge() {\n      return new EC2HardwareBuilder(InstanceType.C3_XLARGE).c3()\n              .ram(7168)\n              .processors(ImmutableList.of(new Processor(4.0, 3.5)))\n              .volumes(ImmutableList.<Volume> of(\n                    new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                    new VolumeBuilder().type(LOCAL).size(40.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build(),\n                    new VolumeBuilder().type(LOCAL).size(40.0f).device(\"/dev/sdc\").bootDevice(false).durable(false).build()))\n              .is64Bit(true);\n   }\n\n   /**\n    * @see InstanceType#C3_2XLARGE\n    */\n   public static EC2HardwareBuilder c3_2xlarge() {\n      return new EC2HardwareBuilder(InstanceType.C3_2XLARGE).c3()\n              .ram(15360)\n              .processors(ImmutableList.of(new Processor(8.0, 3.5)))\n              .volumes(ImmutableList.<Volume> of(\n                    new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                    new VolumeBuilder().type(LOCAL).size(80.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build(),\n                    new VolumeBuilder().type(LOCAL).size(80.0f).device(\"/dev/sdc\").bootDevice(false).durable(false).build()))\n              .is64Bit(true);\n   }\n\n   /**\n    * @see InstanceType#C3_4XLARGE\n    */\n   public static EC2HardwareBuilder c3_4xlarge() {\n      return new EC2HardwareBuilder(InstanceType.C3_4XLARGE).c3()\n              .ram(30720)\n              .processors(ImmutableList.of(new Processor(16.0, 3.4375)))\n              .volumes(ImmutableList.<Volume> of(\n                    new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                    new VolumeBuilder().type(LOCAL).size(160.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build(),\n                    new VolumeBuilder().type(LOCAL).size(160.0f).device(\"/dev/sdc\").bootDevice(false).durable(false).build()))\n              .is64Bit(true);\n   }\n\n   /**\n    * @see InstanceType#C3_8XLARGE\n    */\n   public static EC2HardwareBuilder c3_8xlarge() {\n      return new EC2HardwareBuilder(InstanceType.C3_8XLARGE).c3()\n              .ram(61440)\n              .processors(ImmutableList.of(new Processor(32.0, 3.375)))\n              .volumes(ImmutableList.<Volume> of(\n                    new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                    new VolumeBuilder().type(LOCAL).size(320.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build(),\n                    new VolumeBuilder().type(LOCAL).size(320.0f).device(\"/dev/sdc\").bootDevice(false).durable(false).build()))\n              .is64Bit(true);\n   }\n\n   /**\n    * @see InstanceType#C4_LARGE\n    */\n   public static EC2HardwareBuilder c4_large() {\n      return new EC2HardwareBuilder(InstanceType.C4_LARGE).c4()\n         .ram(3840)\n         .processors(ImmutableList.of(new Processor(2.0, 3.5)))\n         .rootDeviceType(RootDeviceType.EBS);\n   }\n\n   /**\n    * @see InstanceType#C4_XLARGE\n    */\n   public static EC2HardwareBuilder c4_xlarge() {\n      return new EC2HardwareBuilder(InstanceType.C4_XLARGE).c4()\n         .ram(7680)\n         .processors(ImmutableList.of(new Processor(4.0, 3.5)))\n         .rootDeviceType(RootDeviceType.EBS);\n   }\n\n   /**\n    * @see InstanceType#C4_2XLARGE\n    */\n   public static EC2HardwareBuilder c4_2xlarge() {\n      return new EC2HardwareBuilder(InstanceType.C4_2XLARGE).c4()\n         .ram(15360)\n         .processors(ImmutableList.of(new Processor(8.0, 3.5)))\n         .rootDeviceType(RootDeviceType.EBS);\n   }\n\n   /**\n    * @see InstanceType#C4_4XLARGE\n    */\n   public static EC2HardwareBuilder c4_4xlarge() {\n      return new EC2HardwareBuilder(InstanceType.C4_4XLARGE).c4()\n         .ram(30720)\n         .processors(ImmutableList.of(new Processor(16.0, 3.5)))\n         .rootDeviceType(RootDeviceType.EBS);\n   }\n\n   /**\n    * @see InstanceType#C4_8XLARGE\n    */\n   public static EC2HardwareBuilder c4_8xlarge() {\n      return new EC2HardwareBuilder(InstanceType.C4_8XLARGE).c4()\n         .ram(61440)\n         .processors(ImmutableList.of(new Processor(36.0, 3.5)))\n         .rootDeviceType(RootDeviceType.EBS);\n   }\n\n   /**\n    * @see InstanceType#C5_LARGE\n    */\n   public static EC2HardwareBuilder c5_large() {\n      return new EC2HardwareBuilder(InstanceType.C5_LARGE).c5()\n         .ram(4096)\n         .processors(ImmutableList.of(new Processor(2.0, 3.0)))\n         .rootDeviceType(RootDeviceType.EBS);\n   }\n\n   /**\n    * @see InstanceType#C5_XLARGE\n    */\n   public static EC2HardwareBuilder c5_xlarge() {\n      return new EC2HardwareBuilder(InstanceType.C5_XLARGE).c5()\n         .ram(8192)\n         .processors(ImmutableList.of(new Processor(4.0, 3.0)))\n         .rootDeviceType(RootDeviceType.EBS);\n   }\n\n   /**\n    * @see InstanceType#C5_2XLARGE\n    */\n   public static EC2HardwareBuilder c5_2xlarge() {\n      return new EC2HardwareBuilder(InstanceType.C5_2XLARGE).c5()\n         .ram(16384)\n         .processors(ImmutableList.of(new Processor(8.0, 3.0)))\n         .rootDeviceType(RootDeviceType.EBS);\n   }\n\n   /**\n    * @see InstanceType#C5_4XLARGE\n    */\n   public static EC2HardwareBuilder c5_4xlarge() {\n      return new EC2HardwareBuilder(InstanceType.C5_4XLARGE).c5()\n         .ram(32768)\n         .processors(ImmutableList.of(new Processor(16.0, 3.0)))\n         .rootDeviceType(RootDeviceType.EBS);\n   }\n\n   /**\n    * @see InstanceType#C5_9XLARGE\n    */\n   public static EC2HardwareBuilder c5_9xlarge() {\n      return new EC2HardwareBuilder(InstanceType.C5_9XLARGE).c5()\n         .ram(73728)\n         .processors(ImmutableList.of(new Processor(36.0, 3.0)))\n         .rootDeviceType(RootDeviceType.EBS);\n   }\n\n   /**\n    * @see InstanceType#C5_18XLARGE\n    */\n   public static EC2HardwareBuilder c5_18xlarge() {\n      return new EC2HardwareBuilder(InstanceType.C5_18XLARGE).c5()\n         .ram(147456)\n         .processors(ImmutableList.of(new Processor(72.0, 3.0)))\n         .rootDeviceType(RootDeviceType.EBS);\n   }\n\n   /**\n    * @see InstanceType#C5D_LARGE\n    */\n   public static EC2HardwareBuilder c5d_large() {\n      return new EC2HardwareBuilder(InstanceType.C5D_LARGE).c5()\n         .ram(4096)\n         .processors(ImmutableList.of(new Processor(2.0, 3.0)))\n         .volumes(ImmutableList.<Volume>of(\n                 new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                 new VolumeBuilder().type(LOCAL).size(50.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build()))\n           .is64Bit(true);\n   }\n\n   /**\n    * @see InstanceType#C5D_XLARGE\n    */\n   public static EC2HardwareBuilder c5d_xlarge() {\n      return new EC2HardwareBuilder(InstanceType.C5D_XLARGE).c5()\n         .ram(8192)\n         .processors(ImmutableList.of(new Processor(4.0, 3.0)))\n         .volumes(ImmutableList.<Volume>of(\n                 new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                 new VolumeBuilder().type(LOCAL).size(100.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build()))\n           .is64Bit(true);\n   }\n\n   /**\n    * @see InstanceType#C5D_2XLARGE\n    */\n   public static EC2HardwareBuilder c5d_2xlarge() {\n      return new EC2HardwareBuilder(InstanceType.C5D_2XLARGE).c5()\n         .ram(16384)\n         .processors(ImmutableList.of(new Processor(8.0, 3.0)))\n         .volumes(ImmutableList.<Volume>of(\n                 new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                 new VolumeBuilder().type(LOCAL).size(225.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build()))\n           .is64Bit(true);\n   }\n\n   /**\n    * @see InstanceType#C5D_4XLARGE\n    */\n   public static EC2HardwareBuilder c5d_4xlarge() {\n      return new EC2HardwareBuilder(InstanceType.C5D_4XLARGE).c5()\n         .ram(32768)\n         .processors(ImmutableList.of(new Processor(16.0, 3.0)))\n         .volumes(ImmutableList.<Volume>of(\n                 new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                 new VolumeBuilder().type(LOCAL).size(450.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build()))\n           .is64Bit(true);\n   }\n\n   /**\n    * @see InstanceType#C5D_9XLARGE\n    */\n   public static EC2HardwareBuilder c5d_9xlarge() {\n      return new EC2HardwareBuilder(InstanceType.C5D_9XLARGE).c5()\n         .ram(73728)\n         .processors(ImmutableList.of(new Processor(36.0, 3.0)))\n         .volumes(ImmutableList.<Volume>of(\n                 new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                 new VolumeBuilder().type(LOCAL).size(900.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build()))\n           .is64Bit(true);\n   }\n\n   /**\n    * @see InstanceType#C5D_18XLARGE\n    */\n   public static EC2HardwareBuilder c5d_18xlarge() {\n      return new EC2HardwareBuilder(InstanceType.C5D_18XLARGE).c5()\n         .ram(147456)\n         .processors(ImmutableList.of(new Processor(72.0, 3.0)))\n         .volumes(ImmutableList.<Volume>of(\n                 new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                 new VolumeBuilder().type(LOCAL).size(900.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build(),\n                 new VolumeBuilder().type(LOCAL).size(900.0f).device(\"/dev/sdc\").bootDevice(false).durable(false).build()))\n           .is64Bit(true);\n   }\n   \n   /**\n    * @see InstanceType#D2_XLARGE\n    */\n   public static EC2HardwareBuilder d2_xlarge() {\n      return new EC2HardwareBuilder(InstanceType.D2_XLARGE).d2()\n            .ram(31232)\n            .processors(ImmutableList.of(new Processor(4.0, 3.5)))\n            .volumes(ImmutableList.<Volume>of(\n                  new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(2000.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(2000.0f).device(\"/dev/sdc\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(2000.0f).device(\"/dev/sdd\").bootDevice(false).durable(false).build()))\n            .is64Bit(true);\n   }\n\n   /**\n    * @see InstanceType#D2_2XLARGE\n    */\n   public static EC2HardwareBuilder d2_2xlarge() {\n      return new EC2HardwareBuilder(InstanceType.D2_2XLARGE).d2()\n            .ram(62464)\n            .processors(ImmutableList.of(new Processor(8.0, 3.5)))\n            .volumes(ImmutableList.<Volume>of(\n                  new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(2000.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(2000.0f).device(\"/dev/sdc\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(2000.0f).device(\"/dev/sdd\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(2000.0f).device(\"/dev/sde\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(2000.0f).device(\"/dev/sdf\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(2000.0f).device(\"/dev/sdg\").bootDevice(false).durable(false).build()))\n            .is64Bit(true);\n   }\n\n   /**\n    * @see InstanceType#D2_4XLARGE\n    */\n   public static EC2HardwareBuilder d2_4xlarge() {\n      return new EC2HardwareBuilder(InstanceType.D2_4XLARGE).d2()\n            .ram(124928)\n            .processors(ImmutableList.of(new Processor(16.0, 3.5)))\n            .volumes(ImmutableList.<Volume>of(\n                  new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(2000.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(2000.0f).device(\"/dev/sdc\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(2000.0f).device(\"/dev/sdd\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(2000.0f).device(\"/dev/sde\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(2000.0f).device(\"/dev/sdf\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(2000.0f).device(\"/dev/sdg\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(2000.0f).device(\"/dev/sdh\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(2000.0f).device(\"/dev/sdi\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(2000.0f).device(\"/dev/sdj\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(2000.0f).device(\"/dev/sdk\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(2000.0f).device(\"/dev/sdl\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(2000.0f).device(\"/dev/sdm\").bootDevice(false).durable(false).build()))\n            .is64Bit(true);\n   }\n\n   /**\n    * @see InstanceType#D2_8XLARGE\n    */\n   public static EC2HardwareBuilder d2_8xlarge() {\n      return new EC2HardwareBuilder(InstanceType.D2_8XLARGE).d2()\n            .ram(249856)\n            .processors(ImmutableList.of(new Processor(36.0, 3.5)))\n            .volumes(ImmutableList.<Volume>of(\n                  new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(2000.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(2000.0f).device(\"/dev/sdc\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(2000.0f).device(\"/dev/sdd\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(2000.0f).device(\"/dev/sde\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(2000.0f).device(\"/dev/sdf\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(2000.0f).device(\"/dev/sdg\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(2000.0f).device(\"/dev/sdh\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(2000.0f).device(\"/dev/sdi\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(2000.0f).device(\"/dev/sdj\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(2000.0f).device(\"/dev/sdk\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(2000.0f).device(\"/dev/sdl\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(2000.0f).device(\"/dev/sdm\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(2000.0f).device(\"/dev/sdn\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(2000.0f).device(\"/dev/sdo\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(2000.0f).device(\"/dev/sdp\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(2000.0f).device(\"/dev/sdq\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(2000.0f).device(\"/dev/sdr\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(2000.0f).device(\"/dev/sds\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(2000.0f).device(\"/dev/sdt\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(2000.0f).device(\"/dev/sdu\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(2000.0f).device(\"/dev/sdv\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(2000.0f).device(\"/dev/sdw\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(2000.0f).device(\"/dev/sdx\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(2000.0f).device(\"/dev/sdy\").bootDevice(false).durable(false).build()))\n            .is64Bit(true);\n   }\n\n   public static EC2HardwareBuilder cg1_4xlarge() {\n      return new EC2HardwareBuilder(InstanceType.CG1_4XLARGE).cg1()\n            .ram(22 * 1024)\n            .processors(ImmutableList.of(new Processor(4.0, 4.0), new Processor(4.0, 4.0)))\n            .volumes(ImmutableList.<Volume> of(\n                  new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(840.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(840.0f).device(\"/dev/sdc\").bootDevice(false).durable(false).build()))\n            .virtualizationType(VirtualizationType.HVM);\n   }\n\n   public static EC2HardwareBuilder cc1_4xlarge() {\n      return new EC2HardwareBuilder(InstanceType.CC1_4XLARGE).cc1()\n            .ram(23 * 1024)\n            .processors(ImmutableList.of(new Processor(4.0, 4.0), new Processor(4.0, 4.0)))\n            .volumes(ImmutableList.<Volume> of(\n                  new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(840.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(840.0f).device(\"/dev/sdc\").bootDevice(false).durable(false).build()))\n            .virtualizationType(VirtualizationType.HVM);\n   }\n\n   public static EC2HardwareBuilder cc2_8xlarge() {\n      return new EC2HardwareBuilder(InstanceType.CC2_8XLARGE).cc2()\n            .ram(60 * 1024 + 512)\n            .processors(ImmutableList.of(new Processor(8.0, 5.5), new Processor(8.0, 5.5)))\n            .volumes(ImmutableList.<Volume> of(\n                  new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(840.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(840.0f).device(\"/dev/sdc\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(840.0f).device(\"/dev/sdd\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(840.0f).device(\"/dev/sde\").bootDevice(false).durable(false).build()))\n            .virtualizationType(VirtualizationType.HVM);\n   }\n\n   /**\n    * @see InstanceType#G2_2XLARGE\n    */\n   public static EC2HardwareBuilder g2_2xlarge() {\n      return new EC2HardwareBuilder(InstanceType.G2_2XLARGE).g2()\n\t    .ram(15 * 1024)\n            .processors(ImmutableList.of(new Processor(8.0, 3.25)))\n            .volumes(ImmutableList.<Volume> of(\n                  new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(60.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build()))\n            .virtualizationType(VirtualizationType.HVM);\n   }\n\n   /**\n    * @see InstanceType#I2_XLARGE\n    */\n   public static EC2HardwareBuilder i2_xlarge() {\n      return new EC2HardwareBuilder(InstanceType.I2_XLARGE).i2()\n              .ram(30 * 1024 + 512)\n              .processors(ImmutableList.of(new Processor(4.0, 3.5)))\n              .volumes(ImmutableList.<Volume> of(\n                    new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                    new VolumeBuilder().type(LOCAL).size(800.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build()))\n              .virtualizationType(VirtualizationType.HVM);\n   }\n\n   /**\n    * @see InstanceType#I2_2XLARGE\n    */\n   public static EC2HardwareBuilder i2_2xlarge() {\n      return new EC2HardwareBuilder(InstanceType.I2_2XLARGE).i2()\n              .ram(61 * 1024)\n              .processors(ImmutableList.of(new Processor(8.0, 3.375)))\n              .volumes(ImmutableList.<Volume> of(\n                    new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                    new VolumeBuilder().type(LOCAL).size(800.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build(),\n                    new VolumeBuilder().type(LOCAL).size(800.0f).device(\"/dev/sdc\").bootDevice(false).durable(false).build()))\n              .virtualizationType(VirtualizationType.HVM);\n   }\n\n   /**\n    * @see InstanceType#I2_4XLARGE\n    */\n   public static EC2HardwareBuilder i2_4xlarge() {\n      return new EC2HardwareBuilder(InstanceType.I2_4XLARGE).i2()\n              .ram(122 * 1024)\n              .processors(ImmutableList.of(new Processor(16.0, 3.3125)))\n              .volumes(ImmutableList.<Volume> of(\n                    new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                    new VolumeBuilder().type(LOCAL).size(800.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build(),\n                    new VolumeBuilder().type(LOCAL).size(800.0f).device(\"/dev/sdc\").bootDevice(false).durable(false).build(),\n                    new VolumeBuilder().type(LOCAL).size(800.0f).device(\"/dev/sdd\").bootDevice(false).durable(false).build(),\n                    new VolumeBuilder().type(LOCAL).size(800.0f).device(\"/dev/sde\").bootDevice(false).durable(false).build()))\n              .virtualizationType(VirtualizationType.HVM);\n   }\n\n   /**\n    * @see InstanceType#I2_8XLARGE\n    */\n   public static EC2HardwareBuilder i2_8xlarge() {\n      return new EC2HardwareBuilder(InstanceType.I2_8XLARGE).i2()\n              .ram(244 * 1024)\n              .processors(ImmutableList.of(new Processor(32.0, 3.25)))\n              .volumes(ImmutableList.<Volume> of(\n                    new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                    new VolumeBuilder().type(LOCAL).size(800.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build(),\n                    new VolumeBuilder().type(LOCAL).size(800.0f).device(\"/dev/sdc\").bootDevice(false).durable(false).build(),\n                    new VolumeBuilder().type(LOCAL).size(800.0f).device(\"/dev/sdd\").bootDevice(false).durable(false).build(),\n                    new VolumeBuilder().type(LOCAL).size(800.0f).device(\"/dev/sde\").bootDevice(false).durable(false).build(),\n                    new VolumeBuilder().type(LOCAL).size(800.0f).device(\"/dev/sdf\").bootDevice(false).durable(false).build(),\n                    new VolumeBuilder().type(LOCAL).size(800.0f).device(\"/dev/sdg\").bootDevice(false).durable(false).build(),\n                    new VolumeBuilder().type(LOCAL).size(800.0f).device(\"/dev/sdh\").bootDevice(false).durable(false).build(),\n                    new VolumeBuilder().type(LOCAL).size(800.0f).device(\"/dev/sdi\").bootDevice(false).durable(false).build()))\n              .virtualizationType(VirtualizationType.HVM);\n   }\n\n   public static EC2HardwareBuilder hi1_4xlarge() {\n      return new EC2HardwareBuilder(InstanceType.HI1_4XLARGE).hi1()\n            .ram(60 * 1024 + 512)\n            .processors(ImmutableList.of(new Processor(16.0, 2.1875)))\n            .volumes(ImmutableList.<Volume> of(\n                  new VolumeBuilder().type(LOCAL).size(1024.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(1024.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build()))\n            .virtualizationType(VirtualizationType.HVM);\n   }\n   \n   public static EC2HardwareBuilder hs1_8xlarge() {\n      float twoTB = 2048.0f * 1024.0f;\n      Builder<Volume> all24Volumes = ImmutableList.<Volume>builder();\n      all24Volumes.add(new VolumeBuilder().type(LOCAL).size(twoTB).device(\"/dev/sda1\").bootDevice(true).durable(false).build());\n      for (char letter : ImmutableSet.of('b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',\n            'q', 'r', 's', 't', 'u', 'v', 'w', 'x')) {\n         all24Volumes.add(new VolumeBuilder().type(LOCAL).size(twoTB).device(\"/dev/sd\" + letter).bootDevice(false).durable(false).build());\n      }\n      return new EC2HardwareBuilder(InstanceType.HS1_8XLARGE).hs1()\n            .ram(117 * 1024)\n            .processors(ImmutableList.of(new Processor(16.0, 2.1875)))\n            .volumes(all24Volumes.build())\n            .virtualizationType(VirtualizationType.HVM);\n   }\n\n   /**\n    * @see InstanceType#R3_LARGE\n    */\n   public static EC2HardwareBuilder r3_large() {\n      return new EC2HardwareBuilder(InstanceType.R3_LARGE).r3()\n            .ram(15616)\n            .processors(ImmutableList.of(new Processor(2.0, 2.5)))\n            .volumes(ImmutableList.<Volume> of(\n                  new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(32.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build()));\n   }\n\n   /**\n    * @see InstanceType#R3_XLARGE\n    */\n   public static EC2HardwareBuilder r3_xlarge() {\n      return new EC2HardwareBuilder(InstanceType.R3_XLARGE).r3()\n            .ram(31232)\n            .processors(ImmutableList.of(new Processor(4.0, 2.5)))\n            .volumes(ImmutableList.<Volume> of(\n                  new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(80.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build()));\n   }\n\n   /**\n    * @see InstanceType#R3_2XLARGE\n    */\n   public static EC2HardwareBuilder r3_2xlarge() {\n      return new EC2HardwareBuilder(InstanceType.R3_2XLARGE).r3()\n            .ram(62464)\n            .processors(ImmutableList.of(new Processor(8.0, 2.5)))\n            .volumes(ImmutableList.<Volume> of(\n                  new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(160.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build()));\n   }\n\n   /**\n    * @see InstanceType#R3_4XLARGE\n    */\n   public static EC2HardwareBuilder r3_4xlarge() {\n      return new EC2HardwareBuilder(InstanceType.R3_4XLARGE).r3()\n            .ram(124928)\n            .processors(ImmutableList.of(new Processor(16.0, 2.5)))\n            .volumes(ImmutableList.<Volume> of(\n                  new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(320.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build()));\n   }\n\n   /**\n    * @see InstanceType#R3_8XLARGE\n    */\n   public static EC2HardwareBuilder r3_8xlarge() {\n      return new EC2HardwareBuilder(InstanceType.R3_8XLARGE).r3()\n            .ram(249856)\n            .processors(ImmutableList.of(new Processor(32.0, 2.5)))\n            .volumes(ImmutableList.<Volume> of(\n                  new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(320.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build(),\n                  new VolumeBuilder().type(LOCAL).size(320.0f).device(\"/dev/sdc\").bootDevice(false).durable(false).build()));\n   }\n   \n   /**\n    * @see InstanceType#R4_LARGE\n    */\n   public static EC2HardwareBuilder r4_large() {\n      return new EC2HardwareBuilder(InstanceType.R4_LARGE).r4()\n            .ram(15616)\n            .processors(ImmutableList.of(new Processor(2.0, 2.3)));\n   }\n\n   /**\n    * @see InstanceType#R4_XLARGE\n    */\n   public static EC2HardwareBuilder r4_xlarge() {\n      return new EC2HardwareBuilder(InstanceType.R4_XLARGE).r4()\n            .ram(31232)\n            .processors(ImmutableList.of(new Processor(4.0, 2.3)));\n   }\n\n   /**\n    * @see InstanceType#R4_2XLARGE\n    */\n   public static EC2HardwareBuilder r4_2xlarge() {\n      return new EC2HardwareBuilder(InstanceType.R4_2XLARGE).r4()\n            .ram(62464)\n            .processors(ImmutableList.of(new Processor(8.0, 2.3)));\n   }\n\n   /**\n    * @see InstanceType#R4_4XLARGE\n    */\n   public static EC2HardwareBuilder r4_4xlarge() {\n      return new EC2HardwareBuilder(InstanceType.R4_4XLARGE).r4()\n            .ram(124928)\n            .processors(ImmutableList.of(new Processor(16.0, 2.3)));\n   }\n\n   /**\n    * @see InstanceType#R4_8XLARGE\n    */\n   public static EC2HardwareBuilder r4_8xlarge() {\n      return new EC2HardwareBuilder(InstanceType.R4_8XLARGE).r4()\n            .ram(249856)\n            .processors(ImmutableList.of(new Processor(32.0, 2.3)));\n   }\n\n   /**\n    * @see InstanceType#R4_16XLARGE\n    */\n   public static EC2HardwareBuilder r4_16xlarge() {\n      return new EC2HardwareBuilder(InstanceType.R4_16XLARGE).r4()\n            .ram(499712)\n            .processors(ImmutableList.of(new Processor(64.0, 2.3)));\n   }\n\n   /**\n    * @see InstanceType#X1_16XLARGE\n    */\n   public static EC2HardwareBuilder x1_16xlarge() {\n      return new EC2HardwareBuilder(InstanceType.X1_16XLARGE).x1()\n            .ram(999424)\n            .volumes(ImmutableList.<Volume> of(\n                    new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                    new VolumeBuilder().type(LOCAL).size(1920.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build()))\n            .processors(ImmutableList.of(new Processor(64.0, 2.3)));\n   }\n\n   /**\n    * @see InstanceType#X1_32XLARGE\n    */\n   public static EC2HardwareBuilder x1_32xlarge() {\n      return new EC2HardwareBuilder(InstanceType.X1_32XLARGE).x1()\n            .ram(1998848)\n            .volumes(ImmutableList.<Volume> of(\n                    new VolumeBuilder().type(LOCAL).size(10.0f).device(\"/dev/sda1\").bootDevice(true).durable(false).build(),\n                    new VolumeBuilder().type(LOCAL).size(1920.0f).device(\"/dev/sdb\").bootDevice(false).durable(false).build(),\n                    new VolumeBuilder().type(LOCAL).size(1920.0f).device(\"/dev/sdc\").bootDevice(false).durable(false).build()))\n            .processors(ImmutableList.of(new Processor(128.0, 2.3)));\n   }\n\n   /**\n    * @see InstanceType#A1_MEDIUM\n    */\n   public static EC2HardwareBuilder a1_medium() {\n      return new EC2HardwareBuilder(InstanceType.A1_MEDIUM).ram(2048)\n            .processors(ImmutableList.of(new Processor(1, 2.3))).rootDeviceType(RootDeviceType.EBS)\n            .virtualizationType(VirtualizationType.HVM);\n   }\n\n   /**\n    * @see InstanceType#A1_LARGE\n    */\n   public static org.jclouds.ec2.compute.domain.EC2HardwareBuilder a1_large() {\n      return new EC2HardwareBuilder(InstanceType.A1_LARGE).ram(4096).processors(ImmutableList.of(new Processor(2, 2.3)))\n            .rootDeviceType(RootDeviceType.EBS).virtualizationType(VirtualizationType.HVM);\n   }\n\n   /**\n    * @see InstanceType#A1_XLARGE\n    */\n   public static org.jclouds.ec2.compute.domain.EC2HardwareBuilder a1_xlarge() {\n      return new EC2HardwareBuilder(InstanceType.A1_XLARGE).ram(8192)\n            .processors(ImmutableList.of(new Processor(4, 2.3))).rootDeviceType(RootDeviceType.EBS)\n            .virtualizationType(VirtualizationType.HVM);\n   }\n\n   /**\n    * @see InstanceType#A1_2XLARGE\n    */\n   public static org.jclouds.ec2.compute.domain.EC2HardwareBuilder a1_2xlarge() {\n      return new EC2HardwareBuilder(InstanceType.A1_2XLARGE).ram(16384)\n            .processors(ImmutableList.of(new Processor(8, 2.3))).rootDeviceType(RootDeviceType.EBS)\n            .virtualizationType(VirtualizationType.HVM);\n   }\n\n   /**\n    * @see InstanceType#A1_4XLARGE\n    */\n   public static org.jclouds.ec2.compute.domain.EC2HardwareBuilder a1_4xlarge() {\n      return new EC2HardwareBuilder(InstanceType.A1_4XLARGE).ram(32768)\n            .processors(ImmutableList.of(new Processor(16, 2.3))).rootDeviceType(RootDeviceType.EBS)\n            .virtualizationType(VirtualizationType.HVM);\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public Hardware build() {\n      Preconditions.checkNotNull(virtualizationType, \"virtualizationType\");\n      boolean reset = false;\n      if (this.supportsImage == null)\n         reset = true;\n      try {\n         supportsImage = Predicates.<Image> and(rootDeviceType, virtualizationType, imageIds, is64Bit);\n         return super.build();\n      } finally {\n         if (reset)\n            this.supportsImage = null;\n      }\n\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/domain/PasswordDataAndPrivateKey.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.domain;\n\nimport org.jclouds.ec2.domain.PasswordData;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\n/**\n * An encrypted Windows Administrator password, and the private key that can decrypt it.\n */\npublic class PasswordDataAndPrivateKey {\n\n   private final PasswordData passwordData;\n   private final String privateKey;\n\n   public PasswordDataAndPrivateKey(PasswordData passwordData, String privateKey) {\n      this.passwordData = passwordData;\n      this.privateKey = privateKey;\n   }\n\n   public PasswordData getPasswordData() {\n      return passwordData;\n   }\n\n   public String getPrivateKey() {\n      return privateKey;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(passwordData, privateKey);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      PasswordDataAndPrivateKey other = PasswordDataAndPrivateKey.class.cast(obj);\n      return Objects.equal(this.passwordData, other.passwordData) && Objects.equal(this.privateKey, other.privateKey);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"passwordData\", passwordData).toString();\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/domain/RegionAndName.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\npublic class RegionAndName {\n\n   protected final String region;\n   protected final String name;\n\n   public String slashEncode() {\n      return new StringBuilder(region).append('/').append(name).toString();\n   }\n\n   public RegionAndName(String region, String name) {\n      this.region = checkNotNull(region, \"region\");\n      this.name = checkNotNull(name, \"name\");\n   }\n   \n   @Override\n   public int hashCode() {\n      return Objects.hashCode(region, name);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (!(obj instanceof RegionAndName))\n         return false;\n      RegionAndName other = RegionAndName.class.cast(obj);\n      return Objects.equal(region, other.region) && Objects.equal(name, other.name);\n   }\n\n   public String getRegion() {\n      return region;\n   }\n\n   public String getName() {\n      return name;\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(\"\").add(\"region\", region).add(\"name\", name);\n   }\n\n   private static enum RegionFunction implements Function<RegionAndName, String> {\n      INSTANCE;\n      @Override\n      public String apply(RegionAndName input) {\n         return input.getRegion();\n      }\n\n      @Override\n      public String toString() {\n         return \"getRegion()\";\n      }\n   };\n\n   public static Function<RegionAndName, String> regionFunction() {\n      return RegionFunction.INSTANCE;\n   }\n\n   private static enum NameFunction implements Function<RegionAndName, String> {\n      INSTANCE;\n      @Override\n      public String apply(RegionAndName input) {\n         return input.getName();\n      }\n\n      @Override\n      public String toString() {\n         return \"getName()\";\n      }\n   };\n\n   public static Function<RegionAndName, String> nameFunction() {\n      return NameFunction.INSTANCE;\n   }\n   \n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/domain/RegionNameAndIngressRules.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.domain;\n\npublic class RegionNameAndIngressRules extends RegionAndName {\n   private final int[] ports;\n   private final boolean authorizeSelf;\n   private final String vpcId;\n   \n   public RegionNameAndIngressRules(String region, String tag, int[] ports, boolean authorizeSelf, String vpcId) {\n      super(region, tag);\n      this.ports = ports;\n      this.authorizeSelf = authorizeSelf;\n      this.vpcId = vpcId;\n   }\n\n   // intentionally not overriding equals or hash-code so that we can search only by region/tag in a\n   // map\n\n   public int[] getPorts() {\n      return ports;\n   }\n\n   public boolean shouldAuthorizeSelf() {\n      return authorizeSelf;\n   }\n\n   public String getVpcId() {\n      return vpcId;\n   }\n   \n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/extensions/EC2ImageExtension.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.extensions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.common.collect.Iterables.find;\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_IMAGE_AVAILABLE;\nimport static org.jclouds.location.predicates.LocationPredicates.idEquals;\n\nimport java.util.NoSuchElementException;\nimport java.util.Set;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\n\nimport org.jclouds.Constants;\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.domain.CloneImageTemplate;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.ImageBuilder;\nimport org.jclouds.compute.domain.ImageTemplate;\nimport org.jclouds.compute.domain.ImageTemplateBuilder;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.extensions.ImageExtension;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.domain.Location;\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.domain.Reservation;\nimport org.jclouds.ec2.domain.RunningInstance;\nimport org.jclouds.ec2.options.CreateImageOptions;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.util.concurrent.Atomics;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.common.util.concurrent.UncheckedTimeoutException;\n\n/**\n * EC2 implementation of {@link ImageExtension} please note that {@link #createImage(ImageTemplate)}\n * only works by cloning EBS backed instances for the moment.\n */\npublic class EC2ImageExtension implements ImageExtension {\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n   private final EC2Api ec2Api;\n   private final ListeningExecutorService userExecutor;\n   private final Supplier<Set<? extends Location>> locations;\n   private final Predicate<AtomicReference<Image>> imageAvailablePredicate;\n   \n   @Inject\n   public EC2ImageExtension(EC2Api ec2Api, @Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor,\n         @Memoized Supplier<Set<? extends Location>> locations,\n         @Named(TIMEOUT_IMAGE_AVAILABLE) Predicate<AtomicReference<Image>> imageAvailablePredicate) {\n      this.ec2Api = checkNotNull(ec2Api, \"ec2Api\");\n      this.userExecutor = checkNotNull(userExecutor, \"userExecutor\");\n      this.locations = checkNotNull(locations, \"locations\");\n      this.imageAvailablePredicate = checkNotNull(imageAvailablePredicate, \"imageAvailablePredicate\");\n   }\n\n   @Override\n   public ImageTemplate buildImageTemplateFromNode(String name, String id) {\n      String[] parts = AWSUtils.parseHandle(id);\n      String region = parts[0];\n      String instanceId = parts[1];\n      Reservation<? extends RunningInstance> instance = getOnlyElement(ec2Api.getInstanceApi().get()\n            .describeInstancesInRegion(region, instanceId));\n      if (instance == null)\n         throw new NoSuchElementException(\"Cannot find server with id: \" + id);\n      CloneImageTemplate template = new ImageTemplateBuilder.CloneImageTemplateBuilder().nodeId(id).name(name).build();\n      return template;\n   }\n\n   @Override\n   public ListenableFuture<Image> createImage(ImageTemplate template) {\n      checkState(template instanceof CloneImageTemplate, \" ec2 only supports creating images through cloning.\");\n      CloneImageTemplate cloneTemplate = (CloneImageTemplate) template;\n      String[] parts = AWSUtils.parseHandle(cloneTemplate.getSourceNodeId());\n      String region = parts[0];\n      String instanceId = parts[1];\n\n      String imageId = ec2Api.getAMIApi().get().createImageInRegion(region, cloneTemplate.getName(), instanceId,\n            CreateImageOptions.NONE);\n\n      final AtomicReference<Image> image = Atomics.newReference(new ImageBuilder()\n            .location(find(locations.get(), idEquals(region)))\n            .id(region + \"/\" + imageId)\n            .providerId(imageId)\n            .description(cloneTemplate.getName())\n            .operatingSystem(OperatingSystem.builder().description(cloneTemplate.getName()).build())\n            .status(Image.Status.PENDING).build());\n      \n      return userExecutor.submit(new Callable<Image>() {\n         @Override\n         public Image call() throws Exception {\n            if (imageAvailablePredicate.apply(image))\n               return image.get();\n            // TODO: get rid of the expectation that the image will be available, as it is very brittle\n            throw new UncheckedTimeoutException(\"Image was not created within the time limit: \" + image.get());\n         }\n      });\n   }\n\n   @Override\n   public boolean deleteImage(String id) {\n      String[] parts = AWSUtils.parseHandle(id);\n      String region = parts[0];\n      String instanceId = parts[1];\n      try {\n         ec2Api.getAMIApi().get().deregisterImageInRegion(region, instanceId);\n         return true;\n      } catch (Exception e) {\n         return false;\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/extensions/EC2SecurityGroupExtension.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.extensions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Predicates.notNull;\nimport static com.google.common.collect.Iterables.concat;\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static com.google.common.collect.Iterables.transform;\n\nimport java.util.NoSuchElementException;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\n\nimport org.jclouds.Constants;\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.domain.SecurityGroup;\nimport org.jclouds.compute.extensions.SecurityGroupExtension;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.compute.functions.GroupNamingConvention.Factory;\nimport org.jclouds.domain.Location;\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.compute.domain.RegionNameAndIngressRules;\nimport org.jclouds.ec2.domain.RunningInstance;\nimport org.jclouds.ec2.domain.UserIdGroupPair;\nimport org.jclouds.location.Region;\nimport org.jclouds.net.domain.IpPermission;\nimport org.jclouds.net.domain.IpProtocol;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Multimap;\nimport com.google.common.util.concurrent.ListeningExecutorService;\n\n/**\n * An extension to compute service to allow for the manipulation of {@link SecurityGroup}s. Implementation\n * is optional by providers.\n */\npublic class EC2SecurityGroupExtension implements SecurityGroupExtension {\n\n   protected final EC2Api client;\n   protected final ListeningExecutorService userExecutor;\n   protected final Supplier<Set<String>> regions;\n   protected final Function<org.jclouds.ec2.domain.SecurityGroup, SecurityGroup> groupConverter;\n   protected final Supplier<Set<? extends Location>> locations;\n   protected final LoadingCache<RegionAndName, String> groupCreator;\n   protected final Factory namingConvention;\n\n   @Inject\n   public EC2SecurityGroupExtension(EC2Api client,\n                                    @Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor,\n                                    @Region Supplier<Set<String>> regions,\n                                    Function<org.jclouds.ec2.domain.SecurityGroup, SecurityGroup> groupConverter,\n                                    @Memoized Supplier<Set<? extends Location>> locations,\n                                    @Named(\"SECURITY\") LoadingCache<RegionAndName, String> groupCreator,\n                                    GroupNamingConvention.Factory namingConvention) {\n\n      this.client = checkNotNull(client, \"client\");\n      this.userExecutor = checkNotNull(userExecutor, \"userExecutor\");\n      this.regions = checkNotNull(regions, \"regions\");\n      this.groupConverter = checkNotNull(groupConverter, \"groupConverter\");\n      this.locations = checkNotNull(locations, \"locations\");\n      this.groupCreator = checkNotNull(groupCreator, \"groupCreator\");\n      this.namingConvention = checkNotNull(namingConvention, \"namingConvention\");\n   }\n\n   @Override\n   public Set<SecurityGroup> listSecurityGroups() {\n      Iterable<? extends org.jclouds.ec2.domain.SecurityGroup> rawGroups = pollSecurityGroups();\n      Iterable<SecurityGroup> groups = transform(filter(rawGroups, notNull()),\n                                                 groupConverter);\n      return ImmutableSet.copyOf(groups);\n   }\n\n\n   @Override\n   public Set<SecurityGroup> listSecurityGroupsInLocation(final Location location) {\n      String region = AWSUtils.getRegionFromLocationOrNull(location);\n      if (region == null) {\n         return ImmutableSet.of();\n      }\n      return listSecurityGroupsInLocation(region);\n   }\n\n   public Set<SecurityGroup> listSecurityGroupsInLocation(String region) {\n      Iterable<? extends org.jclouds.ec2.domain.SecurityGroup> rawGroups = pollSecurityGroupsByRegion(region);\n      Iterable<SecurityGroup> groups = transform(filter(rawGroups, notNull()),\n                                                 groupConverter);\n      return ImmutableSet.copyOf(groups);\n   }\n\n   @Override\n   public Set<SecurityGroup> listSecurityGroupsForNode(String id) {\n      checkNotNull(id, \"id\");\n      String[] parts = AWSUtils.parseHandle(id);\n      String region = parts[0];\n      String instanceId = parts[1];\n\n      RunningInstance instance = getOnlyElement(Iterables.concat(client.getInstanceApi().get().describeInstancesInRegion(region, instanceId)));\n\n      if (instance == null) {\n         return ImmutableSet.of();\n      }\n\n      Set<String> groupNames = instance.getGroupNames();\n      Set<? extends org.jclouds.ec2.domain.SecurityGroup> rawGroups =\n         client.getSecurityGroupApi().get().describeSecurityGroupsInRegion(region, Iterables.toArray(groupNames, String.class));\n\n      return ImmutableSet.copyOf(transform(filter(rawGroups, notNull()), groupConverter));\n   }\n\n   @Override\n   public SecurityGroup getSecurityGroupById(String id) {\n      checkNotNull(id, \"id\");\n      String[] parts = AWSUtils.parseHandle(id);\n      String region = parts[0];\n      String groupId = parts[1];\n\n      Set<? extends org.jclouds.ec2.domain.SecurityGroup> rawGroups =\n         client.getSecurityGroupApi().get().describeSecurityGroupsInRegion(region, groupId);\n\n      return getOnlyElement(transform(filter(rawGroups, notNull()), groupConverter));\n   }\n\n   @Override\n   public SecurityGroup createSecurityGroup(String name, Location location) {\n      String region = AWSUtils.getRegionFromLocationOrNull(location);\n      if (region != null) {\n         return createSecurityGroup(name, region);\n      } else {\n         return null;\n      }\n   }\n\n   public SecurityGroup createSecurityGroup(String name, String region) {\n      String markerGroup = namingConvention.create().sharedNameForGroup(name);\n      RegionNameAndIngressRules regionAndName = new RegionNameAndIngressRules(region, markerGroup, new int[] {},\n                                                                              false, null);\n\n      groupCreator.getUnchecked(regionAndName);\n\n      return getSecurityGroupById(regionAndName.slashEncode());\n   }\n\n   @Override\n   public boolean removeSecurityGroup(String id) {\n      checkNotNull(id, \"id\");\n      String[] parts = AWSUtils.parseHandle(id);\n      String region = parts[0];\n      String groupName = parts[1];\n\n      boolean deleted = false;\n      if (!client.getSecurityGroupApi().get().describeSecurityGroupsInRegion(region, groupName).isEmpty()) {\n         client.getSecurityGroupApi().get().deleteSecurityGroupInRegion(region, groupName);\n         deleted = true;\n      }\n      groupCreator.invalidate(new RegionNameAndIngressRules(region, groupName, null, false, null));\n      return deleted;\n   }\n\n   @Override\n   public SecurityGroup addIpPermission(IpPermission ipPermission, SecurityGroup group) {\n      String region = AWSUtils.getRegionFromLocationOrNull(group.getLocation());\n      String name = group.getName();\n\n      if (!ipPermission.getCidrBlocks().isEmpty()) {\n         for (String cidr : ipPermission.getCidrBlocks()) {\n            client.getSecurityGroupApi().get().\n               authorizeSecurityGroupIngressInRegion(region,\n                                                     name,\n                                                     ipPermission.getIpProtocol(),\n                                                     ipPermission.getFromPort(),\n                                                     ipPermission.getToPort(),\n                                                     cidr);\n         }\n      }\n\n      if (!ipPermission.getTenantIdGroupNamePairs().isEmpty()) {\n         for (String userId : ipPermission.getTenantIdGroupNamePairs().keySet()) {\n            for (String groupName : ipPermission.getTenantIdGroupNamePairs().get(userId)) {\n               client.getSecurityGroupApi().get().\n                  authorizeSecurityGroupIngressInRegion(region,\n                                                        name,\n                                                        new UserIdGroupPair(userId, groupName));\n            }\n         }\n      }\n\n      return getSecurityGroupById(new RegionAndName(region, group.getName()).slashEncode());\n   }\n\n   @Override\n   public SecurityGroup addIpPermission(IpProtocol protocol, int startPort, int endPort,\n                                        Multimap<String, String> tenantIdGroupNamePairs,\n                                        Iterable<String> ipRanges,\n                                        Iterable<String> groupIds, SecurityGroup group) {\n      String region = AWSUtils.getRegionFromLocationOrNull(group.getLocation());\n      String name = group.getName();\n\n      if (!Iterables.isEmpty(ipRanges)) {\n         for (String cidr : ipRanges) {\n            client.getSecurityGroupApi().get().\n               authorizeSecurityGroupIngressInRegion(region,\n                                                     name,\n                                                     protocol,\n                                                     startPort,\n                                                     endPort,\n                                                     cidr);\n         }\n      }\n\n      if (!tenantIdGroupNamePairs.isEmpty()) {\n         for (String userId : tenantIdGroupNamePairs.keySet()) {\n            for (String groupName : tenantIdGroupNamePairs.get(userId)) {\n               client.getSecurityGroupApi().get().\n                  authorizeSecurityGroupIngressInRegion(region,\n                                                        name,\n                                                        new UserIdGroupPair(userId, groupName));\n            }\n         }\n      }\n\n      return getSecurityGroupById(new RegionAndName(region, group.getName()).slashEncode());\n   }\n\n   @Override\n   public SecurityGroup removeIpPermission(IpPermission ipPermission, SecurityGroup group) {\n      String region = AWSUtils.getRegionFromLocationOrNull(group.getLocation());\n      String name = group.getName();\n\n      if (!ipPermission.getCidrBlocks().isEmpty()) {\n         for (String cidr : ipPermission.getCidrBlocks()) {\n            client.getSecurityGroupApi().get().\n               revokeSecurityGroupIngressInRegion(region,\n                                                  name,\n                                                  ipPermission.getIpProtocol(),\n                                                  ipPermission.getFromPort(),\n                                                  ipPermission.getToPort(),\n                                                  cidr);\n         }\n      }\n\n      if (!ipPermission.getTenantIdGroupNamePairs().isEmpty()) {\n         for (String userId : ipPermission.getTenantIdGroupNamePairs().keySet()) {\n            for (String groupName : ipPermission.getTenantIdGroupNamePairs().get(userId)) {\n               client.getSecurityGroupApi().get().\n                  revokeSecurityGroupIngressInRegion(region,\n                                                     name,\n                                                     new UserIdGroupPair(userId, groupName));\n            }\n         }\n      }\n\n      return getSecurityGroupById(new RegionAndName(region, group.getName()).slashEncode());\n   }\n\n   @Override\n   public SecurityGroup removeIpPermission(IpProtocol protocol, int startPort, int endPort,\n                                           Multimap<String, String> tenantIdGroupNamePairs,\n                                           Iterable<String> ipRanges,\n                                           Iterable<String> groupIds, SecurityGroup group) {\n      String region = AWSUtils.getRegionFromLocationOrNull(group.getLocation());\n      String name = group.getName();\n\n      if (!Iterables.isEmpty(ipRanges)) {\n         for (String cidr : ipRanges) {\n            client.getSecurityGroupApi().get().\n               revokeSecurityGroupIngressInRegion(region,\n                                                  name,\n                                                  protocol,\n                                                  startPort,\n                                                  endPort,\n                                                  cidr);\n         }\n      }\n\n      if (!tenantIdGroupNamePairs.isEmpty()) {\n         for (String userId : tenantIdGroupNamePairs.keySet()) {\n            for (String groupName : tenantIdGroupNamePairs.get(userId)) {\n               client.getSecurityGroupApi().get().\n                  revokeSecurityGroupIngressInRegion(region,\n                                                     name,\n                                                     new UserIdGroupPair(userId, groupName));\n            }\n         }\n      }\n\n      return getSecurityGroupById(new RegionAndName(region, group.getName()).slashEncode());\n   }\n\n   @Override\n   public boolean supportsTenantIdGroupNamePairs() {\n      return true;\n   }\n\n   @Override\n   public boolean supportsTenantIdGroupIdPairs() {\n      return false;\n   }\n\n   @Override\n   public boolean supportsGroupIds() {\n      return false;\n   }\n\n   @Override\n   public boolean supportsPortRangesForGroups() {\n      return false;\n   }\n\n   @Override\n   public boolean supportsExclusionCidrBlocks() {\n      return false;\n   }\n\n   protected Iterable<? extends org.jclouds.ec2.domain.SecurityGroup> pollSecurityGroups() {\n      Iterable<? extends Set<? extends org.jclouds.ec2.domain.SecurityGroup>> groups\n         = transform(regions.get(), allSecurityGroupsInRegion());\n\n      return concat(groups);\n   }\n\n\n   protected Iterable<? extends org.jclouds.ec2.domain.SecurityGroup> pollSecurityGroupsByRegion(String region) {\n      return allSecurityGroupsInRegion().apply(region);\n   }\n\n   protected Function<String, Set<? extends org.jclouds.ec2.domain.SecurityGroup>> allSecurityGroupsInRegion() {\n      return new Function<String, Set<? extends org.jclouds.ec2.domain.SecurityGroup>>() {\n\n         @Override\n         public Set<? extends org.jclouds.ec2.domain.SecurityGroup> apply(String from) {\n            return client.getSecurityGroupApi().get().describeSecurityGroupsInRegion(from);\n         }\n\n      };\n   }\n\n   protected Location findLocationWithId(final String locationId) {\n      if (locationId == null)\n         return null;\n      try {\n         Location location = Iterables.find(locations.get(), new Predicate<Location>() {\n\n            @Override\n            public boolean apply(Location input) {\n               return input.getId().equals(locationId);\n            }\n\n         });\n         return location;\n\n      } catch (NoSuchElementException e) {\n         return null;\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/functions/AddElasticIpsToNodemetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.concurrent.ExecutionException;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadataBuilder;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Throwables;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * This class searches for elastic ip addresses that are associated with the node, and adds them to\n * the publicIpAddress collection if present.\n */\n@Singleton\npublic class AddElasticIpsToNodemetadata implements Function<NodeMetadata, NodeMetadata> {\n\n   private final LoadingCache<RegionAndName, String> cache;\n\n   @Inject\n   protected AddElasticIpsToNodemetadata(@Named(\"ELASTICIP\") LoadingCache<RegionAndName, String> cache) {\n      this.cache = checkNotNull(cache, \"cache\");\n   }\n\n   // Note: Instances only have one Internet routable IP address. When an Elastic IP is associated to an\n   // instance, the instance's existing Public IP address mapping is removed and is no longer valid for this instance\n   // http://aws.amazon.com/articles/1346\n\n   // TODO can there be multiple elastic ips on one instance?\n   @Override\n   public NodeMetadata apply(NodeMetadata arg0) {\n      String[] parts = AWSUtils.parseHandle(arg0.getId());\n      String region = parts[0];\n      String instanceId = parts[1];\n      try {\n         String publicIp = cache.get(new RegionAndName(region, instanceId));\n         // Replace existing public addresses with elastic IP (see note above)\n         return NodeMetadataBuilder.fromNodeMetadata(arg0)\n                 .publicAddresses(ImmutableSet.<String> builder().add(publicIp).build()).build();\n      } catch (CacheLoader.InvalidCacheLoadException e) {\n         // no ip was found\n         return arg0;\n      } catch (ExecutionException e) {\n         throw Throwables.propagate(e);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/functions/CreateUniqueKeyPair.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.domain.KeyPair;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Function;\nimport com.google.inject.Inject;\n\n@Singleton\npublic class CreateUniqueKeyPair implements Function<RegionAndName, KeyPair> {\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n   protected final EC2Api ec2Api;\n   protected final GroupNamingConvention.Factory namingConvention;\n\n   @Inject\n   public CreateUniqueKeyPair(EC2Api ec2Api, GroupNamingConvention.Factory namingConvention) {\n      this.ec2Api = ec2Api;\n      this.namingConvention = checkNotNull(namingConvention, \"namingConvention\");\n   }\n\n   @Override\n   public KeyPair apply(RegionAndName from) {\n      return createNewKeyPairInRegion(from.getRegion(), from.getName());\n   }\n\n   @VisibleForTesting\n   KeyPair createNewKeyPairInRegion(String region, String group) {\n      checkNotNull(region, \"region\");\n      checkNotNull(group, \"group\");\n      logger.debug(\">> creating keyPair region(%s) group(%s)\", region, group);\n      KeyPair keyPair = null;\n      String prefix = group;\n      \n      while (keyPair == null) {\n         String keyName = namingConvention.create().uniqueNameForGroup(prefix);\n         try {\n            keyPair = ec2Api.getKeyPairApi().get().createKeyPairInRegion(region, keyName);\n         } catch (IllegalStateException e) {\n            logger.trace(\"   invalid keyname (%s in %s); retrying\", keyName, region);\n         }\n      }\n      \n      logger.debug(\"<< created keyPair(%s)\", keyPair);\n      return keyPair;\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/functions/CredentialsForInstance.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.concurrent.ConcurrentMap;\nimport java.util.concurrent.ExecutionException;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.domain.KeyPair;\nimport org.jclouds.ec2.domain.RunningInstance;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\n\n@Singleton\npublic class CredentialsForInstance extends CacheLoader<RunningInstance, Optional<LoginCredentials>> {\n\n   private final ConcurrentMap<RegionAndName, KeyPair> credentialsMap;\n   private final Supplier<LoadingCache<RegionAndName, ? extends Image>> imageMap;\n   private final Function<RunningInstance, LoginCredentials> passwordCredentialsFromWindowsInstance;\n\n   @Inject\n   CredentialsForInstance(ConcurrentMap<RegionAndName, KeyPair> credentialsMap,\n            Supplier<LoadingCache<RegionAndName, ? extends Image>> imageMap, Function<RunningInstance, LoginCredentials> passwordCredentialsFromWindowsInstance) {\n      this.credentialsMap = checkNotNull(credentialsMap, \"credentialsMap\");\n      this.imageMap = checkNotNull(imageMap, \"imageMap\");\n      this.passwordCredentialsFromWindowsInstance = checkNotNull(passwordCredentialsFromWindowsInstance, \"passwordCredentialsFromWindowsInstance\");\n   }\n\n   @Override\n   public Optional<LoginCredentials> load(final RunningInstance instance) throws ExecutionException {\n      if (\"windows\".equals(instance.getPlatform())) {\n         return Optional.of(passwordCredentialsFromWindowsInstance.apply(instance));\n      } else  if (instance.getKeyName() != null) {\n         return Optional.of(LoginCredentials.builder().user(getLoginAccountFor(instance)).privateKey(getPrivateKeyOrNull(instance)).build());\n      }\n      return Optional.absent();\n   }\n\n   @VisibleForTesting\n   String getPrivateKeyOrNull(RunningInstance instance) {\n      KeyPair keyPair = credentialsMap.get(new RegionAndName(instance.getRegion(), instance.getKeyName()));\n      return keyPair != null ? keyPair.getKeyMaterial() : null;\n   }\n\n   @VisibleForTesting\n   String getLoginAccountFor(RunningInstance from) throws ExecutionException {\n      return imageMap.get().get(new RegionAndName(from.getRegion(), from.getImageId())).getDefaultCredentials().identity;\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/functions/EC2ImageParser.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.compute.util.ComputeServiceUtils.parseOsFamilyOrUnrecognized;\n\nimport java.util.Map;\nimport java.util.NoSuchElementException;\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.Image.Status;\nimport org.jclouds.compute.domain.ImageBuilder;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.compute.strategy.PopulateDefaultLoginCredentialsForImageStrategy;\nimport org.jclouds.compute.util.ComputeServiceUtils;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.ec2.compute.strategy.ReviseParsedImage;\nimport org.jclouds.ec2.domain.Image.Architecture;\nimport org.jclouds.ec2.domain.Image.ImageState;\nimport org.jclouds.ec2.domain.Image.ImageType;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\n\n@Singleton\npublic class EC2ImageParser implements Function<org.jclouds.ec2.domain.Image, Image> {\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n   \n   private final Map<ImageState, Status> toPortableImageStatus;\n   private final PopulateDefaultLoginCredentialsForImageStrategy credentialProvider;\n   private final Supplier<Set<? extends Location>> locations;\n   private final Supplier<Location> defaultLocation;\n   private final Map<OsFamily, Map<String, String>> osVersionMap;\n   private final ReviseParsedImage reviseParsedImage;\n\n\n   @Inject\n   public EC2ImageParser(Map<ImageState, Image.Status> toPortableImageStatus,\n            PopulateDefaultLoginCredentialsForImageStrategy credentialProvider,\n            Map<OsFamily, Map<String, String>> osVersionMap, @Memoized Supplier<Set<? extends Location>> locations,\n            Supplier<Location> defaultLocation, ReviseParsedImage reviseParsedImage) {\n      this.toPortableImageStatus = checkNotNull(toPortableImageStatus, \"toPortableImageStatus\");\n      this.credentialProvider = checkNotNull(credentialProvider, \"credentialProvider\");\n      this.locations = checkNotNull(locations, \"locations\");\n      this.defaultLocation = checkNotNull(defaultLocation, \"defaultLocation\");\n      this.osVersionMap = checkNotNull(osVersionMap, \"osVersionMap\");\n      this.reviseParsedImage = checkNotNull(reviseParsedImage, \"reviseParsedImage\");\n   }\n\n   @Override\n   public Image apply(final org.jclouds.ec2.domain.Image from) {\n      if (from.getImageType() != ImageType.MACHINE) {\n         return null;\n      }\n      ImageBuilder builder = new ImageBuilder();\n      builder.providerId(from.getId());\n      builder.id(from.getRegion() + \"/\" + from.getId());\n      builder.name(from.getName());\n      builder.description(from.getDescription() != null ? from.getDescription() : from.getImageLocation());\n      builder.userMetadata(ImmutableMap.<String, String> builder().put(\"owner\", from.getImageOwnerId()).put(\n               \"rootDeviceType\", from.getRootDeviceType().value()).put(\"virtualizationType\",\n               from.getVirtualizationType().value()).put(\"hypervisor\", from.getHypervisor().value()).build());\n\n      OperatingSystem.Builder osBuilder = OperatingSystem.builder();\n      osBuilder.is64Bit(from.getArchitecture() == Architecture.X86_64);\n      OsFamily family = parseOsFamily(from);\n      osBuilder.family(family);\n      osBuilder.version(ComputeServiceUtils.parseVersionOrReturnEmptyString(family, from.getImageLocation(),\n               osVersionMap));\n      osBuilder.description(from.getImageLocation());\n      osBuilder.arch(from.getVirtualizationType().value());\n\n      reviseParsedImage.reviseParsedImage(from, builder, family, osBuilder);\n\n      builder.defaultCredentials(credentialProvider.apply(from));\n\n      try {\n         builder.location(Iterables.find(locations.get(), new Predicate<Location>() {\n\n            @Override\n            public boolean apply(Location input) {\n               return input.getId().equals(from.getRegion());\n            }\n\n         }));\n      } catch (NoSuchElementException e) {\n         logger.error(\"unknown region %s for image %s; not in %s\", from.getRegion(), from.getId(), locations);\n         builder.location(new LocationBuilder().scope(LocationScope.REGION).id(from.getRegion()).description(\n                  from.getRegion()).parent(defaultLocation.get()).build());\n      }\n      builder.operatingSystem(osBuilder.build());\n      builder.status(toPortableImageStatus.get(from.getImageState()));\n      builder.backendStatus(from.getRawState());\n      return builder.build();\n   }\n\n   /** \n    * First treats windows as a special case: check if platform==windows.\n    * Then tries matching based on the image name.\n    * And then falls back to checking other types of platform.\n    */\n   private OsFamily parseOsFamily(org.jclouds.ec2.domain.Image from) {\n      if (from.getPlatform() != null && from.getPlatform().equalsIgnoreCase(\"windows\")) {\n         return OsFamily.WINDOWS;\n      }\n      \n      OsFamily family = parseOsFamilyOrUnrecognized(from.getImageLocation());\n      if (family == OsFamily.UNRECOGNIZED && from.getPlatform() != null) {\n         family = parseOsFamilyOrUnrecognized(from.getPlatform());\n      }\n      return family;\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/functions/EC2SecurityGroupIdFromName.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.ImmutableMultimap.of;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.ec2.EC2Api;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.Iterables;\n\n@Singleton\npublic class EC2SecurityGroupIdFromName implements Function<String, String> {\n   protected EC2Api api;\n\n   @Inject\n   public EC2SecurityGroupIdFromName(EC2Api api) {\n      this.api = checkNotNull(api, \"api\");\n   }\n\n   @Override\n   public String apply(String input) {\n      checkNotNull(input, \"input\");\n      String[] parts = AWSUtils.parseHandle(input);\n      String region = parts[0];\n      String name = parts[1];\n      return Iterables.getOnlyElement(api.getSecurityGroupApi().get()\n               .describeSecurityGroupsInRegionWithFilter(region, of(\"group-name\", name))).getId();\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/functions/EC2SecurityGroupToSecurityGroup.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.NoSuchElementException;\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.domain.SecurityGroup;\nimport org.jclouds.compute.domain.SecurityGroupBuilder;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.domain.Location;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.Iterables;\nimport com.google.inject.Inject;\n\n\n/**\n * A function for transforming an EC2-specific SecurityGroup into a generic\n * SecurityGroup object.\n */\n@Singleton\npublic class EC2SecurityGroupToSecurityGroup implements Function<org.jclouds.ec2.domain.SecurityGroup, SecurityGroup> {\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n   \n   protected final Supplier<Set<? extends Location>> locations;\n\n   @Inject\n   public EC2SecurityGroupToSecurityGroup(@Memoized Supplier<Set<? extends Location>> locations) {\n      this.locations = checkNotNull(locations, \"locations\");\n   }\n\n   @Override\n   public SecurityGroup apply(org.jclouds.ec2.domain.SecurityGroup group) {\n      SecurityGroupBuilder builder = new SecurityGroupBuilder();\n      Location location = findLocationWithId(group.getRegion());\n      builder.location(location);\n      builder.id(group.getRegion() + \"/\" + idOrName(group));\n      builder.providerId(group.getId());\n      builder.name(group.getName());\n      builder.ipPermissions(group);\n      builder.ownerId(group.getOwnerId());\n      \n      return builder.build();\n   }\n\n   protected String idOrName(org.jclouds.ec2.domain.SecurityGroup group) {\n      return group.getName();\n   }\n\n   private Location findLocationWithId(final String locationId) {\n      if (locationId == null)\n         return null;\n      try {\n         Location location = Iterables.find(locations.get(), new Predicate<Location>() {\n\n            @Override\n            public boolean apply(Location input) {\n               return input.getId().equals(locationId);\n            }\n\n         });\n         return location;\n\n      } catch (NoSuchElementException e) {\n         logger.debug(\"couldn't match instance location %s in: %s\", locationId, locations.get());\n         return null;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/functions/ImagesToRegionAndIdMap.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.functions;\n\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.common.collect.Maps.uniqueIndex;\n\nimport java.util.Map;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Preconditions;\n\n@Singleton\npublic class ImagesToRegionAndIdMap implements Function<Iterable<? extends Image>, Map<RegionAndName, ? extends Image>> {\n\n   public static Map<RegionAndName, ? extends Image> imagesToMap(Iterable<? extends Image> input) {\n      return new ImagesToRegionAndIdMap().apply(input);\n   }\n\n   @Override\n   public Map<RegionAndName, ? extends Image> apply(Iterable<? extends Image> input) {\n      return uniqueIndex(input, new Function<Image, RegionAndName>() {\n\n         @Override\n         public RegionAndName apply(Image from) {\n            checkState(from.getLocation() != null,\n                     \"in ec2, image locations cannot be null; typically, they are Region-scoped\");\n            String[] segments = from.getId().split(\"/\");\n            Preconditions.checkArgument(segments.length == 2, \"Wrong form for AWS image ID: \" + from);\n            return new RegionAndName(segments[0], segments[1]);\n         }\n\n      });\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/functions/PasswordCredentialsFromWindowsInstance.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static org.jclouds.util.Predicates2.retry;\n\nimport java.util.concurrent.ConcurrentMap;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.compute.domain.PasswordDataAndPrivateKey;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.domain.KeyPair;\nimport org.jclouds.ec2.domain.PasswordData;\nimport org.jclouds.ec2.domain.RunningInstance;\nimport org.jclouds.ec2.features.WindowsApi;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Strings;\nimport com.google.common.util.concurrent.Atomics;\n\n@Singleton\npublic class PasswordCredentialsFromWindowsInstance implements Function<RunningInstance, LoginCredentials> {\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   private final ConcurrentMap<RegionAndName, KeyPair> credentialsMap;\n   private final EC2Api ec2Api;\n   private final Function<PasswordDataAndPrivateKey, LoginCredentials> pwDataToLoginCredentials;\n\n   @Inject\n   protected PasswordCredentialsFromWindowsInstance(ConcurrentMap<RegionAndName, KeyPair> credentialsMap,\n            EC2Api ec2Api, Function<PasswordDataAndPrivateKey, LoginCredentials> pwDataToLoginCredentials) {\n      this.credentialsMap = checkNotNull(credentialsMap, \"credentialsMap\");\n      this.ec2Api = checkNotNull(ec2Api, \"ec2Api\");\n      this.pwDataToLoginCredentials = checkNotNull(pwDataToLoginCredentials, \"pwDataToLoginCredentials\");\n   }\n\n   @Override\n   public LoginCredentials apply(final RunningInstance instance) {\n      Optional<? extends WindowsApi> windowsOption = ec2Api.getWindowsApiForRegion(instance.getRegion());\n      checkState(windowsOption.isPresent(), \"windows feature not present in region %s\", instance.getRegion());\n      \n      final WindowsApi windowsApi = windowsOption.get();\n      \n      LoginCredentials credentials = LoginCredentials.builder().user(\"Administrator\").noPrivateKey().build();\n      String privateKey = getPrivateKeyOrNull(instance);\n      if (privateKey == null) {\n         return credentials;\n      }\n      // The Administrator password will take some time before it is ready - Amazon says\n      // sometimes\n      // 15 minutes.\n      // So we create a predicate that tests if the password is ready, and wrap it in a retryable\n      // predicate.\n      final AtomicReference<PasswordData> data = Atomics.newReference();\n      Predicate<String> passwordReady = new Predicate<String>() {\n         @Override\n         public boolean apply(@Nullable String s) {\n            if (Strings.isNullOrEmpty(s))\n               return false;\n            data.set(windowsApi.getPasswordDataForInstance(instance.getId()));\n            if (data.get() == null)\n               return false;\n            return !Strings.isNullOrEmpty(data.get().getPasswordData());\n         }\n      };\n\n      // TODO: parameterize\n      Predicate<String> passwordReadyRetryable = retry(passwordReady, 600, 10, SECONDS);\n\n      logger.debug(\">> awaiting password data for instance(%s/%s)\", instance.getRegion(), instance.getId());\n      if (passwordReadyRetryable.apply(instance.getId())) {\n         credentials = pwDataToLoginCredentials.apply(new PasswordDataAndPrivateKey(data.get(), privateKey));\n         logger.debug(\"<< obtained password data for instance(%s/%s)\", instance.getRegion(), instance.getId());\n      } else {\n         logger.debug(\"<< unable to get password data for instance(%s/%s)\", instance.getRegion(), instance.getId());\n      }\n      return credentials;\n   }\n\n   @VisibleForTesting\n   String getPrivateKeyOrNull(RunningInstance instance) {\n      KeyPair keyPair = credentialsMap.get(new RegionAndName(instance.getRegion(), instance.getKeyName()));\n      return keyPair != null ? keyPair.getKeyMaterial() : null;\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/functions/PresentInstances.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.concat;\nimport static com.google.common.collect.Iterables.toArray;\nimport static com.google.common.collect.Multimaps.index;\nimport static com.google.common.collect.Multimaps.transformValues;\nimport static org.jclouds.ec2.compute.domain.RegionAndName.nameFunction;\nimport static org.jclouds.ec2.compute.domain.RegionAndName.regionFunction;\n\nimport java.util.Collection;\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.domain.RunningInstance;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\nimport com.google.common.collect.Multimap;\nimport com.google.inject.Inject;\n\n/**\n * returns the instances present in the list.  Makes a single rest call per aggregate on region.\n */\n@Singleton\npublic class PresentInstances implements Function<Set<RegionAndName>, Set<RunningInstance>> {\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   private final EC2Api client;\n\n   @Inject\n   public PresentInstances(EC2Api client) {\n      this.client = checkNotNull(client, \"client\");\n   }\n\n   @Override\n   public Set<RunningInstance> apply(Set<RegionAndName> regionAndIds) {\n      if (checkNotNull(regionAndIds, \"regionAndIds\").isEmpty())\n         return ImmutableSet.of();\n      Builder<RunningInstance> builder = ImmutableSet.<RunningInstance> builder();\n      Multimap<String, String> regionToInstanceIds = transformValues(index(regionAndIds, regionFunction()),\n            nameFunction());\n      for (Map.Entry<String, Collection<String>> entry : regionToInstanceIds.asMap().entrySet()) {\n         String region = entry.getKey();\n         Collection<String> instanceIds = entry.getValue();\n         logger.trace(\"looking for instances %s in region %s\", instanceIds, region);\n         builder.addAll(concat(client.getInstanceApi().get().describeInstancesInRegion(region,\n               toArray(instanceIds, String.class))));\n      }\n      return builder.build();\n   }\n   \n   @Override\n   public String toString() {\n      return \"presentInstances()\";\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/functions/RunningInstanceToNodeMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Predicates.not;\nimport static com.google.common.base.Strings.emptyToNull;\nimport static com.google.common.collect.Iterables.filter;\nimport static org.jclouds.compute.util.ComputeServiceUtils.addMetadataAndParseTagsFromValuesOfEmptyString;\n\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.NoSuchElementException;\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.HardwareBuilder;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadata.Status;\nimport org.jclouds.compute.domain.NodeMetadataBuilder;\nimport org.jclouds.compute.domain.Volume;\nimport org.jclouds.compute.domain.internal.VolumeImpl;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.domain.BlockDevice;\nimport org.jclouds.ec2.domain.InstanceState;\nimport org.jclouds.ec2.domain.RootDeviceType;\nimport org.jclouds.ec2.domain.RunningInstance;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.util.InetAddresses2.IsPrivateIPAddress;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Lists;\nimport com.google.common.collect.Sets;\nimport com.google.common.util.concurrent.UncheckedExecutionException;\nimport com.google.inject.Inject;\n\n@Singleton\npublic class RunningInstanceToNodeMetadata implements Function<RunningInstance, NodeMetadata> {\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   protected final Supplier<Set<? extends Location>> locations;\n   protected final Supplier<Set<? extends Hardware>> hardware;\n   protected final Supplier<LoadingCache<RegionAndName, ? extends Image>> imageMap;\n   protected final Map<String, Credentials> credentialStore;\n   protected final Map<InstanceState, Status> instanceToNodeStatus;\n   protected final GroupNamingConvention.Factory namingConvention;\n\n   @Inject\n   protected RunningInstanceToNodeMetadata(Map<InstanceState, Status> instanceToNodeStatus,\n            Map<String, Credentials> credentialStore, Supplier<LoadingCache<RegionAndName, ? extends Image>> imageMap,\n            @Memoized Supplier<Set<? extends Location>> locations, @Memoized Supplier<Set<? extends Hardware>> hardware,\n            GroupNamingConvention.Factory namingConvention) {\n      this.locations = checkNotNull(locations, \"locations\");\n      this.hardware = checkNotNull(hardware, \"hardware\");\n      this.imageMap = checkNotNull(imageMap, \"imageMap\");\n      this.instanceToNodeStatus = checkNotNull(instanceToNodeStatus, \"instanceToNodeStatus\");\n      this.credentialStore = checkNotNull(credentialStore, \"credentialStore\");\n      this.namingConvention = checkNotNull(namingConvention, \"namingConvention\");\n   }\n\n   @Override\n   public NodeMetadata apply(RunningInstance instance) {\n      if (instance == null || instance.getId() == null)\n         return null;\n      NodeMetadataBuilder builder = new NodeMetadataBuilder();\n      builder.name(instance.getTags().get(\"Name\"));\n      addMetadataAndParseTagsFromValuesOfEmptyString(builder, instance.getTags());\n      builder.providerId(instance.getId());\n      builder.id(instance.getRegion() + \"/\" + instance.getId());\n      String group = getGroupForInstance(instance);\n      builder.group(group);\n      // standard convention from aws-ec2, which might not be re-used outside.\n      if (instance.getPrivateDnsName() != null)\n         builder.hostname(instance.getPrivateDnsName().replaceAll(\"\\\\..*\", \"\"));\n      addCredentialsForInstance(builder, instance);\n      builder.status(instanceToNodeStatus.get(instance.getInstanceState()));\n      builder.backendStatus(instance.getRawState());\n\n      // collect all ip addresses into one bundle in case the api mistakenly put a private address\n      // into the public address field\n      Builder<String> addressesBuilder = ImmutableSet.builder();\n      if (emptyToNull(instance.getIpAddress()) != null)\n         addressesBuilder.add(instance.getIpAddress());\n      if (emptyToNull(instance.getPrivateIpAddress()) != null)\n         addressesBuilder.add(instance.getPrivateIpAddress());\n\n      Set<String> addresses = addressesBuilder.build();\n\n      builder.publicAddresses(filter(addresses, not(IsPrivateIPAddress.INSTANCE)));\n      builder.privateAddresses(filter(addresses, IsPrivateIPAddress.INSTANCE));\n      builder.hardware(parseHardware(instance));\n      Location location = getLocationForAvailabilityZoneOrRegion(instance);\n      builder.location(location);\n      builder.imageId(instance.getRegion() + \"/\" + instance.getImageId());\n\n      // extract the operating system from the image\n      RegionAndName regionAndName = new RegionAndName(instance.getRegion(), instance.getImageId());\n      try {\n         Image image = imageMap.get().getUnchecked(regionAndName);\n         if (image != null)\n            builder.operatingSystem(image.getOperatingSystem());\n      } catch (CacheLoader.InvalidCacheLoadException e) {\n         logger.debug(\"image not found for %s: %s\", regionAndName, e);\n      } catch (UncheckedExecutionException e) {\n         logger.debug(\"error getting image for %s: %s\", regionAndName, e);\n      }\n      return builder.build();\n   }\n\n   protected void addCredentialsForInstance(NodeMetadataBuilder builder, RunningInstance instance) {\n      builder.credentials(LoginCredentials.fromCredentials(credentialStore.get(\"node#\" + instance.getRegion() + \"/\"\n            + instance.getId())));\n   }\n\n   protected Hardware parseHardware(final RunningInstance instance) {\n      Hardware hardware = getHardwareForInstance(instance);\n\n      if (hardware != null) {\n         hardware = HardwareBuilder.fromHardware(hardware).volumes(addEBS(instance, hardware.getVolumes())).build();\n      }\n      return hardware;\n   }\n\n   @VisibleForTesting\n   static List<Volume> addEBS(final RunningInstance instance, Iterable<? extends Volume> volumes) {\n      Iterable<Volume> ebsVolumes = Iterables.transform(instance.getEbsBlockDevices().entrySet(),\n               new Function<Entry<String, BlockDevice>, Volume>() {\n\n                  @Override\n                  public Volume apply(Entry<String, BlockDevice> from) {\n                     return new VolumeImpl(from.getValue().getVolumeId(), Volume.Type.SAN, null, from.getKey(),\n                              instance.getRootDeviceName() != null\n                                       && instance.getRootDeviceName().equals(from.getKey()), true);\n                  }\n               });\n\n      if (instance.getRootDeviceType() == RootDeviceType.EBS) {\n         volumes = Iterables.filter(volumes, new Predicate<Volume>() {\n\n            @Override\n            public boolean apply(Volume input) {\n               return !input.isBootDevice();\n            }\n\n         });\n\n      }\n      return Lists.newArrayList(Iterables.concat(volumes, ebsVolumes));\n\n   }\n\n   @VisibleForTesting\n   String getGroupForInstance(final RunningInstance instance) {\n      String group = parseGroupFrom(instance, instance.getGroupNames());\n      if (group == null && instance.getKeyName() != null) {\n         // when not using a generated security group, e.g. in VPC, try from key:\n         group = parseGroupFrom(instance, Sets.newHashSet(instance.getKeyName()));\n      }\n      return group;\n   }\n\n   private String parseGroupFrom(final RunningInstance instance, final Set<String> data) {\n      String group = null;\n      try {\n         Predicate<String> containsAnyGroup = namingConvention.create().containsAnyGroup();\n         String encodedGroup = Iterables.getOnlyElement(Iterables.filter(data, containsAnyGroup));\n         group = namingConvention.create().extractGroup(encodedGroup);\n      } catch (NoSuchElementException e) {\n         logger.debug(\"no group parsed from %s's data: %s\", instance.getId(), data);\n      } catch (IllegalArgumentException e) {\n         logger.debug(\"too many groups match naming convention; %s's data: %s\", instance.getId(), data);\n      }\n      return group;\n   }\n\n   @VisibleForTesting\n   Hardware getHardwareForInstance(final RunningInstance instance) {\n      try {\n         return Iterables.find(hardware.get(), new Predicate<Hardware>() {\n\n            @Override\n            public boolean apply(Hardware input) {\n               return input.getId().equals(instance.getInstanceType());\n            }\n\n         });\n      } catch (NoSuchElementException e) {\n         logger.debug(\"couldn't match instance type %s in: %s\", instance.getInstanceType(), hardware.get());\n         return null;\n      }\n   }\n\n   private Location getLocationForAvailabilityZoneOrRegion(final RunningInstance instance) {\n      Location location = findLocationWithId(instance.getAvailabilityZone());\n      if (location == null)\n         location = findLocationWithId(instance.getRegion());\n      return location;\n   }\n\n   private Location findLocationWithId(final String locationId) {\n      if (locationId == null)\n         return null;\n      try {\n         Location location = Iterables.find(locations.get(), new Predicate<Location>() {\n\n            @Override\n            public boolean apply(Location input) {\n               return input.getId().equals(locationId);\n            }\n\n         });\n         return location;\n\n      } catch (NoSuchElementException e) {\n         logger.debug(\"couldn't match instance location %s in: %s\", locationId, locations.get());\n         return null;\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/functions/WindowsLoginCredentialsFromEncryptedData.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.functions;\n\nimport static com.google.common.io.BaseEncoding.base64;\n\nimport java.security.KeyFactory;\nimport java.security.PrivateKey;\nimport java.security.spec.KeySpec;\n\nimport javax.crypto.Cipher;\nimport jakarta.inject.Inject;\n\nimport org.jclouds.crypto.Crypto;\nimport org.jclouds.crypto.Pems;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.ec2.compute.domain.PasswordDataAndPrivateKey;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.base.Function;\nimport com.google.common.base.Throwables;\nimport com.google.inject.Singleton;\n\n/**\n * Given an encrypted Windows Administrator password and the decryption key, return a LoginCredentials instance.\n */\n@Singleton\npublic class WindowsLoginCredentialsFromEncryptedData implements Function<PasswordDataAndPrivateKey, LoginCredentials> {\n\n   private final Crypto crypto;\n\n   @Inject\n   public WindowsLoginCredentialsFromEncryptedData(Crypto crypto) {\n      this.crypto = crypto;\n   }\n\n   @Override\n   public LoginCredentials apply(@Nullable PasswordDataAndPrivateKey dataAndKey) {\n      if (dataAndKey == null)\n         return null;\n\n      try {\n         KeySpec keySpec = Pems.privateKeySpec(dataAndKey.getPrivateKey());\n         KeyFactory kf = crypto.rsaKeyFactory();\n         PrivateKey privKey = kf.generatePrivate(keySpec);\n\n         Cipher cipher = crypto.cipher(\"RSA\");\n         cipher.init(Cipher.DECRYPT_MODE, privKey);\n         byte[] cipherText = base64().decode(dataAndKey.getPasswordData().getPasswordData());\n         byte[] plainText = cipher.doFinal(cipherText);\n         String password = new String(plainText, Charsets.US_ASCII);\n\n         return LoginCredentials.builder()\n                                .user(\"Administrator\")\n                                .password(password)\n                                .noPrivateKey()\n                                .build();\n      } catch (Exception e) {\n         throw Throwables.propagate(e);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/internal/EC2ComputeServiceContextImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.internal;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Context;\nimport org.jclouds.compute.Utils;\nimport org.jclouds.compute.internal.ComputeServiceContextImpl;\nimport org.jclouds.ec2.compute.EC2ComputeService;\nimport org.jclouds.ec2.compute.EC2ComputeServiceContext;\nimport org.jclouds.location.Provider;\n\nimport com.google.common.reflect.TypeToken;\n\n@Singleton\npublic class EC2ComputeServiceContextImpl extends ComputeServiceContextImpl implements EC2ComputeServiceContext {\n   @Inject\n   public EC2ComputeServiceContextImpl(@Provider Context backend, @Provider TypeToken<? extends Context> backendType,\n            EC2ComputeService computeService, Utils utils) {\n      super(backend, backendType, computeService, utils);\n   }\n\n   @Override\n   public EC2ComputeService getComputeService() {\n      return EC2ComputeService.class.cast(super.getComputeService());\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/internal/EC2TemplateBuilderImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.internal;\n\nimport static com.google.common.base.Preconditions.checkArgument;\n\nimport java.util.NoSuchElementException;\nimport java.util.Set;\nimport java.util.concurrent.ExecutionException;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Provider;\n\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.TemplateBuilder;\nimport org.jclouds.compute.domain.internal.TemplateBuilderImpl;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.domain.Location;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.util.Throwables2;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.util.concurrent.UncheckedExecutionException;\n\npublic class EC2TemplateBuilderImpl extends TemplateBuilderImpl {\n\n   private final Supplier<LoadingCache<RegionAndName, ? extends Image>> lazyImageCache;\n\n   @Inject\n   protected EC2TemplateBuilderImpl(@Memoized Supplier<Set<? extends Location>> locations,\n         @Memoized Supplier<Set<? extends Image>> images, @Memoized Supplier<Set<? extends Hardware>> sizes,\n         Supplier<Location> defaultLocation, @Named(\"DEFAULT\") Provider<TemplateOptions> optionsProvider,\n         @Named(\"DEFAULT\") Provider<TemplateBuilder> defaultTemplateProvider,\n         Supplier<LoadingCache<RegionAndName, ? extends Image>> imageMap) {\n      super(locations, images, sizes, defaultLocation, optionsProvider, defaultTemplateProvider);\n      this.lazyImageCache = imageMap;\n   }\n\n   final Provider<Image> lazyImageProvider = new Provider<Image>() {\n\n      @Override\n      public Image get() {\n         if (imageId != null) {\n            String[] regionName = imageId.split(\"/\");\n            checkArgument(regionName.length == 2,\n                  \"amazon image ids must include the region ( ex. us-east-1/ami-7ea24a17 ) you specified: \" + imageId);\n            RegionAndName key = new RegionAndName(regionName[0], regionName[1]);\n            try {\n               return lazyImageCache.get().get(key);\n            } catch (ExecutionException e) {\n               throw new NoSuchElementException(String.format(\"could not get imageId(%s/%s)\", key.getRegion(), key.getName()));\n            } catch (UncheckedExecutionException e) {\n               // Primarily for testing: if cache is backed by a map, can get IllegalArgumentException instead of NPE\n               IllegalArgumentException e2 = Throwables2.getFirstThrowableOfType(e, IllegalArgumentException.class);\n               if (e2 != null && e2.getMessage() != null && e2.getMessage().contains(\"not present in\")) {\n                  throw new NoSuchElementException(String.format(\"imageId(%s/%s) not found\", key.getRegion(), key.getName()));\n               }\n               throw new NoSuchElementException(String.format(\"could not get imageId(%s/%s)\", key.getRegion(), key.getName()));\n            } catch (CacheLoader.InvalidCacheLoadException nex) {\n               throw new NoSuchElementException(String.format(\"imageId(%s/%s) not found\", key.getRegion(), key.getName()));\n            }\n         }\n         return null;\n      }\n\n   };\n\n   /**\n    * @throws NoSuchElementException\n    *            if the image is not found\n    */\n   @Override\n   protected Image resolveImage(Hardware size, Iterable<? extends Image> supportedImages) {\n      try {\n         return super.resolveImage(size, supportedImages);\n      } catch (NoSuchElementException e) {\n         Image returnVal = lazyImageProvider.get();\n         if (returnVal != null)\n            return returnVal;\n         throw e;\n      }\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   protected Set<? extends Image> getImages() {\n      if (imageId != null) {\n         Image image = lazyImageProvider.get();\n         return ImmutableSet.of(image);\n      } else {\n         return (Set<Image>) this.images.get();\n      }\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/loaders/CreateSecurityGroupIfNeeded.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.loaders;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.compute.domain.RegionNameAndIngressRules;\nimport org.jclouds.ec2.domain.UserIdGroupPair;\nimport org.jclouds.ec2.features.SecurityGroupApi;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.net.domain.IpProtocol;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.collect.Iterables;\n\n@Singleton\npublic class CreateSecurityGroupIfNeeded extends CacheLoader<RegionAndName, String> {\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n   protected final SecurityGroupApi securityClient;\n   protected final Predicate<RegionAndName> securityGroupEventualConsistencyDelay;\n\n   @Inject\n   public CreateSecurityGroupIfNeeded(EC2Api ec2Api,\n         @Named(\"SECURITY\") Predicate<RegionAndName> securityGroupEventualConsistencyDelay) {\n      this(checkNotNull(ec2Api, \"ec2Api\").getSecurityGroupApi().get(), securityGroupEventualConsistencyDelay);\n   }\n\n   public CreateSecurityGroupIfNeeded(SecurityGroupApi securityClient,\n         @Named(\"SECURITY\") Predicate<RegionAndName> securityGroupEventualConsistencyDelay) {\n      this.securityClient = checkNotNull(securityClient, \"securityClient\");\n      this.securityGroupEventualConsistencyDelay = checkNotNull(securityGroupEventualConsistencyDelay,\n            \"securityGroupEventualConsistencyDelay\");\n   }\n\n   @Override\n   public String load(RegionAndName from) {\n      RegionNameAndIngressRules realFrom = RegionNameAndIngressRules.class.cast(from);\n      createSecurityGroupInRegion(from.getRegion(), from.getName(), realFrom.getPorts());\n      return from.getName();\n   }\n\n   private void createSecurityGroupInRegion(String region, String name, int... ports) {\n      checkNotNull(region, \"region\");\n      checkNotNull(name, \"name\");\n      logger.debug(\">> creating securityGroup region(%s) name(%s)\", region, name);\n      try {\n         securityClient.createSecurityGroupInRegion(region, name, name);\n         boolean created = securityGroupEventualConsistencyDelay.apply(new RegionAndName(region, name));\n         if (!created)\n            throw new RuntimeException(String.format(\"security group %s/%s is not available after creating\", region,\n                  name));\n         logger.debug(\"<< created securityGroup(%s)\", name);\n         for (int port : ports) {\n            createIngressRuleForTCPPort(region, name, port);\n         }\n         if (ports.length > 0) {\n            authorizeGroupToItself(region, name);\n         }\n      } catch (IllegalStateException e) {\n         logger.debug(\"<< reused securityGroup(%s)\", name);\n      }\n   }\n\n   protected void createIngressRuleForTCPPort(String region, String name, int port) {\n      logger.debug(\">> authorizing securityGroup region(%s) name(%s) port(%s)\", region, name, port);\n      securityClient.authorizeSecurityGroupIngressInRegion(region, name, IpProtocol.TCP, port, port, \"0.0.0.0/0\");\n      logger.debug(\"<< authorized securityGroup(%s)\", name);\n   }\n\n   protected void authorizeGroupToItself(String region, String name) {\n      logger.debug(\">> authorizing securityGroup region(%s) name(%s) permission to itself\", region, name);\n      String myOwnerId = Iterables.get(securityClient.describeSecurityGroupsInRegion(region, name), 0).getOwnerId();\n      securityClient.authorizeSecurityGroupIngressInRegion(region, name, new UserIdGroupPair(myOwnerId, name));\n      logger.debug(\"<< authorized securityGroup(%s)\", name);\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/loaders/LoadAllocationIdForInstanceOrNull.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.loaders;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.collect.Iterables;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.domain.PublicIpInstanceIdPair;\n\nimport java.util.NoSuchElementException;\n\n@Singleton\npublic class LoadAllocationIdForInstanceOrNull extends CacheLoader<RegionAndName, String> {\n   private final EC2Api client;\n\n   @Inject\n   public LoadAllocationIdForInstanceOrNull(EC2Api client) {\n      this.client = client;\n   }\n\n   @Override\n   public String load(final RegionAndName key) throws Exception {\n      try {\n         return Iterables.find(client.getElasticIPAddressApi().get().describeAddressesInRegion(key.getRegion()),\n                  new Predicate<PublicIpInstanceIdPair>() {\n\n                     @Override\n                     public boolean apply(PublicIpInstanceIdPair input) {\n                        return key.getName().equals(input.getInstanceId());\n                     }\n\n                  }).getAllocationId();\n      } catch (NoSuchElementException e) {\n         return null;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/loaders/LoadPublicIpForInstanceOrNull.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.loaders;\n\nimport java.util.NoSuchElementException;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.domain.PublicIpInstanceIdPair;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.collect.Iterables;\n\n@Singleton\npublic class LoadPublicIpForInstanceOrNull extends CacheLoader<RegionAndName, String> {\n   private final EC2Api client;\n\n   @Inject\n   public LoadPublicIpForInstanceOrNull(EC2Api client) {\n      this.client = client;\n   }\n\n   @Override\n   public String load(final RegionAndName key) throws Exception {\n      try {\n         return Iterables.find(client.getElasticIPAddressApi().get().describeAddressesInRegion(key.getRegion()),\n                  new Predicate<PublicIpInstanceIdPair>() {\n\n                     @Override\n                     public boolean apply(PublicIpInstanceIdPair input) {\n                        return key.getName().equals(input.getInstanceId());\n                     }\n\n                  }).getPublicIp();\n      } catch (NoSuchElementException e) {\n         return null;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/loaders/RegionAndIdToImage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.loaders;\n\nimport static org.jclouds.ec2.options.DescribeImagesOptions.Builder.imageIds;\n\nimport java.util.concurrent.ExecutionException;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.compute.functions.EC2ImageParser;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.collect.Iterables;\n\n@Singleton\npublic class RegionAndIdToImage extends CacheLoader<RegionAndName, Image> {\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   private final EC2ImageParser parser;\n   private final EC2Api sync;\n\n   @Inject\n   public RegionAndIdToImage(EC2ImageParser parser, EC2Api sync) {\n      this.parser = parser;\n      this.sync = sync;\n   }\n\n   @Override\n   public Image load(RegionAndName key) throws ExecutionException {\n      try {\n         org.jclouds.ec2.domain.Image image = Iterables.getOnlyElement(sync.getAMIApi().get()\n               .describeImagesInRegion(key.getRegion(), imageIds(key.getName())));\n         return parser.apply(image);\n      } catch (Exception e) {\n         throw new ExecutionException(message(key, e), e);\n      }\n   }\n\n   public static String message(RegionAndName key, Exception e) {\n      return String.format(\"could not find image %s/%s: %s\", key.getRegion(), key.getName(), e.getMessage());\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/options/EC2TemplateOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.options;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.common.base.Strings.emptyToNull;\n\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.hash.Hashing;\nimport com.google.common.primitives.Bytes;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.ec2.domain.BlockDeviceMapping;\nimport org.jclouds.ec2.domain.BlockDeviceMapping.MapEBSSnapshotToDevice;\nimport org.jclouds.ec2.domain.BlockDeviceMapping.MapEphemeralDeviceToDevice;\nimport org.jclouds.ec2.domain.BlockDeviceMapping.MapNewVolumeToDevice;\nimport org.jclouds.ec2.domain.BlockDeviceMapping.UnmapDeviceNamed;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.scriptbuilder.domain.Statement;\n\n/**\n * Contains options supported in the {@code ComputeService#runNode} operation on\n * the \"ec2\" provider. <h2>\n * Usage</h2> The recommended way to instantiate a EC2TemplateOptions object is\n * to statically import EC2TemplateOptions.* and invoke a static creation method\n * followed by an instance mutator (if needed):\n * <p/>\n * <code>\n * import static org.jclouds.aws.ec2.compute.options.EC2TemplateOptions.Builder.*;\n * <p/>\n * ComputeService client = // get connection\n * templateBuilder.options(inboundPorts(22, 80, 8080, 443));\n * Set<? extends NodeMetadata> set = client.createNodesInGroup(tag, 2, templateBuilder.build());\n * <code>\n */\npublic class EC2TemplateOptions extends TemplateOptions implements Cloneable {\n   @Override\n   public EC2TemplateOptions clone() {\n      EC2TemplateOptions options = new EC2TemplateOptions();\n      copyTo(options);\n      return options;\n   }\n\n   @Override\n   public void copyTo(TemplateOptions to) {\n      super.copyTo(to);\n      if (to instanceof EC2TemplateOptions) {\n         EC2TemplateOptions eTo = EC2TemplateOptions.class.cast(to);\n         if (!getGroups().isEmpty())\n            eTo.securityGroups(getGroups());\n         if (getKeyPair() != null)\n            eTo.keyPair(getKeyPair());\n         if (!getBlockDeviceMappings().isEmpty())\n            eTo.blockDeviceMappings(getBlockDeviceMappings());\n         if (!shouldAutomaticallyCreateKeyPair())\n            eTo.noKeyPair();\n         if (getUserData() != null)\n            eTo.userData(getUserData());\n         if (getMaxCount() > 0)\n            eTo.maxCount(getMaxCount());\n         if (getClientToken() != null)\n            eTo.clientToken(getClientToken());\n      }\n   }\n\n   private Set<String> groupNames = ImmutableSet.of();\n   private String keyPair = null;\n   private boolean noKeyPair;\n   private List<Byte> userData;\n   private ImmutableSet.Builder<BlockDeviceMapping> blockDeviceMappings = ImmutableSet.builder();\n   private Integer maxCount;\n   private String clientToken = null;\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o)\n         return true;\n      if (o == null || getClass() != o.getClass())\n         return false;\n      EC2TemplateOptions that = EC2TemplateOptions.class.cast(o);\n      return super.equals(that) && equal(this.groupNames, that.groupNames) && equal(this.keyPair, that.keyPair)\n              && equal(this.noKeyPair, that.noKeyPair) && equal(this.userData, that.userData)\n              && equal(this.blockDeviceMappings.build(), that.blockDeviceMappings.build())\n              && equal(this.maxCount, that.maxCount)\n              && equal(this.clientToken, that.clientToken);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects\n               .hashCode(super.hashCode(), groupNames, keyPair, noKeyPair, userData, userData, blockDeviceMappings.build(),\n                       maxCount, clientToken);\n   }\n\n   @Override\n   public ToStringHelper string() {\n      ToStringHelper toString = super.string();\n      if (!groupNames.isEmpty())\n         toString.add(\"groupNames\", groupNames);\n      if (noKeyPair)\n         toString.add(\"noKeyPair\", noKeyPair);\n      toString.add(\"keyPair\", keyPair);\n      if (userData != null && !userData.isEmpty())\n         toString.add(\"userDataCksum\", Hashing.crc32().hashBytes(Bytes.toArray(userData)));\n      ImmutableSet<BlockDeviceMapping> mappings = blockDeviceMappings.build();\n      if (!mappings.isEmpty())\n         toString.add(\"blockDeviceMappings\", mappings);\n      if (maxCount != null && maxCount.intValue() > 0)\n         toString.add(\"maxCount\", maxCount);\n      if (clientToken != null)\n         toString.add(\"clientToken\", clientToken);\n      return toString;\n   }\n\n   public static final EC2TemplateOptions NONE = new EC2TemplateOptions();\n\n   /**\n    *\n    * @see EC2TemplateOptions#securityGroups(Iterable<String>)\n    */\n   public EC2TemplateOptions securityGroups(String... groupNames) {\n      return securityGroups(ImmutableSet.copyOf(groupNames));\n   }\n\n   /**\n    * Specifies the security groups to be used for nodes with this template\n    */\n   public EC2TemplateOptions securityGroups(Iterable<String> groupNames) {\n      checkArgument(!Iterables.isEmpty(groupNames), \"you must specify at least one security group\");\n      for (String groupId : groupNames)\n         checkNotNull(emptyToNull(groupId), \"all security groups must be non-empty\");\n      this.groupNames = ImmutableSet.copyOf(groupNames);\n      return this;\n   }\n\n   /**\n    * Unencoded data\n    */\n   public EC2TemplateOptions userData(byte[] unencodedData) {\n      checkArgument(checkNotNull(unencodedData, \"unencodedData\").length <= 16 * 1024,\n            \"userData cannot be larger than 16kb\");\n      this.userData = Bytes.asList(unencodedData);\n      return this;\n   }\n\n   /**\n    * Specifies the keypair used to run instances with\n    */\n   public EC2TemplateOptions keyPair(String keyPair) {\n      checkState(!noKeyPair, \"you cannot specify both options keyPair and noKeyPair\");\n      this.keyPair = checkNotNull(emptyToNull(keyPair), \"use noKeyPair option to request boot without a keypair\");\n      return this;\n   }\n\n   /**\n    * Do not use a keypair on instances\n    */\n   public EC2TemplateOptions noKeyPair() {\n      checkState(keyPair == null, \"you cannot specify both options keyPair and noKeyPair\");\n      this.noKeyPair = true;\n      return this;\n   }\n\n   public EC2TemplateOptions mapEBSSnapshotToDeviceName(String deviceName, String snapshotId,\n         @Nullable Integer sizeInGib, boolean deleteOnTermination) {\n      return mapEBSSnapshotToDeviceName(deviceName, snapshotId, sizeInGib, deleteOnTermination, null, null, false);\n   }\n\n   public EC2TemplateOptions mapEBSSnapshotToDeviceName(String deviceName, String snapshotId,\n                                                        @Nullable Integer sizeInGib, boolean deleteOnTermination,\n                                                        @Nullable String volumeType, @Nullable Integer iops,\n                                                        boolean encrypted) {\n      blockDeviceMappings.add(new MapEBSSnapshotToDevice(deviceName, snapshotId, sizeInGib, deleteOnTermination,\n              volumeType, iops, encrypted));\n      return this;\n   }\n\n   public EC2TemplateOptions mapNewVolumeToDeviceName(String deviceName, int sizeInGib, boolean deleteOnTermination) {\n      return mapNewVolumeToDeviceName(deviceName, sizeInGib, deleteOnTermination, null, null, false);\n   }\n\n   public EC2TemplateOptions mapNewVolumeToDeviceName(String deviceName, int sizeInGib, boolean deleteOnTermination,\n                                                      @Nullable String volumeType, @Nullable Integer iops,\n                                                      boolean encrypted) {\n      blockDeviceMappings.add(new MapNewVolumeToDevice(deviceName, sizeInGib, deleteOnTermination, volumeType,\n              iops, encrypted));\n      return this;\n   }\n\n   public EC2TemplateOptions mapEphemeralDeviceToDeviceName(String deviceName, String virtualName) {\n      blockDeviceMappings.add(new MapEphemeralDeviceToDevice(deviceName, virtualName));\n      return this;\n   }\n\n   public EC2TemplateOptions unmapDeviceNamed(String deviceName) {\n      blockDeviceMappings.add(new UnmapDeviceNamed(deviceName));\n      return this;\n   }\n\n   public EC2TemplateOptions blockDeviceMappings(Iterable<? extends BlockDeviceMapping> blockDeviceMappings) {\n      this.blockDeviceMappings.addAll(checkNotNull(blockDeviceMappings, \"blockDeviceMappings\"));\n      return this;\n   }\n\n   public EC2TemplateOptions maxCount(Integer maxCount) {\n      this.maxCount = maxCount;\n      return this;\n   }\n\n   public EC2TemplateOptions clientToken(String clientToken) {\n      this.clientToken = checkNotNull(clientToken, \"clientToken\");\n      return this;\n   }\n\n   public static class Builder extends TemplateOptions.Builder {\n      /**\n       * @see EC2TemplateOptions#blockDeviceMappings\n       */\n      public static EC2TemplateOptions blockDeviceMappings(Set<? extends BlockDeviceMapping> blockDeviceMappings) {\n         EC2TemplateOptions options = new EC2TemplateOptions();\n         return options.blockDeviceMappings(blockDeviceMappings);\n      }\n\n      /**\n       * @see EC2TemplateOptions#mapEBSSnapshotToDeviceName\n       */\n      public static EC2TemplateOptions mapEBSSnapshotToDeviceName(String deviceName, String snapshotId,\n            @Nullable Integer sizeInGib, boolean deleteOnTermination) {\n         EC2TemplateOptions options = new EC2TemplateOptions();\n         return options.mapEBSSnapshotToDeviceName(deviceName, snapshotId, sizeInGib, deleteOnTermination);\n      }\n\n      /**\n       * @see EC2TemplateOptions#mapNewVolumeToDeviceName\n       */\n      public static EC2TemplateOptions mapNewVolumeToDeviceName(String deviceName, int sizeInGib,\n            boolean deleteOnTermination) {\n         EC2TemplateOptions options = new EC2TemplateOptions();\n         return options.mapNewVolumeToDeviceName(deviceName, sizeInGib, deleteOnTermination);\n      }\n\n      /**\n       * @see EC2TemplateOptions#mapEphemeralDeviceToDeviceName\n       */\n      public static EC2TemplateOptions mapEphemeralDeviceToDeviceName(String deviceName, String virtualName) {\n         EC2TemplateOptions options = new EC2TemplateOptions();\n         return options.mapEphemeralDeviceToDeviceName(deviceName, virtualName);\n      }\n\n      /**\n       * @see EC2TemplateOptions#unmapDeviceNamed\n       */\n      public static EC2TemplateOptions unmapDeviceNamed(String deviceName) {\n         EC2TemplateOptions options = new EC2TemplateOptions();\n         return options.unmapDeviceNamed(deviceName);\n      }\n\n      /**\n       * @see EC2TemplateOptions#securityGroups(Iterable<String>)\n       */\n      public static EC2TemplateOptions securityGroups(String... groupNames) {\n         EC2TemplateOptions options = new EC2TemplateOptions();\n         return EC2TemplateOptions.class.cast(options.securityGroups(groupNames));\n      }\n\n      /**\n       * @see EC2TemplateOptions#securityGroups(Iterable<String>)\n       */\n      public static EC2TemplateOptions securityGroups(Iterable<String> groupNames) {\n         EC2TemplateOptions options = new EC2TemplateOptions();\n         return EC2TemplateOptions.class.cast(options.securityGroups(groupNames));\n      }\n\n      /**\n       * @see EC2TemplateOptions#keyPair\n       */\n      public static EC2TemplateOptions keyPair(String keyPair) {\n         EC2TemplateOptions options = new EC2TemplateOptions();\n         return EC2TemplateOptions.class.cast(options.keyPair(keyPair));\n      }\n\n      /**\n       * @see EC2TemplateOptions#userData\n       */\n      public static EC2TemplateOptions userData(byte[] unencodedData) {\n         EC2TemplateOptions options = new EC2TemplateOptions();\n         return EC2TemplateOptions.class.cast(options.userData(unencodedData));\n      }\n\n      /**\n       * @see EC2TemplateOptions#noKeyPair\n       */\n      public static EC2TemplateOptions noKeyPair() {\n         EC2TemplateOptions options = new EC2TemplateOptions();\n         return EC2TemplateOptions.class.cast(options.noKeyPair());\n      }\n\n      // methods that only facilitate returning the correct object type\n      /**\n       * @see TemplateOptions#inboundPorts\n       */\n      public static EC2TemplateOptions inboundPorts(int... ports) {\n         EC2TemplateOptions options = new EC2TemplateOptions();\n         return EC2TemplateOptions.class.cast(options.inboundPorts(ports));\n      }\n\n      /**\n       * @see TemplateOptions#port\n       */\n      public static EC2TemplateOptions blockOnPort(int port, int seconds) {\n         EC2TemplateOptions options = new EC2TemplateOptions();\n         return EC2TemplateOptions.class.cast(options.blockOnPort(port, seconds));\n      }\n\n      /**\n       * @see TemplateOptions#installPrivateKey\n       */\n      public static EC2TemplateOptions installPrivateKey(String rsaKey) {\n         EC2TemplateOptions options = new EC2TemplateOptions();\n         return EC2TemplateOptions.class.cast(options.installPrivateKey(rsaKey));\n      }\n\n      /**\n       * @see TemplateOptions#authorizePublicKey\n       */\n      public static EC2TemplateOptions authorizePublicKey(String rsaKey) {\n         EC2TemplateOptions options = new EC2TemplateOptions();\n         return EC2TemplateOptions.class.cast(options.authorizePublicKey(rsaKey));\n      }\n\n      /**\n       * @see TemplateOptions#userMetadata(Map)\n       */\n      public static EC2TemplateOptions userMetadata(Map<String, String> userMetadata) {\n         EC2TemplateOptions options = new EC2TemplateOptions();\n         return EC2TemplateOptions.class.cast(options.userMetadata(userMetadata));\n      }\n\n      /**\n       * @see TemplateOptions#nodeNames(Iterable)\n       */\n      public static EC2TemplateOptions nodeNames(Iterable<String> nodeNames) {\n         EC2TemplateOptions options = new EC2TemplateOptions();\n         return EC2TemplateOptions.class.cast(options.nodeNames(nodeNames));\n      }\n\n      /**\n       * @see TemplateOptions#networks(Iterable)\n       */\n      public static EC2TemplateOptions networks(Iterable<String> networks) {\n         EC2TemplateOptions options = new EC2TemplateOptions();\n         return EC2TemplateOptions.class.cast(options.networks(networks));\n      }\n\n      public static EC2TemplateOptions overrideLoginUser(String user) {\n         EC2TemplateOptions options = new EC2TemplateOptions();\n         return options.overrideLoginUser(user);\n      }\n\n      public static EC2TemplateOptions overrideLoginPassword(String password) {\n         EC2TemplateOptions options = new EC2TemplateOptions();\n         return options.overrideLoginPassword(password);\n      }\n\n      public static EC2TemplateOptions overrideLoginPrivateKey(String privateKey) {\n         EC2TemplateOptions options = new EC2TemplateOptions();\n         return options.overrideLoginPrivateKey(privateKey);\n      }\n\n      public static EC2TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo) {\n         EC2TemplateOptions options = new EC2TemplateOptions();\n         return options.overrideAuthenticateSudo(authenticateSudo);\n      }\n\n      public static EC2TemplateOptions overrideLoginCredentials(LoginCredentials credentials) {\n         EC2TemplateOptions options = new EC2TemplateOptions();\n         return options.overrideLoginCredentials(credentials);\n      }\n\n      public static EC2TemplateOptions nameTask(String name) {\n         EC2TemplateOptions options = new EC2TemplateOptions();\n         return options.nameTask(name);\n      }\n\n      public static EC2TemplateOptions runAsRoot(boolean value) {\n         EC2TemplateOptions options = new EC2TemplateOptions();\n         return options.runAsRoot(value);\n      }\n\n      public static EC2TemplateOptions tags(Iterable<String> tags) {\n         EC2TemplateOptions options = new EC2TemplateOptions();\n         return options.tags(tags);\n      }\n\n      public static EC2TemplateOptions blockUntilRunning(boolean blockUntilRunning) {\n         EC2TemplateOptions options = new EC2TemplateOptions();\n         return options.blockUntilRunning(blockUntilRunning);\n      }\n\n      public static EC2TemplateOptions runScript(Statement script) {\n         EC2TemplateOptions options = new EC2TemplateOptions();\n         return options.runScript(script);\n      }\n\n      public static EC2TemplateOptions runScript(String script) {\n         EC2TemplateOptions options = new EC2TemplateOptions();\n         return options.runScript(script);\n      }\n\n      public static EC2TemplateOptions userMetadata(String key, String value) {\n         EC2TemplateOptions options = new EC2TemplateOptions();\n         return options.userMetadata(key, value);\n      }\n\n      public static EC2TemplateOptions blockOnComplete(boolean value) {\n         EC2TemplateOptions options = new EC2TemplateOptions();\n         return options.blockOnComplete(value);\n      }\n\n      public static EC2TemplateOptions maxCount(Integer maxCount) {\n         EC2TemplateOptions options = new EC2TemplateOptions();\n         return options.maxCount(maxCount);\n      }\n\n      public static EC2TemplateOptions clientToken(String clientToken) {\n         EC2TemplateOptions options = new EC2TemplateOptions();\n         return options.clientToken(clientToken);\n      }\n   }\n\n   // methods that only facilitate returning the correct object type\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public EC2TemplateOptions blockOnPort(int port, int seconds) {\n      return EC2TemplateOptions.class.cast(super.blockOnPort(port, seconds));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public EC2TemplateOptions inboundPorts(int... ports) {\n      return EC2TemplateOptions.class.cast(super.inboundPorts(ports));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public EC2TemplateOptions authorizePublicKey(String publicKey) {\n      return EC2TemplateOptions.class.cast(super.authorizePublicKey(publicKey));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public EC2TemplateOptions installPrivateKey(String privateKey) {\n      return EC2TemplateOptions.class.cast(super.installPrivateKey(privateKey));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public EC2TemplateOptions blockUntilRunning(boolean blockUntilRunning) {\n      return EC2TemplateOptions.class.cast(super.blockUntilRunning(blockUntilRunning));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public EC2TemplateOptions dontAuthorizePublicKey() {\n      return EC2TemplateOptions.class.cast(super.dontAuthorizePublicKey());\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public EC2TemplateOptions nameTask(String name) {\n      return EC2TemplateOptions.class.cast(super.nameTask(name));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public EC2TemplateOptions runAsRoot(boolean runAsRoot) {\n      return EC2TemplateOptions.class.cast(super.runAsRoot(runAsRoot));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public EC2TemplateOptions runScript(Statement script) {\n      return EC2TemplateOptions.class.cast(super.runScript(script));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public EC2TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials) {\n      return EC2TemplateOptions.class.cast(super.overrideLoginCredentials(overridingCredentials));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public EC2TemplateOptions overrideLoginPassword(String password) {\n      return EC2TemplateOptions.class.cast(super.overrideLoginPassword(password));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public EC2TemplateOptions overrideLoginPrivateKey(String privateKey) {\n      return EC2TemplateOptions.class.cast(super.overrideLoginPrivateKey(privateKey));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public EC2TemplateOptions overrideLoginUser(String loginUser) {\n      return EC2TemplateOptions.class.cast(super.overrideLoginUser(loginUser));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public EC2TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo) {\n      return EC2TemplateOptions.class.cast(super.overrideAuthenticateSudo(authenticateSudo));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public EC2TemplateOptions userMetadata(Map<String, String> userMetadata) {\n      return EC2TemplateOptions.class.cast(super.userMetadata(userMetadata));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public EC2TemplateOptions userMetadata(String key, String value) {\n      return EC2TemplateOptions.class.cast(super.userMetadata(key, value));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public EC2TemplateOptions nodeNames(Iterable<String> nodeNames) {\n      return EC2TemplateOptions.class.cast(super.nodeNames(nodeNames));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public EC2TemplateOptions networks(Iterable<String> networks) {\n      return EC2TemplateOptions.class.cast(super.networks(networks));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public EC2TemplateOptions runScript(String script) {\n      return EC2TemplateOptions.class.cast(super.runScript(script));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public EC2TemplateOptions tags(Iterable<String> tags) {\n      return EC2TemplateOptions.class.cast(super.tags(tags));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public EC2TemplateOptions wrapInInitScript(boolean wrapInInitScript) {\n      return EC2TemplateOptions.class.cast(super.wrapInInitScript(wrapInInitScript));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public EC2TemplateOptions blockOnComplete(boolean blockOnComplete) {\n      return EC2TemplateOptions.class.cast(super.blockOnComplete(blockOnComplete));\n   }\n\n   /**\n    * @return groupNames the user specified to run instances with, or zero\n    *         length set to create an implicit group\n    */\n   public Set<String> getGroups() {\n      return groupNames;\n   }\n\n   /**\n    * @return keyPair to use when running the instance or null, to generate a\n    *         keypair.\n    */\n   public String getKeyPair() {\n      return keyPair;\n   }\n\n   /**\n    * @return true (default) if we are supposed to use a keypair\n    */\n   public boolean shouldAutomaticallyCreateKeyPair() {\n      return !noKeyPair;\n   }\n\n   /**\n    * @return unencoded user data.\n    */\n   public byte[] getUserData() {\n      return userData == null ? null : Bytes.toArray(userData);\n   }\n\n   /**\n    * @return BlockDeviceMapping to use when running the instance or null.\n    */\n   public Set<BlockDeviceMapping> getBlockDeviceMappings() {\n      return blockDeviceMappings.build();\n   }\n\n   /**\n    * @return the maximum number of instances to create\n    */\n   public int getMaxCount() {\n      return maxCount != null ? maxCount.intValue() : 0;\n   }\n\n   /**\n    * See <a href=\"http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Run_Instance_Idempotency.html\">here</a> for more information.\n    *\n    * @return the optional client token string, used for idempotency\n    */\n   public String getClientToken() {\n      return clientToken;\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/predicates/EC2ImagePredicates.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.predicates.ImagePredicates;\nimport org.jclouds.ec2.domain.RootDeviceType;\n\nimport com.google.common.base.Predicate;\n\n/**\n * Container for image filters (predicates).\n * \n * This class has static methods that create customized predicates to use with\n * {@link org.jclouds.compute.ComputeService}.\n */\npublic class EC2ImagePredicates {\n\n   /**\n    * evaluates true if the Image has the specified root device type\n    * \n    * @param rootDeviceType\n    *           rootDeviceType of the images\n    * @return predicate\n    */\n   public static Predicate<Image> rootDeviceType(final RootDeviceType rootDeviceType) {\n      checkNotNull(rootDeviceType, \"rootDeviceType must be defined\");\n      return ImagePredicates.userMetadataContains(\"rootDeviceType\", rootDeviceType.value());\n   }\n\n  \n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/predicates/SecurityGroupPresent.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.NoSuchElementException;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.domain.SecurityGroup;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.rest.ResourceNotFoundException;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.Iterables;\nimport com.google.inject.Inject;\n\n@Singleton\npublic class SecurityGroupPresent implements Predicate<RegionAndName> {\n\n   private final EC2Api client;\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   @Inject\n   public SecurityGroupPresent(EC2Api client) {\n      this.client = checkNotNull(client, \"client\");\n   }\n\n   public boolean apply(RegionAndName securityGroup) {\n      logger.trace(\"looking for security group %s/%s\", securityGroup.getRegion(), securityGroup.getName());\n      try {\n         return refresh(securityGroup) != null;\n      } catch (ResourceNotFoundException e) {\n         return false;\n      } catch (NoSuchElementException e) {\n         return false;\n      }\n   }\n\n   protected SecurityGroup refresh(final RegionAndName securityGroup) {\n      return Iterables.getOnlyElement(client.getSecurityGroupApi().get().describeSecurityGroupsInRegionWithFilter(securityGroup.getRegion(),\n              ImmutableMultimap.of(\"group-name\", securityGroup.getName())));\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/strategy/CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.strategy;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static org.jclouds.ssh.SshKeys.fingerprintPrivateKey;\nimport static org.jclouds.ssh.SshKeys.sha1PrivateKey;\n\nimport jakarta.inject.Named;\nimport jakarta.inject.Provider;\nimport jakarta.inject.Singleton;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentMap;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Function;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\nimport com.google.inject.Inject;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.compute.functions.GroupNamingConvention.Factory;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.compute.domain.RegionNameAndIngressRules;\nimport org.jclouds.ec2.compute.options.EC2TemplateOptions;\nimport org.jclouds.ec2.domain.BlockDeviceMapping;\nimport org.jclouds.ec2.domain.KeyPair;\nimport org.jclouds.ec2.options.RunInstancesOptions;\nimport org.jclouds.javax.annotation.Nullable;\n\n@Singleton\npublic class CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions {\n   @VisibleForTesting\n   public Function<RegionAndName, KeyPair> makeKeyPair;\n   @VisibleForTesting\n   public final ConcurrentMap<RegionAndName, KeyPair> credentialsMap;\n   @VisibleForTesting\n   public final LoadingCache<RegionAndName, String> securityGroupMap;\n   @VisibleForTesting\n   public final Provider<RunInstancesOptions> optionsProvider;\n   private final Factory namingConvention;\n\n   @Inject\n   public CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions(Function<RegionAndName, KeyPair> makeKeyPair,\n            ConcurrentMap<RegionAndName, KeyPair> credentialsMap,\n            @Named(\"SECURITY\") LoadingCache<RegionAndName, String> securityGroupMap,\n            Provider<RunInstancesOptions> optionsProvider,\n            GroupNamingConvention.Factory namingConvention) {\n      this.makeKeyPair = checkNotNull(makeKeyPair, \"makeKeyPair\");\n      this.credentialsMap = checkNotNull(credentialsMap, \"credentialsMap\");\n      this.securityGroupMap = checkNotNull(securityGroupMap, \"securityGroupMap\");\n      this.optionsProvider = checkNotNull(optionsProvider, \"optionsProvider\");\n      this.namingConvention = checkNotNull(namingConvention, \"namingConvention\");\n   }\n\n   public RunInstancesOptions execute(String region, String group, Template template) {\n\n      RunInstancesOptions instanceOptions = getOptionsProvider().get().asType(template.getHardware().getId());\n\n      String keyPairName = createNewKeyPairUnlessUserSpecifiedOtherwise(region, group, template.getOptions());\n\n      addSecurityGroups(region, group, template, instanceOptions);\n      if (template.getOptions() instanceof EC2TemplateOptions) {\n\n         if (keyPairName != null)\n            instanceOptions.withKeyName(keyPairName);\n\n         byte[] userData = EC2TemplateOptions.class.cast(template.getOptions()).getUserData();\n\n         if (userData != null)\n            instanceOptions.withUserData(userData);\n\n         Set<BlockDeviceMapping> blockDeviceMappings = EC2TemplateOptions.class.cast(template.getOptions())\n                  .getBlockDeviceMappings();\n         if (!blockDeviceMappings.isEmpty()) {\n            checkState(\"ebs\".equals(template.getImage().getUserMetadata().get(\"rootDeviceType\")),\n                     \"BlockDeviceMapping only available on ebs boot\");\n            instanceOptions.withBlockDeviceMappings(blockDeviceMappings);\n         }\n\n         String clientToken = EC2TemplateOptions.class.cast(template.getOptions()).getClientToken();\n\n         if (clientToken != null) {\n            instanceOptions.withClientToken(clientToken);\n         }\n      }\n      return instanceOptions;\n   }\n\n   protected void addSecurityGroups(String region, String group, Template template, RunInstancesOptions instanceOptions) {\n      Set<String> groups = getSecurityGroupsForTagAndOptions(region, group, null, template.getOptions());\n      instanceOptions.withSecurityGroups(groups);\n   }\n\n   @VisibleForTesting\n   public String createNewKeyPairUnlessUserSpecifiedOtherwise(String region, String group, TemplateOptions options) {\n      String keyPairName = null;\n      boolean shouldAutomaticallyCreateKeyPair = true;\n\n      if (options instanceof EC2TemplateOptions) {\n         keyPairName = EC2TemplateOptions.class.cast(options).getKeyPair();\n         if (keyPairName == null)\n            shouldAutomaticallyCreateKeyPair = EC2TemplateOptions.class.cast(options)\n                     .shouldAutomaticallyCreateKeyPair();\n      }\n\n      if (keyPairName == null && shouldAutomaticallyCreateKeyPair) {\n         keyPairName = createOrImportKeyPair(region, group, options);\n      } else if (keyPairName != null) {\n         if (options.getLoginPrivateKey() != null) {\n            String pem = options.getLoginPrivateKey();\n            KeyPair keyPair = KeyPair.builder().region(region).keyName(keyPairName).fingerprint(\n                     fingerprintPrivateKey(pem)).sha1OfPrivateKey(sha1PrivateKey(pem)).keyMaterial(pem).build();\n            RegionAndName key = new RegionAndName(region, keyPairName);\n            credentialsMap.put(key, keyPair);\n         }\n      }\n\n      if (options.getRunScript() != null) {\n         RegionAndName regionAndName = new RegionAndName(region, keyPairName);\n         checkArgument(\n                  credentialsMap.containsKey(regionAndName),\n                  \"no private key configured for: %s; please use options.overrideLoginCredentialWith(rsa_private_text)\",\n                  regionAndName);\n      }\n      return keyPairName;\n   }\n\n   // base EC2 driver currently does not support key import\n   protected String createOrImportKeyPair(String region, String group, TemplateOptions options) {\n      RegionAndName regionAndGroup = new RegionAndName(region, group);\n      KeyPair keyPair = makeKeyPair.apply(new RegionAndName(region, group));\n      // make sure that we don't request multiple keys simultaneously\n      // if there is already a keypair for the group specified, use it\n      // otherwise create a new keypair and key it under the group and also the regular keyname\n      KeyPair origValue = credentialsMap.putIfAbsent(regionAndGroup, keyPair);\n      if (origValue != null) {\n         return origValue.getKeyName();\n      }\n\n      credentialsMap.put(new RegionAndName(region, keyPair.getKeyName()), keyPair);\n      return keyPair.getKeyName();\n   }\n\n   @VisibleForTesting\n   public Set<String> getSecurityGroupsForTagAndOptions(String region, @Nullable String group, @Nullable String vpcId, TemplateOptions options) {\n      Builder<String> groups = ImmutableSet.builder();\n\n      if (group != null) {\n         String markerGroup = namingConvention.create().sharedNameForGroup(group);\n\n         if (userSpecifiedTheirOwnGroups(options)) {\n            groups.addAll(EC2TemplateOptions.class.cast(options).getGroups());\n         } else {\n            RegionNameAndIngressRules regionNameAndIngressRulesForMarkerGroup = new RegionNameAndIngressRules(region, markerGroup, options\n                     .getInboundPorts(), true, vpcId);\n            // this will create if not yet exists.\n            groups.add(securityGroupMap.getUnchecked(regionNameAndIngressRulesForMarkerGroup));\n         }\n      }\n\n      return groups.build();\n   }\n\n   protected boolean userSpecifiedTheirOwnGroups(TemplateOptions options) {\n      return options instanceof EC2TemplateOptions && !EC2TemplateOptions.class.cast(options).getGroups().isEmpty();\n   }\n\n   // allows us to mock this method\n   @VisibleForTesting\n   public jakarta.inject.Provider<RunInstancesOptions> getOptionsProvider() {\n      return optionsProvider;\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/strategy/DescribeImagesParallel.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.strategy;\n\nimport static com.google.common.collect.Iterables.concat;\nimport static com.google.common.collect.Iterables.transform;\nimport static com.google.common.util.concurrent.Futures.allAsList;\nimport static com.google.common.util.concurrent.Futures.getUnchecked;\n\nimport java.util.List;\nimport java.util.Map.Entry;\nimport java.util.Set;\nimport java.util.concurrent.Callable;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Constants;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.options.DescribeImagesOptions;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Function;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.ListeningExecutorService;\n\n@Singleton\npublic class DescribeImagesParallel implements\n         Function<Iterable<Entry<String, DescribeImagesOptions>>, Iterable<? extends org.jclouds.ec2.domain.Image>> {\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   protected final EC2Api api;\n   final ListeningExecutorService userExecutor;\n\n   @Inject\n   public DescribeImagesParallel(EC2Api api, @Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor) {\n      this.api = api;\n      this.userExecutor = userExecutor;\n   }\n\n   @Override\n   public Iterable<? extends org.jclouds.ec2.domain.Image> apply(\n            final Iterable<Entry<String, DescribeImagesOptions>> queries) {\n      ListenableFuture<List<Set<? extends org.jclouds.ec2.domain.Image>>> futures\n         = allAsList(transform(\n                            queries,\n                            new Function<Entry<String, DescribeImagesOptions>,\n                            ListenableFuture<? extends Set<? extends org.jclouds.ec2.domain.Image>>>() {\n                               public ListenableFuture<Set<? extends org.jclouds.ec2.domain.Image>> apply(\n                                                                                                          final Entry<String, DescribeImagesOptions> from) {\n                                  return userExecutor.submit(new Callable<Set<? extends org.jclouds.ec2.domain.Image>>() {\n                                        @Override\n                                        public Set<? extends org.jclouds.ec2.domain.Image> call() throws Exception {\n                                           return api.getAMIApi().get().describeImagesInRegion(from.getKey(), from.getValue());\n                                        }\n                                     });\n                               }\n                            }));\n      logger.trace(\"amis\");\n\n      return concat(getUnchecked(futures));\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/strategy/EC2CreateNodesInGroupThenAddToSet.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.strategy;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.concat;\nimport static com.google.common.collect.Iterables.size;\nimport static com.google.common.collect.Iterables.transform;\nimport static com.google.common.collect.Sets.difference;\nimport static com.google.common.util.concurrent.Atomics.newReference;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_RUNNING;\nimport static org.jclouds.compute.functions.DefaultCredentialsFromImageOrOverridingCredentials.overrideDefaultCredentialsWithOptionsIfPresent;\nimport static org.jclouds.ec2.compute.util.EC2ComputeUtils.getZoneFromLocationOrNull;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Maps;\nimport com.google.common.collect.Multimap;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.compute.config.CustomizationResponse;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.compute.strategy.CreateNodesInGroupThenAddToSet;\nimport org.jclouds.compute.util.ComputeUtils;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.compute.functions.PresentInstances;\nimport org.jclouds.ec2.compute.options.EC2TemplateOptions;\nimport org.jclouds.ec2.domain.RunningInstance;\nimport org.jclouds.ec2.options.RunInstancesOptions;\nimport org.jclouds.ec2.reference.EC2Constants;\nimport org.jclouds.logging.Logger;\n\n/**\n * creates futures that correlate to\n */\n@Singleton\npublic class EC2CreateNodesInGroupThenAddToSet implements CreateNodesInGroupThenAddToSet {\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   @Inject\n   @Named(EC2Constants.PROPERTY_EC2_AUTO_ALLOCATE_ELASTIC_IPS)\n   @VisibleForTesting\n   boolean autoAllocateElasticIps = false;\n\n   @VisibleForTesting\n   final EC2Api client;\n   @VisibleForTesting\n   final Predicate<AtomicReference<NodeMetadata>> nodeRunning;\n   @VisibleForTesting\n   final LoadingCache<RegionAndName, String> elasticIpCache;\n   @VisibleForTesting\n   final CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions createKeyPairAndSecurityGroupsAsNeededAndReturncustomize;\n   @VisibleForTesting\n   final Function<RunningInstance, NodeMetadata> runningInstanceToNodeMetadata;\n   @VisibleForTesting\n   final ComputeUtils utils;\n   final PresentInstances presentInstances;\n   final LoadingCache<RunningInstance, Optional<LoginCredentials>> instanceToCredentials;\n   final Map<String, Credentials> credentialStore;\n\n   @Inject\n   protected EC2CreateNodesInGroupThenAddToSet(\n         EC2Api client,\n         @Named(\"ELASTICIP\") LoadingCache<RegionAndName, String> elasticIpCache,\n         @Named(TIMEOUT_NODE_RUNNING) Predicate<AtomicReference<NodeMetadata>> nodeRunning,\n         CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions createKeyPairAndSecurityGroupsAsNeededAndReturncustomize,\n         PresentInstances presentInstances, Function<RunningInstance, NodeMetadata> runningInstanceToNodeMetadata,\n         LoadingCache<RunningInstance, Optional<LoginCredentials>> instanceToCredentials,\n         Map<String, Credentials> credentialStore, ComputeUtils utils) {\n      this.client = checkNotNull(client, \"client\");\n      this.elasticIpCache = checkNotNull(elasticIpCache, \"elasticIpCache\");\n      this.nodeRunning = checkNotNull(nodeRunning, \"nodeRunning\");\n      this.presentInstances = checkNotNull(presentInstances, \"presentInstances\");\n      this.createKeyPairAndSecurityGroupsAsNeededAndReturncustomize = checkNotNull(\n            createKeyPairAndSecurityGroupsAsNeededAndReturncustomize,\n            \"createKeyPairAndSecurityGroupsAsNeededAndReturncustomize\");\n      this.runningInstanceToNodeMetadata = checkNotNull(runningInstanceToNodeMetadata, \"runningInstanceToNodeMetadata\");\n      this.instanceToCredentials = checkNotNull(instanceToCredentials, \"instanceToCredentials\");\n      this.credentialStore = checkNotNull(credentialStore, \"credentialStore\");\n      this.utils = checkNotNull(utils, \"utils\");\n   }\n\n   public static final Function<RunningInstance, RegionAndName> instanceToRegionAndName = new Function<RunningInstance, RegionAndName>() {\n      @Override\n      public RegionAndName apply(RunningInstance from) {\n         return new RegionAndName(from.getRegion(), from.getId());\n      }\n   };\n\n   @Override\n   public Map<?, ListenableFuture<Void>> execute(String group, int count, Template template, Set<NodeMetadata> goodNodes,\n         Map<NodeMetadata, Exception> badNodes, Multimap<NodeMetadata, CustomizationResponse> customizationResponses) {\n\n      Template mutableTemplate = template.clone();\n\n      Set<RunningInstance> started = runInstancesAndWarnOnInvisible(group, count, mutableTemplate);\n      if (started.isEmpty()) {\n         logger.warn(\"<< unable to start instances(%s)\", mutableTemplate);\n         return ImmutableMap.of();\n      }\n      populateCredentials(started, template.getOptions());\n\n      if (autoAllocateElasticIps) // before customization as the elastic ips may be needed\n         blockUntilRunningAndAssignElasticIpsToInstancesOrPutIntoBadMap(started, badNodes);\n\n      return utils.customizeNodesAndAddToGoodMapOrPutExceptionIntoBadMap(mutableTemplate.getOptions(),\n            transform(started, runningInstanceToNodeMetadata), goodNodes, badNodes, customizationResponses);\n   }\n\n   /**\n    * attempts to start the specified count of instances. eventual consistency might cause a problem where instances\n    * aren't immediately visible to the api. This method will warn when that occurs.\n    */\n   private Set<RunningInstance> runInstancesAndWarnOnInvisible(String group, int count, Template mutableTemplate) {\n      Set<RunningInstance> started = createKeyPairAndSecurityGroupsAsNeededThenRunInstances(group, count,\n            mutableTemplate);\n      Set<RegionAndName> startedIds = ImmutableSet.copyOf(transform(started, instanceToRegionAndName));\n      if (startedIds.isEmpty()) {\n         return ImmutableSet.copyOf(started);\n      }\n      logger.debug(\"<< started instances(%s)\", startedIds);\n      Set<RunningInstance> visible = presentInstances.apply(startedIds);\n      Set<RegionAndName> visibleIds = ImmutableSet.copyOf(transform(visible, instanceToRegionAndName));\n      logger.trace(\"<< visible instances(%s)\", visibleIds);\n\n      // add an exception for each of the nodes we cannot customize\n      Set<RegionAndName> invisibleIds = difference(startedIds, visibleIds);\n      if (!invisibleIds.isEmpty()) {\n         logger.warn(\"<< not api visible instances(%s)\", invisibleIds);\n      }\n      return started;\n   }\n\n   private void populateCredentials(Set<RunningInstance> input, TemplateOptions options) {\n      LoginCredentials credentials = null;\n      for (RunningInstance instance : input) {\n         credentials = instanceToCredentials.getUnchecked(instance).orNull();\n         if (credentials != null)\n            break;\n      }\n      credentials = overrideDefaultCredentialsWithOptionsIfPresent(credentials, options);\n      if (credentials != null)\n         for (RegionAndName instance : transform(input, instanceToRegionAndName))\n            credentialStore.put(\"node#\" + instance.slashEncode(), credentials);\n   }\n\n   private void blockUntilRunningAndAssignElasticIpsToInstancesOrPutIntoBadMap(Set<RunningInstance> input,\n         Map<NodeMetadata, Exception> badNodes) {\n      Map<RegionAndName, RunningInstance> instancesById = Maps.uniqueIndex(input, instanceToRegionAndName);\n      for (Map.Entry<RegionAndName, RunningInstance> entry : instancesById.entrySet()) {\n         RegionAndName id = entry.getKey();\n         RunningInstance instance = entry.getValue();\n         try {\n            logger.debug(\"<< allocating elastic IP instance(%s)\", id);\n            String ip = client.getElasticIPAddressApi().get().allocateAddressInRegion(id.getRegion());\n            // block until instance is running\n            logger.debug(\">> awaiting status running instance(%s)\", id);\n            AtomicReference<NodeMetadata> node = newReference(runningInstanceToNodeMetadata\n                  .apply(instance));\n            nodeRunning.apply(node);\n            logger.trace(\"<< running instance(%s)\", id);\n            logger.debug(\">> associating elastic IP %s to instance %s\", ip, id);\n            client.getElasticIPAddressApi().get().associateAddressInRegion(id.getRegion(), ip, id.getName());\n            logger.trace(\"<< associated elastic IP %s to instance %s\", ip, id);\n            // add mapping of instance to ip into the cache\n            elasticIpCache.put(id, ip);\n         } catch (RuntimeException e) {\n            badNodes.put(runningInstanceToNodeMetadata.apply(instancesById.get(id)), e);\n         }\n      }\n   }\n\n   private Set<RunningInstance> createKeyPairAndSecurityGroupsAsNeededThenRunInstances(String group, int count,\n         Template template) {\n      String region = AWSUtils.getRegionFromLocationOrNull(template.getLocation());\n      String zone = getZoneFromLocationOrNull(template.getLocation());\n      RunInstancesOptions instanceOptions = createKeyPairAndSecurityGroupsAsNeededAndReturncustomize.execute(region,\n            group, template);\n      return createNodesInRegionAndZone(region, zone, group, count, template, instanceOptions);\n   }\n\n   protected Set<RunningInstance> createNodesInRegionAndZone(String region, String zone, String group,\n                                                             int count, Template template,\n                                                             RunInstancesOptions instanceOptions) {\n      int countStarted = 0;\n      int tries = 0;\n      Set<RunningInstance> started = ImmutableSet.<RunningInstance> of();\n\n      int maxCount = EC2TemplateOptions.class.cast(template.getOptions()).getMaxCount();\n      int countToProvision;\n\n      if (maxCount == 0) {\n         maxCount = count;\n         countToProvision = 1;\n      } else {\n         countToProvision = count;\n      }\n\n      while (countStarted < count && tries++ < count) {\n         if (logger.isDebugEnabled())\n            logger.debug(\">> running %d instance region(%s) zone(%s) ami(%s) params(%s)\", count - countStarted, region,\n                  zone, template.getImage().getProviderId(), instanceOptions.buildFormParameters());\n\n         started = ImmutableSet.copyOf(concat(\n               started,\n               client.getInstanceApi().get().runInstancesInRegion(region, zone, template.getImage().getProviderId(),\n                       countToProvision, maxCount - countStarted, instanceOptions)));\n\n         countStarted = size(started);\n         if (countStarted < count)\n            logger.debug(\">> not enough instances (%d/%d) started, attempting again\", countStarted, count);\n      }\n      return started;\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/strategy/EC2DestroyNodeStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.strategy;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.concurrent.ExecutionException;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.compute.strategy.DestroyNodeStrategy;\nimport org.jclouds.compute.strategy.GetNodeMetadataStrategy;\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.reference.EC2Constants;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\n\n@Singleton\npublic class EC2DestroyNodeStrategy implements DestroyNodeStrategy {\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n   protected final EC2Api client;\n   protected final GetNodeMetadataStrategy getNode;\n   protected final LoadingCache<RegionAndName, String> elasticIpCache;\n\n   @Inject\n   @Named(EC2Constants.PROPERTY_EC2_AUTO_ALLOCATE_ELASTIC_IPS)\n   @VisibleForTesting\n   boolean autoAllocateElasticIps = false;\n\n   @Inject\n   protected EC2DestroyNodeStrategy(EC2Api client, GetNodeMetadataStrategy getNode,\n            @Named(\"ELASTICIP\") LoadingCache<RegionAndName, String> elasticIpCache) {\n      this.client = checkNotNull(client, \"client\");\n      this.getNode = checkNotNull(getNode, \"getNode\");\n      this.elasticIpCache = checkNotNull(elasticIpCache, \"elasticIpCache\");\n   }\n\n   @Override\n   public NodeMetadata destroyNode(String id) {\n      String[] parts = AWSUtils.parseHandle(id);\n      String region = parts[0];\n      String instanceId = parts[1];\n\n      // TODO: can there be multiple?\n      releaseAnyPublicIpForInstanceInRegion(instanceId, region);\n      destroyInstanceInRegion(instanceId, region);\n      return getNode.getNode(id);\n   }\n\n   protected void releaseAnyPublicIpForInstanceInRegion(String instanceId, String region) {\n      if (!autoAllocateElasticIps)\n         return;\n      try {\n         String ip = elasticIpCache.get(new RegionAndName(region, instanceId));\n         logger.debug(\">> disassociating elastic IP %s\", ip);\n         client.getElasticIPAddressApi().get().disassociateAddressInRegion(region, ip);\n         logger.trace(\"<< disassociated elastic IP %s\", ip);\n         elasticIpCache.invalidate(new RegionAndName(region, instanceId));\n         logger.debug(\">> releasing elastic IP %s\", ip);\n         client.getElasticIPAddressApi().get().releaseAddressInRegion(region, ip);\n         logger.trace(\"<< released elastic IP %s\", ip);\n      } catch (CacheLoader.InvalidCacheLoadException e) {\n         // no ip was found\n         return;\n      } catch (ExecutionException e) {\n         // don't propagate as we need to clean up the node regardless\n         logger.warn(e, \"error cleaning up elastic ip for instance %s/%s\", region, instanceId);\n      }\n\n   }\n\n   protected void destroyInstanceInRegion(String instanceId, String region) {\n      client.getInstanceApi().get().terminateInstancesInRegion(region, instanceId);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/strategy/EC2GetImageStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.strategy;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.getOnlyElement;\n\nimport java.util.NoSuchElementException;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.compute.strategy.GetImageStrategy;\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.domain.Image;\nimport org.jclouds.ec2.options.DescribeImagesOptions;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class EC2GetImageStrategy implements GetImageStrategy {\n\n   private final EC2Api client;\n   private final Function<Image, org.jclouds.compute.domain.Image> imageToImage;\n\n   @Inject\n   protected EC2GetImageStrategy(EC2Api client, Function<Image, org.jclouds.compute.domain.Image> imageToImage) {\n      this.client = checkNotNull(client, \"client\");\n      this.imageToImage = checkNotNull(imageToImage, \"imageToImage\");\n   }\n\n   @Override\n   public org.jclouds.compute.domain.Image getImage(String id) {\n      checkNotNull(id, \"id\");\n      String[] parts = AWSUtils.parseHandle(id);\n      String region = parts[0];\n      String instanceId = parts[1];\n      try {\n         Image image = getImageInRegion(region, instanceId);\n         return imageToImage.apply(image);\n      } catch (NoSuchElementException e) {\n         return null;\n      }\n   }\n\n   public Image getImageInRegion(String region, String id) {\n      return getOnlyElement(client.getAMIApi().get().describeImagesInRegion(region,\n               DescribeImagesOptions.Builder.imageIds(id)));\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/strategy/EC2GetNodeMetadataStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.strategy;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.getOnlyElement;\n\nimport java.util.NoSuchElementException;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.strategy.GetNodeMetadataStrategy;\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.domain.RunningInstance;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.Iterables;\n\n@Singleton\npublic class EC2GetNodeMetadataStrategy implements GetNodeMetadataStrategy {\n\n   private final EC2Api client;\n   private final Function<RunningInstance, NodeMetadata> runningInstanceToNodeMetadata;\n\n   @Inject\n   protected EC2GetNodeMetadataStrategy(EC2Api client,\n            Function<RunningInstance, NodeMetadata> runningInstanceToNodeMetadata) {\n      this.client = checkNotNull(client, \"client\");\n      this.runningInstanceToNodeMetadata = checkNotNull(runningInstanceToNodeMetadata, \"runningInstanceToNodeMetadata\");\n   }\n\n   @Override\n   public NodeMetadata getNode(String id) {\n      checkNotNull(id, \"id\");\n      String[] parts = AWSUtils.parseHandle(id);\n      String region = parts[0];\n      String instanceId = parts[1];\n      try {\n         RunningInstance runningInstance = getRunningInstanceInRegion(region, instanceId);\n         return runningInstanceToNodeMetadata.apply(runningInstance);\n      } catch (NoSuchElementException e) {\n         return null;\n      }\n   }\n\n   public RunningInstance getRunningInstanceInRegion(String region, String id) {\n      return getOnlyElement(Iterables.concat(client.getInstanceApi().get().describeInstancesInRegion(region, id)));\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/strategy/EC2ListNodesStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.strategy;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Predicates.and;\nimport static com.google.common.base.Predicates.in;\nimport static com.google.common.base.Predicates.notNull;\nimport static com.google.common.collect.Iterables.concat;\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.toArray;\nimport static com.google.common.collect.Iterables.transform;\nimport static com.google.common.collect.Multimaps.filterKeys;\nimport static com.google.common.collect.Multimaps.index;\nimport static com.google.common.collect.Multimaps.transformValues;\n\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Constants;\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.compute.domain.ComputeMetadata;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.predicates.NodePredicates;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.compute.strategy.ListNodesStrategy;\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.domain.Reservation;\nimport org.jclouds.ec2.domain.RunningInstance;\nimport org.jclouds.location.Region;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Multimap;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.inject.Inject;\n\n@Singleton\npublic class EC2ListNodesStrategy implements ListNodesStrategy {\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   @Inject(optional = true)\n   @Named(Constants.PROPERTY_REQUEST_TIMEOUT)\n   protected static Long maxTime;\n\n   protected final EC2Api client;\n   protected final Supplier<Set<String>> regions;\n   protected final Function<RunningInstance, NodeMetadata> runningInstanceToNodeMetadata;\n   protected final ListeningExecutorService userExecutor;\n\n   @Inject\n   protected EC2ListNodesStrategy(EC2Api client, @Region Supplier<Set<String>> regions,\n            Function<RunningInstance, NodeMetadata> runningInstanceToNodeMetadata,\n            @Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor) {\n      this.client =  checkNotNull(client, \"client\");\n      this.regions =  checkNotNull(regions, \"regions\");\n      this.runningInstanceToNodeMetadata = checkNotNull(runningInstanceToNodeMetadata, \"runningInstanceToNodeMetadata\");\n      this.userExecutor =  checkNotNull(userExecutor, \"userExecutor\");\n   }\n\n   @Override\n   public Set<? extends ComputeMetadata> listNodes() {\n      return listDetailsOnNodesMatching(NodePredicates.all());\n   }\n\n   @Override\n   public Set<? extends NodeMetadata> listNodesByIds(Iterable<String> ids) {\n      Multimap<String, String> idsByHandles = index(ids, splitHandle(1));\n      Multimap<String, String> idsByRegions = transformValues(idsByHandles, splitHandle(0));\n      Multimap<String, String> idsByConfiguredRegions = filterKeys(idsByRegions, in(regions.get()));\n\n      if (idsByConfiguredRegions.isEmpty()) {\n         return ImmutableSet.of();\n      }\n      \n      Iterable<? extends RunningInstance> instances = pollRunningInstancesByRegionsAndIds(idsByConfiguredRegions);\n      Iterable<? extends NodeMetadata> nodes = transform(filter(instances, notNull()),\n                                                         runningInstanceToNodeMetadata);\n      return ImmutableSet.copyOf(nodes);\n   }\n\n   @Override\n   public Set<? extends NodeMetadata> listDetailsOnNodesMatching(Predicate<? super NodeMetadata> filter) {\n      Iterable<? extends RunningInstance> instances = pollRunningInstances();\n      Iterable<? extends NodeMetadata> nodes = filter(transform(filter(instances, notNull()),\n               runningInstanceToNodeMetadata), and(notNull(), filter));\n      return ImmutableSet.copyOf(nodes);\n   }\n\n   protected Iterable<? extends RunningInstance> pollRunningInstances() {\n      Iterable<? extends Set<? extends Reservation<? extends RunningInstance>>> reservations\n         = transform(regions.get(), allInstancesInRegion());\n      \n      return concat(concat(reservations));\n   }\n\n   protected Iterable<? extends RunningInstance> pollRunningInstancesByRegionsAndIds(final Multimap<String, String> idsByRegions) {\n      Iterable<? extends Set<? extends Reservation<? extends RunningInstance>>> reservations\n         = transform(idsByRegions.keySet(), instancesByIdInRegion(idsByRegions));\n      \n      return concat(concat(reservations));\n   }\n\n   protected Function<String, String> splitHandle(final int pos) {\n      return new Function<String, String>() {\n\n         @Override\n         public String apply(String handle) {\n            return AWSUtils.parseHandle(handle)[pos];\n         }\n      };\n   }\n\n   protected Function<String, Set<? extends Reservation<? extends RunningInstance>>> allInstancesInRegion() {\n      return new Function<String, Set<? extends Reservation<? extends RunningInstance>>>() {\n         \n         @Override\n         public Set<? extends Reservation<? extends RunningInstance>> apply(String from) {\n            return client.getInstanceApi().get().describeInstancesInRegion(from);\n         }\n         \n      };\n   }\n\n   protected Function<String, Set<? extends Reservation<? extends RunningInstance>>>\n                                                                  instancesByIdInRegion(final Multimap<String, String> idsByRegions) {\n      return new Function<String, Set<? extends Reservation<? extends RunningInstance>>>() {\n                 \n         @Override\n         public Set<? extends Reservation<? extends RunningInstance>> apply(String from) {\n            return client.getInstanceApi().get()\n               .describeInstancesInRegion(from, toArray(idsByRegions.get(from), String.class));\n         }\n         \n      };\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/strategy/EC2PopulateDefaultLoginCredentialsForImageStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.strategy;\n\nimport static com.google.common.base.Preconditions.checkArgument;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.strategy.impl.ReturnCredentialsBoundToImage;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.domain.LoginCredentials.Builder;\nimport org.jclouds.ec2.domain.Image;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.collect.ImmutableMap;\n\n@Singleton\npublic class EC2PopulateDefaultLoginCredentialsForImageStrategy extends ReturnCredentialsBoundToImage {\n   public EC2PopulateDefaultLoginCredentialsForImageStrategy() {\n      this(null, ImmutableMap.<String, Credentials> of(), ImmutableMap.<OsFamily, LoginCredentials>of());\n   }\n\n   @Inject\n   public EC2PopulateDefaultLoginCredentialsForImageStrategy(@Nullable @Named(\"image\") LoginCredentials creds,\n            Map<String, Credentials> credentialStore, Map<OsFamily, LoginCredentials> osFamilyToCredentials) {\n      super(creds, credentialStore, osFamilyToCredentials);\n   }\n\n   @Override\n   public LoginCredentials apply(Object resourceToAuthenticate) {\n      if (creds != null)\n         return creds;\n      Builder credentials = LoginCredentials.builder().user(\"root\");\n      if (resourceToAuthenticate != null) {\n         String owner = null;\n         String name = null;\n         if (resourceToAuthenticate instanceof Image) {\n            owner = Image.class.cast(resourceToAuthenticate).getImageOwnerId();\n            name = Image.class.cast(resourceToAuthenticate).getName();\n         } else if (resourceToAuthenticate instanceof org.jclouds.compute.domain.Image) {\n            owner = org.jclouds.compute.domain.Image.class.cast(resourceToAuthenticate).getUserMetadata().get(\"owner\");\n            name = org.jclouds.compute.domain.Image.class.cast(resourceToAuthenticate).getUserMetadata().get(\"name\");\n         }\n         checkArgument(owner != null, \"Resource must be an image (for EC2)\");\n         // canonical/alestic images use the ubuntu user to login\n         if (owner.matches(\"063491364108|099720109477\")) {\n            credentials.user(\"ubuntu\");\n            // http://typepad.com/2010/09/introducing-amazon-linux-ami.html\n         } else if (owner.equals(\"137112412989\")) {\n            credentials.user(\"ec2-user\");\n         } else if (owner.equals(\"679593333241\") && name != null && name.startsWith(\"CentOS\")) {\n            credentials.user(\"centos\");\n         }\n      }\n      return credentials.build();\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/strategy/EC2RebootNodeStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.strategy;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.strategy.GetNodeMetadataStrategy;\nimport org.jclouds.compute.strategy.RebootNodeStrategy;\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.features.InstanceApi;\n\n@Singleton\npublic class EC2RebootNodeStrategy implements RebootNodeStrategy {\n   private final InstanceApi client;\n   private final GetNodeMetadataStrategy getNode;\n\n   @Inject\n   protected EC2RebootNodeStrategy(EC2Api client, GetNodeMetadataStrategy getNode) {\n      this.client = client.getInstanceApi().get();\n      this.getNode = getNode;\n   }\n\n   @Override\n   public NodeMetadata rebootNode(String id) {\n      String[] parts = AWSUtils.parseHandle(id);\n      String region = parts[0];\n      String instanceId = parts[1];\n      client.rebootInstancesInRegion(region, instanceId);\n      return getNode.getNode(id);\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/strategy/EC2ResumeNodeStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.strategy;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.strategy.GetNodeMetadataStrategy;\nimport org.jclouds.compute.strategy.ResumeNodeStrategy;\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.features.InstanceApi;\n\n@Singleton\npublic class EC2ResumeNodeStrategy implements ResumeNodeStrategy {\n   private final InstanceApi client;\n   private final GetNodeMetadataStrategy getNode;\n\n   @Inject\n   protected EC2ResumeNodeStrategy(EC2Api client, GetNodeMetadataStrategy getNode) {\n      this.client = client.getInstanceApi().get();\n      this.getNode = getNode;\n   }\n\n   @Override\n   public NodeMetadata resumeNode(String id) {\n      String[] parts = AWSUtils.parseHandle(id);\n      String region = parts[0];\n      String instanceId = parts[1];\n      client.startInstancesInRegion(region, instanceId);\n      return getNode.getNode(id);\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/strategy/EC2SuspendNodeStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.strategy;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.strategy.GetNodeMetadataStrategy;\nimport org.jclouds.compute.strategy.SuspendNodeStrategy;\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.features.InstanceApi;\n\n@Singleton\npublic class EC2SuspendNodeStrategy implements SuspendNodeStrategy {\n   private final InstanceApi client;\n   private final GetNodeMetadataStrategy getNode;\n\n   @Inject\n   protected EC2SuspendNodeStrategy(EC2Api client, GetNodeMetadataStrategy getNode) {\n      this.client = client.getInstanceApi().get();\n      this.getNode = getNode;\n   }\n\n   @Override\n   public NodeMetadata suspendNode(String id) {\n      String[] parts = AWSUtils.parseHandle(id);\n      String region = parts[0];\n      String instanceId = parts[1];\n      client.stopInstancesInRegion(region, true, instanceId);\n      return getNode.getNode(id);\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/strategy/ReviseParsedImage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.strategy;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.domain.ImageBuilder;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.OsFamily;\n\nimport com.google.inject.ImplementedBy;\n\n@ImplementedBy(ReviseParsedImage.NoopReviseParsedImage.class)\npublic interface ReviseParsedImage {\n   void reviseParsedImage(org.jclouds.ec2.domain.Image from, ImageBuilder builder, OsFamily family,\n            OperatingSystem.Builder osBuilder);\n\n   @Singleton\n   public static class NoopReviseParsedImage implements ReviseParsedImage {\n\n      @Override\n      public void reviseParsedImage(org.jclouds.ec2.domain.Image from, ImageBuilder builder, OsFamily family,\n               OperatingSystem.Builder osBuilder) {\n      }\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/suppliers/EC2HardwareSupplier.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.suppliers;\n\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.c1_medium;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.c1_xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.m1_large;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.m1_small;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.m1_xlarge;\n\nimport java.util.Set;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.domain.Hardware;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableSet;\n\n@Singleton\npublic class EC2HardwareSupplier implements Supplier<Set<? extends Hardware>> {\n\n   @Override\n   public Set<? extends Hardware> get() {\n      return ImmutableSet.<Hardware> of(m1_small().build(), c1_medium().build(), c1_xlarge()\n               .build(), m1_large().build(), m1_xlarge().build());\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/suppliers/EC2ImageSupplier.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.suppliers;\n\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.transform;\nimport static org.jclouds.ec2.options.DescribeImagesOptions.Builder.ownedBy;\nimport static org.jclouds.ec2.reference.EC2Constants.PROPERTY_EC2_AMI_OWNERS;\n\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.compute.functions.EC2ImageParser;\nimport org.jclouds.ec2.compute.functions.ImagesToRegionAndIdMap;\nimport org.jclouds.ec2.compute.strategy.DescribeImagesParallel;\nimport org.jclouds.ec2.options.DescribeImagesOptions;\nimport org.jclouds.location.Region;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Predicates;\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMap.Builder;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Sets;\n\n@Singleton\npublic class EC2ImageSupplier implements Supplier<Set<? extends Image>> {\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   private final Supplier<Set<String>> regions;\n   private final DescribeImagesParallel describer;\n   private final String[] amiOwners;\n   private final EC2ImageParser parser;\n   private final Supplier<LoadingCache<RegionAndName, ? extends Image>> cache;\n\n   @Inject\n   protected EC2ImageSupplier(@Region Supplier<Set<String>> regions, DescribeImagesParallel describer,\n         @Named(PROPERTY_EC2_AMI_OWNERS) String[] amiOwners, Supplier<LoadingCache<RegionAndName, ? extends Image>> cache,\n         EC2ImageParser parser) {\n      this.regions = regions;\n      this.describer = describer;\n      this.amiOwners = amiOwners;\n      this.cache = cache;\n      this.parser = parser;\n   }\n\n   @SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n   @Override\n   public Set<? extends Image> get() {\n      if (amiOwners.length == 0) {\n         logger.debug(\">> no owners specified, skipping image parsing\");\n         return ImmutableSet.of();\n      \n      } else {\n         logger.debug(\">> providing images\");\n\n         Iterable<Entry<String, DescribeImagesOptions>> queries = getDescribeQueriesForOwnersInRegions(regions.get(),\n                  amiOwners);\n\n         Iterable<? extends Image> parsedImages = ImmutableSet.copyOf(filter(transform(describer.apply(queries), parser), Predicates\n                  .notNull()));\n\n         Map<RegionAndName, ? extends Image> imageMap = ImagesToRegionAndIdMap.imagesToMap(parsedImages);\n         cache.get().invalidateAll();\n         cache.get().asMap().putAll((Map)imageMap);\n         logger.debug(\"<< images(%d)\", imageMap.size());\n         \n         return Sets.newLinkedHashSet(imageMap.values());\n      }\n   }\n\n   public Iterable<Entry<String, DescribeImagesOptions>> getDescribeQueriesForOwnersInRegions(Set<String> regions,\n         String[] amiOwners) {\n      DescribeImagesOptions options = getOptionsForOwners(amiOwners);\n      Builder<String, DescribeImagesOptions> builder = ImmutableMap.builder();\n      for (String region : regions)\n         builder.put(region, options);\n      return builder.build().entrySet();\n   }\n\n   public DescribeImagesOptions getOptionsForOwners(String... amiOwners) {\n      DescribeImagesOptions options;\n      if (amiOwners.length == 1 && amiOwners[0].equals(\"*\"))\n         options = new DescribeImagesOptions();\n      else\n         options = ownedBy(amiOwners);\n      return options;\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/suppliers/RegionAndNameToImageSupplier.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.suppliers;\n\nimport static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL;\n\nimport java.util.concurrent.TimeUnit;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\n\n@Singleton\npublic class RegionAndNameToImageSupplier implements Supplier<LoadingCache<RegionAndName, ? extends Image>> {\n   private final LoadingCache<RegionAndName, Image> cache;\n\n   @Inject\n   protected RegionAndNameToImageSupplier(CacheLoader<RegionAndName, Image> regionAndIdToImage, \n            @Named(PROPERTY_SESSION_INTERVAL) long expirationSecs) {\n      cache = CacheBuilder.newBuilder().expireAfterWrite(expirationSecs,  TimeUnit.SECONDS).build(regionAndIdToImage);\n   }\n\n   @Override\n   public LoadingCache<RegionAndName, ? extends Image> get() {\n      return cache;\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/compute/util/EC2ComputeUtils.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.util;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationScope;\n\n@Singleton\npublic class EC2ComputeUtils {\n\n   public static String getZoneFromLocationOrNull(Location location) {\n      return location.getScope() == LocationScope.ZONE ? location.getId() : null;\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/config/BaseEC2HttpApiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.config;\n\n\n\n\nimport org.jclouds.aws.config.FormSigningHttpApiModule;\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.suppliers.DescribeAvailabilityZonesInRegion;\nimport org.jclouds.ec2.suppliers.DescribeRegionsForRegionURIs;\nimport org.jclouds.location.config.LocationModule;\nimport org.jclouds.location.suppliers.RegionIdToURISupplier;\nimport org.jclouds.location.suppliers.RegionIdToZoneIdsSupplier;\nimport org.jclouds.location.suppliers.RegionIdsSupplier;\nimport org.jclouds.location.suppliers.ZoneIdToURISupplier;\nimport org.jclouds.location.suppliers.ZoneIdsSupplier;\nimport org.jclouds.location.suppliers.derived.RegionIdsFromRegionIdToURIKeySet;\nimport org.jclouds.location.suppliers.derived.ZoneIdToURIFromJoinOnRegionIdToURI;\nimport org.jclouds.location.suppliers.derived.ZoneIdsFromRegionIdToZoneIdsValues;\nimport org.jclouds.rest.ConfiguresHttpApi;\n\nimport com.google.inject.Scopes;\n\n/**\n * Configures the EC2 connection.\n */\n@ConfiguresHttpApi\npublic abstract class BaseEC2HttpApiModule<A extends EC2Api> extends\n         FormSigningHttpApiModule<A> {\n\n   protected BaseEC2HttpApiModule(Class<A> api) {\n      super(api);\n   }\n\n   @Override\n   protected void installLocations() {\n      install(new LocationModule());\n      bind(RegionIdToZoneIdsSupplier.class).to(DescribeAvailabilityZonesInRegion.class).in(Scopes.SINGLETON);\n      bind(RegionIdToURISupplier.class).to(DescribeRegionsForRegionURIs.class).in(Scopes.SINGLETON);\n      bind(ZoneIdsSupplier.class).to(ZoneIdsFromRegionIdToZoneIdsValues.class).in(Scopes.SINGLETON);\n      bind(RegionIdsSupplier.class).to(RegionIdsFromRegionIdToURIKeySet.class).in(Scopes.SINGLETON);\n      bind(ZoneIdToURISupplier.class).to(ZoneIdToURIFromJoinOnRegionIdToURI.class).in(Scopes.SINGLETON);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/config/EC2HttpApiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.config;\n\n\n\n\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.rest.ConfiguresHttpApi;\n\n\n/**\n * Configures the EC2 connection.\n */\n@ConfiguresHttpApi\npublic class EC2HttpApiModule extends BaseEC2HttpApiModule<EC2Api> {\n\n   public EC2HttpApiModule() {\n      super(EC2Api.class);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/domain/Attachment.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Date;\n\n/**\n * @see <a href=\n *      \"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateVolume.html\"\n *      />\n */\npublic class Attachment implements Comparable<Attachment> {\n   public static enum Status {\n      ATTACHING, ATTACHED, DETACHING, DETACHED, BUSY, UNRECOGNIZED;\n\n      public String value() {\n         return name().toLowerCase();\n      }\n\n      @Override\n      public String toString() {\n         return value();\n      }\n\n      public static Status fromValue(String status) {\n         try {\n            return valueOf(checkNotNull(status, \"status\").toUpperCase());\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n      private String region;\n      private String volumeId;\n      private String instanceId;\n      private String device;\n      private Status status;\n      private Date attachTime;\n      \n      public Builder region(String region) {\n         this.region = region;\n         return this;\n      }\n      \n      public Builder volumeId(String volumeId) {\n         this.volumeId = volumeId;\n         return this;\n      }\n      \n      public Builder instanceId(String instanceId) {\n         this.instanceId = instanceId;\n         return this;\n      }\n      \n      public Builder device(String device) {\n         this.device = device;\n         return this;\n      }\n      \n      public Builder status(Status status) {\n         this.status = status;\n         return this;\n      }\n      \n      public Builder attachTime(Date attachTime)  {\n         this.attachTime = attachTime;\n         return this;\n      }\n\n      public Attachment build() {\n         return new Attachment(region, volumeId, instanceId, device, status, attachTime);\n      }\n   }\n\n   private final String region;\n   private final String volumeId;\n   private final String instanceId;\n   private final String device;\n   private final Status status;\n   private final Date attachTime;\n\n   public Attachment(String region, String volumeId, String instanceId, String device, Status status, Date attachTime) {\n      this.region = checkNotNull(region, \"region\");\n      this.volumeId = volumeId;\n      this.instanceId = instanceId;\n      this.device = device;\n      this.status = status;\n      this.attachTime = attachTime;\n   }\n\n   /**\n    * To be removed in jclouds 1.6 <h4>Warning</h4>\n    * \n    * Especially on EC2 clones that may not support regions, this value is fragile. Consider\n    * alternate means to determine context.\n    */\n   @Deprecated\n   public String getRegion() {\n      return region;\n   }\n\n   /**\n    * The ID of the volume.\n    */\n   public String getVolumeId() {\n      return volumeId;\n   }\n\n   /**\n    * The ID of the instance.\n    */\n   public String getId() {\n      return instanceId;\n   }\n\n   /**\n    * The device as it is exposed to the instance.\n    */\n   public String getDevice() {\n      return device;\n   }\n\n   /**\n    * Volume state.\n    */\n   public Status getStatus() {\n      return status;\n   }\n\n   /**\n    * Time stamp when the attachment initiated.\n    */\n   public Date getAttachTime() {\n      return attachTime;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((attachTime == null) ? 0 : attachTime.hashCode());\n      result = prime * result + ((device == null) ? 0 : device.hashCode());\n      result = prime * result + ((instanceId == null) ? 0 : instanceId.hashCode());\n      result = prime * result + ((region == null) ? 0 : region.hashCode());\n      result = prime * result + ((status == null) ? 0 : status.hashCode());\n      result = prime * result + ((volumeId == null) ? 0 : volumeId.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      Attachment other = (Attachment) obj;\n      if (attachTime == null) {\n         if (other.attachTime != null)\n            return false;\n      } else if (!attachTime.equals(other.attachTime))\n         return false;\n      if (device == null) {\n         if (other.device != null)\n            return false;\n      } else if (!device.equals(other.device))\n         return false;\n      if (instanceId == null) {\n         if (other.instanceId != null)\n            return false;\n      } else if (!instanceId.equals(other.instanceId))\n         return false;\n      if (region == null) {\n         if (other.region != null)\n            return false;\n      } else if (!region.equals(other.region))\n         return false;\n      if (status == null) {\n         if (other.status != null)\n            return false;\n      } else if (!status.equals(other.status))\n         return false;\n      if (volumeId == null) {\n         if (other.volumeId != null)\n            return false;\n      } else if (!volumeId.equals(other.volumeId))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"Attachment [region=\" + region + \", volumeId=\" + volumeId + \", instanceId=\" + instanceId + \", device=\"\n              + device + \", attachTime=\" + attachTime + \", status=\" + status + \"]\";\n   }\n\n   @Override\n   public int compareTo(Attachment o) {\n      return attachTime.compareTo(o.attachTime);\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/domain/AvailabilityZoneInfo.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Set;\n\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Sets;\n\n/**\n * \n * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-ItemType-AvailabilityZoneItemType.html\"\n *      />\n */\npublic class AvailabilityZoneInfo implements Comparable<AvailabilityZoneInfo> {\n\n   private final String zone;\n   private final String state;\n   private final String region;\n   private final Set<String> messages = Sets.newHashSet();\n\n   public AvailabilityZoneInfo(String zone, String zoneState,\n            String region, Iterable<String> messages) {\n      this.zone = checkNotNull(zone, \"zone\");\n      this.state = checkNotNull(zoneState, \"zoneState\");\n      this.region = checkNotNull(region, \"region\");\n      Iterables.addAll(this.messages, checkNotNull(messages, \"messages\"));\n   }\n\n   /**\n    * the Availability Zone.\n    */\n   public String getZone() {\n      return zone;\n   }\n\n   /**\n    * State of the Availability Zone.\n    */\n   public String getState() {\n      return state;\n   }\n\n   /**\n    * Name of the Region.\n    */\n   public String getRegion() {\n      return region;\n   }\n\n   /**\n    * Messages\n    */\n   public Set<String> getMessages() {\n      return messages;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((messages == null) ? 0 : messages.hashCode());\n      result = prime * result + ((region == null) ? 0 : region.hashCode());\n      result = prime * result + ((state == null) ? 0 : state.hashCode());\n      result = prime * result + ((zone == null) ? 0 : zone.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      AvailabilityZoneInfo other = (AvailabilityZoneInfo) obj;\n      if (messages == null) {\n         if (other.messages != null)\n            return false;\n      } else if (!messages.equals(other.messages))\n         return false;\n      if (region == null) {\n         if (other.region != null)\n            return false;\n      } else if (!region.equals(other.region))\n         return false;\n      if (state == null) {\n         if (other.state != null)\n            return false;\n      } else if (!state.equals(other.state))\n         return false;\n      if (zone == null) {\n         if (other.zone != null)\n            return false;\n      } else if (!zone.equals(other.zone))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"AvailabilityZoneInfo [messages=\" + messages + \", region=\" + region + \", state=\"\n               + state + \", zone=\" + zone + \"]\";\n   }\n\n   @Override\n   public int compareTo(AvailabilityZoneInfo that) {\n      return zone.compareTo(that.zone);\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/domain/BlockDevice.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.domain;\n\nimport java.util.Date;\n\nimport org.jclouds.ec2.domain.Attachment.Status;\n\n/**\n * \n * @see <a href=\n *      \"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-ItemType-RunningInstancesItemType.html\"\n *      />\n */\npublic class BlockDevice {\n   private final String volumeId;\n   private final Attachment.Status attachmentStatus;\n   private final Date attachTime;\n   private final boolean deleteOnTermination;\n\n   public BlockDevice(String volumeId, Status attachmentStatus, Date attachTime, boolean deleteOnTermination) {\n      this.volumeId = volumeId;\n      this.attachmentStatus = attachmentStatus;\n      this.attachTime = attachTime;\n      this.deleteOnTermination = deleteOnTermination;\n   }\n\n   public BlockDevice(String volumeId, boolean deleteOnTermination) {\n      this(volumeId, null, null, deleteOnTermination);\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((attachTime == null) ? 0 : attachTime.hashCode());\n      result = prime * result + ((attachmentStatus == null) ? 0 : attachmentStatus.hashCode());\n      result = prime * result + (deleteOnTermination ? 1231 : 1237);\n      result = prime * result + ((volumeId == null) ? 0 : volumeId.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      BlockDevice other = (BlockDevice) obj;\n      if (attachTime == null) {\n         if (other.attachTime != null)\n            return false;\n      } else if (!attachTime.equals(other.attachTime))\n         return false;\n      if (attachmentStatus == null) {\n         if (other.attachmentStatus != null)\n            return false;\n      } else if (!attachmentStatus.equals(other.attachmentStatus))\n         return false;\n      if (deleteOnTermination != other.deleteOnTermination)\n         return false;\n      if (volumeId == null) {\n         if (other.volumeId != null)\n            return false;\n      } else if (!volumeId.equals(other.volumeId))\n         return false;\n      return true;\n   }\n\n   public String getVolumeId() {\n      return volumeId;\n   }\n\n   public Attachment.Status getAttachmentStatus() {\n      return attachmentStatus;\n   }\n\n   public Date getAttachTime() {\n      return attachTime;\n   }\n\n   public boolean isDeleteOnTermination() {\n      return deleteOnTermination;\n   }\n\n   @Override\n   public String toString() {\n      return \"[volumeId=\" + volumeId + \", attachmentStatus=\" + attachmentStatus + \", attachTime=\"\n            + attachTime + \", deleteOnTermination=\" + deleteOnTermination + \"]\";\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/domain/BlockDeviceMapping.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.domain;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Strings.emptyToNull;\n\nimport org.jclouds.javax.annotation.Nullable;\n\npublic class BlockDeviceMapping implements Comparable<BlockDeviceMapping> {\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n      private String deviceName;\n      private String virtualName;\n      private String snapshotId;\n      private Integer sizeInGib;\n      private Boolean noDevice;\n      private Boolean deleteOnTermination;\n      private String volumeType;\n      private Integer iops;\n      private Boolean encrypted;\n\n      public Builder deviceName(String deviceName) {\n         this.deviceName = deviceName;\n         return this;\n      }\n\n      public Builder virtualName(String virtualName) {\n         this.virtualName = virtualName;\n         return this;\n      }\n\n      public Builder snapshotId(String snapshotId) {\n         this.snapshotId = snapshotId;\n         return this;\n      }\n\n      public Builder sizeInGib(Integer sizeInGib) {\n         this.sizeInGib = sizeInGib;\n         return this;\n      }\n\n      public Builder noDevice(Boolean noDevice) {\n         this.noDevice = noDevice;\n         return this;\n      }\n\n      public Builder deleteOnTermination(Boolean deleteOnTermination) {\n         this.deleteOnTermination = deleteOnTermination;\n         return this;\n      }\n\n      public Builder volumeType(String volumeType) {\n         this.volumeType = volumeType;\n         return this;\n      }\n\n      public Builder iops(Integer iops) {\n         this.iops = iops;\n         return this;\n      }\n\n      public Builder encrypted(Boolean encrypted) {\n         this.encrypted = encrypted;\n         return this;\n      }\n\n      public BlockDeviceMapping build() {\n         return new BlockDeviceMapping(deviceName, virtualName, snapshotId, sizeInGib, noDevice, deleteOnTermination,\n                 volumeType, iops, encrypted);\n      }\n\n      public Builder clear() {\n         this.deviceName = null;\n         this.virtualName = null;\n         this.snapshotId = null;\n         this.sizeInGib = null;\n         this.noDevice = null;\n         this.deleteOnTermination = null;\n         this.volumeType = null;\n         this.iops = null;\n         this.encrypted = null;\n         return this;\n      }\n   }\n\n   private final String deviceName;\n   private final String virtualName;\n   private final String snapshotId;\n   private final Integer sizeInGib;\n   private final Boolean noDevice;\n   private final Boolean deleteOnTermination;\n   private final String volumeType;\n   private final Integer iops;\n   private final Boolean encrypted;\n\n   // values expressed in GB\n   private static final Integer VOLUME_SIZE_MIN_VALUE = 1;\n   private static final Integer VOLUME_SIZE_MAX_VALUE = 1000;\n\n   BlockDeviceMapping(String deviceName, @Nullable String virtualName, @Nullable String snapshotId,\n         @Nullable Integer sizeInGib, @Nullable Boolean noDevice, @Nullable Boolean deleteOnTermination,\n         @Nullable String volumeType, @Nullable Integer iops, @Nullable Boolean encrypted) {\n\n      checkNotNull(deviceName, \"deviceName cannot be null\");\n      checkNotNull(emptyToNull(deviceName), \"deviceName must be defined\");\n\n      if (sizeInGib != null) {\n         checkArgument(sizeInGib >= VOLUME_SIZE_MIN_VALUE && sizeInGib <= VOLUME_SIZE_MAX_VALUE,\n               \"Size in Gib must be between %s and %s GB\", VOLUME_SIZE_MIN_VALUE, VOLUME_SIZE_MAX_VALUE);\n      }\n      this.deviceName = deviceName;\n      this.virtualName = virtualName;\n      this.snapshotId = snapshotId;\n      this.sizeInGib = sizeInGib;\n      this.noDevice = noDevice;\n      this.deleteOnTermination = deleteOnTermination;\n      this.volumeType = volumeType;\n      this.iops = iops;\n      this.encrypted = encrypted;\n   }\n\n   public String getDeviceName() {\n      return deviceName;\n   }\n\n   public String getVirtualName() {\n      return virtualName;\n   }\n\n   public String getEbsSnapshotId() {\n      return snapshotId;\n   }\n\n   public Integer getEbsVolumeSize() {\n      return sizeInGib;\n   }\n\n   public Boolean getEbsNoDevice() {\n      return noDevice;\n   }\n\n   public Boolean getEbsDeleteOnTermination() {\n      return deleteOnTermination;\n   }\n\n   public String getEbsVolumeType() {\n      return volumeType;\n   }\n\n   public Integer getEbsIops() {\n      return iops;\n   }\n\n   public Boolean getEbsEncrypted() {\n      return encrypted;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((deleteOnTermination == null) ? 0 : deleteOnTermination.hashCode());\n      result = prime * result + ((deviceName == null) ? 0 : deviceName.hashCode());\n      result = prime * result + ((noDevice == null) ? 0 : noDevice.hashCode());\n      result = prime * result + ((sizeInGib == null) ? 0 : sizeInGib.hashCode());\n      result = prime * result + ((snapshotId == null) ? 0 : snapshotId.hashCode());\n      result = prime * result + ((virtualName == null) ? 0 : virtualName.hashCode());\n      result = prime * result + ((volumeType == null) ? 0 : volumeType.hashCode());\n      result = prime * result + ((iops == null) ? 0 : iops.hashCode());\n      result = prime * result + ((encrypted == null ) ? 0 : encrypted.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      BlockDeviceMapping other = (BlockDeviceMapping) obj;\n      if (deleteOnTermination == null) {\n         if (other.deleteOnTermination != null)\n            return false;\n      } else if (!deleteOnTermination.equals(other.deleteOnTermination))\n         return false;\n      if (deviceName == null) {\n         if (other.deviceName != null)\n            return false;\n      } else if (!deviceName.equals(other.deviceName))\n         return false;\n      if (noDevice == null) {\n         if (other.noDevice != null)\n            return false;\n      } else if (!noDevice.equals(other.noDevice))\n         return false;\n      if (sizeInGib == null) {\n         if (other.sizeInGib != null)\n            return false;\n      } else if (!sizeInGib.equals(other.sizeInGib))\n         return false;\n      if (snapshotId == null) {\n         if (other.snapshotId != null)\n            return false;\n      } else if (!snapshotId.equals(other.snapshotId))\n         return false;\n      if (virtualName == null) {\n         if (other.virtualName != null)\n            return false;\n      } else if (!virtualName.equals(other.virtualName))\n         return false;\n      if (volumeType == null) {\n         if (other.volumeType != null)\n            return false;\n      } else if (!volumeType.equals(other.volumeType))\n         return false;\n      if (iops == null) {\n         if (other.iops != null)\n            return false;\n      } else if (!iops.equals(other.iops))\n         return false;\n      if (encrypted == null) {\n         if (other.encrypted != null)\n            return false;\n      } else if (!encrypted.equals(other.encrypted))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"[deviceName=\" + deviceName + \", virtualName=\" + virtualName + \", snapshotId=\" + snapshotId\n              + \", sizeInGib=\" + sizeInGib + \", noDevice=\" + noDevice + \", deleteOnTermination=\" + deleteOnTermination\n              + \", volumeType=\" + volumeType + \", iops=\" + iops + \", encrypted=\" + encrypted\n              + \"]\";\n   }\n\n   public static class MapEBSSnapshotToDevice extends BlockDeviceMapping {\n      public MapEBSSnapshotToDevice(String deviceName, String snapshotId, @Nullable Integer sizeInGib,\n            @Nullable Boolean deleteOnTermination, @Nullable String volumeType,\n            @Nullable Integer iops, @Nullable Boolean encrypted) {\n         super(deviceName, null, snapshotId, sizeInGib, null, deleteOnTermination, volumeType, iops, encrypted);\n         checkNotNull(emptyToNull(snapshotId), \"snapshotId must be defined\");\n      }\n   }\n\n   public static class MapNewVolumeToDevice extends BlockDeviceMapping {\n      public MapNewVolumeToDevice(String deviceName, Integer sizeInGib, @Nullable Boolean deleteOnTermination,\n                                  @Nullable String volumeType, @Nullable Integer iops, @Nullable Boolean encrypted) {\n         super(deviceName, null, null, sizeInGib, null, deleteOnTermination, volumeType, iops, encrypted);\n         checkNotNull(sizeInGib, \"sizeInGib cannot be null\");\n      }\n   }\n\n   public static class MapEphemeralDeviceToDevice extends BlockDeviceMapping {\n      public MapEphemeralDeviceToDevice(String deviceName, String virtualName) {\n         super(deviceName, virtualName, null, null, null, null, null, null, null);\n         checkNotNull(emptyToNull(virtualName), \"virtualName must be defined\");\n      }\n   }\n\n   public static class UnmapDeviceNamed extends BlockDeviceMapping {\n      public UnmapDeviceNamed(String deviceName) {\n         super(deviceName, null, null, null, true, null, null, null, null);\n      }\n   }\n\n   @Override\n   public int compareTo(BlockDeviceMapping arg0) {\n      return deviceName.compareTo(arg0.deviceName);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/domain/BundleInstanceS3Storage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.javax.annotation.Nullable;\n\n/**\n * \n * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-ItemType-BundleInstanceS3StorageType.html\"\n *      />\n */\npublic class BundleInstanceS3Storage {\n   private final String ccessKeyId;\n   private final String bucket;\n   private final String prefix;\n   private final String secretAccessKey;\n   private final String uploadPolicy;\n   private final String uploadPolicySignature;\n\n   public BundleInstanceS3Storage(@Nullable String ccessKeyId, String bucket, String prefix,\n         @Nullable String secretAccessKey, @Nullable String uploadPolicy, @Nullable String uploadPolicySignature) {\n      this.ccessKeyId = ccessKeyId;\n      this.bucket = checkNotNull(bucket, \"bucket\");\n      this.prefix = checkNotNull(prefix, \"prefix\");\n      this.secretAccessKey = secretAccessKey;\n      this.uploadPolicy = uploadPolicy;\n      this.uploadPolicySignature = uploadPolicySignature;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((ccessKeyId == null) ? 0 : ccessKeyId.hashCode());\n      result = prime * result + ((bucket == null) ? 0 : bucket.hashCode());\n      result = prime * result + ((prefix == null) ? 0 : prefix.hashCode());\n      result = prime * result + ((secretAccessKey == null) ? 0 : secretAccessKey.hashCode());\n      result = prime * result + ((uploadPolicy == null) ? 0 : uploadPolicy.hashCode());\n      result = prime * result + ((uploadPolicySignature == null) ? 0 : uploadPolicySignature.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      BundleInstanceS3Storage other = (BundleInstanceS3Storage) obj;\n      if (ccessKeyId == null) {\n         if (other.ccessKeyId != null)\n            return false;\n      } else if (!ccessKeyId.equals(other.ccessKeyId))\n         return false;\n      if (bucket == null) {\n         if (other.bucket != null)\n            return false;\n      } else if (!bucket.equals(other.bucket))\n         return false;\n      if (prefix == null) {\n         if (other.prefix != null)\n            return false;\n      } else if (!prefix.equals(other.prefix))\n         return false;\n      if (secretAccessKey == null) {\n         if (other.secretAccessKey != null)\n            return false;\n      } else if (!secretAccessKey.equals(other.secretAccessKey))\n         return false;\n      if (uploadPolicy == null) {\n         if (other.uploadPolicy != null)\n            return false;\n      } else if (!uploadPolicy.equals(other.uploadPolicy))\n         return false;\n      if (uploadPolicySignature == null) {\n         if (other.uploadPolicySignature != null)\n            return false;\n      } else if (!uploadPolicySignature.equals(other.uploadPolicySignature))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"[ccessKeyId=\" + ccessKeyId + \", bucket=\" + bucket + \", prefix=\" + prefix + \", secretAccessKey=\"\n            + secretAccessKey + \", uploadPolicy=\" + uploadPolicy + \", uploadPolicySignature=\" + uploadPolicySignature\n            + \"]\";\n   }\n\n\n   /**\n    * \n    * @returnThe bucket in which to store the AMI. You can specify a bucket that\n    *            you already own or a new bucket that Amazon EC2 creates on your\n    *            behalf. If you specify a bucket that belongs to someone else,\n    *            Amazon EC2 returns an error.\n    */\n   public String getBucket() {\n      return bucket;\n   }\n\n   /**\n    * \n    * @return Specifies the beginning of the file name of the AMI.\n    */\n   public String getPrefix() {\n      return prefix;\n   }\n\n\n\n   /**\n    * \n    * @return An Amazon S3 upload policy that gives Amazon EC2 permission to\n    *         upload items into Amazon S3 on the user's behalf. For more\n    *         information on bundling in Windows, go to the Amazon Elastic\n    *         Compute Cloud Developer Guide and Amazon Elastic Compute Cloud\n    *         Getting Started\n    */\n   public String getUploadPolicy() {\n      return uploadPolicy;\n   }\n\n   /**\n    * \n    * @return The signature of the Base64 encoded JSON document.\n    */\n   public String getUploadPolicySignature() {\n      return uploadPolicySignature;\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/domain/BundleTask.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Date;\n\nimport org.jclouds.javax.annotation.Nullable;\n\n/**\n * \n * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-ItemType-BundleInstanceTaskType.html\"\n *      />\n */\npublic class BundleTask implements Comparable<BundleTask> {\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public int compareTo(BundleTask o) {\n      return (this == o) ? 0 : getBundleId().compareTo(o.getBundleId());\n   }\n\n   /**\n    * If the task fails, a description of the error.\n    * \n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-ItemType-BundleInstanceTaskErrorType.html\"\n    *      />\n    */\n   public static class Error {\n      private final String code;\n      private final String message;\n\n      public Error(String code, String message) {\n         this.code = checkNotNull(code, \"code\");\n         this.message = checkNotNull(message, \"message\");\n      }\n\n      public String getCode() {\n         return code;\n      }\n\n      public String getMessage() {\n         return message;\n      }\n\n      @Override\n      public String toString() {\n         return \"[code=\" + code + \", message=\" + message + \"]\";\n      }\n\n      @Override\n      public int hashCode() {\n         final int prime = 31;\n         int result = 1;\n         result = prime * result + ((code == null) ? 0 : code.hashCode());\n         result = prime * result + ((message == null) ? 0 : message.hashCode());\n         return result;\n      }\n\n      @Override\n      public boolean equals(Object obj) {\n         if (this == obj)\n            return true;\n         if (obj == null)\n            return false;\n         if (getClass() != obj.getClass())\n            return false;\n         Error other = (Error) obj;\n         if (code == null) {\n            if (other.code != null)\n               return false;\n         } else if (!code.equals(other.code))\n            return false;\n         if (message == null) {\n            if (other.message != null)\n               return false;\n         } else if (!message.equals(other.message))\n            return false;\n         return true;\n      }\n\n   }\n\n   private final String region;\n   private final String bundleId;\n   private final Error error;\n   private final String instanceId;\n   private final int progress;\n   private final Date startTime;\n   private final String state;\n   private final String bucket;\n   private final String prefix;\n   private final Date updateTime;\n\n   public BundleTask(String region, String bundleId, @Nullable Error error, String instanceId, int progress,\n         Date startTime, String state, String bucket, String prefix, Date updateTime) {\n      this.region = checkNotNull(region, \"region\");\n      this.bundleId = checkNotNull(bundleId, \"bundleId\");\n      this.error = error;\n      this.instanceId = checkNotNull(instanceId, \"instanceId\");\n      this.progress = progress;\n      this.startTime = checkNotNull(startTime, \"startTime\");\n      this.state = checkNotNull(state, \"state\");\n      this.bucket = checkNotNull(bucket, \"bucket\");\n      this.prefix = checkNotNull(prefix, \"prefix\");\n      this.updateTime = checkNotNull(updateTime, \"updateTime\");\n   }\n\n   @Override\n   public String toString() {\n      return \"[bucket=\" + bucket + \", bundleId=\" + bundleId + \", error=\" + error + \", instanceId=\" + instanceId\n            + \", prefix=\" + prefix + \", progress=\" + progress + \", region=\" + region + \", startTime=\" + startTime\n            + \", state=\" + state + \", updateTime=\" + updateTime + \"]\";\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((bucket == null) ? 0 : bucket.hashCode());\n      result = prime * result + ((bundleId == null) ? 0 : bundleId.hashCode());\n      result = prime * result + ((error == null) ? 0 : error.hashCode());\n      result = prime * result + ((instanceId == null) ? 0 : instanceId.hashCode());\n      result = prime * result + ((prefix == null) ? 0 : prefix.hashCode());\n      result = prime * result + progress;\n      result = prime * result + ((region == null) ? 0 : region.hashCode());\n      result = prime * result + ((startTime == null) ? 0 : startTime.hashCode());\n      result = prime * result + ((state == null) ? 0 : state.hashCode());\n      result = prime * result + ((updateTime == null) ? 0 : updateTime.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      BundleTask other = (BundleTask) obj;\n      if (bucket == null) {\n         if (other.bucket != null)\n            return false;\n      } else if (!bucket.equals(other.bucket))\n         return false;\n      if (bundleId == null) {\n         if (other.bundleId != null)\n            return false;\n      } else if (!bundleId.equals(other.bundleId))\n         return false;\n      if (error == null) {\n         if (other.error != null)\n            return false;\n      } else if (!error.equals(other.error))\n         return false;\n      if (instanceId == null) {\n         if (other.instanceId != null)\n            return false;\n      } else if (!instanceId.equals(other.instanceId))\n         return false;\n      if (prefix == null) {\n         if (other.prefix != null)\n            return false;\n      } else if (!prefix.equals(other.prefix))\n         return false;\n      if (progress != other.progress)\n         return false;\n      if (region == null) {\n         if (other.region != null)\n            return false;\n      } else if (!region.equals(other.region))\n         return false;\n      if (startTime == null) {\n         if (other.startTime != null)\n            return false;\n      } else if (!startTime.equals(other.startTime))\n         return false;\n      if (state == null) {\n         if (other.state != null)\n            return false;\n      } else if (!state.equals(other.state))\n         return false;\n      if (updateTime == null) {\n         if (other.updateTime != null)\n            return false;\n      } else if (!updateTime.equals(other.updateTime))\n         return false;\n      return true;\n   }\n\n   /**\n    * To be removed in jclouds 1.6 <h4>Warning</h4>\n    * \n    * Especially on EC2 clones that may not support regions, this value is fragile. Consider\n    * alternate means to determine context.\n    */\n   @Deprecated\n   public String getRegion() {\n      return region;\n   }\n\n   /**\n    * \n    * @return The bucket in which to store the AMI. You can specify a bucket\n    *         that you already own or a new bucket that Amazon EC2 creates on\n    *         your behalf. If you specify a bucket that belongs to someone e\n    *         lse, Amazon EC2 returns an error.\n    */\n   public String getBucket() {\n      return bucket;\n   }\n\n   /**\n    * \n    * @return Specifies the beginning of the file name of the AMI.\n    */\n   public String getPrefix() {\n      return prefix;\n   }\n\n   /**\n    * \n    * @return Identifier for this task.\n    */\n   public String getBundleId() {\n      return bundleId;\n   }\n\n   /**\n    * \n    * @return If the task fails, a description of the error.\n    */\n   public Error getError() {\n      return error;\n   }\n\n   /**\n    * \n    * @return Instance associated with this bundle task\n    */\n   public String getInstanceId() {\n      return instanceId;\n   }\n\n   /**\n    * \n    * @return A percentage description of the progress of the task, such as 20.\n    */\n   public int getProgress() {\n      return progress;\n   }\n\n   /**\n    * \n    * @return The time this task started.\n    */\n   public Date getStartTime() {\n      return startTime;\n   }\n\n   /**\n    * \n    * @return The state of the task.\n    */\n   public String getState() {\n      return state;\n   }\n\n   /**\n    * \n    * @return The time of the most recent update for the task.\n    */\n   public Date getUpdateTime() {\n      return updateTime;\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/domain/Hypervisor.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.domain;\n\nimport com.google.common.base.CaseFormat;\n\n/**\n * Hypervisor of the image.\n */\npublic enum Hypervisor {\n\n   XEN,\n   /**\n    * Oracle VM Server\n    */\n   OVM, UNRECOGNIZED;\n\n   public String value() {\n      return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_HYPHEN, name());\n   }\n\n   public String toString() {\n      return value();\n   }\n\n   public static Hypervisor fromValue(String v) {\n      try {\n         return valueOf(CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_UNDERSCORE, v));\n      } catch (IllegalArgumentException e) {\n         return UNRECOGNIZED;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/domain/Image.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Maps;\nimport com.google.common.collect.Sets;\n\n/**\n * \n * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-ItemType-DescribeImagesResponseItemType.html\"\n *      />\n */\npublic class Image implements Comparable<Image> {\n\n   private final String region;\n   private final Architecture architecture;\n   @Nullable\n   private final String name;\n   @Nullable\n   private final String description;\n   private final String imageId;\n   private final String imageLocation;\n   private final String imageOwnerId;\n   private final ImageState imageState;\n   private final String rawState;\n   private final ImageType imageType;\n   private final boolean isPublic;\n   @Nullable\n   private final String kernelId;\n   @Nullable\n   private final String platform;\n   private final Set<String> productCodes = Sets.newHashSet();\n   @Nullable\n   private final String ramdiskId;\n   private final RootDeviceType rootDeviceType;\n   @Nullable\n   private final String rootDeviceName;\n   private final Map<String, EbsBlockDevice> ebsBlockDevices = Maps.newHashMap();\n   private final Map<String, String> tags = Maps.newLinkedHashMap();\n   private final VirtualizationType virtualizationType;\n\n   public VirtualizationType getVirtualizationType() {\n      return virtualizationType;\n   }\n\n   private final Hypervisor hypervisor;\n\n   public Hypervisor getHypervisor() {\n      return hypervisor;\n   }\n\n   public Image(String region, Architecture architecture, @Nullable String name, @Nullable String description,\n            String imageId, String imageLocation, String imageOwnerId, ImageState imageState, String rawState,\n            ImageType imageType, boolean isPublic, Iterable<String> productCodes, @Nullable String kernelId,\n            @Nullable String platform, @Nullable String ramdiskId, RootDeviceType rootDeviceType,\n            @Nullable String rootDeviceName, Map<String, EbsBlockDevice> ebsBlockDevices,\n            Map<String, String> tags, VirtualizationType virtualizationType, Hypervisor hypervisor) {\n      this.region = checkNotNull(region, \"region\");\n      this.architecture = architecture;\n      this.imageId = checkNotNull(imageId, \"imageId\");\n      this.name = name;\n      this.description = description;\n      this.rootDeviceName = rootDeviceName;\n      this.imageLocation = checkNotNull(imageLocation, \"imageLocation\");\n      this.imageOwnerId = checkNotNull(imageOwnerId, \"imageOwnerId\");\n      this.imageState = checkNotNull(imageState, \"imageState\");\n      this.rawState = checkNotNull(rawState, \"rawState\");\n      this.imageType = checkNotNull(imageType, \"imageType\");\n      this.isPublic = isPublic;\n      this.kernelId = kernelId;\n      this.platform = platform;\n      Iterables.addAll(this.productCodes, checkNotNull(productCodes, \"productCodes\"));\n      this.ramdiskId = ramdiskId;\n      this.rootDeviceType = checkNotNull(rootDeviceType, \"rootDeviceType\");\n      this.ebsBlockDevices.putAll(checkNotNull(ebsBlockDevices, \"ebsBlockDevices\"));\n      this.tags.putAll(checkNotNull(tags, \"tags\"));\n      this.virtualizationType = checkNotNull(virtualizationType, \"virtualizationType\");\n      this.hypervisor = checkNotNull(hypervisor, \"hypervisor\");\n   }\n\n   public static enum ImageState {\n      /**\n       * the image is successfully registered and available for launching\n       */\n      AVAILABLE,\n      /**\n       * the image is deregistered and no longer available for launching\n       */\n      DEREGISTERED, UNRECOGNIZED;\n      public String value() {\n         return name().toLowerCase();\n      }\n\n      public static ImageState fromValue(String v) {\n         try {\n            return valueOf(v.toUpperCase());\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n   }\n\n   public static enum Architecture {\n      I386, X86_64, ARM64, UNRECOGNIZED;\n      public String value() {\n         return name().toLowerCase();\n      }\n\n      public static Architecture fromValue(String v) {\n         try {\n            return valueOf(v.toUpperCase());\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n   }\n\n   public static enum ImageType {\n\n      MACHINE, KERNEL, RAMDISK, UNRECOGNIZED;\n      public String value() {\n         return name().toLowerCase();\n      }\n\n      public static ImageType fromValue(String v) {\n         try {\n            return valueOf(v.toUpperCase());\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n\n   }\n\n   public static class EbsBlockDevice {\n      @Nullable\n      private final String snapshotId;\n      private final long volumeSize;\n      private final boolean deleteOnTermination;\n      private final String volumeType;\n      private final Integer iops;\n      private final boolean encrypted;\n\n      public EbsBlockDevice(@Nullable String snapshotId, long volumeSize, boolean deleteOnTermination,\n                            @Nullable String volumeType, @Nullable Integer iops, boolean encrypted) {\n         this.snapshotId = snapshotId;\n         this.volumeSize = volumeSize;\n         this.deleteOnTermination = deleteOnTermination;\n         this.volumeType = volumeType;\n         this.iops = iops;\n         this.encrypted = encrypted;\n      }\n\n      public String getSnapshotId() {\n         return snapshotId;\n      }\n\n      public long getVolumeSize() {\n         return volumeSize;\n      }\n\n      public boolean isDeleteOnTermination() {\n         return deleteOnTermination;\n      }\n\n      public String getVolumeType() {\n         return volumeType;\n      }\n\n      public Integer getIops() {\n         return iops;\n      }\n\n      public boolean isEncrypted() {\n         return encrypted;\n      }\n\n      @Override\n      public int hashCode() {\n         final int prime = 31;\n         int result = 1;\n         result = prime * result + (deleteOnTermination ? 1231 : 1237);\n         result = prime * result + ((snapshotId == null) ? 0 : snapshotId.hashCode());\n         result = prime * result + (int) (volumeSize ^ (volumeSize >>> 32));\n         result = prime * result + (encrypted ? 1249 : 1259);\n         result = prime * result + ((volumeType == null) ? 0 : volumeType.hashCode());\n         result = prime * result + ((iops == null) ? 0 : iops.hashCode());\n         return result;\n      }\n\n      @Override\n      public boolean equals(Object obj) {\n         if (this == obj)\n            return true;\n         if (obj == null)\n            return false;\n         if (getClass() != obj.getClass())\n            return false;\n         EbsBlockDevice other = (EbsBlockDevice) obj;\n         if (deleteOnTermination != other.deleteOnTermination)\n            return false;\n         if (encrypted != other.encrypted)\n            return false;\n         if (snapshotId == null) {\n            if (other.snapshotId != null)\n               return false;\n         } else if (!snapshotId.equals(other.snapshotId))\n            return false;\n         if (volumeType == null) {\n            if (other.volumeType != null)\n               return false;\n         } else if (!volumeType.equals(other.volumeType))\n            return false;\n         if (iops == null) {\n            if (other.iops != null)\n               return false;\n         } else if (!iops.equals(other.iops))\n            return false;\n         if (volumeSize != other.volumeSize)\n            return false;\n         return true;\n      }\n\n      @Override\n      public String toString() {\n         return \"EbsBlockDevice [deleteOnTermination=\" + deleteOnTermination + \", snapshotId=\" + snapshotId\n                 + \", volumeSize=\" + volumeSize + \", volumeType=\" + volumeType + \", iops=\" + iops\n                 + \", encrypted=\" + encrypted + \"]\";\n      }\n\n   }\n\n   /**\n    * To be removed in jclouds 1.6 <h4>Warning</h4>\n    * \n    * Especially on EC2 clones that may not support regions, this value is fragile. Consider\n    * alternate means to determine context.\n    */\n   @Deprecated\n   public String getRegion() {\n      return region;\n   }\n\n   /**\n    * The architecture of the image (i386 or x86_64).\n    */\n   public Architecture getArchitecture() {\n      return architecture;\n   }\n\n   /**\n    * The ID of the AMI.\n    */\n   public String getId() {\n      return imageId;\n   }\n\n   /**\n    * The location of the AMI.\n    */\n   public String getImageLocation() {\n      return imageLocation;\n   }\n\n   /**\n    * AWS Access Key ID of the image owner.\n    */\n   public String getImageOwnerId() {\n      return imageOwnerId;\n   }\n\n   /**\n    * Current state of the AMI. If the operation returns available, the image is successfully\n    * registered and avail able for launching. If the operation returns deregistered, the image is\n    * deregistered and no longer available for launching.\n    */\n   public ImageState getImageState() {\n      return imageState;\n   }\n\n   /**\n    * raw form of {@link #getImageState()} as taken directly from the api response xml document/\n    */\n   public String getRawState() {\n      return rawState;\n   }\n\n   /**\n    * The type of image (machine, kernel, or ramdisk).\n    */\n   public ImageType getImageType() {\n      return imageType;\n   }\n\n   /**\n    * Returns true if this image has public launch permissions. Returns false if it only has\n    * implicit and explicit launch permissions.\n    */\n   public boolean isPublic() {\n      return isPublic;\n   }\n\n   /**\n    * The kernel associated with the image, if any. Only applicable for machine images.\n    */\n   public String getKernelId() {\n      return kernelId;\n   }\n\n   /**\n    * The operating platform of the instance.\n    */\n   public String getPlatform() {\n      return platform;\n   }\n\n   /**\n    * Product codes of the AMI.\n    */\n   public Set<String> getProductCodes() {\n      return productCodes;\n   }\n\n   /**\n    * The RAM disk associated with the image, if any. Only applicable for machine images.\n    */\n   public String getRamdiskId() {\n      return ramdiskId;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public int compareTo(Image o) {\n      return (this == o) ? 0 : getId().compareTo(o.getId());\n   }\n\n   /**\n    * \n    * @return The root device type used by the AMI. The AMI can use an Amazon EBS or instance store\n    *         root device.\n    */\n   public RootDeviceType getRootDeviceType() {\n      return rootDeviceType;\n   }\n\n   public String getName() {\n      return name;\n   }\n\n   public String getDescription() {\n      return description;\n   }\n\n   public String getRootDeviceName() {\n      return rootDeviceName;\n   }\n\n   public Map<String, EbsBlockDevice> getEbsBlockDevices() {\n      return ebsBlockDevices;\n   }\n\n   public Map<String, String> getTags() {\n      return tags;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((architecture == null) ? 0 : architecture.hashCode());\n      result = prime * result + ((description == null) ? 0 : description.hashCode());\n      result = prime * result + ((ebsBlockDevices == null) ? 0 : ebsBlockDevices.hashCode());\n      result = prime * result + ((tags == null) ? 0 : tags.hashCode());\n      result = prime * result + ((imageId == null) ? 0 : imageId.hashCode());\n      result = prime * result + ((imageLocation == null) ? 0 : imageLocation.hashCode());\n      result = prime * result + ((imageOwnerId == null) ? 0 : imageOwnerId.hashCode());\n      result = prime * result + ((imageType == null) ? 0 : imageType.hashCode());\n      result = prime * result + (isPublic ? 1231 : 1237);\n      result = prime * result + ((kernelId == null) ? 0 : kernelId.hashCode());\n      result = prime * result + ((name == null) ? 0 : name.hashCode());\n      result = prime * result + ((platform == null) ? 0 : platform.hashCode());\n      result = prime * result + ((productCodes == null) ? 0 : productCodes.hashCode());\n      result = prime * result + ((ramdiskId == null) ? 0 : ramdiskId.hashCode());\n      result = prime * result + ((region == null) ? 0 : region.hashCode());\n      result = prime * result + ((rootDeviceName == null) ? 0 : rootDeviceName.hashCode());\n      result = prime * result + ((rootDeviceType == null) ? 0 : rootDeviceType.hashCode());\n      result = prime * result + ((virtualizationType == null) ? 0 : virtualizationType.hashCode());\n      result = prime * result + ((hypervisor == null) ? 0 : hypervisor.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      Image other = (Image) obj;\n      if (architecture == null) {\n         if (other.architecture != null)\n            return false;\n      } else if (!architecture.equals(other.architecture))\n         return false;\n      if (description == null) {\n         if (other.description != null)\n            return false;\n      } else if (!description.equals(other.description))\n         return false;\n      if (ebsBlockDevices == null) {\n         if (other.ebsBlockDevices != null)\n            return false;\n      } else if (!ebsBlockDevices.equals(other.ebsBlockDevices))\n         return false;\n      if (tags == null) {\n         if (other.tags != null)\n            return false;\n      } else if (!tags.equals(other.tags))\n         return false;\n      if (imageId == null) {\n         if (other.imageId != null)\n            return false;\n      } else if (!imageId.equals(other.imageId))\n         return false;\n      if (imageLocation == null) {\n         if (other.imageLocation != null)\n            return false;\n      } else if (!imageLocation.equals(other.imageLocation))\n         return false;\n      if (imageOwnerId == null) {\n         if (other.imageOwnerId != null)\n            return false;\n      } else if (!imageOwnerId.equals(other.imageOwnerId))\n         return false;\n      if (imageType == null) {\n         if (other.imageType != null)\n            return false;\n      } else if (!imageType.equals(other.imageType))\n         return false;\n      if (isPublic != other.isPublic)\n         return false;\n      if (kernelId == null) {\n         if (other.kernelId != null)\n            return false;\n      } else if (!kernelId.equals(other.kernelId))\n         return false;\n      if (name == null) {\n         if (other.name != null)\n            return false;\n      } else if (!name.equals(other.name))\n         return false;\n      if (platform == null) {\n         if (other.platform != null)\n            return false;\n      } else if (!platform.equals(other.platform))\n         return false;\n      if (productCodes == null) {\n         if (other.productCodes != null)\n            return false;\n      } else if (!productCodes.equals(other.productCodes))\n         return false;\n      if (ramdiskId == null) {\n         if (other.ramdiskId != null)\n            return false;\n      } else if (!ramdiskId.equals(other.ramdiskId))\n         return false;\n      if (region == null) {\n         if (other.region != null)\n            return false;\n      } else if (!region.equals(other.region))\n         return false;\n      if (rootDeviceName == null) {\n         if (other.rootDeviceName != null)\n            return false;\n      } else if (!rootDeviceName.equals(other.rootDeviceName))\n         return false;\n      if (rootDeviceType == null) {\n         if (other.rootDeviceType != null)\n            return false;\n      } else if (!rootDeviceType.equals(other.rootDeviceType))\n         return false;\n      if (virtualizationType == null) {\n         if (other.virtualizationType != null)\n            return false;\n      } else if (!virtualizationType.equals(other.virtualizationType))\n         return false;\n      if (hypervisor == null) {\n         if (other.hypervisor != null)\n            return false;\n      } else if (!hypervisor.equals(other.hypervisor))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"Image [architecture=\" + architecture + \", description=\" + description + \", ebsBlockDevices=\"\n               + ebsBlockDevices + \", imageId=\" + imageId + \", imageLocation=\" + imageLocation + \", imageOwnerId=\"\n               + imageOwnerId + \", imageState=\" + rawState + \", imageType=\" + imageType + \", isPublic=\" + isPublic\n               + \", kernelId=\" + kernelId + \", name=\" + name + \", platform=\" + platform + \", productCodes=\"\n               + productCodes + \", ramdiskId=\" + ramdiskId + \", region=\" + region + \", rootDeviceName=\"\n               + rootDeviceName + \", rootDeviceType=\" + rootDeviceType + \", virtualizationType=\" + virtualizationType\n               + \", hypervisor=\" + hypervisor + \", tags=\" + tags + \"]\";\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/domain/ImageAttribute.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.domain;\n\npublic enum ImageAttribute {\n\n   /**\n    * the product code associated with the AMI.\n    */\n   PRODUCT_CODES,\n\n   /**\n    * the ID of the RAM disk associated with the AMI.\n    */\n   RAMDISK,\n\n   /**\n    * the ID of the kernel associated with the AMI.\n    */\n   KERNEL,\n   /**\n    * the launch permissions of the AMI.\n    */\n   LAUNCH_PERMISSION,\n   /**\n    * the operating system platform.\n    */\n   PLATFORM,\n   /**\n    * the mapping that defines native device names to use when exposing virtual devices.\n    */\n   BLOCK_DEVICE_MAPPING, UNRECOGNIZED;\n   public String value() {\n      switch (this) {\n         case PRODUCT_CODES:\n            return \"productCodes\";\n         case RAMDISK:\n            return \"ramdisk\";\n         case KERNEL:\n            return \"kernel\";\n         case LAUNCH_PERMISSION:\n            return \"launchPermission\";\n         case PLATFORM:\n            return \"platform\";\n         case BLOCK_DEVICE_MAPPING:\n            return \"blockDeviceMapping\";\n         default:\n            throw new IllegalArgumentException(\"unmapped attribute: \" + super.name());\n      }\n   }\n\n   @Override\n   public String toString() {\n      return value();\n   }\n\n   public static ImageAttribute fromValue(String attribute) {\n      if (\"productCodes\".equals(attribute))\n         return PRODUCT_CODES;\n      else if (\"ramdisk\".equals(attribute))\n         return RAMDISK;\n      else if (\"kernel\".equals(attribute))\n         return KERNEL;\n      else if (\"launchPermission\".equals(attribute))\n         return LAUNCH_PERMISSION;\n      else if (\"platform\".equals(attribute))\n         return PLATFORM;\n      else if (\"blockDeviceMapping\".equals(attribute))\n         return BLOCK_DEVICE_MAPPING;\n      else\n         return UNRECOGNIZED;\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/domain/InstanceState.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.CaseFormat;\n\npublic enum InstanceState {\n\n   /**\n    * the instance is in the process of being launched\n    */\n   PENDING,\n\n   /**\n    * the instance launched (although the boot process might not be completed)\n    */\n   RUNNING,\n\n   /**\n    * the instance started shutting down\n    */\n   SHUTTING_DOWN,\n   /**\n    * the instance terminated\n    */\n   TERMINATED,\n   /**\n    * the instance is stopping\n    */\n   STOPPING,\n   /**\n    * the instance is stopped\n    */\n   STOPPED, UNRECOGNIZED;\n\n   public String value() {\n      return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_HYPHEN, name());\n   }\n\n   @Override\n   public String toString() {\n      return value();\n   }\n\n   public static InstanceState fromValue(String state) {\n      try {\n         return valueOf(CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_UNDERSCORE, checkNotNull(state, \"state\")));\n      } catch (IllegalArgumentException e) {\n         return UNRECOGNIZED;\n      }\n   }\n\n   public static InstanceState fromValue(int v) {\n      switch (v) {\n         case 0:\n            return PENDING;\n         case 16:\n            return RUNNING;\n         case 32:\n            return SHUTTING_DOWN;\n         case 48:\n            return TERMINATED;\n         case 64:\n            return STOPPING;\n         case 80:\n            return STOPPED;\n         default:\n            return UNRECOGNIZED;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/domain/InstanceStateChange.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\n\n/**\n * \n * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-ItemType-TerminateInstancesResponseInfoType.html\"\n *      />\n */\npublic class InstanceStateChange implements Comparable<InstanceStateChange> {\n\n   private final String region;\n   private final String instanceId;\n   private final InstanceState currentState;\n   private final InstanceState previousState;\n\n   public int compareTo(InstanceStateChange o) {\n      return (this == o) ? 0 : getInstanceId().compareTo(o.getInstanceId());\n   }\n\n   public InstanceStateChange(String region, String instanceId, InstanceState currentState,\n            InstanceState previousState) {\n      this.region = checkNotNull(region, \"region\");\n      this.instanceId = instanceId;\n      this.currentState = currentState;\n      this.previousState = previousState;\n   }\n\n   /**\n    * To be removed in jclouds 1.6 <h4>Warning</h4>\n    * \n    * Especially on EC2 clones that may not support regions, this value is fragile. Consider\n    * alternate means to determine context.\n    */\n   @Deprecated\n   public String getRegion() {\n      return region;\n   }\n\n   public String getInstanceId() {\n      return instanceId;\n   }\n\n   public InstanceState getCurrentState() {\n      return currentState;\n   }\n\n   public InstanceState getPreviousState() {\n      return previousState;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((instanceId == null) ? 0 : instanceId.hashCode());\n      result = prime * result + ((previousState == null) ? 0 : previousState.hashCode());\n      result = prime * result + ((region == null) ? 0 : region.hashCode());\n      result = prime * result + ((currentState == null) ? 0 : currentState.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      InstanceStateChange other = (InstanceStateChange) obj;\n      if (instanceId == null) {\n         if (other.instanceId != null)\n            return false;\n      } else if (!instanceId.equals(other.instanceId))\n         return false;\n      if (previousState == null) {\n         if (other.previousState != null)\n            return false;\n      } else if (!previousState.equals(other.previousState))\n         return false;\n      if (region == null) {\n         if (other.region != null)\n            return false;\n      } else if (!region.equals(other.region))\n         return false;\n      if (currentState == null) {\n         if (other.currentState != null)\n            return false;\n      } else if (!currentState.equals(other.currentState))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"InstanceStateChange [currentState=\" + currentState + \", instanceId=\" + instanceId\n               + \", previousState=\" + previousState + \", region=\" + region + \"]\";\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/domain/InstanceType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.domain;\n\npublic class InstanceType {\n\n   /**\n    * Micro Instance\n    * <ul>\n    * <li>613 MB of memory</li>\n    * <li>up to 2 ECUs (for short periodic bursts)</li>\n    * <li>No instance storage (EBS storage only)</li>\n    * <li>32-bit or 64-bit platform</li>\n    * </ul>\n    */\n   public static final String T1_MICRO = \"t1.micro\";\n\n   /**\n    * Micro Burstable Performance Instance\n    * <ul>\n    * <li>512 MB memory</li>\n    * <li>1 vCPU / 10% baseline performance</li>\n    * <li>No instance storage (EBS storage only)</li>\n    * <li>64-bit platform</li>\n    * </ul>\n    */\n   public static final String T2_NANO = \"t2.nano\";\n\n   /**\n    * Micro Burstable Performance Instance\n    * <ul>\n    * <li>1 GB memory</li>\n    * <li>1 vCPU / 10% baseline performance</li>\n    * <li>No instance storage (EBS storage only)</li>\n    * <li>64-bit platform</li>\n    * </ul>\n    */\n   public static final String T2_MICRO = \"t2.micro\";\n\n   /**\n    * Micro Burstable Performance Instance\n    * <ul>\n    * <li>2 GB memory</li>\n    * <li>1 vCPU / 20% baseline performance</li>\n    * <li>No instance storage (EBS storage only)</li>\n    * <li>64-bit platform</li>\n    * </ul>\n    */\n   public static final String T2_SMALL = \"t2.small\";\n\n   /**\n    * Micro Burstable Performance Instance\n    * <ul>\n    * <li>4 GB memory</li>\n    * <li>2 vCPU / 40% baseline performance</li>\n    * <li>No instance storage (EBS storage only)</li>\n    * <li>64-bit platform</li>\n    * </ul>\n    */\n   public static final String T2_MEDIUM = \"t2.medium\";\n\n   /**\n    * Micro Burstable Performance Instance\n    * <ul>\n    * <li>8 GB memory</li>\n    * <li>2 vCPU / 40% baseline performance</li>\n    * <li>No instance storage (EBS storage only)</li>\n    * <li>64-bit platform</li>\n    * </ul>\n    */\n   public static final String T2_LARGE = \"t2.large\";\n\n   /**\n    * Micro Burstable Performance Instance\n    * <ul>\n    * <li>16 GB memory</li>\n    * <li>4 vCPU / 40% baseline performance</li>\n    * <li>No instance storage (EBS storage only)</li>\n    * <li>64-bit platform</li>\n    * </ul>\n    */\n   public static final String T2_XLARGE = \"t2.xlarge\";\n\n   /**\n    * Micro Burstable Performance Instance\n    * <ul>\n    * <li>32 GB memory</li>\n    * <li>8 vCPU / 40% baseline performance</li>\n    * <li>No instance storage (EBS storage only)</li>\n    * <li>64-bit platform</li>\n    * </ul>\n    */\n   public static final String T2_2XLARGE = \"t2.2xlarge\";\n\n   /**\n    * Micro Burstable Performance Instance\n    * <ul>\n    * <li>512 MB memory</li>\n    * <li>2 vCPU / 10% baseline performance</li>\n    * <li>No instance storage (EBS storage only)</li>\n    * <li>64-bit platform</li>\n    * </ul>\n    */\n   public static final String T3_NANO = \"t3.nano\";\n\n   /**\n    * Micro Burstable Performance Instance\n    * <ul>\n    * <li>1 GB memory</li>\n    * <li>2 vCPU / 10% baseline performance</li>\n    * <li>No instance storage (EBS storage only)</li>\n    * <li>64-bit platform</li>\n    * </ul>\n    */\n   public static final String T3_MICRO = \"t3.micro\";\n\n   /**\n    * Micro Burstable Performance Instance\n    * <ul>\n    * <li>2 GB memory</li>\n    * <li>2 vCPU / 10% baseline performance</li>\n    * <li>No instance storage (EBS storage only)</li>\n    * <li>64-bit platform</li>\n    * </ul>\n    */\n   public static final String T3_SMALL = \"t3.small\";\n\n   /**\n    * Micro Burstable Performance Instance\n    * <ul>\n    * <li>4 GB memory</li>\n    * <li>2 vCPU / 10% baseline performance</li>\n    * <li>No instance storage (EBS storage only)</li>\n    * <li>64-bit platform</li>\n    * </ul>\n    */\n   public static final String T3_MEDIUM = \"t3.medium\";\n\n   /**\n    * Micro Burstable Performance Instance\n    * <ul>\n    * <li>8 GB memory</li>\n    * <li>2 vCPU / 10% baseline performance</li>\n    * <li>No instance storage (EBS storage only)</li>\n    * <li>64-bit platform</li>\n    * </ul>\n    */\n   public static final String T3_LARGE = \"t3.large\";\n\n   /**\n    * Micro Burstable Performance Instance\n    * <ul>\n    * <li>16 GB memory</li>\n    * <li>4 vCPU / 10% baseline performance</li>\n    * <li>No instance storage (EBS storage only)</li>\n    * <li>64-bit platform</li>\n    * </ul>\n    */\n   public static final String T3_XLARGE = \"t3.xlarge\";\n\n   /**\n    * Micro Burstable Performance Instance\n    * <ul>\n    * <li>32 GB memory</li>\n    * <li>8 vCPU / 10% baseline performance</li>\n    * <li>No instance storage (EBS storage only)</li>\n    * <li>64-bit platform</li>\n    * </ul>\n    */\n   public static final String T3_2XLARGE = \"t3.2xlarge\";\n\n    /**\n    * Small Instance\n    * <ul>\n    * <li>1.7 GB memory</li>\n    * <li>1 EC2 Compute Unit (1 virtual core with 1 EC2 Compute Unit)</li>\n    * <li>160 GB instance storage (150 GB plus 10 GB root partition)</li>\n    * <li>32-bit or 64-bit platform</li>\n    * <li>I/O Performance: Moderate</li>\n    * </ul>\n    */\n   public static final String M1_SMALL = \"m1.small\";\n\n   /**\n    * Medium Instance\n    * <ul>\n    * <li>3.75 GB memory</li>\n    * <li>2 EC2 Compute Unit (1 virtual core with 2 EC2 Compute Unit)</li>\n    * <li>410 GB instance storage</li>\n    * <li>32-bit or 64-bit platform</li>\n    * <li>I/O Performance: Moderate</li>\n    * </ul>\n    */\n   public static final String M1_MEDIUM = \"m1.medium\";\n\n   /**\n    * Large Instance\n    * <ul>\n    * <li>7.5 GB memory</li>\n    * <li>4 EC2 Compute Units (2 virtual cores with 2 EC2 Compute Units each)</li>\n    * <li>850 GB instance storage (2x420 GB plus 10 GB root partition)</li>\n    * <li>64-bit platform</li>\n    * <li>I/O Performance: High</li>\n    * </ul>\n    */\n   public static final String M1_LARGE = \"m1.large\";\n\n   /**\n    * Extra Large Instance\n    * <ul>\n    * <li>15 GB memory</li>\n    * <li>8 EC2 Compute Units (4 virtual cores with 2 EC2 Compute Units each)</li>\n    * <li>1690 GB instance storage (4x420 GB plus 10 GB root partition)</li>\n    * <li>64-bit platform</li>\n    * <li>I/O Performance: High</li>\n    * </ul>\n    */\n   public static final String M1_XLARGE = \"m1.xlarge\";\n\n   /**\n    * High-Memory Extra Large Instance\n    * <ul>\n    * <li>17.1 GB of memory</li>\n    * <li>6.5 EC2 Compute Units (2 virtual cores with 3.25 EC2 Compute Units\n    * each)</li>\n    * <li>420 GB of instance storage</li>\n    * <li>64-bit platform</li>\n    * <li>I/O Performance: Moderate</li>\n    * </ul>\n    */\n   public static final String M2_XLARGE = \"m2.xlarge\";\n\n   /**\n    * High-Memory Double Extra Large Instance\n    * <ul>\n    * <li>34.2 GB of memory</li>\n    * <li>13 EC2 Compute Units (4 virtual cores with 3.25 EC2 Compute Units\n    * each)</li>\n    * <li>850 GB of instance storage</li>\n    * <li>64-bit platform</li>\n    * <li>I/O Performance: High</li>\n    * </ul>\n    */\n   public static final String M2_2XLARGE = \"m2.2xlarge\";\n\n   /**\n    * High-Memory Quadruple Extra Large Instance\n    * <ul>\n    * <li>68.4 GB of memory</li>\n    * <li>26 EC2 Compute Units (8 virtual cores with 3.25 EC2 Compute Units\n    * each)</li>\n    * <li>1690 GB of instance storage</li>\n    * <li>64-bit platform</li>\n    * <li>I/O Performance: High</li>\n    * </ul>\n    */\n   public static final String M2_4XLARGE = \"m2.4xlarge\";\n\n   /**\n    * M3 Medium Instance\n    * <ul>\n    * <li>3.75 GiB memory</li>\n    * <li>3 EC2 Compute Units (1 virtual core with 3 EC2 Compute Units)</li>\n    * <li>1 SSD-based volume with 4 GiB of instance storage</li>\n    * <li>32-bit or 64-bit platform</li>\n    * <li>I/O Performance: Moderate</li>\n    * </ul>\n    */\n   public static final String M3_MEDIUM = \"m3.medium\";\n\n   /**\n    * M3 Large Instance\n    * <ul>\n    * <li>7 GiB memory</li>\n    * <li>6.5 EC2 Compute Units (2 virtual cores with 3.25 EC2 Compute Units each)</li>\n    * <li>1 SSD-based volume with 32 GiB of instance storage</li>\n    * <li>32-bit or 64-bit platform</li>\n    * <li>I/O Performance: Moderate</li>\n    * </ul>\n    */\n   public static final String M3_LARGE = \"m3.large\";\n\n   /**\n    * M3 Extra Large Instance\n    * <ul>\n    * <li>15 GiB memory</li>\n    * <li>13 EC2 Compute Units (4 virtual cores with 3.25 EC2 Compute Units each)</li>\n    * <li>EBS storage only</li>\n    * <li>64-bit platform</li>\n    * <li>I/O Performance: Moderate</li>\n    * </ul>\n    */\n   public static final String M3_XLARGE = \"m3.xlarge\";\n\n   /**\n    * M3 Double Extra Large Instance\n    * <ul>\n    * <li>30 GiB memory</li>\n    * <li>26 EC2 Compute Units (8 virtual cores with 3.25 EC2 Compute Units each)</li>\n    * <li>EBS storage only</li>\n    * <li>64-bit platform</li>\n    * <li>I/O Performance: High</li>\n    * </ul>\n    */\n   public static final String M3_2XLARGE = \"m3.2xlarge\";\n   \n   /**\n    * M4 Large Instance\n    * <ul>\n    * <li>8 GiB memory</li>\n    * <li>6.5 EC2 Compute Units (2 virtual cores with 3.25 EC2 Compute Units each)</li>\n    * <li>EBS storage only</li>\n    * <li>64-bit platform</li>\n    * <li>I/O Performance: Moderate</li>\n    * </ul>\n    */\n   public static final String M4_LARGE = \"m4.large\";\n\n   /**\n    * M4 Extra Large Instance\n    * <ul>\n    * <li>16 GiB memory</li>\n    * <li>13 EC2 Compute Units (4 virtual cores with 3.25 EC2 Compute Units each)</li>\n    * <li>EBS storage only</li>\n    * <li>64-bit platform</li>\n    * <li>I/O Performance: High</li>\n    * </ul>\n    */\n   public static final String M4_XLARGE = \"m4.xlarge\";\n\n   /**\n    * M4 Double Extra Large Instance\n    * <ul>\n    * <li>32 GiB memory</li>\n    * <li>26 EC2 Compute Units (8 virtual cores with 3.25 EC2 Compute Units each)</li>\n    * <li>EBS storage only</li>\n    * <li>64-bit platform</li>\n    * <li>I/O Performance: High</li>\n    * </ul>\n    */\n   public static final String M4_2XLARGE = \"m4.2xlarge\";\n\n   /**\n    * M4 Quadruple Extra Large Instance\n    * <ul>\n    * <li>64 GiB memory</li>\n    * <li>53.5 EC2 Compute Units (16 virtual cores with 3.34375 EC2 Compute Units each)</li>\n    * <li>EBS storage only</li>\n    * <li>64-bit platform</li>\n    * <li>I/O Performance: High</li>\n    * </ul>\n    */\n   public static final String M4_4XLARGE = \"m4.4xlarge\";\n\n   /**\n    * M4 Decuple Extra Large Instance\n    * <ul>\n    * <li>160 GiB memory</li>\n    * <li>124.5 EC2 Compute Units (40 virtual cores with 3.1125 EC2 Compute Units each)</li>\n    * <li>EBS storage only</li>\n    * <li>64-bit platform</li>\n    * <li>I/O Performance: High</li>\n    * </ul>\n    */\n   public static final String M4_10XLARGE = \"m4.10xlarge\";\n\n   /**\n    * M4 Sexdecuple Extra Large Instance\n    * <ul>\n    * <li>256 GiB memory</li>\n    * <li>199.2 EC2 Compute Units (64 virtual cores with 3.1125 EC2 Compute Units each)</li>\n    * <li>EBS storage only</li>\n    * <li>64-bit platform</li>\n    * <li>I/O Performance: High</li>\n    * </ul>\n    */\n   public static final String M4_16XLARGE = \"m4.16xlarge\";\n\n   /**\n    * M5 Large Instance\n    * <ul>\n    * <li>8 GiB memory</li>\n    * <li>5 EC2 Compute Units (2 virtual cores with 2.5 EC2 Compute Units each)</li>\n    * <li>EBS storage only</li>\n    * <li>64-bit platform</li>\n    * <li>I/O Performance: Moderate</li>\n    * </ul>\n    */\n   public static final String M5_LARGE = \"m5.large\";\n\n   /**\n    * M5 Extra Large Instance\n    * <ul>\n    * <li>16 GiB memory</li>\n    * <li>10 EC2 Compute Units (4 virtual cores with 2.5 EC2 Compute Units each)</li>\n    * <li>EBS storage only</li>\n    * <li>64-bit platform</li>\n    * <li>I/O Performance: High</li>\n    * </ul>\n    */\n   public static final String M5_XLARGE = \"m5.xlarge\";\n\n   /**\n    * M5 Double Extra Large Instance\n    * <ul>\n    * <li>32 GiB memory</li>\n    * <li>26 EC2 Compute Units (8 virtual cores with 2.5 EC2 Compute Units each)</li>\n    * <li>EBS storage only</li>\n    * <li>64-bit platform</li>\n    * <li>I/O Performance: High</li>\n    * </ul>\n    */\n   public static final String M5_2XLARGE = \"m5.2xlarge\";\n\n   /**\n    * M5 Quadruple Extra Large Instance\n    * <ul>\n    * <li>64 GiB memory</li>\n    * <li>40 EC2 Compute Units (16 virtual cores with 2.5 EC2 Compute Units each)</li>\n    * <li>EBS storage only</li>\n    * <li>64-bit platform</li>\n    * <li>I/O Performance: High</li>\n    * </ul>\n    */\n   public static final String M5_4XLARGE = \"m5.4xlarge\";\n\n   /**\n    * M5 12x Extra Large Instance\n    * <ul>\n    * <li>192 GiB memory</li>\n    * <li>144 EC2 Compute Units (48 virtual cores with 2.5 EC2 Compute Units each)</li>\n    * <li>EBS storage only</li>\n    * <li>64-bit platform</li>\n    * <li>I/O Performance: High</li>\n    * </ul>\n    */\n   public static final String M5_12XLARGE = \"m5.12xlarge\";\n\n   /**\n    * M5 24x Extra Large Instance\n    * <ul>\n    * <li>384 GiB memory</li>\n    * <li>288 EC2 Compute Units (96 virtual cores with 2.5 EC2 Compute Units each)</li>\n    * <li>EBS storage only</li>\n    * <li>64-bit platform</li>\n    * <li>I/O Performance: High</li>\n    * </ul>\n    */\n   public static final String M5_24XLARGE = \"m5.24xlarge\";\n\n   /**\n    * M5D Large Instance\n    * <ul>\n    * <li>8 GiB memory</li>\n    * <li>5 EC2 Compute Units (2 virtual cores with 2.5 EC2 Compute Units each)</li>\n    * <li>1 x 75 NVMe SSD</li>\n    * <li>EBS storage</li>\n    * <li>64-bit platform</li>\n    * <li>I/O Performance: Moderate</li>\n    * </ul>\n    */\n   public static final String M5D_LARGE = \"m5d.large\";\n\n   /**\n    * M5D Extra Large Instance\n    * <ul>\n    * <li>16 GiB memory</li>\n    * <li>10 EC2 Compute Units (4 virtual cores with 2.5 EC2 Compute Units each)</li>\n    * <li>1 x 150 NVMe SSD</li>\n    * <li>64-bit platform</li>\n    * <li>I/O Performance: High</li>\n    * </ul>\n    */\n   public static final String M5D_XLARGE = \"m5d.xlarge\";\n\n   /**\n    * M5D Double Extra Large Instance\n    * <ul>\n    * <li>32 GiB memory</li>\n    * <li>26 EC2 Compute Units (8 virtual cores with 2.5 EC2 Compute Units each)</li>\n    * <li>1 x 300 NVMe SSD</li>\n    * <li>64-bit platform</li>\n    * <li>I/O Performance: High</li>\n    * </ul>\n    */\n   public static final String M5D_2XLARGE = \"m5d.2xlarge\";\n\n   /**\n    * M5D Quadruple Extra Large Instance\n    * <ul>\n    * <li>64 GiB memory</li>\n    * <li>40 EC2 Compute Units (16 virtual cores with 2.5 EC2 Compute Units each)</li>\n    * <li> x 300 NVMe SSD</li>\n    * <li>64-bit platform</li>\n    * <li>I/O Performance: High</li>\n    * </ul>\n    */\n   public static final String M5D_4XLARGE = \"m5d.4xlarge\";\n\n   /**\n    * M5D 12x Extra Large Instance\n    * <ul>\n    * <li>192 GiB memory</li>\n    * <li>144 EC2 Compute Units (48 virtual cores with 2.5 EC2 Compute Units each)</li>\n    * <li>2 x 900 NVMe SSD</li>\n    * <li>64-bit platform</li>\n    * <li>I/O Performance: High</li>\n    * </ul>\n    */\n   public static final String M5D_12XLARGE = \"m5d.12xlarge\";\n\n   /**\n    * M5D 24x Extra Large Instance\n    * <ul>\n    * <li>384 GiB memory</li>\n    * <li>288 EC2 Compute Units (96 virtual cores with 2.5 EC2 Compute Units each)</li>\n    * <li>4 x 900 NVMe SSD</li>\n    * <li>64-bit platform</li>\n    * <li>I/O Performance: High</li>\n    * </ul>\n    */\n   public static final String M5D_24XLARGE = \"m5d.24xlarge\";\n\n   /**\n    * High-CPU Medium Instance\n    * <ul>\n    * <li>1.7 GB of memory</li>\n    * <li>5 EC2 Compute Units (2 virtual cores with 2.5 EC2 Compute Units each)</li>\n    * <li>350 GB of instance storage</li>\n    * <li>32-bit platform</li>\n    * <li>I/O Performance: Moderate</li>\n    * </ul>\n    */\n   public static final String C1_MEDIUM = \"c1.medium\";\n\n   /**\n    * High-CPU Extra Large Instance\n    * <ul>\n    * <li>7 GB of memory</li>\n    * <li>20 EC2 Compute Units (8 virtual cores with 2.5 EC2 Compute Units each)\n    * </li>\n    * <li>1690 GB of instance storage</li>\n    * <li>64-bit platform</li>\n    * <li>I/O Performance: High</li>\n    * </ul>\n    */\n   public static final String C1_XLARGE = \"c1.xlarge\";\n   \n   /**\n    * Cluster Compute Instance\n    * <ul>\n    * <li>22 GB of memory</li>\n    * <li>33.5 EC2 Compute Units (2 x Intel Xeon X5570, quad-core \"Nehalem\"\n    * architecture)</li>\n    * <li>1690 GB of 64-bit storage (2 x 840 GB, plus 10 GB root partition)</li>\n    * <li>10 Gbps Ethernet</li>\n    * <li>64-bit platform</li>\n    * <li>I/O Performance: High</li>\n    * </ul>\n    */\n   public static final String CG1_4XLARGE = \"cg1.4xlarge\";\n   \n   /**\n    * Cluster Compute Instance\n    * <ul>\n    * <li>23 GB of memory</li>\n    * <li>33.5 EC2 Compute Units (2 x Intel Xeon X5570, quad-core \"Nehalem\"\n    * architecture)</li>\n    * <li>1690 GB of 64-bit storage (2 x 840 GB, plus 10 GB root partition)</li>\n    * <li>10 Gbps Ethernet</li>\n    * <li>64-bit platform</li>\n    * <li>I/O Performance: High</li>\n    * </ul>\n    */\n   public static final String CC1_4XLARGE = \"cc1.4xlarge\";\n   \n   /**\n    * Cluster Compute Eight Extra Large specifications\n    * <ul>\n    * <li>60.5 GB of memory</li>\n    * <li>88 EC2 Compute Units (Eight-core 2 x Intel Xeon)</li>\n    * <li>3370 GB of 64-bit storage (4 x 840 GB, plus 10 GB root partition)</li>\n    * <li>10 Gbps Ethernet</li>\n    * <li>64-bit platform</li>\n    * <li>I/O Performance: High</li>\n    * </ul>\n    */\n   public static final String CC2_8XLARGE = \"cc2.8xlarge\";\n\n   /**\n    * High I/O Quadruple Extra Large specifications\n    * <ul>\n    * <li>60.5 GB of memory</li>\n    * <li>35 EC2 Compute Units (16 virtual cores)</li>\n    * <li>2 SSD-based volumes each with 1024 GB of instance storage</li>\n    * <li>64-bit platform</li>\n    * <li>I/O Performance: Very High (10 Gigabit Ethernet)</li>\n    * <li>Storage I/O Performance: Very High**</li>\n    * </ul>\n    */\n   public static final String HI1_4XLARGE = \"hi1.4xlarge\";\n\n   /**\n    * High Storage Eight Extra Large\n    * <ul>\n    * <li>117 GiB of memory</li>\n    * <li>35 EC2 Compute Units (16 virtual cores*)</li>\n    * <li>24 hard disk drives each with 2 TB of instance storage</li>\n    * <li>64-bit platform</li>\n    * <li>I/O Performance: Very High (10 Gigabit Ethernet)</li>\n    * <li>Storage I/O Performance: Very High**</li>\n    * </ul>\n    */\n   public static final String HS1_8XLARGE = \"hs1.8xlarge\";\n\n   /**\n    * GPU Instance Double Extra Large\n    * <ul>\n    * <li>15 GiB of memory</li>\n    * <li>26 EC2 Compute Units (8 virtual cores*), 1xNVIDIA GRID GPU (Kepler GK104)</li>\n    * <li>60 GB instance storage</li>\n    * <li>64-bit platform</li>\n    * <li>I/O Performance: High</li>\n    * </ul>\n    */\n   public static final String G2_2XLARGE = \"g2.2xlarge\";\n\n   /**\n    * C3 High-CPU Large\n    * <ul>\n    *    <li>3.75 GiB of memory</li>\n    *    <li>7 EC2 Compute Units (2 virtual cores)</li>\n    *    <li>2 SSD-based volumes each with 16 GiB of instance storage</li>\n    *    <li>64-bit platform</li>\n    *    <li>I/O Performance: Moderate</li>\n    * </ul>\n    */\n   public static final String C3_LARGE = \"c3.large\";\n\n   /**\n    * C3 High-CPU Extra Large\n    * <ul>\n    *    <li>7 GiB of memory</li>\n    *    <li>14 EC2 Compute Units (4 virtual cores)</li>\n    *    <li>2 SSD-based volumes each with 40 GiB of instance storage</li>\n    *    <li>64-bit platform</li>\n    *    <li>I/O Performance: High</li>\n    * </ul>\n    */\n   public static final String C3_XLARGE = \"c3.xlarge\";\n\n   /**\n    * C3 High-CPU Double Extra Large\n    * <ul>\n    *    <li>15 GiB of memory</li>\n    *    <li>28 EC2 Compute Units (8 virtual cores)</li>\n    *    <li>2 SSD-based volumes each with 80 GiB of instance storage</li>\n    *    <li>64-bit platform</li>\n    *    <li>I/O Performance: High</li>\n    * </ul>\n    */\n   public static final String C3_2XLARGE = \"c3.2xlarge\";\n\n   /**\n    * C3 High-CPU Quadruple Extra Large\n    * <ul>\n    *    <li>30 GiB of memory</li>\n    *    <li>55 EC2 Compute Units (16 virtual cores)</li>\n    *    <li>2 SSD-based volumes each with 160 GiB of instance storage</li>\n    *    <li>64-bit platform</li>\n    *    <li>I/O Performance: High</li>\n    * </ul>\n    */\n   public static final String C3_4XLARGE = \"c3.4xlarge\";\n\n   /**\n    * C3 High-CPU Octuple Extra Large\n    * <ul>\n    *    <li>60 GiB of memory</li>\n    *    <li>108 EC2 Compute Units (32 virtual cores)</li>\n    *    <li>2 SSD-based volumes each with 320 GiB of instance storage</li>\n    *    <li>64-bit platform</li>\n    *    <li>I/O Performance: High</li>\n    * </ul>\n    */\n   public static final String C3_8XLARGE = \"c3.8xlarge\";\n\n   /**\n    * C4 Compute-optimized Extra Large\n    * <ul>\n    *    <li>7.5 GiB of memory</li>\n    *    <li>4 vCPU</li>\n    *    <li>No instance storage (EBS storage only)</li>\n    *    <li>750 Mbps Dedicated EBS Throughput</li>\n    * </ul>\n    */\n   public static final String C4_XLARGE = \"c4.xlarge\";\n\n   /**\n    * C4 Compute-optimized Double Extra Large\n    * <ul>\n    *    <li>8 GiB of memory</li>\n    *    <li>15 vCPU</li>\n    *    <li>No instance storage (EBS storage only)</li>\n    *    <li>1000 Mbps Dedicated EBS Throughput</li>\n    * </ul>\n    */\n   public static final String C4_2XLARGE = \"c4.2xlarge\";\n\n   /**\n    * C4 Compute-optimized Quadruple Extra Large\n    * <ul>\n    *    <li>30 GiB of memory</li>\n    *    <li>16 vCPU</li>\n    *    <li>No instance storage (EBS storage only)</li>\n    *    <li>2000 Mbps Dedicated EBS Throughput</li>\n    * </ul>\n    */\n   public static final String C4_4XLARGE = \"c4.4xlarge\";\n\n   /**\n    * C4 Compute-optimized Octuple Extra Large\n    * <ul>\n    *    <li>60 GiB of memory</li>\n    *    <li>36 vCPU</li>\n    *    <li>No instance storage (EBS storage only)</li>\n    *    <li>4000 Mbps Dedicated EBS Throughput</li>\n    * </ul>\n    */\n   public static final String C4_8XLARGE = \"c4.8xlarge\";\n\n   /**\n    * C4 Compute-optimized Large\n    * <ul>\n    *    <li>3.75 GiB of memory</li>\n    *    <li>2 vCPU</li>\n    *    <li>No instance storage (EBS storage only)</li>\n    *    <li>500 Mbps Dedicated EBS Throughput</li>\n    * </ul>\n    */\n   public static final String C4_LARGE = \"c4.large\";\n\n   /**\n    * C5 Compute-optimized Large\n    * <ul>\n    *    <li>4 GiB of memory</li>\n    *    <li>2 vCPU</li>\n    *    <li>No instance storage (EBS storage only)</li>\n    *    <li>Up to 25 Gbps of network bandwidth using Elastic Network Adapter (ENA)-based Enhanced Networking</li>\n    * </ul>\n    */\n   public static final String C5_LARGE = \"c5.large\";\n\n   /**\n    * C5 Compute-optimized X Large\n    * <ul>\n    *    <li>8 GiB of memory</li>\n    *    <li>4 vCPU</li>\n    *    <li>No instance storage (EBS storage only)</li>\n    *    <li>Up to 25 Gbps of network bandwidth using Elastic Network Adapter (ENA)-based Enhanced Networking</li>\n    * </ul>\n    */\n   public static final String C5_XLARGE = \"c5.xlarge\";\n\n   /**\n    * C5 Compute-optimized 2x Large\n    * <ul>\n    *    <li>16 GiB of memory</li>\n    *    <li>8 vCPU</li>\n    *    <li>No instance storage (EBS storage only)</li>\n    *    <li>Up to 25 Gbps of network bandwidth using Elastic Network Adapter (ENA)-based Enhanced Networking</li>\n    * </ul>\n    */\n   public static final String C5_2XLARGE = \"c5.2xlarge\";\n\n   /**\n    * C5 Compute-optimized 4x Large\n    * <ul>\n    *    <li>32 GiB of memory</li>\n    *    <li>16 vCPU</li>\n    *    <li>No instance storage (EBS storage only)</li>\n    *    <li>Up to 25 Gbps of network bandwidth using Elastic Network Adapter (ENA)-based Enhanced Networking</li>\n    * </ul>\n    */\n   public static final String C5_4XLARGE = \"c5.4xlarge\";\n\n   /**\n    * C5 Compute-optimized 9x Large\n    * <ul>\n    *    <li>72 GiB of memory</li>\n    *    <li>36 vCPU</li>\n    *    <li>No instance storage (EBS storage only)</li>\n    *    <li>Up to 25 Gbps of network bandwidth using Elastic Network Adapter (ENA)-based Enhanced Networking</li>\n    * </ul>\n    */\n   public static final String C5_9XLARGE = \"c5.9xlarge\";\n\n   /**\n    * C5 Compute-optimized 18x Large\n    * <ul>\n    *    <li>144 GiB of memory</li>\n    *    <li>72 vCPU</li>\n    *    <li>No instance storage (EBS storage only)</li>\n    *    <li>Up to 25 Gbps of network bandwidth using Elastic Network Adapter (ENA)-based Enhanced Networking</li>\n    * </ul>\n    */\n   public static final String C5_18XLARGE = \"c5.18xlarge\";\n\n   /**\n    * C5D Compute-optimized Large\n    * <ul>\n    *    <li>4 GiB of memory</li>\n    *    <li>2 vCPU</li>\n    *    <li>1 x 50 NVMe SSD</li>\n    *    <li>Up to 25 Gbps of network bandwidth using Elastic Network Adapter (ENA)-based Enhanced Networking</li>\n    * </ul>\n    */\n   public static final String C5D_LARGE = \"c5d.large\";\n\n   /**\n    * C5D Compute-optimized X Large\n    * <ul>\n    *    <li>8 GiB of memory</li>\n    *    <li>4 vCPU</li>\n    *    <li>1 x 100 NVMe SSD</li>\n    *    <li>Up to 25 Gbps of network bandwidth using Elastic Network Adapter (ENA)-based Enhanced Networking</li>\n    * </ul>\n    */\n   public static final String C5D_XLARGE = \"c5d.xlarge\";\n\n   /**\n    * C5D Compute-optimized 2x Large\n    * <ul>\n    *    <li>16 GiB of memory</li>\n    *    <li>8 vCPU</li>\n    *    <li>1 x 225 NVMe SSD</li>\n    *    <li>Up to 25 Gbps of network bandwidth using Elastic Network Adapter (ENA)-based Enhanced Networking</li>\n    * </ul>\n    */\n   public static final String C5D_2XLARGE = \"c5d.2xlarge\";\n\n   /**\n    * C5D Compute-optimized 4x Large\n    * <ul>\n    *    <li>32 GiB of memory</li>\n    *    <li>16 vCPU</li>\n    *    <li>1 x 450 NVMe SSD</li>\n    *    <li>Up to 25 Gbps of network bandwidth using Elastic Network Adapter (ENA)-based Enhanced Networking</li>\n    * </ul>\n    */\n   public static final String C5D_4XLARGE = \"c5d.4xlarge\";\n\n   /**\n    * C5D Compute-optimized 9x Large\n    * <ul>\n    *    <li>72 GiB of memory</li>\n    *    <li>36 vCPU</li>\n    *    <li>1 x 900 NVMe SSD</li>\n    *    <li>Up to 25 Gbps of network bandwidth using Elastic Network Adapter (ENA)-based Enhanced Networking</li>\n    * </ul>\n    */\n   public static final String C5D_9XLARGE = \"c5d.9xlarge\";\n\n   /**\n    * C5D Compute-optimized 18x Large\n    * <ul>\n    *    <li>144 GiB of memory</li>\n    *    <li>72 vCPU</li>\n    *    <li>2 x 900 NVMe SSD</li>\n    *    <li>Up to 25 Gbps of network bandwidth using Elastic Network Adapter (ENA)-based Enhanced Networking</li>\n    * </ul>\n    */\n   public static final String C5D_18XLARGE = \"c5d.18xlarge\";\n\n   /**\n    * D2 Dense Storage Extra Large\n    * <ul>\n    *    <li>30.5 GiB of memory</li>\n    *    <li>4 vCPU</li>\n    *    <li>3 x 2000gb HDD</li>\n    * </ul>\n    */\n   public static final String D2_XLARGE = \"d2.xlarge\";\n\n   /**\n    * D2 Dense Storage Double Extra Large\n    * <ul>\n    *    <li>61 GiB of memory</li>\n    *    <li>8 vCPU</li>\n    *    <li>6 x 2000gb HDD</li>\n    * </ul>\n    */\n   public static final String D2_2XLARGE = \"d2.2xlarge\";\n\n   /**\n    * D2 Dense Storage Quadruple Extra Large\n    * <ul>\n    *    <li>122 GiB of memory</li>\n    *    <li>16 vCPU</li>\n    *    <li>12 x 2000gb HDD</li>\n    * </ul>\n    */\n   public static final String D2_4XLARGE = \"d2.4xlarge\";\n\n   /**\n    * D2 Dense Storage Octuple Extra Large\n    * <ul>\n    *    <li>244 GiB of memory</li>\n    *    <li>36 vCPU</li>\n    *    <li>24 x 2000gb HDD</li>\n    * </ul>\n    */\n   public static final String D2_8XLARGE = \"d2.8xlarge\";\n\n   /**\n    * I2 Extra Large\n    * <ul>\n    *    <li>30.5 GiB of memory</li>\n    *    <li>14 EC2 Compute Units (4 virtual cores)</li>\n    *    <li>1 SSD-based volume with 800 GiB of instance storage</li>\n    *    <li>64-bit platform</li>\n    *    <li>I/O Performance: High</li>\n    * </ul>\n    */\n   public static final String I2_XLARGE = \"i2.xlarge\";\n\n   /**\n    * I2 Double Extra Large\n    * <ul>\n    *    <li>61 GiB of memory</li>\n    *    <li>27 EC2 Compute Units (8 virtual cores)</li>\n    *    <li>2 SSD-based volumes each with 800 GiB of instance storage</li>\n    *    <li>64-bit platform</li>\n    *    <li>I/O Performance: High</li>\n    * </ul>\n    */\n   public static final String I2_2XLARGE = \"i2.2xlarge\";\n\n   /**\n    * I2 Quadruple Extra Large\n    * <ul>\n    *    <li>122 GiB of memory</li>\n    *    <li>53 EC2 Compute Units (16 virtual cores)</li>\n    *    <li>4 SSD-based volumes each with 800 GiB of instance storage</li>\n    *    <li>64-bit platform</li>\n    *    <li>I/O Performance: High</li>\n    * </ul>\n    */\n   public static final String I2_4XLARGE = \"i2.4xlarge\";\n\n   /**\n    * I2 Octuple Extra Large\n    * <ul>\n    *    <li>244 GiB of memory</li>\n    *    <li>104 EC2 Compute Units (32 virtual cores)</li>\n    *    <li>8 SSD-based volumes each with 800 GiB of instance storage</li>\n    *    <li>64-bit platform</li>\n    *    <li>I/O Performance: High</li>\n    * </ul>\n    */\n   public static final String I2_8XLARGE = \"i2.8xlarge\";\n\n   /**\n    * R3 Large Memory Optimized\n    * <ul>\n    * <li>15.25 GB memory</li>\n    * <li>2 vCPU</li>\n    * <li>1 SSD-based volume with 32 GiB of instance storage</li>\n    * <li>64-bit platform</li>\n    * </ul>\n    */\n   public static final String R3_LARGE = \"r3.large\";\n\n   /**\n    * R3 Extra Large Memory Optimized\n    * <ul>\n    * <li>30.5 GB memory</li>\n    * <li>4 vCPU</li>\n    * <li>1 SSD-based volume with 80 GiB of instance storage</li>\n    * <li>64-bit platform</li>\n    * </ul>\n    */\n   public static final String R3_XLARGE = \"r3.xlarge\";\n\n   /**\n    * R3 Double Extra Large Memory Optimized\n    * <ul>\n    * <li>61 GB memory</li>\n    * <li>8 vCPU</li>\n    * <li>1 SSD-based volume with 160 GiB of instance storage</li>\n    * <li>64-bit platform</li>\n    * <li>Network Performance: High</li>\n    * </ul>\n    */\n   public static final String R3_2XLARGE = \"r3.2xlarge\";\n\n   /**\n    * R3 Quadruple Extra Large Memory Optimized\n    * <ul>\n    * <li>122 GB memory</li>\n    * <li>16 vCPU</li>\n    * <li>1 SSD-based volume with 320 GiB of instance storage</li>\n    * <li>64-bit platform</li>\n    * <li>Network Performance: High</li>\n    * </ul>\n    */\n   public static final String R3_4XLARGE = \"r3.4xlarge\";\n\n   /**\n    * R3 Octuple Extra Large Memory Optimized\n    * <ul>\n    * <li>244 GB memory</li>\n    * <li>32 vCPU</li>\n    * <li>2 SSD-based volumes with 320 GiB of instance storage</li>\n    * <li>64-bit platform</li>\n    * <li>Network Performance: 10 Gigabit</li>\n    * </ul>\n    */\n   public static final String R3_8XLARGE = \"r3.8xlarge\";\n   \n   /**\n    * R4 Large Memory Optimized\n    * <ul>\n    * <li>15.25 GB memory</li>\n    * <li>2 vCPU</li>\n    * <li>No instance storage (EBS storage only)</li>\n    * <li>64-bit platform</li>\n    * <li>Network Performance: up to 10 Gigabit</li>\n    * </ul>\n    */\n   public static final String R4_LARGE = \"r4.large\";\n\n   /**\n    * R4 Extra Large Memory Optimized\n    * <ul>\n    * <li>30.5 GB memory</li>\n    * <li>4 vCPU</li>\n    * <li>No instance storage (EBS storage only)</li>\n    * <li>64-bit platform</li>\n    * <li>Network Performance: up to 10 Gigabit</li>\n    * </ul>\n    */\n   public static final String R4_XLARGE = \"r4.xlarge\";\n\n   /**\n    * R4 Double Extra Large Memory Optimized\n    * <ul>\n    * <li>61 GB memory</li>\n    * <li>8 vCPU</li>\n    * <li>No instance storage (EBS storage only)</li>\n    * <li>64-bit platform</li>\n    * <li>Network Performance: up to 10 Gigabit</li>\n    * </ul>\n    */\n   public static final String R4_2XLARGE = \"r4.2xlarge\";\n\n   /**\n    * R4 Quadruple Extra Large Memory Optimized\n    * <ul>\n    * <li>122 GB memory</li>\n    * <li>16 vCPU</li>\n    * <li>No instance storage (EBS storage only)</li>\n    * <li>64-bit platform</li>\n    * <li>Network Performance: up to 10 Gigabit</li>\n    * </ul>\n    */\n   public static final String R4_4XLARGE = \"r4.4xlarge\";\n\n   /**\n    * R4 Octuple Extra Large Memory Optimized\n    * <ul>\n    * <li>244 GB memory</li>\n    * <li>32 vCPU</li>\n    * <li>No instance storage (EBS storage only)</li>\n    * <li>64-bit platform</li>\n    * <li>Network Performance: 10 Gigabit</li>\n    * </ul>\n    */\n   public static final String R4_8XLARGE = \"r4.8xlarge\";\n   \n   /**\n    * R4 16x Extra Large Memory Optimized\n    * <ul>\n    * <li>488 GB memory</li>\n    * <li>64 vCPU</li>\n    * <li>No instance storage (EBS storage only)</li>\n    * <li>64-bit platform</li>\n    * <li>Network Performance: 25 Gigabit</li>\n    * </ul>\n    */\n   public static final String R4_16XLARGE = \"r4.16xlarge\";\n   \n   /**\n    * X1 16x Large-scale, enterprise-class and in-memory applications\n    * <ul>\n    * <li>976 GB memory</li>\n    * <li>64 vCPU</li>\n    * <li>Intel Xeon E7-8880 v3 (Haswell) processors</li>\n    * <li>1 SSD-based volume with 1920 GiB of instance storage</li>\n    * <li>64-bit platform</li>\n    * <li>Network Performance: 25 Gigabit</li>\n    * </ul>\n    */\n   public static final String X1_16XLARGE = \"x1.16xlarge\";\n   \n   /**\n    * X1 32x Large-scale, enterprise-class and in-memory applications\n    * <ul>\n    * <li>1952 GB memory</li>\n    * <li>128 vCPU</li>\n    * <li>Intel Xeon E7-8880 v3 (Haswell) processors</li>\n    * <li>2 SSD-based volume with 1920 GiB of instance storage</li>\n    * <li>64-bit platform</li>\n    * <li>Network Performance: 25 Gigabit</li>\n    * </ul>\n    */\n   public static final String X1_32XLARGE = \"x1.32xlarge\";\n\n   /**\n    * A1 Medium\n    * <ul>\n    * <li>Provider Id: a1.medium</li>\n    * <li>vCPU: 1</li>\n    * <li>Memory (GiB): 2</li>\n    * <li>No instance storage (EBS storage only)</li>\n    * <li>64-bit platform</li>\n    * <li>Network Performance: up to 10 Gigabit</li>\n    * </ul>\n    */\n   public static final String A1_MEDIUM = \"a1.medium\";\n\n   /**\n    * A1 Large\n    * <ul>\n    * <li>Provider Id: a1.large</li>\n    * <li>vCPU: 2</li>\n    * <li>Memory (GiB): 4</li>\n    * <li>No instance storage (EBS storage only)</li>\n    * <li>64-bit platform</li>\n    * <li>Network Performance: up to 10 Gigabit</li>\n    * </ul>\n    */\n   public static final String A1_LARGE = \"a1.large\";\n\n   /**\n    * A1 XLarge\n    * <ul>\n    * <li>Provider Id: a1.xlarge</li>\n    * <li>vCPU: 4</li>\n    * <li>Memory (GiB): 8</li>\n    * <li>No instance storage (EBS storage only)</li>\n    * <li>64-bit platform</li>\n    * <li>Network Performance: up to 10 Gigabit</li>\n    * </ul>\n    */\n   public static final String A1_XLARGE = \"a1.xlarge\";\n\n   /**\n    * A1 2XLarge\n    * <ul>\n    * <li>Provider Id: a1.2xlarge</li>\n    * <li>vCPU: 8</li>\n    * <li>Memory (GiB): 16</li>\n    * <li>No instance storage (EBS storage only)</li>\n    * <li>64-bit platform</li>\n    * <li>Network Performance: up to 10 Gigabit</li>\n    * </ul>\n    */\n   public static final String A1_2XLARGE = \"a1.2xlarge\";\n\n   /**\n    * A1 4XLarge\n    * <ul>\n    * <li>Provider Id: a1.4xlarge</li>\n    * <li>vCPU: 16</li>\n    * <li>Memory (GiB): 32</li>\n    * <li>No instance storage (EBS storage only)</li>\n    * <li>64-bit platform</li>\n    * <li>Network Performance: up to 10 Gigabit</li>\n    * </ul>\n    */\n   public static final String A1_4XLARGE = \"a1.4xlarge\";\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/domain/KeyPair.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.ssh.SshKeys;\n\n/**\n * \n * @see <a href=\n *      \"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateKeyPair.html\"\n *      />\n */\npublic class KeyPair implements Comparable<KeyPair> {\n   @Override\n   public String toString() {\n      return \"[region=\" + region + \", keyName=\" + keyName + \", fingerprint=\" + fingerprint + \", sha1OfPrivateKey=\"\n               + sha1OfPrivateKey + \", keyMaterial?=\" + (keyMaterial != null) + \"]\";\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n      private String region;\n      private String keyName;\n      private String fingerprint;\n      private String sha1OfPrivateKey;\n      private String keyMaterial;\n\n      public Builder region(String region) {\n         this.region = region;\n         return this;\n      }\n\n      public Builder keyName(String keyName) {\n         this.keyName = keyName;\n         return this;\n      }\n\n      public Builder sha1OfPrivateKey(String sha1OfPrivateKey) {\n         this.sha1OfPrivateKey = sha1OfPrivateKey;\n         return this;\n      }\n\n      public Builder keyMaterial(String keyMaterial) {\n         this.keyMaterial = keyMaterial;\n         return this;\n      }\n\n      public Builder fingerprint(String fingerprint) {\n         this.fingerprint = fingerprint;\n         return this;\n      }\n\n      public KeyPair build() {\n         if (fingerprint == null && keyMaterial != null)\n            fingerprint(SshKeys.fingerprintPrivateKey(keyMaterial));\n         return new KeyPair(region, keyName, sha1OfPrivateKey, keyMaterial, fingerprint);\n      }\n\n      public static Builder fromKeyPair(KeyPair in) {\n         return new Builder().region(in.getRegion()).keyName(in.getKeyName()).sha1OfPrivateKey(in.getSha1OfPrivateKey())\n                  .keyMaterial(in.getKeyMaterial());\n      }\n   }\n\n   private final String region;\n   private final String keyName;\n   private final String sha1OfPrivateKey;\n   @Nullable\n   private final String keyMaterial;\n   @Nullable\n   private final String fingerprint;\n\n   public KeyPair(String region, String keyName, String sha1OfPrivateKey, @Nullable String keyMaterial,\n            @Nullable String fingerprint) {\n      this.region = checkNotNull(region, \"region\");\n      this.keyName = checkNotNull(keyName, \"keyName\");\n      this.sha1OfPrivateKey = checkNotNull(sha1OfPrivateKey, \"sha1OfPrivateKey\");\n      this.keyMaterial = keyMaterial;  // nullable on list\n      this.fingerprint = fingerprint;  // nullable on list\n   }\n\n   /**\n    * To be removed in jclouds 1.6 <h4>Warning</h4>\n    * \n    * Especially on EC2 clones that may not support regions, this value is fragile. Consider\n    * alternate means to determine context.\n    */\n   @Deprecated\n   public String getRegion() {\n      return region;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public int compareTo(KeyPair o) {\n      return (this == o) ? 0 : getKeyName().compareTo(o.getKeyName());\n   }\n\n   /**\n    * A SHA-1 digest of the DER encoded private key.\n    * \n    * @see SshKeys#sha1\n    */\n   public String getSha1OfPrivateKey() {\n      return sha1OfPrivateKey;\n   }\n\n   /**\n    * fingerprint per the following <a\n    * href=\"http://tools.ietf.org/html/draft-friedl-secsh-fingerprint-00\" >spec</a>\n    * \n    * @see SshKeys#fingerprint\n    */\n   public String getFingerprint() {\n      return fingerprint;\n   }\n\n   /**\n    * An unencrypted PEM encoded RSA private key.\n    */\n   public String getKeyMaterial() {\n      return keyMaterial;\n   }\n\n   /**\n    * The key pair name provided in the original request.\n    */\n   public String getKeyName() {\n      return keyName;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((fingerprint == null) ? 0 : fingerprint.hashCode());\n      result = prime * result + ((keyMaterial == null) ? 0 : keyMaterial.hashCode());\n      result = prime * result + ((keyName == null) ? 0 : keyName.hashCode());\n      result = prime * result + ((region == null) ? 0 : region.hashCode());\n      result = prime * result + ((sha1OfPrivateKey == null) ? 0 : sha1OfPrivateKey.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      KeyPair other = (KeyPair) obj;\n      if (fingerprint == null) {\n         if (other.fingerprint != null)\n            return false;\n      } else if (!fingerprint.equals(other.fingerprint))\n         return false;\n      if (keyMaterial == null) {\n         if (other.keyMaterial != null)\n            return false;\n      } else if (!keyMaterial.equals(other.keyMaterial))\n         return false;\n      if (keyName == null) {\n         if (other.keyName != null)\n            return false;\n      } else if (!keyName.equals(other.keyName))\n         return false;\n      if (region == null) {\n         if (other.region != null)\n            return false;\n      } else if (!region.equals(other.region))\n         return false;\n      if (sha1OfPrivateKey == null) {\n         if (other.sha1OfPrivateKey != null)\n            return false;\n      } else if (!sha1OfPrivateKey.equals(other.sha1OfPrivateKey))\n         return false;\n      return true;\n   }\n\n   public Builder toBuilder() {\n      return Builder.fromKeyPair(this);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/domain/PasswordData.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Date;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\n/**\n * The encrypted administrator password for an instance running Windows.\n * \n * <h4>Note</h4>\n * \n * The Windows password is only generated the first time an AMI is launched. It is not generated for\n * rebundled AMIs or after the password is changed on an instance.\n * \n * The password is encrypted using the key pair that you provided.\n * \n * @see <a\n *      href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-GetPasswordData.html\"\n *      >doc</a>\n */\npublic class PasswordData {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return new Builder().fromPasswordData(this);\n   }\n\n   public static class Builder {\n\n      protected String instanceId;\n      protected Date timestamp;\n      protected String passwordData;\n\n      /**\n       * @see PasswordData#getInstanceId()\n       */\n      public Builder instanceId(String instanceId) {\n         this.instanceId = instanceId;\n         return this;\n      }\n\n      /**\n       * @see PasswordData#getTimestamp()\n       */\n      public Builder timestamp(Date timestamp) {\n         this.timestamp = timestamp;\n         return this;\n      }\n\n      /**\n       * @see PasswordData#getPasswordData()\n       */\n      public Builder passwordData(String passwordData) {\n         this.passwordData = passwordData;\n         return this;\n      }\n\n      public PasswordData build() {\n         return new PasswordData(instanceId, timestamp, passwordData);\n      }\n\n      public Builder fromPasswordData(PasswordData in) {\n         return this.instanceId(in.getInstanceId()).timestamp(in.getTimestamp()).passwordData(in.getPasswordData());\n      }\n   }\n\n   protected final String instanceId;\n   protected final Date timestamp;\n   protected final String passwordData;\n\n   protected PasswordData(String instanceId, Date timestamp, String passwordData) {\n      this.instanceId = checkNotNull(instanceId, \"instanceId\");\n      this.timestamp = checkNotNull(timestamp, \"timestamp\");\n      this.passwordData = checkNotNull(passwordData, \"passwordData\");\n   }\n\n   /**\n    * The ID of the instance.\n    */\n   public String getInstanceId() {\n      return instanceId;\n   }\n\n   /**\n    * The time the data was last updated.\n    */\n   public Date getTimestamp() {\n      return timestamp;\n   }\n\n   /**\n    * The password of the instance.\n    */\n   public String getPasswordData() {\n      return passwordData;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(instanceId);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      PasswordData other = PasswordData.class.cast(obj);\n      return Objects.equal(this.instanceId, other.instanceId);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"instanceId\", instanceId).add(\"timestamp\", timestamp)\n               .add(\"passwordData\", passwordData).toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/domain/Permission.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Set;\n\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Sets;\n\n/**\n * \n * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-ItemType-LaunchPermissionItemType.html\"\n *      />\n */\npublic class Permission {\n   private final Set<String> groups = Sets.newHashSet();\n   private final Set<String> userIds = Sets.newHashSet();\n\n   public Permission(Iterable<String> userIds, Iterable<String> groups) {\n      Iterables.addAll(this.userIds, checkNotNull(userIds, \"userIds\"));\n      Iterables.addAll(this.groups, checkNotNull(groups, \"groups\"));\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((groups == null) ? 0 : groups.hashCode());\n      result = prime * result + ((userIds == null) ? 0 : userIds.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      Permission other = (Permission) obj;\n      if (groups == null) {\n         if (other.groups != null)\n            return false;\n      } else if (!groups.equals(other.groups))\n         return false;\n      if (userIds == null) {\n         if (other.userIds != null)\n            return false;\n      } else if (!userIds.equals(other.userIds))\n         return false;\n      return true;\n   }\n\n   /**\n    * \n    * @return Name of the group. Currently supports \\\"all.\\\"\n    */\n   public Set<String> getGroups() {\n      return groups;\n   }\n\n   /**\n    * \n    * @return AWS Access Key ID.\n    */\n   public Set<String> getUserIds() {\n      return userIds;\n   }\n\n   @Override\n   public String toString() {\n      return \"LaunchPermission [groups=\" + groups + \", userIds=\" + userIds + \"]\";\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/domain/PublicIpInstanceIdPair.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * \n * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-ItemType-DescribeAddressesResponseInfoType.html\"\n *      />\n */\npublic class PublicIpInstanceIdPair implements Comparable<PublicIpInstanceIdPair> {\n\n   private final String region;\n   @Nullable\n   private final String instanceId;\n   private final String allocationId;\n   private final String publicIp;\n   private final Map<String, String> tags;\n\n   public PublicIpInstanceIdPair(final String region, final String publicIp, @Nullable final String instanceId,\n         @Nullable final String allocationId, @Nullable final Map<String, String> tags) {\n      this.region = checkNotNull(region, \"region\");\n      this.instanceId = instanceId;\n      this.allocationId = allocationId;\n      this.publicIp = checkNotNull(publicIp, \"publicIp\");\n      this.tags = tags == null ? ImmutableMap.<String, String> of() : ImmutableMap.copyOf(tags);\n   }\n\n   /**\n    * To be removed in jclouds 1.6 <h4>Warning</h4>\n    * \n    * Especially on EC2 clones that may not support regions, this value is fragile. Consider\n    * alternate means to determine context.\n    */\n   @Deprecated\n   public String getRegion() {\n      return region;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public int compareTo(final PublicIpInstanceIdPair o) {\n      return this == o ? 0 : getPublicIp().compareTo(o.getPublicIp());\n   }\n\n   /**\n    * The ID of the instance.\n    */\n   public String getInstanceId() {\n      return instanceId;\n   }\n\n   /**\n    * The ID of the IP allocation (e.g., eipalloc-0ca038968f2a2c986).\n    */\n   public String getAllocationId() {\n      return allocationId;\n   }\n\n   /**\n    * The public IP address.\n    */\n   public String getPublicIp() {\n      return publicIp;\n   }\n   \n   public Map<String, String> getTags() {\n      return tags;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((instanceId == null) ? 0 : instanceId.hashCode());\n      result = prime * result + ((allocationId == null) ? 0 : allocationId.hashCode());\n      result = prime * result + ((publicIp == null) ? 0 : publicIp.hashCode());\n      result = prime * result + ((region == null) ? 0 : region.hashCode());\n      result = prime * result + ((tags == null) ? 0 : tags.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      PublicIpInstanceIdPair other = (PublicIpInstanceIdPair) obj;\n      if (instanceId == null) {\n         if (other.instanceId != null)\n            return false;\n      } else if (!instanceId.equals(other.instanceId))\n         return false;\n      if (allocationId == null) {\n         if (other.allocationId != null)\n            return false;\n      } else if (!allocationId.equals(other.allocationId))\n         return false;\n      if (publicIp == null) {\n         if (other.publicIp != null)\n            return false;\n      } else if (!publicIp.equals(other.publicIp))\n         return false;\n      if (region == null) {\n         if (other.region != null)\n            return false;\n      } else if (!region.equals(other.region))\n         return false;\n      if (tags == null) {\n         if (other.tags != null)\n            return false;\n      } else if (!tags.equals(other.tags))\n         return false;\n      return true;\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/domain/Reservation.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ComparisonChain;\nimport com.google.common.collect.ForwardingSet;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Ordering;\n\n/**\n * \n * @see <a href=\n *      \"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-ItemType-ReservationInfoType.html\"\n *      />\n */\npublic class Reservation<T extends RunningInstance> extends ForwardingSet<T> implements Comparable<Reservation<T>> {\n\n   public static <T extends RunningInstance> Builder<T> builder() {\n      return new Builder<T>();\n   }\n\n   public Builder<T> toBuilder() {\n      return Reservation.<T> builder().fromReservation(this);\n   }\n\n   public static class Builder<T extends RunningInstance> {\n      private String region;\n      private String ownerId;\n      private String requesterId;\n      private String reservationId;\n\n      private ImmutableSet.Builder<T> instances = ImmutableSet.<T> builder();\n      private ImmutableSet.Builder<String> groupNames = ImmutableSet.<String> builder();\n\n      /**\n       * @see Reservation#getRegion()\n       */\n      public Builder<T> region(String region) {\n         this.region = region;\n         return this;\n      }\n\n      /**\n       * @see Reservation#getOwnerId()\n       */\n      public Builder<T> ownerId(String ownerId) {\n         this.ownerId = ownerId;\n         return this;\n      }\n\n      /**\n       * @see Reservation#getRequesterId()\n       */\n      public Builder<T> requesterId(String requesterId) {\n         this.requesterId = requesterId;\n         return this;\n      }\n\n      /**\n       * @see Reservation#getReservationId()\n       */\n      public Builder<T> reservationId(String reservationId) {\n         this.reservationId = reservationId;\n         return this;\n      }\n\n      /**\n       * @see Reservation#iterator\n       */\n      public Builder<T> instance(T instance) {\n         this.instances.add(checkNotNull(instance, \"instance\"));\n         return this;\n      }\n\n      /**\n       * @see Reservation#iterator\n       */\n      public Builder<T> instances(Set<T> instances) {\n         this.instances.addAll(checkNotNull(instances, \"instances\"));\n         return this;\n      }\n\n      /**\n       * @see Reservation#getGroupNames()\n       */\n      public Builder<T> groupName(String groupName) {\n         this.groupNames.add(checkNotNull(groupName, \"groupName\"));\n         return this;\n      }\n\n      /**\n       * @see Reservation#getGroupNames()\n       */\n      public Builder<T> groupNames(Iterable<String> groupNames) {\n         this.groupNames = ImmutableSet.<String> builder().addAll(checkNotNull(groupNames, \"groupNames\"));\n         return this;\n      }\n\n      public Reservation<T> build() {\n         return new Reservation<T>(region, groupNames.build(), instances.build(), ownerId, requesterId, reservationId);\n      }\n\n      public Builder<T> fromReservation(Reservation<T> in) {\n         return region(in.region).ownerId(in.ownerId).requesterId(in.requesterId).reservationId(in.reservationId)\n                  .instances(in).groupNames(in.groupNames);\n      }\n   }\n\n   private final String region;\n   private final ImmutableSet<String> groupNames;\n   private final ImmutableSet<T> instances;\n   @Nullable\n   private final String ownerId;\n   @Nullable\n   private final String requesterId;\n   @Nullable\n   private final String reservationId;\n\n   public Reservation(String region, Iterable<String> groupNames, Iterable<T> instances, @Nullable String ownerId,\n            @Nullable String requesterId, @Nullable String reservationId) {\n      this.region = checkNotNull(region, \"region\");\n      this.groupNames = ImmutableSet.copyOf(checkNotNull(groupNames, \"groupNames\"));\n      this.instances = ImmutableSet.copyOf(checkNotNull(instances, \"instances\"));\n      this.ownerId = ownerId;\n      this.requesterId = requesterId;\n      this.reservationId = reservationId;\n   }\n\n   @Override\n   protected Set<T> delegate() {\n      return instances;\n   }\n\n   /**\n    * To be removed in jclouds 1.6 <h4>Warning</h4>\n    * \n    * Especially on EC2 clones that may not support regions, this value is fragile. Consider\n    * alternate means to determine context.\n    */\n   @Deprecated\n   public String getRegion() {\n      return region;\n   }\n   \n   /**\n    * Names of the security groups.\n    */\n   public Set<String> getGroupNames() {\n      return groupNames;\n   }\n\n   /**\n    * AWS Access Key ID of the user who owns the reservation.\n    */\n   public String getOwnerId() {\n      return ownerId;\n   }\n\n   /**\n    * The ID of the requester that launched the instances on your behalf (for example, AWS\n    * Management Console or Auto Scaling).\n    */\n   public String getRequesterId() {\n      return requesterId;\n   }\n\n   /**\n    * Unique ID of the reservation.\n    */\n   public String getReservationId() {\n      return reservationId;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(region, reservationId, super.hashCode());\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      @SuppressWarnings(\"unchecked\")\n      Reservation<T> that = Reservation.class.cast(obj);\n      return super.equals(that) && Objects.equal(this.region, that.region)\n               && Objects.equal(this.reservationId, that.reservationId);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"region\", region).add(\"reservationId\", reservationId)\n               .add(\"requesterId\", requesterId).add(\"instances\", instances).add(\"groupNames\", groupNames).toString();\n   }\n\n   @Override\n   public int compareTo(Reservation<T> other) {\n      return ComparisonChain.start().compare(region, other.region)\n               .compare(reservationId, other.reservationId, Ordering.natural().nullsLast()).result();\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/domain/ReservedInstancesOffering.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.domain;\n\n/**\n * \n * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateVolume.html\"\n *      />\n */\npublic class ReservedInstancesOffering implements Comparable<ReservedInstancesOffering> {\n   private final String region;\n   private final String availabilityZone;\n   private final long duration;\n   private final float fixedPrice;\n   private final String instanceType;\n   private final String productDescription;\n   private final String id;\n   private final float usagePrice;\n\n   public ReservedInstancesOffering(String region, String availabilityZone, long duration, float fixedPrice, String instanceType,\n         String productDescription, String reservedInstancesOfferingId, float usagePrice) {\n      this.region = region;\n      this.availabilityZone = availabilityZone;\n      this.duration = duration;\n      this.fixedPrice = fixedPrice;\n      this.instanceType = instanceType;\n      this.productDescription = productDescription;\n      this.id = reservedInstancesOfferingId;\n      this.usagePrice = usagePrice;\n   }\n\n   /**\n    * To be removed in jclouds 1.6 <h4>Warning</h4>\n    * \n    * Especially on EC2 clones that may not support regions, this value is fragile. Consider\n    * alternate means to determine context.\n    */\n   @Deprecated\n   public String getRegion() {\n      return region;\n   }\n   \n   /**\n    * @return The Availability Zone in which the Reserved Instance can be used.\n    */\n   public String getAvailabilityZone() {\n      return availabilityZone;\n   }\n\n   /**\n    * \n    * @return The duration of the Reserved Instance, in seconds\n    */\n   public long getDuration() {\n      return duration;\n   }\n\n   /**\n    * \n    * @return The purchase price of the Reserved Instance.\n    */\n   public float getFixedPrice() {\n      return fixedPrice;\n   }\n\n   /**\n    * \n    * @return The instance type on which the Reserved Instance can be used.\n    */\n   public String getInstanceType() {\n      return instanceType;\n   }\n\n   /**\n    * \n    * @return The Reserved Instance description.\n    */\n   public String getProductDescription() {\n      return productDescription;\n   }\n\n   /**\n    * @return The ID of the Reserved Instance offering.\n    */\n   public String getId() {\n      return id;\n   }\n\n   /**\n    * \n    * @return The usage price of the Reserved Instance, per hour.\n    */\n   public float getUsagePrice() {\n      return usagePrice;\n   }\n\n   @Override\n   public int compareTo(ReservedInstancesOffering o) {\n      return id.compareTo(o.id);\n   }\n\n   @Override\n   public String toString() {\n      return \"[availabilityZone=\" + availabilityZone + \", duration=\" + duration\n            + \", fixedPrice=\" + fixedPrice + \", id=\" + id + \", instanceType=\" + instanceType + \", productDescription=\"\n            + productDescription + \", region=\" + region + \", usagePrice=\" + usagePrice + \"]\";\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((availabilityZone == null) ? 0 : availabilityZone.hashCode());\n      result = prime * result + (int) (duration ^ (duration >>> 32));\n      result = prime * result + Float.floatToIntBits(fixedPrice);\n      result = prime * result + ((id == null) ? 0 : id.hashCode());\n      result = prime * result + ((instanceType == null) ? 0 : instanceType.hashCode());\n      result = prime * result + ((productDescription == null) ? 0 : productDescription.hashCode());\n      result = prime * result + ((region == null) ? 0 : region.hashCode());\n      result = prime * result + Float.floatToIntBits(usagePrice);\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      ReservedInstancesOffering other = (ReservedInstancesOffering) obj;\n      if (availabilityZone == null) {\n         if (other.availabilityZone != null)\n            return false;\n      } else if (!availabilityZone.equals(other.availabilityZone))\n         return false;\n      if (duration != other.duration)\n         return false;\n      if (Float.floatToIntBits(fixedPrice) != Float.floatToIntBits(other.fixedPrice))\n         return false;\n      if (id == null) {\n         if (other.id != null)\n            return false;\n      } else if (!id.equals(other.id))\n         return false;\n      if (instanceType == null) {\n         if (other.instanceType != null)\n            return false;\n      } else if (!instanceType.equals(other.instanceType))\n         return false;\n      if (productDescription == null) {\n         if (other.productDescription != null)\n            return false;\n      } else if (!productDescription.equals(other.productDescription))\n         return false;\n      if (region == null) {\n         if (other.region != null)\n            return false;\n      } else if (!region.equals(other.region))\n         return false;\n      if (Float.floatToIntBits(usagePrice) != Float.floatToIntBits(other.usagePrice))\n         return false;\n      return true;\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/domain/RootDeviceType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.domain;\n\nimport com.google.common.base.CaseFormat;\n\n/**\n * The root device type used by the AMI. The AMI can use an Amazon EBS or instance store root\n * device.\n */\npublic enum RootDeviceType {\n\n   INSTANCE_STORE,\n\n   EBS, UNRECOGNIZED;\n\n   public String value() {\n      return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_HYPHEN, name());\n   }\n\n   public String toString() {\n      return value();\n   }\n\n   public static RootDeviceType fromValue(String v) {\n      try {\n         return valueOf(CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_UNDERSCORE, v));\n      } catch (IllegalArgumentException e) {\n         return UNRECOGNIZED;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/domain/RunningInstance.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Date;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.base.Strings;\nimport com.google.common.collect.ComparisonChain;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Maps;\nimport com.google.common.collect.Ordering;\nimport com.google.common.collect.Sets;\n\n/**\n * \n * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-ItemType-RunningInstancesItemType.html\"\n *      />\n */\npublic class RunningInstance implements Comparable<RunningInstance> {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromRunningInstance(this);\n   }\n   \n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String region;\n      protected Set<String> groupNames = Sets.newLinkedHashSet();\n      protected String amiLaunchIndex;\n      protected String dnsName;\n      protected String imageId;\n      protected String instanceId;\n      protected InstanceState instanceState;\n      protected String rawState;\n      protected String instanceType;\n      protected String ipAddress;\n      protected String kernelId;\n      protected String keyName;\n      protected Date launchTime;\n      protected String availabilityZone;\n      protected String virtualizationType = \"paravirtual\";\n      protected String platform;\n      protected String privateDnsName;\n      protected String privateIpAddress;\n      protected String ramdiskId;\n      protected String reason;\n      protected RootDeviceType rootDeviceType = RootDeviceType.INSTANCE_STORE;\n      protected String rootDeviceName;\n      protected Map<String, BlockDevice> ebsBlockDevices = Maps.newLinkedHashMap();\n      protected Map<String, String> tags = Maps.newLinkedHashMap();\n\n      public T tags(Map<String, String> tags) {\n         this.tags = ImmutableMap.copyOf(checkNotNull(tags, \"tags\"));\n         return self();\n      }\n\n      public T tag(String key, String value) {\n         if (key != null)\n            this.tags.put(key, Strings.nullToEmpty(value));\n         return self();\n      }\n      \n      public T region(String region) {\n         this.region = region;\n         return self();\n      }\n\n      public T groupNames(Iterable<String> groupNames) {\n         this.groupNames = ImmutableSet.copyOf(checkNotNull(groupNames, \"groupNames\"));\n         return self();\n      }\n\n      public T groupName(String groupName) {\n         if (groupName != null)\n            this.groupNames.add(groupName);\n         return self();\n      }\n\n      public T amiLaunchIndex(String amiLaunchIndex) {\n         this.amiLaunchIndex = amiLaunchIndex;\n         return self();\n      }\n\n      public T dnsName(String dnsName) {\n         this.dnsName = dnsName;\n         return self();\n      }\n\n      public T imageId(String imageId) {\n         this.imageId = imageId;\n         return self();\n      }\n\n      public T instanceId(String instanceId) {\n         this.instanceId = instanceId;\n         return self();\n      }\n\n      public T instanceState(InstanceState instanceState) {\n         this.instanceState = instanceState;\n         return self();\n      }\n      \n      public T rawState(String rawState) {\n         this.rawState = rawState;\n         return self();\n      }\n      \n      public T instanceType(String instanceType) {\n         this.instanceType = instanceType;\n         return self();\n      }\n\n      public T ipAddress(String ipAddress) {\n         this.ipAddress = ipAddress;\n         return self();\n      }\n\n      public T kernelId(String kernelId) {\n         this.kernelId = kernelId;\n         return self();\n      }\n\n      public T keyName(String keyName) {\n         this.keyName = keyName;\n         return self();\n      }\n\n      public T launchTime(Date launchTime) {\n         this.launchTime = launchTime;\n         return self();\n      }\n\n      public T availabilityZone(String availabilityZone) {\n         this.availabilityZone = availabilityZone;\n         return self();\n      }\n\n      public T virtualizationType(String virtualizationType) {\n         this.virtualizationType = virtualizationType;\n         return self();\n      }\n\n      public T platform(String platform) {\n         this.platform = platform;\n         return self();\n      }\n\n      public T privateDnsName(String privateDnsName) {\n         this.privateDnsName = privateDnsName;\n         return self();\n      }\n\n      public T privateIpAddress(String privateIpAddress) {\n         this.privateIpAddress = privateIpAddress;\n         return self();\n      }\n\n      public T ramdiskId(String ramdiskId) {\n         this.ramdiskId = ramdiskId;\n         return self();\n      }\n\n      public T reason(String reason) {\n         this.reason = reason;\n         return self();\n      }\n\n      public T rootDeviceType(RootDeviceType rootDeviceType) {\n         this.rootDeviceType = rootDeviceType;\n         return self();\n      }\n\n      public T rootDeviceName(String rootDeviceName) {\n         this.rootDeviceName = rootDeviceName;\n         return self();\n      }\n\n      public T devices(Map<String, BlockDevice> ebsBlockDevices) {\n         this.ebsBlockDevices = ImmutableMap.copyOf(checkNotNull(ebsBlockDevices, \"ebsBlockDevices\"));\n         return self();\n      }\n\n      public T device(String key, BlockDevice value) {\n         if (key != null && value != null)\n            this.ebsBlockDevices.put(key, value);\n         return self();\n      }\n      \n      public T fromRunningInstance(RunningInstance in) {\n         return region(in.region).groupNames(in.groupNames).amiLaunchIndex(in.amiLaunchIndex).dnsName(in.dnsName)\n               .imageId(in.imageId).instanceId(in.instanceId).instanceState(in.instanceState).rawState(in.rawState)\n               .instanceType(in.instanceType).ipAddress(in.ipAddress).kernelId(in.kernelId).keyName(in.keyName)\n               .launchTime(in.launchTime).availabilityZone(in.availabilityZone)\n               .virtualizationType(in.virtualizationType).platform(in.platform).privateDnsName(in.privateDnsName)\n               .privateIpAddress(in.privateIpAddress).ramdiskId(in.ramdiskId).reason(in.reason)\n               .rootDeviceType(in.rootDeviceType).rootDeviceName(in.rootDeviceName).devices(in.ebsBlockDevices)\n               .tags(in.tags);\n      }\n      \n      public abstract RunningInstance build();\n\n   }\n   \n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n\n      @Override\n      public RunningInstance build() {\n         return new RunningInstance(region, groupNames, amiLaunchIndex, dnsName, imageId, instanceId, instanceState,\n               rawState, instanceType, ipAddress, kernelId, keyName, launchTime, availabilityZone, virtualizationType,\n               platform, privateDnsName, privateIpAddress, ramdiskId, reason, rootDeviceType, rootDeviceName,\n               ebsBlockDevices, tags);\n      }\n   }\n\n   protected final String region;\n   protected final Set<String> groupNames;\n   protected final String amiLaunchIndex;\n   @Nullable\n   protected final String dnsName;\n   protected final String imageId;\n   protected final String instanceId;\n   protected final InstanceState instanceState;\n   protected final String rawState;\n   protected final String instanceType;\n   @Nullable\n   protected final String ipAddress;\n   @Nullable\n   protected final String kernelId;\n   @Nullable\n   protected final String keyName;\n   protected final Date launchTime;\n   protected final String availabilityZone;\n   protected final String virtualizationType;\n   @Nullable\n   protected final String platform;\n   @Nullable\n   protected final String privateDnsName;\n   @Nullable\n   protected final String privateIpAddress;\n   @Nullable\n   protected final String ramdiskId;\n   @Nullable\n   protected final String reason;\n   protected final RootDeviceType rootDeviceType;\n   @Nullable\n   protected final String rootDeviceName;\n   protected final Map<String, BlockDevice> ebsBlockDevices;\n   protected final Map<String, String> tags;\n\n   protected RunningInstance(String region, Iterable<String> groupNames, @Nullable String amiLaunchIndex,\n            @Nullable String dnsName, String imageId, String instanceId, InstanceState instanceState, String rawState,\n            String instanceType, @Nullable String ipAddress, @Nullable String kernelId, @Nullable String keyName,\n            Date launchTime, String availabilityZone, String virtualizationType, @Nullable String platform,\n            @Nullable String privateDnsName, @Nullable String privateIpAddress, @Nullable String ramdiskId,\n            @Nullable String reason, RootDeviceType rootDeviceType, @Nullable String rootDeviceName,\n            Map<String, BlockDevice> ebsBlockDevices, Map<String, String> tags) {\n      this.region = checkNotNull(region, \"region\");\n      this.amiLaunchIndex = amiLaunchIndex; // nullable on runinstances.\n      this.dnsName = dnsName; // nullable on runinstances.\n      this.imageId = imageId; // nullable on runinstances.\n      this.instanceId = checkNotNull(instanceId, \"instanceId\");\n      this.instanceState = checkNotNull(instanceState, \"instanceState for %s/%s\", region, instanceId);\n      this.rawState = checkNotNull(rawState, \"rawState for %s/%s\", region, instanceId);\n      this.instanceType = checkNotNull(instanceType, \"instanceType for %s/%s\", region, instanceId);\n      this.ipAddress = ipAddress;\n      this.kernelId = kernelId;\n      this.keyName = keyName;\n      this.launchTime = launchTime;  // nullable on spot.\n      this.availabilityZone = availabilityZone;  // nullable on spot.\n      this.virtualizationType = virtualizationType;\n      this.platform = platform;\n      this.privateDnsName = privateDnsName;  // nullable on runinstances.\n      this.privateIpAddress = privateIpAddress;  // nullable on runinstances.\n      this.ramdiskId = ramdiskId;\n      this.reason = reason;\n      this.rootDeviceType = checkNotNull(rootDeviceType, \"rootDeviceType for %s/%s\", region, instanceId);\n      this.rootDeviceName = rootDeviceName;\n      this.ebsBlockDevices = ImmutableMap.copyOf(checkNotNull(ebsBlockDevices, \"ebsBlockDevices for %s/%s\", region, instanceId));\n      this.groupNames = ImmutableSet.copyOf(checkNotNull(groupNames, \"groupNames for %s/%s\", region, instanceId));\n      this.tags = ImmutableMap.<String, String> copyOf(checkNotNull(tags, \"tags\"));\n   }\n\n   /**\n    * To be removed in jclouds 1.6 <h4>Warning</h4>\n    * \n    * Especially on EC2 clones that may not support regions, this value is fragile. Consider\n    * alternate means to determine context.\n    */\n   @Deprecated\n   public String getRegion() {\n      return region;\n   }\n\n   /**\n    * The AMI launch index, which can be used to find this instance within the launch group. For\n    * more information, go to the Metadata section of the Amazon Elastic Compute Cloud Developer\n    * Guide.\n    * \n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/2010-08-31/DeveloperGuide/\" />\n    */\n   public String getAmiLaunchIndex() {\n      return amiLaunchIndex;\n   }\n\n   /**\n    * The public DNS name assigned to the instance. This DNS name is contactable from outside the\n    * Amazon EC2 network. This element remains empty until the instance enters a running state.\n    */\n   public String getDnsName() {\n      return dnsName;\n   }\n\n   /**\n    * Image ID of the AMI used to launch the instance.\n    */\n   public String getImageId() {\n      return imageId;\n   }\n\n   /**\n    * Unique ID of the instance launched.\n    */\n   public String getId() {\n      return instanceId;\n   }\n\n   /**\n    * The current state of the instance.\n    */\n   public InstanceState getInstanceState() {\n      return instanceState;\n   }\n   \n   /**\n    * The current state of the instance, as returned literally from the input XML\n    */\n   public String getRawState() {\n      return rawState;\n   }\n   \n   /**\n    * The instance type.\n    */\n   public String getInstanceType() {\n      return instanceType;\n   }\n\n   /**\n    * Specifies the IP address of the instance.\n    */\n   public String getIpAddress() {\n      return ipAddress;\n   }\n\n   /**\n    * Optional. Kernel associated with this instance.\n    */\n   public String getKernelId() {\n      return kernelId;\n   }\n\n   /**\n    * If this instance was launched with an associated key pair, this displays the key pair name.\n    */\n   public String getKeyName() {\n      return keyName;\n   }\n\n   /**\n    * The time the instance launched.\n    */\n   public Date getLaunchTime() {\n      return launchTime;\n   }\n\n   /**\n    * The location where the instance launched.\n    */\n   public String getAvailabilityZone() {\n      return availabilityZone;\n   }\n\n   /**\n    * Specifies the instance's virtualization type. Valid values are paravirtual or hvm.\n    */\n   public String getVirtualizationType() {\n      return virtualizationType;\n   }\n\n   /**\n    * Platform of the instance (e.g., Windows).\n    */\n   public String getPlatform() {\n      return platform;\n   }\n\n   /**\n    * The private DNS name assigned to the instance. This DNS name can only be used inside the\n    * Amazon EC2 network. This element remains empty until the instance enters a running state.\n    */\n   public String getPrivateDnsName() {\n      return privateDnsName;\n   }\n\n   /**\n    * Specifies the private IP address that is assigned to the instance (Amazon VPC).\n    */\n   public String getPrivateIpAddress() {\n      return privateIpAddress;\n   }\n\n   /**\n    * Optional. RAM disk associated with this instance.\n    */\n   public String getRamdiskId() {\n      return ramdiskId;\n   }\n\n   /**\n    * Reason for the most recent state transition. This might be an empty string.\n    */\n   public String getReason() {\n      return reason;\n   }\n\n   public RootDeviceType getRootDeviceType() {\n      return rootDeviceType;\n   }\n\n   public String getRootDeviceName() {\n      return rootDeviceName;\n   }\n\n   /**\n    * EBS volumes associated with the instance.\n    */\n   public Map<String, BlockDevice> getEbsBlockDevices() {\n      return ebsBlockDevices;\n   }\n   \n   /**\n    * Names of the security groups.\n    */\n   public Set<String> getGroupNames() {\n      return groupNames;\n   }\n\n   /**\n    * tags that are present in the instance\n    */\n   public Map<String, String> getTags() {\n      return tags;\n   }\n\n   @Override\n   public int compareTo(RunningInstance other) {\n      return ComparisonChain.start().compare(region, other.region).compare(instanceId, other.instanceId, Ordering.natural().nullsLast()).result();\n   }\n   \n   @Override\n   public int hashCode() {\n      return Objects.hashCode(region, instanceId);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      RunningInstance that = RunningInstance.class.cast(obj);\n      return Objects.equal(this.region, that.region) && Objects.equal(this.instanceId, that.instanceId);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"region\", region)\n               .add(\"availabilityZone\", availabilityZone).add(\"id\", instanceId).add(\"state\", rawState)\n               .add(\"type\", instanceType).add(\"virtualizationType\", virtualizationType).add(\"imageId\", imageId)\n               .add(\"ipAddress\", ipAddress).add(\"dnsName\", dnsName).add(\"privateIpAddress\", privateIpAddress)\n               .add(\"privateDnsName\", privateDnsName).add(\"keyName\", keyName).add(\"groupNames\", groupNames)\n               .add(\"platform\", platform).add(\"launchTime\", launchTime).add(\"rootDeviceName\", rootDeviceName)\n               .add(\"rootDeviceType\", rootDeviceType).add(\"ebsBlockDevices\", ebsBlockDevices).add(\"tags\", tags);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/domain/SecurityGroup.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.net.domain.IpPermission;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ForwardingSet;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n *\n * @see <a href=\n *      \"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-ItemType-SecurityGroupItemType.html\"\n *      />\n */\npublic class SecurityGroup extends ForwardingSet<IpPermission> {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromSecurityGroup(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String region;\n      protected String id;\n      protected String name;\n      protected String ownerId;\n      protected String description;\n      protected ImmutableSet.Builder<IpPermission> ipPermissions = ImmutableSet.<IpPermission> builder();\n\n      /**\n       * @see SecurityGroup#getRegion()\n       */\n      public T region(String region) {\n         this.region = region;\n         return self();\n      }\n\n      /**\n       * @see SecurityGroup#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see SecurityGroup#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /**\n       * @see SecurityGroup#getOwnerId()\n       */\n      public T ownerId(String ownerId) {\n         this.ownerId = ownerId;\n         return self();\n      }\n\n      /**\n       * @see SecurityGroup#getDescription()\n       */\n      public T description(String description) {\n         this.description = description;\n         return self();\n      }\n\n      /**\n       * @see SecurityGroup#delegate()\n       */\n      public T role(IpPermission role) {\n         this.ipPermissions.add(role);\n         return self();\n      }\n\n      /**\n       * @see SecurityGroup#delegate()\n       */\n      public T ipPermissions(Iterable<IpPermission> ipPermissions) {\n         this.ipPermissions.addAll(checkNotNull(ipPermissions, \"ipPermissions\"));\n         return self();\n      }\n\n      /**\n       * @see SecurityGroup#delegate()\n       */\n      public T ipPermission(IpPermission ipPermission) {\n         this.ipPermissions.add(checkNotNull(ipPermission, \"ipPermission\"));\n         return self();\n      }\n\n      public SecurityGroup build() {\n         return new SecurityGroup(region, id, name, ownerId, description, ipPermissions.build());\n      }\n\n      public T fromSecurityGroup(SecurityGroup in) {\n         return region(in.region).id(in.id).name(in.name).ownerId(in.ownerId).description(in.description)\n               .ipPermissions(in);\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String region;\n   private final String id;\n   private final String name;\n   private final String ownerId;\n   private final String description;\n   private final Set<IpPermission> ipPermissions;\n\n   public SecurityGroup(String region, String id, String name, String ownerId, String description,\n         Iterable<IpPermission> ipPermissions) {\n      this.region = checkNotNull(region, \"region\");\n      this.id = id;\n      this.name = name;\n      this.ownerId = ownerId;\n      this.description = description;\n      this.ipPermissions = ImmutableSet.copyOf(checkNotNull(ipPermissions, \"ipPermissions\"));\n   }\n\n   /**\n    * To be removed in jclouds 1.6 <h4>Warning</h4>\n    *\n    * Especially on EC2 clones that may not support regions, this value is\n    * fragile. Consider alternate means to determine context.\n    */\n   @Deprecated\n   public String getRegion() {\n      return region;\n   }\n\n   /**\n    * id of the security group. Not in all EC2 impls\n    */\n   @Nullable\n   public String getId() {\n      return id;\n   }\n\n   /**\n    * Name of the security group.\n    */\n   public String getName() {\n      return name;\n   }\n\n   /**\n    * AWS Access Key ID of the owner of the security group.\n    */\n   public String getOwnerId() {\n      return ownerId;\n   }\n\n   /**\n    * Description of the security group.\n    */\n   public String getDescription() {\n      return description;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(region, id, name, ownerId);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      SecurityGroup that = SecurityGroup.class.cast(obj);\n      return Objects.equal(this.region, that.region)\n            && Objects.equal(this.id, that.id)\n            && Objects.equal(this.name, that.name)\n            && Objects.equal(this.ownerId, that.ownerId);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"region\", region).add(\"id\", id).add(\"name\", name)\n            .add(\"ownerId\", ownerId).add(\"description\", description)\n            .add(\"ipPermissions\", ipPermissions.isEmpty() ? null : ipPermissions);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   protected Set<IpPermission> delegate() {\n      return ipPermissions;\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/domain/Snapshot.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Date;\n\n/**\n * \n * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateSnapshot.html\"\n *      />\n */\npublic class Snapshot implements Comparable<Snapshot> {\n   public static enum Status {\n      PENDING, COMPLETED, ERROR, UNRECOGNIZED;\n      public String value() {\n         return name().toLowerCase();\n      }\n\n      @Override\n      public String toString() {\n         return value();\n      }\n\n      public static Status fromValue(String status) {\n         try {\n            return valueOf(checkNotNull(status, \"status\").toUpperCase());\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n   }\n\n   private final String region;\n   private final String id;\n   private final String volumeId;\n   private final int volumeSize;\n   private final Status status;\n   private final Date startTime;\n   private final int progress;\n   private final String ownerId;\n   private final String description;\n   private final String ownerAlias;\n\n   public Snapshot(String region, String id, String volumeId, int volumeSize, Status status, Date startTime,\n            int progress, String ownerId, String description, String ownerAlias) {\n      this.region = checkNotNull(region, \"region\");\n      this.id = id;\n      this.volumeId = volumeId;\n      this.volumeSize = volumeSize;\n      this.status = status;\n      this.startTime = startTime;\n      this.progress = progress;\n      this.ownerId = ownerId;\n      this.description = description;\n      this.ownerAlias = ownerAlias;\n   }\n\n   /**\n    * To be removed in jclouds 1.6 <h4>Warning</h4>\n    * \n    * Especially on EC2 clones that may not support regions, this value is fragile. Consider\n    * alternate means to determine context.\n    */\n   @Deprecated\n   public String getRegion() {\n      return region;\n   }\n   \n   /**\n    * The ID of the snapshot.\n    */\n   public String getId() {\n      return id;\n   }\n\n   /**\n    * The ID of the volume.\n    */\n   public String getVolumeId() {\n      return volumeId;\n   }\n\n   /**\n    * The size of the volume, in GiB.\n    */\n   public int getVolumeSize() {\n      return volumeSize;\n   }\n\n   /**\n    * Snapshot state (e.g., pending, completed, or error)\n    */\n   public Status getStatus() {\n      return status;\n   }\n\n   /**\n    * Time stamp when the snapshot was initiated.\n    */\n   public Date getStartTime() {\n      return startTime;\n   }\n\n   /**\n    * The progress of the snapshot, in percentage.\n    */\n   public int getProgress() {\n      return progress;\n   }\n\n   /**\n    * AWS Access Key ID of the user who owns the snapshot.\n    */\n   public String getOwnerId() {\n      return ownerId;\n   }\n\n   /**\n    * Description of the snapshot.\n    */\n   public String getDescription() {\n      return description;\n   }\n\n   /**\n    * The AWS identity alias (e.g., \"amazon\", \"redhat\", \"self\", etc.) or AWS identity ID that owns\n    * the AMI.\n    */\n   public String getOwnerAlias() {\n      return ownerAlias;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((description == null) ? 0 : description.hashCode());\n      result = prime * result + ((id == null) ? 0 : id.hashCode());\n      result = prime * result + ((ownerAlias == null) ? 0 : ownerAlias.hashCode());\n      result = prime * result + ((ownerId == null) ? 0 : ownerId.hashCode());\n      result = prime * result + progress;\n      result = prime * result + ((region == null) ? 0 : region.hashCode());\n      result = prime * result + ((startTime == null) ? 0 : startTime.hashCode());\n      result = prime * result + ((status == null) ? 0 : status.hashCode());\n      result = prime * result + ((volumeId == null) ? 0 : volumeId.hashCode());\n      result = prime * result + volumeSize;\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      Snapshot other = (Snapshot) obj;\n      if (description == null) {\n         if (other.description != null)\n            return false;\n      } else if (!description.equals(other.description))\n         return false;\n      if (id == null) {\n         if (other.id != null)\n            return false;\n      } else if (!id.equals(other.id))\n         return false;\n      if (ownerAlias == null) {\n         if (other.ownerAlias != null)\n            return false;\n      } else if (!ownerAlias.equals(other.ownerAlias))\n         return false;\n      if (ownerId == null) {\n         if (other.ownerId != null)\n            return false;\n      } else if (!ownerId.equals(other.ownerId))\n         return false;\n      if (progress != other.progress)\n         return false;\n      if (region == null) {\n         if (other.region != null)\n            return false;\n      } else if (!region.equals(other.region))\n         return false;\n      if (startTime == null) {\n         if (other.startTime != null)\n            return false;\n      } else if (!startTime.equals(other.startTime))\n         return false;\n      if (status == null) {\n         if (other.status != null)\n            return false;\n      } else if (!status.equals(other.status))\n         return false;\n      if (volumeId == null) {\n         if (other.volumeId != null)\n            return false;\n      } else if (!volumeId.equals(other.volumeId))\n         return false;\n      if (volumeSize != other.volumeSize)\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"Snapshot [description=\" + description + \", id=\" + id + \", ownerAlias=\" + ownerAlias + \", ownerId=\"\n               + ownerId + \", progress=\" + progress + \", startTime=\" + startTime + \", status=\" + status + \", volumeId=\"\n               + volumeId + \", volumeSize=\" + volumeSize + \"]\";\n   }\n\n   @Override\n   public int compareTo(Snapshot o) {\n      return startTime.compareTo(o.startTime);\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/domain/Subnet.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Amazon EC2 VPCs contain one or more subnets.\n * \n * @see <a href=\"http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_Subnets.html\" >doc</a>\n */\npublic final class Subnet {\n\n   public static enum State {\n      /**\n       * The subnet is available for use.\n       */\n      AVAILABLE,\n      /**\n       * The subnet is not yet available for use.\n       */\n      PENDING, UNRECOGNIZED;\n      public String value() {\n         return name().toLowerCase();\n      }\n\n      public static State fromValue(String v) {\n         try {\n            return valueOf(v.toUpperCase());\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n   }\n\n   private final String subnetId;\n   private final State subnetState;\n   private final String vpcId;\n   private final String cidrBlock;\n   private final int availableIpAddressCount;\n   private final String availabilityZone;\n   private final Map<String, String> tags;\n\n   private Subnet(String subnetId, State subnetState, String vpcId, String cidrBlock, int availableIpAddressCount,\n         String availabilityZone, ImmutableMap<String, String> tags) {\n      this.subnetId = checkNotNull(subnetId, \"subnetId\");\n      this.subnetState = checkNotNull(subnetState, \"subnetState for %s\", subnetId);\n      this.vpcId = checkNotNull(vpcId, \"vpcId for %s\", subnetId);\n      this.cidrBlock = checkNotNull(cidrBlock, \"cidrBlock for %s\", subnetId);\n      this.availableIpAddressCount = availableIpAddressCount;\n      this.availabilityZone = checkNotNull(availabilityZone, \"availabilityZone for %s\", subnetId);\n      this.tags = checkNotNull(tags, \"tags for %s\", subnetId);\n   }\n\n   /**\n    * The subnet ID, ex. subnet-c5473ba8\n    */\n   public String getSubnetId() {\n      return subnetId;\n   }\n\n   /**\n    * The subnet state - either available or pending.\n    */\n   public State getSubnetState() {\n      return subnetState;\n   }\n\n   /**\n    * The vpc ID this subnet belongs to.\n    */\n   public String getVpcId() {\n      return vpcId;\n   }\n\n   /**\n    * The CIDR block for this subnet.\n    */\n   public String getCidrBlock() {\n      return cidrBlock;\n   }\n\n   /**\n    * The number of available IPs in this subnet.\n    */\n   public int getAvailableIpAddressCount() {\n      return availableIpAddressCount;\n   }\n\n   /**\n    * The availability zone this subnet is in.\n    */\n   public String getAvailabilityZone() {\n      return availabilityZone;\n   }\n\n   /**\n    * Tags that are attached to this subnet.\n    */\n   public Map<String, String> getTags() {\n      return tags;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(subnetId, vpcId, availabilityZone);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      Subnet that = Subnet.class.cast(obj);\n      return Objects.equal(this.subnetId, that.subnetId) && Objects.equal(this.vpcId, that.vpcId)\n            && Objects.equal(this.availabilityZone, that.availabilityZone);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   private ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"subnetId\", subnetId).add(\"subnetState\", subnetState)\n            .add(\"vpcId\", vpcId).add(\"cidrBlock\", cidrBlock).add(\"availableIpAddressCount\", availableIpAddressCount)\n            .add(\"availabilityZone\", availabilityZone).add(\"tags\", tags);\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().from(this);\n   }\n\n   public static final class Builder {\n      private String subnetId;\n      private State subnetState;\n      private String vpcId;\n      private String cidrBlock;\n      private int availableIpAddressCount;\n      private String availabilityZone;\n      private ImmutableMap.Builder<String, String> tags = ImmutableMap.<String, String> builder();\n\n      /**\n       * @see Subnet#getSubnetId()\n       */\n      public Builder subnetId(String subnetId) {\n         this.subnetId = subnetId;\n         return this;\n      }\n\n      /**\n       * @see Subnet#getState()\n       */\n      public Builder subnetState(State subnetState) {\n         this.subnetState = subnetState;\n         return this;\n      }\n\n      /**\n       * @see Subnet#getVpcId()\n       */\n      public Builder vpcId(String vpcId) {\n         this.vpcId = vpcId;\n         return this;\n      }\n\n      /**\n       * @see Subnet#getCidrBlock()\n       */\n      public Builder cidrBlock(String cidrBlock) {\n         this.cidrBlock = cidrBlock;\n         return this;\n      }\n\n      /**\n       * @see Subnet#getAvailableIpAddressCount()\n       */\n      public Builder availableIpAddressCount(int availableIpAddressCount) {\n         this.availableIpAddressCount = availableIpAddressCount;\n         return this;\n      }\n\n      /**\n       * @see Subnet#getAvailabilityZone()\n       */\n      public Builder availabilityZone(String availabilityZone) {\n         this.availabilityZone = availabilityZone;\n         return this;\n      }\n\n      /**\n       * @see Subnet#getTags()\n       */\n      public Builder tags(Map<String, String> tags) {\n         this.tags.putAll(checkNotNull(tags, \"tags\"));\n         return this;\n      }\n\n      /**\n       * @see Subnet#getTags()\n       */\n      public Builder tag(String key) {\n         return tag(key, \"\");\n      }\n\n      /**\n       * @see Subnet#getTags()\n       */\n      public Builder tag(String key, String value) {\n         this.tags.put(checkNotNull(key, \"key\"), checkNotNull(value, \"value\"));\n         return this;\n      }\n\n      public Subnet build() {\n         return new Subnet(subnetId, subnetState, vpcId, cidrBlock, availableIpAddressCount, availabilityZone,\n               tags.build());\n      }\n\n      public Builder from(Subnet in) {\n         return this.subnetId(in.getSubnetId()).subnetState(in.getSubnetState()).vpcId(in.getVpcId())\n               .cidrBlock(in.getCidrBlock()).availableIpAddressCount(in.getAvailableIpAddressCount())\n               .availabilityZone(in.getAvailabilityZone()).tags(in.getTags());\n      }\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/domain/Tag.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.base.Optional;\n\n/**\n * To help you manage your Amazon EC2 instances, images, and other Amazon EC2\n * resources, you can assign your own metadata to each resource in the form of\n * tags.\n * \n * @see <a\n *      href=\"http://docs.amazonwebservices.com/AWSEC2/latest/UserGuide/Using_Tags.html\"\n *      >doc</a>\n */\npublic class Tag {\n\n   /**\n    * Describes the well-known resource types that can be tagged.\n    */\n   public static final class ResourceType {\n      public static final String CUSTOMER_GATEWAY = \"customer-gateway\";\n      public static final String DHCP_OPTIONS = \"dhcp-options\";\n      public static final String IMAGE = \"image\";\n      public static final String INSTANCE = \"instance\";\n      public static final String INTERNET_GATEWAY = \"internet-gateway\";\n      public static final String NETWORK_ACL = \"network-acl\";\n      public static final String RESERVED_INSTANCES = \"reserved-instances\";\n      public static final String ROUTE_TABLE = \"route-table\";\n      public static final String SECURITY_GROUP = \"security-group\";\n      public static final String SNAPSHOT = \"snapshot\";\n      public static final String SPOT_INSTANCES_REQUEST = \"spot-instances-request\";\n      public static final String SUBNET = \"subnet\";\n      public static final String VOLUME = \"volume\";\n      public static final String VPC = \"vpc\";\n      public static final String VPN_CONNECTION = \"vpn-connection\";\n      public static final String VPN_GATEWAY = \"vpn-gateway\";\n\n      private ResourceType() {\n         throw new AssertionError(\"intentionally unimplemented\");\n      }\n   }\n   \n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().fromTag(this);\n   }\n\n   public static class Builder {\n\n      protected String resourceId;\n      protected String resourceType;\n      protected String key;\n      protected Optional<String> value = Optional.absent();\n\n      /**\n       * @see Tag#getResourceId()\n       */\n      public Builder resourceId(String resourceId) {\n         this.resourceId = resourceId;\n         return this;\n      }\n\n      /**\n       * @see Tag#getResourceType()\n       */\n      public Builder resourceType(String resourceType) {\n         this.resourceType = resourceType;\n         return this;\n      }\n\n      /**\n       * @see Tag#getKey()\n       */\n      public Builder key(String key) {\n         this.key = key;\n         return this;\n      }\n\n      /**\n       * @see TagGroup#getValue()\n       */\n      public Builder value(String value) {\n         this.value = Optional.fromNullable(value);\n         return this;\n      }\n\n      public Tag build() {\n         return new Tag(resourceId, resourceType, key, value);\n      }\n\n      public Builder fromTag(Tag in) {\n         return this.resourceId(in.getResourceId()).resourceType(in.getResourceType()).key(in.getKey())\n               .value(in.getValue().orNull());\n      }\n   }\n\n   protected final String resourceId;\n   protected final String resourceType;\n   protected final String key;\n   protected final Optional<String> value;\n\n   protected Tag(String resourceId, String resourceType, String key, Optional<String> value) {\n      this.resourceId = checkNotNull(resourceId, \"resourceId\");\n      this.resourceType = checkNotNull(resourceType, \"resourceType\");\n      this.key = checkNotNull(key, \"key\");\n      this.value = checkNotNull(value, \"value\");\n   }\n\n   /**\n    * The resource ID ex. i-erf235\n    */\n   public String getResourceId() {\n      return resourceId;\n   }\n\n   /**\n    * The resource type. ex. customer-gateway, dhcp-options, image, instance,\n    * internet-gateway, network-acl, reserved-instances, route-table,\n    * security-group, snapshot, spot-instances-request, subnet, volume, vpc,\n    * vpn-connection, vpn-gateway\n    */\n   public String getResourceType() {\n      return resourceType;\n   }\n\n   /**\n    * The tag key.\n    */\n   public String getKey() {\n      return key;\n   }\n\n   /**\n    * The tag value.\n    */\n   public Optional<String> getValue() {\n      return value;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(resourceId, key);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      Tag other = (Tag) obj;\n      return Objects.equal(this.resourceId, other.resourceId) && Objects.equal(this.key, other.key);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"resourceId\", resourceId)\n            .add(\"resourceType\", resourceType).add(\"key\", key).add(\"value\", value.orNull());\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/domain/UserIdGroupPair.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\n/**\n * \n * @see <a href=\n *      \"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-ItemType-UserIdGroupPairType.html\"\n *      />\n */\npublic class UserIdGroupPair implements Comparable<UserIdGroupPair> {\n   private final String userId;\n   private final String groupName;\n\n   public UserIdGroupPair(String userId, String groupName) {\n      this.userId = checkNotNull(userId, \"userId\");\n      this.groupName = checkNotNull(groupName, \"groupName\");\n   }\n\n\n   @Override\n   public String toString() {\n      return \"[userId=\" + userId + \", groupName=\" + groupName + \"]\";\n   }\n\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public int compareTo(UserIdGroupPair o) {\n      return (this == o) ? 0 : getUserId().compareTo(o.getUserId());\n   }\n\n\n   /**\n    * AWS User ID of an identity. Cannot be used when specifying a CIDR IP address.\n    */\n   public String getUserId() {\n      return userId;\n   }\n\n\n   /**\n    * Name of the security group. Cannot be used when specifying a CIDR IP address.\n    */\n   public String getGroupName() {\n      return groupName;\n   }\n\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((groupName == null) ? 0 : groupName.hashCode());\n      result = prime * result + ((userId == null) ? 0 : userId.hashCode());\n      return result;\n   }\n\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      UserIdGroupPair other = (UserIdGroupPair) obj;\n      if (groupName == null) {\n         if (other.groupName != null)\n            return false;\n      } else if (!groupName.equals(other.groupName))\n         return false;\n      if (userId == null) {\n         if (other.userId != null)\n            return false;\n      } else if (!userId.equals(other.userId))\n         return false;\n      return true;\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/domain/VirtualizationType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.domain;\n\nimport com.google.common.base.CaseFormat;\n\n/**\n * Virtualization type of the image.\n */\npublic enum VirtualizationType {\n\n   PARAVIRTUAL,\n\n   HVM, UNRECOGNIZED;\n\n   public String value() {\n      return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_HYPHEN, name());\n   }\n\n   public String toString() {\n      return value();\n   }\n\n   public static VirtualizationType fromValue(String v) {\n      try {\n         return valueOf(CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_UNDERSCORE, v));\n      } catch (IllegalArgumentException e) {\n         return UNRECOGNIZED;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/domain/Volume.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Sets.newHashSet;\n\nimport java.util.Date;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.CaseFormat;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * \n * @see <a href=\n *      \"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateVolume.html\"\n *      />\n */\npublic class Volume implements Comparable<Volume> {\n\n   public Builder toBuilder() {\n      return builder().fromVolume(this);\n   }\n   \n   /**\n    * Specifies whether the instance's Amazon EBS volumes are stopped or terminated when the\n    * instance is shut down.\n    * \n    */\n   public static enum InstanceInitiatedShutdownBehavior {\n      STOP, TERMINATE, UNRECOGNIZED;\n      public String value() {\n         return name().toLowerCase();\n      }\n\n      @Override\n      public String toString() {\n         return value();\n      }\n\n      public static InstanceInitiatedShutdownBehavior fromValue(String status) {\n         try {\n            return valueOf(checkNotNull(status, \"status\").toUpperCase());\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n   }\n\n   public static enum Status {\n      CREATING, AVAILABLE, IN_USE, DELETING, ERROR, UNRECOGNIZED;\n      public String value() {\n         return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_HYPHEN, name());\n      }\n\n      @Override\n      public String toString() {\n         return value();\n      }\n\n      public static Status fromValue(String status) {\n         try {\n            return valueOf(CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_UNDERSCORE, checkNotNull(status, \"status\")));\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n   }\n   \n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n      private String region;\n      private String id;\n      private int size;\n      @Nullable\n      private String snapshotId;\n      private String availabilityZone;\n      private Status status;\n      private Date createTime;\n      private Set<Attachment> attachments = ImmutableSet.of();\n      @Nullable\n      private String volumeType;\n      @Nullable\n      private Integer iops;\n      private boolean encrypted = false;\n\n      public Builder region(String region) {\n         this.region = region;\n         return this;\n      }\n      \n      public Builder id(String id) {\n         this.id = id;\n         return this;\n      }\n      \n      public Builder size(int size) {\n         this.size = size;\n         return this;\n      }\n      \n      public Builder snapshotId(String snapshotId) {\n         this.snapshotId = snapshotId;\n         return this;\n      }\n      \n      public Builder availabilityZone(String availabilityZone) {\n         this.availabilityZone = availabilityZone;\n         return this;\n      }\n      \n      public Builder status(Status status) {\n         this.status = status;\n         return this;\n      }\n\n      public Builder createTime(Date createTime) {\n         this.createTime = createTime;\n         return this;\n      }\n      \n      public Builder attachments(Attachment... attachments) {\n         this.attachments = newHashSet(attachments);\n         return this;\n      }\n      \n      public Builder attachments(Set<Attachment> attachments) {\n         this.attachments = ImmutableSet.copyOf(attachments);\n         return this;\n      }\n\n      public Builder volumeType(String volumeType) {\n         this.volumeType = volumeType;\n         return this;\n      }\n\n      public Builder iops(Integer iops) {\n         this.iops = iops;\n         return this;\n      }\n\n      public Builder encrypted(boolean encrypted) {\n         this.encrypted = encrypted;\n         return this;\n      }\n\n      public Volume build() {\n         return new Volume(region, id, size, snapshotId, availabilityZone, status, createTime,\n                 volumeType, iops, encrypted, attachments);\n      }\n\n      public Builder fromVolume(Volume in) {\n         return region(in.region).id(in.id).size(in.size).snapshotId(in.snapshotId)\n                  .availabilityZone(in.availabilityZone).status(in.status).createTime(in.createTime)\n                  .volumeType(in.volumeType).iops(in.iops).encrypted(in.encrypted).attachments(in.attachments);\n      }\n   }\n\n   private final String region;\n   private final String id;\n   private final int size;\n   @Nullable\n   private final String snapshotId;\n   private final String availabilityZone;\n   private final Status status;\n   private final Date createTime;\n   private final Set<Attachment> attachments;\n\n   @Nullable\n   private final String volumeType;\n   @Nullable\n   private final Integer iops;\n   private final boolean encrypted;\n\n   public Volume(String region, String id, int size, String snapshotId, String availabilityZone, Volume.Status status,\n            Date createTime, String volumeType, Integer iops, boolean encrypted, Iterable<Attachment> attachments) {\n      this.region = checkNotNull(region, \"region\");\n      this.id = id;\n      this.size = size;\n      this.snapshotId = snapshotId;\n      this.availabilityZone = availabilityZone;\n      this.status = status;\n      this.createTime = createTime;\n      this.volumeType = volumeType;\n      this.iops = iops;\n      this.encrypted = encrypted;\n      this.attachments = ImmutableSet.copyOf(attachments);\n   }\n\n   /**\n    * To be removed in jclouds 1.6 <h4>Warning</h4>\n    * \n    * Especially on EC2 clones that may not support regions, this value is fragile. Consider\n    * alternate means to determine context.\n    */\n   @Deprecated\n   public String getRegion() {\n      return region;\n   }\n\n   public String getId() {\n      return id;\n   }\n\n   public int getSize() {\n      return size;\n   }\n\n   public String getSnapshotId() {\n      return snapshotId;\n   }\n\n   public String getAvailabilityZone() {\n      return availabilityZone;\n   }\n\n   public Status getStatus() {\n      return status;\n   }\n\n   public Date getCreateTime() {\n      return createTime;\n   }\n\n   public String getVolumeType() {\n      return volumeType;\n   }\n\n   public Integer getIops() {\n      return iops;\n   }\n\n   public boolean getEncrypted() {\n      return encrypted;\n   }\n\n   public Set<Attachment> getAttachments() {\n      return attachments;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((attachments == null) ? 0 : attachments.hashCode());\n      result = prime * result + ((availabilityZone == null) ? 0 : availabilityZone.hashCode());\n      result = prime * result + ((createTime == null) ? 0 : createTime.hashCode());\n      result = prime * result + ((id == null) ? 0 : id.hashCode());\n      result = prime * result + ((region == null) ? 0 : region.hashCode());\n      result = prime * result + size;\n      result = prime * result + ((snapshotId == null) ? 0 : snapshotId.hashCode());\n      result = prime * result + ((status == null) ? 0 : status.hashCode());\n      result = prime * result + ((volumeType == null) ? 0 : volumeType.hashCode());\n      result = prime * result + ((iops == null) ? 0 : iops.hashCode());\n      result = prime * result + (encrypted ? 1249 : 1259);\n            return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      Volume other = (Volume) obj;\n      if (attachments == null) {\n         if (other.attachments != null)\n            return false;\n      } else if (!attachments.equals(other.attachments))\n         return false;\n      if (availabilityZone == null) {\n         if (other.availabilityZone != null)\n            return false;\n      } else if (!availabilityZone.equals(other.availabilityZone))\n         return false;\n      if (createTime == null) {\n         if (other.createTime != null)\n            return false;\n      } else if (!createTime.equals(other.createTime))\n         return false;\n      if (id == null) {\n         if (other.id != null)\n            return false;\n      } else if (!id.equals(other.id))\n         return false;\n      if (region == null) {\n         if (other.region != null)\n            return false;\n      } else if (!region.equals(other.region))\n         return false;\n      if (size != other.size)\n         return false;\n      if (snapshotId == null) {\n         if (other.snapshotId != null)\n            return false;\n      } else if (!snapshotId.equals(other.snapshotId))\n         return false;\n      if (status == null) {\n         if (other.status != null)\n            return false;\n      } else if (!status.equals(other.status))\n         return false;\n      if (volumeType == null) {\n         if (other.volumeType != null)\n            return false;\n      } else if (!volumeType.equals(other.volumeType))\n         return false;\n      if (iops == null) {\n         if (other.iops != null)\n            return false;\n      } else if (!iops.equals(other.iops))\n         return false;\n      if (encrypted != other.encrypted)\n         return false;\n      return true;\n   }\n\n   @Override\n   public int compareTo(Volume that) {\n      return id.compareTo(that.id);\n   }\n\n   @Override\n   public String toString() {\n      return \"Volume [attachments=\" + attachments + \", availabilityZone=\" + availabilityZone + \", createTime=\"\n              + createTime + \", id=\" + id + \", region=\" + region + \", size=\" + size + \", snapshotId=\" + snapshotId\n              + \", status=\" + status + \", volumeType=\" + volumeType + \", iops=\" + iops + \", encrypted=\" + encrypted\n              + \"]\";\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/features/AMIApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.features;\n\nimport static org.jclouds.aws.reference.FormParameters.ACTION;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.FormParam;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.aws.filters.FormSigner;\nimport org.jclouds.ec2.binders.BindFiltersToIndexedFormParams;\nimport org.jclouds.ec2.binders.BindUserGroupsToIndexedFormParams;\nimport org.jclouds.ec2.binders.BindUserIdsToIndexedFormParams;\nimport org.jclouds.ec2.domain.Image;\nimport org.jclouds.ec2.domain.Image.EbsBlockDevice;\nimport org.jclouds.ec2.domain.Permission;\nimport org.jclouds.ec2.options.CreateImageOptions;\nimport org.jclouds.ec2.options.DescribeImagesOptions;\nimport org.jclouds.ec2.options.RegisterImageBackedByEbsOptions;\nimport org.jclouds.ec2.options.RegisterImageOptions;\nimport org.jclouds.ec2.xml.BlockDeviceMappingHandler;\nimport org.jclouds.ec2.xml.DescribeImagesResponseHandler;\nimport org.jclouds.ec2.xml.ImageIdHandler;\nimport org.jclouds.ec2.xml.PermissionHandler;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.location.functions.RegionToEndpointOrProviderIfNull;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.EndpointParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.FormParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.VirtualHost;\nimport org.jclouds.rest.annotations.XMLResponseParser;\n\nimport com.google.common.collect.Multimap;\n\n/**\n * Provides access to AMI Services.\n * <p/>\n */\n@RequestFilters(FormSigner.class)\n@VirtualHost\npublic interface AMIApi {\n\n   /**\n    * Returns information about AMIs, AKIs, and ARIs. This includes image type, product codes,\n    * architecture, and kernel and RAM disk IDs. Images available to you include public images,\n    * private images that you own, and private images owned by other users for which you have\n    * explicit launch permissions.\n    * \n    * @param region\n    *           AMIs are tied to the Region where its files are located within Amazon S3.\n    * @see InstanceApi#describeInstances\n    * @see #describeImageAttribute\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeImages.html\"\n    *      />\n    * @see DescribeImagesOptions\n    */\n   @Named(\"DescribeImages\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DescribeImages\")\n   @XMLResponseParser(DescribeImagesResponseHandler.class)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<? extends Image> describeImagesInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n            DescribeImagesOptions... options);\n\n   /**\n    * Returns information about AMIs, AKIs, and ARIs. This includes image type, product codes,\n    * architecture, and kernel and RAM disk IDs. Images available to you include public images,\n    * private images that you own, and private images owned by other users for which you have\n    * explicit launch permissions.\n    *\n    * @param region\n    *           AMIs are tied to the Region where its files are located within Amazon S3.\n    * @param filter\n    *           Multimap of filter key/values.\n    * @see InstanceApi#describeInstances\n    * @see #describeImageAttribute\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeImages.html\"\n    *      />\n    * @see DescribeImagesOptions\n    */\n   @Named(\"DescribeImages\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DescribeImages\")\n   @XMLResponseParser(DescribeImagesResponseHandler.class)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<? extends Image> describeImagesInRegionWithFilter(\n           @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n           @BinderParam(BindFiltersToIndexedFormParams.class) Multimap<String, String> filter,\n           DescribeImagesOptions... options);\n\n   /**\n    * Creates an AMI that uses an Amazon EBS root device from a \"running\" or \"stopped\" instance.\n    * \n    * @param region\n    *           AMIs are tied to the Region where its files are located within Amazon S3.\n    * @param name\n    *           The name of the AMI that was provided during image creation. 3-128 alphanumeric\n    *           characters, parenthesis (()), commas (,), slashes (/), dashes (-), or underscores(_)\n    * @param instanceId\n    *           The ID of the instance.\n    * @return imageId\n    * \n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeImages.html\"\n    *      />\n    * @see CreateImageOptions\n    * @see InstanceApi#runInstances\n    * @see InstanceApi#describeInstances\n    * @see InstanceApi#terminateInstances\n    * @see <a href=\n    *      \"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateImage.html\"\n    *      />\n    */\n   @Named(\"CreateImage\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"CreateImage\")\n   @XMLResponseParser(ImageIdHandler.class)\n   String createImageInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n            @FormParam(\"Name\") String name, @FormParam(\"InstanceId\") String instanceId, CreateImageOptions... options);\n\n   /**\n    * \n    * Deregisters the specified AMI. Once deregistered, the AMI cannot be used to launch new\n    * instances.\n    * \n    * @param region\n    *           AMIs are tied to the Region where its files are located within Amazon S3.\n    * @param imageId\n    *           Unique ID of the AMI which was assigned during registration. To register an AMI, use\n    *           RegisterImage. To view the AMI IDs of AMIs that belong to your identity. use\n    *           DescribeImages.\n    * \n    * @see #describeImages\n    * @see #registerImage\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DeregisterImage.html\"\n    *      />\n    */\n   @Named(\"DeregisterImage\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DeregisterImage\")\n   void deregisterImageInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n            @FormParam(\"ImageId\") String imageId);\n\n   /**\n    * Registers an AMI with Amazon EC2. Images must be registered before they can be launched. To\n    * launch instances, use the {@link InstanceApi#runInstances} operation.\n    * <p/>\n    * Each AMI is associated with an unique ID which is provided by the Amazon EC2 service through\n    * this operation. If needed, you can deregister an AMI at any time.\n    * <p/>\n    * <h3>Note</h3> Any modifications to an AMI backed by Amazon S3 invalidates this registration.\n    * If you make changes to an image, deregister the previous image and register the new image.\n    * \n    * @param region\n    *           AMIs are tied to the Region where its files are located within Amazon S3.\n    * @param name\n    *           The name of the AMI that was provided during image creation. 3-128 alphanumeric\n    *           characters, parenthesis (()), commas (,), slashes (/), dashes (-), or underscores(_)\n    * @param pathToManifest\n    *           Full path to your AMI manifest in Amazon S3 storage.\n    * @param options\n    *           Options to specify metadata such as architecture or secondary volumes to be\n    *           associated with this image.\n    * @return imageId\n    * \n    * @see #describeImages\n    * @see #deregisterImage\n    * @see <a href=\n    *      \"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-RegisterImage.html\"\n    *      />\n    */\n   @Named(\"RegisterImage\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"RegisterImage\")\n   @XMLResponseParser(ImageIdHandler.class)\n   String registerImageFromManifestInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n            @FormParam(\"Name\") String imageName, @FormParam(\"ImageLocation\") String pathToManifest,\n            RegisterImageOptions... options);\n\n   /**\n    * Registers an AMI with Amazon EC2. Images must be registered before they can be launched. To\n    * launch instances, use the {@link InstanceApi#runInstances} operation. The root device name\n    * is /dev/sda1\n    * <p/>\n    * Each AMI is associated with an unique ID which is provided by the Amazon EC2 service through\n    * this operation. If needed, you can deregister an AMI at any time.\n    * <p/>\n    * <h3>Note</h3> AMIs backed by Amazon EBS are automatically registered when you create the\n    * image. However, you can use this to register a snapshot of an instance backed by Amazon EBS.\n    * <p/>\n    * Amazon EBS snapshots are not guaranteed to be bootable.\n    * \n    * @param region\n    *           AMIs are tied to the Region where its files are located within Amazon S3.\n    * @param name\n    *           The name of the AMI that was provided during image creation. 3-128 alphanumeric\n    *           characters, parenthesis (()), commas (,), slashes (/), dashes (-), or underscores(_)\n    * \n    * @param ebsSnapshotId\n    *           The id of the root snapshot (e.g., snap-6eba6e06).\n    * @param options\n    *           Options to specify metadata such as architecture or secondary volumes to be\n    *           associated with this image.\n    * @return imageId\n    * \n    * @see #describeImages\n    * @see #deregisterImage\n    * @see <a href=\n    *      \"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-RegisterImage.html\"\n    *      />\n    */\n   @Named(\"RegisterImage\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = { ACTION, \"RootDeviceName\", \"BlockDeviceMapping.0.DeviceName\" }, values = { \"RegisterImage\",\n            \"/dev/sda1\", \"/dev/sda1\" })\n   @XMLResponseParser(ImageIdHandler.class)\n   String registerUnixImageBackedByEbsInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n            @FormParam(\"Name\") String imageName,\n            @FormParam(\"BlockDeviceMapping.0.Ebs.SnapshotId\") String ebsSnapshotId,\n            RegisterImageBackedByEbsOptions... options);\n\n   /**\n    * Resets the {@code launchPermission}s on an AMI.\n    * \n    * @param region\n    *           AMIs are tied to the Region where its files are located within Amazon S3.\n    * @param imageId\n    *           ID of the AMI on which the attribute will be reset.\n    * \n    * @see #addLaunchPermissionsToImage\n    * @see #describeImageAttribute\n    * @see #removeProductCodesFromImage\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-ResetImageAttribute.html\"\n    *      />\n    */\n   @Named(\"ResetImageAttribute\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = { ACTION, \"Attribute\" }, values = { \"ResetImageAttribute\", \"launchPermission\" })\n   void resetLaunchPermissionsOnImageInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n            @FormParam(\"ImageId\") String imageId);\n\n   /**\n    * Adds {@code launchPermission}s to an AMI.\n    * \n    * @param region\n    *           AMIs are tied to the Region where its files are located within Amazon S3.\n    * @param userIds\n    *           AWS Access Key ID.\n    * @param userGroups\n    *           Name of the groups. Currently supports \\\"all.\\\"\"\n    * @param imageId\n    *           The AMI ID.\n    * \n    * @see #removeLaunchPermissionsFromImage\n    * @see #describeImageAttribute\n    * @see #resetImageAttribute\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-ModifyImageAttribute.html\"\n    *      />\n    */\n   @Named(\"ModifyImageAttribute\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = { ACTION, \"OperationType\", \"Attribute\" }, values = { \"ModifyImageAttribute\", \"add\",\n            \"launchPermission\" })\n   void addLaunchPermissionsToImageInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n            @BinderParam(BindUserIdsToIndexedFormParams.class) Iterable<String> userIds,\n            @BinderParam(BindUserGroupsToIndexedFormParams.class) Iterable<String> userGroups,\n            @FormParam(\"ImageId\") String imageId);\n\n   /**\n    * @see AMIApi#removeLaunchPermissionsToImageInRegion\n    */\n   @Named(\"ModifyImageAttribute\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = { ACTION, \"OperationType\", \"Attribute\" }, values = { \"ModifyImageAttribute\", \"remove\",\n            \"launchPermission\" })\n   void removeLaunchPermissionsFromImageInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n            @BinderParam(BindUserIdsToIndexedFormParams.class) Iterable<String> userIds,\n            @BinderParam(BindUserGroupsToIndexedFormParams.class) Iterable<String> userGroups,\n            @FormParam(\"ImageId\") String imageId);\n\n   /**\n    * Returns the {@link Permission}s of an image.\n    * \n    * @param region\n    *           AMIs are tied to the Region where its files are located within Amazon S3.\n    * @param imageId\n    *           The ID of the AMI for which an attribute will be described\n    * @see #describeImages\n    * @see #modifyImageAttribute\n    * @see #resetImageAttribute\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeImageAttribute.html\"\n    *      />\n    * @see DescribeImagesOptions\n    */\n   @Named(\"DescribeImageAttribute\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = { ACTION, \"Attribute\" }, values = { \"DescribeImageAttribute\", \"launchPermission\" })\n   @XMLResponseParser(PermissionHandler.class)\n   Permission getLaunchPermissionForImageInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n            @FormParam(\"ImageId\") String imageId);\n\n   /**\n    * Returns a map of device name to block device for the image.\n    * \n    * @param region\n    *           AMIs are tied to the Region where its files are located within Amazon S3.\n    * @param imageId\n    *           The ID of the AMI for which an attribute will be described\n    * @see #describeImages\n    * @see #modifyImageAttribute\n    * @see #resetImageAttribute\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeImageAttribute.html\"\n    *      />\n    * @see DescribeImagesOptions\n    */\n   @Named(\"DescribeImageAttribute\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = { ACTION, \"Attribute\" }, values = { \"DescribeImageAttribute\", \"blockDeviceMapping\" })\n   @XMLResponseParser(BlockDeviceMappingHandler.class)\n   Map<String, EbsBlockDevice> getBlockDeviceMappingsForImageInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n            @FormParam(\"ImageId\") String imageId);\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/features/AvailabilityZoneAndRegionApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.features;\n\nimport static org.jclouds.aws.reference.FormParameters.ACTION;\n\nimport java.net.URI;\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.aws.filters.FormSigner;\nimport org.jclouds.ec2.domain.AvailabilityZoneInfo;\nimport org.jclouds.ec2.options.DescribeAvailabilityZonesOptions;\nimport org.jclouds.ec2.options.DescribeRegionsOptions;\nimport org.jclouds.ec2.xml.DescribeAvailabilityZonesResponseHandler;\nimport org.jclouds.ec2.xml.DescribeRegionsResponseHandler;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.location.functions.RegionToEndpointOrProviderIfNull;\nimport org.jclouds.rest.annotations.EndpointParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.FormParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.VirtualHost;\nimport org.jclouds.rest.annotations.XMLResponseParser;\n\n/**\n * Provides access to EC2 Availability Zones and Regions via their REST API.\n * <p/>\n */\n@RequestFilters(FormSigner.class)\n@VirtualHost\npublic interface AvailabilityZoneAndRegionApi {\n\n   /**\n    * Displays Availability Zones that are currently available to the identity and their states.\n    * \n    * @see InstanceApi#runInstances\n    * @see #describeRegions\n    * \n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeAvailabilityZones.html\"\n    *      />\n    */\n   @Named(\"DescribeAvailabilityZones\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DescribeAvailabilityZones\")\n   @XMLResponseParser(DescribeAvailabilityZonesResponseHandler.class)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<AvailabilityZoneInfo> describeAvailabilityZonesInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n            DescribeAvailabilityZonesOptions... options);\n\n   /**\n    * Describes Regions that are currently available to the identity.\n    * \n    * @see InstanceApi#runInstances\n    * @see #describeAvailabilityZones\n    * \n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeRegions.html\"\n    *      />\n    */\n   @Named(\"DescribeRegions\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DescribeRegions\")\n   @XMLResponseParser(DescribeRegionsResponseHandler.class)\n   Map<String, URI> describeRegions(DescribeRegionsOptions... options);\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/features/ElasticBlockStoreApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.features;\n\nimport static org.jclouds.aws.reference.FormParameters.ACTION;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.FormParam;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.aws.filters.FormSigner;\nimport org.jclouds.ec2.EC2Fallbacks.VoidOnVolumeAvailable;\nimport org.jclouds.ec2.binders.BindFiltersToIndexedFormParams;\nimport org.jclouds.ec2.binders.BindUserGroupsToIndexedFormParams;\nimport org.jclouds.ec2.binders.BindUserIdsToIndexedFormParams;\nimport org.jclouds.ec2.binders.BindVolumeIdsToIndexedFormParams;\nimport org.jclouds.ec2.domain.Attachment;\nimport org.jclouds.ec2.domain.Permission;\nimport org.jclouds.ec2.domain.Snapshot;\nimport org.jclouds.ec2.domain.Volume;\nimport org.jclouds.ec2.options.CreateSnapshotOptions;\nimport org.jclouds.ec2.options.CreateVolumeOptions;\nimport org.jclouds.ec2.options.DescribeSnapshotsOptions;\nimport org.jclouds.ec2.options.DetachVolumeOptions;\nimport org.jclouds.ec2.xml.AttachmentHandler;\nimport org.jclouds.ec2.xml.CreateVolumeResponseHandler;\nimport org.jclouds.ec2.xml.DescribeSnapshotsResponseHandler;\nimport org.jclouds.ec2.xml.DescribeVolumesResponseHandler;\nimport org.jclouds.ec2.xml.PermissionHandler;\nimport org.jclouds.ec2.xml.SnapshotHandler;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.location.functions.RegionToEndpointOrProviderIfNull;\nimport org.jclouds.location.functions.ZoneToEndpoint;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.EndpointParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.FormParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.VirtualHost;\nimport org.jclouds.rest.annotations.XMLResponseParser;\n\nimport com.google.common.collect.Multimap;\n\n/**\n * Provides access to EC2 Elastic Block Store services via their REST API.\n * <p/>\n */\n@RequestFilters(FormSigner.class)\n@VirtualHost\npublic interface ElasticBlockStoreApi {\n\n   /**\n    * Creates a new Amazon EBS volume to which any Amazon EC2 instance can attach within the same\n    * Availability Zone. For more information about Amazon EBS, go to the Amazon Elastic Compute\n    * Cloud Developer Guide or Amazon Elastic Compute Cloud User Guide.\n    * \n    * @param availabilityZone\n    *           An Amazon EBS volume must be located within the same Availability Zone as the\n    *           instance to which it attaches.\n    * @param snapshotId\n    *           The snapshot from which to create the new volume.\n    * \n    * @see #describeVolumesInRegion\n    * @see #deleteVolumeInRegion\n    * @see #attachVolumeInRegion\n    * @see #detachVolumeInRegion\n    * @see AvailabilityZoneAndRegionApi#describeAvailabilityZonesInRegion\n    * \n    * \n    * @see <a href=\n    *      \"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateVolume.html\"\n    *      />\n    */\n   @Named(\"CreateVolume\")   \n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"CreateVolume\")\n   @XMLResponseParser(CreateVolumeResponseHandler.class)\n   Volume createVolumeFromSnapshotInAvailabilityZone(\n            @EndpointParam(parser = ZoneToEndpoint.class) @FormParam(\"AvailabilityZone\") String availabilityZone,\n            @FormParam(\"SnapshotId\") String snapshotId);\n\n   /**\n    * Creates a new Amazon EBS volume to which any Amazon EC2 instance can attach within the same\n    * Availability Zone. This is overloaded {@link #createVolumeFromSnapshotInAvailabilityZone},\n    * which creates a volume with a specific size.\n    * For more information about Amazon EBS, go to the Amazon Elastic Compute\n    * Cloud Developer Guide or Amazon Elastic Compute Cloud User Guide.\n    *\n    * @param availabilityZone\n    *           An Amazon EBS volume must be located within the same Availability Zone as the\n    *           instance to which it attaches.\n    * @param size\n    *           Size of volume to be created\n    * @param snapshotId\n    *           The snapshot from which to create the new volume.\n    *\n    * @see #createVolumeFromSnapshotInAvailabilityZone\n    * @see #describeVolumesInRegion\n    * @see #deleteVolumeInRegion\n    * @see #attachVolumeInRegion\n    * @see #detachVolumeInRegion\n    * @see AvailabilityZoneAndRegionApi#describeAvailabilityZonesInRegion\n    *\n    *\n    * @see <a href=\n    *      \"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateVolume.html\"\n    *      />\n    */\n   @Named(\"CreateVolume\")   \n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"CreateVolume\")\n   @XMLResponseParser(CreateVolumeResponseHandler.class)\n   Volume createVolumeFromSnapshotInAvailabilityZone(\n            @EndpointParam(parser = ZoneToEndpoint.class) @FormParam(\"AvailabilityZone\") String availabilityZone,\n            @FormParam(\"Size\") int size, @FormParam(\"SnapshotId\") String snapshotId);\n\n   /**\n    * Creates a new Amazon EBS volume to which any Amazon EC2 instance can attach within the same\n    * Availability Zone. For more information about Amazon EBS, go to the Amazon Elastic Compute\n    * Cloud Developer Guide or Amazon Elastic Compute Cloud User Guide.\n    * \n    * @param availabilityZone\n    *           An Amazon EBS volume must be located within the same Availability Zone as the\n    *           instance to which it attaches.\n    * @param size\n    *           The size of the volume, in GiBs (1-1024). Required if you are not creating a volume\n    *           from a snapshot.\n    * \n    * \n    * @see #describeVolumesInRegion\n    * @see #deleteVolumeInRegion\n    * @see #attachVolumeInRegion\n    * @see #detachVolumeInRegion\n    * @see AvailabilityZoneAndRegionApi#describeAvailabilityZonesInRegion\n    * @see <a href=\n    *      \"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateVolume.html\"\n    *      />\n    */\n   @Named(\"CreateVolume\")   \n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"CreateVolume\")\n   @XMLResponseParser(CreateVolumeResponseHandler.class)\n   Volume createVolumeInAvailabilityZone(\n            @EndpointParam(parser = ZoneToEndpoint.class) @FormParam(\"AvailabilityZone\") String availabilityZone,\n            @FormParam(\"Size\") int size);\n\n   /**\n    * Creates a new Amazon EBS volume to which any Amazon EC2 instance can attach within the same\n    * Availability Zone. For more information about Amazon EBS, go to the Amazon Elastic Compute\n    * Cloud Developer Guide or Amazon Elastic Compute Cloud User Guide.\n    *\n    * @param availabilityZone\n    *           An Amazon EBS volume must be located within the same Availability Zone as the\n    *           instance to which it attaches.\n    * @param options\n    *           options like specifying a snapshot, EBS volume type, etc\n    *\n    *\n    * @see #describeVolumesInRegion\n    * @see #deleteVolumeInRegion\n    * @see #attachVolumeInRegion\n    * @see #detachVolumeInRegion\n    * @see AvailabilityZoneAndRegionApi#describeAvailabilityZonesInRegion\n    * @see <a href=\n    *      \"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateVolume.html\"\n    *      />\n    */\n   @Named(\"CreateVolume\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"CreateVolume\")\n   @XMLResponseParser(CreateVolumeResponseHandler.class)\n   Volume createVolumeInAvailabilityZone(\n           @EndpointParam(parser = ZoneToEndpoint.class) @FormParam(\"AvailabilityZone\") String availabilityZone,\n           CreateVolumeOptions... options);\n\n   /**\n    * Describes the specified Amazon EBS volumes that you own. If you do not specify one or more\n    * volume IDs, Amazon EBS describes all volumes that you own. For more information about Amazon\n    * EBS, go to the Amazon Elastic Compute Cloud Developer Guide or Amazon Elastic Compute Cloud\n    * User Guide.\n    *\n    * @param region\n    *           region where the volume is defined\n    * @param volumeIds\n    *           The ID of the volume to list. Defaults to describe all volumes that you own.\n    *\n    * @see #createSnapshotInRegion\n    * @see #describeSnapshotInRegion\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeVolumes.html\"\n    *      />\n    */\n   @POST\n   @Named(\"DescribeVolumes\")\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DescribeVolumes\")\n   @XMLResponseParser(DescribeVolumesResponseHandler.class)\n   Set<Volume> describeVolumesInRegion(\n           @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n           @BinderParam(BindVolumeIdsToIndexedFormParams.class) String... volumeIds);\n\n   /**\n    * Describes the specified Amazon EBS volumes that you own and match the given filters. If you\n    * do not specify any filters, Amazon EBS describes all volumes that you own. For more\n    * information about Amazon EBS, go to the Amazon Elastic Compute Cloud Developer Guide or\n    * Amazon Elastic Compute Cloud User Guide.\n    *\n    * @param region\n    *           region where the volume is defined\n    * @param filter\n    *           Multimap of filter key/values\n    *\n    * @see #createSnapshotInRegion\n    * @see #describeSnapshotInRegion\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeVolumes.html\"\n    *      />\n    */\n   @POST\n   @Named(\"DescribeVolumes\")\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DescribeVolumes\")\n   @XMLResponseParser(DescribeVolumesResponseHandler.class)\n   Set<Volume> describeVolumesInRegionWithFilter(\n           @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n           @BinderParam(BindFiltersToIndexedFormParams.class) Multimap<String, String> filter);\n\n   /**\n    * Deletes an Amazon EBS volume that you own. For more information about Amazon EBS, go to the\n    * Amazon Elastic Compute Cloud Developer Guide or Amazon Elastic Compute Cloud User Guide.\n    * \n    * @param region\n    *           region where the volume is defined\n    * @param volumeId\n    *           The ID of the volume to delete. The volume remains in the deleting state for several\n    *           minutes after entering this command.\n    * \n    * @see #describeVolumesInRegion\n    * @see #createVolumeInRegion\n    * @see #attachVolumeInRegion\n    * @see #detachVolumeInRegion\n    * \n    * @see <a href=\n    *      \"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteVolume.html\"\n    *      />\n    */\n   @Named(\"DeleteVolume\")   \n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DeleteVolume\")\n   void deleteVolumeInRegion(@EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n            @FormParam(\"VolumeId\") String volumeId);\n\n   /**\n    * Attaches an Amazon EBS volume to a running instance and exposes it as the specified device.\n    * <p/>\n    * \n    * <h3>Note</h3>\n    * \n    * Windows instances currently support devices xvda through xvdp. Devices xvda and xvdb are\n    * reserved by the operating system, xvdc is assigned to drive C:\\, and, depending on the\n    * instance type, devices xvdd through xvde might be reserved by the instance stores. Any device\n    * that is not reserved can be attached to an Amazon EBS volume. For a list of devices that are\n    * reserved by the instance stores, go to the Amazon Elastic Compute Cloud Developer Guide or\n    * Amazon Elastic Compute Cloud User Guide.\n    * \n    * @param region\n    *           region where the volume is defined\n    * @param volumeId\n    *           The ID of the volume to delete. The volume remains in the deleting state for several\n    *           minutes after entering this command.\n    * @param force\n    *           Forces detachment if the previous detachment attempt did not occur cleanly (logging\n    *           into an instance, unmounting the volume, and detaching normally). This option can\n    *           lead to data loss or a corrupted file system. Use this option only as a last resort\n    *           to detach a volume from a failed instance. The instance will not have an opportunity\n    *           to flush file system caches nor file system meta data. If you use this option, you\n    *           must perform file system check and repair procedures.\n    * \n    * @param options\n    *           options like force()\n    * \n    * @see #describeVolumesInRegion\n    * @see #createVolumeInRegion\n    * @see #attachVolumeInRegion\n    * @see #deleteVolumeInRegion\n    * \n    * @see <a href=\n    *      \"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DetachVolume.html\"\n    *      />\n    */\n   @Named(\"DetachVolume\")   \n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DetachVolume\")\n   @Fallback(VoidOnVolumeAvailable.class)\n   void detachVolumeInRegion(@EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n            @FormParam(\"VolumeId\") String volumeId, @FormParam(\"Force\") boolean force, DetachVolumeOptions... options);\n\n   /**\n    * Attaches an Amazon EBS volume to a running instance and exposes it as the specified device.\n    * \n    * <h3>Note</h3> Windows instances currently support devices xvda through xvdp. Devices xvda and\n    * xvdb are reserved by the operating system, xvdc is assigned to drive C:\\, and, depending on\n    * the instance type, devices xvdd through xvde might be reserved by the instance stores. Any\n    * device that is not reserved can be attached to an Amazon EBS volume. For a list of devices\n    * that are reserved by the instance stores, go to the Amazon Elastic Compute Cloud Developer\n    * Guide or Amazon Elastic Compute Cloud User Guide.\n    * \n    * @param region\n    *           region where the volume is defined\n    * @param volumeId\n    *           The ID of the Amazon EBS volume. The volume and instance must be within the same\n    *           Availability Zone and the instance must be running.\n    * @param instanceId\n    *           The ID of the instance to which the volume attaches. The volume and instance must be\n    *           within the same Availability Zone and the instance must be running.\n    * @param device\n    *           Specifies how the device is exposed to the instance (e.g., /dev/sdh).\n    * \n    * @see #describeVolumesInRegion\n    * @see #createVolumeInRegion\n    * @see #detachVolumeInRegion\n    * @see #deleteVolumeInRegion\n    * \n    * @see <a href=\n    *      \"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-AttachVolume.html\"\n    *      />\n    */\n   @Named(\"AttachVolume\")   \n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"AttachVolume\")\n   @XMLResponseParser(AttachmentHandler.class)\n   Attachment attachVolumeInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n            @FormParam(\"VolumeId\") String volumeId, @FormParam(\"InstanceId\") String instanceId,\n            @FormParam(\"Device\") String device);\n\n   /**\n    * Creates a snapshot of an Amazon EBS volume and stores it in Amazon S3. You can use snapshots\n    * for backups, to make identical copies of instance devices, and to save data before shutting\n    * down an instance. For more information about Amazon EBS, go to the Amazon Elastic Compute\n    * Cloud Developer Guide or Amazon Elastic Compute Cloud User Guide.\n    * <p/>\n    * When taking a snapshot of a file system, we recommend unmounting it first. This ensures the\n    * file system metadata is in a consistent state, that the 'mounted indicator' is cleared, and\n    * that all applications using that file system are stopped and in a consistent state. Some file\n    * systems, such as xfs, can freeze and unfreeze activity so a snapshot can be made without\n    * unmounting.\n    * <p/>\n    * For Linux/UNIX, enter the following command from the command line.\n    * \n    * <pre>\n    * umount - d / dev / sdh\n    * </pre>\n    * <p/>\n    * For Windows, open Disk Management, right-click the volume to unmount, and select Change Drive\n    * Letter and Path. Then, select the mount point to remove and click Remove.\n    * \n    * @param region\n    *           Snapshots are tied to Regions and can only be used for volumes within the same\n    *           Region.\n    * @param volumeId\n    *           The ID of the Amazon EBS volume of which to take a snapshot.\n    * @param options\n    *           options like passing a description.\n    * @return the Snapshot in progress\n    * \n    * @see #describeSnapshotsInRegion\n    * @see #deleteSnapshotInRegion\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateSnapshot.html\"\n    *      />\n    */\n   @Named(\"CreateSnapshot\")   \n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"CreateSnapshot\")\n   @XMLResponseParser(SnapshotHandler.class)\n   Snapshot createSnapshotInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n            @FormParam(\"VolumeId\") String volumeId, CreateSnapshotOptions... options);\n\n   /**\n    * Returns information about Amazon EBS snapshots available to the user. Information returned\n    * includes volume ID, status, start time, progress, owner ID, volume size, and description.\n    * Snapshots available to the user include public snapshots available for any user to\n    * createVolume, private snapshots owned by the user making the request, and private snapshots\n    * owned by other users for which the user granted explicit create volume permissions.\n    * <p/>\n    * The create volume permissions fall into 3 categories:\n    * <p/>\n    * <table>\n    * <tr>\n    * <td>Permission</td>\n    * <td>Description</td>\n    * </tr>\n    * <tr>\n    * <td>public</td>\n    * <td>The owner of the snapshot granted create volume permissions for the snapshot to the all\n    * group. All users have create volume permissions for these snapshots.</td>\n    * </tr>\n    * <tr>\n    * <td>explicit</td>\n    * <td>The owner of the snapshot granted create volume permissions to a specific user.</td>\n    * </tr>\n    * <tr>\n    * <td>implicit</td>\n    * <td>A user has implicit create volume permissions for all snapshots he or she owns.</td>\n    * </tr>\n    * </table>\n    * <p/>\n    * \n    * The list of snapshots returned can be modified by specifying snapshot IDs, snapshot owners, or\n    * users with create volume permissions. If no options are specified, Amazon EC2 returns all\n    * snapshots for which the user has create volume permissions.\n    * <p/>\n    * If you specify one or more snapshot IDs, only snapshots that have the specified IDs are\n    * returned. If you specify an invalid snapshot ID, a fault is returned. If you specify a\n    * snapshot ID for which you do not have access, it will not be included in the returned results.\n    * <p/>\n    * If you specify one or more snapshot owners, only snapshots from the specified owners and for\n    * which you have access are returned. The results can include the AWS Account IDs of the\n    * specified owners, amazon for snapshots owned by Amazon or self for snapshots that you own.\n    * <p/>\n    * If you specify a list of restorable users, only users that have create snapshot permissions\n    * for the snapshots are returned. You can specify AWS Account IDs (if you own the snapshot(s)),\n    * self for snapshots for which you own or have explicit permissions, or all for public\n    * snapshots.\n    * \n    * @param region\n    *           Snapshots are tied to Regions and can only be used for volumes within the same\n    *           Region.\n    * @param options\n    *           specify the snapshot ids or other parameters to clarify the list.\n    * @return matching snapshots.\n    * \n    * @see #createSnapshotsInRegion\n    * @see #deleteSnapshotInRegion\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeSnapshots.html\"\n    *      />\n    */\n   @Named(\"DescribeSnapshots\")   \n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DescribeSnapshots\")\n   @XMLResponseParser(DescribeSnapshotsResponseHandler.class)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<Snapshot> describeSnapshotsInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n            DescribeSnapshotsOptions... options);\n\n   /**\n    * Returns information about EBS snapshots matching the given filters.\n    *\n    * @param region\n    *           Snapshots are tied to Regions and can only be used for volumes within the same\n    *           Region.\n    * @param filter\n    *           Multimap of filter key/values.\n    * @param options\n    *           specify the snapshot ids or other parameters to clarify the list.\n    * @return matching snapshots.\n    *\n    * @see #describeSnapshotsInRegion\n    * @see #createSnapshotsInRegion\n    * @see #deleteSnapshotInRegion\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeSnapshots.html\"\n    *      />\n    */\n   @Named(\"DescribeSnapshots\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DescribeSnapshots\")\n   @XMLResponseParser(DescribeSnapshotsResponseHandler.class)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<Snapshot> describeSnapshotsInRegionWithFilter(\n           @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n           @BinderParam(BindFiltersToIndexedFormParams.class) Multimap<String, String> filter,\n           DescribeSnapshotsOptions... options);\n\n   /**\n    * Deletes a snapshot of an Amazon EBS volume that you own. For more information, go to the\n    * Amazon Elastic Compute Cloud Developer Guide or Amazon Elastic Compute Cloud User Guide.\n    * \n    * @param region\n    *           Snapshots are tied to Regions and can only be used for volumes within the same\n    *           Region.\n    * @param snapshotId\n    *           The ID of the Amazon EBS snapshot to delete.\n    * \n    * @see #createSnapshotInRegion\n    * @see #deleteSnapshotInRegion\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteSnapshot.html\"\n    *      />\n    */\n   @Named(\"DeleteSnapshot\")   \n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DeleteSnapshot\")\n   void deleteSnapshotInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n            @FormParam(\"SnapshotId\") String snapshotId);\n\n   /**\n    * Adds {@code createVolumePermission}s to an EBS snapshot.\n    * \n    * @param region\n    *           Snapshots are tied to Regions and can only be used for volumes within the same\n    *           Region.\n    * @param userIds\n    *           AWS Access Key ID.\n    * @param userGroups\n    *           Name of the groups. Currently supports \\\"all.\\\"\"\n    * @param snapshotId\n    *           The ID of the Amazon EBS snapshot.\n    * \n    * @see #removeCreateVolumePermissionsFromSnapshot\n    * @see #describeSnapshotAttribute\n    * @see #resetSnapshotAttribute\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-ModifySnapshotAttribute.html\"\n    *      />\n    */\n   @Named(\"ModifySnapshotAttribute\")   \n   @POST\n   @Path(\"/\")\n   @FormParams(keys = { ACTION, \"OperationType\", \"Attribute\" }, values = { \"ModifySnapshotAttribute\", \"add\",\n            \"createVolumePermission\" })\n   void addCreateVolumePermissionsToSnapshotInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n            @BinderParam(BindUserIdsToIndexedFormParams.class) Iterable<String> userIds,\n            @BinderParam(BindUserGroupsToIndexedFormParams.class) Iterable<String> userGroups,\n            @FormParam(\"SnapshotId\") String snapshotId);\n\n   /**\n    * Removes {@code createVolumePermission}s from an EBS snapshot.\n    * \n    * @param region\n    *           Snapshots are tied to Regions and can only be used for volumes within the same\n    *           Region.\n    * @param userIds\n    *           AWS Access Key ID.\n    * @param userGroups\n    *           Name of the groups. Currently supports \\\"all.\\\"\"\n    * @param snapshotId\n    *           The ID of the Amazon EBS snapshot.\n    * \n    * @see #addCreateVolumePermissionsToSnapshot\n    * @see #describeSnapshotAttribute\n    * @see #resetSnapshotAttribute\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-ModifySnapshotAttribute.html\"\n    *      />\n    */\n   @Named(\"ModifySnapshotAttribute\")   \n   @POST\n   @Path(\"/\")\n   @FormParams(keys = { ACTION, \"OperationType\", \"Attribute\" }, values = { \"ModifySnapshotAttribute\", \"remove\",\n            \"createVolumePermission\" })\n   void removeCreateVolumePermissionsFromSnapshotInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n            @BinderParam(BindUserIdsToIndexedFormParams.class) Iterable<String> userIds,\n            @BinderParam(BindUserGroupsToIndexedFormParams.class) Iterable<String> userGroups,\n            @FormParam(\"SnapshotId\") String snapshotId);\n\n   /**\n    * Returns the {@link Permission}s of an snapshot.\n    * \n    * @param region\n    *           AMIs are tied to the Region where its files are located within Amazon S3.\n    * @param snapshotId\n    *           The ID of the AMI for which an attribute will be described\n    * @see #describeSnapshots\n    * @see #modifySnapshotAttribute\n    * @see #resetSnapshotAttribute\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeSnapshotAttribute.html\"\n    *      />\n    * @see DescribeSnapshotsOptions\n    */\n   @Named(\"DescribeSnapshotAttribute\")   \n   @POST\n   @Path(\"/\")\n   @FormParams(keys = { ACTION, \"Attribute\" }, values = { \"DescribeSnapshotAttribute\", \"createVolumePermission\" })\n   @XMLResponseParser(PermissionHandler.class)\n   Permission getCreateVolumePermissionForSnapshotInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n            @FormParam(\"SnapshotId\") String snapshotId);\n\n   /**\n    * Resets the {@code createVolumePermission}s on an EBS snapshot.\n    * \n    * @param region\n    *           Snapshots are tied to Regions and can only be used for volumes within the same\n    *           Region.\n    * @param snapshotId\n    *           The ID of the Amazon EBS snapshot.\n    * \n    * @see #addCreateVolumePermissionsToSnapshot\n    * @see #describeSnapshotAttribute\n    * @see #removeProductCodesFromSnapshot\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-ResetSnapshotAttribute.html\"\n    *      />\n    */\n   @Named(\"ResetSnapshotAttribute\")   \n   @POST\n   @Path(\"/\")\n   @FormParams(keys = { ACTION, \"Attribute\" }, values = { \"ResetSnapshotAttribute\", \"createVolumePermission\" })\n   void resetCreateVolumePermissionsOnSnapshotInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n            @FormParam(\"SnapshotId\") String snapshotId);\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/features/ElasticIPAddressApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.features;\n\nimport static org.jclouds.aws.reference.FormParameters.ACTION;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.FormParam;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.aws.filters.FormSigner;\nimport org.jclouds.ec2.binders.BindFiltersToIndexedFormParams;\nimport org.jclouds.ec2.binders.BindPublicIpsToIndexedFormParams;\nimport org.jclouds.ec2.domain.PublicIpInstanceIdPair;\nimport org.jclouds.ec2.xml.AllocateAddressResponseHandler;\nimport org.jclouds.ec2.xml.DescribeAddressesResponseHandler;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.location.functions.RegionToEndpointOrProviderIfNull;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.EndpointParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.FormParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SinceApiVersion;\nimport org.jclouds.rest.annotations.VirtualHost;\nimport org.jclouds.rest.annotations.XMLResponseParser;\n\nimport com.google.common.collect.Multimap;\n\n/**\n * Provides access to EC2 Elastic IP Addresses via REST API.\n * <p/>\n */\n@RequestFilters(FormSigner.class)\n@VirtualHost\npublic interface ElasticIPAddressApi {\n\n   /**\n    * Acquires an elastic IP address for use with your identity.\n    * \n    * @param region\n    *           Elastic IP addresses are tied to a Region and cannot be mapped across Regions.\n    * @see #describeAddresses\n    * @see #releaseAddress\n    * @see #associateAddress\n    * @see #disassociateAddress\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-AllocateAddress.html\"\n    */\n   @Named(\"AllocateAddress\")\n   @POST\n   @Path(\"/\")\n   @XMLResponseParser(AllocateAddressResponseHandler.class)\n   @FormParams(keys = ACTION, values = \"AllocateAddress\")\n   String allocateAddressInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region);\n\n   /**\n    * Associates an elastic IP address with an instance. If the IP address is currently assigned to\n    * another instance, the IP address is assigned to the new instance. This is an idempotent\n    * operation. If you enter it more than once, Amazon EC2 does not return an error.\n    * \n    * @param region\n    *           Elastic IP addresses are tied to a Region and cannot be mapped across Regions.\n    * @param publicIp\n    *           IP address that you are assigning to the instance.\n    * @param instanceId\n    *           The instance to associate with the IP address.\n    * \n    * @see #allocateAddress\n    * @see #describeAddresses\n    * @see #releaseAddress\n    * @see #disassociateAddress\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-query-AssociateAddress.html\"\n    */\n   @Named(\"AssociateAddress\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"AssociateAddress\")\n   void associateAddressInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n            @FormParam(\"PublicIp\") String publicIp, @FormParam(\"InstanceId\") String instanceId);\n\n   /**\n    * Disassociates the specified elastic IP address from the instance to which it is assigned. This\n    * is an idempotent operation. If you enter it more than once, Amazon EC2 does not return an\n    * error.\n    * \n    * @param region\n    *           Elastic IP addresses are tied to a Region and cannot be mapped across Regions.\n    * @param publicIp\n    *           IP address that you are assigning to the instance.\n    * \n    * @see #allocateAddress\n    * @see #describeAddresses\n    * @see #releaseAddress\n    * @see #associateAddress\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-query-DisassociateAddress.html\"\n    */\n   @Named(\"DisassociateAddress\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DisassociateAddress\")\n   void disassociateAddressInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n            @FormParam(\"PublicIp\") String publicIp);\n\n   /**\n    * Releases an elastic IP address associated with your identity.\n    * \n    * @param region\n    *           Elastic IP addresses are tied to a Region and cannot be mapped across Regions.\n    * @param publicIp\n    *           The IP address that you are releasing from your identity.\n    * \n    * @see #allocateAddress\n    * @see #describeAddresses\n    * @see #associateAddress\n    * @see #disassociateAddress\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-query-ReleaseAddress.html\"\n    */\n   @Named(\"ReleaseAddress\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"ReleaseAddress\")\n   void releaseAddressInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n            @FormParam(\"PublicIp\") String publicIp);\n\n   /**\n    * Releases an elastic IP address associated with your identity.\n    *\n    * @param region\n    *           Elastic IP addresses are tied to a Region and cannot be mapped across Regions.\n    * @param allocationId\n    *           The Allocation ID (e.g., eipalloc-0ca038968f2a2c986) of the IP address that you are releasing from your identity.\n    *\n    * @see #allocateAddress\n    * @see #describeAddresses\n    * @see #associateAddress\n    * @see #disassociateAddress\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-query-ReleaseAddress.html\"\n    */\n   @Named(\"ReleaseAddress\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"ReleaseAddress\")\n   void releaseAddressInRegionByAllocationId(\n           @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n           @FormParam(\"AllocationId\") String allocationId);\n\n   /**\n    * Lists elastic IP addresses assigned to your identity or provides information about a specific\n    * address.\n    * \n    * @param region\n    *           Elastic IP addresses are tied to a Region and cannot be mapped across Regions.\n    * @param publicIps\n    *           Elastic IP address to describe.\n    * \n    * @throws AWSResponseException\n    *            if the requested publicIp is not found\n    * @see #allocateAddress\n    * @see #releaseAddress\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeAddresses.html\"\n    *      />\n    */\n   @Named(\"DescribeAddresses\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DescribeAddresses\")\n   @XMLResponseParser(DescribeAddressesResponseHandler.class)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<PublicIpInstanceIdPair> describeAddressesInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n            @BinderParam(BindPublicIpsToIndexedFormParams.class) String... publicIps);\n\n   /**\n    * Lists elastic IP addresses assigned to your identity or provides information on addresses\n    * matching a given filter.\n    *\n    * @param region\n    *           Elastic IP addresses are tied to a Region and cannot be mapped across Regions.\n    * @param filter\n    *\n    * @throws AWSResponseException\n    *            if the requested publicIp is not found\n    * @see #allocateAddress\n    * @see #releaseAddress\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeAddresses.html\"\n    *      />\n    */\n   @SinceApiVersion(\"2010-08-31\")\n   @Named(\"DescribeAddresses\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DescribeAddresses\")\n   @XMLResponseParser(DescribeAddressesResponseHandler.class)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<PublicIpInstanceIdPair> describeAddressesInRegionWithFilter(\n           @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n           @BinderParam(BindFiltersToIndexedFormParams.class) Multimap<String, String> filter);\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/features/InstanceApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.features;\n\nimport static org.jclouds.aws.reference.FormParameters.ACTION;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.FormParam;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.aws.filters.FormSigner;\nimport org.jclouds.ec2.binders.BindBlockDeviceMappingToIndexedFormParams;\nimport org.jclouds.ec2.binders.BindFiltersToIndexedFormParams;\nimport org.jclouds.ec2.binders.BindInstanceIdsToIndexedFormParams;\nimport org.jclouds.ec2.binders.IfNotNullBindAvailabilityZoneToFormParam;\nimport org.jclouds.ec2.domain.BlockDevice;\nimport org.jclouds.ec2.domain.InstanceStateChange;\nimport org.jclouds.ec2.domain.Reservation;\nimport org.jclouds.ec2.domain.RunningInstance;\nimport org.jclouds.ec2.domain.Volume.InstanceInitiatedShutdownBehavior;\nimport org.jclouds.ec2.functions.ConvertUnencodedBytesToBase64EncodedString;\nimport org.jclouds.ec2.options.RunInstancesOptions;\nimport org.jclouds.ec2.xml.BlockDeviceMappingHandler;\nimport org.jclouds.ec2.xml.BooleanValueHandler;\nimport org.jclouds.ec2.xml.DescribeInstancesResponseHandler;\nimport org.jclouds.ec2.xml.GetConsoleOutputResponseHandler;\nimport org.jclouds.ec2.xml.InstanceInitiatedShutdownBehaviorHandler;\nimport org.jclouds.ec2.xml.InstanceStateChangeHandler;\nimport org.jclouds.ec2.xml.InstanceTypeHandler;\nimport org.jclouds.ec2.xml.RunInstancesResponseHandler;\nimport org.jclouds.ec2.xml.StringValueHandler;\nimport org.jclouds.ec2.xml.UnencodeStringValueHandler;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.location.functions.RegionToEndpointOrProviderIfNull;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.EndpointParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.FormParams;\nimport org.jclouds.rest.annotations.ParamParser;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SinceApiVersion;\nimport org.jclouds.rest.annotations.VirtualHost;\nimport org.jclouds.rest.annotations.XMLResponseParser;\n\nimport com.google.common.collect.Multimap;\n\n/**\n * Provides access to EC2 Instance Services via their REST API.\n * <p/>\n */\n@RequestFilters(FormSigner.class)\n@VirtualHost\npublic interface InstanceApi {\n\n   /**\n    * Returns information about instances that you own.\n    * <p/>\n    * \n    * If you specify one or more instance IDs, Amazon EC2 returns information\n    * for those instances. If you do not specify instance IDs, Amazon EC2\n    * returns information for all relevant instances. If you specify an invalid\n    * instance ID, a fault is returned. If you specify an instance that you do\n    * not own, it will not be included in the returned results.\n    * <p/>\n    * Recently terminated instances might appear in the returned results.This\n    * interval is usually less than one hour.\n    * \n    * @param region\n    *           Instances are tied to Availability Zones. However, the instance\n    *           ID is tied to the Region.\n    * \n    * @see #runInstancesInRegion\n    * @see #terminateInstancesInRegion\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeInstances.html\"\n    *      />\n    */\n   @Named(\"DescribeInstances\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DescribeInstances\")\n   @XMLResponseParser(DescribeInstancesResponseHandler.class)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<? extends Reservation<? extends RunningInstance>> describeInstancesInRegion(\n         @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n         @BinderParam(BindInstanceIdsToIndexedFormParams.class) String... instanceIds);\n\n   /**\n    * Returns information about instances that you own.\n    * <p/>\n    *\n    * If you specify one or filters, Amazon EC2 returns information for instances\n    * matching those filters. If you do not specify any filters, Amazon EC2\n    * returns information for all relevant instances. If you specify an invalid\n    * filter, a fault is returned. Only instances you own will be included in the\n    * results.\n    * <p/>\n    * Recently terminated instances might appear in the returned results. This\n    * interval is usually less than one hour.\n    *\n    * @param region\n    *           Instances are tied to Availability Zones. However, the instance\n    *           ID is tied to the Region.\n    * @param filter\n    *\n    * @see #runInstancesInRegion\n    * @see #terminateInstancesInRegion\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeInstances.html\"\n    *      />\n    */\n   @SinceApiVersion(\"2010-08-31\")\n   @Named(\"DescribeInstances\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DescribeInstances\")\n   @XMLResponseParser(DescribeInstancesResponseHandler.class)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<? extends Reservation<? extends RunningInstance>> describeInstancesInRegionWithFilter(\n           @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n           @BinderParam(BindFiltersToIndexedFormParams.class) Multimap<String, String> filter);\n\n   /**\n    * Launches a specified number of instances of an AMI for which you have\n    * permissions.\n    * <p/>\n    * \n    * If Amazon EC2 cannot launch the minimum number AMIs you request, no\n    * instances will be launched. If there is insufficient capacity to launch\n    * the maximum number of AMIs you request, Amazon EC2 launches the minimum\n    * number specified for each AMI and allocate the remaining available\n    * instances using round robin.\n    * <p/>\n    * <h4>Security Groups</h4>\n    * <b>Note:</b> Every instance is launched in a security group (created using\n    * the CreateSecurityGroup operation.\n    * <h4>Key Pair</h4>\n    * You can provide an optional key pair ID for each image in the launch\n    * request (created using the CreateKeyPair operation). All instances that\n    * are created from images that use this key pair will have access to the\n    * associated public key at boot. You can use this key to provide secure\n    * access to an instance of an image on a per-instance basis. Amazon EC2\n    * public images use this feature to provide secure access without passwords.\n    * <p/>\n    * <b>Note:</b> Launching public images without a key pair ID will leave them\n    * inaccessible.\n    * <p/>\n    * The public key material is made available to the instance at boot time by\n    * placing it in the openssh_id.pub file on a logical device that is exposed\n    * to the instance as /dev/sda2 (the instance store). The format of this file\n    * is suitable for use as an entry within ~/.ssh/authorized_keys (the OpenSSH\n    * format). This can be done at boot (e.g., as part of rc.local) allowing for\n    * secure access without passwords.\n    * <h4>User Data</h4>\n    * Optional user data can be provided in the launch request. All instances\n    * that collectively comprise the launch request have access to this data.\n    * For more information, go the Amazon Elastic Compute Cloud Developer Guide.\n    * <h4>Product Codes</h4>\n    * \n    * <b>Note:</b> If any of the AMIs have a product code attached for which the\n    * user has not subscribed, the RunInstances call will fail.\n    * <h4>Kernel</h4>\n    * \n    * <b>Important:</b> We strongly recommend using the 2.6.18 Xen stock kernel\n    * with High-CPU and High-Memory instances. Although the default Amazon EC2\n    * kernels will work, the new kernels provide greater stability and\n    * performance for these instance types. For more information about kernels,\n    * go the Amazon Elastic Compute Cloud Developer Guide.\n    * \n    * @param region\n    *           Instances are tied to Availability Zones. However, the instance\n    *           ID is tied to the Region.\n    * @param nullableAvailabilityZone\n    *           Specifies the placement constraints (Availability Zones) for\n    *           launching the instances. If null, Amazon will determine the best\n    *           availability zone to place the instance.\n    * @param imageId\n    *           Unique ID of a machine image, returned by a call to\n    * @param minCount\n    *           Minimum number of instances to launch. If the value is more than\n    *           Amazon EC2 can launch, no instances a re launched at all.\n    *           Constraints: Between 1 and the maximum number allowed for your\n    *           account (default: 20).\n    * @param maxCount\n    *           Maximum number of instances to launch. If the value is more than\n    *           Amazon EC2 can launch, the largest possible number above\n    *           minCount will be launched instead. Constraints: Between 1 and\n    *           the maximum number allowed for your account (default: 20).\n    * @see #describeInstancesInRegion\n    * @see #terminateInstancesInRegion\n    * @see #authorizeSecurityGroupIngressInRegion\n    * @see #revokeSecurityGroupIngressInRegion\n    * @see #describeSecurityGroupsInRegion\n    * @see #createSecurityGroupInRegion\n    * @see #createKeyPairInRegion\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-RunInstances.html\"\n    *      />\n    * @see RunInstancesOptions\n    */\n   @Named(\"RunInstances\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"RunInstances\")\n   @XMLResponseParser(RunInstancesResponseHandler.class)\n   Reservation<? extends RunningInstance> runInstancesInRegion(\n         @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n         @Nullable @BinderParam(IfNotNullBindAvailabilityZoneToFormParam.class) String nullableAvailabilityZone,\n         @FormParam(\"ImageId\") String imageId, @FormParam(\"MinCount\") int minCount,\n         @FormParam(\"MaxCount\") int maxCount, RunInstancesOptions... options);\n\n   /**\n    * Requests a reboot of one or more instances. This operation is\n    * asynchronous; it only queues a request to reboot the specified\n    * instance(s). The operation will succeed if the instances are valid and\n    * belong to you. Requests to reboot terminated instances are ignored. <h3>\n    * Note</h3> If a Linux/UNIX instance does not cleanly shut down within four\n    * minutes, Amazon EC2 will perform a hard reboot.\n    * \n    * @param region\n    *           Instances are tied to Availability Zones. However, the instance\n    *           ID is tied to the Region.\n    * \n    * @param instanceIds\n    *           Instance ID to reboot.\n    * \n    * @see #startInstancesInRegion\n    * @see #runInstancesInRegion\n    * @see #describeInstancesInRegion\n    * @see #terminateInstancesInRegion\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-StopInstances.html\"\n    *      />\n    */\n   @Named(\"RebootInstances\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"RebootInstances\")\n   void rebootInstancesInRegion(\n         @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n         @BinderParam(BindInstanceIdsToIndexedFormParams.class) String... instanceIds);\n\n   /**\n    * Shuts down one or more instances. This operation is idempotent; if you\n    * terminate an instance more than once, each call will succeed.\n    * <p/>\n    * Terminated instances will remain visible after termination (approximately\n    * one hour).\n    * \n    * @param region\n    *           Instances are tied to Availability Zones. However, the instance\n    *           ID is tied to the Region.\n    * @param instanceIds\n    *           Instance ID to terminate.\n    * @see #describeInstancesInRegion\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-TerminateInstances.html\"\n    *      />\n    */\n   @Named(\"TerminateInstances\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"TerminateInstances\")\n   @XMLResponseParser(InstanceStateChangeHandler.class)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<? extends InstanceStateChange> terminateInstancesInRegion(\n         @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n         @BinderParam(BindInstanceIdsToIndexedFormParams.class) String... instanceIds);\n\n   /**\n    * Stops an instance that uses an Amazon EBS volume as its root device.\n    * <p/>\n    * Instances that use Amazon EBS volumes as their root devices can be quickly\n    * stopped and started. When an instance is stopped, the compute resources\n    * are released and you are not billed for hourly instance usage. However,\n    * your root partition Amazon EBS volume remains, continues to persist your\n    * data, and you are charged for Amazon EBS volume usage. You can restart\n    * your instance at any time.\n    * <h3>Note</h3>\n    * Before stopping an instance, make sure it is in a state from which it can\n    * be restarted. Stopping an instance does not preserve data stored in RAM.\n    * <p/>\n    * Performing this operation on an instance that uses an instance store as\n    * its root device returns an error.\n    * \n    * @param region\n    *           Instances are tied to Availability Zones. However, the instance\n    *           ID is tied to the Region.\n    * @param force\n    *           Forces the instance to stop. The instance will not have an\n    *           opportunity to flush file system caches nor file system meta\n    *           data. If you use this option, you must perform file system check\n    *           and repair procedures. This option is not recommended for\n    *           Windows instances.\n    * @param instanceIds\n    *           Instance ID to stop.\n    * \n    * @see #startInstancesInRegion\n    * @see #runInstancesInRegion\n    * @see #describeInstancesInRegion\n    * @see #terminateInstancesInRegion\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-StopInstances.html\"\n    *      />\n    */\n   @Named(\"StopInstances\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"StopInstances\")\n   @XMLResponseParser(InstanceStateChangeHandler.class)\n   Set<? extends InstanceStateChange> stopInstancesInRegion(\n         @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n         @FormParam(\"Force\") boolean force,\n         @BinderParam(BindInstanceIdsToIndexedFormParams.class) String... instanceIds);\n\n   /**\n    * Starts an instance that uses an Amazon EBS volume as its root device.\n    * <p/>\n    * Instances that use Amazon EBS volumes as their root devices can be quickly\n    * stopped and started. When an instance is stopped, the compute resources\n    * are released and you are not billed for hourly instance usage. However,\n    * your root partition Amazon EBS volume remains, continues to persist your\n    * data, and you are charged for Amazon EBS volume usage. You can restart\n    * your instance at any time.\n    * <h3>Note</h3>\n    * Before stopping an instance, make sure it is in a state from which it can\n    * be restarted. Stopping an instance does not preserve data stored in RAM.\n    * <p/>\n    * Performing this operation on an instance that uses an instance store as\n    * its root device returns an error.\n    * \n    * @param region\n    *           Instances are tied to Availability Zones. However, the instance\n    *           ID is tied to the Region.\n    * @param instanceIds\n    *           Instance ID to start.\n    * \n    * @see #stopInstancesInRegion\n    * @see #runInstancesInRegion\n    * @see #describeInstancesInRegion\n    * @see #terminateInstancesInRegion\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-StartInstances.html\"\n    *      />\n    */\n   @Named(\"StartInstances\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"StartInstances\")\n   @XMLResponseParser(InstanceStateChangeHandler.class)\n   Set<? extends InstanceStateChange> startInstancesInRegion(\n         @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n         @BinderParam(BindInstanceIdsToIndexedFormParams.class) String... instanceIds);\n\n   /**\n    * \n    * @param region\n    *           Instances are tied to Availability Zones. However, the instance\n    *           ID is tied to the Region.\n    * @param instanceId\n    *           which instance to describe the attribute of\n    * @return unencoded user data\n    */\n   @Named(\"DescribeInstanceAttribute\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = { ACTION, \"Attribute\" }, values = { \"DescribeInstanceAttribute\", \"userData\" })\n   @XMLResponseParser(UnencodeStringValueHandler.class)\n   String getUserDataForInstanceInRegion(\n         @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n         @FormParam(\"InstanceId\") String instanceId);\n\n   /**\n    * \n    * @param region\n    *           Instances are tied to Availability Zones. However, the instance\n    *           ID is tied to the Region.\n    * @param instanceId\n    *           which instance to describe the attribute of\n    * @return The root device name (e.g., /dev/sda1).\n    */\n   @Named(\"DescribeInstanceAttribute\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = { ACTION, \"Attribute\" }, values = { \"DescribeInstanceAttribute\", \"rootDeviceName\" })\n   @XMLResponseParser(StringValueHandler.class)\n   String getRootDeviceNameForInstanceInRegion(\n         @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n         @FormParam(\"InstanceId\") String instanceId);\n\n   /**\n    * \n    * @param region\n    *           Instances are tied to Availability Zones. However, the instance\n    *           ID is tied to the Region.\n    * @param instanceId\n    *           which instance to describe the attribute of\n    * @return the ID of the RAM disk associated with the AMI.\n    */\n   @Named(\"DescribeInstanceAttribute\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = { ACTION, \"Attribute\" }, values = { \"DescribeInstanceAttribute\", \"ramdisk\" })\n   @XMLResponseParser(StringValueHandler.class)\n   String getRamdiskForInstanceInRegion(\n         @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n         @FormParam(\"InstanceId\") String instanceId);\n\n   /**\n    * \n    * @param region\n    *           Instances are tied to Availability Zones. However, the instance\n    *           ID is tied to the Region.\n    * @param instanceId\n    *           which instance to describe the attribute of\n    * @return the ID of the kernel associated with the AMI.\n    */\n   @Named(\"DescribeInstanceAttribute\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = { ACTION, \"Attribute\" }, values = { \"DescribeInstanceAttribute\", \"kernel\" })\n   @XMLResponseParser(StringValueHandler.class)\n   String getKernelForInstanceInRegion(\n         @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n         @FormParam(\"InstanceId\") String instanceId);\n\n   /**\n    * \n    * @param region\n    *           Instances are tied to Availability Zones. However, the instance\n    *           ID is tied to the Region.\n    * @param instanceId\n    *           which instance to describe the attribute of\n    * @return Specifies whether the instance can be terminated using the APIs.\n    *         You must modify this attribute before you can terminate any\n    *         \"locked\" instances from the APIs.\n    */\n   @Named(\"DescribeInstanceAttribute\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = { ACTION, \"Attribute\" }, values = { \"DescribeInstanceAttribute\", \"disableApiTermination\" })\n   @XMLResponseParser(BooleanValueHandler.class)\n   boolean isApiTerminationDisabledForInstanceInRegion(\n         @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n         @FormParam(\"InstanceId\") String instanceId);\n\n   /**\n    * \n    * @param region\n    *           Instances are tied to Availability Zones. However, the instance\n    *           ID is tied to the Region.\n    * @param instanceId\n    *           which instance to describe the attribute of\n    * @return The instance type of the instance.\n    */\n   @Named(\"DescribeInstanceAttribute\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = { ACTION, \"Attribute\" }, values = { \"DescribeInstanceAttribute\", \"instanceType\" })\n   @XMLResponseParser(InstanceTypeHandler.class)\n   String getInstanceTypeForInstanceInRegion(\n         @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n         @FormParam(\"InstanceId\") String instanceId);\n\n   /**\n    * \n    * @param region\n    *           Instances are tied to Availability Zones. However, the instance\n    *           ID is tied to the Region.\n    * @param instanceId\n    *           which instance to describe the attribute of\n    * @return whether the instance's Amazon EBS volumes are stopped or\n    *         terminated when the instance is shut down.\n    */\n   @Named(\"DescribeInstanceAttribute\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = { ACTION, \"Attribute\" }, values = { \"DescribeInstanceAttribute\",\n         \"instanceInitiatedShutdownBehavior\" })\n   @XMLResponseParser(InstanceInitiatedShutdownBehaviorHandler.class)\n   InstanceInitiatedShutdownBehavior getInstanceInitiatedShutdownBehaviorForInstanceInRegion(\n         @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n         @FormParam(\"InstanceId\") String instanceId);\n\n   /**\n    * \n    * @param region\n    *           Instances are tied to Availability Zones. However, the instance\n    *           ID is tied to the Region.\n    * @param instanceId\n    *           which instance to describe the attribute of\n    * @return Describes the mapping that defines native device names to use when\n    *         exposing virtual devices.\n    */\n   @Named(\"DescribeInstanceAttribute\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = { ACTION, \"Attribute\" }, values = { \"DescribeInstanceAttribute\", \"blockDeviceMapping\" })\n   @XMLResponseParser(BlockDeviceMappingHandler.class)\n   Map<String, BlockDevice> getBlockDeviceMappingForInstanceInRegion(\n         @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n         @FormParam(\"InstanceId\") String instanceId);\n\n   /**\n    * Resets an attribute of an instance to its default value.\n    * \n    * @param region\n    *           Instances are tied to Availability Zones. However, the instance\n    *           ID is tied to the Region.\n    * @param instanceId\n    *           which instance to reset the attribute of\n    * @return the ID of the RAM disk associated with the AMI.\n    */\n   @Named(\"ResetInstanceAttribute\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = { ACTION, \"Attribute\" }, values = { \"ResetInstanceAttribute\", \"ramdisk\" })\n   void resetRamdiskForInstanceInRegion(\n         @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n         @FormParam(\"InstanceId\") String instanceId);\n\n   /**\n    * Resets an attribute of an instance to its default value.\n    * \n    * @param region\n    *           Instances are tied to Availability Zones. However, the instance\n    *           ID is tied to the Region.\n    * @param instanceId\n    *           which instance to reset the attribute of\n    * @return the ID of the kernel associated with the AMI.\n    */\n   @Named(\"ResetInstanceAttribute\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = { ACTION, \"Attribute\" }, values = { \"ResetInstanceAttribute\", \"kernel\" })\n   void resetKernelForInstanceInRegion(\n         @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n         @FormParam(\"InstanceId\") String instanceId);\n\n   /**\n    * Sets the userData used for starting the instance.\n    * <p/>\n    * The instance needs to be in a {@link InstanceState#STOPPED} state, which\n    * implies two things:\n    * <ol>\n    * <li>The instance was launched from an EBS-backed AMI so that it can stop</li>\n    * <li>You have stopped and waited for the instance to transition from\n    * {@link InstanceState#STOPPING} to {@link InstanceState#STOPPED}</li>\n    * </ol>\n    * \n    * @param region\n    *           Instances are tied to Availability Zones. However, the instance\n    *           ID is tied to the Region.\n    * @param instanceId\n    *           which instance to change the attribute of\n    * @param unencodedData\n    *           unencoded data to set as userData\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-ModifyInstanceAttribute.html\"\n    *      />\n    */\n   @Named(\"ModifyInstanceAttribute\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = { ACTION, \"Attribute\" }, values = { \"ModifyInstanceAttribute\", \"userData\" })\n   void setUserDataForInstanceInRegion(\n         @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n         @FormParam(\"InstanceId\") String instanceId,\n         @FormParam(\"Value\") @ParamParser(ConvertUnencodedBytesToBase64EncodedString.class) byte[] unencodedData);\n\n   /**\n    * Sets the ramdisk used for starting the instance.\n    * <p/>\n    * The instance needs to be in a {@link InstanceState#STOPPED} state, which\n    * implies two things:\n    * <ol>\n    * <li>The instance was launched from an EBS-backed AMI so that it can stop</li>\n    * <li>You have stopped and waited for the instance to transition from\n    * {@link InstanceState#STOPPING} to {@link InstanceState#STOPPED}</li>\n    * </ol>\n    * \n    * @param region\n    *           Instances are tied to Availability Zones. However, the instance\n    *           ID is tied to the Region.\n    * @param instanceId\n    *           which instance to change the attribute of\n    * @param ramdisk\n    *           ramdisk used to start the instance\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-ModifyInstanceAttribute.html\"\n    *      />\n    */\n   @Named(\"ModifyInstanceAttribute\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = { ACTION, \"Attribute\" }, values = { \"ModifyInstanceAttribute\", \"ramdisk\" })\n   void setRamdiskForInstanceInRegion(\n         @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n         @FormParam(\"InstanceId\") String instanceId, @FormParam(\"Value\") String ramdisk);\n\n   /**\n    * Sets the kernelId used for starting the instance.\n    * <p/>\n    * The instance needs to be in a {@link InstanceState#STOPPED} state, which\n    * implies two things:\n    * <ol>\n    * <li>The instance was launched from an EBS-backed AMI so that it can stop</li>\n    * <li>You have stopped and waited for the instance to transition from\n    * {@link InstanceState#STOPPING} to {@link InstanceState#STOPPED}</li>\n    * </ol>\n    * \n    * @param region\n    *           Instances are tied to Availability Zones. However, the instance\n    *           ID is tied to the Region.\n    * @param instanceId\n    *           which instance to change the attribute of\n    * @param kernel\n    *           kernelId used to start the instance\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-ModifyInstanceAttribute.html\"\n    *      />\n    */\n   @Named(\"ModifyInstanceAttribute\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = { ACTION, \"Attribute\" }, values = { \"ModifyInstanceAttribute\", \"kernel\" })\n   void setKernelForInstanceInRegion(\n         @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n         @FormParam(\"InstanceId\") String instanceId, @FormParam(\"Value\") String kernel);\n\n   /**\n    * This command works while the instance is running and controls whether or\n    * not the api can be used to terminate the instance.\n    * \n    * @param region\n    *           Instances are tied to Availability Zones. However, the instance\n    *           ID is tied to the Region.\n    * @param instanceId\n    *           which instance to reset the attribute of\n    * @param apiTerminationDisabled\n    *           true to disable api termination\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-ModifyInstanceAttribute.html\"\n    *      />\n    */\n   @Named(\"ModifyInstanceAttribute\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = { ACTION, \"Attribute\" }, values = { \"ModifyInstanceAttribute\", \"disableApiTermination\" })\n   void setApiTerminationDisabledForInstanceInRegion(\n         @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n         @FormParam(\"InstanceId\") String instanceId, @FormParam(\"Value\") boolean apiTerminationDisabled);\n\n   /**\n    * Sets the instanceType used for starting the instance.\n    * <p/>\n    * The instance needs to be in a {@link InstanceState#STOPPED} state, which\n    * implies two things:\n    * <ol>\n    * <li>The instance was launched from an EBS-backed AMI so that it can stop</li>\n    * <li>You have stopped and waited for the instance to transition from\n    * {@link InstanceState#STOPPING} to {@link InstanceState#STOPPED}</li>\n    * </ol>\n    * \n    * @param region\n    *           Instances are tied to Availability Zones. However, the instance\n    *           ID is tied to the Region.\n    * @param instanceId\n    *           which instance to change the attribute of\n    * @param instanceType\n    *           instanceType used to start the instance\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-ModifyInstanceAttribute.html\"\n    *      />\n    */\n   @Named(\"ModifyInstanceAttribute\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = { ACTION, \"Attribute\" }, values = { \"ModifyInstanceAttribute\", \"instanceType\" })\n   void setInstanceTypeForInstanceInRegion(\n         @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n         @FormParam(\"InstanceId\") String instanceId, @FormParam(\"Value\") String instanceType);\n\n   /**\n    * Specifies whether the instance's Amazon EBS volumes are stopped or\n    * terminated when the instance is shut down.\n    * <p/>\n    * The instance needs to be in a {@link InstanceState#STOPPED} state, which\n    * implies two things:\n    * <ol>\n    * <li>The instance was launched from an EBS-backed AMI so that it can stop</li>\n    * <li>You have stopped and waited for the instance to transition from\n    * {@link InstanceState#STOPPING} to {@link InstanceState#STOPPED}</li>\n    * </ol>\n    * \n    * @param region\n    *           Instances are tied to Availability Zones. However, the instance\n    *           ID is tied to the Region.\n    * @param instanceId\n    *           which instance to change the attribute of\n    * @param instanceInitiatedShutdownBehavior\n    *           whether the instance's Amazon EBS volumes are stopped or\n    *           terminated when the instance is shut down.\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-ModifyInstanceAttribute.html\"\n    *      />\n    */\n   @Named(\"ModifyInstanceAttribute\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = { ACTION, \"Attribute\" }, values = { \"ModifyInstanceAttribute\",\n         \"instanceInitiatedShutdownBehavior\" })\n   void setInstanceInitiatedShutdownBehaviorForInstanceInRegion(\n         @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n         @FormParam(\"InstanceId\") String instanceId,\n         @FormParam(\"Value\") InstanceInitiatedShutdownBehavior instanceInitiatedShutdownBehavior);\n\n   /**\n    * Sets the blockDeviceMapping used for an instance.\n    * <p/>\n    * The instance needs to be in a {@link InstanceState#STOPPED} state, which\n    * implies two things:\n    * <ol>\n    * <li>The instance was launched from an EBS-backed AMI so that it can stop</li>\n    * <li>You have stopped and waited for the instance to transition from\n    * {@link InstanceState#STOPPING} to {@link InstanceState#STOPPED}</li>\n    * </ol>\n    * \n    * To create the instances of {@link BlockDevice}, the\n    * constructor can be used with the following parameters:\n    * {@link BlockDevice#EbsBlockDevice(String, String, boolean)}\n    * , that are:\n    * <ol>\n    * <li>Volume id (required), for instance, \"vol-blah\"</li>\n    * <li>Device name (optional), for instance, \"/dev/sda1\". To find out more\n    * about device names, read the next paragraph.</li>\n    * <li>Delete on termination flag (optional), which defines whether the\n    * volume will be deleted upon instance's termination.</li>\n    * </ol>\n    * <p/>\n    * Note that the device names between Linux and Windows differ. For Linux,\n    * ensure that your device name is in the form /dev/sd[a-z] . For example,\n    * /dev/sda , /dev/sdb and /dev/sdh are all valid device names.\n    * <p/>\n    * For Windows, the root device is still referred to as /dev/sda1 . For other\n    * devices, ensure that they are in the form /xvd[c-p] . For example, /xvde ,\n    * /xvdf and /xvdp are all valid Windows device names.\n    * <p/>\n    * <b>NOTE</b>: As of now 02/20/2010, this command only works to change the\n    * DeleteOnTermination property of the device. The volume must be\n    * <i>attached</i> to a stopped instance.\n    * \n    * @param region\n    *           Instances are tied to Availability Zones. However, the instance\n    *           ID is tied to the Region.\n    * @param instanceId\n    *           which instance to change the attribute of\n    * @param blockDeviceMapping\n    *           blockDeviceMapping used to start the instance\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-ModifyInstanceAttribute.html\"\n    *      />\n    */\n   @Named(\"ModifyInstanceAttribute\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = { ACTION }, values = { \"ModifyInstanceAttribute\" })\n   void setBlockDeviceMappingForInstanceInRegion(\n         @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n         @FormParam(\"InstanceId\") String instanceId,\n         @BinderParam(BindBlockDeviceMappingToIndexedFormParams.class) Map<String, BlockDevice> blockDeviceMapping);\n\n   /**\n    * Retrieves console output for the specified instance.\n    *\n    * Instance console output is buffered and posted shortly after instance boot, reboot, and termination. Amazon EC2 preserves\n    * the most recent 64 KB output which will be available for at least one hour after the most recent post.\n    *\n    * @param region\n    *           Instances are tied to Availability Zones. However, the instance\n    *           ID is tied to the Region.\n    * @param instanceId\n    *           which instance to retrieve console output for\n    * @return The console output\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-GetConsoleOutput.html\">\n    *       ApiReference query GetConsoleOutput</a>\n    */\n   @Named(\"GetConsoleOutput\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = { ACTION }, values = { \"GetConsoleOutput\" })\n   @XMLResponseParser(GetConsoleOutputResponseHandler.class)\n   String getConsoleOutputForInstanceInRegion(\n         @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n         @FormParam(\"InstanceId\") String instanceId);\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/features/KeyPairApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.features;\n\nimport static org.jclouds.aws.reference.FormParameters.ACTION;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.FormParam;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.aws.filters.FormSigner;\nimport org.jclouds.ec2.binders.BindFiltersToIndexedFormParams;\nimport org.jclouds.ec2.binders.BindKeyNamesToIndexedFormParams;\nimport org.jclouds.ec2.domain.KeyPair;\nimport org.jclouds.ec2.xml.DescribeKeyPairsResponseHandler;\nimport org.jclouds.ec2.xml.KeyPairResponseHandler;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.location.functions.RegionToEndpointOrProviderIfNull;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.EndpointParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.FormParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.VirtualHost;\nimport org.jclouds.rest.annotations.XMLResponseParser;\n\nimport com.google.common.collect.Multimap;\n\n/**\n * Provides access to EC2 via their REST API.\n * <p/>\n */\n@RequestFilters(FormSigner.class)\n@VirtualHost\npublic interface KeyPairApi {\n\n   /**\n    * Creates a new 2048-bit RSA key pair with the specified name. The public key is stored by\n    * Amazon EC2 and the private key is displayed on the console. The private key is returned as an\n    * unencrypted PEM encoded PKCS#8 private key. If a key with the specified name already exists,\n    * Amazon EC2 returns an error.\n    * \n    * @param region\n    *           Key pairs (to connect to instances) are Region-specific.\n    * @param keyName\n    *           A unique name for the key pair.\n    * \n    * @see #runInstances\n    * @see #describeKeyPairs\n    * @see #deleteKeyPair\n    * \n    * @see <a href=\n    *      \"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateKeyPair.html\"\n    *      />\n    */\n   @Named(\"CreateKeyPair\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"CreateKeyPair\")\n   @XMLResponseParser(KeyPairResponseHandler.class)\n   KeyPair createKeyPairInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n            @FormParam(\"KeyName\") String keyName);\n\n   /**\n    * Returns information about key pairs available to you. If you specify key pairs, information\n    * about those key pairs is returned. Otherwise, information for all registered key pairs is\n    * returned.\n    * \n    * @param region\n    *           Key pairs (to connect to instances) are Region-specific.\n    * @param keyPairNames\n    *           Key pairs to describe.\n    * \n    * @see #runInstances\n    * @see #describeAvailabilityZones\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeKeyPairs.html\"\n    *      />\n    */\n   @Named(\"DescribeKeyPairs\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DescribeKeyPairs\")\n   @XMLResponseParser(DescribeKeyPairsResponseHandler.class)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<KeyPair> describeKeyPairsInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n            @BinderParam(BindKeyNamesToIndexedFormParams.class) String... keyPairNames);\n\n   /**\n    * Returns information about key pairs available to you. If you specify filters,\n    * information about keypairs matching those filters is returned. Otherwise, all\n    * keypairs you have access to are returned.\n    *\n    * @param region\n    *           Key pairs (to connect to instances) are Region-specific.\n    * @param filter\n    *           Multimap of filter key/values.\n    *\n    * @see #runInstances\n    * @see #describeAvailabilityZones\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeKeyPairs.html\"\n    *      />\n    */\n   @Named(\"DescribeKeyPairs\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DescribeKeyPairs\")\n   @XMLResponseParser(DescribeKeyPairsResponseHandler.class)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<KeyPair> describeKeyPairsInRegionWithFilter(\n           @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n           @BinderParam(BindFiltersToIndexedFormParams.class) Multimap<String, String> filter);\n\n   /**\n    * Deletes the specified key pair, by removing the public key from Amazon EC2. You must own the\n    * key pair\n    * \n    * @param region\n    *           Key pairs (to connect to instances) are Region-specific.\n    * @param keyName\n    *           Name of the key pair to delete\n    * \n    * @see #describeKeyPairs\n    * @see #createKeyPair\n    * \n    * @see <a href=\n    *      \"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteKeyPair.html\"\n    *      />\n    */\n   @Named(\"DeleteKeyPair\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DeleteKeyPair\")\n   void deleteKeyPairInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n            @FormParam(\"KeyName\") String keyName);\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/features/SecurityGroupApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.features;\n\nimport static org.jclouds.aws.reference.FormParameters.ACTION;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.FormParam;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.aws.filters.FormSigner;\nimport org.jclouds.ec2.binders.BindFiltersToIndexedFormParams;\nimport org.jclouds.ec2.binders.BindGroupNamesToIndexedFormParams;\nimport org.jclouds.ec2.binders.BindUserIdGroupPairToSourceSecurityGroupFormParams;\nimport org.jclouds.ec2.domain.SecurityGroup;\nimport org.jclouds.ec2.domain.UserIdGroupPair;\nimport org.jclouds.ec2.xml.DescribeSecurityGroupsResponseHandler;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.location.functions.RegionToEndpointOrProviderIfNull;\nimport org.jclouds.net.domain.IpProtocol;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.EndpointParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.FormParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.VirtualHost;\nimport org.jclouds.rest.annotations.XMLResponseParser;\n\nimport com.google.common.collect.Multimap;\n\n/**\n * Provides access to EC2 via their REST API.\n * <p/>\n */\n@RequestFilters(FormSigner.class)\n@VirtualHost\npublic interface SecurityGroupApi {\n\n   /**\n    * Creates a new security group. Group names must be unique per identity.\n    * \n    * @param region\n    *           Security groups are not copied across Regions. Instances within the Region cannot\n    *           communicate with instances outside the Region using group-based firewall rules.\n    *           Traffic from instances in another Region is seen as WAN bandwidth.\n    * @param name\n    *           Name of the security group. Accepts alphanumeric characters, spaces, dashes, and\n    *           underscores.\n    * @param description\n    *           Description of the group. This is informational only. If the description contains\n    *           spaces, you must enc lose it in single quotes (') or URL-encode it. Accepts\n    *           alphanumeric characters, spaces, dashes, and underscores.\n    * @see #runInstances\n    * @see #describeSecurityGroups\n    * @see #authorizeSecurityGroupIngress\n    * @see #revokeSecurityGroupIngress\n    * @see #deleteSecurityGroup\n    * \n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateSecurityGroup.html\"\n    *      />\n    */\n   @Named(\"CreateSecurityGroup\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"CreateSecurityGroup\")\n   void createSecurityGroupInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n            @FormParam(\"GroupName\") String name, @FormParam(\"GroupDescription\") String description);\n\n\n   // Supported by\n   //  * AWS\n   //  * Openstack - https://github.com/openstack/ec2-api/blob/61daf6a80fd6cc9ab800e6b6a2cd3d1d827e2527/ec2api/api/security_group.py#L130\n   //  * Eucalyptus - https://docs.eucalyptus.com/eucalyptus/4.4.0/#euca2ools-guide/euca-delete-group.html\n   //                 https://github.com/eucalyptus/euca2ools/blob/096d97ef2729da976759657d6d6f645a6e959e05/euca2ools/commands/ec2/deletesecuritygroup.py#L37\n   /**\n    * Deletes a security group by ID.\n    *\n    * @param region\n    *           Security groups are not copied across Regions. Instances within the Region cannot\n    *           communicate with instances outside the Region using group-based firewall rules.\n    *           Traffic from instances in another Region is seen as WAN bandwidth.\n    * @param id\n    *           ID of the security group to delete.\n    *\n    * @see #describeSecurityGroups\n    * @see #authorizeSecurityGroupIngress\n    * @see #revokeSecurityGroupIngress\n    * @see #createSecurityGroup\n    *\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteSecurityGroup.html\"\n    *      />\n    */\n   @Named(\"DeleteSecurityGroup\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DeleteSecurityGroup\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void deleteSecurityGroupInRegionById(\n           @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n           @FormParam(\"GroupId\") String id);\n   \n   /**\n    * Deletes a security group that you own.\n    * \n    * @param region\n    *           Security groups are not copied across Regions. Instances within the Region cannot\n    *           communicate with instances outside the Region using group-based firewall rules.\n    *           Traffic from instances in another Region is seen as WAN bandwidth.\n    * @param name\n    *           Name of the security group to delete.\n    * \n    * @see #describeSecurityGroups\n    * @see #authorizeSecurityGroupIngress\n    * @see #revokeSecurityGroupIngress\n    * @see #createSecurityGroup\n    * \n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteSecurityGroup.html\"\n    *      />\n    */\n   @Named(\"DeleteSecurityGroup\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DeleteSecurityGroup\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void deleteSecurityGroupInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region, @FormParam(\"GroupName\") String name);\n\n   /**\n    * Returns information about security groups that you own.\n    * <p><em>NOTE</em> Works with groups in default VPC only</p>\n    *\n    * @param region\n    *           Security groups are not copied across Regions. Instances within the Region cannot\n    *           communicate with instances outside the Region using group-based firewall rules.\n    *           Traffic from instances in another Region is seen as WAN bandwidth.\n    * @param securityGroupNames\n    *           Name of the security groups\n    *\n    * @see #createSecurityGroup\n    * @see #authorizeSecurityGroupIngress\n    * @see #revokeSecurityGroupIngress\n    * @see #deleteSecurityGroup\n    *\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeSecurityGroups.html\"\n    *      />\n    */\n   @Named(\"DescribeSecurityGroups\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DescribeSecurityGroups\")\n   @XMLResponseParser(DescribeSecurityGroupsResponseHandler.class)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<SecurityGroup> describeSecurityGroupsInRegion(\n           @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n           @BinderParam(BindGroupNamesToIndexedFormParams.class) String... securityGroupNames);\n\n   /**\n    * Returns information about security groups that you own.\n    *\n    * @param region\n    *           Security groups are not copied across Regions. Instances within the Region cannot\n    *           communicate with instances outside the Region using group-based firewall rules.\n    *           Traffic from instances in another Region is seen as WAN bandwidth.\n    * @param filter\n    *           Multimap of filter key/values.\n    *\n    * @see #createSecurityGroup\n    * @see #authorizeSecurityGroupIngress\n    * @see #revokeSecurityGroupIngress\n    * @see #deleteSecurityGroup\n    *\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeSecurityGroups.html\"\n    *      />\n    */\n   @Named(\"DescribeSecurityGroups\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DescribeSecurityGroups\")\n   @XMLResponseParser(DescribeSecurityGroupsResponseHandler.class)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<SecurityGroup> describeSecurityGroupsInRegionWithFilter(\n           @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n           @BinderParam(BindFiltersToIndexedFormParams.class) Multimap<String, String> filter);\n\n   /**\n    * \n    * Adds permissions to a security group based on another group.\n    * \n    * @param region\n    *           Security groups are not copied across Regions. Instances within the Region cannot\n    *           communicate with instances outside the Region using group-based firewall rules.\n    *           Traffic from instances in another Region is seen as WAN bandwidth.\n    * @param groupName\n    *           Name of the group to modify. The name must be valid and belong to the identity\n    * @param sourceSecurityGroup\n    *           group to associate with this group.\n    * \n    * @see #createSecurityGroup\n    * @see #describeSecurityGroups\n    * @see #revokeSecurityGroupIngress\n    * @see #deleteSecurityGroup\n    * \n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-AuthorizeSecurityGroupIngress.html\"\n    * \n    */\n   @Named(\"AuthorizeSecurityGroupIngress\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"AuthorizeSecurityGroupIngress\")\n   void authorizeSecurityGroupIngressInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n            @FormParam(\"GroupName\") String groupName,\n            @BinderParam(BindUserIdGroupPairToSourceSecurityGroupFormParams.class) UserIdGroupPair sourceSecurityGroup);\n\n   /**\n    * \n    * Adds permissions to a security group.\n    * <p/>\n    * Permissions are specified by the IP protocol (TCP, UDP or ICMP), the source of the request (by\n    * IP range or an Amazon EC2 user-group pair), the source and destination port ranges (for TCP\n    * and UDP), and the ICMP codes and types (for ICMP). When authorizing ICMP, -1 can be used as a\n    * wildcard in the type and code fields. Permission changes are propagated to instances within\n    * the security group as quickly as possible. However, depending on the number of instances, a\n    * small delay might occur.\n    * \n    * @param region\n    *           Security groups are not copied across Regions. Instances within the Region cannot\n    *           communicate with instances outside the Region using group-based firewall rules.\n    *           Traffic from instances in another Region is seen as WAN bandwidth.\n    * @param groupName\n    *           Name of the group to modify. The name must be valid and belong to the identity\n    * @param ipProtocol\n    *           IP protocol.\n    * @param fromPort\n    *           Start of port range for the TCP and UDP protocols, or an ICMP type number. An ICMP\n    *           type number of -1 indicates a wildcard (i.e., any ICMP type number).\n    * @param toPort\n    *           End of port range for the TCP and UDP protocols, or an ICMP code. An ICMP code of -1\n    *           indicates a wildcard (i.e., any ICMP code).\n    * @param cidrIp\n    *           CIDR range.\n    * \n    * @see #createSecurityGroup\n    * @see #describeSecurityGroups\n    * @see #revokeSecurityGroupIngress\n    * @see #deleteSecurityGroup\n    * \n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-AuthorizeSecurityGroupIngress.html\"\n    * \n    */\n   @Named(\"AuthorizeSecurityGroupIngress\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"AuthorizeSecurityGroupIngress\")\n   void authorizeSecurityGroupIngressInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n            @FormParam(\"GroupName\") String groupName, @FormParam(\"IpProtocol\") IpProtocol ipProtocol,\n            @FormParam(\"FromPort\") int fromPort, @FormParam(\"ToPort\") int toPort, @FormParam(\"CidrIp\") String cidrIp);\n\n   /**\n    * \n    * Revokes permissions from a security group. The permissions used to revoke must be specified\n    * using the same values used to grant the permissions.\n    * \n    * @param region\n    *           Security groups are not copied across Regions. Instances within the Region cannot\n    *           communicate with instances outside the Region using group-based firewall rules.\n    *           Traffic from instances in another Region is seen as WAN bandwidth.\n    * @param groupName\n    *           Name of the group to modify. The name must be valid and belong to the identity\n    * @param sourceSecurityGroup\n    *           group to associate with this group.\n    * \n    * @see #createSecurityGroup\n    * @see #describeSecurityGroups\n    * @see #authorizeSecurityGroupIngress\n    * @see #deleteSecurityGroup\n    * \n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-RevokeSecurityGroupIngress.html\"\n    * \n    */\n   @Named(\"RevokeSecurityGroupIngress\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"RevokeSecurityGroupIngress\")\n   void revokeSecurityGroupIngressInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n            @FormParam(\"GroupName\") String groupName,\n            @BinderParam(BindUserIdGroupPairToSourceSecurityGroupFormParams.class) UserIdGroupPair sourceSecurityGroup);\n\n   /**\n    * \n    * Revokes permissions from a security group. The permissions used to revoke must be specified\n    * using the same values used to grant the permissions.\n    * <p/>\n    * Permissions are specified by IP protocol (TCP, UDP, or ICMP), the source of the request (by IP\n    * range or an Amazon EC2 user-group pair), the source and destination port ranges (for TCP and\n    * UDP), and the ICMP codes and types (for ICMP).\n    * \n    * Permission changes are quickly propagated to instances within the security group. However,\n    * depending on the number of instances in the group, a small delay is might occur.\n    * \n    * @param region\n    *           Security groups are not copied across Regions. Instances within the Region cannot\n    *           communicate with instances outside the Region using group-based firewall rules.\n    *           Traffic from instances in another Region is seen as WAN bandwidth.\n    * @param groupName\n    *           Name of the group to modify. The name must be valid and belong to the identity\n    * @param ipProtocol\n    *           IP protocol.\n    * @param fromPort\n    *           Start of port range for the TCP and UDP protocols, or an ICMP type number. An ICMP\n    *           type number of -1 indicates a wildcard (i.e., any ICMP type number).\n    * @param toPort\n    *           End of port range for the TCP and UDP protocols, or an ICMP code. An ICMP code of -1\n    *           indicates a wildcard (i.e., any ICMP code).\n    * @param cidrIp\n    *           CIDR range.\n    * \n    * @see #createSecurityGroup\n    * @see #describeSecurityGroups\n    * @see #authorizeSecurityGroupIngress\n    * @see #deleteSecurityGroup\n    * \n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-RevokeSecurityGroupIngress.html\"\n    * \n    */\n   @Named(\"RevokeSecurityGroupIngress\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"RevokeSecurityGroupIngress\")\n   void revokeSecurityGroupIngressInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n            @FormParam(\"GroupName\") String groupName, @FormParam(\"IpProtocol\") IpProtocol ipProtocol,\n            @FormParam(\"FromPort\") int fromPort, @FormParam(\"ToPort\") int toPort, @FormParam(\"CidrIp\") String cidrIp);\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/features/SubnetApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.features;\n\nimport static org.jclouds.aws.reference.FormParameters.ACTION;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\n\nimport org.jclouds.Fallbacks.EmptyFluentIterableOnNotFoundOr404;\nimport org.jclouds.aws.filters.FormSigner;\nimport org.jclouds.ec2.binders.BindFiltersToIndexedFormParams;\nimport org.jclouds.ec2.domain.Subnet;\nimport org.jclouds.ec2.xml.DescribeSubnetsResponseHandler;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.FormParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SinceApiVersion;\nimport org.jclouds.rest.annotations.VirtualHost;\nimport org.jclouds.rest.annotations.XMLResponseParser;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.Multimap;\n/**\n * Provides access to Amazon EC2 via the Query API\n * <p/>\n * \n * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeSubnets.html\"\n *      >doc</a>\n */\n@SinceApiVersion(\"2011-01-01\")\n@RequestFilters(FormSigner.class)\n@VirtualHost\npublic interface SubnetApi {\n   /**\n    * Describes all of your subnets for your EC2 resources.\n    * \n    * @return subnets or empty if there are none\n    * @see <a href=\n    *      \"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeSubnets.html\"\n    *      >docs</href>\n    */\n   @Named(\"DescribeSubnets\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DescribeSubnets\")\n   @XMLResponseParser(DescribeSubnetsResponseHandler.class)\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<Subnet> list();\n\n   /**\n    * Describes subnets for your EC2 resources qualified by a filter\n    * \n    * <h4>example</h4>\n    * \n    * <pre>\n    * subnets = subnetApi.filter(new SubnetFilterBuilder().vpcId(&quot;vpc-1a2b3c4d&quot;).build());\n    * </pre>\n    * \n    * @param filter\n    *           which is typically built by {@link SubnetFilterBuilder}\n    * @return tags or empty if there are none that match the filter\n    * @see <a href=\n    *      \"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeSubnets.html\"\n    *      >docs</href>\n    */\n   @Named(\"DescribeSubnets\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DescribeSubnets\")\n   @XMLResponseParser(DescribeSubnetsResponseHandler.class)\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<Subnet> filter(\n         @BinderParam(BindFiltersToIndexedFormParams.class) Multimap<String, String> filter);\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/features/TagApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.features;\n\nimport static org.jclouds.aws.reference.FormParameters.ACTION;\n\nimport java.util.Map;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\n\nimport org.jclouds.Fallbacks.EmptyFluentIterableOnNotFoundOr404;\nimport org.jclouds.aws.filters.FormSigner;\nimport org.jclouds.ec2.binders.BindFiltersToIndexedFormParams;\nimport org.jclouds.ec2.binders.BindResourceIdsToIndexedFormParams;\nimport org.jclouds.ec2.binders.BindTagKeysToIndexedFormParams;\nimport org.jclouds.ec2.binders.BindTagsToIndexedFormParams;\nimport org.jclouds.ec2.domain.Tag;\nimport org.jclouds.ec2.xml.DescribeTagsResponseHandler;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.FormParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SinceApiVersion;\nimport org.jclouds.rest.annotations.VirtualHost;\nimport org.jclouds.rest.annotations.XMLResponseParser;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.Multimap;\n/**\n * Provides access to Amazon EC2 via the Query API\n * <p/>\n * \n * @see <a\n *      href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeTags.html\"\n *      >doc</a>\n */\n@SinceApiVersion(\"2010-08-31\")\n@RequestFilters(FormSigner.class)\n@VirtualHost\npublic interface TagApi {\n   /**\n    * Adds or overwrites one or more tags for the specified resource or\n    * resources. Each resource can have a maximum of 10 tags. Each tag consists\n    * of a key and optional value. Tag keys must be unique per resource.\n    * \n    * <h4>example</h4>\n    * \n    * <pre>\n    * tagApi.applyToResources(ImmutableMap.of(&quot;group&quot;, &quot;backend&quot;), ImmutableSet.of(&quot;i-1a2b3c4d&quot;));\n    * </pre>\n    * \n    * @param tags\n    *           key to an optional value.\n    * @param resourceIds\n    *           The ID of a resource to tag. For example, {@code ami-1a2b3c4d}\n    * \n    * @see <a href=\n    *      \"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateTags.html\"\n    *      >docs</href>\n    */\n   @Named(\"CreateTags\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"CreateTags\")\n   void applyToResources(@BinderParam(BindTagsToIndexedFormParams.class) Iterable<String> tags,\n         @BinderParam(BindResourceIdsToIndexedFormParams.class) Iterable<String> resourceIds);\n\n   /**\n    * like {@link #applyToResources(Map, Iterable)} except that the tags have no\n    * values.\n    * \n    * <h4>example</h4>\n    * \n    * <pre>\n    * tagApi.applyToResources(ImmutableSet.of(&quot;production&quot;, &quot;pci-compliant&quot;), ImmutableSet.of(&quot;i-1a2b3c4d&quot;));\n    * </pre>\n    * \n    * @see #applyToResources(Map, Iterable)\n    */\n   @Named(\"CreateTags\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"CreateTags\")\n   void applyToResources(@BinderParam(BindTagsToIndexedFormParams.class) Map<String, String> tags,\n         @BinderParam(BindResourceIdsToIndexedFormParams.class) Iterable<String> resourceIds);\n\n   /**\n    * Describes all of your tags for your EC2 resources.\n    * \n    * @return tags or empty if there are none\n    * @see <a href=\n    *      \"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeTags.html\"\n    *      >docs</href>\n    */\n   @Named(\"DescribeTags\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DescribeTags\")\n   @XMLResponseParser(DescribeTagsResponseHandler.class)\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<Tag> list();\n\n   /**\n    * Describes tags for your EC2 resources qualified by a filter\n    * \n    * <h4>example</h4>\n    * \n    * <pre>\n    * tags = tagApi.filter(new TagFilterBuilder().image().put(&quot;version&quot;, &quot;1.0&quot;).build());\n    * </pre>\n    * \n    * @param filter\n    *           which is typically built by {@link TagFilterBuilder}\n    * @return tags or empty if there are none that match the filter\n    * @see <a href=\n    *      \"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeTags.html\"\n    *      >docs</href>\n    */\n   @Named(\"DescribeTags\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DescribeTags\")\n   @XMLResponseParser(DescribeTagsResponseHandler.class)\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<Tag> filter(\n         @BinderParam(BindFiltersToIndexedFormParams.class) Multimap<String, String> filter);\n\n   /**\n    * Deletes a specific set of tags from a specific set of resources. This call\n    * is designed to follow a {@link #list() list} or {@link #filter(Multimap)\n    * filter} call. You first determine what tags a resource has, and then you\n    * call {@link TagApi#deleteFromResources(Iterable, Iterable) delete} with\n    * the resource ID and the specific tags you want to delete.\n    * \n    * <h4>example</h4>\n    * \n    * <pre>\n    * tagApi.deleteFromResources(ImmutableSet.of(&quot;Purpose&quot;), ImmutableSet.of(&quot;ami-1a2b3c4d&quot;));\n    * </pre>\n    * \n    * @param tags\n    *           the tag keys\n    * @param resourceIds\n    *           The ID of a resource with the tag. For example,\n    *           {@code ami-1a2b3c4d}\n    * @see <a href=\n    *      \"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteTags.html\"\n    *      >docs</href>\n    */\n   @Named(\"DeleteTags\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DeleteTags\")\n   void deleteFromResources(\n         @BinderParam(BindTagKeysToIndexedFormParams.class) Iterable<String> tags,\n         @BinderParam(BindResourceIdsToIndexedFormParams.class) Iterable<String> resourceIds);\n\n   /**\n    * like {@link #deleteFromResources(Iterable, Iterable)}, except that the\n    * tags are only deleted if they match the value.\n    * \n    * <h4>example</h4>\n    * \n    * <pre>\n    * tagApi.conditionallyDeleteFromResources(ImmutableMap.of(&quot;Purpose&quot;, &quot;production&quot;), ImmutableSet.of(&quot;ami-1a2b3c4d&quot;));\n    * </pre>\n    * \n    * @param conditionalTagValues\n    *           tag id to value it must match before deleting. For a tag without\n    *           a value, supply empty string.\n    * @param resourceIds\n    *           The ID of a resource with the tag. For example,\n    *           {@code ami-1a2b3c4d}\n    * @see #deleteFromResources(Iterable, Iterable)\n    */\n   @Named(\"DeleteTags\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DeleteTags\")\n   void conditionallyDeleteFromResources(\n         @BinderParam(BindTagsToIndexedFormParams.class) Map<String, String> conditionalTagValues,\n         @BinderParam(BindResourceIdsToIndexedFormParams.class) Iterable<String> resourceIds);\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/features/WindowsApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.features;\n\nimport static org.jclouds.aws.reference.FormParameters.ACTION;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.FormParam;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.aws.filters.FormSigner;\nimport org.jclouds.ec2.binders.BindBundleIdsToIndexedFormParams;\nimport org.jclouds.ec2.binders.BindFiltersToIndexedFormParams;\nimport org.jclouds.ec2.binders.BindS3UploadPolicyAndSignature;\nimport org.jclouds.ec2.domain.BundleTask;\nimport org.jclouds.ec2.domain.PasswordData;\nimport org.jclouds.ec2.options.BundleInstanceS3StorageOptions;\nimport org.jclouds.ec2.xml.BundleTaskHandler;\nimport org.jclouds.ec2.xml.DescribeBundleTasksResponseHandler;\nimport org.jclouds.ec2.xml.GetPasswordDataResponseHandler;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.location.functions.RegionToEndpointOrProviderIfNull;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.EndpointParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.FormParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SinceApiVersion;\nimport org.jclouds.rest.annotations.VirtualHost;\nimport org.jclouds.rest.annotations.XMLResponseParser;\n\nimport com.google.common.collect.Multimap;\n\n/**\n * Provides access to EC2 Windows Features via the Query API\n * <p/>\n * \n * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference\" >doc</a>\n */\n@RequestFilters(FormSigner.class)\n@VirtualHost\n@SinceApiVersion(\"2008-08-08\")\npublic interface WindowsApi {\n\n   /**\n    * Bundles the Windows instance. This procedure is not applicable for Linux\n    * and UNIX instances. For more information, go to the Amazon Elastic Compute\n    * Cloud Developer Guide or Amazon Elastic Compute Cloud Getting Started\n    * Guide.\n    * \n    * @param region\n    *           Bundles are tied to the Region where its files are located\n    *           within Amazon S3.\n    * \n    * @param instanceId\n    *           The ID of the instance to bundle.\n    * @param prefix\n    *           Specifies the beginning of the file name of the AMI.\n    * @param bucket\n    *           The bucket in which to store the AMI. You can specify a bucket\n    *           that you already own or a new bucket that Amazon EC2 creates on\n    *           your behalf. If you specify a bucket that belongs to someone\n    *           else, Amazon EC2 returns an error.\n    * @param uploadPolicy\n    *           An Amazon S3 upload policy that gives Amazon EC2 permission to\n    *           upload items into Amazon S3 on the user's behalf.\n    *           <p/>\n    *           ex.\n    * \n    *           <pre>\n    * {\"expiration\": \"2008-08-30T08:49:09Z\",\"conditions\": [\"bucket\": \"my-bucket\"},[\"starts-with\", \"$key\", \"my-new-image\"]]}\n    * </pre>\n    * \n    * @param options\n    *           if the bucket isn't owned by you, use this to set the bucket's\n    *           accesskeyid\n    * @return status of the work\n    * \n    * @see #cancelBundleTaskInRegion\n    * @see #describeBundleTasksInRegion\n    * \n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-BundleInstance.html\"\n    *      />\n    */\n   @Named(\"BundleInstance\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"BundleInstance\")\n   @XMLResponseParser(BundleTaskHandler.class)\n   BundleTask bundleInstanceInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n            @FormParam(\"InstanceId\") String instanceId, @FormParam(\"Storage.S3.Prefix\") String prefix,\n            @FormParam(\"Storage.S3.Bucket\") String bucket,\n            @BinderParam(BindS3UploadPolicyAndSignature.class) String uploadPolicy,\n            BundleInstanceS3StorageOptions... options);\n\n   /**\n    * Cancels an Amazon EC2 bundling operation.\n    * \n    * @param region\n    *           The bundleTask ID is tied to the Region.\n    * @param bundleId\n    *           The ID of the bundle task to cancel.\n    * @return task for the cancel.\n    * \n    * @see #bundleInstanceInRegion\n    * @see #describeBundleTasksInRegion\n    * \n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CancelBundleTask.html\"\n    *      />\n    */\n   @Named(\"CancelBundleTask\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"CancelBundleTask\")\n   @XMLResponseParser(BundleTaskHandler.class)\n   BundleTask cancelBundleTaskInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n            @FormParam(\"BundleId\") String bundleId);\n\n   /**\n    *\n    * Describes current bundling tasks.\n    *\n    * @param region\n    *           The bundleTask ID is tied to the Region.\n    *\n    * @see #cancelBundleTaskInRegion\n    * @see #bundleInstanceInRegion\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeBundleTasks.html\"\n    *      />\n    */\n   @Named(\"DescribeBundleTasks\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DescribeBundleTasks\")\n   @XMLResponseParser(DescribeBundleTasksResponseHandler.class)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<BundleTask> describeBundleTasksInRegion(\n           @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n           @BinderParam(BindBundleIdsToIndexedFormParams.class) String... bundleTaskIds);\n\n   /**\n    *\n    * Describes current bundling tasks.\n    *\n    * @param region\n    *           The bundleTask ID is tied to the Region.\n    * @param filter\n    *           Filter multimap\n    *\n    * @see #cancelBundleTaskInRegion\n    * @see #bundleInstanceInRegion\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeBundleTasks.html\"\n    *      />\n    */\n   @Named(\"DescribeBundleTasks\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DescribeBundleTasks\")\n   @XMLResponseParser(DescribeBundleTasksResponseHandler.class)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<BundleTask> describeBundleTasksInRegionWithFilter(\n           @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n           @BinderParam(BindFiltersToIndexedFormParams.class) Multimap<String, String> filter);\n\n   /**\n    *\n    * Retrieves the encrypted administrator password for the instances running Windows.\n    *\n    * @param region The region where the instance is based\n    * @param instanceId The ID of the instance to query\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-GetPasswordData.html\" />\n    */\n   @Named(\"GetPasswordData\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"GetPasswordData\")\n   @XMLResponseParser(GetPasswordDataResponseHandler.class)\n   PasswordData getPasswordDataInRegion(\n         @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n         @FormParam(\"InstanceId\") String instanceId);\n\n\n   /**\n    * \n    * Retrieves the encrypted administrator password for the instances running Windows. <h4>Note</h4>\n    * \n    * The Windows password is only generated the first time an AMI is launched. It is not generated\n    * for rebundled AMIs or after the password is changed on an instance.\n    * \n    * The password is encrypted using the key pair that you provided.\n    * \n    * @param instanceId\n    *           The ID of the instance to query\n    * @return password data or null if not available\n    * @see <a href=\n    *      \"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-GetPasswordData.html\"\n    *      />\n    */\n   @Named(\"GetPasswordData\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"GetPasswordData\")\n   @XMLResponseParser(GetPasswordDataResponseHandler.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   PasswordData getPasswordDataForInstance(@FormParam(\"InstanceId\") String instanceId);\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/functions/ConvertUnencodedBytesToBase64EncodedString.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.functions;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.io.BaseEncoding.base64;\n\nimport jakarta.inject.Singleton;\n\nimport com.google.common.base.Function;\n\n/**\n * Binds base64 encodes the byte [] input\n */\n@Singleton\npublic class ConvertUnencodedBytesToBase64EncodedString implements Function<Object, String> {\n\n   @Override\n   public String apply(Object from) {\n      checkArgument(checkNotNull(from, \"input\") instanceof byte[], \"this binder is only valid for byte []!\");\n      byte[] unencodedData = (byte[]) from;\n      checkArgument(checkNotNull(unencodedData, \"unencodedData\").length <= 16 * 1024,\n            \"userData cannot be larger than 16kb\");\n      return base64().encode(unencodedData);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/functions/EncodedRSAPublicKeyToBase64.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.functions;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.io.BaseEncoding.base64;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.util.Predicates2;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Predicates;\n\n/**\n * @see <a href=\n *      \"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-ImportKeyPair.html\"\n *      />\n */\n@Singleton\npublic class EncodedRSAPublicKeyToBase64 implements Function<Object, String> {\n   private static final Predicate<String> ALLOWED_MARKERS = Predicates.or(\n      Predicates2.startsWith(\"ssh-rsa\"),\n      Predicates2.startsWith(\"-----BEGIN CERTIFICATE-----\"),\n      Predicates2.startsWith(\"---- BEGIN SSH2 PUBLIC KEY ----\"));\n\n   @Override\n   public String apply(Object from) {\n      String fromString = checkNotNull(from, \"input\").toString();\n      checkArgument(ALLOWED_MARKERS.apply(fromString), \"must be a ssh public key, conforming to %s \", ALLOWED_MARKERS);\n      return base64().encode(fromString.getBytes(UTF_8));\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/options/BundleInstanceS3StorageOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\n\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.ec2.options.internal.BaseEC2RequestOptions;\nimport org.jclouds.location.Provider;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.Multimap;\nimport com.google.inject.Inject;\n\n/**\n * Contains options supported in the Form API for the RegisterImage operation.\n * <h2>\n * Usage</h2> The recommended way to instantiate a\n * BundleInstanceS3StorageOptions object is to statically import\n * BundleInstanceS3StorageOptions.Builder.* and invoke a static creation method\n * followed by an instance mutator (if needed):\n * <p/>\n * <code>\n * import static org.jclouds.ec2.options.BundleInstanceS3StorageOptions.Builder.*\n * <p/>\n * EC2Api connection = // get connection\n * String imageId = connection.getWindowsServices().bundleInstanceInRegion(...bucketOwnedBy(anotherAccessKey));\n * <code>\n * \n * @see <a\n *      href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-BundleInstance.html\"\n *      />\n */\npublic class BundleInstanceS3StorageOptions extends BaseEC2RequestOptions {\n\n   @Inject\n   @VisibleForTesting\n   @Provider\n   Supplier<Credentials> creds;\n\n   @Override\n   public Multimap<String, String> buildFormParameters() {\n      if (getAwsAccessKeyId() == null) {\n         checkState(creds != null, \"creds should have been injected\");\n         bucketOwnedBy(creds.get().identity);\n      }\n      return super.buildFormParameters();\n   }\n\n   /**\n    * \n    * @param ccessKeyId\n    *           The Access Key ID of the owner of the Amazon S3 bucket.\n    */\n   public BundleInstanceS3StorageOptions bucketOwnedBy(String ccessKeyId) {\n      formParameters.put(\"Storage.S3.AWSAccessKeyId\", checkNotNull(ccessKeyId, \"ccessKeyId\"));\n      return this;\n   }\n\n   /**\n    * \n    * @return The Access Key ID of the owner of the Amazon S3 bucket.\n    */\n   public String getAwsAccessKeyId() {\n      return getFirstFormOrNull(\"Storage.S3.AWSAccessKeyId\");\n   }\n\n   public static class Builder {\n      /**\n       * @see BundleInstanceS3StorageOptions#bucketOwnedBy(accessKeyId)\n       */\n      public static BundleInstanceS3StorageOptions bucketOwnedBy(String accessKeyId) {\n         BundleInstanceS3StorageOptions options = new BundleInstanceS3StorageOptions();\n         return options.bucketOwnedBy(accessKeyId);\n      }\n\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/options/CreateImageOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.ec2.options.internal.BaseEC2RequestOptions;\n\n/**\n * Contains options supported in the Form API for the CreateImage operation. <h2>\n * Usage</h2> The recommended way to instantiate a CreateImageOptions object is to statically import\n * CreateImageOptions.Builder.* and invoke a static creation method followed by an instance mutator\n * (if needed):\n * <p/>\n * <code>\n * import static org.jclouds.ec2.options.CreateImageOptions.Builder.*\n * <p/>\n * EC2Api connection = // get connection\n * Future<Set<ImageMetadata>> images = connection.getAMIApi().get().createImage(withDescription(\"123125\").noReboot());\n * <code>\n * \n * @see <a\n *      href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-form-CreateImage.html\"\n *      />\n */\npublic class CreateImageOptions extends BaseEC2RequestOptions {\n   public static final CreateImageOptions NONE = new CreateImageOptions();\n\n   /**\n    * The description of the AMI that was provided during image creation.\n    * <p/>\n    * \n    * Up to 255 characters\n    */\n   public CreateImageOptions withDescription(String description) {\n      formParameters.put(\"Description\", checkNotNull(description, \"description\"));\n      return this;\n   }\n\n   public String getDescription() {\n      return getFirstFormOrNull(\"Description\");\n\n   }\n\n   /**\n    * By default this property is set to false, which means Amazon EC2 attempts to cleanly shut down\n    * the instance before image creation and reboots the instance afterwards. When set to true,\n    * Amazon EC2 does not shut down the instance before creating the image. When this option is\n    * used, file system integrity on the created image cannot be guaranteed.\n    */\n   public CreateImageOptions noReboot() {\n      formParameters.put(\"NoReboot\", \"true\");\n      return this;\n   }\n\n   public boolean getNoReboot() {\n      return getFirstFormOrNull(\"NoReboot\") != null;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see CreateImageOptions#withDescription(String )\n       */\n      public static CreateImageOptions withDescription(String description) {\n         CreateImageOptions options = new CreateImageOptions();\n         return options.withDescription(description);\n      }\n\n      /**\n       * @see CreateImageOptions#noReboot()\n       */\n      public static CreateImageOptions noReboot() {\n         CreateImageOptions options = new CreateImageOptions();\n         return options.noReboot();\n      }\n\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/options/CreateSnapshotOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.ec2.options.internal.BaseEC2RequestOptions;\n\n/**\n * Contains options supported in the Form API for the CreateSnapshot operation. <h2>\n * Usage</h2> The recommended way to instantiate a CreateSnapshotOptions object is to statically\n * import CreateSnapshotOptions.Builder.* and invoke a static creation method followed by an\n * instance mutator (if needed):\n * <p/>\n * <code>\n * import static org.jclouds.ec2.options.CreateSnapshotOptions.Builder.*\n * <p/>\n * EC2Api connection = // get connection\n * Snapshot snapshot = connection.getElasticBlockStoreApi().get().createSnapshotInRegion(volumeId, withDescription(\"123125\"));\n * <code>\n * \n * @see <a\n *      href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-form-CreateSnapshot.html\"\n *      />\n */\npublic class CreateSnapshotOptions extends BaseEC2RequestOptions {\n\n   /**\n    * Description of the Amazon EBS snapshot.\n    * <p/>\n    * \n    * Up to 255 characters\n    */\n   public CreateSnapshotOptions withDescription(String description) {\n      formParameters.put(\"Description\", checkNotNull(description, \"description\"));\n      return this;\n   }\n\n   public String getDescription() {\n      return getFirstFormOrNull(\"Description\");\n\n   }\n\n   public static class Builder {\n\n      /**\n       * @see CreateSnapshotOptions#withDescription(String )\n       */\n      public static CreateSnapshotOptions withDescription(String identityId) {\n         CreateSnapshotOptions options = new CreateSnapshotOptions();\n         return options.withDescription(identityId);\n      }\n\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/options/CreateVolumeOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.ec2.options.internal.BaseEC2RequestOptions;\n\n/**\n * Contains options supported in the Form API for the CreateVolume operation. <h2>\n * Usage</h2> The recommended way to instantiate a CreateVolumeOptions object is to statically\n * import CreateVolumeOptions.Builder.* and invoke a static creation method followed by an\n * instance mutator (if needed):\n * <p/>\n * <code>\n * import static org.jclouds.ec2.options.CreateVolumeOptions.Builder.*\n * <p/>\n * EC2Api connection = // get connection\n * Volume volume = connection.getElasticBlockStoreApi().get().createVolumeInAvailabilityZone(availabilityZone, fromSnapshotId(\"123125\"));\n * <code>\n *\n * @see <a\n *      href=\"http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CreateVolume.html\"\n *      />\n */\npublic class CreateVolumeOptions extends BaseEC2RequestOptions {\n\n   /**\n    * Snapshot ID to create this volume from.\n    */\n   public CreateVolumeOptions withSize(int size) {\n      formParameters.put(\"Size\", Integer.toString(size));\n      return this;\n   }\n\n   public int getSize() {\n      return Integer.parseInt(getFirstFormOrNull(\"Size\"));\n   }\n\n   /**\n    * Snapshot ID to create this volume from.\n    */\n   public CreateVolumeOptions fromSnapshotId(String snapshotId) {\n      formParameters.put(\"SnapshotId\", checkNotNull(snapshotId, \"snapshotId\"));\n      return this;\n   }\n\n   public String getSnapshotId() {\n      return getFirstFormOrNull(\"SnapshotId\");\n   }\n\n   /**\n    * EBS volume type to use - if not specified, will be \"standard\".\n    */\n   public CreateVolumeOptions volumeType(String volumeType) {\n      formParameters.put(\"VolumeType\", checkNotNull(volumeType, \"volumeType\"));\n      return this;\n   }\n\n   public String getVolumeType() {\n      return getFirstFormOrNull(\"VolumeType\");\n   }\n\n   /**\n    * EBS provisioned IOPS\n    */\n   public CreateVolumeOptions withIops(Integer iops) {\n      formParameters.put(\"Iops\", checkNotNull(iops, \"iops\").toString());\n      return this;\n   }\n\n   public Integer getIops() {\n      return Integer.valueOf(getFirstFormOrNull(\"Iops\"));\n   }\n\n   /**\n    * Should this EBS volume be encrypted?\n    */\n   public CreateVolumeOptions isEncrypted(boolean encrypted) {\n      if (encrypted)\n         formParameters.put(\"Encrypted\", \"true\");\n      return this;\n   }\n\n   public boolean getEncrypted() {\n      return Boolean.parseBoolean(getFirstFormOrNull(\"Encrypted\"));\n   }\n\n   public static class Builder {\n\n      /**\n       * @see CreateVolumeOptions#fromSnapshotId(String)\n       */\n      public static CreateVolumeOptions fromSnapshotId(String snapshotId) {\n         CreateVolumeOptions options = new CreateVolumeOptions();\n         return options.fromSnapshotId(snapshotId);\n      }\n\n      /**\n       * @see CreateVolumeOptions#withSize(int)\n       */\n      public static CreateVolumeOptions withSize(int size) {\n         CreateVolumeOptions options = new CreateVolumeOptions();\n         return options.withSize(size);\n      }\n\n      /**\n       * @see CreateVolumeOptions#volumeType(String)\n       */\n      public static CreateVolumeOptions volumeType(String volumeType) {\n         CreateVolumeOptions options = new CreateVolumeOptions();\n         return options.volumeType(volumeType);\n      }\n\n      /**\n       * @see CreateVolumeOptions#withIops(Integer)\n       */\n      public static CreateVolumeOptions withIops(Integer iops) {\n         CreateVolumeOptions options = new CreateVolumeOptions();\n         return options.withIops(iops);\n      }\n\n      /**\n       * @see CreateVolumeOptions#isEncrypted(boolean)\n       */\n      public static CreateVolumeOptions isEncrypted(boolean encrypted) {\n         CreateVolumeOptions options = new CreateVolumeOptions();\n         return options.isEncrypted(encrypted);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/options/DescribeAvailabilityZonesOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.options;\n\nimport java.util.Arrays;\nimport java.util.Set;\n\nimport org.jclouds.ec2.options.internal.BaseEC2RequestOptions;\n\n/**\n * Contains options supported in the Form API for the DescribeAvailabilityZones operation. <h2>\n * Usage</h2> The recommended way to instantiate a DescribeAvailabilityZonesOptions object is to\n * statically import DescribeAvailabilityZonesOptions.Builder.* and invoke a static creation method\n * followed by an instance mutator (if needed):\n * <p/>\n * <code>\n * import static org.jclouds.ec2.options.DescribeAvailabilityZonesOptions.Builder.*\n * <p/>\n * EC2Api connection = // get connection\n * Future<Set<ImageMetadata>> images = connection.getAvailabilityZoneAndRegionApi().get().describeAvailabilityZones(zones(\"us-east-1a\", \"us-east-1b\"));\n * <code>\n * \n * @see <a\n *      href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-form-DescribeAvailabilityZones.html\"\n *      />\n */\npublic class DescribeAvailabilityZonesOptions extends BaseEC2RequestOptions {\n\n   /**\n    * Availability Zone name.\n    */\n   public DescribeAvailabilityZonesOptions zones(String... zones) {\n      String[] zoneStrings = Arrays.copyOf(zones, zones.length, String[].class);\n      indexFormValuesWithPrefix(\"ZoneName\", zoneStrings);\n      return this;\n   }\n\n   public Set<String> getZones() {\n      return getFormValuesWithKeysPrefixedBy(\"ZoneName.\");\n   }\n\n   public static class Builder {\n\n      /**\n       * @see DescribeAvailabilityZonesOptions#zones(String...)\n       */\n      public static DescribeAvailabilityZonesOptions availabilityZones(String... zones) {\n         DescribeAvailabilityZonesOptions options = new DescribeAvailabilityZonesOptions();\n         return options.zones(zones);\n      }\n\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/options/DescribeImagesOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Set;\n\nimport org.jclouds.ec2.options.internal.BaseEC2RequestOptions;\n\n/**\n * Contains options supported in the Form API for the DescribeImages operation. <h2>\n * Usage</h2> The recommended way to instantiate a DescribeImagesOptions object is to statically\n * import DescribeImagesOptions.Builder.* and invoke a static creation method followed by an\n * instance mutator (if needed):\n * <p/>\n * <code>\n * import static org.jclouds.ec2.options.DescribeImagesOptions.Builder.*\n * <p/>\n * EC2Api connection = // get connection\n * Future<Set<ImageMetadata>> images = connection.getAMIApi().get().describeImages(executableBy(\"123125\").imageIds(1000, 1004));\n * <code>\n * \n * @see <a\n *      href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-form-DescribeImages.html\"\n *      />\n */\npublic class DescribeImagesOptions extends BaseEC2RequestOptions {\n   public static final DescribeImagesOptions NONE = new DescribeImagesOptions();\n\n   /**\n    * AMIs for which the specified user has explicit launch permissions.\n    * \n    */\n   public DescribeImagesOptions executableBy(String identityId) {\n      formParameters.put(\"ExecutableBy\", checkNotNull(identityId, \"identityId\"));\n      return this;\n   }\n\n   public String getExecutableBy() {\n      return getFirstFormOrNull(\"ExecutableBy\");\n   }\n\n   /**\n    * AMI IDs to describe.\n    */\n   public DescribeImagesOptions imageIds(String... imageIds) {\n      indexFormValuesWithPrefix(\"ImageId\", imageIds);\n      return this;\n   }\n\n   public DescribeImagesOptions imageIds(Iterable<String> imageIds) {\n      indexFormValuesWithPrefix(\"ImageId\", imageIds);\n      return this;\n   }\n\n   public Set<String> getImageIds() {\n      return getFormValuesWithKeysPrefixedBy(\"ImageId.\");\n   }\n\n   /**\n    * Returns AMIs owned by the specified owner. Multiple owners can be specified.\n    */\n   public DescribeImagesOptions ownedBy(String... owners) {\n      indexFormValuesWithPrefix(\"Owner\", owners);\n      return this;\n   }\n\n   public Set<String> getOwners() {\n      return getFormValuesWithKeysPrefixedBy(\"Owner.\");\n   }\n\n   public static class Builder {\n\n      /**\n       * @see DescribeImagesOptions#executableBy(String )\n       */\n      public static DescribeImagesOptions executableBy(String identityId) {\n         DescribeImagesOptions options = new DescribeImagesOptions();\n         return options.executableBy(identityId);\n      }\n\n      /**\n       * @see DescribeImagesOptions#imageIds(String[] )\n       */\n      public static DescribeImagesOptions imageIds(String... imageIds) {\n         DescribeImagesOptions options = new DescribeImagesOptions();\n         return options.imageIds(imageIds);\n      }\n\n      /**\n       * @see DescribeImagesOptions#ownedBy(String[] )\n       */\n      public static DescribeImagesOptions ownedBy(String... owners) {\n         DescribeImagesOptions options = new DescribeImagesOptions();\n         return options.ownedBy(owners);\n      }\n\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/options/DescribeRegionsOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.options;\n\nimport java.util.Arrays;\nimport java.util.Set;\n\nimport org.jclouds.ec2.options.internal.BaseEC2RequestOptions;\n\n/**\n * Contains options supported in the Form API for the DescribeRegions operation. <h2>\n * Usage</h2> The recommended way to instantiate a DescribeRegionsOptions object is to statically\n * import DescribeRegionsOptions.Builder.* and invoke a static creation method followed by an\n * instance mutator (if needed):\n * <p/>\n * <code>\n * import static org.jclouds.ec2.options.DescribeRegionsOptions.Builder.*\n * <p/>\n * EC2Api connection = // get connection\n * Future<Set<ImageMetadata>> images = connection.getRegionsAndRegionsServices().describeRegions(regions(\"us-east-1a\", \"us-east-1b\"));\n * <code>\n * \n * @see <a\n *      href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-form-DescribeRegions.html\"\n *      />\n */\npublic class DescribeRegionsOptions extends BaseEC2RequestOptions {\n\n   /**\n    * Name of a Region.\n    */\n   public DescribeRegionsOptions regions(String... regions) {\n      String[] regionStrings = Arrays.copyOf(regions, regions.length, String[].class);\n      indexFormValuesWithPrefix(\"RegionName\", regionStrings);\n      return this;\n   }\n\n   public Set<String> getZones() {\n      return getFormValuesWithKeysPrefixedBy(\"RegionName.\");\n   }\n\n   public static class Builder {\n\n      /**\n       * @see DescribeRegionsOptions#regions(String[] )\n       */\n      public static DescribeRegionsOptions regions(String... regions) {\n         DescribeRegionsOptions options = new DescribeRegionsOptions();\n         return options.regions(regions);\n      }\n\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/options/DescribeSnapshotsOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.options;\n\nimport java.util.Set;\n\nimport org.jclouds.ec2.options.internal.BaseEC2RequestOptions;\n\n/**\n * Contains options supported in the Form API for the DescribeSnapshots operation. <h2>\n * Usage</h2> The recommended way to instantiate a DescribeSnapshotsOptions object is to statically\n * import DescribeSnapshotsOptions.Builder.* and invoke a static creation method followed by an\n * instance mutator (if needed):\n * <p/>\n * <code>\n * import static org.jclouds.ec2.options.DescribeSnapshotsOptions.Builder.*\n * <p/>\n * EC2Api connection = // get connection\n * Set<Snapshot> snapshots = connection.getElasticBlockStoreApi().get().describeSnapshots(restorableBy(\"123125\").snapshotIds(1000, 1004));\n * <code>\n * \n * @see <a\n *      href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-form-DescribeSnapshots.html\"\n *      />\n */\npublic class DescribeSnapshotsOptions extends BaseEC2RequestOptions {\n\n   /**\n    * Account ID of a user that can create volumes from the snapshot.\n    * \n    */\n   public DescribeSnapshotsOptions restorableBy(String... accountIds) {\n      indexFormValuesWithPrefix(\"RestorableBy\", accountIds);\n      return this;\n   }\n\n   public String getRestorableBy() {\n      return getFirstFormOrNull(\"RestorableBy\");\n   }\n\n   /**\n    * The ID of the Amazon EBS snapshot.\n    */\n   public DescribeSnapshotsOptions snapshotIds(String... snapshotIds) {\n      indexFormValuesWithPrefix(\"SnapshotId\", snapshotIds);\n      return this;\n   }\n\n   public Set<String> getSnapshotIds() {\n      return getFormValuesWithKeysPrefixedBy(\"SnapshotId.\");\n   }\n\n   /**\n    * Returns snapshots owned by the specified owner. Multiple owners can be specified.\n    * <p/>\n    * Valid Values: self | amazon | AWS Account ID\n    */\n   public DescribeSnapshotsOptions ownedBy(String... owners) {\n      indexFormValuesWithPrefix(\"Owner\", owners);\n      return this;\n   }\n\n   public Set<String> getOwners() {\n      return getFormValuesWithKeysPrefixedBy(\"Owner.\");\n   }\n\n   public static class Builder {\n\n      /**\n       * @see DescribeSnapshotsOptions#restorableBy(String[] )\n       */\n      public static DescribeSnapshotsOptions restorableBy(String... accountIds) {\n         DescribeSnapshotsOptions options = new DescribeSnapshotsOptions();\n         return options.restorableBy(accountIds);\n      }\n\n      /**\n       * @see DescribeSnapshotsOptions#snapshotIds(String[] )\n       */\n      public static DescribeSnapshotsOptions snapshotIds(String... snapshotIds) {\n         DescribeSnapshotsOptions options = new DescribeSnapshotsOptions();\n         return options.snapshotIds(snapshotIds);\n      }\n\n      /**\n       * @see DescribeSnapshotsOptions#ownedBy(String[] )\n       */\n      public static DescribeSnapshotsOptions ownedBy(String... owners) {\n         DescribeSnapshotsOptions options = new DescribeSnapshotsOptions();\n         return options.ownedBy(owners);\n      }\n\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/options/DetachVolumeOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.ec2.options.internal.BaseEC2RequestOptions;\n\n/**\n * Contains options supported in the Form API for the DetachVolume operation. <h2>\n * Usage</h2> The recommended way to instantiate a DetachVolumeOptions object is to statically\n * import DetachVolumeOptions.Builder.* and invoke a static creation method followed by an instance\n * mutator (if needed):\n * <p/>\n * <code>\n * import static org.jclouds.ec2.options.DetachVolumeOptions.Builder.*\n * <p/>\n * EC2Api client = // get connection\n * client.getElasticBlockStoreApi().get().detachVolumeInRegion(null, id, fromDevice(\"123125\").force());\n * <code>\n * \n * @see <a\n *      href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-form-DetachVolume.html\"\n *      />\n */\npublic class DetachVolumeOptions extends BaseEC2RequestOptions {\n   /**\n    * The ID of the instance.\n    */\n   public DetachVolumeOptions fromInstance(String instanceId) {\n      formParameters.put(\"InstanceId\", checkNotNull(instanceId, \"instanceId\"));\n      return this;\n   }\n\n   public String getInstance() {\n      return getFirstFormOrNull(\"InstanceId\");\n\n   }\n\n   /**\n    * The device name.\n    */\n   public DetachVolumeOptions fromDevice(String device) {\n      formParameters.put(\"Device\", checkNotNull(device, \"device\"));\n      return this;\n   }\n\n   public String getDevice() {\n      return getFirstFormOrNull(\"Device\");\n\n   }\n\n   public static class Builder {\n      /**\n       * @see DetachVolumeOptions#fromInstance(String )\n       */\n      public static DetachVolumeOptions fromInstance(String instance) {\n         DetachVolumeOptions options = new DetachVolumeOptions();\n         return options.fromInstance(instance);\n      }\n\n      /**\n       * @see DetachVolumeOptions#fromDevice(String )\n       */\n      public static DetachVolumeOptions fromDevice(String device) {\n         DetachVolumeOptions options = new DetachVolumeOptions();\n         return options.fromDevice(device);\n      }\n\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/options/RegisterImageBackedByEbsOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.options;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.ec2.domain.Image.Architecture;\nimport org.jclouds.javax.annotation.Nullable;\n\n/**\n * Contains options supported in the Form API for the RegisterImage operation. <h2>\n * Usage</h2> The recommended way to instantiate a RegisterImageBackedByEbsOptions object is to statically\n * import RegisterImageBackedByEbsOptions.Builder.* and invoke a static creation method followed by an instance\n * mutator (if needed):\n * <p/>\n * <code>\n * import static org.jclouds.ec2.options.RegisterImageBackedByEbsOptions.Builder.*\n * <p/>\n * EC2Api connection = // get connection\n * String imageId = connection.getImageServices().registerImageBackedByEbs(...addEphemeralBlockDeviceFromSnapshot(\"/dev/sda2\",\"virtual-1\",\"snapshot-id\"));\n * <code>\n * \n * @see <a\n *      href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-form-RegisterImage.html\"\n *      />\n */\npublic class RegisterImageBackedByEbsOptions extends RegisterImageOptions {\n\n   private int deviceIndex = 1;\n\n   /**\n    * \n    * adds a block device to the image from an ebs snapshot. This device is deleted on instance\n    * termination.\n    * \n    * @param name\n    *           The device name (e.g., /dev/sdh).\n    * @param virtualName\n    *           The virtual device name. (nullable)\n    * @param snapshotId\n    *           The ID of the snapshot.\n    */\n   public RegisterImageBackedByEbsOptions addEphemeralBlockDeviceFromSnapshot(String deviceName,\n            @Nullable String virtualName, String snapshotId) {\n      formParameters.put(\"BlockDeviceMapping.\" + deviceIndex + \".DeviceName\", checkNotNull(\n               deviceName, \"deviceName\"));\n      if (virtualName != null)\n         formParameters.put(\"BlockDeviceMapping.\" + deviceIndex + \".VirtualName\", checkNotNull(\n                  virtualName, \"virtualName\"));\n      formParameters.put(\"BlockDeviceMapping.\" + deviceIndex + \".Ebs.SnapshotId\", checkNotNull(\n               snapshotId, \"snapshotId\"));\n      deviceIndex++;\n      return this;\n   }\n\n   /**\n    * \n    * adds a new block device to the image. This device is deleted on instance termination.\n    * \n    * @param name\n    *           The device name (e.g., /dev/sdh).\n    * @param virtualName\n    *           The virtual device name.\n    * @param volumeSize\n    *           The size of the volume, in GiBs.\n    */\n   public RegisterImageBackedByEbsOptions addNewEphemeralBlockDevice(String deviceName,\n            @Nullable String virtualName, int volumeSize) {\n      checkArgument(volumeSize > 0 && volumeSize < 1025, \"volumeSize must be between 1 and 1024 gb\");\n      formParameters.put(\"BlockDeviceMapping.\" + deviceIndex + \".DeviceName\", checkNotNull(\n               deviceName, \"deviceName\"));\n      if (virtualName != null)\n         formParameters.put(\"BlockDeviceMapping.\" + deviceIndex + \".VirtualName\", checkNotNull(\n                  virtualName, \"virtualName\"));\n      formParameters.put(\"BlockDeviceMapping.\" + deviceIndex + \".Ebs.VolumeSize\", volumeSize + \"\");\n      deviceIndex++;\n      return this;\n   }\n\n   /**\n    * \n    * adds a block device to the image from an ebs snapshot.\n    * \n    * @param deviceName\n    *           The device name (e.g., /dev/sdh).\n    * @param virtualName\n    *           The virtual device name. (nullable)\n    * @param snapshotId\n    *           The ID of the snapshot.\n    * @param deleteOnTermination\n    *           Whether this volume should be automatically deleted on instance termination.\n    *           Defaults to false.\n    * @param volumeType\n    *           What EBS volume type should be used.\n    * @param iops\n    *           EBS provisioned IOPS for this volume.\n    * @param encrypted\n    *           Whether this volume should be encrypted.\n    */\n   public RegisterImageBackedByEbsOptions addBlockDeviceFromSnapshot(String deviceName,\n            @Nullable String virtualName, String snapshotId, boolean deleteOnTermination,\n            @Nullable String volumeType, @Nullable Integer iops, boolean encrypted) {\n\n      addAdvancedEbsOptions(deleteOnTermination, volumeType, iops, encrypted);\n      addEphemeralBlockDeviceFromSnapshot(deviceName, virtualName, snapshotId);\n\n      return this;\n   }\n\n   /**\n    *\n    * adds a new block device to the image.\n    *\n    * @param deviceName\n    *           The device name (e.g., /dev/sdh).\n    * @param virtualName\n    *           The virtual device name. (nullable)\n    * @param volumeSize\n    *           The size of the volume, in GiBs..\n    * @param deleteOnTermination\n    *           Whether this volume should be automatically deleted on instance termination.\n    *           Defaults to false.\n    * @param volumeType\n    *           What EBS volume type should be used.\n    * @param iops\n    *           EBS provisioned IOPS for this volume.\n    * @param encrypted\n    *           Whether this volume should be encrypted.\n    */\n   public RegisterImageBackedByEbsOptions addNewBlockDevice(String deviceName,\n                                                            @Nullable String virtualName,\n                                                            int volumeSize,\n                                                            boolean deleteOnTermination,\n                                                            @Nullable String volumeType,\n                                                            @Nullable Integer iops,\n                                                            boolean encrypted) {\n      addAdvancedEbsOptions(deleteOnTermination, volumeType, iops, encrypted);\n      addNewEphemeralBlockDevice(deviceName, virtualName, volumeSize);\n\n      return this;\n   }\n\n   private RegisterImageBackedByEbsOptions addAdvancedEbsOptions(boolean deleteOnTermination,\n                                                                 @Nullable String volumeType,\n                                                                 @Nullable Integer iops,\n                                                                 boolean encrypted) {\n\n      formParameters.put(\"BlockDeviceMapping.\" + deviceIndex + \".Ebs.DeleteOnTermination\",\n              Boolean.toString(deleteOnTermination));\n\n      if (volumeType != null)\n         formParameters.put(\"BlockDeviceMapping.\" + deviceIndex + \".Ebs.VolumeType\", volumeType);\n      if (iops != null)\n         formParameters.put(\"BlockDeviceMapping.\" + deviceIndex + \".Ebs.Iops\", iops.toString());\n      if (encrypted)\n         formParameters.put(\"BlockDeviceMapping.\" + deviceIndex + \".Ebs.Encrypted\", \"true\");\n\n      return this;\n   }\n\n   /**\n    *\n    * adds a block device to the image from an ebs snapshot. This device is retained on instance\n    * termination.\n    *\n    * @param name\n    *           The device name (e.g., /dev/sdh).\n    * @param virtualName\n    *           The virtual device name. (nullable)\n    * @param snapshotId\n    *           The ID of the snapshot.\n    */\n   public RegisterImageBackedByEbsOptions addBlockDeviceFromSnapshot(String deviceName,\n                                                                     @Nullable String virtualName, String snapshotId) {\n      formParameters.put(\"BlockDeviceMapping.\" + deviceIndex + \".Ebs.DeleteOnTermination\", \"false\");\n      addEphemeralBlockDeviceFromSnapshot(deviceName, virtualName, snapshotId);\n      return this;\n   }\n\n   /**\n    * \n    * adds a new block device to the image. This device is retained on instance termination.\n    * \n    * @param name\n    *           The device name (e.g., /dev/sdh).\n    * @param virtualName\n    *           The virtual device name.\n    * @param volumeSize\n    *           The size of the volume, in GiBs..\n    */\n   public RegisterImageBackedByEbsOptions addNewBlockDevice(String deviceName,\n            @Nullable String virtualName, int volumeSize) {\n      formParameters.put(\"BlockDeviceMapping.\" + deviceIndex + \".Ebs.DeleteOnTermination\", \"false\");\n      addNewEphemeralBlockDevice(deviceName, virtualName, volumeSize);\n      return this;\n   }\n\n   public static class Builder {\n      /**\n       * @see RegisterImageBackedByEbsOptions#asArchitecture(Architecture)\n       */\n      public static RegisterImageBackedByEbsOptions asArchitecture(Architecture architecture) {\n         RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions();\n         return options.asArchitecture(architecture);\n      }\n\n      /**\n       * @see RegisterImageBackedByEbsOptions#withDescription(String)\n       */\n      public static RegisterImageBackedByEbsOptions withDescription(String additionalInfo) {\n         RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions();\n         return options.withDescription(additionalInfo);\n      }\n\n      /**\n       * @see RegisterImageBackedByEbsOptions#withKernelId(String)\n       */\n      public static RegisterImageBackedByEbsOptions withKernelId(String kernelId) {\n         RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions();\n         return options.withKernelId(kernelId);\n      }\n\n      /**\n       * @see RegisterImageBackedByEbsOptions#withRamdisk(String)\n       */\n      public static RegisterImageBackedByEbsOptions withRamdisk(String ramdiskId) {\n         RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions();\n         return options.withRamdisk(ramdiskId);\n      }\n\n      /**\n       * @see RegisterImageBackedByEbsOptions#addBlockDeviceFromSnapshot(String, String, String)\n       */\n      public static RegisterImageBackedByEbsOptions addBlockDeviceFromSnapshot(String deviceName,\n               @Nullable String virtualName, String snapshotId) {\n         RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions();\n         return options.addBlockDeviceFromSnapshot(deviceName, virtualName, snapshotId);\n      }\n\n      /**\n       * @see RegisterImageBackedByEbsOptions#addBlockDeviceFromSnapshot(String, String, String, boolean, String, Integer, boolean)\n       */\n      public static RegisterImageBackedByEbsOptions addBlockDeviceFromSnapshot(String deviceName,\n                                                                               @Nullable String virtualName,\n                                                                               String snapshotId,\n                                                                               boolean deleteOnTermination,\n                                                                               @Nullable String volumeType,\n                                                                               @Nullable Integer iops,\n                                                                               boolean encrypted) {\n         RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions();\n         return options.addBlockDeviceFromSnapshot(deviceName, virtualName, snapshotId, deleteOnTermination,\n                 volumeType, iops, encrypted);\n      }\n\n      /**\n       * @see RegisterImageBackedByEbsOptions#addEphemeralBlockDeviceFromSnapshot(String, String,\n       *      String)\n       */\n      public static RegisterImageBackedByEbsOptions addEphemeralBlockDeviceFromSnapshot(\n               String deviceName, @Nullable String virtualName, String snapshotId) {\n         RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions();\n         return options.addEphemeralBlockDeviceFromSnapshot(deviceName, virtualName, snapshotId);\n      }\n\n      /**\n       * @see RegisterImageBackedByEbsOptions#addNewBlockDevice(String, String, int)\n       */\n      public static RegisterImageBackedByEbsOptions addNewBlockDevice(String deviceName,\n               @Nullable String virtualName, int volumeSize) {\n         RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions();\n         return options.addNewBlockDevice(deviceName, virtualName, volumeSize);\n      }\n\n      /**\n       * @see RegisterImageBackedByEbsOptions#addNewBlockDevice(String, String, int, boolean, String, Integer, boolean)\n       */\n      public static RegisterImageBackedByEbsOptions addNewBlockDevice(String deviceName,\n                                                               @Nullable String virtualName,\n                                                               int volumeSize,\n                                                               boolean deleteOnTermination,\n                                                               @Nullable String volumeType,\n                                                               @Nullable Integer iops,\n                                                               boolean encrypted) {\n         RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions();\n         return options.addNewBlockDevice(deviceName, virtualName, volumeSize, deleteOnTermination,\n                 volumeType, iops, encrypted);\n      }\n\n      /**\n       * @see RegisterImageBackedByEbsOptions#addNewEphemeralBlockDevice(String, String, int)\n       */\n      public static RegisterImageBackedByEbsOptions addNewEphemeralBlockDevice(String deviceName,\n               @Nullable String virtualName, int volumeSize) {\n         RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions();\n         return options.addNewEphemeralBlockDevice(deviceName, virtualName, volumeSize);\n      }\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public RegisterImageBackedByEbsOptions asArchitecture(Architecture architecture) {\n      return (RegisterImageBackedByEbsOptions) super.asArchitecture(architecture);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public RegisterImageBackedByEbsOptions withDescription(String info) {\n      return (RegisterImageBackedByEbsOptions) super.withDescription(info);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public RegisterImageBackedByEbsOptions withKernelId(String kernelId) {\n      return (RegisterImageBackedByEbsOptions) super.withKernelId(kernelId);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public RegisterImageBackedByEbsOptions withRamdisk(String ramDiskId) {\n      return (RegisterImageBackedByEbsOptions) super.withRamdisk(ramDiskId);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/options/RegisterImageOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.ec2.domain.Image.Architecture;\nimport org.jclouds.ec2.options.internal.BaseEC2RequestOptions;\n\n/**\n * Contains options supported in the Form API for the RegisterImage operation. <h2>\n * Usage</h2> The recommended way to instantiate a RegisterImageOptions object is to statically\n * import RegisterImageOptions.Builder.* and invoke a static creation method followed by an instance\n * mutator (if needed):\n * <p/>\n * <code>\n * import static org.jclouds.ec2.options.RegisterImageOptions.Builder.*\n * <p/>\n * EC2Api connection = // get connection\n * String imageId = connection.getImageServices().registerImageFromManifest(...withArchitecture(Architecture.I386).withDescription(\"description\"));\n * <code>\n * \n * @see <a\n *      href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-form-RegisterImage.html\"\n *      />\n */\npublic class RegisterImageOptions extends BaseEC2RequestOptions {\n\n   /**\n    * The architecture of the image.\n    */\n   public RegisterImageOptions asArchitecture(Architecture architecture) {\n      formParameters.put(\"Architecture\", checkNotNull(architecture, \"architecture\").value());\n      return this;\n   }\n\n   String getArchitecture() {\n      return getFirstFormOrNull(\"Architecture\");\n   }\n\n   /**\n    *The description of the AMI. \"Up to 255 characters.\"\n    */\n   public RegisterImageOptions withDescription(String info) {\n      formParameters.put(\"Description\", checkNotNull(info, \"info\"));\n      return this;\n   }\n\n   String getDescription() {\n      return getFirstFormOrNull(\"Description\");\n   }\n\n   /**\n    * The ID of the kernel to select.\n    */\n   public RegisterImageOptions withKernelId(String kernelId) {\n      formParameters.put(\"KernelId\", checkNotNull(kernelId, \"kernelId\"));\n      return this;\n   }\n\n   String getKernelId() {\n      return getFirstFormOrNull(\"KernelId\");\n   }\n\n   /**\n    * The ID of the RAM disk to select. Some kernels require additional drivers at launch. Check the\n    * kernel requirements for information on whether you need to specify a RAM disk. To find kernel\n    * requirements, refer to the Resource Center and search for the kernel ID.\n    */\n   public RegisterImageOptions withRamdisk(String ramDiskId) {\n      formParameters.put(\"RamdiskId\", checkNotNull(ramDiskId, \"ramDiskId\"));\n      return this;\n   }\n\n   String getRamdiskId() {\n      return getFirstFormOrNull(\"RamdiskId\");\n   }\n\n   public static class Builder {\n      /**\n       * @see RegisterImageOptions#asArchitecture(Architecture)\n       */\n      public static RegisterImageOptions asArchitecture(Architecture architecture) {\n         RegisterImageOptions options = new RegisterImageOptions();\n         return options.asArchitecture(architecture);\n      }\n\n      /**\n       * @see RegisterImageOptions#withDescription(String)\n       */\n      public static RegisterImageOptions withDescription(String additionalInfo) {\n         RegisterImageOptions options = new RegisterImageOptions();\n         return options.withDescription(additionalInfo);\n      }\n\n      /**\n       * @see RegisterImageOptions#withKernelId(String)\n       */\n      public static RegisterImageOptions withKernelId(String kernelId) {\n         RegisterImageOptions options = new RegisterImageOptions();\n         return options.withKernelId(kernelId);\n      }\n\n      /**\n       * @see RegisterImageOptions#withRamdisk(String)\n       */\n      public static RegisterImageOptions withRamdisk(String ramdiskId) {\n         RegisterImageOptions options = new RegisterImageOptions();\n         return options.withRamdisk(ramdiskId);\n      }\n\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/options/RunInstancesOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.options;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.io.BaseEncoding.base64;\n\nimport java.util.Set;\n\nimport org.jclouds.ec2.domain.BlockDeviceMapping;\nimport org.jclouds.ec2.options.internal.BaseEC2RequestOptions;\n\n/**\n * Contains options supported in the Form API for the RunInstances operation. <h2>\n * Usage</h2> The recommended way to instantiate a RunInstancesOptions object is to statically\n * import RunInstancesOptions.Builder.* and invoke a static creation method followed by an instance\n * mutator (if needed):\n * <p/>\n * <code>\n * import static org.jclouds.aws.ec2.options.RunInstancesOptions.Builder.*\n * <p/>\n * EC2Api connection = // get connection\n * Future<ReservationInfo> instances = connection.runInstances(executableBy(\"123125\").imageIds(1000, 1004));\n * <code>\n * \n * @see <a href=\n *      \"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-form-RunInstances.html\"\n *      />\n */\npublic class RunInstancesOptions extends BaseEC2RequestOptions {\n   public static final RunInstancesOptions NONE = new RunInstancesOptions();\n\n   /**\n    * The name of the key pair.\n    */\n   public RunInstancesOptions withKeyName(String keyName) {\n      formParameters.put(\"KeyName\", checkNotNull(keyName, \"keyName\"));\n      return this;\n   }\n\n   /**\n    * Attach multiple security groups\n    */\n   public RunInstancesOptions withSecurityGroups(String... securityGroups) {\n      indexFormValuesWithPrefix(\"SecurityGroup\", securityGroups);\n      return this;\n   }\n\n   /**\n    * Attach multiple security groups\n    */\n   public RunInstancesOptions withSecurityGroups(Iterable<String> securityGroups) {\n      indexFormValuesWithPrefix(\"SecurityGroup\", securityGroups);\n      return this;\n   }\n\n   /**\n    * Attaches a single security group. Multiple calls to this method won't add more groups.\n    * \n    * @param securityGroup\n    *           name of an existing security group\n    */\n   public RunInstancesOptions withSecurityGroup(String securityGroup) {\n      return withSecurityGroups(securityGroup);\n   }\n\n   /**\n    * Unencoded data\n    */\n   public RunInstancesOptions withUserData(byte[] unencodedData) {\n      int length = checkNotNull(unencodedData, \"unencodedData\").length;\n      checkArgument(length > 0, \"userData cannot be empty\");\n      checkArgument(length <= 16 * 1024, \"userData cannot be larger than 16kb\");\n      formParameters.put(\"UserData\", base64().encode(unencodedData));\n      return this;\n   }\n\n   /**\n    * Specifies the instance type. default small;\n    */\n   public RunInstancesOptions asType(String type) {\n      formParameters.put(\"InstanceType\", checkNotNull(type, \"type\"));\n      return this;\n   }\n\n   /**\n    * The ID of the kernel with which to launch the instance.\n    */\n   public RunInstancesOptions withKernelId(String kernelId) {\n      formParameters.put(\"KernelId\", checkNotNull(kernelId, \"kernelId\"));\n      return this;\n   }\n\n   /**\n    * The ID of the RAM disk with which to launch the instance. Some kernels require additional\n    * drivers at launch. Check the kernel requirements for information on whether you need to\n    * specify a RAM disk. To find kernel requirements, go to the Resource Center and search for the\n    * kernel ID.\n    */\n   public RunInstancesOptions withRamdisk(String ramDiskId) {\n      formParameters.put(\"RamdiskId\", checkNotNull(ramDiskId, \"ramDiskId\"));\n      return this;\n   }\n\n   /**\n    * Specifies the Block Device Mapping for the instance\n    * \n    */\n   public RunInstancesOptions withBlockDeviceMappings(Set<? extends BlockDeviceMapping> mappings) {\n      int i = 1;\n      for (BlockDeviceMapping mapping : checkNotNull(mappings, \"mappings\")) {\n         checkNotNull(mapping.getDeviceName(), \"deviceName\");\n         formParameters.put(String.format(\"BlockDeviceMapping.%d.DeviceName\", i), mapping.getDeviceName());\n         if (mapping.getVirtualName() != null)\n            formParameters.put(String.format(\"BlockDeviceMapping.%d.VirtualName\", i), mapping.getVirtualName());\n         if (mapping.getEbsSnapshotId() != null)\n            formParameters.put(String.format(\"BlockDeviceMapping.%d.Ebs.SnapshotId\", i), mapping.getEbsSnapshotId());\n         if (mapping.getEbsVolumeSize() != null)\n            formParameters.put(String.format(\"BlockDeviceMapping.%d.Ebs.VolumeSize\", i),\n                  String.valueOf(mapping.getEbsVolumeSize()));\n         if (mapping.getEbsNoDevice() != null)\n            formParameters.put(String.format(\"BlockDeviceMapping.%d.Ebs.NoDevice\", i),\n                  String.valueOf(mapping.getEbsNoDevice()));\n         if (mapping.getEbsDeleteOnTermination() != null)\n            formParameters.put(String.format(\"BlockDeviceMapping.%d.Ebs.DeleteOnTermination\", i),\n                  String.valueOf(mapping.getEbsDeleteOnTermination()));\n         if (mapping.getEbsVolumeType() != null)\n            formParameters.put(String.format(\"BlockDeviceMapping.%d.Ebs.VolumeType\", i), mapping.getEbsVolumeType());\n         if (mapping.getEbsIops() != null)\n            formParameters.put(String.format(\"BlockDeviceMapping.%d.Ebs.Iops\", i),\n                    String.valueOf(mapping.getEbsIops()));\n         if (mapping.getEbsEncrypted() != null && mapping.getEbsEncrypted())\n            formParameters.put(String.format(\"BlockDeviceMapping.%d.Ebs.Encrypted\", i), String.valueOf(mapping.getEbsEncrypted()));\n         i++;\n      }\n      return this;\n   }\n\n   /**\n    * Specifies the optional ClientToken field, which triggers idempotent RunInstances calls.\n    * See <a href=\"http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Run_Instance_Idempotency.html\">here</a> for more details.\n    */\n   public RunInstancesOptions withClientToken(String clientToken) {\n      formParameters.put(\"ClientToken\", checkNotNull(clientToken, \"clientToken\"));\n      return this;\n   }\n\n   public static class Builder {\n      /**\n       * @see RunInstancesOptions#withKeyName(String)\n       */\n      public static RunInstancesOptions withKeyName(String keyName) {\n         RunInstancesOptions options = new RunInstancesOptions();\n         return options.withKeyName(keyName);\n      }\n\n      /**\n       * @see RunInstancesOptions#withSecurityGroup(String)\n       */\n      public static RunInstancesOptions withSecurityGroup(String securityGroup) {\n         RunInstancesOptions options = new RunInstancesOptions();\n         return options.withSecurityGroup(securityGroup);\n      }\n\n      /**\n       * @see RunInstancesOptions#withUserData(byte [])\n       */\n      public static RunInstancesOptions withUserData(byte[] unencodedData) {\n         RunInstancesOptions options = new RunInstancesOptions();\n         return options.withUserData(unencodedData);\n      }\n\n      /**\n       * @see RunInstancesOptions#asType(String)\n       */\n      public static RunInstancesOptions asType(String instanceType) {\n         RunInstancesOptions options = new RunInstancesOptions();\n         return options.asType(instanceType);\n      }\n\n      /**\n       * @see RunInstancesOptions#withKernelId(String)\n       */\n      public static RunInstancesOptions withKernelId(String kernelId) {\n         RunInstancesOptions options = new RunInstancesOptions();\n         return options.withKernelId(kernelId);\n      }\n\n      /**\n       * @see RunInstancesOptions#withRamdisk(String)\n       */\n      public static RunInstancesOptions withRamdisk(String ramdiskId) {\n         RunInstancesOptions options = new RunInstancesOptions();\n         return options.withRamdisk(ramdiskId);\n      }\n\n      /**\n       * @see RunInstancesOptions#withBlockDeviceMappings(Set<BlockDeviceMapping> mappings)\n       */\n      public static RunInstancesOptions withBlockDeviceMappings(Set<? extends BlockDeviceMapping> mappings) {\n         RunInstancesOptions options = new RunInstancesOptions();\n         return options.withBlockDeviceMappings(mappings);\n      }\n\n      /**\n       * @see RunInstancesOptions#withClientToken(String)\n       */\n      public static RunInstancesOptions withClientToken(String clientToken) {\n         RunInstancesOptions options = new RunInstancesOptions();\n         return options.withClientToken(clientToken);\n      }\n\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/options/internal/BaseEC2RequestOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.options.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Set;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\nimport org.jclouds.util.Predicates2;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\nimport com.google.common.collect.Iterables;\n\npublic class BaseEC2RequestOptions extends BaseHttpRequestOptions {\n\n   @Override\n   public String toString() {\n      return \"[formParameters=\" + formParameters + \"]\";\n   }\n\n   protected void indexFormValuesWithPrefix(String prefix, String... values) {\n      for (int i = 0; i < values.length; i++) {\n         formParameters.put(prefix + \".\" + (i + 1), checkNotNull(values[i], prefix.toLowerCase() + \"s[\" + i + \"]\"));\n      }\n   }\n\n   protected void indexFormValuesWithPrefix(String prefix, Iterable<String> values) {\n      indexFormValuesWithPrefix(prefix, Iterables.toArray(values, String.class));\n   }\n\n   protected Set<String> getFormValuesWithKeysPrefixedBy(final String prefix) {\n      Builder<String> values = ImmutableSet.builder();\n      for (String key : Iterables.filter(formParameters.keySet(), Predicates2.startsWith(prefix))) {\n         values.add(Iterables.get(formParameters.get(key), 0));\n      }\n      return values.build();\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/predicates/InstanceHasIpAddress.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.predicates;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.AWSResponseException;\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.domain.Reservation;\nimport org.jclouds.ec2.domain.RunningInstance;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Iterables;\nimport com.google.inject.Inject;\n\n/**\n * \n * Tests to see if a task succeeds.\n */\n@Singleton\npublic class InstanceHasIpAddress implements Predicate<RunningInstance> {\n\n   private final EC2Api client;\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   @Inject\n   public InstanceHasIpAddress(EC2Api client) {\n      this.client = client;\n   }\n\n   public boolean apply(RunningInstance instance) {\n      logger.trace(\"looking for ipAddress on instance %s\", instance);\n      try {\n         instance = refresh(instance);\n         return instance.getIpAddress() != null;\n      } catch (AWSResponseException e) {\n         if (e.getError().getCode().equals(\"InvalidInstanceID.NotFound\"))\n            return false;\n         throw e;\n      }\n   }\n\n   private RunningInstance refresh(RunningInstance instance) {\n      Reservation<? extends RunningInstance> reservation = Iterables.getOnlyElement(client.getInstanceApi().get()\n               .describeInstancesInRegion(instance.getRegion(), instance.getId()));\n      return Iterables.getOnlyElement(reservation);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/predicates/InstanceStateRunning.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.predicates;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.domain.InstanceState;\nimport org.jclouds.ec2.domain.Reservation;\nimport org.jclouds.ec2.domain.RunningInstance;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.rest.ResourceNotFoundException;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Iterables;\nimport com.google.inject.Inject;\n\n/**\n * \n * Tests to see if a task succeeds.\n */\n@Singleton\npublic class InstanceStateRunning implements Predicate<RunningInstance> {\n\n   private final EC2Api client;\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   @Inject\n   public InstanceStateRunning(EC2Api client) {\n      this.client = client;\n   }\n\n   public boolean apply(RunningInstance instance) {\n      logger.trace(\"looking for state on instance %s\", instance);\n      try {\n         instance = refresh(instance);\n         logger.trace(\"%s: looking for instance state %s: currently: %s\",\n               instance.getId(), InstanceState.RUNNING, instance\n                     .getInstanceState());\n         return instance.getInstanceState() == InstanceState.RUNNING;\n      } catch (ResourceNotFoundException e) {\n         return false;\n      }\n   }\n\n   private RunningInstance refresh(RunningInstance instance) {\n      Reservation<? extends RunningInstance> reservation = Iterables.getOnlyElement(client\n            .getInstanceApi().get().describeInstancesInRegion(\n                  instance.getRegion(), instance.getId()));\n      return Iterables.getOnlyElement(reservation);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/predicates/InstanceStateStopped.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.predicates;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.ec2.domain.InstanceState;\nimport org.jclouds.ec2.domain.Reservation;\nimport org.jclouds.ec2.domain.RunningInstance;\nimport org.jclouds.ec2.features.InstanceApi;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Iterables;\nimport com.google.inject.Inject;\n\n/**\n * \n * Tests to see if a task succeeds.\n */\n@Singleton\npublic class InstanceStateStopped implements Predicate<RunningInstance> {\n\n   private final InstanceApi client;\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   @Inject\n   public InstanceStateStopped(InstanceApi client) {\n      this.client = client;\n   }\n\n   public boolean apply(RunningInstance instance) {\n      logger.trace(\"looking for state on instance %s\", instance);\n      instance = refresh(instance);\n      logger.trace(\"%s: looking for instance state %s: currently: %s\", instance.getId(),\n               InstanceState.STOPPED, instance.getInstanceState());\n      return instance.getInstanceState() == InstanceState.STOPPED;\n   }\n\n   private RunningInstance refresh(RunningInstance instance) {\n      Reservation<? extends RunningInstance> reservation = Iterables.getOnlyElement(client.describeInstancesInRegion(\n               instance.getRegion(), instance.getId()));\n      return Iterables.getOnlyElement(reservation);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/predicates/InstanceStateTerminated.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.predicates;\n\nimport java.util.NoSuchElementException;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.domain.InstanceState;\nimport org.jclouds.ec2.domain.Reservation;\nimport org.jclouds.ec2.domain.RunningInstance;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Iterables;\nimport com.google.inject.Inject;\n\n/**\n * \n * Tests to see if a task succeeds.\n */\n@Singleton\npublic class InstanceStateTerminated implements Predicate<RunningInstance> {\n\n   private final EC2Api client;\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   @Inject\n   public InstanceStateTerminated(EC2Api client) {\n      this.client = client;\n   }\n\n   public boolean apply(RunningInstance instance) {\n      logger.trace(\"looking for state on instance %s\", instance);\n      try {\n         instance = refresh(instance);\n      } catch (NoSuchElementException e) {\n         return true;\n      }\n      logger.trace(\"%s: looking for instance state %s: currently: %s\", instance.getId(),\n               InstanceState.TERMINATED, instance.getInstanceState());\n      return instance.getInstanceState() == InstanceState.TERMINATED;\n   }\n\n   private RunningInstance refresh(RunningInstance instance) {\n      Reservation<? extends RunningInstance> reservation = Iterables.getOnlyElement(client.getInstanceApi().get()\n               .describeInstancesInRegion(instance.getRegion(), instance.getId()));\n      return Iterables.getOnlyElement(reservation);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/predicates/SnapshotCompleted.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.predicates;\n\nimport static org.jclouds.ec2.options.DescribeSnapshotsOptions.Builder.snapshotIds;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.ec2.domain.Snapshot;\nimport org.jclouds.ec2.features.ElasticBlockStoreApi;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Iterables;\nimport com.google.inject.Inject;\n\n/**\n * \n * Tests to see if a snapshot is completed.\n */\n@Singleton\npublic class SnapshotCompleted implements Predicate<Snapshot> {\n\n   private final ElasticBlockStoreApi client;\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   @Inject\n   public SnapshotCompleted(ElasticBlockStoreApi client) {\n      this.client = client;\n   }\n\n   public boolean apply(Snapshot snapshot) {\n      logger.trace(\"looking for status on snapshot %s\", snapshot.getId());\n\n      snapshot = Iterables.getOnlyElement(client.describeSnapshotsInRegion(snapshot.getRegion(),\n               snapshotIds(snapshot.getId())));\n      logger.trace(\"%s: looking for status %s: currently: %s; progress %d/100\", snapshot,\n               Snapshot.Status.COMPLETED, snapshot.getStatus(), snapshot.getProgress());\n      return snapshot.getStatus() == Snapshot.Status.COMPLETED;\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/predicates/VolumeAttached.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.predicates;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.ec2.domain.Attachment;\nimport org.jclouds.ec2.domain.Volume;\nimport org.jclouds.ec2.features.ElasticBlockStoreApi;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Sets;\nimport com.google.inject.Inject;\n\n/**\n *\n * Tests to see if a volume is attached.\n */\n@Singleton\npublic class VolumeAttached implements Predicate<Attachment> {\n\n   private final ElasticBlockStoreApi client;\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   @Inject\n   public VolumeAttached(ElasticBlockStoreApi client) {\n      this.client = client;\n   }\n\n   public boolean apply(Attachment attachment) {\n      logger.trace(\"looking for volume %s\", attachment.getVolumeId());\n      Volume volume = Iterables.getOnlyElement(client.describeVolumesInRegion(attachment\n               .getRegion(), attachment.getVolumeId()));\n      if (volume.getAttachments().isEmpty()) {\n         return false;\n      }\n      Attachment lastAttachment = Sets.newTreeSet(volume.getAttachments()).last();\n      logger.trace(\"%s: looking for status %s: currently: %s\", lastAttachment,\n               Attachment.Status.ATTACHED, lastAttachment.getStatus());\n      return lastAttachment.getStatus() == Attachment.Status.ATTACHED;\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/predicates/VolumeAvailable.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.predicates;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.ec2.domain.Volume;\nimport org.jclouds.ec2.features.ElasticBlockStoreApi;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Iterables;\nimport com.google.inject.Inject;\n\n/**\n * \n * Tests to see if a volume is completed.\n */\n@Singleton\npublic class VolumeAvailable implements Predicate<Volume> {\n\n   private final ElasticBlockStoreApi client;\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   @Inject\n   public VolumeAvailable(ElasticBlockStoreApi client) {\n      this.client = client;\n   }\n\n   public boolean apply(Volume volume) {\n      logger.trace(\"looking for status on volume %s\", volume.getId());\n      volume = Iterables.getOnlyElement(client.describeVolumesInRegion(volume.getRegion(), volume\n               .getId()));\n      logger.trace(\"%s: looking for status %s: currently: %s\", volume, Volume.Status.AVAILABLE,\n               volume.getStatus());\n      return volume.getStatus() == Volume.Status.AVAILABLE;\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/predicates/VolumeDetached.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.predicates;\n\nimport static com.google.common.collect.Iterables.getLast;\n\nimport jakarta.annotation.Resource;\n\nimport org.jclouds.ec2.domain.Attachment;\nimport org.jclouds.ec2.domain.Volume;\nimport org.jclouds.ec2.features.ElasticBlockStoreApi;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Iterables;\nimport com.google.inject.Inject;\nimport com.google.inject.Singleton;\n\n/**\n * Tests to see if a volume is detached.\n */\n@Singleton\npublic class VolumeDetached implements Predicate<Attachment> {\n\n   private final ElasticBlockStoreApi client;\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   @Inject\n   public VolumeDetached(ElasticBlockStoreApi client) {\n      this.client = client;\n   }\n\n   public boolean apply(Attachment attachment) {\n      logger.trace(\"looking for volume %s\", attachment.getVolumeId());\n      Volume volume = Iterables.getOnlyElement(client.describeVolumesInRegion(attachment\n              .getRegion(), attachment.getVolumeId()));\n\n      /*If attachment size is 0 volume is detached for sure.*/\n      if (volume.getAttachments().isEmpty()) {\n         return true;\n      }\n\n      /* But if attachment size is > 0, then the attachment could be in any state.\n         * So we need to check if the status is DETACHED (return true) or not (return false).\n         */\n      Attachment lastAttachment = getLast(volume.getAttachments());\n      logger.trace(\"%s: looking for status %s: currently: %s\", lastAttachment,\n              Attachment.Status.DETACHED, lastAttachment.getStatus());\n      return lastAttachment.getStatus() == Attachment.Status.DETACHED;\n   }\n}\n\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/reference/EC2Constants.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.reference;\n\n\n/**\n * Configuration properties and constants used in EC2 connections.\n */\npublic class EC2Constants {\n   /**\n    * Listing the universe of amis is extremely expensive. set this to a comma separated value of\n    * the ami owners you wish to use in {@link ComputeService}\n    */\n   public static final String PROPERTY_EC2_AMI_OWNERS = \"jclouds.ec2.ami-owners\";\n\n   /**\n    * Eventual consistency delay for retrieving a security group after it is created (in ms)\n    */\n   public static final String PROPERTY_EC2_TIMEOUT_SECURITYGROUP_PRESENT = \"jclouds.ec2.timeout.securitygroup-present\";\n\n   /**\n    * Whenever a node is created, automatically allocate and assign an elastic ip address, also\n    * deallocate when the node is destroyed.\n    */\n   public static final String PROPERTY_EC2_AUTO_ALLOCATE_ELASTIC_IPS = \"jclouds.ec2.auto-allocate-elastic-ips\";\n   \n   /**\n    * If this property is set to true(default), jclouds generate a name for each instance based on the group. ex.\n    * i-ef34ae2 becomes hadoop-ef34ae2. Note that this depends on {@link EC2Api#getTagApi} returning present.\n    */\n   public static final String PROPERTY_EC2_GENERATE_INSTANCE_NAMES = \"jclouds.ec2.generate-instance-names\";\n\n   protected EC2Constants() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/suppliers/DescribeAvailabilityZonesInRegion.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.suppliers;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.domain.AvailabilityZoneInfo;\nimport org.jclouds.ec2.features.AvailabilityZoneAndRegionApi;\nimport org.jclouds.location.Region;\nimport org.jclouds.location.suppliers.RegionIdToZoneIdsSupplier;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMap.Builder;\nimport com.google.common.collect.ImmutableSet;\n\npublic final class DescribeAvailabilityZonesInRegion implements RegionIdToZoneIdsSupplier {\n   private final EC2Api api;\n   private final Supplier<Set<String>> regions;\n\n   @Inject\n   DescribeAvailabilityZonesInRegion(EC2Api api, @Region Supplier<Set<String>> regions) {\n      this.api = api;\n      this.regions = regions;\n   }\n\n   @Override\n   public Map<String, Supplier<Set<String>>> get() {\n      AvailabilityZoneAndRegionApi zoneApi = api.getAvailabilityZoneAndRegionApi().get();\n      Builder<String, Supplier<Set<String>>> map = ImmutableMap.builder();\n      for (String region : regions.get()) {\n         ImmutableSet.Builder<String> zoneBuilder = ImmutableSet.builder();\n         for (AvailabilityZoneInfo zone : zoneApi.describeAvailabilityZonesInRegion(region)) {\n            zoneBuilder.add(zone.getZone());\n         }\n         map.put(region, Suppliers.<Set<String>>ofInstance(zoneBuilder.build()));\n      }\n      return map.build();\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/suppliers/DescribeRegionsForRegionURIs.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.suppliers;\n\nimport java.net.URI;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.location.suppliers.RegionIdToURISupplier;\nimport org.jclouds.location.suppliers.fromconfig.RegionIdsFromConfiguration;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Uses the {@code DescribeRegions} call to return the regions endpoints, subject to any whitelist present in the\n * property {@link org.jclouds.location.reference.LocationConstants#PROPERTY_REGIONS}.\n */\npublic final class DescribeRegionsForRegionURIs implements RegionIdToURISupplier {\n   private final EC2Api api;\n   private final Set<String> whitelistedRegionIds;\n\n   @Inject DescribeRegionsForRegionURIs(EC2Api api, RegionIdsFromConfiguration regionIdsFromConfiguration) {\n      this.api = api;\n      this.whitelistedRegionIds = regionIdsFromConfiguration.get();\n   }\n\n   @Override\n   public Map<String, Supplier<URI>> get() {\n      ImmutableMap.Builder<String, Supplier<URI>> result = ImmutableMap.builder();\n      for (Entry<String, URI> regionUrl : api.getAvailabilityZoneAndRegionApi().get().describeRegions().entrySet()) {\n         if (whitelistedRegionIds.isEmpty() || whitelistedRegionIds.contains(regionUrl.getKey())) {\n            result.put(regionUrl.getKey(), Suppliers.ofInstance(regionUrl.getValue()));\n         }\n      }\n      return result.build();\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/util/IpPermissions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.util;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\nimport java.util.Map.Entry;\n\nimport org.jclouds.net.domain.IpPermission;\nimport org.jclouds.net.domain.IpProtocol;\nimport org.jclouds.util.Maps2;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Maps;\nimport com.google.common.collect.Multimap;\nimport com.google.common.collect.Multimaps;\n\n/**\n *\n * Shortcut to create ingress rules\n */\npublic class IpPermissions extends IpPermission {\n\n   protected IpPermissions(IpProtocol ipProtocol, int fromPort, int toPort,\n         Multimap<String, String> userIdGroupPairs, Iterable<String> groupIds, Iterable<String> ipRanges) {\n      super(ipProtocol, fromPort, toPort, userIdGroupPairs, groupIds, userIdGroupPairs.isEmpty() ? ipRanges\n            : ImmutableSet.<String> of(), ImmutableSet.<String> of());\n   }\n\n   /**\n    * don't rely on this being here.. it will move\n    */\n   @Beta\n   public static Multimap<String, String> buildFormParametersForIndex(final int index, IpPermission permission) {\n      Map<String, String> headers = Maps.newLinkedHashMap();\n      headers.put(\"IpPermissions.%d.IpProtocol\", permission.getIpProtocol().toString());\n      headers.put(\"IpPermissions.%d.FromPort\", permission.getFromPort() + \"\");\n      headers.put(\"IpPermissions.%d.ToPort\", permission.getToPort() + \"\");\n      String prefix = \"IpPermissions.%d.IpRanges.\";\n      int i = 0;\n      for (String cidrIp : checkNotNull(permission.getCidrBlocks(), \"cidrIps\")) {\n         headers.put(prefix + i++ + \".CidrIp\", cidrIp);\n      }\n      prefix = \"IpPermissions.%d.Groups.\";\n      i = 0;\n      for (String groupId : checkNotNull(permission.getGroupIds(), \"groupIds\")) {\n         headers.put(prefix + i++ + \".GroupId\", groupId);\n      }\n      prefix = \"IpPermissions.%d.Groups.\";\n      i = 0;\n      for (Entry<String, String> tenantIdGroupNamePair : checkNotNull(permission.getTenantIdGroupNamePairs(),\n            \"tenantIdGroupNamePairs\").entries()) {\n         headers.put(prefix + i + \".UserId\", tenantIdGroupNamePair.getKey());\n         headers.put(prefix + i + \".GroupId\", tenantIdGroupNamePair.getValue());\n         i++;\n      }\n      prefix = \"IpPermissions.%d.IpRanges.\";\n      i = 0;\n      for (String cidrIp : checkNotNull(permission.getCidrBlocks(), \"cidrIps\")) {\n         headers.put(prefix + i++ + \".CidrIp\", cidrIp);\n      }\n      return Multimaps.forMap(Maps2.transformKeys(headers, new Function<String, String>() {\n\n         @Override\n         public String apply(String arg0) {\n            return String.format(arg0, index);\n         }\n\n      }));\n   }\n\n   public static ICMPTypeSelection permitICMP() {\n      return new ICMPTypeSelection();\n   }\n\n   public static ToSourceSelection permitAnyProtocol() {\n      return new ToSourceSelection(IpProtocol.ALL, 1, 65535);\n   }\n\n   public static PortSelection permit(IpProtocol protocol) {\n      return new PortSelection(checkNotNull(protocol, \"protocol\"));\n   }\n\n   public static class ICMPTypeSelection extends ToSourceSelection {\n\n      ICMPTypeSelection() {\n         super(IpProtocol.ICMP, -1, -1);\n      }\n\n      /**\n       * @param type ex. 8 for ECHO (i.e. Ping)\n       * @see <a href=\"http://www.iana.org/assignments/icmp-parameters/icmp-parameters.xml\"> ICMP Types</a>\n       */\n      public AndCodeSelection type(int type) {\n         return new AndCodeSelection(type);\n      }\n   }\n\n   public static class AndCodeSelection extends ToSourceSelection {\n      AndCodeSelection(int type) {\n         super(IpProtocol.ICMP, type, -1);\n      }\n\n      public ToSourceSelection andCode(int code) {\n         return new ToSourceSelection(getIpProtocol(), getFromPort(), code);\n      }\n\n   }\n\n   public static class PortSelection extends ToSourceSelection {\n\n      PortSelection(IpProtocol ipProtocol) {\n         super(ipProtocol, ipProtocol == IpProtocol.ICMP ? -1 : 1, ipProtocol == IpProtocol.ICMP ? -1 : 65535);\n      }\n\n      public ToPortSelection fromPort(int port) {\n         return new ToPortSelection(getIpProtocol(), port);\n      }\n\n      public ToSourceSelection port(int port) {\n         return new ToSourceSelection(getIpProtocol(), port, port);\n      }\n   }\n\n   public static class ToPortSelection extends ToSourceSelection {\n\n      ToPortSelection(IpProtocol ipProtocol, int fromPort) {\n         super(ipProtocol, fromPort, ipProtocol == IpProtocol.ICMP ? -1 : 65535);\n      }\n\n      public ToSourceSelection to(int port) {\n         return new ToSourceSelection(getIpProtocol(), getFromPort(), port);\n      }\n   }\n\n   public static class ToVPCSourceSelection extends IpPermissions {\n\n      protected ToVPCSourceSelection(IpProtocol ipProtocol, int fromPort, int toPort) {\n         super(ipProtocol, fromPort, toPort, ImmutableMultimap.<String, String> of(), ImmutableSet.<String> of(),\n               ImmutableSet.of(\"0.0.0.0/0\"));\n      }\n\n      public IpPermissions originatingFromSecurityGroupId(String groupId) {\n         return toVPCSecurityGroups(ImmutableSet.of(checkNotNull(groupId, \"groupId\")));\n      }\n\n      public IpPermissions toVPCSecurityGroups(Iterable<String> groupIds) {\n         return new IpPermissions(getIpProtocol(), getFromPort(), getToPort(), getTenantIdGroupNamePairs(), groupIds,\n               ImmutableSet.<String> of());\n      }\n   }\n\n   public static class ToSourceSelection extends ToVPCSourceSelection {\n      ToSourceSelection(IpProtocol ipProtocol, int fromPort, int toPort) {\n         super(ipProtocol, fromPort, toPort);\n      }\n\n      public IpPermissions originatingFromCidrBlock(String cidrIp) {\n         return originatingFromCidrBlocks(ImmutableSet.of(checkNotNull(cidrIp, \"cidrIp\")));\n      }\n\n      public IpPermissions originatingFromCidrBlocks(Iterable<String> cidrIps) {\n         return new IpPermissions(getIpProtocol(), getFromPort(), getToPort(),\n               ImmutableMultimap.<String, String> of(), ImmutableSet.<String> of(), cidrIps);\n      }\n\n      public IpPermissions originatingFromUserAndSecurityGroup(String userId, String groupName) {\n         return toEC2SecurityGroups(ImmutableMultimap.of(checkNotNull(userId, \"userId\"),\n               checkNotNull(groupName, \"groupName\")));\n      }\n\n      public IpPermissions toEC2SecurityGroups(Multimap<String, String> tenantIdGroupNamePairs) {\n         return new IpPermissions(getIpProtocol(), getFromPort(), getToPort(), tenantIdGroupNamePairs, getGroupIds(),\n               ImmutableSet.<String> of());\n      }\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/util/SubnetFilterBuilder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.util;\n\nimport java.util.Comparator;\nimport java.util.Map.Entry;\n\nimport org.jclouds.ec2.domain.Subnet;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Multimap;\n\n/**\n * You can specify filters so that the response includes information for only\n * certain subnets. For example, you can use a filter to specify that you're\n * interested in the subnets in the available state. You can specify multiple\n * values for a filter. The response includes information for a subnet only if\n * it matches at least one of the filter values that you specified.\n *\n * You can specify multiple filters; for example, specify subnets that are in a\n * specific VPC and are in the available state. The response includes\n * information for a subnet only if it matches all the filters that you\n * specified. If there's no match, no special message is returned, the response\n * is simply empty.\n * \n * <h4>Wildcards</h4> You can use wildcards with the filter values: {@code *}\n * matches zero or more characters, and ? matches exactly one character. You can\n * escape special characters using a backslash before the character. For\n * example, a value of {@code \\*amazon\\?\\\\} searches for the literal string\n * {@code *amazon?\\}.\n * \n * @see SubnetApi\n */\npublic class SubnetFilterBuilder extends ImmutableMultimap.Builder<String, String> {\n\n    private static final String AVAILABILITY_ZONE = \"availability-zone\";\n    private static final String AVAILABLE_IP_ADDRESS_COUNT = \"available-ip-address-count\";\n    private static final String CIDR = \"cidr\";\n    private static final String STATE = \"state\";\n    private static final String SUBNET_ID = \"subnet-id\";\n    private static final String TAG_KEY = \"tag-key\";\n    private static final String TAG_VALUE = \"tag-value\";\n    private static final String TAG_ARBITRARY_BASE = \"tag:\";\n    private static final String VPC_ID = \"vpc-id\";\n\n    public SubnetFilterBuilder availabilityZone(String availabilityZone) {\n        return put(AVAILABILITY_ZONE, availabilityZone);\n    }\n\n    public SubnetFilterBuilder availabilityZones(String... availabilityZones) {\n        return putAll(AVAILABILITY_ZONE, availabilityZones);\n    }\n\n    public SubnetFilterBuilder availabilityZones(Iterable<String> availabilityZones) {\n        return putAll(AVAILABILITY_ZONE, availabilityZones);\n    }\n\n    public SubnetFilterBuilder anyAvailabilityZone() {\n        return putAll(AVAILABILITY_ZONE, ImmutableSet.<String> of());\n    }\n\n    public SubnetFilterBuilder availableIpAddressCount(String availableIpAddressCount) {\n        return put(AVAILABLE_IP_ADDRESS_COUNT, availableIpAddressCount);\n    }\n\n    public SubnetFilterBuilder availableIpAddressCounts(String... availableIpAddressCounts) {\n        return putAll(AVAILABLE_IP_ADDRESS_COUNT, availableIpAddressCounts);\n    }\n\n    public SubnetFilterBuilder availableIpAddressCounts(Iterable<String> availableIpAddressCounts) {\n        return putAll(AVAILABLE_IP_ADDRESS_COUNT, availableIpAddressCounts);\n    }\n\n    public SubnetFilterBuilder anyAvailableIpAddressCount() {\n        return putAll(AVAILABLE_IP_ADDRESS_COUNT, ImmutableSet.<String> of());\n    }\n\n    public SubnetFilterBuilder cidr(String cidr) {\n        return put(CIDR, cidr);\n    }\n\n    public SubnetFilterBuilder cidrs(String... cidrs) {\n        return putAll(CIDR, cidrs);\n    }\n\n    public SubnetFilterBuilder cidrs(Iterable<String> cidrs) {\n        return putAll(CIDR, cidrs);\n    }\n\n    public SubnetFilterBuilder anyCidr() {\n        return putAll(CIDR, ImmutableSet.<String> of());\n    }\n\n    public SubnetFilterBuilder state(String state) {\n        return put(STATE, state);\n    }\n\n    public SubnetFilterBuilder states(String... states) {\n        return putAll(STATE, states);\n    }\n\n    public SubnetFilterBuilder states(Iterable<String> states) {\n        return putAll(STATE, states);\n    }\n\n    public SubnetFilterBuilder anyState() {\n        return putAll(STATE, ImmutableSet.<String> of());\n    }\n\n    public SubnetFilterBuilder available() {\n        return put(STATE, Subnet.State.AVAILABLE.value());\n    }\n\n    public SubnetFilterBuilder pending() {\n        return put(STATE, Subnet.State.PENDING.value());\n    }\n\n    public SubnetFilterBuilder subnetId(String subnetId) {\n        return put(SUBNET_ID, subnetId);\n    }\n\n    public SubnetFilterBuilder subnetIds(String... subnetIds) {\n        return putAll(SUBNET_ID, subnetIds);\n    }\n\n    public SubnetFilterBuilder subnetIds(Iterable<String> subnetIds) {\n        return putAll(SUBNET_ID, subnetIds);\n    }\n\n    public SubnetFilterBuilder anySubnetId() {\n        return putAll(SUBNET_ID, ImmutableSet.<String> of());\n    }\n\n    public SubnetFilterBuilder tagKey(String tagKey) {\n        return put(TAG_KEY, tagKey);\n    }\n\n    public SubnetFilterBuilder tagKeys(String... tagKeys) {\n        return putAll(TAG_KEY, tagKeys);\n    }\n\n    public SubnetFilterBuilder tagKeys(Iterable<String> tagKeys) {\n        return putAll(TAG_KEY, tagKeys);\n    }\n\n    public SubnetFilterBuilder anyTagKey() {\n        return putAll(TAG_KEY, ImmutableSet.<String> of());\n    }\n\n    public SubnetFilterBuilder tagValue(String tagValue) {\n        return put(TAG_VALUE, tagValue);\n    }\n\n    public SubnetFilterBuilder tagValues(String... tagValues) {\n        return putAll(TAG_VALUE, tagValues);\n    }\n\n    public SubnetFilterBuilder tagValues(Iterable<String> tagValues) {\n        return putAll(TAG_VALUE, tagValues);\n    }\n\n    public SubnetFilterBuilder anyTagValue() {\n        return putAll(TAG_VALUE, ImmutableSet.<String> of());\n    }\n\n    public SubnetFilterBuilder vpcId(String vpcId) {\n        return put(VPC_ID, vpcId);\n    }\n\n    public SubnetFilterBuilder vpcIds(String... vpcIds) {\n        return putAll(VPC_ID, vpcIds);\n    }\n\n    public SubnetFilterBuilder vpcIds(Iterable<String> vpcIds) {\n        return putAll(VPC_ID, vpcIds);\n    }\n\n    public SubnetFilterBuilder anyVpcId() {\n        return putAll(VPC_ID, ImmutableSet.<String> of());\n    }\n\n    public SubnetFilterBuilder arbitraryTag(String arbitraryTagKey, String arbitraryTagValue) {\n        return put(TAG_ARBITRARY_BASE + arbitraryTagKey, arbitraryTagValue);\n    }\n\n    public SubnetFilterBuilder arbitraryTag(String arbitraryTagKey, String... arbitraryTagValues) {\n        return putAll(TAG_ARBITRARY_BASE + arbitraryTagKey, arbitraryTagValues);\n    }\n\n    public SubnetFilterBuilder arbitraryTag(String arbitraryTagKey, Iterable<String> arbitraryTagValues) {\n        return putAll(TAG_ARBITRARY_BASE + arbitraryTagKey, arbitraryTagValues);\n    }\n\n\n    // to set correct return val in chain\n\n    @Override\n    public SubnetFilterBuilder put(String key, String value) {\n        return SubnetFilterBuilder.class.cast(super.put(key, value));\n    }\n\n    @Override\n    public SubnetFilterBuilder put(Entry<? extends String, ? extends String> entry) {\n        return SubnetFilterBuilder.class.cast(super.put(entry));\n    }\n\n    @Override\n    public SubnetFilterBuilder putAll(String key, Iterable<? extends String> values) {\n        return SubnetFilterBuilder.class.cast(super.putAll(key, values));\n    }\n\n    @Override\n    public SubnetFilterBuilder putAll(String key, String... values) {\n        return SubnetFilterBuilder.class.cast(super.putAll(key, values));\n    }\n\n    @Override\n    public SubnetFilterBuilder putAll(Multimap<? extends String, ? extends String> multimap) {\n        return SubnetFilterBuilder.class.cast(super.putAll(multimap));\n    }\n\n    @Override\n    @Beta\n    public SubnetFilterBuilder orderKeysBy(Comparator<? super String> keyComparator) {\n        return SubnetFilterBuilder.class.cast(super.orderKeysBy(keyComparator));\n    }\n\n    @Override\n    @Beta\n    public SubnetFilterBuilder orderValuesBy(Comparator<? super String> valueComparator) {\n        return SubnetFilterBuilder.class.cast(super.orderValuesBy(valueComparator));\n    }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/util/TagFilterBuilder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.util;\n\nimport java.util.Comparator;\nimport java.util.Map.Entry;\n\nimport org.jclouds.ec2.domain.Tag;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Multimap;\n\n/**\n * You can use filters to limit the results when describing tags. For example,\n * you could get only the tags for a particular resource type. You can specify\n * multiple values for a filter. A tag must match at least one of the specified\n * values for it to be included in the results.\n * \n * You can specify multiple filters (for example, limit the results to a\n * specific resource type, and get only tags with values that contain the string\n * database). The result includes information for a particular tag only if it\n * matches all your filters. If there's no match, no special message is\n * returned; the response is simply empty.\n * \n * <h4>Wildcards</h4> You can use wildcards with the filter values: {@code *}\n * matches zero or more characters, and ? matches exactly one character. You can\n * escape special characters using a backslash before the character. For\n * example, a value of {@code \\*amazon\\?\\\\} searches for the literal string\n * {@code *amazon?\\}.\n * \n * @see TagApi\n */\npublic class TagFilterBuilder extends ImmutableMultimap.Builder<String, String> {\n\n   private static final String KEY = \"key\";\n   private static final String VALUE = \"value\";\n   private static final String RESOURCE_ID = \"resource-id\";\n   private static final String RESOURCE_TYPE = \"resource-type\";\n\n   public TagFilterBuilder key(String key) {\n      return put(KEY, key);\n   }\n\n   public TagFilterBuilder keys(String... keys) {\n      return putAll(KEY, keys);\n   }\n\n   public TagFilterBuilder keys(Iterable<String> keys) {\n      return putAll(KEY, keys);\n   }\n\n   public TagFilterBuilder anyKey() {\n      return putAll(KEY, ImmutableSet.<String> of());\n   }\n\n   public TagFilterBuilder value(String value) {\n      return put(VALUE, value);\n   }\n\n   public TagFilterBuilder values(String... values) {\n      return putAll(VALUE, ImmutableSet.<String> copyOf(values));\n   }\n\n   public TagFilterBuilder values(Iterable<String> values) {\n      return putAll(VALUE, ImmutableSet.<String> copyOf(values));\n   }\n\n   public TagFilterBuilder anyValue() {\n      return putAll(VALUE, ImmutableSet.<String> of());\n   }\n\n   public TagFilterBuilder resourceId(String resourceId) {\n      return put(RESOURCE_ID, resourceId);\n   }\n\n   public TagFilterBuilder resourceIds(String... resourceIds) {\n      return putAll(RESOURCE_ID, resourceIds);\n   }\n\n   public TagFilterBuilder resourceIds(Iterable<String> resourceIds) {\n      return putAll(RESOURCE_ID, resourceIds);\n   }\n\n   public TagFilterBuilder anyResourceId() {\n      return putAll(RESOURCE_ID, ImmutableSet.<String> of());\n   }\n\n   public TagFilterBuilder resourceType(String resourceType) {\n      return put(RESOURCE_TYPE, resourceType);\n   }\n\n   public TagFilterBuilder resourceTypes(String... resourceTypes) {\n      return putAll(RESOURCE_TYPE, resourceTypes);\n   }\n\n   public TagFilterBuilder resourceTypes(Iterable<String> resourceTypes) {\n      return putAll(RESOURCE_TYPE, resourceTypes);\n   }\n\n   public TagFilterBuilder anyResourceType() {\n      return putAll(RESOURCE_TYPE, ImmutableSet.<String> of());\n   }\n\n   public TagFilterBuilder customerGateway() {\n      return put(RESOURCE_TYPE, Tag.ResourceType.CUSTOMER_GATEWAY);\n   }\n\n   public TagFilterBuilder dhcpOptions() {\n      return put(RESOURCE_TYPE, Tag.ResourceType.DHCP_OPTIONS);\n   }\n\n   public TagFilterBuilder image() {\n      return put(RESOURCE_TYPE, Tag.ResourceType.IMAGE);\n   }\n\n   public TagFilterBuilder instance() {\n      return put(RESOURCE_TYPE, Tag.ResourceType.INSTANCE);\n   }\n\n   public TagFilterBuilder internetGateway() {\n      return put(RESOURCE_TYPE, Tag.ResourceType.INTERNET_GATEWAY);\n   }\n\n   public TagFilterBuilder networkAcl() {\n      return put(RESOURCE_TYPE, Tag.ResourceType.NETWORK_ACL);\n   }\n\n   public TagFilterBuilder reservedInstance() {\n      return put(RESOURCE_TYPE, Tag.ResourceType.RESERVED_INSTANCES);\n   }\n\n   public TagFilterBuilder routeTable() {\n      return put(RESOURCE_TYPE, Tag.ResourceType.ROUTE_TABLE);\n   }\n\n   public TagFilterBuilder securityGroup() {\n      return put(RESOURCE_TYPE, Tag.ResourceType.SECURITY_GROUP);\n   }\n\n   public TagFilterBuilder snapshot() {\n      return put(RESOURCE_TYPE, Tag.ResourceType.SNAPSHOT);\n   }\n\n   public TagFilterBuilder instancesRequest() {\n      return put(RESOURCE_TYPE, Tag.ResourceType.SPOT_INSTANCES_REQUEST);\n   }\n\n   public TagFilterBuilder subnet() {\n      return put(RESOURCE_TYPE, Tag.ResourceType.SUBNET);\n   }\n\n   public TagFilterBuilder volume() {\n      return put(RESOURCE_TYPE, Tag.ResourceType.VOLUME);\n   }\n\n   public TagFilterBuilder vpc() {\n      return put(RESOURCE_TYPE, Tag.ResourceType.VPC);\n   }\n\n   public TagFilterBuilder vpnConnection() {\n      return put(RESOURCE_TYPE, Tag.ResourceType.VPN_CONNECTION);\n   }\n\n   public TagFilterBuilder vpnGateway() {\n      return put(RESOURCE_TYPE, Tag.ResourceType.VPN_GATEWAY);\n   }\n\n   // to set correct return val in chain\n\n   @Override\n   public TagFilterBuilder put(String key, String value) {\n      return TagFilterBuilder.class.cast(super.put(key, value));\n   }\n\n   @Override\n   public TagFilterBuilder put(Entry<? extends String, ? extends String> entry) {\n      return TagFilterBuilder.class.cast(super.put(entry));\n   }\n\n   @Override\n   public TagFilterBuilder putAll(String key, Iterable<? extends String> values) {\n      return TagFilterBuilder.class.cast(super.putAll(key, values));\n   }\n\n   @Override\n   public TagFilterBuilder putAll(String key, String... values) {\n      return TagFilterBuilder.class.cast(super.putAll(key, values));\n   }\n\n   @Override\n   public TagFilterBuilder putAll(Multimap<? extends String, ? extends String> multimap) {\n      return TagFilterBuilder.class.cast(super.putAll(multimap));\n   }\n\n   @Override\n   @Beta\n   public TagFilterBuilder orderKeysBy(Comparator<? super String> keyComparator) {\n      return TagFilterBuilder.class.cast(super.orderKeysBy(keyComparator));\n   }\n\n   @Override\n   @Beta\n   public TagFilterBuilder orderValuesBy(Comparator<? super String> valueComparator) {\n      return TagFilterBuilder.class.cast(super.orderValuesBy(valueComparator));\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/util/Tags.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.util;\n\nimport static com.google.common.collect.Multimaps.index;\n\nimport java.util.Map;\n\nimport org.jclouds.ec2.domain.Tag;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.Maps;\n\npublic class Tags {\n   private Tags() {\n   }\n\n   /**\n    * maps the input on {@link Tag#getResourceId()} with a value of a map of its {@link Tag#getKey()} to\n    * {@link Tag#getValue()}\n    */\n   public static Map<String, Map<String, String>> resourceToTagsAsMap(Iterable<Tag> tags) {\n      return Maps.transformValues(index(tags, resourceIdFunction()).asMap(),\n            new Function<Iterable<Tag>, Map<String, String>>() {\n               @Override\n               public Map<String, String> apply(Iterable<Tag> in) {\n                  return Maps.transformValues(Maps.uniqueIndex(in, keyFunction()), valueFunction());\n               }\n            });\n   }\n\n   public static enum ValueFunction implements Function<Tag, String> {\n      INSTANCE;\n      @Override\n      public String apply(Tag in) {\n         return in.getValue().or(\"\");\n      }\n\n      @Override\n      public String toString() {\n         return \"getValue()\";\n      }\n   }\n\n   public static Function<Tag, String> valueFunction() {\n      return ValueFunction.INSTANCE;\n   }\n\n   public static enum KeyFunction implements Function<Tag, String> {\n      INSTANCE;\n      @Override\n      public String apply(Tag in) {\n         return in.getKey();\n      }\n\n      @Override\n      public String toString() {\n         return \"getKey()\";\n      }\n   }\n\n   public static Function<Tag, String> keyFunction() {\n      return KeyFunction.INSTANCE;\n   }\n\n   public static enum ResourceIdFunction implements Function<Tag, String> {\n      INSTANCE;\n      @Override\n      public String apply(Tag in) {\n         return in.getResourceId();\n      }\n\n      @Override\n      public String toString() {\n         return \"getResourceId()\";\n      }\n   }\n\n   public static Function<Tag, String> resourceIdFunction() {\n      return ResourceIdFunction.INSTANCE;\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/xml/AllocateAddressResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport jakarta.annotation.Resource;\n\nimport org.jclouds.http.functions.ParseSax.HandlerWithResult;\nimport org.jclouds.logging.Logger;\n\npublic class AllocateAddressResponseHandler extends HandlerWithResult<String> {\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   private String ipAddress;\n   private StringBuilder currentText = new StringBuilder();\n\n   protected String currentOrNull() {\n      String returnVal = currentText.toString().trim();\n      return returnVal.equals(\"\") ? null : returnVal;\n   }\n\n   public void endElement(String uri, String name, String qName) {\n      if (qName.equals(\"publicIp\")) {\n         ipAddress = currentOrNull();\n      }\n      currentText.setLength(0);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n\n   @Override\n   public String getResult() {\n      return ipAddress;\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/xml/AttachmentHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport java.util.Date;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\n\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.date.DateService;\nimport org.jclouds.ec2.domain.Attachment;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.location.Region;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Supplier;\n\npublic class AttachmentHandler extends ParseSax.HandlerForGeneratedRequestWithResult<Attachment> {\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   protected final DateService dateService;\n   protected final Supplier<String> defaultRegion;\n\n   @Inject\n   AttachmentHandler(DateService dateService, @Region Supplier<String> defaultRegion) {\n      this.dateService = dateService;\n      this.defaultRegion = defaultRegion;\n   }\n\n   private StringBuilder currentText = new StringBuilder();\n   private String volumeId;\n   private String instanceId;\n   private String device;\n   private Attachment.Status attachmentStatus;\n   private Date attachTime;\n\n   public Attachment getResult() {\n      String region = AWSUtils.findRegionInArgsOrNull(getRequest());\n      if (region == null)\n         region = defaultRegion.get();\n      return new Attachment(region, volumeId, instanceId, device, attachmentStatus, attachTime);\n   }\n\n   public void endElement(String uri, String name, String qName) {\n      if (qName.equals(\"volumeId\")) {\n         volumeId = currentText.toString().trim();\n      } else if (qName.equals(\"volumeId\")) {\n         volumeId = currentText.toString().trim();\n      } else if (qName.equals(\"status\")) {\n         attachmentStatus = Attachment.Status.fromValue(currentText.toString().trim());\n      } else if (qName.equals(\"instanceId\")) {\n         instanceId = currentText.toString().trim();\n      } else if (qName.equals(\"device\")) {\n         device = currentText.toString().trim();\n      } else if (qName.equals(\"attachTime\")) {\n         attachTime = dateService.iso8601DateOrSecondsDateParse(currentText.toString().trim());\n      }\n      currentText.setLength(0);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/xml/BaseReservationHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport static org.jclouds.util.SaxUtils.currentOrNull;\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport java.util.Date;\nimport java.util.Set;\n\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.date.DateService;\nimport org.jclouds.ec2.domain.Attachment;\nimport org.jclouds.ec2.domain.BlockDevice;\nimport org.jclouds.ec2.domain.InstanceState;\nimport org.jclouds.ec2.domain.Reservation;\nimport org.jclouds.ec2.domain.RootDeviceType;\nimport org.jclouds.ec2.domain.RunningInstance;\nimport org.jclouds.ec2.domain.RunningInstance.Builder;\nimport org.jclouds.http.functions.ParseSax.HandlerForGeneratedRequestWithResult;\nimport org.jclouds.location.Region;\nimport org.xml.sax.Attributes;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.Sets;\n\npublic abstract class BaseReservationHandler<T> extends HandlerForGeneratedRequestWithResult<T> {\n\n   protected final DateService dateService;\n   protected final Supplier<String> defaultRegion;\n\n   protected BaseReservationHandler(DateService dateService, @Region Supplier<String> defaultRegion) {\n      this.dateService = dateService;\n      this.defaultRegion = defaultRegion;\n   }\n\n   protected Builder<?> builder = newBuilder();\n\n   protected Builder<?> newBuilder() {\n      return RunningInstance.builder();\n   }\n\n   protected void inItem() {\n      if (endOfInstanceItem()) {\n         refineBuilderBeforeAddingInstance();\n         instances.add(builder.build());\n         builder = newBuilder();\n      }\n   }\n\n   protected StringBuilder currentText = new StringBuilder();\n   protected int itemDepth;\n   protected boolean inInstancesSet;\n   protected boolean inProductCodes;\n   protected boolean inGroupSet;\n\n   // attachments\n   private String volumeId;\n   private Attachment.Status attachmentStatus;\n   private Date attachTime;\n   private boolean deleteOnTermination;\n   private String deviceName;\n\n   // reservation stuff\n   private Set<String> groupNames = Sets.newLinkedHashSet();\n   private String ownerId;\n   private String requesterId;\n   private String reservationId;\n\n   private Set<RunningInstance> instances = Sets.newLinkedHashSet();\n\n\n   public void startElement(String uri, String name, String qName, Attributes attrs) {\n      if (equalsOrSuffix(qName, \"item\")) {\n         itemDepth++;\n      } else if (equalsOrSuffix(qName, \"instancesSet\")) {\n         inInstancesSet = true;\n      } else if (equalsOrSuffix(qName, \"productCodes\")) {\n         inProductCodes = true;\n      } else if (equalsOrSuffix(qName, \"groupSet\")) {\n         inGroupSet = true;\n      } \n   }\n\n   public void endElement(String uri, String name, String qName) {\n      if (equalsOrSuffix(qName, \"item\")) {\n         inItem();\n         itemDepth--;\n      } else if (equalsOrSuffix(qName, \"instancesSet\")) {\n         inInstancesSet = false;\n      } else if (equalsOrSuffix(qName, \"productCodes\")) {\n         inProductCodes = false;\n      } else if (equalsOrSuffix(qName, \"groupSet\")) {\n         inGroupSet = false;\n      } else if (equalsOrSuffix(qName, \"groupId\")) {\n         groupNames.add(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"ownerId\")) {\n         ownerId = currentOrNull(currentText);\n      } else if (equalsOrSuffix(qName, \"requesterId\")) {\n         requesterId = currentOrNull(currentText);\n      } else if (equalsOrSuffix(qName, \"reservationId\")) {\n         reservationId = currentOrNull(currentText);\n      } else if (equalsOrSuffix(qName, \"amiLaunchIndex\")) {\n         builder.amiLaunchIndex(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"dnsName\")) {\n         builder.dnsName(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"imageId\")) {\n         builder.imageId(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"instanceId\")) {\n         builder.instanceId(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"name\")) {\n         String rawState = currentOrNull(currentText);\n         if (rawState != null) {\n            builder.rawState(rawState);\n            builder.instanceState(InstanceState.fromValue(rawState));\n         }\n      } else if (equalsOrSuffix(qName, \"instanceType\")) {\n         builder.instanceType(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"ipAddress\")) {\n         builder.ipAddress(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"kernelId\")) {\n         builder.kernelId(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"keyName\")) {\n         builder.keyName(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"launchTime\")) {\n         builder.launchTime(dateService.iso8601DateOrSecondsDateParse(currentOrNull(currentText)));\n      } else if (equalsOrSuffix(qName, \"availabilityZone\")) {\n         builder.availabilityZone(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"virtualizationType\")) {\n         builder.virtualizationType(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"platform\")) {\n         builder.platform(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"privateDnsName\")) {\n         builder.privateDnsName(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"privateIpAddress\")) {\n         builder.privateIpAddress(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"ramdiskId\")) {\n         builder.ramdiskId(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"reason\")) {\n         builder.reason(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"rootDeviceType\")) {\n         builder.rootDeviceType(RootDeviceType.fromValue(currentOrNull(currentText)));\n      } else if (equalsOrSuffix(qName, \"rootDeviceName\")) {\n         builder.rootDeviceName(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"deviceName\")) {\n         deviceName = currentOrNull(currentText);\n      } else if (equalsOrSuffix(qName, \"volumeId\")) {\n         volumeId = currentOrNull(currentText);\n      } else if (equalsOrSuffix(qName, \"status\")) {\n         attachmentStatus = Attachment.Status.fromValue(currentText.toString().trim());\n      } else if (equalsOrSuffix(qName, \"attachTime\")) {\n         attachTime = dateService.iso8601DateOrSecondsDateParse(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"deleteOnTermination\")) {\n         deleteOnTermination = Boolean.parseBoolean(currentText.toString().trim());\n      } else if (equalsOrSuffix(qName, \"ebs\")) {\n         builder.device(deviceName, new BlockDevice(volumeId, attachmentStatus, attachTime, deleteOnTermination));\n         this.deviceName = null;\n         this.volumeId = null;\n         this.attachmentStatus = null;\n         this.attachTime = null;\n         this.deleteOnTermination = true;\n      }\n      currentText.setLength(0);\n   }\n\n\n   protected void refineBuilderBeforeAddingInstance() {\n      String region = getRequest() != null ? AWSUtils.findRegionInArgsOrNull(getRequest()) : null;\n      builder.region((region == null) ? defaultRegion.get() : region);\n      builder.groupNames(groupNames);\n   }\n\n   protected boolean endOfInstanceItem() {\n      return itemDepth <= 2 && inInstancesSet && !inProductCodes && !inGroupSet;\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n\n   protected Reservation<? extends RunningInstance> newReservation() {\n      String region = getRequest() != null ? AWSUtils.findRegionInArgsOrNull(getRequest()) : null;\n      if (region == null)\n         region = defaultRegion.get();\n      Reservation<? extends RunningInstance> info = new Reservation<RunningInstance>(region, groupNames, instances,\n            ownerId, requesterId, reservationId);\n      this.groupNames = Sets.newLinkedHashSet();\n      this.instances = Sets.newLinkedHashSet();\n      this.ownerId = null;\n      this.requesterId = null;\n      this.reservationId = null;\n      return info;\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/xml/BlockDeviceMappingHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport java.util.Date;\nimport java.util.Map;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.ec2.domain.Attachment;\nimport org.jclouds.ec2.domain.BlockDevice;\nimport org.jclouds.http.functions.ParseSax;\n\nimport com.google.common.collect.Maps;\nimport com.google.inject.Inject;\n\npublic class BlockDeviceMappingHandler extends\n         ParseSax.HandlerWithResult<Map<String, BlockDevice>> {\n   private StringBuilder currentText = new StringBuilder();\n\n   private Map<String, BlockDevice> ebsBlockDevices = Maps.newHashMap();\n   private String deviceName;\n   private String volumeId;\n   private boolean deleteOnTermination = true;  // correct default is true.\n   private Attachment.Status attachmentStatus;\n   private Date attachTime;\n\n   protected final DateService dateService;\n\n   @Inject \n   public BlockDeviceMappingHandler(DateService dateService) {\n      this.dateService = dateService;\n   }\n\n   public Map<String, BlockDevice> getResult() {\n      return ebsBlockDevices;\n   }\n\n   public void endElement(String uri, String name, String qName) {\n      if (qName.equals(\"deviceName\")) {\n         deviceName = currentText.toString().trim();\n      } else if (qName.equals(\"volumeId\")) {\n         volumeId = currentText.toString().trim();\n      } else if (qName.equals(\"deleteOnTermination\")) {\n         deleteOnTermination = Boolean.parseBoolean(currentText.toString().trim());\n      } else if (qName.equals(\"status\")) {\n         attachmentStatus = Attachment.Status.fromValue(currentText.toString().trim());\n      } else if (qName.equals(\"attachTime\")) {\n         attachTime = dateService.iso8601DateOrSecondsDateParse(currentText.toString().trim());\n      } else if (qName.equals(\"item\")) {\n         ebsBlockDevices.put(deviceName, new BlockDevice(volumeId, attachmentStatus, attachTime, deleteOnTermination));\n          this.volumeId = null;\n          this.deviceName = null;\n          this.deleteOnTermination = true;\n          this.attachmentStatus = null;\n          this.attachTime = null;\n      }\n      currentText.setLength(0);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/xml/BooleanValueHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport org.jclouds.http.functions.ParseSax;\n\n/**\n * \n * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-query-DescribeInstanceAttribute.html\"\n *      />\n */\npublic class BooleanValueHandler extends ParseSax.HandlerWithResult<Boolean> {\n\n   private StringBuilder currentText = new StringBuilder();\n   private boolean value;\n\n   public Boolean getResult() {\n      return value;\n   }\n\n   public void endElement(String uri, String name, String qName) {\n      if (qName.equalsIgnoreCase(\"value\")) {\n         this.value = Boolean.parseBoolean(currentText.toString().trim());\n      }\n      currentText.setLength(0);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/xml/BundleTaskHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport java.util.Date;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.date.DateService;\nimport org.jclouds.ec2.domain.BundleTask;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.location.Region;\n\nimport com.google.common.base.Supplier;\n\npublic class BundleTaskHandler extends ParseSax.HandlerForGeneratedRequestWithResult<BundleTask> {\n   protected final DateService dateService;\n   protected final Supplier<String> defaultRegion;\n\n   @Inject\n   protected BundleTaskHandler(DateService dateService, @Region Supplier<String> defaultRegion) {\n      this.dateService = dateService;\n      this.defaultRegion = defaultRegion;\n   }\n\n   private StringBuilder currentText = new StringBuilder();\n\n   private String bundleId;\n   private String code;\n   private String message;\n   private String instanceId;\n   private int progress = 0;\n   private Date startTime;\n   private String state;\n   private String bucket;\n   private String prefix;\n   private Date updateTime;\n\n   public BundleTask getResult() {\n      String region = AWSUtils.findRegionInArgsOrNull(getRequest());\n      if (region == null)\n         region = defaultRegion.get();\n      BundleTask.Error error = null;\n      if (code != null)\n         error = new BundleTask.Error(code, message);\n      BundleTask returnVal = new BundleTask(region, bundleId, error, instanceId, progress, startTime,\n            state, bucket, prefix, updateTime);\n      this.bundleId = null;\n      this.code = null;\n      this.message = null;\n      this.instanceId = null;\n      this.progress = 0;\n      this.startTime = null;\n      this.state = null;\n      this.bucket = null;\n      this.prefix = null;\n      this.updateTime = null;\n      return returnVal;\n   }\n\n   public void endElement(String uri, String name, String qName) {\n      if (qName.equals(\"bundleId\")) {\n         bundleId = currentText.toString().trim();\n      } else if (qName.equals(\"code\")) {\n         code = currentText.toString().trim();\n      } else if (qName.equals(\"message\")) {\n         message = currentText.toString().trim();\n      } else if (qName.equals(\"instanceId\")) {\n         instanceId = currentText.toString().trim();\n      } else if (qName.equals(\"progress\")) {\n         String temp = currentText.toString().trim();\n         temp = temp.substring(0, temp.length() - 1);\n         progress = Integer.parseInt(temp);\n      } else if (qName.equals(\"startTime\")) {\n         startTime = dateService.iso8601DateOrSecondsDateParse(currentText.toString().trim());\n      } else if (qName.equals(\"state\")) {\n         state = currentText.toString().trim();\n      } else if (qName.equals(\"bucket\")) {\n         bucket = currentText.toString().trim();\n      } else if (qName.equals(\"prefix\")) {\n         prefix = currentText.toString().trim();\n      } else if (qName.equals(\"updateTime\")) {\n         updateTime = dateService.iso8601DateOrSecondsDateParse(currentText.toString().trim());\n      }\n      currentText.setLength(0);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/xml/CreateVolumeResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Date;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.date.DateService;\nimport org.jclouds.ec2.domain.Attachment;\nimport org.jclouds.ec2.domain.Volume;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.location.Region;\nimport org.jclouds.location.Zone;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.xml.sax.Attributes;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.Maps;\nimport com.google.common.collect.Sets;\n\npublic class CreateVolumeResponseHandler extends ParseSax.HandlerForGeneratedRequestWithResult<Volume> {\n   protected final DateService dateService;\n   protected final Supplier<String> defaultRegion;\n   protected final Supplier<Map<String, Supplier<Set<String>>>> regionToZonesSupplier;\n   protected final Supplier<Set<String>> zonesSupplier;\n\n   @Inject\n   protected CreateVolumeResponseHandler(DateService dateService, @Region Supplier<String> defaultRegion,\n            @Zone Supplier<Map<String, Supplier<Set<String>>>> regionToZonesSupplier,\n            @Zone Supplier<Set<String>> zonesSupplier) {\n      this.dateService = dateService;\n      this.defaultRegion = defaultRegion;\n      this.regionToZonesSupplier = regionToZonesSupplier;\n      this.zonesSupplier = zonesSupplier;\n   }\n\n   protected StringBuilder currentText = new StringBuilder();\n   \n   protected String id;\n   protected int size;\n   protected String snapshotId;\n   protected String availabilityZone;\n   protected Volume.Status volumeStatus;\n   protected Date createTime;\n   protected Set<Attachment> attachments = Sets.newLinkedHashSet();\n\n   protected String volumeId;\n   protected String instanceId;\n   protected String device;\n   protected Attachment.Status attachmentStatus;\n   protected Date attachTime;\n   protected String volumeType;\n   protected Integer iops;\n   protected boolean encrypted;\n\n   protected boolean inAttachmentSet;\n\n   protected String region;\n\n   public Volume getResult() {\n      return newVolume();\n   }\n\n   public void startElement(String uri, String name, String qName, Attributes attrs) {\n      if (qName.equals(\"attachmentSet\")) {\n         inAttachmentSet = true;\n      }\n   }\n\n   public void endElement(String uri, String name, String qName) {\n      if (qName.equals(\"volumeId\")) {\n         if (inAttachmentSet) {\n            volumeId = currentText.toString().trim();\n         } else {\n            id = currentText.toString().trim();\n         }\n      } else if (qName.equals(\"size\")) {\n         size = Integer.parseInt(currentText.toString().trim());\n      } else if (qName.equals(\"availabilityZone\")) {\n         availabilityZone = currentText.toString().trim();\n      } else if (qName.equals(\"volumeId\")) {\n         if (inAttachmentSet) {\n            volumeId = currentText.toString().trim();\n         } else {\n            id = currentText.toString().trim();\n         }\n      } else if (qName.equals(\"status\")) {\n         if (inAttachmentSet) {\n            attachmentStatus = Attachment.Status.fromValue(currentText.toString().trim());\n         } else {\n            volumeStatus = Volume.Status.fromValue(currentText.toString().trim());\n         }\n      } else if (qName.equals(\"createTime\")) {\n         createTime = dateService.iso8601DateOrSecondsDateParse(currentText.toString().trim());\n      } else if (qName.equals(\"attachmentSet\")) {\n         inAttachmentSet = false;\n      } else if (qName.equals(\"instanceId\")) {\n         instanceId = currentText.toString().trim();\n      } else if (qName.equals(\"snapshotId\")) {\n         snapshotId = currentText.toString().trim();\n         if (snapshotId.equals(\"\"))\n            snapshotId = null;\n      } else if (qName.equals(\"device\")) {\n         device = currentText.toString().trim();\n      } else if (qName.equals(\"attachTime\")) {\n         attachTime = dateService.iso8601DateOrSecondsDateParse(currentText.toString().trim());\n      } else if (qName.equals(\"volumeType\")) {\n         volumeType = currentText.toString().trim();\n         if (volumeType.equals(\"\"))\n            volumeType = null;\n      } else if (qName.equals(\"iops\")) {\n         iops = Integer.parseInt(currentText.toString().trim());\n      } else if (qName.equals(\"encrypted\")) {\n         encrypted = Boolean.parseBoolean(currentText.toString().trim());\n      } else if (qName.equals(\"item\")) {\n         if (inAttachmentSet) {\n            attachments.add(new Attachment(region, volumeId, instanceId, device, attachmentStatus, attachTime));\n            volumeId = null;\n            instanceId = null;\n            device = null;\n            attachmentStatus = null;\n            attachTime = null;\n         }\n\n      }\n      currentText.setLength(0);\n   }\n\n   private Volume newVolume() {\n      Volume volume = new Volume(region, id, size, snapshotId, availabilityZone, volumeStatus, createTime,\n              volumeType, iops, encrypted, attachments);\n      id = null;\n      size = 0;\n      snapshotId = null;\n      availabilityZone = null;\n      volumeStatus = null;\n      createTime = null;\n      attachments = Sets.newLinkedHashSet();\n      volumeType = null;\n      iops = null;\n      encrypted = false;\n      return volume;\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n\n   @Override\n   public CreateVolumeResponseHandler setContext(HttpRequest request) {\n      super.setContext(request);\n      region = AWSUtils.findRegionInArgsOrNull(getRequest());\n      if (region == null) {\n         Set<String> zones = zonesSupplier.get();\n         String zone = findAvailabilityZoneInArgsOrNull(getRequest(), zones);\n         if (zone != null) {\n            Map<String, Set<String>> regionToZones = Maps.transformValues(regionToZonesSupplier.get(), Suppliers\n                     .<Set<String>> supplierFunction());\n            for (Entry<String, Set<String>> entry : regionToZones.entrySet()) {\n               if (entry.getValue().contains(zone)) {\n                  region = entry.getKey();\n                  break;\n               }\n\n            }\n            checkNotNull(region, \"zone %s not in %s\", zone, regionToZones);\n         } else {\n            region = defaultRegion.get();\n         }\n      }\n      return this;\n   }\n\n   public static String findAvailabilityZoneInArgsOrNull(GeneratedHttpRequest gRequest, Set<String> zones) {\n      for (Object arg : gRequest.getInvocation().getArgs()) {\n         if (arg instanceof String) {\n            String zone = (String) arg;\n            if (zones.contains(zone))\n               return zone;\n         }\n      }\n      return null;\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/xml/DescribeAddressesResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\n\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.ec2.domain.PublicIpInstanceIdPair;\nimport org.jclouds.http.functions.ParseSax.HandlerForGeneratedRequestWithResult;\nimport org.jclouds.location.Region;\nimport org.jclouds.logging.Logger;\nimport org.xml.sax.Attributes;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.Sets;\n\npublic class DescribeAddressesResponseHandler extends HandlerForGeneratedRequestWithResult<Set<PublicIpInstanceIdPair>> {\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n   private Set<PublicIpInstanceIdPair> pairs = Sets.newLinkedHashSet();\n   private String ipAddress;\n   private StringBuilder currentText = new StringBuilder();\n   @Inject\n   @Region\n   Supplier<String> defaultRegion;\n   private String allocationId;\n   private String instanceId;\n   private final TagSetHandler tagSetHandler;\n   private boolean inTagSet;\n   private Map<String, String> tagResults;\n\n   @Inject\n   DescribeAddressesResponseHandler(final TagSetHandler tagSetHandler) {\n      this.tagSetHandler = tagSetHandler;\n   }\n\n   @Override\n   public void startElement(final String uri, final String name, final String qName, final Attributes attrs) {\n      if (equalsOrSuffix(qName, \"tagSet\")) {\n         inTagSet = true;\n      }\n      if (inTagSet) {\n         tagSetHandler.startElement(uri, name, qName, attrs);\n      }\n   }\n\n   protected String currentOrNull() {\n      String returnVal = currentText.toString().trim();\n      return returnVal.equals(\"\") ? null : returnVal;\n   }\n\n   @Override\n   public void endElement(final String uri, final String name, final String qName) {\n      if (equalsOrSuffix(qName, \"tagSet\")) {\n         inTagSet = false;\n         tagResults = tagSetHandler.getResult();\n      } else if (inTagSet) {\n         tagSetHandler.endElement(uri, name, qName);\n      } else if (qName.equals(\"publicIp\")) {\n         ipAddress = currentOrNull();\n      } else if (qName.equals(\"instanceId\")) {\n         instanceId = currentOrNull();\n      } else if (qName.equals(\"allocationId\")) {\n         allocationId = currentOrNull();\n      } else if (qName.equals(\"item\")) {\n         String region = AWSUtils.findRegionInArgsOrNull(getRequest());\n         if (region == null)\n            region = defaultRegion.get();\n\n         pairs.add(new PublicIpInstanceIdPair(region, ipAddress, instanceId, allocationId, tagResults));\n         ipAddress = null;\n         instanceId = null;\n         allocationId = null;\n         tagResults = null;\n      }\n\n      currentText.setLength(0);\n   }\n\n   @Override\n   public void characters(final char[] ch, final int start, final int length) {\n      if (inTagSet) {\n         tagSetHandler.characters(ch, start, length);\n      } else {\n         currentText.append(ch, start, length);\n      }\n   }\n\n   @Override\n   public Set<PublicIpInstanceIdPair> getResult() {\n      return pairs;\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/xml/DescribeAvailabilityZonesResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\n\nimport org.jclouds.ec2.domain.AvailabilityZoneInfo;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.location.Region;\nimport org.jclouds.logging.Logger;\nimport org.xml.sax.Attributes;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.Sets;\n\npublic class DescribeAvailabilityZonesResponseHandler extends ParseSax.HandlerWithResult<Set<AvailabilityZoneInfo>> {\n   private StringBuilder currentText = new StringBuilder();\n   private final Supplier<String> defaultRegion;\n\n   private Set<AvailabilityZoneInfo> availabilityZones = Sets.newLinkedHashSet();\n   private String zone;\n   @Resource\n   protected Logger logger = Logger.NULL;\n   private String region;\n   private String zoneState;\n   private boolean inMessageSet;\n   private Set<String> messages = Sets.newHashSet();\n\n   /**\n    * clones like {@code openstack-nova-ec2}, which don't support multiple regions don't return region in the XML\n    * output.\n    */\n   @Inject\n   DescribeAvailabilityZonesResponseHandler(@Region Supplier<String> defaultRegion) {\n      this.defaultRegion = defaultRegion;\n   }\n\n   @Override\n   public void startDocument() {\n      region = defaultRegion.get();\n   }\n\n   public Set<AvailabilityZoneInfo> getResult() {\n      return availabilityZones;\n   }\n\n   public void startElement(String uri, String name, String qName, Attributes attrs) {\n      if (qName.equals(\"messageSet\")) {\n         inMessageSet = true;\n      }\n   }\n\n   public void endElement(String uri, String name, String qName) {\n      if (qName.equals(\"zoneName\")) {\n         zone = currentText.toString().trim();\n      } else if (qName.equals(\"regionName\")) {\n         try {\n            region = currentText.toString().trim();\n         } catch (IllegalArgumentException e) {\n            logger.warn(e, \"unsupported region: %s\", currentText.toString().trim());\n            region = \"UNKNOWN\";\n         }\n      } else if (qName.equals(\"zoneState\")) {\n         zoneState = currentText.toString().trim();\n      } else if (qName.equals(\"message\")) {\n         messages.add(currentText.toString().trim());\n      } else if (qName.equals(\"messageSet\")) {\n         inMessageSet = false;\n      } else if (qName.equals(\"item\") && !inMessageSet) {\n         availabilityZones.add(new AvailabilityZoneInfo(zone, zoneState, region, messages));\n         this.zone = null;\n         this.region = defaultRegion.get();\n         this.zoneState = null;\n         this.messages = Sets.newHashSet();\n      }\n      currentText.setLength(0);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/xml/DescribeBundleTasksResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.ec2.domain.BundleTask;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.http.functions.ParseSax.HandlerWithResult;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\n\nimport com.google.common.collect.Sets;\n\npublic class DescribeBundleTasksResponseHandler extends ParseSax.HandlerWithResult<Set<BundleTask>> {\n\n   private Set<BundleTask> bundleTasks = Sets.newLinkedHashSet();\n   private final BundleTaskHandler bundleTaskHandler;\n\n   @Inject\n   public DescribeBundleTasksResponseHandler(BundleTaskHandler bundleTaskHandler) {\n      this.bundleTaskHandler = bundleTaskHandler;\n   }\n\n   public Set<BundleTask> getResult() {\n      return bundleTasks;\n   }\n\n   @Override\n   public HandlerWithResult<Set<BundleTask>> setContext(HttpRequest request) {\n      bundleTaskHandler.setContext(request);\n      return super.setContext(request);\n   }\n\n   @Override\n   public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {\n      if (!qName.equals(\"item\"))\n         bundleTaskHandler.startElement(uri, localName, qName, attributes);\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) throws SAXException {\n      if (qName.equals(\"item\")) {\n         bundleTasks.add(bundleTaskHandler.getResult());\n      }\n      bundleTaskHandler.endElement(uri, localName, qName);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      bundleTaskHandler.characters(ch, start, length);\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/xml/DescribeImagesResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport static org.jclouds.util.SaxUtils.currentOrNull;\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport java.util.Map;\nimport java.util.Set;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.Maps;\nimport com.google.common.collect.Sets;\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.ec2.domain.Hypervisor;\nimport org.jclouds.ec2.domain.Image;\nimport org.jclouds.ec2.domain.Image.Architecture;\nimport org.jclouds.ec2.domain.Image.EbsBlockDevice;\nimport org.jclouds.ec2.domain.Image.ImageState;\nimport org.jclouds.ec2.domain.Image.ImageType;\nimport org.jclouds.ec2.domain.RootDeviceType;\nimport org.jclouds.ec2.domain.VirtualizationType;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.location.Region;\nimport org.jclouds.logging.Logger;\nimport org.xml.sax.Attributes;\n\n/**\n * Parses the following XML document:\n * <p/>\n * DescribeImagesResponse xmlns=\"http://ec2.amazonaws.com/doc/2010-08-31/\"\n * \n * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeImages.html\"\n *      />\n */\npublic class DescribeImagesResponseHandler extends ParseSax.HandlerForGeneratedRequestWithResult<Set<Image>> {\n\n   @Inject\n   public DescribeImagesResponseHandler(@Region Supplier<String> defaultRegion, TagSetHandler tagSetHandler) {\n      this.defaultRegion = defaultRegion;\n      this.tagSetHandler = tagSetHandler;\n   }\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   protected Set<Image> contents = Sets.newLinkedHashSet();\n   private StringBuilder currentText = new StringBuilder();\n   private final Supplier<String> defaultRegion;\n   private final TagSetHandler tagSetHandler;\n\n   private Architecture architecture;\n   private String name;\n   private String description;\n   private String imageId;\n   private String imageLocation;\n   private String imageOwnerId;\n   private ImageState imageState;\n   private String rawState;\n   private ImageType imageType;\n   private boolean isPublic;\n   private String kernelId;\n   private String platform;\n   private Set<String> productCodes = Sets.newHashSet();\n   private String ramdiskId;\n   private boolean inProductCodes;\n   private boolean inBlockDeviceMapping;\n   private boolean inTagSet;\n   private RootDeviceType rootDeviceType = RootDeviceType.INSTANCE_STORE;\n   private Map<String, EbsBlockDevice> ebsBlockDevices = Maps.newHashMap();\n   private Map<String, String> tags = Maps.newLinkedHashMap();\n   private String deviceName;\n   private String snapshotId;\n   private VirtualizationType virtualizationType = VirtualizationType.PARAVIRTUAL;\n   private Hypervisor hypervisor = Hypervisor.XEN;\n\n   private int volumeSize;\n   private boolean deleteOnTermination = true;  // correct default is true.\n   private boolean encrypted = false;\n   private String volumeType;\n   private Integer iops;\n   private String rootDeviceName;\n\n   public Set<Image> getResult() {\n      return contents;\n   }\n\n   public void startElement(String uri, String name, String qName, Attributes attrs) {\n      if (qName.equals(\"productCodes\")) {\n         inProductCodes = true;\n      } else if (qName.equals(\"blockDeviceMapping\")) {\n         inBlockDeviceMapping = true;\n      } else if (equalsOrSuffix(qName, \"tagSet\")) {\n         inTagSet = true;\n      }\n      if (inTagSet) {\n         tagSetHandler.startElement(uri, name, qName, attrs);\n      }\n   }\n\n   public void endElement(String uri, String name, String qName) {\n      if (equalsOrSuffix(qName, \"tagSet\")) {\n         inTagSet = false;\n         tags = tagSetHandler.getResult();\n      } else if (inTagSet) {\n         tagSetHandler.endElement(uri, name, qName);\n      }\n      if (qName.equals(\"architecture\")) {\n         architecture = Architecture.fromValue(currentText.toString().trim());\n      // Nova Diablo uses the wrong name for this field\n      } else if (qName.equals(\"name\") || qName.equals(\"displayName\")) {\n         this.name = currentText.toString().trim();\n      } else if (qName.equals(\"description\")) {\n         description = currentText.toString().trim();\n      } else if (qName.equals(\"imageId\")) {\n         imageId = currentText.toString().trim();\n      } else if (qName.equals(\"deviceName\")) {\n         deviceName = currentText.toString().trim();\n      } else if (qName.equals(\"imageLocation\")) {\n         imageLocation = currentText.toString().trim();\n      } else if (qName.equals(\"imageOwnerId\")) {\n         imageOwnerId = currentText.toString().trim();\n      } else if (qName.equals(\"imageState\")) {\n         rawState = currentOrNull(currentText);\n         imageState = ImageState.fromValue(rawState);\n      } else if (qName.equals(\"imageType\")) {\n         imageType = ImageType.fromValue(currentText.toString().trim());\n      } else if (qName.equals(\"isPublic\")) {\n         isPublic = Boolean.parseBoolean(currentText.toString().trim());\n      } else if (qName.equals(\"kernelId\")) {\n         kernelId = currentText.toString().trim();\n      } else if (qName.equals(\"platform\")) {\n         platform = currentText.toString().trim();\n      } else if (qName.equals(\"productCode\")) {\n         productCodes.add(currentText.toString().trim());\n      } else if (qName.equals(\"productCodes\")) {\n         inProductCodes = false;\n      } else if (qName.equals(\"blockDeviceMapping\")) {\n         inBlockDeviceMapping = false;\n      } else if (qName.equals(\"snapshotId\")) {\n         snapshotId = currentText.toString().trim();\n      } else if (qName.equals(\"volumeSize\")) {\n         volumeSize = Integer.parseInt(currentText.toString().trim());\n      } else if (qName.equals(\"deleteOnTermination\")) {\n         deleteOnTermination = Boolean.parseBoolean(currentText.toString().trim());\n      } else if (qName.equals(\"encrypted\")) {\n         encrypted = Boolean.parseBoolean(currentText.toString().trim());\n      } else if (qName.equals(\"iops\")) {\n         iops = Integer.valueOf(currentText.toString().trim());\n      } else if (qName.equals(\"volumeType\")) {\n         volumeType = currentText.toString().trim();\n      } else if (qName.equals(\"ramdiskId\")) {\n         ramdiskId = currentText.toString().trim();\n      } else if (qName.equals(\"rootDeviceType\")) {\n         rootDeviceType = RootDeviceType.fromValue(currentText.toString().trim());\n      } else if (qName.equals(\"rootDeviceName\")) {\n         rootDeviceName = currentText.toString().trim();\n      } else if (qName.equals(\"virtualizationType\")) {\n         virtualizationType = VirtualizationType.fromValue(currentText.toString().trim());\n      } else if (qName.equals(\"hypervisor\")) {\n         hypervisor = Hypervisor.fromValue(currentText.toString().trim());\n      } else if (qName.equals(\"item\")) {\n         if (inBlockDeviceMapping) {\n            ebsBlockDevices.put(deviceName, new Image.EbsBlockDevice(snapshotId, volumeSize, deleteOnTermination,\n                    volumeType, iops, encrypted));\n            this.deviceName = null;\n            this.snapshotId = null;\n            this.volumeSize = 0;\n            this.deleteOnTermination = true;\n            this.encrypted = false;\n            this.volumeType = null;\n            this.iops = null;\n         } else if (!inTagSet && !inProductCodes) {\n            try {\n               String region = getRequest() != null ? AWSUtils.findRegionInArgsOrNull(getRequest()) : null;\n               if (region == null)\n                  region = defaultRegion.get();\n               contents.add(new Image(region, architecture, this.name, description, imageId, imageLocation,\n                        imageOwnerId, imageState, rawState, imageType, isPublic, productCodes, kernelId, platform,\n                        ramdiskId, rootDeviceType, rootDeviceName, ebsBlockDevices, tags, virtualizationType, hypervisor));\n            } catch (NullPointerException e) {\n               logger.warn(e, \"malformed image: %s\", imageId);\n            }\n            this.name = null;\n            this.description = null;\n            this.architecture = null;\n            this.imageId = null;\n            this.imageLocation = null;\n            this.imageOwnerId = null;\n            this.imageState = null;\n            this.rawState = null;\n            this.imageType = null;\n            this.isPublic = false;\n            this.kernelId = null;\n            this.platform = null;\n            this.productCodes = Sets.newHashSet();\n            this.ramdiskId = null;\n            this.rootDeviceType = RootDeviceType.INSTANCE_STORE;\n            this.rootDeviceName = null;\n            this.ebsBlockDevices = Maps.newHashMap();\n            this.virtualizationType = VirtualizationType.PARAVIRTUAL;\n            this.hypervisor = Hypervisor.XEN;\n         }\n\n      }\n      currentText.setLength(0);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      if (inTagSet) {\n         tagSetHandler.characters(ch, start, length);\n      } else {\n         currentText.append(ch, start, length);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/xml/DescribeInstancesResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.ec2.domain.Reservation;\nimport org.jclouds.ec2.domain.RunningInstance;\nimport org.jclouds.location.Region;\nimport org.xml.sax.Attributes;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\n\n/**\n * Parses the following XML document:\n * <p/>\n * DescribeImagesResponse xmlns=\"http:\n * \n * @see <a href=\"http: />\n */\npublic class DescribeInstancesResponseHandler extends\n      BaseReservationHandler<Set<Reservation<? extends RunningInstance>>> {\n   private final TagSetHandler tagSetHandler;\n   private Builder<Reservation<? extends RunningInstance>> reservations = ImmutableSet\n         .<Reservation<? extends RunningInstance>> builder();\n   private boolean inTagSet;\n\n   @Inject\n   DescribeInstancesResponseHandler(DateService dateService, @Region Supplier<String> defaultRegion,\n         TagSetHandler tagSetHandler) {\n      super(dateService, defaultRegion);\n      this.tagSetHandler = tagSetHandler;\n   }\n\n   @Override\n   public void startElement(String uri, String name, String qName, Attributes attrs) {\n      super.startElement(uri, name, qName, attrs);\n      if (equalsOrSuffix(qName, \"tagSet\")) {\n         inTagSet = true;\n      }\n      if (inTagSet) {\n         tagSetHandler.startElement(uri, name, qName, attrs);\n      }\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      if (inTagSet) {\n         tagSetHandler.characters(ch, start, length);\n      } else {\n         super.characters(ch, start, length);\n      }\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) {\n      if (equalsOrSuffix(qName, \"tagSet\")) {\n         inTagSet = false;\n         builder.tags(tagSetHandler.getResult());\n      } else if (inTagSet) {\n         tagSetHandler.endElement(uri, name, qName);\n      }\n      super.endElement(uri, name, qName);\n   }\n\n   @Override\n   public Set<Reservation<? extends RunningInstance>> getResult() {\n      return reservations.build();\n   }\n\n   protected boolean endOfReservationItem() {\n      return itemDepth == 1;\n   }\n\n   @Override\n   protected void inItem() {\n      if (endOfReservationItem()) {\n         reservations.add(super.newReservation());\n      } else {\n         super.inItem();\n      }\n   }\n\n   protected boolean endOfInstanceItem() {\n      return itemDepth == 2 && inInstancesSet;\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/xml/DescribeKeyPairsResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport static org.jclouds.util.SaxUtils.currentOrNull;\n\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.ec2.domain.KeyPair;\nimport org.jclouds.ec2.domain.KeyPair.Builder;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.location.Region;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.Sets;\n\n/**\n * Parses: DescribeKeyPairsResponse xmlns=\"http://ec2.amazonaws.com/doc/2010-08-31/\"\n * \n * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeKeyPairs.html\"\n *      />\n */\npublic class DescribeKeyPairsResponseHandler extends ParseSax.HandlerForGeneratedRequestWithResult<Set<KeyPair>> {\n   private final Supplier<String> defaultRegion;\n   private Builder builder;\n\n   @Inject\n   public DescribeKeyPairsResponseHandler(@Region Supplier<String> defaultRegion) {\n      this.defaultRegion = defaultRegion;\n   }\n\n   @Override\n   public void startDocument() {\n      builder = KeyPair.builder().region(defaultRegion.get());\n   }\n\n   private StringBuilder currentText = new StringBuilder();\n   private Set<KeyPair> keyPairs = Sets.newLinkedHashSet();\n\n   public Set<KeyPair> getResult() {\n      return keyPairs;\n   }\n\n   public void endElement(String uri, String name, String qName) {\n\n      if (qName.equals(\"keyFingerprint\")) {\n         builder.sha1OfPrivateKey(currentOrNull(currentText));\n      } else if (qName.equals(\"item\")) {\n         String region = AWSUtils.findRegionInArgsOrNull(getRequest());\n         if (region != null)\n            builder.region(region);\n         try {\n            keyPairs.add(builder.build());\n         } finally {\n            builder = KeyPair.builder().region(defaultRegion.get());\n         }\n      } else if (qName.equals(\"keyName\")) {\n         builder.keyName(currentOrNull(currentText));\n      }\n      currentText.setLength(0);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/xml/DescribeRegionsResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport java.net.URI;\nimport java.util.Map;\n\nimport jakarta.annotation.Resource;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.collect.Maps;\n\npublic class DescribeRegionsResponseHandler extends ParseSax.HandlerWithResult<Map<String, URI>> {\n   private StringBuilder currentText = new StringBuilder();\n\n   private Map<String, URI> regionEndpoints = Maps.newHashMap();\n   private String region;\n   private URI regionEndpoint;\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   public Map<String, URI> getResult() {\n      return regionEndpoints;\n   }\n\n   public void endElement(String uri, String name, String qName) {\n      if (qName.equals(\"regionName\")) {\n         String pending = currentText.toString().trim();\n         if (pending.indexOf(\"Walrus\") == -1)\n            region = pending;\n         // Nova uses regionUrl\n      } else if (qName.equals(\"regionEndpoint\") || qName.equals(\"regionUrl\")) {\n         String pending = currentText.toString().trim();\n         if (pending.indexOf(\"Walrus\") == -1)\n            regionEndpoint = URI.create(pending.startsWith(\"http\") ? pending : String.format(\"https://%s\", pending));\n      } else if (qName.equals(\"item\") && region != null && regionEndpoint != null) {\n         regionEndpoints.put(region, regionEndpoint);\n         this.region = null;\n         this.regionEndpoint = null;\n      }\n      currentText.setLength(0);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/xml/DescribeSecurityGroupsResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.ec2.domain.SecurityGroup;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.http.functions.ParseSax.HandlerForGeneratedRequestWithResult;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\n\n/**\n * Parses: DescribeSecurityGroupsResponse\n * xmlns=\"http://ec2.amazonaws.com/doc/2010-08-31/\"\n *\n * @see <a href=\n *      \"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-query-DescribesecurityGroupInfo.html\"\n *      />\n */\npublic class DescribeSecurityGroupsResponseHandler extends\n      ParseSax.HandlerForGeneratedRequestWithResult<Set<SecurityGroup>> {\n\n   private final SecurityGroupHandler securityGroupHandler;\n\n   private StringBuilder currentText = new StringBuilder();\n   private Builder<SecurityGroup> securityGroups = ImmutableSet.<SecurityGroup> builder();\n   private boolean inSecurityGroupInfo;\n\n   protected int itemDepth;\n\n   @Inject\n   public DescribeSecurityGroupsResponseHandler(SecurityGroupHandler securityGroupHandler) {\n      this.securityGroupHandler = securityGroupHandler;\n   }\n\n   @Override\n   public HandlerForGeneratedRequestWithResult<Set<SecurityGroup>> setContext(HttpRequest request) {\n      securityGroupHandler.setContext(request);\n      return super.setContext(request);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Set<SecurityGroup> getResult() {\n      return securityGroups.build();\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void startElement(String url, String name, String qName, Attributes attributes) throws SAXException {\n      if (equalsOrSuffix(qName, \"item\")) {\n         itemDepth++;\n      } else if (equalsOrSuffix(qName, \"securityGroupInfo\")) {\n         inSecurityGroupInfo = true;\n      }\n      if (inSecurityGroupInfo) {\n         securityGroupHandler.startElement(url, name, qName, attributes);\n      }\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void endElement(String uri, String name, String qName) throws SAXException {\n      if (equalsOrSuffix(qName, \"item\")) {\n         endItem(uri, name, qName);\n         itemDepth--;\n      } else if (equalsOrSuffix(qName, \"securityGroupInfo\")) {\n         inSecurityGroupInfo = false;\n      } else if (inSecurityGroupInfo) {\n         securityGroupHandler.endElement(uri, name, qName);\n      }\n      currentText.setLength(0);\n   }\n\n   protected void endItem(String uri, String name, String qName) throws SAXException {\n      if (inSecurityGroupInfo) {\n         if (itemDepth == 1)\n            securityGroups.add(securityGroupHandler.getResult());\n         else\n            securityGroupHandler.endElement(uri, name, qName);\n      }\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      if (inSecurityGroupInfo) {\n         securityGroupHandler.characters(ch, start, length);\n      } else {\n         currentText.append(ch, start, length);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/xml/DescribeSnapshotsResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.ec2.domain.Snapshot;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.functions.ParseSax;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\n\nimport com.google.common.collect.Sets;\n\npublic class DescribeSnapshotsResponseHandler extends ParseSax.HandlerWithResult<Set<Snapshot>> {\n\n   private Set<Snapshot> snapshots = Sets.newLinkedHashSet();\n   private final SnapshotHandler snapshotHandler;\n   private int itemDepth = 0;\n\n   @Inject\n   public DescribeSnapshotsResponseHandler(SnapshotHandler snapshotHandler) {\n      this.snapshotHandler = snapshotHandler;\n   }\n\n   public Set<Snapshot> getResult() {\n      return snapshots;\n   }\n\n   @Override\n   public void startElement(String uri, String localName, String qName, Attributes attributes)\n            throws SAXException {\n      itemDepth++;\n      snapshotHandler.startElement(uri, localName, qName, attributes);\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) throws SAXException {\n      snapshotHandler.endElement(uri, localName, qName);\n      itemDepth--;\n\n      if (qName.equals(\"item\") && itemDepth == 2) {\n         this.snapshots.add(snapshotHandler.getResult());\n      }\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      snapshotHandler.characters(ch, start, length);\n   }\n\n   @Override\n   public DescribeSnapshotsResponseHandler setContext(HttpRequest request) {\n      snapshotHandler.setContext(request);\n      super.setContext(request);\n      return this;\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/xml/DescribeSubnetsResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport org.jclouds.ec2.domain.Subnet;\nimport org.jclouds.http.functions.ParseSax;\nimport org.xml.sax.Attributes;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\nimport com.google.inject.Inject;\n\n/**\n * @see <a href=\"http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeSubnets.html\" >xml</a>\n */\npublic class DescribeSubnetsResponseHandler extends\n      ParseSax.HandlerForGeneratedRequestWithResult<FluentIterable<Subnet>> {\n   private final SubnetHandler subnetHandler;\n\n   private StringBuilder currentText = new StringBuilder();\n   private boolean inSubnetSet;\n   private boolean inTagSet;\n   private boolean inIpv6CidrBlockAssociationSet;\n   private Builder<Subnet> subnets = ImmutableSet.<Subnet> builder();\n\n   @Inject\n   public DescribeSubnetsResponseHandler(SubnetHandler subnetHandler) {\n      this.subnetHandler = subnetHandler;\n   }\n\n   @Override\n   public FluentIterable<Subnet> getResult() {\n      return FluentIterable.from(subnets.build());\n   }\n\n   @Override\n   public void startElement(String url, String name, String qName, Attributes attributes) {\n      if (equalsOrSuffix(qName, \"subnetSet\")) {\n         inSubnetSet = true;\n      } else if (inSubnetSet) {\n         if (equalsOrSuffix(qName, \"tagSet\")) {\n            inTagSet = true;\n         } else if (equalsOrSuffix(qName, \"ipv6CidrBlockAssociationSet\")) {\n            inIpv6CidrBlockAssociationSet = true;\n         }\n         subnetHandler.startElement(url, name, qName, attributes);\n      }\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) {\n      if (equalsOrSuffix(qName, \"subnetSet\")) {\n         inSubnetSet = false;\n      } else if (equalsOrSuffix(qName, \"tagSet\")) {\n         inTagSet = false;\n         subnetHandler.endElement(uri, name, qName);\n      } else if (equalsOrSuffix(qName, \"ipv6CidrBlockAssociationSet\")) {\n         inIpv6CidrBlockAssociationSet = false;\n         subnetHandler.endElement(uri, name, qName);\n      } else if (equalsOrSuffix(qName, \"item\") && !inTagSet && !inIpv6CidrBlockAssociationSet) {\n         subnets.add(subnetHandler.getResult());\n      } else if (inSubnetSet) {\n         subnetHandler.endElement(uri, name, qName);\n      }\n\n      currentText.setLength(0);\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      if (inSubnetSet) {\n         subnetHandler.characters(ch, start, length);\n      } else {\n         currentText.append(ch, start, length);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/xml/DescribeTagsResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport org.jclouds.ec2.domain.Tag;\nimport org.jclouds.http.functions.ParseSax;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\nimport com.google.inject.Inject;\n\n/**\n * @see <a\n *      href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeTags.html\"\n *      >xml</a>\n */\npublic class DescribeTagsResponseHandler extends ParseSax.HandlerForGeneratedRequestWithResult<FluentIterable<Tag>> {\n\n   private final TagHandler tagHander;\n\n   private StringBuilder currentText = new StringBuilder();\n   private Builder<Tag> tags = ImmutableSet.<Tag> builder();\n   private boolean inTags;\n\n   @Inject\n   public DescribeTagsResponseHandler(TagHandler tagHander) {\n      this.tagHander = tagHander;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public FluentIterable<Tag> getResult() {\n      return FluentIterable.from(tags.build());\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void startElement(String url, String name, String qName, Attributes attributes) throws SAXException {\n      if (equalsOrSuffix(qName, \"tagSet\")) {\n         inTags = true;\n      }\n      if (inTags) {\n         tagHander.startElement(url, name, qName, attributes);\n      }\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void endElement(String uri, String name, String qName) throws SAXException {\n      if (equalsOrSuffix(qName, \"tagSet\")) {\n         inTags = false;\n      } else if (equalsOrSuffix(qName, \"item\")) {\n         tags.add(tagHander.getResult());\n      } else if (inTags) {\n         tagHander.endElement(uri, name, qName);\n      }\n      currentText.setLength(0);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      if (inTags) {\n         tagHander.characters(ch, start, length);\n      } else {\n         currentText.append(ch, start, length);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/xml/DescribeVolumesResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.ec2.domain.Volume;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.functions.ParseSax;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\n\nimport com.google.common.collect.Sets;\n\npublic class DescribeVolumesResponseHandler extends ParseSax.HandlerWithResult<Set<Volume>> {\n\n   private Set<Volume> volumes = Sets.newLinkedHashSet();\n   private final CreateVolumeResponseHandler volumeHandler;\n\n   private boolean inAttachmentSet;\n\n   @Inject\n   public DescribeVolumesResponseHandler(CreateVolumeResponseHandler volumeHandler) {\n      this.volumeHandler = volumeHandler;\n   }\n\n   public Set<Volume> getResult() {\n      return volumes;\n   }\n\n   @Override\n   public void startElement(String uri, String localName, String qName, Attributes attributes)\n            throws SAXException {\n      if (qName.equals(\"attachmentSet\")) {\n         inAttachmentSet = true;\n      }\n      volumeHandler.startElement(uri, localName, qName, attributes);\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) throws SAXException {\n      volumeHandler.endElement(uri, localName, qName);\n      if (qName.equals(\"attachmentSet\")) {\n         inAttachmentSet = false;\n      } else if (qName.equals(\"item\") && !inAttachmentSet) {\n         this.volumes.add(volumeHandler.getResult());\n      }\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      volumeHandler.characters(ch, start, length);\n   }\n\n   @Override\n   public DescribeVolumesResponseHandler setContext(HttpRequest request) {\n      volumeHandler.setContext(request);\n      super.setContext(request);\n      return this;\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/xml/GetConsoleOutputResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.io.BaseEncoding.base64;\n\nimport java.util.regex.Pattern;\n\nimport org.jclouds.http.functions.ParseSax;\n\n/**\n * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-GetConsoleOutput.html\">\n *       ApiReference query GetConsoleOutput</a>\n */\npublic class GetConsoleOutputResponseHandler extends ParseSax.HandlerWithResult<String> {\n\n    private StringBuilder currentText = new StringBuilder();\n    private String output;\n\n    @Override\n    public String getResult() {\n       return output;\n    }\n\n    private static final Pattern whitespace = Pattern.compile(\"\\\\s\");\n\n    @Override\n    public void endElement(String uri, String name, String qName) {\n       if (qName.equalsIgnoreCase(\"output\")) {\n          this.output = new String(base64().decode(whitespace.matcher(currentText).replaceAll(\"\")), UTF_8);\n       }\n       currentText.setLength(0);\n    }\n\n    @Override\n    public void characters(char[] ch, int start, int length) {\n       currentText.append(ch, start, length);\n    }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/xml/GetPasswordDataResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.ec2.domain.PasswordData;\nimport org.jclouds.http.functions.ParseSax;\n\npublic class GetPasswordDataResponseHandler extends ParseSax.HandlerWithResult<PasswordData> {\n   protected final DateService dateService;\n\n\n   @Inject\n   protected GetPasswordDataResponseHandler(DateService dateService) {\n      this.dateService = dateService;\n   }\n\n   private StringBuilder currentText = new StringBuilder();\n   private PasswordData.Builder builder = PasswordData.builder();\n\n   @Override\n   public PasswordData getResult() {\n      return builder.build();\n   }\n\n   public void endElement(String uri, String name, String qName) {\n      if (qName.equals(\"instanceId\")) {\n         builder.instanceId(currentText.toString().trim());\n      } else if (qName.equals(\"timestamp\")) {\n         builder.timestamp(dateService.iso8601DateOrSecondsDateParse(currentText.toString().trim()));\n      } else if (qName.equals(\"passwordData\")) {\n         builder.passwordData(currentText.toString().trim());\n      }\n      currentText.setLength(0);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/xml/ImageIdHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport org.jclouds.http.functions.ParseSax;\n\n/**\n * \n * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-query-RegisterImage.html\"\n *      />\n * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-query-CreateImage.html\"\n *      />\n */\npublic class ImageIdHandler extends ParseSax.HandlerWithResult<String> {\n\n   private StringBuilder currentText = new StringBuilder();\n   private String imageId;\n\n   public String getResult() {\n      return imageId;\n   }\n\n   public void endElement(String uri, String name, String qName) {\n\n      if (qName.equalsIgnoreCase(\"ImageId\")) {\n         this.imageId = currentText.toString().trim();\n      }\n      currentText.setLength(0);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/xml/InstanceInitiatedShutdownBehaviorHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport org.jclouds.ec2.domain.Volume.InstanceInitiatedShutdownBehavior;\nimport org.jclouds.http.functions.ParseSax;\n\n/**\n * \n * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-query-DescribeInstanceAttribute.html\"\n *      />\n */\npublic class InstanceInitiatedShutdownBehaviorHandler extends\n         ParseSax.HandlerWithResult<InstanceInitiatedShutdownBehavior> {\n\n   private StringBuilder currentText = new StringBuilder();\n   private InstanceInitiatedShutdownBehavior behavior;\n\n   public InstanceInitiatedShutdownBehavior getResult() {\n      return behavior;\n   }\n\n   public void endElement(String uri, String name, String qName) {\n      if (qName.equalsIgnoreCase(\"value\")) {\n         this.behavior = InstanceInitiatedShutdownBehavior.fromValue(currentText.toString().trim());\n      }\n      currentText.setLength(0);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/xml/InstanceStateChangeHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.ec2.domain.InstanceState;\nimport org.jclouds.ec2.domain.InstanceStateChange;\nimport org.jclouds.http.functions.ParseSax.HandlerForGeneratedRequestWithResult;\nimport org.jclouds.location.Region;\nimport org.xml.sax.Attributes;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.Sets;\n\n/**\n * Parses the following XML document:\n * <p/>\n * TerminateInstancesResponse xmlns=\"http://ec2.amazonaws.com/doc/2010-08-31/\"\n * StartInstancesResponse xmlns=\"http://ec2.amazonaws.com/doc/2010-08-31/\" StopInstancesResponse\n * xmlns=\"http://ec2.amazonaws.com/doc/2010-08-31/\"\n * \n * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-ItemType-TerminateInstancesResponseInfoType.html\"\n *      />\n * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-ItemType-StartInstancesResponseInfoType.html\"\n *      />\n * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-ItemType-StopInstancesResponseInfoType.html\"\n *      />\n */\npublic class InstanceStateChangeHandler extends\n         HandlerForGeneratedRequestWithResult<Set<InstanceStateChange>> {\n   private StringBuilder currentText = new StringBuilder();\n   @Inject\n   @Region\n   Supplier<String> defaultRegion;\n\n   Set<InstanceStateChange> instances = Sets.newLinkedHashSet();\n   private InstanceState shutdownState;\n   private InstanceState previousState;\n   private String instanceId;\n\n   private boolean inCurrentState;\n\n   private boolean inPreviousState;\n\n   @Override\n   public Set<InstanceStateChange> getResult() {\n      return instances;\n   }\n\n   public void startElement(String uri, String name, String qName, Attributes attrs) {\n      if (qName.equals(\"shutdownState\") || qName.equals(\"currentState\")) {\n         inCurrentState = true;\n      } else if (qName.equals(\"previousState\")) {\n         inPreviousState = true;\n      }\n   }\n\n   public void endElement(String uri, String name, String qName) {\n\n      if (qName.equals(\"instanceId\")) {\n         this.instanceId = currentOrNull();\n      } else if (qName.equals(\"shutdownState\") || qName.equals(\"currentState\")) {\n         inCurrentState = false;\n      } else if (qName.equals(\"previousState\")) {\n         inPreviousState = false;\n      } else if (qName.equals(\"name\")) {\n         if (inCurrentState) {\n            shutdownState = InstanceState.fromValue(currentOrNull());\n         } else if (inPreviousState) {\n            previousState = InstanceState.fromValue(currentOrNull());\n         }\n      } else if (qName.equals(\"item\")) {\n         String region = AWSUtils.findRegionInArgsOrNull(getRequest());\n         if (region == null)\n            region = defaultRegion.get();\n         instances.add(new InstanceStateChange(region, instanceId, shutdownState, previousState));\n         this.instanceId = null;\n         this.shutdownState = null;\n         this.previousState = null;\n      }\n\n      currentText.setLength(0);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n\n   protected String currentOrNull() {\n      String returnVal = currentText.toString().trim();\n      return returnVal.equals(\"\") ? null : returnVal;\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/xml/InstanceTypeHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport org.jclouds.http.functions.ParseSax;\n\n/**\n * \n * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-query-DescribeInstanceAttribute.html\"\n *      />\n */\npublic class InstanceTypeHandler extends\n         ParseSax.HandlerWithResult<String> {\n\n   private StringBuilder currentText = new StringBuilder();\n   private String type;\n\n   public String getResult() {\n      return type;\n   }\n\n   public void endElement(String uri, String name, String qName) {\n      if (qName.equalsIgnoreCase(\"value\")) {\n         this.type = currentText.toString().trim();\n      }\n      currentText.setLength(0);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/xml/IpPermissionHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport static org.jclouds.util.SaxUtils.currentOrNull;\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.net.domain.IpPermission;\nimport org.jclouds.net.domain.IpProtocol;\nimport org.xml.sax.SAXException;\n\npublic class IpPermissionHandler extends ParseSax.HandlerForGeneratedRequestWithResult<IpPermission> {\n\n   private StringBuilder currentText = new StringBuilder();\n   private IpPermission.Builder builder = IpPermission.builder();\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public IpPermission getResult() {\n      try {\n         return builder.build();\n      } finally {\n         builder = IpPermission.builder();\n      }\n   }\n\n   private String userId;\n   private String groupId;\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void endElement(String uri, String name, String qName) throws SAXException {\n      if (equalsOrSuffix(qName, \"ipProtocol\")) {\n         // Algorete: ipProtocol can be an empty tag on EC2 clone (e.g.\n         // OpenStack EC2)\n         builder.ipProtocol(IpProtocol.fromValue(currentOrNegative(currentText)));\n      } else if (equalsOrSuffix(qName, \"fromPort\")) {\n         // Algorete: fromPort can be an empty tag on EC2 clone (e.g. OpenStack\n         // EC2)\n         builder.fromPort(Integer.parseInt(currentOrNegative(currentText)));\n      } else if (equalsOrSuffix(qName, \"toPort\")) {\n         // Algorete: toPort can be an empty tag on EC2 clone (e.g. OpenStack\n         // EC2)\n         builder.toPort(Integer.parseInt(currentOrNegative(currentText)));\n      } else if (equalsOrSuffix(qName, \"cidrIp\")) {\n         builder.cidrBlock(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"userId\")) {\n         this.userId = currentOrNull(currentText);\n      } else if (equalsOrSuffix(qName, \"groupName\") || equalsOrSuffix(qName, \"groupId\")) {\n         this.groupId = currentOrNull(currentText);\n      } else if (equalsOrSuffix(qName, \"item\")) {\n         if (userId != null && groupId != null)\n            builder.tenantIdGroupNamePair(userId, groupId);\n         userId = groupId = null;\n      }\n      currentText.setLength(0);\n   }\n\n   private static String currentOrNegative(StringBuilder currentText) {\n      String returnVal = currentText.toString().trim();\n      return returnVal.equals(\"\") ? \"-1\" : returnVal;\n   }\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/xml/KeyPairResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport static org.jclouds.util.SaxUtils.currentOrNull;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.ec2.domain.KeyPair;\nimport org.jclouds.ec2.domain.KeyPair.Builder;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.location.Region;\n\nimport com.google.common.base.Supplier;\n\n/**\n * \n * @see <a href=\n *      \"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreateKeyPair.html\"\n *      />\n */\npublic class KeyPairResponseHandler extends ParseSax.HandlerForGeneratedRequestWithResult<KeyPair> {\n   private final Supplier<String> defaultRegion;\n   private Builder builder;\n\n   @Inject\n   public KeyPairResponseHandler(@Region Supplier<String> defaultRegion) {\n      this.defaultRegion = defaultRegion;\n   }\n\n   @Override\n   public void startDocument() {\n      builder = KeyPair.builder().region(defaultRegion.get());\n   }\n\n   private StringBuilder currentText = new StringBuilder();\n\n   public KeyPair getResult() {\n      String region = AWSUtils.findRegionInArgsOrNull(getRequest());\n      if (region != null)\n         builder.region(region);\n      try {\n         return builder.build();\n      } finally {\n         builder = KeyPair.builder().region(defaultRegion.get());\n      }\n   }\n\n   public void endElement(String uri, String name, String qName) {\n      if (qName.equals(\"keyFingerprint\")) {\n         builder.sha1OfPrivateKey(currentOrNull(currentText));\n      } else if (qName.equals(\"keyMaterial\")) {\n         builder.keyMaterial(currentOrNull(currentText));\n      } else if (qName.equals(\"keyName\")) {\n         builder.keyName(currentOrNull(currentText));\n      }\n      currentText.setLength(0);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/xml/PermissionHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport java.util.Set;\n\nimport org.jclouds.ec2.domain.Permission;\nimport org.jclouds.http.functions.ParseSax;\n\nimport com.google.common.collect.Sets;\n\n/**\n * \n * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-query-DescribeImageAttribute.html\"\n *      />\n */\npublic class PermissionHandler extends ParseSax.HandlerWithResult<Permission> {\n\n   private StringBuilder currentText = new StringBuilder();\n   private Set<String> userIds = Sets.newHashSet();\n   private Set<String> groups = Sets.newHashSet();\n\n   public Permission getResult() {\n      return new Permission(userIds, groups);\n   }\n\n   public void endElement(String uri, String name, String qName) {\n\n      if (qName.equalsIgnoreCase(\"group\")) {\n         groups.add(currentText.toString().trim());\n      } else if (qName.equalsIgnoreCase(\"userId\")) {\n         userIds.add(currentText.toString().trim());\n      }\n      currentText.setLength(0);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/xml/RunInstancesResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.ec2.domain.Reservation;\nimport org.jclouds.ec2.domain.RunningInstance;\nimport org.jclouds.location.Region;\n\nimport com.google.common.base.Supplier;\n\n/**\n * Parses the following XML document:\n * <p/>\n * RunInstancesResponse xmlns=\"http:\n * \n * @see <a href=\"http: />\n */\npublic class RunInstancesResponseHandler extends BaseReservationHandler<Reservation<? extends RunningInstance>> {\n\n   @Inject\n   public RunInstancesResponseHandler(DateService dateService, @Region Supplier<String> defaultRegion) {\n      super(dateService, defaultRegion);\n   }\n\n   @Override\n   public Reservation<? extends RunningInstance> getResult() {\n      return newReservation();\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/xml/SecurityGroupHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport static org.jclouds.util.SaxUtils.currentOrNull;\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.ec2.domain.SecurityGroup;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.http.functions.ParseSax.HandlerForGeneratedRequestWithResult;\nimport org.jclouds.location.Region;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\n\nimport com.google.common.base.Supplier;\nimport com.google.inject.Inject;\n\npublic class SecurityGroupHandler extends ParseSax.HandlerForGeneratedRequestWithResult<SecurityGroup> {\n\n   protected final IpPermissionHandler ipPermissionHandler;\n   protected final Supplier<String> defaultRegion;\n\n   protected StringBuilder currentText = new StringBuilder();\n   protected SecurityGroup.Builder<?> builder;\n   protected boolean inIpPermissions;\n\n   protected int itemDepth;\n\n   protected String region;\n\n   @Inject\n   public SecurityGroupHandler(IpPermissionHandler ipPermissionHandler, @Region Supplier<String> defaultRegion) {\n      this.ipPermissionHandler = ipPermissionHandler;\n      this.defaultRegion = defaultRegion;\n   }\n\n   protected SecurityGroup.Builder<?> builder() {\n      return SecurityGroup.builder().region(region);\n   }\n\n   @Override\n   public HandlerForGeneratedRequestWithResult<SecurityGroup> setContext(HttpRequest request) {\n      region = AWSUtils.findRegionInArgsOrNull(GeneratedHttpRequest.class.cast(request));\n      if (region == null)\n         region = defaultRegion.get();\n      builder = builder();\n      return super.setContext(request);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public SecurityGroup getResult() {\n      try {\n         return builder.build();\n      } finally {\n         builder = builder();\n      }\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void startElement(String url, String name, String qName, Attributes attributes) throws SAXException {\n      if (equalsOrSuffix(qName, \"item\")) {\n         itemDepth++;\n      } else if (equalsOrSuffix(qName, \"ipPermissions\")) {\n         inIpPermissions = true;\n      }\n      if (inIpPermissions) {\n         ipPermissionHandler.startElement(url, name, qName, attributes);\n      }\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void endElement(String uri, String name, String qName) throws SAXException {\n      if (equalsOrSuffix(qName, \"item\")) {\n         endItem(uri, name, qName);\n         itemDepth--;\n      } else if (equalsOrSuffix(qName, \"ipPermissions\")) {\n         inIpPermissions = false;\n         itemDepth = 0;\n      } else if (inIpPermissions) {\n         ipPermissionHandler.endElement(uri, name, qName);\n      } else if (equalsOrSuffix(qName, \"groupName\")) {\n         builder.name(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"groupId\")) {\n         builder.id(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"ownerId\")) {\n         builder.ownerId(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"groupDescription\")) {\n         builder.description(currentOrNull(currentText));\n      }\n      currentText.setLength(0);\n   }\n\n   protected void endItem(String uri, String name, String qName) throws SAXException {\n      if (inIpPermissions) {\n         if (itemDepth == 2)\n            builder.ipPermission(ipPermissionHandler.getResult());\n         else\n            ipPermissionHandler.endElement(uri, name, qName);\n      }\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      if (inIpPermissions) {\n         ipPermissionHandler.characters(ch, start, length);\n      } else {\n         currentText.append(ch, start, length);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/xml/SnapshotHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport java.util.Date;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.date.DateService;\nimport org.jclouds.ec2.domain.Snapshot;\nimport org.jclouds.ec2.domain.Snapshot.Status;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.location.Region;\n\nimport com.google.common.base.Supplier;\n\npublic class SnapshotHandler extends ParseSax.HandlerForGeneratedRequestWithResult<Snapshot> {\n   private StringBuilder currentText = new StringBuilder();\n\n   protected final DateService dateService;\n   protected final Supplier<String> defaultRegion;\n\n   private String id;\n   private String volumeId;\n   private int volumeSize;\n   private Status status;\n   private Date startTime;\n   private int progress;\n   private String ownerId;\n   private String description;\n   private String ownerAlias;\n\n   @Inject\n   public SnapshotHandler(DateService dateService, @Region Supplier<String> defaultRegion) {\n      this.dateService = dateService;\n      this.defaultRegion = defaultRegion;\n   }\n\n   public Snapshot getResult() {\n      String region = AWSUtils.findRegionInArgsOrNull(getRequest());\n      if (region == null)\n         region = defaultRegion.get();\n      Snapshot snapshot = new Snapshot(region, id, volumeId, volumeSize, status, startTime,\n               progress, ownerId, description, ownerAlias);\n      this.id = null;\n      this.volumeId = null;\n      this.volumeSize = 0;\n      this.status = null;\n      this.startTime = null;\n      this.progress = 0;\n      this.ownerId = null;\n      this.description = null;\n      this.ownerAlias = null;\n      return snapshot;\n   }\n\n   public void endElement(String uri, String name, String qName) {\n      if (qName.equals(\"snapshotId\")) {\n         id = currentText.toString().trim();\n      } else if (qName.equals(\"volumeId\")) {\n         volumeId = currentText.toString().trim();\n      } else if (qName.equals(\"volumeSize\")) {\n         volumeSize = Integer.parseInt(currentText.toString().trim());\n      } else if (qName.equals(\"status\")) {\n         status = Snapshot.Status.fromValue(currentText.toString().trim());\n      } else if (qName.equals(\"startTime\")) {\n         startTime = dateService.iso8601DateOrSecondsDateParse(currentText.toString().trim());\n      } else if (qName.equals(\"progress\")) {\n         String progressString = currentText.toString().trim();\n         if (!progressString.equals(\"\")) {\n            progressString = progressString.substring(0, progressString.length() - 1);\n            progress = Integer.parseInt(progressString);\n         }\n      } else if (qName.equals(\"ownerId\")) {\n         ownerId = currentText.toString().trim();\n      } else if (qName.equals(\"description\")) {\n         description = currentText.toString().trim();\n      } else if (qName.equals(\"ownerAlias\")) {\n         ownerAlias = currentText.toString().trim();\n      }\n      currentText.setLength(0);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/xml/StringValueHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport org.jclouds.http.functions.ParseSax;\n\n/**\n * \n * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-query-DescribeInstanceAttribute.html\"\n *      />\n */\npublic class StringValueHandler extends\n         ParseSax.HandlerWithResult<String> {\n\n   private StringBuilder currentText = new StringBuilder();\n   private String value;\n\n   public String getResult() {\n      return value;\n   }\n\n   public void endElement(String uri, String name, String qName) {\n      if (qName.equalsIgnoreCase(\"value\")) {\n         this.value = currentText.toString().trim();\n      }\n      currentText.setLength(0);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/xml/SubnetHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport static org.jclouds.util.SaxUtils.currentOrNull;\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.ec2.domain.Subnet;\nimport org.jclouds.http.functions.ParseSax;\nimport org.xml.sax.Attributes;\n\n/**\n * @see <a href=\"http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-ItemType-SubnetType.html\" >xml</a>\n */\npublic class SubnetHandler extends ParseSax.HandlerForGeneratedRequestWithResult<Subnet> {\n   private StringBuilder currentText = new StringBuilder();\n   private Subnet.Builder builder = Subnet.builder();\n   private final TagSetHandler tagSetHandler;\n   private boolean inTagSet;\n   private boolean inIpv6CidrBlockAssociationSet;\n\n   @Inject\n   public SubnetHandler(TagSetHandler tagSetHandler) {\n      this.tagSetHandler = tagSetHandler;\n   }\n\n   @Override\n   public Subnet getResult() {\n      try {\n         return builder.build();\n      } finally {\n         builder = Subnet.builder();\n      }\n   }\n\n   @Override\n   public void startElement(String uri, String name, String qName, Attributes attrs) {\n      if (equalsOrSuffix(qName, \"tagSet\")) {\n         inTagSet = true;\n      } else if (equalsOrSuffix(qName, \"ipv6CidrBlockAssociationSet\")) {\n         inIpv6CidrBlockAssociationSet = true;\n      }\n      if (inTagSet) {\n         tagSetHandler.startElement(uri, name, qName, attrs);\n      }\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) {\n      if (equalsOrSuffix(qName, \"ipv6CidrBlockAssociationSet\")) {\n         inIpv6CidrBlockAssociationSet = false;\n      }\n      if (inIpv6CidrBlockAssociationSet) {\n         return; // ignore contents (otherwise \"item\" and \"state\" will confuse us!\n      }\n      \n      if (equalsOrSuffix(qName, \"tagSet\")) {\n         inTagSet = false;\n         builder.tags(tagSetHandler.getResult());\n      } else if (inTagSet) {\n         tagSetHandler.endElement(uri, name, qName);\n      } else if (equalsOrSuffix(qName, \"subnetId\")) {\n         builder.subnetId(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"state\")) {\n         builder.subnetState(Subnet.State.fromValue(currentOrNull(currentText)));\n      } else if (equalsOrSuffix(qName, \"vpcId\")) {\n         builder.vpcId(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"cidrBlock\")) {\n         builder.cidrBlock(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"availableIpAddressCount\")) {\n         builder.availableIpAddressCount(Integer.parseInt(currentOrNull(currentText)));\n      } else if (equalsOrSuffix(qName, \"availabilityZone\")) {\n         builder.availabilityZone(currentOrNull(currentText));\n      }\n      currentText.setLength(0);\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      if (inTagSet) {\n         tagSetHandler.characters(ch, start, length);\n      } else {\n         currentText.append(ch, start, length);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/xml/TagHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport static org.jclouds.util.SaxUtils.currentOrNull;\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport org.jclouds.ec2.domain.Tag;\nimport org.jclouds.http.functions.ParseSax;\nimport org.xml.sax.SAXException;\n\nimport com.google.common.base.Strings;\n\n/**\n * @see <a\n *      href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeTags.html\"\n *      >xml</a>\n */\npublic class TagHandler extends ParseSax.HandlerForGeneratedRequestWithResult<Tag> {\n\n   private StringBuilder currentText = new StringBuilder();\n   private Tag.Builder builder = Tag.builder();\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Tag getResult() {\n      try {\n         return builder.build();\n      } finally {\n         builder = Tag.builder();\n      }\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void endElement(String uri, String name, String qName) throws SAXException {\n      if (equalsOrSuffix(qName, \"resourceId\")) {\n         builder.resourceId(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"resourceType\")) {\n         builder.resourceType(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"key\")) {\n         builder.key(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"value\")) {\n         // empty is same as not present\n         builder.value(Strings.emptyToNull(currentOrNull(currentText)));\n      }\n      currentText.setLength(0);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/xml/TagSetHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport static org.jclouds.util.SaxUtils.currentOrNull;\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport java.util.Map;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.xml.sax.Attributes;\n\nimport com.google.common.base.Strings;\nimport com.google.common.collect.ImmutableMap;\n\npublic class TagSetHandler extends ParseSax.HandlerForGeneratedRequestWithResult<Map<String, String>> {\n   private StringBuilder currentText = new StringBuilder();\n\n   private ImmutableMap.Builder<String, String> result;\n   private boolean inItem = false;\n   private String key;\n   private String value;\n\n   public Map<String, String> getResult() {\n      return result.build();\n   }\n\n   @Override\n   public void startElement(String uri, String localName, String qName, Attributes attributes) {\n      if (equalsOrSuffix(qName, \"tagSet\")) {\n         result = ImmutableMap.builder();\n      } else if (qName.equals(\"item\")) {\n         inItem = true;\n         key = null;\n         value = null;\n      }\n      currentText.setLength(0);\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) {\n      if (qName.equals(\"item\")) {\n         inItem = false;\n         if (key != null) {\n            result.put(key, Strings.nullToEmpty(value));\n         }\n      }\n      if (inItem) {\n         if (qName.equals(\"key\")) {\n            key = currentOrNull(currentText);\n         } else if (qName.equals(\"value\")) {\n            value = currentOrNull(currentText);\n         }\n      }\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/main/java/org/jclouds/ec2/xml/UnencodeStringValueHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.io.BaseEncoding.base64;\n\n/**\n * \n * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-query-DescribeInstanceAttribute.html\"\n *      />\n */\npublic class UnencodeStringValueHandler extends StringValueHandler {\n\n   @Override\n   public String getResult() {\n      String result = super.getResult();\n      if (result != null)\n         result = new String(base64().decode(result), UTF_8);\n      return result;\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/CloudApplicationArchitecturesEC2ApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2;\n\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static org.jclouds.ec2.options.RunInstancesOptions.Builder.asType;\nimport static org.jclouds.util.Predicates2.retry;\nimport static org.jclouds.scriptbuilder.domain.Statements.exec;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.fail;\n\nimport java.io.IOException;\nimport java.net.UnknownHostException;\nimport java.util.Map;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.TimeoutException;\n\nimport org.jclouds.aws.AWSResponseException;\nimport org.jclouds.compute.domain.ExecResponse;\nimport org.jclouds.compute.internal.BaseComputeServiceContextLiveTest;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.ec2.domain.BlockDevice;\nimport org.jclouds.ec2.domain.Image.EbsBlockDevice;\nimport org.jclouds.ec2.domain.InstanceState;\nimport org.jclouds.ec2.domain.InstanceType;\nimport org.jclouds.ec2.domain.KeyPair;\nimport org.jclouds.ec2.domain.PublicIpInstanceIdPair;\nimport org.jclouds.ec2.domain.Reservation;\nimport org.jclouds.ec2.domain.RunningInstance;\nimport org.jclouds.ec2.domain.Volume.InstanceInitiatedShutdownBehavior;\nimport org.jclouds.ec2.predicates.InstanceHasIpAddress;\nimport org.jclouds.ec2.predicates.InstanceStateRunning;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.net.domain.IpProtocol;\nimport org.jclouds.predicates.SocketOpen;\nimport org.jclouds.scriptbuilder.ScriptBuilder;\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.jclouds.ssh.SshClient;\nimport org.jclouds.ssh.SshException;\nimport org.testng.annotations.AfterTest;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Maps;\nimport com.google.common.net.HostAndPort;\nimport com.google.inject.Injector;\n\n/**\n * Follows the book Cloud Application Architectures ISBN: 978-0-596-15636-7\n * <p/>\n * adds in functionality to boot a lamp instance: http://alestic.com/2009/06/ec2-user-data-scripts\n * <p/>\n * Generally disabled, as it incurs higher fees.\n */\n@Test(groups = \"live\", enabled = false, singleThreaded = true, testName = \"CloudApplicationArchitecturesEC2ApiLiveTest\")\npublic class CloudApplicationArchitecturesEC2ApiLiveTest extends BaseComputeServiceContextLiveTest {\n   public CloudApplicationArchitecturesEC2ApiLiveTest() {\n      provider = \"ec2\";\n   }\n\n   private EC2Api client;\n   protected SshClient.Factory sshFactory;\n   private String instancePrefix = System.getProperty(\"user.name\") + \".ec2\";\n   private KeyPair keyPair;\n   private String securityGroupName;\n   private String instanceId;\n   private String address;\n\n   private Predicate<HostAndPort> socketTester;\n   private Predicate<RunningInstance> hasIpTester;\n   private Predicate<RunningInstance> runningTester;\n\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   public void setupContext() {\n      super.setupContext();\n      Injector injector = view.utils().injector();\n      client = injector.getInstance(EC2Api.class);\n      sshFactory = injector.getInstance(SshClient.Factory.class);\n      runningTester = retry(new InstanceStateRunning(client), 180, 5, SECONDS);\n      hasIpTester = retry(new InstanceHasIpAddress(client), 180, 5, SECONDS);\n      SocketOpen socketOpen = injector.getInstance(SocketOpen.class);\n      socketTester = retry(socketOpen, 180, 1, SECONDS);\n   }\n\n   @Test(enabled = false)\n   void testCreateSecurityGroupIngressCidr() throws InterruptedException, ExecutionException, TimeoutException {\n      securityGroupName = instancePrefix + \"ingress\";\n\n      try {\n         client.getSecurityGroupApi().get().deleteSecurityGroupInRegion(null, securityGroupName);\n      } catch (Exception e) {\n      }\n\n      client.getSecurityGroupApi().get().createSecurityGroupInRegion(null, securityGroupName, securityGroupName);\n      for (int port : new int[] { 80, 443, 22 }) {\n         client.getSecurityGroupApi().get().authorizeSecurityGroupIngressInRegion(null, securityGroupName,\n               IpProtocol.TCP, port, port, \"0.0.0.0/0\");\n      }\n   }\n\n   @Test(enabled = false)\n   void testCreateKeyPair() throws InterruptedException, ExecutionException, TimeoutException {\n      String keyName = instancePrefix + \"1\";\n      try {\n         client.getKeyPairApi().get().deleteKeyPairInRegion(null, keyName);\n      } catch (Exception e) {\n\n      }\n      client.getKeyPairApi().get().deleteKeyPairInRegion(null, keyName);\n\n      keyPair = client.getKeyPairApi().get().createKeyPairInRegion(null, keyName);\n      assertNotNull(keyPair);\n      assertNotNull(keyPair.getKeyMaterial());\n      assertNotNull(keyPair.getSha1OfPrivateKey());\n      assertEquals(keyPair.getKeyName(), keyName);\n   }\n\n   @Test(enabled = false, dependsOnMethods = { \"testCreateKeyPair\", \"testCreateSecurityGroupIngressCidr\" })\n   public void testCreateRunningInstance() throws Exception {\n      String script = new ScriptBuilder() // lamp install script\n            .addStatement(exec(\"runurl run.alestic.com/apt/upgrade\"))//\n            .addStatement(exec(\"runurl run.alestic.com/install/lamp\"))//\n            .render(OsFamily.UNIX);\n\n      RunningInstance instance = null;\n      while (instance == null) {\n         try {\n\n            System.out.printf(\"%d: running instance%n\", System.currentTimeMillis());\n            Reservation<? extends RunningInstance> reservation = client.getInstanceApi().get().runInstancesInRegion(\n                  null, null, // allow\n                  // ec2\n                  // to\n                  // chose\n                  // an\n                  // availability\n                  // zone\n                  \"ami-ccf615a5\", // alestic ami allows auto-invoke of\n                  // user data scripts\n                  1, // minimum instances\n                  1, // maximum instances\n                  asType(InstanceType.M1_SMALL) // smallest instance size\n                        .withKeyName(keyPair.getKeyName()) // key I\n                        // created\n                        // above\n                        .withSecurityGroup(securityGroupName) // group I\n                        // created\n                        // above\n                        .withUserData(script.getBytes())); // script to\n            // run as root\n\n            instance = Iterables.getOnlyElement(reservation);\n\n         } catch (HttpResponseException htpe) {\n            if (htpe.getResponse().getStatusCode() == 400)\n               continue;\n            throw htpe;\n         }\n      }\n      assertNotNull(instance.getId());\n      instanceId = instance.getId();\n      assertEquals(instance.getInstanceState(), InstanceState.PENDING);\n      instance = blockUntilWeCanSshIntoInstance(instance);\n\n      verifyInstanceProperties(script);\n      tryToChangeStuff();\n      sshPing(instance);\n      System.out.printf(\"%d: %s ssh connection made%n\", System.currentTimeMillis(), instanceId);\n\n   }\n\n   private void verifyInstanceProperties(String script) {\n      assertEquals(script, client.getInstanceApi().get().getUserDataForInstanceInRegion(null, instanceId));\n\n      assertEquals(null, client.getInstanceApi().get().getRootDeviceNameForInstanceInRegion(null, instanceId));\n\n      assert client.getInstanceApi().get().getRamdiskForInstanceInRegion(null, instanceId).startsWith(\"ari-\");\n\n      assertEquals(false, client.getInstanceApi().get().isApiTerminationDisabledForInstanceInRegion(null, instanceId));\n\n      assert client.getInstanceApi().get().getKernelForInstanceInRegion(null, instanceId).startsWith(\"aki-\");\n\n      assertEquals(InstanceType.M1_SMALL,\n            client.getInstanceApi().get().getInstanceTypeForInstanceInRegion(null, instanceId));\n\n      assertEquals(InstanceInitiatedShutdownBehavior.TERMINATE, client.getInstanceApi().get()\n            .getInstanceInitiatedShutdownBehaviorForInstanceInRegion(null, instanceId));\n\n      assertEquals(ImmutableMap.<String, EbsBlockDevice> of(), client.getInstanceApi().get()\n            .getBlockDeviceMappingForInstanceInRegion(null, instanceId));\n   }\n\n   private void setApiTerminationDisabledForInstanceInRegion() {\n      client.getInstanceApi().get().setApiTerminationDisabledForInstanceInRegion(null, instanceId, true);\n      assertEquals(true, client.getInstanceApi().get().isApiTerminationDisabledForInstanceInRegion(null, instanceId));\n      client.getInstanceApi().get().setApiTerminationDisabledForInstanceInRegion(null, instanceId, false);\n      assertEquals(false, client.getInstanceApi().get().isApiTerminationDisabledForInstanceInRegion(null, instanceId));\n   }\n\n   private void tryToChangeStuff() {\n      setApiTerminationDisabledForInstanceInRegion();\n      setUserDataForInstanceInRegion();\n      setRamdiskForInstanceInRegion();\n      setKernelForInstanceInRegion();\n      setInstanceTypeForInstanceInRegion();\n      setInstanceInitiatedShutdownBehaviorForInstanceInRegion();\n      setBlockDeviceMappingForInstanceInRegion();\n   }\n\n   private void setUserDataForInstanceInRegion() {\n      try {\n         client.getInstanceApi().get().setUserDataForInstanceInRegion(null, instanceId, \"test\".getBytes());\n         fail(\"shouldn't be allowed, as instance needs to be stopped\");\n      } catch (AWSResponseException e) {\n         assertEquals(\"IncorrectInstanceState\", e.getError().getCode());\n      }\n   }\n\n   private void setRamdiskForInstanceInRegion() {\n      try {\n         String ramdisk = client.getInstanceApi().get().getRamdiskForInstanceInRegion(null, instanceId);\n         client.getInstanceApi().get().setRamdiskForInstanceInRegion(null, instanceId, ramdisk);\n         fail(\"shouldn't be allowed, as instance needs to be stopped\");\n      } catch (AWSResponseException e) {\n         assertEquals(\"IncorrectInstanceState\", e.getError().getCode());\n      }\n   }\n\n   private void setKernelForInstanceInRegion() {\n      try {\n         String oldKernel = client.getInstanceApi().get().getKernelForInstanceInRegion(null, instanceId);\n         client.getInstanceApi().get().setKernelForInstanceInRegion(null, instanceId, oldKernel);\n         fail(\"shouldn't be allowed, as instance needs to be stopped\");\n      } catch (AWSResponseException e) {\n         assertEquals(\"IncorrectInstanceState\", e.getError().getCode());\n      }\n   }\n\n   private void setInstanceTypeForInstanceInRegion() {\n      try {\n         client.getInstanceApi().get().setInstanceTypeForInstanceInRegion(null, instanceId, InstanceType.C1_MEDIUM);\n         fail(\"shouldn't be allowed, as instance needs to be stopped\");\n      } catch (AWSResponseException e) {\n         assertEquals(\"IncorrectInstanceState\", e.getError().getCode());\n      }\n   }\n\n   private void setBlockDeviceMappingForInstanceInRegion() {\n      Map<String, BlockDevice> mapping = Maps.newLinkedHashMap();\n      try {\n         client.getInstanceApi().get().setBlockDeviceMappingForInstanceInRegion(null, instanceId, mapping);\n         fail(\"shouldn't be allowed, as instance needs to be ebs based-ami\");\n      } catch (AWSResponseException e) {\n         assertEquals(\"InvalidParameterCombination\", e.getError().getCode());\n      }\n   }\n\n   private void setInstanceInitiatedShutdownBehaviorForInstanceInRegion() {\n      try {\n         client.getInstanceApi().get().setInstanceInitiatedShutdownBehaviorForInstanceInRegion(null, instanceId,\n               InstanceInitiatedShutdownBehavior.STOP);\n         fail(\"shouldn't be allowed, as instance needs to be ebs based-ami\");\n      } catch (AWSResponseException e) {\n         assertEquals(\"UnsupportedInstanceAttribute\", e.getError().getCode());\n      }\n   }\n\n   @Test(enabled = false, dependsOnMethods = \"testCreateRunningInstance\")\n   void testReboot() throws InterruptedException, ExecutionException, TimeoutException, IOException {\n      RunningInstance instance = getInstance(instanceId);\n      System.out.printf(\"%d: %s rebooting instance %n\", System.currentTimeMillis(), instanceId);\n      client.getInstanceApi().get().rebootInstancesInRegion(null, instanceId);\n      Thread.sleep(1000);\n      instance = getInstance(instanceId);\n      blockUntilWeCanSshIntoInstance(instance);\n      SshClient ssh = sshFactory.create(HostAndPort.fromParts(instance.getIpAddress(), 22),\n            LoginCredentials.builder().user(\"root\").privateKey(keyPair.getKeyMaterial()).build());\n      try {\n         ssh.connect();\n         ExecResponse uptime = ssh.exec(\"uptime\");\n         assert uptime.getOutput().indexOf(\"0 min\") != -1 : \"reboot didn't work: \" + uptime;\n      } finally {\n         if (ssh != null)\n            ssh.disconnect();\n      }\n   }\n\n   @Test(enabled = false, dependsOnMethods = \"testReboot\")\n   void testElasticIpAddress() throws InterruptedException, ExecutionException, TimeoutException, IOException {\n      address = client.getElasticIPAddressApi().get().allocateAddressInRegion(null);\n      assertNotNull(address);\n\n      PublicIpInstanceIdPair compare = Iterables.getLast(client.getElasticIPAddressApi().get()\n            .describeAddressesInRegion(null, address));\n\n      assertEquals(compare.getPublicIp(), address);\n      assert compare.getInstanceId() == null;\n\n      client.getElasticIPAddressApi().get().associateAddressInRegion(null, address, instanceId);\n\n      compare = Iterables.getLast(client.getElasticIPAddressApi().get().describeAddressesInRegion(null, address));\n\n      assertEquals(compare.getPublicIp(), address);\n      assertEquals(compare.getInstanceId(), instanceId);\n\n      Reservation<? extends RunningInstance> reservation = Iterables.getOnlyElement(client.getInstanceApi().get()\n            .describeInstancesInRegion(null, instanceId));\n\n      assertNotNull(Iterables.getOnlyElement(reservation).getIpAddress());\n      assertNotEquals(address, Iterables.getOnlyElement(reservation).getIpAddress());\n\n      doCheckKey(address);\n\n      client.getElasticIPAddressApi().get().disassociateAddressInRegion(null, address);\n\n      compare = Iterables.getLast(client.getElasticIPAddressApi().get().describeAddressesInRegion(null, address));\n\n      assertEquals(compare.getPublicIp(), address);\n      assert compare.getInstanceId() == null;\n\n      reservation = Iterables.getOnlyElement(client.getInstanceApi().get().describeInstancesInRegion(null, instanceId));\n      // assert reservation.getRunningInstances().last().getIpAddress() == null;\n      // TODO\n   }\n\n   private RunningInstance blockUntilWeCanSshIntoInstance(RunningInstance instance) throws UnknownHostException {\n      System.out.printf(\"%d: %s awaiting instance to run %n\", System.currentTimeMillis(), instance.getId());\n      assert runningTester.apply(instance);\n\n      instance = getInstance(instance.getId());\n\n      System.out\n            .printf(\"%d: %s awaiting instance to have ip assigned %n\", System.currentTimeMillis(), instance.getId());\n      assert hasIpTester.apply(instance);\n\n      System.out.printf(\"%d: %s awaiting ssh service to start%n\", System.currentTimeMillis(), instance.getIpAddress());\n      assert socketTester.apply(HostAndPort.fromParts(instance.getIpAddress(), 22));\n\n      System.out.printf(\"%d: %s ssh service started%n\", System.currentTimeMillis(), instance.getDnsName());\n      sshPing(instance);\n      System.out.printf(\"%d: %s ssh connection made%n\", System.currentTimeMillis(), instance.getId());\n\n      System.out.printf(\"%d: %s awaiting http service to start%n\", System.currentTimeMillis(), instance.getIpAddress());\n      assert socketTester.apply(HostAndPort.fromParts(instance.getIpAddress(), 80));\n      System.out.printf(\"%d: %s http service started%n\", System.currentTimeMillis(), instance.getDnsName());\n      return instance;\n   }\n\n   private RunningInstance getInstance(String instanceId) {\n      // search my identity for the instance I just created\n      Reservation<? extends RunningInstance> reservation = Iterables.getOnlyElement(client.getInstanceApi().get()\n            .describeInstancesInRegion(null, instanceId)); // last parameter\n      // (ids) narrows the\n      // search\n\n      return Iterables.getOnlyElement(reservation);\n   }\n\n   /**\n    * this tests \"personality\" as the file looked up was sent during instance creation\n    * \n    * @throws UnknownHostException\n    */\n   private void sshPing(RunningInstance newDetails) throws UnknownHostException {\n      try {\n         doCheckKey(newDetails);\n      } catch (SshException e) {// try twice in case there is a network timeout\n         try {\n            Thread.sleep(10 * 1000);\n         } catch (InterruptedException e1) {\n         }\n         doCheckKey(newDetails);\n      }\n   }\n\n   private void doCheckKey(RunningInstance newDetails) throws UnknownHostException {\n      doCheckKey(newDetails.getIpAddress());\n   }\n\n   private void doCheckKey(String address) {\n      SshClient ssh = sshFactory.create(HostAndPort.fromParts(address, 22),\n            LoginCredentials.builder().user(\"root\").privateKey(keyPair.getKeyMaterial()).build());\n      try {\n         ssh.connect();\n         ExecResponse hello = ssh.exec(\"echo hello\");\n         assertEquals(hello.getOutput().trim(), \"hello\");\n      } finally {\n         if (ssh != null)\n            ssh.disconnect();\n      }\n   }\n\n   @AfterTest\n   void cleanup() throws InterruptedException, ExecutionException, TimeoutException {\n      if (address != null)\n         client.getElasticIPAddressApi().get().releaseAddressInRegion(null, address);\n      if (instanceId != null)\n         client.getInstanceApi().get().terminateInstancesInRegion(null, instanceId);\n      if (keyPair != null)\n         client.getKeyPairApi().get().deleteKeyPairInRegion(null, keyPair.getKeyName());\n      if (securityGroupName != null)\n         client.getSecurityGroupApi().get().deleteSecurityGroupInRegion(null, securityGroupName);\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/EBSBootEC2ApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2;\n\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static org.jclouds.ec2.options.CreateSnapshotOptions.Builder.withDescription;\nimport static org.jclouds.ec2.options.DescribeImagesOptions.Builder.imageIds;\nimport static org.jclouds.ec2.options.RegisterImageBackedByEbsOptions.Builder.withKernelId;\nimport static org.jclouds.ec2.options.RunInstancesOptions.Builder.withKeyName;\nimport static org.jclouds.util.Predicates2.retry;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.net.UnknownHostException;\nimport java.util.Map;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.TimeoutException;\n\nimport org.jclouds.aws.AWSResponseException;\nimport org.jclouds.compute.domain.ExecResponse;\nimport org.jclouds.compute.internal.BaseComputeServiceContextLiveTest;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.ec2.domain.Attachment;\nimport org.jclouds.ec2.domain.BlockDevice;\nimport org.jclouds.ec2.domain.Image;\nimport org.jclouds.ec2.domain.Image.Architecture;\nimport org.jclouds.ec2.domain.Image.ImageType;\nimport org.jclouds.ec2.domain.InstanceState;\nimport org.jclouds.ec2.domain.InstanceType;\nimport org.jclouds.ec2.domain.KeyPair;\nimport org.jclouds.ec2.domain.Reservation;\nimport org.jclouds.ec2.domain.RootDeviceType;\nimport org.jclouds.ec2.domain.RunningInstance;\nimport org.jclouds.ec2.domain.Snapshot;\nimport org.jclouds.ec2.domain.Volume;\nimport org.jclouds.ec2.domain.Volume.InstanceInitiatedShutdownBehavior;\nimport org.jclouds.ec2.predicates.InstanceStateRunning;\nimport org.jclouds.ec2.predicates.InstanceStateStopped;\nimport org.jclouds.ec2.predicates.InstanceStateTerminated;\nimport org.jclouds.ec2.predicates.SnapshotCompleted;\nimport org.jclouds.ec2.predicates.VolumeAttached;\nimport org.jclouds.ec2.predicates.VolumeAvailable;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.net.domain.IpProtocol;\nimport org.jclouds.predicates.SocketOpen;\nimport org.jclouds.scriptbuilder.InitScript;\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.jclouds.scriptbuilder.domain.Statements;\nimport org.jclouds.ssh.SshClient;\nimport org.jclouds.ssh.SshException;\nimport org.testng.annotations.AfterTest;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Maps;\nimport com.google.common.net.HostAndPort;\nimport com.google.inject.Injector;\n\n/**\n * Adapted from the following sources: {@link http://gist.github.com/249915}, {@link http\n * ://www.capsunlock.net/2009/12/create-ebs-boot-ami.html}\n * <p/>\n *\n * Generally disabled, as it incurs higher fees.\n */\n@Test(groups = \"live\", enabled = false, singleThreaded = true, testName = \"EBSBootEC2ApiLiveTest\")\npublic class EBSBootEC2ApiLiveTest extends BaseComputeServiceContextLiveTest {\n   public EBSBootEC2ApiLiveTest() {\n      provider = \"ec2\";\n   }\n\n   // TODO: parameterize\n   private static final String IMAGE_ID = \"ami-7e28ca17\";\n\n   // don't need a lot of space. 2GB should be more than enough for testing\n   private static final int VOLUME_SIZE = 2;\n   private static final String SCRIPT_END = \"----COMPLETE----\";\n   private static final String INSTANCE_PREFIX = System.getProperty(\"user.name\") + \".ec2ebs\";\n\n   private EC2Api client;\n   private SshClient.Factory sshFactory;\n\n   private KeyPair keyPair;\n   private String securityGroupName;\n\n   private Predicate<HostAndPort> socketTester;\n   private Predicate<Attachment> attachTester;\n   private Predicate<Volume> volumeTester;\n   private RunningInstance instance;\n   private Predicate<RunningInstance> runningTester;\n   private Predicate<RunningInstance> stoppedTester;\n   private Predicate<RunningInstance> terminatedTester;\n   private Volume volume;\n   private Predicate<Snapshot> snapshotTester;\n   private Snapshot snapshot;\n   private Image ebsImage;\n   private RunningInstance ebsInstance;\n   private Attachment attachment;\n   private String mkEbsBoot;\n\n   @Override\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   public void setupContext() {\n      super.setupContext();\n      Injector injector = view.utils().injector();\n      client = injector.getInstance(EC2Api.class);\n      sshFactory = injector.getInstance(SshClient.Factory.class);\n      SocketOpen socketOpen = injector.getInstance(SocketOpen.class);\n      socketTester = retry(socketOpen, 120, 1, SECONDS);\n\n      VolumeAvailable volumeAvailable = injector.getInstance(VolumeAvailable.class);\n      volumeTester = retry(volumeAvailable, 60, 1, SECONDS);\n\n      SnapshotCompleted snapshotCompleted = injector.getInstance(SnapshotCompleted.class);\n      snapshotTester = retry(snapshotCompleted, 120, 3, SECONDS);\n\n      VolumeAttached volumeAttached = injector.getInstance(VolumeAttached.class);\n      attachTester = retry(volumeAttached, 60, 1, SECONDS);\n\n      runningTester = retry(new InstanceStateRunning(client), 180, 5, SECONDS);\n\n      InstanceStateStopped instanceStateStopped = injector.getInstance(InstanceStateStopped.class);\n      stoppedTester = retry(instanceStateStopped, 60, 1, SECONDS);\n\n      InstanceStateTerminated instanceStateTerminated = injector.getInstance(InstanceStateTerminated.class);\n      terminatedTester = retry(instanceStateTerminated, 60, 1, SECONDS);\n\n      injector.injectMembers(socketOpen); // add logger\n   }\n\n   @Test(enabled = false)\n   void testCreateSecurityGroupIngressCidr() throws InterruptedException, ExecutionException, TimeoutException {\n      securityGroupName = INSTANCE_PREFIX + \"ingress\";\n\n      try {\n         client.getSecurityGroupApi().get().deleteSecurityGroupInRegion(null, securityGroupName);\n      } catch (Exception e) {\n      }\n\n      client.getSecurityGroupApi().get().createSecurityGroupInRegion(null, securityGroupName, securityGroupName);\n      client.getSecurityGroupApi().get().authorizeSecurityGroupIngressInRegion(null, securityGroupName, IpProtocol.TCP,\n            80, 80, \"0.0.0.0/0\");\n      client.getSecurityGroupApi().get().authorizeSecurityGroupIngressInRegion(null, securityGroupName, IpProtocol.TCP,\n            443, 443, \"0.0.0.0/0\");\n      client.getSecurityGroupApi().get().authorizeSecurityGroupIngressInRegion(null, securityGroupName, IpProtocol.TCP,\n            22, 22, \"0.0.0.0/0\");\n   }\n\n   @Test(enabled = false)\n   void testCreateKeyPair() {\n      String keyName = INSTANCE_PREFIX + \"1\";\n      try {\n         client.getKeyPairApi().get().deleteKeyPairInRegion(null, keyName);\n      } catch (Exception e) {\n\n      }\n\n      keyPair = client.getKeyPairApi().get().createKeyPairInRegion(null, keyName);\n      assertNotNull(keyPair);\n      assertNotNull(keyPair.getKeyMaterial());\n      assertNotNull(keyPair.getSha1OfPrivateKey());\n      assertEquals(keyPair.getKeyName(), keyName);\n   }\n\n   @Test(enabled = false, dependsOnMethods = { \"testCreateKeyPair\", \"testCreateSecurityGroupIngressCidr\" })\n   public void testCreateRunningInstance() throws Exception {\n      instance = createInstance(IMAGE_ID);\n   }\n\n   private RunningInstance createInstance(String imageId) throws UnknownHostException {\n      RunningInstance instance = null;\n      while (instance == null) {\n         try {\n            System.out.printf(\"%d: running instance%n\", System.currentTimeMillis());\n            Reservation<? extends RunningInstance> reservation = client.getInstanceApi().get().runInstancesInRegion(\n                  null, null, // allow ec2 to chose an availability zone\n                  imageId, 1, // minimum instances\n                  1, // maximum instances\n                  withKeyName(keyPair.getKeyName())  // key created above\n                        .asType(InstanceType.M1_SMALL)  // smallest instance size\n                        .withSecurityGroup(securityGroupName)); // group created above\n            instance = Iterables.getOnlyElement(reservation);\n         } catch (HttpResponseException htpe) {\n            if (htpe.getResponse().getStatusCode() == 400)\n               continue;\n            throw htpe;\n         }\n      }\n      assertNotNull(instance.getId());\n      assertEquals(instance.getInstanceState(), InstanceState.PENDING);\n      instance = blockUntilWeCanSshIntoInstance(instance);\n      return instance;\n   }\n\n   @Test(enabled = false, dependsOnMethods = \"testCreateRunningInstance\")\n   void testCreateAndAttachVolume() {\n      volume = client.getElasticBlockStoreApi().get().createVolumeInAvailabilityZone(instance.getAvailabilityZone(),\n            VOLUME_SIZE);\n      System.out.printf(\"%d: %s awaiting volume to become available%n\", System.currentTimeMillis(), volume.getId());\n\n      assert volumeTester.apply(volume);\n\n      Attachment attachment = client.getElasticBlockStoreApi().get().attachVolumeInRegion(instance.getRegion(),\n            volume.getId(), instance.getId(), \"/dev/sdh\");\n\n      System.out.printf(\"%d: %s awaiting attachment to complete%n\", System.currentTimeMillis(), attachment.getId());\n\n      assert attachTester.apply(attachment);\n      System.out.printf(\"%d: %s attachment complete%n\", System.currentTimeMillis(), attachment.getId());\n   }\n\n   // TODO use userData to do this, and make initbuilder an example for\n   // something else.\n   @BeforeTest\n   void makeScript() {\n\n      mkEbsBoot = InitScript.builder()\n            .name(\"mkebsboot\")\n            .home(\"/tmp\")\n            .logDir(\"/tmp/logs\")\n            .exportVariables(ImmutableMap.of(\"imageDir\", \"/mnt/tmp\", \"ebsDevice\", \"/dev/sdh\", \"ebsMountPoint\", \"/mnt/ebs\"))\n            .run(Statements\n                  .interpret(\n                        \"echo creating a filesystem and mounting the ebs volume\",\n                        \"{md} {varl}IMAGE_DIR{varr} {varl}EBS_MOUNT_POINT{varr}\",\n                        \"rm -rf {varl}IMAGE_DIR{varr}/*\",\n                        \"yes| mkfs -t ext3 {varl}EBS_DEVICE{varr} 2>&-\",\n                        \"mount {varl}EBS_DEVICE{varr} {varl}EBS_MOUNT_POINT{varr}\",\n                        \"echo making a local working copy of the boot disk\",\n                        \"rsync -ax --exclude /ubuntu/.bash_history --exclude /home/*/.bash_history --exclude /etc/ssh/ssh_host_* --exclude /etc/ssh/moduli --exclude /etc/udev/rules.d/*persistent-net.rules --exclude /var/lib/* --exclude=/mnt/* --exclude=/proc/* --exclude=/tmp/* --exclude=/dev/log / {varl}IMAGE_DIR{varr}\",\n                        \"echo preparing the local working copy\",\n                        \"touch {varl}IMAGE_DIR{varr}/etc/init.d/ec2-init-user-data\",\n                        \"echo copying the local working copy to the ebs mount\", \"{cd} {varl}IMAGE_DIR{varr}\",\n                        \"tar -cSf - * | tar xf - -C {varl}EBS_MOUNT_POINT{varr}\", \"echo size of ebs\",\n                        \"du -sk {varl}EBS_MOUNT_POINT{varr}\", \"echo size of source\", \"du -sk {varl}IMAGE_DIR{varr}\",\n                        \"rm -rf {varl}IMAGE_DIR{varr}/*\", \"umount {varl}EBS_MOUNT_POINT{varr}\", \"echo \" + SCRIPT_END)).build()\n            .render(OsFamily.UNIX);\n   }\n\n   @Test(enabled = false, dependsOnMethods = \"testCreateAndAttachVolume\")\n   void testBundleInstance() {\n      SshClient ssh = sshFactory.create(HostAndPort.fromParts(instance.getIpAddress(), 22),\n            LoginCredentials.builder().user(\"ubuntu\").privateKey(keyPair.getKeyMaterial()).build());\n      try {\n         ssh.connect();\n      } catch (SshException e) {// try twice in case there is a network timeout\n         try {\n            Thread.sleep(10 * 1000);\n         } catch (InterruptedException e1) {\n         }\n         ssh.connect();\n      }\n      try {\n         System.out.printf(\"%d: %s writing ebs script%n\", System.currentTimeMillis(), instance.getId());\n         String script = \"/tmp/mkebsboot-init.sh\";\n         ssh.put(script, Payloads.newStringPayload(mkEbsBoot));\n\n         System.out.printf(\"%d: %s launching ebs script%n\", System.currentTimeMillis(), instance.getId());\n         ssh.exec(\"chmod 755 \" + script);\n         ssh.exec(script + \" init\");\n         ExecResponse output = ssh.exec(\"sudo \" + script + \" start\");\n         System.out.println(output);\n         output = ssh.exec(script + \" status\");\n\n         assert !output.getOutput().trim().equals(\"\") : output;\n         Predicate<String> scriptTester = retry(new ScriptTester(ssh, SCRIPT_END), 600, 10, SECONDS);\n         scriptTester.apply(script);\n      } finally {\n         if (ssh != null)\n            ssh.disconnect();\n      }\n   }\n\n   public static class ScriptTester implements Predicate<String> {\n      private final SshClient ssh;\n      private final String endMatches;\n\n      public ScriptTester(SshClient ssh, String endMatches) {\n         this.ssh = ssh;\n         this.endMatches = endMatches;\n      }\n\n      @Override\n      public boolean apply(String script) {\n         System.out.printf(\"%d: %s testing status%n\", System.currentTimeMillis(), script);\n         ExecResponse output = ssh.exec(script + \" status\");\n         if (output.getOutput().trim().equals(\"\")) {\n            output = ssh.exec(script + \" tail\");\n            String stdout = output.getOutput().trim();\n            if (stdout.contains(endMatches)) {\n               return true;\n            } else {\n               output = ssh.exec(script + \" tailerr\");\n               String stderr = output.getOutput().trim();\n               throw new RuntimeException(String.format(\n                     \"script %s ended without token: stdout.log: [%s]; stderr.log: [%s]; \", script, stdout, stderr));\n            }\n         }\n         return false;\n      }\n\n   }\n\n   @Test(enabled = false, dependsOnMethods = \"testBundleInstance\")\n   void testAMIFromBundle() {\n      volume = Iterables.getOnlyElement(client.getElasticBlockStoreApi().get().describeVolumesInRegion(\n            volume.getRegion(), volume.getId()));\n      if (!volume.getAttachments().isEmpty()) {\n         // should be cleanly unmounted, so force is not necessary.\n         client.getElasticBlockStoreApi().get().detachVolumeInRegion(instance.getRegion(), volume.getId(), false);\n         System.out.printf(\"%d: %s awaiting detachment to complete%n\", System.currentTimeMillis(), volume.getId());\n         assert volumeTester.apply(volume);\n      } else {\n         attachment = null; // protect test closer so that it doesn't try to\n         // detach\n      }\n      snapshot = client.getElasticBlockStoreApi().get().createSnapshotInRegion(volume.getRegion(), volume.getId(),\n            withDescription(\"EBS Ubuntu Hardy\"));\n\n      System.out.printf(\"%d: %s awaiting snapshot to complete%n\", System.currentTimeMillis(), snapshot.getId());\n\n      assert snapshotTester.apply(snapshot);\n      Image image = Iterables.getOnlyElement(client.getAMIApi().get().describeImagesInRegion(snapshot.getRegion(),\n            imageIds(IMAGE_ID)));\n      String description = image.getDescription() == null ? \"jclouds\" : image.getDescription();\n\n      System.out.printf(\"%d: %s creating ami from snapshot%n\", System.currentTimeMillis(), snapshot.getId());\n\n      String amiId = client.getAMIApi().get().registerUnixImageBackedByEbsInRegion(\n            snapshot.getRegion(),\n            \"ebsboot-\" + image.getId(),\n            snapshot.getId(),\n            withKernelId(image.getKernelId()).withRamdisk(image.getRamdiskId()).withDescription(description)\n                  .asArchitecture(Architecture.I386));\n      try {\n         ebsImage = Iterables.getOnlyElement(client.getAMIApi().get().describeImagesInRegion(snapshot.getRegion(),\n               imageIds(amiId)));\n      } catch (AWSResponseException e) {\n         // TODO add a retry handler for this HTTP code 400 and the below error\n         if (e.getError().getCode().equals(\"InvalidAMIID.NotFound\"))\n            ebsImage = Iterables.getOnlyElement(client.getAMIApi().get().describeImagesInRegion(snapshot.getRegion(),\n                  imageIds(amiId)));\n         else\n            throw e;\n      }\n      verifyImage();\n   }\n\n   @Test(enabled = false, dependsOnMethods = { \"testAMIFromBundle\" })\n   public void testInstanceFromEBS() throws Exception {\n      System.out.printf(\"%d: %s creating instance from ebs-backed ami%n\", System.currentTimeMillis(), ebsImage.getId());\n\n      ebsInstance = createInstance(ebsImage.getId());\n\n      client.getInstanceApi().get().stopInstancesInRegion(ebsInstance.getRegion(), true, ebsInstance.getId());\n\n      System.out.printf(\"%d: %s awaiting instance to stop %n\", System.currentTimeMillis(), ebsInstance.getId());\n      stoppedTester.apply(ebsInstance);\n      tryToChangeStuff();\n      System.out.printf(\"%d: %s awaiting instance to start %n\", System.currentTimeMillis(), ebsInstance.getId());\n      client.getInstanceApi().get().startInstancesInRegion(ebsInstance.getRegion(), ebsInstance.getId());\n      ebsInstance = blockUntilWeCanSshIntoInstance(ebsInstance);\n   }\n\n   private void verifyImage() {\n      assertEquals(ebsImage.getImageType(), ImageType.MACHINE);\n      assertEquals(ebsImage.getRootDeviceType(), RootDeviceType.EBS);\n      assertEquals(ebsImage.getRootDeviceName(), \"/dev/sda1\");\n      assertEquals(ebsImage.getEbsBlockDevices().entrySet(),\n            ImmutableMap.of(\"/dev/sda1\", new Image.EbsBlockDevice(snapshot.getId(), VOLUME_SIZE, true, \"standard\", null, false)).entrySet());\n   }\n\n   private void tryToChangeStuff() {\n      setUserDataForInstanceInRegion();\n      setRamdiskForInstanceInRegion();\n      setKernelForInstanceInRegion();\n      setInstanceTypeForInstanceInRegion();\n      setInstanceInitiatedShutdownBehaviorForInstanceInRegion();\n      setBlockDeviceMappingForInstanceInRegion();\n   }\n\n   private void setUserDataForInstanceInRegion() {\n      client.getInstanceApi().get().setUserDataForInstanceInRegion(null, ebsInstance.getId(), \"test\".getBytes());\n      assertEquals(\"test\", client.getInstanceApi().get().getUserDataForInstanceInRegion(null, ebsInstance.getId()));\n   }\n\n   private void setRamdiskForInstanceInRegion() {\n      String ramdisk = client.getInstanceApi().get().getRamdiskForInstanceInRegion(null, ebsInstance.getId());\n      client.getInstanceApi().get().setRamdiskForInstanceInRegion(null, ebsInstance.getId(), ramdisk);\n      assertEquals(ramdisk, client.getInstanceApi().get().getRamdiskForInstanceInRegion(null, ebsInstance.getId()));\n   }\n\n   private void setKernelForInstanceInRegion() {\n      String oldKernel = client.getInstanceApi().get().getKernelForInstanceInRegion(null, ebsInstance.getId());\n      client.getInstanceApi().get().setKernelForInstanceInRegion(null, ebsInstance.getId(), oldKernel);\n      assertEquals(oldKernel, client.getInstanceApi().get().getKernelForInstanceInRegion(null, ebsInstance.getId()));\n   }\n\n   private void setInstanceTypeForInstanceInRegion() {\n      client.getInstanceApi().get()\n            .setInstanceTypeForInstanceInRegion(null, ebsInstance.getId(), InstanceType.C1_MEDIUM);\n      assertEquals(InstanceType.C1_MEDIUM,\n            client.getInstanceApi().get().getInstanceTypeForInstanceInRegion(null, ebsInstance.getId()));\n      client.getInstanceApi().get().setInstanceTypeForInstanceInRegion(null, ebsInstance.getId(), InstanceType.M1_SMALL);\n      assertEquals(InstanceType.M1_SMALL,\n            client.getInstanceApi().get().getInstanceTypeForInstanceInRegion(null, ebsInstance.getId()));\n   }\n\n   private void setBlockDeviceMappingForInstanceInRegion() {\n      String volumeId = ebsInstance.getEbsBlockDevices().get(\"/dev/sda1\").getVolumeId();\n\n      Map<String, BlockDevice> mapping = Maps.newLinkedHashMap();\n      mapping.put(\"/dev/sda1\", new BlockDevice(volumeId, false));\n      try {\n         client.getInstanceApi().get().setBlockDeviceMappingForInstanceInRegion(null, ebsInstance.getId(), mapping);\n\n         Map<String, BlockDevice> devices = client.getInstanceApi().get().getBlockDeviceMappingForInstanceInRegion(null,\n               ebsInstance.getId());\n         assertEquals(devices.size(), 1);\n         String deviceName = Iterables.getOnlyElement(devices.keySet());\n         BlockDevice device = Iterables.getOnlyElement(devices.values());\n\n         assertEquals(device.getVolumeId(), volumeId);\n         assertEquals(deviceName, \"/dev/sda1\");\n         assertEquals(device.isDeleteOnTermination(), false);\n\n         System.out.println(\"OK: setBlockDeviceMappingForInstanceInRegion\");\n      } catch (Exception e) {\n         System.err.println(\"setBlockDeviceMappingForInstanceInRegion\");\n\n         e.printStackTrace();\n      }\n   }\n\n   private void setInstanceInitiatedShutdownBehaviorForInstanceInRegion() {\n      try {\n\n         client.getInstanceApi().get().setInstanceInitiatedShutdownBehaviorForInstanceInRegion(null,\n               ebsInstance.getId(), InstanceInitiatedShutdownBehavior.STOP);\n\n         assertEquals(InstanceInitiatedShutdownBehavior.STOP, client.getInstanceApi().get()\n               .getInstanceInitiatedShutdownBehaviorForInstanceInRegion(null, ebsInstance.getId()));\n         client.getInstanceApi().get().setInstanceInitiatedShutdownBehaviorForInstanceInRegion(null,\n               ebsInstance.getId(), InstanceInitiatedShutdownBehavior.TERMINATE);\n\n         assertEquals(InstanceInitiatedShutdownBehavior.TERMINATE, client.getInstanceApi().get()\n               .getInstanceInitiatedShutdownBehaviorForInstanceInRegion(null, ebsInstance.getId()));\n         System.out.println(\"OK: setInstanceInitiatedShutdownBehaviorForInstanceInRegion\");\n      } catch (Exception e) {\n         System.err.println(\"setInstanceInitiatedShutdownBehaviorForInstanceInRegion\");\n         e.printStackTrace();\n      }\n   }\n\n   /**\n    * this tests \"personality\" as the file looked up was sent during instance creation\n    *\n    * @throws UnknownHostException\n    */\n   private void sshPing(RunningInstance newDetails) throws UnknownHostException {\n      try {\n         doCheckKey(newDetails);\n      } catch (SshException e) {// try twice in case there is a network timeout\n         try {\n            Thread.sleep(10 * 1000);\n         } catch (InterruptedException e1) {\n         }\n         doCheckKey(newDetails);\n      }\n   }\n\n   private void doCheckKey(RunningInstance newDetails) throws UnknownHostException {\n      doCheckKey(newDetails.getIpAddress());\n   }\n\n   private void doCheckKey(String address) {\n      SshClient ssh = sshFactory.create(HostAndPort.fromParts(address, 22),\n            LoginCredentials.builder().user(\"ubuntu\").privateKey(keyPair.getKeyMaterial()).build());\n      try {\n         ssh.connect();\n         ExecResponse hello = ssh.exec(\"echo hello\");\n         assertEquals(hello.getOutput().trim(), \"hello\");\n      } finally {\n         if (ssh != null)\n            ssh.disconnect();\n      }\n   }\n\n   private RunningInstance blockUntilWeCanSshIntoInstance(RunningInstance instance) throws UnknownHostException {\n      System.out.printf(\"%d: %s awaiting instance to run %n\", System.currentTimeMillis(), instance.getId());\n      assert runningTester.apply(instance);\n\n      // search my identity for the instance I just created\n      Reservation<? extends RunningInstance> reservation = Iterables.getOnlyElement(client.getInstanceApi().get()\n            .describeInstancesInRegion(instance.getRegion(), instance.getId())); // last\n      // parameter\n      // (ids)\n      // narrows\n      // the\n      // search\n\n      instance = Iterables.getOnlyElement(reservation);\n\n      System.out.printf(\"%d: %s awaiting ssh service to start%n\", System.currentTimeMillis(), instance.getIpAddress());\n      assert socketTester.apply(HostAndPort.fromParts(instance.getIpAddress(), 22));\n      System.out.printf(\"%d: %s ssh service started%n\", System.currentTimeMillis(), instance.getDnsName());\n      sshPing(instance);\n      System.out.printf(\"%d: %s ssh connection made%n\", System.currentTimeMillis(), instance.getId());\n      return instance;\n   }\n\n   @AfterTest\n   void cleanup() {\n      if (ebsInstance != null) {\n         try {\n            client.getInstanceApi().get().terminateInstancesInRegion(ebsInstance.getRegion(), ebsInstance.getId());\n            terminatedTester.apply(ebsInstance);\n         } catch (Exception e) {\n            e.printStackTrace();\n         }\n      }\n      if (ebsImage != null) {\n         try {\n            client.getAMIApi().get().deregisterImageInRegion(ebsImage.getRegion(), ebsImage.getId());\n         } catch (Exception e) {\n            e.printStackTrace();\n         }\n      }\n\n      if (snapshot != null) {\n         try {\n            client.getElasticBlockStoreApi().get().deleteSnapshotInRegion(snapshot.getRegion(), snapshot.getId());\n         } catch (Exception e) {\n            e.printStackTrace();\n         }\n      }\n      if (attachment != null) {\n         try {\n            client.getElasticBlockStoreApi().get().detachVolumeInRegion(volume.getRegion(), volume.getId(), true);\n            assert volumeTester.apply(volume);\n         } catch (Exception e) {\n            e.printStackTrace();\n         }\n      }\n      if (instance != null) {\n         try {\n            client.getInstanceApi().get().terminateInstancesInRegion(instance.getRegion(), instance.getId());\n            terminatedTester.apply(instance);\n         } catch (Exception e) {\n            e.printStackTrace();\n         }\n      }\n      if (volume != null) {\n         try {\n            client.getElasticBlockStoreApi().get().deleteVolumeInRegion(volume.getRegion(), volume.getId());\n         } catch (Exception e) {\n            e.printStackTrace();\n         }\n      }\n      if (keyPair != null) {\n         try {\n            client.getKeyPairApi().get().deleteKeyPairInRegion(keyPair.getRegion(), keyPair.getKeyName());\n         } catch (Exception e) {\n            e.printStackTrace();\n         }\n      }\n      if (securityGroupName != null) {\n         try {\n            client.getSecurityGroupApi().get().deleteSecurityGroupInRegion(null, securityGroupName);\n         } catch (Exception e) {\n            e.printStackTrace();\n         }\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/EC2ApiMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2;\n\nimport org.jclouds.compute.internal.BaseComputeServiceApiMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"EC2ApiMetadataTest\")\npublic class EC2ApiMetadataTest extends BaseComputeServiceApiMetadataTest {\n\n   public EC2ApiMetadataTest() {\n      super(new EC2ApiMetadata());\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/EC2ContextBuilderText.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2;\n\nimport static org.jclouds.reflect.Reflection2.typeToken;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.View;\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"EC2ContextBuilderTest\")\npublic class EC2ContextBuilderText {\n   public void testAssignability() {\n      View view = ContextBuilder.newBuilder(new EC2ApiMetadata()).credentials(\"foo\", \"bar\")\n              .buildView(typeToken(ComputeServiceContext.class));\n      view.unwrapApi(EC2Api.class);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/binders/BindBlockDeviceMappingToIndexedFormParamsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.File;\nimport java.util.Date;\nimport java.util.Map;\n\nimport org.jclouds.ec2.domain.Attachment.Status;\nimport org.jclouds.ec2.domain.BlockDevice;\nimport org.jclouds.http.HttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Maps;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n/**\n * Tests behavior of {@code BindBlockDeviceMappingToIndexedFormParams}\n */\n@Test(groups = \"unit\")\npublic class BindBlockDeviceMappingToIndexedFormParamsTest {\n   Injector injector = Guice.createInjector();\n   BindBlockDeviceMappingToIndexedFormParams binder = injector\n         .getInstance(BindBlockDeviceMappingToIndexedFormParams.class);\n\n   public void testMappingOrdersLexicographically() {\n      Map<String, BlockDevice> mapping = Maps.newLinkedHashMap();\n      mapping.put(\"apple\", new BlockDevice(\"appleId\", true));\n      Date date = new Date(999999L);\n      mapping.put(\"cranberry\", new BlockDevice(\"cranberry\", Status.ATTACHED, date, false));\n\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\")\n            .addFormParam(\"InstanceId\", \"i-foo\").build();\n      request = binder.bindToRequest(request, mapping);\n      assertEquals(\n            request.getPayload().getRawContent(),\n            \"Action=ModifyInstanceAttribute&BlockDeviceMapping.1.DeviceName=apple&BlockDeviceMapping.1.Ebs.DeleteOnTermination=true&BlockDeviceMapping.1.Ebs.VolumeId=appleId&BlockDeviceMapping.2.DeviceName=cranberry&BlockDeviceMapping.2.Ebs.DeleteOnTermination=false&BlockDeviceMapping.2.Ebs.VolumeId=cranberry&InstanceId=i-foo\");\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testMustBeBlockDeviceMapping() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      binder.bindToRequest(request, new File(\"foo\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testNullIsBad() {\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").build();\n      binder.bindToRequest(request, null);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/binders/BindBundleIdsToIndexedFormParamsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.File;\n\nimport org.jclouds.http.HttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n/**\n * Tests behavior of {@code BindBundleIdsToIndexedFormParams}\n */\n@Test(groups = \"unit\")\npublic class BindBundleIdsToIndexedFormParamsTest {\n   Injector injector = Guice.createInjector();\n   BindBundleIdsToIndexedFormParams binder = injector.getInstance(BindBundleIdsToIndexedFormParams.class);\n\n   public void test() {\n\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      request = binder.bindToRequest(request, new String[] { \"alpha\", \"omega\" });\n      assertEquals(request.getPayload().getRawContent(), \"BundleId.1=alpha&BundleId.2=omega\");\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testMustBeArray() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      binder.bindToRequest(request, new File(\"foo\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testNullIsBad() {\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").build();\n      binder.bindToRequest(request, null);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/binders/BindFiltersToIndexedFormParamsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.File;\n\nimport org.jclouds.http.HttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n/**\n * Tests behavior of {@code BindFiltersToIndexedFormParams}\n */\n@Test(groups = \"unit\")\npublic class BindFiltersToIndexedFormParamsTest {\n   Injector injector = Guice.createInjector();\n   BindFiltersToIndexedFormParams binder = injector.getInstance(BindFiltersToIndexedFormParams.class);\n\n   public void test() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      request = binder.bindToRequest(request, ImmutableMultimap.<String, String> builder()\n                                                               .put(\"resource-type\", \"instance\")\n                                                               .put(\"key\", \"stack\")\n                                                               .putAll(\"value\", \"Test\", \"Production\")\n                                                               .build());\n      assertEquals(\n            request.getPayload().getRawContent(),\n            \"Filter.1.Name=resource-type&Filter.1.Value.1=instance&Filter.2.Name=key&Filter.2.Value.1=stack&Filter.3.Name=value&Filter.3.Value.1=Test&Filter.3.Value.2=Production\");\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testMustBeMultimap() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      binder.bindToRequest(request, new File(\"foo\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testNullIsBad() {\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").build();\n      binder.bindToRequest(request, null);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/binders/BindGroupNamesToIndexedFormParamsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.File;\n\nimport org.jclouds.http.HttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n/**\n * Tests behavior of {@code BindGroupNamesToIndexedFormParams}\n */\n@Test(groups = \"unit\")\npublic class BindGroupNamesToIndexedFormParamsTest {\n   Injector injector = Guice.createInjector();\n   BindGroupNamesToIndexedFormParams binder = injector.getInstance(BindGroupNamesToIndexedFormParams.class);\n\n   public void test() {\n\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      request = binder.bindToRequest(request, new String[] { \"alpha\", \"omega\" });\n      assertEquals(request.getPayload().getRawContent(), \"GroupName.1=alpha&GroupName.2=omega\");\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testMustBeArray() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      binder.bindToRequest(request, new File(\"foo\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testNullIsBad() {\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").build();\n      binder.bindToRequest(request, null);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/binders/BindInstanceIdsToIndexedFormParamsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.File;\n\nimport org.jclouds.http.HttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n/**\n * Tests behavior of {@code BindInstanceIdsToIndexedFormParams}\n */\n@Test(groups = \"unit\")\npublic class BindInstanceIdsToIndexedFormParamsTest {\n   Injector injector = Guice.createInjector();\n   BindInstanceIdsToIndexedFormParams binder = injector.getInstance(BindInstanceIdsToIndexedFormParams.class);\n\n   public void test() {\n\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      request = binder.bindToRequest(request, new String[] { \"alpha\", \"omega\" });\n      assertEquals(request.getPayload().getRawContent(), \"InstanceId.1=alpha&InstanceId.2=omega\");\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testMustBeArray() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      binder.bindToRequest(request, new File(\"foo\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testNullIsBad() {\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").build();\n      binder.bindToRequest(request, null);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/binders/BindKeyNamesToIndexedFormParamsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.File;\n\nimport org.jclouds.http.HttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n/**\n * Tests behavior of {@code BindKeyNamesToIndexedFormParams}\n */\n@Test(groups = \"unit\")\npublic class BindKeyNamesToIndexedFormParamsTest {\n   Injector injector = Guice.createInjector();\n   BindKeyNamesToIndexedFormParams binder = injector.getInstance(BindKeyNamesToIndexedFormParams.class);\n\n   public void test() {\n\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      request = binder.bindToRequest(request, new String[] { \"alpha\", \"omega\" });\n      assertEquals(request.getPayload().getRawContent(), \"KeyName.1=alpha&KeyName.2=omega\");\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testMustBeArray() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      binder.bindToRequest(request, new File(\"foo\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testNullIsBad() {\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").build();\n      binder.bindToRequest(request, null);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/binders/BindProductCodesToIndexedFormParamsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.File;\n\nimport org.jclouds.http.HttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n/**\n * Tests behavior of {@code BindProductCodesToIndexedFormParams}\n */\n@Test(groups = \"unit\")\npublic class BindProductCodesToIndexedFormParamsTest {\n   Injector injector = Guice.createInjector();\n   BindProductCodesToIndexedFormParams binder = injector.getInstance(BindProductCodesToIndexedFormParams.class);\n\n   public void test() {\n\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      request = binder.bindToRequest(request, ImmutableSet.of(\"alpha\", \"omega\"));\n      assertEquals(request.getPayload().getRawContent(), \"ProductCode.1=alpha&ProductCode.2=omega\");\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testMustBeIterable() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      binder.bindToRequest(request, new File(\"foo\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testNullIsBad() {\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").build();\n      binder.bindToRequest(request, null);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/binders/BindPublicIpsToIndexedFormParamsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.File;\n\nimport org.jclouds.http.HttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n/**\n * Tests behavior of {@code BindPublicIpsToIndexedFormParams}\n */\n@Test(groups = \"unit\")\npublic class BindPublicIpsToIndexedFormParamsTest {\n   Injector injector = Guice.createInjector();\n   BindPublicIpsToIndexedFormParams binder = injector.getInstance(BindPublicIpsToIndexedFormParams.class);\n\n   public void test() {\n\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      request = binder.bindToRequest(request, new String[] { \"alpha\", \"omega\" });\n      assertEquals(request.getPayload().getRawContent(), \"PublicIp.1=alpha&PublicIp.2=omega\");\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testMustBeArray() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      binder.bindToRequest(request, new File(\"foo\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testNullIsBad() {\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").build();\n      binder.bindToRequest(request, null);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/binders/BindResourceIdsToIndexedFormParamsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.File;\n\nimport org.jclouds.http.HttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n/**\n * Tests behavior of {@code BindResourceIdsToIndexedFormParams}\n */\n@Test(groups = \"unit\")\npublic class BindResourceIdsToIndexedFormParamsTest {\n   Injector injector = Guice.createInjector();\n   BindResourceIdsToIndexedFormParams binder = injector.getInstance(BindResourceIdsToIndexedFormParams.class);\n\n   public void test() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      request = binder.bindToRequest(request, ImmutableList.builder().add(\"alpha\").add(\"omega\").build());\n      assertEquals(request.getPayload().getRawContent(), \"ResourceId.1=alpha&ResourceId.2=omega\");\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testMustBeArray() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      binder.bindToRequest(request, new File(\"foo\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testNullIsBad() {\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").build();\n      binder.bindToRequest(request, null);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/binders/BindS3UploadPolicyAndSignatureTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\n\nimport org.jclouds.ec2.features.BaseEC2ApiTest;\nimport org.jclouds.ec2.features.InstanceApi;\nimport org.jclouds.http.HttpRequest;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code BindS3UploadPolicyAndSignature}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"BindS3UploadPolicyAndSignatureTest\")\npublic class BindS3UploadPolicyAndSignatureTest extends BaseEC2ApiTest<InstanceApi> {\n   private BindS3UploadPolicyAndSignature binder;\n\n   @BeforeClass\n   @Override\n   protected void setupFactory() throws IOException {\n      super.setupFactory();\n      binder = injector.getInstance(BindS3UploadPolicyAndSignature.class);\n   }\n\n   public void testMapping() {\n      String json = \"{\\\"foo\\\":true}\";\n\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      request = binder.bindToRequest(request, json);\n      assertEquals(\n            request.getPayload().getRawContent(),\n            \"Storage.S3.UploadPolicy=eyJmb28iOnRydWV9&Storage.S3.UploadPolicySignature=UbDQLDM5P3aZ840aqJoH%2B6rwDcRo5KrIfsG7vJWHIVY%3D\");\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testNullIsBad() {\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").build();\n      binder.bindToRequest(request, null);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/binders/BindTagKeysToIndexedFormParamsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.File;\n\nimport org.jclouds.http.HttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code BindTagKeysToIndexedFormParams}\n */\n@Test(groups = \"unit\")\npublic class BindTagKeysToIndexedFormParamsTest {\n   BindTagKeysToIndexedFormParams binder = new BindTagKeysToIndexedFormParams();\n\n   public void test() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      request = binder.bindToRequest(request, ImmutableSet.of(\"one\", \"two\"));\n      assertEquals(request.getPayload().getRawContent(), \"Tag.1.Key=one&Tag.2.Key=two\");\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testMustBeIterable() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      binder.bindToRequest(request, new File(\"foo\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testNullIsBad() {\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").build();\n      binder.bindToRequest(request, null);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/binders/BindTagsToIndexedFormParamsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.File;\n\nimport org.jclouds.http.HttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code BindTagsToIndexedFormParams}\n */\n@Test(groups = \"unit\")\npublic class BindTagsToIndexedFormParamsTest {\n   BindTagsToIndexedFormParams binder = new BindTagsToIndexedFormParams();\n\n   public void test() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      request = binder.bindToRequest(request, ImmutableMap.of(\"one\", \"alpha\", \"two\", \"beta\"));\n      assertEquals(request.getPayload().getRawContent(),\n            \"Tag.1.Key=one&Tag.1.Value=alpha&Tag.2.Key=two&Tag.2.Value=beta\");\n   }\n\n   public void testEmpty() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      request = binder.bindToRequest(request, ImmutableSet.of(\"empty\"));\n      assertEquals(request.getPayload().getRawContent(), \"Tag.1.Key=empty&Tag.1.Value=\");\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testMustBeArray() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      binder.bindToRequest(request, new File(\"foo\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testNullIsBad() {\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").build();\n      binder.bindToRequest(request, null);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/binders/BindUserGroupsToIndexedFormParamsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.File;\n\nimport org.jclouds.http.HttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n/**\n * Tests behavior of {@code BindUserGroupsToIndexedFormParams}\n */\n@Test(groups = \"unit\")\npublic class BindUserGroupsToIndexedFormParamsTest {\n   Injector injector = Guice.createInjector();\n   BindUserGroupsToIndexedFormParams binder = injector.getInstance(BindUserGroupsToIndexedFormParams.class);\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testOnlyAllIsValid() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      binder.bindToRequest(request, ImmutableSet.of(\"alpha\"));\n   }\n\n   public void test() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      request = binder.bindToRequest(request, ImmutableSet.of(\"all\"));\n      assertEquals(request.getPayload().getRawContent(), \"UserGroup.1=all\");\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testMustBeIterable() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      binder.bindToRequest(request, new File(\"foo\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testNullIsBad() {\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").build();\n      binder.bindToRequest(request, null);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/binders/BindUserIdGroupPairToSourceSecurityGroupFormParamsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.File;\n\nimport org.jclouds.ec2.domain.UserIdGroupPair;\nimport org.jclouds.http.HttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n/**\n * Tests behavior of {@code BindUserIdGroupPairToSourceSecurityGroupFormParams}\n */\n@Test(groups = \"unit\")\npublic class BindUserIdGroupPairToSourceSecurityGroupFormParamsTest {\n   Injector injector = Guice.createInjector();\n   BindUserIdGroupPairToSourceSecurityGroupFormParams binder = injector\n         .getInstance(BindUserIdGroupPairToSourceSecurityGroupFormParams.class);\n\n   public void testUserIdGroupPair() {\n      UserIdGroupPair pair = new UserIdGroupPair(\"id\", \"group\");\n\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      request = binder.bindToRequest(request, pair);\n      assertEquals(request.getPayload().getRawContent(), \"SourceSecurityGroupOwnerId=id&SourceSecurityGroupName=group\");\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testMustBeUserIdGroupPair() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      binder.bindToRequest(request, new File(\"foo\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testNullIsBad() {\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").build();\n      binder.bindToRequest(request, null);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/binders/BindUserIdsToIndexedFormParamsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.File;\n\nimport org.jclouds.http.HttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n/**\n * Tests behavior of {@code BindUserIdsToIndexedFormParams}\n */\n@Test(groups = \"unit\")\npublic class BindUserIdsToIndexedFormParamsTest {\n   Injector injector = Guice.createInjector();\n   BindUserIdsToIndexedFormParams binder = injector.getInstance(BindUserIdsToIndexedFormParams.class);\n\n   public void test() {\n\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      request = binder.bindToRequest(request, ImmutableSet.of(\"alpha\", \"omega\"));\n      assertEquals(request.getPayload().getRawContent(), \"UserId.1=alpha&UserId.2=omega\");\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testMustBeIterable() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      binder.bindToRequest(request, new File(\"foo\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testNullIsBad() {\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").build();\n      binder.bindToRequest(request, null);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/binders/BindVolumeIdsToIndexedFormParamsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.File;\n\nimport org.jclouds.http.HttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n/**\n * Tests behavior of {@code BindVolumeIdsToIndexedFormParams}\n */\n@Test(groups = \"unit\")\npublic class BindVolumeIdsToIndexedFormParamsTest {\n   Injector injector = Guice.createInjector();\n   BindVolumeIdsToIndexedFormParams binder = injector.getInstance(BindVolumeIdsToIndexedFormParams.class);\n\n   public void test() {\n\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      request = binder.bindToRequest(request, new String[] { \"alpha\", \"omega\" });\n      assertEquals(request.getPayload().getRawContent(), \"VolumeId.1=alpha&VolumeId.2=omega\");\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testMustBeArray() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      binder.bindToRequest(request, new File(\"foo\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testNullIsBad() {\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").build();\n      binder.bindToRequest(request, null);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/binders/IfNotNullBindAvailabilityZoneToFormParamTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.binders;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertSame;\n\nimport java.io.File;\n\nimport org.jclouds.http.HttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n/**\n * Tests behavior of {@code IfNotNullBindAvailabilityZoneToFormParam}\n */\n@Test(groups = \"unit\")\npublic class IfNotNullBindAvailabilityZoneToFormParamTest {\n   Injector injector = Guice.createInjector();\n   IfNotNullBindAvailabilityZoneToFormParam binder = injector\n         .getInstance(IfNotNullBindAvailabilityZoneToFormParam.class);\n\n   public void test() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      request = binder.bindToRequest(request, \"us-east-1a\");\n      assertEquals(request.getPayload().getRawContent(), \"Placement.AvailabilityZone=us-east-1a\");\n   }\n\n   public void testWhenNullReturnsSame() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      HttpRequest request2 = binder.bindToRequest(request, null);\n      assertSame(request, request2);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testMustBeString() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      binder.bindToRequest(request, new File(\"foo\"));\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/compute/EC2ComputeServiceExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute;\n\nimport static org.jclouds.ec2.compute.options.EC2TemplateOptions.Builder.blockUntilRunning;\nimport static org.jclouds.ec2.compute.options.EC2TemplateOptions.Builder.maxCount;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport jakarta.ws.rs.core.MediaType;\nimport java.util.Set;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMap.Builder;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport org.jclouds.compute.ComputeService;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.ec2.compute.internal.BaseEC2ComputeServiceExpectTest;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\n/**\n * Tests the compute service abstraction of the EC2 api.\n */\n@Test(groups = \"unit\", testName = \"EC2ComputeServiceExpectTest\")\npublic class EC2ComputeServiceExpectTest extends BaseEC2ComputeServiceExpectTest {\n   protected HttpRequest createFirstTagRequest;\n   protected HttpRequest createSecondTagRequest;\n   protected HttpRequest createThirdTagRequest;\n\n   @BeforeClass\n   @Override\n   protected void setupDefaultRequests() {\n      super.setupDefaultRequests();\n      createFirstTagRequest =\n              formSigner.filter(HttpRequest.builder()\n                      .method(\"POST\")\n                      .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                      .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                      .payload(\n                              payloadFromStringWithContentType(\n                                      \"Action=CreateTags\" +\n                                              \"&ResourceId.1=i-2ba64342\" +\n                                              \"&Signature=Trp5e5%2BMqeBeBZbLYa9s9gxahQ9nkx6ETfsGl82IV8Y%3D\" +\n                                              \"&SignatureMethod=HmacSHA256\" +\n                                              \"&SignatureVersion=2\" +\n                                              \"&Tag.1.Key=Name\" +\n                                              \"&Tag.1.Value=test-2ba64342\" +\n                                              \"&Timestamp=2012-04-16T15%3A54%3A08.897Z\" +\n                                              \"&Version=2010-08-31\" +\n                                              \"&AWSAccessKeyId=identity\",\n                                      \"application/x-www-form-urlencoded\"))\n                      .build());\n\n      createSecondTagRequest =\n              formSigner.filter(HttpRequest.builder()\n                      .method(\"POST\")\n                      .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                      .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                      .payload(\n                              payloadFromStringWithContentType(\n                                      \"Action=CreateTags\" +\n                                              \"&ResourceId.1=i-2bc64242\" +\n                                              \"&Signature=Trp5e5%2BMqeBeBZbLYa9s9gxahQ9nkx6ETfsGl82IV8Y%3D\" +\n                                              \"&SignatureMethod=HmacSHA256\" +\n                                              \"&SignatureVersion=2\" +\n                                              \"&Tag.1.Key=Name\" +\n                                              \"&Tag.1.Value=test-2bc64242\" +\n                                              \"&Timestamp=2012-04-16T15%3A54%3A08.897Z\" +\n                                              \"&Version=2010-08-31\" +\n                                              \"&AWSAccessKeyId=identity\",\n                                      \"application/x-www-form-urlencoded\"))\n                      .build());\n\n      createThirdTagRequest =\n              formSigner.filter(HttpRequest.builder()\n                      .method(\"POST\")\n                      .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                      .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                      .payload(\n                              payloadFromStringWithContentType(\n                                      \"Action=CreateTags\" +\n                                              \"&ResourceId.1=i-2be64332\" +\n                                              \"&Signature=Trp5e5%2BMqeBeBZbLYa9s9gxahQ9nkx6ETfsGl82IV8Y%3D\" +\n                                              \"&SignatureMethod=HmacSHA256\" +\n                                              \"&SignatureVersion=2\" +\n                                              \"&Tag.1.Key=Name\" +\n                                              \"&Tag.1.Value=test-2be64332\" +\n                                              \"&Timestamp=2012-04-16T15%3A54%3A08.897Z\" +\n                                              \"&Version=2010-08-31\" +\n                                              \"&AWSAccessKeyId=identity\",\n                                      \"application/x-www-form-urlencoded\"))\n                      .build());\n   }\n\n   public void testCreateNodeWithGeneratedKeyPairAndOverriddenLoginUser() throws Exception {\n      Builder<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder();\n      requestResponseMap.put(describeRegionsRequest, describeRegionsResponse);\n      requestResponseMap.put(describeAvailabilityZonesRequest, describeAvailabilityZonesResponse);\n      requestResponseMap.put(describeImagesRequest, describeImagesResponse);\n      requestResponseMap.put(createKeyPairRequest, createKeyPairResponse);\n      requestResponseMap.put(createSecurityGroupRequest, createSecurityGroupResponse);\n      requestResponseMap.put(describeSecurityGroupFilteredRequest, describeSecurityGroupFilteredResponse);\n      requestResponseMap.put(describeSecurityGroupRequest, describeSecurityGroupResponse);\n      requestResponseMap.put(authorizeSecurityGroupIngressRequest22, authorizeSecurityGroupIngressResponse);\n      requestResponseMap.put(authorizeSecurityGroupIngressRequestGroup, authorizeSecurityGroupIngressResponse);\n      requestResponseMap.put(runInstancesRequest, runInstancesResponse);\n      requestResponseMap.put(describeInstanceRequest, describeInstanceResponse);\n      requestResponseMap.put(describeInstanceMultiIdsRequest, describeInstanceMultiIdsResponse);\n      requestResponseMap.put(describeImageRequest, describeImagesResponse);\n      requestResponseMap.put(createTagsRequest, createTagsResponse);\n\n      ComputeService apiThatCreatesNode = requestsSendResponses(requestResponseMap.build());\n\n      NodeMetadata node = Iterables.getOnlyElement(apiThatCreatesNode.createNodesInGroup(\"test\", 1,\n              blockUntilRunning(false).overrideLoginUser(\"ec2-user\")));\n      assertEquals(node.getCredentials().getUser(), \"ec2-user\");\n      System.out.println(node.getImageId());\n      assertTrue(node.getCredentials().getOptionalPrivateKey().isPresent());\n   }\n\n   public void testCreateThreeNodesWithMaxCountThree() throws Exception {\n\n      Builder<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder();\n      requestResponseMap.put(describeRegionsRequest, describeRegionsResponse);\n      requestResponseMap.put(describeAvailabilityZonesRequest, describeAvailabilityZonesResponse);\n      requestResponseMap.put(describeImagesRequest, describeImagesResponse);\n      requestResponseMap.put(createKeyPairRequest, createKeyPairResponse);\n      requestResponseMap.put(createSecurityGroupRequest, createSecurityGroupResponse);\n      requestResponseMap.put(describeSecurityGroupFilteredRequest, describeSecurityGroupFilteredResponse);\n      requestResponseMap.put(describeSecurityGroupRequest, describeSecurityGroupResponse);\n      requestResponseMap.put(authorizeSecurityGroupIngressRequest22, authorizeSecurityGroupIngressResponse);\n      requestResponseMap.put(authorizeSecurityGroupIngressRequestGroup, authorizeSecurityGroupIngressResponse);\n      requestResponseMap.put(runThreeInstancesRequest, runThreeInstancesResponse);\n      requestResponseMap.put(describeInstanceRequest, describeInstanceResponse);\n      requestResponseMap.put(describeInstanceThreeIdsRequest, describeInstanceThreeIdsResponse);\n      requestResponseMap.put(describeImageRequest, describeImagesResponse);\n      requestResponseMap.put(createFirstTagRequest, createTagsResponse);\n      requestResponseMap.put(createSecondTagRequest, createTagsResponse);\n      requestResponseMap.put(createThirdTagRequest, createTagsResponse);\n\n      ComputeService apiThatCreatesNode = requestsSendResponses(requestResponseMap.build());\n\n      NodeMetadata node = Iterables.getFirst(apiThatCreatesNode.createNodesInGroup(\"test\", 3,\n              maxCount(3).blockUntilRunning(false).overrideLoginUser(\"ec2-user\")), null);\n      assertNotNull(node, \"Node should exist\");\n      assertEquals(node.getCredentials().getUser(), \"ec2-user\", \"User should be ec2-user\");\n   }\n\n   public void testCreateThreeNodesWithMaxCountFourGetThreeNodes() throws Exception {\n\n      Builder<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder();\n      requestResponseMap.put(describeRegionsRequest, describeRegionsResponse);\n      requestResponseMap.put(describeAvailabilityZonesRequest, describeAvailabilityZonesResponse);\n      requestResponseMap.put(describeImagesRequest, describeImagesResponse);\n      requestResponseMap.put(createKeyPairRequest, createKeyPairResponse);\n      requestResponseMap.put(createSecurityGroupRequest, createSecurityGroupResponse);\n      requestResponseMap.put(describeSecurityGroupFilteredRequest, describeSecurityGroupFilteredResponse);\n      requestResponseMap.put(describeSecurityGroupRequest, describeSecurityGroupResponse);\n      requestResponseMap.put(authorizeSecurityGroupIngressRequest22, authorizeSecurityGroupIngressResponse);\n      requestResponseMap.put(authorizeSecurityGroupIngressRequestGroup, authorizeSecurityGroupIngressResponse);\n      requestResponseMap.put(runThreeToFourInstancesRequest, runThreeInstancesResponse);\n      requestResponseMap.put(describeInstanceRequest, describeInstanceResponse);\n      requestResponseMap.put(describeInstanceThreeIdsRequest, describeInstanceThreeIdsResponse);\n      requestResponseMap.put(describeImageRequest, describeImagesResponse);\n      requestResponseMap.put(createFirstTagRequest, createTagsResponse);\n      requestResponseMap.put(createSecondTagRequest, createTagsResponse);\n      requestResponseMap.put(createThirdTagRequest, createTagsResponse);\n\n      ComputeService apiThatCreatesNode = requestsSendResponses(requestResponseMap.build());\n\n      NodeMetadata node = Iterables.getFirst(apiThatCreatesNode.createNodesInGroup(\"test\", 3,\n              maxCount(4).blockUntilRunning(false).overrideLoginUser(\"ec2-user\")), null);\n      assertNotNull(node, \"Node should exist\");\n      assertEquals(node.getCredentials().getUser(), \"ec2-user\", \"User should be ec2-user\");\n   }\n\n   public void testCreateThreeNodesWithSpecifiedName() throws Exception {\n      HttpRequest createFirstNamedTagRequest =\n              formSigner.filter(HttpRequest.builder()\n                      .method(\"POST\")\n                      .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                      .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                      .payload(\n                              payloadFromStringWithContentType(\n                                      \"Action=CreateTags\" +\n                                              \"&ResourceId.1=i-2ba64342\" +\n                                              \"&Signature=Trp5e5%2BMqeBeBZbLYa9s9gxahQ9nkx6ETfsGl82IV8Y%3D\" +\n                                              \"&SignatureMethod=HmacSHA256\" +\n                                              \"&SignatureVersion=2\" +\n                                              \"&Tag.1.Key=Name\" +\n                                              \"&Tag.1.Value=test-node\" +\n                                              \"&Timestamp=2012-04-16T15%3A54%3A08.897Z\" +\n                                              \"&Version=2010-08-31\" +\n                                              \"&AWSAccessKeyId=identity\",\n                                      \"application/x-www-form-urlencoded\"))\n                      .build());\n\n      HttpRequest createSecondNamedTagRequest =\n              formSigner.filter(HttpRequest.builder()\n                      .method(\"POST\")\n                      .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                      .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                      .payload(\n                              payloadFromStringWithContentType(\n                                      \"Action=CreateTags\" +\n                                              \"&ResourceId.1=i-2bc64242\" +\n                                              \"&Signature=Trp5e5%2BMqeBeBZbLYa9s9gxahQ9nkx6ETfsGl82IV8Y%3D\" +\n                                              \"&SignatureMethod=HmacSHA256\" +\n                                              \"&SignatureVersion=2\" +\n                                              \"&Tag.1.Key=Name\" +\n                                              \"&Tag.1.Value=second-node\" +\n                                              \"&Timestamp=2012-04-16T15%3A54%3A08.897Z\" +\n                                              \"&Version=2010-08-31\" +\n                                              \"&AWSAccessKeyId=identity\",\n                                      \"application/x-www-form-urlencoded\"))\n                      .build());\n\n      HttpRequest createThirdNamedTagRequest =\n              formSigner.filter(HttpRequest.builder()\n                      .method(\"POST\")\n                      .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                      .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                      .payload(\n                              payloadFromStringWithContentType(\n                                      \"Action=CreateTags\" +\n                                              \"&ResourceId.1=i-2be64332\" +\n                                              \"&Signature=Trp5e5%2BMqeBeBZbLYa9s9gxahQ9nkx6ETfsGl82IV8Y%3D\" +\n                                              \"&SignatureMethod=HmacSHA256\" +\n                                              \"&SignatureVersion=2\" +\n                                              \"&Tag.1.Key=Name\" +\n                                              \"&Tag.1.Value=third-node\" +\n                                              \"&Timestamp=2012-04-16T15%3A54%3A08.897Z\" +\n                                              \"&Version=2010-08-31\" +\n                                              \"&AWSAccessKeyId=identity\",\n                                      \"application/x-www-form-urlencoded\"))\n                      .build());\n\n      HttpResponse describeNamedInstanceResponse =\n              HttpResponse.builder().statusCode(200)\n                      .payload(payloadFromResourceWithContentType(\n                              \"/describe_instances_running-named.xml\", MediaType.APPLICATION_XML)).build();\n\n\n      Builder<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder();\n      requestResponseMap.put(describeRegionsRequest, describeRegionsResponse);\n      requestResponseMap.put(describeAvailabilityZonesRequest, describeAvailabilityZonesResponse);\n      requestResponseMap.put(describeImagesRequest, describeImagesResponse);\n      requestResponseMap.put(createKeyPairRequest, createKeyPairResponse);\n      requestResponseMap.put(createSecurityGroupRequest, createSecurityGroupResponse);\n      requestResponseMap.put(describeSecurityGroupFilteredRequest, describeSecurityGroupFilteredResponse);\n      requestResponseMap.put(describeSecurityGroupRequest, describeSecurityGroupResponse);\n      requestResponseMap.put(authorizeSecurityGroupIngressRequest22, authorizeSecurityGroupIngressResponse);\n      requestResponseMap.put(authorizeSecurityGroupIngressRequestGroup, authorizeSecurityGroupIngressResponse);\n      requestResponseMap.put(runThreeInstancesRequest, runThreeInstancesResponse);\n      requestResponseMap.put(describeInstanceRequest, describeNamedInstanceResponse);\n      requestResponseMap.put(describeInstanceThreeIdsRequest, describeInstanceThreeIdsResponse);\n      requestResponseMap.put(describeImageRequest, describeImagesResponse);\n      requestResponseMap.put(createFirstNamedTagRequest, createTagsResponse);\n      requestResponseMap.put(createSecondNamedTagRequest, createTagsResponse);\n      requestResponseMap.put(createThirdNamedTagRequest, createTagsResponse);\n\n      ComputeService apiThatCreatesNode = requestsSendResponses(requestResponseMap.build());\n\n      Set<? extends NodeMetadata> nodes = apiThatCreatesNode.createNodesInGroup(\"test\", 3,\n              maxCount(3).blockUntilRunning(false).overrideLoginUser(\"ec2-user\").nodeNames(ImmutableSet.of(\"test-node\", \"second-node\", \"third-node\")));\n\n      NodeMetadata node = Iterables.get(nodes, 0);\n      assertEquals(node.getName(), \"test-node\");\n\n      NodeMetadata secondNode = Iterables.get(nodes, 1);\n      assertEquals(secondNode.getName(), \"second-node\");\n\n      NodeMetadata thirdNode = Iterables.get(nodes, 2);\n      assertEquals(thirdNode.getName(), \"third-node\");\n   }\n\n   //FIXME - issue-1051\n   @Test(enabled = false)\n   public void testCreateNodeWithGeneratedKeyPairAndOverriddenLoginUserWithTemplateBuilder() throws Exception {\n      Builder<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder();\n      requestResponseMap.put(describeRegionsRequest, describeRegionsResponse);\n      requestResponseMap.put(describeAvailabilityZonesRequest, describeAvailabilityZonesResponse);\n      requestResponseMap.put(describeImagesRequest, describeImagesResponse);\n      requestResponseMap.put(createKeyPairRequest, createKeyPairResponse);\n      requestResponseMap.put(createSecurityGroupRequest, createSecurityGroupResponse);\n      requestResponseMap.put(describeSecurityGroupFilteredRequest, describeSecurityGroupFilteredResponse);\n      requestResponseMap.put(describeSecurityGroupRequest, describeSecurityGroupResponse);\n      requestResponseMap.put(authorizeSecurityGroupIngressRequest22, authorizeSecurityGroupIngressResponse);\n      requestResponseMap.put(authorizeSecurityGroupIngressRequestGroup, authorizeSecurityGroupIngressResponse);\n      requestResponseMap.put(runInstancesRequest, runInstancesResponse);\n      requestResponseMap.put(describeInstanceRequest, describeInstanceResponse);\n      requestResponseMap.put(describeInstanceMultiIdsRequest, describeInstanceMultiIdsResponse);\n      requestResponseMap.put(describeImageRequest, describeImagesResponse);\n      requestResponseMap.put(createTagsRequest, createTagsResponse);\n\n      ComputeService apiThatCreatesNode = requestsSendResponses(requestResponseMap.build());\n\n      NodeMetadata node = Iterables.getOnlyElement(\n            apiThatCreatesNode.createNodesInGroup(\"test\", 1,\n            apiThatCreatesNode.templateBuilder().from(\"osDescriptionMatches=.*fedora.*,loginUser=ec2-user\").build()));\n      assertEquals(node.getCredentials().getUser(), \"ec2-user\");\n      assertTrue(node.getCredentials().getOptionalPrivateKey().isPresent());\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/compute/EC2ComputeServiceLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport java.security.SecureRandom;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.domain.TemplateBuilderSpec;\nimport org.jclouds.compute.internal.BaseComputeServiceLiveTest;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.compute.predicates.NodePredicates;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.compute.options.EC2TemplateOptions;\nimport org.jclouds.ec2.domain.BlockDevice;\nimport org.jclouds.ec2.domain.KeyPair;\nimport org.jclouds.ec2.domain.PublicIpInstanceIdPair;\nimport org.jclouds.ec2.domain.Reservation;\nimport org.jclouds.ec2.domain.RunningInstance;\nimport org.jclouds.ec2.domain.SecurityGroup;\nimport org.jclouds.ec2.domain.Snapshot;\nimport org.jclouds.ec2.domain.Volume;\nimport org.jclouds.ec2.features.ElasticBlockStoreApi;\nimport org.jclouds.ec2.features.InstanceApi;\nimport org.jclouds.ec2.features.KeyPairApi;\nimport org.jclouds.ec2.features.SecurityGroupApi;\nimport org.jclouds.ec2.reference.EC2Constants;\nimport org.jclouds.net.domain.IpProtocol;\nimport org.jclouds.scriptbuilder.domain.Statements;\nimport org.jclouds.sshj.config.SshjSshClientModule;\nimport org.jclouds.util.InetAddresses2;\nimport org.testng.SkipException;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSortedSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.net.HostAndPort;\nimport com.google.inject.Module;\n\n@Test(groups = \"live\", singleThreaded = true)\npublic class EC2ComputeServiceLiveTest extends BaseComputeServiceLiveTest {\n\n   protected TemplateBuilderSpec ebsTemplate;\n\n   public EC2ComputeServiceLiveTest() {\n      provider = \"ec2\";\n   }\n\n   @Override\n   protected Module getSshModule() {\n      return new SshjSshClientModule();\n   }\n\n   @Override\n   protected void checkUserMetadataContains(NodeMetadata node, ImmutableMap<String, String> userMetadata) {\n      if (view.unwrapApi(EC2Api.class).getTagApi().isPresent()) {\n         super.checkUserMetadataContains(node, userMetadata);\n      } else {\n         assertTrue(node.getUserMetadata().isEmpty(), \"not expecting metadata when tag extension isn't present: \" + node);\n      }\n   }\n\n   @Override\n   protected void checkTagsInNodeEquals(NodeMetadata node, ImmutableSet<String> tags) {\n      if (view.unwrapApi(EC2Api.class).getTagApi().isPresent()) {\n         super.checkTagsInNodeEquals(node, tags);\n      } else {\n         assertTrue(node.getTags().isEmpty(), \"not expecting tags when tag extension isn't present: \" + node);\n      }\n   }\n\n\n   @Test(enabled = true, dependsOnMethods = \"testCorrectAuthException\")\n   public void testImagesResolveCorrectly() {\n      Template defaultTemplate = client.templateBuilder().build();\n      assertEquals(defaultTemplate.getImage().getId(), defaultTemplate.getImage().getLocation().getId() + \"/\"\n               + defaultTemplate.getImage().getProviderId());\n      Template byId = client.templateBuilder().imageId(defaultTemplate.getImage().getId()).build();\n      assertEquals(byId.getImage(), defaultTemplate.getImage());\n   }\n\n   @Test(enabled = true, dependsOnMethods = \"testCompareSizes\")\n   public void testExtendedOptionsAndLogin() throws Exception {\n      final SecureRandom random = new SecureRandom();\n\n      SecurityGroupApi securityGroupClient = view.unwrapApi(EC2Api.class)\n               .getSecurityGroupApi().get();\n\n      KeyPairApi keyPairClient = view.unwrapApi(EC2Api.class)\n               .getKeyPairApi().get();\n\n      InstanceApi instanceClient = view.unwrapApi(EC2Api.class)\n               .getInstanceApi().get();\n\n      String group = this.group + \"o\";\n\n      TemplateOptions options = client.templateOptions();\n\n      options.as(EC2TemplateOptions.class).securityGroups(group);\n      options.as(EC2TemplateOptions.class).clientToken(Integer.toHexString(random.nextInt(65536 * 1024)));\n\n      String startedId = null;\n      try {\n         cleanupExtendedStuffInRegion(null, securityGroupClient, keyPairClient, group);\n\n         // create a security group that allows ssh in so that our scripts later\n         // will work\n         securityGroupClient.createSecurityGroupInRegion(null, group, group);\n         securityGroupClient.authorizeSecurityGroupIngressInRegion(null, group, IpProtocol.TCP, 22, 22, \"0.0.0.0/0\");\n\n         // create a keypair to pass in as well\n         KeyPair result = keyPairClient.createKeyPairInRegion(null, group);\n         options.as(EC2TemplateOptions.class).keyPair(result.getKeyName());\n         \n         // pass in the private key, so that we can run a script with it\n         assert result.getKeyMaterial() != null : result;\n         options.overrideLoginPrivateKey(result.getKeyMaterial());\n         \n         // an arbitrary command to run\n         options.runScript(Statements.exec(\"find /usr\"));\n         \n         Set<? extends NodeMetadata> nodes = client.createNodesInGroup(group, 1, options);\n         NodeMetadata first = Iterables.get(nodes, 0);\n         assert first.getCredentials() != null : first;\n         assert first.getCredentials().identity != null : first;\n\n         // Verify that the output of createNodesInGroup is the same.\n         assertEquals(client.createNodesInGroup(group, 1, options), nodes, \"Idempotency failing - got different instances\");\n         \n         startedId = Iterables.getOnlyElement(nodes).getProviderId();\n\n         RunningInstance instance = getInstance(instanceClient, startedId);\n\n         assertEquals(instance.getKeyName(), group);\n\n         // make sure we made our dummy group and also let in the user's group\n         assertEquals(ImmutableSortedSet.copyOf(instance.getGroupNames()), ImmutableSortedSet.<String> of(\"jclouds#\" + group, group));\n\n         // make sure our dummy group has no rules\n         SecurityGroup secgroup = Iterables.getOnlyElement(securityGroupClient.describeSecurityGroupsInRegion(null,\n                  \"jclouds#\" + group));\n         assert secgroup.size() == 0 : secgroup;\n\n         // try to run a script with the original keyPair\n         runScriptWithCreds(group, first.getOperatingSystem(),\n               LoginCredentials.builder().user(first.getCredentials().identity).privateKey(result.getKeyMaterial())\n                     .build());\n\n      } finally {\n         client.destroyNodesMatching(NodePredicates.inGroup(group));\n         if (startedId != null) {\n            // ensure we didn't delete these resources!\n            assertEquals(keyPairClient.describeKeyPairsInRegion(null, group).size(), 1);\n            assertEquals(securityGroupClient.describeSecurityGroupsInRegion(null, group).size(), 1);\n         }\n         cleanupExtendedStuffInRegion(null, securityGroupClient, keyPairClient, group);\n      }\n   }\n\n   @Test(enabled = true) //, dependsOnMethods = \"testCompareSizes\")\n   public void testAutoIpAllocation() throws Exception {\n      ComputeServiceContext context = null;\n      String group = this.group + \"aip\";\n      try {\n         Properties overrides = setupProperties();\n         overrides.setProperty(EC2Constants.PROPERTY_EC2_AUTO_ALLOCATE_ELASTIC_IPS, \"true\");\n\n         context = createView(overrides, setupModules());\n\n         TemplateOptions options = client.templateOptions();\n\n         options.blockOnPort(22, 300);\n         options.inboundPorts(22);\n\n         // create a node\n         Set<? extends NodeMetadata> nodes =\n               context.getComputeService().createNodesInGroup(group, 1, options);\n         assertEquals(nodes.size(), 1, \"One node should have been created\");\n\n         // Get public IPs (We should get 1)\n         NodeMetadata node = Iterables.get(nodes, 0);\n         String region = node.getLocation().getParent().getId();\n         Set<String> publicIps = node.getPublicAddresses();\n         assertFalse(Iterables.isEmpty(publicIps), String.format(\"no public addresses attached to node %s\", node));\n         assertEquals(Iterables.size(publicIps), 1);\n\n         // Check that the address is public and port 22 is accessible\n         String ip = Iterables.getOnlyElement(publicIps);\n         assertFalse(InetAddresses2.isPrivateIPAddress(ip));\n         HostAndPort socket = HostAndPort.fromParts(ip, 22);\n         assertTrue(socketTester.apply(socket), String.format(\"failed to open socket %s on node %s\", socket, node));\n\n         // check that there is an elastic ip correlating to it\n         EC2Api ec2 = context.unwrapApi(EC2Api.class);\n         Set<PublicIpInstanceIdPair> ipidpairs =\n               ec2.getElasticIPAddressApi().get().describeAddressesInRegion(region, publicIps.toArray(new String[0]));\n         assertEquals(ipidpairs.size(), 1, String.format(\"there should only be one address pair (%s)\",\n               Iterables.toString(ipidpairs)));\n\n         // check that the elastic ip is in node.publicAddresses\n         PublicIpInstanceIdPair ipidpair = Iterables.get(ipidpairs, 0);\n         assertEquals(region + \"/\" + ipidpair.getInstanceId(), node.getId());\n         \n         // delete the node\n         context.getComputeService().destroyNodesMatching(NodePredicates.inGroup(group));\n\n         // check that the ip is deallocated\n         Set<PublicIpInstanceIdPair> ipidcheck =\n                 ec2.getElasticIPAddressApi().get().describeAddressesInRegion(region, ipidpair.getPublicIp());\n         assertTrue(Iterables.isEmpty(ipidcheck), String.format(\"there should be no address pairs (%s)\",\n               Iterables.toString(ipidcheck)));\n      } finally {\n         context.getComputeService().destroyNodesMatching(NodePredicates.inGroup(group));\n         if (context != null)\n            context.close();\n      }\n   }\n   \n   @Override\n   protected Properties setupProperties() {\n      Properties overrides = super.setupProperties();\n      String ebsSpec = setIfTestSystemPropertyPresent(overrides, provider + \".ebs-template\");\n      if (ebsSpec != null)\n         ebsTemplate = TemplateBuilderSpec.parse(ebsSpec);\n      return overrides;\n   }\n\n   /**\n    * Note we cannot use the micro size as it has no ephemeral space.\n    */\n   @Test\n   public void testMapEBS() throws Exception {\n      if (ebsTemplate == null) {\n         throw new SkipException(\"Test cannot run without the parameter test.\" + provider\n               + \".ebs-template; this property should be in the format defined in TemplateBuilderSpec\");\n      }\n      InstanceApi instanceClient = view.unwrapApi(EC2Api.class)\n               .getInstanceApi().get();\n\n      ElasticBlockStoreApi ebsClient = view.unwrapApi(EC2Api.class)\n               .getElasticBlockStoreApi().get();\n\n      String group = this.group + \"e\";\n      int volumeSize = 8;\n      \n      final Template template = view.getComputeService().templateBuilder().from(ebsTemplate).build();\n\n      Location zone = Iterables.find(view.getComputeService().listAssignableLocations(), new Predicate<Location>() {\n\n         @Override\n         public boolean apply(Location arg0) {\n            return arg0.getScope() == LocationScope.ZONE\n                     && arg0.getParent().getId().equals(template.getLocation().getId());\n         }\n\n      });\n\n      // create volume only to make a snapshot\n      Volume volume = ebsClient.createVolumeInAvailabilityZone(zone.getId(), 4);\n      // Sleep for 5 seconds to make sure the volume creation finishes.\n      Thread.sleep(5000);\n\n      Snapshot snapshot = ebsClient.createSnapshotInRegion(volume.getRegion(), volume.getId());\n      ebsClient.deleteVolumeInRegion(volume.getRegion(), volume.getId());\n\n      template.getOptions().as(EC2TemplateOptions.class)//\n               // .unmapDeviceNamed(\"/dev/foo)\n               .mapEphemeralDeviceToDeviceName(\"/dev/sdm\", \"ephemeral0\")//\n               .mapNewVolumeToDeviceName(\"/dev/sdn\", volumeSize, true)//\n               .mapEBSSnapshotToDeviceName(\"/dev/sdo\", snapshot.getId(), volumeSize, true);\n\n      try {\n         NodeMetadata node = Iterables.getOnlyElement(client.createNodesInGroup(group, 1, template));\n\n         // TODO figure out how to validate the ephemeral drive. perhaps with df -k?\n\n         Map<String, BlockDevice> devices = instanceClient.getBlockDeviceMappingForInstanceInRegion(node.getLocation()\n                  .getParent().getId(), node.getProviderId());\n\n         BlockDevice device = devices.get(\"/dev/sdn\");\n         // check delete on termination\n         assertTrue(device.isDeleteOnTermination());\n\n         volume = Iterables.getOnlyElement(ebsClient.describeVolumesInRegion(node.getLocation().getParent().getId(),\n                  device.getVolumeId()));\n         // check volume size\n         assertEquals(volumeSize, volume.getSize());\n\n         device = devices.get(\"/dev/sdo\");\n         // check delete on termination\n         assertTrue(device.isDeleteOnTermination());\n\n         volume = Iterables.getOnlyElement(ebsClient.describeVolumesInRegion(node.getLocation().getParent().getId(),\n                  device.getVolumeId()));\n         // check volume size\n         assertEquals(volumeSize, volume.getSize());\n         // check volume's snapshot id\n         assertEquals(snapshot.getId(), volume.getSnapshotId());\n\n      } finally {\n         client.destroyNodesMatching(NodePredicates.inGroup(group));\n         ebsClient.deleteSnapshotInRegion(snapshot.getRegion(), snapshot.getId());\n      }\n   }\n\n   /**\n    * Gets the instance with the given ID from the default region\n    * \n    * @throws NoSuchElementException If no instance with that id exists, or the instance is in a different region\n    */\n   public static RunningInstance getInstance(InstanceApi instanceClient, String id) {\n      Reservation<? extends RunningInstance> reservation = Iterables.getOnlyElement(instanceClient\n               .describeInstancesInRegion(null, id));\n      RunningInstance instance = Iterables.getOnlyElement(reservation);\n      return instance;\n   }\n\n   protected static void cleanupExtendedStuffInRegion(String region, SecurityGroupApi securityGroupClient,\n            KeyPairApi keyPairClient, String group) throws InterruptedException {\n      try {\n         for (SecurityGroup secgroup : securityGroupClient.describeSecurityGroupsInRegion(region))\n            if (secgroup.getName().startsWith(\"jclouds#\" + group) || secgroup.getName().equals(group)) {\n               securityGroupClient.deleteSecurityGroupInRegion(region, secgroup.getName());\n            }\n      } catch (Exception e) {\n\n      }\n      try {\n         for (KeyPair pair : keyPairClient.describeKeyPairsInRegion(region))\n            if (pair.getKeyName().startsWith(\"jclouds#\" + group) || pair.getKeyName().equals(group)) {\n               keyPairClient.deleteKeyPairInRegion(region, pair.getKeyName());\n            }\n      } catch (Exception e) {\n\n      }\n      Thread.sleep(2000);\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/compute/EC2TemplateBuilderLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute;\n\nimport static org.jclouds.http.internal.TrackingJavaUrlHttpCommandExecutorService.getArgsForRequestAtIndex;\nimport static org.jclouds.http.internal.TrackingJavaUrlHttpCommandExecutorService.getInvokerOfRequest;\nimport static org.jclouds.http.internal.TrackingJavaUrlHttpCommandExecutorService.getInvokerOfRequestAtIndex;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Collection;\nimport java.util.List;\n\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.internal.BaseTemplateBuilderLiveTest;\nimport org.jclouds.ec2.features.AMIApi;\nimport org.jclouds.ec2.features.AvailabilityZoneAndRegionApi;\nimport org.jclouds.ec2.options.DescribeAvailabilityZonesOptions;\nimport org.jclouds.ec2.options.DescribeImagesOptions;\nimport org.jclouds.ec2.options.DescribeRegionsOptions;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.internal.TrackingJavaUrlHttpCommandExecutorService;\nimport org.jclouds.logging.log4j.config.Log4JLoggingModule;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Collections2;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Lists;\nimport com.google.common.reflect.Invokable;\nimport com.google.inject.Module;\n\npublic abstract class EC2TemplateBuilderLiveTest extends BaseTemplateBuilderLiveTest {\n   \n   @Test\n   public void testTemplateBuilderCanUseImageIdWithoutFetchingAllImages() throws Exception {\n      Template defaultTemplate = view.getComputeService().templateBuilder().build();\n      String defaultImageId = defaultTemplate.getImage().getId();\n      String defaultImageProviderId = defaultTemplate.getImage().getProviderId();\n\n      ComputeServiceContext context = null;\n      try {\n         // Track http commands\n         final List<HttpCommand> commandsInvoked = Lists.newArrayList();\n         context = createView(\n               setupProperties(),\n               ImmutableSet.<Module> of(new Log4JLoggingModule(),\n                     TrackingJavaUrlHttpCommandExecutorService.newTrackingModule(commandsInvoked)));\n         \n         Template template = context.getComputeService().templateBuilder().imageId(defaultImageId)\n                  .build();\n         assertEquals(template.getImage(), defaultTemplate.getImage());\n\n         Collection<HttpCommand> filteredCommandsInvoked = Collections2.filter(commandsInvoked, new Predicate<HttpCommand>() {\n            private final Collection<Invokable<?, Object>> ignored = ImmutableSet.of(\n                     Invokable.from(AvailabilityZoneAndRegionApi.class.getMethod(\"describeRegions\", DescribeRegionsOptions[].class)),\n                     Invokable.from(AvailabilityZoneAndRegionApi.class.getMethod(\"describeAvailabilityZonesInRegion\",\n                           String.class, DescribeAvailabilityZonesOptions[].class)));\n            @Override\n            public boolean apply(HttpCommand input) {\n               return !ignored.contains(getInvokerOfRequest(input));\n            }\n         });\n         \n         assert filteredCommandsInvoked.size() == 1 : commandsInvoked;\n         assertInvokedCommand(getInvokerOfRequestAtIndex(filteredCommandsInvoked, 0), Invokable.from(AMIApi.class\n                  .getMethod(\"describeImagesInRegion\", String.class, DescribeImagesOptions[].class)));\n         assertDescribeImagesOptionsEquals((DescribeImagesOptions[])getArgsForRequestAtIndex(filteredCommandsInvoked, 0).get(1), \n                  defaultImageProviderId);\n\n      } finally {\n         if (context != null)\n            context.close();\n      }\n   }\n   \n   private static void assertDescribeImagesOptionsEquals(DescribeImagesOptions[] actual, String expectedImageId) {\n      assertEquals(actual.length, 1);\n      assertEquals(actual[0].getImageIds(), ImmutableSet.of(expectedImageId));\n   }\n   \n   protected static void assertInvokedCommand(Invokable<?, ?> actual, Invokable<?, ?> expected) {\n      // Invokables can be constructed by different meanings and be of different types. Since we\n      // only want to verify the \"wrapped\" types, let's ignore the invokable type and compare the\n      // types of the underlying methods\n      assertEquals(actual.getDeclaringClass(), expected.getDeclaringClass());\n      assertEquals(actual.getName(), expected.getName());\n      assertEquals(actual.getParameters().size(), expected.getParameters().size());\n      for (int i = 0; i < actual.getParameters().size(); i++) {\n         assertEquals(actual.getParameters().get(i).getType(), expected.getParameters().get(i).getType());\n      }\n      assertEquals(actual.getReturnType(), expected.getReturnType());\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/compute/EC2TemplateBuilderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute;\n\nimport static java.lang.String.format;\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.c1_medium;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.c1_xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.g2_2xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.m1_large;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.m1_small;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.m1_xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.m2_2xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.m2_4xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.m2_xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.t1_micro;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Map;\nimport java.util.NoSuchElementException;\nimport java.util.Set;\n\nimport jakarta.inject.Provider;\n\nimport org.jclouds.compute.domain.ComputeMetadata;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.ImageBuilder;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.domain.TemplateBuilder;\nimport org.jclouds.compute.domain.internal.TemplateBuilderImpl;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.compute.strategy.GetImageStrategy;\nimport org.jclouds.compute.suppliers.ImageCacheSupplier;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.compute.functions.ImagesToRegionAndIdMap;\nimport org.jclouds.ec2.compute.internal.EC2TemplateBuilderImpl;\nimport org.jclouds.ec2.domain.VirtualizationType;\nimport org.jclouds.rest.AuthorizationException;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Functions;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.util.concurrent.Atomics;\nimport com.google.inject.util.Providers;\n\n/**\n * Tests compute service specifically to EC2.\n * \n * These tests are designed to verify the local functionality of jclouds, rather than the\n * interaction with Amazon Web Services.\n * \n * @see EC2ComputeServiceLiveTest\n */\n@Test(testName = \"EC2TemplateBuilderTest\")\npublic class EC2TemplateBuilderTest {\n   Location provider = new LocationBuilder().scope(LocationScope.PROVIDER).id(\"aws-ec2\").description(\"aws-ec2\").build();\n\n   protected Location location = new LocationBuilder().scope(LocationScope.REGION).id(\"us-east-1\").description(\"us-east-1\")\n         .parent(provider).build();\n\n   public static final Hardware HARDWARE_SUPPORTING_BOGUS = g2_2xlarge().id(\"supporting-bogus\")\n         .supportsImageIds(ImmutableSet.of(\"us-east-1/bogus-image\"))\n         .virtualizationType(VirtualizationType.UNRECOGNIZED)\n         .build();\n\n   /**\n    * Verifies that {@link TemplateBuilderImpl} would choose the correct size of the instance, based\n    * on {@link org.jclouds.compute.domain.Hardware} from {@link EC2Hardware}.\n    * \n    * Expected size: m2.xlarge\n    */\n   @Test\n   public void testTemplateChoiceForInstanceByHardwareId() throws Exception {\n      Template template = newTemplateBuilder().os64Bit(true).hardwareId(\"m2.xlarge\").locationId(\"us-east-1\").build();\n\n      assert template != null : \"The returned template was null, but it should have a value.\";\n      // assert m2_xlarge().build().equals(template.getHardware()) : format(\n      // \"Incorrect image determined by the template. Expected: %s. Found: %s.\", \"m2.xlarge\",\n      // String.valueOf(template.getHardware()));\n      assertEquals(template.getHardware().getId(), m2_xlarge().build().getId());\n   }\n\n   @Test\n   public void testTemplateChoiceForInstanceByFastest() throws Exception {\n      Template template = newTemplateBuilder().fastest().build();\n\n      assert template != null : \"The returned template was null, but it should have a value.\";\n      assert g2_2xlarge().build().equals(template.getHardware()) : format(\n               \"Incorrect image determined by the template. Expected: %s. Found: %s.\", g2_2xlarge(), template\n                        .getHardware().getId());\n   }\n\n   /**\n    * Verifies that {@link TemplateBuilderImpl} would choose the correct size of the instance, based\n    * on physical attributes (# of cores, ram, etc).\n    * \n    * Expected size: CC1_4XLARGE\n    */\n   @Test\n   public void testTemplateChoiceForInstanceByAttributes() throws Exception {\n      Template template = newTemplateBuilder().os64Bit(true).minRam(17510).minCores(6.5).smallest().locationId(\n               \"us-east-1\").build();\n\n      assert template != null : \"The returned template was null, but it should have a value.\";\n      assertEquals(template.getHardware().getId(), m2_4xlarge().build().getId());\n   }\n\n   /**\n    * Negative test version of {@link #testTemplateChoiceForInstanceByAttributes}.\n    * \n    * Verifies that {@link TemplateBuilderImpl} would not choose the insufficient size of the\n    * instance, based on physical attributes (# of cores, ram, etc).\n    * \n    * Expected size: anything but m2.xlarge\n    */\n   @Test\n   public void testNegativeTemplateChoiceForInstanceByAttributes() throws Exception {\n      Template template = newTemplateBuilder().os64Bit(true).minRam(17510).minCores(6.7).smallest().locationId(\n               \"us-east-1\").build();\n\n      assert template != null : \"The returned template was null, but it should have a value.\";\n      assert !m2_xlarge().build().equals(template.getHardware()) : format(\n               \"Incorrect image determined by the template. Expected: not %s. Found: %s.\", \"m2.xlarge\", template\n                        .getHardware().getId());\n   }\n\n   @Test\n   public void testTemplateChoiceForInstanceByImageId() throws Exception {\n      Template template = newTemplateBuilder().imageId(\"us-east-1/bogus-image\").build();\n\n      assert template != null : \"The returned template was null, but it should have a value.\";\n      assertEquals(template.getImage().getId(), \"us-east-1/bogus-image\");\n      assertEquals(template.getHardware().getId(), HARDWARE_SUPPORTING_BOGUS.getId());\n   }\n\n   @Test\n   public void testTemplateChoiceForInstanceByImageIdDoesNotGetAllImages() throws Exception {\n      @SuppressWarnings(\"unchecked\")\n      Supplier<Set<? extends Image>> images = createMock(Supplier.class);\n      replay(images);\n      \n      final Image image = new ImageBuilder().providerId(\"bogus-image-provider\").name(\"image\").id(\"us-east-1/bogus-image\").location(location)\n               .operatingSystem(new OperatingSystem(OsFamily.UBUNTU, null, \"1.0\", \"bogus\", \"ubuntu\", true))\n               .description(\"description\").version(\"1.0\").defaultCredentials(LoginCredentials.builder().user(\"root\").build())\n               .status(Image.Status.AVAILABLE)\n               .build();\n      Map<RegionAndName, Image> imageMap = ImmutableMap.of(\n               new RegionAndName(image.getLocation().getId(), \"bogus-image\"), image);\n      \n      // weird compilation error means have to declare extra generics for call to build() - see https://bugs.eclipse.org/bugs/show_bug.cgi?id=365818\n      Supplier<LoadingCache<RegionAndName, ? extends Image>> imageCache = Suppliers.<LoadingCache<RegionAndName, ? extends Image>> ofInstance(\n               CacheBuilder.newBuilder().<RegionAndName, Image>build(CacheLoader.from(Functions.forMap(imageMap))));\n\n      Template template = newTemplateBuilder(images, imageCache).imageId(\"us-east-1/bogus-image\").build();\n\n      assert template != null : \"The returned template was null, but it should have a value.\";\n      assertEquals(template.getImage().getId(), \"us-east-1/bogus-image\");\n      assertEquals(template.getHardware().getId(), HARDWARE_SUPPORTING_BOGUS.getId());\n   }\n\n   @Test(expectedExceptions = {NoSuchElementException.class})\n   public void testNegativeTemplateChoiceForInstanceByImageId() throws Exception {\n      newTemplateBuilder().imageId(\"wrongregion/wrongimageid\").build();\n   }\n\n   private TemplateBuilder newTemplateBuilder() {\n      final Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of(\n               new ImageBuilder().providerId(\"hvm-image-provider\").name(\"image\").id(\"us-east-1/hvm-image\").location(location)\n                        .operatingSystem(new OperatingSystem(OsFamily.UBUNTU, null, \"1.0\", \"hvm\", \"ubuntu\", true))\n                        .description(\"description\").version(\"1.0\").defaultCredentials(LoginCredentials.builder().user(\"root\").build())\n                        .status(Image.Status.AVAILABLE)\n                        .build(), \n               new ImageBuilder().providerId(\"pv-image-provider\").name(\"image\").id(\"us-east-1/pv-image\").location(location)\n                        .operatingSystem(new OperatingSystem(OsFamily.UBUNTU, null, \"1.0\", \"paravirtual\", \"ubuntu\", true))\n                        .description(\"description\").version(\"1.0\").defaultCredentials(LoginCredentials.builder().user(\"root\").build())\n                        .status(Image.Status.AVAILABLE)\n                        .build(),\n               new ImageBuilder().providerId(\"bogus-image-provider\").name(\"image\").id(\"us-east-1/bogus-image\").location(location)\n                        .operatingSystem(new OperatingSystem(OsFamily.UBUNTU, null, \"1.0\", \"bogus\", \"ubuntu\", true))\n                        .description(\"description\").version(\"1.0\").defaultCredentials(LoginCredentials.builder().user(\"root\").build())\n                        .status(Image.Status.AVAILABLE)\n                        .build()));\n      \n      // weird compilation error means have to cast this - see https://bugs.eclipse.org/bugs/show_bug.cgi?id=365818\n      @SuppressWarnings(\"unchecked\")\n      ImmutableMap<RegionAndName, Image> imageMap = (ImmutableMap<RegionAndName, Image>) ImagesToRegionAndIdMap.imagesToMap(images.get());\n      Supplier<LoadingCache<RegionAndName, ? extends Image>> imageCache = Suppliers.<LoadingCache<RegionAndName, ? extends Image>> ofInstance(\n               CacheBuilder.newBuilder().<RegionAndName, Image>build(CacheLoader.from(Functions.forMap(imageMap))));\n\n      return newTemplateBuilder(images, imageCache);\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   private TemplateBuilder newTemplateBuilder(Supplier<Set<? extends Image>> images, Supplier<LoadingCache<RegionAndName, ? extends Image>> imageCache) {\n      Provider<TemplateOptions> optionsProvider = createMock(Provider.class);\n      Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);\n      TemplateOptions defaultOptions = createMock(TemplateOptions.class);\n      GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class);\n\n      expect(optionsProvider.get()).andReturn(defaultOptions);\n\n      replay(optionsProvider);\n      replay(templateBuilderProvider);\n      replay(getImageStrategy);\n      Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n               .<Location> of(location));\n      Supplier<Set<? extends Hardware>> sizes = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet\n               .<Hardware> of(t1_micro().build(), c1_medium().build(), c1_xlarge().build(), m1_large().build(),\n                        m1_small().build(), m1_xlarge().build(), m2_xlarge().build(), m2_2xlarge().build(),\n                        m2_4xlarge().build(), g2_2xlarge().build(), HARDWARE_SUPPORTING_BOGUS));\n\n      return new EC2TemplateBuilderImpl(locations, new ImageCacheSupplier(images, 60,\n            Atomics.<AuthorizationException> newReference(), Providers.of(getImageStrategy)), sizes,\n            Suppliers.ofInstance(location), optionsProvider, templateBuilderProvider, imageCache) {\n      };\n   }\n\n   Function<ComputeMetadata, String> indexer() {\n      return new Function<ComputeMetadata, String>() {\n         @Override\n         public String apply(ComputeMetadata from) {\n            return from.getProviderId();\n         }\n      };\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/compute/TestCanRecreateGroupLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute;\n\nimport org.jclouds.compute.RunNodesException;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.internal.BaseComputeServiceContextLiveTest;\nimport org.jclouds.compute.predicates.NodePredicates;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Throwables;\n\n@Test(groups = \"live\", testName = \"TestCanRecreateGroupLiveTest\")\npublic class TestCanRecreateGroupLiveTest extends BaseComputeServiceContextLiveTest {\n   public TestCanRecreateGroupLiveTest() {\n      provider = \"ec2\";\n   }\n\n   public void testCanRecreateGroup() throws Exception {\n\n      String tag = PREFIX + \"recreate\";\n      view.getComputeService().destroyNodesMatching(NodePredicates.inGroup(tag));\n\n      try {\n         Template template = view.getComputeService().templateBuilder().build();\n         view.getComputeService().createNodesInGroup(tag, 1, template);\n         view.getComputeService().destroyNodesMatching(NodePredicates.inGroup(tag));\n         view.getComputeService().createNodesInGroup(tag, 1, template);\n      } catch (RunNodesException e) {\n         System.err.println(e.getNodeErrors().keySet());\n         Throwables.propagate(e);\n      } finally {\n         view.getComputeService().destroyNodesMatching(NodePredicates.inGroup(tag));\n      }\n   }\n\n   public static final String PREFIX = System.getProperty(\"user.name\") + \"ec2\";\n\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/compute/config/EC2ComputeServiceContextModuleTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.config;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.testng.Assert.fail;\n\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.compute.loaders.RegionAndIdToImage;\nimport org.jclouds.rest.AuthorizationException;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.CacheLoader;\n\n@Test(groups = \"unit\")\npublic class EC2ComputeServiceContextModuleTest {\n   \n   @Test\n   public void testCacheLoaderDoesNotReloadAfterAuthorizationException() throws Exception {\n      EC2ComputeServiceContextModule module = new EC2ComputeServiceContextModule() {\n         public Supplier<CacheLoader<RegionAndName, Image>> provideRegionAndNameToImageSupplierCacheLoader(RegionAndIdToImage delegate) {\n            return super.provideRegionAndNameToImageSupplierCacheLoader(delegate);\n         }\n      };\n      \n      RegionAndName regionAndName = new RegionAndName(\"myregion\", \"myname\");\n      AuthorizationException authException = new AuthorizationException();\n      \n      RegionAndIdToImage mockRegionAndIdToImage = createMock(RegionAndIdToImage.class);\n      expect(mockRegionAndIdToImage.load(regionAndName)).andThrow(authException).once();\n      replay(mockRegionAndIdToImage);\n      \n      CacheLoader<RegionAndName, Image> cacheLoader = module.provideRegionAndNameToImageSupplierCacheLoader(mockRegionAndIdToImage).get();\n\n      for (int i = 0; i < 2; i++) {\n         try {\n            Image image = cacheLoader.load(regionAndName);\n            fail(\"Expected Authorization exception, but got \" + image);\n         } catch (AuthorizationException e) {\n            // success\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/compute/extensions/EC2ImageExtensionExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.extensions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.ImageTemplate;\nimport org.jclouds.compute.extensions.ImageExtension;\nimport org.jclouds.ec2.compute.internal.BaseEC2ComputeServiceExpectTest;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMap.Builder;\nimport com.google.common.util.concurrent.Futures;\n\n@Test(groups = \"unit\", testName = \"EC2ImageExtensionExpectTest\")\npublic class EC2ImageExtensionExpectTest extends BaseEC2ComputeServiceExpectTest {\n\n   public void testCreateImage() {\n      Builder<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder();\n      requestResponseMap.put(describeRegionsRequest, describeRegionsResponse);\n      requestResponseMap.put(describeAvailabilityZonesRequest, describeAvailabilityZonesResponse);\n      requestResponseMap.put(describeImagesRequest, describeImagesResponse);\n      requestResponseMap.put(describeInstanceRequest, describeInstanceResponse);\n      \n      HttpRequest createImageRequest = formSigner.filter(HttpRequest.builder().method(\"POST\")\n                       .endpoint(\"https://ec2.\" + region + \".amazonaws.com/\")\n                       .addHeader(\"Host\", \"ec2.\" + region + \".amazonaws.com\")\n                       .addFormParam(\"Action\", \"CreateImage\")\n                       .addFormParam(\"InstanceId\", \"i-2baa5550\")\n                       .addFormParam(\"Name\", \"test\").build());\n\n      HttpResponse createImageResponse = HttpResponse.builder()\n            .statusCode(200)\n            .payload(payloadFromStringWithContentType(\n            \"<CreateImageResponse><imageId>ami-be3adfd7</imageId></CreateImageResponse>\", MediaType.APPLICATION_XML)).build();\n\n      requestResponseMap.put(createImageRequest, createImageResponse);\n\n      HttpRequest describeImageRequest = formSigner.filter(HttpRequest.builder().method(\"POST\")\n                       .endpoint(\"https://ec2.\" + region + \".amazonaws.com/\")\n                       .addHeader(\"Host\", \"ec2.\" + region + \".amazonaws.com\")\n                       .addFormParam(\"Action\", \"DescribeImages\")\n                       .addFormParam(\"ImageId.1\", \"ami-be3adfd7\").build());\n\n      requestResponseMap.put(describeImageRequest, describeImagesResponse);\n\n      ImageExtension apiThatCreatesImage = requestsSendResponses(requestResponseMap.build()).getImageExtension().get();\n      \n      ImageTemplate newImageTemplate = apiThatCreatesImage.buildImageTemplateFromNode(\"test\", \"us-east-1/i-2baa5550\");\n\n      Image image = Futures.getUnchecked(apiThatCreatesImage.createImage(newImageTemplate));\n      assertEquals(image.getId(), \"us-east-1/ami-be3adfd7\");\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/compute/extensions/EC2ImageExtensionLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.extensions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.getOnlyElement;\n\nimport java.lang.reflect.Field;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.TemplateBuilder;\nimport org.jclouds.compute.domain.TemplateBuilderSpec;\nimport org.jclouds.compute.extensions.ImageExtension;\nimport org.jclouds.compute.extensions.internal.BaseImageExtensionLiveTest;\nimport org.jclouds.compute.suppliers.ImageCacheSupplier;\nimport org.jclouds.sshj.config.SshjSshClientModule;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Throwables;\nimport com.google.common.cache.LoadingCache;\nimport com.google.inject.Key;\nimport com.google.inject.Module;\nimport com.google.inject.TypeLiteral;\n\n/**\n * Live test for ec2 {@link ImageExtension} implementation\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"EC2ImageExtensionLiveTest\")\npublic class EC2ImageExtensionLiveTest extends BaseImageExtensionLiveTest {\n   protected TemplateBuilderSpec ebsTemplate;\n\n   public EC2ImageExtensionLiveTest() {\n      provider = \"ec2\";\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties overrides = super.setupProperties();\n      String ebsSpec = checkNotNull(setIfTestSystemPropertyPresent(overrides, provider + \".ebs-template\"), provider\n            + \".ebs-template\");\n      ebsTemplate = TemplateBuilderSpec.parse(ebsSpec);\n      return overrides;\n   }\n\n   // Getting an image from the cache is tricky in EC2, as images are filtered\n   // by default by owner, and the image being created will be owned by the\n   // current user. If the cache needs to refresh the list, the just added image\n   // will be removed as the image list will be refreshed (potentially) without\n   // taking into account the current user owner id. Instead of using the\n   // TempalteBuilder, just inspect the ImageCacheSupplier directly\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   protected Optional<Image> findImageWithNameInCache(String name) {\n      ImageCacheSupplier imageCache = (ImageCacheSupplier) context.utils().injector()\n            .getInstance(Key.get(new TypeLiteral<Supplier<Set<? extends Image>>>() {\n            }, Memoized.class));\n\n      try {\n         Field field = imageCache.getClass().getDeclaredField(\"imageCache\");\n         field.setAccessible(true);\n         LoadingCache<String, Image> cache = (LoadingCache<String, Image>) field.get(imageCache);\n\n         return Optional.fromNullable(getOnlyElement(filter(cache.asMap().values(), new Predicate<Image>() {\n            @Override\n            public boolean apply(Image input) {\n               return imageGroup.equals(input.getName());\n            }\n         }), null));\n      } catch (NoSuchFieldException ex) {\n         throw Throwables.propagate(ex);\n      } catch (IllegalAccessException ex) {\n         throw Throwables.propagate(ex);\n      }\n   }\n\n   @Override\n   public TemplateBuilder getNodeTemplate() {\n      return super.getNodeTemplate().from(ebsTemplate);\n   }\n\n   @Override\n   protected Module getSshModule() {\n      return new SshjSshClientModule();\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/compute/extensions/EC2SecurityGroupExtensionExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.extensions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.compute.domain.SecurityGroup;\nimport org.jclouds.compute.domain.SecurityGroupBuilder;\nimport org.jclouds.compute.extensions.SecurityGroupExtension;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.compute.internal.BaseEC2ComputeServiceExpectTest;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.net.domain.IpPermission;\nimport org.jclouds.net.domain.IpProtocol;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMap.Builder;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.LinkedHashMultimap;\nimport com.google.common.collect.Multimap;\nimport com.google.common.collect.Sets;\n\n@Test(groups = \"unit\", testName = \"EC2SecurityGroupExtensionExpectTest\")\npublic class EC2SecurityGroupExtensionExpectTest extends BaseEC2ComputeServiceExpectTest {\n   \n   public EC2SecurityGroupExtensionExpectTest() {\n      // Don't use the default (us-east-1) region. Better to ensure we always pass through the\n      // desired region, rather than it falling back to the default!\n      region = \"eu-west-1\";\n   }\n   \n   public void testListSecurityGroups() {\n      HttpRequest describeSecurityGroupsAllRequest = \n         formSigner.filter(HttpRequest.builder()\n                           .method(\"POST\")\n                           .endpoint(\"https://ec2.\" + region + \".amazonaws.com/\")\n                           .addHeader(\"Host\", \"ec2.\" + region + \".amazonaws.com\")\n                           .addFormParam(\"Action\", \"DescribeSecurityGroups\").build());\n      \n      HttpResponse describeSecurityGroupsAllResponse = \n         HttpResponse.builder().statusCode(200)\n         .payload(payloadFromResourceWithContentType(\n                                                     \"/describe_securitygroups_extension_new.xml\", MediaType.APPLICATION_XML)).build();\n      \n      Builder<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder();\n      requestResponseMap.put(describeRegionsRequest, describeRegionsResponse);\n      requestResponseMap.put(describeAvailabilityZonesRequest, describeAvailabilityZonesResponse);\n      requestResponseMap.put(describeSecurityGroupsAllRequest, describeSecurityGroupsAllResponse);\n      requestResponseMap.put(createKeyPairRequest, createKeyPairResponse);\n      requestResponseMap.put(createSecurityGroupRequest, createSecurityGroupResponse);\n\n      requestResponseMap.put(authorizeSecurityGroupIngressRequest22, authorizeSecurityGroupIngressResponse);\n      requestResponseMap.put(authorizeSecurityGroupIngressRequestGroup, authorizeSecurityGroupIngressResponse);\n      requestResponseMap.put(describeInstanceRequest, describeInstanceResponse);\n      \n\n      SecurityGroupExtension extension = requestsSendResponses(requestResponseMap.build()).getSecurityGroupExtension().get();\n      \n      Set<SecurityGroup> groups = extension.listSecurityGroups();\n      assertEquals(2, groups.size());\n   }\n\n   public void testListSecurityGroupsInLocation() {\n      HttpRequest describeSecurityGroupsAllRequest = \n         formSigner.filter(HttpRequest.builder()\n                           .method(\"POST\")\n                           .endpoint(\"https://ec2.\" + region + \".amazonaws.com/\")\n                           .addHeader(\"Host\", \"ec2.\" + region + \".amazonaws.com\")\n                           .addFormParam(\"Action\", \"DescribeSecurityGroups\").build());\n      \n      HttpResponse describeSecurityGroupsAllResponse = \n         HttpResponse.builder().statusCode(200)\n         .payload(payloadFromResourceWithContentType(\n                                                     \"/describe_securitygroups_extension_new.xml\", MediaType.APPLICATION_XML)).build();\n      \n      Builder<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder();\n      requestResponseMap.put(describeRegionsRequest, describeRegionsResponse);\n      requestResponseMap.put(describeAvailabilityZonesRequest, describeAvailabilityZonesResponse);\n      requestResponseMap.put(describeSecurityGroupsAllRequest, describeSecurityGroupsAllResponse);\n      requestResponseMap.put(createKeyPairRequest, createKeyPairResponse);\n      requestResponseMap.put(createSecurityGroupRequest, createSecurityGroupResponse);\n\n      requestResponseMap.put(authorizeSecurityGroupIngressRequest22, authorizeSecurityGroupIngressResponse);\n      requestResponseMap.put(authorizeSecurityGroupIngressRequestGroup, authorizeSecurityGroupIngressResponse);\n      requestResponseMap.put(describeInstanceRequest, describeInstanceResponse);\n      \n\n      SecurityGroupExtension extension = requestsSendResponses(requestResponseMap.build()).getSecurityGroupExtension().get();\n      \n      Set<SecurityGroup> groups = extension.listSecurityGroupsInLocation(new LocationBuilder()\n                                                                         .scope(LocationScope.REGION)\n                                                                         .id(region)\n                                                                         .description(\"region\")\n                                                                         .build());\n      assertEquals(2, groups.size());\n   }\n\n   \n   public void testListSecurityGroupsForNode() {\n      HttpRequest describeSecurityGroupsSingleRequest = \n         formSigner.filter(HttpRequest.builder()\n                           .method(\"POST\")\n                           .endpoint(\"https://ec2.\" + region + \".amazonaws.com/\")\n                           .addHeader(\"Host\", \"ec2.\" + region + \".amazonaws.com\")\n                           .addFormParam(\"Action\", \"DescribeSecurityGroups\")\n                           .addFormParam(\"GroupName.1\", \"sg-3c6ef654\").build());\n      \n      HttpResponse describeSecurityGroupsSingleResponse = \n         HttpResponse.builder().statusCode(200)\n         .payload(payloadFromResourceWithContentType(\n                                                     \"/describe_securitygroups_extension_single.xml\", MediaType.APPLICATION_XML)).build();\n      \n      HttpResponse describeInstanceWithSGResponse = \n            HttpResponse.builder().statusCode(200)\n                           .payload(payloadFromResourceWithContentType(\n                                 \"/describe_instances_running_securitygroups.xml\", MediaType.APPLICATION_XML)).build();\n\n      Builder<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder();\n      requestResponseMap.put(describeRegionsRequest, describeRegionsResponse);\n      requestResponseMap.put(describeAvailabilityZonesRequest, describeAvailabilityZonesResponse);\n      requestResponseMap.put(describeSecurityGroupsSingleRequest, describeSecurityGroupsSingleResponse);\n      requestResponseMap.put(createKeyPairRequest, createKeyPairResponse);\n      requestResponseMap.put(createSecurityGroupRequest, createSecurityGroupResponse);\n\n      requestResponseMap.put(authorizeSecurityGroupIngressRequest22, authorizeSecurityGroupIngressResponse);\n      requestResponseMap.put(authorizeSecurityGroupIngressRequestGroup, authorizeSecurityGroupIngressResponse);\n      requestResponseMap.put(describeInstanceRequest, describeInstanceWithSGResponse);\n      \n\n      SecurityGroupExtension extension = requestsSendResponses(requestResponseMap.build()).getSecurityGroupExtension().get();\n      \n      Set<SecurityGroup> groups = extension.listSecurityGroupsForNode(new RegionAndName(region, \"i-2baa5550\").slashEncode());\n      assertEquals(1, groups.size());\n   }\n\n   public void testGetSecurityGroupById() {\n      HttpRequest describeSecurityGroupsSingleRequest = \n         formSigner.filter(HttpRequest.builder()\n                           .method(\"POST\")\n                           .endpoint(\"https://ec2.\" + region + \".amazonaws.com/\")\n                           .addHeader(\"Host\", \"ec2.\" + region + \".amazonaws.com\")\n                           .addFormParam(\"Action\", \"DescribeSecurityGroups\")\n                           .addFormParam(\"GroupName.1\", \"jclouds#some-group\").build());\n      \n      HttpResponse describeSecurityGroupsSingleResponse = \n         HttpResponse.builder().statusCode(200)\n         .payload(payloadFromResourceWithContentType(\n                                                     \"/describe_securitygroups_extension_single.xml\", MediaType.APPLICATION_XML)).build();\n      \n\n      Builder<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder();\n      requestResponseMap.put(describeRegionsRequest, describeRegionsResponse);\n      requestResponseMap.put(describeAvailabilityZonesRequest, describeAvailabilityZonesResponse);\n      requestResponseMap.put(describeSecurityGroupsSingleRequest, describeSecurityGroupsSingleResponse);\n      requestResponseMap.put(createKeyPairRequest, createKeyPairResponse);\n      requestResponseMap.put(createSecurityGroupRequest, createSecurityGroupResponse);\n\n      requestResponseMap.put(authorizeSecurityGroupIngressRequest22, authorizeSecurityGroupIngressResponse);\n      requestResponseMap.put(authorizeSecurityGroupIngressRequestGroup, authorizeSecurityGroupIngressResponse);\n      \n\n      SecurityGroupExtension extension = requestsSendResponses(requestResponseMap.build()).getSecurityGroupExtension().get();\n      \n      SecurityGroup group = extension.getSecurityGroupById(new RegionAndName(region, \"jclouds#some-group\").slashEncode());\n      assertEquals(\"sg-3c6ef654\", group.getProviderId());\n      assertEquals(region + \"/jclouds#some-group\", group.getId());\n   }\n\n   public void testCreateSecurityGroup() {\n      HttpRequest createSecurityGroupExtRequest = \n               formSigner.filter(HttpRequest.builder()\n                          .method(\"POST\")\n                          .endpoint(\"https://ec2.\" + region + \".amazonaws.com/\")\n                          .addHeader(\"Host\", \"ec2.\" + region + \".amazonaws.com\")\n                          .addFormParam(\"Action\", \"CreateSecurityGroup\")\n                          .addFormParam(\"GroupDescription\", \"jclouds#some-group\")\n                          .addFormParam(\"GroupName\", \"jclouds#some-group\").build());\n\n      HttpRequest describeSecurityGroupsSingleRequest = \n         formSigner.filter(HttpRequest.builder()\n                           .method(\"POST\")\n                           .endpoint(\"https://ec2.\" + region + \".amazonaws.com/\")\n                           .addHeader(\"Host\", \"ec2.\" + region + \".amazonaws.com\")\n                           .addFormParam(\"Action\", \"DescribeSecurityGroups\")\n                           .addFormParam(\"GroupName.1\", \"jclouds#some-group\").build());\n\n      HttpResponse describeSecurityGroupsSingleResponse = \n         HttpResponse.builder().statusCode(200)\n         .payload(payloadFromResourceWithContentType(\n                                                     \"/describe_securitygroups_extension_single.xml\", MediaType.APPLICATION_XML)).build();\n      \n      HttpRequest describeSecurityGroupsSingleFilteredRequest = \n            formSigner.filter(HttpRequest.builder()\n                              .method(\"POST\")\n                              .endpoint(\"https://ec2.\" + region + \".amazonaws.com/\")\n                              .addHeader(\"Host\", \"ec2.\" + region + \".amazonaws.com\")\n                              .addFormParam(\"Action\", \"DescribeSecurityGroups\")\n                              .addFormParam(\"Filter.1.Name\", \"group-name\")\n                              .addFormParam(\"Filter.1.Value.1\", \"jclouds#some-group\").build());\n\n         HttpResponse describeSecurityGroupsSingleFilteredResponse = \n            HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResourceWithContentType(\n                                                        \"/describe_securitygroups_extension_single.xml\", MediaType.APPLICATION_XML)).build();\n\n      Builder<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder();\n      requestResponseMap.put(describeRegionsRequest, describeRegionsResponse);\n      requestResponseMap.put(describeAvailabilityZonesRequest, describeAvailabilityZonesResponse);\n      requestResponseMap.put(describeSecurityGroupsSingleFilteredRequest, describeSecurityGroupsSingleFilteredResponse);\n      requestResponseMap.put(describeSecurityGroupsSingleRequest, describeSecurityGroupsSingleResponse);\n      requestResponseMap.put(createKeyPairRequest, createKeyPairResponse);\n      requestResponseMap.put(createSecurityGroupExtRequest, createSecurityGroupResponse);\n\n      requestResponseMap.put(authorizeSecurityGroupIngressRequest22, authorizeSecurityGroupIngressResponse);\n      requestResponseMap.put(authorizeSecurityGroupIngressRequestGroup, authorizeSecurityGroupIngressResponse);\n      \n\n      SecurityGroupExtension extension = requestsSendResponses(requestResponseMap.build()).getSecurityGroupExtension().get();\n      \n      SecurityGroup group = extension.createSecurityGroup(\"some-group\", new LocationBuilder()\n                                                          .scope(LocationScope.REGION)\n                                                          .id(region)\n                                                          .description(\"region\")\n                                                          .build());\n      \n      assertEquals(\"sg-3c6ef654\", group.getProviderId());\n      assertEquals(region + \"/jclouds#some-group\", group.getId());\n   }\n\n   public void testRemoveSecurityGroup() {\n      HttpRequest describeSecurityGroupsSingleRequest = \n         formSigner.filter(HttpRequest.builder()\n                           .method(\"POST\")\n                           .endpoint(\"https://ec2.\" + region + \".amazonaws.com/\")\n                           .addHeader(\"Host\", \"ec2.\" + region + \".amazonaws.com\")\n                           .addFormParam(\"Action\", \"DescribeSecurityGroups\")\n                           .addFormParam(\"GroupName.1\", \"jclouds#some-group\").build());\n      \n      HttpResponse describeSecurityGroupsSingleResponse = \n         HttpResponse.builder().statusCode(200)\n         .payload(payloadFromResourceWithContentType(\n                                                     \"/describe_securitygroups_extension_single.xml\", MediaType.APPLICATION_XML)).build();\n      \n      HttpRequest deleteSecurityGroupRequest = \n         formSigner.filter(HttpRequest.builder()\n                           .method(\"POST\")\n                           .endpoint(\"https://ec2.\" + region + \".amazonaws.com/\")\n                           .addHeader(\"Host\", \"ec2.\" + region + \".amazonaws.com\")\n                           .addFormParam(\"Action\", \"DeleteSecurityGroup\")\n                           .addFormParam(\"GroupName\", \"jclouds#some-group\").build());\n      \n      HttpResponse deleteSecurityGroupResponse = \n         HttpResponse.builder().statusCode(200)\n         .payload(payloadFromResourceWithContentType(\n                                                     \"/delete_securitygroup.xml\", MediaType.APPLICATION_XML)).build();\n\n      Builder<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder();\n      requestResponseMap.put(describeRegionsRequest, describeRegionsResponse);\n      requestResponseMap.put(describeAvailabilityZonesRequest, describeAvailabilityZonesResponse);\n      requestResponseMap.put(describeSecurityGroupsSingleRequest, describeSecurityGroupsSingleResponse);\n      requestResponseMap.put(deleteSecurityGroupRequest, deleteSecurityGroupResponse);\n      requestResponseMap.put(createKeyPairRequest, createKeyPairResponse);\n      requestResponseMap.put(createSecurityGroupRequest, createSecurityGroupResponse);\n\n      requestResponseMap.put(authorizeSecurityGroupIngressRequest22, authorizeSecurityGroupIngressResponse);\n      requestResponseMap.put(authorizeSecurityGroupIngressRequestGroup, authorizeSecurityGroupIngressResponse);\n      \n\n      SecurityGroupExtension extension = requestsSendResponses(requestResponseMap.build()).getSecurityGroupExtension().get();\n      \n      assertTrue(extension.removeSecurityGroup(new RegionAndName(region, \"jclouds#some-group\").slashEncode()));\n   }\n\n   public void testAddIpPermissionCidrFromIpPermission() {\n      HttpRequest describeSecurityGroupsSingleRequest = \n         formSigner.filter(HttpRequest.builder()\n                           .method(\"POST\")\n                           .endpoint(\"https://ec2.\" + region + \".amazonaws.com/\")\n                           .addHeader(\"Host\", \"ec2.\" + region + \".amazonaws.com\")\n                           .addFormParam(\"Action\", \"DescribeSecurityGroups\")\n                           .addFormParam(\"GroupName.1\", \"jclouds#some-group\").build());\n      \n      HttpResponse describeSecurityGroupsSingleResponse = \n         HttpResponse.builder().statusCode(200)\n         .payload(payloadFromResourceWithContentType(\n                                                     \"/describe_securitygroups_extension_cidr.xml\", MediaType.APPLICATION_XML)).build();\n      \n\n      HttpRequest authorizeSecurityGroupIngressRequestRange = \n               formSigner.filter(HttpRequest.builder()\n                          .method(\"POST\")\n                          .endpoint(\"https://ec2.\" + region + \".amazonaws.com/\")\n                          .addHeader(\"Host\", \"ec2.\" + region + \".amazonaws.com\")\n                          .addFormParam(\"Action\", \"AuthorizeSecurityGroupIngress\")\n                          .addFormParam(\"CidrIp\", \"0.0.0.0/0\")\n                          .addFormParam(\"FromPort\", \"22\")\n                          .addFormParam(\"ToPort\", \"40\")\n                          .addFormParam(\"GroupName\", \"jclouds#some-group\")\n                          .addFormParam(\"IpProtocol\", \"tcp\").build());\n\n      Builder<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder();\n      requestResponseMap.put(describeRegionsRequest, describeRegionsResponse);\n      requestResponseMap.put(describeAvailabilityZonesRequest, describeAvailabilityZonesResponse);\n      requestResponseMap.put(describeSecurityGroupsSingleRequest, describeSecurityGroupsSingleResponse);\n      requestResponseMap.put(createKeyPairRequest, createKeyPairResponse);\n      requestResponseMap.put(createSecurityGroupRequest, createSecurityGroupResponse);\n\n      requestResponseMap.put(authorizeSecurityGroupIngressRequestRange, authorizeSecurityGroupIngressResponse);\n\n      IpPermission.Builder builder = IpPermission.builder();\n\n      builder.ipProtocol(IpProtocol.TCP);\n      builder.fromPort(22);\n      builder.toPort(40);\n      builder.cidrBlock(\"0.0.0.0/0\");\n\n      IpPermission perm = builder.build();\n\n      SecurityGroupExtension extension = requestsSendResponses(requestResponseMap.build()).getSecurityGroupExtension().get();\n\n      SecurityGroupBuilder groupBuilder = new SecurityGroupBuilder();\n      groupBuilder.id(\"jclouds#some-group\");\n      groupBuilder.providerId(\"sg-3c6ef654\");\n      groupBuilder.name(\"jclouds#some-group\");\n      groupBuilder.location(new LocationBuilder()\n                            .scope(LocationScope.REGION)\n                            .id(region)\n                            .description(\"region\")\n                            .build());\n      \n      SecurityGroup origGroup = groupBuilder.build();\n\n      SecurityGroup newGroup = extension.addIpPermission(perm, origGroup);\n\n      assertEquals(1, newGroup.getIpPermissions().size());\n\n      IpPermission newPerm = Iterables.getOnlyElement(newGroup.getIpPermissions());\n\n      assertNotNull(newPerm);\n      assertEquals(IpProtocol.TCP, newPerm.getIpProtocol());\n      assertEquals(22, newPerm.getFromPort());\n      assertEquals(40, newPerm.getToPort());\n      assertEquals(1, newPerm.getCidrBlocks().size());\n      assertTrue(newPerm.getCidrBlocks().contains(\"0.0.0.0/0\"));\n   }\n\n   public void testAddIpPermissionCidrFromParams() {\n      HttpRequest describeSecurityGroupsSingleRequest = \n         formSigner.filter(HttpRequest.builder()\n                           .method(\"POST\")\n                           .endpoint(\"https://ec2.\" + region + \".amazonaws.com/\")\n                           .addHeader(\"Host\", \"ec2.\" + region + \".amazonaws.com\")\n                           .addFormParam(\"Action\", \"DescribeSecurityGroups\")\n                           .addFormParam(\"GroupName.1\", \"jclouds#some-group\").build());\n      \n      HttpResponse describeSecurityGroupsSingleResponse = \n         HttpResponse.builder().statusCode(200)\n         .payload(payloadFromResourceWithContentType(\n                                                     \"/describe_securitygroups_extension_cidr.xml\", MediaType.APPLICATION_XML)).build();\n      \n\n      HttpRequest authorizeSecurityGroupIngressRequestRange = \n               formSigner.filter(HttpRequest.builder()\n                          .method(\"POST\")\n                          .endpoint(\"https://ec2.\" + region + \".amazonaws.com/\")\n                          .addHeader(\"Host\", \"ec2.\" + region + \".amazonaws.com\")\n                          .addFormParam(\"Action\", \"AuthorizeSecurityGroupIngress\")\n                          .addFormParam(\"CidrIp\", \"0.0.0.0/0\")\n                          .addFormParam(\"FromPort\", \"22\")\n                          .addFormParam(\"ToPort\", \"40\")\n                          .addFormParam(\"GroupName\", \"jclouds#some-group\")\n                          .addFormParam(\"IpProtocol\", \"tcp\").build());\n\n      Builder<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder();\n      requestResponseMap.put(describeRegionsRequest, describeRegionsResponse);\n      requestResponseMap.put(describeAvailabilityZonesRequest, describeAvailabilityZonesResponse);\n      requestResponseMap.put(describeSecurityGroupsSingleRequest, describeSecurityGroupsSingleResponse);\n      requestResponseMap.put(createKeyPairRequest, createKeyPairResponse);\n      requestResponseMap.put(createSecurityGroupRequest, createSecurityGroupResponse);\n\n      requestResponseMap.put(authorizeSecurityGroupIngressRequestRange, authorizeSecurityGroupIngressResponse);\n\n      SecurityGroupExtension extension = requestsSendResponses(requestResponseMap.build()).getSecurityGroupExtension().get();\n\n      SecurityGroupBuilder groupBuilder = new SecurityGroupBuilder();\n      groupBuilder.id(\"jclouds#some-group\");\n      groupBuilder.providerId(\"sg-3c6ef654\");\n      groupBuilder.name(\"jclouds#some-group\");\n      groupBuilder.location(new LocationBuilder()\n                            .scope(LocationScope.REGION)\n                            .id(region)\n                            .description(\"region\")\n                            .build());\n      \n      SecurityGroup origGroup = groupBuilder.build();\n\n      SecurityGroup newGroup = extension.addIpPermission(IpProtocol.TCP,\n                                                         22,\n                                                         40,\n                                                         emptyMultimap(),\n                                                         ImmutableSet.of(\"0.0.0.0/0\"),\n                                                         emptyStringSet(),\n                                                         origGroup);\n\n      assertEquals(1, newGroup.getIpPermissions().size());\n\n      IpPermission newPerm = Iterables.getOnlyElement(newGroup.getIpPermissions());\n\n      assertNotNull(newPerm);\n      assertEquals(IpProtocol.TCP, newPerm.getIpProtocol());\n      assertEquals(22, newPerm.getFromPort());\n      assertEquals(40, newPerm.getToPort());\n      assertEquals(1, newPerm.getCidrBlocks().size());\n      assertTrue(newPerm.getCidrBlocks().contains(\"0.0.0.0/0\"));\n   }\n\n\n   public void testAddIpPermissionGroupFromIpPermission() {\n      HttpRequest describeSecurityGroupsSingleRequest = \n         formSigner.filter(HttpRequest.builder()\n                           .method(\"POST\")\n                           .endpoint(\"https://ec2.\" + region + \".amazonaws.com/\")\n                           .addHeader(\"Host\", \"ec2.\" + region + \".amazonaws.com\")\n                           .addFormParam(\"Action\", \"DescribeSecurityGroups\")\n                           .addFormParam(\"GroupName.1\", \"jclouds#some-group\").build());\n      \n      HttpResponse describeSecurityGroupsSingleResponse = \n         HttpResponse.builder().statusCode(200)\n         .payload(payloadFromResourceWithContentType(\n                                                     \"/describe_securitygroups_extension_group.xml\", MediaType.APPLICATION_XML)).build();\n      \n\n      HttpRequest authorizeSecurityGroupIngressRequestGroupTenant = \n               formSigner.filter(HttpRequest.builder()\n                          .method(\"POST\")\n                          .endpoint(\"https://ec2.\" + region + \".amazonaws.com/\")\n                          .addHeader(\"Host\", \"ec2.\" + region + \".amazonaws.com\")\n                          .addFormParam(\"Action\", \"AuthorizeSecurityGroupIngress\")\n                          .addFormParam(\"SourceSecurityGroupName\", \"jclouds#some-group\")\n                          .addFormParam(\"SourceSecurityGroupOwnerId\", \"993194456877\")\n                          .addFormParam(\"GroupName\", \"jclouds#some-group\").build());\n\n      Builder<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder();\n      requestResponseMap.put(describeRegionsRequest, describeRegionsResponse);\n      requestResponseMap.put(describeAvailabilityZonesRequest, describeAvailabilityZonesResponse);\n      requestResponseMap.put(describeSecurityGroupsSingleRequest, describeSecurityGroupsSingleResponse);\n      requestResponseMap.put(createKeyPairRequest, createKeyPairResponse);\n      requestResponseMap.put(createSecurityGroupRequest, createSecurityGroupResponse);\n\n      requestResponseMap.put(authorizeSecurityGroupIngressRequestGroupTenant, authorizeSecurityGroupIngressResponse);\n\n      IpPermission.Builder builder = IpPermission.builder();\n\n      builder.ipProtocol(IpProtocol.TCP);\n      builder.fromPort(22);\n      builder.toPort(40);\n      builder.tenantIdGroupNamePair(\"993194456877\", \"jclouds#some-group\");\n\n      IpPermission perm = builder.build();\n\n      SecurityGroupExtension extension = requestsSendResponses(requestResponseMap.build()).getSecurityGroupExtension().get();\n\n      SecurityGroupBuilder groupBuilder = new SecurityGroupBuilder();\n      groupBuilder.id(\"jclouds#some-group\");\n      groupBuilder.providerId(\"sg-3c6ef654\");\n      groupBuilder.name(\"jclouds#some-group\");\n      groupBuilder.location(new LocationBuilder()\n                            .scope(LocationScope.REGION)\n                            .id(region)\n                            .description(\"region\")\n                            .build());\n      groupBuilder.ownerId(\"993194456877\");\n      \n      SecurityGroup origGroup = groupBuilder.build();\n\n      SecurityGroup newGroup = extension.addIpPermission(perm, origGroup);\n\n      assertEquals(1, newGroup.getIpPermissions().size());\n\n      IpPermission newPerm = Iterables.getOnlyElement(newGroup.getIpPermissions());\n\n      assertNotNull(newPerm);\n      assertEquals(IpProtocol.TCP, newPerm.getIpProtocol());\n      assertEquals(22, newPerm.getFromPort());\n      assertEquals(40, newPerm.getToPort());\n      assertEquals(0, newPerm.getCidrBlocks().size());\n      assertEquals(1, newPerm.getTenantIdGroupNamePairs().size());\n      assertTrue(newPerm.getTenantIdGroupNamePairs().keySet().contains(origGroup.getOwnerId()));\n      assertTrue(newPerm.getTenantIdGroupNamePairs().values().contains(origGroup.getName()));\n   }\n\n   public void testAddIpPermissionGroupFromParams() {\n      HttpRequest describeSecurityGroupsSingleRequest = \n         formSigner.filter(HttpRequest.builder()\n                           .method(\"POST\")\n                           .endpoint(\"https://ec2.\" + region + \".amazonaws.com/\")\n                           .addHeader(\"Host\", \"ec2.\" + region + \".amazonaws.com\")\n                           .addFormParam(\"Action\", \"DescribeSecurityGroups\")\n                           .addFormParam(\"GroupName.1\", \"jclouds#some-group\").build());\n      \n      HttpResponse describeSecurityGroupsSingleResponse = \n         HttpResponse.builder().statusCode(200)\n         .payload(payloadFromResourceWithContentType(\n                                                     \"/describe_securitygroups_extension_group.xml\", MediaType.APPLICATION_XML)).build();\n      \n\n      HttpRequest authorizeSecurityGroupIngressRequestGroupTenant = \n               formSigner.filter(HttpRequest.builder()\n                          .method(\"POST\")\n                          .endpoint(\"https://ec2.\" + region + \".amazonaws.com/\")\n                          .addHeader(\"Host\", \"ec2.\" + region + \".amazonaws.com\")\n                          .addFormParam(\"Action\", \"AuthorizeSecurityGroupIngress\")\n                          .addFormParam(\"SourceSecurityGroupName\", \"jclouds#some-group\")\n                          .addFormParam(\"SourceSecurityGroupOwnerId\", \"993194456877\")\n                          .addFormParam(\"GroupName\", \"jclouds#some-group\").build());\n\n      Builder<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder();\n      requestResponseMap.put(describeRegionsRequest, describeRegionsResponse);\n      requestResponseMap.put(describeAvailabilityZonesRequest, describeAvailabilityZonesResponse);\n      requestResponseMap.put(describeSecurityGroupsSingleRequest, describeSecurityGroupsSingleResponse);\n      requestResponseMap.put(createKeyPairRequest, createKeyPairResponse);\n      requestResponseMap.put(createSecurityGroupRequest, createSecurityGroupResponse);\n\n      requestResponseMap.put(authorizeSecurityGroupIngressRequestGroupTenant, authorizeSecurityGroupIngressResponse);\n\n      SecurityGroupExtension extension = requestsSendResponses(requestResponseMap.build()).getSecurityGroupExtension().get();\n\n      SecurityGroupBuilder groupBuilder = new SecurityGroupBuilder();\n      groupBuilder.id(\"jclouds#some-group\");\n      groupBuilder.providerId(\"sg-3c6ef654\");\n      groupBuilder.name(\"jclouds#some-group\");\n      groupBuilder.ownerId(\"993194456877\");\n      groupBuilder.location(new LocationBuilder()\n                            .scope(LocationScope.REGION)\n                            .id(region)\n                            .description(\"region\")\n                            .build());\n      \n      SecurityGroup origGroup = groupBuilder.build();\n\n      ImmutableMultimap.Builder<String, String> permBuilder = ImmutableMultimap.builder();\n      permBuilder.put(origGroup.getOwnerId(), origGroup.getName());\n      \n      SecurityGroup newGroup = extension.addIpPermission(IpProtocol.TCP,\n                                                         22,\n                                                         40,\n                                                         permBuilder.build(),\n                                                         emptyStringSet(),\n                                                         emptyStringSet(),\n                                                         origGroup);\n\n      assertEquals(1, newGroup.getIpPermissions().size());\n\n      IpPermission newPerm = Iterables.getOnlyElement(newGroup.getIpPermissions());\n\n      assertNotNull(newPerm);\n      assertEquals(IpProtocol.TCP, newPerm.getIpProtocol());\n      assertEquals(22, newPerm.getFromPort());\n      assertEquals(40, newPerm.getToPort());\n      assertEquals(0, newPerm.getCidrBlocks().size());\n      assertEquals(1, newPerm.getTenantIdGroupNamePairs().size());\n      assertTrue(newPerm.getTenantIdGroupNamePairs().keySet().contains(origGroup.getOwnerId()));\n      assertTrue(newPerm.getTenantIdGroupNamePairs().values().contains(origGroup.getName()));\n   }\n\n   private Multimap<String, String> emptyMultimap() {\n      return LinkedHashMultimap.create();\n   }\n\n   private Set<String> emptyStringSet() {\n      return Sets.newLinkedHashSet();\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/compute/extensions/EC2SecurityGroupExtensionLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.extensions;\n\nimport org.jclouds.compute.extensions.internal.BaseSecurityGroupExtensionLiveTest;\nimport org.testng.annotations.Test;\n\n\n/**\n * Live test for ec2 {@link SecurityGroupExtension} implementation\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"EC2SecurityGroupExtensionLiveTest\")\npublic class EC2SecurityGroupExtensionLiveTest extends BaseSecurityGroupExtensionLiveTest {\n\n   public EC2SecurityGroupExtensionLiveTest() {\n      provider = \"ec2\";\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/compute/functions/AddElasticIpsToNodemetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadataBuilder;\nimport org.jclouds.compute.domain.NodeMetadata.Status;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.testng.annotations.Test;\n\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\", singleThreaded = true, testName = \"AddElasticIpsToNodemetadataTest\")\npublic class AddElasticIpsToNodemetadataTest {\n\n   NodeMetadata node = new NodeMetadataBuilder().status(Status.RUNNING).group(\"zkclustertest\").name(\"foo\").hostname(\n            \"ip-10-212-81-7\").privateAddresses(ImmutableSet.of(\"10.212.81.7\")).publicAddresses(\n            ImmutableSet.of(\"174.129.173.155\")).imageId(\"us-east-1/ami-63be790a\").id(\"us-east-1/i-911444f0\")\n            .providerId(\"i-911444f0\").tags(ImmutableSet.of(\"Empty\")).userMetadata(ImmutableMap.of(\"Name\", \"foo\"))\n            .build();\n\n   @Test\n   public void testReturnsNodeWithElasticIpWhenFoundInCacheAndNodeHadAPublicIp() throws Exception {\n      RegionAndName key = new RegionAndName(\"us-east-1\", node.getProviderId());\n      String val = \"1.1.1.1\";\n      LoadingCache<RegionAndName, String> cache = cacheOf(key, val);\n\n      AddElasticIpsToNodemetadata fn = new AddElasticIpsToNodemetadata(cache);\n\n      assertEquals(fn.apply(node).getPublicAddresses(), ImmutableSet.of(\"1.1.1.1\"));\n   }\n\n   @Test\n   public void testReturnsNodeWithIpWhenFoundInCacheAndNodeHadNoPublicIp() throws Exception {\n      RegionAndName key = new RegionAndName(\"us-east-1\", node.getProviderId());\n      String val = \"1.1.1.1\";\n      LoadingCache<RegionAndName, String> cache = cacheOf(key, val);\n\n      AddElasticIpsToNodemetadata fn = new AddElasticIpsToNodemetadata(cache);\n\n      assertEquals(fn.apply(\n               NodeMetadataBuilder.fromNodeMetadata(node).publicAddresses(ImmutableSet.<String> of()).build())\n               .getPublicAddresses(), ImmutableSet.of(\"1.1.1.1\"));\n   }\n\n   @Test\n   public void testReturnsSameNodeWhenNotFoundInCache() throws Exception {\n      RegionAndName key = new RegionAndName(\"us-east-1\", node.getProviderId());\n      String val = null;\n      LoadingCache<RegionAndName, String> cache = cacheOf(key, val);\n\n      AddElasticIpsToNodemetadata fn = new AddElasticIpsToNodemetadata(cache);\n\n      assertEquals(fn.apply(node).getPublicAddresses(), ImmutableSet.of(\"174.129.173.155\"));\n   }\n\n   private LoadingCache<RegionAndName, String> cacheOf(final RegionAndName key, final String val) {\n      return CacheBuilder.newBuilder().build(new CacheLoader<RegionAndName, String>() {\n\n         @Override\n         public String load(RegionAndName in) throws Exception {\n            return key.equals(in) ? val : null;\n         }\n\n      });\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/compute/functions/CreateUniqueKeyPairTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.functions;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.UnknownHostException;\n\nimport org.jclouds.ec2.EC2ApiMetadata;\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.domain.KeyPair;\nimport org.jclouds.ec2.features.KeyPairApi;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.name.Names;\n\n@Test(groups = \"unit\", testName = \"CreateUniqueKeyPairTest\")\npublic class CreateUniqueKeyPairTest {\n   \n   @Test\n   public void testApply() throws UnknownHostException {\n      final EC2Api client = createMock(EC2Api.class);\n      KeyPairApi keyClient = createMock(KeyPairApi.class);\n      KeyPair pair = createMock(KeyPair.class);\n\n      expect(client.getKeyPairApi()).andReturn((Optional) Optional.of(keyClient)).atLeastOnce();\n\n      expect(keyClient.createKeyPairInRegion(\"region\", \"jclouds#group#1\")).andReturn(pair);\n\n      replay(client);\n      replay(keyClient);\n\n      CreateUniqueKeyPair parser = Guice.createInjector(new AbstractModule() {\n\n         @Override\n         protected void configure() {\n            Names.bindProperties(binder(), new EC2ApiMetadata().getDefaultProperties());\n            bind(new TypeLiteral<Supplier<String>>() {\n            }).toInstance(Suppliers.ofInstance(\"1\"));\n            bind(EC2Api.class).toInstance(client);\n         }\n\n      }).getInstance(CreateUniqueKeyPair.class);\n\n      assertEquals(parser.createNewKeyPairInRegion(\"region\", \"group\"), pair);\n\n      verify(client);\n      verify(keyClient);\n   }\n\n   @SuppressWarnings( { \"unchecked\" })\n   @Test\n   public void testApplyWithIllegalStateException() throws UnknownHostException {\n      final EC2Api client = createMock(EC2Api.class);\n      KeyPairApi keyClient = createMock(KeyPairApi.class);\n      final Supplier<String> uniqueIdSupplier = createMock(Supplier.class);\n\n      KeyPair pair = createMock(KeyPair.class);\n\n      expect(client.getKeyPairApi()).andReturn((Optional) Optional.of(keyClient)).atLeastOnce();\n\n      expect(uniqueIdSupplier.get()).andReturn(\"1\");\n      expect(keyClient.createKeyPairInRegion(\"region\", \"jclouds#group#1\")).andThrow(new IllegalStateException());\n      expect(uniqueIdSupplier.get()).andReturn(\"2\");\n      expect(keyClient.createKeyPairInRegion(\"region\", \"jclouds#group#2\")).andReturn(pair);\n\n      replay(client);\n      replay(keyClient);\n      replay(uniqueIdSupplier);\n\n      CreateUniqueKeyPair parser = Guice.createInjector(new AbstractModule() {\n\n         @Override\n         protected void configure() {\n            Names.bindProperties(binder(), new EC2ApiMetadata().getDefaultProperties());\n            bind(new TypeLiteral<Supplier<String>>() {\n            }).toInstance(uniqueIdSupplier);\n            bind(EC2Api.class).toInstance(client);\n         }\n\n      }).getInstance(CreateUniqueKeyPair.class);\n\n      assertEquals(parser.createNewKeyPairInRegion(\"region\", \"group\"), pair);\n\n      verify(client);\n      verify(keyClient);\n      verify(uniqueIdSupplier);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/compute/functions/EC2ImageParserTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.compute.config.BaseComputeServiceContextModule;\nimport org.jclouds.compute.domain.Image.Status;\nimport org.jclouds.compute.domain.ImageBuilder;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.ec2.compute.config.EC2ComputeServiceDependenciesModule;\nimport org.jclouds.ec2.compute.strategy.EC2PopulateDefaultLoginCredentialsForImageStrategy;\nimport org.jclouds.ec2.compute.strategy.ReviseParsedImage;\nimport org.jclouds.ec2.domain.Image;\nimport org.jclouds.ec2.xml.DescribeImagesResponseHandlerTest;\nimport org.jclouds.json.Json;\nimport org.jclouds.json.config.GsonModule;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicates;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Sets;\nimport com.google.inject.Guice;\n\n@Test(groups = \"unit\", testName = \"EC2ImageParserTest\")\npublic class EC2ImageParserTest {\n\n   public void testParseAmznImage() {\n\n      Set<org.jclouds.compute.domain.Image> result = convertImages(\"/amzn_images.xml\");\n      for (org.jclouds.compute.domain.Image image : result) {\n         assertEquals(image.getStatus(), Status.AVAILABLE);\n         assertEquals(image.getBackendStatus(), \"available\");\n      }\n      \n      assertImageEquals(Iterables.get(result, 0), new ImageBuilder().operatingSystem(\n               new OperatingSystem.Builder().family(OsFamily.UNRECOGNIZED).arch(\"paravirtual\").version(\"\").description(\n                        \"137112412989/amzn-ami-0.9.7-beta.i386-ebs\").is64Bit(false).build()).description(\"Amazon\")\n               .defaultCredentials(LoginCredentials.builder().user(\"ec2-user\").build()).id(\"us-east-1/ami-82e4b5c7\").name(\n                        \"amzn-ami-0.9.7-beta.i386-ebs\").providerId(\"ami-82e4b5c7\").location(defaultLocation)\n               .userMetadata(ImmutableMap.of(\"owner\", \"137112412989\", \"rootDeviceType\", \"ebs\")).status(\n                        Status.AVAILABLE).backendStatus(\"available\").build());\n\n      assertImageEquals(Iterables.get(result, 3), new ImageBuilder().operatingSystem(\n               new OperatingSystem.Builder().family(OsFamily.UNRECOGNIZED).arch(\"paravirtual\").version(\"\").description(\n                        \"amzn-ami-us-west-1/amzn-ami-0.9.7-beta.x86_64.manifest.xml\").is64Bit(true).build())\n               .description(\"Amazon Linux AMI x86_64 S3\").defaultCredentials(LoginCredentials.builder().user(\"ec2-user\").build())\n               .id(\"us-east-1/ami-f2e4b5b7\").providerId(\"ami-f2e4b5b7\").name(\"amzn-ami-0.9.7-beta.x86_64-S3\").location(\n                        defaultLocation)\n               .userMetadata(ImmutableMap.of(\"owner\", \"137112412989\", \"rootDeviceType\", \"ebs\")).status(\n                        Status.AVAILABLE).backendStatus(\"available\").build());\n      \n      assertImageEquals(Iterables.get(result, 4), new ImageBuilder().operatingSystem(\n               new OperatingSystem.Builder().family(OsFamily.WINDOWS).arch(\"hvm\").version(\"2008\").description(\n                        \"amazon/NameGivesNoClue_Server-2008-R2_SP1-Language_Packs-64Bit-Base-2012.05.10\")\n                        .is64Bit(true).build())\n               .description(\"Microsoft Windows Server 2008 R2 SP1 Datacenter 64-bit Multi-language AMI provided by Amazon\")\n               .defaultCredentials(LoginCredentials.builder().user(\"root\").build())\n               .id(\"us-east-1/ami-85457ff1\").providerId(\"ami-85457ff1\").name(\"NameGivesNoClue_Server-2008-R2_SP1-Language_Packs-64Bit-Base-2012.05.10\")\n                        .location(defaultLocation)\n               .userMetadata(ImmutableMap.of(\"owner\", \"801119661308\", \"rootDeviceType\", \"ebs\"))\n               .status(Status.AVAILABLE).backendStatus(\"available\").build());\n      \n   }\n\n   private void assertImageEquals(org.jclouds.compute.domain.Image actual, org.jclouds.compute.domain.Image expected) {\n      // Note that ImageImpl.equals does not compare operating system etc; there's an explicit comment:\n      // equals from super is sufficient to establish identity equivalence\n      assertEquals(actual, expected);\n      assertEquals(actual.getOperatingSystem(), expected.getOperatingSystem());\n      assertEquals(actual.getStatus(), expected.getStatus());\n      assertEquals(actual.getBackendStatus(), expected.getBackendStatus());\n      assertEquals(actual.getVersion(), expected.getVersion());\n      assertEquals(actual.getDescription(), expected.getDescription());\n      assertEquals(actual.getDefaultCredentials(), expected.getDefaultCredentials());\n   }\n   \n   static Location defaultLocation = new LocationBuilder().scope(LocationScope.REGION).id(\"us-east-1\").description(\n            \"us-east-1\").build();\n\n   public static Set<org.jclouds.compute.domain.Image> convertImages(String resource) {\n\n      Map<OsFamily, Map<String, String>> map = new BaseComputeServiceContextModule() {\n      }.provideOsVersionMap(new ComputeServiceConstants.ReferenceData(), Guice.createInjector(new GsonModule())\n               .getInstance(Json.class));\n\n      Set<Image> result = DescribeImagesResponseHandlerTest.parseImages(resource);\n      EC2ImageParser parser = new EC2ImageParser(EC2ComputeServiceDependenciesModule.toPortableImageStatus,\n               new EC2PopulateDefaultLoginCredentialsForImageStrategy(), map, Suppliers\n                        .<Set<? extends Location>> ofInstance(ImmutableSet.<Location> of(defaultLocation)), Suppliers\n                        .ofInstance(defaultLocation), new ReviseParsedImage.NoopReviseParsedImage());\n      return Sets.newLinkedHashSet(Iterables.filter(Iterables.transform(result, parser), Predicates.notNull()));\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/compute/functions/EC2SecurityGroupToSecurityGroupTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.SecurityGroup;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.ec2.util.IpPermissions;\nimport org.jclouds.net.domain.IpPermission;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\", testName = \"EC2SecurityGroupToSecurityGroupTest\")\npublic class EC2SecurityGroupToSecurityGroupTest {\n\n   static Location provider = new LocationBuilder().scope(LocationScope.REGION).id(\"us-east-1\")\n         .description(\"us-east-1\").build();\n\n   @Test\n   public void testApply() {\n      IpPermissions authorization = IpPermissions.permitAnyProtocol();\n\n      org.jclouds.ec2.domain.SecurityGroup origGroup = org.jclouds.ec2.domain.SecurityGroup.builder()\n         .region(\"us-east-1\")\n         .id(\"some-id\")\n         .name(\"some-group\")\n         .ownerId(\"some-owner\")\n         .description(\"some-description\")\n         .ipPermission(authorization)\n         .build();\n\n      EC2SecurityGroupToSecurityGroup parser = createGroupParser(ImmutableSet.of(provider));\n\n      SecurityGroup group = parser.apply(origGroup);\n      \n      assertEquals(group.getLocation(), provider);\n      assertEquals(group.getId(), provider.getId() + \"/\" + origGroup.getName());\n      assertEquals(group.getProviderId(), origGroup.getId());\n      assertEquals(group.getName(), origGroup.getName());\n      assertEquals(group.getIpPermissions(), (Set<IpPermission>)origGroup);\n      assertEquals(group.getOwnerId(), origGroup.getOwnerId());\n   }\n\n   private EC2SecurityGroupToSecurityGroup createGroupParser(final ImmutableSet<Location> locations) {\n      Supplier<Set<? extends Location>> locationSupplier = new Supplier<Set<? extends Location>>() {\n\n         @Override\n         public Set<? extends Location> get() {\n            return locations;\n         }\n\n      };\n\n      EC2SecurityGroupToSecurityGroup parser = new EC2SecurityGroupToSecurityGroup(locationSupplier);\n\n      return parser;\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/compute/functions/PresentInstancesTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.functions;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Set;\n\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.domain.Reservation;\nimport org.jclouds.ec2.domain.RunningInstance;\nimport org.jclouds.ec2.features.InstanceApi;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\")\npublic class PresentInstancesTest {\n   RunningInstance instance1 = createMock(RunningInstance.class);\n   RunningInstance instance2 = createMock(RunningInstance.class);\n\n   @SuppressWarnings(\"unchecked\")\n   @Test\n   public void testWhenInstancesPresentSingleCall() {\n\n      EC2Api client = createMock(EC2Api.class);\n      InstanceApi instanceClient = createMock(InstanceApi.class);\n\n      expect(client.getInstanceApi()).andReturn((Optional) Optional.of(instanceClient));\n\n      // avoid imatcher fail.  if you change this, be sure to check multiple jres\n      expect(instanceClient.describeInstancesInRegion(\"us-east-1\", \"i-aaaa\", \"i-bbbb\")).andReturn(\n            Set.class.cast(ImmutableSet.of(Reservation.builder().region(\"us-east-1\")\n                  .instances(ImmutableSet.of(instance1, instance2)).build())));\n\n      replay(client, instanceClient);\n\n      PresentInstances fn = new PresentInstances(client);\n\n      assertEquals(fn.apply(ImmutableSet.of(new RegionAndName(\"us-east-1\", \"i-aaaa\"), new RegionAndName(\"us-east-1\",\n            \"i-bbbb\"))), ImmutableSet.of(instance1, instance2));\n\n      verify(client, instanceClient);\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/compute/functions/RunningInstanceToNodeMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.functions;\n\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.m1_small;\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.UnknownHostException;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadataBuilder;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.NodeMetadata.Status;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.ec2.EC2ApiMetadata;\nimport org.jclouds.ec2.compute.config.EC2ComputeServiceDependenciesModule;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.domain.InstanceState;\nimport org.jclouds.ec2.domain.RunningInstance;\nimport org.jclouds.ec2.xml.DescribeInstancesResponseHandlerTest;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.name.Names;\n\n@Test(groups = \"unit\", testName = \"RunningInstanceToNodeMetadataTest\")\npublic class RunningInstanceToNodeMetadataTest {\n\n   public void testAllStatesCovered() {\n\n      for (InstanceState status : InstanceState.values()) {\n         assert EC2ComputeServiceDependenciesModule.toPortableNodeStatus.containsKey(status) : status;\n      }\n\n   }\n\n   @Test\n   public void testPrivateIpAddressIncorrectlyInPublicAddressFieldGoesToPrivateAddressCollection() {\n      RunningInstance instance = RunningInstance.builder().instanceId(\"id\").imageId(\"image\").instanceType(\"m1.small\")\n               .instanceState(InstanceState.RUNNING).rawState(\"running\").region(\"us-east-1\").ipAddress(\"10.1.1.1\").build();\n\n      RunningInstanceToNodeMetadata parser = createNodeParser(ImmutableSet.<Hardware> of(), ImmutableSet\n               .<Location> of(), ImmutableSet.<Image> of(), ImmutableMap.<String, Credentials> of());\n\n      assertEquals(parser.apply(instance).toString(), new NodeMetadataBuilder().status(Status.RUNNING).backendStatus(\"running\").publicAddresses(\n               ImmutableSet.<String> of()).privateAddresses(ImmutableSet.of(\"10.1.1.1\")).id(\"us-east-1/id\").imageId(\n               \"us-east-1/image\").providerId(\"id\").build().toString());\n   }\n\n   @Test\n   public void testPublicIpAddressIncorrectlyInPrivateAddressFieldGoesToPublicAddressCollection() {\n      RunningInstance instance = RunningInstance.builder().instanceId(\"id\").imageId(\"image\").instanceType(\"m1.small\")\n               .instanceState(InstanceState.RUNNING).rawState(\"running\").region(\"us-east-1\").privateIpAddress(\"1.1.1.1\").build();\n\n      RunningInstanceToNodeMetadata parser = createNodeParser(ImmutableSet.<Hardware> of(), ImmutableSet\n               .<Location> of(), ImmutableSet.<Image> of(), ImmutableMap.<String, Credentials> of());\n\n      assertEquals(parser.apply(instance).toString(), new NodeMetadataBuilder().status(Status.RUNNING).backendStatus(\"running\").privateAddresses(\n               ImmutableSet.<String> of()).publicAddresses(ImmutableSet.of(\"1.1.1.1\")).id(\"us-east-1/id\").imageId(\n               \"us-east-1/image\").providerId(\"id\").build().toString());\n   }\n\n   static Location provider = new LocationBuilder().scope(LocationScope.REGION).id(\"us-east-1\")\n            .description(\"us-east-1\").build();\n\n   @Test\n   public void testApplyWhereTagDoesntMatchAndImageHardwareAndLocationNotFoundButCredentialsFound()\n            throws UnknownHostException {\n      LoginCredentials creds = LoginCredentials.builder().user(\"root\").password(\"abdce\").build();\n\n      RunningInstanceToNodeMetadata parser = createNodeParser(ImmutableSet.<Hardware> of(), ImmutableSet\n               .<Location> of(), ImmutableSet.<Image> of(), ImmutableMap.<String, Credentials> of(\n               \"node#us-east-1/i-0799056f\", creds));\n\n      RunningInstance server = firstInstanceFromResource(\"/describe_instances_running.xml\");\n\n      assertEquals(\n            parser.apply(server).toString(),\n            new NodeMetadataBuilder().status(Status.RUNNING).backendStatus(\"running\").hostname(\"ip-10-243-42-70\")\n                  .publicAddresses(ImmutableSet.<String> of()).privateAddresses(ImmutableSet.of(\"10.243.42.70\"))\n                  .publicAddresses(ImmutableSet.of(\"174.129.81.68\")).credentials(creds)\n                  .imageId(\"us-east-1/ami-82e4b5c7\").id(\"us-east-1/i-0799056f\").providerId(\"i-0799056f\").build().toString());\n   }\n\n   @Test\n   public void testApplyWhereTagDoesntMatchAndImageHardwareAndLocationNotFound() throws UnknownHostException {\n      RunningInstanceToNodeMetadata parser = createNodeParser(ImmutableSet.<Hardware> of(), ImmutableSet\n               .<Location> of(), ImmutableSet.<Image> of(), ImmutableMap.<String, Credentials> of());\n\n      RunningInstance server = firstInstanceFromResource(\"/describe_instances_running.xml\");\n\n      assertEquals(parser.apply(server).toString(),\n            new NodeMetadataBuilder().hostname(\"ip-10-243-42-70\").status(Status.RUNNING).backendStatus(\"running\")\n                  .publicAddresses(ImmutableSet.<String> of()).privateAddresses(ImmutableSet.of(\"10.243.42.70\"))\n                  .publicAddresses(ImmutableSet.of(\"174.129.81.68\")).imageId(\"us-east-1/ami-82e4b5c7\")\n                  .id(\"us-east-1/i-0799056f\").providerId(\"i-0799056f\").build().toString());\n   }\n\n   @Test\n   public void testApplyWhereTagDoesntMatchAndLocationFoundAndImageAndHardwareNotFound() throws UnknownHostException {\n      RunningInstanceToNodeMetadata parser = createNodeParser(ImmutableSet.<Hardware> of(), ImmutableSet.of(provider),\n               ImmutableSet.<Image> of(), ImmutableMap.<String, Credentials> of());\n\n      RunningInstance server = firstInstanceFromResource(\"/describe_instances_running.xml\");\n      NodeMetadata expected = new NodeMetadataBuilder().hostname(\"ip-10-243-42-70\").status(Status.RUNNING).backendStatus(\"running\")\n               .privateAddresses(ImmutableSet.of(\"10.243.42.70\")).publicAddresses(ImmutableSet.of(\"174.129.81.68\"))\n               .imageId(\"us-east-1/ami-82e4b5c7\").id(\"us-east-1/i-0799056f\").providerId(\"i-0799056f\")\n               .location(provider).build();\n\n      assertEquals(parser.apply(server).toString(), expected.toString());\n   }\n\n   @Test\n   public void testApplyWhereTagDoesntMatchAndImageAndLocationFoundAndHardwareNotFound() throws UnknownHostException {\n      RunningInstanceToNodeMetadata parser = createNodeParser(ImmutableSet.<Hardware> of(), ImmutableSet.of(provider),\n               EC2ImageParserTest.convertImages(\"/amzn_images.xml\"), ImmutableMap.<String, Credentials> of());\n\n      RunningInstance server = firstInstanceFromResource(\"/describe_instances_running.xml\");\n\n      assertEquals(\n            parser.apply(server).toString(),\n            new NodeMetadataBuilder()\n                  .status(Status.RUNNING).backendStatus(\"running\")\n                  .hostname(\"ip-10-243-42-70\")\n                  .privateAddresses(ImmutableSet.of(\"10.243.42.70\"))\n                  .publicAddresses(ImmutableSet.of(\"174.129.81.68\"))\n                  .imageId(\"us-east-1/ami-82e4b5c7\")\n                  .operatingSystem(\n                        new OperatingSystem.Builder().family(OsFamily.UNRECOGNIZED).version(\"\").arch(\"paravirtual\")\n                              .description(\"137112412989/amzn-ami-0.9.7-beta.i386-ebs\").is64Bit(false).build())\n                  .id(\"us-east-1/i-0799056f\").providerId(\"i-0799056f\").location(provider).build().toString());\n   }\n\n   @Test\n   public void testApplyWhereTagDoesntMatchAndImageHardwareAndLocationFound() throws UnknownHostException {\n      RunningInstanceToNodeMetadata parser = createNodeParser(ImmutableSet.of(m1_small().build()), ImmutableSet\n               .of(provider), EC2ImageParserTest.convertImages(\"/amzn_images.xml\"), ImmutableMap\n               .<String, Credentials> of());\n\n      RunningInstance server = firstInstanceFromResource(\"/describe_instances_running.xml\");\n\n      assertEquals(\n            parser.apply(server).toString(),\n            new NodeMetadataBuilder()\n                  .hostname(\"ip-10-243-42-70\")\n                  .status(Status.RUNNING).backendStatus(\"running\")\n                  .privateAddresses(ImmutableSet.of(\"10.243.42.70\"))\n                  .publicAddresses(ImmutableSet.of(\"174.129.81.68\"))\n                  .imageId(\"us-east-1/ami-82e4b5c7\")\n                  .hardware(m1_small().build())\n                  .operatingSystem(\n                        new OperatingSystem.Builder().family(OsFamily.UNRECOGNIZED).version(\"\").arch(\"paravirtual\")\n                              .description(\"137112412989/amzn-ami-0.9.7-beta.i386-ebs\").is64Bit(false).build())\n                  .id(\"us-east-1/i-0799056f\").providerId(\"i-0799056f\").location(provider).build().toString());\n   }\n\n   @Test\n   public void testHandleMissingAMIs() {\n\n      // Handle the case when the installed AMI no longer can be found in AWS.\n\n      // Create a null-returning function to simulate that the AMI can't be found.\n      CacheLoader<RegionAndName, Image> nullReturningFunction = new CacheLoader<RegionAndName, Image>() {\n\n         @Override\n         public Image load(@Nullable RegionAndName from) {\n            return null;\n         }\n      };\n      LoadingCache<RegionAndName, Image> instanceToImage = CacheBuilder.newBuilder().build(nullReturningFunction);\n\n      RunningInstanceToNodeMetadata parser = createNodeParser(ImmutableSet.of(m1_small().build()), ImmutableSet\n               .of(provider), ImmutableMap.<String, Credentials> of(),\n               EC2ComputeServiceDependenciesModule.toPortableNodeStatus, instanceToImage);\n\n      RunningInstance server = firstInstanceFromResource(\"/describe_instances_running.xml\");\n\n      assertEquals(\n            parser.apply(server).toString(),\n            new NodeMetadataBuilder().hostname(\"ip-10-243-42-70\").status(Status.RUNNING).backendStatus(\"running\")\n                  .privateAddresses(ImmutableSet.of(\"10.243.42.70\")).publicAddresses(ImmutableSet.of(\"174.129.81.68\"))\n                  .imageId(\"us-east-1/ami-82e4b5c7\").id(\"us-east-1/i-0799056f\").providerId(\"i-0799056f\")\n                  .hardware(m1_small().build()).location(provider).build().toString());\n   }\n\n   @Test\n   public void testGroupNameIsSetWhenCustomKeyNameIsSetAndSecurityGroupIsGenerated() {\n      checkGroupName(RunningInstance.builder().instanceId(\"id\").imageId(\"image\").instanceType(\"m1.small\")\n              .instanceState(InstanceState.RUNNING).rawState(\"running\").region(\"us-east-1\").keyName(\"custom-key\")\n              .groupName(\"jclouds#groupname\").build());\n   }\n\n   @Test\n   public void testGroupNameIsSetWhenCustomSecurityGroupIsSetAndKeyNameIsGenerated() {\n      checkGroupName(RunningInstance.builder().instanceId(\"id\").imageId(\"image\").instanceType(\"m1.small\")\n              .instanceState(InstanceState.RUNNING).rawState(\"running\").region(\"us-east-1\").groupName(\"custom-sec\")\n              .keyName(\"jclouds#groupname#23\").build());\n   }\n\n   protected RunningInstance firstInstanceFromResource(String resource) {\n      return Iterables.get(Iterables.get(DescribeInstancesResponseHandlerTest.parseRunningInstances(resource), 0), 0);\n   }\n\n   protected RunningInstanceToNodeMetadata createNodeParser(final ImmutableSet<Hardware> hardware,\n            final ImmutableSet<Location> locations, final Set<org.jclouds.compute.domain.Image> images,\n            Map<String, Credentials> credentialStore) {\n      Map<InstanceState, Status> instanceToNodeStatus = EC2ComputeServiceDependenciesModule.toPortableNodeStatus;\n\n      CacheLoader<RegionAndName, Image> getRealImage = new CacheLoader<RegionAndName, Image>() {\n\n         @Override\n         public Image load(@Nullable RegionAndName from) {\n            return ImagesToRegionAndIdMap.imagesToMap(images).get(from);\n         }\n      };\n      LoadingCache<RegionAndName, Image> instanceToImage = CacheBuilder.newBuilder().build(getRealImage);\n      return createNodeParser(hardware, locations, credentialStore, instanceToNodeStatus, instanceToImage);\n   }\n\n   private void checkGroupName(RunningInstance instance) {\n      assertEquals(\"groupname\", createNodeParser(ImmutableSet.<Hardware> of(), ImmutableSet\n            .<Location> of(), ImmutableSet.<Image> of(), ImmutableMap.<String, Credentials> of())\n            .apply(instance).getGroup());\n   }\n\n   private RunningInstanceToNodeMetadata createNodeParser(final ImmutableSet<Hardware> hardware,\n            final ImmutableSet<Location> locations, Map<String, Credentials> credentialStore,\n            Map<InstanceState, Status> instanceToNodeStatus, LoadingCache<RegionAndName, Image> instanceToImage) {\n      Supplier<Set<? extends Location>> locationSupplier = new Supplier<Set<? extends Location>>() {\n\n         @Override\n         public Set<? extends Location> get() {\n            return locations;\n         }\n\n      };\n      Supplier<Set<? extends Hardware>> hardwareSupplier = new Supplier<Set<? extends Hardware>>() {\n\n         @Override\n         public Set<? extends Hardware> get() {\n            return hardware;\n         }\n\n      };\n\n      GroupNamingConvention.Factory namingConvention = Guice.createInjector(new AbstractModule() {\n\n         @Override\n         protected void configure() {\n            Names.bindProperties(binder(), new EC2ApiMetadata().getDefaultProperties());\n         }\n\n      }).getInstance(GroupNamingConvention.Factory.class);\n\n      RunningInstanceToNodeMetadata parser = new RunningInstanceToNodeMetadata(instanceToNodeStatus, credentialStore,\n            Suppliers.<LoadingCache<RegionAndName, ? extends Image>> ofInstance(instanceToImage), locationSupplier,\n            hardwareSupplier, namingConvention);\n      return parser;\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/compute/functions/WindowsLoginCredentialsFromEncryptedDataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.functions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.ec2.compute.domain.PasswordDataAndPrivateKey;\nimport org.jclouds.ec2.domain.PasswordData;\nimport org.jclouds.encryption.internal.JCECrypto;\nimport org.testng.annotations.Test;\n\npublic class WindowsLoginCredentialsFromEncryptedDataTest {\n\n   private static final String PRIVATE_KEY = \"-----BEGIN RSA PRIVATE KEY-----\\n\" +\n      \"MIIEowIBAAKCAQEAmN6GOSMnyGNWN19ETBh11tJB5OGs3Dps8kPWqAhF9RyL/mKwkW26vH+h/5Z5\\n\" +\n      \"cA5T80pK72kNnXObFaMHNoX3lavrc6yXF+8F3f1tlFX2Z+iB1pYXz1oBPqT6oOmc2XzcsJuJRakd\\n\" +\n      \"zwRwHDaqljpaW7+TZlxhMa1DmUkD/HHMxDCK8jbUIZDc6BZSrnj2uPwHwW737NRE4aC3fcu4LMwf\\n\" +\n      \"b2VotbNGNiAnNmrb/vtIIGkFE8NYEMpiz0WYTWX4eVKpJImv1PR6G1fMLSvudJs0ARObuLDvuonn\\n\" +\n      \"SCFFdkibrwMKYbHVGGh6FoY1Vy0sqI55dgQU1kSNouiDgOGxgx+TIwIDAQABAoIBAHCS/nk5QGS7\\n\" +\n      \"cpRYXa1EHhNSxx/MaUXM6MoH1x3q6cm1egqdlrWh/vAtdZkIsOkqQ/xX65Me493dcomegwNN6KOZ\\n\" +\n      \"9Uw7/xCq/sEZjga8vzaJ7IOgCGy0NVJyn/a70rv+zW5pO8/G2KLI+95rC3iSBFSoYd3xjcnNdIh/\\n\" +\n      \"UqYnD8oxYpKmf7418pMPsBrkglkFlbVBPiDXdpoSziqSN6uWQG4Yh0WR87aElhM9JJW50Hh6h7g5\\n\" +\n      \"OvgCBzS8G+KXCjqimk108+/ed5Nl6VhPAf79yCVZUueKBhaf2r0Kkyxg7M/Y+LJwcoUusIP7Cv7G\\n\" +\n      \"xyzG2vi21prWRCm2sVCUDyQy5qECgYEA92jGVAaB3OGEUIXn7eVE3U3FQH37XcJMGsHqBIzDG13p\\n\" +\n      \"C97HdN21rwRkz+G2eAsIxA+p9BsO7dSmtKC60kl6iMRgltS3W7xoC37N9BtjhpciHcLg8c70oyDx\\n\" +\n      \"qHiLKuDi90mZ1FPmWupO4FJnGEB3evHUKZSpTrVVMzt+tyEn/psCgYEAni1hrYoMkQgN3sEC3CKB\\n\" +\n      \"0jQkrOMvY219B8Tdf9LXSuP6z9POagDBDhkeT3xn8rAOmOfVGHYdO0CvPqmAkmXhf+g+OREdecQa\\n\" +\n      \"uY0FmvcTt+Dx0c6pRZmm5AhvUVXFXqONsSg79iviXbUy5Hik0k5HTs5E6B4obrh5W+xfMTUXghkC\\n\" +\n      \"gYBn92uAW8uumkYT4HF6EuJBbTD6zPYYjFGW3O4OQ2ip02jfSBrhDVoP1fTXNq6K+3gPi9WLcuNv\\n\" +\n      \"JfF37iMTwzTuzDcaqwDyV9YRHpRFhEzqfhAkGYSVmLZM5scmWKGCv0YhTJiMFUWz5sqGkZopIs4S\\n\" +\n      \"qBTT9FjBbooDIXk6U4CPCQKBgFdVBxEhnz6UC9RpDIMuKi88yuMJrChhUx7u+ryQVH3s0ZXdg6HT\\n\" +\n      \"OMPn6mxIa7v6qJSTq3wN+qW0WQ1n2Kz7wz0zpOctI/EO7RJ1YhrlP+XONLV6PMtIwnQ0lAF8MbTG\\n\" +\n      \"6HxfknugTyMd4DN0yMu0nHpOOI1P2VMIVzkBkK1CevBBAoGBALROGR7a+eijHdp0/A0chfUoBmud\\n\" +\n      \"/TsUt+0g/vf1p69rMt6DqEGMgMtp2jIRnwvLElS7gVqnCTEclxNU/0rCXR+V7ImJm8J4f0ff8m0Y\\n\" +\n      \"Fir9nfCYStszo25NvLFfynS9d/aoBuvqGJaiQyNXiyBJ4MaxxFYagzAWTnDX+kzTlkZ2\\n\" +\n      \"-----END RSA PRIVATE KEY-----\";\n   private static final String ENCRYPTED_PASSWORD = \"gO1oMoIjjIifv2iqcfIKiQD7ziOTVXsuaBJFEQrZdb8uJH/LsAiJXZeGKEeXlHl/oMoR3HEIoYuHxl+p5iHdrpP889RmxWBDGOWC5iTUzK6CRa5mFmF1I5Lpt7v2YeVoQWihSM8B19BEdBdY1svQp9nyhPB4AqLDrY28x/OrmRh/qYq953i6Y4Z8c76OHqqGcUYM4ePysRlcizSgQjdkEDmKC10Ak3OFRRx3/LqYsFIMiOHeg47APg+UANNTyRiTIia5FDhSeHJzaeYCBRQ7UYH0z2rg4cX3YjOz/MoznjHiaaN4MO+5N3v84VawnqwKOvlwPyI2bmz0+9Tr6DKzqA==\";\n\n   protected final DateService dateService = new SimpleDateFormatDateService();\n\n   @Test\n   public void testApply() throws Exception {\n      WindowsLoginCredentialsFromEncryptedData f = new WindowsLoginCredentialsFromEncryptedData(new JCECrypto());\n\n      PasswordData passwordData = PasswordData.builder()\n                                              .instanceId(\"i-2574e22a\")\n                                              .timestamp(dateService.iso8601DateParse(\"2012-07-30T07:27:23.000+0000\"))\n                                              .passwordData(ENCRYPTED_PASSWORD).build();\n\n      LoginCredentials credentials = f.apply(new PasswordDataAndPrivateKey(passwordData, PRIVATE_KEY));\n\n      assertEquals(credentials.getUser(), \"Administrator\");\n      assertEquals(credentials.getOptionalPassword().get(), \"u4.y9mb;nR.\");\n      assertFalse(credentials.getOptionalPrivateKey().isPresent());\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/compute/internal/BaseEC2ComputeServiceContextExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.internal;\n\nimport java.util.Properties;\n\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.ec2.internal.BaseEC2ApiExpectTest;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\n\nimport com.google.common.base.Function;\nimport com.google.inject.Module;\n\npublic abstract class BaseEC2ComputeServiceContextExpectTest<T> extends BaseEC2ApiExpectTest<T> implements\n         Function<ComputeServiceContext, T> {\n\n   @Override\n   public T createClient(Function<HttpRequest, HttpResponse> fn, Module module, Properties props) {\n      return apply(createComputeServiceContext(fn, module, props));\n   }\n\n   private ComputeServiceContext createComputeServiceContext(Function<HttpRequest, HttpResponse> fn, Module module,\n            Properties props) {\n      return createInjector(fn, module, props).getInstance(ComputeServiceContext.class);\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/compute/internal/BaseEC2ComputeServiceExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.internal;\n\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_REGIONS;\n\nimport jakarta.ws.rs.core.MediaType;\nimport java.util.Properties;\n\nimport org.jclouds.compute.ComputeService;\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.BeforeClass;\n\npublic abstract class BaseEC2ComputeServiceExpectTest extends BaseEC2ComputeServiceContextExpectTest<ComputeService> {\n   protected String region;\n\n   @Override\n   protected Properties setupProperties() {\n      Properties properties = super.setupProperties();\n      properties.setProperty(PROPERTY_REGIONS, region);\n      properties.setProperty(provider + \".template\", \"osDescriptionMatches=.*fedora.*\");\n      return properties;\n   }\n\n   protected HttpRequest describeAvailabilityZonesRequest;\n   protected HttpResponse describeAvailabilityZonesResponse;\n   protected HttpRequest describeImagesRequest;\n   protected HttpResponse describeImagesResponse;\n   protected HttpRequest createKeyPairRequest;\n   protected HttpResponse createKeyPairResponse;\n   protected HttpRequest createSecurityGroupRequest;\n   protected HttpResponse createSecurityGroupResponse;\n   protected HttpRequest describeSecurityGroupFilteredRequest;\n   protected HttpResponse describeSecurityGroupFilteredResponse;\n   protected HttpRequest describeSecurityGroupRequest;\n   protected HttpResponse describeSecurityGroupResponse;\n   protected HttpRequest authorizeSecurityGroupIngressRequest22;\n   protected HttpResponse authorizeSecurityGroupIngressResponse;\n   protected HttpRequest authorizeSecurityGroupIngressRequestGroup;\n   protected HttpRequest runInstancesRequest;\n   protected HttpResponse runInstancesResponse;\n   protected HttpRequest runThreeInstancesRequest;\n   protected HttpRequest runThreeToFourInstancesRequest;\n   protected HttpResponse runThreeInstancesResponse;\n   protected HttpRequest describeInstanceRequest;\n   protected HttpResponse describeInstanceResponse;\n   protected HttpRequest describeInstanceMultiIdsRequest;\n   protected HttpResponse describeInstanceMultiIdsResponse;\n   protected HttpRequest describeInstanceThreeIdsRequest;\n   protected HttpResponse describeInstanceThreeIdsResponse;\n   protected HttpRequest describeImageRequest;\n   protected HttpRequest createTagsRequest;\n   protected HttpResponse createTagsResponse;\n\n   public BaseEC2ComputeServiceExpectTest() {\n      region = \"us-east-1\";\n   }\n   \n   @BeforeClass\n   @Override\n   protected void setupDefaultRequests() {\n      super.setupDefaultRequests();\n      describeAvailabilityZonesRequest = \n               formSigner.filter(HttpRequest.builder()\n                          .method(\"POST\")\n                          .endpoint(\"https://ec2.\" + region + \".amazonaws.com/\")\n                          .addHeader(\"Host\", \"ec2.\" + region + \".amazonaws.com\")\n                          .addFormParam(\"Action\", \"DescribeAvailabilityZones\").build());\n      \n      describeAvailabilityZonesResponse = \n               HttpResponse.builder().statusCode(200)\n                           .payload(payloadFromResourceWithContentType(\n                                 \"/availabilityZones-\" + region + \".xml\", MediaType.APPLICATION_XML)).build();\n      describeImagesRequest = \n               formSigner.filter(HttpRequest.builder()\n                          .method(\"POST\")\n                          .endpoint(\"https://ec2.\" + region + \".amazonaws.com/\")\n                          .addHeader(\"Host\", \"ec2.\" + region + \".amazonaws.com\")\n                          .addFormParam(\"Action\", \"DescribeImages\").build());\n      \n      describeImagesResponse = \n               HttpResponse.builder().statusCode(200)\n                           .payload(payloadFromResourceWithContentType(\n                                 \"/describe_images.xml\", MediaType.APPLICATION_XML)).build();\n      \n      createKeyPairRequest = \n               formSigner.filter(HttpRequest.builder()\n                          .method(\"POST\")\n                          .endpoint(\"https://ec2.\" + region + \".amazonaws.com/\")\n                          .addHeader(\"Host\", \"ec2.\" + region + \".amazonaws.com\")\n                          .addFormParam(\"Action\", \"CreateKeyPair\")\n                          .addFormParam(\"KeyName\", \"jclouds#test#0\").build());\n\n      createKeyPairResponse = \n               HttpResponse.builder().statusCode(200)\n                           .payload(payloadFromResourceWithContentType(\n                                 \"/create_keypair.xml\", MediaType.APPLICATION_XML)).build();\n      \n      createSecurityGroupRequest = \n               formSigner.filter(HttpRequest.builder()\n                          .method(\"POST\")\n                          .endpoint(\"https://ec2.\" + region + \".amazonaws.com/\")\n                          .addHeader(\"Host\", \"ec2.\" + region + \".amazonaws.com\")\n                          .addFormParam(\"Action\", \"CreateSecurityGroup\")\n                          .addFormParam(\"GroupDescription\", \"jclouds#test\")\n                          .addFormParam(\"GroupName\", \"jclouds#test\").build());\n\n      createSecurityGroupResponse = \n               HttpResponse.builder().statusCode(200)\n                           .payload(payloadFromResourceWithContentType(\n                                 \"/created_securitygroup.xml\", MediaType.APPLICATION_XML)).build();\n\n      describeSecurityGroupFilteredRequest = \n            formSigner.filter(HttpRequest.builder()\n                       .method(\"POST\")\n                       .endpoint(\"https://ec2.\" + region + \".amazonaws.com/\")\n                       .addHeader(\"Host\", \"ec2.\" + region + \".amazonaws.com\")\n                       .addFormParam(\"Action\", \"DescribeSecurityGroups\")\n                       .addFormParam(\"Filter.1.Name\", \"group-name\")\n                       .addFormParam(\"Filter.1.Value.1\", \"jclouds#test\").build());\n   \n      describeSecurityGroupFilteredResponse = \n            HttpResponse.builder().statusCode(200)\n                        .payload(payloadFromResourceWithContentType(\n                              \"/new_securitygroup.xml\", MediaType.APPLICATION_XML)).build();\n   \n      describeSecurityGroupRequest = \n               formSigner.filter(HttpRequest.builder()\n                          .method(\"POST\")\n                          .endpoint(\"https://ec2.\" + region + \".amazonaws.com/\")\n                          .addHeader(\"Host\", \"ec2.\" + region + \".amazonaws.com\")\n                          .addFormParam(\"Action\", \"DescribeSecurityGroups\")\n                          .addFormParam(\"GroupName.1\", \"jclouds#test\").build());\n      \n      describeSecurityGroupResponse = \n               HttpResponse.builder().statusCode(200)\n                           .payload(payloadFromResourceWithContentType(\n                                 \"/new_securitygroup.xml\", MediaType.APPLICATION_XML)).build();\n      \n      authorizeSecurityGroupIngressRequest22 = \n               formSigner.filter(HttpRequest.builder()\n                          .method(\"POST\")\n                          .endpoint(\"https://ec2.\" + region + \".amazonaws.com/\")\n                          .addHeader(\"Host\", \"ec2.\" + region + \".amazonaws.com\")\n                          .addFormParam(\"Action\", \"AuthorizeSecurityGroupIngress\")\n                          .addFormParam(\"CidrIp\", \"0.0.0.0/0\")\n                          .addFormParam(\"FromPort\", \"22\")\n                          .addFormParam(\"ToPort\", \"22\")\n                          .addFormParam(\"GroupName\", \"jclouds#test\")\n                          .addFormParam(\"IpProtocol\", \"tcp\").build());\n      \n      authorizeSecurityGroupIngressRequestGroup = \n               formSigner.filter(HttpRequest.builder()\n                          .method(\"POST\")\n                          .endpoint(\"https://ec2.\" + region + \".amazonaws.com/\")\n                          .addHeader(\"Host\", \"ec2.\" + region + \".amazonaws.com\")\n                          .addFormParam(\"Action\", \"AuthorizeSecurityGroupIngress\")\n                          .addFormParam(\"SourceSecurityGroupName\", \"jclouds#test\")\n                          .addFormParam(\"SourceSecurityGroupOwnerId\", \"993194456877\")\n                          .addFormParam(\"GroupName\", \"jclouds#test\").build());\n      \n      authorizeSecurityGroupIngressResponse = \n               HttpResponse.builder().statusCode(200)\n                           .payload(payloadFromResourceWithContentType(\n                                 \"/authorize_securitygroup_ingress_response.xml\", MediaType.APPLICATION_XML)).build();\n      \n      runInstancesRequest = \n               formSigner.filter(HttpRequest.builder()\n                          .method(\"POST\")\n                          .endpoint(\"https://ec2.\" + region + \".amazonaws.com/\")\n                          .addHeader(\"Host\", \"ec2.\" + region + \".amazonaws.com\")\n                          .addFormParam(\"Action\", \"RunInstances\")\n                          .addFormParam(\"ImageId\", \"ami-be3adfd7\")\n                          .addFormParam(\"InstanceType\", \"m1.small\")\n                          .addFormParam(\"KeyName\", \"jclouds#test#0\")\n                          .addFormParam(\"MaxCount\", \"1\")\n                          .addFormParam(\"MinCount\", \"1\")\n                          .addFormParam(\"SecurityGroup.1\", \"jclouds#test\").build());\n      \n      runInstancesResponse = \n               HttpResponse.builder().statusCode(200)\n                           .payload(payloadFromResourceWithContentType(\n                                 \"/new_instance.xml\", MediaType.APPLICATION_XML)).build();\n\n      runThreeInstancesRequest =\n              formSigner.filter(HttpRequest.builder()\n                      .method(\"POST\")\n                      .endpoint(\"https://ec2.\" + region + \".amazonaws.com/\")\n                      .addHeader(\"Host\", \"ec2.\" + region + \".amazonaws.com\")\n                      .addFormParam(\"Action\", \"RunInstances\")\n                      .addFormParam(\"ImageId\", \"ami-be3adfd7\")\n                      .addFormParam(\"InstanceType\", \"m1.small\")\n                      .addFormParam(\"KeyName\", \"jclouds#test#0\")\n                      .addFormParam(\"MaxCount\", \"3\")\n                      .addFormParam(\"MinCount\", \"3\")\n                      .addFormParam(\"SecurityGroup.1\", \"jclouds#test\").build());\n\n      runThreeToFourInstancesRequest =\n              formSigner.filter(HttpRequest.builder()\n                      .method(\"POST\")\n                      .endpoint(\"https://ec2.\" + region + \".amazonaws.com/\")\n                      .addHeader(\"Host\", \"ec2.\" + region + \".amazonaws.com\")\n                      .addFormParam(\"Action\", \"RunInstances\")\n                      .addFormParam(\"ImageId\", \"ami-be3adfd7\")\n                      .addFormParam(\"InstanceType\", \"m1.small\")\n                      .addFormParam(\"KeyName\", \"jclouds#test#0\")\n                      .addFormParam(\"MaxCount\", \"4\")\n                      .addFormParam(\"MinCount\", \"3\")\n                      .addFormParam(\"SecurityGroup.1\", \"jclouds#test\").build());\n\n      runThreeInstancesResponse =\n              HttpResponse.builder().statusCode(200)\n                      .payload(payloadFromResourceWithContentType(\n                              \"/run_instances_three.xml\", MediaType.APPLICATION_XML)).build();\n\n      describeInstanceRequest =\n               formSigner.filter(HttpRequest.builder()\n                       .method(\"POST\")\n                       .endpoint(\"https://ec2.\" + region + \".amazonaws.com/\")\n                       .addHeader(\"Host\", \"ec2.\" + region + \".amazonaws.com\")\n                       .addFormParam(\"Action\", \"DescribeInstances\")\n                       .addFormParam(\"InstanceId.1\", \"i-2baa5550\").build());\n      \n      describeInstanceResponse = \n               HttpResponse.builder().statusCode(200)\n                           .payload(payloadFromResourceWithContentType(\n                                 \"/describe_instances_running-1.xml\", MediaType.APPLICATION_XML)).build();\n\n      describeInstanceMultiIdsRequest = \n               formSigner.filter(HttpRequest.builder()\n                          .method(\"POST\")\n                          .endpoint(\"https://ec2.\" + region + \".amazonaws.com/\")\n                          .addHeader(\"Host\", \"ec2.\" + region + \".amazonaws.com\")\n                          .addFormParam(\"Action\", \"DescribeInstances\")\n                          .addFormParam(\"InstanceId.1\", \"i-2baa5550\")\n                          .addFormParam(\"InstanceId.2\", \"i-abcd1234\").build());\n      \n      describeInstanceMultiIdsResponse = \n               HttpResponse.builder().statusCode(200)\n                           .payload(payloadFromResourceWithContentType(\n                                 \"/describe_instances_multiple.xml\", MediaType.APPLICATION_XML)).build();\n\n      describeInstanceThreeIdsRequest =\n              formSigner.filter(HttpRequest.builder()\n                      .method(\"POST\")\n                      .endpoint(\"https://ec2.\" + region + \".amazonaws.com/\")\n                      .addHeader(\"Host\", \"ec2.\" + region + \".amazonaws.com\")\n                      .addFormParam(\"Action\", \"DescribeInstances\")\n                      .addFormParam(\"InstanceId.1\", \"i-2ba64342\")\n                      .addFormParam(\"InstanceId.2\", \"i-2bc64242\")\n                      .addFormParam(\"InstanceId.3\", \"i-2be64332\").build());\n\n      describeInstanceThreeIdsResponse =\n              HttpResponse.builder().statusCode(200)\n                      .payload(payloadFromResourceWithContentType(\n                              \"/describe_instances_multiple.xml\", MediaType.APPLICATION_XML)).build();\n\n      //TODO: duplicate.. shouldn't need this\n      describeImageRequest = \n               formSigner.filter(HttpRequest.builder()\n                          .method(\"POST\")\n                          .endpoint(\"https://ec2.\" + region + \".amazonaws.com/\")\n                          .addHeader(\"Host\", \"ec2.\" + region + \".amazonaws.com\")\n                          .addFormParam(\"ImageId.1\", \"ami-aecd60c7\")\n                          .addFormParam(\"Action\", \"DescribeImages\").build());\n\n      createTagsRequest =\n              formSigner.filter(HttpRequest.builder()\n                      .method(\"POST\")\n                      .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                      .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                      .payload(\n                              payloadFromStringWithContentType(\n                                      \"Action=CreateTags\" +\n                                              \"&ResourceId.1=i-2baa5550\" +\n                                              \"&Signature=Trp5e5%2BMqeBeBZbLYa9s9gxahQ9nkx6ETfsGl82IV8Y%3D\" +\n                                              \"&SignatureMethod=HmacSHA256\" +\n                                              \"&SignatureVersion=2\" +\n                                              \"&Tag.1.Key=Name\" +\n                                              \"&Tag.1.Value=test-2baa5550\" +\n                                              \"&Timestamp=2012-04-16T15%3A54%3A08.897Z\" +\n                                              \"&Version=2010-08-31\" +\n                                              \"&AWSAccessKeyId=identity\",\n                                      \"application/x-www-form-urlencoded\"))\n                      .build());\n\n      createTagsResponse = HttpResponse.builder().statusCode(200).build();\n\n   }\n\n   @Override\n   public ComputeService apply(ComputeServiceContext input) {\n      return input.getComputeService();\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/compute/internal/EC2TemplateBuilderImplTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.internal;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.c1_medium;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.r3_large;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.fail;\n\nimport java.util.NoSuchElementException;\nimport java.util.Set;\n\nimport jakarta.inject.Provider;\n\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.TemplateBuilder;\nimport org.jclouds.compute.domain.internal.TemplateBuilderImpl;\nimport org.jclouds.compute.domain.internal.TemplateBuilderImplTest;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.compute.strategy.GetImageStrategy;\nimport org.jclouds.compute.suppliers.ImageCacheSupplier;\nimport org.jclouds.domain.Location;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.compute.functions.ImagesToRegionAndIdMap;\nimport org.jclouds.ec2.compute.options.EC2TemplateOptions;\nimport org.jclouds.rest.AuthorizationException;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Functions;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Sets;\nimport com.google.common.util.concurrent.Atomics;\nimport com.google.inject.util.Providers;\n\n@Test(groups = \"unit\", singleThreaded = true)\npublic class EC2TemplateBuilderImplTest extends TemplateBuilderImplTest {\n\n   @Override\n   protected TemplateOptions provideTemplateOptions() {\n      return new EC2TemplateOptions();\n   }\n\n   @Override\n   protected EC2TemplateBuilderImpl createTemplateBuilder(final Image knownImage,\n         @Memoized Supplier<Set<? extends Location>> locations, @Memoized final Supplier<Set<? extends Image>> images,\n         @Memoized Supplier<Set<? extends Hardware>> sizes, Location defaultLocation,\n         Provider<TemplateOptions> optionsProvider, Provider<TemplateBuilder> templateBuilderProvider, GetImageStrategy getImageStrategy) {\n\n      LoadingCache<RegionAndName, ? extends Image> imageMap;\n      if (knownImage != null) {\n         final RegionAndName knownRegionAndName = new RegionAndName(knownImage.getLocation().getId(), knownImage.getProviderId());\n\n         imageMap = CacheBuilder.newBuilder().build(new CacheLoader<RegionAndName, Image>() {\n            @Override\n            public Image load(RegionAndName from) {\n               return from.equals(knownRegionAndName) ? knownImage : null;\n            }\n\n         });\n         \n      } else {\n         imageMap = CacheBuilder.newBuilder().build(CacheLoader.from(Functions.forMap(\n                  ImagesToRegionAndIdMap.imagesToMap(images.get()))));\n      }\n\n      return new EC2TemplateBuilderImpl(locations, new ImageCacheSupplier(images, 60,\n            Atomics.<AuthorizationException> newReference(), Providers.of(getImageStrategy)), sizes,\n            Suppliers.ofInstance(defaultLocation), optionsProvider, templateBuilderProvider,\n            Suppliers.<LoadingCache<RegionAndName, ? extends Image>> ofInstance(imageMap));\n   }\n\n   @Override\n   protected String getProviderFormatId(String uniqueLabel) {\n       return \"us-east-1/\" + uniqueLabel;\n   }\n\n   @Override\n   @Test\n   public void testHardwareWithImageIdPredicateOnlyAcceptsImageWhenLocationNull() {\n      // not possible to have null region in ec2\n   }\n   \n   @SuppressWarnings(\"unchecked\")\n   @Test\n   public void testParseOnDemand() {\n\n      Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n            .<Location> of(region));\n      Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(Sets\n            .<Image> newLinkedHashSet());\n      Supplier<Set<? extends Hardware>> sizes = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet\n            .<Hardware> of(c1_medium().build(), r3_large().build()));\n\n      Provider<TemplateOptions> optionsProvider = createMock(Provider.class);\n      Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);\n      TemplateOptions defaultOptions = createMock(TemplateOptions.class);\n      Image knownImage = createMock(Image.class);\n      OperatingSystem os = createMock(OperatingSystem.class);\n      GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class);\n\n      expect(optionsProvider.get()).andReturn(defaultOptions);\n\n      expect(knownImage.getId()).andReturn(\"us-east-1/ami\").atLeastOnce();\n      expect(knownImage.getLocation()).andReturn(region).atLeastOnce();\n      expect(knownImage.getName()).andReturn(null).atLeastOnce();\n      expect(knownImage.getDescription()).andReturn(null).atLeastOnce();\n      expect(knownImage.getVersion()).andReturn(null).atLeastOnce();\n      expect(knownImage.getProviderId()).andReturn(\"ami\").atLeastOnce();\n\n      expect(knownImage.getOperatingSystem()).andReturn(os).atLeastOnce();\n\n      expect(os.getName()).andReturn(null).atLeastOnce();\n      expect(os.getVersion()).andReturn(null).atLeastOnce();\n      expect(os.getFamily()).andReturn(null).atLeastOnce();\n      expect(os.getDescription()).andReturn(null).atLeastOnce();\n      expect(os.getArch()).andReturn(\"hvm\").atLeastOnce();\n      expect(os.is64Bit()).andReturn(false).atLeastOnce();\n\n      replay(knownImage, os, defaultOptions, optionsProvider, templateBuilderProvider, getImageStrategy);\n\n      TemplateBuilderImpl template = createTemplateBuilder(knownImage, locations, images, sizes, region,\n            optionsProvider, templateBuilderProvider, getImageStrategy);\n\n      assertEquals(template.imageId(\"us-east-1/ami\").build().getImage(), knownImage);\n      assertEquals(template.imageId(\"us-east-1/ami\").build().getHardware(), r3_large().build());\n\n      verify(knownImage, os, defaultOptions, optionsProvider, templateBuilderProvider, getImageStrategy);\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Test\n   public void testParseOnDemandUsesDeprecatedHardwareIfNeeded() {\n\n      Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n            .<Location> of(region));\n      Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(Sets\n            .<Image> newLinkedHashSet());\n      Supplier<Set<? extends Hardware>> sizes = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet\n            .<Hardware> of(c1_medium().build(), r3_large().build()));\n\n      Provider<TemplateOptions> optionsProvider = createMock(Provider.class);\n      Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);\n      TemplateOptions defaultOptions = createMock(TemplateOptions.class);\n      Image knownImage = createMock(Image.class);\n      OperatingSystem os = createMock(OperatingSystem.class);\n      GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class);\n\n      expect(optionsProvider.get()).andReturn(defaultOptions);\n\n      expect(knownImage.getId()).andReturn(\"us-east-1/ami\").atLeastOnce();\n      expect(knownImage.getLocation()).andReturn(region).atLeastOnce();\n      expect(knownImage.getName()).andReturn(null).atLeastOnce();\n      expect(knownImage.getDescription()).andReturn(null).atLeastOnce();\n      expect(knownImage.getVersion()).andReturn(null).atLeastOnce();\n      expect(knownImage.getProviderId()).andReturn(\"ami\").atLeastOnce();\n\n      expect(knownImage.getOperatingSystem()).andReturn(os).atLeastOnce();\n\n      expect(os.getName()).andReturn(null).atLeastOnce();\n      expect(os.getVersion()).andReturn(null).atLeastOnce();\n      expect(os.getFamily()).andReturn(null).atLeastOnce();\n      expect(os.getDescription()).andReturn(null).atLeastOnce();\n      // paravirtual not compatible with r3 so deprecated c1 is forced\n      expect(os.getArch()).andReturn(\"paravirtual\").atLeastOnce();\n      expect(os.is64Bit()).andReturn(false).atLeastOnce();\n\n      replay(knownImage, os, defaultOptions, optionsProvider, templateBuilderProvider, getImageStrategy);\n\n      TemplateBuilderImpl template = createTemplateBuilder(knownImage, locations, images, sizes, region,\n            optionsProvider, templateBuilderProvider, getImageStrategy);\n\n      assertEquals(template.imageId(\"us-east-1/ami\").build().getImage(), knownImage);\n      assertEquals(template.imageId(\"us-east-1/ami\").build().getHardware(), c1_medium().build());\n\n      verify(knownImage, os, defaultOptions, optionsProvider, templateBuilderProvider, getImageStrategy);\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Test\n   public void testParseOnDemandWithoutRegionEncodedIntoId() {\n\n      Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n            .<Location> of(region));\n      Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of());\n      Supplier<Set<? extends Hardware>> sizes = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet\n            .<Hardware> of(c1_medium().build()));\n\n      Provider<TemplateOptions> optionsProvider = createMock(Provider.class);\n      Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);\n      TemplateOptions defaultOptions = createMock(TemplateOptions.class);\n      Image knownImage = createMock(Image.class);\n      GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class);\n      expect(knownImage.getId()).andReturn(\"region/ami\").anyTimes();\n      expect(knownImage.getProviderId()).andReturn(\"ami\").anyTimes();\n      expect(knownImage.getLocation()).andReturn(region).anyTimes();\n\n      expect(optionsProvider.get()).andReturn(defaultOptions);\n\n      replay(knownImage,  defaultOptions, optionsProvider, templateBuilderProvider, getImageStrategy);\n\n      TemplateBuilderImpl template = createTemplateBuilder(knownImage, locations, images, sizes, region,\n            optionsProvider, templateBuilderProvider, getImageStrategy);\n      try {\n         template.imageId(\"ami\").build();\n         fail(\"Expected IllegalArgumentException\");\n      } catch (IllegalArgumentException e) {\n\n      }\n\n      verify(knownImage,  defaultOptions, optionsProvider, templateBuilderProvider, getImageStrategy);\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Test(expectedExceptions = NoSuchElementException.class)\n   public void testParseOnDemandNotFound() {\n\n      Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n            .<Location> of(region));\n      Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of());\n      Supplier<Set<? extends Hardware>> sizes = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet\n            .<Hardware> of(c1_medium().build()));\n\n      Location defaultLocation = createMock(Location.class);\n      Provider<TemplateOptions> optionsProvider = createMock(Provider.class);\n      Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);\n      TemplateOptions defaultOptions = createMock(TemplateOptions.class);\n      GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class);\n      Image knownImage = createMock(Image.class);\n      expect(knownImage.getId()).andReturn(\"region/ami\").anyTimes();\n      expect(knownImage.getProviderId()).andReturn(\"ami\").anyTimes();\n      expect(knownImage.getLocation()).andReturn(region).anyTimes();\n\n      expect(defaultLocation.getId()).andReturn(\"region\");\n      expect(optionsProvider.get()).andReturn(defaultOptions);\n\n      replay(knownImage,  defaultOptions, defaultLocation, optionsProvider, templateBuilderProvider, getImageStrategy);\n\n      TemplateBuilderImpl template = createTemplateBuilder(knownImage, locations, images, sizes, defaultLocation,\n            optionsProvider, templateBuilderProvider, getImageStrategy);\n\n      assertEquals(template.imageId(\"region/bad\").build().getImage(), knownImage);\n\n      verify(knownImage,  defaultOptions, defaultLocation, optionsProvider, templateBuilderProvider, getImageStrategy);\n   }\n\n   // The EC2 provider already overrides the getImage method so this test is not useful for EC2\n   @Override\n   @Test(enabled = false)\n   public void testFindImageWithIdDefaultToGetImageStrategy() {\n\n   }\n\n   // The EC2 provider already overrides the getImage method so this test is not useful for EC2\n   @Override\n   public void testFindImageWithIdDefaultToGetImageStrategyAndPopulatesTheCache() {\n\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/compute/loaders/CreateSecurityGroupIfNeededTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.loaders;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.createNiceMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.expectLastCall;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Set;\nimport java.util.concurrent.ExecutionException;\n\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.compute.domain.RegionNameAndIngressRules;\nimport org.jclouds.ec2.domain.SecurityGroup;\nimport org.jclouds.ec2.domain.UserIdGroupPair;\nimport org.jclouds.ec2.features.SecurityGroupApi;\nimport org.jclouds.net.domain.IpProtocol;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Predicates;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\", singleThreaded = true, testName = \"CreateSecurityGroupIfNeeded\")\npublic class CreateSecurityGroupIfNeededTest {\n\n   @SuppressWarnings(\"unchecked\")\n   @Test\n   public void testWhenPort22AndToItselfAuthorizesIngressTwice() throws ExecutionException {\n\n      SecurityGroupApi client = createMock(SecurityGroupApi.class);\n      Predicate<RegionAndName> tester = Predicates.alwaysTrue();\n\n      SecurityGroup group = createNiceMock(SecurityGroup.class);\n      Set<SecurityGroup> groups = ImmutableSet.<SecurityGroup> of(group);\n\n      client.createSecurityGroupInRegion(\"region\", \"group\", \"group\");\n      client.authorizeSecurityGroupIngressInRegion(\"region\", \"group\", IpProtocol.TCP, 22, 22, \"0.0.0.0/0\");\n      expect(client.describeSecurityGroupsInRegion(\"region\", \"group\")).andReturn(Set.class.cast(groups));\n      expect(group.getOwnerId()).andReturn(\"ownerId\");\n      client.authorizeSecurityGroupIngressInRegion(\"region\", \"group\", new UserIdGroupPair(\"ownerId\", \"group\"));\n\n      replay(client);\n      replay(group);\n\n      CreateSecurityGroupIfNeeded function = new CreateSecurityGroupIfNeeded(client, tester);\n\n      assertEquals(\"group\", function.load(new RegionNameAndIngressRules(\"region\", \"group\", new int[] { 22 }, true, null)));\n\n      verify(client);\n      verify(group);\n\n   }\n\n   @Test\n   public void testIllegalStateExceptionCreatingGroupJustReturns() throws ExecutionException {\n\n      SecurityGroupApi client = createMock(SecurityGroupApi.class);\n      Predicate<RegionAndName> tester = Predicates.alwaysTrue();\n\n      client.createSecurityGroupInRegion(\"region\", \"group\", \"group\");\n      expectLastCall().andThrow(new IllegalStateException());\n\n      replay(client);\n\n      CreateSecurityGroupIfNeeded function = new CreateSecurityGroupIfNeeded(client, tester);\n\n      assertEquals(\"group\", function.load(new RegionNameAndIngressRules(\"region\", \"group\", new int[] { 22 }, true, null)));\n\n      verify(client);\n\n   }\n\n   @Test(expectedExceptions = RuntimeException.class)\n   public void testWhenEventualConsistencyExpiresIllegalStateException() throws ExecutionException {\n\n      SecurityGroupApi client = createMock(SecurityGroupApi.class);\n      Predicate<RegionAndName> tester = Predicates.alwaysFalse();\n\n      client.createSecurityGroupInRegion(\"region\", \"group\", \"group\");\n\n      replay(client);\n\n      CreateSecurityGroupIfNeeded function = new CreateSecurityGroupIfNeeded(client, tester);\n      function.load(new RegionNameAndIngressRules(\"region\", \"group\", new int[] { 22 }, true, null));\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/compute/loaders/LoadPublicIpForInstanceOrNullTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.loaders;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.domain.PublicIpInstanceIdPair;\nimport org.jclouds.ec2.features.ElasticIPAddressApi;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\", singleThreaded = true, testName = \"LoadPublicIpForInstanceOrNullTest\")\npublic class LoadPublicIpForInstanceOrNullTest {\n\n   @Test\n   public void testReturnsPublicIpOnMatch() throws Exception {\n      EC2Api client = createMock(EC2Api.class);\n      ElasticIPAddressApi ipClient = createMock(ElasticIPAddressApi.class);\n\n      expect(client.getElasticIPAddressApi()).andReturn((Optional) Optional.of(ipClient)).atLeastOnce();\n      expect(ipClient.describeAddressesInRegion(\"region\")).andReturn(\n            ImmutableSet.<PublicIpInstanceIdPair> of(new PublicIpInstanceIdPair(\"region\", \"1.1.1.1\", \"i-blah\", null, null)))\n            .atLeastOnce();\n\n      replay(client);\n      replay(ipClient);\n\n      LoadPublicIpForInstanceOrNull parser = new LoadPublicIpForInstanceOrNull(client);\n\n      assertEquals(parser.load(new RegionAndName(\"region\", \"i-blah\")), \"1.1.1.1\");\n\n      verify(client);\n      verify(ipClient);\n   }\n\n   @Test\n   public void testReturnsPublicIpAndAllocIdOnMatch() throws Exception {\n      EC2Api client = createMock(EC2Api.class);\n      ElasticIPAddressApi ipClient = createMock(ElasticIPAddressApi.class);\n\n      expect(client.getElasticIPAddressApi()).andReturn((Optional) Optional.of(ipClient)).atLeastOnce();\n      expect(ipClient.describeAddressesInRegion(\"region\")).andReturn(\n                      ImmutableSet.<PublicIpInstanceIdPair> of(new PublicIpInstanceIdPair(\"region\", \"1.1.1.1\", \"i-blah\", \"a-foobar\", null)))\n              .atLeastOnce();\n\n      replay(client);\n      replay(ipClient);\n\n      LoadAllocationIdForInstanceOrNull parser = new LoadAllocationIdForInstanceOrNull(client);\n\n      assertEquals(parser.load(new RegionAndName(\"region\", \"i-blah\")), \"a-foobar\");\n\n      verify(client);\n      verify(ipClient);\n   }\n\n   @Test\n   public void testReturnsNullWhenNotFound() throws Exception {\n      EC2Api client = createMock(EC2Api.class);\n      ElasticIPAddressApi ipClient = createMock(ElasticIPAddressApi.class);\n\n      expect(client.getElasticIPAddressApi()).andReturn((Optional) Optional.of(ipClient)).atLeastOnce();\n\n      expect(ipClient.describeAddressesInRegion(\"region\")).andReturn(ImmutableSet.<PublicIpInstanceIdPair> of())\n               .atLeastOnce();\n\n      replay(client);\n      replay(ipClient);\n\n      LoadPublicIpForInstanceOrNull parser = new LoadPublicIpForInstanceOrNull(client);\n\n      assertEquals(parser.load(new RegionAndName(\"region\", \"i-blah\")), null);\n\n      verify(client);\n      verify(ipClient);\n\n   }\n\n   @Test\n   public void testReturnsNullWhenNotAssigned() throws Exception {\n      EC2Api client = createMock(EC2Api.class);\n      ElasticIPAddressApi ipClient = createMock(ElasticIPAddressApi.class);\n\n      expect(client.getElasticIPAddressApi()).andReturn((Optional) Optional.of(ipClient)).atLeastOnce();\n\n      expect(ipClient.describeAddressesInRegion(\"region\")).andReturn(\n            ImmutableSet.<PublicIpInstanceIdPair> of(new PublicIpInstanceIdPair(\"region\", \"1.1.1.1\", null, null, null)))\n               .atLeastOnce();\n\n      replay(client);\n      replay(ipClient);\n\n      LoadPublicIpForInstanceOrNull parser = new LoadPublicIpForInstanceOrNull(client);\n\n      assertEquals(parser.load(new RegionAndName(\"region\", \"i-blah\")), null);\n\n      verify(client);\n      verify(ipClient);\n\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/compute/loaders/RegionAndIdToImageTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.loaders;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.createNiceMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.jclouds.ec2.options.DescribeImagesOptions.Builder.imageIds;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.NoSuchElementException;\nimport java.util.Set;\nimport java.util.concurrent.ExecutionException;\n\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.compute.functions.EC2ImageParser;\nimport org.jclouds.ec2.features.AMIApi;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\")\npublic class RegionAndIdToImageTest {\n\n   @SuppressWarnings(\"unchecked\")\n   @Test\n   public void testApply() throws ExecutionException {\n\n      EC2ImageParser parser = createMock(EC2ImageParser.class);\n      EC2Api caller = createMock(EC2Api.class);\n      AMIApi client = createMock(AMIApi.class);\n\n      org.jclouds.ec2.domain.Image ec2Image = createMock(org.jclouds.ec2.domain.Image.class);\n      Image image = createNiceMock(Image.class);\n      Set<? extends org.jclouds.ec2.domain.Image> images = ImmutableSet.<org.jclouds.ec2.domain.Image> of(ec2Image);\n\n      expect(caller.getAMIApi()).andReturn((Optional) Optional.of(client)).atLeastOnce();\n      expect(client.describeImagesInRegion(\"region\", imageIds(\"ami\"))).andReturn(Set.class.cast(images));\n      expect(parser.apply(ec2Image)).andReturn(image);\n\n      replay(caller);\n      replay(image);\n      replay(parser);\n      replay(client);\n\n      RegionAndIdToImage function = new RegionAndIdToImage(parser, caller);\n\n      assertEquals(function.load(new RegionAndName(\"region\", \"ami\")), image);\n\n      verify(caller);\n      verify(image);\n      verify(image);\n      verify(client);\n\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Test(expectedExceptions = ExecutionException.class)\n   public void testApplyNotFoundMakesExecutionException() throws ExecutionException {\n\n      EC2ImageParser parser = createMock(EC2ImageParser.class);\n      EC2Api caller = createMock(EC2Api.class);\n      AMIApi client = createMock(AMIApi.class);\n\n      org.jclouds.ec2.domain.Image ec2Image = createMock(org.jclouds.ec2.domain.Image.class);\n      Image image = createNiceMock(Image.class);\n      Set<? extends org.jclouds.ec2.domain.Image> images = ImmutableSet.<org.jclouds.ec2.domain.Image> of(ec2Image);\n\n      expect(caller.getAMIApi()).andReturn((Optional) Optional.of(client)).atLeastOnce();\n      expect(client.describeImagesInRegion(\"region\", imageIds(\"ami\"))).andReturn(Set.class.cast(images));\n      expect(parser.apply(ec2Image)).andThrow(new ResourceNotFoundException());\n\n      replay(caller);\n      replay(image);\n      replay(parser);\n      replay(client);\n\n      RegionAndIdToImage function = new RegionAndIdToImage(parser, caller);\n\n      assertEquals(function.load(new RegionAndName(\"region\", \"ami\")), null);\n\n      verify(caller);\n      verify(image);\n      verify(parser);\n      verify(client);\n\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Test(expectedExceptions = ExecutionException.class)\n   public void testApplyNoSuchElementExceptionMakesExecutionException() throws ExecutionException {\n\n      EC2ImageParser parser = createMock(EC2ImageParser.class);\n      EC2Api caller = createMock(EC2Api.class);\n      AMIApi client = createMock(AMIApi.class);\n\n      org.jclouds.ec2.domain.Image ec2Image = createMock(org.jclouds.ec2.domain.Image.class);\n      Image image = createNiceMock(Image.class);\n      Set<? extends org.jclouds.ec2.domain.Image> images = ImmutableSet.<org.jclouds.ec2.domain.Image> of(ec2Image);\n\n      expect(caller.getAMIApi()).andReturn((Optional) Optional.of(client)).atLeastOnce();\n      expect(client.describeImagesInRegion(\"region\", imageIds(\"ami\"))).andReturn(Set.class.cast(images));\n      expect(parser.apply(ec2Image)).andThrow(new NoSuchElementException());\n\n      replay(caller);\n      replay(image);\n      replay(parser);\n      replay(client);\n\n      RegionAndIdToImage function = new RegionAndIdToImage(parser, caller);\n\n      assertEquals(function.load(new RegionAndName(\"region\", \"ami\")), null);\n\n      verify(caller);\n      verify(image);\n      verify(parser);\n      verify(client);\n\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/compute/options/EC2TemplateOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.options;\n\nimport static org.jclouds.ec2.compute.options.EC2TemplateOptions.Builder.authorizePublicKey;\nimport static org.jclouds.ec2.compute.options.EC2TemplateOptions.Builder.blockOnPort;\nimport static org.jclouds.ec2.compute.options.EC2TemplateOptions.Builder.inboundPorts;\nimport static org.jclouds.ec2.compute.options.EC2TemplateOptions.Builder.installPrivateKey;\nimport static org.jclouds.ec2.compute.options.EC2TemplateOptions.Builder.keyPair;\nimport static org.jclouds.ec2.compute.options.EC2TemplateOptions.Builder.noKeyPair;\nimport static org.jclouds.ec2.compute.options.EC2TemplateOptions.Builder.securityGroups;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\n\nimport java.io.IOException;\n\nimport com.google.common.collect.ImmutableSet;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.testng.annotations.Test;\n\n/**\n * Tests possible uses of EC2TemplateOptions and EC2TemplateOptions.Builder.*\n */\npublic class EC2TemplateOptionsTest {\n\n   public void testAs() {\n      TemplateOptions options = new EC2TemplateOptions();\n      assertEquals(options.as(EC2TemplateOptions.class), options);\n   }\n\n   @Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = \"all security groups must be non-empty\")\n   public void testsecurityGroupsIterableBadFormat() {\n      EC2TemplateOptions options = new EC2TemplateOptions();\n      options.securityGroups(ImmutableSet.of(\"group1\", \"\"));\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testsecurityGroupsIterableEmptyNotOk() {\n      EC2TemplateOptions options = new EC2TemplateOptions();\n      options.securityGroups(ImmutableSet.<String> of());\n   }\n\n   @Test\n   public void testsecurityGroupsIterable() {\n      EC2TemplateOptions options = new EC2TemplateOptions();\n      options.securityGroups(ImmutableSet.of(\"group1\", \"group2\"));\n      assertEquals(options.getGroups(), ImmutableSet.of(\"group1\", \"group2\"));\n\n   }\n\n   @Test\n   public void testsecurityGroupsIterableStatic() {\n      EC2TemplateOptions options = securityGroups(ImmutableSet.of(\"group1\", \"group2\"));\n      assertEquals(options.getGroups(), ImmutableSet.of(\"group1\", \"group2\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = \"all security groups must be non-empty\")\n   public void testsecurityGroupsVarArgsBadFormat() {\n      EC2TemplateOptions options = new EC2TemplateOptions();\n      options.securityGroups(\"mygroup\", \"\");\n   }\n\n   @Test\n   public void testsecurityGroupsVarArgs() {\n      EC2TemplateOptions options = new EC2TemplateOptions();\n      options.securityGroups(\"group1\", \"group2\");\n      assertEquals(options.getGroups(), ImmutableSet.of(\"group1\", \"group2\"));\n\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testsecurityGroupsVarArgsEmptyNotOk() {\n      EC2TemplateOptions options = new EC2TemplateOptions();\n      options.securityGroups();\n   }\n\n   @Test\n   public void testDefaultGroupsVarArgsEmpty() {\n      EC2TemplateOptions options = new EC2TemplateOptions();\n      assertEquals(options.getGroups(), ImmutableSet.of());\n   }\n\n   @Test\n   public void testsecurityGroupsVarArgsStatic() {\n      EC2TemplateOptions options = securityGroups(\"group1\", \"group2\");\n      assertEquals(options.getGroups(), ImmutableSet.of(\"group1\", \"group2\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = \"use noKeyPair option to request boot without a keypair\")\n   public void testkeyPairBadFormat() {\n      EC2TemplateOptions options = new EC2TemplateOptions();\n      options.keyPair(\"\");\n   }\n\n   @Test(expectedExceptions = IllegalStateException.class)\n   public void testkeyPairAndNoKeyPair() {\n      EC2TemplateOptions options = new EC2TemplateOptions();\n      options.keyPair(\"mykeypair\");\n      options.noKeyPair();\n   }\n\n   @Test(expectedExceptions = IllegalStateException.class)\n   public void testNoKeyPairAndKeyPair() {\n      EC2TemplateOptions options = new EC2TemplateOptions();\n      options.noKeyPair();\n      options.keyPair(\"mykeypair\");\n   }\n\n   @Test\n   public void testkeyPair() {\n      EC2TemplateOptions options = new EC2TemplateOptions();\n      options.keyPair(\"mykeypair\");\n      assertEquals(options.getKeyPair(), \"mykeypair\");\n   }\n\n   @Test\n   public void testNullkeyPair() {\n      EC2TemplateOptions options = new EC2TemplateOptions();\n      assertEquals(options.getKeyPair(), null);\n   }\n\n   @Test\n   public void testkeyPairStatic() {\n      EC2TemplateOptions options = keyPair(\"mykeypair\");\n      assertEquals(options.getKeyPair(), \"mykeypair\");\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testkeyPairNPE() {\n      keyPair(null);\n   }\n\n   @Test\n   public void testnoKeyPair() {\n      EC2TemplateOptions options = new EC2TemplateOptions();\n      options.noKeyPair();\n      assertEquals(options.getKeyPair(), null);\n      assert !options.shouldAutomaticallyCreateKeyPair();\n   }\n\n   @Test\n   public void testFalsenoKeyPair() {\n      EC2TemplateOptions options = new EC2TemplateOptions();\n      assertEquals(options.getKeyPair(), null);\n      assert options.shouldAutomaticallyCreateKeyPair();\n   }\n\n   @Test\n   public void testnoKeyPairStatic() {\n      EC2TemplateOptions options = noKeyPair();\n      assertEquals(options.getKeyPair(), null);\n      assert !options.shouldAutomaticallyCreateKeyPair();\n   }\n\n   // superclass tests\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testinstallPrivateKeyBadFormat() {\n      EC2TemplateOptions options = new EC2TemplateOptions();\n      options.installPrivateKey(\"whompy\");\n   }\n\n   @Test\n   public void testinstallPrivateKey() throws IOException {\n      EC2TemplateOptions options = new EC2TemplateOptions();\n      options.installPrivateKey(\"-----BEGIN RSA PRIVATE KEY-----\");\n      assertEquals(options.getPrivateKey(), \"-----BEGIN RSA PRIVATE KEY-----\");\n   }\n\n   @Test\n   public void testNullinstallPrivateKey() {\n      EC2TemplateOptions options = new EC2TemplateOptions();\n      assertEquals(options.getPrivateKey(), null);\n   }\n\n   @Test\n   public void testinstallPrivateKeyStatic() throws IOException {\n      EC2TemplateOptions options = installPrivateKey(\"-----BEGIN RSA PRIVATE KEY-----\");\n      assertEquals(options.getPrivateKey(), \"-----BEGIN RSA PRIVATE KEY-----\");\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testinstallPrivateKeyNPE() {\n      installPrivateKey(null);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testauthorizePublicKeyBadFormat() {\n      EC2TemplateOptions options = new EC2TemplateOptions();\n      options.authorizePublicKey(\"whompy\");\n   }\n\n   @Test\n   public void testauthorizePublicKey() throws IOException {\n      EC2TemplateOptions options = new EC2TemplateOptions();\n      options.authorizePublicKey(\"ssh-rsa\");\n      assertEquals(options.getPublicKey(), \"ssh-rsa\");\n   }\n\n   @Test\n   public void testNullauthorizePublicKey() {\n      EC2TemplateOptions options = new EC2TemplateOptions();\n      assertEquals(options.getPublicKey(), null);\n   }\n\n   @Test\n   public void testauthorizePublicKeyStatic() throws IOException {\n      EC2TemplateOptions options = authorizePublicKey(\"ssh-rsa\");\n      assertEquals(options.getPublicKey(), \"ssh-rsa\");\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testauthorizePublicKeyNPE() {\n      authorizePublicKey(null);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testblockOnPortBadFormat() {\n      EC2TemplateOptions options = new EC2TemplateOptions();\n      options.blockOnPort(-1, -1);\n   }\n\n   @Test\n   public void testblockOnPort() {\n      EC2TemplateOptions options = new EC2TemplateOptions();\n      options.blockOnPort(22, 30);\n      assertEquals(options.getPort(), 22);\n      assertEquals(options.getSeconds(), 30);\n\n   }\n\n   @Test\n   public void testNullblockOnPort() {\n      EC2TemplateOptions options = new EC2TemplateOptions();\n      assertEquals(options.getPort(), -1);\n      assertEquals(options.getSeconds(), -1);\n   }\n\n   @Test\n   public void testblockOnPortStatic() {\n      EC2TemplateOptions options = blockOnPort(22, 30);\n      assertEquals(options.getPort(), 22);\n      assertEquals(options.getSeconds(), 30);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testinboundPortsBadFormat() {\n      EC2TemplateOptions options = new EC2TemplateOptions();\n      options.inboundPorts(-1, -1);\n   }\n\n   @Test\n   public void testinboundPorts() {\n      EC2TemplateOptions options = new EC2TemplateOptions();\n      options.inboundPorts(22, 30);\n      assertEquals(options.getInboundPorts()[0], 22);\n      assertEquals(options.getInboundPorts()[1], 30);\n\n   }\n\n   @Test\n   public void testDefaultOpen22() {\n      EC2TemplateOptions options = new EC2TemplateOptions();\n      assertEquals(options.getInboundPorts()[0], 22);\n   }\n\n   @Test\n   public void testinboundPortsStatic() {\n      EC2TemplateOptions options = inboundPorts(22, 30);\n      assertEquals(options.getInboundPorts()[0], 22);\n      assertEquals(options.getInboundPorts()[1], 30);\n   }\n\n   @Test\n   public void testMaxCountDefault() {\n      EC2TemplateOptions options = new EC2TemplateOptions();\n      assertEquals(options.getMaxCount(), 0);\n   }\n\n   @Test\n   public void testMaxCount() {\n      EC2TemplateOptions options = new EC2TemplateOptions();\n      options.maxCount(2);\n      assertEquals(options.getMaxCount(), 2);\n   }\n\n   @Test\n   public void testMaxCountNull() {\n      EC2TemplateOptions options = new EC2TemplateOptions();\n      options.maxCount(null);\n      assertEquals(options.getMaxCount(), 0);\n   }\n\n   @Test\n   public void testClientTokenDefault() {\n      EC2TemplateOptions options = new EC2TemplateOptions();\n      assertNull(options.getClientToken());\n   }\n\n   @Test\n   public void testClientToken() {\n      EC2TemplateOptions options = new EC2TemplateOptions();\n      options.clientToken(\"some-token\");\n      assertEquals(options.getClientToken(), \"some-token\");\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testClientTokenNPE() {\n      EC2TemplateOptions options = new EC2TemplateOptions();\n      options.clientToken(null);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/compute/strategy/CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.strategy;\n\nimport static com.google.common.io.BaseEncoding.base64;\nimport static org.easymock.EasyMock.anyObject;\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.partialMockBuilder;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertEquals;\n\nimport jakarta.inject.Provider;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentMap;\nimport java.util.concurrent.ExecutionException;\n\nimport com.google.common.base.Function;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\nimport org.jclouds.aws.domain.Region;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.ec2.compute.domain.EC2HardwareBuilder;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.compute.domain.RegionNameAndIngressRules;\nimport org.jclouds.ec2.compute.options.EC2TemplateOptions;\nimport org.jclouds.ec2.domain.BlockDeviceMapping;\nimport org.jclouds.ec2.domain.KeyPair;\nimport org.jclouds.ec2.options.RunInstancesOptions;\nimport org.jclouds.scriptbuilder.domain.Statements;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", singleThreaded = true, testName = \"CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptionsTest\")\npublic class CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptionsTest {\n\n   public static final LoginCredentials CREDENTIALS = LoginCredentials\n         .builder()\n         .privateKey(\n               \"-----BEGIN RSA PRIVATE KEY-----\\n\"\n                     + \"MIIEowIBAAKCAQEA0CbFlhSdbMdad2ux2BVqk6Ut5fLKb0CdbqubGcEBfwsSz9Rp4Ile76P90MpV\\n\"\n                     + \"W1BGKL5V4MO+flG6dZnRWPVmgrNVyDTmEsALiMGjfEwbACEZ1A8C6mPa36wWO7MlxuyMjg8OczTB\\n\"\n                     + \"EXnHNDpxE5a6KowJtzFlmgjHk2Y+Q42UIqPx47lQUv5bdMDCnfNNomSzTVRjOZLUkDja+ybCKdux\\n\"\n                     + \"gqTsuInhuBRMx+wxff8Z43ECdJV6UPoXK3der1dlZunxGCFkCeYq0kCX7FZ7PV35X744jqhD8P+7\\n\"\n                     + \"y5prO4W+M3DWgChUx0OlbDbSHtDVlcfdbj/+4AKYKU6rQOqh+4DPDQIDAQABAoIBAHjQuEiXKJSV\\n\"\n                     + \"1U2RZcVtENInws9AL/2I/Jfa5Qh6vTqXG9EjklywfzkK72x7tDVvD3ngmAoAs5WwLFDL+fXvYhOk\\n\"\n                     + \"sbql8ZCahVdYRWME7XsSu2IZYHDZipXe1XzLS7b9X8uos5Ns4E8bZuNKtI1RJDdD1vPMqRNR2z0T\\n\"\n                     + \"0Dn3eC7t+t+t7PWaK5AXu2ot7DoOeG1QhqJbwd5pMkIn2ydBILytgmDk/2P3EtJGePIJIeQBicmw\\n\"\n                     + \"Z0KrJFa/K2cC8AtmMJUoZMo+mh1yemDbDLCZW30PjFHbZtcszS2cydAgq/HDFkZynvZG0zhbx/To\\n\"\n                     + \"jzcNza1AyypYwOwb2/9/ulXZp0UCgYEA+QFgWDfYLH2zwjU5b6e0UbIyd/X/yRZ+L8lOEBd0Bbu8\\n\"\n                     + \"qO3txaDbwi7o2mG7pJENHJ3u62CHjgTGDNW9V9Q8eNoGtj3uHvMvi7FdDEK8B6izdZyR7hmZmQ/5\\n\"\n                     + \"MIldelyiGZlz1KBSoy4FsCpA7hV7cI6H6x+Im24NxG90/wd/EgMCgYEA1f+cUyUisIO3yKOCf0hQ\\n\"\n                     + \"aL289q2//F2cbvBxtki6I8JzTg1H3oTO2WVrXQeCA3a/yiuRUatgGH4mxrpCF6byVJyqrEWAj4kU\\n\"\n                     + \"uTbhMgIYhLGoaF1e+vMirCRXUXox0i5X976ASzHn64V9JSd1B+UbKfpcFTYYnChmrRDzmhKN1a8C\\n\"\n                     + \"gYBTvIHAyO7ab18/BRUOllAOVSWhr8lXv0eqHEEzKh/rOaoFCRY3qpOcZpgJsGogumK1Z+sLnoeX\\n\"\n                     + \"W8WaVVp6KbY4UeGF8aedItyvVnLbB6ohzTqkZ4Wvk05S6cs75kXYO0SL5U3NiCiiFXz2NA9nwTOk\\n\"\n                     + \"s1nD2PPgiQ76Kx0mEkhKLwKBgFhHEJqv+AZu37Kx2NRe5WS/2KK9/DPD/hM5tv7mM3sq7Nvm2J3v\\n\"\n                     + \"lVDS6J5AyZ5aLzXcER9qncKcz6wtC7SsFs1Wr4VPSoBroRPikrVJbgnXK8yZr+O/xq7Scv7WdJTq\\n\"\n                     + \"rzkw6cWbObvLnltkUn/GQBVqBPBvF2nbtLdyBbuqKb5bAoGBAI1+aoJnvXEXxT4UHrMkQcY0eXRz\\n\"\n                     + \"3UdbzJmtjMW9CR6l9s11mV6PcZP4qnODp3nd6a+lPeL3wVYQ47DsTJ/Bx5dI17zA5mU57n6mV0a3\\n\"\n                     + \"DbSoPKSdaKTQdo2THnVE9P9sPKZWueAcsE4Yw/qcTjoxrtUnAH/AXN250v0tkKIOvMhu\\n\"\n                     + \"-----END RSA PRIVATE KEY-----\").build();\n\n   public static final KeyPair KEYPAIR = KeyPair.builder().region(Region.AP_SOUTHEAST_1).keyName(\"myKeyPair\")\n         .sha1OfPrivateKey(\"13:36:74:b9:56:bb:07:96:c0:19:ab:00:7f:9f:06:d2:16:a0:45:32\")\n         .fingerprint(\"60:15:d1:f1:d9:e2:3c:e2:ee:a9:64:6a:42:a7:34:0c\").keyMaterial(CREDENTIALS.credential).build();\n\n   private static final Provider<RunInstancesOptions> OPTIONS_PROVIDER = new jakarta.inject.Provider<RunInstancesOptions>() {\n\n      @Override\n      public RunInstancesOptions get() {\n         return new RunInstancesOptions();\n      }\n\n   };\n\n   public void testExecuteWithDefaultOptionsEC2() throws SecurityException, NoSuchMethodException {\n      // setup constants\n      String region = Region.AP_SOUTHEAST_1;\n      String group = \"group\";\n      Hardware size = EC2HardwareBuilder.m1_small().build();\n      String systemGeneratedKeyPairName = \"systemGeneratedKeyPair\";\n      String generatedGroup = \"group\";\n      Set<String> generatedGroups = ImmutableSet.of(generatedGroup);\n\n      // create mocks\n      CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions strategy = partialMockBuilder(\n            CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class)\n            .addMockedMethod(\n                  CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class\n                        .getDeclaredMethod(\"getOptionsProvider\"))\n            .addMockedMethod(\n                  CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod(\n                        \"createNewKeyPairUnlessUserSpecifiedOtherwise\", String.class, String.class,\n                        TemplateOptions.class))\n            .addMockedMethod(\n                  CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod(\n                        \"getSecurityGroupsForTagAndOptions\", String.class, String.class, String.class,\n                        TemplateOptions.class))\n            .createMock();\n\n      EC2TemplateOptions options = createMock(EC2TemplateOptions.class);\n      Template template = createMock(Template.class);\n\n      // setup expectations\n      expect(strategy.getOptionsProvider()).andReturn(OPTIONS_PROVIDER);\n      expect(template.getHardware()).andReturn(size).atLeastOnce();\n      expect(template.getOptions()).andReturn(options).atLeastOnce();\n      expect(options.getBlockDeviceMappings()).andReturn(ImmutableSet.<BlockDeviceMapping> of()).atLeastOnce();\n      expect(strategy.createNewKeyPairUnlessUserSpecifiedOtherwise(region, group, options)).andReturn(\n            systemGeneratedKeyPairName);\n      expect(strategy.getSecurityGroupsForTagAndOptions(region, group, null, options)).andReturn(generatedGroups);\n      expect(options.getUserData()).andReturn(null);\n      expect(options.getClientToken()).andReturn(null);\n\n      // replay mocks\n      replay(options);\n      replay(template);\n      replay(strategy);\n\n      // run\n      RunInstancesOptions customize = strategy.execute(region, group, template);\n      assertEquals(customize.buildQueryParameters(), ImmutableMultimap.<String, String> of());\n      assertEquals(\n            customize.buildFormParameters().entries(),\n            ImmutableMultimap.<String, String> of(\"InstanceType\", size.getProviderId(), \"SecurityGroup.1\",\n                  generatedGroup, \"KeyName\", systemGeneratedKeyPairName).entries());\n      assertEquals(customize.buildRequestHeaders(), ImmutableMultimap.<String, String> of());\n      assertEquals(customize.buildStringPayload(), null);\n\n      // verify mocks\n      verify(options);\n      verify(template);\n      verify(strategy);\n   }\n\n   public void testExecuteWithUserData() throws SecurityException, NoSuchMethodException {\n      // setup constants\n      String region = Region.AP_SOUTHEAST_1;\n      String group = \"group\";\n      Hardware size = EC2HardwareBuilder.m1_small().build();\n      String systemGeneratedKeyPairName = \"systemGeneratedKeyPair\";\n      String generatedGroup = \"group\";\n      Set<String> generatedGroups = ImmutableSet.of(generatedGroup);\n\n      // create mocks\n      CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions strategy = partialMockBuilder(\n            CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class)\n            .addMockedMethod(\n                  CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class\n                        .getDeclaredMethod(\"getOptionsProvider\"))\n            .addMockedMethod(\n                  CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod(\n                        \"createNewKeyPairUnlessUserSpecifiedOtherwise\", String.class, String.class,\n                        TemplateOptions.class))\n            .addMockedMethod(\n                  CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod(\n                        \"getSecurityGroupsForTagAndOptions\", String.class, String.class, String.class,\n                        TemplateOptions.class))\n            .createMock();\n\n      EC2TemplateOptions options = createMock(EC2TemplateOptions.class);\n      Template template = createMock(Template.class);\n\n      // setup expectations\n      expect(strategy.getOptionsProvider()).andReturn(OPTIONS_PROVIDER);\n      expect(template.getHardware()).andReturn(size).atLeastOnce();\n      expect(template.getOptions()).andReturn(options).atLeastOnce();\n      expect(options.getBlockDeviceMappings()).andReturn(ImmutableSet.<BlockDeviceMapping> of()).atLeastOnce();\n      expect(options.getClientToken()).andReturn(\"some-token\");\n      expect(strategy.createNewKeyPairUnlessUserSpecifiedOtherwise(region, group, options)).andReturn(\n            systemGeneratedKeyPairName);\n      expect(strategy.getSecurityGroupsForTagAndOptions(region, group, null, options)).andReturn(generatedGroups);\n      expect(options.getUserData()).andReturn(\"hello\".getBytes());\n\n      // replay mocks\n      replay(options);\n      replay(template);\n      replay(strategy);\n\n      // run\n      RunInstancesOptions customize = strategy.execute(region, group, template);\n      assertEquals(customize.buildQueryParameters(), ImmutableMultimap.<String, String> of());\n      assertEquals(\n            customize.buildFormParameters().entries(),\n            ImmutableMultimap.<String, String> of(\"InstanceType\", size.getProviderId(), \"SecurityGroup.1\", \"group\",\n                  \"KeyName\", systemGeneratedKeyPairName, \"UserData\", base64().encode(\"hello\".getBytes()),\n                    \"ClientToken\", \"some-token\").entries());\n\n      assertEquals(customize.buildRequestHeaders(), ImmutableMultimap.<String, String> of());\n      assertEquals(customize.buildStringPayload(), null);\n\n      // verify mocks\n      verify(options);\n      verify(template);\n      verify(strategy);\n   }\n\n   public void testCreateNewKeyPairUnlessUserSpecifiedOtherwise_reusesKeyWhenToldTo() {\n      // setup constants\n      String region = Region.AP_SOUTHEAST_1;\n      String group = \"group\";\n      String userSuppliedKeyPair = \"myKeyPair\";\n\n      // create mocks\n      CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions strategy = setupStrategy();\n      EC2TemplateOptions options = createMock(EC2TemplateOptions.class);\n      KeyPair keyPair = createMock(KeyPair.class);\n\n      // setup expectations\n      expect(options.getKeyPair()).andReturn(userSuppliedKeyPair);\n      expect(options.getLoginPrivateKey()).andReturn(null);\n      expect(options.getRunScript()).andReturn(null);\n\n      // replay mocks\n      replay(options);\n      replay(keyPair);\n      replayStrategy(strategy);\n\n      // run\n      assertEquals(strategy.createNewKeyPairUnlessUserSpecifiedOtherwise(region, group, options), userSuppliedKeyPair);\n\n      // verify mocks\n      verify(options);\n      verify(keyPair);\n      verifyStrategy(strategy);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testCreateNewKeyPairUnlessUserSpecifiedOtherwise_reusesKeyWhenToldToWithRunScriptButNoCredentials() {\n      // setup constants\n      String region = Region.AP_SOUTHEAST_1;\n      String group = \"group\";\n      String userSuppliedKeyPair = \"myKeyPair\";\n\n      // create mocks\n      CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions strategy = setupStrategy();\n      EC2TemplateOptions options = createMock(EC2TemplateOptions.class);\n      KeyPair keyPair = createMock(KeyPair.class);\n\n      // setup expectations\n      expect(options.getKeyPair()).andReturn(userSuppliedKeyPair);\n      expect(options.getLoginUser()).andReturn(null);\n      expect(options.getLoginPassword()).andReturn(null);\n      expect(options.getLoginPrivateKey()).andReturn(null);\n      expect(options.shouldAuthenticateSudo()).andReturn(null);\n      expect(options.getRunScript()).andReturn(Statements.exec(\"echo foo\"));\n\n      expect(strategy.credentialsMap.containsKey(new RegionAndName(region, userSuppliedKeyPair))).andReturn(false);\n\n      // replay mocks\n      replay(options);\n      replay(keyPair);\n      replayStrategy(strategy);\n\n      // run\n      assertEquals(strategy.createNewKeyPairUnlessUserSpecifiedOtherwise(region, group, options), userSuppliedKeyPair);\n\n      // verify mocks\n      verify(options);\n      verify(keyPair);\n      verifyStrategy(strategy);\n   }\n\n   public void testCreateNewKeyPairUnlessUserSpecifiedOtherwise_reusesKeyWhenToldToWithRunScriptAndCredentialsAlreadyInMap() {\n      // setup constants\n      String region = Region.AP_SOUTHEAST_1;\n      String group = \"group\";\n      String userSuppliedKeyPair = \"myKeyPair\";\n\n      // create mocks\n      CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions strategy = setupStrategy();\n      EC2TemplateOptions options = createMock(EC2TemplateOptions.class);\n      KeyPair keyPair = createMock(KeyPair.class);\n\n      // setup expectations\n      expect(options.getKeyPair()).andReturn(userSuppliedKeyPair);\n      expect(options.getLoginPrivateKey()).andReturn(null);\n      expect(options.getRunScript()).andReturn(Statements.exec(\"echo foo\"));\n\n      expect(strategy.credentialsMap.containsKey(new RegionAndName(region, userSuppliedKeyPair))).andReturn(true);\n\n      // replay mocks\n      replay(options);\n      replay(keyPair);\n      replayStrategy(strategy);\n\n      // run\n      assertEquals(strategy.createNewKeyPairUnlessUserSpecifiedOtherwise(region, group, options), userSuppliedKeyPair);\n\n      // verify mocks\n      verify(options);\n      verify(keyPair);\n      verifyStrategy(strategy);\n   }\n\n   public void testCreateNewKeyPairUnlessUserSpecifiedOtherwise_reusesKeyWhenToldToWithRunScriptAndCredentialsSpecified() {\n      // setup constants\n      String region = Region.AP_SOUTHEAST_1;\n      String group = \"group\";\n      String userSuppliedKeyPair = \"myKeyPair\";\n\n      // create mocks\n      CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions strategy = setupStrategy();\n      EC2TemplateOptions options = createMock(EC2TemplateOptions.class);\n      KeyPair keyPair = createMock(KeyPair.class);\n\n      // setup expectations\n      expect(options.getKeyPair()).andReturn(userSuppliedKeyPair);\n      expect(options.getLoginPrivateKey()).andReturn(CREDENTIALS.getOptionalPrivateKey().get()).atLeastOnce();\n\n      // Notice that the fingerprint and sha1 generated\n      expect(strategy.credentialsMap.put(new RegionAndName(region, userSuppliedKeyPair), KEYPAIR)).andReturn(null);\n      expect(options.getRunScript()).andReturn(Statements.exec(\"echo foo\"));\n      expect(strategy.credentialsMap.containsKey(new RegionAndName(region, userSuppliedKeyPair))).andReturn(true);\n\n      // replay mocks\n      replay(options);\n      replay(keyPair);\n      replayStrategy(strategy);\n\n      // run\n      assertEquals(strategy.createNewKeyPairUnlessUserSpecifiedOtherwise(region, group, options), userSuppliedKeyPair);\n\n      // verify mocks\n      verify(options);\n      verify(keyPair);\n      verifyStrategy(strategy);\n   }\n\n   public void testCreateNewKeyPairUnlessUserSpecifiedOtherwise_createsNewKeyPairAndReturnsItsNameByDefault()\n         throws ExecutionException {\n      // setup constants\n      String region = Region.AP_SOUTHEAST_1;\n      String group = \"group\";\n      String userSuppliedKeyPair = null;\n      boolean shouldAutomaticallyCreateKeyPair = true;\n      String systemGeneratedKeyPairName = \"systemGeneratedKeyPair\";\n\n      // create mocks\n      CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions strategy = setupStrategy();\n      EC2TemplateOptions options = createMock(EC2TemplateOptions.class);\n      KeyPair keyPair = createMock(KeyPair.class);\n\n      // setup expectations\n      expect(options.getKeyPair()).andReturn(userSuppliedKeyPair);\n      expect(options.shouldAutomaticallyCreateKeyPair()).andReturn(shouldAutomaticallyCreateKeyPair);\n      expect(keyPair.getKeyName()).andReturn(systemGeneratedKeyPairName).atLeastOnce();\n      expect(strategy.credentialsMap.putIfAbsent(anyObject(RegionAndName.class), anyObject(KeyPair.class))).andReturn(keyPair);\n      expect(options.getRunScript()).andReturn(null);\n\n      // replay mocks\n      replay(options);\n      replay(keyPair);\n      replayStrategy(strategy);\n\n      // run\n      assertEquals(strategy.createNewKeyPairUnlessUserSpecifiedOtherwise(region, group, options),\n            systemGeneratedKeyPairName);\n\n      // verify mocks\n      verify(options);\n      verify(keyPair);\n      verifyStrategy(strategy);\n   }\n\n   public void testCreateNewKeyPairUnlessUserSpecifiedOtherwise_doesntCreateAKeyPairAndReturnsNullWhenToldNotTo() {\n      // setup constants\n      String region = Region.AP_SOUTHEAST_1;\n      String group = \"group\";\n      String userSuppliedKeyPair = null;\n      boolean shouldAutomaticallyCreateKeyPair = false; // here's the important\n      // part!\n\n      // create mocks\n      CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions strategy = setupStrategy();\n      EC2TemplateOptions options = createMock(EC2TemplateOptions.class);\n      KeyPair keyPair = createMock(KeyPair.class);\n\n      // setup expectations\n      expect(options.getKeyPair()).andReturn(userSuppliedKeyPair);\n      expect(options.getRunScript()).andReturn(null);\n      expect(options.shouldAutomaticallyCreateKeyPair()).andReturn(shouldAutomaticallyCreateKeyPair);\n\n      // replay mocks\n      replay(options);\n      replay(keyPair);\n      replayStrategy(strategy);\n\n      // run\n      assertEquals(strategy.createNewKeyPairUnlessUserSpecifiedOtherwise(region, group, options), null);\n\n      // verify mocks\n      verify(options);\n      verify(keyPair);\n      verifyStrategy(strategy);\n   }\n\n   public void testGetSecurityGroupsForTagAndOptions_createsNewGroupByDefaultWhenNoPortsAreSpecifiedWhenDoesntExist()\n         throws ExecutionException {\n      // setup constants\n      String region = Region.AP_SOUTHEAST_1;\n      String group = \"group\";\n      String generatedMarkerGroup = \"jclouds#group\";\n      Set<String> groupIds = ImmutableSet.<String> of();\n      int[] ports = {};\n      boolean shouldAuthorizeSelf = true;\n      Set<String> returnVal = ImmutableSet.<String> of(generatedMarkerGroup);\n\n      // create mocks\n      CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions strategy = setupStrategy();\n      EC2TemplateOptions options = createMock(EC2TemplateOptions.class);\n\n      // setup expectations\n      expect(options.getGroups()).andReturn(groupIds).atLeastOnce();\n      expect(options.getInboundPorts()).andReturn(ports).atLeastOnce();\n      RegionNameAndIngressRules regionNameAndIngressRules = new RegionNameAndIngressRules(region, generatedMarkerGroup,\n            ports, shouldAuthorizeSelf, null);\n      expect(strategy.securityGroupMap.getUnchecked(regionNameAndIngressRules)).andReturn(generatedMarkerGroup);\n\n      // replay mocks\n      replay(options);\n      replayStrategy(strategy);\n\n      // run\n      assertEquals(strategy.getSecurityGroupsForTagAndOptions(region, group, null, options), returnVal);\n\n      // verify mocks\n      verify(options);\n      verifyStrategy(strategy);\n   }\n\n   public void testGetSecurityGroupsForTagAndOptions_createsNewGroupByDefaultWhenPortsAreSpecifiedWhenDoesntExist()\n         throws ExecutionException {\n      // setup constants\n      String region = Region.AP_SOUTHEAST_1;\n      String group = \"group\";\n      String generatedMarkerGroup = \"jclouds#group\";\n      Set<String> groupIds = ImmutableSet.<String> of();\n      int[] ports = { 22, 80 };\n      boolean shouldAuthorizeSelf = true;\n      Set<String> returnVal = ImmutableSet.<String> of(generatedMarkerGroup);\n\n      // create mocks\n      CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions strategy = setupStrategy();\n      EC2TemplateOptions options = createMock(EC2TemplateOptions.class);\n\n      // setup expectations\n      expect(options.getGroups()).andReturn(groupIds).atLeastOnce();\n      expect(options.getInboundPorts()).andReturn(ports).atLeastOnce();\n      RegionNameAndIngressRules regionNameAndIngressRules = new RegionNameAndIngressRules(region, generatedMarkerGroup,\n            ports, shouldAuthorizeSelf, null);\n      expect(strategy.securityGroupMap.getUnchecked(regionNameAndIngressRules)).andReturn(generatedMarkerGroup);\n\n      // replay mocks\n      replay(options);\n      replayStrategy(strategy);\n\n      // run\n      assertEquals(strategy.getSecurityGroupsForTagAndOptions(region, group, null, options), returnVal);\n\n      // verify mocks\n      verify(options);\n      verifyStrategy(strategy);\n   }\n\n   public void testGetSecurityGroupsForTagAndOptions_reusesGroupByDefaultWhenNoPortsAreSpecifiedWhenDoesExist()\n         throws ExecutionException {\n      // setup constants\n      String region = Region.AP_SOUTHEAST_1;\n      String group = \"group\";\n      String generatedMarkerGroup = \"jclouds#group\";\n      Set<String> groupIds = ImmutableSet.<String> of();\n      int[] ports = {};\n      boolean shouldAuthorizeSelf = true;\n      Set<String> returnVal = ImmutableSet.<String> of(generatedMarkerGroup);\n\n      // create mocks\n      CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions strategy = setupStrategy();\n      EC2TemplateOptions options = createMock(EC2TemplateOptions.class);\n\n      // setup expectations\n      expect(options.getGroups()).andReturn(groupIds).atLeastOnce();\n      expect(options.getInboundPorts()).andReturn(ports).atLeastOnce();\n      RegionNameAndIngressRules regionNameAndIngressRules = new RegionNameAndIngressRules(region, generatedMarkerGroup,\n            ports, shouldAuthorizeSelf, null);\n      expect(strategy.securityGroupMap.getUnchecked(regionNameAndIngressRules)).andReturn(generatedMarkerGroup);\n\n      // replay mocks\n      replay(options);\n      replayStrategy(strategy);\n\n      // run\n      assertEquals(strategy.getSecurityGroupsForTagAndOptions(region, group, null, options), returnVal);\n\n      // verify mocks\n      verify(options);\n      verifyStrategy(strategy);\n   }\n\n   public void testGetSecurityGroupsForTagAndOptions_DoesNorReuseGroupByDefaultWhenNoPortsAreSpecifiedWhenDoesExistAndAcceptsUserSuppliedGroups() {\n      // setup constants\n      String region = Region.AP_SOUTHEAST_1;\n      String group = \"group\";\n      Set<String> groupIds = ImmutableSet.<String> of(\"group1\", \"group2\");\n      Set<String> returnVal = ImmutableSet.<String> of(\"group1\", \"group2\");\n\n      // create mocks\n      CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions strategy = setupStrategy();\n      EC2TemplateOptions options = createMock(EC2TemplateOptions.class);\n\n      // setup expectations\n      expect(options.getGroups()).andReturn(groupIds).atLeastOnce();\n\n      // replay mocks\n      replay(options);\n      replayStrategy(strategy);\n\n      // run\n      assertEquals(strategy.getSecurityGroupsForTagAndOptions(region, group, null, options), returnVal);\n\n      // verify mocks\n      verify(options);\n      verifyStrategy(strategy);\n   }\n\n   private void verifyStrategy(CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions strategy) {\n      verify(strategy.makeKeyPair);\n      verify(strategy.credentialsMap);\n      verify(strategy.securityGroupMap);\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   private CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions setupStrategy() {\n      Function<RegionAndName, KeyPair> makeKeyPair = createMock(Function.class);\n      ConcurrentMap<RegionAndName, KeyPair> credentialsMap = createMock(ConcurrentMap.class);\n      LoadingCache<RegionAndName, String> securityGroupMap = createMock(LoadingCache.class);\n      GroupNamingConvention.Factory namingConventionFactory = createMock(GroupNamingConvention.Factory.class);\n      GroupNamingConvention namingConvention = createMock(GroupNamingConvention.class);\n      expect(makeKeyPair.apply(anyObject(RegionAndName.class))).andReturn(null).anyTimes();\n      expect(namingConventionFactory.create()).andReturn(namingConvention).anyTimes();\n      expect(namingConvention.sharedNameForGroup(\"group\")).andReturn(\"jclouds#group\").anyTimes();\n      replay(namingConventionFactory);\n      replay(namingConvention);\n      \n      return new CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions(makeKeyPair, credentialsMap,\n            securityGroupMap, OPTIONS_PROVIDER, namingConventionFactory);\n   }\n\n   private void replayStrategy(CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions strategy) {\n      replay(strategy.makeKeyPair);\n      replay(strategy.credentialsMap);\n      replay(strategy.securityGroupMap);\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/compute/strategy/EC2CreateNodesInGroupThenAddToSetTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.strategy;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.eq;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.reportMatcher;\nimport static org.easymock.EasyMock.verify;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport com.google.common.base.Optional;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Multimap;\nimport org.easymock.IArgumentMatcher;\nimport org.jclouds.compute.config.CustomizationResponse;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadata.Status;\nimport org.jclouds.compute.domain.NodeMetadataBuilder;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.predicates.AtomicNodeRunning;\nimport org.jclouds.compute.strategy.GetNodeMetadataStrategy;\nimport org.jclouds.compute.util.ComputeUtils;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.compute.functions.PresentInstances;\nimport org.jclouds.ec2.compute.functions.RunningInstanceToNodeMetadata;\nimport org.jclouds.ec2.compute.options.EC2TemplateOptions;\nimport org.jclouds.ec2.domain.Reservation;\nimport org.jclouds.ec2.domain.RunningInstance;\nimport org.jclouds.ec2.features.ElasticIPAddressApi;\nimport org.jclouds.ec2.features.InstanceApi;\nimport org.jclouds.ec2.options.RunInstancesOptions;\nimport org.testng.Assert;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", singleThreaded = true, testName = \"EC2CreateNodesInGroupThenAddToSetTest\")\npublic class EC2CreateNodesInGroupThenAddToSetTest {\n\n   @SuppressWarnings(\"unchecked\")\n   public void testIpAllocationThenAfterNodeRunningAssignThenUpdateCache() {\n      Location location = ZONE_AP_SOUTHEAST_1A;\n      String region = \"ap-southeast-1\";\n      String zone = \"ap-southeast-1a\";\n\n      String imageId = \"ami1\";\n      String instanceCreatedId = \"instance1\";\n      NodeMetadata nodeMetadata = new NodeMetadataBuilder().id(region + \"/\" + instanceCreatedId)\n            .providerId(instanceCreatedId).status(Status.RUNNING).build();\n      // setup mocks\n      EC2CreateNodesInGroupThenAddToSet strategy = setupStrategy(nodeMetadata);\n      InputParams input = new InputParams(location);\n      InstanceApi instanceClient = createMock(InstanceApi.class);\n      ElasticIPAddressApi ipClient = createMock(ElasticIPAddressApi.class);\n      RunInstancesOptions ec2Options = createMock(RunInstancesOptions.class);\n      RunningInstance instance = createMock(RunningInstance.class);\n      Reservation<? extends RunningInstance> reservation = new Reservation<RunningInstance>(region,\n            ImmutableSet.<String> of(), ImmutableSet.<RunningInstance> of(instance), \"ownerId\", \"requesterId\",\n            \"reservationId\");\n\n      // enable auto-allocation\n      strategy.autoAllocateElasticIps = true;\n\n      // setup expectations\n      expect(input.template.clone()).andReturn(input.template);\n      expect(strategy.client.getInstanceApi()).andReturn((Optional) Optional.of(instanceClient)).atLeastOnce();\n      expect(\n            strategy.createKeyPairAndSecurityGroupsAsNeededAndReturncustomize\n                  .execute(region, input.tag, input.template)).andReturn(ec2Options);\n      expect(strategy.client.getElasticIPAddressApi()).andReturn((Optional) Optional.of(ipClient)).atLeastOnce();\n\n      expect(input.template.getLocation()).andReturn(input.location).atLeastOnce();\n      expect(input.template.getImage()).andReturn(input.image).atLeastOnce();\n      expect(input.image.getProviderId()).andReturn(imageId).atLeastOnce();\n\n      // differences when ip allocation\n      expect(ipClient.allocateAddressInRegion(region)).andReturn(\"1.1.1.1\");\n      expect(strategy.runningInstanceToNodeMetadata.apply(instance)).andReturn(nodeMetadata).atLeastOnce();\n      ipClient.associateAddressInRegion(region, \"1.1.1.1\", instanceCreatedId);\n      strategy.elasticIpCache.put(new RegionAndName(region, instanceCreatedId), \"1.1.1.1\");\n\n      expect(instanceClient.runInstancesInRegion(region, zone, imageId, 1, input.count, ec2Options)).andReturn(\n            Reservation.class.cast(reservation));\n      expect(instance.getId()).andReturn(instanceCreatedId).atLeastOnce();\n      // simulate a lazy credentials fetch\n      LoginCredentials creds = LoginCredentials.builder().user(\"foo\").privateKey(\"bar\").build();\n      expect(strategy.instanceToCredentials.getUnchecked(instance)).andReturn(Optional.of(creds));\n      expect(instance.getRegion()).andReturn(region).atLeastOnce();\n      expect(strategy.credentialStore.put(\"node#\" + region + \"/\" + instanceCreatedId, creds)).andReturn(null);\n\n      expect(strategy.presentInstances.apply(ImmutableSet.of(new RegionAndName(region, instanceCreatedId)))).andReturn(ImmutableSet.of(instance));\n      expect(input.template.getOptions()).andReturn(input.options).atLeastOnce();\n      expect(input.options.getLoginUser()).andReturn(null);\n      expect(input.options.getLoginPassword()).andReturn(null);\n      expect(input.options.getLoginPrivateKey()).andReturn(null);\n      expect(input.options.shouldAuthenticateSudo()).andReturn(null);\n      expect(input.options.getMaxCount()).andReturn(0);\n\n      expect(\n            strategy.utils.customizeNodesAndAddToGoodMapOrPutExceptionIntoBadMap(eq(input.options),\n                  containsNodeMetadata(nodeMetadata), eq(input.nodes), eq(input.badNodes), eq(input.customization)))\n            .andReturn(null);\n\n      // replay mocks\n      replay(instanceClient);\n      replay(ipClient);\n      replay(ec2Options);\n      replay(instance);\n      input.replayMe();\n      replayStrategy(strategy);\n\n      // run\n      strategy.execute(input.tag, input.count, input.template, input.nodes, input.badNodes, input.customization);\n\n      // verify mocks\n      verify(instanceClient);\n      verify(ipClient);\n      verify(ec2Options);\n      verify(instance);\n      input.verifyMe();\n      verifyStrategy(strategy);\n   }\n\n   @Test\n   public void testZoneAsALocation() {\n      assertRegionAndZoneForLocation(ZONE_AP_SOUTHEAST_1A, \"ap-southeast-1\", \"ap-southeast-1a\");\n   }\n\n   @Test\n   public void testRegionAsALocation() {\n      assertRegionAndZoneForLocation(REGION_AP_SOUTHEAST_1, \"ap-southeast-1\", null);\n   }\n\n   // // fixtures\n\n   public static Iterable<NodeMetadata> containsNodeMetadata(final NodeMetadata in) {\n      reportMatcher(new IArgumentMatcher() {\n\n         @Override\n         public void appendTo(StringBuffer buffer) {\n            buffer.append(\"contains(\");\n            buffer.append(in);\n            buffer.append(\")\");\n         }\n\n         @Override\n         public boolean matches(Object arg) {\n            return Iterables.contains((Iterable<?>) arg, in);\n         }\n\n      });\n      return null;\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   private void assertRegionAndZoneForLocation(Location location, String region, String zone) {\n      String imageId = \"ami1\";\n      String instanceCreatedId = \"instance1\";\n      NodeMetadata nodeMetadata = new NodeMetadataBuilder().id(region + \"/\" + instanceCreatedId)\n            .providerId(instanceCreatedId).status(Status.RUNNING).build();\n\n      // setup mocks\n      EC2CreateNodesInGroupThenAddToSet strategy = setupStrategy(nodeMetadata);\n      InputParams input = new InputParams(location);\n      InstanceApi instanceClient = createMock(InstanceApi.class);\n      RunInstancesOptions ec2Options = createMock(RunInstancesOptions.class);\n      RunningInstance instance = createMock(RunningInstance.class);\n      Reservation<? extends RunningInstance> reservation = new Reservation<RunningInstance>(region,\n            ImmutableSet.<String> of(), ImmutableSet.<RunningInstance> of(instance), \"ownerId\", \"requesterId\",\n            \"reservationId\");\n\n      // setup expectations\n      expect(input.template.clone()).andReturn(input.template);\n      expect(strategy.client.getInstanceApi()).andReturn((Optional) Optional.of(instanceClient)).atLeastOnce();\n      expect(\n            strategy.createKeyPairAndSecurityGroupsAsNeededAndReturncustomize\n                  .execute(region, input.tag, input.template)).andReturn(ec2Options);\n      expect(input.template.getLocation()).andReturn(input.location).atLeastOnce();\n      expect(input.template.getImage()).andReturn(input.image).atLeastOnce();\n      expect(input.image.getProviderId()).andReturn(imageId).atLeastOnce();\n      expect(instanceClient.runInstancesInRegion(region, zone, imageId, 1, input.count, ec2Options)).andReturn(\n            Reservation.class.cast(reservation));\n      expect(instance.getId()).andReturn(instanceCreatedId).atLeastOnce();\n      // simulate a lazy credentials fetch\n      LoginCredentials creds = LoginCredentials.builder().user(\"foo\").privateKey(\"bar\").build();\n      expect(strategy.instanceToCredentials.getUnchecked(instance)).andReturn(Optional.of(creds));\n      expect(instance.getRegion()).andReturn(region).atLeastOnce();\n      expect(strategy.credentialStore.put(\"node#\" + region + \"/\" + instanceCreatedId, creds)).andReturn(null);\n\n      expect(strategy.presentInstances.apply(ImmutableSet.of(new RegionAndName(region, instanceCreatedId)))).andReturn(ImmutableSet.of(instance));\n      expect(input.template.getOptions()).andReturn(input.options).atLeastOnce();\n      expect(input.options.getLoginUser()).andReturn(null);\n      expect(input.options.getLoginPassword()).andReturn(null);\n      expect(input.options.getLoginPrivateKey()).andReturn(null);\n      expect(input.options.shouldAuthenticateSudo()).andReturn(null);\n      expect(input.options.getMaxCount()).andReturn(0);\n\n      expect(strategy.runningInstanceToNodeMetadata.apply(instance)).andReturn(nodeMetadata);\n      expect(\n            strategy.utils.customizeNodesAndAddToGoodMapOrPutExceptionIntoBadMap(eq(input.options),\n                  containsNodeMetadata(nodeMetadata), eq(input.nodes), eq(input.badNodes), eq(input.customization)))\n            .andReturn(null);\n\n      // replay mocks\n      replay(instanceClient);\n      replay(ec2Options);\n      replay(instance);\n      input.replayMe();\n      replayStrategy(strategy);\n\n      // run\n      strategy.execute(input.tag, input.count, input.template, input.nodes, input.badNodes, input.customization);\n\n      // verify mocks\n      verify(instanceClient);\n      verify(ec2Options);\n      verify(instance);\n      input.verifyMe();\n      verifyStrategy(strategy);\n   }\n\n   private static final Location REGION_AP_SOUTHEAST_1 = new LocationBuilder().scope(LocationScope.REGION)\n         .id(\"ap-southeast-1\").description(\"ap-southeast-1\")\n         .parent(new LocationBuilder().scope(LocationScope.PROVIDER).id(\"aws-ec2\").description(\"aws-ec2\").build())\n         .build();\n   private static final Location ZONE_AP_SOUTHEAST_1A = new LocationBuilder().scope(LocationScope.ZONE)\n         .id(\"ap-southeast-1a\").description(\"ap-southeast-1a\").parent(REGION_AP_SOUTHEAST_1).build();\n\n   // /////////////////////////////////////////////////////////////////////\n   @SuppressWarnings(\"unchecked\")\n   private static class InputParams {\n      String tag = \"foo\";\n      int count = 1;\n      Template template = createMock(Template.class);\n      Set<NodeMetadata> nodes = createMock(Set.class);\n      Map<NodeMetadata, Exception> badNodes = createMock(Map.class);\n      Multimap<NodeMetadata, CustomizationResponse> customization = createMock(Multimap.class);\n      Hardware hardware = createMock(Hardware.class);\n      Image image = createMock(Image.class);\n      final Location location;\n      EC2TemplateOptions options = createMock(EC2TemplateOptions.class);\n\n      public InputParams(Location location) {\n         this.location = location;\n      }\n\n      void replayMe() {\n         replay(template);\n         replay(hardware);\n         replay(image);\n         replay(nodes);\n         replay(badNodes);\n         replay(customization);\n         replay(options);\n      }\n\n      void verifyMe() {\n         verify(template);\n         verify(hardware);\n         verify(image);\n         verify(nodes);\n         verify(badNodes);\n         verify(customization);\n         verify(options);\n      }\n   }\n\n   private void verifyStrategy(EC2CreateNodesInGroupThenAddToSet strategy) {\n      verify(strategy.createKeyPairAndSecurityGroupsAsNeededAndReturncustomize);\n      verify(strategy.client);\n      verify(strategy.elasticIpCache);\n      verify(strategy.presentInstances);\n      verify(strategy.runningInstanceToNodeMetadata);\n      verify(strategy.instanceToCredentials);\n      verify(strategy.credentialStore);\n      verify(strategy.utils);\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   private EC2CreateNodesInGroupThenAddToSet setupStrategy(final NodeMetadata node) {\n      EC2Api client = createMock(EC2Api.class);\n      CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions createKeyPairAndSecurityGroupsAsNeededAndReturncustomize = createMock(CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class);\n      PresentInstances presentInstances = createMock(PresentInstances.class);\n      RunningInstanceToNodeMetadata runningInstanceToNodeMetadata = createMock(RunningInstanceToNodeMetadata.class);\n      LoadingCache<RunningInstance, Optional<LoginCredentials>> instanceToCredentials = createMock(LoadingCache.class);\n      LoadingCache<RegionAndName, String> elasticIpCache = createMock(LoadingCache.class);\n      GetNodeMetadataStrategy nodeRunning = new GetNodeMetadataStrategy() {\n\n         @Override\n         public NodeMetadata getNode(String input) {\n            Assert.assertEquals(input, node.getId());\n            return node;\n         }\n         \n      };\n      Map<String, Credentials> credentialStore = createMock(Map.class);\n      ComputeUtils utils = createMock(ComputeUtils.class);\n      return new EC2CreateNodesInGroupThenAddToSet(client, elasticIpCache, new AtomicNodeRunning(nodeRunning),\n            createKeyPairAndSecurityGroupsAsNeededAndReturncustomize, presentInstances, runningInstanceToNodeMetadata,\n            instanceToCredentials, credentialStore, utils);\n   }\n\n   private void replayStrategy(EC2CreateNodesInGroupThenAddToSet strategy) {\n      replay(strategy.createKeyPairAndSecurityGroupsAsNeededAndReturncustomize);\n      replay(strategy.client);\n      replay(strategy.elasticIpCache);\n      replay(strategy.presentInstances);\n      replay(strategy.runningInstanceToNodeMetadata);\n      replay(strategy.instanceToCredentials);\n      replay(strategy.credentialStore);\n      replay(strategy.utils);\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/compute/strategy/EC2DestroyNodeStrategyTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.compute.strategy;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.concurrent.ExecutionException;\n\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.strategy.GetNodeMetadataStrategy;\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.features.ElasticIPAddressApi;\nimport org.jclouds.ec2.features.InstanceApi;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\n\n@Test(groups = \"unit\", singleThreaded = true, testName = \"EC2DestroyNodeStrategyTest\")\npublic class EC2DestroyNodeStrategyTest {\n\n   @SuppressWarnings(\"unchecked\")\n   @Test\n   public void testDestroyNodeTerminatesInstanceAndReturnsRefreshedNode() throws Exception {\n      EC2Api client = createMock(EC2Api.class);\n      InstanceApi instanceClient = createMock(InstanceApi.class);\n      GetNodeMetadataStrategy getNode = createMock(GetNodeMetadataStrategy.class);\n      LoadingCache<RegionAndName, String> elasticIpCache = createMock(LoadingCache.class);\n\n      NodeMetadata node = createMock(NodeMetadata.class);\n\n      expect(client.getInstanceApi()).andReturn((Optional) Optional.of(instanceClient)).atLeastOnce();\n      expect(instanceClient.terminateInstancesInRegion(\"region\", \"i-blah\")).andReturn(null);\n      expect(getNode.getNode(\"region/i-blah\")).andReturn(node);\n\n      replay(client);\n      replay(getNode);\n      replay(instanceClient);\n      replay(elasticIpCache);\n\n      EC2DestroyNodeStrategy destroyer = new EC2DestroyNodeStrategy(client, getNode, elasticIpCache);\n\n      assertEquals(destroyer.destroyNode(\"region/i-blah\"), node);\n\n      verify(client);\n      verify(getNode);\n      verify(instanceClient);\n      verify(elasticIpCache);\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Test\n   public void testDestroyNodeDisassociatesAndReleasesIpThenTerminatesInstanceAndReturnsRefreshedNode()\n            throws Exception {\n      EC2Api client = createMock(EC2Api.class);\n      GetNodeMetadataStrategy getNode = createMock(GetNodeMetadataStrategy.class);\n      LoadingCache<RegionAndName, String> elasticIpCache = createMock(LoadingCache.class);\n      ElasticIPAddressApi ipClient = createMock(ElasticIPAddressApi.class);\n      InstanceApi instanceClient = createMock(InstanceApi.class);\n\n      NodeMetadata node = createMock(NodeMetadata.class);\n\n      expect(elasticIpCache.get(new RegionAndName(\"region\", \"i-blah\"))).andReturn(\"1.1.1.1\");\n\n      expect(client.getElasticIPAddressApi()).andReturn((Optional) Optional.of(ipClient)).atLeastOnce();\n      ipClient.disassociateAddressInRegion(\"region\", \"1.1.1.1\");\n      ipClient.releaseAddressInRegion(\"region\", \"1.1.1.1\");\n      elasticIpCache.invalidate(new RegionAndName(\"region\", \"i-blah\"));\n\n\n      expect(client.getInstanceApi()).andReturn((Optional) Optional.of(instanceClient)).atLeastOnce();\n      expect(instanceClient.terminateInstancesInRegion(\"region\", \"i-blah\")).andReturn(null);\n      expect(getNode.getNode(\"region/i-blah\")).andReturn(node);\n\n      replay(client);\n      replay(getNode);\n      replay(elasticIpCache);\n      replay(instanceClient);\n      replay(ipClient);\n\n      EC2DestroyNodeStrategy destroyer = new EC2DestroyNodeStrategy(client, getNode, elasticIpCache);\n      destroyer.autoAllocateElasticIps = true;\n\n      assertEquals(destroyer.destroyNode(\"region/i-blah\"), node);\n\n      verify(client);\n      verify(getNode);\n      verify(elasticIpCache);\n      verify(instanceClient);\n      verify(ipClient);\n   }\n   \n\n   @SuppressWarnings(\"unchecked\")\n   @Test\n   public void testDestroyNodeSafeOnCacheMissThenTerminatesInstanceAndReturnsRefreshedNode()\n            throws Exception {\n      EC2Api client = createMock(EC2Api.class);\n      GetNodeMetadataStrategy getNode = createMock(GetNodeMetadataStrategy.class);\n      LoadingCache<RegionAndName, String> elasticIpCache = createMock(LoadingCache.class);\n      ElasticIPAddressApi ipClient = createMock(ElasticIPAddressApi.class);\n      InstanceApi instanceClient = createMock(InstanceApi.class);\n\n      NodeMetadata node = createMock(NodeMetadata.class);\n\n      expect(elasticIpCache.get(new RegionAndName(\"region\", \"i-blah\"))).andThrow(new CacheLoader.InvalidCacheLoadException(null));\n\n      expect(client.getInstanceApi()).andReturn((Optional) Optional.of(instanceClient)).atLeastOnce();\n      expect(instanceClient.terminateInstancesInRegion(\"region\", \"i-blah\")).andReturn(null);\n      expect(getNode.getNode(\"region/i-blah\")).andReturn(node);\n\n      replay(client);\n      replay(getNode);\n      replay(elasticIpCache);\n      replay(instanceClient);\n      replay(ipClient);\n\n      EC2DestroyNodeStrategy destroyer = new EC2DestroyNodeStrategy(client, getNode, elasticIpCache);\n      destroyer.autoAllocateElasticIps = true;\n\n      assertEquals(destroyer.destroyNode(\"region/i-blah\"), node);\n\n      verify(client);\n      verify(getNode);\n      verify(elasticIpCache);\n      verify(instanceClient);\n      verify(ipClient);\n   }\n   \n\n   @SuppressWarnings(\"unchecked\")\n   @Test\n   public void testDestroyNodeSafeOnCacheExecutionExceptionThenTerminatesInstanceAndReturnsRefreshedNode()\n            throws Exception {\n      EC2Api client = createMock(EC2Api.class);\n      GetNodeMetadataStrategy getNode = createMock(GetNodeMetadataStrategy.class);\n      LoadingCache<RegionAndName, String> elasticIpCache = createMock(LoadingCache.class);\n      ElasticIPAddressApi ipClient = createMock(ElasticIPAddressApi.class);\n      InstanceApi instanceClient = createMock(InstanceApi.class);\n\n      NodeMetadata node = createMock(NodeMetadata.class);\n\n      expect(elasticIpCache.get(new RegionAndName(\"region\", \"i-blah\"))).andThrow(new ExecutionException(null));\n\n      expect(client.getInstanceApi()).andReturn((Optional) Optional.of(instanceClient)).atLeastOnce();\n      expect(instanceClient.terminateInstancesInRegion(\"region\", \"i-blah\")).andReturn(null);\n      expect(getNode.getNode(\"region/i-blah\")).andReturn(node);\n\n      replay(client);\n      replay(getNode);\n      replay(elasticIpCache);\n      replay(instanceClient);\n      replay(ipClient);\n\n      EC2DestroyNodeStrategy destroyer = new EC2DestroyNodeStrategy(client, getNode, elasticIpCache);\n      destroyer.autoAllocateElasticIps = true;\n\n      assertEquals(destroyer.destroyNode(\"region/i-blah\"), node);\n\n      verify(client);\n      verify(getNode);\n      verify(elasticIpCache);\n      verify(instanceClient);\n      verify(ipClient);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/config/EC2HttpApiModuleExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.config;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport org.jclouds.ec2.internal.BaseEC2ApiExpectTest;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.location.Region;\nimport org.jclouds.location.Zone;\nimport org.jclouds.location.functions.RegionToEndpointOrProviderIfNull;\nimport org.jclouds.location.functions.ZoneToEndpoint;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMap.Builder;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Injector;\nimport com.google.inject.Key;\nimport com.google.inject.Module;\nimport com.google.inject.TypeLiteral;\n\n@Test(groups = \"unit\", testName = \"EC2HttpApiModuleExpectTest\")\npublic class EC2HttpApiModuleExpectTest extends BaseEC2ApiExpectTest<Injector> {\n   private Injector injector;\n\n   @BeforeClass\n   @Override\n   protected void setupDefaultRequests() {\n      super.setupDefaultRequests();\n      Builder<HttpRequest, HttpResponse> builder = ImmutableMap.<HttpRequest, HttpResponse> builder();\n      builder.put(describeRegionsRequest, describeRegionsResponse);\n      builder.putAll(describeAvailabilityZonesRequestResponse);\n\n      injector = requestsSendResponses(builder.build());\n   }\n\n   public void testLocationIdAndURIBindings() {\n\n      assertEquals(injector.getInstance(Key.get(new TypeLiteral<Supplier<Set<String>>>() {\n      }, Region.class)).get(), ImmutableSet.<String> of(\"sa-east-1\", \"ap-northeast-1\", \"eu-west-1\", \"us-east-1\",\n            \"us-west-1\", \"us-west-2\", \"ap-southeast-1\"));\n\n      assertEquals(injector.getInstance(Key.get(new TypeLiteral<Supplier<Set<String>>>() {\n      }, Zone.class)).get(), ImmutableSet.<String> of(\"sa-east-1a\", \"sa-east-1b\", \"ap-northeast-1a\", \"ap-northeast-1b\",\n            \"eu-west-1a\", \"eu-west-1b\", \"eu-west-1c\", \"us-east-1a\", \"us-east-1b\", \"us-east-1c\", \"us-east-1d\",\n            \"us-east-1e\", \"us-west-1a\", \"us-west-1b\", \"us-west-1c\", \"us-west-2a\", \"us-west-2b\", \"us-west-2c\",\n            \"ap-southeast-1a\", \"ap-southeast-1b\"));\n\n      Map<String, Supplier<URI>> regionToURISupplier = injector.getInstance(\n            Key.get(new TypeLiteral<Supplier<Map<String, Supplier<URI>>>>() {\n            }, Region.class)).get();\n\n      assertEquals(regionToURISupplier.get(\"sa-east-1\").get(), URI.create(\"https://ec2.sa-east-1.amazonaws.com\"));\n      assertEquals(regionToURISupplier.get(\"ap-northeast-1\").get(),\n            URI.create(\"https://ec2.ap-northeast-1.amazonaws.com\"));\n      assertEquals(regionToURISupplier.get(\"eu-west-1\").get(), URI.create(\"https://ec2.eu-west-1.amazonaws.com\"));\n      assertEquals(regionToURISupplier.get(\"us-east-1\").get(), URI.create(\"https://ec2.us-east-1.amazonaws.com\"));\n      assertEquals(regionToURISupplier.get(\"us-west-1\").get(), URI.create(\"https://ec2.us-west-1.amazonaws.com\"));\n      assertEquals(regionToURISupplier.get(\"us-west-2\").get(), URI.create(\"https://ec2.us-west-2.amazonaws.com\"));\n      assertEquals(regionToURISupplier.get(\"ap-southeast-1\").get(),\n            URI.create(\"https://ec2.ap-southeast-1.amazonaws.com\"));\n\n      Map<String, Supplier<Set<String>>> regionToZoneIdSupplier = injector.getInstance(\n            Key.get(new TypeLiteral<Supplier<Map<String, Supplier<Set<String>>>>>() {\n            }, Zone.class)).get();\n\n      assertEquals(regionToZoneIdSupplier.get(\"sa-east-1\").get(), ImmutableSet.of(\"sa-east-1a\", \"sa-east-1b\"));\n      assertEquals(regionToZoneIdSupplier.get(\"ap-northeast-1\").get(),\n            ImmutableSet.of(\"ap-northeast-1a\", \"ap-northeast-1b\"));\n      assertEquals(regionToZoneIdSupplier.get(\"eu-west-1\").get(),\n            ImmutableSet.of(\"eu-west-1a\", \"eu-west-1b\", \"eu-west-1c\"));\n      assertEquals(regionToZoneIdSupplier.get(\"us-east-1\").get(),\n            ImmutableSet.of(\"us-east-1a\", \"us-east-1b\", \"us-east-1c\", \"us-east-1d\", \"us-east-1e\"));\n      assertEquals(regionToZoneIdSupplier.get(\"us-west-1\").get(),\n            ImmutableSet.of(\"us-west-1a\", \"us-west-1b\", \"us-west-1c\"));\n      assertEquals(regionToZoneIdSupplier.get(\"us-west-2\").get(),\n            ImmutableSet.of(\"us-west-2a\", \"us-west-2b\", \"us-west-2c\"));\n      assertEquals(regionToZoneIdSupplier.get(\"ap-southeast-1\").get(),\n            ImmutableSet.of(\"ap-southeast-1a\", \"ap-southeast-1b\"));\n\n      Map<String, Supplier<URI>> zoneToURISupplier = injector.getInstance(\n            Key.get(new TypeLiteral<Supplier<Map<String, Supplier<URI>>>>() {\n            }, Zone.class)).get();\n\n      assertEquals(zoneToURISupplier.get(\"sa-east-1a\").get(), URI.create(\"https://ec2.sa-east-1.amazonaws.com\"));\n\n      assertEquals(zoneToURISupplier.get(\"ap-northeast-1a\").get(),\n            URI.create(\"https://ec2.ap-northeast-1.amazonaws.com\"));\n\n      assertEquals(zoneToURISupplier.get(\"eu-west-1a\").get(), URI.create(\"https://ec2.eu-west-1.amazonaws.com\"));\n\n      assertEquals(zoneToURISupplier.get(\"us-east-1a\").get(), URI.create(\"https://ec2.us-east-1.amazonaws.com\"));\n\n      assertEquals(zoneToURISupplier.get(\"us-west-1a\").get(), URI.create(\"https://ec2.us-west-1.amazonaws.com\"));\n\n      assertEquals(zoneToURISupplier.get(\"us-west-2a\").get(), URI.create(\"https://ec2.us-west-2.amazonaws.com\"));\n\n      assertEquals(zoneToURISupplier.get(\"ap-southeast-1a\").get(),\n            URI.create(\"https://ec2.ap-southeast-1.amazonaws.com\"));\n\n   }\n\n   public void testZoneToEndpoint() {\n      assertEquals(injector.getInstance(ZoneToEndpoint.class).apply(\"us-west-2a\"),\n            URI.create(\"https://ec2.us-west-2.amazonaws.com\"));\n   }\n   \n   public void testRegionToEndpointOrProviderIfNull() {\n      assertEquals(injector.getInstance(RegionToEndpointOrProviderIfNull.class).apply(\"us-west-2\"),\n            URI.create(\"https://ec2.us-west-2.amazonaws.com\"));\n   }\n   \n   @Override\n   public Injector createClient(Function<HttpRequest, HttpResponse> fn, Module module, Properties props) {\n      return createInjector(fn, module, props);\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/features/AMIApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.features;\n\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.domain.Image;\nimport org.jclouds.ec2.internal.BaseEC2ApiExpectTest;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\", testName = \"AMIApiExpectTest\")\npublic class AMIApiExpectTest extends BaseEC2ApiExpectTest<EC2Api> {\n\n   HttpRequest filter = HttpRequest.builder().method(\"POST\")\n           .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n           .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n           .addFormParam(\"Action\", \"DescribeImages\")\n           .addFormParam(\"Filter.1.Name\", \"owner-id\")\n           .addFormParam(\"Filter.1.Value.1\", \"206029621532\")\n           .addFormParam(\"Signature\", \"BxOCrCYJujtaUqSPagRvv1ki76veVBiKK3yWHvRWgR0=\")\n           .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n           .addFormParam(\"SignatureVersion\", \"2\")\n           .addFormParam(\"Timestamp\", \"2012-04-16T15:54:08.897Z\")\n           .addFormParam(\"Version\", \"2010-08-31\")\n           .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testFilterWhenResponseIs2xx() {\n      HttpResponse filterResponse = HttpResponse.builder().statusCode(200)\n              .payload(payloadFromResourceWithContentType(\"/describe_images.xml\", \"text/xml\")).build();\n\n      EC2Api apiWhenExist = requestsSendResponses(describeRegionsRequest, describeRegionsResponse, filter, filterResponse);\n\n      Image image = getOnlyElement(apiWhenExist.getAMIApi().get().describeImagesInRegionWithFilter(\"us-east-1\",\n              ImmutableMultimap.<String, String>builder()\n                      .put(\"owner-id\", \"206029621532\")\n                      .build()));\n\n      assertEquals(image.getId(), \"ami-be3adfd7\");\n   }\n\n   public void testFilterWhenResponseIs404() {\n      HttpResponse filterResponse = HttpResponse.builder().statusCode(404).build();\n\n      EC2Api apiWhenNotExist = requestsSendResponses(describeRegionsRequest, describeRegionsResponse, filter, filterResponse);\n\n      assertEquals(apiWhenNotExist.getAMIApi().get().describeImagesInRegionWithFilter(\"us-east-1\",\n              ImmutableMultimap.<String, String>builder()\n                      .put(\"owner-id\", \"206029621532\")\n                      .build()),\n              ImmutableSet.of());\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/features/AMIApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.features;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.concat;\nimport static com.google.common.collect.Iterables.getFirst;\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static com.google.common.collect.Sets.newHashSet;\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static org.jclouds.ec2.options.DescribeImagesOptions.Builder.imageIds;\nimport static org.jclouds.ec2.options.RegisterImageBackedByEbsOptions.Builder.addNewBlockDevice;\nimport static org.jclouds.util.Predicates2.retry;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Iterator;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport org.jclouds.aws.AWSResponseException;\nimport org.jclouds.compute.RunNodesException;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.domain.TemplateBuilderSpec;\nimport org.jclouds.compute.internal.BaseComputeServiceContextLiveTest;\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.domain.BlockDevice;\nimport org.jclouds.ec2.domain.Image;\nimport org.jclouds.ec2.domain.Image.ImageType;\nimport org.jclouds.ec2.domain.RootDeviceType;\nimport org.jclouds.ec2.domain.RunningInstance;\nimport org.jclouds.ec2.domain.Snapshot;\nimport org.jclouds.ec2.options.RegisterImageBackedByEbsOptions;\nimport org.jclouds.ec2.predicates.InstanceStateRunning;\nimport org.jclouds.ec2.predicates.SnapshotCompleted;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMultimap;\n\n/**\n * Tests behavior of {@code AMIApi}\n */\n@Test(groups = \"live\", singleThreaded = true)\npublic class AMIApiLiveTest extends BaseComputeServiceContextLiveTest {\n   private TemplateBuilderSpec ebsTemplate;\n\n   public AMIApiLiveTest() {\n      provider = \"ec2\";\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties overrides = super.setupProperties();\n      String ebsSpec = checkNotNull(setIfTestSystemPropertyPresent(overrides, provider + \".ebs-template\"), provider\n            + \".ebs-template\");\n      ebsTemplate = TemplateBuilderSpec.parse(ebsSpec);\n      return overrides;\n   }\n\n   protected EC2Api ec2Api;\n   protected AMIApi client;\n\n   protected Predicate<RunningInstance> runningTester;\n\n   protected Set<String> imagesToDeregister = newHashSet();\n   protected Set<String> snapshotsToDelete = newHashSet();\n   protected String regionId;\n   protected String ebsBackedImageId;\n   protected String ebsBackedImageName = \"jcloudstest1\";\n   protected String imageId;\n\n   @Override\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   public void setupContext() {\n      super.setupContext();\n      ec2Api = view.unwrapApi(EC2Api.class);\n      runningTester = retry(new InstanceStateRunning(ec2Api), 600, 5, SECONDS);\n\n      client = ec2Api.getAMIApi().get();\n      if (ebsTemplate != null) {\n         Template template = view.getComputeService().templateBuilder().from(ebsTemplate).build();\n         regionId = template.getLocation().getId();\n         imageId = template.getImage().getProviderId();\n         for (Image image : client.describeImagesInRegionWithFilter(regionId,\n                 ImmutableMultimap.<String, String>builder()\n                         .put(\"name\", ebsBackedImageName).build())) {\n            if (ebsBackedImageName.equals(image.getName()))\n               client.deregisterImageInRegion(regionId, image.getId());\n         }\n      }\n   }\n\n   public void testDescribeImageNotExists() {\n      assertEquals(client.describeImagesInRegion(null, imageIds(\"ami-cdf819a3\")).size(), 0);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testDescribeImageBadId() {\n      client.describeImagesInRegion(null, imageIds(\"asdaasdsa\"));\n   }\n\n   public void testDescribeImages() {\n      // Just run in the first region - no need to take the time on all of them.\n      String region = getFirst(ec2Api.getConfiguredRegions(), null);\n      assertNotNull(region, \"region should not be null\");\n      Set<? extends Image> allResults = client.describeImagesInRegion(region);\n      assertNotNull(allResults);\n      assertTrue(allResults.size() >= 2);\n      Iterator<? extends Image> iterator = allResults.iterator();\n      String id1 = iterator.next().getId();\n      String id2 = iterator.next().getId();\n      Set<? extends Image> twoResults = client.describeImagesInRegion(region, imageIds(id1, id2));\n      assertNotNull(twoResults);\n      assertEquals(twoResults.size(), 2);\n      iterator = twoResults.iterator();\n      assertEquals(iterator.next().getId(), id1);\n      assertEquals(iterator.next().getId(), id2);\n   }\n\n   @Test\n   public void testDescribeImagesWithFilter() {\n      // Just run in the first region - no need to take the time on all of them.\n      String region = getFirst(ec2Api.getConfiguredRegions(), null);\n      assertNotNull(region, \"region should not be null\");\n      Set<? extends Image> allResults = client.describeImagesInRegion(region);\n      assertNotNull(allResults);\n      assertTrue(allResults.size() >= 2);\n      String id1 = allResults.iterator().next().getId();\n      Set<? extends Image> filterResult = client.describeImagesInRegionWithFilter(region,\n              ImmutableMultimap.<String, String>builder()\n                      .put(\"image-id\", id1)\n                      .build());\n      assertNotNull(filterResult);\n      assertEquals(filterResult.size(), 1);\n      assertEquals(filterResult.iterator().next().getId(), id1);\n   }\n\n   @Test(expectedExceptions = AWSResponseException.class)\n   public void testDescribeImagesWithInvalidFilter() {\n      // Just run in the first region - no need to take the time on all of them.\n      String region = getFirst(ec2Api.getConfiguredRegions(), null);\n      assertNotNull(region, \"region should not be null\");\n\n      Set<? extends Image> allResults = client.describeImagesInRegion(region);\n      assertNotNull(allResults);\n      assertTrue(allResults.size() >= 2);\n      String id1 = allResults.iterator().next().getId();\n      Set<? extends Image> filterResult = client.describeImagesInRegionWithFilter(region,\n              ImmutableMultimap.<String, String>builder()\n                      .put(\"invalid-filter-id\", id1)\n                      .build());\n      assertNotNull(filterResult);\n      assertEquals(filterResult.size(), 1);\n      assertEquals(filterResult.iterator().next().getId(), id1);\n   }\n\n   @Test\n   public void testCreateAndListEBSBackedImage() throws Exception {\n      Snapshot snapshot = createSnapshot();\n\n      // List of images before...\n      int sizeBefore = client.describeImagesInRegionWithFilter(regionId,\n              ImmutableMultimap.<String, String>builder()\n                      .put(\"name\", ebsBackedImageName).build()).size();\n\n      // Register a new image...\n      ebsBackedImageId = client.registerUnixImageBackedByEbsInRegion(regionId, ebsBackedImageName, snapshot.getId(),\n              newBlockDeviceOption());\n      imagesToDeregister.add(ebsBackedImageId);\n      final Image ebsBackedImage = getOnlyElement(client.describeImagesInRegion(regionId, imageIds(ebsBackedImageId)));\n      assertEquals(ebsBackedImage.getName(), ebsBackedImageName);\n      assertEquals(ebsBackedImage.getImageType(), ImageType.MACHINE);\n      assertEquals(ebsBackedImage.getRootDeviceType(), RootDeviceType.EBS);\n      assertEquals(ebsBackedImage.getRootDeviceName(), \"/dev/sda1\");\n      assertEquals(ebsBackedImage.getDescription(), \"adrian\");\n      assertEquals(\n            ebsBackedImage.getEbsBlockDevices().entrySet(),\n            ImmutableMap.of(\"/dev/sda1\", new Image.EbsBlockDevice(snapshot.getId(), snapshot.getVolumeSize(), true, null, null, false),\n                  \"/dev/sda2\", newBlockDeviceInfo()).entrySet());\n\n      int describeCount = 0;\n      int after = 0;\n\n      // This loop is in here to deal with a lag between image creation and it showing up in filtered describeImage queries.\n      while (describeCount < 10 && after == 0) {\n         describeCount++;\n         Thread.sleep(30000);\n         // List of images after - should be one larger than before\n         after = client.describeImagesInRegionWithFilter(regionId,\n                 ImmutableMultimap.<String, String>builder()\n                         .put(\"name\", ebsBackedImageName).build()).size();\n      }\n      assertEquals(after, sizeBefore + 1);\n   }\n\n   protected RegisterImageBackedByEbsOptions newBlockDeviceOption() {\n      return addNewBlockDevice(\"/dev/sda2\", \"myvirtual\", 5, false, null, null, false).withDescription(\"adrian\");\n   }\n\n   protected Image.EbsBlockDevice newBlockDeviceInfo() {\n      return new Image.EbsBlockDevice(null, 5, false, null, null, false);\n   }\n\n   // Fires up an instance, finds its root volume ID, takes a snapshot, then\n   // terminates the instance.\n   protected Snapshot createSnapshot() throws RunNodesException {\n\n      String instanceId = null;\n      try {\n         RunningInstance instance = getOnlyElement(concat(ec2Api.getInstanceApi().get().runInstancesInRegion(\n               regionId, null, imageId, 1, 1)));\n         instanceId = instance.getId();\n         \n         assertTrue(runningTester.apply(instance), instanceId + \"didn't achieve the state running!\");\n\n         instance = getOnlyElement(concat(ec2Api.getInstanceApi().get().describeInstancesInRegion(regionId,\n               instanceId)));\n         BlockDevice device = instance.getEbsBlockDevices().get(\"/dev/sda1\");\n         assertNotNull(device, \"device: /dev/sda1 not present on: \" + instance);\n         Snapshot snapshot = ec2Api.getElasticBlockStoreApi().get().createSnapshotInRegion(regionId,\n               device.getVolumeId());\n         snapshotsToDelete.add(snapshot.getId());\n         Predicate<Snapshot> snapshotted = retry(new SnapshotCompleted(ec2Api.getElasticBlockStoreApi().get()), 600, 10, SECONDS);\n         assert snapshotted.apply(snapshot);\n         return snapshot;\n      } finally {\n         if (instanceId != null)\n            ec2Api.getInstanceApi().get().terminateInstancesInRegion(regionId, instanceId);\n      }\n   }\n\n   @Test(dependsOnMethods = \"testCreateAndListEBSBackedImage\")\n   public void testGetLaunchPermissionForImage() {\n      client.getLaunchPermissionForImageInRegion(regionId, ebsBackedImageId);\n   }\n\n   @Override\n   @AfterClass(groups = { \"integration\", \"live\" })\n   protected void tearDownContext() {\n      for (String imageId : imagesToDeregister)\n         client.deregisterImageInRegion(regionId, imageId);\n      for (String snapshotId : snapshotsToDelete)\n         ec2Api.getElasticBlockStoreApi().get().deleteSnapshotInRegion(regionId, snapshotId);\n      super.tearDownContext();\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/features/AMIApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.features;\n\nimport static org.jclouds.ec2.options.DescribeImagesOptions.Builder.executableBy;\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport java.io.IOException;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.ec2.options.CreateImageOptions;\nimport org.jclouds.ec2.options.DescribeImagesOptions;\nimport org.jclouds.ec2.options.RegisterImageBackedByEbsOptions;\nimport org.jclouds.ec2.options.RegisterImageOptions;\nimport org.jclouds.ec2.xml.BlockDeviceMappingHandler;\nimport org.jclouds.ec2.xml.DescribeImagesResponseHandler;\nimport org.jclouds.ec2.xml.ImageIdHandler;\nimport org.jclouds.ec2.xml.PermissionHandler;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.http.functions.ReleasePayloadAndReturn;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Lists;\nimport com.google.common.reflect.Invokable;\n/**\n * Tests behavior of {@code AMIApi}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"AMIApiTest\")\npublic class AMIApiTest extends BaseEC2ApiTest<AMIApi> {\n\n   HttpRequest createImage = HttpRequest.builder().method(\"POST\")\n                                        .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                                        .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                                        .addFormParam(\"Action\", \"CreateImage\")\n                                        .addFormParam(\"InstanceId\", \"instanceId\")\n                                        .addFormParam(\"Name\", \"name\")\n                                        .addFormParam(\"Signature\", \"MuMtOMs697BLVks2RUZUNeLdVCo6NXPHuDhh0nmNtvc=\")\n                                        .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n                                        .addFormParam(\"SignatureVersion\", \"2\")\n                                        .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n                                        .addFormParam(\"Version\", \"2010-08-31\")\n                                        .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testCreateImage() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AMIApi.class, \"createImageInRegion\", String.class, String.class, String.class,\n               CreateImageOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"name\", \"instanceId\"));\n\n      request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);\n      \n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, createImage.getPayload().getRawContent().toString(),\n            \"application/x-www-form-urlencoded\", false);\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, ImageIdHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   HttpRequest createImageOptions = HttpRequest.builder().method(\"POST\")\n                                               .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                                               .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                                               .addFormParam(\"Action\", \"CreateImage\")\n                                               .addFormParam(\"Description\", \"description\")\n                                               .addFormParam(\"InstanceId\", \"instanceId\")\n                                               .addFormParam(\"Name\", \"name\")\n                                               .addFormParam(\"NoReboot\", \"true\")\n                                               .addFormParam(\"Signature\", \"8SgbaWihxOICMXDLvwk3ahy/99nhZvTvbno+8dMyvJg=\")\n                                               .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n                                               .addFormParam(\"SignatureVersion\", \"2\")\n                                               .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n                                               .addFormParam(\"Version\", \"2010-08-31\")\n                                               .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testCreateImageOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AMIApi.class, \"createImageInRegion\", String.class, String.class, String.class,\n               CreateImageOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"name\", \"instanceId\", new CreateImageOptions()\n               .withDescription(\"description\").noReboot()));\n\n      request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);\n      \n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, createImageOptions.getPayload().getRawContent().toString(),\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, ImageIdHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   HttpRequest describeImages = HttpRequest.builder().method(\"POST\")\n                                           .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                                           .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                                           .addFormParam(\"Action\", \"DescribeImages\")\n                                           .addFormParam(\"Signature\", \"hQxNAaRVX6OvXV0IKgx1vV0FoNbRyuHQ2fhRhaPJnS8=\")\n                                           .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n                                           .addFormParam(\"SignatureVersion\", \"2\")\n                                           .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n                                           .addFormParam(\"Version\", \"2010-08-31\")\n                                           .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testDescribeImages() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AMIApi.class, \"describeImagesInRegion\", String.class,\n               DescribeImagesOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList((String) null));\n\n      request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);\n      \n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, describeImages.getPayload().getRawContent().toString(),\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, DescribeImagesResponseHandler.class);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(request);\n   }\n\n   HttpRequest describeImagesOptions = HttpRequest.builder().method(\"POST\")\n                                                  .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                                                  .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                                                  .addFormParam(\"Action\", \"DescribeImages\")\n                                                  .addFormParam(\"ExecutableBy\", \"me\")\n                                                  .addFormParam(\"ImageId.1\", \"1\")\n                                                  .addFormParam(\"ImageId.2\", \"2\")\n                                                  .addFormParam(\"Owner.1\", \"fred\")\n                                                  .addFormParam(\"Owner.2\", \"nancy\")\n                                                  .addFormParam(\"Signature\", \"cIft3g1fwMu52NgB0En9NtHyXjVhmeSx7TBP7YR+TvI=\")\n                                                  .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n                                                  .addFormParam(\"SignatureVersion\", \"2\")\n                                                  .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n                                                  .addFormParam(\"Version\", \"2010-08-31\")\n                                                  .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testDescribeImagesOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AMIApi.class, \"describeImagesInRegion\", String.class,\n               DescribeImagesOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, executableBy(\"me\").ownedBy(\"fred\", \"nancy\").imageIds(\n               \"1\", \"2\")));\n\n      request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);\n      \n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, describeImagesOptions.getPayload().getRawContent().toString(),\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, DescribeImagesResponseHandler.class);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(request);\n   }\n\n   HttpRequest deregisterImage = HttpRequest.builder().method(\"POST\")\n                                            .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                                            .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                                            .addFormParam(\"Action\", \"DeregisterImage\")\n                                            .addFormParam(\"ImageId\", \"imageId\")\n                                            .addFormParam(\"Signature\", \"tm6nGoPPJh7xt5TSdV5Ov0DJvcGTAW+YSfXL7j+TkOA=\")\n                                            .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n                                            .addFormParam(\"SignatureVersion\", \"2\")\n                                            .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n                                            .addFormParam(\"Version\", \"2010-08-31\")\n                                            .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testDeregisterImage() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AMIApi.class, \"deregisterImageInRegion\", String.class, String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"imageId\"));\n\n      request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);\n      \n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, deregisterImage.getPayload().getRawContent().toString(),\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   HttpRequest registerImageFromManifest = HttpRequest.builder().method(\"POST\")\n                                                      .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                                                      .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                                                      .addFormParam(\"Action\", \"RegisterImage\")\n                                                      .addFormParam(\"ImageLocation\", \"pathToManifest\")\n                                                      .addFormParam(\"Name\", \"name\")\n                                                      .addFormParam(\"Signature\", \"Ie7k7w4Bdki3uCGeSFGdJ5EKrp/ohkHvWwivbIaVLEM=\")\n                                                      .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n                                                      .addFormParam(\"SignatureVersion\", \"2\")\n                                                      .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n                                                      .addFormParam(\"Version\", \"2010-08-31\")\n                                                      .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testRegisterImageFromManifest() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AMIApi.class, \"registerImageFromManifestInRegion\", String.class, String.class,\n               String.class, RegisterImageOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"name\", \"pathToManifest\"));\n\n      request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);\n      \n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, registerImageFromManifest.getPayload().getRawContent().toString(),\n            \"application/x-www-form-urlencoded\", false);\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, ImageIdHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   HttpRequest registerImageFromManifestOptions = HttpRequest.builder().method(\"POST\")\n                                                             .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                                                             .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                                                             .addFormParam(\"Action\", \"RegisterImage\")\n                                                             .addFormParam(\"Description\", \"description\")\n                                                             .addFormParam(\"ImageLocation\", \"pathToManifest\")\n                                                             .addFormParam(\"Name\", \"name\")\n                                                             .addFormParam(\"Signature\", \"ilWV1eAWW6kTK/jHliQ+IkzJR4DRNy4ye+SKtnUjjDs=\")\n                                                             .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n                                                             .addFormParam(\"SignatureVersion\", \"2\")\n                                                             .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n                                                             .addFormParam(\"Version\", \"2010-08-31\")\n                                                             .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testRegisterImageFromManifestOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AMIApi.class, \"registerImageFromManifestInRegion\", String.class, String.class,\n               String.class, RegisterImageOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"name\", \"pathToManifest\", new RegisterImageOptions()\n               .withDescription(\"description\")));\n\n      request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);\n      \n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, registerImageFromManifestOptions.getPayload().getRawContent().toString(),\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, ImageIdHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   HttpRequest registerImageBackedByEBS = HttpRequest.builder().method(\"POST\")\n                                                     .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                                                     .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                                                     .addFormParam(\"Action\", \"RegisterImage\")\n                                                     .addFormParam(\"BlockDeviceMapping.0.DeviceName\", \"/dev/sda1\")\n                                                     .addFormParam(\"BlockDeviceMapping.0.Ebs.SnapshotId\", \"snapshotId\")\n                                                     .addFormParam(\"Name\", \"imageName\")\n                                                     .addFormParam(\"RootDeviceName\", \"/dev/sda1\")\n                                                     .addFormParam(\"Signature\", \"ZbZcY6uwxPbD65jFmiNZXoWeHY/2zqRuGuDmTfkt84A=\")\n                                                     .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n                                                     .addFormParam(\"SignatureVersion\", \"2\")\n                                                     .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n                                                     .addFormParam(\"Version\", \"2010-08-31\")\n                                                     .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testRegisterImageBackedByEBS() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AMIApi.class, \"registerUnixImageBackedByEbsInRegion\", String.class,\n               String.class, String.class, RegisterImageBackedByEbsOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"imageName\", \"snapshotId\"));\n\n      request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);\n      \n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, registerImageBackedByEBS.getPayload().getRawContent().toString(),\n            \"application/x-www-form-urlencoded\", false);\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, ImageIdHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   HttpRequest registerImageBackedByEBSOptions = HttpRequest.builder().method(\"POST\")\n                                                            .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                                                            .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                                                            .addFormParam(\"Action\", \"RegisterImage\")\n                                                            .addFormParam(\"BlockDeviceMapping.0.DeviceName\", \"/dev/sda1\")\n                                                            .addFormParam(\"BlockDeviceMapping.0.Ebs.SnapshotId\", \"snapshotId\")\n                                                            .addFormParam(\"BlockDeviceMapping.1.DeviceName\", \"/dev/device\")\n                                                            .addFormParam(\"BlockDeviceMapping.1.Ebs.DeleteOnTermination\", \"false\")\n                                                            .addFormParam(\"BlockDeviceMapping.1.Ebs.SnapshotId\", \"snapshot\")\n                                                            .addFormParam(\"BlockDeviceMapping.2.DeviceName\", \"/dev/newdevice\")\n                                                            .addFormParam(\"BlockDeviceMapping.2.Ebs.DeleteOnTermination\", \"false\")\n                                                            .addFormParam(\"BlockDeviceMapping.2.Ebs.VolumeSize\", \"100\")\n                                                            .addFormParam(\"BlockDeviceMapping.2.VirtualName\", \"newblock\")\n                                                            .addFormParam(\"Description\", \"description\")\n                                                            .addFormParam(\"Name\", \"imageName\")\n                                                            .addFormParam(\"RootDeviceName\", \"/dev/sda1\")\n                                                            .addFormParam(\"Signature\", \"DrNujyZMGrKvuw73A7ObFTThXvc/MRfNqjvIy8gey5g=\")\n                                                            .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n                                                            .addFormParam(\"SignatureVersion\", \"2\")\n                                                            .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n                                                            .addFormParam(\"Version\", \"2010-08-31\")\n                                                            .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testRegisterImageBackedByEBSOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AMIApi.class, \"registerUnixImageBackedByEbsInRegion\", String.class,\n               String.class, String.class, RegisterImageBackedByEbsOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"imageName\", \"snapshotId\",\n               new RegisterImageBackedByEbsOptions().withDescription(\"description\").addBlockDeviceFromSnapshot(\n                        \"/dev/device\", null, \"snapshot\").addNewBlockDevice(\"/dev/newdevice\", \"newblock\", 100)));\n\n      request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);\n      \n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, registerImageBackedByEBSOptions.getPayload().getRawContent().toString(),\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, ImageIdHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   HttpRequest getBlockDeviceMappingsForImage = HttpRequest.builder().method(\"POST\")\n                                                           .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                                                           .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                                                           .addFormParam(\"Action\", \"DescribeImageAttribute\")\n                                                           .addFormParam(\"Attribute\", \"blockDeviceMapping\")\n                                                           .addFormParam(\"ImageId\", \"imageId\")\n                                                           .addFormParam(\"Signature\", \"MJCIc1roG+nIWxRSUqV9KP9Wc4AWuuiNkxeDSih5/mI=\")\n                                                           .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n                                                           .addFormParam(\"SignatureVersion\", \"2\")\n                                                           .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n                                                           .addFormParam(\"Version\", \"2010-08-31\")\n                                                           .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testGetBlockDeviceMappingsForImage() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AMIApi.class, \"getBlockDeviceMappingsForImageInRegion\", String.class,\n               String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"imageId\"));\n\n      request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);\n      \n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, getBlockDeviceMappingsForImage.getPayload().getRawContent().toString(),\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, BlockDeviceMappingHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   HttpRequest getLaunchPermissionForImage = HttpRequest.builder().method(\"POST\")\n                                                        .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                                                        .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                                                        .addFormParam(\"Action\", \"DescribeImageAttribute\")\n                                                        .addFormParam(\"Attribute\", \"launchPermission\")\n                                                        .addFormParam(\"ImageId\", \"imageId\")\n                                                        .addFormParam(\"Signature\", \"iN7JbsAhM1NAES3o+Ow8BaaFJ+1g9imBjcU4mFCyrxM=\")\n                                                        .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n                                                        .addFormParam(\"SignatureVersion\", \"2\")\n                                                        .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n                                                        .addFormParam(\"Version\", \"2010-08-31\")\n                                                        .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testGetLaunchPermissionForImage() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AMIApi.class, \"getLaunchPermissionForImageInRegion\", String.class, String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"imageId\"));\n\n      request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);\n      \n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, getLaunchPermissionForImage.getPayload().getRawContent().toString(),\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, PermissionHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   HttpRequest addLaunchPermission = HttpRequest.builder().method(\"POST\")\n                                                          .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                                                          .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                                                          .addFormParam(\"Action\", \"ModifyImageAttribute\")\n                                                          .addFormParam(\"Attribute\", \"launchPermission\")\n                                                          .addFormParam(\"ImageId\", \"imageId\")\n                                                          .addFormParam(\"OperationType\", \"add\")\n                                                          .addFormParam(\"Signature\", \"ZuMuzW/iQDRURhUJaBzvoAdNJrE454y6X0jM24lcxxk=\")\n                                                          .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n                                                          .addFormParam(\"SignatureVersion\", \"2\")\n                                                          .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n                                                          .addFormParam(\"UserGroup.1\", \"all\")\n                                                          .addFormParam(\"UserId.1\", \"bob\")\n                                                          .addFormParam(\"UserId.2\", \"sue\")\n                                                          .addFormParam(\"Version\", \"2010-08-31\")\n                                                          .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testAddLaunchPermissionsToImage() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AMIApi.class, \"addLaunchPermissionsToImageInRegion\", String.class,\n               Iterable.class, Iterable.class, String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, ImmutableList.of(\"bob\", \"sue\"), ImmutableList\n               .of(\"all\"), \"imageId\"));\n\n      request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);\n      \n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, addLaunchPermission.getPayload().getRawContent().toString(),\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   HttpRequest removeLaunchPermission = HttpRequest.builder().method(\"POST\")\n                                                   .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                                                   .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                                                   .addFormParam(\"Action\", \"ModifyImageAttribute\")\n                                                   .addFormParam(\"Attribute\", \"launchPermission\")\n                                                   .addFormParam(\"ImageId\", \"imageId\")\n                                                   .addFormParam(\"OperationType\", \"remove\")\n                                                   .addFormParam(\"Signature\", \"HreSEawbVaUp/UMicCJbhrx+moX01f2pEphJCPz8/5g=\")\n                                                   .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n                                                   .addFormParam(\"SignatureVersion\", \"2\")\n                                                   .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n                                                   .addFormParam(\"UserGroup.1\", \"all\")\n                                                   .addFormParam(\"UserId.1\", \"bob\")\n                                                   .addFormParam(\"UserId.2\", \"sue\")\n                                                   .addFormParam(\"Version\", \"2010-08-31\")\n                                                   .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testRemoveLaunchPermissionsFromImage() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AMIApi.class, \"removeLaunchPermissionsFromImageInRegion\", String.class,\n               Iterable.class, Iterable.class, String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, ImmutableList.of(\"bob\", \"sue\"), ImmutableList\n               .of(\"all\"), \"imageId\"));\n\n      request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);\n      \n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, removeLaunchPermission.getPayload().getRawContent().toString(),\n            \"application/x-www-form-urlencoded\", false);\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   HttpRequest resetLaunchPermissionsOnImage = HttpRequest.builder().method(\"POST\")\n                                                          .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                                                          .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                                                          .addFormParam(\"Action\", \"ResetImageAttribute\")\n                                                          .addFormParam(\"Attribute\", \"launchPermission\")\n                                                          .addFormParam(\"ImageId\", \"imageId\")\n                                                          .addFormParam(\"Signature\", \"fVCR9aGYvNX/Jt1/uqBGcUQRLrHwxtcvmNYKzpul1P4=\")\n                                                          .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n                                                          .addFormParam(\"SignatureVersion\", \"2\")\n                                                          .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n                                                          .addFormParam(\"Version\", \"2010-08-31\")\n                                                          .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testResetLaunchPermissionsOnImage() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AMIApi.class, \"resetLaunchPermissionsOnImageInRegion\", String.class,\n               String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"imageId\"));\n\n      request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);\n      \n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, resetLaunchPermissionsOnImage.getPayload().getRawContent().toString(),\n            \"application/x-www-form-urlencoded\", false);\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/features/AvailabilityZoneAndRegionApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.features;\n\nimport static org.jclouds.ec2.options.DescribeAvailabilityZonesOptions.Builder.availabilityZones;\nimport static org.jclouds.ec2.options.DescribeRegionsOptions.Builder.regions;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.net.URI;\nimport java.util.Iterator;\nimport java.util.Map.Entry;\nimport java.util.Set;\nimport java.util.SortedMap;\n\nimport org.jclouds.compute.internal.BaseComputeServiceContextLiveTest;\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.domain.AvailabilityZoneInfo;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Maps;\n\n/**\n * Tests behavior of {@code AvailabilityZoneAndRegionApi}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"AvailabilityZoneAndRegionApiLiveTest\")\npublic class AvailabilityZoneAndRegionApiLiveTest extends BaseComputeServiceContextLiveTest {\n   public AvailabilityZoneAndRegionApiLiveTest() {\n      provider = \"ec2\";\n   }\n   \n   private EC2Api ec2Api;\n   private AvailabilityZoneAndRegionApi client;\n\n   @Override\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   public void setupContext() {\n      super.setupContext();\n      ec2Api = view.unwrapApi(EC2Api.class);\n      client = ec2Api.getAvailabilityZoneAndRegionApi().get();\n   }\n\n   public void testDescribeAvailabilityZones() {\n      for (String region : ec2Api.getConfiguredRegions()) {\n         Set<AvailabilityZoneInfo> allResults = client.describeAvailabilityZonesInRegion(region);\n         assertNotNull(allResults);\n         assert !allResults.isEmpty() : allResults.size();\n         Iterator<AvailabilityZoneInfo> iterator = allResults.iterator();\n         String id1 = iterator.next().getZone();\n         Set<AvailabilityZoneInfo> oneResult = client.describeAvailabilityZonesInRegion(region,\n               availabilityZones(id1));\n         assertNotNull(oneResult);\n         assertEquals(oneResult.size(), 1);\n         iterator = allResults.iterator();\n         assertEquals(iterator.next().getZone(), id1);\n      }\n   }\n\n   public void testDescribeRegions() {\n      SortedMap<String, URI> allResults = Maps.newTreeMap();\n      allResults.putAll(client.describeRegions());\n      assertNotNull(allResults);\n      assert !allResults.isEmpty() : allResults.size();\n      Iterator<Entry<String, URI>> iterator = allResults.entrySet().iterator();\n      String r1 = iterator.next().getKey();\n      SortedMap<String, URI> oneResult = Maps.newTreeMap();\n      oneResult.putAll(client.describeRegions(regions(r1)));\n      assertNotNull(oneResult);\n      assertEquals(oneResult.size(), 1);\n      iterator = oneResult.entrySet().iterator();\n      assertEquals(iterator.next().getKey(), r1);\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/features/AvailabilityZoneAndRegionApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.features;\n\nimport static org.jclouds.ec2.options.DescribeAvailabilityZonesOptions.Builder.availabilityZones;\nimport static org.jclouds.ec2.options.DescribeRegionsOptions.Builder.regions;\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport java.io.IOException;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.aws.domain.Region;\nimport org.jclouds.ec2.options.DescribeAvailabilityZonesOptions;\nimport org.jclouds.ec2.options.DescribeRegionsOptions;\nimport org.jclouds.ec2.xml.DescribeAvailabilityZonesResponseHandler;\nimport org.jclouds.ec2.xml.DescribeRegionsResponseHandler;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.reflect.Invokable;\n/**\n * Tests behavior of {@code AvailabilityZoneAndRegionApi}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"AvailabilityZoneAndRegionApiTest\")\npublic class AvailabilityZoneAndRegionApiTest extends\n      BaseEC2ApiTest<AvailabilityZoneAndRegionApi> {\n\n   public void testDescribeAvailabilityZones() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AvailabilityZoneAndRegionApi.class, \"describeAvailabilityZonesInRegion\",\n            String.class, DescribeAvailabilityZonesOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(Region.US_WEST_1));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-west-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-west-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, \"Action=DescribeAvailabilityZones\",\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, DescribeAvailabilityZonesResponseHandler.class);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(request);\n   }\n\n   public void testDescribeAvailabilityZonesOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AvailabilityZoneAndRegionApi.class, \"describeAvailabilityZonesInRegion\",\n            String.class, DescribeAvailabilityZonesOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"us-east-1\", availabilityZones(\"us-east-1a\", \"us-east-1b\")));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request,\n            \"Action=DescribeAvailabilityZones&ZoneName.1=us-east-1a&ZoneName.2=us-east-1b\",\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, DescribeAvailabilityZonesResponseHandler.class);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(request);\n   }\n\n   public void testDescribeRegions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AvailabilityZoneAndRegionApi.class, \"describeRegions\",\n            DescribeRegionsOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, \"Action=DescribeRegions\", \"application/x-www-form-urlencoded\",\n            false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, DescribeRegionsResponseHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testDescribeRegionsOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AvailabilityZoneAndRegionApi.class, \"describeRegions\",\n            DescribeRegionsOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(regions(Region.US_EAST_1, Region.US_WEST_1)));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request,\n            \"Action=DescribeRegions&RegionName.1=us-east-1&RegionName.2=us-west-1\",\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, DescribeRegionsResponseHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/features/BaseEC2ApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.features;\n\nimport static com.google.common.collect.Maps.transformValues;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.net.URI;\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.aws.domain.Region;\nimport org.jclouds.aws.filters.FormSigner.FormSignerV2;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.date.DateService;\nimport org.jclouds.ec2.EC2ApiMetadata;\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.config.BaseEC2HttpApiModule;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.location.config.LocationModule;\nimport org.jclouds.location.suppliers.RegionIdToURISupplier;\nimport org.jclouds.location.suppliers.RegionIdToZoneIdsSupplier;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.internal.BaseRestAnnotationProcessingTest;\nimport org.jclouds.util.Suppliers2;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\nimport com.google.inject.Provides;\n\n@Test(groups = \"unit\")\npublic abstract class BaseEC2ApiTest<T> extends BaseRestAnnotationProcessingTest<T> {\n   @ConfiguresHttpApi\n   protected static class StubEC2HttpApiModule extends BaseEC2HttpApiModule<EC2Api> {\n\n      protected StubEC2HttpApiModule() {\n         super(EC2Api.class);\n      }\n\n      @Provides\n      @Singleton\n      LoadingCache<RegionAndName, Image> provide() {\n         return CacheBuilder.newBuilder().build(new CacheLoader<RegionAndName, Image>() {\n\n            @Override\n            public Image load(RegionAndName key) throws Exception {\n               return null;\n            }\n\n         });\n      }\n      \n      @Override\n      protected String provideTimeStamp(DateService dateService) {\n         return \"2009-11-08T15:54:08.897Z\";\n      }\n\n      static class Zones implements jakarta.inject.Provider<Map<String, String>> {\n         @Override\n         public Map<String, String> get() {\n            return ImmutableMap.<String, String> of(\"us-east-1a\", \"us-east-1\");\n         }\n      }\n\n      @Override\n      protected void installLocations() {\n         install(new LocationModule());\n         bind(RegionIdToURISupplier.class).toInstance(new RegionIdToURISupplier() {\n\n            @Override\n            public Map<String, Supplier<URI>> get() {\n               return transformValues(ImmutableMap.<String, URI> of(Region.EU_WEST_1, URI\n                        .create(\"https://ec2.eu-west-1.amazonaws.com\"), Region.US_EAST_1, URI\n                        .create(\"https://ec2.us-east-1.amazonaws.com\"), Region.US_WEST_1, URI\n                        .create(\"https://ec2.us-west-1.amazonaws.com\")), Suppliers2.<URI> ofInstanceFunction());\n            }\n\n         });\n         bind(RegionIdToZoneIdsSupplier.class).toInstance(new RegionIdToZoneIdsSupplier() {\n\n            @Override\n            public Map<String, Supplier<Set<String>>> get() {\n               return transformValues(ImmutableMap.<String, Set<String>> of(\"us-east-1\", ImmutableSet.of(\n                        \"us-east-1a\", \"us-east-1b\", \"us-east-1c\", \"us-east-1b\")), Suppliers2\n                        .<Set<String>> ofInstanceFunction());\n            }\n\n         });\n      }\n   }\n\n   protected FormSignerV2 filter;\n\n   @Override\n   protected void checkFilters(HttpRequest request) {\n      assertEquals(request.getFilters().size(), 1);\n      assertEquals(request.getFilters().get(0).getClass(), FormSignerV2.class);\n   }\n\n   @Override\n   @BeforeTest\n   protected void setupFactory() throws IOException {\n      super.setupFactory();\n      this.filter = injector.getInstance(FormSignerV2.class);\n   }\n\n   @Override\n   protected Module createModule() {\n      return new StubEC2HttpApiModule();\n   }\n   \n   @Override\n   protected ApiMetadata createApiMetadata() {\n      return new EC2ApiMetadata();\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/features/EC2ElasticBlockStoreApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.features;\n\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.domain.Snapshot;\nimport org.jclouds.ec2.domain.Volume;\nimport org.jclouds.ec2.internal.BaseEC2ApiExpectTest;\nimport org.jclouds.ec2.options.CreateVolumeOptions;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMap.Builder;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\", testName = \"EC2ElasticBlockStoreApiExpectTest\")\npublic class EC2ElasticBlockStoreApiExpectTest extends BaseEC2ApiExpectTest<EC2Api> {\n   Volume creating = Volume.builder()\n           .id(\"vol-2a21e543\")\n           .status(Volume.Status.CREATING)\n           .availabilityZone(\"us-east-1a\")\n           .region(\"us-east-1\")\n           .id(\"vol-2a21e543\")\n           .volumeType(\"standard\")\n           .iops(0)\n           .size(1)\n           .createTime(dateService.iso8601DateParse(\"2009-12-28T05:42:53.000Z\"))\n           .build();\n   \n   public void testCreateVolumeInAvailabilityZone() {\n      Builder<HttpRequest, HttpResponse> builder = ImmutableMap.<HttpRequest, HttpResponse>builder();\n      builder.put(describeRegionsRequest, describeRegionsResponse);\n      builder.putAll(describeAvailabilityZonesRequestResponse);\n      builder.put(\n            HttpRequest.builder()\n                       .method(\"POST\")\n                       .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                       .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                       .payload(payloadFromStringWithContentType(\"Action=CreateVolume\" +\n                             \"&AvailabilityZone=us-east-1a\" +\n                             \"&Signature=NCu8HU8u0A385rTgj%2BN5lq606jkc1eu88jof9yAxb6s%3D\" +\n                             \"&SignatureMethod=HmacSHA256\" +\n                             \"&SignatureVersion=2\" +\n                             \"&Size=4\" +\n                             \"&Timestamp=2012-04-16T15%3A54%3A08.897Z\" +\n                             \"&Version=2010-08-31\" +\n                             \"&AWSAccessKeyId=identity\",\n                             \"application/x-www-form-urlencoded\")).build(),\n            HttpResponse.builder()\n                        .statusCode(200)\n                        .payload(payloadFromResource(\"/created_volume.xml\")).build());\n      \n      ElasticBlockStoreApi client = requestsSendResponses(builder.build()).getElasticBlockStoreApi().get();\n\n      assertEquals(client.createVolumeInAvailabilityZone(\"us-east-1a\", 4), creating);\n   }\n\n   public void testCreateVolumeInAvailabilityZoneWithOptions() {\n      Builder<HttpRequest, HttpResponse> builder = ImmutableMap.<HttpRequest, HttpResponse>builder();\n      builder.put(describeRegionsRequest, describeRegionsResponse);\n      builder.putAll(describeAvailabilityZonesRequestResponse);\n      builder.put(\n              HttpRequest.builder()\n                      .method(\"POST\")\n                      .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                      .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                      .payload(payloadFromStringWithContentType(\"Action=CreateVolume\" +\n                              \"&AvailabilityZone=us-east-1a\" +\n                              \"&Iops=0\" +\n                              \"&Signature=uI5tXrwV4zXB3uh0OP4RkfU2HMdQ2yICfpo4gKrajMI%3D\" +\n                              \"&SignatureMethod=HmacSHA256\" +\n                              \"&SignatureVersion=2\" +\n                              \"&Size=4\" +\n                              \"&Timestamp=2012-04-16T15%3A54%3A08.897Z\" +\n                              \"&Version=2010-08-31\" +\n                              \"&VolumeType=standard\" +\n                              \"&AWSAccessKeyId=identity\", \"application/x-www-form-urlencoded\")).build(),\n              HttpResponse.builder()\n                      .statusCode(200)\n                      .payload(payloadFromResource(\"/created_volume.xml\")).build());\n\n      ElasticBlockStoreApi client = requestsSendResponses(builder.build()).getElasticBlockStoreApi().get();\n\n      assertEquals(client.createVolumeInAvailabilityZone(\"us-east-1a\",\n              CreateVolumeOptions.Builder.withSize(4).isEncrypted(false).volumeType(\"standard\").withIops(0)),\n              creating);\n   }\n\n   public void testCreateVolumeFromSnapshotInAvailabilityZoneEuSetsCorrectEndpoint() {\n      String region = \"eu-west-1\";\n      \n      Builder<HttpRequest, HttpResponse> builder = ImmutableMap.<HttpRequest, HttpResponse>builder();\n      builder.put(describeRegionsRequest, describeRegionsResponse);\n      builder.putAll(describeAvailabilityZonesRequestResponse);\n      builder.put(\n            formSigner.filter(HttpRequest.builder()\n                    .method(\"POST\")\n                    .endpoint(\"https://ec2.\" + region + \".amazonaws.com/\")\n                    .addHeader(\"Host\", \"ec2.\" + region + \".amazonaws.com\")\n                    .addFormParam(\"Action\", \"CreateVolume\")\n                    .addFormParam(\"AvailabilityZone\", \"eu-west-1a\")\n                    .addFormParam(\"Size\", \"1\")\n                    .addFormParam(\"SnapshotId\", \"snap-8b7ffbdd\")\n                    .build()),\n              HttpResponse.builder()\n                      .statusCode(200)\n                      .payload(payloadFromResource(\"/created_volume.xml\")).build());\n      \n      ElasticBlockStoreApi client = requestsSendResponses(builder.build()).getElasticBlockStoreApi().get();\n\n      assertEquals(client.createVolumeFromSnapshotInAvailabilityZone(region + \"a\", 1, \"snap-8b7ffbdd\"), creating.toBuilder().region(region).build());\n   }\n\n   HttpRequest filterVolumes = HttpRequest.builder().method(\"POST\")\n           .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n           .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n           .addFormParam(\"Action\", \"DescribeVolumes\")\n           .addFormParam(\"Filter.1.Name\", \"snapshot-id\")\n           .addFormParam(\"Filter.1.Value.1\", \"snap-536d1b3a\")\n           .addFormParam(\"Signature\", \"7g2ySW39nIVfxtIbuVttUBom7sssmQknxX/9SThkm2Y=\")\n           .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n           .addFormParam(\"SignatureVersion\", \"2\")\n           .addFormParam(\"Timestamp\", \"2012-04-16T15:54:08.897Z\")\n           .addFormParam(\"Version\", \"2010-08-31\")\n           .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testFilterVolumesWhenResponseIs2xx() {\n      HttpResponse filterResponse = HttpResponse.builder().statusCode(200)\n              .payload(payloadFromResourceWithContentType(\"/describe_volumes_single.xml\", \"text/xml\")).build();\n\n      EC2Api apiWhenExist = requestsSendResponses(describeRegionsRequest, describeRegionsResponse, filterVolumes, filterResponse);\n\n      Volume volume = getOnlyElement(apiWhenExist.getElasticBlockStoreApi().get().describeVolumesInRegionWithFilter(\"us-east-1\",\n              ImmutableMultimap.<String, String>builder()\n                      .put(\"snapshot-id\", \"snap-536d1b3a\")\n                      .build()));\n\n      assertEquals(volume.getId(), \"vol-4282672b\");\n   }\n\n   @Test(expectedExceptions = ResourceNotFoundException.class)\n   public void testFilterVolumesWhenResponseIs404() {\n      HttpResponse filterResponse = HttpResponse.builder().statusCode(404).build();\n\n      EC2Api apiWhenNotExist = requestsSendResponses(describeRegionsRequest, describeRegionsResponse, filterVolumes, filterResponse);\n\n      assertEquals(apiWhenNotExist.getElasticBlockStoreApi().get().describeVolumesInRegionWithFilter(\"us-east-1\",\n              ImmutableMultimap.<String, String>builder()\n                      .put(\"snapshot-id\", \"snap-536d1b3a\")\n                      .build()),\n              ImmutableSet.of());\n   }\n\n   HttpRequest filterSnapshots = HttpRequest.builder().method(\"POST\")\n           .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n           .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n           .addFormParam(\"Action\", \"DescribeSnapshots\")\n           .addFormParam(\"Filter.1.Name\", \"volume-id\")\n           .addFormParam(\"Filter.1.Value.1\", \"4d826724\")\n           .addFormParam(\"Signature\", \"vT7R4YmfQJPNLSojXEMY1qcErMh0OzrOTYxbGYSZ4Uw=\")\n           .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n           .addFormParam(\"SignatureVersion\", \"2\")\n           .addFormParam(\"Timestamp\", \"2012-04-16T15:54:08.897Z\")\n           .addFormParam(\"Version\", \"2010-08-31\")\n           .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testFilterSnapshotsWhenResponseIs2xx() {\n      HttpResponse filterResponse = HttpResponse.builder().statusCode(200)\n              .payload(payloadFromResourceWithContentType(\"/describe_snapshots.xml\", \"text/xml\")).build();\n\n      EC2Api apiWhenExist = requestsSendResponses(describeRegionsRequest, describeRegionsResponse, filterSnapshots, filterResponse);\n\n      Snapshot snapshot = getOnlyElement(apiWhenExist.getElasticBlockStoreApi().get().describeSnapshotsInRegionWithFilter(\"us-east-1\",\n              ImmutableMultimap.<String, String>builder()\n                      .put(\"volume-id\", \"4d826724\")\n                      .build()));\n\n      assertEquals(snapshot.getId(), \"snap-78a54011\");\n   }\n\n   public void testFilterSnapshotsWhenResponseIs404() {\n      HttpResponse filterResponse = HttpResponse.builder().statusCode(404).build();\n\n      EC2Api apiWhenNotExist = requestsSendResponses(describeRegionsRequest, describeRegionsResponse, filterSnapshots, filterResponse);\n\n      assertEquals(apiWhenNotExist.getElasticBlockStoreApi().get().describeSnapshotsInRegionWithFilter(\"us-east-1\",\n              ImmutableMultimap.<String, String>builder()\n                      .put(\"volume-id\", \"4d826724\")\n                      .build()),\n              ImmutableSet.of());\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/features/ElasticBlockStoreApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.features;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static org.jclouds.ec2.options.CreateVolumeOptions.Builder.fromSnapshotId;\nimport static org.jclouds.ec2.options.CreateVolumeOptions.Builder.withSize;\nimport static org.jclouds.ec2.options.DescribeSnapshotsOptions.Builder.snapshotIds;\nimport static org.jclouds.util.Predicates2.retry;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\nimport java.util.SortedSet;\n\nimport org.jclouds.aws.AWSResponseException;\nimport org.jclouds.compute.internal.BaseComputeServiceContextLiveTest;\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.domain.AvailabilityZoneInfo;\nimport org.jclouds.ec2.domain.Snapshot;\nimport org.jclouds.ec2.domain.Volume;\nimport org.jclouds.ec2.domain.Volume.Status;\nimport org.jclouds.ec2.predicates.SnapshotCompleted;\nimport org.jclouds.ec2.predicates.VolumeAvailable;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Strings;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Sets;\n\n/**\n * Tests behavior of {@code ElasticBlockStoreApi}\n */\n@Test(groups = \"live\", singleThreaded = true)\npublic class ElasticBlockStoreApiLiveTest extends BaseComputeServiceContextLiveTest {\n   public ElasticBlockStoreApiLiveTest() {\n      provider = \"ec2\";\n   }\n\n   protected EC2Api ec2Api;\n   protected ElasticBlockStoreApi client;\n\n   protected String defaultRegion;\n   protected String defaultZone;\n\n   protected String volumeId;\n   protected Snapshot snapshot;\n\n   @Override\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   public void setupContext() {\n      super.setupContext();\n      ec2Api = view.unwrapApi(EC2Api.class);\n      client = ec2Api.getElasticBlockStoreApi().get();\n      AvailabilityZoneInfo info = Iterables.get(ec2Api.getAvailabilityZoneAndRegionApi().get()\n            .describeAvailabilityZonesInRegion(defaultRegion), 0);\n      defaultRegion = checkNotNull(Strings.emptyToNull(info.getRegion()), \"region of \" + info);\n      defaultZone = checkNotNull(Strings.emptyToNull(info.getZone()), \"zone of \" + info);\n   }\n\n   @Test\n   void testDescribeVolumes() {\n      String region = defaultRegion;\n      SortedSet<Volume> allResults = Sets.newTreeSet(client.describeVolumesInRegion(region));\n      assertNotNull(allResults);\n      assertFalse(allResults.isEmpty());\n      Volume volume = allResults.last();\n      SortedSet<Volume> result = Sets.newTreeSet(client.describeVolumesInRegion(region, volume.getId()));\n      assertNotNull(result);\n      Volume compare = result.last();\n      assertEquals(compare, volume);\n   }\n\n   @Test\n   void testDescribeVolumesWithFilter() {\n      String region = defaultRegion;\n      SortedSet<Volume> allResults = Sets.newTreeSet(client.describeVolumesInRegion(region));\n      assertNotNull(allResults);\n      assertFalse(allResults.isEmpty());\n      Volume volume = allResults.last();\n      SortedSet<Volume> result = Sets.newTreeSet(client.describeVolumesInRegionWithFilter(region,\n              ImmutableMultimap.<String, String>builder()\n                      .put(\"volume-id\", volume.getId()).build()));\n      assertNotNull(result);\n      Volume compare = result.last();\n      assertEquals(compare, volume);\n   }\n\n   @Test(expectedExceptions = AWSResponseException.class)\n   void testDescribeVolumesWithInvalidFilter() {\n      String region = defaultRegion;\n      SortedSet<Volume> allResults = Sets.newTreeSet(client.describeVolumesInRegion(region));\n      assertNotNull(allResults);\n      assertFalse(allResults.isEmpty());\n      Volume volume = allResults.last();\n      client.describeVolumesInRegionWithFilter(region,\n              ImmutableMultimap.<String, String>builder()\n                      .put(\"invalid-filter\", volume.getId()).build());\n   }\n\n   @Test\n   void testCreateVolumeInAvailabilityZone() {\n      Volume expected = client.createVolumeInAvailabilityZone(defaultZone,\n              withSize(1));\n      assertNotNull(expected);\n      assertEquals(expected.getAvailabilityZone(), defaultZone);\n      this.volumeId = expected.getId();\n\n      Set<Volume> result = Sets.newLinkedHashSet(client.describeVolumesInRegion(defaultRegion, expected.getId()));\n      assertNotNull(result);\n      assertEquals(result.size(), 1);\n      Volume volume = result.iterator().next();\n      assertEquals(volume.getId(), expected.getId());\n      assertEquals(volume.getVolumeType(), expected.getVolumeType());\n   }\n\n   @Test(dependsOnMethods = \"testCreateVolumeInAvailabilityZone\")\n   void testCreateSnapshotInRegion() {\n      Snapshot snapshot = client.createSnapshotInRegion(defaultRegion, volumeId);\n      Predicate<Snapshot> snapshotted = retry(new SnapshotCompleted(client), 600, 10, SECONDS);\n      assert snapshotted.apply(snapshot);\n\n      Snapshot result = Iterables.getOnlyElement(client.describeSnapshotsInRegion(defaultRegion,\n            snapshotIds(snapshot.getId())));\n\n      assertEquals(result.getProgress(), 100);\n      this.snapshot = result;\n   }\n\n   @Test(dependsOnMethods = \"testCreateSnapshotInRegion\")\n   void testCreateVolumeFromSnapshotInAvailabilityZone() {\n      Volume volume = client.createVolumeFromSnapshotInAvailabilityZone(defaultZone, snapshot.getId());\n      assertNotNull(volume);\n\n      Predicate<Volume> availabile = retry(new VolumeAvailable(client), 600, 10, SECONDS);\n      assert availabile.apply(volume);\n\n      Volume result = Iterables.getOnlyElement(client.describeVolumesInRegion(defaultRegion, volume.getId()));\n      assertEquals(volume.getId(), result.getId());\n      assertEquals(volume.getSnapshotId(), snapshot.getId());\n      assertEquals(volume.getAvailabilityZone(), defaultZone);\n      assertEquals(result.getStatus(), Volume.Status.AVAILABLE);\n\n      client.deleteVolumeInRegion(defaultRegion, result.getId());\n   }\n\n   @Test(dependsOnMethods = \"testCreateVolumeFromSnapshotInAvailabilityZone\")\n   void testCreateVolumeFromSnapshotInAvailabilityZoneWithOptions() {\n      Volume volume = client.createVolumeInAvailabilityZone(defaultZone,\n              fromSnapshotId(snapshot.getId()));\n      assertNotNull(volume);\n\n      Predicate<Volume> availabile = retry(new VolumeAvailable(client), 600, 10, SECONDS);\n      assert availabile.apply(volume);\n\n      Volume result = Iterables.getOnlyElement(client.describeVolumesInRegion(defaultRegion, volume.getId()));\n      assertEquals(volume.getId(), result.getId());\n      assertEquals(volume.getSnapshotId(), snapshot.getId());\n      assertEquals(volume.getAvailabilityZone(), defaultZone);\n      assertEquals(result.getStatus(), Volume.Status.AVAILABLE);\n\n      client.deleteVolumeInRegion(defaultRegion, result.getId());\n   }\n\n   @Test(dependsOnMethods = \"testCreateVolumeFromSnapshotInAvailabilityZoneWithOptions\")\n   void testCreateVolumeFromSnapshotInAvailabilityZoneWithSize() {\n      Volume volume = client.createVolumeFromSnapshotInAvailabilityZone(defaultZone, 2, snapshot.getId());\n      assertNotNull(volume);\n\n      Predicate<Volume> availabile = retry(new VolumeAvailable(client), 600, 10, SECONDS);\n      assert availabile.apply(volume);\n\n      Volume result = Iterables.getOnlyElement(client.describeVolumesInRegion(defaultRegion, volume.getId()));\n      assertEquals(volume.getId(), result.getId());\n      assertEquals(volume.getSnapshotId(), snapshot.getId());\n      assertEquals(volume.getAvailabilityZone(), defaultZone);\n      assertEquals(volume.getSize(), 2);\n      assertEquals(result.getStatus(), Volume.Status.AVAILABLE);\n\n      client.deleteVolumeInRegion(defaultRegion, result.getId());\n   }\n\n   @Test\n   void testAttachVolumeInRegion() {\n      // TODO: need an instance\n   }\n\n   @Test\n   void testDetachVolumeInRegion() {\n      // TODO: need an instance\n   }\n\n   @Test\n   void testDescribeSnapshots() {\n      String region = defaultRegion;\n      SortedSet<Snapshot> allResults = Sets.newTreeSet(client.describeSnapshotsInRegion(region));\n      assertNotNull(allResults);\n      if (!allResults.isEmpty()) {\n         Snapshot snapshot = allResults.last();\n         Snapshot result = Iterables.getOnlyElement(client.describeSnapshotsInRegion(region,\n                 snapshotIds(snapshot.getId())));\n         assertNotNull(result);\n         assertEquals(result, snapshot);\n      }\n   }\n\n   @Test\n   void testDescribeSnapshotsWithFilter() {\n      String region = defaultRegion;\n      SortedSet<Snapshot> allResults = Sets.newTreeSet(client.describeSnapshotsInRegion(region));\n      assertNotNull(allResults);\n      if (!allResults.isEmpty()) {\n         Snapshot snapshot = allResults.last();\n         Snapshot result = Iterables.getOnlyElement(client.describeSnapshotsInRegionWithFilter(region,\n                 ImmutableMultimap.<String, String>builder()\n                         .put(\"snapshot-id\", snapshot.getId()).build()));\n         assertNotNull(result);\n         assertEquals(result, snapshot);\n      }\n   }\n\n   @Test(expectedExceptions = AWSResponseException.class)\n   void testDescribeSnapshotsWithFilterInvalid() {\n      String region = defaultRegion;\n      SortedSet<Snapshot> allResults = Sets.newTreeSet(client.describeSnapshotsInRegion(region));\n      assertNotNull(allResults);\n      if (!allResults.isEmpty()) {\n         Snapshot snapshot = allResults.last();\n         client.describeSnapshotsInRegionWithFilter(region,\n                 ImmutableMultimap.<String, String>builder()\n                         .put(\"invalid-filter\", snapshot.getId()).build());\n      }\n   }\n\n   @Test(enabled = false)\n   public void testAddCreateVolumePermissionsToSnapshot() {\n      // TODO client.addCreateVolumePermissionsToSnapshotInRegion(defaultRegion,\n      // userIds,\n      // userGroups,\n      // snapshotId);\n   }\n\n   @Test(enabled = false)\n   public void testRemoveCreateVolumePermissionsFromSnapshot() {\n      // TODO\n      // client.removeCreateVolumePermissionsFromSnapshotInRegion(defaultRegion,\n      // userIds,\n      // userGroups,\n      // snapshotId);\n   }\n\n   @Test(enabled = false)\n   public void testResetCreateVolumePermissionsOnSnapshot() {\n      // TODO\n      // client.resetCreateVolumePermissionsOnSnapshotInRegion(defaultRegion,\n      // snapshotId);\n   }\n\n   @Test(dependsOnMethods = \"testCreateVolumeFromSnapshotInAvailabilityZoneWithSize\")\n   public void testGetCreateVolumePermissionForSnapshot() {\n      client.getCreateVolumePermissionForSnapshotInRegion(defaultRegion, snapshot.getId());\n   }\n\n   @Test(dependsOnMethods = \"testGetCreateVolumePermissionForSnapshot\")\n   void testDeleteVolumeInRegion() {\n      client.deleteVolumeInRegion(defaultRegion, volumeId);\n      Set<Volume> volumes = client.describeVolumesInRegionWithFilter(defaultRegion, ImmutableMultimap\n            .<String, String> builder().put(\"volume-id\", volumeId).build());\n      // The volume may not exist or remain in \"deleting\" state for a while\n      Volume volume = getOnlyElement(volumes, null);\n      assertTrue(volume == null || Status.DELETING == volume.getStatus());\n   }\n\n   @Test(dependsOnMethods = \"testDeleteVolumeInRegion\")\n   void testDeleteSnapshotInRegion() {\n      client.deleteSnapshotInRegion(defaultRegion, snapshot.getId());\n      assert client.describeSnapshotsInRegion(defaultRegion, snapshotIds(snapshot.getId())).size() == 0;\n   }\n\n   @AfterClass(groups = { \"integration\", \"live\" })\n   @Override\n   protected void tearDownContext() {\n      try {\n         client.deleteSnapshotInRegion(defaultRegion, snapshot.getId());\n         client.deleteVolumeInRegion(defaultRegion, volumeId);\n      } catch (Exception e) {\n         // we don't really care about any exception here, so just delete away.\n      }\n\n      super.tearDownContext();\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/features/ElasticBlockStoreApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.features;\n\nimport static org.jclouds.ec2.options.DescribeSnapshotsOptions.Builder.ownedBy;\nimport static org.jclouds.ec2.options.DetachVolumeOptions.Builder.fromInstance;\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport java.io.IOException;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.ec2.EC2Fallbacks.VoidOnVolumeAvailable;\nimport org.jclouds.ec2.options.CreateSnapshotOptions;\nimport org.jclouds.ec2.options.DescribeSnapshotsOptions;\nimport org.jclouds.ec2.options.DetachVolumeOptions;\nimport org.jclouds.ec2.xml.AttachmentHandler;\nimport org.jclouds.ec2.xml.DescribeSnapshotsResponseHandler;\nimport org.jclouds.ec2.xml.DescribeVolumesResponseHandler;\nimport org.jclouds.ec2.xml.PermissionHandler;\nimport org.jclouds.ec2.xml.SnapshotHandler;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.http.functions.ReleasePayloadAndReturn;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Lists;\nimport com.google.common.reflect.Invokable;\n/**\n * Tests behavior of {@code ElasticBlockStoreApi}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"ElasticBlockStoreApiTest\")\npublic class ElasticBlockStoreApiTest extends BaseEC2ApiTest<ElasticBlockStoreApi> {\n\n   public void testDeleteVolume() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ElasticBlockStoreApi.class, \"deleteVolumeInRegion\", String.class, String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"id\"));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, \"Action=DeleteVolume&VolumeId=id\",\n               \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   HttpRequest describeVolumes = HttpRequest.builder().method(\"POST\")\n                                            .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                                            .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                                            .addFormParam(\"Action\", \"DescribeVolumes\")\n                                            .addFormParam(\"Signature\", \"nNxWg5dwYZEQu1QCzCtNp7iDmPR8wXXdKhWmLEKFLGI=\")\n                                            .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n                                            .addFormParam(\"SignatureVersion\", \"2\")\n                                            .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n                                            .addFormParam(\"Version\", \"2010-08-31\")\n                                            .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testDescribeVolumes() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ElasticBlockStoreApi.class, \"describeVolumesInRegion\", String.class,\n            String[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList((String) null));\n\n      request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);\n      \n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, describeVolumes.getPayload().getRawContent().toString(),\n            \"application/x-www-form-urlencoded\", false);\n      \n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, DescribeVolumesResponseHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testDescribeVolumesArgs() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ElasticBlockStoreApi.class, \"describeVolumesInRegion\", String.class,\n               String[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"1\", \"2\"));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, \"Action=DescribeVolumes&VolumeId.1=1&VolumeId.2=2\",\n               \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, DescribeVolumesResponseHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   HttpRequest attachVolume = HttpRequest.builder().method(\"POST\")\n                                         .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                                         .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                                         .addFormParam(\"Action\", \"AttachVolume\")\n                                         .addFormParam(\"Device\", \"/device\")\n                                         .addFormParam(\"InstanceId\", \"instanceId\")\n                                         .addFormParam(\"Signature\", \"0+UY5oCQzoJapEHq4Dl2R/0nAA8uXEHqvHbnnNI5NcA=\")\n                                         .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n                                         .addFormParam(\"SignatureVersion\", \"2\")\n                                         .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n                                         .addFormParam(\"Version\", \"2010-08-31\")\n                                         .addFormParam(\"VolumeId\", \"id\")\n                                         .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testAttachVolume() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ElasticBlockStoreApi.class, \"attachVolumeInRegion\", String.class, String.class,\n               String.class, String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"id\", \"instanceId\", \"/device\"));\n\n      request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);\n      \n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, attachVolume.getPayload().getRawContent().toString(),\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, AttachmentHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   HttpRequest detachVolume = HttpRequest.builder().method(\"POST\")\n                                         .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                                         .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                                         .addFormParam(\"Action\", \"DetachVolume\")\n                                         .addFormParam(\"Force\", \"false\")\n                                         .addFormParam(\"Signature\", \"tfNB1g2WVqb3EwvBJlk4duU1H1fDOa1SBstsm1elpbg=\")\n                                         .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n                                         .addFormParam(\"SignatureVersion\", \"2\")\n                                         .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n                                         .addFormParam(\"Version\", \"2010-08-31\")\n                                         .addFormParam(\"VolumeId\", \"id\")\n                                         .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testDetachVolume() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ElasticBlockStoreApi.class, \"detachVolumeInRegion\", String.class, String.class,\n               boolean.class, DetachVolumeOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"id\", false));\n\n      request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);\n      \n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, detachVolume.getPayload().getRawContent().toString(),\n            \"application/x-www-form-urlencoded\", false);\n      \n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, VoidOnVolumeAvailable.class);\n\n      checkFilters(request);\n   }\n\n   HttpRequest detachVolumeOptions = HttpRequest.builder().method(\"POST\")\n                                                .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                                                .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                                                .addFormParam(\"Action\", \"DetachVolume\")\n                                                .addFormParam(\"Device\", \"/device\")\n                                                .addFormParam(\"Force\", \"true\")\n                                                .addFormParam(\"InstanceId\", \"instanceId\")\n                                                .addFormParam(\"Signature\", \"VFhgwdkKBKXr/dEn2gvk6Vqq3JIunw4zZgM2Tt/ouME=\")\n                                                .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n                                                .addFormParam(\"SignatureVersion\", \"2\")\n                                                .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n                                                .addFormParam(\"Version\", \"2010-08-31\")\n                                                .addFormParam(\"VolumeId\", \"id\")\n                                                .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testDetachVolumeOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ElasticBlockStoreApi.class, \"detachVolumeInRegion\", String.class, String.class,\n               boolean.class, DetachVolumeOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"id\", true, fromInstance(\"instanceId\").fromDevice(\n               \"/device\")));\n\n      request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);\n      \n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, detachVolumeOptions.getPayload().getRawContent().toString(),\n            \"application/x-www-form-urlencoded\", false);\n      \n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, VoidOnVolumeAvailable.class);\n\n      checkFilters(request);\n   }\n\n   public void testCreateSnapshot() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ElasticBlockStoreApi.class, \"createSnapshotInRegion\", String.class,\n               String.class, CreateSnapshotOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"volumeId\"));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, \"Action=CreateSnapshot&VolumeId=volumeId\",\n               \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, SnapshotHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testCreateSnapshotOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ElasticBlockStoreApi.class, \"createSnapshotInRegion\", String.class,\n               String.class, CreateSnapshotOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"volumeId\", CreateSnapshotOptions.Builder\n               .withDescription(\"description\")));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request,\n               \"Action=CreateSnapshot&VolumeId=volumeId&Description=description\",\n               \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, SnapshotHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testDescribeSnapshots() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ElasticBlockStoreApi.class, \"describeSnapshotsInRegion\", String.class,\n               DescribeSnapshotsOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList((String) null));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, \"Action=DescribeSnapshots\", \"application/x-www-form-urlencoded\",\n               false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, DescribeSnapshotsResponseHandler.class);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(request);\n   }\n\n   public void testDescribeSnapshotsArgs() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ElasticBlockStoreApi.class, \"describeSnapshotsInRegion\", String.class,\n               DescribeSnapshotsOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, ownedBy(\"o1\", \"o2\").restorableBy(\"r1\", \"r2\")\n               .snapshotIds(\"s1\", \"s2\")));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(\n               request,\n               \"Action=DescribeSnapshots&Owner.1=o1&Owner.2=o2&RestorableBy.1=r1&RestorableBy.2=r2&SnapshotId.1=s1&SnapshotId.2=s2\",\n               \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, DescribeSnapshotsResponseHandler.class);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(request);\n   }\n\n   public void testGetCreateVolumePermissionForSnapshot() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ElasticBlockStoreApi.class, \"getCreateVolumePermissionForSnapshotInRegion\",\n               String.class, String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"snapshotId\"));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(\n               request,\n               \"Action=DescribeSnapshotAttribute&Attribute=createVolumePermission&SnapshotId=snapshotId\",\n               \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, PermissionHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   HttpRequest addCreateVolumePermissionsToSnapshot = HttpRequest.builder().method(\"POST\")\n                                                                 .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                                                                 .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                                                                 .addFormParam(\"Action\", \"ModifySnapshotAttribute\")\n                                                                 .addFormParam(\"Attribute\", \"createVolumePermission\")\n                                                                 .addFormParam(\"OperationType\", \"add\")\n                                                                 .addFormParam(\"Signature\", \"s8m8DqQRXmecWguuRjxfl3Ibd+1AjjktGzTlJLUTcPc=\")\n                                                                 .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n                                                                 .addFormParam(\"SignatureVersion\", \"2\")\n                                                                 .addFormParam(\"SnapshotId\", \"snapshotId\")\n                                                                 .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n                                                                 .addFormParam(\"UserGroup.1\", \"all\")\n                                                                 .addFormParam(\"UserId.1\", \"bob\")\n                                                                 .addFormParam(\"UserId.2\", \"sue\")\n                                                                 .addFormParam(\"Version\", \"2010-08-31\")\n                                                                 .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testAddCreateVolumePermissionsToSnapshot() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ElasticBlockStoreApi.class, \"addCreateVolumePermissionsToSnapshotInRegion\",\n               String.class, Iterable.class, Iterable.class, String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, ImmutableList.of(\"bob\", \"sue\"), ImmutableList\n               .of(\"all\"), \"snapshotId\"));\n\n      request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);\n      \n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, addCreateVolumePermissionsToSnapshot.getPayload().getRawContent().toString(),\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   HttpRequest removeCreateVolumePermissionsFromSnapshot = HttpRequest.builder().method(\"POST\")\n                                                                      .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                                                                      .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                                                                      .addFormParam(\"Action\", \"ModifySnapshotAttribute\")\n                                                                      .addFormParam(\"Attribute\", \"createVolumePermission\")\n                                                                      .addFormParam(\"OperationType\", \"remove\")\n                                                                      .addFormParam(\"Signature\", \"RzxHUIWV80cyhQDtrMiHDWUosS1g8cn1+7ONLJCe1dg=\")\n                                                                      .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n                                                                      .addFormParam(\"SignatureVersion\", \"2\")\n                                                                      .addFormParam(\"SnapshotId\", \"snapshotId\")\n                                                                      .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n                                                                      .addFormParam(\"UserGroup.1\", \"all\")\n                                                                      .addFormParam(\"UserId.1\", \"bob\")\n                                                                      .addFormParam(\"UserId.2\", \"sue\")\n                                                                      .addFormParam(\"Version\", \"2010-08-31\")\n                                                                      .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testRemoveCreateVolumePermissionsFromSnapshot() throws SecurityException, NoSuchMethodException,\n            IOException {\n      Invokable<?, ?> method = method(ElasticBlockStoreApi.class, \"removeCreateVolumePermissionsFromSnapshotInRegion\",\n               String.class, Iterable.class, Iterable.class, String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, ImmutableList.of(\"bob\", \"sue\"), ImmutableList\n               .of(\"all\"), \"snapshotId\"));\n\n      request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);\n      \n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, removeCreateVolumePermissionsFromSnapshot.getPayload().getRawContent().toString(),\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testResetCreateVolumePermissionsOnSnapshot() throws SecurityException, NoSuchMethodException,\n            IOException {\n      Invokable<?, ?> method = method(ElasticBlockStoreApi.class, \"resetCreateVolumePermissionsOnSnapshotInRegion\",\n               String.class, String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"snapshotId\"));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(\n               request,\n               \"Action=ResetSnapshotAttribute&Attribute=createVolumePermission&SnapshotId=snapshotId\",\n               \"application/x-www-form-urlencoded\", false);\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/features/ElasticIPAddressApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.features;\n\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.Properties;\n\nimport org.jclouds.Constants;\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.domain.PublicIpInstanceIdPair;\nimport org.jclouds.ec2.internal.BaseEC2ApiExpectTest;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rest.internal.BaseRestApiExpectTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n *\n * @see org.jclouds.ec2.features.ElasticIPAddressApi\n */\n@Test(groups = \"unit\")\npublic class ElasticIPAddressApiExpectTest extends BaseEC2ApiExpectTest<EC2Api> {\n\n   protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      props.put(Constants.PROPERTY_API_VERSION, \"2010-08-31\");\n      return props;\n   }\n\n   HttpRequest filter =\n           HttpRequest.builder()\n                   .method(\"POST\")\n                   .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                   .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                   .payload(BaseRestApiExpectTest.payloadFromStringWithContentType(\n                           \"Action=DescribeAddresses\" +\n                                   \"&Filter.1.Name=instance-id\" +\n                                   \"&Filter.1.Value.1=i-f15ebb98\" +\n                                   \"&Signature=dJbTUsBGHSrarQQAwmLm8LLI255R/lzdE7ZcYJucOzI%3D\" +\n                                   \"&SignatureMethod=HmacSHA256\" +\n                                   \"&SignatureVersion=2\" +\n                                   \"&Timestamp=2012-04-16T15%3A54%3A08.897Z\" +\n                                   \"&Version=2010-08-31\" +\n                                   \"&AWSAccessKeyId=identity\",\n                           \"application/x-www-form-urlencoded\"))\n                   .build();\n\n   public void testFilterWhenResponseIs2xx() throws Exception {\n\n      HttpResponse filterResponse = HttpResponse.builder().statusCode(200)\n              .payload(payloadFromResourceWithContentType(\"/describe_addresses_single.xml\", \"text/xml\")).build();\n\n\n      EC2Api apiWhenExist = requestsSendResponses(describeRegionsRequest, describeRegionsResponse,\n              filter, filterResponse);\n\n      PublicIpInstanceIdPair address = getOnlyElement(apiWhenExist.getElasticIPAddressApi()\n              .get().describeAddressesInRegionWithFilter(\"us-east-1\",\n                      ImmutableMultimap.<String, String>builder()\n                              .put(\"instance-id\", \"i-f15ebb98\")\n                              .build()));\n      assertNotNull(address, \"address should not be null\");\n\n      assertEquals(address.getPublicIp(), \"67.202.55.255\");\n   }\n\n   public void testFilterWhenResponseIs404() throws Exception {\n\n      HttpResponse filterResponse = HttpResponse.builder().statusCode(404).build();\n\n      EC2Api apiWhenDontExist = requestsSendResponses(describeRegionsRequest, describeRegionsResponse,\n              filter, filterResponse);\n\n      assertEquals(apiWhenDontExist.getElasticIPAddressApi()\n              .get().describeAddressesInRegionWithFilter(\"us-east-1\",\n                      ImmutableMultimap.<String, String>builder()\n                              .put(\"instance-id\", \"i-f15ebb98\")\n                              .build()), ImmutableSet.of());\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/features/ElasticIPAddressApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.SortedSet;\n\nimport org.jclouds.compute.internal.BaseComputeServiceContextLiveTest;\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.domain.PublicIpInstanceIdPair;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.Sets;\n\n/**\n * Tests behavior of {@code ElasticIPAddressApi}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"ElasticIPAddressApiLiveTest\")\npublic class ElasticIPAddressApiLiveTest extends BaseComputeServiceContextLiveTest {\n   public ElasticIPAddressApiLiveTest() {\n      provider = \"ec2\";\n   }\n\n   private EC2Api ec2Api;\n   private ElasticIPAddressApi client;\n\n   @Override\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   public void setupContext() {\n      super.setupContext();\n      ec2Api = view.unwrapApi(EC2Api.class);\n      client = ec2Api.getElasticIPAddressApi().get();\n   }\n\n   @Test\n   void testDescribeAddresses() {\n      for (String region : ec2Api.getConfiguredRegions()) {\n         SortedSet<PublicIpInstanceIdPair> allResults = Sets.newTreeSet(client.describeAddressesInRegion(region));\n         assertNotNull(allResults);\n         if (!allResults.isEmpty()) {\n            PublicIpInstanceIdPair pair = allResults.last();\n            SortedSet<PublicIpInstanceIdPair> result = Sets.newTreeSet(client.describeAddressesInRegion(region, pair\n                     .getPublicIp()));\n            assertNotNull(result);\n            PublicIpInstanceIdPair compare = result.last();\n            assertEquals(compare, pair);\n\n            SortedSet<PublicIpInstanceIdPair> filterResult = Sets.newTreeSet(client.describeAddressesInRegionWithFilter(\n                    region, ImmutableMultimap.<String, String>builder().put(\"public-ip\", pair.getPublicIp()).build()));\n            assertNotNull(filterResult);\n            PublicIpInstanceIdPair filterCompare = filterResult.last();\n            assertEquals(filterCompare, pair);\n         }\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/features/ElasticIPAddressApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.features;\n\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport java.io.IOException;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.ec2.xml.AllocateAddressResponseHandler;\nimport org.jclouds.ec2.xml.DescribeAddressesResponseHandler;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.http.functions.ReleasePayloadAndReturn;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Lists;\nimport com.google.common.reflect.Invokable;\n/**\n * Tests behavior of {@code ElasticIPAddressApi}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"ElasticIPAddressApiTest\")\npublic class ElasticIPAddressApiTest extends BaseEC2ApiTest<ElasticIPAddressApi> {\n\n   public void testDisassociateAddress() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ElasticIPAddressApi.class, \"disassociateAddressInRegion\", String.class,\n            String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"127.0.0.1\"));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, \"Action=DisassociateAddress&PublicIp=127.0.0.1\",\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   HttpRequest associateAddress = HttpRequest.builder().method(\"POST\")\n                                             .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                                             .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                                             .addFormParam(\"Action\", \"AssociateAddress\")\n                                             .addFormParam(\"InstanceId\", \"me\")\n                                             .addFormParam(\"PublicIp\", \"127.0.0.1\")\n                                             .addFormParam(\"Signature\", \"nLU6xGLqXtT/dmyAvkN4BdL/3CxQlDWJYeskikhl54k=\")\n                                             .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n                                             .addFormParam(\"SignatureVersion\", \"2\")\n                                             .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n                                             .addFormParam(\"Version\", \"2010-08-31\")\n                                             .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testAssociateAddress() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ElasticIPAddressApi.class, \"associateAddressInRegion\", String.class,\n            String.class, String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"127.0.0.1\", \"me\"));\n\n      request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, associateAddress.getPayload().getRawContent().toString(),\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testReleaseAddress() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ElasticIPAddressApi.class, \"releaseAddressInRegion\", String.class, String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"127.0.0.1\"));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, \"Action=ReleaseAddress&PublicIp=127.0.0.1\",\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testDescribeAddresses() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ElasticIPAddressApi.class, \"describeAddressesInRegion\", String.class,\n            String[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"127.0.0.1\"));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, \"Action=DescribeAddresses&PublicIp.1=127.0.0.1\",\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, DescribeAddressesResponseHandler.class);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(request);\n   }\n\n   public void testAllocateAddress() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ElasticIPAddressApi.class, \"allocateAddressInRegion\", String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList((String) null));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, \"Action=AllocateAddress\", \"application/x-www-form-urlencoded\",\n            false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, AllocateAddressResponseHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/features/InstanceApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.features;\n\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.Properties;\n\nimport org.jclouds.Constants;\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.domain.Reservation;\nimport org.jclouds.ec2.domain.RunningInstance;\nimport org.jclouds.ec2.internal.BaseEC2ApiExpectTest;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rest.internal.BaseRestApiExpectTest;\nimport org.jclouds.util.Strings2;\nimport org.testng.Assert;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n *\n * @see InstanceApi\n */\n@Test(groups = \"unit\")\npublic class InstanceApiExpectTest extends BaseEC2ApiExpectTest<EC2Api> {\n\n   protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      props.put(Constants.PROPERTY_API_VERSION, \"2010-08-31\");\n      return props;\n   }\n\n   HttpRequest filter =\n           HttpRequest.builder()\n                   .method(\"POST\")\n                   .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                   .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                   .payload(BaseRestApiExpectTest.payloadFromStringWithContentType(\n                           \"Action=DescribeInstances\" +\n                                   \"&Filter.1.Name=key-name\" +\n                                   \"&Filter.1.Value.1=\" + Strings2.urlEncode(\"adriancole.ec21\") +\n                                   \"&Signature=%2B2ktAljlAPNUMAJUFh3poQrTvwcwWytuQFBg/ktKdTc%3D\" +\n                                   \"&SignatureMethod=HmacSHA256\" +\n                                   \"&SignatureVersion=2\" +\n                                   \"&Timestamp=2012-04-16T15%3A54%3A08.897Z\" +\n                                   \"&Version=2010-08-31\" +\n                                   \"&AWSAccessKeyId=identity\",\n                           \"application/x-www-form-urlencoded\"))\n                   .build();\n\n   public void testFilterWhenResponseIs2xx() throws Exception {\n\n      HttpResponse filterResponse = HttpResponse.builder().statusCode(200)\n              .payload(payloadFromResourceWithContentType(\"/describe_instances_running.xml\", \"text/xml\")).build();\n\n\n      EC2Api apiWhenExist = requestsSendResponses(describeRegionsRequest, describeRegionsResponse,\n              filter, filterResponse);\n\n      Reservation<? extends RunningInstance> reservation = getOnlyElement(apiWhenExist.getInstanceApi().get().describeInstancesInRegionWithFilter(\"us-east-1\",\n              ImmutableMultimap.<String, String>builder()\n                      .put(\"key-name\", \"adriancole.ec21\")\n                      .build()));\n      RunningInstance instance = getOnlyElement(reservation);\n      assertNotNull(instance, \"Instance should not be null\");\n\n      Assert.assertEquals(instance.getId(), \"i-0799056f\");\n   }\n\n   public void testFilterWhenResponseIs404() throws Exception {\n\n      HttpResponse filterResponse = HttpResponse.builder().statusCode(404).build();\n\n      EC2Api apiWhenDontExist = requestsSendResponses(describeRegionsRequest, describeRegionsResponse,\n              filter, filterResponse);\n\n      Assert.assertEquals(apiWhenDontExist.getInstanceApi().get().describeInstancesInRegionWithFilter(\"us-east-1\",\n              ImmutableMultimap.<String, String>builder()\n                      .put(\"key-name\", \"adriancole.ec21\")\n                      .build()), ImmutableSet.of());\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/features/InstanceApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.features;\n\nimport static com.google.common.collect.Iterables.getFirst;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\n\nimport org.jclouds.aws.AWSResponseException;\nimport org.jclouds.compute.internal.BaseComputeServiceContextLiveTest;\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.domain.Reservation;\nimport org.jclouds.ec2.domain.RunningInstance;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMultimap;\n\n/**\n * Tests behavior of {@code EC2Api}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"InstanceApiLiveTest\")\npublic class InstanceApiLiveTest extends BaseComputeServiceContextLiveTest {\n   public InstanceApiLiveTest() {\n      provider = \"ec2\";\n   }\n\n   private EC2Api ec2Api;\n   private InstanceApi client;\n\n   @Override\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   public void setupContext() {\n      super.setupContext();\n      ec2Api = view.unwrapApi(EC2Api.class);\n      client = ec2Api.getInstanceApi().get();\n   }\n\n   @Test\n   void testDescribeInstances() {\n      for (String region : ec2Api.getConfiguredRegions()) {\n         Set<? extends Reservation<? extends RunningInstance>> allResults = client.describeInstancesInRegion(region);\n         assertNotNull(allResults);\n      }\n   }\n\n   @Test\n   void testFilterInstances() {\n      for (String region : view.unwrapApi(EC2Api.class).getAvailabilityZoneAndRegionApi().get().describeRegions().keySet()) {\n         Set<? extends Reservation<? extends RunningInstance>> allResults = client.describeInstancesInRegion(region);\n         assertNotNull(allResults);\n\n         if (!allResults.isEmpty())  {\n            RunningInstance instance = getFirst(getFirst(allResults, null), null);\n\n            assertNotNull(instance);\n\n            Set<? extends Reservation<? extends RunningInstance>> filterResults = client.describeInstancesInRegionWithFilter(region,\n                    ImmutableMultimap.<String, String>builder()\n                            .put(\"key-name\", instance.getKeyName())\n                            .build());\n\n            assertNotNull(filterResults);\n            assertTrue(!filterResults.isEmpty(), \"No results found for filter, but there should be.\");\n\n         }\n      }\n   }\n\n   @Test(expectedExceptions = AWSResponseException.class)\n   void testInvalidFilterInstances() {\n      for (String region : view.unwrapApi(EC2Api.class).getAvailabilityZoneAndRegionApi().get().describeRegions().keySet()) {\n         Set<? extends Reservation<? extends RunningInstance>> filterResults = client.describeInstancesInRegionWithFilter(region,\n                 ImmutableMultimap.<String, String>builder()\n                         .put(\"invalid-key\", \"some-value\")\n                         .build());\n\n      }\n   }}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/features/InstanceApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.features;\n\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport java.io.IOException;\nimport java.util.Map;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.ec2.domain.BlockDevice;\nimport org.jclouds.ec2.domain.InstanceType;\nimport org.jclouds.ec2.domain.Volume.InstanceInitiatedShutdownBehavior;\nimport org.jclouds.ec2.options.RunInstancesOptions;\nimport org.jclouds.ec2.xml.BlockDeviceMappingHandler;\nimport org.jclouds.ec2.xml.BooleanValueHandler;\nimport org.jclouds.ec2.xml.DescribeInstancesResponseHandler;\nimport org.jclouds.ec2.xml.GetConsoleOutputResponseHandler;\nimport org.jclouds.ec2.xml.InstanceInitiatedShutdownBehaviorHandler;\nimport org.jclouds.ec2.xml.InstanceStateChangeHandler;\nimport org.jclouds.ec2.xml.InstanceTypeHandler;\nimport org.jclouds.ec2.xml.RunInstancesResponseHandler;\nimport org.jclouds.ec2.xml.StringValueHandler;\nimport org.jclouds.ec2.xml.UnencodeStringValueHandler;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.http.functions.ReleasePayloadAndReturn;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Lists;\nimport com.google.common.collect.Maps;\nimport com.google.common.reflect.Invokable;\n/**\n * Tests behavior of {@code InstanceApi}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"InstanceApiTest\")\npublic class InstanceApiTest extends BaseEC2ApiTest<InstanceApi> {\n   public void testDescribeInstances() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(InstanceApi.class, \"describeInstancesInRegion\", String.class, String[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList((String) null));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, \"Action=DescribeInstances\", \"application/x-www-form-urlencoded\",\n               false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, DescribeInstancesResponseHandler.class);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(request);\n   }\n\n   public void testDescribeInstancesArgs() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(InstanceApi.class, \"describeInstancesInRegion\", String.class, String[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"1\", \"2\"));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, \"Action=DescribeInstances&InstanceId.1=1&InstanceId.2=2\",\n               \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, DescribeInstancesResponseHandler.class);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(request);\n   }\n\n   public void testTerminateInstances() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(InstanceApi.class, \"terminateInstancesInRegion\", String.class,\n               String[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"1\", \"2\"));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, \"Action=TerminateInstances&InstanceId.1=1&InstanceId.2=2\",\n               \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, InstanceStateChangeHandler.class);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(request);\n   }\n\n   public void testRunInstances() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(InstanceApi.class, \"runInstancesInRegion\", String.class, String.class,\n               String.class, int.class, int.class, RunInstancesOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, null, \"ami-voo\", 1, 1));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      try {\n         assertPayloadEquals(request, \"Action=RunInstances&ImageId=ami-voo&MinCount=1&MaxCount=1\",\n                  \"application/x-www-form-urlencoded\", false);\n      } catch (AssertionError e) {\n         // mvn 3.0 osx 10.6.5 somehow sorts differently\n         assertPayloadEquals(request, \"Action=RunInstances&ImageId=ami-voo&MaxCount=1&MinCount=1\",\n                  \"application/x-www-form-urlencoded\", false);\n      }\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, RunInstancesResponseHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testRunInstancesOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(InstanceApi.class, \"runInstancesInRegion\", String.class, String.class,\n               String.class, int.class, int.class, RunInstancesOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"eu-west-1\", \"eu-west-1a\", \"ami-voo\",\n               1, 5, new RunInstancesOptions().withKernelId(\"kernelId\").withSecurityGroups(\"group1\", \"group2\")));\n\n      assertRequestLineEquals(request, \"POST https://ec2.eu-west-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.eu-west-1.amazonaws.com\\n\");\n      try {\n         assertPayloadEquals(\n                  request,\n                  \"Action=RunInstances&ImageId=ami-voo&MinCount=1&MaxCount=5&KernelId=kernelId&SecurityGroup.1=group1&SecurityGroup.2=group2&Placement.AvailabilityZone=eu-west-1a\",\n                  \"application/x-www-form-urlencoded\", false);\n      } catch (AssertionError e) {\n         // mvn 3.0 osx 10.6.5 somehow sorts differently\n         assertPayloadEquals(\n                  request,\n                  \"Action=RunInstances&ImageId=ami-voo&MaxCount=5&MinCount=1&KernelId=kernelId&SecurityGroup.1=group1&SecurityGroup.2=group2&Placement.AvailabilityZone=eu-west-1a\",\n                  \"application/x-www-form-urlencoded\", false);\n      }\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, RunInstancesResponseHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testStopInstances() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(InstanceApi.class, \"stopInstancesInRegion\", String.class, boolean.class,\n               String[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, true, \"1\", \"2\"));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, \"Action=StopInstances&Force=true&InstanceId.1=1&InstanceId.2=2\",\n               \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, InstanceStateChangeHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testRebootInstances() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(InstanceApi.class, \"rebootInstancesInRegion\", String.class, String[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"1\", \"2\"));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, \"Action=RebootInstances&InstanceId.1=1&InstanceId.2=2\",\n               \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testStartInstances() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(InstanceApi.class, \"startInstancesInRegion\", String.class, String[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"1\", \"2\"));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, \"Action=StartInstances&InstanceId.1=1&InstanceId.2=2\",\n               \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, InstanceStateChangeHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testGetUserDataForInstanceInRegion() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(InstanceApi.class, \"getUserDataForInstanceInRegion\", String.class, String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"1\"));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request,\n               \"Action=DescribeInstanceAttribute&Attribute=userData&InstanceId=1\",\n               \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, UnencodeStringValueHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testGetRootDeviceNameForInstanceInRegion() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(InstanceApi.class, \"getRootDeviceNameForInstanceInRegion\", String.class,\n               String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"1\"));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request,\n               \"Action=DescribeInstanceAttribute&Attribute=rootDeviceName&InstanceId=1\",\n               \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, StringValueHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testGetRamdiskForInstanceInRegion() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(InstanceApi.class, \"getRamdiskForInstanceInRegion\", String.class, String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"1\"));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request,\n               \"Action=DescribeInstanceAttribute&Attribute=ramdisk&InstanceId=1\",\n               \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, StringValueHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testGetDisableApiTerminationForInstanceInRegion() throws SecurityException, NoSuchMethodException,\n            IOException {\n      Invokable<?, ?> method = method(InstanceApi.class, \"isApiTerminationDisabledForInstanceInRegion\", String.class,\n               String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"1\"));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request,\n               \"Action=DescribeInstanceAttribute&Attribute=disableApiTermination&InstanceId=1\",\n               \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, BooleanValueHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testGetKernelForInstanceInRegion() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(InstanceApi.class, \"getKernelForInstanceInRegion\", String.class, String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"1\"));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, \"Action=DescribeInstanceAttribute&Attribute=kernel&InstanceId=1\",\n               \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, StringValueHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testGetInstanceTypeForInstanceInRegion() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(InstanceApi.class, \"getInstanceTypeForInstanceInRegion\", String.class,\n               String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"1\"));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request,\n               \"Action=DescribeInstanceAttribute&Attribute=instanceType&InstanceId=1\",\n               \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, InstanceTypeHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testGetInstanceInitiatedShutdownBehaviorForInstanceInRegion() throws SecurityException,\n            NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(InstanceApi.class, \"getInstanceInitiatedShutdownBehaviorForInstanceInRegion\",\n               String.class, String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"1\"));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(\n               request,\n               \"Action=DescribeInstanceAttribute&Attribute=instanceInitiatedShutdownBehavior&InstanceId=1\",\n               \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, InstanceInitiatedShutdownBehaviorHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testGetBlockDeviceMappingForInstanceInRegion() throws SecurityException, NoSuchMethodException,\n            IOException {\n      Invokable<?, ?> method = method(InstanceApi.class, \"getBlockDeviceMappingForInstanceInRegion\", String.class,\n               String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"1\"));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request,\n               \"Action=DescribeInstanceAttribute&Attribute=blockDeviceMapping&InstanceId=1\",\n               \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, BlockDeviceMappingHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   HttpRequest setUserDataForInstance = HttpRequest.builder().method(\"POST\")\n                                                   .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                                                   .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                                                   .addFormParam(\"Action\", \"ModifyInstanceAttribute\")\n                                                   .addFormParam(\"Attribute\", \"userData\")\n                                                   .addFormParam(\"InstanceId\", \"1\")\n                                                   .addFormParam(\"Signature\", \"SfxT/1i/WokibleyEHo0zHizHisLzbDzzRxfOdnr1vY=\")\n                                                   .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n                                                   .addFormParam(\"SignatureVersion\", \"2\")\n                                                   .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n                                                   .addFormParam(\"Value\", \"dGVzdA==\")\n                                                   .addFormParam(\"Version\", \"2010-08-31\")\n                                                   .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testSetUserDataForInstanceInRegion() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(InstanceApi.class, \"setUserDataForInstanceInRegion\", String.class, String.class,\n               byte[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"1\", \"test\".getBytes()));\n\n      request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, setUserDataForInstance.getPayload().getRawContent().toString(),\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   HttpRequest setRamdiskForInstance = HttpRequest.builder().method(\"POST\")\n                                                  .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                                                  .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                                                  .addFormParam(\"Action\", \"ModifyInstanceAttribute\")\n                                                  .addFormParam(\"Attribute\", \"ramdisk\")\n                                                  .addFormParam(\"InstanceId\", \"1\")\n                                                  .addFormParam(\"Signature\", \"aMQzFsknmQt1OA8Rb8aIzZoFXGK23UvrMIy8imNVUeQ=\")\n                                                  .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n                                                  .addFormParam(\"SignatureVersion\", \"2\")\n                                                  .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n                                                  .addFormParam(\"Value\", \"test\")\n                                                  .addFormParam(\"Version\", \"2010-08-31\")\n                                                  .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testSetRamdiskForInstanceInRegion() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(InstanceApi.class, \"setRamdiskForInstanceInRegion\", String.class, String.class,\n               String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"1\", \"test\"));\n\n      request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, setRamdiskForInstance.getPayload().getRawContent().toString(),\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   HttpRequest setKernelForInstance = HttpRequest.builder().method(\"POST\")\n                                                 .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                                                 .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                                                 .addFormParam(\"Action\", \"ModifyInstanceAttribute\")\n                                                 .addFormParam(\"Attribute\", \"kernel\")\n                                                 .addFormParam(\"InstanceId\", \"1\")\n                                                 .addFormParam(\"Signature\", \"GaQ9sC0uXHlN5JAMWQpYx+c3XaF38qZgJex/kyqdR1E=\")\n                                                 .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n                                                 .addFormParam(\"SignatureVersion\", \"2\")\n                                                 .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n                                                 .addFormParam(\"Value\", \"test\")\n                                                 .addFormParam(\"Version\", \"2010-08-31\")\n                                                 .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testSetKernelForInstanceInRegion() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(InstanceApi.class, \"setKernelForInstanceInRegion\", String.class, String.class,\n               String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"1\", \"test\"));\n\n      request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, setKernelForInstance.getPayload().getRawContent().toString(),\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   HttpRequest setApiTerminationDisabled = HttpRequest.builder().method(\"POST\")\n                                                      .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                                                      .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                                                      .addFormParam(\"Action\", \"ModifyInstanceAttribute\")\n                                                      .addFormParam(\"Attribute\", \"disableApiTermination\")\n                                                      .addFormParam(\"InstanceId\", \"1\")\n                                                      .addFormParam(\"Signature\", \"hErzi+f4jBADviJ+LVTTGhlHWhMR/pyPUSBZgaHC79I=\")\n                                                      .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n                                                      .addFormParam(\"SignatureVersion\", \"2\")\n                                                      .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n                                                      .addFormParam(\"Value\", \"true\")\n                                                      .addFormParam(\"Version\", \"2010-08-31\")\n                                                      .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testSetApiTerminationDisabledForInstanceInRegion() throws SecurityException, NoSuchMethodException,\n            IOException {\n      Invokable<?, ?> method = method(InstanceApi.class, \"setApiTerminationDisabledForInstanceInRegion\", String.class,\n               String.class, boolean.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"1\", true));\n\n      request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, setApiTerminationDisabled.getPayload().getRawContent().toString(),\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   HttpRequest instanceTypeForInstance = HttpRequest.builder().method(\"POST\")\n                                                    .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                                                    .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                                                    .addFormParam(\"Action\", \"ModifyInstanceAttribute\")\n                                                    .addFormParam(\"Attribute\", \"instanceType\")\n                                                    .addFormParam(\"InstanceId\", \"1\")\n                                                    .addFormParam(\"Signature\", \"OYJQ1w79NoxkcrawNK6U71k3Wl78kqz2ikzTXmQCX2E=\")\n                                                    .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n                                                    .addFormParam(\"SignatureVersion\", \"2\")\n                                                    .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n                                                    .addFormParam(\"Value\", \"c1.medium\")\n                                                    .addFormParam(\"Version\", \"2010-08-31\")\n                                                    .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testSetInstanceTypeForInstanceInRegion() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(InstanceApi.class, \"setInstanceTypeForInstanceInRegion\", String.class,\n               String.class, String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"1\", InstanceType.C1_MEDIUM));\n\n      request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, instanceTypeForInstance.getPayload().getRawContent().toString(),\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   HttpRequest setInstanceInitiatedShutdownBehavior = HttpRequest.builder().method(\"POST\")\n                                                                 .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                                                                 .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                                                                 .addFormParam(\"Action\", \"ModifyInstanceAttribute\")\n                                                                 .addFormParam(\"Attribute\", \"instanceInitiatedShutdownBehavior\")\n                                                                 .addFormParam(\"InstanceId\", \"1\")\n                                                                 .addFormParam(\"Signature\", \"2Tgi9M9AcCv5Y+EXwq0SD6g8bBGtPPEgjdTtfdGZQlI=\")\n                                                                 .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n                                                                 .addFormParam(\"SignatureVersion\", \"2\")\n                                                                 .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n                                                                 .addFormParam(\"Value\", \"terminate\")\n                                                                 .addFormParam(\"Version\", \"2010-08-31\")\n                                                                 .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testSetInstanceInitiatedShutdownBehaviorForInstanceInRegion() throws SecurityException,\n            NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(InstanceApi.class, \"setInstanceInitiatedShutdownBehaviorForInstanceInRegion\",\n               String.class, String.class, InstanceInitiatedShutdownBehavior.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"1\", InstanceInitiatedShutdownBehavior.TERMINATE));\n\n      request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, setInstanceInitiatedShutdownBehavior.getPayload().getRawContent().toString(),\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   HttpRequest setBlockDeviceMapping = HttpRequest.builder().method(\"POST\")\n                                                           .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                                                           .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                                                           .addFormParam(\"Action\", \"ModifyInstanceAttribute\")\n                                                           .addFormParam(\"BlockDeviceMapping.1.DeviceName\", \"/dev/sda1\")\n                                                           .addFormParam(\"BlockDeviceMapping.1.Ebs.DeleteOnTermination\", \"true\")\n                                                           .addFormParam(\"BlockDeviceMapping.1.Ebs.VolumeId\", \"vol-test1\")\n                                                           .addFormParam(\"InstanceId\", \"1\").build();\n\n   public void testSetBlockDeviceMappingForInstanceInRegion() throws SecurityException, NoSuchMethodException,\n            IOException {\n      Invokable<?, ?> method = method(InstanceApi.class, \"setBlockDeviceMappingForInstanceInRegion\", String.class,\n               String.class, Map.class);\n\n      Map<String, BlockDevice> mapping = Maps.newLinkedHashMap();\n      mapping.put(\"/dev/sda1\", new BlockDevice(\"vol-test1\", true));\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"1\", mapping));\n\n      request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, filter.filter(setBlockDeviceMapping).getPayload().getRawContent().toString(),\n            \"application/x-www-form-urlencoded\", false);\n\n\n      checkFilters(request);\n   }\n\n   public void testGetConsoleOutputForInstanceInRegion() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(InstanceApi.class, \"getConsoleOutputForInstanceInRegion\", String.class, String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"1\"));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request,\n               \"Action=GetConsoleOutput&InstanceId=1\",\n               \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, GetConsoleOutputResponseHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/features/KeyPairApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.features;\n\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.domain.KeyPair;\nimport org.jclouds.ec2.internal.BaseEC2ApiExpectTest;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\", testName = \"KeyPairApiExpectTest\")\npublic class KeyPairApiExpectTest extends BaseEC2ApiExpectTest<EC2Api> {\n\n   HttpRequest filter = HttpRequest.builder().method(\"POST\")\n           .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n           .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n           .addFormParam(\"Action\", \"DescribeKeyPairs\")\n           .addFormParam(\"Filter.1.Name\", \"key-name\")\n           .addFormParam(\"Filter.1.Value.1\", \"gsg-keypair\")\n           .addFormParam(\"Signature\", \"xg8vGx+v9UEG0+FGy+hincdI2ziWLbwPJvW85l+vqwg=\")\n           .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n           .addFormParam(\"SignatureVersion\", \"2\")\n           .addFormParam(\"Timestamp\", \"2012-04-16T15:54:08.897Z\")\n           .addFormParam(\"Version\", \"2010-08-31\")\n           .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testFilterWhenResponseIs2xx() {\n      HttpResponse filterResponse = HttpResponse.builder().statusCode(200)\n              .payload(payloadFromResourceWithContentType(\"/describe_keypairs.xml\", \"text/xml\")).build();\n\n      EC2Api apiWhenExist = requestsSendResponses(describeRegionsRequest, describeRegionsResponse, filter, filterResponse);\n\n      KeyPair keyPair = getOnlyElement(apiWhenExist.getKeyPairApi().get().describeKeyPairsInRegionWithFilter(\"us-east-1\",\n              ImmutableMultimap.<String, String>builder()\n                      .put(\"key-name\", \"gsg-keypair\")\n                      .build()));\n\n      assertEquals(keyPair.getKeyName(), \"gsg-keypair\");\n   }\n\n   public void testFilterWhenResponseIs404() {\n      HttpResponse filterResponse = HttpResponse.builder().statusCode(404).build();\n\n      EC2Api apiWhenNotExist = requestsSendResponses(describeRegionsRequest, describeRegionsResponse, filter, filterResponse);\n\n      assertEquals(apiWhenNotExist.getKeyPairApi().get().describeKeyPairsInRegionWithFilter(\"us-east-1\",\n              ImmutableMultimap.<String, String>builder()\n                      .put(\"key-name\", \"gsg-keypair\")\n                      .build()),\n              ImmutableSet.of());\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/features/KeyPairApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.Set;\nimport java.util.SortedSet;\n\nimport org.jclouds.aws.AWSResponseException;\nimport org.jclouds.compute.internal.BaseComputeServiceContextLiveTest;\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.domain.KeyPair;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.Sets;\n\n/**\n * Tests behavior of {@code KeyPairApi}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"KeyPairApiLiveTest\")\npublic class KeyPairApiLiveTest extends BaseComputeServiceContextLiveTest {\n   public KeyPairApiLiveTest() {\n      provider = \"ec2\";\n   }\n\n   private EC2Api ec2Api;\n   private KeyPairApi client;\n   \n   @Override\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   public void setupContext() {\n      super.setupContext();\n      ec2Api = view.unwrapApi(EC2Api.class);\n      client = ec2Api.getKeyPairApi().get();\n   }\n\n   @Test\n   void testDescribeKeyPairs() {\n      for (String region : ec2Api.getConfiguredRegions()) {\n         SortedSet<KeyPair> allResults = Sets.newTreeSet(client.describeKeyPairsInRegion(region));\n         assertNotNull(allResults);\n         if (!allResults.isEmpty()) {\n            KeyPair pair = allResults.last();\n            SortedSet<KeyPair> result = Sets.newTreeSet(client.describeKeyPairsInRegion(region, pair.getKeyName()));\n            assertNotNull(result);\n            KeyPair compare = result.last();\n            assertEquals(compare, pair);\n         }\n      }\n   }\n\n   @Test\n   void testDescribeKeyPairsWithFilter() {\n      for (String region : ec2Api.getConfiguredRegions()) {\n         SortedSet<KeyPair> allResults = Sets.newTreeSet(client.describeKeyPairsInRegion(region));\n         assertNotNull(allResults);\n         if (!allResults.isEmpty()) {\n            KeyPair pair = allResults.last();\n            SortedSet<KeyPair> result = Sets.newTreeSet(client.describeKeyPairsInRegionWithFilter(region,\n                    ImmutableMultimap.<String, String>builder()\n                            .put(\"key-name\", pair.getKeyName()).build()));\n            assertNotNull(result);\n            KeyPair compare = result.last();\n            assertEquals(compare, pair);\n         }\n      }\n   }\n\n   @Test(expectedExceptions = AWSResponseException.class)\n   void testDescribeKeyPairsWithInvalidFilter() {\n      for (String region : ec2Api.getConfiguredRegions()) {\n         SortedSet<KeyPair> allResults = Sets.newTreeSet(client.describeKeyPairsInRegion(region));\n         assertNotNull(allResults);\n         if (!allResults.isEmpty()) {\n            KeyPair pair = allResults.last();\n            client.describeKeyPairsInRegionWithFilter(region,\n                    ImmutableMultimap.<String, String>builder()\n                            .put(\"invalid-filter\", pair.getKeyName()).build());\n         }\n      }\n   }\n\n   public static final String PREFIX = System.getProperty(\"user.name\") + \"-ec2\";\n\n   @Test\n   void testCreateKeyPair() {\n      String keyName = PREFIX + \"1\";\n      try {\n         client.deleteKeyPairInRegion(null, keyName);\n      } catch (Exception e) {\n\n      }\n      client.deleteKeyPairInRegion(null, keyName);\n\n      KeyPair result = client.createKeyPairInRegion(null, keyName);\n      assertNotNull(result);\n      assertNotNull(result.getKeyMaterial());\n      assertNotNull(result.getSha1OfPrivateKey());\n      assertEquals(result.getKeyName(), keyName);\n\n      Set<KeyPair> twoResults = Sets.newLinkedHashSet(client.describeKeyPairsInRegion(null, keyName));\n      assertNotNull(twoResults);\n      assertEquals(twoResults.size(), 1);\n      KeyPair listPair = twoResults.iterator().next();\n      assertEquals(listPair.getKeyName(), result.getKeyName());\n      assertEquals(listPair.getSha1OfPrivateKey(), result.getSha1OfPrivateKey());\n   }\n\n   @AfterClass(groups = { \"integration\", \"live\" })\n   @Override\n   protected void tearDownContext() {\n      String keyName = PREFIX + \"1\";\n      try {\n         client.deleteKeyPairInRegion(null, keyName);\n      } catch (Exception e) {\n\n      }\n\n      super.tearDownContext();\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/features/KeyPairApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.features;\n\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport java.io.IOException;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.ec2.xml.DescribeKeyPairsResponseHandler;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.http.functions.ReleasePayloadAndReturn;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Lists;\nimport com.google.common.reflect.Invokable;\n/**\n * Tests behavior of {@code KeyPairApi}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"KeyPairApiTest\")\npublic class KeyPairApiTest extends BaseEC2ApiTest<KeyPairApi> {\n\n   public void testDeleteKeyPair() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(KeyPairApi.class, \"deleteKeyPairInRegion\", String.class, String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"mykey\"));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, \"Action=DeleteKeyPair&KeyName=mykey\",\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testDescribeKeyPairs() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(KeyPairApi.class, \"describeKeyPairsInRegion\", String.class, String[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList((String) null));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, \"Action=DescribeKeyPairs\", \"application/x-www-form-urlencoded\",\n            false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, DescribeKeyPairsResponseHandler.class);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(request);\n   }\n\n   public void testDescribeKeyPairsArgs() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(KeyPairApi.class, \"describeKeyPairsInRegion\", String.class, String[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"1\", \"2\"));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, \"Action=DescribeKeyPairs&KeyName.1=1&KeyName.2=2\",\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, DescribeKeyPairsResponseHandler.class);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(request);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/features/SecurityGroupApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.features;\n\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.domain.SecurityGroup;\nimport org.jclouds.ec2.internal.BaseEC2ApiExpectTest;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\", testName = \"SecurityGroupApiExpectTest\")\npublic class SecurityGroupApiExpectTest extends BaseEC2ApiExpectTest<EC2Api> {\n\n   HttpRequest filter = HttpRequest.builder().method(\"POST\")\n           .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n           .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n           .addFormParam(\"Action\", \"DescribeSecurityGroups\")\n           .addFormParam(\"Filter.1.Name\", \"owner-id\")\n           .addFormParam(\"Filter.1.Value.1\", \"993194456877\")\n           .addFormParam(\"Signature\", \"zk8EEWkG9Hi0bBLPueF9WdTUKapxQqUXgyJTxeZHXBc=\")\n           .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n           .addFormParam(\"SignatureVersion\", \"2\")\n           .addFormParam(\"Timestamp\", \"2012-04-16T15:54:08.897Z\")\n           .addFormParam(\"Version\", \"2010-08-31\")\n           .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   HttpRequest deleteById = HttpRequest.builder().method(\"POST\")\n         .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n         .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n         .addFormParam(\"Action\", \"DeleteSecurityGroup\")\n         .addFormParam(\"GroupId\", \"sg-3c6ef654\")\n         .addFormParam(\"Signature\", \"FhFx9Uv587s+86KuCOngA2x3DiLRuRrkyd0ZTrXAYbc=\")\n         .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n         .addFormParam(\"SignatureVersion\", \"2\")\n         .addFormParam(\"Timestamp\", \"2012-04-16T15:54:08.897Z\")\n         .addFormParam(\"Version\", \"2010-08-31\")\n         .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   HttpRequest deleteByName = HttpRequest.builder().method(\"POST\")\n         .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n         .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n         .addFormParam(\"Action\", \"DeleteSecurityGroup\")\n         .addFormParam(\"GroupName\", \"jclouds#some-group\")\n         .addFormParam(\"Signature\", \"Jw9ZpWcnAEPaNtZNZBsMyOUUFP1qGETKUzvHiAOz5C8=\")\n         .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n         .addFormParam(\"SignatureVersion\", \"2\")\n         .addFormParam(\"Timestamp\", \"2012-04-16T15:54:08.897Z\")\n         .addFormParam(\"Version\", \"2010-08-31\")\n         .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testFilterWhenResponseIs2xx() {\n      HttpResponse filterResponse = HttpResponse.builder().statusCode(200)\n              .payload(payloadFromResourceWithContentType(\"/describe_securitygroups_extension_single.xml\", \"text/xml\")).build();\n\n      EC2Api apiWhenExist = requestsSendResponses(describeRegionsRequest, describeRegionsResponse, filter, filterResponse);\n\n      SecurityGroup group = getOnlyElement(apiWhenExist.getSecurityGroupApi().get().describeSecurityGroupsInRegionWithFilter(\"us-east-1\",\n              ImmutableMultimap.<String, String>builder()\n                      .put(\"owner-id\", \"993194456877\")\n                      .build()));\n\n      assertEquals(group.getId(), \"sg-3c6ef654\");\n   }\n\n   public void testFilterWhenResponseIs404() {\n      HttpResponse filterResponse = HttpResponse.builder().statusCode(404).build();\n\n      EC2Api apiWhenNotExist = requestsSendResponses(describeRegionsRequest, describeRegionsResponse, filter, filterResponse);\n\n      assertEquals(apiWhenNotExist.getSecurityGroupApi().get().describeSecurityGroupsInRegionWithFilter(\"us-east-1\",\n              ImmutableMultimap.<String, String>builder()\n                      .put(\"owner-id\", \"993194456877\")\n                      .build()),\n              ImmutableSet.of());\n   }\n   \n   public void testDeleteSecurityGroupById() {\n      HttpResponse deleteResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResourceWithContentType(\"/delete_securitygroup.xml\", \"text/xml\")).build();\n\n      EC2Api apiWhenNotExist = requestsSendResponses(\n            describeRegionsRequest, describeRegionsResponse, \n            deleteById, deleteResponse);\n\n      apiWhenNotExist.getSecurityGroupApi().get().deleteSecurityGroupInRegionById(\"us-east-1\", \"sg-3c6ef654\");\n   }\n   \n   public void testDeleteSecurityGroupByIdWhen404() {\n      HttpResponse deleteResponse = HttpResponse.builder().statusCode(404).build();\n\n      EC2Api apiWhenNotExist = requestsSendResponses(\n            describeRegionsRequest, describeRegionsResponse, \n            deleteById, deleteResponse);\n\n      apiWhenNotExist.getSecurityGroupApi().get().deleteSecurityGroupInRegionById(\"us-east-1\", \"sg-3c6ef654\");\n   }\n   \n   public void testDeleteSecurityGroupByName() {\n      HttpResponse deleteResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResourceWithContentType(\"/delete_securitygroup.xml\", \"text/xml\")).build();\n\n      EC2Api apiWhenNotExist = requestsSendResponses(\n            describeRegionsRequest, describeRegionsResponse, \n            deleteByName, deleteResponse);\n\n      apiWhenNotExist.getSecurityGroupApi().get().deleteSecurityGroupInRegion(\"us-east-1\", \"jclouds#some-group\");\n   }\n   \n   public void testDeleteSecurityGroupByNameWhen404() {\n      HttpResponse deleteResponse = HttpResponse.builder().statusCode(404).build();\n\n      EC2Api apiWhenNotExist = requestsSendResponses(\n            describeRegionsRequest, describeRegionsResponse, \n            deleteByName, deleteResponse);\n\n      apiWhenNotExist.getSecurityGroupApi().get().deleteSecurityGroupInRegion(\"us-east-1\", \"jclouds#some-group\");\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/features/SecurityGroupApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.features;\n\nimport static com.google.common.base.Predicates.compose;\nimport static com.google.common.base.Predicates.in;\nimport static com.google.common.collect.Iterables.all;\nimport static com.google.common.collect.Iterables.getLast;\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\n\nimport org.jclouds.aws.AWSResponseException;\nimport org.jclouds.compute.internal.BaseComputeServiceContextLiveTest;\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.domain.SecurityGroup;\nimport org.jclouds.ec2.domain.UserIdGroupPair;\nimport org.jclouds.net.domain.IpPermission;\nimport org.jclouds.net.domain.IpProtocol;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code SecurityGroupApi}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"SecurityGroupApiLiveTest\")\npublic class SecurityGroupApiLiveTest extends BaseComputeServiceContextLiveTest {\n   public SecurityGroupApiLiveTest() {\n      provider = \"ec2\";\n   }\n\n   protected EC2Api ec2Api;\n   protected SecurityGroupApi client;\n\n   @Override\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   public void setupContext() {\n      super.setupContext();\n      ec2Api = view.unwrapApi(EC2Api.class);\n      client = ec2Api.getSecurityGroupApi().get();\n   }\n\n   @Test\n   void testDescribe() {\n      for (String region : ec2Api.getConfiguredRegions()) {\n         Set<SecurityGroup> allResults = client.describeSecurityGroupsInRegion(region);\n         assertNotNull(allResults);\n         if (!allResults.isEmpty()) {\n            final SecurityGroup group = getLast(allResults);\n            // in case there are multiple groups with the same name, which is the case with VPC\n            ImmutableSet<SecurityGroup> expected = FluentIterable.from(allResults)\n                    .filter(new Predicate<SecurityGroup>() {\n                       @Override\n                       public boolean apply(SecurityGroup in) {\n                          return group.getName().equals(in.getName());\n                       }\n                    }).toSet();\n            ImmutableSet<SecurityGroup> result = ImmutableSet.copyOf(client.describeSecurityGroupsInRegion(region,\n                    group.getName()));\n            // the above command has a chance of returning less groups than the original\n            assertTrue(expected.containsAll(result), \"group(s) for name not found\");\n         }\n      }\n   }\n\n   @Test\n   void testFilter() {\n      for (String region : ec2Api.getConfiguredRegions()) {\n         Set<SecurityGroup> allResults = client.describeSecurityGroupsInRegion(region);\n         assertNotNull(allResults);\n         if (!allResults.isEmpty()) {\n            final SecurityGroup group = getLast(allResults);\n            // in case there are multiple groups with the same name, which is the case with VPC\n            ImmutableSet<SecurityGroup> expected = FluentIterable.from(allResults)\n                    .filter(new Predicate<SecurityGroup>() {\n                       @Override\n                       public boolean apply(SecurityGroup in) {\n                          return group.getName().equals(in.getName());\n                       }\n                    }).toSet();\n            ImmutableSet<SecurityGroup> result = ImmutableSet.copyOf(client.describeSecurityGroupsInRegionWithFilter(region,\n                    ImmutableMultimap.<String, String>builder()\n                            .put(\"group-name\", group.getName()).build()));\n            // the above command has a chance of returning less groups than the original\n            assertTrue(expected.containsAll(result), \"group(s) for name not found\");\n         }\n      }\n   }\n\n   @Test(expectedExceptions = AWSResponseException.class)\n   void testFilterInvalid() {\n      for (String region : ec2Api.getConfiguredRegions()) {\n         Set<SecurityGroup> allResults = client.describeSecurityGroupsInRegion(region);\n         assertNotNull(allResults);\n         if (!allResults.isEmpty()) {\n            final SecurityGroup group = getLast(allResults);\n            // in case there are multiple groups with the same name, which is the case with VPC\n            ImmutableSet<SecurityGroup> expected = FluentIterable.from(allResults)\n                    .filter(new Predicate<SecurityGroup>() {\n                       @Override\n                       public boolean apply(SecurityGroup in) {\n                          return group.getName().equals(in.getName());\n                       }\n                    }).toSet();\n            ImmutableSet<SecurityGroup> result = ImmutableSet.copyOf(client.describeSecurityGroupsInRegionWithFilter(region,\n                    ImmutableMultimap.<String, String>builder()\n                            .put(\"invalid-filter\", group.getName()).build()));\n         }\n      }\n   }\n\n   @Test\n   void testCreateSecurityGroup() {\n      String groupName = PREFIX + \"1\";\n      cleanupAndSleep(groupName);\n      try {\n         String groupDescription = PREFIX + \"1 description\";\n         client.deleteSecurityGroupInRegion(null, groupName);\n         client.createSecurityGroupInRegion(null, groupName, groupDescription);\n         verifySecurityGroup(groupName, groupDescription);\n      } finally {\n         client.deleteSecurityGroupInRegion(null, groupName);\n      }\n   }\n\n   protected void cleanupAndSleep(String groupName) {\n      try {\n         client.deleteSecurityGroupInRegion(null, groupName);\n         Thread.sleep(2000);\n      } catch (Exception e) {\n\n      }\n   }\n\n   @Test\n   void testAuthorizeSecurityGroupIngressCidr() {\n      String groupName = PREFIX + \"ingress\";\n      cleanupAndSleep(groupName);\n      try {\n         client.createSecurityGroupInRegion(null, groupName, groupName);\n         client.authorizeSecurityGroupIngressInRegion(null, groupName, IpProtocol.TCP, 80, 80, \"0.0.0.0/0\");\n         assertEventually(new GroupHasPermission(client, groupName, new TCPPort80AllIPs()));\n\n         client.revokeSecurityGroupIngressInRegion(null, groupName, IpProtocol.TCP, 80, 80, \"0.0.0.0/0\");\n         assertEventually(new GroupHasNoPermissions(client, groupName));\n      } finally {\n         client.deleteSecurityGroupInRegion(null, groupName);\n      }\n   }\n\n   @Test\n   void testAuthorizeSecurityGroupIngressSourcePort() {\n      String groupName = PREFIX + \"ingress\";\n      cleanupAndSleep(groupName);\n      try {\n         client.createSecurityGroupInRegion(null, groupName, groupName);\n         client.authorizeSecurityGroupIngressInRegion(null, groupName, IpProtocol.TCP, 80, 80, \"0.0.0.0/0\");\n         assertEventually(new GroupHasPermission(client, groupName, new TCPPort80AllIPs()));\n\n         client.revokeSecurityGroupIngressInRegion(null, groupName, IpProtocol.TCP, 80, 80, \"0.0.0.0/0\");\n         assertEventually(new GroupHasNoPermissions(client, groupName));\n      } finally {\n         client.deleteSecurityGroupInRegion(null, groupName);\n      }\n   }\n\n   private void verifySecurityGroup(String groupName, String description) {\n      Set<SecurityGroup> oneResult = client.describeSecurityGroupsInRegion(null, groupName);\n      assertNotNull(oneResult);\n      assertEquals(oneResult.size(), 1);\n      SecurityGroup listPair = oneResult.iterator().next();\n      assertEquals(listPair.getName(), groupName);\n      assertEquals(listPair.getDescription(), description);\n   }\n\n   @Test\n   void testAuthorizeSecurityGroupIngressSourceGroup() {\n      final String group1Name = PREFIX + \"ingress1\";\n      String group2Name = PREFIX + \"ingress2\";\n      cleanupAndSleep(group2Name);\n      cleanupAndSleep(group1Name);\n      try {\n         client.createSecurityGroupInRegion(null, group1Name, group1Name);\n         client.createSecurityGroupInRegion(null, group2Name, group2Name);\n         ensureGroupsExist(group1Name, group2Name);\n         client.authorizeSecurityGroupIngressInRegion(null, group1Name, IpProtocol.TCP, 80, 80, \"0.0.0.0/0\");\n         assertEventually(new GroupHasPermission(client, group1Name, new TCPPort80AllIPs()));\n         Set<SecurityGroup> oneResult = client.describeSecurityGroupsInRegion(null, group1Name);\n         assertNotNull(oneResult);\n         assertEquals(oneResult.size(), 1);\n         final SecurityGroup group = oneResult.iterator().next();\n         assertEquals(group.getName(), group1Name);\n         final UserIdGroupPair to = new UserIdGroupPair(group.getOwnerId(), group1Name);\n         client.authorizeSecurityGroupIngressInRegion(null, group2Name, to);\n         assertEventually(new GroupHasPermission(client, group2Name, new Predicate<IpPermission>() {\n            @Override\n            public boolean apply(IpPermission arg0) {\n               return arg0.getTenantIdGroupNamePairs().equals(ImmutableMultimap.of(group.getOwnerId(), group1Name));\n            }\n         }));\n\n         client.revokeSecurityGroupIngressInRegion(null, group2Name,\n               new UserIdGroupPair(group.getOwnerId(), group1Name));\n         assertEventually(new GroupHasNoPermissions(client, group2Name));\n      } finally {\n         client.deleteSecurityGroupInRegion(null, group2Name);\n         client.deleteSecurityGroupInRegion(null, group1Name);\n      }\n   }\n\n   public static final class TCPPort80AllIPs implements Predicate<IpPermission> {\n      @Override\n      public boolean apply(IpPermission arg0) {\n         return arg0.getIpProtocol() == IpProtocol.TCP && arg0.getFromPort() == 80 && arg0.getToPort() == 80\n               && arg0.getCidrBlocks().equals(ImmutableSet.of(\"0.0.0.0/0\"));\n      }\n   }\n\n   public static final class GroupHasPermission implements Runnable {\n      private final SecurityGroupApi client;\n      private final String group;\n      private final Predicate<IpPermission> permission;\n\n      public GroupHasPermission(SecurityGroupApi client, String group, Predicate<IpPermission> permission) {\n         this.client = client;\n         this.group = group;\n         this.permission = permission;\n      }\n\n      public void run() {\n         try {\n            Set<SecurityGroup> oneResult = client.describeSecurityGroupsInRegion(null, group);\n            assert all(getOnlyElement(oneResult), permission) : permission\n                  + \": \" + oneResult;\n         } catch (Exception e) {\n            throw new AssertionError(e);\n         }\n      }\n   }\n\n   public static final class GroupHasNoPermissions implements Runnable {\n      private final SecurityGroupApi client;\n      private final String group;\n\n      public GroupHasNoPermissions(SecurityGroupApi client, String group) {\n         this.client = client;\n         this.group = group;\n      }\n\n      public void run() {\n         try {\n            Set<SecurityGroup> oneResult = client.describeSecurityGroupsInRegion(null, group);\n            assertNotNull(oneResult);\n            assertEquals(oneResult.size(), 1);\n            SecurityGroup listPair = oneResult.iterator().next();\n            assertEquals(listPair.size(), 0);\n         } catch (Exception e) {\n            throw new AssertionError(e);\n         }\n      }\n   }\n\n   protected void ensureGroupsExist(String group1Name, String group2Name) {\n      Set<SecurityGroup> twoResults = client.describeSecurityGroupsInRegion(null, group1Name, group2Name);\n      assertNotNull(twoResults);\n      assertTrue(twoResults.size() >= 2);  // in VPC could be multiple groups with the same name\n\n      assertTrue(all(twoResults, compose(in(ImmutableSet.of(group1Name, group2Name)),\n            new Function<SecurityGroup, String>() {\n               @Override\n               public String apply(SecurityGroup in) {\n                  return in.getName();\n               }\n            })));\n   }\n\n   private static final int INCONSISTENCY_WINDOW = 5000;\n\n   /**\n    * Due to eventual consistency, container commands may not return correctly\n    * immediately. Hence, we will try up to the inconsistency window to see if\n    * the assertion completes.\n    */\n   protected static void assertEventually(Runnable assertion) {\n      long start = System.currentTimeMillis();\n      AssertionError error = null;\n      for (int i = 0; i < 30; i++) {\n         try {\n            assertion.run();\n            if (i > 0)\n               System.err.printf(\"%d attempts and %dms asserting %s%n\", i + 1, System.currentTimeMillis() - start,\n                     assertion.getClass().getSimpleName());\n            return;\n         } catch (AssertionError e) {\n            error = e;\n         }\n         try {\n            Thread.sleep(INCONSISTENCY_WINDOW / 30);\n         } catch (InterruptedException e) {\n         }\n      }\n      if (error != null)\n         throw error;\n\n   }\n\n   public static final String PREFIX = System.getProperty(\"user.name\") + \"-ec2\";\n\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/features/SecurityGroupApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.features;\n\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport java.io.IOException;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.ec2.domain.UserIdGroupPair;\nimport org.jclouds.ec2.xml.DescribeSecurityGroupsResponseHandler;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.http.functions.ReleasePayloadAndReturn;\nimport org.jclouds.net.domain.IpProtocol;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Lists;\nimport com.google.common.reflect.Invokable;\n/**\n * Tests behavior of {@code SecurityGroupApi}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"SecurityGroupApiTest\")\npublic class SecurityGroupApiTest extends BaseEC2ApiTest<SecurityGroupApi> {\n\n   public void testDeleteSecurityGroup() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(SecurityGroupApi.class, \"deleteSecurityGroupInRegion\", String.class,\n            String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"name\"));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, \"Action=DeleteSecurityGroup&GroupName=name\",\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, VoidOnNotFoundOr404.class);\n\n      checkFilters(request);\n   }\n\n   HttpRequest createSecurityGroup = HttpRequest.builder().method(\"POST\")\n                                                .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                                                .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                                                .addFormParam(\"Action\", \"CreateSecurityGroup\")\n                                                .addFormParam(\"GroupDescription\", \"description\")\n                                                .addFormParam(\"GroupName\", \"name\")\n                                                .addFormParam(\"Signature\", \"msp9zFJLrRXYsVu/vbSZE8tQVS/TEvF0Cu/ldYVFdcA=\")\n                                                .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n                                                .addFormParam(\"SignatureVersion\", \"2\")\n                                                .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n                                                .addFormParam(\"Version\", \"2010-08-31\")\n                                                .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testCreateSecurityGroup() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(SecurityGroupApi.class, \"createSecurityGroupInRegion\", String.class,\n            String.class, String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"name\", \"description\"));\n\n      request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);\n      \n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, createSecurityGroup.getPayload().getRawContent().toString(),\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testDescribeSecurityGroups() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(SecurityGroupApi.class, \"describeSecurityGroupsInRegion\", String.class,\n            String[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList((String) null));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, \"Action=DescribeSecurityGroups\",\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, DescribeSecurityGroupsResponseHandler.class);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(request);\n   }\n\n   public void testDescribeSecurityGroupsArgs() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(SecurityGroupApi.class, \"describeSecurityGroupsInRegion\", String.class,\n            String[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"1\", \"2\"));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, \"Action=DescribeSecurityGroups&GroupName.1=1&GroupName.2=2\",\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, DescribeSecurityGroupsResponseHandler.class);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(request);\n   }\n\n   public void testAuthorizeSecurityGroupIngressGroup() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(SecurityGroupApi.class, \"authorizeSecurityGroupIngressInRegion\", String.class,\n            String.class, UserIdGroupPair.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"group\", new UserIdGroupPair(\"sourceUser\",\n            \"sourceGroup\")));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(\n            request,\n            \"Action=AuthorizeSecurityGroupIngress&GroupName=group&SourceSecurityGroupOwnerId=sourceUser&SourceSecurityGroupName=sourceGroup\",\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   HttpRequest authorizeSecurityGroupIngressCidr = HttpRequest.builder().method(\"POST\")\n                                                              .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                                                              .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                                                              .addFormParam(\"Action\", \"AuthorizeSecurityGroupIngress\")\n                                                              .addFormParam(\"CidrIp\", \"0.0.0.0/0\")\n                                                              .addFormParam(\"FromPort\", \"6000\")\n                                                              .addFormParam(\"GroupName\", \"group\")\n                                                              .addFormParam(\"IpProtocol\", \"tcp\")\n                                                              .addFormParam(\"Signature\", \"xeaZpQ1Lvhp+qETpEzOPGHW6isAWYwgtBdCnTqWzkAw=\")\n                                                              .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n                                                              .addFormParam(\"SignatureVersion\", \"2\")\n                                                              .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n                                                              .addFormParam(\"ToPort\", \"7000\")\n                                                              .addFormParam(\"Version\", \"2010-08-31\")\n                                                              .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testAuthorizeSecurityGroupIngressCidr() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(SecurityGroupApi.class, \"authorizeSecurityGroupIngressInRegion\", String.class,\n            String.class, IpProtocol.class, int.class, int.class, String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"group\", IpProtocol.TCP, 6000, 7000, \"0.0.0.0/0\"));\n\n      request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);\n      \n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertPayloadEquals(request, authorizeSecurityGroupIngressCidr.getPayload().getRawContent().toString(),\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testRevokeSecurityGroupIngressGroup() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(SecurityGroupApi.class, \"revokeSecurityGroupIngressInRegion\", String.class,\n            String.class, UserIdGroupPair.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"group\", new UserIdGroupPair(\"sourceUser\",\n            \"sourceGroup\")));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(\n            request,\n            \"Action=RevokeSecurityGroupIngress&GroupName=group&SourceSecurityGroupOwnerId=sourceUser&SourceSecurityGroupName=sourceGroup\",\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   HttpRequest revokeSecurityGroupIngressCidr = HttpRequest.builder().method(\"POST\")\n                                                           .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                                                           .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                                                           .addFormParam(\"Action\", \"RevokeSecurityGroupIngress\")\n                                                           .addFormParam(\"CidrIp\", \"0.0.0.0/0\")\n                                                           .addFormParam(\"FromPort\", \"6000\")\n                                                           .addFormParam(\"GroupName\", \"group\")\n                                                           .addFormParam(\"IpProtocol\", \"tcp\")\n                                                           .addFormParam(\"Signature\", \"P5lxCXMwz6FE8Wo79nEMh8clgLDK3rZxCPRTOKssKKQ=\")\n                                                           .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n                                                           .addFormParam(\"SignatureVersion\", \"2\")\n                                                           .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n                                                           .addFormParam(\"ToPort\", \"7000\")\n                                                           .addFormParam(\"Version\", \"2010-08-31\")\n                                                           .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testRevokeSecurityGroupIngressCidr() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(SecurityGroupApi.class, \"revokeSecurityGroupIngressInRegion\", String.class,\n            String.class, IpProtocol.class, int.class, int.class, String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"group\", IpProtocol.TCP, 6000, 7000, \"0.0.0.0/0\"));\n\n      request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);\n      \n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, revokeSecurityGroupIngressCidr.getPayload().getRawContent().toString(),\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/features/SubnetApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.features;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Properties;\n\nimport org.jclouds.Constants;\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.internal.BaseEC2ApiExpectTest;\nimport org.jclouds.ec2.parse.DescribeSubnetsResponseTest;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\")\npublic class SubnetApiExpectTest extends BaseEC2ApiExpectTest<EC2Api> {\n\n   /**\n    * @see SubnetApi\n    * @see SinceApiVersion\n    */\n   protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      props.put(Constants.PROPERTY_API_VERSION, \"2011-01-01\");\n      return props;\n   }\n\n   HttpRequest list = HttpRequest.builder().method(\"POST\")\n                                 .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                                 .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                                 .addFormParam(\"Action\", \"DescribeSubnets\")\n                                 .addFormParam(\"Signature\", \"Uuafp9lnYQmMUcf/JE1epPTQVCSMPqfns+wlZssUsi4=\")\n                                 .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n                                 .addFormParam(\"SignatureVersion\", \"2\")\n                                 .addFormParam(\"Timestamp\", \"2012-04-16T15:54:08.897Z\")\n                                 .addFormParam(\"Version\", \"2011-01-01\")\n                                 .addFormParam(\"AWSAccessKeyId\", \"identity\")\n                                 .build();\n\n   public void testListWhenResponseIs2xx() throws Exception {\n\n      HttpResponse listResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResourceWithContentType(\"/describe_subnets.xml\", \"text/xml\")).build();\n\n      EC2Api apiWhenExist = requestSendsResponse(\n            list, listResponse);\n\n      assertEquals(apiWhenExist.getSubnetApi().get().list().toString(), new DescribeSubnetsResponseTest().expected().toString());\n   }\n\n   public void testListWhenResponseIs404() throws Exception {\n\n      HttpResponse listResponse = HttpResponse.builder().statusCode(404).build();\n\n      EC2Api apiWhenDontExist = requestSendsResponse(\n            list, listResponse);\n\n      assertEquals(apiWhenDontExist.getSubnetApi().get().list().toSet(), ImmutableSet.of());\n   }\n   \n   HttpRequest filter = HttpRequest.builder().method(\"POST\")\n                                   .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                                   .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                                   .addFormParam(\"Action\", \"DescribeSubnets\")\n                                   .addFormParam(\"Filter.1.Name\", \"subnet-id\")\n                                   .addFormParam(\"Filter.1.Value.1\", \"subnet-9d4a7b6c\")\n                                   .addFormParam(\"Signature\", \"+p34YACfLk9km1H3eALnDmrkst9FhJttojVSf7VztLk=\")\n                                   .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n                                   .addFormParam(\"SignatureVersion\", \"2\")\n                                   .addFormParam(\"Timestamp\", \"2012-04-16T15:54:08.897Z\")\n                                   .addFormParam(\"Version\", \"2011-01-01\")\n                                   .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testFilterWhenResponseIs2xx() throws Exception {\n      \n      HttpResponse filterResponse = HttpResponse.builder().statusCode(200)\n               .payload(payloadFromResourceWithContentType(\"/describe_subnets.xml\", \"text/xml\")).build();\n\n      EC2Api apiWhenExist = requestSendsResponse(filter, filterResponse);\n\n      assertEquals(apiWhenExist.getSubnetApi().get().filter(ImmutableMultimap.<String, String> builder()\n                                                         .put(\"subnet-id\", \"subnet-9d4a7b6c\")\n                                                         .build()).toString(),\n               new DescribeSubnetsResponseTest().expected().toString());\n   }\n   \n   public void testFilterWhenResponseIs404() throws Exception {\n\n      HttpResponse filterResponse = HttpResponse.builder().statusCode(404).build();\n\n      EC2Api apiWhenDontExist = requestSendsResponse(filter, filterResponse);\n\n      assertEquals(apiWhenDontExist.getSubnetApi().get().filter(ImmutableMultimap.<String, String> builder()\n                                                                .put(\"subnet-id\", \"subnet-9d4a7b6c\")\n                                                                .build()).toSet(), ImmutableSet.of());\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/features/SubnetApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.features;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static java.lang.String.format;\nimport static java.util.concurrent.TimeUnit.MILLISECONDS;\nimport static java.util.logging.Logger.getAnonymousLogger;\nimport static org.jclouds.util.Predicates2.retry;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.ec2.domain.Subnet;\nimport org.jclouds.ec2.internal.BaseEC2ApiLiveTest;\nimport org.jclouds.ec2.util.SubnetFilterBuilder;\nimport org.testng.SkipException;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * tests ability to list/filter subnets\n */\n@Test(groups = \"live\")\npublic class SubnetApiLiveTest extends BaseEC2ApiLiveTest {\n    \n    private void checkSubnet(Subnet subnet) {\n        getAnonymousLogger().info(format(\"subnet %s vpc: %s\", subnet.getSubnetId(), subnet.getVpcId()));\n        \n        checkNotNull(subnet.getSubnetId(), \"Id: Subnet %s\", subnet);\n        checkNotNull(subnet.getVpcId(), \"VPC: Subnet %s\", subnet);\n        checkNotNull(subnet.getSubnetState(), \"SubnetState: Subnet %s\", subnet);\n        checkNotNull(subnet.getCidrBlock(), \"CIDR Block: %s\", subnet);\n        checkNotNull(subnet.getAvailabilityZone(), \"Availability Zone: %s\", subnet);\n    }\n    \n    @Test\n    public void testListSubnets() {\n        ImmutableSet<Subnet> subnets = api().list().toSet();\n        getAnonymousLogger().info(\"subnets: \" + subnets.size());\n        \n        for (Subnet subnet : subnets) {\n            checkSubnet(subnet);\n            assertEquals(api().filter(new SubnetFilterBuilder().subnetId(subnet.getSubnetId()).build()).get(0), subnet);\n      }\n    }\n\n    @Test\n    public void testFilterWhenNotFound() {\n        assertTrue(retry(new Predicate<Iterable<Subnet>>() {\n                    public boolean apply(Iterable<Subnet> input) {\n                        return api().filter(new SubnetFilterBuilder().subnetId(\"subnet-pants\").build())\n                            .toSet().equals(input);\n                    }\n                }, 600, 200, 200, MILLISECONDS).apply(ImmutableSet.<Subnet> of()));\n    }\n\n    private SubnetApi api() {\n        Optional<? extends SubnetApi> subnetOption = api.getSubnetApi();\n        if (!subnetOption.isPresent())\n            throw new SkipException(\"subnet api not present\");\n        return subnetOption.get();\n    }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/features/TagApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.features;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Properties;\n\nimport org.jclouds.Constants;\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.internal.BaseEC2ApiExpectTest;\nimport org.jclouds.ec2.parse.DescribeTagsResponseTest;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\")\npublic class TagApiExpectTest extends BaseEC2ApiExpectTest<EC2Api> {\n\n   /**\n    * @see TagApi\n    * @see SinceApiVersion\n    */\n   protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      props.put(Constants.PROPERTY_API_VERSION, \"2010-08-31\");\n      return props;\n   }\n   \n   HttpRequest apply = HttpRequest.builder()\n            .method(\"POST\")\n            .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n            .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n            .payload(\n                payloadFromStringWithContentType(\n                        \"Action=CreateTags\" +\n                        \"&ResourceId.1=i-43532\" +\n                        \"&Signature=Trp5e5%2BMqeBeBZbLYa9s9gxahQ9nkx6ETfsGl82IV8Y%3D\" +\n                        \"&SignatureMethod=HmacSHA256\" +\n                        \"&SignatureVersion=2\" +\n                        \"&Tag.1.Key=tag\" +\n                        \"&Tag.1.Value=\" +\n                        \"&Timestamp=2012-04-16T15%3A54%3A08.897Z\" +\n                        \"&Version=2010-08-31\" +\n                        \"&AWSAccessKeyId=identity\",\n                     \"application/x-www-form-urlencoded\"))\n            .build();\n\n   public void testApplyWhenResponseIs2xx() throws Exception {\n\n      HttpResponse applyResponse = HttpResponse.builder().statusCode(200).build();\n\n      EC2Api apiWhenExist = requestSendsResponse(apply, applyResponse);\n\n      apiWhenExist.getTagApi().get().applyToResources(ImmutableSet.of(\"tag\"), ImmutableSet.of(\"i-43532\"));\n   }\n\n   @Test(expectedExceptions = ResourceNotFoundException.class)\n   public void testApplyWhenResponseIs404() throws Exception {\n\n      HttpResponse applyResponse = HttpResponse.builder().statusCode(404).build();\n\n      EC2Api apiWhenDontExist = requestSendsResponse(apply, applyResponse);\n\n      apiWhenDontExist.getTagApi().get().applyToResources(ImmutableSet.of(\"tag\"), ImmutableSet.of(\"i-43532\"));\n   }\n   \n   HttpRequest applyWithValues = HttpRequest.builder()\n            .method(\"POST\")\n            .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n            .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n            .payload(\n               payloadFromStringWithContentType(\n                        \"Action=CreateTags\" +\n                        \"&ResourceId.1=i-43532\" +\n                        \"&Signature=jwCQr50j%2BvGkav4t0BN0G8RmNJ7VaFK6/7N/HKUmHL8%3D\" +\n                        \"&SignatureMethod=HmacSHA256\" +\n                        \"&SignatureVersion=2\" +\n                        \"&Tag.1.Key=tag\" +\n                        \"&Tag.1.Value=value\" +\n                        \"&Timestamp=2012-04-16T15%3A54%3A08.897Z\" +\n                        \"&Version=2010-08-31\" +\n                        \"&AWSAccessKeyId=identity\",\n                     \"application/x-www-form-urlencoded\"))\n            .build();\n\n   public void testApplyWithValuesWhenResponseIs2xx() throws Exception {\n\n      HttpResponse applyResponse = HttpResponse.builder().statusCode(200).build();\n\n      EC2Api apiWhenExist = requestSendsResponse(applyWithValues, applyResponse);\n\n      apiWhenExist.getTagApi().get().applyToResources(ImmutableMap.of(\"tag\", \"value\"), ImmutableSet.of(\"i-43532\"));\n   }\n\n   @Test(expectedExceptions = ResourceNotFoundException.class)\n   public void testApplyWithValuesWhenResponseIs404() throws Exception {\n\n      HttpResponse applyResponse = HttpResponse.builder().statusCode(404).build();\n\n      EC2Api apiWhenDontExist = requestSendsResponse(applyWithValues, applyResponse);\n\n      apiWhenDontExist.getTagApi().get().applyToResources(ImmutableMap.of(\"tag\", \"value\"), ImmutableSet.of(\"i-43532\"));\n   }\n   \n   HttpRequest list = HttpRequest.builder()\n                                       .method(\"POST\")\n                                       .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                                       .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                                       .payload(\n                                          payloadFromStringWithContentType(\n                                                   \"Action=DescribeTags\" +\n                                                   \"&Signature=DYUjPGiRl9copBtmpocMZYVAy4OTrK2AJzcAH5QiBuw%3D\" +\n                                                   \"&SignatureMethod=HmacSHA256\" +\n                                                   \"&SignatureVersion=2\" +\n                                                   \"&Timestamp=2012-04-16T15%3A54%3A08.897Z\" +\n                                                   \"&Version=2010-08-31\" +\n                                                   \"&AWSAccessKeyId=identity\",\n                                                \"application/x-www-form-urlencoded\"))\n                                       .build();\n   \n   public void testListWhenResponseIs2xx() throws Exception {\n\n      HttpResponse listResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResourceWithContentType(\"/describe_tags.xml\", \"text/xml\")).build();\n\n      EC2Api apiWhenExist = requestSendsResponse(\n            list, listResponse);\n\n      assertEquals(apiWhenExist.getTagApi().get().list().toString(), new DescribeTagsResponseTest().expected().toString());\n   }\n\n   public void testListWhenResponseIs404() throws Exception {\n\n      HttpResponse listResponse = HttpResponse.builder().statusCode(404).build();\n\n      EC2Api apiWhenDontExist = requestSendsResponse(\n            list, listResponse);\n\n      assertEquals(apiWhenDontExist.getTagApi().get().list().toSet(), ImmutableSet.of());\n   }\n   \n   HttpRequest filter =\n         HttpRequest.builder()\n                    .method(\"POST\")\n                    .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                    .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                    .payload(payloadFromStringWithContentType(\n                                               \"Action=DescribeTags\" +\n                                               \"&Filter.1.Name=resource-type\" +\n                                               \"&Filter.1.Value.1=instance\" +\n                                               \"&Filter.2.Name=key\" +\n                                               \"&Filter.2.Value.1=stack\" +\n                                               \"&Signature=doNEEZHEzXV/SD2eSZ6PpB1PADcsAF99lXGvsh3MbS4%3D\" +\n                                               \"&SignatureMethod=HmacSHA256\" +\n                                               \"&SignatureVersion=2\" +\n                                               \"&Timestamp=2012-04-16T15%3A54%3A08.897Z\" +\n                                               \"&Version=2010-08-31\" +\n                                               \"&AWSAccessKeyId=identity\",\n                                         \"application/x-www-form-urlencoded\"))\n                    .build();   \n\n   public void testFilterWhenResponseIs2xx() throws Exception {\n      \n      HttpResponse filterResponse = HttpResponse.builder().statusCode(200)\n               .payload(payloadFromResourceWithContentType(\"/describe_tags.xml\", \"text/xml\")).build();\n\n      EC2Api apiWhenExist = requestSendsResponse(filter, filterResponse);\n\n      assertEquals(apiWhenExist.getTagApi().get().filter(ImmutableMultimap.<String, String> builder()\n                                                         .put(\"resource-type\", \"instance\")\n                                                         .put(\"key\", \"stack\")\n                                                         .build()).toString(),\n               new DescribeTagsResponseTest().expected().toString());\n   }\n   \n   public void testFilterWhenResponseIs404() throws Exception {\n\n      HttpResponse filterResponse = HttpResponse.builder().statusCode(404).build();\n\n      EC2Api apiWhenDontExist = requestSendsResponse(filter, filterResponse);\n\n      assertEquals(apiWhenDontExist.getTagApi().get().filter(ImmutableMultimap.<String, String> builder()\n            .put(\"resource-type\", \"instance\")\n            .put(\"key\", \"stack\")\n            .build()).toSet(), ImmutableSet.of());\n   }\n   \n   HttpRequest delete = HttpRequest.builder()\n            .method(\"POST\")\n            .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n            .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n            .payload(\n               payloadFromStringWithContentType(\n                        \"Action=DeleteTags\" +\n                        \"&ResourceId.1=i-43532\" +\n                        \"&Signature=ytM605menR00re60wXMgBDpozrQCi0lVupf755/Mpck%3D\" +\n                        \"&SignatureMethod=HmacSHA256\" +\n                        \"&SignatureVersion=2\" +\n                        \"&Tag.1.Key=tag\" +\n                        \"&Timestamp=2012-04-16T15%3A54%3A08.897Z\" +\n                        \"&Version=2010-08-31\" +\n                        \"&AWSAccessKeyId=identity\",\n                     \"application/x-www-form-urlencoded\"))\n            .build();\n\n   public void testDeleteWhenResponseIs2xx() throws Exception {\n\n      HttpResponse deleteResponse = HttpResponse.builder().statusCode(200).build();\n\n      EC2Api apiWhenExist = requestSendsResponse(delete, deleteResponse);\n\n      apiWhenExist.getTagApi().get().deleteFromResources(ImmutableSet.of(\"tag\"), ImmutableSet.of(\"i-43532\"));\n   }\n\n   @Test(expectedExceptions = ResourceNotFoundException.class)\n   public void testDeleteWhenResponseIs404() throws Exception {\n\n      HttpResponse deleteResponse = HttpResponse.builder().statusCode(404).build();\n\n      EC2Api apiWhenDontExist = requestSendsResponse(delete, deleteResponse);\n\n      apiWhenDontExist.getTagApi().get().deleteFromResources(ImmutableSet.of(\"tag\"), ImmutableSet.of(\"i-43532\"));\n   }\n   \n   \n   HttpRequest conditionallyDelete = HttpRequest.builder()\n            .method(\"POST\")\n            .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n            .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n            .payload(\n               payloadFromStringWithContentType(\n                        \"Action=DeleteTags\" +\n                        \"&ResourceId.1=i-43532\" +\n                        \"&Signature=vRvgPegVDDjIEKudZ5Tpck0GQrVts//1jzk4W5RgI9k%3D\" +\n                        \"&SignatureMethod=HmacSHA256\" +\n                        \"&SignatureVersion=2\" +\n                        \"&Tag.1.Key=tag\" +\n                        \"&Tag.1.Value=value\" +\n                        \"&Timestamp=2012-04-16T15%3A54%3A08.897Z\" +\n                        \"&Version=2010-08-31\" +\n                        \"&AWSAccessKeyId=identity\",\n                     \"application/x-www-form-urlencoded\"))\n            .build();\n\n   public void testConditionallyDeleteWhenResponseIs2xx() throws Exception {\n\n      HttpResponse conditionallyDeleteResponse = HttpResponse.builder().statusCode(200).build();\n\n      EC2Api apiWhenExist = requestSendsResponse(conditionallyDelete, conditionallyDeleteResponse);\n\n      apiWhenExist.getTagApi().get().conditionallyDeleteFromResources(ImmutableMap.of(\"tag\", \"value\"), ImmutableSet.of(\"i-43532\"));\n   }\n\n   @Test(expectedExceptions = ResourceNotFoundException.class)\n   public void testConditionallyDeleteWhenResponseIs404() throws Exception {\n\n      HttpResponse conditionallyDeleteResponse = HttpResponse.builder().statusCode(404).build();\n\n      EC2Api apiWhenDontExist = requestSendsResponse(conditionallyDelete, conditionallyDeleteResponse);\n\n      apiWhenDontExist.getTagApi().get().conditionallyDeleteFromResources(ImmutableMap.of(\"tag\", \"value\"), ImmutableSet.of(\"i-43532\"));\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/features/WindowsApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.features;\n\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\n\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.domain.BundleTask;\nimport org.jclouds.ec2.internal.BaseEC2ApiExpectTest;\nimport org.jclouds.ec2.parse.GetPasswordDataResponseTest;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\", testName = \"WindowsApiExpectTest\")\npublic class WindowsApiExpectTest extends BaseEC2ApiExpectTest<EC2Api> {\n\n   HttpRequest get = HttpRequest.builder()\n                                .method(\"POST\")\n                                .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                                .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                                .payload(\n                                   payloadFromStringWithContentType(\n                                         \"Action=GetPasswordData\" +\n                                               \"&InstanceId=i-2574e22a\" +\n                                               \"&Signature=PMr4kU4p%2BSF2ISHXAFUme1kNh%2BCqftIUQchuw3vhKCw%3D\" +\n                                               \"&SignatureMethod=HmacSHA256\" +\n                                               \"&SignatureVersion=2\" +\n                                               \"&Timestamp=2012-04-16T15%3A54%3A08.897Z\" +\n                                               \"&Version=2010-08-31\" +\n                                               \"&AWSAccessKeyId=identity\",\n                                         \"application/x-www-form-urlencoded\"))\n                                .build();\n\n   HttpRequest filter = HttpRequest.builder().method(\"POST\")\n           .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n           .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n           .addFormParam(\"Action\", \"DescribeBundleTasks\")\n           .addFormParam(\"Filter.1.Name\", \"instance-id\")\n           .addFormParam(\"Filter.1.Value.1\", \"i-12345678\")\n           .addFormParam(\"Signature\", \"y0y3UBUKU/uYwbWPTCbkXzprU+8fMhg5LfF+5hWU2F4=\")\n           .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n           .addFormParam(\"SignatureVersion\", \"2\")\n           .addFormParam(\"Timestamp\", \"2012-04-16T15:54:08.897Z\")\n           .addFormParam(\"Version\", \"2010-08-31\")\n           .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testGetPasswordDataWhenResponseIs2xx() throws Exception {\n\n      HttpResponse getResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResourceWithContentType(\"/get_passworddata.xml\", \"text/xml\")).build();\n\n      EC2Api apiWhenExist = requestSendsResponse(get, getResponse);\n\n      assertEquals(apiWhenExist.getWindowsApi().get().getPasswordDataForInstance(\"i-2574e22a\").toString(), new GetPasswordDataResponseTest().expected().toString());\n   }\n\n   public void testGetPasswordDataWhenResponseIs404() throws Exception {\n\n      HttpResponse getResponse = HttpResponse.builder().statusCode(404).build();\n\n      EC2Api apiWhenDontExist = requestSendsResponse(get, getResponse);\n\n      assertNull(apiWhenDontExist.getWindowsApi().get().getPasswordDataForInstance(\"i-2574e22a\"));\n   }\n\n   public void testFilterBundleTasksWhenResponseIs2xx() {\n      HttpResponse filterResponse = HttpResponse.builder().statusCode(200)\n              .payload(payloadFromResourceWithContentType(\"/describe_bundle_tasks.xml\", \"text/xml\")).build();\n\n      EC2Api apiWhenExist = requestsSendResponses(describeRegionsRequest, describeRegionsResponse, filter, filterResponse);\n\n      BundleTask task = getOnlyElement(apiWhenExist.getWindowsApi().get().describeBundleTasksInRegionWithFilter(\"us-east-1\",\n              ImmutableMultimap.<String, String>builder()\n                      .put(\"instance-id\", \"i-12345678\")\n                      .build()));\n\n      assertEquals(task.getBundleId(), \"bun-c1a540a8\");\n   }\n\n   public void testFilterBundleTasksWhenResponseIs404() {\n      HttpResponse filterResponse = HttpResponse.builder().statusCode(404).build();\n\n      EC2Api apiWhenNotExist = requestsSendResponses(describeRegionsRequest, describeRegionsResponse, filter, filterResponse);\n\n      assertEquals(apiWhenNotExist.getWindowsApi().get().describeBundleTasksInRegionWithFilter(\"us-east-1\",\n              ImmutableMultimap.<String, String>builder()\n                      .put(\"instance-id\", \"i-12345678\")\n                      .build()),\n              ImmutableSet.of());\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/features/WindowsApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.features;\n\nimport org.jclouds.ec2.internal.BaseEC2ApiLiveTest;\nimport org.testng.SkipException;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\n\n@Test(groups = \"live\")\npublic class WindowsApiLiveTest extends BaseEC2ApiLiveTest {\n\n   protected WindowsApi api() {\n      Optional<? extends WindowsApi> windowsOption = api.getWindowsApi();\n      if (!windowsOption.isPresent())\n         throw new SkipException(\"windows api not present\");\n      return windowsOption.get();\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/features/WindowsApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.features;\n\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport java.io.IOException;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.ec2.options.BundleInstanceS3StorageOptions;\nimport org.jclouds.ec2.xml.BundleTaskHandler;\nimport org.jclouds.ec2.xml.DescribeBundleTasksResponseHandler;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Lists;\nimport com.google.common.reflect.Invokable;\n/**\n * Tests behavior of {@code WindowsApi}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"WindowsApiTest\")\npublic class WindowsApiTest extends BaseEC2ApiTest<WindowsApi> {\n\n   HttpRequest bundleInstanceInRegion = HttpRequest.builder().method(\"POST\")\n                                                   .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                                                   .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                                                   .addFormParam(\"Action\", \"BundleInstance\")\n                                                   .addFormParam(\"InstanceId\", \"i-e468cd8d\")\n                                                   .addFormParam(\"Signature\", \"78A6SjliGJg+KzaICB9I4bqEXFoNa4FKonuIwAj9hik=\")\n                                                   .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n                                                   .addFormParam(\"SignatureVersion\", \"2\")\n                                                   .addFormParam(\"Storage.S3.Bucket\", \"my-bucket\")\n                                                   .addFormParam(\"Storage.S3.Prefix\", \"winami\")\n                                                   .addFormParam(\"Storage.S3.UploadPolicy\", \"eyJleHBpcmF0aW9uIjogIjIwMDgtMDgtMzBUMDg6NDk6MDlaIiwiY29uZGl0aW9ucyI6IFt7ImJ1Y2tldCI6ICJteS1idWNrZXQifSxbInN0YXJ0cy13aXRoIiwgIiRrZXkiLCAibXktbmV3LWltYWdlIl1dfQ==\")\n                                                   .addFormParam(\"Storage.S3.UploadPolicySignature\", \"ih/iohGe0A7y4QVRbKaq6BZShzUsmBEJEa9AdFbxM6Y=\")\n                                                   .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n                                                   .addFormParam(\"Version\", \"2010-08-31\")\n                                                   .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testBundleInstanceInRegion() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(WindowsApi.class, \"bundleInstanceInRegion\", String.class, String.class,\n               String.class, String.class, String.class, BundleInstanceS3StorageOptions[].class);\n      GeneratedHttpRequest request = processor\n               .createRequest(\n                        method,\n                        Lists.<Object> newArrayList(\n                        null,\n                        \"i-e468cd8d\",\n                        \"winami\",\n                        \"my-bucket\",\n                        \"{\\\"expiration\\\": \\\"2008-08-30T08:49:09Z\\\",\\\"conditions\\\": [{\\\"bucket\\\": \\\"my-bucket\\\"},[\\\"starts-with\\\", \\\"$key\\\", \\\"my-new-image\\\"]]}\"));\n\n      request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, bundleInstanceInRegion.getPayload().getRawContent().toString(),\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, BundleTaskHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   HttpRequest bundleInstanceInRegionOptions = HttpRequest.builder().method(\"POST\")\n                                                          .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                                                          .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                                                          .addFormParam(\"Action\", \"BundleInstance\")\n                                                          .addFormParam(\"InstanceId\", \"i-e468cd8d\")\n                                                          .addFormParam(\"Signature\", \"9UbWwb+nO2vHn2O59K9FpmaK445RwX7vXsruHRznwik=\")\n                                                          .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n                                                          .addFormParam(\"SignatureVersion\", \"2\")\n                                                          .addFormParam(\"Storage.S3.AWSAccessKeyId\", \"10QMXFEV71ZS32XQFTR2\")\n                                                          .addFormParam(\"Storage.S3.Bucket\", \"my-bucket\")\n                                                          .addFormParam(\"Storage.S3.Prefix\", \"winami\")\n                                                          .addFormParam(\"Storage.S3.UploadPolicy\", \"eyJleHBpcmF0aW9uIjogIjIwMDgtMDgtMzBUMDg6NDk6MDlaIiwiY29uZGl0aW9ucyI6IFt7ImJ1Y2tldCI6ICJteS1idWNrZXQifSxbInN0YXJ0cy13aXRoIiwgIiRrZXkiLCAibXktbmV3LWltYWdlIl1dfQ==\")\n                                                          .addFormParam(\"Storage.S3.UploadPolicySignature\", \"ih/iohGe0A7y4QVRbKaq6BZShzUsmBEJEa9AdFbxM6Y=\")\n                                                          .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n                                                          .addFormParam(\"Version\", \"2010-08-31\")\n                                                          .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testBundleInstanceInRegionOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(WindowsApi.class, \"bundleInstanceInRegion\", String.class, String.class,\n               String.class, String.class, String.class, BundleInstanceS3StorageOptions[].class);\n      GeneratedHttpRequest request = processor\n               .createRequest(\n                        method,\n                        Lists.<Object> newArrayList(\n                        null,\n                        \"i-e468cd8d\",\n                        \"winami\",\n                        \"my-bucket\",\n                        \"{\\\"expiration\\\": \\\"2008-08-30T08:49:09Z\\\",\\\"conditions\\\": [{\\\"bucket\\\": \\\"my-bucket\\\"},[\\\"starts-with\\\", \\\"$key\\\", \\\"my-new-image\\\"]]}\",\n                        BundleInstanceS3StorageOptions.Builder.bucketOwnedBy(\"10QMXFEV71ZS32XQFTR2\")));\n\n      request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);\n      \n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, bundleInstanceInRegionOptions.getPayload().getRawContent().toString(),\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, BundleTaskHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testDescribeBundleTasks() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(WindowsApi.class, \"describeBundleTasksInRegion\", String.class, String[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList((String) null));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, \"Action=DescribeBundleTasks\",\n               \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, DescribeBundleTasksResponseHandler.class);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(request);\n   }\n\n   public void testDescribeBundleTasksArgs() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(WindowsApi.class, \"describeBundleTasksInRegion\", String.class, String[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"1\", \"2\"));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, \"Action=DescribeBundleTasks&BundleId.1=1&BundleId.2=2\",\n               \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, DescribeBundleTasksResponseHandler.class);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(request);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/features/internal/BaseTagApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.features.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static java.util.concurrent.TimeUnit.MILLISECONDS;\nimport static org.jclouds.util.Predicates2.retry;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.logging.Logger;\n\nimport org.jclouds.ec2.domain.Tag;\nimport org.jclouds.ec2.features.TagApi;\nimport org.jclouds.ec2.internal.BaseEC2ApiLiveTest;\nimport org.jclouds.ec2.util.TagFilterBuilder;\nimport org.testng.SkipException;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * tests ability to tag, filter, and delete tags from a resource.\n */\n@Test(groups = \"live\")\npublic abstract class BaseTagApiLiveTest extends BaseEC2ApiLiveTest {\n\n   private Resource resource;\n\n   private Tag tag;\n   private Tag tag2;\n\n   public void testApplyTag() {\n\n      api().applyToResources(ImmutableSet.of(\"foo\"), ImmutableSet.of(resource.id));\n\n      tag = api().filter(new TagFilterBuilder().resourceId(resource.id).key(\"foo\").build()).get(0);\n\n      Logger.getAnonymousLogger().info(\"created tag: \" + tag);\n\n      assertEquals(tag.getKey(), \"foo\");\n      assertEquals(tag.getResourceId(), resource.id);\n      assertEquals(tag.getResourceType(), resource.type);\n      assertFalse(tag.getValue().isPresent());\n   }\n\n   public void testApplyTagWithValue() {\n\n      api().applyToResources(ImmutableMap.of(\"type\", \"bar\"), ImmutableSet.of(resource.id));\n\n      tag2 = api().filter(new TagFilterBuilder().resourceId(resource.id).key(\"type\").build()).get(0);\n\n      Logger.getAnonymousLogger().info(\"created tag: \" + tag2);\n\n      assertEquals(tag2.getKey(), \"type\");\n      assertEquals(tag2.getResourceId(), resource.id);\n      assertEquals(tag2.getResourceType(), resource.type);\n      assertEquals(tag2.getValue().get(), \"bar\");\n   }\n\n   @Test(dependsOnMethods = { \"testApplyTag\", \"testApplyTagWithValue\" })\n   protected void testList() {\n      assertTrue(retry(new Predicate<Iterable<Tag>>() {\n         public boolean apply(Iterable<Tag> input) {\n            return api().list().filter(new Predicate<Tag>() {\n               @Override\n               public boolean apply(Tag in) {\n                  return in.getResourceId().equals(resource.id);\n               }\n            }).toSet().equals(input);\n         }\n      }, 600, 200, 200, MILLISECONDS).apply(ImmutableSet.of(tag, tag2)));\n   }\n\n   @Test(dependsOnMethods = \"testList\")\n   public void testDeleteTags() {\n      // shouldn't delete with the incorrect values\n      api().conditionallyDeleteFromResources(ImmutableMap.of(tag.getKey(), \"FOO\", tag2.getKey(), \"FOO\"),\n            ImmutableSet.of(tag.getResourceId(), tag2.getResourceId()));\n\n      assertEquals(tagsForResource().size(), 2);\n\n      api().deleteFromResources(ImmutableSet.of(tag.getKey(), tag2.getKey()),\n            ImmutableSet.of(tag.getResourceId(), tag2.getResourceId()));\n\n      assertEquals(tagsForResource().size(), 0);\n\n      Logger.getAnonymousLogger().info(\"tags deleted: \" + tag + \", \" + tag2);\n   }\n\n   private FluentIterable<Tag> tagsForResource() {\n      return api().filter(new TagFilterBuilder().resourceId(resource.id).build());\n   }\n\n   @Override\n   @BeforeClass(groups = \"live\")\n   public void setup() {\n      super.setup();\n      resource = checkNotNull(createResourceForTagging(System.getProperty(\"user.name\") + \"-tag\"), \"resource\");\n   }\n\n   public static class Resource {\n      public String id;\n      public String type;\n\n      /**\n       * \n       * @param id\n       *           ex. {sg-abc23d}\n       * @param type\n       *           a type listed in {@link Tag.ResourceType}\n       */\n      public Resource(String id, String type) {\n         this.id = checkNotNull(id, \"id\");\n         this.type = checkNotNull(type, \"type of %s\", id);\n      }\n   }\n\n   protected abstract Resource createResourceForTagging(String prefix);\n\n   protected abstract void cleanupResource(Resource resource);\n   \n   protected TagApi api() {\n      Optional<? extends TagApi> tagOption = api.getTagApi();\n      if (!tagOption.isPresent())\n         throw new SkipException(\"tag api not present\");\n      return tagOption.get();\n   }\n   \n   @AfterClass(groups = \"live\")\n   protected void tearDown() {\n      if (resource != null)\n         cleanupResource(resource);\n      super.tearDown();\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/functions/ConvertUnencodedBytesToBase64EncodedStringTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\n\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n/**\n * Tests behavior of {@code ConvertUnencodedBytesToBase64EncodedString}\n */\n@Test(groups = \"unit\")\npublic class ConvertUnencodedBytesToBase64EncodedStringTest {\n   Injector injector = Guice.createInjector();\n\n   public void testDefault() throws IOException {\n      ConvertUnencodedBytesToBase64EncodedString function = injector\n               .getInstance(ConvertUnencodedBytesToBase64EncodedString.class);\n\n      assertEquals(\"dGVzdA==\", function.apply(\"test\".getBytes()));\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/functions/EncodedRSAPublicKeyToBase64Test.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\n\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code EncodedRSAPublicKeyToBase64}\n */\n@Test(groups = \"unit\")\npublic class EncodedRSAPublicKeyToBase64Test {\n   EncodedRSAPublicKeyToBase64 function = new EncodedRSAPublicKeyToBase64();\n\n   public void testAllowedMarkers() throws IOException {\n      assertEquals(function.apply(\"-----BEGIN CERTIFICATE-----\"), \"LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0t\");\n      assertEquals(function.apply(\"ssh-rsa\"), \"c3NoLXJzYQ==\");\n      assertEquals(function.apply(\"---- BEGIN SSH2 PUBLIC KEY ----\"), \"LS0tLSBCRUdJTiBTU0gyIFBVQkxJQyBLRVkgLS0tLQ==\");\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testDisallowedMarkersIllegalArgument() throws IOException {\n      function.apply(\"ssh-dsa\");\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/internal/BaseEC2ApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.internal;\n\nimport java.util.concurrent.atomic.AtomicInteger;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.config.BaseEC2HttpApiModule;\nimport org.jclouds.rest.ConfiguresHttpApi;\n\nimport com.google.common.base.Supplier;\nimport com.google.inject.Module;\nimport com.google.inject.TypeLiteral;\n\npublic abstract class BaseEC2ApiExpectTest<T> extends BaseEC2ExpectTest<T> {\n   \n   @ConfiguresHttpApi\n   protected static class TestEC2HttpApiModule extends BaseEC2HttpApiModule<EC2Api> {\n\n      protected TestEC2HttpApiModule() {\n         super(EC2Api.class);\n      }\n      \n      @Override\n      protected void configure() {\n         super.configure();\n         // predicatable node names\n         final AtomicInteger suffix = new AtomicInteger();\n         bind(new TypeLiteral<Supplier<String>>() {\n         }).toInstance(new Supplier<String>() {\n\n            @Override\n            public String get() {\n               return suffix.getAndIncrement() + \"\";\n            }\n\n         });\n      }\n\n      @Override\n      protected String provideTimeStamp(DateService dateService) {\n         return CONSTANT_DATE;\n      }\n   }\n\n   @Override\n   protected Module createModule() {\n      return new TestEC2HttpApiModule();\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/internal/BaseEC2ApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.internal;\n\nimport org.jclouds.apis.BaseApiLiveTest;\nimport org.jclouds.ec2.EC2Api;\n\npublic class BaseEC2ApiLiveTest extends BaseApiLiveTest<EC2Api> {\n   public BaseEC2ApiLiveTest() {\n      provider = \"ec2\";\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/internal/BaseEC2ApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.internal;\n\nimport static com.google.common.base.Throwables.propagate;\nimport static com.google.common.net.HttpHeaders.CONTENT_TYPE;\nimport static com.google.common.util.concurrent.MoreExecutors.newDirectExecutorService;\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_XML;\nimport static org.jclouds.util.Strings2.toStringAndClose;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\nimport okhttp3.mockwebserver.RecordedRequest;\n\nimport org.jclouds.Constants;\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.concurrent.config.ExecutorServiceModule;\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.EC2ApiMetadata;\nimport org.testng.annotations.AfterMethod;\nimport org.testng.annotations.BeforeMethod;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Maps;\nimport com.google.inject.Module;\n\n\n/**\n * Tests need to run {@code singleThreaded = true) as otherwise tests will clash on the regionToServers field.\n * Sharing the regionToServers field means less code to write.\n */\npublic class BaseEC2ApiMockTest {\n   protected static final String DEFAULT_REGION = \"us-east-1\";\n\n   // Example keys from http://docs.aws.amazon.com/general/latest/gr/signature-version-2.html\n   private static final String ACCESS_KEY = \"AKIAIOSFODNN7EXAMPLE\";\n   private static final String SECRET_KEY = \"wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY\";\n\n   private Map<String, MockWebServer> regionToServers = Maps.newLinkedHashMap();\n\n   protected EC2Api api() {\n      return builder(new Properties()).buildApi(EC2Api.class);\n   }\n\n   protected ContextBuilder builder(Properties overrides) {\n      overrides.setProperty(Constants.PROPERTY_MAX_RETRIES, \"1\");\n      MockWebServer defaultServer = regionToServers.get(DEFAULT_REGION);\n      return ContextBuilder.newBuilder(new EC2ApiMetadata())\n            .credentials(ACCESS_KEY, SECRET_KEY)\n            .endpoint(defaultServer.url(\"\").toString())\n            .overrides(overrides)\n            .modules(modules);\n   }\n\n   private final Set<Module> modules = ImmutableSet.<Module>of(new ExecutorServiceModule(newDirectExecutorService()));\n\n   @BeforeMethod\n   public void start() throws IOException {\n      MockWebServer server = new MockWebServer();\n      server.start();\n      regionToServers.put(DEFAULT_REGION, server);\n   }\n\n   @AfterMethod(alwaysRun = true)\n   public void stop() throws IOException {\n      for (MockWebServer server : regionToServers.values()) {\n         server.shutdown();\n      }\n   }\n\n   protected void enqueue(String region, MockResponse response) {\n      regionToServers.get(region).enqueue(response);\n   }\n\n   protected void enqueueRegions(String... regions) throws IOException {\n      StringBuilder describeRegionsResponse = new StringBuilder();\n      describeRegionsResponse.append(\"<DescribeRegionsResponse>\");\n      for (String region : regions) {\n         describeRegionsResponse.append(\"<item>\");\n         describeRegionsResponse.append(\"<regionName>\").append(region).append(\"</regionName>\");\n         if (!regionToServers.containsKey(region)) {\n            MockWebServer server = new MockWebServer();\n            server.start();\n            regionToServers.put(region, server);\n         }\n         MockWebServer server = regionToServers.get(region);\n         String regionEndpoint = server.url(\"\").toString();\n         describeRegionsResponse.append(\"<regionEndpoint>\").append(regionEndpoint).append(\"</regionEndpoint>\");\n         describeRegionsResponse.append(\"</item>\");\n      }\n      describeRegionsResponse.append(\"</DescribeRegionsResponse>\");\n      enqueue(DEFAULT_REGION,\n            new MockResponse().addHeader(CONTENT_TYPE, APPLICATION_XML).setBody(describeRegionsResponse.toString()));\n   }\n\n   protected void enqueueXml(String region, String resource) {\n      enqueue(region,\n            new MockResponse().addHeader(CONTENT_TYPE, APPLICATION_XML).setBody(stringFromResource(resource)));\n   }\n\n   protected String stringFromResource(String resourceName) {\n      try {\n         return toStringAndClose(getClass().getResourceAsStream(resourceName));\n      } catch (IOException e) {\n         throw propagate(e);\n      }\n   }\n\n   /** Stripping out authorization, ensures the following post params were sent. */\n   protected RecordedRequest assertPosted(String region, String postParams) throws InterruptedException {\n      RecordedRequest request = regionToServers.get(region).takeRequest();\n      assertEquals(request.getMethod(), \"POST\");\n      assertEquals(request.getPath(), \"/\");\n      assertEquals(request.getBody().readUtf8().replaceAll(\"&Signature.*\", \"\"), postParams);\n      return request;\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/internal/BaseEC2ExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.internal;\n\nimport java.util.Map;\nimport java.util.TimeZone;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.aws.filters.FormSigner;\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rest.internal.BaseRestApiExpectTest;\nimport org.testng.annotations.BeforeClass;\n\nimport com.google.common.base.Functions;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMap.Builder;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Injector;\n\npublic abstract class BaseEC2ExpectTest<T> extends BaseRestApiExpectTest<T> {\n   protected static final String CONSTANT_DATE = \"2012-04-16T15:54:08.897Z\";\n   \n   protected DateService dateService = new SimpleDateFormatDateService();\n   \n   protected FormSigner formSigner;\n\n   protected HttpRequest describeRegionsRequest;\n   \n   protected HttpResponse describeRegionsResponse = HttpResponse.builder().statusCode(200)\n         .payload(payloadFromResourceWithContentType(\"/regionEndpoints-all.xml\", MediaType.APPLICATION_XML))\n         .build();\n   \n   protected Map<HttpRequest, HttpResponse> describeAvailabilityZonesRequestResponse;\n\n   public BaseEC2ExpectTest() {\n      provider = \"ec2\";\n      TimeZone.setDefault(TimeZone.getTimeZone(\"America/Los_Angeles\"));\n   }\n\n   @BeforeClass\n   protected void setupDefaultRequests() {\n      Injector injector = createInjector(Functions.forMap(ImmutableMap.<HttpRequest, HttpResponse> of()),\n            createModule(), setupProperties());\n      formSigner = injector.getInstance(FormSigner.class);\n      describeRegionsRequest = formSigner.filter(HttpRequest.builder().method(\"POST\")\n               .endpoint(\"https://ec2.us-east-1.amazonaws.com/\").addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n               .addFormParam(\"Action\", \"DescribeRegions\").build());\n      \n      Builder<HttpRequest, HttpResponse> builder = ImmutableMap.<HttpRequest, HttpResponse> builder();\n      for (String region : ImmutableSet.of(\"ap-northeast-1\", \"ap-southeast-1\", \"eu-west-1\", \"sa-east-1\", \"us-east-1\", \"us-west-1\", \"us-west-2\")) {\n         builder.put(\n               formSigner.filter(HttpRequest.builder()\n                          .method(\"POST\")\n                          .endpoint(\"https://ec2.\" + region + \".amazonaws.com/\")\n                          .addHeader(\"Host\", \"ec2.\" + region + \".amazonaws.com\")\n                          .payload(payloadFromStringWithContentType(\n                                 \"Action=DescribeAvailabilityZones&Version=2010-08-31\",\n                                 MediaType.APPLICATION_FORM_URLENCODED)).build()),\n               HttpResponse.builder().statusCode(200)\n                           .payload(payloadFromResourceWithContentType(\n                                 \"/availabilityZones-\" + region + \".xml\", MediaType.APPLICATION_XML)).build());               \n\n      }\n      describeAvailabilityZonesRequestResponse = builder.build();\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/options/BundleInstanceS3StorageOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.options;\n\nimport static org.jclouds.ec2.options.BundleInstanceS3StorageOptions.Builder.bucketOwnedBy;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.options.HttpRequestOptions;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tests possible uses of BundleInstanceS3StorageOptions and\n * BundleInstanceS3StorageOptions.Builder.*\n */\npublic class BundleInstanceS3StorageOptionsTest {\n\n   @Test\n   public void testAssignability() {\n      assert HttpRequestOptions.class.isAssignableFrom(BundleInstanceS3StorageOptions.class);\n      assert !String.class.isAssignableFrom(BundleInstanceS3StorageOptions.class);\n   }\n\n   @Test\n   public void testBucketOwnedBy() {\n      BundleInstanceS3StorageOptions options = new BundleInstanceS3StorageOptions();\n      options.bucketOwnedBy(\"test\");\n      assertEquals(options.buildFormParameters().get(\"Storage.S3.AWSAccessKeyId\"), ImmutableList.of(\"test\"));\n   }\n\n   @Test(expectedExceptions = IllegalStateException.class)\n   public void testNullBucketOwnedByNotInjected() {\n      BundleInstanceS3StorageOptions options = new BundleInstanceS3StorageOptions();\n      assertEquals(options.buildFormParameters().get(\"Storage.S3.AWSAccessKeyId\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testNullBucketOwnedBy() {\n      BundleInstanceS3StorageOptions options = new BundleInstanceS3StorageOptions();\n      options.creds = Suppliers.ofInstance(new Credentials(\"foo\", null));\n      assertEquals(options.buildFormParameters().get(\"Storage.S3.AWSAccessKeyId\"), ImmutableList.of(\"foo\"));\n   }\n\n   @Test\n   public void testBucketOwnedByStatic() {\n      BundleInstanceS3StorageOptions options = bucketOwnedBy(\"test\");\n      assertEquals(options.buildFormParameters().get(\"Storage.S3.AWSAccessKeyId\"), ImmutableList.of(\"test\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testBucketOwnedByNPE() {\n      bucketOwnedBy(null);\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/options/CreateImageOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.options;\n\nimport static org.jclouds.ec2.options.CreateImageOptions.Builder.noReboot;\nimport static org.jclouds.ec2.options.CreateImageOptions.Builder.withDescription;\nimport static org.testng.Assert.assertEquals;\n\nimport com.google.common.collect.ImmutableList;\n\nimport org.jclouds.http.options.HttpRequestOptions;\nimport org.testng.annotations.Test;\n\n/**\n * Tests possible uses of CreateImageOptions and CreateImageOptions.Builder.*\n */\npublic class CreateImageOptionsTest {\n\n   @Test\n   public void testAssignability() {\n      assert HttpRequestOptions.class.isAssignableFrom(CreateImageOptions.class);\n      assert !String.class.isAssignableFrom(CreateImageOptions.class);\n   }\n\n   @Test\n   public void testWithDescription() {\n      CreateImageOptions options = new CreateImageOptions();\n      options.withDescription(\"test\");\n      assertEquals(options.buildFormParameters().get(\"Description\"),\n               ImmutableList.of(\"test\"));\n   }\n\n   @Test\n   public void testNullWithDescription() {\n      CreateImageOptions options = new CreateImageOptions();\n      assertEquals(options.buildFormParameters().get(\"Description\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testWithDescriptionStatic() {\n      CreateImageOptions options = withDescription(\"test\");\n      assertEquals(options.buildFormParameters().get(\"Description\"),\n               ImmutableList.of(\"test\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testWithDescriptionNPE() {\n      withDescription(null);\n   }\n\n   @Test\n   public void testNoReboot() {\n      CreateImageOptions options = new CreateImageOptions();\n      options.noReboot();\n      assertEquals(options.buildFormParameters().get(\"NoReboot\"), ImmutableList.of(\"true\"));\n   }\n\n   @Test\n   public void testNoRebootStatic() {\n      CreateImageOptions options = noReboot();\n      assertEquals(options.buildFormParameters().get(\"NoReboot\"), ImmutableList.of(\"true\"));\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/options/CreateSnapshotOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.options;\n\nimport static org.jclouds.ec2.options.CreateSnapshotOptions.Builder.withDescription;\nimport static org.testng.Assert.assertEquals;\n\nimport com.google.common.collect.ImmutableList;\n\nimport org.jclouds.http.options.HttpRequestOptions;\nimport org.testng.annotations.Test;\n\n/**\n * Tests possible uses of CreateSnapshotOptions and CreateSnapshotOptions.Builder.*\n */\npublic class CreateSnapshotOptionsTest {\n\n   @Test\n   public void testAssignability() {\n      assert HttpRequestOptions.class.isAssignableFrom(CreateSnapshotOptions.class);\n      assert !String.class.isAssignableFrom(CreateSnapshotOptions.class);\n   }\n\n   @Test\n   public void testWithDescription() {\n      CreateSnapshotOptions options = new CreateSnapshotOptions();\n      options.withDescription(\"test\");\n      assertEquals(options.buildFormParameters().get(\"Description\"),\n               ImmutableList.of(\"test\"));\n   }\n\n   @Test\n   public void testNullWithDescription() {\n      CreateSnapshotOptions options = new CreateSnapshotOptions();\n      assertEquals(options.buildFormParameters().get(\"Description\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testWithDescriptionStatic() {\n      CreateSnapshotOptions options = withDescription(\"test\");\n      assertEquals(options.buildFormParameters().get(\"Description\"),\n               ImmutableList.of(\"test\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testWithDescriptionNPE() {\n      withDescription(null);\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/options/CreateVolumeOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.options;\n\nimport static org.jclouds.ec2.options.CreateVolumeOptions.Builder.fromSnapshotId;\nimport static org.jclouds.ec2.options.CreateVolumeOptions.Builder.isEncrypted;\nimport static org.jclouds.ec2.options.CreateVolumeOptions.Builder.volumeType;\nimport static org.jclouds.ec2.options.CreateVolumeOptions.Builder.withIops;\nimport static org.jclouds.ec2.options.CreateVolumeOptions.Builder.withSize;\nimport static org.testng.Assert.assertEquals;\n\nimport com.google.common.collect.ImmutableList;\nimport org.jclouds.http.options.HttpRequestOptions;\nimport org.testng.annotations.Test;\n\n/**\n * Tests possible uses of CreateVolumeOptions and CreateVolumeOptions.Builder.*\n */\npublic class CreateVolumeOptionsTest {\n\n   @Test\n   public void testAssignability() {\n      assert HttpRequestOptions.class.isAssignableFrom(CreateVolumeOptions.class);\n      assert !String.class.isAssignableFrom(CreateVolumeOptions.class);\n   }\n\n   @Test\n   public void testVolumeType() {\n      CreateVolumeOptions options = new CreateVolumeOptions();\n      options.volumeType(\"test\");\n      assertEquals(options.buildFormParameters().get(\"VolumeType\"),\n              ImmutableList.of(\"test\"));\n   }\n\n   @Test\n   public void testNullVolumeType() {\n      CreateVolumeOptions options = new CreateVolumeOptions();\n      assertEquals(options.buildFormParameters().get(\"VolumeType\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testVolumeTypeStatic() {\n      CreateVolumeOptions options = volumeType(\"test\");\n      assertEquals(options.buildFormParameters().get(\"VolumeType\"),\n              ImmutableList.of(\"test\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testVolmeTypeNPE() {\n      volumeType(null);\n   }\n\n   @Test\n   public void testFromSnapshotId() {\n      CreateVolumeOptions options = new CreateVolumeOptions();\n      options.fromSnapshotId(\"test\");\n      assertEquals(options.buildFormParameters().get(\"SnapshotId\"),\n              ImmutableList.of(\"test\"));\n   }\n\n   @Test\n   public void testNullFromSnapshotId() {\n      CreateVolumeOptions options = new CreateVolumeOptions();\n      assertEquals(options.buildFormParameters().get(\"SnapshotId\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testWithSnapshotIdStatic() {\n      CreateVolumeOptions options = fromSnapshotId(\"test\");\n      assertEquals(options.buildFormParameters().get(\"SnapshotId\"),\n              ImmutableList.of(\"test\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testFromSnapshotIdNPE() {\n      fromSnapshotId(null);\n   }\n\n   @Test\n   public void testWithIops() {\n      CreateVolumeOptions options = new CreateVolumeOptions();\n      options.withIops(5);\n      assertEquals(options.buildFormParameters().get(\"Iops\"),\n              ImmutableList.of(\"5\"));\n   }\n\n   @Test\n   public void testNullWithIops() {\n      CreateVolumeOptions options = new CreateVolumeOptions();\n      assertEquals(options.buildFormParameters().get(\"Iops\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testWithIopsStatic() {\n      CreateVolumeOptions options = withIops(5);\n      assertEquals(options.buildFormParameters().get(\"Iops\"),\n              ImmutableList.of(\"5\"));\n   }\n\n   @Test\n   public void testWithSize() {\n      CreateVolumeOptions options = new CreateVolumeOptions();\n      options.withSize(5);\n      assertEquals(options.buildFormParameters().get(\"Size\"),\n              ImmutableList.of(\"5\"));\n   }\n\n   @Test\n   public void testNullWithSize() {\n      CreateVolumeOptions options = new CreateVolumeOptions();\n      assertEquals(options.buildFormParameters().get(\"Size\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testWithSizeStatic() {\n      CreateVolumeOptions options = withSize(5);\n      assertEquals(options.buildFormParameters().get(\"Size\"),\n              ImmutableList.of(\"5\"));\n   }\n\n   @Test\n   public void testIsEncrypted() {\n      CreateVolumeOptions options = new CreateVolumeOptions();\n      options.isEncrypted(true);\n      assertEquals(options.buildFormParameters().get(\"Encrypted\"),\n              ImmutableList.of(\"true\"));\n   }\n\n   @Test\n   public void testNullIsEncrypted() {\n      CreateVolumeOptions options = new CreateVolumeOptions();\n      assertEquals(options.buildFormParameters().get(\"Encrypted\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testIsEncryptedStatic() {\n      CreateVolumeOptions options = isEncrypted(true);\n      assertEquals(options.buildFormParameters().get(\"Encrypted\"),\n              ImmutableList.of(\"true\"));\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/options/DescribeImagesOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.options;\n\nimport static org.jclouds.ec2.options.DescribeImagesOptions.Builder.executableBy;\nimport static org.jclouds.ec2.options.DescribeImagesOptions.Builder.imageIds;\nimport static org.jclouds.ec2.options.DescribeImagesOptions.Builder.ownedBy;\nimport static org.testng.Assert.assertEquals;\n\nimport com.google.common.collect.ImmutableList;\n\nimport org.jclouds.http.options.HttpRequestOptions;\nimport org.testng.annotations.Test;\n\n/**\n * Tests possible uses of DescribeImagesOptions and DescribeImagesOptions.Builder.*\n */\npublic class DescribeImagesOptionsTest {\n\n   @Test\n   public void testAssignability() {\n      assert HttpRequestOptions.class.isAssignableFrom(DescribeImagesOptions.class);\n      assert !String.class.isAssignableFrom(DescribeImagesOptions.class);\n   }\n\n   @Test\n   public void testExecutableBy() {\n      DescribeImagesOptions options = new DescribeImagesOptions();\n      options.executableBy(\"test\");\n      assertEquals(options.buildFormParameters().get(\"ExecutableBy\"),\n               ImmutableList.of(\"test\"));\n   }\n\n   @Test\n   public void testNullExecutableBy() {\n      DescribeImagesOptions options = new DescribeImagesOptions();\n      assertEquals(options.buildFormParameters().get(\"ExecutableBy\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testExecutableByStatic() {\n      DescribeImagesOptions options = executableBy(\"test\");\n      assertEquals(options.buildFormParameters().get(\"ExecutableBy\"),\n               ImmutableList.of(\"test\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testExecutableByNPE() {\n      executableBy(null);\n   }\n\n   @Test\n   public void testOwners() {\n      DescribeImagesOptions options = new DescribeImagesOptions();\n      options.ownedBy(\"test\");\n      assertEquals(options.buildFormParameters().get(\"Owner.1\"), ImmutableList.of(\"test\"));\n   }\n\n   @Test\n   public void testMultipleOwners() {\n      DescribeImagesOptions options = new DescribeImagesOptions();\n      options.ownedBy(\"test\", \"trouble\");\n      assertEquals(options.buildFormParameters().get(\"Owner.1\"), ImmutableList.of(\"test\"));\n      assertEquals(options.buildFormParameters().get(\"Owner.2\"),\n               ImmutableList.of(\"trouble\"));\n   }\n\n   @Test\n   public void testNullOwners() {\n      DescribeImagesOptions options = new DescribeImagesOptions();\n      assertEquals(options.buildFormParameters().get(\"Owner.1\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testOwnersStatic() {\n      DescribeImagesOptions options = ownedBy(\"test\");\n      assertEquals(options.buildFormParameters().get(\"Owner.1\"), ImmutableList.of(\"test\"));\n   }\n\n   public void testNoOwners() {\n      ownedBy();\n   }\n\n   @Test\n   public void testImageIds() {\n      DescribeImagesOptions options = new DescribeImagesOptions();\n      options.imageIds(\"test\");\n      assertEquals(options.buildFormParameters().get(\"ImageId.1\"),\n               ImmutableList.of(\"test\"));\n   }\n\n   @Test\n   public void testMultipleImageIds() {\n      DescribeImagesOptions options = new DescribeImagesOptions();\n      options.imageIds(\"test\", \"trouble\");\n      assertEquals(options.buildFormParameters().get(\"ImageId.1\"),\n               ImmutableList.of(\"test\"));\n      assertEquals(options.buildFormParameters().get(\"ImageId.2\"),\n               ImmutableList.of(\"trouble\"));\n   }\n\n   @Test\n   public void testNullImageIds() {\n      DescribeImagesOptions options = new DescribeImagesOptions();\n      assertEquals(options.buildFormParameters().get(\"ImageId.1\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testImageIdsStatic() {\n      DescribeImagesOptions options = imageIds(\"test\");\n      assertEquals(options.buildFormParameters().get(\"ImageId.1\"),\n               ImmutableList.of(\"test\"));\n   }\n\n   public void testNoImageIds() {\n      imageIds();\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/options/DescribeSnapshotsOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.options;\n\nimport static org.jclouds.ec2.options.DescribeSnapshotsOptions.Builder.ownedBy;\nimport static org.jclouds.ec2.options.DescribeSnapshotsOptions.Builder.restorableBy;\nimport static org.jclouds.ec2.options.DescribeSnapshotsOptions.Builder.snapshotIds;\nimport static org.testng.Assert.assertEquals;\n\nimport com.google.common.collect.ImmutableList;\n\nimport org.jclouds.http.options.HttpRequestOptions;\nimport org.testng.annotations.Test;\n\n/**\n * Tests possible uses of DescribeSnapshotsOptions and DescribeSnapshotsOptions.Builder.*\n */\npublic class DescribeSnapshotsOptionsTest {\n\n   @Test\n   public void testAssignability() {\n      assert HttpRequestOptions.class.isAssignableFrom(DescribeSnapshotsOptions.class);\n      assert !String.class.isAssignableFrom(DescribeSnapshotsOptions.class);\n   }\n\n   @Test\n   public void testRestorableBy() {\n      DescribeSnapshotsOptions options = new DescribeSnapshotsOptions();\n      options.restorableBy(\"test\");\n      assertEquals(options.buildFormParameters().get(\"RestorableBy.1\"),\n               ImmutableList.of(\"test\"));\n   }\n\n   @Test\n   public void testNullRestorableBy() {\n      DescribeSnapshotsOptions options = new DescribeSnapshotsOptions();\n      assertEquals(options.buildFormParameters().get(\"RestorableBy.1\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testRestorableByStatic() {\n      DescribeSnapshotsOptions options = restorableBy(\"test\");\n      assertEquals(options.buildFormParameters().get(\"RestorableBy.1\"),\n               ImmutableList.of(\"test\"));\n   }\n\n   @Test\n   public void testOwners() {\n      DescribeSnapshotsOptions options = new DescribeSnapshotsOptions();\n      options.ownedBy(\"test\");\n      assertEquals(options.buildFormParameters().get(\"Owner.1\"), ImmutableList.of(\"test\"));\n   }\n\n   @Test\n   public void testMultipleOwners() {\n      DescribeSnapshotsOptions options = new DescribeSnapshotsOptions();\n      options.ownedBy(\"test\", \"trouble\");\n      assertEquals(options.buildFormParameters().get(\"Owner.1\"), ImmutableList.of(\"test\"));\n      assertEquals(options.buildFormParameters().get(\"Owner.2\"),\n               ImmutableList.of(\"trouble\"));\n   }\n\n   @Test\n   public void testNullOwners() {\n      DescribeSnapshotsOptions options = new DescribeSnapshotsOptions();\n      assertEquals(options.buildFormParameters().get(\"Owner.1\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testOwnersStatic() {\n      DescribeSnapshotsOptions options = ownedBy(\"test\");\n      assertEquals(options.buildFormParameters().get(\"Owner.1\"), ImmutableList.of(\"test\"));\n   }\n\n   public void testNoOwners() {\n      ownedBy();\n   }\n\n   @Test\n   public void testSnapshotIds() {\n      DescribeSnapshotsOptions options = new DescribeSnapshotsOptions();\n      options.snapshotIds(\"test\");\n      assertEquals(options.buildFormParameters().get(\"SnapshotId.1\"),\n               ImmutableList.of(\"test\"));\n   }\n\n   @Test\n   public void testMultipleSnapshotIds() {\n      DescribeSnapshotsOptions options = new DescribeSnapshotsOptions();\n      options.snapshotIds(\"test\", \"trouble\");\n      assertEquals(options.buildFormParameters().get(\"SnapshotId.1\"),\n               ImmutableList.of(\"test\"));\n      assertEquals(options.buildFormParameters().get(\"SnapshotId.2\"),\n               ImmutableList.of(\"trouble\"));\n   }\n\n   @Test\n   public void testNullSnapshotIds() {\n      DescribeSnapshotsOptions options = new DescribeSnapshotsOptions();\n      assertEquals(options.buildFormParameters().get(\"SnapshotId.1\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testSnapshotIdsStatic() {\n      DescribeSnapshotsOptions options = snapshotIds(\"test\");\n      assertEquals(options.buildFormParameters().get(\"SnapshotId.1\"),\n               ImmutableList.of(\"test\"));\n   }\n\n   public void testNoSnapshotIds() {\n      snapshotIds();\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/options/DetachVolumeOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.options;\n\nimport static org.jclouds.ec2.options.DetachVolumeOptions.Builder.fromDevice;\nimport static org.jclouds.ec2.options.DetachVolumeOptions.Builder.fromInstance;\nimport static org.testng.Assert.assertEquals;\n\nimport com.google.common.collect.ImmutableList;\n\nimport org.jclouds.http.options.HttpRequestOptions;\nimport org.testng.annotations.Test;\n\n/**\n * Tests possible uses of DetachVolumeOptions and DetachVolumeOptions.Builder.*\n */\npublic class DetachVolumeOptionsTest {\n\n   @Test\n   public void testAssignability() {\n      assert HttpRequestOptions.class.isAssignableFrom(DetachVolumeOptions.class);\n      assert !String.class.isAssignableFrom(DetachVolumeOptions.class);\n   }\n\n   @Test\n   public void testFromDevice() {\n      DetachVolumeOptions options = new DetachVolumeOptions();\n      options.fromDevice(\"test\");\n      assertEquals(options.buildFormParameters().get(\"Device\"), ImmutableList.of(\"test\"));\n   }\n\n   @Test\n   public void testNullFromDevice() {\n      DetachVolumeOptions options = new DetachVolumeOptions();\n      assertEquals(options.buildFormParameters().get(\"Device\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testFromDeviceStatic() {\n      DetachVolumeOptions options = fromDevice(\"test\");\n      assertEquals(options.buildFormParameters().get(\"Device\"), ImmutableList.of(\"test\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testFromDeviceNPE() {\n      fromDevice(null);\n   }\n\n   @Test\n   public void testFromInstance() {\n      DetachVolumeOptions options = new DetachVolumeOptions();\n      options.fromInstance(\"test\");\n      assertEquals(options.buildFormParameters().get(\"InstanceId\"),\n               ImmutableList.of(\"test\"));\n   }\n\n   @Test\n   public void testNullFromInstance() {\n      DetachVolumeOptions options = new DetachVolumeOptions();\n      assertEquals(options.buildFormParameters().get(\"InstanceId\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testFromInstanceStatic() {\n      DetachVolumeOptions options = fromInstance(\"test\");\n      assertEquals(options.buildFormParameters().get(\"InstanceId\"),\n               ImmutableList.of(\"test\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testFromInstanceNPE() {\n      fromInstance(null);\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/options/RegisterImageBackedByEbsOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.options;\n\nimport static org.jclouds.ec2.options.RegisterImageBackedByEbsOptions.Builder.addBlockDeviceFromSnapshot;\nimport static org.jclouds.ec2.options.RegisterImageBackedByEbsOptions.Builder.addEphemeralBlockDeviceFromSnapshot;\nimport static org.jclouds.ec2.options.RegisterImageBackedByEbsOptions.Builder.addNewBlockDevice;\nimport static org.jclouds.ec2.options.RegisterImageBackedByEbsOptions.Builder.addNewEphemeralBlockDevice;\nimport static org.jclouds.ec2.options.RegisterImageBackedByEbsOptions.Builder.asArchitecture;\nimport static org.jclouds.ec2.options.RegisterImageBackedByEbsOptions.Builder.withDescription;\nimport static org.jclouds.ec2.options.RegisterImageBackedByEbsOptions.Builder.withKernelId;\nimport static org.jclouds.ec2.options.RegisterImageBackedByEbsOptions.Builder.withRamdisk;\nimport static org.testng.Assert.assertEquals;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMultimap;\nimport org.jclouds.ec2.domain.Image.Architecture;\nimport org.jclouds.http.options.HttpRequestOptions;\nimport org.testng.annotations.Test;\n\n/**\n * Tests possible uses of RegisterImageBackedByEbsOptions and\n * RegisterImageBackedByEbsOptions.Builder.*\n */\npublic class RegisterImageBackedByEbsOptionsTest {\n\n   @Test\n   public void testAssignability() {\n      assert HttpRequestOptions.class.isAssignableFrom(RegisterImageBackedByEbsOptions.class);\n      assert !String.class.isAssignableFrom(RegisterImageBackedByEbsOptions.class);\n   }\n\n   @Test\n   public void testWithDescription() {\n      RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions();\n      options.withDescription(\"test\");\n      assertEquals(options.buildFormParameters().get(\"Description\"),\n               ImmutableList.of(\"test\"));\n   }\n\n   @Test\n   public void testNullWithDescription() {\n      RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions();\n      assertEquals(options.buildFormParameters().get(\"Description\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testWithDescriptionStatic() {\n      RegisterImageBackedByEbsOptions options = withDescription(\"test\");\n      assertEquals(options.buildFormParameters().get(\"Description\"),\n               ImmutableList.of(\"test\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testWithDescriptionNPE() {\n      withDescription(null);\n   }\n\n   @Test\n   public void testWithArchitecture() {\n      RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions();\n      options.asArchitecture(Architecture.I386);\n      assertEquals(options.buildFormParameters().get(\"Architecture\"),\n               ImmutableList.of(\"i386\"));\n   }\n\n   @Test\n   public void testNullWithArchitecture() {\n      RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions();\n      assertEquals(options.buildFormParameters().get(\"Architecture\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testWithArchitectureStatic() {\n      RegisterImageBackedByEbsOptions options = asArchitecture(Architecture.I386);\n      assertEquals(options.buildFormParameters().get(\"Architecture\"),\n               ImmutableList.of(\"i386\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testWithArchitectureNPE() {\n      asArchitecture(null);\n   }\n\n   @Test\n   public void testWithKernelId() {\n      RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions();\n      options.withKernelId(\"test\");\n      assertEquals(options.buildFormParameters().get(\"KernelId\"), ImmutableList.of(\"test\"));\n   }\n\n   @Test\n   public void testNullWithKernelId() {\n      RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions();\n      assertEquals(options.buildFormParameters().get(\"KernelId\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testWithKernelIdStatic() {\n      RegisterImageBackedByEbsOptions options = withKernelId(\"test\");\n      assertEquals(options.buildFormParameters().get(\"KernelId\"), ImmutableList.of(\"test\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testWithKernelIdNPE() {\n      withKernelId(null);\n   }\n\n   @Test\n   public void testWithRamdisk() {\n      RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions();\n      options.withRamdisk(\"test\");\n      assertEquals(options.buildFormParameters().get(\"RamdiskId\"),\n               ImmutableList.of(\"test\"));\n   }\n\n   @Test\n   public void testNullWithRamdisk() {\n      RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions();\n      assertEquals(options.buildFormParameters().get(\"RamdiskId\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testWithRamdiskStatic() {\n      RegisterImageBackedByEbsOptions options = withRamdisk(\"test\");\n      assertEquals(options.buildFormParameters().get(\"RamdiskId\"),\n               ImmutableList.of(\"test\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testWithRamdiskNPE() {\n      withRamdisk(null);\n   }\n\n   @Test\n   public void testAddBlockDeviceFromSnapshot() {\n      RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions();\n      options.addBlockDeviceFromSnapshot(\"deviceName\", \"virtualName\", \"snapshotId\");\n      assertEquals(options.buildFormParameters().entries(), ImmutableMultimap.of(\n               \"BlockDeviceMapping.1.Ebs.DeleteOnTermination\", \"false\",\n               \"BlockDeviceMapping.1.DeviceName\", \"deviceName\", \"BlockDeviceMapping.1.VirtualName\",\n               \"virtualName\", \"BlockDeviceMapping.1.Ebs.SnapshotId\", \"snapshotId\").entries());\n   }\n\n   @Test\n   public void testAddBlockDeviceFromSnapshotNullVirtualName() {\n      RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions();\n      options.addBlockDeviceFromSnapshot(\"deviceName\", null, \"snapshotId\");\n      assertEquals(options.buildFormParameters().entries(), ImmutableMultimap.of(\n               \"BlockDeviceMapping.1.Ebs.DeleteOnTermination\", \"false\",\n               \"BlockDeviceMapping.1.DeviceName\", \"deviceName\",\n               \"BlockDeviceMapping.1.Ebs.SnapshotId\", \"snapshotId\").entries());\n   }\n\n   @Test\n   public void testNullAddBlockDeviceFromSnapshot() {\n      RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions();\n      assertEquals(options.buildFormParameters(), ImmutableMultimap.<String, String> of());\n   }\n\n   @Test\n   public void testAddBlockDeviceFromSnapshotStatic() {\n      RegisterImageBackedByEbsOptions options = addBlockDeviceFromSnapshot(\"deviceName\",\n               \"virtualName\", \"snapshotId\");\n      assertEquals(options.buildFormParameters().entries(), ImmutableMultimap.of(\n               \"BlockDeviceMapping.1.Ebs.DeleteOnTermination\", \"false\",\n               \"BlockDeviceMapping.1.DeviceName\", \"deviceName\", \"BlockDeviceMapping.1.VirtualName\",\n               \"virtualName\", \"BlockDeviceMapping.1.Ebs.SnapshotId\", \"snapshotId\").entries());\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testAddBlockDeviceFromSnapshotNPE() {\n      addBlockDeviceFromSnapshot(null, null, null);\n   }\n\n   @Test\n   public void testAdvancedAddBlockDeviceFromSnapshot() {\n      RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions();\n      options.addBlockDeviceFromSnapshot(\"deviceName\", \"virtualName\", \"snapshotId\", true, \"gp2\", 0, false);\n      assertEquals(options.buildFormParameters().entries(), ImmutableMultimap.builder()\n              .put(\"BlockDeviceMapping.1.Ebs.DeleteOnTermination\", \"true\")\n              .put(\"BlockDeviceMapping.1.Ebs.VolumeType\", \"gp2\")\n              .put(\"BlockDeviceMapping.1.Ebs.Iops\", \"0\")\n              .put(\"BlockDeviceMapping.1.DeviceName\", \"deviceName\")\n              .put(\"BlockDeviceMapping.1.VirtualName\", \"virtualName\")\n              .put(\"BlockDeviceMapping.1.Ebs.SnapshotId\", \"snapshotId\")\n              .build()\n              .entries());\n   }\n\n   @Test\n   public void testAdvancedAddBlockDeviceFromSnapshotStatic() {\n      RegisterImageBackedByEbsOptions options = addBlockDeviceFromSnapshot(\"deviceName\", \"virtualName\", \"snapshotId\", true, \"gp2\", 0, true);\n      assertEquals(options.buildFormParameters().entries(), ImmutableMultimap.builder()\n              .put(\"BlockDeviceMapping.1.Ebs.DeleteOnTermination\", \"true\")\n              .put(\"BlockDeviceMapping.1.Ebs.VolumeType\", \"gp2\")\n              .put(\"BlockDeviceMapping.1.Ebs.Iops\", \"0\")\n              .put(\"BlockDeviceMapping.1.Ebs.Encrypted\", \"true\")\n              .put(\"BlockDeviceMapping.1.DeviceName\", \"deviceName\")\n              .put(\"BlockDeviceMapping.1.VirtualName\", \"virtualName\")\n              .put(\"BlockDeviceMapping.1.Ebs.SnapshotId\", \"snapshotId\")\n              .build()\n              .entries());\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testAdvancedAddBlockDeviceFromSnapshotNPE() {\n      addBlockDeviceFromSnapshot(null, null, null, false, null, null, false);\n   }\n\n   @Test\n   public void testAddEphemeralBlockDeviceFromSnapshot() {\n      RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions();\n      options.addEphemeralBlockDeviceFromSnapshot(\"deviceName\", \"virtualName\", \"snapshotId\");\n      assertEquals(options.buildFormParameters().entries(), ImmutableMultimap.of(\n               \"BlockDeviceMapping.1.DeviceName\", \"deviceName\", \"BlockDeviceMapping.1.VirtualName\",\n               \"virtualName\", \"BlockDeviceMapping.1.Ebs.SnapshotId\", \"snapshotId\").entries());\n   }\n\n   @Test\n   public void testAddEphemeralBlockDeviceFromSnapshotNullVirtualName() {\n      RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions();\n      options.addEphemeralBlockDeviceFromSnapshot(\"deviceName\", null, \"snapshotId\");\n      assertEquals(options.buildFormParameters().entries(), ImmutableMultimap.of(\n               \"BlockDeviceMapping.1.DeviceName\", \"deviceName\",\n               \"BlockDeviceMapping.1.Ebs.SnapshotId\", \"snapshotId\").entries());\n   }\n\n   @Test\n   public void testNullAddEphemeralBlockDeviceFromSnapshot() {\n      RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions();\n      assertEquals(options.buildFormParameters(), ImmutableMultimap.<String, String> of());\n   }\n\n   @Test\n   public void testAddEphemeralBlockDeviceFromSnapshotStatic() {\n      RegisterImageBackedByEbsOptions options = addEphemeralBlockDeviceFromSnapshot(\"deviceName\",\n               \"virtualName\", \"snapshotId\");\n      assertEquals(options.buildFormParameters().entries(), ImmutableMultimap.of(\n               \"BlockDeviceMapping.1.DeviceName\", \"deviceName\", \"BlockDeviceMapping.1.VirtualName\",\n               \"virtualName\", \"BlockDeviceMapping.1.Ebs.SnapshotId\", \"snapshotId\").entries());\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testAddEphemeralBlockDeviceFromSnapshotNPE() {\n      addEphemeralBlockDeviceFromSnapshot(null, null, null);\n   }\n\n   // //////\n   @Test\n   public void testAddNewBlockDevice() {\n      RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions();\n      options.addNewBlockDevice(\"deviceName\", \"virtualName\", 1);\n      assertEquals(options.buildFormParameters().entries(), ImmutableMultimap.of(\n               \"BlockDeviceMapping.1.Ebs.DeleteOnTermination\", \"false\",\n               \"BlockDeviceMapping.1.DeviceName\", \"deviceName\", \"BlockDeviceMapping.1.VirtualName\",\n               \"virtualName\", \"BlockDeviceMapping.1.Ebs.VolumeSize\", \"1\").entries());\n   }\n\n   @Test\n   public void testAddNewBlockDeviceNullVirtualName() {\n      RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions();\n      options.addNewBlockDevice(\"deviceName\", null, 1);\n      assertEquals(options.buildFormParameters().entries(), ImmutableMultimap.of(\n               \"BlockDeviceMapping.1.Ebs.DeleteOnTermination\", \"false\",\n               \"BlockDeviceMapping.1.DeviceName\", \"deviceName\",\n               \"BlockDeviceMapping.1.Ebs.VolumeSize\", \"1\").entries());\n   }\n\n   @Test\n   public void testNullAddNewBlockDevice() {\n      RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions();\n      assertEquals(options.buildFormParameters(), ImmutableMultimap.<String, String> of());\n   }\n\n   @Test\n   public void testAddNewBlockDeviceStatic() {\n      RegisterImageBackedByEbsOptions options = addNewBlockDevice(\"deviceName\", \"virtualName\", 1);\n      assertEquals(options.buildFormParameters().entries(), ImmutableMultimap.of(\n               \"BlockDeviceMapping.1.Ebs.DeleteOnTermination\", \"false\",\n               \"BlockDeviceMapping.1.DeviceName\", \"deviceName\", \"BlockDeviceMapping.1.VirtualName\",\n               \"virtualName\", \"BlockDeviceMapping.1.Ebs.VolumeSize\", \"1\").entries());\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testAddNewBlockDeviceNPE() {\n      addNewBlockDevice(null, null, 1);\n   }\n\n   @Test\n   public void testAdvancedAddNewBlockDevice() {\n      RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions();\n      options.addNewBlockDevice(\"deviceName\", \"virtualName\", 5, true, \"gp2\", 0, true);\n      assertEquals(options.buildFormParameters().entries(), ImmutableMultimap.builder()\n              .put(\"BlockDeviceMapping.1.Ebs.DeleteOnTermination\", \"true\")\n              .put(\"BlockDeviceMapping.1.Ebs.VolumeType\", \"gp2\")\n              .put(\"BlockDeviceMapping.1.Ebs.Iops\", \"0\")\n              .put(\"BlockDeviceMapping.1.Ebs.Encrypted\", \"true\")\n              .put(\"BlockDeviceMapping.1.DeviceName\", \"deviceName\")\n              .put(\"BlockDeviceMapping.1.VirtualName\", \"virtualName\")\n              .put(\"BlockDeviceMapping.1.Ebs.VolumeSize\", \"5\")\n              .build()\n              .entries());\n   }\n\n   @Test\n   public void testAdvancedAddNewBlockDeviceStatic() {\n      RegisterImageBackedByEbsOptions options = addNewBlockDevice(\"deviceName\", \"virtualName\", 5, true, \"gp2\", 0, false);\n      assertEquals(options.buildFormParameters().entries(), ImmutableMultimap.builder()\n              .put(\"BlockDeviceMapping.1.Ebs.DeleteOnTermination\", \"true\")\n              .put(\"BlockDeviceMapping.1.Ebs.VolumeType\", \"gp2\")\n              .put(\"BlockDeviceMapping.1.Ebs.Iops\", \"0\")\n              .put(\"BlockDeviceMapping.1.DeviceName\", \"deviceName\")\n              .put(\"BlockDeviceMapping.1.VirtualName\", \"virtualName\")\n              .put(\"BlockDeviceMapping.1.Ebs.VolumeSize\", \"5\")\n              .build()\n              .entries());\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testAdvancedAddNewBlockDeviceNPE() {\n      addNewBlockDevice(null, null, 5, false, null, null, false);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testAddNewBlockDeviceTooBig() {\n      addNewBlockDevice(\"deviceName\", \"virtualName\", 1025);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testAddNewBlockDeviceTooSmall() {\n      addNewBlockDevice(\"deviceName\", \"virtualName\", 0);\n   }\n\n   @Test\n   public void testAddNewEphemeralBlockDevice() {\n      RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions();\n      options.addNewEphemeralBlockDevice(\"deviceName\", \"virtualName\", 1);\n      assertEquals(options.buildFormParameters().entries(), ImmutableMultimap.of(\n               \"BlockDeviceMapping.1.DeviceName\", \"deviceName\", \"BlockDeviceMapping.1.VirtualName\",\n               \"virtualName\", \"BlockDeviceMapping.1.Ebs.VolumeSize\", \"1\").entries());\n   }\n\n   @Test\n   public void testAddNewEphemeralBlockDeviceNullVirtualName() {\n      RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions();\n      options.addNewEphemeralBlockDevice(\"deviceName\", null, 1);\n      assertEquals(options.buildFormParameters().entries(), ImmutableMultimap.of(\n               \"BlockDeviceMapping.1.DeviceName\", \"deviceName\",\n               \"BlockDeviceMapping.1.Ebs.VolumeSize\", \"1\").entries());\n   }\n\n   @Test\n   public void testNullAddNewEphemeralBlockDevice() {\n      RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions();\n      assertEquals(options.buildFormParameters(), ImmutableMultimap.<String, String> of());\n   }\n\n   @Test\n   public void testAddNewEphemeralBlockDeviceStatic() {\n      RegisterImageBackedByEbsOptions options = addNewEphemeralBlockDevice(\"deviceName\",\n               \"virtualName\", 1);\n      assertEquals(options.buildFormParameters().entries(), ImmutableMultimap.of(\n               \"BlockDeviceMapping.1.DeviceName\", \"deviceName\", \"BlockDeviceMapping.1.VirtualName\",\n               \"virtualName\", \"BlockDeviceMapping.1.Ebs.VolumeSize\", \"1\").entries());\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testAddNewEphemeralBlockDeviceNPE() {\n      addNewEphemeralBlockDevice(null, null, 1);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testAddNewEphemeralBlockDeviceTooBig() {\n      addNewEphemeralBlockDevice(\"deviceName\", \"virtualName\", 1025);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testAddNewEphemeralBlockDeviceTooSmall() {\n      addNewEphemeralBlockDevice(\"deviceName\", \"virtualName\", 0);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/options/RegisterImageOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.options;\n\nimport static org.jclouds.ec2.options.RegisterImageOptions.Builder.asArchitecture;\nimport static org.jclouds.ec2.options.RegisterImageOptions.Builder.withDescription;\nimport static org.jclouds.ec2.options.RegisterImageOptions.Builder.withKernelId;\nimport static org.jclouds.ec2.options.RegisterImageOptions.Builder.withRamdisk;\nimport static org.testng.Assert.assertEquals;\n\nimport com.google.common.collect.ImmutableList;\n\nimport org.jclouds.ec2.domain.Image.Architecture;\nimport org.jclouds.http.options.HttpRequestOptions;\nimport org.testng.annotations.Test;\n\n/**\n * Tests possible uses of RegisterImageOptions and RegisterImageOptions.Builder.*\n */\npublic class RegisterImageOptionsTest {\n\n   @Test\n   public void testAssignability() {\n      assert HttpRequestOptions.class.isAssignableFrom(RegisterImageOptions.class);\n      assert !String.class.isAssignableFrom(RegisterImageOptions.class);\n   }\n\n   @Test\n   public void testWithDescription() {\n      RegisterImageOptions options = new RegisterImageOptions();\n      options.withDescription(\"test\");\n      assertEquals(options.buildFormParameters().get(\"Description\"),\n               ImmutableList.of(\"test\"));\n   }\n\n   @Test\n   public void testNullWithDescription() {\n      RegisterImageOptions options = new RegisterImageOptions();\n      assertEquals(options.buildFormParameters().get(\"Description\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testWithDescriptionStatic() {\n      RegisterImageOptions options = withDescription(\"test\");\n      assertEquals(options.buildFormParameters().get(\"Description\"),\n               ImmutableList.of(\"test\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testWithDescriptionNPE() {\n      withDescription(null);\n   }\n\n   @Test\n   public void testWithArchitecture() {\n      RegisterImageOptions options = new RegisterImageOptions();\n      options.asArchitecture(Architecture.I386);\n      assertEquals(options.buildFormParameters().get(\"Architecture\"),\n               ImmutableList.of(\"i386\"));\n   }\n\n   @Test\n   public void testNullWithArchitecture() {\n      RegisterImageOptions options = new RegisterImageOptions();\n      assertEquals(options.buildFormParameters().get(\"Architecture\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testWithArchitectureStatic() {\n      RegisterImageOptions options = asArchitecture(Architecture.I386);\n      assertEquals(options.buildFormParameters().get(\"Architecture\"),\n               ImmutableList.of(\"i386\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testWithArchitectureNPE() {\n      asArchitecture(null);\n   }\n\n   @Test\n   public void testWithKernelId() {\n      RegisterImageOptions options = new RegisterImageOptions();\n      options.withKernelId(\"test\");\n      assertEquals(options.buildFormParameters().get(\"KernelId\"), ImmutableList.of(\"test\"));\n   }\n\n   @Test\n   public void testNullWithKernelId() {\n      RegisterImageOptions options = new RegisterImageOptions();\n      assertEquals(options.buildFormParameters().get(\"KernelId\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testWithKernelIdStatic() {\n      RegisterImageOptions options = withKernelId(\"test\");\n      assertEquals(options.buildFormParameters().get(\"KernelId\"), ImmutableList.of(\"test\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testWithKernelIdNPE() {\n      withKernelId(null);\n   }\n\n   @Test\n   public void testWithRamdisk() {\n      RegisterImageOptions options = new RegisterImageOptions();\n      options.withRamdisk(\"test\");\n      assertEquals(options.buildFormParameters().get(\"RamdiskId\"),\n               ImmutableList.of(\"test\"));\n   }\n\n   @Test\n   public void testNullWithRamdisk() {\n      RegisterImageOptions options = new RegisterImageOptions();\n      assertEquals(options.buildFormParameters().get(\"RamdiskId\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testWithRamdiskStatic() {\n      RegisterImageOptions options = withRamdisk(\"test\");\n      assertEquals(options.buildFormParameters().get(\"RamdiskId\"),\n               ImmutableList.of(\"test\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testWithRamdiskNPE() {\n      withRamdisk(null);\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/options/RunInstancesOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.options;\n\nimport static org.jclouds.ec2.options.RunInstancesOptions.Builder.asType;\nimport static org.jclouds.ec2.options.RunInstancesOptions.Builder.withBlockDeviceMappings;\nimport static org.jclouds.ec2.options.RunInstancesOptions.Builder.withClientToken;\nimport static org.jclouds.ec2.options.RunInstancesOptions.Builder.withKernelId;\nimport static org.jclouds.ec2.options.RunInstancesOptions.Builder.withKeyName;\nimport static org.jclouds.ec2.options.RunInstancesOptions.Builder.withRamdisk;\nimport static org.jclouds.ec2.options.RunInstancesOptions.Builder.withSecurityGroup;\nimport static org.jclouds.ec2.options.RunInstancesOptions.Builder.withUserData;\nimport static org.testng.Assert.assertEquals;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\nimport org.jclouds.ec2.domain.BlockDeviceMapping;\nimport org.jclouds.ec2.domain.InstanceType;\nimport org.jclouds.http.options.HttpRequestOptions;\nimport org.testng.annotations.Test;\n\n/**\n * Tests possible uses of RunInstancesOptions and RunInstancesOptions.Builder.*\n */\npublic class RunInstancesOptionsTest {\n\n   @Test\n   public void testAssignability() {\n      assert HttpRequestOptions.class.isAssignableFrom(RunInstancesOptions.class);\n      assert !String.class.isAssignableFrom(RunInstancesOptions.class);\n   }\n\n   @Test\n   public void testWithKeyName() {\n      RunInstancesOptions options = new RunInstancesOptions();\n      options.withKeyName(\"test\");\n      assertEquals(options.buildFormParameters().get(\"KeyName\"), ImmutableList.of(\"test\"));\n   }\n\n   @Test\n   public void testNullWithKeyName() {\n      RunInstancesOptions options = new RunInstancesOptions();\n      assertEquals(options.buildFormParameters().get(\"KeyName\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testWithKeyNameStatic() {\n      RunInstancesOptions options = withKeyName(\"test\");\n      assertEquals(options.buildFormParameters().get(\"KeyName\"), ImmutableList.of(\"test\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testWithKeyNameNPE() {\n      withKeyName(null);\n   }\n\n   @Test\n   public void testWithSecurityGroup() {\n      RunInstancesOptions options = new RunInstancesOptions();\n      options.withSecurityGroup(\"test\");\n      assertEquals(options.buildFormParameters().get(\"SecurityGroup.1\"), ImmutableList.of(\"test\"));\n   }\n\n   @Test\n   public void testNullWithSecurityGroup() {\n      RunInstancesOptions options = new RunInstancesOptions();\n      assertEquals(options.buildFormParameters().get(\"SecurityGroup\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testWithSecurityGroupStatic() {\n      RunInstancesOptions options = withSecurityGroup(\"test\");\n      assertEquals(options.buildFormParameters().get(\"SecurityGroup.1\"), ImmutableList.of(\"test\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testWithSecurityGroupNPE() {\n      withSecurityGroup(null);\n   }\n\n   @Test\n   public void testNullWithAdditionalInfo() {\n      RunInstancesOptions options = new RunInstancesOptions();\n      assertEquals(options.buildFormParameters().get(\"AdditionalInfo\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testWithUserData() {\n      RunInstancesOptions options = new RunInstancesOptions();\n      options.withUserData(\"test\".getBytes());\n      assertEquals(options.buildFormParameters().get(\"UserData\"), ImmutableList.of(\"dGVzdA==\"));\n   }\n\n   @Test\n   public void testNullWithUserData() {\n      RunInstancesOptions options = new RunInstancesOptions();\n      assertEquals(options.buildFormParameters().get(\"UserData\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testWithUserDataStatic() {\n      RunInstancesOptions options = withUserData(\"test\".getBytes());\n      assertEquals(options.buildFormParameters().get(\"UserData\"), ImmutableList.of(\"dGVzdA==\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testWithUserDataNPE() {\n      withUserData(null);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testWithUserDataEmpty() {\n      withUserData(\"\".getBytes());\n   }\n\n   @Test\n   public void testWithInstanceType() {\n      RunInstancesOptions options = new RunInstancesOptions();\n      options.asType(InstanceType.C1_XLARGE);\n      assertEquals(options.buildFormParameters().get(\"InstanceType\"), ImmutableList.of(\"c1.xlarge\"));\n   }\n\n   @Test\n   public void testNullWithInstanceType() {\n      RunInstancesOptions options = new RunInstancesOptions();\n      assertEquals(options.buildFormParameters().get(\"InstanceType\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testWithInstanceTypeStatic() {\n      RunInstancesOptions options = asType(InstanceType.C1_XLARGE);\n      assertEquals(options.buildFormParameters().get(\"InstanceType\"), ImmutableList.of(\"c1.xlarge\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testWithInstanceTypeNPE() {\n      asType(null);\n   }\n\n   @Test\n   public void testWithKernelId() {\n      RunInstancesOptions options = new RunInstancesOptions();\n      options.withKernelId(\"test\");\n      assertEquals(options.buildFormParameters().get(\"KernelId\"), ImmutableList.of(\"test\"));\n   }\n\n   @Test\n   public void testNullWithKernelId() {\n      RunInstancesOptions options = new RunInstancesOptions();\n      assertEquals(options.buildFormParameters().get(\"KernelId\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testWithKernelIdStatic() {\n      RunInstancesOptions options = withKernelId(\"test\");\n      assertEquals(options.buildFormParameters().get(\"KernelId\"), ImmutableList.of(\"test\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testWithKernelIdNPE() {\n      withKernelId(null);\n   }\n\n   @Test\n   public void testWithRamdisk() {\n      RunInstancesOptions options = new RunInstancesOptions();\n      options.withRamdisk(\"test\");\n      assertEquals(options.buildFormParameters().get(\"RamdiskId\"), ImmutableList.of(\"test\"));\n   }\n\n   @Test\n   public void testNullWithRamdisk() {\n      RunInstancesOptions options = new RunInstancesOptions();\n      assertEquals(options.buildFormParameters().get(\"RamdiskId\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testWithRamdiskStatic() {\n      RunInstancesOptions options = withRamdisk(\"test\");\n      assertEquals(options.buildFormParameters().get(\"RamdiskId\"), ImmutableList.of(\"test\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testWithRamdiskNPE() {\n      withRamdisk(null);\n   }\n\n   @Test\n   public void testNullWithVirtualName() {\n      RunInstancesOptions options = new RunInstancesOptions();\n      assertEquals(options.buildFormParameters().get(\"BlockDeviceMapping.VirtualName\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testWithBlockDeviceMapping() {\n      BlockDeviceMapping mapping = new BlockDeviceMapping.MapNewVolumeToDevice(\"/dev/sda1\", 120, true, \"gp2\", 10, true);\n      RunInstancesOptions options = new RunInstancesOptions().withBlockDeviceMappings(ImmutableSet\n               .<BlockDeviceMapping> of(mapping));\n      assertEquals(options.buildFormParameters().get(\"BlockDeviceMapping.1.DeviceName\"),\n               ImmutableList.of(\"/dev/sda1\"));\n      assertEquals(options.buildFormParameters().get(\"BlockDeviceMapping.1.Ebs.VolumeSize\"),\n               ImmutableList.of(\"120\"));\n      assertEquals(options.buildFormParameters().get(\"BlockDeviceMapping.1.Ebs.DeleteOnTermination\"),\n               ImmutableList.of(\"true\"));\n      assertEquals(options.buildFormParameters().get(\"BlockDeviceMapping.1.Ebs.VolumeType\"),\n              ImmutableList.of(\"gp2\"));\n      assertEquals(options.buildFormParameters().get(\"BlockDeviceMapping.1.Ebs.Iops\"),\n              ImmutableList.of(\"10\"));\n      assertEquals(options.buildFormParameters().get(\"BlockDeviceMapping.1.Ebs.Encrypted\"),\n              ImmutableList.of(\"true\"));\n   }\n\n   @Test\n   public void testNullWithBlockDeviceMapping() {\n      RunInstancesOptions options = new RunInstancesOptions();\n      assertEquals(options.buildFormParameters().get(\"BlockDeviceMapping\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testWithBlockDeviceMappingStatic() {\n      BlockDeviceMapping mapping = new BlockDeviceMapping.MapNewVolumeToDevice(\"/dev/sda1\", 120, true, null, null, false);\n      RunInstancesOptions options = withBlockDeviceMappings(ImmutableSet\n               .<BlockDeviceMapping> of(mapping));\n      assertEquals(options.buildFormParameters().get(\"BlockDeviceMapping.1.DeviceName\"),\n               ImmutableList.of(\"/dev/sda1\"));\n      assertEquals(options.buildFormParameters().get(\"BlockDeviceMapping.1.Ebs.VolumeSize\"),\n               ImmutableList.of(\"120\"));\n      assertEquals(options.buildFormParameters().get(\"BlockDeviceMapping.1.Ebs.DeleteOnTermination\"),\n               ImmutableList.of(\"true\"));\n      assertEquals(options.buildFormParameters().get(\"BlockDeviceMapping.1.Ebs.VolumeType\"),\n              ImmutableList.of());\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testWithBlockDeviceMappingNPE() {\n      withBlockDeviceMappings(null);\n   }\n\n   @Test\n   public void testWithClientToken() {\n      RunInstancesOptions options = withClientToken(\"some-token\");\n      assertEquals(options.buildFormParameters().get(\"ClientToken\"), ImmutableList.of(\"some-token\"));\n   }\n\n   @Test(expectedExceptions =  NullPointerException.class)\n   public void testWithClientTokenNPE() {\n      withClientToken(null);\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/parse/DescribeSubnetsResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.parse;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.ec2.domain.Subnet;\nimport org.jclouds.ec2.xml.DescribeSubnetsResponseHandler;\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableSet;\n\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"DescribeSubnetsResponseTest\")\npublic class DescribeSubnetsResponseTest extends BaseHandlerTest {\n    \n    public void test() {\n        InputStream is = getClass().getResourceAsStream(\"/describe_subnets.xml\");\n        \n        FluentIterable<Subnet> expected = expected();\n        \n        DescribeSubnetsResponseHandler handler = injector.getInstance(DescribeSubnetsResponseHandler.class);\n        FluentIterable<Subnet> result = factory.create(handler).parse(is);\n        \n        assertEquals(result.toString(), expected.toString());\n        \n    }\n    public FluentIterable<Subnet> expected() {\n        return FluentIterable.from(ImmutableSet.<Subnet>builder()\n                                   .add(Subnet.builder()\n                                        .subnetId(\"subnet-9d4a7b6c\")\n                                        .subnetState(Subnet.State.AVAILABLE)\n                                        .vpcId(\"vpc-1a2b3c4d\")\n                                        .cidrBlock(\"10.0.1.0/24\")\n                                        .availableIpAddressCount(250)\n                                        .availabilityZone(\"us-east-1a\")\n                                        .tag(\"Name\", \"ec2-o\")\n                                        .tag(\"Empty\", \"\")\n                                        .build())                \n                                   .add(Subnet.builder()\n                                        .subnetId(\"subnet-6e7f829e\")\n                                        .subnetState(Subnet.State.AVAILABLE)\n                                        .vpcId(\"vpc-1a2b3c4d\")\n                                        .cidrBlock(\"10.0.0.0/24\")\n                                        .availableIpAddressCount(250)\n                                        .availabilityZone(\"us-east-1a\")\n                                        .build()).build());\n    }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/parse/DescribeTagsResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.parse;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.ec2.domain.Tag;\nimport org.jclouds.ec2.xml.DescribeTagsResponseHandler;\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableSet;\n\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"DescribeTagsResponseTest\")\npublic class DescribeTagsResponseTest extends BaseHandlerTest {\n\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/describe_tags.xml\");\n\n      FluentIterable<Tag> expected = expected();\n\n      DescribeTagsResponseHandler handler = injector.getInstance(DescribeTagsResponseHandler.class);\n      FluentIterable<Tag> result = factory.create(handler).parse(is);\n\n      assertEquals(result.toString(), expected.toString());\n\n   }\n   public FluentIterable<Tag> expected() {\n      return FluentIterable.from(ImmutableSet.<Tag>builder()\n               .add(Tag.builder()\n                       .resourceId(\"i-5f4e3d2a\")\n                       .resourceType(\"instance\")\n                       .key(\"webserver\")\n                       .build())                \n               .add(Tag.builder()\n                       .resourceId(\"i-5f4e3d2a\")\n                       .resourceType(\"instance\")\n                       .key(\"stack\")\n                       .value(\"Production\")\n                       .build())                \n               .add(Tag.builder()\n                       .resourceId(\"i-12345678\")\n                       .resourceType(\"instance\")\n                       .key(\"database_server\")\n                       .build())                \n               .add(Tag.builder()\n                       .resourceId(\"i-12345678\")\n                       .resourceType(\"instance\")\n                       .key(\"stack\")\n                       .value(\"Test\")\n                       .build()).build());\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/parse/GetPasswordDataResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.parse;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.ec2.domain.PasswordData;\nimport org.jclouds.ec2.xml.GetPasswordDataResponseHandler;\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.testng.annotations.Test;\n\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"GetPasswordDataResponseTest\")\npublic class GetPasswordDataResponseTest extends BaseHandlerTest {\n   protected final DateService dateService = new SimpleDateFormatDateService();\n\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/get_passworddata.xml\");\n\n      PasswordData expected = expected();\n\n      GetPasswordDataResponseHandler handler = injector.getInstance(GetPasswordDataResponseHandler.class);\n      PasswordData result = factory.create(handler).parse(is);\n\n      assertEquals(result.toString(), expected.toString());\n  }\n\n   public PasswordData expected() {\n      return PasswordData.builder()\n                         .instanceId(\"i-2574e22a\")\n                         .timestamp(dateService.iso8601DateParse(\"2012-07-30T07:27:23.000+0000\"))\n                         .passwordData(\"TGludXggdmVyc2lvbiAyLjYuMTYteGVuVSAoYnVpbGRlckBwYXRjaGJhdC5hbWF6b25zYSkgKGdj\").build();\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/predicates/VolumeDetachedTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.predicates;\n\nimport static com.google.common.collect.Sets.newHashSet;\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Date;\nimport java.util.Set;\n\nimport org.jclouds.ec2.domain.Attachment;\nimport org.jclouds.ec2.domain.Attachment.Status;\nimport org.jclouds.ec2.domain.Volume;\nimport org.jclouds.ec2.features.ElasticBlockStoreApi;\nimport org.testng.annotations.BeforeMethod;\nimport org.testng.annotations.DataProvider;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", singleThreaded = true)\npublic class VolumeDetachedTest {\n\n   private ElasticBlockStoreApi client;\n   private VolumeDetached volumeDetached;\n\n   @BeforeMethod\n   public void setUp() {\n      client = createMock(ElasticBlockStoreApi.class);\n      volumeDetached = new VolumeDetached(client);\n   }\n\n   @Test\n   public void testVolumeWithEmptyListOfAttachments() {\n      Attachment attachment = newAttachmentWithStatus(Status.ATTACHED);\n      Set<Volume> volumes = newHashSet(newVolumeWithAttachments(/* empty */));\n\n      expect(client.describeVolumesInRegion(attachment.getRegion(),\n         attachment.getVolumeId())).andReturn(volumes);\n      replay(client);\n\n      assertTrue(volumeDetached.apply(attachment));\n      verify(client);\n   }\n\n   @DataProvider(name = \"notDetachedStatuses\")\n   public Object[][] provideNotDetachedStatuses() {\n      return new Object[][] {\n         {Status.ATTACHED},\n         {Status.ATTACHING},\n         {Status.BUSY},\n         {Status.DETACHING},\n         {Status.UNRECOGNIZED}\n      };\n   }\n\n   @Test(dataProvider = \"notDetachedStatuses\")\n   public void testWithDifferentStatus(Status attachmentStatus) {\n      Attachment attachment = newAttachmentWithStatus(attachmentStatus);\n      Set<Volume> volumes = newHashSet(newVolumeWithAttachments(attachment));\n\n      expect(client.describeVolumesInRegion(attachment.getRegion(),\n         attachment.getVolumeId())).andReturn(volumes);\n      replay(client);\n\n      assertFalse(volumeDetached.apply(attachment));\n      verify(client);\n   }\n\n   @Test\n   public void testWithStatusDetached() {\n      Attachment attachment = newAttachmentWithStatus(Status.DETACHED);\n      Set<Volume> volumes = newHashSet(newVolumeWithAttachments(attachment));\n\n      expect(client.describeVolumesInRegion(attachment.getRegion(),\n         attachment.getVolumeId())).andReturn(volumes);\n      replay(client);\n\n      assertTrue(volumeDetached.apply(attachment));\n      verify(client);\n   }\n\n   private Volume newVolumeWithAttachments(Attachment... attachments) {\n      return Volume.builder().region(\"us-east-1\").attachments(attachments).build();\n   }\n\n   private Attachment newAttachmentWithStatus(Status status) {\n      return Attachment.builder()\n         .volumeId(\"1\").status(status).region(\"us-east-1\").attachTime(new Date())\n         .device(\"/dev/sda\").instanceId(\"us-east-1/i-1234\").build();\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/suppliers/DescribeAvailabilityZonesInRegionMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.suppliers;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.fail;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport okhttp3.mockwebserver.MockResponse;\n\nimport org.jclouds.ec2.internal.BaseEC2ApiMockTest;\nimport org.jclouds.rest.AuthorizationException;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableSet;\n\n\n@Test(groups = \"unit\", testName = \"DescribeAvailabilityZonesInRegionMockTest\", singleThreaded = true)\npublic class DescribeAvailabilityZonesInRegionMockTest extends BaseEC2ApiMockTest {\n\n   public void onlySendsRequestsToConfiguredRegions() throws Exception {\n      enqueueRegions(\"us-east-1\");\n      enqueueXml(\"us-east-1\", \"/availabilityZones.xml\");\n\n      Map<String, Supplier<Set<String>>> result = new DescribeAvailabilityZonesInRegion(api(),\n            supplyRegionIds(\"us-east-1\")).get();\n\n      assertEquals(result.size(), 1);\n      assertEquals(result.get(\"us-east-1\").get(),\n            ImmutableSet.of(\"us-east-1a\", \"us-east-1b\", \"us-east-1c\", \"us-east-1d\"));\n\n      assertPosted(\"us-east-1\", \"Action=DescribeRegions\");\n      assertPosted(\"us-east-1\", \"Action=DescribeAvailabilityZones\");\n   }\n\n   public void failsOnAuthorizationErrorToAnyRegion() throws Exception {\n      enqueueRegions(\"us-east-1\", \"eu-central-1\");\n      enqueueXml(\"us-east-1\", \"/availabilityZones.xml\");\n      enqueue(\"eu-central-1\", new MockResponse().setResponseCode(401));\n\n      DescribeAvailabilityZonesInRegion supplier = new DescribeAvailabilityZonesInRegion(api(),\n            supplyRegionIds(\"us-east-1\", \"eu-central-1\"));\n\n      try {\n         supplier.get();\n         fail();\n      } catch (AuthorizationException e){\n\n      }\n\n      assertPosted(\"us-east-1\", \"Action=DescribeRegions\");\n      assertPosted(\"us-east-1\", \"Action=DescribeAvailabilityZones\");\n      assertPosted(\"eu-central-1\", \"Action=DescribeAvailabilityZones\");\n   }\n\n   private static Supplier<Set<String>> supplyRegionIds(String... regionIds) {\n      return Suppliers.<Set<String>>ofInstance(ImmutableSet.copyOf(regionIds));\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/suppliers/DescribeRegionsForRegionURIsMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.suppliers;\n\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_REGIONS;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.net.URI;\nimport java.util.Map;\nimport java.util.Properties;\n\nimport org.jclouds.ec2.internal.BaseEC2ApiMockTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\n\n@Test(groups = \"unit\", testName = \"DescribeRegionsForRegionURIsMockTest\", singleThreaded = true)\npublic class DescribeRegionsForRegionURIsMockTest extends BaseEC2ApiMockTest {\n\n   public void buildsUrlsForEachRegion() throws Exception {\n      enqueueRegions(\"us-east-1\", \"eu-central-1\");\n\n      Map<String, Supplier<URI>> result = supplier(new Properties()).get();\n\n      assertEquals(result.size(), 2);\n      assertNotNull(result.get(\"us-east-1\").get());\n      assertNotNull(result.get(\"eu-central-1\").get());\n\n      assertPosted(\"us-east-1\", \"Action=DescribeRegions\");\n   }\n\n   public void honorsRegionWhitelist() throws Exception {\n      enqueueRegions(\"us-east-1\", \"eu-central-1\");\n\n      Properties overrides = new Properties();\n      overrides.setProperty(PROPERTY_REGIONS, \"us-east-1\");\n\n      Map<String, Supplier<URI>> result = supplier(overrides).get();\n\n      assertEquals(result.size(), 1);\n      assertNotNull(result.get(\"us-east-1\").get());\n\n      assertPosted(\"us-east-1\", \"Action=DescribeRegions\");\n   }\n\n   private DescribeRegionsForRegionURIs supplier(Properties overrides) {\n      return builder(overrides).buildInjector().getInstance(DescribeRegionsForRegionURIs.class);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/util/IpPermissionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.util;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.net.domain.IpProtocol;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests possible uses of IpPermissions\n */\n@Test(testName = \"IpPermissionsTest\")\npublic class IpPermissionsTest {\n   public void testAllProtocol() {\n      IpPermissions authorization = IpPermissions.permitAnyProtocol();\n      assertEquals(\n            IpPermissions.buildFormParametersForIndex(0, authorization).toString(),\n            \"{IpPermissions.0.IpProtocol=[-1], IpPermissions.0.FromPort=[1], IpPermissions.0.ToPort=[65535], IpPermissions.0.IpRanges.0.CidrIp=[0.0.0.0/0]}\");\n   }\n\n   public void testAllProtocolCidrBound() {\n      IpPermissions authorization = IpPermissions.permit(IpProtocol.ALL).originatingFromCidrBlock(\"1.1.1.1/32\");\n      assertEquals(\n            IpPermissions.buildFormParametersForIndex(0, authorization).toString(),\n            \"{IpPermissions.0.IpProtocol=[-1], IpPermissions.0.FromPort=[1], IpPermissions.0.ToPort=[65535], IpPermissions.0.IpRanges.0.CidrIp=[1.1.1.1/32]}\");\n   }\n\n   public void testJustProtocolAndCidr() {\n      IpPermissions authorization = IpPermissions.permit(IpProtocol.TCP).originatingFromCidrBlock(\"1.1.1.1/32\");\n      assertEquals(\n            IpPermissions.buildFormParametersForIndex(0, authorization).toString(),\n            \"{IpPermissions.0.IpProtocol=[tcp], IpPermissions.0.FromPort=[1], IpPermissions.0.ToPort=[65535], IpPermissions.0.IpRanges.0.CidrIp=[1.1.1.1/32]}\");\n   }\n\n   public void testAnyProtocol() {\n      IpPermissions authorization = IpPermissions.permitAnyProtocol().originatingFromCidrBlock(\"1.1.1.1/32\");\n      assertEquals(\n            IpPermissions.buildFormParametersForIndex(0, authorization).toString(),\n            \"{IpPermissions.0.IpProtocol=[-1], IpPermissions.0.FromPort=[1], IpPermissions.0.ToPort=[65535], IpPermissions.0.IpRanges.0.CidrIp=[1.1.1.1/32]}\");\n   }\n\n   public void testMultipleCidrs() {\n      IpPermissions authorization = IpPermissions.permit(IpProtocol.TCP).originatingFromCidrBlocks(\n            ImmutableSet.of(\"1.1.1.1/32\", \"1.1.1.2/32\"));\n      assertEquals(\n            IpPermissions.buildFormParametersForIndex(0, authorization).toString(),\n            \"{IpPermissions.0.IpProtocol=[tcp], IpPermissions.0.FromPort=[1], IpPermissions.0.ToPort=[65535], IpPermissions.0.IpRanges.0.CidrIp=[1.1.1.1/32], IpPermissions.0.IpRanges.1.CidrIp=[1.1.1.2/32]}\");\n   }\n\n   public void testProtocolFromAndToPortAndGroupIds() {\n      IpPermissions authorization = IpPermissions.permit(IpProtocol.UDP).fromPort(11).to(53)\n            .originatingFromSecurityGroupId(\"groupId\");\n      assertEquals(\n            IpPermissions.buildFormParametersForIndex(0, authorization).toString(),\n            \"{IpPermissions.0.IpProtocol=[udp], IpPermissions.0.FromPort=[11], IpPermissions.0.ToPort=[53], IpPermissions.0.Groups.0.GroupId=[groupId]}\");\n   }\n\n   public void testProtocolICMPAny() {\n      IpPermissions authorization = IpPermissions.permitICMP().originatingFromSecurityGroupId(\"groupId\");\n      assertEquals(\n            IpPermissions.buildFormParametersForIndex(0, authorization).toString(),\n            \"{IpPermissions.0.IpProtocol=[icmp], IpPermissions.0.FromPort=[-1], IpPermissions.0.ToPort=[-1], IpPermissions.0.Groups.0.GroupId=[groupId]}\");\n   }\n\n   public void testProtocolICMPTypeAnyCode() {\n      IpPermissions authorization = IpPermissions.permitICMP().type(8).originatingFromSecurityGroupId(\"groupId\");\n      assertEquals(\n            IpPermissions.buildFormParametersForIndex(0, authorization).toString(),\n            \"{IpPermissions.0.IpProtocol=[icmp], IpPermissions.0.FromPort=[8], IpPermissions.0.ToPort=[-1], IpPermissions.0.Groups.0.GroupId=[groupId]}\");\n   }\n\n   public void testProtocolICMPTypeCode() {\n      IpPermissions authorization = IpPermissions.permitICMP().type(8).andCode(0)\n            .originatingFromSecurityGroupId(\"groupId\");\n      assertEquals(\n            IpPermissions.buildFormParametersForIndex(0, authorization).toString(),\n            \"{IpPermissions.0.IpProtocol=[icmp], IpPermissions.0.FromPort=[8], IpPermissions.0.ToPort=[0], IpPermissions.0.Groups.0.GroupId=[groupId]}\");\n   }\n\n   public void testProtocolFromAndToPortAndUserGroups() {\n      IpPermissions authorization = IpPermissions.permit(IpProtocol.ICMP).originatingFromUserAndSecurityGroup(\"userId\",\n            \"groupId\");\n      assertEquals(\n            IpPermissions.buildFormParametersForIndex(0, authorization).toString(),\n            \"{IpPermissions.0.IpProtocol=[icmp], IpPermissions.0.FromPort=[-1], IpPermissions.0.ToPort=[-1], IpPermissions.0.Groups.0.UserId=[userId], IpPermissions.0.Groups.0.GroupId=[groupId]}\");\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/util/TagsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.util;\n\nimport static org.jclouds.ec2.domain.Tag.ResourceType.IMAGE;\nimport static org.jclouds.ec2.domain.Tag.ResourceType.INSTANCE;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.ec2.domain.Tag;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\n\n@Test\npublic class TagsTest {\n   Tag resourceTag1 = Tag.builder().resourceType(IMAGE).resourceId(\"1\").key(\"key\").value(\"value\").build();\n\n   public void testValueFunction() {\n      assertEquals(Tags.valueFunction().apply(resourceTag1), \"value\");\n   }\n\n   public void testKeyFunction() {\n      assertEquals(Tags.keyFunction().apply(resourceTag1), \"key\");\n   }\n\n   Tag resourceTag2 = Tag.builder().resourceType(IMAGE).resourceId(\"1\").key(\"foo\").value(\"bar\").build();\n   Tag resource2Tag1 = Tag.builder().resourceType(INSTANCE).resourceId(\"2\").key(\"absent\").build();\n   Tag resource2Tag2 = Tag.builder().resourceType(INSTANCE).resourceId(\"2\").key(\"hello\").value(\"world\").build();\n\n   public void testResourceToTagsAsMap() {\n      assertEquals(\n            Tags.resourceToTagsAsMap(ImmutableSet.of(resourceTag1, resourceTag2, resource2Tag1, resource2Tag2)),\n            ImmutableMap.of(\"1\", ImmutableMap.of(\"key\", \"value\", \"foo\", \"bar\"),\n                            \"2\", ImmutableMap.of(\"absent\", \"\", \"hello\", \"world\")));\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/xml/AllocateAddressResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\nimport java.net.UnknownHostException;\n\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code AllocateAddressResponseHandler}\n */\n//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"AllocateAddressResponseHandlerTest\")\npublic class AllocateAddressResponseHandlerTest extends BaseHandlerTest {\n   public void testApplyInputStream() throws UnknownHostException {\n\n      InputStream is = getClass().getResourceAsStream(\"/allocate_address.xml\");\n\n      String result = factory.create(injector.getInstance(AllocateAddressResponseHandler.class))\n               .parse(is);\n\n      assertEquals(result, \"67.202.55.255\");\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/xml/AttachmentHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.ec2.domain.Attachment;\nimport org.jclouds.http.functions.ParseSax;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code AttachmentHandler}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"AttachmentHandlerTest\")\npublic class AttachmentHandlerTest extends BaseEC2HandlerTest {\n   public void testApplyInputStream() {\n      DateService dateService = injector.getInstance(DateService.class);\n      InputStream is = getClass().getResourceAsStream(\"/attach.xml\");\n\n      Attachment expected = new Attachment(defaultRegion, \"vol-4d826724\", \"i-6058a509\", \"/dev/sdh\",\n            Attachment.Status.ATTACHING, dateService.iso8601DateParse(\"2008-05-07T11:51:50.000Z\"));\n\n      AttachmentHandler handler = injector.getInstance(AttachmentHandler.class);\n      addDefaultRegionToHandler(handler);\n      Attachment result = factory.create(handler).parse(is);\n\n      assertEquals(result, expected);\n   }\n\n   private void addDefaultRegionToHandler(ParseSax.HandlerWithResult<?> handler) {\n      handler.setContext(request);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/xml/BaseEC2HandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.domain.Region;\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.http.functions.config.SaxParserModule;\nimport org.jclouds.location.Zone;\nimport org.jclouds.util.Suppliers2;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Maps;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Provides;\n\n@Test(groups = \"unit\")\npublic abstract class BaseEC2HandlerTest extends BaseHandlerTest {\n   protected String defaultRegion = Region.US_EAST_1;\n\n   @BeforeTest\n   @Override\n   protected void setUpInjector() {\n      injector = Guice.createInjector(new SaxParserModule(), new AbstractModule() {\n\n         @Override\n         protected void configure() {\n\n         }\n\n         @Singleton\n         @Provides\n         @org.jclouds.location.Region\n         Supplier<String> provideDefaultRegion() {\n            return Suppliers.ofInstance(defaultRegion);\n         }\n\n         @Singleton\n         @Provides\n         @Zone\n         Supplier<Map<String, Supplier<Set<String>>>> provideRegionToAvailabilityZoneMap() {\n            return Suppliers.<Map<String, Supplier<Set<String>>>> ofInstance(Maps.transformValues(ImmutableMap\n                     .<String, Set<String>> of(\"us-east-1\", ImmutableSet.of(\"us-east-1a\")), Suppliers2\n                     .<Set<String>> ofInstanceFunction()));\n         }\n\n         @Singleton\n         @Provides\n         @Zone\n         Supplier<Set<String>> provideZones() {\n            return Suppliers.<Set<String>> ofInstance(ImmutableSet.of(\"us-east-1a\"));\n         }\n      });\n      factory = injector.getInstance(ParseSax.Factory.class);\n      assert factory != null;\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/xml/BlockDeviceMappingHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\nimport java.util.Map;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.ec2.domain.Attachment;\nimport org.jclouds.ec2.domain.BlockDevice;\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Tests behavior of {@code BlockDeviceMappingHandler}\n */\n//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"BlockDeviceMappingHandlerTest\")\npublic class BlockDeviceMappingHandlerTest extends BaseHandlerTest {\n   public void testApplyInputStream() {\n\n      InputStream is = getClass().getResourceAsStream(\n               \"/describe_image_attribute_blockDeviceMapping.xml\");\n\n      DateService dateService = injector.getInstance(DateService.class);\n      Map<String, BlockDevice> expected = ImmutableMap.<String, BlockDevice> of(\"/dev/sda1\",\n               new BlockDevice(\"vol-d74b82be\", Attachment.Status.ATTACHED, dateService\n                        .iso8601DateParse(\"2010-02-20T18:25:26.000Z\"), true), \"/dev/sdf\",\n               new BlockDevice(\"vol-another\", Attachment.Status.DETACHED, dateService\n                        .iso8601DateParse(\"2010-02-20T19:26:26.000Z\"), false));\n\n      Map<String, BlockDevice> result = factory.create(\n               injector.getInstance(BlockDeviceMappingHandler.class)).parse(is);\n\n      assertEquals(result, expected);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/xml/BundleTaskHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.ec2.domain.BundleTask;\nimport org.jclouds.http.functions.ParseSax;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code BundleTaskHandler}\n */\n//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"BundleTaskHandlerTest\")\npublic class BundleTaskHandlerTest extends BaseEC2HandlerTest {\n   public void testBundleInstance() {\n      DateService dateService = injector.getInstance(DateService.class);\n      InputStream is = getClass().getResourceAsStream(\"/bundle_instance.xml\");\n\n      BundleTask expected = new BundleTask(defaultRegion, \"bun-c1a540a8\", null, \"i-12345678\", 70, dateService\n            .iso8601DateParse(\"2008-10-07T11:41:50.000Z\"), \"bundling\", \"my-bucket\", \"winami\", dateService\n            .iso8601DateParse(\"2008-10-07T11:51:50.000Z\"));\n\n      BundleTaskHandler handler = injector.getInstance(BundleTaskHandler.class);\n      addDefaultRegionToHandler(handler);\n      BundleTask result = factory.create(handler).parse(is);\n\n      assertEquals(result, expected);\n   }\n\n   public void testCancleBundleTask() {\n      DateService dateService = injector.getInstance(DateService.class);\n      InputStream is = getClass().getResourceAsStream(\"/cancel_bundle_task.xml\");\n      BundleTask expected = new BundleTask(defaultRegion, \"bun-cla322b9\", null, \"i-12345678\", 20, dateService\n            .iso8601DateParse(\"2008-10-07T11:41:50.000Z\"), \"canceling\", \"my-bucket\", \"my-new-image\", dateService\n            .iso8601DateParse(\"2008-10-07T11:51:50.000Z\"));\n\n      BundleTaskHandler handler = injector.getInstance(BundleTaskHandler.class);\n      addDefaultRegionToHandler(handler);\n      BundleTask result = factory.create(handler).parse(is);\n\n      assertEquals(result, expected);\n   }\n\n   private void addDefaultRegionToHandler(ParseSax.HandlerWithResult<?> handler) {\n      handler.setContext(request);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/xml/CreateVolumeResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.aws.domain.Region;\nimport org.jclouds.date.DateService;\nimport org.jclouds.ec2.domain.Attachment;\nimport org.jclouds.ec2.domain.Volume;\nimport org.jclouds.http.functions.ParseSax;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Sets;\n\n/**\n * Tests behavior of {@code CreateVolumeResponseHandler}\n */\n//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"CreateVolumeResponseHandlerTest\")\npublic class CreateVolumeResponseHandlerTest extends BaseEC2HandlerTest {\n\n   public void testApplyInputStream() {\n      DateService dateService = injector.getInstance(DateService.class);\n      InputStream is = getClass().getResourceAsStream(\"/created_volume.xml\");\n\n      Volume expected = new Volume(Region.US_EAST_1, \"vol-2a21e543\", 1, null,\n              \"us-east-1a\", Volume.Status.CREATING, dateService\n              .iso8601DateParse(\"2009-12-28T05:42:53.000Z\"), \"standard\", 0, false,\n              Sets.<Attachment> newLinkedHashSet());\n\n      CreateVolumeResponseHandler handler = injector.getInstance(CreateVolumeResponseHandler.class);\n      addDefaultRegionToHandler(handler);\n      Volume result = factory.create(handler).parse(is);\n\n      assertEquals(result, expected);\n   }\n\n   private void addDefaultRegionToHandler(ParseSax.HandlerWithResult<?> handler) {\n      handler.setContext(request);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/xml/DescribeAddressesResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\nimport java.net.UnknownHostException;\nimport java.util.Collections;\nimport java.util.Set;\n\nimport org.jclouds.ec2.domain.PublicIpInstanceIdPair;\nimport org.jclouds.http.functions.ParseSax;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code DescribeAddressesResponseHandler}\n */\n//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"DescribeAddressesResponseHandlerTest\")\npublic class DescribeAddressesResponseHandlerTest extends BaseEC2HandlerTest {\n   public void testApplyInputStream() throws UnknownHostException {\n\n      InputStream is = getClass().getResourceAsStream(\"/describe_addresses.xml\");\n\n      DescribeAddressesResponseHandler handler = injector\n               .getInstance(DescribeAddressesResponseHandler.class);\n      addDefaultRegionToHandler(handler);\n\n      Set<PublicIpInstanceIdPair> result = factory.create(handler).parse(is);\n      \n      assertEquals(result, ImmutableSet.of(new PublicIpInstanceIdPair(defaultRegion, \"67.202.55.255\", \"i-f15ebb98\",\n            null, Collections.<String, String> emptyMap()), new PublicIpInstanceIdPair(defaultRegion, \"67.202.55.233\", null, null,\n            Collections.<String, String> emptyMap())));\n   }\n   \n   public void testApplyInputStreamWithTags() throws UnknownHostException {\n\n      InputStream is = getClass().getResourceAsStream(\"/describe_addresses_with_tags.xml\");\n\n      DescribeAddressesResponseHandler handler = injector.getInstance(DescribeAddressesResponseHandler.class);\n      addDefaultRegionToHandler(handler);\n\n      Set<PublicIpInstanceIdPair> result = factory.create(handler).parse(is);\n\n      assertEquals(result.size(), 3);\n      assertEquals(result, ImmutableSet.of(new PublicIpInstanceIdPair(defaultRegion, \"67.202.55.255\", \"i-f15ebb98\",\n            null, Collections.<String, String> emptyMap()), new PublicIpInstanceIdPair(defaultRegion, \"67.202.55.233\", null,\n            null, Collections.<String, String> emptyMap()), new PublicIpInstanceIdPair(defaultRegion, \"54.76.27.192\", null,\n            null, ImmutableMap.of(\"Name\", \"value-fa97d19c\", \"Empty\", \"\"))));\n   }\n\n   private void addDefaultRegionToHandler(final ParseSax.HandlerWithResult<?> handler) {\n      handler.setContext(request);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/xml/DescribeAvailabilityZonesResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\nimport java.util.Set;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.ec2.domain.AvailabilityZoneInfo;\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.http.functions.config.SaxParserModule;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\nimport com.google.inject.Provides;\n\n/**\n * Tests behavior of {@code DescribeAvailabilityZonesResponseHandler}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"DescribeAvailabilityZonesResponseHandlerTest\")\npublic class DescribeAvailabilityZonesResponseHandlerTest extends BaseHandlerTest {\n\n   @BeforeTest\n   protected void setUpInjector() {\n      injector = Guice.createInjector(new SaxParserModule() {\n         \n         @Singleton\n         @Provides\n         @org.jclouds.location.Region\n         Supplier<String> provideDefaultRegion() {\n            return Suppliers.ofInstance(\"SHOULDNTSEETHISASXMLHASREGIONDATA\");\n         }\n\n      });\n      factory = injector.getInstance(ParseSax.Factory.class);\n      assert factory != null;\n   }\n\n   public void testApplyInputStream() {\n\n      InputStream is = getClass().getResourceAsStream(\"/availabilityZones.xml\");\n\n      Set<AvailabilityZoneInfo> expected = ImmutableSet.<AvailabilityZoneInfo> of(\n\n      new AvailabilityZoneInfo(\"us-east-1a\", \"available\", \"us-east-1\", ImmutableSet.<String> of()),\n               new AvailabilityZoneInfo(\"us-east-1b\", \"available\", \"us-east-1\", ImmutableSet\n                        .<String> of()),\n\n               new AvailabilityZoneInfo(\"us-east-1c\", \"available\", \"us-east-1\", ImmutableSet\n                        .<String> of(\"our service is awesome\")),\n\n               new AvailabilityZoneInfo(\"us-east-1d\", \"downlikeaclown\", \"us-east-1\", ImmutableSet\n                        .<String> of()));\n      Set<AvailabilityZoneInfo> result = factory.create(\n               injector.getInstance(DescribeAvailabilityZonesResponseHandler.class)).parse(is);\n\n      assertEquals(result, expected);\n   }\n\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/xml/DescribeBundleTasksResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.ec2.domain.BundleTask;\nimport org.jclouds.http.functions.ParseSax;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Iterables;\n\n/**\n * Tests behavior of {@code DescribeBundleTasksResponseHandler}\n */\n//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"DescribeBundleTasksResponseHandlerTest\")\npublic class DescribeBundleTasksResponseHandlerTest extends BaseEC2HandlerTest {\n   public void testApplyInputStream() {\n      DateService dateService = injector.getInstance(DateService.class);\n      InputStream is = getClass().getResourceAsStream(\"/describe_bundle_tasks.xml\");\n\n      BundleTask expected = new BundleTask(defaultRegion, \"bun-c1a540a8\", null, \"i-12345678\", 20, dateService\n            .iso8601DateParse(\"2008-10-07T11:41:50.000Z\"), \"canceling\", \"my-bucket\", \"winami\", dateService\n            .iso8601DateParse(\"2008-10-07T11:51:50.000Z\"));\n\n      DescribeBundleTasksResponseHandler handler = injector.getInstance(DescribeBundleTasksResponseHandler.class);\n      addDefaultRegionToHandler(handler);\n      BundleTask result = Iterables.getOnlyElement(factory.create(handler).parse(is));\n\n      assertEquals(result, expected);\n   }\n\n   private void addDefaultRegionToHandler(ParseSax.HandlerWithResult<?> handler) {\n      handler.setContext(request);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/xml/DescribeImagesResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport static com.google.common.collect.Iterables.get;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\n\nimport java.io.InputStream;\nimport java.util.Set;\n\nimport org.jclouds.ec2.compute.functions.EC2ImageParserTest;\nimport org.jclouds.ec2.domain.Hypervisor;\nimport org.jclouds.ec2.domain.Image;\nimport org.jclouds.ec2.domain.RootDeviceType;\nimport org.jclouds.ec2.domain.VirtualizationType;\nimport org.jclouds.ec2.domain.Image.Architecture;\nimport org.jclouds.ec2.domain.Image.EbsBlockDevice;\nimport org.jclouds.ec2.domain.Image.ImageState;\nimport org.jclouds.ec2.domain.Image.ImageType;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.http.functions.config.SaxParserModule;\nimport org.jclouds.location.Region;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Sets;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport com.google.inject.TypeLiteral;\n\n/**\n * Tests behavior of {@code DescribeImagesResponseHandler}\n */\n@Test(groups = \"unit\", testName = \"DescribeImagesResponseHandlerTest\")\npublic class DescribeImagesResponseHandlerTest {\n\n   public void testUNIX() {\n      Set<Image> contents = ImmutableSet.of(new Image(\"us-east-1\", Architecture.I386, null, null, \"ami-be3adfd7\",\n               \"ec2-public-images/fedora-8-i386-base-v1.04.manifest.xml\", \"206029621532\", ImageState.AVAILABLE, \"available\",\n               ImageType.MACHINE, false, Sets.<String> newHashSet(\"9961934F\"), \"aki-4438dd2d\", null, \"ari-4538dd2c\",\n               RootDeviceType.INSTANCE_STORE, null, ImmutableMap.<String, EbsBlockDevice> of(),\n               ImmutableMap.<String, String> of(), VirtualizationType.PARAVIRTUAL, Hypervisor.XEN));\n\n      Set<Image> result = parseImages(\"/describe_images.xml\");\n\n      assertEquals(result.toString(), contents.toString());\n      assertEquals(get(result, 0).getImageState(), ImageState.AVAILABLE);\n      assertEquals(get(result, 0).getRawState(), \"available\");\n   }\n\n   public void testWindows() {\n      Set<Image> contents = ImmutableSet.of(new Image(\"us-east-1\", Architecture.X86_64, null, null, \"ami-02eb086b\",\n               \"aws-solutions-amis/SqlSvrStd2003r2-x86_64-Win_SFWBasic5.1-v1.0.manifest.xml\", \"771350841976\",\n               ImageState.AVAILABLE, \"available\", ImageType.MACHINE, true, Sets.<String> newHashSet(\"5771E9A6\"), null, \"windows\",\n               null, RootDeviceType.INSTANCE_STORE, null, ImmutableMap.<String, EbsBlockDevice> of(),\n               ImmutableMap.<String, String> of(), VirtualizationType.PARAVIRTUAL, Hypervisor.XEN));\n\n\n      Set<Image> result = parseImages(\"/describe_images_windows.xml\");\n\n      assertEquals(result.toString(), contents.toString());\n      assertEquals(get(result, 0).getImageState(), ImageState.AVAILABLE);\n      assertEquals(get(result, 0).getRawState(), \"available\");\n   }\n\n   public void testEBS() {\n      Set<Image> contents = ImmutableSet.of(new Image(\"us-east-1\", Architecture.I386, \"websrv_2009-12-10\",\n              \"Web Server AMI\", \"ami-246f8d4d\", \"706093390852/websrv_2009-12-10\", \"706093390852\",\n              ImageState.AVAILABLE, \"available\", ImageType.MACHINE, true, Sets.<String> newHashSet(), null, \"windows\", null,\n              RootDeviceType.EBS, \"/dev/sda1\",\n              ImmutableMap.<String, EbsBlockDevice> of(\"/dev/sda1\",\n                      new EbsBlockDevice(\"snap-d01272b9\", 30, true, \"standard\", null, false),\n                      \"xvdf\", new EbsBlockDevice(\"snap-d31272ba\", 250, false, \"standard\", null, false)),\n              ImmutableMap.<String, String> of(), VirtualizationType.HVM, Hypervisor.XEN));\n\n      Set<Image> result = parseImages(\"/describe_images_ebs.xml\");\n\n      assertEquals(result.toString(), contents.toString());\n      assertEquals(get(result, 0).getImageState(), ImageState.AVAILABLE);\n      assertEquals(get(result, 0).getRawState(), \"available\");\n      assertEquals(get(result, 0).getEbsBlockDevices().get(\"/dev/sda1\").getVolumeType(), \"standard\");\n      assertEquals(get(result, 0).getEbsBlockDevices().get(\"/dev/sda1\").isEncrypted(), false);\n      assertNull(get(result, 0).getEbsBlockDevices().get(\"/dev/sda1\").getIops());\n   }\n   \n   public void testTags() {\n      Set<Image> contents = ImmutableSet.of(new Image(\"us-east-1\", Architecture.I386, null, null, \"ami-be3adfd7\",\n            \"ec2-public-images/fedora-8-i386-base-v1.04.manifest.xml\", \"206029621532\", ImageState.AVAILABLE, \"available\",\n            ImageType.MACHINE, false, Sets.<String> newHashSet(\"9961934F\"), \"aki-4438dd2d\", null, \"ari-4538dd2c\",\n            RootDeviceType.INSTANCE_STORE, null, ImmutableMap.<String, EbsBlockDevice> of(),\n            ImmutableMap.<String, String> of(\"Name\", \"Some machine name\", \"Second\", \"Second value\"),\n            VirtualizationType.PARAVIRTUAL, Hypervisor.XEN));\n\n      Set<Image> result = parseImages(\"/describe_images_tags.xml\");\n\n      assertEquals(result.toString(), contents.toString());\n      assertEquals(get(result, 0).getImageState(), ImageState.AVAILABLE);\n      assertEquals(get(result, 0).getRawState(), \"available\");\n      assertEquals(get(result, 0).getTags().get(\"Name\"), \"Some machine name\");\n      assertEquals(get(result, 0).getTags().get(\"Second\"), \"Second value\");\n   }\n\n   public void testDiabloWithIncorrectDisplayNameField() {\n      Set<Image> contents = ImmutableSet.of(new Image(\"us-east-1\", Architecture.X86_64, \"CentOS 6.2 Server 64-bit 20120125\", \"\", \"ami-0000054e\",\n               \"local (CentOS 6.2 Server 64-bit 20120125)\", \"\", ImageState.AVAILABLE, \"available\",\n               ImageType.MACHINE, true, Sets.<String> newHashSet(), \"aki-0000054c\", null, \"ari-0000054d\",\n               RootDeviceType.INSTANCE_STORE, \"/dev/sda1\", ImmutableMap.<String, EbsBlockDevice> of(),\n               ImmutableMap.<String, String> of(), VirtualizationType.PARAVIRTUAL, Hypervisor.XEN));\n      \n      Set<Image> result = parseImages(\"/describe_images_nova.xml\");\n\n      assertEquals(result.toString(), contents.toString());\n      assertEquals(get(result, 0).getImageState(), ImageState.AVAILABLE);\n      assertEquals(get(result, 0).getRawState(), \"available\");\n   }\n\n   static ParseSax<Set<Image>> createParser() {\n      Injector injector = Guice.createInjector(new SaxParserModule(), new AbstractModule() {\n\n         @Override\n         protected void configure() {\n            bind(new TypeLiteral<Supplier<String>>() {\n            }).annotatedWith(Region.class).toInstance(Suppliers.ofInstance(\"us-east-1\"));\n         }\n\n      });\n      ParseSax<Set<Image>> parser = injector.getInstance(ParseSax.Factory.class).create(\n               injector.getInstance(DescribeImagesResponseHandler.class));\n      return parser;\n   }\n\n   public static Set<Image> parseImages(String resource) {\n      InputStream is = EC2ImageParserTest.class.getResourceAsStream(resource);\n      return createParser().parse(is);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/xml/DescribeInstanceAttributeTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.ec2.domain.InstanceType;\nimport org.jclouds.ec2.domain.Volume.InstanceInitiatedShutdownBehavior;\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code DescribeInstanceAttribute}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"DescribeInstanceAttributeTest\")\npublic class DescribeInstanceAttributeTest extends BaseHandlerTest {\n\n   public void testInstanceInitiatedShutdownBehaviorHandler() {\n      InputStream is = getClass().getResourceAsStream(\"/instanceInitiatedShutdownBehavior.xml\");\n\n      InstanceInitiatedShutdownBehaviorHandler handler = injector\n               .getInstance(InstanceInitiatedShutdownBehaviorHandler.class);\n      InstanceInitiatedShutdownBehavior result = factory.create(handler).parse(is);\n\n      assertEquals(result, InstanceInitiatedShutdownBehavior.STOP);\n   }\n\n   public void testInstanceTypeHandler() {\n      InputStream is = getClass().getResourceAsStream(\"/instanceType.xml\");\n\n      InstanceTypeHandler handler = injector.getInstance(InstanceTypeHandler.class);\n      String result = factory.create(handler).parse(is);\n\n      assertEquals(result, InstanceType.M1_SMALL);\n   }\n\n   public void testBooleanValueHandler() {\n      InputStream is = getClass().getResourceAsStream(\"/disableApiTermination.xml\");\n\n      BooleanValueHandler handler = injector.getInstance(BooleanValueHandler.class);\n      Boolean result = factory.create(handler).parse(is);\n\n      assert !result;\n   }\n\n   public void testStringValueHandler() {\n      InputStream is = getClass().getResourceAsStream(\"/ramdisk.xml\");\n\n      StringValueHandler handler = injector.getInstance(StringValueHandler.class);\n      String result = factory.create(handler).parse(is);\n\n      assertEquals(result, \"ari-a51cf9cc\");\n   }\n\n   public void testUnencodeStringValueHandler() {\n      InputStream is = getClass().getResourceAsStream(\"/userData.xml\");\n      UnencodeStringValueHandler handler = injector.getInstance(UnencodeStringValueHandler.class);\n      String result = factory.create(handler).parse(is);\n      assertEquals(result, \"#!/bin/bash\\n\");\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/xml/DescribeInstancesResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport static com.google.common.collect.Iterables.get;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\nimport java.net.UnknownHostException;\nimport java.util.Set;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.ec2.domain.Attachment;\nimport org.jclouds.ec2.domain.BlockDevice;\nimport org.jclouds.ec2.domain.InstanceState;\nimport org.jclouds.ec2.domain.InstanceType;\nimport org.jclouds.ec2.domain.Reservation;\nimport org.jclouds.ec2.domain.RootDeviceType;\nimport org.jclouds.ec2.domain.RunningInstance;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.http.functions.config.SaxParserModule;\nimport org.jclouds.location.Region;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport com.google.inject.TypeLiteral;\n\n/**\n * Tests behavior of {@code DescribeInstancesResponseHandler}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"DescribeInstancesResponseHandlerTest\")\npublic class DescribeInstancesResponseHandlerTest extends BaseEC2HandlerTest {\n\n   private DateService dateService;\n\n   @BeforeTest\n   @Override\n   protected void setUpInjector() {\n      super.setUpInjector();\n      dateService = injector.getInstance(DateService.class);\n      assert dateService != null;\n   }\n\n   public void testWhenRunning() throws UnknownHostException {\n\n      Set<Reservation<RunningInstance>> contents = ImmutableSet.of(new Reservation<RunningInstance>(defaultRegion,\n               ImmutableSet.of(\"adriancole.ec2ingress\"), ImmutableSet.of(RunningInstance.builder().region(\n                        defaultRegion).groupName(\"adriancole.ec2ingress\").amiLaunchIndex(\"0\").dnsName(\n                        \"ec2-174-129-81-68.compute-1.amazonaws.com\").imageId(\"ami-82e4b5c7\").instanceId(\"i-0799056f\")\n                        .instanceState(InstanceState.RUNNING).rawState(\"running\").instanceType(InstanceType.M1_SMALL)\n                        .ipAddress(\"174.129.81.68\").kernelId(\"aki-a71cf9ce\").keyName(\"adriancole.ec21\").launchTime(\n                                 dateService.iso8601DateOrSecondsDateParse(\"2009-11-09T03:00:34.000Z\"))\n                        // MonitoringState.DISABLED,\n                        .availabilityZone(\"us-east-1c\").virtualizationType(\"paravirtual\").privateDnsName(\n                                 \"ip-10-243-42-70.ec2.internal\").privateIpAddress(\"10.243.42.70\").ramdiskId(\n                                 \"ari-a51cf9cc\").rootDeviceType(RootDeviceType.INSTANCE_STORE).build()),\n               \"993194456877\", null, \"r-a3c508cb\"));\n\n      Set<Reservation<? extends RunningInstance>> result = parseRunningInstances(\"/describe_instances_running.xml\");\n\n      assertEquals(result.toString(), contents.toString());\n      assertEquals(get(get(result, 0), 0).getInstanceState(), InstanceState.RUNNING);\n      assertEquals(get(get(result, 0), 0).getRawState(), \"running\");\n   }\n   \n   public void testWhenRunningAndSecondsDate() throws UnknownHostException {\n\n      Set<Reservation<RunningInstance>> contents = ImmutableSet.of(new Reservation<RunningInstance>(defaultRegion,\n               ImmutableSet.of(\"adriancole.ec2ingress\"), ImmutableSet.of(RunningInstance.builder().region(\n                        defaultRegion).groupName(\"adriancole.ec2ingress\").amiLaunchIndex(\"0\").dnsName(\n                        \"ec2-174-129-81-68.compute-1.amazonaws.com\").imageId(\"ami-82e4b5c7\").instanceId(\"i-0799056f\")\n                        .instanceState(InstanceState.RUNNING).rawState(\"running\").instanceType(InstanceType.M1_SMALL)\n                        .ipAddress(\"174.129.81.68\").kernelId(\"aki-a71cf9ce\").keyName(\"adriancole.ec21\").launchTime(\n                                 dateService.iso8601DateOrSecondsDateParse(\"2009-11-09T03:00:34+0000\"))\n                        // MonitoringState.DISABLED,\n                        .availabilityZone(\"us-east-1c\").virtualizationType(\"paravirtual\").privateDnsName(\n                                 \"ip-10-243-42-70.ec2.internal\").privateIpAddress(\"10.243.42.70\").ramdiskId(\n                                 \"ari-a51cf9cc\").rootDeviceType(RootDeviceType.INSTANCE_STORE).build()),\n               \"993194456877\", null, \"r-a3c508cb\"));\n\n      Set<Reservation<? extends RunningInstance>> result = parseRunningInstances(\"/describe_instances_running.xml\");\n\n      assertEquals(result.toString(), contents.toString());\n      assertEquals(get(get(result, 0), 0).getInstanceState(), InstanceState.RUNNING);\n      assertEquals(get(get(result, 0), 0).getRawState(), \"running\");\n\n   }\n\n   public void testApplyInputStream() {\n      Set<Reservation<RunningInstance>> contents = ImmutableSet.of(new Reservation<RunningInstance>(defaultRegion,\n               ImmutableSet.of(\"default\"), ImmutableSet.of(RunningInstance.builder().region(defaultRegion).groupName(\n                        \"default\").amiLaunchIndex(\"23\").dnsName(\"ec2-72-44-33-4.compute-1.amazonaws.com\").imageId(\n                        \"ami-6ea54007\").instanceId(\"i-28a64341\").instanceState(InstanceState.RUNNING).rawState(\n                        \"running\").instanceType(InstanceType.M1_LARGE).kernelId(\"aki-ba3adfd3\").keyName(\n                        \"example-key-name\").launchTime(dateService.iso8601DateOrSecondsDateParse(\"2007-08-07T11:54:42.000Z\"))\n               // MonitoringState.DISABLED,\n                        .availabilityZone(\"us-east-1b\").virtualizationType(\"paravirtual\").privateDnsName(\n                                 \"10-251-50-132.ec2.internal\")// product codes\n                        // ImmutableSet.of(\"774F4FF8\")\n                        .tags(ImmutableMap.of(\"Name\", \"ec2-o\", \"Empty\", \"\"))\n                        .ramdiskId(\"ari-badbad00\").rootDeviceType(RootDeviceType.INSTANCE_STORE).build(),\n                        RunningInstance.builder().region(defaultRegion).groupName(\"default\").amiLaunchIndex(\"23\")\n                                 .dnsName(\"ec2-72-44-33-6.compute-1.amazonaws.com\").imageId(\"ami-6ea54007\").instanceId(\n                                          \"i-28a64435\").instanceState(InstanceState.RUNNING).rawState(\"running\")\n                                 .instanceType(InstanceType.M1_LARGE).kernelId(\"aki-ba3adfd3\").keyName(\n                                          \"example-key-name\").launchTime(\n                                          dateService.iso8601DateOrSecondsDateParse(\"2007-08-07T11:54:42.000Z\"))\n                                 // MonitoringState.DISABLED,\n                                 .availabilityZone(\"us-east-1b\").virtualizationType(\"paravirtual\").privateDnsName(\n                                          \"10-251-50-134.ec2.internal\")// product codes\n                                 // ImmutableSet.of(\"774F4FF8\")\n                                 .ramdiskId(\"ari-badbad00\").rootDeviceType(RootDeviceType.INSTANCE_STORE).build()),\n               \"UYY3TLBUXIEON5NQVUUX6OMPWBZIQNFM\", null, \"r-44a5402d\"));\n\n      Set<Reservation<? extends RunningInstance>> result = parseRunningInstances(\"/describe_instances.xml\");\n\n      assertEquals(result.toString(), contents.toString());\n      assertEquals(get(get(result, 0), 0).getInstanceState(), InstanceState.RUNNING);\n      assertEquals(get(get(result, 0), 0).getRawState(), \"running\");\n\n   }\n\n   public void testEBS() throws UnknownHostException {\n\n      Set<Reservation<RunningInstance>> contents = ImmutableSet.of(new Reservation<RunningInstance>(defaultRegion,\n               ImmutableSet.of(\"adriancole.ec2ebsingress\"), ImmutableSet.of(RunningInstance.builder().region(\n                        defaultRegion).groupName(\"adriancole.ec2ebsingress\").amiLaunchIndex(\"0\").dnsName(\n                        \"ec2-75-101-203-146.compute-1.amazonaws.com\").imageId(\"ami-849875ed\").instanceId(\"i-e564438d\")\n                        .instanceState(InstanceState.RUNNING).rawState(\"running\").instanceType(InstanceType.M1_SMALL)\n                        .ipAddress(\"75.101.203.146\").kernelId(\"aki-a71cf9ce\")\n                        .keyName(\"adriancole.ec2ebs1\")\n                        .launchTime(dateService.iso8601DateOrSecondsDateParse(\"2009-12-30T04:06:23.000Z\"))\n                        // MonitoringState.DISABLED\n                        .availabilityZone(\"us-east-1b\")\n                        // \"placement\"\n                        .virtualizationType(\"hvm\").privateDnsName(\"domU-12-31-39-09-CE-53.compute-1.internal\")\n                        .privateIpAddress(\"10.210.209.157\").ramdiskId(\"ari-a51cf9cc\")\n                        .rootDeviceType(RootDeviceType.EBS).rootDeviceName(\"/dev/sda1\").device(\n                                 \"/dev/sda1\",\n                                 new BlockDevice(\"vol-dc6ca8b5\", Attachment.Status.ATTACHED, dateService\n                                          .iso8601DateOrSecondsDateParse(\"2009-12-30T04:06:29.000Z\"), true)).build()),\n               \"993194456877\", null, \"r-596dd731\"));\n\n      Set<Reservation<? extends RunningInstance>> result = parseRunningInstances(\"/describe_instances_ebs.xml\");\n\n      assertEquals(result.toString(), contents.toString());\n      assertEquals(get(get(result, 0), 0).getInstanceState(), InstanceState.RUNNING);\n      assertEquals(get(get(result, 0), 0).getRawState(), \"running\");\n   }\n\n   static ParseSax<Set<Reservation<? extends RunningInstance>>> createParser() {\n      Injector injector = Guice.createInjector(new SaxParserModule(), new AbstractModule() {\n\n         @Override\n         protected void configure() {\n            bind(new TypeLiteral<Supplier<String>>() {\n            }).annotatedWith(Region.class).toInstance(Suppliers.ofInstance(\"us-east-1\"));\n         }\n\n      });\n      ParseSax<Set<Reservation<? extends RunningInstance>>> parser = injector\n               .getInstance(ParseSax.Factory.class)\n               .create(injector.getInstance(DescribeInstancesResponseHandler.class));\n      return parser;\n   }\n\n   public static Set<Reservation<? extends RunningInstance>> parseRunningInstances(String resource) {\n      InputStream is = DescribeInstancesResponseHandlerTest.class.getResourceAsStream(resource);\n      return createParser().parse(is);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/xml/DescribeKeyPairsResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\nimport java.util.Set;\n\nimport org.jclouds.ec2.domain.KeyPair;\nimport org.jclouds.http.functions.ParseSax;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code DescribeKeyPairsResponseHandler}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"DescribeKeyPairsResponseHandlerTest\")\npublic class DescribeKeyPairsResponseHandlerTest extends BaseEC2HandlerTest {\n   public void testApplyInputStream() {\n\n      InputStream is = getClass().getResourceAsStream(\"/describe_keypairs.xml\");\n\n      Set<KeyPair> expected = ImmutableSet.of(new KeyPair(defaultRegion, \"gsg-keypair\",\n               \"1f:51:ae:28:bf:89:e9:d8:1f:25:5d:37:2d:7d:b8:ca:9f:f5:f1:6f\", null, null));\n\n      DescribeKeyPairsResponseHandler handler = injector.getInstance(DescribeKeyPairsResponseHandler.class);\n      addDefaultRegionToHandler(handler);\n      Set<KeyPair> result = factory.create(handler).parse(is);\n      assertEquals(result, expected);\n   }\n\n   private void addDefaultRegionToHandler(ParseSax.HandlerWithResult<?> handler) {\n      handler.setContext(request);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/xml/DescribeRegionsResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\nimport java.net.URI;\nimport java.util.Map;\n\nimport org.jclouds.aws.domain.Region;\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.http.functions.config.SaxParserModule;\nimport org.jclouds.location.Provider;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.TypeLiteral;\n\n/**\n * Tests behavior of {@code DescribeRegionsResponseHandler}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"DescribeRegionsResponseHandlerTest\")\npublic class DescribeRegionsResponseHandlerTest extends BaseHandlerTest {\n   @BeforeTest\n   @Override\n   protected void setUpInjector() {\n      injector = Guice.createInjector(new SaxParserModule(), new AbstractModule() {\n\n         @Override\n         protected void configure() {\n            bind(new TypeLiteral<Supplier<URI>>(){}).annotatedWith(Provider.class).toInstance(\n                  Suppliers.ofInstance(URI.create(\"https://booya\")));\n         }\n\n      });\n      factory = injector.getInstance(ParseSax.Factory.class);\n      assert factory != null;\n   }\n\n   public void testApplyInputStream() {\n\n      InputStream is = getClass().getResourceAsStream(\n            \"/regionEndpoints.xml\");\n\n      Map<String, URI> expected = ImmutableMap\n            .<String, URI> of(Region.EU_WEST_1, URI\n                  .create(\"https://ec2.eu-west-1.amazonaws.com\"),\n                  Region.US_EAST_1, URI\n                        .create(\"https://ec2.us-east-1.amazonaws.com\"),\n                  Region.US_WEST_1, URI\n                        .create(\"https://ec2.us-west-1.amazonaws.com\"));\n\n      Map<String, URI> result = factory.create(\n            injector.getInstance(DescribeRegionsResponseHandler.class)).parse(\n            is);\n\n      assertEquals(result, expected);\n   }\n\n   public void testEuc() {\n\n      InputStream is = Strings2\n            .toInputStream(\"<DescribeRegionsResponse xmlns=\\\"http://ec2.amazonaws.com/doc/2010-08-31/\\\"><requestId>6a3b36f9-9ff4-47cf-87e3-285b08fbe5e5</requestId><regionInfo><item><regionName>Eucalyptus</regionName><regionEndpoint>http://173.205.188.130:8773/services/Eucalyptus</regionEndpoint></item><item><regionName>Walrus</regionName><regionEndpoint>http://173.205.188.130:8773/services/Walrus</regionEndpoint></item></regionInfo></DescribeRegionsResponse>\");\n\n      Map<String, URI> expected = ImmutableMap.<String, URI> of(\"Eucalyptus\",\n            URI.create(\"http://173.205.188.130:8773/services/Eucalyptus\"));\n\n      Map<String, URI> result = factory.create(\n            injector.getInstance(DescribeRegionsResponseHandler.class)).parse(\n            is);\n\n      assertEquals(result, expected);\n   }\n   \n   public void testEuc2() {\n\n      InputStream is = Strings2\n            .toInputStream(\"<?xml version=\\\"1.0\\\" ?><DescribeRegionsResponse xmlns=\\\"http://ec2.amazonaws.com/doc/2009-11-30/\\\"><requestId>1LAQRTCLTLPS6CEIC627</requestId><regionInfo><item><regionUrl>http://10.255.255.1:8773/services/Cloud</regionUrl><regionName>nova</regionName></item></regionInfo></DescribeRegionsResponse>\");\n\n      Map<String, URI> expected = ImmutableMap.<String, URI> of(\"nova\",\n            URI.create(\"http://10.255.255.1:8773/services/Cloud\"));\n\n      Map<String, URI> result = factory.create(\n            injector.getInstance(DescribeRegionsResponseHandler.class)).parse(\n            is);\n\n      assertEquals(result, expected);\n   }\n\n   public void testUnsupportedAdditionalRegionDoesntBreak() {\n\n      InputStream is = getClass().getResourceAsStream(\n            \"/regionEndpoints-additional.xml\");\n\n      Map<String, URI> expected = ImmutableMap\n            .<String, URI> of(\"jp-west-1\", URI\n                  .create(\"https://ec2.jp-west-1.amazonaws.com\"),\n                  Region.EU_WEST_1, URI\n                        .create(\"https://ec2.eu-west-1.amazonaws.com\"),\n                  Region.US_EAST_1, URI\n                        .create(\"https://ec2.us-east-1.amazonaws.com\"),\n                  Region.US_WEST_1, URI\n                        .create(\"https://ec2.us-west-1.amazonaws.com\"));\n\n      Map<String, URI> result = factory.create(\n            injector.getInstance(DescribeRegionsResponseHandler.class)).parse(\n            is);\n\n      assertEquals(result, expected);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/xml/DescribeSecurityGroupsResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\nimport java.util.Set;\n\nimport org.jclouds.ec2.domain.SecurityGroup;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.net.domain.IpPermission;\nimport org.jclouds.net.domain.IpProtocol;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.LinkedHashMultimap;\nimport com.google.common.collect.Multimap;\n\n/**\n * Tests behavior of {@code DescribeSecurityGroupsResponseHandler}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"DescribeSecurityGroupsResponseHandlerTest\")\npublic class DescribeSecurityGroupsResponseHandlerTest extends BaseEC2HandlerTest {\n   public void testApplyInputStream() {\n\n      InputStream is = getClass().getResourceAsStream(\"/describe_securitygroups.xml\");\n\n      Set<SecurityGroup> expected = ImmutableSet.of(\n            new SecurityGroup(defaultRegion, \"sg-3c6ef654\", \"WebServers\", \"UYY3TLBUXIEON5NQVUUX6OMPWBZIQNFM\", \"Web Servers\",\n                  ImmutableSet.of(new IpPermission(IpProtocol.TCP, 80, 80, ImmutableMultimap.<String, String> of(),\n                        ImmutableSet.<String> of(), ImmutableSet.of(\"0.0.0.0/0\"), ImmutableSet.<String> of()))),\n            new SecurityGroup(defaultRegion, \"sg-867309ab\", \"RangedPortsBySource\", \"UYY3TLBUXIEON5NQVUUX6OMPWBZIQNFM\", \"Group A\",\n                  ImmutableSet.of(new IpPermission(IpProtocol.TCP, 6000, 7000, ImmutableMultimap\n                        .<String, String> of(), ImmutableSet.<String> of(), ImmutableSet.<String> of(), ImmutableSet.<String> of()))));\n\n      DescribeSecurityGroupsResponseHandler handler = injector.getInstance(DescribeSecurityGroupsResponseHandler.class);\n      addDefaultRegionToHandler(handler);\n      Set<SecurityGroup> result = factory.create(handler).parse(is);\n\n      assertEquals(result.toString(), expected.toString());\n   }\n\n   // Response from OpenStack 1.1 EC2 API\n   public void testApplyInputStreamWithEmptyFields() {\n\n      InputStream is = getClass().getResourceAsStream(\"/describe_securitygroups_empty.xml\");\n\n      Multimap<String, String> userIdGroupPairs = LinkedHashMultimap.create();\n      userIdGroupPairs.put(\"UYY3TLBUXIEON5NQVUUX6OMPWBZIQNFM\", \"jclouds#cluster#world\");\n\n      Set<SecurityGroup> expected = ImmutableSet.of(\n            new SecurityGroup(defaultRegion, \"sg-3c6ef654\", \"jclouds#cluster#world\", \"UYY3TLBUXIEON5NQVUUX6OMPWBZIQNFM\", \"Cluster\",\n                  ImmutableSet.of(\n                        new IpPermission(IpProtocol.TCP, 22, 22, ImmutableMultimap.<String, String> of(),\n                              ImmutableSet.<String> of(), ImmutableSet.of(\"0.0.0.0/0\"), ImmutableSet.<String> of()),\n                        new IpPermission(IpProtocol.ALL, -1, -1, userIdGroupPairs,\n                              ImmutableSet.<String> of(), ImmutableSet.<String> of(), ImmutableSet.<String> of()))));\n\n      DescribeSecurityGroupsResponseHandler handler = injector.getInstance(DescribeSecurityGroupsResponseHandler.class);\n      addDefaultRegionToHandler(handler);\n      Set<SecurityGroup> result = factory.create(handler).parse(is);\n\n      assertEquals(result.toString(), expected.toString());\n   }\n\n   private void addDefaultRegionToHandler(ParseSax.HandlerWithResult<?> handler) {\n      handler.setContext(request);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/xml/DescribeSnapshotsResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\nimport java.util.Set;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.ec2.domain.Snapshot;\nimport org.jclouds.http.functions.ParseSax;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Sets;\n\n/**\n * Tests behavior of {@code DescribeSnapshotsResponseHandler}\n */\n//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"DescribeSnapshotsResponseHandlerTest\")\npublic class DescribeSnapshotsResponseHandlerTest extends BaseEC2HandlerTest {\n   public void testApplyInputStream() {\n      DateService dateService = injector.getInstance(DateService.class);\n      InputStream is = getClass().getResourceAsStream(\"/describe_snapshots.xml\");\n\n      Set<Snapshot> expected = Sets.newLinkedHashSet();\n      expected.add(new Snapshot(defaultRegion, \"snap-78a54011\", \"vol-4d826724\", 10,\n               Snapshot.Status.PENDING, dateService.iso8601DateParse(\"2008-05-07T12:51:50.000Z\"),\n               80, \"218213537122\", \"Daily Backup\", null));\n\n      DescribeSnapshotsResponseHandler handler = injector\n               .getInstance(DescribeSnapshotsResponseHandler.class);\n      addDefaultRegionToHandler(handler);\n      Set<Snapshot> result = factory.create(handler).parse(is);\n\n      assertEquals(result, expected);\n   }\n\n   private void addDefaultRegionToHandler(ParseSax.HandlerWithResult<?> handler) {\n      handler.setContext(request);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/xml/DescribeVolumesResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\nimport java.util.Set;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.ec2.domain.Attachment;\nimport org.jclouds.ec2.domain.Volume;\nimport org.jclouds.http.functions.ParseSax;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Sets;\n\n/**\n * Tests behavior of {@code DescribeVolumesResponseHandler}\n */\n//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"DescribeVolumesResponseHandlerTest\")\npublic class DescribeVolumesResponseHandlerTest extends BaseEC2HandlerTest {\n\n   public void testApplyInputStream() {\n      DateService dateService = injector.getInstance(DateService.class);\n      InputStream is = getClass().getResourceAsStream(\"/describe_volumes.xml\");\n\n      Set<Volume> expected = Sets.newLinkedHashSet();\n      expected.add(new Volume(defaultRegion, \"vol-2a21e543\", 1, null, \"us-east-1a\",\n               Volume.Status.AVAILABLE, dateService.iso8601DateParse(\"2009-12-28T05:42:53.000Z\"),\n               \"standard\", 0, false, Sets.<Attachment> newLinkedHashSet()));\n      expected.add(new Volume(defaultRegion, \"vol-4282672b\", 800, \"snap-536d1b3a\",\n              \"us-east-1a\", Volume.Status.IN_USE, dateService\n              .iso8601DateParse(\"2008-05-07T11:51:50.000Z\"),\n              \"standard\", 0, false,\n              Sets.<Attachment> newHashSet(new Attachment(defaultRegion, \"vol-4282672b\", \"i-6058a509\",\n                      \"/dev/sdh\", Attachment.Status.ATTACHED, dateService\n                      .iso8601DateParse(\"2008-05-07T12:51:50.000Z\")))));\n\n      DescribeVolumesResponseHandler handler = injector\n               .getInstance(DescribeVolumesResponseHandler.class);\n      addDefaultRegionToHandler(handler);\n      Set<Volume> result = factory.create(handler).parse(is);\n\n      assertEquals(result, expected);\n   }\n\n   private void addDefaultRegionToHandler(ParseSax.HandlerWithResult<?> handler) {\n      handler.setContext(request);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/xml/GetConsoleOutputResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code GetConsoleOutputResponseHandler}\n */\n//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"GetConsoleOutputResponseHandlerTest\")\npublic class GetConsoleOutputResponseHandlerTest extends BaseHandlerTest {\n   public void testApplyInputStream() {\n\n      InputStream is = getClass().getResourceAsStream(\n               \"/get_console_output_response.xml\");\n\n      String result = factory.create(\n               injector.getInstance(GetConsoleOutputResponseHandler.class)).parse(is);\n\n      String expected = \"Linux version 2.6.16-xenU (builder@patchbat.amazonsa) (gcc version 4.0.1 20050727 (Red Hat 4.0.1-5)) #1 SMP Thu Oct 26 08:41:26 SAST 2006\\n\" + \n              \"BIOS-provided physical RAM map:\\n\" + \n              \"Xen: 0000000000000000 - 000000006a400000 (usable)\\n\" + \n              \"980MB HIGHMEM available.\\n\" + \n              \"727MB LOWMEM available.\\n\" + \n              \"NX (Execute Disable) protection: active\\n\" + \n              \"IRQ lockup detection disabled\\n\" + \n              \"Built 1 zonelists\\n\" + \n              \"Kernel command line: root=/dev/sda1 ro 4\\n\" + \n              \"Enabling fast FPU save and restore... done.\\n\";\n\n      assertEquals(result, expected);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/xml/InstanceStateChangeHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\nimport java.util.Set;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.ec2.domain.InstanceState;\nimport org.jclouds.ec2.domain.InstanceStateChange;\nimport org.jclouds.http.functions.ParseSax;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code InstanceStateChangeHandler}\n */\n//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"InstanceStateChangeHandlerTest\")\npublic class InstanceStateChangeHandlerTest extends BaseEC2HandlerTest {\n\n   private DateService dateService;\n\n   @BeforeTest\n   @Override\n   protected void setUpInjector() {\n      super.setUpInjector();\n      dateService = injector.getInstance(DateService.class);\n      assert dateService != null;\n   }\n\n   public void testTerminate() {\n\n      InputStream is = getClass().getResourceAsStream(\"/terminate_instances.xml\");\n\n      Set<InstanceStateChange> expected = ImmutableSet.of(new InstanceStateChange(defaultRegion,\n               \"i-3ea74257\", InstanceState.SHUTTING_DOWN, InstanceState.RUNNING));\n\n      InstanceStateChangeHandler handler = injector.getInstance(InstanceStateChangeHandler.class);\n      addDefaultRegionToHandler(handler);\n      Set<InstanceStateChange> result = factory.create(handler).parse(is);\n      assertEquals(result, expected);\n   }\n\n   public void testStart() {\n\n      InputStream is = getClass().getResourceAsStream(\"/start_instances.xml\");\n\n      Set<InstanceStateChange> expected = ImmutableSet.of(new InstanceStateChange(defaultRegion,\n               \"i-10a64379\", InstanceState.PENDING, InstanceState.STOPPED));\n      InstanceStateChangeHandler handler = injector.getInstance(InstanceStateChangeHandler.class);\n      addDefaultRegionToHandler(handler);\n      Set<InstanceStateChange> result = factory.create(handler).parse(is);\n      assertEquals(result, expected);\n   }\n\n   public void testStop() {\n\n      InputStream is = getClass().getResourceAsStream(\"/stop_instances.xml\");\n\n      Set<InstanceStateChange> expected = ImmutableSet.of(new InstanceStateChange(defaultRegion,\n               \"i-10a64379\", InstanceState.STOPPING, InstanceState.RUNNING));\n\n      InstanceStateChangeHandler handler = injector.getInstance(InstanceStateChangeHandler.class);\n      addDefaultRegionToHandler(handler);\n      Set<InstanceStateChange> result = factory.create(handler).parse(is);\n      assertEquals(result, expected);\n   }\n\n   private void addDefaultRegionToHandler(ParseSax.HandlerWithResult<?> handler) {\n      handler.setContext(request);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/xml/KeyPairResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.io.InputStream;\n\nimport org.jclouds.ec2.domain.KeyPair;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.ssh.SshKeys;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code KeyPairResponseHandler}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"KeyPairResponseHandlerTest\")\npublic class KeyPairResponseHandlerTest extends BaseEC2HandlerTest {\n   public void testApplyInputStream() throws IOException {\n\n      InputStream is = getClass().getResourceAsStream(\"/create_keypair.xml\");\n\n      KeyPair expected = KeyPair.builder().region(defaultRegion).keyName(\"jclouds#test#0\").sha1OfPrivateKey(\n               \"13:36:74:b9:56:bb:07:96:c0:19:ab:00:7f:9f:06:d2:16:a0:45:32\").keyMaterial(\n               \"-----BEGIN RSA PRIVATE KEY-----\\n\"\n                        + \"MIIEowIBAAKCAQEA0CbFlhSdbMdad2ux2BVqk6Ut5fLKb0CdbqubGcEBfwsSz9Rp4Ile76P90MpV\\n\"\n                        + \"W1BGKL5V4MO+flG6dZnRWPVmgrNVyDTmEsALiMGjfEwbACEZ1A8C6mPa36wWO7MlxuyMjg8OczTB\\n\"\n                        + \"EXnHNDpxE5a6KowJtzFlmgjHk2Y+Q42UIqPx47lQUv5bdMDCnfNNomSzTVRjOZLUkDja+ybCKdux\\n\"\n                        + \"gqTsuInhuBRMx+wxff8Z43ECdJV6UPoXK3der1dlZunxGCFkCeYq0kCX7FZ7PV35X744jqhD8P+7\\n\"\n                        + \"y5prO4W+M3DWgChUx0OlbDbSHtDVlcfdbj/+4AKYKU6rQOqh+4DPDQIDAQABAoIBAHjQuEiXKJSV\\n\"\n                        + \"1U2RZcVtENInws9AL/2I/Jfa5Qh6vTqXG9EjklywfzkK72x7tDVvD3ngmAoAs5WwLFDL+fXvYhOk\\n\"\n                        + \"sbql8ZCahVdYRWME7XsSu2IZYHDZipXe1XzLS7b9X8uos5Ns4E8bZuNKtI1RJDdD1vPMqRNR2z0T\\n\"\n                        + \"0Dn3eC7t+t+t7PWaK5AXu2ot7DoOeG1QhqJbwd5pMkIn2ydBILytgmDk/2P3EtJGePIJIeQBicmw\\n\"\n                        + \"Z0KrJFa/K2cC8AtmMJUoZMo+mh1yemDbDLCZW30PjFHbZtcszS2cydAgq/HDFkZynvZG0zhbx/To\\n\"\n                        + \"jzcNza1AyypYwOwb2/9/ulXZp0UCgYEA+QFgWDfYLH2zwjU5b6e0UbIyd/X/yRZ+L8lOEBd0Bbu8\\n\"\n                        + \"qO3txaDbwi7o2mG7pJENHJ3u62CHjgTGDNW9V9Q8eNoGtj3uHvMvi7FdDEK8B6izdZyR7hmZmQ/5\\n\"\n                        + \"MIldelyiGZlz1KBSoy4FsCpA7hV7cI6H6x+Im24NxG90/wd/EgMCgYEA1f+cUyUisIO3yKOCf0hQ\\n\"\n                        + \"aL289q2//F2cbvBxtki6I8JzTg1H3oTO2WVrXQeCA3a/yiuRUatgGH4mxrpCF6byVJyqrEWAj4kU\\n\"\n                        + \"uTbhMgIYhLGoaF1e+vMirCRXUXox0i5X976ASzHn64V9JSd1B+UbKfpcFTYYnChmrRDzmhKN1a8C\\n\"\n                        + \"gYBTvIHAyO7ab18/BRUOllAOVSWhr8lXv0eqHEEzKh/rOaoFCRY3qpOcZpgJsGogumK1Z+sLnoeX\\n\"\n                        + \"W8WaVVp6KbY4UeGF8aedItyvVnLbB6ohzTqkZ4Wvk05S6cs75kXYO0SL5U3NiCiiFXz2NA9nwTOk\\n\"\n                        + \"s1nD2PPgiQ76Kx0mEkhKLwKBgFhHEJqv+AZu37Kx2NRe5WS/2KK9/DPD/hM5tv7mM3sq7Nvm2J3v\\n\"\n                        + \"lVDS6J5AyZ5aLzXcER9qncKcz6wtC7SsFs1Wr4VPSoBroRPikrVJbgnXK8yZr+O/xq7Scv7WdJTq\\n\"\n                        + \"rzkw6cWbObvLnltkUn/GQBVqBPBvF2nbtLdyBbuqKb5bAoGBAI1+aoJnvXEXxT4UHrMkQcY0eXRz\\n\"\n                        + \"3UdbzJmtjMW9CR6l9s11mV6PcZP4qnODp3nd6a+lPeL3wVYQ47DsTJ/Bx5dI17zA5mU57n6mV0a3\\n\"\n                        + \"DbSoPKSdaKTQdo2THnVE9P9sPKZWueAcsE4Yw/qcTjoxrtUnAH/AXN250v0tkKIOvMhu\\n\"\n                        + \"-----END RSA PRIVATE KEY-----\").build();\n\n      KeyPairResponseHandler handler = injector.getInstance(KeyPairResponseHandler.class);\n      addDefaultRegionToHandler(handler);\n      KeyPair result = factory.create(handler).parse(is);\n\n      assertEquals(result, expected);\n\n      assert SshKeys.privateKeyHasSha1(result.getKeyMaterial(), result.getSha1OfPrivateKey());\n      assert SshKeys.privateKeyHasFingerprint(result.getKeyMaterial(), result.getFingerprint());\n\n   }\n\n   private void addDefaultRegionToHandler(ParseSax.HandlerWithResult<?> handler) {\n      handler.setContext(request);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/xml/PermissionHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.ec2.domain.Permission;\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Sets;\n\n/**\n * Tests behavior of {@code PermissionHandler}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"PermissionHandlerTest\")\npublic class PermissionHandlerTest extends BaseHandlerTest {\n   public void testApplyInputStream() {\n\n      InputStream is = getClass().getResourceAsStream(\n               \"/describe_image_attribute_launchPermission.xml\");\n\n      Permission expected = new Permission(Sets.newHashSet(\"495219933132\"), Sets.newHashSet(\"all\"));\n\n      Permission result = factory.create(injector.getInstance(PermissionHandler.class)).parse(is);\n\n      assertEquals(result, expected);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/xml/RunInstancesResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.ec2.domain.InstanceState;\nimport org.jclouds.ec2.domain.InstanceType;\nimport org.jclouds.ec2.domain.Reservation;\nimport org.jclouds.ec2.domain.RootDeviceType;\nimport org.jclouds.ec2.domain.RunningInstance;\nimport org.jclouds.http.functions.ParseSax;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code RunInstancesResponseHandler}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"RunInstancesResponseHandlerTest\")\npublic class RunInstancesResponseHandlerTest extends BaseEC2HandlerTest {\n\n   private DateService dateService;\n\n   @BeforeTest\n   @Override\n   protected void setUpInjector() {\n      super.setUpInjector();\n      dateService = injector.getInstance(DateService.class);\n      assert dateService != null;\n   }\n\n   public void testEC2() {\n\n      InputStream is = getClass().getResourceAsStream(\"/run_instances.xml\");\n\n      Reservation<? extends RunningInstance> expected = new Reservation<RunningInstance>(defaultRegion, ImmutableSet\n               .of(\"default\"), ImmutableSet.of(\n\n      RunningInstance.builder().region(defaultRegion).groupName(\"default\").amiLaunchIndex(\"0\")\n               .imageId(\"ami-60a54009\").instanceId(\"i-2ba64342\").instanceState(InstanceState.PENDING).rawState(\n                        \"pending\").instanceType(InstanceType.M1_SMALL).keyName(\"example-key-name\").launchTime(\n                        dateService.iso8601DateParse(\"2007-08-07T11:51:50.000Z\"))// MonitoringState.ENABLED,\n               .availabilityZone(\"us-east-1b\").build(),\n\n      RunningInstance.builder().region(defaultRegion).groupName(\"default\").amiLaunchIndex(\"1\")\n               .imageId(\"ami-60a54009\").instanceId(\"i-2bc64242\").instanceState(InstanceState.PENDING).rawState(\n                        \"pending\").instanceType(InstanceType.M1_SMALL).keyName(\"example-key-name\").launchTime(\n                        dateService.iso8601DateParse(\"2007-08-07T11:51:50.000Z\"))// MonitoringState.ENABLED,\n               .availabilityZone(\"us-east-1b\").build(),\n\n      RunningInstance.builder().region(defaultRegion).groupName(\"default\").amiLaunchIndex(\"2\")\n               .imageId(\"ami-60a54009\").instanceId(\"i-2be64332\").instanceState(InstanceState.PENDING).rawState(\n                        \"pending\").instanceType(InstanceType.M1_SMALL).keyName(\"example-key-name\").launchTime(\n                        dateService.iso8601DateParse(\"2007-08-07T11:51:50.000Z\"))// MonitoringState.ENABLED,\n               .availabilityZone(\"us-east-1b\").build()),\n      \"AIDADH4IGTRXXKCD\", null, \"r-47a5402e\");\n\n      RunInstancesResponseHandler handler = injector.getInstance(RunInstancesResponseHandler.class);\n      addDefaultRegionToHandler(handler);\n      Reservation<? extends RunningInstance> result = factory.create(handler).parse(is);\n      assertEquals(result.toString(), expected.toString());\n   }\n\n   public void testCloudBridge() {\n\n      InputStream is = getClass().getResourceAsStream(\"/run_instances_cloudbridge.xml\");\n\n      Reservation<? extends RunningInstance> expected = new Reservation<RunningInstance>(defaultRegion, ImmutableSet\n               .of(\"jclouds#greenqloud-computeblock\"), ImmutableSet.of(\n\n      RunningInstance.builder().region(defaultRegion).groupName(\"jclouds#greenqloud-computeblock\").amiLaunchIndex(\"0\")\n               .imageId(\"qmi-9ac92558\").instanceId(\"i-01b0dac3\").instanceState(InstanceState.PENDING).rawState(\n                        \"pending\").instanceType(InstanceType.M1_SMALL).keyName(\"jclouds#greenqloud-computeblock#35\")\n                        .launchTime(dateService.iso8601DateParse(\"2012-06-15T19:06:35.000+00:00\"))\n                        .rootDeviceType(RootDeviceType.EBS).availabilityZone(\"is-1a\").build()),\n      \"56eeacd9-c790-45c3-85f3-e4380b55e1d8<\", null, \"r-f847a6ca\");\n\n      RunInstancesResponseHandler handler = injector.getInstance(RunInstancesResponseHandler.class);\n      addDefaultRegionToHandler(handler);\n      Reservation<? extends RunningInstance> result = factory.create(handler).parse(is);\n      assertEquals(result.toString(), expected.toString());\n   }\n\n   private void addDefaultRegionToHandler(ParseSax.HandlerWithResult<?> handler) {\n      handler.setContext(request);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/java/org/jclouds/ec2/xml/SnapshotHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ec2.xml;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.ec2.domain.Snapshot;\nimport org.jclouds.http.functions.ParseSax;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code SnapshotHandler}\n */\n//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"SnapshotHandlerTest\")\npublic class SnapshotHandlerTest extends BaseEC2HandlerTest {\n   public void testApplyInputStream() {\n      DateService dateService = injector.getInstance(DateService.class);\n      InputStream is = getClass().getResourceAsStream(\"/created_snapshot.xml\");\n\n      Snapshot expected = new Snapshot(defaultRegion, \"snap-78a54011\", \"vol-4d826724\", 10,\n               Snapshot.Status.PENDING, dateService.iso8601DateParse(\"2008-05-07T12:51:50.000Z\"),\n               60, \"213457642086\", \"Daily Backup\", null);\n\n      SnapshotHandler handler = injector.getInstance(SnapshotHandler.class);\n      addDefaultRegionToHandler(handler);\n      Snapshot result = factory.create(handler).parse(is);\n      assertEquals(result, expected);\n   }\n\n   private void addDefaultRegionToHandler(ParseSax.HandlerWithResult<?> handler) {\n      handler.setContext(request);\n   }\n}\n"
  },
  {
    "path": "apis/ec2/src/test/resources/allocate_address.xml",
    "content": "<AllocateAddressResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n  <publicIp>67.202.55.255</publicIp>\n</AllocateAddressResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/amzn_images.xml",
    "content": "<?xml version=\"1.0\"?>\n<DescribeImagesResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n    <requestId>6104eee1-affd-49d7-92a0-516cab8a8ba6</requestId>\n    <imagesSet>\n        <item>\n            <imageId>ami-82e4b5c7</imageId>\n            <imageLocation>137112412989/amzn-ami-0.9.7-beta.i386-ebs</imageLocation>\n            <imageState>available</imageState>\n            <imageOwnerId>137112412989</imageOwnerId>\n            <isPublic>true</isPublic>\n            <architecture>i386</architecture>\n            <imageType>machine</imageType>\n            <kernelId>aki-99a0f1dc</kernelId>\n            <name>amzn-ami-0.9.7-beta.i386-ebs</name>\n            <description>Amazon</description>\n            <rootDeviceType>ebs</rootDeviceType>\n            <rootDeviceName>/dev/sda1</rootDeviceName>\n            <blockDeviceMapping>\n                <item>\n                    <deviceName>/dev/sda1</deviceName>\n                    <ebs>\n                        <snapshotId>snap-e98b7b82</snapshotId>\n                        <volumeSize>10</volumeSize>\n                        <deleteOnTermination>true</deleteOnTermination>\n                    </ebs>\n                </item>\n            </blockDeviceMapping>\n            <virtualizationType>paravirtual</virtualizationType>\n        </item>\n        <item>\n            <imageId>ami-8ce4b5c9</imageId>\n            <imageLocation>137112412989/amzn-ami-0.9.7-beta.x86_64-ebs</imageLocation>\n            <imageState>available</imageState>\n            <imageOwnerId>137112412989</imageOwnerId>\n            <isPublic>true</isPublic>\n            <architecture>x86_64</architecture>\n            <imageType>machine</imageType>\n            <kernelId>aki-9ba0f1de</kernelId>\n            <name>amzn-ami-0.9.7-beta.x86_64-ebs</name>\n            <description>Amazon</description>\n            <rootDeviceType>ebs</rootDeviceType>\n            <rootDeviceName>/dev/sda1</rootDeviceName>\n            <blockDeviceMapping>\n                <item>\n                    <deviceName>/dev/sda1</deviceName>\n                    <ebs>\n                        <snapshotId>snap-8d8b7be6</snapshotId>\n                        <volumeSize>10</volumeSize>\n                        <deleteOnTermination>true</deleteOnTermination>\n                    </ebs>\n                </item>\n            </blockDeviceMapping>\n            <virtualizationType>paravirtual</virtualizationType>\n        </item>\n        <item>\n            <imageId>ami-f0e4b5b5</imageId>\n            <imageLocation>amzn-ami-us-west-1/amzn-ami-0.9.7-beta.i386.manifest.xml</imageLocation>\n            <imageState>available</imageState>\n            <imageOwnerId>137112412989</imageOwnerId>\n            <isPublic>true</isPublic>\n            <architecture>i386</architecture>\n            <imageType>machine</imageType>\n            <kernelId>aki-99a0f1dc</kernelId>\n            <name>amzn-ami-0.9.7-beta.i386-S3</name>\n            <description>Amazon Linux AMI i386 S3</description>\n            <rootDeviceType>instance-store</rootDeviceType>\n            <blockDeviceMapping/>\n            <virtualizationType>paravirtual</virtualizationType>\n        </item>\n        <item>\n            <imageId>ami-f2e4b5b7</imageId>\n            <imageLocation>amzn-ami-us-west-1/amzn-ami-0.9.7-beta.x86_64.manifest.xml</imageLocation>\n            <imageState>available</imageState>\n            <imageOwnerId>137112412989</imageOwnerId>\n            <isPublic>true</isPublic>\n            <architecture>x86_64</architecture>\n            <imageType>machine</imageType>\n            <kernelId>aki-9ba0f1de</kernelId>\n            <name>amzn-ami-0.9.7-beta.x86_64-S3</name>\n            <description>Amazon Linux AMI x86_64 S3</description>\n            <rootDeviceType>instance-store</rootDeviceType>\n            <blockDeviceMapping/>\n            <virtualizationType>paravirtual</virtualizationType>\n        </item>\n        <item>\n            <imageId>ami-85457ff1</imageId>\n            <imageLocation>amazon/NameGivesNoClue_Server-2008-R2_SP1-Language_Packs-64Bit-Base-2012.05.10</imageLocation>\n            <imageState>available</imageState>\n            <imageOwnerId>801119661308</imageOwnerId>\n            <isPublic>true</isPublic>\n            <architecture>x86_64</architecture>\n            <imageType>machine</imageType>\n            <platform>windows</platform>\n            <imageOwnerAlias>amazon</imageOwnerAlias>\n            <name>NameGivesNoClue_Server-2008-R2_SP1-Language_Packs-64Bit-Base-2012.05.10</name>\n            <description>Microsoft Windows Server 2008 R2 SP1 Datacenter 64-bit Multi-language AMI provided by Amazon</description>\n            <rootDeviceType>ebs</rootDeviceType>\n            <rootDeviceName>/dev/sda1</rootDeviceName>\n            <blockDeviceMapping>\n                <item>\n                    <deviceName>/dev/sda1</deviceName>\n                    <ebs>\n                        <snapshotId>snap-84a433ef</snapshotId>\n                        <volumeSize>30</volumeSize>\n                        <deleteOnTermination>true</deleteOnTermination>\n                    </ebs>\n                </item>\n            </blockDeviceMapping>\n            <virtualizationType>hvm</virtualizationType>\n            <hypervisor>xen</hypervisor>\n        </item>\n    </imagesSet>\n</DescribeImagesResponse>\n"
  },
  {
    "path": "apis/ec2/src/test/resources/attach.xml",
    "content": "<AttachVolumeResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n    <volumeId>vol-4d826724</volumeId>\n    <instanceId>i-6058a509</instanceId>\n    <device>/dev/sdh</device>\n    <status>attaching</status>\n    <attachTime>2008-05-07T11:51:50.000Z</attachTime>\n</AttachVolumeResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/authorize_securitygroup_ingress_response.xml",
    "content": "<AuthorizeSecurityGroupIngressResponse xmlns=\"http://ec2.amazonaws.com/doc/2011-05-15/\">\n    <requestId>9b6a9df1-bc19-4e56-9d11-7f8382538667</requestId>\n    <return>true</return>\n</AuthorizeSecurityGroupIngressResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/availabilityZones-ap-northeast-1.xml",
    "content": "<DescribeAvailabilityZonesResponse xmlns=\"http://ec2.amazonaws.com/doc/2011-05-15/\">\n    <requestId>24251909-7fb6-4080-8ca3-fbb5a1ddb02d</requestId>\n    <availabilityZoneInfo>\n        <item>\n            <zoneName>ap-northeast-1a</zoneName>\n            <zoneState>available</zoneState>\n            <regionName>ap-northeast-1</regionName>\n            <messageSet/>\n        </item>\n        <item>\n            <zoneName>ap-northeast-1b</zoneName>\n            <zoneState>available</zoneState>\n            <regionName>ap-northeast-1</regionName>\n            <messageSet/>\n        </item>\n    </availabilityZoneInfo>\n</DescribeAvailabilityZonesResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/availabilityZones-ap-southeast-1.xml",
    "content": "<DescribeAvailabilityZonesResponse xmlns=\"http://ec2.amazonaws.com/doc/2011-05-15/\">\n    <requestId>22c5332d-c331-4310-b695-e21e76c3fdb0</requestId>\n    <availabilityZoneInfo>\n        <item>\n            <zoneName>ap-southeast-1a</zoneName>\n            <zoneState>available</zoneState>\n            <regionName>ap-southeast-1</regionName>\n            <messageSet/>\n        </item>\n        <item>\n            <zoneName>ap-southeast-1b</zoneName>\n            <zoneState>available</zoneState>\n            <regionName>ap-southeast-1</regionName>\n            <messageSet/>\n        </item>\n    </availabilityZoneInfo>\n</DescribeAvailabilityZonesResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/availabilityZones-eu-west-1.xml",
    "content": "<DescribeAvailabilityZonesResponse xmlns=\"http://ec2.amazonaws.com/doc/2011-05-15/\">\n    <requestId>386c8215-6ec8-4495-aaa6-8c4175688093</requestId>\n    <availabilityZoneInfo>\n        <item>\n            <zoneName>eu-west-1a</zoneName>\n            <zoneState>available</zoneState>\n            <regionName>eu-west-1</regionName>\n            <messageSet/>\n        </item>\n        <item>\n            <zoneName>eu-west-1b</zoneName>\n            <zoneState>available</zoneState>\n            <regionName>eu-west-1</regionName>\n            <messageSet/>\n        </item>\n        <item>\n            <zoneName>eu-west-1c</zoneName>\n            <zoneState>available</zoneState>\n            <regionName>eu-west-1</regionName>\n            <messageSet/>\n        </item>\n    </availabilityZoneInfo>\n</DescribeAvailabilityZonesResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/availabilityZones-sa-east-1.xml",
    "content": "<DescribeAvailabilityZonesResponse xmlns=\"http://ec2.amazonaws.com/doc/2011-05-15/\">\n    <requestId>d2e09bd5-b2ec-4c6b-aac9-6bf1fa217cb5</requestId>\n    <availabilityZoneInfo>\n        <item>\n            <zoneName>sa-east-1a</zoneName>\n            <zoneState>available</zoneState>\n            <regionName>sa-east-1</regionName>\n            <messageSet/>\n        </item>\n        <item>\n            <zoneName>sa-east-1b</zoneName>\n            <zoneState>available</zoneState>\n            <regionName>sa-east-1</regionName>\n            <messageSet/>\n        </item>\n    </availabilityZoneInfo>\n</DescribeAvailabilityZonesResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/availabilityZones-us-east-1.xml",
    "content": "<DescribeAvailabilityZonesResponse xmlns=\"http://ec2.amazonaws.com/doc/2011-05-15/\">\n    <requestId>ed825abf-edbb-4677-83d5-0fbd86ce5a5d</requestId>\n    <availabilityZoneInfo>\n        <item>\n            <zoneName>us-east-1a</zoneName>\n            <zoneState>available</zoneState>\n            <regionName>us-east-1</regionName>\n            <messageSet/>\n        </item>\n        <item>\n            <zoneName>us-east-1b</zoneName>\n            <zoneState>available</zoneState>\n            <regionName>us-east-1</regionName>\n            <messageSet/>\n        </item>\n        <item>\n            <zoneName>us-east-1c</zoneName>\n            <zoneState>available</zoneState>\n            <regionName>us-east-1</regionName>\n            <messageSet/>\n        </item>\n        <item>\n            <zoneName>us-east-1d</zoneName>\n            <zoneState>available</zoneState>\n            <regionName>us-east-1</regionName>\n            <messageSet/>\n        </item>\n        <item>\n            <zoneName>us-east-1e</zoneName>\n            <zoneState>available</zoneState>\n            <regionName>us-east-1</regionName>\n            <messageSet/>\n        </item>\n    </availabilityZoneInfo>\n</DescribeAvailabilityZonesResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/availabilityZones-us-west-1.xml",
    "content": "<DescribeAvailabilityZonesResponse xmlns=\"http://ec2.amazonaws.com/doc/2011-05-15/\">\n    <requestId>dbfb2a5f-ce75-49fb-846b-e2cf2fc5cdbb</requestId>\n    <availabilityZoneInfo>\n        <item>\n            <zoneName>us-west-1a</zoneName>\n            <zoneState>available</zoneState>\n            <regionName>us-west-1</regionName>\n            <messageSet/>\n        </item>\n        <item>\n            <zoneName>us-west-1b</zoneName>\n            <zoneState>available</zoneState>\n            <regionName>us-west-1</regionName>\n            <messageSet/>\n        </item>\n        <item>\n            <zoneName>us-west-1c</zoneName>\n            <zoneState>available</zoneState>\n            <regionName>us-west-1</regionName>\n            <messageSet/>\n        </item>\n    </availabilityZoneInfo>\n</DescribeAvailabilityZonesResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/availabilityZones-us-west-2.xml",
    "content": "<DescribeAvailabilityZonesResponse xmlns=\"http://ec2.amazonaws.com/doc/2011-05-15/\">\n    <requestId>e40c2bc4-7231-4df1-a604-202bb8333332</requestId>\n    <availabilityZoneInfo>\n        <item>\n            <zoneName>us-west-2a</zoneName>\n            <zoneState>available</zoneState>\n            <regionName>us-west-2</regionName>\n            <messageSet/>\n        </item>\n        <item>\n            <zoneName>us-west-2b</zoneName>\n            <zoneState>available</zoneState>\n            <regionName>us-west-2</regionName>\n            <messageSet/>\n        </item>\n        <item>\n            <zoneName>us-west-2c</zoneName>\n            <zoneState>available</zoneState>\n            <regionName>us-west-2</regionName>\n            <messageSet/>\n        </item>\n    </availabilityZoneInfo>\n</DescribeAvailabilityZonesResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/availabilityZones.xml",
    "content": "<?xml version=\"1.0\"?>\n<DescribeAvailabilityZonesResponse\n    xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n    <requestId>ec786fbb-338a-4f6f-a479-293773911366</requestId>\n    <availabilityZoneInfo>\n        <item>\n            <zoneName>us-east-1a</zoneName>\n            <zoneState>available</zoneState>\n            <regionName>us-east-1</regionName>\n            <messageSet />\n        </item>\n        <item>\n            <zoneName>us-east-1b</zoneName>\n            <zoneState>available</zoneState>\n            <regionName>us-east-1</regionName>\n            <messageSet />\n        </item>\n        <item>\n            <zoneName>us-east-1c</zoneName>\n            <zoneState>available</zoneState>\n            <regionName>us-east-1</regionName>\n            <messageSet>\n                <item>\n                    <message>our service is awesome</message>\n                </item>\n            </messageSet>\n        </item>\n        <item>\n            <zoneName>us-east-1d</zoneName>\n            <zoneState>downlikeaclown</zoneState>\n            <regionName>us-east-1</regionName>\n            <messageSet />\n        </item>\n    </availabilityZoneInfo>\n</DescribeAvailabilityZonesResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/bundle_instance.xml",
    "content": "<BundleInstanceResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-04-04/\">\n\t<requestId>bun-c1a540a8</requestId>\n\t<bundleInstanceTask>\n\t\t<instanceId>i-12345678</instanceId>\n\t\t<bundleId>bun-c1a540a8</bundleId>\n\t\t<state>bundling</state>\n\t\t<startTime>2008-10-07T11:41:50.000Z</startTime>\n\t\t<updateTime>2008-10-07T11:51:50.000Z</updateTime>\n\t\t<progress>70%</progress>\n\t\t<storage>\n\t\t\t<S3>\n\t\t\t\t<bucket>my-bucket</bucket>\n\t\t\t\t<prefix>winami</prefix>\n\t\t\t</S3>\n\t\t</storage>\n\t</bundleInstanceTask>\n</BundleInstanceResponse>\n\n"
  },
  {
    "path": "apis/ec2/src/test/resources/cancel_bundle_task.xml",
    "content": "<CancelBundleTaskResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-04-04/\">\n\t<bundleInstanceTask>\n\t\t<instanceId>i-12345678</instanceId>\n\t\t<bundleId>bun-cla322b9</bundleId>\n\t\t<state>canceling</state>\n\t\t<startTime>2008-10-07T11:41:50.000Z</startTime>\n\t\t<updateTime>2008-10-07T11:51:50.000Z</updateTime>\n\t\t<progress>20%</progress>\n\t\t<storage>\n\t\t\t<S3>\n\t\t\t\t<bucket>my-bucket</bucket>\n\t\t\t\t<prefix>my-new-image</prefix>\n\t\t\t</S3>\n\t\t</storage>\n\t</bundleInstanceTask>\n</CancelBundleTaskResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/create_keypair.xml",
    "content": "<CreateKeyPairResponse xmlns=\"http://ec2.amazonaws.com/doc/2011-05-15/\">\n    <requestId>bb5e3a3c-e254-454d-ba29-d607cdf6357a</requestId>\n    <keyName>jclouds#test#0</keyName>\n    <keyFingerprint>13:36:74:b9:56:bb:07:96:c0:19:ab:00:7f:9f:06:d2:16:a0:45:32</keyFingerprint>\n    <keyMaterial>-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEA0CbFlhSdbMdad2ux2BVqk6Ut5fLKb0CdbqubGcEBfwsSz9Rp4Ile76P90MpV\nW1BGKL5V4MO+flG6dZnRWPVmgrNVyDTmEsALiMGjfEwbACEZ1A8C6mPa36wWO7MlxuyMjg8OczTB\nEXnHNDpxE5a6KowJtzFlmgjHk2Y+Q42UIqPx47lQUv5bdMDCnfNNomSzTVRjOZLUkDja+ybCKdux\ngqTsuInhuBRMx+wxff8Z43ECdJV6UPoXK3der1dlZunxGCFkCeYq0kCX7FZ7PV35X744jqhD8P+7\ny5prO4W+M3DWgChUx0OlbDbSHtDVlcfdbj/+4AKYKU6rQOqh+4DPDQIDAQABAoIBAHjQuEiXKJSV\n1U2RZcVtENInws9AL/2I/Jfa5Qh6vTqXG9EjklywfzkK72x7tDVvD3ngmAoAs5WwLFDL+fXvYhOk\nsbql8ZCahVdYRWME7XsSu2IZYHDZipXe1XzLS7b9X8uos5Ns4E8bZuNKtI1RJDdD1vPMqRNR2z0T\n0Dn3eC7t+t+t7PWaK5AXu2ot7DoOeG1QhqJbwd5pMkIn2ydBILytgmDk/2P3EtJGePIJIeQBicmw\nZ0KrJFa/K2cC8AtmMJUoZMo+mh1yemDbDLCZW30PjFHbZtcszS2cydAgq/HDFkZynvZG0zhbx/To\njzcNza1AyypYwOwb2/9/ulXZp0UCgYEA+QFgWDfYLH2zwjU5b6e0UbIyd/X/yRZ+L8lOEBd0Bbu8\nqO3txaDbwi7o2mG7pJENHJ3u62CHjgTGDNW9V9Q8eNoGtj3uHvMvi7FdDEK8B6izdZyR7hmZmQ/5\nMIldelyiGZlz1KBSoy4FsCpA7hV7cI6H6x+Im24NxG90/wd/EgMCgYEA1f+cUyUisIO3yKOCf0hQ\naL289q2//F2cbvBxtki6I8JzTg1H3oTO2WVrXQeCA3a/yiuRUatgGH4mxrpCF6byVJyqrEWAj4kU\nuTbhMgIYhLGoaF1e+vMirCRXUXox0i5X976ASzHn64V9JSd1B+UbKfpcFTYYnChmrRDzmhKN1a8C\ngYBTvIHAyO7ab18/BRUOllAOVSWhr8lXv0eqHEEzKh/rOaoFCRY3qpOcZpgJsGogumK1Z+sLnoeX\nW8WaVVp6KbY4UeGF8aedItyvVnLbB6ohzTqkZ4Wvk05S6cs75kXYO0SL5U3NiCiiFXz2NA9nwTOk\ns1nD2PPgiQ76Kx0mEkhKLwKBgFhHEJqv+AZu37Kx2NRe5WS/2KK9/DPD/hM5tv7mM3sq7Nvm2J3v\nlVDS6J5AyZ5aLzXcER9qncKcz6wtC7SsFs1Wr4VPSoBroRPikrVJbgnXK8yZr+O/xq7Scv7WdJTq\nrzkw6cWbObvLnltkUn/GQBVqBPBvF2nbtLdyBbuqKb5bAoGBAI1+aoJnvXEXxT4UHrMkQcY0eXRz\n3UdbzJmtjMW9CR6l9s11mV6PcZP4qnODp3nd6a+lPeL3wVYQ47DsTJ/Bx5dI17zA5mU57n6mV0a3\nDbSoPKSdaKTQdo2THnVE9P9sPKZWueAcsE4Yw/qcTjoxrtUnAH/AXN250v0tkKIOvMhu\n-----END RSA PRIVATE KEY-----</keyMaterial>\n</CreateKeyPairResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/created_securitygroup.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<CreateSecurityGroupResponse xmlns=\"http://ec2.amazonaws.com/doc/2011-05-15/\">\n    <requestId>8bf8a888-33af-459a-8424-13d4da0c2341</requestId>\n    <return>true</return>\n    <groupId>sg-3c6ef654</groupId>\n</CreateSecurityGroupResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/created_snapshot.xml",
    "content": "<CreateSnapshotResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n  <snapshotId>snap-78a54011</snapshotId>\n  <volumeId>vol-4d826724</volumeId>\n  <volumeSize>10</volumeSize>\n  <status>pending</status>\n  <startTime>2008-05-07T12:51:50.000Z</startTime>\n  <progress>60%</progress>\n  <ownerId>213457642086</ownerId>\n  <description>Daily Backup</description>\n</CreateSnapshotResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/created_volume.xml",
    "content": "<CreateVolumeResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n    <requestId>0c67a4c9-d7ec-45ef-8016-bf7944668962</requestId>\n    <volumeId>vol-2a21e543</volumeId>\n    <size>1</size>\n    <snapshotId/>\n    <availabilityZone>us-east-1a</availabilityZone>\n    <status>creating</status>\n    <createTime>2009-12-28T05:42:53.000Z</createTime>\n    <volumeType>standard</volumeType>\n    <iops>0</iops>\n    <encrypted>false</encrypted>\n</CreateVolumeResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/delete_keypair.xml",
    "content": "<DeleteKeyPairResponse xmlns=\"http://ec2.amazonaws.com/doc/2014-10-01/\">\n <requestId>d4904fd9-82c2-4ea5-adfe-a9cc3EXAMPLE</requestId>\n <return>true</return>\n</DeleteKeyPairResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/delete_placementgroup.xml",
    "content": "<DeletePlacementGroupResponse xmlns=\"http://ec2.amazonaws.com/doc/2014-10-01/\">\n <requestId>d4904fd9-82c2-4ea5-adfe-a9cc3EXAMPLE</requestId>\n <return>true</return>\n</DeletePlacementGroupResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/delete_securitygroup.xml",
    "content": "<DeleteSecurityGroupResponse xmlns=\"http://ec2.amazonaws.com/doc/2013-02-01/\">\n  <requestId>59dbff89-35bd-4eac-99ed-be587EXAMPLE</requestId> \n  <return>true</return>\n</DeleteSecurityGroupResponse>\n"
  },
  {
    "path": "apis/ec2/src/test/resources/describe_addresses.xml",
    "content": "<DescribeAddressesResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n    <addressesSet>\n        <item>\n            <instanceId>i-f15ebb98</instanceId>\n            <publicIp>67.202.55.255</publicIp>\n        </item>\n        <item>\n            <publicIp>67.202.55.233</publicIp>\n        </item>\n    </addressesSet>\n</DescribeAddressesResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/describe_addresses_single.xml",
    "content": "<DescribeAddressesResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n    <addressesSet>\n        <item>\n            <instanceId>i-f15ebb98</instanceId>\n            <publicIp>67.202.55.255</publicIp>\n        </item>\n    </addressesSet>\n</DescribeAddressesResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/describe_addresses_with_tags.xml",
    "content": "<DescribeAddressesResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n    <addressesSet>\n        <item>\n            <instanceId>i-f15ebb98</instanceId>\n            <publicIp>67.202.55.255</publicIp>\n        </item>\n        <item>\n            <publicIp>67.202.55.233</publicIp>\n        </item>\n        <item>\n            <publicIp>54.76.27.192</publicIp>\n            <tagSet>\n                <item>\n                    <key>Name</key>\n                    <value>value-fa97d19c</value>\n                </item>\n                <item>\n                    <key>Empty</key>\n                    <value/>\n                </item>\n            </tagSet>\n        </item>\n    </addressesSet>\n</DescribeAddressesResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/describe_bundle_tasks.xml",
    "content": "<DescribeBundleTasksResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n\t<bundleInstanceTasksSet>\n\t\t<item>\n\t\t\t<instanceId>i-12345678</instanceId>\n\t\t\t<bundleId>bun-c1a540a8</bundleId>\n\t\t\t<state>canceling</state>\n\t\t\t<startTime>2008-10-07T11:41:50.000Z</startTime>\n\t\t\t<updateTime>2008-10-07T11:51:50.000Z</updateTime>\n\t\t\t<progress>20%</progress>\n\t\t\t<storage>\n\t\t\t\t<S3>\n\t\t\t\t\t<bucket>my-bucket</bucket>\n\t\t\t\t\t<prefix>winami</prefix>\n\t\t\t\t</S3>\n\t\t\t</storage>\n\t\t</item>\n\t</bundleInstanceTasksSet>\n</DescribeBundleTasksResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/describe_image_attribute_blockDeviceMapping.xml",
    "content": "<DescribeInstanceAttributeResponse\n   xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n    <instanceId>i-7f629614</instanceId>\n    <blockDeviceMapping>\n        <item>\n            <deviceName>/dev/sda1</deviceName>\n            <ebs>\n                <volumeId>vol-d74b82be</volumeId>\n                <status>attached</status>\n                <attachTime>2010-02-20T18:25:26.000Z</attachTime>\n                <deleteOnTermination>true</deleteOnTermination>\n            </ebs>\n        </item>\n        <item>\n            <deviceName>/dev/sdf</deviceName>\n            <ebs>\n                <volumeId>vol-another</volumeId>\n                <status>detached</status>\n                <attachTime>2010-02-20T19:26:26.000Z</attachTime>\n                <deleteOnTermination>false</deleteOnTermination>\n            </ebs>\n        </item>\n    </blockDeviceMapping>\n</DescribeInstanceAttributeResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/describe_image_attribute_launchPermission.xml",
    "content": "<DescribeImageAttributeResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n  <imageId>ami-61a54008</imageId>\n  <launchPermission>\n    <item>\n      <group>all</group>\n    </item>\n    <item>\n      <userId>495219933132</userId>\n    </item>\n  </launchPermission>\n</DescribeImageAttributeResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/describe_images.xml",
    "content": "<DescribeImagesResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n    <imagesSet>\n        <item>\n            <imageId>ami-be3adfd7</imageId>\n            <imageLocation>ec2-public-images/fedora-8-i386-base-v1.04.manifest.xml</imageLocation>\n            <imageState>available</imageState>\n            <imageOwnerId>206029621532</imageOwnerId>\n            <isPublic>false</isPublic>\n            <productCodes>\n                <item>\n                    <productCode>9961934F</productCode>\n                </item>\n            </productCodes>\n            <architecture>i386</architecture>\n            <imageType>machine</imageType>\n            <kernelId>aki-4438dd2d</kernelId>\n            <ramdiskId>ari-4538dd2c</ramdiskId>\n            <rootDeviceType>instance-store</rootDeviceType>\n            <blockDeviceMapping />\n            <virtualizationType>paravirtual</virtualizationType>\n        </item>\n    </imagesSet>\n</DescribeImagesResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/describe_images_ebs.xml",
    "content": "<?xml version=\"1.0\"?>\n<DescribeImagesResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n    <requestId>c952eb86-3a28-4987-8df5-dd08e3e8e502</requestId>\n    <imagesSet>\n        <item>\n            <imageId>ami-246f8d4d</imageId>\n            <imageLocation>706093390852/websrv_2009-12-10\n            </imageLocation>\n            <imageState>available</imageState>\n            <imageOwnerId>706093390852</imageOwnerId>\n            <isPublic>true</isPublic>\n            <architecture>i386</architecture>\n            <imageType>machine</imageType>\n            <platform>windows</platform>\n            <name>websrv_2009-12-10</name>\n            <description>Web Server AMI</description>\n            <rootDeviceType>ebs</rootDeviceType>\n            <rootDeviceName>/dev/sda1</rootDeviceName>\n            <blockDeviceMapping>\n                <item>\n                    <deviceName>/dev/sda1</deviceName>\n                    <ebs>\n                        <snapshotId>snap-d01272b9</snapshotId>\n                        <volumeSize>30</volumeSize>\n                        <deleteOnTermination>true</deleteOnTermination>\n                        <volumeType>standard</volumeType>\n                        <encrypted>false</encrypted>\n                    </ebs>\n                </item>\n                <item>\n                    <deviceName>xvdf</deviceName>\n                    <ebs>\n                        <snapshotId>snap-d31272ba</snapshotId>\n                        <volumeSize>250</volumeSize>\n                        <deleteOnTermination>false</deleteOnTermination>\n                        <volumeType>standard</volumeType>\n                        <encrypted>false</encrypted>\n                    </ebs>\n                </item>\n            </blockDeviceMapping>\n            <virtualizationType>hvm</virtualizationType>\n        </item>\n    </imagesSet>\n</DescribeImagesResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/describe_images_imageextension0.xml",
    "content": "<DescribeImagesResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n  <imagesSet>\n    <item>\n      <imageId>ami-0</imageId>\n      <imageLocation>ec2-public-images/fedora-8-i386-base-v1.04.manifest.xml\n      </imageLocation>\n      <imageState>available</imageState>\n      <imageOwnerId>206029621532</imageOwnerId>\n      <isPublic>false</isPublic>\n      <productCodes>\n        <item>\n          <productCode>9961934F</productCode>\n        </item>\n      </productCodes>\n      <architecture>i386</architecture>\n      <imageType>machine</imageType>\n      <kernelId>aki-4438dd2d</kernelId>\n      <ramdiskId>ari-4538dd2c</ramdiskId>\n      <rootDeviceType>instance-store</rootDeviceType>\n      <blockDeviceMapping />\n      <virtualizationType>paravirtual</virtualizationType>\n    </item>\n  </imagesSet>\n</DescribeImagesResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/describe_images_imageextension1.xml",
    "content": "<DescribeImagesResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n  <imagesSet>\n    <item>\n      <imageId>ami-1</imageId>\n      <imageLocation>ec2-public-images/fedora-8-i386-base-v1.04.manifest.xml\n      </imageLocation>\n      <imageState>deregistered</imageState>\n      <imageOwnerId>206029621532</imageOwnerId>\n      <isPublic>false</isPublic>\n      <productCodes>\n        <item>\n          <productCode>9961934F</productCode>\n        </item>\n      </productCodes>\n      <architecture>i386</architecture>\n      <imageType>machine</imageType>\n      <kernelId>aki-4438dd2d</kernelId>\n      <ramdiskId>ari-4538dd2c</ramdiskId>\n      <rootDeviceType>instance-store</rootDeviceType>\n      <blockDeviceMapping />\n      <virtualizationType>paravirtual</virtualizationType>\n    </item>\n  </imagesSet>\n</DescribeImagesResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/describe_images_imageextension2.xml",
    "content": "<DescribeImagesResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n  <imagesSet>\n    <item>\n      <imageId>ami-2</imageId>\n      <imageLocation>ec2-public-images/fedora-8-i386-base-v1.04.manifest.xml\n      </imageLocation>\n      <imageState>unrecognized</imageState>\n      <imageOwnerId>206029621532</imageOwnerId>\n      <isPublic>false</isPublic>\n      <productCodes>\n        <item>\n          <productCode>9961934F</productCode>\n        </item>\n      </productCodes>\n      <architecture>i386</architecture>\n      <imageType>machine</imageType>\n      <kernelId>aki-4438dd2d</kernelId>\n      <ramdiskId>ari-4538dd2c</ramdiskId>\n      <rootDeviceType>instance-store</rootDeviceType>\n      <blockDeviceMapping />\n      <virtualizationType>paravirtual</virtualizationType>\n    </item>\n  </imagesSet>\n</DescribeImagesResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/describe_images_nova.xml",
    "content": "<?xml version=\"1.0\" ?>\n<DescribeImagesResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-04-04/\">\n    <requestId>f3daebdd-c435-4af4-86fc-d467e4530e57</requestId>\n    <imagesSet>\n        <item>\n            <displayName>CentOS 6.2 Server 64-bit 20120125</displayName>\n            <description />\n            <imageOwnerId />\n            <isPublic>true</isPublic>\n            <imageId>ami-0000054e</imageId>\n            <imageState>available</imageState>\n            <rootDeviceType>instance-store</rootDeviceType>\n            <architecture>x86_64</architecture>\n            <imageLocation>local (CentOS 6.2 Server 64-bit 20120125)</imageLocation>\n            <kernelId>aki-0000054c</kernelId>\n            <ramdiskId>ari-0000054d</ramdiskId>\n            <rootDeviceName>/dev/sda1</rootDeviceName>\n            <imageType>machine</imageType>\n        </item>\n    </imagesSet>\n</DescribeImagesResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/describe_images_tags.xml",
    "content": "<DescribeImagesResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n    <imagesSet>\n        <item>\n            <imageId>ami-be3adfd7</imageId>\n            <imageLocation>ec2-public-images/fedora-8-i386-base-v1.04.manifest.xml</imageLocation>\n            <imageState>available</imageState>\n            <imageOwnerId>206029621532</imageOwnerId>\n            <isPublic>false</isPublic>\n            <productCodes>\n                <item>\n                    <productCode>9961934F</productCode>\n                </item>\n            </productCodes>\n            <architecture>i386</architecture>\n            <imageType>machine</imageType>\n            <kernelId>aki-4438dd2d</kernelId>\n            <ramdiskId>ari-4538dd2c</ramdiskId>\n            <rootDeviceType>instance-store</rootDeviceType>\n            <blockDeviceMapping />\n            <virtualizationType>paravirtual</virtualizationType>\n            <tagSet>\n                <item>\n                    <key>Name</key>\n                    <value>Some machine name</value>\n                </item>\n                <item>\n                    <key>Second</key>\n                    <value>Second value</value>\n                </item>\n            </tagSet>\n        </item>\n    </imagesSet>\n</DescribeImagesResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/describe_images_windows.xml",
    "content": "<DescribeImagesResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n    <imagesSet>\n        <item>\n            <imageId>ami-02eb086b</imageId>\n            <imageLocation>aws-solutions-amis/SqlSvrStd2003r2-x86_64-Win_SFWBasic5.1-v1.0.manifest.xml</imageLocation>\n            <imageState>available</imageState>\n            <imageOwnerId>771350841976</imageOwnerId>            \n            <isPublic>true</isPublic>\n            <productCodes>\n                <item>\n                    <productCode>5771E9A6</productCode>\n                </item>\n            </productCodes>\n            <architecture>x86_64</architecture>\n            <imageType>machine</imageType>\n            <platform>windows</platform>\n            <rootDeviceType>instance-store</rootDeviceType>\n            <blockDeviceMapping/>\n            <virtualizationType>paravirtual</virtualizationType>\n        </item>\n    </imagesSet>\n</DescribeImagesResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/describe_instances.xml",
    "content": "<DescribeInstancesResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n    <reservationSet>\n        <item>\n            <reservationId>r-44a5402d</reservationId>\n            <ownerId>UYY3TLBUXIEON5NQVUUX6OMPWBZIQNFM</ownerId>\n            <groupSet>\n                <item>\n                    <groupId>default</groupId>\n                </item>\n            </groupSet>\n            <instancesSet>\n                <item>\n                    <instanceId>i-28a64341</instanceId>\n                    <imageId>ami-6ea54007</imageId>\n                    <instanceState>\n                        <code>0</code>\n                        <name>running</name>\n                    </instanceState>\n                    <privateDnsName>10-251-50-132.ec2.internal\n                    </privateDnsName>\n                    <dnsName>ec2-72-44-33-4.compute-1.amazonaws.com\n                    </dnsName>\n                    <keyName>example-key-name</keyName>\n                    <amiLaunchIndex>23</amiLaunchIndex>\n                    <productCodesSet>\n                        <item>\n                            <productCode>774F4FF8</productCode>\n                        </item>\n                    </productCodesSet>\n                    <instanceType>m1.large</instanceType>\n                    <launchTime>2007-08-07T11:54:42.000Z</launchTime>\n                    <placement>\n                        <availabilityZone>us-east-1b</availabilityZone>\n                    </placement>\n                    <monitoring>\n                        <state>disabled</state>\n                    </monitoring>\n                    <kernelId>aki-ba3adfd3</kernelId>\n                    <ramdiskId>ari-badbad00</ramdiskId>\n                    <hypervisor>xen</hypervisor>\n                    <tagSet>\n                       <item>\n                           <key>Name</key>\n                           <value>ec2-o</value>\n                       </item>\n                       <item>\n                           <key>Empty</key>\n                           <value />\n                       </item>\n                    </tagSet>\n                </item>\n                <item>\n                    <instanceId>i-28a64435</instanceId>\n                    <imageId>ami-6ea54007</imageId>\n                    <instanceState>\n                        <code>0</code>\n                        <name>running</name>\n                    </instanceState>\n                    <privateDnsName>10-251-50-134.ec2.internal\n                    </privateDnsName>\n                    <dnsName>ec2-72-44-33-6.compute-1.amazonaws.com\n                    </dnsName>\n                    <keyName>example-key-name</keyName>\n                    <amiLaunchIndex>23</amiLaunchIndex>\n                    <productCodesSet>\n                        <item>\n                            <productCode>774F4FF8</productCode>\n                        </item>\n                    </productCodesSet>\n                    <instanceType>m1.large</instanceType>\n                    <launchTime>2007-08-07T11:54:42.000Z</launchTime>\n                    <placement>\n                        <availabilityZone>us-east-1b</availabilityZone>\n                    </placement>\n                    <monitoring>\n                        <state>disabled</state>\n                    </monitoring>\n                    <kernelId>aki-ba3adfd3</kernelId>\n                    <ramdiskId>ari-badbad00</ramdiskId>\n                    <hypervisor>xen</hypervisor>\n                </item>\n            </instancesSet>\n        </item>\n    </reservationSet>\n</DescribeInstancesResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/describe_instances_ebs.xml",
    "content": "<?xml version=\"1.0\"?>\n<DescribeInstancesResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n    <requestId>423068c0-523e-41a7-877c-7123e91d85e2</requestId>\n    <reservationSet>\n        <item>\n            <reservationId>r-596dd731</reservationId>\n            <ownerId>993194456877</ownerId>\n            <groupSet>\n                <item>\n                    <groupId>adriancole.ec2ebsingress</groupId>\n                </item>\n            </groupSet>\n            <instancesSet>\n                <item>\n                    <instanceId>i-e564438d</instanceId>\n                    <imageId>ami-849875ed</imageId>\n                    <instanceState>\n                        <code>16</code>\n                        <name>running</name>\n                    </instanceState>\n                    <privateDnsName>domU-12-31-39-09-CE-53.compute-1.internal\n                    </privateDnsName>\n                    <dnsName>ec2-75-101-203-146.compute-1.amazonaws.com\n                    </dnsName>\n                    <reason />\n                    <keyName>adriancole.ec2ebs1</keyName>\n                    <amiLaunchIndex>0</amiLaunchIndex>\n                    <productCodes />\n                    <instanceType>m1.small</instanceType>\n                    <launchTime>2009-12-30T04:06:23.000Z</launchTime>\n                    <placement>\n                        <availabilityZone>us-east-1b</availabilityZone>\n                        <groupName>placement</groupName>\n                    </placement>\n                    <kernelId>aki-a71cf9ce</kernelId>\n                    <ramdiskId>ari-a51cf9cc</ramdiskId>\n                    <monitoring>\n                        <state>disabled</state>\n                    </monitoring>\n                    <virtualizationType>hvm</virtualizationType>\n                    <privateIpAddress>10.210.209.157</privateIpAddress>\n                    <ipAddress>75.101.203.146</ipAddress>\n                    <hypervisor>xen</hypervisor>\n                    <rootDeviceType>ebs</rootDeviceType>\n                    <rootDeviceName>/dev/sda1</rootDeviceName>\n                    <blockDeviceMapping>\n                        <item>\n                            <deviceName>/dev/sda1</deviceName>\n                            <ebs>\n                                <volumeId>vol-dc6ca8b5</volumeId>\n                                <status>attached</status>\n                                <attachTime>2009-12-30T04:06:29.000Z\n                                </attachTime>\n                                <deleteOnTermination>true\n                                </deleteOnTermination>\n                            </ebs>\n                        </item>\n                    </blockDeviceMapping>\n                </item>\n            </instancesSet>\n        </item>\n    </reservationSet>\n</DescribeInstancesResponse>\n"
  },
  {
    "path": "apis/ec2/src/test/resources/describe_instances_empty.xml",
    "content": "<DescribeInstancesResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n    <reservationSet>\n        <item>\n            <reservationId>r-44a5402d</reservationId>\n            <ownerId>UYY3TLBUXIEON5NQVUUX6OMPWBZIQNFM</ownerId>\n            <groupSet>\n                <item>\n                    <groupId>default</groupId>\n                </item>\n            </groupSet>\n            <instancesSet>\n            </instancesSet>\n        </item>\n    </reservationSet>\n</DescribeInstancesResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/describe_instances_multiple.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<DescribeInstancesResponse xmlns=\"http://ec2.amazonaws.com/doc/2011-05-15/\">\n    <requestId>f6d3252e-35e5-4ef5-b2c5-62da95dd829b</requestId>\n    <reservationSet>\n        <item>\n            <reservationId>r-205ad944</reservationId>\n            <ownerId>993194456877</ownerId>\n            <groupSet>\n                <item>\n                    <groupId>sg-3c6ef654</groupId>\n                    <groupName>jclouds#mygroup2</groupName>\n                </item>\n            </groupSet>\n            <instancesSet>\n                <item>\n                    <instanceId>i-2baa5550</instanceId>\n                    <imageId>ami-aecd60c7</imageId>\n                    <instanceState>\n                        <code>16</code>\n                        <name>running</name>\n                    </instanceState>\n                    <privateDnsName>ip-10-28-89-195.ec2.internal</privateDnsName>\n                    <dnsName>ec2-50-16-1-166.compute-1.amazonaws.com</dnsName>\n                    <reason/>\n                    <keyName>jclouds#mygroup2#81</keyName>\n                    <amiLaunchIndex>0</amiLaunchIndex>\n                    <productCodes/>\n                    <instanceType>t1.micro</instanceType>\n                    <launchTime>2012-08-02T04:28:30.000Z</launchTime>\n                    <placement>\n                        <availabilityZone>us-east-1e</availabilityZone>\n                        <groupName/>\n                        <tenancy>default</tenancy>\n                    </placement>\n                    <kernelId>aki-88aa75e1</kernelId>\n                    <monitoring>\n                        <state>disabled</state>\n                    </monitoring>\n                    <privateIpAddress>10.28.89.195</privateIpAddress>\n                    <ipAddress>50.16.1.166</ipAddress>\n                    <groupSet>\n                        <item>\n                            <groupId>sg-3c6ef654</groupId>\n                            <groupName>jclouds#mygroup2</groupName>\n                        </item>\n                    </groupSet>\n                    <architecture>x86_64</architecture>\n                    <rootDeviceType>ebs</rootDeviceType>\n                    <rootDeviceName>/dev/sda1</rootDeviceName>\n                    <blockDeviceMapping>\n                        <item>\n                            <deviceName>/dev/sda1</deviceName>\n                            <ebs>\n                                <volumeId>vol-f2d7c993</volumeId>\n                                <status>attached</status>\n                                <attachTime>2012-08-02T04:28:56.000Z</attachTime>\n                                <deleteOnTermination>true</deleteOnTermination>\n                            </ebs>\n                        </item>\n                    </blockDeviceMapping>\n                    <virtualizationType>paravirtual</virtualizationType>\n                    <clientToken/>\n                    <tagSet>\n                        <item>\n                            <key>Name</key>\n                            <value>mygroup2-2baa5550</value>\n                        </item>\n                    </tagSet>\n                    <hypervisor>xen</hypervisor>\n                </item>\n                <item>\n                    <instanceId>i-abcd1234</instanceId>\n                    <imageId>ami-aecd60c7</imageId>\n                    <instanceState>\n                        <code>16</code>\n                        <name>running</name>\n                    </instanceState>\n                    <privateDnsName>ip-10-28-89-100.ec2.internal</privateDnsName>\n                    <dnsName>ec2-50-16-1-100.compute-1.amazonaws.com</dnsName>\n                    <reason/>\n                    <keyName>jclouds#mygroup2#82</keyName>\n                    <amiLaunchIndex>0</amiLaunchIndex>\n                    <productCodes/>\n                    <instanceType>t1.micro</instanceType>\n                    <launchTime>2012-08-01T04:28:30.000Z</launchTime>\n                    <placement>\n                        <availabilityZone>us-east-1e</availabilityZone>\n                        <groupName/>\n                        <tenancy>default</tenancy>\n                    </placement>\n                    <kernelId>aki-88aa75e1</kernelId>\n                    <monitoring>\n                        <state>disabled</state>\n                    </monitoring>\n                    <privateIpAddress>10.28.89.100</privateIpAddress>\n                    <ipAddress>50.16.1.100</ipAddress>\n                    <groupSet>\n                        <item>\n                            <groupId>sg-3c6ef654</groupId>\n                            <groupName>jclouds#mygroup2</groupName>\n                        </item>\n                    </groupSet>\n                    <architecture>x86_64</architecture>\n                    <rootDeviceType>ebs</rootDeviceType>\n                    <rootDeviceName>/dev/sda1</rootDeviceName>\n                    <blockDeviceMapping>\n                        <item>\n                            <deviceName>/dev/sda1</deviceName>\n                            <ebs>\n                                <volumeId>vol-f2d7c900</volumeId>\n                                <status>attached</status>\n                                <attachTime>2012-08-01T04:28:56.000Z</attachTime>\n                                <deleteOnTermination>true</deleteOnTermination>\n                            </ebs>\n                        </item>\n                    </blockDeviceMapping>\n                    <virtualizationType>paravirtual</virtualizationType>\n                    <clientToken/>\n                    <tagSet>\n                        <item>\n                            <key>Name</key>\n                            <value>mygroup2-abcd1234</value>\n                        </item>\n                    </tagSet>\n                    <hypervisor>xen</hypervisor>\n                </item>\n            </instancesSet>\n        </item>\n    </reservationSet>\n</DescribeInstancesResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/describe_instances_running-1.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<DescribeInstancesResponse xmlns=\"http://ec2.amazonaws.com/doc/2011-05-15/\">\n    <requestId>f6d3252e-35e5-4ef5-b2c5-62da95dd829b</requestId>\n    <reservationSet>\n        <item>\n            <reservationId>r-205ad944</reservationId>\n            <ownerId>993194456877</ownerId>\n            <groupSet>\n                <item>\n                    <groupId>sg-3c6ef654</groupId>\n                    <groupName>jclouds#mygroup2</groupName>\n                </item>\n            </groupSet>\n            <instancesSet>\n                <item>\n                    <instanceId>i-2baa5550</instanceId>\n                    <imageId>ami-aecd60c7</imageId>\n                    <instanceState>\n                        <code>16</code>\n                        <name>running</name>\n                    </instanceState>\n                    <privateDnsName>ip-10-28-89-195.ec2.internal</privateDnsName>\n                    <dnsName>ec2-50-16-1-166.compute-1.amazonaws.com</dnsName>\n                    <reason/>\n                    <keyName>jclouds#mygroup2#81</keyName>\n                    <amiLaunchIndex>0</amiLaunchIndex>\n                    <productCodes/>\n                    <instanceType>t1.micro</instanceType>\n                    <launchTime>2012-08-02T04:28:30.000Z</launchTime>\n                    <placement>\n                        <availabilityZone>us-east-1e</availabilityZone>\n                        <groupName/>\n                        <tenancy>default</tenancy>\n                    </placement>\n                    <kernelId>aki-88aa75e1</kernelId>\n                    <monitoring>\n                        <state>disabled</state>\n                    </monitoring>\n                    <privateIpAddress>10.28.89.195</privateIpAddress>\n                    <ipAddress>50.16.1.166</ipAddress>\n                    <groupSet>\n                        <item>\n                            <groupId>sg-3c6ef654</groupId>\n                            <groupName>jclouds#mygroup2</groupName>\n                        </item>\n                    </groupSet>\n                    <architecture>x86_64</architecture>\n                    <rootDeviceType>ebs</rootDeviceType>\n                    <rootDeviceName>/dev/sda1</rootDeviceName>\n                    <blockDeviceMapping>\n                        <item>\n                            <deviceName>/dev/sda1</deviceName>\n                            <ebs>\n                                <volumeId>vol-f2d7c993</volumeId>\n                                <status>attached</status>\n                                <attachTime>2012-08-02T04:28:56.000Z</attachTime>\n                                <deleteOnTermination>true</deleteOnTermination>\n                            </ebs>\n                        </item>\n                    </blockDeviceMapping>\n                    <virtualizationType>paravirtual</virtualizationType>\n                    <clientToken/>\n                    <tagSet>\n                        <item>\n                            <key>Name</key>\n                            <value>mygroup2-2baa5550</value>\n                        </item>\n                    </tagSet>\n                    <hypervisor>xen</hypervisor>\n                </item>\n            </instancesSet>\n        </item>\n    </reservationSet>\n</DescribeInstancesResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/describe_instances_running-named.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<DescribeInstancesResponse xmlns=\"http://ec2.amazonaws.com/doc/2011-05-15/\">\n    <requestId>f6d3252e-35e5-4ef5-b2c5-62da95dd829b</requestId>\n    <reservationSet>\n        <item>\n            <reservationId>r-205ad944</reservationId>\n            <ownerId>993194456877</ownerId>\n            <groupSet>\n                <item>\n                    <groupId>sg-3c6ef654</groupId>\n                    <groupName>jclouds#mygroup2</groupName>\n                </item>\n            </groupSet>\n            <instancesSet>\n                <item>\n                    <instanceId>i-2ba64342</instanceId>\n                    <imageId>ami-aecd60c7</imageId>\n                    <instanceState>\n                        <code>16</code>\n                        <name>running</name>\n                    </instanceState>\n                    <privateDnsName>ip-10-28-89-195.ec2.internal</privateDnsName>\n                    <dnsName>ec2-50-16-1-166.compute-1.amazonaws.com</dnsName>\n                    <reason/>\n                    <keyName>jclouds#mygroup2#81</keyName>\n                    <amiLaunchIndex>0</amiLaunchIndex>\n                    <productCodes/>\n                    <instanceType>t1.micro</instanceType>\n                    <launchTime>2012-08-02T04:28:30.000Z</launchTime>\n                    <placement>\n                        <availabilityZone>us-east-1e</availabilityZone>\n                        <groupName/>\n                        <tenancy>default</tenancy>\n                    </placement>\n                    <kernelId>aki-88aa75e1</kernelId>\n                    <monitoring>\n                        <state>disabled</state>\n                    </monitoring>\n                    <privateIpAddress>10.28.89.195</privateIpAddress>\n                    <ipAddress>50.16.1.166</ipAddress>\n                    <groupSet>\n                        <item>\n                            <groupId>sg-3c6ef654</groupId>\n                            <groupName>jclouds#mygroup2</groupName>\n                        </item>\n                    </groupSet>\n                    <architecture>x86_64</architecture>\n                    <rootDeviceType>ebs</rootDeviceType>\n                    <rootDeviceName>/dev/sda1</rootDeviceName>\n                    <blockDeviceMapping>\n                        <item>\n                            <deviceName>/dev/sda1</deviceName>\n                            <ebs>\n                                <volumeId>vol-f2d7c993</volumeId>\n                                <status>attached</status>\n                                <attachTime>2012-08-02T04:28:56.000Z</attachTime>\n                                <deleteOnTermination>true</deleteOnTermination>\n                            </ebs>\n                        </item>\n                    </blockDeviceMapping>\n                    <virtualizationType>paravirtual</virtualizationType>\n                    <clientToken/>\n                    <tagSet>\n                        <item>\n                            <key>Name</key>\n                            <value>test-node</value>\n                        </item>\n                    </tagSet>\n                    <hypervisor>xen</hypervisor>\n                </item>\n                <item>\n                    <instanceId>i-2bc64242</instanceId>\n                    <imageId>ami-aecd60c7</imageId>\n                    <instanceState>\n                        <code>16</code>\n                        <name>running</name>\n                    </instanceState>\n                    <privateDnsName>ip-10-28-89-195.ec2.internal</privateDnsName>\n                    <dnsName>ec2-50-16-1-166.compute-1.amazonaws.com</dnsName>\n                    <reason/>\n                    <keyName>jclouds#mygroup2#81</keyName>\n                    <amiLaunchIndex>0</amiLaunchIndex>\n                    <productCodes/>\n                    <instanceType>t1.micro</instanceType>\n                    <launchTime>2012-08-02T04:28:30.000Z</launchTime>\n                    <placement>\n                        <availabilityZone>us-east-1e</availabilityZone>\n                        <groupName/>\n                        <tenancy>default</tenancy>\n                    </placement>\n                    <kernelId>aki-88aa75e1</kernelId>\n                    <monitoring>\n                        <state>disabled</state>\n                    </monitoring>\n                    <privateIpAddress>10.28.89.195</privateIpAddress>\n                    <ipAddress>50.16.1.166</ipAddress>\n                    <groupSet>\n                        <item>\n                            <groupId>sg-3c6ef654</groupId>\n                            <groupName>jclouds#mygroup2</groupName>\n                        </item>\n                    </groupSet>\n                    <architecture>x86_64</architecture>\n                    <rootDeviceType>ebs</rootDeviceType>\n                    <rootDeviceName>/dev/sda1</rootDeviceName>\n                    <blockDeviceMapping>\n                        <item>\n                            <deviceName>/dev/sda1</deviceName>\n                            <ebs>\n                                <volumeId>vol-f2d7c993</volumeId>\n                                <status>attached</status>\n                                <attachTime>2012-08-02T04:28:56.000Z</attachTime>\n                                <deleteOnTermination>true</deleteOnTermination>\n                            </ebs>\n                        </item>\n                    </blockDeviceMapping>\n                    <virtualizationType>paravirtual</virtualizationType>\n                    <clientToken/>\n                    <tagSet>\n                        <item>\n                            <key>Name</key>\n                            <value>second-node</value>\n                        </item>\n                    </tagSet>\n                    <hypervisor>xen</hypervisor>\n                </item>\n                <item>\n                    <instanceId>i-2be64332</instanceId>\n                    <imageId>ami-aecd60c7</imageId>\n                    <instanceState>\n                        <code>16</code>\n                        <name>running</name>\n                    </instanceState>\n                    <privateDnsName>ip-10-28-89-195.ec2.internal</privateDnsName>\n                    <dnsName>ec2-50-16-1-166.compute-1.amazonaws.com</dnsName>\n                    <reason/>\n                    <keyName>jclouds#mygroup2#81</keyName>\n                    <amiLaunchIndex>0</amiLaunchIndex>\n                    <productCodes/>\n                    <instanceType>t1.micro</instanceType>\n                    <launchTime>2012-08-02T04:28:30.000Z</launchTime>\n                    <placement>\n                        <availabilityZone>us-east-1e</availabilityZone>\n                        <groupName/>\n                        <tenancy>default</tenancy>\n                    </placement>\n                    <kernelId>aki-88aa75e1</kernelId>\n                    <monitoring>\n                        <state>disabled</state>\n                    </monitoring>\n                    <privateIpAddress>10.28.89.195</privateIpAddress>\n                    <ipAddress>50.16.1.166</ipAddress>\n                    <groupSet>\n                        <item>\n                            <groupId>sg-3c6ef654</groupId>\n                            <groupName>jclouds#mygroup2</groupName>\n                        </item>\n                    </groupSet>\n                    <architecture>x86_64</architecture>\n                    <rootDeviceType>ebs</rootDeviceType>\n                    <rootDeviceName>/dev/sda1</rootDeviceName>\n                    <blockDeviceMapping>\n                        <item>\n                            <deviceName>/dev/sda1</deviceName>\n                            <ebs>\n                                <volumeId>vol-f2d7c993</volumeId>\n                                <status>attached</status>\n                                <attachTime>2012-08-02T04:28:56.000Z</attachTime>\n                                <deleteOnTermination>true</deleteOnTermination>\n                            </ebs>\n                        </item>\n                    </blockDeviceMapping>\n                    <virtualizationType>paravirtual</virtualizationType>\n                    <clientToken/>\n                    <tagSet>\n                        <item>\n                            <key>Name</key>\n                            <value>third-node</value>\n                        </item>\n                    </tagSet>\n                    <hypervisor>xen</hypervisor>\n                </item>\n            </instancesSet>\n        </item>\n    </reservationSet>\n</DescribeInstancesResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/describe_instances_running.xml",
    "content": "<DescribeInstancesResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n    <requestId>ae75a8cc-b707-4a20-b130-61ad6f20de61</requestId>\n    <reservationSet>\n        <item>\n            <reservationId>r-a3c508cb</reservationId>\n            <ownerId>993194456877</ownerId>\n            <groupSet>\n                <item>\n                    <groupId>adriancole.ec2ingress</groupId>\n                </item>\n            </groupSet>\n            <instancesSet>\n                <item>\n                    <instanceId>i-0799056f</instanceId>\n                    <imageId>ami-82e4b5c7</imageId>\n                    <instanceState>\n                        <code>16</code>\n                        <name>running</name>\n                    </instanceState>\n                    <privateDnsName>ip-10-243-42-70.ec2.internal\n                    </privateDnsName>\n                    <dnsName>ec2-174-129-81-68.compute-1.amazonaws.com\n                    </dnsName>\n                    <reason />\n                    <keyName>adriancole.ec21</keyName>\n                    <amiLaunchIndex>0</amiLaunchIndex>\n                    <productCodes />\n                    <instanceType>m1.small</instanceType>\n                    <launchTime>2009-11-09T03:00:34.000Z</launchTime>\n                    <placement>\n                        <availabilityZone>us-east-1c</availabilityZone>\n                    </placement>\n                    <kernelId>aki-a71cf9ce</kernelId>\n                    <ramdiskId>ari-a51cf9cc</ramdiskId>\n                    <monitoring>\n                        <state>disabled</state>\n                    </monitoring>\n                    <privateIpAddress>10.243.42.70</privateIpAddress>\n                    <ipAddress>174.129.81.68</ipAddress>\n                    <hypervisor>xen</hypervisor>                    \n                </item>\n            </instancesSet>\n        </item>\n    </reservationSet>\n</DescribeInstancesResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/describe_instances_running_securitygroups.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<DescribeInstancesResponse xmlns=\"http://ec2.amazonaws.com/doc/2011-05-15/\">\n    <requestId>f6d3252e-35e5-4ef5-b2c5-62da95dd829b</requestId>\n    <reservationSet>\n        <item>\n            <reservationId>r-205ad944</reservationId>\n            <ownerId>993194456877</ownerId>\n            <groupSet>\n                <item>\n                    <groupId>sg-3c6ef654</groupId>\n                    <groupName>jclouds#some-group</groupName>\n                </item>\n            </groupSet>\n            <instancesSet>\n                <item>\n                    <instanceId>i-2baa5550</instanceId>\n                    <imageId>ami-aecd60c7</imageId>\n                    <instanceState>\n                        <code>16</code>\n                        <name>running</name>\n                    </instanceState>\n                    <privateDnsName>ip-10-28-89-195.ec2.internal</privateDnsName>\n                    <dnsName>ec2-50-16-1-166.compute-1.amazonaws.com</dnsName>\n                    <reason/>\n                    <keyName>jclouds#mygroup2#81</keyName>\n                    <amiLaunchIndex>0</amiLaunchIndex>\n                    <productCodes/>\n                    <instanceType>t1.micro</instanceType>\n                    <launchTime>2012-08-02T04:28:30.000Z</launchTime>\n                    <placement>\n                        <availabilityZone>us-east-1e</availabilityZone>\n                        <groupName/>\n                        <tenancy>default</tenancy>\n                    </placement>\n                    <kernelId>aki-88aa75e1</kernelId>\n                    <monitoring>\n                        <state>disabled</state>\n                    </monitoring>\n                    <privateIpAddress>10.28.89.195</privateIpAddress>\n                    <ipAddress>50.16.1.166</ipAddress>\n                    <groupSet>\n                        <item>\n                          <groupId>sg-3c6ef654</groupId>\n                          <groupName>jclouds#some-group</groupName>\n                        </item>\n                    </groupSet>\n                    <architecture>x86_64</architecture>\n                    <rootDeviceType>ebs</rootDeviceType>\n                    <rootDeviceName>/dev/sda1</rootDeviceName>\n                    <blockDeviceMapping>\n                        <item>\n                            <deviceName>/dev/sda1</deviceName>\n                            <ebs>\n                                <volumeId>vol-f2d7c993</volumeId>\n                                <status>attached</status>\n                                <attachTime>2012-08-02T04:28:56.000Z</attachTime>\n                                <deleteOnTermination>true</deleteOnTermination>\n                            </ebs>\n                        </item>\n                    </blockDeviceMapping>\n                    <virtualizationType>paravirtual</virtualizationType>\n                    <clientToken/>\n                    <tagSet>\n                        <item>\n                            <key>Name</key>\n                            <value>mygroup2-2baa5550</value>\n                        </item>\n                    </tagSet>\n                    <hypervisor>xen</hypervisor>\n                </item>\n            </instancesSet>\n        </item>\n    </reservationSet>\n</DescribeInstancesResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/describe_instances_three_ids.xml",
    "content": "<DescribeInstancesResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n  <reservationId>r-47a5402e</reservationId>\n  <ownerId>AIDADH4IGTRXXKCD</ownerId>\n  <groupSet>\n    <item>\n      <groupId>default</groupId>\n    </item>\n  </groupSet>\n  <instancesSet>\n    <item>\n      <instanceId>i-2ba64342</instanceId>\n      <imageId>ami-aecd60c7</imageId>\n      <instanceState>\n        <code>0</code>\n        <name>pending</name>\n      </instanceState>\n      <privateDnsName></privateDnsName>\n      <dnsName></dnsName>\n      <keyName>example-key-name</keyName>\n      <amiLaunchIndex>0</amiLaunchIndex>\n      <instanceType>m1.small</instanceType>\n      <launchTime>2007-08-07T11:51:50.000Z</launchTime>\n      <placement>\n        <availabilityZone>us-east-1b</availabilityZone>\n      </placement>\n      <monitoring>\n        <state>enabled</state>\n      </monitoring>\n      <hypervisor>xen</hypervisor>      \n    </item>\n    <item>\n      <instanceId>i-2bc64242</instanceId>\n      <imageId>ami-aecd60c7</imageId>\n      <instanceState>\n        <code>0</code>\n        <name>pending</name>\n      </instanceState>\n      <privateDnsName></privateDnsName>\n      <dnsName></dnsName>\n      <keyName>example-key-name</keyName>\n      <amiLaunchIndex>1</amiLaunchIndex>\n      <instanceType>m1.small</instanceType>\n      <launchTime>2007-08-07T11:51:50.000Z</launchTime>\n      <placement>\n\t\t  <availabilityZone>us-east-1b</availabilityZone>\n      </placement>\n      <monitoring>\n        <state>enabled</state>\n      </monitoring>\n      <hypervisor>xen</hypervisor>\n    </item>\n    <item>\n      <instanceId>i-2be64332</instanceId>\n      <imageId>ami-aecd60c7</imageId>\n      <instanceState>\n        <code>0</code>\n        <name>pending</name>\n      </instanceState>\n      <privateDnsName></privateDnsName>\n      <dnsName></dnsName>\n      <keyName>example-key-name</keyName>\n      <amiLaunchIndex>2</amiLaunchIndex>\n      <instanceType>m1.small</instanceType>\n      <launchTime>2007-08-07T11:51:50.000Z</launchTime>\n      <placement>\n\t\t  <availabilityZone>us-east-1b</availabilityZone>\n      </placement>\n      <monitoring>\n        <state>enabled</state>\n      </monitoring>\n      <hypervisor>xen</hypervisor>\n    </item>\n  </instancesSet>\n</DescribeInstancesResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/describe_keypairs.xml",
    "content": "<DescribeKeyPairsResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n  <keySet>\n    <item>\n      <keyName>gsg-keypair</keyName>\n      <keyFingerprint>1f:51:ae:28:bf:89:e9:d8:1f:25:5d:37:2d:7d:b8:ca:9f:f5:f1:6f</keyFingerprint>\n    </item>\n  </keySet>\n</DescribeKeyPairsResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/describe_keypairs_jcloudssingle.xml",
    "content": "<DescribeKeyPairsResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n  <keySet>\n    <item>\n      <keyName>jclouds#sg-3c6ef654</keyName>\n      <keyFingerprint>1f:51:ae:28:bf:89:e9:d8:1f:25:5d:37:2d:7d:b8:ca:9f:f5:f1:6f</keyFingerprint>\n    </item>\n  </keySet>\n</DescribeKeyPairsResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/describe_securitygroups.xml",
    "content": "<DescribeSecurityGroupsResponse\n\txmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n\t<securityGroupInfo>\n\t\t<item>\n\t\t\t<ownerId>UYY3TLBUXIEON5NQVUUX6OMPWBZIQNFM</ownerId>\n                        <groupId>sg-3c6ef654</groupId>\n\t\t\t<groupName>WebServers</groupName>\n\t\t\t<groupDescription>Web Servers</groupDescription>\n\t\t\t<ipPermissions>\n\t\t\t\t<item>\n\t\t\t\t\t<ipProtocol>tcp</ipProtocol>\n\t\t\t\t\t<fromPort>80</fromPort>\n\t\t\t\t\t<toPort>80</toPort>\n\t\t\t\t\t<groups />\n\t\t\t\t\t<ipRanges>\n\t\t\t\t\t\t<item>\n\t\t\t\t\t\t\t<cidrIp>0.0.0.0/0</cidrIp>\n\t\t\t\t\t\t</item>\n\t\t\t\t\t</ipRanges>\n\t\t\t\t</item>\n\t\t\t</ipPermissions>\n\t\t</item>\n\t\t<item>\n\t\t\t<ownerId>UYY3TLBUXIEON5NQVUUX6OMPWBZIQNFM</ownerId>\n                        <groupId>sg-867309ab</groupId>\n                        <groupName>RangedPortsBySource</groupName>\n\t\t\t<groupDescription>Group A</groupDescription>\n\t\t\t<ipPermissions>\n\t\t\t\t<item>\n\t\t\t\t\t<ipProtocol>tcp</ipProtocol>\n\t\t\t\t\t<fromPort>6000</fromPort>\n\t\t\t\t\t<toPort>7000</toPort>\n\t\t\t\t\t<groups />\n\t\t\t\t\t<ipRanges />\n\t\t\t\t</item>\n\t\t\t</ipPermissions>\n\t\t</item>\n\t</securityGroupInfo>\n</DescribeSecurityGroupsResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/describe_securitygroups_empty.xml",
    "content": "<?xml version=\"1.0\" ?>\n<DescribeSecurityGroupsResponse\n\txmlns=\"http://ec2.amazonaws.com/doc/2010-08-31/\">\n\t<requestId>L6EFIZVPJS76T3K5-0UV</requestId>\n\t<securityGroupInfo>\n\t\t<item>\n\t\t\t<ipPermissions>\n\t\t\t\t<item>\n\t\t\t\t\t<toPort>22</toPort>\n\t\t\t\t\t<ipProtocol>tcp</ipProtocol>\n\t\t\t\t\t<ipRanges>\n\t\t\t\t\t\t<item>\n\t\t\t\t\t\t\t<cidrIp>0.0.0.0/0</cidrIp>\n\t\t\t\t\t\t</item>\n\t\t\t\t\t</ipRanges>\n\t\t\t\t\t<groups />\n\t\t\t\t\t<fromPort>22</fromPort>\n\t\t\t\t</item>\n\n\t\t\t\t<item>\n\t\t\t\t\t<toPort />\n\t\t\t\t\t<ipProtocol />\n\t\t\t\t\t<ipRanges />\n\t\t\t\t\t<groups>\n\t\t\t\t\t\t<item>\n                                                  <groupId>sg-3c6ef654</groupId>\n\t\t\t\t\t\t\t<groupName>jclouds#cluster#world</groupName>\n\t\t\t\t\t\t\t<userId>UYY3TLBUXIEON5NQVUUX6OMPWBZIQNFM</userId>\n\t\t\t\t\t\t</item>\n\t\t\t\t\t</groups>\n\t\t\t\t\t<fromPort />\n\t\t\t\t</item>\n\t\t\t</ipPermissions>\n\t\t\t<groupName>jclouds#cluster#world</groupName>\n                        <groupId>sg-3c6ef654</groupId>\n\t\t\t<groupDescription>Cluster</groupDescription>\n\t\t\t<ownerId>UYY3TLBUXIEON5NQVUUX6OMPWBZIQNFM</ownerId>\n\t\t</item>\n\n\t</securityGroupInfo>\n</DescribeSecurityGroupsResponse>\n"
  },
  {
    "path": "apis/ec2/src/test/resources/describe_securitygroups_extension_cidr.xml",
    "content": "<DescribeSecurityGroupsResponse\n\txmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n\t<securityGroupInfo>\n\t\t<item>\n                  <ownerId>993194456877</ownerId>\n                  <groupId>sg-3c6ef654</groupId>\n                  <groupName>jclouds#some-group</groupName>\n                  <groupDescription>jclouds#some-group</groupDescription>\n                  <ipPermissions>\n                    <item>\n                      <ipProtocol>tcp</ipProtocol>\n                      <fromPort>22</fromPort>\n                      <toPort>40</toPort>\n                      <groups />\n                      <ipRanges>\n                        <item>\n                          <cidrIp>0.0.0.0/0</cidrIp>\n                        </item>\n                      </ipRanges>\n                    </item>\n                  </ipPermissions>\n\t\t</item>\n\t</securityGroupInfo>\n</DescribeSecurityGroupsResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/describe_securitygroups_extension_group.xml",
    "content": "<DescribeSecurityGroupsResponse\n\txmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n\t<securityGroupInfo>\n\t\t<item>\n                  <ownerId>993194456877</ownerId>\n                  <groupName>jclouds#some-group</groupName>\n                  <groupDescription>jclouds#some-group</groupDescription>\n                  <groupId>sg-3c6ef654</groupId>\n                  <ipPermissions>\n                    <item>\n                      <ipProtocol>tcp</ipProtocol>\n                      <fromPort>22</fromPort>\n                      <toPort>40</toPort>\n                      <groups>\n                        <item>\n                          <userId>993194456877</userId>\n                          <groupId>sg-3c6ef654</groupId>\n                          <groupName>jclouds#some-group</groupName>\n                        </item>\n                      </groups>\n                      <ipRanges/>\n                    </item>\n                  </ipPermissions>\n\t\t</item>\n\t</securityGroupInfo>\n</DescribeSecurityGroupsResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/describe_securitygroups_extension_new.xml",
    "content": "<DescribeSecurityGroupsResponse\n\txmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n\t<securityGroupInfo>\n\t\t<item>\n                  <ownerId>993194456877</ownerId>\n                  <groupName>jclouds#some-group</groupName>\n                  <groupDescription>jclouds#some-group</groupDescription>\n                  <groupId>sg-3c6ef654</groupId>\n                  <ipPermissions/>\n\t\t</item>\n\t\t<item>\n                  <ownerId>993194456877</ownerId>\n                  <groupId>sg-3a2b3c4d</groupId>\n                  <groupName>group-a</groupName>\n                  <groupDescription>Group A</groupDescription>\n                  <ipPermissions>\n                    <item>\n                      <ipProtocol>tcp</ipProtocol>\n                      <fromPort>6000</fromPort>\n                      <toPort>7000</toPort>\n                      <groups />\n                      <ipRanges />\n                    </item>\n                  </ipPermissions>\n\t\t</item>\n\t</securityGroupInfo>\n</DescribeSecurityGroupsResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/describe_securitygroups_extension_single.xml",
    "content": "<DescribeSecurityGroupsResponse\n\txmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n\t<securityGroupInfo>\n\t\t<item>\n                  <ownerId>993194456877</ownerId>\n                  <groupName>jclouds#some-group</groupName>\n                  <groupDescription>jclouds#some-group</groupDescription>\n                  <groupId>sg-3c6ef654</groupId>\n                  <ipPermissions/>\n\t\t</item>\n\t</securityGroupInfo>\n</DescribeSecurityGroupsResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/describe_snapshots.xml",
    "content": "<DescribeSnapshotsResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n    <snapshotSet>\n        <item>\n            <snapshotId>snap-78a54011</snapshotId>\n            <volumeId>vol-4d826724</volumeId>\n            <status>pending</status>\n            <startTime>2008-05-07T12:51:50.000Z</startTime>\n            <progress>80%</progress>\n            <ownerId>218213537122</ownerId>\n            <volumeSize>10</volumeSize>\n            <description>Daily Backup</description>\n            <tagSet>\n                <item>\n                    <key>Name</key>\n                    <value>example_name_tag</value>\n                </item>\n            </tagSet>\n        </item>\n    </snapshotSet>\n</DescribeSnapshotsResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/describe_subnets.xml",
    "content": "<DescribeSubnetsResponse xmlns=\"http://ec2.amazonaws.com/doc/2012-12-01/\">\n  <requestId>7a62c49f-347e-4fc4-9331-6e8eEXAMPLE</requestId>\n  <subnetSet>\n    <item>\n      <subnetId>subnet-9d4a7b6c</subnetId>\n      <state>available</state>\n      <vpcId>vpc-1a2b3c4d</vpcId>\n      <cidrBlock>10.0.1.0/24</cidrBlock>\n      <availableIpAddressCount>250</availableIpAddressCount>\n      <availabilityZone>us-east-1a</availabilityZone>\n      <tagSet>\n        <item>\n          <key>Name</key>\n          <value>ec2-o</value>\n        </item>\n        <item>\n          <key>Empty</key>\n          <value />\n        </item>\n      </tagSet>\n    </item>\n    <item>\n      <subnetId>subnet-6e7f829e</subnetId>\n      <state>available</state>\n      <vpcId>vpc-1a2b3c4d</vpcId>\n      <cidrBlock>10.0.0.0/24</cidrBlock> \n      <availableIpAddressCount>250</availableIpAddressCount>\n      <availabilityZone>us-east-1a</availabilityZone>\n      <tagSet/>\n      \n    </item>\n  </subnetSet>\n</DescribeSubnetsResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/describe_tags.xml",
    "content": "<DescribeTagsResponse xmlns=\"http://ec2.amazonaws.com/doc/2012-10-01/\">\n   <requestId>7a62c49f-347e-4fc4-9331-6e8eEXAMPLE</requestId>\n   <tagSet>\n       <item>\n         <resourceId>i-5f4e3d2a</resourceId>\n         <resourceType>instance</resourceType>\n         <key>webserver</key>\n         <value/>\n      </item>\n       <item>\n         <resourceId>i-5f4e3d2a</resourceId>\n         <resourceType>instance</resourceType>\n         <key>stack</key>\n         <value>Production</value>\n      </item>\n      <item>\n         <resourceId>i-12345678</resourceId>\n         <resourceType>instance</resourceType>\n         <key>database_server</key>\n         <value/>\n      </item>\n       <item>\n         <resourceId>i-12345678</resourceId>\n         <resourceType>instance</resourceType>\n         <key>stack</key>\n         <value>Test</value>\n      </item>\n    </tagSet>\n</DescribeTagsResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/describe_volumes.xml",
    "content": "<?xml version=\"1.0\"?>\n<DescribeVolumesResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n    <requestId>31ab5542-e479-44cb-aa94-c340c2481e0b</requestId>\n    <volumeSet>\n        <item>\n            <volumeId>vol-2a21e543</volumeId>\n            <size>1</size>\n            <snapshotId />\n            <availabilityZone>us-east-1a</availabilityZone>\n            <status>available</status>\n            <createTime>2009-12-28T05:42:53.000Z</createTime>\n            <volumeType>standard</volumeType>\n            <iops>0</iops>\n            <encrypted>false</encrypted>\n            <attachmentSet />\n        </item>\n        <item>\n            <volumeId>vol-4282672b</volumeId>\n            <size>800</size>\n            <snapshotId>snap-536d1b3a</snapshotId>\n            <availabilityZone>us-east-1a</availabilityZone>\n            <status>in-use</status>\n            <createTime>2008-05-07T11:51:50.000Z</createTime>\n            <volumeType>standard</volumeType>\n            <iops>0</iops>\n            <encrypted>false</encrypted>\n            <attachmentSet>\n                <item>\n                    <volumeId>vol-4282672b</volumeId>\n                    <instanceId>i-6058a509</instanceId>\n                    <device>/dev/sdh</device>\n                    <status>attached</status>\n                    <attachTime>2008-05-07T12:51:50.000Z</attachTime>\n                </item>\n            </attachmentSet>\n        </item>\n    </volumeSet>\n</DescribeVolumesResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/describe_volumes_single.xml",
    "content": "<?xml version=\"1.0\"?>\n<DescribeVolumesResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n    <requestId>31ab5542-e479-44cb-aa94-c340c2481e0b</requestId>\n    <volumeSet>\n        <item>\n            <volumeId>vol-4282672b</volumeId>\n            <size>800</size>\n            <snapshotId>snap-536d1b3a</snapshotId>\n            <availabilityZone>us-east-1a</availabilityZone>\n            <status>in-use</status>\n            <createTime>2008-05-07T11:51:50.000Z</createTime>\n            <volumeType>standard</volumeType>\n            <iops>0</iops>\n            <encrypted>false</encrypted>\n            <attachmentSet />\n        </item>\n    </volumeSet>\n</DescribeVolumesResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/disableApiTermination.xml",
    "content": "<?xml version=\"1.0\"?>\n<DescribeInstanceAttributeResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n    <requestId>b47e8cff-0647-4260-adfe-022c878b1f7d</requestId>\n    <instanceId>i-e9290f81</instanceId>\n    <disableApiTermination>\n        <value>false</value>\n    </disableApiTermination>\n</DescribeInstanceAttributeResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/get_console_output_response.xml",
    "content": "<GetConsoleOutputResponse xmlns=\"http://ec2.amazonaws.com/doc/2012-05-01/\">\n  <requestId>59dbff89-35bd-4eac-99ed-be587EXAMPLE</requestId> \n  <instanceId>i-28a64341</instanceId>\n  <timestamp>2010-10-14T01:12:41.000Z</timestamp>\n  <output>TGludXggdmVyc2lvbiAyLjYuMTYteGVuVSAoYnVpbGRlckBwYXRjaGJhdC5hbWF6b25zYSkgKGdj\nYyB2ZXJzaW9uIDQuMC4xIDIwMDUwNzI3IChSZWQgSGF0IDQuMC4xLTUpKSAjMSBTTVAgVGh1IE9j\ndCAyNiAwODo0MToyNiBTQVNUIDIwMDYKQklPUy1wcm92aWRlZCBwaHlzaWNhbCBSQU0gbWFwOgpY\nZW46IDAwMDAwMDAwMDAwMDAwMDAgLSAwMDAwMDAwMDZhNDAwMDAwICh1c2FibGUpCjk4ME1CIEhJ\nR0hNRU0gYXZhaWxhYmxlLgo3MjdNQiBMT1dNRU0gYXZhaWxhYmxlLgpOWCAoRXhlY3V0ZSBEaXNh\nYmxlKSBwcm90ZWN0aW9uOiBhY3RpdmUKSVJRIGxvY2t1cCBkZXRlY3Rpb24gZGlzYWJsZWQKQnVp\nbHQgMSB6b25lbGlzdHMKS2VybmVsIGNvbW1hbmQgbGluZTogcm9vdD0vZGV2L3NkYTEgcm8gNApF\nbmFibGluZyBmYXN0IEZQVSBzYXZlIGFuZCByZXN0b3JlLi4uIGRvbmUuCg==</output>\n</GetConsoleOutputResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/get_passworddata.xml",
    "content": "<GetPasswordDataResponse xmlns=\"http://ec2.amazonaws.com/doc/2012-06-15/\">\n  <requestId>59dbff89-35bd-4eac-99ed-be587EXAMPLE</requestId> \n  <instanceId>i-2574e22a</instanceId>\n  <timestamp>2012-07-30T07:27:23.000+0000</timestamp>\n  <passwordData>TGludXggdmVyc2lvbiAyLjYuMTYteGVuVSAoYnVpbGRlckBwYXRjaGJhdC5hbWF6b25zYSkgKGdj</passwordData>\n</GetPasswordDataResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/instanceInitiatedShutdownBehavior.xml",
    "content": "<DescribeInstanceAttributeResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n    <requestId>564827a8-c70d-4a76-bb9b-87fb5e5a6cee</requestId>\n    <instanceId>i-7736101f</instanceId>\n    <instanceInitiatedShutdownBehavior>\n        <value>stop</value>\n    </instanceInitiatedShutdownBehavior>\n</DescribeInstanceAttributeResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/instanceType.xml",
    "content": "<?xml version=\"1.0\"?>\n<DescribeInstanceAttributeResponse\n    xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n    <requestId>947779ee-439a-46b5-82db-5f015f75b6d0</requestId>\n    <instanceId>i-7736101f</instanceId>\n    <instanceType>\n        <value>m1.small</value>\n    </instanceType>\n</DescribeInstanceAttributeResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/log4j.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE log4j:configuration SYSTEM \"log4j.dtd\">\n\n    <!--\n        For more configuration infromation and examples see the Apache\n        Log4j website: http://logging.apache.org/log4j/\n    -->\n<log4j:configuration xmlns:log4j=\"http://jakarta.apache.org/log4j/\"\n    debug=\"false\">\n\n    <!-- A time/date based rolling appender -->\n    <appender name=\"WIREFILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds-wire.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n\n    <!-- A time/date based rolling appender -->\n    <appender name=\"FILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n    <!-- A time/date based rolling appender -->\n    <appender name=\"COMPUTEFILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds-compute.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n\n    <!-- A time/date based rolling appender -->\n    <appender name=\"SSHFILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds-ssh.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n\n    <appender name=\"ASYNCCOMPUTE\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"COMPUTEFILE\" />\n    </appender>\n\n    <appender name=\"ASYNCSSH\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"SSHFILE\" />\n    </appender>\n\n    <appender name=\"ASYNC\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"FILE\" />\n    </appender>\n\n    <appender name=\"ASYNCWIRE\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"WIREFILE\" />\n    </appender>\n\n    <!-- ================ -->\n    <!-- Limit categories -->\n    <!-- ================ -->\n\n    <category name=\"org.jclouds\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNC\" />\n    </category>\n\n    <category name=\"jclouds.headers\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNCWIRE\" />\n    </category>\n\n    <category name=\"jclouds.ssh\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNCSSH\" />\n    </category>\n    <category name=\"jclouds.wire\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNCWIRE\" />\n    </category>\n    <category name=\"jclouds.compute\">\n        <priority value=\"TRACE\" />\n        <appender-ref ref=\"ASYNCCOMPUTE\" />\n    </category>\n    <!-- ======================= -->\n    <!-- Setup the Root category -->\n    <!-- ======================= -->\n\n    <root>\n        <priority value=\"WARN\" />\n    </root>\n\n</log4j:configuration>\n"
  },
  {
    "path": "apis/ec2/src/test/resources/new_instance.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<RunInstancesResponse xmlns=\"http://ec2.amazonaws.com/doc/2011-05-15/\">\n    <requestId>99260d2b-1bdc-4473-b386-48d22e96900a</requestId>\n    <reservationId>r-205ad944</reservationId>\n    <ownerId>993194456877</ownerId>\n    <groupSet>\n        <item>\n            <groupId>sg-3c6ef654</groupId>\n            <groupName>jclouds#test</groupName>\n        </item>\n    </groupSet>\n    <instancesSet>\n        <item>\n            <instanceId>i-2baa5550</instanceId>\n            <imageId>ami-aecd60c7</imageId>\n            <instanceState>\n                <code>0</code>\n                <name>pending</name>\n            </instanceState>\n            <privateDnsName/>\n            <dnsName/>\n            <reason/>\n            <keyName>jclouds#test#0</keyName>\n            <amiLaunchIndex>0</amiLaunchIndex>\n            <productCodes/>\n            <instanceType>t1.micro</instanceType>\n            <launchTime>2012-08-02T04:28:30.000Z</launchTime>\n            <placement>\n                <availabilityZone>us-east-1e</availabilityZone>\n                <groupName/>\n                <tenancy>default</tenancy>\n            </placement>\n            <kernelId>aki-88aa75e1</kernelId>\n            <monitoring>\n                <state>disabled</state>\n            </monitoring>\n            <groupSet>\n                <item>\n                    <groupId>sg-3c6ef654</groupId>\n                    <groupName>jclouds#test</groupName>\n                </item>\n            </groupSet>\n            <stateReason>\n                <code>pending</code>\n                <message>pending</message>\n            </stateReason>\n            <architecture>x86_64</architecture>\n            <rootDeviceType>ebs</rootDeviceType>\n            <rootDeviceName>/dev/sda1</rootDeviceName>\n            <blockDeviceMapping/>\n            <virtualizationType>paravirtual</virtualizationType>\n            <clientToken/>\n            <hypervisor>xen</hypervisor>\n        </item>\n    </instancesSet>\n</RunInstancesResponse>\n"
  },
  {
    "path": "apis/ec2/src/test/resources/new_securitygroup.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<DescribeSecurityGroupsResponse xmlns=\"http://ec2.amazonaws.com/doc/2011-05-15/\">\n    <requestId>6df3e2a6-76c0-414b-89ff-9318144e0bbe</requestId>\n    <securityGroupInfo>\n        <item>\n            <ownerId>993194456877</ownerId>\n            <groupId>sg-3c6ef654</groupId>\n            <groupName>jclouds#test</groupName>\n            <groupDescription>jclouds#test</groupDescription>\n            <ipPermissions/>\n            <ipPermissionsEgress/>\n        </item>\n    </securityGroupInfo>\n</DescribeSecurityGroupsResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/ramdisk.xml",
    "content": "<?xml version=\"1.0\"?>\n<DescribeInstanceAttributeResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n    <requestId>94174289-29d5-40d2-95f2-2b3d3005d58c</requestId>\n    <instanceId>i-c72d0baf</instanceId>\n    <ramdisk>\n        <value>ari-a51cf9cc</value>\n    </ramdisk>\n</DescribeInstanceAttributeResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/regionEndpoints-additional.xml",
    "content": "<?xml version=\"1.0\"?>\n<DescribeRegionsResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n    <requestId>2bffb2f8-3b03-4be9-92bd-a35b27a2f51a</requestId>\n    <regionInfo>\n        <item>\n            <regionName>eu-west-1</regionName>\n            <regionEndpoint>ec2.eu-west-1.amazonaws.com</regionEndpoint>\n        </item>\n        <item>\n            <regionName>us-east-1</regionName>\n            <regionEndpoint>ec2.us-east-1.amazonaws.com</regionEndpoint>\n        </item>\n        <item>\n            <regionName>us-west-1</regionName>\n            <regionEndpoint>ec2.us-west-1.amazonaws.com</regionEndpoint>\n        </item>\n        <item>\n            <regionName>jp-west-1</regionName>\n            <regionEndpoint>ec2.jp-west-1.amazonaws.com</regionEndpoint>\n        </item>\n    </regionInfo>\n</DescribeRegionsResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/regionEndpoints-all.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<DescribeRegionsResponse xmlns=\"http://ec2.amazonaws.com/doc/2011-05-15/\">\n    <requestId>8392a998-c7bb-41fc-be15-045f528d7627</requestId>\n    <regionInfo>\n        <item>\n            <regionName>eu-west-1</regionName>\n            <regionEndpoint>ec2.eu-west-1.amazonaws.com</regionEndpoint>\n        </item>\n        <item>\n            <regionName>sa-east-1</regionName>\n            <regionEndpoint>ec2.sa-east-1.amazonaws.com</regionEndpoint>\n        </item>\n        <item>\n            <regionName>us-east-1</regionName>\n            <regionEndpoint>ec2.us-east-1.amazonaws.com</regionEndpoint>\n        </item>\n        <item>\n            <regionName>ap-northeast-1</regionName>\n            <regionEndpoint>ec2.ap-northeast-1.amazonaws.com</regionEndpoint>\n        </item>\n        <item>\n            <regionName>us-west-2</regionName>\n            <regionEndpoint>ec2.us-west-2.amazonaws.com</regionEndpoint>\n        </item>\n        <item>\n            <regionName>us-west-1</regionName>\n            <regionEndpoint>ec2.us-west-1.amazonaws.com</regionEndpoint>\n        </item>\n        <item>\n            <regionName>ap-southeast-1</regionName>\n            <regionEndpoint>ec2.ap-southeast-1.amazonaws.com</regionEndpoint>\n        </item>\n    </regionInfo>\n</DescribeRegionsResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/regionEndpoints.xml",
    "content": "<?xml version=\"1.0\"?>\n<DescribeRegionsResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n    <requestId>2bffb2f8-3b03-4be9-92bd-a35b27a2f51a</requestId>\n    <regionInfo>\n        <item>\n            <regionName>eu-west-1</regionName>\n            <regionEndpoint>ec2.eu-west-1.amazonaws.com</regionEndpoint>\n        </item>\n        <item>\n            <regionName>us-east-1</regionName>\n            <regionEndpoint>ec2.us-east-1.amazonaws.com</regionEndpoint>\n        </item>\n        <item>\n            <regionName>us-west-1</regionName>\n            <regionEndpoint>ec2.us-west-1.amazonaws.com</regionEndpoint>\n        </item>\n    </regionInfo>\n</DescribeRegionsResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/run_instances.xml",
    "content": "<RunInstancesResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n  <reservationId>r-47a5402e</reservationId>\n  <ownerId>AIDADH4IGTRXXKCD</ownerId>\n  <groupSet>\n    <item>\n      <groupId>default</groupId>\n    </item>\n  </groupSet>\n  <instancesSet>\n    <item>\n      <instanceId>i-2ba64342</instanceId>\n      <imageId>ami-60a54009</imageId>\n      <instanceState>\n        <code>0</code>\n        <name>pending</name>\n      </instanceState>\n      <privateDnsName></privateDnsName>\n      <dnsName></dnsName>\n      <keyName>example-key-name</keyName>\n      <amiLaunchIndex>0</amiLaunchIndex>\n      <instanceType>m1.small</instanceType>\n      <launchTime>2007-08-07T11:51:50.000Z</launchTime>\n      <placement>\n        <availabilityZone>us-east-1b</availabilityZone>\n      </placement>\n      <monitoring>\n        <state>enabled</state>\n      </monitoring>\n      <hypervisor>xen</hypervisor>      \n    </item>\n    <item>\n      <instanceId>i-2bc64242</instanceId>\n      <imageId>ami-60a54009</imageId>\n      <instanceState>\n        <code>0</code>\n        <name>pending</name>\n      </instanceState>\n      <privateDnsName></privateDnsName>\n      <dnsName></dnsName>\n      <keyName>example-key-name</keyName>\n      <amiLaunchIndex>1</amiLaunchIndex>\n      <instanceType>m1.small</instanceType>\n      <launchTime>2007-08-07T11:51:50.000Z</launchTime>\n      <placement>\n\t\t  <availabilityZone>us-east-1b</availabilityZone>\n      </placement>\n      <monitoring>\n        <state>enabled</state>\n      </monitoring>\n      <hypervisor>xen</hypervisor>\n    </item>\n    <item>\n      <instanceId>i-2be64332</instanceId>\n      <imageId>ami-60a54009</imageId>\n      <instanceState>\n        <code>0</code>\n        <name>pending</name>\n      </instanceState>\n      <privateDnsName></privateDnsName>\n      <dnsName></dnsName>\n      <keyName>example-key-name</keyName>\n      <amiLaunchIndex>2</amiLaunchIndex>\n      <instanceType>m1.small</instanceType>\n      <launchTime>2007-08-07T11:51:50.000Z</launchTime>\n      <placement>\n\t\t  <availabilityZone>us-east-1b</availabilityZone>\n      </placement>\n      <monitoring>\n        <state>enabled</state>\n      </monitoring>\n      <hypervisor>xen</hypervisor>\n    </item>\n  </instancesSet>\n</RunInstancesResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/run_instances_cloudbridge.xml",
    "content": "<?xml version=\"1.0\"?>\n<RunInstancesResponse xmlns=\"http://ec2.amazonaws.com/doc/2010-08-31/\">\n  <requestId>56eeacd9-c790-45c3-85f3-e4380b55e1d8</requestId>\n  <reservationId>r-f847a6ca</reservationId>\n  <ownerId>55ed6530-9b32-48f1-acb7-6ec0d3255a65</ownerId>\n  <groupSet>\n    <item>\n      <groupId>jclouds#greenqloud-computeblock</groupId>\n    </item>\n    <item>\n      <groupId>jclouds#greenqloud-computeblock</groupId>\n    </item>\n  </groupSet>\n  <instancesSet>\n    <item>\n      <instanceId>i-01b0dac3</instanceId>\n      <imageId>qmi-9ac92558</imageId>\n      <instanceState>\n        <code>0</code>\n        <name>pending</name>\n      </instanceState>\n      <privateDnsName/>\n      <dnsName/>\n      <reason/>\n      <keyName>jclouds#greenqloud-computeblock#35</keyName>\n      <amiLaunchIndex>0</amiLaunchIndex>\n      <productCodes>\n        <item>\n          <productCode/>\n        </item>\n      </productCodes>\n      <instanceType>m1.small</instanceType>\n      <launchTime>2012-06-15T19:06:35.000+00:00</launchTime>\n      <placement>\n        <availabilityZone>is-1a</availabilityZone>\n      </placement>\n      <kernelId/>\n      <ramdiskId/>\n      <platform/>\n      <monitoring>\n        <state>disabled</state>\n      </monitoring>\n      <subnetId/>\n      <vpcId/>\n      <privateIpAddress/>\n      <groupSet>\n        <item>\n          <groupId>jclouds#greenqloud-computeblock</groupId>\n        </item>\n        <item>\n          <groupId>jclouds#greenqloud-computeblock</groupId>\n        </item>\n      </groupSet>\n      <stateReason>\n        <code>pending</code>\n        <message>pending</message>\n      </stateReason>\n      <architecture/>\n      <rootDeviceType>ebs</rootDeviceType>\n      <rootDeviceName/>\n      <blockDeviceMapping/>\n      <instanceLifecycle/>\n      <spotInstanceRequestId/>\n      <hypervisor>xen</hypervisor>\n    </item>\n  </instancesSet>\n  <requesterId/>\n</RunInstancesResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/run_instances_three.xml",
    "content": "<RunInstancesResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n  <reservationId>r-47a5402e</reservationId>\n  <ownerId>AIDADH4IGTRXXKCD</ownerId>\n  <groupSet>\n    <item>\n      <groupId>default</groupId>\n    </item>\n  </groupSet>\n  <instancesSet>\n    <item>\n      <instanceId>i-2ba64342</instanceId>\n      <imageId>ami-aecd60c7</imageId>\n      <instanceState>\n        <code>0</code>\n        <name>pending</name>\n      </instanceState>\n      <privateDnsName></privateDnsName>\n      <dnsName></dnsName>\n      <keyName>example-key-name</keyName>\n      <amiLaunchIndex>0</amiLaunchIndex>\n      <instanceType>m1.small</instanceType>\n      <launchTime>2007-08-07T11:51:50.000Z</launchTime>\n      <placement>\n        <availabilityZone>us-east-1b</availabilityZone>\n      </placement>\n      <monitoring>\n        <state>enabled</state>\n      </monitoring>\n      <hypervisor>xen</hypervisor>      \n    </item>\n    <item>\n      <instanceId>i-2bc64242</instanceId>\n      <imageId>ami-aecd60c7</imageId>\n      <instanceState>\n        <code>0</code>\n        <name>pending</name>\n      </instanceState>\n      <privateDnsName></privateDnsName>\n      <dnsName></dnsName>\n      <keyName>example-key-name</keyName>\n      <amiLaunchIndex>1</amiLaunchIndex>\n      <instanceType>m1.small</instanceType>\n      <launchTime>2007-08-07T11:51:50.000Z</launchTime>\n      <placement>\n\t\t  <availabilityZone>us-east-1b</availabilityZone>\n      </placement>\n      <monitoring>\n        <state>enabled</state>\n      </monitoring>\n      <hypervisor>xen</hypervisor>\n    </item>\n    <item>\n      <instanceId>i-2be64332</instanceId>\n      <imageId>ami-aecd60c7</imageId>\n      <instanceState>\n        <code>0</code>\n        <name>pending</name>\n      </instanceState>\n      <privateDnsName></privateDnsName>\n      <dnsName></dnsName>\n      <keyName>example-key-name</keyName>\n      <amiLaunchIndex>2</amiLaunchIndex>\n      <instanceType>m1.small</instanceType>\n      <launchTime>2007-08-07T11:51:50.000Z</launchTime>\n      <placement>\n\t\t  <availabilityZone>us-east-1b</availabilityZone>\n      </placement>\n      <monitoring>\n        <state>enabled</state>\n      </monitoring>\n      <hypervisor>xen</hypervisor>\n    </item>\n  </instancesSet>\n</RunInstancesResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/start_instances.xml",
    "content": "<StartInstancesResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n    <instancesSet>\n        <item>\n            <instanceId>i-10a64379</instanceId>\n            <currentState>\n                <code>0</code>\n                <name>pending</name>\n            </currentState>\n            <previousState>\n                <code>80</code>\n                <name>stopped</name>\n            </previousState>\n        </item>\n    </instancesSet>\n</StartInstancesResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/stop_instances.xml",
    "content": "<StopInstancesResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n    <instancesSet>\n        <item>\n            <instanceId>i-10a64379</instanceId>\n            <currentState>\n                <code>64</code>\n                <name>stopping</name>\n            </currentState>\n            <previousState>\n                <code>16</code>\n                <name>running</name>\n            </previousState>\n        </item>\n    </instancesSet>\n</StopInstancesResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/terminate_instances.xml",
    "content": "<TerminateInstancesResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n  <instancesSet>\n    <item>\n      <instanceId>i-3ea74257</instanceId>\n      <shutdownState>\n        <code>32</code>\n        <name>shutting-down</name>\n      </shutdownState>\n      <previousState>\n        <code>16</code>\n        <name>running</name>\n      </previousState>\n    </item>\n  </instancesSet>\n</TerminateInstancesResponse>"
  },
  {
    "path": "apis/ec2/src/test/resources/userData.xml",
    "content": "<?xml version=\"1.0\"?>\n<DescribeInstanceAttributeResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n    <requestId>0d0ca353-fba3-402c-8516-005e2b41d0ba</requestId>\n    <instanceId>i-c72d0baf</instanceId>\n    <userData>\n        <value>IyEvYmluL2Jhc2gK</value>\n    </userData>\n</DescribeInstanceAttributeResponse>"
  },
  {
    "path": "apis/elasticstack/README.txt",
    "content": "#\n# The jclouds API for ElasticHosts' Cloud Servers API (http://www.elastichosts.com/cloud-hosting/api/).\n#\n# TODO: Implementation status.\n# TODO: Supported features.\n# TODO: Usage example.\n"
  },
  {
    "path": "apis/elasticstack/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.elasticstack.*;version=\"${project.version}\";-noimport:=true"
  },
  {
    "path": "apis/elasticstack/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.api</groupId>\n  <artifactId>elasticstack</artifactId>\n  <name>jclouds elasticstack core</name>\n  <description>jclouds components to access elasticstack</description>\n\n  <properties>\n    <test.elasticstack.endpoint>https://api-lon-p.elastichosts.com</test.elasticstack.endpoint>\n    <test.elasticstack.api-version>2.0</test.elasticstack.api-version>\n    <test.elasticstack.build-version />\n    <test.elasticstack.identity>FIXME_IDENTITY</test.elasticstack.identity>\n    <test.elasticstack.credential>FIXME_CREDENTIAL</test.elasticstack.credential>\n    <test.elasticstack.template>imageId=38df0986-4d85-4b76-b502-3878ffc80161,loginUser=toor</test.elasticstack.template>\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-log4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-sshj</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.squareup.okhttp3</groupId>\n      <artifactId>mockwebserver</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.squareup.okhttp3</groupId>\n      <artifactId>okhttp-tls</artifactId>\n      <scope>test</scope>\n      <exclusions>\n        <exclusion>\n          <groupId>org.bouncycastle</groupId>\n          <artifactId>bcprov-jdk15on</artifactId>\n        </exclusion>\n      </exclusions>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.elasticstack.endpoint>${test.elasticstack.endpoint}</test.elasticstack.endpoint>\n                    <test.elasticstack.api-version>${test.elasticstack.api-version}</test.elasticstack.api-version>\n                    <test.elasticstack.build-version>${test.elasticstack.build-version}</test.elasticstack.build-version>\n                    <test.elasticstack.identity>${test.elasticstack.identity}</test.elasticstack.identity>\n                    <test.elasticstack.credential>${test.elasticstack.credential}</test.elasticstack.credential>\n                    <test.elasticstack.template>${test.elasticstack.template}</test.elasticstack.template>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/ElasticStackApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack;\n\nimport java.io.Closeable;\nimport java.util.Set;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.elasticstack.binders.BindDriveDataToPlainTextString;\nimport org.jclouds.elasticstack.binders.BindDriveToPlainTextString;\nimport org.jclouds.elasticstack.binders.BindServerToPlainTextString;\nimport org.jclouds.elasticstack.domain.Drive;\nimport org.jclouds.elasticstack.domain.DriveData;\nimport org.jclouds.elasticstack.domain.DriveInfo;\nimport org.jclouds.elasticstack.domain.ImageConversionType;\nimport org.jclouds.elasticstack.domain.Server;\nimport org.jclouds.elasticstack.domain.ServerInfo;\nimport org.jclouds.elasticstack.domain.StandardDrive;\nimport org.jclouds.elasticstack.functions.KeyValuesDelimitedByBlankLinesToDriveInfo;\nimport org.jclouds.elasticstack.functions.KeyValuesDelimitedByBlankLinesToServerInfo;\nimport org.jclouds.elasticstack.functions.ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet;\nimport org.jclouds.elasticstack.functions.ListOfKeyValuesDelimitedByBlankLinesToServerInfoSet;\nimport org.jclouds.elasticstack.functions.ListOfKeyValuesDelimitedByBlankLinesToStandardDriveSet;\nimport org.jclouds.elasticstack.functions.ReturnPayload;\nimport org.jclouds.elasticstack.functions.SplitNewlines;\nimport org.jclouds.http.filters.BasicAuthentication;\nimport org.jclouds.io.Payload;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\n\n/**\n * Provides synchronous access to elasticstack via their REST API.\n * <p/>\n *\n * @see <a href=\"TODO: insert URL of provider documentation\" />\n */\n@RequestFilters(BasicAuthentication.class)\n@Consumes(MediaType.TEXT_PLAIN)\npublic interface ElasticStackApi extends Closeable {\n\n   /**\n    * list of server uuids in your account\n    *\n    * @return or empty set if no servers are found\n    */\n   @GET\n   @Path(\"/servers/list\")\n   @ResponseParser(SplitNewlines.class)\n   Set<String> listServers();\n\n   /**\n    * Get all servers info\n    *\n    * @return or empty set if no servers are found\n    */\n   @GET\n   @Path(\"/servers/info\")\n   @ResponseParser(ListOfKeyValuesDelimitedByBlankLinesToServerInfoSet.class)\n   Set<ServerInfo> listServerInfo();\n\n   /**\n    * @param uuid\n    *           what to get\n    * @return null, if not found\n    */\n   @GET\n   @Fallback(NullOnNotFoundOr404.class)\n   @ResponseParser(KeyValuesDelimitedByBlankLinesToServerInfo.class)\n   @Path(\"/servers/{uuid}/info\")\n   ServerInfo getServerInfo(@PathParam(\"uuid\") String uuid);\n\n   /**\n    * create a new server\n    *\n    * @param createServer\n    * @return newly created server\n    */\n   @POST\n   @Fallback(NullOnNotFoundOr404.class)\n   @ResponseParser(KeyValuesDelimitedByBlankLinesToServerInfo.class)\n   @Path(\"/servers/create/stopped\")\n   ServerInfo createServer(\n           @BinderParam(BindServerToPlainTextString.class) Server createServer);\n\n   /**\n    * set server configuration\n    *\n    * @param uuid\n    *           what server to change\n    * @param setServer\n    *           what values to change\n    * @return new data\n    */\n   @POST\n   @Fallback(NullOnNotFoundOr404.class)\n   @ResponseParser(KeyValuesDelimitedByBlankLinesToServerInfo.class)\n   @Path(\"/servers/{uuid}/set\")\n   ServerInfo setServerConfiguration(@PathParam(\"uuid\") String uuid,\n                                                       @BinderParam(BindServerToPlainTextString.class) Server setServer);\n\n   /**\n    * Destroy a server\n    *\n    * @param uuid\n    *           what to destroy\n    */\n   @POST\n   @Path(\"/servers/{uuid}/destroy\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void destroyServer(@PathParam(\"uuid\") String uuid);\n\n   /**\n    * Start a server\n    *\n    * @param uuid\n    *           what to start\n    */\n   @POST\n   @Path(\"/servers/{uuid}/start\")\n   void startServer(@PathParam(\"uuid\") String uuid);\n\n   /**\n    * Stop a server\n    * <p/>\n    * Kills the server immediately, equivalent to a power failure. Server reverts to a stopped\n    * status if it is persistent and is automatically destroyed otherwise.\n    *\n    * @param uuid\n    *           what to stop\n    */\n   @POST\n   @Path(\"/servers/{uuid}/stop\")\n   void stopServer(@PathParam(\"uuid\") String uuid);\n\n   /**\n    * Shutdown a server\n    * <p/>\n    * Sends the server an ACPI power-down event. Server reverts to a stopped status if it is\n    * persistent and is automatically destroyed otherwise.\n    * <h4>note</h4> behaviour on shutdown depends on how your server OS is set up to respond to an\n    * ACPI power button signal.\n    *\n    * @param uuid\n    *           what to shutdown\n    */\n   @POST\n   @Path(\"/servers/{uuid}/shutdown\")\n   void shutdownServer(@PathParam(\"uuid\") String uuid);\n\n\n   /**\n    * Reset a server\n    *\n    * @param uuid\n    *           what to reset\n    */\n   @POST\n   @Path(\"/servers/{uuid}/reset\")\n   void resetServer(@PathParam(\"uuid\") String uuid);\n\n   /**\n    * list of drive uuids in your account\n    *\n    * @return or empty set if no drives are found\n    */\n   @GET\n   @Path(\"/drives/list\")\n   @ResponseParser(SplitNewlines.class)\n   Set<String> listDrives();\n\n   /**\n    * Get all drives info\n    *\n    * @return or empty set if no drives are found\n    */\n   @GET\n   @Path(\"/drives/info\")\n   @ResponseParser(ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet.class)\n   Set<DriveInfo> listDriveInfo();\n   \n   /**\n    * Lists standard drive UUIDs in your account\n    *\n    * @return or empty set if no standard drives are found\n    */\n   @GET\n   @Path(\"/drives/list/standard\")\n   @ResponseParser(SplitNewlines.class)\n   Set<String> listStandardDrives();\n\n   /**\n    * Gets information about all standard drives\n    *\n    * @return or empty set if no standard drives are found\n    */\n   @GET\n   @Path(\"/drives/info/standard\")\n   @ResponseParser(ListOfKeyValuesDelimitedByBlankLinesToStandardDriveSet.class)\n   Set<StandardDrive> listStandardDriveInfo();\n\n   /**\n    * @param uuid\n    *           what to get\n    * @return null, if not found\n    */\n   @GET\n   @Fallback(NullOnNotFoundOr404.class)\n   @ResponseParser(KeyValuesDelimitedByBlankLinesToDriveInfo.class)\n   @Path(\"/drives/{uuid}/info\")\n   DriveInfo getDriveInfo(@PathParam(\"uuid\") String uuid);\n\n   /**\n    * create a new drive\n    *\n    * @param createDrive\n    *           required parameters: name, size\n    * @return newly created drive\n    */\n   @POST\n   @Fallback(NullOnNotFoundOr404.class)\n   @ResponseParser(KeyValuesDelimitedByBlankLinesToDriveInfo.class)\n   @Path(\"/drives/create\")\n   DriveInfo createDrive(@BinderParam(BindDriveToPlainTextString.class) Drive createDrive);\n\n   /**\n    * set extra drive data\n    *\n    * @param uuid\n    *           what drive to change\n    * @param setDrive\n    *           what values to change\n    * @return new data\n    */\n   @POST\n   @Fallback(NullOnNotFoundOr404.class)\n   @ResponseParser(KeyValuesDelimitedByBlankLinesToDriveInfo.class)\n   @Path(\"/drives/{uuid}/set\")\n   DriveInfo setDriveData(@PathParam(\"uuid\") String uuid,\n                                            @BinderParam(BindDriveDataToPlainTextString.class) DriveData setDrive);\n\n   /**\n    * Destroy a drive\n    *\n    * @param uuid\n    *           what to delete\n    */\n   @POST\n   @Path(\"/drives/{uuid}/destroy\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void destroyDrive(@PathParam(\"uuid\") String uuid);\n\n   /**\n    * create and start a new server\n    *\n    * @param createServer\n    * @return newly created server\n    */\n   @POST\n   @Fallback(NullOnNotFoundOr404.class)\n   @ResponseParser(KeyValuesDelimitedByBlankLinesToServerInfo.class)\n   @Path(\"/servers/create\")\n   ServerInfo createAndStartServer(\n           @BinderParam(BindServerToPlainTextString.class) Server createServer);\n\n   /**\n    * Image a drive from another drive. The actual imaging process is asynchronous, with progress\n    * reported via drive info.\n    *\n    * @param source\n    *           drive to copy from\n    * @param destination\n    *           drive to copy to\n    */\n   @POST\n   @Path(\"/drives/{destination}/image/{source}\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void imageDrive(@PathParam(\"source\") String source, @PathParam(\"destination\") String destination);\n\n   /**\n    * @see #imageDrive(String, String)\n    * @param conversionType\n    *           Supports 'gzip' or 'gunzip' conversions.\n    */\n   @POST\n   @Path(\"/drives/{destination}/image/{source}/{conversion}\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void imageDrive(@PathParam(\"source\") String source, @PathParam(\"destination\") String destination,\n                                     @PathParam(\"conversion\") ImageConversionType conversionType);\n\n   /**\n    * Read binary data from a drive\n    *\n    * @param uuid\n    *           drive to read\n    * @param offset\n    *           start at the specified offset in bytes\n    * @param size\n    *           the specified size in bytes; must be <=4096k\n    * @return binary content of the drive.\n    */\n   @POST\n   @Consumes(MediaType.APPLICATION_OCTET_STREAM)\n   @Path(\"/drives/{uuid}/read/{offset}/{size}\")\n   @ResponseParser(ReturnPayload.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   Payload readDrive(@PathParam(\"uuid\") String uuid, @PathParam(\"offset\") long offset,\n                                       @PathParam(\"size\") long size);\n\n   /**\n    * Write binary data to a drive\n    *\n    * @param uuid\n    *           drive to write\n    * @param content\n    *           what to write.\n    *           <ul>\n    *           <li>Binary data (Content-Type: application/octet-stream)</li>\n    *           <li>Supports raw data or Content-Encoding: gzip</li>\n    *           <li>Does not support Transfer-Encoding: chunked</li>\n    *           </ul>\n    */\n   @POST\n   @Produces(MediaType.APPLICATION_OCTET_STREAM)\n   @Path(\"/drives/{uuid}/write\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void writeDrive(@PathParam(\"uuid\") String uuid, Payload content);\n\n   /**\n    * @see ElasticStackApi#writeDrive(String, Payload)\n    * @param offset\n    *           the byte offset in the target drive at which to start writing, not an offset in the\n    *           input stream.\n    */\n   @POST\n   @Produces(MediaType.APPLICATION_OCTET_STREAM)\n   @Path(\"/drives/{uuid}/write/{offset}\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void writeDrive(@PathParam(\"uuid\") String uuid, Payload content, @PathParam(\"offset\") long offset);\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/ElasticStackApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack;\n\nimport static org.jclouds.elasticstack.reference.ElasticStackConstants.PROPERTY_VNC_PASSWORD;\nimport static org.jclouds.reflect.Reflection2.typeToken;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.elasticstack.compute.config.ElasticStackComputeServiceContextModule;\nimport org.jclouds.elasticstack.config.ElasticStackHttpApiModule;\nimport org.jclouds.rest.internal.BaseHttpApiMetadata;\n\nimport com.google.auto.service.AutoService;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n/**\n * Implementation of {@link ApiMetadata} for the ElasticStack API\n */\n@AutoService(ApiMetadata.class)\npublic class ElasticStackApiMetadata extends BaseHttpApiMetadata<ElasticStackApi> {\n\n   @Override\n   public Builder toBuilder() {\n      return new Builder().fromApiMetadata(this);\n   }\n\n   public ElasticStackApiMetadata() {\n      this(new Builder());\n   }\n\n   protected ElasticStackApiMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = BaseHttpApiMetadata.defaultProperties();\n      properties.setProperty(PROPERTY_VNC_PASSWORD, \"IL9vs34d\");\n      // passwords are set post-boot, so auth failures are possible\n      // from a race condition applying the password set script\n      properties.setProperty(\"jclouds.ssh.max-retries\", \"5\");\n      properties.setProperty(\"jclouds.ssh.retry-auth\", \"true\");\n      return properties;\n   }\n\n   public static class Builder extends BaseHttpApiMetadata.Builder<ElasticStackApi, Builder> {\n\n      protected Builder() {\n         id(\"elasticstack\")\n         .name(\"ElasticStack API\")\n         .identityName(\"UUID\")\n         .credentialName(\"Secret API key\")\n         .documentation(URI.create(\"http://www.elasticstack.com/cloud-platform/api\"))\n         .version(\"1.0\")\n         .defaultEndpoint(\"https://api-lon-p.elastichosts.com\")\n         .defaultProperties(ElasticStackApiMetadata.defaultProperties())\n         .view(typeToken(ComputeServiceContext.class))\n         .defaultModules(ImmutableSet.<Class<? extends Module>>of(ElasticStackHttpApiModule.class, ElasticStackComputeServiceContextModule.class));\n      }\n\n      @Override\n      public ElasticStackApiMetadata build() {\n         return new ElasticStackApiMetadata(this);\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/binders/BindDriveDataToPlainTextString.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.elasticstack.domain.DriveData;\nimport org.jclouds.elasticstack.functions.ListOfMapsToListOfKeyValuesDelimitedByBlankLines;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableSet;\n\n@Singleton\npublic class BindDriveDataToPlainTextString implements Binder {\n   private final Function<DriveData, Map<String, String>> createDriveRequestToMap;\n   private final ListOfMapsToListOfKeyValuesDelimitedByBlankLines listOfMapsToListOfKeyValuesDelimitedByBlankLines;\n\n   @Inject\n   public BindDriveDataToPlainTextString(Function<DriveData, Map<String, String>> createDriveRequestToMap,\n         ListOfMapsToListOfKeyValuesDelimitedByBlankLines listOfMapsToListOfKeyValuesDelimitedByBlankLines) {\n      this.createDriveRequestToMap = createDriveRequestToMap;\n      this.listOfMapsToListOfKeyValuesDelimitedByBlankLines = listOfMapsToListOfKeyValuesDelimitedByBlankLines;\n   }\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object payload) {\n      checkArgument(payload instanceof DriveData, \"this binder is only valid for DriveData!\");\n      DriveData create = DriveData.class.cast(payload);\n      Map<String, String> map = createDriveRequestToMap.apply(create);\n      request.setPayload(listOfMapsToListOfKeyValuesDelimitedByBlankLines.apply(ImmutableSet.of(map)));\n      request.getPayload().getContentMetadata().setContentType(MediaType.TEXT_PLAIN);\n      return request;\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/binders/BindDriveToPlainTextString.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.elasticstack.domain.Drive;\nimport org.jclouds.elasticstack.functions.ListOfMapsToListOfKeyValuesDelimitedByBlankLines;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableSet;\n\n@Singleton\npublic class BindDriveToPlainTextString implements Binder {\n   private final Function<Drive, Map<String, String>>  createDriveRequestToMap;\n   private final ListOfMapsToListOfKeyValuesDelimitedByBlankLines listOfMapsToListOfKeyValuesDelimitedByBlankLines;\n\n   @Inject\n   public BindDriveToPlainTextString(Function<Drive, Map<String, String>>  createDriveRequestToMap,\n         ListOfMapsToListOfKeyValuesDelimitedByBlankLines listOfMapsToListOfKeyValuesDelimitedByBlankLines) {\n      this.createDriveRequestToMap = createDriveRequestToMap;\n      this.listOfMapsToListOfKeyValuesDelimitedByBlankLines = listOfMapsToListOfKeyValuesDelimitedByBlankLines;\n   }\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object payload) {\n      checkArgument(payload instanceof Drive, \"this binder is only valid for Drive!\");\n      Drive create = Drive.class.cast(payload);\n      Map<String, String> map = createDriveRequestToMap.apply(create);\n      request.setPayload(listOfMapsToListOfKeyValuesDelimitedByBlankLines.apply(ImmutableSet.of(map)));\n      request.getPayload().getContentMetadata().setContentType(MediaType.TEXT_PLAIN);\n      return request;\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/binders/BindServerToPlainTextString.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.elasticstack.domain.Server;\nimport org.jclouds.elasticstack.functions.ListOfMapsToListOfKeyValuesDelimitedByBlankLines;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableSet;\n\n@Singleton\npublic class BindServerToPlainTextString implements Binder {\n   private final Function<Server, Map<String, String>> createServerRequestToMap;\n   private final ListOfMapsToListOfKeyValuesDelimitedByBlankLines listOfMapsToListOfKeyValuesDelimitedByBlankLines;\n\n   @Inject\n   public BindServerToPlainTextString(Function<Server, Map<String, String>> createServerRequestToMap,\n         ListOfMapsToListOfKeyValuesDelimitedByBlankLines listOfMapsToListOfKeyValuesDelimitedByBlankLines) {\n      this.createServerRequestToMap = createServerRequestToMap;\n      this.listOfMapsToListOfKeyValuesDelimitedByBlankLines = listOfMapsToListOfKeyValuesDelimitedByBlankLines;\n   }\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object payload) {\n      checkArgument(payload instanceof Server, \"this binder is only valid for Server!\");\n      Server create = Server.class.cast(payload);\n      Map<String, String> map = createServerRequestToMap.apply(create);\n      request.setPayload(listOfMapsToListOfKeyValuesDelimitedByBlankLines.apply(ImmutableSet.of(map)));\n      request.getPayload().getContentMetadata().setContentType(MediaType.TEXT_PLAIN);\n      return request;\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/compute/ElasticStackComputeServiceAdapter.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.compute;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Predicates.notNull;\nimport static com.google.common.collect.Iterables.contains;\nimport static com.google.common.collect.Iterables.filter;\nimport static org.jclouds.concurrent.FutureIterables.transformParallel;\nimport static org.jclouds.elasticstack.util.Servers.small;\n\nimport java.util.Map;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Constants;\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.ComputeServiceAdapter;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.HardwareBuilder;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.Processor;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.domain.Volume;\nimport org.jclouds.compute.domain.internal.VolumeImpl;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.elasticstack.ElasticStackApi;\nimport org.jclouds.elasticstack.domain.Device;\nimport org.jclouds.elasticstack.domain.Drive;\nimport org.jclouds.elasticstack.domain.DriveInfo;\nimport org.jclouds.elasticstack.domain.ImageConversionType;\nimport org.jclouds.elasticstack.domain.Server;\nimport org.jclouds.elasticstack.domain.ServerInfo;\nimport org.jclouds.elasticstack.domain.ServerStatus;\nimport org.jclouds.elasticstack.domain.WellKnownImage;\nimport org.jclouds.elasticstack.reference.ElasticStackConstants;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\nimport com.google.common.util.concurrent.Futures;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.common.util.concurrent.UncheckedExecutionException;\n\n/**\n * defines the connection between the {@link org.jclouds.elasticstack.ElasticStackApi} implementation\n * and the jclouds {@link org.jclouds.compute.ComputeService}\n */\n@Singleton\npublic class ElasticStackComputeServiceAdapter implements\n      ComputeServiceAdapter<ServerInfo, Hardware, DriveInfo, Location> {\n   private final ElasticStackApi client;\n   private final Predicate<DriveInfo> driveNotClaimed;\n   private final Supplier<Map<String, WellKnownImage>> preinstalledImages;\n   private final LoadingCache<String, DriveInfo> cache;\n   private final String defaultVncPassword;\n   private final ListeningExecutorService userExecutor;\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   @Inject\n   public ElasticStackComputeServiceAdapter(ElasticStackApi client, Predicate<DriveInfo> driveNotClaimed,\n         @Memoized Supplier<Map<String, WellKnownImage>> preinstalledImages, LoadingCache<String, DriveInfo> cache,\n         @Named(ElasticStackConstants.PROPERTY_VNC_PASSWORD) String defaultVncPassword,\n         @Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor) {\n      this.client = checkNotNull(client, \"client\");\n      this.driveNotClaimed = checkNotNull(driveNotClaimed, \"driveNotClaimed\");\n      this.preinstalledImages = checkNotNull(preinstalledImages, \"preinstalledImages\");\n      this.cache = checkNotNull(cache, \"cache\");\n      this.defaultVncPassword = checkNotNull(defaultVncPassword, \"defaultVncPassword\");\n      checkArgument(defaultVncPassword.length() <= 8, \"vnc passwords should be less that 8 characters!\");\n      this.userExecutor = checkNotNull(userExecutor, \"userExecutor\");\n   }\n\n   @Override\n   public NodeAndInitialCredentials<ServerInfo> createNodeWithGroupEncodedIntoName(String tag, String name, Template template) {\n      long bootSize = (long) (template.getHardware().getVolumes().get(0).getSize() * 1024 * 1024 * 1024L);\n\n      logger.debug(\">> creating boot drive bytes(%d)\", bootSize);\n      DriveInfo drive = client\n            .createDrive(new Drive.Builder().name(template.getImage().getId()).size(bootSize).build());\n      logger.debug(\"<< drive (%s)\", drive);\n\n      boolean success = driveNotClaimed.apply(drive);\n      if (!success) {\n         client.destroyDrive(drive.getUuid());\n         throw new IllegalStateException(String.format(\"could not create drive %s in time!\", drive));\n      }\n\n      logger.debug(\">> imaging boot drive source(%s)\", template.getImage().getId());\n      try {\n         client.imageDrive(template.getImage().getId(), drive.getUuid(), ImageConversionType.GUNZIP);\n      } catch (IllegalStateException ex) {\n         logger.debug(\">> could not image drive(%s). Cleaning up resources. [%s]\", drive.getUuid(), ex.getMessage());\n         client.destroyDrive(drive.getUuid());\n         throw ex;\n      }\n\n      boolean ready = driveNotClaimed.apply(drive);\n      if (!ready) {\n         client.destroyDrive(drive.getUuid());\n         throw new IllegalStateException(String.format(\"could not image drive %s in time!\", drive));\n      }\n      logger.debug(\"<< imaged (%s)\", drive);\n\n      template.getOptions().userMetadata(ComputeServiceConstants.NODE_GROUP_KEY, tag);\n\n      Server toCreate = small(name, drive.getUuid(), defaultVncPassword).mem(template.getHardware().getRam())\n               .cpu((int) (template.getHardware().getProcessors().get(0).getSpeed()))\n               .tags(template.getOptions().getTags()).userMetadata(template.getOptions().getUserMetadata()).build();\n\n      ServerInfo from = client.createServer(toCreate);\n\n      client.startServer(from.getUuid());\n      from = client.getServerInfo(from.getUuid());\n      return new NodeAndInitialCredentials<ServerInfo>(from, from.getUuid(), LoginCredentials.builder()\n            .password(defaultVncPassword).build());\n   }\n\n   @Override\n   public Iterable<Hardware> listHardwareProfiles() {\n      Builder<Hardware> hardware = ImmutableSet.builder();\n      for (double cpu : new double[] { 1000, 5000, 10000, 20000 })\n         for (int ram : new int[] { 512, 1024, 2048, 4096, 8192 }) {\n            final float size = (float) cpu / 1000;\n            String id = String.format(\"cpu=%f,ram=%s,disk=%f\", cpu, ram, size);\n            hardware.add(new HardwareBuilder().supportsImage(new Predicate<Image>() {\n\n               @Override\n               public boolean apply(Image input) {\n                  String toParse = input.getUserMetadata().get(\"size\");\n                  return toParse != null && Float.parseFloat(toParse) <= size;\n               }\n\n               @Override\n               public String toString() {\n                  return \"sizeLessThanOrEqual(\" + size + \")\";\n               }\n\n            }).ids(id).ram(ram).processors(ImmutableList.of(new Processor(1, cpu))).hypervisor(\"kvm\")\n                  .volumes(ImmutableList.<Volume> of(new VolumeImpl(size, true, true))).build());\n         }\n      return hardware.build();\n   }\n\n   /**\n    * look up the current standard images and do not error out, if they are not\n    * found.\n    */\n   @Override\n   public Iterable<DriveInfo> listImages() {\n      return FluentIterable.from(transformParallel(preinstalledImages.get().keySet(),\n            new Function<String, ListenableFuture<? extends DriveInfo>>() {\n\n               @Override\n               public ListenableFuture<? extends DriveInfo> apply(String input) {\n                  try {\n                     return Futures.immediateFuture(cache.getUnchecked(input));\n                  } catch (CacheLoader.InvalidCacheLoadException e) {\n                     logger.debug(\"drive %s not found\", input);\n                  } catch (UncheckedExecutionException e) {\n                     logger.warn(e, \"error finding drive %s: %s\", input, e.getMessage());\n                  }\n                  return Futures.immediateFuture(null);\n               }\n\n               @Override\n               public String toString() {\n                  return \"seedDriveCache()\";\n               }\n\n            }, userExecutor, null, logger, \"drives\")).filter(notNull());\n   }\n\n   @Override\n   public Iterable<ServerInfo> listNodes() {\n      return (Iterable<ServerInfo>) client.listServerInfo();\n   }\n\n   @Override\n   public Iterable<ServerInfo> listNodesByIds(final Iterable<String> ids) {\n      return filter(listNodes(), new Predicate<ServerInfo>() {\n\n            @Override\n            public boolean apply(ServerInfo server) {\n               return contains(ids, server.getUuid());\n            }\n         });\n   }\n\n   @Override\n   public Iterable<Location> listLocations() {\n      // Not using the adapter to determine locations\n      return ImmutableSet.<Location>of();\n   }\n\n   @Override\n   public ServerInfo getNode(String id) {\n      return client.getServerInfo(id);\n   }   \n   \n   @Override\n   public DriveInfo getImage(String id) {\n      return client.getDriveInfo(id);\n   }\n\n   @Override\n   public void destroyNode(String id) {\n      ServerInfo server = getNode(id);\n      if (server != null) {\n         if (server.getStatus() != ServerStatus.STOPPED)\n            client.stopServer(id);\n         client.destroyServer(id);\n         for (Device dev : server.getDevices().values())\n            client.destroyDrive(dev.getDriveUuid());\n      }\n   }\n\n   @Override\n   public void rebootNode(String id) {\n      client.resetServer(id);\n   }\n\n   @Override\n   public void resumeNode(String id) {\n      client.startServer(id);\n   }\n\n   @Override\n   public void suspendNode(String id) {\n      client.stopServer(id);\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/compute/config/ElasticStackComputeServiceContextModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.compute.config;\n\nimport static com.google.common.base.Suppliers.memoizeWithExpiration;\nimport static java.util.concurrent.TimeUnit.MILLISECONDS;\nimport static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL;\nimport static org.jclouds.util.Predicates2.retry;\n\nimport java.io.IOException;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.ComputeServiceAdapter;\nimport org.jclouds.compute.config.ComputeServiceAdapterContextModule;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.Volume;\nimport org.jclouds.compute.reference.ComputeServiceConstants.Timeouts;\nimport org.jclouds.domain.Location;\nimport org.jclouds.elasticstack.ElasticStackApi;\nimport org.jclouds.elasticstack.compute.ElasticStackComputeServiceAdapter;\nimport org.jclouds.elasticstack.compute.functions.ServerInfoToNodeMetadata;\nimport org.jclouds.elasticstack.compute.functions.ServerInfoToNodeMetadata.DeviceToVolume;\nimport org.jclouds.elasticstack.compute.functions.ServerInfoToNodeMetadata.GetImageIdFromServer;\nimport org.jclouds.elasticstack.compute.functions.StandardDriveToWellKnownImage;\nimport org.jclouds.elasticstack.compute.functions.WellKnownImageToImage;\nimport org.jclouds.elasticstack.domain.Device;\nimport org.jclouds.elasticstack.domain.DriveInfo;\nimport org.jclouds.elasticstack.domain.Server;\nimport org.jclouds.elasticstack.domain.ServerInfo;\nimport org.jclouds.elasticstack.domain.StandardDrive;\nimport org.jclouds.elasticstack.domain.WellKnownImage;\nimport org.jclouds.elasticstack.predicates.DriveClaimed;\nimport org.jclouds.elasticstack.suppliers.WellKnownImageSupplier;\nimport org.jclouds.functions.IdentityFunction;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.suppliers.MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Predicates;\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.Maps;\nimport com.google.inject.Provides;\nimport com.google.inject.TypeLiteral;\n\npublic class ElasticStackComputeServiceContextModule extends\n      ComputeServiceAdapterContextModule<ServerInfo, Hardware, DriveInfo, Location> {\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   protected void configure() {\n      super.configure();\n      bind(new TypeLiteral<ComputeServiceAdapter<ServerInfo, Hardware, DriveInfo, Location>>() {\n      }).to(ElasticStackComputeServiceAdapter.class);\n      bind(new TypeLiteral<Function<ServerInfo, NodeMetadata>>() {\n      }).to(ServerInfoToNodeMetadata.class);\n      bind(new TypeLiteral<Function<Image, Image>>() {\n      }).to(Class.class.cast(IdentityFunction.class));\n      bind(new TypeLiteral<Function<Hardware, Hardware>>() {\n      }).to(Class.class.cast(IdentityFunction.class));\n      bind(new TypeLiteral<Function<Location, Location>>() {\n      }).to(Class.class.cast(IdentityFunction.class));\n      bind(new TypeLiteral<Function<Device, Volume>>() {\n      }).to(DeviceToVolume.class);\n      bind(new TypeLiteral<Function<Server, String>>() {\n      }).to(GetImageIdFromServer.class);\n      bind(new TypeLiteral<Function<DriveInfo, Image>>() {\n      }).to(WellKnownImageToImage.class);\n      bind(new TypeLiteral<Function<StandardDrive, WellKnownImage>>() {\n      }).to(StandardDriveToWellKnownImage.class);\n      bind(new TypeLiteral<Supplier<List<WellKnownImage>>>() {\n      }).to(WellKnownImageSupplier.class);\n   }\n\n   @Provides\n   @Singleton\n   protected final LoadingCache<String, DriveInfo> cache(GetDrive getDrive) {\n      return CacheBuilder.newBuilder().build(getDrive);\n   }\n\n   @Singleton\n   public static class GetDrive extends CacheLoader<String, DriveInfo> {\n      private final ElasticStackApi client;\n\n      @Inject\n      public GetDrive(ElasticStackApi client) {\n         this.client = client;\n      }\n\n      @Override\n      public DriveInfo load(String input) {\n         return client.getDriveInfo(input);\n      }\n   }\n\n   @Singleton\n   @Provides\n   @Memoized\n   protected final Supplier<Map<String, WellKnownImage>> provideImages(@Named(PROPERTY_SESSION_INTERVAL) long seconds,\n         @Memoized final Supplier<List<WellKnownImage>> wellKnownImageSupplier) throws IOException {\n      // The image map won't change. Memoize it during the session.\n      // This map can't be created directly as a singleton, as Guice needs it to construct the ElasticStackComputeServiceAdapter\n      // and a misconfiguration such as invalid credentials, etc would cause the Guice injection to fail\n      return memoizeWithExpiration(new Supplier<Map<String, WellKnownImage>>() {\n         @Override\n         public Map<String, WellKnownImage> get() {\n            return Maps.uniqueIndex(wellKnownImageSupplier.get(), new Function<WellKnownImage, String>() {\n               @Override\n               public String apply(WellKnownImage input) {\n                  return input.getUuid();\n               }\n            });\n         }\n      }, seconds, TimeUnit.SECONDS);\n   }\n   \n   @Singleton\n   @Provides\n   @Memoized\n   protected final Supplier<List<WellKnownImage>> provideWellKnownImageSupplier(AtomicReference<AuthorizationException> authException,\n         @Named(PROPERTY_SESSION_INTERVAL) long seconds, WellKnownImageSupplier uncached)\n         throws IOException {\n      return MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier.create(authException, uncached, seconds,\n            TimeUnit.SECONDS);\n   }\n\n   @Provides\n   @Singleton\n   protected final Predicate<DriveInfo> supplyDriveUnclaimed(DriveClaimed driveClaimed, Timeouts timeouts) {\n      return retry(Predicates.not(driveClaimed), timeouts.nodeRunning, 1000, MILLISECONDS);\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/compute/functions/ServerInfoToNodeMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.compute.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.compute.predicates.ImagePredicates.idEquals;\nimport static org.jclouds.compute.util.ComputeServiceUtils.groupFromMapOrName;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.domain.HardwareBuilder;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadata.Status;\nimport org.jclouds.compute.domain.NodeMetadataBuilder;\nimport org.jclouds.compute.domain.Processor;\nimport org.jclouds.compute.domain.Volume;\nimport org.jclouds.compute.domain.VolumeBuilder;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.domain.Location;\nimport org.jclouds.elasticstack.domain.Device;\nimport org.jclouds.elasticstack.domain.DriveInfo;\nimport org.jclouds.elasticstack.domain.Server;\nimport org.jclouds.elasticstack.domain.ServerInfo;\nimport org.jclouds.elasticstack.domain.ServerStatus;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.util.concurrent.UncheckedExecutionException;\n\n@Singleton\npublic class ServerInfoToNodeMetadata implements Function<ServerInfo, NodeMetadata> {\n   public static final Map<ServerStatus, Status> serverStatusToNodeStatus = ImmutableMap\n         .<ServerStatus, Status> builder().put(ServerStatus.ACTIVE, Status.RUNNING)//\n         .put(ServerStatus.STOPPED, Status.SUSPENDED)//\n         .put(ServerStatus.PAUSED, Status.SUSPENDED)//\n         .put(ServerStatus.DUMPED, Status.PENDING)//\n         .put(ServerStatus.DEAD, Status.TERMINATED)//\n         .put(ServerStatus.UNRECOGNIZED, Status.UNRECOGNIZED)//\n         .build();\n\n   private final Function<Server, String> getImageIdFromServer;\n   private final Supplier<Set<? extends Image>> images;\n   private final Supplier<Location> locationSupplier;\n   private final Function<Device, Volume> deviceToVolume;\n   private final GroupNamingConvention nodeNamingConvention;\n\n   @Inject\n   ServerInfoToNodeMetadata(Function<Server, String> getImageIdFromServer, @Memoized Supplier<Set<? extends Image>> images,\n         Function<Device, Volume> deviceToVolume, Supplier<Location> locationSupplier,\n         GroupNamingConvention.Factory namingConvention) {\n      this.nodeNamingConvention = checkNotNull(namingConvention, \"namingConvention\").createWithoutPrefix();\n      this.locationSupplier = checkNotNull(locationSupplier, \"locationSupplier\");\n      this.deviceToVolume = checkNotNull(deviceToVolume, \"deviceToVolume\");\n      this.images = checkNotNull(images, \"images\");\n      this.getImageIdFromServer = checkNotNull(getImageIdFromServer, \"getImageIdFromServer\");\n   }\n\n   @Override\n   public NodeMetadata apply(ServerInfo from) {\n      NodeMetadataBuilder builder = new NodeMetadataBuilder();\n      builder.ids(from.getUuid());\n      builder.name(from.getName());\n      builder.location(locationSupplier.get());\n      builder.group(groupFromMapOrName(from.getUserMetadata(), from.getName(), nodeNamingConvention));\n      builder.tags(from.getTags());\n      builder.userMetadata(from.getUserMetadata());\n      String imageId = getImageIdFromServer.apply(from);\n      if (imageId != null) {\n         Optional<? extends Image> image = FluentIterable.from(images.get()).firstMatch(idEquals(imageId));\n         if (image.isPresent()) {\n            builder.operatingSystem(image.get().getOperatingSystem());\n         }\n      }\n      builder.hardware(new HardwareBuilder().ids(from.getUuid()).hypervisor(\"kvm\")\n            .processors(ImmutableList.of(new Processor(1, from.getCpu()))).ram(from.getMem())\n            .volumes(Iterables.transform(from.getDevices().values(), deviceToVolume)).build());\n      builder.status(serverStatusToNodeStatus.get(from.getStatus()));\n      builder.publicAddresses(ImmutableSet.<String> of(from.getNics().get(0).getDhcp()));\n      builder.privateAddresses(ImmutableSet.<String> of());\n      return builder.build();\n   }\n\n   @Singleton\n   public static final class DeviceToVolume implements Function<Device, Volume> {\n      @Resource\n      protected Logger logger = Logger.NULL;\n\n      private final LoadingCache<String, DriveInfo> cache;\n\n      @Inject\n      public DeviceToVolume(LoadingCache<String, DriveInfo> cache) {\n         this.cache = checkNotNull(cache, \"cache\");\n      }\n\n      @Override\n      public Volume apply(Device input) {\n         VolumeBuilder builder = new VolumeBuilder();\n         builder.id(input.getId());\n         try {\n            DriveInfo drive = cache.getUnchecked(input.getDriveUuid());\n            builder.size(drive.getSize() / (float) (1024 * 1024));\n         } catch (NullPointerException e) {\n            logger.debug(\"drive %s not found\", input.getDriveUuid());\n         } catch (UncheckedExecutionException e) {\n            logger.warn(e, \"error finding drive %s: %s\", input.getDriveUuid(), e.getMessage());\n         }\n         return builder.durable(true).type(Volume.Type.NAS).build();\n      }\n   }\n\n   /**\n    * When we create the boot drive of the server, by convention we set the name\n    * to the image it came from.\n    * \n    * \n    */\n   @Singleton\n   public static class GetImageIdFromServer implements Function<Server, String> {\n      @Resource\n      protected Logger logger = Logger.NULL;\n\n      private final LoadingCache<String, DriveInfo> cache;\n\n      @Inject\n      public GetImageIdFromServer(LoadingCache<String, DriveInfo> cache) {\n         this.cache = cache;\n      }\n\n      @Override\n      public String apply(Server from) {\n         String imageId = null;\n         if (!from.getBootDeviceIds().isEmpty()) {\n            String bootDeviceId = Iterables.get(from.getBootDeviceIds(), 0);\n            Device bootDevice = from.getDevices().get(bootDeviceId);\n            if (bootDevice != null) {\n               try {\n                  DriveInfo drive = cache.getUnchecked(bootDevice.getDriveUuid());\n                  imageId = drive.getName();\n               } catch (NullPointerException e) {\n                  logger.debug(\"drive %s not found\", bootDevice.getDriveUuid());\n               } catch (UncheckedExecutionException e) {\n                  logger.warn(e, \"error finding drive %s: %s\", bootDevice.getDriveUuid(), e.getMessage());\n               }\n            }\n         }\n         return imageId;\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/compute/functions/StandardDriveToWellKnownImage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.compute.functions;\n\nimport static com.google.common.collect.Iterables.tryFind;\nimport static java.util.Arrays.asList;\n\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.elasticstack.domain.StandardDrive;\nimport org.jclouds.elasticstack.domain.WellKnownImage;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\n\n/**\n * Transforms a standard drive into an image that can be used to create nodes.\n */\n@Singleton\npublic class StandardDriveToWellKnownImage implements Function<StandardDrive, WellKnownImage> {\n\n   /*\n    * Expression to finds the version in a text string in a Unix OS:\n    * CentOS 6 => 6\n    * CentOS Linux 6.5 =>\n    * Debian Linux 7.4 (Wheezy) => 7.4\n    * Ubuntu Linux 12.04.1 LTS (Precise Pangolin) => 12.04.1\n    */\n   private static final Pattern UNIX_VERSION_PATTERN = Pattern.compile(\"[^\\\\d]*(\\\\d+(?:\\\\.\\\\d+)*).*\");\n\n   /*\n    * Expression to finds the version in a text string in a Windows OS:\n    * Windows Server 2012 => 2012\n    * Windows Standard 2008 R2 => 2008 R2\n    * Windows Standard 2008 R2 + SQL => 2008 R2 + SQL\n    */\n   private static final Pattern WINDOWS_VERSION_PATTERN = Pattern.compile(\"[^\\\\d]*(\\\\d+.*)\");\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   @Override\n   public WellKnownImage apply(StandardDrive input) {\n      WellKnownImage.Builder builder = WellKnownImage.builder();\n      builder.uuid(input.getUuid());\n      builder.size(toGb(input.getSize()));\n      builder.description(input.getName());\n\n      OsFamily family = extractOsFamily(input.getName());\n      String version = extractOsVersion(family, input.getName());\n\n      builder.osFamily(family);\n      builder.osVersion(version);\n      builder.is64bit(is64bit(input.getName()));\n\n      return builder.build();\n   }\n\n   private static boolean is64bit(String name) {\n      return !name.contains(\"32bit\");\n   }\n\n   private OsFamily extractOsFamily(final String name) {\n      final String lowerCaseName = name.toLowerCase();\n      Optional<OsFamily> family = tryFind(asList(OsFamily.values()), new Predicate<OsFamily>() {\n         @Override\n         public boolean apply(OsFamily input) {\n            return lowerCaseName.startsWith(input.name().toLowerCase());\n         }\n      });\n\n      if (!family.isPresent()) {\n         logger.warn(\"could not find the operating system family for image: %s\", name);\n      }\n\n      return family.or(OsFamily.UNRECOGNIZED);\n   }\n\n   private String extractOsVersion(OsFamily family, String name) {\n      String version = null;\n      if (family == OsFamily.WINDOWS) {\n         // TODO: Find a way to restrict better the windows version\n         Matcher matcher = WINDOWS_VERSION_PATTERN.matcher(name);\n         if (matcher.matches()) {\n            version = matcher.group(1);\n         }\n      } else {\n         Matcher matcher = UNIX_VERSION_PATTERN.matcher(name);\n         if (matcher.matches()) {\n            version = matcher.group(1);\n         }\n      }\n\n      if (version == null) {\n         logger.warn(\"could not find the operating system version for image: %s\", name);\n      }\n\n      return version;\n   }\n\n   private static int toGb(long sizeInBytes) {\n      return (int) (sizeInBytes / (1024 * 1024 * 1024));\n   }\n\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/compute/functions/WellKnownImageToImage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.compute.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.Image.Status;\nimport org.jclouds.compute.domain.ImageBuilder;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.elasticstack.domain.DriveInfo;\nimport org.jclouds.elasticstack.domain.WellKnownImage;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableMap;\n\n@Singleton\npublic class WellKnownImageToImage implements Function<DriveInfo, Image> {\n   private final Supplier<Location> locationSupplier;\n   private final Supplier<Map<String, WellKnownImage>> preinstalledImages;\n   private final Map<String, Credentials> credentialStore;\n\n   @Inject\n   public WellKnownImageToImage(Supplier<Location> locationSupplier,\n         @Memoized Supplier<Map<String, WellKnownImage>> preinstalledImages, Map<String, Credentials> credentialStore) {\n      this.locationSupplier = checkNotNull(locationSupplier, \"locationSupplier cannot be null\");\n      this.preinstalledImages = checkNotNull(preinstalledImages, \"preinstalledImages cannot be null\");\n      this.credentialStore = checkNotNull(credentialStore, \"credentialStore cannot be null\");\n   }\n\n   @Override\n   public Image apply(DriveInfo drive) {\n      WellKnownImage input = preinstalledImages.get().get(drive.getUuid());\n      // set credentials in the store here, as opposed to directly modifying the image. we need to\n      // set credentials on the image outside of this function so that they can be for example\n      // overridden by properties\n      credentialStore.put(\"image#\" + drive.getUuid(), LoginCredentials.builder().user(input.getLoginUser()).build());\n      return new ImageBuilder()\n            .ids(drive.getUuid())\n            .userMetadata(\n                  ImmutableMap.<String, String> builder().putAll(drive.getUserMetadata())\n                        .put(\"size\", input.getSize() + \"\").build())\n            .location(locationSupplier.get())\n            .name(input.getDescription())\n            .description(drive.getName())\n            .status(Status.AVAILABLE)\n            .operatingSystem(\n                  new OperatingSystem.Builder().family(input.getOsFamily()).version(input.getOsVersion())\n                        .name(input.getDescription()).description(drive.getName()).is64Bit(input.is64bit()).build())\n            .version(\"\").build();\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/config/ElasticStackHttpApiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.config;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.elasticstack.ElasticStackApi;\nimport org.jclouds.elasticstack.domain.Device;\nimport org.jclouds.elasticstack.domain.Drive;\nimport org.jclouds.elasticstack.domain.DriveData;\nimport org.jclouds.elasticstack.domain.DriveMetrics;\nimport org.jclouds.elasticstack.domain.NIC;\nimport org.jclouds.elasticstack.domain.Server;\nimport org.jclouds.elasticstack.domain.ServerMetrics;\nimport org.jclouds.elasticstack.functions.CreateDriveRequestToMap;\nimport org.jclouds.elasticstack.functions.DriveDataToMap;\nimport org.jclouds.elasticstack.functions.MapToDevices;\nimport org.jclouds.elasticstack.functions.MapToDevices.DeviceToId;\nimport org.jclouds.elasticstack.functions.MapToDriveMetrics;\nimport org.jclouds.elasticstack.functions.MapToNICs;\nimport org.jclouds.elasticstack.functions.MapToServerMetrics;\nimport org.jclouds.elasticstack.functions.ServerToMap;\nimport org.jclouds.elasticstack.handlers.ElasticStackErrorHandler;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.annotation.ClientError;\nimport org.jclouds.http.annotation.Redirection;\nimport org.jclouds.http.annotation.ServerError;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.config.HttpApiModule;\n\nimport com.google.common.base.Function;\nimport com.google.inject.TypeLiteral;\n\n/**\n * Configures the elasticstack connection.\n */\n@ConfiguresHttpApi\npublic class ElasticStackHttpApiModule extends HttpApiModule<ElasticStackApi> {\n\n   @Override\n   protected void configure() {\n      super.configure();\n      bind(new TypeLiteral<Function<Drive, Map<String, String>>>() {\n      }).to(CreateDriveRequestToMap.class);\n      bind(new TypeLiteral<Function<DriveData, Map<String, String>>>() {\n      }).to(DriveDataToMap.class);\n      bind(new TypeLiteral<Function<Map<String, String>, List<NIC>>>() {\n      }).to(MapToNICs.class);\n      bind(new TypeLiteral<Function<Map<String, String>, Map<String, ? extends Device>>>() {\n      }).to(MapToDevices.class);\n      bind(new TypeLiteral<Function<Map<String, String>, Map<String, ? extends DriveMetrics>>>() {\n      }).to(MapToDriveMetrics.class);\n      bind(new TypeLiteral<Function<Map<String, String>, ServerMetrics>>() {\n      }).to(MapToServerMetrics.class);\n      bind(new TypeLiteral<Function<Device, String>>() {\n      }).to(DeviceToId.class);\n      bind(new TypeLiteral<Function<Server, Map<String, String>>>() {\n      }).to(ServerToMap.class);\n   }\n\n   @Override\n   protected void bindErrorHandlers() {\n      bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(ElasticStackErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(ElasticStackErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(ElasticStackErrorHandler.class);\n   }\n\n   @Override\n   protected void bindRetryHandlers() {\n      // TODO\n   }\n\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/domain/BlockDevice.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.domain;\n\nimport static com.google.common.base.Preconditions.checkArgument;\n\npublic class BlockDevice extends Device {\n   public static class Builder extends Device.Builder {\n      private final int index;\n\n      public Builder(int index) {\n         this.index = index;\n      }\n\n      @Override\n      public Device build() {\n         return new BlockDevice(uuid, mediaType, index);\n      }\n\n   }\n\n   private final int index;\n\n   public BlockDevice(String driveUuid, MediaType mediaType, int index) {\n      super(driveUuid, mediaType);\n      checkArgument(index >= 0 && index < 8, \"index must be between 0 and 7\");\n      this.index = index;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + index;\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      BlockDevice other = (BlockDevice) obj;\n      if (index != other.index)\n         return false;\n      return true;\n   }\n\n   @Override\n   public String getId() {\n      return String.format(\"block:%d\", index);\n   }\n\n   public int getIndex() {\n      return index;\n   }\n\n   @Override\n   public String toString() {\n      return \"[id=\" + getId() + \", driveUuid=\" + driveUuid + \", mediaType=\" + mediaType + \"]\";\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/domain/ClaimType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\n/**\n * either 'exclusive' (the default) or 'shared' to allow multiple servers to access a drive\n * simultaneously\n */\npublic enum ClaimType {\n   /**\n    * \n    */\n   EXCLUSIVE,\n   /**\n    * allow multiple servers to access a drive simultaneously\n    */\n   SHARED, UNRECOGNIZED;\n\n   public String value() {\n      return name().toLowerCase();\n   }\n\n   @Override\n   public String toString() {\n      return value();\n   }\n\n   public static ClaimType fromValue(String claim) {\n      try {\n         return valueOf(checkNotNull(claim, \"claim\").toUpperCase());\n      } catch (IllegalArgumentException e) {\n         return UNRECOGNIZED;\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/domain/CreateDriveRequest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.collect.ImmutableSet;\n\npublic class CreateDriveRequest extends Drive {\n   public static class Builder extends Drive.Builder {\n\n      private Set<String> avoid = ImmutableSet.of();\n\n      @Nullable\n      private String encryptionCipher;\n\n      public Builder avoid(Iterable<String> avoid) {\n         this.avoid = ImmutableSet.copyOf(checkNotNull(avoid, \"avoid\"));\n         return this;\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder claimType(ClaimType claimType) {\n         return Builder.class.cast(super.claimType(claimType));\n      }\n\n      public Builder encryptionCipher(String encryptionCipher) {\n         this.encryptionCipher = encryptionCipher;\n         return this;\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder name(String name) {\n         return Builder.class.cast(super.name(name));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder readers(Iterable<String> readers) {\n         return Builder.class.cast(super.readers(readers));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder size(long size) {\n         return Builder.class.cast(super.size(size));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder tags(Iterable<String> tags) {\n         return Builder.class.cast(super.tags(tags));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder userMetadata(Map<String, String> userMetadata) {\n         return Builder.class.cast(super.userMetadata(userMetadata));\n      }\n\n      public CreateDriveRequest build() {\n         return new CreateDriveRequest(name, size, claimType, readers, tags, userMetadata, encryptionCipher, avoid);\n      }\n   }\n\n   private final Set<String> avoid;\n   @Nullable\n   private final String encryptionCipher;\n\n   public CreateDriveRequest(String name, long size, @Nullable ClaimType claimType, Iterable<String> readers,\n         Iterable<String> tags, Map<String, String> userMetadata, @Nullable String encryptionCipher,\n         Iterable<String> avoid) {\n      super(null, name, size, claimType, readers, tags, userMetadata);\n      this.encryptionCipher = encryptionCipher;\n      this.avoid = ImmutableSet.copyOf(checkNotNull(avoid, \"avoid\"));\n   }\n\n   /**\n    * \n    * @return list of existing drives to ensure this new drive is created on physical different\n    *         hardware than those existing drives\n    */\n   public Set<String> getAvoid() {\n      return avoid;\n   }\n\n   /**\n    * \n    * @return either 'none' or 'aes-xts-plain' (the default)\n    */\n   @Nullable\n   public String getEncryptionCipher() {\n      return encryptionCipher;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = super.hashCode();\n      result = prime * result + ((avoid == null) ? 0 : avoid.hashCode());\n      result = prime * result + ((encryptionCipher == null) ? 0 : encryptionCipher.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (!super.equals(obj))\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      CreateDriveRequest other = (CreateDriveRequest) obj;\n      if (avoid == null) {\n         if (other.avoid != null)\n            return false;\n      } else if (!avoid.equals(other.avoid))\n         return false;\n      if (encryptionCipher == null) {\n         if (other.encryptionCipher != null)\n            return false;\n      } else if (!encryptionCipher.equals(other.encryptionCipher))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"[name=\" + name + \", size=\" + size + \", claimType=\" + claimType + \", readers=\" + readers + \", tags=\"\n            + tags + \", userMetadata=\" + userMetadata + \", avoid=\" + avoid + \", encryptionCipher=\" + encryptionCipher\n            + \"]\";\n   }\n\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/domain/Device.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\npublic abstract class Device {\n   public abstract static class Builder {\n      protected String uuid;\n      protected MediaType mediaType = MediaType.DISK;\n\n      public Builder mediaType(MediaType mediaType) {\n         this.mediaType = mediaType;\n         return this;\n      }\n\n      public Builder uuid(String uuid) {\n         this.uuid = uuid;\n         return this;\n      }\n\n      public abstract Device build();\n   }\n\n   protected final String driveUuid;\n   protected final MediaType mediaType;\n\n   public Device(String driveUuid, MediaType mediaType) {\n      this.driveUuid = checkNotNull(driveUuid, \"driveUuid\");\n      this.mediaType = checkNotNull(mediaType, \"mediaType\");\n   }\n\n   /**\n    * id generated based on the device bus, unit, and/or index numbers;\n    */\n   public abstract String getId();\n\n   /**\n    * \n    * @return Drive UUID to connect as specified device.\n    */\n   public String getDriveUuid() {\n      return driveUuid;\n   }\n\n   /**\n    * \n    * @return set to 'cdrom' to simulate a cdrom, set to 'disk' or leave unset to simulate a hard\n    *         disk.\n    */\n   public MediaType getMediaType() {\n      return mediaType;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((driveUuid == null) ? 0 : driveUuid.hashCode());\n      result = prime * result + ((mediaType == null) ? 0 : mediaType.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      Device other = (Device) obj;\n      if (driveUuid == null) {\n         if (other.driveUuid != null)\n            return false;\n      } else if (!driveUuid.equals(other.driveUuid))\n         return false;\n      if (mediaType != other.mediaType)\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"[driveUuid=\" + driveUuid + \", mediaType=\" + mediaType + \"]\";\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/domain/Drive.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.collect.ImmutableSet;\n\npublic class Drive extends Item {\n   public static class Builder extends Item.Builder {\n      protected long size;\n      protected ClaimType claimType = ClaimType.EXCLUSIVE;\n      protected Set<String> readers = ImmutableSet.of();\n\n      public Builder claimType(ClaimType claimType) {\n         this.claimType = claimType;\n         return this;\n      }\n\n      public Builder readers(Iterable<String> readers) {\n         this.readers = ImmutableSet.copyOf(checkNotNull(readers, \"readers\"));\n         return this;\n      }\n\n      public Builder size(long size) {\n         this.size = size;\n         return this;\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder uuid(String uuid) {\n         return Builder.class.cast(super.uuid(uuid));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder name(String name) {\n         return Builder.class.cast(super.name(name));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder tags(Iterable<String> tags) {\n         return Builder.class.cast(super.tags(tags));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder userMetadata(Map<String, String> userMetadata) {\n         return Builder.class.cast(super.userMetadata(userMetadata));\n      }\n\n      public Drive build() {\n         return new Drive(uuid, name, size, claimType, readers, tags, userMetadata);\n      }\n\n      @Override\n      public int hashCode() {\n         final int prime = 31;\n         int result = super.hashCode();\n         result = prime * result + ((claimType == null) ? 0 : claimType.hashCode());\n         result = prime * result + ((readers == null) ? 0 : readers.hashCode());\n         result = prime * result + (int) (size ^ (size >>> 32));\n         return result;\n      }\n\n      @Override\n      public boolean equals(Object obj) {\n         if (this == obj)\n            return true;\n         if (!super.equals(obj))\n            return false;\n         if (getClass() != obj.getClass())\n            return false;\n         Builder other = (Builder) obj;\n         if (claimType != other.claimType)\n            return false;\n         if (readers == null) {\n            if (other.readers != null)\n               return false;\n         } else if (!readers.equals(other.readers))\n            return false;\n         if (size != other.size)\n            return false;\n         return true;\n      }\n   }\n\n   protected final long size;\n   protected final ClaimType claimType;\n   protected final Set<String> readers;\n\n   public Drive(@Nullable String uuid, String name, long size, @Nullable ClaimType claimType,\n         Iterable<String> readers, Iterable<String> tags, Map<String, String> userMetadata) {\n      super(uuid, name, tags, userMetadata);\n      this.size = size;\n      this.claimType = checkNotNull(claimType, \"set claimType to exclusive, not null\");\n      this.readers = ImmutableSet.copyOf(checkNotNull(readers, \"readers\"));\n   }\n\n   /**\n    * \n    * @return either 'exclusive' (the default) or 'shared' to allow multiple servers to access a\n    *         drive simultaneously\n    */\n   @Nullable\n   public ClaimType getClaimType() {\n      return claimType;\n   }\n\n   /**\n    * \n    * @return list of users allowed to read from a drive or 'ffffffff-ffff-ffff-ffff-ffffffffffff'\n    *         for all users\n    */\n   public Set<String> getReaders() {\n      return readers;\n   }\n\n   /**\n    * \n    * @return size of drive in bytes\n    */\n   public long getSize() {\n      return size;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((claimType == null) ? 0 : claimType.hashCode());\n      result = prime * result + ((name == null) ? 0 : name.hashCode());\n      result = prime * result + ((readers == null) ? 0 : readers.hashCode());\n      result = prime * result + (int) (size ^ (size >>> 32));\n      result = prime * result + ((tags == null) ? 0 : tags.hashCode());\n      result = prime * result + ((userMetadata == null) ? 0 : userMetadata.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      Drive other = (Drive) obj;\n      if (claimType != other.claimType)\n         return false;\n      if (name == null) {\n         if (other.name != null)\n            return false;\n      } else if (!name.equals(other.name))\n         return false;\n      if (readers == null) {\n         if (other.readers != null)\n            return false;\n      } else if (!readers.equals(other.readers))\n         return false;\n      if (size != other.size)\n         return false;\n      if (tags == null) {\n         if (other.tags != null)\n            return false;\n      } else if (!tags.equals(other.tags))\n         return false;\n      if (userMetadata == null) {\n         if (other.userMetadata != null)\n            return false;\n      } else if (!userMetadata.equals(other.userMetadata))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"[uuid=\" + uuid + \", name=\" + name + \", tags=\" + tags + \", userMetadata=\" + userMetadata + \", size=\"\n            + size + \", claimType=\" + claimType + \", readers=\" + readers + \"]\";\n   }\n\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/domain/DriveData.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.domain;\n\nimport java.util.Map;\n\nimport org.jclouds.javax.annotation.Nullable;\n\n\npublic class DriveData extends Drive {\n   public static class Builder extends Drive.Builder {\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder claimType(ClaimType claimType) {\n         return Builder.class.cast(super.claimType(claimType));\n      }\n\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder name(String name) {\n         return Builder.class.cast(super.name(name));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder readers(Iterable<String> readers) {\n         return Builder.class.cast(super.readers(readers));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder size(long size) {\n         return Builder.class.cast(super.size(size));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder tags(Iterable<String> tags) {\n         return Builder.class.cast(super.tags(tags));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder userMetadata(Map<String, String> userMetadata) {\n         return Builder.class.cast(super.userMetadata(userMetadata));\n      }\n\n      public DriveData build() {\n         return new DriveData(uuid, name, size, claimType, readers, tags, userMetadata);\n      }\n   }\n\n   public DriveData(@Nullable String uuid, String name, long size, @Nullable ClaimType claimType, Iterable<String> readers,\n         Iterable<String> tags, Map<String, String> userMetadata) {\n      super(uuid, name, size, claimType, readers, tags, userMetadata);\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/domain/DriveInfo.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.collect.ImmutableSet;\n\npublic class DriveInfo extends Drive {\n   public static class Builder extends Drive.Builder {\n\n      protected DriveStatus status;\n      protected String user;\n      protected Set<String> claimed = ImmutableSet.of();\n      @Nullable\n      protected String encryptionCipher;\n      @Nullable\n      protected String imaging;\n      protected DriveMetrics metrics;\n\n      public Builder status(DriveStatus status) {\n         this.status = status;\n         return this;\n      }\n\n      public Builder user(String user) {\n         this.user = user;\n         return this;\n      }\n\n      public Builder claimed(Iterable<String> claimed) {\n         this.claimed = ImmutableSet.copyOf(checkNotNull(claimed, \"claimed\"));\n         return this;\n      }\n\n      public Builder imaging(String imaging) {\n         this.imaging = imaging;\n         return this;\n      }\n\n      public Builder metrics(DriveMetrics metrics) {\n         this.metrics = metrics;\n         return this;\n      }\n\n      public Builder encryptionCipher(String encryptionCipher) {\n         this.encryptionCipher = encryptionCipher;\n         return this;\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder claimType(ClaimType claimType) {\n         return Builder.class.cast(super.claimType(claimType));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder readers(Iterable<String> readers) {\n         return Builder.class.cast(super.readers(readers));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder size(long size) {\n         return Builder.class.cast(super.size(size));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder uuid(String uuid) {\n         return Builder.class.cast(super.uuid(uuid));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder name(String name) {\n         return Builder.class.cast(super.name(name));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder tags(Iterable<String> tags) {\n         return Builder.class.cast(super.tags(tags));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder userMetadata(Map<String, String> userMetadata) {\n         return Builder.class.cast(super.userMetadata(userMetadata));\n      }\n\n      public static Builder fromDriveInfo(DriveInfo driveInfo) {\n         return new Builder().uuid(driveInfo.getUuid()).name(driveInfo.getName()).size(driveInfo.getSize())\n               .claimType(driveInfo.getClaimType()).readers(driveInfo.getReaders()).tags(driveInfo.getTags())\n               .userMetadata(driveInfo.getUserMetadata()).status(driveInfo.getStatus()).user(driveInfo.getUser())\n               .claimed(driveInfo.getClaimed()).encryptionCipher(driveInfo.getEncryptionCipher())\n               .imaging(driveInfo.getImaging()).metrics(driveInfo.getMetrics());\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public DriveInfo build() {\n         return new DriveInfo(uuid, name, size, claimType, readers, tags, userMetadata, status, user, claimed,\n               encryptionCipher, imaging, metrics);\n      }\n\n   }\n\n   protected final DriveStatus status;\n   protected final String user;\n   protected final Set<String> claimed;\n   @Nullable\n   protected final String encryptionCipher;\n   @Nullable\n   protected final String imaging;\n   protected final DriveMetrics metrics;\n\n   public DriveInfo(String uuid, String name, long size, ClaimType claimType, Iterable<String> readers,\n         Iterable<String> tags, Map<String, String> userMetadata, DriveStatus status, String user, Set<String> claimed,\n         String encryptionCipher, String imaging, DriveMetrics metrics) {\n      super(uuid, name, size, claimType, readers, tags, userMetadata);\n      this.status = status;\n      this.user = user;\n      this.claimed = ImmutableSet.copyOf(checkNotNull(claimed, \"claimed\"));\n      this.encryptionCipher = encryptionCipher;\n      this.imaging = imaging;\n      this.metrics = checkNotNull(metrics, \"metrics\");\n   }\n\n   /**\n    * \n    * @return current status of the drive\n    */\n   public DriveStatus getStatus() {\n      return status;\n   }\n\n   /**\n    * \n    * @return owner of the drive\n    */\n   public String getUser() {\n      return user;\n   }\n\n   /**\n    * \n    * @return if drive is in use by a server, values are the server uuids\n    */\n   public Set<String> getClaimed() {\n      return claimed;\n   }\n\n   /**\n    * \n    * @return either 'none' or 'aes-xts-plain' (the default)\n    */\n   @Nullable\n   public String getEncryptionCipher() {\n      return encryptionCipher;\n   }\n\n   /**\n    * \n    * @return percentage completed of drive imaging if this is underway, or 'queued' if waiting for\n    *         another imaging operation to complete first\n    */\n   public String getImaging() {\n      return imaging;\n   }\n\n   /**\n    * \n    * @return i/o and request metrics for read and write ops\n    */\n   public DriveMetrics getMetrics() {\n      return metrics;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = super.hashCode();\n      result = prime * result + ((claimed == null) ? 0 : claimed.hashCode());\n      result = prime * result + ((metrics == null) ? 0 : metrics.hashCode());\n      result = prime * result + ((encryptionCipher == null) ? 0 : encryptionCipher.hashCode());\n      result = prime * result + ((imaging == null) ? 0 : imaging.hashCode());\n      result = prime * result + ((status == null) ? 0 : status.hashCode());\n      result = prime * result + ((user == null) ? 0 : user.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (!super.equals(obj))\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      DriveInfo other = (DriveInfo) obj;\n      if (claimed == null) {\n         if (other.claimed != null)\n            return false;\n      } else if (!claimed.equals(other.claimed))\n         return false;\n      if (metrics == null) {\n         if (other.metrics != null)\n            return false;\n      } else if (!metrics.equals(other.metrics))\n         return false;\n      if (encryptionCipher == null) {\n         if (other.encryptionCipher != null)\n            return false;\n      } else if (!encryptionCipher.equals(other.encryptionCipher))\n         return false;\n      if (imaging == null) {\n         if (other.imaging != null)\n            return false;\n      } else if (!imaging.equals(other.imaging))\n         return false;\n      if (status != other.status)\n         return false;\n      if (user == null) {\n         if (other.user != null)\n            return false;\n      } else if (!user.equals(other.user))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"[size=\" + size + \", claimType=\" + claimType + \", readers=\" + readers + \", uuid=\" + uuid + \", name=\"\n            + name + \", tags=\" + tags + \", userMetadata=\" + userMetadata + \", status=\" + status + \", user=\" + user\n            + \", claimed=\" + claimed + \", encryptionCipher=\" + encryptionCipher + \", imaging=\" + imaging\n            + \", metrics=\" + metrics + \"]\";\n   }\n\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/domain/DriveMetrics.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.domain;\n\n\npublic class DriveMetrics {\n   public static class Builder {\n      protected long readBytes;\n      protected long readRequests;\n      protected long writeBytes;\n      protected long writeRequests;\n\n      public Builder readBytes(long readBytes) {\n         this.readBytes = readBytes;\n         return this;\n      }\n\n      public Builder readRequests(long readRequests) {\n         this.readRequests = readRequests;\n         return this;\n      }\n\n      public Builder writeBytes(long writeBytes) {\n         this.writeBytes = writeBytes;\n         return this;\n      }\n\n      public Builder writeRequests(long writeRequests) {\n         this.writeRequests = writeRequests;\n         return this;\n      }\n\n      public DriveMetrics build() {\n         return new DriveMetrics(readBytes, readRequests, writeBytes, writeRequests);\n      }\n   }\n\n   protected final long readBytes;\n   protected final long readRequests;\n   protected final long writeBytes;\n   protected final long writeRequests;\n\n   public DriveMetrics(long readBytes, long readRequests, long writeBytes, long writeRequests) {\n      this.readBytes = readBytes;\n      this.readRequests = readRequests;\n      this.writeBytes = writeBytes;\n      this.writeRequests = writeRequests;\n   }\n\n   /**\n    * \n    * @return Cumulative i/o byte/request count for each drive\n    */\n   public long getReadBytes() {\n      return readBytes;\n   }\n\n   /**\n    * \n    * @return Cumulative i/o byte/request count for each drive\n    */\n   public long getReadRequests() {\n      return readRequests;\n   }\n\n   /**\n    * \n    * @return Cumulative i/o byte/request count for each drive\n    */\n   public long getWriteBytes() {\n      return writeBytes;\n   }\n\n   /**\n    * \n    * @return Cumulative i/o byte/request count for each drive\n    */\n   public long getWriteRequests() {\n      return writeRequests;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + (int) (readBytes ^ (readBytes >>> 32));\n      result = prime * result + (int) (readRequests ^ (readRequests >>> 32));\n      result = prime * result + (int) (writeBytes ^ (writeBytes >>> 32));\n      result = prime * result + (int) (writeRequests ^ (writeRequests >>> 32));\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      DriveMetrics other = (DriveMetrics) obj;\n      if (readBytes != other.readBytes)\n         return false;\n      if (readRequests != other.readRequests)\n         return false;\n      if (writeBytes != other.writeBytes)\n         return false;\n      if (writeRequests != other.writeRequests)\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"[readBytes=\" + readBytes + \", readRequests=\" + readRequests + \", writeBytes=\" + writeBytes\n            + \", writeRequests=\" + writeRequests + \"]\";\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/domain/DriveStatus.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\npublic enum DriveStatus {\n   ACTIVE, INACTIVE, COPYING, IMAGING, UNRECOGNIZED;\n\n   public String value() {\n      return name().toLowerCase();\n   }\n\n   @Override\n   public String toString() {\n      return value();\n   }\n\n   public static DriveStatus fromValue(String status) {\n      try {\n         return valueOf(checkNotNull(status, \"status\").toUpperCase());\n      } catch (IllegalArgumentException e) {\n         return UNRECOGNIZED;\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/domain/IDEDevice.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.domain;\n\nimport static com.google.common.base.Preconditions.checkArgument;\n\npublic class IDEDevice extends Device {\n   public static class Builder extends Device.Builder {\n      private final int bus;\n      private final int unit;\n\n      public Builder(int bus, int unit) {\n         this.bus = bus;\n         this.unit = unit;\n      }\n\n      @Override\n      public Device build() {\n         return new IDEDevice(uuid, mediaType, bus, unit);\n      }\n\n   }\n\n   private final int bus;\n   private final int unit;\n\n   public IDEDevice(String driveUuid, MediaType mediaType, int bus, int unit) {\n      super(driveUuid, mediaType);\n      checkArgument(bus == 0 || bus == 1, \"bus must be 0 or 1\");\n      checkArgument(unit == 0 || unit == 1, \"unit must be 0 or 1\");\n      this.bus = bus;\n      this.unit = unit;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + bus;\n      result = prime * result + unit;\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      IDEDevice other = (IDEDevice) obj;\n      if (bus != other.bus)\n         return false;\n      if (unit != other.unit)\n         return false;\n      return true;\n   }\n\n   @Override\n   public String getId() {\n      return String.format(\"ide:%d:%d\", bus, unit);\n   }\n\n   public int getBus() {\n      return bus;\n   }\n\n   public int getUnit() {\n      return unit;\n   }\n\n   @Override\n   public String toString() {\n      return \"[id=\" + getId() + \", driveUuid=\" + driveUuid + \", mediaType=\" + mediaType + \"]\";\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/domain/ImageConversionType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\npublic enum ImageConversionType {\n   GZIP, GUNZIP, UNRECOGNIZED;\n\n   public String value() {\n      return name().toLowerCase();\n   }\n\n   @Override\n   public String toString() {\n      return value();\n   }\n\n   public static ImageConversionType fromValue(String type) {\n      try {\n         return valueOf(checkNotNull(type, \"type\").toUpperCase());\n      } catch (IllegalArgumentException e) {\n         return UNRECOGNIZED;\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/domain/Item.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\n\npublic class Item {\n   public static class Builder {\n      protected String uuid;\n      protected String name;\n      protected Set<String> tags = ImmutableSet.of();\n      protected Map<String, String> userMetadata = ImmutableMap.of();\n\n      public Builder uuid(String uuid) {\n         this.uuid = uuid;\n         return this;\n      }\n\n      public Builder name(String name) {\n         this.name = name;\n         return this;\n      }\n\n      public Builder tags(Iterable<String> tags) {\n         this.tags = ImmutableSet.copyOf(checkNotNull(tags, \"tags\"));\n         return this;\n      }\n\n      public Builder userMetadata(Map<String, String> userMetadata) {\n         this.userMetadata = ImmutableMap.copyOf(checkNotNull(userMetadata, \"userMetadata\"));\n         return this;\n      }\n\n      public Item build() {\n         return new Item(uuid, name, tags, userMetadata);\n      }\n\n      @Override\n      public int hashCode() {\n         final int prime = 31;\n         int result = 1;\n         result = prime * result + ((name == null) ? 0 : name.hashCode());\n         result = prime * result + ((tags == null) ? 0 : tags.hashCode());\n         result = prime * result + ((userMetadata == null) ? 0 : userMetadata.hashCode());\n         result = prime * result + ((uuid == null) ? 0 : uuid.hashCode());\n         return result;\n      }\n\n      @Override\n      public boolean equals(Object obj) {\n         if (this == obj)\n            return true;\n         if (obj == null)\n            return false;\n         if (getClass() != obj.getClass())\n            return false;\n         Builder other = (Builder) obj;\n         if (name == null) {\n            if (other.name != null)\n               return false;\n         } else if (!name.equals(other.name))\n            return false;\n         if (tags == null) {\n            if (other.tags != null)\n               return false;\n         } else if (!tags.equals(other.tags))\n            return false;\n         if (userMetadata == null) {\n            if (other.userMetadata != null)\n               return false;\n         } else if (!userMetadata.equals(other.userMetadata))\n            return false;\n         if (uuid == null) {\n            if (other.uuid != null)\n               return false;\n         } else if (!uuid.equals(other.uuid))\n            return false;\n         return true;\n      }\n   }\n\n   @Nullable\n   protected final String uuid;\n   protected final String name;\n   protected final Set<String> tags;\n   protected final Map<String, String> userMetadata;\n\n   public Item(@Nullable String uuid, String name, Iterable<String> tags, Map<String, String> userMetadata) {\n      this.uuid = uuid;\n      this.name = checkNotNull(name, \"name\");\n      this.tags = ImmutableSet.copyOf(checkNotNull(tags, \"tags\"));\n      this.userMetadata = ImmutableMap.copyOf(checkNotNull(userMetadata, \"userMetadata\"));\n   }\n\n   /**\n    * \n    * @return uuid of the item.\n    */\n   @Nullable\n   public String getUuid() {\n      return uuid;\n   }\n\n   /**\n    * \n    * @return name of the item\n    */\n   public String getName() {\n      return name;\n   }\n\n   /**\n    * \n    * @return list of tags\n    */\n   public Set<String> getTags() {\n      return tags;\n   }\n\n   /**\n    * \n    * @return user-defined KEY VALUE pairs\n    */\n   public Map<String, String> getUserMetadata() {\n      return userMetadata;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((name == null) ? 0 : name.hashCode());\n      result = prime * result + ((tags == null) ? 0 : tags.hashCode());\n      result = prime * result + ((userMetadata == null) ? 0 : userMetadata.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      Item other = (Item) obj;\n      if (name == null) {\n         if (other.name != null)\n            return false;\n      } else if (!name.equals(other.name))\n         return false;\n      if (tags == null) {\n         if (other.tags != null)\n            return false;\n      } else if (!tags.equals(other.tags))\n         return false;\n      if (userMetadata == null) {\n         if (other.userMetadata != null)\n            return false;\n      } else if (!userMetadata.equals(other.userMetadata))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"[uuid=\" + uuid + \", name=\" + name + \", tags=\" + tags + \", userMetadata=\" + userMetadata + \"]\";\n   }\n\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/domain/MediaType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\n/**\n * Media type - set to 'cdrom' to simulate a cdrom, set to 'disk' or leave unset to simulate a hard\n * disk.\n */\npublic enum MediaType {\n   DISK, CDROM, UNRECOGNIZED;\n\n   public String value() {\n      return name().toLowerCase();\n   }\n\n   @Override\n   public String toString() {\n      return value();\n   }\n\n   public static MediaType fromValue(String type) {\n      try {\n         return valueOf(checkNotNull(type, \"type\").toUpperCase());\n      } catch (IllegalArgumentException e) {\n         return UNRECOGNIZED;\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/domain/Model.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\npublic enum Model {\n   E1000, RTl8139, VIRTIO, UNRECOGNIZED;\n\n   public String value() {\n      return name().toLowerCase();\n   }\n\n   @Override\n   public String toString() {\n      return value();\n   }\n\n   public static Model fromValue(String model) {\n      try {\n         return valueOf(checkNotNull(model, \"model\").toUpperCase());\n      } catch (IllegalArgumentException e) {\n         return UNRECOGNIZED;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/domain/NIC.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.collect.ImmutableSet;\n\npublic class NIC {\n   public static class Builder {\n      private String dhcp;\n      private Model model;\n      private String vlan;\n      private String mac;\n      // TODO elasticstack specific\n      private Set<String> block = ImmutableSet.of();\n\n      public Builder dhcp(String dhcp) {\n         this.dhcp = dhcp;\n         return this;\n      }\n\n      public Builder model(Model model) {\n         this.model = model;\n         return this;\n      }\n\n      public Builder vlan(String vlan) {\n         this.vlan = vlan;\n         return this;\n      }\n\n      public Builder mac(String mac) {\n         this.mac = mac;\n         return this;\n      }\n\n      public Builder block(Iterable<String> block) {\n         this.block = ImmutableSet.copyOf(checkNotNull(block, \"block\"));\n         return this;\n      }\n\n      public NIC build() {\n         return new NIC(dhcp, model, vlan, mac, block);\n      }\n   }\n\n   private final String dhcp;\n   private final Model model;\n   private final String vlan;\n   private final String mac;\n   private final Set<String> block;\n\n   public NIC(@Nullable String dhcp, Model model, @Nullable String vlan, @Nullable String mac, Iterable<String> block) {\n      this.dhcp = dhcp;\n      this.model = checkNotNull(model, \"model\");\n      this.vlan = vlan;\n      this.mac = mac;\n      this.block = ImmutableSet.copyOf(checkNotNull(block, \"block\"));\n   }\n\n   /**\n    * \n    * @return The IP address offered by DHCP to network interface 0. If unset, no address is\n    *         offered. Set to 'auto' to allocate a temporary IP at boot.\n    */\n   public String getDhcp() {\n      return dhcp;\n   }\n\n   /**\n    * \n    * @return Create network interface with given type (use 'e1000' as default value; 'rtl8139' or\n    *         'virtio' are also available).\n    */\n   public Model getModel() {\n      return model;\n   }\n\n   /**\n    * \n    * @return The VLAN to which the network interface is attached.\n    */\n   public String getVlan() {\n      return vlan;\n   }\n\n   /**\n    * \n    * @return The MAC address of the network interface. If unset, a randomly generated address is\n    *         used. If set, should be unique on the VLAN.\n    */\n   public String getMac() {\n      return mac;\n   }\n\n   // TODO undocumented\n   public Set<String> getBlock() {\n      return block;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((block == null) ? 0 : block.hashCode());\n      result = prime * result + ((dhcp == null) ? 0 : dhcp.hashCode());\n      result = prime * result + ((mac == null) ? 0 : mac.hashCode());\n      result = prime * result + ((model == null) ? 0 : model.hashCode());\n      result = prime * result + ((vlan == null) ? 0 : vlan.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      NIC other = (NIC) obj;\n      if (block == null) {\n         if (other.block != null)\n            return false;\n      } else if (!block.equals(other.block))\n         return false;\n      if (dhcp == null) {\n         if (other.dhcp != null)\n            return false;\n      } else if (!dhcp.equals(other.dhcp))\n         return false;\n      if (mac == null) {\n         if (other.mac != null)\n            return false;\n      } else if (!mac.equals(other.mac))\n         return false;\n      if (model != other.model)\n         return false;\n      if (vlan == null) {\n         if (other.vlan != null)\n            return false;\n      } else if (!vlan.equals(other.vlan))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"[dhcp=\" + dhcp + \", model=\" + model + \", vlan=\" + vlan + \", mac=\" + mac + \", block=\" + block + \"]\";\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/domain/SCSIDevice.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.domain;\n\nimport static com.google.common.base.Preconditions.checkArgument;\n\npublic class SCSIDevice extends Device {\n   public static class Builder extends Device.Builder {\n      private final int unit;\n\n      public Builder(int unit) {\n         this.unit = unit;\n      }\n\n      @Override\n      public Device build() {\n         return new SCSIDevice(uuid, mediaType, unit);\n      }\n\n   }\n\n   private static final int bus = 0;\n   private final int unit;\n\n   public SCSIDevice(String driveUuid, MediaType mediaType, int unit) {\n      super(driveUuid, mediaType);\n      checkArgument(unit >= 0 && unit < 8, \"unit must be between 0 and 7\");\n      this.unit = unit;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + bus;\n      result = prime * result + unit;\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      SCSIDevice other = (SCSIDevice) obj;\n      if (unit != other.unit)\n         return false;\n      return true;\n   }\n\n   public int getBus() {\n      return bus;\n   }\n\n   public int getUnit() {\n      return unit;\n   }\n\n   @Override\n   public String getId() {\n      return String.format(\"scsi:%d:%d\", bus, unit);\n   }\n\n   @Override\n   public String toString() {\n      return \"[id=\" + getId() + \", driveUuid=\" + driveUuid + \", mediaType=\" + mediaType + \"]\";\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/domain/Server.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\n\npublic class Server extends Item {\n\n   public static class Builder extends Item.Builder {\n      protected int cpu;\n      protected Integer smp;\n      protected int mem;\n      protected boolean persistent;\n      protected Map<String, ? extends Device> devices = ImmutableMap.of();\n      protected Set<String> bootDeviceIds = ImmutableSet.of();\n      protected List<NIC> nics = ImmutableList.of();\n      protected VNC vnc;\n\n      public Builder cpu(int cpu) {\n         this.cpu = cpu;\n         return this;\n      }\n\n      public Builder smp(Integer smp) {\n         this.smp = smp;\n         return this;\n      }\n\n      public Builder mem(int mem) {\n         this.mem = mem;\n         return this;\n      }\n\n      public Builder persistent(boolean persistent) {\n         this.persistent = persistent;\n         return this;\n      }\n\n      public Builder devices(Map<String, ? extends Device> devices) {\n         this.devices = ImmutableMap.copyOf(checkNotNull(devices, \"devices\"));\n         return this;\n      }\n\n      public Builder bootDeviceIds(Iterable<String> bootDeviceIds) {\n         this.bootDeviceIds = ImmutableSet.copyOf(checkNotNull(bootDeviceIds, \"bootDeviceIds\"));\n         return this;\n      }\n\n      public Builder nics(Iterable<NIC> nics) {\n         this.nics = ImmutableList.copyOf(checkNotNull(nics, \"nics\"));\n         return this;\n      }\n\n      public Builder vnc(VNC vnc) {\n         this.vnc = vnc;\n         return this;\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder uuid(String uuid) {\n         return Builder.class.cast(super.uuid(uuid));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder name(String name) {\n         return Builder.class.cast(super.name(name));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder tags(Iterable<String> tags) {\n         return Builder.class.cast(super.tags(tags));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder userMetadata(Map<String, String> userMetadata) {\n         return Builder.class.cast(super.userMetadata(userMetadata));\n      }\n\n      public Server build() {\n         return new Server(uuid, name, cpu, smp, mem, persistent, devices, bootDeviceIds, tags, userMetadata, nics, vnc);\n      }\n\n      public static Builder fromServer(Server in) {\n         return new Builder().uuid(in.getUuid()).name(in.getName()).cpu(in.getCpu()).mem(in.getMem())\n               .persistent(in.isPersistent()).devices(in.getDevices()).bootDeviceIds(in.getBootDeviceIds())\n               .tags(in.getTags()).userMetadata(in.getUserMetadata()).nics(in.getNics()).vnc(in.getVnc());\n      }\n   }\n\n   protected final int cpu;\n   protected final Integer smp;\n   protected final int mem;\n   protected final boolean persistent;\n   @Nullable\n   protected final Map<String, ? extends Device> devices;\n   protected final Set<String> bootDeviceIds;\n   protected final List<NIC> nics;\n   protected final VNC vnc;\n\n   public Server(@Nullable String uuid, String name, int cpu, @Nullable Integer smp, int mem, boolean persistent,\n         Map<String, ? extends Device> devices, Iterable<String> bootDeviceIds, Iterable<String> tags,\n         Map<String, String> userMetadata, Iterable<NIC> nics, VNC vnc) {\n      super(uuid, name, tags, userMetadata);\n      this.cpu = cpu;\n      this.smp = smp;\n      this.mem = mem;\n      this.persistent = persistent;\n      this.devices = ImmutableMap.copyOf(checkNotNull(devices, \"devices\"));\n      this.bootDeviceIds = ImmutableSet.copyOf(checkNotNull(bootDeviceIds, \"bootDeviceIds\"));\n      this.nics = ImmutableList.copyOf(checkNotNull(nics, \"nics\"));\n      this.vnc = checkNotNull(vnc, \"vnc\");\n   }\n\n   /**\n    * \n    * @return CPU quota in core MHz.\n    */\n   public int getCpu() {\n      return cpu;\n   }\n\n   /**\n    * \n    * @return number of virtual processors or null if calculated based on cpu.\n    */\n   public Integer getSmp() {\n      return smp;\n   }\n\n   /**\n    * \n    * @return virtual memory size in MB.\n    */\n   public int getMem() {\n      return mem;\n   }\n\n   /**\n    * \n    * @return 'true' means that server will revert to a 'stopped' status on server stop or shutdown,\n    *         rather than being destroyed automatically.\n    */\n   public boolean isPersistent() {\n      return persistent;\n   }\n\n   /**\n    * \n    * @return devices present, mapped by id\n    */\n   public Map<String, ? extends Device> getDevices() {\n      return devices;\n   }\n\n   /**\n    * \n    * @return ids of the devices to boot, e.g. ide:0:0 or ide:1:0\n    * @see Device#getId()\n    */\n   public Set<String> getBootDeviceIds() {\n      return bootDeviceIds;\n   }\n\n   public List<NIC> getNics() {\n      return nics;\n   }\n\n   public VNC getVnc() {\n      return vnc;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = super.hashCode();\n      result = prime * result + ((bootDeviceIds == null) ? 0 : bootDeviceIds.hashCode());\n      result = prime * result + cpu;\n      result = prime * result + ((devices == null) ? 0 : devices.hashCode());\n      result = prime * result + mem;\n      result = prime * result + ((nics == null) ? 0 : nics.hashCode());\n      result = prime * result + (persistent ? 1231 : 1237);\n      result = prime * result + ((smp == null) ? 0 : smp.hashCode());\n      result = prime * result + ((vnc == null) ? 0 : vnc.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (!super.equals(obj))\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      Server other = (Server) obj;\n      if (bootDeviceIds == null) {\n         if (other.bootDeviceIds != null)\n            return false;\n      } else if (!bootDeviceIds.equals(other.bootDeviceIds))\n         return false;\n      if (cpu != other.cpu)\n         return false;\n      if (devices == null) {\n         if (other.devices != null)\n            return false;\n      } else if (!devices.equals(other.devices))\n         return false;\n      if (mem != other.mem)\n         return false;\n      if (nics == null) {\n         if (other.nics != null)\n            return false;\n      } else if (!nics.equals(other.nics))\n         return false;\n      if (persistent != other.persistent)\n         return false;\n      if (smp == null) {\n         if (other.smp != null)\n            return false;\n      } else if (!smp.equals(other.smp))\n         return false;\n      if (vnc == null) {\n         if (other.vnc != null)\n            return false;\n      } else if (!vnc.equals(other.vnc))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"[uuid=\" + uuid + \", name=\" + name + \", tags=\" + tags + \", userMetadata=\" + userMetadata + \", cpu=\" + cpu\n            + \", smp=\" + smp + \", mem=\" + mem + \", persistent=\" + persistent + \", devices=\" + devices\n            + \", bootDeviceIds=\" + bootDeviceIds + \", nics=\" + nics + \", vnc=\" + vnc + \"]\";\n   }\n\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/domain/ServerInfo.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.domain;\n\nimport java.util.Date;\nimport java.util.Map;\n\nimport org.jclouds.javax.annotation.Nullable;\n\npublic class ServerInfo extends Server {\n\n   public static class Builder extends Server.Builder {\n      protected ServerStatus status;\n      protected Date started;\n      protected String user;\n      protected ServerMetrics metrics;\n\n      public Builder status(ServerStatus status) {\n         this.status = status;\n         return this;\n      }\n\n      public Builder started(Date started) {\n         this.started = started;\n         return this;\n      }\n\n      public Builder user(String user) {\n         this.user = user;\n         return this;\n      }\n\n      public Builder metrics(ServerMetrics metrics) {\n         this.metrics = metrics;\n         return this;\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder cpu(int cpu) {\n         return Builder.class.cast(super.cpu(cpu));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder smp(Integer smp) {\n         return Builder.class.cast(super.smp(smp));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder mem(int mem) {\n         return Builder.class.cast(super.mem(mem));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder persistent(boolean persistent) {\n         return Builder.class.cast(super.persistent(persistent));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder devices(Map<String, ? extends Device> devices) {\n         return Builder.class.cast(super.devices(devices));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder bootDeviceIds(Iterable<String> bootDeviceIds) {\n         return Builder.class.cast(super.bootDeviceIds(bootDeviceIds));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder nics(Iterable<NIC> nics) {\n         return Builder.class.cast(super.nics(nics));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder vnc(VNC vnc) {\n         return Builder.class.cast(super.vnc(vnc));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder uuid(String uuid) {\n         return Builder.class.cast(super.uuid(uuid));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder name(String name) {\n         return Builder.class.cast(super.name(name));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder tags(Iterable<String> tags) {\n         return Builder.class.cast(super.tags(tags));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder userMetadata(Map<String, String> userMetadata) {\n         return Builder.class.cast(super.userMetadata(userMetadata));\n      }\n\n      public ServerInfo build() {\n         return new ServerInfo(uuid, name, cpu, smp, mem, persistent, devices, bootDeviceIds, tags, userMetadata, nics,\n               vnc, status, started, user, metrics);\n      }\n   }\n\n   protected final ServerStatus status;\n   @Nullable\n   protected final Date started;\n   @Nullable\n   protected final String user;\n   protected final ServerMetrics metrics;\n\n   public ServerInfo(String uuid, String name, int cpu, Integer smp, int mem, boolean persistent,\n         Map<String, ? extends Device> devices, Iterable<String> bootDeviceIds, Iterable<String> tags,\n         Map<String, String> userMetadata, Iterable<NIC> nics, VNC vnc, ServerStatus status, Date started, String user,\n         @Nullable ServerMetrics metrics) {\n      super(uuid, name, cpu, smp, mem, persistent, devices, bootDeviceIds, tags, userMetadata, nics, vnc);\n      this.status = status;\n      this.started = started;\n      this.user = user;\n      this.metrics = metrics;\n   }\n\n   /**\n    * \n    * @return active | stopped | paused | dumped | dead\n    */\n   public ServerStatus getStatus() {\n      return status;\n   }\n\n   // TODO undocumented\n   public Date getStarted() {\n      return started;\n   }\n\n   /**\n    * \n    * @return metrics, if the server is running, or null\n    */\n   @Nullable\n   public ServerMetrics getMetrics() {\n      return metrics;\n   }\n\n   // TODO undocumented\n   /**\n    * \n    * @return owner of the server.\n    */\n   public String getUser() {\n      return user;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = super.hashCode();\n      result = prime * result + ((metrics == null) ? 0 : metrics.hashCode());\n      result = prime * result + ((started == null) ? 0 : started.hashCode());\n      result = prime * result + ((status == null) ? 0 : status.hashCode());\n      result = prime * result + ((user == null) ? 0 : user.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (!super.equals(obj))\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      ServerInfo other = (ServerInfo) obj;\n      if (metrics == null) {\n         if (other.metrics != null)\n            return false;\n      } else if (!metrics.equals(other.metrics))\n         return false;\n      if (started == null) {\n         if (other.started != null)\n            return false;\n      } else if (!started.equals(other.started))\n         return false;\n      if (status != other.status)\n         return false;\n      if (user == null) {\n         if (other.user != null)\n            return false;\n      } else if (!user.equals(other.user))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"[cpu=\" + cpu + \", smp=\" + smp + \", mem=\" + mem + \", persistent=\" + persistent + \", devices=\" + devices\n            + \", bootDeviceIds=\" + bootDeviceIds + \", nics=\" + nics + \", vnc=\" + vnc + \", uuid=\" + uuid + \", name=\"\n            + name + \", tags=\" + tags + \", userMetadata=\" + userMetadata + \", status=\" + status + \", started=\"\n            + started + \", user=\" + user + \", metrics=\" + metrics + \"]\";\n   }\n\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/domain/ServerMetrics.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\n\nimport com.google.common.collect.ImmutableMap;\n\npublic class ServerMetrics {\n\n   public static class Builder {\n      protected long txPackets;\n      protected long tx;\n      protected long rxPackets;\n      protected long rx;\n      protected Map<String, ? extends DriveMetrics> driveMetrics = ImmutableMap.<String, DriveMetrics> of();\n\n      public Builder txPackets(long txPackets) {\n         this.txPackets = txPackets;\n         return this;\n      }\n\n      public Builder tx(long tx) {\n         this.tx = tx;\n         return this;\n      }\n\n      public Builder rxPackets(long rxPackets) {\n         this.rxPackets = rxPackets;\n         return this;\n      }\n\n      public Builder rx(long rx) {\n         this.rx = rx;\n         return this;\n      }\n\n      public Builder driveMetrics(Map<String, ? extends DriveMetrics> driveMetrics) {\n         this.driveMetrics = ImmutableMap.copyOf(checkNotNull(driveMetrics, \"driveMetrics\"));\n         return this;\n      }\n\n      public ServerMetrics build() {\n         return new ServerMetrics(tx, txPackets, rx, rxPackets, driveMetrics);\n      }\n   }\n\n   protected final long txPackets;\n   protected final long tx;\n   protected final long rxPackets;\n   protected final long rx;\n   protected final Map<String, ? extends DriveMetrics> driveMetrics;\n\n   public ServerMetrics(long tx, long txPackets, long rx, long rxPackets, Map<String, ? extends DriveMetrics> driveMetrics) {\n      this.txPackets = txPackets;\n      this.tx = tx;\n      this.rxPackets = rxPackets;\n      this.rx = rx;\n      this.driveMetrics = ImmutableMap.copyOf(checkNotNull(driveMetrics, \"driveMetrics\"));\n   }\n\n   // TODO undocumented\n   public long getTxPackets() {\n      return txPackets;\n   }\n\n   // TODO undocumented\n   public long getTx() {\n      return tx;\n   }\n\n   // TODO undocumented\n   public long getRxPackets() {\n      return rxPackets;\n   }\n\n   // TODO undocumented\n   public long getRx() {\n      return rx;\n   }\n\n   /**\n    * \n    * @return metrics keyed on device id ex. {@code ide:0:0}\n    */\n   public Map<String, ? extends DriveMetrics> getDriveMetrics() {\n      return driveMetrics;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((driveMetrics == null) ? 0 : driveMetrics.hashCode());\n      result = prime * result + (int) (rx ^ (rx >>> 32));\n      result = prime * result + (int) (rxPackets ^ (rxPackets >>> 32));\n      result = prime * result + (int) (tx ^ (tx >>> 32));\n      result = prime * result + (int) (txPackets ^ (txPackets >>> 32));\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      ServerMetrics other = (ServerMetrics) obj;\n      if (driveMetrics == null) {\n         if (other.driveMetrics != null)\n            return false;\n      } else if (!driveMetrics.equals(other.driveMetrics))\n         return false;\n      if (rx != other.rx)\n         return false;\n      if (rxPackets != other.rxPackets)\n         return false;\n      if (tx != other.tx)\n         return false;\n      if (txPackets != other.txPackets)\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"[ txPackets=\" + txPackets + \", tx=\" + tx + \", rxPackets=\" + rxPackets + \", rx=\" + rx + \", driveMetrics=\"\n            + driveMetrics + \"]\";\n   }\n\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/domain/ServerStatus.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\npublic enum ServerStatus {\n   ACTIVE, STOPPED, PAUSED, DUMPED, DEAD, UNRECOGNIZED;\n   public String value() {\n      return name().toLowerCase();\n   }\n\n   @Override\n   public String toString() {\n      return value();\n   }\n\n   public static ServerStatus fromValue(String status) {\n      try {\n         return valueOf(checkNotNull(status, \"status\").toUpperCase());\n      } catch (IllegalArgumentException e) {\n         return UNRECOGNIZED;\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/domain/StandardDrive.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\n\nimport org.jclouds.javax.annotation.Nullable;\n\npublic class StandardDrive extends Drive {\n   public static class Builder extends Drive.Builder {\n\n      protected ImageConversionType format;\n      protected MediaType media;\n      protected long rawSize;\n\n      public Builder format(ImageConversionType format) {\n         this.format = format;\n         return this;\n      }\n\n      public Builder media(MediaType media) {\n         this.media = media;\n         return this;\n      }\n\n      public Builder rawSize(long rawSize) {\n         this.rawSize = rawSize;\n         return this;\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder claimType(ClaimType claimType) {\n         return Builder.class.cast(super.claimType(claimType));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder readers(Iterable<String> readers) {\n         return Builder.class.cast(super.readers(readers));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder size(long size) {\n         return Builder.class.cast(super.size(size));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder uuid(String uuid) {\n         return Builder.class.cast(super.uuid(uuid));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder name(String name) {\n         return Builder.class.cast(super.name(name));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder tags(Iterable<String> tags) {\n         return Builder.class.cast(super.tags(tags));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder userMetadata(Map<String, String> userMetadata) {\n         return Builder.class.cast(super.userMetadata(userMetadata));\n      }\n\n      public static Builder fromDriveInfo(StandardDrive driveInfo) {\n         return new Builder().uuid(driveInfo.getUuid()).name(driveInfo.getName()).size(driveInfo.getSize())\n               .claimType(driveInfo.getClaimType()).readers(driveInfo.getReaders()).tags(driveInfo.getTags())\n               .userMetadata(driveInfo.getUserMetadata()).media(driveInfo.getMedia());\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public StandardDrive build() {\n         return new StandardDrive(uuid, name, size, claimType, readers, tags, userMetadata, format, media, rawSize);\n      }\n\n   }\n\n   protected final ImageConversionType format;\n   protected final MediaType media;\n   protected final long rawSize;\n\n   public StandardDrive(String uuid, String name, long size, ClaimType claimType, Iterable<String> readers,\n         Iterable<String> tags, Map<String, String> userMetadata, @Nullable ImageConversionType format,\n         MediaType media, long rawSize) {\n      super(uuid, name, size, claimType, readers, tags, userMetadata);\n      this.format = format;\n      this.media = checkNotNull(media, \"media\");\n      this.rawSize = rawSize;\n   }\n\n   public MediaType getMedia() {\n      return media;\n   }\n   \n   public ImageConversionType getFormat() {\n      return format;\n   }\n\n   public long getRawSize() {\n      return rawSize;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = super.hashCode();\n      result = prime * result + ((format == null) ? 0 : format.hashCode());\n      result = prime * result + ((media == null) ? 0 : media.hashCode());\n      result = prime * result + (int) (rawSize ^ (rawSize >>> 32));\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (!super.equals(obj))\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      StandardDrive other = (StandardDrive) obj;\n      if (format != other.format)\n         return false;\n      if (media == null) {\n         if (other.media != null)\n            return false;\n      } else if (!media.equals(other.media))\n         return false;\n      if (rawSize != other.rawSize)\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"StandardDrive [format=\" + format + \", media=\" + media + \", rawSize=\" + rawSize + \", size=\" + size\n            + \", claimType=\" + claimType + \", readers=\" + readers + \", uuid=\" + uuid + \", name=\" + name + \", tags=\"\n            + tags + \", userMetadata=\" + userMetadata + \"]\";\n   }\n\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/domain/VNC.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.domain;\n\nimport org.jclouds.javax.annotation.Nullable;\n\npublic class VNC {\n   @Nullable\n   private final String ip;\n   @Nullable\n   private final String password;\n   private final boolean tls;\n\n   public VNC(String ip, String password, boolean tls) {\n      this.ip = ip;\n      this.password = password;\n      this.tls = tls;\n   }\n\n   /**\n    * \n    * @return IP address for overlay VNC access on port 5900. Set to 'auto', to reuse nic:0:dhcp if\n    *         available, or otherwise allocate a temporary IP at boot.\n    */\n   public String getIp() {\n      return ip;\n   }\n\n   /**\n    * \n    * @return Password for VNC access. If unset, VNC is disabled.\n    */\n   public String getPassword() {\n      return password;\n   }\n\n   /**\n    * \n    * @return Set to 'on' to require VeNCrypt-style TLS auth in addition to the password. If this is\n    *         unset, only unencrypted VNC is available.\n    */\n   public boolean isTls() {\n      return tls;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((ip == null) ? 0 : ip.hashCode());\n      result = prime * result + ((password == null) ? 0 : password.hashCode());\n      result = prime * result + (tls ? 1231 : 1237);\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      VNC other = (VNC) obj;\n      if (ip == null) {\n         if (other.ip != null)\n            return false;\n      } else if (!ip.equals(other.ip))\n         return false;\n      if (password == null) {\n         if (other.password != null)\n            return false;\n      } else if (!password.equals(other.password))\n         return false;\n      if (tls != other.tls)\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"[ip=\" + ip + \", password=\" + password + \", tls=\" + tls + \"]\";\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/domain/WellKnownImage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.domain;\n\nimport static com.google.common.base.MoreObjects.firstNonNull;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\npublic class WellKnownImage {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n      private String loginUser;\n      private String uuid;\n      private String description;\n      private OsFamily osFamily;\n      private String osVersion;\n      private int size;\n      private boolean is64bit;\n\n      public Builder loginUser(String loginUser) {\n         this.loginUser = loginUser;\n         return this;\n      }\n\n      public Builder uuid(String uuid) {\n         this.uuid = uuid;\n         return this;\n      }\n\n      public Builder description(String description) {\n         this.description = description;\n         return this;\n      }\n\n      public Builder osFamily(OsFamily osFamily) {\n         this.osFamily = osFamily;\n         return this;\n      }\n\n      public Builder osVersion(String osVersion) {\n         this.osVersion = osVersion;\n         return this;\n      }\n\n      public Builder size(int size) {\n         this.size = size;\n         return this;\n      }\n\n      public Builder is64bit(boolean is64bit) {\n         this.is64bit = is64bit;\n         return this;\n      }\n\n      public WellKnownImage build() {\n         return new WellKnownImage(loginUser, uuid, description, osFamily, osVersion, size, is64bit);\n      }\n   }\n\n   public static final String DEFAULT_USER = \"toor\";\n\n   private final String loginUser;\n   private final String uuid;\n   private final String description;\n   private final OsFamily osFamily;\n   private final String osVersion;\n   private final int size;\n   private final boolean is64bit;\n\n   public WellKnownImage(@Nullable String loginUser, String uuid, String description, OsFamily osFamily,\n         @Nullable String osVersion, int size, @Nullable Boolean is64bit) {\n      this.loginUser = firstNonNull(loginUser, DEFAULT_USER);\n      this.uuid = checkNotNull(uuid, \"uuid cannot be null\");\n      this.description = checkNotNull(description, \"description cannot be null\");\n      this.osFamily = checkNotNull(osFamily, \"osFamily cannot be null\");\n      this.osVersion = osVersion;\n      this.size = size;\n      this.is64bit = firstNonNull(is64bit, Boolean.TRUE);\n   }\n\n   public String getUuid() {\n      return uuid;\n   }\n\n   public String getDescription() {\n      return description;\n   }\n\n   public OsFamily getOsFamily() {\n      return osFamily;\n   }\n\n   public String getOsVersion() {\n      return osVersion;\n   }\n\n   public int getSize() {\n      return size;\n   }\n\n   public boolean is64bit() {\n      return is64bit;\n   }\n\n   public String getLoginUser() {\n      return loginUser;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(uuid, description, osFamily, osVersion, size, is64bit, loginUser);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (obj == null)\n         return false;\n      if (!(obj instanceof WellKnownImage)){\n         return false;\n      }\n      WellKnownImage that = (WellKnownImage) obj;\n      return Objects.equal(this.loginUser, that.loginUser)\n         && Objects.equal(this.uuid, that.uuid)\n         && Objects.equal(this.description, that.description)\n         && Objects.equal(this.osFamily, that.osFamily)\n         && Objects.equal(this.osVersion, that.osVersion)\n         && Objects.equal(this.size, that.size)\n         && Objects.equal(this.is64bit, that.is64bit);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"uuid\", uuid).add(\"description\", description)\n            .add(\"osFamily\", osFamily).add(\"osVersion\", osVersion).add(\"size\", size).add(\"is64bit\", is64bit)\n            .add(\"loginUser\", loginUser).toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/functions/BaseDriveToMap.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\nimport java.util.Map.Entry;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.elasticstack.domain.ClaimType;\nimport org.jclouds.elasticstack.domain.Drive;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Joiner;\nimport com.google.common.collect.ImmutableMap;\n\n@Singleton\npublic class BaseDriveToMap implements Function<Drive, Map<String, String>> {\n   @Override\n   public Map<String, String> apply(Drive from) {\n      checkNotNull(from, \"drive\");\n      ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();\n      builder.put(\"name\", from.getName());\n      builder.put(\"size\", from.getSize() + \"\");\n      if (from.getClaimType() != ClaimType.EXCLUSIVE)\n         builder.put(\"claim:type\", from.getClaimType().toString());\n      if (!from.getReaders().isEmpty())\n         builder.put(\"readers\", Joiner.on(' ').join(from.getReaders()));\n      if (!from.getTags().isEmpty())\n         builder.put(\"tags\", Joiner.on(' ').join(from.getTags()));\n      for (Entry<String, String> entry : from.getUserMetadata().entrySet())\n         builder.put(\"user:\" + entry.getKey(), entry.getValue());\n      return builder.build();\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/functions/CreateDriveRequestToMap.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.functions;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.elasticstack.domain.CreateDriveRequest;\nimport org.jclouds.elasticstack.domain.Drive;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Joiner;\nimport com.google.common.collect.ImmutableMap;\n\n@Singleton\npublic class CreateDriveRequestToMap implements Function<Drive, Map<String, String>> {\n   private final BaseDriveToMap baseDriveToMap;\n\n   @Inject\n   public CreateDriveRequestToMap(BaseDriveToMap baseDriveToMap) {\n      this.baseDriveToMap = baseDriveToMap;\n   }\n\n   @Override\n   public Map<String, String> apply(Drive from) {\n      ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();\n      builder.putAll(baseDriveToMap.apply(from));\n      if (from instanceof CreateDriveRequest) {\n         CreateDriveRequest create = CreateDriveRequest.class.cast(from);\n         if (!create.getAvoid().isEmpty())\n            builder.put(\"avoid\", Joiner.on(' ').join(create.getAvoid()));\n         if (create.getEncryptionCipher() != null)\n            builder.put(\"encryption:cipher\", create.getEncryptionCipher());\n      }\n      return builder.build();\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/functions/DriveDataToMap.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.functions;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.elasticstack.domain.DriveData;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableMap;\n\n@Singleton\npublic class DriveDataToMap implements Function<DriveData, Map<String, String>> {\n   private final BaseDriveToMap baseDriveToMap;\n\n   @Inject\n   public DriveDataToMap(BaseDriveToMap baseDriveToMap) {\n      this.baseDriveToMap = baseDriveToMap;\n   }\n\n   @Override\n   public Map<String, String> apply(DriveData from) {\n      ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();\n      builder.putAll(baseDriveToMap.apply(from));\n      return builder.build();\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/functions/KeyValuesDelimitedByBlankLinesToDriveInfo.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.functions;\n\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.elasticstack.domain.DriveInfo;\nimport org.jclouds.http.HttpResponse;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.Iterables;\n\n@Singleton\npublic class KeyValuesDelimitedByBlankLinesToDriveInfo implements Function<HttpResponse, DriveInfo> {\n   private final ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet setParser;\n\n   @Inject\n   public KeyValuesDelimitedByBlankLinesToDriveInfo(ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet setParser) {\n      this.setParser = setParser;\n   }\n\n   @Override\n   public DriveInfo apply(HttpResponse response) {\n      Set<DriveInfo> drives = setParser.apply(response);\n      if (drives.isEmpty())\n         return null;\n      return Iterables.get(drives, 0);\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/functions/KeyValuesDelimitedByBlankLinesToServerInfo.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.functions;\n\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.elasticstack.domain.ServerInfo;\nimport org.jclouds.http.HttpResponse;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.Iterables;\n\n@Singleton\npublic class KeyValuesDelimitedByBlankLinesToServerInfo implements Function<HttpResponse, ServerInfo> {\n   private final ListOfKeyValuesDelimitedByBlankLinesToServerInfoSet setParser;\n\n   @Inject\n   public KeyValuesDelimitedByBlankLinesToServerInfo(ListOfKeyValuesDelimitedByBlankLinesToServerInfoSet setParser) {\n      this.setParser = setParser;\n   }\n\n   @Override\n   public ServerInfo apply(HttpResponse response) {\n      Set<ServerInfo> drives = setParser.apply(response);\n      if (drives.isEmpty())\n         return null;\n      return Iterables.get(drives, 0);\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/functions/ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.functions;\n\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.elasticstack.domain.DriveInfo;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ReturnStringIf2xx;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\n\n@Singleton\npublic class ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet implements Function<HttpResponse, Set<DriveInfo>> {\n   private final ReturnStringIf2xx returnStringIf200;\n   private final ListOfKeyValuesDelimitedByBlankLinesToListOfMaps mapConverter;\n   private final MapToDriveInfo mapToDrive;\n\n   @Inject\n   ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet(ReturnStringIf2xx returnStringIf200,\n         ListOfKeyValuesDelimitedByBlankLinesToListOfMaps mapConverter, MapToDriveInfo mapToDrive) {\n      this.returnStringIf200 = returnStringIf200;\n      this.mapConverter = mapConverter;\n      this.mapToDrive = mapToDrive;\n   }\n\n   @Override\n   public Set<DriveInfo> apply(HttpResponse response) {\n      String text = returnStringIf200.apply(response);\n      if (text == null || text.trim().equals(\"\"))\n         return ImmutableSet.<DriveInfo> of();\n      return ImmutableSet.copyOf(Iterables.transform(mapConverter.apply(text), mapToDrive));\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/functions/ListOfKeyValuesDelimitedByBlankLinesToListOfMaps.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.functions;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport jakarta.inject.Singleton;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.Lists;\nimport com.google.common.collect.Maps;\n\n@Singleton\npublic class ListOfKeyValuesDelimitedByBlankLinesToListOfMaps implements Function<String, List<Map<String, String>>> {\n\n   @Override\n   public List<Map<String, String>> apply(String from) {\n      List<Map<String, String>> maps = Lists.newArrayList();\n      for (String listOfKeyValues : Splitter.on(\"\\n\\n\").split(from)) {\n         if (!\"\".equals(listOfKeyValues)) {\n            Map<String, String> map = Maps.newLinkedHashMap();\n            for (String keyValueLine : Splitter.on('\\n').split(listOfKeyValues)) {\n               if (!\"\".equals(keyValueLine)) {\n                  int firstIndex = keyValueLine.indexOf(' ');\n                  if (firstIndex != -1) {\n                     String key = keyValueLine.substring(0, firstIndex);\n                     String value = keyValueLine.substring(firstIndex + 1).replace(\"\\\\n\", \"\\n\");\n                     map.put(key, value);\n                  }\n               }\n            }\n            if (!map.isEmpty())\n               maps.add(map);\n         }\n      }\n      return maps;\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/functions/ListOfKeyValuesDelimitedByBlankLinesToServerInfoSet.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.functions;\n\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.elasticstack.domain.ServerInfo;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ReturnStringIf2xx;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\n\n@Singleton\npublic class ListOfKeyValuesDelimitedByBlankLinesToServerInfoSet implements Function<HttpResponse, Set<ServerInfo>> {\n   private final ReturnStringIf2xx returnStringIf200;\n   private final ListOfKeyValuesDelimitedByBlankLinesToListOfMaps mapConverter;\n   private final MapToServerInfo mapToServer;\n\n   @Inject\n   ListOfKeyValuesDelimitedByBlankLinesToServerInfoSet(ReturnStringIf2xx returnStringIf200,\n         ListOfKeyValuesDelimitedByBlankLinesToListOfMaps mapConverter, MapToServerInfo mapToServer) {\n      this.returnStringIf200 = returnStringIf200;\n      this.mapConverter = mapConverter;\n      this.mapToServer = mapToServer;\n   }\n\n   @Override\n   public Set<ServerInfo> apply(HttpResponse response) {\n      String text = returnStringIf200.apply(response);\n      if (text == null || text.trim().equals(\"\"))\n         return ImmutableSet.<ServerInfo> of();\n      return ImmutableSet.copyOf(Iterables.transform(mapConverter.apply(text), mapToServer));\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/functions/ListOfKeyValuesDelimitedByBlankLinesToStandardDriveSet.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Strings.nullToEmpty;\n\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.elasticstack.domain.StandardDrive;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ReturnStringIf2xx;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\n\n@Singleton\npublic class ListOfKeyValuesDelimitedByBlankLinesToStandardDriveSet implements Function<HttpResponse, Set<StandardDrive>> {\n   private final ReturnStringIf2xx returnStringIf2xx;\n   private final ListOfKeyValuesDelimitedByBlankLinesToListOfMaps mapConverter;\n   private final MapToStandardDrive mapToStandardDrive;\n\n   @Inject\n   ListOfKeyValuesDelimitedByBlankLinesToStandardDriveSet(ReturnStringIf2xx returnStringIf2xx,\n         ListOfKeyValuesDelimitedByBlankLinesToListOfMaps mapConverter, MapToStandardDrive mapToStandardDrive) {\n      this.returnStringIf2xx = checkNotNull(returnStringIf2xx, \"returnStringIf2xx\");\n      this.mapConverter = checkNotNull(mapConverter, \"mapConverter\");\n      this.mapToStandardDrive = checkNotNull(mapToStandardDrive, \"mapToStandardDrive\");\n   }\n\n   @Override\n   public Set<StandardDrive> apply(HttpResponse response) {\n      String text = nullToEmpty(returnStringIf2xx.apply(response));\n      if (text.trim().equals(\"\")) {\n         return ImmutableSet.<StandardDrive> of();\n      }\n      return ImmutableSet.copyOf(Iterables.transform(mapConverter.apply(text), mapToStandardDrive));\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/functions/ListOfMapsToListOfKeyValuesDelimitedByBlankLines.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.functions;\n\nimport java.util.Map;\n\nimport jakarta.inject.Singleton;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Joiner;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Maps;\n\n@Singleton\npublic class ListOfMapsToListOfKeyValuesDelimitedByBlankLines implements\n      Function<Iterable<Map<String, String>>, String> {\n\n   @Override\n   public String apply(Iterable<Map<String, String>> from) {\n      return Joiner.on(\"\\n\\n\").join(Iterables.transform(from, new Function<Map<String, String>, String>() {\n\n         @Override\n         public String apply(Map<String, String> from) {\n            return Joiner.on('\\n').withKeyValueSeparator(\" \")\n                  .join(Maps.transformValues(from, new Function<String, String>() {\n\n                     @Override\n                     public String apply(String from) {\n                        return from.replace(\"\\n\", \"\\\\n\");\n                     }\n\n                  }));\n         }\n\n      }));\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/functions/MapToDevices.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.functions;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.elasticstack.domain.BlockDevice;\nimport org.jclouds.elasticstack.domain.Device;\nimport org.jclouds.elasticstack.domain.IDEDevice;\nimport org.jclouds.elasticstack.domain.MediaType;\nimport org.jclouds.elasticstack.domain.SCSIDevice;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Maps;\nimport com.google.common.collect.ImmutableSet.Builder;\n\n@Singleton\npublic class MapToDevices implements Function<Map<String, String>, Map<String, ? extends Device>> {\n   @Singleton\n   public static class DeviceToId implements Function<Device, String> {\n      @Override\n      public String apply(Device input) {\n         return input.getId();\n      }\n   }\n\n   private final Function<Device, String> deviceToId;\n\n   @Inject\n   public MapToDevices(Function<Device, String> deviceToId) {\n      this.deviceToId = deviceToId;\n   }\n\n   public Map<String, ? extends Device> apply(Map<String, String> from) {\n      Builder<Device> devices = ImmutableSet.builder();\n      addIDEDevices(from, devices);\n      addSCSIDevices(from, devices);\n      addBlockDevices(from, devices);\n\n      return Maps.uniqueIndex(devices.build(), deviceToId);\n   }\n\n   protected void addBlockDevices(Map<String, String> from, Builder<Device> devices) {\n      BLOCK: for (int index : new int[] { 0, 1, 2, 3, 4, 5, 6, 7 }) {\n         String key = String.format(\"block:0:%d\", index);\n         if (!from.containsKey(key))\n            break BLOCK;\n         devices.add(populateBuilder(new BlockDevice.Builder(index), key, from).build());\n      }\n   }\n\n   protected void addSCSIDevices(Map<String, String> from, Builder<Device> devices) {\n      SCSI: for (int unit : new int[] { 0, 1, 2, 3, 4, 5, 6, 7 }) {\n         String key = String.format(\"scsi:0:%d\", unit);\n         if (!from.containsKey(key))\n            break SCSI;\n         devices.add(populateBuilder(new SCSIDevice.Builder(unit), key, from).build());\n      }\n   }\n\n   protected void addIDEDevices(Map<String, String> from, Builder<Device> devices) {\n      IDE: for (int bus : new int[] { 0, 1 })\n         for (int unit : new int[] { 0, 1 }) {\n            String key = String.format(\"ide:%d:%d\", bus, unit);\n            if (!from.containsKey(key))\n               break IDE;\n            devices.add(populateBuilder(new IDEDevice.Builder(bus, unit), key, from).build());\n         }\n   }\n\n   protected Device.Builder populateBuilder(Device.Builder deviceBuilder, String key, Map<String, String> from) {\n      deviceBuilder.uuid(from.get(key));\n      if (from.containsKey(key + \":media\"))\n         deviceBuilder.mediaType(MediaType.fromValue(from.get(key + \":media\")));\n      return deviceBuilder;\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/functions/MapToDriveInfo.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.functions;\n\nimport java.util.Map;\nimport java.util.Map.Entry;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.elasticstack.domain.ClaimType;\nimport org.jclouds.elasticstack.domain.DriveInfo;\nimport org.jclouds.elasticstack.domain.DriveMetrics;\nimport org.jclouds.elasticstack.domain.DriveStatus;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.Maps;\n\n@Singleton\npublic class MapToDriveInfo implements Function<Map<String, String>, DriveInfo> {\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   @Override\n   public DriveInfo apply(Map<String, String> from) {\n      if (from.isEmpty())\n         return null;\n      DriveInfo.Builder builder = new DriveInfo.Builder();\n      builder.name(from.get(\"name\"));\n      if (from.containsKey(\"tags\"))\n         builder.tags(Splitter.on(' ').split(from.get(\"tags\")));\n      if (from.containsKey(\"status\"))\n         builder.status(DriveStatus.fromValue(from.get(\"status\")));\n      builder.metrics(buildMetrics(from));\n      builder.user(from.get(\"user\"));\n      builder.encryptionCipher(from.get(\"encryption:cipher\"));\n      builder.uuid(from.get(\"drive\"));\n      if (from.containsKey(\"claim:type\"))\n         builder.claimType(ClaimType.fromValue(from.get(\"claim:type\")));\n      if (from.containsKey(\"claimed\"))\n         builder.claimed(Splitter.on(' ').split(from.get(\"claimed\")));\n      if (from.containsKey(\"readers\"))\n         builder.readers(Splitter.on(' ').split(from.get(\"readers\")));\n      if (from.containsKey(\"size\"))\n         builder.size(Long.parseLong(from.get(\"size\")));\n      Map<String, String> metadata = Maps.newLinkedHashMap();\n      for (Entry<String, String> entry : from.entrySet()) {\n         if (entry.getKey().startsWith(\"user:\"))\n            metadata.put(entry.getKey().substring(entry.getKey().indexOf(':') + 1), entry.getValue());\n      }\n      builder.userMetadata(metadata);\n      try {\n         return builder.build();\n      } catch (NullPointerException e) {\n         logger.warn(\"entry missing data: %s; %s\", e.getMessage(), from);\n         return null;\n      }\n   }\n\n   protected DriveMetrics buildMetrics(Map<String, String> from) {\n      DriveMetrics.Builder metricsBuilder = new DriveMetrics.Builder();\n      if (from.containsKey(\"read:bytes\"))\n         metricsBuilder.readBytes(Long.parseLong(from.get(\"read:bytes\")));\n      if (from.containsKey(\"read:requests\"))\n         metricsBuilder.readRequests(Long.parseLong(from.get(\"read:requests\")));\n      if (from.containsKey(\"write:bytes\"))\n         metricsBuilder.writeBytes(Long.parseLong(from.get(\"write:bytes\")));\n      if (from.containsKey(\"write:requests\"))\n         metricsBuilder.writeRequests(Long.parseLong(from.get(\"write:requests\")));\n      return metricsBuilder.build();\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/functions/MapToDriveMetrics.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.functions;\n\nimport java.util.Map;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.elasticstack.domain.DriveMetrics;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMap.Builder;\n\n@Singleton\npublic class MapToDriveMetrics implements Function<Map<String, String>, Map<String, ? extends DriveMetrics>> {\n\n   public Map<String, ? extends DriveMetrics> apply(Map<String, String> from) {\n      Builder<String, DriveMetrics> builder = ImmutableMap.builder();\n      addIDEDevices(from, builder);\n      addSCSIDevices(from, builder);\n      addBlockDevices(from, builder);\n      return builder.build();\n   }\n\n   protected void addBlockDevices(Map<String, String> from, Builder<String, DriveMetrics> devices) {\n      BLOCK: for (int index : new int[] { 0, 1, 2, 3, 4, 5, 6, 7 }) {\n         String key = String.format(\"block:0:%d\", index);\n         if (!from.containsKey(key))\n            break BLOCK;\n         devices.put(key, buildMetrics(key, from));\n      }\n   }\n\n   protected void addSCSIDevices(Map<String, String> from, Builder<String, DriveMetrics> devices) {\n      SCSI: for (int unit : new int[] { 0, 1, 2, 3, 4, 5, 6, 7 }) {\n         String key = String.format(\"scsi:0:%d\", unit);\n         if (!from.containsKey(key))\n            break SCSI;\n         devices.put(key, buildMetrics(key, from));\n      }\n   }\n\n   protected void addIDEDevices(Map<String, String> from, Builder<String, DriveMetrics> devices) {\n      IDE: for (int bus : new int[] { 0, 1 })\n         for (int unit : new int[] { 0, 1 }) {\n            String key = String.format(\"ide:%d:%d\", bus, unit);\n            if (!from.containsKey(key))\n               break IDE;\n            devices.put(key, buildMetrics(key, from));\n         }\n   }\n\n   protected DriveMetrics buildMetrics(String key, Map<String, String> from) {\n      DriveMetrics.Builder builder = new DriveMetrics.Builder();\n      if (from.containsKey(key + \":read:bytes\"))\n         builder.readBytes(Long.parseLong(from.get(key + \":read:bytes\")));\n      if (from.containsKey(key + \":read:requests\"))\n         builder.readRequests(Long.parseLong(from.get(key + \":read:requests\")));\n      if (from.containsKey(key + \":write:bytes\"))\n         builder.writeBytes(Long.parseLong(from.get(key + \":write:bytes\")));\n      if (from.containsKey(key + \":write:requests\"))\n         builder.writeRequests(Long.parseLong(from.get(key + \":write:requests\")));\n      return builder.build();\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/functions/MapToNICs.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.functions;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.elasticstack.domain.Model;\nimport org.jclouds.elasticstack.domain.NIC;\nimport org.jclouds.rest.annotations.ApiVersion;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.ImmutableList;\nimport com.google.inject.Inject;\n\n@Singleton\npublic class MapToNICs implements Function<Map<String, String>, List<NIC>> {\n\n   private String apiVersion;\n\n   @Inject\n   public MapToNICs(@ApiVersion String apiVersion) {\n      this.apiVersion = apiVersion;\n   }\n\n   @Override\n   public List<NIC> apply(Map<String, String> from) {\n      ImmutableList.Builder<NIC> nics = ImmutableList.builder();\n      NIC:\n      for (int id : new int[]{0, 1}) {\n         String key = String.format(\"nic:%d\", id);\n         if (!from.containsKey(key + \":model\"))\n            break NIC;\n\n         NIC.Builder nicBuilder = new NIC.Builder();\n         final String ip = getDhcpIp(from, key);\n         nicBuilder.dhcp(ip);\n         nicBuilder.model(Model.fromValue(from.get(key + \":model\")));\n         nicBuilder.vlan(from.get(key + \":vlan\"));\n         nicBuilder.mac(from.get(key + \":mac\"));\n         if (from.containsKey(key + \":block\"))\n            nicBuilder.block(Splitter.on(' ').split(from.get(key + \":block\")));\n         nics.add(nicBuilder.build());\n      }\n\n      return nics.build();\n   }\n\n   private String getDhcpIp(Map<String, String> from, String key) {\n      if (apiVersion.equals(\"2.0\")) {\n         final String ip = from.get(key + \":dhcp:ip\");\n         return ip == null ? \"auto\" : ip;\n      } else {\n         final String ip = from.get(key + \":dhcp\");\n         return ip == null ? \"auto\" : ip;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/functions/MapToServerInfo.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.functions;\n\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.elasticstack.domain.Device;\nimport org.jclouds.elasticstack.domain.NIC;\nimport org.jclouds.elasticstack.domain.ServerInfo;\nimport org.jclouds.elasticstack.domain.ServerMetrics;\nimport org.jclouds.elasticstack.domain.ServerStatus;\nimport org.jclouds.elasticstack.domain.VNC;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.Maps;\n\n@Singleton\npublic class MapToServerInfo implements Function<Map<String, String>, ServerInfo> {\n   private final Function<Map<String, String>, Map<String, ? extends Device>> mapToDevices;\n   private final Function<Map<String, String>, ServerMetrics> mapToMetrics;\n   private final Function<Map<String, String>, List<NIC>> mapToNICs;\n\n   @Inject\n   public MapToServerInfo(Function<Map<String, String>, Map<String, ? extends Device>> mapToDevices,\n                          Function<Map<String, String>, ServerMetrics> mapToMetrics, Function<Map<String, String>, List<NIC>> mapToNICs) {\n      this.mapToDevices = mapToDevices;\n      this.mapToMetrics = mapToMetrics;\n      this.mapToNICs = mapToNICs;\n   }\n\n   @Override\n   public ServerInfo apply(Map<String, String> from) {\n      if (from.isEmpty())\n         return null;\n      ServerInfo.Builder builder = new ServerInfo.Builder();\n      builder.name(from.get(\"name\"));\n      builder.persistent(Boolean.parseBoolean(from.get(\"persistent\")));\n      if (from.containsKey(\"tags\"))\n         builder.tags(Splitter.on(' ').split(from.get(\"tags\")));\n      if (from.containsKey(\"status\"))\n         builder.status(ServerStatus.fromValue(from.get(\"status\")));\n\n\n      if (from.containsKey(\"smp:cores\")) {\n            builder.smp(Integer.parseInt(from.get(\"smp:cores\")));\n      } else if (from.containsKey(\"smp\") && !\"auto\".equals(from.get(\"smp\"))) {\n            builder.smp(Integer.parseInt(from.get(\"smp\")));\n      }\n\n      builder.cpu(Integer.parseInt(from.get(\"cpu\")));\n      builder.mem(Integer.parseInt(from.get(\"mem\")));\n      builder.user(from.get(\"user\"));\n      if (from.containsKey(\"started\"))\n         builder.started(new Date(Long.parseLong(from.get(\"started\"))));\n      builder.uuid(from.get(\"server\"));\n      if (from.containsKey(\"boot\"))\n         builder.bootDeviceIds(Splitter.on(' ').split(from.get(\"boot\")));\n\n\n      builder.vnc(new VNC(from.get(\"vnc:ip\") == null ? \"auto\" : from.get(\"vnc:ip\"), from.get(\"password\"), from.containsKey(\"vnc:tls\")\n              && Boolean.valueOf(from.get(\"vnc:tls\"))));\n\n\n      Map<String, String> metadata = Maps.newLinkedHashMap();\n      for (Entry<String, String> entry : from.entrySet()) {\n         if (entry.getKey().startsWith(\"user:\"))\n            metadata.put(entry.getKey().substring(entry.getKey().indexOf(':') + 1), entry.getValue());\n      }\n      builder.userMetadata(metadata);\n      builder.nics(mapToNICs.apply(from));\n      builder.devices(mapToDevices.apply(from));\n      builder.metrics(mapToMetrics.apply(from));\n      return builder.build();\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/functions/MapToServerMetrics.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.functions;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.elasticstack.domain.DriveMetrics;\nimport org.jclouds.elasticstack.domain.ServerMetrics;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class MapToServerMetrics implements Function<Map<String, String>, ServerMetrics> {\n   private final Function<Map<String, String>, Map<String, ? extends DriveMetrics>> mapToDriveMetrics;\n\n   @Inject\n   public MapToServerMetrics(Function<Map<String, String>, Map<String, ? extends DriveMetrics>> mapToDriveMetrics) {\n      this.mapToDriveMetrics = mapToDriveMetrics;\n   }\n\n   public ServerMetrics apply(Map<String, String> from) {\n      ServerMetrics.Builder metricsBuilder = new ServerMetrics.Builder();\n      if (from.containsKey(\"tx:packets\"))\n         metricsBuilder.txPackets(Long.parseLong(from.get(\"tx:packets\")));\n      if (from.containsKey(\"tx\"))\n         metricsBuilder.tx(Long.parseLong(from.get(\"tx\")));\n      if (from.containsKey(\"rx:packets\"))\n         metricsBuilder.rxPackets(Long.parseLong(from.get(\"rx:packets\")));\n      if (from.containsKey(\"rx\"))\n         metricsBuilder.rx(Long.parseLong(from.get(\"rx\")));\n      metricsBuilder.driveMetrics(mapToDriveMetrics.apply(from));\n\n      ServerMetrics metrics = metricsBuilder.build();\n      return metrics;\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/functions/MapToStandardDrive.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.functions;\n\nimport java.util.Map;\nimport java.util.Map.Entry;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.elasticstack.domain.ClaimType;\nimport org.jclouds.elasticstack.domain.ImageConversionType;\nimport org.jclouds.elasticstack.domain.MediaType;\nimport org.jclouds.elasticstack.domain.StandardDrive;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.Maps;\n\n@Singleton\npublic class MapToStandardDrive implements Function<Map<String, String>, StandardDrive> {\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   @Override\n   public StandardDrive apply(Map<String, String> from) {\n      if (from.isEmpty())\n         return null;\n      StandardDrive.Builder builder = new StandardDrive.Builder();\n      builder.name(from.get(\"name\"));\n      builder.media(MediaType.fromValue(from.get(\"media\")));\n      if (from.containsKey(\"tags\"))\n         builder.tags(Splitter.on(' ').split(from.get(\"tags\")));\n      builder.uuid(from.get(\"drive\"));\n      if (from.containsKey(\"claim:type\"))\n         builder.claimType(ClaimType.fromValue(from.get(\"claim:type\")));\n      if (from.containsKey(\"readers\"))\n         builder.readers(Splitter.on(' ').split(from.get(\"readers\")));\n      if (from.containsKey(\"size\"))\n         builder.size(Long.parseLong(from.get(\"size\")));\n      if (from.containsKey(\"rawsize\"))\n         builder.rawSize(Long.parseLong(from.get(\"rawsize\")));\n      if (from.containsKey(\"format\"))\n         builder.format(ImageConversionType.fromValue(from.get(\"format\")));\n      Map<String, String> metadata = Maps.newLinkedHashMap();\n      for (Entry<String, String> entry : from.entrySet()) {\n         String key = entry.getKey();\n         if (key.startsWith(\"user:\"))\n            metadata.put(key.substring(key.indexOf(':') + 1), entry.getValue());\n      }\n      builder.userMetadata(metadata);\n      try {\n         return builder.build();\n      } catch (NullPointerException e) {\n         logger.warn(\"entry missing data: %s; %s\", e.getMessage(), from);\n         return null;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/functions/ReturnPayload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.functions;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.io.Payload;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class ReturnPayload implements Function<HttpResponse, Payload> {\n\n   public Payload apply(HttpResponse from) {\n      return from.getPayload();\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/functions/ServerToMap.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\nimport java.util.Map.Entry;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.elasticstack.domain.Device;\nimport org.jclouds.elasticstack.domain.NIC;\nimport org.jclouds.elasticstack.domain.Server;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.rest.annotations.ApiVersion;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Joiner;\nimport com.google.common.collect.ImmutableMap;\n\n@Singleton\npublic class ServerToMap implements Function<Server, Map<String, String>> {\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   @ApiVersion\n   private final String apiVersion;\n\n   @Inject\n   public ServerToMap(@ApiVersion String apiVersion) {\n      this.apiVersion = apiVersion;\n   }\n\n   @Override\n   public Map<String, String> apply(Server from) {\n      checkNotNull(from, \"server\");\n      ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();\n      builder.put(\"name\", from.getName());\n      builder.put(\"cpu\", from.getCpu() + \"\");\n      if (from.getSmp() != null)\n         builder.put(\"smp\", from.getSmp() + \"\");\n      else\n         builder.put(\"smp\", \"auto\");\n      builder.put(\"mem\", from.getMem() + \"\");\n      builder.put(\"persistent\", from.isPersistent() + \"\");\n      if (!from.getBootDeviceIds().isEmpty())\n         builder.put(\"boot\", Joiner.on(' ').join(from.getBootDeviceIds()));\n      for (Entry<String, ? extends Device> entry : from.getDevices().entrySet()) {\n         builder.put(entry.getKey(), entry.getValue().getDriveUuid());\n         builder.put(entry.getKey() + \":media\", entry.getValue().getMediaType().toString());\n      }\n      int nicId = 0;\n      for (NIC nic : from.getNics()) {\n         builder.put(\"nic:\" + nicId + \":model\", nic.getModel().toString());\n         if (nic.getDhcp() != null)\n            builder.put(\"nic:\" + nicId + \":dhcp\", nic.getDhcp());\n         if (nic.getVlan() != null)\n            builder.put(\"nic:\" + nicId + \":vlan\", nic.getVlan());\n         if (nic.getMac() != null)\n            logger.trace(\"setting mac on network interfaces not supported: %s\", nic);\n         nicId++;\n      }\n\n      String vncIp = from.getVnc().getIp();\n      if (apiVersion.equals(\"2.0\")) {\n         builder.put(\"vnc\", \"auto\");\n      } else {\n         builder.put(\"vnc:ip\", vncIp == null ? \"auto\" : vncIp);\n      }\n\n      if (from.getVnc().getPassword() != null)\n         builder.put(\"password\", from.getVnc().getPassword());\n      if (from.getVnc().isTls())\n         builder.put(\"vnc:tls\", \"on\");\n      if (!from.getTags().isEmpty())\n         builder.put(\"tags\", Joiner.on(' ').join(from.getTags()));\n      for (Entry<String, String> entry : from.getUserMetadata().entrySet())\n         builder.put(\"user:\" + entry.getKey(), entry.getValue());\n      return builder.build();\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/functions/SplitNewlines.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.functions;\n\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ReturnStringIf2xx;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.ImmutableSet;\n\n@Singleton\npublic class SplitNewlines implements Function<HttpResponse, Set<String>> {\n   private final ReturnStringIf2xx returnStringIf200;\n\n   @Inject\n   SplitNewlines(ReturnStringIf2xx returnStringIf200) {\n      this.returnStringIf200 = returnStringIf200;\n   }\n\n   @Override\n   public Set<String> apply(HttpResponse response) {\n      String payload = returnStringIf200.apply(response);\n      return payload == null ? ImmutableSet.<String> of() : ImmutableSet.copyOf(Splitter.on('\\n').omitEmptyStrings()\n            .split(payload));\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/handlers/ElasticStackErrorHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.handlers;\n\nimport static org.jclouds.http.HttpUtils.releasePayload;\nimport static org.jclouds.util.Closeables2.closeQuietly;\nimport static org.jclouds.util.Strings2.toStringAndClose;\n\nimport java.io.IOException;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.ResourceNotFoundException;\n\n/**\n * This will parse and set an appropriate exception on the command object.\n * \n * <p/>\n * Errors are returned with an appropriate HTTP status code, an X-Elastic- Error header specifying\n * the error type, and a text description in the HTTP body.\n */\n@Singleton\npublic class ElasticStackErrorHandler implements HttpErrorHandler {\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   public void handleError(HttpCommand command, HttpResponse response) {\n      // it is important to always read fully and close streams\n      String message = parseMessage(response);\n      Exception exception = message != null ? new HttpResponseException(command, response, message)\n            : new HttpResponseException(command, response);\n      try {\n         message = message != null ? message : String.format(\"%s -> %s\", command.getCurrentRequest().getRequestLine(),\n               response.getStatusLine());\n         switch (response.getStatusCode()) {\n         case 400:\n            if ((command.getCurrentRequest().getEndpoint().getPath().endsWith(\"/info\"))\n                  || (message != null && message.indexOf(\"could not be found\") != -1))\n               exception = new ResourceNotFoundException(message, exception);\n            else\n               exception = new IllegalArgumentException(message, exception);\n            break;\n         case 401:\n            exception = new AuthorizationException(message, exception);\n            break;\n         case 404:\n            if (!command.getCurrentRequest().getMethod().equals(\"DELETE\")) {\n               exception = new ResourceNotFoundException(message, exception);\n            }\n            break;\n         case 405:\n            exception = new IllegalArgumentException(message, exception);\n            break;\n         case 409:\n            exception = new IllegalStateException(message, exception);\n            break;\n         }\n      } finally {\n         closeQuietly(response.getPayload());\n         command.setException(exception);\n      }\n   }\n\n   public String parseMessage(HttpResponse response) {\n      if (response.getPayload() == null)\n         return null;\n      try {\n         return toStringAndClose(response.getPayload().openStream());\n      } catch (IOException e) {\n         throw new RuntimeException(e);\n      } finally {\n         releasePayload(response);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/predicates/DriveClaimed.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.elasticstack.ElasticStackApi;\nimport org.jclouds.elasticstack.domain.DriveInfo;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Predicate;\n\n@Singleton\npublic class DriveClaimed implements Predicate<DriveInfo> {\n\n   private final ElasticStackApi client;\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   @Inject\n   public DriveClaimed(ElasticStackApi client) {\n      this.client = client;\n   }\n\n   public boolean apply(DriveInfo drive) {\n      logger.trace(\"looking for claims on drive %s\", checkNotNull(drive, \"drive\"));\n      drive = refresh(drive);\n      if (drive == null)\n         return false;\n      logger.trace(\"%s: looking for drive claims: currently: %s\", drive.getUuid(), drive.getClaimed());\n      return !drive.getClaimed().isEmpty();\n   }\n\n   private DriveInfo refresh(DriveInfo drive) {\n      return client.getDriveInfo(drive.getUuid());\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/reference/ElasticStackConstants.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.reference;\n\n/**\n * Common constants used in ElasticStack provider\n */\npublic final class ElasticStackConstants {\n\n    /**\n     * default VNC password used on new machines\n     */\n    public static final String PROPERTY_VNC_PASSWORD = \"jclouds.elasticstack.vnc-password\";\n\n    private ElasticStackConstants() {\n        throw new AssertionError(\"intentionally unimplemented\");\n    }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/suppliers/StandardDiskImageSupplier.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.suppliers;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.List;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.elasticstack.ElasticStackApi;\nimport org.jclouds.elasticstack.domain.MediaType;\nimport org.jclouds.elasticstack.domain.StandardDrive;\nimport org.jclouds.elasticstack.domain.WellKnownImage;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Supplies the pre-installed images.\n */\n@Singleton\npublic class StandardDiskImageSupplier implements WellKnownImageSupplier {\n\n   private final ElasticStackApi api;\n\n   private final Function<StandardDrive, WellKnownImage> standardDriveToWellKnownImage;\n\n   @Inject\n   StandardDiskImageSupplier(ElasticStackApi api, Function<StandardDrive, WellKnownImage> standardDriveToWellKnownImage) {\n      this.api = checkNotNull(api, \"api\");\n      this.standardDriveToWellKnownImage = checkNotNull(standardDriveToWellKnownImage, \"standardDriveToWellKnownImage\");\n   }\n\n   @Override\n   public List<WellKnownImage> get() {\n      ImmutableList.Builder<WellKnownImage> images = ImmutableList.builder();\n      for (StandardDrive drive : api.listStandardDriveInfo()) {\n         if (drive.getMedia() == MediaType.DISK) {\n            images.add(standardDriveToWellKnownImage.apply(drive));\n         }\n      }\n      return images.build();\n   }\n\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/suppliers/WellKnownImageSupplier.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.suppliers;\n\nimport java.util.List;\n\nimport org.jclouds.elasticstack.domain.WellKnownImage;\n\nimport com.google.common.base.Supplier;\nimport com.google.inject.ImplementedBy;\n\n/**\n * Supplies the well known images\n */\n@ImplementedBy(StandardDiskImageSupplier.class)\npublic interface WellKnownImageSupplier extends Supplier<List<WellKnownImage>> {\n\n}\n"
  },
  {
    "path": "apis/elasticstack/src/main/java/org/jclouds/elasticstack/util/Servers.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.util;\n\nimport org.jclouds.elasticstack.domain.IDEDevice;\nimport org.jclouds.elasticstack.domain.Model;\nimport org.jclouds.elasticstack.domain.NIC;\nimport org.jclouds.elasticstack.domain.Server;\nimport org.jclouds.elasticstack.domain.VNC;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\n\npublic class Servers {\n   /**\n    * Helper to create a small persistent server\n    * \n    * @param name\n    *           what to name the server\n    * @param driveUuuid\n    *           id of the boot drive\n    * @param vncPassword\n    *           password for vnc\n    * @return a builder for a persistent 1Ghz 512m server with DHCP enabled network.\n    */\n   public static Server.Builder small(String name, String driveUuuid, String vncPassword) {\n      return new Server.Builder().name(name).cpu(1000).mem(512).persistent(true)\n            .devices(ImmutableMap.of(\"ide:0:0\", new IDEDevice.Builder(0, 0).uuid(driveUuuid).build()))\n            .bootDeviceIds(ImmutableSet.of(\"ide:0:0\"))\n            .nics(ImmutableSet.of(new NIC.Builder().model(Model.E1000).dhcp(\"auto\").build()))\n            .vnc(new VNC(null, vncPassword, false));\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/test/java/org/jclouds/elasticstack/ElasticStackApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack;\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static org.jclouds.util.Predicates2.retry;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.io.IOException;\nimport java.util.Set;\nimport java.util.logging.Logger;\n\nimport org.jclouds.compute.domain.ExecResponse;\nimport org.jclouds.compute.internal.BaseComputeServiceContextLiveTest;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.elasticstack.domain.ClaimType;\nimport org.jclouds.elasticstack.domain.CreateDriveRequest;\nimport org.jclouds.elasticstack.domain.DriveData;\nimport org.jclouds.elasticstack.domain.DriveInfo;\nimport org.jclouds.elasticstack.domain.DriveStatus;\nimport org.jclouds.elasticstack.domain.IDEDevice;\nimport org.jclouds.elasticstack.domain.ImageConversionType;\nimport org.jclouds.elasticstack.domain.Model;\nimport org.jclouds.elasticstack.domain.Server;\nimport org.jclouds.elasticstack.domain.ServerInfo;\nimport org.jclouds.elasticstack.domain.ServerStatus;\nimport org.jclouds.elasticstack.domain.StandardDrive;\nimport org.jclouds.elasticstack.predicates.DriveClaimed;\nimport org.jclouds.elasticstack.util.Servers;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.predicates.SocketOpen;\nimport org.jclouds.ssh.SshClient;\nimport org.jclouds.sshj.config.SshjSshClientModule;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.AfterGroups;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Predicates;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.net.HostAndPort;\nimport com.google.gson.Gson;\nimport com.google.inject.Guice;\n\n/**\n * Tests behavior of {@code ElasticStackApi}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"ElasticStackApiLiveTest\")\npublic class ElasticStackApiLiveTest extends BaseComputeServiceContextLiveTest {\n\n   public ElasticStackApiLiveTest() {\n      provider = \"elasticstack\";\n   }\n\n   protected long driveSize = 1 * 1024 * 1024 * 1024L;\n   protected int maxDriveImageTime = 360;\n   protected String vncPassword = \"Il0veVNC\";\n   protected ElasticStackApi client;\n   protected Predicate<HostAndPort> socketTester;\n   protected Predicate<DriveInfo> driveNotClaimed;\n   protected String imageId;\n\n   @Override\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   public void setupContext() {\n      super.setupContext();\n      imageId = view.getComputeService().templateBuilder().build().getImage().getId();\n         \n      client = view.utils().injector().getInstance(ElasticStackApi.class);\n      driveNotClaimed = retry(Predicates.not(new DriveClaimed(client)), maxDriveImageTime, 1, SECONDS);\n      SocketOpen socketOpen = context.utils().injector().getInstance(SocketOpen.class);\n      socketTester = retry(socketOpen, maxDriveImageTime, 1, SECONDS);\n   }\n   \n   @Test\n   public void testListServers() throws Exception {\n      Set<String> servers = client.listServers();\n      assertNotNull(servers);\n   }\n\n   @Test\n   public void testListServerInfo() throws Exception {\n      Set<? extends ServerInfo> servers = client.listServerInfo();\n      assertNotNull(servers);\n   }\n\n   @Test\n   public void testGetServer() throws Exception {\n      for (String serverUUID : client.listServers()) {\n         assert !\"\".equals(serverUUID);\n         assertNotNull(client.getServerInfo(serverUUID));\n      }\n   }\n\n   @Test\n   public void testListDrives() throws Exception {\n      Set<String> drives = client.listDrives();\n      assertNotNull(drives);\n   }\n   \n   @Test\n   public void testListStandardDrives() throws Exception {\n      Set<String> drives = client.listStandardDrives();\n      assertNotNull(drives);\n      assertFalse(drives.isEmpty(), \"standard drive list should not be empty\");\n   }\n\n   @Test\n   public void testListDriveInfo() throws Exception {\n      Set<? extends DriveInfo> drives = client.listDriveInfo();\n      assertNotNull(drives);\n   }\n   \n   @Test\n   public void testListStandardDriveInfo() throws Exception {\n      Set<? extends StandardDrive> drives = client.listStandardDriveInfo();\n      assertNotNull(drives);\n      assertFalse(drives.isEmpty(), \"standard drive list should not be empty\");\n   }\n\n   @Test\n   public void testGetDrive() throws Exception {\n      for (String driveUUID : client.listDrives()) {\n         assert !\"\".equals(driveUUID) : driveUUID;\n         assert client.getDriveInfo(driveUUID) != null : driveUUID;\n      }\n   }\n\n   protected String prefix = System.getProperty(\"user.name\") + \".test\";\n   protected DriveInfo drive;\n\n   @Test\n   public void testCreateDrive() throws Exception {\n      drive = client.createDrive(new CreateDriveRequest.Builder().name(prefix).size(driveSize).build());\n      checkCreatedDrive();\n\n      DriveInfo newInfo = client.getDriveInfo(drive.getUuid());\n      checkDriveMatchesGet(newInfo);\n\n   }\n\n   protected void checkDriveMatchesGet(DriveInfo newInfo) {\n      assertEquals(newInfo.getUuid(), drive.getUuid());\n   }\n\n   protected void checkCreatedDrive() {\n      assertNotNull(drive.getUuid());\n      assertNotNull(drive.getUser());\n      assertEquals(drive.getName(), prefix);\n      assertEquals(drive.getSize(), driveSize);\n      assertEquals(drive.getStatus(), DriveStatus.ACTIVE);\n      // for some reason, these occasionally return as 4096,1\n      // assertEquals(info.getReadBytes(), 0L);\n      // assertEquals(info.getWriteBytes(), 0L);\n      // assertEquals(info.getReadRequests(), 0L);\n      // assertEquals(info.getWriteRequests(), 0L);\n      assertEquals(drive.getEncryptionCipher(), \"aes-xts-plain\");\n   }\n\n   @Test(dependsOnMethods = \"testCreateDrive\")\n   public void testSetDriveData() throws Exception {\n\n      DriveInfo drive2 = client.setDriveData(drive.getUuid(), new DriveData.Builder().claimType(ClaimType.SHARED).name(\n               \"rediculous\").readers(ImmutableSet.of(\"ffffffff-ffff-ffff-ffff-ffffffffffff\")).tags(\n               ImmutableSet.of(\"networking\", \"security\", \"gateway\")).userMetadata(ImmutableMap.of(\"foo\", \"bar\"))\n               .build());\n\n      assertNotNull(drive2.getUuid(), drive.getUuid());\n      assertEquals(drive2.getName(), \"rediculous\");\n      assertEquals(drive2.getClaimType(), ClaimType.SHARED);\n      assertEquals(drive2.getReaders(), ImmutableSet.of(\"ffffffff-ffff-ffff-ffff-ffffffffffff\"));\n      assertEquals(drive2.getTags(), ImmutableSet.of(\"networking\", \"security\", \"gateway\"));\n      assertEquals(drive2.getUserMetadata(), ImmutableMap.of(\"foo\", \"bar\"));\n      drive = drive2;\n   }\n\n   protected ServerInfo server;\n\n   @Test(dependsOnMethods = \"testSetDriveData\")\n   public void testCreateAndStartServer() throws Exception {\n      Logger.getAnonymousLogger().info(\"preparing drive\");\n      prepareDrive();\n\n      Server serverRequest = Servers.small(prefix, drive.getUuid(), vncPassword).build();\n\n      Logger.getAnonymousLogger().info(\"starting server\");\n      server = client.createServer(serverRequest);\n      client.startServer(server.getUuid());\n      server = client.getServerInfo(server.getUuid());\n      checkStartedServer();\n\n      Server newInfo = client.getServerInfo(server.getUuid());\n      checkServerMatchesGet(newInfo);\n\n   }\n\n   protected void checkServerMatchesGet(Server newInfo) {\n      assertEquals(newInfo.getUuid(), server.getUuid());\n   }\n\n   protected void checkStartedServer() {\n      System.out.println(new Gson().toJson(server));\n      assertNotNull(server.getUuid());\n      assertNotNull(server.getUser());\n      assertEquals(server.getName(), prefix);\n      assertEquals(server.isPersistent(), true);\n      assertEquals(server.getDevices(), ImmutableMap.of(\"ide:0:0\", new IDEDevice.Builder(0, 0).uuid(drive.getUuid())\n               .build()));\n      assertEquals(server.getBootDeviceIds(), ImmutableSet.of(\"ide:0:0\"));\n      assertEquals(server.getNics().get(0).getDhcp(), server.getVnc().getIp());\n      assertEquals(server.getNics().get(0).getModel(), Model.E1000);\n      assertEquals(server.getStatus(), ServerStatus.ACTIVE);\n   }\n\n   @Test(dependsOnMethods = \"testCreateAndStartServer\")\n   public void testConnectivity() throws Exception {\n      HostAndPort vncsocket = HostAndPort.fromParts(server.getVnc().getIp(), 5900);\n      Logger.getAnonymousLogger().info(\"awaiting vnc: \" + vncsocket);\n      assert socketTester.apply(vncsocket) : server;\n      HostAndPort sshsocket = HostAndPort.fromParts(server.getNics().get(0).getDhcp(), 22);\n      Logger.getAnonymousLogger().info(\"awaiting ssh: \" + sshsocket);\n      assert socketTester.apply(sshsocket) : server;\n      doConnectViaSsh(server, getSshCredentials(server));\n   }\n\n   @Test(dependsOnMethods = \"testConnectivity\")\n   public void testLifeCycle() throws Exception {\n      client.stopServer(server.getUuid());\n      assertEquals(client.getServerInfo(server.getUuid()).getStatus(), ServerStatus.STOPPED);\n\n      client.startServer(server.getUuid());\n      assertEquals(client.getServerInfo(server.getUuid()).getStatus(), ServerStatus.ACTIVE);\n\n      client.resetServer(server.getUuid());\n      assertEquals(client.getServerInfo(server.getUuid()).getStatus(), ServerStatus.ACTIVE);\n\n      client.shutdownServer(server.getUuid());\n      // behavior on shutdown depends on how your server OS is set up to respond to an ACPI power\n      // button signal\n      assert client.getServerInfo(server.getUuid()).getStatus() == ServerStatus.ACTIVE || client.getServerInfo(\n               server.getUuid()).getStatus() == ServerStatus.STOPPED;\n   }\n\n   @Test(dependsOnMethods = \"testLifeCycle\")\n   public void testSetServerConfiguration() throws Exception {\n      client.stopServer(server.getUuid());\n      assertEquals(client.getServerInfo(server.getUuid()).getStatus(), ServerStatus.STOPPED);\n\n      ServerInfo server2 = client.setServerConfiguration(server.getUuid(), Server.Builder.fromServer(server).name(\n               \"rediculous\").tags(ImmutableSet.of(\"networking\", \"security\", \"gateway\")).userMetadata(\n               ImmutableMap.of(\"foo\", \"bar\")).build());\n\n      assertNotNull(server2.getUuid(), server.getUuid());\n      assertEquals(server2.getName(), \"rediculous\");\n      checkTagsAndMetadata(server2);\n      server = server2;\n   }\n\n   protected void checkTagsAndMetadata(ServerInfo server2) {\n      assertEquals(server2.getTags(), ImmutableSet.of(\"networking\", \"security\", \"gateway\"));\n      assertEquals(server2.getUserMetadata(), ImmutableMap.of(\"foo\", \"bar\"));\n   }\n\n   @Test(dependsOnMethods = \"testSetServerConfiguration\")\n   public void testDestroyServer() throws Exception {\n      client.destroyServer(server.getUuid());\n      assertEquals(client.getServerInfo(server.getUuid()), null);\n   }\n\n   @Test(dependsOnMethods = \"testDestroyServer\")\n   public void testDestroyDrive() throws Exception {\n      client.destroyDrive(drive.getUuid());\n      assertEquals(client.getDriveInfo(drive.getUuid()), null);\n   }\n\n   protected void doConnectViaSsh(Server server, LoginCredentials creds) throws IOException {\n      SshClient ssh = Guice.createInjector(new SshjSshClientModule()).getInstance(SshClient.Factory.class).create(\n               HostAndPort.fromParts(server.getVnc().getIp(), 22), creds);\n      try {\n         ssh.connect();\n         ExecResponse hello = ssh.exec(\"echo hello\");\n         assertEquals(hello.getOutput().trim(), \"hello\");\n         System.err.println(ssh.exec(\"df -k\").getOutput());\n         System.err.println(ssh.exec(\"mount\").getOutput());\n         System.err.println(ssh.exec(\"uname -a\").getOutput());\n      } finally {\n         if (ssh != null)\n            ssh.disconnect();\n      }\n   }\n\n   @AfterGroups(groups = \"live\")\n   @Override\n   protected void tearDownContext() {\n      try {\n         client.destroyServer(server.getUuid());\n      } catch (Exception e) {\n         // no need to check null or anything as we swallow all\n      }\n      try {\n         client.destroyDrive(drive.getUuid());\n      } catch (Exception e) {\n\n      }\n      super.tearDownContext();\n   }\n\n   private DriveInfo drive2;\n   private DriveInfo drive3;\n\n   public void testWeCanReadAndWriteToDrive() throws IOException {\n      drive2 = client.createDrive(new CreateDriveRequest.Builder().name(prefix + \"2\").size(1 * 1024 * 1024L).build());\n      client.writeDrive(drive2.getUuid(), Payloads.newStringPayload(\"foo\"));\n      assertEquals(Strings2.toStringAndClose(client.readDrive(drive2.getUuid(), 0, 3).openStream()), \"foo\");\n   }\n\n   @Test(dependsOnMethods = \"testWeCanReadAndWriteToDrive\")\n   public void testWeCopyADriveContentsViaGzip() throws IOException {\n      try {\n         drive3 = client\n                  .createDrive(new CreateDriveRequest.Builder().name(prefix + \"3\").size(1 * 1024 * 1024L).build());\n         System.err.println(\"before image; drive 2\" + client.getDriveInfo(drive2.getUuid()));\n         System.err.println(\"before image; drive 3\" + client.getDriveInfo(drive3.getUuid()));\n         client.imageDrive(drive2.getUuid(), drive3.getUuid());\n         assert driveNotClaimed.apply(drive3) : client.getDriveInfo(drive3.getUuid());\n         assert driveNotClaimed.apply(drive2) : client.getDriveInfo(drive2.getUuid());\n         System.err.println(\"after image; drive 2\" + client.getDriveInfo(drive2.getUuid()));\n         System.err.println(\"after image; drive 3\" + client.getDriveInfo(drive3.getUuid()));\n         assertEquals(Strings2.toStringAndClose(client.readDrive(drive3.getUuid(), 0, 3).openStream()), \"foo\");\n      } finally {\n         client.destroyDrive(drive2.getUuid());\n         client.destroyDrive(drive3.getUuid());\n      }\n   }\n\n   protected LoginCredentials getSshCredentials(Server server) {\n      return LoginCredentials.builder().user(\"toor\").password(server.getVnc().getPassword()).build();\n   }\n\n   protected void prepareDrive() {\n      System.err.println(\"before prepare\" + client.getDriveInfo(drive.getUuid()));\n      client.imageDrive(imageId, drive.getUuid(), ImageConversionType.GUNZIP);\n      assert driveNotClaimed.apply(drive) : client.getDriveInfo(drive.getUuid());\n      System.err.println(\"after prepare\" + client.getDriveInfo(drive.getUuid()));\n   }\n\n}\n"
  },
  {
    "path": "apis/elasticstack/src/test/java/org/jclouds/elasticstack/ElasticStackApiMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack;\n\nimport org.jclouds.compute.internal.BaseComputeServiceApiMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ElasticStackApiMetadataTest\")\npublic class ElasticStackApiMetadataTest extends BaseComputeServiceApiMetadataTest {\n\n   public ElasticStackApiMetadataTest() {\n      super(new ElasticStackApiMetadata());\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/test/java/org/jclouds/elasticstack/ElasticStackApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack;\n\nimport static org.jclouds.reflect.Reflection2.method;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.elasticstack.binders.BindServerToPlainTextStringTest;\nimport org.jclouds.elasticstack.domain.CreateDriveRequest;\nimport org.jclouds.elasticstack.domain.Drive;\nimport org.jclouds.elasticstack.domain.DriveData;\nimport org.jclouds.elasticstack.domain.ImageConversionType;\nimport org.jclouds.elasticstack.domain.Server;\nimport org.jclouds.elasticstack.functions.KeyValuesDelimitedByBlankLinesToDriveInfo;\nimport org.jclouds.elasticstack.functions.KeyValuesDelimitedByBlankLinesToServerInfo;\nimport org.jclouds.elasticstack.functions.ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet;\nimport org.jclouds.elasticstack.functions.ListOfKeyValuesDelimitedByBlankLinesToServerInfoSet;\nimport org.jclouds.elasticstack.functions.ReturnPayload;\nimport org.jclouds.elasticstack.functions.SplitNewlines;\nimport org.jclouds.elasticstack.suppliers.MockStandardDiskImageSupplier;\nimport org.jclouds.elasticstack.suppliers.WellKnownImageSupplier;\nimport org.jclouds.fallbacks.MapHttp4xxCodesToExceptions;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.filters.BasicAuthentication;\nimport org.jclouds.http.functions.ReleasePayloadAndReturn;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.rest.internal.BaseRestAnnotationProcessingTest;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Iterables;\nimport com.google.common.reflect.Invokable;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Module;\nimport com.google.inject.Scopes;\n/**\n * Tests behavior of {@code ElasticStackApi}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"ElasticStackApiTest\")\npublic class ElasticStackApiTest extends BaseRestAnnotationProcessingTest<ElasticStackApi> {\n   public void testListServers() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ElasticStackApi.class, \"listServers\");\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(httpRequest, \"GET https://api-lon-p.elastichosts.com/servers/list HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: text/plain\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      // now make sure request filters apply by replaying\n      httpRequest = (GeneratedHttpRequest) Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);\n      httpRequest = (GeneratedHttpRequest) Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);\n\n      assertRequestLineEquals(httpRequest, \"GET https://api-lon-p.elastichosts.com/servers/list HTTP/1.1\");\n      // for example, using basic authentication, we should get \"only one\"\n      // header\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: text/plain\\nAuthorization: Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      // TODO: insert expected response class, which probably extends ParseJson\n      assertResponseParserClassEquals(method, httpRequest, SplitNewlines.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testListServerInfo() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ElasticStackApi.class, \"listServerInfo\");\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(httpRequest, \"GET https://api-lon-p.elastichosts.com/servers/info HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: text/plain\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ListOfKeyValuesDelimitedByBlankLinesToServerInfoSet.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testGetServerInfo() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ElasticStackApi.class, \"getServerInfo\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"uuid\"));\n\n      assertRequestLineEquals(httpRequest, \"GET https://api-lon-p.elastichosts.com/servers/uuid/info HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: text/plain\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, KeyValuesDelimitedByBlankLinesToServerInfo.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testCreateAndStartServer() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ElasticStackApi.class, \"createAndStartServer\", Server.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\n            BindServerToPlainTextStringTest.SERVER));\n\n      assertRequestLineEquals(httpRequest, \"POST https://api-lon-p.elastichosts.com/servers/create HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: text/plain\\n\");\n      assertPayloadEquals(httpRequest, BindServerToPlainTextStringTest.CREATED_SERVER, \"text/plain\", false);\n\n      assertResponseParserClassEquals(method, httpRequest, KeyValuesDelimitedByBlankLinesToServerInfo.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testCreateServer() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ElasticStackApi.class, \"createServer\", Server.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\n            BindServerToPlainTextStringTest.SERVER));\n\n      assertRequestLineEquals(httpRequest, \"POST https://api-lon-p.elastichosts.com/servers/create/stopped HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: text/plain\\n\");\n      assertPayloadEquals(httpRequest, BindServerToPlainTextStringTest.CREATED_SERVER, \"text/plain\", false);\n\n      assertResponseParserClassEquals(method, httpRequest, KeyValuesDelimitedByBlankLinesToServerInfo.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testSetServerConfiguration() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ElasticStackApi.class, \"setServerConfiguration\", String.class, Server.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"100\",\n            BindServerToPlainTextStringTest.SERVER));\n\n      assertRequestLineEquals(httpRequest, \"POST https://api-lon-p.elastichosts.com/servers/100/set HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: text/plain\\n\");\n      assertPayloadEquals(httpRequest, BindServerToPlainTextStringTest.CREATED_SERVER, \"text/plain\", false);\n\n      assertResponseParserClassEquals(method, httpRequest, KeyValuesDelimitedByBlankLinesToServerInfo.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testDestroyServer() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ElasticStackApi.class, \"destroyServer\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"uuid\"));\n\n      assertRequestLineEquals(httpRequest, \"POST https://api-lon-p.elastichosts.com/servers/uuid/destroy HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: text/plain\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, VoidOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testStartServer() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ElasticStackApi.class, \"startServer\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"uuid\"));\n\n      assertRequestLineEquals(httpRequest, \"POST https://api-lon-p.elastichosts.com/servers/uuid/start HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: text/plain\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testStopServer() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ElasticStackApi.class, \"stopServer\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"uuid\"));\n\n      assertRequestLineEquals(httpRequest, \"POST https://api-lon-p.elastichosts.com/servers/uuid/stop HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: text/plain\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testShutdownServer() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ElasticStackApi.class, \"shutdownServer\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"uuid\"));\n\n      assertRequestLineEquals(httpRequest, \"POST https://api-lon-p.elastichosts.com/servers/uuid/shutdown HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: text/plain\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testResetServer() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ElasticStackApi.class, \"resetServer\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"uuid\"));\n\n      assertRequestLineEquals(httpRequest, \"POST https://api-lon-p.elastichosts.com/servers/uuid/reset HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: text/plain\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testListDrives() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ElasticStackApi.class, \"listDrives\");\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(httpRequest, \"GET https://api-lon-p.elastichosts.com/drives/list HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: text/plain\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      // now make sure request filters apply by replaying\n      httpRequest = (GeneratedHttpRequest) Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);\n      httpRequest = (GeneratedHttpRequest) Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);\n\n      assertRequestLineEquals(httpRequest, \"GET https://api-lon-p.elastichosts.com/drives/list HTTP/1.1\");\n      // for example, using basic authentication, we should get \"only one\"\n      // header\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: text/plain\\nAuthorization: Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      // TODO: insert expected response class, which probably extends ParseJson\n      assertResponseParserClassEquals(method, httpRequest, SplitNewlines.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testListDriveInfo() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ElasticStackApi.class, \"listDriveInfo\");\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(httpRequest, \"GET https://api-lon-p.elastichosts.com/drives/info HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: text/plain\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testGetDriveInfo() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ElasticStackApi.class, \"getDriveInfo\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"uuid\"));\n\n      assertRequestLineEquals(httpRequest, \"GET https://api-lon-p.elastichosts.com/drives/uuid/info HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: text/plain\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, KeyValuesDelimitedByBlankLinesToDriveInfo.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testCreateDrive() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ElasticStackApi.class, \"createDrive\", Drive.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\n            new CreateDriveRequest.Builder().name(\"foo\").size(10000L).build()));\n\n      assertRequestLineEquals(httpRequest, \"POST https://api-lon-p.elastichosts.com/drives/create HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: text/plain\\n\");\n      assertPayloadEquals(httpRequest, \"name foo\\nsize 10000\", \"text/plain\", false);\n\n      assertResponseParserClassEquals(method, httpRequest, KeyValuesDelimitedByBlankLinesToDriveInfo.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testSetDriveData() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ElasticStackApi.class, \"setDriveData\", String.class, DriveData.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"100\",\n            new DriveData.Builder().name(\"foo\").size(10000L).tags(ImmutableList.of(\"production\", \"candy\")).build()));\n\n      assertRequestLineEquals(httpRequest, \"POST https://api-lon-p.elastichosts.com/drives/100/set HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: text/plain\\n\");\n      assertPayloadEquals(httpRequest, \"name foo\\nsize 10000\\ntags production candy\", \"text/plain\", false);\n\n      assertResponseParserClassEquals(method, httpRequest, KeyValuesDelimitedByBlankLinesToDriveInfo.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testDestroyDrive() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ElasticStackApi.class, \"destroyDrive\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"uuid\"));\n\n      assertRequestLineEquals(httpRequest, \"POST https://api-lon-p.elastichosts.com/drives/uuid/destroy HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: text/plain\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, VoidOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testImageDrive() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ElasticStackApi.class, \"imageDrive\", String.class, String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"100\", \"200\"));\n\n      assertRequestLineEquals(httpRequest, \"POST https://api-lon-p.elastichosts.com/drives/200/image/100 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: text/plain\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, VoidOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testImageDriveWithConversion() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ElasticStackApi.class, \"imageDrive\", String.class, String.class,\n            ImageConversionType.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"100\", \"200\",\n            ImageConversionType.GUNZIP));\n\n      assertRequestLineEquals(httpRequest, \"POST https://api-lon-p.elastichosts.com/drives/200/image/100/gunzip HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: text/plain\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, VoidOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n\n   }\n\n   public void testReadDrive() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ElasticStackApi.class, \"readDrive\", String.class, long.class, long.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"100\", 1024, 2048));\n\n      assertRequestLineEquals(httpRequest, \"POST https://api-lon-p.elastichosts.com/drives/100/read/1024/2048 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: application/octet-stream\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ReturnPayload.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testWriteDrive() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ElasticStackApi.class, \"writeDrive\", String.class, Payload.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"100\",\n            Payloads.newStringPayload(\"foo\")));\n\n      assertRequestLineEquals(httpRequest, \"POST https://api-lon-p.elastichosts.com/drives/100/write HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: text/plain\\n\");\n      assertPayloadEquals(httpRequest, \"foo\", MediaType.APPLICATION_OCTET_STREAM, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, VoidOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n   }\n\n   public void testWriteDriveOffset() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(ElasticStackApi.class, \"writeDrive\", String.class, Payload.class, long.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"100\",\n            Payloads.newStringPayload(\"foo\"), 2048));\n\n      assertRequestLineEquals(httpRequest, \"POST https://api-lon-p.elastichosts.com/drives/100/write/2048 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: text/plain\\n\");\n      assertPayloadEquals(httpRequest, \"foo\", MediaType.APPLICATION_OCTET_STREAM, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, VoidOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n   }\n\n   @Override\n   protected void checkFilters(HttpRequest request) {\n      assertEquals(request.getFilters().size(), 1);\n      assertEquals(request.getFilters().get(0).getClass(), BasicAuthentication.class);\n   }\n\n   @Override\n   protected ApiMetadata createApiMetadata() {\n      return new ElasticStackApiMetadata();\n   }\n\n   @Override\n   protected Module createModule() {\n      return new AbstractModule() {\n         @Override\n         protected void configure() {\n            bind(WellKnownImageSupplier.class).to(MockStandardDiskImageSupplier.class).in(Scopes.SINGLETON);\n         }\n      };\n   }\n\n}\n"
  },
  {
    "path": "apis/elasticstack/src/test/java/org/jclouds/elasticstack/ElasticStackMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack;\n\nimport static org.jclouds.Constants.PROPERTY_CREDENTIAL;\nimport static org.jclouds.Constants.PROPERTY_IDENTITY;\nimport static org.jclouds.util.Strings2.toStringAndClose;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport jakarta.ws.rs.core.HttpHeaders;\n\nimport okhttp3.mockwebserver.MockWebServer;\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.RecordedRequest;\n\nimport org.jclouds.elasticstack.domain.StandardDrive;\nimport org.jclouds.http.BaseMockWebServerTest;\nimport org.jclouds.http.config.JavaUrlHttpCommandExecutorServiceModule;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Throwables;\nimport com.google.inject.Module;\n\n\n/**\n * Mock tests for the {@link ElasticStackApi} class.\n */\n@Test(groups = \"unit\", testName = \"ElasticStackMockTest\")\npublic class ElasticStackMockTest extends BaseMockWebServerTest {\n\n   public void testListStandardDrives() throws IOException, InterruptedException {\n      MockWebServer server = mockWebServer(new MockResponse()\n            .setBody(payloadFromResource(\"/standard_drives_uuids.txt\")));\n      ElasticStackApi api = api(ElasticStackApi.class, server.url(\"/\").toString());\n\n      try {\n         Set<String> standardDrives = api.listStandardDrives();\n         assertEquals(standardDrives.size(), 36);\n\n         RecordedRequest request = server.takeRequest();\n         assertAuthentication(request);\n         assertEquals(request.getRequestLine(), \"GET /drives/list/standard HTTP/1.1\");\n      } finally {\n         api.close();\n         server.shutdown();\n      }\n   }\n\n   public void testListStandardDriveInfo() throws IOException, InterruptedException {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(payloadFromResource(\"/standard_drives.txt\")));\n      ElasticStackApi api = api(ElasticStackApi.class, server.url(\"/\").toString());\n\n      try {\n         Set<StandardDrive> standardDrives = api.listStandardDriveInfo();\n         assertEquals(standardDrives.size(), 36);\n\n         RecordedRequest request = server.takeRequest();\n         assertAuthentication(request);\n         assertEquals(request.getRequestLine(), \"GET /drives/info/standard HTTP/1.1\");\n      } finally {\n         api.close();\n         server.shutdown();\n      }\n   }\n\n   private static void assertAuthentication(final RecordedRequest request) throws InterruptedException {\n      assertEquals(request.getHeader(HttpHeaders.AUTHORIZATION), \"Basic dXVpZDphcGlrZXk=\");\n   }\n\n   private String payloadFromResource(String resource) {\n      try {\n         return toStringAndClose(getClass().getResourceAsStream(resource));\n      } catch (IOException e) {\n         throw Throwables.propagate(e);\n      }\n   }\n\n   @Override\n   protected void addOverrideProperties(Properties props) {\n      props.setProperty(PROPERTY_IDENTITY, \"uuid\");\n      props.setProperty(PROPERTY_CREDENTIAL, \"apikey\");\n   }\n\n   @Override\n   protected Module createConnectionModule() {\n      return new JavaUrlHttpCommandExecutorServiceModule();\n   }\n\n}\n"
  },
  {
    "path": "apis/elasticstack/src/test/java/org/jclouds/elasticstack/binders/BindDriveDataToPlainTextStringTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.util.Map;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.elasticstack.domain.ClaimType;\nimport org.jclouds.elasticstack.domain.Drive;\nimport org.jclouds.elasticstack.domain.DriveData;\nimport org.jclouds.elasticstack.functions.CreateDriveRequestToMap;\nimport org.jclouds.elasticstack.functions.DriveDataToMap;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.TypeLiteral;\n\n@Test(groups = { \"unit\" })\npublic class BindDriveDataToPlainTextStringTest {\n\n   private static final BindDriveDataToPlainTextString FN = Guice.createInjector(new AbstractModule() {\n\n      @Override\n      protected void configure() {\n         bind(new TypeLiteral<Function<Drive, Map<String, String>>>() {\n         }).to(CreateDriveRequestToMap.class);\n         bind(new TypeLiteral<Function<DriveData, Map<String, String>>>() {\n         }).to(DriveDataToMap.class);\n      }\n\n   }).getInstance(BindDriveDataToPlainTextString.class);\n\n   public void testSimple() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"https://host/drives/create\").build();\n      FN.bindToRequest(request, new DriveData.Builder().name(\"foo\").size(100L).build());\n      assertEquals(request.getPayload().getContentMetadata().getContentType(), MediaType.TEXT_PLAIN);\n      assertEquals(request.getPayload().getRawContent(), \"name foo\\nsize 100\");\n   }\n\n   public void testComplete() throws IOException {\n      DriveData input = new DriveData.Builder().name(\"Ubuntu 10.10 Server Edition Linux 64bit Preinstalled System\")\n      //\n            .size(8589934592L)//\n            .claimType(ClaimType.SHARED)//\n            .readers(ImmutableSet.of(\"ffffffff-ffff-ffff-ffff-ffffffffffff\"))//\n            .tags(ImmutableSet.of(\"tag1\", \"tag2\")).userMetadata(ImmutableMap.of(\"foo\", \"bar\", \"baz\", \"raz\"))//\n            .build();\n\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"https://host/drives/create\").build();\n      FN.bindToRequest(request, input);\n      assertEquals(request.getPayload().getContentMetadata().getContentType(), MediaType.TEXT_PLAIN);\n      assertEquals(request.getPayload().getRawContent(),\n            Strings2.toStringAndClose(BindDriveDataToPlainTextStringTest.class.getResourceAsStream(\"/drive_data.txt\")));\n\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/test/java/org/jclouds/elasticstack/binders/BindDriveToPlainTextStringTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.util.Map;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.elasticstack.domain.ClaimType;\nimport org.jclouds.elasticstack.domain.CreateDriveRequest;\nimport org.jclouds.elasticstack.domain.Drive;\nimport org.jclouds.elasticstack.domain.DriveData;\nimport org.jclouds.elasticstack.functions.CreateDriveRequestToMap;\nimport org.jclouds.elasticstack.functions.DriveDataToMap;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.TypeLiteral;\n\n@Test(groups = { \"unit\" })\npublic class BindDriveToPlainTextStringTest {\n\n   private static final BindDriveToPlainTextString FN = Guice.createInjector(new AbstractModule() {\n\n      @Override\n      protected void configure() {\n         bind(new TypeLiteral<Function<Drive, Map<String, String>>>() {\n         }).to(CreateDriveRequestToMap.class);\n         bind(new TypeLiteral<Function<DriveData, Map<String, String>>>() {\n         }).to(DriveDataToMap.class);\n      }\n\n   }).getInstance(BindDriveToPlainTextString.class);\n\n   public void testSimple() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"https://host/drives/create\").build();\n      FN.bindToRequest(request, new CreateDriveRequest.Builder().name(\"foo\").size(100L).build());\n      assertEquals(request.getPayload().getContentMetadata().getContentType(), MediaType.TEXT_PLAIN);\n      assertEquals(request.getPayload().getRawContent(), \"name foo\\nsize 100\");\n   }\n\n   public void testComplete() throws IOException {\n      CreateDriveRequest input = new CreateDriveRequest.Builder()\n            .name(\"Ubuntu 10.10 Server Edition Linux 64bit Preinstalled System\")\n            //\n            .size(8589934592L)//\n            .claimType(ClaimType.SHARED)//\n            .readers(ImmutableSet.of(\"ffffffff-ffff-ffff-ffff-ffffffffffff\"))//\n            .tags(ImmutableSet.of(\"tag1\", \"tag2\")).userMetadata(ImmutableMap.of(\"foo\", \"bar\", \"baz\", \"raz\"))//\n            .encryptionCipher(\"aes-xts-plain\").avoid(ImmutableSet.of(\"avoid1\")).build();\n\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"https://host/drives/create\").build();\n      FN.bindToRequest(request, input);\n      assertEquals(request.getPayload().getContentMetadata().getContentType(), MediaType.TEXT_PLAIN);\n      assertEquals(request.getPayload().getRawContent(),\n            Strings2.toStringAndClose(BindDriveToPlainTextStringTest.class\n                  .getResourceAsStream(\"/create_drive.txt\")));\n\n   }\n\n}\n"
  },
  {
    "path": "apis/elasticstack/src/test/java/org/jclouds/elasticstack/binders/BindServerToPlainTextStringTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.util.Map;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.elasticstack.domain.IDEDevice;\nimport org.jclouds.elasticstack.domain.Model;\nimport org.jclouds.elasticstack.domain.NIC;\nimport org.jclouds.elasticstack.domain.Server;\nimport org.jclouds.elasticstack.domain.VNC;\nimport org.jclouds.elasticstack.functions.ServerToMap;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.annotations.ApiVersion;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Throwables;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport com.google.inject.TypeLiteral;\n\n@Test(groups = { \"unit\" })\npublic class BindServerToPlainTextStringTest {\n\n   public static final String CREATED_SERVER;\n   static {\n      try {\n         CREATED_SERVER = Strings2.toStringAndClose(BindServerToPlainTextStringTest.class\n               .getResourceAsStream(\"/create_server.txt\"));\n      } catch (IOException e) {\n         throw Throwables.propagate(e);\n      }\n   }\n   public static final Server SERVER = new Server.Builder()\n         .name(\"TestServer\")\n         .cpu(2000)\n         .mem(1024)\n         .devices(\n               ImmutableMap.of(\"ide:0:0\", new IDEDevice.Builder(0, 0).uuid(\"08c92dd5-70a0-4f51-83d2-835919d254df\")\n                     .build())).bootDeviceIds(ImmutableSet.of(\"ide:0:0\"))\n         .nics(ImmutableSet.of(new NIC.Builder().model(Model.E1000).\n\n         build())).vnc(new VNC(null, \"XXXXXXXX\", false)).build();\n   private Injector i = Guice.createInjector(new AbstractModule() {\n\n      @Override\n      protected void configure() {\n         bindConstant().annotatedWith(ApiVersion.class).to(\"1.0\");\n         bind(new TypeLiteral<Function<Server, Map<String, String>>>() {\n         }).to(ServerToMap.class);\n      }\n\n   });\n\n   public void testSimple() throws IOException {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"https://host/drives/create\").build();\n      i.getInstance(BindServerToPlainTextString.class).bindToRequest(request, SERVER);\n      assertEquals(request.getPayload().getContentMetadata().getContentType(), MediaType.TEXT_PLAIN);\n      assertEquals(request.getPayload().getRawContent(), CREATED_SERVER);\n   }\n\n}\n"
  },
  {
    "path": "apis/elasticstack/src/test/java/org/jclouds/elasticstack/compute/ElasticStackComputeServiceAdapterTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.compute;\n\nimport static org.easymock.EasyMock.anyObject;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.expectLastCall;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\n\nimport java.util.Map;\nimport java.util.UUID;\n\nimport org.easymock.EasyMock;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.HardwareBuilder;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.Image.Status;\nimport org.jclouds.compute.domain.ImageBuilder;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.Processor;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.domain.Volume.Type;\nimport org.jclouds.compute.domain.VolumeBuilder;\nimport org.jclouds.compute.domain.internal.TemplateImpl;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.elasticstack.ElasticStackApi;\nimport org.jclouds.elasticstack.domain.DriveInfo;\nimport org.jclouds.elasticstack.domain.DriveMetrics;\nimport org.jclouds.elasticstack.domain.ImageConversionType;\nimport org.jclouds.elasticstack.domain.WellKnownImage;\nimport org.testng.annotations.BeforeMethod;\nimport org.testng.annotations.Test;\nimport org.testng.collections.Maps;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Predicates;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.util.concurrent.MoreExecutors;\n\n@Test(groups = \"unit\", testName = \"ElasticStackComputeServiceAdapterTest\")\npublic class ElasticStackComputeServiceAdapterTest {\n\n   private Image image;\n   private Hardware hardware;\n   private Template template;\n\n   @BeforeMethod\n   public void setup() {\n      image = new ImageBuilder().ids(\"mock\").operatingSystem(OperatingSystem.builder().description(\"mock\").build())\n            .status(Status.AVAILABLE).build();\n      hardware = new HardwareBuilder().ids(\"mock\").volume(new VolumeBuilder().type(Type.LOCAL).size(1.0f).build())\n            .processor(new Processor(1.0, 1.0)).build();\n      template = new TemplateImpl(image, hardware, new LocationBuilder().id(\"mock\").scope(LocationScope.PROVIDER)\n            .description(\"mock\").build(), TemplateOptions.NONE);\n   }\n\n   @Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = \"imageDrive call failed\")\n   public void testDiskIsDestroyedIfImageFails() {\n      Supplier<Map<String, WellKnownImage>> preInstalledImageSupplier = Suppliers.ofInstance(Maps\n            .<String, WellKnownImage> newHashMap());\n      LoadingCache<String, DriveInfo> driveCache = CacheBuilder.newBuilder().build(\n            new CacheLoader<String, DriveInfo>() {\n               @Override\n               public DriveInfo load(String key) throws Exception {\n                  throw new IllegalStateException(\"cache should not be used\");\n               }\n            });\n\n      ElasticStackApi api = EasyMock.createMock(ElasticStackApi.class);\n      Predicate<DriveInfo> driveNotClaimed = Predicates.alwaysTrue();\n      DriveInfo mockDrive = new DriveInfo.Builder().uuid(UUID.randomUUID().toString()).name(\"mock\")\n            .metrics(new DriveMetrics.Builder().build()).build();\n\n      expect(api.createDrive(anyObject(DriveInfo.class))).andReturn(mockDrive);\n      api.imageDrive(image.getId(), mockDrive.getUuid(), ImageConversionType.GUNZIP);\n      // Set a custom exception message to make sure the exception is thrown at the right point\n      expectLastCall().andThrow(new IllegalStateException(\"imageDrive call failed\"));\n      api.destroyDrive(mockDrive.getUuid());\n      expectLastCall();\n\n      replay(api);\n\n      ElasticStackComputeServiceAdapter adapter = new ElasticStackComputeServiceAdapter(api, driveNotClaimed,\n            preInstalledImageSupplier, driveCache, \"12345678\", MoreExecutors.newDirectExecutorService());\n\n      try {\n         adapter.createNodeWithGroupEncodedIntoName(\"mock-group\", \"mock-name\", template);\n      } catch (IllegalStateException ex) {\n         verify(api);\n         throw ex;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/test/java/org/jclouds/elasticstack/compute/ElasticStackComputeServiceLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.compute;\n\nimport org.jclouds.compute.domain.ExecResponse;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.internal.BaseComputeServiceLiveTest;\nimport org.jclouds.sshj.config.SshjSshClientModule;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Module;\n\n@Test(groups = \"live\", testName = \"ElasticStackComputeServiceLiveTest\")\npublic class ElasticStackComputeServiceLiveTest extends BaseComputeServiceLiveTest {\n\n   public ElasticStackComputeServiceLiveTest() {\n      provider = \"elasticstack\";\n   }\n\n   @Override\n   protected Module getSshModule() {\n      return new SshjSshClientModule();\n   }\n\n   @Override\n   public void testOptionToNotBlock() {\n      // start call is blocking anyway.\n   }\n\n   protected void checkResponseEqualsHostname(ExecResponse execResponse, NodeMetadata node1) {\n      // hostname is not predictable based on node metadata\n      assert execResponse.getOutput().trim().equals(\"ubuntu\") : execResponse.getOutput();\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/test/java/org/jclouds/elasticstack/compute/functions/GetImageIdFromServerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.compute.functions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\n\nimport java.util.Map;\nimport java.util.UUID;\n\nimport org.jclouds.elasticstack.compute.functions.ServerInfoToNodeMetadata.GetImageIdFromServer;\nimport org.jclouds.elasticstack.domain.Device;\nimport org.jclouds.elasticstack.domain.DriveInfo;\nimport org.jclouds.elasticstack.domain.DriveMetrics;\nimport org.jclouds.elasticstack.domain.SCSIDevice;\nimport org.jclouds.elasticstack.domain.Server;\nimport org.jclouds.elasticstack.domain.VNC;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Maps;\n\n/**\n * Unit tests for the {@link GetImageIdFromServer} class.\n */\n@Test(groups = \"unit\", testName = \"GetImageIdFromServerTest\")\npublic class GetImageIdFromServerTest {\n\n   private static final String UNKNOWN_DRIVE_UUID = UUID.randomUUID().toString();\n\n   private LoadingCache<String, DriveInfo> knownDrives = CacheBuilder.newBuilder().build(\n         new CacheLoader<String, DriveInfo>() {\n            @Override\n            public DriveInfo load(String key) throws Exception {\n               // Use a mock UUID to be able to simulate the unknown drives\n               return UNKNOWN_DRIVE_UUID.equals(key) ? null : new DriveInfo.Builder().name(\"foo\")\n                     .metrics(new DriveMetrics.Builder().build()).build();\n            }\n         });\n\n   private GetImageIdFromServer function = new GetImageIdFromServer(knownDrives);\n\n   public void testImageIdExists() {\n      Map<String, Device> devices = deviceMapFor(UUID.randomUUID().toString());\n      Server server = serverFor(devices, devices.keySet());\n      assertEquals(function.apply(server), \"foo\");\n   }\n\n   public void testImageIdExistsAndUsesTheFirstDevice() {\n      Map<String, Device> devices = deviceMapFor(UUID.randomUUID().toString(), UNKNOWN_DRIVE_UUID);\n      Server server = serverFor(devices, devices.keySet());\n      assertEquals(function.apply(server), \"foo\");\n   }\n\n   public void testImageIdIsNullWhenNoBootableDevices() {\n      Map<String, Device> devices = deviceMapFor(UUID.randomUUID().toString());\n      Server server = serverFor(devices, ImmutableSet.<String> of());\n      assertNull(function.apply(server));\n   }\n\n   public void testImageIdIsNullWhenNoDeviceWithGivenId() {\n      Map<String, Device> devices = deviceMapFor(UUID.randomUUID().toString());\n      Server server = serverFor(ImmutableMap.<String, Device> of(), devices.keySet());\n      assertNull(function.apply(server));\n   }\n\n   private static Map<String, Device> deviceMapFor(String... uuids) {\n      ImmutableSet.Builder<Device> devices = ImmutableSet.builder();\n      for (int i = 0; i < uuids.length; i++) {\n         devices.add(new SCSIDevice.Builder(i).uuid(uuids[i]).build());\n      }\n\n      return Maps.uniqueIndex(devices.build(), new Function<Device, String>() {\n         @Override\n         public String apply(Device input) {\n            return input.getId();\n         }\n      });\n   }\n\n   private static Server serverFor(Map<String, Device> devices, Iterable<String> deviceIds) {\n      return new Server.Builder().name(\"test\").vnc(new VNC(null, null, false)).devices(devices)\n            .bootDeviceIds(deviceIds).build();\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/test/java/org/jclouds/elasticstack/compute/functions/StandardDriveToWellKnownImageTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.compute.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.UUID;\n\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.elasticstack.domain.MediaType;\nimport org.jclouds.elasticstack.domain.StandardDrive;\nimport org.jclouds.elasticstack.domain.WellKnownImage;\nimport org.testng.annotations.Test;\n\n/**\n * Unit tests for the {@link StandardDriveToWellKnownImage} class.\n */\n@Test(groups = \"unit\", testName = \"StandardDriveToWellKnownImageTest\")\npublic class StandardDriveToWellKnownImageTest {\n\n   private StandardDriveToWellKnownImage function = new StandardDriveToWellKnownImage();\n   \n   public void testUnknownOperatingSystemParsing() {\n      assertOS(\"Foo Linux 6.5\", OsFamily.UNRECOGNIZED, \"6.5\", true);\n   }\n   \n   public void testOperatingSystemWithoutVersionParsing() {\n      assertOS(\"Ubuntu Linux\", OsFamily.UBUNTU, null, true);\n   }\n\n   public void testKnownOperatingSystemParsing() {\n\n      // Elastichosts\n      assertOS(\"centOS Linux 6.5\", OsFamily.CENTOS, \"6.5\", true);\n      assertOS(\"Debian Linux 7.4 (Wheezy)\", OsFamily.DEBIAN, \"7.4\", true);\n      assertOS(\"Ubuntu Linux 12.04.1 LTS (Precise Pangolin)\", OsFamily.UBUNTU, \"12.04.1\", true);\n      assertOS(\"Ubuntu Linux 13.10 (Saucy Salamander)\", OsFamily.UBUNTU, \"13.10\", true);\n      assertOS(\"Ubuntu 14.04 LTS (Trusty Tahr)\", OsFamily.UBUNTU, \"14.04\", true);\n      assertOS(\"Windows Server 2012\", OsFamily.WINDOWS, \"2012\", true);\n      assertOS(\"Windows Server 2012 + SQL\", OsFamily.WINDOWS, \"2012 + SQL\", true);\n      assertOS(\"Windows Server 2012 R2\", OsFamily.WINDOWS, \"2012 R2\", true);\n      assertOS(\"Windows Standard 2008 R2\", OsFamily.WINDOWS, \"2008 R2\", true);\n      assertOS(\"Windows Standard 2008 R2 + SQL\", OsFamily.WINDOWS, \"2008 R2 + SQL\", true);\n      assertOS(\"Windows Web Server 2008 R2\", OsFamily.WINDOWS, \"2008 R2\", true);\n      assertOS(\"Windows Web Server 2008 R2 + SQL\", OsFamily.WINDOWS, \"2008 R2 + SQL\", true);\n\n      // Go2Cloud\n      assertOS(\"Ubuntu 10.10\", OsFamily.UBUNTU, \"10.10\", true);\n      assertOS(\"Debian 6.0.2.1\", OsFamily.DEBIAN, \"6.0.2.1\", true);\n      assertOS(\"Windows 2008 R2 (x64) with SP1\", OsFamily.WINDOWS, \"2008 R2 (x64) with SP1\", true);\n      assertOS(\"Windows 8 Developer Preview (x64)\", OsFamily.WINDOWS, \"8 Developer Preview (x64)\", true);\n\n      // OpenHosting\n      assertOS(\"CentOS Linux 5.5 64\", OsFamily.CENTOS, \"5.5\", true);\n      assertOS(\"CentOS Linux 5.6 64\", OsFamily.CENTOS, \"5.6\", true);\n      assertOS(\"CentOS Linux 5.7 64\", OsFamily.CENTOS, \"5.7\", true);\n      assertOS(\"Debian Linux 5.0\", OsFamily.DEBIAN, \"5.0\", true);\n      assertOS(\"Debian Linux 6 (Squeeze) 64\", OsFamily.DEBIAN, \"6\", true);\n      assertOS(\"Ubuntu 10.04.3 LTS (lucid) Server 64\", OsFamily.UBUNTU, \"10.04.3\", true);\n      assertOS(\"Windows 2008 R2 Standard Edition\", OsFamily.WINDOWS, \"2008 R2 Standard Edition\", true);\n\n      // Skalicloud\n      assertOS(\"CentOS 5.5 -32bit\", OsFamily.CENTOS, \"5.5\", false);\n      assertOS(\"CentOS 5.5 -64bit\", OsFamily.CENTOS, \"5.5\", true);\n      assertOS(\"CentOS 5.6 -32bit\", OsFamily.CENTOS, \"5.6\", false);\n      assertOS(\"CentOS 5.6 -64bit\", OsFamily.CENTOS, \"5.6\", true);\n      assertOS(\"Debian 5 -32bit\", OsFamily.DEBIAN, \"5\", false);\n      assertOS(\"Debian 5 -64bit\", OsFamily.DEBIAN, \"5\", true);\n      assertOS(\"Debian 6 -64bit -Experimental\", OsFamily.DEBIAN, \"6\", true);\n      assertOS(\"Ubuntu Server 10.04 -32bit\", OsFamily.UBUNTU, \"10.04\", false);\n      assertOS(\"Ubuntu Server 10.04 -64bit\", OsFamily.UBUNTU, \"10.04\", true);\n      assertOS(\"Ubuntu Server 10.10 -32bit\", OsFamily.UBUNTU, \"10.10\", false);\n      assertOS(\"Ubuntu Server 10.10 -64bit\", OsFamily.UBUNTU, \"10.10\", true);\n      assertOS(\"Windows 2008R2 Web Edition\", OsFamily.WINDOWS, \"2008R2 Web Edition\", true);\n      assertOS(\"Windows Server 2008R2 Standard\", OsFamily.WINDOWS, \"2008R2 Standard\", true);\n\n      // ServerLove\n      assertOS(\"CentOS Linux 5.7\", OsFamily.CENTOS, \"5.7\", true);\n      assertOS(\"CentOS Linux 6.2\", OsFamily.CENTOS, \"6.2\", true);\n      assertOS(\"Debian Linux 6.0\", OsFamily.DEBIAN, \"6.0\", true);\n      assertOS(\"Ubuntu 10.04 LTS\", OsFamily.UBUNTU, \"10.04\", true);\n      assertOS(\"Ubuntu 12.04 LTS\", OsFamily.UBUNTU, \"12.04\", true);\n      assertOS(\"Windows Server 2008 R2 Standard\", OsFamily.WINDOWS, \"2008 R2 Standard\", true);\n      assertOS(\"Windows Server 2008 R2 Standard SP1 with SQL Server 2008 R2 Web Edition\", OsFamily.WINDOWS,\n            \"2008 R2 Standard SP1 with SQL Server 2008 R2 Web Edition\", true);\n      assertOS(\"Windows Server 2012 Standard\", OsFamily.WINDOWS, \"2012 Standard\", true);\n      assertOS(\"Windows Web Server 2008 R2\", OsFamily.WINDOWS, \"2008 R2\", true);\n      assertOS(\"Windows Web Server 2008 R2 SP1 with SQL Server 2008 R2 Web Edition\", OsFamily.WINDOWS,\n            \"2008 R2 SP1 with SQL Server 2008 R2 Web Edition\", true);\n   }\n\n   private void assertOS(String name, OsFamily expectedFamily, String expectedVersion, boolean expectedIs64bit) {\n      StandardDrive drive = standardDrive(name);\n      WellKnownImage image = function.apply(drive);\n\n      assertEquals(image.getOsFamily(), expectedFamily, String.format(\"Parsing family for [%s]:\", name));\n      assertEquals(image.getOsVersion(), expectedVersion, String.format(\"Parsing version for [%s]:\", name));\n      assertEquals(image.is64bit(), expectedIs64bit, String.format(\"Parsing arch for [%s]:\", name));\n   }\n\n   private static StandardDrive standardDrive(String name) {\n      return new StandardDrive.Builder().uuid(UUID.randomUUID().toString()).size(1).name(name).media(MediaType.DISK)\n            .build();\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/test/java/org/jclouds/elasticstack/functions/BaseDriveToMapTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\n\nimport org.jclouds.elasticstack.domain.ClaimType;\nimport org.jclouds.elasticstack.domain.Drive;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = { \"unit\" })\npublic class BaseDriveToMapTest {\n\n   private static final BaseDriveToMap BASEDRIVE_TO_MAP = new BaseDriveToMap();\n\n   public void testBasics() {\n      assertEquals(BASEDRIVE_TO_MAP.apply(new Drive.Builder().name(\"foo\").size(100L).build()),\n            ImmutableMap.of(\"name\", \"foo\", \"size\", \"100\"));\n   }\n\n   public void testComplete() throws IOException {\n      Drive one = new Drive.Builder().name(\"Ubuntu 10.10 Server Edition Linux 64bit Preinstalled System\")\n      //\n            .size(8589934592L)//\n            .claimType(ClaimType.SHARED)//\n            .readers(ImmutableSet.of(\"ffffffff-ffff-ffff-ffff-ffffffffffff\"))//\n            .tags(ImmutableSet.of(\"tag1\", \"tag2\")).userMetadata(ImmutableMap.of(\"foo\", \"bar\", \"baz\", \"raz\"))//\n            .build();\n      assertEquals(\n            BASEDRIVE_TO_MAP.apply(one),\n            ImmutableMap.builder().put(\"name\", \"Ubuntu 10.10 Server Edition Linux 64bit Preinstalled System\")\n                  .put(\"size\", \"8589934592\").put(\"claim:type\", \"shared\")\n                  .put(\"readers\", \"ffffffff-ffff-ffff-ffff-ffffffffffff\").put(\"tags\", \"tag1 tag2\")\n                  .put(\"user:foo\", \"bar\").put(\"user:baz\", \"raz\").build()\n\n      );\n\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/test/java/org/jclouds/elasticstack/functions/CreateDriveRequestToMapTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\n\nimport org.jclouds.elasticstack.domain.ClaimType;\nimport org.jclouds.elasticstack.domain.CreateDriveRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\n\n@Test(groups = { \"unit\" })\npublic class CreateDriveRequestToMapTest {\n\n   private static final CreateDriveRequestToMap BASEDRIVE_TO_MAP = Guice.createInjector().getInstance(\n         CreateDriveRequestToMap.class);\n\n   public void testBasics() {\n      assertEquals(BASEDRIVE_TO_MAP.apply(new CreateDriveRequest.Builder().name(\"foo\").size(100L).build()),\n            ImmutableMap.of(\"name\", \"foo\", \"size\", \"100\"));\n   }\n\n   public void testComplete() throws IOException {\n      CreateDriveRequest one = new CreateDriveRequest.Builder()\n            .name(\"Ubuntu 10.10 Server Edition Linux 64bit Preinstalled System\")\n            //\n            .size(8589934592L)//\n            .claimType(ClaimType.SHARED)//\n            .readers(ImmutableSet.of(\"ffffffff-ffff-ffff-ffff-ffffffffffff\"))//\n            .tags(ImmutableSet.of(\"tag1\", \"tag2\")).userMetadata(ImmutableMap.of(\"foo\", \"bar\", \"baz\", \"raz\"))//\n            .encryptionCipher(\"aes-xts-plain\").avoid(ImmutableSet.of(\"avoid1\")).build();\n      assertEquals(\n            BASEDRIVE_TO_MAP.apply(one),\n            ImmutableMap.builder().put(\"name\", \"Ubuntu 10.10 Server Edition Linux 64bit Preinstalled System\")\n                  .put(\"size\", \"8589934592\").put(\"claim:type\", \"shared\")\n                  .put(\"readers\", \"ffffffff-ffff-ffff-ffff-ffffffffffff\").put(\"tags\", \"tag1 tag2\")\n                  .put(\"user:foo\", \"bar\").put(\"user:baz\", \"raz\").put(\"encryption:cipher\", \"aes-xts-plain\")\n                  .put(\"avoid\", \"avoid1\").build()\n\n      );\n\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/test/java/org/jclouds/elasticstack/functions/DriveDataToMapTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\n\nimport org.jclouds.elasticstack.domain.ClaimType;\nimport org.jclouds.elasticstack.domain.DriveData;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\n\n@Test(groups = { \"unit\" })\npublic class DriveDataToMapTest {\n\n   private static final DriveDataToMap BASEDRIVE_TO_MAP = Guice.createInjector().getInstance(DriveDataToMap.class);\n\n   public void testBasics() {\n      assertEquals(BASEDRIVE_TO_MAP.apply(new DriveData.Builder().name(\"foo\").size(100L).build()),\n            ImmutableMap.of(\"name\", \"foo\", \"size\", \"100\"));\n   }\n\n   public void testComplete() throws IOException {\n      DriveData one = new DriveData.Builder().name(\"Ubuntu 10.10 Server Edition Linux 64bit Preinstalled System\")\n      //\n            .size(8589934592L)//\n            .claimType(ClaimType.SHARED)//\n            .readers(ImmutableSet.of(\"ffffffff-ffff-ffff-ffff-ffffffffffff\"))//\n            .tags(ImmutableSet.of(\"tag1\", \"tag2\")).userMetadata(ImmutableMap.of(\"foo\", \"bar\", \"baz\", \"raz\"))//\n            .build();\n      assertEquals(\n            BASEDRIVE_TO_MAP.apply(one),\n            ImmutableMap.builder().put(\"name\", \"Ubuntu 10.10 Server Edition Linux 64bit Preinstalled System\")\n                  .put(\"size\", \"8589934592\").put(\"claim:type\", \"shared\")\n                  .put(\"readers\", \"ffffffff-ffff-ffff-ffff-ffffffffffff\").put(\"tags\", \"tag1 tag2\")\n                  .put(\"user:foo\", \"bar\").put(\"user:baz\", \"raz\").build()\n\n      );\n\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/test/java/org/jclouds/elasticstack/functions/KeyValuesDelimitedByBlankLinesToDriveInfoTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Guice;\n\n@Test(groups = { \"unit\" })\npublic class KeyValuesDelimitedByBlankLinesToDriveInfoTest {\n\n   private static final KeyValuesDelimitedByBlankLinesToDriveInfo FN = Guice.createInjector().getInstance(\n         KeyValuesDelimitedByBlankLinesToDriveInfo.class);\n\n   public void testNone() {\n      assertEquals(FN.apply(HttpResponse.builder().statusCode(200).message(\"\").payload(\"\").build()), null);\n      assertEquals(FN.apply(HttpResponse.builder().statusCode(200).message(\"\").payload(\"\\n\\n\").build()), null);\n      assertEquals(FN.apply(HttpResponse.builder().statusCode(200).message(\"\").build()), null);\n   }\n\n   public void testOne() {\n      assertEquals(FN.apply(HttpResponse.builder().statusCode(200).message(\"\").payload(MapToDriveInfoTest.class\n            .getResourceAsStream(\"/drive.txt\")).build()), MapToDriveInfoTest.ONE);\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/test/java/org/jclouds/elasticstack/functions/KeyValuesDelimitedByBlankLinesToServerInfoTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.elasticstack.domain.Device;\nimport org.jclouds.elasticstack.domain.DriveMetrics;\nimport org.jclouds.elasticstack.domain.NIC;\nimport org.jclouds.elasticstack.domain.ServerMetrics;\nimport org.jclouds.elasticstack.functions.MapToDevices.DeviceToId;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rest.annotations.ApiVersion;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.TypeLiteral;\n\n@Test(groups = { \"unit\" })\npublic class KeyValuesDelimitedByBlankLinesToServerInfoTest {\n\n   private static final KeyValuesDelimitedByBlankLinesToServerInfo FN = Guice.createInjector(new AbstractModule() {\n\n      @Override\n      protected void configure() {\n         bindConstant().annotatedWith(ApiVersion.class).to(\"1.0\");\n         bind(new TypeLiteral<Function<Map<String, String>, List<NIC>>>() {\n         }).to(MapToNICs.class);\n         bind(new TypeLiteral<Function<Map<String, String>, Map<String, ? extends Device>>>() {\n         }).to(MapToDevices.class);\n         bind(new TypeLiteral<Function<Map<String, String>, Map<String, ? extends DriveMetrics>>>() {\n         }).to(MapToDriveMetrics.class);\n         bind(new TypeLiteral<Function<Map<String, String>, ServerMetrics>>() {\n         }).to(MapToServerMetrics.class);\n         bind(new TypeLiteral<Function<Device, String>>() {\n         }).to(DeviceToId.class);\n      }\n\n   }).getInstance(KeyValuesDelimitedByBlankLinesToServerInfo.class);\n\n   public void testNone() {\n      assertEquals(FN.apply(HttpResponse.builder().statusCode(200).message(\"\").payload(\"\").build()), null);\n      assertEquals(FN.apply(HttpResponse.builder().statusCode(200).message(\"\").payload(\"\\n\\n\").build()), null);\n      assertEquals(FN.apply(HttpResponse.builder().statusCode(200).message(\"\").build()), null);\n   }\n\n   public void testOne() {\n      assertEquals(FN.apply(HttpResponse.builder().statusCode(200).message(\"\").payload(MapToServerInfoTest.class\n            .getResourceAsStream(\"/servers.txt\")).build()), MapToServerInfoTest.ONE);\n   }\n\n   public void testNew() {\n      assertEquals(FN.apply(HttpResponse.builder().statusCode(200).message(\"\").payload(MapToServerInfoTest.class\n            .getResourceAsStream(\"/new_server.txt\")).build()), MapToServerInfoTest.NEW);\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/test/java/org/jclouds/elasticstack/functions/ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSetTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.elasticstack.domain.DriveInfo;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\n\n@Test(groups = { \"unit\" })\npublic class ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSetTest {\n\n   private static final ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet FN = Guice.createInjector().getInstance(\n         ListOfKeyValuesDelimitedByBlankLinesToDriveInfoSet.class);\n\n   public void testNone() {\n      assertEquals(FN.apply(HttpResponse.builder().statusCode(200).message(\"\").payload(\"\").build()), ImmutableSet.<DriveInfo> of());\n      assertEquals(FN.apply(HttpResponse.builder().statusCode(200).message(\"\").payload(\"\\n\\n\").build()), ImmutableSet.<DriveInfo> of());\n      assertEquals(FN.apply(HttpResponse.builder().statusCode(200).message(\"\").build()), ImmutableSet.<DriveInfo> of());\n   }\n\n   public void testOne() {\n      assertEquals(FN.apply(HttpResponse.builder().statusCode(200).message(\"\").payload(MapToDriveInfoTest.class\n            .getResourceAsStream(\"/drive.txt\")).build()), ImmutableSet.<DriveInfo> of(MapToDriveInfoTest.ONE));\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/test/java/org/jclouds/elasticstack/functions/ListOfKeyValuesDelimitedByBlankLinesToListOfMapsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Lists;\n\n@Test(groups = { \"unit\" })\npublic class ListOfKeyValuesDelimitedByBlankLinesToListOfMapsTest {\n\n   private static final ListOfKeyValuesDelimitedByBlankLinesToListOfMaps FN = new ListOfKeyValuesDelimitedByBlankLinesToListOfMaps();\n\n   public void testNone() {\n      assertEquals(FN.apply(\"\"), Lists.newArrayList());\n      assertEquals(FN.apply(\"\\n\\n\\n\"), Lists.newArrayList());\n   }\n\n   public void testOneMap() {\n      assertEquals(FN.apply(\"key1 value1\\nkey2 value2\"),\n            ImmutableList.of(ImmutableMap.of(\"key1\", \"value1\", \"key2\", \"value2\")));\n      assertEquals(FN.apply(\"key1 value1\\nkey2 value2\\n\\n\"),\n            ImmutableList.of(ImmutableMap.of(\"key1\", \"value1\", \"key2\", \"value2\")));\n   }\n\n   public void testValueEncodesNewlines() {\n      assertEquals(FN.apply(\"key1 value1\\\\n\\nkey2 value2\"),\n            ImmutableList.of(ImmutableMap.of(\"key1\", \"value1\\n\", \"key2\", \"value2\")));\n   }\n\n   public void testTwoMaps() {\n      assertEquals(\n            FN.apply(\"key1 value1\\nkey2 value2\\n\\nkey1 v1\\nkey2 v2\"),\n            ImmutableList.of(ImmutableMap.of(\"key1\", \"value1\", \"key2\", \"value2\"),\n                  ImmutableMap.of(\"key1\", \"v1\", \"key2\", \"v2\")));\n      assertEquals(\n            FN.apply(\"key1 value1\\nkey2 value2\\n\\nkey1 v1\\nkey2 v2\\n\\n\"),\n            ImmutableList.of(ImmutableMap.of(\"key1\", \"value1\", \"key2\", \"value2\"),\n                  ImmutableMap.of(\"key1\", \"v1\", \"key2\", \"v2\")));\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/test/java/org/jclouds/elasticstack/functions/ListOfKeyValuesDelimitedByBlankLinesToServerInfoSetTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.elasticstack.domain.Device;\nimport org.jclouds.elasticstack.domain.DriveMetrics;\nimport org.jclouds.elasticstack.domain.NIC;\nimport org.jclouds.elasticstack.domain.ServerInfo;\nimport org.jclouds.elasticstack.domain.ServerMetrics;\nimport org.jclouds.elasticstack.functions.MapToDevices.DeviceToId;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rest.annotations.ApiVersion;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.TypeLiteral;\n\n@Test(groups = { \"unit\" })\npublic class ListOfKeyValuesDelimitedByBlankLinesToServerInfoSetTest {\n\n   private static final ListOfKeyValuesDelimitedByBlankLinesToServerInfoSet FN = Guice.createInjector(\n         new AbstractModule() {\n\n            @Override\n            protected void configure() {\n               bindConstant().annotatedWith(ApiVersion.class).to(\"1.0\");\n               bind(new TypeLiteral<Function<Map<String, String>, List<NIC>>>() {\n               }).to(MapToNICs.class);\n               bind(new TypeLiteral<Function<Map<String, String>, Map<String, ? extends Device>>>() {\n               }).to(MapToDevices.class);\n               bind(new TypeLiteral<Function<Map<String, String>, Map<String, ? extends DriveMetrics>>>() {\n               }).to(MapToDriveMetrics.class);\n               bind(new TypeLiteral<Function<Map<String, String>, ServerMetrics>>() {\n               }).to(MapToServerMetrics.class);\n               bind(new TypeLiteral<Function<Device, String>>() {\n               }).to(DeviceToId.class);\n            }\n\n         }).getInstance(ListOfKeyValuesDelimitedByBlankLinesToServerInfoSet.class);\n\n   public void testNone() {\n      assertEquals(FN.apply(HttpResponse.builder().statusCode(200).message(\"\").payload(\"\").build()), ImmutableSet.<ServerInfo> of());\n      assertEquals(FN.apply(HttpResponse.builder().statusCode(200).message(\"\").payload(\"\\n\\n\").build()),\n            ImmutableSet.<ServerInfo> of());\n      assertEquals(FN.apply(HttpResponse.builder().statusCode(200).message(\"\").build()), ImmutableSet.<ServerInfo> of());\n   }\n\n   public void testOne() {\n      assertEquals(FN.apply(HttpResponse.builder().statusCode(200).message(\"\").payload(MapToServerInfoTest.class\n            .getResourceAsStream(\"/servers.txt\")).build()), ImmutableSet.<ServerInfo> of(MapToServerInfoTest.ONE,\n            MapToServerInfoTest.TWO));\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/test/java/org/jclouds/elasticstack/functions/ListOfKeyValuesDelimitedByBlankLinesToStandardDriveSetTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.elasticstack.domain.StandardDrive;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\n\n@Test(groups = { \"unit\" })\npublic class ListOfKeyValuesDelimitedByBlankLinesToStandardDriveSetTest {\n\n   private static final ListOfKeyValuesDelimitedByBlankLinesToStandardDriveSet FN = Guice.createInjector().getInstance(\n         ListOfKeyValuesDelimitedByBlankLinesToStandardDriveSet.class);\n\n   public void testNone() {\n      assertEquals(FN.apply(HttpResponse.builder().statusCode(200).message(\"\").payload(\"\").build()), ImmutableSet.<StandardDrive> of());\n      assertEquals(FN.apply(HttpResponse.builder().statusCode(200).message(\"\").payload(\"\\n\\n\").build()), ImmutableSet.<StandardDrive> of());\n      assertEquals(FN.apply(HttpResponse.builder().statusCode(200).message(\"\").build()), ImmutableSet.<StandardDrive> of());\n   }\n\n   public void testOne() {\n      assertEquals(FN.apply(HttpResponse.builder().statusCode(200).message(\"\").payload(MapToStandardDriveTest.class\n            .getResourceAsStream(\"/standard_drive.txt\")).build()), ImmutableSet.<StandardDrive> of(MapToStandardDriveTest.ONE));\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/test/java/org/jclouds/elasticstack/functions/ListOfMapsToListOfKeyValuesDelimitedByBlankLinesTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Map;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\n\n@Test(groups = { \"unit\" })\npublic class ListOfMapsToListOfKeyValuesDelimitedByBlankLinesTest {\n\n   private static final ListOfMapsToListOfKeyValuesDelimitedByBlankLines FN = new ListOfMapsToListOfKeyValuesDelimitedByBlankLines();\n\n   public void testNone() {\n      assertEquals(FN.apply(ImmutableList.<Map<String, String>> of()), \"\");\n   }\n\n   public void testOneMap() {\n      assertEquals(\n            FN.apply(ImmutableList.<Map<String, String>> of(ImmutableMap.of(\"key1\", \"value1\", \"key2\", \"value2\"))),\n            \"key1 value1\\nkey2 value2\");\n   }\n\n   public void testValueEncodesNewlines() {\n      assertEquals(\n            FN.apply(ImmutableList.<Map<String, String>> of(ImmutableMap.of(\"key1\", \"value1\\n\", \"key2\", \"value2\"))),\n            \"key1 value1\\\\n\\nkey2 value2\");\n   }\n\n   public void testTwoMaps() {\n      assertEquals(FN.apply(ImmutableList.<Map<String, String>> of(ImmutableMap.of(\"key1\", \"value1\", \"key2\", \"value2\"),\n            ImmutableMap.of(\"key1\", \"v1\", \"key2\", \"v2\"))), \"key1 value1\\nkey2 value2\\n\\nkey1 v1\\nkey2 v2\");\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/test/java/org/jclouds/elasticstack/functions/MapToDriveInfoTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.util.Map;\n\nimport org.jclouds.elasticstack.domain.ClaimType;\nimport org.jclouds.elasticstack.domain.DriveInfo;\nimport org.jclouds.elasticstack.domain.DriveMetrics;\nimport org.jclouds.elasticstack.domain.DriveStatus;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = { \"unit\" })\npublic class MapToDriveInfoTest {\n   public static final DriveInfo ONE = new DriveInfo.Builder()\n         .status(DriveStatus.ACTIVE)\n         .name(\"Ubuntu 10.10 Server Edition Linux 64bit Preinstalled System\")\n         .metrics(\n               new DriveMetrics.Builder().readBytes(4096L).writeBytes(8589938688L).writeRequests(2097153L)\n                     .readRequests(1L).build())\n         .user(\"58ca3c1f-7629-4771-9b71-863f40153ba4\")\n         .encryptionCipher(\"aes-xts-plain\")\n         .uuid(\"b8171d28-755a-4271-b891-7998871a160e\")\n         .claimType(ClaimType.SHARED)\n         .claimed(\n               ImmutableSet.of(\n                     \"00109617-2c6b-424b-9cfa-5b572c17bafe:guest:692cd1c7-a863-4a22-8170-fc6e6feb68af:ide:0:0\",\n                     \"00031836-a624-4b22-bc7d-41ff8977087b:guest:a1414360-7c24-4730-8c97-180bf7775a71:ide:0:0\",\n                     \"0002c6df-a1d2-4d1d-96f0-f95405a28183:guest:386f1cc7-affc-49c1-82a5-2f8e412170e4:ide:0:0\",\n                     \"00031836-a624-4b22-bc7d-41ff8977087b:guest:17b076be-430d-4a76-9df3-b9896fec82a5:ide:0:0\",\n                     \"000663ee-9fb6-4461-90f6-01327a4aff07:guest:f83b519f-feab-42cf-859c-f61495681ada:ide:0:1\"))//\n         .readers(ImmutableSet.of(\"ffffffff-ffff-ffff-ffff-ffffffffffff\"))//\n         .size(8589934592L)//\n         .userMetadata(ImmutableMap.of(\"foo\", \"bar\", \"baz\", \"raz\")).build();\n\n   private static final MapToDriveInfo MAP_TO_DRIVE = new MapToDriveInfo();\n\n   public void testEmptyMapReturnsNull() {\n      assertEquals(MAP_TO_DRIVE.apply(ImmutableMap.<String, String> of()), null);\n   }\n\n   public void testBasics() {\n      DriveInfo expects = new DriveInfo.Builder().name(\"foo\").size(100L).metrics(new DriveMetrics.Builder().build())\n            .build();\n      assertEquals(MAP_TO_DRIVE.apply(ImmutableMap.of(\"name\", \"foo\", \"size\", \"100\")), expects);\n   }\n\n   public void testComplete() throws IOException {\n\n      Map<String, String> input = new ListOfKeyValuesDelimitedByBlankLinesToListOfMaps().apply(\n            Strings2.toStringAndClose(MapToDriveInfoTest.class.getResourceAsStream(\"/drive.txt\"))).get(0);\n\n      assertEquals(MAP_TO_DRIVE.apply(input), ONE);\n\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/test/java/org/jclouds/elasticstack/functions/MapToServerInfoTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.util.Date;\nimport java.util.Map;\n\nimport org.jclouds.elasticstack.domain.DriveMetrics;\nimport org.jclouds.elasticstack.domain.IDEDevice;\nimport org.jclouds.elasticstack.domain.MediaType;\nimport org.jclouds.elasticstack.domain.Model;\nimport org.jclouds.elasticstack.domain.NIC;\nimport org.jclouds.elasticstack.domain.ServerInfo;\nimport org.jclouds.elasticstack.domain.ServerMetrics;\nimport org.jclouds.elasticstack.domain.ServerStatus;\nimport org.jclouds.elasticstack.domain.VNC;\nimport org.jclouds.elasticstack.functions.MapToDevices.DeviceToId;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = { \"unit\" })\npublic class MapToServerInfoTest {\n   public static final ServerInfo ONE = new ServerInfo.Builder()\n         .persistent(true)\n         .uuid(\"f8bee9cd-8e4b-4a05-8593-1314e3bfe49b\")\n         .cpu(2000)\n         .bootDeviceIds(ImmutableSet.of(\"ide:0:0\"))\n         .smp(1)\n         .mem(1024)\n         .status(ServerStatus.ACTIVE)\n         .started(new Date(1291493868L))\n         .user(\"2f6244eb-50bc-4403-847e-f03cc3706a1f\")\n         .name(\"jo\")\n         .vnc(new VNC(\"46.20.114.124\", \"HfHzVmLT\", false))\n         .nics(ImmutableSet.of(new NIC.Builder()\n               .model(Model.E1000)\n               .dhcp(\"46.20.114.124\")\n               .block(\n                     ImmutableList.of(\"tcp/43594\", \"tcp/5902\", \"udp/5060\", \"tcp/5900\", \"tcp/5901\", \"tcp/21\", \"tcp/22\",\n                           \"tcp/23\", \"tcp/25\", \"tcp/110\", \"tcp/143\", \"tcp/43595\")).build()))\n         .devices(\n               ImmutableMap.of(\"ide:0:0\",\n                     new IDEDevice.Builder(0, 0).uuid(\"4af85ed3-0caa-4736-8a26-a33d7de0a122\").build()\n\n               ))\n         .metrics(\n               new ServerMetrics.Builder()\n                     .tx(2550)\n                     .txPackets(31)\n                     .rx(455530)\n                     .rxPackets(7583)\n                     .driveMetrics(\n                           ImmutableMap.of(\"ide:0:0\", new DriveMetrics.Builder().readRequests(11154)\n                                 .readBytes(45686784).writeRequests(3698).writeBytes(15147008).build())).build())\n         .build();\n\n   public static final ServerInfo TWO = new ServerInfo.Builder()\n         .status(ServerStatus.STOPPED)\n         .name(\"Demo\")\n         .mem(1024)\n         .cpu(2000)\n         .persistent(true)\n         .uuid(\"0f962616-2071-4173-be79-7dd084271edf\")\n         .bootDeviceIds(ImmutableSet.of(\"ide:0:0\"))\n         .user(\"2f6244eb-50bc-4403-847e-f03cc3706a1f\")\n         .vnc(new VNC(\"auto\", \"HWbjvrg2\", false))\n         .nics(ImmutableSet.of(new NIC.Builder().model(Model.E1000).dhcp(\"auto\").build()))\n         .devices(\n               ImmutableMap.of(\n                     \"ide:0:0\",\n                     new IDEDevice.Builder(0, 0).uuid(\"853bb98a-4fff-4c2f-a265-97c363f19ea5\")\n                           .mediaType(MediaType.CDROM).build()))\n         .metrics(\n               new ServerMetrics.Builder().driveMetrics(ImmutableMap.of(\"ide:0:0\", new DriveMetrics.Builder().build()))\n                     .build()).build();\n\n   private static final MapToServerInfo MAP_TO_DRIVE = new MapToServerInfo(new MapToDevices(new DeviceToId()),\n         new MapToServerMetrics(new MapToDriveMetrics()), new MapToNICs(\"1.0\"));\n\n\n   private static final MapToServerInfo MAP_TO_DRIVE_2_0 = new MapToServerInfo(new MapToDevices(new DeviceToId()),\n         new MapToServerMetrics(new MapToDriveMetrics()), new MapToNICs(\"2.0\"));\n\n\n   public void testEmptyMapReturnsNull() {\n      assertEquals(MAP_TO_DRIVE.apply(ImmutableMap.<String, String> of()), null);\n   }\n\n   public void testBasics() {\n      ServerInfo expects = new ServerInfo.Builder().name(\"foo\").uuid(\"hello\").vnc(new VNC(\"auto\", null, false))\n            .cpu(1000).mem(2048).metrics(new ServerMetrics.Builder().build()).build();\n      assertEquals(MAP_TO_DRIVE.apply(ImmutableMap.of(\"name\", \"foo\", \"server\", \"hello\", \"vnc:ip\", \"auto\", \"cpu\",\n            \"1000\", \"mem\", \"2048\")), expects);\n   }\n\n   public void testComplete() throws IOException {\n\n      Map<String, String> input = new ListOfKeyValuesDelimitedByBlankLinesToListOfMaps().apply(\n            Strings2.toStringAndClose(MapToServerInfoTest.class.getResourceAsStream(\"/servers.txt\"))).get(0);\n\n      assertEquals(MAP_TO_DRIVE.apply(input), ONE);\n\n   }\n\n   public static final ServerInfo NEW = new ServerInfo.Builder()\n         .persistent(true)\n         .uuid(\"bd98615a-6f74-4d63-ad1e-b13338b9356a\")\n         .cpu(1000)\n         .bootDeviceIds(ImmutableSet.of(\"ide:0:0\"))\n         .smp(1)\n         .mem(512)\n         .status(ServerStatus.ACTIVE)\n         .started(new Date(1292695612))\n         .user(\"2f6244eb-50bc-4403-847e-f03cc3706a1f\")\n         .name(\"adriancole.test\")\n         .vnc(new VNC(\"83.222.249.221\", \"XXXXXXXX\", false))\n         .nics(ImmutableSet.of(new NIC.Builder()\n               .dhcp(\"auto\")\n               .model(Model.E1000)\n               .block(\n                     ImmutableList.of(\"tcp/43594\", \"tcp/5902\", \"udp/5060\", \"tcp/5900\", \"tcp/5901\", \"tcp/21\", \"tcp/22\",\n                           \"tcp/23\", \"tcp/25\", \"tcp/110\", \"tcp/143\", \"tcp/43595\")).build()))\n         .devices(\n               ImmutableMap.of(\"ide:0:0\",\n                     new IDEDevice.Builder(0, 0).uuid(\"403c9a86-0aab-4e47-aa95-e9768021c4c1\").build()\n\n               ))\n         .metrics(\n               new ServerMetrics.Builder().driveMetrics(ImmutableMap.of(\"ide:0:0\", new DriveMetrics.Builder().build()))\n                     .build()).build();\n\n   public void testNew() throws IOException {\n\n      Map<String, String> input = new ListOfKeyValuesDelimitedByBlankLinesToListOfMaps().apply(\n            Strings2.toStringAndClose(MapToServerInfoTest.class.getResourceAsStream(\"/new_server.txt\"))).get(0);\n\n      assertEquals(MAP_TO_DRIVE.apply(input), NEW);\n\n   }\n\n   public void testNew2() throws IOException {\n\n      Map<String, String> input = new ListOfKeyValuesDelimitedByBlankLinesToListOfMaps().apply(\n              Strings2.toStringAndClose(MapToServerInfoTest.class.getResourceAsStream(\"/new_server2.txt\"))).get(0);\n\n      assertEquals(MAP_TO_DRIVE_2_0.apply(input), NEW);\n\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/test/java/org/jclouds/elasticstack/functions/MapToStandardDriveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.util.Map;\n\nimport org.jclouds.elasticstack.domain.ClaimType;\nimport org.jclouds.elasticstack.domain.ImageConversionType;\nimport org.jclouds.elasticstack.domain.MediaType;\nimport org.jclouds.elasticstack.domain.StandardDrive;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = { \"unit\" })\npublic class MapToStandardDriveTest {\n   public static final StandardDrive ONE = new StandardDrive.Builder()\n         .name(\"Windows Web Server 2008 R2\")\n         .uuid(\"11b84345-7169-4279-8038-18d6ba1a7712\")//\n         .claimType(ClaimType.SHARED)\n         .readers(ImmutableSet.of(\"ffffffff-ffff-ffff-ffff-ffffffffffff\"))//\n         .size(4743757824L)//\n         .rawSize(11811160064L)//\n         .format(ImageConversionType.GZIP)//\n         .media(MediaType.DISK)//\n         .build();\n\n   private static final MapToStandardDrive MAP_TO_STANDARD_DRIVE = new MapToStandardDrive();\n\n   public void testEmptyMapReturnsNull() {\n      assertEquals(MAP_TO_STANDARD_DRIVE.apply(ImmutableMap.<String, String> of()), null);\n   }\n\n   public void testBasics() {\n      StandardDrive expects = new StandardDrive.Builder().name(\"foo\").size(100L).media(MediaType.DISK)\n            .format(ImageConversionType.GZIP).rawSize(5L).build();\n      assertEquals(MAP_TO_STANDARD_DRIVE.apply(ImmutableMap.of(\"name\", \"foo\", \"size\", \"100\", \"format\", \"gzip\", \"media\",\n            \"disk\", \"rawsize\", \"5\")), expects);\n   }\n\n   public void testComplete() throws IOException {\n      Map<String, String> input = new ListOfKeyValuesDelimitedByBlankLinesToListOfMaps().apply(\n            Strings2.toStringAndClose(MapToStandardDriveTest.class.getResourceAsStream(\"/standard_drive.txt\"))).get(0);\n      assertEquals(MAP_TO_STANDARD_DRIVE.apply(input), ONE);\n   }\n}\n"
  },
  {
    "path": "apis/elasticstack/src/test/java/org/jclouds/elasticstack/functions/ServerToMapTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.elasticstack.domain.IDEDevice;\nimport org.jclouds.elasticstack.domain.Model;\nimport org.jclouds.elasticstack.domain.NIC;\nimport org.jclouds.elasticstack.domain.Server;\nimport org.jclouds.elasticstack.domain.VNC;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = { \"unit\" })\npublic class ServerToMapTest {\n\n   private static final ServerToMap SERVER_TO_MAP = new ServerToMap(\"1.0\");\n   private static final ServerToMap SERVER_TO_MAP_V2 = new ServerToMap(\"2.0\");\n\n    public void testBasics() {\n      assertEquals(\n            SERVER_TO_MAP.apply(new Server.Builder()\n                  .name(\"TestServer\")\n                  .cpu(2000)\n                  .mem(1024)\n                  .devices(\n                        ImmutableMap.of(\"ide:0:0\",\n                              new IDEDevice.Builder(0, 0).uuid(\"08c92dd5-70a0-4f51-83d2-835919d254df\").build()))\n                  .bootDeviceIds(ImmutableSet.of(\"ide:0:0\")).nics(ImmutableSet.of(new NIC.Builder().model(Model.E1000).\n\n                  build())).vnc(new VNC(null, \"XXXXXXXX\", false)).build()),\n            ImmutableMap\n                  .builder()\n                  .putAll(ImmutableMap.of(\"name\", \"TestServer\", \"cpu\", \"2000\", \"smp\", \"auto\", \"mem\", \"1024\"))\n                  .putAll(\n                        ImmutableMap.of(\"persistent\", \"false\", \"boot\", \"ide:0:0\", \"ide:0:0\",\n                              \"08c92dd5-70a0-4f51-83d2-835919d254df\"))\n                  .putAll(\n                        ImmutableMap.of(\"ide:0:0:media\", \"disk\", \"nic:0:model\", \"e1000\", \"vnc:ip\", \"auto\",\n                              \"password\", \"XXXXXXXX\")).build());\n   }\n\n   public void testWeDontSetMac() {\n      assertEquals(\n            SERVER_TO_MAP.apply(new Server.Builder()\n                  .name(\"TestServer\")\n                  .cpu(2000)\n                  .mem(1024)\n                  .devices(\n                        ImmutableMap.of(\"ide:0:0\",\n                              new IDEDevice.Builder(0, 0).uuid(\"08c92dd5-70a0-4f51-83d2-835919d254df\").build()))\n                  .bootDeviceIds(ImmutableSet.of(\"ide:0:0\"))\n                  .nics(ImmutableSet.of(new NIC.Builder().mac(\"foo\").model(Model.E1000).\n\n                  build())).vnc(new VNC(null, \"XXXXXXXX\", false)).build()),\n            ImmutableMap\n                  .builder()\n                  .putAll(ImmutableMap.of(\"name\", \"TestServer\", \"cpu\", \"2000\", \"smp\", \"auto\", \"mem\", \"1024\"))\n                  .putAll(\n                        ImmutableMap.of(\"persistent\", \"false\", \"boot\", \"ide:0:0\", \"ide:0:0\",\n                              \"08c92dd5-70a0-4f51-83d2-835919d254df\"))\n                  .putAll(\n                        ImmutableMap.of(\"ide:0:0:media\", \"disk\", \"nic:0:model\", \"e1000\", \"vnc:ip\", \"auto\",\n                              \"password\", \"XXXXXXXX\")).build());\n   }\n\n    public void testBasicsV2() {\n      assertEquals(\n            SERVER_TO_MAP_V2.apply(new Server.Builder()\n                  .name(\"TestServer\")\n                  .cpu(2000)\n                  .mem(1024)\n                  .devices(\n                        ImmutableMap.of(\"ide:0:0\",\n                              new IDEDevice.Builder(0, 0).uuid(\"08c92dd5-70a0-4f51-83d2-835919d254df\").build()))\n                  .bootDeviceIds(ImmutableSet.of(\"ide:0:0\")).nics(ImmutableSet.of(new NIC.Builder().model(Model.E1000).\n\n                  build())).vnc(new VNC(null, \"XXXXXXXX\", false)).build()),\n            ImmutableMap\n                  .builder()\n                  .putAll(ImmutableMap.of(\"name\", \"TestServer\", \"cpu\", \"2000\", \"smp\", \"auto\", \"mem\", \"1024\"))\n                  .putAll(\n                        ImmutableMap.of(\"persistent\", \"false\", \"boot\", \"ide:0:0\", \"ide:0:0\",\n                              \"08c92dd5-70a0-4f51-83d2-835919d254df\"))\n                  .putAll(\n                        ImmutableMap.of(\"ide:0:0:media\", \"disk\", \"nic:0:model\", \"e1000\", \"vnc\", \"auto\",\n                              \"password\", \"XXXXXXXX\")).build());\n   }\n\n}\n"
  },
  {
    "path": "apis/elasticstack/src/test/java/org/jclouds/elasticstack/functions/SplitNewlinesTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\nimport java.util.Set;\n\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableSortedSet;\nimport com.google.inject.Guice;\n\n/**\n * Tests behavior of {@code NewlineDelimitedStringHandler}\n */\n@Test(groups = \"unit\")\npublic class SplitNewlinesTest {\n\n   static Function<HttpResponse, Set<String>> createParser() {\n      return Guice.createInjector().getInstance(SplitNewlines.class);\n   }\n\n   public void test() {\n      InputStream is = SplitNewlinesTest.class.getResourceAsStream(\"/uuids.txt\");\n      Set<String> list = createParser().apply(HttpResponse.builder().statusCode(200).message(\"ok\").payload(is).build());\n      assertEquals(list, ImmutableSortedSet.of(\"7e8ab721-81c9-4cb9-a651-4cafbfe1501c\",\n            \"ea6a8fdb-dab3-4d06-86c2-41a5835e6ed9\", \"74744450-d338-4087-b3b8-59b505110a57\"));\n   }\n\n}\n"
  },
  {
    "path": "apis/elasticstack/src/test/java/org/jclouds/elasticstack/handlers/ElasticStackErrorHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.handlers;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.reportMatcher;\nimport static org.easymock.EasyMock.verify;\n\nimport java.net.URI;\n\nimport org.easymock.IArgumentMatcher;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Guice;\n\n@Test(groups = { \"unit\" })\npublic class ElasticStackErrorHandlerTest {\n\n   @Test\n   public void test400MakesIllegalArgumentException() {\n      assertCodeMakes(\"GET\", URI.create(\"https://elasticstack.com/foo\"), 400, \"\", \"Bad Request\",\n            IllegalArgumentException.class);\n   }\n\n   @Test\n   public void test400MakesResourceNotFoundExceptionOnInfo() {\n      assertCodeMakes(\"GET\", URI.create(\"https://elasticstack.com/foo/info\"), 400, \"\", \"\",\n            ResourceNotFoundException.class);\n   }\n\n   @Test\n   public void test400MakesResourceNotFoundExceptionOnMessageNotFound() {\n      assertCodeMakes(\n            \"GET\",\n            URI.create(\"https://elasticstack.com/foo\"),\n            400,\n            \"\",\n            \"errors:system Drive 8f9b42b1-26de-49ad-a3fd-d4fa06524339 could not be found. Please re-validate your entry.\",\n            ResourceNotFoundException.class);\n   }\n\n   @Test\n   public void test401MakesAuthorizationException() {\n      assertCodeMakes(\"GET\", URI.create(\"https://elasticstack.com/foo\"), 401, \"\", \"Unauthorized\",\n            AuthorizationException.class);\n   }\n\n   @Test\n   public void test404MakesResourceNotFoundException() {\n      assertCodeMakes(\"GET\", URI.create(\"https://elasticstack.com/foo\"), 404, \"\", \"Not Found\",\n            ResourceNotFoundException.class);\n   }\n\n   @Test\n   public void test405MakesIllegalArgumentException() {\n      assertCodeMakes(\"GET\", URI.create(\"https://elasticstack.com/foo\"), 405, \"\", \"Method Not Allowed\",\n            IllegalArgumentException.class);\n   }\n\n   @Test\n   public void test409MakesIllegalStateException() {\n      assertCodeMakes(\"GET\", URI.create(\"https://elasticstack.com/foo\"), 409, \"\", \"Conflict\",\n            IllegalStateException.class);\n   }\n\n   private void assertCodeMakes(String method, URI uri, int statusCode, String message, String content,\n         Class<? extends Exception> expected) {\n      assertCodeMakes(method, uri, statusCode, message, \"text/xml\", content, expected);\n   }\n\n   private void assertCodeMakes(String method, URI uri, int statusCode, String message, String contentType,\n         String content, Class<? extends Exception> expected) {\n\n      ElasticStackErrorHandler function = Guice.createInjector().getInstance(ElasticStackErrorHandler.class);\n\n      HttpCommand command = createMock(HttpCommand.class);\n      HttpRequest request = HttpRequest.builder().method(method).endpoint(uri).build();\n      HttpResponse response = HttpResponse.builder().statusCode(statusCode).message(message).payload(content).build();\n      response.getPayload().getContentMetadata().setContentType(contentType);\n\n      expect(command.getCurrentRequest()).andReturn(request).atLeastOnce();\n      command.setException(classEq(expected));\n\n      replay(command);\n\n      function.handleError(command, response);\n\n      verify(command);\n   }\n\n   public static Exception classEq(final Class<? extends Exception> in) {\n      reportMatcher(new IArgumentMatcher() {\n\n         @Override\n         public void appendTo(StringBuffer buffer) {\n            buffer.append(\"classEq(\");\n            buffer.append(in);\n            buffer.append(\")\");\n         }\n\n         @Override\n         public boolean matches(Object arg) {\n            return arg.getClass() == in;\n         }\n\n      });\n      return null;\n   }\n\n}\n"
  },
  {
    "path": "apis/elasticstack/src/test/java/org/jclouds/elasticstack/suppliers/MockStandardDiskImageSupplier.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elasticstack.suppliers;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.transform;\nimport static org.jclouds.util.Strings2.toStringAndClose;\n\nimport java.io.IOException;\nimport java.util.List;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.elasticstack.domain.StandardDrive;\nimport org.jclouds.elasticstack.domain.WellKnownImage;\nimport org.jclouds.elasticstack.functions.ListOfKeyValuesDelimitedByBlankLinesToListOfMaps;\nimport org.jclouds.elasticstack.functions.MapToStandardDrive;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Throwables;\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Mock {@link WellKnownImageSupplier} to be used in tests.\n */\n@Singleton\npublic class MockStandardDiskImageSupplier implements WellKnownImageSupplier {\n\n   private final Function<StandardDrive, WellKnownImage> standardDriveToWellKnownImage;\n   private final ListOfKeyValuesDelimitedByBlankLinesToListOfMaps mapConverter;\n   private final MapToStandardDrive mapToStandardDrive;\n   \n   @Inject\n   public MockStandardDiskImageSupplier(Function<StandardDrive, WellKnownImage> standardDriveToWellKnownImage,\n         ListOfKeyValuesDelimitedByBlankLinesToListOfMaps mapConverter, MapToStandardDrive mapToStandardDrive) {\n      this.standardDriveToWellKnownImage = checkNotNull(standardDriveToWellKnownImage, \"standardDriveToWellKnownImage cannot be null\");\n      this.mapConverter = checkNotNull(mapConverter, \"mapConverter cannot be null\");\n      this.mapToStandardDrive = checkNotNull(mapToStandardDrive, \"mapToStandardDrive cannot be null\");\n   }\n\n   @Override\n   public List<WellKnownImage> get() {\n      try {\n         String mockDrives = toStringAndClose(getClass().getResourceAsStream(\"/standard_drives.txt\"));\n         Iterable<StandardDrive> parsedDrives = transform(mapConverter.apply(mockDrives), mapToStandardDrive);\n         return ImmutableList.copyOf(transform(parsedDrives, standardDriveToWellKnownImage));\n      } catch (IOException ex) {\n         throw Throwables.propagate(ex);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/elasticstack/src/test/resources/create_drive.txt",
    "content": "name Ubuntu 10.10 Server Edition Linux 64bit Preinstalled System\nsize 8589934592\nclaim:type shared\nreaders ffffffff-ffff-ffff-ffff-ffffffffffff\ntags tag1 tag2\nuser:foo bar\nuser:baz raz\navoid avoid1\nencryption:cipher aes-xts-plain"
  },
  {
    "path": "apis/elasticstack/src/test/resources/create_server.txt",
    "content": "name TestServer\ncpu 2000\nsmp auto\nmem 1024\npersistent false\nboot ide:0:0\nide:0:0 08c92dd5-70a0-4f51-83d2-835919d254df\nide:0:0:media disk\nnic:0:model e1000\nvnc:ip auto\npassword XXXXXXXX"
  },
  {
    "path": "apis/elasticstack/src/test/resources/drive.txt",
    "content": "status active\nname Ubuntu 10.10 Server Edition Linux 64bit Preinstalled System\nread:bytes 4096\nuser 58ca3c1f-7629-4771-9b71-863f40153ba4\nencryption:cipher aes-xts-plain\ndrive b8171d28-755a-4271-b891-7998871a160e\nwrite:bytes 8589938688\nclaim:type shared\nclaimed 00109617-2c6b-424b-9cfa-5b572c17bafe:guest:692cd1c7-a863-4a22-8170-fc6e6feb68af:ide:0:0 00031836-a624-4b22-bc7d-41ff8977087b:guest:a1414360-7c24-4730-8c97-180bf7775a71:ide:0:0 0002c6df-a1d2-4d1d-96f0-f95405a28183:guest:386f1cc7-affc-49c1-82a5-2f8e412170e4:ide:0:0 00031836-a624-4b22-bc7d-41ff8977087b:guest:17b076be-430d-4a76-9df3-b9896fec82a5:ide:0:0 000663ee-9fb6-4461-90f6-01327a4aff07:guest:f83b519f-feab-42cf-859c-f61495681ada:ide:0:1\nreaders ffffffff-ffff-ffff-ffff-ffffffffffff\nread:requests 1\nwrite:requests 2097153\nsize 8589934592\nuser:foo bar\nuser:baz raz"
  },
  {
    "path": "apis/elasticstack/src/test/resources/drive_data.txt",
    "content": "name Ubuntu 10.10 Server Edition Linux 64bit Preinstalled System\nsize 8589934592\nclaim:type shared\nreaders ffffffff-ffff-ffff-ffff-ffffffffffff\ntags tag1 tag2\nuser:foo bar\nuser:baz raz"
  },
  {
    "path": "apis/elasticstack/src/test/resources/log4j.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE log4j:configuration SYSTEM \"log4j.dtd\">\n\n    <!--\n        For more configuration infromation and examples see the Apache\n        Log4j website: http://logging.apache.org/log4j/\n    -->\n<log4j:configuration xmlns:log4j=\"http://jakarta.apache.org/log4j/\"\n    debug=\"false\">\n\n    <!-- A time/date based rolling appender -->\n    <appender name=\"WIREFILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds-wire.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n\n    <!-- A time/date based rolling appender -->\n    <appender name=\"FILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n    \n    <!-- A time/date based rolling appender -->\n    <appender name=\"COMPUTEFILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds-compute.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n\n    <!-- A time/date based rolling appender -->\n    <appender name=\"SSHFILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds-ssh.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n\n    <appender name=\"ASYNCCOMPUTE\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"COMPUTEFILE\" />\n    </appender>\n    \n    <appender name=\"ASYNCSSH\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"SSHFILE\" />\n    </appender>\n\n    <appender name=\"ASYNC\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"FILE\" />\n    </appender>\n\n    <appender name=\"ASYNCWIRE\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"WIREFILE\" />\n    </appender>\n\n    <!-- ================ -->\n    <!-- Limit categories -->\n    <!-- ================ -->\n\n    <category name=\"org.jclouds\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNC\" />\n    </category>\n\n    <category name=\"jclouds.headers\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNCWIRE\" />\n    </category>\n    \n    <category name=\"jclouds.ssh\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNCSSH\" />\n    </category>\n    \n    <category name=\"jclouds.wire\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNCWIRE\" />\n    </category>\n\n    <category name=\"jclouds.compute\">\n        <priority value=\"TRACE\" />\n        <appender-ref ref=\"ASYNCCOMPUTE\" />\n    </category>\n    <!-- ======================= -->\n    <!-- Setup the Root category -->\n    <!-- ======================= -->\n\n    <root>\n        <priority value=\"WARN\" />\n    </root>\n\n</log4j:configuration>\n"
  },
  {
    "path": "apis/elasticstack/src/test/resources/new_server.txt",
    "content": "ide:0:0:write:requests 0\nboot ide:0:0\npassword XXXXXXXX\nide:0:0 403c9a86-0aab-4e47-aa95-e9768021c4c1\nide:0:0:read:requests 0\nide:0:0:read:bytes 0\nvnc:ip 83.222.249.221\ntx:packets 0\ntx 0\nrx 0\nsmp 1\nmem 512\nnic:0:model e1000\nstatus active\nstarted 1292695612\nrx:packets 0\nuser 2f6244eb-50bc-4403-847e-f03cc3706a1f\nide:0:0:media disk\nname adriancole.test\npersistent true\nnic:0:block tcp/43594 tcp/5902 udp/5060 tcp/5900 tcp/5901 tcp/21 tcp/22 tcp/23 tcp/25 tcp/110 tcp/143 tcp/43595\nserver bd98615a-6f74-4d63-ad1e-b13338b9356a\nide:0:0:write:bytes 0\ncpu 1000"
  },
  {
    "path": "apis/elasticstack/src/test/resources/new_server2.txt",
    "content": "ide:0:0:write:requests 0\nboot ide:0:0\npassword XXXXXXXX\nide:0:0 403c9a86-0aab-4e47-aa95-e9768021c4c1\nide:0:0:read:requests 0\nide:0:0:read:bytes 0\nvnc auto\nvnc:ip 83.222.249.221\ntx:packets 0\ntx 0\nrx 0\nsmp 1\nmem 512\nnic:0:model e1000\nstatus active\nstarted 1292695612\nrx:packets 0\nuser 2f6244eb-50bc-4403-847e-f03cc3706a1f\nide:0:0:media disk\nname adriancole.test\npersistent true\nnic:0:block tcp/43594 tcp/5902 udp/5060 tcp/5900 tcp/5901 tcp/21 tcp/22 tcp/23 tcp/25 tcp/110 tcp/143 tcp/43595\nserver bd98615a-6f74-4d63-ad1e-b13338b9356a\nide:0:0:write:bytes 0\ncpu 1000"
  },
  {
    "path": "apis/elasticstack/src/test/resources/server2.txt",
    "content": "ide:0:0:write:requests 3698\nboot ide:0:0\npassword HfHzVmLT\nide:0:0 4af85ed3-0caa-4736-8a26-a33d7de0a122\nide:0:0:read:requests 11154\nide:0:0:read:bytes 45686784\nvnc:ip 46.20.114.124\ntx:packets 31\ntx 2550\nrx 455530\nsmp 1\nmem 1024\nnic:0:model e1000\nstatus active\nstarted 1291493868\nrx:packets 7583\nuser 2f6244eb-50bc-4403-847e-f03cc3706a1f\nname jo\npersistent true\nnic:0:block tcp/43594 tcp/5902 udp/5060 tcp/5900 tcp/5901 tcp/21 tcp/22 tcp/23 tcp/25 tcp/110 tcp/143 tcp/43595\nserver f8bee9cd-8e4b-4a05-8593-1314e3bfe49b\nnic:0:dhcp auto\nnic:0:dhcp:ip 46.20.114.124\nide:0:0:write:bytes 15147008\ncpu 2000\n\nstatus stopped\nname Demo\nmem 1024\nboot ide:0:0\npassword HWbjvrg2\npersistent true\nserver 0f962616-2071-4173-be79-7dd084271edf\nsmp auto\nnic:0:dhcp auto\nuser 2f6244eb-50bc-4403-847e-f03cc3706a1f\nnic:0:model e1000\nvnc:ip auto\nide:0:0 853bb98a-4fff-4c2f-a265-97c363f19ea5\ncpu 2000\nide:0:0:media cdrom\n"
  },
  {
    "path": "apis/elasticstack/src/test/resources/servers.txt",
    "content": "ide:0:0:write:requests 3698\nboot ide:0:0\npassword HfHzVmLT\nide:0:0 4af85ed3-0caa-4736-8a26-a33d7de0a122\nide:0:0:read:requests 11154\nide:0:0:read:bytes 45686784\nvnc:ip 46.20.114.124\ntx:packets 31\ntx 2550\nrx 455530\nsmp 1\nmem 1024\nnic:0:model e1000\nstatus active\nstarted 1291493868\nrx:packets 7583\nuser 2f6244eb-50bc-4403-847e-f03cc3706a1f\nname jo\npersistent true\nnic:0:block tcp/43594 tcp/5902 udp/5060 tcp/5900 tcp/5901 tcp/21 tcp/22 tcp/23 tcp/25 tcp/110 tcp/143 tcp/43595\nserver f8bee9cd-8e4b-4a05-8593-1314e3bfe49b\nnic:0:dhcp 46.20.114.124\nide:0:0:write:bytes 15147008\ncpu 2000\n\nstatus stopped\nname Demo\nmem 1024\nboot ide:0:0\npassword HWbjvrg2\npersistent true\nserver 0f962616-2071-4173-be79-7dd084271edf\nsmp auto\nnic:0:dhcp auto\nuser 2f6244eb-50bc-4403-847e-f03cc3706a1f\nnic:0:model e1000\nvnc:ip auto\nide:0:0 853bb98a-4fff-4c2f-a265-97c363f19ea5\ncpu 2000\nide:0:0:media cdrom\n"
  },
  {
    "path": "apis/elasticstack/src/test/resources/standard_drive.txt",
    "content": "claim:type shared\ndrive 11b84345-7169-4279-8038-18d6ba1a7712\nformat gzip\nmedia disk\nname Windows Web Server 2008 R2\nrawsize 11811160064\nreaders ffffffff-ffff-ffff-ffff-ffffffffffff\nsize 4743757824"
  },
  {
    "path": "apis/elasticstack/src/test/resources/standard_drives.txt",
    "content": "claim:type shared\ndrive ce85ef47-9794-4ed7-a8bd-af902ec0eddc\nformat gzip\nmedia disk\nname Debian Linux 7.4 (Wheezy)\nrawsize 1073741824\nreaders ffffffff-ffff-ffff-ffff-ffffffffffff\nsize 184549376\n\nclaim:type shared\ndrive 82890da7-a036-4427-ac24-caea6c644a2f\nformat gzip\nmedia disk\nname Ubuntu 14.04 LTS (Trusty Tahr)\nrawsize 1073741824\nreaders ffffffff-ffff-ffff-ffff-ffffffffffff\nsize 264241152\n\nclaim:type shared\ndrive 62f512cd-82c7-498e-88d8-a09ac2ef20e7\nformat gzip\nmedia disk\nname Ubuntu Linux 12.04.1 LTS (Precise Pangolin)\nrawsize 1073741824\nreaders ffffffff-ffff-ffff-ffff-ffffffffffff\nsize 201326592\n\nclaim:type shared\ndrive 4f31382b-5098-4610-8993-bbebb844febd\nformat gzip\nmedia disk\nname Ubuntu Linux 13.10 (Saucy Salamander)\nrawsize 1073741824\nreaders ffffffff-ffff-ffff-ffff-ffffffffffff\nsize 230686720\n\nclaim:type shared\ndrive cdea53be-2511-4c91-9779-f6421f623a49\nformat gzip\nmedia disk\nname Windows Server 2012\nrawsize 15032385536\nreaders ffffffff-ffff-ffff-ffff-ffffffffffff\nsize 7671382016\n\nclaim:type shared\ndrive 7b9807cc-3c92-425f-878c-1d45927f3f9c\nformat gzip\nmedia disk\nname Windows Server 2012 + SQL\nrawsize 32212254720\nreaders ffffffff-ffff-ffff-ffff-ffffffffffff\nsize 17192452096\n\nclaim:type shared\ndrive 61ef248d-6616-4378-9702-9101870741d2\nformat gzip\nmedia disk\nname Windows Server 2012 R2\nrawsize 10737418240\nreaders ffffffff-ffff-ffff-ffff-ffffffffffff\nsize 5368709120\n\nclaim:type shared\ndrive 6c0c3072-f55f-4dd2-9308-951dacf41ce3\nformat gzip\nmedia disk\nname Windows Standard 2008 R2\nrawsize 9663676416\nreaders ffffffff-ffff-ffff-ffff-ffffffffffff\nsize 4345298944\n\nclaim:type shared\ndrive 63677762-4423-464f-92fd-5c43d449a716\nformat gzip\nmedia disk\nname Windows Standard 2008 R2 + SQL\nrawsize 20401094656\nreaders ffffffff-ffff-ffff-ffff-ffffffffffff\nsize 14050918400\n\nclaim:type shared\ndrive 11b84345-7169-4279-8038-18d6ba1a7712\nformat gzip\nmedia disk\nname Windows Web Server 2008 R2\nrawsize 11811160064\nreaders ffffffff-ffff-ffff-ffff-ffffffffffff\nsize 4743757824\n\nclaim:type shared\ndrive b23e81b9-103e-4f9d-8ce5-b57bb529007c\nformat gzip\nmedia disk\nname Windows Web Server 2008 R2 + SQL\nrawsize 20401094656\nreaders ffffffff-ffff-ffff-ffff-ffffffffffff\nsize 14357102592\n\nclaim:type shared\ndrive 8d5c93b8-e4e4-4943-b41e-873576b7fcd1\nformat gzip\nmedia disk\nname centOS Linux 6.5\nrawsize 1073741824\nreaders ffffffff-ffff-ffff-ffff-ffffffffffff\nsize 218103808\n\nclaim:type shared\ndrive 65cb106c-3dff-4f27-9607-f25bbe0a3fc6\nmedia cdrom\nname Debian 7.4 DVD\nreaders ffffffff-ffff-ffff-ffff-ffffffffffff\nsize 3955228672\n\nclaim:type shared\ndrive 8eeaa0d5-9696-4fb2-b34e-ccca28f54138\nmedia cdrom\nname Fedora 19 Install DVD\nreaders ffffffff-ffff-ffff-ffff-ffffffffffff\nsize 4445962240\n\nclaim:type shared\ndrive 4d0971b5-9780-4b42-a0a0-ea06a0669b8b\nmedia cdrom\nname Fedora 20 Install DVD\nreaders ffffffff-ffff-ffff-ffff-ffffffffffff\nsize 4605345792\n\nclaim:type shared\ndrive 07a08d47-1f24-4c99-a080-ea6b38502c66\nmedia cdrom\nname FreeBSD 10.0 DVD\nreaders ffffffff-ffff-ffff-ffff-ffffffffffff\nsize 2487222272\n\nclaim:type shared\ndrive 321eaeb7-a5a5-4ffd-9a62-db1d0ffd133f\nmedia cdrom\nname FreeBSD 9.2 DVD\nreaders ffffffff-ffff-ffff-ffff-ffffffffffff\nsize 2554331136\n\nclaim:type shared\ndrive cf0dfc73-2ab2-4317-a515-698ed4097c90\nmedia cdrom\nname Knoppix 7.2 DVD\nreaders ffffffff-ffff-ffff-ffff-ffffffffffff\nsize 4114612224\n\nclaim:type shared\ndrive 696a3dee-c29d-4bd2-afb9-06e995702b65\nmedia cdrom\nname Linux Mint 16 (Petra) DVD\nreaders ffffffff-ffff-ffff-ffff-ffffffffffff\nsize 1329594368\n\nclaim:type shared\ndrive 3f9ddec5-0f9e-4879-85fb-e412abe0cb37\nmedia cdrom\nname Microsoft SQL Express 2012\nreaders ffffffff-ffff-ffff-ffff-ffffffffffff\nsize 5507121152\n\nclaim:type shared\ndrive e58ad21f-c53f-47a1-95bd-c6d614a59d2d\nmedia cdrom\nname System Rescue CD 4.0.1\nreaders ffffffff-ffff-ffff-ffff-ffffffffffff\nsize 473956352\n\nclaim:type shared\ndrive 7fed7f41-7af7-42d9-bbf6-d96427757bc4\nmedia cdrom\nname Ubuntu 12.04.4 Desktop DVD\nreaders ffffffff-ffff-ffff-ffff-ffffffffffff\nsize 771751936\n\nclaim:type shared\ndrive 50f8aa7a-090e-413a-8be9-e0ef498b7012\nmedia cdrom\nname Ubuntu 12.04.4 Server DVD\nreaders ffffffff-ffff-ffff-ffff-ffffffffffff\nsize 713031680\n\nclaim:type shared\ndrive a8e87123-1d88-4bd4-ba60-3a42248f7bc0\nmedia cdrom\nname Ubuntu 13.10 Desktop DVD\nreaders ffffffff-ffff-ffff-ffff-ffffffffffff\nsize 926941184\n\nclaim:type shared\ndrive 00798d0a-1081-4590-8b6c-af1f927e209c\nmedia cdrom\nname Ubuntu 13.10 Server DVD\nreaders ffffffff-ffff-ffff-ffff-ffffffffffff\nsize 704643072\n\nclaim:type shared\ndrive 92f4a7e9-daa2-45f1-967c-cf460cf5bca1\nmedia cdrom\nname Ubuntu 14.04 LTS Desktop Live CD\nreaders ffffffff-ffff-ffff-ffff-ffffffffffff\nsize 1010827264\n\nclaim:type shared\ndrive 9dfbbe29-5352-415a-9f7c-70ec7409b684\nmedia cdrom\nname Ubuntu 14.04 LTS Server Install CD\nreaders ffffffff-ffff-ffff-ffff-ffffffffffff\nsize 591396864\n\nclaim:type shared\ndrive 5a4419f8-6c39-490c-87e9-21e33a1c8add\nmedia cdrom\nname Virtio Drivers 1.74\nreaders ffffffff-ffff-ffff-ffff-ffffffffffff\nsize 62914560\n\nclaim:type shared\ndrive 554f5ed7-811a-400d-9f96-3f829a2bc145\nmedia cdrom\nname Windows 2012 R2 Evaluation CD\nreaders ffffffff-ffff-ffff-ffff-ffffffffffff\nsize 5368709120\n\nclaim:type shared\ndrive 6cf6b5e4-f54f-4525-876b-d07123791880\nmedia cdrom\nname Windows Server 2008 R2 Trial Install CD\nreaders ffffffff-ffff-ffff-ffff-ffffffffffff\nsize 3170893824\n\nclaim:type shared\ndrive f89af28e-ff00-4fc9-a7ed-22e7fa5a88db\nmedia cdrom\nname Windows Server 2008 Trial Install CD\nreaders ffffffff-ffff-ffff-ffff-ffffffffffff\nsize 2663383040\n\nclaim:type shared\ndrive 0cc82095-a967-4e93-af04-9e265fbb4251\nmedia cdrom\nname Windows Server 2012 Install CD\nreaders ffffffff-ffff-ffff-ffff-ffffffffffff\nsize 3695181824\n\nclaim:type shared\ndrive dde6f196-a4bd-4ca7-b631-4d84d69b9490\nmedia cdrom\nname Windows Server 2012 R2 Install CD\nreaders ffffffff-ffff-ffff-ffff-ffffffffffff\nsize 4479516672\n\nclaim:type shared\ndrive 7aead6d3-c3e6-4940-85c7-f5ee61f6ef2b\nmedia cdrom\nname Windows Web Server 2008 Trial Install CD\nreaders ffffffff-ffff-ffff-ffff-ffffffffffff\nsize 2248146944\n\nclaim:type shared\ndrive 312ccda0-c3b2-4cac-911b-68b82a498075\nmedia cdrom\nname arch Linux 2014-03-01\nreaders ffffffff-ffff-ffff-ffff-ffffffffffff\nsize 553648128\n\nclaim:type shared\ndrive f42919f6-f535-44cd-bc9f-6bb6e44d05d8\nmedia cdrom\nname centOS 6.5 Live DVD\nreaders ffffffff-ffff-ffff-ffff-ffffffffffff\nsize 1874853888"
  },
  {
    "path": "apis/elasticstack/src/test/resources/standard_drives_uuids.txt",
    "content": "ce85ef47-9794-4ed7-a8bd-af902ec0eddc\n82890da7-a036-4427-ac24-caea6c644a2f\n62f512cd-82c7-498e-88d8-a09ac2ef20e7\n4f31382b-5098-4610-8993-bbebb844febd\ncdea53be-2511-4c91-9779-f6421f623a49\n7b9807cc-3c92-425f-878c-1d45927f3f9c\n61ef248d-6616-4378-9702-9101870741d2\n6c0c3072-f55f-4dd2-9308-951dacf41ce3\n63677762-4423-464f-92fd-5c43d449a716\n11b84345-7169-4279-8038-18d6ba1a7712\nb23e81b9-103e-4f9d-8ce5-b57bb529007c\n8d5c93b8-e4e4-4943-b41e-873576b7fcd1\n65cb106c-3dff-4f27-9607-f25bbe0a3fc6\n8eeaa0d5-9696-4fb2-b34e-ccca28f54138\n4d0971b5-9780-4b42-a0a0-ea06a0669b8b\n07a08d47-1f24-4c99-a080-ea6b38502c66\n321eaeb7-a5a5-4ffd-9a62-db1d0ffd133f\ncf0dfc73-2ab2-4317-a515-698ed4097c90\n696a3dee-c29d-4bd2-afb9-06e995702b65\n3f9ddec5-0f9e-4879-85fb-e412abe0cb37\ne58ad21f-c53f-47a1-95bd-c6d614a59d2d\n7fed7f41-7af7-42d9-bbf6-d96427757bc4\n50f8aa7a-090e-413a-8be9-e0ef498b7012\na8e87123-1d88-4bd4-ba60-3a42248f7bc0\n00798d0a-1081-4590-8b6c-af1f927e209c\n92f4a7e9-daa2-45f1-967c-cf460cf5bca1\n9dfbbe29-5352-415a-9f7c-70ec7409b684\n5a4419f8-6c39-490c-87e9-21e33a1c8add\n554f5ed7-811a-400d-9f96-3f829a2bc145\n6cf6b5e4-f54f-4525-876b-d07123791880\nf89af28e-ff00-4fc9-a7ed-22e7fa5a88db\n0cc82095-a967-4e93-af04-9e265fbb4251\ndde6f196-a4bd-4ca7-b631-4d84d69b9490\n7aead6d3-c3e6-4940-85c7-f5ee61f6ef2b\n312ccda0-c3b2-4cac-911b-68b82a498075\nf42919f6-f535-44cd-bc9f-6bb6e44d05d8"
  },
  {
    "path": "apis/elasticstack/src/test/resources/uuids.txt",
    "content": "7e8ab721-81c9-4cb9-a651-4cafbfe1501c\nea6a8fdb-dab3-4d06-86c2-41a5835e6ed9\n74744450-d338-4087-b3b8-59b505110a57\n"
  },
  {
    "path": "apis/filesystem/README.txt",
    "content": "#\n# The jclouds API for accessing a local filesystem as a blobstore.\n#\n# TODO: Implementation status.\n# TODO: Supported features.\n# TODO: Usage example.\n"
  },
  {
    "path": "apis/filesystem/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.filesystem.*;version=\"${project.version}\";-noimport:=true"
  },
  {
    "path": "apis/filesystem/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.api</groupId>\n  <artifactId>filesystem</artifactId>\n  <name>jclouds filesystem core</name>\n  <description>jclouds components to access filesystem</description>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-blobstore</artifactId>\n      <version>${project.version}</version>\n      <type>jar</type>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-blobstore</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-log4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <build>\n    <plugins>\n      <plugin>\n        <groupId>org.apache.maven.plugins</groupId>\n        <artifactId>maven-surefire-plugin</artifactId>\n        <executions>\n          <execution>\n            <id>integration</id>\n            <phase>integration-test</phase>\n            <goals>\n              <goal>test</goal>\n            </goals>\n            <configuration>\n              <threadCount>1</threadCount>\n              <excludes>\n                <exclude>**/*LiveTest.java</exclude>\n                <exclude>**/Base*Test.java</exclude>\n              </excludes>\n              <includes>\n                <include>**/*IntegrationTest.java</include>\n              </includes>\n              <systemPropertyVariables>\n                <jclouds.blobstore.httpstream.url>${jclouds.blobstore.httpstream.url}</jclouds.blobstore.httpstream.url>\n                <jclouds.blobstore.httpstream.md5>${jclouds.blobstore.httpstream.md5}</jclouds.blobstore.httpstream.md5>\n              </systemPropertyVariables>\n            </configuration>\n          </execution>\n        </executions>\n      </plugin>\n    </plugins>\n  </build>\n\n</project>\n\n"
  },
  {
    "path": "apis/filesystem/src/main/java/org/jclouds/filesystem/FilesystemApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.filesystem;\n\nimport static org.jclouds.filesystem.reference.FilesystemConstants.PROPERTY_AUTO_DETECT_CONTENT_TYPE;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.apis.internal.BaseApiMetadata;\nimport org.jclouds.blobstore.BlobStoreContext;\nimport org.jclouds.filesystem.config.FilesystemBlobStoreContextModule;\n\nimport com.google.auto.service.AutoService;\nimport org.jclouds.rest.internal.BaseHttpApiMetadata;\n\n/**\n * Implementation of {@link ApiMetadata} for jclouds Filesystem-based BlobStore\n */\n@AutoService(ApiMetadata.class)\npublic class FilesystemApiMetadata extends BaseApiMetadata {\n\n   @Override\n   public Builder toBuilder() {\n      return new Builder().fromApiMetadata(this);\n   }\n\n   public FilesystemApiMetadata() {\n      super(new Builder());\n   }\n\n   protected FilesystemApiMetadata(Builder builder) {\n      super(builder);\n   }\n\n   @Override\n   public Properties getDefaultProperties() {\n      Properties properties = BaseHttpApiMetadata.defaultProperties();\n      properties.setProperty(PROPERTY_AUTO_DETECT_CONTENT_TYPE, \"false\");\n      return properties;\n   }\n\n   public static class Builder extends BaseApiMetadata.Builder<Builder> {\n\n      protected Builder() {\n         id(\"filesystem\")\n         .name(\"Filesystem-based BlobStore\")\n         .identityName(\"Unused\")\n         .defaultEndpoint(\"http://localhost/transient\")\n         .defaultIdentity(System.getProperty(\"user.name\"))\n         .defaultCredential(\"bar\")\n         .version(\"1\")\n         .documentation(URI.create(\"http://www.jclouds.org/documentation/userguide/blobstore-guide\"))\n         .defaultProperties(FilesystemApiMetadata.defaultProperties())\n         .view(BlobStoreContext.class)\n         .defaultModule(FilesystemBlobStoreContextModule.class);\n      }\n\n      @Override\n      public FilesystemApiMetadata build() {\n         return new FilesystemApiMetadata(this);\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/filesystem/src/main/java/org/jclouds/filesystem/config/FilesystemBlobStoreContextModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.filesystem.config;\n\nimport static org.jclouds.filesystem.util.Utils.isWindows;\n\nimport org.jclouds.blobstore.BlobRequestSigner;\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.LocalBlobRequestSigner;\nimport org.jclouds.blobstore.LocalStorageStrategy;\nimport org.jclouds.blobstore.attr.ConsistencyModel;\nimport org.jclouds.blobstore.config.BlobStoreObjectModule;\nimport org.jclouds.blobstore.config.LocalBlobStore;\nimport org.jclouds.blobstore.util.BlobUtils;\nimport org.jclouds.filesystem.predicates.validators.FilesystemBlobKeyValidator;\nimport org.jclouds.filesystem.predicates.validators.FilesystemContainerNameValidator;\nimport org.jclouds.filesystem.predicates.validators.internal.FilesystemBlobKeyValidatorImpl;\nimport org.jclouds.filesystem.predicates.validators.internal.FilesystemContainerNameValidatorImpl;\nimport org.jclouds.filesystem.strategy.internal.FilesystemStorageStrategyImpl;\nimport org.jclouds.filesystem.util.internal.FileSystemBlobUtilsImpl;\n\nimport com.google.inject.AbstractModule;\n\npublic class FilesystemBlobStoreContextModule extends AbstractModule {\n\n   @Override\n   protected void configure() {\n      bind(BlobStore.class).to(LocalBlobStore.class);\n      install(new BlobStoreObjectModule());\n      if (isWindows()) {\n         bind(ConsistencyModel.class).toInstance(ConsistencyModel.EVENTUAL);\n      } else {\n         bind(ConsistencyModel.class).toInstance(ConsistencyModel.STRICT);\n      }\n      bind(LocalStorageStrategy.class).to(FilesystemStorageStrategyImpl.class);\n      bind(BlobUtils.class).to(FileSystemBlobUtilsImpl.class);\n      bind(FilesystemBlobKeyValidator.class).to(FilesystemBlobKeyValidatorImpl.class);\n      bind(FilesystemContainerNameValidator.class).to(FilesystemContainerNameValidatorImpl.class);\n      bind(BlobRequestSigner.class).to(LocalBlobRequestSigner.class);\n   }\n\n}\n"
  },
  {
    "path": "apis/filesystem/src/main/java/org/jclouds/filesystem/predicates/validators/FilesystemBlobKeyValidator.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.filesystem.predicates.validators;\n\nimport org.jclouds.predicates.Validator;\n\n/**\n * Validates name for filesystem container blob keys\n *\n * @see org.jclouds.rest.InputParamValidator\n * @see org.jclouds.predicates.Validator\n */\npublic abstract class FilesystemBlobKeyValidator extends Validator<String> {\n}\n"
  },
  {
    "path": "apis/filesystem/src/main/java/org/jclouds/filesystem/predicates/validators/FilesystemContainerNameValidator.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.filesystem.predicates.validators;\n\nimport org.jclouds.predicates.Validator;\n\n/**\n * Validates container name for filesystem provider\n *\n * @see org.jclouds.rest.InputParamValidator\n * @see org.jclouds.predicates.Validator\n */\npublic abstract class FilesystemContainerNameValidator extends Validator<String> {\n}\n"
  },
  {
    "path": "apis/filesystem/src/main/java/org/jclouds/filesystem/predicates/validators/internal/FilesystemBlobKeyValidatorImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.filesystem.predicates.validators.internal;\n\nimport org.jclouds.filesystem.predicates.validators.FilesystemBlobKeyValidator;\n\nimport com.google.inject.Singleton;\n\nimport java.io.File;\nimport java.util.Arrays;\n\n/**\n * Validates name for filesystem container blob keys implementation\n *\n * @see org.jclouds.rest.InputParamValidator\n * @see org.jclouds.predicates.Validator\n */\n@Singleton\npublic class FilesystemBlobKeyValidatorImpl extends FilesystemBlobKeyValidator {\n\n    @Override\n    public void validate(String name) throws IllegalArgumentException {\n        //blob key cannot be null or empty\n        if (name == null || name.length() < 1)\n            throw new IllegalArgumentException(\"Blob key can't be null or empty\");\n\n        //blobkey cannot start with / (or \\ in Windows) character\n        if (name.startsWith(\"\\\\\") || name.startsWith(\"/\"))\n            throw new IllegalArgumentException(\"Blob key '\" + name + \"' cannot start with \\\\ or /\");\n        if (Arrays.asList(name.split(File.separator.equals(\"\\\\\") ? \"\\\\\\\\\" : File.separator)).contains(\"..\"))\n            throw new IllegalArgumentException(\"Blob key '\" + name + \"' cannot contain ../\");\n    }\n\n}\n"
  },
  {
    "path": "apis/filesystem/src/main/java/org/jclouds/filesystem/predicates/validators/internal/FilesystemContainerNameValidatorImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.filesystem.predicates.validators.internal;\n\nimport org.jclouds.filesystem.predicates.validators.FilesystemContainerNameValidator;\n\nimport com.google.inject.Singleton;\n\n/**\n * Validates container name for filesystem provider implementation\n *\n * @see org.jclouds.rest.InputParamValidator\n * @see org.jclouds.predicates.Validator\n */\n@Singleton\npublic class FilesystemContainerNameValidatorImpl extends FilesystemContainerNameValidator {\n\n    @Override\n    public void validate(String name) throws IllegalArgumentException {\n        //container name cannot be null or empty\n        if (name == null || name.length() < 1)\n            throw new IllegalArgumentException(\"Container name can't be null or empty\");\n\n        //container name cannot contains / (or \\ in Windows) character\n        if (name.contains(\"\\\\\") || name.contains(\"/\"))\n            throw new IllegalArgumentException(\"Container name '\" + name + \"' cannot contain \\\\ or /\");\n        if (name.equals(\".\") || name.equals(\"..\"))\n            throw new IllegalArgumentException(\"Container name cannot be . or ..\");\n    }\n\n}\n"
  },
  {
    "path": "apis/filesystem/src/main/java/org/jclouds/filesystem/reference/FilesystemConstants.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.filesystem.reference;\n\n/**\n * Common constants used in filesystem provider\n */\npublic final class FilesystemConstants {\n\n    /** Specify the base directory where provider starts its file operations - must exists */\n    public static final String PROPERTY_BASEDIR = \"jclouds.filesystem.basedir\";\n\n    /** Specify if the Content-Type of a file should be autodetected if it is not set */\n    public static final String PROPERTY_AUTO_DETECT_CONTENT_TYPE = \"jclouds.filesystem.auto-detect-content-type\";\n\n    private FilesystemConstants() {\n        throw new AssertionError(\"intentionally unimplemented\");\n    }\n}\n"
  },
  {
    "path": "apis/filesystem/src/main/java/org/jclouds/filesystem/strategy/internal/FilesystemStorageStrategyImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.filesystem.strategy.internal;\n\nimport static com.google.common.base.Charsets.US_ASCII;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Strings.isNullOrEmpty;\nimport static com.google.common.io.BaseEncoding.base16;\nimport static java.nio.file.Files.createDirectories;\nimport static java.nio.file.Files.getFileAttributeView;\nimport static java.nio.file.Files.getPosixFilePermissions;\nimport static java.nio.file.Files.move;\nimport static java.nio.file.Files.probeContentType;\nimport static java.nio.file.Files.readAttributes;\nimport static java.nio.file.Files.setPosixFilePermissions;\nimport static java.nio.file.Files.newDirectoryStream;\nimport static org.jclouds.filesystem.util.Utils.delete;\nimport static org.jclouds.filesystem.util.Utils.isPrivate;\nimport static org.jclouds.filesystem.util.Utils.isWindows;\nimport static org.jclouds.filesystem.util.Utils.setPrivate;\nimport static org.jclouds.filesystem.util.Utils.setPublic;\nimport static org.jclouds.util.Closeables2.closeQuietly;\n\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.nio.ByteBuffer;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.AccessDeniedException;\nimport java.nio.file.DirectoryStream;\nimport java.nio.file.NoSuchFileException;\nimport java.nio.file.StandardCopyOption;\nimport java.nio.file.Path;\nimport java.nio.file.attribute.BasicFileAttributes;\nimport java.nio.file.attribute.PosixFilePermission;\nimport java.nio.file.attribute.UserDefinedFileAttributeView;\nimport java.util.Collection;\nimport java.util.Date;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.UUID;\nimport java.util.regex.Pattern;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Provider;\n\nimport com.google.common.base.Strings;\nimport org.jclouds.blobstore.ContainerNotFoundException;\nimport org.jclouds.blobstore.KeyNotFoundException;\nimport org.jclouds.blobstore.LocalStorageStrategy;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.BlobAccess;\nimport org.jclouds.blobstore.domain.BlobBuilder;\nimport org.jclouds.blobstore.domain.ContainerAccess;\nimport org.jclouds.blobstore.domain.MutableStorageMetadata;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.domain.StorageType;\nimport org.jclouds.blobstore.domain.Tier;\nimport org.jclouds.blobstore.domain.internal.MutableStorageMetadataImpl;\nimport org.jclouds.blobstore.options.CreateContainerOptions;\nimport org.jclouds.blobstore.options.ListContainerOptions;\nimport org.jclouds.blobstore.reference.BlobStoreConstants;\nimport org.jclouds.domain.Location;\nimport org.jclouds.filesystem.predicates.validators.FilesystemBlobKeyValidator;\nimport org.jclouds.filesystem.predicates.validators.FilesystemContainerNameValidator;\nimport org.jclouds.filesystem.reference.FilesystemConstants;\nimport org.jclouds.filesystem.util.Utils;\nimport org.jclouds.io.ContentMetadata;\nimport org.jclouds.io.Payload;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.annotations.ParamValidators;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Throwables;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Sets;\nimport com.google.common.hash.HashCode;\nimport com.google.common.hash.Hashing;\nimport com.google.common.hash.HashingInputStream;\nimport com.google.common.io.ByteSource;\nimport com.google.common.io.Files;\nimport com.google.common.primitives.Longs;\n\n/**\n * FilesystemStorageStrategyImpl implements a blob store that stores objects\n * on the file system. Content metadata and user attributes are stored in\n * extended attributes if the file system supports them. Directory blobs\n * (blobs that end with a /) cannot have content, but otherwise appear in\n * LIST like normal blobs.\n */\npublic class FilesystemStorageStrategyImpl implements LocalStorageStrategy {\n\n   private static final String XATTR_CACHE_CONTROL = \"user.cache-control\";\n   private static final String XATTR_CONTENT_DISPOSITION = \"user.content-disposition\";\n   private static final String XATTR_CONTENT_ENCODING = \"user.content-encoding\";\n   private static final String XATTR_CONTENT_LANGUAGE = \"user.content-language\";\n   private static final String XATTR_CONTENT_MD5 = \"user.content-md5\";\n   private static final String XATTR_CONTENT_TYPE = \"user.content-type\";\n   private static final String XATTR_EXPIRES = \"user.expires\";\n   private static final String XATTR_STORAGE_TIER = \"user.storage-tier\";\n   private static final String XATTR_USER_METADATA_PREFIX = \"user.user-metadata.\";\n   private static final byte[] DIRECTORY_MD5 =\n           Hashing.md5().hashBytes(new byte[0]).asBytes();\n   private static final Pattern MPU_ETAG_FORMAT = Pattern.compile(\"\\\"[a-f0-9]{32}-\\\\d+\\\"\");\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   protected final Provider<BlobBuilder> blobBuilders;\n   protected final String baseDirectory;\n   protected final boolean autoDetectContentType;\n   protected final FilesystemContainerNameValidator filesystemContainerNameValidator;\n   protected final FilesystemBlobKeyValidator filesystemBlobKeyValidator;\n   private final Supplier<Location> defaultLocation;\n\n   @Inject\n   protected FilesystemStorageStrategyImpl(Provider<BlobBuilder> blobBuilders,\n         @Named(FilesystemConstants.PROPERTY_BASEDIR) String baseDir,\n         @Named(FilesystemConstants.PROPERTY_AUTO_DETECT_CONTENT_TYPE) boolean autoDetectContentType,\n         FilesystemContainerNameValidator filesystemContainerNameValidator,\n         FilesystemBlobKeyValidator filesystemBlobKeyValidator,\n         Supplier<Location> defaultLocation) {\n      this.blobBuilders = checkNotNull(blobBuilders, \"filesystem storage strategy blobBuilders\");\n      this.baseDirectory = checkNotNull(baseDir, \"filesystem storage strategy base directory\");\n      this.autoDetectContentType = autoDetectContentType;\n      this.filesystemContainerNameValidator = checkNotNull(filesystemContainerNameValidator,\n            \"filesystem container name validator\");\n      this.filesystemBlobKeyValidator = checkNotNull(filesystemBlobKeyValidator, \"filesystem blob key validator\");\n      this.defaultLocation = defaultLocation;\n   }\n\n   @Override\n   public boolean containerExists(String container) {\n      filesystemContainerNameValidator.validate(container);\n      return directoryExists(container, null);\n   }\n\n   @Override\n   public Collection<String> getAllContainerNames() {\n      File[] files = new File(buildPathStartingFromBaseDir()).listFiles();\n      if (files == null) {\n         return ImmutableList.of();\n      }\n      ImmutableList.Builder<String> containers = ImmutableList.builder();\n      for (File file : files) {\n         if (file.isDirectory()) {\n            containers.add(file.getName());\n         }\n      }\n      return containers.build();\n   }\n\n   @Override\n   public boolean createContainerInLocation(String container, Location location, CreateContainerOptions options) {\n      // TODO: implement location\n      logger.debug(\"Creating container %s\", container);\n      filesystemContainerNameValidator.validate(container);\n      boolean created = createDirectoryWithResult(container, null);\n      if (created) {\n         setContainerAccess(container, options.isPublicRead() ? ContainerAccess.PUBLIC_READ : ContainerAccess.PRIVATE);\n      }\n      return created;\n   }\n\n   @Override\n   public ContainerAccess getContainerAccess(String container) {\n      filesystemContainerNameValidator.validate(container);\n      File file = new File(buildPathStartingFromBaseDir(container));\n      if (!file.exists()) {\n         throw new ContainerNotFoundException(container, \"in getContainerAccess\");\n      }\n      Path path = file.toPath();\n\n      if ( isWindows() ) {\n         try {\n            if (isPrivate(path)) {\n               return ContainerAccess.PRIVATE;\n            } else {\n               return ContainerAccess.PUBLIC_READ;\n            }\n         } catch (IOException e) {\n            throw new RuntimeException(e);\n         }\n      } else {\n         Set<PosixFilePermission> permissions;\n         try {\n            permissions = getPosixFilePermissions(path);\n         } catch (IOException ioe) {\n            throw Throwables.propagate(ioe);\n         }\n         return permissions.contains(PosixFilePermission.OTHERS_READ)\n               ? ContainerAccess.PUBLIC_READ : ContainerAccess.PRIVATE;\n      }\n   }\n\n   @Override\n   public void setContainerAccess(String container, ContainerAccess access) {\n      filesystemContainerNameValidator.validate(container);\n      Path path = new File(buildPathStartingFromBaseDir(container)).toPath();\n\n      if ( isWindows() ) {\n         try {\n            if (access == ContainerAccess.PRIVATE) {\n               setPrivate(path);\n            } else {\n               setPublic(path);\n            }\n         } catch (IOException e) {\n            throw new RuntimeException(e);\n         }\n      } else {\n         Set<PosixFilePermission> permissions;\n         try {\n            permissions = getPosixFilePermissions(path);\n            if (access == ContainerAccess.PRIVATE) {\n               permissions.remove(PosixFilePermission.OTHERS_READ);\n            } else if (access == ContainerAccess.PUBLIC_READ) {\n               permissions.add(PosixFilePermission.OTHERS_READ);\n            }\n            setPosixFilePermissions(path, permissions);\n         } catch (IOException ioe) {\n            throw Throwables.propagate(ioe);\n         }\n      }\n   }\n\n   @Override\n   public void deleteContainer(String container) {\n      filesystemContainerNameValidator.validate(container);\n      if (!containerExists(container)) {\n         return;\n      }\n      deleteDirectory(container, null);\n   }\n\n   @Override\n   public void clearContainer(final String container) {\n      clearContainer(container, ListContainerOptions.Builder.recursive());\n   }\n\n   @Override\n   public void clearContainer(String container, ListContainerOptions options) {\n      filesystemContainerNameValidator.validate(container);\n      checkArgument(options.getDir() == null || options.getPrefix() == null, \"cannot specify both directory and prefix\");\n      String optsPrefix = Strings.nullToEmpty(options.getDir() == null ? options.getPrefix() : options.getDir());\n      String normalizedOptsPath = normalize(optsPrefix);\n      String basePath = buildPathStartingFromBaseDir(container, normalizedOptsPath);\n      filesystemBlobKeyValidator.validate(basePath);\n      try {\n         File object = new File(basePath);\n         if (object.isFile()) {\n            // To mimic the S3 type blobstores, a prefix for an object blob\n            // should also get deleted\n            delete(object);\n         }\n         else if (object.isDirectory() && (optsPrefix.endsWith(File.separator) || isNullOrEmpty(optsPrefix))) {\n            // S3 blobstores will only match prefixes that end with a trailing slash/file separator\n            // For instance, if we have a blob at /path/1/2/a, a prefix of /path/1/2 will not list /path/1/2/a\n            // but a prefix of /path/1/2/ will\n            File containerFile = openFolder(container + File.separator + normalizedOptsPath);\n            File[] children = containerFile.listFiles();\n            if (null != children) {\n               for (File child : children) {\n                  if (options.isRecursive()) {\n                     Utils.deleteRecursively(child);\n                  } else {\n                     if (child.isFile()) {\n                        Utils.delete(child);\n                     }\n                  }\n               }\n            }\n\n            // Empty dirs in path if they don't have any objects\n            if (!optsPrefix.isEmpty()) {\n               if (options.isRecursive()) {\n                  //first, remove the empty dir. It should be totally empty if it was a\n                  // recursive delete\n                  deleteDirectory(container, optsPrefix);\n               }\n               removeDirectoriesTreeOfBlobKey(container, optsPrefix);\n            }\n         }\n      } catch (IOException e) {\n         logger.error(e, \"An error occurred while clearing container %s\", container);\n         Throwables.propagate(e);\n      }\n   }\n\n   @Override\n   public StorageMetadata getContainerMetadata(String container) {\n      filesystemContainerNameValidator.validate(container);\n      MutableStorageMetadata metadata = new MutableStorageMetadataImpl();\n      metadata.setName(container);\n      metadata.setType(StorageType.CONTAINER);\n      metadata.setLocation(getLocation(container));\n      Path path = new File(buildPathStartingFromBaseDir(container)).toPath();\n      BasicFileAttributes attr;\n      try {\n         attr = readAttributes(path, BasicFileAttributes.class);\n      } catch (NoSuchFileException nsfe) {\n         return null;\n      } catch (IOException e) {\n         throw Throwables.propagate(e);\n      }\n      metadata.setCreationDate(new Date(attr.creationTime().toMillis()));\n      return metadata;\n   }\n\n   @Override\n   public boolean blobExists(String container, String key) {\n      filesystemContainerNameValidator.validate(container);\n      filesystemBlobKeyValidator.validate(key);\n      try {\n         return buildPathAndChecksIfBlobExists(container, key);\n      } catch (IOException e) {\n         logger.error(e, \"An error occurred while checking key %s in container %s\",\n               container, key);\n         throw Throwables.propagate(e);\n      }\n   }\n\n   /**\n    * Returns all the blobs key inside a container\n    *\n    * @param container\n    * @return\n    * @throws IOException\n    */\n   @Override\n   public Iterable<String> getBlobKeysInsideContainer(String container, String prefix, String delimiter) throws IOException {\n      filesystemContainerNameValidator.validate(container);\n      // check if container exists\n      // TODO maybe an error is more appropriate\n      Set<String> blobNames = Sets.newHashSet();\n      if (!containerExists(container)) {\n         return blobNames;\n      }\n\n      File containerFile = openFolder(container);\n      final int containerPathLength = containerFile.getAbsolutePath().length() + 1;\n      if (prefix != null) {\n         // prefix may end with a partial directory so only list the complete parent\n         int index = prefix.lastIndexOf('/');\n         if (index != -1) {\n            containerFile = new File(containerFile, prefix.substring(0, index + 1));\n         }\n      }\n\n      populateBlobKeysInContainer(containerFile, blobNames, prefix, delimiter, new Function<String, String>() {\n         @Override\n         public String apply(String string) {\n            return denormalize(string.substring(containerPathLength));\n         }\n      });\n      return blobNames;\n   }\n\n   @Override\n   public Blob getBlob(final String container, final String key) {\n      filesystemContainerNameValidator.validate(container);\n      filesystemBlobKeyValidator.validate(key);\n      BlobBuilder builder = blobBuilders.get();\n      builder.name(key);\n      File file = getFileForBlobKey(container, key);\n      ByteSource byteSource;\n      boolean isDirectory = false;\n\n      if (getDirectoryBlobSuffix(key) != null) {\n         if (!file.isDirectory()) {\n            // filesystem blobstore does not allow the existence of \"file\" and\n            // \"file/\" and getDirectoryBlobSuffix normalizes \"file/\" to \"file\".\n            // Therefore we need to return null when the normalized file is not\n            // a directory.\n            return null;\n         }\n         logger.debug(\"%s - %s is a directory\", container, key);\n         byteSource = ByteSource.empty();\n         isDirectory = true;\n      } else {\n         byteSource = Files.asByteSource(file);\n      }\n      try {\n         String cacheControl = null;\n         String contentDisposition = null;\n         String contentEncoding = null;\n         String contentLanguage = null;\n         String contentType = isDirectory ? \"application/x-directory\" : null;\n         HashCode hashCode = null;\n         String eTag = null;\n         Date expires = null;\n         Tier tier = Tier.STANDARD;\n         ImmutableMap.Builder<String, String> userMetadata = ImmutableMap.builder();\n\n         UserDefinedFileAttributeView view = getUserDefinedFileAttributeView(file.toPath());\n         if (view != null) {\n            try {\n               Set<String> attributes = ImmutableSet.copyOf(view.list());\n\n               cacheControl = readStringAttributeIfPresent(view, attributes, XATTR_CACHE_CONTROL);\n               contentDisposition = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_DISPOSITION);\n               contentEncoding = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_ENCODING);\n               contentLanguage = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_LANGUAGE);\n               if (!isDirectory) {\n                  contentType = readStringAttributeIfPresent(view, attributes, XATTR_CONTENT_TYPE);\n                  if (contentType == null && autoDetectContentType) {\n                     contentType = probeContentType(file.toPath());\n                  }\n               }\n               if (attributes.contains(XATTR_CONTENT_MD5)) {\n                  ByteBuffer buf = ByteBuffer.allocate(view.size(XATTR_CONTENT_MD5));\n                  view.read(XATTR_CONTENT_MD5, buf);\n                  byte [] etagBytes = buf.array();\n                  if (etagBytes.length == 16) {\n                     // regular object\n                     hashCode = HashCode.fromBytes(buf.array());\n                     eTag = \"\\\"\" + hashCode + \"\\\"\";\n                  } else {\n                     // multi-part object\n                     eTag = new String(etagBytes, US_ASCII);\n                  }\n               }\n               if (attributes.contains(XATTR_EXPIRES)) {\n                  ByteBuffer buf = ByteBuffer.allocate(view.size(XATTR_EXPIRES));\n                  view.read(XATTR_EXPIRES, buf);\n                  buf.flip();\n                  expires = new Date(buf.asLongBuffer().get());\n               }\n               String tierString = readStringAttributeIfPresent(view, attributes, XATTR_STORAGE_TIER);\n               if (tierString != null) {\n                  tier = Tier.valueOf(tierString);\n               }\n               for (String attribute : attributes) {\n                  if (!attribute.startsWith(XATTR_USER_METADATA_PREFIX)) {\n                     continue;\n                  }\n                  String value = readStringAttributeIfPresent(view, attributes, attribute);\n                  userMetadata.put(attribute.substring(XATTR_USER_METADATA_PREFIX.length()), value);\n               }\n            } catch (IOException e) {\n               logger.debug(\"xattrs not supported on %s\", file.toPath());\n            }\n\n            builder.payload(byteSource)\n               .cacheControl(cacheControl)\n               .contentDisposition(contentDisposition)\n               .contentEncoding(contentEncoding)\n               .contentLanguage(contentLanguage)\n               .contentLength(byteSource.size())\n               .contentMD5(hashCode)\n               .eTag(eTag)\n               .contentType(contentType)\n               .expires(expires)\n               .tier(tier)\n               .userMetadata(userMetadata.build());\n         } else {\n            builder.payload(byteSource)\n               .contentLength(byteSource.size())\n               .contentMD5(byteSource.hash(Hashing.md5()).asBytes());\n         }\n      } catch (FileNotFoundException fnfe) {\n         return null;\n      } catch (IOException e) {\n         throw Throwables.propagate(e);\n      }\n      Blob blob = builder.type(isDirectory ? StorageType.FOLDER : StorageType.BLOB).build();\n      blob.getMetadata().setContainer(container);\n      blob.getMetadata().setLastModified(new Date(file.lastModified()));\n      blob.getMetadata().setSize(file.length());\n      if (blob.getPayload().getContentMetadata().getContentMD5() != null)\n         blob.getMetadata().setETag(base16().lowerCase().encode(blob.getPayload().getContentMetadata().getContentMD5()));\n      return blob;\n   }\n\n   private void writeCommonMetadataAttr(UserDefinedFileAttributeView view, Blob blob) throws IOException {\n      ContentMetadata metadata = blob.getMetadata().getContentMetadata();\n      writeStringAttributeIfPresent(view, XATTR_CACHE_CONTROL, metadata.getCacheControl());\n      writeStringAttributeIfPresent(view, XATTR_CONTENT_DISPOSITION, metadata.getContentDisposition());\n      writeStringAttributeIfPresent(view, XATTR_CONTENT_ENCODING, metadata.getContentEncoding());\n      writeStringAttributeIfPresent(view, XATTR_CONTENT_LANGUAGE, metadata.getContentLanguage());\n      writeStringAttributeIfPresent(view, XATTR_CONTENT_TYPE, metadata.getContentType());\n      Date expires = metadata.getExpires();\n      if (expires != null) {\n         ByteBuffer buf = ByteBuffer.allocate(Longs.BYTES).putLong(expires.getTime());\n         buf.flip();\n         view.write(XATTR_EXPIRES, buf);\n      }\n      writeStringAttributeIfPresent(view, XATTR_STORAGE_TIER, blob.getMetadata().getTier().toString());\n      for (Map.Entry<String, String> entry : blob.getMetadata().getUserMetadata().entrySet()) {\n         writeStringAttributeIfPresent(view, XATTR_USER_METADATA_PREFIX + entry.getKey(), entry.getValue());\n      }\n   }\n\n   private String putDirectoryBlob(final String containerName, final Blob blob) throws IOException {\n      String blobKey = blob.getMetadata().getName();\n      ContentMetadata metadata = blob.getMetadata().getContentMetadata();\n      Long contentLength = metadata.getContentLength();\n      if (contentLength != null && contentLength != 0) {\n         throw new IllegalArgumentException(\n                 \"Directory blob cannot have content: \" + blobKey);\n      }\n      File outputFile = getFileForBlobKey(containerName, blobKey);\n      Path outputPath = outputFile.toPath();\n      if (!outputFile.isDirectory() && !outputFile.mkdirs()) {\n         throw new IOException(\"Unable to mkdir: \" + outputPath);\n      }\n\n      UserDefinedFileAttributeView view = getUserDefinedFileAttributeView(outputPath);\n      if (view != null) {\n         try {\n            view.write(XATTR_CONTENT_MD5, ByteBuffer.wrap(DIRECTORY_MD5));\n            writeCommonMetadataAttr(view, blob);\n         } catch (IOException e) {\n            logger.debug(\"xattrs not supported on %s\", outputPath);\n         }\n      } else {\n         logger.warn(\"xattr not supported on %s\", blobKey);\n      }\n\n      return base16().lowerCase().encode(DIRECTORY_MD5);\n   }\n\n   @Override\n   public String putBlob(final String containerName, final Blob blob) throws IOException {\n      return putBlob(containerName, blob, BlobAccess.PRIVATE);\n   }\n\n   @Override\n   public String putBlob(final String containerName, final Blob blob, BlobAccess access) throws IOException {\n      String blobKey = blob.getMetadata().getName();\n      Payload payload = blob.getPayload();\n      filesystemContainerNameValidator.validate(containerName);\n      filesystemBlobKeyValidator.validate(blobKey);\n      if (getDirectoryBlobSuffix(blobKey) != null) {\n         return putDirectoryBlob(containerName, blob);\n      }\n      File outputFile = getFileForBlobKey(containerName, blobKey);\n      // TODO: should we use a known suffix to filter these out during list?\n      String tmpBlobName = blobKey + \"-\" + UUID.randomUUID();\n      File tmpFile = getFileForBlobKey(containerName, tmpBlobName);\n      Path tmpPath = tmpFile.toPath();\n      boolean isMpu = false;\n      if (blob.getMetadata() != null && blob.getMetadata().getETag() != null)\n         isMpu = MPU_ETAG_FORMAT.matcher(blob.getMetadata().getETag()).matches();\n      InputStream inputStream = null;\n      byte[] eTag = null;\n      try {\n         Files.createParentDirs(tmpFile);\n         if (isMpu) {\n            inputStream = payload.openStream();\n            eTag = blob.getMetadata().getETag().getBytes();\n         } else {\n            inputStream = new HashingInputStream(Hashing.md5(), payload.openStream());\n         }\n         long actualSize = Files.asByteSink(tmpFile).writeFrom(inputStream);\n         Long expectedSize = blob.getMetadata().getContentMetadata().getContentLength();\n         if (expectedSize != null && actualSize != expectedSize) {\n            throw new IOException(\"Content-Length mismatch, actual: \" + actualSize +\n                  \" expected: \" + expectedSize);\n         }\n\n         if (!isMpu) {\n            HashCode actualHashCode = ((HashingInputStream) inputStream).hash();\n            HashCode expectedHashCode = payload.getContentMetadata().getContentMD5AsHashCode();\n            if (expectedHashCode != null && !actualHashCode.equals(expectedHashCode)) {\n               throw new IOException(\"MD5 hash code mismatch, actual: \" + actualHashCode +\n                       \" expected: \" + expectedHashCode);\n            }\n            payload.getContentMetadata().setContentMD5(actualHashCode);\n            eTag = actualHashCode.asBytes();\n         }\n\n         // TODO: is this necessary?\n         if (isWindows() && outputFile.exists()) {\n            delete(outputFile);\n         }\n\n         UserDefinedFileAttributeView view = getUserDefinedFileAttributeView(tmpPath);\n         if (view != null) {\n            try {\n               view.write(XATTR_CONTENT_MD5, ByteBuffer.wrap(eTag));\n               writeCommonMetadataAttr(view, blob);\n            } catch (IOException e) {\n               logger.debug(\"xattrs not supported on %s\", tmpPath);\n            }\n         }\n\n         setBlobAccess(containerName, tmpBlobName, access);\n\n         move(tmpPath, outputFile.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);\n         tmpFile = null;\n\n         return base16().lowerCase().encode(eTag);\n      } finally {\n         if (tmpFile != null) {\n            try {\n               delete(tmpFile);\n            } catch (IOException e) {\n               logger.debug(\"Could not delete %s: %s\", tmpFile, e);\n            }\n         }\n         closeQuietly(inputStream);\n         if (payload != null) {\n            payload.release();\n         }\n      }\n   }\n\n   @Override\n   public void removeBlob(final String container, final String blobKey) {\n      filesystemContainerNameValidator.validate(container);\n      filesystemBlobKeyValidator.validate(blobKey);\n      String fileName = buildPathStartingFromBaseDir(container, blobKey);\n      logger.debug(\"Deleting blob %s\", fileName);\n      File fileToBeDeleted = new File(fileName);\n\n      if (fileToBeDeleted.isDirectory()) {\n         try {\n            UserDefinedFileAttributeView view = getUserDefinedFileAttributeView(fileToBeDeleted.toPath());\n            if (view != null) {\n               for (String s : view.list()) {\n                  view.delete(s);\n               }\n            }\n         } catch (IOException e) {\n            logger.debug(\"Could not delete attributes from %s: %s\", fileToBeDeleted, e);\n         }\n      }\n\n      try {\n         delete(fileToBeDeleted);\n      } catch (IOException e) {\n         logger.debug(\"Could not delete %s: %s\", fileToBeDeleted, e);\n      }\n\n      // now examine if the key of the blob is a complex key (with a directory structure)\n      // and eventually remove empty directory\n      removeDirectoriesTreeOfBlobKey(container, blobKey);\n   }\n\n   @Override\n   public BlobAccess getBlobAccess(String containerName, String blobName) {\n      filesystemContainerNameValidator.validate(containerName);\n      filesystemBlobKeyValidator.validate(blobName);\n      if (!new File(buildPathStartingFromBaseDir(containerName)).exists()) {\n         throw new ContainerNotFoundException(containerName, \"in getBlobAccess\");\n      }\n      File file = new File(buildPathStartingFromBaseDir(containerName, blobName));\n      if (!file.exists()) {\n         throw new KeyNotFoundException(containerName, blobName, \"in getBlobAccess\");\n      }\n      Path path = file.toPath();\n\n      if ( isWindows() ) {\n         try {\n            if (isPrivate(path)) {\n               return BlobAccess.PRIVATE;\n            } else {\n               return BlobAccess.PUBLIC_READ;\n            }\n         } catch (IOException e) {\n            throw new RuntimeException(e);\n         }\n      } else {\n         Set<PosixFilePermission> permissions;\n         try {\n            permissions = getPosixFilePermissions(path);\n         } catch (IOException ioe) {\n            throw Throwables.propagate(ioe);\n         }\n         return permissions.contains(PosixFilePermission.OTHERS_READ)\n               ? BlobAccess.PUBLIC_READ : BlobAccess.PRIVATE;\n      }\n   }\n\n   @Override\n   public void setBlobAccess(String container, String name, BlobAccess access) {\n      filesystemContainerNameValidator.validate(container);\n      filesystemBlobKeyValidator.validate(name);\n      Path path = new File(buildPathStartingFromBaseDir(container, name)).toPath();\n      if ( isWindows() ) {\n         try {\n            if (access == BlobAccess.PRIVATE) {\n               setPrivate(path);\n            } else {\n               setPublic(path);\n            }\n         } catch (IOException e) {\n            throw new RuntimeException(e);\n         }\n      } else {\n         Set<PosixFilePermission> permissions;\n         try {\n            permissions = getPosixFilePermissions(path);\n            if (access == BlobAccess.PRIVATE) {\n               permissions.remove(PosixFilePermission.OTHERS_READ);\n            } else if (access == BlobAccess.PUBLIC_READ) {\n               permissions.add(PosixFilePermission.OTHERS_READ);\n            }\n            setPosixFilePermissions(path, permissions);\n         } catch (IOException ioe) {\n            throw Throwables.propagate(ioe);\n         }\n      }\n   }\n\n   @Override\n   public Location getLocation(final String containerName) {\n      return defaultLocation.get();\n   }\n\n   @Override\n   public String getSeparator() {\n      return \"/\";\n   }\n\n   public boolean createContainer(String container) {\n      filesystemContainerNameValidator.validate(container);\n      return createContainerInLocation(container, null, CreateContainerOptions.NONE);\n   }\n\n   public Blob newBlob(@ParamValidators({ FilesystemBlobKeyValidator.class }) String name) {\n      filesystemBlobKeyValidator.validate(name);\n      return blobBuilders.get().name(name).build();\n   }\n\n   /**\n    * Returns a {@link File} object that links to the blob\n    *\n    * @param container\n    * @param blobKey\n    * @return\n    */\n   public File getFileForBlobKey(String container, String blobKey) {\n      filesystemContainerNameValidator.validate(container);\n      filesystemBlobKeyValidator.validate(blobKey);\n      String fileName = buildPathStartingFromBaseDir(container, blobKey);\n      File blobFile = new File(fileName);\n      return blobFile;\n   }\n\n   public boolean directoryExists(String container, String directory) {\n      return buildPathAndChecksIfDirectoryExists(container, directory);\n   }\n\n   public void createDirectory(String container, String directory) {\n      createDirectoryWithResult(container, directory);\n   }\n\n   public void deleteDirectory(String container, String directory) {\n      // create complete dir path\n      String fullDirPath = buildPathStartingFromBaseDir(container, directory);\n      try {\n         Utils.deleteRecursively(new File(fullDirPath));\n      } catch (IOException ex) {\n         logger.error(\"An error occurred removing directory %s.\", fullDirPath);\n         Throwables.propagate(ex);\n      }\n   }\n\n   public long countBlobs(String container, ListContainerOptions options) {\n      // TODO: honor options\n      try {\n         return Iterables.size(getBlobKeysInsideContainer(container, null, null));\n      } catch (IOException ioe) {\n         throw Throwables.propagate(ioe);\n      }\n   }\n\n   // ---------------------------------------------------------- Private methods\n\n   private boolean buildPathAndChecksIfBlobExists(String... tokens) throws IOException {\n      String path = buildPathStartingFromBaseDir(tokens);\n      File file = new File(path);\n      boolean exists = file.exists() && file.isFile();\n      if (!exists && getDirectoryBlobSuffix(tokens[tokens.length - 1]) != null\n              && file.isDirectory()) {\n         UserDefinedFileAttributeView view = getUserDefinedFileAttributeView(file.toPath());\n         try {\n            exists = view != null && view.list().contains(XATTR_CONTENT_MD5);\n         } catch (IOException ioe) {\n            logger.debug(\"xattrs not supported on %s\", file.toPath());\n         }\n      }\n      return exists;\n   }\n\n   private static String getDirectoryBlobSuffix(String key) {\n      for (String suffix : BlobStoreConstants.DIRECTORY_SUFFIXES) {\n         if (key.endsWith(suffix)) {\n            return suffix;\n         }\n      }\n      return null;\n   }\n\n   private static String directoryBlobName(String key) {\n      String suffix = getDirectoryBlobSuffix(key);\n      if (suffix != null) {\n         if (!BlobStoreConstants.DIRECTORY_BLOB_SUFFIX.equals(suffix)) {\n            key = key.substring(0, key.lastIndexOf(suffix));\n         }\n         return key + BlobStoreConstants.DIRECTORY_BLOB_SUFFIX;\n      }\n      return null;\n   }\n\n   protected UserDefinedFileAttributeView getUserDefinedFileAttributeView(Path path) throws IOException {\n      return getFileAttributeView(path, UserDefinedFileAttributeView.class);\n   }\n\n   /**\n    * Check if the file system resource whose name is obtained applying buildPath on the input path\n    * tokens is a directory, otherwise a RuntimeException is thrown\n    *\n    * @param tokens\n    *           the tokens that make up the name of the resource on the file system\n    */\n   private boolean buildPathAndChecksIfDirectoryExists(String... tokens) {\n      String path = buildPathStartingFromBaseDir(tokens);\n      File file = new File(path);\n      boolean exists = file.exists() || file.isDirectory();\n      return exists;\n   }\n\n   /**\n    * Facility method used to concatenate path tokens normalizing separators\n    *\n    * @param pathTokens\n    *           all the string in the proper order that must be concatenated in order to obtain the\n    *           filename\n    * @return the resulting string\n    */\n   protected String buildPathStartingFromBaseDir(String... pathTokens) {\n      String normalizedToken = removeFileSeparatorFromBorders(normalize(baseDirectory), true);\n      StringBuilder completePath = new StringBuilder(normalizedToken);\n      if (pathTokens != null && pathTokens.length > 0) {\n         for (int i = 0; i < pathTokens.length; i++) {\n            if (pathTokens[i] != null) {\n               normalizedToken = removeFileSeparatorFromBorders(normalize(pathTokens[i]), false);\n               completePath.append(File.separator).append(normalizedToken);\n            }\n         }\n      }\n      return completePath.toString();\n   }\n\n   /**\n    * Convert path to the current OS filesystem standard\n    *\n    * @param path\n    * @return\n    */\n   private static String normalize(String path) {\n      if (null != path) {\n         if (isWindows()) {\n            path = path.replace(\"\\\\\", File.separator);\n         }\n         return path.replace(\"/\", File.separator);\n      }\n      return path;\n   }\n\n   /**\n    * Convert path to jclouds standard (/)\n    */\n   private static String denormalize(String path) {\n      if (null != path && isWindows() ) {\n         return path.replace(\"\\\\\", \"/\");\n      }\n      return path;\n   }\n\n   /**\n    * Remove leading and trailing separator character from the string.\n    *\n    * @param pathToBeCleaned\n    * @param onlyTrailing\n    *           only trailing separator char from path\n    * @return\n    */\n   private String removeFileSeparatorFromBorders(String pathToBeCleaned, boolean onlyTrailing) {\n      if (null == pathToBeCleaned || pathToBeCleaned.equals(\"\"))\n         return pathToBeCleaned;\n\n      int beginIndex = 0;\n      int endIndex = pathToBeCleaned.length();\n\n      // search for separator chars\n      if (!onlyTrailing) {\n         if (pathToBeCleaned.charAt(0) == '/' || (pathToBeCleaned.charAt(0) == '\\\\' && isWindows()))\n            beginIndex = 1;\n      }\n      if (pathToBeCleaned.charAt(pathToBeCleaned.length() - 1) == '/' ||\n            (pathToBeCleaned.charAt(pathToBeCleaned.length() - 1) == '\\\\' && isWindows()))\n         endIndex--;\n\n      return pathToBeCleaned.substring(beginIndex, endIndex);\n   }\n\n   /**\n    * Checks if a directory is empty using a DirectoryStream iterator\n    *\n    * @param directoryPath\n    */\n   private boolean isDirEmpty(String directoryPath) throws IOException {\n      Path path = new File(directoryPath).toPath();\n      try (DirectoryStream<Path> dirStream = newDirectoryStream(path)) {\n         return !dirStream.iterator().hasNext();\n      }\n   }\n\n   /**\n    * Removes recursively the directory structure of a complex blob key, only if the directory is\n    * empty\n    *\n    * @param container\n    * @param blobKey\n    */\n   private void removeDirectoriesTreeOfBlobKey(String container, String blobKey) {\n      String normalizedBlobKey = normalize(blobKey);\n\n      File file = new File(normalizedBlobKey);\n      // TODO\n      // \"/media/data/works/java/amazon/jclouds/master/filesystem/aa/bb/cc/dd/eef6f0c8-0206-460b-8870-352e6019893c.txt\"\n      String parentPath = file.getParent();\n      // no need to manage \"/\" parentPath, because \"/\" cannot be used as start\n      // char of blobkey\n      if (!isNullOrEmpty(parentPath)) {\n         // remove parent directory only it's empty\n         File directory = new File(buildPathStartingFromBaseDir(container, parentPath));\n         // don't delete directory if it's a directory blob\n         try {\n            UserDefinedFileAttributeView view = getUserDefinedFileAttributeView(directory.toPath());\n            if (view == null) { // OSX HFS+ does not support UserDefinedFileAttributeView\n                logger.debug(\"Could not look for attributes from %s\", directory);\n            } else if (!view.list().isEmpty()) {\n               return;\n            }\n         } catch (IOException e) {\n            logger.debug(\"Could not look for attributes from %s: %s\", directory, e);\n         }\n\n         // Don't need to do a listing on the dir, which could be costly. The iterator should be more performant.\n         try {\n            if (isDirEmpty(directory.getPath())) {\n               try {\n                  delete(directory);\n               } catch (IOException e) {\n                  logger.debug(\"Could not delete %s: %s\", directory, e);\n                  return;\n               }\n               // recursively call for removing other path\n               removeDirectoriesTreeOfBlobKey(container, parentPath);\n            }\n         } catch (IOException e) {\n            logger.debug(\"Could not locate directory %s\", directory, e);\n            return;\n         }\n      }\n   }\n\n   private File openFolder(String folderName) throws IOException {\n      String baseFolderName = buildPathStartingFromBaseDir(folderName);\n      File folder = new File(baseFolderName);\n      if (folder.exists()) {\n         if (!folder.isDirectory()) {\n            throw new IOException(\"Resource \" + baseFolderName + \" isn't a folder.\");\n         }\n      }\n      return folder;\n   }\n\n   private static void populateBlobKeysInContainer(File directory, Set<String> blobNames,\n         String prefix, String delimiter, Function<String, String> function) {\n      File[] children = directory.listFiles();\n      if (children == null) {\n         return;\n      }\n      for (File child : children) {\n         String fullPath = function.apply(child.getAbsolutePath());\n         if (child.isFile()) {\n            if (prefix != null && !fullPath.startsWith(prefix)) {\n               continue;\n            }\n            blobNames.add(fullPath);\n         } else if (child.isDirectory()) {\n            // Consider a prefix /a/b/c but we have only descended to path /a.\n            // We need to match the path against the prefix to continue\n            // matching down to /a/b.\n            if (prefix != null && !fullPath.startsWith(prefix) && !prefix.startsWith(fullPath + \"/\")) {\n               continue;\n            }\n            blobNames.add(fullPath + File.separator); // TODO: undo if failures\n            // Skip recursion if the delimiter tells us not to return children.\n            if (delimiter != null && delimiter.equals(\"/\")) {\n               continue;\n            }\n            populateBlobKeysInContainer(child, blobNames, prefix, delimiter, function);\n         }\n      }\n   }\n\n   /**\n    * Creates a directory and returns the result\n    *\n    * @param container\n    * @param directory\n    * @return true if the directory was created, otherwise false\n    */\n   protected boolean createDirectoryWithResult(String container, String directory) {\n      String directoryFullName = buildPathStartingFromBaseDir(container, directory);\n      logger.debug(\"Creating directory %s\", directoryFullName);\n\n      // cannot use directoryFullName, because the following method rebuild\n      // another time the path starting from base directory\n      if (buildPathAndChecksIfDirectoryExists(container, directory)) {\n         logger.debug(\"Directory %s already exists\", directoryFullName);\n         return false;\n      }\n\n      File directoryToCreate = new File(directoryFullName);\n      try {\n         createDirectories(directoryToCreate.toPath());\n      } catch (AccessDeniedException ade) {\n         throw new AuthorizationException(ade);\n      } catch (IOException ioe) {\n         logger.debug(\"Could not create directory: %s\", ioe.getMessage());\n         return false;\n      }\n      return true;\n   }\n\n   /** Read the String representation of filesystem attribute, or return null if not present. */\n   private static String readStringAttributeIfPresent(UserDefinedFileAttributeView view, Set<String> attributes,\n         String name) throws IOException {\n      if (!attributes.contains(name)) {\n         return null;\n      }\n      ByteBuffer buf = ByteBuffer.allocate(view.size(name));\n      view.read(name, buf);\n      return new String(buf.array(), StandardCharsets.UTF_8);\n   }\n\n   /** Write an filesystem attribute, if its value is non-null. */\n   private static void writeStringAttributeIfPresent(UserDefinedFileAttributeView view, String name, String value) throws IOException {\n      if (value != null) {\n         view.write(name, ByteBuffer.wrap(value.getBytes(StandardCharsets.UTF_8)));\n      }\n   }\n\n   private static void copyStringAttributeIfPresent(UserDefinedFileAttributeView view, String name, Map<String, String> attrs) throws IOException {\n      writeStringAttributeIfPresent(view, name, attrs.get(name));\n   }\n}\n"
  },
  {
    "path": "apis/filesystem/src/main/java/org/jclouds/filesystem/util/Utils.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.filesystem.util;\n\nimport static java.nio.file.FileSystems.getDefault;\n\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.nio.file.AccessDeniedException;\nimport java.nio.file.DirectoryNotEmptyException;\nimport java.nio.file.Files;\nimport java.nio.file.NoSuchFileException;\nimport java.nio.file.Path;\nimport java.nio.file.InvalidPathException;\nimport java.nio.file.attribute.AclEntry;\nimport java.nio.file.attribute.AclEntryPermission;\nimport java.nio.file.attribute.AclEntryType;\nimport java.nio.file.attribute.AclFileAttributeView;\nimport java.nio.file.attribute.UserPrincipal;\nimport java.util.List;\nimport java.util.concurrent.CopyOnWriteArrayList;\nimport java.util.concurrent.TimeUnit;\n\nimport com.google.common.util.concurrent.Uninterruptibles;\n\n/**\n * Utilities for the filesystem blobstore.\n */\npublic class Utils {\n   /** Private constructor for utility class. */\n   private Utils() {\n      // Do nothing\n   }\n\n   /**\n    * Determine if Java is running on a Mac OS\n    */\n   public static boolean isMacOSX() {\n      String osName = System.getProperty(\"os.name\");\n      return osName.contains(\"OS X\");\n   }\n\n   /**\n    * Determine if Java is running on a windows OS\n    */\n   public static boolean isWindows() {\n      return System.getProperty(\"os.name\", \"\").toLowerCase().contains(\"windows\");\n   }\n\n   /** Delete a file or a directory recursively. */\n   public static void deleteRecursively(File file) throws IOException {\n      if (file.isDirectory()) {\n         File[] children = file.listFiles();\n         if (children != null) {\n            for (File child : children) {\n               deleteRecursively(child);\n            }\n         }\n      }\n\n      delete(file);\n   }\n\n   public static void delete(File file) throws IOException {\n      Path path;\n      try {\n         path = file.toPath();\n      } catch (InvalidPathException ipe) {\n         throw new IOException(\"Invalid file: \" + file, ipe);\n      }\n\n      for (int n = 0; n < 10; n++) {\n         try {\n            Files.delete(path);\n            if (Files.exists(path)) {\n               Uninterruptibles.sleepUninterruptibly(200, TimeUnit.MILLISECONDS);\n               continue;\n            }\n            return;\n         } catch (DirectoryNotEmptyException dnee) {\n            // A previous file delete operation did not finish before this call\n            Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);\n            continue;\n         } catch (AccessDeniedException ade) {\n            // The file was locked by antivirus, indexing, or another operation triggered by previous file modification\n            Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);\n            continue;\n         } catch (NoSuchFileException nse) {\n            return; // The file has been eventually deleted after a previous operation that failed. no-op\n         }\n      }\n      // File could not be deleted multiple times. It is very likely locked in another process\n      throw new IOException(\"Could not delete: \" + path);\n   }\n\n   /**\n    * @return Localized name for the \"Everyone\" Windows principal.\n    */\n   public static final String getWindowsEveryonePrincipalName() {\n      if (isWindows()) {\n         try {\n            Process process = new ProcessBuilder(\"whoami\", \"/groups\").start();\n            try {\n               String line;\n               try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {\n                  while ((line = reader.readLine()) != null) {\n                     if (line.indexOf(\"S-1-1-0\") != -1) {\n                        return line.split(\"\\\\s{2,}\")[0];\n                     }\n                  }\n               }\n            } finally {\n               process.destroy();\n            }\n         } catch (IOException e) {\n         }\n      }\n      // Default/fallback value\n      return \"Everyone\";\n   }\n\n   public static final String WINDOWS_EVERYONE = getWindowsEveryonePrincipalName();\n\n   /**\n    * @param path The path to a Windows file or directory.\n    * @return true if path has permissions set to Everyone on windows. The exact permissions are not checked.\n    */\n   public static boolean isPrivate(Path path) throws IOException {\n      UserPrincipal everyone = getDefault().getUserPrincipalLookupService()\n            .lookupPrincipalByName(WINDOWS_EVERYONE);\n      AclFileAttributeView aclFileAttributes = java.nio.file.Files.getFileAttributeView(\n            path, AclFileAttributeView.class);\n      for (AclEntry aclEntry : aclFileAttributes.getAcl()) {\n         if (aclEntry.principal().equals(everyone)) {\n            return false;\n         }\n      }\n      return true;\n   }\n\n   /**\n    * @param path Remove \"Everyone\" from this path's Windows ACL permissions.\n    */\n   public static void setPrivate(Path path) throws IOException {\n      UserPrincipal everyone = getDefault().getUserPrincipalLookupService()\n            .lookupPrincipalByName(WINDOWS_EVERYONE);\n      AclFileAttributeView aclFileAttributes = java.nio.file.Files.getFileAttributeView(\n            path, AclFileAttributeView.class);\n      CopyOnWriteArrayList<AclEntry> aclList = new CopyOnWriteArrayList(aclFileAttributes.getAcl());\n      for (AclEntry aclEntry : aclList) {\n         if (aclEntry.principal().equals(everyone) && aclEntry.type().equals(AclEntryType.ALLOW)) {\n            aclList.remove(aclEntry);\n         }\n      }\n      aclFileAttributes.setAcl(aclList);\n   }\n\n   /**\n    * @param path Add \"Everyone\" with read enabled to this path's Windows ACL permissions.\n    */\n   public static void setPublic(Path path) throws IOException {\n      UserPrincipal everyone = getDefault().getUserPrincipalLookupService()\n            .lookupPrincipalByName(WINDOWS_EVERYONE);\n      AclFileAttributeView aclFileAttributes = java.nio.file.Files.getFileAttributeView(\n            path, AclFileAttributeView.class);\n      List<AclEntry> list = aclFileAttributes.getAcl();\n      list.add(AclEntry.newBuilder().setPrincipal(everyone).setPermissions(\n            AclEntryPermission.READ_DATA,\n            AclEntryPermission.READ_ACL,\n            AclEntryPermission.READ_ATTRIBUTES,\n            AclEntryPermission.READ_NAMED_ATTRS)\n            .setType(AclEntryType.ALLOW)\n            .build());\n      aclFileAttributes.setAcl(list);\n   }\n}\n"
  },
  {
    "path": "apis/filesystem/src/main/java/org/jclouds/filesystem/util/internal/FileSystemBlobUtilsImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.filesystem.util.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Provider;\n\nimport org.jclouds.blobstore.LocalStorageStrategy;\nimport org.jclouds.blobstore.domain.BlobBuilder;\nimport org.jclouds.blobstore.options.ListContainerOptions;\nimport org.jclouds.blobstore.util.BlobUtils;\nimport org.jclouds.filesystem.strategy.internal.FilesystemStorageStrategyImpl;\n\nimport com.google.inject.Inject;\n\n/**\n * Implements the {@link BlobUtils} interfaced and act as a bridge to\n * {@link LocalStorageStrategy} when used inside {@link BlobStore}\n */\npublic class FileSystemBlobUtilsImpl implements BlobUtils {\n\n   protected final FilesystemStorageStrategyImpl storageStrategy;\n   protected final Provider<BlobBuilder> blobBuilders;\n\n   @Inject\n   public FileSystemBlobUtilsImpl(LocalStorageStrategy storageStrategy, Provider<BlobBuilder> blobBuilders) {\n      this.storageStrategy = (FilesystemStorageStrategyImpl) checkNotNull(storageStrategy, \"Filesystem Storage Strategy\");\n      this.blobBuilders = checkNotNull(blobBuilders, \"Filesystem  blobBuilders\");\n   }\n\n   @Override\n   public BlobBuilder blobBuilder() {\n      return blobBuilders.get();\n   }\n\n   @Override\n   public boolean directoryExists(String containerName, String directory) {\n      return storageStrategy.directoryExists(containerName, directory);\n   }\n\n   @Override\n   public void createDirectory(String containerName, String directory) {\n      storageStrategy.createDirectory(containerName, directory);\n   }\n\n   @Override\n   public long countBlobs(String container, ListContainerOptions options) {\n      return storageStrategy.countBlobs(container, options);\n   }\n\n   @Override\n   public void clearContainer(String container, ListContainerOptions options) {\n      storageStrategy.clearContainer(container, options);\n   }\n\n   @Override\n   public void deleteDirectory(String container, String directory) {\n      storageStrategy.deleteDirectory(container, directory);\n   }\n\n}\n"
  },
  {
    "path": "apis/filesystem/src/test/java/org/jclouds/filesystem/FilesystemApiMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.filesystem;\n\nimport org.jclouds.blobstore.internal.BaseBlobStoreApiMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"FilesystemApiMetadataTest\")\npublic class FilesystemApiMetadataTest extends BaseBlobStoreApiMetadataTest {\n\n   public FilesystemApiMetadataTest() {\n      super(new FilesystemApiMetadata());\n   }\n}\n"
  },
  {
    "path": "apis/filesystem/src/test/java/org/jclouds/filesystem/FilesystemBlobStoreTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.filesystem;\n\nimport static com.google.common.io.BaseEncoding.base16;\nimport static org.jclouds.filesystem.util.Utils.isMacOSX;\nimport static org.jclouds.utils.TestUtils.NO_INVOCATIONS;\nimport static org.jclouds.utils.TestUtils.SINGLE_NO_ARG_INVOCATION;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNotSame;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.Assert.fail;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.net.URI;\nimport java.util.Iterator;\nimport java.util.Properties;\nimport java.util.Set;\nimport java.util.concurrent.TimeUnit;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.blobstore.BlobRequestSigner;\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.BlobStoreContext;\nimport org.jclouds.blobstore.ContainerNotFoundException;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.BlobMetadata;\nimport org.jclouds.blobstore.domain.MutableBlobMetadata;\nimport org.jclouds.blobstore.domain.PageSet;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.domain.StorageType;\nimport org.jclouds.blobstore.options.GetOptions;\nimport org.jclouds.blobstore.options.ListContainerOptions;\nimport org.jclouds.filesystem.reference.FilesystemConstants;\nimport org.jclouds.filesystem.util.Utils;\nimport org.jclouds.filesystem.utils.TestUtils;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.io.ByteStreams2;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.payloads.PhantomPayload;\nimport org.jclouds.io.payloads.StringPayload;\nimport org.jclouds.util.Closeables2;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.AfterMethod;\nimport org.testng.annotations.BeforeMethod;\nimport org.testng.annotations.DataProvider;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Sets;\nimport com.google.common.io.ByteSource;\nimport com.google.common.io.Files;\nimport com.google.common.util.concurrent.Uninterruptibles;\nimport com.google.inject.CreationException;\n\n@Test(groups = \"unit\", testName = \"FilesystemBlobStoreTest\", singleThreaded = true)\npublic class FilesystemBlobStoreTest {\n\n    private static final String CONTAINER_NAME = \"fun-blobstore-test\";\n    private static final String TARGET_CONTAINER_NAME = TestUtils.TARGET_BASE_DIR + CONTAINER_NAME;\n    private static final String LOGGING_CONFIG_KEY = \"java.util.logging.config.file\";\n    private static final String LOGGING_CONFIG_VALUE = \"src/main/resources/logging.properties\";\n\n    private static final String PROVIDER = \"filesystem\";\n\n    static {\n        System.setProperty(LOGGING_CONFIG_KEY, LOGGING_CONFIG_VALUE);\n    }\n\n    private BlobStoreContext context = null;\n    private BlobStore blobStore = null;\n\n    @BeforeMethod\n    protected void setUp() throws Exception {\n        // create context for filesystem container\n        Properties prop = new Properties();\n        prop.setProperty(FilesystemConstants.PROPERTY_BASEDIR, TestUtils.TARGET_BASE_DIR);\n        prop.setProperty(FilesystemConstants.PROPERTY_AUTO_DETECT_CONTENT_TYPE, \"false\");\n        context = ContextBuilder.newBuilder(PROVIDER).overrides(prop).build(BlobStoreContext.class);\n        // create a container in the default location\n        blobStore = context.getBlobStore();\n        new File(TestUtils.TARGET_BASE_DIR).mkdir();\n        TestUtils.createResources();\n    }\n\n    @AfterMethod\n    protected void tearDown() throws IOException {\n        context.close();\n        Utils.deleteRecursively(new File(TestUtils.TARGET_BASE_DIR));\n    }\n\n    /**\n     * Checks if context parameters are managed in the correct way\n     */\n    public void testParameters() {\n        // no base directory declared in properties\n        try {\n            Properties props = new Properties();\n            context = ContextBuilder.newBuilder(PROVIDER).overrides(props).build(BlobStoreContext.class);\n            fail(\"No error if base directory is not specified\");\n        } catch (CreationException e) {\n        }\n\n        // no base directory declared in properties\n        try {\n            Properties props = new Properties();\n            props.setProperty(FilesystemConstants.PROPERTY_BASEDIR, null);\n            context = ContextBuilder.newBuilder(PROVIDER).overrides(props).build(BlobStoreContext.class);\n            fail(\"No error if base directory is null in the option\");\n        } catch (NullPointerException e) {\n        }\n    }\n\n    /**\n     * Test of list method of the root context\n     */\n    public void testList_Root() throws IOException {\n        PageSet<? extends StorageMetadata> containersRetrieved;\n        Set<String> containersCreated = Sets.newHashSet();\n\n        // Testing list with no containers\n        containersRetrieved = blobStore.list();\n        assertTrue(containersRetrieved.isEmpty(), \"List operation returns a not empty set of container\");\n\n        // Testing list with some containers\n        String[] containerNames = {\"34343\", \"aaaa\", \"bbbbb\"};\n        containersCreated = Sets.newHashSet();\n        for (String containerName : containerNames) {\n            blobStore.createContainerInLocation(null, containerName);\n            containersCreated.add(containerName);\n        }\n\n        containersRetrieved = blobStore.list();\n        assertEquals(containersCreated.size(), containersRetrieved.size(), \"Different numbers of container\");\n\n        for (StorageMetadata data : containersRetrieved) {\n            String containerName = data.getName();\n            if (!containersCreated.remove(containerName)) {\n                fail(\"Container list contains unexpected value [\" + containerName + \"]\");\n            }\n        }\n        assertTrue(containersCreated.isEmpty(), \"List operation doesn't return all values.\");\n\n        for (String containerName : containerNames) {\n            // delete all creaded containers\n            blobStore.deleteContainer(containerName);\n        }\n        containersRetrieved = blobStore.list();\n        assertTrue(containersRetrieved.isEmpty(), \"List operation returns a not empty set of container\");\n    }\n\n    public void testList_NoOptionSingleContainer() throws IOException {\n        blobStore.createContainerInLocation(null, CONTAINER_NAME);\n        // Testing list for an empty container\n        checkForContainerContent(CONTAINER_NAME, null);\n\n        // creates blobs in first container\n        Set<String> blobsExpected = TestUtils.createBlobsInContainer(CONTAINER_NAME,\n              \"bbb/ccc/ddd/1234.jpg\",\n              \"4rrr.jpg\",\n              \"rrr/sss/788.jpg\",\n              \"xdc/wert.kpg\");\n\n        checkForContainerContent(CONTAINER_NAME, blobsExpected);\n    }\n\n    @Test\n    public void testList_RootNonRecursive() throws IOException {\n        blobStore.createContainerInLocation(null, CONTAINER_NAME);\n        // Testing list for an empty container\n        checkForContainerContent(CONTAINER_NAME, null);\n\n        TestUtils.createBlobsInContainer(CONTAINER_NAME, \"a\");\n        ListContainerOptions options = ListContainerOptions.Builder\n                .withDetails()\n                .inDirectory(\"\");\n        PageSet<? extends StorageMetadata> res = blobStore.list(CONTAINER_NAME, options);\n        assertTrue(res.size() == 1);\n        assertEquals(res.iterator().next().getName(), \"a\");\n    }\n\n    public void testList_NotExistingContainer() {\n        // Testing list for a not existing container\n        try {\n            blobStore.list(CONTAINER_NAME);\n            fail(\"Found a not existing container\");\n        } catch (ContainerNotFoundException e) {\n            // ok if arriver here\n        }\n    }\n\n    public void testList_NoOptionDoubleContainer() throws IOException {\n        final String CONTAINER_NAME2 = \"container2\";\n\n        // create first container\n        blobStore.createContainerInLocation(null, CONTAINER_NAME);\n        // checks for empty container\n        checkForContainerContent(CONTAINER_NAME, null);\n\n        // create second container\n        blobStore.createContainerInLocation(null, CONTAINER_NAME2);\n        // checks for empty\n        checkForContainerContent(CONTAINER_NAME2, null);\n\n        // creates blobs in first container\n\n        Set<String> blobNamesCreatedInContainer1 = TestUtils.createBlobsInContainer(CONTAINER_NAME,\n              \"bbb/ccc/ddd/1234.jpg\",\n              TestUtils.createRandomBlobKey(),\n              \"rrr/sss/788.jpg\",\n              \"xdc/wert.kpg\");\n\n        // creates blobs in second container\n        blobStore.createContainerInLocation(null, CONTAINER_NAME2);\n        Set<String> blobNamesCreatedInContainer2 = TestUtils.createBlobsInContainer(CONTAINER_NAME2,\n              \"asd/bbb/ccc/ddd/1234.jpg\",\n              TestUtils.createRandomBlobKey(),\n              \"rrr/sss/788.jpg\",\n              \"xdc/wert.kpg\");\n\n        // test blobs in first container\n        checkForContainerContent(CONTAINER_NAME, blobNamesCreatedInContainer1);\n        // test blobs in second container\n        checkForContainerContent(CONTAINER_NAME2, blobNamesCreatedInContainer2);\n    }\n\n    public void testList_Subdirectory() throws IOException {\n        blobStore.createContainerInLocation(null, CONTAINER_NAME);\n        // Testing list for an empty container\n        checkForContainerContent(CONTAINER_NAME, null);\n\n        // creates blobs in first container\n        Set<String> blobsExpected = TestUtils.createBlobsInContainer(CONTAINER_NAME,\n              \"bbb/ccc/ddd/1234.jpg\",\n              \"4rrr.jpg\",\n              \"rrr/sss/788.jpg\",\n              \"rrr/wert.kpg\");\n\n        // remove not expected values\n        blobsExpected.remove(\"bbb/ccc/ddd/1234.jpg\");\n        blobsExpected.remove(\"4rrr.jpg\");\n\n        checkForContainerContent(CONTAINER_NAME, \"rrr\", blobsExpected);\n        checkForContainerContent(CONTAINER_NAME, \"rrr/\", blobsExpected);\n    }\n\n    /**\n     * TODO Should throws an exception?\n     */\n    public void testClearContainer_NotExistingContainer() {\n        blobStore.clearContainer(CONTAINER_NAME);\n    }\n\n    public void testClearContainer_NoOptions() throws IOException {\n        final String CONTAINER_NAME2 = \"containerToClear\";\n\n        // create containers\n        blobStore.createContainerInLocation(null, CONTAINER_NAME);\n        blobStore.createContainerInLocation(null, CONTAINER_NAME2);\n\n        // creates blobs in first container\n        Set<String> blobNamesCreatedInContainer1 = TestUtils.createBlobsInContainer(CONTAINER_NAME,\n              \"bbb/ccc/ddd/1234.jpg\",\n              TestUtils.createRandomBlobKey(),\n              \"rrr/sss/788.jpg\",\n              \"xdc/wert.kpg\");\n\n        // creates blobs in second container\n        blobStore.createContainerInLocation(null, CONTAINER_NAME2);\n        Set<String> blobNamesCreatedInContainer2 = TestUtils.createBlobsInContainer(CONTAINER_NAME2,\n              \"asd/bbb/ccc/ddd/1234.jpg\",\n              TestUtils.createRandomBlobKey(),\n              \"rrr/sss/788.jpg\",\n              \"xdc/wert.kpg\");\n\n        // test blobs in containers\n        checkForContainerContent(CONTAINER_NAME, blobNamesCreatedInContainer1);\n        checkForContainerContent(CONTAINER_NAME2, blobNamesCreatedInContainer2);\n\n        // delete blobs in first container\n        blobStore.clearContainer(CONTAINER_NAME);\n        checkForContainerContent(CONTAINER_NAME, null);\n        checkForContainerContent(CONTAINER_NAME2, blobNamesCreatedInContainer2);\n        // delete blobs in second container\n        blobStore.clearContainer(CONTAINER_NAME2);\n        checkForContainerContent(CONTAINER_NAME2, null);\n    }\n\n    public void testCountBlobs_NotExistingContainer() {\n        blobStore.countBlobs(PROVIDER);\n    }\n\n    public void testCountBlobs_NoOptionsEmptyContainer() {\n        blobStore.createContainerInLocation(null, CONTAINER_NAME);\n        blobStore.countBlobs(PROVIDER);\n    }\n\n    public void testCountBlobs_NoOptions() {\n        blobStore.createContainerInLocation(null, CONTAINER_NAME);\n        blobStore.countBlobs(PROVIDER);\n    }\n\n    public void testRemoveBlob_SimpleBlobKey() throws IOException {\n        final String BLOB_KEY = TestUtils.createRandomBlobKey(null, \".txt\");\n        boolean result;\n\n        blobStore.createContainerInLocation(null, CONTAINER_NAME);\n\n        // checks that blob doesn't exists\n        result = blobStore.blobExists(CONTAINER_NAME, BLOB_KEY);\n        assertFalse(result, \"Blob exists\");\n\n        // create the blob\n        TestUtils.createBlobsInContainer(CONTAINER_NAME, BLOB_KEY);\n        result = blobStore.blobExists(CONTAINER_NAME, BLOB_KEY);\n        assertTrue(result, \"Blob exists\");\n\n        // remove it\n        blobStore.removeBlob(CONTAINER_NAME, BLOB_KEY);\n        result = blobStore.blobExists(CONTAINER_NAME, BLOB_KEY);\n        assertFalse(result, \"Blob still exists\");\n        TestUtils.fileExists(TARGET_CONTAINER_NAME + \"/\" + BLOB_KEY, false);\n    }\n\n    public void testRemoveBlob_TwoSimpleBlobKeys() throws IOException {\n        final String BLOB_KEY1 = TestUtils.createRandomBlobKey(null, null);\n        final String BLOB_KEY2 = TestUtils.createRandomBlobKey(null, null);\n        boolean result;\n\n        // create the container and checks that blob doesn't exists\n        blobStore.createContainerInLocation(null, CONTAINER_NAME);\n        result = blobStore.blobExists(CONTAINER_NAME, BLOB_KEY1);\n        assertFalse(result, \"Blob1 exists\");\n        result = blobStore.blobExists(CONTAINER_NAME, BLOB_KEY2);\n        assertFalse(result, \"Blob2 exists\");\n\n        // create the blob\n        TestUtils.createBlobsInContainer(CONTAINER_NAME, BLOB_KEY1, BLOB_KEY2);\n        result = blobStore.blobExists(CONTAINER_NAME, BLOB_KEY1);\n        assertTrue(result, \"Blob \" + BLOB_KEY1 + \" doesn't exist\");\n        result = blobStore.blobExists(CONTAINER_NAME, BLOB_KEY2);\n        assertTrue(result, \"Blob \" + BLOB_KEY2 + \" doesn't exist\");\n\n        // remove first blob\n        blobStore.removeBlob(CONTAINER_NAME, BLOB_KEY1);\n        result = blobStore.blobExists(CONTAINER_NAME, BLOB_KEY1);\n        assertFalse(result, \"Blob1 still exists\");\n        result = blobStore.blobExists(CONTAINER_NAME, BLOB_KEY2);\n        assertTrue(result, \"Blob2 doesn't exist\");\n        TestUtils.fileExists(TARGET_CONTAINER_NAME + File.separator + BLOB_KEY1, false);\n        TestUtils.fileExists(TARGET_CONTAINER_NAME + File.separator + BLOB_KEY2, true);\n        // remove second blob\n        blobStore.removeBlob(CONTAINER_NAME, BLOB_KEY2);\n        result = blobStore.blobExists(CONTAINER_NAME, BLOB_KEY2);\n        assertFalse(result, \"Blob2 still exists\");\n        TestUtils.fileExists(TARGET_CONTAINER_NAME + File.separator + BLOB_KEY2, false);\n    }\n\n    /**\n     * Test of removeBlob method, with only one blob with a complex path as key\n     */\n    @Test\n    public void testRemoveBlob_ComplexBlobKey() throws IOException {\n        final String BLOB_KEY = TestUtils.createRandomBlobKey(\"aa/bb/cc/dd/\", null);\n        boolean result;\n\n        // checks that blob doesn't exists\n        blobStore.createContainerInLocation(null, CONTAINER_NAME);\n        result = blobStore.blobExists(CONTAINER_NAME, BLOB_KEY);\n        assertFalse(result, \"Blob exists\");\n        TestUtils.fileExists(TARGET_CONTAINER_NAME + File.separator + BLOB_KEY, false);\n\n        // create the blob\n        TestUtils.createBlobsInContainer(CONTAINER_NAME, BLOB_KEY);\n        result = blobStore.blobExists(CONTAINER_NAME, BLOB_KEY);\n        assertTrue(result, \"Blob doesn't exist\");\n\n        // remove it\n        blobStore.removeBlob(CONTAINER_NAME, BLOB_KEY);\n        result = blobStore.blobExists(CONTAINER_NAME, BLOB_KEY);\n        assertFalse(result, \"Blob still exists\");\n        // file removed\n        TestUtils.fileExists(TARGET_CONTAINER_NAME + File.separator + BLOB_KEY, false);\n        // also the entire directory structure was removed\n        TestUtils.directoryExists(TARGET_CONTAINER_NAME + \"/aa\", false);\n    }\n\n    /**\n     * Test of removeBlob method, with two blobs with a complex path as key and\n     * when first blob is removed, not all of its key's path is removed, because\n     * it is shared with the second blob's key\n     */\n    @Test\n    public void testRemoveBlob_TwoComplexBlobKeys() throws IOException {\n        final String BLOB_KEY1 = TestUtils.createRandomBlobKey(\"aa/bb/cc/dd/\", null);\n        final String BLOB_KEY2 = TestUtils.createRandomBlobKey(\"aa/bb/ee/ff/\", null);\n        boolean result;\n\n        blobStore.createContainerInLocation(null, CONTAINER_NAME);\n\n        // checks that blob doesn't exist\n        result = blobStore.blobExists(CONTAINER_NAME, BLOB_KEY1);\n        assertFalse(result, \"Blob1 exists\");\n        result = blobStore.blobExists(CONTAINER_NAME, BLOB_KEY2);\n        assertFalse(result, \"Blob2 exists\");\n\n        // create the blobs\n        TestUtils.createBlobsInContainer(CONTAINER_NAME, BLOB_KEY1, BLOB_KEY2);\n        result = blobStore.blobExists(CONTAINER_NAME, BLOB_KEY1);\n        assertTrue(result, \"Blob \" + BLOB_KEY1 + \" doesn't exist\");\n        result = blobStore.blobExists(CONTAINER_NAME, BLOB_KEY2);\n        assertTrue(result, \"Blob \" + BLOB_KEY2 + \" doesn't exist\");\n\n        // remove first blob\n        Uninterruptibles.sleepUninterruptibly(5, TimeUnit.SECONDS);\n        blobStore.removeBlob(CONTAINER_NAME, BLOB_KEY1);\n        Uninterruptibles.sleepUninterruptibly(5, TimeUnit.SECONDS);\n        result = blobStore.blobExists(CONTAINER_NAME, BLOB_KEY1);\n        assertFalse(result, \"Blob still exists\");\n        // first file deleted, not the second\n        TestUtils.fileExists(TARGET_CONTAINER_NAME + File.separator + BLOB_KEY1, false);\n        TestUtils.fileExists(TARGET_CONTAINER_NAME + File.separator + BLOB_KEY2, true);\n        // only partial directory structure was removed, because it shares a path\n        // with the second blob created\n        TestUtils.directoryExists(TARGET_CONTAINER_NAME + \"/aa/bb/cc/dd\", false);\n        TestUtils.directoryExists(TARGET_CONTAINER_NAME + \"/aa/bb\", true);\n        // remove second blob\n        blobStore.removeBlob(CONTAINER_NAME, BLOB_KEY2);\n        result = blobStore.blobExists(CONTAINER_NAME, BLOB_KEY2);\n        assertFalse(result, \"Blob still exists\");\n        TestUtils.fileExists(TARGET_CONTAINER_NAME + File.separator + BLOB_KEY2, false);\n        // now all the directory structure is empty\n        TestUtils.directoryExists(TARGET_CONTAINER_NAME + \"/aa\", false);\n    }\n\n    public void testContainerExists() throws IOException {\n        boolean result;\n\n        result = blobStore.containerExists(CONTAINER_NAME);\n        assertFalse(result, \"Container exists\");\n\n        // create container\n        TestUtils.createContainerAsDirectory(CONTAINER_NAME);\n\n        result = blobStore.containerExists(CONTAINER_NAME);\n        assertTrue(result, \"Container doesn't exist\");\n    }\n\n    public void testCreateContainerInLocation() throws IOException {\n        final String CONTAINER_NAME2 = \"funambol-test-2\";\n        final String TARGET_CONTAINER_NAME2 = TestUtils.TARGET_BASE_DIR + CONTAINER_NAME2;\n\n        boolean result;\n\n        result = blobStore.containerExists(CONTAINER_NAME);\n        assertFalse(result, \"Container exists\");\n        result = blobStore.createContainerInLocation(null, CONTAINER_NAME);\n        assertTrue(result, \"Container not created\");\n        result = blobStore.containerExists(CONTAINER_NAME);\n        assertTrue(result, \"Container doesn't exist\");\n        TestUtils.directoryExists(TARGET_CONTAINER_NAME, true);\n\n        result = blobStore.containerExists(CONTAINER_NAME2);\n        assertFalse(result, \"Container exists\");\n        result = blobStore.createContainerInLocation(null, CONTAINER_NAME2);\n        assertTrue(result, \"Container not created\");\n        result = blobStore.containerExists(CONTAINER_NAME2);\n        assertTrue(result, \"Container doesn't exist\");\n        TestUtils.directoryExists(TestUtils.TARGET_BASE_DIR + CONTAINER_NAME2, true);\n    }\n\n    public void testPutBlobSimpleName() {\n        blobStore.createContainerInLocation(null, CONTAINER_NAME);\n        putBlobAndCheckIt(TestUtils.createRandomBlobKey(\"putBlob-\", \".jpg\"));\n        putBlobAndCheckIt(TestUtils.createRandomBlobKey(\"putBlob-\", \".jpg\"));\n    }\n\n    @Test(dataProvider = \"ignoreOnMacOSX\")\n    public void testPutDirectoryBlobs() {\n        blobStore.createContainerInLocation(null, CONTAINER_NAME);\n\n        String parentKey = TestUtils.createRandomBlobKey(\"a/b/c/directory-\", \"/\");\n        String childKey = TestUtils.createRandomBlobKey(parentKey + \"directory-\", File.separator);\n        blobStore.putBlob(CONTAINER_NAME, createDirBlob(parentKey));\n        assertTrue(blobStore.blobExists(CONTAINER_NAME, parentKey));\n\n        blobStore.putBlob(CONTAINER_NAME, createDirBlob(childKey));\n        assertTrue(blobStore.blobExists(CONTAINER_NAME, childKey));\n\n        blobStore.removeBlob(CONTAINER_NAME, parentKey);\n        Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);\n        assertFalse(blobStore.blobExists(CONTAINER_NAME, parentKey));\n        assertTrue(blobStore.blobExists(CONTAINER_NAME, childKey));\n    }\n\n    @Test(dataProvider = \"ignoreOnMacOSX\")\n    public void testGetDirectoryBlob() throws IOException {\n        blobStore.createContainerInLocation(null, CONTAINER_NAME);\n\n        String blobKey = TestUtils.createRandomBlobKey(\"a/b/c/directory-\", \"/\");\n        blobStore.putBlob(CONTAINER_NAME, createDirBlob(blobKey));\n\n        assertTrue(blobStore.blobExists(CONTAINER_NAME, blobKey));\n\n        Blob blob = blobStore.getBlob(CONTAINER_NAME, blobKey);\n        assertEquals(blob.getMetadata().getName(), blobKey, \"Created blob name is different\");\n\n        assertTrue(!blobStore.blobExists(CONTAINER_NAME,\n                blobKey.substring(0, blobKey.length() - 1)));\n    }\n\n    @Test(dataProvider = \"ignoreOnMacOSX\")\n    public void testListDirectoryBlobsS3FS() {\n        blobStore.createContainerInLocation(null, CONTAINER_NAME);\n        checkForContainerContent(CONTAINER_NAME, null);\n\n        String d = TestUtils.createRandomBlobKey(\"directory-\", \"\");\n        blobStore.putBlob(CONTAINER_NAME, createDirBlob(d + File.separator));\n        assertTrue(blobStore.blobExists(CONTAINER_NAME, d + File.separator));\n\n        ListContainerOptions options = ListContainerOptions.Builder\n                .withDetails()\n                .inDirectory(\"\");\n        PageSet<? extends StorageMetadata> res = blobStore.list(CONTAINER_NAME, options);\n        assertTrue(res.size() == 1);\n        assertEquals(res.iterator().next().getName(), d + File.separator);\n    }\n\n\n    /**\n     * Test of putBlob method with a complex key, with path in the filename, eg\n     * picture/filename.jpg\n     */\n    public void testPutBlobComplexName1() {\n        blobStore.createContainerInLocation(null, CONTAINER_NAME);\n        putBlobAndCheckIt(TestUtils.createRandomBlobKey(\"picture/putBlob-\", \".jpg\"));\n        putBlobAndCheckIt(TestUtils.createRandomBlobKey(\"video/putBlob-\", \".jpg\"));\n        putBlobAndCheckIt(TestUtils.createRandomBlobKey(\"putBlob-\", \".jpg\"));\n        putBlobAndCheckIt(TestUtils.createRandomBlobKey(\"video/putBlob-\", \".jpg\"));\n    }\n\n    /**\n     * Test of putBlob method with a complex key, with path in the filename, eg\n     * picture/filename.jpg\n     */\n    public void testPutBlobComplexName2() {\n        blobStore.createContainerInLocation(null, CONTAINER_NAME);\n        putBlobAndCheckIt(TestUtils.createRandomBlobKey(\"aa/bb/cc/dd/ee/putBlob-\", \".jpg\"));\n        putBlobAndCheckIt(TestUtils.createRandomBlobKey(\"aa/bb/cc/dd/ee/putBlob-\", \".jpg\"));\n        putBlobAndCheckIt(TestUtils.createRandomBlobKey(\"putBlob-\", \".jpg\"));\n    }\n\n    public void testBlobExists() throws IOException {\n        boolean result;\n        String blobKey;\n\n        // when location doesn't exists\n        blobKey = TestUtils.createRandomBlobKey();\n        try {\n            blobStore.blobExists(CONTAINER_NAME, blobKey);\n            fail();\n        } catch (ContainerNotFoundException cnfe) {\n            // expected\n        }\n\n        // when location exists\n        blobStore.createContainerInLocation(null, CONTAINER_NAME);\n        result = blobStore.blobExists(CONTAINER_NAME, blobKey);\n        assertFalse(result, \"Blob exists\");\n\n        // create blob\n        TestUtils.createBlobAsFile(CONTAINER_NAME, blobKey, TestUtils.getImageForBlobPayload());\n        result = blobStore.blobExists(CONTAINER_NAME, blobKey);\n        assertTrue(result, \"Blob doesn't exist\");\n\n        // complex path test\n        blobKey = TestUtils.createRandomBlobKey(\"ss/asdas/\", \"\");\n        result = blobStore.blobExists(CONTAINER_NAME, blobKey);\n        assertFalse(result, \"Blob exists\");\n        TestUtils.createBlobAsFile(CONTAINER_NAME, blobKey, TestUtils.getImageForBlobPayload());\n        result = blobStore.blobExists(CONTAINER_NAME, blobKey);\n        assertTrue(result, \"Blob doesn't exist\");\n    }\n\n    public void testGetBlob_NotExistingContainer() {\n        try {\n            blobStore.getBlob(CONTAINER_NAME, TestUtils.createRandomBlobKey(), null);\n            fail(\"Retrieve must fail, container does not exist.\");\n        } catch (ContainerNotFoundException e) {\n            // correct if arrive here\n        }\n    }\n\n    public void testGetBlob() throws IOException {\n        String blobKey = TestUtils.createRandomBlobKey();\n        GetOptions options = null;\n        Blob resultBlob;\n\n        blobStore.createContainerInLocation(null, CONTAINER_NAME);\n\n        resultBlob = blobStore.getBlob(CONTAINER_NAME, blobKey, options);\n        assertNull(resultBlob, \"Blob exists\");\n\n        // create blob\n        TestUtils.createBlobsInContainer(CONTAINER_NAME, blobKey);\n\n        resultBlob = blobStore.getBlob(CONTAINER_NAME, blobKey, options);\n\n        assertNotNull(resultBlob, \"Blob exists\");\n        // checks file content\n        ByteSource expectedFile = Files.asByteSource(new File(TARGET_CONTAINER_NAME, blobKey));\n        assertEquals(expectedFile.read(), ByteStreams2.toByteArrayAndClose(resultBlob.getPayload().openStream()),\n                \"Blob payload differs from file content\");\n        // metadata are verified in the test for blobMetadata, so no need to\n        // perform a complete test here\n        assertNotNull(resultBlob.getMetadata(), \"Metadata null\");\n        MutableBlobMetadata metadata = resultBlob.getMetadata();\n        assertEquals(blobKey, metadata.getName(), \"Wrong blob metadata\");\n    }\n\n    public void testBlobMetadata_withDefaultMetadata() throws IOException {\n        String BLOB_KEY = TestUtils.createRandomBlobKey(null, null);\n        // create the blob\n        blobStore.createContainerInLocation(null, CONTAINER_NAME);\n        Blob blob = blobStore.blobBuilder(BLOB_KEY)\n           .payload(TestUtils.getImageForBlobPayload())\n           .build();\n        blobStore.putBlob(CONTAINER_NAME, blob);\n\n        BlobMetadata metadata = blobStore.blobMetadata(CONTAINER_NAME, BLOB_KEY);\n        assertNotNull(metadata, \"Metadata null\");\n\n        assertEquals(metadata.getName(), BLOB_KEY, \"Wrong blob name\");\n        assertEquals(metadata.getType(), StorageType.BLOB, \"Wrong blob type\");\n        assertEquals(metadata.getContentMetadata().getContentType(), \"application/unknown\", \"Wrong blob content-type\");\n        assertEquals(base16().lowerCase().encode(metadata.getContentMetadata().getContentMD5()), metadata.getETag(),\n                \"Wrong blob MD5\");\n        assertEquals(metadata.getLocation(), null, \"Wrong blob location\");\n        assertEquals(metadata.getProviderId(), null, \"Wrong blob provider id\");\n        assertEquals(metadata.getUri(), null, \"Wrong blob URI\");\n        assertNotNull(metadata.getUserMetadata(), \"No blob UserMetadata\");\n        assertEquals(metadata.getUserMetadata().size(), 0, \"Wrong blob UserMetadata\");\n        // metadata.getLastModified()\n        File file = new File(TARGET_CONTAINER_NAME, BLOB_KEY);\n        assertEquals(metadata.getContentMetadata().getContentLength(), Long.valueOf(file.length()), \"Wrong blob size\");\n    }\n\n    public void testDeleteContainer_NotExistingContainer() {\n        blobStore.deleteContainer(CONTAINER_NAME);\n    }\n\n    public void testDeleteContainer_EmptyContanier() {\n        boolean result;\n        blobStore.createContainerInLocation(null, CONTAINER_NAME);\n\n        result = blobStore.containerExists(CONTAINER_NAME);\n        assertTrue(result, \"Container doesn't exists\");\n        TestUtils.directoryExists(TARGET_CONTAINER_NAME, true);\n\n        // delete container\n        blobStore.deleteContainer(CONTAINER_NAME);\n        result = blobStore.containerExists(CONTAINER_NAME);\n        assertFalse(result, \"Container still exists\");\n        TestUtils.directoryExists(TARGET_CONTAINER_NAME, false);\n    }\n\n    public void testDeleteContainer() throws IOException {\n        boolean result;\n        String CONTAINER_NAME2 = \"container-to-delete\";\n        String TARGET_CONTAINER_NAME2 = TestUtils.TARGET_BASE_DIR + CONTAINER_NAME2;\n        blobStore.createContainerInLocation(null, CONTAINER_NAME);\n        blobStore.createContainerInLocation(null, CONTAINER_NAME2);\n\n        result = blobStore.containerExists(CONTAINER_NAME);\n        assertTrue(result, \"Container [\" + CONTAINER_NAME + \"] doesn't exists\");\n        TestUtils.directoryExists(TARGET_CONTAINER_NAME, true);\n        result = blobStore.containerExists(CONTAINER_NAME2);\n        assertTrue(result, \"Container [\" + CONTAINER_NAME2 + \"] doesn't exists\");\n        TestUtils.directoryExists(TARGET_CONTAINER_NAME2, true);\n\n        // create blobs inside container\n        TestUtils.createBlobsInContainer(CONTAINER_NAME, TestUtils.createRandomBlobKey(\"testutils-\", null),\n                TestUtils.createRandomBlobKey(\"testutils-\", null),\n                TestUtils.createRandomBlobKey(\"ab123s\" + File.separator + \"testutils-\", null));\n        TestUtils.createBlobsInContainer(CONTAINER_NAME, TestUtils.createRandomBlobKey(\"testutils-\", null),\n                TestUtils.createRandomBlobKey(\"testutils-\", null),\n                TestUtils.createRandomBlobKey(\"asda123s\" + File.separator + \"testutils-\", null),\n                TestUtils.createRandomBlobKey(\"123-_3s\" + File.separator + \"testutils-\", null));\n\n        // delete first container\n        blobStore.deleteContainer(CONTAINER_NAME);\n        result = blobStore.containerExists(CONTAINER_NAME);\n        assertFalse(result, \"Container [\" + CONTAINER_NAME + \"] still exists\");\n        TestUtils.directoryExists(TARGET_CONTAINER_NAME, false);\n        result = blobStore.containerExists(CONTAINER_NAME2);\n        assertTrue(result, \"Container [\" + CONTAINER_NAME2 + \"] still exists\");\n        TestUtils.directoryExists(TARGET_CONTAINER_NAME2, true);\n        // delete second container\n        blobStore.deleteContainer(CONTAINER_NAME2);\n        result = blobStore.containerExists(CONTAINER_NAME2);\n        assertFalse(result, \"Container [\" + CONTAINER_NAME2 + \"] still exists\");\n        TestUtils.directoryExists(TARGET_CONTAINER_NAME2, false);\n    }\n\n    @Test\n    public void testInvalidContainerName() {\n\tString containerName = \"file\" + File.separator + \"system\";\n        try {\n            blobStore.createContainerInLocation(null, containerName);\n            fail(\"Wrong container name not recognized\");\n        } catch (IllegalArgumentException e) {\n        }\n        try {\n            blobStore.containerExists(containerName);\n            fail(\"Wrong container name not recognized\");\n        } catch (IllegalArgumentException e) {\n        }\n    }\n\n    public void testRanges() throws IOException {\n        blobStore.createContainerInLocation(null, CONTAINER_NAME);\n        String input = \"abcdefgh\";\n        Payload payload;\n        Blob blob = blobStore.blobBuilder(\"test\").payload(new StringPayload(input)).build();\n        blobStore.putBlob(CONTAINER_NAME, blob);\n\n        GetOptions getOptionsRangeStartAt = new GetOptions();\n        getOptionsRangeStartAt.startAt(1);\n        Blob blobRangeStartAt = blobStore.getBlob(CONTAINER_NAME, blob.getMetadata().getName(), getOptionsRangeStartAt);\n        payload = blobRangeStartAt.getPayload();\n        try {\n            assertEquals(input.substring(1), Strings2.toStringAndClose(payload.openStream()));\n        } finally {\n            Closeables2.closeQuietly(payload);\n        }\n\n        GetOptions getOptionsRangeTail = new GetOptions();\n        getOptionsRangeTail.tail(3);\n        Blob blobRangeTail = blobStore.getBlob(CONTAINER_NAME, blob.getMetadata().getName(), getOptionsRangeTail);\n        payload = blobRangeTail.getPayload();\n        try {\n            assertEquals(input.substring(5), Strings2.toStringAndClose(payload.openStream()));\n        } finally {\n            Closeables2.closeQuietly(payload);\n        }\n\n        GetOptions getOptionsFragment = new GetOptions();\n        getOptionsFragment.range(4, 6);\n        Blob blobFragment = blobStore.getBlob(CONTAINER_NAME, blob.getMetadata().getName(), getOptionsFragment);\n        payload = blobFragment.getPayload();\n        try {\n            assertEquals(input.substring(4, 7), Strings2.toStringAndClose(payload.openStream()));\n        } finally {\n            Closeables2.closeQuietly(payload);\n        }\n    }\n\n    /** Test that BlobRequestSigner creates expected URIs.  */\n    public void testBlobRequestSigner() throws Exception {\n        String containerName = \"container\";\n        String blobName = \"blob\";\n        URI endPoint = new URI(\"http\", \"localhost\",\n                String.format(\"/transient/%s/%s\", containerName, blobName),\n                /*fragment=*/ null);\n        BlobRequestSigner signer = context.getSigner();\n        HttpRequest request;\n        HttpRequest expected;\n\n        request = signer.signGetBlob(containerName, blobName);\n        expected = HttpRequest.builder()\n                .method(\"GET\")\n                .endpoint(endPoint)\n                .headers(request.getHeaders())\n                .build();\n        assertEquals(expected, request);\n\n        Blob blob = blobStore.blobBuilder(blobName).forSigning().build();\n        request = signer.signPutBlob(containerName, blob);\n        expected = HttpRequest.builder()\n                .method(\"PUT\")\n                .endpoint(endPoint)\n                .headers(request.getHeaders())\n                .payload(new PhantomPayload())\n                .build();\n        assertEquals(expected, request);\n    }\n\n    // public void testInvalidBlobKey() {\n    // try {\n    // blobStore.newBlob(File.separator + \"testwrongblobkey\");\n    // fail(\"Wrong blob key not recognized\");\n    // } catch (IllegalArgumentException e) {}\n    //\n    // try {\n    // blobStore.newBlob(\"testwrongblobkey\" + File.separator);\n    // fail(\"Wrong blob key not recognized\");\n    // } catch (IllegalArgumentException e) {}\n    // }\n\n    // ---------------------------------------------------------- Private Methods\n\n    /**\n     * Creates a {@link Blob} object filled with data from a file\n     *\n     * @param keyName\n     * @param filePayload\n     * @return\n     */\n    private Blob createBlob(String keyName, File filePayload) {\n        return blobStore.blobBuilder(keyName).payload(filePayload).build();\n    }\n\n    private Blob createDirBlob(String keyName) {\n        return blobStore.blobBuilder(keyName)\n                .payload(ByteSource.empty())\n                .build();\n    }\n\n    /**\n     * Tests if container contains only the expected blobs\n     *\n     * @param containerName\n     * @param expectedBlobKeys\n     */\n    private void checkForContainerContent(final String containerName, Set<String> expectedBlobKeys) {\n        checkForContainerContent(containerName, null, expectedBlobKeys);\n    }\n\n    private void checkForContainerContent(final String containerName, String inDirectory, Set<String> expectedBlobKeys) {\n        ListContainerOptions options = ListContainerOptions.Builder.recursive();\n        if (null != inDirectory && !\"\".equals(inDirectory))\n            options.inDirectory(inDirectory);\n\n        PageSet<? extends StorageMetadata> blobsRetrieved = blobStore.list(containerName, options);\n        for (Iterator<? extends StorageMetadata> it = blobsRetrieved.iterator(); it.hasNext();) {\n           // TODO: FluentIterable\n           if (it.next().getType() != StorageType.BLOB) {\n              it.remove();\n           }\n        }\n\n        // nothing expected\n        if (null == expectedBlobKeys || 0 == expectedBlobKeys.size()) {\n            assertTrue(blobsRetrieved.isEmpty(), \"Wrong blob number retrieved in the container [\" + containerName + \"]\");\n            return;\n        }\n\n        // copies values\n        Set<String> expectedBlobKeysCopy = Sets.newHashSet();\n        for (String value : expectedBlobKeys) {\n            expectedBlobKeysCopy.add(value);\n        }\n        assertEquals(blobsRetrieved.size(), expectedBlobKeysCopy.size(),\n                \"Wrong blob number retrieved in the container [\" + containerName + \"]\");\n        for (StorageMetadata data : blobsRetrieved) {\n            String blobName = data.getName();\n            if (!expectedBlobKeysCopy.remove(blobName)) {\n                fail(\"List for container [\" + containerName + \"] contains unexpected value [\" + blobName + \"]\");\n            }\n        }\n        assertTrue(expectedBlobKeysCopy.isEmpty(), \"List operation for container [\" + containerName\n                + \"] doesn't return all values.\");\n    }\n\n    /**\n     * Create a blob with putBlob method\n     */\n    private void putBlobAndCheckIt(String blobKey) {\n        Blob blob;\n\n        TestUtils.fileExists(TARGET_CONTAINER_NAME + File.separator + blobKey, false);\n\n        // create the blob\n        blob = createBlob(blobKey, TestUtils.getImageForBlobPayload());\n        String eTag = blobStore.putBlob(CONTAINER_NAME, blob);\n        assertNotNull(eTag, \"putBlob result null\");\n        assertNotSame(eTag, \"\", \"putBlob result empty\");\n\n        // checks if the blob exists\n        TestUtils.fileExists(TARGET_CONTAINER_NAME + File.separator + blobKey, true);\n    }\n\n    @DataProvider\n    public Object[][] ignoreOnMacOSX() {\n        return isMacOSX() ? NO_INVOCATIONS\n                : SINGLE_NO_ARG_INVOCATION;\n    }\n}\n"
  },
  {
    "path": "apis/filesystem/src/test/java/org/jclouds/filesystem/integration/FilesystemBlobIntegrationTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.filesystem.integration;\n\nimport static org.jclouds.filesystem.util.Utils.isMacOSX;\nimport static org.jclouds.utils.TestUtils.NO_INVOCATIONS;\nimport static org.jclouds.utils.TestUtils.SINGLE_NO_ARG_INVOCATION;\n\nimport java.io.IOException;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Properties;\n\nimport static org.assertj.core.api.Assertions.assertThat;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.hash.Hasher;\nimport com.google.common.hash.Hashing;\nimport com.google.common.io.BaseEncoding;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.BlobBuilder;\nimport org.jclouds.blobstore.domain.BlobMetadata;\nimport org.jclouds.blobstore.domain.MultipartPart;\nimport org.jclouds.blobstore.domain.MultipartUpload;\nimport org.jclouds.blobstore.domain.Tier;\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.integration.internal.BaseBlobIntegrationTest;\nimport org.jclouds.blobstore.integration.internal.BaseBlobStoreIntegrationTest;\nimport org.jclouds.blobstore.options.PutOptions;\nimport org.jclouds.filesystem.reference.FilesystemConstants;\nimport org.jclouds.filesystem.utils.TestUtils;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\nimport org.testng.annotations.DataProvider;\nimport org.testng.annotations.Test;\nimport org.testng.SkipException;\n\n@Test(groups = { \"integration\" }, singleThreaded = true, testName = \"blobstore.FilesystemBlobIntegrationTest\")\npublic class FilesystemBlobIntegrationTest extends BaseBlobIntegrationTest {\n   public FilesystemBlobIntegrationTest() {\n      provider = \"filesystem\";\n      BaseBlobStoreIntegrationTest.SANITY_CHECK_RETURNED_BUCKET_NAME = true;\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      props.setProperty(FilesystemConstants.PROPERTY_BASEDIR, TestUtils.TARGET_BASE_DIR);\n      return props;\n   }\n\n   // Mac OS X HFS+ does not support UserDefinedFileAttributeView:\n   // https://bugs.openjdk.java.net/browse/JDK-8030048\n   @Override\n   @Test(enabled = false)\n   public void checkContentMetadata(Blob blob) {\n      if (!isMacOSX()) {\n         super.checkContentMetadata(blob);\n      }\n   }\n\n   // Mac OS X HFS+ does not support UserDefinedFileAttributeView:\n   // https://bugs.openjdk.java.net/browse/JDK-8030048\n   @Override\n   protected void checkContentDisposition(Blob blob, String contentDisposition) {\n      if (!isMacOSX()) {\n         super.checkContentDisposition(blob, contentDisposition);\n      }\n   }\n\n   // Mac OS X HFS+ does not support UserDefinedFileAttributeView:\n   // https://bugs.openjdk.java.net/browse/JDK-8030048\n   @Override\n   protected void validateMetadata(BlobMetadata metadata) throws IOException {\n      if (!isMacOSX()) {\n         super.validateMetadata(metadata);\n      }\n   }\n\n   // Mac OS X HFS+ does not support UserDefinedFileAttributeView:\n   // https://bugs.openjdk.java.net/browse/JDK-8030048\n   @Test(dataProvider = \"ignoreOnMacOSX\")\n   @Override\n   public void testCreateBlobWithExpiry() throws InterruptedException {\n      super.testCreateBlobWithExpiry();\n   }\n\n   /*\n    * Java on OS X does not support extended attributes, which the filesystem\n    * backend uses to implement user metadata\n    */\n   @Override\n   protected void checkUserMetadata(Map<String, String> userMetadata1, Map<String, String> userMetadata2) {\n      if (!isMacOSX()) {\n         super.checkUserMetadata(userMetadata1, userMetadata2);\n      }\n   }\n   \n   @Override\n   protected void testPutBlobTierHelper(Tier tier, PutOptions options) throws Exception {\n      checkExtendedAttributesSupport();\n      super.testPutBlobTierHelper(tier, options);\n   }\n\n   @Override\n   public void testSetBlobAccess() throws Exception {\n      throw new SkipException(\"filesystem does not support anonymous access\");\n   }\n\n   @Override\n   protected void checkMPUParts(Blob blob, List<MultipartPart> partsList) {\n      // Mac OS X HFS+ does not support UserDefinedFileAttributeView:\n      // https://bugs.openjdk.java.net/browse/JDK-8030048\n      if (isMacOSX()) {\n         return;\n      }\n      assertThat(blob.getMetadata().getETag()).endsWith(String.format(\"-%d\\\"\", partsList.size()));\n      Hasher eTagHasher = Hashing.md5().newHasher();\n      for (MultipartPart part : partsList) {\n         eTagHasher.putBytes(BaseEncoding.base16().lowerCase().decode(part.partETag()));\n      }\n      String expectedETag = new StringBuilder(\"\\\"\")\n         .append(eTagHasher.hash())\n         .append(\"-\")\n         .append(partsList.size())\n         .append(\"\\\"\")\n         .toString();\n      assertThat(blob.getMetadata().getETag()).isEqualTo(expectedETag);\n   }\n\n   // Mac OS X HFS+ does not support UserDefinedFileAttributeView:\n   // https://bugs.openjdk.java.net/browse/JDK-8030048\n   @Test(dataProvider = \"ignoreOnMacOSX\", groups = { \"integration\", \"live\" })\n   public void testMultipartUploadMultiplePartsKnownETag() throws Exception {\n      BlobStore blobStore = view.getBlobStore();\n      String container = getContainerName();\n      // Pre-computed ETag returned by AWS S3 for the MPU consisting of two 5MB parts filled with 'b'\n      String expectedETag = \"\\\"84462a16f6a60478d50148808aa609c1-2\\\"\";\n      int partSize = 5 * 1024 * 1024;\n      try {\n         String name = \"blob-name\";\n         BlobBuilder blobBuilder = blobStore.blobBuilder(name);\n         Blob blob = blobBuilder.build();\n         MultipartUpload mpu = blobStore.initiateMultipartUpload(container, blob.getMetadata(), new PutOptions());\n\n         byte[] content = new byte[partSize];\n         Arrays.fill(content, (byte) 'b');\n         Payload payload = Payloads.newByteArrayPayload(content);\n\n         payload.getContentMetadata().setContentLength((long) partSize);\n\n         MultipartPart part1 = blobStore.uploadMultipartPart(mpu, 1, payload);\n         MultipartPart part2 = blobStore.uploadMultipartPart(mpu, 2, payload);\n         blobStore.completeMultipartUpload(mpu, ImmutableList.of(part1, part2));\n\n         BlobMetadata newBlobMetadata = blobStore.blobMetadata(container, name);\n         assertThat(newBlobMetadata.getETag()).isEqualTo(expectedETag);\n      } finally {\n         returnContainer(container);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void test10000PartMultipartUpload() throws Exception {\n      BlobStore blobStore = view.getBlobStore();\n      String container = getContainerName();\n      int partSize = (int) blobStore.getMinimumMultipartPartSize();\n      try {\n         String name = \"blob-name\";\n         BlobBuilder blobBuilder = blobStore.blobBuilder(name);\n         Blob blob = blobBuilder.build();\n         MultipartUpload mpu = blobStore.initiateMultipartUpload(container, blob.getMetadata(), new PutOptions());\n         ImmutableList.Builder<MultipartPart> parts = ImmutableList.builder();\n         byte[] content = new byte[partSize];\n\n         for (int i = 0; i < 10 * 1000; ++i) {\n            Payload payload = Payloads.newByteArrayPayload(content);\n            payload.getContentMetadata().setContentLength((long) partSize);\n            parts.add(blobStore.uploadMultipartPart(mpu, i, payload));\n         }\n\n         blobStore.completeMultipartUpload(mpu, parts.build());\n\n         BlobMetadata newBlobMetadata = blobStore.blobMetadata(container, name);\n         assertThat(newBlobMetadata.getSize()).isEqualTo(10 * 1000 * partSize);\n      } finally {\n         returnContainer(container);\n      }\n   }\n\n   protected void checkExtendedAttributesSupport() {\n      if (isMacOSX()) {\n         throw new SkipException(\"filesystem does not support extended attributes in Mac OSX\");\n      }\n   }\n\n    @DataProvider\n    public Object[][] ignoreOnMacOSX() {\n        return isMacOSX() ? NO_INVOCATIONS\n                : SINGLE_NO_ARG_INVOCATION;\n    }\n}\n"
  },
  {
    "path": "apis/filesystem/src/test/java/org/jclouds/filesystem/integration/FilesystemContainerIntegrationTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.filesystem.integration;\n\nimport static org.jclouds.blobstore.options.ListContainerOptions.Builder.maxResults;\nimport static org.jclouds.filesystem.util.Utils.isMacOSX;\nimport static org.testng.Assert.assertEquals;\nimport static org.jclouds.utils.TestUtils.NO_INVOCATIONS;\nimport static org.jclouds.utils.TestUtils.SINGLE_NO_ARG_INVOCATION;\n\nimport java.io.IOException;\nimport java.util.Properties;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.TimeoutException;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport com.google.common.collect.ImmutableSet;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.BlobMetadata;\nimport org.jclouds.blobstore.domain.PageSet;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.integration.internal.BaseBlobStoreIntegrationTest;\nimport org.jclouds.blobstore.integration.internal.BaseContainerIntegrationTest;\nimport org.jclouds.filesystem.reference.FilesystemConstants;\nimport org.jclouds.filesystem.utils.TestUtils;\nimport org.testng.SkipException;\nimport org.testng.annotations.DataProvider;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\n\n@Test(groups = { \"integration\", \"live\" }, testName = \"blobstore.FilesystemContainerIntegrationTest\")\npublic class FilesystemContainerIntegrationTest extends BaseContainerIntegrationTest {\n   public FilesystemContainerIntegrationTest() {\n      provider = \"filesystem\";\n      BaseBlobStoreIntegrationTest.SANITY_CHECK_RETURNED_BUCKET_NAME = true;\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      props.setProperty(FilesystemConstants.PROPERTY_BASEDIR, TestUtils.TARGET_BASE_DIR);\n      return props;\n   }\n\n   @Test(dataProvider = \"ignoreOnWindows\", groups = { \"integration\", \"live\" })\n   public void testNotWithDetails() throws InterruptedException {\n      String key = \"hello\";\n\n      // NOTE all metadata in jclouds comes out as lowercase, in an effort to\n      // normalize the\n      // providers.\n      Blob object = view.getBlobStore().blobBuilder(key).userMetadata(ImmutableMap.of(\"Adrian\", \"powderpuff\"))\n            .payload(TEST_STRING).contentType(MediaType.TEXT_PLAIN).build();\n      String containerName = getContainerName();\n      try {\n         addBlobToContainer(containerName, object);\n         validateContent(containerName, key);\n\n         PageSet<? extends StorageMetadata> container = view.getBlobStore().list(containerName, maxResults(1));\n\n         BlobMetadata metadata = (BlobMetadata) Iterables.getOnlyElement(container);\n         // transient container should be lenient and not return metadata on\n         // undetailed listing.\n\n         assertEquals(metadata.getUserMetadata().size(), 0);\n\n      } finally {\n         returnContainer(containerName);\n      }\n   }\n\n   // Mac OS X HFS+ does not support UserDefinedFileAttributeView:\n   // https://bugs.openjdk.java.net/browse/JDK-8030048\n   @Test(dataProvider = \"ignoreOnMacOSX\")\n   @Override\n   public void testWithDetails() throws InterruptedException, IOException {\n      super.testWithDetails();\n   }\n\n   @Override\n   @Test(dataProvider = \"ignoreOnWindows\")\n   public void containerExists() throws InterruptedException {\n      super.containerExists();\n   }\n\n   @Override\n   @Test(dataProvider = \"ignoreOnWindows\")\n   public void deleteContainerWithContents() throws InterruptedException {\n      super.deleteContainerWithContents();\n   }\n\n   @Override\n   @Test(dataProvider = \"ignoreOnWindows\")\n   public void deleteContainerWithoutContents() throws InterruptedException {\n      super.deleteContainerWithoutContents();\n   }\n\n   @Override\n   @Test(dataProvider = \"ignoreOnWindows\")\n   public void deleteContainerIfEmptyWithContents() throws InterruptedException {\n      super.deleteContainerIfEmptyWithContents();\n   }\n\n   @Override\n   @Test(dataProvider = \"ignoreOnWindows\")\n   public void deleteContainerIfEmptyWithoutContents() throws InterruptedException {\n      super.deleteContainerIfEmptyWithoutContents();\n   }\n\n   @Override\n   @Test(dataProvider = \"ignoreOnWindows\")\n   public void testListContainer() throws InterruptedException, ExecutionException, TimeoutException {\n      super.testListContainer();\n   }\n\n   @Override\n   @Test(dataProvider = \"ignoreOnWindows\")\n   public void testListContainerMarker() throws InterruptedException {\n      super.testListContainerMarker();\n   }\n\n   @Override\n   @Test(dataProvider = \"ignoreOnWindows\")\n   public void testListContainerPrefix() throws InterruptedException {\n      super.testListContainerPrefix();\n   }\n\n   @Override\n   @Test(dataProvider = \"ignoreOnWindows\")\n   public void testListRootUsesDelimiter() throws InterruptedException {\n      super.testListRootUsesDelimiter();\n   }\n\n   @Override\n   @Test(dataProvider = \"ignoreOnWindows\")\n   public void testPutTwiceIsOkAndDoesntOverwrite() throws InterruptedException {\n      super.testPutTwiceIsOkAndDoesntOverwrite();\n   }\n\n   @Override\n   @Test(dataProvider = \"ignoreOnWindows\")\n   public void testListContainerMaxResults() throws InterruptedException {\n      super.testListContainerMaxResults();\n   }\n\n   @Override\n   public void testDirectory() {\n      throw new SkipException(\"There is no notion of marker blobs in the file system blob store\");\n   }\n\n   @DataProvider\n   public Object[][] ignoreOnMacOSX() {\n      return isMacOSX() ? NO_INVOCATIONS\n            : SINGLE_NO_ARG_INVOCATION;\n   }\n\n   @DataProvider\n   public Object[][] ignoreOnWindows() {\n      return TestUtils.isWindowsOs() ? NO_INVOCATIONS\n            : SINGLE_NO_ARG_INVOCATION;\n   }\n\n   @Override\n   @DataProvider\n   public Object[][] getBlobsToEscape() {\n      if (TestUtils.isWindowsOs()) {\n         Object[][] result = new Object[1][1];\n         result[0][0] = ImmutableSet.of(\"%20\", \" %20\");\n         return result;\n      }\n      return super.getBlobsToEscape();\n   }\n\n   @Override\n   @Test(groups = { \"integration\", \"live\" })\n   public void testSetContainerAccess() throws Exception {\n      throw new SkipException(\"filesystem does not support anonymous access\");\n   }\n\n}\n"
  },
  {
    "path": "apis/filesystem/src/test/java/org/jclouds/filesystem/integration/FilesystemServiceIntegrationTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.filesystem.integration;\n\nimport java.util.Properties;\n\nimport org.jclouds.blobstore.integration.internal.BaseBlobStoreIntegrationTest;\nimport org.jclouds.blobstore.integration.internal.BaseServiceIntegrationTest;\nimport org.jclouds.filesystem.reference.FilesystemConstants;\nimport org.jclouds.filesystem.utils.TestUtils;\nimport org.testng.annotations.Test;\n\n@Test(groups = { \"integration\", \"live\" }, testName = \"blobstore.FilesystemServiceIntegrationTest\")\npublic class FilesystemServiceIntegrationTest extends BaseServiceIntegrationTest {\n   public FilesystemServiceIntegrationTest() {\n      provider = \"filesystem\";\n      BaseBlobStoreIntegrationTest.SANITY_CHECK_RETURNED_BUCKET_NAME = true;\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      props.setProperty(FilesystemConstants.PROPERTY_BASEDIR, TestUtils.TARGET_BASE_DIR);\n      return props;\n   }\n}\n"
  },
  {
    "path": "apis/filesystem/src/test/java/org/jclouds/filesystem/predicates/validators/internal/FilesystemBlobKeyValidatorTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.filesystem.predicates.validators.internal;\n\nimport static org.testng.Assert.fail;\n\nimport java.io.File;\n\nimport org.jclouds.filesystem.predicates.validators.FilesystemBlobKeyValidator;\nimport org.testng.annotations.Test;\n\n\n/**\n * Test class for {@link FilesystemBlobKeyValidator } class\n */\n@Test(groups = \"unit\", testName = \"filesystem.FilesystemBlobKeyValidatorTest\")\npublic class FilesystemBlobKeyValidatorTest {\n\n    @Test\n    public void testNamesValidity() {\n        FilesystemBlobKeyValidator validator = new FilesystemBlobKeyValidatorImpl();\n\n        validator.validate(\"all.img\");\n        validator.validate(\"all\" + File.separator + \"is\" + File.separator + \"\" + \"ok\");\n        validator.validate(\"all\" + File.separator + \"is\" + File.separator + \"..\" + \"ok\");\n    }\n\n    @Test\n    public void testInvalidNames() {\n        FilesystemBlobKeyValidator validator = new FilesystemBlobKeyValidatorImpl();\n\n        try {\n            validator.validate(\"\");\n            fail(\"Blob key value incorrect, but was not recognized\");\n        } catch (IllegalArgumentException e) {}\n\n        try {\n            validator.validate(File.separator + \"is\" + File.separator + \"\" + \"ok\");\n            fail(\"Blob key value incorrect, but was not recognized\");\n        } catch (IllegalArgumentException e) {}\n\n        try {\n            validator.validate(\"all\" + File.separator + \"..\" + File.separator + \"ok\");\n            fail(\"Blob key value incorrect, but was not recognized\");\n        } catch (IllegalArgumentException e) {}\n    }\n\n\n    //---------------------------------------------------------- Private methods\n\n}\n"
  },
  {
    "path": "apis/filesystem/src/test/java/org/jclouds/filesystem/predicates/validators/internal/FilesystemContainerNameValidatorTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.filesystem.predicates.validators.internal;\n\nimport static org.testng.Assert.fail;\n\nimport java.io.File;\n\nimport org.jclouds.filesystem.predicates.validators.FilesystemContainerNameValidator;\nimport org.testng.annotations.Test;\n\n\n/**\n * Test class for {@link FilesystemContainerNameValidator } class\n */\n@Test(groups = \"unit\", testName = \"filesystem.FilesystemContainerNameValidatorTest\")\npublic class FilesystemContainerNameValidatorTest {\n\n    @Test\n    public void testNamesValidity() {\n        FilesystemContainerNameValidator validator = new FilesystemContainerNameValidatorImpl();\n\n        validator.validate(\"all.img\");\n    }\n\n    @Test\n    public void testInvalidNames() {\n        FilesystemContainerNameValidator validator = new FilesystemContainerNameValidatorImpl();\n\n        try {\n            validator.validate(\"\");\n            fail(\"Container name value incorrect, but was not recognized\");\n        } catch (IllegalArgumentException e) {}\n\n        try {\n            validator.validate(null);\n            fail(\"Container name value incorrect, but was not recognized\");\n        } catch (IllegalArgumentException e) {}\n\n        try {\n            validator.validate(File.separator + \"is\" + File.separator + \"\" + \"ok\");\n            fail(\"Container name value incorrect, but was not recognized\");\n        } catch (IllegalArgumentException e) {}\n\n        try {\n            validator.validate(\"all\" + File.separator + \"is\" + File.separator);\n            fail(\"Container name value incorrect, but was not recognized\");\n        } catch (IllegalArgumentException e) {}\n\n        try {\n            validator.validate(\".\");\n            fail(\"Container name value incorrect, but was not recognized\");\n        } catch (IllegalArgumentException e) {}\n\n        try {\n            validator.validate(\"..\");\n            fail(\"Container name value incorrect, but was not recognized\");\n        } catch (IllegalArgumentException e) {}\n    }\n\n\n    //---------------------------------------------------------- Private methods\n\n}\n"
  },
  {
    "path": "apis/filesystem/src/test/java/org/jclouds/filesystem/strategy/internal/FilesystemStorageStrategyImplTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.filesystem.strategy.internal;\n\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.jclouds.filesystem.util.Utils.isMacOSX;\nimport static org.jclouds.utils.TestUtils.NO_INVOCATIONS;\nimport static org.jclouds.utils.TestUtils.SINGLE_NO_ARG_INVOCATION;\nimport static org.jclouds.utils.TestUtils.randomByteSource;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.Assert.fail;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.IOException;\nimport java.nio.file.InvalidPathException;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.concurrent.TimeUnit;\n\nimport jakarta.inject.Provider;\n\nimport org.assertj.core.api.Fail;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.BlobBuilder;\nimport org.jclouds.blobstore.domain.ContainerAccess;\nimport org.jclouds.blobstore.domain.internal.BlobBuilderImpl;\nimport org.jclouds.blobstore.options.ListContainerOptions;\nimport org.jclouds.domain.Location;\nimport org.jclouds.filesystem.predicates.validators.internal.FilesystemBlobKeyValidatorImpl;\nimport org.jclouds.filesystem.predicates.validators.internal.FilesystemContainerNameValidatorImpl;\nimport org.jclouds.filesystem.utils.TestUtils;\nimport org.jclouds.io.payloads.FilePayload;\nimport org.jclouds.io.payloads.InputStreamPayload;\nimport org.jclouds.util.Throwables2;\nimport org.testng.annotations.AfterMethod;\nimport org.testng.annotations.BeforeMethod;\nimport org.testng.annotations.DataProvider;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Lists;\nimport com.google.common.collect.Sets;\nimport com.google.common.io.ByteSource;\nimport com.google.common.io.Files;\nimport com.google.common.util.concurrent.Uninterruptibles;\n\n/**\n * Test class for {@link FilesystemStorageStrategyImpl } class\n */\n@Test(groups = \"unit\", testName = \"filesystem.FilesystemBlobUtilsTest\", singleThreaded = true)\npublic class FilesystemStorageStrategyImplTest {\n   private static final String CONTAINER_NAME = \"funambol-test\";\n   private static final String TARGET_CONTAINER_NAME = TestUtils.TARGET_BASE_DIR + CONTAINER_NAME;\n\n   private static final String LOGGING_CONFIG_KEY = \"java.util.logging.config.file\";\n   private static final String LOGGING_CONFIG_VALUE = \"src/main/resources/logging.properties\";\n\n   private static final String FS = File.separator;\n   private static final Supplier<Location> defaultLocation = new Supplier<Location>() {\n      @Override\n      public Location get() {\n         return null;\n      }\n   };\n\n   static {\n      System.setProperty(LOGGING_CONFIG_KEY, LOGGING_CONFIG_VALUE);\n   }\n\n   private FilesystemStorageStrategyImpl storageStrategy;\n\n   @BeforeMethod\n   protected void setUp() throws Exception {\n      storageStrategy = new FilesystemStorageStrategyImpl(new Provider<BlobBuilder>() {\n         @Override\n         public BlobBuilder get() {\n            return new BlobBuilderImpl();\n         }\n\n      }, TestUtils.TARGET_BASE_DIR, false, new FilesystemContainerNameValidatorImpl(), new FilesystemBlobKeyValidatorImpl(), defaultLocation);\n      TestUtils.cleanDirectoryContent(TestUtils.TARGET_BASE_DIR);\n      TestUtils.createResources();\n   }\n\n   @AfterMethod\n   protected void tearDown() throws IOException {\n      TestUtils.cleanDirectoryContent(TestUtils.TARGET_BASE_DIR);\n   }\n\n   public void testCreateDirectory() {\n      storageStrategy.createDirectory(CONTAINER_NAME, null);\n      TestUtils.directoryExists(TARGET_CONTAINER_NAME, true);\n\n      storageStrategy.createDirectory(CONTAINER_NAME, \"subdir\");\n      TestUtils.directoryExists(TARGET_CONTAINER_NAME + FS + \"subdir\", true);\n\n      storageStrategy.createDirectory(CONTAINER_NAME, \"subdir1\" + FS);\n      TestUtils.directoryExists(TARGET_CONTAINER_NAME + FS + \"subdir1\", true);\n\n      storageStrategy.createDirectory(CONTAINER_NAME, FS + \"subdir2\");\n      TestUtils.directoryExists(TARGET_CONTAINER_NAME + FS + \"subdir2\", true);\n\n      storageStrategy.createDirectory(CONTAINER_NAME, \"subdir3\" + FS + \"subdir4\");\n      TestUtils.directoryExists(TARGET_CONTAINER_NAME + FS + \"subdir2\", true);\n   }\n\n   public void testCreateDirectory_DirectoryAlreadyExists() {\n      storageStrategy.createDirectory(CONTAINER_NAME, null);\n      storageStrategy.createDirectory(CONTAINER_NAME, null);\n   }\n\n   public void testCreateContainer() {\n      boolean result;\n\n      TestUtils.directoryExists(TARGET_CONTAINER_NAME, false);\n      result = storageStrategy.createContainer(CONTAINER_NAME);\n      assertTrue(result, \"Container not created\");\n      TestUtils.directoryExists(TARGET_CONTAINER_NAME, true);\n   }\n\n   public void testCreateContainerAccess() {\n      boolean result;\n\n      TestUtils.directoryExists(TARGET_CONTAINER_NAME, false);\n      result = storageStrategy.createContainer(CONTAINER_NAME);\n      assertTrue(result, \"Container not created\");\n      TestUtils.directoryExists(TARGET_CONTAINER_NAME, true);\n\n      storageStrategy.setContainerAccess(CONTAINER_NAME, ContainerAccess.PRIVATE);\n      assertEquals(storageStrategy.getContainerAccess(CONTAINER_NAME), ContainerAccess.PRIVATE);\n      storageStrategy.setContainerAccess(CONTAINER_NAME, ContainerAccess.PUBLIC_READ);\n      assertEquals(storageStrategy.getContainerAccess(CONTAINER_NAME), ContainerAccess.PUBLIC_READ);\n   }\n\n   public void testCreateContainer_ContainerAlreadyExists() {\n      boolean result;\n\n      TestUtils.directoryExists(TARGET_CONTAINER_NAME, false);\n      result = storageStrategy.createContainer(CONTAINER_NAME);\n      assertTrue(result, \"Container not created\");\n      result = storageStrategy.createContainer(CONTAINER_NAME);\n      assertFalse(result, \"Container not created\");\n   }\n\n   public void testDeleteDirectory() throws IOException {\n      TestUtils.createContainerAsDirectory(CONTAINER_NAME);\n      TestUtils.createBlobsInContainer(CONTAINER_NAME, new String[] {\n               TestUtils.createRandomBlobKey(\"lev1\" + FS + \"lev2\" + FS + \"lev3\" + FS, \".txt\"),\n               TestUtils.createRandomBlobKey(\"lev1\" + FS + \"lev2\" + FS + \"lev4\" + FS, \".jpg\") });\n\n      // delete directory in different ways\n      storageStrategy.deleteDirectory(CONTAINER_NAME, \"lev1\" + FS + \"lev2\" + FS + \"lev4\");\n      TestUtils.directoryExists(TARGET_CONTAINER_NAME + FS + \"lev1\" + FS + \"lev2\" + FS + \"lev4\", false);\n      TestUtils.directoryExists(TARGET_CONTAINER_NAME + FS + \"lev1\" + FS + \"lev2\", true);\n\n      storageStrategy.deleteDirectory(CONTAINER_NAME, \"lev1\" + FS + \"lev2\" + FS + \"lev3\" + FS);\n      TestUtils.directoryExists(TARGET_CONTAINER_NAME + FS + \"lev1\" + FS + \"lev2\" + FS + \"lev3\", false);\n      TestUtils.directoryExists(TARGET_CONTAINER_NAME + FS + \"lev1\" + FS + \"lev2\", true);\n\n      storageStrategy.deleteDirectory(CONTAINER_NAME, FS + \"lev1\");\n      TestUtils.directoryExists(TARGET_CONTAINER_NAME + FS + \"lev1\", false);\n      TestUtils.directoryExists(TARGET_CONTAINER_NAME, true);\n\n      // delete the directory and all the files inside\n      TestUtils.createBlobsInContainer(CONTAINER_NAME, new String[] {\n               TestUtils.createRandomBlobKey(\"lev1\" + FS + \"lev2\" + FS + \"lev3\" + FS, \".txt\"),\n               TestUtils.createRandomBlobKey(\"lev1\" + FS + \"lev2\" + FS + \"lev4\" + FS, \".jpg\") });\n      storageStrategy.deleteDirectory(CONTAINER_NAME, null);\n      TestUtils.directoryExists(TARGET_CONTAINER_NAME, false);\n   }\n\n   public void testDirectoryExists() throws IOException {\n      final String SUBDIRECTORY_NAME = \"ad\" + FS + \"sda\" + FS + \"asd\";\n      boolean result;\n\n      result = storageStrategy.directoryExists(CONTAINER_NAME, null);\n      assertFalse(result, \"Directory exist\");\n\n      // create the container\n      TestUtils.createContainerAsDirectory(CONTAINER_NAME);\n      // check if exists\n      result = storageStrategy.directoryExists(CONTAINER_NAME, null);\n      assertTrue(result, \"Directory doesn't exist\");\n      result = storageStrategy.directoryExists(CONTAINER_NAME + FS, null);\n      assertTrue(result, \"Directory doesn't exist\");\n\n      result = storageStrategy.directoryExists(CONTAINER_NAME, SUBDIRECTORY_NAME);\n      assertFalse(result, \"Directory exist\");\n\n      // create subdirs inside the container\n      TestUtils.createContainerAsDirectory(CONTAINER_NAME + FS + SUBDIRECTORY_NAME);\n      // check if exists\n      result = storageStrategy.directoryExists(CONTAINER_NAME, SUBDIRECTORY_NAME);\n      assertTrue(result, \"Directory doesn't exist\");\n      result = storageStrategy.directoryExists(CONTAINER_NAME, FS + SUBDIRECTORY_NAME);\n      assertTrue(result, \"Directory doesn't exist\");\n      result = storageStrategy.directoryExists(CONTAINER_NAME, SUBDIRECTORY_NAME + FS);\n      assertTrue(result, \"Directory doesn't exist\");\n      result = storageStrategy.directoryExists(CONTAINER_NAME + FS, FS + SUBDIRECTORY_NAME);\n      assertTrue(result, \"Directory doesn't exist\");\n\n   }\n\n   public void testClearContainer() throws IOException {\n      storageStrategy.createContainer(CONTAINER_NAME);\n      Set<String> blobs = TestUtils.createBlobsInContainer(CONTAINER_NAME, new String[] {\n               TestUtils.createRandomBlobKey(\"clean_container-\", \".jpg\"),\n               TestUtils.createRandomBlobKey(\"bf\" + FS + \"sd\" + FS + \"as\" + FS + \"clean_container-\", \".jpg\") });\n      // test if file exits\n      for (String blob : blobs) {\n         TestUtils.fileExists(TARGET_CONTAINER_NAME + FS + blob, true);\n      }\n\n      // clear the container\n      storageStrategy.clearContainer(CONTAINER_NAME);\n      // test if container still exits\n      TestUtils.directoryExists(TARGET_CONTAINER_NAME, true);\n      // test if file was cleared\n      for (String blob : blobs) {\n         TestUtils.fileExists(TARGET_CONTAINER_NAME + FS + blob, false);\n      }\n   }\n\n   public void testClearContainer_NotExistingContainer() throws IOException {\n      // test if container still exits\n      TestUtils.directoryExists(TARGET_CONTAINER_NAME, false);\n      // clear the container\n      storageStrategy.clearContainer(CONTAINER_NAME);\n      // test if container still exits\n      TestUtils.directoryExists(TARGET_CONTAINER_NAME, false);\n   }\n\n   public void testClearContainerAndThenDeleteContainer() throws IOException {\n      storageStrategy.createContainer(CONTAINER_NAME);\n      Set<String> blobs = TestUtils.createBlobsInContainer(CONTAINER_NAME, new String[] {\n               TestUtils.createRandomBlobKey(\"clean_container-\", \".jpg\"),\n               TestUtils.createRandomBlobKey(\"bf\" + FS + \"sd\" + FS + \"as\" + FS + \"clean_container-\", \".jpg\") });\n      // test if file exits\n      for (String blob : blobs) {\n         TestUtils.fileExists(TARGET_CONTAINER_NAME + FS + blob, true);\n      }\n\n      // clear the container\n      storageStrategy.clearContainer(CONTAINER_NAME);\n      // test if container still exits\n      TestUtils.directoryExists(TARGET_CONTAINER_NAME, true);\n      // test if file was cleared\n      for (String blob : blobs) {\n         TestUtils.fileExists(TARGET_CONTAINER_NAME + FS + blob, false);\n      }\n\n      // delete the container\n      storageStrategy.deleteContainer(CONTAINER_NAME);\n      // test if container still exits\n      TestUtils.directoryExists(TARGET_CONTAINER_NAME, false);\n      assertFalse(storageStrategy.containerExists(CONTAINER_NAME), \"Container still exists\");\n   }\n\n   public void testDeleteContainer() throws IOException {\n      final String BLOB_KEY1 = \"blobName.jpg\";\n      final String BLOB_KEY2 = \"aa\" + FS + \"bb\" + FS + \"cc\" + FS + \"dd\" + FS + \"ee\" + FS + \"ff\" + FS + \"23\" + FS\n               + \"blobName.jpg\";\n      boolean result;\n\n      result = storageStrategy.createContainer(CONTAINER_NAME);\n\n      // put data inside the container\n      TestUtils.createBlobsInContainer(CONTAINER_NAME, new String[] { BLOB_KEY1, BLOB_KEY2 });\n\n      storageStrategy.deleteContainer(CONTAINER_NAME);\n      assertTrue(result, \"Cannot delete container\");\n      TestUtils.directoryExists(CONTAINER_NAME, false);\n   }\n\n   public void testDeleteContainer_EmptyContainer() {\n      boolean result;\n\n      result = storageStrategy.createContainer(CONTAINER_NAME);\n      assertTrue(result, \"Cannot create container\");\n\n      storageStrategy.deleteContainer(CONTAINER_NAME);\n      TestUtils.directoryExists(CONTAINER_NAME, false);\n   }\n\n   public void testDeleteContainerNoErrorWhenNotExists() {\n      storageStrategy.deleteContainer(CONTAINER_NAME);\n   }\n\n   public void testGetAllContainerNames() {\n      Iterable<String> resultList;\n\n      // no container\n      resultList = storageStrategy.getAllContainerNames();\n      assertNotNull(resultList, \"Result is null\");\n      assertFalse(resultList.iterator().hasNext(), \"Containers detected\");\n\n      // create containers\n      storageStrategy.createContainer(CONTAINER_NAME + \"1\");\n      storageStrategy.createContainer(CONTAINER_NAME + \"2\");\n      storageStrategy.createContainer(CONTAINER_NAME + \"3\");\n\n      List<String> containers = Lists.newArrayList();\n      resultList = storageStrategy.getAllContainerNames();\n      Iterator<String> containersIterator = resultList.iterator();\n      while (containersIterator.hasNext()) {\n         containers.add(containersIterator.next());\n      }\n      assertEquals(containers.size(), 3, \"Different containers number\");\n      assertTrue(containers.contains(CONTAINER_NAME + \"1\"), \"Containers doesn't exist\");\n      assertTrue(containers.contains(CONTAINER_NAME + \"2\"), \"Containers doesn't exist\");\n      assertTrue(containers.contains(CONTAINER_NAME + \"3\"), \"Containers doesn't exist\");\n   }\n\n   public void testContainerExists() {\n      boolean result;\n\n      TestUtils.directoryExists(TARGET_CONTAINER_NAME, false);\n      result = storageStrategy.containerExists(CONTAINER_NAME);\n      assertFalse(result, \"Container exists\");\n      storageStrategy.createContainer(CONTAINER_NAME);\n      result = storageStrategy.containerExists(CONTAINER_NAME);\n      assertTrue(result, \"Container exists\");\n   }\n\n   public void testNewBlob() {\n      String blobKey;\n      Blob newBlob;\n\n      blobKey = TestUtils.createRandomBlobKey(\"blobtest-\", \".txt\");\n      newBlob = storageStrategy.newBlob(blobKey);\n      assertNotNull(newBlob, \"Created blob was null\");\n      assertNotNull(newBlob.getMetadata(), \"Created blob metadata were null\");\n      assertEquals(newBlob.getMetadata().getName(), blobKey, \"Created blob name is different\");\n\n      blobKey = TestUtils.createRandomBlobKey(\"blobtest-\", \"\");\n      newBlob = storageStrategy.newBlob(blobKey);\n      assertEquals(newBlob.getMetadata().getName(), blobKey, \"Created blob name is different\");\n\n      blobKey = TestUtils.createRandomBlobKey(\"asd\" + FS + \"asd\" + FS + \"asdasd\" + FS + \"afadsf-\", \"\");\n      newBlob = storageStrategy.newBlob(blobKey);\n      assertEquals(newBlob.getMetadata().getName(), blobKey, \"Created blob name is different\");\n   }\n\n   @Test(dataProvider = \"ignoreOnMacOSX\")\n   public void testWriteDirectoryBlob() throws IOException {\n      String blobKey = TestUtils.createRandomBlobKey(\"a/b/c/directory-\", \"/\");\n      Blob blob = storageStrategy.newBlob(blobKey);\n      storageStrategy.putBlob(CONTAINER_NAME, blob);\n      // verify that the files is equal\n      File blobFullPath = new File(TARGET_CONTAINER_NAME, blobKey);\n      assertTrue(blobFullPath.isDirectory());\n\n      assertTrue(storageStrategy.blobExists(CONTAINER_NAME, blobKey));\n   }\n\n   @Test(dataProvider = \"ignoreOnMacOSX\")\n   public void testGetDirectoryBlob() throws IOException {\n      String blobKey = TestUtils.createRandomBlobKey(\"a/b/c/directory-\", \"/\");\n      Blob blob = storageStrategy.newBlob(blobKey);\n      storageStrategy.putBlob(CONTAINER_NAME, blob);\n\n      assertTrue(storageStrategy.blobExists(CONTAINER_NAME, blobKey));\n\n      blob = storageStrategy.getBlob(CONTAINER_NAME, blobKey);\n      assertEquals(blob.getMetadata().getName(), blobKey, \"Created blob name is different\");\n\n      assertTrue(!storageStrategy.blobExists(CONTAINER_NAME,\n              blobKey.substring(0, blobKey.length() - 1)));\n   }\n\n   @Test(dataProvider = \"ignoreOnMacOSX\")\n   public void testGetBlobContentType_AutoDetect_True() throws IOException {\n      FilesystemStorageStrategyImpl storageStrategyAutoDetectContentType = new FilesystemStorageStrategyImpl(\n          new Provider<BlobBuilder>() {\n             @Override\n             public BlobBuilder get() {\n                return new BlobBuilderImpl();\n             }\n          }, TestUtils.TARGET_BASE_DIR, true, new FilesystemContainerNameValidatorImpl(), new FilesystemBlobKeyValidatorImpl(), defaultLocation);\n\n      String blobKey = TestUtils.createRandomBlobKey(\"file-\", \".jpg\");\n      TestUtils.createBlobsInContainer(CONTAINER_NAME, blobKey);\n      Blob blob = storageStrategyAutoDetectContentType.getBlob(CONTAINER_NAME, blobKey);\n      assertEquals(blob.getMetadata().getContentMetadata().getContentType(), \"image/jpeg\");\n\n      blobKey = TestUtils.createRandomBlobKey(\"file-\", \".pdf\");\n      TestUtils.createBlobsInContainer(CONTAINER_NAME, blobKey);\n      blob = storageStrategyAutoDetectContentType.getBlob(CONTAINER_NAME, blobKey);\n      assertEquals(blob.getMetadata().getContentMetadata().getContentType(), \"application/pdf\");\n\n      blobKey = TestUtils.createRandomBlobKey(\"file-\", \".mp4\");\n      TestUtils.createBlobsInContainer(CONTAINER_NAME, blobKey);\n      blob = storageStrategyAutoDetectContentType.getBlob(CONTAINER_NAME, blobKey);\n      assertEquals(blob.getMetadata().getContentMetadata().getContentType(), \"video/mp4\");\n   }\n\n   @Test(dataProvider = \"ignoreOnMacOSX\")\n   public void testGetBlobContentType_AutoDetect_False() throws IOException {\n      String blobKey = TestUtils.createRandomBlobKey(\"file-\", \".jpg\");\n      TestUtils.createBlobsInContainer(CONTAINER_NAME, blobKey);\n      Blob blob = storageStrategy.getBlob(CONTAINER_NAME, blobKey);\n      assertEquals(blob.getMetadata().getContentMetadata().getContentType(), null);\n   }\n\n   public void testListDirectoryBlob() throws IOException {\n      String blobKey = TestUtils.createRandomBlobKey(\"directory-\", File.separator);\n      Blob blob = storageStrategy.newBlob(blobKey);\n      storageStrategy.putBlob(CONTAINER_NAME, blob);\n\n      Iterable<String> keys = storageStrategy.getBlobKeysInsideContainer(CONTAINER_NAME, null, null);\n      Iterator<String> iter = keys.iterator();\n      assertTrue(iter.hasNext());\n      assertEquals(iter.next(), blobKey);\n      assertFalse(iter.hasNext());\n   }\n\n   public void testDeleteDirectoryBlob() throws IOException {\n      String blobKey = TestUtils.createRandomBlobKey(\"a/b/c/directory-\", \"/\");\n      Blob blob = storageStrategy.newBlob(blobKey);\n      storageStrategy.putBlob(CONTAINER_NAME, blob);\n      File blobFullPath = new File(TARGET_CONTAINER_NAME, blobKey);\n      assertTrue(blobFullPath.isDirectory());\n\n      storageStrategy.removeBlob(CONTAINER_NAME, blobKey);\n   }\n\n   @Test(dataProvider = \"ignoreOnMacOSX\")\n   public void testDeleteIntermediateDirectoryBlob() throws IOException {\n      String parentKey = TestUtils.createRandomBlobKey(\"a/b/c/directory-\", \"/\");\n      String childKey = TestUtils.createRandomBlobKey(parentKey + \"directory-\", \"/\");\n      storageStrategy.putBlob(CONTAINER_NAME, storageStrategy.newBlob(parentKey));\n      storageStrategy.putBlob(CONTAINER_NAME, storageStrategy.newBlob(childKey));\n\n      storageStrategy.removeBlob(CONTAINER_NAME, parentKey);\n      Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);\n      assertFalse(storageStrategy.blobExists(CONTAINER_NAME, parentKey));\n      assertTrue(storageStrategy.blobExists(CONTAINER_NAME, childKey));\n   }\n\n   public void testWritePayloadOnFile() throws IOException {\n      String blobKey = TestUtils.createRandomBlobKey(\"writePayload-\", \".img\");\n      File sourceFile = TestUtils.getImageForBlobPayload();\n      FilePayload filePayload = new FilePayload(sourceFile);\n      Blob blob = storageStrategy.newBlob(blobKey);\n      blob.setPayload(filePayload);\n\n      // write files\n      storageStrategy.putBlob(CONTAINER_NAME, blob);\n\n      // verify that the files is equal\n      File blobFullPath = new File(TARGET_CONTAINER_NAME, blobKey);\n      ByteSource expectedInput = Files.asByteSource(sourceFile);\n      ByteSource actualInput = Files.asByteSource(blobFullPath);\n      assertTrue(expectedInput.contentEquals(actualInput),\n            \"Files are not equal\");\n   }\n\n   public void testWritePayloadOnFileInputStream() throws IOException {\n      String blobKey = TestUtils.createRandomBlobKey(\"writePayload-\", \".img\");\n      File sourceFile = TestUtils.getImageForBlobPayload();\n      InputStreamPayload fileInputStreamPayload = new InputStreamPayload(\n            new FileInputStream(sourceFile));\n      Blob blob = storageStrategy.newBlob(blobKey);\n      blob.setPayload(fileInputStreamPayload);\n\n      // write files\n      storageStrategy.putBlob(CONTAINER_NAME, blob);\n\n      // verify that the files is equal\n      File blobFullPath = new File(TARGET_CONTAINER_NAME, blobKey);\n      ByteSource expectedInput = Files.asByteSource(sourceFile);\n      ByteSource actualInput = Files.asByteSource(blobFullPath);\n      assertTrue(expectedInput.contentEquals(actualInput),\n            \"Files are not equal\");\n   }\n\n   public void testWritePayloadOnFile_SourceFileDoesntExist() {\n      File sourceFile = new File(\"asdfkjsadkfjasdlfasdflk.asdfasdfas\");\n      FilePayload payload = new FilePayload(sourceFile);\n      try {\n         payload.getInput();\n         fail(\"Exception not thrown\");\n      } catch (Exception ex) {\n         assertNotNull(Throwables2.getFirstThrowableOfType(ex, IOException.class));\n      }\n   }\n\n   public void testGetFileForBlobKey() {\n      String blobKey;\n      File fileForPayload;\n      String fullPath = (new File(TARGET_CONTAINER_NAME).getAbsolutePath()) + FS;\n\n      blobKey = TestUtils.createRandomBlobKey(\"getFileForBlobKey-\", \".img\");\n      fileForPayload = storageStrategy.getFileForBlobKey(CONTAINER_NAME, blobKey);\n      assertNotNull(fileForPayload, \"Result File object is null\");\n      assertEquals(fileForPayload.getAbsolutePath(), fullPath + blobKey, \"Wrong file path\");\n\n      blobKey = TestUtils.createRandomBlobKey(\"asd\" + FS + \"vmad\" + FS + \"andsnf\" + FS + \"getFileForBlobKey-\", \".img\");\n      fileForPayload = storageStrategy.getFileForBlobKey(CONTAINER_NAME, blobKey);\n      assertEquals(fileForPayload.getAbsolutePath(), fullPath + blobKey, \"Wrong file path\");\n   }\n\n   public void testGetFileForBlobKey_AbsolutePath() throws Exception {\n      String absoluteBasePath = (new File(getAbsoluteDirectory(), \"basedir\")).getAbsolutePath() + FS;\n      String absoluteContainerPath = absoluteBasePath + CONTAINER_NAME + FS;\n\n      // create storageStrategy with an absolute path\n      FilesystemStorageStrategyImpl storageStrategyAbsolute = new FilesystemStorageStrategyImpl(\n               new Provider<BlobBuilder>() {\n                  @Override\n                  public BlobBuilder get() {\n                     return new BlobBuilderImpl();\n                  }\n               }, absoluteBasePath, false, new FilesystemContainerNameValidatorImpl(), new FilesystemBlobKeyValidatorImpl(), defaultLocation);\n      TestUtils.cleanDirectoryContent(absoluteContainerPath);\n\n      String blobKey;\n      File fileForPayload;\n\n      blobKey = TestUtils.createRandomBlobKey(\"getFileForBlobKey-\", \".img\");\n      fileForPayload = storageStrategyAbsolute.getFileForBlobKey(CONTAINER_NAME, blobKey);\n      assertNotNull(fileForPayload, \"Result File object is null\");\n      assertEquals(fileForPayload.getAbsolutePath(), absoluteContainerPath + blobKey, \"Wrong file path\");\n\n      blobKey = TestUtils.createRandomBlobKey(\"asd\" + FS + \"vmad\" + FS + \"andsnf\" + FS + \"getFileForBlobKey-\", \".img\");\n      fileForPayload = storageStrategyAbsolute.getFileForBlobKey(CONTAINER_NAME, blobKey);\n      assertEquals(fileForPayload.getAbsolutePath(), absoluteContainerPath + blobKey, \"Wrong file path\");\n   }\n\n   public void testBlobExists() throws IOException {\n      String[] sourceBlobKeys = { TestUtils.createRandomBlobKey(\"blobExists-\", \".jpg\"),\n               TestUtils.createRandomBlobKey(\"blobExists-\", \".jpg\"),\n               TestUtils.createRandomBlobKey(\"afasd\" + FS + \"asdma\" + FS + \"blobExists-\", \".jpg\") };\n\n      for (String blobKey : sourceBlobKeys) {\n         assertFalse(storageStrategy.blobExists(CONTAINER_NAME, blobKey), \"Blob \" + blobKey + \" exists\");\n      }\n      TestUtils.createBlobsInContainer(CONTAINER_NAME, sourceBlobKeys);\n      for (String blobKey : sourceBlobKeys) {\n         assertTrue(storageStrategy.blobExists(CONTAINER_NAME, blobKey), \"Blob \" + blobKey + \" doesn't exist\");\n      }\n   }\n\n   public void testRemoveBlob() throws IOException {\n      storageStrategy.createContainer(CONTAINER_NAME);\n      Set<String> blobKeys = TestUtils.createBlobsInContainer(CONTAINER_NAME, new String[] {\n               TestUtils.createRandomBlobKey(\"removeBlob-\", \".jpg\"),\n               TestUtils.createRandomBlobKey(\"removeBlob-\", \".jpg\"),\n               TestUtils.createRandomBlobKey(\"346\" + FS + \"g3sx2\" + FS + \"removeBlob-\", \".jpg\"),\n               TestUtils.createRandomBlobKey(\"346\" + FS + \"g3sx2\" + FS + \"removeBlob-\", \".jpg\") });\n\n      Set<String> remainingBlobKeys = Sets.newHashSet();\n      for (String key : blobKeys) {\n         remainingBlobKeys.add(key);\n      }\n      for (String blobKeyToRemove : blobKeys) {\n         storageStrategy.removeBlob(CONTAINER_NAME, blobKeyToRemove);\n         // checks if the blob was removed\n         TestUtils.fileExists(blobKeyToRemove, false);\n         remainingBlobKeys.remove(blobKeyToRemove);\n         // checks if all other blobs still exists\n         for (String remainingBlobKey : remainingBlobKeys) {\n            TestUtils.fileExists(TARGET_CONTAINER_NAME + FS + remainingBlobKey, true);\n         }\n      }\n   }\n\n   public void testRemoveBlob_ContainerNotExists() {\n      storageStrategy.removeBlob(\"asdasdasd\", \"sdfsdfsdfasd\");\n   }\n\n   public void testRemoveBlob_BlobNotExists() {\n      storageStrategy.createContainer(CONTAINER_NAME);\n      storageStrategy.removeBlob(CONTAINER_NAME, \"sdfsdfsdfasd\");\n   }\n\n   public void testGetBlobKeysInsideContainer() throws IOException {\n      Iterable<String> resultList;\n\n      // no container\n      resultList = storageStrategy.getBlobKeysInsideContainer(CONTAINER_NAME, null, null);\n      assertNotNull(resultList, \"Result is null\");\n      assertFalse(resultList.iterator().hasNext(), \"Blobs detected\");\n\n      // create blobs\n      storageStrategy.createContainer(CONTAINER_NAME);\n      Set<String> createBlobKeys = TestUtils.createBlobsInContainer(CONTAINER_NAME, new String[] {\n               TestUtils.createRandomBlobKey(\"GetBlobKeys-\", \".jpg\"),\n               TestUtils.createRandomBlobKey(\"GetBlobKeys-\", \".jpg\"),\n               TestUtils.createRandomBlobKey(\"563\" + \"/\" + \"g3sx2\" + \"/\" + \"removeBlob-\", \".jpg\"),\n               TestUtils.createRandomBlobKey(\"563\" + \"/\" + \"g3sx2\" + \"/\" + \"removeBlob-\", \".jpg\") });\n      storageStrategy.getBlobKeysInsideContainer(CONTAINER_NAME, null, null);\n\n      List<String> retrievedBlobKeys = Lists.newArrayList();\n      resultList = storageStrategy.getBlobKeysInsideContainer(CONTAINER_NAME, null, null);\n      Iterator<String> containersIterator = resultList.iterator();\n      while (containersIterator.hasNext()) {\n         retrievedBlobKeys.add(containersIterator.next());\n      }\n      int expectedBlobs = retrievedBlobKeys.size() - 2;  // ignore two directories\n      assertEquals(expectedBlobs, createBlobKeys.size(), \"Different blobs number\");\n      for (String createdBlobKey : createBlobKeys) {\n         assertTrue(retrievedBlobKeys.contains(createdBlobKey), \"Blob \" + createdBlobKey + \" not found\");\n      }\n   }\n\n   public void testCountsBlob() {\n      storageStrategy.countBlobs(CONTAINER_NAME, ListContainerOptions.NONE);\n   }\n\n   public void testInvalidBlobKey() {\n      try {\n         storageStrategy.newBlob(FS + \"test.jpg\");\n         fail(\"Wrong blob key not recognized\");\n      } catch (IllegalArgumentException e) {\n      }\n   }\n\n   public void testInvalidContainerName() {\n      try {\n         storageStrategy.createContainer(\"file\" + FS + \"system\");\n         fail(\"Wrong container name not recognized\");\n      } catch (IllegalArgumentException e) {\n      }\n   }\n\n   @Test(dataProvider = \"ignoreOnMacOSX\")\n   public void testOverwriteBlobMetadata() throws Exception {\n      String blobKey = TestUtils.createRandomBlobKey(\"writePayload-\", \".img\");\n\n      // write blob\n      Blob blob = new BlobBuilderImpl()\n            .name(blobKey)\n            .payload(randomByteSource().slice(0, 1024))\n            .userMetadata(ImmutableMap.of(\"key1\", \"value1\"))\n            .build();\n      storageStrategy.putBlob(CONTAINER_NAME, blob);\n\n      blob = storageStrategy.getBlob(CONTAINER_NAME, blobKey);\n      assertEquals(blob.getMetadata().getUserMetadata().get(\"key1\"), \"value1\");\n\n      // overwrite blob\n      blob = new BlobBuilderImpl()\n            .name(blobKey)\n            .payload(randomByteSource().slice(0, 1024))\n            // no metadata\n            .build();\n      Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);\n      storageStrategy.putBlob(CONTAINER_NAME, blob);\n\n      blob = storageStrategy.getBlob(CONTAINER_NAME, blobKey);\n      assertFalse(blob.getMetadata().getUserMetadata().containsKey(\"key1\"));\n   }\n\n   @Test\n   public void testPutIncorrectContentLength() throws Exception {\n      Blob blob = new BlobBuilderImpl()\n            .name(\"key\")\n            .payload(randomByteSource().slice(0, 1024))\n            .contentLength(512)\n            .build();\n      try {\n         storageStrategy.putBlob(CONTAINER_NAME, blob);\n         Fail.failBecauseExceptionWasNotThrown(IOException.class);\n      } catch (IOException ioe) {\n         // expected\n      }\n   }\n\n   @Test\n   public void testDeletingInvalidPathFileEndsNormally() {\n      String invalidPathBlobKey = \"A<!:!@#$%^&*?]8 /\\0\";\n      try {\n         storageStrategy.removeBlob(CONTAINER_NAME, invalidPathBlobKey);\n      } catch (InvalidPathException ipe) {\n         fail(\"Deleting an invalid path ended with an InvalidPathException.\", ipe);\n      }\n   }\n\n   @Test\n   public void testGetBlobTrailingSlash() throws Exception {\n      String key = \"key\";\n      ByteSource byteSource = randomByteSource().slice(0, 1024);\n      Blob blob = new BlobBuilderImpl()\n            .name(key)\n            .payload(byteSource)\n            .contentLength(byteSource.size())\n            .build();\n      storageStrategy.putBlob(CONTAINER_NAME, blob);\n\n      blob = storageStrategy.getBlob(CONTAINER_NAME, key);\n      assertThat(blob).isNotNull();\n\n      blob = storageStrategy.getBlob(CONTAINER_NAME, key + \"/\");\n      assertThat(blob).isNull();\n   }\n\n   @Test\n   public void testPutBlobTrailingSlash() throws Exception {\n      String key = \"key\";\n      ByteSource byteSource = ByteSource.empty();\n      Blob blob = new BlobBuilderImpl()\n            .name(key + \"/\")\n            .payload(byteSource)\n            .contentLength(byteSource.size())\n            .build();\n      storageStrategy.putBlob(CONTAINER_NAME, blob);\n\n      blob = storageStrategy.getBlob(CONTAINER_NAME, key);\n      assertThat(blob).isNull();\n\n      blob = storageStrategy.getBlob(CONTAINER_NAME, key + \"/\");\n      assertThat(blob).isNotNull();\n   }\n\n   // ---------------------------------------------------------- Private methods\n\n   /**\n    * Calculates an absolute directory path that depends on operative system\n    *\n    * @return\n    */\n   private String getAbsoluteDirectory() throws IOException {\n      File tempFile = File.createTempFile(\"prefix\", \"suffix\");\n      String tempAbsolutePath = tempFile.getParent();\n\n      return tempAbsolutePath;\n   }\n\n   @DataProvider\n   public Object[][] ignoreOnMacOSX() {\n        return isMacOSX() ? NO_INVOCATIONS\n                : SINGLE_NO_ARG_INVOCATION;\n   }\n}\n"
  },
  {
    "path": "apis/filesystem/src/test/java/org/jclouds/filesystem/utils/TestUtils.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.filesystem.utils;\n\nimport static org.jclouds.utils.TestUtils.randomByteSource;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Iterator;\nimport java.util.Random;\nimport java.util.Set;\nimport java.util.UUID;\n\nimport org.jclouds.filesystem.util.Utils;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Iterators;\nimport com.google.common.collect.Sets;\nimport com.google.common.io.ByteSource;\nimport com.google.common.io.Files;\n\n/**\n * Utility class for test\n */\npublic class TestUtils {\n\n    private static final String TARGET_RESOURCE_DIR = \".\" + File.separator + \"target\" + File.separator + \"resources\" + File.separator;\n\n    /** All the files available for the tests */\n    private static final Iterable<File> IMAGE_RESOURCES = ImmutableList.of(\n                    new File(TARGET_RESOURCE_DIR + \"image1.jpg\"),\n                    new File(TARGET_RESOURCE_DIR + \"image2.jpg\"),\n                    new File(TARGET_RESOURCE_DIR + \"image3.jpg\"),\n                    new File(TARGET_RESOURCE_DIR + \"image4.jpg\"));\n\n    public static final String TARGET_BASE_DIR = \".\" + File.separator + \"target\" + File.separator + \"basedir\" + File.separator;\n\n    private static final Iterator<File> IMAGE_RESOURCES_ITERATOR =\n            Iterators.cycle(IMAGE_RESOURCES);\n\n    /**\n     * Generate a random blob key simple name (with no path in the key)\n     * @return \n     */\n    public static String createRandomBlobKey() {\n        return createRandomBlobKey(\"\", \"\");\n    }\n\n    /**\n     * Generate a random blob key simple name (with no path in the key)\n     * @param prefix a prefix to the id, default \"testkey-\"\n     * @param extension a extension for the blob key, default \".jpg\"\n     * @return\n     */\n    public static String createRandomBlobKey(String prefix, String extension) {\n        String okPrefix = (null != prefix && !\"\".equals(prefix)) ? prefix : \"testkey-\";\n        String okExtension = (null != extension && !\"\".equals(extension)) ? extension : \".jpg\";\n        return okPrefix + UUID.randomUUID().toString() + okExtension;\n    }\n\n    /**\n     * Creates blobs in container\n     * @param containerName\n     * @param blobNames\n     * @return a Set with all blobs created\n     * @throws IOException\n     */\n   public static Set<String> createBlobsInContainer(String containerName, String... blobNames) throws IOException {\n        Set<String> blobNamesCreatedInContainer = Sets.newHashSet();\n        for (String blobName : blobNames) {\n            createBlobAsFile(containerName, blobName, getImageForBlobPayload());\n            blobNamesCreatedInContainer.add(blobName);\n        }\n        return blobNamesCreatedInContainer;\n    }\n\n    /**\n     * Creates a container object creating a directory\n     * @param containerName\n     * @throws IOException\n     */\n    public static void createContainerAsDirectory(String containerName) throws IOException {\n        File file = new File(TARGET_BASE_DIR, containerName);\n        if (!file.mkdirs()) {\n            throw new IOException(\"Could not mkdir: \" + file);\n        }\n    }\n\n    /**\n     *\n     * @param directoryFullPath the directory path\n     * @return\n     */\n    public static boolean directoryExists(String directoryFullPath) {\n        File file = new File(directoryFullPath);\n        boolean exists = file.exists() || file.isDirectory();\n\n        return exists;\n    }\n\n    /**\n     * \n     * @param directoryFullPath\n     * @param checkResult\n     * @param expectedResult\n     * @return\n     */\n    public static boolean directoryExists(String directoryFullPath, boolean expectedResult) {\n        boolean exists = directoryExists(directoryFullPath);\n\n        if (expectedResult) {\n            assertTrue(exists, \"Directory \" + directoryFullPath + \" doens't exists\");\n        } else {\n            assertFalse(exists, \"Directory \" + directoryFullPath + \" still exists\");\n        }\n        return exists;\n    }\n\n\n    public static boolean fileExists(String fileFullName) {\n        File file = new File(fileFullName);\n        boolean exists = file.exists() || file.isFile();\n        return exists;\n    }\n\n    /**\n     *\n     * @param fileFullName\n     * @param checkResult\n     * @param expectedResult\n     * @return\n     */\n    public static boolean fileExists(String fileFullName, boolean expectedResult) {\n        boolean exists = fileExists(fileFullName);\n\n        if (expectedResult) {\n            assertTrue(exists, \"File \" + fileFullName + \" doens't exists\");\n        } else {\n            assertFalse(exists, \"File \" + fileFullName + \" still exists\");\n        }\n        return exists;\n    }\n\n\n    /**\n     * Empty a directory\n     * \n     * @param directoryName\n     * @throws IOException\n     */\n    public static void cleanDirectoryContent(String directoryName) throws IOException {\n        File parentDirectory = new File(directoryName);\n        File[] children = parentDirectory.listFiles();\n        if (null != children) {\n            for (File child : children) {\n                Utils.deleteRecursively(child);\n            }\n        }\n    }\n\n    /**\n     * Create a blob object from a given file\n     * @param source\n     * @param containerName\n     * @param blobKey\n     * @throws IOException\n     */\n    public static void createBlobAsFile(String containerName, String blobKey, File source) throws IOException {\n        String filePath;\n        if (blobKey.startsWith(\"\\\\\"))\n            filePath = containerName  + blobKey;\n        else\n            filePath = containerName + File.separator + blobKey;\n        File file = new File(TARGET_BASE_DIR + filePath);\n        Files.createParentDirs(file);\n        Files.copy(source, file);\n    }\n\n\n    /**\n     * Returns a pointer to an image, cycling between the ones that are available\n     * @return\n     */\n    public static File getImageForBlobPayload() {\n        return IMAGE_RESOURCES_ITERATOR.next();\n    }\n\n    /** Create resources used by tests. */\n    public static void createResources() throws IOException {\n        File resourceDir = new File(TestUtils.TARGET_RESOURCE_DIR);\n        if (resourceDir.exists()) {\n            Utils.deleteRecursively(resourceDir);\n        }\n        if (!resourceDir.mkdir()) {\n            throw new IOException(\"Could not create: \" + TARGET_RESOURCE_DIR);\n        }\n        Random random = new Random();\n        for (File file : IMAGE_RESOURCES) {\n            int length = random.nextInt(2 * 1024 * 1024);\n            ByteSource byteSource = randomByteSource().slice(0, length);\n            byteSource.copyTo(Files.asByteSink(file));\n        }\n    }\n\n    public static boolean isWindowsOs() {\n        return System.getProperty(\"os.name\", \"\").toLowerCase().contains(\"windows\");\n    }\n}\n"
  },
  {
    "path": "apis/filesystem/src/test/resources/logging.properties",
    "content": "#\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\n#\n\n# Set the default logging level for all loggers to WARNING\n.level = INFO\n\nhandlers = java.util.logging.ConsoleHandler\njava.util.logging.ConsoleHandler.level = ALL\njava.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter\n"
  },
  {
    "path": "apis/glacier/README.md",
    "content": "AWS Glacier\n======================\nYou can find more information about our Glacier provider in this [guide](http://jclouds.apache.org/guides/glacier/)\n\nLicense\n-------\nLicensed under the Apache License, Version 2.0\n"
  },
  {
    "path": "apis/glacier/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.glacier.*;version=\"${project.version}\";-noimport:=true"
  },
  {
    "path": "apis/glacier/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://maven.apache.org/POM/4.0.0\"\n         xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n\n  <groupId>org.apache.jclouds.api</groupId>\n  <artifactId>glacier</artifactId>\n  <name>Apache jclouds :: AWS :: Glacier API</name>\n  <description>jclouds components to access an implementation of glacier</description>\n\n  <properties>\n    <test.aws.identity>FIXME_IDENTITY</test.aws.identity>\n    <test.aws.credential>FIXME_CREDENTIAL</test.aws.credential>\n    <test.glacier.endpoint>https://glacier.us-east-1.amazonaws.com</test.glacier.endpoint>\n    <test.glacier.api-version>2012-06-01</test.glacier.api-version>\n    <test.glacier.build-version />\n    <test.glacier.identity>${test.aws.identity}</test.glacier.identity>\n    <test.glacier.credential>${test.aws.credential}</test.glacier.credential>\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>sts</artifactId>\n      <version>${project.version}</version>\n      <type>jar</type>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-blobstore</artifactId>\n      <version>${project.version}</version>\n      <type>jar</type>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-blobstore</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-log4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.logging.log4j</groupId>\n      <artifactId>log4j-core</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.squareup.okhttp3</groupId>\n      <artifactId>mockwebserver</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.assertj</groupId>\n      <artifactId>assertj-core</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <suiteXmlFiles>\n                    <suiteXmlFile>src/test/resources/testng.xml</suiteXmlFile>\n                  </suiteXmlFiles>\n                  <groups>live</groups>\n                  <excludedGroups>livelong</excludedGroups>\n                  <systemPropertyVariables>\n                    <jclouds.blobstore.httpstream.url>\n                      ${jclouds.blobstore.httpstream.url}\n                    </jclouds.blobstore.httpstream.url>\n                    <jclouds.blobstore.httpstream.md5>\n                      ${jclouds.blobstore.httpstream.md5}\n                    </jclouds.blobstore.httpstream.md5>\n                    <test.glacier.endpoint>${test.glacier.endpoint}</test.glacier.endpoint>\n                    <test.glacier.api-version>${test.glacier.api-version}</test.glacier.api-version>\n                    <test.glacier.build-version>${test.glacier.build-version}</test.glacier.build-version>\n                    <test.glacier.identity>${test.glacier.identity}</test.glacier.identity>\n                    <test.glacier.credential>${test.glacier.credential}</test.glacier.credential>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n    <profile>\n      <id>livelong</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <suiteXmlFiles>\n                    <suiteXmlFile>src/test/resources/testng.xml</suiteXmlFile>\n                  </suiteXmlFiles>\n                  <groups>live</groups>\n                  <excludedGroups>liveshort, setup</excludedGroups>\n                  <systemPropertyVariables>\n                    <jclouds.blobstore.httpstream.url>\n                      ${jclouds.blobstore.httpstream.url}\n                    </jclouds.blobstore.httpstream.url>\n                    <jclouds.blobstore.httpstream.md5>\n                      ${jclouds.blobstore.httpstream.md5}\n                    </jclouds.blobstore.httpstream.md5>\n                    <test.glacier.endpoint>${test.glacier.endpoint}</test.glacier.endpoint>\n                    <test.glacier.api-version>${test.glacier.api-version}</test.glacier.api-version>\n                    <test.glacier.build-version>${test.glacier.build-version}</test.glacier.build-version>\n                    <test.glacier.identity>${test.glacier.identity}</test.glacier.identity>\n                    <test.glacier.credential>${test.glacier.credential}</test.glacier.credential>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n    <profile>\n      <id>livelongsetup</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <suiteXmlFiles>\n                    <suiteXmlFile>src/test/resources/testng.xml</suiteXmlFile>\n                  </suiteXmlFiles>\n                  <groups>live</groups>\n                  <excludedGroups>liveshort, longtest</excludedGroups>\n                  <systemPropertyVariables>\n                    <jclouds.blobstore.httpstream.url>\n                      ${jclouds.blobstore.httpstream.url}\n                    </jclouds.blobstore.httpstream.url>\n                    <jclouds.blobstore.httpstream.md5>\n                      ${jclouds.blobstore.httpstream.md5}\n                    </jclouds.blobstore.httpstream.md5>\n                    <test.glacier.endpoint>${test.glacier.endpoint}</test.glacier.endpoint>\n                    <test.glacier.api-version>${test.glacier.api-version}</test.glacier.api-version>\n                    <test.glacier.build-version>${test.glacier.build-version}</test.glacier.build-version>\n                    <test.glacier.identity>${test.glacier.identity}</test.glacier.identity>\n                    <test.glacier.credential>${test.glacier.credential}</test.glacier.credential>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n</project>\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/GlacierApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier;\n\nimport static org.jclouds.Constants.PROPERTY_IDEMPOTENT_METHODS;\nimport static org.jclouds.aws.reference.AWSConstants.PROPERTY_HEADER_TAG;\nimport static org.jclouds.reflect.Reflection2.typeToken;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.blobstore.BlobStoreContext;\nimport org.jclouds.glacier.blobstore.config.GlacierBlobStoreContextModule;\nimport org.jclouds.glacier.config.GlacierHttpApiModule;\nimport org.jclouds.glacier.config.GlacierParserModule;\nimport org.jclouds.glacier.reference.GlacierHeaders;\nimport org.jclouds.rest.internal.BaseHttpApiMetadata;\n\nimport com.google.auto.service.AutoService;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n/**\n * Implementation of ApiMetadata for Amazon Glacier API\n */\n@AutoService(ApiMetadata.class)\npublic class GlacierApiMetadata extends BaseHttpApiMetadata {\n\n   private static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromApiMetadata(this);\n   }\n\n   public GlacierApiMetadata() {\n      this(builder());\n   }\n\n   protected GlacierApiMetadata(Builder builder) {\n      super(new Builder());\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = BaseHttpApiMetadata.defaultProperties();\n      properties.setProperty(PROPERTY_HEADER_TAG, GlacierHeaders.DEFAULT_AMAZON_HEADERTAG);\n      properties.setProperty(PROPERTY_IDEMPOTENT_METHODS, \"DELETE,GET,HEAD,OPTIONS,POST,PUT\");\n      return properties;\n   }\n\n   public static class Builder extends BaseHttpApiMetadata.Builder<GlacierClient, Builder> {\n\n      protected Builder() {\n         super(GlacierClient.class);\n         id(\"glacier\")\n               .name(\"Amazon Glacier API\")\n               .identityName(\"Access Key ID\")\n               .credentialName(\"Secret Access Key\")\n               .defaultEndpoint(\"https://glacier.us-east-1.amazonaws.com\")\n               .documentation(URI.create(\"http://docs.aws.amazon.com/amazonglacier/latest/dev/amazon-glacier-api.html\"))\n               .version(\"2012-06-01\")\n               .defaultProperties(GlacierApiMetadata.defaultProperties())\n               .view(typeToken(BlobStoreContext.class))\n               .defaultModules(ImmutableSet.<Class<? extends Module>> of(GlacierHttpApiModule.class,\n                     GlacierParserModule.class, GlacierBlobStoreContextModule.class));\n      }\n\n      @Override\n      public GlacierApiMetadata build() {\n         return new GlacierApiMetadata(this);\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/GlacierClient.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier;\n\nimport static org.jclouds.blobstore.attr.BlobScopes.CONTAINER;\n\nimport java.io.Closeable;\nimport java.net.URI;\nimport java.util.Map;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.blobstore.attr.BlobScope;\nimport org.jclouds.glacier.binders.BindArchiveOutputRangeToHeaders;\nimport org.jclouds.glacier.binders.BindArchiveSizeToHeaders;\nimport org.jclouds.glacier.binders.BindContentRangeToHeaders;\nimport org.jclouds.glacier.binders.BindDescriptionToHeaders;\nimport org.jclouds.glacier.binders.BindHashesToHeaders;\nimport org.jclouds.glacier.binders.BindJobRequestToJsonPayload;\nimport org.jclouds.glacier.binders.BindMultipartTreeHashToHeaders;\nimport org.jclouds.glacier.binders.BindPartSizeToHeaders;\nimport org.jclouds.glacier.domain.ArchiveMetadataCollection;\nimport org.jclouds.glacier.domain.JobMetadata;\nimport org.jclouds.glacier.domain.JobRequest;\nimport org.jclouds.glacier.domain.MultipartUploadMetadata;\nimport org.jclouds.glacier.domain.PaginatedJobCollection;\nimport org.jclouds.glacier.domain.PaginatedMultipartUploadCollection;\nimport org.jclouds.glacier.domain.PaginatedVaultCollection;\nimport org.jclouds.glacier.domain.VaultMetadata;\nimport org.jclouds.glacier.fallbacks.FalseOnIllegalArgumentException;\nimport org.jclouds.glacier.filters.RequestAuthorizeSignature;\nimport org.jclouds.glacier.functions.GetPayloadFromHttpContent;\nimport org.jclouds.glacier.functions.ParseArchiveIdHeader;\nimport org.jclouds.glacier.functions.ParseArchiveMetadataCollectionFromHttpContent;\nimport org.jclouds.glacier.functions.ParseJobIdHeader;\nimport org.jclouds.glacier.functions.ParseJobMetadataFromHttpContent;\nimport org.jclouds.glacier.functions.ParseJobMetadataListFromHttpContent;\nimport org.jclouds.glacier.functions.ParseMultipartUploadIdHeader;\nimport org.jclouds.glacier.functions.ParseMultipartUploadListFromHttpContent;\nimport org.jclouds.glacier.functions.ParseMultipartUploadPartListFromHttpContent;\nimport org.jclouds.glacier.functions.ParseMultipartUploadTreeHashHeader;\nimport org.jclouds.glacier.functions.ParseVaultMetadataFromHttpContent;\nimport org.jclouds.glacier.functions.ParseVaultMetadataListFromHttpContent;\nimport org.jclouds.glacier.options.PaginationOptions;\nimport org.jclouds.glacier.predicates.validators.DescriptionValidator;\nimport org.jclouds.glacier.predicates.validators.PartSizeValidator;\nimport org.jclouds.glacier.predicates.validators.PayloadValidator;\nimport org.jclouds.glacier.predicates.validators.VaultNameValidator;\nimport org.jclouds.glacier.reference.GlacierHeaders;\nimport org.jclouds.glacier.util.ContentRange;\nimport org.jclouds.io.Payload;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.Headers;\nimport org.jclouds.rest.annotations.ParamValidators;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\n\nimport com.google.common.hash.HashCode;\n\n/** Provides access to Amazon Glacier resources via their REST API. */\n@Headers(keys = GlacierHeaders.VERSION, values = \"2012-06-01\")\n@RequestFilters(RequestAuthorizeSignature.class)\n@BlobScope(CONTAINER)\npublic interface GlacierClient extends Closeable {\n\n   /**\n    * Creates a new vault to store archives. An account can only create up to 1,000 vaults per region, but each vault\n    * can contain an unlimited number of archives.\n    *\n    * @param vaultName\n    *           A name for the Vault being created.\n    * @return A reference to an URI pointing to the resource created.\n    */\n   @Named(\"CreateVault\")\n   @PUT\n   @Path(\"/-/vaults/{vault}\")\n   URI createVault(@ParamValidators(VaultNameValidator.class) @PathParam(\"vault\") String vaultName);\n\n   /**\n    * Deletes a vault. Vaults can only be deleted if there are no archives in the vault in the last inventory computed\n    * by Amazon, and there are no new uploads after it. This is very important, as Amazon only updates inventories once\n    * every 24 hours.\n    *\n    * @param vaultName\n    *           Name of the Vault being deleted.\n    * @return False if the vault was not empty and therefore not deleted, true otherwise.\n    */\n   @Named(\"DeleteVault\")\n   @DELETE\n   @Path(\"/-/vaults/{vault}\")\n   @Fallback(FalseOnIllegalArgumentException.class)\n   boolean deleteVault(@ParamValidators(VaultNameValidator.class) @PathParam(\"vault\") String vaultName);\n\n   /**\n    * Retrieves the metadata for a vault. The response include information like the vault ARN, the creation data, the\n    * number of archives contained within the vault and total size of these archives. The number of archives and\n    * the total size is based on the last inventory computed by amazon and the information may be outdated.\n    *\n    * @param vaultName\n    *           Name of the Vault being described.\n    * @return A VaultMetadata object containing all the information relevant to the vault if the vault exists,\n    * null otherwise.\n    */\n   @Named(\"DescribeVault\")\n   @GET\n   @Path(\"/-/vaults/{vault}\")\n   @ResponseParser(ParseVaultMetadataFromHttpContent.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   VaultMetadata describeVault(@ParamValidators(VaultNameValidator.class) @PathParam(\"vault\") String vaultName);\n\n   /**\n    * Lists vaults according to specified options. By default this operation returns up to 1,000 vaults.\n    *\n    * @param options\n    *          Options used for pagination.\n    * @return A PaginatedVaultCollection object containing the list of vaults.\n    */\n   @Named(\"ListVaults\")\n   @GET\n   @Path(\"/-/vaults\")\n   @ResponseParser(ParseVaultMetadataListFromHttpContent.class)\n   PaginatedVaultCollection listVaults(PaginationOptions options);\n\n   /**\n    * @see GlacierClient#listVaults(PaginationOptions)\n    */\n   @Named(\"ListVaults\")\n   @GET\n   @Path(\"/-/vaults\")\n   @ResponseParser(ParseVaultMetadataListFromHttpContent.class)\n   PaginatedVaultCollection listVaults();\n\n   /**\n    * Stores an archive in a vault. Archives up to 4GB in size can be uploaded using this operation. Once the archive\n    * is uploaded it is immutable, this means that archive or its description cannot be modified. Except for the\n    * optional description Glacier does not support additional metadata.\n    *\n    * @param vaultName\n    *           Name of the Vault where the archive is being stored.\n    * @param payload\n    *           Payload to be uploaded.\n    * @param description\n    *           Description for the archive.\n    * @return A String containing the Archive identifier in Amazon Glacier.\n    */\n   @Named(\"UploadArchive\")\n   @POST\n   @Path(\"/-/vaults/{vault}/archives\")\n   @ResponseParser(ParseArchiveIdHeader.class)\n   String uploadArchive(\n         @ParamValidators(VaultNameValidator.class) @PathParam(\"vault\") String vaultName,\n         @ParamValidators(PayloadValidator.class) @BinderParam(BindHashesToHeaders.class) Payload payload,\n         @ParamValidators(DescriptionValidator.class) @BinderParam(BindDescriptionToHeaders.class) String description);\n\n   /**\n    * @see GlacierClient#uploadArchive(String, org.jclouds.io.Payload, String)\n    */\n   @Named(\"UploadArchive\")\n   @POST\n   @Path(\"/-/vaults/{vault}/archives\")\n   @ResponseParser(ParseArchiveIdHeader.class)\n   String uploadArchive(\n         @ParamValidators(VaultNameValidator.class) @PathParam(\"vault\") String vaultName,\n         @ParamValidators(PayloadValidator.class) @BinderParam(BindHashesToHeaders.class) Payload payload);\n\n   /**\n    * Deletes an archive from a vault. Be aware that after deleting an archive it may still be listed in the\n    * inventories until amazon compute a new inventory.\n    *\n    * @param vaultName\n    *           Name of the Vault where the archive is stored.\n    * @param archiveId\n    *           Amazon Glacier archive identifier.\n    * @return False if the archive was not deleted, true otherwise.\n    */\n   @Named(\"DeleteArchive\")\n   @DELETE\n   @Path(\"/-/vaults/{vault}/archives/{archive}\")\n   boolean deleteArchive(\n         @ParamValidators(VaultNameValidator.class) @PathParam(\"vault\") String vaultName,\n         @PathParam(\"archive\") String archiveId);\n\n   /**\n    * Starts a new multipart upload. Using a multipart upload you can upload archives up to 40,000GB (10,000 parts,\n    * 4GB each). The part size must be a megabyte multiplied by a power of 2 and every part must be the same size\n    * except the last one, which can have a smaller size. In addition, you don't need to know the archive size to\n    * initiate a multipart upload.\n    *\n    * @param vaultName\n    *           Name of the Vault where the archive is going to be stored.\n    * @param partSizeInMB\n    *           Content size for each part.\n    * @param description\n    *           The archive description.\n    * @return The Multipart Upload Id.\n    */\n   @Named(\"InitiateMultipartUpload\")\n   @POST\n   @Path(\"/-/vaults/{vault}/multipart-uploads\")\n   @ResponseParser(ParseMultipartUploadIdHeader.class)\n   String initiateMultipartUpload(\n         @ParamValidators(VaultNameValidator.class) @PathParam(\"vault\") String vaultName,\n         @ParamValidators(PartSizeValidator.class) @BinderParam(BindPartSizeToHeaders.class) long partSizeInMB,\n         @ParamValidators(DescriptionValidator.class) @BinderParam(BindDescriptionToHeaders.class) String description);\n\n   /**\n    * @see GlacierClient#initiateMultipartUpload(String, long, String)\n    */\n   @Named(\"InitiateMultipartUpload\")\n   @POST\n   @Path(\"/-/vaults/{vault}/multipart-uploads\")\n   @ResponseParser(ParseMultipartUploadIdHeader.class)\n   String initiateMultipartUpload(\n         @ParamValidators(VaultNameValidator.class) @PathParam(\"vault\") String vaultName,\n         @ParamValidators(PartSizeValidator.class) @BinderParam(BindPartSizeToHeaders.class) long partSizeInMB);\n\n\n   /**\n    * Uploads one of the multipart upload parts. The part size has to match the one specified in the multipart upload\n    * request, and the range needs to be aligned. In addition, to ensure that the data is not corrupted, the tree hash\n    * and the linear hash are checked by Glacier.\n    *\n    * @param vaultName\n    *           Name of the Vault where the archive is going to be stored.\n    * @param uploadId\n    *           Multipart upload identifier.\n    * @param range\n    *           The content range that this part is uploading.\n    * @param payload\n    *           Content for this part.\n    * @return Tree-hash of the payload calculated by Amazon. This hash needs to be stored to complete the multipart\n    *         upload.\n    */\n   @Named(\"UploadPart\")\n   @PUT\n   @Path(\"/-/vaults/{vault}/multipart-uploads/{uploadId}\")\n   @ResponseParser(ParseMultipartUploadTreeHashHeader.class)\n   HashCode uploadPart(\n         @ParamValidators(VaultNameValidator.class) @PathParam(\"vault\") String vaultName,\n         @PathParam(\"uploadId\") String uploadId,\n         @BinderParam(BindContentRangeToHeaders.class) ContentRange range,\n         @ParamValidators(PayloadValidator.class) @BinderParam(BindHashesToHeaders.class) Payload payload);\n\n   /**\n    * Completes the multipart upload. After uploading all the parts this operation should be called to inform Glacier.\n    * Again, the checksum and the ranges of the whole archive will be computed to verify the data.\n    *\n    * @param vaultName\n    *           Name of the Vault where the archive is going to be stored.\n    * @param uploadId\n    *           Multipart upload identifier.\n    * @param hashes\n    *           Map containing the pairs partnumber-treehash of each uploaded part.\n    * @param archiveSize\n    *           Size of the complete archive.\n    * @return A String containing the Archive identifier in Amazon Glacier.\n    */\n   @Named(\"CompleteMultipartUpload\")\n   @POST\n   @Path(\"/-/vaults/{vault}/multipart-uploads/{uploadId}\")\n   @ResponseParser(ParseArchiveIdHeader.class)\n   String completeMultipartUpload(\n         @ParamValidators(VaultNameValidator.class) @PathParam(\"vault\") String vaultName,\n         @PathParam(\"uploadId\") String uploadId,\n         @BinderParam(BindMultipartTreeHashToHeaders.class) Map<Integer, HashCode> hashes,\n         @BinderParam(BindArchiveSizeToHeaders.class) long archiveSize);\n\n\n   /**\n    * Aborts the multipart upload. Once aborted, you cannot upload any more parts to it.\n    *\n    * @param vaultName\n    *           Name of the Vault where the archive was going to be stored.\n    * @param uploadId\n    *           Multipart upload identifier.\n    * @return True if the multipart upload was aborted, false otherwise.\n    */\n   @Named(\"AbortMultipartUpload\")\n   @DELETE\n   @Path(\"/-/vaults/{vault}/multipart-uploads/{uploadId}\")\n   boolean abortMultipartUpload(\n         @ParamValidators(VaultNameValidator.class) @PathParam(\"vault\") String vaultName,\n         @PathParam(\"uploadId\") String uploadId);\n\n   /**\n    * Lists the multipart upload parts. You can list the parts of an ongoing multipart upload at any time. By default\n    * it returns up to 1,000 uploaded parts, but you can control this using the request options.\n    *\n    * @param vaultName\n    *           Name of the Vault where the archive is going to be stored.\n    * @param uploadId\n    *           Multipart upload identifier.\n    * @param options\n    *          Options used for pagination.\n    * @return A MultipartUploadMetadata, containing an iterable part list with a marker.\n    */\n   @Named(\"ListParts\")\n   @GET\n   @Path(\"/-/vaults/{vault}/multipart-uploads/{uploadId}\")\n   @ResponseParser(ParseMultipartUploadPartListFromHttpContent.class)\n   MultipartUploadMetadata listParts(\n         @ParamValidators(VaultNameValidator.class) @PathParam(\"vault\") String vaultName,\n         @PathParam(\"uploadId\") String uploadId,\n         PaginationOptions options);\n\n\n   /**\n    * @see GlacierClient#listParts(String, String, org.jclouds.glacier.options.PaginationOptions)\n    */\n   @Named(\"ListParts\")\n   @GET\n   @Path(\"/-/vaults/{vault}/multipart-uploads/{uploadId}\")\n   @ResponseParser(ParseMultipartUploadPartListFromHttpContent.class)\n   MultipartUploadMetadata listParts(\n         @ParamValidators(VaultNameValidator.class) @PathParam(\"vault\") String vaultName,\n         @PathParam(\"uploadId\") String uploadId);\n\n   /**\n    * Lists the ongoing multipart uploads in a vault. By default, this operation returns up to  1,000 multipart uploads.\n    * You can control this using the request options.\n    *\n    * @param vaultName\n    *           Name of the Vault where the archive is going to be stored.\n    * @param options\n    *          Options used for pagination.\n    * @return A PaginatedMultipartUploadCollection, containing an iterable multipart upload list with a marker.\n    */\n   @Named(\"ListMultipartUploads\")\n   @GET\n   @Path(\"/-/vaults/{vault}/multipart-uploads\")\n   @ResponseParser(ParseMultipartUploadListFromHttpContent.class)\n   PaginatedMultipartUploadCollection listMultipartUploads(\n         @ParamValidators(VaultNameValidator.class) @PathParam(\"vault\") String vaultName,\n         PaginationOptions options);\n   \n   /**\n    * @see GlacierClient#listMultipartUploads(String, org.jclouds.glacier.options.PaginationOptions)\n    */\n   @Named(\"ListMultipartUploads\")\n   @GET\n   @Path(\"/-/vaults/{vault}/multipart-uploads\")\n   @ResponseParser(ParseMultipartUploadListFromHttpContent.class)\n   PaginatedMultipartUploadCollection listMultipartUploads(\n         @ParamValidators(VaultNameValidator.class) @PathParam(\"vault\") String vaultName);\n\n   /**\n    * Initiates a job. The job can be an inventory retrieval or an archive retrieval. Once the job is started the\n    * estimated time to complete it is ~4 hours.\n    *\n    * @param vaultName\n    *           Name of the target Vault for the job.\n    * @param job\n    *          JobRequest instance with the concrete request.\n    * @return The job identifier.\n    */\n   @Named(\"InitiateJob\")\n   @POST\n   @Path(\"/-/vaults/{vault}/jobs\")\n   @ResponseParser(ParseJobIdHeader.class)\n   String initiateJob(@ParamValidators(VaultNameValidator.class) @PathParam(\"vault\") String vaultName,\n         @BinderParam(BindJobRequestToJsonPayload.class) JobRequest job);\n\n   /**\n    * Retrieves information about an ongoing job. Among the information you will find the initiation date, the user who\n    * initiated the job or the status message.\n    *\n    * @param vaultName\n    *           Name of the target Vault for the job.\n    * @param jobId\n    *          Job identifier.\n    * @return The job metadata if the job exists in the vault, null otherwise.\n    */\n   @Named(\"DescribeJob\")\n   @GET\n   @Path(\"/-/vaults/{vault}/jobs/{job}\")\n   @ResponseParser(ParseJobMetadataFromHttpContent.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   JobMetadata describeJob(@ParamValidators(VaultNameValidator.class) @PathParam(\"vault\") String vaultName,\n         @PathParam(\"job\") String jobId);\n\n   /**\n    * Lists the ongoing jobs and the recently finished jobs for a vault. By default this operation returns up to\n    * 1,000 jobs in the response, but you can control this using the request options. Note that this operation also\n    * returns the recently finished jobs and you can still download their output.\n    *\n    * @param vaultName\n    *           Name of the target Vault.\n    * @param options\n    *          Options used for pagination\n    * @return A PaginatedJobCollection, containing an iterable job list with a marker.\n    */\n   @Named(\"ListJobs\")\n   @GET\n   @Path(\"/-/vaults/{vault}/jobs\")\n   @ResponseParser(ParseJobMetadataListFromHttpContent.class)\n   PaginatedJobCollection listJobs(@ParamValidators(VaultNameValidator.class) @PathParam(\"vault\") String vaultName,\n         PaginationOptions options);\n\n   /**\n    * Lists jobs.\n    */\n   @Named(\"ListJobs\")\n   @GET\n   @Path(\"/-/vaults/{vault}/jobs\")\n   @ResponseParser(ParseJobMetadataListFromHttpContent.class)\n   PaginatedJobCollection listJobs(@ParamValidators(VaultNameValidator.class) @PathParam(\"vault\") String vaultName);\n\n   /**\n    * Gets the raw job output of any kind of job. You can download the job output within the 24 hour period after\n    * Glacier comlpetes a job.\n    *\n    * @param vaultName\n    *           Name of the target Vault for the job.\n    * @param jobId\n    *          Job identifier.\n    * @param range\n    *          The range of bytes to retrieve from the output.\n    * @return The content data.\n    */\n   @Named(\"GetJobOutput\")\n   @GET\n   @Path(\"/-/vaults/{vault}/jobs/{job}/output\")\n   @ResponseParser(GetPayloadFromHttpContent.class)\n   Payload getJobOutput(@ParamValidators(VaultNameValidator.class) @PathParam(\"vault\") String vaultName,\n         @PathParam(\"job\") String jobId,\n         @BinderParam(BindArchiveOutputRangeToHeaders.class) ContentRange range);\n\n   /**\n    * Downloads the output of an archive retrieval job.\n    *\n    * @param vaultName\n    *           Name of the target Vault for the job.\n    * @param jobId\n    *          Job identifier.\n    * @return The content data.\n    */\n   @Named(\"GetJobOutput\")\n   @GET\n   @Path(\"/-/vaults/{vault}/jobs/{job}/output\")\n   @ResponseParser(GetPayloadFromHttpContent.class)\n   Payload getJobOutput(@ParamValidators(VaultNameValidator.class) @PathParam(\"vault\") String vaultName,\n         @PathParam(\"job\") String jobId);\n\n   /**\n    * Gets the job output for the given job ID. The job must be an inventory retrieval, otherwise this operation will\n    * fail. This operation will parse the job output and build a collection of ArchiveMetadata.\n    *\n    * @param vaultName\n    *           Name of the target Vault for the job.\n    * @param jobId\n    *          Job identifier.\n    * @return The ArchiveMetadata collection\n    */\n   @Named(\"GetInventoryRetrievalOutput\")\n   @GET\n   @Path(\"/-/vaults/{vault}/jobs/{job}/output\")\n   @ResponseParser(ParseArchiveMetadataCollectionFromHttpContent.class)\n   ArchiveMetadataCollection getInventoryRetrievalOutput(@ParamValidators(VaultNameValidator.class) @PathParam(\"vault\") String vaultName,\n         @PathParam(\"job\") String jobId);\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/GlacierResponseException.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.glacier.domain.GlacierError;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\n\n/**\n * Encapsulates a GlacierError.\n */\npublic class GlacierResponseException extends HttpResponseException {\n\n   private static final long serialVersionUID = 1L;\n   private final GlacierError error;\n\n   public GlacierResponseException(HttpCommand command, HttpResponse response, GlacierError error) {\n      super(\"request \" + command.getCurrentRequest().getRequestLine() + \" failed with code \" + response.getStatusCode()\n            + \", error: \" + error.toString(), command, response);\n      this.error = checkNotNull(error, \"error\");\n   }\n\n   public GlacierError getError() {\n      return error;\n   }\n\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/binders/BindArchiveOutputRangeToHeaders.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.glacier.util.ContentRange;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\n/**\n * Binds the ContentRange to the request headers.\n */\npublic class BindArchiveOutputRangeToHeaders implements Binder {\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkArgument(input instanceof ContentRange, \"This binder is only valid for ContentRange\");\n      checkNotNull(request, \"request\");\n      ContentRange range = ContentRange.class.cast(input);\n      return (R) request.toBuilder().addHeader(\"Range\", \"bytes=\" + range.toString()).build();\n   }\n\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/binders/BindArchiveSizeToHeaders.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.glacier.reference.GlacierHeaders;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\n/**\n * Binds the Archive size to the request headers.\n */\npublic class BindArchiveSizeToHeaders implements Binder {\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkArgument(input instanceof Long, \"This binder is only valid for long\");\n      checkNotNull(request, \"request\");\n      Long archiveSize = Long.class.cast(input);\n      return (R) request.toBuilder()\n            .replaceHeader(GlacierHeaders.ARCHIVE_SIZE, Long.toString(archiveSize))\n            .build();\n   }\n\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/binders/BindContentRangeToHeaders.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.glacier.util.ContentRange;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\nimport com.google.common.net.HttpHeaders;\n\n/**\n * Binds the ContentRange to the request headers.\n */\npublic class BindContentRangeToHeaders implements Binder {\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkArgument(input instanceof ContentRange, \"This binder is only valid for Payload\");\n      checkNotNull(request, \"request\");\n      ContentRange range = ContentRange.class.cast(input);\n      return (R) request.toBuilder().addHeader(HttpHeaders.CONTENT_RANGE, range.buildHeader()).build();\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/binders/BindDescriptionToHeaders.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.glacier.reference.GlacierHeaders;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\n/**\n * Binds the archive description to the request headers.\n */\npublic class BindDescriptionToHeaders implements Binder {\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkNotNull(request, \"request\");\n      if (input == null)\n         return request;\n      checkArgument(input instanceof String, \"This binder is only valid for string\");\n      String description = String.class.cast(input);\n      return (R) request.toBuilder().replaceHeader(GlacierHeaders.ARCHIVE_DESCRIPTION, description).build();\n   }\n\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/binders/BindHashesToHeaders.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.io.IOException;\n\nimport org.jclouds.glacier.reference.GlacierHeaders;\nimport org.jclouds.glacier.util.TreeHash;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.io.Payload;\nimport org.jclouds.rest.Binder;\n\n/**\n * Binds the linear hash and the tree hash of payload to the request headers.\n */\npublic class BindHashesToHeaders implements Binder {\n\n   private HttpRequest addChecksumHeaders(HttpRequest request, Payload payload) {\n      try {\n         TreeHash hash = TreeHash.buildTreeHashFromPayload(payload);\n         request = request.toBuilder()\n               .addHeader(GlacierHeaders.LINEAR_HASH, hash.getLinearHash().toString())\n               .addHeader(GlacierHeaders.TREE_HASH, hash.getTreeHash().toString())\n               .build();\n      } catch (IOException e) {\n         throw new HttpException(\"Error hashing the payload\", e);\n      }\n      return request;\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkArgument(input instanceof Payload, \"This binder is only valid for Payload\");\n      checkNotNull(request, \"request\");\n      Payload payload = Payload.class.cast(input);\n      return (R) addChecksumHeaders(request, payload);\n   }\n\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/binders/BindJobRequestToJsonPayload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.glacier.domain.JobRequest;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.json.Json;\nimport org.jclouds.rest.Binder;\n\nimport com.google.inject.Inject;\n\npublic class BindJobRequestToJsonPayload implements Binder {\n   @Inject\n   private Json json;\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkArgument(input instanceof JobRequest,\n            \"This binder is only valid for JobRequest\");\n      checkNotNull(request, \"request\");\n      request.setPayload(json.toJson(input));\n      return request;\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/binders/BindMultipartTreeHashToHeaders.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\n\nimport org.jclouds.glacier.reference.GlacierHeaders;\nimport org.jclouds.glacier.util.TreeHash;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\nimport com.google.common.hash.HashCode;\n\n/**\n * Binds the Tree hash to the request headers.\n */\npublic class BindMultipartTreeHashToHeaders implements Binder {\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkArgument(input instanceof Map, \"This binder is only valid for Map\");\n      checkNotNull(request, \"request\");\n      Map<Integer, HashCode> map = Map.class.cast(input);\n      checkArgument(map.size() != 0, \"The map cannot be empty\");\n      return (R) request.toBuilder()\n            .addHeader(GlacierHeaders.TREE_HASH, TreeHash.buildTreeHashFromMap(map).toString())\n            .build();\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/binders/BindPartSizeToHeaders.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.glacier.reference.GlacierHeaders;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\n/**\n * Binds the Part size to the request headers.\n */\npublic class BindPartSizeToHeaders implements Binder {\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkArgument(input instanceof Long, \"This binder is only valid for long\");\n      checkNotNull(request, \"request\");\n      Long partSizeInMB = Long.class.cast(input);\n      return (R) request.toBuilder()\n            .replaceHeader(GlacierHeaders.PART_SIZE, Long.toString(partSizeInMB << 20))\n            .build();\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/blobstore/GlacierBlobStore.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.blobstore;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static org.jclouds.util.Predicates2.retry;\n\nimport java.util.List;\nimport java.util.Set;\nimport java.util.concurrent.TimeUnit;\n\nimport org.jclouds.blobstore.BlobStoreContext;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.BlobAccess;\nimport org.jclouds.blobstore.domain.BlobMetadata;\nimport org.jclouds.blobstore.domain.ContainerAccess;\nimport org.jclouds.blobstore.domain.MultipartPart;\nimport org.jclouds.blobstore.domain.MultipartUpload;\nimport org.jclouds.blobstore.domain.MutableBlobMetadata;\nimport org.jclouds.blobstore.domain.PageSet;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.domain.internal.BlobImpl;\nimport org.jclouds.blobstore.domain.internal.MutableBlobMetadataImpl;\nimport org.jclouds.blobstore.internal.BaseBlobStore;\nimport org.jclouds.blobstore.options.CreateContainerOptions;\nimport org.jclouds.blobstore.options.GetOptions;\nimport org.jclouds.blobstore.options.ListContainerOptions;\nimport org.jclouds.blobstore.options.PutOptions;\nimport org.jclouds.blobstore.util.BlobUtils;\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.domain.Location;\nimport org.jclouds.glacier.GlacierClient;\nimport org.jclouds.glacier.blobstore.functions.ArchiveMetadataCollectionToStorageMetadata;\nimport org.jclouds.glacier.blobstore.functions.ListContainerOptionsToInventoryRetrievalJobRequest;\nimport org.jclouds.glacier.blobstore.functions.PaginatedVaultCollectionToStorageMetadata;\nimport org.jclouds.glacier.blobstore.strategy.MultipartUploadStrategy;\nimport org.jclouds.glacier.blobstore.strategy.PollingStrategy;\nimport org.jclouds.glacier.domain.ArchiveRetrievalJobRequest;\nimport org.jclouds.glacier.util.ContentRange;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.PayloadSlicer;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Throwables;\nimport com.google.inject.Inject;\nimport com.google.inject.Provider;\nimport com.google.inject.Singleton;\nimport com.google.inject.name.Named;\n\n@Singleton\npublic class GlacierBlobStore extends BaseBlobStore {\n   public static final long DEFAULT_INVENTORY_UPDATE_TIME = TimeUnit.HOURS.toMillis(24);\n\n   @Inject(optional = true)\n   @Named(\"jclouds.glacier.inventory.update.time\")\n   private long inventoryUpdateTime = DEFAULT_INVENTORY_UPDATE_TIME;\n\n   private final GlacierClient sync;\n   private final Provider<MultipartUploadStrategy> multipartUploadStrategy;\n   private final Provider<PollingStrategy> pollingStrategy;\n   private final PaginatedVaultCollectionToStorageMetadata vaultsToContainers;\n   private final ArchiveMetadataCollectionToStorageMetadata archivesToBlobs;\n   private final ListContainerOptionsToInventoryRetrievalJobRequest containerOptionsToInventoryRetrieval;\n\n   @Inject\n   GlacierBlobStore(BlobStoreContext context, BlobUtils blobUtils, Supplier<Location> defaultLocation,\n                    @Memoized Supplier<Set<? extends Location>> locations, PayloadSlicer slicer, GlacierClient sync,\n                    Provider<MultipartUploadStrategy> multipartUploadStrategy,\n                    Provider<PollingStrategy> pollingStrategy,\n                    PaginatedVaultCollectionToStorageMetadata vaultsToContainers,\n                    ArchiveMetadataCollectionToStorageMetadata archivesToBlobs, ListContainerOptionsToInventoryRetrievalJobRequest containerOptionsToInventoryRetrieval) {\n      super(context, blobUtils, defaultLocation, locations, slicer);\n      this.containerOptionsToInventoryRetrieval = checkNotNull(containerOptionsToInventoryRetrieval,\n            \"containerOptionsToInventoryRetrieval\");\n      this.archivesToBlobs = checkNotNull(archivesToBlobs, \"archivesToBlobs\");\n      this.pollingStrategy = checkNotNull(pollingStrategy, \"pollingStrategy\");\n      this.vaultsToContainers = checkNotNull(vaultsToContainers, \"vaultsToContainers\");\n      this.multipartUploadStrategy = checkNotNull(multipartUploadStrategy, \"multipartUploadStrategy\");\n      this.sync = checkNotNull(sync, \"sync\");\n   }\n\n   /**\n    * Deletes the container and all its blobs.\n    * Inventories will be retrieved until the container is gone. Since inventories need 24 hours to be updated this\n    * operation may take days.\n    *\n    * @param container\n    *          container name\n    * @see <a href=\"http://aws.amazon.com/glacier/faqs/#data-inventories\" />\n    */\n   @Override\n   public void deleteContainer(String container) {\n      // attempt to delete possibly-empty vault to avoid inventory retrieval\n      if (!sync.deleteVault(container)) {\n         deletePathAndEnsureGone(container);\n      }\n   }\n\n   @Override\n   protected void deletePathAndEnsureGone(String container) {\n      checkState(retry(new Predicate<String>() {\n          public boolean apply(String container) {\n             clearContainer(container);\n             return sync.deleteVault(container);\n          }\n       }, inventoryUpdateTime).apply(container), \"%s still exists after deleting!\", container);\n   }\n\n   @Override\n   protected boolean deleteAndVerifyContainerGone(String container) {\n      return sync.deleteVault(container);\n   }\n\n   /**\n    * Lists the containers.\n    *\n    * @return a PageSet of StorageMetadata\n    */\n   @Override\n   public PageSet<? extends StorageMetadata> list() {\n      return vaultsToContainers.apply(sync.listVaults());\n   }\n\n   /**\n    * Checks if the container exists.\n    * This implementation invokes {@link GlacierClient#describeVault(String)}.\n    *\n    * @param container\n    *          container name\n    * @return true if the vault exists, false otherwise\n    */\n   @Override\n   public boolean containerExists(String container) {\n      return sync.describeVault(container) != null;\n   }\n\n   /**\n    * Creates a container.\n    * Location is currently ignored.\n    *\n    * @param location\n    *          currently ignored\n    * @param container\n    *          container name\n    * @return true if the container was created, false otherwise\n    */\n   @Override\n   public boolean createContainerInLocation(@Nullable Location location, String container) {\n      return sync.createVault(container) != null;\n   }\n\n   /**\n    * Creates a container.\n    * Location and options are currently ignored.\n    *\n    * @param location\n    *          currently ignored\n    * @param container\n    *          container name\n    * @param options\n    *          currently ignored\n    * @return true if the container was created, false otherwise\n    */\n   @Override\n   public boolean createContainerInLocation(@Nullable Location location, String container,\n                                            CreateContainerOptions options) {\n      return createContainerInLocation(location, container);\n   }\n\n   @Override\n   public ContainerAccess getContainerAccess(String container) {\n      throw new UnsupportedOperationException(\"not implemented\");\n   }\n\n   @Override\n   public void setContainerAccess(String container, ContainerAccess access) {\n      throw new UnsupportedOperationException(\"not implemented\");\n   }\n\n   /**\n    * Lists the blobs in the container.\n    * An inventory will be retrieved to obtain the list. Note that this will take hours and the result may be\n    * inaccurate (Inventories are updated every 24 hours).\n    *\n    * @param container\n    *          container name\n    * @param listContainerOptions\n    *          list options\n    * @return the blob list\n    * @see <a href=\"http://aws.amazon.com/glacier/faqs/#data-inventories\" />\n    */\n   @Override\n   public PageSet<? extends StorageMetadata> list(String container, ListContainerOptions listContainerOptions) {\n      String jobId = sync.initiateJob(container, containerOptionsToInventoryRetrieval.apply(listContainerOptions));\n      try {\n         if (pollingStrategy.get().waitForSuccess(container, jobId)) {\n            return archivesToBlobs.apply(sync.getInventoryRetrievalOutput(container, jobId));\n         }\n      } catch (InterruptedException e) {\n         Throwables.propagate(e);\n      }\n      return null;\n   }\n\n   /**\n    * Checks if the blob exists in the container.\n    * An inventory will be retrieved to obtain the blob list and the method will iterate through it. This operation\n    * will take several hours and the result may be inaccurate (Inventories are updated every 24 hours).\n    *\n    * @param container\n    *          container name\n    * @param key\n    *          blob key\n    * @return true if the blob exists, false otherwise\n    * @see <a href=\"http://aws.amazon.com/glacier/faqs/#data-inventories\" />\n    */\n   @Override\n   public boolean blobExists(String container, String key) {\n      return blobMetadata(container, key) != null;\n   }\n\n   /**\n    * Stores a blob in a container. The blob name will be ignored, since it's not supported by Glacier.\n    *\n    * @param container\n    *          container name\n    * @param blob\n    *          blob to upload\n    * @return the blob name\n    */\n   @Override\n   public String putBlob(String container, Blob blob) {\n      return sync.uploadArchive(container, blob.getPayload());\n   }\n\n   /**\n    * Stores the blob in a container.\n    *\n    * @param container\n    *          container name\n    * @param blob\n    *          blob to upload\n    * @param options\n    *          upload options.\n    * @return the blob name\n    */\n   @Override\n   public String putBlob(String container, Blob blob, PutOptions options) {\n      if (options.isMultipart()) {\n         return multipartUploadStrategy.get().execute(container, blob);\n      }\n      return putBlob(container, blob);\n   }\n\n   /**\n    * Retrieves the blob metadata.\n    * An inventory will be retrieved to obtain the blob list and the method will iterate through it. This operation\n    * will take several hours and the result may be inaccurate (Inventories are updated every 24 hours).\n    *\n    * @param container\n    *          container name\n    * @param key\n    *          blob name\n    * @return null if the blob doesn't exist, the blob metadata otherwise\n    * @see <a href=\"http://aws.amazon.com/glacier/faqs/#data-inventories\" />\n    */\n   @Override\n   public BlobMetadata blobMetadata(String container, String key) {\n      PageSet<? extends StorageMetadata> blobMetadataSet = list(container, null);\n      for (StorageMetadata blob : blobMetadataSet) {\n         if (blob.getName().equals(key)) {\n            return (BlobMetadata) blob;\n         }\n      }\n      return null;\n   }\n\n   private static ArchiveRetrievalJobRequest buildArchiveRetrievalRequest(String key, GetOptions getOptions) {\n      ArchiveRetrievalJobRequest.Builder requestBuilder = ArchiveRetrievalJobRequest.builder().archiveId(key);\n      if (getOptions != null) {\n         int size = getOptions.getRanges().size();\n         checkArgument(size <= 1, \"The number of ranges should be zero or one\");\n         if (size == 1) {\n            requestBuilder.range(ContentRange.fromString(getOptions.getRanges().get(0)));\n         }\n      }\n      return requestBuilder.build();\n   }\n\n   /**\n    * Retrieves the blob\n    * This operation will take several hours.\n    *\n    * @param container\n    *          container name\n    * @param key\n    *          blob name\n    * @return The blob to retrieve, or null if the blob doesn't exist or the archive retrieval fails\n    */\n   @Override\n   public Blob getBlob(String container, String key, GetOptions getOptions) {\n      String jobId = sync.initiateJob(container, buildArchiveRetrievalRequest(key, getOptions));\n      try {\n         if (pollingStrategy.get().waitForSuccess(container, jobId)) {\n            MutableBlobMetadata blobMetadata = new MutableBlobMetadataImpl();\n            blobMetadata.setContainer(container);\n            blobMetadata.setName(key);\n\n            Blob blob = new BlobImpl(blobMetadata);\n            blob.setPayload(sync.getJobOutput(container, jobId));\n            return blob;\n         }\n      } catch (InterruptedException e) {\n         Throwables.propagate(e);\n      }\n      return null;\n   }\n\n   /**\n    * Retrieves the blob using default options\n    * This operation will take several hours.\n    *\n    * @param container\n    *          container name\n    * @param key\n    *          blob name\n    * @return The blob to retrieve, or null if the blob doesn't exist or the archive retrieval fails\n    */\n   @Override\n   public Blob getBlob(String container, String key) {\n      return getBlob(container, key, null);\n   }\n\n   /**\n    * Deletes the blob.\n    *\n    * @param container\n    *          container name\n    * @param key\n    *          blob name\n    */\n   @Override\n   public void removeBlob(String container, String key) {\n      sync.deleteArchive(container, key);\n   }\n\n   @Override\n   public BlobAccess getBlobAccess(String container, String name) {\n      return BlobAccess.PRIVATE;\n   }\n\n   @Override\n   public void setBlobAccess(String container, String name, BlobAccess access) {\n      throw new UnsupportedOperationException(\"not implemented\");\n   }\n\n   @Override\n   public MultipartUpload initiateMultipartUpload(String container, BlobMetadata blobMetadata, PutOptions options) {\n      throw new UnsupportedOperationException(\"not yet implemented\");\n   }\n\n   @Override\n   public void abortMultipartUpload(MultipartUpload mpu) {\n      throw new UnsupportedOperationException(\"not yet implemented\");\n   }\n\n   @Override\n   public String completeMultipartUpload(MultipartUpload mpu, List<MultipartPart> parts) {\n      throw new UnsupportedOperationException(\"not yet implemented\");\n   }\n\n   @Override\n   public MultipartPart uploadMultipartPart(MultipartUpload mpu, int partNumber, Payload payload) {\n      throw new UnsupportedOperationException(\"not yet implemented\");\n   }\n\n   @Override\n   public List<MultipartPart> listMultipartUpload(MultipartUpload mpu) {\n      throw new UnsupportedOperationException(\"not yet implemented\");\n   }\n\n   @Override\n   public List<MultipartUpload> listMultipartUploads(String container) {\n      throw new UnsupportedOperationException(\"not yet implemented\");\n   }\n\n   @Override\n   public long getMinimumMultipartPartSize() {\n      throw new UnsupportedOperationException(\"not yet implemented\");\n   }\n\n   @Override\n   public long getMaximumMultipartPartSize() {\n      throw new UnsupportedOperationException(\"not yet implemented\");\n   }\n\n   @Override\n   public int getMaximumNumberOfParts() {\n      throw new UnsupportedOperationException(\"not yet implemented\");\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/blobstore/config/GlacierBlobStoreContextModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.blobstore.config;\n\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.attr.ConsistencyModel;\nimport org.jclouds.blobstore.strategy.ClearListStrategy;\nimport org.jclouds.glacier.blobstore.GlacierBlobStore;\nimport org.jclouds.glacier.blobstore.strategy.MultipartUploadStrategy;\nimport org.jclouds.glacier.blobstore.strategy.PollingStrategy;\nimport org.jclouds.glacier.blobstore.strategy.SlicingStrategy;\nimport org.jclouds.glacier.blobstore.strategy.internal.BasePollingStrategy;\nimport org.jclouds.glacier.blobstore.strategy.internal.BaseSlicingStrategy;\nimport org.jclouds.glacier.blobstore.strategy.internal.ClearVaultStrategy;\nimport org.jclouds.glacier.blobstore.strategy.internal.SequentialMultipartUploadStrategy;\n\nimport com.google.inject.AbstractModule;\n\npublic class GlacierBlobStoreContextModule extends AbstractModule {\n   @Override\n   protected void configure() {\n      bind(ConsistencyModel.class).toInstance(ConsistencyModel.EVENTUAL);\n      bind(BlobStore.class).to(GlacierBlobStore.class);\n      bind(MultipartUploadStrategy.class).to(SequentialMultipartUploadStrategy.class);\n      bind(SlicingStrategy.class).to(BaseSlicingStrategy.class);\n      bind(ClearListStrategy.class).to(ClearVaultStrategy.class);\n      bind(PollingStrategy.class).to(BasePollingStrategy.class);\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/blobstore/functions/ArchiveMetadataCollectionToStorageMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.blobstore.functions;\n\nimport org.jclouds.blobstore.domain.MutableBlobMetadata;\nimport org.jclouds.blobstore.domain.PageSet;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.domain.internal.MutableBlobMetadataImpl;\nimport org.jclouds.blobstore.domain.internal.PageSetImpl;\nimport org.jclouds.glacier.domain.ArchiveMetadata;\nimport org.jclouds.glacier.domain.ArchiveMetadataCollection;\nimport org.jclouds.io.MutableContentMetadata;\nimport org.jclouds.io.payloads.BaseMutableContentMetadata;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.Iterables;\n\npublic class ArchiveMetadataCollectionToStorageMetadata implements Function<ArchiveMetadataCollection,\n      PageSet<? extends StorageMetadata>>  {\n   @Override\n   public PageSet<? extends StorageMetadata> apply(ArchiveMetadataCollection archives) {\n      return new PageSetImpl<StorageMetadata>(Iterables.transform(archives, new ArchiveMetadataToBlobMetadata()), null);\n   }\n\n   private static class ArchiveMetadataToBlobMetadata implements Function<ArchiveMetadata, MutableBlobMetadata> {\n      @Override\n      public MutableBlobMetadata apply(ArchiveMetadata from) {\n         MutableContentMetadata contentMetadata = new BaseMutableContentMetadata();\n         contentMetadata.setContentLength(from.getSize());\n\n         MutableBlobMetadata to = new MutableBlobMetadataImpl();\n         to.setName(from.getArchiveId());\n         to.setCreationDate(from.getCreationDate());\n         to.setContentMetadata(contentMetadata);\n         return to;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/blobstore/functions/ListContainerOptionsToInventoryRetrievalJobRequest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.blobstore.functions;\n\nimport org.jclouds.blobstore.options.ListContainerOptions;\nimport org.jclouds.glacier.domain.InventoryRetrievalJobRequest;\n\nimport com.google.common.base.Function;\n\npublic class ListContainerOptionsToInventoryRetrievalJobRequest implements Function<ListContainerOptions,\n      InventoryRetrievalJobRequest>  {\n   @Override\n   public InventoryRetrievalJobRequest apply(ListContainerOptions listContainerOptions) {\n      InventoryRetrievalJobRequest.Builder builder = InventoryRetrievalJobRequest.builder();\n      if (listContainerOptions != null) {\n         if (listContainerOptions.getMarker() != null) {\n            builder.marker(listContainerOptions.getMarker());\n         }\n         if (listContainerOptions.getMaxResults() != null) {\n            builder.limit(listContainerOptions.getMaxResults());\n         }\n      }\n      return builder.build();\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/blobstore/functions/PaginatedVaultCollectionToStorageMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.blobstore.functions;\n\nimport org.jclouds.blobstore.domain.PageSet;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.domain.internal.PageSetImpl;\nimport org.jclouds.glacier.domain.PaginatedVaultCollection;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.Iterables;\n\npublic class PaginatedVaultCollectionToStorageMetadata implements Function<PaginatedVaultCollection,\n      PageSet<? extends StorageMetadata>>  {\n   @Override\n   public PageSet<? extends StorageMetadata> apply(PaginatedVaultCollection vaults) {\n      return new PageSetImpl<StorageMetadata>(Iterables.transform(vaults, new VaultMetadataToStorageMetadata()),\n            (String) vaults.nextMarker().orNull());\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/blobstore/functions/VaultMetadataToStorageMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.blobstore.functions;\n\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.domain.StorageType;\nimport org.jclouds.blobstore.domain.internal.StorageMetadataImpl;\nimport org.jclouds.glacier.domain.VaultMetadata;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableMap;\n\npublic class VaultMetadataToStorageMetadata implements Function<VaultMetadata, StorageMetadata> {\n   @Override\n   public StorageMetadata apply(VaultMetadata vault) {\n      return new StorageMetadataImpl(StorageType.CONTAINER, vault.getVaultARN(), vault.getVaultName(), null, null, null,\n            vault.getCreationDate(), vault.getLastInventoryDate(), ImmutableMap.<String, String>of());\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/blobstore/strategy/MultipartUploadStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.blobstore.strategy;\n\nimport org.jclouds.blobstore.domain.Blob;\n\npublic interface MultipartUploadStrategy {\n   String execute(String container, Blob blob);\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/blobstore/strategy/PayloadSlice.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.blobstore.strategy;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.glacier.util.ContentRange;\nimport org.jclouds.io.Payload;\n\n/**\n * Represents an ordered part of data from a payload\n */\npublic class PayloadSlice {\n   private final Payload payload;\n   private final ContentRange range;\n   private final int part;\n\n   public PayloadSlice(Payload payload, ContentRange range, int part) {\n      this.payload = checkNotNull(payload, \"payload\");\n      this.range = checkNotNull(range, \"range\");\n      checkArgument(part >= 0, \"The part number cannot be negative\");\n      this.part = part;\n   }\n\n   public Payload getPayload() {\n      return payload;\n   }\n\n   public ContentRange getRange() {\n      return range;\n   }\n\n   public int getPart() {\n      return part;\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/blobstore/strategy/PollingStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.blobstore.strategy;\n\npublic interface PollingStrategy {\n   boolean waitForSuccess(String vault, String job) throws InterruptedException;\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/blobstore/strategy/SlicingStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.blobstore.strategy;\n\nimport org.jclouds.io.Payload;\n\npublic interface SlicingStrategy {\n   int MAX_LIST_PARTS_RETURNED = 1000;\n   int MAX_LIST_MPU_RETURNED = 1000;\n   int MAX_NUMBER_OF_PARTS = 10000;\n\n   long MIN_PART_SIZE = 1L << 20; //1 MB, last part can be < 1 MB\n   long MAX_PART_SIZE = 1L << 32; //4 GB\n\n   void startSlicing(Payload payload);\n   PayloadSlice nextSlice();\n   boolean hasNext();\n   long getPartSizeInMB();\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/blobstore/strategy/internal/BasePollingStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.blobstore.strategy.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.concurrent.TimeUnit;\n\nimport org.jclouds.glacier.GlacierClient;\nimport org.jclouds.glacier.blobstore.strategy.PollingStrategy;\nimport org.jclouds.glacier.domain.JobMetadata;\nimport org.jclouds.glacier.domain.JobStatus;\n\nimport com.google.inject.Inject;\nimport com.google.inject.Singleton;\n\n/**\n * This implementation waits a fixed amount of time before start polling.\n */\n@Singleton\npublic class BasePollingStrategy implements PollingStrategy {\n   public static final long DEFAULT_INITIAL_WAIT = TimeUnit.HOURS.toMillis(3);\n   public static final long DEFAULT_TIME_BETWEEN_POLLS = TimeUnit.MINUTES.toMillis(15);\n\n   private final GlacierClient client;\n   private final long initialWait;\n   private final long timeBetweenPolls;\n\n   public BasePollingStrategy(GlacierClient client, long initialWait, long timeBetweenPolls) {\n      this.client = checkNotNull(client, \"client\");\n      this.initialWait = initialWait;\n      this.timeBetweenPolls = timeBetweenPolls;\n   }\n\n   @Inject\n   public BasePollingStrategy(GlacierClient client) {\n      this(client, Long.parseLong(System.getProperty(\"test.glacier.initial-wait\",\n              Long.toString(DEFAULT_INITIAL_WAIT))), DEFAULT_TIME_BETWEEN_POLLS);\n   }\n\n   private boolean inProgress(String job, String vault) {\n      JobMetadata jobMetadata = client.describeJob(vault, job);\n      return (jobMetadata != null) && (jobMetadata.getStatusCode() == JobStatus.IN_PROGRESS);\n   }\n\n   private boolean succeeded(String job, String vault) {\n      JobMetadata jobMetadata = client.describeJob(vault, job);\n      return (jobMetadata != null) && (jobMetadata.getStatusCode() == JobStatus.SUCCEEDED);\n   }\n\n   @Override\n   public boolean waitForSuccess(String vault, String job) throws InterruptedException {\n      // Avoid waiting if the job doesn't exist\n      if (client.describeJob(vault, job) == null) {\n         return false;\n      }\n      Thread.sleep(initialWait);\n      while (inProgress(job, vault)) {\n         Thread.sleep(timeBetweenPolls);\n      }\n      return succeeded(job, vault);\n   }\n\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/blobstore/strategy/internal/BaseSlicingStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.blobstore.strategy.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static java.lang.Math.sqrt;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.glacier.blobstore.strategy.PayloadSlice;\nimport org.jclouds.glacier.blobstore.strategy.SlicingStrategy;\nimport org.jclouds.glacier.util.ContentRange;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.PayloadSlicer;\n\nimport com.google.inject.Inject;\nimport com.google.inject.name.Named;\n\n/**\n * This implementation slice a payload based on the (part size)/(number of parts) ratio. This ratio may be overriden.\n */\n@Singleton\npublic class BaseSlicingStrategy implements SlicingStrategy {\n\n   public static final double DEFAULT_RATIO = 0.32; // (part size/number of parts) ratio\n\n   @Inject(optional = true)\n   @Named(\"jclouds.mpu.part.ratio\")\n   private double ratio = DEFAULT_RATIO;\n\n   private final PayloadSlicer slicer;\n   private Payload payload;\n   private volatile long partSizeInMB;\n   private volatile long total;\n   private volatile long copied;\n   private volatile int part;\n\n   @Inject\n   public BaseSlicingStrategy(PayloadSlicer slicer) {\n      this.slicer = checkNotNull(slicer, \"slicer\");\n      this.total = 0;\n      this.copied = 0;\n      this.partSizeInMB = 0;\n      this.part = 0;\n   }\n\n   protected long calculatePartSize(long length) {\n      long lengthInMB = (length / (1L << 20)) + 1;\n      double fpPartSizeInMB = sqrt(ratio * lengthInMB); //Get the part size which matches the given ratio\n      long partSizeInMB = Long.highestOneBit((long) fpPartSizeInMB - 1) << 1;\n      if (partSizeInMB < 1) return 1;\n      else if (partSizeInMB > MAX_PART_SIZE) return MAX_PART_SIZE;\n      return partSizeInMB;\n   }\n\n   public long getRemaining() {\n      return total - copied;\n   }\n\n   @Override\n   public void startSlicing(Payload payload) {\n      this.payload = checkNotNull(payload, \"payload\");\n      this.copied = 0;\n      this.total = checkNotNull(payload.getContentMetadata().getContentLength(), \"contentLength\");\n      this.partSizeInMB = calculatePartSize(total);\n      this.part = 0;\n   }\n\n   @Override\n   public PayloadSlice nextSlice() {\n      checkNotNull(this.payload, \"payload\");\n      long sliceLength = Math.min(getRemaining(), partSizeInMB << 20);\n      Payload slicedPayload = slicer.slice(payload, copied, sliceLength);\n      ContentRange range = ContentRange.build(copied, copied + sliceLength - 1);\n      copied += sliceLength;\n      part++;\n      return new PayloadSlice(slicedPayload, range, part);\n   }\n\n   @Override\n   public boolean hasNext() {\n      return this.getRemaining() != 0;\n   }\n\n   @Override\n   public long getPartSizeInMB() {\n      return partSizeInMB;\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/blobstore/strategy/internal/ClearVaultStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.blobstore.strategy.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.blobstore.options.ListContainerOptions;\nimport org.jclouds.blobstore.strategy.ClearListStrategy;\nimport org.jclouds.glacier.GlacierClient;\nimport org.jclouds.glacier.blobstore.strategy.PollingStrategy;\nimport org.jclouds.glacier.domain.ArchiveMetadata;\nimport org.jclouds.glacier.domain.ArchiveMetadataCollection;\nimport org.jclouds.glacier.domain.InventoryRetrievalJobRequest;\nimport org.jclouds.rest.ResourceNotFoundException;\n\nimport com.google.common.base.Throwables;\nimport com.google.inject.Inject;\nimport com.google.inject.Singleton;\n\n/**\n * An inventory will be retrieved to obtain the blob list and the method will iterate through it deleting the blobs.\n * This operation will take several hours and the result may be inaccurate (Inventories are updated every 24 hours).\n */\n@Singleton\npublic class ClearVaultStrategy implements ClearListStrategy {\n   private final GlacierClient client;\n   private final PollingStrategy pollingStrategy;\n\n   @Inject\n   public ClearVaultStrategy(GlacierClient client, PollingStrategy pollingStrategy) {\n      this.client = checkNotNull(client, \"client\");\n      this.pollingStrategy = checkNotNull(pollingStrategy, \"pollingStrategy\");\n   }\n\n   @Override\n   public void execute(String container, ListContainerOptions listContainerOptions) {\n      String jobId = client.initiateJob(container, InventoryRetrievalJobRequest.builder().build());\n      try {\n         if (pollingStrategy.waitForSuccess(container, jobId)) {\n            ArchiveMetadataCollection archives = client.getInventoryRetrievalOutput(container, jobId);\n            for (ArchiveMetadata archive : archives) {\n               try {\n                  client.deleteArchive(container, archive.getArchiveId());\n               } catch (ResourceNotFoundException ignored) {\n               }\n            }\n         }\n      } catch (InterruptedException e) {\n         Throwables.propagate(e);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/blobstore/strategy/internal/SequentialMultipartUploadStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.blobstore.strategy.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.glacier.GlacierClient;\nimport org.jclouds.glacier.blobstore.strategy.MultipartUploadStrategy;\nimport org.jclouds.glacier.blobstore.strategy.PayloadSlice;\nimport org.jclouds.glacier.blobstore.strategy.SlicingStrategy;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.hash.HashCode;\nimport com.google.inject.Inject;\nimport com.google.inject.Singleton;\n\n/**\n * This implementation uploads the parts sequentially.\n */\n@Singleton\npublic class SequentialMultipartUploadStrategy implements MultipartUploadStrategy {\n   private final GlacierClient client;\n   private final SlicingStrategy slicer;\n\n   @Inject\n   public SequentialMultipartUploadStrategy(GlacierClient client, SlicingStrategy slicer) {\n      this.client = checkNotNull(client, \"client\");\n      this.slicer = checkNotNull(slicer, \"slicer\");\n   }\n\n   @Override\n   public String execute(String container, Blob blob) {\n      slicer.startSlicing(blob.getPayload());\n      String uploadId = client.initiateMultipartUpload(container, slicer.getPartSizeInMB(),\n            blob.getMetadata().getName());\n      try {\n         ImmutableMap.Builder<Integer, HashCode> hashes = ImmutableMap.builder();\n         while (slicer.hasNext()) {\n            PayloadSlice slice = slicer.nextSlice();\n            hashes.put(slice.getPart(),\n                  client.uploadPart(container, uploadId, slice.getRange(), slice.getPayload()));\n         }\n         return client.completeMultipartUpload(container, uploadId, hashes.build(),\n               blob.getPayload().getContentMetadata().getContentLength());\n      } catch (RuntimeException exception) {\n         client.abortMultipartUpload(container, uploadId);\n         throw exception;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/config/GlacierHttpApiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.config;\n\nimport java.util.concurrent.TimeUnit;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.Constants;\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.glacier.GlacierClient;\nimport org.jclouds.glacier.filters.RequestAuthorizeSignature;\nimport org.jclouds.glacier.handlers.ParseGlacierErrorFromJsonContent;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.annotation.ClientError;\nimport org.jclouds.http.annotation.Redirection;\nimport org.jclouds.http.annotation.ServerError;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.config.HttpApiModule;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.inject.Provides;\nimport com.google.inject.Scopes;\n\n/**\n * Configures the mappings. Installs the Object and Parser modules.\n */\n@ConfiguresHttpApi\npublic class GlacierHttpApiModule extends HttpApiModule<GlacierClient> {\n\n   @Override\n   protected void configure() {\n      super.configure();\n      bind(RequestAuthorizeSignature.class).in(Scopes.SINGLETON);\n   }\n\n   @Provides\n   @TimeStamp\n   protected String provideTimeStamp(@TimeStamp Supplier<String> cache) {\n      return cache.get();\n   }\n\n   @Provides\n   @TimeStamp\n   Supplier<String> provideTimeStampCache(@Named(Constants.PROPERTY_SESSION_INTERVAL) long seconds,\n         final DateService dateService) {\n      return Suppliers.memoizeWithExpiration(new Supplier<String>() {\n\n         @Override\n         public String get() {\n            return dateService.iso8601SecondsDateFormat().replaceAll(\"[-:]\", \"\");\n         }\n      }, seconds, TimeUnit.SECONDS);\n   }\n\n   @Override\n   protected void bindErrorHandlers() {\n      bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(ParseGlacierErrorFromJsonContent.class);\n      bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(ParseGlacierErrorFromJsonContent.class);\n      bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(ParseGlacierErrorFromJsonContent.class);\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/config/GlacierParserModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.config;\n\nimport org.jclouds.json.config.GsonModule.DateAdapter;\nimport org.jclouds.json.config.GsonModule.Iso8601DateAdapter;\n\nimport com.google.inject.AbstractModule;\n\n/**\n * Configures the parser mappings.\n */\npublic class GlacierParserModule extends AbstractModule {\n\n   @Override\n   protected void configure() {\n      bind(DateAdapter.class).to(Iso8601DateAdapter.class);\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/domain/ArchiveMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ComparisonChain;\nimport com.google.common.hash.HashCode;\nimport com.google.gson.annotations.SerializedName;\n\npublic class ArchiveMetadata implements Comparable<ArchiveMetadata> {\n\n   @SerializedName(\"ArchiveId\")\n   private final String archiveId;\n   @SerializedName(\"ArchiveDescription\")\n   private final String description;\n   @SerializedName(\"CreationDate\")\n   private final Date creationDate;\n   @SerializedName(\"Size\")\n   private final long size;\n   @SerializedName(\"SHA256TreeHash\")\n   private final HashCode treeHash;\n\n   @ConstructorProperties({ \"ArchiveId\", \"ArchiveDescription\", \"CreationDate\", \"Size\", \"SHA256TreeHash\" })\n   public ArchiveMetadata(String archiveId, @Nullable String description, Date creationDate, long size, String hashCode) {\n      this.archiveId = checkNotNull(archiveId, \"archiveId\");\n      this.description = description;\n      this.creationDate = (Date) checkNotNull(creationDate, \"creationDate\").clone();\n      this.size = size;\n      this.treeHash = HashCode.fromString(checkNotNull(hashCode, \"hashCode\"));\n   }\n\n   public String getArchiveId() {\n      return archiveId;\n   }\n\n   public String getDescription() {\n      return description;\n   }\n\n   public Date getCreationDate() {\n      return (Date) creationDate.clone();\n   }\n\n   public long getSize() {\n      return size;\n   }\n\n   public HashCode getTreeHash() {\n      return treeHash;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(this.archiveId, this.description, this.creationDate, this.size, this.treeHash);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      ArchiveMetadata other = (ArchiveMetadata) obj;\n\n      return Objects.equal(this.archiveId, other.archiveId)\n            && Objects.equal(this.description, other.description)\n            && Objects.equal(this.creationDate, other.creationDate)\n            && Objects.equal(this.treeHash, other.treeHash)\n            && Objects.equal(this.size, other.size);\n   }\n\n   @Override\n   public String toString() {\n      return \"ArchiveMetadata [archiveId=\" + archiveId + \", description=\" + description\n            + \", creationDate=\" + creationDate + \", treeHash=\" + treeHash + \", size=\" + size + \"]\";\n   }\n\n   @Override\n   public int compareTo(ArchiveMetadata o) {\n      return ComparisonChain.start().compare(this.archiveId, o.archiveId).result();\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/domain/ArchiveMetadataCollection.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\nimport java.util.Iterator;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.gson.annotations.SerializedName;\n\n\npublic class ArchiveMetadataCollection extends FluentIterable<ArchiveMetadata>{\n\n   @SerializedName(\"ArchiveList\")\n   private final Iterable<ArchiveMetadata> archives;\n   @SerializedName(\"VaultARN\")\n   private final String vaultARN;\n   @SerializedName(\"InventoryDate\")\n   private final Date inventoryDate;\n\n   @ConstructorProperties({ \"ArchiveList\", \"VaultARN\", \"InventoryDate\" })\n   public ArchiveMetadataCollection(Iterable<ArchiveMetadata> archives, String vaultARN, Date inventoryDate) {\n      this.archives = checkNotNull(archives, \"archives\");\n      this.vaultARN = checkNotNull(vaultARN, \"vaultARN\");\n      this.inventoryDate = (Date) checkNotNull(inventoryDate, \"inventoryDate\").clone();\n   }\n\n   @Override\n   public Iterator<ArchiveMetadata> iterator() {\n      return archives.iterator();\n   }\n\n   public String getVaultARN() {\n      return vaultARN;\n   }\n\n   public Date getInventoryDate() {\n      return (Date) inventoryDate.clone();\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/domain/ArchiveRetrievalJobRequest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.glacier.util.ContentRange;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.Objects;\nimport com.google.gson.annotations.SerializedName;\n\npublic class ArchiveRetrievalJobRequest extends JobRequest {\n   private static final String TYPE = \"archive-retrieval\";\n\n   @SerializedName(\"ArchiveId\")\n   private final String archiveId;\n   @SerializedName(\"Description\")\n   private final String description;\n   @SerializedName(\"RetrievalByteRange\")\n   private final ContentRange range;\n\n   private ArchiveRetrievalJobRequest(String archiveId, @Nullable String description, @Nullable ContentRange range) {\n      super(TYPE);\n      this.archiveId = checkNotNull(archiveId, \"archiveId\");\n      this.description = description;\n      this.range = range;\n   }\n\n   @ConstructorProperties({ \"ArchiveId\", \"Description\", \"RetrievalByteRange\" })\n   private ArchiveRetrievalJobRequest(String archiveId, @Nullable String description, @Nullable String range) {\n      this(archiveId, description, range == null ? null : ContentRange.fromString(range));\n   }\n\n   public String getDescription() {\n      return description;\n   }\n\n   public ContentRange getRange() {\n      return range;\n   }\n\n   public String getArchiveId() {\n      return archiveId;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(this.archiveId, this.description, this.range);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      ArchiveRetrievalJobRequest other = (ArchiveRetrievalJobRequest) obj;\n\n      return Objects.equal(this.archiveId, other.archiveId) && Objects.equal(this.description, other.description)\n            && Objects.equal(this.range, other.range);\n   }\n\n   @Override\n   public String toString() {\n      return \"InventoryRetrievalParameters [archiveId=\" + archiveId + \", description=\" + description + \", range=\"\n            + range + \"]\";\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n      private String archiveId;\n      private String description;\n      private ContentRange range;\n\n      Builder() {\n      }\n\n      public Builder archiveId(String archiveId) {\n         this.archiveId = archiveId;\n         return this;\n      }\n\n      public Builder description(String description) {\n         this.description = description;\n         return this;\n      }\n\n      public Builder range(ContentRange range) {\n         this.range = range;\n         return this;\n      }\n\n      public ArchiveRetrievalJobRequest build() {\n         return new ArchiveRetrievalJobRequest(archiveId, description, range);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/domain/GlacierError.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.Objects;\n\n/**\n * Defines attributes to describe a GlacierError\n */\npublic class GlacierError {\n\n   private final String code;\n   private final String message;\n   private final String type;\n\n   @ConstructorProperties({ \"code\", \"message\", \"type\" })\n   public GlacierError(@Nullable String code, @Nullable String message, @Nullable String type) {\n      this.code = code;\n      this.message = message;\n      this.type = type;\n   }\n\n   public String getCode() {\n      return code;\n   }\n\n   public String getMessage() {\n      return message;\n   }\n\n   public String getType() {\n      return type;\n   }\n\n   public boolean isValid() {\n      return (this.code != null) && (this.message != null) && (this.type != null);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(this.code, this.message, this.type);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      GlacierError other = (GlacierError) obj;\n\n      return Objects.equal(this.code, other.code)\n            && Objects.equal(this.message, other.message)\n            && Objects.equal(this.type, other.type);\n   }\n\n   @Override\n   public String toString() {\n      return \"GlacierError [code=\" + this.getCode() + \", message=\" + this.getMessage() + \"type=\" + this.getType() + \"]\";\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/domain/InventoryRetrievalJobRequest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.Objects;\nimport com.google.gson.annotations.SerializedName;\n\npublic class InventoryRetrievalJobRequest extends JobRequest {\n   private static final String TYPE = \"inventory-retrieval\";\n\n   @SerializedName(\"Description\")\n   private final String description;\n   @SerializedName(\"Format\")\n   private final String format;\n   @SerializedName(\"InventoryRetrievalParameters\")\n   private final InventoryRetrievalParameters parameters;\n\n   @ConstructorProperties({ \"Description\", \"Format\" })\n   private InventoryRetrievalJobRequest(@Nullable String description, @Nullable String format) {\n      super(TYPE);\n      this.description = description;\n      this.format = format;\n      this.parameters = new InventoryRetrievalParameters();\n   }\n\n   public String getDescription() {\n      return description;\n   }\n\n   public String getFormat() {\n      return format;\n   }\n\n   public InventoryRetrievalParameters getParameters() {\n      return this.parameters;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(this.description, this.format, this.parameters);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      InventoryRetrievalJobRequest other = (InventoryRetrievalJobRequest) obj;\n\n      return Objects.equal(this.description, other.description) && Objects.equal(this.format, other.format)\n            && Objects.equal(this.parameters, other.parameters);\n   }\n\n   @Override\n   public String toString() {\n      return \"InventoryRetrievalJobRequest [description=\" + description + \", format=\" + format + \",\" +\n            \"parameters=\" + parameters + \"]\";\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n      private String description;\n      private String format;\n      private String startDate;\n      private String endDate;\n      private Integer limit;\n      private String marker;\n\n      Builder() {\n      }\n\n      public Builder description(String description) {\n         this.description = description;\n         return this;\n      }\n\n      public Builder format(String format) {\n         this.format = format;\n         return this;\n      }\n\n      public Builder startDate(String startDate) {\n         this.startDate = startDate;\n         return this;\n      }\n\n      public Builder endDate(String endDate) {\n         this.endDate = endDate;\n         return this;\n      }\n\n      public Builder limit(Integer limit) {\n         this.limit = limit;\n         return this;\n      }\n\n      public Builder marker(String marker) {\n         this.marker = marker;\n         return this;\n      }\n\n      public InventoryRetrievalJobRequest build() {\n         InventoryRetrievalJobRequest request = new InventoryRetrievalJobRequest(description, format);\n         request.getParameters().setEndDate(endDate);\n         request.getParameters().setStartDate(startDate);\n         request.getParameters().setLimit(limit);\n         request.getParameters().setMarker(marker);\n         return request;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/domain/InventoryRetrievalParameters.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.domain;\n\nimport com.google.common.base.Objects;\nimport com.google.gson.annotations.SerializedName;\n\npublic class InventoryRetrievalParameters {\n      @SerializedName(\"StartDate\")\n      private String startDate;\n      @SerializedName(\"EndDate\")\n      private String endDate;\n      @SerializedName(\"Limit\")\n      private Integer limit;\n      @SerializedName(\"Marker\")\n      private String marker;\n\n      public InventoryRetrievalParameters() {\n      }\n\n      public String getStartDate() {\n         return startDate;\n      }\n\n      public void setStartDate(String startDate) {\n         this.startDate = startDate;\n      }\n\n      public String getEndDate() {\n         return endDate;\n      }\n\n      public void setEndDate(String endDate) {\n         this.endDate = endDate;\n      }\n\n      public Integer getLimit() {\n         return limit;\n      }\n\n      public void setLimit(Integer limit) {\n         this.limit = limit;\n      }\n\n      public String getMarker() {\n         return marker;\n      }\n\n      public void setMarker(String marker) {\n         this.marker = marker;\n      }\n\n      @Override\n      public int hashCode() {\n         return Objects.hashCode(this.startDate, this.endDate, this.limit, this.marker);\n      }\n\n      @Override\n      public boolean equals(Object obj) {\n         if (obj == null)\n            return false;\n         if (getClass() != obj.getClass())\n            return false;\n         InventoryRetrievalParameters other = (InventoryRetrievalParameters) obj;\n\n         return Objects.equal(this.startDate, other.startDate) && Objects.equal(this.endDate, other.endDate)\n               && Objects.equal(this.limit, other.limit)\n               && Objects.equal(this.marker, other.marker);\n      }\n\n      @Override\n      public String toString() {\n         return \"InventoryRetrievalParameters [startDate=\" + startDate + \", endDate=\" + endDate + \", limit=\" + limit\n               + \", marker=\" + marker + \"]\";\n      }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/domain/JobMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\n\nimport org.jclouds.glacier.util.ContentRange;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.Objects;\nimport com.google.gson.annotations.SerializedName;\n\npublic class JobMetadata {\n   @SerializedName(\"Action\")\n   private final String action;\n   @SerializedName(\"ArchiveId\")\n   private final String archiveId;\n   @SerializedName(\"ArchiveSizeInBytes\")\n   private final Long archiveSizeInBytes;\n   @SerializedName(\"ArchiveSHA256TreeHash\")\n   private final String archiveSHA256TreeHash;\n   @SerializedName(\"Completed\")\n   private final boolean completed;\n   @SerializedName(\"CompletionDate\")\n   private final Date completionDate;\n   @SerializedName(\"CreationDate\")\n   private final Date creationDate;\n   @SerializedName(\"InventorySizeInBytes\")\n   private final Long inventorySizeInBytes;\n   @SerializedName(\"JobDescription\")\n   private final String jobDescription;\n   @SerializedName(\"JobId\")\n   private final String jobId;\n   @SerializedName(\"RetrievalByteRange\")\n   private final ContentRange retrievalByteRange;\n   @SerializedName(\"SHA256TreeHash\")\n   private final String sha256TreeHash;\n   @SerializedName(\"SNSTopic\")\n   private final String snsTopic;\n   @SerializedName(\"StatusCode\")\n   private final JobStatus statusCode;\n   @SerializedName(\"StatusMessage\")\n   private final String statusMessage;\n   @SerializedName(\"VaultARN\")\n   private final String vaultArn;\n   @SerializedName(\"InventoryRetrievalParameters\")\n   private final InventoryRetrievalParameters parameters;\n\n   @ConstructorProperties({ \"Action\", \"ArchiveId\", \"ArchiveSizeInBytes\", \"ArchiveSHA256TreeHash\", \"Completed\",\n         \"CompletionDate\", \"CreationDate\", \"InventorySizeInBytes\", \"JobDescription\", \"JobId\", \"RetrievalByteRange\",\n         \"SHA256TreeHash\", \"SNSTopic\", \"StatusCode\", \"StatusMessage\", \"VaultARN\", \"InventoryRetrievalParameters\" })\n   public JobMetadata(String action, @Nullable String archiveId, @Nullable Long archiveSizeInBytes,\n         @Nullable String archiveSHA256TreeHash, boolean completed, @Nullable Date completionDate, Date creationDate,\n         @Nullable Long inventorySizeInBytes, @Nullable String jobDescription, String jobId,\n         @Nullable String retrievalByteRange, @Nullable String sha256TreeHash, @Nullable String snsTopic,\n         String statusCode, @Nullable String statusMessage, String vaultArn,\n         @Nullable InventoryRetrievalParameters parameters) {\n      super();\n      this.action = checkNotNull(action, \"action\");\n      this.archiveId = archiveId;\n      this.archiveSizeInBytes = archiveSizeInBytes;\n      this.archiveSHA256TreeHash = archiveSHA256TreeHash;\n      this.completed = completed;\n      this.completionDate = completionDate == null ? null : (Date) completionDate.clone();\n      this.creationDate = (Date) checkNotNull(creationDate, \"creationDate\").clone();\n      this.inventorySizeInBytes = inventorySizeInBytes;\n      this.jobDescription = jobDescription;\n      this.jobId = checkNotNull(jobId, \"jobId\");\n      this.retrievalByteRange = retrievalByteRange == null ? null : ContentRange.fromString(retrievalByteRange);\n      this.sha256TreeHash = sha256TreeHash;\n      this.snsTopic = snsTopic;\n      this.statusCode = JobStatus.fromString(checkNotNull(statusCode, \"statusCode\"));\n      this.statusMessage = statusMessage;\n      this.vaultArn = checkNotNull(vaultArn, \"vaultArn\");\n      this.parameters = parameters;\n   }\n\n   public String getAction() {\n      return action;\n   }\n\n   public String getArchiveId() {\n      return archiveId;\n   }\n\n   public Long getArchiveSizeInBytes() {\n      return archiveSizeInBytes;\n   }\n\n   public String getArchiveSHA256TreeHash() {\n      return archiveSHA256TreeHash;\n   }\n\n   public boolean isCompleted() {\n      return completed;\n   }\n\n   public Date getCompletionDate() {\n      return completionDate == null ? null : (Date) completionDate.clone();\n   }\n\n   public Date getCreationDate() {\n      return (Date) creationDate.clone();\n   }\n\n   public Long getInventorySizeInBytes() {\n      return inventorySizeInBytes;\n   }\n\n   public String getJobDescription() {\n      return jobDescription;\n   }\n\n   public String getJobId() {\n      return jobId;\n   }\n\n   public ContentRange getRetrievalByteRange() {\n      return retrievalByteRange;\n   }\n\n   public String getSha256TreeHash() {\n      return sha256TreeHash;\n   }\n\n   public String getSnsTopic() {\n      return snsTopic;\n   }\n\n   public JobStatus getStatusCode() {\n      return statusCode;\n   }\n\n   public String getStatusMessage() {\n      return statusMessage;\n   }\n\n   public String getVaultArn() {\n      return vaultArn;\n   }\n\n   public InventoryRetrievalParameters getParameters() {\n      return parameters;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(this.action, this.archiveId, this.archiveSizeInBytes, this.archiveSHA256TreeHash,\n            this.completed, this.completionDate, this.creationDate, this.inventorySizeInBytes, this.jobDescription,\n            this.jobId, this.retrievalByteRange, this.sha256TreeHash, this.snsTopic, this.statusCode,\n            this.statusMessage, this.vaultArn, this.parameters);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      JobMetadata other = (JobMetadata) obj;\n\n      return Objects.equal(this.jobId, other.jobId);\n   }\n\n   @Override\n   public String toString() {\n      return \"JobMetadata [jobId=\" + jobId + \", statusCode=\" + statusCode + \", statusMessage=\" + statusMessage + \"]\";\n   }\n}\n\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/domain/JobRequest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.gson.annotations.SerializedName;\n\n\npublic abstract class JobRequest {\n   @SerializedName(\"Type\")\n   protected final String type;\n\n   public JobRequest(String type) {\n      this.type = checkNotNull(type, \"type\");\n   }\n\n   public String getType() {\n      return type;\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/domain/JobStatus.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.domain;\n\nimport com.google.common.base.CaseFormat;\n\npublic enum JobStatus {\n   SUCCEEDED,\n   FAILED,\n   IN_PROGRESS;\n\n   public static JobStatus fromString(String symbol) {\n      return JobStatus.valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, symbol));\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/domain/MultipartUploadMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\nimport java.util.Iterator;\n\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.glacier.options.PaginationOptions;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ComparisonChain;\nimport com.google.gson.annotations.SerializedName;\n\n/**\n * Defines the attributes needed for Multipart uploads. Extends IterableWithMarker to support requesting paginated\n * multipart upload parts.\n */\npublic class MultipartUploadMetadata extends IterableWithMarker<PartMetadata> implements Comparable<MultipartUploadMetadata> {\n\n   @SerializedName(\"ArchiveDescription\")\n   private final String archiveDescription;\n   @SerializedName(\"CreationDate\")\n   private final Date creationDate;\n   @SerializedName(\"MultipartUploadId\")\n   private final String multipartUploadId;\n   @SerializedName(\"PartSizeInBytes\")\n   private final long partSizeInBytes;\n   @SerializedName(\"VaultARN\")\n   private final String vaultARN;\n   @SerializedName(\"Parts\")\n   private final Iterable<PartMetadata> parts;\n   @SerializedName(\"Marker\")\n   private final String marker;\n\n   @ConstructorProperties({ \"ArchiveDescription\", \"CreationDate\", \"MultipartUploadId\", \"PartSizeInBytes\", \"VaultARN\",\n         \"Parts\", \"Marker\" })\n   public MultipartUploadMetadata(@Nullable String archiveDescription, Date creationDate, String multipartUploadId,\n         long partSizeInBytes, String vaultARN, @Nullable Iterable<PartMetadata> parts, @Nullable String marker) {\n      super();\n      this.archiveDescription = archiveDescription;\n      this.creationDate = (Date) checkNotNull(creationDate, \"creationDate\").clone();\n      this.multipartUploadId = checkNotNull(multipartUploadId, \"multipartUploadId\");\n      this.partSizeInBytes = partSizeInBytes;\n      this.vaultARN = checkNotNull(vaultARN, \"vaultARN\");\n      this.parts = parts;\n      this.marker = marker;\n   }\n\n   public String getArchiveDescription() {\n      return archiveDescription;\n   }\n\n   public Date getCreationDate() {\n      return (Date) creationDate.clone();\n   }\n\n   public String getMultipartUploadId() {\n      return multipartUploadId;\n   }\n\n   public long getPartSizeInBytes() {\n      return partSizeInBytes;\n   }\n\n   public long getPartSizeInMB() {\n      return partSizeInBytes >> 20;\n   }\n\n   public String getVaultARN() {\n      return vaultARN;\n   }\n\n   @Override\n   public Iterator<PartMetadata> iterator() {\n      return parts == null ? null : parts.iterator();\n   }\n\n   @Override\n   public Optional<Object> nextMarker() {\n      return Optional.<Object>fromNullable(marker);\n   }\n\n   public PaginationOptions nextPaginationOptions() {\n      return PaginationOptions.class.cast(nextMarker().get());\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(this.archiveDescription, this.creationDate, this.multipartUploadId, this.partSizeInBytes,\n            this.vaultARN, this.marker, this.parts);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      MultipartUploadMetadata other = (MultipartUploadMetadata) obj;\n\n      return Objects.equal(this.archiveDescription, other.archiveDescription)\n            && Objects.equal(this.creationDate, other.creationDate)\n            && Objects.equal(this.multipartUploadId, other.multipartUploadId)\n            && Objects.equal(this.partSizeInBytes, other.partSizeInBytes)\n            && Objects.equal(this.vaultARN, other.vaultARN)\n            && Objects.equal(this.marker, other.marker)\n            && Objects.equal(this.parts, other.parts);\n   }\n\n   @Override\n   public String toString() {\n      return \"MultipartUploadMetadata [archiveDescription=\" + archiveDescription + \", creationDate=\" + creationDate\n            + \", multipartUploadId=\" + multipartUploadId + \", partSizeInBytes=\" + partSizeInBytes + \", vaultARN=\"\n            + vaultARN + \", marker=\" + marker + \", parts=\" + parts + \"]\";\n   }\n\n   @Override\n   public int compareTo(MultipartUploadMetadata o) {\n      return ComparisonChain.start().compare(this.creationDate, o.creationDate).result();\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/domain/PaginatedJobCollection.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Iterator;\n\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.glacier.options.PaginationOptions;\n\nimport com.google.common.base.Optional;\nimport com.google.gson.annotations.SerializedName;\n\n/**\n * Paginated collection used to store Job listing information.\n */\npublic class PaginatedJobCollection extends IterableWithMarker<JobMetadata> {\n   @SerializedName(\"JobList\")\n   private final Iterable<JobMetadata> jobs;\n   @SerializedName(\"Marker\")\n   private final String marker;\n\n   @ConstructorProperties({ \"JobList\", \"Marker\" })\n   public PaginatedJobCollection(Iterable<JobMetadata> jobs, String marker) {\n      this.jobs = checkNotNull(jobs, \"jobs\");\n      this.marker = marker;\n   }\n\n   @Override\n   public Iterator<JobMetadata> iterator() {\n      return jobs.iterator();\n   }\n\n   @Override\n   public Optional<Object> nextMarker() {\n      return Optional.<Object>fromNullable(marker);\n   }\n\n   public PaginationOptions nextPaginationOptions() {\n      return PaginationOptions.class.cast(nextMarker().get());\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/domain/PaginatedMultipartUploadCollection.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Iterator;\n\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.glacier.options.PaginationOptions;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.Optional;\nimport com.google.gson.annotations.SerializedName;\n\n/**\n * Paginated collection used to store multipart upload lists.\n */\npublic class PaginatedMultipartUploadCollection extends IterableWithMarker<MultipartUploadMetadata> {\n\n   @SerializedName(\"UploadsList\")\n   private final Iterable<MultipartUploadMetadata> uploads;\n   @SerializedName(\"Marker\")\n   private final String marker;\n\n   @ConstructorProperties({ \"UploadsList\", \"Marker\" })\n   public PaginatedMultipartUploadCollection(Iterable<MultipartUploadMetadata> uploads, @Nullable String marker) {\n      this.uploads = checkNotNull(uploads, \"uploads\");\n      this.marker = marker;\n   }\n\n   @Override\n   public Iterator<MultipartUploadMetadata> iterator() {\n      return uploads.iterator();\n   }\n\n   @Override\n   public Optional<Object> nextMarker() {\n      return Optional.<Object>fromNullable(marker);\n   }\n\n   public PaginationOptions nextPaginationOptions() {\n      return PaginationOptions.class.cast(nextMarker().get());\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/domain/PaginatedVaultCollection.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Iterator;\n\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.glacier.options.PaginationOptions;\n\nimport com.google.common.base.Optional;\nimport com.google.gson.annotations.SerializedName;\n\n/**\n * Paginated collection used to store Vault listing information.\n */\npublic class PaginatedVaultCollection extends IterableWithMarker<VaultMetadata> {\n\n   @SerializedName(\"VaultList\")\n   private final Iterable<VaultMetadata> vaults;\n   @SerializedName(\"Marker\")\n   private final String marker;\n\n   @ConstructorProperties({ \"VaultList\", \"Marker\" })\n   public PaginatedVaultCollection(Iterable<VaultMetadata> vaults, String marker) {\n      this.vaults = checkNotNull(vaults, \"vaults\");\n      this.marker = marker;\n   }\n\n   @Override\n   public Iterator<VaultMetadata> iterator() {\n      return vaults.iterator();\n   }\n\n   @Override\n   public Optional<Object> nextMarker() {\n      return Optional.<Object>fromNullable(marker);\n   }\n\n   public PaginationOptions nextPaginationOptions() {\n      return PaginationOptions.class.cast(nextMarker().get());\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/domain/PartMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.glacier.util.ContentRange;\n\nimport com.google.common.hash.HashCode;\nimport com.google.gson.annotations.SerializedName;\n\n/**\n * Defines the attributes needed for a multipart upload part.\n */\npublic class PartMetadata {\n\n   @SerializedName(\"SHA256TreeHash\")\n   private final HashCode treeHash;\n   @SerializedName(\"RangeInBytes\")\n   private final ContentRange range;\n\n   @ConstructorProperties({ \"SHA256TreeHash\", \"RangeInBytes\" })\n   public PartMetadata(String treeHash, String range) {\n      super();\n      this.treeHash = HashCode.fromString(checkNotNull(treeHash, \"treeHash\"));\n      this.range = ContentRange.fromString(checkNotNull(range, \"range\"));\n   }\n\n   public ContentRange getRange() {\n      return range;\n   }\n\n   public HashCode getTreeHash() {\n      return treeHash;\n   }\n\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/domain/VaultMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ComparisonChain;\nimport com.google.gson.annotations.SerializedName;\n\n/**\n * Defines the attributes needed to describe a vault.\n */\npublic class VaultMetadata implements Comparable<VaultMetadata> {\n\n   @SerializedName(\"VaultName\")\n   private final String vaultName;\n   @SerializedName(\"VaultARN\")\n   private final String vaultARN;\n   @SerializedName(\"CreationDate\")\n   private final Date creationDate;\n   @SerializedName(\"LastInventoryDate\")\n   private final Date lastInventoryDate;\n   @SerializedName(\"NumberOfArchives\")\n   private final long numberOfArchives;\n   @SerializedName(\"SizeInBytes\")\n   private final long sizeInBytes;\n\n   @ConstructorProperties({ \"VaultName\", \"VaultARN\", \"CreationDate\", \"LastInventoryDate\", \"NumberOfArchives\",\n         \"SizeInBytes\" })\n   public VaultMetadata(String vaultName, String vaultARN, Date creationDate, @Nullable Date lastInventoryDate,\n         long numberOfArchives, long sizeInBytes) {\n      this.vaultName = checkNotNull(vaultName, \"vaultName\");\n      this.vaultARN = checkNotNull(vaultARN, \"vaultARN\");\n      this.creationDate = (Date) checkNotNull(creationDate, \"creationDate\").clone();\n      this.lastInventoryDate = lastInventoryDate;\n      this.numberOfArchives = numberOfArchives;\n      this.sizeInBytes = sizeInBytes;\n   }\n\n   public String getVaultName() {\n      return vaultName;\n   }\n\n   public String getVaultARN() {\n      return vaultARN;\n   }\n\n   public Date getCreationDate() {\n      return (Date) creationDate.clone();\n   }\n\n   public Date getLastInventoryDate() {\n      return lastInventoryDate;\n   }\n\n   public long getNumberOfArchives() {\n      return numberOfArchives;\n   }\n\n   public long getSizeInBytes() {\n      return sizeInBytes;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(this.vaultName, this.vaultARN, this.creationDate, this.lastInventoryDate,\n            this.numberOfArchives, this.sizeInBytes);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      VaultMetadata other = (VaultMetadata) obj;\n\n      return Objects.equal(this.vaultName, other.vaultName) && Objects.equal(this.vaultARN, other.vaultARN)\n            && Objects.equal(this.creationDate, other.creationDate)\n            && Objects.equal(this.lastInventoryDate, other.lastInventoryDate)\n            && Objects.equal(this.numberOfArchives, other.numberOfArchives)\n            && Objects.equal(this.sizeInBytes, other.sizeInBytes);\n   }\n\n   @Override\n   public String toString() {\n      return \"VaultMetadata [vaultName=\" + vaultName + \", vaultARN=\" + vaultARN + \", creationDate=\" + creationDate\n            + \", lastInventoryDate=\" + lastInventoryDate + \", numberOfArchives=\" + numberOfArchives + \", sizeInBytes=\"\n            + sizeInBytes + \"]\";\n   }\n\n   @Override\n   public int compareTo(VaultMetadata o) {\n      return ComparisonChain.start().compare(this.vaultName, o.getVaultName()).result();\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/fallbacks/FalseOnIllegalArgumentException.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.fallbacks;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Throwables.propagate;\nimport static org.jclouds.util.Throwables2.getFirstThrowableOfType;\n\nimport org.jclouds.Fallback;\n\n/**\n * Returns false when encountering an IllegalArgumentException.\n */\npublic class FalseOnIllegalArgumentException implements Fallback<Boolean> {\n   @Override\n   public Boolean createOrPropagate(Throwable t) throws Exception {\n      if (getFirstThrowableOfType(checkNotNull(t, \"throwable\"), IllegalArgumentException.class) != null)\n         return false;\n      throw propagate(t);\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/filters/RequestAuthorizeSignature.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.filters;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Provider;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Constants;\nimport org.jclouds.crypto.Crypto;\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.glacier.reference.GlacierHeaders;\nimport org.jclouds.glacier.util.AWSRequestSignerV4;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpRequestFilter;\nimport org.jclouds.http.HttpUtils;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.net.HttpHeaders;\n\n/**\n * Signs the request using the AWSRequestSignerV4.\n */\n@Singleton\npublic class RequestAuthorizeSignature implements HttpRequestFilter {\n\n   private final AWSRequestSignerV4 signer;\n\n   @Resource\n   @Named(Constants.LOGGER_SIGNATURE)\n   Logger signatureLog = Logger.NULL;\n\n   private final Provider<String> timeStampProvider;\n   private final HttpUtils utils;\n\n   @Inject\n   public RequestAuthorizeSignature(@TimeStamp Provider<String> timeStampProvider,\n         @org.jclouds.location.Provider Supplier<Credentials> creds, Crypto crypto, HttpUtils utils) {\n      checkNotNull(creds, \"creds\");\n      this.signer = new AWSRequestSignerV4(creds.get().identity, creds.get().credential, checkNotNull(crypto, \"crypto\"));\n      this.timeStampProvider = checkNotNull(timeStampProvider, \"timeStampProvider\");\n      this.utils = checkNotNull(utils, \"utils\");\n   }\n\n   @Override\n   public HttpRequest filter(HttpRequest request) throws HttpException {\n      request = request.toBuilder().removeHeader(HttpHeaders.DATE)\n            .replaceHeader(GlacierHeaders.ALTERNATE_DATE, timeStampProvider.get())\n            .replaceHeader(HttpHeaders.HOST, request.getEndpoint().getHost()).build();\n      utils.logRequest(signatureLog, request, \">>\");\n      request = this.signer.sign(request);\n      utils.logRequest(signatureLog, request, \"<<\");\n      return request;\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/functions/GetPayloadFromHttpContent.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.functions;\n\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.io.Payload;\n\nimport com.google.common.base.Function;\n\n/**\n * Gets the payload from the http response.\n */\npublic class GetPayloadFromHttpContent implements Function<HttpResponse, Payload> {\n\n   @Override\n   public Payload apply(HttpResponse from) {\n      if (from.getPayload() == null)\n         throw new HttpException(\"Did not receive payload\");\n      return from.getPayload();\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/functions/ParseArchiveIdHeader.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.functions;\n\nimport org.jclouds.glacier.reference.GlacierHeaders;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpResponse;\n\nimport com.google.common.base.Function;\n\n/**\n * Parses the archiveId from the HttpResponse.\n */\npublic class ParseArchiveIdHeader implements Function<HttpResponse, String> {\n\n   @Override\n   public String apply(HttpResponse from) {\n      String id = from.getFirstHeaderOrNull(GlacierHeaders.ARCHIVE_ID);\n      if (id == null)\n         throw new HttpException(\"Did not receive ArchiveId\");\n      return id;\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/functions/ParseArchiveMetadataCollectionFromHttpContent.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.functions;\n\nimport org.jclouds.glacier.domain.ArchiveMetadataCollection;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\n\nimport com.google.inject.Inject;\nimport com.google.inject.TypeLiteral;\n\npublic class ParseArchiveMetadataCollectionFromHttpContent extends ParseJson<ArchiveMetadataCollection> {\n\n   @Inject\n   public ParseArchiveMetadataCollectionFromHttpContent(Json json) {\n      super(json, TypeLiteral.get(ArchiveMetadataCollection.class));\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/functions/ParseJobIdHeader.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.functions;\n\nimport org.jclouds.glacier.reference.GlacierHeaders;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpResponse;\n\nimport com.google.common.base.Function;\n\n/**\n * Parses the jobId from the HttpResponse.\n */\npublic class ParseJobIdHeader implements Function<HttpResponse, String> {\n\n   @Override\n   public String apply(HttpResponse from) {\n      String id = from.getFirstHeaderOrNull(GlacierHeaders.JOB_ID);\n      if (id == null) {\n         throw new HttpException(\"Did not receive JobId\");\n      }\n      return id;\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/functions/ParseJobMetadataFromHttpContent.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.functions;\n\nimport org.jclouds.glacier.domain.JobMetadata;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\n\nimport com.google.inject.Inject;\nimport com.google.inject.TypeLiteral;\n\n/**\n * Parses the JSON job information from the HttpResponse.\n */\npublic class ParseJobMetadataFromHttpContent extends ParseJson<JobMetadata> {\n\n   @Inject\n   public ParseJobMetadataFromHttpContent(Json json) {\n      super(json, TypeLiteral.get(JobMetadata.class));\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/functions/ParseJobMetadataListFromHttpContent.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.functions;\n\nimport org.jclouds.glacier.domain.PaginatedJobCollection;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\n\nimport com.google.inject.Inject;\nimport com.google.inject.TypeLiteral;\n\n/**\n * Parses the JSON job list from the HttpResponse.\n */\npublic class ParseJobMetadataListFromHttpContent extends ParseJson<PaginatedJobCollection> {\n\n   @Inject\n   public ParseJobMetadataListFromHttpContent(Json json) {\n      super(json, TypeLiteral.get(PaginatedJobCollection.class));\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/functions/ParseMultipartUploadIdHeader.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.functions;\n\nimport org.jclouds.glacier.reference.GlacierHeaders;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpResponse;\n\nimport com.google.common.base.Function;\n\n/**\n * Parses the multipart upload id from the HttpResponse.\n */\npublic class ParseMultipartUploadIdHeader implements Function<HttpResponse, String> {\n   @Override\n   public String apply(HttpResponse from) {\n      String id = from.getFirstHeaderOrNull(GlacierHeaders.MULTIPART_UPLOAD_ID);\n      if (id == null)\n         throw new HttpException(\"Did not receive Multipart upload Id\");\n      return id;\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/functions/ParseMultipartUploadListFromHttpContent.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.functions;\n\nimport org.jclouds.glacier.domain.PaginatedMultipartUploadCollection;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\n\nimport com.google.inject.Inject;\nimport com.google.inject.TypeLiteral;\n\n/**\n * Parses the JSON multipart upload list from the HttpResponse.\n */\npublic class ParseMultipartUploadListFromHttpContent extends ParseJson<PaginatedMultipartUploadCollection> {\n\n   @Inject\n   public ParseMultipartUploadListFromHttpContent(Json json) {\n      super(json, TypeLiteral.get(PaginatedMultipartUploadCollection.class));\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/functions/ParseMultipartUploadPartListFromHttpContent.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.functions;\n\nimport org.jclouds.glacier.domain.MultipartUploadMetadata;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\n\nimport com.google.inject.Inject;\nimport com.google.inject.TypeLiteral;\n\n/**\n * Parses the JSON multipart upload part list from the HttpResponse.\n */\npublic class ParseMultipartUploadPartListFromHttpContent extends ParseJson<MultipartUploadMetadata> {\n\n   @Inject\n   public ParseMultipartUploadPartListFromHttpContent(Json json) {\n      super(json, TypeLiteral.get(MultipartUploadMetadata.class));\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/functions/ParseMultipartUploadTreeHashHeader.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.functions;\n\nimport org.jclouds.glacier.reference.GlacierHeaders;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpResponse;\n\nimport com.google.common.base.Function;\nimport com.google.common.hash.HashCode;\n\n/**\n * Parses the tree hash header from the HttpResponse.\n */\npublic class ParseMultipartUploadTreeHashHeader implements Function<HttpResponse, HashCode> {\n   @Override\n   public HashCode apply(HttpResponse from) {\n      String treehash = from.getFirstHeaderOrNull(GlacierHeaders.TREE_HASH);\n      if (treehash == null)\n         throw new HttpException(\"Did not receive Tree hash\");\n      return HashCode.fromString(treehash);\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/functions/ParseVaultMetadataFromHttpContent.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.functions;\n\nimport org.jclouds.glacier.domain.VaultMetadata;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\n\nimport com.google.inject.Inject;\nimport com.google.inject.TypeLiteral;\n\n/**\n * Parses the JSON vault information from the HttpResponse.\n */\npublic class ParseVaultMetadataFromHttpContent extends ParseJson<VaultMetadata> {\n\n   @Inject\n   public ParseVaultMetadataFromHttpContent(Json json) {\n      super(json, TypeLiteral.get(VaultMetadata.class));\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/functions/ParseVaultMetadataListFromHttpContent.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.functions;\n\nimport org.jclouds.glacier.domain.PaginatedVaultCollection;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\n\nimport com.google.inject.Inject;\nimport com.google.inject.TypeLiteral;\n\n/**\n * Parses the JSON vault list from the HttpResponse.\n */\npublic class ParseVaultMetadataListFromHttpContent extends ParseJson<PaginatedVaultCollection> {\n\n   @Inject\n   public ParseVaultMetadataListFromHttpContent(Json json) {\n      super(json, TypeLiteral.get(PaginatedVaultCollection.class));\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/handlers/ParseGlacierErrorFromJsonContent.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.handlers;\n\nimport org.jclouds.glacier.GlacierResponseException;\nimport org.jclouds.glacier.domain.GlacierError;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.InsufficientResourcesException;\nimport org.jclouds.rest.ResourceNotFoundException;\n\nimport com.google.inject.Inject;\nimport com.google.inject.TypeLiteral;\n\n/**\n * Parses a GlacierError from a Json response content.\n */\npublic class ParseGlacierErrorFromJsonContent extends ParseJson<GlacierError> implements HttpErrorHandler {\n\n   @Inject\n   public ParseGlacierErrorFromJsonContent(Json json) {\n      super(json, TypeLiteral.get(GlacierError.class));\n   }\n\n   private static Exception refineException(GlacierError error, Exception exception) {\n      if (\"AccessDeniedException\".equals(error.getCode())) {\n         return new AuthorizationException(error.getMessage(), exception);\n      } else if (\"InvalidParameterValueException\".equals(error.getCode())) {\n         return new IllegalArgumentException(error.getMessage(), exception);\n      } else if (\"LimitExceededException\".equals(error.getCode())) {\n         return new InsufficientResourcesException(error.getMessage(), exception);\n      } else if (\"ResourceNotFoundException\".equals(error.getCode())) {\n         return new ResourceNotFoundException(error.getMessage(), exception);\n      }\n      return exception;\n   }\n\n   @Override\n   public void handleError(HttpCommand command, HttpResponse response) {\n      GlacierError error = this.apply(response);\n      Exception exception = error.isValid()\n            ? refineException(error, new GlacierResponseException(command, response, error))\n            : new HttpResponseException(command, response);\n      command.setException(exception);\n   }\n\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/options/PaginationOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.options;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\n/**\n * Pagination options used to specify the collection responses.\n *\n * @see <a href=\"http://docs.aws.amazon.com/amazonglacier/latest/dev/api-vaults-get.html\" />\n */\npublic class PaginationOptions extends BaseHttpRequestOptions {\n\n   private static final int MIN_LIMIT = 1;\n   private static final int MAX_LIMIT = 1000;\n\n   public PaginationOptions marker(String marker) {\n      queryParameters.put(\"marker\", checkNotNull(marker, \"marker\"));\n      return this;\n   }\n\n   public PaginationOptions limit(int limit) {\n      checkArgument(limit >= MIN_LIMIT, \"limit must be >= \" + MIN_LIMIT + \" but was \" + limit);\n      checkArgument(limit <= MAX_LIMIT, \"limit must be <= \" + MAX_LIMIT + \" but was \" + limit);\n      queryParameters.put(\"limit\", Integer.toString(limit));\n      return this;\n   }\n\n   public static class Builder {\n\n      public static PaginationOptions marker(String marker) {\n         PaginationOptions options = new PaginationOptions();\n         return options.marker(marker);\n      }\n\n      public static PaginationOptions limit(int limit) {\n         PaginationOptions options = new PaginationOptions();\n         return options.limit(limit);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/predicates/validators/DescriptionValidator.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.predicates.validators;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Strings.isNullOrEmpty;\n\nimport org.jclouds.predicates.Validator;\n\nimport com.google.common.base.CharMatcher;\nimport com.google.inject.Singleton;\n\n/**\n * Validates the archive description string.\n */\n@Singleton\npublic final class DescriptionValidator extends Validator<String> {\n\n   private static final int MAX_DESC_LENGTH = 1024;\n\n   private static final CharMatcher DESCRIPTION_ACCEPTABLE_RANGE = CharMatcher.inRange(' ', '~');\n\n   @Override\n   public void validate(String description) {\n      if (isNullOrEmpty(description))\n         return;\n      checkArgument(description.length() <= MAX_DESC_LENGTH,\n            \"Description can't be longer than %s characters but was %s\",\n            MAX_DESC_LENGTH, description.length());\n      checkArgument(DESCRIPTION_ACCEPTABLE_RANGE.matchesAllOf(description),\n            \"Description should have ASCII values between 32 and 126.\");\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/predicates/validators/PartSizeValidator.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.predicates.validators;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.predicates.Validator;\n\nimport com.google.inject.Singleton;\n\n/**\n * Validates the part size parameter used when initiating multipart uploads.\n */\n@Singleton\npublic final class PartSizeValidator extends Validator<Long> {\n   private static final int MIN_PART_SIZE = 1;\n   private static final int MAX_PART_SIZE = 4096;\n\n   @Override\n   public void validate(Long partSizeInMB) throws IllegalArgumentException {\n      checkNotNull(partSizeInMB, \"partSizeInMB\");\n      checkArgument(!(partSizeInMB < MIN_PART_SIZE || partSizeInMB > MAX_PART_SIZE || Long.bitCount(partSizeInMB) != 1),\n            \"partSizeInMB must be a power of 2 between 1 and 4096.\");\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/predicates/validators/PayloadValidator.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.predicates.validators;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.io.Payload;\nimport org.jclouds.predicates.Validator;\n\nimport com.google.inject.Singleton;\n\n/**\n * Validates the Glacier archive payload being uploaded.\n */\n@Singleton\npublic final class PayloadValidator extends Validator<Payload> {\n\n   private static final long MAX_CONTENT_SIZE = 1L << 32; // 4GiB\n\n   @Override\n   public void validate(Payload payload) {\n      checkNotNull(payload, \"Archive must have a payload.\");\n      checkNotNull(payload.getContentMetadata().getContentLength(), \"Content length must be set.\");\n      checkArgument(payload.getContentMetadata().getContentLength() <= MAX_CONTENT_SIZE,\n            \"Max content size is 4gb but was %s\", payload.getContentMetadata().getContentLength());\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/predicates/validators/VaultNameValidator.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.predicates.validators;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Strings.isNullOrEmpty;\n\nimport org.jclouds.predicates.Validator;\n\nimport com.google.common.base.CharMatcher;\nimport com.google.inject.Singleton;\n\n/**\n * Validates Vault names according to Amazon Vault conventions.\n *\n * @see <a href=\"http://docs.aws.amazon.com/amazonglacier/latest/dev/api-vault-put.html\" />\n */\n@Singleton\npublic final class VaultNameValidator extends Validator<String> {\n\n   private static final int MIN_LENGTH = 1;\n   private static final int MAX_LENGTH = 255;\n\n   private static final CharMatcher VAULT_NAME_ACCEPTABLE_RANGE = CharMatcher.inRange('a', 'z')\n         .or(CharMatcher.inRange('A', 'Z'))\n         .or(CharMatcher.inRange('0', '9'))\n         .or(CharMatcher.anyOf(\"-_.\"));\n\n   @Override\n   public void validate(String vaultName) {\n      checkArgument(!isNullOrEmpty(vaultName) && vaultName.length() <= MAX_LENGTH,\n            \"Can't be null or empty. Length must be %s to %s symbols.\", MIN_LENGTH, MAX_LENGTH);\n      checkArgument(VAULT_NAME_ACCEPTABLE_RANGE.matchesAllOf(vaultName),\n            \"Should contain only ASCII letters and numbers, underscores, hyphens, or periods.\");\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/reference/GlacierHeaders.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.reference;\n\n/**\n * Headers used by Amazon Glacier.\n */\npublic final class GlacierHeaders {\n\n   public static final String DEFAULT_AMAZON_HEADERTAG = \"amz\";\n   public static final String HEADER_PREFIX = \"x-\" + DEFAULT_AMAZON_HEADERTAG + \"-\";\n   public static final String REQUEST_ID = HEADER_PREFIX + \"RequestId\";\n   public static final String VERSION = HEADER_PREFIX + \"glacier-version\";\n   public static final String ALTERNATE_DATE = HEADER_PREFIX + \"date\";\n   public static final String ARCHIVE_DESCRIPTION = HEADER_PREFIX + \"archive-description\";\n   public static final String LINEAR_HASH = HEADER_PREFIX + \"content-sha256\";\n   public static final String TREE_HASH = HEADER_PREFIX + \"sha256-tree-hash\";\n   public static final String ARCHIVE_ID = HEADER_PREFIX + \"archive-id\";\n   public static final String MULTIPART_UPLOAD_ID = HEADER_PREFIX + \"multipart-upload-id\";\n   public static final String PART_SIZE = HEADER_PREFIX + \"part-size\";\n   public static final String ARCHIVE_SIZE = HEADER_PREFIX + \"archive-size\";\n   public static final String JOB_ID = HEADER_PREFIX + \"job-id\";\n\n   private GlacierHeaders() {\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/util/AWSRequestSignerV4.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.util;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.util.Closeables2.closeQuietly;\n\nimport java.io.IOException;\nimport java.util.Locale;\nimport java.util.Map.Entry;\n\nimport javax.crypto.Mac;\n\nimport org.jclouds.crypto.Crypto;\nimport org.jclouds.glacier.reference.GlacierHeaders;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpRequest;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Joiner;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Multimap;\nimport com.google.common.collect.SortedSetMultimap;\nimport com.google.common.collect.TreeMultimap;\nimport com.google.common.hash.HashCode;\nimport com.google.common.hash.Hashing;\nimport com.google.common.hash.HashingInputStream;\nimport com.google.common.io.BaseEncoding;\nimport com.google.common.io.ByteSource;\nimport com.google.common.io.ByteStreams;\nimport com.google.common.net.HttpHeaders;\n\n// TODO: Query parameters, not necessary for Glacier\n// TODO: Endpoint on buildCredentialScope is being read from the static string. Uncool.\n/**\n * Signs requests using the AWSv4 signing algorithm\n *\n * @see <a href=\"http://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html\" />\n */\npublic final class AWSRequestSignerV4 {\n\n   public static final String AUTH_TAG = \"AWS4\";\n   public static final String HEADER_TAG = \"x-amz-\";\n   public static final String ALGORITHM = AUTH_TAG + \"-HMAC-SHA256\";\n   public static final String TERMINATION_STRING = \"aws4_request\";\n   public static final String REGION = \"us-east-1\";\n   public static final String SERVICE = \"glacier\";\n\n   private final Crypto crypto;\n   private final String identity;\n   private final String credential;\n\n   public AWSRequestSignerV4(String identity, String credential, Crypto crypto) {\n      this.crypto = checkNotNull(crypto, \"crypto\");\n      this.identity = checkNotNull(identity, \"identity\");\n      this.credential = checkNotNull(credential, \"credential\");\n   }\n\n   private static HashCode buildHashedCanonicalRequest(String method, String endpoint, HashCode hashedPayload,\n         String canonicalizedHeadersString, String signedHeaders) {\n      return Hashing.sha256().newHasher()\n            .putString(method, UTF_8)\n            .putString(\"\\n\", UTF_8)\n            .putString(endpoint, UTF_8)\n            .putString(\"\\n\", UTF_8)\n            .putString(\"\\n\", UTF_8)\n            .putString(canonicalizedHeadersString, UTF_8)\n            .putString(\"\\n\", UTF_8)\n            .putString(signedHeaders, UTF_8)\n            .putString(\"\\n\", UTF_8)\n            .putString(hashedPayload.toString(), UTF_8)\n            .hash();\n   }\n\n   private static String createStringToSign(String date, String credentialScope, HashCode hashedCanonicalRequest) {\n      return ALGORITHM + \"\\n\" + date + \"\\n\" + credentialScope + \"\\n\" + hashedCanonicalRequest.toString();\n   }\n\n   private static String formatDateWithoutTimestamp(String date) {\n      return date.substring(0, 8);\n   }\n\n   private static String buildCredentialScope(String dateWithoutTimeStamp) {\n      return dateWithoutTimeStamp + \"/\" + REGION + \"/\" + SERVICE + \"/\" + TERMINATION_STRING;\n   }\n\n   private static Multimap<String, String> buildCanonicalizedHeadersMap(HttpRequest request) {\n      Multimap<String, String> headers = request.getHeaders();\n      SortedSetMultimap<String, String> canonicalizedHeaders = TreeMultimap.create();\n      for (Entry<String, String> header : headers.entries()) {\n         if (header.getKey() == null)\n            continue;\n         String key = header.getKey().toString().toLowerCase(Locale.getDefault());\n         // Ignore any headers that are not particularly interesting.\n         if (key.equalsIgnoreCase(HttpHeaders.CONTENT_TYPE) || key.equalsIgnoreCase(HttpHeaders.CONTENT_MD5)\n               || key.equalsIgnoreCase(HttpHeaders.HOST) || key.startsWith(HEADER_TAG)) {\n            canonicalizedHeaders.put(key, header.getValue());\n         }\n      }\n      return canonicalizedHeaders;\n   }\n\n   private static String buildCanonicalizedHeadersString(Multimap<String, String> canonicalizedHeadersMap) {\n      StringBuilder canonicalizedHeadersBuffer = new StringBuilder();\n      for (Entry<String, String> header : canonicalizedHeadersMap.entries()) {\n         String key = header.getKey();\n         canonicalizedHeadersBuffer.append(key.toLowerCase()).append(':').append(header.getValue()).append('\\n');\n      }\n      return canonicalizedHeadersBuffer.toString();\n   }\n\n   private static String buildSignedHeaders(Multimap<String, String> canonicalizedHeadersMap) {\n      return Joiner.on(';').join(Iterables.transform(canonicalizedHeadersMap.keySet(), new Function<String, String>() {\n\n         @Override\n         public String apply(String input) {\n            return input.toLowerCase();\n         }\n      }));\n   }\n\n   private static HashCode buildHashedPayload(HttpRequest request) {\n      HashingInputStream his = null;\n      try {\n         his = new HashingInputStream(Hashing.sha256(),\n               request.getPayload() == null ? ByteSource.empty().openStream() : request.getPayload().openStream());\n         ByteStreams.copy(his, ByteStreams.nullOutputStream());\n         return his.hash();\n      } catch (IOException e) {\n         throw new HttpException(\"Error signing request\", e);\n      } finally {\n         closeQuietly(his);\n      }\n   }\n\n   private static String buildAuthHeader(String accessKey, String credentialScope, String signedHeaders,\n         String signature) {\n      return ALGORITHM + \" \" + \"Credential=\" + accessKey + \"/\" + credentialScope + \",\" + \"SignedHeaders=\"\n            + signedHeaders + \",\" + \"Signature=\" + signature;\n   }\n\n   private byte[] hmacSha256(byte[] key, String s) {\n      try {\n         Mac hmacSHA256 = crypto.hmacSHA256(key);\n         return hmacSHA256.doFinal(s.getBytes());\n      } catch (Exception e) {\n         throw new HttpException(\"Error signing request\", e);\n      }\n   }\n\n   private String buildSignature(String dateWithoutTimestamp, String stringToSign) {\n      byte[] kSecret = (AUTH_TAG + credential).getBytes(UTF_8);\n      byte[] kDate = hmacSha256(kSecret, dateWithoutTimestamp);\n      byte[] kRegion = hmacSha256(kDate, REGION);\n      byte[] kService = hmacSha256(kRegion, SERVICE);\n      byte[] kSigning = hmacSha256(kService, TERMINATION_STRING);\n      return BaseEncoding.base16().encode(hmacSha256(kSigning, stringToSign)).toLowerCase();\n   }\n\n   public HttpRequest sign(HttpRequest request) {\n      // Grab the needed data to build the signature\n      Multimap<String, String> canonicalizedHeadersMap = buildCanonicalizedHeadersMap(request);\n      String canonicalizedHeadersString = buildCanonicalizedHeadersString(canonicalizedHeadersMap);\n      String signedHeaders = buildSignedHeaders(canonicalizedHeadersMap);\n      String date = request.getFirstHeaderOrNull(GlacierHeaders.ALTERNATE_DATE);\n      String dateWithoutTimestamp = formatDateWithoutTimestamp(date);\n      String method = request.getMethod();\n      String endpoint = request.getEndpoint().getRawPath();\n      String credentialScope = buildCredentialScope(dateWithoutTimestamp);\n      HashCode hashedPayload = buildHashedPayload(request);\n\n      // Task 1: Create a Canonical Request For Signature Version 4.\n      HashCode hashedCanonicalRequest = buildHashedCanonicalRequest(method, endpoint, hashedPayload,\n            canonicalizedHeadersString, signedHeaders);\n\n      // Task 2: Create a String to Sign for Signature Version 4.\n      String stringToSign = createStringToSign(date, credentialScope, hashedCanonicalRequest);\n\n      // Task 3: Calculate the AWS Signature Version 4.\n      String signature = buildSignature(dateWithoutTimestamp, stringToSign);\n\n      // Sign the request\n      String authHeader = buildAuthHeader(identity, credentialScope, signedHeaders, signature);\n      request = request.toBuilder().replaceHeader(HttpHeaders.AUTHORIZATION, authHeader).build();\n      return request;\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/util/ContentRange.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.util;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Strings.isNullOrEmpty;\n\nimport com.google.common.base.Objects;\n\n/**\n * This class represents a range of bytes.\n */\npublic final class ContentRange {\n   private final long from;\n   private final long to;\n\n   private ContentRange(long from, long to) {\n      checkArgument(from < to, \"\\\"from\\\" should be lower than \\\"to\\\"\");\n      checkArgument(from >= 0 && to > 0, \"\\\"from\\\" cannot be negative and \\\"to\\\" has to be positive\");\n      this.from = from;\n      this.to = to;\n   }\n\n   public static ContentRange fromString(String contentRangeString) {\n      checkArgument(!isNullOrEmpty(contentRangeString) && contentRangeString.matches(\"[0-9]+-[0-9]+\"),\n            \"The string should be two numbers separated by a hyphen (from-to)\");\n      String[] strings = contentRangeString.split(\"-\", 2);\n      long from = Long.parseLong(strings[0]);\n      long to = Long.parseLong(strings[1]);\n      return new ContentRange(from, to);\n   }\n\n   public static ContentRange fromPartNumber(long partNumber, long partSizeInMB) {\n      checkArgument(partNumber >= 0, \"The part number cannot be negative\");\n      checkArgument(partSizeInMB > 0, \"The part size has to be positive\");\n      long from = partNumber * (partSizeInMB << 20);\n      long to = from + (partSizeInMB << 20) - 1;\n      return new ContentRange(from, to);\n   }\n\n   public static ContentRange build(long from, long to) {\n      return new ContentRange(from, to);\n   }\n\n   public long getFrom() {\n      return from;\n   }\n\n   public long getTo() {\n      return to;\n   }\n\n   public String buildHeader() {\n      return \"bytes \" + from + \"-\" + to + \"/*\";\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(this.from, this.to);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      ContentRange other = (ContentRange) obj;\n      return Objects.equal(this.from, other.from) && Objects.equal(this.to, other.to);\n   }\n\n   @Override\n   public String toString() {\n      return from + \"-\" + to;\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/main/java/org/jclouds/glacier/util/TreeHash.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.util;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.util.Closeables2.closeQuietly;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.Collection;\nimport java.util.Iterator;\nimport java.util.Map;\n\nimport org.jclouds.io.Payload;\n\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableList.Builder;\nimport com.google.common.collect.ImmutableSortedMap;\nimport com.google.common.hash.HashCode;\nimport com.google.common.hash.Hashing;\nimport com.google.common.hash.HashingInputStream;\nimport com.google.common.io.ByteStreams;\n\npublic final class TreeHash {\n   private static final int CHUNK_SIZE = 1024 * 1024;\n\n   private final HashCode treeHash;\n   private final HashCode linearHash;\n\n   private TreeHash(HashCode treeHash, HashCode linearHash) {\n      this.treeHash = checkNotNull(treeHash, \"treeHash\");\n      this.linearHash = checkNotNull(linearHash, \"linearHash\");\n   }\n\n   public HashCode getLinearHash() {\n      return linearHash;\n   }\n\n   public HashCode getTreeHash() {\n      return treeHash;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(this.treeHash, this.linearHash);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      TreeHash other = (TreeHash) obj;\n      return Objects.equal(this.treeHash, other.treeHash) && Objects.equal(this.linearHash, other.linearHash);\n   }\n\n   @Override\n   public String toString() {\n      return \"TreeHash [treeHash=\" + treeHash + \", linearHash=\" + linearHash + \"]\";\n   }\n\n   private static HashCode hashList(Collection<HashCode> hashList) {\n      Builder<HashCode> result = ImmutableList.builder();\n      while (hashList.size() > 1) {\n         //Hash pairs of values and add them to the result list.\n         for (Iterator<HashCode> it = hashList.iterator(); it.hasNext();) {\n            HashCode hc1 = it.next();\n            if (it.hasNext()) {\n                HashCode hc2 = it.next();\n                result.add(Hashing.sha256().newHasher()\n                      .putBytes(hc1.asBytes())\n                      .putBytes(hc2.asBytes())\n                      .hash());\n            } else {\n               result.add(hc1);\n            }\n         }\n         hashList = result.build();\n         result = ImmutableList.builder();\n      }\n      return hashList.iterator().next();\n   }\n\n   /**\n    * Builds the Hash and the TreeHash values of the payload.\n    *\n    * @return The calculated TreeHash.\n    * @see <a href=\"http://docs.aws.amazon.com/amazonglacier/latest/dev/checksum-calculations.html\" />\n    */\n   public static TreeHash buildTreeHashFromPayload(Payload payload) throws IOException {\n      InputStream is = null;\n      try {\n         is = checkNotNull(payload, \"payload\").openStream();\n         Builder<HashCode> list = ImmutableList.builder();\n         HashingInputStream linearHis = new HashingInputStream(Hashing.sha256(), is);\n         while (true) {\n             HashingInputStream chunkedHis = new HashingInputStream(\n                     Hashing.sha256(), ByteStreams.limit(linearHis, CHUNK_SIZE));\n             long count = ByteStreams.copy(chunkedHis, ByteStreams.nullOutputStream());\n             if (count == 0) {\n                 break;\n             }\n             list.add(chunkedHis.hash());\n         }\n         //The result list contains exactly one element now.\n         return new TreeHash(hashList(list.build()), linearHis.hash());\n      } finally {\n         closeQuietly(is);\n      }\n   }\n\n   /**\n    * Builds a TreeHash based on a map of hashed chunks.\n    *\n    * @return The calculated TreeHash.\n    * @see <a href=\"http://docs.aws.amazon.com/amazonglacier/latest/dev/checksum-calculations.html\" />\n    */\n   public static HashCode buildTreeHashFromMap(Map<Integer, HashCode> map) {\n      checkArgument(!map.isEmpty(), \"The map cannot be empty.\");\n      return hashList(ImmutableSortedMap.copyOf(map).values());\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/test/java/org/jclouds/glacier/GlacierApiMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier;\n\nimport org.jclouds.blobstore.internal.BaseBlobStoreApiMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"GlacierApiMetadataTest\")\npublic class GlacierApiMetadataTest extends BaseBlobStoreApiMetadataTest {\n\n   public GlacierApiMetadataTest() {\n      super(new GlacierApiMetadata());\n   }\n\n}\n"
  },
  {
    "path": "apis/glacier/src/test/java/org/jclouds/glacier/GlacierClientLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier;\n\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.jclouds.glacier.util.TestUtils.MiB;\nimport static org.jclouds.glacier.util.TestUtils.buildPayload;\n\nimport java.util.UUID;\n\nimport org.jclouds.apis.BaseApiLiveTest;\nimport org.jclouds.glacier.domain.PaginatedVaultCollection;\nimport org.jclouds.glacier.util.ContentRange;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.hash.HashCode;\n\n/**\n * Live test for Glacier.\n */\n@Test(groups = {\"live\", \"liveshort\"})\npublic class GlacierClientLiveTest extends BaseApiLiveTest<GlacierClient> {\n\n   private final String VAULT_NAME1 = UUID.randomUUID().toString();\n   private final String VAULT_NAME2 = UUID.randomUUID().toString();\n   private final String VAULT_NAME3 = UUID.randomUUID().toString();\n\n   public GlacierClientLiveTest() {\n      this.provider = \"glacier\";\n   }\n\n   @Test\n   public void testDeleteVaultIfEmptyOrNotFound() throws Exception {\n      assertThat(api.deleteVault(UUID.randomUUID().toString())).isTrue();\n   }\n\n   @Test\n   public void testDescribeNonExistentVault() throws Exception {\n      assertThat(api.describeVault(UUID.randomUUID().toString())).isNull();\n   }\n\n   @Test\n   public void testCreateVault() throws Exception {\n      assertThat(api.createVault(VAULT_NAME1).toString()).contains(\"/vaults/\" + VAULT_NAME1);\n      assertThat(api.createVault(VAULT_NAME2).toString()).contains(\"/vaults/\" + VAULT_NAME2);\n      assertThat(api.createVault(VAULT_NAME3).toString()).contains(\"/vaults/\" + VAULT_NAME3);\n   }\n\n   @Test(dependsOnMethods = {\"testCreateVault\"})\n   public void testListAndDescribeVaults() throws Exception {\n      PaginatedVaultCollection vaults = api.listVaults();\n      assertThat(vaults).containsAll(ImmutableList.of(\n            api.describeVault(VAULT_NAME1),\n            api.describeVault(VAULT_NAME2),\n            api.describeVault(VAULT_NAME3)));\n   }\n\n   @Test(dependsOnMethods = {\"testCreateVault\"})\n   public void testListMultipartUploadWithEmptyList() throws Exception {\n      assertThat(api.listMultipartUploads(VAULT_NAME1)).isEmpty();\n   }\n\n   @Test(dependsOnMethods = {\"testListMultipartUploadWithEmptyList\"})\n   public void testInitiateListAndAbortMultipartUpload() throws Exception {\n      long partSizeInMb = 1;\n      String uploadId = api.initiateMultipartUpload(VAULT_NAME1, partSizeInMb);\n      try {\n         assertThat(api.listMultipartUploads(VAULT_NAME1)).extracting(\"multipartUploadId\").contains(uploadId);\n\n         HashCode part1 = api.uploadPart(VAULT_NAME1, uploadId,\n               ContentRange.fromPartNumber(0, partSizeInMb), buildPayload(partSizeInMb * MiB));\n         HashCode part2 = api.uploadPart(VAULT_NAME1, uploadId,\n               ContentRange.fromPartNumber(1, partSizeInMb), buildPayload(partSizeInMb * MiB));\n         assertThat(part1).isNotNull();\n         assertThat(part2).isNotNull();\n         assertThat(api.listParts(VAULT_NAME1, uploadId).iterator()).toIterable().extracting(\"treeHash\").containsExactly(part1, part2);\n      } finally {\n         assertThat(api.abortMultipartUpload(VAULT_NAME1, uploadId)).isTrue();\n      }\n   }\n\n   @Test(dependsOnMethods = {\"testListAndDescribeVaults\", \"testListMultipartUploadWithEmptyList\",\n         \"testInitiateListAndAbortMultipartUpload\"})\n   public void testDeleteVaultAndArchive() throws Exception {\n      assertThat(api.deleteVault(VAULT_NAME1)).isTrue();\n      assertThat(api.deleteVault(VAULT_NAME2)).isTrue();\n      assertThat(api.deleteVault(VAULT_NAME3)).isTrue();\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/test/java/org/jclouds/glacier/GlacierClientLongLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier;\n\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.jclouds.glacier.blobstore.strategy.internal.BasePollingStrategy.DEFAULT_TIME_BETWEEN_POLLS;\nimport static org.jclouds.glacier.util.TestUtils.MiB;\nimport static org.jclouds.glacier.util.TestUtils.buildData;\nimport static org.jclouds.glacier.util.TestUtils.buildPayload;\n\nimport java.io.IOException;\nimport java.io.InputStream;\n\nimport org.jclouds.apis.BaseApiLiveTest;\nimport org.jclouds.glacier.blobstore.strategy.internal.BasePollingStrategy;\nimport org.jclouds.glacier.domain.ArchiveRetrievalJobRequest;\nimport org.jclouds.glacier.domain.InventoryRetrievalJobRequest;\nimport org.jclouds.glacier.domain.JobMetadata;\nimport org.jclouds.glacier.domain.JobStatus;\nimport org.jclouds.glacier.domain.VaultMetadata;\nimport org.jclouds.glacier.util.ContentRange;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.hash.HashCode;\nimport com.google.common.io.Closer;\n\n/**\n * Long live test for Glacier.\n */\npublic class GlacierClientLongLiveTest extends BaseApiLiveTest<GlacierClient>{\n\n   private static final long PART_SIZE = 1;\n   private static final String VAULT_NAME = \"JCLOUDS_LIVE_TESTS\";\n   private static final String ARCHIVE_DESCRIPTION = \"test archive\";\n\n   private String archiveId = null;\n   private String archiveRetrievalJob = null;\n   private String inventoryRetrievalJob = null;\n\n   public GlacierClientLongLiveTest() {\n      this.provider = \"glacier\";\n   }\n\n   @Test(groups = {\"live\", \"livelong\", \"setup\"})\n   public void testSetVault() throws Exception {\n      api.createVault(VAULT_NAME);\n      api.uploadArchive(VAULT_NAME, buildPayload(1 * MiB), ARCHIVE_DESCRIPTION);\n   }\n\n   @Test(groups = {\"live\", \"livelong\", \"longtest\"})\n   public void testUploadArchive() {\n      String archiveId = api.uploadArchive(VAULT_NAME, buildPayload(1 * MiB));\n      assertThat(api.deleteArchive(VAULT_NAME, archiveId)).isTrue();\n   }\n\n   @Test(groups = {\"live\", \"livelong\", \"longtest\"})\n   public void testCompleteMultipartUpload() {\n      String uploadId = api.initiateMultipartUpload(VAULT_NAME, PART_SIZE);\n      ImmutableMap.Builder<Integer, HashCode> hashes = ImmutableMap.builder();\n      hashes.put(0, api.uploadPart(VAULT_NAME, uploadId, ContentRange.fromPartNumber(0, PART_SIZE),\n            buildPayload(PART_SIZE * MiB)));\n      hashes.put(1, api.uploadPart(VAULT_NAME, uploadId, ContentRange.fromPartNumber(1, PART_SIZE),\n            buildPayload(PART_SIZE * MiB)));\n      archiveId = api.completeMultipartUpload(VAULT_NAME, uploadId, hashes.build(), PART_SIZE * 2 * MiB);\n      assertThat(archiveId).isNotNull();\n   }\n\n   @Test(groups = {\"live\", \"livelong\", \"longtest\"}, dependsOnMethods = {\"testUploadArchive\", \"testCompleteMultipartUpload\"})\n   public void testInitiateJob() {\n      ArchiveRetrievalJobRequest archiveRetrieval = ArchiveRetrievalJobRequest.builder().archiveId(archiveId).build();\n      InventoryRetrievalJobRequest inventoryRetrieval = InventoryRetrievalJobRequest.builder().build();\n      archiveRetrievalJob = api.initiateJob(VAULT_NAME, archiveRetrieval);\n      inventoryRetrievalJob = api.initiateJob(VAULT_NAME, inventoryRetrieval);\n      assertThat(archiveRetrievalJob).isNotNull();\n      assertThat(inventoryRetrievalJob).isNotNull();\n   }\n\n   @Test(groups = {\"live\", \"livelong\", \"longtest\"}, dependsOnMethods = {\"testInitiateJob\"})\n   public void testDescribeJob() {\n      VaultMetadata vaultMetadata = api.describeVault(VAULT_NAME);\n\n      JobMetadata archiveRetrievalMetadata = api.describeJob(VAULT_NAME, archiveRetrievalJob);\n      assertThat(archiveRetrievalMetadata.getArchiveId()).isEqualTo(archiveId);\n      assertThat(archiveRetrievalMetadata.getJobId()).isEqualTo(archiveRetrievalJob);\n      assertThat(archiveRetrievalMetadata.getVaultArn()).isEqualTo(vaultMetadata.getVaultARN());\n\n      JobMetadata inventoryRetrievalMetadata = api.describeJob(VAULT_NAME, inventoryRetrievalJob);\n      assertThat(inventoryRetrievalMetadata.getJobId()).isEqualTo(inventoryRetrievalJob);\n      assertThat(inventoryRetrievalMetadata.getVaultArn()).isEqualTo(vaultMetadata.getVaultARN());\n   }\n\n   @Test(groups = {\"live\", \"livelong\", \"longtest\"}, dependsOnMethods = {\"testInitiateJob\"})\n   public void testListJobs() {\n         assertThat(api.listJobs(VAULT_NAME)).extracting(\"jobId\").contains(inventoryRetrievalJob, archiveRetrievalJob);\n   }\n\n   @Test(groups = {\"live\", \"livelong\", \"longtest\"}, dependsOnMethods = {\"testInitiateJob\", \"testDescribeJob\", \"testListJobs\"})\n   public void testWaitForSucceed() throws InterruptedException {\n      new BasePollingStrategy(api).waitForSuccess(VAULT_NAME, archiveRetrievalJob);\n      new BasePollingStrategy(api, 0, DEFAULT_TIME_BETWEEN_POLLS).waitForSuccess(VAULT_NAME,\n            inventoryRetrievalJob);\n      assertThat(api.describeJob(VAULT_NAME, archiveRetrievalJob).getStatusCode()).isEqualTo(JobStatus.SUCCEEDED);\n      assertThat(api.describeJob(VAULT_NAME, inventoryRetrievalJob).getStatusCode()).isEqualTo(JobStatus.SUCCEEDED);\n   }\n\n   @Test(groups = {\"live\", \"livelong\", \"longtest\"}, dependsOnMethods = {\"testWaitForSucceed\"})\n   public void testGetJobOutput() throws IOException {\n      Closer closer = Closer.create();\n      try {\n         InputStream inputStream = closer.register(api.getJobOutput(VAULT_NAME, archiveRetrievalJob).openStream());\n         InputStream expectedInputStream = closer.register(buildData(PART_SIZE * 2 * MiB).openStream());\n         assertThat(inputStream).hasContentEqualTo(expectedInputStream);\n      } finally {\n         closer.close();\n      }\n   }\n\n   @Test(groups = {\"live\", \"livelong\", \"longtest\"}, dependsOnMethods = {\"testWaitForSucceed\"})\n   public void testGetInventoryRetrievalOutput() throws InterruptedException {\n      assertThat(api.getInventoryRetrievalOutput(VAULT_NAME, inventoryRetrievalJob))\n            .extracting(\"description\").contains(ARCHIVE_DESCRIPTION);\n   }\n\n   @Test(groups = {\"live\", \"livelong\", \"longtest\"}, dependsOnMethods = {\"testGetJobOutput\"})\n   public void testDeleteArchive() throws Exception {\n      assertThat(api.deleteArchive(VAULT_NAME, archiveId)).isTrue();\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/test/java/org/jclouds/glacier/GlacierClientMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.util.concurrent.MoreExecutors.newDirectExecutorService;\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.jclouds.Constants.PROPERTY_MAX_RETRIES;\nimport static org.jclouds.Constants.PROPERTY_SO_TIMEOUT;\nimport static org.jclouds.glacier.util.TestUtils.MiB;\nimport static org.jclouds.glacier.util.TestUtils.buildPayload;\nimport static org.jclouds.util.Strings2.urlEncode;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.net.URI;\nimport java.net.URL;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.concurrent.config.ExecutorServiceModule;\nimport org.jclouds.glacier.domain.ArchiveMetadataCollection;\nimport org.jclouds.glacier.domain.ArchiveRetrievalJobRequest;\nimport org.jclouds.glacier.domain.InventoryRetrievalJobRequest;\nimport org.jclouds.glacier.domain.JobMetadata;\nimport org.jclouds.glacier.domain.MultipartUploadMetadata;\nimport org.jclouds.glacier.domain.PaginatedMultipartUploadCollection;\nimport org.jclouds.glacier.domain.PaginatedVaultCollection;\nimport org.jclouds.glacier.domain.VaultMetadata;\nimport org.jclouds.glacier.options.PaginationOptions;\nimport org.jclouds.glacier.reference.GlacierHeaders;\nimport org.jclouds.glacier.util.ContentRange;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.io.Payload;\nimport org.jclouds.json.Json;\nimport org.jclouds.json.internal.GsonWrapper;\nimport org.testng.Assert;\nimport org.testng.annotations.AfterMethod;\nimport org.testng.annotations.BeforeMethod;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.hash.HashCode;\nimport com.google.common.io.Resources;\nimport com.google.common.net.HttpHeaders;\nimport com.google.common.net.MediaType;\nimport com.google.gson.Gson;\nimport com.google.inject.Module;\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\nimport okhttp3.mockwebserver.RecordedRequest;\n\n/**\n * Mock test for Glacier.\n */\n@Test(singleThreaded = true, groups = {\"mock\"}, testName = \"GlacierClientMockTest\")\npublic class GlacierClientMockTest {\n\n   private static final String REQUEST_ID = \"AAABZpJrTyioDC_HsOmHae8EZp_uBSJr6cnGOLKp_XJCl-Q\";\n   private static final String DATE = \"Sun, 25 Mar 2012 12:00:00 GMT\";\n   private static final String HTTP = \"HTTP/1.1\";\n   private static final String VAULT_NAME = \"examplevault\";\n   private static final String VAULT_NAME1 = \"examplevault1\";\n   private static final String VAULT_NAME2 = \"examplevault2\";\n   private static final String VAULT_NAME3 = \"examplevault3\";\n   private static final String LOCATION = \"/111122223333/\";\n   private static final String VAULT_LOCATION = LOCATION + \"vaults/\" + VAULT_NAME;\n   private static final String VAULT_ARN_PREFIX = \"arn:aws:glacier:us-east-1:012345678901:vaults/\";\n   private static final String VAULT_ARN = VAULT_ARN_PREFIX + VAULT_NAME;\n   private static final String VAULT_ARN1 = VAULT_ARN_PREFIX + VAULT_NAME1;\n   private static final String VAULT_ARN3 = VAULT_ARN_PREFIX + VAULT_NAME3;\n   private static final String ARCHIVE_ID = \"NkbByEejwEggmBz2fTHgJrg0XBoDfjP4q6iu87-TjhqG6eGoOY9Z8i1_AUyUsuhPAdTqLHy8pTl5nfCFJmDl2yEZONi5L26Omw12vcs01MNGntHEQL8MBfGlqrEXAMPLEArchiveId\";\n   private static final String ARCHIVE_LOCATION = VAULT_LOCATION + \"/archives/\" + ARCHIVE_ID;\n   private static final HashCode TREEHASH = HashCode.fromString(\"beb0fe31a1c7ca8c6c04d574ea906e3f97b31fdca7571defb5b44dca89b5af60\");\n   private static final String DESCRIPTION = \"test description\";\n   private static final String MULTIPART_UPLOAD_LOCATION = VAULT_LOCATION + \"/multipart-uploads/\" + ARCHIVE_ID;\n   private static final String MULTIPART_UPLOAD_ID = \"OW2fM5iVylEpFEMM9_HpKowRapC3vn5sSL39_396UW9zLFUWVrnRHaPjUJddQ5OxSHVXjYtrN47NBZ-khxOjyEXAMPLE\";\n   private static final String MARKER = \"xsQdFIRsfJr20CW2AbZBKpRZAFTZSJIMtL2hYf8mvp8dM0m4RUzlaqoEye6g3h3ecqB_zqwB7zLDMeSWhwo65re4C4Ev\";\n   private static final String JOB_ID = \"HkF9p6o7yjhFx-K3CGl6fuSm6VzW9T7esGQfco8nUXVYwS0jlb5gq1JZ55yHgt5vP54ZShjoQzQVVh7vEXAMPLEjobID\";\n   private static final Set<Module> modules = ImmutableSet.<Module> of(new ExecutorServiceModule(newDirectExecutorService(),\n         newDirectExecutorService()));\n\n   private MockWebServer server;\n   private GlacierClient client;\n\n   private static GlacierClient getGlacierClient(URL server) {\n      Properties overrides = new Properties();\n      // prevent expect-100 bug http://code.google.com/p/mockwebserver/issues/detail?id=6\n      overrides.setProperty(PROPERTY_SO_TIMEOUT, \"0\");\n      overrides.setProperty(PROPERTY_MAX_RETRIES, \"1\");\n      return ContextBuilder.newBuilder(\"glacier\").credentials(\"accessKey\", \"secretKey\").endpoint(server.toString())\n            .modules(modules).overrides(overrides).buildApi(GlacierClient.class);\n   }\n\n   private static MockResponse buildBaseResponse(int responseCode) {\n      MockResponse mr = new MockResponse();\n      mr.setResponseCode(responseCode);\n      mr.addHeader(GlacierHeaders.REQUEST_ID, REQUEST_ID);\n      mr.addHeader(HttpHeaders.DATE, DATE);\n      return mr;\n   }\n\n   private static String getResponseBody(String path) throws IOException {\n      return Resources.toString(Resources.getResource(GlacierClientMockTest.class, path), UTF_8);\n   }\n\n   @BeforeMethod\n   private void initServer() throws IOException {\n      server = new MockWebServer();\n      server.start();\n      client = getGlacierClient(server.url(\"/\").url());\n   }\n\n   @AfterMethod\n   private void shutdownServer() {\n      try {\n         server.shutdown();\n      } catch (IOException e) {\n         // MockWebServer 2.1.0 introduces an active wait for its executor\n         // termination. That active wait is a hardcoded value and throws an IOE\n         // if the executor has not terminated in that timeout. It is safe to\n         // ignore this exception as the functionality has been properly\n         // verified.\n      }\n   }\n\n   @Test\n   public void testCreateVault() throws InterruptedException {\n      MockResponse mr = buildBaseResponse(201);\n      mr.addHeader(HttpHeaders.LOCATION, VAULT_LOCATION);\n      server.enqueue(mr);\n\n      assertThat(client.createVault(VAULT_NAME)).isEqualTo(URI.create(server.url(\"/\") + VAULT_LOCATION.substring(1)));\n\n      assertEquals(server.takeRequest().getRequestLine(), \"PUT /-/vaults/\" + VAULT_NAME + \" \" + HTTP);\n   }\n\n   @Test\n   public void testDeleteVault() throws InterruptedException {\n      server.enqueue(buildBaseResponse(204));\n\n      assertThat(client.deleteVault(VAULT_NAME)).isTrue();\n\n      assertEquals(server.takeRequest().getRequestLine(), \"DELETE /-/vaults/\" + VAULT_NAME + \" \" + HTTP);\n   }\n\n   @Test\n   public void testDescribeVault() throws InterruptedException, IOException {\n      MockResponse mr = buildBaseResponse(200);\n      mr.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8);\n      mr.setBody(getResponseBody(\"/json/describeVaultResponseBody.json\"));\n      mr.addHeader(HttpHeaders.CONTENT_LENGTH, mr.getBody().size());\n      server.enqueue(mr);\n\n      VaultMetadata vault = client.describeVault(VAULT_NAME);\n      assertThat(vault.getVaultName()).isEqualTo(VAULT_NAME);\n      assertThat(vault.getVaultARN()).isEqualTo(VAULT_ARN);\n      assertThat(vault.getSizeInBytes()).isEqualTo(78088912);\n      assertThat(vault.getNumberOfArchives()).isEqualTo(192);\n\n      assertEquals(server.takeRequest().getRequestLine(), \"GET /-/vaults/\" + VAULT_NAME + \" \" + HTTP);\n   }\n\n   @Test\n   public void testListVaults() throws InterruptedException, IOException {\n      MockResponse mr = buildBaseResponse(200);\n      mr.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8);\n      mr.setBody(getResponseBody(\"/json/listVaultsResponseBody.json\"));\n      mr.addHeader(HttpHeaders.CONTENT_LENGTH, mr.getBody().size());\n      server.enqueue(mr);\n\n      assertThat(client.listVaults()).extracting(\"vaultName\").containsExactly(VAULT_NAME1, VAULT_NAME2, VAULT_NAME3);\n\n      assertEquals(server.takeRequest().getRequestLine(), \"GET /-/vaults \" + HTTP);\n   }\n\n   @Test\n   public void testListVaultsWithEmptyList() throws InterruptedException, IOException {\n      MockResponse mr = buildBaseResponse(200);\n      mr.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8);\n      mr.setBody(getResponseBody(\"/json/listVaultsWithEmptyListResponseBody.json\"));\n      mr.addHeader(HttpHeaders.CONTENT_LENGTH, mr.getBody().size());\n      server.enqueue(mr);\n\n      assertThat(client.listVaults()).isEmpty();\n   }\n\n   @Test\n   public void testListVaultsWithQueryParams() throws InterruptedException, IOException {\n      MockResponse mr = buildBaseResponse(200);\n      mr.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8);\n      mr.setBody(getResponseBody(\"/json/listVaultsWithQueryParamsResponseBody.json\"));\n      mr.addHeader(HttpHeaders.CONTENT_LENGTH, mr.getBody().size());\n      server.enqueue(mr);\n\n      PaginatedVaultCollection vaults = client.listVaults(PaginationOptions.Builder.limit(2).marker(VAULT_ARN1));\n      assertThat(vaults).extracting(\"vaultName\").containsExactly(VAULT_NAME1, VAULT_NAME2);\n      assertThat(vaults.nextMarker().get()).isEqualTo(VAULT_ARN3);\n\n      assertEquals(server.takeRequest().getRequestLine(),\n              \"GET /-/vaults?limit=2&marker=\" + urlEncode(VAULT_ARN1, '/') + \" \" + HTTP);\n   }\n\n   @Test\n   public void testUploadArchive() throws InterruptedException {\n      MockResponse mr = buildBaseResponse(201);\n      mr.addHeader(GlacierHeaders.TREE_HASH, TREEHASH);\n      mr.addHeader(HttpHeaders.LOCATION, ARCHIVE_LOCATION);\n      mr.addHeader(GlacierHeaders.ARCHIVE_ID, ARCHIVE_ID);\n      server.enqueue(mr);\n\n      assertThat(client.uploadArchive(VAULT_NAME, buildPayload(10), DESCRIPTION)).isEqualTo(ARCHIVE_ID);\n\n      RecordedRequest request = server.takeRequest();\n      assertEquals(request.getRequestLine(), \"POST /-/vaults/\" + VAULT_NAME + \"/archives \" + HTTP);\n      assertEquals(request.getHeader(GlacierHeaders.ARCHIVE_DESCRIPTION), DESCRIPTION);\n      assertNotNull(request.getHeader(GlacierHeaders.TREE_HASH));\n      assertNotNull(request.getHeader(GlacierHeaders.LINEAR_HASH));\n   }\n\n   @Test\n   public void testDeleteArchive() throws InterruptedException {\n      MockResponse mr = buildBaseResponse(204);\n      server.enqueue(mr);\n\n      assertThat(client.deleteArchive(VAULT_NAME, ARCHIVE_ID)).isTrue();\n\n      assertEquals(server.takeRequest().getRequestLine(), \"DELETE /-/vaults/\" + VAULT_NAME + \"/archives/\" + ARCHIVE_ID + \" \" + HTTP);\n   }\n\n   @Test\n   public void testInitiateMultipartUpload() throws InterruptedException {\n      MockResponse mr = buildBaseResponse(201);\n      mr.addHeader(HttpHeaders.LOCATION, MULTIPART_UPLOAD_LOCATION);\n      mr.addHeader(GlacierHeaders.MULTIPART_UPLOAD_ID, MULTIPART_UPLOAD_ID);\n      server.enqueue(mr);\n\n      assertThat(client.initiateMultipartUpload(VAULT_NAME, 4, DESCRIPTION)).isEqualTo(MULTIPART_UPLOAD_ID);\n\n      RecordedRequest request = server.takeRequest();\n      assertEquals(request.getRequestLine(), \"POST /-/vaults/\" + VAULT_NAME + \"/multipart-uploads \" + HTTP);\n      assertEquals(request.getHeader(GlacierHeaders.PART_SIZE), \"4194304\");\n      assertEquals(request.getHeader(GlacierHeaders.ARCHIVE_DESCRIPTION), DESCRIPTION);\n   }\n\n   @Test\n   public void testUploadPart() throws InterruptedException {\n      MockResponse mr = buildBaseResponse(204);\n      mr.addHeader(GlacierHeaders.TREE_HASH, TREEHASH);\n      server.enqueue(mr);\n\n      assertThat(client.uploadPart(VAULT_NAME, MULTIPART_UPLOAD_ID, ContentRange.fromPartNumber(0, 4),\n              buildPayload(4 * MiB))).isEqualTo(TREEHASH);\n\n      RecordedRequest request = server.takeRequest();\n      assertEquals(request.getRequestLine(),\n            \"PUT /-/vaults/\" + VAULT_NAME + \"/multipart-uploads/\" + MULTIPART_UPLOAD_ID + \" \" + HTTP);\n      assertEquals(request.getHeader(HttpHeaders.CONTENT_RANGE), \"bytes 0-4194303/*\");\n      assertEquals(request.getHeader(HttpHeaders.CONTENT_LENGTH), \"4194304\");\n   }\n\n   // TODO: Change size to 4096 when moving to JDK 7\n   @Test\n   public void testUploadPartMaxSize() throws InterruptedException {\n      // force the server to discard the request body\n      server.setBodyLimit(0);\n      MockResponse mr = buildBaseResponse(204);\n      mr.addHeader(GlacierHeaders.TREE_HASH, TREEHASH);\n      server.enqueue(mr);\n\n      long size = 1024;\n      ContentRange range = ContentRange.fromPartNumber(0, size);\n      Payload payload = buildPayload(1);\n      payload.getContentMetadata().setContentLength(size * MiB);\n      try {\n         /* The client.uploadPart call should throw an HttpResponseException since the payload is smaller than expected.\n          * This trick makes the test way faster.\n          */\n         client.uploadPart(VAULT_NAME, MULTIPART_UPLOAD_ID, range, payload);\n         Assert.fail();\n      } catch (HttpResponseException e) {\n      }\n\n      RecordedRequest request = server.takeRequest();\n      assertEquals(request.getRequestLine(), \"PUT /-/vaults/\" + VAULT_NAME + \"/multipart-uploads/\" + MULTIPART_UPLOAD_ID + \" \" + HTTP);\n      assertEquals(request.getHeader(HttpHeaders.CONTENT_RANGE), range.buildHeader());\n      assertEquals(request.getHeader(HttpHeaders.CONTENT_LENGTH), payload.getContentMetadata().getContentLength().toString());\n   }\n\n   @Test\n   public void testCompleteMultipartUpload() throws IOException, InterruptedException {\n      MockResponse mr = buildBaseResponse(201);\n      mr.addHeader(HttpHeaders.LOCATION, ARCHIVE_LOCATION);\n      mr.addHeader(GlacierHeaders.ARCHIVE_ID, ARCHIVE_ID);\n      server.enqueue(mr);\n\n      HashCode partHashcode = HashCode.fromString(\"9bc1b2a288b26af7257a36277ae3816a7d4f16e89c1e7e77d0a5c48bad62b360\");\n      ImmutableMap<Integer, HashCode> map = ImmutableMap.of(\n            1, partHashcode,\n            2, partHashcode,\n            3, partHashcode,\n            4, partHashcode);\n      assertThat(client.completeMultipartUpload(VAULT_NAME, MULTIPART_UPLOAD_ID, map, 8 * MiB)).isEqualTo(ARCHIVE_ID);\n\n      RecordedRequest request = server.takeRequest();\n      assertEquals(request.getRequestLine(),\n            \"POST /-/vaults/\" + VAULT_NAME + \"/multipart-uploads/\" + MULTIPART_UPLOAD_ID + \" \" + HTTP);\n      assertEquals(request.getHeader(GlacierHeaders.TREE_HASH),\n            \"9491cb2ed1d4e7cd53215f4017c23ec4ad21d7050a1e6bb636c4f67e8cddb844\");\n      assertEquals(request.getHeader(GlacierHeaders.ARCHIVE_SIZE), \"8388608\");\n   }\n\n   @Test\n   public void testAbortMultipartUpload() throws IOException, InterruptedException {\n      MockResponse mr = buildBaseResponse(204);\n      server.enqueue(mr);\n\n      assertTrue(client.abortMultipartUpload(VAULT_NAME, MULTIPART_UPLOAD_ID));\n\n      assertEquals(server.takeRequest().getRequestLine(),\n              \"DELETE /-/vaults/\" + VAULT_NAME + \"/multipart-uploads/\" + MULTIPART_UPLOAD_ID + \" \" + HTTP);\n   }\n\n   @Test\n   public void testListParts() throws IOException, InterruptedException {\n      MockResponse mr = buildBaseResponse(200);\n      mr.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8);\n      mr.setBody(getResponseBody(\"/json/listPartsResponseBody.json\"));\n      mr.addHeader(HttpHeaders.CONTENT_LENGTH, mr.getBody().size());\n      server.enqueue(mr);\n\n      MultipartUploadMetadata mpu = client.listParts(VAULT_NAME, MULTIPART_UPLOAD_ID, PaginationOptions.Builder.limit(1).marker(\"1001\"));\n      assertThat(mpu.getArchiveDescription()).isEqualTo(\"archive description 1\");\n      assertThat(mpu.getMultipartUploadId()).isEqualTo(MULTIPART_UPLOAD_ID);\n      assertThat(mpu.getPartSizeInBytes()).isEqualTo(4194304);\n      assertThat(mpu.iterator()).toIterable().extracting(\"treeHash\").containsExactly(HashCode.fromString(\"01d34dabf7be316472c93b1ef80721f5d4\"));\n      assertThat(mpu.iterator()).toIterable().extracting(\"range\").containsExactly(ContentRange.fromString(\"4194304-8388607\"));\n\n      assertEquals(server.takeRequest().getRequestLine(),\n              \"GET /-/vaults/examplevault/multipart-uploads/\" + MULTIPART_UPLOAD_ID + \"?limit=1&marker=1001 \" + HTTP);\n   }\n\n   @Test\n   public void testListMultipartUploads() throws IOException, InterruptedException {\n      MockResponse mr = buildBaseResponse(200);\n      mr.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8);\n      mr.setBody(getResponseBody(\"/json/listMultipartUploadsResponseBody.json\"));\n      mr.addHeader(HttpHeaders.CONTENT_LENGTH, mr.getBody().size());\n      server.enqueue(mr);\n\n      PaginatedMultipartUploadCollection mpus = client.listMultipartUploads(VAULT_NAME, PaginationOptions.Builder.limit(1).marker(MARKER));\n      assertThat(mpus).extracting(\"archiveDescription\").containsExactly(\"archive 2\");\n      assertThat(mpus).extracting(\"multipartUploadId\").containsExactly(\"nPyGOnyFcx67qqX7E-0tSGiRi88hHMOwOxR-_jNyM6RjVMFfV29lFqZ3rNsSaWBugg6OP92pRtufeHdQH7ClIpSF6uJc\");\n      assertThat(mpus).extracting(\"partSizeInBytes\").containsExactly(4194304L);\n      assertThat(mpus).extracting(\"vaultARN\").containsExactly(VAULT_ARN);\n\n      assertEquals(server.takeRequest().getRequestLine(),\n              \"GET /-/vaults/examplevault/multipart-uploads?limit=1&marker=\" + MARKER + \" \" + HTTP);\n   }\n\n   @Test\n   public void testListMultipartUploadsWithEmptyList() throws IOException, InterruptedException {\n      MockResponse mr = buildBaseResponse(200);\n      mr.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8);\n      mr.setBody(getResponseBody(\"/json/listMultipartUploadsWithEmptyListResponseBody.json\"));\n      mr.addHeader(HttpHeaders.CONTENT_LENGTH, mr.getBody().size());\n      server.enqueue(mr);\n\n      assertThat(client.listMultipartUploads(VAULT_NAME, PaginationOptions.Builder.limit(1).marker(MARKER))).isEmpty();\n\n      assertEquals(server.takeRequest().getRequestLine(),\n              \"GET /-/vaults/examplevault/multipart-uploads?limit=1&marker=\" + MARKER + \" \" + HTTP);\n   }\n\n   @Test\n   public void testInitiateArchiveRetrievalJob() throws IOException, InterruptedException {\n      MockResponse mr = buildBaseResponse(202);\n      mr.addHeader(HttpHeaders.LOCATION, VAULT_LOCATION + \"/jobs/\" + JOB_ID);\n      mr.addHeader(GlacierHeaders.JOB_ID, JOB_ID);\n      server.enqueue(mr);\n\n      ContentRange range = ContentRange.fromString(\"2097152-4194303\");\n      ArchiveRetrievalJobRequest retrieval = ArchiveRetrievalJobRequest.builder()\n            .archiveId(ARCHIVE_ID)\n            .description(DESCRIPTION)\n            .range(range)\n            .build();\n      assertThat(client.initiateJob(VAULT_NAME, retrieval)).isEqualTo(JOB_ID);\n\n      RecordedRequest request = server.takeRequest();\n      Json json = new GsonWrapper(new Gson());\n      ArchiveRetrievalJobRequest job = json.fromJson(request.getBody().readUtf8(), ArchiveRetrievalJobRequest.class);\n      assertThat(job.getDescription()).isEqualTo(DESCRIPTION);\n      assertThat(job.getRange()).isEqualTo(range);\n      assertThat(job.getArchiveId()).isEqualTo(ARCHIVE_ID);\n      assertThat(job.getType()).isEqualTo(\"archive-retrieval\");\n\n      assertEquals(request.getRequestLine(), \"POST /-/vaults/\" + VAULT_NAME + \"/jobs \" + HTTP);\n   }\n\n   @Test\n   public void testInitiateInventoryRetrievalJob() throws IOException, InterruptedException {\n      MockResponse mr = buildBaseResponse(202);\n      mr.addHeader(HttpHeaders.LOCATION, VAULT_LOCATION + \"/jobs/\" + JOB_ID);\n      mr.addHeader(GlacierHeaders.JOB_ID, JOB_ID);\n      server.enqueue(mr);\n\n      String marker = \"vyS0t2jHQe5qbcDggIeD50chS1SXwYMrkVKo0KHiTUjEYxBGCqRLKaiySzdN7QXGVVV5XZpNVG67pCZ_uykQXFMLaxOSu2hO_-5C0AtWMDrfo7LgVOyfnveDRuOSecUo3Ueq7K0\";\n      int limit = 10000;\n      String startDate = \"2013-12-04T21:25:42Z\";\n      String endDate = \"2013-12-05T21:25:42Z\";\n      String format = \"CSV\";\n      InventoryRetrievalJobRequest job = InventoryRetrievalJobRequest.builder()\n            .format(format)\n            .endDate(endDate)\n            .startDate(startDate)\n            .limit(limit)\n            .marker(marker)\n            .build();\n      assertThat(client.initiateJob(VAULT_NAME, job)).isEqualTo(JOB_ID);\n\n      RecordedRequest request = server.takeRequest();\n      Json json = new GsonWrapper(new Gson());\n      job = json.fromJson(request.getBody().readUtf8(), InventoryRetrievalJobRequest.class);\n      assertThat(job.getFormat()).isEqualTo(format);\n      assertThat(job.getParameters().getMarker()).isEqualTo(marker);\n      assertThat(job.getParameters().getLimit()).isEqualTo(limit);\n      assertThat(job.getParameters().getStartDate()).isEqualTo(startDate);\n      assertThat(job.getParameters().getEndDate()).isEqualTo(endDate);\n      assertThat(job.getType()).isEqualTo(\"inventory-retrieval\");\n\n      assertEquals(request.getRequestLine(), \"POST /-/vaults/examplevault/jobs HTTP/1.1\");\n   }\n\n   @Test\n   public void testDescribeJob() throws IOException, InterruptedException {\n      MockResponse mr = buildBaseResponse(200);\n      mr.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8);\n      mr.setBody(getResponseBody(\"/json/describeJobResponseBody.json\"));\n      mr.addHeader(HttpHeaders.CONTENT_LENGTH, mr.getBody().size());\n      server.enqueue(mr);\n\n      JobMetadata job = client.describeJob(VAULT_NAME, JOB_ID);\n      assertThat(job.getAction()).isEqualTo(\"ArchiveRetrieval\");\n      assertThat(job.getArchiveId()).isEqualTo(ARCHIVE_ID);\n      assertThat(ContentRange.fromString(\"0-16777215\")).isEqualTo(job.getRetrievalByteRange());\n      assertThat(job.getVaultArn()).isEqualTo(\"arn:aws:glacier:us-east-1:012345678901:vaults/examplevault\");\n\n      assertEquals(server.takeRequest().getRequestLine(), \"GET /-/vaults/\" + VAULT_NAME + \"/jobs/\" + JOB_ID + \" \" + HTTP);\n   }\n\n   @Test\n   public void testListJobs() throws IOException, InterruptedException {\n      MockResponse mr = buildBaseResponse(200);\n      mr.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8);\n      mr.setBody(getResponseBody(\"/json/listJobsResponseBody.json\"));\n      mr.addHeader(HttpHeaders.CONTENT_LENGTH, mr.getBody().size());\n      server.enqueue(mr);\n\n      assertThat(client.listJobs(VAULT_NAME)).extracting(\"jobId\").containsExactly(\n               \"s4MvaNHIh6mOa1f8iY4ioG2921SDPihXxh3Kv0FBX-JbNPctpRvE4c2_BifuhdGLqEhGBNGeB6Ub-JMunR9JoVa8y1hQ\",\n               \"CQ_tf6fOR4jrJCL61Mfk6VM03oY8lmnWK93KK4gLig1UPAbZiN3UV4G_5nq4AfmJHQ_dOMLOX5k8ItFv0wCPN0oaz5dG\");\n\n      assertEquals(server.takeRequest().getRequestLine(), \"GET /-/vaults/examplevault/jobs HTTP/1.1\");\n   }\n\n   @Test\n   public void testGetJobOutput() throws IOException, InterruptedException {\n      MockResponse mr = buildBaseResponse(200);\n      mr.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8);\n      mr.setBody(getResponseBody(\"/json/getJobOutputResponseBody.json\"));\n      mr.addHeader(HttpHeaders.CONTENT_LENGTH, mr.getBody().size());\n      server.enqueue(mr);\n\n      Payload payload = client.getJobOutput(VAULT_NAME, JOB_ID);\n      assertThat(payload.getContentMetadata().getContentType()).isEqualTo(MediaType.JSON_UTF_8.toString());\n      assertThat(payload.getContentMetadata().getContentLength()).isEqualTo(mr.getBody().size());\n      assertThat(payload.openStream())\n              .hasContentEqualTo(Resources.getResource(GlacierClientMockTest.class,\n                      \"/json/getJobOutputResponseBody.json\").openStream());\n\n      assertEquals(server.takeRequest().getRequestLine(),\n              \"GET /-/vaults/\" + VAULT_NAME + \"/jobs/\" + JOB_ID + \"/output \" + HTTP);\n   }\n\n   @Test\n   public void testGetJobOutputWithContentRange() throws IOException, InterruptedException {\n      MockResponse mr = buildBaseResponse(206);\n      mr.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8);\n      mr.setBody(getResponseBody(\"/json/getJobOutputResponseBody.json\"));\n      mr.addHeader(HttpHeaders.CONTENT_LENGTH, mr.getBody().size());\n      server.enqueue(mr);\n\n      ContentRange range = ContentRange.fromString(\"16-32\");\n      client.getJobOutput(VAULT_NAME, JOB_ID, range);\n\n      RecordedRequest request = server.takeRequest();\n      assertEquals(request.getHeader(\"Range\"), \"bytes=\" + range.toString());\n      assertEquals(request.getRequestLine(),\n              \"GET /-/vaults/\" + VAULT_NAME + \"/jobs/\" + JOB_ID + \"/output \" + HTTP);\n   }\n\n   @Test\n   public void testGetInventoryRetrievalOutput() throws IOException, InterruptedException {\n      MockResponse mr = buildBaseResponse(200);\n      mr.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8);\n      mr.setBody(getResponseBody(\"/json/getJobOutputResponseBody.json\"));\n      mr.addHeader(HttpHeaders.CONTENT_LENGTH, mr.getBody().size());\n      server.enqueue(mr);\n\n      ArchiveMetadataCollection archives = client.getInventoryRetrievalOutput(VAULT_NAME, JOB_ID);\n      assertThat(archives.getVaultARN()).isEqualTo(\"arn:aws:glacier:us-east-1:012345678901:vaults/examplevault\");\n      assertThat(archives).extracting(\"archiveId\").containsExactly(\n              \"DMTmICA2n5Tdqq5BV2z7og-A20xnpAPKt3UXwWxdWsn_D6auTUrW6kwy5Qyj9xd1MCE1mBYvMQ63LWaT8yTMzMaCxB_9VBWrW4Jw4zsvg5kehAPDVKcppUD1X7b24JukOr4mMAq-oA\",\n              \"2lHzwhKhgF2JHyvCS-ZRuF08IQLuyB4265Hs3AXj9MoAIhz7tbXAvcFeHusgU_hViO1WeCBe0N5lsYYHRyZ7rrmRkNRuYrXUs_sjl2K8ume_7mKO_0i7C-uHE1oHqaW9d37pabXrSA\");\n      assertThat(archives).extracting(\"description\").containsExactly(\"my archive1\", \"my archive2\");\n      assertThat(archives).extracting(\"size\").containsExactly(2140123L, 2140123L);\n      assertThat(archives).extracting(\"treeHash\").containsExactly(\n              HashCode.fromString(\"6b9d4cf8697bd3af6aa1b590a0b27b337da5b18988dbcc619a3e608a554a1e62\"),\n              HashCode.fromString(\"7f2fe580edb35154041fa3d4b41dd6d3adaef0c85d2ff6309f1d4b520eeecda3\"));\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/test/java/org/jclouds/glacier/blobstore/strategy/internal/BaseSlicingStrategyTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.blobstore.strategy.internal;\n\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.jclouds.glacier.util.TestUtils.MiB;\nimport static org.jclouds.glacier.util.TestUtils.GiB;\nimport static org.jclouds.glacier.util.TestUtils.buildPayload;\n\nimport org.jclouds.glacier.blobstore.strategy.PayloadSlice;\nimport org.jclouds.glacier.util.ContentRange;\nimport org.jclouds.io.internal.BasePayloadSlicer;\nimport org.testng.annotations.Test;\n\n@Test(groups = {\"unit\"})\npublic class BaseSlicingStrategyTest {\n   @Test\n   public void slicing100MBTest() {\n      BaseSlicingStrategy slicer = new BaseSlicingStrategy(new BasePayloadSlicer());\n      slicer.startSlicing(buildPayload(100 * MiB));\n\n      long offset = 0;\n      while (slicer.hasNext()) {\n         PayloadSlice slice = slicer.nextSlice();\n         long expectedLength = (slicer.hasNext() ? 8 : 4) * MiB;\n         assertThat(slice.getPayload().getContentMetadata().getContentLength()).isEqualTo(expectedLength);\n         assertThat(slice.getRange()).isEqualTo(ContentRange.build(offset, offset + expectedLength - 1));\n         offset += expectedLength;\n      }\n   }\n\n   @Test\n   public void slicing2000MBTest() {\n      BaseSlicingStrategy slicer = new BaseSlicingStrategy(new BasePayloadSlicer());\n      slicer.startSlicing(buildPayload(2000 * MiB));\n\n      long offset = 0;\n      while (slicer.hasNext()) {\n         PayloadSlice slice = slicer.nextSlice();\n         long expectedLength = (slicer.hasNext() ? 32 : 16) * MiB;\n         assertThat(slice.getPayload().getContentMetadata().getContentLength()).isEqualTo(expectedLength);\n         assertThat(slice.getRange()).isEqualTo(ContentRange.build(offset, offset + expectedLength - 1));\n         offset += expectedLength;\n      }\n   }\n\n   @Test\n   public void slicing2MBTest() {\n      BaseSlicingStrategy slicer = new BaseSlicingStrategy(new BasePayloadSlicer());\n      slicer.startSlicing(buildPayload(2 * MiB));\n\n      long offset = 0;\n      while (slicer.hasNext()) {\n         PayloadSlice slice = slicer.nextSlice();\n         long expectedLength = 1 * MiB;\n         assertThat(slice.getPayload().getContentMetadata().getContentLength()).isEqualTo(expectedLength);\n         assertThat(slice.getRange()).isEqualTo(ContentRange.build(offset, offset + expectedLength - 1));\n         offset += expectedLength;\n      }\n   }\n\n   @Test\n   public void slicing40000GBTest() {\n      BaseSlicingStrategy slicer = new BaseSlicingStrategy(new BasePayloadSlicer());\n      slicer.startSlicing(buildPayload(40000 * GiB));\n\n      long offset = 0;\n      while (slicer.hasNext()) {\n         PayloadSlice slice = slicer.nextSlice();\n         long expectedLength = 4096 * MiB;\n         assertThat(slice.getPayload().getContentMetadata().getContentLength()).isEqualTo(expectedLength);\n         assertThat(slice.getRange()).isEqualTo(ContentRange.build(offset, offset + expectedLength - 1));\n         offset += expectedLength;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/test/java/org/jclouds/glacier/blobstore/strategy/internal/MultipartUploadStrategyMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.blobstore.strategy.internal;\n\nimport static com.google.common.util.concurrent.MoreExecutors.newDirectExecutorService;\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.jclouds.Constants.PROPERTY_MAX_RETRIES;\nimport static org.jclouds.Constants.PROPERTY_SO_TIMEOUT;\nimport static org.jclouds.glacier.reference.GlacierHeaders.ARCHIVE_DESCRIPTION;\nimport static org.jclouds.glacier.reference.GlacierHeaders.ARCHIVE_ID;\nimport static org.jclouds.glacier.reference.GlacierHeaders.ARCHIVE_SIZE;\nimport static org.jclouds.glacier.reference.GlacierHeaders.MULTIPART_UPLOAD_ID;\nimport static org.jclouds.glacier.reference.GlacierHeaders.PART_SIZE;\nimport static org.jclouds.glacier.reference.GlacierHeaders.TREE_HASH;\nimport static org.jclouds.glacier.util.TestUtils.MiB;\nimport static org.jclouds.glacier.util.TestUtils.buildPayload;\n\nimport java.io.IOException;\nimport java.net.URL;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.blobstore.domain.internal.BlobBuilderImpl;\nimport org.jclouds.concurrent.config.ExecutorServiceModule;\nimport org.jclouds.glacier.GlacierClient;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.io.internal.BasePayloadSlicer;\nimport org.testng.annotations.AfterMethod;\nimport org.testng.annotations.BeforeMethod;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.hash.HashCode;\nimport com.google.common.net.HttpHeaders;\nimport com.google.inject.Module;\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\nimport okhttp3.mockwebserver.RecordedRequest;\n\n@Test(groups = {\"mock\"}, singleThreaded = true)\npublic class MultipartUploadStrategyMockTest {\n   private static final Set<Module> modules = ImmutableSet.<Module> of(new ExecutorServiceModule(newDirectExecutorService(),\n         newDirectExecutorService()));\n   private static HashCode hash8 = HashCode.fromString(\"c87a460c93d4a8ffcf09a9a236cc17a486d7ed8a1a2f48e9c361c5f7ac0f1280\");\n   private static HashCode hash4 = HashCode.fromString(\"9491cb2ed1d4e7cd53215f4017c23ec4ad21d7050a1e6bb636c4f67e8cddb844\");\n   private static HashCode hcomp = HashCode.fromString(\"e196b8ae66b4e55a10c84647957c1291c84ffafa44bfdb88d87f0456e5399e46\");\n\n   MockWebServer server;\n   GlacierClient client;\n\n   private static GlacierClient getGlacierClient(URL server) {\n      Properties overrides = new Properties();\n      // prevent expect-100 bug http://code.google.com/p/mockwebserver/issues/detail?id=6\n      overrides.setProperty(PROPERTY_SO_TIMEOUT, \"0\");\n      overrides.setProperty(PROPERTY_MAX_RETRIES, \"1\");\n      return ContextBuilder.newBuilder(\"glacier\").credentials(\"accessKey\", \"secretKey\").endpoint(server.toString())\n            .modules(modules).overrides(overrides).buildApi(GlacierClient.class);\n   }\n\n   @BeforeMethod\n   private void initServer() throws IOException {\n      server = new MockWebServer();\n      server.start();\n      client = getGlacierClient(server.url(\"/\").url());\n   }\n\n   @AfterMethod\n   private void shutdownServer() throws IOException {\n      server.shutdown();\n   }\n\n   @Test\n   public void testSequentialMPU() throws IOException, InterruptedException {\n      server.enqueue(new MockResponse().setResponseCode(201).addHeader(MULTIPART_UPLOAD_ID, \"upload-id\"));\n      for (int i = 0; i < 12; i++) {\n         server.enqueue(new MockResponse().setResponseCode(204).addHeader(TREE_HASH, hash8));\n      }\n      server.enqueue(new MockResponse().setResponseCode(204).addHeader(TREE_HASH, hash4));\n      server.enqueue(new MockResponse().setResponseCode(201).addHeader(ARCHIVE_ID, \"archive-id\"));\n\n      SequentialMultipartUploadStrategy strat = new SequentialMultipartUploadStrategy(client,\n            new BaseSlicingStrategy(new BasePayloadSlicer()));\n\n      assertThat(strat.execute(\"vault\", new BlobBuilderImpl().name(\"test\").payload(buildPayload(100 * MiB)).build()))\n            .isEqualTo(\"archive-id\");\n\n      RecordedRequest initiate = server.takeRequest();\n      assertThat(initiate.getRequestLine()).isEqualTo(\"POST /-/vaults/vault/multipart-uploads HTTP/1.1\");\n      assertThat(initiate.getHeader(ARCHIVE_DESCRIPTION)).isEqualTo(\"test\");\n      assertThat(Long.parseLong(initiate.getHeader(PART_SIZE))).isEqualTo(8 * MiB);\n\n      RecordedRequest p1 = server.takeRequest();\n      assertThat(p1.getRequestLine())\n            .isEqualTo(\"PUT /-/vaults/vault/multipart-uploads/upload-id HTTP/1.1\");\n      assertThat(Long.parseLong(p1.getHeader(HttpHeaders.CONTENT_LENGTH))).isEqualTo(8388608);\n      assertThat(HashCode.fromString(p1.getHeader(TREE_HASH))).isEqualTo(hash8);\n\n      for (int i = 0; i < 11; i++) {\n         server.takeRequest();\n      }\n\n      RecordedRequest p13 = server.takeRequest();\n      assertThat(p13.getRequestLine())\n            .isEqualTo(\"PUT /-/vaults/vault/multipart-uploads/upload-id HTTP/1.1\");\n      assertThat(HashCode.fromString(p13.getHeader(TREE_HASH))).isEqualTo(hash4);\n      assertThat(Long.parseLong(p13.getHeader(HttpHeaders.CONTENT_LENGTH))).isEqualTo(4194304);\n\n      RecordedRequest complete = server.takeRequest();\n      assertThat(complete.getRequestLine()).isEqualTo(\"POST /-/vaults/vault/multipart-uploads/upload-id HTTP/1.1\");\n      assertThat(HashCode.fromString(complete.getHeader(TREE_HASH))).isEqualTo(hcomp);\n      assertThat(Long.parseLong(complete.getHeader(ARCHIVE_SIZE))).isEqualTo(100 * MiB);\n   }\n\n   @Test(expectedExceptions = HttpResponseException.class)\n   public void testSequentialMPUAbort() throws InterruptedException {\n      server.enqueue(new MockResponse().setResponseCode(201).addHeader(MULTIPART_UPLOAD_ID, \"upload-id\"));\n      server.enqueue(new MockResponse().setResponseCode(204).addHeader(TREE_HASH, hash8));\n      server.enqueue(new MockResponse().setResponseCode(404));\n      server.enqueue(new MockResponse().setResponseCode(204));\n\n      SequentialMultipartUploadStrategy strat = new SequentialMultipartUploadStrategy(client,\n            new BaseSlicingStrategy(new BasePayloadSlicer()));\n\n      try {\n         strat.execute(\"vault\", new BlobBuilderImpl().name(\"test\").payload(buildPayload(100 * MiB)).build());\n      } finally {\n         server.takeRequest();\n         server.takeRequest();\n         server.takeRequest();\n         RecordedRequest abort = server.takeRequest();\n         assertThat(abort.getRequestLine()).isEqualTo(\"DELETE /-/vaults/vault/multipart-uploads/upload-id HTTP/1.1\");\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/glacier/src/test/java/org/jclouds/glacier/predicates/validators/DescriptionValidatorTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.predicates.validators;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static org.jclouds.glacier.util.TestUtils.buildData;\n\nimport java.io.IOException;\n\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"DescriptionValidatorTest\")\npublic class DescriptionValidatorTest {\n\n   private static final DescriptionValidator VALIDATOR = new DescriptionValidator();\n\n   public void testValidate() throws IOException {\n      VALIDATOR.validate(\"This is a valid description\");\n      VALIDATOR.validate(\"This_is*A#valid@Description\");\n      VALIDATOR.validate(\"This~Is~A~Valid~Description\");\n      VALIDATOR.validate(\"&Valid$Description\");\n      VALIDATOR.validate(\"\");\n      VALIDATOR.validate(buildData(1024).asCharSource(UTF_8).read());\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testIllegalCharacter() {\n      VALIDATOR.validate(Character.toString((char) 31));\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testIllegalCharacter2() {\n      VALIDATOR.validate(Character.toString((char) 127));\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testDescriptionTooLong() throws IOException {\n      VALIDATOR.validate(buildData(1025).asCharSource(UTF_8).read());\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/test/java/org/jclouds/glacier/predicates/validators/PartSizeValidatorTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.predicates.validators;\n\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"PartSizeValidatorTest\")\npublic class PartSizeValidatorTest {\n   private static final PartSizeValidator VALIDATOR = new PartSizeValidator();\n\n   public void testValidate() {\n      VALIDATOR.validate(1L);\n      VALIDATOR.validate(2L);\n      VALIDATOR.validate(4L);\n      VALIDATOR.validate(32L);\n      VALIDATOR.validate(4096L);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testZero() {\n      VALIDATOR.validate(0L);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testTooBig() {\n      VALIDATOR.validate(8192L);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testNotPowerOfTwo() {\n      VALIDATOR.validate(25L);\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/test/java/org/jclouds/glacier/predicates/validators/PayloadValidatorTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.predicates.validators;\n\nimport static org.jclouds.glacier.util.TestUtils.GiB;\nimport static org.jclouds.glacier.util.TestUtils.buildPayload;\n\nimport org.jclouds.io.Payload;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"PayloadValidatorTest\")\npublic class PayloadValidatorTest {\n\n   private static final PayloadValidator VALIDATOR = new PayloadValidator();\n\n   public void testValidate() {\n      VALIDATOR.validate(buildPayload(10));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testNoContentLength() {\n      Payload payload = buildPayload(10);\n      payload.getContentMetadata().setContentLength(null);\n      VALIDATOR.validate(payload);\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testNullPayload() {\n      VALIDATOR.validate(null);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testContentLengthTooBig() {\n      VALIDATOR.validate(buildPayload(5 * GiB));\n   }\n\n}\n"
  },
  {
    "path": "apis/glacier/src/test/java/org/jclouds/glacier/predicates/validators/VaultNameValidatorTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.predicates.validators;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static org.jclouds.glacier.util.TestUtils.buildData;\n\nimport java.io.IOException;\n\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"VaultNameValidatorTest\")\npublic class VaultNameValidatorTest {\n\n   private static final VaultNameValidator VALIDATOR = new VaultNameValidator();\n\n   public void testValidate() throws IOException {\n      VALIDATOR.validate(\"VALID_NAME\");\n      VALIDATOR.validate(\"VALID-NAME\");\n      VALIDATOR.validate(\"VALID255NAME\");\n      VALIDATOR.validate(\"255VALID-NAME\");\n      VALIDATOR.validate(\"VALID.NAME\");\n      VALIDATOR.validate(buildData(255).asCharSource(UTF_8).read());\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testEmptyName() {\n      VALIDATOR.validate(\"\");\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testIllegalCharacters() {\n      VALIDATOR.validate(\"<InvalidName>\");\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testIllegalCharacters2() {\n      VALIDATOR.validate(\"INVALID,NAME\");\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testNameTooLong() throws IOException {\n      VALIDATOR.validate(buildData(256).asCharSource(UTF_8).read());\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/test/java/org/jclouds/glacier/util/AWSRequestSignerV4Test.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.util;\n\nimport static org.assertj.core.api.Assertions.assertThat;\n\nimport java.security.NoSuchAlgorithmException;\nimport java.security.cert.CertificateException;\n\nimport org.jclouds.encryption.internal.JCECrypto;\nimport org.jclouds.http.HttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Multimap;\nimport com.google.common.collect.TreeMultimap;\n\n@Test(groups = \"unit\", testName = \"AWSRequestSignerV4Test\")\npublic class AWSRequestSignerV4Test {\n\n   @Test\n   public void testSignatureCalculation() throws NoSuchAlgorithmException, CertificateException {\n      String auth = \"AWS4-HMAC-SHA256 \" + \"Credential=AKIAIOSFODNN7EXAMPLE/20120525/us-east-1/glacier/aws4_request,\"\n            + \"SignedHeaders=host;x-amz-date;x-amz-glacier-version,\"\n            + \"Signature=3ce5b2f2fffac9262b4da9256f8d086b4aaf42eba5f111c21681a65a127b7c2a\";\n      String identity = \"AKIAIOSFODNN7EXAMPLE\";\n      String credential = \"wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY\";\n      AWSRequestSignerV4 signer = new AWSRequestSignerV4(identity, credential, new JCECrypto());\n      HttpRequest request = signer.sign(createRequest());\n      assertThat(request.getFirstHeaderOrNull(\"Authorization\")).isEqualTo(auth);\n   }\n\n   private HttpRequest createRequest() {\n      Multimap<String, String> headers = TreeMultimap.create();\n      headers.put(\"Host\", \"glacier.us-east-1.amazonaws.com\");\n      headers.put(\"x-amz-date\", \"20120525T002453Z\");\n      headers.put(\"x-amz-glacier-version\", \"2012-06-01\");\n      HttpRequest request = HttpRequest.builder().method(\"PUT\")\n            .endpoint(\"https://glacier.us-east-1.amazonaws.com/-/vaults/examplevault\").headers(headers).build();\n      return request;\n   }\n\n}\n"
  },
  {
    "path": "apis/glacier/src/test/java/org/jclouds/glacier/util/ContentRangeTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.util;\n\nimport static org.assertj.core.api.Assertions.assertThat;\n\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ContentRangeTest\")\npublic class ContentRangeTest {\n   @Test\n   public void testContentRangeFromString() {\n      ContentRange range = ContentRange.fromString(\"0-10\");\n      assertThat(range.getFrom()).isEqualTo(0);\n      assertThat(range.getTo()).isEqualTo(10);\n\n      range = ContentRange.fromString(\"1000-2000\");\n      assertThat(range.getFrom()).isEqualTo(1000);\n      assertThat(range.getTo()).isEqualTo(2000);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testContentRangeFromStringWithoutTo() {\n      ContentRange.fromString(\"-10\");\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testContentRangeFromStringWithoutFrom() {\n      ContentRange.fromString(\"10-\");\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testContentRangeFromStringWithEmptyString() {\n      ContentRange.fromString(\"\");\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testContentRangeFromStringWithNullString() {\n      ContentRange.fromString(null);\n   }\n\n   @Test\n   public void testContentRangeFromPartNumber() {\n      ContentRange range = ContentRange.fromPartNumber(0, 4096);\n      assertThat(range.getFrom()).isEqualTo(0);\n      assertThat(range.getTo()).isEqualTo((4096L << 20) - 1);\n\n      range = ContentRange.fromPartNumber(1, 4096);\n      assertThat(range.getFrom()).isEqualTo(4096L << 20);\n      assertThat(range.getTo()).isEqualTo(2 * (4096L << 20) - 1);\n\n      range = ContentRange.fromPartNumber(2, 4096);\n      assertThat(range.getFrom()).isEqualTo(2 * (4096L << 20));\n      assertThat(range.getTo()).isEqualTo(3 * (4096L << 20) - 1);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testContentRangeFromPartNumberWithNegativePartNumber() {\n      ContentRange.fromPartNumber(-1, 4096);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testContentRangeFromPartNumberWithZeroPartSize() {\n      ContentRange.fromPartNumber(0, 0);\n   }\n\n   @Test\n   public void testBuildContentRange() {\n      ContentRange range = ContentRange.build(0, 4096);\n      assertThat(range.getFrom()).isEqualTo(0);\n      assertThat(range.getTo()).isEqualTo(4096);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testBuildContentRangeWithTransposedValues() {\n      ContentRange.build(50, 10);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testBuildContentRangeWithNegatives() {\n      ContentRange.build(-100, -50);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testBuildContentRangeWithZeroTo() {\n      ContentRange.build(0, 0);\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/test/java/org/jclouds/glacier/util/TestUtils.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.util;\n\nimport static com.google.common.net.MediaType.PLAIN_TEXT_UTF_8;\n\nimport java.util.Arrays;\n\nimport org.jclouds.io.ByteSources;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.payloads.ByteSourcePayload;\n\nimport com.google.common.io.ByteSource;\n\npublic class TestUtils {\n   public static final long MiB = 1L << 20;\n   public static final long GiB = 1L << 30;\n   public static final long TiB = 1L << 40;\n\n   public static Payload buildPayload(long size) {\n      ByteSource data = buildData(size);\n      Payload payload = new ByteSourcePayload(data);\n      payload.getContentMetadata().setContentType(PLAIN_TEXT_UTF_8.toString());\n      payload.getContentMetadata().setContentLength(size);\n      return payload;\n   }\n\n   public static ByteSource buildData(long size) {\n      byte[] array = new byte[1024];\n      Arrays.fill(array, (byte) 'a');\n      return ByteSources.repeatingArrayByteSource(array).slice(0, size);\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/test/java/org/jclouds/glacier/util/TreeHashTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glacier.util;\n\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.jclouds.glacier.util.TestUtils.MiB;\nimport static org.jclouds.glacier.util.TestUtils.buildData;\n\nimport java.io.IOException;\n\nimport org.jclouds.io.payloads.ByteSourcePayload;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMap.Builder;\nimport com.google.common.hash.HashCode;\n\n@Test(groups = \"unit\", testName = \"TreeHasherTest\")\npublic class TreeHashTest {\n\n   @Test\n   public void testTreeHasherWith1MBPayload() throws IOException {\n      TreeHash th = TreeHash.buildTreeHashFromPayload(new ByteSourcePayload(buildData(1 * MiB)));\n      assertThat(th.getLinearHash())\n              .isEqualTo(HashCode.fromString(\"9bc1b2a288b26af7257a36277ae3816a7d4f16e89c1e7e77d0a5c48bad62b360\"));\n      assertThat(th.getTreeHash())\n              .isEqualTo(HashCode.fromString(\"9bc1b2a288b26af7257a36277ae3816a7d4f16e89c1e7e77d0a5c48bad62b360\"));\n   }\n\n   @Test\n   public void testTreeHasherWith2MBPayload() throws IOException {\n      TreeHash th = TreeHash.buildTreeHashFromPayload(new ByteSourcePayload(buildData(2 * MiB)));\n      assertThat(th.getLinearHash())\n              .isEqualTo(HashCode.fromString(\"5256ec18f11624025905d057d6befb03d77b243511ac5f77ed5e0221ce6d84b5\"));\n      assertThat(th.getTreeHash())\n              .isEqualTo(HashCode.fromString(\"560c2c9333c719cb00cfdffee3ba293db17f58743cdd1f7e4055373ae6300afa\"));\n   }\n\n   @Test\n   public void testTreeHasherWith3MBPayload() throws IOException {\n      TreeHash th = TreeHash.buildTreeHashFromPayload(new ByteSourcePayload(buildData(3 * MiB)));\n      assertThat(th.getLinearHash())\n              .isEqualTo(HashCode.fromString(\"6f850bc94ae6f7de14297c01616c36d712d22864497b28a63b81d776b035e656\"));\n      assertThat(th.getTreeHash())\n              .isEqualTo(HashCode.fromString(\"70239f4f2ead7561f69d48b956b547edef52a1280a93c262c0b582190be7db17\"));\n   }\n\n   @Test\n   public void testTreeHasherWithMoreThan3MBPayload() throws IOException {\n      TreeHash th = TreeHash.buildTreeHashFromPayload(new ByteSourcePayload(buildData(3 * MiB + 512 * 1024)));\n      assertThat(th.getLinearHash())\n              .isEqualTo(HashCode.fromString(\"34c8bdd269f89a091cf17d5d23503940e0abf61c4b6544e42854b9af437f31bb\"));\n      assertThat(th.getTreeHash())\n              .isEqualTo(HashCode.fromString(\"daede4eb580f914dacd5e0bdf7015c937fd615c1e6c6552d25cb04a8b7219828\"));\n   }\n\n   @Test\n   public void testBuildTreeHashFromMap() throws IOException {\n      Builder<Integer, HashCode> map = ImmutableMap.<Integer, HashCode>builder();\n      map.put(2, HashCode.fromString(\"9bc1b2a288b26af7257a36277ae3816a7d4f16e89c1e7e77d0a5c48bad62b360\"));\n      map.put(1, HashCode.fromString(\"9bc1b2a288b26af7257a36277ae3816a7d4f16e89c1e7e77d0a5c48bad62b360\"));\n      HashCode treehash = TreeHash.buildTreeHashFromMap(map.build());\n      assertThat(treehash).isEqualTo(HashCode.fromString(\"560c2c9333c719cb00cfdffee3ba293db17f58743cdd1f7e4055373ae6300afa\"));\n   }\n}\n"
  },
  {
    "path": "apis/glacier/src/test/resources/json/describeJobResponseBody.json",
    "content": "{\n  \"Action\": \"ArchiveRetrieval\",\n  \"ArchiveId\": \"NkbByEejwEggmBz2fTHgJrg0XBoDfjP4q6iu87-TjhqG6eGoOY9Z8i1_AUyUsuhPAdTqLHy8pTl5nfCFJmDl2yEZONi5L26Omw12vcs01MNGntHEQL8MBfGlqrEXAMPLEArchiveId\",\n  \"ArchiveSizeInBytes\": 16777216,\n  \"ArchiveSHA256TreeHash\": \"beb0fe31a1c7ca8c6c04d574ea906e3f97b31fdca7571defb5b44dca89b5af60\",\n  \"Completed\": false,\n  \"CreationDate\": \"2012-05-15T17:21:39.339Z\",\n  \"CompletionDate\": \"2012-05-15T17:21:43.561Z\",\n  \"InventorySizeInBytes\": null,\n  \"JobDescription\": \"My ArchiveRetrieval Job\",\n  \"JobId\": \"HkF9p6o7yjhFx-K3CGl6fuSm6VzW9T7esGQfco8nUXVYwS0jlb5gq1JZ55yHgt5vP54ZShjoQzQVVh7vEXAMPLEjobID\",\n  \"RetrievalByteRange\": \"0-16777215\",\n  \"SHA256TreeHash\": \"beb0fe31a1c7ca8c6c04d574ea906e3f97b31fdca7571defb5b44dca89b5af60\",\n  \"SNSTopic\": \"arn:aws:sns:us-east-1:012345678901:mytopic\",\n  \"StatusCode\": \"InProgress\",\n  \"StatusMessage\": \"Operation in progress.\",\n  \"VaultARN\": \"arn:aws:glacier:us-east-1:012345678901:vaults/examplevault\"\n}\n"
  },
  {
    "path": "apis/glacier/src/test/resources/json/describeVaultResponseBody.json",
    "content": "{\n  \"CreationDate\" : \"2012-02-20T17:01:45.198Z\",\n  \"LastInventoryDate\" : \"2012-03-20T17:03:43.221Z\",\n  \"NumberOfArchives\" : 192,\n  \"SizeInBytes\" : 78088912,\n  \"VaultARN\" : \"arn:aws:glacier:us-east-1:012345678901:vaults/examplevault\",\n  \"VaultName\" : \"examplevault\"\n}\n"
  },
  {
    "path": "apis/glacier/src/test/resources/json/getJobOutputResponseBody.json",
    "content": "{\n  \"VaultARN\": \"arn:aws:glacier:us-east-1:012345678901:vaults/examplevault\",\n  \"InventoryDate\": \"2011-12-12T14:19:01Z\",\n  \"ArchiveList\": [\n    {\n      \"ArchiveId\": \"DMTmICA2n5Tdqq5BV2z7og-A20xnpAPKt3UXwWxdWsn_D6auTUrW6kwy5Qyj9xd1MCE1mBYvMQ63LWaT8yTMzMaCxB_9VBWrW4Jw4zsvg5kehAPDVKcppUD1X7b24JukOr4mMAq-oA\",\n      \"ArchiveDescription\": \"my archive1\",\n      \"CreationDate\": \"2012-05-15T17:19:46.700Z\",\n      \"Size\": 2140123,\n      \"SHA256TreeHash\": \"6b9d4cf8697bd3af6aa1b590a0b27b337da5b18988dbcc619a3e608a554a1e62\"\n    },\n    {\n      \"ArchiveId\": \"2lHzwhKhgF2JHyvCS-ZRuF08IQLuyB4265Hs3AXj9MoAIhz7tbXAvcFeHusgU_hViO1WeCBe0N5lsYYHRyZ7rrmRkNRuYrXUs_sjl2K8ume_7mKO_0i7C-uHE1oHqaW9d37pabXrSA\",\n      \"ArchiveDescription\": \"my archive2\",\n      \"CreationDate\": \"2012-05-15T17:21:39.339Z\",\n      \"Size\": 2140123,\n      \"SHA256TreeHash\": \"7f2fe580edb35154041fa3d4b41dd6d3adaef0c85d2ff6309f1d4b520eeecda3\"\n    }\n  ]\n}\n"
  },
  {
    "path": "apis/glacier/src/test/resources/json/listJobsResponseBody.json",
    "content": "{\n  \"JobList\": [\n    {\n      \"Action\": \"ArchiveRetrieval\",\n      \"ArchiveId\": \"58-3KpZfcMPUznvMZNPaKyJx9wODCsWTnqcjtx2CjKZ6b-XgxEuA8yvZOYTPQfd7gWR4GRm2XR08gcnWbLV4VPV_kDWtZJKi0TFhKKVPzwrZnA4-FXuIBfViYUIVveeiBE51FO4bvg\",\n      \"ArchiveSizeInBytes\": 8388608,\n      \"ArchiveSHA256TreeHash\": \"106086b256ddf0fedf3d9e72f461d5983a2566247ebe7e1949246bc61359b4f4\",\n      \"Completed\": true,\n      \"CompletionDate\": \"2012-05-01T00:25:20.043Z\",\n      \"CreationDate\": \"2012-05-01T00:25:16.344Z\",\n      \"InventorySizeInBytes\": null,\n      \"JobDescription\": \"aaabbbccc\",\n      \"JobId\": \"s4MvaNHIh6mOa1f8iY4ioG2921SDPihXxh3Kv0FBX-JbNPctpRvE4c2_BifuhdGLqEhGBNGeB6Ub-JMunR9JoVa8y1hQ\",\n      \"RetrievalByteRange\": \"0-8388607\",\n      \"SHA256TreeHash\": \"106086b256ddf0fedf3d9e72f461d5983a2566247ebe7e1949246bc61359b4f4\",\n      \"SNSTopic\": null,\n      \"StatusCode\": \"Succeeded\",\n      \"StatusMessage\": \"Succeeded\",\n      \"VaultARN\": \"arn:aws:glacier:us-east-1:012345678901:vaults/examplevault\"\n    },\n    {\n      \"Action\": \"ArchiveRetrieval\",\n      \"ArchiveId\": \"2NVGpf83U6qB9M2u-Ihh61yoFLRDEoh7YLZWKBn80A2i1xG8uieBwGjAr4RkzOHA0E07ZjtI267R03Z-6Hxd8pyGQkBdciCSH1-Lw63Kx9qKpZbPCdU0uTW_WAdwF6lR6w8iSyKdvw\",\n      \"ArchiveSizeInBytes\": 1048576,\n      \"ArchiveSHA256TreeHash\": \"3d2ae052b2978727e0c51c0a5e32961c6a56650d1f2e4ceccab6472a5ed4a0\",\n      \"Completed\": true,\n      \"CompletionDate\": \"2012-05-01T16:59:48.444Z\",\n      \"CreationDate\": \"2012-05-01T16:59:42.977Z\",\n      \"InventorySizeInBytes\": null,\n      \"JobDescription\": \"aaabbbccc\",\n      \"JobId\": \"CQ_tf6fOR4jrJCL61Mfk6VM03oY8lmnWK93KK4gLig1UPAbZiN3UV4G_5nq4AfmJHQ_dOMLOX5k8ItFv0wCPN0oaz5dG\",\n      \"RetrievalByteRange\": \"0-1048575\",\n      \"SHA256TreeHash\": \"3d2ae052b2978727e0c51c0a5e32961c6a56650d1f2e4ceccab6472a5ed4a0\",\n      \"SNSTopic\": null,\n      \"StatusCode\": \"Succeeded\",\n      \"StatusMessage\": \"Succeeded\",\n      \"VaultARN\": \"arn:aws:glacier:us-east-1:012345678901:vaults/examplevault\"\n    }\n  ],\n  \"Marker\": \"CQ_tf6fOR4jrJCL61Mfk6VM03oY8lmnWK93KK4gLig1UPAbZiN3UV4G_5nq4AfmJHQ_dOMLOX5k8ItFv0wCPN0oaz5dG\"\n}\n"
  },
  {
    "path": "apis/glacier/src/test/resources/json/listMultipartUploadsResponseBody.json",
    "content": "{\n  \"Marker\": \"qt-RBst_7yO8gVIonIBsAxr2t-db0pE4s8MNeGjKjGdNpuU-cdSAcqG62guwV9r5jh5mLyFPzFEitTpNE7iQfHiu1XoV\",\n  \"UploadsList\" : [\n    {\n      \"ArchiveDescription\": \"archive 2\",\n      \"CreationDate\": \"2012-04-01T15:00:00.000Z\",\n      \"MultipartUploadId\": \"nPyGOnyFcx67qqX7E-0tSGiRi88hHMOwOxR-_jNyM6RjVMFfV29lFqZ3rNsSaWBugg6OP92pRtufeHdQH7ClIpSF6uJc\",\n      \"PartSizeInBytes\": 4194304,\n      \"VaultARN\": \"arn:aws:glacier:us-east-1:012345678901:vaults/examplevault\"\n    }\n  ]\n}\n"
  },
  {
    "path": "apis/glacier/src/test/resources/json/listMultipartUploadsWithEmptyListResponseBody.json",
    "content": "{\n  \"Marker\": \"qt-RBst_7yO8gVIonIBsAxr2t-db0pE4s8MNeGjKjGdNpuU-cdSAcqG62guwV9r5jh5mLyFPzFEitTpNE7iQfHiu1XoV\",\n  \"UploadsList\" : []\n}\n"
  },
  {
    "path": "apis/glacier/src/test/resources/json/listPartsResponseBody.json",
    "content": "{\n  \"ArchiveDescription\" : \"archive description 1\",\n  \"CreationDate\" : \"2012-03-20T17:03:43.221Z\",\n  \"Marker\": \"MfgsKHVjbQ6EldVl72bn3_n5h2TaGZQUO-Qb3B9j3TITf7WajQ\",\n  \"MultipartUploadId\" : \"OW2fM5iVylEpFEMM9_HpKowRapC3vn5sSL39_396UW9zLFUWVrnRHaPjUJddQ5OxSHVXjYtrN47NBZ-khxOjyEXAMPLE\",\n  \"PartSizeInBytes\" : 4194304,\n  \"Parts\" :\n  [ {\n    \"RangeInBytes\" : \"4194304-8388607\",\n    \"SHA256TreeHash\" : \"01d34dabf7be316472c93b1ef80721f5d4\"\n    }],\n  \"VaultARN\" : \"arn:aws:glacier:us-east-1:012345678901:vaults/demo1-vault\"\n}\n"
  },
  {
    "path": "apis/glacier/src/test/resources/json/listVaultsResponseBody.json",
    "content": "{\n  \"Marker\": null,\n  \"VaultList\": [ \n   {\n    \"CreationDate\": \"2012-03-16T22:22:47.214Z\",\n    \"LastInventoryDate\": \"2012-03-21T22:06:51.218Z\",\n    \"NumberOfArchives\": 2,\n    \"SizeInBytes\": 12334,\n    \"VaultARN\": \"arn:aws:glacier:us-east-1:012345678901:vaults/examplevault1\",\n    \"VaultName\": \"examplevault1\"\n   }, \n   {\n    \"CreationDate\": \"2012-03-19T22:06:51.218Z\",\n    \"LastInventoryDate\": \"2012-03-21T22:06:51.218Z\",\n    \"NumberOfArchives\": 0,\n    \"SizeInBytes\": 0,\n    \"VaultARN\": \"arn:aws:glacier:us-east-1:012345678901:vaults/examplevault2\",\n    \"VaultName\": \"examplevault2\"\n   },\n   {\n    \"CreationDate\": \"2012-03-19T22:06:51.218Z\",\n    \"LastInventoryDate\": \"2012-03-25T12:14:31.121Z\",\n    \"NumberOfArchives\": 0,\n    \"SizeInBytes\": 0,\n    \"VaultARN\": \"arn:aws:glacier:us-east-1:012345678901:vaults/examplevault3\",\n    \"VaultName\": \"examplevault3\"\n   } \n  ]\n}\n"
  },
  {
    "path": "apis/glacier/src/test/resources/json/listVaultsWithEmptyListResponseBody.json",
    "content": "{\n  \"Marker\": null,\n  \"VaultList\": []\n}\n"
  },
  {
    "path": "apis/glacier/src/test/resources/json/listVaultsWithQueryParamsResponseBody.json",
    "content": "{\n  \"Marker\": \"arn:aws:glacier:us-east-1:012345678901:vaults/examplevault3\",\n  \"VaultList\": [ \n   {\n    \"CreationDate\": \"2012-03-16T22:22:47.214Z\",\n    \"LastInventoryDate\": \"2012-03-21T22:06:51.218Z\",\n    \"NumberOfArchives\": 2,\n    \"SizeInBytes\": 12334,\n    \"VaultARN\": \"arn:aws:glacier:us-east-1:012345678901:vaults/examplevault1\",\n    \"VaultName\": \"examplevault1\"\n   }, \n   {\n    \"CreationDate\": \"2012-03-19T22:06:51.218Z\",\n    \"LastInventoryDate\": \"2012-03-21T22:06:51.218Z\",\n    \"NumberOfArchives\": 0,\n    \"SizeInBytes\": 0,\n    \"VaultARN\": \"arn:aws:glacier:us-east-1:012345678901:vaults/examplevault2\",\n    \"VaultName\": \"examplevault2\"\n   }\n  ]\n}\n"
  },
  {
    "path": "apis/glacier/src/test/resources/testng.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE suite SYSTEM \"http://testng.org/testng-1.0.dtd\" >\n<suite name=\"tests\">\n  <test name=\"livelong\">\n    <groups>\n      <run>\n        <include name=\"livelong\" />\n      </run>\n    </groups>\n    <classes>\n      <class name=\"org.jclouds.glacier.GlacierClientLongLiveTest\" />\n    </classes>\n  </test>\n  <test name=\"mock\">\n    <groups>\n      <run>\n        <include name=\"mock\" />\n      </run>\n    </groups>\n    <classes>\n      <class name=\"org.jclouds.glacier.GlacierClientMockTest\" />\n    </classes>\n  </test>\n  <test name=\"liveshort\">\n    <groups>\n      <run>\n        <include name=\"liveshort\" />\n      </run>\n    </groups>\n    <classes>\n      <class name=\"org.jclouds.glacier.GlacierClientLiveTest\" />\n    </classes>\n  </test>\n</suite>\n"
  },
  {
    "path": "apis/oauth/README",
    "content": "In order to use oauth applications must specify the following properties:\n\nMandatory, when using non-Azure Active Directory oauth:\n<myprovider>.identity - the oauth identity (e.g., service account email in Google Api's)\n<myprovider>.credential - the private key used to sign requests, in pem format\noauth.endpoint - the endpoint to use for authentication (e.g., \"http://accounts.google.com/o/oauth2/token\" in Google Api's)\noauth.audience - the \"audience\" of the token request (e.g., \"http://accounts.google.com/o/oauth2/token\" in Google Api's)\n\nMandatory, when using oauth to authenticate against Azure Active Directory:\n<myprovider>.identity - the application GUID set up for as a Service Principal for your Azure account\n<myprovider>.credential - the password associated with the application GUID\noauth.endpoint - the endpoint to use for Azure AD authentication (URL of the form the URL \"https://login.microsoftonline.com/<Tenant ID>/oauth2/token\")\n\nFor Azure Active Directory, setting up a service principal to work with Azure Resource Manager and Azure AD as well as finding out the <Tenant ID> is described at https://azure.microsoft.com/en-us/documentation/articles/resource-group-authenticate-service-principal/\n\nRunning the live test on for non client_credentials oauth grant type:\n\nmvn clean install -Plive \\\n-Dtest.oauth.identity=<email addr> \\\n-Dtest.oauth.credential=<private key> \\\n-Dtest.oauth.endpoint=https://accounts.google.com/o/oauth2/token \\\n-Dtest.jclouds.oauth.audience=https://accounts.google.com/o/oauth2/token \\\n-Dtest.jclouds.oauth.scope=https://www.googleapis.com/auth/prediction \\\n\n\nTo Run the live test against Azure Active Directory which uses the client_credentials grant type when using a password:\n\nmvn clean install -Plive \\\n-Dtest.oauth.identity=<azure app id> \\\n-Dtest.oauth.credential=<azure app password> \\\n-Dtest.oauth.endpoint=https://login.microsoftonline.com/<tenant id>/oauth2/token \\\n-Dtest.jclouds.oauth.resource=https://management.azure.com/ \\\n-Dtest.jclouds.oauth.credential-type=clientCredentialsSecret\n\nTo run the live test against Azure Active directory using the client_credentials grant type with a certificate and private key:\n\nmvn clean install -Plive \\\n-Dtest.jclouds.oauth.credential-type=clientCredentialsP12AndCertificate \\\n-Dtest.jclouds.oauth.resource=https://management.azure.com/ \\\n-Dtest.oauth.endpoint=https://login.microsoftonline.com/<tenant id>/oauth2/token \\\n-Dtest.jclouds.oauth.audience=https://login.microsoftonline.com/<tenant id>/oauth2/token \n-Dtest.oauth.identity=<azure app id> \\\n-Dtest.oauth.credential=<path to unencrypted private key PEM file> \\\n-Dtest.jclouds.oauth.certificate=<path to certificate PEM file>\n\n"
  },
  {
    "path": "apis/oauth/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.oauth.*;version=\"${project.version}\";-noimport:=true"
  },
  {
    "path": "apis/oauth/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n\n  <groupId>org.apache.jclouds.api</groupId>\n  <artifactId>oauth</artifactId>\n  <name>jclouds OAuth core</name>\n  <description>jclouds components to access OAuth</description>\n\n  <properties>\n    <test.oauth.identity>FIX_ME</test.oauth.identity>\n    <test.oauth.credential>FIX_ME</test.oauth.credential>\n    <test.oauth.endpoint>FIX_ME</test.oauth.endpoint>\n    <test.jclouds.oauth.audience>FIX_ME</test.jclouds.oauth.audience>\n    <test.jclouds.oauth.scope>FIX_ME</test.jclouds.oauth.scope>\n    <test.oauth.api-version>2</test.oauth.api-version>\n    <test.oauth.build-version />\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.value</groupId>\n      <artifactId>auto-value</artifactId>\n      <scope>provided</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-slf4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.squareup.okhttp3</groupId>\n      <artifactId>mockwebserver</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>ch.qos.logback</groupId>\n      <artifactId>logback-classic</artifactId>\n      <scope>test</scope>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>default-test</id>\n                <configuration>\n                  <skipTests>true</skipTests>\n                </configuration>\n              </execution>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.oauth.identity>${test.oauth.identity}</test.oauth.identity>\n                    <test.oauth.credential>${test.oauth.credential}</test.oauth.credential>\n                    <test.oauth.endpoint>${test.oauth.endpoint}</test.oauth.endpoint>\n                    <test.oauth.api-version>${test.oauth.api-version}</test.oauth.api-version>\n                    <test.oauth.build-version>${test.oauth.build-version}</test.oauth.build-version>\n                    <test.jclouds.oauth.jws-alg>${test.jclouds.oauth.jws-alg}</test.jclouds.oauth.jws-alg>\n                    <test.jclouds.oauth.audience>${test.jclouds.oauth.audience}</test.jclouds.oauth.audience>\n                    <test.jclouds.oauth.scope>${test.jclouds.oauth.scope}</test.jclouds.oauth.scope>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n</project>\n"
  },
  {
    "path": "apis/oauth/src/main/java/org/jclouds/oauth/v2/AuthorizationApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.oauth.v2;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.io.Closeable;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.FormParam;\nimport jakarta.ws.rs.POST;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.OAuthFallbacks.AuthorizationExceptionOn4xx;\nimport org.jclouds.oauth.v2.config.Authorization;\nimport org.jclouds.oauth.v2.domain.Claims;\nimport org.jclouds.oauth.v2.domain.ClientCredentialsClaims;\nimport org.jclouds.oauth.v2.domain.Token;\nimport org.jclouds.oauth.v2.functions.ClaimsToAssertion;\nimport org.jclouds.oauth.v2.functions.ClientCredentialsClaimsToAssertion;\nimport org.jclouds.rest.annotations.Endpoint;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.FormParams;\nimport org.jclouds.rest.annotations.ParamParser;\n\n/**\n * Binds to an OAuth2 <a href=\"http://tools.ietf.org/html/rfc6749#section-3.1\">authorization endpoint</a>.\n */\n@Endpoint(Authorization.class)\npublic interface AuthorizationApi extends Closeable {\n   @Named(\"oauth2:authorize\")\n   @POST\n   @FormParams(keys = \"grant_type\", values = \"urn:ietf:params:oauth:grant-type:jwt-bearer\")\n   @Consumes(APPLICATION_JSON)\n   @Fallback(AuthorizationExceptionOn4xx.class)\n   Token authorize(@FormParam(\"assertion\") @ParamParser(ClaimsToAssertion.class) Claims claims);\n\n   @Named(\"oauth2:authorize_client_secret\")\n   @POST\n   @FormParams(keys = \"grant_type\", values = \"client_credentials\")\n   @Consumes(APPLICATION_JSON)\n   @Fallback(AuthorizationExceptionOn4xx.class)\n   Token authorizeClientSecret(\n           @FormParam(\"client_id\") String client_id,\n           @FormParam(\"client_secret\") String client_secret,\n           @FormParam(\"resource\") String resource,\n           @FormParam(\"scope\") @Nullable String scope\n   );\n\n   @Named(\"oauth2:authorize_client_p12\")\n   @POST\n   @FormParams(keys = {\"grant_type\", \"client_assertion_type\"}, values = {\"client_credentials\", \"urn:ietf:params:oauth:client-assertion-type:jwt-bearer\"})\n   @Consumes(APPLICATION_JSON)\n   @Fallback(AuthorizationExceptionOn4xx.class)\n   Token authorize(\n            @FormParam(\"client_id\") String client_id,\n            @FormParam(\"client_assertion\") @ParamParser(ClientCredentialsClaimsToAssertion.class) ClientCredentialsClaims claim,\n            @FormParam(\"resource\") String resource,\n            @FormParam(\"scope\") @Nullable String scope\n   );\n}\n"
  },
  {
    "path": "apis/oauth/src/main/java/org/jclouds/oauth/v2/OAuthFallbacks.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.oauth.v2;\n\nimport static com.google.common.base.Throwables.propagate;\nimport static org.jclouds.http.HttpUtils.returnValueOnCodeOrNull;\n\nimport org.jclouds.Fallback;\nimport org.jclouds.rest.AuthorizationException;\n\nimport com.google.common.base.Predicate;\n\npublic class OAuthFallbacks {\n\n   /**\n    * Fallback used to propagate an {@link AuthorizationException} on any 4xx\n    * response.\n    * <p>\n    * Since OAuth requests will take place as part of the OAuth filter\n    * execution, providers will not have direct access to configure its\n    * behavior. Any failure in the filter execution due to a client side error\n    * (such as malformed ids, etc) should be mapped to an\n    * <code>AuthorizationException</code> so providers and clients can properly\n    * handle the error.\n    * <p>\n    * Note that we use a fallback instead of an error handler to allow each\n    * provider to bind their own handlers in a clean way, without having to\n    * rebind the OAuth one.\n    */\n   public static final class AuthorizationExceptionOn4xx implements Fallback<Object> {\n      public Void createOrPropagate(Throwable t) throws Exception {\n         AuthorizationException ex = returnValueOnCodeOrNull(t, new AuthorizationException(t.getMessage(), t),\n               new Predicate<Integer>() {\n                  @Override\n                  public boolean apply(Integer input) {\n                     return input >= 400 && input < 500;\n                  }\n               });\n         throw ex != null ? ex : propagate(t);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/oauth/src/main/java/org/jclouds/oauth/v2/config/Authorization.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.oauth.v2.config;\n\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\nimport jakarta.inject.Qualifier;\n\n@Retention(value = RetentionPolicy.RUNTIME)\n@Target(value = {ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})\n@Qualifier\npublic @interface Authorization {\n}\n"
  },
  {
    "path": "apis/oauth/src/main/java/org/jclouds/oauth/v2/config/CertificateFingerprintSupplier.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.oauth.v2.config;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Throwables.propagate;\nimport static org.jclouds.crypto.Pems.x509Certificate;\nimport static org.jclouds.oauth.v2.config.OAuthProperties.CERTIFICATE;\nimport static org.jclouds.util.Throwables2.getFirstThrowableOfType;\n\nimport java.io.IOException;\nimport java.security.PrivateKey;\nimport java.security.cert.CertificateException;\nimport java.security.cert.X509Certificate;\n\nimport com.google.inject.Inject;\nimport com.google.inject.Singleton;\nimport jakarta.inject.Named;\n\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.location.Provider;\nimport org.jclouds.oauth.v2.domain.CertificateFingerprint;\nimport org.jclouds.rest.AuthorizationException;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.util.concurrent.UncheckedExecutionException;\nimport com.google.common.hash.Hashing;\nimport static com.google.common.io.BaseEncoding.base64;\nimport com.google.common.hash.HashCode;\n\n/**\n * Loads the fingerprint of a certificate associated with the {@link PrivateKey} from a pem X509Certificate.\n */\n@Singleton // due to cache\nfinal class CertificateFingerprintSupplier implements Supplier<CertificateFingerprint> {\n\n    private final Supplier<Credentials> creds;\n    private final LoadingCache<Credentials, CertificateFingerprint> certCache;\n\n    @Inject CertificateFingerprintSupplier(@Provider Supplier<Credentials> creds, CertificateFingerprintForCredentials loader) {\n        this.creds = creds;\n        // throw out the certificate fingerprint related to old credentials\n        this.certCache = CacheBuilder.newBuilder().maximumSize(2).build(checkNotNull(loader, \"loader\"));\n    }\n\n    /**\n     * it is relatively expensive to extract a certificate from a PEM and calculate it's fingerprint.\n     * cache the relationship between current credentials so that the fingerprint is only recalculated once.\n     */\n    @VisibleForTesting\n    static final class CertificateFingerprintForCredentials extends CacheLoader<Credentials, CertificateFingerprint> {\n        @Inject(optional = true) @Named(CERTIFICATE) String certInPemFormat;\n\n        @Override public CertificateFingerprint load(Credentials in) {\n            try {\n                /**\n                 * CERTIFICATE made optional on injection so that it's not required when other OAuth methods\n                 * are used.\n                 */\n                if (certInPemFormat == null) {\n                    throw new IllegalArgumentException(\"certificate not specified.\");\n                }\n                X509Certificate cert = null;\n                cert = x509Certificate(certInPemFormat);\n\n                /** Get the fingerprint in Base64 format */\n                byte[] encodedCert = cert.getEncoded();\n                HashCode hash = Hashing.sha1().hashBytes(encodedCert);\n                String fingerprint = base64().encode(hash.asBytes());\n\n                return CertificateFingerprint.create(fingerprint, cert);\n            } catch (CertificateException e) {\n                throw new AssertionError(e);\n            } catch (IOException e) {\n                throw propagate(e);\n            } catch (IllegalArgumentException e) {\n                throw new AuthorizationException(\"cannot parse cert. \" + e.getMessage(), e);\n            }\n        }\n    }\n\n    @Override public CertificateFingerprint get() {\n        try {\n            // loader always throws UncheckedExecutionException so no point in using get()\n            return certCache.getUnchecked(checkNotNull(creds.get(), \"credential supplier returned null\"));\n        } catch (UncheckedExecutionException e) {\n            AuthorizationException authorizationException = getFirstThrowableOfType(e, AuthorizationException.class);\n            if (authorizationException != null) {\n                throw authorizationException;\n            }\n            throw e;\n        }\n    }\n}\n\n"
  },
  {
    "path": "apis/oauth/src/main/java/org/jclouds/oauth/v2/config/CredentialType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.oauth.v2.config;\n\nimport static com.google.common.base.CaseFormat.LOWER_CAMEL;\nimport static com.google.common.base.CaseFormat.UPPER_UNDERSCORE;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\n/** Defines the contents of the credential field in {@link org.jclouds.ContextBuilder#credentials(String, String)}. */\npublic enum CredentialType {\n\n   BEARER_TOKEN_CREDENTIALS,\n\n   /** Contents are a PEM-encoded P12 Private Key. */\n   P12_PRIVATE_KEY_CREDENTIALS,\n\n   /** Contents are an ID and Secret */\n   CLIENT_CREDENTIALS_SECRET,\n\n   /** Contents are an ID and PEM-encoded Private Key.  The certificate is specified as it's own property. */\n   CLIENT_CREDENTIALS_P12_AND_CERTIFICATE;\n\n   @Override public String toString() {\n      return UPPER_UNDERSCORE.to(LOWER_CAMEL, name());\n   }\n\n   public static CredentialType fromValue(String credentialType) {\n      return valueOf(LOWER_CAMEL.to(UPPER_UNDERSCORE, checkNotNull(credentialType, \"credentialType\")));\n   }\n}\n"
  },
  {
    "path": "apis/oauth/src/main/java/org/jclouds/oauth/v2/config/OAuthConfigFactory.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.oauth.v2.config;\n\nimport static org.jclouds.oauth.v2.config.OAuthProperties.AUDIENCE;\nimport static org.jclouds.oauth.v2.config.OAuthProperties.RESOURCE;\n\nimport java.util.List;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.annotations.Beta;\nimport com.google.inject.ImplementedBy;\nimport com.google.inject.Inject;\n\n/**\n * Provides all OAuth configuration. Implementations are api-specific.\n */\n@Beta\n@ImplementedBy(OAuthConfigFactory.OAuthConfigFromProperties.class)\npublic interface OAuthConfigFactory {\n\n   @AutoValue\n   public abstract static class OAuthConfig {\n      public abstract List<String> scopes();\n      @Nullable public abstract String audience();\n      @Nullable public abstract String resource();\n\n      public static OAuthConfig create(List<String> scopes, String audience, String resource) {\n         return new AutoValue_OAuthConfigFactory_OAuthConfig(scopes, audience, resource);\n      }\n   }\n\n   /**\n    * Returns the OAuth configuration to be used to authenticate the gicen\n    * request.\n    */\n   OAuthConfig forRequest(HttpRequest input);\n\n   public static class OAuthConfigFromProperties implements OAuthConfigFactory {\n      private final OAuthScopes scopes;\n\n      @Inject(optional = true)\n      @Named(AUDIENCE)\n      private String audience;\n\n      @Inject(optional = true)\n      @Named(RESOURCE)\n      private String resource;\n\n      @Inject\n      OAuthConfigFromProperties(OAuthScopes scopes) {\n         this.scopes = scopes;\n      }\n\n      @Override\n      public OAuthConfig forRequest(HttpRequest input) {\n         return OAuthConfig.create(scopes.forRequest(input), audience, resource);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/oauth/src/main/java/org/jclouds/oauth/v2/config/OAuthModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.oauth.v2.config;\n\nimport static org.jclouds.oauth.v2.config.OAuthProperties.CREDENTIAL_TYPE;\nimport static org.jclouds.oauth.v2.config.CredentialType.BEARER_TOKEN_CREDENTIALS;\nimport static org.jclouds.oauth.v2.config.CredentialType.P12_PRIVATE_KEY_CREDENTIALS;\nimport static org.jclouds.oauth.v2.config.CredentialType.CLIENT_CREDENTIALS_SECRET;\nimport static org.jclouds.oauth.v2.config.CredentialType.CLIENT_CREDENTIALS_P12_AND_CERTIFICATE;\nimport static org.jclouds.rest.config.BinderUtils.bindHttpApi;\n\nimport java.net.URI;\nimport java.security.PrivateKey;\nimport java.util.Map;\n\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.oauth.v2.AuthorizationApi;\nimport org.jclouds.oauth.v2.domain.CertificateFingerprint;\nimport org.jclouds.oauth.v2.filters.JWTBearerTokenFlow;\nimport org.jclouds.oauth.v2.filters.BearerTokenFromCredentials;\nimport org.jclouds.oauth.v2.filters.ClientCredentialsJWTBearerTokenFlow;\nimport org.jclouds.oauth.v2.filters.ClientCredentialsSecretFlow;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Inject;\nimport com.google.inject.Injector;\nimport com.google.inject.Provider;\nimport com.google.inject.Provides;\nimport com.google.inject.TypeLiteral;\n\npublic final class OAuthModule extends AbstractModule {\n\n   @Override protected void configure() {\n      bindHttpApi(binder(), AuthorizationApi.class);\n      bind(CredentialType.class).toProvider(CredentialTypeFromPropertyOrDefault.class);\n      bind(new TypeLiteral<Supplier<PrivateKey>>() {}).annotatedWith(Authorization.class).to(PrivateKeySupplier.class);\n      bind(new TypeLiteral<Supplier<CertificateFingerprint>>() {}).annotatedWith(Authorization.class).to(CertificateFingerprintSupplier.class);\n   }\n\n   @Provides\n   @Authorization\n   protected Supplier<URI> oauthEndpoint(@jakarta.inject.Named(\"oauth.endpoint\") String endpoint) {\n      return Suppliers.ofInstance(URI.create(endpoint));\n   }\n\n   @Singleton\n   public static class CredentialTypeFromPropertyOrDefault implements Provider<CredentialType> {\n      @Inject(optional = true)\n      @Named(CREDENTIAL_TYPE)\n      String credentialType = P12_PRIVATE_KEY_CREDENTIALS.toString();\n\n      @Override\n      public CredentialType get() {\n         return CredentialType.fromValue(credentialType);\n      }\n   }\n   \n   @Provides\n   @Singleton\n   protected Map<CredentialType, Class<? extends OAuthFilter>> authenticationFlowMap() {\n      return ImmutableMap.of(P12_PRIVATE_KEY_CREDENTIALS, JWTBearerTokenFlow.class,\n                             BEARER_TOKEN_CREDENTIALS, BearerTokenFromCredentials.class,\n                             CLIENT_CREDENTIALS_SECRET, ClientCredentialsSecretFlow.class,\n                             CLIENT_CREDENTIALS_P12_AND_CERTIFICATE, ClientCredentialsJWTBearerTokenFlow.class);\n   }\n\n   @Provides\n   @Singleton\n   protected OAuthFilter authenticationFilterForCredentialType(CredentialType credentialType,\n         Map<CredentialType, Class<? extends OAuthFilter>> authenticationFlows, Injector injector) {\n      if (!authenticationFlows.containsKey(credentialType)) {\n         throw new IllegalArgumentException(\"Unsupported credential type: \" + credentialType);\n      }\n      return injector.getInstance(authenticationFlows.get(credentialType));\n   }\n\n}\n"
  },
  {
    "path": "apis/oauth/src/main/java/org/jclouds/oauth/v2/config/OAuthProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.oauth.v2.config;\n\npublic final class OAuthProperties {\n\n   /** The JSON Web Signature alg, must be {@code RS256} or {@code none}. */\n   public static final String JWS_ALG = \"jclouds.oauth.jws-alg\";\n\n   /**\n    * The oauth audience, who this token is intended for. For instance in JWT and for\n    * google API's this property maps to: {\"aud\",\"https://accounts.google.com/o/oauth2/token\"}\n    *\n    * @see <a href=\"https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-30\">doc</a>\n    */\n   public static final String AUDIENCE = \"jclouds.oauth.audience\";\n\n   /**\n    * Specify if credentials are id + private key or if you are reusing an oauth2 token.\n    *\n    * @see org.jclouds.oauth.v2.config.CredentialType\n    */\n   public static final String CREDENTIAL_TYPE = \"jclouds.oauth.credential-type\";\n\n   /**\n    * When using oauth with Azure Active Directory and Client Credentials, a \"resource\" must\n    * be specified as part of the request.\n    *\n    * @see <a href=\"https://msdn.microsoft.com/en-us/library/azure/dn645543.aspx\">doc</a>\n    */\n   public static final String RESOURCE = \"jclouds.oauth.resource\";\n\n   /**\n    * When using oauth with Azure Active Directory, Client Credentials, and using JWT\n    * authentication, the certificate associated with the Private Key must be provided.\n    * The fingerprint of the certificate is included in the JWT headers.\n    */\n   public static final String CERTIFICATE = \"jclouds.oauth.certificate\";\n\n   private OAuthProperties() {\n   }\n}\n\n"
  },
  {
    "path": "apis/oauth/src/main/java/org/jclouds/oauth/v2/config/OAuthScopes.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.oauth.v2.config;\n\nimport java.util.List;\n\nimport org.jclouds.http.HttpRequest;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Implementations are api-specific, typically routing GET or HEAD requests to a read-only role, and others to a\n * read-write one.\n */\npublic interface OAuthScopes {\n\n   /** Returns a list of scopes needed to perform the request. */\n   List<String> forRequest(HttpRequest input);\n\n   @AutoValue public abstract static class SingleScope implements OAuthScopes {\n      abstract List<String> scopes();\n\n      public static SingleScope create(String scope) {\n         return new AutoValue_OAuthScopes_SingleScope(ImmutableList.of(scope));\n      }\n\n      @Override public List<String> forRequest(HttpRequest input) {\n         return scopes();\n      }\n\n      SingleScope() {\n      }\n   }\n   \n   @AutoValue public abstract static class NoScopes implements OAuthScopes {\n       public static NoScopes create() {\n          return new AutoValue_OAuthScopes_NoScopes();\n       }\n\n       @Override public List<String> forRequest(HttpRequest input) {\n          return ImmutableList.of();\n       }\n\n       NoScopes() {\n       }\n    }\n\n   @AutoValue public abstract static class ReadOrWriteScopes implements OAuthScopes {\n      abstract List<String> readScopes();\n\n      abstract List<String> writeScopes();\n\n      public static ReadOrWriteScopes create(String readScope, String writeScope) {\n         return new AutoValue_OAuthScopes_ReadOrWriteScopes( //\n               ImmutableList.of(readScope), //\n               ImmutableList.of(writeScope) //\n         );\n      }\n\n      @Override public List<String> forRequest(HttpRequest input) {\n         if (input.getMethod().equals(\"GET\") || input.getMethod().equals(\"HEAD\")) {\n            return readScopes();\n         }\n         return writeScopes();\n      }\n\n      ReadOrWriteScopes() {\n      }\n   }\n}\n"
  },
  {
    "path": "apis/oauth/src/main/java/org/jclouds/oauth/v2/config/PrivateKeySupplier.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.oauth.v2.config;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Throwables.propagate;\nimport static org.jclouds.crypto.Pems.privateKeySpec;\nimport static org.jclouds.util.Throwables2.getFirstThrowableOfType;\n\nimport java.io.IOException;\nimport java.security.KeyFactory;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.PrivateKey;\nimport java.security.spec.InvalidKeySpecException;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.location.Provider;\nimport org.jclouds.rest.AuthorizationException;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.io.ByteSource;\nimport com.google.common.util.concurrent.UncheckedExecutionException;\n\n/**\n * Loads {@link PrivateKey} from a pem private key using and RSA KeyFactory. The pem pk algorithm must match the\n * KeyFactory algorithm.\n */\n@Singleton // due to cache\nfinal class PrivateKeySupplier implements Supplier<PrivateKey> {\n\n   private final Supplier<Credentials> creds;\n   private final LoadingCache<Credentials, PrivateKey> keyCache;\n\n   @Inject PrivateKeySupplier(@Provider Supplier<Credentials> creds, PrivateKeyForCredentials loader) {\n      this.creds = creds;\n      // throw out the private key related to old credentials\n      this.keyCache = CacheBuilder.newBuilder().maximumSize(2).build(checkNotNull(loader, \"loader\"));\n   }\n\n   /**\n    * it is relatively expensive to extract a private key from a PEM. cache the relationship between current\n    * credentials\n    * so that the private key is only recalculated once.\n    */\n   @VisibleForTesting\n   static final class PrivateKeyForCredentials extends CacheLoader<Credentials, PrivateKey> {\n\n      @Override public PrivateKey load(Credentials in) {\n         try {\n            String privateKeyInPemFormat = checkNotNull(in.credential, \"credential in PEM format\");\n            KeyFactory keyFactory = KeyFactory.getInstance(\"RSA\");\n            return keyFactory.generatePrivate(privateKeySpec(ByteSource.wrap(privateKeyInPemFormat.getBytes(UTF_8))));\n         } catch (NoSuchAlgorithmException e) {\n            throw new AssertionError(e);\n         } catch (IOException e) {\n            throw propagate(e);\n         } catch (InvalidKeySpecException e) {\n            throw new AuthorizationException(\"security exception loading credentials. \" + e.getMessage(), e);\n            // catch IAE that is thrown when parsing the pk fails\n         } catch (IllegalArgumentException e) {\n            throw new AuthorizationException(\"cannot parse pk. \" + e.getMessage(), e);\n         }\n      }\n   }\n\n   @Override public PrivateKey get() {\n      try {\n         // loader always throws UncheckedExecutionException so no point in using get()\n         return keyCache.getUnchecked(checkNotNull(creds.get(), \"credential supplier returned null\"));\n      } catch (UncheckedExecutionException e) {\n         AuthorizationException authorizationException = getFirstThrowableOfType(e, AuthorizationException.class);\n         if (authorizationException != null) {\n            throw authorizationException;\n         }\n         throw e;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/oauth/src/main/java/org/jclouds/oauth/v2/domain/CertificateFingerprint.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.oauth.v2.domain;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\nimport java.security.cert.X509Certificate;\n\n/**\n * Details corresponding the a client_credential Azure AD Oauth request\n */\n@AutoValue\npublic abstract class CertificateFingerprint {\n    /** The fingerprint of the certificate **/\n    public abstract String fingerprint();\n\n    /** The certificate */\n    public abstract X509Certificate certificate();\n\n    @SerializedNames({ \"fingerprint\", \"certificate\" })\n    public static CertificateFingerprint create(String fingerprint, X509Certificate certificate) {\n        return new AutoValue_CertificateFingerprint(fingerprint, certificate);\n    }\n\n    CertificateFingerprint() {\n    }\n}\n"
  },
  {
    "path": "apis/oauth/src/main/java/org/jclouds/oauth/v2/domain/Claims.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.oauth.v2.domain;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n/**\n * Claims corresponding to a {@linkplain Token JWT Token}.\n *\n * @see <a href=\"https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-30#section-4\">registered list</a>\n */\n@AutoValue\npublic abstract class Claims {\n   /** The issuer of this token. In google, the service account email. */\n   public abstract String iss();\n\n   /** A comma-separated list of scopes needed to perform the request. */\n   public abstract String scope();\n\n   /**\n    * The oauth audience, who this token is intended for. For instance in JWT and for\n    * google API's, this maps to: {@code https://accounts.google.com/o/oauth2/token}\n    */\n   public abstract String aud();\n\n   /** The expiration time, in seconds since {@link #iat()}. */\n   public abstract long exp();\n\n   /** The time at which the JWT was issued, in seconds since the epoch. */\n   public abstract long iat();\n\n   @SerializedNames({ \"iss\", \"scope\", \"aud\", \"exp\", \"iat\" })\n   public static Claims create(String iss, String scope, String aud, long exp, long iat) {\n      return new AutoValue_Claims(iss, scope, aud, exp, iat);\n   }\n\n   Claims() {\n   }\n}\n"
  },
  {
    "path": "apis/oauth/src/main/java/org/jclouds/oauth/v2/domain/ClientCredentialsAuthArgs.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.oauth.v2.domain;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n/**\n * Details corresponding the a client_credential Azure AD Oauth request\n */\n@AutoValue\npublic abstract class ClientCredentialsAuthArgs {\n    /** The ID of the client. **/\n    public abstract String clientId();\n\n    /** The claims for the JWT. */\n    public abstract ClientCredentialsClaims claims();\n\n    /** The resource to authorize against. **/\n    public abstract String resource();\n\n    /** The scope(s) to authorize against. **/\n    @Nullable public abstract String scope();\n\n    @SerializedNames({ \"client_id\", \"claims\", \"resource\", \"scope\" })\n    public static ClientCredentialsAuthArgs create(String clientId, ClientCredentialsClaims claims, String resource, String scope) {\n        return new AutoValue_ClientCredentialsAuthArgs(clientId, claims, resource, scope);\n    }\n\n    ClientCredentialsAuthArgs() {\n    }\n}\n"
  },
  {
    "path": "apis/oauth/src/main/java/org/jclouds/oauth/v2/domain/ClientCredentialsClaims.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.oauth.v2.domain;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n/**\n * Claims corresponding to a {@linkplain Token JWT Token} for use when making a client_credentials grant request.\n *\n * @see <a href=\"https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-30#section-4\">registered list</a>\n */\n@AutoValue\npublic abstract class ClientCredentialsClaims {\n    /**\n     * The issuer of this token. In Azure, it is either the email address for the Active Directory account\n     * or the ID of the application set up as a Service Principal.\n     */\n    public abstract String iss();\n\n    /** The subject of the JWT.  For Azure, \"sub\" is typically equal to \"iss\". */\n    public abstract String sub();\n\n    /**\n     * The oauth audience, who this token is intended for. For instance in JWT and for Azure\n     * Resource Manager APIs, this maps to https://login.microsoftonline.com/TENANT_ID/oauth2/token.\n     */\n    public abstract String aud();\n\n    /** The expiration time, in seconds since the epoch after which the JWT must not be accepted for processing. */\n    public abstract long exp();\n\n    /** The time before which the JWT must not be accepted for processing, in seconds since the epoch. */\n    public abstract long nbf();\n\n    /** \"JWT ID\", a unique identifier for the JWT. */\n    @Nullable\n    public abstract String jti();\n\n    @SerializedNames({ \"iss\", \"sub\", \"aud\", \"exp\", \"nbf\", \"jti\" })\n    public static ClientCredentialsClaims create(String iss, String sub, String aud, long exp, long nbf, @Nullable String jti) {\n        return new AutoValue_ClientCredentialsClaims(iss, sub, aud, exp, nbf, jti);\n    }\n\n    ClientCredentialsClaims() {\n    }\n}\n"
  },
  {
    "path": "apis/oauth/src/main/java/org/jclouds/oauth/v2/domain/ClientSecret.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.oauth.v2.domain;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n/**\n * Details corresponding the a client_credential Azure AD Oauth request\n */\n@AutoValue\npublic abstract class ClientSecret {\n    /** The ID of the client. **/\n    public abstract String clientId();\n\n    /** The secret of the client. **/\n    public abstract String clientSecret();\n\n    /** The resource to authorize against. **/\n    public abstract String resource();\n\n    /** The scope(s) to authorize against. **/\n    @Nullable public abstract String scope();\n\n    @SerializedNames({ \"client_id\", \"client_secret\", \"resource\", \"scope\" })\n    public static ClientSecret create(String clientId, String clientSecret, String resource, String scope) {\n        return new AutoValue_ClientSecret(clientId, clientSecret, resource, scope);\n    }\n\n    ClientSecret() {\n    }\n}\n"
  },
  {
    "path": "apis/oauth/src/main/java/org/jclouds/oauth/v2/domain/Token.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.oauth.v2.domain;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n/**\n * The oauth token, obtained upon a successful token request and ready to embed in requests.\n */\n@AutoValue\npublic abstract class Token {\n   /** The access token obtained from the OAuth server. */\n   public abstract String accessToken();\n\n   /** The type of the token, e.g., {@code Bearer}. */\n   public abstract String tokenType();\n\n   /** In how many seconds this token expires. */\n   public abstract long expiresIn();\n\n   @SerializedNames({\"access_token\", \"token_type\", \"expires_in\"})\n   public static Token create(String accessToken, String tokenType, long expiresIn) {\n      return new AutoValue_Token(accessToken, tokenType, expiresIn);\n   }\n}\n"
  },
  {
    "path": "apis/oauth/src/main/java/org/jclouds/oauth/v2/filters/BearerTokenFromCredentials.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.oauth.v2.filters;\n\nimport static java.lang.String.format;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.location.Provider;\n\nimport com.google.common.base.Supplier;\n\n/**\n * When the user supplies {@link org.jclouds.oauth.v2.config.CredentialType#BEARER_TOKEN_CREDENTIALS}, the credential\n * is a literal bearer token. This filter applies that to the request.\n */\npublic final class BearerTokenFromCredentials implements OAuthFilter {\n   private final Supplier<Credentials> creds;\n\n   @Inject BearerTokenFromCredentials(@Provider Supplier<Credentials> creds) {\n      this.creds = creds;\n   }\n\n   @Override public HttpRequest filter(HttpRequest request) throws HttpException {\n      return request.toBuilder().addHeader(\"Authorization\", format(\"%s %s\", \"Bearer\", creds.get().credential)).build();\n   }\n}\n"
  },
  {
    "path": "apis/oauth/src/main/java/org/jclouds/oauth/v2/filters/ClientCredentialsJWTBearerTokenFlow.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.oauth.v2.filters;\n\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL;\n\nimport java.util.UUID;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\n\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.location.Provider;\nimport org.jclouds.oauth.v2.AuthorizationApi;\nimport org.jclouds.oauth.v2.config.OAuthConfigFactory;\nimport org.jclouds.oauth.v2.config.OAuthConfigFactory.OAuthConfig;\nimport org.jclouds.oauth.v2.domain.ClientCredentialsAuthArgs;\nimport org.jclouds.oauth.v2.domain.ClientCredentialsClaims;\nimport org.jclouds.oauth.v2.domain.Token;\n\nimport com.google.common.base.Joiner;\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\n\n/**\n * Authorizes new Bearer Tokens at runtime by authorizing claims needed for the http request.\n *\n * <h3>Cache</h3>\n * This maintains a time-based Bearer Token cache. By default expires after 59 minutes\n * (the maximum time a token is valid is 60 minutes).\n * This cache and expiry period is system-wide and does not attend to per-instance expiry time\n * (e.g. \"expires_in\" from Google Compute -- which is set to the standard 3600 seconds).\n */\npublic class ClientCredentialsJWTBearerTokenFlow implements OAuthFilter {\n    private static final Joiner ON_SPACE = Joiner.on(\" \");\n\n    private final Supplier<Credentials> credentialsSupplier;\n    private final OAuthConfigFactory oauthConfigFactory;\n    private final LoadingCache<ClientCredentialsAuthArgs, Token> tokenCache;\n\n    @Inject\n    ClientCredentialsJWTBearerTokenFlow(AuthorizeToken loader, @Named(PROPERTY_SESSION_INTERVAL) long tokenDuration,\n                                        @Provider Supplier<Credentials> credentialsSupplier,\n                                        OAuthConfigFactory oauthConfigFactory) {\n        this.credentialsSupplier = credentialsSupplier;\n        this.oauthConfigFactory = oauthConfigFactory;\n        // since the session interval is also the token expiration time requested to the server make the token expire a\n        // bit before the deadline to make sure there aren't session expiration exceptions\n        long cacheExpirationSeconds = tokenDuration > 30 ? tokenDuration - 30 : tokenDuration;\n        this.tokenCache = CacheBuilder.newBuilder().expireAfterWrite(cacheExpirationSeconds, SECONDS).build(loader);\n    }\n\n    static final class AuthorizeToken extends CacheLoader<ClientCredentialsAuthArgs, Token> {\n        private final AuthorizationApi api;\n        private final long tokenDuration;\n\n        @Inject AuthorizeToken(AuthorizationApi api, @Named(PROPERTY_SESSION_INTERVAL) long tokenDuration) {\n            this.api = api;\n            this.tokenDuration = tokenDuration;\n        }\n\n        long currentTimeSeconds() {\n            return System.currentTimeMillis() / 1000;\n        }\n\n        @Override public Token load(ClientCredentialsAuthArgs key) throws Exception {\n            final long now = currentTimeSeconds();\n            final ClientCredentialsClaims claims = ClientCredentialsClaims.create(\n                  key.claims().iss(),\n                  key.claims().sub(),\n                  key.claims().aud(),\n                  now + tokenDuration,\n                  now,\n                  UUID.randomUUID().toString()\n            );\n            return api.authorize(key.clientId(), claims, key.resource(), key.scope());\n        }\n    }\n\n    @Override public HttpRequest filter(HttpRequest request) throws HttpException {\n        OAuthConfig oauthConfig = oauthConfigFactory.forRequest(request);\n        ClientCredentialsClaims claims = ClientCredentialsClaims.create( //\n                credentialsSupplier.get().identity, // iss\n                credentialsSupplier.get().identity, // sub\n                oauthConfig.audience(), // aud\n                -1, // placeholder exp for the cache\n                -1, // placeholder nbf for the cache\n                null // placeholder jti for the cache\n        );\n        ClientCredentialsAuthArgs authArgs = ClientCredentialsAuthArgs.create(\n                credentialsSupplier.get().identity,\n                claims,\n                oauthConfig.resource(),\n                oauthConfig.scopes().isEmpty() ? null : ON_SPACE.join(oauthConfig.scopes())\n         );\n\n        Token token = tokenCache.getUnchecked(authArgs);\n        String authorization = String.format(\"%s %s\", token.tokenType(), token.accessToken());\n        return request.toBuilder().addHeader(\"Authorization\", authorization).build();\n    }\n}\n\n"
  },
  {
    "path": "apis/oauth/src/main/java/org/jclouds/oauth/v2/filters/ClientCredentialsSecretFlow.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.oauth.v2.filters;\n\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.location.Provider;\nimport org.jclouds.oauth.v2.AuthorizationApi;\nimport org.jclouds.oauth.v2.config.OAuthConfigFactory;\nimport org.jclouds.oauth.v2.config.OAuthConfigFactory.OAuthConfig;\nimport org.jclouds.oauth.v2.domain.ClientSecret;\nimport org.jclouds.oauth.v2.domain.Token;\n\nimport com.google.common.base.Joiner;\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.inject.Inject;\n\n/**\n * Authorizes new Bearer Tokens at runtime by sending up for the http request.\n *\n * To retrieve the Bearer Token, a request of grant_type=client_credentials is\n * used.  The credential supplied is a password.\n *\n * <h3>Cache</h3>\n * This maintains a time-based Bearer Token cache. By default expires after 59 minutes\n * (the maximum time a token is valid is 60 minutes).\n */\npublic class ClientCredentialsSecretFlow implements OAuthFilter {\n    private static final Joiner ON_SPACE = Joiner.on(\" \");\n\n    private final Supplier<Credentials> credentialsSupplier;\n    private final LoadingCache<ClientSecret, Token> tokenCache;\n    private final OAuthConfigFactory oauthConfigFactory;\n\n    @Inject\n    ClientCredentialsSecretFlow(AuthorizeToken loader, @Named(PROPERTY_SESSION_INTERVAL) long tokenDuration,\n                                @Provider Supplier<Credentials> credentialsSupplier,\n                                OAuthConfigFactory oauthConfigFactory) {\n        this.credentialsSupplier = credentialsSupplier;\n        this.oauthConfigFactory = oauthConfigFactory;\n        // since the session interval is also the token expiration time requested to the server make the token expire a\n        // bit before the deadline to make sure there aren't session expiration exceptions\n        long cacheExpirationSeconds = tokenDuration > 30 ? tokenDuration - 30 : tokenDuration;\n        this.tokenCache = CacheBuilder.newBuilder().expireAfterWrite(cacheExpirationSeconds, SECONDS).build(loader);\n    }\n\n    static final class AuthorizeToken extends CacheLoader<ClientSecret, Token> {\n        private final AuthorizationApi api;\n\n        @Inject AuthorizeToken(AuthorizationApi api) {\n            this.api = api;\n        }\n\n        @Override public Token load(ClientSecret key) throws Exception {\n            return api.authorizeClientSecret(key.clientId(), key.clientSecret(), key.resource(), key.scope());\n        }\n    }\n\n    @Override public HttpRequest filter(HttpRequest request) throws HttpException {\n        OAuthConfig oauthConfig = oauthConfigFactory.forRequest(request);\n        ClientSecret client = ClientSecret.create(\n                credentialsSupplier.get().identity,\n                credentialsSupplier.get().credential,\n                oauthConfig.resource(),\n                oauthConfig.scopes().isEmpty() ? null : ON_SPACE.join(oauthConfig.scopes())\n        );\n        Token token = tokenCache.getUnchecked(client);\n        String authorization = String.format(\"%s %s\", token.tokenType(), token.accessToken());\n        return request.toBuilder().addHeader(\"Authorization\", authorization).build();\n    }\n}\n"
  },
  {
    "path": "apis/oauth/src/main/java/org/jclouds/oauth/v2/filters/JWTBearerTokenFlow.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.oauth.v2.filters;\n\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\n\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.location.Provider;\nimport org.jclouds.oauth.v2.AuthorizationApi;\nimport org.jclouds.oauth.v2.config.OAuthConfigFactory;\nimport org.jclouds.oauth.v2.config.OAuthConfigFactory.OAuthConfig;\nimport org.jclouds.oauth.v2.domain.Claims;\nimport org.jclouds.oauth.v2.domain.Token;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.base.Joiner;\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\n\n/**\n * Authorizes new Bearer Tokens at runtime by authorizing claims needed for the http request.\n *\n * <h3>Cache</h3>\n * This maintains a time-based Bearer Token cache. By default expires after 59 minutes\n * (the maximum time a token is valid is 60 minutes).\n * This cache and expiry period is system-wide and does not attend to per-instance expiry time\n * (e.g. \"expires_in\" from Google Compute -- which is set to the standard 3600 seconds).\n */\npublic class JWTBearerTokenFlow implements OAuthFilter {\n   private static final Joiner ON_COMMA = Joiner.on(\",\");\n\n   private final Supplier<Credentials> credentialsSupplier;\n   private final OAuthConfigFactory oauthConfigFactory;\n   private final LoadingCache<TokenCacheKey, Token> tokenCache;\n\n   @Inject JWTBearerTokenFlow(AuthorizeToken loader, @Named(PROPERTY_SESSION_INTERVAL) long tokenDuration,\n         @Provider Supplier<Credentials> credentialsSupplier, OAuthConfigFactory oauthConfigFactory) {\n      this.credentialsSupplier = credentialsSupplier;\n      this.oauthConfigFactory = oauthConfigFactory;\n      // since the session interval is also the token expiration time requested to the server make the token expire a\n      // bit before the deadline to make sure there aren't session expiration exceptions\n      long cacheExpirationSeconds = tokenDuration > 30 ? tokenDuration - 30 : tokenDuration;\n      this.tokenCache = CacheBuilder.newBuilder().expireAfterWrite(cacheExpirationSeconds, SECONDS).build(loader);\n   }\n\n   static final class AuthorizeToken extends CacheLoader<TokenCacheKey, Token> {\n      private final AuthorizationApi api;\n      private final long tokenDuration;\n\n      @Inject AuthorizeToken(AuthorizationApi api, @Named(PROPERTY_SESSION_INTERVAL) long tokenDuration) {\n         this.api = api;\n         this.tokenDuration = tokenDuration;\n      }\n\n      @Override public Token load(TokenCacheKey tokenCacheKey) throws Exception {\n         final Claims claims = Claims.create(\n               tokenCacheKey.claims().iss(),\n               tokenCacheKey.claims().scope(),\n               tokenCacheKey.claims().aud(),\n               tokenCacheKey.startTime + tokenDuration,\n               tokenCacheKey.startTime);\n         return api.authorize(claims);\n      }\n   }\n\n   @Override public HttpRequest filter(HttpRequest request) throws HttpException {\n      long now = currentTimeSeconds();\n      OAuthConfig oauthConfig = oauthConfigFactory.forRequest(request);\n      Claims claims = Claims.create( //\n            credentialsSupplier.get().identity, // iss\n            ON_COMMA.join(oauthConfig.scopes()), // scope\n            oauthConfig.audience(), // aud\n            -1, // placeholder exp for the cache\n            -1 // placeholder iat for the cache\n      );\n      final TokenCacheKey tokenCacheKey = TokenCacheKey.create(claims, now);\n      Token token = tokenCache.getUnchecked(tokenCacheKey);\n      String authorization = String.format(\"%s %s\", token.tokenType(), token.accessToken());\n      return request.toBuilder().addHeader(\"Authorization\", authorization).build();\n   }\n\n   long currentTimeSeconds() {\n      return System.currentTimeMillis() / 1000;\n   }\n\n   @AutoValue\n   abstract static class TokenCacheKey {\n      public abstract Claims claims();\n\n      long startTime;\n\n      public static TokenCacheKey create(Claims claims, long startTime) {\n         final AutoValue_JWTBearerTokenFlow_TokenCacheKey tokenCacheKey = new AutoValue_JWTBearerTokenFlow_TokenCacheKey(claims);\n         tokenCacheKey.startTime = startTime;\n         return tokenCacheKey;\n      }\n\n      TokenCacheKey() {\n      }\n   }\n}\n"
  },
  {
    "path": "apis/oauth/src/main/java/org/jclouds/oauth/v2/filters/OAuthFilter.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.oauth.v2.filters;\n\nimport org.jclouds.http.HttpRequestFilter;\n\n/** Indicates use of auth mechanism according to {@link org.jclouds.oauth.v2.config.OAuthProperties#CREDENTIAL_TYPE). */\npublic interface OAuthFilter extends HttpRequestFilter {\n}\n"
  },
  {
    "path": "apis/oauth/src/main/java/org/jclouds/oauth/v2/functions/ClaimsToAssertion.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.oauth.v2.functions;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.base.Joiner.on;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.io.BaseEncoding.base64Url;\nimport static org.jclouds.oauth.v2.config.OAuthProperties.JWS_ALG;\n\nimport java.security.InvalidKeyException;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.PrivateKey;\nimport java.security.Signature;\nimport java.security.SignatureException;\nimport java.util.List;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\n\nimport org.jclouds.json.Json;\nimport org.jclouds.oauth.v2.config.Authorization;\nimport org.jclouds.rest.AuthorizationException;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableList;\n\npublic final class ClaimsToAssertion implements Function<Object, String> {\n   private static final List<String> SUPPORTED_ALGS = ImmutableList.of(\"RS256\", \"none\");\n\n   private final Supplier<PrivateKey> privateKey;\n   private final Json json;\n   private final String alg;\n\n   @Inject ClaimsToAssertion(@Named(JWS_ALG) String alg, @Authorization Supplier<PrivateKey> privateKey, Json json) {\n      this.alg = alg;\n      checkArgument(SUPPORTED_ALGS.contains(alg), \"%s %s not in supported list\", JWS_ALG, alg, SUPPORTED_ALGS);\n      this.privateKey = privateKey;\n      this.json = json;\n   }\n\n   @Override public String apply(Object input) {\n      String encodedHeader = String.format(\"{\\\"alg\\\":\\\"%s\\\",\\\"typ\\\":\\\"JWT\\\"}\", alg);\n      String encodedClaimSet = json.toJson(input);\n\n      encodedHeader = base64Url().omitPadding().encode(encodedHeader.getBytes(UTF_8));\n      encodedClaimSet = base64Url().omitPadding().encode(encodedClaimSet.getBytes(UTF_8));\n\n      byte[] signature = alg.equals(\"none\")\n            ? null\n            : sha256(privateKey.get(), on(\".\").join(encodedHeader, encodedClaimSet).getBytes(UTF_8));\n      String encodedSignature = signature != null ?  base64Url().omitPadding().encode(signature) : \"\";\n\n      // the final assertion in base 64 encoded {header}.{claimSet}.{signature} format\n      return on(\".\").join(encodedHeader, encodedClaimSet, encodedSignature);\n   }\n\n   static byte[] sha256(PrivateKey privateKey, byte[] input) {\n      try {\n         Signature signature = Signature.getInstance(\"SHA256withRSA\");\n         signature.initSign(privateKey);\n         signature.update(input);\n         return signature.sign();\n      } catch (NoSuchAlgorithmException e) {\n         throw new AssertionError(e);\n      } catch (SignatureException e) {\n         throw new AuthorizationException(e);\n      } catch (InvalidKeyException e) {\n         throw new AuthorizationException(e);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/oauth/src/main/java/org/jclouds/oauth/v2/functions/ClientCredentialsClaimsToAssertion.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.oauth.v2.functions;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.base.Joiner.on;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.io.BaseEncoding.base64Url;\nimport static org.jclouds.oauth.v2.config.OAuthProperties.JWS_ALG;\n\nimport java.security.InvalidKeyException;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.PrivateKey;\nimport java.security.Signature;\nimport java.security.SignatureException;\nimport java.util.List;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\n\nimport org.jclouds.json.Json;\nimport org.jclouds.oauth.v2.config.Authorization;\nimport org.jclouds.oauth.v2.domain.CertificateFingerprint;\nimport org.jclouds.rest.AuthorizationException;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableList;\n\npublic final class ClientCredentialsClaimsToAssertion implements Function<Object, String> {\n    private static final List<String> SUPPORTED_ALGS = ImmutableList.of(\"RS256\", \"none\");\n\n    private final Supplier<PrivateKey> privateKey;\n    private final Supplier<CertificateFingerprint> certFingerprint;\n    private final Json json;\n    private final String alg;\n\n    @Inject ClientCredentialsClaimsToAssertion(@Named(JWS_ALG) String alg,\n                                               @Authorization Supplier<PrivateKey> privateKey,\n                                               @Authorization Supplier<CertificateFingerprint> certFingerprint,\n                                               Json json) {\n        this.alg = alg;\n        checkArgument(SUPPORTED_ALGS.contains(alg), \"%s %s not in supported list\", JWS_ALG, alg, SUPPORTED_ALGS);\n        this.privateKey = privateKey;\n        this.certFingerprint = certFingerprint;\n        this.json = json;\n    }\n\n    @Override public String apply(Object input) {\n        String encodedHeader = String.format(\"{\\\"alg\\\":\\\"%s\\\",\\\"typ\\\":\\\"JWT\\\",\\\"x5t\\\":\\\"%s\\\"}\", alg, certFingerprint.get().fingerprint());\n        String encodedClaimSet = json.toJson(input);\n\n        encodedHeader = base64Url().omitPadding().encode(encodedHeader.getBytes(UTF_8));\n        encodedClaimSet = base64Url().omitPadding().encode(encodedClaimSet.getBytes(UTF_8));\n\n        byte[] signature = alg.equals(\"none\")\n                ? null\n                : sha256(privateKey.get(), on(\".\").join(encodedHeader, encodedClaimSet).getBytes(UTF_8));\n        String encodedSignature = signature != null ?  base64Url().omitPadding().encode(signature) : \"\";\n\n        // the final assertion in base 64 encoded {header}.{claimSet}.{signature} format\n        return on(\".\").join(encodedHeader, encodedClaimSet, encodedSignature);\n    }\n\n    static byte[] sha256(PrivateKey privateKey, byte[] input) {\n        try {\n            Signature signature = Signature.getInstance(\"SHA256withRSA\");\n            signature.initSign(privateKey);\n            signature.update(input);\n            return signature.sign();\n        } catch (NoSuchAlgorithmException e) {\n            throw new AssertionError(e);\n        } catch (SignatureException e) {\n            throw new AuthorizationException(e);\n        } catch (InvalidKeyException e) {\n            throw new AuthorizationException(e);\n        }\n    }\n}\n"
  },
  {
    "path": "apis/oauth/src/test/java/org/jclouds/oauth/v2/AuthorizationApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.oauth.v2;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.oauth.v2.OAuthTestUtils.setCredential;\nimport static org.jclouds.oauth.v2.config.OAuthProperties.JWS_ALG;\nimport static org.jclouds.oauth.v2.config.OAuthProperties.RESOURCE;\nimport static org.jclouds.oauth.v2.config.OAuthProperties.AUDIENCE;\nimport static org.jclouds.oauth.v2.config.OAuthProperties.CERTIFICATE;\nimport static org.jclouds.oauth.v2.config.OAuthProperties.CREDENTIAL_TYPE;\nimport static org.jclouds.providers.AnonymousProviderMetadata.forApiOnEndpoint;\nimport static org.jclouds.utils.TestUtils.NO_INVOCATIONS;\nimport static org.jclouds.utils.TestUtils.SINGLE_NO_ARG_INVOCATION;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.Properties;\nimport java.util.UUID;\n\nimport org.jclouds.apis.BaseApiLiveTest;\nimport org.jclouds.oauth.v2.config.CredentialType;\nimport org.jclouds.oauth.v2.config.OAuthModule;\nimport org.jclouds.oauth.v2.config.OAuthScopes;\nimport org.jclouds.oauth.v2.config.OAuthScopes.SingleScope;\nimport org.jclouds.oauth.v2.domain.Claims;\nimport org.jclouds.oauth.v2.domain.ClientCredentialsClaims;\nimport org.jclouds.oauth.v2.domain.Token;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.testng.annotations.DataProvider;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.inject.Binder;\nimport com.google.inject.Module;\nimport com.google.inject.name.Names;\n\n@Test(groups = \"live\", singleThreaded = true)\npublic class AuthorizationApiLiveTest extends BaseApiLiveTest<AuthorizationApi> {\n\n   private final String jwsAlg = \"RS256\";\n   private String scope;\n   private String audience;\n   private String credentialType;\n   private String resource;\n   private String certificate;\n\n   public AuthorizationApiLiveTest() {\n      provider = \"oauth\";\n   }\n\n   @DataProvider\n   public Object[][] onlyRunForP12PrivateKeyCredentials() {\n      return (CredentialType.fromValue(credentialType) == CredentialType.P12_PRIVATE_KEY_CREDENTIALS) ?\n            SINGLE_NO_ARG_INVOCATION : NO_INVOCATIONS;\n   }\n\n   @DataProvider\n   public Object[][] onlyRunForClientCredentialsSecret() {\n      return (CredentialType.fromValue(credentialType) == CredentialType.CLIENT_CREDENTIALS_SECRET) ?\n              SINGLE_NO_ARG_INVOCATION : NO_INVOCATIONS;\n   }\n\n   @DataProvider\n   public Object[][] onlyRunForClientCredentialsP12() {\n      return (CredentialType.fromValue(credentialType) == CredentialType.CLIENT_CREDENTIALS_P12_AND_CERTIFICATE) ?\n              SINGLE_NO_ARG_INVOCATION : NO_INVOCATIONS;\n   }\n\n   @Test(dataProvider = \"onlyRunForP12PrivateKeyCredentials\")\n   public void authenticateP12PrivateKeyCredentialsTest() throws Exception {\n      long now = System.currentTimeMillis() / 1000;\n      Claims claims = Claims.create(\n              identity, // iss\n              scope, // scope\n              audience, // aud\n              now + 3600, // exp\n              now // iat\n      );\n\n      Token token = api.authorize(claims);\n\n      assertNotNull(token, \"no token when authorizing \" + claims);\n   }\n\n   @Test(dataProvider = \"onlyRunForClientCredentialsSecret\")\n   public void authenticateClientCredentialsSecretTest() throws Exception {\n      Token token = api.authorizeClientSecret(identity, credential, resource, scope);\n\n      assertNotNull(token, \"no token when authorizing \" + identity);\n   }\n\n   @Test(dataProvider = \"onlyRunForClientCredentialsSecret\")\n   public void authenticateClientCredentialsSecretNullScopeTest() throws Exception {\n      Token token = api.authorizeClientSecret(identity, credential, resource, null);\n\n      assertNotNull(token, \"no token when authorizing \" + identity);\n   }\n\n   @Test(dataProvider = \"onlyRunForClientCredentialsP12\")\n   public void authenticateClientCredentialsP12Test() throws Exception {\n      long now = System.currentTimeMillis() / 1000;\n      ClientCredentialsClaims claims = ClientCredentialsClaims.create(\n              identity, // iss\n              identity, // sub\n              audience, // aud\n              now + 3600, // exp\n              now, // iat\n              UUID.randomUUID().toString()\n      );\n\n      Token token = api.authorize(identity, claims, resource, null);\n\n      assertNotNull(token, \"no token when authorizing \" + claims);\n   }\n\n   /** OAuth isn't registered as a provider intentionally, so we fake one. */\n   @Override protected ProviderMetadata createProviderMetadata() {\n      return forApiOnEndpoint(AuthorizationApi.class, endpoint).toBuilder().id(\"oauth\").build();\n   }\n\n   @Override protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      props.setProperty(JWS_ALG, jwsAlg);\n\n      // scope is required for P12_PRIVATE_KEY_CREDENTIALS, optional for CLIENT_CREDENTIALS_SECRET.\n      // Moved the not-NULL check to P12_PRIVATE_KEY_CREDENTIALS specific parameters.\n      scope = setIfTestSystemPropertyPresent(props, \"jclouds.oauth.scope\");\n\n      // Determine which type of Credential to use, default to P12_PRIVATE_KEY_CREDENTIALS\n      credentialType = setIfTestSystemPropertyPresent(props, CREDENTIAL_TYPE);\n      if (credentialType == null) {\n         credentialType = CredentialType.P12_PRIVATE_KEY_CREDENTIALS.toString();\n         props.setProperty(CREDENTIAL_TYPE, credentialType);\n      }\n\n      // Set the credential specific properties.\n      if (CredentialType.fromValue(credentialType) == CredentialType.CLIENT_CREDENTIALS_SECRET) {\n         resource = checkNotNull(setIfTestSystemPropertyPresent(props, RESOURCE), \"test.\" + RESOURCE);\n      } else if (CredentialType.fromValue(credentialType) == CredentialType.CLIENT_CREDENTIALS_P12_AND_CERTIFICATE) {\n         audience = checkNotNull(setIfTestSystemPropertyPresent(props, AUDIENCE), \"test.jclouds.oauth.audience\");\n         resource = checkNotNull(setIfTestSystemPropertyPresent(props, RESOURCE), \"test.\" + RESOURCE);\n         certificate = setCredential(props, CERTIFICATE);\n         credential = setCredential(props, \"oauth.credential\");\n      } else if (CredentialType.fromValue(credentialType) == CredentialType.P12_PRIVATE_KEY_CREDENTIALS) {\n         audience = checkNotNull(setIfTestSystemPropertyPresent(props, AUDIENCE), \"test.jclouds.oauth.audience\");\n         credential = setCredential(props, \"oauth.credential\");\n         checkNotNull(scope, \"test.jclouds.oauth.scope\");\n      }\n\n      return props;\n   }\n\n   @Override protected Iterable<Module> setupModules() {\n      return ImmutableList.<Module>builder() //\n            .add(new OAuthModule()) //\n            .add(new Module() {\n               @Override public void configure(Binder binder) {\n                  // ContextBuilder erases oauth.endpoint, as that's the same name as the provider key.\n                  binder.bindConstant().annotatedWith(Names.named(\"oauth.endpoint\")).to(endpoint);\n                  binder.bind(OAuthScopes.class).toInstance(SingleScope.create(scope));\n               }\n            }).addAll(super.setupModules()).build();\n   }\n}\n\n"
  },
  {
    "path": "apis/oauth/src/test/java/org/jclouds/oauth/v2/AuthorizationApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.oauth.v2;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.io.BaseEncoding.base64Url;\nimport static com.google.common.util.concurrent.MoreExecutors.newDirectExecutorService;\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\nimport static org.jclouds.Constants.PROPERTY_MAX_RETRIES;\nimport static org.jclouds.oauth.v2.config.CredentialType.P12_PRIVATE_KEY_CREDENTIALS;\nimport static org.jclouds.oauth.v2.config.CredentialType.CLIENT_CREDENTIALS_SECRET;\nimport static org.jclouds.oauth.v2.config.CredentialType.CLIENT_CREDENTIALS_P12_AND_CERTIFICATE;\nimport static org.jclouds.oauth.v2.config.OAuthProperties.CERTIFICATE;\nimport static org.jclouds.oauth.v2.config.OAuthProperties.AUDIENCE;\nimport static org.jclouds.oauth.v2.config.OAuthProperties.CREDENTIAL_TYPE;\nimport static org.jclouds.oauth.v2.config.OAuthProperties.JWS_ALG;\nimport static org.jclouds.oauth.v2.config.OAuthProperties.RESOURCE;\nimport static org.jclouds.util.Strings2.toStringAndClose;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.fail;\n\nimport java.io.IOException;\nimport java.net.URL;\nimport java.util.Properties;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\nimport okhttp3.mockwebserver.RecordedRequest;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.concurrent.config.ExecutorServiceModule;\nimport org.jclouds.oauth.v2.config.CredentialType;\nimport org.jclouds.oauth.v2.config.OAuthModule;\nimport org.jclouds.oauth.v2.config.OAuthScopes;\nimport org.jclouds.oauth.v2.config.OAuthScopes.SingleScope;\nimport org.jclouds.oauth.v2.domain.Claims;\nimport org.jclouds.oauth.v2.domain.ClientCredentialsClaims;\nimport org.jclouds.oauth.v2.domain.Token;\nimport org.jclouds.rest.AnonymousHttpApiMetadata;\nimport org.jclouds.rest.AuthorizationException;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Joiner;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.io.BaseEncoding;\nimport com.google.inject.Binder;\nimport com.google.inject.Module;\n\n\n@Test(groups = \"unit\", testName = \"OAuthApiMockTest\")\npublic class AuthorizationApiMockTest {\n   private static final String SCOPE = \"https://www.googleapis.com/auth/prediction\";\n\n   private static final String header = \"{\\\"alg\\\":\\\"RS256\\\",\\\"typ\\\":\\\"JWT\\\"}\";\n\n   private static final String claims = \"{\\\"iss\\\":\\\"761326798069-r5mljlln1rd4lrbhg75efgigp36m78j5@developer\"\n         + \".gserviceaccount.com\\\",\\\"scope\\\":\\\"\" + SCOPE + \"\\\",\\\"aud\\\":\\\"https://accounts.google\"\n         + \".com/o/oauth2/token\\\",\\\"exp\\\":1328573381,\\\"iat\\\":1328569781}\";\n\n   private static final Token TOKEN = Token.create(\"1/8xbJqaOZXSUZbHLl5EOtu1pxz3fmmetKx9W8CV4t79M\", \"Bearer\", 3600);\n\n   private static final Claims CLAIMS = Claims.create(\n         \"761326798069-r5mljlln1rd4lrbhg75efgigp36m78j5@developer.gserviceaccount.com\", // iss\n         SCOPE, // scope\n         \"https://accounts.google.com/o/oauth2/token\", // aud\n         1328573381, // exp\n         1328569781 // iat\n         );\n\n   private static final String clientCredentialsHeader = \"{\\\"alg\\\":\\\"RS256\\\",\\\"typ\\\":\\\"JWT\\\",\\\"x5t\\\":\\\"RZk6mx4gGECvF6XWZWkK9qaGdHk=\\\"}\";\n   private static final String clientCredentialsClaims = \"{\\\"iss\\\":\\\"a242b44e-2c2a-3bdd-b094-6152da263c54\\\",\" +\n         \"\\\"sub\\\":\\\"a242b44e-2c2a-3bdd-b094-6152da263c54\\\",\\\"aud\\\":\" +\n         \"\\\"https://login.microsoftonline.com/a242ccee-1a1a-3bdd-b094-6152da263c54/oauth2/token\\\"\" +\n         \",\\\"exp\\\":1328573381,\\\"nbf\\\":1328569781,\\\"jti\\\":\\\"abcdefgh\\\"}\";\n\n   private static final ClientCredentialsClaims CLIENT_CREDENTIALS_CLAIMS = ClientCredentialsClaims.create(\n           \"a242b44e-2c2a-3bdd-b094-6152da263c54\", // iss\n           \"a242b44e-2c2a-3bdd-b094-6152da263c54\", // sub\n           \"https://login.microsoftonline.com/a242ccee-1a1a-3bdd-b094-6152da263c54/oauth2/token\", //aud\n           1328573381, // exp\n           1328569781, // nbf\n           \"abcdefgh\" // jti\n   );\n\n   public void testGenerateJWTRequest() throws Exception {\n      MockWebServer server = new MockWebServer();\n\n      try {\n         server.enqueue(new MockResponse().setBody(\"{\\n\"\n                 + \"  \\\"access_token\\\" : \\\"1/8xbJqaOZXSUZbHLl5EOtu1pxz3fmmetKx9W8CV4t79M\\\",\\n\"\n                 + \"  \\\"token_type\\\" : \\\"Bearer\\\",\\n\" + \"  \\\"expires_in\\\" : 3600\\n\" + \"}\"));\n         server.start();\n\n         AuthorizationApi api = api(server.url(\"/\").url(), P12_PRIVATE_KEY_CREDENTIALS);\n\n         assertEquals(api.authorize(CLAIMS), TOKEN);\n\n         RecordedRequest request = server.takeRequest();\n         assertEquals(request.getMethod(), \"POST\");\n         assertEquals(request.getHeader(\"Accept\"), APPLICATION_JSON);\n         assertEquals(request.getHeader(\"Content-Type\"), \"application/x-www-form-urlencoded\");\n\n         assertEquals(\n                 request.getBody().readUtf8(), //\n                 \"grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&\"\n                         +\n                         // Base64 Encoded Header\n                         \"assertion=\"\n                         + Joiner.on('.').join(encoding.encode(header.getBytes(UTF_8)),\n                         encoding.encode(claims.getBytes(UTF_8)),\n                         // Base64 encoded {header}.{claims} signature (using\n                         // SHA256)\n                         \"W2Lesr_98AzVYiMbzxFqmwcOjpIWlwqkC6pNn1fXND9oSDNNnFhy-AAR6DKH-x9ZmxbY80\"\n                                 + \"R5fH-OCeWumXlVgceKN8Z2SmgQsu8ElTpypQA54j_5j8vUImJ5hsOUYPeyF1U2BUzZ3L5g\"\n                                 + \"03PXBA0YWwRU9E1ChH28dQBYuGiUmYw\"));\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testAuthorizationExceptionIsPopulatedOn4xx() throws Exception {\n      MockWebServer server = new MockWebServer();\n      try {\n         server.enqueue(new MockResponse().setResponseCode(400));\n         server.start();\n\n         AuthorizationApi api = api(server.url(\"/\").url(), P12_PRIVATE_KEY_CREDENTIALS);\n         api.authorize(CLAIMS);\n         fail(\"An AuthorizationException should have been raised\");\n      } catch (AuthorizationException ex) {\n         // Success\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGenerateClientSecretRequest() throws Exception {\n      MockWebServer server = new MockWebServer();\n\n      String credential = \"password\";\n      String identity = \"user\";\n      String resource = \"http://management.azure.com/\";\n      String encoded_resource = \"http%3A//management.azure.com/\";\n\n      try {\n         server.enqueue(new MockResponse().setBody(\"{\\n\"\n                 + \"  \\\"access_token\\\" : \\\"1/8xbJqaOZXSUZbHLl5EOtu1pxz3fmmetKx9W8CV4t79M\\\",\\n\"\n                 + \"  \\\"token_type\\\" : \\\"Bearer\\\",\\n\" + \"  \\\"expires_in\\\" : 3600\\n\" + \"}\"));\n         server.start();\n\n         AuthorizationApi api = api(server.url(\"/\").url(), CLIENT_CREDENTIALS_SECRET);\n\n         assertEquals(api.authorizeClientSecret(identity, credential, resource, null), TOKEN);\n\n         RecordedRequest request = server.takeRequest();\n         assertEquals(request.getMethod(), \"POST\");\n         assertEquals(request.getHeader(\"Accept\"), APPLICATION_JSON);\n         assertEquals(request.getHeader(\"Content-Type\"), \"application/x-www-form-urlencoded\");\n\n         assertEquals(\n                 request.getBody().readUtf8(), //\n                 \"grant_type=client_credentials&client_id=\" + identity\n                         + \"&client_secret=\" + credential\n                         + \"&resource=\" + encoded_resource);\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGenerateClientCredentialsJWTRequest() throws Exception {\n      MockWebServer server = new MockWebServer();\n\n      String identity = \"user\";\n      String resource = \"http://management.azure.com/\";\n      String encoded_resource = \"http%3A//management.azure.com/\";\n\n      try {\n         server.enqueue(new MockResponse().setBody(\"{\\n\"\n                 + \"  \\\"access_token\\\" : \\\"1/8xbJqaOZXSUZbHLl5EOtu1pxz3fmmetKx9W8CV4t79M\\\",\\n\"\n                 + \"  \\\"token_type\\\" : \\\"Bearer\\\",\\n\" + \"  \\\"expires_in\\\" : 3600\\n\" + \"}\"));\n         server.start();\n\n         AuthorizationApi api = api(server.url(\"/\").url(), CLIENT_CREDENTIALS_P12_AND_CERTIFICATE);\n         assertEquals(api.authorize(identity, CLIENT_CREDENTIALS_CLAIMS, resource, null), TOKEN);\n\n         RecordedRequest request = server.takeRequest();\n         assertEquals(request.getMethod(), \"POST\");\n         assertEquals(request.getHeader(\"Accept\"), APPLICATION_JSON);\n         assertEquals(request.getHeader(\"Content-Type\"), \"application/x-www-form-urlencoded\");\n\n         assertEquals(\n                 request.getBody().readUtf8(),\n                 \"grant_type=client_credentials&\" +\n                         \"client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer&\" +\n                         \"client_id=\" + identity + \"&\" +\n                         \"client_assertion=\" +\n                         Joiner.on(\".\").join(encoding.encode(clientCredentialsHeader.getBytes(UTF_8)),\n                                 encoding.encode(clientCredentialsClaims.getBytes(UTF_8)),\n                                 \"ip3i0YLlunb4iq8sUMlpYDKnEuzmvlLpF4NQvn_aiysO5cuT5QHuGREq\" +\n                                         \"gyEa-UMhfZoW49ggUWjS7YBT00r64cFE3dovaNMiZYZuVWu_\" +\n                                         \"FpqO2QlwV7uXqhaRIE0cyabbKG44YJwA-NE4rtFZedFMo94F\" +\n                                         \"6aOz2FN3en8zS9UVqmM\"\n                                 ) + \"&\" +\n                         \"resource=\" + encoded_resource);\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   private final BaseEncoding encoding = base64Url().omitPadding();\n\n   private AuthorizationApi api(URL url, CredentialType credentialType) throws IOException {\n      Properties overrides = new Properties();\n      overrides.setProperty(\"oauth.endpoint\", url.toString());\n      overrides.setProperty(JWS_ALG, \"RS256\");\n      overrides.setProperty(CREDENTIAL_TYPE, credentialType.toString());\n      overrides.setProperty(AUDIENCE, \"https://accounts.google.com/o/oauth2/token\");\n      overrides.setProperty(RESOURCE, \"https://management.azure.com/\");\n      overrides.setProperty(PROPERTY_MAX_RETRIES, \"1\");\n      overrides.setProperty(CERTIFICATE, toStringAndClose(OAuthTestUtils.class.getResourceAsStream(\"/testcert.pem\")));\n\n      return ContextBuilder.newBuilder(AnonymousHttpApiMetadata.forApi(AuthorizationApi.class))\n            .credentials(\"foo\", toStringAndClose(OAuthTestUtils.class.getResourceAsStream(\"/testpk.pem\")))\n            .endpoint(url.toString())\n            .overrides(overrides)\n            .modules(ImmutableSet.of(new ExecutorServiceModule(newDirectExecutorService()), new OAuthModule(), new Module() {\n               @Override public void configure(Binder binder) {\n                  binder.bind(OAuthScopes.class).toInstance(SingleScope.create(SCOPE));\n               }\n            }))\n            .buildApi(AuthorizationApi.class);\n   }\n}\n"
  },
  {
    "path": "apis/oauth/src/test/java/org/jclouds/oauth/v2/OAuthTestUtils.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.oauth.v2;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Throwables.propagate;\nimport static org.jclouds.oauth.v2.config.CredentialType.BEARER_TOKEN_CREDENTIALS;\nimport static org.jclouds.oauth.v2.config.OAuthProperties.AUDIENCE;\nimport static org.jclouds.oauth.v2.config.OAuthProperties.CREDENTIAL_TYPE;\nimport static org.jclouds.util.Strings2.toStringAndClose;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Properties;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.io.Files;\n\npublic class OAuthTestUtils {\n\n   public static Properties defaultProperties(Properties properties) {\n      try {\n         properties = properties == null ? new Properties() : properties;\n         properties.put(\"oauth.identity\", \"foo\");\n         properties.put(\"oauth.credential\", toStringAndClose(OAuthTestUtils.class.getResourceAsStream(\"/testpk.pem\")));\n         properties.put(\"oauth.endpoint\", \"http://localhost:5000/o/oauth2/token\");\n         properties.put(AUDIENCE, \"https://accounts.google.com/o/oauth2/token\");\n         return properties;\n      } catch (IOException e) {\n         throw propagate(e);\n      }\n   }\n\n   public static Properties bearerTokenAuthProperties(Properties properties) {\n      properties = properties == null ? new Properties() : properties;\n      properties.put(\"oauth.identity\", \"761326798069-r5mljlln1rd4lrbhg75efgigp36m78j5@developer.gserviceaccount.com\");\n      properties.put(\"oauth.credential\", \"1/8xbJqaOZXSUZbHLl5EOtu1pxz3fmmetKx9W8CV4t79M\");\n      properties.put(\"oauth.endpoint\", \"http://localhost:5000/o/oauth2/token\");\n      properties.put(AUDIENCE, \"https://accounts.google.com/o/oauth2/token\");\n      properties.put(CREDENTIAL_TYPE, BEARER_TOKEN_CREDENTIALS.toString());\n      return properties;\n   }\n\n   // TODO: move to jclouds-core\n   public static String setCredential(Properties overrides, String key) {\n      String val = null;\n      String credentialFromFile = null;\n      String testKey = \"test.\" + key;\n\n      if (System.getProperties().containsKey(testKey)) {\n         val = System.getProperty(testKey);\n      }\n      checkNotNull(val, \"the property %s must be set (pem private key file path or private key as a string)\", testKey);\n\n      if (val.startsWith(\"-----BEGIN\")) {\n         return val;\n      }\n\n      try {\n         credentialFromFile = Files.toString(new File(val), Charsets.UTF_8);\n      } catch (IOException e) {\n         throw propagate(e);\n      }\n      overrides.setProperty(key, credentialFromFile);\n      return credentialFromFile;\n   }\n\n   public static String getMandatoryProperty(Properties properties, String key) {\n      checkNotNull(properties);\n      checkNotNull(key);\n      String value = properties.getProperty(key);\n      return checkNotNull(value, \"mandatory property %s or test.%s was not present\", key, key);\n   }\n\n}\n"
  },
  {
    "path": "apis/oauth/src/test/java/org/jclouds/oauth/v2/config/PrivateKeySupplierTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.oauth.v2.config;\n\nimport static com.google.common.base.Suppliers.ofInstance;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.io.File;\nimport java.security.PrivateKey;\nimport java.util.Properties;\n\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.oauth.v2.OAuthTestUtils;\nimport org.jclouds.oauth.v2.config.PrivateKeySupplier.PrivateKeyForCredentials;\nimport org.jclouds.rest.AuthorizationException;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.base.Suppliers;\nimport com.google.common.io.Files;\n\n@Test(groups = \"unit\")\npublic class PrivateKeySupplierTest {\n\n   /** Test loading the credentials by extracting a pk from a PKCS12 keystore. */\n   public void testLoadPKString() throws Exception {\n      assertNotNull(loadPrivateKey());\n   }\n\n   @Test(expectedExceptions = AuthorizationException.class)\n   public void testAuthorizationExceptionIsThrownOnBadKeys() {\n      PrivateKeySupplier supplier = new PrivateKeySupplier(\n            Suppliers.ofInstance(new Credentials(\"MOMMA\", \"FileNotFoundCredential\")),\n            new PrivateKeyForCredentials());\n      supplier.get();\n   }\n\n   public void testCredentialsAreLoadedOnRightAlgoAndCredentials() {\n      Properties propertied = OAuthTestUtils.defaultProperties(new Properties());\n      Credentials validCredentials = new Credentials(propertied.getProperty(\"oauth.identity\"),\n              propertied.getProperty(\"oauth.credential\"));\n      PrivateKeySupplier supplier = new PrivateKeySupplier(Suppliers.ofInstance(validCredentials),\n            new PrivateKeyForCredentials());\n      assertNotNull(supplier.get());\n   }\n\n   public static PrivateKey loadPrivateKey() throws Exception {\n      PrivateKeySupplier supplier = new PrivateKeySupplier(ofInstance(new Credentials(\"foo\",\n            Files.asCharSource(new File(\"src/test/resources/testpk.pem\"), Charsets.UTF_8).read())),\n            new PrivateKeyForCredentials());\n      return supplier.get();\n   }\n}\n"
  },
  {
    "path": "apis/oauth/src/test/java/org/jclouds/oauth/v2/filters/TestJWTBearerTokenFlow.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.oauth.v2.filters;\n\nimport static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\n\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.location.Provider;\nimport org.jclouds.oauth.v2.config.OAuthConfigFactory;\n\nimport com.google.common.base.Supplier;\n\npublic class TestJWTBearerTokenFlow extends JWTBearerTokenFlow {\n\n   @Inject TestJWTBearerTokenFlow(AuthorizeToken loader, @Named(PROPERTY_SESSION_INTERVAL) long tokenDuration,\n          @Provider Supplier<Credentials> credentialsSupplier, OAuthConfigFactory oauthConfigFactory) {\n      super(loader, tokenDuration, credentialsSupplier, oauthConfigFactory);\n   }\n\n   /** Constant time for testing. */\n   long currentTimeSeconds() {\n      return 0;\n   }\n}\n"
  },
  {
    "path": "apis/oauth/src/test/java/org/jclouds/oauth/v2/functions/ClaimsToAssertionTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.oauth.v2.functions;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.io.BaseEncoding.base64Url;\nimport static org.jclouds.oauth.v2.config.PrivateKeySupplierTest.loadPrivateKey;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class ClaimsToAssertionTest {\n\n   private static final String PAYLOAD = \"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.\\n\" +\n           \"eyJpc3MiOiI3NjEzMjY3OTgwNjktcjVtbGpsbG4xcmQ0bHJiaGc3NWVmZ2lncDM2bTc4ajVAZ\" +\n           \"GV2ZWxvcGVyLmdzZXJ2aWNlYWNjb3VudC5jb20iLCJzY29wZSI6Imh0dHBzOi8vd3d3Lmdvb2ds\" +\n           \"ZWFwaXMuY29tL2F1dGgvcHJlZGljdGlvbiIsImF1ZCI6Imh0dHBzOi8vYWNjb3VudHMuZ29vZ2x\" +\n           \"lLmNvbS9vL29hdXRoMi90b2tlbiIsImV4cCI6MTMyODU1NDM4NSwiaWF0IjoxMzI4NTUwNzg1fQ\";\n\n   private static final String SHA256withRSA_PAYLOAD_SIGNATURE_RESULT =\n           \"bmQrCv4gjkLWDK1JNJni74_kPiSDUMF_FImgqKJMUIgkDX1m2Sg3bH1yjF-cjBN7CvfAscnageo\" +\n                   \"GtL2TGbwoTjJgUO5Yy0esavUUF-mBQHQtSw-2nL-9TNyM4SNi6fHPbgr83GGKOgA86r\" +\n                   \"I9-nj3oUGd1fQty2k4Lsd-Zdkz6es\";\n\n\n   public void sha256() throws Exception {\n      byte[] payloadSignature = ClaimsToAssertion.sha256(loadPrivateKey(), PAYLOAD.getBytes(UTF_8));\n      assertNotNull(payloadSignature);\n\n      assertEquals(base64Url().omitPadding().encode(payloadSignature), SHA256withRSA_PAYLOAD_SIGNATURE_RESULT);\n   }\n}\n"
  },
  {
    "path": "apis/oauth/src/test/resources/logback.xml",
    "content": "<?xml version=\"1.0\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<configuration scan=\"false\">\n    <appender name=\"FILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <appender name=\"WIREFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds-wire.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n    \n    <root>\n        <level value=\"warn\" />\n    </root>\n\n    <logger name=\"org.jclouds\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"FILE\" />\n    </logger>\n\n    <logger name=\"jclouds.wire\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n\n    <logger name=\"jclouds.headers\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n\n</configuration>\n"
  },
  {
    "path": "apis/oauth/src/test/resources/testcert.pem",
    "content": "-----BEGIN CERTIFICATE-----\nMIIDkTCCAnmgAwIBAgIJAISFMZeicwQVMA0GCSqGSIb3DQEBCwUAMF8xCzAJBgNV\nBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRMwEQYDVQQHDApTYW50YSBDcnV6\nMQ8wDQYDVQQKDAZKQ1Rlc3QxFTATBgNVBAMMDGpjdGVzdHNwY2VydDAeFw0xNjA1\nMTQxNzUzMzFaFw0yNjA1MTIxNzUzMzFaMF8xCzAJBgNVBAYTAlVTMRMwEQYDVQQI\nDApDYWxpZm9ybmlhMRMwEQYDVQQHDApTYW50YSBDcnV6MQ8wDQYDVQQKDAZKQ1Rl\nc3QxFTATBgNVBAMMDGpjdGVzdHNwY2VydDCCASIwDQYJKoZIhvcNAQEBBQADggEP\nADCCAQoCggEBALKkugQxFZq224O2Hb1Q+J8VyXs+fjbwGSErhyY0ynENvCaq2trG\nMia0NAqtRZmG5Fn3KEYo9yCjjm0N34mer5u8X8aErvBa1LTkwrK2dQQ1oXGtbFn1\ndTqho00YwxzMxT3raDw9xXhexloDQbr/EAm4f1zu+05BSC3xSDVvvzARBPSseVfw\ngxWpS4M4aQp9M6Tv2ENYnecfl6StkaPdxaguJeVdpSoBe7piEEz1f2LEoC3Fw6De\nJIUgzQyVoffCWCA+RCf3o8GOqce0+INW50rcEv1JrGrDSUeEUYDCg+FniT9vKBsm\nsV8u3o1YxvtWmAY3KtXC7akwqHSdifecLtECAwEAAaNQME4wHQYDVR0OBBYEFL2W\n1+sMin4FbE9RFQr6FqEh9NFUMB8GA1UdIwQYMBaAFL2W1+sMin4FbE9RFQr6FqEh\n9NFUMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBADaHB0PbSooF1PkD\n2KwwYck7cm9C0jmnUVdcmJ6GrG8OdXEP14E4rUzrstFK0XSPHYoBH0p0xMISutHD\nRVLgsxXbnPhXVKaTuDspgedSAaHPFQJNEtMHHCNaSS2Vyh+2Ha9HLD7dsy+9QBKf\nEt4MMLXT/n4WVzKJcweWI/T8oIIbfHzPTo+jWYfTxxKJcL+C/GY2QREkKs+5mR2t\nN4q69ydcjeajB9F8XPbJlTDen+6ofwtQ45tS5w5EjV3SvOh4QOEVz1su9F5Ojw7Q\noPuUKMynxeo2E6FsiNj5m+8NPLKiX2phnKMogbJyOhligj1QRR+zBc/62aPCP6Z4\n2pWp7Lc=\n-----END CERTIFICATE-----\n"
  },
  {
    "path": "apis/oauth/src/test/resources/testpk.pem",
    "content": "-----BEGIN RSA PRIVATE KEY-----\nMIICXgIBAAKBgQCwqwzakEPP+U9vx9JCuMHebFIVQZ4Sjaj2RU9dJ6YT2s3u7dC6\n/0fGM5xm4fXmSHqyGC6PC8weQSkxnSpbU+R4jMWPM8ML4TIr5wP0avbg+wy3+WWI\nof0MN7YHkCfqpaaiKiMw7niK1y07YvxJN8LX1xLpE7aXgIpn6L/qtJdHnQIDAQAB\nAoGBAIAHlcsW3W3smPrC7sdXqXeNPHcXFH0RmC7Qz9EMmLiuyqqqQagitFsYr/GH\nM3Ltd611BNi5jfUm97ly0m1ZAKp/nkTMVhfKfRIVsBDHtjQHcUOR9tr0LslptmaN\nTG0bovbUohe5KwOqMK4YOjUQbInChVBrf7VrNQtv8e0eShdpAkEA3lzLP9QYfP1i\nC4iYXqS7cgMDrs3qujC7PoyB54maen+Uvgyau1ZJpKMzXYkORPcYk+b71bl9jF80\nU+7LDnJjPwJBAMtksvL1V8DC5DYL43497JW4KBN4YZ3K7YWx/9gkvc3Q9VdXiUGu\n6WKjmcbmsPI/jFdeO71uy934N8qEXLJcyiMCQQCTNKcxWD3l8PCJZiJI9ZFKBwjX\nHmb4X+51mBsfpw7nbbKQplOBFbynC4ujrmoN6e8RaubpNGUTGqvPrNQsejmNAkEA\nlUDEAH4BczaQ+QgoXI9ceVG2NvNzzrMHMcC5Ggd8MPhR0VIvKsAMC5I6WjcXSe1Q\nMxy3gf84Ix7u8fHHhCuLOQJAQRhrlXiQUk4cJumNhjza5/+KtaV4FPbEQi+qcWE6\ntGoHPEBfbXyUdcUD4ae8X1W0yri0BuyVNaOCpGCBRIhPZA==\n-----END RSA PRIVATE KEY-----\n"
  },
  {
    "path": "apis/openstack-cinder/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.openstack.cinder.v1.*;version=\"${project.version}\";-noimport:=true"
  },
  {
    "path": "apis/openstack-cinder/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.api</groupId>\n  <artifactId>openstack-cinder</artifactId>\n  <name>jclouds openstack-cinder api</name>\n  <description>jclouds components to access an implementation of OpenStack Cinder</description>\n\n  <properties>\n    <!-- keystone endpoint -->\n    <test.openstack-cinder.endpoint>http://localhost:5000/v2.0/</test.openstack-cinder.endpoint>\n    <!-- keystone version -->\n    <test.openstack-cinder.api-version>1</test.openstack-cinder.api-version>\n    <test.openstack-cinder.build-version />\n    <test.openstack-cinder.identity>FIXME_IDENTITY</test.openstack-cinder.identity>\n    <test.openstack-cinder.credential>FIXME_CREDENTIALS</test.openstack-cinder.credential>\n    <test.jclouds.keystone.credential-type>passwordCredentials</test.jclouds.keystone.credential-type>\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-keystone</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-keystone</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-slf4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>ch.qos.logback</groupId>\n      <artifactId>logback-classic</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.openstack-cinder.endpoint>${test.openstack-cinder.endpoint}</test.openstack-cinder.endpoint>\n                    <test.openstack-cinder.api-version>${test.openstack-cinder.api-version}</test.openstack-cinder.api-version>\n                    <test.openstack-cinder.build-version>${test.openstack-cinder.build-version}</test.openstack-cinder.build-version>\n                    <test.openstack-cinder.identity>${test.openstack-cinder.identity}</test.openstack-cinder.identity>\n                    <test.openstack-cinder.credential>${test.openstack-cinder.credential}</test.openstack-cinder.credential>\n                    <test.jclouds.keystone.credential-type>${test.jclouds.keystone.credential-type}</test.jclouds.keystone.credential-type>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n"
  },
  {
    "path": "apis/openstack-cinder/src/main/java/org/jclouds/openstack/cinder/v1/CinderApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.cinder.v1;\n\nimport java.io.Closeable;\nimport java.util.Set;\n\nimport org.jclouds.location.Region;\nimport org.jclouds.location.functions.RegionToEndpoint;\nimport org.jclouds.openstack.cinder.v1.domain.Snapshot;\nimport org.jclouds.openstack.cinder.v1.domain.Volume;\nimport org.jclouds.openstack.cinder.v1.domain.VolumeType;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.cinder.v1.extensions.AvailabilityZoneApi;\nimport org.jclouds.openstack.cinder.v1.features.QuotaApi;\nimport org.jclouds.openstack.cinder.v1.features.SnapshotApi;\nimport org.jclouds.openstack.cinder.v1.features.VolumeApi;\nimport org.jclouds.openstack.cinder.v1.features.VolumeTypeApi;\nimport org.jclouds.openstack.v2_0.features.ExtensionApi;\nimport org.jclouds.openstack.v2_0.services.Extension;\nimport org.jclouds.rest.annotations.Delegate;\nimport org.jclouds.rest.annotations.EndpointParam;\n\nimport com.google.inject.Provides;\n\n/**\n * Provides access to OpenStack Block Storage (Cinder) v1 API.\n */\npublic interface CinderApi extends Closeable {\n\n   /**\n    * @return the Region codes configured\n    */\n   @Provides\n   @Region\n   Set<String> getConfiguredRegions();\n\n   /**\n    * Provides access to {@link Extension} features.\n    */\n   @Delegate\n   ExtensionApi getExtensionApi(@EndpointParam(parser = RegionToEndpoint.class) String region);\n\n   /**\n    * Provides access to {@link Volume} features.\n    */\n   @Delegate\n   VolumeApi getVolumeApi(@EndpointParam(parser = RegionToEndpoint.class) String region);\n\n   /**\n    * Provides access to {@link VolumeType} features.\n    */\n   @Delegate\n   VolumeTypeApi getVolumeTypeApi(@EndpointParam(parser = RegionToEndpoint.class) String region);\n\n   /**\n    * Provides access to {@link Snapshot} features.\n    */\n   @Delegate\n   SnapshotApi getSnapshotApi(@EndpointParam(parser = RegionToEndpoint.class) String region);\n\n   /**\n    * Provides access to quota features.\n    */\n   @Delegate\n   QuotaApi getQuotaApi(@EndpointParam(parser = RegionToEndpoint.class) String region);\n\n   /**\n    * Provides access to Availability Zone features\n    */\n   @Delegate\n   AvailabilityZoneApi getAvailabilityZoneApi(\n         @EndpointParam(parser = RegionToEndpoint.class) @Nullable String region);\n\n   /**\n    * @return the Zone codes configured\n    * @deprecated Please use {@link #getConfiguredRegions()} instead. To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   @Provides\n   @Region\n   Set<String> getConfiguredZones();\n\n   /**\n    * Provides access to Extension features.\n    * @deprecated Please use {@link #getExtensionApi(String region)} instead. To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   @Delegate\n   ExtensionApi getExtensionApiForZone(\n         @EndpointParam(parser = RegionToEndpoint.class) String zone);\n\n   /**\n    * Provides access to Volume features.\n    * @deprecated Please use {@link #getVolumeApi(String region)} instead. To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   @Delegate\n   VolumeApi getVolumeApiForZone(\n         @EndpointParam(parser = RegionToEndpoint.class) String zone);\n\n   /**\n    * Provides access to VolumeType features.\n    * @deprecated Please use {@link #getVolumeTypeApi(String region)} instead. To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   @Delegate\n   VolumeTypeApi getVolumeTypeApiForZone(\n         @EndpointParam(parser = RegionToEndpoint.class) String zone);\n\n   /**\n    * Provides access to Snapshot features.\n    * @deprecated Please use {@link #getSnapshotApi(String)} instead. To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   @Delegate\n   SnapshotApi getSnapshotApiForZone(\n         @EndpointParam(parser = RegionToEndpoint.class) String zone);\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/main/java/org/jclouds/openstack/cinder/v1/CinderApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.cinder.v1;\n\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.CREDENTIAL_TYPE;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.SERVICE_TYPE;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.openstack.cinder.v1.config.CinderHttpApiModule;\nimport org.jclouds.openstack.cinder.v1.config.CinderParserModule;\nimport org.jclouds.openstack.keystone.auth.config.AuthenticationModule;\nimport org.jclouds.openstack.keystone.auth.config.CredentialTypes;\nimport org.jclouds.openstack.keystone.catalog.config.ServiceCatalogModule;\nimport org.jclouds.openstack.keystone.catalog.config.ServiceCatalogModule.RegionModule;\nimport org.jclouds.openstack.keystone.config.KeystoneProperties;\nimport org.jclouds.openstack.v2_0.ServiceType;\nimport org.jclouds.rest.internal.BaseHttpApiMetadata;\n\nimport com.google.auto.service.AutoService;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n/**\n * Implementation of {@link ApiMetadata} for Cinder v1 API\n */\n@AutoService(ApiMetadata.class)\npublic class CinderApiMetadata extends BaseHttpApiMetadata<CinderApi> {\n\n   @Override\n   public Builder toBuilder() {\n      return new Builder().fromApiMetadata(this);\n   }\n\n   public CinderApiMetadata() {\n      this(new Builder());\n   }\n\n   protected CinderApiMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = BaseHttpApiMetadata.defaultProperties();\n      properties.setProperty(SERVICE_TYPE, ServiceType.BLOCK_STORAGE);\n      properties.setProperty(KeystoneProperties.KEYSTONE_VERSION, \"2\");\n      properties.setProperty(CREDENTIAL_TYPE, CredentialTypes.PASSWORD_CREDENTIALS);\n      return properties;\n   }\n\n   public static class Builder extends BaseHttpApiMetadata.Builder<CinderApi, Builder> {\n\n      protected Builder() {\n          id(\"openstack-cinder\")\n         .name(\"OpenStack Cinder Folsom API\")\n         .identityName(\"${tenantName}:${userName} or ${userName}, if your keystone supports a default tenant\")\n         .credentialName(\"${password}\")\n         .endpointName(\"Keystone base URL ending in /v2.0/\")\n         .documentation(URI.create(\"http://api.openstack.org/\"))\n         .version(\"1\")\n         .defaultEndpoint(\"http://localhost:5000/v2.0/\")\n         .defaultProperties(CinderApiMetadata.defaultProperties())\n         .defaultModules(ImmutableSet.<Class<? extends Module>>builder()\n                                     .add(AuthenticationModule.class)\n                                     .add(ServiceCatalogModule.class)\n                                     .add(RegionModule.class)\n                                     .add(CinderParserModule.class)\n                                     .add(CinderHttpApiModule.class)\n                                     .build());\n      }\n\n      @Override\n      public CinderApiMetadata build() {\n         return new CinderApiMetadata(this);\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/main/java/org/jclouds/openstack/cinder/v1/config/CinderHttpApiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.cinder.v1.config;\n\nimport java.net.URI;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.annotation.ClientError;\nimport org.jclouds.http.annotation.Redirection;\nimport org.jclouds.http.annotation.ServerError;\nimport org.jclouds.json.config.GsonModule.DateAdapter;\nimport org.jclouds.json.config.GsonModule.Iso8601DateAdapter;\nimport org.jclouds.openstack.cinder.v1.CinderApi;\nimport org.jclouds.openstack.cinder.v1.handlers.CinderErrorHandler;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.config.HttpApiModule;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.Multimap;\nimport com.google.inject.Provides;\n\n/**\n * Configures the Cinder connection.\n */\n@ConfiguresHttpApi\npublic class CinderHttpApiModule extends HttpApiModule<CinderApi> {\n\n   @Override\n   protected void configure() {\n      bind(DateAdapter.class).to(Iso8601DateAdapter.class);\n      super.configure();\n   }\n   \n   @Provides\n   @Singleton\n   public final Multimap<URI, URI> aliases() {\n      return ImmutableMultimap.<URI, URI>builder().build();\n   }\n\n   @Override\n   protected void bindErrorHandlers() {\n      bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(CinderErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(CinderErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(CinderErrorHandler.class);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/main/java/org/jclouds/openstack/cinder/v1/config/CinderParserModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.cinder.v1.config;\n\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.gson.JsonDeserializationContext;\nimport com.google.gson.JsonDeserializer;\nimport com.google.gson.JsonElement;\nimport com.google.gson.JsonParseException;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Provides;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.json.config.GsonModule.DateAdapter;\nimport org.jclouds.openstack.cinder.v1.domain.Snapshot;\nimport org.jclouds.openstack.cinder.v1.domain.SnapshotExtendedAttributes;\nimport org.jclouds.openstack.cinder.v1.domain.Volume;\n\nimport jakarta.inject.Singleton;\nimport java.beans.ConstructorProperties;\nimport java.lang.reflect.Type;\nimport java.util.Date;\nimport java.util.Map;\n\npublic class CinderParserModule extends AbstractModule {\n\n   @Provides\n   @Singleton\n   public final Map<Type, Object> provideCustomAdapterBindings() {\n      return ImmutableMap.<Type, Object>of(\n            Snapshot.class, new SnapshotAdapter()\n      );\n   }\n\n   @Override\n   protected void configure() {\n      bind(DateAdapter.class).to(GsonModule.Iso8601DateAdapter.class);\n   }\n\n   @Singleton\n   public static class SnapshotAdapter implements JsonDeserializer<Snapshot> {\n      @Override\n      public Snapshot deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context)\n            throws JsonParseException {\n         Snapshot snapshotBase;\n\n         snapshotBase = apply((SnapshotInternal) context.deserialize(jsonElement, SnapshotInternal.class));\n\n         Snapshot.Builder result = Snapshot.builder().fromSnapshot(snapshotBase);\n         SnapshotExtendedAttributes extendedAttributes = context.deserialize(jsonElement, SnapshotExtendedAttributes.class);\n         if (!Objects.equal(extendedAttributes, SnapshotExtendedAttributes.builder().build())) {\n            result.extendedAttributes(extendedAttributes);\n         }\n         return result.build();\n      }\n\n      public Snapshot apply(Snapshot in) {\n         return in.toBuilder().build();\n      }\n\n      private static class SnapshotInternal extends Snapshot {\n         @ConstructorProperties({\"id\", \"volume_id\", \"status\", \"size\", \"created_at\", \"display_name\", \"display_description\", \"extendedAttributes\"})\n         protected SnapshotInternal(String id, String volumeId, Volume.Status status, int size, @Nullable Date created, @Nullable String name, @Nullable String description, @Nullable SnapshotExtendedAttributes extendedAttributes) {\n            super(id, volumeId, status, size, created, name, description, extendedAttributes);\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/main/java/org/jclouds/openstack/cinder/v1/domain/AvailabilityZone.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.cinder.v1.domain;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport java.beans.ConstructorProperties;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\n/**\n * availability zone for cinder\n */\npublic class AvailabilityZone {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return new Builder().fromAvailabilityZone(this);\n   }\n\n   public static class Builder {\n\n      protected boolean available;\n      protected String name;\n\n      /**\n       * @see AvailabilityZone#getName()\n       */\n      public Builder name(String name) {\n         this.name = name;\n         return this;\n      }\n\n      /**\n       * @see AvailabilityZone#getZoneState()\n       */\n      public Builder available(boolean available) {\n         this.available = available;\n         return this;\n      }\n\n\n      public AvailabilityZone build() {\n         return new AvailabilityZone(name, new ZoneState(available));\n      }\n\n      public Builder fromAvailabilityZone(AvailabilityZone in) {\n         return this\n               .name(in.getName())\n               .available(in.getZoneState().available());\n      }\n   }\n\n   private final String name;\n   private final ZoneState state;\n\n   @ConstructorProperties({\"zoneName\", \"zoneState\"})\n   protected AvailabilityZone(String name, ZoneState zoneState) {\n      this.name = checkNotNull(name);\n      this.state = checkNotNull(zoneState);\n   }\n\n   public String getName() {\n      return this.name;\n   }\n\n   public ZoneState getZoneState() {\n      return this.state;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(name, state);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      AvailabilityZone that = AvailabilityZone.class.cast(obj);\n      return Objects.equal(this.name, that.name) && Objects.equal(this.state, that.state);\n   }\n\n   protected MoreObjects.ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"name\", name)\n            .add(\"state\", state);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/main/java/org/jclouds/openstack/cinder/v1/domain/Snapshot.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.cinder.v1.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\n\nimport jakarta.inject.Named;\n\nimport com.google.common.base.Optional;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * An Openstack Cinder Volume Snapshot.\n */\npublic class Snapshot {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n   \n   public Builder toBuilder() {\n      return new Builder().fromSnapshot(this);\n   }\n\n   public static class Builder {\n\n      protected String id;\n      protected String volumeId;\n      protected Volume.Status status;\n      protected int size;\n      protected Date created;\n      protected String name;\n      protected String description;\n      protected SnapshotExtendedAttributes extendedAttributes;\n   \n      /** \n       * @see Snapshot#getId()\n       */\n      public Builder id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /** \n       * @see Snapshot#getVolumeId()\n       */\n      public Builder volumeId(String volumeId) {\n         this.volumeId = volumeId;\n         return self();\n      }\n\n      /** \n       * @see Snapshot#getStatus()\n       */\n      public Builder status(Volume.Status status) {\n         this.status = status;\n         return self();\n      }\n\n      /** \n       * @see Snapshot#getSize()\n       */\n      public Builder size(int size) {\n         this.size = size;\n         return self();\n      }\n\n      /** \n       * @see Snapshot#getCreated()\n       */\n      public Builder created(Date created) {\n         this.created = created;\n         return self();\n      }\n\n      /** \n       * @see Snapshot#getName()\n       */\n      public Builder name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /** \n       * @see Snapshot#getDescription()\n       */\n      public Builder description(String description) {\n         this.description = description;\n         return self();\n      }\n\n      /**\n       * @see Snapshot#getExtendedAttributes()\n       */\n      public Builder extendedAttributes(SnapshotExtendedAttributes extendedAttributes) {\n         this.extendedAttributes = extendedAttributes;\n         return self();\n      }\n\n      public Snapshot build() {\n         return new Snapshot(id, volumeId, status, size, created, name, description, extendedAttributes);\n      }\n      \n      public Builder fromSnapshot(Snapshot in) {\n         return this\n                  .id(in.getId())\n                  .volumeId(in.getVolumeId())\n                  .status(in.getStatus())\n                  .size(in.getSize())\n                  .created(in.getCreated())\n                  .name(in.getName())\n                  .description(in.getDescription())\n                  .extendedAttributes(in.getExtendedAttributes().orNull());\n      }\n\n      protected Builder self() {\n         return this;\n      }\n   }\n\n\n   private final String id;\n   @Named(\"volume_id\")\n   private final String volumeId;\n   private final Volume.Status status;\n   private final int size;\n   @Named(\"created_at\")\n   private final Date created;\n   @Named(\"display_name\")\n   private final String name;\n   @Named(\"display_description\")\n   private final String description;\n   private final Optional<SnapshotExtendedAttributes> extendedAttributes;\n\n   @ConstructorProperties({\"id\", \"volume_id\", \"status\", \"size\", \"created_at\", \"display_name\", \"display_description\", \"extendedAttributes\"})\n   protected Snapshot(String id, String volumeId, Volume.Status status, int size, @Nullable Date created, @Nullable String name, @Nullable String description, @Nullable SnapshotExtendedAttributes extendedAttributes) {\n      this.id = checkNotNull(id, \"id\");\n      this.volumeId = checkNotNull(volumeId, \"volumeId\");\n      this.status = checkNotNull(status, \"status\");\n      this.size = size;\n      this.created = created;\n      this.name = name;\n      this.description = description;\n      this.extendedAttributes = Optional.fromNullable(extendedAttributes);\n   }\n\n   /**\n    * @return The id of this snapshot\n    */\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * @return The id of the Volume this snapshot was taken from\n    */\n   public String getVolumeId() {\n      return this.volumeId;\n   }\n\n   /**\n    * @return The status of this snapshot\n    */\n   public Volume.Status getStatus() {\n      return this.status;\n   }\n\n   /**\n    * @return The size in GB of the volume this snapshot was taken from\n    */\n   public int getSize() {\n      return this.size;\n   }\n\n   /**\n    * @return The data the snapshot was taken\n    */\n   @Nullable\n   public Date getCreated() {\n      return this.created;\n   }\n\n   /**\n    * @return The name of this snapshot - as displayed in the openstack console\n    */\n   @Nullable\n   public String getName() {\n      return this.name;\n   }\n\n   /**\n    * @return The description of this snapshot - as displayed in the openstack console\n    */\n   @Nullable\n   public String getDescription() {\n      return this.description;\n   }\n\n   /**\n    * @return Extended attributes for this snapshot. Only present when the\n    *         {@code os-extended-snapshot-attributes} extension is installed\n    */\n   @Nullable\n   public Optional<SnapshotExtendedAttributes> getExtendedAttributes() {\n      return this.extendedAttributes;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, volumeId, status, size, created, name, description, extendedAttributes);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Snapshot that = Snapshot.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n               && Objects.equal(this.volumeId, that.volumeId)\n               && Objects.equal(this.status, that.status)\n               && Objects.equal(this.size, that.size)\n               && Objects.equal(this.created, that.created)\n               && Objects.equal(this.name, that.name)\n               && Objects.equal(this.description, that.description)\n               && Objects.equal(this.extendedAttributes, that.extendedAttributes);\n   }\n   \n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"volumeId\", volumeId).add(\"status\", status).add(\"size\", size).add(\"created\", created).add(\"name\", name).add(\"description\", description).add(\"extendedAttributes\", extendedAttributes);\n   }\n   \n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/main/java/org/jclouds/openstack/cinder/v1/domain/SnapshotExtendedAttributes.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.openstack.cinder.v1.domain;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport jakarta.inject.Named;\nimport java.beans.ConstructorProperties;\n\n/**\n * Additional attributes delivered by Extended Snapshot Attributes extensions\n */\npublic class SnapshotExtendedAttributes {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return new Builder().fromExtendedAttributes(this);\n   }\n\n   public static class Builder {\n\n      protected String projectId;\n      protected String progress;\n\n      /**\n       * @see SnapshotExtendedAttributes#getProjectId()\n       */\n      public Builder projectId(String projectId) {\n         this.projectId = projectId;\n         return self();\n      }\n\n      /**\n       * @see SnapshotExtendedAttributes#getProgress()\n       */\n      public Builder progress(String progress) {\n         this.progress = progress;\n         return self();\n      }\n\n      public SnapshotExtendedAttributes build() {\n         return new SnapshotExtendedAttributes(projectId, progress);\n      }\n\n      public Builder fromExtendedAttributes(SnapshotExtendedAttributes in) {\n         return this\n               .projectId(in.getProjectId())\n               .progress(in.getProgress());\n      }\n\n      protected Builder self() {\n         return this;\n      }\n   }\n\n   @Named(\"os-extended-snapshot-attributes:project_id\")\n   private final String projectId;\n   private final String progress;\n\n   @ConstructorProperties({\"os-extended-snapshot-attributes:project_id\", \"os-extended-snapshot-attributes:progress\"})\n   protected SnapshotExtendedAttributes(@Nullable String projectId, @Nullable String progress) {\n      this.projectId = projectId;\n      this.progress = progress;\n   }\n\n   /**\n    * @return the project id of this snapshot\n    */\n   @Nullable\n   public String getProjectId() {\n      return this.projectId;\n   }\n\n   /**\n    * @return the progress of this snapshot\n    */\n   @Nullable\n   public String getProgress() {\n      return this.progress;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(projectId, progress);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      SnapshotExtendedAttributes that = SnapshotExtendedAttributes.class.cast(obj);\n      return Objects.equal(this.projectId, that.projectId)\n            && Objects.equal(this.progress, that.progress);\n   }\n\n   protected MoreObjects.ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"projectId\", projectId).add(\"progress\", progress);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/main/java/org/jclouds/openstack/cinder/v1/domain/Volume.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.cinder.v1.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.CaseFormat;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * An Openstack Cinder Volume.\n */\npublic class Volume {\n\n   public static enum Status {\n      CREATING, AVAILABLE, ATTACHING, IN_USE, DELETING, ERROR, ERROR_DELETING, UNRECOGNIZED;\n      \n      public String value() {\n         return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_HYPHEN, name());\n      }\n      \n      @Override\n      public String toString() {\n         return value();\n      }\n      \n      public static Status fromValue(String status) {\n         try {\n            return valueOf(CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_UNDERSCORE, checkNotNull(status, \"status\")));\n         } \n         catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n   \n   public Builder toBuilder() {\n      return new Builder().fromVolume(this);\n   }\n\n   public static class Builder {\n\n      protected String id;\n      protected Volume.Status status;\n      protected int size;\n      protected String zone;\n      protected Date created;\n      protected Set<VolumeAttachment> attachments = ImmutableSet.of();\n      protected String volumeType;\n      protected String snapshotId;\n      protected String name;\n      protected String description;\n      protected Map<String, String> metadata = ImmutableMap.of();\n      protected String tenantId;\n   \n      /**\n       * @see Volume#getId()\n       */\n      public Builder id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /** \n       * @see Volume#getStatus()\n       */\n      public Builder status(Volume.Status status) {\n         this.status = status;\n         return self();\n      }\n\n      /** \n       * @see Volume#getSize()\n       */\n      public Builder size(int size) {\n         this.size = size;\n         return self();\n      }\n\n      /** \n       * @see Volume#getZone()\n       */\n      public Builder zone(String zone) {\n         this.zone = zone;\n         return self();\n      }\n\n      /** \n       * @see Volume#getCreated()\n       */\n      public Builder created(Date created) {\n         this.created = created;\n         return self();\n      }\n\n      /** \n       * @see Volume#getAttachments()\n       */\n      public Builder attachments(Set<VolumeAttachment> attachments) {\n         this.attachments = ImmutableSet.copyOf(checkNotNull(attachments, \"attachments\"));      \n         return self();\n      }\n\n      public Builder attachments(VolumeAttachment... in) {\n         return attachments(ImmutableSet.copyOf(in));\n      }\n\n      /** \n       * @see Volume#getVolumeType()\n       */\n      public Builder volumeType(String volumeType) {\n         this.volumeType = volumeType;\n         return self();\n      }\n\n      /** \n       * @see Volume#getSnapshotId()\n       */\n      public Builder snapshotId(String snapshotId) {\n         this.snapshotId = snapshotId;\n         return self();\n      }\n\n      /** \n       * @see Volume#getName()\n       */\n      public Builder name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /** \n       * @see Volume#getDescription()\n       */\n      public Builder description(String description) {\n         this.description = description;\n         return self();\n      }\n\n      /** \n       * @see Volume#getMetadata()\n       */\n      public Builder metadata(Map<String, String> metadata) {\n         this.metadata = ImmutableMap.copyOf(checkNotNull(metadata, \"metadata\"));     \n         return self();\n      }\n\n      /**\n       * @see Volume#getTenantId()\n       */\n      public Builder tenantId(String tenantId) {\n         this.tenantId = tenantId;\n         return self();\n      }\n\n      public Volume build() {\n         return new Volume(id, status, size, zone, created, attachments, volumeType, snapshotId, name, description, metadata, tenantId);\n      }\n      \n      public Builder fromVolume(Volume in) {\n         return this\n                  .id(in.getId())\n                  .status(in.getStatus())\n                  .size(in.getSize())\n                  .zone(in.getZone())\n                  .created(in.getCreated())\n                  .attachments(in.getAttachments())\n                  .volumeType(in.getVolumeType())\n                  .snapshotId(in.getSnapshotId())\n                  .name(in.getName())\n                  .description(in.getDescription())\n                  .metadata(in.getMetadata())\n                  .tenantId(in.getTenantId());\n      }\n\n      protected Builder self() {\n         return this;\n      }\n   }\n\n   /**\n    * Creates a dummy Volume when you need a Volume with just the volumeId. \n    * Several fields must be set in the returned Volume:\n    * \n    * 1. status=Status.UNRECOGNIZED\n    * 2. zone=\"nova\"\n    * 3. created=[The Date the method was called]\n    */\n   public static Volume forId(String volumeId) {\n      return builder().id(volumeId).status(Status.UNRECOGNIZED).zone(\"nova\").created(new Date()).build();\n   }\n\n   private final String id;\n   private final Volume.Status status;\n   private final int size;\n   @Named(\"availability_zone\")\n   private final String zone;\n   @Named(\"created_at\")\n   private final Date created;\n   private final Set<VolumeAttachment> attachments;\n   @Named(\"volume_type\")\n   private final String volumeType;\n   @Named(\"snapshot_id\")\n   private final String snapshotId;\n   @Named(\"display_name\")\n   private final String name;\n   @Named(\"display_description\")\n   private final String description;\n   private final Map<String, String> metadata;\n   @Named(\"os-vol-tenant-attr:tenant_id\")\n   private final String tenantId;\n\n   @ConstructorProperties({\"id\", \"status\", \"size\", \"availability_zone\", \"created_at\", \"attachments\", \"volume_type\", \"snapshot_id\", \"display_name\", \"display_description\", \"metadata\", \"os-vol-tenant-attr:tenant_id\"})\n   protected Volume(String id, Volume.Status status, int size, String zone, Date created, @Nullable Set<VolumeAttachment> attachments, @Nullable String volumeType, @Nullable String snapshotId, @Nullable String name, @Nullable String description, @Nullable Map<String, String> metadata, @Nullable String tenantId) {\n      this.id = checkNotNull(id, \"id\");\n      this.status = checkNotNull(status, \"status\");\n      this.size = size;\n      this.zone = zone;\n      this.created = checkNotNull(created, \"created\");\n      this.attachments = attachments == null ? ImmutableSet.<VolumeAttachment>of() : ImmutableSet.copyOf(attachments);      \n      this.volumeType = volumeType;\n      this.snapshotId = snapshotId;\n      this.name = name;\n      this.description = description;\n      this.metadata = metadata == null ? ImmutableMap.<String, String>of() : ImmutableMap.copyOf(metadata);\n      this.tenantId = tenantId;\n   }\n\n   /**\n    * @return the id of this volume\n    */\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * @return the status of this volume\n    */\n   public Volume.Status getStatus() {\n      return this.status;\n   }\n\n   /**\n    * @return the size in GB of this volume\n    */\n   public int getSize() {\n      return this.size;\n   }\n\n   /**\n    * @return the availabilityZone containing this volume\n    */\n   @Nullable\n   public String getZone() {\n      return this.zone;\n   }\n\n   /**\n    * @return the time this volume was created\n    */\n   public Date getCreated() {\n      return this.created;\n   }\n\n   /**\n    * @return the set of attachments (to Servers)\n    */\n   public Set<VolumeAttachment> getAttachments() {\n      return this.attachments;\n   }\n\n   /**\n    * @return the type of this volume\n    */\n   @Nullable\n   public String getVolumeType() {\n      return this.volumeType;\n   }\n\n   @Nullable\n   public String getSnapshotId() {\n      return this.snapshotId;\n   }\n\n   /**\n    * @return the name of this volume - as displayed in the openstack console\n    */\n   @Nullable\n   public String getName() {\n      return this.name;\n   }\n\n   /**\n    * @return the description of this volume - as displayed in the openstack console\n    */\n   @Nullable\n   public String getDescription() {\n      return this.description;\n   }\n\n   public Map<String, String> getMetadata() {\n      return this.metadata;\n   }\n\n   /**\n    * @return the tenant id of this volume\n    */\n   @Nullable\n   public String getTenantId() {\n      return this.tenantId;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, status, size, zone, created, attachments, volumeType, snapshotId, name, description, metadata, tenantId);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Volume that = Volume.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n               && Objects.equal(this.status, that.status)\n               && Objects.equal(this.size, that.size)\n               && Objects.equal(this.zone, that.zone)\n               && Objects.equal(this.created, that.created)\n               && Objects.equal(this.attachments, that.attachments)\n               && Objects.equal(this.volumeType, that.volumeType)\n               && Objects.equal(this.snapshotId, that.snapshotId)\n               && Objects.equal(this.name, that.name)\n               && Objects.equal(this.description, that.description)\n               && Objects.equal(this.metadata, that.metadata)\n               && Objects.equal(this.tenantId, that.tenantId);\n\n   }\n   \n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"status\", status).add(\"size\", size).add(\"zone\", zone).add(\"created\", created).add(\"attachments\", attachments).add(\"volumeType\", volumeType).add(\"snapshotId\", snapshotId).add(\"name\", name).add(\"description\", description).add(\"metadata\", metadata).add(\"extendedAttributes\", tenantId);\n   }\n   \n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/main/java/org/jclouds/openstack/cinder/v1/domain/VolumeAttachment.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.cinder.v1.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * An OpenStack Cinder Volume Attachment (describes how Volumes are attached to Servers).\n */\npublic class VolumeAttachment {\n\n   public static Builder<?> builder() { \n      return new ConcreteBuilder();\n   }\n   \n   public Builder<?> toBuilder() { \n      return new ConcreteBuilder().fromVolumeAttachment(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>>  {\n      protected abstract T self();\n\n      protected String id;\n      protected String volumeId;\n      protected String serverId;\n      protected String device;\n   \n      /** \n       * @see VolumeAttachment#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /** \n       * @see VolumeAttachment#getVolumeId()\n       */\n      public T volumeId(String volumeId) {\n         this.volumeId = volumeId;\n         return self();\n      }\n\n      /** \n       * @see VolumeAttachment#getServerId()\n       */\n      public T serverId(String serverId) {\n         this.serverId = serverId;\n         return self();\n      }\n\n      /** \n       * @see VolumeAttachment#getDevice()\n       */\n      public T device(String device) {\n         this.device = device;\n         return self();\n      }\n\n      public VolumeAttachment build() {\n         return new VolumeAttachment(id, volumeId, serverId, device);\n      }\n      \n      public T fromVolumeAttachment(VolumeAttachment in) {\n         return this\n                  .id(in.getId())\n                  .volumeId(in.getVolumeId())\n                  .serverId(in.getServerId())\n                  .device(in.getDevice());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   @Named(\"volume_id\")\n   private final String volumeId;\n   @Named(\"server_id\")\n   private final String serverId;\n   private final String device;\n\n   @ConstructorProperties({\n      \"id\", \"volume_id\", \"server_id\", \"device\"\n   })\n   protected VolumeAttachment(String id, String volumeId, @Nullable String serverId, @Nullable String device) {\n      this.id = checkNotNull(id, \"id\");\n      this.volumeId = checkNotNull(volumeId, \"volumeId\");\n      this.serverId = serverId;\n      this.device = device;\n   }\n\n   /**\n    * @return the attachment id (typically the same as #getVolumeId())\n    */\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * @return the id of the volume attached\n    */\n   public String getVolumeId() {\n      return this.volumeId;\n   }\n\n   /**\n    * @return the id of the server the volume is attached to\n    */\n   @Nullable\n   public String getServerId() {\n      return this.serverId;\n   }\n\n   /**\n    * @return the device name (e.g. \"/dev/vdc\")\n    */\n   @Nullable\n   public String getDevice() {\n      return this.device;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, volumeId, serverId, device);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      VolumeAttachment that = VolumeAttachment.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n               && Objects.equal(this.volumeId, that.volumeId)\n               && Objects.equal(this.serverId, that.serverId)\n               && Objects.equal(this.device, that.device);\n   }\n   \n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"volumeId\", volumeId).add(\"serverId\", serverId).add(\"device\", device);\n   }\n   \n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/main/java/org/jclouds/openstack/cinder/v1/domain/VolumeQuota.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.cinder.v1.domain;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\npublic class VolumeQuota {\n\n   private final String id;\n   private final int volumes;\n   private final int gigabytes;\n   private final int snapshots;\n\n   protected VolumeQuota(String id, int volumes, int gigabytes, int snapshots) {\n      this.id = checkNotNull(id, \"id\");\n      this.volumes = volumes;\n      this.gigabytes = gigabytes;\n      this.snapshots = snapshots;\n   }\n\n   /**\n    * The id of the tenant this set of limits applies to\n    */\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * The limit of the number of volumes that can be created for the tenant\n    */\n   public int getVolumes() {\n      return this.volumes;\n   }\n\n   /**\n    * The limit of the total size of all volumes for the tenant\n    */\n   public int getGigabytes() {\n      return this.gigabytes;\n   }\n\n   /**\n    * The limit of the number of snapshots that can be used by the tenant\n    */\n   public int getSnapshots() {\n      return this.snapshots;\n   }\n\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, volumes, gigabytes, snapshots);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      VolumeQuota that = VolumeQuota.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n            && Objects.equal(this.volumes, that.volumes)\n            && Objects.equal(this.gigabytes, that.gigabytes)\n            && Objects.equal(this.snapshots, that.snapshots);\n   }\n\n   protected MoreObjects.ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"volumes\", volumes).add(\"gigabytes\", gigabytes).add(\"snapshots\", snapshots);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromVolumeQuota(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String id;\n      protected int volumes;\n      protected int gigabytes;\n      protected int snapshots;\n\n\n      /**\n       * @see VolumeQuota#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see VolumeQuota#getVolumes()\n       */\n      public T volumes(int volumes) {\n         this.volumes = volumes;\n         return self();\n      }\n\n      /**\n       * @see VolumeQuota#getGigabytes()\n       */\n      public T gigabytes(int gigabytes) {\n         this.gigabytes = gigabytes;\n         return self();\n      }\n\n      /**\n       * @see VolumeQuota#getSnapshots()\n       */\n      public T snapshots(int snapshots) {\n         this.snapshots = snapshots;\n         return self();\n      }\n\n\n      public VolumeQuota build() {\n         return new VolumeQuota(id, volumes, gigabytes, snapshots);\n      }\n\n      public T fromVolumeQuota(VolumeQuota in) {\n         return this\n               .id(in.getId())\n               .volumes(in.getVolumes())\n               .gigabytes(in.getGigabytes())\n               .snapshots(in.getSnapshots());\n\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/main/java/org/jclouds/openstack/cinder/v1/domain/VolumeType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.cinder.v1.domain;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableMap;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport jakarta.inject.Named;\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\nimport java.util.Map;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\n/**\n * An Openstack Cinder Volume Type.\n */\npublic class VolumeType {\n\n   public static Builder<?> builder() { \n      return new ConcreteBuilder();\n   }\n   \n   public Builder<?> toBuilder() { \n      return new ConcreteBuilder().fromVolumeType(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>>  {\n      protected abstract T self();\n\n      protected String id;\n      protected String name;\n      protected Date created;\n      protected Date updated;\n      protected Map<String, String> extraSpecs = ImmutableMap.of();\n   \n      /** \n       * @see VolumeType#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /** \n       * @see VolumeType#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /** \n       * @see VolumeType#getCreated()\n       */\n      public T created(Date created) {\n         this.created = created;\n         return self();\n      }\n\n      /** \n       * @see VolumeType#getUpdated()\n       */\n      public T updated(Date updated) {\n         this.updated = updated;\n         return self();\n      }\n\n      /** \n       * @see VolumeType#getExtraSpecs()\n       */\n      public T extraSpecs(Map<String, String> extraSpecs) {\n         if (extraSpecs != null)\n         {\n            this.extraSpecs = ImmutableMap.copyOf(extraSpecs);\n         }\n         return self();\n      }\n\n      public VolumeType build() {\n         return new VolumeType(id, name, created, updated, extraSpecs);\n      }\n      \n      public T fromVolumeType(VolumeType in) {\n         return this\n                  .id(in.getId())\n                  .name(in.getName())\n                  .created(in.getCreated().orNull())\n                  .updated(in.getUpdated().orNull())\n                  .extraSpecs(in.getExtraSpecs());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final String name;\n   @Named(\"created_at\")\n   private final Optional<Date> created;\n   @Named(\"updated_at\")\n   private final Optional<Date> updated;\n   @Named(\"extra_specs\")\n   private final Map<String, String> extraSpecs;\n\n   @ConstructorProperties({\n      \"id\", \"name\", \"created_at\", \"updated_at\", \"extra_specs\"\n   })\n   protected VolumeType(String id, String name, @Nullable Date created, @Nullable Date updated, @Nullable Map<String, String> extraSpecs) {\n      this.id = checkNotNull(id, \"id\");\n      this.name = checkNotNull(name, \"name\");\n      this.created = Optional.fromNullable(created);\n      this.updated = Optional.fromNullable(updated);\n      if (extraSpecs == null)\n         this.extraSpecs = ImmutableMap.of();\n      else\n         this.extraSpecs = ImmutableMap.copyOf(extraSpecs);\n   }\n\n   public String getId() {\n      return this.id;\n   }\n\n   public String getName() {\n      return this.name;\n   }\n\n   /**\n    * The Date the VolumeType was created\n    */\n   public Optional<Date> getCreated() {\n      return this.created;\n   }\n\n   /**\n    * The Date the VolumeType as last updated - absent if no updates have taken place\n    */\n   public Optional<Date> getUpdated() {\n      return this.updated;\n   }\n\n   public Map<String, String> getExtraSpecs() {\n      return this.extraSpecs;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, name, created, updated, extraSpecs);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      VolumeType that = VolumeType.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n               && Objects.equal(this.name, that.name)\n               && Objects.equal(this.created, that.created)\n               && Objects.equal(this.updated, that.updated)\n               && Objects.equal(this.extraSpecs, that.extraSpecs);\n   }\n   \n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"name\", name).add(\"created\", created).add(\"updated\", updated).add(\"extraSpecs\", extraSpecs);\n   }\n   \n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/main/java/org/jclouds/openstack/cinder/v1/domain/ZoneState.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.cinder.v1.domain;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\nimport java.beans.ConstructorProperties;\n\n/**\n * zone state for availability zones\n */\npublic class ZoneState {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return new Builder().fromZoneState(this);\n   }\n\n   public static class Builder {\n\n      protected boolean available;\n\n      /**\n       * @see ZoneState#available() ()\n       */\n      public Builder available(Boolean available) {\n         this.available = available;\n         return this;\n      }\n\n      public ZoneState build() {\n         return new ZoneState(available);\n      }\n\n      public Builder fromZoneState(ZoneState in) {\n         return this\n               .available(in.available());\n      }\n   }\n\n   private final Boolean available;\n\n   @ConstructorProperties({\"available\"})\n   protected ZoneState(Boolean available) {\n      this.available = available;\n   }\n\n   public boolean available() {\n      return this.available;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(available);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      ZoneState that = ZoneState.class.cast(obj);\n      return Objects.equal(this.available, that.available);\n   }\n\n   protected MoreObjects.ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"available\", available);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/main/java/org/jclouds/openstack/cinder/v1/extensions/AvailabilityZoneApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.openstack.cinder.v1.extensions;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.collect.FluentIterable;\nimport org.jclouds.Fallbacks;\nimport org.jclouds.openstack.cinder.v1.domain.AvailabilityZone;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.v2_0.ServiceType;\nimport org.jclouds.openstack.v2_0.services.Extension;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.core.MediaType;\n\n/**\n * Provides access to the OpenStack Block Storage (Cinder) Availability Zone Extension API.\n */\n@Beta\n@Extension(of = ServiceType.BLOCK_STORAGE, namespace = ExtensionNamespaces.ADMIN_ACTIONS)\n@RequestFilters(AuthenticateRequest.class)\n@Consumes(MediaType.APPLICATION_JSON)\n@Path(\"/os-availability-zone\")\npublic interface AvailabilityZoneApi {\n\n   /**\n    * Lists all availability zones\n    *\n    * @return all availability zones\n    */\n   @GET\n   @SelectJson(\"availabilityZoneInfo\")\n   @Fallback(Fallbacks.EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<AvailabilityZone> list();\n\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/main/java/org/jclouds/openstack/cinder/v1/extensions/ExtensionNamespaces.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.cinder.v1.extensions;\n\n/**\n * Extension namespaces\n */\npublic final class ExtensionNamespaces {\n\n   /**\n    * Admin Action extension\n    */\n   public static final String ADMIN_ACTIONS = \"http://docs.openstack.org/ext/admin-actions/api/v1.1\";\n\n   private ExtensionNamespaces() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/main/java/org/jclouds/openstack/cinder/v1/features/QuotaApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.cinder.v1.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.cinder.v1.domain.VolumeQuota;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.SkipEncoding;\n\n/**\n * Provides access to the Quota API.\n *\n */\n@SkipEncoding({'/', '='})\n@RequestFilters(AuthenticateRequest.class)\n@Consumes(MediaType.APPLICATION_JSON)\n@Path(\"/os-quota-sets\")\npublic interface QuotaApi {\n\n   @Named(\"quota:get\")\n   @GET\n   @SelectJson(\"quota_set\")\n   @Path(\"/{tenant_id}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   VolumeQuota getByTenant(@PathParam(\"tenant_id\") String tenantId);\n\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/main/java/org/jclouds/openstack/cinder/v1/features/SnapshotApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.cinder.v1.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyFluentIterableOnNotFoundOr404;\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.cinder.v1.domain.Snapshot;\nimport org.jclouds.openstack.cinder.v1.options.CreateSnapshotOptions;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.SkipEncoding;\n\nimport com.google.common.collect.FluentIterable;\n\n/**\n * Provides access to Volume Snapshots API.\n *\n */\n@SkipEncoding({'/', '='})\n@RequestFilters(AuthenticateRequest.class)\n@Consumes(MediaType.APPLICATION_JSON)\n@Path(\"/snapshots\")\npublic interface SnapshotApi {\n   /**\n    * Returns a summary list of Snapshots.\n    *\n    * @return The list of Snapshots\n    */\n   @Named(\"snapshot:list\")\n   @GET\n   @SelectJson(\"snapshots\")\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<? extends Snapshot> list();\n\n   /**\n    * Returns a detailed list of Snapshots.\n    *\n    * @return The list of Snapshots\n    */\n   @Named(\"snapshot:list\")\n   @GET\n   @Path(\"/detail\")\n   @SelectJson(\"snapshots\")\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<? extends Snapshot> listInDetail();\n\n   /**\n    * Return data about the given Snapshot.\n    *\n    * @param snapshotId Id of the Snapshot\n    * @return Details of a specific Snapshot\n    */\n   @Named(\"snapshot:get\")\n   @GET\n   @Path(\"/{id}\")\n   @SelectJson(\"snapshot\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Snapshot get(@PathParam(\"id\") String snapshotId);\n\n   /**\n    * Creates a new Snapshot. The Volume status must be Available.\n    *\n    * @param volumeId The Volume Id from which to create the Snapshot\n    * @param options See CreateSnapshotOptions\n    * @return The new Snapshot\n    */\n   @Named(\"snapshot:create\")\n   @POST\n   @SelectJson(\"snapshot\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @MapBinder(CreateSnapshotOptions.class)\n   Snapshot create(@PayloadParam(\"volume_id\") String volumeId, CreateSnapshotOptions... options);\n\n   /**\n    * Delete a Snapshot.\n    *\n    * @param snapshotId Id of the Snapshot\n    * @return true if successful, false otherwise\n    */\n   @Named(\"snapshot:delete\")\n   @DELETE\n   @Path(\"/{id}\")\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean delete(@PathParam(\"id\") String snapshotId);\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/main/java/org/jclouds/openstack/cinder/v1/features/VolumeApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.cinder.v1.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyFluentIterableOnNotFoundOr404;\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.cinder.v1.domain.Volume;\nimport org.jclouds.openstack.cinder.v1.options.CreateVolumeOptions;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.SkipEncoding;\n\nimport com.google.common.collect.FluentIterable;\n\n/**\n * Provides access to the Volume API.\n *\n * This API strictly handles creating and managing Volumes. To attach a Volume to a Server you need to use the\n * @see VolumeAttachmentApi\n *\n */\n@SkipEncoding({'/', '='})\n@RequestFilters(AuthenticateRequest.class)\n@Consumes(MediaType.APPLICATION_JSON)\n@Path(\"/volumes\")\npublic interface VolumeApi {\n   /**\n    * Returns a summary list of Volumes.\n    *\n    * @return The list of Volumes\n    */\n   @Named(\"volume:list\")\n   @GET\n   @SelectJson(\"volumes\")\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<? extends Volume> list();\n\n   /**\n    * Returns a detailed list of Volumes.\n    *\n    * @return The list of Volumes\n    */\n   @Named(\"volume:list\")\n   @GET\n   @Path(\"/detail\")\n   @SelectJson(\"volumes\")\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<? extends Volume> listInDetail();\n\n   /**\n    * Return data about the given Volume.\n    *\n    * @param volumeId Id of the Volume\n    * @return Details of a specific Volume\n    */\n   @Named(\"volume:get\")\n   @GET\n   @Path(\"/{id}\")\n   @SelectJson(\"volume\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Volume get(@PathParam(\"id\") String volumeId);\n\n   /**\n    * Creates a new Volume\n    *\n    * @param volumeId Id of the Volume\n    * @param options See CreateVolumeOptions\n    * @return The new Volume\n    */\n   @Named(\"volume:create\")\n   @POST\n   @SelectJson(\"volume\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @MapBinder(CreateVolumeOptions.class)\n   Volume create(@PayloadParam(\"size\") int sizeGB, CreateVolumeOptions... options);\n\n   /**\n    * Delete a Volume. The Volume status must be Available or Error.\n    *\n    * @param volumeId Id of the Volume\n    * @return true if successful, false otherwise\n    */\n   @Named(\"volume:delete\")\n   @DELETE\n   @Path(\"/{id}\")\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean delete(@PathParam(\"id\") String volumeId);\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/main/java/org/jclouds/openstack/cinder/v1/features/VolumeTypeApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.cinder.v1.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyFluentIterableOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.cinder.v1.domain.VolumeType;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.SkipEncoding;\n\nimport com.google.common.collect.FluentIterable;\n\n/**\n * Provides access to the OpenStack Block Storage (Cinder) v1 Volume Types API.\n *\n */\n@SkipEncoding({'/', '='})\n@RequestFilters(AuthenticateRequest.class)\n@Consumes(MediaType.APPLICATION_JSON)\n@Path(\"/types\")\npublic interface VolumeTypeApi {\n   /**\n    * Returns a summary list of VolumeTypes.\n    *\n    * @return The list of VolumeTypes\n    */\n   @Named(\"volumeType:list\")\n   @GET\n   @SelectJson(\"volume_types\")\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<? extends VolumeType> list();\n\n   /**\n    * Return data about the given VolumeType.\n    *\n    * @param volumeTypeId Id of the VolumeType\n    * @return Details of a specific VolumeType\n    */\n   @Named(\"volumeType:get\")\n   @GET\n   @Path(\"/{id}\")\n   @SelectJson(\"volume_type\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   VolumeType get(@PathParam(\"id\") String volumeTypeId);\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/main/java/org/jclouds/openstack/cinder/v1/handlers/CinderErrorHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.cinder.v1.handlers;\n\nimport static org.jclouds.http.HttpUtils.closeClientButKeepContentStream;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.InsufficientResourcesException;\nimport org.jclouds.rest.ResourceNotFoundException;\n\n/**\n * This will parse and set an appropriate exception on the command object.\n */\n@Singleton\npublic class CinderErrorHandler implements HttpErrorHandler {\n\n   public void handleError(HttpCommand command, HttpResponse response) {\n      // it is important to always read fully and close streams\n      byte[] data = closeClientButKeepContentStream(response);\n      String message = data != null ? new String(data) : null;\n\n      Exception exception = message != null ? new HttpResponseException(command, response, message)\n               : new HttpResponseException(command, response);\n      message = message != null ? message : String.format(\"%s -> %s\", command.getCurrentRequest().getRequestLine(),\n               response.getStatusLine());\n      switch (response.getStatusCode()) {\n         case 400:\n            if (message.contains(\"quota exceeded\"))\n               exception = new InsufficientResourcesException(message, exception);\n            else if (message.contains(\"Invalid volume\"))\n               exception = new IllegalStateException(message, exception);\n            break;\n         case 401:\n         case 403:\n            exception = new AuthorizationException(message, exception);\n            break;\n         case 404:\n            if (!command.getCurrentRequest().getMethod().equals(\"DELETE\")) {\n               exception = new ResourceNotFoundException(message, exception);\n            }\n            break;\n         case 413:\n            exception = new InsufficientResourcesException(message, exception);\n            break;\n      }\n      command.setException(exception);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/main/java/org/jclouds/openstack/cinder/v1/options/CreateSnapshotOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.cinder.v1.options;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.MapBinder;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Maps;\n\npublic class CreateSnapshotOptions implements MapBinder {\n   public static final CreateSnapshotOptions NONE = new CreateSnapshotOptions();\n\n   @Inject\n   private BindToJsonPayload jsonBinder;\n\n   private String name;\n   private String description;\n   private boolean force = false;\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      Map<String, Object> data = Maps.newHashMap(postParams);\n      if (name != null)\n         data.put(\"display_name\", name);\n      if (description != null)\n         data.put(\"display_description\", description);\n      if (force)\n         data.put(\"force\", \"true\");\n      return jsonBinder.bindToRequest(request, ImmutableMap.of(\"snapshot\", data));\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object toBind) {\n      throw new IllegalStateException(\"CreateSnapshot is a POST operation\");\n   }\n\n   @Override\n   public boolean equals(Object object) {\n      if (this == object) {\n         return true;\n      }\n      if (!(object instanceof CreateSnapshotOptions)) return false;\n      final CreateSnapshotOptions other = CreateSnapshotOptions.class.cast(object);\n      return equal(name, other.name) && equal(description, other.description);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(name, description);\n   }\n\n   protected ToStringHelper string() {\n      return toStringHelper(\"\").add(\"name\", name).add(\"description\", description);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   public CreateSnapshotOptions name(String name) {\n      this.name = name;\n      return this;\n   }\n\n   public CreateSnapshotOptions description(String description) {\n      this.description = description;\n      return this;\n   }\n\n   public CreateSnapshotOptions force() {\n      this.force = true;\n      return this;\n   }\n   \n   public String getName() {\n      return name;\n   }\n\n   public String getDescription() {\n      return description;\n   }\n\n   public boolean isForce() {\n      return force;\n   }\n\n   public static class Builder {\n      /**\n       * @see CreateSnapshotOptions#getName()\n       */\n      public static CreateSnapshotOptions name(String name) {\n         return new CreateSnapshotOptions().name(name);\n      }\n      /**\n       * @see CreateSnapshotOptions#getDescription()\n       */\n      public static CreateSnapshotOptions description(String description) {\n         return new CreateSnapshotOptions().description(description);\n      }\n\n      /**\n       * @see CreateSnapshotOptions#isForce()\n       */\n      public static CreateSnapshotOptions force() {\n         return new CreateSnapshotOptions().force();\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/main/java/org/jclouds/openstack/cinder/v1/options/CreateVolumeOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.cinder.v1.options;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\nimport java.util.Map.Entry;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.MapBinder;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Maps;\n\npublic class CreateVolumeOptions implements MapBinder {\n   public static final CreateVolumeOptions NONE = new CreateVolumeOptions();\n\n   @Inject\n   private BindToJsonPayload jsonBinder;\n\n   protected String name;\n   protected String description;\n   protected String volumeType;\n   protected String availabilityZone;\n   protected String snapshotId;\n   protected Map<String, String> metadata = ImmutableMap.of();\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      Map<String, Object> image = Maps.newHashMap();\n      image.putAll(postParams);\n      if (name != null)\n         image.put(\"display_name\", name);\n      if (description != null)\n         image.put(\"display_description\", description);\n      if (volumeType != null)\n         image.put(\"volume_type\", volumeType);\n      if (availabilityZone != null)\n         image.put(\"availability_zone\", availabilityZone);\n      if (snapshotId != null)\n         image.put(\"snapshot_id\", snapshotId);\n      if (!metadata.isEmpty())\n         image.put(\"metadata\", metadata);\n      return jsonBinder.bindToRequest(request, ImmutableMap.of(\"volume\", image));\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object toBind) {\n      throw new IllegalStateException(\"CreateVolume is a POST operation\");\n   }\n\n   @Override\n   public boolean equals(Object object) {\n      if (this == object) {\n         return true;\n      }\n      if (!(object instanceof CreateVolumeOptions)) return false;\n      final CreateVolumeOptions other = CreateVolumeOptions.class.cast(object);\n      return equal(volumeType, other.volumeType) && equal(availabilityZone, other.availabilityZone) && equal(snapshotId, other.snapshotId)\n            && equal(name, other.name) && equal(description, other.description) && equal(metadata, other.metadata);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(volumeType, availabilityZone, snapshotId, name, description, metadata);\n   }\n\n   protected ToStringHelper string() {\n      return toStringHelper(\"\").add(\"volumeType\", volumeType).add(\"availabilityZone\", availabilityZone)\n            .add(\"snapshotId\", snapshotId).add(\"name\", name).add(\"description\", description).add(\"metadata\", metadata);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   /**\n    * Custom cloud server metadata can also be supplied at launch time. This\n    * metadata is stored in the API system where it is retrievable by querying\n    * the API for server status. The maximum size of the metadata key and value\n    * is each 255 bytes and the maximum number of key-value pairs that can be\n    * supplied per volume is 5.\n    */\n   public CreateVolumeOptions metadata(Map<String, String> metadata) {\n      checkNotNull(metadata, \"metadata\");\n      checkArgument(metadata.size() <= 5,\n            \"you cannot have more then 5 metadata values.  You specified: \" + metadata.size());\n      for (Entry<String, String> entry : metadata.entrySet()) {\n         checkArgument(\n               entry.getKey().getBytes().length < 255,\n               String.format(\"maximum length of metadata key is 255 bytes.  Key specified %s is %d bytes\",\n                     entry.getKey(), entry.getKey().getBytes().length));\n         checkArgument(entry.getKey().getBytes().length < 255, String.format(\n               \"maximum length of metadata value is 255 bytes.  Value specified for %s (%s) is %d bytes\",\n               entry.getKey(), entry.getValue(), entry.getValue().getBytes().length));\n      }\n      this.metadata = ImmutableMap.copyOf(metadata);\n      return this;\n   }\n\n   /**\n    * @param name The name of the Volume\n    */\n   public CreateVolumeOptions name(String name) {\n      this.name = name;\n      return this;\n   }\n\n   /**\n    * @param description A description of the Volume\n    */\n   public CreateVolumeOptions description(String description) {\n      this.description = description;\n      return this;\n   }\n\n   /**\n    * @see VolumeTypeApi#list()\n    * \n    * @param volumeType The type of Volume to create\n    */\n   public CreateVolumeOptions volumeType(String volumeType) {\n      this.volumeType = volumeType;\n      return this;\n   }\n\n   /**\n    * @param availabilityZone The optional availability zone in which to create a Volume\n    */\n   public CreateVolumeOptions availabilityZone(String availabilityZone) {\n      this.availabilityZone = availabilityZone;\n      return this;\n   }\n\n   /**\n    * @param snapshotId The optional snapshot from which to create a Volume\n    */\n   public CreateVolumeOptions snapshotId(String snapshotId) {\n      this.snapshotId = snapshotId;\n      return this;\n   }\n\n   public String getVolumeType() {\n      return volumeType;\n   }\n\n   public String getAvailabilityZone() {\n      return availabilityZone;\n   }\n\n   public String getSnapshotId() {\n      return snapshotId;\n   }\n\n   public String getName() {\n      return name;\n   }\n\n   public String getDescription() {\n      return description;\n   }\n\n   public Map<String, String> getMetadata() {\n      return metadata;\n   }\n\n   public static class Builder {\n      /**\n       * @see CreateVolumeOptions#getName()\n       */\n      public static CreateVolumeOptions name(String name) {\n         return new CreateVolumeOptions().name(name);\n      }\n      /**\n       * @see CreateVolumeOptions#getDescription()\n       */\n      public static CreateVolumeOptions description(String description) {\n         return new CreateVolumeOptions().description(description);\n      }\n\n      /**\n       * @see CreateVolumeOptions#getVolumeType()\n       */\n      public static CreateVolumeOptions volumeType(String volumeType) {\n         return new CreateVolumeOptions().volumeType(volumeType);\n      }\n\n      /**\n       * @see CreateVolumeOptions#getAvailabilityZone()\n       */\n      public static CreateVolumeOptions availabilityZone(String availabilityZone) {\n         return new CreateVolumeOptions().availabilityZone(availabilityZone);\n      }\n\n      /**\n       * @see CreateVolumeOptions#getSnapshotId()\n       */\n      public static CreateVolumeOptions snapshotId(String snapshotId) {\n         return new CreateVolumeOptions().snapshotId(snapshotId);\n      }\n\n      /**\n       * @see CreateVolumeOptions#getMetadata()\n       */\n      public static CreateVolumeOptions metadata(Map<String, String> metadata) {\n         return new CreateVolumeOptions().metadata(metadata);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/main/java/org/jclouds/openstack/cinder/v1/predicates/SnapshotPredicates.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.cinder.v1.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static org.jclouds.util.Predicates2.retry;\n\nimport org.jclouds.openstack.cinder.v1.domain.Snapshot;\nimport org.jclouds.openstack.cinder.v1.domain.Volume;\nimport org.jclouds.openstack.cinder.v1.domain.Volume.Status;\nimport org.jclouds.openstack.cinder.v1.features.SnapshotApi;\n\nimport com.google.common.base.Predicate;\n\n/**\n * Tests to see if snapshot has reached status. This class is most useful when paired with a RetryablePredicate as\n * in the code below. This class can be used to block execution until the Snapshot status has reached a desired state.\n * This is useful when your Snapshot needs to be 100% ready before you can continue with execution.\n *\n * <pre>\n * {@code\n * Snapshot snapshot = snapshotApi.create(volumeId);\n * RetryablePredicate<String> awaitAvailable = RetryablePredicate.create(\n *    SnapshotPredicates.available(snapshotApi), 600, 10, 10, TimeUnit.SECONDS);\n *\n * if (!awaitAvailable.apply(snapshot.getId())) {\n *    throw new TimeoutException(\"Timeout on snapshot: \" + snapshot);\n * }\n * }\n * </pre>\n *\n * You can also use the static convenience methods as so.\n *\n * <pre>\n * {@code\n * Snapshot snapshot = snapshotApi.create(volumeId);\n *\n * if (!SnapshotPredicates.awaitAvailable(snapshotApi).apply(snapshot.getId())) {\n *    throw new TimeoutException(\"Timeout on snapshot: \" + snapshot);\n * }\n * }\n * </pre>\n */\npublic class SnapshotPredicates {\n   /**\n    * Wait until a Snapshot is Available.\n    *\n    * @param snapshotApi The SnapshotApi in the region where your Snapshot resides.\n    * @return RetryablePredicate That will check the status every 5 seconds for a maxiumum of 20 minutes.\n    */\n   public static Predicate<Snapshot> awaitAvailable(SnapshotApi snapshotApi) {\n      StatusUpdatedPredicate statusPredicate = new StatusUpdatedPredicate(snapshotApi, Volume.Status.AVAILABLE);\n      return retry(statusPredicate, 1200, 5, 5, SECONDS);\n   }\n\n   /**\n    * Wait until a Snapshot no longer exists.\n    *\n    * @param snapshotApi The SnapshotApi in the region where your Snapshot resides.\n    * @return RetryablePredicate That will check the whether the Snapshot exists\n    * every 5 seconds for a maxiumum of 20 minutes.\n    */\n   public static Predicate<Snapshot> awaitDeleted(SnapshotApi snapshotApi) {\n      DeletedPredicate deletedPredicate = new DeletedPredicate(snapshotApi);\n      return retry(deletedPredicate, 1200, 5, 5, SECONDS);\n   }\n\n   public static Predicate<Snapshot> awaitStatus(SnapshotApi snapshotApi, Volume.Status status, long maxWaitInSec,\n         long periodInSec) {\n   StatusUpdatedPredicate statusPredicate = new StatusUpdatedPredicate(snapshotApi, status);\n      return retry(statusPredicate, maxWaitInSec, periodInSec, periodInSec, SECONDS);\n   }\n\n   private static class StatusUpdatedPredicate implements Predicate<Snapshot> {\n      private SnapshotApi snapshotApi;\n      private Status status;\n\n      public StatusUpdatedPredicate(SnapshotApi snapshotApi, Volume.Status status) {\n         this.snapshotApi = checkNotNull(snapshotApi, \"snapshotApi must be defined\");\n         this.status = checkNotNull(status, \"status must be defined\");\n      }\n\n      /**\n       * @return boolean Return true when the snapshot reaches status, false otherwise\n       */\n      @Override\n      public boolean apply(Snapshot snapshot) {\n         checkNotNull(snapshot, \"snapshot must be defined\");\n\n         if (status.equals(snapshot.getStatus())) {\n            return true;\n         }\n         else {\n            Snapshot snapshotUpdated = snapshotApi.get(snapshot.getId());\n            checkNotNull(snapshotUpdated, \"Snapshot %s not found.\", snapshot.getId());\n\n            return status.equals(snapshotUpdated.getStatus());\n         }\n      }\n   }\n\n   private static class DeletedPredicate implements Predicate<Snapshot> {\n      private SnapshotApi snapshotApi;\n\n      public DeletedPredicate(SnapshotApi snapshotApi) {\n         this.snapshotApi = checkNotNull(snapshotApi, \"snapshotApi must be defined\");\n      }\n\n      /**\n       * @return boolean Return true when the snapshot is deleted, false otherwise\n       */\n      @Override\n      public boolean apply(Snapshot snapshot) {\n         checkNotNull(snapshot, \"snapshot must be defined\");\n\n         return snapshotApi.get(snapshot.getId()) == null;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/main/java/org/jclouds/openstack/cinder/v1/predicates/VolumePredicates.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.cinder.v1.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static org.jclouds.util.Predicates2.retry;\n\nimport org.jclouds.openstack.cinder.v1.domain.Volume;\nimport org.jclouds.openstack.cinder.v1.domain.Volume.Status;\nimport org.jclouds.openstack.cinder.v1.features.VolumeApi;\n\nimport com.google.common.base.Predicate;\n\n/**\n * Tests to see if volume has reached status. This class is most useful when paired with a RetryablePredicate as\n * in the code below. This class can be used to block execution until the Volume status has reached a desired state.\n * This is useful when your Volume needs to be 100% ready before you can continue with execution.\n *\n * <pre>\n * {@code\n * Volume volume = volumeApi.create(100);\n *\n * RetryablePredicate<String> awaitAvailable = RetryablePredicate.create(\n *    VolumePredicates.available(volumeApi), 600, 10, 10, TimeUnit.SECONDS);\n *\n * if (!awaitAvailable.apply(volume.getId())) {\n *    throw new TimeoutException(\"Timeout on volume: \" + volume);\n * }\n * }\n * </pre>\n *\n * You can also use the static convenience methods as so.\n *\n * <pre>\n * {@code\n * Volume volume = volumeApi.create(100);\n *\n * if (!VolumePredicates.awaitAvailable(volumeApi).apply(volume.getId())) {\n *    throw new TimeoutException(\"Timeout on volume: \" + volume);\n * }\n * }\n * </pre>\n */\npublic class VolumePredicates {\n   /**\n    * Wait until a Volume is Available.\n    *\n    * @param volumeApi The VolumeApi in the region where your Volume resides.\n    * @return RetryablePredicate That will check the status every 5 seconds for a maxiumum of 10 minutes.\n    */\n   public static Predicate<Volume> awaitAvailable(VolumeApi volumeApi) {\n      StatusUpdatedPredicate statusPredicate = new StatusUpdatedPredicate(volumeApi, Volume.Status.AVAILABLE);\n      return retry(statusPredicate, 600, 5, 5, SECONDS);\n   }\n\n   /**\n    * Wait until a Volume is In Use.\n    *\n    * @param volumeApi The VolumeApi in the region where your Volume resides.\n    * @return RetryablePredicate That will check the status every 5 seconds for a maxiumum of 10 minutes.\n    */\n   public static Predicate<Volume> awaitInUse(VolumeApi volumeApi) {\n      StatusUpdatedPredicate statusPredicate = new StatusUpdatedPredicate(volumeApi, Volume.Status.IN_USE);\n      return retry(statusPredicate, 600, 5, 5, SECONDS);\n   }\n\n   /**\n    * Wait until a Volume no longer exists.\n    *\n    * @param volumeApi The VolumeApi in the region where your Volume resides.\n    * @return RetryablePredicate That will check the whether the Volume exists\n    * every 5 seconds for a maxiumum of 10 minutes.\n    */\n   public static Predicate<Volume> awaitDeleted(VolumeApi volumeApi) {\n      DeletedPredicate deletedPredicate = new DeletedPredicate(volumeApi);\n      return retry(deletedPredicate, 600, 5, 5, SECONDS);\n   }\n\n   public static Predicate<Volume> awaitStatus(\n         VolumeApi volumeApi, Volume.Status status, long maxWaitInSec, long periodInSec) {\n      StatusUpdatedPredicate statusPredicate = new StatusUpdatedPredicate(volumeApi, status);\n      return retry(statusPredicate, maxWaitInSec, periodInSec, periodInSec, SECONDS);\n   }\n\n   private static class StatusUpdatedPredicate implements Predicate<Volume> {\n      private VolumeApi volumeApi;\n      private Status status;\n\n      public StatusUpdatedPredicate(VolumeApi volumeApi, Volume.Status status) {\n         this.volumeApi = checkNotNull(volumeApi, \"volumeApi must be defined\");\n         this.status = checkNotNull(status, \"status must be defined\");\n      }\n\n      /**\n       * @return boolean Return true when the volume reaches status, false otherwise\n       */\n      @Override\n      public boolean apply(Volume volume) {\n         checkNotNull(volume, \"volume must be defined\");\n         Volume volumeUpdated = volumeApi.get(volume.getId());\n         checkNotNull(volumeUpdated, \"Volume %s not found.\", volume.getId());\n         return status.equals(volumeUpdated.getStatus());\n      }\n   }\n\n   private static class DeletedPredicate implements Predicate<Volume> {\n      private VolumeApi volumeApi;\n\n      public DeletedPredicate(VolumeApi volumeApi) {\n         this.volumeApi = checkNotNull(volumeApi, \"volumeApi must be defined\");\n      }\n\n      /**\n       * @return boolean Return true when the snapshot is deleted, false otherwise\n       */\n      @Override\n      public boolean apply(Volume volume) {\n         checkNotNull(volume, \"volume must be defined\");\n\n         return volumeApi.get(volume.getId()) == null;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/test/java/org/jclouds/openstack/cinder/v1/domain/VolumeTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.cinder.v1.domain;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"VolumeTest\")\npublic class VolumeTest {\n   public void testVolumeForId() {\n      Volume volume = Volume.forId(\"60761c60-0f56-4499-b522-ff13e120af10\");\n      \n      assertEquals(volume.getId(), \"60761c60-0f56-4499-b522-ff13e120af10\");\n      assertEquals(volume.getStatus(), Volume.Status.UNRECOGNIZED);\n      assertEquals(volume.getZone(), \"nova\");\n   }\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/test/java/org/jclouds/openstack/cinder/v1/features/AvailabilityZoneApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.cinder.v1.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.net.URI;\n\nimport com.google.common.collect.Iterables;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.cinder.v1.domain.AvailabilityZone;\nimport org.jclouds.openstack.cinder.v1.extensions.AvailabilityZoneApi;\nimport org.jclouds.openstack.cinder.v1.internal.BaseCinderApiExpectTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"AvailabilityZoneApiExpectTest\")\npublic class AvailabilityZoneApiExpectTest extends BaseCinderApiExpectTest {\n\n   public void testListAvailabilityZones() throws Exception {\n      URI endpoint = URI.create(\"http://172.16.0.1:8776/v1/50cdb4c60374463198695d9f798fa34d/os-availability-zone\");\n      AvailabilityZoneApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/availability_zones_list.json\")).build()\n      ).getAvailabilityZoneApi(\"RegionOne\");\n\n      AvailabilityZone availabilityZoneActual = Iterables.getFirst(api.list(), null);\n      AvailabilityZone availabilityZoneExpected = getTestAvailabilityZone();\n\n      assertNotNull(availabilityZoneActual);\n      assertEquals(availabilityZoneActual, availabilityZoneExpected);\n   }\n\n   protected AvailabilityZone getTestAvailabilityZone() {\n      return AvailabilityZone.builder()\n            .name(\"nova\")\n            .available(true)\n            .build();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/test/java/org/jclouds/openstack/cinder/v1/features/AvailabilityZoneApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.cinder.v1.features;\n\nimport com.google.common.base.Strings;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Iterables;\nimport org.jclouds.openstack.cinder.v1.domain.AvailabilityZone;\nimport org.jclouds.openstack.cinder.v1.extensions.AvailabilityZoneApi;\nimport org.jclouds.openstack.cinder.v1.internal.BaseCinderApiLiveTest;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport static org.testng.Assert.assertTrue;\n\n@Test(groups = \"live\", testName = \"AvailabilityZoneApiLiveTest\", singleThreaded = true)\npublic class AvailabilityZoneApiLiveTest extends BaseCinderApiLiveTest {\n\n   private AvailabilityZoneApi availabilityZoneApi;\n\n   public AvailabilityZoneApiLiveTest() {\n      super();\n      provider = \"openstack-cinder\";\n   }\n\n   @BeforeClass(groups = {\"integration\", \"live\"})\n   public void setupContext() {\n      super.setup();\n      String region = Iterables.getFirst(api.getConfiguredRegions(), \"regionOne\");\n      availabilityZoneApi = api.getAvailabilityZoneApi(region);\n   }\n\n   public void testListAvailabilityZones() {\n      ImmutableList<? extends AvailabilityZone> cinderZones = availabilityZoneApi.list().toList();\n\n      assertTrue(!cinderZones.isEmpty());\n      for (AvailabilityZone zone : cinderZones) {\n         assertTrue(!Strings.isNullOrEmpty(zone.getName()));\n         assertTrue(zone.getZoneState().available());\n      }\n\n   }\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/test/java/org/jclouds/openstack/cinder/v1/features/QuotasApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.cinder.v1.features;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.cinder.v1.domain.VolumeQuota;\nimport org.jclouds.openstack.cinder.v1.internal.BaseCinderApiExpectTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"QuotaApiExpectTest\")\npublic class QuotasApiExpectTest extends BaseCinderApiExpectTest {\n\n   public void testGetQuotas() throws Exception {\n      URI endpoint = URI.create(\"http://172.16.0.1:8776/v1/50cdb4c60374463198695d9f798fa34d/os-quota-sets/demo\");\n      QuotaApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/quotas.json\")).build()\n      ).getQuotaApi(\"RegionOne\");\n\n      assertEquals(api.getByTenant(\"demo\"), getTestQuotas());\n   }\n\n   public static VolumeQuota getTestQuotas() {\n      return VolumeQuota.builder()\n            .gigabytes(1000)\n            .volumes(10)\n            .snapshots(20)\n            .id(\"demo\").build();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/test/java/org/jclouds/openstack/cinder/v1/features/QuotasApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.cinder.v1.features;\n\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.concurrent.ExecutionException;\n\nimport org.jclouds.openstack.cinder.v1.domain.VolumeQuota;\nimport org.jclouds.openstack.cinder.v1.internal.BaseCinderApiLiveTest;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Iterables;\n\n@Test(groups = \"live\", testName = \"QuotasApiLiveTest\", singleThreaded = true)\npublic class QuotasApiLiveTest extends BaseCinderApiLiveTest {\n\n   private QuotaApi quotaApi;\n\n   public QuotasApiLiveTest() {\n      super();\n      provider = \"openstack-cinder\";\n   }\n\n   @BeforeClass(groups = {\"integration\", \"live\"})\n   public void setupContext() {\n      super.setup();\n      String region = Iterables.getFirst(api.getConfiguredRegions(), \"nova\");\n      quotaApi = api.getQuotaApi(region);\n   }\n\n   public void testGetStorageQuotas() throws ExecutionException, InterruptedException {\n      VolumeQuota volumeQuota = quotaApi.getByTenant(\"demo\");\n\n      assertTrue(volumeQuota.getGigabytes() >= 0);\n      assertTrue(volumeQuota.getVolumes() >= 0);\n      assertTrue(volumeQuota.getSnapshots() >= 0);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/test/java/org/jclouds/openstack/cinder/v1/features/SnapshotApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.cinder.v1.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.Set;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.openstack.cinder.v1.domain.Snapshot;\nimport org.jclouds.openstack.cinder.v1.domain.SnapshotExtendedAttributes;\nimport org.jclouds.openstack.cinder.v1.domain.Volume;\nimport org.jclouds.openstack.cinder.v1.internal.BaseCinderApiExpectTest;\nimport org.jclouds.openstack.cinder.v1.options.CreateSnapshotOptions;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.io.ByteSource;\n\n/**\n * Tests SnapshotApi Guice wiring and parsing\n */\n@Test(groups = \"unit\", testName = \"SnapshotApiExpectTest\")\npublic class SnapshotApiExpectTest extends BaseCinderApiExpectTest {\n   private DateService dateService = new SimpleDateFormatDateService();\n\n   public void testListSnapshots() {\n      URI endpoint = URI.create(\"http://172.16.0.1:8776/v1/50cdb4c60374463198695d9f798fa34d/snapshots\");\n      SnapshotApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/snapshot_list_simple.json\")).build()\n      ).getSnapshotApi(\"RegionOne\");\n\n      Set<? extends Snapshot> snapshots = api.list().toSet();\n      assertEquals(snapshots, ImmutableSet.of(testSnapshot()));\n   }\n\n   public void testListSnapshotsInDetail() {\n      URI endpoint = URI.create(\"http://172.16.0.1:8776/v1/50cdb4c60374463198695d9f798fa34d/snapshots/detail\");\n      SnapshotApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/snapshot_list_details.json\")).build()\n      ).getSnapshotApi(\"RegionOne\");\n\n      Set<? extends Snapshot> snapshots = api.listInDetail().toSet();\n      assertEquals(snapshots, ImmutableSet.of(testSnapshotDetailed()));\n\n      // double-check individual fields\n      Snapshot snappy = Iterables.getOnlyElement(snapshots);\n      assertEquals(snappy.getId(), \"67d03df1-ce5d-4ba7-adbe-492ceb80170b\");\n      assertEquals(snappy.getVolumeId(), \"ea6f70ef-2784-40b9-9d14-d7f33c507c3f\");\n      assertEquals(snappy.getStatus(), Volume.Status.AVAILABLE);\n      assertEquals(snappy.getDescription(), \"jclouds test snapshot\");\n      assertEquals(snappy.getName(), \"jclouds-test-snapshot\");\n      assertEquals(snappy.getSize(), 1);\n   }\n\n   public void testGetSnapshot() {\n      URI endpoint = URI.create(\"http://172.16.0.1:8776/v1/50cdb4c60374463198695d9f798fa34d/snapshots/67d03df1-ce5d-4ba7-adbe-492ceb80170b\");\n      SnapshotApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/snapshot_get.json\")).build()\n      ).getSnapshotApi(\"RegionOne\");\n\n      Snapshot snapshot = api.get(\"67d03df1-ce5d-4ba7-adbe-492ceb80170b\");\n      assertEquals(snapshot, testSnapshotDetailed());\n   }\n\n   public void testCreateSnapshot() {\n      URI endpoint = URI.create(\"http://172.16.0.1:8776/v1/50cdb4c60374463198695d9f798fa34d/snapshots\");\n      SnapshotApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint)\n                  .method(\"POST\")\n                  .payload(payloadFromResourceWithContentType(\"/snapshot_create.json\", MediaType.APPLICATION_JSON))\n                  .build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/snapshot_create_response.json\")).build()\n      ).getSnapshotApi(\"RegionOne\");\n\n      CreateSnapshotOptions options = CreateSnapshotOptions.Builder\n            .name(\"jclouds-test-snapshot\")\n            .description(\"jclouds test snapshot\")\n            .force();\n\n      Snapshot snapshot = api.create(\"ea6f70ef-2784-40b9-9d14-d7f33c507c3f\", options);\n      assertEquals(snapshot, testSnapshotCreate());\n   }\n\n   @Test(expectedExceptions = IllegalStateException.class)\n   public void testCreateSnapshotVolumeIllegalStateFail() {\n      URI endpoint = URI.create(\"http://172.16.0.1:8776/v1/50cdb4c60374463198695d9f798fa34d/snapshots\");\n      SnapshotApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint)\n                  .method(\"POST\")\n                  .payload(payloadFromResourceWithContentType(\"/snapshot_create.json\", MediaType.APPLICATION_JSON))\n                  .build(),\n            HttpResponse.builder()\n                  .statusCode(400)\n                  .payload(Payloads.newByteSourcePayload(ByteSource\n                        .wrap(\"{\\\"badRequest\\\": {\\\"message\\\": \\\"Invalid volume: must be available\\\", \\\"code\\\": 400}}\"\n                              .getBytes())))\n                  .build()\n      ).getSnapshotApi(\"RegionOne\");\n\n      CreateSnapshotOptions options = CreateSnapshotOptions.Builder\n            .name(\"jclouds-test-snapshot\")\n            .description(\"jclouds test snapshot\")\n            .force();\n\n      api.create(\"ea6f70ef-2784-40b9-9d14-d7f33c507c3f\", options);\n   }\n\n   public void testDeleteSnapshot() {\n      URI endpoint = URI.create(\"http://172.16.0.1:8776/v1/50cdb4c60374463198695d9f798fa34d/snapshots/67d03df1-ce5d-4ba7-adbe-492ceb80170b\");\n      SnapshotApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint).method(\"DELETE\").build(),\n            HttpResponse.builder().statusCode(200).build()\n      ).getSnapshotApi(\"RegionOne\");\n\n      assertTrue(api.delete(\"67d03df1-ce5d-4ba7-adbe-492ceb80170b\"));\n   }\n\n   @Test(expectedExceptions = IllegalStateException.class)\n   public void testDeleteSnapshotIllegalStateFail() {\n      URI endpoint = URI.create(\"http://172.16.0.1:8776/v1/50cdb4c60374463198695d9f798fa34d/snapshots/67d03df1-ce5d-4ba7-adbe-492ceb80170b\");\n      SnapshotApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint).method(\"DELETE\").build(),\n            HttpResponse.builder()\n                  .statusCode(400)\n                  .payload(Payloads.newByteSourcePayload(ByteSource\n                        .wrap(\"{\\\"badRequest\\\": {\\\"message\\\": \\\"Invalid volume: Volume Snapshot status must be available or error\\\", \\\"code\\\": 400}}\"\n                              .getBytes())))\n                  .build()\n      ).getSnapshotApi(\"RegionOne\");\n\n      api.delete(\"67d03df1-ce5d-4ba7-adbe-492ceb80170b\");\n   }\n\n   protected Snapshot testSnapshotCreate() {\n      return Snapshot.builder()\n            .id(\"67d03df1-ce5d-4ba7-adbe-492ceb80170b\")\n            .volumeId(\"ea6f70ef-2784-40b9-9d14-d7f33c507c3f\")\n            .description(\"jclouds test snapshot\")\n            .status(Volume.Status.CREATING)\n            .name(\"jclouds-test-snapshot\")\n            .size(1)\n            .created(dateService.iso8601DateParse(\"2012-11-02T16:23:27.000000\"))\n            .build();\n   }\n\n   protected Snapshot testSnapshot() {\n      return Snapshot.builder()\n            .id(\"67d03df1-ce5d-4ba7-adbe-492ceb80170b\")\n            .volumeId(\"ea6f70ef-2784-40b9-9d14-d7f33c507c3f\")\n            .description(\"jclouds test snapshot\")\n            .status(Volume.Status.AVAILABLE)\n            .name(\"jclouds-test-snapshot\")\n            .size(1)\n            .created(dateService.iso8601DateParse(\"2012-11-02T16:23:27.000000\"))\n            .build();\n   }\n\n   protected Snapshot testSnapshotDetailed() {\n      return Snapshot.builder()\n            .id(\"67d03df1-ce5d-4ba7-adbe-492ceb80170b\")\n            .volumeId(\"ea6f70ef-2784-40b9-9d14-d7f33c507c3f\")\n            .description(\"jclouds test snapshot\")\n            .status(Volume.Status.AVAILABLE)\n            .name(\"jclouds-test-snapshot\")\n            .size(1)\n            .created(dateService.iso8601DateParse(\"2012-11-02T16:23:27.000000\"))\n            .extendedAttributes(SnapshotExtendedAttributes.builder().projectId(\"cc03fd4f503f4d9c986b381b8abe6af5\").progress(\"100%\").build())\n            .build();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/test/java/org/jclouds/openstack/cinder/v1/features/VolumeAndSnapshotApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.cinder.v1.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\n\nimport org.jclouds.openstack.cinder.v1.domain.Snapshot;\nimport org.jclouds.openstack.cinder.v1.domain.Volume;\nimport org.jclouds.openstack.cinder.v1.internal.BaseCinderApiLiveTest;\nimport org.jclouds.openstack.cinder.v1.options.CreateSnapshotOptions;\nimport org.jclouds.openstack.cinder.v1.options.CreateVolumeOptions;\nimport org.jclouds.openstack.cinder.v1.predicates.SnapshotPredicates;\nimport org.jclouds.openstack.cinder.v1.predicates.VolumePredicates;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Objects;\nimport com.google.common.collect.Iterables;\n\n/**\n * Tests behavior of VolumeApi\n */\n@Test(groups = \"live\", testName = \"VolumeApiLiveTest\", singleThreaded = true)\npublic class VolumeAndSnapshotApiLiveTest extends BaseCinderApiLiveTest {\n   private static final String name = System.getProperty(\"user.name\").replace('.', '-').toLowerCase();\n\n   private String region;\n\n   private VolumeApi volumeApi;\n   private SnapshotApi snapshotApi;\n\n   private Volume testVolume;\n   private Snapshot testSnapshot;\n\n   @BeforeClass(groups = {\"integration\", \"live\"})\n   @Override\n   public void setup() {\n      super.setup();\n      region = Iterables.getLast(api.getConfiguredRegions(), \"nova\");\n      volumeApi = api.getVolumeApi(region);\n      snapshotApi = api.getSnapshotApi(region);\n   }\n\n   @AfterClass(groups = { \"integration\", \"live\" })\n   @Override\n   protected void tearDown() {\n      if (testSnapshot != null) {\n         assertTrue(snapshotApi.delete(testSnapshot.getId()));\n         assertTrue(SnapshotPredicates.awaitDeleted(snapshotApi).apply(testSnapshot));\n      }\n\n      if (testVolume != null) {\n         assertTrue(volumeApi.delete(testVolume.getId()));\n         assertTrue(VolumePredicates.awaitDeleted(volumeApi).apply(testVolume));\n      }\n\n      super.tearDown();\n   }\n\n   public void testCreateVolume() {\n      CreateVolumeOptions options = CreateVolumeOptions.Builder\n            .name(name)\n            .description(\"description of test volume\");\n      testVolume = volumeApi.create(100, options);\n\n      assertTrue(VolumePredicates.awaitAvailable(volumeApi).apply(testVolume));\n   }\n\n   @Test(dependsOnMethods = \"testCreateVolume\")\n   public void testListVolumes() {\n      Set<? extends Volume> volumes = volumeApi.list().toSet();\n      assertNotNull(volumes);\n      boolean foundIt = false;\n      for (Volume vol : volumes) {\n         Volume details = volumeApi.get(vol.getId());\n         assertNotNull(details);\n         if (Objects.equal(details.getId(), testVolume.getId())) {\n            foundIt = true;\n            break;\n         }\n      }\n      assertTrue(foundIt, \"Failed to find the volume we created in list() response\");\n   }\n\n   @Test(dependsOnMethods = \"testCreateVolume\")\n   public void testListVolumesInDetail() {\n      Set<? extends Volume> volumes = volumeApi.listInDetail().toSet();\n      assertNotNull(volumes);\n      boolean foundIt = false;\n      for (Volume vol : volumes) {\n         Volume details = volumeApi.get(vol.getId());\n         assertNotNull(details);\n         assertNotNull(details.getId());\n         assertNotNull(details.getCreated());\n         assertTrue(details.getSize() > -1);\n\n         assertEquals(details.getId(), vol.getId());\n         assertEquals(details.getSize(), vol.getSize());\n         assertEquals(details.getName(), vol.getName());\n         assertEquals(details.getDescription(), vol.getDescription());\n         assertEquals(details.getCreated(), vol.getCreated());\n         assertEquals(details.getTenantId(), vol.getTenantId());\n         if (Objects.equal(details.getId(), testVolume.getId())) {\n            foundIt = true;\n            break;\n         }\n      }\n      assertTrue(foundIt, \"Failed to find the volume we previously created in listInDetail() response\");\n   }\n\n   @Test(dependsOnMethods = \"testCreateVolume\")\n   public void testCreateSnapshot() {\n      testSnapshot = snapshotApi.create(\n               testVolume.getId(),\n               CreateSnapshotOptions.Builder.name(\"jclouds-live-test\").description(\n                        \"jclouds live test snapshot\").force());\n      assertNotNull(testSnapshot);\n      assertNotNull(testSnapshot.getId());\n      assertNotNull(testSnapshot.getStatus());\n      assertTrue(testSnapshot.getSize() > -1);\n      assertNotNull(testSnapshot.getCreated());\n\n      assertTrue(SnapshotPredicates.awaitAvailable(snapshotApi).apply(testSnapshot));\n   }\n\n   @Test(dependsOnMethods = \"testCreateSnapshot\")\n   public void testListSnapshots() {\n      Set<? extends Snapshot> snapshots = snapshotApi.listInDetail().toSet();\n      assertNotNull(snapshots);\n      boolean foundIt = false;\n      for (Snapshot snap : snapshots) {\n         Snapshot details = snapshotApi.get(snap.getId());\n         if (Objects.equal(snap.getVolumeId(), testVolume.getId())) {\n            foundIt = true;\n         }\n         assertNotNull(details);\n         assertEquals(details.getId(), snap.getId());\n         assertEquals(details.getVolumeId(), snap.getVolumeId());\n         assertEquals(details.getExtendedAttributes(), snap.getExtendedAttributes());\n      }\n     assertTrue(foundIt, \"Failed to find the snapshot we previously created in listSnapshots() response\");\n   }\n\n   @Test(dependsOnMethods = \"testCreateSnapshot\")\n   public void testListSnapshotsInDetail() {\n      Set<? extends Snapshot> snapshots = snapshotApi.listInDetail().toSet();\n      assertNotNull(snapshots);\n      boolean foundIt = false;\n      for (Snapshot snap : snapshots) {\n         Snapshot details = snapshotApi.get(snap.getId());\n         if (Objects.equal(snap.getVolumeId(), testVolume.getId())) {\n            foundIt = true;\n            assertSame(details, testSnapshot);\n         }\n         assertSame(details, snap);\n      }\n\n      assertTrue(foundIt, \"Failed to find the snapshot we created in listSnapshotsInDetail() response\");\n   }\n\n   private void assertSame(Snapshot a, Snapshot b) {\n      assertNotNull(a);\n      assertNotNull(b);\n      assertEquals(a.getId(), b.getId());\n      assertEquals(a.getDescription(), b.getDescription());\n      assertEquals(a.getName(), b.getName());\n      assertEquals(a.getVolumeId(), b.getVolumeId());\n   }\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/test/java/org/jclouds/openstack/cinder/v1/features/VolumeApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.cinder.v1.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.Set;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.cinder.v1.domain.Volume;\nimport org.jclouds.openstack.cinder.v1.domain.VolumeAttachment;\nimport org.jclouds.openstack.cinder.v1.internal.BaseCinderApiExpectTest;\nimport org.jclouds.openstack.cinder.v1.options.CreateVolumeOptions;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\n\n/**\n * Tests VolumeApi Guice wiring and parsing\n */\n@Test(groups = \"unit\", testName = \"VolumeApiExpectTest\")\npublic class VolumeApiExpectTest extends BaseCinderApiExpectTest {\n   private DateService dateService = new SimpleDateFormatDateService();\n\n   public void testListVolumes() {\n      URI endpoint = URI.create(\"http://172.16.0.1:8776/v1/50cdb4c60374463198695d9f798fa34d/volumes\");\n      VolumeApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, \n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/volume_list_simple.json\")).build()\n      ).getVolumeApi(\"RegionOne\");\n\n      Set<? extends Volume> volumes = api.list().toSet();\n      assertEquals(volumes, ImmutableSet.of(testVolume()));\n   }\n   \n   public void testListVolumesInDetail() {\n      URI endpoint = URI.create(\"http://172.16.0.1:8776/v1/50cdb4c60374463198695d9f798fa34d/volumes/detail\");\n      VolumeApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/volume_list_details.json\")).build()\n      ).getVolumeApi(\"RegionOne\");\n\n      Set<? extends Volume> volumes = api.listInDetail().toSet();\n      assertEquals(volumes, ImmutableSet.of(testVolumeDetailed()));\n   }\n\n   public void testCreateVolume() {\n      URI endpoint = URI.create(\"http://172.16.0.1:8776/v1/50cdb4c60374463198695d9f798fa34d/volumes\");\n      VolumeApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint)\n                  .method(\"POST\")\n                  .payload(payloadFromResourceWithContentType(\"/volume_create.json\", MediaType.APPLICATION_JSON))\n                  .build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/volume_create_response.json\")).build()\n      ).getVolumeApi(\"RegionOne\");\n\n      CreateVolumeOptions options = CreateVolumeOptions.Builder\n            .name(\"jclouds-test-volume\")\n            .description(\"description of test volume\");\n      Volume volume = api.create(1, options);\n      assertEquals(volume, testVolumeCreate());\n   }\n\n   public void testGetVolume() {\n      URI endpoint = URI.create(\"http://172.16.0.1:8776/v1/50cdb4c60374463198695d9f798fa34d/volumes/60761c60-0f56-4499-b522-ff13e120af10\");\n      VolumeApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/volume_get.json\")).build()\n      ).getVolumeApi(\"RegionOne\");\n\n      Volume volume = api.get(\"60761c60-0f56-4499-b522-ff13e120af10\");\n      assertEquals(volume, testVolume());\n      // double-check equals()\n      assertEquals(volume.getName(), \"test\");\n      assertEquals(volume.getZone(), \"nova\");\n      assertEquals(volume.getStatus(), Volume.Status.IN_USE);\n      assertEquals(volume.getDescription(), \"This is a test volume\");\n      assertEquals(Iterables.getOnlyElement(volume.getAttachments()), testAttachment());\n   }\n\n   public void testDeleteVolume() {\n      URI endpoint = URI.create(\"http://172.16.0.1:8776/v1/50cdb4c60374463198695d9f798fa34d/volumes/60761c60-0f56-4499-b522-ff13e120af10\");\n      VolumeApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint).method(\"DELETE\").build(),\n            HttpResponse.builder().statusCode(202).build()\n      ).getVolumeApi(\"RegionOne\");\n\n      assertTrue(api.delete(\"60761c60-0f56-4499-b522-ff13e120af10\"));\n   }\n\n   protected Volume testVolumeCreate() {\n      return Volume.builder()\n            .id(\"60761c60-0f56-4499-b522-ff13e120af10\")\n            .size(1)\n            .name(\"jclouds-test-volume\")\n            .zone(\"nova\")\n            .status(Volume.Status.CREATING)\n            .volumeType(\"None\")\n            .description(\"description of test volume\")\n            .created(dateService.iso8601DateParse(\"2012-10-29T20:53:28.000000\"))\n            .build();\n   }\n\n   protected Volume testVolume() {\n      return Volume.builder()\n            .id(\"60761c60-0f56-4499-b522-ff13e120af10\")\n            .size(1)\n            .name(\"test\")\n            .zone(\"nova\")\n            .status(Volume.Status.IN_USE)\n            .volumeType(\"None\")\n            .description(\"This is a test volume\")\n            .attachments(ImmutableSet.of(testAttachment()))\n            .created(dateService.iso8601DateParse(\"2012-10-29T20:53:28.000000\"))\n            .build();\n   }\n\n   protected Volume testVolumeDetailed() {\n      return Volume.builder()\n            .id(\"60761c60-0f56-4499-b522-ff13e120af10\")\n            .size(1)\n            .name(\"test\")\n            .zone(\"nova\")\n            .status(Volume.Status.IN_USE)\n            .volumeType(\"None\")\n            .description(\"This is a test volume\")\n            .attachments(ImmutableSet.of(testAttachment()))\n            .created(dateService.iso8601DateParse(\"2012-10-29T20:53:28.000000\"))\n            .tenantId(\"0ad7eca25ff847b2947a7865b82b851c\")\n            .build();\n   }\n\n   protected VolumeAttachment testAttachment() {\n      return VolumeAttachment.builder()\n            .id(\"60761c60-0f56-4499-b522-ff13e120af10\")\n            .volumeId(\"60761c60-0f56-4499-b522-ff13e120af10\")\n            .serverId(\"0229a1c1-d54a-4836-8527-2ab28b42e2bb\")\n            .device(\"/dev/vdc\")\n            .build();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/test/java/org/jclouds/openstack/cinder/v1/features/VolumeTypeApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.cinder.v1.features;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\nimport java.util.Set;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.cinder.v1.domain.VolumeType;\nimport org.jclouds.openstack.cinder.v1.internal.BaseCinderApiExpectTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests Guice wiring and parsing of VolumeTypeApi\n */\n@Test(groups = \"unit\", testName = \"VolumeTypeApiExpectTest\")\npublic class VolumeTypeApiExpectTest extends BaseCinderApiExpectTest {\n   private DateService dateService = new SimpleDateFormatDateService();\n\n   public void testListVolumeTypes() {\n      URI endpoint = URI.create(\"http://172.16.0.1:8776/v1/50cdb4c60374463198695d9f798fa34d/types\");\n      VolumeTypeApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/volume_type_list_simple.json\")).build()\n      ).getVolumeTypeApi(\"RegionOne\");\n\n      Set<? extends VolumeType> types = api.list().toSet();\n      assertEquals(types, testVolumeTypes());\n   }\n\n   public void testGetVolumeType() {\n      URI endpoint = URI.create(\"http://172.16.0.1:8776/v1/50cdb4c60374463198695d9f798fa34d/types/1\");\n      VolumeTypeApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/volume_type_get.json\")).build()\n      ).getVolumeTypeApi(\"RegionOne\");\n\n      VolumeType type = api.get(\"1\");\n      assertEquals(type, testVolumeType());\n   }\n\n   public VolumeType testVolumeType() {\n      return VolumeType.builder()\n            .id(\"1\")\n            .name(\"jclouds-test-1\")\n            .created(dateService.iso8601SecondsDateParse(\"2012-05-10 12:33:06\"))\n            .extraSpecs(ImmutableMap.of(\"test\", \"value1\", \"test1\", \"wibble\"))\n            .build();\n   }\n   public Set<VolumeType> testVolumeTypes() {\n      VolumeType firstVolumeType = testVolumeType();\n      VolumeType secondVolumeTypeWithEmptyExtraSpecs = VolumeType.builder()\n              .id(\"2\")\n              .name(\"jclouds-test-2\")\n              .created(dateService.iso8601SecondsDateParse(\"2012-05-10 12:33:06\"))\n              .build();\n      VolumeType thirdVolumeTypeWithNullableExtraSpecs = VolumeType.builder()\n              .id(\"3\")\n              .name(\"jclouds-test-3\")\n              .created(dateService.iso8601SecondsDateParse(\"2012-05-10 12:33:06\"))\n              .extraSpecs(null)\n              .build();\n      return ImmutableSet.of(firstVolumeType, secondVolumeTypeWithEmptyExtraSpecs, thirdVolumeTypeWithNullableExtraSpecs);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/test/java/org/jclouds/openstack/cinder/v1/features/VolumeTypeApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.cinder.v1.features;\n\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.Set;\n\nimport org.jclouds.openstack.cinder.v1.domain.VolumeType;\nimport org.jclouds.openstack.cinder.v1.internal.BaseCinderApiLiveTest;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeGroups;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Iterables;\n\n/**\n * Tests behavior of VolumeTypeApi.\n */\n@Test(groups = \"live\", testName = \"VolumeTypeApiLiveTest\", singleThreaded = true)\npublic class VolumeTypeApiLiveTest extends BaseCinderApiLiveTest {\n   private VolumeTypeApi volumeTypeApi;\n   private String region;\n\n   @BeforeGroups(groups = {\"integration\", \"live\"})\n   @Override\n   public void setup() {\n      super.setup();\n      region = Iterables.getLast(api.getConfiguredRegions(), \"nova\");\n      volumeTypeApi = api.getVolumeTypeApi(region);\n   }\n\n   @AfterClass(groups = { \"integration\", \"live\" })\n   @Override\n   protected void tearDown() {\n      super.tearDown();\n   }\n\n   public void testListAndGetVolumeTypes() {\n      Set<? extends VolumeType> volumeTypes = volumeTypeApi.list().toSet();\n      assertNotNull(volumeTypes);\n\n      for (VolumeType vt : volumeTypes) {\n         VolumeType details = volumeTypeApi.get(vt.getId());\n         assertNotNull(details);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/test/java/org/jclouds/openstack/cinder/v1/internal/BaseCinderApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.cinder.v1.internal;\n\nimport org.jclouds.openstack.cinder.v1.CinderApi;\n\n/**\n * Base class for writing Volume Rest Api Expect tests\n */\npublic class BaseCinderApiExpectTest extends BaseCinderExpectTest<CinderApi> {\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/test/java/org/jclouds/openstack/cinder/v1/internal/BaseCinderApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.cinder.v1.internal;\n\nimport java.util.Properties;\n\nimport org.jclouds.apis.BaseApiLiveTest;\nimport org.jclouds.openstack.cinder.v1.CinderApi;\nimport org.jclouds.openstack.keystone.config.KeystoneProperties;\n\n/**\n * Tests behavior of CinderApi\n */\npublic class BaseCinderApiLiveTest extends BaseApiLiveTest<CinderApi> {\n\n   public BaseCinderApiLiveTest() {\n      provider = \"openstack-cinder\";\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      setIfTestSystemPropertyPresent(props, KeystoneProperties.CREDENTIAL_TYPE);\n      return props;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/test/java/org/jclouds/openstack/cinder/v1/internal/BaseCinderExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.cinder.v1.internal;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.keystone.v2_0.internal.KeystoneFixture;\nimport org.jclouds.rest.internal.BaseRestApiExpectTest;\n\n/**\n * Base class for writing Nova Expect tests\n */\npublic class BaseCinderExpectTest<T> extends BaseRestApiExpectTest<T> {\n   protected HttpRequest keystoneAuthWithUsernameAndPassword;\n   protected HttpRequest keystoneAuthWithUsernameAndPasswordAndTenantName;\n   protected HttpRequest keystoneAuthWithAccessKeyAndSecretKeyAndTenantName;\n   protected String authToken;\n   protected HttpResponse responseWithKeystoneAccess;\n   protected HttpRequest extensionsOfNovaRequest;\n   protected HttpResponse extensionsOfNovaResponse;\n   protected HttpResponse unmatchedExtensionsOfNovaResponse;\n   protected HttpRequest keystoneAuthWithAccessKeyAndSecretKeyAndTenantId;\n   protected String identityWithTenantId;\n\n   public BaseCinderExpectTest() {\n      provider = \"openstack-cinder\";\n      keystoneAuthWithUsernameAndPassword = KeystoneFixture.INSTANCE.initialAuthWithUsernameAndPassword(identity,\n            credential);\n      keystoneAuthWithUsernameAndPasswordAndTenantName = KeystoneFixture.INSTANCE.initialAuthWithUsernameAndPasswordAndTenantName(identity,\n            credential);\n      keystoneAuthWithAccessKeyAndSecretKeyAndTenantName = KeystoneFixture.INSTANCE.initialAuthWithAccessKeyAndSecretKeyAndTenantName(identity,\n            credential);\n      keystoneAuthWithAccessKeyAndSecretKeyAndTenantId = KeystoneFixture.INSTANCE.initialAuthWithAccessKeyAndSecretKeyAndTenantId(identity,\n              credential);\n      \n      authToken = KeystoneFixture.INSTANCE.getAuthToken();\n      responseWithKeystoneAccess = KeystoneFixture.INSTANCE.responseWithAccess();\n      // now, createContext arg will need tenant prefix\n      identityWithTenantId = KeystoneFixture.INSTANCE.getTenantId() + \":\" + identity;\n      identity = KeystoneFixture.INSTANCE.getTenantName() + \":\" + identity;\n   }\n\n   @Override\n   protected HttpRequestComparisonType compareHttpRequestAsType(HttpRequest input) {\n      return HttpRequestComparisonType.JSON;\n   }\n   \n   protected HttpRequest.Builder<?> authenticatedGET() {\n      return HttpRequest.builder()\n                        .method(\"GET\")\n                        .addHeader(\"Accept\", MediaType.APPLICATION_JSON)\n                        .addHeader(\"X-Auth-Token\", authToken);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/test/resources/availability_zones_list.json",
    "content": "{\n    \"availabilityZoneInfo\": [{\n        \"zoneState\": {\n            \"available\": true\n        },\n        \"zoneName\": \"nova\"\n    }]\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/test/resources/quotas.json",
    "content": "{\n    \"quota_set\": {\n        \"gigabytes\": 1000,\n        \"volumes\": 10,\n        \"snapshots\": 20,\n        \"id\": \"demo\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/test/resources/snapshot_create.json",
    "content": "{\n    \"snapshot\": {\n        \"display_name\": \"jclouds-test-snapshot\",\n        \"volume_id\": \"ea6f70ef-2784-40b9-9d14-d7f33c507c3f\",\n        \"display_description\": \"jclouds test snapshot\",\n        \"force\": \"true\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/test/resources/snapshot_create_response.json",
    "content": "{\n    \"snapshot\": {\n        \"status\": \"creating\",\n        \"display_name\": \"jclouds-test-snapshot\",\n        \"created_at\": \"2012-11-02T16:23:27.000000\",\n        \"display_description\": \"jclouds test snapshot\",\n        \"volume_id\": \"ea6f70ef-2784-40b9-9d14-d7f33c507c3f\",\n        \"id\": \"67d03df1-ce5d-4ba7-adbe-492ceb80170b\",\n        \"size\": 1\n    }\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/test/resources/snapshot_get.json",
    "content": "{\n    \"snapshot\": {\n        \"status\": \"available\",\n        \"display_name\": \"jclouds-test-snapshot\",\n        \"created_at\": \"2012-11-02T16:23:27.000000\",\n        \"display_description\": \"jclouds test snapshot\",\n        \"os-extended-snapshot-attributes:progress\": \"100%\",\n        \"volume_id\": \"ea6f70ef-2784-40b9-9d14-d7f33c507c3f\",\n        \"os-extended-snapshot-attributes:project_id\": \"cc03fd4f503f4d9c986b381b8abe6af5\",\n        \"id\": \"67d03df1-ce5d-4ba7-adbe-492ceb80170b\",\n        \"size\": 1\n    }\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/test/resources/snapshot_list_details.json",
    "content": "{\n    \"snapshots\": [\n        {\n            \"status\": \"available\",\n            \"display_name\": \"jclouds-test-snapshot\",\n            \"created_at\": \"2012-11-02T16:23:27.000000\",\n            \"display_description\": \"jclouds test snapshot\",\n            \"os-extended-snapshot-attributes:progress\": \"100%\",\n            \"volume_id\": \"ea6f70ef-2784-40b9-9d14-d7f33c507c3f\",\n            \"os-extended-snapshot-attributes:project_id\": \"cc03fd4f503f4d9c986b381b8abe6af5\",\n            \"id\": \"67d03df1-ce5d-4ba7-adbe-492ceb80170b\",\n            \"size\": 1\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/test/resources/snapshot_list_simple.json",
    "content": "{\n    \"snapshots\": [\n        {\n            \"status\": \"available\",\n            \"display_name\": \"jclouds-test-snapshot\",\n            \"created_at\": \"2012-11-02T16:23:27.000000\",\n            \"display_description\": \"jclouds test snapshot\",\n            \"volume_id\": \"ea6f70ef-2784-40b9-9d14-d7f33c507c3f\",\n            \"id\": \"67d03df1-ce5d-4ba7-adbe-492ceb80170b\",\n            \"size\": 1\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/test/resources/volume_create.json",
    "content": "{\n    \"volume\": {\n        \"display_name\": \"jclouds-test-volume\",\n        \"display_description\": \"description of test volume\",\n        \"size\": 1\n    }\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/test/resources/volume_create_response.json",
    "content": "{\n    \"volume\": {\n        \"status\": \"creating\",\n        \"display_name\": \"jclouds-test-volume\",\n        \"attachments\": [],\n        \"availability_zone\": \"nova\",\n        \"created_at\": \"2012-10-29T20:53:28.000000\",\n        \"display_description\": \"description of test volume\",\n        \"volume_type\": \"None\",\n        \"snapshot_id\": null,\n        \"metadata\": {},\n        \"id\": \"60761c60-0f56-4499-b522-ff13e120af10\",\n        \"size\": 1\n    }\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/test/resources/volume_get.json",
    "content": "{\n    \"volume\": {\n        \"status\": \"in-use\",\n        \"display_name\": \"test\",\n        \"attachments\": [\n            {\n                \"device\": \"/dev/vdc\",\n                \"server_id\": \"0229a1c1-d54a-4836-8527-2ab28b42e2bb\",\n                \"id\": \"60761c60-0f56-4499-b522-ff13e120af10\",\n                \"volume_id\": \"60761c60-0f56-4499-b522-ff13e120af10\"\n            }\n        ],\n        \"availability_zone\": \"nova\",\n        \"created_at\": \"2012-10-29T20:53:28.000000\",\n        \"display_description\": \"This is a test volume\",\n        \"volume_type\": \"None\",\n        \"snapshot_id\": null,\n        \"metadata\": {},\n        \"id\": \"60761c60-0f56-4499-b522-ff13e120af10\",\n        \"size\": 1\n    }\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/test/resources/volume_list_details.json",
    "content": "{\n    \"volumes\": [\n        {\n            \"status\": \"in-use\",\n            \"display_name\": \"test\",\n            \"attachments\": [\n                {\n                    \"device\": \"/dev/vdc\",\n                    \"server_id\": \"0229a1c1-d54a-4836-8527-2ab28b42e2bb\",\n                    \"id\": \"60761c60-0f56-4499-b522-ff13e120af10\",\n                    \"volume_id\": \"60761c60-0f56-4499-b522-ff13e120af10\"\n                }\n            ],\n            \"availability_zone\": \"nova\",\n            \"created_at\": \"2012-10-29T20:53:28.000000\",\n            \"os-vol-tenant-attr:tenant_id\": \"0ad7eca25ff847b2947a7865b82b851c\",\n            \"display_description\": \"This is a test volume\",\n            \"volume_type\": \"None\",\n            \"snapshot_id\": null,\n            \"metadata\": {},\n            \"id\": \"60761c60-0f56-4499-b522-ff13e120af10\",\n            \"size\": 1\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/test/resources/volume_list_simple.json",
    "content": "{\n    \"volumes\": [\n        {\n            \"status\": \"in-use\",\n            \"display_name\": \"test\",\n            \"attachments\": [\n                {\n                    \"device\": \"/dev/vdc\",\n                    \"server_id\": \"0229a1c1-d54a-4836-8527-2ab28b42e2bb\",\n                    \"id\": \"60761c60-0f56-4499-b522-ff13e120af10\",\n                    \"volume_id\": \"60761c60-0f56-4499-b522-ff13e120af10\"\n                }\n            ],\n            \"availability_zone\": \"nova\",\n            \"created_at\": \"2012-10-29T20:53:28.000000\",\n            \"display_description\": \"This is a test volume\",\n            \"volume_type\": \"None\",\n            \"snapshot_id\": null,\n            \"metadata\": {},\n            \"id\": \"60761c60-0f56-4499-b522-ff13e120af10\",\n            \"size\": 1\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/test/resources/volume_type_get.json",
    "content": "{\n    \"volume_type\": {\n        \"name\": \"jclouds-test-1\",\n        \"deleted\": false,\n        \"created_at\": \"2012-05-10 12:33:06\",\n        \"updated_at\": null,\n        \"extra_specs\": {\n            \"test\": \"value1\",\n            \"test1\": \"wibble\"\n        },\n        \"deleted_at\": null,\n        \"id\": 1\n    }\n}\n"
  },
  {
    "path": "apis/openstack-cinder/src/test/resources/volume_type_list_simple.json",
    "content": "{\n    \"volume_types\": [\n        {\n            \"name\": \"jclouds-test-1\",\n            \"deleted\": false,\n            \"created_at\": \"2012-05-10 12:33:06\",\n            \"updated_at\": null,\n            \"extra_specs\": {\n                \"test\": \"value1\",\n                \"test1\": \"wibble\"\n            },\n            \"deleted_at\": null,\n            \"id\": 1\n        },\n        {\n            \"name\": \"jclouds-test-2\",\n            \"deleted\": false,\n            \"created_at\": \"2012-05-10 12:33:06\",\n            \"updated_at\": null,\n            \"extra_specs\": {},\n            \"deleted_at\": null,\n            \"id\": 2\n        },\n        {\n            \"name\": \"jclouds-test-3\",\n            \"deleted\": false,\n            \"created_at\": \"2012-05-10 12:33:06\",\n            \"updated_at\": null,\n            \"extra_specs\": null,\n            \"deleted_at\": null,\n            \"id\": 3\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-keystone/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.openstack.keystone.*;version=\"${project.version}\";-noimport:=true,\\\n    org.jclouds.openstack.v2_0.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "apis/openstack-keystone/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.api</groupId>\n  <artifactId>openstack-keystone</artifactId>\n  <name>jclouds openstack-keystone api</name>\n  <description>jclouds components to access an implementation of OpenStack Keystone</description>\n\n  <properties>\n    <!-- keystone version 2 -->\n    <test.openstack-keystone.endpoint>http://localhost:5000/v${jclouds.api-version}/</test.openstack-keystone.endpoint>\n    <test.openstack-keystone.api-version>2.0</test.openstack-keystone.api-version>\n    <test.openstack-keystone.build-version />\n    <test.openstack-keystone.identity>FIXME_TENANT:FIXME_USER</test.openstack-keystone.identity>\n    <test.openstack-keystone.credential>FIXME_PASSWORD</test.openstack-keystone.credential>\n    <!-- keystone version 3 -->\n    <test.openstack-keystone-3.endpoint>http://localhost/identity/v3</test.openstack-keystone-3.endpoint>\n    <test.openstack-keystone-3.api-version>3</test.openstack-keystone-3.api-version>\n    <test.openstack-keystone-3.build-version />\n    <test.openstack-keystone-3.identity>FIXME_DOMAIN:FIXME_USER</test.openstack-keystone-3.identity>\n    <test.openstack-keystone-3.credential>FIXME_PASSWORD</test.openstack-keystone-3.credential>\n    <test.jclouds.keystone.credential-type>passwordCredentials</test.jclouds.keystone.credential-type>\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-slf4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <!-- A driver that supports the PATCH verb is needed for tests -->\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-okhttp</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>ch.qos.logback</groupId>\n      <artifactId>logback-classic</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.squareup.okhttp3</groupId>\n      <artifactId>mockwebserver</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.value</groupId>\n      <artifactId>auto-value</artifactId>\n      <scope>provided</scope>\n    </dependency>\n  </dependencies>\n  \n  <build>\n    <plugins>\n    <!-- Disabling error-prone compiler due to: https://github.com/google/error-prone/issues/711\n         The fix is only available in error-prone versions that do not support Java 7 -->\n      <plugin>\n        <groupId>org.apache.maven.plugins</groupId>\n        <artifactId>maven-compiler-plugin</artifactId>\n        <version>3.8.0</version>\n        <inherited>false</inherited>\n        <configuration>\n          <source>${maven.compile.source}</source>\n          <target>${maven.compile.target}</target>\n          <encoding>${project.build.sourceEncoding}</encoding>\n        </configuration>\n      </plugin>\n    </plugins>\n  </build>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <excludes>\n                    <exclude>none</exclude>\n                  </excludes>\n                  <includes>\n                    <include>**/keystone/v2_0/**/*IntegrationTest.java</include>\n                    <include>**/keystone/v2_0/**/*LiveTest.java</include>\n                  </includes>\n                  <systemPropertyVariables>\n                    <test.openstack-keystone.endpoint>${test.openstack-keystone.endpoint}</test.openstack-keystone.endpoint>\n                    <test.openstack-keystone.api-version>${test.openstack-keystone.api-version}</test.openstack-keystone.api-version>\n                    <test.openstack-keystone.build-version>${test.openstack-keystone.build-version}</test.openstack-keystone.build-version>\n                    <test.openstack-keystone.identity>${test.openstack-keystone.identity}</test.openstack-keystone.identity>\n                    <test.openstack-keystone.credential>${test.openstack-keystone.credential}</test.openstack-keystone.credential>\n                    <test.jclouds.keystone.credential-type>${test.jclouds.keystone.credential-type}</test.jclouds.keystone.credential-type>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n    <profile>\n      <id>live-v3</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <excludes>\n                    <exclude>none</exclude>\n                  </excludes>\n                  <includes>\n                    <include>**/keystone/v3/**/*IntegrationTest.java</include>\n                    <include>**/keystone/v3/**/*LiveTest.java</include>\n                  </includes>\n                  <systemPropertyVariables>\n                    <test.openstack-keystone-3.endpoint>${test.openstack-keystone.endpoint}</test.openstack-keystone-3.endpoint>\n                    <test.openstack-keystone-3.api-version>${test.openstack-keystone.api-version}</test.openstack-keystone-3.api-version>\n                    <test.openstack-keystone-3.build-version>${test.openstack-keystone.build-version}</test.openstack-keystone-3.build-version>\n                    <test.openstack-keystone-3.identity>${test.openstack-keystone-3.identity}</test.openstack-keystone-3.identity>\n                    <test.openstack-keystone-3.credential>${test.openstack-keystone-3.credential}</test.openstack-keystone-3.credential>\n                    <test.jclouds.keystone.credential-type>${test.jclouds.keystone.credential-type}</test.jclouds.keystone.credential-type>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/auth/AuthHeaders.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.auth;\n\npublic final class AuthHeaders {\n\n   public static final String AUTH_USER = \"X-Auth-User\";\n   public static final String AUTH_KEY = \"X-Auth-Key\";\n   public static final String AUTH_TOKEN = \"X-Auth-Token\";\n\n   private AuthHeaders() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/auth/AuthenticationApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.auth;\n\nimport org.jclouds.openstack.keystone.auth.domain.ApiAccessKeyCredentials;\nimport org.jclouds.openstack.keystone.auth.domain.AuthInfo;\nimport org.jclouds.openstack.keystone.auth.domain.TenantOrDomainAndCredentials;\nimport org.jclouds.openstack.keystone.auth.domain.PasswordCredentials;\nimport org.jclouds.openstack.keystone.auth.domain.TokenCredentials;\n\n/**\n * Authentication methods to be implemented to all Keystone authentication APIs.\n */\npublic interface AuthenticationApi {\n\n   AuthInfo authenticatePassword(TenantOrDomainAndCredentials<PasswordCredentials> credentials);\n\n   AuthInfo authenticateAccessKey(TenantOrDomainAndCredentials<ApiAccessKeyCredentials> credentials);\n\n   AuthInfo authenticateToken(TenantOrDomainAndCredentials<TokenCredentials> credentials);\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/auth/config/Authentication.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.auth.config;\n\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\nimport jakarta.inject.Qualifier;\n\n@Retention(value = RetentionPolicy.RUNTIME)\n@Target(value = { ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })\n@Qualifier\npublic @interface Authentication {\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/auth/config/AuthenticationModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.auth.config;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static org.jclouds.rest.config.BinderUtils.bindHttpApi;\n\nimport java.util.Map;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.TimeoutException;\n\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpRetryHandler;\nimport org.jclouds.http.annotation.ClientError;\nimport org.jclouds.location.Provider;\nimport org.jclouds.openstack.keystone.auth.AuthenticationApi;\nimport org.jclouds.openstack.keystone.auth.domain.AuthInfo;\nimport org.jclouds.openstack.keystone.auth.functions.AuthenticateApiAccessKeyCredentials;\nimport org.jclouds.openstack.keystone.auth.functions.AuthenticatePasswordCredentials;\nimport org.jclouds.openstack.keystone.auth.functions.AuthenticateTokenCredentials;\nimport org.jclouds.openstack.keystone.auth.handlers.RetryOnRenew;\nimport org.jclouds.openstack.keystone.config.KeystoneProperties;\nimport org.jclouds.openstack.keystone.v2_0.auth.V2AuthenticationApi;\nimport org.jclouds.openstack.keystone.v3.auth.V3AuthenticationApi;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\nimport com.google.common.collect.Maps;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Injector;\nimport com.google.inject.Provides;\n\npublic class AuthenticationModule extends AbstractModule {\n\n   @Override\n   protected void configure() {\n      bind(HttpRetryHandler.class).annotatedWith(ClientError.class).to(RetryOnRenew.class);\n      bindHttpApi(binder(), V2AuthenticationApi.class);\n      bindHttpApi(binder(), V3AuthenticationApi.class);\n   }\n\n   @Provides\n   @Singleton\n   protected final AuthenticationApi provideAuthenticationApi(Injector i,\n         @Named(KeystoneProperties.KEYSTONE_VERSION) String keystoneVersion) {\n      return authenticationApis(i).get(keystoneVersion);\n   }\n\n   protected Map<String, AuthenticationApi> authenticationApis(Injector i) {\n      Map<String, AuthenticationApi> authenticationApis = Maps.newHashMap();\n      authenticationApis.put(\"2\", i.getInstance(V2AuthenticationApi.class));\n      authenticationApis.put(\"3\", i.getInstance(V3AuthenticationApi.class));\n      return authenticationApis;\n   }\n\n   /**\n    * borrowing concurrency code to ensure that caching takes place properly\n    */\n   @Provides\n   @Singleton\n   @Authentication\n   protected final Supplier<String> provideAuthenticationTokenCache(final Supplier<AuthInfo> supplier)\n         throws InterruptedException, ExecutionException, TimeoutException {\n      return new Supplier<String>() {\n         @Override\n         public String get() {\n            return supplier.get().getAuthToken();\n         }\n      };\n   }\n\n   @Provides\n   @Singleton\n   protected final Map<String, Function<Credentials, AuthInfo>> provideAuthenticationMethods(Injector i) {\n      return authenticationMethods(i);\n   }\n\n   protected Map<String, Function<Credentials, AuthInfo>> authenticationMethods(Injector i) {\n      Builder<Function<Credentials, AuthInfo>> fns = ImmutableSet.builder();\n      fns.add(i.getInstance(AuthenticatePasswordCredentials.class));\n      fns.add(i.getInstance(AuthenticateApiAccessKeyCredentials.class));\n      fns.add(i.getInstance(AuthenticateTokenCredentials.class));\n      return CredentialTypes.indexByCredentialType(fns.build());\n   }\n\n   @Provides\n   @Singleton\n   protected final Function<Credentials, AuthInfo> authenticationMethodForCredentialType(\n         @Named(KeystoneProperties.CREDENTIAL_TYPE) String credentialType,\n         Map<String, Function<Credentials, AuthInfo>> authenticationMethods) {\n      checkArgument(authenticationMethods.containsKey(credentialType), \"credential type %s not in supported list: %s\",\n            credentialType, authenticationMethods.keySet());\n      return authenticationMethods.get(credentialType);\n   }\n\n   // TODO: what is the timeout of the session token? modify default accordingly\n   // PROPERTY_SESSION_INTERVAL is default to 60 seconds, but we have this here\n   // at 11 hours for now.\n   @Provides\n   @Singleton\n   public final LoadingCache<Credentials, AuthInfo> provideAuthInfoCache(Function<Credentials, AuthInfo> getAccess) {\n      return CacheBuilder.newBuilder().expireAfterWrite(11, TimeUnit.HOURS).build(CacheLoader.from(getAccess));\n   }\n\n   // Temporary conversion of a cache to a supplier until there is a\n   // single-element cache\n   // http://code.google.com/p/guava-libraries/issues/detail?id=872\n   @Provides\n   @Singleton\n   protected final Supplier<AuthInfo> provideAuthInfoSupplier(final LoadingCache<Credentials, AuthInfo> cache,\n         @Provider final Supplier<Credentials> creds) {\n      return new Supplier<AuthInfo>() {\n         @Override\n         public AuthInfo get() {\n            return cache.getUnchecked(creds.get());\n         }\n      };\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/auth/config/CredentialType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.auth.config;\n\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\nimport jakarta.inject.Qualifier;\n\n/**\n * @see CredentialTypes\n */\n@Retention(value = RetentionPolicy.RUNTIME)\n@Target(value = { ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })\n@Qualifier\npublic @interface CredentialType {\n   /**\n    * @see CredentialTypes\n    */\n   String value();\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/auth/config/CredentialTypes.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.auth.config;\n\nimport static com.google.common.base.Preconditions.checkArgument;\n\nimport java.util.Map;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.Maps;\n\n/**\n * Configuration properties and constants used in Keystone connections.\n */\npublic class CredentialTypes {\n\n   public static final String API_ACCESS_KEY_CREDENTIALS = \"apiAccessKeyCredentials\";\n\n   public static final String PASSWORD_CREDENTIALS = \"passwordCredentials\";\n\n   public static final String TOKEN_CREDENTIALS = \"tokenCredentials\";\n\n   public static <T> String credentialTypeOf(T input) {\n      Class<?> authenticationType = input.getClass();\n      CredentialType credentialType = findCredentialType(authenticationType);\n      checkArgument(credentialType != null, \"programming error: %s should have annotation %s\", authenticationType,\n            CredentialType.class.getName());\n      return credentialType.value();\n   }\n\n   public static <T> Map<String, T> indexByCredentialType(Iterable<T> iterable) {\n      return Maps.uniqueIndex(iterable, new Function<T, String>() {\n         @Override\n         public String apply(T input) {\n            return credentialTypeOf(input);\n         }\n      });\n   }\n\n   /**\n    * Find an annotation in teh given class or their parents. We need this since\n    * AutoValue classes inherit the classes we define.\n    */\n   public static CredentialType findCredentialType(Class<?> input) {\n      if (input == null)\n         return null;\n      CredentialType ann = input.getAnnotation(CredentialType.class);\n      return ann != null ? ann : findCredentialType(input.getSuperclass());\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/auth/domain/ApiAccessKeyCredentials.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.auth.domain;\n\nimport static org.jclouds.openstack.keystone.auth.config.CredentialTypes.API_ACCESS_KEY_CREDENTIALS;\n\nimport org.jclouds.openstack.keystone.auth.config.CredentialType;\n\nimport com.google.auto.value.AutoValue;\n\n@CredentialType(API_ACCESS_KEY_CREDENTIALS)\n@AutoValue\npublic abstract class ApiAccessKeyCredentials {\n\n   public abstract String accessKey();\n   public abstract String secretKey();\n\n   public static ApiAccessKeyCredentials create(String accessKey, String secretKey) {\n      return builder().accessKey(accessKey).secretKey(secretKey).build();\n   }\n\n   ApiAccessKeyCredentials() {\n\n   }\n\n   public static Builder builder() {\n      return new AutoValue_ApiAccessKeyCredentials.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder accessKey(String accessKey);\n      public abstract Builder secretKey(String secretKey);\n\n      public abstract ApiAccessKeyCredentials build();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/auth/domain/AuthInfo.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.auth.domain;\n\n/**\n * Common interface for authentication objects.\n */\npublic interface AuthInfo {\n\n   String getAuthToken();\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/auth/domain/PasswordCredentials.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.auth.domain;\n\nimport static org.jclouds.openstack.keystone.auth.config.CredentialTypes.PASSWORD_CREDENTIALS;\n\nimport org.jclouds.openstack.keystone.auth.config.CredentialType;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.base.MoreObjects;\n\n@CredentialType(PASSWORD_CREDENTIALS)\n@AutoValue\npublic abstract class PasswordCredentials {\n\n   public abstract String username();\n   public abstract String password();\n\n   public static PasswordCredentials create(String username, String password) {\n      return builder().username(username).password(password).build();\n   }\n\n   PasswordCredentials() {\n\n   }\n   \n   @Override\n   public final String toString() {\n      return MoreObjects.toStringHelper(this).add(\"username\", username())\n            .add(\"password\", password() == null ? null : \"*****\").toString();\n   }\n\n   public static Builder builder() {\n      return new AutoValue_PasswordCredentials.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder username(String username);\n      public abstract Builder password(String password);\n      \n      public abstract PasswordCredentials build();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/auth/domain/TenantOrDomainAndCredentials.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.auth.domain;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.auto.value.AutoValue;\n\n/**\n * Keystone credentials with tenant. Configure the tenant properties to the\n * configured context credentials.\n */\n@AutoValue\npublic abstract class TenantOrDomainAndCredentials<T> {\n\n   @Nullable public abstract String tenantOrDomainId();\n   @Nullable public abstract String tenantOrDomainName();\n   @Nullable public abstract String scope();\n   @Nullable public abstract String projectDomainName();\n   @Nullable public abstract String projectDomainId();\n   public abstract T credentials(); \n\n   TenantOrDomainAndCredentials() {\n\n   }\n\n   public static <T> Builder<T> builder() {\n      return new AutoValue_TenantOrDomainAndCredentials.Builder<T>();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder<T> {\n      public abstract Builder<T> tenantOrDomainId(String tenantId);\n      public abstract Builder<T> tenantOrDomainName(String tenantName);\n      public abstract Builder<T> scope(String scope);\n      public abstract Builder<T> projectDomainName(String projectDomainName);\n      public abstract Builder<T> projectDomainId(String projectDomainId); \n      public abstract Builder<T> credentials(T credentials);\n\n      public abstract TenantOrDomainAndCredentials<T> build();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/auth/domain/TokenCredentials.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.auth.domain;\n\nimport static org.jclouds.openstack.keystone.auth.config.CredentialTypes.TOKEN_CREDENTIALS;\n\nimport org.jclouds.openstack.keystone.auth.config.CredentialType;\n\nimport com.google.auto.value.AutoValue;\n\n@CredentialType(TOKEN_CREDENTIALS)\n@AutoValue\npublic abstract class TokenCredentials {\n\n   public abstract String id();\n\n   public static TokenCredentials create(String id) {\n      return builder().id(id).build();\n   }\n\n   TokenCredentials() {\n\n   }\n\n   public static Builder builder() {\n      return new AutoValue_TokenCredentials.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder id(String id);\n\n      public abstract TokenCredentials build();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/auth/filters/AuthenticateRequest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.auth.filters;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpRequestFilter;\nimport org.jclouds.openstack.keystone.auth.AuthHeaders;\nimport org.jclouds.openstack.keystone.auth.config.Authentication;\n\nimport com.google.common.base.Supplier;\n\n/**\n * Signs the Keystone-based request. This will update the Authentication Token before 24 hours is up.\n */\n@Singleton\npublic class AuthenticateRequest implements HttpRequestFilter {\n\n   private final Supplier<String> authTokenProvider;\n\n   @Inject\n   AuthenticateRequest(@Authentication Supplier<String> authTokenProvider) {\n      this.authTokenProvider = authTokenProvider;\n   }\n\n   @Override\n   public HttpRequest filter(HttpRequest request) throws HttpException {\n      return request.toBuilder().replaceHeader(AuthHeaders.AUTH_TOKEN, authTokenProvider.get()).build();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/auth/functions/AuthenticateApiAccessKeyCredentials.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.auth.functions;\n\nimport static org.jclouds.openstack.keystone.auth.config.CredentialTypes.API_ACCESS_KEY_CREDENTIALS;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.openstack.keystone.auth.AuthenticationApi;\nimport org.jclouds.openstack.keystone.auth.config.CredentialType;\nimport org.jclouds.openstack.keystone.auth.domain.ApiAccessKeyCredentials;\nimport org.jclouds.openstack.keystone.auth.domain.AuthInfo;\nimport org.jclouds.openstack.keystone.auth.domain.TenantOrDomainAndCredentials;\n\n@CredentialType(API_ACCESS_KEY_CREDENTIALS)\n@Singleton\npublic class AuthenticateApiAccessKeyCredentials extends BaseAuthenticator<ApiAccessKeyCredentials> {\n\n   private final AuthenticationApi auth;\n\n   @Inject\n   AuthenticateApiAccessKeyCredentials(AuthenticationApi auth) {\n      this.auth = auth;\n   }\n\n   @Override\n   public ApiAccessKeyCredentials createCredentials(String identity, String credential) {\n      return ApiAccessKeyCredentials.builder().accessKey(identity).secretKey(credential).build();\n   }\n\n   @Override\n   public AuthInfo authenticate(TenantOrDomainAndCredentials<ApiAccessKeyCredentials> credentials) {\n      return auth.authenticateAccessKey(credentials);\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/auth/functions/AuthenticatePasswordCredentials.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.auth.functions;\n\nimport static org.jclouds.openstack.keystone.auth.config.CredentialTypes.PASSWORD_CREDENTIALS;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.openstack.keystone.auth.AuthenticationApi;\nimport org.jclouds.openstack.keystone.auth.config.CredentialType;\nimport org.jclouds.openstack.keystone.auth.domain.AuthInfo;\nimport org.jclouds.openstack.keystone.auth.domain.TenantOrDomainAndCredentials;\nimport org.jclouds.openstack.keystone.auth.domain.PasswordCredentials;\n\n@CredentialType(PASSWORD_CREDENTIALS)\n@Singleton\npublic class AuthenticatePasswordCredentials extends BaseAuthenticator<PasswordCredentials> {\n\n   private final AuthenticationApi auth;\n\n   @Inject\n   AuthenticatePasswordCredentials(AuthenticationApi auth) {\n      this.auth = auth;\n   }\n\n   @Override\n   public PasswordCredentials createCredentials(String identity, String credential) {\n      return PasswordCredentials.builder().username(identity).password(credential).build();\n   }\n\n   @Override\n   public AuthInfo authenticate(TenantOrDomainAndCredentials<PasswordCredentials> credentials) {\n      return auth.authenticatePassword(credentials);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/auth/functions/AuthenticateTokenCredentials.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.auth.functions;\n\nimport static org.jclouds.openstack.keystone.auth.config.CredentialTypes.TOKEN_CREDENTIALS;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.openstack.keystone.auth.AuthenticationApi;\nimport org.jclouds.openstack.keystone.auth.config.CredentialType;\nimport org.jclouds.openstack.keystone.auth.domain.AuthInfo;\nimport org.jclouds.openstack.keystone.auth.domain.TenantOrDomainAndCredentials;\nimport org.jclouds.openstack.keystone.auth.domain.TokenCredentials;\n\n@CredentialType(TOKEN_CREDENTIALS)\n@Singleton\npublic class AuthenticateTokenCredentials extends BaseAuthenticator<TokenCredentials> {\n\n   private final AuthenticationApi auth;\n\n   @Inject\n   AuthenticateTokenCredentials(AuthenticationApi auth) {\n      this.auth = auth;\n   }\n\n   @Override\n   public TokenCredentials createCredentials(String identity, String credential) {\n      return TokenCredentials.builder().id(credential).build();\n   }\n\n   @Override\n   public AuthInfo authenticate(TenantOrDomainAndCredentials<TokenCredentials> credentials) {\n      return auth.authenticateToken(credentials);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/auth/functions/BaseAuthenticator.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.auth.functions;\n\nimport static com.google.common.base.Preconditions.checkState;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.PROJECT_DOMAIN_ID;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.PROJECT_DOMAIN_NAME;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.REQUIRES_TENANT;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.SCOPE;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.TENANT_ID;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.TENANT_NAME;\n\nimport jakarta.annotation.PostConstruct;\nimport jakarta.annotation.Resource;\n\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.openstack.keystone.auth.domain.AuthInfo;\nimport org.jclouds.openstack.keystone.auth.domain.TenantOrDomainAndCredentials;\nimport org.jclouds.openstack.keystone.v3.domain.Auth.Scope;\n\nimport com.google.common.base.Function;\nimport com.google.inject.Inject;\nimport com.google.inject.name.Named;\n\npublic abstract class BaseAuthenticator<C> implements Function<Credentials, AuthInfo> {\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   @Inject(optional = true)\n   @Named(TENANT_NAME)\n   protected String defaultTenantName;\n\n   @Inject(optional = true)\n   @Named(TENANT_ID)\n   protected String defaultTenantId;\n\n   @Inject(optional = true)\n   @Named(REQUIRES_TENANT)\n   protected boolean requiresTenant;\n\n   @Inject(optional = true)\n   @Named(SCOPE)\n   protected String scope = Scope.UNSCOPED;\n\n   @Inject(optional = true)\n   @Named(PROJECT_DOMAIN_NAME)\n   protected String projectDomainName;\n\n   @Inject(optional = true)\n   @Named(PROJECT_DOMAIN_ID)\n   protected String projectDomainId;\n\n   @PostConstruct\n   public void checkPropertiesAreCompatible() {\n      checkState(defaultTenantName == null || defaultTenantId == null, \"you cannot specify both %s and %s\", TENANT_NAME,\n            TENANT_ID);\n      checkState(projectDomainName == null || projectDomainId == null, \"you cannot specify both %s and %s\",\n            PROJECT_DOMAIN_NAME, PROJECT_DOMAIN_ID);\n   }\n\n   @Override\n   public AuthInfo apply(Credentials input) {\n      String tenantName = defaultTenantName;\n      String usernameOrAccessKey = input.identity;\n      String passwordOrSecretKeyOrToken = input.credential;\n\n      if (defaultTenantName == null && input.identity.indexOf(':') != -1) {\n         tenantName = input.identity.substring(0, input.identity.lastIndexOf(':'));\n         usernameOrAccessKey = input.identity.substring(input.identity.lastIndexOf(':') + 1);\n      }\n\n      if (defaultTenantId == null && tenantName == null && requiresTenant) {\n         throw new IllegalArgumentException(String.format(\n               \"current configuration is set to [%s]. Unless you set [%s] or [%s], you must prefix your identity with 'tenantName:'\",\n               REQUIRES_TENANT, TENANT_NAME, TENANT_ID));\n      }\n\n      C creds = createCredentials(usernameOrAccessKey, passwordOrSecretKeyOrToken);\n      TenantOrDomainAndCredentials<C> credsWithTenant = TenantOrDomainAndCredentials.<C> builder()\n            .tenantOrDomainId(defaultTenantId).tenantOrDomainName(tenantName).scope(scope)\n            .projectDomainName(projectDomainName).projectDomainId(projectDomainId).credentials(creds).build();\n\n      return authenticate(credsWithTenant);\n   }\n\n   public abstract C createCredentials(String identity, String credential);\n\n   public abstract AuthInfo authenticate(TenantOrDomainAndCredentials<C> credentials);\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/auth/handlers/RetryOnRenew.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.auth.handlers;\n\nimport java.util.concurrent.TimeUnit;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\n\nimport org.jclouds.Constants;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpRetryHandler;\nimport org.jclouds.http.handlers.BackoffLimitedRetryHandler;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.openstack.keystone.auth.AuthHeaders;\nimport org.jclouds.openstack.keystone.auth.domain.AuthInfo;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.cache.Cache;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.Multimap;\nimport com.google.common.util.concurrent.Uninterruptibles;\nimport com.google.inject.Inject;\nimport com.google.inject.Singleton;\n\n/**\n * This will parse and set an appropriate exception on the command object.\n */\n@Singleton\npublic class RetryOnRenew implements HttpRetryHandler {\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   @VisibleForTesting\n   @Inject(optional = true)\n   @Named(Constants.PROPERTY_MAX_RETRIES)\n   static int NUM_RETRIES = 5;\n\n   private final LoadingCache<Credentials, AuthInfo> authenticationResponseCache;\n\n   private final BackoffLimitedRetryHandler backoffHandler;\n\n   @Inject\n   RetryOnRenew(LoadingCache<Credentials, AuthInfo> authenticationResponseCache,\n         BackoffLimitedRetryHandler backoffHandler) {\n      this.authenticationResponseCache = authenticationResponseCache;\n      this.backoffHandler = backoffHandler;\n   }\n\n   /*\n    * The reason retries need to be tracked is that it is possible that a token\n    * can be expired at any time. The reason we track by request is that only\n    * some requests might return a 401 (such as temporary URLs). However\n    * consistent failures of the magnitude this code tracks should indicate a\n    * problem.\n    */\n   private static final Cache<HttpCommand, Integer> retryCountMap = CacheBuilder.newBuilder()\n         .expireAfterWrite(5, TimeUnit.MINUTES).build();\n\n   @Override\n   public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) {\n      boolean retry = false; // default\n      switch (response.getStatusCode()) {\n         case 401:\n            // Do not retry on 401 from authentication request\n            Multimap<String, String> headers = command.getCurrentRequest().getHeaders();\n            if (headers != null && headers.containsKey(AuthHeaders.AUTH_USER)\n                  && headers.containsKey(AuthHeaders.AUTH_KEY) && !headers.containsKey(AuthHeaders.AUTH_TOKEN)) {\n               retry = false;\n            } else {\n               // This is not an authentication request returning 401\n               // Check if we already had seen this request\n               Integer count = retryCountMap.getIfPresent(command);\n\n               if (count == null) {\n                  // First time this non-authentication request failed\n                  logger.debug(\"invalidating authentication token - first time for %s\", command);\n                  retryCountMap.put(command, 1);\n                  authenticationResponseCache.invalidateAll();\n                  retry = true;\n               } else {\n                  // This request has failed before\n                  if (count + 1 >= NUM_RETRIES) {\n                     logger.debug(\"too many 401s - giving up after: %s for %s\", count, command);\n                     retry = false;\n                  } else {\n                     // Retry just in case\n                     logger.debug(\"invalidating authentication token - retry %s for %s\", count, command);\n                     retryCountMap.put(command, count + 1);\n                     // Wait between retries\n                     authenticationResponseCache.invalidateAll();\n                     Uninterruptibles.sleepUninterruptibly(5, TimeUnit.SECONDS);\n                     retry = true;\n                  }\n               }\n            }\n            break;\n         case 408:\n            return backoffHandler.shouldRetryRequest(command, response);\n      }\n      return retry;\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/catalog/ServiceEndpoint.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.catalog;\n\nimport java.net.URI;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.base.Enums;\n\n/**\n * Common properties for OpenStack service endpoints.\n * <p>\n * This class provides a common view on the service catalog endpoints so it can\n * be parsed in a generic way for Keystone v2 and v3.\n */\n@AutoValue\npublic abstract class ServiceEndpoint {\n\n   public enum Interface {\n      PUBLIC, ADMIN, INTERNAL, UNRECOGNIZED;\n\n      public static Interface fromValue(String iface) {\n         return Enums.getIfPresent(Interface.class, iface.toUpperCase()).or(UNRECOGNIZED);\n      }\n   }\n\n   @Nullable public abstract String id();\n   @Nullable public abstract String regionId();\n   public abstract URI url();\n   public abstract Interface iface();\n   public abstract String type();\n   @Nullable public abstract String version();\n   \n   ServiceEndpoint() {\n      \n   }\n   \n   public static Builder builder() {\n      return new AutoValue_ServiceEndpoint.Builder();\n   }\n   \n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder id(String id);\n      public abstract Builder regionId(String regionId);\n      public abstract Builder url(URI url);\n      public abstract Builder iface(Interface iface);\n      public abstract Builder type(String type);\n      public abstract Builder version(String version);\n      \n      public Builder iface(String iface) {\n         return iface(Interface.fromValue(iface));\n      }\n      \n      public abstract ServiceEndpoint build();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/catalog/config/InternalUrlModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.catalog.config;\n\nimport org.jclouds.openstack.keystone.catalog.functions.InternalURL;\nimport org.jclouds.openstack.keystone.catalog.functions.ServiceEndpointResolutionStrategy;\n\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Singleton;\n\n/**\n * Guice module to configure JClouds in order to use the internal urls to\n * communicate with the services.\n */\n@Singleton\npublic class InternalUrlModule extends AbstractModule {\n   @Override\n   protected void configure() {\n      bind(ServiceEndpointResolutionStrategy.class).to(InternalURL.class);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/catalog/config/KeystoneAdminURLModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.catalog.config;\n\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.KEYSTONE_VERSION;\nimport static org.jclouds.util.Suppliers2.getLastValueInMap;\n\nimport java.net.URI;\nimport java.util.NoSuchElementException;\n\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.location.Provider;\nimport org.jclouds.openstack.keystone.catalog.suppliers.RegionIdToAdminURIFromServiceEndpointsForTypeAndVersion;\nimport org.jclouds.openstack.keystone.catalog.suppliers.RegionIdToAdminURISupplier;\nimport org.jclouds.openstack.v2_0.ServiceType;\nimport org.jclouds.openstack.v2_0.services.Identity;\nimport org.jclouds.rest.annotations.ApiVersion;\nimport org.jclouds.util.Suppliers2;\n\nimport com.google.common.base.Supplier;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Provides;\nimport com.google.inject.assistedinject.FactoryModuleBuilder;\n\npublic class KeystoneAdminURLModule extends AbstractModule {\n\n   @Override\n   protected void configure() {\n      install(new FactoryModuleBuilder().implement(RegionIdToAdminURISupplier.class,\n               RegionIdToAdminURIFromServiceEndpointsForTypeAndVersion.class).build(RegionIdToAdminURISupplier.Factory.class));\n   }\n\n   /**\n    * in some cases, there is no {@link ServiceType#IDENTITY} entry in the service catalog. In\n    * other cases, there's no adminURL entry present. Fallback to the provider in this case.\n    */\n   @Provides\n   @Singleton\n   @Identity\n   protected final Supplier<URI> provideIdentityAdminUrl(final RegionIdToAdminURISupplier.Factory factory,\n         @ApiVersion final String version, @Named(KEYSTONE_VERSION) String keystoneVersion,\n         @Provider final Supplier<URI> providerURI) {\n      // There is a convention to use service types such as \"identityv3\" for specific endpoints. let's look first for\n      // those endpoints, and fallback to the default \"identity\" one or the project URL.\n      Supplier<URI> identityServiceForSpecificVersionInType = getLastValueInMap(factory.createForApiTypeAndVersion(\n            ServiceType.IDENTITY + \"v\" + keystoneVersion, version));\n      Supplier<URI> identityServiceForVersion = Suppliers2.onThrowable(identityServiceForSpecificVersionInType,\n            NoSuchElementException.class,\n            getLastValueInMap(factory.createForApiTypeAndVersion(ServiceType.IDENTITY, version)));\n      Supplier<URI> whenIdentityServiceIsntListedFallbackToProviderURI = Suppliers2.onThrowable(\n               identityServiceForVersion, NoSuchElementException.class, providerURI);\n      Supplier<URI> whenIdentityServiceHasNoAdminURLFallbackToProviderURI = Suppliers2.or(\n               whenIdentityServiceIsntListedFallbackToProviderURI, providerURI);\n      return whenIdentityServiceHasNoAdminURLFallbackToProviderURI;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/catalog/config/ServiceCatalogModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.catalog.config;\n\nimport static org.jclouds.util.Suppliers2.getLastValueInMap;\n\nimport java.net.URI;\nimport java.util.List;\nimport java.util.Map;\n\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.location.Provider;\nimport org.jclouds.location.suppliers.ImplicitLocationSupplier;\nimport org.jclouds.location.suppliers.LocationsSupplier;\nimport org.jclouds.location.suppliers.RegionIdToURISupplier;\nimport org.jclouds.location.suppliers.RegionIdsSupplier;\nimport org.jclouds.location.suppliers.all.RegionToProvider;\nimport org.jclouds.location.suppliers.derived.RegionIdsFromRegionIdToURIKeySet;\nimport org.jclouds.location.suppliers.implicit.FirstRegion;\nimport org.jclouds.openstack.keystone.catalog.ServiceEndpoint;\nimport org.jclouds.openstack.keystone.catalog.suppliers.LocationIdToURIFromServiceEndpointsForTypeAndVersion;\nimport org.jclouds.openstack.keystone.catalog.suppliers.RegionIdToAdminURIFromServiceEndpointsForTypeAndVersion;\nimport org.jclouds.openstack.keystone.catalog.suppliers.RegionIdToAdminURISupplier;\nimport org.jclouds.openstack.keystone.catalog.suppliers.RegionIdToURIFromServiceEndpointsForTypeAndVersion;\nimport org.jclouds.openstack.keystone.config.KeystoneProperties;\nimport org.jclouds.openstack.keystone.v2_0.catalog.V2ServiceCatalog;\nimport org.jclouds.openstack.keystone.v3.catalog.V3ServiceCatalog;\nimport org.jclouds.rest.annotations.ApiVersion;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.Maps;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Injector;\nimport com.google.inject.Provides;\nimport com.google.inject.Scopes;\nimport com.google.inject.assistedinject.FactoryModuleBuilder;\n\npublic class ServiceCatalogModule extends AbstractModule {\n\n   @Override\n   protected void configure() {\n      \n   }\n   \n   @Provides\n   @Singleton\n   protected final Supplier<List<ServiceEndpoint>> provideServiceCatalog(Injector i,\n         @Named(KeystoneProperties.KEYSTONE_VERSION) String keystoneVersion) {\n      Map<String, Supplier<List<ServiceEndpoint>>> serviceCatalogs = Maps.newHashMap();\n      serviceCatalogs.put(\"2\", i.getInstance(V2ServiceCatalog.class));\n      serviceCatalogs.put(\"3\", i.getInstance(V3ServiceCatalog.class));\n      return serviceCatalogs.get(keystoneVersion);\n   }\n   \n   /**\n    * For global services who have no regions, such as DNS. To use, do the following\n    * <ol>\n    * <li>add this module to your {@link org.jclouds.apis.ApiMetadata#getDefaultModules()}</li>\n    * <li>create a service-specific annotation, such as {@code @CloudDNS}, and make sure that has the meta-annotation\n    * {@link jakarta.inject.Qualifier}</li>\n    * <li>add the above annotation to any {@code Api} classes by placing it on the type. ex.\n    * {@code @Endpoint(CloudDNS.class)}</li>\n    * <li>add the following to your {@link org.jclouds.rest.config.RestClientModule}</li>\n    *\n    * <pre>\n    * bind(new TypeLiteral&lt;Supplier&lt;URI&gt;&gt;() {\n    * }).annotatedWith(CloudDNS.class).to(new TypeLiteral&lt;Supplier&lt;URI&gt;&gt;() {\n    * });\n    * </pre>\n    */\n   public static class ProviderModule extends AbstractModule {\n      @Override\n      protected void configure() {\n         install(new FactoryModuleBuilder().build(LocationIdToURIFromServiceEndpointsForTypeAndVersion.Factory.class));\n      }\n\n      @Provides\n      @Singleton\n      protected final Supplier<URI> provideZoneIdToURISupplierForApiVersion(\n            @Named(KeystoneProperties.SERVICE_TYPE) String serviceType, @ApiVersion String apiVersion,\n            LocationIdToURIFromServiceEndpointsForTypeAndVersion.Factory factory) {\n         return getLastValueInMap(factory.createForApiTypeAndVersion(serviceType, apiVersion));\n      }\n\n      @Provides\n      @Singleton\n      final Function<ServiceEndpoint, String> provideProvider(@Provider final String provider) {\n         return new Function<ServiceEndpoint, String>() {\n            @Override\n            public String apply(ServiceEndpoint in) {\n               return provider;\n            }\n         };\n      }\n   }\n\n   public static class RegionModule extends AbstractModule {\n      @Override\n      protected void configure() {\n         install(new FactoryModuleBuilder().implement(RegionIdToURISupplier.class,\n               RegionIdToURIFromServiceEndpointsForTypeAndVersion.class).build(RegionIdToURISupplier.Factory.class));\n         install(new FactoryModuleBuilder().implement(RegionIdToAdminURISupplier.class,\n               RegionIdToAdminURIFromServiceEndpointsForTypeAndVersion.class).build(RegionIdToAdminURISupplier.Factory.class));\n         // Dynamically build the region list as opposed to from properties\n         bind(RegionIdsSupplier.class).to(RegionIdsFromRegionIdToURIKeySet.class);\n         bind(ImplicitLocationSupplier.class).to(FirstRegion.class).in(Scopes.SINGLETON);\n         bind(LocationsSupplier.class).to(RegionToProvider.class).in(Scopes.SINGLETON);\n      }\n\n      @Provides\n      @Singleton\n      protected final RegionIdToURISupplier guiceProvideRegionIdToURISupplierForApiVersion(\n              @Named(KeystoneProperties.SERVICE_TYPE) String serviceType, @ApiVersion String apiVersion,\n              RegionIdToURISupplier.Factory factory) {\n         return provideRegionIdToURISupplierForApiVersion(serviceType, apiVersion, factory);\n      }\n\n      // Supply the region to id map from keystone, based on the servicetype and\n      // api version in config\n      protected RegionIdToURISupplier provideRegionIdToURISupplierForApiVersion(\n            @Named(KeystoneProperties.SERVICE_TYPE) String serviceType, @ApiVersion String apiVersion,\n            RegionIdToURISupplier.Factory factory) {\n         return factory.createForApiTypeAndVersion(serviceType, apiVersion);\n      }\n\n      @Provides\n      @Singleton\n      protected final RegionIdToAdminURISupplier guiceProvideRegionIdToAdminURISupplierForApiVersion(\n              @Named(KeystoneProperties.SERVICE_TYPE) String serviceType, @ApiVersion String apiVersion,\n              RegionIdToAdminURISupplier.Factory factory) {\n         return provideRegionIdToAdminURISupplierForApiVersion(serviceType, apiVersion, factory);\n      }\n\n      // Supply the region to id to AdminURL map from keystone, based on the\n      // servicetype and api version in config\n      protected RegionIdToAdminURISupplier provideRegionIdToAdminURISupplierForApiVersion(\n            @Named(KeystoneProperties.SERVICE_TYPE) String serviceType, @ApiVersion String apiVersion,\n            RegionIdToAdminURISupplier.Factory factory) {\n         return factory.createForApiTypeAndVersion(serviceType, apiVersion);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/catalog/functions/AdminEndpointResolutionStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.catalog.functions;\n\nimport com.google.inject.ImplementedBy;\n\n/**\n * Given a sets of endpoints for a particular service and version, return the\n * URL of the admin endpoint to be used to connect to the service.\n */\n@ImplementedBy(AdminURL.class)\npublic interface AdminEndpointResolutionStrategy extends ServiceEndpointResolutionStrategy {\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/catalog/functions/AdminURL.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.catalog.functions;\n\nimport static org.jclouds.openstack.keystone.catalog.ServiceEndpoint.Interface.ADMIN;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.openstack.keystone.catalog.ServiceEndpoint;\n\nimport com.google.common.base.Predicate;\n\n@Singleton\npublic class AdminURL extends BaseEndpointResolutionStrategy implements AdminEndpointResolutionStrategy {\n\n   @Override\n   protected Predicate<ServiceEndpoint> filter() {\n      return withIface(ADMIN);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/catalog/functions/BaseEndpointResolutionStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.catalog.functions;\n\nimport static com.google.common.collect.Iterables.tryFind;\n\nimport java.net.URI;\nimport java.util.Collection;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.keystone.catalog.ServiceEndpoint;\nimport org.jclouds.openstack.keystone.catalog.ServiceEndpoint.Interface;\n\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\n\n/**\n * Resolves the endpoint to be used to connect to a service based on a given\n * predicate.\n */\npublic abstract class BaseEndpointResolutionStrategy implements ServiceEndpointResolutionStrategy {\n\n   protected abstract Predicate<ServiceEndpoint> filter();\n\n   @Nullable\n   @Override\n   public Supplier<URI> apply(Collection<ServiceEndpoint> input) {\n      Predicate<ServiceEndpoint> filter = filter();\n      Optional<ServiceEndpoint> serviceEndpoint = tryFind(input, filter);\n      return Suppliers.ofInstance(serviceEndpoint.isPresent() ? serviceEndpoint.get().url() : null);\n   }\n\n   protected static Predicate<ServiceEndpoint> withIface(final Interface iface) {\n      return new Predicate<ServiceEndpoint>() {\n         @Override\n         public boolean apply(ServiceEndpoint input) {\n            return input.iface().equals(iface);\n         }\n\n         @Override\n         public String toString() {\n            return \"interface(\" + iface.name().toLowerCase() + \")\";\n         }\n      };\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/catalog/functions/InternalURL.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.catalog.functions;\n\nimport static org.jclouds.openstack.keystone.catalog.ServiceEndpoint.Interface.INTERNAL;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.openstack.keystone.catalog.ServiceEndpoint;\n\nimport com.google.common.base.Predicate;\n\n@Singleton\npublic class InternalURL extends BaseEndpointResolutionStrategy {\n\n   @Override\n   protected Predicate<ServiceEndpoint> filter() {\n      return withIface(INTERNAL);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/catalog/functions/PublicURLOrInternal.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.catalog.functions;\n\nimport static com.google.common.base.Predicates.or;\nimport static org.jclouds.openstack.keystone.catalog.ServiceEndpoint.Interface.INTERNAL;\nimport static org.jclouds.openstack.keystone.catalog.ServiceEndpoint.Interface.PUBLIC;\n\nimport java.net.URI;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.List;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.openstack.keystone.catalog.ServiceEndpoint;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\n\n@Singleton\npublic class PublicURLOrInternal extends BaseEndpointResolutionStrategy {\n\n   @Override\n   public Supplier<URI> apply(Collection<ServiceEndpoint> input) {\n      List<ServiceEndpoint> publicEndpointsFirst = new ArrayList<ServiceEndpoint>(input);\n      Collections.sort(publicEndpointsFirst, PublicInterfacesFirst);\n      return super.apply(publicEndpointsFirst);\n   }\n\n   @Override\n   protected Predicate<ServiceEndpoint> filter() {\n      return or(withIface(PUBLIC), withIface(INTERNAL));\n   }\n\n   private static final Comparator<ServiceEndpoint> PublicInterfacesFirst = new Comparator<ServiceEndpoint>() {\n      @Override\n      public int compare(ServiceEndpoint left, ServiceEndpoint right) {\n         // We only care about public interfaces, since the collection will be\n         // filtered only by public or internal ones\n         if (PUBLIC.equals(left.iface())) {\n            return -1;\n         } else if (PUBLIC.equals(right.iface())) {\n            return 1;\n         } else {\n            return 0;\n         }\n      };\n   };\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/catalog/functions/ReturnRegionOrProvider.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.catalog.functions;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.location.Provider;\nimport org.jclouds.openstack.keystone.catalog.ServiceEndpoint;\n\n@Singleton\npublic class ReturnRegionOrProvider implements ServiceEndpointToRegion {\n   private final String provider;\n\n   @Inject\n   ReturnRegionOrProvider(@Provider String provider) {\n      this.provider = provider;\n   }\n\n   @Override\n   public String apply(ServiceEndpoint input) {\n      return input.regionId() != null ? input.regionId() : provider;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/catalog/functions/ServiceEndpointResolutionStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.catalog.functions;\n\nimport java.net.URI;\nimport java.util.Collection;\n\nimport org.jclouds.openstack.keystone.catalog.ServiceEndpoint;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.inject.ImplementedBy;\n\n/**\n * Given a sets of endpoints for a particular service and version, return the\n * URL to be used to connect to the service.\n */\n@ImplementedBy(PublicURLOrInternal.class)\npublic interface ServiceEndpointResolutionStrategy extends Function<Collection<ServiceEndpoint>, Supplier<URI>> {\n   \n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/catalog/functions/ServiceEndpointToRegion.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.catalog.functions;\n\nimport org.jclouds.openstack.keystone.catalog.ServiceEndpoint;\n\nimport com.google.common.base.Function;\nimport com.google.inject.ImplementedBy;\n\n@ImplementedBy(ReturnRegionOrProvider.class)\npublic interface ServiceEndpointToRegion extends Function<ServiceEndpoint, String> {\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/catalog/suppliers/LocationIdToURIFromServiceEndpointsForTypeAndVersion.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.catalog.suppliers;\n\nimport static com.google.common.collect.Iterables.any;\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.isEmpty;\nimport static com.google.common.collect.Maps.transformValues;\nimport static com.google.common.collect.Multimaps.asMap;\nimport static com.google.common.collect.Multimaps.index;\n\nimport java.net.URI;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\n\nimport jakarta.annotation.Resource;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.openstack.keystone.catalog.ServiceEndpoint;\nimport org.jclouds.openstack.keystone.catalog.functions.ServiceEndpointResolutionStrategy;\nimport org.jclouds.openstack.keystone.catalog.functions.ServiceEndpointToRegion;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Predicates;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.Multimap;\nimport com.google.inject.Inject;\nimport com.google.inject.assistedinject.Assisted;\n\npublic class LocationIdToURIFromServiceEndpointsForTypeAndVersion implements Supplier<Map<String, Supplier<URI>>> {\n\n   public interface Factory {\n      \n      LocationIdToURIFromServiceEndpointsForTypeAndVersion createForApiTypeAndVersion(@Assisted(\"apiType\") String apiType,\n                                                                                      @Nullable @Assisted(\"apiVersion\") String apiVersion) throws NoSuchElementException;\n   }\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   protected final Supplier<List<ServiceEndpoint>> serviceEndpoints;\n   protected final ServiceEndpointResolutionStrategy resolveServiceEndpointURI;\n   protected final ServiceEndpointToRegion serviceEndpointToRegion;\n   protected final String apiType;\n   protected final String apiVersion;\n\n   @Inject\n   LocationIdToURIFromServiceEndpointsForTypeAndVersion(Supplier<List<ServiceEndpoint>> serviceEndpoints,\n                                                        ServiceEndpointResolutionStrategy resolveServiceEndpointURI, ServiceEndpointToRegion serviceEndpointToRegion,\n                                                        @Assisted(\"apiType\") String apiType, @Nullable @Assisted(\"apiVersion\") String apiVersion) {\n      this.serviceEndpoints = serviceEndpoints;\n      this.resolveServiceEndpointURI = resolveServiceEndpointURI;\n      this.serviceEndpointToRegion = serviceEndpointToRegion;\n      this.apiType = apiType;\n      this.apiVersion = apiVersion;\n   }\n\n   @Override\n   public Map<String, Supplier<URI>> get() {\n      List<ServiceEndpoint> endpoints = serviceEndpoints.get();\n      if (endpoints.isEmpty()) {\n         throw new NoSuchElementException(\n               \"No endpoints were found in the service catalog. Make sure your authentication token has the right scopes and permissions\");\n      }\n\n      // Filter endpoints by service type\n      Iterable<ServiceEndpoint> endpointsForType = filter(endpoints, apiTypeEquals);\n      if (isEmpty(endpointsForType)) {\n         throw new NoSuchElementException(String.format(\"no endpoints for apiType %s in service endpoints %s\", apiType,\n               endpoints));\n      }\n      \n      // Check if there are endpoints for a particular version, if specified and\n      // there are versioned endpoints\n      boolean checkVersionId = apiVersion != null && any(endpointsForType, versionAware);\n      Predicate<ServiceEndpoint> versionFilter = checkVersionId ? apiVersionEqualsVersionId : Predicates.<ServiceEndpoint> alwaysTrue();\n      Iterable<ServiceEndpoint> endpointsForTypeAndVersion = filter(endpointsForType, versionFilter);\n      if (isEmpty(endpointsForTypeAndVersion)) {\n         throw new NoSuchElementException(String.format(\n               \"no service endpoints for apiType %s are of version %s, or version agnostic: %s\", apiType, apiVersion,\n               endpointsForType));\n      }\n\n      logger.debug(\"service endpoints for apiType %s and version %s: %s\", apiType, apiVersion,\n            endpointsForTypeAndVersion);\n      \n      Multimap<String, ServiceEndpoint> locationToServiceEndpoints = index(endpointsForTypeAndVersion,\n            serviceEndpointToRegion);\n      return transformValues(asMap(locationToServiceEndpoints), resolveServiceEndpointURI);\n   }\n\n   private final Predicate<ServiceEndpoint> apiVersionEqualsVersionId = new Predicate<ServiceEndpoint>() {\n      @Override\n      public boolean apply(ServiceEndpoint input) {\n         return input.version().equals(apiVersion);\n      }\n   };\n\n   private final Predicate<ServiceEndpoint> versionAware = new Predicate<ServiceEndpoint>() {\n      @Override\n      public boolean apply(ServiceEndpoint input) {\n         return input.version() != null;\n      }\n   };\n\n   private final Predicate<ServiceEndpoint> apiTypeEquals = new Predicate<ServiceEndpoint>() {\n      @Override\n      public boolean apply(ServiceEndpoint input) {\n         return input.type().equals(apiType);\n      }\n   };\n\n   @Override\n   public String toString() {\n      return \"locationIdToURIFromServiceEndpointsForTypeAndVersion(\" + apiType + \", \" + apiVersion + \")\";\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/catalog/suppliers/RegionIdToAdminURIFromServiceEndpointsForTypeAndVersion.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.catalog.suppliers;\n\nimport java.util.List;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.keystone.catalog.ServiceEndpoint;\nimport org.jclouds.openstack.keystone.catalog.functions.AdminEndpointResolutionStrategy;\nimport org.jclouds.openstack.keystone.catalog.functions.ServiceEndpointToRegion;\n\nimport com.google.common.base.Supplier;\nimport com.google.inject.assistedinject.Assisted;\n\npublic class RegionIdToAdminURIFromServiceEndpointsForTypeAndVersion extends LocationIdToURIFromServiceEndpointsForTypeAndVersion implements\n      RegionIdToAdminURISupplier {\n   @Inject\n   public RegionIdToAdminURIFromServiceEndpointsForTypeAndVersion(Supplier<List<ServiceEndpoint>> serviceEndpoints,\n                                                                  AdminEndpointResolutionStrategy resolveServiceEndpointURI, ServiceEndpointToRegion serviceEndpointToRegion,\n                                                                  @Assisted(\"apiType\") String apiType, @Nullable @Assisted(\"apiVersion\") String apiVersion) {\n      super(serviceEndpoints, resolveServiceEndpointURI, serviceEndpointToRegion, apiType, apiVersion);\n   }\n\n   @Override\n   public String toString() {\n      return \"regionIdToAdminURIFromServiceEndpointsForTypeAndVersion(\" + apiType + \", \" + apiVersion + \")\";\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/catalog/suppliers/RegionIdToAdminURISupplier.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.catalog.suppliers;\n\nimport java.net.URI;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.Supplier;\nimport com.google.inject.ImplementedBy;\nimport com.google.inject.assistedinject.Assisted;\n\n@ImplementedBy(RegionIdToAdminURIFromServiceEndpointsForTypeAndVersion.class)\npublic interface RegionIdToAdminURISupplier extends Supplier<Map<String, Supplier<URI>>> {\n\n   interface Factory {\n\n      RegionIdToAdminURISupplier createForApiTypeAndVersion(@Assisted(\"apiType\") String apiType,\n               @Nullable @Assisted(\"apiVersion\") String apiVersion) throws NoSuchElementException;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/catalog/suppliers/RegionIdToURIFromServiceEndpointsForTypeAndVersion.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.catalog.suppliers;\n\nimport java.util.List;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.location.suppliers.RegionIdToURISupplier;\nimport org.jclouds.openstack.keystone.catalog.ServiceEndpoint;\nimport org.jclouds.openstack.keystone.catalog.functions.ServiceEndpointResolutionStrategy;\nimport org.jclouds.openstack.keystone.catalog.functions.ServiceEndpointToRegion;\n\nimport com.google.common.base.Supplier;\nimport com.google.inject.assistedinject.Assisted;\n\npublic class RegionIdToURIFromServiceEndpointsForTypeAndVersion extends LocationIdToURIFromServiceEndpointsForTypeAndVersion implements\n      RegionIdToURISupplier {\n\n   @Inject\n   public RegionIdToURIFromServiceEndpointsForTypeAndVersion(Supplier<List<ServiceEndpoint>> serviceEndpoints,\n                                                             ServiceEndpointResolutionStrategy resolveServiceEndpointURI, ServiceEndpointToRegion serviceEndpointToRegion,\n                                                             @Assisted(\"apiType\") String apiType, @Nullable @Assisted(\"apiVersion\") String apiVersion) {\n      super(serviceEndpoints, resolveServiceEndpointURI, serviceEndpointToRegion, apiType, apiVersion);\n   }\n\n   @Override\n   public String toString() {\n      return \"regionIdToURIFromAccessForTypeAndVersion(\" + apiType + \", \" + apiVersion + \")\";\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/config/KeystoneProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.config;\n\nimport org.jclouds.openstack.keystone.auth.config.CredentialTypes;\nimport org.jclouds.rest.annotations.SinceApiVersion;\n\n/**\n * Configuration properties and constants used in Keystone connections.\n */\npublic final class KeystoneProperties {\n\n   /**\n    * Type of credentials used to log into the auth service.\n    *\n    * <h3>valid values</h3>\n    * <ul>\n    * <li>apiAccessKeyCredentials</li>\n    * <li>passwordCredentials</li>\n    * <li>tokenCredentials</li>\n    * </ul>\n    *\n    * @see CredentialTypes\n    * @see <a href=\n    *      \"http://docs.openstack.org/api/openstack-identity-service/2.0/content/POST_authenticate_v2.0_tokens_Service_API_Api_Operations.html\"\n    *      />\n    */\n   public static final String CREDENTIAL_TYPE = \"jclouds.keystone.credential-type\";\n\n   /**\n    * set this property to specify the tenant id of the authenticated user.\n    * Cannot be used simultaneously with {@link #TENANT_NAME}\n    *\n    * @see <a href=\"http://wiki.openstack.org/CLIAuth\">openstack docs</a>\n    */\n   public static final String TENANT_ID = \"jclouds.keystone.tenant-id\";\n\n   /**\n    * set this property to specify the tenant name of the authenticated user.\n    * Cannot be used simultaneously with {@link #TENANT_ID}\n    *\n    * @see <a href=\"http://wiki.openstack.org/CLIAuth\">openstack docs</a>\n    */\n   public static final String TENANT_NAME = \"jclouds.keystone.tenant-name\";\n\n   /**\n    * set this property to {@code true} to designate that the service requires\n    * explicit specification of either {@link #TENANT_NAME} or\n    * {@link #TENANT_ID}\n    *\n    * @see <a href=\"http://wiki.openstack.org/CLIAuth\">openstack docs</a>\n    */\n   public static final String REQUIRES_TENANT = \"jclouds.keystone.requires-tenant\";\n\n   /**\n    * set this property to specify for scoped authentication.\n    * <p>\n    * The format is one of the following:\n    * <ul>\n    * <li>project:<project-id></li>\n    * <li>domain:<domain-name></li>\n    * <li></li>\n    * </ul>\n    * For example: <code>project:457841231597451534</code>\n    */\n   @SinceApiVersion(\"3\")\n   public static final String SCOPE = \"jclouds.keystone.scope\";\n\n   /**\n    * Set this property to specify the domain name of project (tenant)\n    * scope.<br/>\n    * Required property when authentication {@link #SCOPE} is 'project:' and\n    * project (tenant) domain is different than the user domain (Otherwise, the\n    * domain used is the same as the user). <br/>\n    * Cannot be used simultaneously with {@link #PROJECT_DOMAIN_ID}\n    *\n    * @see <a href=\n    *      \"https://docs.openstack.org/keystone/latest/api_curl_examples.html#project-scoped\">openstack\n    *      docs : Identity service (Keystone)</a>\n    */\n   public static final String PROJECT_DOMAIN_NAME = \"jclouds.keystone.project-domain-name\";\n\n   /**\n    * Set this property to specify the domain id of project (tenant) scope.<br/>\n    * Required property when authentication {@link #SCOPE} is 'project:' and\n    * project (tenant) domain is different than the user domain (Otherwise, the\n    * domain used is the same as the user). <br/>\n    * Cannot be used simultaneously with {@link #PROJECT_DOMAIN_NAME}\n    *\n    * \n    * @see <a href=\n    *      \"https://docs.openstack.org/keystone/latest/api_curl_examples.html#project-scoped\">openstack\n    *      docs : Identity service (Keystone)</a>\n    */\n   public static final String PROJECT_DOMAIN_ID = \"jclouds.keystone.project-domain-id\";\n\n   /**\n    * type of the keystone service. ex. {@code compute}\n    *\n    * @see ServiceType\n    */\n   public static final String SERVICE_TYPE = \"jclouds.keystone.service-type\";\n\n   /**\n    * Version of keystone to be used by services. Default: 3.\n    */\n   public static final String KEYSTONE_VERSION = \"jclouds.keystone.version\";\n\n   private KeystoneProperties() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/KeystoneApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0;\n\nimport java.io.Closeable;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.keystone.v2_0.domain.ApiMetadata;\nimport org.jclouds.openstack.keystone.v2_0.extensions.RoleAdminApi;\nimport org.jclouds.openstack.keystone.v2_0.extensions.ServiceAdminApi;\nimport org.jclouds.openstack.keystone.v2_0.extensions.TenantAdminApi;\nimport org.jclouds.openstack.keystone.v2_0.extensions.UserAdminApi;\nimport org.jclouds.openstack.keystone.v2_0.features.ServiceApi;\nimport org.jclouds.openstack.keystone.v2_0.features.TenantApi;\nimport org.jclouds.openstack.keystone.v2_0.features.TokenApi;\nimport org.jclouds.openstack.keystone.v2_0.features.UserApi;\nimport org.jclouds.openstack.v2_0.features.ExtensionApi;\nimport org.jclouds.rest.annotations.Delegate;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.SelectJson;\n\nimport com.google.common.base.Optional;\n\n/**\n * Provides access to the OpenStack Identity (Keystone) REST API.\n */\npublic interface KeystoneApi extends Closeable {\n\n   /**\n    * Discover API version information, links to documentation (PDF, HTML, WADL), and supported media types\n    *\n    * @return the {@link ApiMetadata}\n    */\n   @Named(\"keystone:getApiMetadata\")\n   @GET\n   @SelectJson(\"version\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   ApiMetadata getApiMetadata();\n\n   /**\n    * Provides access to Token features\n    */\n   @Delegate\n   ServiceApi getServiceApi();\n\n   /**\n    * Provides access to Extension features.\n    */\n   @Delegate\n   ExtensionApi getExtensionApi();\n\n   /**\n    * Provides access to Token features\n    */\n   @Delegate\n   Optional<? extends TokenApi> getTokenApi();\n\n   /**\n    * Provides access to User features\n    */\n   @Delegate\n   Optional<? extends UserApi> getUserApi();\n\n   /**\n    * Provides access to Tenant features\n    */\n   @Delegate\n   Optional<? extends TenantApi> getTenantApi();\n\n   /**\n    * Provides access to Admin user features\n    */\n   @Delegate\n   Optional<? extends UserAdminApi> getUserAdminApi();\n\n   /**\n    * Provides access to Admin tenant features\n    */\n   @Delegate\n   Optional<? extends TenantAdminApi> getTenantAdminApi();\n\n   /**\n    * Provides access to Admin role features\n    */\n   @Delegate\n   Optional<? extends RoleAdminApi> getRoleAdminApi();\n\n   /**\n    * Provides access to Admin service features\n    */\n   @Delegate\n   Optional<? extends ServiceAdminApi> getServiceAdminApi();\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/KeystoneApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0;\n\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.CREDENTIAL_TYPE;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.KEYSTONE_VERSION;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.SERVICE_TYPE;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.openstack.keystone.auth.config.AuthenticationModule;\nimport org.jclouds.openstack.keystone.auth.config.CredentialTypes;\nimport org.jclouds.openstack.keystone.catalog.config.KeystoneAdminURLModule;\nimport org.jclouds.openstack.keystone.catalog.config.ServiceCatalogModule;\nimport org.jclouds.openstack.keystone.v2_0.config.KeystoneHttpApiModule;\nimport org.jclouds.openstack.keystone.v2_0.config.KeystoneParserModule;\nimport org.jclouds.openstack.v2_0.ServiceType;\nimport org.jclouds.rest.internal.BaseHttpApiMetadata;\n\nimport com.google.auto.service.AutoService;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n/**\n * Implementation of {@link ApiMetadata} for Keystone 2.0 API\n */\n@AutoService(ApiMetadata.class)\npublic class KeystoneApiMetadata extends BaseHttpApiMetadata<KeystoneApi> {\n\n   @Override\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromApiMetadata(this);\n   }\n\n   public KeystoneApiMetadata() {\n      this(new ConcreteBuilder());\n   }\n\n   protected KeystoneApiMetadata(Builder<?> builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = BaseHttpApiMetadata.defaultProperties();\n      properties.setProperty(CREDENTIAL_TYPE, CredentialTypes.PASSWORD_CREDENTIALS);\n      properties.setProperty(SERVICE_TYPE, ServiceType.IDENTITY);\n      properties.setProperty(KEYSTONE_VERSION, \"2\");\n      return properties;\n   }\n\n   public abstract static class Builder<T extends Builder<T>> extends BaseHttpApiMetadata.Builder<KeystoneApi, T> {\n\n      protected Builder() {\n          id(\"openstack-keystone\")\n         .name(\"OpenStack Keystone Essex+ API\")\n         .identityName(\"${tenantName}:${userName} or ${userName}, if your keystone supports a default tenant\")\n         .credentialName(\"${password}\")\n         .endpointName(\"Keystone base url ending in /v${jclouds.api-version}/\")\n         .documentation(URI.create(\"http://api.openstack.org/\"))\n         .version(\"2.0\")\n         .defaultEndpoint(\"http://localhost:5000/v${jclouds.api-version}/\")\n         .defaultProperties(KeystoneApiMetadata.defaultProperties())\n         .defaultModules(ImmutableSet.<Class<? extends Module>>builder()\n                                     .add(AuthenticationModule.class)\n                                     .add(ServiceCatalogModule.class)\n                                     .add(KeystoneAdminURLModule.class)\n                                     .add(KeystoneParserModule.class)\n                                     .add(KeystoneHttpApiModule.class).build());\n      }\n\n      @Override\n      public KeystoneApiMetadata build() {\n         return new KeystoneApiMetadata(this);\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/KeystoneFallbacks.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0;\n\nimport static org.jclouds.Fallbacks.valOnNotFoundOr404;\n\nimport org.jclouds.Fallback;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.PaginatedCollection;\n\nimport com.google.common.collect.ImmutableSet;\n\npublic final class KeystoneFallbacks {\n   private KeystoneFallbacks() {\n   }\n\n   public static final class EmptyPaginatedCollectionOnNotFoundOr404 implements Fallback<PaginatedCollection<Object>> {\n      private static final PaginatedCollection<Object> EMPTY = new PaginatedCollection<Object>(\n            ImmutableSet.<Object> of(), ImmutableSet.<Link> of()) {\n      };\n\n      @Override\n      public PaginatedCollection<Object> createOrPropagate(Throwable t) throws Exception {\n         return valOnNotFoundOr404(EMPTY, t);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/auth/V2AuthenticationApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.auth;\n\nimport java.io.Closeable;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.openstack.keystone.auth.AuthenticationApi;\nimport org.jclouds.openstack.keystone.auth.domain.ApiAccessKeyCredentials;\nimport org.jclouds.openstack.keystone.auth.domain.PasswordCredentials;\nimport org.jclouds.openstack.keystone.auth.domain.TenantOrDomainAndCredentials;\nimport org.jclouds.openstack.keystone.v2_0.binders.BindAuthToJsonPayload;\nimport org.jclouds.openstack.keystone.v2_0.domain.Access;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.SelectJson;\n\nimport com.google.inject.name.Named;\n\n/**\n * Provides access to the OpenStack Keystone Service API.\n */\n@Consumes(MediaType.APPLICATION_JSON)\n@Path(\"/tokens\")\npublic interface V2AuthenticationApi extends AuthenticationApi, Closeable {\n\n   /**\n    * Authenticate to generate a token.\n    *\n    * @return access with token\n    */\n   @Named(\"authenticate\")\n   @POST\n   @SelectJson(\"access\")\n   @MapBinder(BindAuthToJsonPayload.class)\n   @Override\n   Access authenticatePassword(TenantOrDomainAndCredentials<PasswordCredentials> credentials);\n\n   /**\n    * Authenticate to generate a token.\n    *\n    * @return access with token\n    */\n   @Named(\"authenticate\")\n   @POST\n   @SelectJson(\"access\")\n   @MapBinder(BindAuthToJsonPayload.class)\n   @Override\n   Access authenticateAccessKey(TenantOrDomainAndCredentials<ApiAccessKeyCredentials> credentials);\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/binders/BindAuthToJsonPayload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Predicates.instanceOf;\nimport static com.google.common.collect.Iterables.tryFind;\nimport static org.jclouds.openstack.keystone.auth.config.CredentialTypes.findCredentialType;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.json.Json;\nimport org.jclouds.openstack.keystone.auth.config.CredentialType;\nimport org.jclouds.openstack.keystone.auth.domain.TenantOrDomainAndCredentials;\nimport org.jclouds.rest.MapBinder;\nimport org.jclouds.rest.binders.BindToJsonPayload;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\n\nimport com.google.common.base.Optional;\nimport com.google.common.base.Strings;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMap.Builder;\n\n@Singleton\npublic class BindAuthToJsonPayload extends BindToJsonPayload implements MapBinder {\n   @Inject\n   public BindAuthToJsonPayload(Json jsonBinder) {\n      super(jsonBinder);\n   }\n\n   protected TenantOrDomainAndCredentials<?> findCredentialsInArgs(GeneratedHttpRequest gRequest) {\n      Optional<Object> credentials = tryFind(gRequest.getInvocation().getArgs(), instanceOf(TenantOrDomainAndCredentials.class));\n      return credentials.isPresent() ? (TenantOrDomainAndCredentials<?>) credentials.get() : null;\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      checkArgument(checkNotNull(request, \"request\") instanceof GeneratedHttpRequest,\n            \"this binder is only valid for GeneratedHttpRequests!\");\n      GeneratedHttpRequest gRequest = (GeneratedHttpRequest) request;\n      Builder<String, Object> builder = ImmutableMap.builder();\n\n      TenantOrDomainAndCredentials<?> credentials = findCredentialsInArgs(gRequest);\n      if (credentials != null) {\n         CredentialType credentialType = findCredentialType(credentials.credentials().getClass());\n         checkArgument(credentialType != null, \"the given credentials must be annotated with @CredentialType\");\n\n         builder.put(credentialType.value(), credentials.credentials());\n\n         // TODO: is tenantName permanent? or should we switch to tenantId at\n         // some point. seems most tools still use tenantName\n         if (credentials != null) {\n            if (!Strings.isNullOrEmpty(credentials.tenantOrDomainId()))\n               builder.put(\"tenantId\", credentials.tenantOrDomainId());\n            else if (!Strings.isNullOrEmpty(credentials.tenantOrDomainName()))\n               builder.put(\"tenantName\", credentials.tenantOrDomainName());\n         }\n      }\n\n      R authRequest = super.bindToRequest(request, ImmutableMap.of(\"auth\", builder.build()));\n      authRequest.getPayload().setSensitive(true);\n      return authRequest;\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/catalog/V2ServiceCatalog.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.catalog;\n\nimport static org.jclouds.openstack.keystone.catalog.ServiceEndpoint.Interface.ADMIN;\nimport static org.jclouds.openstack.keystone.catalog.ServiceEndpoint.Interface.INTERNAL;\nimport static org.jclouds.openstack.keystone.catalog.ServiceEndpoint.Interface.PUBLIC;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.logging.Logger;\nimport org.jclouds.openstack.keystone.auth.domain.AuthInfo;\nimport org.jclouds.openstack.keystone.catalog.ServiceEndpoint;\nimport org.jclouds.openstack.keystone.catalog.ServiceEndpoint.Interface;\nimport org.jclouds.openstack.keystone.v2_0.domain.Access;\nimport org.jclouds.openstack.keystone.v2_0.domain.Endpoint;\nimport org.jclouds.openstack.keystone.v2_0.domain.Service;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableList;\n\n@Singleton\npublic class V2ServiceCatalog implements Supplier<List<ServiceEndpoint>> {\n\n   @Resource\n   private Logger logger = Logger.NULL;\n\n   private final Supplier<AuthInfo> authInfo;\n\n   @Inject\n   V2ServiceCatalog(Supplier<AuthInfo> authInfo) {\n      this.authInfo = authInfo;\n   }\n\n   @Override\n   public List<ServiceEndpoint> get() {\n      Access access = (Access) authInfo.get();\n      ImmutableList.Builder<ServiceEndpoint> serviceEndpoints = ImmutableList.builder();\n      for (Service service : access) {\n         for (Endpoint endpoint : service) {\n            if (endpoint.getAdminURL() != null) {\n               serviceEndpoints.add(toServiceEndpoint(service.getType(), ADMIN).apply(endpoint));\n            }\n            if (endpoint.getInternalURL() != null) {\n               serviceEndpoints.add(toServiceEndpoint(service.getType(), INTERNAL).apply(endpoint));\n            }\n            if (endpoint.getPublicURL() != null) {\n               serviceEndpoints.add(toServiceEndpoint(service.getType(), PUBLIC).apply(endpoint));\n            }\n         }\n      }\n\n      return serviceEndpoints.build();\n   }\n\n   private Function<Endpoint, ServiceEndpoint> toServiceEndpoint(final String type, final Interface iface) {\n      return new Function<Endpoint, ServiceEndpoint>() {\n         @Override\n         public ServiceEndpoint apply(Endpoint input) {\n            ServiceEndpoint.Builder builder = ServiceEndpoint.builder().id(input.getId()).iface(iface)\n                  .regionId(input.getRegion()).type(type).version(input.getVersionId());\n\n            switch (iface) {\n               case ADMIN:\n                  builder.url(input.getAdminURL());\n                  break;\n               case INTERNAL:\n                  builder.url(input.getInternalURL());\n                  break;\n               case PUBLIC:\n                  builder.url(input.getPublicURL());\n                  break;\n               case UNRECOGNIZED:\n                  URI url = input.getPublicURL() != null ? input.getPublicURL() : input.getInternalURL();\n                  logger.warn(\"Unrecognized endpoint interface for %s. Using URL: %s\", input, url);\n                  builder.url(url);\n                  break;\n            }\n\n            return builder.build();\n         }\n      };\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/config/KeystoneHttpApiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.config;\n\nimport java.net.URI;\nimport java.util.Set;\nimport java.util.concurrent.TimeUnit;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.annotation.ClientError;\nimport org.jclouds.http.annotation.Redirection;\nimport org.jclouds.http.annotation.ServerError;\nimport org.jclouds.openstack.keystone.v2_0.KeystoneApi;\nimport org.jclouds.openstack.keystone.v2_0.handlers.KeystoneErrorHandler;\nimport org.jclouds.openstack.v2_0.domain.Extension;\nimport org.jclouds.openstack.v2_0.functions.PresentWhenExtensionAnnotationMatchesExtensionSet;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.config.HttpApiModule;\nimport org.jclouds.rest.functions.ImplicitOptionalConverter;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.inject.Binder;\nimport com.google.inject.Provides;\nimport com.google.inject.multibindings.MapBinder;\n\n/**\n * Configures the Keystone API.\n */\n@ConfiguresHttpApi\npublic class KeystoneHttpApiModule extends HttpApiModule<KeystoneApi> {\n\n   public KeystoneHttpApiModule() {\n   }\n\n   // Allow providers to cleanly contribute their own aliases\n   public static MapBinder<URI, URI> namespaceAliasBinder(Binder binder) {\n      return MapBinder.newMapBinder(binder, URI.class, URI.class, NamespaceAliases.class).permitDuplicates();\n   }\n\n   @Override\n   protected void configure() {\n      bind(ImplicitOptionalConverter.class).to(PresentWhenExtensionAnnotationMatchesExtensionSet.class);\n      super.configure();\n      namespaceAliasBinder(binder());\n   }\n\n   @Provides\n   @Singleton\n   public final LoadingCache<String, Set<? extends Extension>> provideExtensionsByRegion(final jakarta.inject.Provider<KeystoneApi> keystoneApi) {\n      return CacheBuilder.newBuilder().expireAfterWrite(23, TimeUnit.HOURS)\n            .build(CacheLoader.from(Suppliers.memoize(new Supplier<Set<? extends Extension>>() {\n               @Override\n               public Set<? extends Extension> get() {\n                  return keystoneApi.get().getExtensionApi().list();\n               }\n            })));\n   }\n\n   @Override\n   protected void bindErrorHandlers() {\n      bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(KeystoneErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(KeystoneErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(KeystoneErrorHandler.class);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/config/KeystoneParserModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.config;\n\nimport static com.google.common.base.Preconditions.checkState;\n\nimport java.io.IOException;\nimport java.util.Set;\n\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.json.config.GsonModule.DateAdapter;\nimport org.jclouds.json.internal.NullFilteringTypeAdapterFactories.SetTypeAdapter;\nimport org.jclouds.json.internal.NullFilteringTypeAdapterFactories.SetTypeAdapterFactory;\n\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\nimport com.google.gson.TypeAdapter;\nimport com.google.gson.stream.JsonReader;\nimport com.google.gson.stream.JsonToken;\nimport com.google.gson.stream.JsonWriter;\nimport com.google.inject.AbstractModule;\n\npublic class KeystoneParserModule extends AbstractModule {\n\n   @Override\n   protected void configure() {\n      bind(DateAdapter.class).to(GsonModule.Iso8601DateAdapter.class);\n      bind(SetTypeAdapterFactory.class).to(ValuesSetTypeAdapterFactory.class);\n   }\n\n   /**\n    * Handles the goofy structures with \"values\" holder wrapping an array\n    * http://docs.openstack.org/api/openstack-identity-service/2.0/content/Versions-d1e472.html\n    * <p/>\n    * Treats [A,B,C] and {\"values\"=[A,B,C], \"someotherstuff\"=...} as the same Set\n    */\n   public static class ValuesSetTypeAdapterFactory extends SetTypeAdapterFactory {\n\n      @Override\n      @SuppressWarnings(\"unchecked\")\n      protected <E, I> TypeAdapter<I> newAdapter(TypeAdapter<E> elementAdapter) {\n         return (TypeAdapter<I>) new Adapter<E>(elementAdapter);\n      }\n\n      public static final class Adapter<E> extends TypeAdapter<Set<E>> {\n\n         private final SetTypeAdapter<E> delegate;\n\n         public Adapter(TypeAdapter<E> elementAdapter) {\n            this.delegate = new SetTypeAdapter<E>(elementAdapter);\n            nullSafe();\n         }\n\n         public void write(JsonWriter out, Set<E> value) throws IOException {\n            this.delegate.write(out, value);\n         }\n\n         @Override\n         public Set<E> read(JsonReader in) throws IOException {\n            if (in.peek() == JsonToken.BEGIN_OBJECT) {\n               Builder<E> builder = ImmutableSet.<E>builder();\n               boolean foundValues = false;\n               in.beginObject();\n               while (in.hasNext()) {\n                  String name = in.nextName();\n                  if (Objects.equal(\"values\", name)) {\n                     foundValues = true;\n                     builder.addAll(delegate.read(in));\n                  } else {\n                     in.skipValue();\n                  }\n               }\n               checkState(foundValues, \"Expected BEGIN_ARRAY or the object to contain an array called 'values'\");\n               in.endObject();\n               return builder.build();\n            } else {\n               return delegate.read(in);\n            }\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/config/NamespaceAliases.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.config;\n\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\nimport jakarta.inject.Qualifier;\n\n@Retention(value = RetentionPolicy.RUNTIME)\n@Target(value = { ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })\n@Qualifier\npublic @interface NamespaceAliases {\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/domain/Access.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.keystone.auth.domain.AuthInfo;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ForwardingSet;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * TODO\n *\n * @see <a href=\n *      \"http://docs.openstack.org/api/openstack-identity-service/2.0/content/Identity-Service-Concepts-e1362.html\"\n *      />\n */\npublic class Access extends ForwardingSet<Service> implements Comparable<Access>, AuthInfo {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromAccess(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected Token token;\n      protected User user;\n      protected ImmutableSet.Builder<Service> serviceCatalog = ImmutableSet.<Service> builder();\n\n      /**\n       * @see Access#getToken()\n       */\n      public T token(Token token) {\n         this.token = token;\n         return self();\n      }\n\n      /**\n       * @see Access#getUser()\n       */\n      public T user(User user) {\n         this.user = user;\n         return self();\n      }\n\n      /**\n       * @see Access#delegate()\n       */\n      public T service(Service service) {\n         this.serviceCatalog.add(service);\n         return self();\n      }\n\n      /**\n       * @see Access#delegate()\n       */\n      public T services(Iterable<Service> serviceCatalog) {\n         this.serviceCatalog.addAll(serviceCatalog);\n         return self();\n      }\n\n      public Access build() {\n         return new Access(token, user, serviceCatalog.build());\n      }\n\n      public T fromAccess(Access in) {\n         return this.token(in.getToken()).user(in.getUser()).services(in);\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final Token token;\n   private final User user;\n   private final Set<Service> serviceCatalog;\n\n   @ConstructorProperties({ \"token\", \"user\", \"serviceCatalog\" })\n   protected Access(Token token, User user, @Nullable Set<Service> serviceCatalog) {\n      this.token = checkNotNull(token, \"token\");\n      this.user = checkNotNull(user, \"user\");\n      this.serviceCatalog = serviceCatalog == null ? ImmutableSet.<Service> of() : ImmutableSet.copyOf(serviceCatalog);\n   }\n\n   /**\n    * TODO\n    */\n   public Token getToken() {\n      return this.token;\n   }\n\n   /**\n    * TODO\n    */\n   public User getUser() {\n      return this.user;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(token, user, serviceCatalog);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      Access that = Access.class.cast(obj);\n      return Objects.equal(this.token, that.token) && Objects.equal(this.user, that.user)\n            && Objects.equal(this.serviceCatalog, that.serviceCatalog);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"token\", token).add(\"user\", user)\n            .add(\"serviceCatalog\", serviceCatalog);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int compareTo(Access that) {\n      if (that == null)\n         return 1;\n      if (this == that)\n         return 0;\n      return this.token.compareTo(that.token);\n   }\n\n   @Override\n   protected Set<Service> delegate() {\n      return serviceCatalog;\n   }\n\n   @Override\n   public String getAuthToken() {\n      return token.getId();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/domain/ApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\nimport java.util.Set;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.Resource;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Class ApiMetadata\n */\npublic class ApiMetadata extends Resource {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromApiMetadata(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> extends Resource.Builder<T>  {\n      protected String status;\n      protected Date updated;\n      protected Set<MediaType> mediaTypes = ImmutableSet.of();\n\n      /**\n       * @see ApiMetadata#getStatus()\n       */\n      public T status(String status) {\n         this.status = status;\n         return self();\n      }\n\n      /**\n       * @see ApiMetadata#getUpdated()\n       */\n      public T updated(Date updated) {\n         this.updated = updated;\n         return self();\n      }\n\n      /**\n       * @see ApiMetadata#getMediaTypes()\n       */\n      public T mediaTypes(Set<MediaType> mediaTypes) {\n         this.mediaTypes = ImmutableSet.copyOf(checkNotNull(mediaTypes, \"mediaTypes\"));\n         return self();\n      }\n\n      public T mediaTypes(MediaType... in) {\n         return mediaTypes(ImmutableSet.copyOf(in));\n      }\n\n      public ApiMetadata build() {\n         return new ApiMetadata(id, name, links, status, updated, mediaTypes);\n      }\n\n      public T fromApiMetadata(ApiMetadata in) {\n         return super.fromResource(in)\n               .status(in.getStatus())\n               .updated(in.getUpdated())\n               .mediaTypes(in.getMediaTypes());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String status;\n   private final Date updated;\n   @Named(\"media-types\")\n   private final Set<MediaType> mediaTypes;\n\n   @ConstructorProperties({\n         \"id\", \"name\", \"links\", \"status\", \"updated\", \"media-types\"\n   })\n   protected ApiMetadata(String id, @Nullable String name, java.util.Set<Link> links, @Nullable String status, @Nullable Date updated, Set<MediaType> mediaTypes) {\n      super(id, name, links);\n      this.status = status;\n      this.updated = updated;\n      this.mediaTypes = ImmutableSet.copyOf(checkNotNull(mediaTypes, \"mediaTypes\"));\n   }\n\n   @Nullable\n   public String getStatus() {\n      return this.status;\n   }\n\n   @Nullable\n   public Date getUpdated() {\n      return this.updated;\n   }\n\n   public Set<MediaType> getMediaTypes() {\n      return this.mediaTypes;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(status, updated, mediaTypes);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      ApiMetadata that = ApiMetadata.class.cast(obj);\n      return super.equals(that) && Objects.equal(this.status, that.status)\n            && Objects.equal(this.updated, that.updated)\n            && Objects.equal(this.mediaTypes, that.mediaTypes);\n   }\n\n   protected ToStringHelper string() {\n      return super.string()\n            .add(\"status\", status).add(\"updated\", updated).add(\"mediaTypes\", mediaTypes);\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/domain/Endpoint.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.domain;\n\nimport java.beans.ConstructorProperties;\nimport java.net.URI;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.base.Objects;\n\n/**\n * An network-accessible address, usually described by URL, where a service may\n * be accessed. If using an extension for templates, you can create an endpoint\n * template, which represents the templates of all the consumable services that\n * are available across the regions.\n *\n * @see <a href=\n *      \"http://docs.openstack.org/api/openstack-identity-service/2.0/content/Identity-Endpoint-Concepts-e1362.html\"\n *      />\n */\npublic class Endpoint {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromEndpoint(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String id;\n      protected String versionId;\n      protected String region;\n      protected URI publicURL;\n      protected URI internalURL;\n      protected URI adminURL;\n      protected String tenantId;\n      protected URI versionInfo;\n      protected URI versionList;\n\n\n      /**\n       * @see Endpoint#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see Endpoint#getVersionId()\n       */\n      public T versionId(String versionId) {\n         this.versionId = versionId;\n         return self();\n      }\n\n      /**\n       * @see Endpoint#getRegion()\n       */\n      public T region(String region) {\n         this.region = region;\n         return self();\n      }\n\n      /**\n       * @see Endpoint#getPublicURL()\n       */\n      public T publicURL(URI publicURL) {\n         this.publicURL = publicURL;\n         return self();\n      }\n\n      /**\n       * @see Endpoint#getInternalURL()\n       */\n      public T internalURL(URI internalURL) {\n         this.internalURL = internalURL;\n         return self();\n      }\n\n      /**\n       * @see Endpoint#getAdminURL()\n       */\n      public T adminURL(URI adminURL) {\n         this.adminURL = adminURL;\n         return self();\n      }\n\n      /**\n       * @see Endpoint#getVersionInfo()\n       */\n      public T versionInfo(URI versionInfo) {\n         this.versionInfo = versionInfo;\n         return self();\n      }\n\n      /**\n       * @see Endpoint#getVersionList()\n       */\n      public T versionList(URI versionList) {\n         this.versionList = versionList;\n         return self();\n      }\n\n      /**\n       * @see Endpoint#getPublicURL()\n       */\n      public T publicURL(String publicURL) {\n         return publicURL(URI.create(publicURL));\n      }\n\n      /**\n       * @see Endpoint#getInternalURL()\n       */\n      public T internalURL(String internalURL) {\n         return internalURL(URI.create(internalURL));\n      }\n\n      /**\n       * @see Endpoint#getAdminURL()\n       */\n      public T adminURL(String adminURL) {\n         return adminURL(URI.create(adminURL));\n      }\n\n      /**\n       * @see Endpoint#getVersionInfo()\n       */\n      public T versionInfo(String versionInfo) {\n         return versionInfo(URI.create(versionInfo));\n      }\n\n      /**\n       * @see Endpoint#getVersionList()\n       */\n      public T versionList(String versionList) {\n         return versionList(URI.create(versionList));\n      }\n\n      /**\n       * @see Endpoint#getTenantId()\n       */\n      public T tenantId(String tenantId) {\n         this.tenantId = tenantId;\n         return self();\n      }\n\n      public Endpoint build() {\n         return new Endpoint(id, versionId, region, publicURL, internalURL, adminURL, versionInfo, versionList, null,\n               tenantId);\n      }\n\n      public T fromEndpoint(Endpoint in) {\n         return this.versionId(in.getVersionId()).region(in.getRegion()).publicURL(in.getPublicURL())\n               .internalURL(in.getInternalURL()).adminURL(in.getAdminURL()).versionInfo(in.getVersionInfo())\n               .versionList(in.getVersionList()).tenantId(in.getTenantId());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final String tenantId;\n   private final String region;\n   private final URI publicURL;\n   private final URI internalURL;\n   private final URI adminURL;\n\n   // fields not defined in\n   // https://github.com/openstack/keystone/blob/master/keystone/service.py\n   private final String versionId;\n   private final URI versionInfo;\n   private final URI versionList;\n\n   @ConstructorProperties({ \"id\", \"versionId\", \"region\", \"publicURL\", \"internalURL\", \"adminURL\", \"versionInfo\",\n         \"versionList\", \"tenantName\", \"tenantId\" })\n   protected Endpoint(@Nullable String id, @Nullable String versionId, @Nullable String region,\n         @Nullable URI publicURL, @Nullable URI internalURL, @Nullable URI adminURL, @Nullable URI versionInfo,\n         @Nullable URI versionList, @Nullable String tenantName, @Nullable String tenantId) {\n      this.id = id;\n      this.versionId = versionId;\n      this.tenantId = tenantId != null ? tenantId : tenantName;\n      this.region = region;\n      this.publicURL = publicURL;\n      this.internalURL = internalURL;\n      this.adminURL = adminURL;\n      this.versionInfo = versionInfo;\n      this.versionList = versionList;\n   }\n\n   /**\n    * When providing an ID, it is assumed that the endpoint exists in the\n    * current OpenStack deployment\n    *\n    * @return the id of the endpoint in the current OpenStack deployment, or\n    *         null if not specified\n    */\n   @Nullable\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    *\n    * <h4>Note</h4>\n    *\n    * This is not defined in <a href=\n    * \"https://github.com/openstack/keystone/blob/master/keystone/service.py\"\n    * >KeyStone</a>, rather only in <a href=\n    * \"http://docs.rackspace.com/auth/api/v2.0/auth-client-devguide/content/Release_Notes-d1e140.html\"\n    * >Rackspace</a>\n    */\n   @Nullable\n   public String getVersionId() {\n      return this.versionId;\n   }\n\n   /**\n    * @return the region of the endpoint, or null if not specified\n    */\n   @Nullable\n   public String getRegion() {\n      return this.region;\n   }\n\n   /**\n    * @return the public url of the endpoint\n    */\n   @Nullable\n   public URI getPublicURL() {\n      return this.publicURL;\n   }\n\n   /**\n    * @return the internal url of the endpoint\n    */\n   @Nullable\n   public URI getInternalURL() {\n      return this.internalURL;\n   }\n\n   /**\n    * @return the admin url of the endpoint\n    */\n   @Nullable\n   public URI getAdminURL() {\n      return this.adminURL;\n   }\n\n   /**\n    *\n    * <h4>Note</h4>\n    *\n    * This is not defined in <a href=\n    * \"https://github.com/openstack/keystone/blob/master/keystone/service.py\"\n    * >KeyStone</a>, rather only in <a href=\n    * \"http://docs.rackspace.com/auth/api/v2.0/auth-client-devguide/content/Release_Notes-d1e140.html\"\n    * >Rackspace</a>\n    */\n   @Nullable\n   public URI getVersionInfo() {\n      return this.versionInfo;\n   }\n\n   /**\n    *\n    * <h4>Note</h4>\n    *\n    * This is not defined in <a href=\n    * \"https://github.com/openstack/keystone/blob/master/keystone/service.py\"\n    * >KeyStone</a>, rather only in <a href=\n    * \"http://docs.rackspace.com/auth/api/v2.0/auth-client-devguide/content/Release_Notes-d1e140.html\"\n    * >Rackspace</a>\n    */\n   @Nullable\n   public URI getVersionList() {\n      return this.versionList;\n   }\n\n   /**\n    * @return the tenant versionId of the endpoint or null\n    */\n   @Nullable\n   public String getTenantId() {\n      return this.tenantId;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, versionId, region, publicURL, internalURL, adminURL, versionInfo, versionList,\n            tenantId);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      Endpoint that = Endpoint.class.cast(obj);\n      return Objects.equal(this.id, that.id) && Objects.equal(this.versionId, that.versionId)\n            && Objects.equal(this.region, that.region) && Objects.equal(this.publicURL, that.publicURL)\n            && Objects.equal(this.internalURL, that.internalURL) && Objects.equal(this.adminURL, that.adminURL)\n            && Objects.equal(this.versionInfo, that.versionInfo) && Objects.equal(this.versionList, that.versionList)\n            && Objects.equal(this.tenantId, that.tenantId);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"id\", id).add(\"versionId\", versionId)\n            .add(\"region\", region).add(\"publicURL\", publicURL).add(\"internalURL\", internalURL)\n            .add(\"adminURL\", adminURL).add(\"versionInfo\", versionInfo).add(\"versionList\", versionList)\n            .add(\"tenantId\", tenantId);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/domain/MediaType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Class MediaType\n */\npublic class MediaType {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromMediaType(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>>  {\n      protected abstract T self();\n\n      protected String base;\n      protected String type;\n\n      /**\n       * @see MediaType#getBase()\n       */\n      public T base(String base) {\n         this.base = base;\n         return self();\n      }\n\n      /**\n       * @see MediaType#getType()\n       */\n      public T type(String type) {\n         this.type = type;\n         return self();\n      }\n\n      public MediaType build() {\n         return new MediaType(base, type);\n      }\n\n      public T fromMediaType(MediaType in) {\n         return this\n               .base(in.getBase())\n               .type(in.getType());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String base;\n   private final String type;\n\n   @ConstructorProperties({\n         \"base\", \"type\"\n   })\n   protected MediaType(@Nullable String base, @Nullable String type) {\n      this.base = base;\n      this.type = type;\n   }\n\n   @Nullable\n   public String getBase() {\n      return this.base;\n   }\n\n   @Nullable\n   public String getType() {\n      return this.type;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(base, type);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      MediaType that = MediaType.class.cast(obj);\n      return Objects.equal(this.base, that.base)\n            && Objects.equal(this.type, that.type);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"base\", base).add(\"type\", type);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/domain/Role.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * A personality that a user assumes when performing a specific set of operations. A role includes a\n * set of right and privileges. A user assuming that role inherits those rights and privileges.\n * <p/>\n * In Keystone, a token that is issued to a user includes the list of roles that user can assume.\n * Services that are being called by that user determine how they interpret the set of roles a user\n * has and which operations or resources each roles grants access to.\n *\n * @see <a href=\"http://docs.openstack.org/api/openstack-identity-service/2.0/content/Identity-Service-Concepts-e1362.html\"\n/>\n */\npublic class Role {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromRole(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>>  {\n      protected abstract T self();\n      protected String id;\n      protected String name;\n      protected String description;\n      protected String serviceId;\n      protected String tenantId;\n\n      /**\n       * @see Role#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see Role#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /**\n       * @see Role#getDescription()\n       */\n      public T description(String description) {\n         this.description = description;\n         return self();\n      }\n\n      /**\n       * @see Role#getServiceId()\n       */\n      public T serviceId(String serviceId) {\n         this.serviceId = serviceId;\n         return self();\n      }\n\n      /**\n       * @see Role#getTenantId()\n       */\n      public T tenantId(String tenantId) {\n         this.tenantId = tenantId;\n         return self();\n      }\n\n      public Role build() {\n         return new Role(id, name, description, serviceId, tenantId, null);\n      }\n\n      public T fromRole(Role in) {\n         return this\n               .id(in.getId())\n               .name(in.getName())\n               .description(in.getDescription())\n               .serviceId(in.getServiceId())\n               .tenantId(in.getTenantId());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final String name;\n   private final String description;\n   private final String serviceId;\n   private final String tenantId;\n\n   @ConstructorProperties({\n         \"id\", \"name\", \"description\", \"serviceId\", \"tenantId\", \"tenantName\"\n   })\n   protected Role(@Nullable String id, String name, @Nullable String description, @Nullable String serviceId, @Nullable String tenantId,\n                  @Nullable String tenantName) {\n      this.id = id;\n      this.name = checkNotNull(name, \"name\");\n      this.description = description;\n      this.serviceId = serviceId;\n      this.tenantId = tenantId != null ? tenantId :  tenantName;\n   }\n\n   /**\n    * When providing an ID, it is assumed that the role exists in the current OpenStack deployment\n    *\n    * @return the id of the role in the current OpenStack deployment\n    */\n   @Nullable\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * @return the name of the role\n    */\n   public String getName() {\n      return this.name;\n   }\n\n   /**\n    * @return the description of the role\n    */\n   @Nullable\n   public String getDescription() {\n      return this.description;\n   }\n\n   /**\n    * @return the service id of the role or null, if not present\n    */\n   @Nullable\n   public String getServiceId() {\n      return this.serviceId;\n   }\n\n   /**\n    * @return the tenant id of the role or null, if not present\n    */\n   @Nullable\n   public String getTenantId() {\n      return this.tenantId;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, name, description, serviceId, tenantId);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Role that = Role.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n            && Objects.equal(this.name, that.name)\n            && Objects.equal(this.description, that.description)\n            && Objects.equal(this.serviceId, that.serviceId)\n            && Objects.equal(this.tenantId, that.tenantId);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).omitNullValues()\n            .add(\"id\", id).add(\"name\", name).add(\"description\", description).add(\"serviceId\", serviceId).add(\"tenantId\", tenantId);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/domain/Service.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ForwardingSet;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * An OpenStack service, such as Compute (Nova), Object Storage (Swift), or Image Service (Glance).\n * A service provides one or more endpoints through which users can access resources and perform\n * (presumably useful) operations.\n *\n * @see <a href=\"http://docs.openstack.org/api/openstack-typeentity-service/2.0/content/Identity-Service-Concepts-e1362.html\"\n/>\n */\npublic class Service extends ForwardingSet<Endpoint> {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromService(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>>  {\n      protected abstract T self();\n\n      protected String id;\n      protected String type;\n      protected String name;\n      protected String description;\n      protected ImmutableSet.Builder<Endpoint> endpoints = ImmutableSet.<Endpoint>builder();\n      \n      /**\n       * @see Service#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see Service#getType()\n       */\n      public T type(String type) {\n         this.type = type;\n         return self();\n      }\n\n      /**\n       * @see Service#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n      \n      /**\n       * @see Service#getDescription()\n       */\n      public T description(String description) {\n         this.description = description;\n         return self();\n      }\n\n      /**\n       * @see Service#delegate()\n       */\n      public T endpoint(Endpoint endpoint) {\n         this.endpoints.add(endpoint);\n         return self();\n      }\n\n      /**\n       * @see Service#delegate()\n       */\n      public T endpoints(Iterable<Endpoint> endpoints) {\n         this.endpoints.addAll(endpoints);\n         return self();\n      }\n\n      public Service build() {\n         return new Service(id, type, name, description, endpoints.build());\n      }\n\n      public T fromService(Service in) {\n         return this\n               .id(in.getId())\n               .type(in.getType())\n               .name(in.getName())\n               .description(in.getDescription())\n               .endpoints(in);\n      }\n   }\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final String type;\n   private final String name;\n   private final String description;\n   private final Set<Endpoint> endpoints;\n\n   @ConstructorProperties({\n         \"id\", \"type\", \"name\", \"description\", \"endpoints\"\n   })\n   protected Service(@Nullable String id, String type, String name, @Nullable String description, @Nullable Set<Endpoint> endpoints) {\n      this.id = id;\n      this.type = checkNotNull(type, \"type\");\n      this.name = checkNotNull(name, \"name\");\n      this.description = description;\n      this.endpoints = endpoints == null ? ImmutableSet.<Endpoint>of() : ImmutableSet.copyOf(endpoints);\n   }\n   \n   /**\n    * When providing an ID, it is assumed that the service exists in the current OpenStack deployment\n    *\n    * @return the id of the service in the current OpenStack deployment\n    */\n   @Nullable\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * such as {@code compute} (Nova), {@code object-store} (Swift), or {@code image} (Glance)\n    *\n    * @return the type of the service in the current OpenStack deployment\n    */\n   public String getType() {\n      return this.type;\n   }\n\n   /**\n    * @return the name of the service\n    */\n   public String getName() {\n      return this.name;\n   }\n   \n   /**\n    * @return the description of the service\n    */\n   public String getDescription() {\n      return this.description;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, type, name, description, endpoints);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Service that = Service.class.cast(obj);\n      return Objects.equal(this.id, that.id) \n            && Objects.equal(this.type, that.type)\n            && Objects.equal(this.name, that.name)\n            && Objects.equal(this.description, that.description)\n            && Objects.equal(this.endpoints, that.endpoints);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).omitNullValues()\n            .add(\"id\", id).add(\"type\", type).add(\"name\", name)\n            .add(\"description\", description).add(\"endpoints\", endpoints);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   protected Set<Endpoint> delegate() {\n      return endpoints;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/domain/Tenant.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * A container used to group or isolate resources and/or identity objects.\n * Depending on the service operator, a tenant may map to a customer, account,\n * organization, or project.\n * \n * @see <a href=\n *      \"http://docs.openstack.org/api/openstack-identity-service/2.0/content/Identity-Service-Concepts-e1362.html\"\n *      />\n */\npublic class Tenant {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromTenant(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String id;\n      protected String name;\n      protected String description;\n      protected Boolean enabled;\n\n      /**\n       * @see Tenant#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see Tenant#isEnabled()\n       */\n      public T enabled(Boolean enabled) {\n         this.enabled = enabled;\n         return self();\n      }\n\n      /**\n       * @see Tenant#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /**\n       * @see Tenant#getDescription()\n       */\n      public T description(String description) {\n         this.description = description;\n         return self();\n      }\n\n      public Tenant build() {\n         return new Tenant(id, name, description, enabled);\n      }\n\n      public T fromTenant(Tenant in) {\n         return this.id(in.getId()).name(in.getName()).description(in.getDescription());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final String name;\n   private final String description;\n   private final Boolean enabled;\n\n   @ConstructorProperties({ \"id\", \"name\", \"description\", \"enabled\" })\n   protected Tenant(String id, String name, @Nullable String description, @Nullable Boolean enabled) {\n      this.id = checkNotNull(id, \"id\");\n      this.name = checkNotNull(name, \"name\");\n      this.description = description;\n      this.enabled = enabled;\n   }\n\n   /**\n    * When providing an ID, it is assumed that the tenant exists in the current\n    * OpenStack deployment\n    * \n    * @return the id of the tenant in the current OpenStack deployment\n    */\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * @return the name of the tenant\n    */\n   public String getName() {\n      return this.name;\n   }\n\n   /**\n    * @return the description of the tenant\n    */\n   @Nullable\n   public String getDescription() {\n      return this.description;\n   }\n\n   /**\n    * @return if the tenant is enabled\n    */\n   public boolean isEnabled() {\n      return this.enabled;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, name, description);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      Tenant that = Tenant.class.cast(obj);\n      return Objects.equal(this.id, that.id) && Objects.equal(this.name, that.name)\n            && Objects.equal(this.description, that.description) && Objects.equal(this.enabled, that.enabled);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"id\", id).add(\"name\", name)\n            .add(\"description\", description).add(\"enabled\", enabled);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/domain/Token.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.base.Optional;\n\n/**\n * A token is an arbitrary bit of text that is used to access resources. Each token has a scope\n * which describes which resources are accessible with it. A token may be revoked at anytime and is\n * valid for a finite duration.\n * <p/>\n * While Keystone supports token-based authentication in this release, the intention is for it to\n * support additional protocols in the future. The intent is for it to be an integration service\n * foremost, and not a aspire to be a full-fledged identity store and management solution.\n *\n * @see <a href=\"http://docs.openstack.org/api/openstack-identity-service/2.0/content/Identity-Service-Concepts-e1362.html\"\n/>\n */\npublic class Token implements Comparable<Token> {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromToken(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>>  {\n      protected abstract T self();\n\n      protected String id;\n      protected Date expires;\n      protected Optional<Tenant> tenant = Optional.absent();\n\n      /**\n       * @see Token#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see Token#getExpires()\n       */\n      public T expires(Date expires) {\n         this.expires = expires;\n         return self();\n      }\n\n      /**\n       * @see Token#getTenant()\n       */\n      public T tenant(Tenant tenant) {\n         this.tenant = Optional.fromNullable(tenant);\n         return self();\n      }\n\n      public Token build() {\n         return new Token(id, expires, tenant);\n      }\n\n      public T fromToken(Token in) {\n         return this\n               .id(in.getId())\n               .expires(in.getExpires())\n               .tenant(in.getTenant().orNull());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final Date expires;\n   private final Optional<Tenant> tenant;\n\n   @ConstructorProperties({\n         \"id\", \"expires\", \"tenant\"\n   })\n   protected Token(String id, Date expires, @Nullable Optional<Tenant> tenant) {\n      this.id = checkNotNull(id, \"id\");\n      this.expires = checkNotNull(expires, \"expires\");\n      this.tenant = tenant == null ? Optional.<Tenant> absent() : tenant;\n   }\n\n   /**\n    * When providing an ID, it is assumed that the token exists in the current OpenStack deployment\n    *\n    * @return the id of the token in the current OpenStack deployment\n    */\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * @return the expires of the token\n    */\n   public Date getExpires() {\n      return this.expires;\n   }\n\n   /**\n    * @return the tenant assigned to the token\n    */\n   public Optional<Tenant> getTenant() {\n      return this.tenant;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, expires, tenant);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Token that = Token.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n            && Objects.equal(this.expires, that.expires)\n            && Objects.equal(this.tenant, that.tenant);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).omitNullValues()\n            .add(\"id\", id).add(\"expires\", expires).add(\"tenant\", tenant.orNull());\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int compareTo(Token that) {\n      if (that == null)\n         return 1;\n      if (this == that)\n         return 0;\n      return this.id.compareTo(that.id);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/domain/User.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ForwardingSet;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * A digital representation of a person, system, or service who uses OpenStack\n * cloud services. Keystone authentication services will validate that incoming\n * request are being made by the user who claims to be making the call. Users\n * have a login and may be assigned tokens to access users. Users may be\n * directly assigned to a particular tenant and behave as if they are contained\n * in that tenant.\n * \n * @see <a href=\n *      \"http://docs.openstack.org/api/openstack-identity-service/2.0/content/Identity-User-Concepts-e1362.html\"\n *      />\n */\npublic class User extends ForwardingSet<Role> {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromUser(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String id;\n      protected String name;\n      protected String email;\n      protected Boolean enabled;\n      protected String tenantId;\n      protected ImmutableSet.Builder<Role> roles = ImmutableSet.<Role> builder();\n\n      /**\n       * @see User#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see User#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /**\n       * @see User#getEmail()\n       */\n      public T email(String email) {\n         this.email = email;\n         return self();\n      }\n\n      /**\n       * @see User#isEnabled()\n       */\n      public T enabled(Boolean enabled) {\n         this.enabled = enabled;\n         return self();\n      }\n\n      /**\n       * @see User#getTenantId\n       */\n      public T tenantId(String tenantId) {\n         this.tenantId = tenantId;\n         return self();\n      }\n\n      /**\n       * @see User#delegate()\n       */\n      public T role(Role role) {\n         this.roles.add(role);\n         return self();\n      }\n\n      /**\n       * @see User#delegate()\n       */\n      public T roles(Iterable<Role> roles) {\n         this.roles.addAll(roles);\n         return self();\n      }\n\n      public User build() {\n         return new User(id, name, email, enabled, tenantId, roles.build());\n      }\n\n      public T fromUser(User in) {\n         return this.id(in.getId()).name(in.getName()).email(in.getEmail()).enabled(in.isEnabled())\n               .tenantId(in.getTenantId()).roles(in);\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final String name;\n   private final String email;\n   private final Boolean enabled;\n   private final String tenantId;\n   private final Set<Role> roles;\n\n   @ConstructorProperties({ \"id\", \"name\", \"email\", \"enabled\", \"tenantId\", \"roles\" })\n   protected User(String id, String name, @Nullable String email, @Nullable Boolean enabled, @Nullable String tenantId,\n         @Nullable Set<Role> roles) {\n      this.id = checkNotNull(id, \"id\");\n      this.name = checkNotNull(name, \"name\");\n      this.email = email;\n      this.enabled = enabled;\n      this.tenantId = tenantId;\n      this.roles = roles == null ? ImmutableSet.<Role> of() : ImmutableSet.copyOf(roles);\n   }\n\n   /**\n    * When providing an ID, it is assumed that the user exists in the current\n    * OpenStack deployment\n    * \n    * @return the id of the user in the current OpenStack deployment\n    */\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * @return the name of the user\n    */\n   public String getName() {\n      return this.name;\n   }\n\n   /**\n    * @return the e-mail\n    */\n   public String getEmail() {\n      return this.email;\n   }\n\n   /**\n    * @return if the user is enabled\n    */\n   public boolean isEnabled() {\n      return this.enabled;\n   }\n\n   /**\n    * @return the user tenant\n    */\n   public String getTenantId() {\n      return this.tenantId;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, name, email, enabled, tenantId, roles);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      User that = User.class.cast(obj);\n      return Objects.equal(this.id, that.id) && Objects.equal(this.name, that.name)\n            && Objects.equal(this.roles, that.roles) && Objects.equal(this.enabled, that.enabled)\n            && Objects.equal(this.tenantId, that.tenantId) && Objects.equal(this.email, that.email);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"id\", id).add(\"name\", name).add(\"email\", email)\n            .add(\"enabled\", enabled).add(\"roles\", roles).add(\"tenanId\", tenantId);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   protected Set<Role> delegate() {\n      return roles;\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/extensions/ExtensionAliases.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.extensions;\n\n/**\n * Extension aliases\n *\n * @see <a href= \"http://docs.openstack.org/developer/keystone/extension_development.html\" />\n */\npublic final class ExtensionAliases {\n   /**\n    * OpenStack Keystone Admin Support\n    */\n   public static final String OS_KSADM = \"OS-KSADM\";\n\n   private ExtensionAliases() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/extensions/ExtensionNames.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.extensions;\n\n/**\n * Extension names\n *\n * @see <a href= \"http://docs.openstack.org/developer/keystone/extension_development.html\" />\n */\npublic final class ExtensionNames {\n   /**\n    * OpenStack Keystone Admin Support\n    */\n   public static final String OS_KSADM = \"OpenStack Keystone Admin\";\n\n   private ExtensionNames() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/extensions/ExtensionNamespaces.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.extensions;\n\n/**\n * Extension namespaces\n *\n * @see <a href= \"http://docs.openstack.org/developer/keystone/extension_development.html\" />\n */\npublic final class ExtensionNamespaces {\n   /**\n    * OpenStack Keystone Admin Support\n    */\n   public static final String OS_KSADM = \"http://docs.openstack.org/identity/api/ext/OS-KSADM/v1.0\";\n\n   private ExtensionNamespaces() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/extensions/RoleAdminApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.extensions;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyFluentIterableOnNotFoundOr404;\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.keystone.v2_0.domain.Role;\nimport org.jclouds.openstack.v2_0.ServiceType;\nimport org.jclouds.openstack.v2_0.services.Extension;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.WrapWith;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.collect.FluentIterable;\n\n/**\n * Provides access to the OpenStack Keystone Role Administration Extension API.\n *\n */\n@Beta\n@Extension(of = ServiceType.IDENTITY, namespace = ExtensionNamespaces.OS_KSADM,\n      name = ExtensionNames.OS_KSADM, alias = ExtensionAliases.OS_KSADM)\n@RequestFilters(AuthenticateRequest.class)\n@Path(\"OS-KSADM/roles\")\npublic interface RoleAdminApi {\n\n   /**\n    * Returns a summary list of roles.\n    *\n    * @return The list of roles\n    */\n   @Named(\"role:list\")\n   @GET\n   @SelectJson(\"roles\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<? extends Role> list();\n\n   /**\n    * Creates a new Role\n    *\n    * @return the new Role\n    */\n   @Named(\"role:create\")\n   @POST\n   @SelectJson(\"role\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @WrapWith(\"role\")\n   @Nullable\n   Role create(@PayloadParam(\"name\") String name);\n\n   /**\n    * Gets the role\n    *\n    * @return the role\n    */\n   @Named(\"role:get\")\n   @GET\n   @SelectJson(\"role\")\n   @Path(\"/{id}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Role get(@PathParam(\"id\") String roleId);\n\n   /**\n    * Deletes a role\n    *\n    * @return true if successful\n    */\n   @Named(\"role:delete\")\n   @DELETE\n   @Path(\"/{id}\")\n   @Consumes\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean delete(@PathParam(\"id\") String roleId);\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/extensions/ServiceAdminApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.extensions;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyPagedIterableOnNotFoundOr404;\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.collect.PagedIterable;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.keystone.v2_0.KeystoneFallbacks.EmptyPaginatedCollectionOnNotFoundOr404;\nimport org.jclouds.openstack.keystone.v2_0.domain.Service;\nimport org.jclouds.openstack.keystone.v2_0.functions.internal.ParseServices;\nimport org.jclouds.openstack.keystone.v2_0.functions.internal.ParseServices.ToPagedIterable;\nimport org.jclouds.openstack.v2_0.ServiceType;\nimport org.jclouds.openstack.v2_0.domain.PaginatedCollection;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\nimport org.jclouds.openstack.v2_0.services.Extension;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.Transform;\nimport org.jclouds.rest.annotations.WrapWith;\n\nimport com.google.common.annotations.Beta;\n\n/**\n * Provides access to Service Administration actions.\n */\n@Beta\n@Consumes(MediaType.APPLICATION_JSON)\n@Extension(of = ServiceType.IDENTITY, namespace = ExtensionNamespaces.OS_KSADM,\n      name = ExtensionNames.OS_KSADM, alias = ExtensionAliases.OS_KSADM)\n@RequestFilters(AuthenticateRequest.class)\n@Path(\"OS-KSADM/services\")\npublic interface ServiceAdminApi {\n\n   /**\n    * Retrieve the list of services\n    * <p/>\n    *\n    * @return the list of services\n    */\n   @Named(\"service:list\")\n   @GET\n   @ResponseParser(ParseServices.class)\n   @Transform(ToPagedIterable.class)\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   PagedIterable<Service> list();\n\n   @Named(\"service:list\")\n   @GET\n   @ResponseParser(ParseServices.class)\n   @Fallback(EmptyPaginatedCollectionOnNotFoundOr404.class)\n   PaginatedCollection<Service> list(PaginationOptions options);\n\n   /**\n    * Creates a new Service\n    *\n    * @return the new Service\n    */\n   @Named(\"service:create\")\n   @POST\n   @SelectJson(\"OS-KSADM:service\")\n   @WrapWith(\"OS-KSADM:service\")\n   @Nullable\n   Service create(@PayloadParam(\"name\") String name, @PayloadParam(\"type\") String type,\n         @PayloadParam(\"description\") String description);\n\n   /**\n    * Gets the service\n    *\n    * @return the service\n    */\n   @Named(\"service:get\")\n   @GET\n   @SelectJson(\"OS-KSADM:service\")\n   @Path(\"/{serviceId}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Service get(@PathParam(\"serviceId\") String serviceId);\n\n   /**\n    * Deletes a service\n    *\n    * @return true if successful\n    */\n   @Named(\"service:delete\")\n   @DELETE\n   @Path(\"/{id}\")\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean delete(@PathParam(\"id\") String serviceId);\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/extensions/TenantAdminApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.extensions;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.keystone.v2_0.domain.Tenant;\nimport org.jclouds.openstack.keystone.v2_0.options.CreateTenantOptions;\nimport org.jclouds.openstack.keystone.v2_0.options.UpdateTenantOptions;\nimport org.jclouds.openstack.v2_0.ServiceType;\nimport org.jclouds.openstack.v2_0.services.Extension;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\nimport com.google.common.annotations.Beta;\n\n/**\n * Provides access to Tenant Administration actions.\n */\n@Beta\n@Consumes(MediaType.APPLICATION_JSON)\n@Extension(of = ServiceType.IDENTITY, namespace = ExtensionNamespaces.OS_KSADM,\n      name = ExtensionNames.OS_KSADM, alias = ExtensionAliases.OS_KSADM)\n@RequestFilters(AuthenticateRequest.class)\n@Path(\"/tenants\")\npublic interface TenantAdminApi {\n\n   /**\n    * Creates a new tenant\n    *\n    * @return the new tenant\n    */\n   @Named(\"tenant:create\")\n   @POST\n   @SelectJson(\"tenant\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @Nullable\n   Tenant create(@PayloadParam(\"name\") String name);\n\n   /**\n    * Creates a new tenant\n    *\n    * @return the new tenant\n    */\n   @Named(\"tenant:create\")\n   @POST\n   @SelectJson(\"tenant\")\n   @MapBinder(CreateTenantOptions.class)\n   @Nullable\n   Tenant create(@PayloadParam(\"name\") String name, CreateTenantOptions options);\n\n   /**\n    * Deletes a tenant\n    *\n    * @return true if successful\n    */\n   @Named(\"tenant:delete\")\n   @DELETE\n   @Path(\"/{id}\")\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean delete(@PathParam(\"id\") String userId);\n\n   /**\n    * Updates a tenant\n    *\n    * @return the updated tenant\n    */\n   @Named(\"tenant:updateTenant\")\n   @PUT\n   @Path(\"/{id}\")\n   @SelectJson(\"tenant\")\n   @MapBinder(UpdateTenantOptions.class)\n   @Nullable\n   Tenant update(@PathParam(\"id\") String id, UpdateTenantOptions options);\n\n   /**\n    * Adds role to a user on a tenant\n    */\n   @Named(\"tenant:addRoleOnTenant\")\n   @PUT\n   @Path(\"/{id}/users/{userId}/roles/OS-KSADM/{roleId}\")\n   void addRoleOnTenant(@PathParam(\"id\") String tenantId, @PathParam(\"userId\") String userId,\n         @PathParam(\"roleId\") String roleId);\n\n   /**\n    * Deletes role to a user on tenant\n    *\n    * @return true if successful\n    */\n   @Named(\"tenant:deleteRoleOnTenant\")\n   @DELETE\n   @Path(\"/{id}/users/{userId}/roles/OS-KSADM/{roleId}\")\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean deleteRoleOnTenant(@PathParam(\"id\") String tenantId, @PathParam(\"userId\") String userdId,\n         @PathParam(\"roleId\") String roleId);\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/extensions/UserAdminApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.extensions;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.keystone.v2_0.domain.User;\nimport org.jclouds.openstack.keystone.v2_0.options.CreateUserOptions;\nimport org.jclouds.openstack.keystone.v2_0.options.UpdateUserOptions;\nimport org.jclouds.openstack.v2_0.ServiceType;\nimport org.jclouds.openstack.v2_0.services.Extension;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\nimport com.google.common.annotations.Beta;\n\n/**\n * Provides access to User Administration actions.\n */\n@Beta\n@Consumes(MediaType.APPLICATION_JSON)\n@Extension(of = ServiceType.IDENTITY, namespace = ExtensionNamespaces.OS_KSADM,\n      name = ExtensionNames.OS_KSADM, alias = ExtensionAliases.OS_KSADM)\n@RequestFilters(AuthenticateRequest.class)\n@Path(\"/users\")\npublic interface UserAdminApi {\n\n   /**\n    * Creates a new user\n    *\n    * @return the new user\n    */\n   @Named(\"user:create\")\n   @POST\n   @SelectJson(\"user\")\n   @Nullable\n   User create(@PayloadParam(\"name\") String name, @PayloadParam(\"password\") String password);\n\n   /**\n    * Creates a new user\n    *\n    * @return the new user\n    */\n   @Named(\"user:create\")\n   @POST\n   @SelectJson(\"user\")\n   @MapBinder(CreateUserOptions.class)\n   @Nullable\n   User create(@PayloadParam(\"name\") String name,\n         @PayloadParam(\"password\") String password, CreateUserOptions options);\n\n   /**\n    * Deletes an user\n    *\n    * @return true if successful\n    */\n   @Named(\"user:delete\")\n   @DELETE\n   @Path(\"/{id}\")\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean delete(@PathParam(\"id\") String userId);\n\n   /**\n    * Updates an user\n    *\n    * @return the updated user\n    */\n   @Named(\"user:updateUser\")\n   @PUT\n   @Path(\"/{id}\")\n   @SelectJson(\"user\")\n   @MapBinder(UpdateUserOptions.class)\n   @Nullable\n   User update(@PathParam(\"id\") String id, UpdateUserOptions options);\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/features/ServiceApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.features;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.keystone.v2_0.domain.Tenant;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\n/**\n * Provides access to the Keystone Tenant API.\n */\n@Consumes(MediaType.APPLICATION_JSON)\n@RequestFilters(AuthenticateRequest.class)\n@Path(\"/tenants\")\npublic interface ServiceApi {\n\n   /**\n    * The operation returns a list of tenants which the current token provides access to.\n    */\n   @Named(\"service:listTenants\")\n   @GET\n   @SelectJson(\"tenants\")\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<Tenant> listTenants();\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/features/TenantApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.features;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyPagedIterableOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.collect.PagedIterable;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.keystone.v2_0.KeystoneFallbacks.EmptyPaginatedCollectionOnNotFoundOr404;\nimport org.jclouds.openstack.keystone.v2_0.domain.Tenant;\nimport org.jclouds.openstack.keystone.v2_0.functions.internal.ParseTenants;\nimport org.jclouds.openstack.keystone.v2_0.functions.internal.ParseTenants.ToPagedIterable;\nimport org.jclouds.openstack.v2_0.domain.PaginatedCollection;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\nimport org.jclouds.openstack.v2_0.services.Identity;\nimport org.jclouds.rest.annotations.Endpoint;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.Transform;\n\nimport com.google.inject.name.Named;\n\n/**\n * Provides access to the Keystone Tenant API.\n */\n@Consumes(MediaType.APPLICATION_JSON)\n@RequestFilters(AuthenticateRequest.class)\n@Endpoint(Identity.class)\n@Path(\"/tenants\")\npublic interface TenantApi {\n\n   /**\n    * The operation returns a list of tenants which the current token provides access to.\n    */\n   @Named(\"tenant:list\")\n   @GET\n   @ResponseParser(ParseTenants.class)\n   @Transform(ToPagedIterable.class)\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   PagedIterable<Tenant> list();\n\n   @Named(\"tenant:list\")\n   @GET\n   @ResponseParser(ParseTenants.class)\n   @Fallback(EmptyPaginatedCollectionOnNotFoundOr404.class)\n   PaginatedCollection<Tenant> list(PaginationOptions options);\n\n   /**\n    * Retrieve information about a tenant, by tenant ID\n    *\n    * @return the information about the tenant\n    */\n   @Named(\"tenant:get\")\n   @GET\n   @SelectJson(\"tenant\")\n   @Path(\"/{id}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Tenant get(@PathParam(\"id\") String tenantId);\n\n   /**\n    * Retrieve information about a tenant, by tenant name\n    * <p/>\n    * NOTE: currently not working in openstack ( https://bugs.launchpad.net/keystone/+bug/956687 )\n    *\n    * @return the information about the tenant\n    */\n   @Named(\"tenant:get\")\n   @GET\n   @SelectJson(\"tenant\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Tenant getByName(@QueryParam(\"name\") String tenantName);\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/features/TokenApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.features;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.HEAD;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.keystone.v2_0.domain.Endpoint;\nimport org.jclouds.openstack.keystone.v2_0.domain.Token;\nimport org.jclouds.openstack.keystone.v2_0.domain.User;\nimport org.jclouds.openstack.v2_0.services.Identity;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\n/**\n * Provides access to the Keystone Admin API.\n */\n@Consumes(MediaType.APPLICATION_JSON)\n@RequestFilters(AuthenticateRequest.class)\n@org.jclouds.rest.annotations.Endpoint(Identity.class)\n@Path(\"/tokens/{token}\")\npublic interface TokenApi {\n\n   /**\n    * Validate a token and, if it is valid, return access information regarding the tenant (though not the service catalog)/\n    *\n    * @return the requested information\n    */\n   @Named(\"token:get\")\n   @GET\n   @SelectJson(\"token\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Token get(@PathParam(\"token\") String token);\n\n   /**\n    * Validate a token and, if it is valid, return access information regarding the tenant (though not the service catalog)/\n    *\n    * @return the requested information\n    */\n   @Named(\"token:getuser\")\n   @GET\n   @SelectJson(\"user\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   User getUserOfToken(@PathParam(\"token\") String token);\n\n   /**\n    * Validate a token. This is a high-performance variant of the #getToken() call that does not return any further\n    * information.\n    *\n    * @return true if the token is valid\n    */\n   @Named(\"token:valid\")\n   @HEAD\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean isValid(@PathParam(\"token\") String token);\n\n   /**\n    * List all endpoints for a token\n    * <p/>\n    * NOTE: currently not working in openstack ( https://bugs.launchpad.net/keystone/+bug/988672 )\n    *\n    * @return the set of endpoints\n    */\n   @Named(\"token:listEndpoints\")\n   @GET\n   @SelectJson(\"endpoints\")\n   @Path(\"/endpoints\")\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<Endpoint> listEndpointsForToken(@PathParam(\"token\") String token);\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/features/UserApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.features;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyPagedIterableOnNotFoundOr404;\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.collect.PagedIterable;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.keystone.v2_0.KeystoneFallbacks.EmptyPaginatedCollectionOnNotFoundOr404;\nimport org.jclouds.openstack.keystone.v2_0.domain.Role;\nimport org.jclouds.openstack.keystone.v2_0.domain.User;\nimport org.jclouds.openstack.keystone.v2_0.functions.internal.ParseUsers;\nimport org.jclouds.openstack.keystone.v2_0.functions.internal.ParseUsers.ToPagedIterable;\nimport org.jclouds.openstack.v2_0.domain.PaginatedCollection;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\nimport org.jclouds.openstack.v2_0.services.Identity;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.Transform;\n\n/**\n * Provides access to the Keystone User API.\n */\n@Consumes(MediaType.APPLICATION_JSON)\n@org.jclouds.rest.annotations.Endpoint(Identity.class)\n@RequestFilters(AuthenticateRequest.class)\npublic interface UserApi {\n\n   /**\n    * Retrieve the list of users\n    * <p/>\n    * NOTE: this method is not in API documentation for keystone, but does work\n    *\n    * @return the list of users\n    */\n   @Named(\"user:list\")\n   @GET\n   @Path(\"/users\")\n   @ResponseParser(ParseUsers.class)\n   @Transform(ToPagedIterable.class)\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   PagedIterable<User> list();\n\n   @Named(\"user:list\")\n   @GET\n   @Path(\"/users\")\n   @ResponseParser(ParseUsers.class)\n   @Fallback(EmptyPaginatedCollectionOnNotFoundOr404.class)\n   PaginatedCollection<User> list(PaginationOptions options);\n\n   /**\n    * Retrieve information about a user, by user ID\n    *\n    * @return the information about the user\n    */\n   @Named(\"user:get\")\n   @GET\n   @SelectJson(\"user\")\n   @Path(\"/users/{userId}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   User get(@PathParam(\"userId\") String userId);\n\n   /**\n    * Retrieve information about a user, by user name\n    * <p/>\n    * NOTE: currently not working in openstack ( https://bugs.launchpad.net/keystone/+bug/956687 )\n    *\n    * @return the information about the user\n    */\n   @Named(\"user:getByName\")\n   @GET\n   @SelectJson(\"user\")\n   @Path(\"/users\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   User getByName(@QueryParam(\"name\") String userName);\n\n   /**\n    * Retrieves the list of global roles associated with a specific user (excludes tenant roles).\n    * <p/>\n    * NOTE: Broken in openstack ( https://bugs.launchpad.net/keystone/+bug/933565 )\n    *\n    * @return the set of Roles granted to the user\n    */\n   @Named(\"user:listRolesOfUser\")\n   @GET\n   @SelectJson(\"roles\")\n   @Path(\"/users/{userId}/roles\")\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<Role> listRolesOfUser(@PathParam(\"userId\") String userId);\n\n   /**\n    * List the roles a user has been granted on a specific tenant\n    *\n    * @return the set of roles\n    */\n   @Named(\"user:listRolesOfUserOnTenant\")\n   @GET\n   @SelectJson(\"roles\")\n   @Path(\"/tenants/{tenantId}/users/{userId}/roles\")\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<Role> listRolesOfUserOnTenant(@PathParam(\"userId\") String userId,\n         @PathParam(\"tenantId\") String tenantId);\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/functions/internal/ParseServices.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.functions.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.internal.Arg0ToPagedIterable;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\nimport org.jclouds.openstack.keystone.v2_0.KeystoneApi;\nimport org.jclouds.openstack.keystone.v2_0.domain.Service;\nimport org.jclouds.openstack.keystone.v2_0.extensions.ServiceAdminApi;\nimport org.jclouds.openstack.keystone.v2_0.functions.internal.ParseServices.Services;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.PaginatedCollection;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.inject.TypeLiteral;\n\n/**\n * boiler plate until we determine a better way\n */\n@Beta\n@Singleton\npublic class ParseServices extends ParseJson<Services> {\n   static class Services extends PaginatedCollection<Service> {\n\n      @ConstructorProperties({ \"OS-KSADM:services\", \"services_links\" })\n      protected Services(Iterable<Service> services, Iterable<Link> services_links) {\n         super(services, services_links);\n      }\n\n   }\n\n   @Inject\n   public ParseServices(Json json) {\n      super(json, TypeLiteral.get(Services.class));\n   }\n\n   public static class ToPagedIterable extends Arg0ToPagedIterable.FromCaller<Service, ToPagedIterable> {\n\n      private final KeystoneApi api;\n\n      @Inject\n      protected ToPagedIterable(KeystoneApi api) {\n         this.api = checkNotNull(api, \"api\");\n      }\n\n      @Override\n      protected Function<Object, IterableWithMarker<Service>> markerToNextForArg0(Optional<Object> ignored) {\n         final ServiceAdminApi serviceApi = api.getServiceAdminApi().get();\n         return new Function<Object, IterableWithMarker<Service>>() {\n\n            @SuppressWarnings(\"unchecked\")\n            @Override\n            public IterableWithMarker<Service> apply(Object input) {\n               PaginationOptions paginationOptions = PaginationOptions.class.cast(input);\n               return IterableWithMarker.class.cast(serviceApi.list(paginationOptions));\n            }\n\n            @Override\n            public String toString() {\n               return \"listServices()\";\n            }\n         };\n      }\n\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/functions/internal/ParseTenants.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.functions.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport com.google.common.base.Optional;\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.internal.Arg0ToPagedIterable;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\nimport org.jclouds.openstack.keystone.v2_0.KeystoneApi;\nimport org.jclouds.openstack.v2_0.domain.PaginatedCollection;\nimport org.jclouds.openstack.keystone.v2_0.domain.Tenant;\nimport org.jclouds.openstack.keystone.v2_0.features.TenantApi;\nimport org.jclouds.openstack.keystone.v2_0.functions.internal.ParseTenants.Tenants;\nimport org.jclouds.openstack.v2_0.domain.Link;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Function;\nimport com.google.inject.TypeLiteral;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\n\n/**\n * boiler plate until we determine a better way\n */\n@Beta\n@Singleton\npublic class ParseTenants extends ParseJson<Tenants> {\n   static class Tenants extends PaginatedCollection<Tenant> {\n\n      @ConstructorProperties({ \"tenants\", \"tenants_links\" })\n      protected Tenants(Iterable<Tenant> tenants, Iterable<Link> tenants_links) {\n         super(tenants, tenants_links);\n      }\n\n   }\n\n   @Inject\n   public ParseTenants(Json json) {\n      super(json, TypeLiteral.get(Tenants.class));\n   }\n\n   public static class ToPagedIterable extends Arg0ToPagedIterable.FromCaller<Tenant, ToPagedIterable> {\n\n      private final KeystoneApi api;\n\n      @Inject\n      protected ToPagedIterable(KeystoneApi api) {\n         this.api = checkNotNull(api, \"api\");\n      }\n\n      @Override\n      protected Function<Object, IterableWithMarker<Tenant>> markerToNextForArg0(Optional<Object> ignored) {\n         final TenantApi tenantApi = api.getTenantApi().get();\n         return new Function<Object, IterableWithMarker<Tenant>>() {\n\n            @SuppressWarnings(\"unchecked\")\n            @Override\n            public IterableWithMarker<Tenant> apply(Object input) {\n               PaginationOptions paginationOptions = PaginationOptions.class.cast(input);\n               return IterableWithMarker.class.cast(tenantApi.list(paginationOptions));\n            }\n\n            @Override\n            public String toString() {\n               return \"listTenants()\";\n            }\n         };\n      }\n\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/functions/internal/ParseUsers.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.functions.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport com.google.common.base.Optional;\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.internal.Arg0ToPagedIterable;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\nimport org.jclouds.openstack.keystone.v2_0.KeystoneApi;\nimport org.jclouds.openstack.v2_0.domain.PaginatedCollection;\nimport org.jclouds.openstack.keystone.v2_0.domain.User;\nimport org.jclouds.openstack.keystone.v2_0.features.UserApi;\nimport org.jclouds.openstack.keystone.v2_0.functions.internal.ParseUsers.Users;\nimport org.jclouds.openstack.v2_0.domain.Link;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Function;\nimport com.google.inject.TypeLiteral;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\n\n/**\n * boiler plate until we determine a better way\n */\n@Beta\n@Singleton\npublic class ParseUsers extends ParseJson<Users> {\n   static class Users extends PaginatedCollection<User> {\n\n      @ConstructorProperties({ \"users\", \"users_links\" })\n      protected Users(Iterable<User> users, Iterable<Link> users_links) {\n         super(users, users_links);\n      }\n\n   }\n\n   @Inject\n   public ParseUsers(Json json) {\n      super(json, TypeLiteral.get(Users.class));\n   }\n\n   public static class ToPagedIterable extends Arg0ToPagedIterable.FromCaller<User, ToPagedIterable> {\n\n      private final KeystoneApi api;\n\n      @Inject\n      protected ToPagedIterable(KeystoneApi api) {\n         this.api = checkNotNull(api, \"api\");\n      }\n\n      @Override\n      protected Function<Object, IterableWithMarker<User>> markerToNextForArg0(Optional<Object> ignored) {\n         final UserApi userApi = api.getUserApi().get();\n         return new Function<Object, IterableWithMarker<User>>() {\n\n            @SuppressWarnings(\"unchecked\")\n            @Override\n            public IterableWithMarker<User> apply(Object input) {\n               PaginationOptions paginationOptions = PaginationOptions.class.cast(input);\n               return IterableWithMarker.class.cast(userApi.list(paginationOptions));\n            }\n\n            @Override\n            public String toString() {\n               return \"listUsers()\";\n            }\n         };\n      }\n\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/handlers/KeystoneErrorHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.handlers;\n\nimport com.google.inject.Inject;\nimport org.jclouds.Constants;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.ResourceNotFoundException;\n\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport static org.jclouds.http.HttpUtils.closeClientButKeepContentStream;\n\n/**\n * This will parse and set an appropriate exception on the command object.\n */\n// TODO: is there error spec someplace? let's type errors, etc.\n@Singleton\npublic class KeystoneErrorHandler implements HttpErrorHandler {\n\n   @Inject(optional = true)\n   @Named(Constants.PROPERTY_LOGGER_WIRE_LOG_SENSITIVE_INFO)\n   private boolean logSensitiveInformation = false;\n\n   public void handleError(HttpCommand command, HttpResponse response) {\n      // it is important to always read fully and close streams\n      byte[] data = closeClientButKeepContentStream(response);\n      String message = data != null ? new String(data) : null;\n\n      Exception exception = message != null ? new HttpResponseException(command, response, message)\n               : new HttpResponseException(command, response, logSensitiveInformation);\n      message = message != null ? message : String.format(\"%s -> %s\", command.getCurrentRequest().getRequestLine(),\n               response.getStatusLine());\n      switch (response.getStatusCode()) {\n         case 400:\n            break;\n         case 401:\n         case 403:\n            exception = new AuthorizationException(message, exception);\n            break;\n         case 404:\n            if (!command.getCurrentRequest().getMethod().equals(\"DELETE\")) {\n               exception = new ResourceNotFoundException(message, exception);\n            }\n            break;\n      }\n      command.setException(exception);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/options/CreateTenantOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.options;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.MapBinder;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableMap;\n\npublic class CreateTenantOptions implements MapBinder {\n   @Inject\n   private BindToJsonPayload jsonBinder;\n\n   private String description;\n   private boolean enabled;\n\n   @Override\n   public boolean equals(Object object) {\n      if (this == object) {\n         return true;\n      }\n      if (object instanceof CreateTenantOptions) {\n         final CreateTenantOptions other = CreateTenantOptions.class.cast(object);\n         return equal(description, other.description) && equal(enabled, other.enabled);\n      } else {\n         return false;\n      }\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(description, enabled);\n   }\n\n   protected ToStringHelper string() {\n      ToStringHelper toString = MoreObjects.toStringHelper(\"\").omitNullValues();\n      toString.add(\"description\", description);\n      toString.add(\"enabled\", Boolean.valueOf(enabled));\n      return toString;\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   static class ServerRequest {\n      final String name;\n      String description;\n      boolean enabled;\n\n      private ServerRequest(String name) {\n         this.name = name;\n      }\n\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      ServerRequest tenant = new ServerRequest(checkNotNull(postParams.get(\"name\"), \"name parameter not present\")\n            .toString());\n      if (description != null)\n         tenant.description = description;\n      tenant.enabled = enabled;\n\n      return bindToRequest(request, (Object) ImmutableMap.of(\"tenant\", tenant));\n   }\n\n   /**\n    * Gets the default tenant description\n    */\n   public String getDescription() {\n      return this.description;\n   }\n\n   /**\n    * A description can be defined when creating a tenant.\n    */\n   public CreateTenantOptions description(String description) {\n      this.description = description;\n      return this;\n   }\n\n   public boolean isEnabled() {\n      return this.enabled;\n   }\n\n   public CreateTenantOptions enabled(boolean enabled) {\n      this.enabled = enabled;\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see CreateTenantOptions#description(String)\n       */\n      public static CreateTenantOptions description(String description) {\n         CreateTenantOptions options = new CreateTenantOptions();\n         return options.description(description);\n      }\n\n      /**\n       * @see CreateTenantOptions#enabled(boolean)\n       */\n      public static CreateTenantOptions enabled(boolean enabled) {\n         CreateTenantOptions options = new CreateTenantOptions();\n         return options.enabled(enabled);\n      }\n\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      return jsonBinder.bindToRequest(request, input);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/options/CreateUserOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.options;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.MapBinder;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableMap;\n\npublic class CreateUserOptions implements MapBinder{\n   @Inject\n   private BindToJsonPayload jsonBinder;\n\n   private String tenant;\n   private String password;\n   private String email;\n   private boolean enabled;\n\n   @Override\n   public boolean equals(Object object) {\n      if (this == object) {\n         return true;\n      }\n      if (object instanceof CreateUserOptions) {\n         final CreateUserOptions other = CreateUserOptions.class.cast(object);\n         return equal(tenant, other.tenant) && equal(password, other.password) && equal(email, other.email)\n               && equal(enabled, other.enabled);\n      } else {\n         return false;\n      }\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(tenant, password, email, enabled);\n   }\n\n   protected ToStringHelper string() {\n      ToStringHelper toString = MoreObjects.toStringHelper(\"\").omitNullValues();\n      toString.add(\"tenant\", tenant);\n      toString.add(\"password\", password);\n      toString.add(\"email\", email);\n      toString.add(\"enabled\", Boolean.valueOf(enabled));\n      return toString;\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   static class ServerRequest {\n      final String name;\n      String tenantId;\n      String password;\n      String email;\n      boolean enabled;\n\n      private ServerRequest(String name, String password) {\n         this.name = name;\n         this.password = password;\n      }\n\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      ServerRequest user = new ServerRequest(checkNotNull(postParams.get(\"name\"), \"name parameter not present\")\n            .toString(), checkNotNull(postParams.get(\"password\"), \"password parameter not present\")\n            .toString());\n      if (email != null)\n         user.email = email;\n      if (password != null)\n         user.password = password;\n      if (tenant != null)\n         user.tenantId = tenant;\n      user.enabled = enabled;\n\n      return bindToRequest(request, (Object) ImmutableMap.of(\"user\", user));\n   }\n\n   /**\n    * Gets the default user tenant\n    */\n   public String getTenant() {\n      return this.tenant;\n   }\n\n   /**\n    * A default tenant can be defined when creating an user.\n    */\n   public CreateUserOptions tenant(String tenant) {\n      this.tenant = tenant;\n      return this;\n   }\n\n   /**\n    * Gets the user e-mail\n    */\n   public String getEmail() {\n      return this.email;\n   }\n\n   /**\n    * @see #getEmail()\n    */\n   public CreateUserOptions email(String email) {\n      this.email = email;\n      return this;\n   }\n\n   public boolean isEnabled() {\n      return this.enabled;\n   }\n\n   public CreateUserOptions enabled(boolean enabled) {\n      this.enabled = enabled;\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see CreateUserOptions#tenant(String)\n       */\n      public static CreateUserOptions tenant(String tenant) {\n         CreateUserOptions options = new CreateUserOptions();\n         return options.tenant(tenant);\n      }\n\n      /**\n       * @see CreateUserOptions#email(String)\n       */\n      public static CreateUserOptions email(String email) {\n         CreateUserOptions options = new CreateUserOptions();\n         return options.email(email);\n      }\n\n      /**\n       * @see CreateUserOptions#enabled(boolean)\n       */\n      public static CreateUserOptions enabled(boolean enabled) {\n         CreateUserOptions options = new CreateUserOptions();\n         return options.enabled(enabled);\n      }\n\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      return jsonBinder.bindToRequest(request, input);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/options/UpdateTenantOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.options;\n\nimport static com.google.common.base.Objects.equal;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.MapBinder;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableMap;\n\npublic class UpdateTenantOptions implements MapBinder {\n   @Inject\n   private BindToJsonPayload jsonBinder;\n\n   private String name;\n   private String description;\n   private boolean enabled;\n\n   @Override\n   public boolean equals(Object object) {\n      if (this == object) {\n         return true;\n      }\n      if (object instanceof UpdateTenantOptions) {\n         final UpdateTenantOptions other = UpdateTenantOptions.class.cast(object);\n         return equal(description, other.description) && equal(enabled, other.enabled) && equal(name, other.name);\n      } else {\n         return false;\n      }\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(name, description, enabled);\n   }\n\n   protected ToStringHelper string() {\n      ToStringHelper toString = MoreObjects.toStringHelper(\"\").omitNullValues();\n      toString.add(\"name\", name);\n      toString.add(\"description\", description);\n      toString.add(\"enabled\", Boolean.valueOf(enabled));\n      return toString;\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   static class ServerRequest {\n      String name;\n      String description;\n      boolean enabled;\n\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      ServerRequest tenant = new ServerRequest();\n      if (description != null)\n         tenant.description = description;\n      if (name != null)\n         tenant.name = name;\n      tenant.enabled = enabled;\n\n      return bindToRequest(request, (Object) ImmutableMap.of(\"tenant\", tenant));\n   }\n\n   /**\n    * Gets the default tenant description\n    */\n   public String getDescription() {\n      return this.description;\n   }\n\n   /**\n    * A description can be defined when creating a tenant.\n    */\n   public UpdateTenantOptions description(String description) {\n      this.description = description;\n      return this;\n   }\n\n   public boolean isEnabled() {\n      return this.enabled;\n   }\n\n   public UpdateTenantOptions enabled(boolean enabled) {\n      this.enabled = enabled;\n      return this;\n   }\n\n   public UpdateTenantOptions name(String name) {\n      this.name = name;\n      return this;\n   }\n\n   public String getName() {\n      return this.name;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see UpdateTenantOptions#name(String)\n       */\n      public static UpdateTenantOptions name(String name) {\n         UpdateTenantOptions options = new UpdateTenantOptions();\n         return options.name(name);\n      }\n\n      /**\n       * @see UpdateTenantOptions#description(String)\n       */\n      public static UpdateTenantOptions description(String description) {\n         UpdateTenantOptions options = new UpdateTenantOptions();\n         return options.description(description);\n      }\n\n      /**\n       * @see UpdateTenantOptions#enabled(boolean)\n       */\n      public static UpdateTenantOptions enabled(boolean enabled) {\n         UpdateTenantOptions options = new UpdateTenantOptions();\n         return options.enabled(enabled);\n      }\n\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      return jsonBinder.bindToRequest(request, input);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/options/UpdateUserOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.options;\n\nimport static com.google.common.base.Objects.equal;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.MapBinder;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableMap;\n\npublic class UpdateUserOptions implements MapBinder{\n   @Inject\n   private BindToJsonPayload jsonBinder;\n\n   private String name;\n   private String email;\n   private String password;\n   private boolean enabled;\n\n   @Override\n   public boolean equals(Object object) {\n      if (this == object) {\n         return true;\n      }\n      if (object instanceof UpdateUserOptions) {\n         final UpdateUserOptions other = UpdateUserOptions.class.cast(object);\n         return equal(name, other.name) && equal(email, other.email)\n               && equal(enabled, other.enabled) && equal(password, other.password);\n      } else {\n         return false;\n      }\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(name, email, enabled, password);\n   }\n\n   protected ToStringHelper string() {\n      ToStringHelper toString = MoreObjects.toStringHelper(\"\").omitNullValues();\n      toString.add(\"name\", name);\n      toString.add(\"email\", email);\n      toString.add(\"password\", password);\n      toString.add(\"enabled\", Boolean.valueOf(enabled));\n      return toString;\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   static class ServerRequest {\n      \n      String name;\n      String email;\n      String password;\n      boolean enabled;\n\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      ServerRequest user = new ServerRequest();\n      if (email != null)\n         user.email = email;\n      if (name != null)\n         user.name = name;\n      if (password != null)\n         user.password = password;\n      user.enabled = enabled;\n\n      return bindToRequest(request, (Object) ImmutableMap.of(\"user\", user));\n   }\n\n   /**\n    * Gets the default user name\n    */\n   public String getName() {\n      return this.name;\n   }\n\n   /**\n    * A name can be defined when updating an user.\n    */\n   public UpdateUserOptions name(String name) {\n      this.name = name;\n      return this;\n   }\n\n   /**\n    * Gets the default password\n    */\n   public String getPassword() {\n      return password;\n   }\n\n   public UpdateUserOptions password(String password) {\n      this.password = password;\n      return this;\n   }\n   \n   /**\n    * Gets the user e-mail\n    */\n   public String getEmail() {\n      return this.email;\n   }\n\n   /**\n    * @see #getEmail()\n    */\n   public UpdateUserOptions email(String email) {\n      this.email = email;\n      return this;\n   }\n\n   public boolean isEnabled() {\n      return this.enabled;\n   }\n\n   public UpdateUserOptions enabled(boolean enabled) {\n      this.enabled = enabled;\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see UpdateUserOptions#name(String)\n       */\n      public static UpdateUserOptions name(String name) {\n         UpdateUserOptions options = new UpdateUserOptions();\n         return options.name(name);\n      }\n\n      /**\n       * @see UpdateUserOptions#email(String)\n       */\n      public static UpdateUserOptions email(String email) {\n         UpdateUserOptions options = new UpdateUserOptions();\n         return options.email(email);\n      }\n\n      /**\n       * @see UpdateUserOptions#enabled(boolean)\n       */\n      public static UpdateUserOptions enabled(boolean enabled) {\n         UpdateUserOptions options = new UpdateUserOptions();\n         return options.enabled(enabled);\n      }\n      \n      /**\n       * @see UpdateUserOptions#password(String)\n       */\n      public static UpdateUserOptions password(String password) {\n         UpdateUserOptions options = new UpdateUserOptions();\n         return options.password(password);\n      }\n\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      return jsonBinder.bindToRequest(request, input);\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v3/KeystoneApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v3;\n\nimport java.io.Closeable;\n\nimport org.jclouds.openstack.keystone.v3.features.AuthApi;\nimport org.jclouds.openstack.keystone.v3.features.CatalogApi;\nimport org.jclouds.openstack.keystone.v3.features.ProjectApi;\nimport org.jclouds.openstack.keystone.v3.features.RegionApi;\nimport org.jclouds.openstack.keystone.v3.features.UserApi;\nimport org.jclouds.rest.annotations.Delegate;\n\n/**\n * Provides access to the OpenStack Identity (Keystone) REST API.\n */\npublic interface KeystoneApi extends Closeable {\n\n   /**\n    * Provides access to authentication and token management features.\n    */\n   @Delegate\n   AuthApi getAuthApi();\n\n   /**\n    * Provides access to service catalog features.\n    */\n   @Delegate\n   CatalogApi getCatalogApi();\n   \n   /**\n    * Provides access to region features.\n    */\n   @Delegate\n   RegionApi getRegionApi();\n   \n   /**\n    * Provides access to project features.\n    */\n   @Delegate\n   ProjectApi getProjectApi();\n   \n   /**\n    * Provides access to user features.\n    */\n   @Delegate\n   UserApi getUserApi();\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v3/KeystoneApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v3;\n\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.CREDENTIAL_TYPE;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.KEYSTONE_VERSION;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.SERVICE_TYPE;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.openstack.keystone.auth.config.AuthenticationModule;\nimport org.jclouds.openstack.keystone.catalog.config.KeystoneAdminURLModule;\nimport org.jclouds.openstack.keystone.catalog.config.ServiceCatalogModule;\nimport org.jclouds.openstack.keystone.v3.config.KeystoneHttpApiModule;\nimport org.jclouds.openstack.v2_0.ServiceType;\nimport org.jclouds.rest.internal.BaseHttpApiMetadata;\n\nimport com.google.auto.service.AutoService;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n/**\n * Implementation of {@link ApiMetadata} for Keystone 3.0 API\n */\n@AutoService(ApiMetadata.class)\npublic class KeystoneApiMetadata extends BaseHttpApiMetadata<KeystoneApi> {\n\n   @Override\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromApiMetadata(this);\n   }\n\n   public KeystoneApiMetadata() {\n      this(new ConcreteBuilder());\n   }\n\n   protected KeystoneApiMetadata(Builder<?> builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = BaseHttpApiMetadata.defaultProperties();\n      properties.setProperty(CREDENTIAL_TYPE, org.jclouds.openstack.keystone.auth.config.CredentialTypes.PASSWORD_CREDENTIALS);\n      properties.setProperty(SERVICE_TYPE, ServiceType.IDENTITY);\n      properties.setProperty(KEYSTONE_VERSION, \"3\");\n      return properties;\n   }\n\n   public abstract static class Builder<T extends Builder<T>> extends BaseHttpApiMetadata.Builder<KeystoneApi, T> {\n\n      protected Builder() {\n          id(\"openstack-keystone-3\")\n         .name(\"OpenStack Keystone 3.x API\")\n         .identityName(\"${domain}:${userName} or ${userName}, if your keystone supports a default project\")\n         .credentialName(\"${password}\")\n         .endpointName(\"Keystone V3 base URL\")\n         .documentation(URI.create(\"http://api.openstack.org/\"))\n         .version(\"3\")\n         .defaultEndpoint(\"http://localhost/identity/v3\")\n         .defaultProperties(KeystoneApiMetadata.defaultProperties())\n         .defaultModules(ImmutableSet.<Class<? extends Module>>builder()\n                                     .add(AuthenticationModule.class)\n                                     .add(ServiceCatalogModule.class)\n                                     .add(KeystoneAdminURLModule.class)\n                                     .add(KeystoneHttpApiModule.class)\n                                     .build());\n      }\n\n      @Override\n      public KeystoneApiMetadata build() {\n         return new KeystoneApiMetadata(this);\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v3/auth/V3AuthenticationApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v3.auth;\n\nimport java.io.Closeable;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.openstack.keystone.auth.AuthenticationApi;\nimport org.jclouds.openstack.keystone.auth.domain.PasswordCredentials;\nimport org.jclouds.openstack.keystone.auth.domain.TenantOrDomainAndCredentials;\nimport org.jclouds.openstack.keystone.auth.domain.TokenCredentials;\nimport org.jclouds.openstack.keystone.auth.domain.ApiAccessKeyCredentials;\nimport org.jclouds.openstack.keystone.auth.domain.AuthInfo;\nimport org.jclouds.openstack.keystone.v3.binders.BindAccessKeyAuthToJsonPayload;\nimport org.jclouds.openstack.keystone.v3.binders.BindPasswordAuthToJsonPayload;\nimport org.jclouds.openstack.keystone.v3.binders.BindTokenAuthToJsonPayload;\nimport org.jclouds.openstack.keystone.v3.domain.Token;\nimport org.jclouds.openstack.keystone.v3.parsers.ParseTokenFromHttpResponse;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.ResponseParser;\n\nimport com.google.inject.name.Named;\n\n/**\n * Provides access to the OpenStack Keystone Authentication API.\n */\n@Consumes(MediaType.APPLICATION_JSON)\n@Path(\"/auth/tokens\")\npublic interface V3AuthenticationApi extends AuthenticationApi, Closeable {\n\n   @Named(\"token:create\")\n   @POST\n   @ResponseParser(ParseTokenFromHttpResponse.class)\n   @MapBinder(BindPasswordAuthToJsonPayload.class)\n   @Override\n   Token authenticatePassword(TenantOrDomainAndCredentials<PasswordCredentials> credentials);\n\n   @Named(\"token:create\")\n   @POST\n   @ResponseParser(ParseTokenFromHttpResponse.class)\n   @MapBinder(BindTokenAuthToJsonPayload.class)\n   @Override\n   Token authenticateToken(TenantOrDomainAndCredentials<TokenCredentials> credentials);\n\n   @Named(\"token:create\")\n   @POST\n   @ResponseParser(ParseTokenFromHttpResponse.class)\n   @MapBinder(BindAccessKeyAuthToJsonPayload.class)\n   @Override\n   AuthInfo authenticateAccessKey(TenantOrDomainAndCredentials<ApiAccessKeyCredentials> credentials);\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v3/binders/BindAccessKeyAuthToJsonPayload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v3.binders;\n\nimport org.jclouds.json.Json;\nimport org.jclouds.openstack.keystone.auth.domain.ApiAccessKeyCredentials;\nimport org.jclouds.openstack.keystone.auth.domain.TenantOrDomainAndCredentials;\nimport org.jclouds.openstack.keystone.v3.domain.Auth;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport static java.util.Collections.singletonList;\n\n@Singleton\npublic class BindAccessKeyAuthToJsonPayload extends BindAuthToJsonPayload<ApiAccessKeyCredentials> {\n\n    @Inject\n    protected BindAccessKeyAuthToJsonPayload(Json jsonBinder) {\n        super(jsonBinder);\n    }\n\n    @Override\n    protected Auth buildAuth(TenantOrDomainAndCredentials<ApiAccessKeyCredentials> credentials, Object scope) {\n        Auth.Identity.AccessKeyAuth accessKeyAuth = Auth.Identity.AccessKeyAuth.create(\n                credentials.credentials().accessKey(),\n                credentials.credentials().secretKey());\n        return Auth.create(Auth.Identity.create(singletonList(\"application_credential\"), null, null, accessKeyAuth), null);\n    }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v3/binders/BindAuthToJsonPayload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v3.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Predicates.instanceOf;\nimport static com.google.common.collect.Iterables.tryFind;\nimport static org.jclouds.openstack.keystone.v3.domain.Auth.Scope.DOMAIN;\nimport static org.jclouds.openstack.keystone.v3.domain.Auth.Scope.DOMAIN_ID;\nimport static org.jclouds.openstack.keystone.v3.domain.Auth.Scope.PROJECT;\nimport static org.jclouds.openstack.keystone.v3.domain.Auth.Scope.PROJECT_ID;\nimport static org.jclouds.openstack.keystone.v3.domain.Auth.Scope.UNSCOPED;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.json.Json;\nimport org.jclouds.openstack.keystone.auth.domain.TenantOrDomainAndCredentials;\nimport org.jclouds.openstack.keystone.v3.domain.Auth;\nimport org.jclouds.openstack.keystone.v3.domain.Auth.DomainIdScope;\nimport org.jclouds.openstack.keystone.v3.domain.Auth.DomainScope;\nimport org.jclouds.openstack.keystone.v3.domain.Auth.Id;\nimport org.jclouds.openstack.keystone.v3.domain.Auth.Name;\nimport org.jclouds.openstack.keystone.v3.domain.Auth.ProjectIdScope;\nimport org.jclouds.openstack.keystone.v3.domain.Auth.ProjectIdScope.ProjectId;\nimport org.jclouds.openstack.keystone.v3.domain.Auth.ProjectScope;\nimport org.jclouds.openstack.keystone.v3.domain.Auth.ProjectScope.ProjectName;\nimport org.jclouds.rest.MapBinder;\nimport org.jclouds.rest.binders.BindToJsonPayload;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\n\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\n\npublic abstract class BindAuthToJsonPayload<T> extends BindToJsonPayload implements MapBinder {\n\n   private static final Set<String> SCOPE_PREFIXES = ImmutableSet.of(PROJECT, PROJECT_ID, DOMAIN, DOMAIN_ID);\n\n   protected BindAuthToJsonPayload(Json jsonBinder) {\n      super(jsonBinder);\n   }\n\n   protected abstract Auth buildAuth(TenantOrDomainAndCredentials<T> credentials, Object scope);\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      checkArgument(checkNotNull(request, \"request\") instanceof GeneratedHttpRequest,\n            \"this binder is only valid for GeneratedHttpRequests!\");\n      GeneratedHttpRequest gRequest = (GeneratedHttpRequest) request;\n\n      Optional<Object> authentication = tryFind(gRequest.getInvocation().getArgs(),\n            instanceOf(TenantOrDomainAndCredentials.class));\n      checkArgument(authentication.isPresent(), \"no credentials found in the api call arguments\");\n\n      @SuppressWarnings(\"unchecked\")\n      TenantOrDomainAndCredentials<T> credentials = (TenantOrDomainAndCredentials<T>) authentication.get();\n      Object scope = parseScope(credentials);\n      Auth auth = buildAuth(credentials, scope);\n\n      R authRequest = super.bindToRequest(request, ImmutableMap.of(\"auth\", auth));\n      authRequest.getPayload().setSensitive(true);\n\n      return authRequest;\n   }\n\n   private Object parseScope(TenantOrDomainAndCredentials<T> credentials) {\n      String scope = credentials.scope();\n      // If there is no prefix, assume an unscoped authentication\n      if (!scope.contains(\":\")) {\n         checkArgument(scope.equals(UNSCOPED), \"Invalid scope: %s\", scope);\n         return UNSCOPED;\n      }\n      // Otherwise, parse if it is a project or domain scope\n      String[] parts = scope.split(\":\");\n      checkArgument(parts.length == 2, \"Invalid scope: %s\", scope);\n      checkArgument(SCOPE_PREFIXES.contains(parts[0]), \"Scope prefix should be: %s\", SCOPE_PREFIXES);\n\n      if (PROJECT.equals(parts[0])) {\n         return ProjectScope.create(ProjectName.create(parts[1], parseProjectDomain(credentials, true)));\n      } else if (PROJECT_ID.equals(parts[0])) {\n         // tenant (name/id) was never used as domain for project-id; so try to\n         // keep backward compatibility\n         return ProjectIdScope.create(ProjectId.create(parts[1], parseProjectDomain(credentials, false)));\n      } else if (DOMAIN.equals(parts[0])) {\n         return DomainScope.create(Name.create(parts[1]));\n      } else {\n         return DomainIdScope.create(Id.create(parts[1]));\n      }\n   }\n\n   private Object parseProjectDomain(TenantOrDomainAndCredentials<T> credentials, boolean useTenantAsDefaultDomain) {\n      // Before 'projectDomainName'/'projectDomainId' support,\n      // 'tenantOrDomainId' was used as domain (id) for project-scoped by name,\n      // but not by id, so 'useTenantAsDefaultDomain' flag allows to manage that\n      Object domainScope = null;\n      if (useTenantAsDefaultDomain && credentials.tenantOrDomainId() != null) {\n         domainScope = Id.create(credentials.tenantOrDomainId());\n      } else if (credentials.projectDomainName() != null) {\n         domainScope = Name.create(credentials.projectDomainName());\n      } else if (credentials.projectDomainId() != null) {\n         domainScope = Id.create(credentials.projectDomainId());\n      } else if (useTenantAsDefaultDomain) {\n         domainScope = Name.create(credentials.tenantOrDomainName());\n      }\n      return domainScope;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v3/binders/BindPasswordAuthToJsonPayload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v3.binders;\n\nimport static java.util.Collections.singletonList;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.json.Json;\nimport org.jclouds.openstack.keystone.auth.domain.PasswordCredentials;\nimport org.jclouds.openstack.keystone.auth.domain.TenantOrDomainAndCredentials;\nimport org.jclouds.openstack.keystone.v3.domain.Auth;\nimport org.jclouds.openstack.keystone.v3.domain.Auth.Identity;\nimport org.jclouds.openstack.keystone.v3.domain.Auth.Identity.PasswordAuth;\nimport org.jclouds.openstack.keystone.v3.domain.Auth.Identity.PasswordAuth.UserAuth;\nimport org.jclouds.openstack.keystone.v3.domain.Auth.Identity.PasswordAuth.UserAuth.DomainAuth;\n\n@Singleton\npublic class BindPasswordAuthToJsonPayload extends BindAuthToJsonPayload<PasswordCredentials> {\n\n   @Inject\n   BindPasswordAuthToJsonPayload(Json jsonBinder) {\n      super(jsonBinder);\n   }\n\n   @Override\n   protected Auth buildAuth(TenantOrDomainAndCredentials<PasswordCredentials> credentials, Object scope) {\n      PasswordCredentials creds = credentials.credentials();\n      DomainAuth domain = DomainAuth.create(credentials.tenantOrDomainName());\n      UserAuth user = UserAuth.create(creds.username(), domain, creds.password());\n\n      return Auth.create(Identity.create(singletonList(\"password\"), null, PasswordAuth.create(user), null), scope);\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v3/binders/BindTokenAuthToJsonPayload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v3.binders;\n\nimport static java.util.Collections.singletonList;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.json.Json;\nimport org.jclouds.openstack.keystone.auth.domain.TenantOrDomainAndCredentials;\nimport org.jclouds.openstack.keystone.auth.domain.TokenCredentials;\nimport org.jclouds.openstack.keystone.v3.domain.Auth;\nimport org.jclouds.openstack.keystone.v3.domain.Auth.Id;\nimport org.jclouds.openstack.keystone.v3.domain.Auth.Identity;\n\n@Singleton\npublic class BindTokenAuthToJsonPayload extends BindAuthToJsonPayload<TokenCredentials> {\n\n   @Inject\n   BindTokenAuthToJsonPayload(Json jsonBinder) {\n      super(jsonBinder);\n   }\n\n   @Override\n   protected Auth buildAuth(TenantOrDomainAndCredentials<TokenCredentials> credentials, Object scope) {\n      Id token = Id.create(credentials.credentials().id());\n      return Auth.create(Identity.create(singletonList(\"token\"), token, null, null), scope);\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v3/catalog/V3ServiceCatalog.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v3.catalog;\n\nimport java.util.List;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.logging.Logger;\nimport org.jclouds.openstack.keystone.auth.domain.AuthInfo;\nimport org.jclouds.openstack.keystone.catalog.ServiceEndpoint;\nimport org.jclouds.openstack.keystone.v3.domain.Catalog;\nimport org.jclouds.openstack.keystone.v3.domain.Endpoint;\nimport org.jclouds.openstack.keystone.v3.domain.Token;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableList;\n\n@Singleton\npublic class V3ServiceCatalog implements Supplier<List<ServiceEndpoint>> {\n\n   @Resource\n   private Logger logger = Logger.NULL;\n\n   private final Supplier<AuthInfo> authInfo;\n\n   @Inject\n   V3ServiceCatalog(Supplier<AuthInfo> authInfo) {\n      this.authInfo = authInfo;\n   }\n\n   @Override\n   public List<ServiceEndpoint> get() {\n      Token token = (Token) authInfo.get();\n\n      ImmutableList.Builder<ServiceEndpoint> serviceEndpoints = ImmutableList.builder();\n      for (Catalog catalog : token.catalog()) {\n         for (Endpoint endpoint : catalog.endpoints()) {\n            serviceEndpoints.add(ServiceEndpoint.builder().id(endpoint.id()).iface(endpoint.iface())\n                  .regionId(endpoint.regionId()).type(catalog.type()).url(endpoint.url()).build());\n         }\n      }\n\n      return serviceEndpoints.build();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v3/config/KeystoneHttpApiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v3.config;\n\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.json.config.GsonModule.DateAdapter;\nimport org.jclouds.openstack.keystone.v3.KeystoneApi;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.config.HttpApiModule;\n\n/**\n * Configures the Keystone API.\n */\n@ConfiguresHttpApi\npublic class KeystoneHttpApiModule extends HttpApiModule<KeystoneApi> {\n\n   @Override\n   protected void configure() {\n      super.configure();\n      bind(DateAdapter.class).to(GsonModule.Iso8601DateAdapter.class);\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v3/domain/Auth.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v3.domain;\n\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class Auth {\n   public abstract Identity identity();\n\n   @Nullable\n   public abstract Object scope();\n\n   @SerializedNames({ \"identity\", \"scope\" })\n   public static Auth create(Identity identity, Object scope) {\n      return new AutoValue_Auth(identity, scope);\n   }\n\n   @AutoValue\n   public abstract static class Identity {\n      public abstract List<String> methods();\n\n      @Nullable\n      public abstract Id token();\n\n      @Nullable\n      public abstract PasswordAuth password();\n\n      @Nullable\n      public abstract AccessKeyAuth secret();\n\n      @SerializedNames({ \"methods\", \"token\", \"password\", \"application_credential\" })\n      public static Identity create(List<String> methods, Id token, PasswordAuth password, AccessKeyAuth accessKeyAuth) {\n         return new AutoValue_Auth_Identity(methods, token, password, accessKeyAuth);\n      }\n\n      @AutoValue\n      public abstract static class AccessKeyAuth {\n         public abstract String id();\n         public abstract String secret();\n\n         @SerializedNames({ \"id\", \"secret\" })\n         public static AccessKeyAuth create(String id, String secret) {\n            return new AutoValue_Auth_Identity_AccessKeyAuth(id, secret);\n         }\n      }\n\n      @AutoValue\n      public abstract static class PasswordAuth {\n         public abstract UserAuth user();\n\n         @SerializedNames({ \"user\" })\n         public static PasswordAuth create(UserAuth user) {\n            return new AutoValue_Auth_Identity_PasswordAuth(user);\n         }\n\n         @AutoValue\n         public abstract static class UserAuth {\n            public abstract String name();\n\n            public abstract DomainAuth domain();\n\n            public abstract String password();\n\n            @SerializedNames({ \"name\", \"domain\", \"password\" })\n            public static UserAuth create(String name, DomainAuth domain, String password) {\n               return new AutoValue_Auth_Identity_PasswordAuth_UserAuth(name, domain, password);\n            }\n\n            @AutoValue\n            public abstract static class DomainAuth {\n               @Nullable\n               public abstract String name();\n\n               @SerializedNames({ \"name\" })\n               public static DomainAuth create(String name) {\n                  return new AutoValue_Auth_Identity_PasswordAuth_UserAuth_DomainAuth(name);\n               }\n            }\n         }\n      }\n   }\n\n   @AutoValue\n   public abstract static class Id {\n      public abstract String id();\n\n      @SerializedNames({ \"id\" })\n      public static Id create(String id) {\n         return new AutoValue_Auth_Id(id);\n      }\n   }\n\n   @AutoValue\n   public abstract static class Name {\n      @Nullable\n      public abstract String name();\n\n      @SerializedNames({ \"name\" })\n      public static Name create(String name) {\n         return new AutoValue_Auth_Name(name);\n      }\n   }\n\n   public static class Scope {\n      public static final String PROJECT = \"project\";\n      public static final String PROJECT_ID = \"projectId\";\n      public static final String DOMAIN = \"domain\";\n      public static final String DOMAIN_ID = \"domainId\";\n      public static final String UNSCOPED = \"unscoped\";\n   }\n\n   @AutoValue\n   public abstract static class ProjectScope {\n      public abstract ProjectName project();\n\n      @SerializedNames({ Scope.PROJECT })\n      public static ProjectScope create(ProjectName project) {\n         return new AutoValue_Auth_ProjectScope(project);\n      }\n\n      @AutoValue\n      public abstract static class ProjectName {\n         public abstract String name();\n\n         @Nullable\n         public abstract Object domain();\n\n         @SerializedNames({ \"name\", Scope.DOMAIN })\n         public static ProjectName create(String name, Object domain) {\n            return new AutoValue_Auth_ProjectScope_ProjectName(name, domain);\n         }\n\n         public static ProjectName create(String name, Name domain) {\n            return new AutoValue_Auth_ProjectScope_ProjectName(name, domain);\n         }\n\n         public static ProjectName create(String name, Id domain) {\n            return new AutoValue_Auth_ProjectScope_ProjectName(name, domain);\n         }\n      }\n   }\n\n   @AutoValue\n   public abstract static class ProjectIdScope {\n      public abstract ProjectId project();\n\n      @SerializedNames({ Scope.PROJECT })\n      public static ProjectIdScope create(ProjectId project) {\n         return new AutoValue_Auth_ProjectIdScope(project);\n      }\n\n      @AutoValue\n      public abstract static class ProjectId {\n         public abstract String id();\n\n         @Nullable\n         public abstract Object domain();\n\n         @SerializedNames({ \"id\", Scope.DOMAIN })\n         public static ProjectId create(String id, Object domain) {\n            return new AutoValue_Auth_ProjectIdScope_ProjectId(id, domain);\n         }\n\n         public static ProjectId create(String id, Name domain) {\n            return new AutoValue_Auth_ProjectIdScope_ProjectId(id, domain);\n         }\n\n         public static ProjectId create(String id, Id domain) {\n            return new AutoValue_Auth_ProjectIdScope_ProjectId(id, domain);\n         }\n      }\n   }\n\n   @AutoValue\n   public abstract static class DomainIdScope {\n      public abstract Id domain();\n\n      @SerializedNames({ Scope.DOMAIN })\n      public static DomainIdScope create(Id id) {\n         return new AutoValue_Auth_DomainIdScope(id);\n      }\n   }\n\n   @AutoValue\n   public abstract static class DomainScope {\n      public abstract Name domain();\n\n      @SerializedNames({ Scope.DOMAIN })\n      public static DomainScope create(Name name) {\n         return new AutoValue_Auth_DomainScope(name);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v3/domain/Catalog.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v3.domain;\n\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\n\n@AutoValue\npublic abstract class Catalog {\n\n   public abstract String id();\n   @Nullable public abstract String name();\n   public abstract String type();\n   public abstract List<Endpoint> endpoints();\n\n   @SerializedNames({ \"id\", \"name\", \"type\", \"endpoints\" })\n   public static Catalog create(String id, String name, String type, List<Endpoint> endpoints) {\n      return builder().id(id).name(name).type(type).endpoints(endpoints).build();\n   }\n\n   Catalog() {\n   }\n\n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_Catalog.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder id(String id);\n      public abstract Builder name(String name);\n      public abstract Builder type(String type);\n      public abstract Builder endpoints(List<Endpoint> endpoints);\n\n      abstract List<Endpoint> endpoints();\n      abstract Catalog autoBuild();\n\n      public Catalog build() {\n         endpoints(endpoints() == null ? ImmutableList.<Endpoint> of() : ImmutableList.copyOf(endpoints()));\n         return autoBuild();\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v3/domain/Endpoint.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v3.domain;\n\nimport java.net.URI;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class Endpoint {\n\n   @Nullable public abstract String id();\n   @Nullable public abstract String region();\n   @Nullable public abstract String regionId();\n   @Nullable public abstract String serviceId();\n   public abstract URI url();\n   @Nullable public abstract Boolean enabled();\n   public abstract String iface();\n\n   @SerializedNames({ \"id\", \"region\", \"region_id\", \"service_id\", \"url\", \"enabled\", \"interface\" })\n   public static Endpoint create(String id, String region, String regionId, String serviceId, URI url, Boolean enabled,\n         String iface) {\n      return builder().id(serviceId).region(region).regionId(regionId).serviceId(serviceId).url(url).enabled(enabled)\n            .iface(iface).build();\n   }\n\n   Endpoint() {\n   }\n\n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_Endpoint.Builder();\n   }\n   \n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder id(String id);\n      public abstract Builder region(String region);\n      public abstract Builder regionId(String regionId);\n      public abstract Builder serviceId(String serviceId);\n      public abstract Builder url(URI url);\n      public abstract Builder enabled(Boolean enabled);\n      public abstract Builder iface(String iface);\n      public abstract Endpoint build();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v3/domain/Group.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v3.domain;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class Group {\n\n   public abstract String id();\n   public abstract String name();\n   @Nullable public abstract String description();\n   @Nullable public abstract String domainId();\n   @Nullable public abstract Link link();\n\n   @SerializedNames({ \"id\", \"name\", \"description\", \"domain_id\", \"links\" })\n   public static Group create(String id, String name, String description, String domainId, Link link) {\n      return builder().id(id).name(name).description(description).domainId(domainId).link(link).build();\n   }\n\n   Group() {\n   }\n\n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_Group.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder id(String id);\n      public abstract Builder name(String string);\n      public abstract Builder description(String description);\n      public abstract Builder domainId(String domainId);\n      public abstract Builder link(Link link);\n      public abstract Group build();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v3/domain/Link.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v3.domain;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class Link {\n\n   public abstract String self();\n\n   @SerializedNames({\"self\"})\n   public static Link create(String self) {\n      return new AutoValue_Link(self);\n   }\n\n   Link() {\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v3/domain/Project.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v3.domain;\n\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\n\n@AutoValue\npublic abstract class Project {\n\n   public abstract boolean isDomain();\n   @Nullable public abstract String description();\n   @Nullable public abstract String domainId();\n   @Nullable public abstract String domainName();\n   public abstract boolean enabled();\n   @Nullable public abstract String id();\n   public abstract String name();\n   @Nullable public abstract String parentId();\n   @Nullable public abstract List<String> tags();\n   @Nullable public abstract Link link();\n\n   @SerializedNames({ \"is_domain\", \"description\", \"domain_id\", \"domain_name\", \"enabled\", \"id\", \"name\", \"parent_id\",\n         \"tags\", \"links\" })\n   public static Project create(boolean isDomain, String description, String domainId, String domainName,\n         boolean enabled, String id, String name, String parentId, List<String> tags, Link link) {\n      return builder().isDomain(isDomain).description(description).domainId(domainId).domainName(domainName)\n            .enabled(enabled).id(id).name(name).parentId(parentId).tags(tags).link(link).build();\n   }\n\n   Project() {\n   }\n   \n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_Project.Builder().isDomain(false).enabled(true);\n   }\n   \n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder isDomain(boolean isDomain);\n      public abstract Builder description(String description);\n      public abstract Builder domainId(String domainId);\n      public abstract Builder domainName(String domainName);\n      public abstract Builder enabled(boolean enabled);\n      public abstract Builder id(String id);\n      public abstract Builder name(String name);\n      public abstract Builder parentId(String parentId);\n      public abstract Builder tags(List<String> tags);\n      public abstract Builder link(Link link);\n      \n      abstract List<String> tags();\n      abstract Project autoBuild();\n      \n      public Project build() {\n         tags(tags() == null ? null : ImmutableList.copyOf(tags()));\n         return autoBuild();\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v3/domain/Region.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v3.domain;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class Region {\n\n   public abstract String id();\n   public abstract String description();\n   @Nullable public abstract Link link();\n   @Nullable public abstract String parentRegionId();\n\n   @SerializedNames({ \"id\", \"description\", \"links\", \"parent_region_id\" })\n   public static Region create(String id, String description, Link link, String parentRegionId) {\n      return builder().id(id).description(description).link(link).parentRegionId(parentRegionId).build();\n   }\n\n   Region() {\n   }\n\n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_Region.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder id(String id);\n      public abstract Builder description(String name);\n      public abstract Builder link(Link link);\n      public abstract Builder parentRegionId(String parentRegionId);\n      public abstract Region build();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v3/domain/Token.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v3.domain;\n\nimport java.util.Date;\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\nimport org.jclouds.openstack.keystone.auth.domain.AuthInfo;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\n\n@AutoValue\npublic abstract class Token implements AuthInfo {\n\n   @Nullable public abstract String id();\n   public abstract List<String> methods();\n   @Nullable public abstract Date expiresAt();\n   @Nullable public abstract Object extras();\n   @Nullable public abstract List<Catalog> catalog();\n   @Nullable public abstract List<String> auditIds();\n   public abstract User user();\n   public abstract Date issuedAt();\n   \n   @Override\n   public String getAuthToken() {\n      return id();\n   }\n   \n   @SerializedNames({ \"id\", \"methods\", \"expires_at\", \"extras\", \"catalog\", \"audit_ids\", \"user\", \"issued_at\" })\n   private static Token create(String id, List<String> methods, Date expiresAt, Object extras, List<Catalog> catalog,\n         List<String> auditIds, User user, Date issuedAt) {\n      return builder().id(id).methods(methods).expiresAt(expiresAt).extras(extras).catalog(catalog).auditIds(auditIds)\n            .user(user).issuedAt(issuedAt).build();\n   }\n\n   Token() {\n   }\n\n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_Token.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n\n      public abstract Builder id(String id);\n      public abstract Builder methods(List<String> methods);\n      public abstract Builder expiresAt(Date expiresAt);\n      public abstract Builder extras(Object extras);\n      public abstract Builder catalog(List<Catalog> catalog);\n      public abstract Builder auditIds(List<String> auditIds);\n      public abstract Builder user(User user);\n      public abstract Builder issuedAt(Date issuedAt);\n\n      abstract List<Catalog> catalog();\n      abstract List<String> methods();\n      abstract List<String> auditIds();\n\n      abstract Token autoBuild();\n\n      public Token build() {\n         return catalog(catalog() != null ? ImmutableList.copyOf(catalog()) : ImmutableList.<Catalog>of())\n                 .methods(methods() != null ? ImmutableList.copyOf(methods()) : ImmutableList.<String>of())\n                 .auditIds(auditIds() != null ? ImmutableList.copyOf(auditIds()) : ImmutableList.<String>of())\n                 .autoBuild();\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v3/domain/User.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v3.domain;\n\nimport java.util.Date;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class User {\n\n   @AutoValue\n   public abstract static class Domain {\n      public abstract String id();\n      public abstract String name();\n\n      @SerializedNames({ \"id\", \"name\" })\n      public static Domain create(String id, String name) {\n         return new AutoValue_User_Domain(id, name);\n      }\n   }\n\n   public abstract String id();\n   public abstract String name();\n   @Nullable public abstract Date passwordExpiresAt();\n   @Nullable public abstract Domain domain();\n   @Nullable public abstract String domainId();\n   @Nullable public abstract String defaultProjectId();\n   @Nullable public abstract Boolean enabled();\n   @Nullable public abstract Link link();\n\n   @SerializedNames({ \"id\", \"name\", \"password_expires_at\", \"domain\", \"domain_id\", \"default_project_id\", \"enabled\", \"links\" })\n   public static User create(String id, String name, Date passwordExpiresAt, Domain domain, String domainId,\n         String defaultProjectId, Boolean enabled, Link link) {\n      return builder().id(id).name(name).passwordExpiresAt(passwordExpiresAt).domain(domain).domainId(domainId)\n            .defaultProjectId(defaultProjectId).enabled(enabled).link(link).build();\n   }\n\n   User() {\n   }\n   \n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_User.Builder();\n   }\n   \n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder id(String id);\n      public abstract Builder name(String name);\n      public abstract Builder passwordExpiresAt(Date passwordExpiresAt);\n      public abstract Builder domain(Domain domain);\n      public abstract Builder domainId(String domainId);\n      public abstract Builder defaultProjectId(String defaultProjectId);\n      public abstract Builder enabled(Boolean enabled);\n      public abstract Builder link(Link link);\n      public abstract User build();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v3/features/AuthApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v3.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.HEAD;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.keystone.v3.domain.Token;\nimport org.jclouds.openstack.keystone.v3.domain.User;\nimport org.jclouds.openstack.v2_0.services.Identity;\nimport org.jclouds.rest.annotations.Endpoint;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.Headers;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\n/**\n * Provides access to the Keystone Authentication API.\n */\n@Consumes(MediaType.APPLICATION_JSON)\n@RequestFilters(AuthenticateRequest.class)\n@Endpoint(Identity.class)\n@Path(\"/auth\")\npublic interface AuthApi {\n\n   /**\n    * Validate a token and, if it is valid, return access information regarding the tenant (though not the service catalog).\n    */\n   @Named(\"token:get\")\n   @GET\n   @SelectJson(\"token\")\n   @Path(\"/tokens\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   @Headers(keys = \"X-Subject-Token\", values = \"{token}\")\n   Token get(@PathParam(\"token\") String token);\n\n   /**\n    * Validate a token and, if it is valid, return access information regarding the tenant (though not the service catalog).\n    */\n   @Named(\"token:getuser\")\n   @GET\n   @SelectJson(\"user\")\n   @Path(\"/tokens\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   @Headers(keys = \"X-Subject-Token\", values = \"{token}\")\n   User getUserOfToken(@PathParam(\"token\") String token);\n\n   /**\n    * Validate a token. This is a high-performance variant of the #getToken() call that does not return any further\n    * information.\n    */\n   @Named(\"token:check\")\n   @HEAD\n   @Path(\"/tokens\")\n   @Headers(keys = \"X-Subject-Token\", values = \"{token}\")\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean isValid(@PathParam(\"token\") String token);\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v3/features/CatalogApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v3.features;\n\nimport java.util.List;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyListOnNotFoundOr404;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.keystone.v3.domain.Endpoint;\nimport org.jclouds.openstack.v2_0.services.Identity;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\n/**\n * Provides access to the Keystone Admin API.\n */\n@Consumes(MediaType.APPLICATION_JSON)\n@RequestFilters(AuthenticateRequest.class)\n@org.jclouds.rest.annotations.Endpoint(Identity.class)\npublic interface CatalogApi {\n\n   /**\n    * List all endpoints for a token.\n    * <p>\n    * NOTE: currently not working in openstack ( https://bugs.launchpad.net/keystone/+bug/988672 )\n    */\n   @Named(\"endpoints:list\")\n   @GET\n   @SelectJson(\"endpoints\")\n   @Path(\"/endpoints\")\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   List<Endpoint> endpoints();\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v3/features/ProjectApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v3.features;\n\nimport java.util.List;\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.HEAD;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyListOnNotFoundOr404;\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.keystone.v3.domain.Project;\nimport org.jclouds.openstack.v2_0.services.Identity;\nimport org.jclouds.rest.annotations.Endpoint;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PATCH;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.WrapWith;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\n/**\n * Provides access to the Keystone Projects API.\n */\n@Consumes(MediaType.APPLICATION_JSON)\n@RequestFilters(AuthenticateRequest.class)\n@Endpoint(Identity.class)\n@Path(\"/projects\")\npublic interface ProjectApi {\n\n   @Named(\"projects:list\")\n   @GET\n   @SelectJson(\"projects\")\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   List<Project> list();\n   \n   @Named(\"projects:get\")\n   @GET\n   @Path(\"/{id}\")\n   @SelectJson(\"project\")\n   @Fallback(NullOnNotFoundOr404.class)\n   Project get(@PathParam(\"id\") String id);\n   \n   @Named(\"projects:create\")\n   @POST\n   @SelectJson(\"project\")\n   @WrapWith(\"project\") \n   Project create(@PayloadParam(\"name\") String name, @Nullable @PayloadParam(\"description\") String description,\n         @PayloadParam(\"enabled\") boolean enabled, @PayloadParam(\"is_domain\") boolean isDomain,\n         @Nullable @PayloadParam(\"domain_id\") String domainId, @Nullable @PayloadParam(\"parent_id\") String parentId);\n   \n   @Named(\"projects:update\")\n   @PATCH\n   @Path(\"/{id}\")\n   @SelectJson(\"project\")\n   Project update(@PathParam(\"id\") String id, @WrapWith(\"project\") Project project);\n   \n   @Named(\"projects:delete\")\n   @DELETE\n   @Path(\"/{id}\")\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean delete(@PathParam(\"id\") String id);\n   \n   @Named(\"projects:listTags\")\n   @GET\n   @Path(\"/{projectId}/tags\")\n   @SelectJson(\"tags\")\n   Set<String> listTags(@PathParam(\"projectId\") String projectId);\n   \n   @Named(\"projects:hasTag\")\n   @HEAD\n   @Path(\"/{projectId}/tags/{tag}\")\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean hasTag(@PathParam(\"projectId\") String projectId, @PathParam(\"tag\") String tag);\n   \n   @Named(\"projects:addTag\")\n   @PUT\n   @Path(\"/{projectId}/tags/{tag}\")\n   void addTag(@PathParam(\"projectId\") String projectId, @PathParam(\"tag\") String tag);\n   \n   @Named(\"projects:removeTag\")\n   @DELETE\n   @Path(\"/{projectId}/tags/{tag}\")\n   void removeTag(@PathParam(\"projectId\") String projectId, @PathParam(\"tag\") String tag);\n   \n   @Named(\"projects:setTags\")\n   @PUT\n   @Path(\"/{projectId}/tags\")\n   @MapBinder(BindToJsonPayload.class)\n   void setTags(@PathParam(\"projectId\") String projectId, @PayloadParam(\"tags\") Set<String> tags);\n   \n   @Named(\"projects:removeTags\")\n   @DELETE\n   @Path(\"/{projectId}/tags\")\n   void removeAllTags(@PathParam(\"projectId\") String projectId);\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v3/features/RegionApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v3.features;\n\nimport java.util.List;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyListOnNotFoundOr404;\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.keystone.v3.domain.Region;\nimport org.jclouds.openstack.v2_0.services.Identity;\nimport org.jclouds.rest.annotations.Endpoint;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.PATCH;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.WrapWith;\n\n/**\n * Provides access to the Keystone Region API.\n */\n@Consumes(MediaType.APPLICATION_JSON)\n@RequestFilters(AuthenticateRequest.class)\n@Endpoint(Identity.class)\n@Path(\"/regions\")\npublic interface RegionApi {\n\n   @Named(\"regions:list\")\n   @GET\n   @SelectJson(\"regions\")\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   List<Region> list();\n\n   @Named(\"regions:get\")\n   @GET\n   @Path(\"/{id}\")\n   @SelectJson(\"region\")\n   @Fallback(NullOnNotFoundOr404.class)\n   Region get(@PathParam(\"id\") String id);\n\n   @Named(\"regions:create\")\n   @POST\n   @SelectJson(\"region\")\n   @WrapWith(\"region\")\n   Region create(@PayloadParam(\"id\") String id, @Nullable @PayloadParam(\"description\") String description,\n         @Nullable @PayloadParam(\"parent_region_id\") String parentId);\n\n   @Named(\"regions:update\")\n   @PATCH\n   @Path(\"/{id}\")\n   @SelectJson(\"region\")\n   @WrapWith(\"region\")\n   Region update(@PathParam(\"id\") String id, @Nullable @PayloadParam(\"description\") String description,\n         @Nullable @PayloadParam(\"parent_region_id\") String parentId);\n\n   @Named(\"regions:delete\")\n   @DELETE\n   @Path(\"/{id}\")\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean delete(@PathParam(\"id\") String id);\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v3/features/UserApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v3.features;\n\nimport java.util.List;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyListOnNotFoundOr404;\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.keystone.v3.domain.Group;\nimport org.jclouds.openstack.keystone.v3.domain.Project;\nimport org.jclouds.openstack.keystone.v3.domain.User;\nimport org.jclouds.openstack.v2_0.services.Identity;\nimport org.jclouds.rest.annotations.Endpoint;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.PATCH;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.WrapWith;\n\n/**\n * Provides access to the Keystone User API.\n */\n@Consumes(MediaType.APPLICATION_JSON)\n@RequestFilters(AuthenticateRequest.class)\n@Endpoint(Identity.class)\n@Path(\"/users\")\npublic interface UserApi {\n\n   @Named(\"users:list\")\n   @GET\n   @SelectJson(\"users\")\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   List<User> list();\n\n   @Named(\"users:get\")\n   @GET\n   @Path(\"/{id}\")\n   @SelectJson(\"user\")\n   @Fallback(NullOnNotFoundOr404.class)\n   User get(@PathParam(\"id\") String id);\n\n   @Named(\"users:create\")\n   @POST\n   @SelectJson(\"user\")\n   @WrapWith(\"user\")\n   User create(@PayloadParam(\"name\") String name, @Nullable @PayloadParam(\"password\") String password,\n         @Nullable @PayloadParam(\"enabled\") Boolean enabled, @Nullable @PayloadParam(\"domain_id\") String domainId,\n         @Nullable @PayloadParam(\"default_project_id\") String defaultProjectId);\n\n   @Named(\"users:update\")\n   @PATCH\n   @Path(\"/{id}\")\n   @SelectJson(\"user\")\n   @WrapWith(\"user\")\n   User update(@PathParam(\"id\") String id, @PayloadParam(\"name\") String name,\n         @Nullable @PayloadParam(\"password\") String password, @Nullable @PayloadParam(\"enabled\") Boolean enabled,\n         @Nullable @PayloadParam(\"domain_id\") String domainId,\n         @Nullable @PayloadParam(\"default_project_id\") String defaultProjectId);\n\n   @Named(\"users:delete\")\n   @DELETE\n   @Path(\"/{id}\")\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean delete(@PathParam(\"id\") String id);\n\n   @Named(\"users:groups\")\n   @GET\n   @Path(\"/{id}/groups\")\n   @SelectJson(\"groups\")\n   List<Group> listGroups(@PathParam(\"id\") String id);\n\n   @Named(\"users:projects\")\n   @GET\n   @Path(\"/{id}/projects\")\n   @SelectJson(\"projects\")\n   List<Project> listProjects(@PathParam(\"id\") String id);\n\n   @Named(\"users:password\")\n   @POST\n   @Path(\"/{id}/password\")\n   @WrapWith(\"user\")\n   void changePassword(@PathParam(\"id\") String id, @PayloadParam(\"original_password\") String originalPassword,\n         @PayloadParam(\"password\") String newPassword);\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v3/parsers/ParseTokenFromHttpResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v3.parsers;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseFirstJsonValueNamed;\nimport org.jclouds.json.internal.GsonWrapper;\nimport org.jclouds.openstack.keystone.v3.domain.Token;\n\nimport com.google.common.base.Function;\nimport com.google.inject.Inject;\nimport com.google.inject.TypeLiteral;\n\n@Singleton\npublic class ParseTokenFromHttpResponse implements Function<HttpResponse, Token> {\n   private final ParseFirstJsonValueNamed<Token> parser;\n\n   @Inject\n   ParseTokenFromHttpResponse(GsonWrapper gsonView) {\n      this.parser = new ParseFirstJsonValueNamed<Token>(gsonView, TypeLiteral.get(Token.class), \"token\");\n   }\n\n   public Token apply(HttpResponse response) {\n      checkNotNull(response, \"response\");\n      Token toParse = parser.apply(response);\n      checkNotNull(toParse, \"parsed result from %s\", response);\n      String xSubjectToken = response.getFirstHeaderOrNull(\"X-Subject-Token\");\n      return toParse.toBuilder().id(xSubjectToken).build();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/v2_0/ServiceType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.v2_0;\n\n/**\n * An OpenStack service, such as Compute (Nova), Object Storage (Swift), or Image Service (Glance).\n * A service provides one or more endpoints through which users can access resources and perform\n * (presumably useful) operations.\n */\npublic final class ServiceType {\n   /**\n    * Object Storage (Swift)\n    */\n   public static final String OBJECT_STORE = \"object-store\";\n\n   /**\n    * Compute (Nova)\n    */\n   public static final String COMPUTE = \"compute\";\n\n   /**\n    * Image Service (Glance)\n    */\n   public static final String IMAGE = \"image\";\n\n   /**\n    * Identity Service (Keystone)\n    */\n   public static final String IDENTITY = \"identity\";\n\n   /**\n    * Network Service (Neutron)\n    */\n   public static final String NETWORK = \"network\";\n\n   /**\n    * Block Storage (Cinder)\n    */\n   public static final String BLOCK_STORAGE = \"volume\";\n\n   /**\n    * Database Service (Trove)\n    */\n   public static final String DATABASE = \"database\";\n\n   /**\n    * @deprecated use {@link #MESSAGING} instead.\n    * Queues Service (Marconi)\n    */\n   @Deprecated\n   public static final String QUEUES = \"queuing\";\n\n   /**\n    * Orchestration Service (Heat)\n    */\n   public static final String ORCHESTRATION = \"orchestration\";\n\n   /**\n    * CDN Service (Poppy)\n    */\n   public static final String CDN = \"cdn\";\n\n   /**\n    * Shared Filsystem Service (Manila)\n    */\n   public static final String SHARED_FILESYSTEM = \"share\";\n\n   /**\n    * Messaging Service (Zaqar)\n    */\n   public static final String MESSAGING = \"messaging\";\n\n   private ServiceType() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/v2_0/domain/Extension.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.v2_0.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * The OpenStack Compute API is extensible. Extensions serve two purposes: They\n * allow the introduction of new features in the API without requiring a version\n * change and they allow the introduction of vendor specific niche\n * functionality.\n * \n * @see <a href=\n      \"http://docs.openstack.org/api/openstack-compute/2/content/Extensions-d1e1444.html\"\n      />\n*/\npublic class Extension extends Resource {\n\n   public static Builder<?> builder() { \n      return new ConcreteBuilder();\n   }\n   \n   public Builder<?> toBuilder() { \n      return new ConcreteBuilder().fromExtension(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> extends Resource.Builder<T>  {\n      protected URI namespace;\n      protected String alias;\n      protected Date updated;\n      protected String description;\n   \n      /** \n       * @see Extension#getNamespace()\n       */\n      public T namespace(URI namespace) {\n         this.namespace = namespace;\n         return self();\n      }\n\n      /** \n       * @see Extension#getAlias()\n       */\n      public T alias(String alias) {\n         this.alias = alias;\n         return self();\n      }\n\n      /**\n       * @see Extension#getAlias()\n       */\n      @Override\n      public T id(String id) {\n         return alias(id);\n      }\n\n      /** \n       * @see Extension#getUpdated()\n       */\n      public T updated(Date updated) {\n         this.updated = updated;\n         return self();\n      }\n\n      /** \n       * @see Extension#getDescription()\n       */\n      public T description(String description) {\n         this.description = description;\n         return self();\n      }\n\n      public Extension build() {\n         return new Extension(name, links, namespace, alias, updated, description);\n      }\n      \n      public T fromExtension(Extension in) {\n         return super.fromResource(in)\n                  .namespace(in.getNamespace())\n                  .alias(in.getAlias())\n                  .updated(in.getUpdated())\n                  .description(in.getDescription());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final URI namespace;\n   private final String alias;\n   private final Date updated;\n   private final String description;\n\n   @ConstructorProperties({\n      \"name\", \"links\", \"namespace\", \"alias\", \"updated\", \"description\"\n   })\n   protected Extension(@Nullable String name, Set<Link> links, @Nullable URI namespace, String alias,\n         @Nullable Date updated, String description) {\n      super(alias, name, links);\n      this.namespace = namespace;\n      this.alias = checkNotNull(alias, \"alias\");\n      this.updated = updated;\n      this.description = checkNotNull(description, \"description\");\n   }\n\n   @Nullable\n   public URI getNamespace() {\n      return this.namespace;\n   }\n\n   public String getAlias() {\n      return this.alias;\n   }\n\n   @Nullable\n   public Date getUpdated() {\n      return this.updated;\n   }\n\n   public String getDescription() {\n      return this.description;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(namespace, alias, updated, description);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Extension that = Extension.class.cast(obj);\n      return super.equals(that) && Objects.equal(this.namespace, that.namespace)\n               && Objects.equal(this.alias, that.alias)\n               && Objects.equal(this.updated, that.updated)\n               && Objects.equal(this.description, that.description);\n   }\n   \n   protected ToStringHelper string() {\n      return super.string()\n            .add(\"namespace\", namespace).add(\"alias\", alias).add(\"updated\", updated).add(\"description\", description);\n   }\n   \n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/v2_0/domain/Limit.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.v2_0.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.Optional;\n\npublic final class Limit {\n\n   private final String verb;\n   private final String unit;\n   private final int value;\n   private final Optional<Integer> remaining;\n   @Named(\"next-available\")\n   private final Optional<Date> nextAvailable;\n\n   @ConstructorProperties({ \"verb\", \"unit\", \"value\", \"remaining\", \"next-available\" })\n   private Limit(String verb, String unit, int value, @Nullable Integer remaining, @Nullable Date nextAvailable) {\n      this.verb = checkNotNull(verb, \"verb\");\n      this.unit = checkNotNull(unit, \"unit\");\n      this.value = value;\n      this.remaining = Optional.fromNullable(remaining);\n      this.nextAvailable = Optional.fromNullable(nextAvailable);\n   }\n\n   public String getVerb() {\n      return verb;\n   }\n\n   public String getUnit() {\n      return unit;\n   }\n\n   public int getValue() {\n      return value;\n   }\n\n   public Optional<Integer> getRemaining() {\n      return remaining;\n   }\n\n   public Optional<Date> getNextAvailable() {\n      return nextAvailable;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(verb, unit);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      Limit that = Limit.class.cast(obj);\n      return equal(this.verb, that.verb) && equal(this.unit, that.unit);\n   }\n\n   @Override\n   public String toString() {\n      return toStringHelper(this).omitNullValues().add(\"verb\", verb).add(\"unit\", unit).add(\"value\", value)\n            .add(\"remaining\", remaining.orNull()).add(\"nextAvailable\", nextAvailable.orNull()).toString();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/v2_0/domain/Limits.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.v2_0.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Map;\n\nimport jakarta.inject.Named;\n\nimport com.google.common.base.Objects;\n\npublic final class Limits {\n\n   @Named(\"rate\")\n   private final Iterable<RateLimit> rateLimits;\n   @Named(\"absolute\")\n   private final Map<String, Integer> absoluteLimits;\n\n   @ConstructorProperties({ \"rate\", \"absolute\" })\n   private Limits(Iterable<RateLimit> rateLimits, Map<String, Integer> absoluteLimits) {\n      this.rateLimits = checkNotNull(rateLimits, \"rateLimits\");\n      this.absoluteLimits = checkNotNull(absoluteLimits, \"absoluteLimits\");\n   }\n\n   public Iterable<RateLimit> getRateLimits() {\n      return rateLimits;\n   }\n\n   public Map<String, Integer> getAbsoluteLimits() {\n      return absoluteLimits;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(rateLimits, absoluteLimits);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      Limits that = Limits.class.cast(obj);\n      return equal(this.rateLimits, that.rateLimits) && equal(this.absoluteLimits, that.absoluteLimits);\n   }\n\n   @Override\n   public String toString() {\n      return toStringHelper(this).add(\"rateLimits\", rateLimits).add(\"absoluteLimits\", absoluteLimits).toString();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/v2_0/domain/Link.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.v2_0.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.net.URI;\n\nimport jakarta.inject.Named;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.base.Optional;\n\n/**\n * For convenience, resources contain links to themselves. This allows a api to easily obtain a\n * resource URIs rather than to construct them.\n * \n * @see <a href= \"http://docs.openstack.org/api/openstack-compute/1.1/content/LinksReferences.html\"\n *      />\n */\npublic class Link {\n   /**\n    * Relations associated with resources.\n    */\n   public static enum Relation {\n      /**\n       * a versioned link to the resource. These links should be used in cases where the link will\n       * be followed immediately.\n       */\n      SELF,\n      /**\n       * a permanent link to a resource that is appropriate for long term storage.\n       */\n      BOOKMARK,\n      /**\n       * \n       */\n      DESCRIBEDBY,\n      /**\n       * Indicates that the link's context is a part of a series, and that the next in the series is\n       * the link target.\n       */\n      NEXT,\n\n      /**\n       * Indicates that the link's context is a part of a series, and that the previous in the\n       * series is the link target.\n       */\n      PREVIOUS,\n\n      ALTERNATE,\n      /**\n       * the value returned by the OpenStack service was not recognized.\n       */\n      UNRECOGNIZED;\n\n      public String value() {\n         return name().toLowerCase();\n      }\n\n      public static Relation fromValue(String v) {\n         try {\n            return valueOf(v.toUpperCase());\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n   }\n\n   public static Link create(Relation relation, URI href) {\n      return new Link(relation, null, href);\n   }\n\n   public static Link create(Relation relation, String type, URI href) {\n      return new Link(relation, Optional.fromNullable(type), href);\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().fromLink(this);\n   }\n\n   public static class Builder {\n\n      protected Link.Relation relation;\n      protected Optional<String> type = Optional.absent();\n      protected URI href;\n\n      /**\n       * @see Link#getRelation()\n       */\n      public Builder relation(Link.Relation relation) {\n         this.relation = relation;\n         return this;\n      }\n\n      /**\n       * @see Link#getType()\n       */\n      public Builder type(String type) {\n         this.type = Optional.fromNullable(type);\n         return this;\n      }\n\n      /**\n       * @see Link#getHref()\n       */\n      public Builder href(URI href) {\n         this.href = href;\n         return this;\n      }\n\n      public Link build() {\n         return new Link(relation, type, href);\n      }\n\n      public Builder fromLink(Link in) {\n         return this.relation(in.getRelation()).type(in.getType().orNull()).href(in.getHref());\n      }\n   }\n\n   @Named(\"rel\")\n   private final Link.Relation relation;\n   private final Optional<String> type;\n   private final URI href;\n\n   @ConstructorProperties({ \"rel\", \"type\", \"href\" })\n   protected Link(Link.Relation relation, Optional<String> type, URI href) {\n      this.href = checkNotNull(href, \"href\");\n      this.relation = checkNotNull(relation, \"relation of %s\", href);\n      this.type = (type == null) ? Optional.<String> absent() : type;\n   }\n\n   /**\n    * There are three kinds of link relations associated with resources. A self link contains a\n    * versioned link to the resource. These links should be used in cases where the link will be\n    * followed immediately. A bookmark link provides a permanent link to a resource that is\n    * appropriate for long term storage. An alternate link can contain an alternate representation\n    * of the resource. For example, an OpenStack Compute image may have an alternate representation\n    * in the OpenStack Image service. Note that the type attribute here is used to provide a hint as\n    * to the type of representation to expect when following the link.\n    * \n    * @return the relation of the resource in the current OpenStack deployment\n    */\n   public Link.Relation getRelation() {\n      return this.relation;\n   }\n\n   /**\n    * @return the type of the resource or null if not specified\n    */\n   public Optional<String> getType() {\n      return this.type;\n   }\n\n   /**\n    * @return the href of the resource\n    */\n   public URI getHref() {\n      return this.href;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(relation, type, href);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      Link that = Link.class.cast(obj);\n      return Objects.equal(this.relation, that.relation) && Objects.equal(this.type, that.type)\n               && Objects.equal(this.href, that.href);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"relation\", relation).add(\"type\", type.orNull())\n               .add(\"href\", href);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/v2_0/domain/PaginatedCollection.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.v2_0.domain;\n\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Multimap;\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\n\nimport java.util.Iterator;\n\nimport static org.jclouds.http.utils.Queries.queryParser;\n\n/**\n * Base class for a paginated collection in OpenStack.\n *\n */\npublic class PaginatedCollection<T> extends IterableWithMarker<T> {\n   private final Iterable<T> resources;\n   private final Iterable<Link> links;\n   private final Integer totalEntries;\n\n   protected PaginatedCollection(@Nullable Iterable<T> resources, @Nullable Iterable<Link> links,\n                                 @Nullable Integer totalEntries) {\n      this.resources = resources != null ? resources : ImmutableSet.<T> of();\n      this.links = links != null ? links : ImmutableSet.<Link> of();\n      this.totalEntries = totalEntries;\n   }\n\n   protected PaginatedCollection(Iterable<T> resources, Iterable<Link> links) {\n      this(resources, links, null);\n   }\n\n   @Override\n   public Iterator<T> iterator() {\n      return resources.iterator();\n   }\n\n   /**\n    * links that relate to this collection\n    */\n   public Iterable<Link> getLinks() {\n      return links;\n   }\n\n   /**\n    * @return The total number of entries in this collection, if that information is present.\n    */\n   public Optional<Integer> getTotalEntries() {\n      return Optional.fromNullable(totalEntries);\n   }\n\n   public PaginationOptions nextPaginationOptions() {\n      return PaginationOptions.class.cast(nextMarker().get());\n   }\n\n   @Override\n   public Optional<Object> nextMarker() {\n      for (Link link : getLinks()) {\n         if (Link.Relation.NEXT == link.getRelation()) {\n            return Optional.of(toPaginationOptions(link));\n         }\n      }\n\n      return Optional.absent();\n   }\n\n   private Object toPaginationOptions(Link link) {\n      Multimap<String, String> queryParams = queryParser().apply(link.getHref().getRawQuery());\n      PaginationOptions paginationOptions = PaginationOptions.Builder.queryParameters(queryParams);\n\n      return paginationOptions;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/v2_0/domain/RateLimit.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.v2_0.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Named;\n\nimport com.google.common.base.Objects;\n\npublic final class RateLimit {\n\n   private final String uri;\n   private final String regex;\n   @Named(\"limit\")\n   private final Iterable<Limit> limits;\n\n   @ConstructorProperties({ \"uri\", \"regex\", \"limit\" })\n   private RateLimit(String uri, String regex, Iterable<Limit> limits) {\n      this.uri = checkNotNull(uri, \"uri\");\n      this.regex = checkNotNull(regex, \"regex\");\n      this.limits = checkNotNull(limits, \"limit\");\n   }\n\n   public String getUri() {\n      return uri;\n   }\n\n   public String getRegex() {\n      return regex;\n   }\n\n   public Iterable<Limit> getLimits() {\n      return limits;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(uri);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      RateLimit that = RateLimit.class.cast(obj);\n      return equal(this.uri, that.uri);\n   }\n\n   @Override\n   public String toString() {\n      return toStringHelper(this).add(\"uri\", uri).add(\"regex\", regex).add(\"limits\", limits).toString();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/v2_0/domain/Resource.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.v2_0.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Resource found in a paginated collection\n *\n * @see <a href=\n\"http://docs.openstack.org/api/openstack-compute/1.1/content/Paginated_Collections-d1e664.html\"\n/>\n */\npublic class Resource implements Comparable<Resource> {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromResource(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>>  {\n      protected abstract T self();\n\n      protected String id;\n      protected String name;\n      protected Set<Link> links;\n\n      /**\n       * @see Resource#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see Resource#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /**\n       * @see Resource#getLinks()\n       */\n      public T links(Set<Link> links) {\n         this.links = links == null ? null : ImmutableSet.copyOf(links);\n         return self();\n      }\n\n      public T links(Link... in) {\n         return links(in == null ? null : ImmutableSet.copyOf(in));\n      }\n\n      public Resource build() {\n         return new Resource(id, name, links);\n      }\n\n      public T fromResource(Resource in) {\n         return this\n               .id(in.getId())\n               .name(in.getName())\n               .links(in.getLinks());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final String name;\n   private final Set<Link> links;\n\n   @ConstructorProperties({\n         \"id\", \"name\", \"links\"\n   })\n   protected Resource(String id, @Nullable String name, @Nullable Set<Link> links) {\n      this.id = checkNotNull(id, \"id\");\n      this.name = name;\n      this.links = links == null ? null : ImmutableSet.copyOf(links);\n   }\n   \n   /**\n    * When providing an ID, it is assumed that the resource exists in the current OpenStack\n    * deployment\n    *\n    * @return the id of the resource in the current OpenStack deployment\n    */\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * @return the name of the resource\n    */\n   @Nullable\n   public String getName() {\n      return this.name;\n   }\n\n   /**\n    * @return the links of the id address allocated to the new server\n    */\n   @Nullable\n   public Set<Link> getLinks() {\n      return this.links;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, name, links);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Resource that = Resource.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n            && Objects.equal(this.name, that.name)\n            && Objects.equal(this.links, that.links);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"name\", name).add(\"links\", links);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int compareTo(Resource that) {\n      if (that == null)\n         return 1;\n      if (this == that)\n         return 0;\n      return this.getId().compareTo(that.getId());\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/v2_0/features/ExtensionApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.v2_0.features;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.v2_0.domain.Extension;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\n/**\n * Provides access to OpenStack Extension APIs.\n */\n@Consumes(MediaType.APPLICATION_JSON)\n@RequestFilters(AuthenticateRequest.class)\n@Path(\"/extensions\")\npublic interface ExtensionApi {\n\n   /**\n    * Lists all available extensions\n    *\n    * @return all extensions\n    */\n   @Named(\"extension:list\")\n   @GET\n   @SelectJson(\"extensions\")\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<Extension> list();\n\n   /**\n    * Extensions may also be queried individually by their unique alias.\n    *\n    * @param id\n    *           id of the extension\n    * @return extension or null if not found\n    */\n   @Named(\"extension:get\")\n   @GET\n   @SelectJson(\"extension\")\n   @Path(\"/{alias}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Extension get(@PathParam(\"alias\") String id);\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/v2_0/functions/PresentWhenExtensionAnnotationMatchesExtensionSet.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.v2_0.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.any;\nimport static org.jclouds.openstack.v2_0.predicates.ExtensionPredicates.aliasEquals;\nimport static org.jclouds.openstack.v2_0.predicates.ExtensionPredicates.nameEquals;\nimport static org.jclouds.openstack.v2_0.predicates.ExtensionPredicates.namespaceOrAliasEquals;\nimport static org.jclouds.util.Optionals2.unwrapIfOptional;\n\nimport java.net.URI;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.openstack.keystone.v2_0.config.NamespaceAliases;\nimport org.jclouds.openstack.v2_0.domain.Extension;\nimport org.jclouds.reflect.InvocationSuccess;\nimport org.jclouds.rest.functions.ImplicitOptionalConverter;\n\nimport com.google.common.base.Optional;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Sets;\n\n/**\n * We use the annotation {@link Extension} to bind a class that implements an extension\n * API to an {@link Extension}.\n *\n * Match in the following order:\n *\n * 1. Match by namespace\n * 2. Match by namespace aliases\n * 3. Match by alias\n * 4. Match by name\n *\n * New versions of openstack have no namespaces anymore.\n * Alias is different than a namespace alias - it's an alternative namespace URL to match against.\n */\npublic class PresentWhenExtensionAnnotationMatchesExtensionSet implements\n      ImplicitOptionalConverter {\n   private final LoadingCache<String, Set<? extends Extension>> extensions;\n   private final Map<URI, Set<URI>> aliases;\n\n   @Inject\n   PresentWhenExtensionAnnotationMatchesExtensionSet(\n         LoadingCache<String, Set<? extends Extension>> extensions, @NamespaceAliases Map<URI, Set<URI>> aliases) {\n      this.extensions = extensions;\n      this.aliases = aliases == null ? ImmutableMap.<URI, Set<URI>> of() : ImmutableMap.copyOf(aliases);\n   }\n\n   private boolean checkExtension(String invocationArg, URI namespace,\n         Set<URI> aliasesForNamespace, String alias, String name) {\n      if (any(extensions.getUnchecked(invocationArg), namespaceOrAliasEquals(namespace, aliasesForNamespace)))\n         return true;\n      // Could not find extension by namespace or namespace alias. Try to find it by alias next:\n      if ( !\"\".equals(alias)) {\n         if (any(extensions.getUnchecked(invocationArg), aliasEquals(alias)))\n            return true;\n      }\n      // Could not find extension by namespace or namespace alias or alias. Try to find it by name next:\n      if ( !\"\".equals(name)) {\n         if (any(extensions.getUnchecked(invocationArg), nameEquals(name)))\n            return true;\n      }\n      return false;\n   }\n\n   @Override\n   public Optional<Object> apply(InvocationSuccess input) {\n      Class<?> target = unwrapIfOptional(input.getInvocation().getInvokable().getReturnType());\n      Optional<org.jclouds.openstack.v2_0.services.Extension> ext = Optional.fromNullable(target\n            .getAnnotation(org.jclouds.openstack.v2_0.services.Extension.class));\n      if (ext.isPresent()) {\n         URI namespace = URI.create(ext.get().namespace());\n         List<Object> args = input.getInvocation().getArgs();\n         Set<URI> aliasesForNamespace = aliases.containsKey(namespace) ? aliases.get(namespace) : Sets.<URI> newHashSet();\n         String name = ext.get().name();\n         String alias = ext.get().alias();\n\n         if (args.isEmpty()) {\n            if (checkExtension(\"\", namespace, aliasesForNamespace, alias, name)) {\n               return input.getResult();\n            }\n         } else if (args.size() == 1) {\n            String arg0 = checkNotNull(args.get(0), \"arg[0] in %s\", input).toString();\n            if (checkExtension(arg0, namespace, aliasesForNamespace, alias, name)) {\n               return input.getResult();\n            }\n         } else {\n            throw new RuntimeException(String.format(\"expecting zero or one args %s\", input));\n         }\n\n         return Optional.absent();\n      } else {\n         // No extension annotation, should check whether to return absent\n         return input.getResult();\n      }\n   }\n\n   @Override\n   public String toString() {\n      return \"PresentWhenExtensionAnnotationMatchesExtensionSet()\";\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/v2_0/options/PaginationOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.v2_0.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\n\nimport java.util.Date;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.Multimap;\n\n/**\n * Options used to control paginated results (aka list commands).\n *\n */\npublic class PaginationOptions extends BaseHttpRequestOptions {\n   /**\n    * Many OpenStack interfaces take different params for pagination. Using queryParams allows you to make\n    * use of them all if necessary.\n    */\n   public PaginationOptions queryParameters(Multimap<String, String> queryParams) {\n      checkNotNull(queryParams, \"queryParams\");\n      queryParameters.putAll(queryParams);\n      return this;\n   }\n\n   /**\n    * Only return objects changed since a specified time.\n    *\n    * @deprecated The {@code changes-since} query does not apply to all OpenStack APIs. Please refer to the OpenStack\n    *             Nova {@code ListOptions.changesSince(Date)} and Glance {@code ListImageOptions.changesSince(Date)}.\n    *             To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   public PaginationOptions changesSince(Date changesSince) {\n      this.queryParameters.put(\"changes-since\", checkNotNull(changesSince, \"changesSince\").getTime() / 1000 + \"\");\n      return this;\n   }\n\n   /**\n    * The marker parameter is the ID of the last item in the previous list. Items are sorted by\n    * create time in descending order. When a create time is not available they are sorted by ID.\n    */\n   public PaginationOptions marker(String marker) {\n      queryParameters.put(\"marker\", checkNotNull(marker, \"marker\"));\n      return this;\n   }\n\n   /**\n    * To reduce load on the service, list operations will return a maximum of 1,000 items at a time.\n    * To navigate the collection, the parameters limit and offset can be set in the URI\n    * (e.g.?limit=0&offset=0). If an offset is given beyond the end of a list an empty list will be\n    * returned.\n    * <p/>\n    * Note that list operations never return itemNotFound (404) faults.\n    */\n   public PaginationOptions limit(int limit) {\n      checkState(limit >= 0, \"limit must be >= 0\");\n      checkState(limit <= 10000, \"limit must be <= 10000\");\n      queryParameters.put(\"limit\", Integer.toString(limit));\n      return this;\n   }\n\n   public static class Builder {\n      /**\n       * @see PaginationOptions#queryParameters(Multimap)\n       */\n      public static PaginationOptions queryParameters(Multimap<String, String> queryParams) {\n         PaginationOptions options = new PaginationOptions();\n         return options.queryParameters(queryParams);\n      }\n\n      /**\n       * @see PaginationOptions#changesSince(Date)\n       * @deprecated The {@code changes-since} query does not apply to all OpenStack APIs. Please refer to the OpenStack\n       *             Nova {@code ListOptions.changesSince(Date)} and Glance {@code ListImageOptions.changesSince(Date)}.\n       *             To be removed in jclouds 2.0.\n       */\n      @Deprecated\n      public static PaginationOptions changesSince(Date changesSince) {\n         PaginationOptions options = new PaginationOptions();\n         return options.changesSince(changesSince);\n      }\n\n      /**\n       * @see PaginationOptions#marker(String)\n       */\n      public static PaginationOptions marker(String marker) {\n         PaginationOptions options = new PaginationOptions();\n         return options.marker(marker);\n      }\n\n      /**\n       * @see PaginationOptions#limit(int)\n       */\n      public static PaginationOptions limit(int limit) {\n         PaginationOptions options = new PaginationOptions();\n         return options.limit(limit);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/v2_0/predicates/ExtensionPredicates.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.v2_0.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.net.URI;\nimport java.util.Collection;\n\nimport org.jclouds.openstack.v2_0.domain.Extension;\n\nimport com.google.common.base.Predicate;\n\n/**\n * Predicates handy when working with Extensions\n */\n\npublic class ExtensionPredicates {\n\n   /**\n    * matches namespace of the given extension\n    *\n    * @param namespace\n    *           ex {@code http://docs.openstack.org/ext/keypairs/api/v1.1}\n    * @return predicate that will match namespace of the given extension\n    */\n   public static Predicate<Extension> namespaceEquals(final URI namespace) {\n      checkNotNull(namespace, \"namespace must be defined\");\n\n      return new Predicate<Extension>() {\n         @Override\n         public boolean apply(Extension ext) {\n            return ext.getNamespace() == null ? false : namespace.toASCIIString().equals(\n                  ext.getNamespace().toASCIIString().replace(\"https\", \"http\"));\n         }\n\n         @Override\n         public String toString() {\n            return \"namespaceEquals(\" + namespace + \")\";\n         }\n      };\n   }\n\n   /**\n    * matches alias of the given extension\n    *\n    * @param alias\n    *           ex. {@code os-keypairs}\n    * @return predicate that will alias of the given extension\n    */\n   public static Predicate<Extension> aliasEquals(final String alias) {\n      checkNotNull(alias, \"alias must be defined\");\n\n      return new Predicate<Extension>() {\n         @Override\n         public boolean apply(Extension ext) {\n            return alias.equals(ext.getAlias());\n         }\n\n         @Override\n         public String toString() {\n            return \"aliasEquals(\" + alias + \")\";\n         }\n      };\n   }\n   /**\n    * matches namespace of the given extension\n    *\n    * @param namespace\n    *           ex {@code http://docs.openstack.org/ext/keypairs/api/v1.1}\n    * @param namespaceAliases\n    *           Collection of ex {@code http://docs.openstack.org/compute/ext/keypairs/api/v1.1}\n    * @return predicate that will match namespace of the given extension\n    */\n   public static Predicate<Extension> namespaceOrAliasEquals(final URI namespace, final Collection<URI> namespaceAliases) {\n      checkNotNull(namespace, \"namespace must be defined\");\n      checkNotNull(namespaceAliases, \"namespace aliases must be defined\");\n\n      return new Predicate<Extension>() {\n         @Override\n         public boolean apply(Extension ext) {\n            return ext.getNamespace() == null ? false : (namespaceEquals(namespace).apply(ext) || namespaceAliases.contains(ext\n                  .getNamespace()));\n         }\n\n         @Override\n         public String toString() {\n            return \"namespaceOrAliasEquals(\" + namespace + \")\";\n         }\n      };\n   }\n\n   /**\n    * matches name of the given extension\n    *\n    * @param name\n    *           ex {@code http://docs.openstack.org/ext/keypairs/api/v1.1}\n    * @return predicate that will match name of the given extension\n    */\n   public static Predicate<Extension> nameEquals(final String name) {\n      checkNotNull(name, \"extension name must be defined\");\n\n      return new Predicate<Extension>() {\n         @Override\n         public boolean apply(Extension ext) {\n            return name.equals(ext.getName());\n         }\n\n         @Override\n         public String toString() {\n            return \"nameEquals(\" + name + \")\";\n         }\n      };\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/v2_0/predicates/LinkPredicates.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.v2_0.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.net.URI;\n\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.Link.Relation;\n\nimport com.google.common.base.Predicate;\n\n/**\n * Predicates handy when working with Link Types\n */\n\npublic class LinkPredicates {\n   /**\n    * matches links of the given relation\n    * \n    * @param rel relation of the link\n    * @return predicate that will match links of the given rel\n    */\n   public static Predicate<Link> relationEquals(final Relation rel) {\n      checkNotNull(rel, \"rel must be defined\");\n\n      return new Predicate<Link>() {\n         @Override\n         public boolean apply(Link link) {\n            return rel.equals(link.getRelation());\n         }\n\n         @Override\n         public String toString() {\n            return \"relEquals(\" + rel + \")\";\n         }\n      };\n   }\n\n   /**\n    * matches links of the given href\n    * \n    * @param href\n    * @return predicate that will match links of the given href\n    */\n   public static Predicate<Link> hrefEquals(final URI href) {\n      checkNotNull(href, \"href must be defined\");\n\n      return new Predicate<Link>() {\n         @Override\n         public boolean apply(Link link) {\n            return href.equals(link.getHref());\n         }\n\n         @Override\n         public String toString() {\n            return \"hrefEquals(\" + href + \")\";\n         }\n      };\n   }\n\n   /**\n    * matches links of the given type\n    * \n    * @param type\n    *           ex. application/pdf\n    * @return predicate that will match links of the given type\n    */\n   public static Predicate<Link> typeEquals(final String type) {\n      checkNotNull(type, \"type must be defined\");\n\n      return new Predicate<Link>() {\n         @Override\n         public boolean apply(Link link) {\n            return type.equals(link.getType().orNull());\n         }\n\n         @Override\n         public String toString() {\n            return \"typeEquals(\" + type + \")\";\n         }\n      };\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/v2_0/services/Compute.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.v2_0.services;\n\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\nimport jakarta.inject.Qualifier;\n\n/**\n * Compute (Nova)\n * \n * @see <a href=\"http://docs.openstack.org/api/openstack-typeentity-service/2.0/content/Identity-Service-Concepts-e1362.html\"\n *      />\n * @see ServiceType#COMPUTE\n */\n@Retention(value = RetentionPolicy.RUNTIME)\n@Target(value = { ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })\n@Qualifier\npublic @interface Compute {\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/v2_0/services/Extension.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.v2_0.services;\n\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\nimport jakarta.inject.Qualifier;\n\n/**\n * An extension of a {@link ServiceType service}. In order for us to understand\n * the context of the extension, we must consider the <a href=\n * \"http://docs.openstack.org/api/openstack-compute/2/content/Extensions-d1e1444.html\"\n * >extensions call</a>.\n *\n * <br/>\n * For our purposes, the minimal context of an extension is the type of the\n * service it extends ex. {@link ServiceType#COMPUTE}, and its namespace ex. <a\n * href\n * =\"http://docs.openstack.org/ext/keypairs/api/v1.1\">http://docs.openstack.org\n * /ext/keypairs/api/v1.1</a>.\n *\n * <br/><br/>\n * A keystone extension example:<br/><br/>\n * {<br/>\n * \"updated\": \"2014-12-03T00:00:00Z\",<br/>\n * \"name\": \"DiskConfig\",<br/>\n * \"links\": [<br/>\n *<br/>\n * ],<br/>\n * \"namespace\": \"http://docs.openstack.org/compute/ext/fake_xml\",<br/>\n * \"alias\": \"OS-DCF\",<br/>\n * \"description\": \"Disk Management Extension.\"<br/>\n * },<br/>\n *<br/>\n * @see ServiceType\n * @see <a href=\n *      \"http://docs.openstack.org/api/openstack-compute/2/content/Extensions-d1e1444.html\"\n *      />\n * @see <a href=\"http://nova.openstack.org/api_ext\" />\n * @see <a href=\"http://nova.openstack.org/api_ext/ext_keypairs.html\" />\n */\n@Retention(value = RetentionPolicy.RUNTIME)\n@Target(value = { ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })\n@Qualifier\npublic @interface Extension {\n\n   /**\n    * the service type this is an extension of.\n    *\n    * <h3>note</h3>\n    *\n    * This isn't necessarily one of the built-in {@link ServiceType services},\n    * it could be an extension of a custom service.\n    *\n    * @return the service type this is an extension of.\n    *\n    */\n   String of();\n\n   /**\n    * namespace ex. <a href\n    * =\"http://docs.openstack.org/ext/keypairs/api/v1.1\">http\n    * ://docs.openstack.org /ext/keypairs/api/v1.1</a>.\n    *\n    * @return the namespace of the extension\n    */\n   String namespace();\n\n   /**\n    * @return the name of the extension\n    */\n   String name() default \"\";\n\n   /**\n    * @return the alias of the extension\n    */\n   String alias() default \"\";\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/v2_0/services/Identity.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.v2_0.services;\n\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\nimport jakarta.inject.Qualifier;\n\n/**\n * Identity Service (Keystone)\n * \n * @see <a href=\"http://docs.openstack.org/api/openstack-typeentity-service/2.0/content/Identity-Service-Concepts-e1362.html\"\n *      />\n * @see ServiceType#IMAGE\n */\n@Retention(value = RetentionPolicy.RUNTIME)\n@Target(value = { ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })\n@Qualifier\npublic @interface Identity {\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/v2_0/services/Image.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.v2_0.services;\n\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\nimport jakarta.inject.Qualifier;\n\n/**\n * Image Service (Glance)\n * \n * @see <a href=\"http://docs.openstack.org/api/openstack-typeentity-service/2.0/content/Identity-Service-Concepts-e1362.html\"\n *      />\n * @see ServiceType#IMAGE\n */\n@Retention(value = RetentionPolicy.RUNTIME)\n@Target(value = { ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })\n@Qualifier\npublic @interface Image {\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/main/java/org/jclouds/openstack/v2_0/services/ObjectStore.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.v2_0.services;\n\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\nimport jakarta.inject.Qualifier;\n\n/**\n * Object Storage (Swift)\n * \n * @see <a href=\"http://docs.openstack.org/api/openstack-typeentity-service/2.0/content/Identity-Service-Concepts-e1362.html\"\n *      />\n * @see ServiceType#OBJECT_STORE\n */\n@Retention(value = RetentionPolicy.RUNTIME)\n@Target(value = { ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })\n@Qualifier\npublic @interface ObjectStore {\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/auth/config/CredentialTypesTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.auth.config;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.openstack.keystone.auth.domain.PasswordCredentials;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\", testName = \"CredentialTypesTest\")\npublic class CredentialTypesTest {\n\n   public void testCredentialTypeOfWhenValid() {\n      assertEquals(\n            CredentialTypes.credentialTypeOf(PasswordCredentials.builder().username(\"username\").password(\"password\")\n                  .build()), CredentialTypes.PASSWORD_CREDENTIALS);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testCredentialTypeOfWithoutAnnotation() {\n      CredentialTypes.credentialTypeOf(\"\");\n   }\n\n   public void testIndexByCredentialTypeWhenValid() {\n      assertEquals(\n            CredentialTypes.indexByCredentialType(\n                  ImmutableSet.of(PasswordCredentials.builder().username(\"username\").password(\"password\").build()))\n                  .keySet(), ImmutableSet.of(CredentialTypes.PASSWORD_CREDENTIALS));\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testIndexByCredentialTypeWithoutAnnotation() {\n      CredentialTypes.indexByCredentialType(ImmutableSet.of(\"\"));\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/auth/config/ProviderModuleExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.auth.config;\n\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.CREDENTIAL_TYPE;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.KEYSTONE_VERSION;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.SERVICE_TYPE;\nimport static org.jclouds.util.Suppliers2.getLastValueInMap;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.Closeable;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\nimport java.net.URI;\nimport java.util.Properties;\n\nimport jakarta.inject.Qualifier;\nimport jakarta.inject.Singleton;\nimport jakarta.ws.rs.HEAD;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\n\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.json.config.GsonModule.DateAdapter;\nimport org.jclouds.json.config.GsonModule.Iso8601DateAdapter;\nimport org.jclouds.location.suppliers.RegionIdToURISupplier;\nimport org.jclouds.openstack.keystone.catalog.config.ServiceCatalogModule;\nimport org.jclouds.openstack.keystone.catalog.config.ServiceCatalogModule.ProviderModule;\nimport org.jclouds.openstack.keystone.catalog.config.ServiceCatalogModule.RegionModule;\nimport org.jclouds.openstack.keystone.v2_0.KeystoneApi;\nimport org.jclouds.openstack.keystone.v2_0.internal.BaseKeystoneRestApiExpectTest;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.annotations.ApiVersion;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.config.HttpApiModule;\nimport org.jclouds.rest.internal.BaseHttpApiMetadata;\nimport org.jclouds.rest.internal.BaseRestApiExpectTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\nimport com.google.inject.Provides;\n\n/**\n * Tests configuration via {@link ProviderModule}\n */\n@Test(groups = \"unit\", testName = \"ProviderModuleExpectTest\")\npublic class ProviderModuleExpectTest extends BaseRestApiExpectTest<ProviderModuleExpectTest.DNSApi> {\n\n   @Retention(RUNTIME)\n   @Target(METHOD)\n   @Qualifier\n   static @interface DNS {\n   }\n\n   @ConfiguresHttpApi\n   public static class DNSHttpApiModule extends HttpApiModule<DNSApi> {\n\n      @Override\n      public void configure() {\n         bind(DateAdapter.class).to(Iso8601DateAdapter.class);\n         super.configure();\n      }\n\n      @Provides\n      @Singleton\n      @DNS\n      protected final Supplier<URI> provideCDNUrl(RegionIdToURISupplier.Factory factory, @ApiVersion String apiVersion) {\n         return getLastValueInMap(factory.createForApiTypeAndVersion(\"dns\", apiVersion));\n      }\n   }\n\n   @org.jclouds.rest.annotations.Endpoint(DNS.class)\n   interface DNSApi extends Closeable {\n      @HEAD\n      @Path(\"/zones/{zoneName}\")\n      @Fallback(FalseOnNotFoundOr404.class)\n      boolean zoneExists(@PathParam(\"zoneName\") String zoneName);\n   }\n\n   public void testDNSEndpointApplied() {\n      KeystoneAuth keystoneAuth = new KeystoneAuth();\n\n      DNSApi api = requestsSendResponses(\n            keystoneAuth.getKeystoneAuthWithUsernameAndPassword(),\n            keystoneAuth.getResponseWithKeystoneAccess(),\n            HttpRequest.builder().method(\"HEAD\").endpoint(\"http://172.16.0.1:8776/v1/3456/zones/foo.com\").build(),\n            HttpResponse.builder().statusCode(200).build());\n      assertTrue(api.zoneExists(\"foo.com\"));\n   }\n\n   private static class DNSApiMetadata extends BaseHttpApiMetadata<DNSApi> {\n\n      @Override\n      public Builder toBuilder() {\n         return new Builder().fromApiMetadata(this);\n      }\n\n      public DNSApiMetadata() {\n         this(new Builder());\n      }\n\n      protected DNSApiMetadata(Builder builder) {\n         super(builder);\n      }\n\n      public static Properties defaultProperties() {\n         Properties properties = BaseHttpApiMetadata.defaultProperties();\n         properties.setProperty(SERVICE_TYPE, \"dns\");\n         properties.setProperty(KEYSTONE_VERSION, \"2\");\n         properties.setProperty(CREDENTIAL_TYPE, CredentialTypes.PASSWORD_CREDENTIALS);\n         return properties;\n      }\n\n      public static class Builder extends BaseHttpApiMetadata.Builder<DNSApi, Builder> {\n\n         protected Builder() {\n            id(\"dns\")\n            .name(\"DNS API\")\n            .identityName(\"${tenantName}:${userName} or ${userName}, if your keystone supports a default tenant\")\n            .credentialName(\"${password}\")\n            .endpointName(\"Keystone base url ending in /v2.0/\")\n            .documentation(URI.create(\"http://dns\"))\n            .version(\"1.0\")\n            .defaultEndpoint(\"http://localhost:5000/v2.0/\")\n            .defaultProperties(DNSApiMetadata.defaultProperties())\n            .defaultModules(ImmutableSet.<Class<? extends Module>>builder()\n                                        .add(AuthenticationModule.class)\n                                        .add(ServiceCatalogModule.class)\n                                        .add(RegionModule.class)\n                                        .add(DNSHttpApiModule.class).build());\n         }\n\n         @Override\n         public DNSApiMetadata build() {\n            return new DNSApiMetadata(this);\n         }\n\n         @Override\n         protected Builder self() {\n            return this;\n         }\n      }\n   }\n\n   @Override\n   public ApiMetadata createApiMetadata() {\n      return new DNSApiMetadata();\n   }\n   \n   public static class KeystoneAuth extends BaseKeystoneRestApiExpectTest<KeystoneApi> {\n      public HttpRequest getKeystoneAuthWithUsernameAndPassword() {\n         return keystoneAuthWithUsernameAndPassword;\n      }\n      \n      public HttpResponse getResponseWithKeystoneAccess() {\n         return responseWithKeystoneAccess;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/auth/handlers/RetryOnRenewTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.auth.handlers;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.expectLastCall;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.handlers.BackoffLimitedRetryHandler;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.openstack.keystone.auth.domain.AuthInfo;\nimport org.testng.annotations.Test;\n\nimport com.google.common.cache.LoadingCache;\n\n/**\n * Tests behavior of {@code RetryOnRenew} handler\n */\n@Test(groups = \"unit\", testName = \"RetryOnRenewTest\")\npublic class RetryOnRenewTest {\n   @Test\n   public void test401ShouldRetry() {\n      HttpCommand command = createMock(HttpCommand.class);\n      HttpRequest request = createMock(HttpRequest.class);\n      HttpResponse response = createMock(HttpResponse.class);\n      @SuppressWarnings(\"unchecked\")\n      LoadingCache<Credentials, AuthInfo> cache = createMock(LoadingCache.class);\n      BackoffLimitedRetryHandler backoffHandler = createMock(BackoffLimitedRetryHandler.class);\n\n      expect(command.getCurrentRequest()).andReturn(request);\n\n      cache.invalidateAll();\n      expectLastCall();\n\n      expect(response.getPayload()).andReturn(Payloads.newStringPayload(\"\")).anyTimes();\n      expect(response.getStatusCode()).andReturn(401).atLeastOnce();\n\n      replay(command);\n      replay(response);\n      replay(cache);\n      replay(backoffHandler);\n\n      RetryOnRenew retry = new RetryOnRenew(cache, backoffHandler);\n\n      assertTrue(retry.shouldRetryRequest(command, response));\n\n      verify(command);\n      verify(response);\n      verify(cache);\n   }\n\n   @Test\n   public void test401ShouldRetry4Times() {\n      HttpCommand command = createMock(HttpCommand.class);\n      HttpRequest request = createMock(HttpRequest.class);\n      HttpResponse response = createMock(HttpResponse.class);\n\n      @SuppressWarnings(\"unchecked\")\n      LoadingCache<Credentials, AuthInfo> cache = createMock(LoadingCache.class);\n      BackoffLimitedRetryHandler backoffHandler = createMock(BackoffLimitedRetryHandler.class);\n\n      expect(command.getCurrentRequest()).andReturn(request).anyTimes();\n      expect(request.getHeaders()).andStubReturn(null);\n\n      cache.invalidateAll();\n      expectLastCall().anyTimes();\n\n      expect(response.getPayload()).andReturn(Payloads.newStringPayload(\"\")).anyTimes();\n      expect(response.getStatusCode()).andReturn(401).anyTimes();\n\n      replay(command, request, response, cache);\n\n      RetryOnRenew retry = new RetryOnRenew(cache, backoffHandler);\n\n      for (int i = 0; i < RetryOnRenew.NUM_RETRIES - 1; ++i) {\n         assertTrue(retry.shouldRetryRequest(command, response), \"Expected retry to succeed\");\n      }\n\n      assertFalse(retry.shouldRetryRequest(command, response), \"Expected retry to fail on attempt \" + RetryOnRenew.NUM_RETRIES);\n\n      verify(command, response, cache);\n   }\n\n   @Test\n   public void test408ShouldRetry() {\n      HttpCommand command = createMock(HttpCommand.class);\n      HttpResponse response = createMock(HttpResponse.class);\n      @SuppressWarnings(\"unchecked\")\n      LoadingCache<Credentials, AuthInfo> cache = createMock(LoadingCache.class);\n      BackoffLimitedRetryHandler backoffHandler = createMock(BackoffLimitedRetryHandler.class);\n\n      expect(backoffHandler.shouldRetryRequest(command, response)).andReturn(true).once();\n      expect(response.getStatusCode()).andReturn(408).once();\n\n      replay(command);\n      replay(response);\n      replay(cache);\n      replay(backoffHandler);\n\n      RetryOnRenew retry = new RetryOnRenew(cache, backoffHandler);\n\n      assertTrue(retry.shouldRetryRequest(command, response));\n\n      verify(command);\n      verify(response);\n      verify(cache);\n      verify(backoffHandler);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/auth/suppliers/LocationIdToURIFromAccessForTypeAndVersionTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.auth.suppliers;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.location.Provider;\nimport org.jclouds.openstack.keystone.auth.domain.AuthInfo;\nimport org.jclouds.openstack.keystone.catalog.ServiceEndpoint;\nimport org.jclouds.openstack.keystone.catalog.suppliers.LocationIdToURIFromServiceEndpointsForTypeAndVersion;\nimport org.jclouds.openstack.keystone.v2_0.catalog.V2ServiceCatalog;\nimport org.jclouds.openstack.keystone.v2_0.parse.ParseAccessTest;\nimport org.jclouds.openstack.keystone.v2_0.parse.ParseRackspaceAccessTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Maps;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Provides;\nimport com.google.inject.Scopes;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.assistedinject.FactoryModuleBuilder;\n\n@Test(groups = \"unit\", testName = \"LocationIdToURIFromAccessForTypeAndVersionTest\")\npublic class LocationIdToURIFromAccessForTypeAndVersionTest {\n   private final LocationIdToURIFromServiceEndpointsForTypeAndVersion.Factory factory = Guice.createInjector(\n         new AbstractModule() {\n\n            @Override\n            protected void configure() {\n               bindConstant().annotatedWith(Provider.class).to(\"openstack-keystone\");\n               bind(new TypeLiteral<Supplier<URI>>() {\n               }).annotatedWith(Provider.class).toInstance(Suppliers.ofInstance(URI.create(\"https://identity\")));\n               install(new FactoryModuleBuilder().implement(LocationIdToURIFromServiceEndpointsForTypeAndVersion.class,\n                     LocationIdToURIFromServiceEndpointsForTypeAndVersion.class).build(\n                     LocationIdToURIFromServiceEndpointsForTypeAndVersion.Factory.class));\n               // We test against a 2.0 service catalog but it is OK for the purpose of this test\n               bind(new TypeLiteral<Supplier<List<ServiceEndpoint>>>() {\n               }).to(V2ServiceCatalog.class).in(Scopes.SINGLETON);\n            }\n\n            @Provides\n            @Singleton\n            public Supplier<AuthInfo> provide() {\n               return Suppliers.<AuthInfo> ofInstance(new ParseAccessTest().expected());\n            }\n\n         }).getInstance(LocationIdToURIFromServiceEndpointsForTypeAndVersion.Factory.class);\n\n   public void testRegionUnmatchesOkWhenNoVersionIdSet() {\n      assertEquals(\n            Maps.transformValues(factory.createForApiTypeAndVersion(\"compute\", \"2\").get(),\n                  Suppliers.<URI> supplierFunction()),\n            ImmutableMap.of(\"az-1.region-a.geo-1\",\n                  URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456\"), \"az-2.region-a.geo-1\",\n                  URI.create(\"https://az-2.region-a.geo-1.compute.hpcloudsvc.com/v2/3456\"), \"az-3.region-a.geo-1\",\n                  URI.create(\"https://az-3.region-a.geo-1.compute.hpcloudsvc.com/v2/3456\")));\n   }\n\n   public void testRegionMatches() {\n      assertEquals(\n            Maps.transformValues(factory.createForApiTypeAndVersion(\"compute\", \"2\").get(),\n                  Suppliers.<URI> supplierFunction()),\n            ImmutableMap.of(\"az-1.region-a.geo-1\",\n                  URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456\"), \"az-2.region-a.geo-1\",\n                  URI.create(\"https://az-2.region-a.geo-1.compute.hpcloudsvc.com/v2/3456\"), \"az-3.region-a.geo-1\",\n                  URI.create(\"https://az-3.region-a.geo-1.compute.hpcloudsvc.com/v2/3456\")));\n   }\n\n   private final LocationIdToURIFromServiceEndpointsForTypeAndVersion.Factory raxFactory = Guice.createInjector(\n         new AbstractModule() {\n\n            @Override\n            protected void configure() {\n               bindConstant().annotatedWith(Provider.class).to(\"rackspace\");\n               bind(new TypeLiteral<Supplier<URI>>() {\n               }).annotatedWith(Provider.class).toInstance(Suppliers.ofInstance(URI.create(\"https://identity\")));\n               install(new FactoryModuleBuilder().implement(LocationIdToURIFromServiceEndpointsForTypeAndVersion.class,\n                     LocationIdToURIFromServiceEndpointsForTypeAndVersion.class).build(\n                     LocationIdToURIFromServiceEndpointsForTypeAndVersion.Factory.class));\n               // We test against a 2.0 service catalog but it is OK for the purpose of this test\n               bind(new TypeLiteral<Supplier<List<ServiceEndpoint>>>() {\n               }).to(V2ServiceCatalog.class).in(Scopes.SINGLETON);\n            }\n\n            @Provides\n            @Singleton\n            public Supplier<AuthInfo> provide() {\n               return Suppliers.<AuthInfo> ofInstance(new ParseRackspaceAccessTest().expected());\n            }\n         }).getInstance(LocationIdToURIFromServiceEndpointsForTypeAndVersion.Factory.class);\n\n   @Test(expectedExceptions = NoSuchElementException.class)\n   public void testWhenNotInList() {\n      assertEquals(\n            Maps.transformValues(raxFactory.createForApiTypeAndVersion(\"goo\", \"1.0\").get(),\n                  Suppliers.<URI> supplierFunction()),\n            ImmutableMap.of(\"rackspace\", URI.create(\"https://servers.api.rackspacecloud.com/v1.0/40806637803162\")));\n   }\n\n   public void testProviderWhenNoRegions() {\n      Map<String, URI> withNoRegions = Maps.transformValues(raxFactory.createForApiTypeAndVersion(\"compute\", \"1.0\")\n            .get(), Suppliers.<URI> supplierFunction());\n      assertEquals(withNoRegions,\n            ImmutableMap.of(\"rackspace\", URI.create(\"https://servers.api.rackspacecloud.com/v1.0/40806637803162\")));\n   }\n\n   public void testOkWithNoVersions() {\n      assertEquals(Maps.transformValues(raxFactory.createForApiTypeAndVersion(\"rax:database\", null).get(),\n            Suppliers.<URI> supplierFunction()), ImmutableMap.of(\"DFW\",\n            URI.create(\"https://dfw.databases.api.rackspacecloud.com/v1.0/40806637803162\"), \"ORD\",\n            URI.create(\"https://ord.databases.api.rackspacecloud.com/v1.0/40806637803162\")));\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/auth/suppliers/RegionIdToAdminURIFromAccessForTypeAndVersionTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.auth.suppliers;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.location.Provider;\nimport org.jclouds.openstack.keystone.auth.domain.AuthInfo;\nimport org.jclouds.openstack.keystone.catalog.ServiceEndpoint;\nimport org.jclouds.openstack.keystone.catalog.suppliers.RegionIdToAdminURIFromServiceEndpointsForTypeAndVersion;\nimport org.jclouds.openstack.keystone.catalog.suppliers.RegionIdToAdminURISupplier;\nimport org.jclouds.openstack.keystone.v2_0.catalog.V2ServiceCatalog;\nimport org.jclouds.openstack.keystone.v2_0.parse.ParseAccessTest;\nimport org.jclouds.openstack.keystone.v2_0.parse.ParseRackspaceAccessTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Maps;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Provides;\nimport com.google.inject.Scopes;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.assistedinject.FactoryModuleBuilder;\n\n@Test(groups = \"unit\", testName = \"RegionIdToAdminURIFromAccessForTypeAndVersionTest\")\npublic class RegionIdToAdminURIFromAccessForTypeAndVersionTest {\n   private final RegionIdToAdminURISupplier.Factory factory = Guice.createInjector(new AbstractModule() {\n\n      @Override\n      protected void configure() {\n         bindConstant().annotatedWith(Provider.class).to(\"openstack-keystone\");\n         bind(new TypeLiteral<Supplier<URI>>() {\n         }).annotatedWith(Provider.class).toInstance(Suppliers.ofInstance(URI.create(\"https://identity\")));\n         install(new FactoryModuleBuilder().implement(RegionIdToAdminURISupplier.class,\n                  RegionIdToAdminURIFromServiceEndpointsForTypeAndVersion.class).build(RegionIdToAdminURISupplier.Factory.class));\n         // We test against a 2.0 service catalog but it is OK for the purpose of this test\n         bind(new TypeLiteral<Supplier<List<ServiceEndpoint>>>() {\n         }).to(V2ServiceCatalog.class).in(Scopes.SINGLETON);\n      }\n\n      @Provides\n      @Singleton\n      public Supplier<AuthInfo> provide() {\n         return Suppliers.<AuthInfo> ofInstance(new ParseAccessTest().expected());\n      }\n   }).getInstance(RegionIdToAdminURISupplier.Factory.class);\n\n   public void testRegionMatches() {\n      assertEquals(Maps.transformValues(factory.createForApiTypeAndVersion(\"identity\", \"2.0\").get(), Suppliers\n               .<URI> supplierFunction()), ImmutableMap.of(\"region-a.geo-1\", URI.create(\"https://csnode.jclouds.org:35357/v2.0/\")));\n      Map<String, URI> map = Maps.newLinkedHashMap();\n      map.put(\"region-a.geo-1\", null);\n      map.put(\"region-b.geo-1\", null);\n      map.put(\"region-c.geo-1\", null);\n      assertEquals(Maps.transformValues(factory.createForApiTypeAndVersion(\"compute\", \"2\").get(), Suppliers\n               .<URI> supplierFunction()), map);\n   }\n   \n   private final RegionIdToAdminURISupplier.Factory raxFactory = Guice.createInjector(new AbstractModule() {\n\n      @Override\n      protected void configure() {\n         bindConstant().annotatedWith(Provider.class).to(\"rackspace\");\n         bind(new TypeLiteral<Supplier<URI>>() {\n         }).annotatedWith(Provider.class).toInstance(Suppliers.ofInstance(URI.create(\"https://identity\")));\n         install(new FactoryModuleBuilder().implement(RegionIdToAdminURISupplier.class,\n                  RegionIdToAdminURIFromServiceEndpointsForTypeAndVersion.class).build(RegionIdToAdminURISupplier.Factory.class));\n         // We test against a 2.0 service catalog but it is OK for the purpose of this test\n         bind(new TypeLiteral<Supplier<List<ServiceEndpoint>>>() {\n         }).to(V2ServiceCatalog.class).in(Scopes.SINGLETON);\n      }\n\n      @Provides\n      @Singleton\n      public Supplier<AuthInfo> provide() {\n         return Suppliers.<AuthInfo> ofInstance(new ParseRackspaceAccessTest().expected());\n      }\n   }).getInstance(RegionIdToAdminURISupplier.Factory.class);\n\n   @Test(expectedExceptions = NoSuchElementException.class)\n   public void testWhenNotInList() {\n      assertEquals(Maps.transformValues(raxFactory.createForApiTypeAndVersion(\"goo\", \"1.0\").get(), Suppliers\n               .<URI> supplierFunction()), ImmutableMap.of(\"rackspace\", URI\n               .create(\"https://servers.api.rackspacecloud.com/v1.0/40806637803162\")));\n   }\n   \n   public void testProviderWhenNoRegions() {\n      Map<String, URI> map = Maps.newLinkedHashMap();\n      map.put(\"rackspace\", null);\n      assertEquals(Maps.transformValues(raxFactory.createForApiTypeAndVersion(\"compute\", \"1.0\").get(), Suppliers\n               .<URI> supplierFunction()), map);\n   }\n   \n   public void testOkWithNoVersions() {\n      Map<String, URI> map = Maps.newLinkedHashMap();\n      map.put(\"DFW\", null);\n      map.put(\"ORD\", null);\n      assertEquals(Maps.transformValues(raxFactory.createForApiTypeAndVersion(\"rax:database\", null).get(), Suppliers\n               .<URI> supplierFunction()), map);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/auth/suppliers/RegionIdToURIFromAccessForTypeAndVersionTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.auth.suppliers;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\nimport java.util.List;\nimport java.util.NoSuchElementException;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.location.Provider;\nimport org.jclouds.location.suppliers.RegionIdToURISupplier;\nimport org.jclouds.openstack.keystone.auth.domain.AuthInfo;\nimport org.jclouds.openstack.keystone.catalog.ServiceEndpoint;\nimport org.jclouds.openstack.keystone.catalog.suppliers.RegionIdToURIFromServiceEndpointsForTypeAndVersion;\nimport org.jclouds.openstack.keystone.v2_0.catalog.V2ServiceCatalog;\nimport org.jclouds.openstack.keystone.v2_0.parse.ParseAccessTest;\nimport org.jclouds.openstack.keystone.v2_0.parse.ParseRackspaceAccessTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Maps;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Provides;\nimport com.google.inject.Scopes;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.assistedinject.FactoryModuleBuilder;\n\n@Test(groups = \"unit\", testName = \"RegionIdToURIFromAccessForTypeAndVersionTest\")\npublic class RegionIdToURIFromAccessForTypeAndVersionTest {\n   private final RegionIdToURISupplier.Factory factory = Guice.createInjector(new AbstractModule() {\n\n      @Override\n      protected void configure() {\n         bindConstant().annotatedWith(Provider.class).to(\"openstack-keystone\");\n         bind(new TypeLiteral<Supplier<URI>>() {\n         }).annotatedWith(Provider.class).toInstance(Suppliers.ofInstance(URI.create(\"https://identity\")));\n         install(new FactoryModuleBuilder().implement(RegionIdToURISupplier.class,\n                  RegionIdToURIFromServiceEndpointsForTypeAndVersion.class).build(\n                  RegionIdToURISupplier.Factory.class));\n         // We test against a 2.0 service catalog but it is OK for the purpose of this test\n         bind(new TypeLiteral<Supplier<List<ServiceEndpoint>>>() {\n         }).to(V2ServiceCatalog.class).in(Scopes.SINGLETON);\n      }\n\n      @Provides\n      @Singleton\n      public Supplier<AuthInfo> provide() {\n         return Suppliers.<AuthInfo> ofInstance(new ParseAccessTest().expected());\n      }\n   }).getInstance(RegionIdToURISupplier.Factory.class);\n\n   @Test(expectedExceptions = NoSuchElementException.class)\n   public void testRegionUnmatches() {\n      factory.createForApiTypeAndVersion(\"compute\", \"1.0\").get();\n   }\n   \n   public void testRegionMatches() {\n      assertEquals(Maps.transformValues(factory.createForApiTypeAndVersion(\"compute\", \"2\").get(), Suppliers\n               .<URI> supplierFunction()), ImmutableMap.of(\"az-1.region-a.geo-1\", URI\n               .create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456\"), \"az-2.region-a.geo-1\", URI\n               .create(\"https://az-2.region-a.geo-1.compute.hpcloudsvc.com/v2/3456\"), \"az-3.region-a.geo-1\", URI\n               .create(\"https://az-3.region-a.geo-1.compute.hpcloudsvc.com/v2/3456\")));\n   }\n\n   private final RegionIdToURISupplier.Factory raxFactory = Guice.createInjector(new AbstractModule() {\n\n      @Override\n      protected void configure() {\n         bindConstant().annotatedWith(Provider.class).to(\"rackspace\");\n         bind(new TypeLiteral<Supplier<URI>>() {\n         }).annotatedWith(Provider.class).toInstance(Suppliers.ofInstance(URI.create(\"https://identity\")));\n         install(new FactoryModuleBuilder().implement(RegionIdToURISupplier.class,\n                  RegionIdToURIFromServiceEndpointsForTypeAndVersion.class).build(\n                  RegionIdToURISupplier.Factory.class));\n         // We test against a 2.0 service catalog but it is OK for the purpose of this test\n         bind(new TypeLiteral<Supplier<List<ServiceEndpoint>>>() {\n         }).to(V2ServiceCatalog.class).in(Scopes.SINGLETON);\n      }\n\n      @Provides\n      @Singleton\n      public Supplier<AuthInfo> provide() {\n         return Suppliers.<AuthInfo> ofInstance(new ParseRackspaceAccessTest().expected());\n      }\n   }).getInstance(RegionIdToURISupplier.Factory.class);\n\n   @Test(expectedExceptions = NoSuchElementException.class)\n   public void testWhenNotInList() {\n      assertEquals(Maps.transformValues(raxFactory.createForApiTypeAndVersion(\"goo\", \"1.0\").get(), Suppliers\n               .<URI> supplierFunction()), ImmutableMap.of(\"rackspace\", URI\n               .create(\"https://servers.api.rackspacecloud.com/v1.0/40806637803162\")));\n   }\n\n   public void testProviderWhenNoRegions() {\n      assertEquals(Maps.transformValues(raxFactory.createForApiTypeAndVersion(\"compute\", \"1.0\").get(), Suppliers\n               .<URI> supplierFunction()), ImmutableMap.of(\"rackspace\", URI\n               .create(\"https://servers.api.rackspacecloud.com/v1.0/40806637803162\")));\n   }\n\n   public void testOkWithNoVersions() {\n      assertEquals(Maps.transformValues(raxFactory.createForApiTypeAndVersion(\"rax:database\", null).get(), Suppliers\n               .<URI> supplierFunction()), ImmutableMap.of(\"DFW\", URI\n               .create(\"https://dfw.databases.api.rackspacecloud.com/v1.0/40806637803162\"), \"ORD\", URI\n               .create(\"https://ord.databases.api.rackspacecloud.com/v1.0/40806637803162\")));\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/catalog/functions/AdminURLTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.catalog.functions;\n\nimport static org.jclouds.openstack.keystone.catalog.ServiceEndpoint.Interface.ADMIN;\nimport static org.jclouds.openstack.keystone.catalog.ServiceEndpoint.Interface.PUBLIC;\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\nimport java.util.Collections;\n\nimport org.jclouds.openstack.keystone.catalog.ServiceEndpoint;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"AdminURLTest\")\npublic class AdminURLTest {\n   private final AdminURL fn = new AdminURL();\n\n   public void testAdminURL() {\n      assertEquals(\n            fn.apply(\n                  Collections.singletonList(ServiceEndpoint\n                        .builder()\n                        .type(\"cdn\")\n                        .regionId(\"LON\")\n                        .version(\"1.0\")\n                        .url(URI\n                              .create(\"https://cdn3.clouddrive.com/v1/MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953\"))\n                        .iface(ADMIN).build())).get(),\n            URI.create(\"https://cdn3.clouddrive.com/v1/MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953\"));\n   }\n\n   public void testReturnsNullIfNotAdminURI() {\n      assertEquals(\n            fn.apply(\n                  Collections.singletonList(ServiceEndpoint.builder().type(\"cdn\").regionId(\"LON\").version(\"1.0\")\n                        .url(URI.create(\"https://192.168.1.1\")).iface(PUBLIC).build())).get(), null);\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/catalog/functions/InternalURLTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.catalog.functions;\n\nimport static org.jclouds.openstack.keystone.catalog.ServiceEndpoint.Interface.INTERNAL;\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\nimport java.util.Collections;\n\nimport org.jclouds.openstack.keystone.catalog.ServiceEndpoint;\nimport org.testng.annotations.Test;\n\n/**\n */\n@Test(groups = \"unit\", testName = \"InternalURLTest\")\npublic class InternalURLTest {\n   private final InternalURL fn = new InternalURL();\n\n   public void testInternalURL() {\n      assertEquals(\n            fn.apply(Collections.singletonList(ServiceEndpoint.builder().type(\"cdn\").regionId(\"regionOne\")\n                  .version(\"2.0\")\n                  .url(URI.create(\"https://ericsson.com/v2/1900e98b-7272-4cbd-8e95-0b8c2a9266c0\"))\n                  .iface(INTERNAL).build())).get(),\n            URI.create(\"https://ericsson.com/v2/1900e98b-7272-4cbd-8e95-0b8c2a9266c0\"));\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/catalog/functions/PublicURLOrInternalTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.catalog.functions;\n\nimport static org.jclouds.openstack.keystone.catalog.ServiceEndpoint.Interface.INTERNAL;\nimport static org.jclouds.openstack.keystone.catalog.ServiceEndpoint.Interface.PUBLIC;\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\nimport java.util.Collections;\n\nimport org.jclouds.openstack.keystone.catalog.ServiceEndpoint;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"PublicURLOrInternalTest\")\npublic class PublicURLOrInternalTest {\n   private final PublicURLOrInternal fn = new PublicURLOrInternal();\n\n   public void testPublicURLNotNullReturnsPublicURL() {\n      assertEquals(\n            fn.apply(\n                  Collections.singletonList(ServiceEndpoint\n                        .builder()\n                        .type(\"cdn\")\n                        .regionId(\"LON\")\n                        .version(\"1.0\")\n                        .url(URI\n                              .create(\"https://cdn3.clouddrive.com/v1/MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953\"))\n                        .iface(PUBLIC).build())).get(),\n            URI.create(\"https://cdn3.clouddrive.com/v1/MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953\"));\n   }\n\n   public void testPublicURLNullReturnsInternalURL() {\n      assertEquals(\n            fn.apply(\n                  Collections.singletonList(ServiceEndpoint.builder().type(\"cdn\").regionId(\"LON\").version(\"1.0\")\n                        .url(URI.create(\"https://192.168.1.1\")).iface(INTERNAL).build())).get(),\n            URI.create(\"https://192.168.1.1\"));\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/catalog/functions/ReturnRegionOrProviderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.catalog.functions;\n\nimport static org.jclouds.openstack.keystone.catalog.ServiceEndpoint.Interface.PUBLIC;\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\n\nimport org.jclouds.openstack.keystone.catalog.ServiceEndpoint;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ReturnRegionOrProviderTest\")\npublic class ReturnRegionOrProviderTest {\n   private final ReturnRegionOrProvider fn = new ReturnRegionOrProvider(\"openstack-keystone\");\n\n   public void testRegionNotNullReturnsRegion() {\n      assertEquals(\n            fn.apply(ServiceEndpoint.builder().type(\"cdn\").regionId(\"LON\").version(\"1.0\")\n                  .url(URI.create(\"https://cdn3.clouddrive.com/v1/MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953\"))\n                  .iface(PUBLIC).build()), \"LON\");\n   }\n\n   public void testRegionNullReturnsProvider() {\n      assertEquals(\n            fn.apply(ServiceEndpoint.builder().type(\"cdn\").version(\"1.0\")\n                  .url(URI.create(\"https://cdn3.clouddrive.com/v1/MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953\"))\n                  .iface(PUBLIC).build()), \"openstack-keystone\");\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/KeystoneApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.keystone.v2_0.domain.ApiMetadata;\nimport org.jclouds.openstack.keystone.v2_0.internal.BaseKeystoneRestApiExpectTest;\nimport org.jclouds.openstack.keystone.v2_0.parse.ParseRackspaceApiMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(testName = \"KeystoneApiExpectTest\")\npublic class KeystoneApiExpectTest extends BaseKeystoneRestApiExpectTest<KeystoneApi> {\n\n   public void testGetApiMetaData() {\n      KeystoneApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess,\n            HttpRequest.builder().method(\"GET\").endpoint(endpoint + \"/v2.0/\").\n            addHeader(\"Accept\", APPLICATION_JSON).build(),\n            HttpResponse.builder().statusCode(200).\n                  payload(payloadFromResourceWithContentType(\"/raxVersion.json\", APPLICATION_JSON)).build());\n      ApiMetadata metadata = api.getApiMetadata();\n\n      assertEquals(metadata, new ParseRackspaceApiMetadataTest().expected());\n   }\n\n}\n\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/KeystoneApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0;\n\nimport static org.testng.Assert.assertNotNull;\n\nimport org.jclouds.openstack.keystone.v2_0.domain.ApiMetadata;\nimport org.jclouds.openstack.keystone.v2_0.internal.BaseKeystoneApiLiveTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests KeystoneApi\n */\n@Test(groups = \"live\", testName = \"KeystoneApiLiveTest\")\npublic class KeystoneApiLiveTest extends BaseKeystoneApiLiveTest {\n\n   public void testGetApiMetaData() {\n      ApiMetadata result = api.getApiMetadata();\n      assertNotNull(result);\n      assertNotNull(result.getId());\n      assertNotNull(result.getStatus());\n      assertNotNull(result.getUpdated());\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/extensions/RoleAdminApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.extensions;\n\nimport static org.jclouds.util.Predicates2.retry;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\n\nimport org.jclouds.openstack.keystone.v2_0.domain.Role;\nimport org.jclouds.openstack.keystone.v2_0.internal.BaseKeystoneApiLiveTest;\nimport org.testng.SkipException;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\n\n/**\n * Tests behavior of RoleAdminApi\n */\n@Test(groups = \"live\", testName = \"RoleAdminApiLiveTest\", singleThreaded = true)\npublic class RoleAdminApiLiveTest extends BaseKeystoneApiLiveTest {\n\n   private Optional<? extends RoleAdminApi> roleAdminOption;\n\n   private Role testRole;\n\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   @Override\n   public void setup() {\n      super.setup();\n      roleAdminOption = api.getRoleAdminApi();\n      if (!roleAdminOption.isPresent()) {\n         throw new SkipException(\"The tests are skipped since OS-KSADM extension is not exposed through the Keystone API\");\n      }\n   }\n\n   @AfterClass(groups = { \"integration\", \"live\" })\n   @Override\n   protected void tearDown() {\n      if (testRole != null) {\n         final String roleId = testRole.getId();\n         assertTrue(roleAdminOption.get().delete(roleId));\n         assertTrue(retry(new Predicate<RoleAdminApi>() {\n            public boolean apply(RoleAdminApi roleApi) {\n               return roleApi.get(roleId) == null;\n            }\n         }, 5 * 1000L).apply(roleAdminOption.get()));\n      }\n      super.tearDown();\n   }\n\n   public void testCreateRole() {\n      testRole = roleAdminOption.get().create(\"jclouds-test-role\");\n      assertTrue(retry(new Predicate<RoleAdminApi>() {\n         public boolean apply(RoleAdminApi roleApi) {\n            return roleApi.get(testRole.getId()) != null;\n         }\n      }, 180 * 1000L).apply(roleAdminOption.get()));\n\n      assertEquals(roleAdminOption.get().get(testRole.getId()).getName(), \"jclouds-test-role\");\n   }\n\n   public void testListRoles() {\n      RoleAdminApi roleApi = roleAdminOption.get();\n      Set<? extends Role> roles = roleApi.list().toSet();\n      assertNotNull(roles);\n      assertFalse(roles.isEmpty());\n      for (Role role : roles) {\n         Role aRole = roleApi.get(role.getId());\n         assertEquals(aRole, role);\n      }\n\n   }\n\n   @Test(dependsOnMethods = { \"testCreateRole\" })\n   public void testGetRole() {\n\n      Role testGetRole = roleAdminOption.get().get(testRole.getId());\n      assertNotNull(testGetRole);\n      assertEquals(testGetRole.getName(), \"jclouds-test-role\");\n\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/extensions/RoleAdminApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.extensions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\nimport okhttp3.mockwebserver.RecordedRequest;\n\nimport org.jclouds.openstack.keystone.v2_0.KeystoneApi;\nimport org.jclouds.openstack.keystone.v2_0.domain.Role;\nimport org.jclouds.openstack.v2_0.internal.BaseOpenStackMockTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableSet;\n\n\n/**\n * Tests RoleApi Guice wiring and parsing\n */\n@Test(groups = \"unit\", testName = \"RoleAdminApiMockTest\")\npublic class RoleAdminApiMockTest extends BaseOpenStackMockTest<KeystoneApi> {\n\n   Set<Role> expectedRoles = ImmutableSet.of(\n         Role.builder().id(\"22529316b2384072b2e8946af5e8cfb6\").name(\"admin\").build(),\n         Role.builder().id(\"9fe2ff9ee4384b1894a90878d3e92bab\").name(\"_member_\")\n               .description(\"Default role for project membership\").build());\n\n   public void listRoles() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access_version_uids.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/admin_extensions.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(\n            stringFromResource(\"/role_list_response.json\"))));\n\n      try {\n         KeystoneApi keystoneApi = api(server.url(\"/\").toString(), \"openstack-keystone\");\n         RoleAdminApi roleAdminApi = keystoneApi.getRoleAdminApi().get();\n         FluentIterable<? extends Role> roles = roleAdminApi.list();\n\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertExtensions(server);\n         RecordedRequest updateRoleRequest = server.takeRequest();\n         assertEquals(updateRoleRequest.getRequestLine(), \"GET /OS-KSADM/roles HTTP/1.1\");\n\n         assertEquals(roles.size(), 2);\n         assertEquals(roles.toSet(), expectedRoles);\n\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void createRole() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access_version_uids.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/admin_extensions.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(201).setBody(\n            stringFromResource(\"/role_create_response.json\"))));\n\n      try {\n         KeystoneApi keystoneApi = api(server.url(\"/\").toString(), \"openstack-keystone\");\n         RoleAdminApi roleAdminApi = keystoneApi.getRoleAdminApi().get();\n         Role testRole = roleAdminApi.create(\"jclouds-role\");\n\n         assertNotNull(testRole);\n         assertEquals(testRole.getId(), \"r1000\");\n\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertExtensions(server);\n         RecordedRequest createRoleRequest = server.takeRequest();\n         assertEquals(createRoleRequest.getRequestLine(), \"POST /OS-KSADM/roles HTTP/1.1\");\n         assertEquals(createRoleRequest.getBody().readUtf8(), \"{\\\"role\\\":{\\\"name\\\":\\\"jclouds-role\\\"}}\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void getRole() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access_version_uids.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/admin_extensions.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(\n            stringFromResource(\"/role_create_response.json\"))));\n\n      try {\n         KeystoneApi keystoneApi = api(server.url(\"/\").toString(), \"openstack-keystone\");\n         RoleAdminApi roleAdminApi = keystoneApi.getRoleAdminApi().get();\n         Role role = roleAdminApi.get(\"r1000\");\n\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertExtensions(server);\n         RecordedRequest updateRoleRequest = server.takeRequest();\n         assertEquals(updateRoleRequest.getRequestLine(), \"GET /OS-KSADM/roles/r1000 HTTP/1.1\");\n\n         /*\n          * Check response\n          */\n         assertEquals(role.getId(), \"r1000\");\n         assertEquals(role.getName(), \"jclouds-role\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void deleteRole() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access_version_uids.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/admin_extensions.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(204)));\n\n      try {\n         KeystoneApi keystoneApi = api(server.url(\"/\").toString(), \"openstack-keystone\");\n         RoleAdminApi roleAdminApi = keystoneApi.getRoleAdminApi().get();\n         boolean success = roleAdminApi.delete(\"r1000\");\n\n         assertTrue(success);\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertExtensions(server);\n         RecordedRequest updateRoleRequest = server.takeRequest();\n         assertEquals(updateRoleRequest.getRequestLine(), \"DELETE /OS-KSADM/roles/r1000 HTTP/1.1\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/extensions/ServiceAdminApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.extensions;\n\nimport static org.jclouds.util.Predicates2.retry;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\n\nimport org.jclouds.openstack.keystone.v2_0.domain.Service;\nimport org.jclouds.openstack.keystone.v2_0.internal.BaseKeystoneApiLiveTest;\nimport org.testng.SkipException;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\n\n/**\n * Tests behavior of ServiceAdminApi\n */\n@Test(groups = \"live\", testName = \"ServiceAdminApiLiveTest\", singleThreaded = true)\npublic class ServiceAdminApiLiveTest extends BaseKeystoneApiLiveTest {\n\n   private Optional<? extends ServiceAdminApi> serviceAdminOption;\n\n   private Service testService;\n\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   @Override\n   public void setup() {\n      super.setup();\n      serviceAdminOption = api.getServiceAdminApi();\n      if (!serviceAdminOption.isPresent()) {\n         throw new SkipException(\"The tests are skipped since OS-KSADM extension is not exposed through the Keystone API\");\n      }\n   }\n\n   @AfterClass(groups = { \"integration\", \"live\" })\n   @Override\n   protected void tearDown() {\n      if (testService != null) {\n         final String serviceId = testService.getId();\n         assertTrue(serviceAdminOption.get().delete(serviceId));\n         assertTrue(retry(new Predicate<ServiceAdminApi>() {\n            public boolean apply(ServiceAdminApi serviceApi) {\n               return serviceApi.get(serviceId) == null;\n            }\n         }, 5 * 1000L).apply(serviceAdminOption.get()));\n      }\n      super.tearDown();\n   }\n\n   public void testListServices() {\n      ServiceAdminApi serviceApi = serviceAdminOption.get();\n      Set<? extends Service> services = serviceApi.list().concat().toSet();\n      assertNotNull(services);\n      assertFalse(services.isEmpty());\n      for (Service service : services) {\n         Service aService = serviceApi.get(service.getId());\n         assertEquals(aService, service);\n      }\n\n   }\n\n   @Test\n   public void testCreateService() {\n      testService = serviceAdminOption.get().create(\"jclouds-test-service\", \"jclouds-service-type\",\n            \"jclouds-service-description\");\n      assertTrue(retry(new Predicate<ServiceAdminApi>() {\n         public boolean apply(ServiceAdminApi serviceApi) {\n            return serviceApi.get(testService.getId()) != null;\n         }\n      }, 180 * 1000L).apply(serviceAdminOption.get()));\n\n      assertEquals(serviceAdminOption.get().get(testService.getId()).getName(), \"jclouds-test-service\");\n   }\n\n   @Test(dependsOnMethods = { \"testCreateService\" })\n   public void testGetService() {\n      Service testGetService = serviceAdminOption.get().get(testService.getId());\n      assertNotNull(testGetService);\n      assertEquals(testGetService.getName(), \"jclouds-test-service\");\n\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/extensions/ServiceAdminApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.extensions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.Set;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\nimport okhttp3.mockwebserver.RecordedRequest;\n\nimport org.jclouds.collect.PagedIterable;\nimport org.jclouds.openstack.keystone.v2_0.KeystoneApi;\nimport org.jclouds.openstack.keystone.v2_0.domain.Service;\nimport org.jclouds.openstack.v2_0.domain.PaginatedCollection;\nimport org.jclouds.openstack.v2_0.internal.BaseOpenStackMockTest;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n\n/**\n * Tests ServiceApi Guice wiring and parsing\n */\n@Test(groups = \"unit\", testName = \"ServiceAdminApiMockTest\")\npublic class ServiceAdminApiMockTest extends BaseOpenStackMockTest<KeystoneApi> {\n\n   Set<Service> expectedServices = ImmutableSet.of(\n         Service.builder().name(\"neutron\").type(\"network\").id(\"150a35a1e24547fdb4122b7fc90929b0\")\n               .description(\"Network Service\").build(),\n         Service.builder().name(\"cinder\").type(\"volume\").id(\"313b229fcede4a148f5bd11199264f8e\")\n               .description(\"OpenStack Volume Service\").build());\n\n   public void listServices() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access_version_uids.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/admin_extensions.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(\n            stringFromResource(\"/service_list_response.json\"))));\n\n      try {\n         KeystoneApi keystoneApi = api(server.url(\"/\").toString(), \"openstack-keystone\");\n         ServiceAdminApi serviceAdminApi = keystoneApi.getServiceAdminApi().get();\n         PagedIterable<? extends Service> services = serviceAdminApi.list();\n\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertExtensions(server);\n         RecordedRequest updateServiceRequest = server.takeRequest();\n         assertEquals(updateServiceRequest.getRequestLine(), \"GET /OS-KSADM/services HTTP/1.1\");\n\n         assertEquals(services.concat().size(), 2);\n         assertEquals(services.concat().toSet(), expectedServices);\n\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void listServicesPage() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access_version_uids.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/admin_extensions.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(\n            stringFromResource(\"/service_list_response.json\"))));\n\n      try {\n         KeystoneApi keystoneApi = api(server.url(\"/\").toString(), \"openstack-keystone\");\n         ServiceAdminApi serviceAdminApi = keystoneApi.getServiceAdminApi().get();\n         PaginatedCollection<? extends Service> services = serviceAdminApi.list(new PaginationOptions());\n\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertExtensions(server);\n         RecordedRequest updateServiceRequest = server.takeRequest();\n         assertEquals(updateServiceRequest.getRequestLine(), \"GET /OS-KSADM/services HTTP/1.1\");\n\n         assertEquals(services.size(), 2);\n         assertEquals(services.toSet(), expectedServices);\n\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void createService() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access_version_uids.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/admin_extensions.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(201).setBody(\n            stringFromResource(\"/service_create_response.json\"))));\n\n      try {\n         KeystoneApi keystoneApi = api(server.url(\"/\").toString(), \"openstack-keystone\");\n         ServiceAdminApi serviceAdminApi = keystoneApi.getServiceAdminApi().get();\n         Service testService = serviceAdminApi.create(\"jclouds-service-test\", \"jclouds-service-type\",\n               \"jclouds-service-description\");\n\n         assertNotNull(testService);\n         assertEquals(testService.getId(), \"s1000\");\n\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertExtensions(server);\n         RecordedRequest createServiceRequest = server.takeRequest();\n         assertEquals(createServiceRequest.getRequestLine(), \"POST /OS-KSADM/services HTTP/1.1\");\n         String bodyRequest = createServiceRequest.getBody().readUtf8();\n         assertEquals(\n               bodyRequest,\n               \"{\\\"OS-KSADM:service\\\":{\\\"name\\\":\\\"jclouds-service-test\\\",\\\"type\\\":\\\"jclouds-service-type\\\",\\\"description\\\":\\\"jclouds-service-description\\\"}}\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void getService() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access_version_uids.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/admin_extensions.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(\n            stringFromResource(\"/service_create_response.json\"))));\n\n      try {\n         KeystoneApi keystoneApi = api(server.url(\"/\").toString(), \"openstack-keystone\");\n         ServiceAdminApi serviceAdminApi = keystoneApi.getServiceAdminApi().get();\n         Service service = serviceAdminApi.get(\"s1000\");\n\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertExtensions(server);\n         RecordedRequest updateServiceRequest = server.takeRequest();\n         assertEquals(updateServiceRequest.getRequestLine(), \"GET /OS-KSADM/services/s1000 HTTP/1.1\");\n\n         /*\n          * Check response\n          */\n         assertEquals(service.getId(), \"s1000\");\n         assertEquals(service.getName(), \"jclouds-service-test\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void deleteService() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access_version_uids.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/admin_extensions.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(204)));\n\n      try {\n         KeystoneApi keystoneApi = api(server.url(\"/\").toString(), \"openstack-keystone\");\n         ServiceAdminApi serviceAdminApi = keystoneApi.getServiceAdminApi().get();\n         serviceAdminApi.delete(\"s1000\");\n\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertExtensions(server);\n         RecordedRequest updateServiceRequest = server.takeRequest();\n         assertEquals(updateServiceRequest.getRequestLine(), \"DELETE /OS-KSADM/services/s1000 HTTP/1.1\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/extensions/TenantAdminApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.extensions;\n\nimport static org.jclouds.util.Predicates2.retry;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.openstack.keystone.v2_0.domain.Tenant;\nimport org.jclouds.openstack.keystone.v2_0.features.TenantApi;\nimport org.jclouds.openstack.keystone.v2_0.internal.BaseKeystoneApiLiveTest;\nimport org.jclouds.openstack.keystone.v2_0.options.CreateTenantOptions;\nimport org.jclouds.openstack.keystone.v2_0.options.UpdateTenantOptions;\nimport org.testng.SkipException;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\n\n/**\n * Tests behavior of TenantAdminApi\n */\n@Test(groups = \"live\", testName = \"TenantAdminApiLiveTest\", singleThreaded = true)\npublic class TenantAdminApiLiveTest extends BaseKeystoneApiLiveTest {\n\n   private Optional<? extends TenantAdminApi> tenantAdminOption;\n   private Optional<? extends TenantApi> tenantApi;\n\n   private Tenant testTenant;\n\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   @Override\n   public void setup() {\n      super.setup();\n      tenantAdminOption = api.getTenantAdminApi();\n      if (!tenantAdminOption.isPresent()) {\n         throw new SkipException(\n               \"The tests are skipped since OS-KSADM extension is not exposed through the Keystone API\");\n      }\n      tenantApi = api.getTenantApi();\n   }\n\n   @AfterClass(groups = { \"integration\", \"live\" })\n   @Override\n   protected void tearDown() {\n      if (testTenant != null) {\n         final String tenantId = testTenant.getId();\n         assertTrue(tenantAdminOption.get().delete(tenantId));\n         assertTrue(retry(new Predicate<TenantApi>() {\n            public boolean apply(TenantApi tenantApi) {\n               return tenantApi.get(tenantId) == null;\n            }\n         }, 5 * 1000L).apply(tenantApi.get()));\n      }\n      super.tearDown();\n   }\n\n   public void testCreateTenant() {\n      testTenant = tenantAdminOption.get().create(\"jclouds-test-tenant\",\n            CreateTenantOptions.Builder.enabled(true).description(\"jclouds-test-description\"));\n      assertTrue(retry(new Predicate<TenantApi>() {\n         public boolean apply(TenantApi tenantApi) {\n            return tenantApi.get(testTenant.getId()) != null;\n         }\n      }, 180 * 1000L).apply(tenantApi.get()));\n\n      assertEquals(tenantApi.get().get(testTenant.getId()).getName(), \"jclouds-test-tenant\");\n      assertEquals(tenantApi.get().get(testTenant.getId()).getDescription(), \"jclouds-test-description\");\n      assertEquals(tenantApi.get().get(testTenant.getId()).isEnabled(), true);\n   }\n\n   public void testUpdateTenant() {\n      testTenant = tenantAdminOption.get().update(\n            testTenant.getId(),\n            UpdateTenantOptions.Builder.description(\"jclouds-test-description-modified\").enabled(false)\n                  .name(\"jclouds-test-tenant-modified\"));\n\n      assertEquals(tenantApi.get().get(testTenant.getId()).getName(), \"jclouds-test-tenant-modified\");\n      assertEquals(tenantApi.get().get(testTenant.getId()).getDescription(), \"jclouds-test-description-modified\");\n      assertEquals(tenantApi.get().get(testTenant.getId()).isEnabled(), false);\n\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/extensions/TenantAdminApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.extensions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\nimport okhttp3.mockwebserver.RecordedRequest;\n\nimport org.jclouds.openstack.keystone.v2_0.KeystoneApi;\nimport org.jclouds.openstack.keystone.v2_0.domain.Tenant;\nimport org.jclouds.openstack.keystone.v2_0.options.CreateTenantOptions;\nimport org.jclouds.openstack.keystone.v2_0.options.UpdateTenantOptions;\nimport org.jclouds.openstack.v2_0.internal.BaseOpenStackMockTest;\nimport org.testng.annotations.Test;\n\n\n/**\n * Tests TenantApi Guice wiring and parsing\n */\n@Test(groups = \"unit\", testName = \"TenantAdminApiMockTest\")\npublic class TenantAdminApiMockTest extends BaseOpenStackMockTest<KeystoneApi> {\n\n   public void createTenant() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access_version_uids.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/admin_extensions.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(201).setBody(\n            stringFromResource(\"/tenant_create_response.json\"))));\n\n      try {\n         KeystoneApi keystoneApi = api(server.url(\"/\").toString(), \"openstack-keystone\");\n         TenantAdminApi tenantAdminApi = keystoneApi.getTenantAdminApi().get();\n         CreateTenantOptions createTenantOptions = CreateTenantOptions.Builder.description(\"jclouds-description\")\n               .enabled(true);\n         Tenant testTenant = tenantAdminApi.create(\"jclouds-tenant\", createTenantOptions);\n\n         assertNotNull(testTenant);\n         assertEquals(testTenant.getId(), \"t1000\");\n\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertExtensions(server);\n         RecordedRequest createTenantRequest = server.takeRequest();\n         assertEquals(createTenantRequest.getRequestLine(), \"POST /tenants HTTP/1.1\");\n         assertEquals(createTenantRequest.getBody().readUtf8(),\n               \"{\\\"tenant\\\":{\\\"name\\\":\\\"jclouds-tenant\\\",\\\"description\\\":\\\"jclouds-description\\\",\\\"enabled\\\":true}}\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void updateTenant() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access_version_uids.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/admin_extensions.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(\n            stringFromResource(\"/tenant_update_response.json\"))));\n\n      try {\n         KeystoneApi keystoneApi = api(server.url(\"/\").toString(), \"openstack-keystone\");\n         TenantAdminApi tenantAdminApi = keystoneApi.getTenantAdminApi().get();\n         UpdateTenantOptions updateTenantOptions = UpdateTenantOptions.Builder\n               .description(\"jclouds-description-modified\").enabled(false).name(\"jclouds-tenant-modified\");\n         Tenant updatedTenant = tenantAdminApi.update(\"t1000\", updateTenantOptions);\n\n         assertNotNull(updatedTenant);\n         assertEquals(updatedTenant.getId(), \"t1000\");\n\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertExtensions(server);\n         RecordedRequest updateTenantRequest = server.takeRequest();\n         assertEquals(updateTenantRequest.getRequestLine(), \"PUT /tenants/t1000 HTTP/1.1\");\n         assertEquals(\n               updateTenantRequest.getBody().readUtf8(),\n               \"{\\\"tenant\\\":{\\\"name\\\":\\\"jclouds-tenant-modified\\\",\\\"description\\\":\\\"jclouds-description-modified\\\",\\\"enabled\\\":false}}\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void deleteTenant() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access_version_uids.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/admin_extensions.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(204)));\n\n      try {\n         KeystoneApi keystoneApi = api(server.url(\"/\").toString(), \"openstack-keystone\");\n         TenantAdminApi tenantAdminApi = keystoneApi.getTenantAdminApi().get();\n         tenantAdminApi.delete(\"t1000\");\n\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertExtensions(server);\n         RecordedRequest updateTenantRequest = server.takeRequest();\n         assertEquals(updateTenantRequest.getRequestLine(), \"DELETE /tenants/t1000 HTTP/1.1\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void addRoleOnTenant() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access_version_uids.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/admin_extensions.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(201)));\n\n      try {\n         KeystoneApi keystoneApi = api(server.url(\"/\").toString(), \"openstack-keystone\");\n         TenantAdminApi tenantAdminApi = keystoneApi.getTenantAdminApi().get();\n         tenantAdminApi.addRoleOnTenant(\"u1000\", \"t1000\", \"r1000\");\n\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertExtensions(server);\n         RecordedRequest updateTenantRequest = server.takeRequest();\n         assertEquals(updateTenantRequest.getRequestLine(),\n               \"PUT /tenants/u1000/users/t1000/roles/OS-KSADM/r1000 HTTP/1.1\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void deleteRoleOnTenant() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access_version_uids.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/admin_extensions.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(204)));\n\n      try {\n         KeystoneApi keystoneApi = api(server.url(\"/\").toString(), \"openstack-keystone\");\n         TenantAdminApi tenantAdminApi = keystoneApi.getTenantAdminApi().get();\n         tenantAdminApi.deleteRoleOnTenant(\"t1000\", \"u1000\", \"r1000\");\n\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertExtensions(server);\n         RecordedRequest updateTenantRequest = server.takeRequest();\n         assertEquals(updateTenantRequest.getRequestLine(),\n               \"DELETE /tenants/t1000/users/u1000/roles/OS-KSADM/r1000 HTTP/1.1\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/extensions/UserAdminApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.extensions;\n\nimport static org.jclouds.util.Predicates2.retry;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.openstack.keystone.v2_0.domain.User;\nimport org.jclouds.openstack.keystone.v2_0.features.UserApi;\nimport org.jclouds.openstack.keystone.v2_0.internal.BaseKeystoneApiLiveTest;\nimport org.jclouds.openstack.keystone.v2_0.options.CreateUserOptions;\nimport org.jclouds.openstack.keystone.v2_0.options.UpdateUserOptions;\nimport org.testng.SkipException;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\n\n/**\n * Tests behavior of UserAdminApi\n */\n@Test(groups = \"live\", testName = \"UserAdminApiLiveTest\", singleThreaded = true)\npublic class UserAdminApiLiveTest extends BaseKeystoneApiLiveTest {\n\n   private Optional<? extends UserAdminApi> userAdminOption;\n   private Optional<? extends UserApi> userApi;\n\n   private User testUser;\n\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   @Override\n   public void setup() {\n      super.setup();\n      userAdminOption = api.getUserAdminApi();\n      if (!userAdminOption.isPresent()) {\n         throw new SkipException(\"The tests are skipped since OS-KSADM extension is not exposed through the Keystone API\");\n      }\n      userApi = api.getUserApi();\n   }\n\n   @AfterClass(groups = { \"integration\", \"live\" })\n   @Override\n   protected void tearDown() {\n      if (testUser != null) {\n         final String userId = testUser.getId();\n         assertTrue(userAdminOption.get().delete(userId));\n         assertTrue(retry(new Predicate<UserApi>() {\n            public boolean apply(UserApi userApi) {\n               return userApi.get(userId) == null;\n            }\n         }, 5 * 1000L).apply(userApi.get()));\n      }\n      super.tearDown();\n   }\n\n   @Test\n   public void testCreateUser() {\n      testUser = userAdminOption.get().create(\"jclouds-test-user\", \"jclouds-test-password\",\n            CreateUserOptions.Builder.email(\"jclouds-test@jclouds.org\").enabled(true));\n      assertTrue(retry(new Predicate<UserApi>() {\n         public boolean apply(UserApi userApi) {\n            return userApi.get(testUser.getId()) != null;\n         }\n      }, 180 * 1000L).apply(userApi.get()));\n\n      assertEquals(userApi.get().get(testUser.getId()).getName(), \"jclouds-test-user\");\n      assertEquals(userApi.get().get(testUser.getId()).getEmail(), \"jclouds-test@jclouds.org\");\n      assertEquals(userApi.get().get(testUser.getId()).isEnabled(), true);\n   }\n\n   @Test(dependsOnMethods = { \"testCreateUser\" })\n   public void testUpdateUser() {\n      testUser = userAdminOption.get().update(\n            testUser.getId(),\n            UpdateUserOptions.Builder.email(\"jclouds-test.modified@jclouds.org\").enabled(false)\n                  .name(\"jclouds-test-user-modified\").password(\"jclouds-test-password-modified\"));\n\n      assertEquals(userApi.get().get(testUser.getId()).getName(), \"jclouds-test-user-modified\");\n      assertEquals(userApi.get().get(testUser.getId()).getEmail(), \"jclouds-test.modified@jclouds.org\");\n      assertEquals(userApi.get().get(testUser.getId()).isEnabled(), false);\n\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/extensions/UserAdminApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.extensions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\nimport okhttp3.mockwebserver.RecordedRequest;\n\nimport org.jclouds.openstack.keystone.v2_0.KeystoneApi;\nimport org.jclouds.openstack.keystone.v2_0.domain.User;\nimport org.jclouds.openstack.keystone.v2_0.options.CreateUserOptions;\nimport org.jclouds.openstack.keystone.v2_0.options.UpdateUserOptions;\nimport org.jclouds.openstack.v2_0.internal.BaseOpenStackMockTest;\nimport org.testng.annotations.Test;\n\n\n/**\n * Tests UserApi Guice wiring and parsing\n */\n@Test(groups = \"unit\", testName = \"UserAdminApiMockTest\")\npublic class UserAdminApiMockTest extends BaseOpenStackMockTest<KeystoneApi> {\n\n   public void createUser() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access_version_uids.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/admin_extensions.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(201).setBody(\n            stringFromResource(\"/user_create_response.json\"))));\n\n      try {\n         KeystoneApi keystoneApi = api(server.url(\"/\").toString(), \"openstack-keystone\");\n         UserAdminApi userAdminApi = keystoneApi.getUserAdminApi().get();\n         CreateUserOptions createUserOptions = CreateUserOptions.Builder.email(\"john.smith@example.org\").enabled(true)\n               .tenant(\"12345\");\n         User testUser = userAdminApi.create(\"jqsmith\", \"jclouds-password\", createUserOptions);\n\n         assertNotNull(testUser);\n         assertEquals(testUser.getId(), \"u1000\");\n\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertExtensions(server);\n         RecordedRequest createUserRequest = server.takeRequest();\n         assertEquals(createUserRequest.getRequestLine(), \"POST /users HTTP/1.1\");\n         assertEquals(\n               createUserRequest.getBody().readUtf8(),\n               \"{\\\"user\\\":{\\\"name\\\":\\\"jqsmith\\\",\\\"tenantId\\\":\\\"12345\\\",\\\"password\\\":\\\"jclouds-password\\\",\\\"email\\\":\\\"john.smith@example.org\\\",\\\"enabled\\\":true}}\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void updateUser() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access_version_uids.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/admin_extensions.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(\n            stringFromResource(\"/user_update_response.json\"))));\n\n      try {\n         KeystoneApi keystoneApi = api(server.url(\"/\").toString(), \"openstack-keystone\");\n         UserAdminApi userAdminApi = keystoneApi.getUserAdminApi().get();\n         UpdateUserOptions updateUserOptions = UpdateUserOptions.Builder.email(\"john.smith.renamed@example.org\")\n               .enabled(false).name(\"jqsmith-renamed\").password(\"jclouds-password\");\n         User updatedUser = userAdminApi.update(\"u1000\", updateUserOptions);\n\n         assertNotNull(updatedUser);\n         assertEquals(updatedUser.getId(), \"u1000\");\n\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertExtensions(server);\n         RecordedRequest updateUserRequest = server.takeRequest();\n         assertEquals(updateUserRequest.getRequestLine(), \"PUT /users/u1000 HTTP/1.1\");\n         assertEquals(\n               updateUserRequest.getBody().readUtf8(),\n               \"{\\\"user\\\":{\\\"name\\\":\\\"jqsmith-renamed\\\",\\\"email\\\":\\\"john.smith.renamed@example.org\\\",\\\"password\\\":\\\"jclouds-password\\\",\\\"enabled\\\":false}}\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void deleteUser() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access_version_uids.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/admin_extensions.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(204)));\n\n      try {\n         KeystoneApi keystoneApi = api(server.url(\"/\").toString(), \"openstack-keystone\");\n         UserAdminApi userAdminApi = keystoneApi.getUserAdminApi().get();\n         userAdminApi.delete(\"u1000\");\n\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertExtensions(server);\n         RecordedRequest updateUserRequest = server.takeRequest();\n         assertEquals(updateUserRequest.getRequestLine(), \"DELETE /users/u1000 HTTP/1.1\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/features/ServiceApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.Set;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.keystone.v2_0.KeystoneApi;\nimport org.jclouds.openstack.keystone.v2_0.domain.Tenant;\nimport org.jclouds.openstack.keystone.v2_0.internal.BaseKeystoneRestApiExpectTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests parsing and Guice wiring of ServiceApi\n */\n@Test(testName = \"ServiceApiExpectTest\")\npublic class ServiceApiExpectTest extends BaseKeystoneRestApiExpectTest<KeystoneApi> {\n\n   public void testListTenants() {\n      ServiceApi api = requestsSendResponses(\n               keystoneAuthWithUsernameAndPasswordAndTenantName,\n               responseWithKeystoneAccess,\n               authenticatedGET().endpoint(endpoint + \"/v2.0/tenants\").build(),\n               HttpResponse.builder().statusCode(200)\n                        .payload(payloadFromResourceWithContentType(\"/tenant_list.json\", APPLICATION_JSON)).build())\n               .getServiceApi();\n      Set<? extends Tenant> tenants = api.listTenants();\n      assertNotNull(tenants);\n      assertFalse(tenants.isEmpty());\n\n      Set<Tenant> expected = ImmutableSet.of(Tenant.builder().name(\"demo\").id(\"05d1dc7af71646deba64cfc17b81bec0\")\n               .enabled(true).build(), Tenant.builder().name(\"admin\").id(\"7aa2e17ec29f44d193c48feaba0852cc\")\n               .enabled(true).build());\n\n      assertEquals(tenants, expected);\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/features/ServiceApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.features;\n\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.Set;\n\nimport org.jclouds.openstack.keystone.v2_0.domain.Tenant;\nimport org.jclouds.openstack.keystone.v2_0.internal.BaseKeystoneApiLiveTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests ServiceApi\n */\n@Test(groups = \"live\", testName = \"ServiceApiLiveTest\")\npublic class ServiceApiLiveTest extends BaseKeystoneApiLiveTest {\n\n   public void testTenants() {\n      Set<? extends Tenant> result = api.getServiceApi().listTenants();\n      assertNotNull(result);\n      assertFalse(result.isEmpty());\n\n      for (Tenant tenant : result) {\n         assertNotNull(tenant.getId());        \n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/features/TenantApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.Set;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.keystone.v2_0.KeystoneApi;\nimport org.jclouds.openstack.keystone.v2_0.domain.Tenant;\nimport org.jclouds.openstack.keystone.v2_0.internal.BaseKeystoneRestApiExpectTest;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests parsing and Guice wiring of TenantApi\n */\n@Test(testName = \"TenantApiExpectTest\")\npublic class TenantApiExpectTest extends BaseKeystoneRestApiExpectTest<KeystoneApi> {\n\n   public TenantApiExpectTest() {\n      endpoint = \"https://csnode.jclouds.org:35357\";\n   }\n\n   Set<Tenant> expectedTenants = ImmutableSet.of(Tenant.builder().name(\"demo\").id(\"05d1dc7af71646deba64cfc17b81bec0\")\n            .enabled(true).build(), Tenant.builder().name(\"admin\").id(\"7aa2e17ec29f44d193c48feaba0852cc\").enabled(true)\n            .build());\n\n   public void testListTenants() {\n      TenantApi api = requestsSendResponses(\n               keystoneAuthWithUsernameAndPasswordAndTenantName,\n               responseWithKeystoneAccess,\n               authenticatedGET().endpoint(endpoint + \"/v2.0/tenants\").build(),\n               HttpResponse.builder().statusCode(200).payload(\n                        payloadFromResourceWithContentType(\"/tenant_list.json\", APPLICATION_JSON)).build())\n               .getTenantApi().get();\n\n      assertEquals(api.list().concat().toSet(), expectedTenants);\n   }\n   \n   public void testListTenantsPage() {\n      TenantApi api = requestsSendResponses(\n               keystoneAuthWithUsernameAndPasswordAndTenantName,\n               responseWithKeystoneAccess,\n               authenticatedGET().endpoint(endpoint + \"/v2.0/tenants\").build(),\n               HttpResponse.builder().statusCode(200).payload(\n                        payloadFromResourceWithContentType(\"/tenant_list.json\", APPLICATION_JSON)).build())\n               .getTenantApi().get();\n      Set<? extends Tenant> tenants = api.list(new PaginationOptions()).toSet();\n      assertNotNull(tenants);\n      assertFalse(tenants.isEmpty());\n\n      assertEquals(tenants, expectedTenants);\n   }\n\n   // this is not a compatible format of json per:\n   // http://docs.openstack.org/api/openstack-identity-service/2.0/content/Paginated_Collections-d1e325.html\n   @Test(enabled = false)\n   public void testListTenantsATT() {\n      TenantApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint + \"/v2.0/tenants\").build(),\n            HttpResponse.builder().statusCode(200).payload(\n                  payloadFromResourceWithContentType(\"/tenant_list_att.json\", APPLICATION_JSON)).build())\n            .getTenantApi().get();\n\n      Set<Tenant> expected = ImmutableSet.of(Tenant.builder().name(\"this-is-a-test\").id(\"14\").description(\"None\").build());\n\n      assertEquals(api.list().concat().toSet(), expected);\n   }\n   \n   public void testGetTenant() {\n      TenantApi api = requestsSendResponses(\n               keystoneAuthWithUsernameAndPasswordAndTenantName,\n               responseWithKeystoneAccess,\n               authenticatedGET().endpoint(endpoint + \"/v2.0/tenants/013ba41150a14830bec85ffe93353bcc\").build(),\n               HttpResponse.builder().statusCode(200).payload(\n                        payloadFromResourceWithContentType(\"/tenant_details.json\", APPLICATION_JSON)).build())\n               .getTenantApi().get();\n      Tenant tenant = api.get(\"013ba41150a14830bec85ffe93353bcc\");\n      assertNotNull(tenant);\n      assertEquals(tenant, Tenant.builder().id(\"013ba41150a14830bec85ffe93353bcc\").name(\"admin\").enabled(true).\n            build());\n   }\n\n   public void testGetTenantByName() {\n      TenantApi api = requestsSendResponses(\n               keystoneAuthWithUsernameAndPasswordAndTenantName,\n               responseWithKeystoneAccess,\n               authenticatedGET().endpoint(endpoint + \"/v2.0/tenants?name=admin\").build(),\n               HttpResponse.builder().statusCode(200).payload(\n                        payloadFromResourceWithContentType(\"/tenant_details.json\", APPLICATION_JSON)).build())\n               .getTenantApi().get();\n      Tenant tenant = api.getByName(\"admin\");\n      assertNotNull(tenant);\n      assertEquals(tenant, Tenant.builder().id(\"013ba41150a14830bec85ffe93353bcc\").name(\"admin\").enabled(true).\n            build());\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/features/TenantApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.Set;\n\nimport org.jclouds.openstack.keystone.v2_0.domain.Tenant;\nimport org.jclouds.openstack.keystone.v2_0.internal.BaseKeystoneApiLiveTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests TenantApi\n */\n@Test(groups = \"live\", testName = \"TenantApiLiveTest\")\npublic class TenantApiLiveTest extends BaseKeystoneApiLiveTest {\n\n   public void testTenants() {\n      TenantApi tenantApi = api.getTenantApi().get();\n      Set<? extends Tenant> result = tenantApi.list().concat().toSet();\n      assertNotNull(result);\n      assertFalse(result.isEmpty());\n\n      for (Tenant tenant : result) {\n         assertNotNull(tenant.getId());\n\n         Tenant aTenant = tenantApi.get(tenant.getId());\n         assertNotNull(aTenant, \"get returned null for tenant: \" + tenant);\n\n         assertEquals(aTenant, tenant);\n      }\n   }\n\n   public void testTenantsByName() {\n\n      TenantApi tenantApi = api.getTenantApi().get();\n\n      for (Tenant tenant : tenantApi.list().concat()) {\n         Tenant aTenant = tenantApi.getByName(tenant.getName());\n         assertNotNull(aTenant, \"get returned null for tenant: \" + tenant);\n\n         assertEquals(aTenant, tenant);\n      }\n\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/features/TokenApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.Set;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.keystone.v2_0.KeystoneApi;\nimport org.jclouds.openstack.keystone.v2_0.domain.Endpoint;\nimport org.jclouds.openstack.keystone.v2_0.domain.Role;\nimport org.jclouds.openstack.keystone.v2_0.domain.Tenant;\nimport org.jclouds.openstack.keystone.v2_0.domain.Token;\nimport org.jclouds.openstack.keystone.v2_0.domain.User;\nimport org.jclouds.openstack.keystone.v2_0.internal.BaseKeystoneRestApiExpectTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests parsing and Guice wiring of TokenApi\n */\n@Test(testName = \"TokenApiExpectTest\")\npublic class TokenApiExpectTest extends BaseKeystoneRestApiExpectTest<KeystoneApi> {\n\n   public TokenApiExpectTest() {\n      endpoint = \"https://csnode.jclouds.org:35357\";\n   }\n\n   private DateService dateService = new SimpleDateFormatDateService();\n\n   public void testGetToken() {\n      TokenApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint + \"/v2.0/tokens/sometokenorother\").build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResourceWithContentType(\"/token_details.json\", APPLICATION_JSON)).build())\n            .getTokenApi().get();\n      Token token = api.get(\"sometokenorother\");\n      assertNotNull(token);\n      assertEquals(token,\n            Token.builder().id(\"167eccdc790946969ced473732e8109b\").expires(dateService.iso8601SecondsDateParse(\"2012-04-28T12:42:50Z\"))\n                  .tenant(Tenant.builder().id(\"4cea93f5464b4f1c921fb3e0461d72b5\").name(\"demo\").enabled(true).build()).build());\n   }\n\n   public void testGetUserOfToken() {\n      TokenApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint + \"/v2.0/tokens/sometokenorother\").build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResourceWithContentType(\"/token_details.json\", APPLICATION_JSON)).build())\n            .getTokenApi().get();\n      User user = api.getUserOfToken(\"sometokenorother\");\n      assertNotNull(user);\n      assertEquals(user, User.builder().id(\"2b9b606181634ae9ac86fd95a8bc2cde\").name(\"admin\")\n            .roles(ImmutableSet.of(Role.builder().id(\"79cada5c02814b57a52e0eed4dd388cb\").name(\"admin\").build()))\n            .build());\n   }\n\n   public void testCheckTokenIsValid() {\n      TokenApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess,\n            HttpRequest.builder().method(\"HEAD\")\n                       .endpoint(endpoint + \"/v2.0/tokens/sometokenorother\")\n                       .addHeader(\"Accept\", APPLICATION_JSON)\n                       .addHeader(\"X-Auth-Token\", authToken)\n                       .build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResourceWithContentType(\"/token_details.json\", APPLICATION_JSON)).build())\n            .getTokenApi().get();\n      assertTrue(api.isValid(\"sometokenorother\"));\n   }\n\n   @Test\n   public void testGetEndpointsForToken() {\n      TokenApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint + \"/v2.0/tokens/XXXXXX/endpoints\").build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResourceWithContentType(\"/user_endpoints.json\", APPLICATION_JSON)).build())\n            .getTokenApi().get();\n      Set<? extends Endpoint> endpoints = api.listEndpointsForToken(\"XXXXXX\");\n\n      assertEquals(endpoints, ImmutableSet.of(\n            Endpoint.builder().publicURL(URI.create(\"https://csnode.jclouds.org/v2.0/\"))\n                  .adminURL(URI.create(\"https://csnode.jclouds.org:35357/v2.0/\"))\n                  .region(\"region-a.geo-1\").id(\"2.0\").versionId(\"2.0\").build()\n      ));\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/features/TokenApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.AssertJUnit.assertTrue;\n\nimport java.util.Properties;\nimport java.util.Set;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.keystone.v2_0.KeystoneApi;\nimport org.jclouds.openstack.keystone.v2_0.domain.Endpoint;\nimport org.jclouds.openstack.keystone.v2_0.domain.Token;\nimport org.jclouds.openstack.keystone.v2_0.domain.User;\nimport org.jclouds.openstack.keystone.v2_0.internal.BaseKeystoneApiLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Iterables;\nimport com.google.inject.Injector;\nimport com.google.inject.Module;\n\n/**\n * Tests TokenApi\n */\n@Test(groups = \"live\", testName = \"TokenApiLiveTest\", singleThreaded = true)\npublic class TokenApiLiveTest extends BaseKeystoneApiLiveTest {\n\n   protected String token;\n   \n   @Override\n   protected KeystoneApi create(Properties props, Iterable<Module> modules) {\n      Injector injector = newBuilder().modules(modules).overrides(props).buildInjector();\n      grabToken(injector.getInstance(AuthenticateRequest.class));\n      return injector.getInstance(KeystoneApi.class);\n   }\n\n   // Get the token currently in use (there's currently no listTokens())\n   private void grabToken(AuthenticateRequest ar) {\n      HttpRequest test = ar.filter(HttpRequest.builder().method(\"GET\").endpoint(endpoint).build());\n      token = Iterables.getOnlyElement(test.getHeaders().get(\"X-Auth-Token\"));\n   }\n\n   public void testToken() {\n\n      TokenApi tokenApi = api.getTokenApi().get();\n      assertTrue(tokenApi.isValid(token));\n      Token result = tokenApi.get(token);\n      assertNotNull(result);\n      assertEquals(result.getId(), token);\n      assertNotNull(result.getTenant());\n\n      User user = tokenApi.getUserOfToken(token);\n      assertNotNull(user);\n      assertNotNull(user.getId());\n      assertNotNull(user.getName());\n\n   }\n\n   public void testInvalidToken() {\n\n      TokenApi tokenApi = api.getTokenApi().get();\n      assertFalse(tokenApi.isValid(\"thisisnotarealtoken!\"));\n      assertNull(tokenApi.get(\"thisisnotarealtoken!\"));\n\n   }\n\n   public void testTokenEndpoints() {\n\n      TokenApi tokenApi = api.getTokenApi().get();\n      Set<? extends Endpoint> endpoints = tokenApi.listEndpointsForToken(token);\n      assertNotNull(endpoints);\n      assertFalse(endpoints.isEmpty());\n\n   }\n\n   public void testInvalidTokenEndpoints() {\n\n      TokenApi tokenApi = api.getTokenApi().get();\n      assertTrue(tokenApi.listEndpointsForToken(\"thisisnotarealtoken!\").isEmpty());\n\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/features/UserApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.openstack.keystone.v2_0.KeystoneApi;\nimport org.jclouds.openstack.v2_0.domain.PaginatedCollection;\nimport org.jclouds.openstack.keystone.v2_0.domain.Role;\nimport org.jclouds.openstack.keystone.v2_0.domain.User;\nimport org.jclouds.openstack.keystone.v2_0.internal.BaseKeystoneRestApiExpectTest;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\nimport org.jclouds.rest.AuthorizationException;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests parsing and Guice wiring of UserApi\n */\n@Test(singleThreaded = true, testName = \"UserApiExpectTest\")\npublic class UserApiExpectTest extends BaseKeystoneRestApiExpectTest<KeystoneApi> {\n   \n   public UserApiExpectTest() {\n      endpoint = \"https://csnode.jclouds.org:35357\";\n   }\n   \n   Set<User> expectedUsers = ImmutableSet.of(\n         User.builder().name(\"nova\").id(\"e021dfd758eb44a89f1c57c8ef3be8e2\").email(\"nova@example.com\").enabled(true).\n         tenantId(\"ab1da202f5774cceb5da2aeff1f0aa87\").build(),\n         User.builder().name(\"glance\").id(\"3f6c1c9ba993495ead7d2eb2192e284f\").email(\"glance@example.com\").enabled(true).\n         tenantId(\"ab1da202f5774cceb5da2aeff1f0aa87\").build(),\n         User.builder().name(\"demo\").id(\"667b2e1420604df8b67cd8ea57d4ee64\").email(\"demo@example.com\").enabled(true).\n         tenantId(null).build(),\n         User.builder().name(\"admin\").id(\"2b9b606181634ae9ac86fd95a8bc2cde\").email(\"admin@example.com\").enabled(true).\n         tenantId(null).build());\n   \n   public void testListUsers() {\n      UserApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint + \"/v2.0/users\").build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResourceWithContentType(\"/user_list.json\", APPLICATION_JSON)).build())\n            .getUserApi().get();\n     \n      assertEquals(api.list().concat().toSet(), expectedUsers);\n   }\n   \n   public void testListUsersPage() {\n      UserApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint + \"/v2.0/users\").build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResourceWithContentType(\"/user_list.json\", APPLICATION_JSON)).build())\n            .getUserApi().get();\n      PaginatedCollection<? extends User> users = api.list(new PaginationOptions());\n      assertNotNull(users);\n      assertFalse(users.isEmpty());\n\n\n      assertEquals(users.toSet(), expectedUsers);\n   }\n   \n   @Test(expectedExceptions = AuthorizationException.class)\n   public void testListUsersFailNotAuth() {\n      UserApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint + \"/v2.0/users\").build(),\n            HttpResponse.builder().statusCode(401).build()).getUserApi().get();\n      api.list(new PaginationOptions());\n   }\n\n   public void testGetUser() {\n      UserApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint + \"/v2.0/users/e021dfd758eb44a89f1c57c8ef3be8e2\").build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResourceWithContentType(\"/user_details.json\", APPLICATION_JSON)).build())\n            .getUserApi().get();\n      User user = api.get(\"e021dfd758eb44a89f1c57c8ef3be8e2\");\n      assertNotNull(user);\n      assertEquals(user, User.builder().name(\"nova\").id(\"e021dfd758eb44a89f1c57c8ef3be8e2\").email(\"nova@example.com\").enabled(true).\n            tenantId(\"ab1da202f5774cceb5da2aeff1f0aa87\").build());\n   }\n\n   public void testGetUserByName() {\n      UserApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint + \"/v2.0/users?name=nova\").build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResourceWithContentType(\"/user_details.json\", APPLICATION_JSON)).build())\n            .getUserApi().get();\n      User user = api.getByName(\"nova\");\n      assertNotNull(user);\n      assertEquals(user, User.builder().name(\"nova\").id(\"e021dfd758eb44a89f1c57c8ef3be8e2\").email(\"nova@example.com\").enabled(true).\n            tenantId(\"ab1da202f5774cceb5da2aeff1f0aa87\").build());\n   }\n\n   public void testListRolesOfUser() {\n      UserApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint + \"/v2.0/users/3f6c1c9ba993495ead7d2eb2192e284f/roles\").build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResourceWithContentType(\"/user_role_list.json\", APPLICATION_JSON)).build())\n            .getUserApi().get();\n      Set<? extends Role> roles = api.listRolesOfUser(\"3f6c1c9ba993495ead7d2eb2192e284f\");\n      assertNotNull(roles);\n      assertFalse(roles.isEmpty());\n      assertEquals(roles, ImmutableSet.of(\n            Role.builder().id(\"79cada5c02814b57a52e0eed4dd388cb\").name(\"admin\").build()\n      ));\n   }\n\n   @Test(expectedExceptions = HttpResponseException.class)\n   public void testListRolesOfUserFailNotImplemented() {\n      UserApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint + \"/v2.0/users/5f6c1c9ba993495ead7d2eb2192e284f/roles\").build(),\n            HttpResponse.builder().statusCode(501).build()).getUserApi().get();\n      assertTrue(api.listRolesOfUser(\"5f6c1c9ba993495ead7d2eb2192e284f\").isEmpty());\n   }\n\n   public void testListRolesOfUserInTenant() {\n      UserApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint + \"/v2.0/users/3f6c1c9ba993495ead7d2eb2192e284f/roles\").build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResourceWithContentType(\"/user_tenant_role_list.json\", APPLICATION_JSON)).build())\n            .getUserApi().get();\n      Set<? extends Role> roles = api.listRolesOfUser(\"3f6c1c9ba993495ead7d2eb2192e284f\");\n      assertNotNull(roles);\n      assertFalse(roles.isEmpty());\n      assertEquals(roles, ImmutableSet.of(\n         Role.builder().id(\"31c451195aac49b386039341e2c92a16\").name(\"KeystoneServiceAdmin\").build(),\n         Role.builder().id(\"79cada5c02814b57a52e0eed4dd388cb\").name(\"admin\").build(),\n         Role.builder().id(\"6ea17ddd37a6447794cb0e164d4db894\").name(\"KeystoneAdmin\").build()));\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/features/UserApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.Set;\n\nimport org.jclouds.openstack.keystone.v2_0.domain.Role;\nimport org.jclouds.openstack.keystone.v2_0.domain.Tenant;\nimport org.jclouds.openstack.keystone.v2_0.domain.User;\nimport org.jclouds.openstack.keystone.v2_0.internal.BaseKeystoneApiLiveTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests UserApi\n */\n@Test(groups = \"live\", testName = \"UserApiLiveTest\", singleThreaded = true)\npublic class UserApiLiveTest extends BaseKeystoneApiLiveTest {\n\n   public void testUsers() {\n\n      UserApi userApi = api.getUserApi().get();\n      Set<? extends User> users = userApi.list().concat().toSet();\n      assertNotNull(users);\n      assertFalse(users.isEmpty());\n      for (User user : users) {\n         User aUser = userApi.get(user.getId());\n         assertEquals(aUser, user);\n      }\n\n   }\n\n   public void testUserRolesOnTenant() {\n\n      UserApi userApi = api.getUserApi().get();\n      Set<? extends Tenant> tenants = api.getTenantApi().get().list().concat().toSet();\n\n      for (User user : userApi.list().concat()) {\n         for (Tenant tenant : tenants) {\n            Set<? extends Role> roles = userApi.listRolesOfUserOnTenant(user.getId(), tenant.getId());\n            for (Role role : roles) {\n               assertNotNull(role.getId());\n            }\n         }\n      }\n\n   }\n\n   public void testListRolesOfUser() {\n\n      UserApi userApi = api.getUserApi().get();\n      for (User user : userApi.list().concat()) {\n         Set<? extends Role> roles = userApi.listRolesOfUser(user.getId());\n         for (Role role : roles) {\n            assertNotNull(role.getId());\n         }\n      }\n\n   }\n\n   public void testUsersByName() {\n\n      UserApi userApi = api.getUserApi().get();\n      for (User user : userApi.list().concat()) {\n         User aUser = userApi.getByName(user.getName());\n         assertEquals(aUser, user);\n      }\n\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/functions/internal/ParseUsersTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.functions.internal;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.lang.reflect.Type;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.openstack.keystone.v2_0.config.KeystoneParserModule;\nimport org.jclouds.openstack.keystone.v2_0.domain.User;\nimport org.jclouds.openstack.keystone.v2_0.functions.internal.ParseUsers.Users;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.reflect.TypeToken;\nimport com.google.gson.Gson;\nimport com.google.gson.JsonSyntaxException;\nimport com.google.inject.Guice;\n\n@Test(testName = \"ParseUsersTest\")\npublic class ParseUsersTest {\n\n   private Gson gson = Guice.createInjector(new GsonModule(), new KeystoneParserModule()).getInstance(Gson.class);\n   private Type usersMapType = new TypeToken<Map<String, Set<? extends User>>>() {\n      private static final long serialVersionUID = 1L;\n   }.getType();\n\n   Set<User> expectedUsers = ImmutableSet.of(\n         User.builder().name(\"nova\").id(\"e021dfd758eb44a89f1c57c8ef3be8e2\").email(\"nova@example.com\").enabled(true).\n         tenantId(\"ab1da202f5774cceb5da2aeff1f0aa87\").build(),\n         User.builder().name(\"glance\").id(\"3f6c1c9ba993495ead7d2eb2192e284f\").email(\"glance@example.com\").enabled(true).\n         tenantId(\"ab1da202f5774cceb5da2aeff1f0aa87\").build(),\n         User.builder().name(\"demo\").id(\"667b2e1420604df8b67cd8ea57d4ee64\").email(\"demo@example.com\").enabled(true).\n         tenantId(null).build(),\n         User.builder().name(\"admin\").id(\"2b9b606181634ae9ac86fd95a8bc2cde\").email(\"admin@example.com\").enabled(true).\n         tenantId(null).build());\n\n   public void testParseUsersInMap() throws JsonSyntaxException, IOException {\n      String json = Strings2.toStringAndClose(getClass().getResourceAsStream(\"/user_list.json\"));\n      Map<String, Set<? extends User>> users = gson.fromJson(json, usersMapType);\n      assertEquals(users.get(\"users\"), expectedUsers);\n   }\n\n   public void testParseUsers() throws JsonSyntaxException, IOException {\n      String json = Strings2.toStringAndClose(getClass().getResourceAsStream(\"/user_list.json\"));\n      Users users = gson.fromJson(json, Users.class);\n      assertEquals(users.toSet(), expectedUsers);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/internal/BaseKeystoneApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.internal;\n\nimport java.util.Properties;\n\nimport org.jclouds.apis.BaseApiLiveTest;\nimport org.jclouds.openstack.keystone.config.KeystoneProperties;\nimport org.jclouds.openstack.keystone.v2_0.KeystoneApi;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code KeystoneApi}\n */\n@Test(groups = \"live\")\npublic class BaseKeystoneApiLiveTest extends BaseApiLiveTest<KeystoneApi> {\n\n   public BaseKeystoneApiLiveTest() {\n      provider = \"openstack-keystone\";\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      setIfTestSystemPropertyPresent(props, KeystoneProperties.CREDENTIAL_TYPE);\n      return props;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/internal/BaseKeystoneRestApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.internal;\n\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.SERVICE_TYPE;\n\nimport java.util.Properties;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.keystone.v2_0.KeystoneApiMetadata;\nimport org.jclouds.openstack.v2_0.ServiceType;\nimport org.jclouds.rest.internal.BaseRestApiExpectTest;\n\nimport com.google.common.base.Objects;\n\n/**\n * Base class for writing KeyStone 2.0 Rest Api Expect tests\n */\npublic class BaseKeystoneRestApiExpectTest<S> extends BaseRestApiExpectTest<S> {\n   protected HttpRequest keystoneAuthWithUsernameAndPasswordAndTenantName;\n   protected HttpRequest keystoneAuthWithUsernameAndPassword;\n   protected HttpRequest keystoneAuthWithAccessKeyAndSecretKey;\n   protected String authToken;\n   protected HttpResponse responseWithKeystoneAccess;\n   protected String endpoint = \"http://localhost:5000\";\n\n   public BaseKeystoneRestApiExpectTest() {\n      provider = \"openstack-keystone\";\n      keystoneAuthWithUsernameAndPasswordAndTenantName = KeystoneFixture.INSTANCE\n            .initialAuthWithUsernameAndPasswordAndTenantName(identity, credential);\n      keystoneAuthWithUsernameAndPassword = KeystoneFixture.INSTANCE\n            .initialAuthWithUsernameAndPassword(identity, credential);\n      keystoneAuthWithAccessKeyAndSecretKey = KeystoneFixture.INSTANCE\n            .initialAuthWithAccessKeyAndSecretKeyAndTenantName(identity, credential);\n\n      authToken = KeystoneFixture.INSTANCE.getAuthToken();\n      responseWithKeystoneAccess = KeystoneFixture.INSTANCE.responseWithAccess();\n      // now, createContext arg will need tenant prefix\n      identity = KeystoneFixture.INSTANCE.getTenantName() + \":\" + identity;\n   }\n\n   protected HttpRequest.Builder<?> authenticatedGET() {\n      return HttpRequest.builder().method(\"GET\").addHeader(\"Accept\", MediaType.APPLICATION_JSON)\n            .addHeader(\"X-Auth-Token\", authToken);\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      props.put(SERVICE_TYPE, ServiceType.IDENTITY);\n      return props;\n   }\n\n   @Override\n   protected HttpRequestComparisonType compareHttpRequestAsType(HttpRequest input) {\n      return Objects.equal(\"HEAD\", input.getMethod()) ? HttpRequestComparisonType.DEFAULT\n            : HttpRequestComparisonType.JSON;\n   }\n\n   @Override\n   protected ApiMetadata createApiMetadata() {\n      return new KeystoneApiMetadata();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/internal/KeystoneFixture.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.internal;\nimport static java.lang.String.format;\nimport static org.jclouds.rest.internal.BaseRestApiExpectTest.payloadFromStringWithContentType;\n\nimport java.io.IOException;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.io.Payload;\nimport org.jclouds.util.Strings2;\n\nimport com.google.common.base.Throwables;\nimport com.google.common.net.HttpHeaders;\n\n/**\n * Base class for writing KeyStone Rest Api Expect tests\n */\npublic enum KeystoneFixture {\n   INSTANCE;\n\n   public String getTenantId() {\n      return \"12346637803162\";\n   }\n\n   public String getTenantName() {\n\t      return \"user@jclouds.apache.org\";\n\t   }\n\n   public HttpRequest initialAuthWithUsernameAndPassword(String username, String password) {\n      return HttpRequest.builder().method(\"POST\")\n            .endpoint(\"http://localhost:5000/v2.0/tokens\")\n            .addHeader(HttpHeaders.ACCEPT, \"application/json\")\n            .payload(\n                     payloadFromStringWithContentType(\n                              format(\n                                       \"{\\\"auth\\\":{\\\"passwordCredentials\\\":{\\\"username\\\":\\\"%s\\\",\\\"password\\\":\\\"%s\\\"}}}\",\n                                       username, password), \"application/json\")).build();\n   }\n\n   public HttpRequest initialAuthWithUsernameAndPasswordAndTenantName(String username, String password) {\n      return HttpRequest.builder().method(\"POST\")\n            .endpoint(\"http://localhost:5000/v2.0/tokens\")\n            .addHeader(HttpHeaders.ACCEPT, \"application/json\")\n            .payload(\n                     payloadFromStringWithContentType(\n                              format(\n                                       \"{\\\"auth\\\":{\\\"passwordCredentials\\\":{\\\"username\\\":\\\"%s\\\",\\\"password\\\":\\\"%s\\\"},\\\"tenantName\\\":\\\"%s\\\"}}\",\n                                       username, password, getTenantName()), \"application/json\")).build();\n   }\n\n   public HttpRequest initialAuthWithAccessKeyAndSecretKeyAndTenantName(String accessKey, String secretKey) {\n      return HttpRequest.builder().method(\"POST\")\n            .endpoint(\"http://localhost:5000/v2.0/tokens\")\n            .addHeader(HttpHeaders.ACCEPT, \"application/json\")\n            .payload(\n                     payloadFromStringWithContentType(\n                              format(\n                                       \"{\\\"auth\\\":{\\\"apiAccessKeyCredentials\\\":{\\\"accessKey\\\":\\\"%s\\\",\\\"secretKey\\\":\\\"%s\\\"},\\\"tenantName\\\":\\\"%s\\\"}}\",\n                                       accessKey, secretKey, getTenantName()), \"application/json\")).build();\n   }\n\n   public HttpRequest initialAuthWithAccessKeyAndSecretKeyAndTenantId(String accessKey, String secretKey) {\n      return HttpRequest.builder().method(\"POST\")\n            .endpoint(\"http://localhost:5000/v2.0/tokens\")\n            .addHeader(HttpHeaders.ACCEPT, \"application/json\")\n            .payload(\n                     payloadFromStringWithContentType(\n                              format(\n                                       \"{\\\"auth\\\":{\\\"apiAccessKeyCredentials\\\":{\\\"accessKey\\\":\\\"%s\\\",\\\"secretKey\\\":\\\"%s\\\"},\\\"tenantId\\\":\\\"%s\\\"}}\",\n                                       accessKey, secretKey, getTenantId()), \"application/json\")).build();\n   }\n\n   public String getAuthToken() {\n      return  \"Auth_4f173437e4b013bee56d1007\";\n   }\n\n   public HttpResponse responseWithAccess() {\n      return HttpResponse.builder().statusCode(200).message(\"HTTP/1.1 200\").payload(\n            payloadFromResourceWithContentType(\"/keystoneAuthResponse.json\", \"application/json\")).build();\n   }\n\n\n   public Payload payloadFromResourceWithContentType(String resource, String contentType) {\n      try {\n         return payloadFromStringWithContentType(Strings2.toStringAndClose(getClass().getResourceAsStream(resource)),\n                  contentType);\n      } catch (IOException e) {\n         throw Throwables.propagate(e);\n      }\n\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/parse/ParseAccessTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.parse;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.openstack.keystone.v2_0.domain.Access;\nimport org.jclouds.openstack.keystone.v2_0.domain.Endpoint;\nimport org.jclouds.openstack.keystone.v2_0.domain.Role;\nimport org.jclouds.openstack.keystone.v2_0.domain.Service;\nimport org.jclouds.openstack.keystone.v2_0.domain.Tenant;\nimport org.jclouds.openstack.keystone.v2_0.domain.Token;\nimport org.jclouds.openstack.keystone.v2_0.domain.User;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport static org.jclouds.openstack.v2_0.ServiceType.BLOCK_STORAGE;\nimport static org.jclouds.openstack.v2_0.ServiceType.COMPUTE;\nimport static org.jclouds.openstack.v2_0.ServiceType.DATABASE;\nimport static org.jclouds.openstack.v2_0.ServiceType.IDENTITY;\nimport static org.jclouds.openstack.v2_0.ServiceType.IMAGE;\nimport static org.jclouds.openstack.v2_0.ServiceType.NETWORK;\nimport static org.jclouds.openstack.v2_0.ServiceType.OBJECT_STORE;\nimport static org.jclouds.openstack.v2_0.ServiceType.MESSAGING;\nimport static org.jclouds.openstack.v2_0.ServiceType.SHARED_FILESYSTEM;\n\n\n@Test(groups = \"unit\", testName = \"ParseAccessTest\")\npublic class ParseAccessTest extends BaseItemParserTest<Access> {\n\n   @Override\n   public String resource() {\n      return \"/keystoneAuthResponse.json\";\n   }\n\n   @Override\n   @SelectJson(\"access\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Access expected() {\n      return Access.builder()\n            .token(Token.builder()\n                  .expires(new SimpleDateFormatDateService().iso8601DateParse(\"2012-01-18T21:35:59.050Z\"))\n                  .id(\"Auth_4f173437e4b013bee56d1007\")\n                  .tenant(Tenant.builder().id(\"40806637803162\").name(\"user@jclouds.org-default-tenant\").build()).build())\n            .user(User.builder()\n                  .id(\"36980896575174\").name(\"user@jclouds.org\")\n                  .role(Role.builder().id(\"00000000004022\").serviceId(\"110\").name(\"Admin\").tenantId(\"40806637803162\").build())\n                  .role(Role.builder().id(\"00000000004024\").serviceId(\"140\").name(\"user\").tenantId(\"40806637803162\").build())\n                  .role(Role.builder().id(\"00000000004004\").serviceId(\"100\").name(\"domainuser\").build())\n                  .role(Role.builder().id(\"00000000004016\").serviceId(\"120\").name(\"netadmin\").tenantId(\"40806637803162\").build()).build())\n            .service(Service.builder().name(\"Object Storage\").type(OBJECT_STORE)\n                  .endpoint(Endpoint.builder()\n                        .tenantId(\"40806637803162\")\n                        .publicURL(\"https://objects.jclouds.org/v1.0/40806637803162\")\n                        .adminURL(\"https://objects.jclouds.org/v1.0/\")\n                        .id(\"1.0\")\n                        .region(\"region-a.geo-1\").build()).build())\n            .service(Service.builder().name(\"Identity\").type(IDENTITY)\n                  .endpoint(Endpoint.builder()\n                        .publicURL(\"https://csnode.jclouds.org/v2.0/\")\n                        .adminURL(\"https://csnode.jclouds.org:35357/v2.0/\")\n                        .region(\"region-a.geo-1\")\n                        .id(\"2.0\")\n                        .versionId(\"2.0\").build()).build())\n            .service(Service.builder().name(\"Image Management\").type(IMAGE)\n                  .endpoint(Endpoint.builder()\n                        .tenantId(\"40806637803162\")\n                        .publicURL(\"https://glance.jclouds.org:9292/\")\n                        .region(\"az-1.region-a.geo-1\")\n                        .id(\"1.0\").build()).build())\n            .service(Service.builder().name(\"Compute\").type(COMPUTE)\n                  .endpoint(Endpoint.builder()\n                        .tenantId(\"3456\")\n                        .publicURL(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456\")\n                        .region(\"az-1.region-a.geo-1\")\n                        .versionId(\"2\")\n                        .versionInfo(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/\")\n                        .versionList(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com\").build())\n                  .endpoint(Endpoint.builder()\n                        .tenantId(\"3456\")\n                        .publicURL(\"https://az-2.region-a.geo-1.compute.hpcloudsvc.com/v2/3456\")\n                        .region(\"az-2.region-a.geo-1\")\n                        .versionId(\"2\")\n                        .versionInfo(\"https://az-2.region-a.geo-1.compute.hpcloudsvc.com/v2/\")\n                        .versionList(\"https://az-2.region-a.geo-1.compute.hpcloudsvc.com\").build())\n                  .endpoint(Endpoint.builder()\n                        .tenantId(\"3456\")\n                        .publicURL(\"https://az-3.region-a.geo-1.compute.hpcloudsvc.com/v2/3456\")\n                        .region(\"az-3.region-a.geo-1\")\n                        .versionId(\"2\")\n                        .versionInfo(\"https://az-3.region-a.geo-1.compute.hpcloudsvc.com/v2/\")\n                        .versionList(\"https://az-3.region-a.geo-1.compute.hpcloudsvc.com\").build()).build())\n            .service(Service.builder().name(\"Neutron Service\").type(NETWORK)\n                  .endpoint(Endpoint.builder()\n                        .tenantId(\"3456\")\n                        .publicURL(\"https://csnode.jclouds.org:9696/v1.0/tenants/3456\")\n                        .internalURL(\"https://csnode.jclouds.org:9696/v1.0/tenants/3456\")\n                        .adminURL(\"https://csnode.jclouds.org:9696/v1.0\")\n                        .region(\"region-a.geo-1\")\n                        .versionId(\"1.0\").build()).build())\n            .service(Service.builder().name(\"Quantum Service\").type(NETWORK)\n                  .endpoint(Endpoint.builder()\n                        .tenantId(\"3456\")\n                        .publicURL(\"https://csnode.jclouds.org:9696\")\n                        .internalURL(\"https://csnode.jclouds.org:9696\")\n                        .adminURL(\"https://csnode.jclouds.org:9696\")\n                        .region(\"region-a.geo-1\")\n                        .versionId(\"2.0\").build()).build())\n            .service(Service.builder().name(\"cinder\").type(BLOCK_STORAGE)\n                  .endpoint(Endpoint.builder()\n                        .id(\"08330c2dcbfc4c6c8dc7a0949fbf5da7\")\n                        .publicURL(\"http://172.16.0.1:8776/v1/50cdb4c60374463198695d9f798fa34d\")\n                        .internalURL(\"http://10.0.2.15:8776/v1/50cdb4c60374463198695d9f798fa34d\")\n                        .adminURL(\"http://10.0.2.15:8776/v1/50cdb4c60374463198695d9f798fa34d\")\n                        .region(\"RegionOne\").build()).build())\n            .service(Service.builder().name(\"manila\").type(SHARED_FILESYSTEM)\n                  .endpoint(Endpoint.builder()\n                        .id(\"c06b43bc23e44be6b079ac319718014e\")\n                        .publicURL(\"http://172.16.0.1:8786/v1/50cdb4c60374463198695d9f798fa34d\")\n                        .internalURL(\"http://10.0.2.15:8786/v1/50cdb4c60374463198695d9f798fa34d\")\n                        .adminURL(\"http://10.0.2.15:8786/v1/50cdb4c60374463198695d9f798fa34d\")\n                        .region(\"RegionOne\").build()).build())\n            .service(Service.builder().name(\"trove\").type(DATABASE)\n                  .endpoint(Endpoint.builder()\n                        .publicURL(\"http://172.16.0.1:8776/v1/3456\")\n                        .tenantId(\"123123\")\n                        .region(\"RegionOne\").build()).build())\n            .service(Service.builder().name(\"zaqar\").type(MESSAGING)\n                  .endpoint(Endpoint.builder()\n                        .id(\"3456789\")\n                        .publicURL(\"http://172.16.0.1:8888\")\n                        .internalURL(\"http://10.0.2.15:8888\")\n                        .adminURL(\"http://10.0.2.15:8888\")\n                        .region(\"RegionOne\").build()).build())\n            .service(Service.builder().name(\"dns\").type(\"dns\")\n                  .endpoint(Endpoint.builder()\n                        .publicURL(\"http://172.16.0.1:8776/v1/3456\")\n                        .tenantId(\"3456\")\n                        .build()).build()).build();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/parse/ParseAdminAccessTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.parse;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.openstack.keystone.v2_0.domain.Access;\nimport org.jclouds.openstack.keystone.v2_0.domain.Endpoint;\nimport org.jclouds.openstack.keystone.v2_0.domain.Role;\nimport org.jclouds.openstack.keystone.v2_0.domain.Service;\nimport org.jclouds.openstack.keystone.v2_0.domain.Tenant;\nimport org.jclouds.openstack.keystone.v2_0.domain.Token;\nimport org.jclouds.openstack.keystone.v2_0.domain.User;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ParseAdminAccessTest\")\npublic class ParseAdminAccessTest extends BaseItemParserTest<Access> {\n\n   @Override\n   public String resource() {\n      return \"/adminAuth.json\";\n   }\n\n   @Override\n   @SelectJson(\"access\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Access expected() {\n      return Access.builder()\n                   .token(Token.builder()\n                               .expires(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2012-08-01T13:08:52Z\"))\n                               .id(\"946b8ad1ede4422f87ab21dcba27896d\")\n                               .tenant(Tenant.builder().id(\"2fdc88ae152948c690b97ba307acae9b\").name(\"admin\")\n                               .enabled(true).build()).build())\n                   .user(User.builder()\n                         .id(\"b4d134cfe3cf43ad8ba0c2fc5b5d8f91\")\n                         .name(\"admin\")\n                         .role(Role.builder().name(\"admin\").build())\n                         .role(Role.builder().name(\"KeystoneServiceAdmin\").build())\n                         .role(Role.builder().name(\"KeystoneAdmin\").build()).build())\n                   .service(Service.builder().name(\"Compute Service\").type(\"compute\")\n                                   .endpoint(Endpoint.builder()\n                                                     .adminURL(\"http://10.0.1.13:8774/v2/2fdc88ae152948c690b97ba307acae9b\")\n                                                     .internalURL(\"http://10.0.1.13:8774/v2/2fdc88ae152948c690b97ba307acae9b\")\n                                                     .publicURL(\"http://10.0.1.13:8774/v2/2fdc88ae152948c690b97ba307acae9b\")\n                                                     .region(\"RegionOne\").build()).build())\n                   .service(Service.builder().name(\"S3 Service\").type(\"s3\")\n                                   .endpoint(Endpoint.builder()\n                                                     .adminURL(\"http://10.0.1.13:3333\")\n                                                     .internalURL(\"http://10.0.1.13:3333\")\n                                                     .publicURL(\"http://10.0.1.13:3333\")\n                                                     .region(\"RegionOne\").build()).build())\n                   .service(Service.builder().name(\"Image Service\").type(\"image\")\n                                   .endpoint(Endpoint.builder()\n                                                     .adminURL(\"http://10.0.1.13:9292\")\n                                                     .internalURL(\"http://10.0.1.13:9292\")\n                                                     .publicURL(\"http://10.0.1.13:9292\")\n                                                     .region(\"RegionOne\").build()).build())\n                   .service(Service.builder().name(\"Volume Service\").type(\"volume\")\n                                   .endpoint(Endpoint.builder()\n                                                     .adminURL(\"http://10.0.1.13:8776/v1/2fdc88ae152948c690b97ba307acae9b\")\n                                                     .internalURL(\"http://10.0.1.13:8776/v1/2fdc88ae152948c690b97ba307acae9b\")\n                                                     .publicURL(\"http://10.0.1.13:8776/v1/2fdc88ae152948c690b97ba307acae9b\")\n                                                     .region(\"RegionOne\").build()).build())\n                   .service(Service.builder().name(\"EC2 Service\").type(\"ec2\")\n                                   .endpoint(Endpoint.builder()\n                                                     .adminURL(\"http://10.0.1.13:8773/services/Admin\")\n                                                     .internalURL(\"http://10.0.1.13:8773/services/Cloud\")\n                                                     .publicURL(\"http://10.0.1.13:8773/services/Cloud\")\n                                                     .region(\"RegionOne\").build()).build())\n                   .service(Service.builder().name(\"Identity Service\").type(\"identity\")\n                                   .endpoint(Endpoint.builder()\n                                                     .adminURL(\"http://10.0.1.13:35357/v2.0\")\n                                                     .internalURL(\"http://10.0.1.13:5000/v2.0\")\n                                                     .publicURL(\"http://10.0.1.13:5000/v2.0\")\n                                                     .region(\"RegionOne\").build()).build()).build();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/parse/ParseDevstackApiMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.parse;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.openstack.keystone.v2_0.config.KeystoneParserModule;\nimport org.jclouds.openstack.keystone.v2_0.domain.ApiMetadata;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\", testName = \"ParseDevstackApiMetadataTest\")\npublic class ParseDevstackApiMetadataTest extends BaseItemParserTest<ApiMetadata> {\n\n   @Override\n   public String resource() {\n      return \"/devstackVersion.json\";\n   }\n\n   // http://docs.openstack.org/api/openstack-identity-service/2.0/content/Versions-d1e472.html\n   @Override\n   @SelectJson(\"version\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public ApiMetadata expected() {\n      return ApiMetadata.builder().id(\"v2.0\")\n            .links(ImmutableSet.of(Link.builder().relation(Link.Relation.SELF).href(URI.create(\"http://172.16.89.167:5000/v2.0/\")).build(),\n                  Link.builder().relation(Link.Relation.DESCRIBEDBY).type(\"text/html\").href(URI.create(\"http://docs.openstack.org/api/openstack-identity-service/2.0/content/\")).build(),\n                  Link.builder().relation(Link.Relation.DESCRIBEDBY).type(\"application/pdf\").href(URI.create(\"http://docs.openstack.org/api/openstack-identity-service/2.0/identity-dev-guide-2.0.pdf\")).build()\n            ))\n            .status(\"beta\")\n            .updated(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2011-11-19T00:00:00+00:00\"))\n            .mediaTypes(ImmutableSet.of(\n                  org.jclouds.openstack.keystone.v2_0.domain.MediaType.builder().base(\"application/json\").type(\"application/vnd.openstack.identity-v2.0+json\").build(),\n                  org.jclouds.openstack.keystone.v2_0.domain.MediaType.builder().base(\"application/xml\").type(\"application/vnd.openstack.identity-v2.0+xml\").build()\n            ))\n            .build();\n   }\n\n   @Override\n   protected Injector injector() {\n      return Guice.createInjector(new GsonModule(), new KeystoneParserModule());\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/parse/ParseMinimalAccessTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.parse;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.openstack.keystone.v2_0.domain.Access;\nimport org.jclouds.openstack.keystone.v2_0.domain.Token;\nimport org.jclouds.openstack.keystone.v2_0.domain.User;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ParseMinimalAccessTest\")\npublic class ParseMinimalAccessTest extends BaseItemParserTest<Access> {\n\n   @Override\n   public String resource() {\n      return \"/access_minimal.json\";\n   }\n\n   @Override\n   @SelectJson(\"access\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Access expected() {\n      return Access.builder()\n                   .token(Token.builder()\n                               .expires(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2012-12-02T01:44:54Z\"))\n                               .id(\"5afc3adea6654e758b4a9cf01bafe507\").build())\n                   .user(User.builder()\n                             .id(\"bf45fd7586c2410c980c651b918aa850\")\n                             .name(\"nova\")\n//                             .username(\"nova\") TODO: add optional username field!\n                             .build()).build();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/parse/ParseRackspaceAccessTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.parse;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.openstack.keystone.v2_0.domain.Access;\nimport org.jclouds.openstack.keystone.v2_0.domain.Endpoint;\nimport org.jclouds.openstack.keystone.v2_0.domain.Role;\nimport org.jclouds.openstack.keystone.v2_0.domain.Service;\nimport org.jclouds.openstack.keystone.v2_0.domain.Tenant;\nimport org.jclouds.openstack.keystone.v2_0.domain.Token;\nimport org.jclouds.openstack.keystone.v2_0.domain.User;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ParseRackspaceAccessTest\")\npublic class ParseRackspaceAccessTest extends BaseItemParserTest<Access> {\n\n   @Override\n   public String resource() {\n      return \"/raxAuth.json\";\n   }\n\n   @Override\n   @SelectJson(\"access\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Access expected() {\n      return Access.builder()\n                   .token(Token.builder()\n                               .expires(new SimpleDateFormatDateService().iso8601DateParse(\"2012-06-06T20:56:47.000-05:00\"))\n                               .id(\"Auth_4f173437e4b013bee56d1007\")\n                               .tenant(Tenant.builder().id(\"40806637803162\").name(\"40806637803162\").build()).build())\n                   .user(User.builder()\n                             .id(\"54321\")\n                             .name(\"joe\")\n                             .role(Role.builder()\n                                       .id(\"3\")\n                                       .name(\"identity:user-admin\")\n                                       .description(\"User Admin Role.\").build()).build())\n                   .service(Service.builder().name(\"cloudDatabases\").type(\"rax:database\")\n                                   .endpoint(Endpoint.builder()\n                                                     .tenantId(\"40806637803162\")\n                                                     .publicURL(\"https://dfw.databases.api.rackspacecloud.com/v1.0/40806637803162\")\n                                                     .region(\"DFW\").build())\n                                   .endpoint(Endpoint.builder()\n                                                     .tenantId(\"40806637803162\")\n                                                     .publicURL(\"https://ord.databases.api.rackspacecloud.com/v1.0/40806637803162\")\n                                                     .region(\"ORD\").build()).build())\n                   .service(Service.builder().name(\"cloudServers\").type(\"compute\")\n                                   .endpoint(Endpoint.builder()\n                                                     .tenantId(\"40806637803162\")\n                                                     .publicURL(\"https://servers.api.rackspacecloud.com/v1.0/40806637803162\")\n                                                     .versionId(\"1.0\")\n                                                     .versionInfo(\"https://servers.api.rackspacecloud.com/v1.0\")\n                                                     .versionList(\"https://servers.api.rackspacecloud.com/\").build()).build())\n                   .service(Service.builder().name(\"cloudFiles\").type(\"object-store\")\n                                   .endpoint(Endpoint.builder()\n                                                     .tenantId(\"MossoCloudFS_dc1f419c-5059-4c87-a389-3f2e33a77b22\")\n                                                     .publicURL(\"https://storage101.dfw1.clouddrive.com/v1/MossoCloudFS_dc1f419c-5059-4c87-a389-3f2e33a77b22\")\n                                                     .internalURL(\"https://snet-storage101.dfw1.clouddrive.com/v1/MossoCloudFS_dc1f419c-5059-4c87-a389-3f2e33a77b22\")\n                                                     .region(\"DFW\").build()).build())\n                   .service(Service.builder().name(\"cloudServersOpenStack\").type(\"compute\")\n                                   .endpoint(Endpoint.builder()\n                                                     .tenantId(\"40806637803162\")\n                                                     .publicURL(\"https://dfw.servers.api.rackspacecloud.com/v2/40806637803162\")\n                                                     .versionInfo(\"https://dfw.servers.api.rackspacecloud.com/v2\")\n                                                     .versionList(\"https://dfw.servers.api.rackspacecloud.com/\")\n                                                     .versionId(\"2\")\n                                                     .region(\"DFW\").build()).build())\n                   .service(Service.builder().name(\"cloudLoadBalancers\").type(\"rax:load-balancer\")\n                                   .endpoint(Endpoint.builder()\n                                                     .tenantId(\"40806637803162\")\n                                                     .publicURL(\"https://ord.loadbalancers.api.rackspacecloud.com/v1.0/40806637803162\")\n                                                     .region(\"ORD\").build())\n                                   .endpoint(Endpoint.builder()\n                                                     .tenantId(\"40806637803162\")\n                                                     .publicURL(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/40806637803162\")\n                                                     .region(\"DFW\").build()).build())\n                   .service(Service.builder().name(\"cloudBlockStorage\").type(\"volume\")\n                                   .endpoint(Endpoint.builder()\n                                                     .tenantId(\"40806637803162\")\n                                                     .publicURL(\"https://dfw.blockstorage.api.rackspacecloud.com/v1/40806637803162\")\n                                                     .region(\"DFW\").build())\n                                   .endpoint(Endpoint.builder()\n                                                     .tenantId(\"40806637803162\")\n                                                     .publicURL(\"https://ord.blockstorage.api.rackspacecloud.com/v1/40806637803162\")\n                                                     .region(\"ORD\").build()).build())\n                   .service(Service.builder().name(\"cloudMonitoring\").type(\"rax:monitor\")\n                                   .endpoint(Endpoint.builder()\n                                                     .tenantId(\"40806637803162\")\n                                                     .publicURL(\"https://monitoring.api.rackspacecloud.com/v1.0/40806637803162\").build()).build())\n                   .service(Service.builder().name(\"cloudDNS\").type(\"rax:dns\")\n                                   .endpoint(Endpoint.builder()\n                                                     .tenantId(\"40806637803162\")\n                                                     .publicURL(\"https://dns.api.rackspacecloud.com/v1.0/40806637803162\").build()).build())\n                   .service(Service.builder().name(\"cloudFilesCDN\").type(\"rax:object-cdn\")\n                                   .endpoint(Endpoint.builder()\n                                                     .tenantId(\"MossoCloudFS_dc1f419c-5059-4c87-a389-3f2e33a77b22\")\n                                                     .publicURL(\"https://cdn1.clouddrive.com/v1/MossoCloudFS_dc1f419c-5059-4c87-a389-3f2e33a77b22\")\n                                                     .region(\"DFW\").build()).build())\n                   .service(Service.builder().name(\"cloudQueues\").type(\"rax:queues\")\n                                   .endpoint(Endpoint.builder()\n                                                     .tenantId(\"40806637803162\")\n                                                     .publicURL(\"https://dfw.queues.api.rackspacecloud.com/v1/40806637803162\")\n                                                     .internalURL(\"https://snet-dfw.queues.api.rackspacecloud.com/v1/40806637803162\")\n                                                     .region(\"DFW\").build())\n                                    .endpoint(Endpoint.builder()\n                                                     .tenantId(\"40806637803162\")\n                                                     .publicURL(\"https://ord.queues.api.rackspacecloud.com/v1/40806637803162\")\n                                                     .internalURL(\"https://snet-ord.queues.api.rackspacecloud.com/v1/40806637803162\")\n                                                     .region(\"ORD\").build()).build()).build();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/parse/ParseRackspaceApiMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.parse;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.openstack.keystone.v2_0.config.KeystoneParserModule;\nimport org.jclouds.openstack.keystone.v2_0.domain.ApiMetadata;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\", testName = \"ParseApiMetadataTest\")\npublic class ParseRackspaceApiMetadataTest extends BaseItemParserTest<ApiMetadata> {\n\n   @Override\n   public String resource() {\n      return \"/raxVersion.json\";\n   }\n\n   // http://docs.openstack.org/api/openstack-identity-service/2.0/content/Versions-d1e472.html\n   @Override\n   @SelectJson(\"version\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public ApiMetadata expected() {\n      return ApiMetadata.builder().id(\"v2.0\")\n            .links(ImmutableSet.of(Link.builder().relation(Link.Relation.SELF).href(URI.create(\"https://identity.api.rackspacecloud.com/v2.0\")).build(),\n                  Link.builder().relation(Link.Relation.DESCRIBEDBY).type(\"application/pdf\").href(URI.create(\"http://docs.rackspacecloud.com/auth/api/v2.0/auth-client-devguide-latest.pdf\")).build(),\n                  Link.builder().relation(Link.Relation.DESCRIBEDBY).type(\"application/vnd.sun.wadl+xml\").href(URI.create(\"http://docs.rackspacecloud.com/auth/api/v2.0/auth.wadl\")).build()\n            ))\n            .status(\"BETA\")\n            .updated(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2012-01-21T11:33:21-06:00\"))\n            .mediaTypes(ImmutableSet.of(\n                  org.jclouds.openstack.keystone.v2_0.domain.MediaType.builder().base(\"application/xml\").type(\"application/vnd.openstack.identity+xml;version=2.0\").build(),\n                  org.jclouds.openstack.keystone.v2_0.domain.MediaType.builder().base(\"application/json\").type(\"application/vnd.openstack.identity+json;version=2.0\").build()\n            ))\n            .build();\n   }\n\n   @Override\n   protected Injector injector() {\n      return Guice.createInjector(new GsonModule(), new KeystoneParserModule());\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/parse/ParseRackspaceCryptoTokenAccessTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.parse;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.openstack.keystone.v2_0.domain.Access;\nimport org.jclouds.openstack.keystone.v2_0.domain.Endpoint;\nimport org.jclouds.openstack.keystone.v2_0.domain.Role;\nimport org.jclouds.openstack.keystone.v2_0.domain.Service;\nimport org.jclouds.openstack.keystone.v2_0.domain.Tenant;\nimport org.jclouds.openstack.keystone.v2_0.domain.Token;\nimport org.jclouds.openstack.keystone.v2_0.domain.User;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ParseRackspaceCryptoTokenAccessTest\")\npublic class ParseRackspaceCryptoTokenAccessTest extends BaseItemParserTest<Access> {\n\n   @Override\n   public String resource() {\n      return \"/raxCryptoAuth.json\";\n   }\n\n   @Override\n   @SelectJson(\"access\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Access expected() {\n      return Access.builder()\n                   .token(Token.builder()\n                               .expires(new SimpleDateFormatDateService().iso8601DateParse(\"2012-06-06T20:56:47.000-05:00\"))\n                               .id(\"AADMTnolqiuwewdqwdqsdf2324f4234fndquipwou12e08_qw23f2e32f2qw4rf2432fddi_ar23d2q32p_DJOIASdd32d2323d23dqoiwjdaosiqowdijOAQIDJWqowid0aisjd_ajoisdjaoisdj1209ejdalo___qwdqwd---sdpoaqwdsaasdisdjw023d23q23edasd435gtf3g3w4egf4g4323efasdsdvsdvsasdvjmhfg43OINAOISndqaiosjkdq0w\")\n                               .tenant(Tenant.builder().id(\"40806637803162\").name(\"40806637803162\").build()).build())\n                   .user(User.builder()\n                             .id(\"54321\")\n                             .name(\"joe\")\n                             .role(Role.builder()\n                                       .id(\"3\")\n                                       .name(\"identity:user-admin\")\n                                       .description(\"User Admin Role.\").build()).build())\n                   .service(Service.builder().name(\"cloudDatabases\").type(\"rax:database\")\n                                   .endpoint(Endpoint.builder()\n                                                     .tenantId(\"40806637803162\")\n                                                     .publicURL(\"https://dfw.databases.api.rackspacecloud.com/v1.0/40806637803162\")\n                                                     .region(\"DFW\").build())\n                                   .endpoint(Endpoint.builder()\n                                                     .tenantId(\"40806637803162\")\n                                                     .publicURL(\"https://ord.databases.api.rackspacecloud.com/v1.0/40806637803162\")\n                                                     .region(\"ORD\").build()).build())\n                   .service(Service.builder().name(\"cloudServers\").type(\"compute\")\n                                   .endpoint(Endpoint.builder()\n                                                     .tenantId(\"40806637803162\")\n                                                     .publicURL(\"https://servers.api.rackspacecloud.com/v1.0/40806637803162\")\n                                                     .versionId(\"1.0\")\n                                                     .versionInfo(\"https://servers.api.rackspacecloud.com/v1.0\")\n                                                     .versionList(\"https://servers.api.rackspacecloud.com/\").build()).build())\n                   .service(Service.builder().name(\"cloudFiles\").type(\"object-store\")\n                                   .endpoint(Endpoint.builder()\n                                                     .tenantId(\"MossoCloudFS_dc1f419c-5059-4c87-a389-3f2e33a77b22\")\n                                                     .publicURL(\"https://storage101.dfw1.clouddrive.com/v1/MossoCloudFS_dc1f419c-5059-4c87-a389-3f2e33a77b22\")\n                                                     .internalURL(\"https://snet-storage101.dfw1.clouddrive.com/v1/MossoCloudFS_dc1f419c-5059-4c87-a389-3f2e33a77b22\")\n                                                     .region(\"DFW\").build()).build())\n                   .service(Service.builder().name(\"cloudServersOpenStack\").type(\"compute\")\n                                   .endpoint(Endpoint.builder()\n                                                     .tenantId(\"40806637803162\")\n                                                     .publicURL(\"https://dfw.servers.api.rackspacecloud.com/v2/40806637803162\")\n                                                     .versionInfo(\"https://dfw.servers.api.rackspacecloud.com/v2\")\n                                                     .versionList(\"https://dfw.servers.api.rackspacecloud.com/\")\n                                                     .versionId(\"2\")\n                                                     .region(\"DFW\").build()).build())\n                   .service(Service.builder().name(\"cloudLoadBalancers\").type(\"rax:load-balancer\")\n                                   .endpoint(Endpoint.builder()\n                                                     .tenantId(\"40806637803162\")\n                                                     .publicURL(\"https://ord.loadbalancers.api.rackspacecloud.com/v1.0/40806637803162\")\n                                                     .region(\"ORD\").build())\n                                   .endpoint(Endpoint.builder()\n                                                     .tenantId(\"40806637803162\")\n                                                     .publicURL(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/40806637803162\")\n                                                     .region(\"DFW\").build()).build())\n                   .service(Service.builder().name(\"cloudBlockStorage\").type(\"volume\")\n                                   .endpoint(Endpoint.builder()\n                                                     .tenantId(\"40806637803162\")\n                                                     .publicURL(\"https://dfw.blockstorage.api.rackspacecloud.com/v1/40806637803162\")\n                                                     .region(\"DFW\").build())\n                                   .endpoint(Endpoint.builder()\n                                                     .tenantId(\"40806637803162\")\n                                                     .publicURL(\"https://ord.blockstorage.api.rackspacecloud.com/v1/40806637803162\")\n                                                     .region(\"ORD\").build()).build())\n                   .service(Service.builder().name(\"cloudMonitoring\").type(\"rax:monitor\")\n                                   .endpoint(Endpoint.builder()\n                                                     .tenantId(\"40806637803162\")\n                                                     .publicURL(\"https://monitoring.api.rackspacecloud.com/v1.0/40806637803162\").build()).build())\n                   .service(Service.builder().name(\"cloudDNS\").type(\"rax:dns\")\n                                   .endpoint(Endpoint.builder()\n                                                     .tenantId(\"40806637803162\")\n                                                     .publicURL(\"https://dns.api.rackspacecloud.com/v1.0/40806637803162\").build()).build())\n                   .service(Service.builder().name(\"cloudFilesCDN\").type(\"rax:object-cdn\")\n                                   .endpoint(Endpoint.builder()\n                                                     .tenantId(\"MossoCloudFS_dc1f419c-5059-4c87-a389-3f2e33a77b22\")\n                                                     .publicURL(\"https://cdn1.clouddrive.com/v1/MossoCloudFS_dc1f419c-5059-4c87-a389-3f2e33a77b22\")\n                                                     .region(\"DFW\").build()).build())\n                   .service(Service.builder().name(\"cloudQueues\").type(\"rax:queues\")\n                                   .endpoint(Endpoint.builder()\n                                                     .tenantId(\"40806637803162\")\n                                                     .publicURL(\"https://dfw.queues.api.rackspacecloud.com/v1/40806637803162\")\n                                                     .internalURL(\"https://snet-dfw.queues.api.rackspacecloud.com/v1/40806637803162\")\n                                                     .region(\"DFW\").build())\n                                    .endpoint(Endpoint.builder()\n                                                     .tenantId(\"40806637803162\")\n                                                     .publicURL(\"https://ord.queues.api.rackspacecloud.com/v1/40806637803162\")\n                                                     .internalURL(\"https://snet-ord.queues.api.rackspacecloud.com/v1/40806637803162\")\n                                                     .region(\"ORD\").build()).build()).build();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/parse/ParseRandomEndpointVersionAccessTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v2_0.parse;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.openstack.keystone.v2_0.domain.Access;\nimport org.jclouds.openstack.keystone.v2_0.domain.Endpoint;\nimport org.jclouds.openstack.keystone.v2_0.domain.Role;\nimport org.jclouds.openstack.keystone.v2_0.domain.Service;\nimport org.jclouds.openstack.keystone.v2_0.domain.Tenant;\nimport org.jclouds.openstack.keystone.v2_0.domain.Token;\nimport org.jclouds.openstack.keystone.v2_0.domain.User;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ParseRandomEndpointVersionAccessTest\")\npublic class ParseRandomEndpointVersionAccessTest extends BaseItemParserTest<Access> {\n\n   @Override\n   public String resource() {\n      return \"/access_version_uids.json\";\n   }\n\n   @Override\n   @SelectJson(\"access\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Access expected() {\n      return Access.builder()\n                   .token(Token.builder()\n                               .expires(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2012-09-29T19:53:45Z\"))\n                               .id(\"b267e2e240624b108b1ed5bba6e5882e\")\n                               .tenant(Tenant.builder()\n                                              //  \"enabled\": true,\n                                             .id(\"82d8d2f865484776a1daf1e2245d3317\")\n                                             .name(\"demo\").enabled(true).build()).build())\n                    .service(Service.builder().type(\"compute\").name(\"nova\")\n                                    .endpoint(Endpoint.builder()\n                                                      .adminURL(\"http://10.10.10.10:8774/v2/82d8d2f865484776a1daf1e2245d3317\")\n                                                      .region(\"RegionOne\")\n                                                      .internalURL(\"http://10.10.10.10:8774/v2/82d8d2f865484776a1daf1e2245d3317\")\n                                                      .id(\"bb3ce9ccdc5045909882688b90cc3ff0\")\n                                                      .publicURL(\"http://10.10.10.10:8774/v2/82d8d2f865484776a1daf1e2245d3317\").build()).build())\n                    .service(Service.builder().type(\"s3\").name(\"s3\")\n                                    .endpoint(Endpoint.builder()\n                                                      .adminURL(\"http://10.10.10.10:3333\")\n                                                      .region(\"RegionOne\")\n                                                      .internalURL(\"http://10.10.10.10:3333\")\n                                                      .id(\"9646263f31ea4f499732c5e1370ecf5e\")\n                                                      .publicURL(\"http://10.10.10.10:3333\").build()).build())\n                    .service(Service.builder().type(\"image\").name(\"glance\")\n                                    .endpoint(Endpoint.builder()\n                                                      .adminURL(\"http://10.10.10.10:9292\")\n                                                      .region(\"RegionOne\")\n                                                      .internalURL(\"http://10.10.10.10:9292\")\n                                                      .id(\"aa5d0b2574824ba097dc07faacf3be65\")\n                                                      .publicURL(\"http://10.10.10.10:9292\").build()).build())\n                    .service(Service.builder().type(\"volume\").name(\"cinder\")\n                                    .endpoint(Endpoint.builder()\n                                                      .adminURL(\"http://10.10.10.10:8776/v1/82d8d2f865484776a1daf1e2245d3317\")\n                                                      .region(\"RegionOne\")\n                                                      .internalURL(\"http://10.10.10.10:8776/v1/82d8d2f865484776a1daf1e2245d3317\")\n                                                      .id(\"7679065b1405447eb5f1a38a6b99ccc0\")\n                                                      .publicURL(\"http://10.10.10.10:8776/v1/82d8d2f865484776a1daf1e2245d3317\").build()).build())\n                    .service(Service.builder().type(\"ec2\").name(\"ec2\")\n                                    .endpoint(Endpoint.builder()\n                                                      .adminURL(\"http://10.10.10.10:8773/services/Admin\")\n                                                      .region(\"RegionOne\")\n                                                      .internalURL(\"http://10.10.10.10:8773/services/Cloud\")\n                                                      .id(\"22b007f023fb4c42be094916eb2bf18b\")\n                                                      .publicURL(\"http://10.10.10.10:8773/services/Cloud\").build()).build())\n                    .service(Service.builder().type(\"identity\").name(\"keystone\")\n                                    .endpoint(Endpoint.builder()\n                                                      .adminURL(\"http://10.10.10.10:35357/v2.0\")\n                                                      .region(\"RegionOne\")\n                                                      .internalURL(\"http://10.10.10.10:5000/v2.0\")\n                                                      .id(\"57ee5fb4f9a840f3b965909681d0fc53\")\n                                                      .publicURL(\"http://10.10.10.10:5000/v2.0\").build()).build())\n                   .user(User.builder()\n                             .id(\"ca248caf55844c14a4876c22112bbbb9\")\n                             .name(\"demo\")\n//                             .username(\"demo\")\n                             .role(Role.builder().name(\"Member\").build()).build()).build();\n//                   \"metadata\": {\n//                       \"is_admin\": 0,\n//                       \"roles\": [\"1f697d8e3ace4f5a80f7701e554ee5d9\"]\n//                   }\n\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v3/auth/V3AuthenticationApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v3.auth;\n\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.Properties;\n\nimport org.jclouds.openstack.keystone.auth.domain.PasswordCredentials;\nimport org.jclouds.openstack.keystone.auth.domain.TenantOrDomainAndCredentials;\nimport org.jclouds.openstack.keystone.auth.domain.TokenCredentials;\nimport org.jclouds.openstack.keystone.auth.domain.ApiAccessKeyCredentials;\nimport org.jclouds.openstack.keystone.v3.internal.BaseV3KeystoneApiLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.Iterables;\n\n@Test(groups = \"live\", testName = \"V3AuthenticationApiLiveTest\")\npublic class V3AuthenticationApiLiveTest extends BaseV3KeystoneApiLiveTest {\n\n   private String tenant;\n   private String user;\n\n   @Override\n   protected Properties setupProperties() {\n      Properties properties = super.setupProperties();\n      tenant = Iterables.get(Splitter.on(\":\").split(identity), 0);\n      user = Iterables.get(Splitter.on(\":\").split(identity), 1);\n      return properties;\n   }\n\n   public void testAuthenticatePassword() {\n      assertNotNull(authenticationApi.authenticatePassword(TenantOrDomainAndCredentials.<PasswordCredentials> builder()\n            .tenantOrDomainName(tenant).scope(\"unscoped\")\n            .credentials(PasswordCredentials.builder().username(user).password(credential).build()).build()));\n   }\n\n   public void testAuthenticateToken() {\n      assertNotNull(authenticationApi.authenticateToken(TenantOrDomainAndCredentials.<TokenCredentials> builder()\n            .tenantOrDomainName(tenant).scope(\"unscoped\")\n            .credentials(TokenCredentials.builder().id(token.get()).build()).build()));\n   }\n\n   public void testAuthenticateAccessKey() {\n      assertNotNull(authenticationApi.authenticateAccessKey(TenantOrDomainAndCredentials.<ApiAccessKeyCredentials> builder()\n            .tenantOrDomainName(tenant).scope(\"unscoped\")\n            .credentials(ApiAccessKeyCredentials.builder().accessKey(identity).secretKey(credential).build()).build()));\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v3/auth/V3AuthenticationApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v3.auth;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.openstack.keystone.auth.domain.ApiAccessKeyCredentials;\nimport org.jclouds.openstack.keystone.auth.domain.AuthInfo;\nimport org.jclouds.openstack.keystone.auth.domain.PasswordCredentials;\nimport org.jclouds.openstack.keystone.auth.domain.TenantOrDomainAndCredentials;\nimport org.jclouds.openstack.keystone.auth.domain.TokenCredentials;\nimport org.jclouds.openstack.keystone.v3.domain.Token;\nimport org.jclouds.openstack.keystone.v3.internal.BaseV3KeystoneApiMockTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"V3AuthenticationApiMockTest\", singleThreaded = true)\npublic class V3AuthenticationApiMockTest extends BaseV3KeystoneApiMockTest {\n\n   public void testAuthenticatePassword() throws InterruptedException {\n\n      TenantOrDomainAndCredentials<PasswordCredentials> credentials = TenantOrDomainAndCredentials\n            .<PasswordCredentials> builder().tenantOrDomainName(\"domain\").scope(\"unscoped\")\n            .credentials(PasswordCredentials.builder().username(\"identity\").password(\"credential\").build()).build();\n\n      checkTokenResult(credentials, \"/v3/auth-password.json\");\n   }\n\n   public void testAuthenticatePasswordScoped() throws InterruptedException {\n\n      TenantOrDomainAndCredentials<PasswordCredentials> credentials = TenantOrDomainAndCredentials\n            .<PasswordCredentials> builder().tenantOrDomainName(\"domain\").scope(\"projectId:1234567890\")\n            .credentials(PasswordCredentials.builder().username(\"identity\").password(\"credential\").build()).build();\n\n      checkTokenResult(credentials, \"/v3/auth-password-scoped.json\");\n   }\n\n   public void testAuthenticatePasswordProjectScopedIdDomainBackwardsCompat() throws InterruptedException {\n      // See JCLOUDS-1414, before add of KeystoneProperties.PROJECT_DOMAIN,\n      // TENANT_ID was not used as domain for project-scoped with id\n      // => Unit test only for backward compatibility (is the same as\n      // 'testAuthenticatePasswordScoped' with TENANT-ID in addition)\n\n      TenantOrDomainAndCredentials<PasswordCredentials> credentials = TenantOrDomainAndCredentials\n            .<PasswordCredentials> builder().tenantOrDomainName(\"domain\").scope(\"projectId:1234567890\")\n            .tenantOrDomainId(\"somethingShouldNotBeUsed\")\n            .credentials(PasswordCredentials.builder().username(\"identity\").password(\"credential\").build()).build();\n\n      checkTokenResult(credentials, \"/v3/auth-password-scoped.json\");\n   }\n\n   public void testAuthenticatePasswordProjectScopedNameDomainBackwardsCompat() throws InterruptedException {\n      // See JCLOUDS-1414, before add of KeystoneProperties.PROJECT_DOMAIN,\n      // domain-id of project-scoped could be filled with TENANT_ID\n      // => Unit test only for backward compatibility\n\n      TenantOrDomainAndCredentials<PasswordCredentials> credentials = TenantOrDomainAndCredentials\n            .<PasswordCredentials> builder().tenantOrDomainName(\"domain\").scope(\"project:my-project\")\n            .tenantOrDomainId(\"default\")\n            .credentials(PasswordCredentials.builder().username(\"identity\").password(\"credential\").build()).build();\n\n      checkTokenResult(credentials, \"/v3/auth-password-project-scoped-name-domain-backwards-compat.json\");\n   }\n\n   public void testAuthenticatePasswordProjectScopedIdDomainId() throws InterruptedException {\n\n      TenantOrDomainAndCredentials<PasswordCredentials> credentials = TenantOrDomainAndCredentials\n            .<PasswordCredentials> builder().tenantOrDomainName(\"domain\").scope(\"projectId:42-project-42\")\n            .projectDomainId(\"42-domain-42\")\n            .credentials(PasswordCredentials.builder().username(\"identity\").password(\"credential\").build()).build();\n\n      checkTokenResult(credentials, \"/v3/auth-password-project-scoped-id-domain-id.json\");\n   }\n\n   public void testAuthenticatePasswordProjectScopedIdDomainName() throws InterruptedException {\n\n      TenantOrDomainAndCredentials<PasswordCredentials> credentials = TenantOrDomainAndCredentials\n            .<PasswordCredentials> builder().tenantOrDomainName(\"domain\").scope(\"projectId:42\")\n            .projectDomainName(\"default\")\n            .credentials(PasswordCredentials.builder().username(\"identity\").password(\"credential\").build()).build();\n\n      checkTokenResult(credentials, \"/v3/auth-password-project-scoped-id-domain-name.json\");\n   }\n\n   public void testAuthenticatePasswordProjectScopedNameDomainId() throws InterruptedException {\n\n      TenantOrDomainAndCredentials<PasswordCredentials> credentials = TenantOrDomainAndCredentials\n            .<PasswordCredentials> builder().tenantOrDomainName(\"domain\").scope(\"project:my-project\")\n            .projectDomainId(\"42\")\n            .credentials(PasswordCredentials.builder().username(\"identity\").password(\"credential\").build()).build();\n\n      checkTokenResult(credentials, \"/v3/auth-password-project-scoped-name-domain-id.json\");\n   }\n\n   public void testAuthenticatePasswordProjectScopedNameDomainName() throws InterruptedException {\n\n      TenantOrDomainAndCredentials<PasswordCredentials> credentials = TenantOrDomainAndCredentials\n            .<PasswordCredentials> builder().tenantOrDomainName(\"domain\").scope(\"project:my-project\")\n            .projectDomainName(\"default\")\n            .credentials(PasswordCredentials.builder().username(\"identity\").password(\"credential\").build()).build();\n\n      checkTokenResult(credentials, \"/v3/auth-password-project-scoped-name-domain-name.json\");\n   }\n\n   public void testAuthenticateToken() throws InterruptedException {\n\n      TenantOrDomainAndCredentials<TokenCredentials> credentials = TenantOrDomainAndCredentials\n            .<TokenCredentials> builder().tenantOrDomainName(\"domain\").scope(\"unscoped\")\n            .credentials(TokenCredentials.builder().id(\"token\").build()).build();\n\n      checkTokenResult(credentials, \"/v3/auth-token.json\");\n   }\n\n   public void testAuthenticateTokenScoped() throws InterruptedException {\n\n      TenantOrDomainAndCredentials<TokenCredentials> credentials = TenantOrDomainAndCredentials\n            .<TokenCredentials> builder().tenantOrDomainName(\"domain\").scope(\"domain:mydomain\")\n            .credentials(TokenCredentials.builder().id(\"token\").build()).build();\n\n      checkTokenResult(credentials, \"/v3/auth-token-scoped.json\");\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   private void checkTokenResult(TenantOrDomainAndCredentials<?> credentials, String json) throws InterruptedException {\n      server.enqueue(jsonResponse(\"/v3/token.json\"));\n\n      AuthInfo authInfo = null;\n\n      if (credentials.credentials() instanceof PasswordCredentials) {\n         authInfo = authenticationApi\n               .authenticatePassword((TenantOrDomainAndCredentials<PasswordCredentials>) credentials);\n      } else if (credentials.credentials() instanceof TokenCredentials) {\n         authInfo = authenticationApi.authenticateToken((TenantOrDomainAndCredentials<TokenCredentials>) credentials);\n      } else if (credentials.credentials() instanceof ApiAccessKeyCredentials) {\n         authInfo = authenticationApi\n               .authenticateAccessKey((TenantOrDomainAndCredentials<ApiAccessKeyCredentials>) credentials);\n      } else {\n         throw new IllegalArgumentException(String.format(\"Unsupported authentication method with class: %s\",\n               credentials.credentials().getClass().getName()));\n      }\n\n      assertTrue(authInfo instanceof Token);\n      assertEquals(authInfo, tokenFromResource(\"/v3/token.json\"));\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"POST\", \"/auth/tokens\", stringFromResource(json));\n   }\n\n   public void testAuthenticateAccessKey() throws InterruptedException {\n\n      TenantOrDomainAndCredentials<ApiAccessKeyCredentials> credentials = TenantOrDomainAndCredentials\n            .<ApiAccessKeyCredentials> builder().tenantOrDomainName(\"domain\").scope(\"unscoped\")\n            .credentials(ApiAccessKeyCredentials.builder().accessKey(\"identity\").secretKey(\"credential\").build()).build();\n\n\n      checkTokenResult(credentials, \"/v3/auth-accesskey.json\");\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v3/features/AuthApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v3.features;\n\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.openstack.keystone.v3.internal.BaseV3KeystoneApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"AuthApiLiveTest\")\npublic class AuthApiLiveTest extends BaseV3KeystoneApiLiveTest {\n\n   public void testIsTokenValid() {\n      assertTrue(api().isValid(token.get()));\n   }\n\n   public void testGetToken() {\n      assertNotNull(api().get(token.get()));\n   }\n\n   private AuthApi api() {\n      return api.getAuthApi();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v3/features/AuthApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v3.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport okhttp3.mockwebserver.RecordedRequest;\n\nimport org.jclouds.openstack.keystone.v3.domain.Token;\nimport org.jclouds.openstack.keystone.v3.domain.User;\nimport org.jclouds.openstack.keystone.v3.internal.BaseV3KeystoneApiMockTest;\nimport org.testng.annotations.Test;\n\n\n@Test(groups = \"unit\", testName = \"AuthApiMockTest\", singleThreaded = true)\npublic class AuthApiMockTest extends BaseV3KeystoneApiMockTest {\n\n   public void testGetToken() throws InterruptedException {\n      enqueueAuthentication(server);\n      server.enqueue(jsonResponse(\"/v3/token.json\"));\n\n      Token token = api.getAuthApi().get(authToken);\n\n      assertEquals(token, tokenFromResource(\"/v3/token.json\"));\n\n      assertEquals(server.getRequestCount(), 2);\n      assertAuthentication(server);\n      RecordedRequest request = assertSent(server, \"GET\", \"/auth/tokens\");\n      assertEquals(request.getHeader(\"X-Subject-Token\"), authToken);\n   }\n\n   public void testGetTokenReturns404() throws InterruptedException {\n      enqueueAuthentication(server);\n      server.enqueue(response404());\n\n      Token token = api.getAuthApi().get(\"foo\");\n      assertNull(token);\n\n      assertEquals(server.getRequestCount(), 2);\n      assertAuthentication(server);\n      RecordedRequest request = assertSent(server, \"GET\", \"/auth/tokens\");\n      assertEquals(request.getHeader(\"X-Subject-Token\"), \"foo\");\n   }\n   \n   public void testIsValidToken() throws InterruptedException {\n      enqueueAuthentication(server);\n      server.enqueue(response204());\n\n      boolean valid = api.getAuthApi().isValid(authToken);\n      assertTrue(valid);\n\n      assertEquals(server.getRequestCount(), 2);\n      assertAuthentication(server);\n      RecordedRequest request = assertSent(server, \"HEAD\", \"/auth/tokens\");\n      assertEquals(request.getHeader(\"X-Subject-Token\"), authToken);\n   }\n\n   public void testIsValidTokenReturns404() throws InterruptedException {\n      enqueueAuthentication(server);\n      server.enqueue(response404());\n\n      boolean valid = api.getAuthApi().isValid(\"foo\");\n      assertFalse(valid);\n\n      assertEquals(server.getRequestCount(), 2);\n      assertAuthentication(server);\n      RecordedRequest request = assertSent(server, \"HEAD\", \"/auth/tokens\");\n      assertEquals(request.getHeader(\"X-Subject-Token\"), \"foo\");\n   }\n   \n   public void testGetUserOfToken() throws InterruptedException {\n      enqueueAuthentication(server);\n      server.enqueue(jsonResponse(\"/v3/token.json\"));\n\n      User user = api.getAuthApi().getUserOfToken(authToken);\n\n      assertEquals(user, tokenFromResource(\"/v3/token.json\").user());\n\n      assertEquals(server.getRequestCount(), 2);\n      assertAuthentication(server);\n      RecordedRequest request = assertSent(server, \"GET\", \"/auth/tokens\");\n      assertEquals(request.getHeader(\"X-Subject-Token\"), authToken);\n   }\n\n   public void testGetUserOfTokenReturns404() throws InterruptedException {\n      enqueueAuthentication(server);\n      server.enqueue(response404());\n\n      User user = api.getAuthApi().getUserOfToken(\"foo\");\n      assertNull(user);\n\n      assertEquals(server.getRequestCount(), 2);\n      assertAuthentication(server);\n      RecordedRequest request = assertSent(server, \"GET\", \"/auth/tokens\");\n      assertEquals(request.getHeader(\"X-Subject-Token\"), \"foo\");\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v3/features/CatalogApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v3.features;\n\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.List;\n\nimport org.jclouds.openstack.keystone.v3.domain.Endpoint;\nimport org.jclouds.openstack.keystone.v3.internal.BaseV3KeystoneApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"CatalogApiLiveTest\")\npublic class CatalogApiLiveTest extends BaseV3KeystoneApiLiveTest {\n\n   @Test\n   public void testTenants() {\n      List<Endpoint> result = api.getCatalogApi().endpoints();\n      assertNotNull(result);\n      assertFalse(result.isEmpty());\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v3/features/CatalogApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v3.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.List;\n\nimport org.jclouds.openstack.keystone.v3.domain.Endpoint;\nimport org.jclouds.openstack.keystone.v3.internal.BaseV3KeystoneApiMockTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"CatalogApiMockTest\", singleThreaded = true)\npublic class CatalogApiMockTest extends BaseV3KeystoneApiMockTest {\n\n   public void testListEndpoints() throws InterruptedException {\n      enqueueAuthentication(server);\n      server.enqueue(jsonResponse(\"/v3/endpoints.json\"));\n\n      List<Endpoint> endpoints = api.getCatalogApi().endpoints();\n      assertFalse(endpoints.isEmpty());\n      \n      assertEquals(server.getRequestCount(), 2);\n      assertAuthentication(server);\n      assertSent(server, \"GET\", \"/endpoints\");\n   }\n\n   public void testListEndpointsReturns404() throws InterruptedException {\n      enqueueAuthentication(server);\n      server.enqueue(response404());\n\n      List<Endpoint> endpoints = api.getCatalogApi().endpoints();\n      assertTrue(endpoints.isEmpty());\n      \n      assertEquals(server.getRequestCount(), 2);\n      assertAuthentication(server);\n      assertSent(server, \"GET\", \"/endpoints\");\n   }\n   \n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v3/features/ProjectApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v3.features;\n\nimport static com.google.common.collect.Iterables.any;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\n\nimport org.jclouds.openstack.keystone.v3.domain.Project;\nimport org.jclouds.openstack.keystone.v3.internal.BaseV3KeystoneApiLiveTest;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"live\", testName = \"ProjectApiLiveTest\", singleThreaded = true)\npublic class ProjectApiLiveTest extends BaseV3KeystoneApiLiveTest {\n\n   private Project project;\n   \n   @BeforeClass\n   public void createTestProject() {\n      project = api().create(getClass().getSimpleName(), null, true, false, null, null);\n      assertNotNull(project.id());\n   }\n   \n   @Test\n   public void testListProjects() {\n      assertTrue(any(api().list(), new Predicate<Project>() {\n         @Override\n         public boolean apply(Project input) {\n            return input.id().equals(project.id());\n         }\n      }));\n   }\n   \n   @Test\n   public void testGetProject() {\n      assertNotNull(api().get(project.id()));\n   }\n   \n   @Test\n   public void testUpdateProject() {\n      Project updated = api().get(project.id());\n      api().update(project.id(), updated.toBuilder().description(\"Updated\").build());\n      project = api().get(project.id());\n      assertEquals(project.description(), \"Updated\");\n   }\n   \n   @Test\n   public void testSetAndListTags() {\n      api().setTags(project.id(), ImmutableSet.of(\"foo\", \"bar\"));\n      Set<String> projectTags = api().listTags(project.id());\n      assertEquals(projectTags, ImmutableSet.of(\"foo\", \"bar\"));\n   }\n   \n   @Test(dependsOnMethods = \"testSetAndListTags\")\n   public void testHasTag() {\n      assertTrue(api().hasTag(project.id(), \"foo\"));\n   }\n   \n   @Test(dependsOnMethods = \"testSetAndListTags\")\n   public void testAddTag() {\n      api().addTag(project.id(), \"three\");\n      assertTrue(api().hasTag(project.id(), \"three\"));\n   }\n   \n   @Test(dependsOnMethods = \"testSetAndListTags\")\n   public void testRemoveTag() {\n      api().removeTag(project.id(), \"bar\");\n      assertFalse(api().hasTag(project.id(), \"bar\"));\n   }\n   \n   @Test(dependsOnMethods = \"testRemoveTag\")\n   public void testRemoveAllTags() {\n      api().removeAllTags(project.id());\n      assertTrue(api().listTags(project.id()).isEmpty());\n   }\n   \n   @AfterClass(alwaysRun = true)\n   public void deleteProject() {\n      assertTrue(api().delete(project.id()));\n   }\n   \n   private ProjectApi api() {\n      return api.getProjectApi();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v3/features/ProjectApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v3.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.List;\nimport java.util.Set;\n\nimport okhttp3.mockwebserver.MockResponse;\n\nimport org.jclouds.openstack.keystone.v3.domain.Project;\nimport org.jclouds.openstack.keystone.v3.internal.BaseV3KeystoneApiMockTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n\n@Test(groups = \"unit\", testName = \"ProjectApiMockTest\", singleThreaded = true)\npublic class ProjectApiMockTest extends BaseV3KeystoneApiMockTest {\n\n   public void testListProjects() throws InterruptedException {\n      enqueueAuthentication(server);\n      server.enqueue(jsonResponse(\"/v3/projects.json\").setResponseCode(201));\n\n      List<Project> projects = api.getProjectApi().list();\n      assertFalse(projects.isEmpty());\n\n      assertEquals(server.getRequestCount(), 2);\n      assertAuthentication(server);\n      assertSent(server, \"GET\", \"/projects\");\n   }\n\n   public void testListProjectsReturns404() throws InterruptedException {\n      enqueueAuthentication(server);\n      server.enqueue(response404());\n\n      List<Project> projects = api.getProjectApi().list();\n      assertTrue(projects.isEmpty());\n\n      assertEquals(server.getRequestCount(), 2);\n      assertAuthentication(server);\n      assertSent(server, \"GET\", \"/projects\");\n   }\n\n   public void testGetProject() throws InterruptedException {\n      enqueueAuthentication(server);\n      server.enqueue(jsonResponse(\"/v3/project.json\"));\n\n      Project project = api.getProjectApi().get(\"2f9b30f706bc45d7923e055567be2e98\");\n      assertNotNull(project);\n\n      assertEquals(server.getRequestCount(), 2);\n      assertAuthentication(server);\n      assertSent(server, \"GET\", \"/projects/2f9b30f706bc45d7923e055567be2e98\");\n   }\n\n   public void testGetProjectReturns404() throws InterruptedException {\n      enqueueAuthentication(server);\n      server.enqueue(response404());\n\n      Project project = api.getProjectApi().get(\"2f9b30f706bc45d7923e055567be2e98\");\n      assertNull(project);\n\n      assertEquals(server.getRequestCount(), 2);\n      assertAuthentication(server);\n      assertSent(server, \"GET\", \"/projects/2f9b30f706bc45d7923e055567be2e98\");\n   }\n\n   public void testCreateProject() throws InterruptedException {\n      enqueueAuthentication(server);\n      server.enqueue(jsonResponse(\"/v3/project.json\"));\n\n      Project project = api.getProjectApi().create(\"foo\", null, true, false, null, null);\n      assertNotNull(project);\n\n      assertEquals(server.getRequestCount(), 2);\n      assertAuthentication(server);\n      assertSent(server, \"POST\", \"/projects\", \"{\\\"project\\\":{\\\"is_domain\\\":false,\\\"enabled\\\":true,\\\"name\\\":\\\"foo\\\"}}\");\n   }\n\n   public void testUpdateProject() throws InterruptedException {\n      enqueueAuthentication(server);\n      server.enqueue(jsonResponse(\"/v3/project.json\"));\n\n      Project project = api.getProjectApi().update(\"2f9b30f706bc45d7923e055567be2e98\",\n            Project.builder().name(\"foo\").build());\n      assertNotNull(project);\n\n      assertEquals(server.getRequestCount(), 2);\n      assertAuthentication(server);\n      assertSent(server, \"PATCH\", \"/projects/2f9b30f706bc45d7923e055567be2e98\",\n            \"{\\\"project\\\":{\\\"is_domain\\\":false,\\\"enabled\\\":true,\\\"name\\\":\\\"foo\\\"}}\");\n   }\n\n   public void testDeleteProject() throws InterruptedException {\n      enqueueAuthentication(server);\n      server.enqueue(response204());\n\n      boolean deleted = api.getProjectApi().delete(\"2f9b30f706bc45d7923e055567be2e98\");\n      assertTrue(deleted);\n\n      assertEquals(server.getRequestCount(), 2);\n      assertAuthentication(server);\n      assertSent(server, \"DELETE\", \"/projects/2f9b30f706bc45d7923e055567be2e98\");\n   }\n\n   public void testDeleteProjectReturns404() throws InterruptedException {\n      enqueueAuthentication(server);\n      server.enqueue(response404());\n\n      boolean deleted = api.getProjectApi().delete(\"2f9b30f706bc45d7923e055567be2e98\");\n      assertFalse(deleted);\n\n      assertEquals(server.getRequestCount(), 2);\n      assertAuthentication(server);\n      assertSent(server, \"DELETE\", \"/projects/2f9b30f706bc45d7923e055567be2e98\");\n   }\n\n   public void testListTags() throws InterruptedException {\n      enqueueAuthentication(server);\n      server.enqueue(new MockResponse().setBody(\"{\\\"tags\\\":[\\\"foo\\\",\\\"bar\\\"]}\"));\n\n      Set<String> tags = api.getProjectApi().listTags(\"2f9b30f706bc45d7923e055567be2e98\");\n      assertEquals(tags, ImmutableSet.of(\"foo\", \"bar\"));\n\n      assertEquals(server.getRequestCount(), 2);\n      assertAuthentication(server);\n      assertSent(server, \"GET\", \"/projects/2f9b30f706bc45d7923e055567be2e98/tags\");\n   }\n\n   public void testHasTag() throws InterruptedException {\n      enqueueAuthentication(server);\n      server.enqueue(response204());\n\n      boolean hasTag = api.getProjectApi().hasTag(\"2f9b30f706bc45d7923e055567be2e98\", \"foo\");\n      assertTrue(hasTag);\n\n      assertEquals(server.getRequestCount(), 2);\n      assertAuthentication(server);\n      assertSent(server, \"HEAD\", \"/projects/2f9b30f706bc45d7923e055567be2e98/tags/foo\");\n   }\n\n   public void testAddTag() throws InterruptedException {\n      enqueueAuthentication(server);\n      server.enqueue(response201());\n\n      api.getProjectApi().addTag(\"2f9b30f706bc45d7923e055567be2e98\", \"foo\");\n\n      assertEquals(server.getRequestCount(), 2);\n      assertAuthentication(server);\n      assertSent(server, \"PUT\", \"/projects/2f9b30f706bc45d7923e055567be2e98/tags/foo\");\n   }\n\n   public void testRemoveTag() throws InterruptedException {\n      enqueueAuthentication(server);\n      server.enqueue(response204());\n\n      api.getProjectApi().removeTag(\"2f9b30f706bc45d7923e055567be2e98\", \"foo\");\n\n      assertEquals(server.getRequestCount(), 2);\n      assertAuthentication(server);\n      assertSent(server, \"DELETE\", \"/projects/2f9b30f706bc45d7923e055567be2e98/tags/foo\");\n   }\n\n   public void testSetTags() throws InterruptedException {\n      enqueueAuthentication(server);\n      server.enqueue(new MockResponse().setBody(\"{\\\"tags\\\":[\\\"foo\\\",\\\"bar\\\"]}\"));\n\n      api.getProjectApi().setTags(\"2f9b30f706bc45d7923e055567be2e98\", ImmutableSet.of(\"foo\", \"bar\"));\n\n      assertEquals(server.getRequestCount(), 2);\n      assertAuthentication(server);\n      assertSent(server, \"PUT\", \"/projects/2f9b30f706bc45d7923e055567be2e98/tags\", \"{\\\"tags\\\":[\\\"foo\\\",\\\"bar\\\"]}\");\n   }\n   \n   public void testRemoveAllTags() throws InterruptedException {\n      enqueueAuthentication(server);\n      server.enqueue(response204());\n\n      api.getProjectApi().removeAllTags(\"2f9b30f706bc45d7923e055567be2e98\");\n\n      assertEquals(server.getRequestCount(), 2);\n      assertAuthentication(server);\n      assertSent(server, \"DELETE\", \"/projects/2f9b30f706bc45d7923e055567be2e98/tags\");\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v3/features/RegionApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v3.features;\n\nimport static com.google.common.collect.Iterables.any;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.openstack.keystone.v3.domain.Region;\nimport org.jclouds.openstack.keystone.v3.internal.BaseV3KeystoneApiLiveTest;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\n\n@Test(groups = \"live\", testName = \"RegionApiLiveTest\", singleThreaded = true)\npublic class RegionApiLiveTest extends BaseV3KeystoneApiLiveTest {\n\n   private Region region;\n   \n   @BeforeClass\n   public void createTestRegion() {\n      region = api().create(getClass().getSimpleName(), null, null);\n      assertEquals(region.id(), getClass().getSimpleName());\n   }\n   \n   @Test\n   public void testListRegions() {\n      assertTrue(any(api().list(), new Predicate<Region>() {\n         @Override\n         public boolean apply(Region input) {\n            return input.id().equals(region.id());\n         }\n      }));\n   }\n   \n   @Test\n   public void testGetRegion() {\n      assertNotNull(api().get(region.id()));\n   }\n   \n   @Test\n   public void testUpdateRegion() {\n      api().update(region.id(), \"Updated\", null);\n      region = api().get(region.id());\n      assertEquals(region.description(), \"Updated\");\n   }\n   \n   @AfterClass(alwaysRun = true)\n   public void deleteRegion() {\n      assertTrue(api().delete(region.id()));\n   }\n   \n   private RegionApi api() {\n      return api.getRegionApi();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v3/features/RegionApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v3.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.List;\n\nimport org.jclouds.openstack.keystone.v3.domain.Region;\nimport org.jclouds.openstack.keystone.v3.internal.BaseV3KeystoneApiMockTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"RegionApiMockTest\", singleThreaded = true)\npublic class RegionApiMockTest extends BaseV3KeystoneApiMockTest {\n\n   public void testListRegions() throws InterruptedException {\n      enqueueAuthentication(server);\n      server.enqueue(jsonResponse(\"/v3/regions.json\"));\n\n      List<Region> regions = api.getRegionApi().list();\n      assertFalse(regions.isEmpty());\n\n      assertEquals(server.getRequestCount(), 2);\n      assertAuthentication(server);\n      assertSent(server, \"GET\", \"/regions\");\n   }\n\n   public void testListRegionsReturns404() throws InterruptedException {\n      enqueueAuthentication(server);\n      server.enqueue(response404());\n\n      List<Region> regions = api.getRegionApi().list();\n      assertTrue(regions.isEmpty());\n\n      assertEquals(server.getRequestCount(), 2);\n      assertAuthentication(server);\n      assertSent(server, \"GET\", \"/regions\");\n   }\n\n   public void testGetRegion() throws InterruptedException {\n      enqueueAuthentication(server);\n      server.enqueue(jsonResponse(\"/v3/region.json\"));\n\n      Region region = api.getRegionApi().get(\"RegionOne\");\n      assertNotNull(region);\n\n      assertEquals(server.getRequestCount(), 2);\n      assertAuthentication(server);\n      assertSent(server, \"GET\", \"/regions/RegionOne\");\n   }\n\n   public void testGetRegionReturns404() throws InterruptedException {\n      enqueueAuthentication(server);\n      server.enqueue(response404());\n\n      Region region = api.getRegionApi().get(\"RegionOne\");\n      assertNull(region);\n\n      assertEquals(server.getRequestCount(), 2);\n      assertAuthentication(server);\n      assertSent(server, \"GET\", \"/regions/RegionOne\");\n   }\n\n   public void testCreateRegion() throws InterruptedException {\n      enqueueAuthentication(server);\n      server.enqueue(jsonResponse(\"/v3/region.json\"));\n\n      Region region = api.getRegionApi().create(\"RegionOne\", \"Description\", \"12345\");\n      assertNotNull(region);\n\n      assertEquals(server.getRequestCount(), 2);\n      assertAuthentication(server);\n      assertSent(server, \"POST\", \"/regions\",\n            \"{\\\"region\\\":{\\\"id\\\":\\\"RegionOne\\\",\\\"description\\\":\\\"Description\\\",\\\"parent_region_id\\\":\\\"12345\\\"}}\");\n   }\n\n   public void testUpdateRegion() throws InterruptedException {\n      enqueueAuthentication(server);\n      server.enqueue(jsonResponse(\"/v3/region.json\"));\n\n      Region region = api.getRegionApi().update(\"RegionOne\", \"Updated\", null);\n      assertNotNull(region);\n\n      assertEquals(server.getRequestCount(), 2);\n      assertAuthentication(server);\n      assertSent(server, \"PATCH\", \"/regions/RegionOne\", \"{\\\"region\\\":{\\\"description\\\":\\\"Updated\\\"}}\");\n   }\n\n   public void testDeleteRegion() throws InterruptedException {\n      enqueueAuthentication(server);\n      server.enqueue(response204());\n\n      boolean deleted = api.getRegionApi().delete(\"RegionOne\");\n      assertTrue(deleted);\n\n      assertEquals(server.getRequestCount(), 2);\n      assertAuthentication(server);\n      assertSent(server, \"DELETE\", \"/regions/RegionOne\");\n   }\n\n   public void testDeleteRegionReturns404() throws InterruptedException {\n      enqueueAuthentication(server);\n      server.enqueue(response404());\n\n      boolean deleted = api.getRegionApi().delete(\"RegionOne\");\n      assertFalse(deleted);\n\n      assertEquals(server.getRequestCount(), 2);\n      assertAuthentication(server);\n      assertSent(server, \"DELETE\", \"/regions/RegionOne\");\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v3/features/UserApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v3.features;\n\nimport static com.google.common.collect.Iterables.any;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.openstack.keystone.v3.domain.User;\nimport org.jclouds.openstack.keystone.v3.internal.BaseV3KeystoneApiLiveTest;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\n\n@Test(groups = \"live\", testName = \"UserApiLiveTest\", singleThreaded = true)\npublic class UserApiLiveTest extends BaseV3KeystoneApiLiveTest {\n\n   private User user;\n   \n   @BeforeClass\n   public void createTestUser() {\n      user = api().create(getClass().getSimpleName(), \"p4ssw0rd\", true, null, null);\n      assertNotNull(user);\n   }\n   \n   @Test\n   public void testListUsers() {\n      assertTrue(any(api().list(), new Predicate<User>() {\n         @Override\n         public boolean apply(User input) {\n            return input.id().equals(user.id());\n         }\n      }));\n   }\n   \n   @Test\n   public void testGetUser() {\n      assertNotNull(api().get(user.id()));\n   }\n   \n   @Test\n   public void testUpdateUser() {\n      api().update(user.id(), \"Updated\", null, null, null, null);\n      user = api().get(user.id());\n      assertEquals(user.name(), \"Updated\");\n   }\n   \n   @Test\n   public void testListGroups() {\n      assertNotNull(api().listGroups(user.id()));\n   }\n   \n   @Test\n   public void testListProjects() {\n      assertNotNull(api().listProjects(user.id()));\n   }\n   \n   @Test\n   public void testChangePassword() {\n      api().changePassword(user.id(), \"p4ssw0rd\", \"Newp4ssw0rd\");\n   }\n   \n   @AfterClass(alwaysRun = true)\n   public void deleteUser() {\n      assertTrue(api().delete(user.id()));\n   }\n   \n   private UserApi api() {\n      return api.getUserApi();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v3/features/UserApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v3.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.List;\n\nimport org.jclouds.openstack.keystone.v3.domain.Group;\nimport org.jclouds.openstack.keystone.v3.domain.Project;\nimport org.jclouds.openstack.keystone.v3.domain.User;\nimport org.jclouds.openstack.keystone.v3.internal.BaseV3KeystoneApiMockTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"UserApiMockTest\", singleThreaded = true)\npublic class UserApiMockTest extends BaseV3KeystoneApiMockTest {\n\n   public void testListUsers() throws InterruptedException {\n      enqueueAuthentication(server);\n      server.enqueue(jsonResponse(\"/v3/users.json\"));\n\n      List<User> users = api.getUserApi().list();\n      assertFalse(users.isEmpty());\n\n      assertEquals(server.getRequestCount(), 2);\n      assertAuthentication(server);\n      assertSent(server, \"GET\", \"/users\");\n   }\n\n   public void testListUsersReturns404() throws InterruptedException {\n      enqueueAuthentication(server);\n      server.enqueue(response404());\n\n      List<User> users = api.getUserApi().list();\n      assertTrue(users.isEmpty());\n\n      assertEquals(server.getRequestCount(), 2);\n      assertAuthentication(server);\n      assertSent(server, \"GET\", \"/users\");\n   }\n\n   public void testGetUser() throws InterruptedException {\n      enqueueAuthentication(server);\n      server.enqueue(jsonResponse(\"/v3/user.json\"));\n\n      User user = api.getUserApi().get(\"0bedc61110fd4e94a251260a47f18f29\");\n      assertNotNull(user);\n\n      assertEquals(server.getRequestCount(), 2);\n      assertAuthentication(server);\n      assertSent(server, \"GET\", \"/users/0bedc61110fd4e94a251260a47f18f29\");\n   }\n\n   public void testGetUserReturns404() throws InterruptedException {\n      enqueueAuthentication(server);\n      server.enqueue(response404());\n\n      User user = api.getUserApi().get(\"0bedc61110fd4e94a251260a47f18f29\");\n      assertNull(user);\n\n      assertEquals(server.getRequestCount(), 2);\n      assertAuthentication(server);\n      assertSent(server, \"GET\", \"/users/0bedc61110fd4e94a251260a47f18f29\");\n   }\n\n   public void testCreateUser() throws InterruptedException {\n      enqueueAuthentication(server);\n      server.enqueue(jsonResponse(\"/v3/user.json\"));\n\n      User user = api.getUserApi().create(\"user\", \"p4ssw0rd\", true, \"123\", \"789\");\n      assertNotNull(user);\n\n      assertEquals(server.getRequestCount(), 2);\n      assertAuthentication(server);\n      assertSent(server, \"POST\", \"/users\", \"{\\\"user\\\":{\\\"name\\\":\\\"user\\\",\\\"password\\\":\\\"p4ssw0rd\\\",\\\"enabled\\\":true,\"\n            + \"\\\"domain_id\\\":\\\"123\\\",\\\"default_project_id\\\":\\\"789\\\"}}\");\n   }\n\n   public void testUpdateUser() throws InterruptedException {\n      enqueueAuthentication(server);\n      server.enqueue(jsonResponse(\"/v3/user.json\"));\n\n      User user = api.getUserApi().update(\"0bedc61110fd4e94a251260a47f18f29\", \"foo\", null, null, null, null);\n      assertNotNull(user);\n\n      assertEquals(server.getRequestCount(), 2);\n      assertAuthentication(server);\n      assertSent(server, \"PATCH\", \"/users/0bedc61110fd4e94a251260a47f18f29\", \"{\\\"user\\\":{\\\"name\\\":\\\"foo\\\"}}\");\n   }\n\n   public void testDeleteUser() throws InterruptedException {\n      enqueueAuthentication(server);\n      server.enqueue(response204());\n\n      boolean deleted = api.getUserApi().delete(\"0bedc61110fd4e94a251260a47f18f29\");\n      assertTrue(deleted);\n\n      assertEquals(server.getRequestCount(), 2);\n      assertAuthentication(server);\n      assertSent(server, \"DELETE\", \"/users/0bedc61110fd4e94a251260a47f18f29\");\n   }\n\n   public void testDeleteUserReturns404() throws InterruptedException {\n      enqueueAuthentication(server);\n      server.enqueue(response404());\n\n      boolean deleted = api.getUserApi().delete(\"0bedc61110fd4e94a251260a47f18f29\");\n      assertFalse(deleted);\n\n      assertEquals(server.getRequestCount(), 2);\n      assertAuthentication(server);\n      assertSent(server, \"DELETE\", \"/users/0bedc61110fd4e94a251260a47f18f29\");\n   }\n\n   public void testListGroups() throws InterruptedException {\n      enqueueAuthentication(server);\n      server.enqueue(jsonResponse(\"/v3/groups.json\"));\n\n      List<Group> groups = api.getUserApi().listGroups(\"0bedc61110fd4e94a251260a47f18f29\");\n      assertFalse(groups.isEmpty());\n\n      assertEquals(server.getRequestCount(), 2);\n      assertAuthentication(server);\n      assertSent(server, \"GET\", \"/users/0bedc61110fd4e94a251260a47f18f29/groups\");\n   }\n\n   public void testListProjects() throws InterruptedException {\n      enqueueAuthentication(server);\n      server.enqueue(jsonResponse(\"/v3/projects.json\"));\n\n      List<Project> projects = api.getUserApi().listProjects(\"0bedc61110fd4e94a251260a47f18f29\");\n      assertFalse(projects.isEmpty());\n\n      assertEquals(server.getRequestCount(), 2);\n      assertAuthentication(server);\n      assertSent(server, \"GET\", \"/users/0bedc61110fd4e94a251260a47f18f29/projects\");\n   }\n\n   public void testChangePassword() throws InterruptedException {\n      enqueueAuthentication(server);\n      server.enqueue(response204());\n\n      api.getUserApi().changePassword(\"0bedc61110fd4e94a251260a47f18f29\", \"foo\", \"bar\");\n\n      assertEquals(server.getRequestCount(), 2);\n      assertAuthentication(server);\n      assertSent(server, \"POST\", \"/users/0bedc61110fd4e94a251260a47f18f29/password\",\n            \"{\\\"user\\\":{\\\"original_password\\\":\\\"foo\\\",\\\"password\\\":\\\"bar\\\"}}\");\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v3/internal/BaseV3KeystoneApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v3.internal;\n\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.CREDENTIAL_TYPE;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.SCOPE;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.SERVICE_TYPE;\n\nimport java.util.Properties;\n\nimport org.jclouds.apis.BaseApiLiveTest;\nimport org.jclouds.http.okhttp.config.OkHttpCommandExecutorServiceModule;\nimport org.jclouds.logging.slf4j.config.SLF4JLoggingModule;\nimport org.jclouds.openstack.keystone.auth.AuthenticationApi;\nimport org.jclouds.openstack.keystone.auth.config.Authentication;\nimport org.jclouds.openstack.keystone.v3.KeystoneApi;\nimport org.jclouds.rest.ApiContext;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Key;\nimport com.google.inject.Module;\nimport com.google.inject.TypeLiteral;\n\npublic class BaseV3KeystoneApiLiveTest extends BaseApiLiveTest<KeystoneApi> {\n\n   protected Supplier<String> token;\n   protected AuthenticationApi authenticationApi;\n\n   public BaseV3KeystoneApiLiveTest() {\n      provider = \"openstack-keystone-3\";\n   }\n\n   @Override\n   protected KeystoneApi create(Properties props, Iterable<Module> modules) {\n      ApiContext<KeystoneApi> ctx = newBuilder().modules(modules).overrides(props).build();\n      authenticationApi = ctx.utils().injector().getInstance(AuthenticationApi.class);\n      token = ctx.utils().injector().getInstance(Key.get(new TypeLiteral<Supplier<String>>() {\n      }, Authentication.class));\n      return ctx.getApi();\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      setIfTestSystemPropertyPresent(props, CREDENTIAL_TYPE);\n      setIfTestSystemPropertyPresent(props, SCOPE);\n      String customServiceType = setIfTestSystemPropertyPresent(props, SERVICE_TYPE);\n      if (customServiceType == null) {\n         props.setProperty(SERVICE_TYPE, \"identityv3\");\n      }\n      return props;\n   }\n   \n   @Override\n   protected Iterable<Module> setupModules() {\n      ImmutableSet.Builder<Module> modules = ImmutableSet.builder();\n      modules.add(new OkHttpCommandExecutorServiceModule());\n      modules.add(new SLF4JLoggingModule());\n      return modules.build();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v3/internal/BaseV3KeystoneApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v3.internal;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static com.google.common.util.concurrent.MoreExecutors.newDirectExecutorService;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.Set;\nimport java.util.UUID;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\nimport okhttp3.mockwebserver.RecordedRequest;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.concurrent.config.ExecutorServiceModule;\nimport org.jclouds.http.okhttp.config.OkHttpCommandExecutorServiceModule;\nimport org.jclouds.json.Json;\nimport org.jclouds.logging.slf4j.config.SLF4JLoggingModule;\nimport org.jclouds.openstack.keystone.auth.AuthenticationApi;\nimport org.jclouds.openstack.keystone.config.KeystoneProperties;\nimport org.jclouds.openstack.keystone.v3.KeystoneApi;\nimport org.jclouds.openstack.keystone.v3.KeystoneApiMetadata;\nimport org.jclouds.openstack.keystone.v3.domain.Token;\nimport org.jclouds.rest.ApiContext;\nimport org.testng.annotations.AfterMethod;\nimport org.testng.annotations.BeforeMethod;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.base.Throwables;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.io.Resources;\nimport com.google.common.reflect.TypeToken;\nimport com.google.gson.JsonParser;\nimport com.google.inject.Module;\n\n\npublic class BaseV3KeystoneApiMockTest {\n   \n   private static final String DEFAULT_ENDPOINT = new KeystoneApiMetadata().getDefaultEndpoint().orNull();\n   \n   protected MockWebServer server;\n   protected KeystoneApi api;\n   protected AuthenticationApi authenticationApi;\n   protected String authToken;\n   private Json json;\n   \n   // So that we can ignore formatting.\n   private final JsonParser parser = new JsonParser();\n   \n   @BeforeMethod\n   public void start() throws IOException {\n      server = new MockWebServer();\n      server.start();\n      \n      ApiContext<KeystoneApi> ctx = ContextBuilder.newBuilder(\"openstack-keystone-3\")\n              .credentials(\"domain:identity\", \"credential\")\n              .endpoint(url(\"\"))\n              .modules(modules())\n              .overrides(overrides())\n              .build();\n      json = ctx.utils().injector().getInstance(Json.class);\n      authenticationApi = ctx.utils().injector().getInstance(AuthenticationApi.class);\n      api = ctx.getApi();\n   }\n\n   @AfterMethod(alwaysRun = true)\n   public void stop() throws IOException {\n      server.shutdown();\n      api.close();\n   }\n   \n   protected Properties overrides() {\n      Properties overrides = new Properties();\n      overrides.setProperty(KeystoneProperties.SCOPE, \"projectId:1234567890\");\n      overrides.setProperty(KeystoneProperties.SERVICE_TYPE, \"identityv3\");\n      return overrides;\n   }\n   \n   protected Set<Module> modules() {\n      ImmutableSet.Builder<Module> modules = ImmutableSet.builder();\n      modules.add(new ExecutorServiceModule(newDirectExecutorService()));\n      modules.add(new OkHttpCommandExecutorServiceModule());\n      modules.add(new SLF4JLoggingModule());\n      return modules.build();\n   }\n\n   protected String url(String path) {\n      return server.url(path).toString();\n   }\n   \n   protected void enqueueAuthentication(MockWebServer server) {\n      authToken = UUID.randomUUID().toString();\n      server.enqueue(jsonResponse(\"/v3/token.json\").addHeader(\"X-Subject-Token\", authToken));\n   }\n\n   protected MockResponse jsonResponse(String resource) {\n      return new MockResponse().addHeader(\"Content-Type\", \"application/json\").setBody(stringFromResource(resource));\n   }\n\n   protected MockResponse response404() {\n      return new MockResponse().setStatus(\"HTTP/1.1 404 Not Found\");\n   }\n   \n   protected MockResponse response201() {\n      return new MockResponse().setStatus(\"HTTP/1.1 201 Created\");\n   }\n   \n   protected MockResponse response204() {\n      return new MockResponse().setStatus(\"HTTP/1.1 204 No Content\");\n   }\n\n   protected String stringFromResource(String resourceName) {\n      try {\n         return Resources.toString(getClass().getResource(resourceName), Charsets.UTF_8)\n               .replace(DEFAULT_ENDPOINT, url(\"\"));\n      } catch (IOException e) {\n         throw Throwables.propagate(e);\n      }\n   }\n   \n   protected <T> T onlyObjectFromResource(String resourceName, TypeToken<Map<String, T>> type) {\n      // Assume JSON objects passed here will be in the form: { \"entity\": { ... } }\n      String text = stringFromResource(resourceName);\n      Map<String, T> object = json.fromJson(text, type.getType());\n      checkArgument(!object.isEmpty(), \"The given json does not contain any object: %s\", text);\n      checkArgument(object.keySet().size() == 1, \"The given json does not contain more than one object: %s\", text);\n      return object.get(getOnlyElement(object.keySet()));\n   }\n\n   protected <T> T objectFromResource(String resourceName, Class<T> type) {\n      String text = stringFromResource(resourceName);\n      return json.fromJson(text, type);\n   }\n   \n   protected void assertAuthentication(MockWebServer server) throws InterruptedException {\n      RecordedRequest request = assertSentNoAuth(server, \"POST\", \"/auth/tokens\");\n      assertBody(request, stringFromResource(\"/v3/auth-password-scoped.json\"));\n   }\n   \n   private RecordedRequest assertSentNoAuth(MockWebServer server, String method, String path) throws InterruptedException {\n      RecordedRequest request = server.takeRequest();\n      assertEquals(request.getMethod(), method);\n      assertEquals(request.getPath(), path);\n      assertEquals(request.getHeader(\"Accept\"), \"application/json\");\n      return request;\n   }\n\n   protected RecordedRequest assertSent(MockWebServer server, String method, String path) throws InterruptedException {\n      RecordedRequest request = assertSentNoAuth(server, method, path);\n      assertEquals(request.getHeader(\"X-Auth-Token\"), authToken);\n      return request;\n   }\n\n   protected RecordedRequest assertSent(MockWebServer server, String method, String path, String json)\n         throws InterruptedException {\n      RecordedRequest request = assertSent(server, method, path);\n      assertBody(request, json);\n      return request;\n   }\n   \n   private void assertBody(RecordedRequest request, String body) {\n      assertEquals(request.getHeader(\"Content-Type\"), \"application/json\");\n      assertEquals(parser.parse(request.getBody().readUtf8()), parser.parse(body));\n   }\n\n   protected Token tokenFromResource(String resource) {\n      return onlyObjectFromResource(resource, new TypeToken<Map<String, Token>>() {\n         private static final long serialVersionUID = 1L;\n      });\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/v2_0/functions/PresentWhenExtensionAnnotationNamespaceEqualsAnyNamespaceInExtensionsSetTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.v2_0.functions;\n\nimport static org.jclouds.reflect.Reflection2.method;\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\nimport java.util.List;\nimport java.util.Set;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.openstack.keystone.v2_0.config.NamespaceAliases;\nimport org.jclouds.openstack.v2_0.ServiceType;\nimport org.jclouds.openstack.v2_0.domain.Extension;\nimport org.jclouds.reflect.Invocation;\nimport org.jclouds.reflect.InvocationSuccess;\nimport org.jclouds.rest.annotations.Delegate;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Functions;\nimport com.google.common.base.Optional;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Multimap;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Provides;\nimport com.google.inject.multibindings.MapBinder;\n\n@Test(groups = \"unit\", testName = \"PresentWhenExtensionAnnotationNamespaceEqualsAnyNamespaceInExtensionsSetTest\")\npublic class PresentWhenExtensionAnnotationNamespaceEqualsAnyNamespaceInExtensionsSetTest {\n\n   Extension keypairs = Extension.builder().alias(\"os-keypairs\").name(\"Keypairs\").namespace(\n            URI.create(\"http://docs.openstack.org/ext/keypairs/api/v1.1\")).updated(\n            new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2011-08-08T00:00:00+00:00\")).description(\n            \"Keypair Support\").build();\n\n   @org.jclouds.openstack.v2_0.services.Extension(of = ServiceType.COMPUTE, namespace = \"http://docs.openstack.org/ext/keypairs/api/v1.1\")\n   interface KeyPairApi {\n\n   }\n\n   Extension floatingIps = Extension.builder().alias(\"os-floating-ips\").name(\"Floating_ips\").namespace(\n            URI.create(\"http://docs.openstack.org/ext/floating_ips/api/v1.1\")).updated(\n            new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2011-06-16T00:00:00+00:00\")).description(\n            \"Floating IPs support\").build();\n\n   @org.jclouds.openstack.v2_0.services.Extension(of = ServiceType.COMPUTE, name = \"Floating_ips\", alias = \"os-floating-ips\", namespace = \"http://docs.openstack.org/ext/floating_ips/api/v1.1\")\n   interface FloatingIPApi {\n\n   }\n\n   interface NovaApi {\n\n      @Delegate\n      Optional<FloatingIPApi> getFloatingIPExtensionApi(String region);\n\n      @Delegate\n      Optional<KeyPairApi> getKeyPairExtensionApi(String region);\n\n   }\n\n   InvocationSuccess getFloatingIPExtension(List<Object> args) throws SecurityException, NoSuchMethodException {\n      return InvocationSuccess.create(\n            Invocation.create(method(NovaApi.class, \"getFloatingIPExtensionApi\", String.class), args), \"foo\");\n   }\n\n   InvocationSuccess getKeyPairExtension(List<Object> args) throws SecurityException, NoSuchMethodException {\n      return InvocationSuccess.create(\n            Invocation.create(method(NovaApi.class, \"getKeyPairExtensionApi\", String.class), args), \"foo\");\n   }\n\n   public void testPresentWhenExtensionsIncludeNamespaceFromAnnotationAbsentWhenNot() throws SecurityException, NoSuchMethodException {\n\n      assertEquals(whenExtensionsInRegionInclude(\"region\", keypairs, floatingIps).apply(getFloatingIPExtension(ImmutableList.<Object> of(\"region\"))), Optional.of(\"foo\"));\n      assertEquals(whenExtensionsInRegionInclude(\"region\", keypairs, floatingIps).apply(getKeyPairExtension(ImmutableList.<Object> of(\"region\"))), Optional.of(\"foo\"));\n      assertEquals(whenExtensionsInRegionInclude(\"region\", keypairs).apply(getFloatingIPExtension(ImmutableList.<Object> of(\"region\"))), Optional.absent());\n      assertEquals(whenExtensionsInRegionInclude(\"region\", floatingIps).apply(getKeyPairExtension(ImmutableList.<Object> of(\"region\"))), Optional.absent());\n   }\n\n   public void testRegionWithoutExtensionsReturnsAbsent() throws SecurityException, NoSuchMethodException {\n      assertEquals(whenExtensionsInRegionInclude(\"region\", floatingIps).apply(\n               getFloatingIPExtension(ImmutableList.<Object> of(\"differentregion\"))), Optional.absent());\n      assertEquals(whenExtensionsInRegionInclude(\"region\", keypairs).apply(\n               getKeyPairExtension(ImmutableList.<Object> of(\"differentregion\"))), Optional.absent());\n   }\n\n   /**\n    * It is possible that the /extensions call returned the correct extension, but that the\n    * namespaces were different, for whatever reason. One way to address this is to have a multimap\n    * of the authoritative namespace to alternate ones, which could be wired up with guice\n    *\n    */\n   public void testPresentWhenAliasForExtensionMapsToNamespace() throws SecurityException, NoSuchMethodException {\n      Extension keypairsWithDifferentNamespace = keypairs.toBuilder().namespace(\n               URI.create(\"http://docs.openstack.org/ext/arbitrarilydifferent/keypairs/api/v1.1\")).build();\n\n      Multimap<URI, URI> aliases = ImmutableMultimap.of(keypairs.getNamespace(), keypairsWithDifferentNamespace\n               .getNamespace());\n\n      assertEquals(whenExtensionsAndAliasesInRegionInclude(\"region\", ImmutableSet.of(keypairsWithDifferentNamespace), aliases).apply(\n              getKeyPairExtension(ImmutableList.<Object> of(\"region\"))), Optional.of(\"foo\"));\n      assertEquals(whenExtensionsAndAliasesInRegionInclude(\"region\", ImmutableSet.of(keypairsWithDifferentNamespace), aliases).apply(\n              getFloatingIPExtension(ImmutableList.<Object> of(\"region\"))), Optional.absent());\n\n   }\n\n   /**\n    * In devstack and going forward, namespaces are being deprecated. When namespace is missing (or replaced with a\n    * \"fake\" /fake namespace), allow matching by name and alias.\n    *\n    */\n   public void testPresentWhenNameSpaceIsFakeAndMatchByNameOrAlias() throws SecurityException, NoSuchMethodException {\n      // Revert to alias\n      Extension floatingIpsWithFakeNamespace = floatingIps.toBuilder()\n            .namespace(URI.create(\"http://docs.openstack.org/ext/fake\"))\n            .build();\n\n      // Revert to name\n      Extension floatingIpsWithFakeNamespaceAndAlias = floatingIps.toBuilder()\n            .namespace(URI.create(\"http://docs.openstack.org/ext/fake\"))\n            .alias(\"fake\")\n            .build();\n\n      Multimap<URI, URI> aliases = ImmutableMultimap.of();\n\n      assertEquals(whenExtensionsAndAliasesInRegionInclude(\"region\", ImmutableSet.of(floatingIpsWithFakeNamespace), aliases).apply(\n            getFloatingIPExtension(ImmutableList.<Object> of(\"region\"))), Optional.of(\"foo\"));\n\n      assertEquals(whenExtensionsAndAliasesInRegionInclude(\"region\", ImmutableSet.of(floatingIpsWithFakeNamespaceAndAlias), aliases).apply(\n            getFloatingIPExtension(ImmutableList.<Object> of(\"region\"))), Optional.of(\"foo\"));\n   }\n   \n   public void testPresentWhenNameSpaceIsMissingAndMatchByNameOrAlias() throws SecurityException, NoSuchMethodException {\n      // Revert to alias\n      Extension floatingIpsWithMissingNamespace = floatingIps.toBuilder()\n            .namespace(null)\n            .build();\n\n      // Revert to name\n      Extension floatingIpsWithMissingNamespaceAndAlias = floatingIps.toBuilder()\n            .namespace(null)\n            .alias(\"fake\")\n            .build();\n\n      Multimap<URI, URI> aliases = ImmutableMultimap.of();\n\n      assertEquals(whenExtensionsAndAliasesInRegionInclude(\"region\", ImmutableSet.of(floatingIpsWithMissingNamespace), aliases).apply(\n            getFloatingIPExtension(ImmutableList.<Object> of(\"region\"))), Optional.of(\"foo\"));\n\n      assertEquals(whenExtensionsAndAliasesInRegionInclude(\"region\", ImmutableSet.of(floatingIpsWithMissingNamespaceAndAlias), aliases).apply(\n            getFloatingIPExtension(ImmutableList.<Object> of(\"region\"))), Optional.of(\"foo\"));\n   }\n\n   private PresentWhenExtensionAnnotationMatchesExtensionSet whenExtensionsInRegionInclude(\n            String region, Extension... extensions) {\n      return whenExtensionsAndAliasesInRegionInclude(region, ImmutableSet.copyOf(extensions), ImmutableMultimap.<URI, URI> of());\n   }\n\n   private PresentWhenExtensionAnnotationMatchesExtensionSet whenExtensionsAndAliasesInRegionInclude(\n            String region, final Set<Extension> extensions, final Multimap<URI, URI> aliases) {\n      final LoadingCache<String, Set<? extends Extension>> extensionsForRegion = CacheBuilder.newBuilder().build(\n               CacheLoader.from(Functions.forMap(ImmutableMap.<String, Set<? extends Extension>>of(region, extensions, \"differentregion\",\n                        ImmutableSet.<Extension> of()))));\n\n      PresentWhenExtensionAnnotationMatchesExtensionSet fn = Guice.createInjector(\n               new AbstractModule() {\n                  @Override\n                  protected void configure() {\n                     MapBinder<URI, URI> aliasBindings = MapBinder.newMapBinder(binder(),\n                           URI.class, URI.class, NamespaceAliases.class).permitDuplicates();\n                     for (URI key : aliases.keySet()) {\n                        for (URI value : aliases.get(key)) {\n                           aliasBindings.addBinding(key).toInstance(value);\n                        }\n                     }\n                  }\n\n                  @Provides\n                  LoadingCache<String, Set<? extends Extension>> getExtensions() {\n                     return extensionsForRegion;\n                  }\n\n               }).getInstance(PresentWhenExtensionAnnotationMatchesExtensionSet.class);\n\n      return fn;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/v2_0/internal/BaseOpenStackMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.v2_0.internal;\n\nimport static com.google.common.util.concurrent.MoreExecutors.newDirectExecutorService;\nimport static org.jclouds.Constants.PROPERTY_MAX_RETRIES;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.Closeable;\nimport java.io.IOException;\nimport java.net.URL;\nimport java.util.Properties;\nimport java.util.Set;\nimport java.util.concurrent.BlockingQueue;\nimport java.util.concurrent.LinkedBlockingQueue;\nimport java.util.regex.Pattern;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\nimport okhttp3.mockwebserver.QueueDispatcher;\nimport okhttp3.mockwebserver.RecordedRequest;\nimport okhttp3.mockwebserver.SocketPolicy;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.concurrent.config.ExecutorServiceModule;\nimport org.jclouds.util.Strings2;\n\nimport com.google.common.base.Throwables;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.net.HttpHeaders;\nimport com.google.common.net.MediaType;\nimport com.google.common.reflect.TypeToken;\nimport com.google.gson.JsonElement;\nimport com.google.gson.JsonParser;\nimport com.google.inject.Module;\n\n\npublic class BaseOpenStackMockTest<A extends Closeable> {\n\n   /**\n    * Needed for backwards-compatibility. This variable might not be up-to-date\n    * with current services available.\n    * */\n   @Deprecated\n   public static final String accessRackspace = \"{\\\"access\\\":{\\\"token\\\":{\\\"id\\\":\\\"b84f4a37-5126-4603-9521-ccd0665fbde1\\\",\\\"expires\\\":\\\"2013-04-13T16:49:57.000-05:00\\\",\\\"tenant\\\":{\\\"id\\\":\\\"123123\\\",\\\"name\\\":\\\"123123\\\"}},\\\"serviceCatalog\\\":[{\\\"endpoints\\\":[{\\\"tenantId\\\":\\\"123123\\\",\\\"publicURL\\\":\\\"URL/v1.0/123123\\\"}],\\\"name\\\":\\\"cloudMonitoring\\\",\\\"type\\\":\\\"rax:monitor\\\"},{\\\"endpoints\\\":[{\\\"region\\\":\\\"DFW\\\",\\\"tenantId\\\":\\\"MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\\\",\\\"publicURL\\\":\\\"URL/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\\\"},{\\\"region\\\":\\\"ORD\\\",\\\"tenantId\\\":\\\"MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\\\",\\\"publicURL\\\":\\\"URL/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\\\"}],\\\"name\\\":\\\"cloudFilesCDN\\\",\\\"type\\\":\\\"rax:object-cdn\\\"},{\\\"endpoints\\\":[{\\\"region\\\":\\\"ORD\\\",\\\"tenantId\\\":\\\"123123\\\",\\\"publicURL\\\":\\\"URL/v1.0/123123\\\"},{\\\"region\\\":\\\"DFW\\\",\\\"tenantId\\\":\\\"123123\\\",\\\"publicURL\\\":\\\"URL/v1.0/123123\\\"}],\\\"name\\\":\\\"cloudLoadBalancers\\\",\\\"type\\\":\\\"rax:load-balancer\\\"},{\\\"endpoints\\\":[{\\\"region\\\":\\\"DFW\\\",\\\"tenantId\\\":\\\"123123\\\",\\\"publicURL\\\":\\\"URL/v1.0/123123\\\"},{\\\"region\\\":\\\"ORD\\\",\\\"tenantId\\\":\\\"123123\\\",\\\"publicURL\\\":\\\"URL/v1.0/123123\\\"}],\\\"name\\\":\\\"cloudDatabases\\\",\\\"type\\\":\\\"rax:database\\\"},{\\\"endpoints\\\":[{\\\"region\\\":\\\"DFW\\\",\\\"tenantId\\\":\\\"MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\\\",\\\"publicURL\\\":\\\"URL/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\\\",\\\"internalURL\\\":\\\"URL/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\\\"},{\\\"region\\\":\\\"ORD\\\",\\\"tenantId\\\":\\\"MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\\\",\\\"publicURL\\\":\\\"URL/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\\\",\\\"internalURL\\\":\\\"URL/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\\\"}],\\\"name\\\":\\\"cloudFiles\\\",\\\"type\\\":\\\"object-store\\\"},{\\\"endpoints\\\":[{\\\"tenantId\\\":\\\"123123\\\",\\\"publicURL\\\":\\\"URL/v1.0/123123\\\",\\\"versionInfo\\\":\\\"URL/v1.0\\\",\\\"versionList\\\":\\\"URL/\\\",\\\"versionId\\\":\\\"1.0\\\"}],\\\"name\\\":\\\"cloudServers\\\",\\\"type\\\":\\\"compute\\\"},{\\\"endpoints\\\":[{\\\"region\\\":\\\"DFW\\\",\\\"tenantId\\\":\\\"123123\\\",\\\"publicURL\\\":\\\"URL/v2/123123\\\",\\\"versionInfo\\\":\\\"URL/v2\\\",\\\"versionList\\\":\\\"URL/\\\",\\\"versionId\\\":\\\"2\\\"},{\\\"region\\\":\\\"ORD\\\",\\\"tenantId\\\":\\\"123123\\\",\\\"publicURL\\\":\\\"URL/v2/123123\\\",\\\"versionInfo\\\":\\\"URL/v2\\\",\\\"versionList\\\":\\\"URL/\\\",\\\"versionId\\\":\\\"2\\\"}],\\\"name\\\":\\\"cloudServersOpenStack\\\",\\\"type\\\":\\\"compute\\\"},{\\\"endpoints\\\":[{\\\"tenantId\\\":\\\"123123\\\",\\\"publicURL\\\":\\\"URL/v1.0/123123\\\"}],\\\"name\\\":\\\"cloudDNS\\\",\\\"type\\\":\\\"rax:dns\\\"},{\\\"endpoints\\\":[{\\\"tenantId\\\":\\\"123123\\\",\\\"publicURL\\\":\\\"URL/v1.0/123123\\\"}],\\\"name\\\":\\\"cloudBackup\\\",\\\"type\\\":\\\"rax:backup\\\"},{\\\"endpoints\\\":[{\\\"region\\\":\\\"DFW\\\",\\\"tenantId\\\":\\\"123123\\\",\\\"publicURL\\\":\\\"URL/v1/123123\\\"},{\\\"region\\\":\\\"ORD\\\",\\\"tenantId\\\":\\\"123123\\\",\\\"publicURL\\\":\\\"URL/v1/123123\\\"}],\\\"name\\\":\\\"cloudBlockStorage\\\",\\\"type\\\":\\\"volume\\\"},{\\\"endpoints\\\":[{\\\"region\\\":\\\"DFW\\\",\\\"tenantId\\\":\\\"123123\\\",\\\"publicURL\\\":\\\"URL/v1/123123\\\",\\\"internalURL\\\":\\\"URL/v1/123123\\\"},{\\\"region\\\":\\\"ORD\\\",\\\"tenantId\\\":\\\"123123\\\",\\\"publicURL\\\":\\\"URL/v1/123123\\\",\\\"internalURL\\\":\\\"URL/v1/123123\\\"}],\\\"name\\\":\\\"zaqar\\\",\\\"type\\\":\\\"messaging\\\"},{\\\"endpoints\\\":[{\\\"region\\\":\\\"DFW\\\",\\\"tenantId\\\":\\\"123123\\\",\\\"publicURL\\\":\\\"URL/v1/123123\\\",\\\"internalURL\\\":\\\"URL/v1/123123\\\"},{\\\"region\\\":\\\"ORD\\\",\\\"tenantId\\\":\\\"123123\\\",\\\"publicURL\\\":\\\"URL/v1/123123\\\",\\\"internalURL\\\":\\\"URL/v1/123123\\\"}],\\\"name\\\":\\\"autoscale\\\",\\\"type\\\":\\\"rax:autoscale\\\"}],\\\"user\\\":{\\\"id\\\":\\\"1234\\\",\\\"roles\\\":[{\\\"id\\\":\\\"3\\\",\\\"description\\\":\\\"User Admin Role.\\\",\\\"name\\\":\\\"identity:user-admin\\\"}],\\\"name\\\":\\\"jclouds-joe\\\",\\\"RAX-AUTH:defaultRegion\\\":\\\"DFW\\\"}}}\";\n\n   private final Set<Module> modules = ImmutableSet.<Module> of(\n         new ExecutorServiceModule(newDirectExecutorService()));\n\n   /**\n    * Pattern for replacing the URL token with the correct local address.\n    */\n   private static final Pattern urlTokenPattern = Pattern.compile(\":\\\\s*\\\"\\\\s*URL\");\n\n   @SuppressWarnings(\"serial\")\n   public A api(String uri, String provider, Properties overrides) {\n      if (!overrides.containsKey(PROPERTY_MAX_RETRIES)) {\n         overrides.setProperty(PROPERTY_MAX_RETRIES, \"1\");\n      }\n\n      return ContextBuilder.newBuilder(provider)\n            .credentials(\"jclouds:joe\", \"letmein\")\n            .endpoint(uri)\n            .overrides(overrides)\n            .modules(modules)\n            .buildApi(new TypeToken<A>(getClass()) {});\n   }\n\n   public A api(String uri, String provider) {\n      return api(uri, provider, new Properties());\n   }\n\n   public static MockWebServer mockOpenStackServer() throws IOException {\n      MockWebServer server = new MockWebServer();\n      server.start();\n      URL url = server.url(\"\").url();\n      server.setDispatcher(getURLReplacingQueueDispatcher(url.toString()));\n      return server;\n   }\n\n   /**\n    * there's no built-in way to defer evaluation of a response header, hence\n    * this method, which allows us to send back links to the mock server.\n    */\n   public static QueueDispatcher getURLReplacingQueueDispatcher(final String url) {\n      final String strippedUrl = url.endsWith(\"/\") ? url.substring(0, url.length() - 1) : url;\n\n      final QueueDispatcher dispatcher = new QueueDispatcher() {\n         protected final BlockingQueue<MockResponse> responseQueue = new LinkedBlockingQueue<MockResponse>();\n\n         @Override\n         public MockResponse dispatch(RecordedRequest request) throws InterruptedException {\n            MockResponse response = responseQueue.take();\n            if (response.getBody() != null) {\n               /*\n                * \"URL\" must be used in the service catalog sample (such as\n                * access.json or accessRackspace.json) for the declared service\n                * endpoints.\n                */\n               String newBody = urlTokenPattern.matcher(new String(response.getBody().readByteArray())).replaceAll(\": \\\"\" + strippedUrl);\n\n               response = response.setBody(newBody);\n            }\n            return response;\n         }\n\n         @Override\n         public void enqueueResponse(MockResponse response) {\n            responseQueue.add(response);\n         }\n\n         @Override\n         public MockResponse peek() {\n            return super.peek().setSocketPolicy(SocketPolicy.EXPECT_CONTINUE);\n         }\n      };\n\n      return dispatcher;\n   }\n\n   /**\n    * Ensure json headers are included\n    * */\n   public MockResponse addCommonHeaders(MockResponse mockResponse) {\n      mockResponse.addHeader(HttpHeaders.ACCEPT, MediaType.JSON_UTF_8.withoutParameters());\n      return mockResponse;\n   }\n\n   /**\n    * Get a string from a resource\n    *\n    * @param resourceName\n    *           The name of the resource.\n    * @return The content of the resource\n    */\n   public String stringFromResource(String resourceName) {\n      try {\n         return Strings2.toStringAndClose(getClass().getResourceAsStream(resourceName));\n      } catch (IOException e) {\n         throw Throwables.propagate(e);\n      }\n   }\n\n   /**\n    * Ensures server received authentication request.\n    */\n   public void assertAuthentication(MockWebServer server) {\n      assertTrue(server.getRequestCount() >= 1);\n      try {\n         assertEquals(server.takeRequest().getRequestLine(), \"POST /tokens HTTP/1.1\");\n      } catch (InterruptedException e) {\n         Throwables.propagate(e);\n      }\n   }\n\n   /**\n    * Ensures server received an extensions request. Most OpenStack APIs that expose an {@link ExtensionApi}\n    * should use this method.\n    */\n   public void assertExtensions(MockWebServer server) {\n      assertExtensions(server, \"\");\n   }\n\n   /**\n    * Ensures server received a <i>versioned</i> extensions request. This is necessary for testing APIs whose version\n    * is not included in the Endpoint's {@link Endpoint#getPublicURL() publicURL}.\n    */\n   public void assertExtensions(MockWebServer server, String path) {\n      assertTrue(server.getRequestCount() >= 1);\n      try {\n         assertEquals(server.takeRequest().getRequestLine(), \"GET \" + path + \"/extensions HTTP/1.1\");\n      } catch (InterruptedException e) {\n         Throwables.propagate(e);\n      }\n   }\n\n   /**\n    * Ensures the request has a json header.\n    *\n    * @param request\n    * @see RecordedRequest\n    */\n   private void assertContentTypeIsJSON(RecordedRequest request) {\n      assertTrue(request.getHeaders().values(\"Content-Type\").contains(\"application/json\"));\n   }\n\n   /**\n    * Ensures the request has a json header for the proper REST methods.\n    *\n    * @param request\n    * @param method\n    *           The request method (such as GET).\n    * @param path\n    *           The path requested for this REST call.\n    * @see RecordedRequest\n    */\n   public void assertRequest(RecordedRequest request, String method, String path) {\n      assertEquals(request.getMethod(), method);\n      assertEquals(request.getPath(), path);\n   }\n\n   /**\n    * Ensures the request is json and has the same contents as the resource\n    * file provided.\n    *\n    * @param request\n    * @param method\n    *           The request method (such as GET).\n    * @param resourceLocation\n    *           The location of the resource file. Contents will be compared to\n    *           the request body as JSON.\n    * @see RecordedRequest\n    */\n   public void assertRequest(RecordedRequest request, String method, String path, String resourceLocation) {\n      assertRequest(request, method, path);\n      assertContentTypeIsJSON(request);\n      JsonParser parser = new JsonParser();\n      JsonElement requestJson = null;  // to be compared\n      JsonElement resourceJson;        // to be compared\n      try {\n         requestJson = parser.parse(request.getBody().readUtf8());\n      } catch (Exception e) {\n         Throwables.propagate(e);\n      }\n      resourceJson = parser.parse(stringFromResource(resourceLocation));\n      assertEquals(requestJson, resourceJson); // Compare as JSON\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/v2_0/options/PaginationOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.v2_0.options;\n\nimport static org.jclouds.openstack.v2_0.options.PaginationOptions.Builder.limit;\nimport static org.jclouds.openstack.v2_0.options.PaginationOptions.Builder.marker;\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tests behavior of {@code ListOptions}\n */\n@Test(groups = \"unit\", testName = \"PaginationOptionsTest\")\npublic class PaginationOptionsTest {\n\n   public void testMarker() {\n      String marker = \"52415800-8b69-11e0-9b19-734f6f006e54\";\n      PaginationOptions options = new PaginationOptions().marker(marker);\n      assertEquals(ImmutableList.of(marker), options.buildQueryParameters().get(\"marker\"));\n   }\n\n   public void testMaxResults() {\n      int limit = 1;\n      PaginationOptions options = new PaginationOptions().limit(limit);\n      assertEquals(ImmutableList.of(\"1\"), options.buildQueryParameters().get(\"limit\"));\n   }\n\n   public void testMarkerStatic() {\n      String marker = \"52415800-8b69-11e0-9b19-734f6f006e54\";\n      PaginationOptions options = marker(marker);\n      assertEquals(ImmutableList.of(marker), options.buildQueryParameters().get(\"marker\"));\n   }\n\n   public void testMaxResultsStatic() {\n      int limit = 1;\n      PaginationOptions options = limit(limit);\n      assertEquals(ImmutableList.of(\"1\"), options.buildQueryParameters().get(\"limit\"));\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/v2_0/predicates/ExtensionPredicatesTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.v2_0.predicates;\n\nimport static org.jclouds.openstack.v2_0.predicates.ExtensionPredicates.aliasEquals;\nimport static org.jclouds.openstack.v2_0.predicates.ExtensionPredicates.namespaceEquals;\n\nimport java.net.URI;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.openstack.v2_0.domain.Extension;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ExtensionPredicatesTest\")\npublic class ExtensionPredicatesTest {\n   Extension ref = Extension.builder().alias(\"os-keypairs\").name(\"Keypairs\").namespace(\n            URI.create(\"http://docs.openstack.org/ext/keypairs/api/v1.1\")).updated(\n            new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2011-08-08T00:00:00+00:00\")).description(\n            \"Keypair Support\").build();\n\n   @Test\n   public void testAliasEqualsWhenEqual() {\n      assert aliasEquals(\"os-keypairs\").apply(ref);\n   }\n\n   @Test\n   public void testAliasEqualsWhenNotEqual() {\n      assert !aliasEquals(\"foo\").apply(ref);\n   }\n\n   @Test\n   public void testNamespaceEqualsWhenEqual() {\n      assert namespaceEquals(URI.create(\"http://docs.openstack.org/ext/keypairs/api/v1.1\")).apply(ref);\n   }\n   \n   @Test\n   public void testNamespaceEqualsWhenNullNamespace() {\n      Extension withoutNamespace = ref.toBuilder().namespace(null).build();\n      assert !namespaceEquals(URI.create(\"http://docs.openstack.org/ext/keypairs/api/v1.1\")).apply(withoutNamespace);\n   }\n\n   @Test\n   public void testNamespaceEqualsWhenEqualEvenOnInputHttps() {\n      assert namespaceEquals(URI.create(\"http://docs.openstack.org/ext/keypairs/api/v1.1\")).apply(\n               ref.toBuilder().namespace(URI.create(\"https://docs.openstack.org/ext/keypairs/api/v1.1\")).build());\n   }\n\n   @Test\n   public void testNamespaceEqualsWhenNotEqual() {\n      assert !namespaceEquals(URI.create(\"foo\")).apply(ref);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/java/org/jclouds/openstack/v2_0/predicates/LinkPredicatesTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.v2_0.predicates;\n\nimport static org.jclouds.openstack.v2_0.predicates.LinkPredicates.hrefEquals;\nimport static org.jclouds.openstack.v2_0.predicates.LinkPredicates.relationEquals;\nimport static org.jclouds.openstack.v2_0.predicates.LinkPredicates.typeEquals;\n\nimport java.net.URI;\n\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.Link.Relation;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"LinkPredicatesTest\")\npublic class LinkPredicatesTest {\n   Link ref = Link.builder().type(\"application/pdf\").relation(Relation.DESCRIBEDBY).href(\n            URI.create(\"http://docs.openstack.org/ext/keypairs/api/v1.1\")).build();\n\n   @Test\n   public void testRelationEqualsWhenEqual() {\n      assert relationEquals(Relation.DESCRIBEDBY).apply(ref);\n   }\n\n   @Test\n   public void testRelationEqualsWhenNotEqual() {\n      assert !relationEquals(Relation.UNRECOGNIZED).apply(ref);\n   }\n\n   @Test\n   public void testTypeEqualsWhenEqual() {\n      assert typeEquals(\"application/pdf\").apply(ref);\n   }\n\n   @Test\n   public void testTypeEqualsWhenNotEqual() {\n      assert !typeEquals(\"foo\").apply(ref);\n   }\n\n   @Test\n   public void testHrefEqualsWhenEqual() {\n      assert hrefEquals(URI.create(\"http://docs.openstack.org/ext/keypairs/api/v1.1\")).apply(ref);\n   }\n\n   @Test\n   public void testHrefEqualsWhenNotEqual() {\n      assert !hrefEquals(URI.create(\"foo\")).apply(ref);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/access_minimal.json",
    "content": "{\n    \"access\": {\n        \"token\": {\n            \"expires\": \"2012-12-02T01:44:54Z\",\n            \"id\": \"5afc3adea6654e758b4a9cf01bafe507\"\n        },\n        \"serviceCatalog\": [],\n        \"user\": {\n            \"username\": \"nova\",\n            \"roles_links\": [],\n            \"id\": \"bf45fd7586c2410c980c651b918aa850\",\n            \"roles\": [],\n            \"name\": \"nova\"\n        }\n    }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/access_version_uids.json",
    "content": "{\n    \"access\": {\n        \"token\": {\n            \"expires\": \"2012-09-29T19:53:45Z\",\n            \"id\": \"b267e2e240624b108b1ed5bba6e5882e\",\n            \"tenant\": {\n                \"enabled\": true,\n                \"description\": null,\n                \"name\": \"demo\",\n                \"id\": \"82d8d2f865484776a1daf1e2245d3317\"\n            }\n        },\n        \"serviceCatalog\": [\n            {\n                \"endpoints\": [\n                    {\n                        \"adminURL\": \"http://10.10.10.10:8774/v2/82d8d2f865484776a1daf1e2245d3317\",\n                        \"region\": \"RegionOne\",\n                        \"internalURL\": \"http://10.10.10.10:8774/v2/82d8d2f865484776a1daf1e2245d3317\",\n                        \"id\": \"bb3ce9ccdc5045909882688b90cc3ff0\",\n                        \"publicURL\": \"http://10.10.10.10:8774/v2/82d8d2f865484776a1daf1e2245d3317\"\n                    }\n                ],\n                \"endpoints_links\": [],\n                \"type\": \"compute\",\n                \"name\": \"nova\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"adminURL\": \"http://10.10.10.10:3333\",\n                        \"region\": \"RegionOne\",\n                        \"internalURL\": \"http://10.10.10.10:3333\",\n                        \"id\": \"9646263f31ea4f499732c5e1370ecf5e\",\n                        \"publicURL\": \"http://10.10.10.10:3333\"\n                    }\n                ],\n                \"endpoints_links\": [],\n                \"type\": \"s3\",\n                \"name\": \"s3\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"adminURL\": \"http://10.10.10.10:9292\",\n                        \"region\": \"RegionOne\",\n                        \"internalURL\": \"http://10.10.10.10:9292\",\n                        \"id\": \"aa5d0b2574824ba097dc07faacf3be65\",\n                        \"publicURL\": \"http://10.10.10.10:9292\"\n                    }\n                ],\n                \"endpoints_links\": [],\n                \"type\": \"image\",\n                \"name\": \"glance\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"adminURL\": \"http://10.10.10.10:8776/v1/82d8d2f865484776a1daf1e2245d3317\",\n                        \"region\": \"RegionOne\",\n                        \"internalURL\": \"http://10.10.10.10:8776/v1/82d8d2f865484776a1daf1e2245d3317\",\n                        \"id\": \"7679065b1405447eb5f1a38a6b99ccc0\",\n                        \"publicURL\": \"http://10.10.10.10:8776/v1/82d8d2f865484776a1daf1e2245d3317\"\n                    }\n                ],\n                \"endpoints_links\": [],\n                \"type\": \"volume\",\n                \"name\": \"cinder\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"adminURL\": \"http://10.10.10.10:8773/services/Admin\",\n                        \"region\": \"RegionOne\",\n                        \"internalURL\": \"http://10.10.10.10:8773/services/Cloud\",\n                        \"id\": \"22b007f023fb4c42be094916eb2bf18b\",\n                        \"publicURL\": \"http://10.10.10.10:8773/services/Cloud\"\n                    }\n                ],\n                \"endpoints_links\": [],\n                \"type\": \"ec2\",\n                \"name\": \"ec2\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"adminURL\": \"http://10.10.10.10:35357/v2.0\",\n                        \"region\": \"RegionOne\",\n                        \"internalURL\": \"http://10.10.10.10:5000/v2.0\",\n                        \"id\": \"57ee5fb4f9a840f3b965909681d0fc53\",\n                        \"publicURL\": \"http://10.10.10.10:5000/v2.0\"\n                    }\n                ],\n                \"endpoints_links\": [],\n                \"type\": \"identity\",\n                \"name\": \"keystone\"\n            }\n        ],\n        \"user\": {\n            \"username\": \"demo\",\n            \"roles_links\": [],\n            \"id\": \"ca248caf55844c14a4876c22112bbbb9\",\n            \"roles\": [\n                {\n                    \"name\": \"Member\"\n                }\n            ],\n            \"name\": \"demo\"\n        },\n        \"metadata\": {\n            \"is_admin\": 0,\n            \"roles\": [\n                \"1f697d8e3ace4f5a80f7701e554ee5d9\"\n            ]\n        }\n    }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/adminAuth.json",
    "content": "{\n    \"access\": {\n        \"token\": {\n            \"expires\": \"2012-08-01T13:08:52Z\",\n            \"id\": \"946b8ad1ede4422f87ab21dcba27896d\",\n            \"tenant\": {\n                \"enabled\": true,\n                \"description\": null,\n                \"name\": \"admin\",\n                \"id\": \"2fdc88ae152948c690b97ba307acae9b\"\n            }\n        },\n        \"serviceCatalog\": [\n            {\n                \"endpoints\": [\n                    {\n                        \"adminURL\": \"http://10.0.1.13:8774/v2/2fdc88ae152948c690b97ba307acae9b\",\n                        \"region\": \"RegionOne\",\n                        \"publicURL\": \"http://10.0.1.13:8774/v2/2fdc88ae152948c690b97ba307acae9b\",\n                        \"internalURL\": \"http://10.0.1.13:8774/v2/2fdc88ae152948c690b97ba307acae9b\"\n                    }\n                ],\n                \"endpoints_links\": [],\n                \"type\": \"compute\",\n                \"name\": \"Compute Service\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"adminURL\": \"http://10.0.1.13:3333\",\n                        \"region\": \"RegionOne\",\n                        \"publicURL\": \"http://10.0.1.13:3333\",\n                        \"internalURL\": \"http://10.0.1.13:3333\"\n                    }\n                ],\n                \"endpoints_links\": [],\n                \"type\": \"s3\",\n                \"name\": \"S3 Service\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"adminURL\": \"http://10.0.1.13:9292\",\n                        \"region\": \"RegionOne\",\n                        \"publicURL\": \"http://10.0.1.13:9292\",\n                        \"internalURL\": \"http://10.0.1.13:9292\"\n                    }\n                ],\n                \"endpoints_links\": [],\n                \"type\": \"image\",\n                \"name\": \"Image Service\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"adminURL\": \"http://10.0.1.13:8776/v1/2fdc88ae152948c690b97ba307acae9b\",\n                        \"region\": \"RegionOne\",\n                        \"publicURL\": \"http://10.0.1.13:8776/v1/2fdc88ae152948c690b97ba307acae9b\",\n                        \"internalURL\": \"http://10.0.1.13:8776/v1/2fdc88ae152948c690b97ba307acae9b\"\n                    }\n                ],\n                \"endpoints_links\": [],\n                \"type\": \"volume\",\n                \"name\": \"Volume Service\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"adminURL\": \"http://10.0.1.13:8773/services/Admin\",\n                        \"region\": \"RegionOne\",\n                        \"publicURL\": \"http://10.0.1.13:8773/services/Cloud\",\n                        \"internalURL\": \"http://10.0.1.13:8773/services/Cloud\"\n                    }\n                ],\n                \"endpoints_links\": [],\n                \"type\": \"ec2\",\n                \"name\": \"EC2 Service\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"adminURL\": \"http://10.0.1.13:35357/v2.0\",\n                        \"region\": \"RegionOne\",\n                        \"publicURL\": \"http://10.0.1.13:5000/v2.0\",\n                        \"internalURL\": \"http://10.0.1.13:5000/v2.0\"\n                    }\n                ],\n                \"endpoints_links\": [],\n                \"type\": \"identity\",\n                \"name\": \"Identity Service\"\n            }\n        ],\n        \"user\": {\n            \"username\": \"admin\",\n            \"roles_links\": [],\n            \"id\": \"b4d134cfe3cf43ad8ba0c2fc5b5d8f91\",\n            \"roles\": [\n                {\n                    \"name\": \"admin\"\n                },\n                {\n                    \"name\": \"KeystoneServiceAdmin\"\n                },\n                {\n                    \"name\": \"KeystoneAdmin\"\n                }\n            ],\n            \"name\": \"admin\"\n        },\n        \"metadata\": {\n            \"is_admin\": 0,\n            \"roles\": [\n                \"a2bb9cb209f14ec18d0f747ccdef4bb6\",\n                \"27cb69f42476498cb11e83b7d90fc419\",\n                \"7758efbae00a480385493f77f7860c29\"\n            ]\n        }\n    }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/admin_extensions.json",
    "content": "{\n    \"extensions\": [\n        {\n            \"name\": \"OS-KSADM\",\n            \"alias\": \"OS-KSADM\",\n            \"namespace\": \"http://docs.openstack.org/identity/api/ext/OS-KSADM/v1.0\",\n            \"updated\": \"2011-08-08T00:00:00+00:00\",\n            \"description\": \"Keystone Administration Extension\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/devstackVersion.json",
    "content": "{\n    \"version\": {\n        \"status\": \"beta\",\n        \"updated\": \"2011-11-19T00:00:00Z\",\n        \"media-types\": [\n            {\n                \"base\": \"application/json\",\n                \"type\": \"application/vnd.openstack.identity-v2.0+json\"\n            },\n            {\n                \"base\": \"application/xml\",\n                \"type\": \"application/vnd.openstack.identity-v2.0+xml\"\n            }\n        ],\n        \"id\": \"v2.0\",\n        \"links\": [\n            {\n                \"href\": \"http://172.16.89.167:5000/v2.0/\",\n                \"rel\": \"self\"\n            },\n            {\n                \"href\": \"http://docs.openstack.org/api/openstack-identity-service/2.0/content/\",\n                \"type\": \"text/html\",\n                \"rel\": \"describedby\"\n            },\n            {\n                \"href\": \"http://docs.openstack.org/api/openstack-identity-service/2.0/identity-dev-guide-2.0.pdf\",\n                \"type\": \"application/pdf\",\n                \"rel\": \"describedby\"\n            }\n        ]\n    }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/keystoneAuthResponse.json",
    "content": "{\n    \"access\": {\n        \"token\": {\n            \"expires\": \"2012-01-18T21:35:59.050Z\",\n            \"id\": \"Auth_4f173437e4b013bee56d1007\",\n            \"tenant\": {\n                \"id\": \"40806637803162\",\n                \"name\": \"user@jclouds.org-default-tenant\"\n            }\n        },\n        \"user\": {\n            \"id\": \"36980896575174\",\n            \"name\": \"user@jclouds.org\",\n            \"roles\": [\n                {\n                    \"id\": \"00000000004022\",\n                    \"serviceId\": \"110\",\n                    \"name\": \"Admin\",\n                    \"tenantName\": \"40806637803162\"\n                },\n                {\n                    \"id\": \"00000000004024\",\n                    \"serviceId\": \"140\",\n                    \"name\": \"user\",\n                    \"tenantName\": \"40806637803162\"\n                },\n                {\n                    \"id\": \"00000000004004\",\n                    \"serviceId\": \"100\",\n                    \"name\": \"domainuser\"\n                },\n                {\n                    \"id\": \"00000000004016\",\n                    \"serviceId\": \"120\",\n                    \"name\": \"netadmin\",\n                    \"tenantName\": \"40806637803162\"\n                }\n            ]\n        },\n        \"serviceCatalog\": [\n            {\n                \"name\": \"Object Storage\",\n                \"type\": \"object-store\",\n                \"endpoints\": [\n                    {\n                        \"tenantName\": \"40806637803162\",\n                        \"adminURL\": \"https://objects.jclouds.org/v1.0/\",\n                        \"publicURL\": \"https://objects.jclouds.org/v1.0/40806637803162\",\n                        \"region\": \"region-a.geo-1\",\n                        \"id\": \"1.0\"\n                    }\n                ]\n            },\n            {\n                \"name\": \"Identity\",\n                \"type\": \"identity\",\n                \"endpoints\": [\n                    {\n                        \"adminURL\": \"https://csnode.jclouds.org:35357/v2.0/\",\n                        \"publicURL\": \"https://csnode.jclouds.org/v2.0/\",\n                        \"region\": \"region-a.geo-1\",\n                        \"id\": \"2.0\",\n                        \"versionId\": \"2.0\",\n                        \"list\": \"https://csnode.jclouds.org/extension\"\n                    }\n                ]\n            },\n            {\n                \"name\": \"Image Management\",\n                \"type\": \"image\",\n                \"endpoints\": [\n                    {\n                        \"tenantName\": \"40806637803162\",\n                        \"publicURL\": \"https://glance.jclouds.org:9292/\",\n                        \"region\": \"az-1.region-a.geo-1\",\n                        \"id\": \"1.0\"\n                    }\n                ]\n            },\n            {\n                \"name\": \"Compute\",\n                \"type\": \"compute\",\n                \"endpoints\": [\n                    {\n                        \"tenantId\": \"3456\",\n                        \"publicURL\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456\",\n                        \"publicURL2\": \"https://az-1.region-a.geo-1.ec2-compute.hpcloudsvc.com/services/Cloud\",\n                        \"region\": \"az-1.region-a.geo-1\",\n                        \"versionId\": \"2\",\n                        \"versionInfo\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/\",\n                        \"versionList\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com\"\n                    },\n                    {\n                        \"tenantId\": \"3456\",\n                        \"publicURL\": \"https://az-2.region-a.geo-1.compute.hpcloudsvc.com/v2/3456\",\n                        \"publicURL2\": \"https://az-2.region-a.geo-1.ec2-compute.hpcloudsvc.com/services/Cloud\",\n                        \"region\": \"az-2.region-a.geo-1\",\n                        \"versionId\": \"2\",\n                        \"versionInfo\": \"https://az-2.region-a.geo-1.compute.hpcloudsvc.com/v2/\",\n                        \"versionList\": \"https://az-2.region-a.geo-1.compute.hpcloudsvc.com\"\n                    },\n                    {\n                        \"tenantId\": \"3456\",\n                        \"publicURL\": \"https://az-3.region-a.geo-1.compute.hpcloudsvc.com/v2/3456\",\n                        \"publicURL2\": \"https://az-3.region-a.geo-1.ec2-compute.hpcloudsvc.com/services/Cloud\",\n                        \"region\": \"az-3.region-a.geo-1\",\n                        \"versionId\": \"2\",\n                        \"versionInfo\": \"https://az-3.region-a.geo-1.compute.hpcloudsvc.com/v2/\",\n                        \"versionList\": \"https://az-3.region-a.geo-1.compute.hpcloudsvc.com\"\n                    }\n                ]\n            },\n            {\n                \"type\": \"network\",\n                \"name\": \"Neutron Service\",\n                \"endpoints\": [\n                    {\n                        \"tenantId\": \"3456\",\n                        \"adminURL\": \"https://csnode.jclouds.org:9696/v1.0\",\n                        \"region\": \"region-a.geo-1\",\n                        \"versionId\": \"1.0\",\n                        \"publicURL\": \"https://csnode.jclouds.org:9696/v1.0/tenants/3456\",\n                        \"internalURL\": \"https://csnode.jclouds.org:9696/v1.0/tenants/3456\"\n                    }\n                ],\n                \"endpoints_links\": []\n            },\n            {\n                \"type\": \"network\",\n                \"name\": \"Quantum Service\",\n                \"endpoints\": [\n                    {\n                        \"tenantId\": \"3456\",\n                        \"adminURL\": \"https://csnode.jclouds.org:9696\",\n                        \"region\": \"region-a.geo-1\",\n                        \"versionId\": \"2.0\",\n                        \"publicURL\": \"https://csnode.jclouds.org:9696\",\n                        \"internalURL\": \"https://csnode.jclouds.org:9696\"\n                    }\n                ],\n                \"endpoints_links\": []\n            },\n            {\n                \"type\": \"volume\",\n                \"name\": \"cinder\",\n                \"endpoints\": [\n                    {\n                        \"adminURL\": \"http://10.0.2.15:8776/v1/50cdb4c60374463198695d9f798fa34d\",\n                        \"region\": \"RegionOne\",\n                        \"internalURL\": \"http://10.0.2.15:8776/v1/50cdb4c60374463198695d9f798fa34d\",\n                        \"id\": \"08330c2dcbfc4c6c8dc7a0949fbf5da7\",\n                        \"publicURL\": \"http://172.16.0.1:8776/v1/50cdb4c60374463198695d9f798fa34d\"\n                    }\n                ],\n                \"endpoints_links\": []\n            },\n            {\n                \"type\": \"share\",\n                \"name\": \"manila\",\n                \"endpoints\": [\n                    {\n                        \"adminURL\": \"http://10.0.2.15:8786/v1/50cdb4c60374463198695d9f798fa34d\",\n                        \"region\": \"RegionOne\",\n                        \"internalURL\": \"http://10.0.2.15:8786/v1/50cdb4c60374463198695d9f798fa34d\",\n                        \"id\": \"c06b43bc23e44be6b079ac319718014e\",\n                        \"publicURL\": \"http://172.16.0.1:8786/v1/50cdb4c60374463198695d9f798fa34d\"\n                    }\n                ],\n                \"endpoints_links\": []\n            },\n            {\n                \"type\": \"database\",\n                \"name\": \"trove\",\n                \"endpoints\": [\n                    {\n                        \"publicURL\": \"http://172.16.0.1:8776/v1/3456\",\n                        \"tenantId\": \"123123\",\n                        \"region\": \"RegionOne\"\n                    }\n                ]\n            },\n            {\n                \"type\": \"messaging\",\n                \"name\": \"zaqar\",\n                \"endpoints\": [\n                    {\n                        \"adminURL\": \"http://10.0.2.15:8888\",\n                        \"region\": \"RegionOne\",\n                        \"internalURL\": \"http://10.0.2.15:8888\",\n                        \"id\": \"3456789\",\n                        \"publicURL\": \"http://172.16.0.1:8888\"\n                    }\n                ],\n                \"endpoints_links\": []\n            },\n            {\n                \"type\": \"dns\",\n                \"name\": \"dns\",\n                \"endpoints\": [\n                    {\n                        \"publicURL\": \"http://172.16.0.1:8776/v1/3456\",\n                        \"tenantId\": \"3456\"\n                    }\n                ]\n            }\n        ]\n    }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/keystoneAuthResponse_openstack.json",
    "content": "{\n    \"access\": {\n        \"token\": {\n            \"expires\": \"2012-03-23T21:44:09\",\n            \"id\": \"Auth_4f173437e4b013bee56d1007\",\n            \"tenant\": {\n                \"id\": \"3456\",\n                \"name\": \"508151008\"\n            }\n        },\n        \"serviceCatalog\": [\n            {\n                \"endpoints\": [\n                    {\n                        \"adminURL\": \"https://nova-api.openstack.org:9774/v2/3456\",\n                        \"region\": \"RegionOne\",\n                        \"internalURL\": \"https://nova-api.openstack.org:9774/v2/3456\",\n                        \"publicURL\": \"https://nova-api.openstack.org:9774/v2/3456\"\n                    }\n                ],\n                \"type\": \"compute\",\n                \"name\": \"nova\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"adminURL\": \"https://GLANCE_API_IS_NOT_DISCLOSED/v1.1/3456\",\n                        \"region\": \"RegionOne\",\n                        \"internalURL\": \"https://GLANCE_API_IS_NOT_DISCLOSED/v1.1/3456\",\n                        \"publicURL\": \"https://GLANCE_API_IS_NOT_DISCLOSED/v1.1/3456\"\n                    }\n                ],\n                \"type\": \"image\",\n                \"name\": \"glance\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"adminURL\": \"https://nova-api.openstack.org:5443/v2.0\",\n                        \"region\": \"RegionOne\",\n                        \"internalURL\": \"https://keystone.thefreecloud.org:5000/v2.0\",\n                        \"publicURL\": \"https://keystone.thefreecloud.org:5000/v2.0\"\n                    }\n                ],\n                \"type\": \"identity\",\n                \"name\": \"keystone\"\n            }\n        ],\n        \"user\": {\n            \"id\": \"43\",\n            \"roles\": [\n                {\n                    \"tenantId\": \"3456\",\n                    \"id\": \"2\",\n                    \"name\": \"Member\"\n                }\n            ],\n            \"name\": \"508151008\"\n        }\n    }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/logback.xml",
    "content": "<?xml version=\"1.0\"?>\n<configuration scan=\"false\">\n    <appender name=\"FILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds.log</file>\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n    <appender name=\"WIREFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds-wire.log</file>\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n    <appender name=\"COMPUTEFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds-compute.log</file>\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <logger name=\"org.jclouds\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"FILE\" />\n    </logger>\n    <logger name=\"jclouds.compute\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"COMPUTEFILE\" />\n    </logger>\n    <logger name=\"jclouds.wire\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n    <logger name=\"jclouds.headers\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n\n    <root>\n        <level value=\"INFO\" />\n    </root>\n</configuration>"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/raxAuth.json",
    "content": "{\n    \"access\": {\n        \"token\": {\n            \"id\": \"Auth_4f173437e4b013bee56d1007\",\n            \"expires\": \"2012-06-06T20:56:47.000-05:00\",\n            \"tenant\": {\n                \"id\": \"40806637803162\",\n                \"name\": \"40806637803162\"\n            }\n        },\n        \"serviceCatalog\": [\n            {\n                \"endpoints\": [\n                    {\n                        \"region\": \"DFW\",\n                        \"tenantId\": \"40806637803162\",\n                        \"publicURL\": \"https://dfw.databases.api.rackspacecloud.com/v1.0/40806637803162\"\n                    },\n                    {\n                        \"region\": \"ORD\",\n                        \"tenantId\": \"40806637803162\",\n                        \"publicURL\": \"https://ord.databases.api.rackspacecloud.com/v1.0/40806637803162\"\n                    }\n                ],\n                \"name\": \"cloudDatabases\",\n                \"type\": \"rax:database\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"tenantId\": \"40806637803162\",\n                        \"publicURL\": \"https://servers.api.rackspacecloud.com/v1.0/40806637803162\",\n                        \"versionInfo\": \"https://servers.api.rackspacecloud.com/v1.0\",\n                        \"versionList\": \"https://servers.api.rackspacecloud.com/\",\n                        \"versionId\": \"1.0\"\n                    }\n                ],\n                \"name\": \"cloudServers\",\n                \"type\": \"compute\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"region\": \"DFW\",\n                        \"tenantId\": \"MossoCloudFS_dc1f419c-5059-4c87-a389-3f2e33a77b22\",\n                        \"publicURL\": \"https://storage101.dfw1.clouddrive.com/v1/MossoCloudFS_dc1f419c-5059-4c87-a389-3f2e33a77b22\",\n                        \"internalURL\": \"https://snet-storage101.dfw1.clouddrive.com/v1/MossoCloudFS_dc1f419c-5059-4c87-a389-3f2e33a77b22\"\n                    }\n                ],\n                \"name\": \"cloudFiles\",\n                \"type\": \"object-store\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"region\": \"DFW\",\n                        \"tenantId\": \"40806637803162\",\n                        \"publicURL\": \"https://dfw.servers.api.rackspacecloud.com/v2/40806637803162\",\n                        \"versionInfo\": \"https://dfw.servers.api.rackspacecloud.com/v2\",\n                        \"versionList\": \"https://dfw.servers.api.rackspacecloud.com/\",\n                        \"versionId\": \"2\"\n                    }\n                ],\n                \"name\": \"cloudServersOpenStack\",\n                \"type\": \"compute\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"region\": \"ORD\",\n                        \"tenantId\": \"40806637803162\",\n                        \"publicURL\": \"https://ord.loadbalancers.api.rackspacecloud.com/v1.0/40806637803162\"\n                    },\n                    {\n                        \"region\": \"DFW\",\n                        \"tenantId\": \"40806637803162\",\n                        \"publicURL\": \"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/40806637803162\"\n                    }\n                ],\n                \"name\": \"cloudLoadBalancers\",\n                \"type\": \"rax:load-balancer\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"publicURL\": \"https://dfw.blockstorage.api.rackspacecloud.com/v1/40806637803162\",\n                        \"tenantId\": \"40806637803162\",\n                        \"region\": \"DFW\"\n                    },\n                    {\n                        \"publicURL\": \"https://ord.blockstorage.api.rackspacecloud.com/v1/40806637803162\",\n                        \"tenantId\": \"40806637803162\",\n                        \"region\": \"ORD\"\n                    }\n                ],\n                \"type\": \"volume\",\n                \"name\": \"cloudBlockStorage\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"tenantId\": \"40806637803162\",\n                        \"publicURL\": \"https://monitoring.api.rackspacecloud.com/v1.0/40806637803162\"\n                    }\n                ],\n                \"name\": \"cloudMonitoring\",\n                \"type\": \"rax:monitor\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"tenantId\": \"40806637803162\",\n                        \"publicURL\": \"https://dns.api.rackspacecloud.com/v1.0/40806637803162\"\n                    }\n                ],\n                \"name\": \"cloudDNS\",\n                \"type\": \"rax:dns\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"region\": \"DFW\",\n                        \"tenantId\": \"MossoCloudFS_dc1f419c-5059-4c87-a389-3f2e33a77b22\",\n                        \"publicURL\": \"https://cdn1.clouddrive.com/v1/MossoCloudFS_dc1f419c-5059-4c87-a389-3f2e33a77b22\"\n                    }\n                ],\n                \"name\": \"cloudFilesCDN\",\n                \"type\": \"rax:object-cdn\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"internalURL\": \"https://snet-dfw.queues.api.rackspacecloud.com/v1/40806637803162\",\n                        \"publicURL\": \"https://dfw.queues.api.rackspacecloud.com/v1/40806637803162\",\n                        \"tenantId\": \"40806637803162\",\n                        \"region\": \"DFW\"\n                    },\n                    {\n                        \"internalURL\": \"https://snet-ord.queues.api.rackspacecloud.com/v1/40806637803162\",\n                        \"publicURL\": \"https://ord.queues.api.rackspacecloud.com/v1/40806637803162\",\n                        \"tenantId\": \"40806637803162\",\n                        \"region\": \"ORD\"\n                    }\n                ],\n                \"type\": \"rax:queues\",\n                \"name\": \"cloudQueues\"\n            }\n        ],\n        \"user\": {\n            \"id\": \"54321\",\n            \"roles\": [\n                {\n                    \"id\": \"3\",\n                    \"description\": \"User Admin Role.\",\n                    \"name\": \"identity:user-admin\"\n                }\n            ],\n            \"name\": \"joe\"\n        }\n    }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/raxCryptoAuth.json",
    "content": "{\n    \"access\": {\n        \"token\": {\n            \"id\": \"AADMTnolqiuwewdqwdqsdf2324f4234fndquipwou12e08_qw23f2e32f2qw4rf2432fddi_ar23d2q32p_DJOIASdd32d2323d23dqoiwjdaosiqowdijOAQIDJWqowid0aisjd_ajoisdjaoisdj1209ejdalo___qwdqwd---sdpoaqwdsaasdisdjw023d23q23edasd435gtf3g3w4egf4g4323efasdsdvsdvsasdvjmhfg43OINAOISndqaiosjkdq0w\",\n            \"expires\": \"2012-06-06T20:56:47.000-05:00\",\n            \"tenant\": {\n                \"id\": \"40806637803162\",\n                \"name\": \"40806637803162\"\n            },\n            \"RAX-AUTH:authenticatedBy\": [\n                \"APIKEY\"\n            ]\n        },\n        \"serviceCatalog\": [\n            {\n                \"endpoints\": [\n                    {\n                        \"region\": \"DFW\",\n                        \"tenantId\": \"40806637803162\",\n                        \"publicURL\": \"https://dfw.databases.api.rackspacecloud.com/v1.0/40806637803162\"\n                    },\n                    {\n                        \"region\": \"ORD\",\n                        \"tenantId\": \"40806637803162\",\n                        \"publicURL\": \"https://ord.databases.api.rackspacecloud.com/v1.0/40806637803162\"\n                    }\n                ],\n                \"name\": \"cloudDatabases\",\n                \"type\": \"rax:database\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"tenantId\": \"40806637803162\",\n                        \"publicURL\": \"https://servers.api.rackspacecloud.com/v1.0/40806637803162\",\n                        \"versionInfo\": \"https://servers.api.rackspacecloud.com/v1.0\",\n                        \"versionList\": \"https://servers.api.rackspacecloud.com/\",\n                        \"versionId\": \"1.0\"\n                    }\n                ],\n                \"name\": \"cloudServers\",\n                \"type\": \"compute\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"region\": \"DFW\",\n                        \"tenantId\": \"MossoCloudFS_dc1f419c-5059-4c87-a389-3f2e33a77b22\",\n                        \"publicURL\": \"https://storage101.dfw1.clouddrive.com/v1/MossoCloudFS_dc1f419c-5059-4c87-a389-3f2e33a77b22\",\n                        \"internalURL\": \"https://snet-storage101.dfw1.clouddrive.com/v1/MossoCloudFS_dc1f419c-5059-4c87-a389-3f2e33a77b22\"\n                    }\n                ],\n                \"name\": \"cloudFiles\",\n                \"type\": \"object-store\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"region\": \"DFW\",\n                        \"tenantId\": \"40806637803162\",\n                        \"publicURL\": \"https://dfw.servers.api.rackspacecloud.com/v2/40806637803162\",\n                        \"versionInfo\": \"https://dfw.servers.api.rackspacecloud.com/v2\",\n                        \"versionList\": \"https://dfw.servers.api.rackspacecloud.com/\",\n                        \"versionId\": \"2\"\n                    }\n                ],\n                \"name\": \"cloudServersOpenStack\",\n                \"type\": \"compute\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"region\": \"ORD\",\n                        \"tenantId\": \"40806637803162\",\n                        \"publicURL\": \"https://ord.loadbalancers.api.rackspacecloud.com/v1.0/40806637803162\"\n                    },\n                    {\n                        \"region\": \"DFW\",\n                        \"tenantId\": \"40806637803162\",\n                        \"publicURL\": \"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/40806637803162\"\n                    }\n                ],\n                \"name\": \"cloudLoadBalancers\",\n                \"type\": \"rax:load-balancer\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"publicURL\": \"https://dfw.blockstorage.api.rackspacecloud.com/v1/40806637803162\",\n                        \"tenantId\": \"40806637803162\",\n                        \"region\": \"DFW\"\n                    },\n                    {\n                        \"publicURL\": \"https://ord.blockstorage.api.rackspacecloud.com/v1/40806637803162\",\n                        \"tenantId\": \"40806637803162\",\n                        \"region\": \"ORD\"\n                    }\n                ],\n                \"type\": \"volume\",\n                \"name\": \"cloudBlockStorage\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"tenantId\": \"40806637803162\",\n                        \"publicURL\": \"https://monitoring.api.rackspacecloud.com/v1.0/40806637803162\"\n                    }\n                ],\n                \"name\": \"cloudMonitoring\",\n                \"type\": \"rax:monitor\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"tenantId\": \"40806637803162\",\n                        \"publicURL\": \"https://dns.api.rackspacecloud.com/v1.0/40806637803162\"\n                    }\n                ],\n                \"name\": \"cloudDNS\",\n                \"type\": \"rax:dns\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"region\": \"DFW\",\n                        \"tenantId\": \"MossoCloudFS_dc1f419c-5059-4c87-a389-3f2e33a77b22\",\n                        \"publicURL\": \"https://cdn1.clouddrive.com/v1/MossoCloudFS_dc1f419c-5059-4c87-a389-3f2e33a77b22\"\n                    }\n                ],\n                \"name\": \"cloudFilesCDN\",\n                \"type\": \"rax:object-cdn\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"internalURL\": \"https://snet-dfw.queues.api.rackspacecloud.com/v1/40806637803162\",\n                        \"publicURL\": \"https://dfw.queues.api.rackspacecloud.com/v1/40806637803162\",\n                        \"tenantId\": \"40806637803162\",\n                        \"region\": \"DFW\"\n                    },\n                    {\n                        \"internalURL\": \"https://snet-ord.queues.api.rackspacecloud.com/v1/40806637803162\",\n                        \"publicURL\": \"https://ord.queues.api.rackspacecloud.com/v1/40806637803162\",\n                        \"tenantId\": \"40806637803162\",\n                        \"region\": \"ORD\"\n                    }\n                ],\n                \"type\": \"rax:queues\",\n                \"name\": \"cloudQueues\"\n            }\n        ],\n        \"user\": {\n            \"id\": \"54321\",\n            \"roles\": [\n                {\n                    \"id\": \"3\",\n                    \"description\": \"User Admin Role.\",\n                    \"name\": \"identity:user-admin\"\n                }\n            ],\n            \"name\": \"joe\"\n        }\n    }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/raxVersion.json",
    "content": "{\n    \"version\": {\n        \"id\": \"v2.0\",\n        \"updated\": \"2012-01-21T11:33:21-06:00\",\n        \"status\": \"BETA\",\n        \"links\": [\n            {\n                \"rel\": \"self\",\n                \"href\": \"https://identity.api.rackspacecloud.com/v2.0\"\n            },\n            {\n                \"rel\": \"describedby\",\n                \"type\": \"application/pdf\",\n                \"href\": \"http://docs.rackspacecloud.com/auth/api/v2.0/auth-client-devguide-latest.pdf\"\n            },\n            {\n                \"rel\": \"describedby\",\n                \"type\": \"application/vnd.sun.wadl+xml\",\n                \"href\": \"http://docs.rackspacecloud.com/auth/api/v2.0/auth.wadl\"\n            }\n        ],\n        \"media-types\": {\n            \"values\": [\n                {\n                    \"base\": \"application/xml\",\n                    \"type\": \"application/vnd.openstack.identity+xml;version=2.0\"\n                },\n                {\n                    \"base\": \"application/json\",\n                    \"type\": \"application/vnd.openstack.identity+json;version=2.0\"\n                }\n            ]\n        }\n    }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/role_create_response.json",
    "content": "{\n    \"role\": {\n        \"id\": \"r1000\",\n        \"name\": \"jclouds-role\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/role_list_response.json",
    "content": "{\n    \"roles\": [\n        {\n            \"id\": \"22529316b2384072b2e8946af5e8cfb6\",\n            \"name\": \"admin\"\n        },\n        {\n            \"enabled\": \"True\",\n            \"description\": \"Default role for project membership\",\n            \"name\": \"_member_\",\n            \"id\": \"9fe2ff9ee4384b1894a90878d3e92bab\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/service_create_response.json",
    "content": "{\n    \"OS-KSADM:service\": {\n        \"id\": \"s1000\",\n        \"type\": \"jclouds-service-type\",\n        \"name\": \"jclouds-service-test\",\n        \"description\": \"jclouds-service-description\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/service_list_response.json",
    "content": "{\n    \"OS-KSADM:services\": [\n        {\n            \"id\": \"150a35a1e24547fdb4122b7fc90929b0\",\n            \"type\": \"network\",\n            \"name\": \"neutron\",\n            \"description\": \"Network Service\"\n        },\n        {\n            \"id\": \"313b229fcede4a148f5bd11199264f8e\",\n            \"type\": \"volume\",\n            \"name\": \"cinder\",\n            \"description\": \"OpenStack Volume Service\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/tenant_create_response.json",
    "content": "{\n    \"tenant\": {\n        \"id\": \"t1000\",\n        \"name\": \"jclouds-tenant\",\n        \"description\": \"jclouds-description\",\n        \"enabled\": true\n    }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/tenant_details.json",
    "content": "{\n    \"tenant\": {\n        \"enabled\": true,\n        \"description\": null,\n        \"name\": \"admin\",\n        \"id\": \"013ba41150a14830bec85ffe93353bcc\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/tenant_list.json",
    "content": "{\n    \"tenants_links\": [],\n    \"tenants\": [\n        {\n            \"enabled\": true,\n            \"description\": null,\n            \"name\": \"demo\",\n            \"id\": \"05d1dc7af71646deba64cfc17b81bec0\"\n        },\n        {\n            \"enabled\": true,\n            \"description\": null,\n            \"name\": \"admin\",\n            \"id\": \"7aa2e17ec29f44d193c48feaba0852cc\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/tenant_list_att.json",
    "content": "{\n    \"tenants\": {\n        \"values\": [\n            {\n                \"enabled\": true,\n                \"description\": \"None\",\n                \"name\": \"this-is-a-test\",\n                \"id\": \"14\"\n            }\n        ],\n        \"links\": []\n    }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/tenant_update_response.json",
    "content": "{\n    \"tenant\": {\n        \"id\": \"t1000\",\n        \"name\": \"jclouds-tenant-modified\",\n        \"description\": \"jclouds-description-modified\",\n        \"enabled\": false\n    }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/token_details.json",
    "content": "{\n    \"access\": {\n        \"token\": {\n            \"expires\": \"2012-04-28T12:42:50Z\",\n            \"id\": \"167eccdc790946969ced473732e8109b\",\n            \"tenant\": {\n                \"id\": \"4cea93f5464b4f1c921fb3e0461d72b5\",\n                \"enabled\": true,\n                \"description\": null,\n                \"name\": \"demo\"\n            }\n        },\n        \"user\": {\n            \"username\": \"admin\",\n            \"roles_links\": [],\n            \"id\": \"2b9b606181634ae9ac86fd95a8bc2cde\",\n            \"roles\": [\n                {\n                    \"id\": \"79cada5c02814b57a52e0eed4dd388cb\",\n                    \"name\": \"admin\"\n                }\n            ],\n            \"name\": \"admin\"\n        }\n    }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/user_create_response.json",
    "content": "{\n    \"user\": {\n        \"id\": \"u1000\",\n        \"name\": \"jqsmith\",\n        \"email\": \"john.smith@example.org\",\n        \"enabled\": true\n    }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/user_details.json",
    "content": "{\n    \"user\": {\n        \"name\": \"nova\",\n        \"enabled\": true,\n        \"email\": \"nova@example.com\",\n        \"id\": \"e021dfd758eb44a89f1c57c8ef3be8e2\",\n        \"tenantId\": \"ab1da202f5774cceb5da2aeff1f0aa87\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/user_endpoints.json",
    "content": "{\n    \"endpoints\": [\n        {\n            \"adminURL\": \"https://csnode.jclouds.org:35357/v2.0/\",\n            \"publicURL\": \"https://csnode.jclouds.org/v2.0/\",\n            \"region\": \"region-a.geo-1\",\n            \"id\": \"2.0\",\n            \"versionId\": \"2.0\",\n            \"list\": \"https://csnode.jclouds.org/extension\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/user_list.json",
    "content": "{\n    \"users\": [\n        {\n            \"name\": \"admin\",\n            \"enabled\": true,\n            \"email\": \"admin@example.com\",\n            \"id\": \"2b9b606181634ae9ac86fd95a8bc2cde\",\n            \"tenantId\": null\n        },\n        {\n            \"name\": \"demo\",\n            \"enabled\": true,\n            \"email\": \"demo@example.com\",\n            \"id\": \"667b2e1420604df8b67cd8ea57d4ee64\",\n            \"tenantId\": null\n        },\n        {\n            \"name\": \"nova\",\n            \"enabled\": true,\n            \"email\": \"nova@example.com\",\n            \"id\": \"e021dfd758eb44a89f1c57c8ef3be8e2\",\n            \"tenantId\": \"ab1da202f5774cceb5da2aeff1f0aa87\"\n        },\n        {\n            \"name\": \"glance\",\n            \"enabled\": true,\n            \"email\": \"glance@example.com\",\n            \"id\": \"3f6c1c9ba993495ead7d2eb2192e284f\",\n            \"tenantId\": \"ab1da202f5774cceb5da2aeff1f0aa87\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/user_role_list.json",
    "content": "{\n    \"roles\": [\n        {\n            \"id\": \"79cada5c02814b57a52e0eed4dd388cb\",\n            \"name\": \"admin\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/user_tenant_role_list.json",
    "content": "{\n    \"roles\": [\n        {\n            \"id\": \"31c451195aac49b386039341e2c92a16\",\n            \"name\": \"KeystoneServiceAdmin\"\n        },\n        {\n            \"id\": \"79cada5c02814b57a52e0eed4dd388cb\",\n            \"name\": \"admin\"\n        },\n        {\n            \"id\": \"6ea17ddd37a6447794cb0e164d4db894\",\n            \"name\": \"KeystoneAdmin\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/user_update_response.json",
    "content": "{\n    \"user\": {\n        \"id\": \"u1000\",\n        \"name\": \"jqsmith-renamed\",\n        \"email\": \"john.smith.renamed@example.org\",\n        \"enabled\": false\n    }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/v3/auth-accesskey.json",
    "content": "{\n    \"auth\": {\n        \"identity\": {\n            \"methods\": [\n                \"application_credential\"\n            ],\n            \"application_credential\": {\n                \"id\": \"identity\",\n                \"secret\": \"credential\"\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/v3/auth-password-project-scoped-id-domain-id.json",
    "content": "{\n    \"auth\": {\n        \"identity\": {\n            \"methods\": [\n                \"password\"\n            ],\n            \"password\": {\n                \"user\": {\n                    \"name\": \"identity\",\n                    \"domain\": {\n                        \"name\": \"domain\"\n                    },\n                    \"password\": \"credential\"\n                }\n            }\n        },\n        \"scope\": {\n            \"project\": {\n                \"id\": \"42-project-42\",\n                \"domain\": {\n                    \"id\": \"42-domain-42\"\n                }\n            }\n        }\n    }\n}"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/v3/auth-password-project-scoped-id-domain-name.json",
    "content": "{\n    \"auth\": {\n        \"identity\": {\n            \"methods\": [\n                \"password\"\n            ],\n            \"password\": {\n                \"user\": {\n                    \"name\": \"identity\",\n                    \"domain\": {\n                        \"name\": \"domain\"\n                    },\n                    \"password\": \"credential\"\n                }\n            }\n        },\n        \"scope\": {\n            \"project\": {\n                \"id\": \"42\",\n                \"domain\": {\n                    \"name\": \"default\"\n                }\n            }\n        }\n    }\n}"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/v3/auth-password-project-scoped-name-domain-backwards-compat.json",
    "content": "{\n    \"auth\": {\n        \"identity\": {\n            \"methods\": [\n                \"password\"\n            ],\n            \"password\": {\n                \"user\": {\n                    \"name\": \"identity\",\n                    \"domain\": {\n                        \"name\": \"domain\"\n                    },\n                    \"password\": \"credential\"\n                }\n            }\n        },\n        \"scope\": {\n            \"project\": {\n                \"name\": \"my-project\",\n                \"domain\": {\n                    \"id\": \"default\"\n                }\n            }\n        }\n    }\n}"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/v3/auth-password-project-scoped-name-domain-id.json",
    "content": "{\n    \"auth\": {\n        \"identity\": {\n            \"methods\": [\n                \"password\"\n            ],\n            \"password\": {\n                \"user\": {\n                    \"name\": \"identity\",\n                    \"domain\": {\n                        \"name\": \"domain\"\n                    },\n                    \"password\": \"credential\"\n                }\n            }\n        },\n        \"scope\": {\n            \"project\": {\n                \"name\": \"my-project\",\n                \"domain\": {\n                    \"id\": \"42\"\n                }\n            }\n        }\n    }\n}"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/v3/auth-password-project-scoped-name-domain-name.json",
    "content": "{\n    \"auth\": {\n        \"identity\": {\n            \"methods\": [\n                \"password\"\n            ],\n            \"password\": {\n                \"user\": {\n                    \"name\": \"identity\",\n                    \"domain\": {\n                        \"name\": \"domain\"\n                    },\n                    \"password\": \"credential\"\n                }\n            }\n        },\n        \"scope\": {\n            \"project\": {\n                \"name\": \"my-project\",\n                \"domain\": {\n                    \"name\": \"default\"\n                }\n            }\n        }\n    }\n}"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/v3/auth-password-scoped.json",
    "content": "{\n    \"auth\": {\n        \"identity\": {\n            \"methods\": [\n                \"password\"\n            ],\n            \"password\": {\n                \"user\": {\n                    \"name\": \"identity\",\n                    \"domain\": {\n                        \"name\": \"domain\"\n                    },\n                    \"password\": \"credential\"\n                }\n            }\n        },\n        \"scope\": {\n            \"project\": {\n                \"id\": \"1234567890\"\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/v3/auth-password.json",
    "content": "{\n    \"auth\": {\n        \"identity\": {\n            \"methods\": [\n                \"password\"\n            ],\n            \"password\": {\n                \"user\": {\n                    \"name\": \"identity\",\n                    \"domain\": {\n                        \"name\": \"domain\"\n                    },\n                    \"password\": \"credential\"\n                }\n            }\n        },\n        \"scope\": \"unscoped\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/v3/auth-token-scoped.json",
    "content": "{\n    \"auth\": {\n        \"identity\": {\n            \"methods\": [\n                \"token\"\n            ],\n            \"token\": {\n                \"id\": \"token\"\n            }\n        },\n        \"scope\": {\n            \"domain\": {\n                \"name\": \"mydomain\"\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/v3/auth-token.json",
    "content": "{\n    \"auth\": {\n        \"identity\": {\n            \"methods\": [\n                \"token\"\n            ],\n            \"token\": {\n                \"id\": \"token\"\n            }\n        },\n        \"scope\": \"unscoped\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/v3/endpoints.json",
    "content": "{\n  \"endpoints\": [\n    {\n      \"region_id\": \"RegionOne\",\n      \"links\": {\n        \"self\": \"http://localhost/identity/v3/endpoints/151d1dd2c86b4af783143ab1aa9d9a39\"\n      },\n      \"url\": \"http://localhost/compute/v2/$(project_id)s\",\n      \"region\": \"RegionOne\",\n      \"enabled\": true,\n      \"interface\": \"public\",\n      \"service_id\": \"a14c47dc13194bf2a2195e861db9f906\",\n      \"id\": \"151d1dd2c86b4af783143ab1aa9d9a39\"\n    },\n    {\n      \"region_id\": \"RegionOne\",\n      \"links\": {\n        \"self\": \"http://localhost/identity/v3/endpoints/1a9f6c6bea0e4ff5bb8b17e3647a706e\"\n      },\n      \"url\": \"http://localhost/volume/v2/$(project_id)s\",\n      \"region\": \"RegionOne\",\n      \"enabled\": true,\n      \"interface\": \"public\",\n      \"service_id\": \"238841bcff5f4f2b9ee2f7973c19e22a\",\n      \"id\": \"1a9f6c6bea0e4ff5bb8b17e3647a706e\"\n    },\n    {\n      \"region_id\": \"RegionOne\",\n      \"links\": {\n        \"self\": \"http://localhost/identity/v3/endpoints/206d6d831dbf44ccad854ffb419b4f02\"\n      },\n      \"url\": \"http://localhost/volume/v1/$(project_id)s\",\n      \"region\": \"RegionOne\",\n      \"enabled\": true,\n      \"interface\": \"public\",\n      \"service_id\": \"a222e99e3d24476baa7762858dc34006\",\n      \"id\": \"206d6d831dbf44ccad854ffb419b4f02\"\n    },\n    {\n      \"region_id\": \"RegionOne\",\n      \"links\": {\n        \"self\": \"http://localhost/identity/v3/endpoints/23f60684390f4376aca5d828f2381e6e\"\n      },\n      \"url\": \"http://localhost:8080\",\n      \"region\": \"RegionOne\",\n      \"enabled\": true,\n      \"interface\": \"admin\",\n      \"service_id\": \"2774503aa5354d70a801df09a813db46\",\n      \"id\": \"23f60684390f4376aca5d828f2381e6e\"\n    },\n    {\n      \"region_id\": \"RegionOne\",\n      \"links\": {\n        \"self\": \"http://localhost/identity/v3/endpoints/572671cba1d34bd29fdd160eac891971\"\n      },\n      \"url\": \"http://localhost/volume/v3/$(project_id)s\",\n      \"region\": \"RegionOne\",\n      \"enabled\": true,\n      \"interface\": \"public\",\n      \"service_id\": \"be984bfb8b5f447d8a0ea3fa075054fc\",\n      \"id\": \"572671cba1d34bd29fdd160eac891971\"\n    },\n    {\n      \"region_id\": \"RegionOne\",\n      \"links\": {\n        \"self\": \"http://localhost/identity/v3/endpoints/882c0c04727744ee8d20839f5f9eec9a\"\n      },\n      \"url\": \"http://localhost/compute/v2.1\",\n      \"region\": \"RegionOne\",\n      \"enabled\": true,\n      \"interface\": \"public\",\n      \"service_id\": \"fcc6a934957545bbb5fee29a217530ef\",\n      \"id\": \"882c0c04727744ee8d20839f5f9eec9a\"\n    },\n    {\n      \"region_id\": \"RegionOne\",\n      \"links\": {\n        \"self\": \"http://localhost/identity/v3/endpoints/9f1b314e3bc5403a8dcdef14c9eb044c\"\n      },\n      \"url\": \"http://localhost/identity/v3\",\n      \"region\": \"RegionOne\",\n      \"enabled\": true,\n      \"interface\": \"public\",\n      \"service_id\": \"6b73ec12f7754a8696d758561a1cf5f1\",\n      \"id\": \"9f1b314e3bc5403a8dcdef14c9eb044c\"\n    },\n    {\n      \"region_id\": \"RegionOne\",\n      \"links\": {\n        \"self\": \"http://localhost/identity/v3/endpoints/bb2aa713d1154809aeb414e6fd71ba95\"\n      },\n      \"url\": \"http://localhost/image\",\n      \"region\": \"RegionOne\",\n      \"enabled\": true,\n      \"interface\": \"public\",\n      \"service_id\": \"5dbcb1098b2e41e083c05c9006bd9830\",\n      \"id\": \"bb2aa713d1154809aeb414e6fd71ba95\"\n    },\n    {\n      \"region_id\": \"RegionOne\",\n      \"links\": {\n        \"self\": \"http://localhost/identity/v3/endpoints/dcf25870430f468d8f8dfd9d3acb95cc\"\n      },\n      \"url\": \"http://localhost:9696/\",\n      \"region\": \"RegionOne\",\n      \"enabled\": true,\n      \"interface\": \"public\",\n      \"service_id\": \"d12688144a6e4d9db17ead14f4670d5b\",\n      \"id\": \"dcf25870430f468d8f8dfd9d3acb95cc\"\n    },\n    {\n      \"region_id\": \"RegionOne\",\n      \"links\": {\n        \"self\": \"http://localhost/identity/v3/endpoints/eb1517fb194a4df09109aa4606c245b9\"\n      },\n      \"url\": \"http://localhost/identity/v3\",\n      \"region\": \"RegionOne\",\n      \"enabled\": true,\n      \"interface\": \"admin\",\n      \"service_id\": \"6b73ec12f7754a8696d758561a1cf5f1\",\n      \"id\": \"eb1517fb194a4df09109aa4606c245b9\"\n    },\n    {\n      \"region_id\": \"RegionOne\",\n      \"links\": {\n        \"self\": \"http://localhost/identity/v3/endpoints/edd066392b3549508739e18d5e69dbb7\"\n      },\n      \"url\": \"http://localhost/placement\",\n      \"region\": \"RegionOne\",\n      \"enabled\": true,\n      \"interface\": \"public\",\n      \"service_id\": \"74efa863cb264dcbba922ff254a19876\",\n      \"id\": \"edd066392b3549508739e18d5e69dbb7\"\n    },\n    {\n      \"region_id\": \"RegionOne\",\n      \"links\": {\n        \"self\": \"http://localhost/identity/v3/endpoints/ef84daa849894b8ebda274615a083139\"\n      },\n      \"url\": \"http://localhost:8080/v1/AUTH_$(project_id)s\",\n      \"region\": \"RegionOne\",\n      \"enabled\": true,\n      \"interface\": \"public\",\n      \"service_id\": \"2774503aa5354d70a801df09a813db46\",\n      \"id\": \"ef84daa849894b8ebda274615a083139\"\n    }\n  ],\n  \"links\": {\n    \"self\": \"http://localhost/identity/v3/endpoints\",\n    \"previous\": null,\n    \"next\": null\n  }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/v3/groups.json",
    "content": "{\n    \"groups\": [\n        {\n            \"description\": \"Developers cleared for work on all general projects\",\n            \"domain_id\": \"1789d1\",\n            \"id\": \"ea167b\",\n            \"links\": {\n                \"self\": \"https://example.com/identity/v3/groups/ea167b\"\n            },\n            \"name\": \"Developers\"\n        },\n        {\n            \"description\": \"Developers cleared for work on secret projects\",\n            \"domain_id\": \"1789d1\",\n            \"id\": \"a62db1\",\n            \"links\": {\n                \"self\": \"https://example.com/identity/v3/groups/a62db1\"\n            },\n            \"name\": \"Secure Developers\"\n        }\n    ],\n    \"links\": {\n        \"self\": \"http://example.com/identity/v3/users/9fe1d3/groups\",\n        \"previous\": null,\n        \"next\": null\n    }\n}"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/v3/project.json",
    "content": "{\n  \"project\": {\n    \"is_domain\": false,\n    \"description\": \"Updated\",\n    \"links\": {\n      \"self\": \"http://localhost/identity/v3/projects/2f9b30f706bc45d7923e055567be2e98\"\n    },\n    \"tags\": [],\n    \"enabled\": true,\n    \"id\": \"2f9b30f706bc45d7923e055567be2e98\",\n    \"parent_id\": \"default\",\n    \"domain_id\": \"default\",\n    \"name\": \"ProjectApiLiveTest\"\n  }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/v3/projects.json",
    "content": "{\n  \"links\": {\n    \"self\": \"http://localhost/identity/v3/projects\",\n    \"previous\": null,\n    \"next\": null\n  },\n  \"projects\": [\n    {\n      \"is_domain\": false,\n      \"description\": \"Updated\",\n      \"links\": {\n        \"self\": \"http://localhost/identity/v3/projects/2f9b30f706bc45d7923e055567be2e98\"\n      },\n      \"tags\": [],\n      \"enabled\": true,\n      \"id\": \"2f9b30f706bc45d7923e055567be2e98\",\n      \"parent_id\": \"default\",\n      \"domain_id\": \"default\",\n      \"name\": \"ProjectApiLiveTest\"\n    },\n    {\n      \"is_domain\": false,\n      \"description\": \"\",\n      \"links\": {\n        \"self\": \"http://localhost/identity/v3/projects/2fa489f9b84541b8a614c8c9df0d7596\"\n      },\n      \"tags\": [],\n      \"enabled\": true,\n      \"id\": \"2fa489f9b84541b8a614c8c9df0d7596\",\n      \"parent_id\": \"default\",\n      \"domain_id\": \"default\",\n      \"name\": \"service\"\n    },\n    {\n      \"is_domain\": false,\n      \"description\": \"\",\n      \"links\": {\n        \"self\": \"http://localhost/identity/v3/projects/43de288ea0ce4d2b8b811055b10f156b\"\n      },\n      \"tags\": [],\n      \"enabled\": true,\n      \"id\": \"43de288ea0ce4d2b8b811055b10f156b\",\n      \"parent_id\": \"default\",\n      \"domain_id\": \"default\",\n      \"name\": \"jclouds\"\n    },\n    {\n      \"is_domain\": false,\n      \"description\": \"Bootstrap project for initializing the cloud.\",\n      \"links\": {\n        \"self\": \"http://localhost/identity/v3/projects/90131053e7384f8a9e970544e0845913\"\n      },\n      \"tags\": [],\n      \"enabled\": true,\n      \"id\": \"90131053e7384f8a9e970544e0845913\",\n      \"parent_id\": \"default\",\n      \"domain_id\": \"default\",\n      \"name\": \"admin\"\n    },\n    {\n      \"is_domain\": false,\n      \"description\": \"\",\n      \"links\": {\n        \"self\": \"http://localhost/identity/v3/projects/d91b807dc87d477381500e8c920b10c7\"\n      },\n      \"tags\": [],\n      \"enabled\": true,\n      \"id\": \"d91b807dc87d477381500e8c920b10c7\",\n      \"parent_id\": \"default\",\n      \"domain_id\": \"default\",\n      \"name\": \"demo\"\n    }\n  ]\n}"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/v3/region.json",
    "content": "{\n  \"region\": {\n    \"parent_region_id\": null,\n    \"id\": \"RegionOne\",\n    \"links\": {\n      \"self\": \"http://localhost/identity/v3/regions/RegionApiLiveTest\"\n    },\n    \"description\": \"Updated\"\n  }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/v3/regions.json",
    "content": "{\n  \"regions\": [\n    {\n      \"parent_region_id\": null,\n      \"id\": \"RegionOne\",\n      \"links\": {\n        \"self\": \"http://localhost/identity/v3/regions/RegionOne\"\n      },\n      \"description\": \"\"\n    }\n  ],\n  \"links\": {\n    \"self\": \"http://localhost/identity/v3/regions\",\n    \"previous\": null,\n    \"next\": null\n  }\n}\n\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/v3/token.json",
    "content": "{\n  \"token\": {\n    \"methods\": [\n      \"password\"\n    ],\n    \"roles\": [\n      {\n        \"id\": \"9fe2ff9ee4384b1894a90878d3e92bab\",\n        \"name\": \"_member_\"\n      },\n      {\n        \"id\": \"df7d043a09d34a7c9e2bad15926ee097\",\n        \"name\": \"cpf_org_manager\"\n      },\n      {\n        \"id\": \"3af119c426a742999e7890f6d1f70b36\",\n        \"name\": \"cpf_admin\"\n      }\n    ],\n    \"expires_at\": \"2017-12-10T11:48:46.546830Z\",\n    \"project\": {\n      \"domain\": {\n        \"id\": \"2347b158dcaf488496b44cc4edfd2bd8\",\n        \"name\": \"0kjFQF29\"\n      },\n      \"id\": \"2233c4d7d5c044b1b48e1bef25c1f305\",\n      \"name\": \"0kjFQF29-prj\"\n    },\n    \"catalog\": [\n      {\n        \"endpoints\": [\n          {\n            \"region_id\": \"uk-1\",\n            \"url\": \"https://objectstorage.myprovider.com/v1/AUTH_2233c4d7d5c044b1b48e1bef25c1f305\",\n            \"region\": \"uk-1\",\n            \"interface\": \"public\",\n            \"id\": \"b506af0e016a4b5fb592f196da569a41\",\n            \"name\": \"objectstorage\"\n          }\n        ],\n        \"type\": \"object-store\",\n        \"id\": \"024329e4fde148e58ecd90b7d9872438\",\n        \"name\": \"objectstorage\"\n      },\n      {\n        \"endpoints\": [\n          {\n            \"region_id\": \"uk-1\",\n            \"url\": \"https://keymanagement.myprovider.com/v1\",\n            \"region\": \"uk-1\",\n            \"interface\": \"public\",\n            \"id\": \"0419c448001845af8f6828cf49745e72\",\n            \"name\": \"keymanagement\"\n          }\n        ],\n        \"type\": \"keystore\",\n        \"id\": \"07f309b0ef9d42758ea4de47bdca9c32\",\n        \"name\": \"keymanagement\"\n      },\n      {\n        \"endpoints\": [\n          {\n            \"region_id\": \"uk-1\",\n            \"url\": \"https://certificate.myprovider.com/v1\",\n            \"region\": \"uk-1\",\n            \"interface\": \"public\",\n            \"id\": \"e1cc93936fb94cdbadc20f17c4ad3140\",\n            \"name\": \"certificate\"\n          }\n        ],\n        \"type\": \"certificate\",\n        \"id\": \"0bd9a971e97d4c15af6b94311e4e9c15\",\n        \"name\": \"certificate\"\n      },\n      {\n        \"endpoints\": [\n          {\n            \"region_id\": \"uk-1\",\n            \"url\": \"https://orchestration.myprovider.com/v1/2233c4d7d5c044b1b48e1bef25c1f305\",\n            \"region\": \"uk-1\",\n            \"interface\": \"public\",\n            \"id\": \"c3ee708a6ae24ddf92c078526c36a446\",\n            \"name\": \"orchestration\"\n          }\n        ],\n        \"type\": \"orchestration\",\n        \"id\": \"0dafa2a9240c41268c37818979769c88\",\n        \"name\": \"orchestration\"\n      },\n      {\n        \"endpoints\": [\n          {\n            \"region_id\": \"uk-1\",\n            \"url\": \"https://blockstorage.myprovider.com/v1/2233c4d7d5c044b1b48e1bef25c1f305\",\n            \"region\": \"uk-1\",\n            \"interface\": \"public\",\n            \"id\": \"ba9061d324954b1a9f6b1c1f5d4a5c5e\",\n            \"name\": \"blockstorage\"\n          }\n        ],\n        \"type\": \"volume\",\n        \"id\": \"0ec640e57e4d4374841d2ab7b292f2c2\",\n        \"name\": \"blockstorage\"\n      },\n      {\n        \"endpoints\": [\n          {\n            \"region_id\": \"uk-1\",\n            \"url\": \"https://loadbalancing.myprovider.com\",\n            \"region\": \"uk-1\",\n            \"interface\": \"public\",\n            \"id\": \"169bcb3f92384f709232864f4d5304eb\",\n            \"name\": \"loadbalancing\"\n          }\n        ],\n        \"type\": \"loadbalancing\",\n        \"id\": \"15ef761fa00a438985213aec7b6fb18a\",\n        \"name\": \"loadbalancing\"\n      },\n      {\n        \"endpoints\": [],\n        \"type\": \"dwh\",\n        \"id\": \"1a53a2e82370422d90174c4acf585ea9\",\n        \"name\": \"dwh\"\n      },\n      {\n        \"endpoints\": [],\n        \"type\": \"contract\",\n        \"id\": \"1b35fa74ae0e46ebbc2014f976fec0e1\",\n        \"name\": \"contract\"\n      },\n      {\n        \"endpoints\": [],\n        \"type\": \"appplatform\",\n        \"id\": \"253096ed430c49c48c9f3549e867b538\",\n        \"name\": \"appplatform\"\n      },\n      {\n        \"endpoints\": [\n          {\n            \"region_id\": \"uk-1\",\n            \"url\": \"https://compute-w.myprovider.com\",\n            \"region\": \"uk-1\",\n            \"interface\": \"public\",\n            \"id\": \"e26ad89a682d4c8f8a71c9e76cd785b4\",\n            \"name\": \"compute-w\"\n          }\n        ],\n        \"type\": \"compute-w\",\n        \"id\": \"327c11710f184555b43bc6fdfc47626b\",\n        \"name\": \"compute-w\"\n      },\n      {\n        \"endpoints\": [],\n        \"type\": \"notification\",\n        \"id\": \"3435ad7a1da04b1cb2e249665529eb51\",\n        \"name\": \"notification\"\n      },\n      {\n        \"endpoints\": [\n          {\n            \"region_id\": \"uk-1\",\n            \"url\": \"https://compute.myprovider.com/v2/2233c4d7d5c044b1b48e1bef25c1f305\",\n            \"region\": \"uk-1\",\n            \"interface\": \"public\",\n            \"id\": \"f70e51b9a6a74a87a4c7055b8df8bedf\",\n            \"name\": \"compute\"\n          }\n        ],\n        \"type\": \"compute\",\n        \"id\": \"3e19093f50cc4590973c8953e2c327f9\",\n        \"name\": \"compute\"\n      },\n      {\n        \"endpoints\": [\n          {\n            \"region_id\": \"uk-1\",\n            \"url\": \"https://queue.myprovider.com\",\n            \"region\": \"uk-1\",\n            \"interface\": \"public\",\n            \"id\": \"c46b5ec51ab04402a9ffd8177743ba6f\",\n            \"name\": \"queue\"\n          }\n        ],\n        \"type\": \"queue\",\n        \"id\": \"4a9ab69b74ec4948a0a6958177d30387\",\n        \"name\": \"queue\"\n      },\n      {\n        \"endpoints\": [\n          {\n            \"region_id\": \"uk-1\",\n            \"url\": \"https://autoscale.myprovider.com/autoscale_schedulers\",\n            \"region\": \"uk-1\",\n            \"interface\": \"public\",\n            \"id\": \"071ee50be4b341558e37f84abac47d02\",\n            \"name\": \"autoscale\"\n          }\n        ],\n        \"type\": \"autoscale\",\n        \"id\": \"4f158b2836434c7ca6ee47e40a3ee56c\",\n        \"name\": \"autoscale\"\n      },\n      {\n        \"endpoints\": [\n          {\n            \"region_id\": \"uk-1\",\n            \"url\": \"https://telemetry.myprovider.com\",\n            \"region\": \"uk-1\",\n            \"interface\": \"public\",\n            \"id\": \"6ac15657fbc548d7ab2ed986b8d94192\",\n            \"name\": \"telemetry\"\n          }\n        ],\n        \"type\": \"metering\",\n        \"id\": \"54ee7596f0e1433cb8db6201be2cf772\",\n        \"name\": \"telemetry\"\n      },\n      {\n        \"endpoints\": [],\n        \"type\": \"cdn\",\n        \"id\": \"5954129d136e4a76b7cd6f3d1f3808b5\",\n        \"name\": \"cdn\"\n      },\n      {\n        \"endpoints\": [],\n        \"type\": \"oss\",\n        \"id\": \"5a252878ffd7402498b6b74b575a899a\",\n        \"name\": \"oss\"\n      },\n      {\n        \"endpoints\": [\n          {\n            \"region_id\": \"uk-1\",\n            \"url\": \"https://rolemanagement.myprovider.com/v1\",\n            \"region\": \"uk-1\",\n            \"interface\": \"public\",\n            \"id\": \"2d600a5de6ec42c6a5eab7b519832d87\",\n            \"name\": \"rolemanagement\"\n          }\n        ],\n        \"type\": \"rolemanagement\",\n        \"id\": \"5bc90099f0ad490c811239a6a3a8f853\",\n        \"name\": \"rolemanagement\"\n      },\n      {\n        \"endpoints\": [\n          {\n            \"region_id\": \"uk-1\",\n            \"url\": \"https://compute-b.myprovider.com\",\n            \"region\": \"uk-1\",\n            \"interface\": \"public\",\n            \"id\": \"768450282d5546409395d2cb35502dad\",\n            \"name\": \"compute-b\"\n          }\n        ],\n        \"type\": \"compute-b\",\n        \"id\": \"65f754202b6049578e9a292a801e28f7\",\n        \"name\": \"compute-b\"\n      },\n      {\n        \"endpoints\": [\n          {\n            \"region_id\": \"uk-1\",\n            \"url\": \"https://networking.myprovider.com\",\n            \"region\": \"uk-1\",\n            \"interface\": \"public\",\n            \"id\": \"675910513a7e466c84c39c5ca9445b81\",\n            \"name\": \"networking\"\n          }\n        ],\n        \"type\": \"network\",\n        \"id\": \"6cf37e33dc7140b9b032faabfa53a53e\",\n        \"name\": \"networking\"\n      },\n      {\n        \"endpoints\": [],\n        \"type\": \"dns\",\n        \"id\": \"7426c97af5174c1abdb8b84ba02227ce\",\n        \"name\": \"dns\"\n      },\n      {\n        \"endpoints\": [\n          {\n            \"region_id\": \"uk-1\",\n            \"url\": \"https://database.myprovider.com/v1.0/2233c4d7d5c044b1b48e1bef25c1f305\",\n            \"region\": \"uk-1\",\n            \"interface\": \"public\",\n            \"id\": \"6976cbeed14c464da15c13e949b41607\",\n            \"name\": \"database\"\n          }\n        ],\n        \"type\": \"database\",\n        \"id\": \"75c0280f15844d7a9eb22b1ad5a978e8\",\n        \"name\": \"database\"\n      },\n      {\n        \"endpoints\": [\n          {\n            \"region_id\": \"uk-1\",\n            \"url\": \"http://localhost/identity/v3\",\n            \"region\": \"uk-1\",\n            \"interface\": \"admin\",\n            \"id\": \"db15a7126d4a4f1f81903bb4d56be32b\",\n            \"name\": \"identity\"\n          }\n        ],\n        \"type\": \"identity\",\n        \"id\": \"79066fe949064550930a61b33a49eb53\",\n        \"name\": \"identity\"\n      },\n      {\n        \"endpoints\": [],\n        \"type\": \"intdns\",\n        \"id\": \"804190a423804019aab8fd934db0086e\",\n        \"name\": \"intdns\"\n      },\n      {\n        \"endpoints\": [],\n        \"type\": \"invoicing\",\n        \"id\": \"8d364df08cbc4d7188f0cf83744b0336\",\n        \"name\": \"invoicing\"\n      },\n      {\n        \"endpoints\": [],\n        \"type\": \"catalog\",\n        \"id\": \"9674ae5917af401397071c028ff33b68\",\n        \"name\": \"catalog\"\n      },\n      {\n        \"endpoints\": [\n          {\n            \"region_id\": \"uk-1\",\n            \"url\": \"https://software.myprovider.com/v1.0\",\n            \"region\": \"uk-1\",\n            \"interface\": \"public\",\n            \"id\": \"fd6g35fgknrzumut7bx6p6bwzehkfhrz\",\n            \"name\": \"software\"\n          }\n        ],\n        \"type\": \"software\",\n        \"id\": \"9760973e49b04b00b41e60c180a80562\",\n        \"name\": \"software\"\n      },\n      {\n        \"endpoints\": [\n          {\n            \"region_id\": \"uk-1\",\n            \"url\": \"https://blockstorage.myprovider.com/v2/2233c4d7d5c044b1b48e1bef25c1f305\",\n            \"region\": \"uk-1\",\n            \"interface\": \"public\",\n            \"id\": \"8c4ace3bbbd44883b5762a9ad8432a46\",\n            \"name\": \"blockstoragev2\"\n          }\n        ],\n        \"type\": \"volumev2\",\n        \"id\": \"9bf82d0466714eee86e304ab3301aec9\",\n        \"name\": \"blockstorage\"\n      },\n      {\n        \"endpoints\": [],\n        \"type\": \"dnsadmin\",\n        \"id\": \"a2b90094346c48deabb9ca645bacf588\",\n        \"name\": \"dnsadmin\"\n      },\n      {\n        \"endpoints\": [\n          {\n            \"region_id\": \"uk-1\",\n            \"url\": \"https://vmimport.myprovider.com\",\n            \"region\": \"uk-1\",\n            \"interface\": \"public\",\n            \"id\": \"225257ec50ef47668185587cc6edb95d\",\n            \"name\": \"vmimport\"\n          }\n        ],\n        \"type\": \"vmimport\",\n        \"id\": \"c73fa07c3b604b4f89d5a2b9c4621cf2\",\n        \"name\": \"vmimport\"\n      },\n      {\n        \"endpoints\": [\n          {\n            \"region_id\": \"uk-1\",\n            \"url\": \"http://localhost/identity/v3\",\n            \"region\": \"uk-1\",\n            \"interface\": \"public\",\n            \"id\": \"27dc2bba1c5d4a14b68657fc8fdd4e3e\",\n            \"name\": \"identityv3\"\n          },\n          {\n            \"region_id\": \"uk-1\",\n            \"url\": \"http://localhost/identity/v3\",\n            \"region\": \"uk-1\",\n            \"interface\": \"admin\",\n            \"id\": \"27dc2bba1c5d4a14b68657fc8fdd4e3e\",\n            \"name\": \"identityv3\"\n          }\n        ],\n        \"type\": \"identityv3\",\n        \"id\": \"cc6f50d496884ef0a751acb2e1eceedd\",\n        \"name\": \"identityv3\"\n      },\n      {\n        \"endpoints\": [\n          {\n            \"region_id\": \"uk-1\",\n            \"url\": \"https://applicationmanagement.myprovider.com\",\n            \"region\": \"uk-1\",\n            \"interface\": \"public\",\n            \"id\": \"06fbcf8235434f23a08faed03b4af9ac\",\n            \"name\": \"appmanagement\"\n          }\n        ],\n        \"type\": \"appmanagement\",\n        \"id\": \"ce2f6bbe7a9f446b82d63725bd7bb484\",\n        \"name\": \"appmanagement\"\n      },\n      {\n        \"endpoints\": [],\n        \"type\": \"nosql\",\n        \"id\": \"d07aa581c0734b6bb85cd496115b5110\",\n        \"name\": \"nosql\"\n      },\n      {\n        \"endpoints\": [],\n        \"type\": \"baremetal\",\n        \"id\": \"d2f57dcae4c84466ac357220ff3d8900\",\n        \"name\": \"baremetal\"\n      },\n      {\n        \"endpoints\": [],\n        \"type\": \"mail\",\n        \"id\": \"d4601f51af8f43f3b0e3409e4cbac690\",\n        \"name\": \"mail\"\n      },\n      {\n        \"endpoints\": [\n          {\n            \"region_id\": \"uk-1\",\n            \"url\": \"https://networking-ex.myprovider.com\",\n            \"region\": \"uk-1\",\n            \"interface\": \"public\",\n            \"id\": \"bf356065e45349a5bde5e043c95a1923\",\n            \"name\": \"networking-ex\"\n          }\n        ],\n        \"type\": \"networking-ex\",\n        \"id\": \"d4937aa1275c41378bf2ae1dbe829c68\",\n        \"name\": \"networking-ex\"\n      },\n      {\n        \"endpoints\": [\n          {\n            \"region_id\": \"jp-east-1\",\n            \"url\": \"https://identity.gls.cloud.global.fujitsu.com/v3\",\n            \"region\": \"jp-east-1\",\n            \"interface\": \"public\",\n            \"id\": \"dc2ebf9d6fc04f1facc263a733cf754d\",\n            \"name\": \"global-identity\"\n          }\n        ],\n        \"type\": \"global-identity\",\n        \"id\": \"e74b9c29d6504f10a8fb8e1495f3f5c6\",\n        \"name\": \"global-identity\"\n      },\n      {\n        \"endpoints\": [\n          {\n            \"region_id\": \"uk-1\",\n            \"url\": \"https://image.myprovider.com\",\n            \"region\": \"uk-1\",\n            \"interface\": \"public\",\n            \"id\": \"a832d640886b4ef89027339a2edf8fcd\",\n            \"name\": \"image\"\n          }\n        ],\n        \"type\": \"image\",\n        \"id\": \"ea850dab0e964e12a9f66787ee8623ae\",\n        \"name\": \"image\"\n      },\n      {\n        \"endpoints\": [],\n        \"type\": \"billing\",\n        \"id\": \"f1302a2477bf492bb3e867952175974a\",\n        \"name\": \"billing\"\n      },\n      {\n        \"endpoints\": [\n          {\n            \"region_id\": \"uk-1\",\n            \"url\": \"https://import-export.myprovider.com\",\n            \"region\": \"uk-1\",\n            \"interface\": \"public\",\n            \"id\": \"e8bde8fe61a14a88b414e5568fc17201\",\n            \"name\": \"import-export\"\n          }\n        ],\n        \"type\": \"import-export\",\n        \"id\": \"fc302725919645199373077fa299fc6e\",\n        \"name\": \"import-export\"\n      }\n    ],\n    \"extras\": {},\n    \"user\": {\n      \"domain\": {\n        \"id\": \"2347b158dcaf488496b44cc4edfd2bd8\",\n        \"name\": \"0kjFQF29\"\n      },\n      \"id\": \"f1f24aea666542eeb58dc129c29734f0\",\n      \"name\": \"cloudsoft\"\n    },\n    \"audit_ids\": [\n      \"kr9Qqe-1QFOOlrt2XP6AqA\"\n    ],\n    \"issued_at\": \"2017-12-10T08:48:46.546877Z\"\n  }\n}"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/v3/user.json",
    "content": "{\n  \"user\": {\n    \"password_expires_at\": null,\n    \"links\": {\n      \"self\": \"http://localhost/identity/v3/users/0bedc61110fd4e94a251260a47f18f29\"\n    },\n    \"enabled\": true,\n    \"id\": \"0bedc61110fd4e94a251260a47f18f29\",\n    \"options\": {},\n    \"domain_id\": \"default\",\n    \"name\": \"User\"\n  }\n}\n"
  },
  {
    "path": "apis/openstack-keystone/src/test/resources/v3/users.json",
    "content": "{\n  \"users\": [\n    {\n      \"password_expires_at\": null,\n      \"name\": \"UserApiLiveTest\",\n      \"links\": {\n        \"self\": \"http://localhost/identity/v3/users/0bedc61110fd4e94a251260a47f18f29\"\n      },\n      \"domain_id\": \"default\",\n      \"enabled\": true,\n      \"id\": \"0bedc61110fd4e94a251260a47f18f29\",\n      \"options\": {}\n    },\n    {\n      \"password_expires_at\": null,\n      \"name\": \"glance-swift\",\n      \"links\": {\n        \"self\": \"http://localhost/identity/v3/users/1194933d3f1147a3b0824848bb7ec5e2\"\n      },\n      \"domain_id\": \"default\",\n      \"enabled\": true,\n      \"id\": \"1194933d3f1147a3b0824848bb7ec5e2\",\n      \"options\": {}\n    },\n    {\n      \"password_expires_at\": null,\n      \"name\": \"nova\",\n      \"links\": {\n        \"self\": \"http://localhost/identity/v3/users/290999fc41fb48e397feef465d014fb6\"\n      },\n      \"domain_id\": \"default\",\n      \"enabled\": true,\n      \"id\": \"290999fc41fb48e397feef465d014fb6\",\n      \"options\": {}\n    },\n    {\n      \"password_expires_at\": null,\n      \"name\": \"placement\",\n      \"links\": {\n        \"self\": \"http://localhost/identity/v3/users/34e6ac0dd9bb4601bac4971785abd7f5\"\n      },\n      \"domain_id\": \"default\",\n      \"enabled\": true,\n      \"id\": \"34e6ac0dd9bb4601bac4971785abd7f5\",\n      \"options\": {}\n    },\n    {\n      \"name\": \"jclouds\",\n      \"links\": {\n        \"self\": \"http://localhost/identity/v3/users/6c3b325a28264f00865b38442429fd77\"\n      },\n      \"domain_id\": \"default\",\n      \"enabled\": true,\n      \"options\": {},\n      \"default_project_id\": \"43de288ea0ce4d2b8b811055b10f156b\",\n      \"id\": \"6c3b325a28264f00865b38442429fd77\",\n      \"password_expires_at\": null\n    },\n    {\n      \"password_expires_at\": null,\n      \"name\": \"cinder\",\n      \"links\": {\n        \"self\": \"http://localhost/identity/v3/users/6e705bff20794de5955acf0936f02b3f\"\n      },\n      \"domain_id\": \"default\",\n      \"enabled\": true,\n      \"id\": \"6e705bff20794de5955acf0936f02b3f\",\n      \"options\": {}\n    },\n    {\n      \"name\": \"demo\",\n      \"links\": {\n        \"self\": \"http://localhost/identity/v3/users/84910c7070144530a6b9627fe0e1743f\"\n      },\n      \"domain_id\": \"default\",\n      \"enabled\": true,\n      \"options\": {},\n      \"id\": \"84910c7070144530a6b9627fe0e1743f\",\n      \"email\": \"demo@example.com\",\n      \"password_expires_at\": null\n    },\n    {\n      \"password_expires_at\": null,\n      \"name\": \"swift\",\n      \"links\": {\n        \"self\": \"http://localhost/identity/v3/users/87306cb2f0954ca8919f0fbaf29a780f\"\n      },\n      \"domain_id\": \"default\",\n      \"enabled\": true,\n      \"id\": \"87306cb2f0954ca8919f0fbaf29a780f\",\n      \"options\": {}\n    },\n    {\n      \"password_expires_at\": null,\n      \"name\": \"glance\",\n      \"links\": {\n        \"self\": \"http://localhost/identity/v3/users/94c9f0f5e056489ebfef25870e8944fe\"\n      },\n      \"domain_id\": \"default\",\n      \"enabled\": true,\n      \"id\": \"94c9f0f5e056489ebfef25870e8944fe\",\n      \"options\": {}\n    },\n    {\n      \"password_expires_at\": null,\n      \"name\": \"admin\",\n      \"links\": {\n        \"self\": \"http://localhost/identity/v3/users/ab7bd6c2dd394fce8318e7562115d3f8\"\n      },\n      \"domain_id\": \"default\",\n      \"enabled\": true,\n      \"id\": \"ab7bd6c2dd394fce8318e7562115d3f8\",\n      \"options\": {}\n    },\n    {\n      \"password_expires_at\": null,\n      \"name\": \"neutron\",\n      \"links\": {\n        \"self\": \"http://localhost/identity/v3/users/d3607e141e334823978eec2e1ccca8de\"\n      },\n      \"domain_id\": \"default\",\n      \"enabled\": true,\n      \"id\": \"d3607e141e334823978eec2e1ccca8de\",\n      \"options\": {}\n    }\n  ],\n  \"links\": {\n    \"self\": \"http://localhost/identity/v3/users\",\n    \"previous\": null,\n    \"next\": null\n  }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/README.md",
    "content": "OpenStack Neutron\n=================\n\nNeutron is a virtual network service for Openstack.\n\n"
  },
  {
    "path": "apis/openstack-neutron/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.openstack.neutron.v2.*;version=\"${project.version}\";-noimport:=true"
  },
  {
    "path": "apis/openstack-neutron/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.api</groupId>\n  <artifactId>openstack-neutron</artifactId>\n  <name>jclouds openstack-neutron api</name>\n  <description>jclouds components to access an implementation of OpenStack Neutron</description>\n\n  <properties>\n    <!-- keystone endpoint -->\n    <test.openstack-neutron.endpoint>http://localhost:5000/v2.0/</test.openstack-neutron.endpoint>\n    <!-- keystone version -->\n    <test.openstack-neutron.api-version>v2.0</test.openstack-neutron.api-version>\n    <test.openstack-neutron.build-version />\n    <test.openstack-neutron.identity>FIXME_IDENTITY</test.openstack-neutron.identity>\n    <test.openstack-neutron.credential>FIXME_CREDENTIALS</test.openstack-neutron.credential>\n    <test.jclouds.keystone.credential-type>passwordCredentials</test.jclouds.keystone.credential-type>\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-keystone</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-keystone</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-slf4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>ch.qos.logback</groupId>\n      <artifactId>logback-classic</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.squareup.okhttp3</groupId>\n      <artifactId>mockwebserver</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <scope>provided</scope>\n      <optional>true</optional>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.value</groupId>\n      <artifactId>auto-value</artifactId>\n      <scope>provided</scope>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.openstack-neutron.endpoint>${test.openstack-neutron.endpoint}</test.openstack-neutron.endpoint>\n                    <test.openstack-neutron.api-version>${test.openstack-neutron.api-version}</test.openstack-neutron.api-version>\n                    <test.openstack-neutron.build-version>${test.openstack-neutron.build-version}</test.openstack-neutron.build-version>\n                    <test.openstack-neutron.identity>${test.openstack-neutron.identity}</test.openstack-neutron.identity>\n                    <test.openstack-neutron.credential>${test.openstack-neutron.credential}</test.openstack-neutron.credential>\n                    <test.jclouds.keystone.credential-type>${test.jclouds.keystone.credential-type}</test.jclouds.keystone.credential-type>\n                  </systemPropertyVariables>\n                  <parallel>classes</parallel>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/NeutronApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2;\n\nimport java.io.Closeable;\nimport java.util.Set;\n\nimport jakarta.ws.rs.Path;\n\nimport org.jclouds.location.Region;\nimport org.jclouds.openstack.neutron.v2.features.FloatingIPApi;\nimport org.jclouds.openstack.neutron.v2.extensions.RouterApi;\nimport org.jclouds.openstack.neutron.v2.features.SecurityGroupApi;\nimport org.jclouds.openstack.neutron.v2.extensions.lbaas.v1.LBaaSApi;\nimport org.jclouds.openstack.neutron.v2.extensions.FWaaSApi;\nimport org.jclouds.openstack.neutron.v2.features.NetworkApi;\nimport org.jclouds.openstack.neutron.v2.features.PortApi;\nimport org.jclouds.openstack.neutron.v2.features.SubnetApi;\nimport org.jclouds.openstack.neutron.v2.functions.VersionAwareRegionToEndpoint;\nimport org.jclouds.openstack.v2_0.features.ExtensionApi;\nimport org.jclouds.rest.annotations.Delegate;\nimport org.jclouds.rest.annotations.EndpointParam;\n\nimport com.google.common.base.Optional;\nimport com.google.inject.Provides;\n\n/**\n * Provides access to the OpenStack Networking (Neutron) v2 API.\n *\n * The service-side API will always have a v2.0 in the path.\n * However, the endpoint will sometimes contain a v2.0 and sometimes it will not.\n * The @Path annotation here ensures the path is always added. The VersionAwareRegionToEndpoint ensures that the\n * endpoint will always look the same.\n *\n * Cannot leave labs until fixed:\n * TODO: https://issues.apache.org/jira/browse/JCLOUDS-773\n */\n@Path(\"v2.0\")\npublic interface NeutronApi extends Closeable {\n   /**\n    * @return the Region codes configured\n    */\n   @Provides\n   @Region\n   Set<String> getConfiguredRegions();\n\n   /**\n    * Provides access to Extension features.\n    */\n   @Delegate\n   ExtensionApi getExtensionApi(@EndpointParam(parser = VersionAwareRegionToEndpoint.class) String region);\n\n   /**\n    * Provides access to Network features.\n    */\n   @Delegate\n   NetworkApi getNetworkApi(@EndpointParam(parser = VersionAwareRegionToEndpoint.class) String region);\n\n   /**\n    * Provides access to Subnet features.\n    */\n   @Delegate\n   SubnetApi getSubnetApi(@EndpointParam(parser = VersionAwareRegionToEndpoint.class) String region);\n\n   /**\n    * Provides access to Port features.\n    */\n   @Delegate\n   PortApi getPortApi(@EndpointParam(parser = VersionAwareRegionToEndpoint.class) String region);\n\n   /**\n    * Provides access to SecurityGroup features.\n    */\n   @Delegate\n   SecurityGroupApi getSecurityGroupApi(@EndpointParam(parser = VersionAwareRegionToEndpoint.class) String region);\n\n   /**\n    * Provides access to Floating IP features.\n    */\n   @Delegate\n   FloatingIPApi getFloatingIPApi(@EndpointParam(parser = VersionAwareRegionToEndpoint.class) String region);\n\n   /**\n    * Provides access to Router features.\n    *\n    * <h3>NOTE</h3>\n    * This API is an extension that may or may not be present in your OpenStack cloud. Use the Optional return type\n    * to determine if it is present.\n    */\n   @Delegate\n   Optional<RouterApi> getRouterApi(@EndpointParam(parser = VersionAwareRegionToEndpoint.class) String region);\n\n   /**\n    * Provides access to LBaaS features.\n    *\n    * <h3>NOTE</h3>\n    * This API is an extension that may or may not be present in your OpenStack cloud. Use the Optional return type\n    * to determine if it is present.\n    */\n   @Delegate\n   Optional<LBaaSApi> getLBaaSApi(@EndpointParam(parser = VersionAwareRegionToEndpoint.class) String region);\n\n   /**\n    * Provides access to FWaaS features.\n    *\n    * <h3>NOTE</h3>\n    * This API is an extension that may or may not be present in your OpenStack cloud. Use the Optional return type\n    * to determine if it is present.\n    */\n   @Delegate\n   Optional<FWaaSApi> getFWaaSApi(@EndpointParam(parser = VersionAwareRegionToEndpoint.class) String region);\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/NeutronApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2;\n\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.CREDENTIAL_TYPE;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.KEYSTONE_VERSION;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.SERVICE_TYPE;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.openstack.keystone.auth.config.AuthenticationModule;\nimport org.jclouds.openstack.keystone.auth.config.CredentialTypes;\nimport org.jclouds.openstack.keystone.catalog.config.ServiceCatalogModule;\nimport org.jclouds.openstack.keystone.catalog.config.ServiceCatalogModule.RegionModule;\nimport org.jclouds.openstack.neutron.v2.config.NeutronHttpApiModule;\nimport org.jclouds.openstack.v2_0.ServiceType;\nimport org.jclouds.rest.internal.BaseHttpApiMetadata;\n\nimport com.google.auto.service.AutoService;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n/**\n * Implementation of {@link org.jclouds.apis.ApiMetadata} for Neutron 2.0 API\n *\n */\n@AutoService(ApiMetadata.class)\npublic class NeutronApiMetadata extends BaseHttpApiMetadata<NeutronApi> {\n\n   @Override\n   public Builder toBuilder() {\n      return new Builder().fromApiMetadata(this);\n   }\n\n   public NeutronApiMetadata() {\n      this(new Builder());\n   }\n\n   protected NeutronApiMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = BaseHttpApiMetadata.defaultProperties();\n      properties.setProperty(SERVICE_TYPE, ServiceType.NETWORK);\n      properties.setProperty(CREDENTIAL_TYPE, CredentialTypes.PASSWORD_CREDENTIALS);\n      properties.setProperty(KEYSTONE_VERSION, \"2\");\n      return properties;\n   }\n\n   public static class Builder extends BaseHttpApiMetadata.Builder<NeutronApi, Builder> {\n\n      protected Builder() {\n         super(NeutronApi.class);\n         id(\"openstack-neutron\")\n            .name(\"OpenStack Neutron API\")\n            .identityName(\"${tenantName}:${userName} or ${userName}, if your keystone supports a default tenant\")\n            .credentialName(\"${password}\")\n            .endpointName(\"Neutron base url ending in /v2.0/\")\n            .documentation(URI.create(\"http://docs.openstack.org/api/openstack-network/2.0/content/\"))\n            .version(\"v2.0\")\n            .defaultEndpoint(\"http://localhost:5000/v2.0/\")\n            .defaultProperties(NeutronApiMetadata.defaultProperties())\n            .defaultModules(ImmutableSet.<Class<? extends Module>>builder()\n               .add(AuthenticationModule.class)\n               .add(ServiceCatalogModule.class)\n               .add(RegionModule.class)\n               .add(NeutronHttpApiModule.class).build());\n      }\n\n      @Override\n      public NeutronApiMetadata build() {\n         return new NeutronApiMetadata(this);\n      }\n\n      @Override\n      public Builder fromApiMetadata(ApiMetadata in) {\n         super.fromApiMetadata(in);\n         return this;\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/config/NeutronHttpApiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.config;\n\nimport static org.jclouds.openstack.keystone.v2_0.config.KeystoneHttpApiModule.namespaceAliasBinder;\n\nimport java.net.URI;\nimport java.util.Set;\nimport java.util.concurrent.TimeUnit;\n\nimport jakarta.inject.Provider;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.annotation.ClientError;\nimport org.jclouds.http.annotation.Redirection;\nimport org.jclouds.http.annotation.ServerError;\nimport org.jclouds.json.config.GsonModule.DateAdapter;\nimport org.jclouds.json.config.GsonModule.Iso8601DateAdapter;\nimport org.jclouds.openstack.neutron.v2.NeutronApi;\nimport org.jclouds.openstack.neutron.v2.extensions.ExtensionNamespaces;\nimport org.jclouds.openstack.neutron.v2.handlers.NeutronErrorHandler;\nimport org.jclouds.openstack.v2_0.domain.Extension;\nimport org.jclouds.openstack.v2_0.functions.PresentWhenExtensionAnnotationMatchesExtensionSet;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.config.HttpApiModule;\nimport org.jclouds.rest.functions.ImplicitOptionalConverter;\n\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.inject.Provides;\nimport com.google.inject.multibindings.MapBinder;\n\n/**\n * Configures the Neutron connection.\n *\n */\n@ConfiguresHttpApi\npublic class NeutronHttpApiModule extends HttpApiModule<NeutronApi> {\n\n   @Override\n   protected void configure() {\n      bind(DateAdapter.class).to(Iso8601DateAdapter.class);\n      bind(ImplicitOptionalConverter.class).to(PresentWhenExtensionAnnotationMatchesExtensionSet.class);\n      super.configure();\n      bindAliases();\n   }\n\n   private void bindAliases() {\n      MapBinder<URI, URI> namespaceAliases = namespaceAliasBinder(binder());\n      namespaceAliases.addBinding(URI.create(ExtensionNamespaces.L3_ROUTER)).toInstance(\n            URI.create(\"http://docs.openstack.org/ext/neutron/router/api/v1.0\"));\n      namespaceAliases.addBinding(URI.create(ExtensionNamespaces.SECURITY_GROUPS)).toInstance(\n            URI.create(\"http://docs.openstack.org/ext/securitygroups/api/v2.0\"));\n      namespaceAliases.addBinding(URI.create(ExtensionNamespaces.LBAAS)).toInstance(\n            URI.create(\"http://docs.openstack.org/networking/ext/lbaas/api/v1.0\"));\n   }\n\n   @Provides\n   @Singleton\n   public LoadingCache<String, Set<? extends Extension>> provideExtensionsByRegion(final Provider<NeutronApi> neutronApi) {\n      return CacheBuilder.newBuilder().expireAfterWrite(23, TimeUnit.HOURS)\n            .build(new CacheLoader<String, Set<? extends Extension>>() {\n               @Override\n               public Set<? extends Extension> load(String key) throws Exception {\n                  return neutronApi.get().getExtensionApi(key).list();\n               }\n            });\n   }\n\n   @Override\n   protected void bindErrorHandlers() {\n      bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(NeutronErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(NeutronErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(NeutronErrorHandler.class);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/AddressPair.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\n/**\n * Contains a mapping between a MAC address and an IP address.\n */\npublic class AddressPair  {\n\n   @Named(\"mac_address\")\n   private String macAddress;\n   @Named(\"ip_address\")\n   private String ipAddress;\n\n   @ConstructorProperties({\"mac_address\", \"ip_address\"})\n   protected AddressPair(String macAddress, String ipAddress) {\n      checkNotNull(macAddress, \"mac address should not be null\");\n      checkNotNull(ipAddress, \"ip should not be null\");\n      this.macAddress = macAddress;\n      this.ipAddress = ipAddress;\n   }\n\n   /**\n    * Copy constructor\n    * @param addressPair\n    */\n   private AddressPair(AddressPair addressPair) {\n      this(addressPair.getMacAddress(), addressPair.getIpAddress());\n   }\n\n   /**\n    * Default constructor\n    */\n   private AddressPair() {}\n\n   /**\n    * @return the macAddress of the AddressPair\n    */\n   @Nullable\n   public String getMacAddress() {\n      return macAddress;\n   }\n\n   /**\n    * @return the ipAddress of the AddressPair\n    */\n   @Nullable\n   public String getIpAddress() {\n      return ipAddress;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(macAddress, ipAddress);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      AddressPair that = AddressPair.class.cast(obj);\n      return Objects.equal(this.macAddress, that.macAddress) && Objects.equal(this.ipAddress, that.ipAddress);\n   }\n\n   protected MoreObjects.ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).add(\"macAddress\", macAddress).add(\"ipAddress\", ipAddress);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   /**\n    * Returns a builder, but requires the user to specify any parameters required when creating a resource.\n    * In this case, both parameters are required.\n    * @return the Builder for AddressPair\n    */\n   public static Builder builder(String macAddress, String ipAddress) {\n      return new Builder(macAddress, ipAddress);\n   }\n\n   /**\n    * Gets a Builder configured as this object.\n    */\n   public Builder toBuilder() {\n      return new Builder().fromAddressPair(this);\n   }\n\n   public static class Builder {\n      // Keep track of the builder's state.\n      private AddressPair addressPair;\n\n      /**\n       * No-parameters constructor used when updating.\n       * */\n      private Builder() {\n         addressPair = new AddressPair();\n      }\n\n      /**\n       * Required parameters constructor used when creating.\n       * @param macAddress\n       * @param ipAddress\n       */\n      private Builder(String macAddress, String ipAddress) {\n         addressPair = new AddressPair();\n         addressPair.macAddress = macAddress;\n         addressPair.ipAddress = ipAddress;\n      }\n\n      /**\n       * Provide the macAddress to the AddressPair's Builder.\n       *\n       * @return the Builder.\n       * @see AddressPair#getMacAddress()\n       */\n      public Builder macAddress(String macAddress) {\n         addressPair.macAddress = macAddress;\n         return this;\n      }\n\n      /**\n       * Provide the ipAddress to the AddressPair's Builder.\n       *\n       * @return the Builder.\n       * @see AddressPair#getIpAddress()\n       */\n      public Builder ipAddress(String ipAddress) {\n         addressPair.ipAddress = ipAddress;\n         return this;\n      }\n\n      /**\n       * @return a AddressPair constructed with this Builder.\n       */\n      public AddressPair build() {\n         // Use the copy constructor to copy the builder's state (config) object and pass back to the user.\n         // Immutability is preserved, and fields are defined only once.\n         return new AddressPair(addressPair);\n      }\n\n      /**\n       * @return a Builder from another AddressPair.\n       */\n      public Builder fromAddressPair(AddressPair in) {\n         return this.macAddress(in.getMacAddress()).ipAddress(in.getIpAddress());\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/AllocationPool.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\n/**\n * A Neutron Subnet Allocation Pool\n * Contains a start and an end IP address describing the pool.\n *\n * @see <a\n *      href=\"http://docs.openstack.org/api/openstack-network/2.0/content/Subnets.html\">api\n *      doc</a>\n */\npublic class AllocationPool {\n\n   protected final String start;\n   protected final String end;\n\n   @ConstructorProperties({\"start\", \"end\"})\n   protected AllocationPool(String start, String end) {\n      this.start = start;\n      this.end = end;\n   }\n\n   /**\n    * @return the start of the AllocationPool\n    */\n   @Nullable\n   public String getStart() {\n      return start;\n   }\n\n   /**\n    * @return the end of the AllocationPool\n    */\n   @Nullable\n   public String getEnd() {\n      return end;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(start, end);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      AllocationPool that = AllocationPool.class.cast(obj);\n      return Objects.equal(this.start, that.start) && Objects.equal(this.end, that.end);\n   }\n\n   protected MoreObjects.ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).add(\"start\", start).add(\"end\", end);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   /**\n    * @return the Builder for AllocationPool\n    */\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   /**\n    * Gets a Builder configured as this object.\n    */\n   public Builder toBuilder() {\n      return new Builder().fromAllocationPool(this);\n   }\n\n   public static class Builder {\n      protected String start;\n      protected String end;\n\n      /**\n       * Provide the start to the AllocationPool's Builder.\n       *\n       * @return the Builder.\n       * @see AllocationPool#getStart()\n       */\n      public Builder start(String start) {\n         this.start = start;\n         return this;\n      }\n\n      /**\n       * Provide the end to the AllocationPool's Builder.\n       *\n       * @return the Builder.\n       * @see AllocationPool#getEnd()\n       */\n      public Builder end(String end) {\n         this.end = end;\n         return this;\n      }\n\n      /**\n       * @return a AllocationPool constructed with this Builder.\n       */\n      public AllocationPool build() {\n         return new AllocationPool(start, end);\n      }\n\n      /**\n       * @return a Builder from another AllocationPool.\n       */\n      public Builder fromAllocationPool(AllocationPool in) {\n         return this.start(in.getStart()).end(in.getEnd());\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/CreateFirewall.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n/**\n * Representation of creation options for an OpenStack Neutron Firewall.\n *\n * @see <a\n *      href=\"http://docs.openstack.org/admin-guide-cloud/content/fwaas_api_abstractions.html\">api\n *      doc</a>\n */\n@AutoValue\npublic abstract class CreateFirewall {\n\n   /**\n    * @see Builder#tenantId(String)\n    */\n   @Nullable public abstract String getTenantId();\n\n   /**\n    * @see Builder#name(String)\n    */\n   @Nullable public abstract String getName();\n\n   /**\n    * @see Builder#description(String)\n    */\n   @Nullable public abstract String getDescription();\n\n   /**\n    * @see Builder#adminStateUp(Boolean)\n    */\n   @Nullable public abstract Boolean getAdminStateUp();\n\n   /**\n    * @see Builder#firewallPolicyId(String)\n    */\n   @Nullable public abstract String getFirewallPolicyId();\n\n   @SerializedNames({ \"tenant_id\", \"name\", \"description\", \"admin_state_up\", \"firewall_policy_id\"})\n   public static CreateFirewall create(String tenantId, String name, String description, Boolean adminStateUp, String firewallPolicyId) {\n      return builder().tenantId(tenantId).name(name).description(description).adminStateUp(adminStateUp)\n              .firewallPolicyId(firewallPolicyId).build();\n   }\n\n   public static Builder builder() {\n      return new AutoValue_CreateFirewall.Builder();\n   }\n\n   public abstract Builder toBuilder();\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n\n      /**\n       *\n       * @param tenantId Owner of the firewall. Only admin users can specify a tenant_id other than its own.\n       * @return The CreateFirewall builder.\n       */\n      public abstract Builder tenantId(String tenantId);\n\n      /**\n       *\n       * @param name Human readable name for the firewall (255 characters limit).\n       * @return The CreateFirewall builder.\n       */\n      public abstract Builder name(String name);\n\n      /**\n       *\n       * @param description Human readable description for the firewall (1024 characters limit).\n       * @return The CreateFirewall builder.\n       */\n      public abstract Builder description(String description);\n\n      /**\n       *\n       * @param adminStateUp The administrative state of the firewall. If False (down), the firewall does not forward any packets.\n       * @return The CreateFirewall builder.\n       */\n      public abstract Builder adminStateUp(Boolean adminStateUp);\n\n      /**\n       *\n       * @param firewallPolicyId The firewall policy uuid that this firewall is associated with. This firewall implements the rules contained in the\n       *                         firewall policy represented by this uuid.\n       *\n       * @return The CreateFirewall builder.\n       */\n      public abstract Builder firewallPolicyId(String firewallPolicyId);\n\n      @Nullable public abstract String getTenantId();\n      @Nullable public abstract String getName();\n      @Nullable public abstract String getDescription();\n      @Nullable public abstract Boolean getAdminStateUp();\n      @Nullable public abstract String getFirewallPolicyId();\n\n      public abstract CreateFirewall build();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/CreateFirewallPolicy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain;\n\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Representation of creation options for an OpenStack Neutron Firewall Policy.\n *\n * @see <a\n *      href=\"http://docs.openstack.org/admin-guide-cloud/content/fwaas_api_abstractions.html\">api\n *      doc</a>\n */\n@AutoValue\npublic abstract class CreateFirewallPolicy {\n\n   /**\n    * @see Builder#tenantId(String)\n    */\n   @Nullable public abstract String getTenantId();\n\n   /**\n    * @see Builder#name(String)\n    */\n   @Nullable public abstract String getName();\n\n   /**\n    * @see Builder#description(String)\n    */\n   @Nullable public abstract String getDescription();\n\n   /**\n    * @see Builder#shared(Boolean)\n    */\n   @Nullable public abstract Boolean getShared();\n\n   /**\n    * @see Builder#firewallRules(java.util.List)\n    */\n   @Nullable public abstract List<String> getFirewallRules();\n\n   /**\n    * @see Builder#audited(Boolean)\n    */\n   @Nullable public abstract Boolean getAudited();\n\n   @SerializedNames({\"tenant_id\", \"name\", \"description\", \"shared\", \"firewall_rules\", \"audited\"})\n   private static CreateFirewallPolicy create(String tenantId, String name, String description, Boolean shared, List<String> firewallRules, Boolean audited) {\n      return builder().tenantId(tenantId).name(name).description(description).shared(shared).firewallRules(firewallRules).audited(audited).build();\n   }\n\n   public static Builder builder() {\n      return new AutoValue_CreateFirewallPolicy.Builder().shared(false).audited(false);\n   }\n\n   public abstract Builder toBuilder();\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n\n      /**\n       *\n       * @param tenantId Owner of the firewall. Only admin users can specify a tenant_id other than its own.\n       * @return The CreateFirewallPolicy builder.\n       */\n      public abstract Builder tenantId(String tenantId);\n\n      /**\n       *\n       * @param name Human readable name for the firewall (255 characters limit).\n       * @return The CreateFirewallPolicy builder.\n       */\n      public abstract Builder name(String name);\n\n      /**\n       *\n       * @param description Human readable description for the firewall (1024 characters limit).\n       * @return The CreateFirewallPolicy builder.\n       */\n      public abstract Builder description(String description);\n\n      /**\n       *\n       * @param shared When set to True makes this firewall policy visible to tenants other than its owner and\n       *               can be used to associate with firewalls not owned by its tenant.\n       * @return The CreateFirewallPolicy builder.\n       */\n      public abstract Builder shared(Boolean shared);\n\n      /**\n       *\n       * @param firewallRules This is an ordered list of firewall rule uuids.\n       *                      The firewall applies the rules in the order in which they appear in this list.\n       * @return The CreateFirewallPolicy builder.\n       */\n      public abstract Builder firewallRules(List<String> firewallRules);\n\n      /**\n       *\n       * @param audited When set to True by the policy owner indicates that the firewall policy has been audited. This attribute is meant to aid in the\n       *                firewall policy audit work flows. Each time the firewall policy or the associated firewall rules are changed, this attribute is set\n       *                to False and must be explicitly set to True through an update operation.\n       * @return The CreateFirewallPolicy builder.\n       */\n      public abstract Builder audited(Boolean audited);\n\n      @Nullable public abstract String getTenantId();\n      @Nullable public abstract String getName();\n      @Nullable public abstract String getDescription();\n      @Nullable public abstract Boolean getShared();\n      @Nullable public abstract List<String> getFirewallRules();\n      @Nullable public abstract Boolean getAudited();\n\n      abstract CreateFirewallPolicy autoBuild();\n\n      public CreateFirewallPolicy build() {\n         firewallRules(getFirewallRules() != null ? ImmutableList.copyOf(getFirewallRules()) : ImmutableList.<String>of());\n         return autoBuild();\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/CreateFirewallRule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n/**\n * Representation of creation options for an OpenStack Neutron Firewall Rule.\n *\n * @see <a\n *      href=\"http://docs.openstack.org/admin-guide-cloud/content/fwaas_api_abstractions.html\">api\n *      doc</a>\n */\n@AutoValue\npublic abstract class CreateFirewallRule {\n\n   /**\n    * @see Builder#tenantId(String)\n    */\n   @Nullable public abstract String getTenantId();\n   /**\n    * @see Builder#name(String)\n    */\n   @Nullable public abstract String getName();\n   /**\n    * @see Builder#description(String)\n    */\n   @Nullable public abstract String getDescription();\n   /**\n    * @see Builder#firewallPolicyId(String)\n    */\n   @Nullable public abstract String getFirewallPolicyId();\n   /**\n    * @see Builder#shared(Boolean)\n    */\n   @Nullable public abstract Boolean getShared();\n   /**\n    * @see Builder#protocol(String)\n    */\n   @Nullable public abstract String getProtocol();\n   /**\n    * @see Builder#ipVersion(IpVersion)\n    */\n   @Nullable public abstract IpVersion getIpVersion();\n   /**\n    * @see Builder#sourceIpAddress(String)\n    */\n   @Nullable public abstract String getSourceIpAddress();\n   /**\n    * @see Builder#destinationIpAddress(String)\n    */\n   @Nullable public abstract String getDestinationIpAddress();\n   /**\n    * @see Builder#sourcePort(String)\n    */\n   @Nullable public abstract String getSourcePort();\n   /**\n    * @see Builder#destinationPort(String)\n    */\n   @Nullable public abstract String getDestinationPort();\n   /**\n    * see Builder#position(Integer)\n    */\n   @Nullable public abstract Integer getPosition();\n   /**\n    * @see Builder#action(String)\n    */\n   @Nullable public abstract String getAction();\n   /**\n    * @see Builder#enabled(Boolean)\n    */\n   @Nullable public abstract Boolean getEnabled();\n\n   @SerializedNames({ \"tenant_id\", \"name\", \"description\", \"firewall_policy_id\", \"shared\", \"protocol\", \"ip_version\", \"source_ip_address\",\n           \"destination_ip_address\", \"source_port\", \"destination_port\", \"position\", \"action\", \"enabled\"})\n   public static CreateFirewallRule create(String tenantId, String name, String description, String firewallPolicyId, Boolean shared, String protocol,\n                                     IpVersion ipVersion, String sourceIpAddress, String destinationIpAddress, String sourcePort, String destinationPort, int position,\n                                     String action, Boolean enabled) {\n      return builder().tenantId(tenantId).name(name).description(description).firewallPolicyId(firewallPolicyId).shared(shared)\n              .protocol(protocol).ipVersion(ipVersion).sourceIpAddress(sourceIpAddress).destinationIpAddress(destinationIpAddress).sourcePort(sourcePort)\n              .destinationPort(destinationPort).position(position).action(action).enabled(enabled).build();\n   }\n\n   public static Builder builder() {\n      return new AutoValue_CreateFirewallRule.Builder();\n   }\n\n   public abstract Builder toBuilder();\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n\n      /**\n       *\n       * @param tenantId Owner of the firewall. Only admin users can specify a tenant_id other than its own.\n       * @return The CreateFirewallRule builder.\n       */\n      public abstract Builder tenantId(String tenantId);\n\n      /**\n       *\n       * @param name Human readable name for the firewall (255 characters limit).\n       * @return The CreateFirewallRule builder.\n       */\n      public abstract Builder name(String name);\n\n      /**\n       *\n       * @param description Human readable description for the firewall (1024 characters limit).\n       * @return The CreateFirewallRule builder.\n       */\n      public abstract Builder description(String description);\n\n      /**\n       *\n       * @param shared When set to True makes this firewall policy visible to tenants other than its owner and\n       *               can be used to associate with firewalls not owned by its tenant.\n       * @return The CreateFirewallRule builder.\n       */\n      public abstract Builder shared(Boolean shared);\n\n      /**\n       *\n       * @param firewallPolicyId This is a read-only attribute that gets populated with the uuid of the firewall policy when this firewall rule is associated\n       *                         with a firewall policy. A firewall rule can be associated with only one firewall policy at a time. However, the association\n       *                         can be changed to a different firewall policy.\n       * @return The CreateFirewallRule builder.\n       */\n      public abstract Builder firewallPolicyId(String firewallPolicyId);\n\n      /**\n       *\n       * @param protocol IP protocol (icmp, tcp, udp, None).\n       * @return The CreateFirewallRule builder.\n       */\n      public abstract Builder protocol(String protocol);\n\n      /**\n       *\n       * @param ipVersion IP version (4, 6).\n       * @return The CreateFirewallRule builder.\n       */\n      public abstract Builder ipVersion(IpVersion ipVersion);\n\n      /**\n       *\n       * @param sourceIpAddress Source IP address or CIDR.\n       * @return The CreateFirewallRule builder.\n       */\n      public abstract Builder sourceIpAddress(String sourceIpAddress);\n\n      /**\n       *\n       * @param destinationIpAddress Destination IP address or CIDR.\n       * @return The CreateFirewallRule builder.\n       */\n      public abstract Builder destinationIpAddress(String destinationIpAddress);\n\n      /**\n       *\n       * @param sourcePort Source port number or a range.\n       * @return The CreateFirewallRule builder.\n       */\n      public abstract Builder sourcePort(String sourcePort);\n\n      /**\n       *\n       * @param destinationPort Destination port number or a range.\n       * @return The CreateFirewallRule builder.\n       */\n      public abstract Builder destinationPort(String destinationPort);\n\n      /**\n       *\n       * @param position This is a read-only attribute that gets assigned to this rule when the rule is associated with a firewall policy. It indicates the\n       *                 position of this rule in that firewall policy.\n       * @return The CreateFirewallRule builder.\n       */\n      public abstract Builder position(Integer position);\n\n      /**\n       *\n       * @param action Action to be performed on the traffic matching the rule (allow, deny).\n       * @return The CreateFirewallRule builder.\n       */\n      public abstract Builder action(String action);\n\n      /**\n       *\n       * @param enabled When set to False, disables this rule in the firewall policy. Facilitates selectively turning off rules without having to\n       *                disassociate the rule from the firewall policy.\n       * @return The CreateFirewallRule builder.\n       */\n      public abstract Builder enabled(Boolean enabled);\n\n      @Nullable public abstract String getTenantId();\n      @Nullable public abstract String getName();\n      @Nullable public abstract String getDescription();\n      @Nullable public abstract Boolean getShared();\n      @Nullable public abstract String getFirewallPolicyId();\n      @Nullable public abstract String getProtocol();\n      @Nullable public abstract IpVersion getIpVersion();\n      @Nullable public abstract String getSourceIpAddress();\n      @Nullable public abstract String getDestinationIpAddress();\n      @Nullable public abstract String getSourcePort();\n      @Nullable public abstract String getDestinationPort();\n      @Nullable public abstract Integer getPosition();\n      @Nullable public abstract String getAction();\n      @Nullable public abstract Boolean getEnabled();\n\n      public abstract CreateFirewallRule build();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/ExternalGatewayInfo.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\n/**\n * Information on the external gateway for the router\n */\npublic class ExternalGatewayInfo {\n\n   @Named(\"network_id\")\n   protected final String networkId;\n   @Named(\"enable_snat\")\n   protected final Boolean enableSnat;\n\n   @ConstructorProperties({\"network_id\", \"enable_snat\"})\n   protected ExternalGatewayInfo(String networkId, Boolean enableSnat) {\n      this.networkId = networkId;\n      this.enableSnat = enableSnat;\n   }\n\n   /**\n    * @return the networkId of the ExternalGatewayInfo\n    */\n   @Nullable\n   public String getNetworkId() {\n      return networkId;\n   }\n\n   /**\n    * @return the enableSnat status of the ExternalGatewayInfo\n    */\n   @Nullable\n   public Boolean getEnableSnat() {\n      return enableSnat;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(networkId, enableSnat);\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o)\n         return true;\n      if (o == null || getClass() != o.getClass())\n         return false;\n\n      ExternalGatewayInfo that = (ExternalGatewayInfo) o;\n\n      return Objects.equal(this.networkId, that.networkId) &&\n            Objects.equal(this.enableSnat, that.enableSnat);\n   }\n\n   /**\n    * @return the Builder for ExternalGatewayInfo\n    */\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   /**\n    * Gets a Builder configured as this object.\n    */\n   public Builder toBuilder() {\n      return new Builder().fromExternalGatewayInfo(this);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"networkId\", networkId)\n            .add(\"enableSnat\", enableSnat)\n            .toString();\n   }\n\n   public static class Builder {\n      protected String networkId;\n      protected Boolean enableSnat;\n\n      /**\n       * Provide the networkId to the ExternalGatewayInfo's Builder.\n       *\n       * @return the Builder.\n       * @see ExternalGatewayInfo#getNetworkId()\n       */\n      public Builder networkId(String networkId) {\n         this.networkId = networkId;\n         return this;\n      }\n\n      /**\n       * Provide the enableSnat status to the ExternalGatewayInfo's Builder.\n       *\n       * @return the Builder.\n       * @see ExternalGatewayInfo#getEnableSnat()\n       */\n      public Builder enableSnat(Boolean enableSnat) {\n         this.enableSnat = enableSnat;\n         return this;\n      }\n\n      /**\n       * @return a ExternalGatewayInfo constructed with this Builder.\n       */\n      public ExternalGatewayInfo build() {\n         return new ExternalGatewayInfo(networkId, enableSnat);\n      }\n\n      /**\n       * @return a Builder from another ExternalGatewayInfo.\n       */\n      public Builder fromExternalGatewayInfo(ExternalGatewayInfo in) {\n         return this.networkId(in.getNetworkId()).enableSnat(in.getEnableSnat());\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/ExtraDhcpOption.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\n/**\n * This is used to provide additional DHCP-related options to Subnet. This is\n * based on a neutron extension.\n * For example PXE boot options to DHCP clients can be specified (e.g. tftp-server,\n * server-ip-address, bootfile-name)\n *\n * @see <a\n *      href=\"http://docs.openstack.org/api/openstack-network/2.0/content/Subnets.html\">api\n *      doc</a>\n */\npublic class ExtraDhcpOption {\n\n   protected final String id;\n   @Named(\"opt_name\")\n   protected final String optionName;\n   @Named(\"opt_value\")\n   protected final String optionValue;\n\n   @ConstructorProperties({\"id\", \"opt_name\", \"opt_value\"})\n   protected ExtraDhcpOption(String id, String optionName, String optionValue) {\n      this.id = id;\n      this.optionName = optionName;\n      this.optionValue = optionValue;\n   }\n\n   /**\n    * @return the id of the ExtraDhcpOption\n    */\n   @Nullable\n   public String getId() {\n      return id;\n   }\n\n   /**\n    * @return the optionName of the ExtraDhcpOption\n    */\n   @Nullable\n   public String getOptionName() {\n      return optionName;\n   }\n\n   /**\n    * @return the optionValue of the ExtraDhcpOption\n    */\n   @Nullable\n   public String getOptionValue() {\n      return optionValue;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, optionName, optionValue);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      ExtraDhcpOption that = ExtraDhcpOption.class.cast(obj);\n      return Objects.equal(this.id, that.id) && Objects.equal(this.optionName, that.optionName)\n            && Objects.equal(this.optionValue, that.optionValue);\n   }\n\n   protected MoreObjects.ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).add(\"id\", id).add(\"optionName\", optionName).add(\"optionValue\", optionValue);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   /**\n    * @return the Builder for ExtraDhcpOption\n    */\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   /**\n    * Gets a Builder configured as this object.\n    */\n   public Builder toBuilder() {\n      return new Builder().fromExtraDhcpOption(this);\n   }\n\n   public static class Builder {\n      protected String id;\n      protected String optionName;\n      protected String optionValue;\n\n      /**\n       * Provide the id to the ExtraDhcpOption's Builder.\n       *\n       * @return the Builder.\n       * @see ExtraDhcpOption#getId()\n       */\n      public Builder id(String id) {\n         this.id = id;\n         return this;\n      }\n\n      /**\n       * Provide the optionName to the ExtraDhcpOption's Builder.\n       *\n       * @return the Builder.\n       * @see ExtraDhcpOption#getOptionName()\n       */\n      public Builder optionName(String optionName) {\n         this.optionName = optionName;\n         return this;\n      }\n\n      /**\n       * Provide the optionValue to the ExtraDhcpOption's Builder.\n       *\n       * @return the Builder.\n       * @see ExtraDhcpOption#getOptionValue()\n       */\n      public Builder optionValue(String optionValue) {\n         this.optionValue = optionValue;\n         return this;\n      }\n\n      /**\n       * @return a ExtraDhcpOption constructed with this Builder.\n       */\n      public ExtraDhcpOption build() {\n         return new ExtraDhcpOption(id, optionName, optionValue);\n      }\n\n      /**\n       * @return a Builder from another ExtraDhcpOption.\n       */\n      public Builder fromExtraDhcpOption(ExtraDhcpOption in) {\n         return this.id(in.getId()).optionName(in.getOptionName()).optionValue(in.getOptionValue());\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/Firewall.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n/**\n * A Firewall\n *\n * @see <a\n *      href=\"http://docs.openstack.org/admin-guide-cloud/content/fwaas_api_abstractions.html\">api\n *      doc</a>\n */\n@AutoValue\npublic abstract class Firewall {\n\n   public abstract String getId();\n   public abstract String getTenantId();\n   @Nullable public abstract String getName();\n   @Nullable public abstract String getDescription();\n   @Nullable public abstract Boolean isAdminStateUp();\n   public abstract String getStatus();\n   @Nullable public abstract String getFirewallPolicyId();\n\n   @SerializedNames({\"id\", \"tenant_id\", \"name\", \"description\", \"admin_state_up\", \"status\", \"firewall_policy_id\"})\n   public static Firewall create(String id, String tenantId, String name, String description, Boolean adminStateUp, String status, String firewallPolicyId) {\n      return new AutoValue_Firewall(id, tenantId, name, description, adminStateUp, status, firewallPolicyId);\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/FirewallPolicies.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.PaginatedCollection;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * A collection of FirewallPolicies\n */\npublic class FirewallPolicies extends PaginatedCollection<FirewallPolicy> {\n   public static final FirewallPolicies EMPTY = new FirewallPolicies(ImmutableSet.<FirewallPolicy> of(), ImmutableSet.<Link> of());\n\n   @ConstructorProperties({\"firewall_policies\", \"firewall_policies_links\"})\n   protected FirewallPolicies(Iterable<FirewallPolicy> firewallPolicies, Iterable<Link> firewallPoliciesLinks) {\n      super(firewallPolicies, firewallPoliciesLinks);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/FirewallPolicy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain;\n\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n/**\n * A firewall policy\n *\n * @see <a\n *      href=\"http://docs.openstack.org/admin-guide-cloud/content/fwaas_api_abstractions.html\">api doc</a>\n */\n@AutoValue\npublic abstract class FirewallPolicy {\n\n   public abstract String getId();\n   public abstract String getTenantId();\n   public abstract String getName();\n   @Nullable public abstract String getDescription();\n   public abstract boolean isShared();\n   @Nullable public abstract List<String> getFirewallRules();\n   public abstract boolean isAudited();\n\n   @SerializedNames({\"id\", \"tenant_id\", \"name\", \"description\", \"shared\", \"firewall_rules\", \"audited\"})\n   private static FirewallPolicy create(String id, String tenantId, String name, String description, boolean shared, List<String> firewallRules, boolean audited) {\n      return new AutoValue_FirewallPolicy(id, tenantId, name, description, shared, firewallRules, audited);\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/FirewallRule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class FirewallRule {\n\n   public abstract String getId();\n   public abstract String getTenantId();\n   public abstract String getName();\n   @Nullable public abstract String getDescription();\n   @Nullable public abstract String getFirewallPolicyId();\n   public abstract boolean isShared();\n   @Nullable public abstract String getProtocol();\n   @Nullable public abstract IpVersion getIpVersion();\n   @Nullable public abstract String getSourceIpAddress();\n   @Nullable public abstract String getDestinationIpAddress();\n   @Nullable public abstract String getSourcePort();\n   @Nullable public abstract String getDestinationPort();\n   @Nullable public abstract Integer getPosition(); // for AutoValue.builder\n   @Nullable public abstract String getAction();\n   public abstract boolean isEnabled();\n\n   @SerializedNames({\"id\", \"tenant_id\", \"name\", \"description\", \"firewall_policy_id\", \"shared\", \"protocol\", \"ip_version\", \"source_ip_address\",\n           \"destination_ip_address\", \"source_port\", \"destination_port\", \"position\", \"action\", \"enabled\"})\n   public static FirewallRule create(String id, String tenantId, String name, String description, String firewallPolicyId, boolean shared, String protocol,\n                          IpVersion ipVersion, String sourceIpAddress, String destinationIpAddress, String sourcePort, String destinationPort, int position,\n                          String action, boolean enabled) {\n      return new AutoValue_FirewallRule(id, tenantId, name, description, firewallPolicyId, shared, protocol, ipVersion, sourceIpAddress,\n              destinationIpAddress, sourcePort, destinationPort, position, action, enabled);\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/FirewallRules.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.PaginatedCollection;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * A collection of FirewallRules\n */\npublic class FirewallRules extends PaginatedCollection<FirewallRule> {\n   public static final FirewallRules EMPTY = new FirewallRules(ImmutableSet.<FirewallRule> of(), ImmutableSet.<Link> of());\n\n   @ConstructorProperties({\"firewall_rules\", \"firewall_rules_links\"})\n   protected FirewallRules(Iterable<FirewallRule> firewallRules, Iterable<Link> firewallRulesLinks) {\n      super(firewallRules, firewallRulesLinks);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/Firewalls.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.PaginatedCollection;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * A collection of Firewalls\n */\npublic class Firewalls extends PaginatedCollection<Firewall> {\n   public static final Firewalls EMPTY = new Firewalls(ImmutableSet.<Firewall> of(), ImmutableSet.<Link> of());\n\n   @ConstructorProperties({\"firewalls\", \"firewalls_links\"})\n   protected Firewalls(Iterable<Firewall> firewalls, Iterable<Link> firewallsLinks) {\n      super(firewalls, firewallsLinks);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/FloatingIP.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\n/**\n * A Neutron Floating IP\n *\n */\npublic class FloatingIP {\n\n   private String id;\n   @Named(\"router_id\")\n   private String routerId;\n   @Named(\"project_id\")\n   private String projectId;\n   @Named(\"tenant_id\")\n   private String tenantId;\n   // Only mandatory attribute when creating\n   @Named(\"floating_network_id\")\n   private String floatingNetworkId;\n   @Named(\"fixed_ip_address\")\n   private String fixedIpAddress;\n   @Named(\"floating_ip_address\")\n   private String floatingIpAddress;\n   @Named(\"port_id\")\n   private String portId;\n   @Named(\"availability_zone\")\n   private String availabilityZone;\n\n   /**\n    * Deserialization constructor\n    */\n   @ConstructorProperties({\"id\", \"router_id\", \"project_id\", \"tenant_id\", \"floating_network_id\", \"fixed_ip_address\",\n         \"floating_ip_address\", \"port_id\", \"availability_zone\"})\n   private FloatingIP(String id, String routerId, String projectId, String tenantId, String floatingNetworkId, String fixedIpAddress,\n         String floatingIpAddress, String portId, String availabilityZone) {\n      this.id = id;\n      this.routerId = routerId;\n      this.projectId = projectId;\n      this.tenantId = tenantId;\n      this.floatingNetworkId = floatingNetworkId;\n      this.fixedIpAddress = fixedIpAddress;\n      this.floatingIpAddress = floatingIpAddress;\n      this.portId = portId;\n      this.availabilityZone = availabilityZone;\n   }\n\n   private FloatingIP() {}\n\n   /**\n    * @param floatingIP The floating IP to copy from\n    */\n   private FloatingIP(FloatingIP floatingIP) {\n      this(floatingIP.id, floatingIP.routerId, floatingIP.projectId, floatingIP.tenantId, floatingIP.floatingNetworkId,\n            floatingIP.fixedIpAddress, floatingIP.floatingIpAddress, floatingIP.portId, floatingIP.availabilityZone);\n   }\n\n   /**\n    * @return the id of the floating IP\n    */\n   @Nullable\n   public String getId() {\n      return id;\n   }\n\n   /**\n    * @return the router id of this floating IP\n    */\n   @Nullable\n   public String getRouterId() {\n      return routerId;\n   }\n\n   /**\n    * @return the project id of the Floating IP\n    */\n   @Nullable\n   public String getProjectId() {\n      return projectId;\n   }\n\n   /**\n    * @return the tenant id of the Floating IP\n    */\n   @Nullable\n   public String getTenantId() {\n      return tenantId;\n   }\n\n   /**\n    * @return the floating network id for this floating IP\n    */\n   @Nullable\n   public String getFloatingNetworkId() {\n      return floatingNetworkId;\n   }\n\n   /**\n    * @return the fixed IP address for this floating IP\n    */\n   @Nullable\n   public String getFixedIpAddress() {\n      return fixedIpAddress;\n   }\n\n   /**\n    * @return the floating IP address for this floating IP\n    */\n   @Nullable\n   public String getFloatingIpAddress() {\n      return floatingIpAddress;\n   }\n\n   /**\n    * @return the port id for this floating IP\n    */\n   @Nullable\n   public String getPortId() {\n      return portId;\n   }\n\n   /**\n    * @return the availability zone for this floating IP\n    */\n   @Nullable\n   public String getAvailabilityZone() {\n      return availabilityZone;\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o)\n         return true;\n      if (o == null || getClass() != o.getClass())\n         return false;\n\n      FloatingIP that = (FloatingIP) o;\n\n      return Objects.equal(this.id, that.id) &&\n            Objects.equal(this.routerId, that.routerId) &&\n            Objects.equal(this.projectId, that.projectId) &&\n            Objects.equal(this.tenantId, that.tenantId) &&\n            Objects.equal(this.floatingNetworkId, that.floatingNetworkId) &&\n            Objects.equal(this.fixedIpAddress, that.fixedIpAddress) &&\n            Objects.equal(this.floatingIpAddress, that.floatingIpAddress) &&\n            Objects.equal(this.portId, that.portId) &&\n            Objects.equal(this.availabilityZone, that.availabilityZone);\n\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, routerId, projectId, tenantId, floatingNetworkId, fixedIpAddress, floatingIpAddress,\n            portId, availabilityZone);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id)\n            .add(\"routerId\", routerId)\n            .add(\"projectId\", projectId)\n            .add(\"tenantId\", tenantId)\n            .add(\"floatingNetworkId\", floatingNetworkId)\n            .add(\"fixedIpAddress\", fixedIpAddress)\n            .add(\"floatingIpAddress\", floatingIpAddress)\n            .add(\"portId\", portId)\n            .add(\"availabilityZone\", availabilityZone)\n            .toString();\n   }\n\n   /**\n    * @return the Builder for creating a new floating IP\n    */\n   public static CreateBuilder createBuilder(String floatingNetworkId) {\n      return new CreateBuilder(floatingNetworkId);\n   }\n\n   /**\n    * @return the Builder for updating a floating IP\n    */\n   public static UpdateBuilder updateBuilder() {\n      return new UpdateBuilder();\n   }\n\n   private abstract static class Builder<ParameterizedBuilderType> {\n      protected FloatingIP floatingIP;\n\n      /**\n       * No-parameters constructor.\n       * */\n      private Builder() {\n         floatingIP = new FloatingIP();\n      }\n\n      protected abstract ParameterizedBuilderType self();\n\n      /**\n       * Provide the project ID for this Floating IP.\n       *\n       * @return the Builder.\n       * @see FloatingIP#getProjectId() ()\n       */\n      public ParameterizedBuilderType projectId(String projectId) {\n         floatingIP.projectId = projectId;\n         return self();\n      }\n\n      /**\n       * Provide the tenantId for this Floating IP. Admin-only.\n       * When keystone is enabled, it is not mandatory to specify tenant_id for resources in create requests, as the\n       * tenant identifier will be derived from the Authentication token. Please note that the default authorization\n       * settings only allow administrative users to create resources on behalf of a different tenant.\n       *\n       * @return the Builder.\n       * @see FloatingIP#getTenantId()\n       */\n      public ParameterizedBuilderType tenantId(String tenantId) {\n         floatingIP.tenantId = tenantId;\n         return self();\n      }\n\n      /**\n       * Provides the floating network id for this Floating IP.\n       * Mandatory when creating a floating IP.\n       * Floating IPs can only be created on external networks. If the network specified by floating_network_id is not\n       * external (for example, router:external=false), a 400 error is returned.\n       *\n       * @return the Builder.\n       * @see FloatingIP#getFloatingNetworkId() ()\n       */\n      public ParameterizedBuilderType floatingNetworkId(String floatingNetworkId) {\n         floatingIP.floatingNetworkId = floatingNetworkId;\n         return self();\n      }\n\n      /**\n       * Provides the fixed ip address for this Floating IP.\n       * As an OpenStack Networking port might be associated with multiple IP addresses, the particular IP address to\n       * associate with the floating IP can be specified using the fixed_ip_address request body parameter. The default\n       * logic of this operation is to associate the floating IP with a single IP address configured on a port; hence,\n       * if a port has multiple IP addresses, it is mandatory to specify the fixed_ip_address attribute. If an invalid\n       * IP address is specified in fixed_ip_address a 400 error will be returned.\n       *\n       * @return the Builder.\n       * @see FloatingIP#getFixedIpAddress()\n       */\n      public ParameterizedBuilderType fixedIpAddress(String fixedIpAddress) {\n         floatingIP.fixedIpAddress = fixedIpAddress;\n         return self();\n      }\n\n      /**\n       * Provides the port id for this Floating IP.\n       * Users can associate the floating IP with an internal port using the port_id attribute in the request body.\n       * If an invalid port identifier is specified, a 404 error will be returned. The internal OpenStack Networking\n       * port associated with the Floating IP must have at least an IP address configured, otherwise a 400 error will\n       * be returned.\n       *\n       * @return the Builder.\n       * @see FloatingIP#getPortId()\n       */\n      public ParameterizedBuilderType portId(String portId) {\n         floatingIP.portId = portId;\n         return self();\n      }\n\n      /**\n       * Provides the availability zone for this Floating IP.\n       *\n       * @return the Builder.\n       * @see FloatingIP#getAvailabilityZone()\n       */\n      public ParameterizedBuilderType availabilityZone(String availabilityZone) {\n         floatingIP.availabilityZone = availabilityZone;\n         return self();\n      }\n\n   }\n\n   public static class CreateBuilder extends Builder<CreateBuilder> {\n      /**\n       * Supply required properties for creating a Builder\n       */\n      private CreateBuilder(String floatingNetworkId) {\n         floatingIP.floatingNetworkId = floatingNetworkId;\n      }\n\n      /**\n       * @return a CreateFloatingIP constructed with this Builder.\n       */\n      public CreateFloatingIP build() {\n         return new CreateFloatingIP(floatingIP);\n      }\n\n      protected CreateBuilder self() {\n         return this;\n      }\n   }\n\n   public static class UpdateBuilder extends Builder<UpdateBuilder> {\n      /**\n       * Supply required properties for updating a Builder\n       */\n      private UpdateBuilder() {\n      }\n\n      /**\n       * Provide the floating ip address for this Floating IP.\n       * An address for the floating ip will be automatically allocated, unless the floating_ip_address attribute is\n       * specified in the request body. If the requested floating IP address does not fall in the external network's\n       * subnet range, a 400 error will be returned. If the requested floating IP address is already in use, a 409\n       * error code will be returned.\n       *\n       * @return the Builder.\n       * @see FloatingIP#getFloatingIpAddress()\n       */\n      public UpdateBuilder floatingIpAddress(String floatingIpAddress) {\n         floatingIP.floatingIpAddress = floatingIpAddress;\n         return this;\n      }\n\n      /**\n       * @return a UpdateFloatingIP constructed with this Builder.\n       */\n      public UpdateFloatingIP build() {\n         return new UpdateFloatingIP(floatingIP);\n      }\n\n      protected UpdateBuilder self() {\n         return this;\n      }\n   }\n\n   public static class CreateFloatingIP extends FloatingIP {\n      private CreateFloatingIP(FloatingIP floatingIP) {\n         super(floatingIP);\n      }\n   }\n   public static class UpdateFloatingIP extends FloatingIP {\n      private UpdateFloatingIP(FloatingIP floatingIP) {\n         super(floatingIP);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/FloatingIPs.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.PaginatedCollection;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * A collection of Floating IPs\n */\npublic class FloatingIPs extends PaginatedCollection<FloatingIP> {\n   public static final FloatingIPs EMPTY = new FloatingIPs(ImmutableSet.<FloatingIP> of(), ImmutableSet.<Link> of());\n\n   @ConstructorProperties({\"floatingips\", \"floatingips_links\"})\n   protected FloatingIPs(Iterable<FloatingIP> floatingIPs, Iterable<Link> floatingIPsLinks) {\n      super(floatingIPs, floatingIPsLinks);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/HostRoute.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * A Neutron Subnet Host Route\n *\n * @see <a href=\"http://docs.openstack.org/api/openstack-network/2.0/content/Subnets.html\">api doc</a>\n */\npublic class HostRoute {\n\n   @Named(\"destination\")\n   private final String destinationCidr;\n   @Named(\"nexthop\")\n   private final String nextHop;\n\n   @ConstructorProperties({\"destination\", \"nexthop\"})\n   protected HostRoute(String destinationCidr, String nextHop) {\n      this.destinationCidr = destinationCidr;\n      this.nextHop = nextHop;\n   }\n\n   /**\n    * @return the destination CIDR for this route.\n    */\n   @Nullable\n   public String getDestinationCidr() {\n      return destinationCidr;\n   }\n\n   /**\n    * @return the IP of the next hop to forward traffic to.\n    */\n   @Nullable\n   public String getNextHop() {\n      return nextHop;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(destinationCidr, nextHop);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      HostRoute that = HostRoute.class.cast(obj);\n      return Objects.equal(this.destinationCidr, that.destinationCidr) && Objects.equal(this.nextHop, that.nextHop);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"destinationCidr\", destinationCidr).add(\"nextHop\", nextHop);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return new Builder().fromHostRoute(this);\n   }\n\n   public static class Builder {\n      protected String destinationCidr;\n      protected String nextHop;\n\n      /**\n       * This should be a valid CIDR.\n       * @see HostRoute#getDestinationCidr()\n       */\n      public Builder destinationCidr(String destinationCidr) {\n         this.destinationCidr = destinationCidr;\n         return this;\n      }\n\n      /**\n       * This should be a valid IP address.\n       * @see HostRoute#getNextHop()\n       */\n      public Builder nextHop(String nextHop) {\n         this.nextHop = nextHop;\n         return this;\n      }\n\n      public HostRoute build() {\n         return new HostRoute(destinationCidr, nextHop);\n      }\n\n      public Builder fromHostRoute(HostRoute in) {\n         return this.destinationCidr(in.getDestinationCidr()).nextHop(in.getNextHop());\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/IP.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\n/**\n * Describes an IP address\n */\npublic class IP {\n\n   @Named(\"ip_address\")\n   protected final String ipAddress;\n   @Named(\"subnet_id\")\n   protected final String subnetId;\n\n   @ConstructorProperties({\"ip_address\", \"subnet_id\"})\n   protected IP(String ipAddress, String subnetId) {\n      this.ipAddress = ipAddress;\n      this.subnetId = subnetId;\n   }\n\n   /**\n    * @return the ipAddress of the IP\n    */\n   @Nullable\n   public String getIpAddress() {\n      return ipAddress;\n   }\n\n   /**\n    * @return the subnetId of the IP\n    */\n   @Nullable\n   public String getSubnetId() {\n      return subnetId;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(ipAddress, subnetId);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      IP that = IP.class.cast(obj);\n      return Objects.equal(this.ipAddress, that.ipAddress) && Objects.equal(this.subnetId, that.subnetId);\n   }\n\n   protected MoreObjects.ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).add(\"ipAddress\", ipAddress).add(\"subnetId\", subnetId);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   /**\n    * @return the Builder for IP\n    */\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   /**\n    * Gets a Builder configured as this object.\n    */\n   public Builder toBuilder() {\n      return new Builder().fromIP(this);\n   }\n\n   public static class Builder {\n      protected String ipAddress;\n      protected String subnetId;\n\n      /**\n       * Provide the ipAddress to the IP's Builder.\n       *\n       * @return the Builder.\n       * @see IP#getIpAddress()\n       */\n      public Builder ipAddress(String ipAddress) {\n         this.ipAddress = ipAddress;\n         return this;\n      }\n\n      /**\n       * Provide the subnetId to the IP's Builder.\n       *\n       * @return the Builder.\n       * @see IP#getSubnetId()\n       */\n      public Builder subnetId(String subnetId) {\n         this.subnetId = subnetId;\n         return this;\n      }\n\n      /**\n       * @return a IP constructed with this Builder.\n       */\n      public IP build() {\n         return new IP(ipAddress, subnetId);\n      }\n\n      /**\n       * @return a Builder from another IP.\n       */\n      public Builder fromIP(IP in) {\n         return this.ipAddress(in.getIpAddress()).subnetId(in.getSubnetId());\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/IPv6DHCPMode.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.openstack.neutron.v2.domain;\n\n/**\n * Enumerates DHCP modes for UPv6\n */\npublic enum IPv6DHCPMode {\n   OFF(\"off\"),\n   SLAAC(\"slaac\"),\n   DHCPV6_STATEFUL(\"dhcpv6-stateful\"),\n   DHCPV6_STATELESS(\"dhcpv6-stateless\"),\n   /**\n    * Used by jclouds when the service returns an unknown value other than null.\n    */\n   UNRECOGNIZED(\"unrecognized\");\n\n   private String name;\n\n   private IPv6DHCPMode(String name) {\n      this.name = name;\n   }\n\n   public String toString() {\n      return name;\n   }\n\n   /*\n    * This provides GSON enum support in jclouds.\n    * */\n   public static IPv6DHCPMode fromValue(String name){\n      if (name != null) {\n         for (IPv6DHCPMode value : IPv6DHCPMode.values()) {\n            if (name.equalsIgnoreCase(value.name)) {\n               return value;\n            }\n         }\n         return UNRECOGNIZED;\n      }\n      return null;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/IpVersion.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain;\n\npublic enum IpVersion {\n\n   IPV4(4),\n   IPV6(6),\n   UNRECOGNIZED(Integer.MAX_VALUE);;\n\n   private final int version;\n\n   IpVersion(int version) {\n      this.version = version;\n   }\n\n   public int version() {\n      return this.version;\n   }\n\n   public static IpVersion fromValue(String value) {\n      try {\n         int statusCode = Integer.parseInt(value);\n         switch (statusCode) {\n            case 4:\n               return IpVersion.IPV4;\n            case 6:\n               return IpVersion.IPV6;\n            default:\n               return IpVersion.IPV4;\n         }\n      } catch (NumberFormatException e) {\n         return IpVersion.UNRECOGNIZED;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/Network.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * A Neutron network\n *\n * @see <a\n *      href=\"http://docs.openstack.org/api/openstack-network/2.0/content/Networks.html\">api\n *      doc</a>\n */\npublic class Network {\n\n   private String id;\n   private NetworkStatus status;\n   private ImmutableSet<String> subnets;\n\n   private String name;\n   @Named(\"admin_state_up\")\n   private Boolean adminStateUp;\n   private Boolean shared;\n   @Named(\"tenant_id\")\n   private String tenantId;\n   @Named(\"availability_zone\")\n   private String availabilityZone;\n\n   // providernet.py: Provider Networks Extension\n   @Named(\"provider:network_type\")\n   private NetworkType networkType;\n   @Named(\"provider:physical_network\")\n   private String physicalNetworkName;\n   @Named(\"provider:segmentation_id\")\n   private Integer segmentationId;\n\n   // external_net.py: Configurable external gateway modes extension\n   @Named(\"router:external\")\n   private Boolean external;\n\n   // portsecurity.py: VMWare port security\n   @Named(\"port_security_enabled\")\n   private Boolean portSecurity;\n\n   // n1kv.py: Cisco plugin extension; admin rights might be needed\n   @Named(\"n1kv:profile_id\")\n   // UUID\n   private String profileId;\n   @Named(\"n1kv:multicast_ip\")\n   private String multicastIp;\n   @Named(\"n1kv:segment_add\")\n   private String segmentAdd;\n   @Named(\"n1kv:segment_del\")\n   private String segmentDel;\n   @Named(\"n1kv:member_segments\")\n   private String memberSegments;\n\n   // multiprovidernet.py: Multiprovider net extension; Segments and provider\n   // values cannot both be set.\n   private ImmutableSet<NetworkSegment> segments;\n\n   // flavor.py: Flavor support for network and router\n   @Named(\"flavor:network\")\n   private String networkFlavor;\n\n   @ConstructorProperties({\"id\", \"status\", \"subnets\", \"name\", \"admin_state_up\", \"shared\", \"tenant_id\", \"availability_zone\",\n         \"provider:network_type\", \"provider:physical_network\", \"provider:segmentation_id\", \"router:external\",\n         \"port_security_enabled\", \"n1kv:profile_id\", \"n1kv:multicast_ip\", \"n1kv:segment_add\", \"n1kv:segment_del\",\n         \"n1kv:member_segments\", \"segments\", \"flavor:network\"})\n   private Network(String id, NetworkStatus status, ImmutableSet<String> subnets, String name, Boolean adminStateUp,\n         Boolean shared, String tenantId, String availabilityZone, NetworkType networkType, String physicalNetworkName, Integer segmentationId,\n         Boolean external, Boolean portSecurity, String profileId, String multicastIp, String segmentAdd,\n         String segmentDel, String memberSegments, ImmutableSet<NetworkSegment> segments, String networkFlavor) {\n      // No checkNotNulls. With Neutron, any of these properties can be left null when used in an update.\n      this.id = id;\n      this.status = status;\n      this.subnets = subnets;\n      this.name = name;\n      this.adminStateUp = adminStateUp;\n      this.shared = shared;\n      this.tenantId = tenantId;\n      this.availabilityZone = availabilityZone;\n      this.networkType = networkType;\n      this.physicalNetworkName = physicalNetworkName;\n      this.segmentationId = segmentationId;\n      this.external = external;\n      this.portSecurity = portSecurity;\n      this.profileId = profileId;\n      this.multicastIp = multicastIp;\n      this.segmentAdd = segmentAdd;\n      this.segmentDel = segmentDel;\n      this.memberSegments = memberSegments;\n      this.segments = segments;\n      this.networkFlavor = networkFlavor;\n   }\n\n   /**\n    * Default constructor.\n    */\n   private Network() {}\n\n   /**\n    * Copy constructor\n    * @param network\n    */\n   private Network(Network network) {\n      this(network.id,\n      network.status,\n      network.subnets,\n      network.name,\n      network.adminStateUp,\n      network.shared,\n      network.tenantId,\n      network.availabilityZone,\n      network.networkType,\n      network.physicalNetworkName,\n      network.segmentationId,\n      network.external,\n      network.portSecurity,\n      network.profileId,\n      network.multicastIp,\n      network.segmentAdd,\n      network.segmentDel,\n      network.memberSegments,\n      network.segments,\n      network.networkFlavor);\n   }\n\n   /**\n    * @return the id of the Network\n    */\n   @Nullable\n   public String getId() {\n      return id;\n   }\n\n   /**\n    * @return the status of the Network\n    */\n   @Nullable\n   public NetworkStatus getStatus() {\n      return status;\n   }\n\n   /**\n    * @return the subnets of the Network\n    */\n   @Nullable\n   public ImmutableSet<String> getSubnets() {\n      return subnets;\n   }\n\n   /**\n    * @return the name of the Network\n    */\n   @Nullable\n   public String getName() {\n      return name;\n   }\n\n   /**\n    * @return the adminStateUp of the Network\n    */\n   @Nullable\n   public Boolean getAdminStateUp() {\n      return adminStateUp;\n   }\n\n   /**\n    * The shared attribute can be used to create a public network, i.e.: a network which is shared with all other tenants.\n    * Control of the shared attribute could be reserved to particular users only, such as administrators.\n    * In this case, regular users trying to create a shared network will receive a 403 - Forbidden error.\n    * @return true if the network resource can be accessed by any tenant or not, false if not\n    */\n   @Nullable\n   public Boolean getShared() {\n      return shared;\n   }\n\n   /**\n    * @return the tenantId of the Network\n    */\n   @Nullable\n   public String getTenantId() {\n      return tenantId;\n   }\n\n   /**\n    * @return the availability zone of the Network\n    */\n   @Nullable\n   public String getAvailabilityZone() {\n      return availabilityZone;\n   }\n\n   /**\n    * @return the networkType of the Network\n    */\n   @Nullable\n   public NetworkType getNetworkType() {\n      return networkType;\n   }\n\n   /**\n    * @return the physicalNetworkName of the Network\n    */\n   @Nullable\n   public String getPhysicalNetworkName() {\n      return physicalNetworkName;\n   }\n\n   /**\n    * @return the segmentationId of the Network\n    */\n   @Nullable\n   public Integer getSegmentationId() {\n      return segmentationId;\n   }\n\n   /**\n    * Adds external network attribute to network resource.\n    * @return the external of the Network\n    */\n   @Nullable\n   public Boolean getExternal() {\n      return external;\n   }\n\n   /**\n    * @return the portSecurity of the Network\n    */\n   @Nullable\n   public Boolean getPortSecurity() {\n      return portSecurity;\n   }\n\n   /**\n    * @return the profileId of the Network\n    */\n   @Nullable\n   public String getProfileId() {\n      return profileId;\n   }\n\n   /**\n    * @return the multicastIp of the Network\n    */\n   @Nullable\n   public String getMulticastIp() {\n      return multicastIp;\n   }\n\n   /**\n    * @return the segmentAdd of the Network\n    */\n   @Nullable\n   public String getSegmentAdd() {\n      return segmentAdd;\n   }\n\n   /**\n    * @return the segmentDel of the Network\n    */\n   @Nullable\n   public String getSegmentDel() {\n      return segmentDel;\n   }\n\n   /**\n    * @return the memberSegments of the Network\n    */\n   @Nullable\n   public String getMemberSegments() {\n      return memberSegments;\n   }\n\n   /**\n    * @return the segments of the Network\n    */\n   @Nullable\n   public ImmutableSet<NetworkSegment> getSegments() {\n      return segments;\n   }\n\n   /**\n    * @return the networkFlavor of the Network\n    */\n   @Nullable\n   public String getNetworkFlavor() {\n      return networkFlavor;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, status, subnets, name, adminStateUp, shared, tenantId, availabilityZone, networkType,\n            physicalNetworkName, segmentationId, external, portSecurity, profileId, multicastIp, segmentAdd, segmentDel,\n            memberSegments, segments, networkFlavor);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      Network that = Network.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n            && Objects.equal(this.status, that.status)\n            && Objects.equal(this.subnets, that.subnets)\n            && Objects.equal(this.name, that.name)\n            && Objects.equal(this.adminStateUp, that.adminStateUp)\n            && Objects.equal(this.shared, that.shared)\n            && Objects.equal(this.tenantId, that.tenantId)\n            && Objects.equal(this.availabilityZone, that.availabilityZone)\n            && Objects.equal(this.networkType, that.networkType)\n            && Objects.equal(this.physicalNetworkName, that.physicalNetworkName)\n            && Objects.equal(this.segmentationId, that.segmentationId)\n            && Objects.equal(this.external, that.external)\n            && Objects.equal(this.portSecurity, that.portSecurity)\n            && Objects.equal(this.profileId, that.profileId)\n            && Objects.equal(this.multicastIp, that.multicastIp)\n            && Objects.equal(this.segmentAdd, that.segmentAdd)\n            && Objects.equal(this.segmentDel, that.segmentDel)\n            && Objects.equal(this.memberSegments, that.memberSegments)\n            && Objects.equal(this.segments, that.segments)\n            && Objects.equal(this.networkFlavor, that.networkFlavor);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id)\n            .add(\"status\", status)\n            .add(\"subnets\", subnets)\n            .add(\"name\", name)\n            .add(\"adminStateUp\", adminStateUp)\n            .add(\"shared\", shared)\n            .add(\"tenantId\", tenantId)\n            .add(\"availabilityZone\", availabilityZone)\n            .add(\"networkType\", networkType)\n            .add(\"physicalNetworkName\", physicalNetworkName)\n            .add(\"segmentationId\", segmentationId)\n            .add(\"external\", external)\n            .add(\"portSecurity\", portSecurity)\n            .add(\"profileId\", profileId)\n            .add(\"multicastIp\", multicastIp)\n            .add(\"segmentAdd\", segmentAdd)\n            .add(\"segmentDel\", segmentDel)\n            .add(\"memberSegments\", memberSegments)\n            .add(\"segments\", segments)\n            .add(\"networkFlavor\", networkFlavor)\n            .toString();\n   }\n\n   /*\n    * Methods to get the Create and Update builders follow\n    */\n\n   /**\n    * @return the Builder for creating a new Router\n    */\n   public static CreateBuilder createBuilder(String name) {\n      return new CreateBuilder(name);\n   }\n\n   /**\n    * @return the Builder for updating a Router\n    */\n   public static UpdateBuilder updateBuilder() {\n      return new UpdateBuilder();\n   }\n\n   private abstract static class Builder<ParameterizedBuilderType> {\n      protected Network network;\n\n      /**\n       * No-parameters constructor used when updating.\n       * */\n      private Builder() {\n         network = new Network();\n      }\n\n      protected abstract ParameterizedBuilderType self();\n\n      /**\n       * Provide the name to the Network's Builder.\n       *\n       * @return the Builder.\n       * @see Network#getName()\n       */\n      public ParameterizedBuilderType name(String name) {\n         network.name = name;\n         return self();\n      }\n\n      /**\n       * Provide the adminStateUp to the Network's Builder.\n       *\n       * @return the Builder.\n       * @see Network#isAdminStateUp()\n       */\n      public ParameterizedBuilderType adminStateUp(Boolean adminStateUp) {\n         network.adminStateUp = adminStateUp;\n         return self();\n      }\n\n      /**\n       * Provide the shared to the Network's Builder.\n       *\n       * @return the Builder.\n       * @see Network#isShared()\n       */\n      public ParameterizedBuilderType shared(Boolean shared) {\n         network.shared = shared;\n         return self();\n      }\n\n      /**\n       * Provide the tenantId to the Network's Builder.\n       *\n       * @return the Builder.\n       * @see Network#getTenantId()\n       */\n      public ParameterizedBuilderType tenantId(String tenantId) {\n         network.tenantId = tenantId;\n         return self();\n      }\n\n      /**\n       * Provide the availabilityZone to the Network's Builder.\n       *\n       * @return the Builder.\n       * @see Network#getAvailabilityZone() ()\n       */\n      public ParameterizedBuilderType availabilityZone(String availabilityZone) {\n         network.availabilityZone = availabilityZone;\n         return self();\n      }\n\n      /**\n       * Provide the networkType to the Network's Builder.\n       *\n       * @return the Builder.\n       * @see Network#getNetworkType()\n       */\n      public ParameterizedBuilderType networkType(NetworkType networkType) {\n         network.networkType = networkType;\n         return self();\n      }\n\n      /**\n       * Provide the physicalNetworkName to the Network's Builder.\n       *\n       * @return the Builder.\n       * @see Network#getPhysicalNetworkName()\n       */\n      public ParameterizedBuilderType physicalNetworkName(String physicalNetworkName) {\n         network.physicalNetworkName = physicalNetworkName;\n         return self();\n      }\n\n      /**\n       * Provide the segmentationId to the Network's Builder.\n       *\n       * @return the Builder.\n       * @see Network#getSegmentationId()\n       */\n      public ParameterizedBuilderType segmentationId(Integer segmentationId) {\n         network.segmentationId = segmentationId;\n         return self();\n      }\n\n      /**\n       * Adds external network attribute to network resource.\n       *\n       * @return the Builder.\n       * @see Network#isExternal()\n       */\n      public ParameterizedBuilderType external(Boolean external) {\n         network.external = external;\n         return self();\n      }\n\n      /**\n       * Provide the portSecurity to the Network's Builder.\n       *\n       * @return the Builder.\n       * @see Network#isPortSecurity()\n       */\n      public ParameterizedBuilderType portSecurity(Boolean portSecurity) {\n         network.portSecurity = portSecurity;\n         return self();\n      }\n\n      /**\n       * Provide the profileId to the Network's Builder.\n       *\n       * @return the Builder.\n       * @see Network#getProfileId()\n       */\n      public ParameterizedBuilderType profileId(String profileId) {\n         network.profileId = profileId;\n         return self();\n      }\n\n      /**\n       * Provide the multicastIp to the Network's Builder.\n       *\n       * @return the Builder.\n       * @see Network#getMulticastIp()\n       */\n      public ParameterizedBuilderType multicastIp(String multicastIp) {\n         network.multicastIp = multicastIp;\n         return self();\n      }\n\n      /**\n       * Provide the segmentAdd to the Network's Builder.\n       * Cisco plugin extension; admin right might be needed to use this.\n       *\n       * @return the Builder.\n       * @see Network#getSegmentAdd()\n       */\n      public ParameterizedBuilderType segmentAdd(String segmentAdd) {\n         network.segmentAdd = segmentAdd;\n         return self();\n      }\n\n      /**\n       * Provide the segmentDel to the Network's Builder.\n       * Cisco plugin extension; admin right might be needed to use this.\n       *\n       * @return the Builder.\n       * @see Network#getSegmentDel()\n       */\n      public ParameterizedBuilderType segmentDel(String segmentDel) {\n         network.segmentDel = segmentDel;\n         return self();\n      }\n\n      /**\n       * Provide the memberSegments to the Network's Builder.\n       * Cisco plugin extension; admin right might be needed to use this.\n       *\n       * @return the Builder.\n       * @see Network#getMemberSegments()\n       */\n      public ParameterizedBuilderType memberSegments(String memberSegments) {\n         network.memberSegments = memberSegments;\n         return self();\n      }\n\n      /**\n       * Provide the segments to the Network's Builder.\n       * Multiprovider extension.\n       *\n       * @return the Builder.\n       * @see Network#getSegments()\n       */\n      public ParameterizedBuilderType segments(ImmutableSet<NetworkSegment> segments) {\n         network.segments = segments;\n         return self();\n      }\n\n      /**\n       * Provide the networkFlavor to the Network's Builder.\n       *\n       * @return the Builder.\n       * @see Network#getNetworkFlavor()\n       */\n      public ParameterizedBuilderType networkFlavor(String networkFlavor) {\n         network.networkFlavor = networkFlavor;\n         return self();\n      }\n   }\n\n   /**\n    * Create and Update builders (inheriting from Builder)\n    */\n   public static class CreateBuilder extends Builder<CreateBuilder> {\n      /**\n       * Supply required properties for creating a Builder\n       */\n      private CreateBuilder(String name) {\n         network.name = name;\n      }\n\n      /**\n       * @return a CreateNetwork constructed with this Builder.\n       */\n      public CreateNetwork build() {\n         return new CreateNetwork(network);\n      }\n\n      protected CreateBuilder self() {\n         return this;\n      }\n   }\n\n   /**\n    * Create and Update builders (inheriting from Builder)\n    */\n   public static class UpdateBuilder extends Builder<UpdateBuilder> {\n      /**\n       * Supply required properties for updating a Builder\n       */\n      private UpdateBuilder() {\n      }\n\n      /**\n       * @return a UpdateNetwork constructed with this Builder.\n       */\n      public UpdateNetwork build() {\n         return new UpdateNetwork(network);\n      }\n\n      protected UpdateBuilder self() {\n         return this;\n      }\n   }\n\n   /**\n    * Create and Update options - extend the domain class, passed to API update and create calls.\n    * Essentially the same as the domain class. Ensure validation and safe typing.\n    */\n   public static class CreateNetwork extends Network {\n      /**\n       * Copy constructor\n       */\n      private CreateNetwork(Network network) {\n         super(network);\n         checkNotNull(network.name, \"name should not be null\");\n      }\n   }\n\n   /**\n    * Create and Update options - extend the domain class, passed to API update and create calls.\n    * Essentially the same as the domain class. Ensure validation and safe typing.\n    */\n   public static class UpdateNetwork extends Network  {\n      /**\n       * Copy constructor\n       */\n      private UpdateNetwork(Network network) {\n         super(network);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/NetworkSegment.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\n/**\n * A Neutron Network Segment\n * Segments and provider values cannot both be set.\n *\n * @see <a\n *      href=\"http://docs.openstack.org/api/openstack-network/2.0/content/Subnets.html\">api\n *      doc</a>\n */\npublic class NetworkSegment {\n\n   @Named(\"provider:network_type\")\n   protected final NetworkType networkType;\n   @Named(\"provider:physical_network\")\n   protected final String physicalNetwork;\n   @Named(\"provider:segmentation_id\")\n   protected final Integer segmentationId;\n\n   @ConstructorProperties({\"provider:network_type\", \"provider:physical_network\", \"provider:segmentation_id\"})\n   protected NetworkSegment(NetworkType networkType, String physicalNetwork, Integer segmentationId) {\n      this.networkType = networkType;\n      this.physicalNetwork = physicalNetwork;\n      this.segmentationId = segmentationId;\n   }\n\n   /**\n    * @return the networkType of the NetworkSegment\n    */\n   @Nullable\n   public NetworkType getNetworkType() {\n      return networkType;\n   }\n\n   /**\n    * @return the physicalNetwork of the NetworkSegment\n    */\n   @Nullable\n   public String getPhysicalNetwork() {\n      return physicalNetwork;\n   }\n\n   /**\n    * @return the segmentationId of the NetworkSegment\n    */\n   @Nullable\n   public Integer getSegmentationId() {\n      return segmentationId;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(networkType, physicalNetwork, segmentationId);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      NetworkSegment that = NetworkSegment.class.cast(obj);\n      return Objects.equal(this.networkType, that.networkType)\n            && Objects.equal(this.physicalNetwork, that.physicalNetwork)\n            && Objects.equal(this.segmentationId, that.segmentationId);\n   }\n\n   protected MoreObjects.ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).add(\"networkType\", networkType).add(\"physicalNetwork\", physicalNetwork)\n            .add(\"segmentationId\", segmentationId);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   /**\n    * @return the Builder for NetworkSegment\n    */\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   /**\n    * Gets a Builder configured as this object.\n    */\n   public Builder toBuilder() {\n      return new Builder().fromNetworkSegment(this);\n   }\n\n   public static class Builder {\n      protected NetworkType networkType;\n      protected String physicalNetwork;\n      protected Integer segmentationId;\n\n      /**\n       * Provide the networkType to the NetworkSegment's Builder.\n       *\n       * @return the Builder.\n       * @see NetworkSegment#getNetworkType()\n       */\n      public Builder networkType(NetworkType networkType) {\n         this.networkType = networkType;\n         return this;\n      }\n\n      /**\n       * Provide the physicalNetwork to the NetworkSegment's Builder.\n       *\n       * @return the Builder.\n       * @see NetworkSegment#getPhysicalNetwork()\n       */\n      public Builder physicalNetwork(String physicalNetwork) {\n         this.physicalNetwork = physicalNetwork;\n         return this;\n      }\n\n      /**\n       * Provide the segmentationId to the NetworkSegment's Builder.\n       *\n       * @return the Builder.\n       * @see NetworkSegment#getSegmentationId()\n       */\n      public Builder segmentationId(int segmentationId) {\n         this.segmentationId = segmentationId;\n         return this;\n      }\n\n      /**\n       * @return a NetworkSegment constructed with this Builder.\n       */\n      public NetworkSegment build() {\n         return new NetworkSegment(networkType, physicalNetwork, segmentationId);\n      }\n\n      /**\n       * @return a Builder from another NetworkSegment.\n       */\n      public Builder fromNetworkSegment(NetworkSegment in) {\n         return this.networkType(in.getNetworkType()).physicalNetwork(in.getPhysicalNetwork())\n               .segmentationId(in.getSegmentationId());\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/NetworkStatus.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.openstack.neutron.v2.domain;\n\n/**\n * Enumerates Network Status.\n */\npublic enum NetworkStatus {\n   ACTIVE(\"active\"),\n   DOWN(\"down\"),\n   BUILD(\"build\"),\n   ERROR(\"error\"),\n   /**\n    * Used by jclouds when the service returns an unknown value other than null.\n    */\n   UNRECOGNIZED(\"unrecognized\");\n\n   private final String name;\n\n   private NetworkStatus(String name) {\n      this.name = name;\n   }\n\n   @Override\n   public String toString() {\n      return name();\n   }\n\n   /*\n    * This provides GSON enum support in jclouds.\n    * @param name The string representation of this enum value.\n    * @return The corresponding enum value.\n    */\n   public static NetworkStatus fromValue(String name) {\n      if (name != null) {\n         for (NetworkStatus value : NetworkStatus.values()) {\n           if (name.equalsIgnoreCase(value.name)) {\n             return value;\n           }\n         }\n         return UNRECOGNIZED;\n       }\n       return null;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/NetworkType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.openstack.neutron.v2.domain;\n\n/**\n * Enumerates supported Network types.\n */\npublic enum NetworkType {\n   /**\n    * Used to describe a local network.\n    */\n   LOCAL(\"local\"),\n   /**\n    * Used to describe a flat network.\n    */\n   FLAT(\"flat\"),\n   /**\n    * Used to describe a VLAN network. NetworkSegment might have to be set.\n    */\n   VLAN(\"vlan\"),\n   /**\n    * Used to describe a Virtual Extensible LAN (VXLAN) network.\n    * It uses a VLAN-like encapsulation technique to encapsulate MAC-based\n    * OSI layer 2 Ethernet frames within layer 4 UDP packets.\n    */\n   VXLAN(\"vxlan\"),\n   /**\n    * Used to describe a GRE tunnel network. A virtual network realized as\n    * packets encapsulated using Generic Routing Encapsulation. GRE tunnel\n    * packets are routed by the compute node hosts, so GRE tunnels are not\n    * associated by the openvswitch plugin with specific physical networks.\n    */\n   GRE(\"gre\"),\n   /**\n    * Used by jclouds when the service returns an unknown value other than null.\n    */\n   UNRECOGNIZED(\"unrecognized\");\n\n   private String name;\n\n   private NetworkType(String name) {\n      this.name = name;\n   }\n\n   @Override\n   public String toString() {\n      return name;\n   }\n\n   /*\n    * This provides GSON enum support in jclouds.\n    * @param name The string representation of this enum value.\n    * @return The corresponding enum value.\n    */\n   public static NetworkType fromValue(String name) {\n      if (name != null) {\n         for (NetworkType value : NetworkType.values()) {\n           if (name.equalsIgnoreCase(value.name)) {\n             return value;\n           }\n         }\n         return UNRECOGNIZED;\n       }\n       return null;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/Networks.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Set;\n\nimport com.google.common.base.Predicate;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.PaginatedCollection;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * A collection of Networks\n */\npublic class Networks extends PaginatedCollection<Network> {\n   public static final Networks EMPTY = new Networks(ImmutableSet.<Network> of(), ImmutableSet.<Link> of());\n\n   @ConstructorProperties({\"networks\", \"networks_links\"})\n   protected Networks(Iterable<Network> networks, Iterable<Link> networksLinks) {\n      super(networks, networksLinks);\n   }\n\n   public static class Predicates {\n\n      public static Predicate<Network> externalNetworks(final String availabilityZone) {\n         return new Predicate<Network>() {\n            @Override\n            public boolean apply(Network network) {\n               return availabilityZone.equals(network.getAvailabilityZone()) && network.getExternal();\n            }\n         };\n      }\n\n      public static Predicate<Network> namedNetworks(final Set<String> names) {\n         return new Predicate<Network>() {\n            @Override\n            public boolean apply(Network network) {\n               return names.contains(network.getName());\n            }\n         };\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/Port.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * A Neutron port\n *\n * @see <a\n *      href=\"http://docs.openstack.org/api/openstack-network/1.0/content/Ports.html\">api\n *      doc</a>\n */\npublic class Port {\n\n   private String id;\n   private NetworkStatus status;\n\n   // Extensions\n\n   // portbindings.py\n   // The service will return the vif type for the specific port.\n   @Named(\"binding:vif_type\")\n   private VIFType vifType;\n   // The service may return a dictionary containing additional\n   // information needed by the interface driver. The set of items\n   // returned may depend on the value of VIF_TYPE.\n   @Named(\"binding:vif_details\")\n   private ImmutableMap<String, Object> vifDetails;\n\n   // Plugins\n\n   // qos.py\n   @Named(\"queue_id\")\n   private String qosQueueId;\n\n   private String name;\n   @Named(\"network_id\")\n   private String networkId;\n   @Named(\"admin_state_up\")\n   private Boolean adminStateUp;\n   @Named(\"mac_address\")\n   private String macAddress;\n   @Named(\"fixed_ips\")\n   private ImmutableSet<IP> fixedIps;\n   @Named(\"device_id\")\n   private String deviceId;\n   @Named(\"device_owner\")\n   private String deviceOwner;\n   @Named(\"tenant_id\")\n   private String tenantId;\n   @Named(\"security_groups\")\n   private ImmutableSet<String> securityGroups;\n\n   // Extensions\n\n   // allowedaddresspairs.py\n   @Named(\"allowed_address_pairs\")\n   private ImmutableSet<AddressPair> allowedAddressPairs;\n\n   // extra_dhcp_opt.py\n   @Named(\"extra_dhcp_opts\")\n   private ImmutableSet<ExtraDhcpOption> extraDhcpOptions;\n\n   // portbindings.py\n   // The type of vnic that this port should be attached to\n   @Named(\"binding:vnic_type\")\n   private VNICType vnicType;\n   // In some cases different implementations may be run on different hosts.\n   // The host on which the port will be allocated.\n   @Named(\"binding:host_id\")\n   private String hostId;\n   // The profile will be a dictionary that enables the application running\n   // on the specific host to pass and receive vif port specific information to\n   // the plugin.\n   @Named(\"binding:profile\")\n   private ImmutableMap<String, Object> profile;\n\n   // portsecurity.py\n   @Named(\"port_security_enabled\")\n   private Boolean portSecurity;\n\n   // Plugins\n\n   // n1kv.py\n   @Named(\"n1kv:profile_id\")\n   private String profileId;\n\n   // maclearning.py\n   @Named(\"mac_learning_enabled\")\n   private Boolean macLearning;\n\n   // qos.py\n   @Named(\"rxtx_factor\")\n   private Integer qosRxtxFactor;\n\n   @ConstructorProperties({\"id\", \"status\", \"binding:vif_type\", \"binding:vif_details\", \"queue_id\", \"name\", \"network_id\",\n         \"admin_state_up\", \"mac_address\", \"fixed_ips\", \"device_id\", \"device_owner\", \"tenant_id\", \"security_groups\",\n         \"allowed_address_pairs\", \"extra_dhcp_opts\", \"binding:vnic_type\", \"binding:host_id\", \"binding:profile\",\n         \"port_security_enabled\", \"n1kv:profile_id\", \"mac_learning_enabled\", \"rxtx_factor\"})\n   protected Port(String id, NetworkStatus status, VIFType vifType, ImmutableMap<String, Object> vifDetails, String qosQueueId,\n         String name, String networkId, Boolean adminStateUp, String macAddress, ImmutableSet<IP> fixedIps, String deviceId,\n         String deviceOwner, String tenantId, ImmutableSet<String> securityGroups, ImmutableSet<AddressPair> allowedAddressPairs,\n         ImmutableSet<ExtraDhcpOption> extraDhcpOptions, VNICType vnicType, String hostId, ImmutableMap<String, Object> profile,\n         Boolean portSecurity, String profileId, Boolean macLearning, Integer qosRxtxFactor) {\n      this.id = id;\n      this.status = status;\n      this.vifType = vifType;\n      this.vifDetails = vifDetails;\n      this.qosQueueId = qosQueueId;\n      this.name = name;\n      this.networkId = networkId;\n      this.adminStateUp = adminStateUp;\n      this.macAddress = macAddress;\n      this.fixedIps = fixedIps;\n      this.deviceId = deviceId;\n      this.deviceOwner = deviceOwner;\n      this.tenantId = tenantId;\n      this.securityGroups = securityGroups;\n      this.allowedAddressPairs = allowedAddressPairs;\n      this.extraDhcpOptions = extraDhcpOptions;\n      this.vnicType = vnicType;\n      this.hostId = hostId;\n      this.profile = profile;\n      this.portSecurity = portSecurity;\n      this.profileId = profileId;\n      this.macLearning = macLearning;\n      this.qosRxtxFactor = qosRxtxFactor;\n   }\n\n   /**\n    * Default constructor.\n    */\n   private Port() {}\n\n   /**\n    * Copy constructor\n    * @param port\n    */\n   private Port(Port port) {\n      this(port.id,\n      port.status,\n      port.vifType,\n      port.vifDetails,\n      port.qosQueueId,\n      port.name,\n      port.networkId,\n      port.adminStateUp,\n      port.macAddress,\n      port.fixedIps,\n      port.deviceId,\n      port.deviceOwner,\n      port.tenantId,\n      port.securityGroups,\n      port.allowedAddressPairs,\n      port.extraDhcpOptions,\n      port.vnicType,\n      port.hostId,\n      port.profile,\n      port.portSecurity,\n      port.profileId,\n      port.macLearning,\n      port.qosRxtxFactor);\n   }\n\n   /**\n    * @return the id of the Port\n    */\n   @Nullable\n   public String getId() {\n      return id;\n   }\n\n   /**\n    * @return the status of the Port\n    */\n   @Nullable\n   public NetworkStatus getStatus() {\n      return status;\n   }\n\n   /**\n    *\n    * @return the vifType of the Port. Visible to only administrative users.\n    *\n    */\n   @Nullable\n   public VIFType getVifType() {\n      return vifType;\n   }\n\n   /**\n    * @return the vifDetails of the Port. A dictionary that enables the application to pass information about functions\n    * that Networking API v2.0 provides. Specify the following value: port_filter : Boolean to define whether\n    * Networking API v2.0 provides port filtering features such as security group and anti-MAC/IP spoofing. Visible to\n    * only administrative users.\n    */\n   @Nullable\n   public ImmutableMap<String, Object> getVifDetails() {\n      return vifDetails;\n   }\n\n   /**\n    * @return the qosQueueId of the Port\n    */\n   @Nullable\n   public String getQosQueueId() {\n      return qosQueueId;\n   }\n\n   /**\n    * @return the name of the Port\n    */\n   @Nullable\n   public String getName() {\n      return name;\n   }\n\n   /**\n    * @return the id of the network where this port is associated with.\n    */\n   @Nullable\n   public String getNetworkId() {\n      return networkId;\n   }\n\n   /**\n    * @return the administrative state of port. If false, port does not forward packets.\n    */\n   @Nullable\n   public Boolean getAdminStateUp() {\n      return adminStateUp;\n   }\n\n   /**\n    * @return the macAddress of the Port\n    */\n   @Nullable\n   public String getMacAddress() {\n      return macAddress;\n   }\n\n   /**\n    * @return the set of fixed ips this port has been assigned.\n    */\n   @Nullable\n   public ImmutableSet<IP> getFixedIps() {\n      return fixedIps;\n   }\n\n   /**\n    * @return the id of the device (e.g. server) using this port.\n    */\n   @Nullable\n   public String getDeviceId() {\n      return deviceId;\n   }\n\n   /**\n    * @return the entity (e.g.: dhcp agent) using this port.\n    */\n   @Nullable\n   public String getDeviceOwner() {\n      return deviceOwner;\n   }\n\n   /**\n    * @return the tenantId of the Port\n    */\n   @Nullable\n   public String getTenantId() {\n      return tenantId;\n   }\n\n   /**\n    * @return the set of security groups\n    */\n   @Nullable\n   public ImmutableSet<String> getSecurityGroups() {\n      return securityGroups;\n   }\n\n   /**\n    * @return the allowedAddressPairs of the Port\n    */\n   @Nullable\n   public ImmutableSet<AddressPair> getAllowedAddressPairs() {\n      return allowedAddressPairs;\n   }\n\n   /**\n    * @return the extraDhcpOptions of the Port\n    */\n   @Nullable\n   public ImmutableSet<ExtraDhcpOption> getExtraDhcpOptions() {\n      return extraDhcpOptions;\n   }\n\n   /**\n    * @return the vnicType of the Port. This extended attribute is visible to only port owners and administrative users.\n    * Specifies a value of normal (virtual nic), direct (pci passthrough), or macvtap (virtual interface with a\n    * tap-like software interface). These values support SR-IOV PCI passthrough networking. The ML2 plug-in supports\n    * the vnic_type.\n    */\n   @Nullable\n   public VNICType getVnicType() {\n      return vnicType;\n   }\n\n   /**\n    * @return the hostId of the Port. The ID of the host where the port is allocated. In some cases, different\n    * implementations can run on different hosts. Visible to only administrative users.\n    */\n   @Nullable\n   public String getHostId() {\n      return hostId;\n   }\n\n   /**\n    * @return the profile of the Port. A dictionary that enables the application to pass information about functions\n    * that the Networking API provides. To enable or disable port filtering features such as security group and\n    * anti-MAC/IP spoofing, specify port_filter: True or port_filter: False. Visible to only administrative users.\n    */\n   @Nullable\n   public ImmutableMap<String, Object> getProfile() {\n      return profile;\n   }\n\n   /**\n    * @return the portSecurity of the Port\n    */\n   @Nullable\n   public Boolean getPortSecurity() {\n      return portSecurity;\n   }\n\n   /**\n    * @return the profileId of the Port\n    */\n   @Nullable\n   public String getProfileId() {\n      return profileId;\n   }\n\n   /**\n    * @return the macLearning of the Port\n    */\n   @Nullable\n   public Boolean getMacLearning() {\n      return macLearning;\n   }\n\n   /**\n    * @return the qosRxtxFactor of the Port\n    */\n   @Nullable\n   public Integer getQosRxtxFactor() {\n      return qosRxtxFactor;\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o)\n         return true;\n      if (o == null || getClass() != o.getClass())\n         return false;\n\n      Port that = (Port) o;\n\n      return Objects.equal(this.id, that.id) &&\n            Objects.equal(this.status, that.status) &&\n            Objects.equal(this.vifType, that.vifType) &&\n            Objects.equal(this.vifDetails, that.vifDetails) &&\n            Objects.equal(this.qosQueueId, that.qosQueueId) &&\n            Objects.equal(this.name, that.name) &&\n            Objects.equal(this.networkId, that.networkId) &&\n            Objects.equal(this.adminStateUp, that.adminStateUp) &&\n            Objects.equal(this.macAddress, that.macAddress) &&\n            Objects.equal(this.fixedIps, that.fixedIps) &&\n            Objects.equal(this.deviceId, that.deviceId) &&\n            Objects.equal(this.deviceOwner, that.deviceOwner) &&\n            Objects.equal(this.tenantId, that.tenantId) &&\n            Objects.equal(this.securityGroups, that.securityGroups) &&\n            Objects.equal(this.allowedAddressPairs, that.allowedAddressPairs) &&\n            Objects.equal(this.extraDhcpOptions, that.extraDhcpOptions) &&\n            Objects.equal(this.vnicType, that.vnicType) &&\n            Objects.equal(this.hostId, that.hostId) &&\n            Objects.equal(this.profile, that.profile) &&\n            Objects.equal(this.portSecurity, that.portSecurity) &&\n            Objects.equal(this.profileId, that.profileId) &&\n            Objects.equal(this.macLearning, that.macLearning) &&\n            Objects.equal(this.qosRxtxFactor, that.qosRxtxFactor);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, status, vifType, vifDetails, qosQueueId, name,\n            networkId, adminStateUp, macAddress, fixedIps, deviceId,\n            deviceOwner, tenantId, securityGroups, allowedAddressPairs, extraDhcpOptions,\n            vnicType, hostId, profile, portSecurity, profileId,\n            macLearning, qosRxtxFactor);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id)\n            .add(\"status\", status)\n            .add(\"vifType\", vifType)\n            .add(\"vifDetails\", vifDetails)\n            .add(\"qosQueueId\", qosQueueId)\n            .add(\"name\", name)\n            .add(\"networkId\", networkId)\n            .add(\"adminStateUp\", adminStateUp)\n            .add(\"macAddress\", macAddress)\n            .add(\"fixedIps\", fixedIps)\n            .add(\"deviceId\", deviceId)\n            .add(\"deviceOwner\", deviceOwner)\n            .add(\"tenantId\", tenantId)\n            .add(\"securityGroups\", securityGroups)\n            .add(\"allowedAddressPairs\", allowedAddressPairs)\n            .add(\"extraDhcpOptions\", extraDhcpOptions)\n            .add(\"vnicType\", vnicType)\n            .add(\"hostId\", hostId)\n            .add(\"profile\", profile)\n            .add(\"portSecurity\", portSecurity)\n            .add(\"profileId\", profileId)\n            .add(\"macLearning\", macLearning)\n            .add(\"qosRxtxFactor\", qosRxtxFactor)\n            .toString();\n   }\n\n   /*\n    * Methods to get the Create and Update builders follow\n    */\n\n   /**\n    * @return the Builder for creating a new Router\n    */\n   public static CreateBuilder createBuilder(String networkId) {\n      return new CreateBuilder(networkId);\n   }\n\n   /**\n    * @return the Builder for updating a Router\n    */\n   public static UpdateBuilder updateBuilder() {\n      return new UpdateBuilder();\n   }\n\n   private abstract static class Builder<ParameterizedBuilderType> {\n      protected Port port;\n\n      /**\n       * No-parameters constructor used when updating.\n       */\n      private Builder() {\n         port = new Port();\n      }\n\n      protected abstract ParameterizedBuilderType self();\n\n      /**\n       * Provide the name to the Port's Builder.\n       *\n       * @return the Builder.\n       * @see Port#getName()\n       */\n      public ParameterizedBuilderType name(String name) {\n         port.name = name;\n         return self();\n      }\n\n      /**\n       * Provide the networkId to the Port's Builder.\n       *\n       * @return the Builder.\n       * @see Port#getNetworkId()\n       */\n      public ParameterizedBuilderType networkId(String networkId) {\n         port.networkId = networkId;\n         return self();\n      }\n\n      /**\n       * Provide the adminStateUp to the Port's Builder.\n       *\n       * @return the Builder.\n       * @see Port#getAdminStateUp()\n       */\n      public ParameterizedBuilderType adminStateUp(Boolean adminStateUp) {\n         port.adminStateUp = adminStateUp;\n         return self();\n      }\n\n      /**\n       * Provide the macAddress to the Port's Builder.\n       *\n       * @return the Builder.\n       * @see Port#getMacAddress()\n       */\n      public ParameterizedBuilderType macAddress(String macAddress) {\n         port.macAddress = macAddress;\n         return self();\n      }\n\n      /**\n       * Provide the fixedIps to the Port's Builder.\n       *\n       * @return the Builder.\n       * @see Port#getFixedIps()\n       */\n      public ParameterizedBuilderType fixedIps(ImmutableSet<IP> fixedIps) {\n         port.fixedIps = fixedIps;\n         return self();\n      }\n\n      /**\n       * Provide the deviceId to the Port's Builder.\n       *\n       * @return the Builder.\n       * @see Port#getDeviceId()\n       */\n      public ParameterizedBuilderType deviceId(String deviceId) {\n         port.deviceId = deviceId;\n         return self();\n      }\n\n      /**\n       * Provide the deviceOwner to the Port's Builder.\n       *\n       * @return the Builder.\n       * @see Port#getDeviceOwner()\n       */\n      public ParameterizedBuilderType deviceOwner(String deviceOwner) {\n         port.deviceOwner = deviceOwner;\n         return self();\n      }\n\n      /**\n       * Provide the tenantId to the Port's Builder.\n       *\n       * @return the Builder.\n       * @see Port#getTenantId()\n       */\n      public ParameterizedBuilderType tenantId(String tenantId) {\n         port.tenantId = tenantId;\n         return self();\n      }\n\n      /**\n       * Provide the tenantId to the Port's Builder.\n       *\n       * @return the Builder.\n       * @see Port#getSecurityGroups()\n       */\n      public ParameterizedBuilderType securityGroups(ImmutableSet<String> securityGroups) {\n         port.securityGroups = securityGroups;\n         return self();\n      }\n\n      /**\n       * Provide the allowedAddressPairs to the Port's Builder.\n       *\n       * @return the Builder.\n       * @see Port#getAllowedAddressPairs()\n       */\n      public ParameterizedBuilderType allowedAddressPairs(ImmutableSet<AddressPair> allowedAddressPairs) {\n         port.allowedAddressPairs = allowedAddressPairs;\n         return self();\n      }\n\n      /**\n       * Provide the extraDhcpOptions to the Port's Builder.\n       *\n       * @return the Builder.\n       * @see Port#getExtraDhcpOptions()\n       */\n      public ParameterizedBuilderType extraDhcpOptions(ImmutableSet<ExtraDhcpOption> extraDhcpOptions) {\n         port.extraDhcpOptions = extraDhcpOptions;\n         return self();\n      }\n\n      /**\n       * Provide the vnicType to the Port's Builder.\n       * Specify a value of normal (virtual nic), direct (pci passthrough), or macvtap (virtual interface with a\n       * tap-like software interface). These values support SR-IOV PCI passthrough networking. The ML2 plug-in supports\n       * the vnic_type.\n       *\n       * @return the Builder.\n       * @see Port#getVnicType()\n       */\n      public ParameterizedBuilderType vnicType(VNICType vnicType) {\n         port.vnicType = vnicType;\n         return self();\n      }\n\n      /**\n       * Provide the hostId to the Port's Builder.\n       *\n       * @return the Builder.\n       * @see Port#getHostId()\n       */\n      public ParameterizedBuilderType hostId(String hostId) {\n         port.hostId = hostId;\n         return self();\n      }\n\n      /**\n       * Provide the profile to the Port's Builder.\n       * This attribute is a dictionary that can be used (with admin credentials) to supply information influencing the\n       * binding of the port. This functionality is needed for SR-IOV PCI passthrough.\n       *\n       * @return the Builder.\n       * @see Port#getProfile()\n       */\n      public ParameterizedBuilderType profile(ImmutableMap<String, Object> profile) {\n         port.profile = profile;\n         return self();\n      }\n\n      /**\n       * Provide the portSecurity to the Port's Builder.\n       *\n       * @return the Builder.\n       * @see Port#getPortSecurity()\n       */\n      public ParameterizedBuilderType portSecurity(Boolean portSecurity) {\n         port.portSecurity = portSecurity;\n         return self();\n      }\n\n      /**\n       * Provide the profileId to the Port's Builder.\n       *\n       * @return the Builder.\n       * @see Port#getProfileId()\n       */\n      public ParameterizedBuilderType profileId(String profileId) {\n         port.profileId = profileId;\n         return self();\n      }\n\n      /**\n       * Provide the macLearning to the Port's Builder.\n       *\n       * @return the Builder.\n       * @see Port#getMacLearning()\n       */\n      public ParameterizedBuilderType macLearning(Boolean macLearning) {\n         port.macLearning = macLearning;\n         return self();\n      }\n\n      /**\n       * Provide the qosRxtxFactor to the Port's Builder.\n       *\n       * @return the Builder.\n       * @see Port#getQosRxtxFactor()\n       */\n      public ParameterizedBuilderType qosRxtxFactor(int qosRxtxFactor) {\n         port.qosRxtxFactor = qosRxtxFactor;\n         return self();\n      }\n   }\n\n   /**\n    * Create and Update builders (inheriting from Builder)\n    */\n   public static class CreateBuilder extends Builder<CreateBuilder> {\n      /**\n       *\n       * Supply required properties for creating a Builder\n       */\n      private CreateBuilder(String networkId) {\n         port.networkId = networkId;\n      }\n\n      /**\n       * @return a CreatePort constructed with this Builder.\n       */\n      public CreatePort build() {\n         return new CreatePort(port);\n      }\n\n      protected CreateBuilder self() {\n         return this;\n      }\n   }\n\n   /**\n    * Create and Update builders (inheriting from Builder)\n    */\n   public static class UpdateBuilder extends Builder<UpdateBuilder> {\n      /**\n       * Supply required properties for updating a Builder\n       */\n      private UpdateBuilder() {\n      }\n\n      /**\n       * @return a UpdatePort constructed with this Builder.\n       */\n      public UpdatePort build() {\n         return new UpdatePort(port);\n      }\n\n      protected UpdateBuilder self() {\n         return this;\n      }\n   }\n\n   /**\n    * Create and Update options - extend the domain class, passed to API update and create calls.\n    * Essentially the same as the domain class. Ensure validation and safe typing.\n    */\n   public static class CreatePort extends Port {\n      /**\n       * Copy constructor\n       */\n      private CreatePort(Port port) {\n         super(port);\n         checkNotNull(port.networkId, \"networkId should not be null\");\n      }\n   }\n\n   /**\n    * Create and Update options - extend the domain class, passed to API update and create calls.\n    * Essentially the same as the domain class. Ensure validation and safe typing.\n    */\n   public static class UpdatePort extends Port {\n      /**\n       * Copy constructor\n       */\n      private UpdatePort(Port port) {\n         super(port);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/Ports.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.PaginatedCollection;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * A collection of Ports\n */\npublic class Ports extends PaginatedCollection<Port> {\n   public static final Ports EMPTY = new Ports(ImmutableSet.<Port> of(), ImmutableSet.<Link> of());\n\n   @ConstructorProperties({\"ports\", \"ports_links\"})\n   protected Ports(Iterable<Port> ports, Iterable<Link> portsLinks) {\n      super(ports, portsLinks);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/Router.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\n/**\n * A Neutron Router\n *\n * @see <a\n *      href=\"http://docs.openstack.org/api/openstack-network/2.0/content/router_ext_concepts.html\">api\n *      doc</a>\n */\npublic class Router {\n\n   private String id;\n   private NetworkStatus status;\n\n   private String name;\n   @Named(\"tenant_id\")\n   private String tenantId;\n   @Named(\"admin_state_up\")\n   private Boolean adminStateUp;\n   @Named(\"external_gateway_info\")\n   private ExternalGatewayInfo externalGatewayInfo;\n\n   /**\n    * @param id\n    * @param status\n    * @param name\n    * @param tenantId\n    * @param adminStateUp\n    * @param externalGatewayInfo\n    */\n   @ConstructorProperties({\"id\", \"status\", \"name\", \"tenant_id\", \"admin_state_up\", \"external_gateway_info\"})\n   private Router(String id, NetworkStatus status, String name, String tenantId, Boolean adminStateUp, ExternalGatewayInfo externalGatewayInfo) {\n      this.id = id;\n      this.status = status;\n      this.name = name;\n      this.tenantId = tenantId;\n      this.adminStateUp = adminStateUp;\n      this.externalGatewayInfo = externalGatewayInfo;\n   }\n\n   /**\n    * Default constructor.\n    */\n   private Router() {}\n\n   /**\n    * Copy constructor\n    * @param router\n    */\n   private Router(Router router) {\n      this(router.id, router.status, router.name, router.tenantId, router.adminStateUp, router.externalGatewayInfo);\n   }\n\n   /**\n    * @return the id of the Router\n    */\n   @Nullable\n   public String getId() {\n      return id;\n   }\n\n   /**\n    * @return the status of the Router\n    */\n   @Nullable\n   public NetworkStatus getStatus() {\n      return status;\n   }\n\n   /**\n    * @return the name of the Router\n    */\n   @Nullable\n   public String getName() {\n      return name;\n   }\n\n   /**\n    * @return the tenantId of the Router\n    */\n   @Nullable\n   public String getTenantId() {\n      return tenantId;\n   }\n\n   /**\n    * @return the adminStateUp of the Router\n    */\n   @Nullable\n   public Boolean getAdminStateUp() {\n      return adminStateUp;\n   }\n\n   /**\n    * @return the externalGatewayInfo of the Router\n    */\n   @Nullable\n   public ExternalGatewayInfo getExternalGatewayInfo() {\n      return externalGatewayInfo;\n   }\n\n   /**\n    * @return the Builder for creating a new Router\n    */\n   public static CreateBuilder createBuilder() {\n      return new CreateBuilder();\n   }\n\n   /**\n    * @return the Builder for updating a Router\n    */\n   public static UpdateBuilder updateBuilder() {\n      return new UpdateBuilder();\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o)\n         return true;\n      if (o == null || getClass() != o.getClass())\n         return false;\n\n      Router that = (Router) o;\n\n      return Objects.equal(this.id, that.id) &&\n            Objects.equal(this.status, that.status) &&\n            Objects.equal(this.name, that.name) &&\n            Objects.equal(this.tenantId, that.tenantId) &&\n            Objects.equal(this.adminStateUp, that.adminStateUp) &&\n            Objects.equal(this.externalGatewayInfo, that.externalGatewayInfo);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, status, name, tenantId, adminStateUp, externalGatewayInfo);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id)\n            .add(\"status\", status)\n            .add(\"name\", name)\n            .add(\"tenantId\", tenantId)\n            .add(\"adminStateUp\", adminStateUp)\n            .add(\"externalGatewayInfo\", externalGatewayInfo)\n            .toString();\n   }\n\n   private abstract static class Builder<ParameterizedBuilderType> {\n      protected Router router;\n\n      /**\n       * No-parameters constructor used when updating.\n       * */\n      private Builder() {\n         router = new Router();\n      }\n\n      protected abstract ParameterizedBuilderType self();\n\n      /**\n       * Provide the name to the Router's Builder.\n       *\n       * @return the Builder.\n       * @see Router#getName()\n       */\n      public ParameterizedBuilderType name(String name) {\n         router.name = name;\n         return self();\n      }\n\n      /**\n       * Provide the tenantId to the Router's Builder.\n       *\n       * @return the Builder.\n       * @see Router#getTenantId()\n       */\n      public ParameterizedBuilderType tenantId(String tenantId) {\n         router.tenantId = tenantId;\n         return self();\n      }\n\n      /**\n       * Provide the adminStateUp to the Router's Builder.\n       *\n       * @return the Builder.\n       * @see Router#getAdminStateUp()\n       */\n      public ParameterizedBuilderType adminStateUp(Boolean adminStateUp) {\n         router.adminStateUp = adminStateUp;\n         return self();\n      }\n\n      /**\n       * Provide the externalGatewayInfo to the Router's Builder.\n       *\n       * @return the Builder.\n       * @see Router#getExternalGatewayInfo()\n       */\n      public ParameterizedBuilderType externalGatewayInfo(ExternalGatewayInfo externalGatewayInfo) {\n         router.externalGatewayInfo = externalGatewayInfo;\n         return self();\n      }\n   }\n\n   public static class CreateBuilder extends Builder<CreateBuilder> {\n      /**\n       * Supply required properties for creating a Builder\n       */\n      private CreateBuilder() {\n      }\n\n      /**\n       * @return a CreateRouter constructed with this Builder.\n       */\n      public CreateRouter build() {\n         return new CreateRouter(router);\n      }\n\n      protected CreateBuilder self() {\n         return this;\n      }\n   }\n\n   public static class UpdateBuilder extends Builder<UpdateBuilder> {\n      /**\n       * Supply required properties for updating a Builder\n       */\n      private UpdateBuilder() {\n      }\n\n      /**\n       * @return a UpdateRouter constructed with this Builder.\n       */\n      public UpdateRouter build() {\n         return new UpdateRouter(router);\n      }\n\n      protected UpdateBuilder self() {\n         return this;\n      }\n   }\n\n   public static class CreateRouter extends Router{\n      /**\n       * Copy constructor\n       */\n      private CreateRouter(Router router) {\n         super(router);\n      }\n   }\n   public static class UpdateRouter extends Router{\n      /**\n       * Copy constructor\n       */\n      private UpdateRouter(Router router) {\n         super(router);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/RouterInterface.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\n/**\n * A Neutron Router Interface\n *\n * @see <a\n *      href=\"http://docs.openstack.org/api/openstack-network/2.0/content/router_add_interface.html\">api\n *      doc</a>\n */\npublic class RouterInterface {\n\n   @Named(\"subnet_id\")\n   protected final String subnetId;\n   @Named(\"port_id\")\n   protected final String portId;\n\n   @ConstructorProperties({\"subnet_id\", \"port_id\"})\n   protected RouterInterface(String subnetId, String portId) {\n      this.subnetId = subnetId;\n      this.portId = portId;\n   }\n\n   /**\n    * @return the subnetId of the RouterInterface\n    */\n   @Nullable\n   public String getSubnetId() {\n      return subnetId;\n   }\n\n   /**\n    * @return the portId of the RouterInterface\n    */\n   @Nullable\n   public String getPortId() {\n      return portId;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(subnetId, portId);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      RouterInterface that = RouterInterface.class.cast(obj);\n      return Objects.equal(this.subnetId, that.subnetId) && Objects.equal(this.portId, that.portId);\n   }\n\n   protected MoreObjects.ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).add(\"subnetId\", subnetId).add(\"portId\", portId);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   /**\n    * @return the Builder for RouterInterface\n    */\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   /**\n    * Gets a Builder configured as this object.\n    */\n   public Builder toBuilder() {\n      return new Builder().fromRouterInterface(this);\n   }\n\n   public static class Builder {\n      protected String subnetId;\n      protected String portId;\n\n      /**\n       * Provide the subnetId to the RouterInterface's Builder.\n       *\n       * @return the Builder.\n       * @see RouterInterface#getSubnetId()\n       */\n      public Builder subnetId(String subnetId) {\n         this.subnetId = subnetId;\n         return this;\n      }\n\n      /**\n       * Provide the portId to the RouterInterface's Builder.\n       *\n       * @return the Builder.\n       * @see RouterInterface#getPortId()\n       */\n      public Builder portId(String portId) {\n         this.portId = portId;\n         return this;\n      }\n\n      /**\n       * @return a RouterInterface constructed with this Builder.\n       */\n      public RouterInterface build() {\n         return new RouterInterface(subnetId, portId);\n      }\n\n      /**\n       * @return a Builder from another RouterInterface.\n       */\n      public Builder fromRouterInterface(RouterInterface in) {\n         return this.subnetId(in.getSubnetId()).portId(in.getPortId());\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/Routers.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.PaginatedCollection;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * A collection of Routers\n */\npublic class Routers extends PaginatedCollection<Router> {\n   public static final Routers EMPTY = new Routers(ImmutableSet.<Router> of(), ImmutableSet.<Link> of());\n\n   @ConstructorProperties({\"routers\", \"routers_links\"})\n   protected Routers(Iterable<Router> routers, Iterable<Link> routersLinks) {\n      super(routers, routersLinks);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/Rule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\n/**\n * Contains a mapping between a MAC address and an IP address.\n */\npublic class Rule {\n\n   private String id;\n   @Named(\"tenant_id\")\n   private String tenantId;\n   private RuleDirection direction;\n   @Named(\"security_group_id\")\n   private String securityGroupId;\n   private RuleEthertype ethertype;\n   @Named(\"port_range_min\")\n   private Integer portRangeMin;\n   @Named(\"port_range_max\")\n   private Integer portRangeMax;\n   private RuleProtocol protocol;\n   @Named(\"remote_group_id\")\n   private String remoteGroupId;\n   @Named(\"remote_ip_prefix\")\n   private String remoteIpPrefix;\n\n   @ConstructorProperties({\"id\", \"tenant_id\", \"direction\", \"security_group_id\", \"ethertype\", \"port_range_min\",\n         \"port_range_max\", \"protocol\", \"remote_group_id\", \"remote_ip_prefix\"})\n   protected Rule(String id, String tenantId, RuleDirection direction, String securityGroupId,\n         RuleEthertype ethertype, Integer portRangeMin, Integer portRangeMax,\n         RuleProtocol protocol, String remoteGroupId, String remoteIpPrefix) {\n      this.id = id;\n      this.tenantId = tenantId;\n      this.direction = direction;\n      this.securityGroupId = securityGroupId;\n      this.ethertype = ethertype;\n      this.portRangeMin = portRangeMin;\n      this.portRangeMax = portRangeMax;\n      this.protocol = protocol;\n      this.remoteGroupId = remoteGroupId;\n      this.remoteIpPrefix = remoteIpPrefix;\n   }\n\n   private Rule(Rule rule) {\n      this(rule.id,\n            rule.tenantId,\n            rule.direction,\n            rule.securityGroupId,\n            rule.ethertype,\n            rule.portRangeMin,\n            rule.portRangeMax,\n            rule.protocol,\n            rule.remoteGroupId,\n            rule.remoteIpPrefix\n      );\n   }\n\n   private Rule() {}\n\n   /**\n    * @return The identifier for this rule.\n    */\n   @Nullable\n   public String getId() {\n      return id;\n   }\n\n   /**\n    * @return The identifier of the tenant for this rule.\n    */\n   @Nullable\n   public String getTenantId() {\n      return tenantId;\n   }\n\n   /**\n    * @return The direction in which the security group rule is applied.\n    */\n   @Nullable\n   public RuleDirection getDirection() {\n      return direction;\n   }\n\n   /**\n    * @return The security group ID to associate with this security group rule.\n    */\n   @Nullable\n   public String getSecurityGroupId() {\n      return securityGroupId;\n   }\n\n   /**\n    * @return The internet protocol version type of this rule.\n    */\n   @Nullable\n   public RuleEthertype getEthertype() {\n      return ethertype;\n   }\n\n   /**\n    * @return The minimum port number in the range that is matched by the security group rule. If the protocol is TCP\n    * or UDP, this value must be less than or equal to the value of the port_range_max attribute. If the protocol is\n    * ICMP, this value must be an ICMP type.\n    */\n   @Nullable\n   public Integer getPortRangeMin() {\n      return portRangeMin;\n   }\n\n   /**\n    * @return The maximum port number in the range that is matched by the security group rule. The port_range_min\n    * attribute constrains the port_range_max attribute. If the protocol is ICMP, this value must be an ICMP type.\n    */\n   @Nullable\n   public Integer getPortRangeMax() {\n      return portRangeMax;\n   }\n\n   /**\n    * @return The protocol that is matched by the security group rule. Valid values are null, tcp, udp, and icmp.\n    */\n   @Nullable\n   public RuleProtocol getProtocol() {\n      return protocol;\n   }\n\n   /**\n    * @return The remote group ID to be associated with this security group rule.\n    */\n   @Nullable\n   public String getRemoteGroupId() {\n      return remoteGroupId;\n   }\n\n   /**\n    * @return The remote IP prefix to be associated with this security group rule. This attribute matches the specified\n    * IP prefix as the source IP address of the IP packet.\n    */\n   @Nullable\n   public String getRemoteIpPrefix() {\n      return remoteIpPrefix;\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o)\n         return true;\n      if (o == null || getClass() != o.getClass())\n         return false;\n\n      Rule that = (Rule) o;\n\n      return Objects.equal(this.id, that.id) &&\n            Objects.equal(this.tenantId, that.tenantId) &&\n            Objects.equal(this.direction, that.direction) &&\n            Objects.equal(this.securityGroupId, that.securityGroupId) &&\n            Objects.equal(this.ethertype, that.ethertype) &&\n            Objects.equal(this.portRangeMin, that.portRangeMin) &&\n            Objects.equal(this.portRangeMax, that.portRangeMax) &&\n            Objects.equal(this.protocol, that.protocol) &&\n            Objects.equal(this.remoteGroupId, that.remoteGroupId) &&\n            Objects.equal(this.remoteIpPrefix, that.remoteIpPrefix);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, tenantId, direction, securityGroupId, ethertype, portRangeMin,\n            portRangeMax, protocol, remoteGroupId, remoteIpPrefix);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id)\n            .add(\"tenantId\", tenantId)\n            .add(\"direction\", direction)\n            .add(\"securityGroupId\", securityGroupId)\n            .add(\"ethertype\", ethertype)\n            .add(\"portRangeMin\", portRangeMin)\n            .add(\"portRangeMax\", portRangeMax)\n            .add(\"protocol\", protocol)\n            .add(\"remoteGroupId\", remoteGroupId)\n            .add(\"remoteIpPrefix\", remoteIpPrefix)\n            .toString();\n   }\n\n\n   /*\n    * Methods to get the Create and Update builders follow\n    */\n\n   /**\n    * @return the Builder for creating a new SecurityGroupRule\n    */\n   public static CreateBuilder createBuilder(RuleDirection direction, String securityGroupId) {\n      return new CreateBuilder(direction, securityGroupId);\n   }\n\n   public abstract static class Builder<ParameterizedBuilderType> {\n      // Keep track of the builder's state.\n      protected Rule rule;\n\n      private Builder() {\n         rule = new Rule();\n      }\n\n      protected abstract ParameterizedBuilderType self();\n\n      /**\n       * The tenant id for this rule. Usually can only be specified by administrators.\n       *\n       * @return the Builder.\n       * @see Rule#getTenantId()\n       */\n      public ParameterizedBuilderType tenantId(String tenantId) {\n         rule.tenantId = tenantId;\n         return self();\n      }\n\n      /**\n       * The direction in which the security group rule is applied.\n       *\n       * @return the Builder.\n       * @see Rule#getDirection()\n       */\n      public ParameterizedBuilderType direction(RuleDirection direction) {\n         rule.direction = direction;\n         return self();\n      }\n\n      /**\n       * The security group ID to associate with this security group rule.\n       *\n       * @return the Builder.\n       * @see Rule#getSecurityGroupId()\n       */\n      public ParameterizedBuilderType securityGroupId(String securityGroupId) {\n         rule.securityGroupId = securityGroupId;\n         return self();\n      }\n\n      /**\n       * The internet protocol version for this rule.\n       *\n       * @return the Builder.\n       * @see Rule#getEthertype()\n       */\n      public ParameterizedBuilderType ethertype(RuleEthertype ethertype) {\n         rule.ethertype = ethertype;\n         return self();\n      }\n\n      /**\n       * The minimum port number in the range that is matched by the security group rule.\n       *\n       * @return the Builder.\n       * @see Rule#getPortRangeMin()\n       */\n      public ParameterizedBuilderType portRangeMin(Integer portRangeMin) {\n         rule.portRangeMin = portRangeMin;\n         return self();\n      }\n\n      /**\n       * The maximum port number in the range that is matched by the security group rule.\n       *\n       * @return the Builder.\n       * @see Rule#getPortRangeMax()\n       */\n      public ParameterizedBuilderType portRangeMax(Integer portRangeMax) {\n         rule.portRangeMax = portRangeMax;\n         return self();\n      }\n\n      /**\n       * The protocol that is matched by the security group rule. Valid values are null, tcp, udp, and icmp.\n       *\n       * @return the Builder.\n       * @see Rule#getProtocol()\n       */\n      public ParameterizedBuilderType protocol(RuleProtocol protocol) {\n         rule.protocol = protocol;\n         return self();\n      }\n\n      /**\n       * The remote group ID to be associated with this security group rule. You can specify either remote_group_id or\n       * remote_ip_prefix in the request body.\n       *\n       * @return the Builder.\n       * @see Rule#getRemoteGroupId()\n       */\n      public ParameterizedBuilderType remoteGroupId(String remoteGroupId) {\n         rule.remoteGroupId = remoteGroupId;\n         return self();\n      }\n\n      /**\n       * The remote IP prefix to be associated with this security group rule. You can specify either remote_group_id\n       * or remote_ip_prefix in the request body. This attribute matches the specified IP prefix as the source IP\n       * address of the IP packet.\n       *\n       * @return the Builder.\n       * @see Rule#getRemoteIpPrefix()\n       */\n      public ParameterizedBuilderType remoteIpPrefix(String remoteIpPrefix) {\n         rule.remoteIpPrefix = remoteIpPrefix;\n         return self();\n      }\n   }\n\n   /**\n    * This is used to build a CreateBuilder object.\n    */\n   public static class CreateBuilder extends Builder<CreateBuilder> {\n      /**\n       * Supply required properties for creating a Builder\n       */\n      private CreateBuilder(RuleDirection direction, String securityGroupId) {\n         rule.direction = direction;\n         rule.securityGroupId = securityGroupId;\n      }\n\n      /**\n       * @return a CreateRule constructed with this Builder.\n       */\n      public CreateRule build() {\n         return new CreateRule(rule);\n      }\n\n      protected CreateBuilder self() {\n         return this;\n      }\n   }\n\n   /**\n    * Create and Update options - extend the domain class, passed to API update and create calls.\n    * Essentially the same as the domain class. Ensure validation and safe typing.\n    */\n   public static class CreateRule extends Rule {\n      private CreateRule(Rule rule) {\n         super(rule);\n         checkNotNull(this.getDirection(), \"direction should not be null\");\n         checkNotNull(this.getSecurityGroupId(), \"security group id should not be null\");\n         if (this.getPortRangeMax() != null && this.getPortRangeMin() != null) {\n            checkArgument(this.getPortRangeMax() >= this.getPortRangeMin(),\n                  \"port range max should be greater than or equal to port range min\");\n         }\n         checkArgument(this.getRemoteGroupId() == null || this.getRemoteIpPrefix() == null,\n               \"You can specify either remote_group_id or remote_ip_prefix in the request body.\");\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/RuleDirection.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.openstack.neutron.v2.domain;\n\n/**\n * The direction in which the security group rule is applied.\n */\npublic enum RuleDirection {\n   /**\n    * For a compute instance, an ‘ingress’ security group rule matches traffic that is incoming (ingress) for that instance.\n    */\n   INGRESS(\"ingress\"),\n   /**\n    * An ‘egress’ rule is applied to traffic leaving the instance.\n    */\n   EGRESS(\"egress\"),\n   /**\n    * Used by jclouds when the service returns an unknown value other than null.\n    */\n   UNRECOGNIZED(\"unrecognized\");\n\n   private String name;\n\n   private RuleDirection(String name) {\n      this.name = name;\n   }\n\n   public String toString() {\n      return name;\n   }\n\n   /*\n    * This provides GSON enum support in jclouds.\n    * */\n   public static RuleDirection fromValue(String name){\n      if (name != null) {\n         for (RuleDirection value : RuleDirection.values()) {\n            if (name.equalsIgnoreCase(value.name)) {\n               return value;\n            }\n         }\n         return UNRECOGNIZED;\n      }\n      return null;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/RuleEthertype.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.openstack.neutron.v2.domain;\n\n/**\n * The direction in which the security group rule is applied.\n */\npublic enum RuleEthertype {\n   /**\n    * Internet Protocol version 4\n    */\n   IPV4(\"IPv4\"),\n   /**\n    * Internet Protocol version 6\n    */\n   IPV6(\"IPv6\"),\n   /**\n    * Used by jclouds when the service returns an unknown value other than null.\n    */\n   UNRECOGNIZED(\"unrecognized\");\n\n   private String name;\n\n   private RuleEthertype(String name) {\n      this.name = name;\n   }\n\n   public String toString() {\n      return name;\n   }\n\n   /*\n    * This provides GSON enum support in jclouds.\n    * */\n   public static RuleEthertype fromValue(String name){\n      if (name != null) {\n         for (RuleEthertype value : RuleEthertype.values()) {\n            if (name.equalsIgnoreCase(value.name)) {\n               return value;\n            }\n         }\n         return UNRECOGNIZED;\n      }\n      return null;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/RuleProtocol.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.openstack.neutron.v2.domain;\n\n/**\n * The protocol that is matched by the security group rule. Valid values are null, tcp, udp, and icmp.\n */\npublic enum RuleProtocol {\n   /**\n    * Transmission Control Protocol\n    */\n   TCP(\"tcp\"),\n   /**\n    * User Datagram Protocol\n    */\n   UDP(\"udp\"),\n   /**\n    * Internet Control Message Protocol\n    */\n   ICMP(\"icmp\"),\n   /**\n    * Used by jclouds when the service returns an unknown value other than null.\n    */\n   UNRECOGNIZED(\"unrecognized\");\n\n   private String name;\n\n   private RuleProtocol(String name) {\n      this.name = name;\n   }\n\n   public String toString() {\n      return name;\n   }\n\n   /*\n    * This provides GSON enum support in jclouds.\n    * */\n   public static RuleProtocol fromValue(String name){\n      if (name != null) {\n         for (RuleProtocol value : RuleProtocol.values()) {\n            if (name.equalsIgnoreCase(value.name)) {\n               return value;\n            }\n         }\n         return UNRECOGNIZED;\n      }\n      return null;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/Rules.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.PaginatedCollection;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * A collection of Networks\n */\npublic class Rules extends PaginatedCollection<Rule> {\n   public static final Rules EMPTY = new Rules(ImmutableSet.<Rule> of(), ImmutableSet.<Link> of());\n\n   @ConstructorProperties({\"security_group_rules\", \"security_group_rules_links\"})\n   protected Rules(Iterable<Rule> securityGroups, Iterable<Link> securityGroupRulesLinks) {\n      super(securityGroups, securityGroupRulesLinks);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/SecurityGroup.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Contains a mapping between a MAC address and an IP address.\n */\npublic class SecurityGroup {\n\n   private String id;\n   @Named(\"tenant_id\")\n   private String tenantId;\n   private String name;\n   private String description;\n   @Named(\"security_group_rules\")\n   private ImmutableList<Rule> rules;\n\n   @ConstructorProperties({\"id\", \"tenant_id\", \"name\", \"description\", \"security_group_rules\"})\n   protected SecurityGroup(String id, String tenantId, String name, String description,\n         ImmutableList<Rule> rules) {\n      this.id = id;\n      this.tenantId = tenantId;\n      this.name = name;\n      this.description = description;\n      this.rules = rules;\n   }\n\n   private SecurityGroup(SecurityGroup securityGroup) {\n      this(securityGroup.id,\n            securityGroup.tenantId,\n            securityGroup.name,\n            securityGroup.description,\n            securityGroup.rules\n      );\n   }\n\n   private SecurityGroup() {}\n\n   /**\n    * @return The identifier for this Security Group.\n    */\n   @Nullable\n   public String getId() {\n      return id;\n   }\n\n   /**\n    * @return The identifier of the tenant for this Security Group.\n    */\n   @Nullable\n   public String getTenantId() {\n      return tenantId;\n   }\n\n   /**\n    * @return The name of the Security Group.\n    */\n   @Nullable\n   public String getName() {\n      return name;\n   }\n\n   /**\n    * @return The description of the Security Group.\n    */\n   @Nullable\n   public String getDescription() {\n      return description;\n   }\n\n   /**\n    * @return The collection of rules for this Security Group.\n    */\n   public ImmutableList<Rule> getRules() {\n      return rules != null ? rules : ImmutableList.<Rule>of();\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o)\n         return true;\n      if (o == null || getClass() != o.getClass())\n         return false;\n\n      SecurityGroup that = (SecurityGroup) o;\n\n      return Objects.equal(this.id, that.id) &&\n            Objects.equal(this.tenantId, that.tenantId) &&\n            Objects.equal(this.name, that.name) &&\n            Objects.equal(this.description, that.description) &&\n            Objects.equal(this.rules, that.rules);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, tenantId, name, description, rules);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id)\n            .add(\"tenantId\", tenantId)\n            .add(\"name\", name)\n            .add(\"description\", description)\n            .add(\"securityGroupRules\", rules)\n            .toString();\n   }\n\n   /*\n    * Methods to get the Create and Update builders follow\n    */\n\n   /**\n    * @return the Builder for creating a new SecurityGroup\n    */\n   public static CreateBuilder createBuilder() {\n      return new CreateBuilder();\n   }\n\n   private abstract static class Builder<ParameterizedBuilderType> {\n      // Keep track of the builder's state.\n      protected SecurityGroup securityGroup;\n\n      private Builder() {\n         securityGroup = new SecurityGroup();\n      }\n\n      protected abstract ParameterizedBuilderType self();\n\n      /**\n       * The tenant id for this Security Group. Usually can only be specified by administrators.\n       *\n       * @return the Builder.\n       * @see SecurityGroup#getTenantId()\n       */\n      public ParameterizedBuilderType tenantId(String tenantId) {\n         securityGroup.tenantId = tenantId;\n         return self();\n      }\n\n      /**\n       * The name for this Security Group.\n       *\n       * @return the Builder.\n       * @see SecurityGroup#getName()\n       */\n      public ParameterizedBuilderType name(String name) {\n         securityGroup.name = name;\n         return self();\n      }\n\n      /**\n       * The description for this Security Group.\n       *\n       * @return the Builder.\n       * @see SecurityGroup#getDescription()\n       */\n      public ParameterizedBuilderType description(String description) {\n         securityGroup.description = description;\n         return self();\n      }\n   }\n\n   /**\n    * Create and Update builders (inheriting from Builder)\n    */\n   public static class CreateBuilder extends Builder<CreateBuilder> {\n      /**\n       * Supply required properties for creating a Builder\n       */\n      private CreateBuilder() {\n      }\n\n      /**\n       * @return a CreateSecurityGroup constructed with this Builder.\n       */\n      public CreateSecurityGroup build() {\n         return new CreateSecurityGroup(securityGroup);\n      }\n\n      protected CreateBuilder self() {\n         return this;\n      }\n   }\n\n   /**\n    * Create and Update options - extend the domain class, passed to API update and create calls.\n    * Essentially the same as the domain class. Ensure validation and safe typing.\n    */\n   public static class CreateSecurityGroup extends SecurityGroup {\n      private CreateSecurityGroup(SecurityGroup securityGroup) {\n         super(securityGroup);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/SecurityGroups.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.PaginatedCollection;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * A collection of Networks\n */\npublic class SecurityGroups extends PaginatedCollection<SecurityGroup> {\n   public static final SecurityGroups EMPTY = new SecurityGroups(ImmutableSet.<SecurityGroup> of(), ImmutableSet.<Link> of());\n\n   @ConstructorProperties({\"security_groups\", \"security_groups_links\"})\n   protected SecurityGroups(Iterable<SecurityGroup> securityGroups, Iterable<Link> securityGroupsLinks) {\n      super(securityGroups, securityGroupsLinks);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/Subnet.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Collection;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * A Neutron subnet\n *\n * @see <a href=\"http://docs.openstack.org/api/openstack-network/2.0/content/Subnets.html\">api doc</a>\n */\npublic class Subnet {\n\n   private String id;\n\n   private String name;\n   @Named(\"network_id\")\n   private String networkId;\n   @Named(\"tenant_id\")\n   private String tenantId;\n   // Cannot be used for updates.\n   @Named(\"allocation_pools\")\n   private ImmutableSet<AllocationPool> allocationPools;\n   @Named(\"gateway_ip\")\n   private String gatewayIp;\n   @Named(\"ip_version\")\n   private Integer ipVersion;\n   private String cidr;\n   @Named(\"enable_dhcp\")\n   private Boolean enableDhcp;\n   @Named(\"dns_nameservers\")\n   private ImmutableSet<String> dnsNameServers;\n   @Named(\"host_routes\")\n   private ImmutableSet<HostRoute> hostRoutes;\n   @Named(\"ipv6_address_mode\")\n   private IPv6DHCPMode ipv6AddressMode;\n   @Named(\"ipv6_ra_mode\")\n   private IPv6DHCPMode ipv6RaMode;\n\n   @ConstructorProperties({\"id\", \"name\", \"network_id\", \"tenant_id\", \"allocation_pools\", \"gateway_ip\", \"ip_version\",\n         \"cidr\", \"enable_dhcp\", \"dns_nameservers\", \"host_routes\", \"ipv6_address_mode\", \"ipv6_ra_mode\"})\n   private Subnet(String id, String name, String networkId, String tenantId, ImmutableSet<AllocationPool> allocationPools,\n         String gatewayIp, Integer ipVersion, String cidr, Boolean enableDhcp, ImmutableSet<String> dnsNameServers, ImmutableSet<HostRoute> hostRoutes,\n         IPv6DHCPMode ipv6AddressMode, IPv6DHCPMode ipv6RaMode) {\n      this.id = id;\n      this.name = name;\n      this.networkId = networkId;\n      this.tenantId = tenantId;\n      this.allocationPools = allocationPools;\n      this.gatewayIp = gatewayIp;\n      this.ipVersion = ipVersion;\n      this.cidr = cidr;\n      this.enableDhcp = enableDhcp;\n      this.dnsNameServers = dnsNameServers;\n      this.hostRoutes = hostRoutes;\n      this.ipv6AddressMode = ipv6AddressMode;\n      this.ipv6RaMode = ipv6RaMode;\n   }\n\n   /**\n    * Default constructor.\n    */\n   private Subnet() {}\n\n   /**\n    * Copy constructor\n    * @param subnet\n    */\n   private Subnet(Subnet subnet) {\n      this(subnet.id,\n            subnet.name,\n            subnet.networkId,\n            subnet.tenantId,\n            subnet.allocationPools,\n            subnet.gatewayIp,\n            subnet.ipVersion,\n            subnet.cidr,\n            subnet.enableDhcp,\n            subnet.dnsNameServers,\n            subnet.hostRoutes,\n            subnet.ipv6AddressMode,\n            subnet.ipv6RaMode);\n   }\n\n   /**\n    * @return the id of the subnet\n    */\n   @Nullable\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * @return the name of the subnet\n    */\n   @Nullable\n   public String getName() {\n      return this.name;\n   }\n\n   /**\n    * @return the id of the network this subnet is associated with.\n    */\n   @Nullable\n   public String getNetworkId() {\n      return networkId;\n   }\n\n   /**\n    * @return the id of the tenant where this entity is associated with.\n    */\n   @Nullable\n   public String getTenantId() {\n      return tenantId;\n   }\n\n   /**\n    * @return the sub-ranges of CIDR available for dynamic allocation to ports.\n    */\n   @Nullable\n   public ImmutableSet<AllocationPool> getAllocationPools() {\n      return allocationPools;\n   }\n\n   /**\n    * @return the default gateway used by devices in this subnet.\n    */\n   @Nullable\n   public String getGatewayIp() {\n      return gatewayIp;\n   }\n\n   /**\n    * @return the IP version used by this subnet.\n    */\n   @Nullable\n   public Integer getIpVersion() {\n      return ipVersion;\n   }\n\n   /**\n    * @return the CIDR representing the IP range for this subnet, based on IP version.\n    */\n   @Nullable\n   public String getCidr() {\n      return cidr;\n   }\n\n   /**\n    * @return true if DHCP is enabled for this subnet, false if not.\n    */\n   @Nullable\n   public Boolean getEnableDhcp() {\n      return enableDhcp;\n   }\n\n   /**\n    * @return Configurable maximum amount of name servers per subnet. The default is 5.\n    */\n   @Nullable\n   public ImmutableSet<String> getDnsNameservers() {\n      return dnsNameServers;\n   }\n\n   /**\n    * @return Configurable maximum amount of routes per subnet. The default is 20.\n    */\n   @Nullable\n   public ImmutableSet<HostRoute> getHostRoutes() {\n      return hostRoutes;\n   }\n\n   /**\n    * @return The IP v6 Address Mode.\n    */\n   @Nullable\n   public IPv6DHCPMode getIPv6AddressMode() {\n      return ipv6AddressMode;\n   }\n\n   /**\n    * @return The IP v6 Router Advertisement mode.\n    */\n   @Nullable\n   public IPv6DHCPMode getIPv6RAMode() {\n      return ipv6RaMode;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, name, networkId, tenantId, allocationPools, gatewayIp,\n            ipVersion, cidr, enableDhcp, dnsNameServers, hostRoutes,\n            ipv6AddressMode, ipv6RaMode);\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o)\n         return true;\n      if (o == null || getClass() != o.getClass())\n         return false;\n\n      Subnet that = (Subnet) o;\n\n      return Objects.equal(this.id, that.id) &&\n            Objects.equal(this.name, that.name) &&\n            Objects.equal(this.networkId, that.networkId) &&\n            Objects.equal(this.tenantId, that.tenantId) &&\n            Objects.equal(this.allocationPools, that.allocationPools) &&\n            Objects.equal(this.gatewayIp, that.gatewayIp) &&\n            Objects.equal(this.ipVersion, that.ipVersion) &&\n            Objects.equal(this.cidr, that.cidr) &&\n            Objects.equal(this.enableDhcp, that.enableDhcp) &&\n            Objects.equal(this.dnsNameServers, that.dnsNameServers) &&\n            Objects.equal(this.hostRoutes, that.hostRoutes) &&\n            Objects.equal(this.ipv6AddressMode, that.ipv6AddressMode) &&\n            Objects.equal(this.ipv6RaMode, that.ipv6RaMode);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id)\n            .add(\"name\", name)\n            .add(\"networkId\", networkId)\n            .add(\"tenantId\", tenantId)\n            .add(\"allocationPools\", allocationPools)\n            .add(\"gatewayIp\", gatewayIp)\n            .add(\"ipVersion\", ipVersion)\n            .add(\"cidr\", cidr)\n            .add(\"enableDhcp\", enableDhcp)\n            .add(\"dnsNameServers\", dnsNameServers)\n            .add(\"hostRoutes\", hostRoutes)\n            .add(\"ipv6AddressMode\", ipv6AddressMode)\n            .add(\"ipv6RaMode\", ipv6RaMode)\n            .toString();\n   }\n\n   /*\n    * Methods to get the Create and Update builders follow\n    */\n\n   /**\n    * @return the Builder for creating a new Router\n    */\n   public static CreateBuilder createBuilder(String networkId, String cidr) {\n      return new CreateBuilder(networkId, cidr);\n   }\n\n   /**\n    * @return the Builder for updating a Router\n    */\n   public static UpdateBuilder updateBuilder() {\n      return new UpdateBuilder();\n   }\n\n   private abstract static class Builder<ParameterizedBuilderType> {\n      protected Subnet subnet;\n\n      /**\n       * No-parameters constructor used when updating.\n       */\n      private Builder() {\n         subnet = new Subnet();\n      }\n\n      protected abstract ParameterizedBuilderType self();\n\n      /**\n       * @see Subnet#getName()\n       */\n      public ParameterizedBuilderType name(String name) {\n         subnet.name = name;\n         return self();\n      }\n\n      /**\n       * @see Subnet#getNetworkId()\n       */\n      public ParameterizedBuilderType networkId(String networkId) {\n         subnet.networkId = networkId;\n         return self();\n      }\n\n      /**\n       * Only administrators can specify a tenant ID that is not their own.\n       * As it is optional, this is usually omitted in requests.\n       * @see Subnet#getTenantId()\n       */\n      public ParameterizedBuilderType tenantId(String tenantId) {\n         subnet.tenantId = tenantId;\n         return self();\n      }\n\n      /**\n       * @see Subnet#getAllocationPools()\n       */\n      public ParameterizedBuilderType allocationPools(Collection<AllocationPool> allocationPools) {\n         subnet.allocationPools = ImmutableSet.copyOf(allocationPools);\n         return self();\n      }\n\n      /**\n       * @see Subnet#getGatewayIp()\n       */\n      public ParameterizedBuilderType gatewayIp(String gatewayIp) {\n         subnet.gatewayIp = gatewayIp;\n         return self();\n      }\n\n      /**\n       * @see Subnet#getIpVersion()\n       */\n      public ParameterizedBuilderType ipVersion(int ipVersion) {\n         subnet.ipVersion = ipVersion;\n         return self();\n      }\n\n      /**\n       * @see Subnet#getCidr()\n       */\n      public ParameterizedBuilderType cidr(String cidr) {\n         subnet.cidr = cidr;\n         return self();\n      }\n\n      /**\n       * @see Subnet#getEnableDhcp()\n       */\n      public ParameterizedBuilderType enableDhcp(Boolean enableDhcp) {\n         subnet.enableDhcp = enableDhcp;\n         return self();\n      }\n\n      /**\n       * @see Subnet#getDnsNameservers()\n       */\n      public ParameterizedBuilderType dnsNameServers(ImmutableSet<String> dnsNameServers) {\n         subnet.dnsNameServers = dnsNameServers;\n         return self();\n      }\n\n      /**\n       * @see Subnet#getHostRoutes()\n       */\n      public ParameterizedBuilderType hostRoutes(ImmutableSet<HostRoute> hostRoutes) {\n         subnet.hostRoutes = hostRoutes;\n         return self();\n      }\n\n      /**\n       * @see Subnet#getIPv6RAMode()\n       */\n      public ParameterizedBuilderType ipv6RaMode(IPv6DHCPMode ipv6RaMode) {\n         subnet.ipv6RaMode = ipv6RaMode;\n         return self();\n      }\n\n      /**\n       * @see Subnet#getIPv6AddressMode()\n       */\n      public ParameterizedBuilderType ipv6AddressMode(IPv6DHCPMode ipv6AddressMode) {\n         subnet.ipv6AddressMode = ipv6AddressMode;\n         return self();\n      }\n   }\n\n   /**\n    * Create and Update builders (inheriting from Builder)\n    */\n   public static class CreateBuilder extends Builder<CreateBuilder> {\n      /**\n       *\n       * Supply required properties for creating a Builder\n       */\n      private CreateBuilder(String networkId, String cidr) {\n         subnet.networkId = networkId;\n         subnet.cidr = cidr;\n      }\n\n      /**\n       * @return a CreateSubnet constructed with this Builder.\n       */\n      public CreateSubnet build() {\n         return new CreateSubnet(subnet);\n      }\n\n      protected CreateBuilder self() {\n         return this;\n      }\n   }\n\n   /**\n    * Create and Update builders (inheriting from Builder)\n    */\n   public static class UpdateBuilder extends Builder<UpdateBuilder> {\n      /**\n       * Supply required properties for updating a Builder\n       */\n      private UpdateBuilder() {\n      }\n\n      /**\n       * @return a UpdateSubnet constructed with this Builder.\n       */\n      public UpdateSubnet build() {\n         return new UpdateSubnet(subnet);\n      }\n\n      protected UpdateBuilder self() {\n         return this;\n      }\n   }\n\n   /**\n    * Create and Update options - extend the domain class, passed to API update and create calls.\n    * Essentially the same as the domain class. Ensure validation and safe typing.\n    */\n   public static class CreateSubnet extends Subnet {\n      /**\n       * Copy constructor\n       */\n      private CreateSubnet(Subnet subnet) {\n         super(subnet);\n         checkNotNull(subnet.networkId, \"networkId should not be null\");\n         checkNotNull(subnet.cidr, \"cidr should not be null\");\n      }\n   }\n\n   /**\n    * Create and Update options - extend the domain class, passed to API update and create calls.\n    * Essentially the same as the domain class. Ensure validation and safe typing.\n    */\n   public static class UpdateSubnet extends Subnet {\n      /**\n       * Copy constructor\n       */\n      private UpdateSubnet(Subnet subnet) {\n         super(subnet);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/Subnets.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.PaginatedCollection;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * A collection of Subnets\n */\npublic class Subnets extends PaginatedCollection<Subnet> {\n   public static final Subnets EMPTY = new Subnets(ImmutableSet.<Subnet> of(), ImmutableSet.<Link> of());\n\n   @ConstructorProperties({\"subnets\", \"subnets_links\"})\n   protected Subnets(Iterable<Subnet> subnets, Iterable<Link> subnetsLinks) {\n      super(subnets, subnetsLinks);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/UpdateFirewall.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n\n/**\n * Representation of update options for an OpenStack Neutron Firewall.\n *\n * @see <a\n * href=\"http://docs.openstack.org/admin-guide-cloud/content/fwaas_api_abstractions.html\">api\n * doc</a>\n */\n@AutoValue\npublic abstract class UpdateFirewall {\n\n   @Nullable public abstract String getTenantId();\n   @Nullable public abstract String getName();\n   @Nullable public abstract String getDescription();\n   @Nullable public abstract Boolean getAdminStateUp();\n   @Nullable public abstract String getFirewallPolicyId();\n\n   @SerializedNames({\"tenant_id\", \"name\", \"description\", \"admin_state_up\", \"firewall_policy_id\"})\n   public static UpdateFirewall create(String tenantId, String name, String description, Boolean adminStateUp, String firewallPolicyId) {\n      return builder().tenantId(tenantId).name(name).description(description).adminStateUp(adminStateUp).firewallPolicyId(firewallPolicyId).build();\n   }\n\n   public static Builder builder() {\n      return new AutoValue_UpdateFirewall.Builder();\n   }\n\n   public abstract Builder toBuilder();\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder tenantId(String tenantId);\n      public abstract Builder name(String name);\n      public abstract Builder description(String description);\n      public abstract Builder adminStateUp(Boolean adminStateUp);\n      public abstract Builder firewallPolicyId(String firewallPolicyId);\n\n      @Nullable public abstract String getTenantId();\n      @Nullable public abstract String getName();\n      @Nullable public abstract String getDescription();\n      @Nullable public abstract Boolean getAdminStateUp();\n      @Nullable public abstract String getFirewallPolicyId();\n\n      public abstract UpdateFirewall build();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/UpdateFirewallPolicy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain;\n\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Representation of update options for an OpenStack Neutron Firewall Policy.\n *\n * @see <a\n *      href=\"http://docs.openstack.org/admin-guide-cloud/content/fwaas_api_abstractions.html\">api\n *      doc</a>\n */\n@AutoValue\npublic abstract class UpdateFirewallPolicy {\n\n   @Nullable public abstract String getTenantId();\n   @Nullable public abstract String getName();\n   @Nullable public abstract String getDescription();\n   @Nullable public abstract Boolean getShared();\n   @Nullable public abstract List<String> getFirewallRules();\n   @Nullable public abstract Boolean getAudited();\n\n   @SerializedNames({\"tenant_id\", \"name\", \"description\", \"shared\", \"firewall_rules\", \"audited\"})\n   private static UpdateFirewallPolicy create(String tenantId, String name, String description, Boolean shared, List<String> firewallRules, Boolean audited) {\n      return builder().tenantId(tenantId).name(name).description(description).shared(shared).firewallRules(firewallRules).audited(audited).build();\n   }\n\n   public static Builder builder() {\n      return new AutoValue_UpdateFirewallPolicy.Builder().shared(false).audited(false);\n   }\n\n   public abstract Builder toBuilder();\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder tenantId(String tenantId);\n      public abstract Builder name(String name);\n      public abstract Builder description(String description);\n      public abstract Builder shared(Boolean shared);\n      public abstract Builder firewallRules(List<String> firewallRules);\n      public abstract Builder audited(Boolean audited);\n\n      abstract UpdateFirewallPolicy autoBuild();\n\n      @Nullable public abstract String getTenantId();\n      @Nullable public abstract String getName();\n      @Nullable public abstract String getDescription();\n      @Nullable public abstract Boolean getShared();\n      @Nullable public abstract List<String> getFirewallRules();\n      @Nullable public abstract Boolean getAudited();\n\n      public UpdateFirewallPolicy build() {\n         firewallRules(getFirewallRules() != null ? ImmutableList.copyOf(getFirewallRules()) : ImmutableList.<String>of());\n         return autoBuild();\n      }\n\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/UpdateFirewallRule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n/**\n * Representation of update options for an OpenStack Neutron Firewall Rule.\n *\n * @see <a\n *      href=\"http://docs.openstack.org/admin-guide-cloud/content/fwaas_api_abstractions.html\">api\n *      doc</a>\n */\n@AutoValue\npublic abstract class UpdateFirewallRule {\n\n   @Nullable public abstract String getTenantId();\n   @Nullable public abstract String getName();\n   @Nullable public abstract String getDescription();\n   @Nullable public abstract String getFirewallPolicyId();\n   @Nullable public abstract Boolean getShared();\n   @Nullable public abstract String getProtocol();\n   @Nullable public abstract IpVersion getIpVersion();\n   @Nullable public abstract String getSourceIpAddress();\n   @Nullable public abstract String getDestinationIpAddress();\n   @Nullable public abstract String getSourcePort();\n   @Nullable public abstract String getDestinationPort();\n   @Nullable public abstract Integer getPosition();\n   @Nullable public abstract String getAction();\n   @Nullable public abstract Boolean getEnabled();\n\n   @SerializedNames({ \"tenant_id\", \"name\", \"description\", \"firewall_policy_id\", \"shared\", \"protocol\", \"ip_version\", \"source_ip_address\",\n           \"destination_ip_address\", \"source_port\", \"destination_port\", \"position\", \"action\", \"enabled\"})\n   public static UpdateFirewallRule create(String tenantId, String name, String description, String firewallPolicyId, Boolean shared, String protocol,\n                                           IpVersion ipVersion, String sourceIpAddress, String destinationIpAddress, String sourcePort, String destinationPort, int position,\n                                           String action, Boolean enabled) {\n      return builder().tenantId(tenantId).name(name).description(description).firewallPolicyId(firewallPolicyId).shared(shared)\n              .protocol(protocol).ipVersion(ipVersion).sourceIpAddress(sourceIpAddress).destinationIpAddress(destinationIpAddress).sourcePort(sourcePort)\n              .destinationPort(destinationPort).position(position).action(action).enabled(enabled).build();\n   }\n\n   public static Builder builder() {\n      return new AutoValue_UpdateFirewallRule.Builder().shared(false).enabled(false).position(null);\n   }\n\n   public abstract Builder toBuilder();\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder tenantId(String tenantId);\n      public abstract Builder name(String name);\n      public abstract Builder description(String description);\n      public abstract Builder firewallPolicyId(String firewallPolicyId);\n      public abstract Builder shared(Boolean shared);\n      public abstract Builder protocol(String protocol);\n      public abstract Builder ipVersion(IpVersion ipVersion);\n      public abstract Builder sourceIpAddress(String sourceIpAddress);\n      public abstract Builder destinationIpAddress(String destinationIpAddress);\n      public abstract Builder sourcePort(String sourcePort);\n      public abstract Builder destinationPort(String destinationPort);\n      public abstract Builder position(Integer position);\n      public abstract Builder action(String action);\n      public abstract Builder enabled(Boolean enabled);\n\n      @Nullable public abstract String getTenantId();\n      @Nullable public abstract String getName();\n      @Nullable public abstract String getDescription();\n      @Nullable public abstract String getFirewallPolicyId();\n      @Nullable public abstract Boolean getShared();\n      @Nullable public abstract String getProtocol();\n      @Nullable public abstract IpVersion getIpVersion();\n      @Nullable public abstract String getSourceIpAddress();\n      @Nullable public abstract String getDestinationIpAddress();\n      @Nullable public abstract String getSourcePort();\n      @Nullable public abstract String getDestinationPort();\n      @Nullable public abstract Integer getPosition();\n      @Nullable public abstract String getAction();\n      @Nullable public abstract Boolean getEnabled();\n\n      public abstract UpdateFirewallRule build();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/VIFType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.openstack.neutron.v2.domain;\n\npublic enum VIFType {\n   UNBOUND(\"unbound\"),\n   BINDING_FAILED(\"binding_failed\"),\n   IOVISOR(\"iovisor\"),\n   OVS(\"ovs\"),\n   BRIDGE(\"bridge\"),\n   _802_QBG(\"802.1qbg\"),\n   _802_QBH(\"802.1qbh\"),\n   HYPERV(\"hyperv\"),\n   MIDONET(\"midonet\"),\n   MLNX_DIRECT(\"mlnx_direct\"),\n   MLNX_HOSTDEV(\"hostdev\"),\n   OTHER(\"other\"),\n   /**\n    * Used by jclouds when the service returns an unknown value other than null.\n    */\n   UNRECOGNIZED(\"unrecognized\");\n\n   private String name;\n\n   private VIFType(String name) {\n      this.name = name;\n   }\n\n   public String toString() {\n      return name;\n   }\n\n   /*\n    * This provides GSON enum support in jclouds.\n    * */\n   public static VIFType fromValue(String name){\n      if (name != null) {\n         for (VIFType value : VIFType.values()) {\n            if (name.equalsIgnoreCase(value.name)) {\n               return value;\n            }\n         }\n         return UNRECOGNIZED;\n      }\n      return null;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/VNICType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.openstack.neutron.v2.domain;\n\n/**\n * Enumerates supported VNIC types.\n */\npublic enum VNICType {\n   NORMAL(\"normal\"),\n   DIRECT(\"direct\"),\n   MACVTAP(\"macvtap\"),\n   /**\n    * Used by jclouds when the service returns an unknown value other than null.\n    */\n   UNRECOGNIZED(\"unrecognized\");\n\n   private String name;\n\n   private VNICType(String name) {\n      this.name = name;\n   }\n\n   public String toString() {\n      return name;\n   }\n\n   /*\n    * This provides GSON enum support in jclouds.\n    * */\n   public static VNICType fromValue(String name){\n      if (name != null) {\n         for (VNICType value : VNICType.values()) {\n            if (name.equalsIgnoreCase(value.name)) {\n               return value;\n            }\n         }\n         return UNRECOGNIZED;\n      }\n      return null;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/lbaas/v1/HealthMonitor.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain.lbaas.v1;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ImmutableList;\n\n/**\n * A Neutron LBaaS v1 HealthMonitor.\n */\npublic class HealthMonitor {\n\n   // Mandatory attributes when creating\n   @Named(\"tenant_id\")\n   private String tenantId;\n   private ProbeType type;\n   // Mandatory attributes that can be updated\n   private Integer delay;\n   private Integer timeout;\n   @Named(\"max_retries\")\n   private Integer maxRetries;\n   // Optional attributes that can be updated\n   @Named(\"http_method\")\n   private HttpMethod httpMethod;\n   @Named(\"url_path\")\n   private String urlPath;\n   @Named(\"expected_codes\")\n   private String expectedCodes;\n   @Named(\"admin_state_up\")\n   private Boolean adminStateUp;\n   // Read-only attributes\n   private String id;\n   private ImmutableList<PoolStatus> pools;\n   private LBaaSStatus status;\n   @Named(\"status_description\")\n   private String statusDescription;\n\n   /**\n    * Deserialization constructor\n    */\n   @ConstructorProperties({ \"id\", \"tenant_id\", \"type\", \"delay\", \"timeout\", \"max_retries\", \"http_method\", \"url_path\",\n         \"expected_codes\", \"pools\", \"admin_state_up\", \"status\", \"status_description\" })\n   private HealthMonitor(String id, String tenantId, ProbeType type, Integer delay, Integer timeout,\n         Integer maxRetries, HttpMethod httpMethod, String urlPath, String expectedCodes,\n         ImmutableList<PoolStatus> pools, Boolean adminStateUp, LBaaSStatus status, String statusDescription) {\n      this.id = id;\n      this.tenantId = tenantId;\n      this.type = type;\n      this.delay = delay;\n      this.timeout = timeout;\n      this.maxRetries = maxRetries;\n      this.httpMethod = httpMethod;\n      this.urlPath = urlPath;\n      this.expectedCodes = expectedCodes;\n      this.pools = pools;\n      this.adminStateUp = adminStateUp;\n      this.status = status;\n      this.statusDescription = statusDescription;\n   }\n\n   /**\n    * Default constructor.\n    */\n   private HealthMonitor() {\n   }\n\n   /**\n    * Copy constructor.\n    *\n    * @param healthMonitor the HealthMonitor to copy from.\n    */\n   private HealthMonitor(HealthMonitor healthMonitor) {\n      this(healthMonitor.id, healthMonitor.tenantId, healthMonitor.type, healthMonitor.delay, healthMonitor.timeout,\n            healthMonitor.maxRetries, healthMonitor.httpMethod, healthMonitor.urlPath, healthMonitor.expectedCodes,\n            healthMonitor.pools, healthMonitor.adminStateUp, healthMonitor.status, healthMonitor.statusDescription);\n   }\n\n   /**\n    * @return the id of the HealthMonitor.\n    */\n   @Nullable\n   public String getId() {\n      return id;\n   }\n\n   /**\n    * @return the tenant id of the HealthMonitor.\n    */\n   @Nullable\n   public String getTenantId() {\n      return tenantId;\n   }\n\n   /**\n    * @return the probe type for this HealthMonitor.\n    */\n   @Nullable\n   public ProbeType getType() {\n      return type;\n   }\n\n   /**\n    * @return the delay for this HealthMonitor.\n    */\n   @Nullable\n   public Integer getDelay() {\n      return delay;\n   }\n\n   /**\n    * @return the timeout for this HealthMonitor.\n    */\n   @Nullable\n   public Integer getTimeout() {\n      return timeout;\n   }\n\n   /**\n    * @return the max retries for this HealthMonitor.\n    */\n   @Nullable\n   public Integer getMaxRetries() {\n      return maxRetries;\n   }\n\n   /**\n    * @return the HTTP method for this HealthMonitor.\n    */\n   @Nullable\n   public HttpMethod getHttpMethod() {\n      return httpMethod;\n   }\n\n   /**\n    * @return the URL path for this HealthMonitor.\n    */\n   @Nullable\n   public String getUrlPath() {\n      return urlPath;\n   }\n\n   /**\n    * @return the expected codes for this HealthMonitor.\n    */\n   @Nullable\n   public String getExpectedCodes() {\n      return expectedCodes;\n   }\n\n   /**\n    * @return the pools for this HealthMonitor.\n    */\n   @Nullable\n   public ImmutableList<PoolStatus> getPools() {\n      return pools;\n   }\n\n   /**\n    * @return the administrative state for this HealthMonitor.\n    */\n   @Nullable\n   public Boolean getAdminStateUp() {\n      return adminStateUp;\n   }\n\n   /**\n    * @return the status for this HealthMonitor.\n    */\n   @Nullable\n   public LBaaSStatus getStatus() {\n      return status;\n   }\n\n   /**\n    * @return the status description for this HealthMonitor.\n    */\n   @Nullable\n   public String getStatusDescription() {\n      return statusDescription;\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o)\n         return true;\n      if (o == null || getClass() != o.getClass())\n         return false;\n\n      HealthMonitor that = (HealthMonitor) o;\n\n      return Objects.equal(this.id, that.id) && Objects.equal(this.tenantId, that.tenantId)\n            && Objects.equal(this.type, that.type) && Objects.equal(this.delay, that.delay)\n            && Objects.equal(this.timeout, that.timeout) && Objects.equal(this.maxRetries, that.maxRetries)\n            && Objects.equal(this.httpMethod, that.httpMethod) && Objects.equal(this.urlPath, that.urlPath)\n            && Objects.equal(this.expectedCodes, that.expectedCodes) && Objects.equal(this.pools, that.pools)\n            && Objects.equal(this.adminStateUp, that.adminStateUp) && Objects.equal(this.status, that.status)\n            && Objects.equal(this.statusDescription, that.statusDescription);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, tenantId, type, delay, timeout, maxRetries, httpMethod, urlPath, expectedCodes,\n            pools, adminStateUp, status, statusDescription);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).add(\"id\", id).add(\"tenantId\", tenantId).add(\"type\", type)\n            .add(\"delay\", delay).add(\"timeout\", timeout).add(\"maxRetries\", maxRetries).add(\"httpMethod\", httpMethod)\n            .add(\"urlPath\", urlPath).add(\"expectedCodes\", expectedCodes).add(\"pools\", pools)\n            .add(\"adminStateUp\", adminStateUp).add(\"status\", status).add(\"statusDescription\", statusDescription)\n            .toString();\n   }\n\n   /*\n    * Methods to get the Create and Update builders follow.\n    */\n\n   /**\n    * @return the Builder for creating a new HealthMonitor.\n    */\n   public static CreateBuilder createBuilder(ProbeType type, Integer delay, Integer timeout, Integer maxRetries) {\n      return new CreateBuilder(type, delay, timeout, maxRetries);\n   }\n\n   /**\n    * @return the Builder for updating a HealthMonitor.\n    */\n   public static UpdateBuilder updateBuilder() {\n      return new UpdateBuilder();\n   }\n\n   private abstract static class Builder<ParameterizedBuilderType> {\n      protected HealthMonitor healthMonitor;\n\n      /**\n       * Default constructor.\n       */\n      private Builder() {\n         healthMonitor = new HealthMonitor();\n      }\n\n      protected abstract ParameterizedBuilderType self();\n\n      /**\n       * Provides the delay for this HealthMonitor's Builder.\n       *\n       * @return the Builder.\n       * @see HealthMonitor#getDelay()\n       */\n      public ParameterizedBuilderType delay(Integer delay) {\n         healthMonitor.delay = delay;\n         return self();\n      }\n\n      /**\n       * Provides the timeout for this HealthMonitor's Builder.\n       *\n       * @return the Builder.\n       * @see HealthMonitor#getTimeout()\n       */\n      public ParameterizedBuilderType timeout(Integer timeout) {\n         healthMonitor.timeout = timeout;\n         return self();\n      }\n\n      /**\n       * Provides the max retries for this HealthMonitor's Builder.\n       *\n       * @return the Builder.\n       * @see HealthMonitor#getMaxRetries()\n       */\n      public ParameterizedBuilderType maxRetries(Integer maxRetries) {\n         healthMonitor.maxRetries = maxRetries;\n         return self();\n      }\n\n      /**\n       * Provides the HTTP method for this HealthMonitor's Builder.\n       *\n       * @return the Builder.\n       * @see HealthMonitor#getHttpMethod()\n       */\n      public ParameterizedBuilderType httpMethod(HttpMethod httpMethod) {\n         healthMonitor.httpMethod = httpMethod;\n         return self();\n      }\n\n      /**\n       * Provides the URL path for this HealthMonitor's Builder.\n       *\n       * @return the Builder.\n       * @see HealthMonitor#getUrlPath()\n       */\n      public ParameterizedBuilderType urlPath(String urlPath) {\n         healthMonitor.urlPath = urlPath;\n         return self();\n      }\n\n      /**\n       * Provides the expected codes for this HealthMonitor's Builder.\n       *\n       * @return the Builder.\n       * @see HealthMonitor#getExpectedCodes()\n       */\n      public ParameterizedBuilderType expectedCodes(String expectedCodes) {\n         healthMonitor.expectedCodes = expectedCodes;\n         return self();\n      }\n\n      /**\n       * Provides the administrative state for this HealthMonitor's Builder.\n       *\n       * @return the Builder.\n       * @see HealthMonitor#getAdminStateUp()\n       */\n      public ParameterizedBuilderType adminStateUp(Boolean adminStateUp) {\n         healthMonitor.adminStateUp = adminStateUp;\n         return self();\n      }\n   }\n\n   /**\n    * Create builder (inheriting from Builder).\n    */\n   public static class CreateBuilder extends Builder<CreateBuilder> {\n      /**\n       * Supply required properties for creating a HealthMonitor's CreateBuilder.\n       *\n       * @param type the probe type.\n       * @param delay the delay.\n       * @param timeout the timeout.\n       * @param maxRetries the max retries.\n       */\n      private CreateBuilder(ProbeType type, Integer delay, Integer timeout, Integer maxRetries) {\n         type(type).delay(delay).timeout(timeout).maxRetries(maxRetries);\n      }\n\n      /**\n       * Provides the tenantId for this HealthMonitor's CreateBuilder. Admin-only.\n       * When keystone is enabled, it is not mandatory to specify tenant_id for resources in create requests, as the\n       * tenant identifier will be derived from the Authentication token. Please note that the default authorization\n       * settings only allow administrative users to create resources on behalf of a different tenant.\n       *\n       * @return the Builder.\n       * @see HealthMonitor#getTenantId()\n       */\n      public CreateBuilder tenantId(String tenantId) {\n         healthMonitor.tenantId = tenantId;\n         return self();\n      }\n\n      /**\n       * Provides the probe type for this HealthMonitor's Builder.\n       *\n       * @return the Builder.\n       * @see HealthMonitor#getType()\n       */\n      public CreateBuilder type(ProbeType type) {\n         healthMonitor.type = type;\n         return self();\n      }\n\n      /**\n       * @return a CreateHealthMonitor constructed with this Builder.\n       */\n      public CreateHealthMonitor build() {\n         return new CreateHealthMonitor(healthMonitor);\n      }\n\n      @Override\n      protected CreateBuilder self() {\n         return this;\n      }\n   }\n\n   /**\n    * Update builder (inheriting from Builder).\n    */\n   public static class UpdateBuilder extends Builder<UpdateBuilder> {\n      /**\n       * Supply required properties for creating a HealthMonitor's UpdateBuilder.\n       */\n      private UpdateBuilder() {\n      }\n\n      /**\n       * @return an UpdateHealthMonitor constructed with this Builder.\n       */\n      public UpdateHealthMonitor build() {\n         return new UpdateHealthMonitor(healthMonitor);\n      }\n\n      @Override\n      protected UpdateBuilder self() {\n         return this;\n      }\n   }\n\n   /**\n    * Create options - extend the domain class, passed to API create calls.\n    * Essentially the same as the domain class. Ensure validation and safe typing.\n    */\n   public static class CreateHealthMonitor extends HealthMonitor {\n      /**\n       * Copy constructor.\n       *\n       * @param healthMonitor the HealthMonitor to copy from.\n       */\n      private CreateHealthMonitor(HealthMonitor healthMonitor) {\n         super(healthMonitor);\n      }\n   }\n\n   /**\n    * Update options - extend the domain class, passed to API update calls.\n    * Essentially the same as the domain class. Ensure validation and safe typing.\n    */\n   public static class UpdateHealthMonitor extends HealthMonitor {\n      /**\n       * Copy constructor.\n       *\n       * @param healthMonitor the HealthMonitor to copy from.\n       */\n      private UpdateHealthMonitor(HealthMonitor healthMonitor) {\n         super(healthMonitor);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/lbaas/v1/HealthMonitorStatus.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain.lbaas.v1;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\n/**\n * A Neutron LBaaS v1 HealthMonitorStatus.\n * Contains an id and status describing the health monitor's status.\n *\n * @see Pool#getHealthMonitorsStatus()\n */\npublic class HealthMonitorStatus {\n\n   // Mandatory attributes\n   @Named(\"monitor_id\")\n   protected final String id;\n   protected final LBaaSStatus status;\n   // Optional attributes\n   @Named(\"status_description\")\n   protected final String statusDescription;\n\n   @ConstructorProperties({ \"monitor_id\", \"status\", \"status_description\" })\n   protected HealthMonitorStatus(String id, LBaaSStatus status, String statusDescription) {\n      this.id = id;\n      this.status = status;\n      this.statusDescription = statusDescription;\n   }\n\n   /**\n    * @return the id of the HealthMonitorStatus.\n    */\n   @Nullable\n   public String getId() {\n      return id;\n   }\n\n   /**\n    * @return the status of the HealthMonitorStatus\n    */\n   @Nullable\n   public LBaaSStatus getStatus() {\n      return status;\n   }\n\n   /**\n    * @return the status description of the HealthMonitorStatus\n    */\n   @Nullable\n   public String getStatusDescription() {\n      return statusDescription;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, status, statusDescription);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      HealthMonitorStatus that = HealthMonitorStatus.class.cast(obj);\n      return Objects.equal(this.id, that.id) && Objects.equal(this.status, that.status)\n            && Objects.equal(this.statusDescription, that.statusDescription);\n   }\n\n   protected MoreObjects.ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).add(\"id\", id).add(\"status\", status)\n            .add(\"statusDescription\", statusDescription);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/lbaas/v1/HealthMonitors.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain.lbaas.v1;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.PaginatedCollection;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * A collection of Neutron LBaaS v1 HealthMonitors.\n */\npublic class HealthMonitors extends PaginatedCollection<HealthMonitor> {\n   public static final HealthMonitors EMPTY = new HealthMonitors(ImmutableSet.<HealthMonitor> of(),\n         ImmutableSet.<Link> of());\n\n   @ConstructorProperties({ \"health_monitors\", \"health_monitors_links\" })\n   protected HealthMonitors(Iterable<HealthMonitor> healthMonitors, Iterable<Link> healthMonitorsLinks) {\n      super(healthMonitors, healthMonitorsLinks);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/lbaas/v1/HttpMethod.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.openstack.neutron.v2.domain.lbaas.v1;\n\n\n/**\n * Enumerates supported HTTP methods used by probes of type HTTP/HTTPS that are sent by health monitor to verify member state.\n */\npublic enum HttpMethod {\n   /**\n    * Health monitor sends a GET HTTP request to the member.\n    */\n   GET(\"GET\"),\n   /**\n    * Health monitor sends a POST HTTP request to the member.\n    */\n   POST(\"POST\"),\n   /**\n    * Health monitor sends a PUT HTTP request to the member.\n    */\n   PUT(\"PUT\"),\n   /**\n    * Health monitor sends a DELETE HTTP request to the member.\n    */\n   DELETE(\"DELETE\"),\n   /**\n    * Health monitor sends a HEAD HTTP request to the member.\n    */\n   HEAD(\"HEAD\"),\n   /**\n    * Used by jclouds when the service returns an unknown value other than null.\n    */\n   UNRECOGNIZED(\"unrecognized\");\n\n   private String name;\n\n   private HttpMethod(String name) {\n      this.name = name;\n   }\n\n   @Override\n   public String toString() {\n      return name;\n   }\n\n   /*\n    * This provides GSON enum support in jclouds.\n    * */\n   public static HttpMethod fromValue(String name){\n      if (name != null) {\n         for (HttpMethod value : HttpMethod.values()) {\n            if (name.equalsIgnoreCase(value.name)) {\n               return value;\n            }\n         }\n         return UNRECOGNIZED;\n      }\n      return null;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/lbaas/v1/LBaaSStatus.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.openstack.neutron.v2.domain.lbaas.v1;\n\n/**\n * Enumerates supported Neutron LBaaS v1 resources status.\n */\npublic enum LBaaSStatus {\n   /**\n    * The LBaaS v1 resource is ready and active.\n    */\n   ACTIVE(\"active\"),\n   /**\n    * The LBaaS v1 resource is being created.\n    */\n   PENDING_CREATE(\"pending_create\"),\n   /**\n    * The LBaaS v1 resource is being updated.\n    */\n   PENDING_UPDATE(\"pending_update\"),\n   /**\n    * The LBaaS v1 resource is going to be deleted.\n    */\n   PENDING_DELETE(\"pending_delete\"),\n   /**\n    * The LBaaS v1 resource is created but not active.\n    */\n   INACTIVE(\"inactive\"),\n   /**\n    * The LBaaS v1 resource is in an error state.\n    */\n   ERROR(\"error\"),\n   /**\n    * Used by jclouds when the service returns an unknown value other than null.\n    */\n   UNRECOGNIZED(\"unrecognized\");\n\n   private String name;\n\n   private LBaaSStatus(String name) {\n      this.name = name;\n   }\n\n   @Override\n   public String toString() {\n      return name;\n   }\n\n   /*\n    * This provides GSON enum support in jclouds.\n    * */\n   public static LBaaSStatus fromValue(String name){\n      if (name != null) {\n         for (LBaaSStatus value : LBaaSStatus.values()) {\n            if (name.equalsIgnoreCase(value.name)) {\n               return value;\n            }\n         }\n         return UNRECOGNIZED;\n      }\n      return null;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/lbaas/v1/Member.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain.lbaas.v1;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\n/**\n * A Neutron LBaaS v1 Member.\n */\npublic class Member {\n\n   // Mandatory attributes when creating\n   @Named(\"tenant_id\")\n   private String tenantId;\n   private String address;\n   @Named(\"protocol_port\")\n   private Integer protocolPort;\n   // Mandatory attributes that can be updated\n   @Named(\"pool_id\")\n   private String poolId;\n   // Optional attributes that can be updated\n   private Integer weight;\n   @Named(\"admin_state_up\")\n   private Boolean adminStateUp;\n   // Read-only attributes\n   private String id;\n   private LBaaSStatus status;\n   @Named(\"status_description\")\n   private String statusDescription;\n\n   /**\n    * Deserialization constructor.\n    */\n   @ConstructorProperties({ \"id\", \"tenant_id\", \"pool_id\", \"address\", \"protocol_port\", \"weight\", \"admin_state_up\",\n         \"status\", \"status_description\" })\n   private Member(String id, String tenantId, String poolId, String address, Integer protocolPort, Integer weight,\n         Boolean adminStateUp, LBaaSStatus status, String statusDescription) {\n      this.id = id;\n      this.tenantId = tenantId;\n      this.poolId = poolId;\n      this.address = address;\n      this.protocolPort = protocolPort;\n      this.weight = weight;\n      this.adminStateUp = adminStateUp;\n      this.status = status;\n      this.statusDescription = statusDescription;\n   }\n\n   /**\n    * Default constructor.\n    */\n   private Member() {\n   }\n\n   /**\n    * Copy constructor.\n    *\n    * @param member the Member to copy from.\n    */\n   private Member(Member member) {\n      this(member.id, member.tenantId, member.poolId, member.address, member.protocolPort, member.weight,\n            member.adminStateUp, member.status, member.statusDescription);\n   }\n\n   /**\n    * @return the id of the Member.\n    */\n   @Nullable\n   public String getId() {\n      return id;\n   }\n\n   /**\n    * @return the tenant id of the Member.\n    */\n   @Nullable\n   public String getTenantId() {\n      return tenantId;\n   }\n\n   /**\n    * @return the pool id for this Member.\n    */\n   @Nullable\n   public String getPoolId() {\n      return poolId;\n   }\n\n   /**\n    * @return the address for this Member.\n    */\n   @Nullable\n   public String getAddress() {\n      return address;\n   }\n\n   /**\n    * @return the protocol port for this Member.\n    */\n   @Nullable\n   public Integer getProtocolPort() {\n      return protocolPort;\n   }\n\n   /**\n    * @return the weight for this Member.\n    */\n   @Nullable\n   public Integer getWeight() {\n      return weight;\n   }\n\n   /**\n    * @return the administrative state for this Member.\n    */\n   @Nullable\n   public Boolean getAdminStateUp() {\n      return adminStateUp;\n   }\n\n   /**\n    * @return the status for this Member.\n    */\n   @Nullable\n   public LBaaSStatus getStatus() {\n      return status;\n   }\n\n   /**\n    * @return the status description for this Member.\n    */\n   @Nullable\n   public String getStatusDescription() {\n      return statusDescription;\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o)\n         return true;\n      if (o == null || getClass() != o.getClass())\n         return false;\n\n      Member that = (Member) o;\n\n      return Objects.equal(this.id, that.id) && Objects.equal(this.tenantId, that.tenantId)\n            && Objects.equal(this.poolId, that.poolId) && Objects.equal(this.address, that.address)\n            && Objects.equal(this.protocolPort, that.protocolPort) && Objects.equal(this.weight, that.weight)\n            && Objects.equal(this.adminStateUp, that.adminStateUp) && Objects.equal(this.status, that.status)\n            && Objects.equal(this.statusDescription, that.statusDescription);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, tenantId, poolId, address, protocolPort, weight, adminStateUp, status,\n            statusDescription);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).add(\"id\", id).add(\"tenantId\", tenantId).add(\"poolId\", poolId)\n            .add(\"address\", address).add(\"protocolPort\", protocolPort).add(\"weight\", weight)\n            .add(\"adminStateUp\", adminStateUp).add(\"status\", status).add(\"statusDescription\", statusDescription)\n            .toString();\n   }\n\n   /*\n    * Methods to get the Create and Update builders follow.\n    */\n\n   /**\n    * @return the Builder for creating a new Member.\n    */\n   public static CreateBuilder createBuilder(String poolId, String address, Integer port) {\n      return new CreateBuilder(poolId, address, port);\n   }\n\n   /**\n    * @return the Builder for updating a Member.\n    */\n   public static UpdateBuilder updateBuilder() {\n      return new UpdateBuilder();\n   }\n\n   private abstract static class Builder<ParameterizedBuilderType> {\n      protected Member member;\n\n      /**\n       * Default constructor.\n       */\n      private Builder() {\n         member = new Member();\n      }\n\n      protected abstract ParameterizedBuilderType self();\n\n      /**\n       * Provides the pool id for this Member's Builder.\n       *\n       * @return the Builder.\n       * @see Member#getPoolId()\n       */\n      public ParameterizedBuilderType poolId(String poolId) {\n         member.poolId = poolId;\n         return self();\n      }\n\n      /**\n       * Provides the weight for this Member's Builder.\n       *\n       * @return the Builder.\n       * @see Member#getWeight()\n       */\n      public ParameterizedBuilderType weight(Integer weight) {\n         member.weight = weight;\n         return self();\n      }\n\n      /**\n       * Provides the administrative state for this Member's Builder.\n       *\n       * @return the Builder.\n       * @see Member#getAdminStateUp()\n       */\n      public ParameterizedBuilderType adminStateUp(Boolean adminStateUp) {\n         member.adminStateUp = adminStateUp;\n         return self();\n      }\n   }\n\n   /**\n    * Create builder (inheriting from Builder).\n    */\n   public static class CreateBuilder extends Builder<CreateBuilder> {\n      /**\n       * Supply required properties for creating a Member's CreateBuilder.\n       *\n       * @param poolId the pool id.\n       * @param address the IP address.\n       * @param port the protocol port.\n       */\n      private CreateBuilder(String poolId, String address, Integer port) {\n         poolId(poolId).address(address).protocolPort(port);\n      }\n\n      /**\n       * Provides the tenantId for this Member's Builder. Admin-only.\n       * When keystone is enabled, it is not mandatory to specify tenant_id for resources in create requests, as the\n       * tenant identifier will be derived from the Authentication token. Please note that the default authorization\n       * settings only allow administrative users to create resources on behalf of a different tenant.\n       *\n       * @return the Builder.\n       * @see Member#getTenantId()\n       */\n      public CreateBuilder tenantId(String tenantId) {\n         member.tenantId = tenantId;\n         return self();\n      }\n\n      /**\n       * Provides the address for this Member's Builder.\n       *\n       * @return the Builder.\n       * @see Member#getAddress()\n       */\n      public CreateBuilder address(String address) {\n         member.address = address;\n         return self();\n      }\n\n      /**\n       * Provides the protocol port for this Member's Builder.\n       *\n       * @return the Builder.\n       * @see Member#getProtocolPort()\n       */\n      public CreateBuilder protocolPort(Integer protocolPort) {\n         member.protocolPort = protocolPort;\n         return self();\n      }\n\n      /**\n       * @return a CreateMember constructed with this Builder.\n       */\n      public CreateMember build() {\n         return new CreateMember(member);\n      }\n\n      @Override\n      protected CreateBuilder self() {\n         return this;\n      }\n   }\n\n   /**\n    * Update builder (inheriting from Builder).\n    */\n   public static class UpdateBuilder extends Builder<UpdateBuilder> {\n      /**\n       * Supply required properties for creating a Member's UpdateBuilder.\n       */\n      private UpdateBuilder() {\n      }\n\n      /**\n       * @return a UpdateMember constructed with this Builder.\n       */\n      public UpdateMember build() {\n         return new UpdateMember(member);\n      }\n\n      @Override\n      protected UpdateBuilder self() {\n         return this;\n      }\n   }\n\n   /**\n    * Create options - extend the domain class, passed to API create calls.\n    * Essentially the same as the domain class. Ensure validation and safe typing.\n    */\n   public static class CreateMember extends Member {\n      /**\n       * Copy constructor.\n       *\n       * @param member the Member to copy from.\n       */\n      private CreateMember(Member member) {\n         super(member);\n      }\n   }\n\n   /**\n    * Update options - extend the domain class, passed to API update calls.\n    * Essentially the same as the domain class. Ensure validation and safe typing.\n    */\n   public static class UpdateMember extends Member {\n      /**\n       * Copy constructor.\n       *\n       * @param member the Member to copy from.\n       */\n      private UpdateMember(Member member) {\n         super(member);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/lbaas/v1/Members.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain.lbaas.v1;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.PaginatedCollection;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * A collection of of Neutron LBaaS v1 Members.\n */\npublic class Members extends PaginatedCollection<Member> {\n   public static final Members EMPTY = new Members(ImmutableSet.<Member> of(), ImmutableSet.<Link> of());\n\n   @ConstructorProperties({ \"members\", \"members_links\" })\n   protected Members(Iterable<Member> members, Iterable<Link> membersLinks) {\n      super(members, membersLinks);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/lbaas/v1/Pool.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain.lbaas.v1;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * A Neutron LBaaS v1 Pool.\n */\npublic class Pool {\n\n   // Load balancing methods that must be supported by all providers.\n   // Not an enum type because any provider may support additional balancing methods.\n   public static String ROUND_ROBIN = \"ROUND_ROBIN\";\n   public static String LEAST_CONNECTIONS = \"LEAST_CONNECTIONS\";\n   public static String SOURCE_IP = \"SOURCE_IP\";\n\n   // Mandatory attributes when creating\n   @Named(\"tenant_id\")\n   private String tenantId;\n   @Named(\"subnet_id\")\n   private String subnetId;\n   private Protocol protocol;\n   // Mandatory attributes that can be updated\n   @Named(\"lb_method\")\n   private String lbMethod;\n   // Optional attributes when creating\n   private String provider;\n   // Optional attributes that can be updated\n   private String name;\n   private String description;\n   @Named(\"health_monitors\")\n   private ImmutableSet<String> healthMonitors;\n   @Named(\"admin_state_up\")\n   private Boolean adminStateUp;\n   // Read-only attributes\n   private String id;\n   @Named(\"vip_id\")\n   private String vipId;\n   private ImmutableSet<String> members;\n   @Named(\"health_monitors_status\")\n   private ImmutableList<HealthMonitorStatus> healthMonitorsStatus;\n   private LBaaSStatus status;\n   @Named(\"status_description\")\n   private String statusDescription;\n\n   /**\n    * Deserialization constructor.\n    */\n   @ConstructorProperties({ \"id\", \"tenant_id\", \"vip_id\", \"name\", \"description\", \"subnet_id\", \"protocol\", \"provider\",\n         \"lb_method\", \"health_monitors\", \"health_monitors_status\", \"members\", \"admin_state_up\", \"status\",\n         \"status_description\" })\n   private Pool(String id, String tenantId, String vipId, String name, String description, String subnetId,\n         Protocol protocol, String provider, String lbMethod, ImmutableSet<String> healthMonitors,\n         ImmutableList<HealthMonitorStatus> healthMonitorsStatus, ImmutableSet<String> members, Boolean adminStateUp,\n         LBaaSStatus status, String statusDescription) {\n      this.id = id;\n      this.tenantId = tenantId;\n      this.vipId = vipId;\n      this.name = name;\n      this.description = description;\n      this.subnetId = subnetId;\n      this.protocol = protocol;\n      this.provider = provider;\n      this.lbMethod = lbMethod;\n      this.healthMonitors = healthMonitors;\n      this.healthMonitorsStatus = healthMonitorsStatus;\n      this.members = members;\n      this.adminStateUp = adminStateUp;\n      this.status = status;\n      this.statusDescription = statusDescription;\n   }\n\n   /**\n    * Default constructor.\n    */\n   private Pool() {\n   }\n\n   /**\n    * Copy constructor.\n    *\n    * @param pool the Pool to copy from.\n    */\n   private Pool(Pool pool) {\n      this(pool.id, pool.tenantId, pool.vipId, pool.name, pool.description, pool.subnetId, pool.protocol,\n            pool.provider, pool.lbMethod, pool.healthMonitors, pool.healthMonitorsStatus, pool.members,\n            pool.adminStateUp, pool.status, pool.statusDescription);\n   }\n\n   /**\n    * @return the id of the Pool.\n    */\n   @Nullable\n   public String getId() {\n      return id;\n   }\n\n   /**\n    * @return the tenant id of the Pool.\n    */\n   @Nullable\n   public String getTenantId() {\n      return tenantId;\n   }\n\n   /**\n    * @return the virtual IP id of the Pool.\n    */\n   @Nullable\n   public String getVIPId() {\n      return vipId;\n   }\n\n   /**\n    * @return the name of the Pool.\n    */\n   @Nullable\n   public String getName() {\n      return name;\n   }\n\n   /**\n    * @return the description of the Pool.\n    */\n   @Nullable\n   public String getDescription() {\n      return description;\n   }\n\n   /**\n    * @return the subnet id for this Pool.\n    */\n   @Nullable\n   public String getSubnetId() {\n      return subnetId;\n   }\n\n   /**\n    * @return the protocol for this Pool.\n    */\n   @Nullable\n   public Protocol getProtocol() {\n      return protocol;\n   }\n\n   /**\n    * @return the provider for this Pool.\n    */\n   @Nullable\n   public String getProvider() {\n      return provider;\n   }\n\n   /**\n    * @return the load balancing method for this Pool.\n    */\n   @Nullable\n   public String getLBMethod() {\n      return lbMethod;\n   }\n\n   /**\n    * @return the health monitors for this Pool.\n    */\n   @Nullable\n   public ImmutableSet<String> getHealthMonitors() {\n      return healthMonitors;\n   }\n\n   /**\n    * @return the health monitors status for this Pool.\n    */\n   @Nullable\n   public ImmutableList<HealthMonitorStatus> getHealthMonitorsStatus() {\n      return healthMonitorsStatus;\n   }\n\n   /**\n    * @return the members for this Pool.\n    */\n   @Nullable\n   public ImmutableSet<String> getMembers() {\n      return members;\n   }\n\n   /**\n    * @return the administrative state for this Pool.\n    */\n   @Nullable\n   public Boolean getAdminStateUp() {\n      return adminStateUp;\n   }\n\n   /**\n    * @return the status for this Pool.\n    */\n   @Nullable\n   public LBaaSStatus getStatus() {\n      return status;\n   }\n\n   /**\n    * @return the status description for this Pool.\n    */\n   @Nullable\n   public String getStatusDescription() {\n      return statusDescription;\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o)\n         return true;\n      if (o == null || getClass() != o.getClass())\n         return false;\n\n      Pool that = (Pool) o;\n\n      return Objects.equal(this.id, that.id) && Objects.equal(this.tenantId, that.tenantId)\n            && Objects.equal(this.vipId, that.vipId) && Objects.equal(this.name, that.name)\n            && Objects.equal(this.description, that.description) && Objects.equal(this.subnetId, that.subnetId)\n            && Objects.equal(this.protocol, that.protocol) && Objects.equal(this.provider, that.provider)\n            && Objects.equal(this.lbMethod, that.lbMethod) && Objects.equal(this.healthMonitors, that.healthMonitors)\n            && Objects.equal(this.healthMonitorsStatus, that.healthMonitorsStatus)\n            && Objects.equal(this.members, that.members) && Objects.equal(this.adminStateUp, that.adminStateUp)\n            && Objects.equal(this.status, that.status) && Objects.equal(this.statusDescription, that.statusDescription);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, tenantId, vipId, name, description, subnetId, protocol, provider, lbMethod,\n            healthMonitors, healthMonitorsStatus, members, adminStateUp, status, statusDescription);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).add(\"id\", id).add(\"tenantId\", tenantId).add(\"vipId\", vipId)\n            .add(\"name\", name).add(\"description\", description).add(\"subnetId\", subnetId).add(\"protocol\", protocol)\n            .add(\"provider\", provider).add(\"lbMethod\", lbMethod).add(\"healthMonitors\", healthMonitors)\n            .add(\"healthMonitorsStatus\", healthMonitorsStatus).add(\"members\", members)\n            .add(\"adminStateUp\", adminStateUp).add(\"status\", status).add(\"statusDescription\", statusDescription)\n            .toString();\n   }\n\n   /*\n    * Methods to get the Create and Update builders follow.\n    */\n\n   /**\n    * @return the Builder for creating a new Pool.\n    */\n   public static CreateBuilder createBuilder(String subnetId, Protocol protocol, String lbMethod) {\n      return new CreateBuilder(subnetId, protocol, lbMethod);\n   }\n\n   /**\n    * @return the Builder for updating a Pool.\n    */\n   public static UpdateBuilder updateBuilder() {\n      return new UpdateBuilder();\n   }\n\n   private abstract static class Builder<ParameterizedBuilderType> {\n      protected Pool pool;\n\n      /**\n       * Default constructor.\n       */\n      private Builder() {\n         pool = new Pool();\n      }\n\n      protected abstract ParameterizedBuilderType self();\n\n      /**\n       * Provides the name for this Pool's Builder.\n       *\n       * @return the Builder.\n       * @see Pool#getName()\n       */\n      public ParameterizedBuilderType name(String name) {\n         pool.name = name;\n         return self();\n      }\n\n      /**\n       * Provides the description for this Pool's Builder.\n       *\n       * @return the Builder.\n       * @see Pool#getDescription()\n       */\n      public ParameterizedBuilderType description(String description) {\n         pool.description = description;\n         return self();\n      }\n\n      /**\n       * Provides the load balancing method for this Pool's Builder.\n       *\n       * @return the Builder.\n       * @see Pool#getLBMethod()\n       */\n      public ParameterizedBuilderType lbMethod(String lbMethod) {\n         pool.lbMethod = lbMethod;\n         return self();\n      }\n\n      /**\n       * Provides the health monitors for this Pool's Builder.\n       *\n       * @return the Builder.\n       * @see Pool#getHealthMonitors()\n       */\n      public ParameterizedBuilderType healthMonitors(ImmutableSet<String> healthMonitors) {\n         pool.healthMonitors = healthMonitors;\n         return self();\n      }\n\n      /**\n       * Provides the administrative state for this Pool's Builder.\n       *\n       * @return the Builder.\n       * @see Pool#getAdminStateUp()\n       */\n      public ParameterizedBuilderType adminStateUp(Boolean adminStateUp) {\n         pool.adminStateUp = adminStateUp;\n         return self();\n      }\n   }\n\n   /**\n    * Create builder (inheriting from Builder).\n    */\n   public static class CreateBuilder extends Builder<CreateBuilder> {\n      /**\n       * Supply required properties for creating a Pool's CreateBuilder.\n       *\n       * @param subnetId the subnet id.\n       * @param protocol the protocol.\n       * @param lbMethod the load balancing method.\n       */\n      private CreateBuilder(String subnetId, Protocol protocol, String lbMethod) {\n         subnetId(subnetId).protocol(protocol).lbMethod(lbMethod);\n      }\n\n      /**\n       * Provides the tenantId for this Pool's Builder. Admin-only.\n       * When keystone is enabled, it is not mandatory to specify tenant_id for resources in create requests, as the\n       * tenant identifier will be derived from the Authentication token. Please note that the default authorization\n       * settings only allow administrative users to create resources on behalf of a different tenant.\n       *\n       * @return the Builder.\n       * @see Pool#getTenantId()\n       */\n      public CreateBuilder tenantId(String tenantId) {\n         pool.tenantId = tenantId;\n         return self();\n      }\n\n      /**\n       * Provides the subnet id for this Pool's Builder.\n       *\n       * @return the Builder.\n       * @see Pool#getSubnetId()\n       */\n      public CreateBuilder subnetId(String subnetId) {\n         pool.subnetId = subnetId;\n         return self();\n      }\n\n      /**\n       * Provides the protocol for this Pool's Builder.\n       *\n       * @return the Builder.\n       * @see Pool#getProtocol()\n       */\n      public CreateBuilder protocol(Protocol protocol) {\n         pool.protocol = protocol;\n         return self();\n      }\n\n      /**\n       * Provides the provider for this Pool's Builder.\n       *\n       * @return the Builder.\n       * @see Pool#getProvider()\n       */\n      public CreateBuilder provider(String provider) {\n         pool.provider = provider;\n         return self();\n      }\n\n      /**\n       * @return a CreatePool constructed with this Builder.\n       */\n      public CreatePool build() {\n         return new CreatePool(pool);\n      }\n\n      @Override\n      protected CreateBuilder self() {\n         return this;\n      }\n   }\n\n   /**\n    * Update builder (inheriting from Builder).\n    */\n   public static class UpdateBuilder extends Builder<UpdateBuilder> {\n      /**\n       * Supply required properties for creating a Pool's UpdateBuilder.\n       */\n      private UpdateBuilder() {\n      }\n\n      /**\n       * @return a UpdatePool constructed with this Builder.\n       */\n      public UpdatePool build() {\n         return new UpdatePool(pool);\n      }\n\n      @Override\n      protected UpdateBuilder self() {\n         return this;\n      }\n   }\n\n   /**\n    * Create options - extend the domain class, passed to API create calls.\n    * Essentially the same as the domain class. Ensure validation and safe typing.\n    */\n   public static class CreatePool extends Pool {\n      /**\n       * Copy constructor.\n       *\n       * @param pool the Pool to copy from.\n       */\n      private CreatePool(Pool pool) {\n         super(pool);\n      }\n   }\n\n   /**\n    * Update options - extend the domain class, passed to API update calls.\n    * Essentially the same as the domain class. Ensure validation and safe typing.\n    */\n   public static class UpdatePool extends Pool {\n      /**\n       * Copy constructor.\n       *\n       * @param pool the Pool to copy from.\n       */\n      private UpdatePool(Pool pool) {\n         super(pool);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/lbaas/v1/PoolStatus.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain.lbaas.v1;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\n/**\n * A Neutron LBaaS v1 PoolStatus.\n * Contains an id and status describing the pool's status.\n *\n * @see HealthMonitor#getPools()\n */\npublic class PoolStatus {\n\n   // Mandatory attributes\n   @Named(\"pool_id\")\n   protected final String id;\n   protected final LBaaSStatus status;\n   // Optional attributes\n   @Named(\"status_description\")\n   protected final String statusDescription;\n\n   @ConstructorProperties({ \"pool_id\", \"status\", \"status_description\" })\n   protected PoolStatus(String id, LBaaSStatus status, String statusDescription) {\n      this.id = id;\n      this.status = status;\n      this.statusDescription = statusDescription;\n   }\n\n   /**\n    * @return the id of the PoolStatus.\n    */\n   @Nullable\n   public String getId() {\n      return id;\n   }\n\n   /**\n    * @return the status of the PoolStatus.\n    */\n   @Nullable\n   public LBaaSStatus getStatus() {\n      return status;\n   }\n\n   /**\n    * @return the status description of the PoolStatus.\n    */\n   @Nullable\n   public String getStatusDescription() {\n      return statusDescription;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, status, statusDescription);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      PoolStatus that = PoolStatus.class.cast(obj);\n      return Objects.equal(this.id, that.id) && Objects.equal(this.status, that.status)\n            && Objects.equal(this.statusDescription, that.statusDescription);\n   }\n\n   protected MoreObjects.ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).add(\"id\", id).add(\"status\", status)\n            .add(\"statusDescription\", statusDescription);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/lbaas/v1/Pools.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain.lbaas.v1;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.PaginatedCollection;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * A collection of of Neutron LBaaS v1 Pools.\n */\npublic class Pools extends PaginatedCollection<Pool> {\n   public static final Pools EMPTY = new Pools(ImmutableSet.<Pool> of(), ImmutableSet.<Link> of());\n\n   @ConstructorProperties({ \"pools\", \"pools_links\" })\n   protected Pools(Iterable<Pool> pools, Iterable<Link> poolsLinks) {\n      super(pools, poolsLinks);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/lbaas/v1/ProbeType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.openstack.neutron.v2.domain.lbaas.v1;\n\n/**\n * Enumerates supported types of probe sent by health monitor to verify member state.\n */\npublic enum ProbeType {\n   /**\n    * Health monitor pings the members by using ICMP.\n    */\n   PING(\"PING\"),\n   /**\n    * Health monitor connects to the members by using TCP.\n    */\n   TCP(\"TCP\"),\n   /**\n    * Health monitor sends an HTTP request to the member.\n    */\n   HTTP(\"HTTP\"),\n   /**\n    * Health monitor sends a secure HTTP request to the member.\n    */\n   HTTPS(\"HTTPS\"),\n   /**\n    * Used by jclouds when the service returns an unknown value other than null.\n    */\n   UNRECOGNIZED(\"unrecognized\");\n\n   private String name;\n\n   private ProbeType(String name) {\n      this.name = name;\n   }\n\n   @Override\n   public String toString() {\n      return name;\n   }\n\n   /*\n    * This provides GSON enum support in jclouds.\n    * */\n   public static ProbeType fromValue(String name){\n      if (name != null) {\n         for (ProbeType value : ProbeType.values()) {\n            if (name.equalsIgnoreCase(value.name)) {\n               return value;\n            }\n         }\n         return UNRECOGNIZED;\n      }\n      return null;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/lbaas/v1/Protocol.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.openstack.neutron.v2.domain.lbaas.v1;\n\n/**\n * Enumerates supported protocols.\n * Protocol must be specified for the front-end (see {@link VIP}) and for the back-end instances (see {@link Pool}).\n */\npublic enum Protocol {\n   /**\n    * Use TCP for routing traffic.\n    */\n   TCP(\"TCP\"),\n   /**\n    * Use HTTP for routing traffic.\n    */\n   HTTP(\"HTTP\"),\n   /**\n    * Use HTTPS for routing traffic.\n    */\n   HTTPS(\"HTTPS\"),\n   /**\n    * Used by jclouds when the service returns an unknown value other than null.\n    */\n   UNRECOGNIZED(\"unrecognized\");\n\n   private String name;\n\n   private Protocol(String name) {\n      this.name = name;\n   }\n\n   @Override\n   public String toString() {\n      return name;\n   }\n\n   /*\n    * This provides GSON enum support in jclouds.\n    * */\n   public static Protocol fromValue(String name){\n      if (name != null) {\n         for (Protocol value : Protocol.values()) {\n            if (name.equalsIgnoreCase(value.name)) {\n               return value;\n            }\n         }\n         return UNRECOGNIZED;\n      }\n      return null;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/lbaas/v1/SessionPersistence.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain.lbaas.v1;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\n/**\n * A Neutron LBaaS v1 SessionPersistence.\n * Contains a type and cookie name describing the session persistence.\n */\npublic class SessionPersistence {\n\n   // Mandatory attributes\n   protected final Type type;\n   // Optional attributes\n   @Named(\"cookie_name\")\n   protected final String cookieName;\n\n   @ConstructorProperties({ \"type\", \"cookie_name\" })\n   protected SessionPersistence(Type type, String cookieName) {\n      this.type = type;\n      this.cookieName = cookieName;\n   }\n\n   /**\n    * @return the type of the SessionPersistence.\n    */\n   @Nullable\n   public Type getType() {\n      return type;\n   }\n\n   /**\n    * @return the cookie name of the SessionPersistence.\n    */\n   @Nullable\n   public String getCookieName() {\n      return cookieName;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(type, cookieName);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      SessionPersistence that = SessionPersistence.class.cast(obj);\n      return Objects.equal(this.type, that.type) && Objects.equal(this.cookieName, that.cookieName);\n   }\n\n   protected MoreObjects.ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).add(\"type\", type).add(\"cookieName\", cookieName);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   /*\n    * Methods to get the builder follow.\n    */\n\n   /**\n    * @return the Builder for SessionPersistence.\n    */\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   /**\n    * Builder.\n    */\n   public static class Builder {\n      protected Type type;\n      protected String cookieName;\n\n      /**\n       * Provides the type to the SessionPersistence's Builder.\n       *\n       * @return the Builder.\n       * @see SessionPersistence#getType()\n       */\n      public Builder type(Type type) {\n         this.type = type;\n         return this;\n      }\n\n      /**\n       * Provides the cookie name to the SessionPersistence's Builder.\n       *\n       * @return the Builder.\n       * @see SessionPersistence#getCookieName()\n       */\n      public Builder cookieName(String cookieName) {\n         this.cookieName = cookieName;\n         return this;\n      }\n\n      /**\n       * @return a SessionPersistence constructed with this Builder.\n       */\n      public SessionPersistence build() {\n         return new SessionPersistence(type, cookieName);\n      }\n   }\n\n   /**\n    * Enumerates supported SessionPersistence types.\n    */\n   public static enum Type {\n      /**\n       * All connections that originate from the same source IP address are handled by the same member of the pool.\n       */\n      SOURCE_IP(\"SOURCE_IP\"),\n      /**\n       * The load balancing function creates a cookie on the first request from a client. Subsequent requests that\n       * contain the same cookie value are handled by the same member of the pool.\n       */\n      HTTP_COOKIE(\"HTTP_COOKIE\"),\n      /**\n       * The load balancing function relies on a cookie established by the back-end application. All requests with the\n       * same cookie value are handled by the same member of the pool.\n       */\n      APP_COOKIE(\"APP_COOKIE\"),\n      /**\n       * Used by jclouds when the service returns an unknown value other than null.\n       */\n      UNRECOGNIZED(\"unrecognized\");\n\n      private String name;\n\n      private Type(String name) {\n         this.name = name;\n      }\n\n      @Override\n      public String toString() {\n         return name;\n      }\n\n      /*\n       * This provides GSON enum support in jclouds.\n       * */\n      public static Type fromValue(String name){\n         if (name != null) {\n            for (Type value : Type.values()) {\n               if (name.equalsIgnoreCase(value.name)) {\n                  return value;\n               }\n            }\n            return UNRECOGNIZED;\n         }\n         return null;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/lbaas/v1/VIP.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain.lbaas.v1;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\n/**\n * A Neutron LBaaS v1 VIP.\n */\npublic class VIP {\n\n   // Mandatory attributes when creating\n   @Named(\"tenant_id\")\n   private String tenantId;\n   @Named(\"subnet_id\")\n   private String subnetId;\n   private Protocol protocol;\n   @Named(\"protocol_port\")\n   private Integer protocolPort;\n   // Mandatory attributes that can be updated\n   @Named(\"pool_id\")\n   private String poolId;\n   // Optional attributes when creating\n   private String address;\n   // Optional attributes that can be updated\n   private String name;\n   private String description;\n   @Named(\"session_persistence\")\n   private SessionPersistence sessionPersistence;\n   @Named(\"connection_limit\")\n   private Integer connectionLimit;\n   @Named(\"admin_state_up\")\n   private Boolean adminStateUp;\n   // Read-only attributes\n   private String id;\n   @Named(\"port_id\")\n   private String portId;\n   private LBaaSStatus status;\n   @Named(\"status_description\")\n   private String statusDescription;\n\n   /**\n    * Deserialization constructor.\n    */\n   @ConstructorProperties({ \"id\", \"tenant_id\", \"name\", \"description\", \"subnet_id\", \"address\", \"port_id\", \"protocol\",\n         \"protocol_port\", \"pool_id\", \"session_persistence\", \"connection_limit\", \"admin_state_up\", \"status\",\n         \"status_description\" })\n   private VIP(String id, String tenantId, String name, String description, String subnetId, String address,\n         String portId, Protocol protocol, Integer protocolPort, String poolId, SessionPersistence sessionPersistence,\n         Integer connectionLimit, Boolean adminStateUp, LBaaSStatus status, String statusDescription) {\n      this.id = id;\n      this.tenantId = tenantId;\n      this.name = name;\n      this.description = description;\n      this.subnetId = subnetId;\n      this.address = address;\n      this.portId = portId;\n      this.protocol = protocol;\n      this.protocolPort = protocolPort;\n      this.poolId = poolId;\n      this.sessionPersistence = sessionPersistence;\n      this.connectionLimit = connectionLimit;\n      this.adminStateUp = adminStateUp;\n      this.status = status;\n      this.statusDescription = statusDescription;\n   }\n\n   /**\n    * Default constructor.\n    */\n   private VIP() {\n   }\n\n   /**\n    * Copy constructor.\n    *\n    * @param VIP the VIP to copy from.\n    */\n   private VIP(VIP vip) {\n      this(vip.id, vip.tenantId, vip.name, vip.description, vip.subnetId, vip.address, vip.portId, vip.protocol,\n            vip.protocolPort, vip.poolId, vip.sessionPersistence, vip.connectionLimit, vip.adminStateUp, vip.status,\n            vip.statusDescription);\n   }\n\n   /**\n    * @return the id of the VIP.\n    */\n   @Nullable\n   public String getId() {\n      return id;\n   }\n\n   /**\n    * @return the tenant id of the VIP.\n    */\n   @Nullable\n   public String getTenantId() {\n      return tenantId;\n   }\n\n   /**\n    * @return the name of the VIP.\n    */\n   @Nullable\n   public String getName() {\n      return name;\n   }\n\n   /**\n    * @return the description of the VIP.\n    */\n   @Nullable\n   public String getDescription() {\n      return description;\n   }\n\n   /**\n    * @return the subnet id for this VIP.\n    */\n   @Nullable\n   public String getSubnetId() {\n      return subnetId;\n   }\n\n   /**\n    * @return the address for this VIP.\n    */\n   @Nullable\n   public String getAddress() {\n      return address;\n   }\n\n   /**\n    * @return the port id for this VIP.\n    */\n   @Nullable\n   public String getPortId() {\n      return portId;\n   }\n\n   /**\n    * @return the protocol for this VIP.\n    */\n   @Nullable\n   public Protocol getProtocol() {\n      return protocol;\n   }\n\n   /**\n    * @return the protocol port for this VIP.\n    */\n   @Nullable\n   public Integer getProtocolPort() {\n      return protocolPort;\n   }\n\n   /**\n    * @return the pool id for this VIP.\n    */\n   @Nullable\n   public String getPoolId() {\n      return poolId;\n   }\n\n   /**\n    * @return the session persistence for this VIP.\n    */\n   @Nullable\n   public SessionPersistence getSessionPersistence() {\n      return sessionPersistence;\n   }\n\n   /**\n    * @return the connection limit for this VIP.\n    */\n   @Nullable\n   public Integer getConnectionLimit() {\n      return connectionLimit;\n   }\n\n   /**\n    * @return the administrative state for this VIP.\n    */\n   @Nullable\n   public Boolean getAdminStateUp() {\n      return adminStateUp;\n   }\n\n   /**\n    * @return the status for this VIP.\n    */\n   @Nullable\n   public LBaaSStatus getStatus() {\n      return status;\n   }\n\n   /**\n    * @return the status description for this VIP.\n    */\n   @Nullable\n   public String getStatusDescription() {\n      return statusDescription;\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o)\n         return true;\n      if (o == null || getClass() != o.getClass())\n         return false;\n\n      VIP that = (VIP) o;\n\n      return Objects.equal(this.id, that.id) && Objects.equal(this.tenantId, that.tenantId)\n            && Objects.equal(this.name, that.name) && Objects.equal(this.description, that.description)\n            && Objects.equal(this.subnetId, that.subnetId) && Objects.equal(this.address, that.address)\n            && Objects.equal(this.portId, that.portId) && Objects.equal(this.protocol, that.protocol)\n            && Objects.equal(this.protocolPort, that.protocolPort) && Objects.equal(this.poolId, that.poolId)\n            && Objects.equal(this.sessionPersistence, that.sessionPersistence)\n            && Objects.equal(this.connectionLimit, that.connectionLimit)\n            && Objects.equal(this.adminStateUp, that.adminStateUp) && Objects.equal(this.status, that.status)\n            && Objects.equal(this.statusDescription, that.statusDescription);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, tenantId, name, description, subnetId, address, portId, protocol, protocolPort,\n            poolId, sessionPersistence, connectionLimit, adminStateUp, status, statusDescription);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).add(\"id\", id).add(\"tenantId\", tenantId).add(\"name\", name)\n            .add(\"description\", description).add(\"subnetId\", subnetId).add(\"address\", address).add(\"portId\", portId)\n            .add(\"protocol\", protocol).add(\"protocolPort\", protocolPort).add(\"poolId\", poolId)\n            .add(\"sessionPersistence\", sessionPersistence).add(\"connectionLimit\", connectionLimit)\n            .add(\"adminStateUp\", adminStateUp).add(\"status\", status).add(\"statusDescription\", statusDescription)\n            .toString();\n   }\n\n   /*\n    * Methods to get the Create and Update builders follow.\n    */\n\n   /**\n    * @return the Builder for creating a new VIP.\n    */\n   public static CreateBuilder createBuilder(String subnetId, Protocol protocol, Integer port, String poolId) {\n      return new CreateBuilder(subnetId, protocol, port, poolId);\n   }\n\n   /**\n    * @return the Builder for updating a VIP.\n    */\n   public static UpdateBuilder updateBuilder() {\n      return new UpdateBuilder();\n   }\n\n   private abstract static class Builder<ParameterizedBuilderType> {\n      protected VIP vip;\n\n      /**\n       * Default constructor.\n       */\n      private Builder() {\n         vip = new VIP();\n      }\n\n      protected abstract ParameterizedBuilderType self();\n\n      /**\n       * Provides the name for this VIP's Builder.\n       *\n       * @return the Builder.\n       * @see VIP#getName()\n       */\n      public ParameterizedBuilderType name(String name) {\n         vip.name = name;\n         return self();\n      }\n\n      /**\n       * Provides the description for this VIP's Builder.\n       *\n       * @return the Builder.\n       * @see VIP#getDescription()\n       */\n      public ParameterizedBuilderType description(String description) {\n         vip.description = description;\n         return self();\n      }\n\n      /**\n       * Provides the pool id for this VIP's Builder.\n       *\n       * @return the Builder.\n       * @see VIP#getPoolId()\n       */\n      public ParameterizedBuilderType poolId(String poolId) {\n         vip.poolId = poolId;\n         return self();\n      }\n\n      /**\n       * Provides the session persistence for this VIP's Builder.\n       *\n       * @return the Builder.\n       * @see VIP#getSessionPersistence()\n       */\n      public ParameterizedBuilderType sessionPersistence(SessionPersistence sessionPersistence) {\n         vip.sessionPersistence = sessionPersistence;\n         return self();\n      }\n\n      /**\n       * Provides the connection limit for this VIP's Builder.\n       *\n       * @return the Builder.\n       * @see VIP#getConnectionLimit()\n       */\n      public ParameterizedBuilderType connectionLimit(Integer connectionLimit) {\n         vip.connectionLimit = connectionLimit;\n         return self();\n      }\n\n      /**\n       * Provides the administrative state for this VIP's Builder.\n       *\n       * @return the Builder.\n       * @see VIP#getAdminStateUp()\n       */\n      public ParameterizedBuilderType adminStateUp(Boolean adminStateUp) {\n         vip.adminStateUp = adminStateUp;\n         return self();\n      }\n   }\n\n   /**\n    * Create builder (inheriting from Builder).\n    */\n   public static class CreateBuilder extends Builder<CreateBuilder> {\n      /**\n       * Supply required properties for creating a VIP's CreateBuilder\n       */\n      private CreateBuilder(String subnetId, Protocol protocol, Integer port, String poolId) {\n         subnetId(subnetId).protocol(protocol).protocolPort(port).poolId(poolId);\n      }\n\n      /**\n       * Provides the tenantId for this VIP's Builder. Admin-only.\n       * When keystone is enabled, it is not mandatory to specify tenant_id for resources in create requests, as the\n       * tenant identifier will be derived from the Authentication token. Please note that the default authorization\n       * settings only allow administrative users to create resources on behalf of a different tenant.\n       *\n       * @return the Builder.\n       * @see VIP#getTenantId()\n       */\n      public CreateBuilder tenantId(String tenantId) {\n         vip.tenantId = tenantId;\n         return self();\n      }\n\n      /**\n       * Provides the subnet id for this VIP's Builder.\n       *\n       * @return the Builder.\n       * @see VIP#getSubnetId()\n       */\n      public CreateBuilder subnetId(String subnetId) {\n         vip.subnetId = subnetId;\n         return self();\n      }\n\n      /**\n       * Provides the address for this VIP's Builder.\n       *\n       * @return the Builder.\n       * @see VIP#getAddress()\n       */\n      public CreateBuilder address(String address) {\n         vip.address = address;\n         return self();\n      }\n\n      /**\n       * Provides the protocol for this VIP's Builder.\n       *\n       * @return the Builder.\n       * @see VIP#getProtocol()\n       */\n      public CreateBuilder protocol(Protocol protocol) {\n         vip.protocol = protocol;\n         return self();\n      }\n\n      /**\n       * Provides the protocol port for this VIP's Builder.\n       *\n       * @return the Builder.\n       * @see VIP#getProtocolPort()\n       */\n      public CreateBuilder protocolPort(Integer protocolPort) {\n         vip.protocolPort = protocolPort;\n         return self();\n      }\n\n      /**\n       * @return a CreateVIP constructed with this Builder.\n       */\n      public CreateVIP build() {\n         return new CreateVIP(vip);\n      }\n\n      @Override\n      protected CreateBuilder self() {\n         return this;\n      }\n   }\n\n   /**\n    * Update builder (inheriting from Builder).\n    */\n   public static class UpdateBuilder extends Builder<UpdateBuilder> {\n      /**\n       * Supply required properties for creating a VIP's UpdateBuilder.\n       */\n      private UpdateBuilder() {\n      }\n\n      /**\n       * @return a UpdateVIP constructed with this Builder.\n       */\n      public UpdateVIP build() {\n         return new UpdateVIP(vip);\n      }\n\n      @Override\n      protected UpdateBuilder self() {\n         return this;\n      }\n   }\n\n   /**\n    * Create options - extend the domain class, passed to API create calls.\n    * Essentially the same as the domain class. Ensure validation and safe typing.\n    */\n   public static class CreateVIP extends VIP {\n      /**\n       * Copy constructor.\n       *\n       * @param vip the VIP to copy from.\n       */\n      private CreateVIP(VIP vip) {\n         super(vip);\n      }\n   }\n\n   /**\n    * Update options - extend the domain class, passed to API update calls.\n    * Essentially the same as the domain class. Ensure validation and safe typing.\n    */\n   public static class UpdateVIP extends VIP {\n      /**\n       * Copy constructor.\n       *\n       * @param vip the VIP to copy from.\n       */\n      private UpdateVIP(VIP vip) {\n         super(vip);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/domain/lbaas/v1/VIPs.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.domain.lbaas.v1;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.PaginatedCollection;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * A collection of of Neutron LBaaS v1 VIPs.\n */\npublic class VIPs extends PaginatedCollection<VIP> {\n   public static final VIPs EMPTY = new VIPs(ImmutableSet.<VIP> of(), ImmutableSet.<Link> of());\n\n   @ConstructorProperties({ \"vips\", \"vips_links\" })\n   protected VIPs(Iterable<VIP> vips, Iterable<Link> vipsLinks) {\n      super(vips, vipsLinks);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/extensions/ExtensionNamespaces.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.extensions;\n\n/**\n * Extension Namespaces for OpenStack Networking (Neutron).\n */\npublic final class ExtensionNamespaces {\n   /**\n    * Neutron Layer-3 Router Extension\n    */\n   public static final String L3_ROUTER = \"http://docs.openstack.org/ext/neutron/router/api/v1.0\";\n   /**\n    * Neutron Security Groups Extension\n    */\n   public static final String SECURITY_GROUPS = \"http://docs.openstack.org/ext/securitygroups/api/v2.0\";\n   /**\n    * LBaaS Extension.\n    */\n   public static final String LBAAS = \"http://wiki.openstack.org/neutron/LBaaS/API_1.0\";\n   /**\n    * FWaaS Extension.\n    */\n   public static final String FWAAS = \"http://wiki.openstack.org/Neutron/FWaaS/API_1.0\";\n\n   private ExtensionNamespaces() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/extensions/FWaaSApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.extensions;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyPagedIterableOnNotFoundOr404;\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.collect.PagedIterable;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.keystone.v2_0.KeystoneFallbacks.EmptyPaginatedCollectionOnNotFoundOr404;\nimport org.jclouds.openstack.neutron.v2.domain.CreateFirewall;\nimport org.jclouds.openstack.neutron.v2.domain.CreateFirewallPolicy;\nimport org.jclouds.openstack.neutron.v2.domain.CreateFirewallRule;\nimport org.jclouds.openstack.neutron.v2.domain.Firewall;\nimport org.jclouds.openstack.neutron.v2.domain.FirewallPolicy;\nimport org.jclouds.openstack.neutron.v2.domain.FirewallRule;\nimport org.jclouds.openstack.neutron.v2.domain.UpdateFirewall;\nimport org.jclouds.openstack.neutron.v2.domain.UpdateFirewallPolicy;\nimport org.jclouds.openstack.neutron.v2.domain.UpdateFirewallRule;\nimport org.jclouds.openstack.neutron.v2.functions.FirewallPolicyToPagedIterable;\nimport org.jclouds.openstack.neutron.v2.functions.FirewallRuleToPagedIterable;\nimport org.jclouds.openstack.neutron.v2.functions.FirewallToPagedIterable;\nimport org.jclouds.openstack.neutron.v2.functions.ParseFirewallPolicies;\nimport org.jclouds.openstack.neutron.v2.functions.ParseFirewallRules;\nimport org.jclouds.openstack.neutron.v2.functions.ParseFirewalls;\nimport org.jclouds.openstack.v2_0.ServiceType;\nimport org.jclouds.openstack.v2_0.domain.PaginatedCollection;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\nimport org.jclouds.openstack.v2_0.services.Extension;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.Transform;\nimport org.jclouds.rest.annotations.WrapWith;\n\nimport com.google.common.annotations.Beta;\n\n/**\n * The FWaaS extension provides OpenStack users with the ability to deploy firewalls to protect their networks.\n * <p/>\n *\n * @see <a href=\n *      \"http://specs.openstack.org/openstack/neutron-specs/specs/api/firewall_as_a_service__fwaas_.html\">api doc</a>\n * @see <a href=\n *      \"http://git.openstack.org/cgit/openstack/neutron-fwaas/tree/neutron_fwaas/extensions/firewall.py\">extension info</a>\n */\n@Beta\n@Path(\"/fw\")\n@RequestFilters(AuthenticateRequest.class)\n@Consumes(MediaType.APPLICATION_JSON)\n@Extension(of = ServiceType.NETWORK, namespace = ExtensionNamespaces.FWAAS, name = \"Firewall service\", alias = \"fwaas\")\npublic interface FWaaSApi {\n\n   /**\n    * Returns the list of all routers currently defined in Neutron for the current tenant. The list provides the unique\n    * identifier of each firewall configured for the tenant\n    *\n    * @return the list of all firewall references configured for the tenant.\n    */\n   @Named(\"fw:list\")\n   @GET\n   @Transform(FirewallToPagedIterable.class)\n   @ResponseParser(ParseFirewalls.class)\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   @Path(\"/firewalls\")\n   PagedIterable<Firewall> list();\n\n   /**\n    * @return the list of all firewall references configured for the tenant.\n    */\n   @Named(\"firewall:list\")\n   @GET\n   @ResponseParser(ParseFirewalls.class)\n   @Fallback(EmptyPaginatedCollectionOnNotFoundOr404.class)\n   @Path(\"/firewalls\")\n   PaginatedCollection<Firewall> list(PaginationOptions options);\n\n   /**\n    * Returns the details for a specific firewall.\n    *\n    * @param id the id of the firewall to return\n    * @return firewall or empty if not found\n    */\n   @Named(\"firewall:get\")\n   @GET\n   @Path(\"/firewalls/{id}\")\n   @SelectJson(\"firewall\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Firewall get(@PathParam(\"id\") String id);\n\n   /**\n    * Create a new firewall\n    *\n    * @param firewall Options for creating a firewall\n    * @return the newly created firewall\n    */\n   @Named(\"firewall:create\")\n   @POST\n   @SelectJson(\"firewall\")\n   @Path(\"/firewalls\")\n   Firewall create(@WrapWith(\"firewall\") CreateFirewall firewall);\n\n   /**\n    * Update a firewall\n    *\n    * @param id the id of the firewall to update\n    * @param updateFirewall Contains only the attributes to update\n    * @return The modified firewall\n    */\n   @Named(\"firewall:update\")\n   @PUT\n   @Path(\"/firewalls/{id}\")\n   @SelectJson(\"firewall\")\n   Firewall update(@PathParam(\"id\") String id, @WrapWith(\"firewall\") UpdateFirewall updateFirewall);\n\n   /**\n    * Deletes the specified firewall\n    *\n    * @param id the id of the firewall to delete\n    * @return true if delete successful, false if not\n    */\n   @Named(\"firewall:delete\")\n   @DELETE\n   @Path(\"/firewalls/{id}\")\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean delete(@PathParam(\"id\") String id);\n\n   @Named(\"firewall:createPolicy\")\n   @POST\n   @SelectJson(\"firewall_policy\")\n   @Path(\"/firewall_policies\")\n   FirewallPolicy createFirewallPolicy(@WrapWith(\"firewall_policy\") CreateFirewallPolicy firewallPolicy);\n\n   @Named(\"firewall:listPolicies\")\n   @GET\n   @Transform(FirewallPolicyToPagedIterable.class)\n   @ResponseParser(ParseFirewallPolicies.class)\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   @Path(\"/firewall_policies\")\n   PagedIterable<FirewallPolicy> listFirewallPolicies();\n\n   @Named(\"firewall:listPolicies\")\n   @GET\n   @ResponseParser(ParseFirewallPolicies.class)\n   @Fallback(EmptyPaginatedCollectionOnNotFoundOr404.class)\n   @Path(\"/firewall_policies\")\n   PaginatedCollection<FirewallPolicy> listFirewallPolicies(PaginationOptions options);\n\n   @Named(\"firewall:getPolicy\")\n   @GET\n   @SelectJson(\"firewall_policy\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Path(\"/firewall_policies/{id}\")\n   FirewallPolicy getFirewallPolicy(@PathParam(\"id\") String id);\n\n   @Named(\"firewall:updatePolicy\")\n   @PUT\n   @SelectJson(\"firewall_policy\")\n   @Path(\"/firewall_policies/{id}\")\n   FirewallPolicy updateFirewallPolicy(@PathParam(\"id\") String id, @WrapWith(\"firewall_policy\") UpdateFirewallPolicy updateFirewallPolicy);\n\n   @Named(\"firewall:deletePolicy\")\n   @DELETE\n   @Path(\"/firewall_policies/{id}\")\n   boolean deleteFirewallPolicy(@PathParam(\"id\") String id);\n\n   @Named(\"firewall:createFirewallRule\")\n   @POST\n   @SelectJson(\"firewall_rule\")\n   @Path(\"/firewall_rules\")\n   FirewallRule createFirewallRule(@WrapWith(\"firewall_rule\") CreateFirewallRule firewallRule);\n\n   @Named(\"firewall:listFirewallRules\")\n   @GET\n   @Transform(FirewallRuleToPagedIterable.class)\n   @ResponseParser(ParseFirewallRules.class)\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   @Path(\"/firewall_rules\")\n   PagedIterable<FirewallRule> listFirewallRules();\n\n   @Named(\"firewall:listFirewallRules\")\n   @GET\n   @ResponseParser(ParseFirewallRules.class)\n   @Fallback(EmptyPaginatedCollectionOnNotFoundOr404.class)\n   @Path(\"/firewall_rules\")\n   PaginatedCollection<FirewallRule> listFirewallRules(PaginationOptions options);\n\n   @Named(\"firewall:getFirewallRule\")\n   @GET\n   @Path(\"/firewall_rules/{id}\")\n   @SelectJson(\"firewall_rule\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   FirewallRule getFirewallRule(@PathParam(\"id\") String firewallRuleId);\n\n   @Named(\"firewall:updateFirewallRule\")\n   @PUT\n   @Path(\"/firewall_rules/{id}\")\n   @SelectJson(\"firewall_rule\")\n   FirewallRule updateFirewallRule(@PathParam(\"id\") String id, @WrapWith(\"firewall_rule\") UpdateFirewallRule updateFirewallRule);\n\n   @Named(\"firewall:deleteFirewallRule\")\n   @DELETE\n   @Path(\"/firewall_rules/{id}\")\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean deleteFirewallRule(@PathParam(\"id\") String id);\n\n   @Named(\"firewall:insertFirewallRuleToPolicy\")\n   @PUT\n   @Path(\"/firewall_policies/{id}/insert_rule\")\n   FirewallPolicy insertFirewallRuleToPolicy(@PathParam(\"id\") String policyId, @WrapWith(\"firewall_rule_id\") String firewallRuleId);\n\n   @Named(\"firewall:removeFirewallRuleFromPolicy\")\n   @DELETE\n   @Path(\"/firewall_policies/{id}/remove_rule\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   FirewallPolicy removeFirewallRuleFromPolicy(@PathParam(\"id\") String policyId, @WrapWith(\"firewall_rule_id\") String firewallRuleId);\n\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/extensions/RouterApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.extensions;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyPagedIterableOnNotFoundOr404;\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.collect.PagedIterable;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.neutron.v2.domain.Router;\nimport org.jclouds.openstack.neutron.v2.domain.RouterInterface;\nimport org.jclouds.openstack.neutron.v2.domain.Routers;\nimport org.jclouds.openstack.neutron.v2.fallbacks.EmptyRoutersFallback;\nimport org.jclouds.openstack.neutron.v2.functions.ParseRouters;\nimport org.jclouds.openstack.neutron.v2.functions.RouterToPagedIterable;\nimport org.jclouds.openstack.neutron.v2.options.EmptyOptions;\nimport org.jclouds.openstack.v2_0.ServiceType;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\nimport org.jclouds.openstack.v2_0.services.Extension;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.Transform;\nimport org.jclouds.rest.annotations.WrapWith;\n\nimport com.google.common.annotations.Beta;\n\n/**\n * Provides access to Router operations for the OpenStack Networking (Neutron) v2 API.\n * <p/>\n * A logical entity for forwarding packets across internal subnets and NATting them on external\n * networks through an appropriate external gateway.\n *\n * @see <a href=\n *      \"http://docs.openstack.org/api/openstack-network/2.0/content/router_ext.html\">api doc</a>\n *\n * @see <a href=\n * \"https://github.com/openstack/neutron/tree/master/neutron/extensions\">neutron extensions</a>\n */\n@Beta\n@Path(\"/routers\")\n@RequestFilters(AuthenticateRequest.class)\n@Consumes(MediaType.APPLICATION_JSON)\n@Extension(of = ServiceType.NETWORK, namespace = ExtensionNamespaces.L3_ROUTER, name = \"Neutron L3 Router\", alias = \"router\")\npublic interface RouterApi {\n\n   /**\n    * Returns the list of all routers currently defined in Neutron for the current tenant. The list provides the unique\n    * identifier of each router configured for the tenant\n    *\n    * @return the list of all router references configured for the tenant.\n    */\n   @Named(\"router:list\")\n   @GET\n   @Transform(RouterToPagedIterable.class)\n   @ResponseParser(ParseRouters.class)\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   PagedIterable<Router> list();\n\n   /**\n    * @see <a href=\"http://docs.openstack.org/api/openstack-network/2.0/content/pagination.html\">api doc</a>\n    */\n   @Named(\"router:list\")\n   @GET\n   @ResponseParser(ParseRouters.class)\n   @Fallback(EmptyRoutersFallback.class)\n   Routers list(PaginationOptions options);\n\n   /**\n    * Returns a Routers collection that should contain a single router with the id requested.\n    *\n    * @param id the id of the router to return\n    * @return Routers collection or empty if not found\n    */\n   @Named(\"router:get\")\n   @GET\n   @Path(\"/{id}\")\n   @SelectJson(\"router\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Router get(@PathParam(\"id\") String id);\n\n   /**\n    * Create a new router\n    *\n    * @param router Options for creating a router\n    * @return the newly created router\n    */\n   @Named(\"router:create\")\n   @POST\n   @SelectJson(\"router\")\n   Router create(@WrapWith(\"router\") Router.CreateRouter router);\n\n   /**\n    * Update a router\n    *\n    * @param id the id of the router to update\n    * @param router Contains only the attributes to update\n    * @return The modified router\n    */\n   @Named(\"router:update\")\n   @PUT\n   @Path(\"/{id}\")\n   @SelectJson(\"router\")\n   Router update(@PathParam(\"id\") String id, @WrapWith(\"router\") Router.UpdateRouter router);\n\n   /**\n    * Deletes the specified router\n    *\n    * @param id the id of the router to delete\n    * @return true if delete successful, false if not\n    */\n   @Named(\"router:delete\")\n   @DELETE\n   @Path(\"/{id}\")\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean delete(@PathParam(\"id\") String id);\n\n   /**\n    * Add a interface to a router to connect to the specified subnet\n    *\n    * @param routerId the id of the router to create the interface at\n    * @param subnetId the id of the subnet to connect with the interface\n    * @return the newly-created router interface\n    */\n   @Named(\"router:addInterfaceForSubnet\")\n   @PUT\n   @Path(\"/{id}/add_router_interface\")\n   @MapBinder(EmptyOptions.class)\n   RouterInterface addInterfaceForSubnet(@PathParam(\"id\") String routerId, @PayloadParam(\"subnet_id\") String subnetId);\n\n   /**\n    * Add a interface to a router to connect to the specified port\n    *\n    * @param routerId the id of the router to create the interface at\n    * @param portId the id of the port to connect with the interface\n    * @return the newly-created router interface\n    */\n   @Named(\"router:addInterfaceForPort\")\n   @PUT\n   @Path(\"/{id}/add_router_interface\")\n   @MapBinder(EmptyOptions.class)\n   RouterInterface addInterfaceForPort(@PathParam(\"id\") String routerId, @PayloadParam(\"port_id\") String portId);\n\n   /**\n    * Remove the interface where the specified subnet is connected to\n    *\n    * @param routerId the id of the router to remove the interface from\n    * @param subnetId the id of the subnet to disconnect from the interface\n    */\n   @Named(\"router:removeInterfaceForSubnet\")\n   @PUT\n   @Path(\"/{id}/remove_router_interface\")\n   @MapBinder(EmptyOptions.class)\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean removeInterfaceForSubnet(@PathParam(\"id\") String routerId, @PayloadParam(\"subnet_id\") String subnetId);\n\n   /**\n    * Remove the interface where the specified port is connected to\n    *\n    * @param routerId the id of the router to remove the interface from\n    * @param portId the id of the port to disconnect from the interface\n    */\n   @Named(\"router:removeInterfaceForPort\")\n   @PUT\n   @Path(\"/{id}/remove_router_interface\")\n   @MapBinder(EmptyOptions.class)\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean removeInterfaceForPort(@PathParam(\"id\") String routerId, @PayloadParam(\"port_id\") String portId);\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/extensions/lbaas/v1/LBaaSApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.extensions.lbaas.v1;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyPagedIterableOnNotFoundOr404;\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.collect.PagedIterable;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.HealthMonitor;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.HealthMonitors;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.Member;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.Members;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.Pool;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.Pools;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.VIP;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.VIPs;\nimport org.jclouds.openstack.neutron.v2.extensions.ExtensionNamespaces;\nimport org.jclouds.openstack.neutron.v2.fallbacks.lbaas.v1.EmptyHealthMonitorsFallback;\nimport org.jclouds.openstack.neutron.v2.fallbacks.lbaas.v1.EmptyMembersFallback;\nimport org.jclouds.openstack.neutron.v2.fallbacks.lbaas.v1.EmptyPoolsFallback;\nimport org.jclouds.openstack.neutron.v2.fallbacks.lbaas.v1.EmptyVIPsFallback;\nimport org.jclouds.openstack.neutron.v2.functions.lbaas.v1.HealthMonitorsToPagedIterable;\nimport org.jclouds.openstack.neutron.v2.functions.lbaas.v1.MembersToPagedIterable;\nimport org.jclouds.openstack.neutron.v2.functions.lbaas.v1.ParseHealthMonitors;\nimport org.jclouds.openstack.neutron.v2.functions.lbaas.v1.ParseMembers;\nimport org.jclouds.openstack.neutron.v2.functions.lbaas.v1.ParsePools;\nimport org.jclouds.openstack.neutron.v2.functions.lbaas.v1.ParseVIPs;\nimport org.jclouds.openstack.neutron.v2.functions.lbaas.v1.PoolsToPagedIterable;\nimport org.jclouds.openstack.neutron.v2.functions.lbaas.v1.VIPsToPagedIterable;\nimport org.jclouds.openstack.v2_0.ServiceType;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\nimport org.jclouds.openstack.v2_0.services.Extension;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.Transform;\nimport org.jclouds.rest.annotations.WrapWith;\n\nimport com.google.common.annotations.Beta;\n\n/**\n * Provides access to load-balancing operations for the OpenStack Networking (Neutron) v2 API.\n * <p/>\n * LBaaS v1 is an extension to load-balance the traffic between instances and external networks.\n */\n@Beta\n@Extension(of = ServiceType.NETWORK, namespace = ExtensionNamespaces.LBAAS)\n@Path(\"/lb\")\n@RequestFilters(AuthenticateRequest.class)\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface LBaaSApi {\n\n   /**\n    * Returns a list of VIPs to which the tenant has access. Default policy settings return only\n    * those VIPs that are owned by the tenant who submits the request, unless the request is submitted by an\n    * user with administrative rights.\n    *\n    * @return the list of all VIP references configured for the tenant.\n    */\n   @Named(\"vip:list\")\n   @GET\n   @Path(\"/vips\")\n   @Transform(VIPsToPagedIterable.class)\n   @ResponseParser(ParseVIPs.class)\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   PagedIterable<VIP> listVIPs();\n\n   /**\n    * @return the list of all VIP references configured for the tenant.\n    */\n   @Named(\"vip:list\")\n   @GET\n   @Path(\"/vips\")\n   @ResponseParser(ParseVIPs.class)\n   @Fallback(EmptyVIPsFallback.class)\n   VIPs listVIPs(PaginationOptions options);\n\n   /**\n    * Returns the details for a specific VIP.\n    *\n    * @param id the id of the VIP to return.\n    * @return VIP or null if not found.\n    */\n   @Named(\"vip:get\")\n   @GET\n   @Path(\"/vips/{id}\")\n   @SelectJson(\"vip\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   VIP getVIP(@PathParam(\"id\") String id);\n\n   /**\n    * Creates a new VIP.\n    *\n    * @param vip describes the VIP to be created.\n    * @return a reference of the newly-created VIP.\n    */\n   @Named(\"vip:create\")\n   @POST\n   @Path(\"/vips\")\n   @SelectJson(\"vip\")\n   VIP createVIP(@WrapWith(\"vip\") VIP.CreateVIP vip);\n\n   /**\n    * Update a VIP.\n    *\n    * @param id the id of the VIP to update.\n    * @param vip the VIP's attributes to update.\n    * @return a reference of the updated VIP.\n    */\n   @Named(\"vip:update\")\n   @PUT\n   @Path(\"/vips/{id}\")\n   @SelectJson(\"vip\")\n   VIP updateVIP(@PathParam(\"id\") String id, @WrapWith(\"vip\") VIP.UpdateVIP vip);\n\n   /**\n    * Deletes the specified VIP.\n    *\n    * @param id the id of the VIP to delete.\n    * @return true if delete successful, false if not.\n    */\n   @Named(\"vip:delete\")\n   @DELETE\n   @Path(\"/vips/{id}\")\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean deleteVIP(@PathParam(\"id\") String id);\n\n   /**\n    * Returns a list of Pools to which the tenant has access. Default policy settings return only\n    * those Pools that are owned by the tenant who submits the request, unless the request is submitted by an\n    * user with administrative rights.\n    *\n    * @return the list of all Pool references configured for the tenant.\n    */\n   @Named(\"pool:list\")\n   @GET\n   @Path(\"/pools\")\n   @Transform(PoolsToPagedIterable.class)\n   @ResponseParser(ParsePools.class)\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   PagedIterable<Pool> listPools();\n\n   /**\n    * @return the list of all Pool references configured for the tenant.\n    */\n   @Named(\"pool:list\")\n   @GET\n   @Path(\"/pools\")\n   @ResponseParser(ParsePools.class)\n   @Fallback(EmptyPoolsFallback.class)\n   Pools listPools(PaginationOptions options);\n\n   /**\n    * Returns the details for a specific Pool.\n    *\n    * @param id the id of the Pool to return.\n    * @return Pool or null if not found.\n    */\n   @Named(\"pool:get\")\n   @GET\n   @Path(\"/pools/{id}\")\n   @SelectJson(\"pool\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Pool getPool(@PathParam(\"id\") String id);\n\n   /**\n    * Creates a new Pool.\n    *\n    * @param pool describes the Pool to be created.\n    * @return a reference of the newly-created Pool.\n    */\n   @Named(\"pool:create\")\n   @POST\n   @Path(\"/pools\")\n   @SelectJson(\"pool\")\n   Pool createPool(@WrapWith(\"pool\") Pool.CreatePool pool);\n\n   /**\n    * Update a Pool.\n    *\n    * @param id the id of the Pool to update.\n    * @param pool the Pool's attributes to update.\n    * @return a reference of the updated Pool.\n    */\n   @Named(\"pool:update\")\n   @PUT\n   @Path(\"/pools/{id}\")\n   @SelectJson(\"pool\")\n   Pool updatePool(@PathParam(\"id\") String id, @WrapWith(\"pool\") Pool.UpdatePool pool);\n\n   /**\n    * Deletes the specified Pool.\n    *\n    * @param id the id of the Pool to delete.\n    * @return true if delete successful, false if not.\n    */\n   @Named(\"pool:delete\")\n   @DELETE\n   @Path(\"/pools/{id}\")\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean deletePool(@PathParam(\"id\") String id);\n\n   /**\n    * Returns a list of Members to which the tenant has access. Default policy settings return only\n    * those Members that are owned by the tenant who submits the request, unless the request is submitted by an\n    * user with administrative rights.\n    *\n    * @return the list of all Member references configured for the tenant.\n    */\n   @Named(\"member:list\")\n   @GET\n   @Path(\"/members\")\n   @Transform(MembersToPagedIterable.class)\n   @ResponseParser(ParseMembers.class)\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   PagedIterable<Member> listMembers();\n\n   /**\n    * @return the list of all Member references configured for the tenant.\n    */\n   @Named(\"member:list\")\n   @GET\n   @Path(\"/members\")\n   @ResponseParser(ParseMembers.class)\n   @Fallback(EmptyMembersFallback.class)\n   Members listMembers(PaginationOptions options);\n\n   /**\n    * Returns the details for a specific Member.\n    *\n    * @param id the id of the Member to return.\n    * @return Member or null if not found.\n    */\n   @Named(\"member:get\")\n   @GET\n   @Path(\"/members/{id}\")\n   @SelectJson(\"member\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Member getMember(@PathParam(\"id\") String id);\n\n   /**\n    * Creates a new Member.\n    *\n    * @param member describes the Member to be created.\n    * @return a reference of the newly-created Member.\n    */\n   @Named(\"member:create\")\n   @POST\n   @Path(\"/members\")\n   @SelectJson(\"member\")\n   Member createMember(@WrapWith(\"member\") Member.CreateMember member);\n\n   /**\n    * Update a Member.\n    *\n    * @param id the id of the Member to update.\n    * @param member the Member's attributes to update.\n    * @return a reference of the updated Member.\n    */\n   @Named(\"member:update\")\n   @PUT\n   @Path(\"/members/{id}\")\n   @SelectJson(\"member\")\n   Member updateMember(@PathParam(\"id\") String id, @WrapWith(\"member\") Member.UpdateMember member);\n\n   /**\n    * Deletes the specified Member.\n    *\n    * @param id the id of the Member to delete.\n    * @return true if delete successful, false if not.\n    */\n   @Named(\"member:delete\")\n   @DELETE\n   @Path(\"/members/{id}\")\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean deleteMember(@PathParam(\"id\") String id);\n\n   /**\n    * Returns a list of HealthMonitors to which the tenant has access. Default policy settings return only\n    * those HealthMonitors that are owned by the tenant who submits the request, unless the request is submitted by an\n    * user with administrative rights.\n    *\n    * @return the list of all HealthMonitor references configured for the tenant.\n    */\n   @Named(\"health_monitor:list\")\n   @GET\n   @Path(\"/health_monitors\")\n   @Transform(HealthMonitorsToPagedIterable.class)\n   @ResponseParser(ParseHealthMonitors.class)\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   PagedIterable<HealthMonitor> listHealthMonitors();\n\n   /**\n    * @return the list of all HealthMonitor references configured for the tenant.\n    */\n   @Named(\"health_monitor:list\")\n   @GET\n   @Path(\"/health_monitors\")\n   @ResponseParser(ParseHealthMonitors.class)\n   @Fallback(EmptyHealthMonitorsFallback.class)\n   HealthMonitors listHealthMonitors(PaginationOptions options);\n\n   /**\n    * Returns the details for a specific HealthMonitor.\n    *\n    * @param id the id of the HealthMonitor to return.\n    * @return Health Monitor or null if not found.\n    */\n   @Named(\"health_monitor:get\")\n   @GET\n   @Path(\"/health_monitors/{id}\")\n   @SelectJson(\"health_monitor\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   HealthMonitor getHealthMonitor(@PathParam(\"id\") String id);\n\n   /**\n    * Creates a new HealthMonitor.\n    *\n    * @param healthMonitor describes the HealthMonitor to be created.\n    * @return a reference of the newly-created HealthMonitor.\n    */\n   @Named(\"health_monitor:create\")\n   @POST\n   @Path(\"/health_monitors\")\n   @SelectJson(\"health_monitor\")\n   HealthMonitor createHealthMonitor(@WrapWith(\"health_monitor\") HealthMonitor.CreateHealthMonitor healthMonitor);\n\n   /**\n    * Update a HealthMonitor.\n    *\n    * @param id the id of the HealthMonitor to update.\n    * @param healthMonitor the HealthMonitor's attributes to update.\n    * @return a reference of the updated HealthMonitor.\n    */\n   @Named(\"health_monitor:update\")\n   @PUT\n   @Path(\"/health_monitors/{id}\")\n   @SelectJson(\"health_monitor\")\n   HealthMonitor updateHealthMonitor(@PathParam(\"id\") String id,\n         @WrapWith(\"health_monitor\") HealthMonitor.UpdateHealthMonitor healthMonitor);\n\n   /**\n    * Deletes the specified Health Monitor.\n    *\n    * @param id the id of the Health Monitor to delete.\n    * @return true if delete successful, false if not.\n    */\n   @Named(\"health_monitor:delete\")\n   @DELETE\n   @Path(\"/health_monitors/{id}\")\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean deleteHealthMonitor(@PathParam(\"id\") String id);\n\n   /**\n    * Associate a HealthMonitor to a Pool.\n    *\n    * @param poolId the id of the Pool to associate.\n    * @param healthMonitorId the id of the HealthMonitor to associate.\n    * @return the newly associated HealthMonitor.\n    */\n   @Named(\"pool:associate_health_monitor\")\n   @POST\n   @Path(\"/pools/{pool-id}/health_monitors\")\n   @SelectJson(\"health_monitor\")\n   @Payload(\"%7B\\\"health_monitor\\\":%7B\\\"id\\\":\\\"{healthMonitorId}\\\"%7D%7D\")\n   @Produces(MediaType.APPLICATION_JSON)\n   HealthMonitor associateHealthMonitor(@PathParam(\"pool-id\") String poolId,\n         @PayloadParam(\"healthMonitorId\") String healthMonitorId);\n\n   /**\n    * Disassociate a HealthMonitor from a Pool.\n    *\n    * @param poolId the id of the Pool to disassociate.\n    * @param healthMonitorId the id of the HealthMonitor to disassociate.\n    * @return true if disassociate successful, false if not.\n    */\n   @Named(\"pool:disassociate_health_monitor\")\n   @DELETE\n   @Path(\"/pools/{pool-id}/health_monitors/{health-monitor-id}\")\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean disassociateHealthMonitor(@PathParam(\"pool-id\") String poolId,\n         @PathParam(\"health-monitor-id\") String healthMonitorId);\n\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/fallbacks/EmptyFloatingIPsFallback.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.openstack.neutron.v2.fallbacks;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Throwables.propagate;\nimport static org.jclouds.http.HttpUtils.contains404;\nimport static org.jclouds.util.Throwables2.getFirstThrowableOfType;\n\nimport org.jclouds.Fallback;\nimport org.jclouds.openstack.neutron.v2.domain.FloatingIPs;\nimport org.jclouds.rest.ResourceNotFoundException;\n\npublic class EmptyFloatingIPsFallback implements Fallback<FloatingIPs> {\n   @Override\n   public FloatingIPs createOrPropagate(Throwable t) throws Exception {\n      if ((getFirstThrowableOfType(checkNotNull(t, \"throwable\"), ResourceNotFoundException.class) != null)\n            || contains404(t)) {\n         return FloatingIPs.EMPTY;\n      }\n      throw propagate(t);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/fallbacks/EmptyNetworksFallback.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.openstack.neutron.v2.fallbacks;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Throwables.propagate;\nimport static org.jclouds.http.HttpUtils.contains404;\nimport static org.jclouds.util.Throwables2.getFirstThrowableOfType;\n\nimport org.jclouds.Fallback;\nimport org.jclouds.openstack.neutron.v2.domain.Networks;\nimport org.jclouds.rest.ResourceNotFoundException;\n\npublic class EmptyNetworksFallback implements Fallback<Networks> {\n   @Override\n   public Networks createOrPropagate(Throwable t) throws Exception {\n      if ((getFirstThrowableOfType(checkNotNull(t, \"throwable\"), ResourceNotFoundException.class) != null)\n            || contains404(t)) {\n         return Networks.EMPTY;\n      }\n      throw propagate(t);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/fallbacks/EmptyPortsFallback.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.openstack.neutron.v2.fallbacks;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Throwables.propagate;\nimport static org.jclouds.http.HttpUtils.contains404;\nimport static org.jclouds.util.Throwables2.getFirstThrowableOfType;\n\nimport org.jclouds.Fallback;\nimport org.jclouds.openstack.neutron.v2.domain.Ports;\nimport org.jclouds.rest.ResourceNotFoundException;\n\npublic class EmptyPortsFallback implements Fallback<Ports> {\n   @Override\n   public Ports createOrPropagate(Throwable t) throws Exception {\n      if ((getFirstThrowableOfType(checkNotNull(t, \"throwable\"), ResourceNotFoundException.class) != null)\n            || contains404(t)) {\n         return Ports.EMPTY;\n      }\n      throw propagate(t);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/fallbacks/EmptyRoutersFallback.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.openstack.neutron.v2.fallbacks;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Throwables.propagate;\nimport static org.jclouds.http.HttpUtils.contains404;\nimport static org.jclouds.util.Throwables2.getFirstThrowableOfType;\n\nimport org.jclouds.Fallback;\nimport org.jclouds.openstack.neutron.v2.domain.Routers;\nimport org.jclouds.rest.ResourceNotFoundException;\n\npublic class EmptyRoutersFallback implements Fallback<Routers> {\n   @Override\n   public Routers createOrPropagate(Throwable t) throws Exception {\n      if ((getFirstThrowableOfType(checkNotNull(t, \"throwable\"), ResourceNotFoundException.class) != null)\n            || contains404(t)) {\n         return Routers.EMPTY;\n      }\n      throw propagate(t);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/fallbacks/EmptyRulesFallback.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.openstack.neutron.v2.fallbacks;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Throwables.propagate;\nimport static org.jclouds.http.HttpUtils.contains404;\nimport static org.jclouds.util.Throwables2.getFirstThrowableOfType;\n\nimport org.jclouds.Fallback;\nimport org.jclouds.openstack.neutron.v2.domain.Rules;\nimport org.jclouds.rest.ResourceNotFoundException;\n\npublic class EmptyRulesFallback implements Fallback<Rules> {\n   @Override\n   public Rules createOrPropagate(Throwable t) throws Exception {\n      if ((getFirstThrowableOfType(checkNotNull(t, \"throwable\"), ResourceNotFoundException.class) != null)\n            || contains404(t)) {\n         return Rules.EMPTY;\n      }\n      throw propagate(t);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/fallbacks/EmptySecurityGroupsFallback.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.openstack.neutron.v2.fallbacks;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Throwables.propagate;\nimport static org.jclouds.http.HttpUtils.contains404;\nimport static org.jclouds.util.Throwables2.getFirstThrowableOfType;\n\nimport org.jclouds.Fallback;\nimport org.jclouds.openstack.neutron.v2.domain.SecurityGroups;\nimport org.jclouds.rest.ResourceNotFoundException;\n\npublic class EmptySecurityGroupsFallback implements Fallback<SecurityGroups> {\n   @Override\n   public SecurityGroups createOrPropagate(Throwable t) throws Exception {\n      if ((getFirstThrowableOfType(checkNotNull(t, \"throwable\"), ResourceNotFoundException.class) != null)\n            || contains404(t)) {\n         return SecurityGroups.EMPTY;\n      }\n      throw propagate(t);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/fallbacks/EmptySubnetsFallback.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.openstack.neutron.v2.fallbacks;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Throwables.propagate;\nimport static org.jclouds.http.HttpUtils.contains404;\nimport static org.jclouds.util.Throwables2.getFirstThrowableOfType;\n\nimport org.jclouds.Fallback;\nimport org.jclouds.openstack.neutron.v2.domain.Subnets;\nimport org.jclouds.rest.ResourceNotFoundException;\n\npublic class EmptySubnetsFallback implements Fallback<Subnets> {\n   @Override\n   public Subnets createOrPropagate(Throwable t) throws Exception {\n      if ((getFirstThrowableOfType(checkNotNull(t, \"throwable\"), ResourceNotFoundException.class) != null)\n            || contains404(t)) {\n         return Subnets.EMPTY;\n      }\n      throw propagate(t);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/fallbacks/lbaas/v1/EmptyHealthMonitorsFallback.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.openstack.neutron.v2.fallbacks.lbaas.v1;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Throwables.propagate;\nimport static org.jclouds.http.HttpUtils.contains404;\nimport static org.jclouds.util.Throwables2.getFirstThrowableOfType;\n\nimport org.jclouds.Fallback;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.HealthMonitors;\nimport org.jclouds.rest.ResourceNotFoundException;\n\npublic class EmptyHealthMonitorsFallback implements Fallback<HealthMonitors> {\n   @Override\n   public HealthMonitors createOrPropagate(Throwable t) throws Exception {\n      if ((getFirstThrowableOfType(checkNotNull(t, \"throwable\"), ResourceNotFoundException.class) != null)\n            || contains404(t)) {\n         return HealthMonitors.EMPTY;\n      }\n      throw propagate(t);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/fallbacks/lbaas/v1/EmptyMembersFallback.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.openstack.neutron.v2.fallbacks.lbaas.v1;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Throwables.propagate;\nimport static org.jclouds.http.HttpUtils.contains404;\nimport static org.jclouds.util.Throwables2.getFirstThrowableOfType;\n\nimport org.jclouds.Fallback;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.Members;\nimport org.jclouds.rest.ResourceNotFoundException;\n\npublic class EmptyMembersFallback implements Fallback<Members> {\n   @Override\n   public Members createOrPropagate(Throwable t) throws Exception {\n      if ((getFirstThrowableOfType(checkNotNull(t, \"throwable\"), ResourceNotFoundException.class) != null)\n            || contains404(t)) {\n         return Members.EMPTY;\n      }\n      throw propagate(t);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/fallbacks/lbaas/v1/EmptyPoolsFallback.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.openstack.neutron.v2.fallbacks.lbaas.v1;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Throwables.propagate;\nimport static org.jclouds.http.HttpUtils.contains404;\nimport static org.jclouds.util.Throwables2.getFirstThrowableOfType;\n\nimport org.jclouds.Fallback;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.Pools;\nimport org.jclouds.rest.ResourceNotFoundException;\n\npublic class EmptyPoolsFallback implements Fallback<Pools> {\n   @Override\n   public Pools createOrPropagate(Throwable t) throws Exception {\n      if ((getFirstThrowableOfType(checkNotNull(t, \"throwable\"), ResourceNotFoundException.class) != null)\n            || contains404(t)) {\n         return Pools.EMPTY;\n      }\n      throw propagate(t);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/fallbacks/lbaas/v1/EmptyVIPsFallback.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.openstack.neutron.v2.fallbacks.lbaas.v1;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Throwables.propagate;\nimport static org.jclouds.http.HttpUtils.contains404;\nimport static org.jclouds.util.Throwables2.getFirstThrowableOfType;\n\nimport org.jclouds.Fallback;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.VIPs;\nimport org.jclouds.rest.ResourceNotFoundException;\n\npublic class EmptyVIPsFallback implements Fallback<VIPs> {\n   @Override\n   public VIPs createOrPropagate(Throwable t) throws Exception {\n      if ((getFirstThrowableOfType(checkNotNull(t, \"throwable\"), ResourceNotFoundException.class) != null)\n            || contains404(t)) {\n         return VIPs.EMPTY;\n      }\n      throw propagate(t);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/features/FloatingIPApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyPagedIterableOnNotFoundOr404;\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.collect.PagedIterable;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.neutron.v2.domain.FloatingIP;\nimport org.jclouds.openstack.neutron.v2.domain.FloatingIPs;\nimport org.jclouds.openstack.neutron.v2.fallbacks.EmptyFloatingIPsFallback;\nimport org.jclouds.openstack.neutron.v2.functions.FloatingIPsToPagedIterable;\nimport org.jclouds.openstack.neutron.v2.functions.ParseFloatingIPs;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.Transform;\nimport org.jclouds.rest.annotations.WrapWith;\n\nimport com.google.common.annotations.Beta;\n\n/**\n * Provides access to Floating IP operations for the OpenStack Networking (Neutron) v2 API.\n * <p/>\n * A floating IP is an IP address on an external network, which is associated with a specific port, and optionally a\n * specific IP address, on a private OpenStack Networking network. Therefore a floating IP allows access to an\n * instance on a private network from an external network. Floating IPs can only be defined on networks for which the\n * attribute floatingip:external (by the external network extension) has been set to True.\n */\n@Beta\n@Path(\"/floatingips\")\n@RequestFilters(AuthenticateRequest.class)\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface FloatingIPApi {\n\n   /**\n    * Returns a list of floating IPs to which the tenant has access. Default policy settings return only\n    * those floating IPs that are owned by the tenant who submits the request, unless the request is submitted by an\n    * user with administrative rights.\n    *\n    * @return the list of all floatingIP references configured for the tenant.\n    */\n   @Named(\"floatingip:list\")\n   @GET\n   @Transform(FloatingIPsToPagedIterable.class)\n   @ResponseParser(ParseFloatingIPs.class)\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   PagedIterable<FloatingIP> list();\n\n   /**\n    * @return the list of all floatingIP references configured for the tenant.\n    */\n   @Named(\"floatingip:list\")\n   @GET\n   @ResponseParser(ParseFloatingIPs.class)\n   @Fallback(EmptyFloatingIPsFallback.class)\n   FloatingIPs list(PaginationOptions options);\n\n   /**\n    * Returns the details for a specific floating IP.\n    *\n    * @param id the id of the floatingIP to return\n    * @return FloatingIPs collection or empty if not found\n    */\n   @Named(\"floatingip:get\")\n   @GET\n   @Path(\"/{id}\")\n   @SelectJson(\"floatingip\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   FloatingIP get(@PathParam(\"id\") String id);\n\n   /**\n    * Creates a floating IP.\n    *\n    * @param createFloatingIP Options for creating a Floating IP\n    * @return the newly created Floating IP\n    */\n   @Named(\"floatingip:create\")\n   @POST\n   @SelectJson(\"floatingip\")\n   FloatingIP create(@WrapWith(\"floatingip\") FloatingIP.CreateFloatingIP createFloatingIP);\n\n   /**\n    * Update a Floating IP\n    *\n    * @param id the id of the Floating IP to update\n    * @param updateFloatingIP Contains only the attributes to update\n    * @return The modified Floating IP\n    */\n   @Named(\"floatingip:update\")\n   @PUT\n   @Path(\"/{id}\")\n   @SelectJson(\"floatingip\")\n   FloatingIP update(@PathParam(\"id\") String id, @WrapWith(\"floatingip\") FloatingIP.UpdateFloatingIP updateFloatingIP);\n\n   /**\n    * Deletes the specified floatingIP\n    *\n    * @param id the id of the floatingIP to delete\n    * @return true if delete successful, false if not\n    */\n   @Named(\"floatingip:delete\")\n   @DELETE\n   @Path(\"/{id}\")\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean delete(@PathParam(\"id\") String id);\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/features/NetworkApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks;\nimport org.jclouds.Fallbacks.EmptyPagedIterableOnNotFoundOr404;\nimport org.jclouds.collect.PagedIterable;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.neutron.v2.domain.Network;\nimport org.jclouds.openstack.neutron.v2.domain.Networks;\nimport org.jclouds.openstack.neutron.v2.fallbacks.EmptyNetworksFallback;\nimport org.jclouds.openstack.neutron.v2.functions.NetworksToPagedIterable;\nimport org.jclouds.openstack.neutron.v2.functions.ParseNetworks;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.Transform;\nimport org.jclouds.rest.annotations.WrapWith;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Provides access to Network operations for the OpenStack Networking (Neutron) v2 API.\n * <p/>\n * Each tenant can define one or more networks. A network is a virtual isolated layer-2 broadcast domain reserved to the\n * tenant. A tenant can create several ports for a network, and plug virtual interfaces into these ports.\n *\n * @see <a href=\n *      \"http://docs.openstack.org/api/openstack-network/2.0/content/Networks.html\">api doc</a>\n */\n@Beta\n@Path(\"/networks\")\n@RequestFilters(AuthenticateRequest.class)\n@Consumes(MediaType.APPLICATION_JSON)\n@Produces(MediaType.APPLICATION_JSON)\npublic interface NetworkApi {\n\n   /**\n    * Returns all networks currently defined in Neutron for the current tenant.\n    *\n    * @return the list of all networks configured for the tenant\n    */\n   @Named(\"network:list\")\n   @GET\n   @ResponseParser(ParseNetworks.class)\n   @Transform(NetworksToPagedIterable.class)\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   PagedIterable<Network> list();\n\n   /**\n    * @see <a href=\"http://docs.openstack.org/api/openstack-network/2.0/content/pagination.html\">api doc</a>\n    */\n   @Named(\"network:list\")\n   @GET\n   @ResponseParser(ParseNetworks.class)\n   @Fallback(EmptyNetworksFallback.class)\n   Networks list(PaginationOptions options);\n\n   /**\n    * Return a specific network\n    *\n    * @param id the id of the network to return\n    * @return Network or null if not found\n    */\n   @Named(\"network:get\")\n   @GET\n   @Path(\"/{id}\")\n   @SelectJson(\"network\")\n   @Fallback(Fallbacks.NullOnNotFoundOr404.class)\n   @Nullable\n   Network get(@PathParam(\"id\") String id);\n\n   /**\n    * Create a new network with the specified type\n    *\n    * @param network Describes the network to be created.\n    * @return a reference of the newly-created network\n    */\n   @Named(\"network:create\")\n   @POST\n   @SelectJson(\"network\")\n   Network create(@WrapWith(\"network\") Network.CreateNetwork network);\n\n   /**\n    * Create multiple networks\n    *\n    * @param networks the bulk of networks to create\n    * @return list of references of the newly-created networks\n    */\n   @Named(\"network:createBulk\")\n   @POST\n   @SelectJson(\"networks\")\n   FluentIterable<Network> createBulk(@WrapWith(\"networks\") ImmutableList<Network.CreateNetwork> networks);\n\n   /**\n    * Update a network\n    *\n    * @param id the id of the network to update\n    * @param network the network to update\n    * @return true if update successful, false if not\n    */\n   @Named(\"network:update\")\n   @PUT\n   @Path(\"/{id}\")\n   @SelectJson(\"network\")\n   Network update(@PathParam(\"id\") String id, @WrapWith(\"network\") Network.UpdateNetwork network);\n\n   /**\n    * Deletes the specified network\n    *\n    * @param id the id of the network to delete\n    * @return true if delete was successful, false if not\n    */\n   @Named(\"network:delete\")\n   @DELETE\n   @Path(\"/{id}\")\n   @Fallback(Fallbacks.FalseOnNotFoundOr404.class)\n   boolean delete(@PathParam(\"id\") String id);\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/features/PortApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.features;\n\nimport java.util.List;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks;\nimport org.jclouds.Fallbacks.EmptyPagedIterableOnNotFoundOr404;\nimport org.jclouds.collect.PagedIterable;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.neutron.v2.domain.Port;\nimport org.jclouds.openstack.neutron.v2.domain.Ports;\nimport org.jclouds.openstack.neutron.v2.fallbacks.EmptyPortsFallback;\nimport org.jclouds.openstack.neutron.v2.functions.ParsePorts;\nimport org.jclouds.openstack.neutron.v2.functions.PortsToPagedIterable;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.Transform;\nimport org.jclouds.rest.annotations.WrapWith;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.collect.FluentIterable;\n\n/**\n * Provides access to Port operations for the OpenStack Networking (Neutron) v2 API.\n * <p/>\n * A port represents a virtual switch port on a logical network switch where all the interfaces attached to a given network are connected.\n * <p/>\n * A port has an administrative state which is either 'DOWN' or 'ACTIVE'. Ports which are administratively down will not be able to receive/send traffic.\n * @see <a href=\n *      \"http://docs.openstack.org/api/openstack-network/2.0/content/Ports.html\">api doc</a>\n */\n@Beta\n@Path(\"/ports\")\n@RequestFilters(AuthenticateRequest.class)\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface PortApi {\n\n   /**\n    * Returns the list of all ports currently defined in Neutron for the current tenant. The list provides the unique\n    * identifier of each network configured for the tenant.\n    *\n    * @return the list of all port references configured for the tenant\n    */\n   @Named(\"port:list\")\n   @GET\n   @Transform(PortsToPagedIterable.class)\n   @ResponseParser(ParsePorts.class)\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   PagedIterable<Port> list();\n\n   /**\n    * @see <a href=\"http://docs.openstack.org/api/openstack-network/2.0/content/pagination.html\">api doc</a>\n    */\n   @Named(\"port:list\")\n   @GET\n   @ResponseParser(ParsePorts.class)\n   @Fallback(EmptyPortsFallback.class)\n   Ports list(PaginationOptions options);\n\n   /**\n    * Returns the specific port\n    *\n    * @param id the id of the port to return\n    * @return Port or null if not found\n    */\n   @Named(\"port:get\")\n   @GET\n   @Path(\"/{id}\")\n   @SelectJson(\"port\")\n   @Fallback(Fallbacks.NullOnNotFoundOr404.class)\n   @Nullable\n   Port get(@PathParam(\"id\") String id);\n\n   /**\n    * Create a new port in the specified network\n    *\n    * @param port the port details\n    * @return a reference of the newly-created port\n    */\n   @Named(\"port:create\")\n   @POST\n   @SelectJson(\"port\")\n   Port create(@WrapWith(\"port\") Port.CreatePort port);\n\n   /**\n    * Create multiple ports\n    *\n    * @param ports the bulk of ports to create\n    * @return list of references of the newly-created ports\n    */\n   @Named(\"port:createBulk\")\n   @POST\n   @SelectJson(\"ports\")\n   FluentIterable<Port> createBulk(@WrapWith(\"ports\") List<Port.CreatePort> ports);\n\n   /**\n    * Update a port\n    *\n    * @param id the id of the port to update\n    * @param port CreatePort with just the attributes to update\n    * @return true if update successful, false if not\n    */\n   @Named(\"port:update\")\n   @PUT\n   @Path(\"/{id}\")\n   @SelectJson(\"port\")\n   Port update(@PathParam(\"id\") String id, @WrapWith(\"port\") Port.UpdatePort port);\n\n   /**\n    * Delete a port\n    *\n    * @param id the id of the port to delete\n    * @return true if delete successful, false if not\n    */\n   @Named(\"port:delete\")\n   @DELETE\n   @Path(\"/{id}\")\n   @Fallback(Fallbacks.FalseOnNotFoundOr404.class)\n   boolean delete(@PathParam(\"id\") String id);\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/features/SecurityGroupApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks;\nimport org.jclouds.Fallbacks.EmptyPagedIterableOnNotFoundOr404;\nimport org.jclouds.collect.PagedIterable;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.neutron.v2.domain.Rule;\nimport org.jclouds.openstack.neutron.v2.domain.Rules;\nimport org.jclouds.openstack.neutron.v2.domain.SecurityGroup;\nimport org.jclouds.openstack.neutron.v2.domain.SecurityGroups;\nimport org.jclouds.openstack.neutron.v2.fallbacks.EmptyRulesFallback;\nimport org.jclouds.openstack.neutron.v2.fallbacks.EmptySecurityGroupsFallback;\nimport org.jclouds.openstack.neutron.v2.functions.ParseRules;\nimport org.jclouds.openstack.neutron.v2.functions.ParseSecurityGroups;\nimport org.jclouds.openstack.neutron.v2.functions.RulesToPagedIterable;\nimport org.jclouds.openstack.neutron.v2.functions.SecurityGroupsToPagedIterable;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.Transform;\nimport org.jclouds.rest.annotations.WrapWith;\n\nimport com.google.common.annotations.Beta;\n\n/**\n * Provides access to Security Group extension operations for the OpenStack Networking (Neutron) v2 API.\n * <p/>\n * Security groups and security group rules allows administrators and tenants the ability to specify the type of\n * traffic and direction (ingress/egress) that is allowed to pass through a port. A security group is a container for\n * security group rules.\n */\n@Beta\n@RequestFilters(AuthenticateRequest.class)\n@Consumes(MediaType.APPLICATION_JSON)\n@Produces(MediaType.APPLICATION_JSON)\npublic interface SecurityGroupApi {\n\n   /**\n    * @return all security groups currently defined in Neutron for the current tenant.\n    */\n   @Path(\"/security-groups\")\n   @Named(\"security-group:list\")\n   @GET\n   @ResponseParser(ParseSecurityGroups.class)\n   @Transform(SecurityGroupsToPagedIterable.class)\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   PagedIterable<SecurityGroup> listSecurityGroups();\n\n   /**\n    * @return all security groups currently defined in Neutron for the current tenant.\n    */\n   @Path(\"/security-groups\")\n   @Named(\"security-group:list\")\n   @GET\n   @ResponseParser(ParseSecurityGroups.class)\n   @Fallback(EmptySecurityGroupsFallback.class)\n   SecurityGroups listSecurityGroups(PaginationOptions options);\n\n   /**\n    * @param id the id of the security group to return\n    * @return SecurityGroup or null if not found.\n    */\n   @Path(\"/security-groups/{id}\")\n   @Named(\"security-group:get\")\n   @GET\n   @SelectJson(\"security_group\")\n   @Fallback(Fallbacks.NullOnNotFoundOr404.class)\n   @Nullable\n   SecurityGroup getSecurityGroup(@PathParam(\"id\") String id);\n\n   /**\n    * Creates a new SecurityGroup.\n    *\n    * @param securityGroup Describes the security group to be created.\n    * @return a reference of the newly-created security group\n    */\n   @Path(\"/security-groups\")\n   @Named(\"secuity-group:create\")\n   @POST\n   @SelectJson(\"security_group\")\n   SecurityGroup create(@WrapWith(\"security_group\") SecurityGroup.CreateSecurityGroup securityGroup);\n\n   /**\n    * Deletes the specified Security Group.\n    *\n    * @param id the id of the security group to delete\n    * @return true if delete was successful, false if not\n    */\n   @Path(\"/security-groups/{id}\")\n   @Named(\"security-group:delete\")\n   @DELETE\n   @Fallback(Fallbacks.FalseOnNotFoundOr404.class)\n   boolean deleteSecurityGroup(@PathParam(\"id\") String id);\n\n   /**\n    * Rules\n    */\n\n   /**\n    * @return all security groups rules currently defined in Neutron for the current tenant.\n    */\n   @Path(\"/security-group-rules\")\n   @Named(\"security-group-rule:list\")\n   @GET\n   @ResponseParser(ParseRules.class)\n   @Transform(RulesToPagedIterable.class)\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   PagedIterable<Rule> listRules();\n\n   /**\n    * @return all security groups rules currently defined in Neutron for the current tenant.\n    */\n   @Path(\"/security-group-rules\")\n   @Named(\"security-group-rule:list\")\n   @GET\n   @ResponseParser(ParseRules.class)\n   @Fallback(EmptyRulesFallback.class)\n   Rules listRules(PaginationOptions options);\n\n   /**\n    * @param id the id of the security group rule to return.\n    * @return SecurityGroupRule or null if not found.\n    */\n   @Path(\"/security-group-rules/{id}\")\n   @Named(\"security-group-rule:get\")\n   @GET\n   @SelectJson(\"security_group_rule\")\n   @Fallback(Fallbacks.NullOnNotFoundOr404.class)\n   @Nullable\n   Rule get(@PathParam(\"id\") String id);\n\n   /**\n    * Creates a new Security Group Rule.\n    *\n    * @param securityGroupRule Describes the security group rule to be created.\n    * @return a reference of the newly-created security group rule.\n    */\n   @Path(\"/security-group-rules\")\n   @Named(\"security-group-rule:create\")\n   @POST\n   @SelectJson(\"security_group_rule\")\n   Rule create(@WrapWith(\"security_group_rule\") Rule.CreateRule securityGroupRule);\n\n   /**\n    * Deletes the specified Security Group Rule.\n    *\n    * @param id the id of the security group rule to delete.\n    * @return true if delete was successful, false if not.\n    */\n   @Path(\"/security-group-rules/{id}\")\n   @Named(\"security-group-rule:delete\")\n   @DELETE\n   @Fallback(Fallbacks.FalseOnNotFoundOr404.class)\n   boolean deleteRule(@PathParam(\"id\") String id);\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/features/SubnetApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.features;\n\nimport java.util.List;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks;\nimport org.jclouds.Fallbacks.EmptyPagedIterableOnNotFoundOr404;\nimport org.jclouds.collect.PagedIterable;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.neutron.v2.domain.Subnet;\nimport org.jclouds.openstack.neutron.v2.domain.Subnets;\nimport org.jclouds.openstack.neutron.v2.fallbacks.EmptySubnetsFallback;\nimport org.jclouds.openstack.neutron.v2.functions.ParseSubnets;\nimport org.jclouds.openstack.neutron.v2.functions.SubnetsToPagedIterable;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.Transform;\nimport org.jclouds.rest.annotations.WrapWith;\n\nimport com.google.common.collect.FluentIterable;\n\n/**\n * Provides access to Subnet operations for the OpenStack Networking (Neutron) v2 API.\n *\n * @see <a href=\n *      \"http://docs.openstack.org/api/openstack-network/2.0/content/Subnets.html\">api doc</a>\n */\n@Path(\"/subnets\")\n@RequestFilters(AuthenticateRequest.class)\n@Consumes(MediaType.APPLICATION_JSON)\n@Produces(MediaType.APPLICATION_JSON)\npublic interface SubnetApi {\n\n   /**\n    * Returns the list of all subnets currently defined in Neutron for the current tenant. The list provides the unique\n    * identifier of each subnet configured for the tenant.\n    *\n    * @return the list of all subnet references configured for the tenant\n    */\n   @Named(\"subnet:list\")\n   @GET\n   @ResponseParser(ParseSubnets.class)\n   @Transform(SubnetsToPagedIterable.class)\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   PagedIterable<Subnet> list();\n\n   /**\n    * @see <a href=\"http://docs.openstack.org/api/openstack-network/2.0/content/pagination.html\">api doc</a>\n    */\n   @Named(\"subnet:list\")\n   @GET\n   @ResponseParser(ParseSubnets.class)\n   @Fallback(EmptySubnetsFallback.class)\n   Subnets list(PaginationOptions options);\n\n   /**\n    * Returns the specific Subnet.\n    *\n    * @param id the id of the subnet to return\n    * @return Subnet or null if not found\n    */\n   @Named(\"subnet:get\")\n   @GET\n   @Path(\"/{id}\")\n   @SelectJson(\"subnet\")\n   @Fallback(Fallbacks.NullOnNotFoundOr404.class)\n   @Nullable\n   Subnet get(@PathParam(\"id\") String id);\n\n   /**\n    * Create a subnet within a specified network\n    *\n    * @param subnet the subnet to be created\n    * @return a reference of the newly-created subnet\n    */\n   @Named(\"subnet:create\")\n   @POST\n   @SelectJson(\"subnet\")\n   Subnet create(@WrapWith(\"subnet\") Subnet.CreateSubnet subnet);\n\n   /**\n    * Create multiple subnets\n    *\n    * @param subnets the bulk of subnets to create\n    * @return list of references of the newly-created subnets\n    */\n   @Named(\"subnet:createBulk\")\n   @POST\n   @SelectJson(\"subnets\")\n   FluentIterable<Subnet> createBulk(@WrapWith(\"subnets\") List<Subnet.CreateSubnet> subnets);\n\n   /**\n    * Update a subnet\n    *\n    * @param id the id of the subnet to update\n    * @return true if update was successful, false if not\n    */\n   @Named(\"subnet:update\")\n   @PUT\n   @Path(\"/{id}\")\n   @SelectJson(\"subnet\")\n   Subnet update(@PathParam(\"id\") String id, @WrapWith(\"subnet\") Subnet.UpdateSubnet subnet);\n\n   /**\n    * Delete a subnet\n    *\n    * @param id the id of the subnet to delete\n    * @return true if delete successful, false if not\n    */\n   @Named(\"subnet:delete\")\n   @DELETE\n   @Path(\"/{id}\")\n   @Fallback(Fallbacks.FalseOnNotFoundOr404.class)\n   boolean delete(@PathParam(\"id\") String id);\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/functions/FirewallPolicyToPagedIterable.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.internal.Arg0ToPagedIterable;\nimport org.jclouds.openstack.neutron.v2.NeutronApi;\nimport org.jclouds.openstack.neutron.v2.domain.FirewallPolicy;\nimport org.jclouds.openstack.neutron.v2.extensions.FWaaSApi;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\n\n/**\n * Ensures FirewallRule works as PagedIterable.\n */\npublic class FirewallPolicyToPagedIterable extends Arg0ToPagedIterable.FromCaller<FirewallPolicy, FirewallPolicyToPagedIterable> {\n\n   private final NeutronApi api;\n\n   @Inject\n   protected FirewallPolicyToPagedIterable(NeutronApi api) {\n      this.api = checkNotNull(api, \"api\");\n   }\n\n   @Override\n   protected Function<Object, IterableWithMarker<FirewallPolicy>> markerToNextForArg0(Optional<Object> arg0) {\n      String region = arg0.isPresent() ? arg0.get().toString() : null;\n      final FWaaSApi firewallApi = api.getFWaaSApi(region).get();\n      return new Function<Object, IterableWithMarker<FirewallPolicy>>() {\n\n         @SuppressWarnings(\"unchecked\")\n         @Override\n         public IterableWithMarker<FirewallPolicy> apply(Object input) {\n            return IterableWithMarker.class.cast(firewallApi.listFirewallPolicies());\n         }\n\n         @Override\n         public String toString() {\n            return \"listFirewallPolicies()\";\n         }\n      };\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/functions/FirewallRuleToPagedIterable.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.internal.Arg0ToPagedIterable;\nimport org.jclouds.openstack.neutron.v2.NeutronApi;\nimport org.jclouds.openstack.neutron.v2.domain.FirewallRule;\nimport org.jclouds.openstack.neutron.v2.extensions.FWaaSApi;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\n\n/**\n * Ensures FirewallRule works as PagedIterable.\n */\npublic class FirewallRuleToPagedIterable extends Arg0ToPagedIterable.FromCaller<FirewallRule, FirewallRuleToPagedIterable> {\n\n   private final NeutronApi api;\n\n   @Inject\n   protected FirewallRuleToPagedIterable(NeutronApi api) {\n      this.api = checkNotNull(api, \"api\");\n   }\n\n   @Override\n   protected Function<Object, IterableWithMarker<FirewallRule>> markerToNextForArg0(Optional<Object> arg0) {\n      String region = arg0.isPresent() ? arg0.get().toString() : null;\n      final FWaaSApi firewallApi = api.getFWaaSApi(region).get();\n      return new Function<Object, IterableWithMarker<FirewallRule>>() {\n\n         @SuppressWarnings(\"unchecked\")\n         @Override\n         public IterableWithMarker<FirewallRule> apply(Object input) {\n            return IterableWithMarker.class.cast(firewallApi.listFirewallRules());\n         }\n\n         @Override\n         public String toString() {\n            return \"listFirewallRules()\";\n         }\n      };\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/functions/FirewallToPagedIterable.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.internal.Arg0ToPagedIterable;\nimport org.jclouds.openstack.neutron.v2.NeutronApi;\nimport org.jclouds.openstack.neutron.v2.domain.Firewall;\nimport org.jclouds.openstack.neutron.v2.extensions.FWaaSApi;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\n\n/**\n * Ensures Firewall works as PagedIterable.\n */\npublic class FirewallToPagedIterable extends Arg0ToPagedIterable.FromCaller<Firewall, FirewallToPagedIterable> {\n\n   private final NeutronApi api;\n\n   @Inject\n   protected FirewallToPagedIterable(NeutronApi api) {\n      this.api = checkNotNull(api, \"api\");\n   }\n\n   @Override\n   protected Function<Object, IterableWithMarker<Firewall>> markerToNextForArg0(Optional<Object> arg0) {\n      String region = arg0.isPresent() ? arg0.get().toString() : null;\n      final FWaaSApi firewallApi = api.getFWaaSApi(region).get();\n      return new Function<Object, IterableWithMarker<Firewall>>() {\n\n         @SuppressWarnings(\"unchecked\")\n         @Override\n         public IterableWithMarker<Firewall> apply(Object input) {\n            return IterableWithMarker.class.cast(firewallApi.list());\n         }\n\n         @Override\n         public String toString() {\n            return \"listFirewalls()\";\n         }\n      };\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/functions/FloatingIPsToPagedIterable.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.functions;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.internal.Arg0ToPagedIterable;\nimport org.jclouds.openstack.neutron.v2.NeutronApi;\nimport org.jclouds.openstack.neutron.v2.domain.FloatingIP;\nimport org.jclouds.openstack.neutron.v2.features.FloatingIPApi;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\n\nimport jakarta.inject.Inject;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\n/**\n * Ensures Floating IPs works as PagedIterable.\n */\npublic class FloatingIPsToPagedIterable extends Arg0ToPagedIterable.FromCaller<FloatingIP, FloatingIPsToPagedIterable> {\n\n   private final NeutronApi api;\n\n   @Inject\n   protected FloatingIPsToPagedIterable(NeutronApi api) {\n      this.api = checkNotNull(api, \"api\");\n   }\n\n   @Override\n   protected Function<Object, IterableWithMarker<FloatingIP>> markerToNextForArg0(Optional<Object> arg0) {\n      String region = arg0.isPresent() ? arg0.get().toString() : null;\n      final FloatingIPApi floatingIPApi = api.getFloatingIPApi(region);\n      return new Function<Object, IterableWithMarker<FloatingIP>>() {\n\n         @SuppressWarnings(\"unchecked\")\n         @Override\n         public IterableWithMarker<FloatingIP> apply(Object input) {\n            PaginationOptions paginationOptions = PaginationOptions.class.cast(input);\n            return IterableWithMarker.class.cast(floatingIPApi.list(paginationOptions));\n         }\n\n         @Override\n         public String toString() {\n            return \"listfloatingIPs()\";\n         }\n      };\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/functions/NetworksToPagedIterable.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.functions;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.internal.Arg0ToPagedIterable;\nimport org.jclouds.openstack.neutron.v2.NeutronApi;\nimport org.jclouds.openstack.neutron.v2.domain.Network;\nimport org.jclouds.openstack.neutron.v2.features.NetworkApi;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\n\nimport jakarta.inject.Inject;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\n/**\n * Makes Networks work as a PagedIterable.\n */\npublic class NetworksToPagedIterable extends Arg0ToPagedIterable.FromCaller<Network, NetworksToPagedIterable> {\n\n   private final NeutronApi api;\n\n   @Inject\n   protected NetworksToPagedIterable(NeutronApi api) {\n      this.api = checkNotNull(api, \"api\");\n   }\n\n   @Override\n   protected Function<Object, IterableWithMarker<Network>> markerToNextForArg0(Optional<Object> arg0) {\n      String region = arg0.isPresent() ? arg0.get().toString() : null;\n      final NetworkApi networkApi = api.getNetworkApi(region);\n      return new Function<Object, IterableWithMarker<Network>>() {\n\n         @SuppressWarnings(\"unchecked\")\n         @Override\n         public IterableWithMarker<Network> apply(Object input) {\n            PaginationOptions paginationOptions = PaginationOptions.class.cast(input);\n            return IterableWithMarker.class.cast(networkApi.list(paginationOptions));\n         }\n\n         @Override\n         public String toString() {\n            return \"listNetworks()\";\n         }\n      };\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/functions/ParseFirewallPolicies.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.functions;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\nimport org.jclouds.openstack.neutron.v2.domain.FirewallPolicies;\n\nimport com.google.inject.TypeLiteral;\n\n/**\n * Used by jclouds to provide more specific collections and fallbacks.\n */\n@Singleton\npublic class ParseFirewallPolicies extends ParseJson<FirewallPolicies> {\n\n   @Inject\n   public ParseFirewallPolicies(Json json) {\n      super(json, TypeLiteral.get(FirewallPolicies.class));\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/functions/ParseFirewallRules.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.functions;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\nimport org.jclouds.openstack.neutron.v2.domain.FirewallRules;\n\nimport com.google.inject.TypeLiteral;\n\n/**\n * Used by jclouds to provide more specific collections and fallbacks.\n */\n@Singleton\npublic class ParseFirewallRules extends ParseJson<FirewallRules> {\n\n   @Inject\n   public ParseFirewallRules(Json json) {\n      super(json, TypeLiteral.get(FirewallRules.class));\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/functions/ParseFirewalls.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.functions;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\nimport org.jclouds.openstack.neutron.v2.domain.Firewalls;\n\nimport com.google.inject.TypeLiteral;\n\n/**\n * Used by jclouds to provide more specific collections and fallbacks.\n */\n@Singleton\npublic class ParseFirewalls extends ParseJson<Firewalls> {\n\n   @Inject\n   public ParseFirewalls(Json json) {\n      super(json, TypeLiteral.get(Firewalls.class));\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/functions/ParseFloatingIPs.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.functions;\n\nimport com.google.inject.TypeLiteral;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\nimport org.jclouds.openstack.neutron.v2.domain.FloatingIPs;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\n/**\n * Used by jclouds to provide more specific collections and fallbacks.\n */\n@Singleton\npublic class ParseFloatingIPs extends ParseJson<FloatingIPs> {\n\n   @Inject\n   public ParseFloatingIPs(Json json) {\n      super(json, TypeLiteral.get(FloatingIPs.class));\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/functions/ParseNetworks.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.functions;\n\n\nimport com.google.inject.TypeLiteral;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\nimport org.jclouds.openstack.neutron.v2.domain.Networks;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\n/**\n * Used by jclouds to provide more specific collections and fallbacks.\n */\n@Singleton\npublic class ParseNetworks extends ParseJson<Networks> {\n\n   @Inject\n   public ParseNetworks(Json json) {\n      super(json, TypeLiteral.get(Networks.class));\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/functions/ParsePorts.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.functions;\n\nimport com.google.inject.TypeLiteral;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\nimport org.jclouds.openstack.neutron.v2.domain.Ports;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\n/**\n * Used by jclouds to provide more specific collections and fallbacks.\n */\n@Singleton\npublic class ParsePorts extends ParseJson<Ports> {\n\n   @Inject\n   public ParsePorts(Json json) {\n      super(json, TypeLiteral.get(Ports.class));\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/functions/ParseRouters.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.functions;\n\nimport com.google.inject.TypeLiteral;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\nimport org.jclouds.openstack.neutron.v2.domain.Routers;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\n/**\n * Used by jclouds to provide more specific collections and fallbacks.\n */\n@Singleton\npublic class ParseRouters extends ParseJson<Routers> {\n\n   @Inject\n   public ParseRouters(Json json) {\n      super(json, TypeLiteral.get(Routers.class));\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/functions/ParseRules.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.functions;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\nimport org.jclouds.openstack.neutron.v2.domain.Rules;\n\nimport com.google.inject.TypeLiteral;\n\n/**\n * Used by jclouds to provide more specific collections and fallbacks.\n */\n@Singleton\npublic class ParseRules extends ParseJson<Rules> {\n\n   @Inject\n   public ParseRules(Json json) {\n      super(json, TypeLiteral.get(Rules.class));\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/functions/ParseSecurityGroups.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.functions;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\nimport org.jclouds.openstack.neutron.v2.domain.SecurityGroups;\n\nimport com.google.inject.TypeLiteral;\n\n/**\n * Used by jclouds to provide more specific collections and fallbacks.\n */\n@Singleton\npublic class ParseSecurityGroups extends ParseJson<SecurityGroups> {\n\n   @Inject\n   public ParseSecurityGroups(Json json) {\n      super(json, TypeLiteral.get(SecurityGroups.class));\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/functions/ParseSubnets.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.functions;\n\nimport com.google.inject.TypeLiteral;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\nimport org.jclouds.openstack.neutron.v2.domain.Subnets;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\n/**\n * Used by jclouds to provide more specific collections and fallbacks.\n */\n@Singleton\npublic class ParseSubnets extends ParseJson<Subnets> {\n\n   @Inject\n   public ParseSubnets(Json json) {\n      super(json, TypeLiteral.get(Subnets.class));\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/functions/PortsToPagedIterable.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.functions;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.internal.Arg0ToPagedIterable;\nimport org.jclouds.openstack.neutron.v2.NeutronApi;\nimport org.jclouds.openstack.neutron.v2.domain.Port;\nimport org.jclouds.openstack.neutron.v2.features.PortApi;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\n\nimport jakarta.inject.Inject;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\n/**\n * Ensures Ports works as a paged iterable.\n */\npublic class PortsToPagedIterable extends Arg0ToPagedIterable.FromCaller<Port, PortsToPagedIterable> {\n\n   private final NeutronApi api;\n\n   @Inject\n   protected PortsToPagedIterable(NeutronApi api) {\n      this.api = checkNotNull(api, \"api\");\n   }\n\n   @Override\n   protected Function<Object, IterableWithMarker<Port>> markerToNextForArg0(Optional<Object> arg0) {\n      String region = arg0.isPresent() ? arg0.get().toString() : null;\n      final PortApi portApi = api.getPortApi(region);\n      return new Function<Object, IterableWithMarker<Port>>() {\n\n         @SuppressWarnings(\"unchecked\")\n         @Override\n         public IterableWithMarker<Port> apply(Object input) {\n            PaginationOptions paginationOptions = PaginationOptions.class.cast(input);\n            return IterableWithMarker.class.cast(portApi.list(paginationOptions));\n         }\n\n         @Override\n         public String toString() {\n            return \"listPortsInDetail()\";\n         }\n      };\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/functions/RouterToPagedIterable.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.internal.Arg0ToPagedIterable;\nimport org.jclouds.openstack.neutron.v2.NeutronApi;\nimport org.jclouds.openstack.neutron.v2.domain.Router;\nimport org.jclouds.openstack.neutron.v2.extensions.RouterApi;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\n\n/**\n * Ensures Routers works as PagedIterable.\n */\npublic class RouterToPagedIterable extends Arg0ToPagedIterable.FromCaller<Router, RouterToPagedIterable> {\n\n   private final NeutronApi api;\n\n   @Inject\n   protected RouterToPagedIterable(NeutronApi api) {\n      this.api = checkNotNull(api, \"api\");\n   }\n\n   @Override\n   protected Function<Object, IterableWithMarker<Router>> markerToNextForArg0(Optional<Object> arg0) {\n      String region = arg0.isPresent() ? arg0.get().toString() : null;\n      final RouterApi routerApi = api.getRouterApi(region).get();\n      return new Function<Object, IterableWithMarker<Router>>() {\n\n         @SuppressWarnings(\"unchecked\")\n         @Override\n         public IterableWithMarker<Router> apply(Object input) {\n            PaginationOptions paginationOptions = PaginationOptions.class.cast(input);\n            return IterableWithMarker.class.cast(routerApi.list(paginationOptions));\n         }\n\n         @Override\n         public String toString() {\n            return \"listRouters()\";\n         }\n      };\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/functions/RulesToPagedIterable.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.internal.Arg0ToPagedIterable;\nimport org.jclouds.openstack.neutron.v2.NeutronApi;\nimport org.jclouds.openstack.neutron.v2.domain.Rule;\nimport org.jclouds.openstack.neutron.v2.features.SecurityGroupApi;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\n\n/**\n * Ensures Routers works as PagedIterable.\n */\npublic class RulesToPagedIterable extends\n      Arg0ToPagedIterable.FromCaller<Rule, RulesToPagedIterable> {\n\n   private final NeutronApi api;\n\n   @Inject\n   protected RulesToPagedIterable(NeutronApi api) {\n      this.api = checkNotNull(api, \"api\");\n   }\n\n   @Override\n   protected Function<Object, IterableWithMarker<Rule>> markerToNextForArg0(Optional<Object> arg0) {\n      String region = arg0.isPresent() ? arg0.get().toString() : null;\n      final SecurityGroupApi securityGroupApi = api.getSecurityGroupApi(region);\n      return new Function<Object, IterableWithMarker<Rule>>() {\n\n         @SuppressWarnings(\"unchecked\")\n         @Override\n         public IterableWithMarker<Rule> apply(Object input) {\n            PaginationOptions paginationOptions = PaginationOptions.class.cast(input);\n            return IterableWithMarker.class.cast(securityGroupApi.listRules(paginationOptions));\n         }\n\n         @Override\n         public String toString() {\n            return \"listRules()\";\n         }\n      };\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/functions/SecurityGroupsToPagedIterable.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.internal.Arg0ToPagedIterable;\nimport org.jclouds.openstack.neutron.v2.NeutronApi;\nimport org.jclouds.openstack.neutron.v2.domain.SecurityGroup;\nimport org.jclouds.openstack.neutron.v2.features.SecurityGroupApi;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\n\n/**\n * Ensures Routers works as PagedIterable.\n */\npublic class SecurityGroupsToPagedIterable extends\n      Arg0ToPagedIterable.FromCaller<SecurityGroup, SecurityGroupsToPagedIterable> {\n\n   private final NeutronApi api;\n\n   @Inject\n   protected SecurityGroupsToPagedIterable(NeutronApi api) {\n      this.api = checkNotNull(api, \"api\");\n   }\n\n   @Override\n   protected Function<Object, IterableWithMarker<SecurityGroup>> markerToNextForArg0(Optional<Object> arg0) {\n      String region = arg0.isPresent() ? arg0.get().toString() : null;\n      final SecurityGroupApi securityGroupApi = api.getSecurityGroupApi(region);\n      return new Function<Object, IterableWithMarker<SecurityGroup>>() {\n\n         @SuppressWarnings(\"unchecked\")\n         @Override\n         public IterableWithMarker<SecurityGroup> apply(Object input) {\n            PaginationOptions paginationOptions = PaginationOptions.class.cast(input);\n            return IterableWithMarker.class.cast(securityGroupApi.listSecurityGroups(paginationOptions));\n         }\n\n         @Override\n         public String toString() {\n            return \"listSecurityGroups()\";\n         }\n      };\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/functions/SubnetsToPagedIterable.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.functions;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.internal.Arg0ToPagedIterable;\nimport org.jclouds.openstack.neutron.v2.NeutronApi;\nimport org.jclouds.openstack.neutron.v2.domain.Subnet;\nimport org.jclouds.openstack.neutron.v2.features.SubnetApi;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\n\nimport jakarta.inject.Inject;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\n/**\n * Ensures Subnets works as a PagedIterable.\n */\npublic class SubnetsToPagedIterable extends Arg0ToPagedIterable.FromCaller<Subnet, SubnetsToPagedIterable> {\n\n   private final NeutronApi api;\n\n   @Inject\n   protected SubnetsToPagedIterable(NeutronApi api) {\n      this.api = checkNotNull(api, \"api\");\n   }\n\n   @Override\n   protected Function<Object, IterableWithMarker<Subnet>> markerToNextForArg0(Optional<Object> arg0) {\n      String region = arg0.isPresent() ? arg0.get().toString() : null;\n      final SubnetApi subnetApi = api.getSubnetApi(region);\n      return new Function<Object, IterableWithMarker<Subnet>>() {\n\n         @SuppressWarnings(\"unchecked\")\n         @Override\n         public IterableWithMarker<Subnet> apply(Object input) {\n            PaginationOptions paginationOptions = PaginationOptions.class.cast(input);\n            return IterableWithMarker.class.cast(subnetApi.list(paginationOptions));\n         }\n\n         @Override\n         public String toString() {\n            return \"listSubnets()\";\n         }\n      };\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/functions/VersionAwareRegionToEndpoint.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.functions;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\n\nimport java.net.URI;\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.location.Region;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\n\npublic class VersionAwareRegionToEndpoint implements Function<Object, URI> {\n\n   private final Supplier<Map<String, Supplier<URI>>> regionToEndpointSupplier;\n\n   @Inject\n   public VersionAwareRegionToEndpoint(@Region Supplier<Map<String, Supplier<URI>>> regionToEndpointSupplier) {\n      this.regionToEndpointSupplier = checkNotNull(regionToEndpointSupplier, \"regionToEndpointSupplier\");\n   }\n\n   /**\n    * A quick fix to ensure Neutron works with endpoint definitions that are not version-agnostic.\n    * The service-side API will always have a v2.0 in the path.\n    * However, the endpoint will sometimes contain a v2.0 and sometimes it will not.\n    * The VersionAwareRegionToEndpoint ensures that the endpoint will always look the same\n    * before /v2.0 is added to it.\n    *\n    * Cannot leave labs until fixed:\n    * TODO: https://issues.apache.org/jira/browse/JCLOUDS-773\n    * This code will be unnecessary once this is supported.\n    */\n   @Override\n   public URI apply(Object from) {\n      Map<String, Supplier<URI>> regionToEndpoint = regionToEndpointSupplier.get();\n      checkState(!regionToEndpoint.isEmpty(), \"no region name to endpoint mappings configured!\");\n      checkArgument(regionToEndpoint.containsKey(from),\n               \"requested location %s, which is not in the configured locations: %s\", from, regionToEndpoint);\n      String uri = regionToEndpoint.get(from).get().toString();\n\n      if (uri.endsWith(\"/v2.0\")) {\n         return URI.create(uri.substring(0, uri.length() - 5));\n      }\n\n      return regionToEndpoint.get(from).get();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/functions/lbaas/v1/HealthMonitorsToPagedIterable.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.functions.lbaas.v1;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.internal.Arg0ToPagedIterable;\nimport org.jclouds.openstack.neutron.v2.NeutronApi;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.HealthMonitor;\nimport org.jclouds.openstack.neutron.v2.extensions.lbaas.v1.LBaaSApi;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\n\n/**\n * Makes HealthMonitors work as a PagedIterable.\n */\npublic class HealthMonitorsToPagedIterable extends\n      Arg0ToPagedIterable.FromCaller<HealthMonitor, HealthMonitorsToPagedIterable> {\n\n   private final NeutronApi api;\n\n   @Inject\n   protected HealthMonitorsToPagedIterable(NeutronApi api) {\n      this.api = checkNotNull(api, \"api\");\n   }\n\n   @Override\n   protected Function<Object, IterableWithMarker<HealthMonitor>> markerToNextForArg0(Optional<Object> arg0) {\n      String region = arg0.isPresent() ? arg0.get().toString() : null;\n      final LBaaSApi lbaasApi = api.getLBaaSApi(region).get();\n      return new Function<Object, IterableWithMarker<HealthMonitor>>() {\n\n         @SuppressWarnings(\"unchecked\")\n         @Override\n         public IterableWithMarker<HealthMonitor> apply(Object input) {\n            PaginationOptions paginationOptions = PaginationOptions.class.cast(input);\n            return IterableWithMarker.class.cast(lbaasApi.listHealthMonitors(paginationOptions));\n         }\n\n         @Override\n         public String toString() {\n            return \"listHealthMonitors()\";\n         }\n      };\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/functions/lbaas/v1/MembersToPagedIterable.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.functions.lbaas.v1;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.internal.Arg0ToPagedIterable;\nimport org.jclouds.openstack.neutron.v2.NeutronApi;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.Member;\nimport org.jclouds.openstack.neutron.v2.extensions.lbaas.v1.LBaaSApi;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\n\n/**\n * Makes Members work as a PagedIterable.\n */\npublic class MembersToPagedIterable extends Arg0ToPagedIterable.FromCaller<Member, MembersToPagedIterable> {\n\n   private final NeutronApi api;\n\n   @Inject\n   protected MembersToPagedIterable(NeutronApi api) {\n      this.api = checkNotNull(api, \"api\");\n   }\n\n   @Override\n   protected Function<Object, IterableWithMarker<Member>> markerToNextForArg0(Optional<Object> arg0) {\n      String region = arg0.isPresent() ? arg0.get().toString() : null;\n      final LBaaSApi lbaasApi = api.getLBaaSApi(region).get();\n      return new Function<Object, IterableWithMarker<Member>>() {\n\n         @SuppressWarnings(\"unchecked\")\n         @Override\n         public IterableWithMarker<Member> apply(Object input) {\n            PaginationOptions paginationOptions = PaginationOptions.class.cast(input);\n            return IterableWithMarker.class.cast(lbaasApi.listMembers(paginationOptions));\n         }\n\n         @Override\n         public String toString() {\n            return \"listMembers()\";\n         }\n      };\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/functions/lbaas/v1/ParseHealthMonitors.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.functions.lbaas.v1;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.HealthMonitors;\n\nimport com.google.inject.TypeLiteral;\n\n/**\n * Used by jclouds to provide more specific collections and fallbacks.\n */\n@Singleton\npublic class ParseHealthMonitors extends ParseJson<HealthMonitors> {\n\n   @Inject\n   public ParseHealthMonitors(Json json) {\n      super(json, TypeLiteral.get(HealthMonitors.class));\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/functions/lbaas/v1/ParseMembers.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.functions.lbaas.v1;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.Members;\n\nimport com.google.inject.TypeLiteral;\n\n/**\n * Used by jclouds to provide more specific collections and fallbacks.\n */\n@Singleton\npublic class ParseMembers extends ParseJson<Members> {\n\n   @Inject\n   public ParseMembers(Json json) {\n      super(json, TypeLiteral.get(Members.class));\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/functions/lbaas/v1/ParsePools.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.functions.lbaas.v1;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.Pools;\n\nimport com.google.inject.TypeLiteral;\n\n/**\n * Used by jclouds to provide more specific collections and fallbacks.\n */\n@Singleton\npublic class ParsePools extends ParseJson<Pools> {\n\n   @Inject\n   public ParsePools(Json json) {\n      super(json, TypeLiteral.get(Pools.class));\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/functions/lbaas/v1/ParseVIPs.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.functions.lbaas.v1;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.VIPs;\n\nimport com.google.inject.TypeLiteral;\n\n/**\n * Used by jclouds to provide more specific collections and fallbacks.\n */\n@Singleton\npublic class ParseVIPs extends ParseJson<VIPs> {\n\n   @Inject\n   public ParseVIPs(Json json) {\n      super(json, TypeLiteral.get(VIPs.class));\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/functions/lbaas/v1/PoolsToPagedIterable.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.functions.lbaas.v1;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.internal.Arg0ToPagedIterable;\nimport org.jclouds.openstack.neutron.v2.NeutronApi;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.Pool;\nimport org.jclouds.openstack.neutron.v2.extensions.lbaas.v1.LBaaSApi;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\n\n/**\n * Makes Pools work as a PagedIterable.\n */\npublic class PoolsToPagedIterable extends Arg0ToPagedIterable.FromCaller<Pool, PoolsToPagedIterable> {\n\n   private final NeutronApi api;\n\n   @Inject\n   protected PoolsToPagedIterable(NeutronApi api) {\n      this.api = checkNotNull(api, \"api\");\n   }\n\n   @Override\n   protected Function<Object, IterableWithMarker<Pool>> markerToNextForArg0(Optional<Object> arg0) {\n      String region = arg0.isPresent() ? arg0.get().toString() : null;\n      final LBaaSApi lbaasApi = api.getLBaaSApi(region).get();\n      return new Function<Object, IterableWithMarker<Pool>>() {\n\n         @SuppressWarnings(\"unchecked\")\n         @Override\n         public IterableWithMarker<Pool> apply(Object input) {\n            PaginationOptions paginationOptions = PaginationOptions.class.cast(input);\n            return IterableWithMarker.class.cast(lbaasApi.listPools(paginationOptions));\n         }\n\n         @Override\n         public String toString() {\n            return \"listPools()\";\n         }\n      };\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/functions/lbaas/v1/VIPsToPagedIterable.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.functions.lbaas.v1;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.internal.Arg0ToPagedIterable;\nimport org.jclouds.openstack.neutron.v2.NeutronApi;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.VIP;\nimport org.jclouds.openstack.neutron.v2.extensions.lbaas.v1.LBaaSApi;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\n\n/**\n * Makes VIPs work as a PagedIterable.\n */\npublic class VIPsToPagedIterable extends Arg0ToPagedIterable.FromCaller<VIP, VIPsToPagedIterable> {\n\n   private final NeutronApi api;\n\n   @Inject\n   protected VIPsToPagedIterable(NeutronApi api) {\n      this.api = checkNotNull(api, \"api\");\n   }\n\n   @Override\n   protected Function<Object, IterableWithMarker<VIP>> markerToNextForArg0(Optional<Object> arg0) {\n      String region = arg0.isPresent() ? arg0.get().toString() : null;\n      final LBaaSApi lbaasApi = api.getLBaaSApi(region).get();\n      return new Function<Object, IterableWithMarker<VIP>>() {\n\n         @SuppressWarnings(\"unchecked\")\n         @Override\n         public IterableWithMarker<VIP> apply(Object input) {\n            PaginationOptions paginationOptions = PaginationOptions.class.cast(input);\n            return IterableWithMarker.class.cast(lbaasApi.listVIPs(paginationOptions));\n         }\n\n         @Override\n         public String toString() {\n            return \"listVIPs()\";\n         }\n      };\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/handlers/NeutronErrorHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.handlers;\n\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.ResourceNotFoundException;\n\nimport jakarta.inject.Singleton;\n\nimport static org.jclouds.http.HttpUtils.closeClientButKeepContentStream;\n\n/**\n * This will parse and set an appropriate exception on the command object.\n */\n@Singleton\npublic class NeutronErrorHandler implements HttpErrorHandler {\n   public void handleError(HttpCommand command, HttpResponse response) {\n      // it is important to always read fully and close streams\n      byte[] data = closeClientButKeepContentStream(response);\n      String message = data != null ? new String(data) : null;\n\n      Exception exception = message != null ? new HttpResponseException(command, response, message)\n            : new HttpResponseException(command, response);\n      message = message != null ? message : String.format(\"%s -> %s\", command.getCurrentRequest().getRequestLine(),\n            response.getStatusLine());\n      switch (response.getStatusCode()) {\n         case 400:\n            break;\n         case 401:\n         case 403:\n            exception = new AuthorizationException(message, exception);\n            break;\n         case 404:\n            if (!command.getCurrentRequest().getMethod().equals(\"DELETE\")) {\n               exception = new ResourceNotFoundException(message, exception);\n            }\n            break;\n         case 409:\n            exception = new IllegalStateException(exception.getMessage(), exception);\n            break;\n      }\n      command.setException(exception);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/main/java/org/jclouds/openstack/neutron/v2/options/EmptyOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.options;\n\nimport com.google.inject.Inject;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.MapBinder;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport java.util.Map;\n\n/**\n * This class is used for methods who don't need a wrapper around their JSON body\n *\n */\npublic class EmptyOptions implements MapBinder {\n\n   @Inject\n   private BindToJsonPayload jsonBinder;\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      return bindToRequest(request, (Object) postParams);\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      return jsonBinder.bindToRequest(request, input);\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/java/org/jclouds/openstack/neutron/v2/NeutronApiMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.reflect.TypeToken;\nimport org.jclouds.View;\nimport org.jclouds.apis.internal.BaseApiMetadataTest;\nimport org.testng.annotations.Test;\n\n/**\n * The Neutron metadata test.\n */\n@Test(groups = \"unit\", testName = \"NeutronApiMetadataTest\")\npublic class NeutronApiMetadataTest extends BaseApiMetadataTest {\n   public NeutronApiMetadataTest() {\n      super(new NeutronApiMetadata(), ImmutableSet.<TypeToken<? extends View>>of());\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/java/org/jclouds/openstack/neutron/v2/extensions/FWaaSApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.openstack.neutron.v2.extensions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.openstack.neutron.v2.domain.CreateFirewall;\nimport org.jclouds.openstack.neutron.v2.domain.CreateFirewallPolicy;\nimport org.jclouds.openstack.neutron.v2.domain.CreateFirewallRule;\nimport org.jclouds.openstack.neutron.v2.domain.Firewall;\nimport org.jclouds.openstack.neutron.v2.domain.FirewallPolicy;\nimport org.jclouds.openstack.neutron.v2.domain.FirewallRule;\nimport org.jclouds.openstack.neutron.v2.domain.UpdateFirewall;\nimport org.jclouds.openstack.neutron.v2.domain.UpdateFirewallPolicy;\nimport org.jclouds.openstack.neutron.v2.domain.UpdateFirewallRule;\nimport org.jclouds.openstack.neutron.v2.internal.BaseNeutronApiLiveTest;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\nimport org.testng.Assert;\nimport org.testng.annotations.BeforeMethod;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicates;\nimport com.google.common.collect.Iterables;\n\n/**\n * Tests parsing and Guice wiring of FWaaSApi\n */\n@Test(groups = \"live\", testName = \"FWaaSApiLiveTest\")\npublic class FWaaSApiLiveTest extends BaseNeutronApiLiveTest {\n\n   private FWaaSApi fWaaSApi;\n\n   @BeforeMethod\n   void setUp() {\n      Optional<String> optionalRegion = Iterables.tryFind(api.getConfiguredRegions(), Predicates.notNull());\n      if (!optionalRegion.isPresent()) Assert.fail();\n      fWaaSApi = api.getFWaaSApi(optionalRegion.get()).get();\n   }\n   /**\n    * Smoke test for the Firewall extension for Neutron\n    */\n   public void testCreateUpdateAndDeleteFirewallRule() {\n\n      String inboundPort = \"22\";\n      FirewallRule firewallRule = null;\n\n      try {\n         // methods under test\n         firewallRule = fWaaSApi.createFirewallRule(CreateFirewallRule.builder()\n                 .name(String.format(\"jclouds-test-%s-fw-rule-%s\", this.getClass().getCanonicalName().toLowerCase(), inboundPort))\n                 .description(\"jclouds test fw rule\")\n                 .destinationIpAddress(\"192.168.0.1\")\n                 .destinationPort(inboundPort)\n                 .enabled(true)\n                 .action(\"allow\")\n                 .protocol(\"tcp\")\n                 .build());\n\n         assertFalse(fWaaSApi.listFirewallRules().concat().toList().isEmpty());\n         assertNotNull(fWaaSApi.listFirewallRules(PaginationOptions.Builder.limit(1)));\n\n         // get\n         firewallRule = fWaaSApi.getFirewallRule(firewallRule.getId());\n         assertEquals(firewallRule.getName(), String.format(\"jclouds-test-%s-fw-rule-%s\", this.getClass().getCanonicalName().toLowerCase(), inboundPort));\n         assertEquals(firewallRule.getDescription(), \"jclouds test fw rule\");\n\n         // update\n         FirewallRule updatedFirewallRule = fWaaSApi.updateFirewallRule(firewallRule.getId(), UpdateFirewallRule.builder().name(firewallRule.getName() + \"-updated\").build());\n         firewallRule = fWaaSApi.getFirewallRule(firewallRule.getId());\n         assertEquals(updatedFirewallRule, firewallRule);\n      } finally {\n         // delete\n         if (fWaaSApi != null) {\n            assertTrue(fWaaSApi.deleteFirewallRule(firewallRule.getId()));\n         }\n      }\n   }\n\n   public void testCreateUpdateAndDeleteFirewallPolicy() {\n\n      String inboundPort = \"80\";\n      FirewallRule firewallRule = fWaaSApi.createFirewallRule(CreateFirewallRule.builder()\n              .name(String.format(\"jclouds-test-%s-fw-rule-%s\", this.getClass().getCanonicalName().toLowerCase(), inboundPort))\n              .description(\"jclouds test fw rule\")\n              .destinationIpAddress(\"192.168.0.1\")\n              .destinationPort(inboundPort)\n              .enabled(true)\n              .action(\"allow\")\n              .protocol(\"tcp\")\n              .build());\n      FirewallPolicy firewallPolicy = null;\n\n      try {\n         // methods under test\n         firewallPolicy = fWaaSApi.createFirewallPolicy(CreateFirewallPolicy.builder()\n                 .name(String.format(\"jclouds-test-%s-fw-policy\", this.getClass().getCanonicalName().toLowerCase()))\n                 .description(\"jclouds test fw policy\")\n                 .build());\n\n         assertFalse(fWaaSApi.listFirewallPolicies().concat().toList().isEmpty());\n         assertNotNull(fWaaSApi.listFirewallPolicies(PaginationOptions.Builder.limit(1)));\n\n         // get\n         firewallPolicy = fWaaSApi.getFirewallPolicy(firewallPolicy.getId());\n         assertEquals(firewallPolicy.getName(), String.format(\"jclouds-test-%s-fw-policy\", this.getClass().getCanonicalName().toLowerCase()));\n         assertEquals(firewallPolicy.getDescription(), \"jclouds test fw policy\");\n\n         // update\n         FirewallPolicy updatedFirewallPolicy = fWaaSApi.updateFirewallPolicy(firewallPolicy.getId(), UpdateFirewallPolicy.builder()\n                 .name(String.format(\"jclouds-test-%s-fw-policy-update\", this.getClass().getCanonicalName().toLowerCase())).build());\n         firewallPolicy = fWaaSApi.getFirewallPolicy(firewallPolicy.getId());\n         assertEquals(updatedFirewallPolicy, firewallPolicy);\n\n         firewallPolicy = fWaaSApi.insertFirewallRuleToPolicy(firewallPolicy.getId(), firewallRule.getId());\n         assertNotNull(firewallPolicy);\n         assertFalse(firewallPolicy.getFirewallRules().isEmpty());\n\n         firewallPolicy = fWaaSApi.removeFirewallRuleFromPolicy(firewallPolicy.getId(), firewallRule.getId());\n         assertNotNull(firewallPolicy);\n         assertTrue(firewallPolicy.getFirewallRules().isEmpty());\n      } finally {\n         // delete\n         if (fWaaSApi != null) {\n            try {\n               if (firewallPolicy != null) {\n                  assertTrue(fWaaSApi.deleteFirewallPolicy(firewallPolicy.getId()));\n               }\n            } finally {\n               assertTrue(fWaaSApi.deleteFirewallRule(firewallRule.getId()));\n            }\n         }\n      }\n   }\n\n   public void testCreateUpdateAndDeleteFirewall() {\n\n      FirewallPolicy firewallPolicy = fWaaSApi.createFirewallPolicy(CreateFirewallPolicy.builder()\n              .name(String.format(\"jclouds-test-%s-fw-policy\", this.getClass().getCanonicalName().toLowerCase()))\n              .description(\"jclouds test fw policy\")\n              .build());\n\n      Firewall firewall = null;\n\n      try {\n         // methods under test\n         firewall = fWaaSApi.create(CreateFirewall.builder().name(String.format(\"jclouds-test-%s-fw\", this.getClass().getCanonicalName().toLowerCase()))\n                 .description(\"jclouds test firewall\")\n                 .firewallPolicyId(firewallPolicy.getId())\n                 .build());\n\n         assertFalse(fWaaSApi.list().concat().toList().isEmpty());\n         assertNotNull(fWaaSApi.list(PaginationOptions.Builder.limit(1)));\n\n         // get\n         firewall = fWaaSApi.get(firewall.getId());\n         assertEquals(firewall.getName(), String.format(\"jclouds-test-%s-fw\", this.getClass().getCanonicalName().toLowerCase()));\n         assertEquals(firewall.getDescription(), \"jclouds test firewall\");\n\n         // update\n         Firewall updatedFirewall = fWaaSApi.update(firewall.getId(), UpdateFirewall.builder().name(String.format(\"jclouds-test-%s-fw_updated\", this.getClass()\n                 .getCanonicalName().toLowerCase())).build());\n         firewall = fWaaSApi.get(firewall.getId());\n         assertEquals(updatedFirewall, firewall);\n\n      } finally {\n         // delete\n         if (fWaaSApi != null) {\n            try {\n               if (firewallPolicy != null) {\n                  assertTrue(fWaaSApi.deleteFirewallPolicy(firewallPolicy.getId()));\n               }\n         } finally {\n            if (firewall != null) {\n               assertTrue(fWaaSApi.delete(firewall.getId()));\n            }         }\n         }\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/java/org/jclouds/openstack/neutron/v2/extensions/FWaaSApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.extensions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.net.URISyntaxException;\nimport java.util.List;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\n\nimport org.jclouds.openstack.neutron.v2.NeutronApi;\nimport org.jclouds.openstack.neutron.v2.domain.CreateFirewall;\nimport org.jclouds.openstack.neutron.v2.domain.CreateFirewallPolicy;\nimport org.jclouds.openstack.neutron.v2.domain.CreateFirewallRule;\nimport org.jclouds.openstack.neutron.v2.domain.Firewall;\nimport org.jclouds.openstack.neutron.v2.domain.FirewallPolicy;\nimport org.jclouds.openstack.neutron.v2.domain.FirewallRule;\nimport org.jclouds.openstack.neutron.v2.domain.FloatingIP;\nimport org.jclouds.openstack.neutron.v2.domain.UpdateFirewall;\nimport org.jclouds.openstack.neutron.v2.domain.UpdateFirewallPolicy;\nimport org.jclouds.openstack.neutron.v2.domain.UpdateFirewallRule;\nimport org.jclouds.openstack.neutron.v2.features.FloatingIPApi;\nimport org.jclouds.openstack.neutron.v2.internal.BaseNeutronApiMockTest;\nimport org.jclouds.openstack.v2_0.domain.PaginatedCollection;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Iterables;\n\n/**\n * Tests Floating Api Guice wiring and parsing\n *\n */\n@Test\npublic class FWaaSApiMockTest extends BaseNeutronApiMockTest {\n\n   public void testCreateFirewall() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/extension_list.json\"))));\n      server.enqueue(addCommonHeaders(\n            new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/firewall_create_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         FWaaSApi api = neutronApi.getFWaaSApi(\"RegionOne\").get();\n\n         CreateFirewall firewallRequest = CreateFirewall.builder()\n                 .firewallPolicyId(\"c69933c1-b472-44f9-8226-30dc4ffd454c\")\n                 .adminStateUp(Boolean.TRUE)\n                 .build();\n\n         Firewall firewall = api.create(firewallRequest);\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertExtensions(server, uriApiVersion + \"\");\n         assertRequest(server.takeRequest(), \"POST\", uriApiVersion + \"/fw/firewalls\", \"/firewall_create_request.json\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(firewall);\n         assertEquals(firewall.getName(), \"\");\n         assertEquals(firewall.getTenantId(), \"45977fa2dbd7482098dd68d0d8970117\");\n         assertEquals(firewall.getDescription(), \"\");\n         assertEquals(firewall.getId(), \"3b0ef8f4-82c7-44d4-a4fb-6177f9a21977\");\n         assertEquals(firewall.getStatus(), \"PENDING_CREATE\");\n         assertTrue(firewall.isAdminStateUp());\n         assertEquals(firewall.getFirewallPolicyId(), \"c69933c1-b472-44f9-8226-30dc4ffd454c\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testListSpecificPageFirewall() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/extension_list.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/firewall_list_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         FWaaSApi api = neutronApi.getFWaaSApi(\"RegionOne\").get();\n\n         PaginatedCollection<Firewall> firewalls = api.list(PaginationOptions.Builder.limit(2).marker(\"abcdefg\"));\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertExtensions(server, uriApiVersion + \"\");\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/fw/firewalls?limit=2&marker=abcdefg\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(firewalls);\n         assertEquals(firewalls.size(), 1);\n         assertEquals(Iterables.getFirst(firewalls, null).getId(), \"5eb708e7-3856-449a-99ac-fec27cd745f9\");\n         assertEquals(firewalls.get(0).getId(), \"5eb708e7-3856-449a-99ac-fec27cd745f9\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testListPagedFirewall() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/floatingip_list_response_paged1.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/floatingip_list_response_paged2.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         FloatingIPApi api = neutronApi.getFloatingIPApi(\"RegionOne\");\n\n         // Note: Lazy! Have to actually look at the collection.\n         List<FloatingIP> floatingIPs = api.list().concat().toList();\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/floatingips\");\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/floatingips?marker=71c1e68c-171a-4aa2-aca5-50ea153a3718\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(floatingIPs);\n         assertEquals(floatingIPs.size(), 4);\n         assertEquals(floatingIPs.get(0).getId(), \"2f245a7b-796b-4f26-9cf9-9e82d248fda7\");\n         assertEquals(floatingIPs.get(3).getId(), \"61cea855-49cb-4846-997d-801b70c71bdd2\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGetFirewall() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/extension_list.json\"))));\n      server.enqueue(addCommonHeaders(\n            new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/firewall_get_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         FWaaSApi api = neutronApi.getFWaaSApi(\"RegionOne\").get();\n\n         Firewall firewall = api.get(\"12345\");\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertExtensions(server, uriApiVersion + \"\");\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/fw/firewalls/12345\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(firewall);\n         assertEquals(firewall.getId(), \"3b0ef8f4-82c7-44d4-a4fb-6177f9a21977\");\n         assertEquals(firewall.getTenantId(), \"45977fa2dbd7482098dd68d0d8970117\");\n         assertEquals(firewall.getDescription(), \"\");\n         assertEquals(firewall.getName(), \"\");\n         assertEquals(firewall.getStatus(), \"ACTIVE\");\n         assertEquals(firewall.getFirewallPolicyId(), \"c69933c1-b472-44f9-8226-30dc4ffd454c\");\n\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testUpdateFirewall() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/extension_list.json\"))));\n      server.enqueue(addCommonHeaders(\n            new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/firewall_update_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         FWaaSApi api = neutronApi.getFWaaSApi(\"RegionOne\").get();\n\n         UpdateFirewall updateFirewall = UpdateFirewall.builder()\n               .adminStateUp(false)\n               .build();\n\n         Firewall firewall = api.update(\"12345\", updateFirewall);\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertExtensions(server, uriApiVersion + \"\");\n         assertRequest(server.takeRequest(), \"PUT\", uriApiVersion + \"/fw/firewalls/12345\", \"/firewall_update_request.json\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(firewall);\n         assertFalse(firewall.isAdminStateUp());\n\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testDeleteFirewall() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/extension_list.json\"))));\n      server.enqueue(addCommonHeaders(\n            new MockResponse().setResponseCode(201)));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         FWaaSApi api = neutronApi.getFWaaSApi(\"RegionOne\").get();\n\n         boolean result = api.delete(\"12345\");\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertExtensions(server, uriApiVersion + \"\");\n         assertRequest(server.takeRequest(), \"DELETE\", uriApiVersion + \"/fw/firewalls/12345\");\n\n         /*\n          * Check response\n          */\n         assertTrue(result);\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testCreateFirewallPolicy() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/extension_list.json\"))));\n      server.enqueue(addCommonHeaders(\n              new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/firewall_policy_create_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         FWaaSApi api = neutronApi.getFWaaSApi(\"RegionOne\").get();\n\n         CreateFirewallPolicy firewallPolicyRequest = CreateFirewallPolicy.builder()\n                 .name(\"jclouds-fw-policy_group-52-e8b\")\n                 .build();\n\n         FirewallPolicy firewallPolicy = api.createFirewallPolicy(firewallPolicyRequest);\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertExtensions(server, uriApiVersion + \"\");\n         assertRequest(server.takeRequest(), \"POST\", uriApiVersion + \"/fw/firewall_policies\", \"/firewall_policy_create_request.json\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(firewallPolicy);\n         assertEquals(firewallPolicy.getName(), \"jclouds-fw-policy_group-52-e8b\");\n         assertEquals(firewallPolicy.getTenantId(), \"3e00d5716204446c8d3c47a466eec25a\");\n         assertEquals(firewallPolicy.getDescription(), \"\");\n         assertEquals(firewallPolicy.getId(), \"12971159-95cf-4ca1-9baa-c82298ae0918\");\n         assertEquals(firewallPolicy.isShared(), false);\n         assertEquals(firewallPolicy.getFirewallRules(), ImmutableList.of());\n         assertEquals(firewallPolicy.isAudited(), false);\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGetFirewallPolicy() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/extension_list.json\"))));\n      server.enqueue(addCommonHeaders(\n              new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/firewall_policy_get_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         FWaaSApi api = neutronApi.getFWaaSApi(\"RegionOne\").get();\n\n         FirewallPolicy firewallPolicy = api.getFirewallPolicy(\"12345\");\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertExtensions(server, uriApiVersion + \"\");\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/fw/firewall_policies/12345\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(firewallPolicy);\n         assertEquals(firewallPolicy.getId(), \"18d2f4e5-afdd-4c10-87ea-d35f38faf98c\");\n         assertEquals(firewallPolicy.getTenantId(), \"e1defcdd823741c89afd5824040deed2\");\n         assertEquals(firewallPolicy.getDescription(), \"\");\n         assertEquals(firewallPolicy.getName(), \"myfirewallrule\");\n         assertEquals(firewallPolicy.isAudited(), false);\n         assertEquals(firewallPolicy.isShared(), true);\n\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testUpdateFirewallPolicy() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/extension_list.json\"))));\n      server.enqueue(addCommonHeaders(\n              new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/firewall_policy_get_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         FWaaSApi api = neutronApi.getFWaaSApi(\"RegionOne\").get();\n\n         UpdateFirewallPolicy updateFirewallPolicy = UpdateFirewallPolicy.builder()\n                 .shared(true)\n                 .build();\n\n         FirewallPolicy firewallPolicy = api.updateFirewallPolicy(\"12345\", updateFirewallPolicy);\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertExtensions(server, uriApiVersion + \"\");\n         assertRequest(server.takeRequest(), \"PUT\", uriApiVersion + \"/fw/firewall_policies/12345\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(firewallPolicy);\n         assertEquals(firewallPolicy.getId(), \"18d2f4e5-afdd-4c10-87ea-d35f38faf98c\");\n         assertEquals(firewallPolicy.getTenantId(), \"e1defcdd823741c89afd5824040deed2\");\n         assertEquals(firewallPolicy.getDescription(), \"\");\n         assertEquals(firewallPolicy.getName(), \"myfirewallrule\");\n         assertEquals(firewallPolicy.isAudited(), false);\n         assertEquals(firewallPolicy.isShared(), true);\n\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testInsertFirewallRuleIntoFirewallPolicy() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/extension_list.json\"))));\n      server.enqueue(addCommonHeaders(\n              new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/firewall_policy_insert_rule_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         FWaaSApi api = neutronApi.getFWaaSApi(\"RegionOne\").get();\n\n         FirewallPolicy updatedFirewallPolicy = api.insertFirewallRuleToPolicy(\"12345\", \"59585143-e819-48c9-944d-f03e0f049dba\");\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertExtensions(server, uriApiVersion + \"\");\n         assertRequest(server.takeRequest(), \"PUT\", uriApiVersion + \"/fw/firewall_policies/12345/insert_rule\", \"/firewall_policy_insert_rule_request.json\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(updatedFirewallPolicy);\n\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testCreateFirewallRule() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/extension_list.json\"))));\n      server.enqueue(addCommonHeaders(\n              new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/firewall_rule_create_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         FWaaSApi api = neutronApi.getFWaaSApi(\"RegionOne\").get();\n\n         CreateFirewallRule firewallRuleRequest = CreateFirewallRule.builder()\n                 .name(\"jclouds-fw-rule_group-52-e8b_port-22\")\n                 .tenantId(\"3e00d5716204446c8d3c47a466eec25a\")\n                 .protocol(\"tcp\")\n                 .destinationIpAddress(\"192.168.0.117\")\n                 .destinationPort(\"22\")\n                 .action(\"allow\")\n                 .shared(false)\n                 .enabled(true)\n                 .build();\n\n         FirewallRule firewallRule = api.createFirewallRule(firewallRuleRequest);\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertExtensions(server, uriApiVersion + \"\");\n         assertRequest(server.takeRequest(), \"POST\", uriApiVersion + \"/fw/firewall_rules\", \"/firewall_rule_create_request.json\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(firewallRule);\n         assertEquals(firewallRule.getName(), \"jclouds-fw-rule_group-52-e8b_port-22\");\n         assertEquals(firewallRule.getTenantId(), \"3e00d5716204446c8d3c47a466eec25a\");\n         assertEquals(firewallRule.getDescription(), \"\");\n         assertEquals(firewallRule.getId(), \"59585143-e819-48c9-944d-f03e0f049dba\");\n         assertEquals(firewallRule.isShared(), false);\n         assertEquals(firewallRule.isEnabled(), true);\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGetFirewallRule() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/extension_list.json\"))));\n      server.enqueue(addCommonHeaders(\n              new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/firewall_rule_get_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         FWaaSApi api = neutronApi.getFWaaSApi(\"RegionOne\").get();\n\n         FirewallRule firewallRule = api.getFirewallRule(\"12345\");\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertExtensions(server, uriApiVersion + \"\");\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/fw/firewall_rules/12345\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(firewallRule);\n         assertEquals(firewallRule.getId(), \"736b1686-3301-4a3d-9eaf-15e3c2682edc\");\n         assertEquals(firewallRule.getTenantId(), \"3e00d5716204446c8d3c47a466eec25a\");\n         assertEquals(firewallRule.getDescription(), \"jclouds test fw rule\");\n         assertEquals(firewallRule.getName(), \"jclouds-test-org.jclouds.openstack.neutron.v2.extensions.fwaasapilivetest-fw-rule-22\");\n         assertEquals(firewallRule.getAction(), \"allow\");\n         assertEquals(firewallRule.isEnabled(), true);\n         assertEquals(firewallRule.getIpVersion().version(), 4);\n         assertEquals(firewallRule.isShared(), false);\n\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testUpdateFirewallRule() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/extension_list.json\"))));\n      server.enqueue(addCommonHeaders(\n              new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/firewall_rule_update_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         FWaaSApi api = neutronApi.getFWaaSApi(\"RegionOne\").get();\n\n         UpdateFirewallRule updateFirewallRule = UpdateFirewallRule.builder()\n                 .build();\n\n         FirewallRule firewallRule = api.updateFirewallRule(\"12345\", updateFirewallRule);\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertExtensions(server, uriApiVersion + \"\");\n         assertRequest(server.takeRequest(), \"PUT\", uriApiVersion + \"/fw/firewall_rules/12345\", \"/firewall_rule_update_request.json\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(firewallRule);\n\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testDeleteFirewallRule() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/extension_list.json\"))));\n      server.enqueue(addCommonHeaders(\n              new MockResponse().setResponseCode(201)));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         FWaaSApi api = neutronApi.getFWaaSApi(\"RegionOne\").get();\n\n         boolean result = api.deleteFirewallRule(\"12345\");\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertExtensions(server, uriApiVersion + \"\");\n         assertRequest(server.takeRequest(), \"DELETE\", uriApiVersion + \"/fw/firewall_rules/12345\");\n\n         /*\n          * Check response\n          */\n         assertTrue(result);\n      } finally {\n         server.shutdown();\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/java/org/jclouds/openstack/neutron/v2/extensions/RouterApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.openstack.neutron.v2.extensions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\n\nimport org.jclouds.openstack.neutron.v2.domain.ExternalGatewayInfo;\nimport org.jclouds.openstack.neutron.v2.domain.Network;\nimport org.jclouds.openstack.neutron.v2.domain.NetworkType;\nimport org.jclouds.openstack.neutron.v2.domain.Port;\nimport org.jclouds.openstack.neutron.v2.domain.Router;\nimport org.jclouds.openstack.neutron.v2.domain.RouterInterface;\nimport org.jclouds.openstack.neutron.v2.domain.Subnet;\nimport org.jclouds.openstack.neutron.v2.features.NetworkApi;\nimport org.jclouds.openstack.neutron.v2.features.PortApi;\nimport org.jclouds.openstack.neutron.v2.features.SubnetApi;\nimport org.jclouds.openstack.neutron.v2.internal.BaseNeutronApiLiveTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests parsing and Guice wiring of RouterApi\n */\n@Test(groups = \"live\", testName = \"RouterApiLiveTest\")\npublic class RouterApiLiveTest extends BaseNeutronApiLiveTest {\n\n   public void testCreateUpdateAndDeleteRouter() {\n      for (String region : api.getConfiguredRegions()) {\n         RouterApi routerApi = api.getRouterApi(region).get();\n         NetworkApi networkApi = api.getNetworkApi(region);\n         SubnetApi subnetApi = api.getSubnetApi(region);\n\n         Network network = networkApi.create(\n               Network.createBuilder(\"jclouds-network-test\").external(true).networkType(NetworkType.LOCAL).build());\n         assertNotNull(network);\n\n         Subnet subnet = subnetApi.create(Subnet.createBuilder(network.getId(), \"192.168.0.0/16\").ipVersion(4).build());\n         assertNotNull(subnet);\n\n         Router router = routerApi.create(Router.createBuilder().name(\"jclouds-router-test\")\n            .externalGatewayInfo(ExternalGatewayInfo.builder().networkId(network.getId()).enableSnat(true).build()).build());\n         assertNotNull(router);\n\n         /* List and Get test */\n         Set<Router> routers = api.getRouterApi(region).get().list().concat().toSet();\n         Router routerList = routers.iterator().next();\n         Router routerGet = api.getRouterApi(region).get().get(routerList.getId());\n\n         assertNotNull(routerGet);\n         assertEquals(routerGet, routerList);\n         /***/\n\n         routerGet = routerApi.get(router.getId());\n\n         assertEquals(routerGet.getName(), router.getName());\n         assertEquals(routerGet.getId(), router.getId());\n         assertEquals(routerGet.getExternalGatewayInfo().getNetworkId(), router.getExternalGatewayInfo().getNetworkId());\n\n         Router routerUpdate = routerApi.update(router.getId(), Router.updateBuilder().name(\"jclouds-router-test-rename\").build());\n         assertNotNull(routerUpdate);\n         assertEquals(routerUpdate.getName(), \"jclouds-router-test-rename\");\n\n         routerGet = routerApi.get(router.getId());\n\n         assertEquals(routerGet.getId(), router.getId());\n         assertEquals(routerGet.getName(), \"jclouds-router-test-rename\");\n\n         assertTrue(routerApi.delete(router.getId()));\n         assertTrue(subnetApi.delete(subnet.getId()));\n         assertTrue(networkApi.delete(network.getId()));\n      }\n   }\n\n   public void testCreateAndDeleteRouterInterfaceForSubnet() {\n      for (String region : api.getConfiguredRegions()) {\n         RouterApi routerApi = api.getRouterApi(region).get();\n         NetworkApi networkApi = api.getNetworkApi(region);\n         SubnetApi subnetApi = api.getSubnetApi(region);\n\n         Network network = networkApi.create(Network.createBuilder(\"jclouds-network-test\").external(true).networkType(NetworkType.LOCAL).build());\n         assertNotNull(network);\n\n         Subnet subnet = subnetApi.create(Subnet.createBuilder(network.getId(), \"192.168.0.0/16\").ipVersion(4).build());\n         assertNotNull(subnet);\n\n         Network network2 = networkApi.create(Network.createBuilder(\"jclouds-network-test2\").external(true).networkType(NetworkType.LOCAL).build());\n         assertNotNull(network2);\n\n         Subnet subnet2 = subnetApi.create(Subnet.createBuilder(network2.getId(), \"192.169.0.0/16\").ipVersion(4).build());\n         assertNotNull(subnet2);\n\n         Router router = routerApi.create(Router.createBuilder().name(\"jclouds-router-test\").build());\n         assertNotNull(router);\n\n         RouterInterface routerInterface = routerApi.addInterfaceForSubnet(router.getId(), subnet.getId());\n         assertNotNull(routerInterface);\n\n         RouterInterface routerInterface2 = routerApi.addInterfaceForSubnet(router.getId(), subnet2.getId());\n         assertNotNull(routerInterface2);\n\n         assertTrue(routerApi.removeInterfaceForSubnet(router.getId(), subnet.getId()));\n         assertTrue(routerApi.removeInterfaceForSubnet(router.getId(), subnet2.getId()));\n         assertTrue(routerApi.delete(router.getId()));\n         assertTrue(subnetApi.delete(subnet.getId()));\n         assertTrue(networkApi.delete(network.getId()));\n         assertTrue(subnetApi.delete(subnet2.getId()));\n         assertTrue(networkApi.delete(network2.getId()));\n      }\n   }\n\n   public void testCreateAndDeleteRouterInterfaceForPort() {\n      for (String region : api.getConfiguredRegions()) {\n         RouterApi routerApi = api.getRouterApi(region).get();\n         NetworkApi networkApi = api.getNetworkApi(region);\n         SubnetApi subnetApi = api.getSubnetApi(region);\n         PortApi portApi = api.getPortApi(region);\n\n         Network network = networkApi.create(Network.createBuilder(\"jclouds-network-test\").external(true).networkType(NetworkType.LOCAL).build());\n         assertNotNull(network);\n\n         Subnet subnet = subnetApi.create(Subnet.createBuilder(network.getId(), \"192.168.0.0/16\").ipVersion(4).build());\n         assertNotNull(subnet);\n\n         Network network2 = networkApi.create(Network.createBuilder(\"jclouds-network-test2\").external(true).networkType(NetworkType.LOCAL).build());\n         assertNotNull(network2);\n\n         Subnet subnet2 = subnetApi.create(Subnet.createBuilder(network2.getId(), \"192.169.0.0/16\").ipVersion(4).build());\n         assertNotNull(subnet2);\n\n         Port port = portApi.create(Port.createBuilder(network.getId()).build());\n         assertNotNull(port);\n\n         Port port2 = portApi.create(Port.createBuilder(network2.getId()).build());\n         assertNotNull(port2);\n\n         Router router = routerApi.create(Router.createBuilder().name(\"jclouds-router-test\").build());\n         assertNotNull(router);\n\n         RouterInterface routerInterface = routerApi.addInterfaceForPort(router.getId(), port.getId());\n         assertNotNull(routerInterface);\n\n         RouterInterface routerInterface2 = routerApi.addInterfaceForPort(router.getId(), port2.getId());\n         assertNotNull(routerInterface2);\n\n         assertTrue(routerApi.removeInterfaceForPort(router.getId(), port.getId()));\n         assertTrue(routerApi.removeInterfaceForPort(router.getId(), port2.getId()));\n         assertTrue(routerApi.delete(router.getId()));\n         assertTrue(subnetApi.delete(subnet.getId()));\n         assertTrue(networkApi.delete(network.getId()));\n         assertTrue(subnetApi.delete(subnet2.getId()));\n         assertTrue(networkApi.delete(network2.getId()));\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/java/org/jclouds/openstack/neutron/v2/extensions/RouterApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.extensions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.net.URISyntaxException;\nimport java.util.List;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\n\nimport org.jclouds.openstack.neutron.v2.NeutronApi;\nimport org.jclouds.openstack.neutron.v2.domain.ExternalGatewayInfo;\nimport org.jclouds.openstack.neutron.v2.domain.NetworkStatus;\nimport org.jclouds.openstack.neutron.v2.domain.Router;\nimport org.jclouds.openstack.neutron.v2.domain.RouterInterface;\nimport org.jclouds.openstack.neutron.v2.domain.Routers;\nimport org.jclouds.openstack.neutron.v2.internal.BaseNeutronApiMockTest;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\nimport org.testng.annotations.Test;\n\n\n/**\n * Tests NetworkApi Guice wiring and parsing\n *\n */\n@Test\npublic class RouterApiMockTest extends BaseNeutronApiMockTest {\n\n   public void testCreateRouter() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/extension_list.json\"))));\n      server.enqueue(addCommonHeaders(\n            new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/router_create_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         RouterApi api = neutronApi.getRouterApi(\"RegionOne\").get();\n\n         Router.CreateRouter createRouter = Router.createBuilder().name(\"another_router\").adminStateUp(Boolean.TRUE)\n               .externalGatewayInfo(ExternalGatewayInfo.builder()\n                     .networkId(\"8ca37218-28ff-41cb-9b10-039601ea7e6b\")\n                     .enableSnat(true)\n                     .build())\n               .build();\n\n         Router router = api.create(createRouter);\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertExtensions(server, uriApiVersion + \"\");\n         assertRequest(server.takeRequest(), \"POST\", uriApiVersion + \"/routers\", \"/router_create_request.json\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(router);\n         assertEquals(router.getName(), \"another_router\");\n         assertEquals(router.getExternalGatewayInfo().getNetworkId(), \"8ca37218-28ff-41cb-9b10-039601ea7e6b\");\n         assertEquals(router.getExternalGatewayInfo().getEnableSnat().booleanValue(), true);\n         assertEquals(router.getStatus(), NetworkStatus.ACTIVE);\n         assertEquals(router.getAdminStateUp(), Boolean.TRUE);\n         assertEquals(router.getId(), \"8604a0de-7f6b-409a-a47c-a1cc7bc77b2e\");\n         assertEquals(router.getTenantId(), \"6b96ff0cb17a4b859e1e575d221683d3\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testListSpecificPageRouter() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/extension_list.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/router_list_response_paged1.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         RouterApi api = neutronApi.getRouterApi(\"RegionOne\").get();\n\n         Routers routers = api.list(PaginationOptions.Builder.limit(2).marker(\"abcdefg\"));\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertExtensions(server, uriApiVersion + \"\");\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/routers?limit=2&marker=abcdefg\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(routers);\n         assertEquals(routers.size(), 2);\n         assertEquals(routers.first().get().getId(), \"a9254bdb-2613-4a13-ac4c-adc581fba50d\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testListPagedRouter() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/extension_list.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/router_list_response_paged1.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/router_list_response_paged2.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         RouterApi api = neutronApi.getRouterApi(\"RegionOne\").get();\n\n         // Note: Lazy! Have to actually look at the collection.\n         List<Router> routers = api.list().concat().toList();\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 4);\n         assertAuthentication(server);\n         assertExtensions(server, uriApiVersion + \"\");\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/routers\");\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/routers?marker=71c1e68c-171a-4aa2-aca5-50ea153a3718\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(routers);\n         assertEquals(routers.size(), 4);\n         assertEquals(routers.get(0).getId(), \"a9254bdb-2613-4a13-ac4c-adc581fba50d\");\n         assertEquals(routers.get(3).getId(), \"a9254bdb-2613-4a13-ac4c-adc581fba50d_4\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGetRouter() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/extension_list.json\"))));\n      server.enqueue(addCommonHeaders(\n            new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/router_get_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         RouterApi api = neutronApi.getRouterApi(\"RegionOne\").get();\n\n         Router router = api.get(\"12345\");\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertExtensions(server, uriApiVersion + \"\");\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/routers/12345\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(router);\n         assertEquals(router.getName(), \"router1\");\n         assertEquals(router.getExternalGatewayInfo().getNetworkId(), \"3c5bcddd-6af9-4e6b-9c3e-c153e521cab8\");\n         assertEquals(router.getStatus(), NetworkStatus.ACTIVE);\n         assertEquals(router.getAdminStateUp(), Boolean.TRUE);\n         assertEquals(router.getId(), \"a9254bdb-2613-4a13-ac4c-adc581fba50d\");\n         assertEquals(router.getTenantId(), \"33a40233088643acb66ff6eb0ebea679\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testUpdateRouter() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/extension_list.json\"))));\n      server.enqueue(addCommonHeaders(\n            new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/router_update_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         RouterApi api = neutronApi.getRouterApi(\"RegionOne\").get();\n\n         Router.UpdateRouter updateRouter = Router.updateBuilder()\n               .externalGatewayInfo(\n                     ExternalGatewayInfo.builder().networkId(\"8ca37218-28ff-41cb-9b10-039601ea7e6b\").build())\n               .build();\n\n         Router router = api.update(\"12345\", updateRouter);\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertExtensions(server, uriApiVersion + \"\");\n         assertRequest(server.takeRequest(), \"PUT\", uriApiVersion + \"/routers/12345\", \"/router_update_request.json\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(router);\n         assertEquals(router.getName(), \"another_router\");\n         assertEquals(router.getExternalGatewayInfo().getNetworkId(), \"8ca37218-28ff-41cb-9b10-039601ea7e6b\");\n         assertEquals(router.getStatus(), NetworkStatus.ACTIVE);\n         assertEquals(router.getAdminStateUp(), Boolean.TRUE);\n         assertEquals(router.getId(), \"8604a0de-7f6b-409a-a47c-a1cc7bc77b2e\");\n         assertEquals(router.getTenantId(), \"6b96ff0cb17a4b859e1e575d221683d3\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testDeleteRouter() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/extension_list.json\"))));\n      server.enqueue(addCommonHeaders(\n            new MockResponse().setResponseCode(201)));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         RouterApi api = neutronApi.getRouterApi(\"RegionOne\").get();\n\n         boolean result = api.delete(\"12345\");\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertExtensions(server, uriApiVersion + \"\");\n         assertRequest(server.takeRequest(), \"DELETE\", uriApiVersion + \"/routers/12345\");\n\n         /*\n          * Check response\n          */\n         assertTrue(result);\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testAddRouterInterfaceForSubnet() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/extension_list.json\"))));\n      server.enqueue(addCommonHeaders(\n            new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/router_add_interface_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         RouterApi api = neutronApi.getRouterApi(\"RegionOne\").get();\n\n         RouterInterface routerInterface = api.addInterfaceForSubnet(\"12345\", \"a2f1f29d-571b-4533-907f-5803ab96ead1\");\n\n         /*\n          * Check request\n          */\n         assertAuthentication(server);\n         assertExtensions(server, uriApiVersion + \"\");\n         assertRequest(server.takeRequest(), \"PUT\", uriApiVersion + \"/routers/12345/add_router_interface\", \"/router_add_interface_request.json\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(routerInterface);\n         assertEquals(routerInterface.getSubnetId(), \"a2f1f29d-571b-4533-907f-5803ab96ead1\");\n         assertEquals(routerInterface.getPortId(), \"3a44f4e5-1694-493a-a1fb-393881c673a4\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testAddRouterInterfaceForPort() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/extension_list.json\"))));\n      server.enqueue(addCommonHeaders(\n            new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/router_add_interface_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         RouterApi api = neutronApi.getRouterApi(\"RegionOne\").get();\n\n         RouterInterface routerInterface = api.addInterfaceForPort(\"12345\", \"portid\");\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertExtensions(server, uriApiVersion + \"\");\n         assertRequest(server.takeRequest(), \"PUT\", uriApiVersion + \"/routers/12345/add_router_interface\", \"/router_add_interface_port_request.json\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(routerInterface);\n         assertEquals(routerInterface.getSubnetId(), \"a2f1f29d-571b-4533-907f-5803ab96ead1\");\n         assertEquals(routerInterface.getPortId(), \"3a44f4e5-1694-493a-a1fb-393881c673a4\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testRemoveRouterInterfaceForSubnet() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/extension_list.json\"))));\n      server.enqueue(addCommonHeaders(\n            new MockResponse().setResponseCode(201)));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         RouterApi api = neutronApi.getRouterApi(\"RegionOne\").get();\n\n         boolean result = api.removeInterfaceForSubnet(\"12345\", \"a2f1f29d-571b-4533-907f-5803ab96ead1\");\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertExtensions(server, uriApiVersion + \"\");\n         assertRequest(server.takeRequest(), \"PUT\", uriApiVersion + \"/routers/12345/remove_router_interface\", \"/router_remove_interface_subnet_request.json\");\n\n         /*\n          * Check response\n          */\n         assertTrue(result);\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testRemoveRouterInterfaceForPort() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/extension_list.json\"))));\n      server.enqueue(addCommonHeaders(\n            new MockResponse().setResponseCode(201)));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         RouterApi api = neutronApi.getRouterApi(\"RegionOne\").get();\n\n         boolean result = api.removeInterfaceForPort(\"12345\", \"portid\");\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertExtensions(server, uriApiVersion + \"\");\n         assertRequest(server.takeRequest(), \"PUT\", uriApiVersion + \"/routers/12345/remove_router_interface\", \"/router_remove_interface_port_request.json\");\n\n         /*\n          * Check response\n          */\n         assertTrue(result);\n      } finally {\n         server.shutdown();\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/java/org/jclouds/openstack/neutron/v2/extensions/lbaas/v1/LBaaSApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.openstack.neutron.v2.extensions.lbaas.v1;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Map;\nimport java.util.concurrent.TimeUnit;\n\nimport org.jclouds.logging.Logger;\nimport org.jclouds.openstack.neutron.v2.domain.Network;\nimport org.jclouds.openstack.neutron.v2.domain.NetworkType;\nimport org.jclouds.openstack.neutron.v2.domain.Subnet;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.HealthMonitor;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.HealthMonitors;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.HttpMethod;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.LBaaSStatus;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.Member;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.Members;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.Pool;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.Pools;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.ProbeType;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.Protocol;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.SessionPersistence;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.VIP;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.VIPs;\nimport org.jclouds.openstack.neutron.v2.features.NetworkApi;\nimport org.jclouds.openstack.neutron.v2.features.SubnetApi;\nimport org.jclouds.openstack.neutron.v2.internal.BaseNeutronApiLiveTest;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Maps;\nimport com.google.common.util.concurrent.Uninterruptibles;\n\n@Test(groups = \"live\", testName = \"LBaaSApiLiveTest\")\npublic class LBaaSApiLiveTest extends BaseNeutronApiLiveTest {\n\n   private Logger logger = getLoggingModule().createLoggerFactory().getLogger(LBaaSApiLiveTest.class.getName());\n\n   private Map<String, Network> networks = Maps.newLinkedHashMap();\n   private Map<String, Subnet> subnets = Maps.newLinkedHashMap();\n\n   public void testLBaaSPresence() throws Exception {\n      for (String region : api.getConfiguredRegions()) {\n         Optional<LBaaSApi> lBaaSv1Api = api.getLBaaSApi(region);\n\n         /*\n          * Check response\n          */\n         assertNotNull(lBaaSv1Api);\n         if (lBaaSv1Api.isPresent()) {\n            logger.info(\"LBaaS API Version 1 is available\");\n         } else {\n            logger.info(\"LBaaS API Version 1 is unavailable\");\n         }\n      }\n   }\n\n   @BeforeClass\n   public void createSubnets() {\n      for (String region : api.getConfiguredRegions()) {\n         Optional<LBaaSApi> lbaasApiExtension = api.getLBaaSApi(region);\n         if (!lbaasApiExtension.isPresent()) {\n            continue;\n         }\n         NetworkApi networkApi = api.getNetworkApi(region);\n         SubnetApi subnetApi = api.getSubnetApi(region);\n\n         Network network = networkApi.create(Network.createBuilder(\"jclouds-lbaas-test-network\").networkType(NetworkType.LOCAL).build());\n         assertNotNull(network);\n         networks.put(region, network);\n\n         Subnet subnet = subnetApi.create(Subnet.createBuilder(network.getId(), \"10.0.0.0/24\").ipVersion(4).name(\"jclouds-lbaas-test-subnet\").build());\n         assertNotNull(subnet);\n         subnets.put(region, subnet);\n      }\n   }\n\n   @AfterClass\n   public void deleteSubnets() {\n      for (String region : api.getConfiguredRegions()) {\n         NetworkApi networkApi = api.getNetworkApi(region);\n         SubnetApi subnetApi = api.getSubnetApi(region);\n\n         try {\n            Subnet subnet = subnets.get(region);\n            if (subnet != null) {\n               assertTrue(subnetApi.delete(subnet.getId()));\n            }\n         } finally {\n            Network network = networks.get(region);\n            if (network != null) {\n               assertTrue(networkApi.delete(network.getId()));\n            }\n         }\n      }\n   }\n\n   public void testCreateUpdateAndDeletePool() {\n      for (String region : api.getConfiguredRegions()) {\n         Optional<LBaaSApi> lbaasApiExtension = api.getLBaaSApi(region);\n         if (!lbaasApiExtension.isPresent()) {\n            continue;\n         }\n         LBaaSApi lbaasApi = lbaasApiExtension.get();\n\n         Subnet subnet = subnets.get(region);\n         Pool pool = null;\n\n         try {\n            // Create\n            Pool.CreatePool createPool = Pool.createBuilder(subnet.getId(), Protocol.HTTP, Pool.ROUND_ROBIN)\n                  .name(\"jclouds-lbaas-test-pool\").description(null).healthMonitors(null).provider(null).adminStateUp(null).build();\n            pool = lbaasApi.createPool(createPool);\n            assertNotNull(pool);\n            assertNotNull(pool.getId());\n            assertEquals(pool.getTenantId(), subnet.getTenantId());\n            assertNull(pool.getVIPId());\n            assertEquals(pool.getName(), \"jclouds-lbaas-test-pool\");\n            assertEquals(pool.getDescription(), \"\");\n            assertEquals(pool.getSubnetId(), subnet.getId());\n            assertEquals(pool.getProtocol(), Protocol.HTTP);\n            assertNotNull(pool.getProvider());\n            assertEquals(pool.getLBMethod(), Pool.ROUND_ROBIN);\n            assertNotNull(pool.getHealthMonitors());\n            assertTrue(pool.getHealthMonitors().isEmpty());\n            assertNotNull(pool.getHealthMonitorsStatus());\n            assertTrue(pool.getHealthMonitorsStatus().isEmpty());\n            assertNotNull(pool.getMembers());\n            assertTrue(pool.getMembers().isEmpty());\n            assertEquals(pool.getAdminStateUp(), Boolean.TRUE);\n            assertTrue(pool.getStatus() == LBaaSStatus.PENDING_CREATE || pool.getStatus() == LBaaSStatus.ACTIVE);\n            assertNull(pool.getStatusDescription());\n\n            // List and Get\n            Pools pools = lbaasApi.listPools(PaginationOptions.Builder.queryParameters(ImmutableMap.of(\"name\", \"jclouds-lbaas-test-pool\").asMultimap()));\n            assertNotNull(pools);\n            assertFalse(pools.isEmpty());\n            Pool poolList = pools.first().get();\n            Pool poolGet = lbaasApi.getPool(poolList.getId());\n            assertNotNull(poolGet);\n            assertEquals(poolGet, poolList);\n\n            poolGet = lbaasApi.getPool(pool.getId());\n            assertNotNull(poolGet);\n            assertEquals(poolGet.getName(), pool.getName());\n            assertEquals(poolGet.getId(), pool.getId());\n\n            // Update\n            Pool.UpdatePool updatePool = Pool.updateBuilder().name(\"jclouds-lbaas-test-pool-renamed\").description(\"new description\").lbMethod(Pool.ROUND_ROBIN)\n                  .healthMonitors(null).adminStateUp(Boolean.FALSE).build();\n            Pool poolUpdate = lbaasApi.updatePool(pool.getId(), updatePool);\n            assertNotNull(poolUpdate);\n            assertEquals(poolUpdate.getName(), \"jclouds-lbaas-test-pool-renamed\");\n            assertEquals(poolUpdate.getLBMethod(), Pool.ROUND_ROBIN);\n            assertNotNull(poolUpdate.getHealthMonitors());\n            assertTrue(poolUpdate.getHealthMonitors().isEmpty());\n            assertNotNull(poolUpdate.getHealthMonitorsStatus());\n            assertTrue(poolUpdate.getHealthMonitorsStatus().isEmpty());\n            assertEquals(poolUpdate.getAdminStateUp(), Boolean.FALSE);\n\n            poolGet = lbaasApi.getPool(pool.getId());\n            assertNotNull(poolGet);\n            assertEquals(poolGet.getId(), pool.getId());\n            assertEquals(poolGet.getTenantId(), subnet.getTenantId());\n            assertNull(poolGet.getVIPId());\n            assertEquals(poolGet.getName(), \"jclouds-lbaas-test-pool-renamed\");\n            assertEquals(poolGet.getDescription(), \"new description\");\n            assertEquals(poolGet.getSubnetId(), subnet.getId());\n            assertEquals(poolGet.getProtocol(), Protocol.HTTP);\n            assertNotNull(poolGet.getProvider());\n            assertEquals(poolGet.getLBMethod(), Pool.ROUND_ROBIN);\n            assertNotNull(poolGet.getHealthMonitors());\n            assertTrue(poolGet.getHealthMonitors().isEmpty());\n            assertNotNull(poolGet.getHealthMonitorsStatus());\n            assertTrue(poolGet.getHealthMonitorsStatus().isEmpty());\n            assertNotNull(poolGet.getMembers());\n            assertTrue(poolGet.getMembers().isEmpty());\n            assertEquals(poolGet.getAdminStateUp(), Boolean.FALSE);\n            assertTrue(poolGet.getStatus() == LBaaSStatus.PENDING_UPDATE || poolGet.getStatus() == LBaaSStatus.ACTIVE);\n            assertNull(poolGet.getStatusDescription());\n         } finally {\n            if (pool != null) {\n               // Delete\n               assertTrue(lbaasApi.deletePool(pool.getId()));\n               Pool poolGet = lbaasApi.getPool(pool.getId());\n               assertNull(poolGet);\n            }\n         }\n      }\n   }\n\n   public void testCreateUpdateAndDeleteMember() throws InterruptedException {\n      for (String region : api.getConfiguredRegions()) {\n         Optional<LBaaSApi> lbaasApiExtension = api.getLBaaSApi(region);\n         if (!lbaasApiExtension.isPresent()) {\n            continue;\n         }\n         LBaaSApi lbaasApi = lbaasApiExtension.get();\n\n         Subnet subnet = subnets.get(region);\n         Pool pool1 = null;\n         Pool pool2 = null;\n         Member member = null;\n\n         try {\n            // Create pools\n            Pool.CreateBuilder createBuilder = Pool.createBuilder(subnet.getId(), Protocol.HTTP, Pool.ROUND_ROBIN)\n                  .name(\"jclouds-lbaas-test-member-pool-1\").description(null).healthMonitors(null).provider(null).adminStateUp(null);\n            pool1 = lbaasApi.createPool(createBuilder.build());\n            assertNotNull(pool1);\n            createBuilder.name(\"jclouds-lbaas-test-member-pool-2\");\n            pool2 = lbaasApi.createPool(createBuilder.build());\n            assertNotNull(pool2);\n\n            // Create\n            Member.CreateMember createMember = Member.createBuilder(pool1.getId(), \"10.0.0.100\", 80)\n                  .weight(null).adminStateUp(null).build();\n            member = lbaasApi.createMember(createMember);\n            assertNotNull(member);\n            assertNotNull(member.getId());\n            assertEquals(member.getTenantId(), subnet.getTenantId());\n            assertEquals(member.getPoolId(), pool1.getId());\n            assertEquals(member.getAddress(), \"10.0.0.100\");\n            assertEquals(member.getProtocolPort(), Integer.valueOf(80));\n            assertEquals(member.getWeight(), Integer.valueOf(1));\n            assertEquals(member.getAdminStateUp(), Boolean.TRUE);\n            assertTrue(member.getStatus() == LBaaSStatus.PENDING_CREATE || member.getStatus() == LBaaSStatus.ACTIVE);\n            assertNull(member.getStatusDescription());\n\n            // List and Get\n            Thread.sleep(5000);\n            Uninterruptibles.sleepUninterruptibly(5, TimeUnit.SECONDS);\n            Members members = lbaasApi.listMembers(PaginationOptions.Builder.queryParameters(ImmutableMap.of(\"tenant_id\", subnet.getTenantId()).asMultimap()));\n            assertNotNull(members);\n            assertFalse(members.isEmpty());\n            Member memberList = members.first().get();\n            Member memberGet = lbaasApi.getMember(memberList.getId());\n            assertNotNull(memberGet);\n            assertEquals(memberGet, memberList);\n\n            memberGet = lbaasApi.getMember(member.getId());\n            assertNotNull(memberGet);\n            assertEquals(memberGet.getId(), member.getId());\n\n            // Verify member appears in pool1 and not in pool2\n            Pool pool1Get = lbaasApi.getPool(pool1.getId());\n            assertNotNull(pool1Get);\n            assertNotNull(pool1Get.getMembers());\n            assertFalse(pool1Get.getMembers().isEmpty());\n            assertEquals(pool1Get.getMembers().iterator().next(), member.getId());\n            Pool pool2Get = lbaasApi.getPool(pool2.getId());\n            assertNotNull(pool2Get);\n            assertNotNull(pool2Get.getMembers());\n            assertTrue(pool2Get.getMembers().isEmpty());\n\n            // Update\n            Member.UpdateMember updateMember = Member.updateBuilder()\n                  .poolId(pool2.getId()).weight(2).adminStateUp(Boolean.FALSE).build();\n            Member memberUpdate = lbaasApi.updateMember(member.getId(), updateMember);\n            assertNotNull(memberUpdate);\n            assertEquals(memberUpdate.getPoolId(), pool2.getId());\n            assertEquals(memberUpdate.getWeight(), Integer.valueOf(2));\n            assertEquals(memberUpdate.getAdminStateUp(), Boolean.FALSE);\n\n            memberGet = lbaasApi.getMember(member.getId());\n            assertNotNull(memberGet);\n            assertNotNull(memberGet.getId());\n            assertEquals(memberGet.getTenantId(), subnet.getTenantId());\n            assertEquals(memberGet.getPoolId(), pool2.getId());\n            assertEquals(member.getAddress(), \"10.0.0.100\");\n            assertEquals(memberGet.getProtocolPort(), Integer.valueOf(80));\n            assertEquals(memberGet.getWeight(), Integer.valueOf(2));\n            assertEquals(memberGet.getAdminStateUp(), Boolean.FALSE);\n            assertTrue(memberGet.getStatus() == LBaaSStatus.PENDING_UPDATE || memberGet.getStatus() == LBaaSStatus.ACTIVE);\n            assertNull(memberGet.getStatusDescription());\n\n            // Verify member appears in pool2 and not in pool1\n            pool1Get = lbaasApi.getPool(pool1.getId());\n            assertNotNull(pool1Get);\n            assertNotNull(pool1Get.getMembers());\n            assertTrue(pool1Get.getMembers().isEmpty());\n            pool2Get = lbaasApi.getPool(pool2.getId());\n            assertNotNull(pool2Get);\n            assertNotNull(pool2Get.getMembers());\n            assertFalse(pool2Get.getMembers().isEmpty());\n            assertEquals(pool2Get.getMembers().iterator().next(), member.getId());\n         } finally {\n            if (member != null) {\n               // Delete\n               assertTrue(lbaasApi.deleteMember(member.getId()));\n               Member memberGet = lbaasApi.getMember(member.getId());\n               assertNull(memberGet);\n\n               // Verify member does not appear in pool1 and in pool2\n               Pool pool1Get = lbaasApi.getPool(pool1.getId());\n               assertNotNull(pool1Get);\n               assertNotNull(pool1Get.getMembers());\n               assertTrue(pool1Get.getMembers().isEmpty());\n               Pool pool2Get = lbaasApi.getPool(pool2.getId());\n               assertNotNull(pool2Get);\n               assertNotNull(pool2Get.getMembers());\n               assertTrue(pool2Get.getMembers().isEmpty());\n            }\n            if (pool2 != null) {\n               assertTrue(lbaasApi.deletePool(pool2.getId()));\n            }\n            if (pool1 != null) {\n               assertTrue(lbaasApi.deletePool(pool1.getId()));\n            }\n         }\n      }\n   }\n\n   public void testCreateUpdateAndDeleteVIP() {\n      for (String region : api.getConfiguredRegions()) {\n         Optional<LBaaSApi> lbaasApiExtension = api.getLBaaSApi(region);\n         if (!lbaasApiExtension.isPresent()) {\n            continue;\n         }\n         LBaaSApi lbaasApi = lbaasApiExtension.get();\n\n         Subnet subnet = subnets.get(region);\n         Pool pool1 = null;\n         Pool pool2 = null;\n         VIP vip = null;\n\n         try {\n            // Create pools\n            Pool.CreateBuilder createBuilder = Pool.createBuilder(subnet.getId(), Protocol.HTTP, Pool.ROUND_ROBIN)\n                  .name(\"jclouds-lbaas-test-vip-pool-1\").description(null).healthMonitors(null).provider(null).adminStateUp(null);\n            pool1 = lbaasApi.createPool(createBuilder.build());\n            assertNotNull(pool1);\n            createBuilder.name(\"jclouds-lbaas-test-vip-pool-2\");\n            pool2 = lbaasApi.createPool(createBuilder.build());\n            assertNotNull(pool2);\n\n            // Create\n            VIP.CreateVIP createVIP = VIP.createBuilder(subnet.getId(), Protocol.HTTP, 80, pool1.getId())\n                  .name(\"jclouds-lbaas-test-vip\").description(null).address(null).sessionPersistence(null).connectionLimit(null).build();\n            vip = lbaasApi.createVIP(createVIP);\n            assertNotNull(vip);\n            assertNotNull(vip.getId());\n            assertEquals(vip.getTenantId(), subnet.getTenantId());\n            assertEquals(vip.getName(), \"jclouds-lbaas-test-vip\");\n            assertEquals(vip.getDescription(), \"\");\n            assertEquals(vip.getSubnetId(), subnet.getId());\n            assertNotNull(vip.getAddress());\n            assertNotNull(vip.getPortId());\n            assertEquals(vip.getProtocol(), Protocol.HTTP);\n            assertEquals(vip.getProtocolPort(), Integer.valueOf(80));\n            assertEquals(vip.getPoolId(), pool1.getId());\n            assertNull(vip.getSessionPersistence());\n            assertEquals(vip.getConnectionLimit(), Integer.valueOf(-1));\n            assertEquals(vip.getAdminStateUp(), Boolean.TRUE);\n            assertTrue(vip.getStatus() == LBaaSStatus.PENDING_CREATE || vip.getStatus() == LBaaSStatus.ACTIVE);\n            assertNull(vip.getStatusDescription());\n\n            // List and Get\n            VIPs vips = lbaasApi.listVIPs(PaginationOptions.Builder.queryParameters(ImmutableMap.of(\"tenant_id\", subnet.getTenantId()).asMultimap()));\n            assertNotNull(vips);\n            assertFalse(vips.isEmpty());\n            VIP vipList = vips.first().get();\n            VIP vipGet = lbaasApi.getVIP(vipList.getId());\n            assertNotNull(vipGet);\n            assertEquals(vipGet, vipList);\n\n            vipGet = lbaasApi.getVIP(vip.getId());\n            assertNotNull(vipGet);\n            assertEquals(vipGet.getId(), vip.getId());\n\n            // Verify VIP appears in pool1 and not in pool2\n            Pool pool1Get = lbaasApi.getPool(pool1.getId());\n            assertNotNull(pool1Get);\n            assertEquals(pool1Get.getVIPId(), vip.getId());\n            Pool pool2Get = lbaasApi.getPool(pool2.getId());\n            assertNotNull(pool2Get);\n            assertNotEquals(pool2Get.getVIPId(), vip.getId());\n\n            // Update\n            SessionPersistence sessionPersistence = SessionPersistence.builder().type(SessionPersistence.Type.HTTP_COOKIE).cookieName(null).build();\n            VIP.UpdateVIP updateVIP = VIP.updateBuilder()\n                  .name(\"jclouds-lbaas-test-vip-renamed\").description(\"new description\").poolId(pool2.getId())\n                  .sessionPersistence(sessionPersistence).connectionLimit(2).adminStateUp(Boolean.FALSE).build();\n            VIP vipUpdate = lbaasApi.updateVIP(vip.getId(), updateVIP);\n            assertNotNull(vipUpdate);\n            assertEquals(vipUpdate.getName(), \"jclouds-lbaas-test-vip-renamed\");\n            assertEquals(vipUpdate.getDescription(), \"new description\");\n            assertEquals(vipUpdate.getPoolId(), pool2.getId());\n            assertEquals(vipUpdate.getSessionPersistence(), sessionPersistence);\n            assertEquals(vipUpdate.getConnectionLimit(), Integer.valueOf(2));\n            assertEquals(vipUpdate.getAdminStateUp(), Boolean.FALSE);\n\n            vipGet = lbaasApi.getVIP(vip.getId());\n            assertNotNull(vipGet);\n            assertNotNull(vipGet.getId());\n            assertEquals(vipGet.getTenantId(), subnet.getTenantId());\n            assertEquals(vipGet.getName(), \"jclouds-lbaas-test-vip-renamed\");\n            assertEquals(vipGet.getDescription(), \"new description\");\n            assertEquals(vipGet.getSubnetId(), subnet.getId());\n            assertNotNull(vipGet.getAddress());\n            assertNotNull(vipGet.getPortId());\n            assertEquals(vipGet.getProtocol(), Protocol.HTTP);\n            assertEquals(vipGet.getProtocolPort(), Integer.valueOf(80));\n            assertEquals(vipGet.getPoolId(), pool2.getId());\n            assertEquals(vipGet.getSessionPersistence(), sessionPersistence);\n            assertEquals(vipGet.getConnectionLimit(), Integer.valueOf(2));\n            assertEquals(vipGet.getAdminStateUp(), Boolean.FALSE);\n            assertTrue(vipGet.getStatus() == LBaaSStatus.PENDING_UPDATE || vipGet.getStatus() == LBaaSStatus.ACTIVE);\n            assertNull(vipGet.getStatusDescription());\n\n            // Verify VIP appears in pool2 and not in pool1\n            pool1Get = lbaasApi.getPool(pool1.getId());\n            assertNotNull(pool1Get);\n            assertNotEquals(pool1Get.getVIPId(), vip.getId());\n            pool2Get = lbaasApi.getPool(pool2.getId());\n            assertNotNull(pool2Get);\n            assertEquals(pool2Get.getVIPId(), vip.getId());\n         } finally {\n            if (vip != null) {\n               // Delete\n               assertTrue(lbaasApi.deleteVIP(vip.getId()));\n               VIP vipGet = lbaasApi.getVIP(vip.getId());\n               assertNull(vipGet);\n\n               // Verify VIP does not appear in pool1 and in pool2\n               Pool pool1Get = lbaasApi.getPool(pool1.getId());\n               assertNotNull(pool1Get);\n               assertNotEquals(pool1Get.getVIPId(), vip.getId());\n               Pool pool2Get = lbaasApi.getPool(pool2.getId());\n               assertNotNull(pool2Get);\n               assertNotEquals(pool2Get.getVIPId(), vip.getId());\n            }\n            if (pool2 != null) {\n               assertTrue(lbaasApi.deletePool(pool2.getId()));\n            }\n            if (pool1 != null) {\n               assertTrue(lbaasApi.deletePool(pool1.getId()));\n            }\n         }\n      }\n   }\n\n   public void testCreateUpdateAndDeleteHealthMonitor() {\n      for (String region : api.getConfiguredRegions()) {\n         Optional<LBaaSApi> lbaasApiExtension = api.getLBaaSApi(region);\n         if (!lbaasApiExtension.isPresent()) {\n            continue;\n         }\n         LBaaSApi lbaasApi = lbaasApiExtension.get();\n\n         Subnet subnet = subnets.get(region);\n         HealthMonitor healthMonitor = null;\n\n         try {\n            // Create\n            HealthMonitor.CreateHealthMonitor createHealthMonitor = HealthMonitor.createBuilder(ProbeType.HTTP, Integer.valueOf(1), Integer.valueOf(1), Integer.valueOf(1))\n                  .httpMethod(null).urlPath(null).expectedCodes(null).adminStateUp(null).build();\n            healthMonitor = lbaasApi.createHealthMonitor(createHealthMonitor);\n            assertNotNull(healthMonitor);\n            assertNotNull(healthMonitor.getId());\n            assertEquals(healthMonitor.getTenantId(), subnet.getTenantId());\n            assertEquals(healthMonitor.getType(), ProbeType.HTTP);\n            assertEquals(healthMonitor.getDelay(), Integer.valueOf(1));\n            assertEquals(healthMonitor.getTimeout(), Integer.valueOf(1));\n            assertEquals(healthMonitor.getMaxRetries(), Integer.valueOf(1));\n            assertEquals(healthMonitor.getHttpMethod(), HttpMethod.GET);\n            assertEquals(healthMonitor.getUrlPath(), \"/\");\n            assertEquals(healthMonitor.getExpectedCodes(), \"200\");\n            assertNotNull(healthMonitor.getPools());\n            assertTrue(healthMonitor.getPools().isEmpty());\n            assertEquals(healthMonitor.getAdminStateUp(), Boolean.TRUE);\n            //assertEquals(healthMonitor.getStatus(), LBaaSStatus.PENDING_CREATE);\n            assertNull(healthMonitor.getStatus());\n            assertNull(healthMonitor.getStatusDescription());\n\n            // List and Get\n            HealthMonitors healthMonitors = lbaasApi.listHealthMonitors(PaginationOptions.Builder.queryParameters(ImmutableMap.of(\"tenant_id\", subnet.getTenantId()).asMultimap()));\n            assertNotNull(healthMonitors);\n            assertFalse(healthMonitors.isEmpty());\n            HealthMonitor healthMonitorList = healthMonitors.first().get();\n            HealthMonitor healthMonitorGet = lbaasApi.getHealthMonitor(healthMonitorList.getId());\n            assertNotNull(healthMonitorGet);\n            assertEquals(healthMonitorGet, healthMonitorList);\n\n            healthMonitorGet = lbaasApi.getHealthMonitor(healthMonitor.getId());\n            assertNotNull(healthMonitorGet);\n            assertEquals(healthMonitorGet.getId(), healthMonitor.getId());\n\n            // Update\n            HealthMonitor.UpdateHealthMonitor updateHealthMonitor = HealthMonitor.updateBuilder().delay(Integer.valueOf(2)).timeout(Integer.valueOf(2)).maxRetries(Integer.valueOf(2))\n                  .httpMethod(HttpMethod.HEAD).urlPath(\"/index.html\").expectedCodes(\"201\").adminStateUp(Boolean.FALSE).build();\n            HealthMonitor healthMonitorUpdate = lbaasApi.updateHealthMonitor(healthMonitor.getId(), updateHealthMonitor);\n            assertNotNull(healthMonitorUpdate);\n            assertEquals(healthMonitorUpdate.getDelay(), Integer.valueOf(2));\n            assertEquals(healthMonitorUpdate.getTimeout(), Integer.valueOf(2));\n            assertEquals(healthMonitorUpdate.getMaxRetries(), Integer.valueOf(2));\n            assertEquals(healthMonitorUpdate.getHttpMethod(), HttpMethod.HEAD);\n            assertEquals(healthMonitorUpdate.getUrlPath(), \"/index.html\");\n            assertEquals(healthMonitorUpdate.getExpectedCodes(), \"201\");\n            assertEquals(healthMonitorUpdate.getAdminStateUp(), Boolean.FALSE);\n\n            healthMonitorGet = lbaasApi.getHealthMonitor(healthMonitor.getId());\n            assertNotNull(healthMonitorGet);\n            assertNotNull(healthMonitorGet.getId());\n            assertEquals(healthMonitorGet.getTenantId(), subnet.getTenantId());\n            assertEquals(healthMonitorGet.getType(), ProbeType.HTTP);\n            assertEquals(healthMonitorGet.getDelay(), Integer.valueOf(2));\n            assertEquals(healthMonitorGet.getTimeout(), Integer.valueOf(2));\n            assertEquals(healthMonitorGet.getMaxRetries(), Integer.valueOf(2));\n            assertEquals(healthMonitorGet.getHttpMethod(), HttpMethod.HEAD);\n            assertEquals(healthMonitorGet.getUrlPath(), \"/index.html\");\n            assertEquals(healthMonitorGet.getExpectedCodes(), \"201\");\n            assertNotNull(healthMonitorGet.getPools());\n            assertTrue(healthMonitorGet.getPools().isEmpty());\n            assertEquals(healthMonitorGet.getAdminStateUp(), Boolean.FALSE);\n            //assertEquals(healthMonitorGet.getStatus(), LBaaSStatus.PENDING_UPDATE);\n            assertNull(healthMonitorGet.getStatus());\n            assertNull(healthMonitorGet.getStatusDescription());\n         } finally {\n            if (healthMonitor != null) {\n               // Delete\n               assertTrue(lbaasApi.deleteHealthMonitor(healthMonitor.getId()));\n               HealthMonitor healthMonitorGet = lbaasApi.getHealthMonitor(healthMonitor.getId());\n               assertNull(healthMonitorGet);\n            }\n         }\n      }\n   }\n\n   public void testAssociateAndDisassociateHealthMonitorWithPool() {\n      for (String region : api.getConfiguredRegions()) {\n         Optional<LBaaSApi> lbaasApiExtension = api.getLBaaSApi(region);\n         if (!lbaasApiExtension.isPresent()) {\n            continue;\n         }\n         LBaaSApi lbaasApi = lbaasApiExtension.get();\n\n         Subnet subnet = subnets.get(region);\n         Pool pool = null;\n         HealthMonitor healthMonitor = null;\n\n         try {\n            // Create pool\n            Pool.CreatePool poolCreateOptions = Pool.createBuilder(subnet.getId(), Protocol.TCP, Pool.ROUND_ROBIN)\n                  .name(\"jclouds-lbaas-test-pool-association\").build();\n            pool = lbaasApi.createPool(poolCreateOptions);\n            assertNotNull(pool);\n            assertNotNull(pool.getId());\n            assertNotNull(pool.getHealthMonitors());\n            assertTrue(pool.getHealthMonitors().isEmpty());\n            assertNotNull(pool.getHealthMonitorsStatus());\n            assertTrue(pool.getHealthMonitorsStatus().isEmpty());\n\n            // Create health monitor\n            HealthMonitor.CreateHealthMonitor healthMonitorCreateOptions = HealthMonitor.createBuilder(ProbeType.HTTP, Integer.valueOf(1), Integer.valueOf(1), Integer.valueOf(1)).build();\n            healthMonitor = lbaasApi.createHealthMonitor(healthMonitorCreateOptions);\n            assertNotNull(healthMonitor);\n            assertNotNull(healthMonitor.getId());\n            assertNotNull(healthMonitor.getPools());\n            assertTrue(healthMonitor.getPools().isEmpty());\n\n            // Associate health monitor with pool\n            HealthMonitor healthMonitorAssociated = lbaasApi.associateHealthMonitor(pool.getId(), healthMonitor.getId());\n            assertNotNull(healthMonitorAssociated);\n\n            // Verify health monitor is associated with pool\n            Pool poolGet = lbaasApi.getPool(pool.getId());\n            assertNotNull(poolGet);\n            assertNotNull(poolGet.getHealthMonitors());\n            assertEquals(poolGet.getHealthMonitors().size(), 1);\n            assertEquals(poolGet.getHealthMonitors().iterator().next(), healthMonitor.getId());\n            assertNotNull(poolGet.getHealthMonitorsStatus());\n            assertEquals(poolGet.getHealthMonitorsStatus().size(), 1);\n            assertEquals(poolGet.getHealthMonitorsStatus().iterator().next().getId(), healthMonitor.getId());\n\n            HealthMonitor healthMonitorGet = lbaasApi.getHealthMonitor(healthMonitor.getId());\n            assertNotNull(healthMonitorGet);\n            assertNotNull(healthMonitorGet.getPools());\n            assertEquals(healthMonitorGet.getPools().size(), 1);\n            assertEquals(healthMonitorGet.getPools().iterator().next().getId(), pool.getId());\n\n            // Disassociate health monitor from pool\n            assertTrue(lbaasApi.disassociateHealthMonitor(pool.getId(), healthMonitor.getId()));\n\n            // Verify health monitor is disassociated from pool\n            poolGet = lbaasApi.getPool(pool.getId());\n            assertNotNull(poolGet);\n            assertNotNull(poolGet.getHealthMonitors());\n            assertTrue(poolGet.getHealthMonitors().isEmpty());\n            assertNotNull(poolGet.getHealthMonitorsStatus());\n            assertTrue(poolGet.getHealthMonitorsStatus().isEmpty());\n\n            healthMonitorGet = lbaasApi.getHealthMonitor(healthMonitor.getId());\n            assertNotNull(healthMonitorGet);\n            assertNotNull(healthMonitorGet.getPools());\n            assertTrue(healthMonitorGet.getPools().isEmpty());\n         } finally {\n            if (healthMonitor != null) {\n               assertTrue(lbaasApi.deleteHealthMonitor(healthMonitor.getId()));\n            }\n            if (pool != null) {\n               assertTrue(lbaasApi.deletePool(pool.getId()));\n            }\n         }\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/java/org/jclouds/openstack/neutron/v2/extensions/lbaas/v1/LBaaSApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.extensions.lbaas.v1;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.util.List;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\n\nimport org.jclouds.openstack.neutron.v2.NeutronApi;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.HealthMonitor;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.HealthMonitors;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.HttpMethod;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.LBaaSStatus;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.Member;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.Members;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.Pool;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.Pools;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.ProbeType;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.Protocol;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.SessionPersistence;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.VIP;\nimport org.jclouds.openstack.neutron.v2.domain.lbaas.v1.VIPs;\nimport org.jclouds.openstack.neutron.v2.internal.BaseNeutronApiMockTest;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableSet;\n\n\n@Test\npublic class LBaaSApiMockTest extends BaseNeutronApiMockTest {\n\n   public void testWhenNamespaceInExtensionsLBaaSPresent() throws IOException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/extension_list_with_lbaas_v1_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         Optional<LBaaSApi> lbaasApiExtension = neutronApi.getLBaaSApi(\"RegionOne\");\n\n         assertAuthentication(server);\n\n         /*\n          * Check response\n          */\n         assertNotNull(lbaasApiExtension);\n         assertEquals(lbaasApiExtension.isPresent(), true, \"LBaaS API Version 1 is expected to be available\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testWhenNamespaceNotInExtensionsListLBaaSNotPresent() throws IOException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/extension_list_without_lbaas_v1_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         Optional<LBaaSApi> lbaasApiExtension = neutronApi.getLBaaSApi(\"RegionOne\");\n\n         assertAuthentication(server);\n\n         /*\n          * Check response\n          */\n         assertNotNull(lbaasApiExtension);\n         assertEquals(lbaasApiExtension.isPresent(), false, \"LBaaS API Version 1 is expected to be unavailable\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testCreatePool() throws IOException, InterruptedException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/extension_list_with_lbaas_v1_response.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/lbaas/v1/pool_create_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         LBaaSApi lbaasApi = neutronApi.getLBaaSApi(\"RegionOne\").get();\n\n         Pool.CreatePool createPool = Pool.createBuilder(\"8032909d-47a1-4715-90af-5153ffe39861\", Protocol.TCP, Pool.ROUND_ROBIN)\n               .name(\"NewPool\").description(null).healthMonitors(null).provider(null).adminStateUp(null).build();\n\n         Pool pool = lbaasApi.createPool(createPool);\n\n         /*\n          * Check request\n          */\n         assertAuthentication(server);\n         server.takeRequest();\n         assertRequest(server.takeRequest(), \"POST\", uriApiVersion + \"/lb/pools\", \"/lbaas/v1/pool_create_request.json\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(pool);\n         assertNotNull(pool.getId());\n         assertEquals(pool.getTenantId(), \"83657cfcdfe44cd5920adaf26c48ceea\");\n         assertNull(pool.getVIPId());\n         assertEquals(pool.getName(), \"NewPool\");\n         assertEquals(pool.getDescription(), \"\");\n         assertEquals(pool.getSubnetId(), \"8032909d-47a1-4715-90af-5153ffe39861\");\n         assertEquals(pool.getProtocol(), Protocol.TCP);\n         assertEquals(pool.getProvider(), \"HAPROXY\");\n         assertEquals(pool.getLBMethod(), Pool.ROUND_ROBIN);\n         assertNotNull(pool.getMembers());\n         assertTrue(pool.getMembers().isEmpty());\n         assertNotNull(pool.getHealthMonitors());\n         assertTrue(pool.getHealthMonitors().isEmpty());\n         assertNotNull(pool.getHealthMonitorsStatus());\n         assertTrue(pool.getHealthMonitorsStatus().isEmpty());\n         assertEquals(pool.getAdminStateUp(), Boolean.TRUE);\n         assertEquals(pool.getStatus(), LBaaSStatus.PENDING_CREATE);\n         assertNull(pool.getStatusDescription());\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testListSpecificPagePool() throws IOException, InterruptedException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/extension_list_with_lbaas_v1_response.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/lbaas/v1/pool_list_response_paged1.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         LBaaSApi lbaasApi = neutronApi.getLBaaSApi(\"RegionOne\").get();\n\n         Pools pools = lbaasApi.listPools(PaginationOptions.Builder.limit(2).marker(\"abcdefg\"));\n\n         /*\n          * Check request\n          */\n         assertAuthentication(server);\n         server.takeRequest();\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/lb/pools?limit=2&marker=abcdefg\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(pools);\n         assertEquals(pools.size(), 1);\n         assertEquals(pools.first().get().getId(), \"72741b06-df4d-4715-b142-276b6bce75ab\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testListPagedPool() throws IOException, InterruptedException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/extension_list_with_lbaas_v1_response.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/lbaas/v1/pool_list_response_paged1.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/lbaas/v1/pool_list_response_paged2.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         LBaaSApi lbaasApi = neutronApi.getLBaaSApi(\"RegionOne\").get();\n\n         // Note: Lazy! Have to actually look at the collection.\n         List<Pool> pools = lbaasApi.listPools().concat().toList();\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 4);\n         assertAuthentication(server);\n         server.takeRequest();\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/lb/pools\");\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/lb/pools?marker=71c1e68c-171a-4aa2-aca5-50ea153a3718\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(pools);\n         assertEquals(pools.size(), 2);\n         assertEquals(pools.get(0).getId(), \"72741b06-df4d-4715-b142-276b6bce75ab\");\n         assertEquals(pools.get(1).getId(), \"72741b06-df4d-4715-b142-276b6bce75ab_2\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGetPool() throws IOException, InterruptedException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/extension_list_with_lbaas_v1_response.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/lbaas/v1/pool_get_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         LBaaSApi lbaasApi = neutronApi.getLBaaSApi(\"RegionOne\").get();\n\n         Pool pool = lbaasApi.getPool(\"72741b06-df4d-4715-b142-276b6bce75ab\");\n\n         /*\n          * Check request\n          */\n         assertAuthentication(server);\n         server.takeRequest();\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/lb/pools/72741b06-df4d-4715-b142-276b6bce75ab\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(pool);\n         assertEquals(pool.getId(), \"72741b06-df4d-4715-b142-276b6bce75ab\");\n         assertEquals(pool.getTenantId(), \"83657cfcdfe44cd5920adaf26c48ceea\");\n         assertNotNull(pool.getVIPId());\n         assertEquals(pool.getName(), \"app_pool\");\n         assertEquals(pool.getDescription(), \"\");\n         assertEquals(pool.getSubnetId(), \"8032909d-47a1-4715-90af-5153ffe39861\");\n         assertEquals(pool.getProtocol(), Protocol.HTTP);\n         assertEquals(pool.getProvider(), \"HAPROXY\");\n         assertEquals(pool.getLBMethod(), Pool.ROUND_ROBIN);\n         assertNotNull(pool.getMembers());\n         assertEquals(pool.getMembers().size(), 2);\n         assertNotNull(pool.getHealthMonitors());\n         assertEquals(pool.getHealthMonitors().size(), 2);\n         assertNotNull(pool.getHealthMonitorsStatus());\n         assertEquals(pool.getHealthMonitorsStatus().size(), 2);\n         assertEquals(pool.getAdminStateUp(), Boolean.TRUE);\n         assertEquals(pool.getStatus(), LBaaSStatus.ACTIVE);\n         assertNull(pool.getStatusDescription());\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testUpdatePool() throws IOException, InterruptedException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/extension_list_with_lbaas_v1_response.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/lbaas/v1/pool_update_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         LBaaSApi lbaasApi = neutronApi.getLBaaSApi(\"RegionOne\").get();\n\n         Pool.UpdatePool updatePool = Pool.updateBuilder().name(\"new_name\").description(\"new description\").lbMethod(\"NEW_LB_METHOD\")\n               .healthMonitors(ImmutableSet.of(\"5d4b5228-33b0-4e60-b225-9b727c1a20e7\")).adminStateUp(Boolean.FALSE).build();\n\n         Pool pool = lbaasApi.updatePool(\"72741b06-df4d-4715-b142-276b6bce75ab\", updatePool);\n\n         /*\n          * Check request\n          */\n         assertAuthentication(server);\n         server.takeRequest();\n         assertRequest(server.takeRequest(), \"PUT\", uriApiVersion + \"/lb/pools/72741b06-df4d-4715-b142-276b6bce75ab\", \"/lbaas/v1/pool_update_request.json\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(pool);\n         assertEquals(pool.getId(), \"72741b06-df4d-4715-b142-276b6bce75ab\");\n         assertEquals(pool.getTenantId(), \"83657cfcdfe44cd5920adaf26c48ceea\");\n         assertNotNull(pool.getVIPId());\n         assertEquals(pool.getName(), \"new_name\");\n         assertEquals(pool.getDescription(), \"new description\");\n         assertEquals(pool.getSubnetId(), \"8032909d-47a1-4715-90af-5153ffe39861\");\n         assertEquals(pool.getProtocol(), Protocol.HTTP);\n         assertEquals(pool.getProvider(), \"HAPROXY\");\n         assertEquals(pool.getLBMethod(), \"NEW_LB_METHOD\");\n         assertNotNull(pool.getMembers());\n         assertEquals(pool.getMembers().size(), 2);\n         assertNotNull(pool.getHealthMonitors());\n         assertEquals(pool.getHealthMonitors().size(), 1);\n         assertEquals(pool.getHealthMonitors().iterator().next(), \"5d4b5228-33b0-4e60-b225-9b727c1a20e7\");\n         assertNotNull(pool.getHealthMonitorsStatus());\n         assertEquals(pool.getHealthMonitorsStatus().size(), 1);\n         assertEquals(pool.getHealthMonitorsStatus().iterator().next().getId(), \"5d4b5228-33b0-4e60-b225-9b727c1a20e7\");\n         assertEquals(pool.getAdminStateUp(), Boolean.FALSE);\n         assertEquals(pool.getStatus(), LBaaSStatus.ACTIVE);\n         assertNull(pool.getStatusDescription());\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testDeletePool() throws IOException, InterruptedException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/extension_list_with_lbaas_v1_response.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(204)));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         LBaaSApi lbaasApi = neutronApi.getLBaaSApi(\"RegionOne\").get();\n\n         boolean result = lbaasApi.deletePool(\"72741b06-df4d-4715-b142-276b6bce75ab\");\n\n         /*\n          * Check request\n          */\n         assertAuthentication(server);\n         server.takeRequest();\n         assertRequest(server.takeRequest(), \"DELETE\", uriApiVersion + \"/lb/pools/72741b06-df4d-4715-b142-276b6bce75ab\");\n\n         /*\n          * Check response\n          */\n         assertTrue(result);\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testCreateMember() throws IOException, InterruptedException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/extension_list_with_lbaas_v1_response.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/lbaas/v1/member_create_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         LBaaSApi lbaasApi = neutronApi.getLBaaSApi(\"RegionOne\").get();\n\n         Member.CreateMember createMember = Member.createBuilder(\"72741b06-df4d-4715-b142-276b6bce75ab\", null, 80)\n               .weight(null).adminStateUp(null).build();\n\n         Member member = lbaasApi.createMember(createMember);\n\n         /*\n          * Check request\n          */\n         assertAuthentication(server);\n         server.takeRequest();\n         assertRequest(server.takeRequest(), \"POST\", uriApiVersion + \"/lb/members\", \"/lbaas/v1/member_create_request.json\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(member);\n         assertNotNull(member.getId());\n         assertEquals(member.getTenantId(), \"83657cfcdfe44cd5920adaf26c48ceea\");\n         assertEquals(member.getPoolId(), \"72741b06-df4d-4715-b142-276b6bce75ab\");\n         assertNotNull(member.getAddress());\n         assertEquals(member.getProtocolPort(), Integer.valueOf(80));\n         assertEquals(member.getWeight(), Integer.valueOf(1));\n         assertEquals(member.getAdminStateUp(), Boolean.TRUE);\n         assertEquals(member.getStatus(), LBaaSStatus.PENDING_CREATE);\n         assertNull(member.getStatusDescription());\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testListSpecificPageMember() throws IOException, InterruptedException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/extension_list_with_lbaas_v1_response.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/lbaas/v1/member_list_response_paged1.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         LBaaSApi lbaasApi = neutronApi.getLBaaSApi(\"RegionOne\").get();\n\n         Members members = lbaasApi.listMembers(PaginationOptions.Builder.limit(2).marker(\"abcdefg\"));\n\n         /*\n          * Check request\n          */\n         assertAuthentication(server);\n         server.takeRequest();\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/lb/members?limit=2&marker=abcdefg\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(members);\n         assertEquals(members.size(), 1);\n         assertEquals(members.first().get().getId(), \"48a471ea-64f1-4eb6-9be7-dae6bbe40a0f\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testListPagedMember() throws IOException, InterruptedException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/extension_list_with_lbaas_v1_response.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/lbaas/v1/member_list_response_paged1.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/lbaas/v1/member_list_response_paged2.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         LBaaSApi lbaasApi = neutronApi.getLBaaSApi(\"RegionOne\").get();\n\n         // Note: Lazy! Have to actually look at the collection.\n         List<Member> members = lbaasApi.listMembers().concat().toList();\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 4);\n         assertAuthentication(server);\n         server.takeRequest();\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/lb/members\");\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/lb/members?marker=396f12f8-521e-4b91-8e21-2e003500433a\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(members);\n         assertEquals(members.size(), 2);\n         assertEquals(members.get(0).getId(), \"48a471ea-64f1-4eb6-9be7-dae6bbe40a0f\");\n         assertEquals(members.get(1).getId(), \"701b531b-111a-4f21-ad85-4795b7b12af6\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGetMember() throws IOException, InterruptedException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/extension_list_with_lbaas_v1_response.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/lbaas/v1/member_get_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         LBaaSApi lbaasApi = neutronApi.getLBaaSApi(\"RegionOne\").get();\n\n         Member member = lbaasApi.getMember(\"48a471ea-64f1-4eb6-9be7-dae6bbe40a0f\");\n\n         /*\n          * Check request\n          */\n         assertAuthentication(server);\n         server.takeRequest();\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/lb/members/48a471ea-64f1-4eb6-9be7-dae6bbe40a0f\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(member);\n         assertEquals(member.getId(), \"48a471ea-64f1-4eb6-9be7-dae6bbe40a0f\");\n         assertEquals(member.getTenantId(), \"83657cfcdfe44cd5920adaf26c48ceea\");\n         assertEquals(member.getPoolId(), \"72741b06-df4d-4715-b142-276b6bce75ab\");\n         assertEquals(member.getAddress(), \"10.0.0.5\");\n         assertEquals(member.getProtocolPort(), Integer.valueOf(80));\n         assertEquals(member.getWeight(), Integer.valueOf(1));\n         assertEquals(member.getAdminStateUp(), Boolean.TRUE);\n         assertEquals(member.getStatus(), LBaaSStatus.ACTIVE);\n         assertNull(member.getStatusDescription());\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testUpdateMember() throws IOException, InterruptedException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/extension_list_with_lbaas_v1_response.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/lbaas/v1/member_update_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         LBaaSApi lbaasApi = neutronApi.getLBaaSApi(\"RegionOne\").get();\n\n         Member.UpdateMember updateMember = Member.updateBuilder().poolId(\"new_pool_id\").weight(2)\n               .adminStateUp(Boolean.FALSE).build();\n\n         Member member = lbaasApi.updateMember(\"48a471ea-64f1-4eb6-9be7-dae6bbe40a0f\", updateMember);\n\n         /*\n          * Check request\n          */\n         assertAuthentication(server);\n         server.takeRequest();\n         assertRequest(server.takeRequest(), \"PUT\", uriApiVersion + \"/lb/members/48a471ea-64f1-4eb6-9be7-dae6bbe40a0f\", \"/lbaas/v1/member_update_request.json\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(member);\n         assertEquals(member.getId(), \"48a471ea-64f1-4eb6-9be7-dae6bbe40a0f\");\n         assertEquals(member.getTenantId(), \"83657cfcdfe44cd5920adaf26c48ceea\");\n         assertEquals(member.getPoolId(), \"new_pool_id\");\n         assertEquals(member.getAddress(), \"10.0.0.5\");\n         assertEquals(member.getProtocolPort(), Integer.valueOf(80));\n         assertEquals(member.getWeight(), Integer.valueOf(2));\n         assertEquals(member.getAdminStateUp(), Boolean.FALSE);\n         assertEquals(member.getStatus(), LBaaSStatus.ACTIVE);\n         assertNull(member.getStatusDescription());\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testDeleteMember() throws IOException, InterruptedException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/extension_list_with_lbaas_v1_response.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(204)));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         LBaaSApi lbaasApi = neutronApi.getLBaaSApi(\"RegionOne\").get();\n\n         boolean result = lbaasApi.deleteMember(\"48a471ea-64f1-4eb6-9be7-dae6bbe40a0f\");\n\n         /*\n          * Check request\n          */\n         assertAuthentication(server);\n         server.takeRequest();\n         assertRequest(server.takeRequest(), \"DELETE\", uriApiVersion + \"/lb/members/48a471ea-64f1-4eb6-9be7-dae6bbe40a0f\");\n\n         /*\n          * Check response\n          */\n         assertTrue(result);\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testCreateVIP() throws IOException, InterruptedException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/extension_list_with_lbaas_v1_response.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/lbaas/v1/vip_create_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         LBaaSApi lbaasApi = neutronApi.getLBaaSApi(\"RegionOne\").get();\n\n         VIP.CreateVIP createVIP = VIP.createBuilder(\"8032909d-47a1-4715-90af-5153ffe39861\", Protocol.HTTP, 80, \"61b1f87a-7a21-4ad3-9dda-7f81d249944f\")\n               .name(\"NewVip\").description(null).address(null).sessionPersistence(null).connectionLimit(null).build();\n\n         VIP vip = lbaasApi.createVIP(createVIP);\n\n         /*\n          * Check request\n          */\n         assertAuthentication(server);\n         server.takeRequest();\n         assertRequest(server.takeRequest(), \"POST\", uriApiVersion + \"/lb/vips\", \"/lbaas/v1/vip_create_request.json\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(vip);\n         assertNotNull(vip.getId());\n         assertEquals(vip.getTenantId(), \"83657cfcdfe44cd5920adaf26c48ceea\");\n         assertEquals(vip.getName(), \"NewVip\");\n         assertEquals(vip.getDescription(), \"\");\n         assertEquals(vip.getSubnetId(), \"8032909d-47a1-4715-90af-5153ffe39861\");\n         assertEquals(vip.getAddress(), \"10.0.0.11\");\n         assertEquals(vip.getPortId(), \"f7e6fe6a-b8b5-43a8-8215-73456b32e0f5\");\n         assertEquals(vip.getProtocol(), Protocol.HTTP);\n         assertEquals(vip.getProtocolPort(), Integer.valueOf(80));\n         assertEquals(vip.getPoolId(), \"61b1f87a-7a21-4ad3-9dda-7f81d249944f\");\n         assertNull(vip.getSessionPersistence());\n         assertEquals(vip.getConnectionLimit(), Integer.valueOf(-1));\n         assertEquals(vip.getAdminStateUp(), Boolean.TRUE);\n         assertEquals(vip.getStatus(), LBaaSStatus.PENDING_CREATE);\n         assertNull(vip.getStatusDescription());\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testListSpecificPageVIP() throws IOException, InterruptedException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/extension_list_with_lbaas_v1_response.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/lbaas/v1/vip_list_response_paged1.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         LBaaSApi lbaasApi = neutronApi.getLBaaSApi(\"RegionOne\").get();\n\n         VIPs vips = lbaasApi.listVIPs(PaginationOptions.Builder.limit(2).marker(\"abcdefg\"));\n\n         /*\n          * Check request\n          */\n         assertAuthentication(server);\n         server.takeRequest();\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/lb/vips?limit=2&marker=abcdefg\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(vips);\n         assertEquals(vips.size(), 1);\n         assertEquals(vips.first().get().getId(), \"4ec89087-d057-4e2c-911f-60a3b47ee304\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testListPagedVIP() throws IOException, InterruptedException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/extension_list_with_lbaas_v1_response.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/lbaas/v1/vip_list_response_paged1.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/lbaas/v1/vip_list_response_paged2.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         LBaaSApi lbaasApi = neutronApi.getLBaaSApi(\"RegionOne\").get();\n\n         // Note: Lazy! Have to actually look at the collection.\n         List<VIP> vips = lbaasApi.listVIPs().concat().toList();\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 4);\n         assertAuthentication(server);\n         server.takeRequest();\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/lb/vips\");\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/lb/vips?marker=396f12f8-521e-4b91-8e21-2e003500433a\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(vips);\n         assertEquals(vips.size(), 2);\n         assertEquals(vips.get(0).getId(), \"4ec89087-d057-4e2c-911f-60a3b47ee304\");\n         assertEquals(vips.get(1).getId(), \"c987d2be-9a3c-4ac9-a046-e8716b1350e2\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGetVIP() throws IOException, InterruptedException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/extension_list_with_lbaas_v1_response.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/lbaas/v1/vip_get_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         LBaaSApi lbaasApi = neutronApi.getLBaaSApi(\"RegionOne\").get();\n\n         VIP vip = lbaasApi.getVIP(\"4ec89087-d057-4e2c-911f-60a3b47ee304\");\n\n         /*\n          * Check request\n          */\n         assertAuthentication(server);\n         server.takeRequest();\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/lb/vips/4ec89087-d057-4e2c-911f-60a3b47ee304\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(vip);\n         assertNotNull(vip.getId());\n         assertEquals(vip.getTenantId(), \"83657cfcdfe44cd5920adaf26c48ceea\");\n         assertEquals(vip.getName(), \"my-vip\");\n         assertEquals(vip.getDescription(), \"\");\n         assertEquals(vip.getSubnetId(), \"8032909d-47a1-4715-90af-5153ffe39861\");\n         assertEquals(vip.getAddress(), \"10.0.0.10\");\n         assertEquals(vip.getPortId(), \"b5a743d6-056b-468b-862d-fb13a9aa694e\");\n         assertEquals(vip.getProtocol(), Protocol.HTTP);\n         assertEquals(vip.getProtocolPort(), Integer.valueOf(80));\n         assertEquals(vip.getPoolId(), \"72741b06-df4d-4715-b142-276b6bce75ab\");\n         SessionPersistence sessionPersistence = SessionPersistence.builder().type(SessionPersistence.Type.APP_COOKIE).cookieName(\"MyAppCookie\").build();\n         assertEquals(vip.getSessionPersistence(), sessionPersistence);\n         assertEquals(vip.getConnectionLimit(), Integer.valueOf(1000));\n         assertEquals(vip.getAdminStateUp(), Boolean.TRUE);\n         assertEquals(vip.getStatus(), LBaaSStatus.ACTIVE);\n         assertNull(vip.getStatusDescription());\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testUpdateVIP() throws IOException, InterruptedException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/extension_list_with_lbaas_v1_response.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/lbaas/v1/vip_update_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         LBaaSApi lbaasApi = neutronApi.getLBaaSApi(\"RegionOne\").get();\n\n         SessionPersistence sessionPersistence = SessionPersistence.builder().type(SessionPersistence.Type.APP_COOKIE).cookieName(\"MyNewAppCookie\").build();\n         VIP.UpdateVIP updateVIP = VIP.updateBuilder().name(\"new-name\").description(\"new description\").poolId(\"61b1f87a-7a21-4ad3-9dda-7f81d249944f\")\n               .sessionPersistence(sessionPersistence).connectionLimit(50).adminStateUp(Boolean.FALSE).build();\n\n         VIP vip = lbaasApi.updateVIP(\"c987d2be-9a3c-4ac9-a046-e8716b1350e2\", updateVIP);\n\n         /*\n          * Check request\n          */\n         assertAuthentication(server);\n         server.takeRequest();\n         assertRequest(server.takeRequest(), \"PUT\", uriApiVersion + \"/lb/vips/c987d2be-9a3c-4ac9-a046-e8716b1350e2\", \"/lbaas/v1/vip_update_request.json\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(vip);\n         assertNotNull(vip.getId());\n         assertEquals(vip.getTenantId(), \"83657cfcdfe44cd5920adaf26c48ceea\");\n         assertEquals(vip.getName(), \"new-name\");\n         assertEquals(vip.getDescription(), \"new description\");\n         assertEquals(vip.getSubnetId(), \"8032909d-47a1-4715-90af-5153ffe39861\");\n         assertEquals(vip.getAddress(), \"10.0.0.11\");\n         assertEquals(vip.getPortId(), \"f7e6fe6a-b8b5-43a8-8215-73456b32e0f5\");\n         assertEquals(vip.getProtocol(), Protocol.HTTP);\n         assertEquals(vip.getProtocolPort(), Integer.valueOf(80));\n         assertEquals(vip.getPoolId(), \"61b1f87a-7a21-4ad3-9dda-7f81d249944f\");\n         assertEquals(vip.getSessionPersistence(), sessionPersistence);\n         assertEquals(vip.getConnectionLimit(), Integer.valueOf(50));\n         assertEquals(vip.getAdminStateUp(), Boolean.FALSE);\n         assertEquals(vip.getStatus(), LBaaSStatus.PENDING_UPDATE);\n         assertNull(vip.getStatusDescription());\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testDeleteVIP() throws IOException, InterruptedException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/extension_list_with_lbaas_v1_response.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(204)));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         LBaaSApi lbaasApi = neutronApi.getLBaaSApi(\"RegionOne\").get();\n\n         boolean result = lbaasApi.deleteVIP(\"c987d2be-9a3c-4ac9-a046-e8716b1350e2\");\n\n         /*\n          * Check request\n          */\n         assertAuthentication(server);\n         server.takeRequest();\n         assertRequest(server.takeRequest(), \"DELETE\", uriApiVersion + \"/lb/vips/c987d2be-9a3c-4ac9-a046-e8716b1350e2\");\n\n         /*\n          * Check response\n          */\n         assertTrue(result);\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testCreateHealthMonitor() throws IOException, InterruptedException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/extension_list_with_lbaas_v1_response.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/lbaas/v1/health_monitor_create_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         LBaaSApi lbaasApi = neutronApi.getLBaaSApi(\"RegionOne\").get();\n\n         HealthMonitor.CreateHealthMonitor createHealthMonitor = HealthMonitor.createBuilder(ProbeType.HTTP, Integer.valueOf(1), Integer.valueOf(1), Integer.valueOf(1))\n               .httpMethod(null).urlPath(null).expectedCodes(null).adminStateUp(null).build();\n\n         HealthMonitor healthMonitor = lbaasApi.createHealthMonitor(createHealthMonitor);\n\n         /*\n          * Check request\n          */\n         assertAuthentication(server);\n         server.takeRequest();\n         assertRequest(server.takeRequest(), \"POST\", uriApiVersion + \"/lb/health_monitors\", \"/lbaas/v1/health_monitor_create_request.json\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(healthMonitor);\n         assertNotNull(healthMonitor.getId());\n         assertEquals(healthMonitor.getTenantId(), \"4fd44f30292945e481c7b8a0c8908869\");\n         assertEquals(healthMonitor.getType(), ProbeType.HTTP);\n         assertEquals(healthMonitor.getDelay(), Integer.valueOf(1));\n         assertEquals(healthMonitor.getTimeout(), Integer.valueOf(1));\n         assertEquals(healthMonitor.getMaxRetries(), Integer.valueOf(1));\n         assertEquals(healthMonitor.getHttpMethod(), HttpMethod.GET);\n         assertEquals(healthMonitor.getUrlPath(), \"/\");\n         assertEquals(healthMonitor.getExpectedCodes(), \"200\");\n         assertNotNull(healthMonitor.getPools());\n         assertTrue(healthMonitor.getPools().isEmpty());\n         assertEquals(healthMonitor.getAdminStateUp(), Boolean.TRUE);\n         assertEquals(healthMonitor.getStatus(), LBaaSStatus.PENDING_CREATE);\n         assertNull(healthMonitor.getStatusDescription());\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testListSpecificPageHealthMonitor() throws IOException, InterruptedException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/extension_list_with_lbaas_v1_response.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/lbaas/v1/health_monitor_list_response_paged1.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         LBaaSApi lbaasApi = neutronApi.getLBaaSApi(\"RegionOne\").get();\n\n         HealthMonitors healthMonitors = lbaasApi.listHealthMonitors(PaginationOptions.Builder.limit(2).marker(\"abcdefg\"));\n\n         /*\n          * Check request\n          */\n         assertAuthentication(server);\n         server.takeRequest();\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/lb/health_monitors?limit=2&marker=abcdefg\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(healthMonitors);\n         assertEquals(healthMonitors.size(), 1);\n         assertEquals(healthMonitors.first().get().getId(), \"466c8345-28d8-4f84-a246-e04380b0461d\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testListPagedHealthMonitor() throws IOException, InterruptedException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/extension_list_with_lbaas_v1_response.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/lbaas/v1/health_monitor_list_response_paged1.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/lbaas/v1/health_monitor_list_response_paged2.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         LBaaSApi lbaasApi = neutronApi.getLBaaSApi(\"RegionOne\").get();\n\n         // Note: Lazy! Have to actually look at the collection.\n         List<HealthMonitor> healthMonitors = lbaasApi.listHealthMonitors().concat().toList();\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 4);\n         assertAuthentication(server);\n         server.takeRequest();\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/lb/health_monitors\");\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/lb/health_monitors?marker=396f12f8-521e-4b91-8e21-2e003500433a\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(healthMonitors);\n         assertEquals(healthMonitors.size(), 2);\n         assertEquals(healthMonitors.get(0).getId(), \"466c8345-28d8-4f84-a246-e04380b0461d\");\n         assertEquals(healthMonitors.get(1).getId(), \"5d4b5228-33b0-4e60-b225-9b727c1a20e7\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGetHealthMonitor() throws IOException, InterruptedException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/extension_list_with_lbaas_v1_response.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/lbaas/v1/health_monitor_get_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         LBaaSApi lbaasApi = neutronApi.getLBaaSApi(\"RegionOne\").get();\n\n         HealthMonitor healthMonitor = lbaasApi.getHealthMonitor(\"5d4b5228-33b0-4e60-b225-9b727c1a20e7\");\n\n         /*\n          * Check request\n          */\n         assertAuthentication(server);\n         server.takeRequest();\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/lb/health_monitors/5d4b5228-33b0-4e60-b225-9b727c1a20e7\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(healthMonitor);\n         assertEquals(healthMonitor.getId(), \"5d4b5228-33b0-4e60-b225-9b727c1a20e7\");\n         assertEquals(healthMonitor.getTenantId(), \"4fd44f30292945e481c7b8a0c8908869\");\n         assertEquals(healthMonitor.getType(), ProbeType.HTTP);\n         assertEquals(healthMonitor.getDelay(), Integer.valueOf(5));\n         assertEquals(healthMonitor.getTimeout(), Integer.valueOf(2));\n         assertEquals(healthMonitor.getMaxRetries(), Integer.valueOf(2));\n         assertEquals(healthMonitor.getHttpMethod(), HttpMethod.GET);\n         assertEquals(healthMonitor.getUrlPath(), \"/\");\n         assertEquals(healthMonitor.getExpectedCodes(), \"200\");\n         assertNotNull(healthMonitor.getPools());\n         assertTrue(healthMonitor.getPools().isEmpty());\n         assertEquals(healthMonitor.getAdminStateUp(), Boolean.TRUE);\n         assertEquals(healthMonitor.getStatus(), LBaaSStatus.ACTIVE);\n         assertNull(healthMonitor.getStatusDescription());\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testUpdateHealthMonitor() throws IOException, InterruptedException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/extension_list_with_lbaas_v1_response.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/lbaas/v1/health_monitor_update_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         LBaaSApi lbaasApi = neutronApi.getLBaaSApi(\"RegionOne\").get();\n\n         HealthMonitor.UpdateHealthMonitor updateHealthMonitor = HealthMonitor.updateBuilder().delay(Integer.valueOf(1)).timeout(Integer.valueOf(1)).maxRetries(Integer.valueOf(1))\n               .httpMethod(HttpMethod.HEAD).urlPath(\"/index.html\").expectedCodes(\"201\").adminStateUp(Boolean.FALSE).build();\n\n         HealthMonitor healthMonitor = lbaasApi.updateHealthMonitor(\"466c8345-28d8-4f84-a246-e04380b0461d\", updateHealthMonitor);\n\n         /*\n          * Check request\n          */\n         assertAuthentication(server);\n         server.takeRequest();\n         assertRequest(server.takeRequest(), \"PUT\", uriApiVersion + \"/lb/health_monitors/466c8345-28d8-4f84-a246-e04380b0461d\", \"/lbaas/v1/health_monitor_update_request.json\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(healthMonitor);\n         assertEquals(healthMonitor.getId(), \"466c8345-28d8-4f84-a246-e04380b0461d\");\n         assertEquals(healthMonitor.getTenantId(), \"4fd44f30292945e481c7b8a0c8908869\");\n         assertEquals(healthMonitor.getType(), ProbeType.HTTP);\n         assertEquals(healthMonitor.getDelay(), Integer.valueOf(1));\n         assertEquals(healthMonitor.getTimeout(), Integer.valueOf(1));\n         assertEquals(healthMonitor.getMaxRetries(), Integer.valueOf(1));\n         assertEquals(healthMonitor.getHttpMethod(), HttpMethod.HEAD);\n         assertEquals(healthMonitor.getUrlPath(), \"/index.html\");\n         assertEquals(healthMonitor.getExpectedCodes(), \"201\");\n         assertNotNull(healthMonitor.getPools());\n         assertTrue(healthMonitor.getPools().isEmpty());\n         assertEquals(healthMonitor.getAdminStateUp(), Boolean.FALSE);\n         assertEquals(healthMonitor.getStatus(), LBaaSStatus.ACTIVE);\n         assertNull(healthMonitor.getStatusDescription());\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testDeleteHealthMonitor() throws IOException, InterruptedException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/extension_list_with_lbaas_v1_response.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(204)));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         LBaaSApi lbaasApi = neutronApi.getLBaaSApi(\"RegionOne\").get();\n\n         boolean result = lbaasApi.deleteHealthMonitor(\"466c8345-28d8-4f84-a246-e04380b0461d\");\n\n         /*\n          * Check request\n          */\n         assertAuthentication(server);\n         server.takeRequest();\n         assertRequest(server.takeRequest(), \"DELETE\", uriApiVersion + \"/lb/health_monitors/466c8345-28d8-4f84-a246-e04380b0461d\");\n\n         /*\n          * Check response\n          */\n         assertTrue(result);\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testAssociateHealthMonitorWithPool() throws IOException, InterruptedException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/extension_list_with_lbaas_v1_response.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/lbaas/v1/pool_associate_health_monitor_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         LBaaSApi lbaasApi = neutronApi.getLBaaSApi(\"RegionOne\").get();\n\n         HealthMonitor healthMonitor = lbaasApi.associateHealthMonitor(\"72741b06-df4d-4715-b142-276b6bce75ab\", \"5d4b5228-33b0-4e60-b225-9b727c1a20e7\");\n\n         /*\n          * Check request\n          */\n         assertAuthentication(server);\n         server.takeRequest();\n         assertRequest(server.takeRequest(), \"POST\", uriApiVersion + \"/lb/pools/72741b06-df4d-4715-b142-276b6bce75ab/health_monitors\", \"/lbaas/v1/pool_associate_health_monitor_request.json\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(healthMonitor);\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testDisassociateHealthMonitorFromPool() throws IOException, InterruptedException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/extension_list_with_lbaas_v1_response.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(204)));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         LBaaSApi lbaasApi = neutronApi.getLBaaSApi(\"RegionOne\").get();\n\n         boolean result = lbaasApi.disassociateHealthMonitor(\"72741b06-df4d-4715-b142-276b6bce75ab\", \"5d4b5228-33b0-4e60-b225-9b727c1a20e7\");\n\n         /*\n          * Check request\n          */\n         assertAuthentication(server);\n         server.takeRequest();\n         assertRequest(server.takeRequest(), \"DELETE\", uriApiVersion + \"/lb/pools/72741b06-df4d-4715-b142-276b6bce75ab/health_monitors/5d4b5228-33b0-4e60-b225-9b727c1a20e7\");\n\n         /*\n          * Check response\n          */\n         assertTrue(result);\n      } finally {\n         server.shutdown();\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/java/org/jclouds/openstack/neutron/v2/features/ExtensionApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.Set;\n\nimport org.jclouds.openstack.neutron.v2.internal.BaseNeutronApiLiveTest;\nimport org.jclouds.openstack.v2_0.domain.Extension;\nimport org.jclouds.openstack.v2_0.features.ExtensionApi;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@link ExtensionApi}\n */\n@Test(groups = \"live\", testName = \"ExtensionApiLiveTest\")\npublic class ExtensionApiLiveTest extends BaseNeutronApiLiveTest {\n\n   /**\n    * Tests the listing of Neutron Extensions.\n    *\n    * @throws Exception\n    */\n   public void testListExtensions() throws Exception {\n      for (String regionId : api.getConfiguredRegions()) {\n         ExtensionApi extensionApi = api.getExtensionApi(regionId);\n         Set<Extension> response = extensionApi.list();\n         assertNotNull(response);\n         assertFalse(response.isEmpty());\n\n         for (Extension extension : response) {\n            assertNotNull(extension.getId());\n            assertNotNull(extension.getName());\n            assertNotNull(extension.getDescription());\n            assertNotNull(extension.getLinks());\n            // Namespace and updated fields are nullable\n         }\n      }\n   }\n\n   /**\n    * Tests retrieval of Neutron Extensions by their alias.\n    *\n    * @throws Exception\n    */\n   public void testGetExtensionByAlias() throws Exception {\n      for (String regionId : api.getConfiguredRegions()) {\n         ExtensionApi extensionApi = api.getExtensionApi(regionId);\n         Set<Extension> response = extensionApi.list();\n         assertNotNull(response);\n\n         for (Extension extension : response) {\n            Extension details = extensionApi.get(extension.getId());\n            assertNotNull(details);\n            assertEquals(details.getId(), extension.getId());\n            assertEquals(details.getName(), extension.getName());\n            assertEquals(details.getDescription(), extension.getDescription());\n            assertEquals(details.getNamespace(), extension.getNamespace());\n            assertEquals(details.getUpdated(), extension.getUpdated());\n            assertEquals(details.getLinks(), extension.getLinks());\n         }\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/java/org/jclouds/openstack/neutron/v2/features/ExtensionApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.Set;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\n\nimport org.jclouds.openstack.neutron.v2.NeutronApi;\nimport org.jclouds.openstack.neutron.v2.internal.BaseNeutronApiMockTest;\nimport org.jclouds.openstack.v2_0.domain.Extension;\nimport org.jclouds.openstack.v2_0.features.ExtensionApi;\nimport org.testng.annotations.Test;\n\n\n/**\n * Tests annotation parsing of {@code ExtensionApi}\n */\n@Test(groups = \"unit\", testName = \"ExtensionApiMockTest\")\npublic class ExtensionApiMockTest extends BaseNeutronApiMockTest {\n\n   public void testListExtensions() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse()\n         .setResponseCode(200).setBody(stringFromResource(\"/extension_list.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         ExtensionApi api = neutronApi.getExtensionApi(\"RegionOne\");\n\n         Set<Extension> extensions = api.list();\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertExtensions(server, uriApiVersion + \"\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(extensions);\n         assertEquals(extensions.size(), 15);\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGetExtensionByAlias() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse()\n         .setResponseCode(200).setBody(stringFromResource(\"/extension_details.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n\n         Extension routerExtension = neutronApi.getExtensionApi(\"RegionOne\").get(\"router\");\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/extensions/router\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(routerExtension);\n         assertEquals(routerExtension.getName(), \"Neutron L3 Router\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/java/org/jclouds/openstack/neutron/v2/features/FloatingIPApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.openstack.neutron.v2.features;\n\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\n\nimport com.google.common.base.Predicate;\nimport org.jclouds.openstack.neutron.v2.domain.FloatingIP;\nimport org.jclouds.openstack.neutron.v2.domain.IP;\nimport org.jclouds.openstack.neutron.v2.domain.Network;\nimport org.jclouds.openstack.neutron.v2.internal.BaseNeutronApiLiveTest;\nimport org.testng.Assert;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests parsing and Guice wiring of FloatingIPApi\n */\n@Test(groups = \"live\", testName = \"FloatingIPApiLiveTest\")\npublic class FloatingIPApiLiveTest extends BaseNeutronApiLiveTest {\n\n   public void testCreateUpdateAndDeleteFloatingIP() {\n      for (String region : api.getConfiguredRegions()) {\n\n         FloatingIPApi floatingIPApi = api.getFloatingIPApi(region);\n         NetworkApi networkApi = api.getNetworkApi(region);\n\n         FloatingIP floatingIPGet = null;\n         Network network;\n\n         try {\n            network = networkApi.list().concat().firstMatch(new Predicate<Network>() {\n               @Override\n               public boolean apply(Network input) {\n                  return input.getExternal();\n               }\n            }).orNull();\n\n            if (network == null) Assert.fail(\"Cannot find a suitable external network. Please add it manually or contact your administrator\");\n\n            FloatingIP floatingIP = floatingIPApi.create(FloatingIP.createBuilder(network.getId()).availabilityZone(network.getAvailabilityZone()).build());\n            /* List and Get test */\n            Set<FloatingIP> floatingIPs = floatingIPApi.list().concat().toSet();\n            floatingIPGet = floatingIPApi.get(floatingIP.getId());\n\n            assertNotNull(floatingIPGet);\n            assertTrue(floatingIPs.contains(floatingIP));\n         }\n         finally {\n            assertTrue(floatingIPApi.delete(floatingIPGet.getId()));\n         }\n      }\n   }\n\n   public Set<IP> getFixedAddresses(String subnetId) {\n      return ImmutableSet.of(IP.builder().subnetId(subnetId).build());\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/java/org/jclouds/openstack/neutron/v2/features/FloatingIPApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.net.URISyntaxException;\nimport java.util.List;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\n\nimport org.jclouds.openstack.neutron.v2.NeutronApi;\nimport org.jclouds.openstack.neutron.v2.domain.FloatingIP;\nimport org.jclouds.openstack.neutron.v2.domain.FloatingIPs;\nimport org.jclouds.openstack.neutron.v2.internal.BaseNeutronApiMockTest;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\nimport org.testng.annotations.Test;\n\n\n/**\n * Tests Floating Api Guice wiring and parsing\n *\n */\n@Test\npublic class FloatingIPApiMockTest extends BaseNeutronApiMockTest {\n\n   public void testCreateFloatingIP() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(\n            new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/floatingip_create_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         FloatingIPApi api = neutronApi.getFloatingIPApi(\"RegionOne\");\n\n         FloatingIP.CreateFloatingIP createFip = FloatingIP.createBuilder(\"376da547-b977-4cfe-9cba-275c80debf57\")\n               .portId(\"ce705c24-c1ef-408a-bda3-7bbd946164ab\")\n               .build();\n\n         FloatingIP floatingIP = api.create(createFip);\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"POST\", uriApiVersion + \"/floatingips\", \"/floatingip_create_request.json\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(floatingIP);\n         assertEquals(floatingIP.getRouterId(), \"d23abc8d-2991-4a55-ba98-2aaea84cc72f\");\n         assertEquals(floatingIP.getTenantId(), \"4969c491a3c74ee4af974e6d800c62de\");\n         assertEquals(floatingIP.getFloatingNetworkId(), \"376da547-b977-4cfe-9cba-275c80debf57\");\n         assertEquals(floatingIP.getFixedIpAddress(), \"10.0.0.3\");\n         assertEquals(floatingIP.getFloatingIpAddress(), \"172.24.4.228\");\n         assertEquals(floatingIP.getPortId(), \"ce705c24-c1ef-408a-bda3-7bbd946164ab\");\n         assertEquals(floatingIP.getId(), \"2f245a7b-796b-4f26-9cf9-9e82d248fda7\");\n\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testListSpecificPageFloatingIP() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/floatingip_list_response_paged1.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         FloatingIPApi api = neutronApi.getFloatingIPApi(\"RegionOne\");\n\n         FloatingIPs floatingIPs = api.list(PaginationOptions.Builder.limit(2).marker(\"abcdefg\"));\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/floatingips?limit=2&marker=abcdefg\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(floatingIPs);\n         assertEquals(floatingIPs.size(), 2);\n         assertEquals(floatingIPs.first().get().getId(), \"2f245a7b-796b-4f26-9cf9-9e82d248fda7\");\n         assertEquals(floatingIPs.get(1).getId(), \"61cea855-49cb-4846-997d-801b70c71bdd\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testListPagedFloatingIP() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/floatingip_list_response_paged1.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/floatingip_list_response_paged2.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         FloatingIPApi api = neutronApi.getFloatingIPApi(\"RegionOne\");\n\n         // Note: Lazy! Have to actually look at the collection.\n         List<FloatingIP> floatingIPs = api.list().concat().toList();\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/floatingips\");\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/floatingips?marker=71c1e68c-171a-4aa2-aca5-50ea153a3718\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(floatingIPs);\n         assertEquals(floatingIPs.size(), 4);\n         assertEquals(floatingIPs.get(0).getId(), \"2f245a7b-796b-4f26-9cf9-9e82d248fda7\");\n         assertEquals(floatingIPs.get(3).getId(), \"61cea855-49cb-4846-997d-801b70c71bdd2\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGetFloatingIP() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(\n            new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/floatingip_get_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         FloatingIPApi api = neutronApi.getFloatingIPApi(\"RegionOne\");\n\n         FloatingIP floatingIP = api.get(\"12345\");\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/floatingips/12345\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(floatingIP);\n         assertEquals(floatingIP.getId(), \"2f245a7b-796b-4f26-9cf9-9e82d248fda7\");\n         assertEquals(floatingIP.getPortId(), \"ce705c24-c1ef-408a-bda3-7bbd946164ab\");\n         assertEquals(floatingIP.getFloatingIpAddress(), \"172.24.4.228\");\n         assertEquals(floatingIP.getFixedIpAddress(), \"10.0.0.3\");\n         assertEquals(floatingIP.getFloatingNetworkId(), \"376da547-b977-4cfe-9cba-275c80debf57\");\n         assertEquals(floatingIP.getRouterId(), \"d23abc8d-2991-4a55-ba98-2aaea84cc72f\");\n         assertEquals(floatingIP.getTenantId(), \"4969c491a3c74ee4af974e6d800c62de\");\n\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testUpdateFloatingIP() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(\n            new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/floatingip_update_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         FloatingIPApi api = neutronApi.getFloatingIPApi(\"RegionOne\");\n\n         FloatingIP.UpdateFloatingIP updateFloatingIP = FloatingIP.updateBuilder()\n               .portId(\"fc861431-0e6c-4842-a0ed-e2363f9bc3a8\")\n               .build();\n\n         FloatingIP floatingIP = api.update(\"12345\", updateFloatingIP);\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"PUT\", uriApiVersion + \"/floatingips/12345\", \"/floatingip_update_request.json\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(floatingIP);\n         assertEquals(floatingIP.getPortId(), \"fc861431-0e6c-4842-a0ed-e2363f9bc3a8\");\n\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testUpdateFloatingIPDissociate() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(\n            new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/floatingip_update_dissociate_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         FloatingIPApi api = neutronApi.getFloatingIPApi(\"RegionOne\");\n\n         FloatingIP.UpdateFloatingIP updateFloatingIP = FloatingIP.updateBuilder().build();\n\n         FloatingIP floatingIP = api.update(\"12345\", updateFloatingIP);\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"PUT\", uriApiVersion + \"/floatingips/12345\", \"/floatingip_update_dissociate_request.json\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(floatingIP);\n         assertNull(floatingIP.getPortId());\n\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testDeleteFloatingIP() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(\n            new MockResponse().setResponseCode(201)));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         FloatingIPApi api = neutronApi.getFloatingIPApi(\"RegionOne\");\n\n         boolean result = api.delete(\"12345\");\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"DELETE\", uriApiVersion + \"/floatingips/12345\");\n\n         /*\n          * Check response\n          */\n         assertTrue(result);\n      } finally {\n         server.shutdown();\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/java/org/jclouds/openstack/neutron/v2/features/NetworkApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.features;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Sets;\nimport org.jclouds.openstack.neutron.v2.domain.Network;\nimport org.jclouds.openstack.neutron.v2.domain.NetworkType;\nimport org.jclouds.openstack.neutron.v2.internal.BaseNeutronApiLiveTest;\nimport org.jclouds.openstack.neutron.v2.util.PredicateUtil;\nimport org.testng.annotations.Test;\n\nimport java.util.Set;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\n/**\n * Tests parsing and Guice wiring of NetworkApi\n */\n@Test(groups = \"live\", testName = \"NetworkApiLiveTest\")\npublic class NetworkApiLiveTest extends BaseNeutronApiLiveTest {\n\n   public void testCreateUpdateAndDeleteNetwork() {\n      for (String region : api.getConfiguredRegions()) {\n         NetworkApi networkApi = api.getNetworkApi(region);\n         Network net = networkApi.create(Network.createBuilder(\"jclouds-test\").networkType(NetworkType.LOCAL).build());\n         Network test = networkApi.create(Network.createBuilder(\"jclouds-test\").build());\n         assertNotNull(net);\n\n         /* List and get tests */\n         Network networkList = api.getNetworkApi(region).list().concat().toSet().iterator().next();\n         assertNotNull(networkList);\n         Network networkGet = api.getNetworkApi(region).get(networkList.getId());\n         assertEquals(networkList, networkGet);\n         /****/\n\n         Network network = networkApi.get(net.getId());\n\n         assertEquals(network.getId(), net.getId());\n         assertEquals(network.getName(), \"jclouds-test\");\n         assertEquals(network.getNetworkType(), NetworkType.LOCAL);\n         assertTrue(network.getSubnets().isEmpty());\n         assertNotNull(networkApi.update(net.getId(), Network.updateBuilder().name(\"jclouds-live-test\").build()));\n\n         network = networkApi.get(net.getId());\n\n         assertEquals(network.getId(), net.getId());\n         assertEquals(network.getName(), \"jclouds-live-test\");\n         assertTrue(network.getSubnets().isEmpty());\n\n         Network net2 = networkApi.create(Network.createBuilder(\"jclouds-test2\").networkType(NetworkType.LOCAL).build());\n         assertNotNull(net2);\n\n         assertTrue(networkApi.delete(net.getId()));\n         assertTrue(networkApi.delete(net2.getId()));\n         assertTrue(networkApi.delete(test.getId()));\n      }\n   }\n\n   public void testBulkCreateNetwork() {\n      for (String region : api.getConfiguredRegions()) {\n         NetworkApi networkApi = api.getNetworkApi(region);\n         Set<Network> nets = networkApi.createBulk(\n               ImmutableList.of(\n                  Network.createBuilder(\"jclouds-live-test-1\").networkType(NetworkType.LOCAL).adminStateUp(true).build(),\n                  Network.createBuilder(\"jclouds-live-test-2\").networkType(NetworkType.LOCAL).adminStateUp(false).build(),\n                  Network.createBuilder(\"jclouds-live-test-3\").networkType(NetworkType.LOCAL).adminStateUp(false).build()\n               )\n         ).toSet();\n         Set<Network> existingNets = networkApi.list().concat().toSet();\n\n         assertNotNull(nets);\n         assertTrue(!nets.isEmpty());\n         assertEquals(nets.size(), 3);\n\n         for (Network net : nets) {\n            Predicate<Network> idEqualsPredicate = PredicateUtil.createIdEqualsPredicate(net.getId());\n            assertEquals(1, Sets.filter(existingNets, idEqualsPredicate).size());\n            assertTrue(networkApi.delete(net.getId()));\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/java/org/jclouds/openstack/neutron/v2/features/NetworkApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.features;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableList;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\n\nimport org.jclouds.openstack.neutron.v2.NeutronApi;\nimport org.jclouds.openstack.neutron.v2.domain.Network;\nimport org.jclouds.openstack.neutron.v2.domain.NetworkStatus;\nimport org.jclouds.openstack.neutron.v2.domain.NetworkType;\nimport org.jclouds.openstack.neutron.v2.domain.Networks;\nimport org.jclouds.openstack.neutron.v2.internal.BaseNeutronApiMockTest;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\nimport org.testng.annotations.Test;\n\nimport java.io.IOException;\nimport java.net.URISyntaxException;\nimport java.util.List;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\n/**\n * Tests NetworkApi Guice wiring and parsing\n *\n */\n@Test\npublic class NetworkApiMockTest extends BaseNeutronApiMockTest {\n\n   public void testCreateNetwork() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/network_create_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         NetworkApi api = neutronApi.getNetworkApi(\"RegionOne\");\n\n         Network.CreateNetwork createNetwork = Network.createBuilder(\"jclouds-wibble\")\n               .networkType(NetworkType.LOCAL)\n               .build();\n\n         Network network = api.create(createNetwork);\n\n         /*\n          * Check request\n          */\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"POST\", uriApiVersion + \"/networks\", \"/network_create_request.json\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(network);\n         assertEquals(network.getName(), \"jclouds-wibble\");\n         assertEquals(network.getNetworkType(), NetworkType.LOCAL);\n         assertEquals(network.getTenantId(), \"1234567890\");\n         assertEquals(network.getStatus(), NetworkStatus.ACTIVE);\n         assertEquals(network.getId(), \"624312ff-d14b-4ba3-9834-1c78d23d574d\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testListSpecificPageNetwork() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/network_list_response_paged1.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         NetworkApi api = neutronApi.getNetworkApi(\"RegionOne\");\n\n         Networks networks = api.list(PaginationOptions.Builder.limit(2).marker(\"abcdefg\"));\n\n         /*\n          * Check request\n          */\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/networks?limit=2&marker=abcdefg\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(networks);\n         assertEquals(networks.first().get().getId(), \"396f12f8-521e-4b91-8e21-2e003500433a\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   // These fail tests uncover issues with the fallback annotations.\n   public void testListSpecificPageNetworkFail() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(404).setBody(stringFromResource(\"/network_list_response_paged1.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         NetworkApi api = neutronApi.getNetworkApi(\"RegionOne\");\n\n         Networks networks = api.list(PaginationOptions.Builder.limit(2).marker(\"abcdefg\"));\n\n         /*\n          * Check request\n          */\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/networks?limit=2&marker=abcdefg\");\n\n         /*\n          * Check response\n          */\n         assertTrue(networks.isEmpty());\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testListPagedNetwork() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/network_list_response_paged1.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/network_list_response_paged2.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         NetworkApi api = neutronApi.getNetworkApi(\"RegionOne\");\n\n         // Note: Lazy! Have to actually look at the collection.\n         List<Network> networks = api.list().concat().toList();\n         assertEquals(networks.size(), 4);\n         // look at last element\n         assertEquals(networks.get(3).getId(), \"71c1e68c-171a-4aa2-aca5-50ea153a3718_2\");\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/networks\");\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/networks?marker=71c1e68c-171a-4aa2-aca5-50ea153a3718\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(networks);\n         assertEquals(networks.get(0).getId(), \"396f12f8-521e-4b91-8e21-2e003500433a\");\n         assertEquals(networks.get(3).getId(), \"71c1e68c-171a-4aa2-aca5-50ea153a3718_2\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGetNetwork() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/network_get_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         NetworkApi api = neutronApi.getNetworkApi(\"RegionOne\");\n\n         Network network = api.get(\"12345\");\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/networks/12345\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(network);\n         assertEquals(network.getName(), \"jclouds-wibble\");\n         assertEquals(network.getId(), \"624312ff-d14b-4ba3-9834-1c78d23d574d\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testCreateNetworkBulk() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/network_bulk_create_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         NetworkApi api = neutronApi.getNetworkApi(\"RegionOne\");\n\n         Network.CreateNetwork createNetwork1 = Network.createBuilder(\"jclouds-wibble\")\n               .networkType(NetworkType.LOCAL)\n               .build();\n\n         Network.CreateNetwork createNetwork2 = Network.createBuilder(\"jclouds-wibble2\")\n               .networkType(NetworkType.LOCAL)\n               .build();\n\n         FluentIterable<Network> networks = api.createBulk(ImmutableList.of(createNetwork1, createNetwork2));\n\n         /*\n          * Check request\n          */\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"POST\", uriApiVersion + \"/networks\", \"/network_bulk_create_request.json\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(networks);\n         assertEquals(networks.size(), 2);\n         assertEquals(networks.get(0).getName(), \"jclouds-wibble\");\n         assertEquals(networks.get(0).getNetworkType(), NetworkType.LOCAL);\n         assertEquals(networks.get(0).getTenantId(), \"1234567890\");\n         assertEquals(networks.get(0).getStatus(), NetworkStatus.ACTIVE);\n         assertEquals(networks.get(0).getId(), \"624312ff-d14b-4ba3-9834-1c78d23d574d\");\n\n         assertEquals(networks.get(1).getName(), \"jclouds-wibble2\");\n         assertEquals(networks.get(1).getNetworkType(), NetworkType.LOCAL);\n         assertEquals(networks.get(1).getTenantId(), \"1234567890\");\n         assertEquals(networks.get(1).getStatus(), NetworkStatus.ACTIVE);\n         assertEquals(networks.get(1).getId(), \"624312ff-d14b-4ba3-9834-1c78d23d574e\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testUpdateNetwork() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/network_update_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         NetworkApi api = neutronApi.getNetworkApi(\"RegionOne\");\n\n         Network.UpdateNetwork updateNetwork = Network.updateBuilder()\n               .name(\"jclouds-wibble-updated\")\n               .networkType(NetworkType.LOCAL)\n               .build();\n\n         Network network = api.update(\"123456\", updateNetwork);\n\n         /*\n          * Check request\n          */\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"PUT\", uriApiVersion + \"/networks/123456\", \"/network_update_request.json\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(network);\n         assertEquals(network.getName(), \"updated_name\");\n         assertEquals(network.getId(), \"fc68ea2c-b60b-4b4f-bd82-94ec81110766\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testDeleteNetwork() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(201)));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         NetworkApi api = neutronApi.getNetworkApi(\"RegionOne\");\n\n         boolean result = api.delete(\"123456\");\n\n         /*\n          * Check request\n          */\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"DELETE\", uriApiVersion + \"/networks/123456\");\n\n         /*\n          * Check response\n          */\n         assertTrue(result);\n      } finally {\n         server.shutdown();\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/java/org/jclouds/openstack/neutron/v2/features/PortApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.features;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Sets;\nimport org.jclouds.openstack.neutron.v2.domain.IP;\nimport org.jclouds.openstack.neutron.v2.domain.Network;\nimport org.jclouds.openstack.neutron.v2.domain.NetworkType;\nimport org.jclouds.openstack.neutron.v2.domain.Port;\nimport org.jclouds.openstack.neutron.v2.domain.Subnet;\nimport org.jclouds.openstack.neutron.v2.internal.BaseNeutronApiLiveTest;\nimport org.jclouds.openstack.neutron.v2.util.PredicateUtil;\nimport org.testng.annotations.Test;\n\nimport java.util.Set;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\n/**\n * Tests PortApi in combination with the Network & SubnetApi\n */\n@Test(groups = \"live\", testName = \"PortApiLiveTest\")\npublic class PortApiLiveTest extends BaseNeutronApiLiveTest {\n\n   public void testCreateUpdateAndDeletePort() {\n      for (String region : api.getConfiguredRegions()) {\n         NetworkApi networkApi = api.getNetworkApi(region);\n         SubnetApi subnetApi = api.getSubnetApi(region);\n         PortApi portApi = api.getPortApi(region);\n         String networkId = networkApi.create(\n               Network.createBuilder(\"JClouds-Live-Network\").networkType(NetworkType.LOCAL).build()).getId();\n         String ipv4SubnetId = subnetApi.create(Subnet.createBuilder(networkId, \"198.51.100.0/24\").ipVersion(4)\n               .name(\"JClouds-Live-IPv4-Subnet\").build()).getId();\n         String ipv6SubnetId = subnetApi.create(Subnet.createBuilder(networkId, \"a1ca:1e1:c:107d::/96\").ipVersion(6)\n               .name(\"JClouds-Live-IPv6-Subnet\").build()).getId();\n\n         assertNotNull(networkId);\n         assertNotNull(ipv4SubnetId);\n         assertNotNull(ipv6SubnetId);\n\n         String ipv4PortId = portApi.create(Port.createBuilder(networkId).name(\"JClouds-Live-IPv4-Port\")\n               .fixedIps(ImmutableSet.copyOf(getFixedAddresses(ipv4SubnetId))).build()).getId();\n         String ipv6PortId = portApi.create(Port.createBuilder(networkId).name(\"JClouds-Live-IPv6-Port\")\n               .fixedIps(ImmutableSet.copyOf(getFixedAddresses(ipv6SubnetId))).build()).getId();\n\n         /* List and get test */\n         Port portList = api.getPortApi(region).list().concat().toSet().iterator().next();\n         assertNotNull(portList);\n         Port portGet = api.getPortApi(region).get(portList.getId());\n         assertEquals(portList, portGet);\n         /****/\n\n         assertNotNull(ipv4PortId);\n         assertNotNull(ipv6PortId);\n\n         Port ipv4Port = portApi.get(ipv4PortId);\n         assertNotNull(ipv4Port);\n         assertEquals(ipv4Port.getId(), ipv4PortId);\n         assertEquals(ipv4Port.getName(), \"JClouds-Live-IPv4-Port\");\n\n         Port ipv6Port = portApi.get(ipv6PortId);\n         assertNotNull(ipv6Port);\n         assertEquals(ipv6Port.getId(), ipv6PortId);\n         assertEquals(ipv6Port.getName(), \"JClouds-Live-IPv6-Port\");\n\n         assertNotNull(portApi.update(ipv4PortId, Port.updateBuilder().name(\"Updated\").build()));\n         Port updatedIpv4Port = portApi.get(ipv4PortId);\n         assertEquals(updatedIpv4Port.getName(), \"Updated\");\n\n         assertTrue(portApi.delete(ipv4PortId));\n         assertTrue(portApi.delete(ipv6PortId));\n         assertTrue(subnetApi.delete(ipv4SubnetId));\n         assertTrue(subnetApi.delete(ipv6SubnetId));\n         assertTrue(networkApi.delete(networkId));\n      }\n   }\n\n   public void testBulkCreatePort() {\n      for (String region : api.getConfiguredRegions()) {\n         NetworkApi networkApi = api.getNetworkApi(region);\n         SubnetApi subnetApi = api.getSubnetApi(region);\n         PortApi portApi = api.getPortApi(region);\n\n         String networkId = networkApi.create(\n               Network.createBuilder(\"JClouds-Live-Network\").networkType(NetworkType.LOCAL).build()).getId();\n         String ipv4SubnetId = subnetApi.create(Subnet.createBuilder(networkId, \"198.51.100.0/24\").ipVersion(4)\n               .name(\"JClouds-Live-IPv4-Subnet\").build()).getId();\n         String ipv6SubnetId = subnetApi.create(Subnet.createBuilder(networkId, \"a1ca:1e1:c:107d::/96\").ipVersion(6)\n               .name(\"JClouds-Live-IPv6-Subnet\").build()).getId();\n\n         assertNotNull(networkId);\n         assertNotNull(ipv4SubnetId);\n         assertNotNull(ipv6SubnetId);\n\n         Set<? extends Port> ports = portApi.createBulk(\n               ImmutableList.of(\n                     Port.createBuilder(networkId).name(\"JClouds-Live-IPv4-Subnet-1\")\n                           .fixedIps(ImmutableSet.copyOf(getFixedAddresses(ipv4SubnetId))).build(),\n                     Port.createBuilder(networkId).name(\"JClouds-Live-IPv4-Subnet-2\")\n                           .fixedIps(ImmutableSet.copyOf(getFixedAddresses(ipv4SubnetId))).build(),\n                     Port.createBuilder(networkId).name(\"JClouds-Live-IPv6-Subnet-1\")\n                           .fixedIps(ImmutableSet.copyOf(getFixedAddresses(ipv6SubnetId))).build(),\n                     Port.createBuilder(networkId).name(\"JClouds-Live-IPv6-Subnet-2\")\n                           .fixedIps(ImmutableSet.copyOf(getFixedAddresses(ipv6SubnetId))).build()\n               )\n         ).toSet();\n         Set<? extends Port> existingPorts = portApi.list().concat().toSet();\n\n         assertNotNull(ports);\n         assertFalse(ports.isEmpty());\n         assertEquals(ports.size(), 4);\n\n         for (Port port : ports) {\n            Predicate<Port> idEqualsPredicate = PredicateUtil.createIdEqualsPredicate(port.getId());\n            assertEquals(1, Sets.filter(existingPorts, idEqualsPredicate).size());\n            assertTrue(portApi.delete(port.getId()));\n         }\n         assertTrue(subnetApi.delete(ipv4SubnetId));\n         assertTrue(subnetApi.delete(ipv6SubnetId));\n         assertTrue(networkApi.delete(networkId));\n      }\n   }\n\n   public Set<IP> getFixedAddresses(String subnetId) {\n      return ImmutableSet.of(\n         IP.builder().subnetId(subnetId).build()\n      );\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/java/org/jclouds/openstack/neutron/v2/features/PortApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.net.URISyntaxException;\nimport java.util.List;\nimport java.util.Map;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\n\nimport org.jclouds.openstack.neutron.v2.NeutronApi;\nimport org.jclouds.openstack.neutron.v2.domain.AddressPair;\nimport org.jclouds.openstack.neutron.v2.domain.NetworkStatus;\nimport org.jclouds.openstack.neutron.v2.domain.Port;\nimport org.jclouds.openstack.neutron.v2.domain.Ports;\nimport org.jclouds.openstack.neutron.v2.domain.VIFType;\nimport org.jclouds.openstack.neutron.v2.domain.VNICType;\nimport org.jclouds.openstack.neutron.v2.internal.BaseNeutronApiMockTest;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\n\n\n/**\n * Tests NetworkApi Guice wiring and parsing\n *\n */\n@Test\npublic class PortApiMockTest extends BaseNeutronApiMockTest {\n\n   public void testCreatePort() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(\n            new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/port_create_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         PortApi api = neutronApi.getPortApi(\"RegionOne\");\n\n         Port.CreatePort createPort = Port.createBuilder(\"6aeaf34a-c482-4bd3-9dc3-7faf36412f12\")\n               .name(\"port1\")\n               .adminStateUp(Boolean.TRUE)\n               .deviceId(\"d6b4d3a5-c700-476f-b609-1493dd9dadc0\")\n               .allowedAddressPairs(ImmutableSet.of(AddressPair.builder(\"12\", \"111.222.333.444\").build()))\n               .build();\n\n         Port port = api.create(createPort);\n\n         /*\n          * Check request\n          */\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"POST\", uriApiVersion + \"/ports\", \"/port_create_request.json\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(port);\n         assertEquals(port.getAllowedAddressPairs().iterator().next().getIpAddress(), \"192.168.1.1\");\n         assertEquals(port.getAllowedAddressPairs().iterator().next().getMacAddress(), \"12:12\");\n         assertEquals(port.getName(), \"port1\");\n         assertEquals(port.getStatus(), NetworkStatus.ACTIVE);\n         assertEquals(port.getId(), \"ebe69f1e-bc26-4db5-bed0-c0afb4afe3db\");\n         assertEquals(port.getDeviceId(), \"d6b4d3a5-c700-476f-b609-1493dd9dadc0\");\n         assertEquals(port.getDeviceOwner(), \"\");\n         assertEquals(port.getMacAddress(), \"fa:16:3e:a6:50:c1\");\n         assertEquals(port.getNetworkId(), \"6aeaf34a-c482-4bd3-9dc3-7faf36412f12\");\n         assertEquals(port.getFixedIps().iterator().next().getIpAddress(), \"192.168.111.4\");\n         assertEquals(port.getFixedIps().iterator().next().getSubnetId(), \"22b44fc2-4ffb-4de4-b0f9-69d58b37ae27\");\n         assertEquals(port.getTenantId(), \"cf1a5775e766426cb1968766d0191908\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testListSpecificPagePort() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/port_list_response_paged1.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         PortApi api = neutronApi.getPortApi(\"RegionOne\");\n\n         Ports ports = api.list(PaginationOptions.Builder.limit(2).marker(\"abcdefg\"));\n\n         /*\n          * Check request\n          */\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/ports?limit=2&marker=abcdefg\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(ports);\n         assertEquals(ports.size(), 2);\n         assertEquals(ports.first().get().getId(), \"24e6637e-c521-45fc-8b8b-d7331aa3c99f\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testListPagedPort() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/port_list_response_paged1.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/port_list_response_paged2.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         PortApi api = neutronApi.getPortApi(\"RegionOne\");\n\n         // Note: Lazy! Have to actually look at the collection.\n         List<Port> ports = api.list().concat().toList();\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/ports\");\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/ports?marker=71c1e68c-171a-4aa2-aca5-50ea153a3718\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(ports);\n         assertEquals(ports.size(), 4);\n         assertEquals(ports.get(0).getId(), \"24e6637e-c521-45fc-8b8b-d7331aa3c99f\");\n         assertEquals(ports.get(3).getId(), \"e54dfd9b-ce6e-47f7-af47-1609cfd1cdb0_4\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testCreateBulkPort() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(\n            new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/port_create_bulk_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         PortApi api = neutronApi.getPortApi(\"RegionOne\");\n\n         Port.CreatePort createPort1 = Port.createBuilder(\"64239a54-dcc4-4b39-920b-b37c2144effa\")\n               .name(\"port1\")\n               .adminStateUp(Boolean.TRUE)\n               .deviceId(\"24df1d04-d5cb-41e1-8de5-61ed77c558df\")\n               .securityGroups(ImmutableSet.of(\"dbc107f4-afcd-4d5a-9352-f68f82241d5b\"))\n               .build();\n\n         Port.CreatePort createPort2 = Port.createBuilder(\"e6031bc2-901a-4c66-82da-f4c32ed89406\")\n               .name(\"port2\")\n               .adminStateUp(Boolean.FALSE)\n               .securityGroups(\n                     ImmutableSet.of(\"8bf3f7cc-8471-40b1-815f-9da47e79775b\", \"dbc107f4-afcd-4d5a-9352-f68f82241d5b\"))\n               .build();\n\n         FluentIterable<Port> ports = api.createBulk(ImmutableList.of(createPort1, createPort2));\n\n         /*\n          * Check request\n          */\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"POST\", uriApiVersion + \"/ports\", \"/port_create_bulk_request.json\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(ports);\n         assertEquals(ports.size(), 2);\n         assertEquals(ports.get(0).getName(), \"port1\");\n         assertEquals(ports.get(1).getName(), \"port2\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGetPort() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(\n            new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/port_get_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         PortApi api = neutronApi.getPortApi(\"RegionOne\");\n\n         Port port = api.get(\"12345\");\n\n         /*\n          * Check request\n          */\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/ports/12345\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(port);\n         assertEquals(port.getName(), \"jclouds-wibble\");\n         assertEquals(port.getStatus(), NetworkStatus.ACTIVE);\n         assertEquals(port.getId(), \"624312ff-d14b-4ba3-9834-1c78d23d574d\");\n         assertEquals(port.getTenantId(), \"1234567890\");\n         assertEquals(port.getNetworkId(), \"1234567890\");\n         assertEquals(port.getVnicType(), VNICType.NORMAL);\n         assertEquals(port.getVifType(), VIFType.HYPERV);\n         assertEquals(port.getVifDetails().get(\"name1\"), \"value1\");\n         assertEquals(((Map<String, Double>)port.getVifDetails().get(\"name2\")).get(\"mapname2\").intValue(), 3);\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testUpdatePort() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(\n            new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/port_update_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         PortApi api = neutronApi.getPortApi(\"RegionOne\");\n\n         Port.UpdatePort updatePort = Port.updateBuilder()\n               .securityGroups(\n                     ImmutableSet.of(\"85cc3048-abc3-43cc-89b3-377341426ac5\", \"c5ab5c29-2c99-44cb-a4b8-e70a88b77799\"))\n               .build();\n\n         Port port = api.update(\"12345\", updatePort);\n\n         /*\n          * Check request\n          */\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"PUT\", uriApiVersion + \"/ports/12345\", \"/port_update_request.json\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(port);\n         assertEquals(port.getId(), \"1d8591f4-7b62-428e-857d-e82a15e5a7f1\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testDeletePort() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(201)));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         PortApi api = neutronApi.getPortApi(\"RegionOne\");\n\n         boolean result = api.delete(\"12345\");\n\n         /*\n          * Check request\n          */\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"DELETE\", uriApiVersion + \"/ports/12345\");\n\n         /*\n          * Check response\n          */\n         assertTrue(result);\n      } finally {\n         server.shutdown();\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/java/org/jclouds/openstack/neutron/v2/features/SecurityGroupApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.openstack.neutron.v2.features;\n\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.size;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.openstack.neutron.v2.domain.Rule;\nimport org.jclouds.openstack.neutron.v2.domain.RuleDirection;\nimport org.jclouds.openstack.neutron.v2.domain.RuleEthertype;\nimport org.jclouds.openstack.neutron.v2.domain.RuleProtocol;\nimport org.jclouds.openstack.neutron.v2.domain.SecurityGroup;\nimport org.jclouds.openstack.neutron.v2.internal.BaseNeutronApiLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\n\n/**\n * Tests parsing and Guice wiring of RouterApi\n */\n@Test(groups = \"live\", testName = \"SecurityGroupApiLiveTest\")\npublic class SecurityGroupApiLiveTest extends BaseNeutronApiLiveTest {\n\n   /**\n    * Smoke test for the Security Group extension for Neutron\n    */\n   public void testCreateUpdateAndDeleteSecurityGroup() {\n      for (String region : api.getConfiguredRegions()) {\n         SecurityGroupApi sgApi = null;\n         Rule rule = null;\n         SecurityGroup securityGroup = null;\n\n         try {\n            sgApi = api.getSecurityGroupApi(region);\n\n            securityGroup = sgApi.create(\n                  SecurityGroup.createBuilder().name(\"jclouds-test\").description(\"jclouds test security group\")\n                        .build());\n            assertNotNull(securityGroup);\n\n            rule = sgApi.create(\n                  Rule.createBuilder(RuleDirection.INGRESS, securityGroup.getId())\n                        .ethertype(RuleEthertype.IPV6)\n                        .portRangeMax(90)\n                        .portRangeMin(80)\n                        .protocol(RuleProtocol.TCP)\n                        .build());\n\n            assertNotNull(rule);\n\n            // Refresh\n            securityGroup = sgApi.getSecurityGroup(securityGroup.getId());\n\n            assertEquals(securityGroup.getName(), \"jclouds-test\");\n            assertEquals(securityGroup.getDescription(), \"jclouds test security group\");\n            assertEquals(size(filter(securityGroup.getRules(), new Predicate<Rule>() {\n               @Override\n               public boolean apply(Rule input) {\n                  return RuleDirection.INGRESS.equals(input.getDirection());\n               }\n            })), 1);\n\n            Rule newSecGroupRule = null;\n\n            for (Rule sgr : securityGroup.getRules()) {\n               if (sgr.getId().equals(rule.getId())) {\n                  newSecGroupRule = sgr;\n                  break;\n               }\n            }\n            assertNotNull(newSecGroupRule, \"Did not find the new rule in the group.\");\n\n            assertEquals(rule, newSecGroupRule);\n\n            assertEquals(rule.getEthertype(), RuleEthertype.IPV6);\n            assertEquals(rule.getProtocol(), RuleProtocol.TCP);\n            assertEquals(rule.getPortRangeMax().intValue(), 90);\n            assertEquals(rule.getPortRangeMin().intValue(), 80);\n            assertEquals(rule.getDirection(), RuleDirection.INGRESS);\n         } finally {\n            if (sgApi != null) {\n               try {\n                  if (rule != null) {\n                     assertTrue(sgApi.deleteRule(rule.getId()));\n                  }\n               } finally {\n                  assertTrue(sgApi.deleteSecurityGroup(securityGroup.getId()));\n               }\n            }\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/java/org/jclouds/openstack/neutron/v2/features/SecurityGroupApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.features;\n\nimport static com.google.common.collect.Iterables.size;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.net.URISyntaxException;\nimport java.util.List;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\n\nimport org.jclouds.openstack.neutron.v2.NeutronApi;\nimport org.jclouds.openstack.neutron.v2.domain.Rule;\nimport org.jclouds.openstack.neutron.v2.domain.RuleDirection;\nimport org.jclouds.openstack.neutron.v2.domain.RuleEthertype;\nimport org.jclouds.openstack.neutron.v2.domain.RuleProtocol;\nimport org.jclouds.openstack.neutron.v2.domain.Rules;\nimport org.jclouds.openstack.neutron.v2.domain.SecurityGroup;\nimport org.jclouds.openstack.neutron.v2.domain.SecurityGroups;\nimport org.jclouds.openstack.neutron.v2.internal.BaseNeutronApiMockTest;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\nimport org.testng.annotations.Test;\n\n\n/**\n * Tests SecurityGroupApi Guice wiring and parsing\n *\n */\n@Test\npublic class SecurityGroupApiMockTest extends BaseNeutronApiMockTest {\n\n   public void testCreateSecurityGroup() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(\n            new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/security_group_create_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         SecurityGroupApi api = neutronApi.getSecurityGroupApi(\"RegionOne\");\n\n         SecurityGroup.CreateSecurityGroup createSecurityGroup = SecurityGroup.createBuilder().name(\"new-webservers\")\n               .description(\"security group for webservers\")\n               .build();\n\n         SecurityGroup securityGroup = api.create(createSecurityGroup);\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"POST\", uriApiVersion + \"/security-groups\", \"/security_group_create_request.json\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(securityGroup);\n         assertEquals(securityGroup.getId(), \"2076db17-a522-4506-91de-c6dd8e837028\");\n         assertEquals(securityGroup.getTenantId(), \"e4f50856753b4dc6afee5fa6b9b6c550\");\n         assertEquals(securityGroup.getName(), \"new-webservers\");\n         assertEquals(securityGroup.getDescription(), \"security group for webservers\");\n\n         Rule sgr0 = securityGroup.getRules().get(0);\n         Rule sgr1 = securityGroup.getRules().get(1);\n\n         assertEquals(sgr0.getId(), \"38ce2d8e-e8f1-48bd-83c2-d33cb9f50c3d\");\n         assertEquals(sgr1.getId(), \"565b9502-12de-4ffd-91e9-68885cff6ae1\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testCreateSecurityGroupRule() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(\n            new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/security_group_rule_create_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         SecurityGroupApi api = neutronApi.getSecurityGroupApi(\"RegionOne\");\n\n         Rule.CreateRule createSecurityGroupRule = Rule.createBuilder(\n               RuleDirection.INGRESS, \"a7734e61-b545-452d-a3cd-0189cbd9747a\")\n               .portRangeMin(80)\n               .portRangeMax(80)\n               .ethertype(RuleEthertype.IPV4)\n               .protocol(RuleProtocol.TCP)\n               .remoteGroupId(\"85cc3048-abc3-43cc-89b3-377341426ac5\")\n               .build();\n\n         Rule rule = api.create(createSecurityGroupRule);\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"POST\", uriApiVersion + \"/security-group-rules\", \"/security_group_rule_create_request.json\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(rule);\n         assertEquals(rule.getId(), \"2bc0accf-312e-429a-956e-e4407625eb62\");\n         assertEquals(rule.getTenantId(), \"e4f50856753b4dc6afee5fa6b9b6c550\");\n         assertEquals(rule.getDirection(), RuleDirection.INGRESS);\n         assertEquals(rule.getPortRangeMax().intValue(), 80);\n         assertEquals(rule.getPortRangeMin().intValue(), 80);\n         assertEquals(rule.getEthertype(), RuleEthertype.IPV4);\n         assertEquals(rule.getProtocol(), RuleProtocol.TCP);\n         assertEquals(rule.getRemoteGroupId(), \"85cc3048-abc3-43cc-89b3-377341426ac5\");\n         assertEquals(rule.getSecurityGroupId(), \"a7734e61-b545-452d-a3cd-0189cbd9747a\");\n\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testListSpecificPageSecurityGroup() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/security_group_list_response_paged1.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         SecurityGroupApi api = neutronApi.getSecurityGroupApi(\"RegionOne\");\n\n         SecurityGroups securityGroups = api.listSecurityGroups(PaginationOptions.Builder.limit(2).marker(\"abcdefg\"));\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/security-groups?limit=2&marker=abcdefg\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(securityGroups);\n         assertEquals(size(securityGroups), 2);\n         // Ensures the full collection is parsed and ordering is preserved.\n         assertEquals(securityGroups.first().get().getId(), \"85cc3048-abc3-43cc-89b3-377341426ac5\");\n         assertEquals(securityGroups.get(1).getId(), \"85cc3048-abc3-43cc-89b3-377341426ac52\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testListSpecificPageSecurityGroupRule() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/security_group_rule_list_response_paged1.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         SecurityGroupApi api = neutronApi.getSecurityGroupApi(\"RegionOne\");\n\n         Rules rules = api.listRules(PaginationOptions.Builder.limit(2).marker(\"abcdefg\"));\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/security-group-rules?limit=2&marker=abcdefg\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(rules);\n         assertEquals(rules.size(), 4);\n         // Ensures the full collection is parsed and ordering is preserved.\n         assertEquals(rules.first().get().getId(), \"3c0e45ff-adaf-4124-b083-bf390e5482ff\");\n         assertEquals(rules.get(3).getId(), \"f7d45c89-008e-4bab-88ad-d6811724c51c\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testListPagedSecurityGroups() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/security_group_list_response_paged1.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/security_group_list_response_paged2.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         SecurityGroupApi api = neutronApi.getSecurityGroupApi(\"RegionOne\");\n\n         // Note: Lazy! Have to actually look at the collection.\n         List<SecurityGroup> securityGroups = api.listSecurityGroups().concat().toList();\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/security-groups\");\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/security-groups?marker=71c1e68c-171a-4aa2-aca5-50ea153a3718\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(securityGroups);\n         assertEquals(securityGroups.size(), 4);\n         // Ensures ordering is preserved and both pages are parsed.\n         assertEquals(securityGroups.get(0).getId(), \"85cc3048-abc3-43cc-89b3-377341426ac5\");\n         assertEquals(securityGroups.get(3).getId(), \"85cc3048-abc3-43cc-89b3-377341426ac524\");\n\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testListPagedSecurityGroupRules() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/security_group_rule_list_response_paged1.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/security_group_rule_list_response_paged2.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         SecurityGroupApi api = neutronApi.getSecurityGroupApi(\"RegionOne\");\n\n         // Note: Lazy! Have to actually look at the collection.\n         List<Rule> rules = api.listRules().concat().toList();\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/security-group-rules\");\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/security-group-rules?marker=71c1e68c-171a-4aa2-aca5-50ea153a3718\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(rules);\n         assertEquals(rules.size(), 8);\n         // Ensures both pages are tested and ordering is preserved.\n         assertEquals(rules.get(0).getId(), \"3c0e45ff-adaf-4124-b083-bf390e5482ff\");\n         assertEquals(rules.get(7).getId(), \"f7d45c89-008e-4bab-88ad-d6811724c51c2\");\n\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGetSecurityGroup() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(\n            new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/security_group_get_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         SecurityGroupApi api = neutronApi.getSecurityGroupApi(\"RegionOne\");\n\n         SecurityGroup securityGroup = api.getSecurityGroup(\"12345\");\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/security-groups/12345\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(securityGroup);\n         assertEquals(securityGroup.getName(), \"default\");\n         assertEquals(securityGroup.getDescription(), \"default\");\n         assertEquals(securityGroup.getId(), \"85cc3048-abc3-43cc-89b3-377341426ac5\");\n         assertEquals(securityGroup.getTenantId(), \"e4f50856753b4dc6afee5fa6b9b6c550\");\n         Rule sgr = securityGroup.getRules().get(0);\n         assertEquals(sgr.getId(), \"3c0e45ff-adaf-4124-b083-bf390e5482ff\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGetSecurityGroupRule() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(\n            new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/security_group_rule_get_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         SecurityGroupApi api = neutronApi.getSecurityGroupApi(\"RegionOne\");\n\n         Rule rule = api.get(\"12345\");\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/security-group-rules/12345\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(rule);\n         assertEquals(rule.getDirection(), RuleDirection.EGRESS);\n         assertEquals(rule.getEthertype(), RuleEthertype.IPV6);\n         assertEquals(rule.getId(), \"3c0e45ff-adaf-4124-b083-bf390e5482ff\");\n         assertEquals(rule.getTenantId(), \"e4f50856753b4dc6afee5fa6b9b6c550\");\n         assertEquals(rule.getSecurityGroupId(), \"85cc3048-abc3-43cc-89b3-377341426ac5\");\n\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testDeleteSecurityGroup() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(\n            new MockResponse().setResponseCode(201)));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         SecurityGroupApi api = neutronApi.getSecurityGroupApi(\"RegionOne\");\n\n         boolean result = api.deleteSecurityGroup(\"12345\");\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"DELETE\", uriApiVersion + \"/security-groups/12345\");\n\n         /*\n          * Check response\n          */\n         assertTrue(result);\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testDeleteSecurityGroupRule() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(\n            new MockResponse().setResponseCode(201)));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         SecurityGroupApi api = neutronApi.getSecurityGroupApi(\"RegionOne\");\n\n         boolean result = api.deleteRule(\"12345\");\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"DELETE\", uriApiVersion + \"/security-group-rules/12345\");\n\n         /*\n          * Check response\n          */\n         assertTrue(result);\n      } finally {\n         server.shutdown();\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/java/org/jclouds/openstack/neutron/v2/features/SubnetApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.features;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Sets;\nimport org.jclouds.openstack.neutron.v2.domain.AllocationPool;\nimport org.jclouds.openstack.neutron.v2.domain.HostRoute;\nimport org.jclouds.openstack.neutron.v2.domain.Network;\nimport org.jclouds.openstack.neutron.v2.domain.NetworkType;\nimport org.jclouds.openstack.neutron.v2.domain.Subnet;\nimport org.jclouds.openstack.neutron.v2.internal.BaseNeutronApiLiveTest;\nimport org.jclouds.openstack.neutron.v2.util.PredicateUtil;\nimport org.testng.annotations.Test;\n\nimport java.util.Set;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\n/**\n * Tests subnet api in combination with the network api\n */\n@Test(groups = \"live\", testName = \"SubnetApiLiveTest\")\npublic class SubnetApiLiveTest extends BaseNeutronApiLiveTest {\n\n   public void testCreateUpdateAndDeleteSubnet() {\n      for (String region : api.getConfiguredRegions()) {\n         NetworkApi networkApi = api.getNetworkApi(region);\n         String networkId = networkApi.create(Network.createBuilder(\"jclouds-live-test\").networkType(NetworkType.LOCAL).build()).getId();\n\n         SubnetApi subnetApi = api.getSubnetApi(region);\n         ImmutableSet<AllocationPool> allocationPools = ImmutableSet.of(\n            AllocationPool.builder().start(\"a3:bc00::10\").end(\"a3:bc00::20\").build(),\n            AllocationPool.builder().start(\"a3:bc00::50\").end(\"a3:bc00::90\").build()\n         );\n         ImmutableSet<HostRoute> hostRoutes = ImmutableSet.of(\n            HostRoute.builder().destinationCidr(\"a3:bc00::/48\").nextHop(\"a3:bc00::0004\").build()\n         );\n         Subnet subnet = subnetApi.create(Subnet.createBuilder(networkId, \"a3:bc00::/48\").ipVersion(6).allocationPools(allocationPools).hostRoutes(hostRoutes).build());\n         assertNotNull(subnet);\n\n         /* Test list and get */\n         Subnet subnetList = api.getSubnetApi(region).list().concat().toSet().iterator().next();\n         assertNotNull(subnetList);\n         Subnet subnetGet = api.getSubnetApi(region).get(subnetList.getId());\n         assertEquals(subnetList, subnetGet);\n         /***/\n\n         Subnet retrievedSubnet = subnetApi.get(subnet.getId());\n\n         assertEquals(retrievedSubnet.getId(), subnet.getId());\n         assertEquals(retrievedSubnet.getCidr(), \"a3:bc00::/48\");\n         assertTrue(retrievedSubnet.getDnsNameservers().isEmpty());\n         assertEquals(retrievedSubnet.getAllocationPools().size(), 2);\n         assertEquals(retrievedSubnet.getHostRoutes().size(), 1);\n         assertNotNull(subnetApi.update(retrievedSubnet.getId(), Subnet.updateBuilder().name(\"jclouds-live-test-update\").build()));\n\n         retrievedSubnet = subnetApi.get(retrievedSubnet.getId());\n\n         assertEquals(retrievedSubnet.getId(), subnet.getId());\n         assertEquals(retrievedSubnet.getName(), \"jclouds-live-test-update\");\n         assertTrue(retrievedSubnet.getDnsNameservers().isEmpty());\n\n         Subnet subnet2 = subnetApi.create(Subnet.createBuilder(networkId, \"a3:bd01::/48\").ipVersion(6).build());\n         assertNotNull(subnet2);\n\n         assertTrue(subnetApi.delete(subnet.getId()));\n         assertTrue(subnetApi.delete(subnet2.getId()));\n         assertTrue(networkApi.delete(networkId));\n      }\n   }\n\n   public void testBulkCreateSubnet() {\n      for (String region : api.getConfiguredRegions()) {\n         NetworkApi networkApi = api.getNetworkApi(region);\n         String networkId = networkApi.create(Network.createBuilder(\"jclouds-live-test\").networkType(NetworkType.LOCAL).build()).getId();\n\n         SubnetApi subnetApi = api.getSubnetApi(region);\n         Set<? extends Subnet> subnets = subnetApi.createBulk(\n               ImmutableList.of(\n                  Subnet.createBuilder(\"jclouds-live-test-1\", \"a3:bd01::/48\").ipVersion(6).networkId(networkId).build(),\n                  Subnet.createBuilder(\"jclouds-live-test-2\", \"a3:bd02::/48\").ipVersion(6).networkId(networkId).build(),\n                  Subnet.createBuilder(\"jclouds-live-test-3\", \"a3:bd03::/48\").ipVersion(6).networkId(networkId).build()\n               )\n         ).toSet();\n         Set<Subnet> existingSubnets = subnetApi.list().concat().toSet();\n\n         assertNotNull(subnets);\n         assertTrue(!subnets.isEmpty());\n         assertEquals(subnets.size(), 3);\n\n         for (Subnet net : subnets) {\n            Predicate<Subnet> idEqualsPredicate = PredicateUtil.createIdEqualsPredicate(net.getId());\n            assertEquals(1, Sets.filter(existingSubnets, idEqualsPredicate).size());\n            assertTrue(subnetApi.delete(net.getId()));\n         }\n         assertTrue(networkApi.delete(networkId));\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/java/org/jclouds/openstack/neutron/v2/features/SubnetApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.net.URISyntaxException;\nimport java.util.List;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\n\nimport org.jclouds.openstack.neutron.v2.NeutronApi;\nimport org.jclouds.openstack.neutron.v2.domain.IPv6DHCPMode;\nimport org.jclouds.openstack.neutron.v2.domain.Subnet;\nimport org.jclouds.openstack.neutron.v2.domain.Subnets;\nimport org.jclouds.openstack.neutron.v2.internal.BaseNeutronApiMockTest;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableList;\n\n\n/**\n * Tests NetworkApi Guice wiring and parsing\n *\n */\n@Test\npublic class SubnetApiMockTest extends BaseNeutronApiMockTest {\n\n   public void testCreateSubnet() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/subnet_create_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         SubnetApi api = neutronApi.getSubnetApi(\"RegionOne\");\n\n         Subnet.CreateSubnet createSubnet = Subnet.createBuilder(\"1234567890\", \"10.0.3.0/24\")\n               .name(\"jclouds-wibble\")\n               .ipVersion(4)\n               .build();\n\n         Subnet subnet = api.create(createSubnet);\n\n         /*\n          * Check request\n          */\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"POST\", uriApiVersion + \"/subnets\", \"/subnet_create_request.json\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(subnet);\n         assertEquals(subnet.getName(), \"jclouds-wibble\");\n         assertEquals(subnet.getIpVersion().intValue(), 4);\n         assertEquals(subnet.getCidr(), \"10.0.3.0/24\");\n         assertEquals(subnet.getTenantId(), \"1234567890\");\n         assertEquals(subnet.getId(), \"624312ff-d14b-4ba3-9834-1c78d23d574d\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testListSpecificPageSubnet() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/subnet_list_response_pages1.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         SubnetApi api = neutronApi.getSubnetApi(\"RegionOne\");\n\n         Subnets subnets = api.list(PaginationOptions.Builder.limit(2).marker(\"abcdefg\"));\n\n         /*\n          * Check request\n          */\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/subnets?limit=2&marker=abcdefg\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(subnets);\n         assertEquals(subnets.first().get().getId(), \"16dba3bc-f3fa-4775-afdc-237e12c72f6a\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testListPagedSubnet() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/subnet_list_response_pages1.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/subnet_list_response_pages2.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         SubnetApi api = neutronApi.getSubnetApi(\"RegionOne\");\n\n         // Note: Lazy! Have to actually look at the collection.\n         List<Subnet> subnets = api.list().concat().toList();\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/subnets\");\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/subnets?marker=71c1e68c-171a-4aa2-aca5-50ea153a3718\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(subnets);\n         assertEquals(subnets.size(), 4);\n         assertEquals(subnets.get(0).getId(), \"16dba3bc-f3fa-4775-afdc-237e12c72f6a\");\n         assertEquals(subnets.get(3).getId(), \"6ba4c788-661f-49ab-9bf8-5f10cbbb2f57\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGetSubnet() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/subnet_get_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         SubnetApi api = neutronApi.getSubnetApi(\"RegionOne\");\n\n         Subnet subnet = api.get(\"12345\");\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"GET\", uriApiVersion + \"/subnets/12345\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(subnet);\n         assertEquals(subnet.getName(), \"jclouds-wibble\");\n         assertEquals(subnet.getId(), \"624312ff-d14b-4ba3-9834-1c78d23d574d\");\n         assertEquals(subnet.getTenantId(), \"1234567890\");\n         assertEquals(subnet.getIPv6AddressMode(), IPv6DHCPMode.SLAAC);\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testCreateBulkSubnet() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(201).setBody(stringFromResource(\"/subnet_bulk_create_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         SubnetApi api = neutronApi.getSubnetApi(\"RegionOne\");\n\n         Subnet.CreateSubnet createSubnet1 = Subnet.createBuilder(\"e6031bc2-901a-4c66-82da-f4c32ed89406\",\n               \"192.168.199.0/24\")\n               .ipVersion(4)\n               .build();\n\n         Subnet.CreateSubnet createSubnet2 = Subnet.createBuilder(\"64239a54-dcc4-4b39-920b-b37c2144effa\",\n               \"10.56.4.0/22\")\n               .ipVersion(4)\n               .build();\n\n         FluentIterable<Subnet> subnets = api.createBulk(ImmutableList.of(createSubnet1, createSubnet2));\n\n         /*\n          * Check request\n          */\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"POST\", uriApiVersion + \"/subnets\", \"/subnet_bulk_create_request.json\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(subnets);\n         assertEquals(subnets.size(), 2);\n         assertEquals(subnets.get(0).getName(), \"\");\n         assertEquals(subnets.get(0).getIpVersion().intValue(), 4);\n         assertEquals(subnets.get(0).getCidr(), \"192.168.199.0/24\");\n         assertTrue(subnets.get(0).getDnsNameservers().isEmpty());\n         assertTrue(subnets.get(0).getEnableDhcp());\n         assertTrue(subnets.get(0).getHostRoutes().isEmpty());\n         assertEquals(subnets.get(0).getTenantId(), \"d19231fc08ec4bc4829b668040d34512\");\n         assertEquals(subnets.get(0).getId(), \"0468a7a7-290d-4127-aedd-6c9449775a24\");\n         assertEquals(subnets.get(0).getNetworkId(), \"e6031bc2-901a-4c66-82da-f4c32ed89406\");\n         assertEquals(subnets.get(0).getAllocationPools().iterator().next().getStart(), \"192.168.199.2\");\n         assertEquals(subnets.get(0).getAllocationPools().iterator().next().getEnd(), \"192.168.199.254\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testUpdateSubnet() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(stringFromResource(\"/subnet_update_response.json\"))));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         SubnetApi api = neutronApi.getSubnetApi(\"RegionOne\");\n\n         Subnet.UpdateSubnet updateSubnet = Subnet.updateBuilder()\n               .name(\"new_name\")\n               .gatewayIp(\"10.0.3.254\")\n               .build();\n\n         Subnet subnet = api.update(\"12345\", updateSubnet);\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"PUT\", uriApiVersion + \"/subnets/12345\", \"/subnet_update_request.json\");\n\n         /*\n          * Check response\n          */\n         assertNotNull(subnet);\n         assertEquals(subnet.getName(), \"new_name\");\n         assertEquals(subnet.getId(), \"9436e561-47bf-436a-b1f1-fe23a926e031\");\n         assertEquals(subnet.getTenantId(), \"c1210485b2424d48804aad5d39c61b8f\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testDeleteSubnet() throws IOException, InterruptedException, URISyntaxException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200)));\n\n      try {\n         NeutronApi neutronApi = api(server.url(\"/\").toString(), \"openstack-neutron\", overrides);\n         SubnetApi api = neutronApi.getSubnetApi(\"RegionOne\");\n\n         boolean result = api.delete(\"12345\");\n\n         /*\n          * Check request\n          */\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"DELETE\", uriApiVersion + \"/subnets/12345\");\n\n         /*\n          * Check response\n          */\n         assertTrue(result);\n      } finally {\n         server.shutdown();\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/java/org/jclouds/openstack/neutron/v2/internal/BaseNeutronApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.internal;\n\nimport java.util.Properties;\n\nimport org.jclouds.apis.BaseApiLiveTest;\nimport org.jclouds.logging.config.LoggingModule;\nimport org.jclouds.logging.slf4j.config.SLF4JLoggingModule;\nimport org.jclouds.openstack.keystone.config.KeystoneProperties;\nimport org.jclouds.openstack.neutron.v2.NeutronApi;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code NeutronApi}\n *\n */\n@Test(groups = \"live\")\npublic class BaseNeutronApiLiveTest extends BaseApiLiveTest<NeutronApi> {\n\n   public BaseNeutronApiLiveTest() {\n      provider = \"openstack-neutron\";\n   }\n\n   @Override\n   protected LoggingModule getLoggingModule() {\n      return new SLF4JLoggingModule();\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      setIfTestSystemPropertyPresent(props, KeystoneProperties.CREDENTIAL_TYPE);\n      return props;\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/java/org/jclouds/openstack/neutron/v2/internal/BaseNeutronApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.neutron.v2.internal;\n\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.CREDENTIAL_TYPE;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.SERVICE_TYPE;\n\nimport java.util.Properties;\n\nimport org.jclouds.openstack.keystone.auth.config.CredentialTypes;\nimport org.jclouds.openstack.neutron.v2.NeutronApi;\nimport org.jclouds.openstack.v2_0.internal.BaseOpenStackMockTest;\n\n/**\n * Base class for writing Neutron Mock tests\n *\n */\npublic class BaseNeutronApiMockTest extends BaseOpenStackMockTest<NeutronApi> {\n   protected Properties overrides;\n   protected String uriApiVersion = \"/v2.0\";\n\n   /**\n    * Base Mock Test\n    */\n   public BaseNeutronApiMockTest() {\n      overrides = new Properties();\n      overrides.setProperty(SERVICE_TYPE, \"network\");\n      overrides.setProperty(CREDENTIAL_TYPE, CredentialTypes.PASSWORD_CREDENTIALS);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/java/org/jclouds/openstack/neutron/v2/util/ClassUtil.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.openstack.neutron.v2.util;\n\nimport java.lang.reflect.Field;\n\npublic class ClassUtil {\n\n    public static Field findField(Class clazz, String fieldName) {\n        Field fieldToFind = null;\n        if (clazz.getSuperclass() != null)\n            fieldToFind = findField(clazz.getSuperclass(), fieldName);\n\n        if (fieldToFind != null)\n            return fieldToFind;\n\n        for (Field field : clazz.getDeclaredFields()) {\n            if (field.getName().equals(fieldName))\n                return field;\n        }\n        return null;\n    }\n\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/java/org/jclouds/openstack/neutron/v2/util/PredicateUtil.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.openstack.neutron.v2.util;\n\nimport com.google.common.base.Predicate;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport java.lang.reflect.Field;\n\npublic class PredicateUtil {\n\n    public static <T> Predicate<T> createIdEqualsPredicate(final String id) {\n        return new Predicate<T>() {\n            @Override\n            public boolean apply(@Nullable T input) {\n                if (input == null) return false;\n\n                try {\n                    Class clazz = input.getClass();\n                    Field field = ClassUtil.findField(clazz, \"id\");\n                    field.setAccessible(true);\n                    String value = (String) field.get(input);\n                    field.setAccessible(false);\n                    return value != null && value.equals(id);\n                } catch (IllegalAccessException iae) {\n                    return false;\n                }\n            }\n        };\n    }\n\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/access.json",
    "content": "{\n    \"access\": {\n        \"metadata\": {\n            \"roles\": [\n                \"9fe2ff9ee4384b1894a90878d3e92bab\",\n                \"b926cb0f4e2642678735f86c2b06205e\",\n                \"33484487e73d4da0918a19b9c7e1f8ae\",\n                \"f2e54c2105fb49e29479af047115cebc\"\n            ],\n            \"is_admin\": 0\n        },\n        \"user\": {\n            \"name\": \"joe\",\n            \"roles\": [\n                {\n                    \"name\": \"_member_\"\n                },\n                {\n                    \"name\": \"anotherrole\"\n                },\n                {\n                    \"name\": \"heat_stack_owner\"\n                },\n                {\n                    \"name\": \"Member\"\n                }\n            ],\n            \"id\": \"8fbf8e68d36e4ac7bcf912a26213bd49\",\n            \"roles_links\": [],\n            \"username\": \"joe\"\n        },\n        \"serviceCatalog\": [\n            {\n                \"name\": \"nova\",\n                \"type\": \"compute\",\n                \"endpoints_links\": [],\n                \"endpoints\": [\n                    {\n                        \"publicURL\": \"URL/v2/da0d12be20394afb851716e10a49e4a7\",\n                        \"id\": \"2122bcaa704343c19ad2578410d4961d\",\n                        \"internalURL\": \"URL/v2/da0d12be20394afb851716e10a49e4a7\",\n                        \"region\": \"RegionOne\",\n                        \"adminURL\": \"URL/v2/da0d12be20394afb851716e10a49e4a7\"\n                    }\n                ]\n            },\n            {\n                \"name\": \"neutron\",\n                \"type\": \"network\",\n                \"endpoints_links\": [],\n                \"endpoints\": [\n                    {\n                        \"publicURL\": \"URL/\",\n                        \"id\": \"65a4d3f13cfb49a6a57a04e205cc2158\",\n                        \"internalURL\": \"URL/\",\n                        \"region\": \"RegionOne\",\n                        \"adminURL\": \"URL/\"\n                    }\n                ]\n            },\n            {\n                \"name\": \"cinderv2\",\n                \"type\": \"volumev2\",\n                \"endpoints_links\": [],\n                \"endpoints\": [\n                    {\n                        \"publicURL\": \"URL/v2/da0d12be20394afb851716e10a49e4a7\",\n                        \"id\": \"31fe4d92eac44044b05be21c6f44cebc\",\n                        \"internalURL\": \"URL/v2/da0d12be20394afb851716e10a49e4a7\",\n                        \"region\": \"RegionOne\",\n                        \"adminURL\": \"URL/v2/da0d12be20394afb851716e10a49e4a7\"\n                    }\n                ]\n            },\n            {\n                \"name\": \"trove\",\n                \"type\": \"database\",\n                \"endpoints_links\": [],\n                \"endpoints\": [\n                    {\n                        \"publicURL\": \"URL/v1.0/da0d12be20394afb851716e10a49e4a7\",\n                        \"id\": \"06b7a7dbd25c4a01819c879700a9712a\",\n                        \"internalURL\": \"URL/v1.0/da0d12be20394afb851716e10a49e4a7\",\n                        \"region\": \"RegionOne\",\n                        \"adminURL\": \"URL/v1.0/da0d12be20394afb851716e10a49e4a7\"\n                    }\n                ]\n            },\n            {\n                \"name\": \"s3\",\n                \"type\": \"s3\",\n                \"endpoints_links\": [],\n                \"endpoints\": [\n                    {\n                        \"publicURL\": \"URL\",\n                        \"id\": \"93b0b67091324e8ba01b62ee0584994c\",\n                        \"internalURL\": \"URL\",\n                        \"region\": \"RegionOne\",\n                        \"adminURL\": \"URL\"\n                    }\n                ]\n            },\n            {\n                \"name\": \"glance\",\n                \"type\": \"image\",\n                \"endpoints_links\": [],\n                \"endpoints\": [\n                    {\n                        \"publicURL\": \"URL\",\n                        \"id\": \"a542e91bcfa046bfa1bf2397356d1414\",\n                        \"internalURL\": \"URL\",\n                        \"region\": \"RegionOne\",\n                        \"adminURL\": \"URL\"\n                    }\n                ]\n            },\n            {\n                \"name\": \"novav3\",\n                \"type\": \"computev3\",\n                \"endpoints_links\": [],\n                \"endpoints\": [\n                    {\n                        \"publicURL\": \"URL/v3\",\n                        \"id\": \"9c3e8abb576d483db93bcef70c67bc1d\",\n                        \"internalURL\": \"URL/v3\",\n                        \"region\": \"RegionOne\",\n                        \"adminURL\": \"URL/v3\"\n                    }\n                ]\n            },\n            {\n                \"name\": \"heat\",\n                \"type\": \"cloudformation\",\n                \"endpoints_links\": [],\n                \"endpoints\": [\n                    {\n                        \"publicURL\": \"URL/v1\",\n                        \"id\": \"6f4ca5ca9698425b85c300b3fc176c39\",\n                        \"internalURL\": \"URL/v1\",\n                        \"region\": \"RegionOne\",\n                        \"adminURL\": \"URL/v1\"\n                    }\n                ]\n            },\n            {\n                \"name\": \"cinder\",\n                \"type\": \"volume\",\n                \"endpoints_links\": [],\n                \"endpoints\": [\n                    {\n                        \"publicURL\": \"URL/v1/da0d12be20394afb851716e10a49e4a7\",\n                        \"id\": \"037039c676694a35aa28d34fce09e51d\",\n                        \"internalURL\": \"URL/v1/da0d12be20394afb851716e10a49e4a7\",\n                        \"region\": \"RegionOne\",\n                        \"adminURL\": \"URL/v1/da0d12be20394afb851716e10a49e4a7\"\n                    }\n                ]\n            },\n            {\n                \"name\": \"ec2\",\n                \"type\": \"ec2\",\n                \"endpoints_links\": [],\n                \"endpoints\": [\n                    {\n                        \"publicURL\": \"URL/services/Cloud\",\n                        \"id\": \"1d242631bccb4ff4ba7a395dbcb51648\",\n                        \"internalURL\": \"URL/services/Cloud\",\n                        \"region\": \"RegionOne\",\n                        \"adminURL\": \"URL/services/Admin\"\n                    }\n                ]\n            },\n            {\n                \"name\": \"heat\",\n                \"type\": \"orchestration\",\n                \"endpoints_links\": [],\n                \"endpoints\": [\n                    {\n                        \"publicURL\": \"URL/v1/da0d12be20394afb851716e10a49e4a7\",\n                        \"id\": \"199d00075e4a40308a6ad2aa8980d0cd\",\n                        \"internalURL\": \"URL/v1/da0d12be20394afb851716e10a49e4a7\",\n                        \"region\": \"RegionOne\",\n                        \"adminURL\": \"URL/v1/da0d12be20394afb851716e10a49e4a7\"\n                    }\n                ]\n            },\n            {\n                \"name\": \"swift\",\n                \"type\": \"object-store\",\n                \"endpoints_links\": [],\n                \"endpoints\": [\n                    {\n                        \"publicURL\": \"URL/v1/AUTH_da0d12be20394afb851716e10a49e4a7\",\n                        \"id\": \"26b2cb1efb044193b847fc3f2fb12e82\",\n                        \"internalURL\": \"URL/v1/AUTH_da0d12be20394afb851716e10a49e4a7\",\n                        \"region\": \"RegionOne\",\n                        \"adminURL\": \"URL\"\n                    }\n                ]\n            },\n            {\n                \"name\": \"keystone\",\n                \"type\": \"identity\",\n                \"endpoints_links\": [],\n                \"endpoints\": [\n                    {\n                        \"publicURL\": \"URL/v2.0\",\n                        \"id\": \"1bbfe80b50df4c4a84040aa782e42140\",\n                        \"internalURL\": \"URL/v2.0\",\n                        \"region\": \"RegionOne\",\n                        \"adminURL\": \"URL/v2.0\"\n                    }\n                ]\n            }\n        ],\n        \"token\": {\n            \"tenant\": {\n                \"name\": \"jclouds\",\n                \"id\": \"da0d12be20394afb851716e10a49e4a7\",\n                \"enabled\": true,\n                \"description\": null\n            },\n            \"id\": \"TOKEN\",\n            \"expires\": \"2014-04-28T22:48:24Z\",\n            \"issued_at\": \"2014-04-28T21:48:24.972896\"\n        }\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/extension_details.json",
    "content": "{\n    \"extension\": {\n        \"name\": \"Neutron L3 Router\",\n        \"namespace\": \"http://docs.openstack.org/ext/neutron/router/api/v1.0\",\n        \"alias\": \"router\",\n        \"updated\": \"2012-07-20T10:00:00-00:00\",\n        \"description\": \"Router abstraction for basic L3 forwarding between L2 Neutron networks and access to external networks via a NAT gateway.\",\n        \"links\": []\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/extension_list.json",
    "content": "{\n  \"extensions\": [\n    {\n      \"updated\": \"2013-01-20T00:00:00-00:00\",\n      \"name\": \"Neutron Service Type Management\",\n      \"links\": [],\n      \"namespace\": \"http://docs.openstack.org/ext/neutron/service-type/api/v1.0\",\n      \"alias\": \"service-type\",\n      \"description\": \"API for retrieving service providers for Neutron advanced services\"\n    },\n    {\n      \"updated\": \"2012-10-05T10:00:00-00:00\",\n      \"name\": \"security-group\",\n      \"links\": [],\n      \"namespace\": \"http://docs.openstack.org/ext/securitygroups/api/v2.0\",\n      \"alias\": \"security-group\",\n      \"description\": \"The security groups extension.\"\n    },\n    {\n      \"updated\": \"2013-02-07T10:00:00-00:00\",\n      \"name\": \"Loadbalancer Agent Scheduler\",\n      \"links\": [],\n      \"namespace\": \"http://docs.openstack.org/ext/lbaas_agent_scheduler/api/v1.0\",\n      \"alias\": \"lbaas_agent_scheduler\",\n      \"description\": \"Schedule pools among lbaas agents\"\n    },\n    {\n      \"updated\": \"2013-02-25T10:00:00-00:00\",\n      \"name\": \"Firewall service\",\n      \"links\": [],\n      \"namespace\": \"http://wiki.openstack.org/Neutron/FWaaS/API_1.0\",\n      \"alias\": \"fwaas\",\n      \"description\": \"Extension for Firewall service\"\n    },\n    {\n      \"updated\": \"2014-02-03T10:00:00-00:00\",\n      \"name\": \"Port Binding\",\n      \"links\": [],\n      \"namespace\": \"http://docs.openstack.org/ext/binding/api/v1.0\",\n      \"alias\": \"binding\",\n      \"description\": \"Expose port bindings of a virtual port to external application\"\n    },\n    {\n      \"updated\": \"2012-07-29T10:00:00-00:00\",\n      \"name\": \"Quota management support\",\n      \"links\": [],\n      \"namespace\": \"http://docs.openstack.org/network/ext/quotas-sets/api/v2.0\",\n      \"alias\": \"quotas\",\n      \"description\": \"Expose functions for quotas management per tenant\"\n    },\n    {\n      \"updated\": \"2014-01-01T10:00:00-00:00\",\n      \"name\": \"Nuage security-group\",\n      \"links\": [],\n      \"namespace\": \"http://nuagenetworks.net/ext/secgroup/api/v1.0\",\n      \"alias\": \"nuage-security-group\",\n      \"description\": \"Nuage security-group\"\n    },\n    {\n      \"updated\": \"2014-01-01T10:00:00-00:00\",\n      \"name\": \"Nuage router\",\n      \"links\": [],\n      \"namespace\": \"http://nuagenetworks.net/ext/routers/api/v1.0\",\n      \"alias\": \"nuage-router\",\n      \"description\": \"Nuage Router\"\n    },\n    {\n      \"updated\": \"2013-01-14T10:00:00-00:00\",\n      \"name\": \"Neutron external network\",\n      \"links\": [],\n      \"namespace\": \"http://docs.openstack.org/ext/neutron/external_net/api/v1.0\",\n      \"alias\": \"external-net\",\n      \"description\": \"Adds external network attribute to network resource.\"\n    },\n    {\n      \"updated\": \"2012-07-20T10:00:00-00:00\",\n      \"name\": \"Neutron L3 Router\",\n      \"links\": [],\n      \"namespace\": \"http://docs.openstack.org/ext/neutron/router/api/v1.0\",\n      \"alias\": \"router\",\n      \"description\": \"Router abstraction for basic L3 forwarding between L2 Neutron networks and access to external networks via a NAT gateway.\"\n    },\n    {\n      \"updated\": \"2014-01-01T10:00:00-00:00\",\n      \"name\": \"Nuage subnet\",\n      \"links\": [],\n      \"namespace\": \"http://nuagenetworks.net/ext/subnets/api/v1.0\",\n      \"alias\": \"nuage-subnet\",\n      \"description\": \"Nuage subnet\"\n    },\n    {\n      \"updated\": \"2013-05-29T10:00:00-00:00\",\n      \"name\": \"VPN service\",\n      \"links\": [],\n      \"namespace\": \"https://wiki.openstack.org/Neutron/VPNaaS\",\n      \"alias\": \"vpnaas\",\n      \"description\": \"Extension for VPN service\"\n    },\n    {\n      \"updated\": \"2014-01-01T10:00:00-00:00\",\n      \"name\": \"NetPartition\",\n      \"links\": [],\n      \"namespace\": \"http://nuagenetworks.net/ext/net_partition/api/v1.0\",\n      \"alias\": \"net-partition\",\n      \"description\": \"NetPartition\"\n    },\n    {\n      \"updated\": \"2012-10-07T10:00:00-00:00\",\n      \"name\": \"LoadBalancing service\",\n      \"links\": [],\n      \"namespace\": \"http://wiki.openstack.org/neutron/LBaaS/API_1.0\",\n      \"alias\": \"lbaas\",\n      \"description\": \"Extension for LoadBalancing service\"\n    },\n    {\n      \"updated\": \"2013-02-01T10:00:00-00:00\",\n      \"name\": \"Neutron Extra Route\",\n      \"links\": [],\n      \"namespace\": \"http://docs.openstack.org/ext/neutron/extraroutes/api/v1.0\",\n      \"alias\": \"extraroute\",\n      \"description\": \"Extra routes configuration for L3 router\"\n    }\n  ]\n}"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/extension_list_with_lbaas_v1_response.json",
    "content": "{\n    \"extensions\": [\n        {\n            \"updated\": \"2013-01-20T00:00:00-00:00\",\n            \"name\": \"Neutron Service Type Management\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/ext/neutron/service-type/api/v1.0\",\n            \"alias\": \"service-type\",\n            \"description\": \"API for retrieving service providers for Neutron advanced services\"\n        },\n        {\n            \"updated\": \"2012-10-05T10:00:00-00:00\",\n            \"name\": \"security-group\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/ext/securitygroups/api/v2.0\",\n            \"alias\": \"security-group\",\n            \"description\": \"The security groups extension.\"\n        },\n        {\n            \"updated\": \"2013-02-07T10:00:00-00:00\",\n            \"name\": \"L3 Agent Scheduler\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/ext/l3_agent_scheduler/api/v1.0\",\n            \"alias\": \"l3_agent_scheduler\",\n            \"description\": \"Schedule routers among l3 agents\"\n        },\n        {\n            \"updated\": \"2013-02-07T10:00:00-00:00\",\n            \"name\": \"Loadbalancer Agent Scheduler\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/ext/lbaas_agent_scheduler/api/v1.0\",\n            \"alias\": \"lbaas_agent_scheduler\",\n            \"description\": \"Schedule pools among lbaas agents\"\n        },\n        {\n            \"updated\": \"2013-03-28T10:00:00-00:00\",\n            \"name\": \"Neutron L3 Configurable external gateway mode\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/ext/neutron/ext-gw-mode/api/v1.0\",\n            \"alias\": \"ext-gw-mode\",\n            \"description\": \"Extension of the router abstraction for specifying whether SNAT should occur on the external gateway\"\n        },\n        {\n            \"updated\": \"2014-02-03T10:00:00-00:00\",\n            \"name\": \"Port Binding\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/ext/binding/api/v1.0\",\n            \"alias\": \"binding\",\n            \"description\": \"Expose port bindings of a virtual port to external application\"\n        },\n        {\n            \"updated\": \"2012-09-07T10:00:00-00:00\",\n            \"name\": \"Provider Network\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/ext/provider/api/v1.0\",\n            \"alias\": \"provider\",\n            \"description\": \"Expose mapping of virtual networks to physical networks\"\n        },\n        {\n            \"updated\": \"2013-02-03T10:00:00-00:00\",\n            \"name\": \"agent\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/ext/agent/api/v2.0\",\n            \"alias\": \"agent\",\n            \"description\": \"The agent management extension.\"\n        },\n        {\n            \"updated\": \"2012-07-29T10:00:00-00:00\",\n            \"name\": \"Quota management support\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/network/ext/quotas-sets/api/v2.0\",\n            \"alias\": \"quotas\",\n            \"description\": \"Expose functions for quotas management per tenant\"\n        },\n        {\n            \"updated\": \"2013-02-07T10:00:00-00:00\",\n            \"name\": \"DHCP Agent Scheduler\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/ext/dhcp_agent_scheduler/api/v1.0\",\n            \"alias\": \"dhcp_agent_scheduler\",\n            \"description\": \"Schedule networks among dhcp agents\"\n        },\n        {\n            \"updated\": \"2013-06-27T10:00:00-00:00\",\n            \"name\": \"Multi Provider Network\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/ext/multi-provider/api/v1.0\",\n            \"alias\": \"multi-provider\",\n            \"description\": \"Expose mapping of virtual networks to multiple physical networks\"\n        },\n        {\n            \"updated\": \"2013-01-14T10:00:00-00:00\",\n            \"name\": \"Neutron external network\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/ext/neutron/external_net/api/v1.0\",\n            \"alias\": \"external-net\",\n            \"description\": \"Adds external network attribute to network resource.\"\n        },\n        {\n            \"updated\": \"2012-07-20T10:00:00-00:00\",\n            \"name\": \"Neutron L3 Router\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/ext/neutron/router/api/v1.0\",\n            \"alias\": \"router\",\n            \"description\": \"Router abstraction for basic L3 forwarding between L2 Neutron networks and access to external networks via a NAT gateway.\"\n        },\n        {\n            \"updated\": \"2013-07-23T10:00:00-00:00\",\n            \"name\": \"Allowed Address Pairs\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/ext/allowedaddresspairs/api/v2.0\",\n            \"alias\": \"allowed-address-pairs\",\n            \"description\": \"Provides allowed address pairs\"\n        },\n        {\n            \"updated\": \"2013-03-17T12:00:00-00:00\",\n            \"name\": \"Neutron Extra DHCP opts\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/ext/neutron/extra_dhcp_opt/api/v1.0\",\n            \"alias\": \"extra_dhcp_opt\",\n            \"description\": \"Extra options configuration for DHCP. For example PXE boot options to DHCP clients can be specified (e.g. tftp-server, server-ip-address, bootfile-name)\"\n        },\n        {\n            \"updated\": \"2012-10-07T10:00:00-00:00\",\n            \"name\": \"LoadBalancing service\",\n            \"links\": [],\n            \"namespace\": \"http://wiki.openstack.org/neutron/LBaaS/API_1.0\",\n            \"alias\": \"lbaas\",\n            \"description\": \"Extension for LoadBalancing service\"\n        },\n        {\n            \"updated\": \"2013-02-01T10:00:00-00:00\",\n            \"name\": \"Neutron Extra Route\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/ext/neutron/extraroutes/api/v1.0\",\n            \"alias\": \"extraroute\",\n            \"description\": \"Extra routes configuration for L3 router\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/extension_list_without_lbaas_v1_response.json",
    "content": "{\n    \"extensions\": [\n        {\n            \"updated\": \"2013-01-20T00:00:00-00:00\",\n            \"name\": \"Neutron Service Type Management\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/ext/neutron/service-type/api/v1.0\",\n            \"alias\": \"service-type\",\n            \"description\": \"API for retrieving service providers for Neutron advanced services\"\n        },\n        {\n            \"updated\": \"2012-10-05T10:00:00-00:00\",\n            \"name\": \"security-group\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/ext/securitygroups/api/v2.0\",\n            \"alias\": \"security-group\",\n            \"description\": \"The security groups extension.\"\n        },\n        {\n            \"updated\": \"2013-02-07T10:00:00-00:00\",\n            \"name\": \"L3 Agent Scheduler\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/ext/l3_agent_scheduler/api/v1.0\",\n            \"alias\": \"l3_agent_scheduler\",\n            \"description\": \"Schedule routers among l3 agents\"\n        },\n        {\n            \"updated\": \"2013-02-07T10:00:00-00:00\",\n            \"name\": \"Loadbalancer Agent Scheduler\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/ext/lbaas_agent_scheduler/api/v1.0\",\n            \"alias\": \"lbaas_agent_scheduler\",\n            \"description\": \"Schedule pools among lbaas agents\"\n        },\n        {\n            \"updated\": \"2013-03-28T10:00:00-00:00\",\n            \"name\": \"Neutron L3 Configurable external gateway mode\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/ext/neutron/ext-gw-mode/api/v1.0\",\n            \"alias\": \"ext-gw-mode\",\n            \"description\": \"Extension of the router abstraction for specifying whether SNAT should occur on the external gateway\"\n        },\n        {\n            \"updated\": \"2014-02-03T10:00:00-00:00\",\n            \"name\": \"Port Binding\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/ext/binding/api/v1.0\",\n            \"alias\": \"binding\",\n            \"description\": \"Expose port bindings of a virtual port to external application\"\n        },\n        {\n            \"updated\": \"2012-09-07T10:00:00-00:00\",\n            \"name\": \"Provider Network\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/ext/provider/api/v1.0\",\n            \"alias\": \"provider\",\n            \"description\": \"Expose mapping of virtual networks to physical networks\"\n        },\n        {\n            \"updated\": \"2013-02-03T10:00:00-00:00\",\n            \"name\": \"agent\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/ext/agent/api/v2.0\",\n            \"alias\": \"agent\",\n            \"description\": \"The agent management extension.\"\n        },\n        {\n            \"updated\": \"2012-07-29T10:00:00-00:00\",\n            \"name\": \"Quota management support\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/network/ext/quotas-sets/api/v2.0\",\n            \"alias\": \"quotas\",\n            \"description\": \"Expose functions for quotas management per tenant\"\n        },\n        {\n            \"updated\": \"2013-02-07T10:00:00-00:00\",\n            \"name\": \"DHCP Agent Scheduler\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/ext/dhcp_agent_scheduler/api/v1.0\",\n            \"alias\": \"dhcp_agent_scheduler\",\n            \"description\": \"Schedule networks among dhcp agents\"\n        },\n        {\n            \"updated\": \"2013-06-27T10:00:00-00:00\",\n            \"name\": \"Multi Provider Network\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/ext/multi-provider/api/v1.0\",\n            \"alias\": \"multi-provider\",\n            \"description\": \"Expose mapping of virtual networks to multiple physical networks\"\n        },\n        {\n            \"updated\": \"2013-01-14T10:00:00-00:00\",\n            \"name\": \"Neutron external network\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/ext/neutron/external_net/api/v1.0\",\n            \"alias\": \"external-net\",\n            \"description\": \"Adds external network attribute to network resource.\"\n        },\n        {\n            \"updated\": \"2012-07-20T10:00:00-00:00\",\n            \"name\": \"Neutron L3 Router\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/ext/neutron/router/api/v1.0\",\n            \"alias\": \"router\",\n            \"description\": \"Router abstraction for basic L3 forwarding between L2 Neutron networks and access to external networks via a NAT gateway.\"\n        },\n        {\n            \"updated\": \"2013-07-23T10:00:00-00:00\",\n            \"name\": \"Allowed Address Pairs\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/ext/allowedaddresspairs/api/v2.0\",\n            \"alias\": \"allowed-address-pairs\",\n            \"description\": \"Provides allowed address pairs\"\n        },\n        {\n            \"updated\": \"2013-03-17T12:00:00-00:00\",\n            \"name\": \"Neutron Extra DHCP opts\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/ext/neutron/extra_dhcp_opt/api/v1.0\",\n            \"alias\": \"extra_dhcp_opt\",\n            \"description\": \"Extra options configuration for DHCP. For example PXE boot options to DHCP clients can be specified (e.g. tftp-server, server-ip-address, bootfile-name)\"\n        },\n        {\n            \"updated\": \"2013-02-01T10:00:00-00:00\",\n            \"name\": \"Neutron Extra Route\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/ext/neutron/extraroutes/api/v1.0\",\n            \"alias\": \"extraroute\",\n            \"description\": \"Extra routes configuration for L3 router\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/firewall_create_request.json",
    "content": "{\n  \"firewall\": {\n    \"admin_state_up\": true,\n    \"firewall_policy_id\": \"c69933c1-b472-44f9-8226-30dc4ffd454c\"\n  }\n}"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/firewall_create_response.json",
    "content": "{\n  \"firewall\": {\n    \"admin_state_up\": true,\n    \"description\": \"\",\n    \"firewall_policy_id\": \"c69933c1-b472-44f9-8226-30dc4ffd454c\",\n    \"id\": \"3b0ef8f4-82c7-44d4-a4fb-6177f9a21977\",\n    \"name\": \"\",\n    \"status\": \"PENDING_CREATE\",\n    \"tenant_id\": \"45977fa2dbd7482098dd68d0d8970117\"\n  }\n}"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/firewall_get_response.json",
    "content": "{\n  \"firewall\": {\n    \"admin_state_up\": true,\n    \"description\": \"\",\n    \"firewall_policy_id\": \"c69933c1-b472-44f9-8226-30dc4ffd454c\",\n    \"id\": \"3b0ef8f4-82c7-44d4-a4fb-6177f9a21977\",\n    \"name\": \"\",\n    \"status\": \"ACTIVE\",\n    \"tenant_id\": \"45977fa2dbd7482098dd68d0d8970117\"\n  }\n}"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/firewall_list_response.json",
    "content": "{\n  \"firewalls\": [\n    {\n      \"status\": \"ACTIVE\",\n      \"name\": \"fw\",\n      \"admin_state_up\": true,\n      \"tenant_id\": \"3e00d5716204446c8d3c47a466eec25a\",\n      \"firewall_policy_id\": \"5083ef0d-7ad2-4305-acd8-bd036c332e1e\",\n      \"id\": \"5eb708e7-3856-449a-99ac-fec27cd745f9\",\n      \"description\": \"\"\n    }\n  ]\n}"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/firewall_policy_create_request.json",
    "content": "{\n  \"firewall_policy\": {\n    \"name\": \"jclouds-fw-policy_group-52-e8b\",\n    \"shared\": false,\n    \"firewall_rules\": [],\n    \"audited\": false\n  }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/firewall_policy_create_response.json",
    "content": "{\n  \"firewall_policy\": {\n    \"name\": \"jclouds-fw-policy_group-52-e8b\",\n    \"firewall_rules\": [],\n    \"tenant_id\": \"3e00d5716204446c8d3c47a466eec25a\",\n    \"audited\": false,\n    \"shared\": false,\n    \"id\": \"12971159-95cf-4ca1-9baa-c82298ae0918\",\n    \"description\": \"\"\n  }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/firewall_policy_get_response.json",
    "content": "{\n  \"firewall_policy\": {\n    \"name\": \"myfirewallrule\",\n    \"firewall_rules\": [\n      \"3e5a4e53-4390-4b22-baea-75529dbeafb8\",\n      \"4e58f636-1ef1-4e8e-b3ad-5f7f9d1f9f23\"\n    ],\n    \"tenant_id\": \"e1defcdd823741c89afd5824040deed2\",\n    \"audited\": false,\n    \"shared\": true,\n    \"id\": \"18d2f4e5-afdd-4c10-87ea-d35f38faf98c\",\n    \"description\": \"\"\n  }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/firewall_policy_insert_rule_request.json",
    "content": "{\"firewall_rule_id\": \"59585143-e819-48c9-944d-f03e0f049dba\"}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/firewall_policy_insert_rule_response.json",
    "content": "{\n  \"name\": \"jclouds-fw-policy_group-52-e8b\",\n  \"firewall_rules\": [\"59585143-e819-48c9-944d-f03e0f049dba\"],\n  \"shared\": false,\n  \"audited\": false,\n  \"tenant_id\": \"3e00d5716204446c8d3c47a466eec25a\",\n  \"id\": \"12971159-95cf-4ca1-9baa-c82298ae0918\",\n  \"firewall_list\": [],\n  \"description\": \"\"\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/firewall_policy_list_response.json",
    "content": "{\n  \"firewall_policies\": [\n    {\n      \"name\": \"myfirewallrule\",\n      \"firewall_rules\": [\n        \"3e5a4e53-4390-4b22-baea-75529dbeafb8\",\n        \"4e58f636-1ef1-4e8e-b3ad-5f7f9d1f9f23\"\n      ],\n      \"tenant_id\": \"e1defcdd823741c89afd5824040deed2\",\n      \"audited\": false,\n      \"shared\": true,\n      \"id\": \"18d2f4e5-afdd-4c10-87ea-d35f38faf98c\",\n      \"description\": \"\"\n    },\n    {\n      \"name\": \"Policy SBT\",\n      \"firewall_rules\": [],\n      \"tenant_id\": \"ba6ba03f266e4ccfb07d2372bc8d68a2\",\n      \"audited\": false,\n      \"shared\": true,\n      \"id\": \"31d6368b-3d8b-49a1-af5d-901283223801\",\n      \"description\": \"\"\n    },\n    {\n      \"name\": \"FW-POLICY-DEMO\",\n      \"firewall_rules\": [\n        \"e434b562-c33f-4d64-84da-adfaaa94630e\",\n        \"03a3d9d7-eb92-49c4-83c1-a479ec37d87b\",\n        \"1086d52d-2323-434d-a1e8-ade5791fb5ac\",\n        \"7240cdf3-a8da-4006-90e2-9191d998fee0\",\n        \"eec4cdbe-859f-45c5-9acb-1935056af1e4\",\n        \"a18ee08e-9d5d-4c9e-9372-c4b8f71c6c75\",\n        \"7aefe7f9-01f6-4387-900e-177684e3c59d\",\n        \"b6017900-7811-4428-9940-a02033042c88\",\n        \"94129848-4eb8-4c8e-9164-cd8ee60faa49\",\n        \"e0649a2b-a327-45ed-a3a0-f068cb3fcf37\",\n        \"53f5bf0a-05e3-4a30-800b-611151a9685d\",\n        \"e07558b1-5e18-4d2d-a79b-0a95f36d1715\",\n        \"43931a28-513d-4cbb-80fa-464bf49df65f\",\n        \"79572a32-fda4-4f2c-bdad-bb11a08af9ed\"\n      ],\n      \"tenant_id\": \"cfb5b69938dc49f19f192eabf62a32e6\",\n      \"audited\": false,\n      \"shared\": true,\n      \"id\": \"4c0743e4-0361-4ed0-a6ce-2a8959d978a9\",\n      \"description\": \"\"\n    },\n    {\n      \"name\": \"fw-policy\",\n      \"firewall_rules\": [\n        \"3c51d308-1c5c-4776-b4ac-6d3c9ebd5685\",\n        \"e614f597-4eb2-457a-a102-5b9ad2beba42\",\n        \"e908239c-2b40-4afa-8ec3-9c4b437367da\",\n        \"1ae9b906-9250-4f8c-a262-b0fe6e7b1680\",\n        \"daa2ee3c-760c-4c67-81a8-e61a310366f1\",\n        \"1bd356b4-d0b0-4a86-a5a3-3245ac838960\",\n        \"e72605a4-f866-4cfe-9962-6577c4a87a4d\"\n      ],\n      \"tenant_id\": \"3e00d5716204446c8d3c47a466eec25a\",\n      \"audited\": false,\n      \"shared\": false,\n      \"id\": \"5083ef0d-7ad2-4305-acd8-bd036c332e1e\",\n      \"description\": \"\"\n    },\n    {\n      \"name\": \"PolicyOfTheVoid\",\n      \"firewall_rules\": [],\n      \"tenant_id\": \"85c79b517ef6431881c9477d2227be5f\",\n      \"audited\": true,\n      \"shared\": true,\n      \"id\": \"60779a72-21bd-4b97-a587-cd5fb8b8e7c0\",\n      \"description\": \"\"\n    },\n    {\n      \"name\": \"Policy\",\n      \"firewall_rules\": [\n        \"2b6646ea-a0d8-4982-b3e2-e14ad2743428\",\n        \"21a42289-b05c-4271-9f06-1172b88c8465\",\n        \"7b998345-1660-428f-969d-bfcdb4c0dbaf\",\n        \"8996fcfd-b88d-4b68-bff7-5fb07fc0088a\",\n        \"55b96a08-f868-45fd-9386-1fd831b7b63b\",\n        \"df5aaeb6-50d7-4344-9f00-f973d5e28185\",\n        \"bc23bcb1-1a81-4658-b72d-485da3af8a8a\"\n      ],\n      \"tenant_id\": \"ccef3550ec724607a8024977b3b4e410\",\n      \"audited\": false,\n      \"shared\": true,\n      \"id\": \"63337440-d0ad-4a3c-9e26-777a6e360119\",\n      \"description\": \"Ping + SSH\"\n    },\n    {\n      \"name\": \"allow_all\",\n      \"firewall_rules\": [\"d52ea23a-9911-44ef-815b-f3b4b6b0df64\"],\n      \"tenant_id\": \"53b1ed26b8874556bc7141f9482fd789\",\n      \"audited\": false,\n      \"shared\": true,\n      \"id\": \"6e3d5d6d-1356-43eb-91ef-d6f70888632d\",\n      \"description\": \"Allow All\"\n    },\n    {\n      \"name\": \"Politique Production\",\n      \"firewall_rules\": [\n        \"a6f58b76-5c90-4530-908c-cc7dbd945a4b\",\n        \"3521380b-624c-42a1-8415-992b52a9dfec\",\n        \"fbcf3060-bd0c-4cd9-b4b1-cf3c76b7fe7d\",\n        \"45aecaba-a659-490a-8f12-92adfda79c15\",\n        \"5cfc4e09-a765-4f4e-93d5-8a9650f051f8\",\n        \"304ff502-eb6f-46b5-8110-c75a483c23e0\",\n        \"1662f0bb-a9a6-415a-b1a7-19ba113d7a52\",\n        \"8bbd0490-452c-4bee-a70f-213558e0bc65\",\n        \"e39fcf85-bea2-49fa-8a8e-c69c5f2e29ae\",\n        \"1bbdd6ba-9ae8-4cd3-8815-ef992c56cb63\",\n        \"100e638c-77cf-4f1e-8194-5a26171f645a\",\n        \"91b8316c-96ae-41da-9c14-42e1f778c0a8\"\n      ],\n      \"tenant_id\": \"13a12b25d3cf4275905e2a6b9878a619\",\n      \"audited\": false,\n      \"shared\": true,\n      \"id\": \"89d7ef67-4cb8-485f-83ac-14085e616137\",\n      \"description\": \"\"\n    },\n    {\n      \"name\": \"any-shared\",\n      \"firewall_rules\": [\"b35ab1c6-309d-4690-b16c-0343a535651c\"],\n      \"tenant_id\": \"3fdcdc95fc88431597700dbb20be37c6\",\n      \"audited\": false,\n      \"shared\": true,\n      \"id\": \"a0a3a1b1-d985-4507-b785-311f8e981fa6\",\n      \"description\": \"\"\n    },\n    {\n      \"name\": \"production\",\n      \"firewall_rules\": [\"5dbe3498-b230-4b34-9915-7bcc22bed99c\"],\n      \"tenant_id\": \"94eb5f2fd9ed471992e2c5c2313b0703\",\n      \"audited\": false,\n      \"shared\": true,\n      \"id\": \"a23d0af2-3124-49cf-ae04-02c175eda549\",\n      \"description\": \"production\"\n    },\n    {\n      \"name\": \"PolProdStdDmz1\",\n      \"firewall_rules\": [\n        \"3178c9f6-f017-462b-b93f-715e11247c30\",\n        \"2b775a98-9813-48e0-8f32-a04dfc176872\",\n        \"a5a7e990-fbe4-429b-a55c-35df087b6f80\",\n        \"6ca67373-b89e-492d-94c6-1c40765800ce\",\n        \"bf93dda9-6f42-42cf-852f-689b6facf5b4\",\n        \"e3bd91ee-1337-4d73-9484-836a0fb5869b\"\n      ],\n      \"tenant_id\": \"3345a933109049779647ff02ca498f3a\",\n      \"audited\": false,\n      \"shared\": true,\n      \"id\": \"afc19c5c-d136-4dbf-b614-c0b784a4f68d\",\n      \"description\": \"\"\n    },\n    {\n      \"name\": \"ALL\",\n      \"firewall_rules\": [\n        \"43bfdc83-5f76-407d-b851-5803d4e23f0b\",\n        \"316965f2-4242-4c56-8e34-22f4ff1992a3\",\n        \"1fb6cbde-4446-4bef-9eac-cc6b76afc565\",\n        \"a3da3767-608d-493d-b15a-1793d66891c8\",\n        \"6f58413b-3667-41f6-93b4-eef813632aee\",\n        \"a28bdf75-894f-4af5-9063-e2fcee4cb01d\",\n        \"0ed005c7-2d89-43a1-8aaf-714d44858173\",\n        \"710e513c-df2b-4c78-8572-bd9701f5b108\",\n        \"016922c5-7810-41cb-ae2c-04bbd87b3b24\",\n        \"22d6ade0-0f0d-473a-9cec-4b5ba22db8e4\",\n        \"7ed0e62c-848d-4e4e-baa7-eea7e9c3c3ec\",\n        \"05a34244-0922-4a6d-b551-c95c500f2194\",\n        \"9d40ac55-0802-4590-aa89-8199dab7038f\",\n        \"3d1f3c70-44e1-4c6e-9253-53421976d707\",\n        \"4d22985f-ad50-459d-af00-eea902900e41\",\n        \"dd16596d-065d-4a3a-bb75-054ab7acf54f\",\n        \"33228008-6dba-4270-9c55-3d8752472795\",\n        \"46ea5a1c-8b4b-4eaf-b9c2-767efa8bc2ae\",\n        \"3b3c3136-d914-46ae-ace3-726f638ed1d5\",\n        \"2c3f8fce-3d05-405a-8249-1d3843b8a62d\",\n        \"23106a5d-556e-4e78-af13-1d0c9280b2e2\",\n        \"40e342d6-86fc-4205-b306-e9dcd816b958\",\n        \"bf290614-8ab0-487f-811f-4474a51a40d3\",\n        \"08b91c69-310d-4d55-bea1-ffe0d95e150b\",\n        \"8e9509ff-93cb-442d-92c6-1cfb79b9243c\",\n        \"019bd1b9-2f2b-4cfa-b645-6eb779d4622e\",\n        \"4f7fd6e2-7ac5-4a46-8e3d-c4dcdde8a3f0\",\n        \"4fd8fc8b-c449-457d-8526-6ba23f6f299d\",\n        \"e2a96758-70ba-499c-bd97-6d8ee55610ed\",\n        \"ade798f5-862a-442b-8168-f39a06030535\"\n      ],\n      \"tenant_id\": \"b6e174b62a964db7bf897a38b92fc217\",\n      \"audited\": false,\n      \"shared\": true,\n      \"id\": \"e0f918c2-7a10-45d1-a5f9-9b2a2026bf3e\",\n      \"description\": \"\"\n    },\n    {\n      \"name\": \"Pre-Prod\",\n      \"firewall_rules\": [\n        \"fd124f42-f064-4259-b840-1ca05203c6b7\",\n        \"f03bd950-6c56-4f5e-a307-45967078f507\"\n      ],\n      \"tenant_id\": \"80cf934d6ffb4ef5b244f1c512ad1e61\",\n      \"audited\": false,\n      \"shared\": true,\n      \"id\": \"e2a5fb51-698c-4898-87e8-f1eee6b50919\",\n      \"description\": \"\"\n    },\n    {\n      \"name\": \"ports VM ouverts\",\n      \"firewall_rules\": [\"c5535724-8ed8-4e50-933a-17e37b06994d\"],\n      \"tenant_id\": \"66165eac36f846099ab3f667f0c05229\",\n      \"audited\": false,\n      \"shared\": true,\n      \"id\": \"e5b8e392-1e70-4948-a6a4-b3726b528059\",\n      \"description\": \"ouverture de tous les ports du projet stagiaires\"\n    },\n    {\n      \"name\": \"www\",\n      \"firewall_rules\": [\n        \"75452b36-268e-4e75-aaf4-f0e7ed50bc97\",\n        \"c9e77ca0-1bc8-497d-904d-948107873dc6\",\n        \"67004fb6-9111-441f-a3c1-b94b08bbd496\",\n        \"80965cc0-2d60-48e8-8fe9-78be016f10b6\",\n        \"41c72886-f39d-450e-b4b5-818ebddf17d5\",\n        \"c854fab5-bdaf-4a86-9359-78de93e5df01\",\n        \"350288f9-4aea-4e13-b434-91141e5e5960\",\n        \"03d2a6ad-633f-431a-8463-4370d06a22c8\"\n      ],\n      \"tenant_id\": \"9145d91459d248b1b02fdaca97c6a75d\",\n      \"audited\": false,\n      \"shared\": true,\n      \"id\": \"f2b08c1e-aa81-4668-8ae1-1401bcb0576c\",\n      \"description\": \"\"\n    },\n    {\n      \"name\": \"fw-policy\",\n      \"firewall_rules\": [\n        \"32ea5280-b601-4531-903f-ddef6dd1b733\",\n        \"f6f39ac3-0bda-47ff-b8b9-f089a5440e19\",\n        \"dad47cfb-893f-4d7c-8e40-c7a86bcda175\",\n        \"1d089edc-ae35-4c60-b6af-79b69e2f3247\",\n        \"eac689d5-ce70-4d4a-bf43-5d1416ebb770\",\n        \"3c1318de-e095-4870-a2ec-3091fee81683\",\n        \"beb6249b-5e98-4c25-a356-d45f5b0cae29\",\n        \"b4b2362e-0d16-42ef-b8e4-9de56ca00c84\",\n        \"72c159d0-4777-4468-9136-543ba42d18f0\"\n      ],\n      \"tenant_id\": \"94eb5f2fd9ed471992e2c5c2313b0703\",\n      \"audited\": false,\n      \"shared\": true,\n      \"id\": \"f66e862e-9982-465e-a5af-79d61ca9c6eb\",\n      \"description\": \"\"\n    }\n  ]\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/firewall_rule_create_request.json",
    "content": "{\n  \"firewall_rule\": {\n    \"tenant_id\": \"3e00d5716204446c8d3c47a466eec25a\",\n    \"name\": \"jclouds-fw-rule_group-52-e8b_port-22\",\n    \"shared\": false,\n    \"protocol\": \"tcp\",\n    \"destination_ip_address\": \"192.168.0.117\",\n    \"destination_port\": \"22\",\n    \"action\": \"allow\",\n    \"enabled\": true\n  }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/firewall_rule_create_response.json",
    "content": "{\n  \"firewall_rule\": {\n    \"protocol\": \"tcp\",\n    \"description\": \"\",\n    \"source_port\": null,\n    \"source_ip_address\": null,\n    \"destination_ip_address\": \"192.168.0.117\",\n    \"firewall_policy_id\": null,\n    \"position\": null,\n    \"destination_port\": \"22\",\n    \"id\": \"59585143-e819-48c9-944d-f03e0f049dba\",\n    \"name\": \"jclouds-fw-rule_group-52-e8b_port-22\",\n    \"tenant_id\": \"3e00d5716204446c8d3c47a466eec25a\",\n    \"enabled\": true,\n    \"action\": \"allow\",\n    \"ip_version\": 4,\n    \"shared\": false\n  }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/firewall_rule_get_response.json",
    "content": "{\n  \"firewall_rule\": {\n    \"protocol\": \"tcp\",\n    \"description\": \"jclouds test fw rule\",\n    \"source_port\": null,\n    \"source_ip_address\": null,\n    \"destination_ip_address\": \"192.168.0.1\",\n    \"firewall_policy_id\": null,\n    \"position\": null,\n    \"destination_port\": \"22\",\n    \"id\": \"736b1686-3301-4a3d-9eaf-15e3c2682edc\",\n    \"name\": \"jclouds-test-org.jclouds.openstack.neutron.v2.extensions.fwaasapilivetest-fw-rule-22\",\n    \"tenant_id\": \"3e00d5716204446c8d3c47a466eec25a\",\n    \"enabled\": true,\n    \"action\": \"allow\",\n    \"ip_version\": 4,\n    \"shared\": false\n  }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/firewall_rule_update_request.json",
    "content": "{\n  \"firewall_rule\": {\n    \"shared\": false,\n    \"enabled\": false\n  }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/firewall_rule_update_response.json",
    "content": "{\n  \"firewall_rule\": {\n    \"protocol\": \"tcp\",\n    \"description\": \"jclouds test fw rule\",\n    \"source_port\": null,\n    \"source_ip_address\": null,\n    \"destination_ip_address\": \"192.168.0.1\",\n    \"firewall_policy_id\": null,\n    \"position\": null,\n    \"destination_port\": \"22\",\n    \"id\": \"736b1686-3301-4a3d-9eaf-15e3c2682edc\",\n    \"name\": \"jclouds-test-org.jclouds.openstack.neutron.v2.extensions.fwaasapilivetest-fw-rule-22-updated\",\n    \"tenant_id\": \"3e00d5716204446c8d3c47a466eec25a\",\n    \"enabled\": false,\n    \"action\": \"allow\",\n    \"ip_version\": 4,\n    \"shared\": false\n  }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/firewall_update_request.json",
    "content": "{\n  \"firewall\": {\n    \"admin_state_up\": false\n  }\n}"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/firewall_update_response.json",
    "content": "{\n  \"firewall\": {\n    \"admin_state_up\": false,\n    \"description\": \"\",\n    \"firewall_policy_id\": \"c69933c1-b472-44f9-8226-30dc4ffd454c\",\n    \"id\": \"3b0ef8f4-82c7-44d4-a4fb-6177f9a21977\",\n    \"name\": \"\",\n    \"status\": \"PENDING_UPDATE\",\n    \"tenant_id\": \"45977fa2dbd7482098dd68d0d8970117\"\n  }\n}"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/floatingip_create_request.json",
    "content": "{\n    \"floatingip\": {\n        \"floating_network_id\": \"376da547-b977-4cfe-9cba-275c80debf57\",\n        \"port_id\": \"ce705c24-c1ef-408a-bda3-7bbd946164ab\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/floatingip_create_response.json",
    "content": "{\n    \"floatingip\": {\n        \"router_id\": \"d23abc8d-2991-4a55-ba98-2aaea84cc72f\",\n        \"tenant_id\": \"4969c491a3c74ee4af974e6d800c62de\",\n        \"floating_network_id\": \"376da547-b977-4cfe-9cba-275c80debf57\",\n        \"fixed_ip_address\": \"10.0.0.3\",\n        \"floating_ip_address\": \"172.24.4.228\",\n        \"port_id\": \"ce705c24-c1ef-408a-bda3-7bbd946164ab\",\n        \"id\": \"2f245a7b-796b-4f26-9cf9-9e82d248fda7\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/floatingip_get_response.json",
    "content": "{\n    \"floatingip\": {\n        \"router_id\": \"d23abc8d-2991-4a55-ba98-2aaea84cc72f\",\n        \"tenant_id\": \"4969c491a3c74ee4af974e6d800c62de\",\n        \"floating_network_id\": \"376da547-b977-4cfe-9cba-275c80debf57\",\n        \"fixed_ip_address\": \"10.0.0.3\",\n        \"floating_ip_address\": \"172.24.4.228\",\n        \"port_id\": \"ce705c24-c1ef-408a-bda3-7bbd946164ab\",\n        \"id\": \"2f245a7b-796b-4f26-9cf9-9e82d248fda7\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/floatingip_list_response.json",
    "content": "{\n    \"floatingips\": [\n        {\n            \"router_id\": \"d23abc8d-2991-4a55-ba98-2aaea84cc72f\",\n            \"tenant_id\": \"4969c491a3c74ee4af974e6d800c62de\",\n            \"floating_network_id\": \"376da547-b977-4cfe-9cba-275c80debf57\",\n            \"fixed_ip_address\": \"10.0.0.3\",\n            \"floating_ip_address\": \"172.24.4.228\",\n            \"port_id\": \"ce705c24-c1ef-408a-bda3-7bbd946164ab\",\n            \"id\": \"2f245a7b-796b-4f26-9cf9-9e82d248fda7\"\n        },\n        {\n            \"router_id\": null,\n            \"tenant_id\": \"4969c491a3c74ee4af974e6d800c62de\",\n            \"floating_network_id\": \"376da547-b977-4cfe-9cba-275c80debf57\",\n            \"fixed_ip_address\": null,\n            \"floating_ip_address\": \"172.24.4.227\",\n            \"port_id\": null,\n            \"id\": \"61cea855-49cb-4846-997d-801b70c71bdd\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/floatingip_list_response_paged1.json",
    "content": "{\n    \"floatingips\": [\n        {\n            \"router_id\": \"d23abc8d-2991-4a55-ba98-2aaea84cc72f\",\n            \"tenant_id\": \"4969c491a3c74ee4af974e6d800c62de\",\n            \"floating_network_id\": \"376da547-b977-4cfe-9cba-275c80debf57\",\n            \"fixed_ip_address\": \"10.0.0.3\",\n            \"floating_ip_address\": \"172.24.4.228\",\n            \"port_id\": \"ce705c24-c1ef-408a-bda3-7bbd946164ab\",\n            \"id\": \"2f245a7b-796b-4f26-9cf9-9e82d248fda7\"\n        },\n        {\n            \"router_id\": null,\n            \"tenant_id\": \"4969c491a3c74ee4af974e6d800c62de\",\n            \"floating_network_id\": \"376da547-b977-4cfe-9cba-275c80debf57\",\n            \"fixed_ip_address\": null,\n            \"floating_ip_address\": \"172.24.4.227\",\n            \"port_id\": null,\n            \"id\": \"61cea855-49cb-4846-997d-801b70c71bdd\"\n        }\n    ],\n    \"floatingips_links\": [\n        {\n            \"href\": \"/v2.0/floatingips.json?marker=71c1e68c-171a-4aa2-aca5-50ea153a3718\",\n            \"rel\": \"next\"\n        },\n        {\n            \"href\": \"/v2.0/floatingips.json?marker=396f12f8-521e-4b91-8e21-2e003500433a&page_reverse=True\",\n            \"rel\": \"previous\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/floatingip_list_response_paged2.json",
    "content": "{\n    \"floatingips\": [\n        {\n            \"router_id\": \"d23abc8d-2991-4a55-ba98-2aaea84cc72f2\",\n            \"tenant_id\": \"4969c491a3c74ee4af974e6d800c62de2\",\n            \"floating_network_id\": \"376da547-b977-4cfe-9cba-275c80debf572\",\n            \"fixed_ip_address\": \"10.0.0.3\",\n            \"floating_ip_address\": \"172.24.4.228\",\n            \"port_id\": \"ce705c24-c1ef-408a-bda3-7bbd946164ab2\",\n            \"id\": \"2f245a7b-796b-4f26-9cf9-9e82d248fda72\"\n        },\n        {\n            \"router_id\": null,\n            \"tenant_id\": \"4969c491a3c74ee4af974e6d800c62de2\",\n            \"floating_network_id\": \"376da547-b977-4cfe-9cba-275c80debf572\",\n            \"fixed_ip_address\": null,\n            \"floating_ip_address\": \"172.24.4.227\",\n            \"port_id\": null,\n            \"id\": \"61cea855-49cb-4846-997d-801b70c71bdd2\"\n        }\n    ],\n    \"floatingips_links\": [\n        {\n            \"href\": \"/v2.0/floatingips.json?marker=396f12f8-521e-4b91-8e21-2e003500433a&page_reverse=True\",\n            \"rel\": \"previous\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/floatingip_update_dissociate_request.json",
    "content": "{\n    \"floatingip\": {\n\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/floatingip_update_dissociate_response.json",
    "content": "{\n    \"floatingip\": {\n        \"router_id\": \"d23abc8d-2991-4a55-ba98-2aaea84cc72f\",\n        \"tenant_id\": \"4969c491a3c74ee4af974e6d800c62de\",\n        \"floating_network_id\": \"376da547-b977-4cfe-9cba-275c80debf57\",\n        \"fixed_ip_address\": null,\n        \"floating_ip_address\": \"172.24.4.228\",\n        \"port_id\": null,\n        \"id\": \"2f245a7b-796b-4f26-9cf9-9e82d248fda7\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/floatingip_update_request.json",
    "content": "{\n    \"floatingip\": {\n        \"port_id\": \"fc861431-0e6c-4842-a0ed-e2363f9bc3a8\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/floatingip_update_response.json",
    "content": "{\n    \"floatingip\": {\n        \"router_id\": \"d23abc8d-2991-4a55-ba98-2aaea84cc72f\",\n        \"tenant_id\": \"4969c491a3c74ee4af974e6d800c62de\",\n        \"floating_network_id\": \"376da547-b977-4cfe-9cba-275c80debf57\",\n        \"fixed_ip_address\": \"10.0.0.4\",\n        \"floating_ip_address\": \"172.24.4.228\",\n        \"port_id\": \"fc861431-0e6c-4842-a0ed-e2363f9bc3a8\",\n        \"id\": \"2f245a7b-796b-4f26-9cf9-9e82d248fda7\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/lbaas/v1/health_monitor_create_request.json",
    "content": "{\n    \"health_monitor\": {\n        \"delay\": 1,\n        \"max_retries\": 1,\n        \"type\": \"HTTP\",\n        \"timeout\": 1\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/lbaas/v1/health_monitor_create_response.json",
    "content": "{\n    \"health_monitor\": {\n        \"status\": \"PENDING_CREATE\",\n        \"admin_state_up\": true,\n        \"tenant_id\": \"4fd44f30292945e481c7b8a0c8908869\",\n        \"delay\": 1,\n        \"expected_codes\": \"200\",\n        \"max_retries\": 1,\n        \"http_method\": \"GET\",\n        \"timeout\": 1,\n        \"pools\": [],\n        \"url_path\": \"/\",\n        \"type\": \"HTTP\",\n        \"id\": \"b624decf-d5d3-4c66-9a3d-f047e7786181\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/lbaas/v1/health_monitor_get_response.json",
    "content": "{\n    \"health_monitor\": {\n        \"status\": \"ACTIVE\",\n        \"admin_state_up\": true,\n        \"tenant_id\": \"4fd44f30292945e481c7b8a0c8908869\",\n        \"delay\": 5,\n        \"expected_codes\": \"200\",\n        \"max_retries\": 2,\n        \"http_method\": \"GET\",\n        \"timeout\": 2,\n        \"url_path\": \"/\",\n        \"type\": \"HTTP\",\n        \"pools\": [],\n        \"id\": \"5d4b5228-33b0-4e60-b225-9b727c1a20e7\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/lbaas/v1/health_monitor_list_response_paged1.json",
    "content": "{\n    \"health_monitors\": [\n        {\n            \"status\": \"ACTIVE\",\n            \"admin_state_up\": true,\n            \"tenant_id\": \"4fd44f30292945e481c7b8a0c8908869\",\n            \"delay\": 10,\n            \"max_retries\": 1,\n            \"timeout\": 1,\n            \"type\": \"PING\",\n            \"id\": \"466c8345-28d8-4f84-a246-e04380b0461d\"\n        }\n    ],\n    \"health_monitors_links\": [\n        {\n            \"href\": \"/v2.0/lb/health_monitors.json?marker=396f12f8-521e-4b91-8e21-2e003500433a\",\n            \"rel\": \"next\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/lbaas/v1/health_monitor_list_response_paged2.json",
    "content": "{\n    \"health_monitors\": [\n        {\n            \"status\": \"ACTIVE\",\n            \"admin_state_up\": true,\n            \"tenant_id\": \"4fd44f30292945e481c7b8a0c8908869\",\n            \"delay\": 5,\n            \"expected_codes\": \"200\",\n            \"max_retries\": 2,\n            \"http_method\": \"GET\",\n            \"timeout\": 2,\n            \"url_path\": \"/\",\n            \"type\": \"HTTP\",\n            \"id\": \"5d4b5228-33b0-4e60-b225-9b727c1a20e7\"\n        }\n    ],\n    \"health_monitors_links\": [\n        {\n            \"href\": \"/v2.0/lb/health_monitors.json?marker=396f12f8-521e-4b91-8e21-2e003500433a\",\n            \"rel\": \"previous\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/lbaas/v1/health_monitor_update_request.json",
    "content": "{\n    \"health_monitor\": {\n        \"delay\": 1,\n        \"max_retries\": 1,\n        \"timeout\": 1,\n        \"http_method\": \"HEAD\",\n        \"url_path\": \"/index.html\",\n        \"expected_codes\": \"201\",\n        \"admin_state_up\": false\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/lbaas/v1/health_monitor_update_response.json",
    "content": "{\n    \"health_monitor\": {\n        \"status\": \"ACTIVE\",\n        \"admin_state_up\": false,\n        \"tenant_id\": \"4fd44f30292945e481c7b8a0c8908869\",\n        \"delay\": 1,\n        \"expected_codes\": \"201\",\n        \"max_retries\": 1,\n        \"http_method\": \"HEAD\",\n        \"timeout\": 1,\n        \"pools\": [],\n        \"url_path\": \"/index.html\",\n        \"type\": \"HTTP\",\n        \"id\": \"466c8345-28d8-4f84-a246-e04380b0461d\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/lbaas/v1/member_create_request.json",
    "content": "{\n    \"member\": {\n        \"protocol_port\": 80,\n        \"pool_id\": \"72741b06-df4d-4715-b142-276b6bce75ab\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/lbaas/v1/member_create_response.json",
    "content": "{\n    \"member\": {\n        \"status\": \"PENDING_CREATE\",\n        \"protocol_port\": 80,\n        \"weight\": 1,\n        \"admin_state_up\": true,\n        \"tenant_id\": \"83657cfcdfe44cd5920adaf26c48ceea\",\n        \"pool_id\": \"72741b06-df4d-4715-b142-276b6bce75ab\",\n        \"address\": \"10.0.0.5\",\n        \"id\":\"48a471ea-64f1-4eb6-9be7-dae6bbe40a0f\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/lbaas/v1/member_get_response.json",
    "content": "{\n    \"member\": {\n        \"status\": \"ACTIVE\",\n        \"protocol_port\": 80,\n        \"weight\": 1,\n        \"admin_state_up\": true,\n        \"tenant_id\": \"83657cfcdfe44cd5920adaf26c48ceea\",\n        \"pool_id\": \"72741b06-df4d-4715-b142-276b6bce75ab\",\n        \"address\": \"10.0.0.5\",\n        \"id\":\"48a471ea-64f1-4eb6-9be7-dae6bbe40a0f\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/lbaas/v1/member_list_response_paged1.json",
    "content": "{\n    \"members\": [\n        {\n            \"status\": \"ACTIVE\",\n            \"protocol_port\": 80,\n            \"weight\": 1,\n            \"admin_state_up\": true,\n            \"tenant_id\": \"83657cfcdfe44cd5920adaf26c48ceea\",\n            \"pool_id\": \"72741b06-df4d-4715-b142-276b6bce75ab\",\n            \"address\": \"10.0.0.5\",\n            \"id\":\"48a471ea-64f1-4eb6-9be7-dae6bbe40a0f\"\n        }\n    ],\n    \"members_links\": [\n        {\n            \"href\": \"/v2.0/lb/members.json?marker=396f12f8-521e-4b91-8e21-2e003500433a\",\n            \"rel\": \"next\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/lbaas/v1/member_list_response_paged2.json",
    "content": "{\n    \"members\": [\n        {\n            \"status\": \"ACTIVE\",\n            \"protocol_port\": 80,\n            \"weight\": 1,\n            \"admin_state_up\": true,\n            \"tenant_id\": \"83657cfcdfe44cd5920adaf26c48ceea\",\n            \"pool_id\": \"72741b06-df4d-4715-b142-276b6bce75ab\",\n            \"address\": \"10.0.0.5\",\n            \"id\":\"701b531b-111a-4f21-ad85-4795b7b12af6\"\n        }\n    ],\n    \"members_links\": [\n        {\n            \"href\": \"/v2.0/lb/members.json?marker=86ae12f8-521e-4b91-8e21-2e0035005fdc\",\n            \"rel\": \"previous\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/lbaas/v1/member_update_request.json",
    "content": "{\n    \"member\": {\n        \"weight\": 2,\n        \"admin_state_up\": false,\n        \"pool_id\": \"new_pool_id\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/lbaas/v1/member_update_response.json",
    "content": "{\n    \"member\": {\n        \"status\": \"ACTIVE\",\n        \"protocol_port\": 80,\n        \"weight\": 2,\n        \"admin_state_up\": false,\n        \"tenant_id\": \"83657cfcdfe44cd5920adaf26c48ceea\",\n        \"pool_id\": \"new_pool_id\",\n        \"address\": \"10.0.0.5\",\n        \"id\":\"48a471ea-64f1-4eb6-9be7-dae6bbe40a0f\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/lbaas/v1/pool_associate_health_monitor_request.json",
    "content": "{\n    \"health_monitor\": {\n        \"id\":\"5d4b5228-33b0-4e60-b225-9b727c1a20e7\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/lbaas/v1/pool_associate_health_monitor_response.json",
    "content": "{\n    \"health_monitor\": {\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/lbaas/v1/pool_create_request.json",
    "content": "{\n    \"pool\": {\n        \"subnet_id\":\"8032909d-47a1-4715-90af-5153ffe39861\",\n        \"lb_method\":\"ROUND_ROBIN\",\n        \"protocol\":\"TCP\",\n        \"name\":\"NewPool\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/lbaas/v1/pool_create_response.json",
    "content": "{\n    \"pool\": {\n        \"status\": \"PENDING_CREATE\",\n        \"lb_method\": \"ROUND_ROBIN\",\n        \"protocol\": \"TCP\",\n        \"provider\": \"HAPROXY\",\n        \"description\": \"\",\n        \"health_monitors\": [],\n        \"health_monitors_status\": [],\n        \"subnet_id\": \"8032909d-47a1-4715-90af-5153ffe39861\",\n        \"tenant_id\": \"83657cfcdfe44cd5920adaf26c48ceea\",\n        \"admin_state_up\": true,\n        \"name\": \"NewPool\",\n        \"members\": [],\n        \"id\": \"a224402b-794b-4c0c-9d08-d95640a6f5a1\",\n        \"vip_id\": null\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/lbaas/v1/pool_get_response.json",
    "content": "{\n    \"pool\": {\n        \"status\": \"ACTIVE\",\n        \"lb_method\": \"ROUND_ROBIN\",\n        \"protocol\": \"HTTP\",\n        \"provider\": \"HAPROXY\",\n        \"description\": \"\",\n        \"health_monitors\": [\n            \"466c8345-28d8-4f84-a246-e04380b0461d\",\n            \"5d4b5228-33b0-4e60-b225-9b727c1a20e7\"\n        ],\n        \"health_monitors_status\": [\n            {\n                \"status\": \"ACTIVE\",\n                \"monitor_id\": \"466c8345-28d8-4f84-a246-e04380b0461d\",\n                \"status_dezcription\": null\n            },\n            {\n                \"status\": \"ACTIVE\",\n                \"monitor_id\": \"5d4b5228-33b0-4e60-b225-9b727c1a20e7\",\n                \"status_dezcription\": null\n            }\n        ],\n        \"subnet_id\": \"8032909d-47a1-4715-90af-5153ffe39861\",\n        \"tenant_id\": \"83657cfcdfe44cd5920adaf26c48ceea\",\n        \"admin_state_up\": true,\n        \"name\": \"app_pool\",\n        \"members\": [\n            \"701b531b-111a-4f21-ad85-4795b7b12af6\",\n            \"beb53b4d-230b-4abd-8118-575b8fa006ef\"\n        ],\n        \"id\": \"72741b06-df4d-4715-b142-276b6bce75ab\",\n        \"vip_id\": \"4ec89087-d057-4e2c-911f-60a3b47ee304\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/lbaas/v1/pool_list_response_paged1.json",
    "content": "{\n    \"pools\": [\n        {\n            \"status\": \"ACTIVE\",\n            \"lb_method\": \"ROUND_ROBIN\",\n            \"protocol\": \"HTTP\",\n            \"description\": \"\",\n            \"health_monitors\": [\n                \"466c8345-28d8-4f84-a246-e04380b0461d\",\n                \"5d4b5228-33b0-4e60-b225-9b727c1a20e7\"\n            ],\n            \"health_monitors_status\": [\n                {\n                    \"status\": \"ACTIVE\",\n                    \"monitor_id\": \"466c8345-28d8-4f84-a246-e04380b0461d\",\n                    \"status_dezcription\": null\n                },\n                {\n                    \"status\": \"ACTIVE\",\n                    \"monitor_id\": \"5d4b5228-33b0-4e60-b225-9b727c1a20e7\",\n                    \"status_dezcription\": null\n                }\n            ],\n            \"subnet_id\": \"8032909d-47a1-4715-90af-5153ffe39861\",\n            \"tenant_id\": \"83657cfcdfe44cd5920adaf26c48ceea\",\n            \"admin_state_up\": true,\n            \"name\": \"app_pool\",\n            \"members\": [\n                \"701b531b-111a-4f21-ad85-4795b7b12af6\",\n                \"beb53b4d-230b-4abd-8118-575b8fa006ef\"\n            ],\n            \"id\":\"72741b06-df4d-4715-b142-276b6bce75ab\",\n            \"vip_id\":\"4ec89087-d057-4e2c-911f-60a3b47ee304\"\n        }\n    ],\n    \"pools_links\": [\n        {\n            \"href\": \"/v2.0/lb/pools.json?marker=71c1e68c-171a-4aa2-aca5-50ea153a3718\",\n            \"rel\": \"next\"\n        },\n        {\n            \"href\": \"/v2.0/lb/pools.json?marker=396f12f8-521e-4b91-8e21-2e003500433a&page_reverse=True\",\n            \"rel\": \"previous\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/lbaas/v1/pool_list_response_paged2.json",
    "content": "{\n    \"pools\": [\n        {\n            \"status\": \"ACTIVE\",\n            \"lb_method\": \"ROUND_ROBIN\",\n            \"protocol\": \"TCP\",\n            \"description\": \"\",\n            \"health_monitors\": [\n                \"466c8345-28d8-4f84-a246-e04380b0461d\",\n                \"5d4b5228-33b0-4e60-b225-9b727c1a20e7\"\n            ],\n            \"health_monitors_status\": [\n                {\n                    \"status\": \"ACTIVE\",\n                    \"monitor_id\": \"466c8345-28d8-4f84-a246-e04380b0461d\",\n                    \"status_dezcription\": null\n                },\n                {\n                    \"status\": \"ACTIVE\",\n                    \"monitor_id\": \"5d4b5228-33b0-4e60-b225-9b727c1a20e7\",\n                    \"status_dezcription\": null\n                }\n            ],\n            \"subnet_id\": \"8032909d-47a1-4715-90af-5153ffe39861\",\n            \"tenant_id\": \"83657cfcdfe44cd5920adaf26c48ceea\",\n            \"admin_state_up\": true,\n            \"name\": \"app_pool2\",\n            \"members\": [\n                \"701b531b-111a-4f21-ad85-4795b7b12af6\",\n                \"beb53b4d-230b-4abd-8118-575b8fa006ef\"\n            ],\n            \"id\":\"72741b06-df4d-4715-b142-276b6bce75ab_2\",\n            \"vip_id\":\"4ec89087-d057-4e2c-911f-60a3b47ee304\"\n        }\n    ],\n    \"pools_links\": [\n        {\n            \"href\": \"/v2.0/lb/pools.json?marker=396f12f8-521e-4b91-8e21-2e003500433a&page_reverse=True\",\n            \"rel\": \"previous\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/lbaas/v1/pool_update_request.json",
    "content": "{\n    \"pool\": {\n        \"name\": \"new_name\",\n        \"description\": \"new description\",\n        \"lb_method\": \"NEW_LB_METHOD\",\n        \"health_monitors\": [\n            \"5d4b5228-33b0-4e60-b225-9b727c1a20e7\"\n        ],\n        \"admin_state_up\": false\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/lbaas/v1/pool_update_response.json",
    "content": "{\n    \"pool\": {\n        \"status\": \"ACTIVE\",\n        \"lb_method\":\"NEW_LB_METHOD\",\n        \"protocol\": \"HTTP\",\n        \"provider\": \"HAPROXY\",\n        \"description\": \"new description\",\n        \"health_monitors\": [\n            \"5d4b5228-33b0-4e60-b225-9b727c1a20e7\"\n        ],\n        \"health_monitors_status\": [\n            {\n                \"status\": \"ACTIVE\",\n                \"monitor_id\": \"5d4b5228-33b0-4e60-b225-9b727c1a20e7\",\n                \"status_dezcription\": null\n            }\n        ],\n        \"subnet_id\": \"8032909d-47a1-4715-90af-5153ffe39861\",\n        \"tenant_id\": \"83657cfcdfe44cd5920adaf26c48ceea\",\n        \"admin_state_up\": false,\n        \"name\": \"new_name\",\n        \"members\": [\n            \"701b531b-111a-4f21-ad85-4795b7b12af6\",\n            \"beb53b4d-230b-4abd-8118-575b8fa006ef\"\n        ],\n        \"id\": \"72741b06-df4d-4715-b142-276b6bce75ab\",\n        \"vip_id\": \"4ec89087-d057-4e2c-911f-60a3b47ee304\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/lbaas/v1/vip_create_request.json",
    "content": "{\n    \"vip\": {\n        \"protocol\": \"HTTP\",\n        \"name\": \"NewVip\",\n        \"subnet_id\": \"8032909d-47a1-4715-90af-5153ffe39861\",\n        \"pool_id\": \"61b1f87a-7a21-4ad3-9dda-7f81d249944f\",\n        \"protocol_port\":80\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/lbaas/v1/vip_create_response.json",
    "content": "{\n    \"vip\": {\n        \"status\": \"PENDING_CREATE\",\n        \"protocol\": \"HTTP\",\n        \"description\": \"\",\n        \"admin_state_up\": true,\n        \"subnet_id\": \"8032909d-47a1-4715-90af-5153ffe39861\",\n        \"tenant_id\": \"83657cfcdfe44cd5920adaf26c48ceea\",\n        \"connection_limit\": -1,\n        \"pool_id\": \"61b1f87a-7a21-4ad3-9dda-7f81d249944f\",\n        \"address\": \"10.0.0.11\",\n        \"protocol_port\": 80,\n        \"port_id\": \"f7e6fe6a-b8b5-43a8-8215-73456b32e0f5\",\n        \"id\": \"c987d2be-9a3c-4ac9-a046-e8716b1350e2\",\n        \"name\": \"NewVip\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/lbaas/v1/vip_get_response.json",
    "content": "{\n    \"vip\": {\n        \"status\": \"ACTIVE\",\n        \"protocol\": \"HTTP\",\n        \"description\": \"\",\n        \"admin_state_up\": true,\n        \"subnet_id\": \"8032909d-47a1-4715-90af-5153ffe39861\",\n        \"tenant_id\": \"83657cfcdfe44cd5920adaf26c48ceea\",\n        \"connection_limit\": 1000,\n        \"pool_id\": \"72741b06-df4d-4715-b142-276b6bce75ab\",\n        \"session_persistence\": {\n            \"cookie_name\": \"MyAppCookie\",\n            \"type\": \"APP_COOKIE\"\n        },\n        \"address\": \"10.0.0.10\",\n        \"protocol_port\": 80,\n        \"port_id\": \"b5a743d6-056b-468b-862d-fb13a9aa694e\",\n        \"id\": \"4ec89087-d057-4e2c-911f-60a3b47ee304\",\n        \"name\": \"my-vip\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/lbaas/v1/vip_list_response_paged1.json",
    "content": "{\n    \"vips\": [\n        {\n            \"status\": \"ACTIVE\",\n            \"protocol\": \"HTTP\",\n            \"description\": \"\",\n            \"admin_state_up\": true,\n            \"subnet_id\": \"8032909d-47a1-4715-90af-5153ffe39861\",\n            \"tenant_id\": \"83657cfcdfe44cd5920adaf26c48ceea\",\n            \"connection_limit\": 1000,\n            \"pool_id\": \"72741b06-df4d-4715-b142-276b6bce75ab\",\n            \"session_persistence\": {\n                \"cookie_name\": \"MyAppCookie\",\n                \"type\": \"APP_COOKIE\"\n            },\n            \"address\": \"10.0.0.10\",\n            \"protocol_port\": 80,\n            \"port_id\": \"b5a743d6-056b-468b-862d-fb13a9aa694e\",\n            \"id\": \"4ec89087-d057-4e2c-911f-60a3b47ee304\",\n            \"name\": \"my-vip1\"\n        }\n    ],\n    \"vips_links\": [\n        {\n            \"href\": \"/v2.0/lb/vips.json?marker=396f12f8-521e-4b91-8e21-2e003500433a\",\n            \"rel\": \"next\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/lbaas/v1/vip_list_response_paged2.json",
    "content": "{\n    \"vips\": [\n        {\n            \"status\": \"ACTIVE\",\n            \"protocol\": \"HTTPS\",\n            \"description\": \"\",\n            \"admin_state_up\": true,\n            \"subnet_id\": \"8032909d-47a1-4715-90af-5153ffe39861\",\n            \"tenant_id\": \"83657cfcdfe44cd5920adaf26c48ceea\",\n            \"connection_limit\": 100,\n            \"pool_id\": \"61b1f87a-7a21-4ad3-9dda-7f81d249944f\",\n            \"session_persistence\": {\n                \"cookie_name\": null,\n                \"type\": \"HTTP_COOKIE\"\n            },\n            \"address\": \"10.0.0.11\",\n            \"protocol_port\": 80,\n            \"port_id\": \"f7e6fe6a-b8b5-43a8-8215-73456b32e0f5\",\n            \"id\": \"c987d2be-9a3c-4ac9-a046-e8716b1350e2\",\n            \"name\": \"my-vip2\"\n        }\n    ],\n    \"vips_links\": [\n        {\n            \"href\": \"/v2.0/lb/vips.json?marker=ABCDEFf8-521e-4b91-8e21-2e003500433a\",\n            \"rel\": \"previous\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/lbaas/v1/vip_update_request.json",
    "content": "{\n    \"vip\": {\n        \"name\": \"new-name\",\n        \"description\": \"new description\",\n        \"pool_id\": \"61b1f87a-7a21-4ad3-9dda-7f81d249944f\",\n        \"session_persistence\": {\n            \"cookie_name\": \"MyNewAppCookie\",\n            \"type\": \"APP_COOKIE\"\n        },\n        \"connection_limit\": 50,\n        \"admin_state_up\": false\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/lbaas/v1/vip_update_response.json",
    "content": "{\n    \"vip\": {\n        \"status\": \"PENDING_UPDATE\",\n        \"protocol\": \"HTTP\",\n        \"description\": \"new description\",\n        \"admin_state_up\": false,\n        \"subnet_id\": \"8032909d-47a1-4715-90af-5153ffe39861\",\n        \"tenant_id\": \"83657cfcdfe44cd5920adaf26c48ceea\",\n        \"connection_limit\": 50,\n        \"pool_id\": \"61b1f87a-7a21-4ad3-9dda-7f81d249944f\",\n        \"session_persistence\": {\n            \"cookie_name\": \"MyNewAppCookie\",\n            \"type\": \"APP_COOKIE\"\n        },\n        \"address\": \"10.0.0.11\",\n        \"protocol_port\": 80,\n        \"port_id\": \"f7e6fe6a-b8b5-43a8-8215-73456b32e0f5\",\n        \"id\": \"c987d2be-9a3c-4ac9-a046-e8716b1350e2\",\n        \"name\": \"new-name\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/list_networks.json",
    "content": "{\"networks\": [\n    {\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"16dba3bc-f3fa-4775-afdc-237e12c72f6a\"\n    },\n    {\n        \"name\": \"wibble\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"1a104cf5-cb18-4d35-9407-2fd2646d9d0b\"\n    },\n    {\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"31083ae2-420d-48b2-ac98-9f7a4fd8dbdc\"\n    },\n    {\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"49c6d6fa-ff2a-459d-b975-75a8d31c9a89\"\n    },\n    {\n        \"name\": \"wibble\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"5cb3d6f4-62cb-41c9-b964-ba7d9df79e4e\"\n    },\n    {\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"5d51d012-3491-4db7-b1b5-6f254015015d\"\n    },\n    {\n        \"name\": \"wibble\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"5f9cf7dc-22ca-4097-8e49-1cc8b23faf17\"\n    },\n    {\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"6319ecad-6bff-48b2-9b53-02ede8cb7588\"\n    },\n    {\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"6ba4c788-661f-49ab-9bf8-5f10cbbb2f57\"\n    },\n    {\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"74ed170b-5069-4353-ab38-9719766dc57e\"\n    },\n    {\n        \"name\": \"wibble\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"b71fcac1-e864-4031-8c5b-edbecd9ece36\"\n    },\n    {\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"c7681895-d84d-4650-9ca0-82c72036b855\"\n    }\n]}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/list_ports.json",
    "content": "{\"ports\": [\n    {\n        \"status\": \"ACTIVE\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"16dba3bc-f3fa-4775-afdc-237e12c72f6a\"\n    },\n    {\n        \"status\": \"ACTIVE\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"wibble\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"1a104cf5-cb18-4d35-9407-2fd2646d9d0b\"\n    },\n    {\n        \"status\": \"ACTIVE\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"31083ae2-420d-48b2-ac98-9f7a4fd8dbdc\"\n    },\n    {\n        \"status\": \"ACTIVE\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"49c6d6fa-ff2a-459d-b975-75a8d31c9a89\"\n    },\n    {\n        \"status\": \"ACTIVE\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"wibble\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"5cb3d6f4-62cb-41c9-b964-ba7d9df79e4e\"\n    },\n    {\n        \"status\": \"ACTIVE\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"5d51d012-3491-4db7-b1b5-6f254015015d\"\n    },\n    {\n        \"status\": \"ACTIVE\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"wibble\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"5f9cf7dc-22ca-4097-8e49-1cc8b23faf17\"\n    },\n    {\n        \"status\": \"ACTIVE\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"6319ecad-6bff-48b2-9b53-02ede8cb7588\"\n    },\n    {\n        \"status\": \"ACTIVE\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"6ba4c788-661f-49ab-9bf8-5f10cbbb2f57\"\n    },\n    {\n        \"status\": \"ACTIVE\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"74ed170b-5069-4353-ab38-9719766dc57e\"\n    },\n    {\n        \"status\": \"ACTIVE\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"wibble\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"b71fcac1-e864-4031-8c5b-edbecd9ece36\"\n    },\n    {\n        \"status\": \"ACTIVE\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"c7681895-d84d-4650-9ca0-82c72036b855\"\n    }\n]}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/list_routers.json",
    "content": "{\"routers\": [\n    {\n        \"status\": \"ACTIVE\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"16dba3bc-f3fa-4775-afdc-237e12c72f6a\"\n    },\n    {\n        \"status\": \"ACTIVE\",\n        \"name\": \"wibble\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"1a104cf5-cb18-4d35-9407-2fd2646d9d0b\"\n    },\n    {\n        \"status\": \"ACTIVE\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"31083ae2-420d-48b2-ac98-9f7a4fd8dbdc\"\n    },\n    {\n        \"status\": \"ACTIVE\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"49c6d6fa-ff2a-459d-b975-75a8d31c9a89\"\n    },\n    {\n        \"status\": \"ACTIVE\",\n        \"name\": \"wibble\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"5cb3d6f4-62cb-41c9-b964-ba7d9df79e4e\"\n    },\n    {\n        \"status\": \"ACTIVE\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"5d51d012-3491-4db7-b1b5-6f254015015d\"\n    },\n    {\n        \"status\": \"ACTIVE\",\n        \"name\": \"wibble\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"5f9cf7dc-22ca-4097-8e49-1cc8b23faf17\"\n    },\n    {\n        \"status\": \"ACTIVE\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"6319ecad-6bff-48b2-9b53-02ede8cb7588\"\n    },\n    {\n        \"status\": \"ACTIVE\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"6ba4c788-661f-49ab-9bf8-5f10cbbb2f57\"\n    },\n    {\n        \"status\": \"ACTIVE\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"74ed170b-5069-4353-ab38-9719766dc57e\"\n    },\n    {\n        \"status\": \"ACTIVE\",\n        \"name\": \"wibble\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"b71fcac1-e864-4031-8c5b-edbecd9ece36\"\n    },\n    {\n        \"status\": \"ACTIVE\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"c7681895-d84d-4650-9ca0-82c72036b855\"\n    }\n]}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/list_subnets.json",
    "content": "{\"subnets\": [\n    {\n        \"ip_version\": 4,\n        \"cidr\": \"10.0.3.0/24\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"16dba3bc-f3fa-4775-afdc-237e12c72f6a\"\n    },\n    {\n        \"ip_version\": 4,\n        \"cidr\": \"10.0.3.0/24\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"wibble\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"1a104cf5-cb18-4d35-9407-2fd2646d9d0b\"\n    },\n    {\n        \"ip_version\": 4,\n        \"cidr\": \"10.0.3.0/24\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"31083ae2-420d-48b2-ac98-9f7a4fd8dbdc\"\n    },\n    {\n        \"ip_version\": 4,\n        \"cidr\": \"10.0.3.0/24\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"49c6d6fa-ff2a-459d-b975-75a8d31c9a89\"\n    },\n    {\n        \"ip_version\": 4,\n        \"cidr\": \"10.0.3.0/24\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"wibble\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"5cb3d6f4-62cb-41c9-b964-ba7d9df79e4e\"\n    },\n    {\n        \"ip_version\": 4,\n        \"cidr\": \"10.0.3.0/24\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"5d51d012-3491-4db7-b1b5-6f254015015d\"\n    },\n    {\n        \"ip_version\": 4,\n        \"cidr\": \"10.0.3.0/24\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"wibble\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"5f9cf7dc-22ca-4097-8e49-1cc8b23faf17\"\n    },\n    {\n        \"ip_version\": 4,\n        \"cidr\": \"10.0.3.0/24\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"6319ecad-6bff-48b2-9b53-02ede8cb7588\"\n    },\n    {\n        \"ip_version\": 4,\n        \"cidr\": \"10.0.3.0/24\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"6ba4c788-661f-49ab-9bf8-5f10cbbb2f57\"\n    },\n    {\n        \"ip_version\": 4,\n        \"cidr\": \"10.0.3.0/24\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"74ed170b-5069-4353-ab38-9719766dc57e\"\n    },\n    {\n        \"ip_version\": 4,\n        \"cidr\": \"10.0.3.0/24\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"wibble\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"b71fcac1-e864-4031-8c5b-edbecd9ece36\"\n    },\n    {\n        \"ip_version\": 4,\n        \"cidr\": \"10.0.3.0/24\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"c7681895-d84d-4650-9ca0-82c72036b855\"\n    }\n]}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/logback.xml",
    "content": "<?xml version=\"1.0\"?>\n<configuration scan=\"false\">\n    <appender name=\"FILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds.log</file>\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n    <appender name=\"WIREFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds-wire.log</file>\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n    <appender name=\"COMPUTEFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds-compute.log</file>\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <logger name=\"org.jclouds\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"FILE\" />\n    </logger>\n    <logger name=\"jclouds.compute\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"COMPUTEFILE\" />\n    </logger>\n    <logger name=\"jclouds.wire\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n    <logger name=\"jclouds.headers\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n\n    <root>\n        <level value=\"INFO\" />\n    </root>\n</configuration>"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/network.json",
    "content": "{\"network\": {\n    \"provider:network_type\": \"local\",\n    \"status\": \"ACTIVE\",\n    \"name\": \"jclouds-wibble\",\n    \"tenant_id\": \"1234567890\",\n    \"id\": \"624312ff-d14b-4ba3-9834-1c78d23d574d\"\n}}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/network_bulk_create_request.json",
    "content": "{\n    \"networks\": [\n        {\n            \"provider:network_type\": \"local\",\n            \"name\": \"jclouds-wibble\"\n        },\n        {\n            \"provider:network_type\": \"local\",\n            \"name\": \"jclouds-wibble2\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/network_bulk_create_response.json",
    "content": "{\n    \"networks\": [\n        {\n            \"provider:network_type\": \"local\",\n            \"status\": \"ACTIVE\",\n            \"name\": \"jclouds-wibble\",\n            \"tenant_id\": \"1234567890\",\n            \"id\": \"624312ff-d14b-4ba3-9834-1c78d23d574d\"\n        },\n        {\n            \"provider:network_type\": \"local\",\n            \"status\": \"ACTIVE\",\n            \"name\": \"jclouds-wibble2\",\n            \"tenant_id\": \"1234567890\",\n            \"id\": \"624312ff-d14b-4ba3-9834-1c78d23d574e\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/network_create_request.json",
    "content": "{\"network\": {\n    \"provider:network_type\": \"local\",\n    \"name\": \"jclouds-wibble\"\n}}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/network_create_response.json",
    "content": "{\"network\": {\n    \"provider:network_type\": \"local\",\n    \"status\": \"ACTIVE\",\n    \"name\": \"jclouds-wibble\",\n    \"tenant_id\": \"1234567890\",\n    \"id\": \"624312ff-d14b-4ba3-9834-1c78d23d574d\"\n}}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/network_get_response.json",
    "content": "{\"network\": {\n    \"provider:network_type\": \"local\",\n    \"status\": \"ACTIVE\",\n    \"name\": \"jclouds-wibble\",\n    \"tenant_id\": \"1234567890\",\n    \"id\": \"624312ff-d14b-4ba3-9834-1c78d23d574d\"\n}}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/network_list_response.json",
    "content": "{\"networks\": [\n    {\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"16dba3bc-f3fa-4775-afdc-237e12c72f6a\"\n    },\n    {\n        \"name\": \"wibble\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"1a104cf5-cb18-4d35-9407-2fd2646d9d0b\"\n    },\n    {\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"31083ae2-420d-48b2-ac98-9f7a4fd8dbdc\"\n    },\n    {\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"49c6d6fa-ff2a-459d-b975-75a8d31c9a89\"\n    },\n    {\n        \"name\": \"wibble\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"5cb3d6f4-62cb-41c9-b964-ba7d9df79e4e\"\n    },\n    {\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"5d51d012-3491-4db7-b1b5-6f254015015d\"\n    },\n    {\n        \"name\": \"wibble\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"5f9cf7dc-22ca-4097-8e49-1cc8b23faf17\"\n    },\n    {\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"6319ecad-6bff-48b2-9b53-02ede8cb7588\"\n    },\n    {\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"6ba4c788-661f-49ab-9bf8-5f10cbbb2f57\"\n    },\n    {\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"74ed170b-5069-4353-ab38-9719766dc57e\"\n    },\n    {\n        \"name\": \"wibble\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"b71fcac1-e864-4031-8c5b-edbecd9ece36\"\n    },\n    {\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"c7681895-d84d-4650-9ca0-82c72036b855\"\n    }\n]}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/network_list_response_paged1.json",
    "content": "{\n    \"networks\": [\n        {\n            \"admin_state_up\": true,\n            \"id\": \"396f12f8-521e-4b91-8e21-2e003500433a\",\n            \"name\": \"net3\",\n            \"provider:network_type\": \"vlan\",\n            \"provider:physical_network\": \"physnet1\",\n            \"provider:segmentation_id\": 1002,\n            \"router:external\": false,\n            \"shared\": false,\n            \"status\": \"ACTIVE\",\n            \"subnets\": [],\n            \"tenant_id\": \"20bd52ff3e1b40039c312395b04683cf\"\n        },\n        {\n            \"admin_state_up\": true,\n            \"id\": \"71c1e68c-171a-4aa2-aca5-50ea153a3718\",\n            \"name\": \"net2\",\n            \"provider:network_type\": \"vlan\",\n            \"provider:physical_network\": \"physnet1\",\n            \"provider:segmentation_id\": 1001,\n            \"router:external\": false,\n            \"shared\": false,\n            \"status\": \"ACTIVE\",\n            \"subnets\": [],\n            \"tenant_id\": \"20bd52ff3e1b40039c312395b04683cf\"\n        }\n    ],\n    \"networks_links\": [\n        {\n            \"href\": \"/v2.0/networks.json?marker=71c1e68c-171a-4aa2-aca5-50ea153a3718\",\n            \"rel\": \"next\"\n        },\n        {\n            \"href\": \"/v2.0/networks.json?marker=396f12f8-521e-4b91-8e21-2e003500433a&page_reverse=True\",\n            \"rel\": \"previous\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/network_list_response_paged2.json",
    "content": "{\n    \"networks\": [\n        {\n            \"admin_state_up\": true,\n            \"id\": \"396f12f8-521e-4b91-8e21-2e003500433a_2\",\n            \"name\": \"net3\",\n            \"provider:network_type\": \"vlan\",\n            \"provider:physical_network\": \"physnet1\",\n            \"provider:segmentation_id\": 1002,\n            \"router:external\": false,\n            \"shared\": false,\n            \"status\": \"ACTIVE\",\n            \"subnets\": [],\n            \"tenant_id\": \"20bd52ff3e1b40039c312395b04683cf\"\n        },\n        {\n            \"admin_state_up\": true,\n            \"id\": \"71c1e68c-171a-4aa2-aca5-50ea153a3718_2\",\n            \"name\": \"net2\",\n            \"provider:network_type\": \"vlan\",\n            \"provider:physical_network\": \"physnet1\",\n            \"provider:segmentation_id\": 1001,\n            \"router:external\": false,\n            \"shared\": false,\n            \"status\": \"ACTIVE\",\n            \"subnets\": [],\n            \"tenant_id\": \"20bd52ff3e1b40039c312395b04683cf\"\n        }\n    ],\n    \"networks_links\": [\n        {\n            \"href\": \"/v2.0/networks.json?marker=396f12f8-521e-4b91-8e21-2e003500433a&page_reverse=True\",\n            \"rel\": \"previous\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/network_update_request.json",
    "content": "{\"network\": {\n    \"provider:network_type\": \"local\",\n    \"name\": \"jclouds-wibble-updated\"\n}}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/network_update_response.json",
    "content": "{\n    \"network\": {\n        \"status\": \"ACTIVE\",\n        \"subnets\": [],\n        \"name\": \"updated_name\",\n        \"admin_state_up\": false,\n        \"shared\": false,\n        \"tenant_id\": \"c1210485b2424d48804aad5d39c61b8f\",\n        \"id\": \"fc68ea2c-b60b-4b4f-bd82-94ec81110766\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/port.json",
    "content": "{\"port\": {\n    \"status\": \"ACTIVE\",\n    \"network_id\": \"1234567890\",\n    \"name\": \"jclouds-wibble\",\n    \"tenant_id\": \"1234567890\",\n    \"id\": \"624312ff-d14b-4ba3-9834-1c78d23d574d\"\n}}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/port_create_bulk_request.json",
    "content": "{\n    \"ports\": [\n        {\n            \"admin_state_up\": true,\n            \"device_id\": \"24df1d04-d5cb-41e1-8de5-61ed77c558df\",\n            \"name\": \"port1\",\n            \"network_id\": \"64239a54-dcc4-4b39-920b-b37c2144effa\",\n            \"security_groups\": [\n                \"dbc107f4-afcd-4d5a-9352-f68f82241d5b\"\n            ]\n        },\n        {\n            \"admin_state_up\": false,\n            \"name\": \"port2\",\n            \"network_id\": \"e6031bc2-901a-4c66-82da-f4c32ed89406\",\n            \"security_groups\": [\n                \"8bf3f7cc-8471-40b1-815f-9da47e79775b\",\n                \"dbc107f4-afcd-4d5a-9352-f68f82241d5b\"\n            ]\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/port_create_bulk_response.json",
    "content": "{\n    \"ports\": [\n        {\n            \"admin_state_up\": true,\n            \"allowed_address_pairs\": [],\n            \"device_id\": \"24df1d04-d5cb-41e1-8de5-61ed77c558df\",\n            \"device_owner\": \"\",\n            \"fixed_ips\": [\n                {\n                    \"ip_address\": \"10.56.4.2\",\n                    \"subnet_id\": \"b0e7435c-1512-45fb-aa9e-9a7c5932fb30\"\n                }\n            ],\n            \"id\": \"4fa2a5b2-d758-449d-80d6-dff31df9e91e\",\n            \"mac_address\": \"fa:16:3e:63:b0:82\",\n            \"name\": \"port1\",\n            \"network_id\": \"64239a54-dcc4-4b39-920b-b37c2144effa\",\n            \"security_groups\": [\n                \"dbc107f4-afcd-4d5a-9352-f68f82241d5b\"\n            ],\n            \"status\": \"DOWN\",\n            \"tenant_id\": \"d19231fc08ec4bc4829b668040d34512\"\n        },\n        {\n            \"admin_state_up\": false,\n            \"allowed_address_pairs\": [],\n            \"device_id\": \"\",\n            \"device_owner\": \"\",\n            \"fixed_ips\": [\n                {\n                    \"ip_address\": \"192.168.199.2\",\n                    \"subnet_id\": \"0468a7a7-290d-4127-aedd-6c9449775a24\"\n                }\n            ],\n            \"id\": \"d3c059b8-40fd-489a-8d17-97bde9370987\",\n            \"mac_address\": \"fa:16:3e:86:09:06\",\n            \"name\": \"port2\",\n            \"network_id\": \"e6031bc2-901a-4c66-82da-f4c32ed89406\",\n            \"security_groups\": [\n                \"8bf3f7cc-8471-40b1-815f-9da47e79775b\",\n                \"dbc107f4-afcd-4d5a-9352-f68f82241d5b\"\n            ],\n            \"status\": \"DOWN\",\n            \"tenant_id\": \"d19231fc08ec4bc4829b668040d34512\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/port_create_request.json",
    "content": "{\n    \"port\": {\n        \"admin_state_up\": true,\n        \"device_id\": \"d6b4d3a5-c700-476f-b609-1493dd9dadc0\",\n        \"name\": \"port1\",\n        \"network_id\": \"6aeaf34a-c482-4bd3-9dc3-7faf36412f12\",\n        \"allowed_address_pairs\": [\n            {\n                \"ip_address\": \"111.222.333.444\",\n                \"mac_address\": \"12\"\n            }\n        ]\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/port_create_response.json",
    "content": "{\n    \"port\": {\n        \"admin_state_up\": true,\n        \"device_id\": \"d6b4d3a5-c700-476f-b609-1493dd9dadc0\",\n        \"device_owner\": \"\",\n        \"allowed_address_pairs\": [\n            {\n                \"ip_address\": \"192.168.1.1\",\n                \"mac_address\": \"12:12\"\n            },\n            {\n                \"mac_address\": \"12:13\",\n                \"ip_address\": \"192.168.1.2\"\n            }\n        ],\n        \"fixed_ips\": [\n            {\n                \"ip_address\": \"192.168.111.4\",\n                \"subnet_id\": \"22b44fc2-4ffb-4de4-b0f9-69d58b37ae27\"\n            }\n        ],\n        \"id\": \"ebe69f1e-bc26-4db5-bed0-c0afb4afe3db\",\n        \"mac_address\": \"fa:16:3e:a6:50:c1\",\n        \"name\": \"port1\",\n        \"network_id\": \"6aeaf34a-c482-4bd3-9dc3-7faf36412f12\",\n        \"status\": \"ACTIVE\",\n        \"tenant_id\": \"cf1a5775e766426cb1968766d0191908\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/port_get_response.json",
    "content": "{\"port\": {\n    \"status\": \"ACTIVE\",\n    \"network_id\": \"1234567890\",\n    \"name\": \"jclouds-wibble\",\n    \"tenant_id\": \"1234567890\",\n    \"id\": \"624312ff-d14b-4ba3-9834-1c78d23d574d\",\n    \"binding:vnic_type\": \"normal\",\n    \"binding:vif_type\": \"hyperv\",\n    \"binding:vif_details\": {\"name1\": \"value1\", \"name2\": {\"mapname2\": 3}}\n}}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/port_list_response.json",
    "content": "{\"ports\": [\n    {\n        \"status\": \"ACTIVE\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"16dba3bc-f3fa-4775-afdc-237e12c72f6a\"\n    },\n    {\n        \"status\": \"ACTIVE\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"wibble\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"1a104cf5-cb18-4d35-9407-2fd2646d9d0b\"\n    },\n    {\n        \"status\": \"ACTIVE\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"31083ae2-420d-48b2-ac98-9f7a4fd8dbdc\"\n    },\n    {\n        \"status\": \"ACTIVE\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"49c6d6fa-ff2a-459d-b975-75a8d31c9a89\"\n    },\n    {\n        \"status\": \"ACTIVE\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"wibble\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"5cb3d6f4-62cb-41c9-b964-ba7d9df79e4e\"\n    },\n    {\n        \"status\": \"ACTIVE\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"5d51d012-3491-4db7-b1b5-6f254015015d\"\n    },\n    {\n        \"status\": \"ACTIVE\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"wibble\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"5f9cf7dc-22ca-4097-8e49-1cc8b23faf17\"\n    },\n    {\n        \"status\": \"ACTIVE\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"6319ecad-6bff-48b2-9b53-02ede8cb7588\"\n    },\n    {\n        \"status\": \"ACTIVE\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"6ba4c788-661f-49ab-9bf8-5f10cbbb2f57\"\n    },\n    {\n        \"status\": \"ACTIVE\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"74ed170b-5069-4353-ab38-9719766dc57e\"\n    },\n    {\n        \"status\": \"ACTIVE\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"wibble\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"b71fcac1-e864-4031-8c5b-edbecd9ece36\"\n    },\n    {\n        \"status\": \"ACTIVE\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"c7681895-d84d-4650-9ca0-82c72036b855\"\n    }\n]}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/port_list_response_paged1.json",
    "content": "{\n    \"ports\": [\n        {\n            \"admin_state_up\": true,\n            \"device_id\": \"257614cc-e178-4c92-9c61-3b28d40eca44\",\n            \"device_owner\": \"\",\n            \"fixed_ips\": [\n                {\n                    \"ip_address\": \"192.168.111.3\",\n                    \"subnet_id\": \"22b44fc2-4ffb-4de4-b0f9-69d58b37ae27\"\n                }\n            ],\n            \"id\": \"24e6637e-c521-45fc-8b8b-d7331aa3c99f\",\n            \"mac_address\": \"fa:16:3e:0f:3f:b5\",\n            \"name\": \"\",\n            \"network_id\": \"6aeaf34a-c482-4bd3-9dc3-7faf36412f12\",\n            \"status\": \"ACTIVE\",\n            \"tenant_id\": \"cf1a5775e766426cb1968766d0191908\"\n        },\n        {\n            \"admin_state_up\": true,\n            \"device_id\": \"d266f9de-fe2c-4705-93b3-9da71168c93b\",\n            \"device_owner\": \"\",\n            \"fixed_ips\": [\n                {\n                    \"ip_address\": \"192.168.111.2\",\n                    \"subnet_id\": \"22b44fc2-4ffb-4de4-b0f9-69d58b37ae27\"\n                }\n            ],\n            \"id\": \"e54dfd9b-ce6e-47f7-af47-1609cfd1cdb0\",\n            \"mac_address\": \"fa:16:3e:f5:41:7f\",\n            \"name\": \"\",\n            \"network_id\": \"6aeaf34a-c482-4bd3-9dc3-7faf36412f12\",\n            \"status\": \"ACTIVE\",\n            \"tenant_id\": \"cf1a5775e766426cb1968766d0191908\"\n        }\n    ],\n    \"ports_links\": [\n        {\n            \"href\": \"/v2.0/ports.json?marker=71c1e68c-171a-4aa2-aca5-50ea153a3718\",\n            \"rel\": \"next\"\n        },\n        {\n            \"href\": \"/v2.0/ports.json?marker=396f12f8-521e-4b91-8e21-2e003500433a&page_reverse=True\",\n            \"rel\": \"previous\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/port_list_response_paged2.json",
    "content": "{\n    \"ports\": [\n        {\n            \"admin_state_up\": true,\n            \"device_id\": \"257614cc-e178-4c92-9c61-3b28d40eca44_3\",\n            \"device_owner\": \"\",\n            \"fixed_ips\": [\n                {\n                    \"ip_address\": \"192.168.111.3\",\n                    \"subnet_id\": \"22b44fc2-4ffb-4de4-b0f9-69d58b37ae27\"\n                }\n            ],\n            \"id\": \"24e6637e-c521-45fc-8b8b-d7331aa3c99f-2_3\",\n            \"mac_address\": \"fa:16:3e:0f:3f:b5\",\n            \"name\": \"3\",\n            \"network_id\": \"6aeaf34a-c482-4bd3-9dc3-7faf36412f12\",\n            \"status\": \"ACTIVE\",\n            \"tenant_id\": \"cf1a5775e766426cb1968766d0191908\"\n        },\n        {\n            \"admin_state_up\": true,\n            \"device_id\": \"d266f9de-fe2c-4705-93b3-9da71168c93b\",\n            \"device_owner\": \"\",\n            \"fixed_ips\": [\n                {\n                    \"ip_address\": \"192.168.111.2\",\n                    \"subnet_id\": \"22b44fc2-4ffb-4de4-b0f9-69d58b37ae27\"\n                }\n            ],\n            \"id\": \"e54dfd9b-ce6e-47f7-af47-1609cfd1cdb0_4\",\n            \"mac_address\": \"fa:16:3e:f5:41:7f\",\n            \"name\": \"4\",\n            \"network_id\": \"6aeaf34a-c482-4bd3-9dc3-7faf36412f12\",\n            \"status\": \"ACTIVE\",\n            \"tenant_id\": \"cf1a5775e766426cb1968766d0191908\"\n        }\n    ],\n    \"ports_links\": [\n        {\n            \"href\": \"/v2.0/ports.json?marker=396f12f8-521e-4b91-8e21-2e003500433a&page_reverse=True\",\n            \"rel\": \"previous\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/port_update_request.json",
    "content": "{\n    \"port\": {\n        \"security_groups\": [\n            \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n            \"c5ab5c29-2c99-44cb-a4b8-e70a88b77799\"\n        ]\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/port_update_response.json",
    "content": "{\n    \"port\": {\n        \"admin_state_up\": true,\n        \"device_id\": \"24df1d04-d5cb-41e1-8de5-61ed77c558df\",\n        \"device_owner\": \"compute:None\",\n        \"fixed_ips\": [\n            {\n                \"ip_address\": \"10.0.0.3\",\n                \"subnet_id\": \"3b498f11-0a20-43ed-b992-0e4202d5f930\"\n            }\n        ],\n        \"id\": \"1d8591f4-7b62-428e-857d-e82a15e5a7f1\",\n        \"mac_address\": \"fa:16:3e:b6:da:54\",\n        \"name\": \"\",\n        \"network_id\": \"abaf2e70-4305-4e8d-ac70-3e4cc5f66a07\",\n        \"security_groups\": [\n            \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n            \"c5ab5c29-2c99-44cb-a4b8-e70a88b77799\"\n        ],\n        \"status\": \"ACTIVE\",\n        \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/router.json",
    "content": "{\"router\": {\n    \"status\": \"ACTIVE\",\n    \"external_gateway_info\": {\n        \"network_id\": \"624312ff-d14b-4ba3-9834-1c78d23d574d\"\n    },\n    \"name\": \"jclouds-wibble\",\n    \"tenant_id\": \"1234567890\",\n    \"id\": \"16dba3bc-f3fa-4775-afdc-237e12c72f6a\"\n}}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/router_add_interface_port_request.json",
    "content": "{\n    \"port_id\": \"portid\"\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/router_add_interface_request.json",
    "content": "{\n    \"subnet_id\": \"a2f1f29d-571b-4533-907f-5803ab96ead1\"\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/router_add_interface_response.json",
    "content": "{\n    \"subnet_id\": \"a2f1f29d-571b-4533-907f-5803ab96ead1\",\n    \"port_id\": \"3a44f4e5-1694-493a-a1fb-393881c673a4\"\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/router_create_request.json",
    "content": "{\n    \"router\": {\n        \"name\": \"another_router\",\n        \"external_gateway_info\": {\n            \"network_id\": \"8ca37218-28ff-41cb-9b10-039601ea7e6b\",\n            \"enable_snat\":true\n        },\n        \"admin_state_up\": true\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/router_create_response.json",
    "content": "{\n    \"router\": {\n        \"status\": \"ACTIVE\",\n        \"external_gateway_info\": {\n            \"network_id\": \"8ca37218-28ff-41cb-9b10-039601ea7e6b\",\n            \"enable_snat\":true\n        },\n        \"name\": \"another_router\",\n        \"admin_state_up\": true,\n        \"tenant_id\": \"6b96ff0cb17a4b859e1e575d221683d3\",\n        \"id\": \"8604a0de-7f6b-409a-a47c-a1cc7bc77b2e\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/router_get_response.json",
    "content": "{\n    \"router\": {\n        \"status\": \"ACTIVE\",\n        \"external_gateway_info\": {\n            \"network_id\": \"3c5bcddd-6af9-4e6b-9c3e-c153e521cab8\"\n        },\n        \"name\": \"router1\",\n        \"admin_state_up\": true,\n        \"tenant_id\": \"33a40233088643acb66ff6eb0ebea679\",\n        \"id\": \"a9254bdb-2613-4a13-ac4c-adc581fba50d\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/router_list_response.json",
    "content": "{\"routers\": [\n    {\n        \"status\": \"ACTIVE\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"16dba3bc-f3fa-4775-afdc-237e12c72f6a\"\n    },\n    {\n        \"status\": \"ACTIVE\",\n        \"name\": \"wibble\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"1a104cf5-cb18-4d35-9407-2fd2646d9d0b\"\n    },\n    {\n        \"status\": \"ACTIVE\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"31083ae2-420d-48b2-ac98-9f7a4fd8dbdc\"\n    },\n    {\n        \"status\": \"ACTIVE\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"49c6d6fa-ff2a-459d-b975-75a8d31c9a89\"\n    },\n    {\n        \"status\": \"ACTIVE\",\n        \"name\": \"wibble\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"5cb3d6f4-62cb-41c9-b964-ba7d9df79e4e\"\n    },\n    {\n        \"status\": \"ACTIVE\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"5d51d012-3491-4db7-b1b5-6f254015015d\"\n    },\n    {\n        \"status\": \"ACTIVE\",\n        \"name\": \"wibble\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"5f9cf7dc-22ca-4097-8e49-1cc8b23faf17\"\n    },\n    {\n        \"status\": \"ACTIVE\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"6319ecad-6bff-48b2-9b53-02ede8cb7588\"\n    },\n    {\n        \"status\": \"ACTIVE\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"6ba4c788-661f-49ab-9bf8-5f10cbbb2f57\"\n    },\n    {\n        \"status\": \"ACTIVE\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"74ed170b-5069-4353-ab38-9719766dc57e\"\n    },\n    {\n        \"status\": \"ACTIVE\",\n        \"name\": \"wibble\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"b71fcac1-e864-4031-8c5b-edbecd9ece36\"\n    },\n    {\n        \"status\": \"ACTIVE\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"c7681895-d84d-4650-9ca0-82c72036b855\"\n    }\n]}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/router_list_response_paged1.json",
    "content": "{\n    \"routers\": [\n        {\n            \"status\": \"ACTIVE\",\n            \"external_gateway_info\": {\n                \"network_id\": \"3c5bcddd-6af9-4e6b-9c3e-c153e521cab8\"\n            },\n            \"name\": \"router1\",\n            \"admin_state_up\": true,\n            \"tenant_id\": \"33a40233088643acb66ff6eb0ebea679\",\n            \"id\": \"a9254bdb-2613-4a13-ac4c-adc581fba50d\"\n        },\n        {\n            \"status\": \"ACTIVE\",\n            \"external_gateway_info\": {\n                \"network_id\": \"3c5bcddd-6af9-4e6b-9c3e-c153e521cab8_2\"\n            },\n            \"name\": \"router2\",\n            \"admin_state_up\": true,\n            \"tenant_id\": \"33a40233088643acb66ff6eb0ebea679_2\",\n            \"id\": \"a9254bdb-2613-4a13-ac4c-adc581fba50d_2\"\n        }\n    ],\n    \"routers_links\": [\n        {\n            \"href\": \"/v2.0/routers.json?marker=71c1e68c-171a-4aa2-aca5-50ea153a3718\",\n            \"rel\": \"next\"\n        },\n        {\n            \"href\": \"/v2.0/routers.json?marker=396f12f8-521e-4b91-8e21-2e003500433a&page_reverse=True\",\n            \"rel\": \"previous\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/router_list_response_paged2.json",
    "content": "{\n    \"routers\": [\n        {\n            \"status\": \"ACTIVE\",\n            \"external_gateway_info\": {\n                \"network_id\": \"3c5bcddd-6af9-4e6b-9c3e-c153e521cab8_3\"\n            },\n            \"name\": \"router3\",\n            \"admin_state_up\": true,\n            \"tenant_id\": \"33a40233088643acb66ff6eb0ebea679_3\",\n            \"id\": \"a9254bdb-2613-4a13-ac4c-adc581fba50d_3\"\n        },\n        {\n            \"status\": \"ACTIVE\",\n            \"external_gateway_info\": {\n                \"network_id\": \"3c5bcddd-6af9-4e6b-9c3e-c153e521cab8_4\"\n            },\n            \"name\": \"router4\",\n            \"admin_state_up\": true,\n            \"tenant_id\": \"33a40233088643acb66ff6eb0ebea679_4\",\n            \"id\": \"a9254bdb-2613-4a13-ac4c-adc581fba50d_4\"\n        }\n    ],\n    \"routers_links\": [\n        {\n            \"href\": \"/v2.0/routers.json?marker=396f12f8-521e-4b91-8e21-2e003500433a&page_reverse=True\",\n            \"rel\": \"previous\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/router_remove_interface_port_request.json",
    "content": "{\n    \"port_id\": \"portid\"\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/router_remove_interface_subnet_request.json",
    "content": "{\n    \"subnet_id\": \"a2f1f29d-571b-4533-907f-5803ab96ead1\"\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/router_update_request.json",
    "content": "{\n    \"router\": {\n        \"external_gateway_info\": {\n            \"network_id\": \"8ca37218-28ff-41cb-9b10-039601ea7e6b\"\n        }\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/router_update_response.json",
    "content": "{\n    \"router\": {\n        \"status\": \"ACTIVE\",\n        \"external_gateway_info\": {\n            \"network_id\": \"8ca37218-28ff-41cb-9b10-039601ea7e6b\"\n        },\n        \"name\": \"another_router\",\n        \"admin_state_up\": true,\n        \"tenant_id\": \"6b96ff0cb17a4b859e1e575d221683d3\",\n        \"id\": \"8604a0de-7f6b-409a-a47c-a1cc7bc77b2e\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/security_group_create_request.json",
    "content": "{\n    \"security_group\": {\n        \"name\": \"new-webservers\",\n        \"description\": \"security group for webservers\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/security_group_create_response.json",
    "content": "{\n    \"security_group\": {\n        \"description\": \"security group for webservers\",\n        \"id\": \"2076db17-a522-4506-91de-c6dd8e837028\",\n        \"name\": \"new-webservers\",\n        \"security_group_rules\": [\n            {\n                \"direction\": \"egress\",\n                \"ethertype\": \"IPv4\",\n                \"id\": \"38ce2d8e-e8f1-48bd-83c2-d33cb9f50c3d\",\n                \"port_range_max\": null,\n                \"port_range_min\": null,\n                \"protocol\": null,\n                \"remote_group_id\": null,\n                \"remote_ip_prefix\": null,\n                \"security_group_id\": \"2076db17-a522-4506-91de-c6dd8e837028\",\n                \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n            },\n            {\n                \"direction\": \"egress\",\n                \"ethertype\": \"IPv6\",\n                \"id\": \"565b9502-12de-4ffd-91e9-68885cff6ae1\",\n                \"port_range_max\": null,\n                \"port_range_min\": null,\n                \"protocol\": null,\n                \"remote_group_id\": null,\n                \"remote_ip_prefix\": null,\n                \"security_group_id\": \"2076db17-a522-4506-91de-c6dd8e837028\",\n                \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n            }\n        ],\n        \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/security_group_get_response.json",
    "content": "{\n    \"security_group\": {\n        \"description\": \"default\",\n        \"id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n        \"name\": \"default\",\n        \"security_group_rules\": [\n            {\n                \"direction\": \"egress\",\n                \"ethertype\": \"IPv6\",\n                \"id\": \"3c0e45ff-adaf-4124-b083-bf390e5482ff\",\n                \"port_range_max\": null,\n                \"port_range_min\": null,\n                \"protocol\": null,\n                \"remote_group_id\": null,\n                \"remote_ip_prefix\": null,\n                \"security_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n                \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n            },\n            {\n                \"direction\": \"egress\",\n                \"ethertype\": \"IPv4\",\n                \"id\": \"93aa42e5-80db-4581-9391-3a608bd0e448\",\n                \"port_range_max\": null,\n                \"port_range_min\": null,\n                \"protocol\": null,\n                \"remote_group_id\": null,\n                \"remote_ip_prefix\": null,\n                \"security_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n                \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n            },\n            {\n                \"direction\": \"ingress\",\n                \"ethertype\": \"IPv6\",\n                \"id\": \"c0b09f00-1d49-4e64-a0a7-8a186d928138\",\n                \"port_range_max\": null,\n                \"port_range_min\": null,\n                \"protocol\": null,\n                \"remote_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n                \"remote_ip_prefix\": null,\n                \"security_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n                \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n            },\n            {\n                \"direction\": \"ingress\",\n                \"ethertype\": \"IPv4\",\n                \"id\": \"f7d45c89-008e-4bab-88ad-d6811724c51c\",\n                \"port_range_max\": null,\n                \"port_range_min\": null,\n                \"protocol\": null,\n                \"remote_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n                \"remote_ip_prefix\": null,\n                \"security_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n                \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n            }\n        ],\n        \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/security_group_list_response.json",
    "content": "{\n    \"security_groups\": [\n        {\n            \"description\": \"default\",\n            \"id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n            \"name\": \"default\",\n            \"security_group_rules\": [\n                {\n                    \"direction\": \"egress\",\n                    \"ethertype\": \"IPv6\",\n                    \"id\": \"3c0e45ff-adaf-4124-b083-bf390e5482ff\",\n                    \"port_range_max\": null,\n                    \"port_range_min\": null,\n                    \"protocol\": null,\n                    \"remote_group_id\": null,\n                    \"remote_ip_prefix\": null,\n                    \"security_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n                    \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n                },\n                {\n                    \"direction\": \"egress\",\n                    \"ethertype\": \"IPv4\",\n                    \"id\": \"93aa42e5-80db-4581-9391-3a608bd0e448\",\n                    \"port_range_max\": null,\n                    \"port_range_min\": null,\n                    \"protocol\": null,\n                    \"remote_group_id\": null,\n                    \"remote_ip_prefix\": null,\n                    \"security_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n                    \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n                },\n                {\n                    \"direction\": \"ingress\",\n                    \"ethertype\": \"IPv6\",\n                    \"id\": \"c0b09f00-1d49-4e64-a0a7-8a186d928138\",\n                    \"port_range_max\": null,\n                    \"port_range_min\": null,\n                    \"protocol\": null,\n                    \"remote_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n                    \"remote_ip_prefix\": null,\n                    \"security_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n                    \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n                },\n                {\n                    \"direction\": \"ingress\",\n                    \"ethertype\": \"IPv4\",\n                    \"id\": \"f7d45c89-008e-4bab-88ad-d6811724c51c\",\n                    \"port_range_max\": null,\n                    \"port_range_min\": null,\n                    \"protocol\": null,\n                    \"remote_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n                    \"remote_ip_prefix\": null,\n                    \"security_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n                    \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n                }\n            ],\n            \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n        },\n        {\n            \"description\": \"default\",\n            \"id\": \"85cc3048-abc3-43cc-89b3-377341426ac52\",\n            \"name\": \"default\",\n            \"security_group_rules\": [\n                {\n                    \"direction\": \"egress\",\n                    \"ethertype\": \"IPv6\",\n                    \"id\": \"3c0e45ff-adaf-4124-b083-bf390e5482ff2\",\n                    \"port_range_max\": null,\n                    \"port_range_min\": null,\n                    \"protocol\": null,\n                    \"remote_group_id\": null,\n                    \"remote_ip_prefix\": null,\n                    \"security_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n                    \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n                },\n                {\n                    \"direction\": \"egress\",\n                    \"ethertype\": \"IPv4\",\n                    \"id\": \"93aa42e5-80db-4581-9391-3a608bd0e4482\",\n                    \"port_range_max\": null,\n                    \"port_range_min\": null,\n                    \"protocol\": null,\n                    \"remote_group_id\": null,\n                    \"remote_ip_prefix\": null,\n                    \"security_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n                    \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n                },\n                {\n                    \"direction\": \"ingress\",\n                    \"ethertype\": \"IPv6\",\n                    \"id\": \"c0b09f00-1d49-4e64-a0a7-8a186d9281382\",\n                    \"port_range_max\": null,\n                    \"port_range_min\": null,\n                    \"protocol\": null,\n                    \"remote_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n                    \"remote_ip_prefix\": null,\n                    \"security_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n                    \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n                },\n                {\n                    \"direction\": \"ingress\",\n                    \"ethertype\": \"IPv4\",\n                    \"id\": \"f7d45c89-008e-4bab-88ad-d6811724c51c2\",\n                    \"port_range_max\": null,\n                    \"port_range_min\": null,\n                    \"protocol\": null,\n                    \"remote_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n                    \"remote_ip_prefix\": null,\n                    \"security_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n                    \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n                }\n            ],\n            \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/security_group_list_response_paged1.json",
    "content": "{\n    \"security_groups\": [\n        {\n            \"description\": \"default\",\n            \"id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n            \"name\": \"default\",\n            \"security_group_rules\": [\n                {\n                    \"direction\": \"egress\",\n                    \"ethertype\": \"IPv6\",\n                    \"id\": \"3c0e45ff-adaf-4124-b083-bf390e5482ff\",\n                    \"port_range_max\": null,\n                    \"port_range_min\": null,\n                    \"protocol\": null,\n                    \"remote_group_id\": null,\n                    \"remote_ip_prefix\": null,\n                    \"security_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n                    \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n                },\n                {\n                    \"direction\": \"egress\",\n                    \"ethertype\": \"IPv4\",\n                    \"id\": \"93aa42e5-80db-4581-9391-3a608bd0e448\",\n                    \"port_range_max\": null,\n                    \"port_range_min\": null,\n                    \"protocol\": null,\n                    \"remote_group_id\": null,\n                    \"remote_ip_prefix\": null,\n                    \"security_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n                    \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n                },\n                {\n                    \"direction\": \"ingress\",\n                    \"ethertype\": \"IPv6\",\n                    \"id\": \"c0b09f00-1d49-4e64-a0a7-8a186d928138\",\n                    \"port_range_max\": null,\n                    \"port_range_min\": null,\n                    \"protocol\": null,\n                    \"remote_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n                    \"remote_ip_prefix\": null,\n                    \"security_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n                    \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n                },\n                {\n                    \"direction\": \"ingress\",\n                    \"ethertype\": \"IPv4\",\n                    \"id\": \"f7d45c89-008e-4bab-88ad-d6811724c51c\",\n                    \"port_range_max\": null,\n                    \"port_range_min\": null,\n                    \"protocol\": null,\n                    \"remote_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n                    \"remote_ip_prefix\": null,\n                    \"security_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n                    \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n                }\n            ],\n            \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n        },\n        {\n            \"description\": \"default\",\n            \"id\": \"85cc3048-abc3-43cc-89b3-377341426ac52\",\n            \"name\": \"default\",\n            \"security_group_rules\": [\n                {\n                    \"direction\": \"egress\",\n                    \"ethertype\": \"IPv6\",\n                    \"id\": \"3c0e45ff-adaf-4124-b083-bf390e5482ff2\",\n                    \"port_range_max\": null,\n                    \"port_range_min\": null,\n                    \"protocol\": null,\n                    \"remote_group_id\": null,\n                    \"remote_ip_prefix\": null,\n                    \"security_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n                    \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n                },\n                {\n                    \"direction\": \"egress\",\n                    \"ethertype\": \"IPv4\",\n                    \"id\": \"93aa42e5-80db-4581-9391-3a608bd0e4482\",\n                    \"port_range_max\": null,\n                    \"port_range_min\": null,\n                    \"protocol\": null,\n                    \"remote_group_id\": null,\n                    \"remote_ip_prefix\": null,\n                    \"security_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n                    \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n                },\n                {\n                    \"direction\": \"ingress\",\n                    \"ethertype\": \"IPv6\",\n                    \"id\": \"c0b09f00-1d49-4e64-a0a7-8a186d9281382\",\n                    \"port_range_max\": null,\n                    \"port_range_min\": null,\n                    \"protocol\": null,\n                    \"remote_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n                    \"remote_ip_prefix\": null,\n                    \"security_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n                    \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n                },\n                {\n                    \"direction\": \"ingress\",\n                    \"ethertype\": \"IPv4\",\n                    \"id\": \"f7d45c89-008e-4bab-88ad-d6811724c51c2\",\n                    \"port_range_max\": null,\n                    \"port_range_min\": null,\n                    \"protocol\": null,\n                    \"remote_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n                    \"remote_ip_prefix\": null,\n                    \"security_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n                    \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n                }\n            ],\n            \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n        }\n    ],\n    \"security_groups_links\": [\n        {\n            \"href\": \"/v2.0/security-groups.json?marker=71c1e68c-171a-4aa2-aca5-50ea153a3718\",\n            \"rel\": \"next\"\n        },\n        {\n            \"href\": \"/v2.0/security-groups.json?marker=396f12f8-521e-4b91-8e21-2e003500433a&page_reverse=True\",\n            \"rel\": \"previous\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/security_group_list_response_paged2.json",
    "content": "{\n    \"security_groups\": [\n        {\n            \"description\": \"default\",\n            \"id\": \"85cc3048-abc3-43cc-89b3-377341426ac53\",\n            \"name\": \"default\",\n            \"security_group_rules\": [\n                {\n                    \"direction\": \"egress\",\n                    \"ethertype\": \"IPv6\",\n                    \"id\": \"3c0e45ff-adaf-4124-b083-bf390e5482ff\",\n                    \"port_range_max\": null,\n                    \"port_range_min\": null,\n                    \"protocol\": null,\n                    \"remote_group_id\": null,\n                    \"remote_ip_prefix\": null,\n                    \"security_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n                    \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n                },\n                {\n                    \"direction\": \"egress\",\n                    \"ethertype\": \"IPv4\",\n                    \"id\": \"93aa42e5-80db-4581-9391-3a608bd0e448\",\n                    \"port_range_max\": null,\n                    \"port_range_min\": null,\n                    \"protocol\": null,\n                    \"remote_group_id\": null,\n                    \"remote_ip_prefix\": null,\n                    \"security_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n                    \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n                },\n                {\n                    \"direction\": \"ingress\",\n                    \"ethertype\": \"IPv6\",\n                    \"id\": \"c0b09f00-1d49-4e64-a0a7-8a186d928138\",\n                    \"port_range_max\": null,\n                    \"port_range_min\": null,\n                    \"protocol\": null,\n                    \"remote_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n                    \"remote_ip_prefix\": null,\n                    \"security_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n                    \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n                },\n                {\n                    \"direction\": \"ingress\",\n                    \"ethertype\": \"IPv4\",\n                    \"id\": \"f7d45c89-008e-4bab-88ad-d6811724c51c\",\n                    \"port_range_max\": null,\n                    \"port_range_min\": null,\n                    \"protocol\": null,\n                    \"remote_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n                    \"remote_ip_prefix\": null,\n                    \"security_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n                    \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n                }\n            ],\n            \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n        },\n        {\n            \"description\": \"default\",\n            \"id\": \"85cc3048-abc3-43cc-89b3-377341426ac524\",\n            \"name\": \"default\",\n            \"security_group_rules\": [\n                {\n                    \"direction\": \"egress\",\n                    \"ethertype\": \"IPv6\",\n                    \"id\": \"3c0e45ff-adaf-4124-b083-bf390e5482ff2\",\n                    \"port_range_max\": null,\n                    \"port_range_min\": null,\n                    \"protocol\": null,\n                    \"remote_group_id\": null,\n                    \"remote_ip_prefix\": null,\n                    \"security_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n                    \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n                },\n                {\n                    \"direction\": \"egress\",\n                    \"ethertype\": \"IPv4\",\n                    \"id\": \"93aa42e5-80db-4581-9391-3a608bd0e4482\",\n                    \"port_range_max\": null,\n                    \"port_range_min\": null,\n                    \"protocol\": null,\n                    \"remote_group_id\": null,\n                    \"remote_ip_prefix\": null,\n                    \"security_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n                    \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n                },\n                {\n                    \"direction\": \"ingress\",\n                    \"ethertype\": \"IPv6\",\n                    \"id\": \"c0b09f00-1d49-4e64-a0a7-8a186d9281382\",\n                    \"port_range_max\": null,\n                    \"port_range_min\": null,\n                    \"protocol\": null,\n                    \"remote_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n                    \"remote_ip_prefix\": null,\n                    \"security_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n                    \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n                },\n                {\n                    \"direction\": \"ingress\",\n                    \"ethertype\": \"IPv4\",\n                    \"id\": \"f7d45c89-008e-4bab-88ad-d6811724c51c2\",\n                    \"port_range_max\": null,\n                    \"port_range_min\": null,\n                    \"protocol\": null,\n                    \"remote_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n                    \"remote_ip_prefix\": null,\n                    \"security_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n                    \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n                }\n            ],\n            \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n        }\n    ],\n    \"security_groups_links\": [\n        {\n            \"href\": \"/v2.0/security-groups.json?marker=396f12f8-521e-4b91-8e21-2e003500433a&page_reverse=True\",\n            \"rel\": \"previous\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/security_group_rule_create_request.json",
    "content": "{\n    \"security_group_rule\": {\n        \"direction\": \"ingress\",\n        \"port_range_min\": 80,\n        \"ethertype\": \"IPv4\",\n        \"port_range_max\": 80,\n        \"protocol\": \"tcp\",\n        \"remote_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n        \"security_group_id\": \"a7734e61-b545-452d-a3cd-0189cbd9747a\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/security_group_rule_create_response.json",
    "content": "{\n    \"security_group_rule\": {\n        \"direction\": \"ingress\",\n        \"ethertype\": \"IPv4\",\n        \"id\": \"2bc0accf-312e-429a-956e-e4407625eb62\",\n        \"port_range_max\": 80,\n        \"port_range_min\": 80,\n        \"protocol\": \"tcp\",\n        \"remote_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n        \"remote_ip_prefix\": null,\n        \"security_group_id\": \"a7734e61-b545-452d-a3cd-0189cbd9747a\",\n        \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n    }\n}\n\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/security_group_rule_get_response.json",
    "content": "{\n    \"security_group_rule\": {\n        \"direction\": \"egress\",\n        \"ethertype\": \"IPv6\",\n        \"id\": \"3c0e45ff-adaf-4124-b083-bf390e5482ff\",\n        \"port_range_max\": null,\n        \"port_range_min\": null,\n        \"protocol\": null,\n        \"remote_group_id\": null,\n        \"remote_ip_prefix\": null,\n        \"security_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n        \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/security_group_rule_list_response.json",
    "content": "{\n    \"security_group_rules\": [\n        {\n            \"direction\": \"egress\",\n            \"ethertype\": \"IPv6\",\n            \"id\": \"3c0e45ff-adaf-4124-b083-bf390e5482ff\",\n            \"port_range_max\": null,\n            \"port_range_min\": null,\n            \"protocol\": null,\n            \"remote_group_id\": null,\n            \"remote_ip_prefix\": null,\n            \"security_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n            \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n        },\n        {\n            \"direction\": \"egress\",\n            \"ethertype\": \"IPv4\",\n            \"id\": \"93aa42e5-80db-4581-9391-3a608bd0e448\",\n            \"port_range_max\": null,\n            \"port_range_min\": null,\n            \"protocol\": null,\n            \"remote_group_id\": null,\n            \"remote_ip_prefix\": null,\n            \"security_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n            \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n        },\n        {\n            \"direction\": \"ingress\",\n            \"ethertype\": \"IPv6\",\n            \"id\": \"c0b09f00-1d49-4e64-a0a7-8a186d928138\",\n            \"port_range_max\": null,\n            \"port_range_min\": null,\n            \"protocol\": null,\n            \"remote_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n            \"remote_ip_prefix\": null,\n            \"security_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n            \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n        },\n        {\n            \"direction\": \"ingress\",\n            \"ethertype\": \"IPv4\",\n            \"id\": \"f7d45c89-008e-4bab-88ad-d6811724c51c\",\n            \"port_range_max\": null,\n            \"port_range_min\": null,\n            \"protocol\": null,\n            \"remote_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n            \"remote_ip_prefix\": null,\n            \"security_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n            \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/security_group_rule_list_response_paged1.json",
    "content": "{\n    \"security_group_rules\": [\n        {\n            \"direction\": \"egress\",\n            \"ethertype\": \"IPv6\",\n            \"id\": \"3c0e45ff-adaf-4124-b083-bf390e5482ff\",\n            \"port_range_max\": null,\n            \"port_range_min\": null,\n            \"protocol\": null,\n            \"remote_group_id\": null,\n            \"remote_ip_prefix\": null,\n            \"security_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n            \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n        },\n        {\n            \"direction\": \"egress\",\n            \"ethertype\": \"IPv4\",\n            \"id\": \"93aa42e5-80db-4581-9391-3a608bd0e448\",\n            \"port_range_max\": null,\n            \"port_range_min\": null,\n            \"protocol\": null,\n            \"remote_group_id\": null,\n            \"remote_ip_prefix\": null,\n            \"security_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n            \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n        },\n        {\n            \"direction\": \"ingress\",\n            \"ethertype\": \"IPv6\",\n            \"id\": \"c0b09f00-1d49-4e64-a0a7-8a186d928138\",\n            \"port_range_max\": null,\n            \"port_range_min\": null,\n            \"protocol\": null,\n            \"remote_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n            \"remote_ip_prefix\": null,\n            \"security_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n            \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n        },\n        {\n            \"direction\": \"ingress\",\n            \"ethertype\": \"IPv4\",\n            \"id\": \"f7d45c89-008e-4bab-88ad-d6811724c51c\",\n            \"port_range_max\": null,\n            \"port_range_min\": null,\n            \"protocol\": null,\n            \"remote_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n            \"remote_ip_prefix\": null,\n            \"security_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n            \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n        }\n    ],\n    \"security_group_rules_links\": [\n        {\n            \"href\": \"/v2.0/security-group-rules.json?marker=71c1e68c-171a-4aa2-aca5-50ea153a3718\",\n            \"rel\": \"next\"\n        },\n        {\n            \"href\": \"/v2.0/security-group-rules.json?marker=396f12f8-521e-4b91-8e21-2e003500433a&page_reverse=True\",\n            \"rel\": \"previous\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/security_group_rule_list_response_paged2.json",
    "content": "{\n    \"security_group_rules\": [\n        {\n            \"direction\": \"egress\",\n            \"ethertype\": \"IPv6\",\n            \"id\": \"3c0e45ff-adaf-4124-b083-bf390e5482ff2\",\n            \"port_range_max\": null,\n            \"port_range_min\": null,\n            \"protocol\": null,\n            \"remote_group_id\": null,\n            \"remote_ip_prefix\": null,\n            \"security_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n            \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n        },\n        {\n            \"direction\": \"egress\",\n            \"ethertype\": \"IPv4\",\n            \"id\": \"93aa42e5-80db-4581-9391-3a608bd0e4482\",\n            \"port_range_max\": null,\n            \"port_range_min\": null,\n            \"protocol\": null,\n            \"remote_group_id\": null,\n            \"remote_ip_prefix\": null,\n            \"security_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n            \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n        },\n        {\n            \"direction\": \"ingress\",\n            \"ethertype\": \"IPv6\",\n            \"id\": \"c0b09f00-1d49-4e64-a0a7-8a186d9281382\",\n            \"port_range_max\": null,\n            \"port_range_min\": null,\n            \"protocol\": null,\n            \"remote_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n            \"remote_ip_prefix\": null,\n            \"security_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n            \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n        },\n        {\n            \"direction\": \"ingress\",\n            \"ethertype\": \"IPv4\",\n            \"id\": \"f7d45c89-008e-4bab-88ad-d6811724c51c2\",\n            \"port_range_max\": null,\n            \"port_range_min\": null,\n            \"protocol\": null,\n            \"remote_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n            \"remote_ip_prefix\": null,\n            \"security_group_id\": \"85cc3048-abc3-43cc-89b3-377341426ac5\",\n            \"tenant_id\": \"e4f50856753b4dc6afee5fa6b9b6c550\"\n        }\n    ],\n    \"security_group_rules_links\": [\n        {\n            \"href\": \"/v2.0/security-group-rules.json?marker=396f12f8-521e-4b91-8e21-2e003500433a&page_reverse=True\",\n            \"rel\": \"previous\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/subnet.json",
    "content": "{\"subnet\": {\n    \"ip_version\": 4,\n    \"cidr\": \"10.0.3.0/24\",\n    \"network_id\": \"1234567890\",\n    \"name\": \"jclouds-wibble\",\n    \"tenant_id\": \"1234567890\",\n    \"id\": \"624312ff-d14b-4ba3-9834-1c78d23d574d\"\n}}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/subnet_bulk_create_request.json",
    "content": "{\n    \"subnets\": [\n        {\n            \"cidr\": \"192.168.199.0/24\",\n            \"ip_version\": 4,\n            \"network_id\": \"e6031bc2-901a-4c66-82da-f4c32ed89406\"\n        },\n        {\n            \"cidr\": \"10.56.4.0/22\",\n            \"ip_version\": 4,\n            \"network_id\": \"64239a54-dcc4-4b39-920b-b37c2144effa\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/subnet_bulk_create_response.json",
    "content": "{\n    \"subnets\": [\n        {\n            \"allocation_pools\": [\n                {\n                    \"end\": \"192.168.199.254\",\n                    \"start\": \"192.168.199.2\"\n                }\n            ],\n            \"cidr\": \"192.168.199.0/24\",\n            \"dns_nameservers\": [\n\n            ],\n            \"enable_dhcp\": true,\n            \"gateway_ip\": \"192.168.199.1\",\n            \"host_routes\": [\n\n            ],\n            \"id\": \"0468a7a7-290d-4127-aedd-6c9449775a24\",\n            \"ip_version\": 4,\n            \"name\": \"\",\n            \"network_id\": \"e6031bc2-901a-4c66-82da-f4c32ed89406\",\n            \"tenant_id\": \"d19231fc08ec4bc4829b668040d34512\"\n        },\n        {\n            \"allocation_pools\": [\n                {\n                    \"end\": \"10.56.7.254\",\n                    \"start\": \"10.56.4.2\"\n                }\n            ],\n            \"cidr\": \"10.56.4.0/22\",\n            \"dns_nameservers\": [\n\n            ],\n            \"enable_dhcp\": true,\n            \"gateway_ip\": \"10.56.4.1\",\n            \"host_routes\": [\n\n            ],\n            \"id\": \"b0e7435c-1512-45fb-aa9e-9a7c5932fb30\",\n            \"ip_version\": 4,\n            \"name\": \"\",\n            \"network_id\": \"64239a54-dcc4-4b39-920b-b37c2144effa\",\n            \"tenant_id\": \"d19231fc08ec4bc4829b668040d34512\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/subnet_create_request.json",
    "content": "{\"subnet\": {\n    \"ip_version\": 4,\n    \"cidr\": \"10.0.3.0/24\",\n    \"network_id\": \"1234567890\",\n    \"name\": \"jclouds-wibble\"\n}}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/subnet_create_response.json",
    "content": "{\"subnet\": {\n    \"ip_version\": 4,\n    \"cidr\": \"10.0.3.0/24\",\n    \"network_id\": \"1234567890\",\n    \"name\": \"jclouds-wibble\",\n    \"tenant_id\": \"1234567890\",\n    \"id\": \"624312ff-d14b-4ba3-9834-1c78d23d574d\"\n}}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/subnet_get_response.json",
    "content": "{\"subnet\": {\n    \"ip_version\": 4,\n    \"cidr\": \"10.0.3.0/24\",\n    \"network_id\": \"1234567890\",\n    \"name\": \"jclouds-wibble\",\n    \"tenant_id\": \"1234567890\",\n    \"id\": \"624312ff-d14b-4ba3-9834-1c78d23d574d\",\n    \"ipv6_address_mode\": \"slaac\"\n}}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/subnet_list_response.json",
    "content": "{\"subnets\": [\n    {\n        \"ip_version\": 4,\n        \"cidr\": \"10.0.3.0/24\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"16dba3bc-f3fa-4775-afdc-237e12c72f6a\"\n    },\n    {\n        \"ip_version\": 4,\n        \"cidr\": \"10.0.3.0/24\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"wibble\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"1a104cf5-cb18-4d35-9407-2fd2646d9d0b\"\n    },\n    {\n        \"ip_version\": 4,\n        \"cidr\": \"10.0.3.0/24\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"31083ae2-420d-48b2-ac98-9f7a4fd8dbdc\"\n    },\n    {\n        \"ip_version\": 4,\n        \"cidr\": \"10.0.3.0/24\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"49c6d6fa-ff2a-459d-b975-75a8d31c9a89\"\n    },\n    {\n        \"ip_version\": 4,\n        \"cidr\": \"10.0.3.0/24\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"wibble\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"5cb3d6f4-62cb-41c9-b964-ba7d9df79e4e\"\n    },\n    {\n        \"ip_version\": 4,\n        \"cidr\": \"10.0.3.0/24\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"5d51d012-3491-4db7-b1b5-6f254015015d\"\n    },\n    {\n        \"ip_version\": 4,\n        \"cidr\": \"10.0.3.0/24\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"wibble\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"5f9cf7dc-22ca-4097-8e49-1cc8b23faf17\"\n    },\n    {\n        \"ip_version\": 4,\n        \"cidr\": \"10.0.3.0/24\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"6319ecad-6bff-48b2-9b53-02ede8cb7588\"\n    },\n    {\n        \"ip_version\": 4,\n        \"cidr\": \"10.0.3.0/24\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"6ba4c788-661f-49ab-9bf8-5f10cbbb2f57\"\n    },\n    {\n        \"ip_version\": 4,\n        \"cidr\": \"10.0.3.0/24\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"74ed170b-5069-4353-ab38-9719766dc57e\"\n    },\n    {\n        \"ip_version\": 4,\n        \"cidr\": \"10.0.3.0/24\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"wibble\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"b71fcac1-e864-4031-8c5b-edbecd9ece36\"\n    },\n    {\n        \"ip_version\": 4,\n        \"cidr\": \"10.0.3.0/24\",\n        \"network_id\": \"1234567890\",\n        \"name\": \"jclouds-test\",\n        \"tenant_id\": \"1234567890\",\n        \"id\": \"c7681895-d84d-4650-9ca0-82c72036b855\"\n    }\n]}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/subnet_list_response_pages1.json",
    "content": "{\n    \"subnets\": [\n        {\n            \"ip_version\": 4,\n            \"cidr\": \"10.0.3.0/24\",\n            \"network_id\": \"1234567890\",\n            \"name\": \"jclouds-test\",\n            \"tenant_id\": \"1234567890\",\n            \"id\": \"16dba3bc-f3fa-4775-afdc-237e12c72f6a\"\n        },\n        {\n            \"ip_version\": 4,\n            \"cidr\": \"10.0.3.0/24\",\n            \"network_id\": \"1234567890\",\n            \"name\": \"wibble\",\n            \"tenant_id\": \"1234567890\",\n            \"id\": \"1a104cf5-cb18-4d35-9407-2fd2646d9d0b\"\n        }\n    ],\n    \"subnets_links\": [\n        {\n            \"href\": \"/v2.0/subnets.json?marker=71c1e68c-171a-4aa2-aca5-50ea153a3718\",\n            \"rel\": \"next\"\n        },\n        {\n            \"href\": \"/v2.0/subnets.json?marker=396f12f8-521e-4b91-8e21-2e003500433a&page_reverse=True\",\n            \"rel\": \"previous\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/subnet_list_response_pages2.json",
    "content": "{\n    \"subnets\": [\n        {\n            \"ip_version\": 4,\n            \"cidr\": \"10.0.3.0/24\",\n            \"network_id\": \"1234567890\",\n            \"name\": \"jclouds-test\",\n            \"tenant_id\": \"1234567890\",\n            \"id\": \"6319ecad-6bff-48b2-9b53-02ede8cb7588\"\n        },\n        {\n            \"ip_version\": 4,\n            \"cidr\": \"10.0.3.0/24\",\n            \"network_id\": \"1234567890\",\n            \"name\": \"jclouds-test\",\n            \"tenant_id\": \"1234567890\",\n            \"id\": \"6ba4c788-661f-49ab-9bf8-5f10cbbb2f57\"\n        }\n    ],\n    \"subnets_links\": [\n        {\n            \"href\": \"/v2.0/subnets.json?marker=396f12f8-521e-4b91-8e21-2e003500433a&page_reverse=True\",\n            \"rel\": \"previous\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/subnet_update_request.json",
    "content": "{\n    \"subnet\": {\n        \"gateway_ip\": \"10.0.3.254\",\n        \"name\": \"new_name\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-neutron/src/test/resources/subnet_update_response.json",
    "content": "{\n    \"subnet\": {\n        \"name\": \"new_name\",\n        \"network_id\": \"ed2e3c10-2e43-4297-9006-2863a2d1abbc\",\n        \"tenant_id\": \"c1210485b2424d48804aad5d39c61b8f\",\n        \"allocation_pools\": [\n            {\n                \"start\": \"10.0.3.20\",\n                \"end\": \"10.0.3.150\"\n            }\n        ],\n        \"gateway_ip\": \"10.0.3.254\",\n        \"ip_version\": 4,\n        \"cidr\": \"10.0.3.0/24\",\n        \"enable_dhcp\": true,\n        \"id\": \"9436e561-47bf-436a-b1f1-fe23a926e031\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.openstack.nova.v2_0.*;version=\"${project.version}\";-noimport:=true"
  },
  {
    "path": "apis/openstack-nova/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.api</groupId>\n  <artifactId>openstack-nova</artifactId>\n  <name>Apache jclouds :: OpenStack :: Nova API</name>\n  <description>jclouds components to access an implementation of OpenStack Nova</description>\n\n  <properties>\n    <!-- keystone endpoint -->\n    <test.openstack-nova.endpoint>http://localhost:5000/v2.0/</test.openstack-nova.endpoint>\n    <!-- keystone version -->\n    <test.openstack-nova.api-version>2</test.openstack-nova.api-version>\n    <test.openstack-nova.build-version />\n    <test.openstack-nova.identity>FIXME_IDENTITY</test.openstack-nova.identity>\n    <test.openstack-nova.credential>FIXME_CREDENTIALS</test.openstack-nova.credential>\n    <test.openstack-nova.template />\n    <test.jclouds.openstack-nova.auto-allocate-floating-ips>false</test.jclouds.openstack-nova.auto-allocate-floating-ips>\n    <test.jclouds.keystone.credential-type>passwordCredentials</test.jclouds.keystone.credential-type>\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-keystone</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-neutron</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-keystone</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-cinder</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-sshj</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-slf4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>ch.qos.logback</groupId>\n      <artifactId>logback-classic</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.squareup.okhttp3</groupId>\n      <artifactId>mockwebserver</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.value</groupId>\n      <artifactId>auto-value</artifactId>\n      <scope>provided</scope>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.openstack-nova.endpoint>${test.openstack-nova.endpoint}</test.openstack-nova.endpoint>\n                    <test.openstack-nova.api-version>${test.openstack-nova.api-version}</test.openstack-nova.api-version>\n                    <test.openstack-nova.build-version>${test.openstack-nova.build-version}</test.openstack-nova.build-version>\n                    <test.openstack-nova.identity>${test.openstack-nova.identity}</test.openstack-nova.identity>\n                    <test.openstack-nova.credential>${test.openstack-nova.credential}</test.openstack-nova.credential>\n                    <test.openstack-nova.template>${test.openstack-nova.template}</test.openstack-nova.template>\n                    <test.jclouds.openstack-nova.auto-allocate-floating-ips>${test.jclouds.openstack-nova.auto-allocate-floating-ips}</test.jclouds.openstack-nova.auto-allocate-floating-ips>\n                    <test.jclouds.keystone.credential-type>${test.jclouds.keystone.credential-type}</test.jclouds.keystone.credential-type>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n\n</project>\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/NovaApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0;\n\nimport com.google.common.base.Optional;\nimport com.google.inject.Provides;\nimport org.jclouds.location.Region;\nimport org.jclouds.location.functions.RegionToEndpoint;\nimport org.jclouds.openstack.nova.v2_0.extensions.AttachInterfaceApi;\nimport org.jclouds.openstack.nova.v2_0.extensions.AvailabilityZoneApi;\nimport org.jclouds.openstack.nova.v2_0.extensions.ConsolesApi;\nimport org.jclouds.openstack.nova.v2_0.extensions.FlavorExtraSpecsApi;\nimport org.jclouds.openstack.nova.v2_0.extensions.FloatingIPApi;\nimport org.jclouds.openstack.nova.v2_0.extensions.FloatingIPPoolApi;\nimport org.jclouds.openstack.nova.v2_0.extensions.HostAdministrationApi;\nimport org.jclouds.openstack.nova.v2_0.extensions.HostAggregateApi;\nimport org.jclouds.openstack.nova.v2_0.extensions.HypervisorApi;\nimport org.jclouds.openstack.nova.v2_0.extensions.KeyPairApi;\nimport org.jclouds.openstack.nova.v2_0.extensions.QuotaApi;\nimport org.jclouds.openstack.nova.v2_0.extensions.SecurityGroupApi;\nimport org.jclouds.openstack.nova.v2_0.extensions.ServerAdminApi;\nimport org.jclouds.openstack.nova.v2_0.extensions.ServerWithSecurityGroupsApi;\nimport org.jclouds.openstack.nova.v2_0.extensions.SimpleTenantUsageApi;\nimport org.jclouds.openstack.nova.v2_0.extensions.VirtualInterfaceApi;\nimport org.jclouds.openstack.nova.v2_0.extensions.VolumeApi;\nimport org.jclouds.openstack.nova.v2_0.extensions.VolumeAttachmentApi;\nimport org.jclouds.openstack.nova.v2_0.extensions.VolumeTypeApi;\nimport org.jclouds.openstack.nova.v2_0.features.FlavorApi;\nimport org.jclouds.openstack.nova.v2_0.features.ImageApi;\nimport org.jclouds.openstack.nova.v2_0.features.ServerApi;\nimport org.jclouds.openstack.v2_0.features.ExtensionApi;\nimport org.jclouds.rest.annotations.Delegate;\nimport org.jclouds.rest.annotations.EndpointParam;\n\nimport java.io.Closeable;\nimport java.util.Set;\n\n/**\n * Provides access to the OpenStack Compute (Nova) v2 API.\n * <p/>\n *\n */\npublic interface NovaApi extends Closeable {\n   /**\n    *\n    * @return the Region codes configured\n    */\n   @Provides\n   @Region\n   Set<String> getConfiguredRegions();\n\n   /**\n    * Provides access to Server features.\n    */\n   @Delegate\n   ServerApi getServerApi(@EndpointParam(parser = RegionToEndpoint.class) String region);\n\n   /**\n    * Provides access to Flavor features.\n    */\n   @Delegate\n   FlavorApi getFlavorApi(@EndpointParam(parser = RegionToEndpoint.class) String region);\n\n   /**\n    * Provides access to Extension features.\n    */\n   @Delegate\n   ExtensionApi getExtensionApi(@EndpointParam(parser = RegionToEndpoint.class) String region);\n\n   /**\n    * Provides access to Image features.\n    */\n   @Delegate\n   ImageApi getImageApi(@EndpointParam(parser = RegionToEndpoint.class) String region);\n\n   /**\n    * Provides access to Availability Zone features.\n    *\n    * <h3>NOTE</h3>\n    * This API is an extension that may or may not be present in your OpenStack cloud. Use the Optional return type\n    * to determine if it is present.\n    */\n   @Delegate\n   Optional<AvailabilityZoneApi> getAvailabilityZoneApi(\n         @EndpointParam(parser = RegionToEndpoint.class) String region);\n\n   /**\n    * Provides access to Floating IP features.\n    *\n    * <h3>NOTE</h3>\n    * This API is an extension that may or may not be present in your OpenStack cloud. Use the Optional return type\n    * to determine if it is present.\n    */\n   @Delegate\n   Optional<FloatingIPApi> getFloatingIPApi(\n         @EndpointParam(parser = RegionToEndpoint.class) String region);\n\n   /**\n    * Provides access to Security Group features.\n    *\n    * <h3>NOTE</h3>\n    * This API is an extension that may or may not be present in your OpenStack cloud. Use the Optional return type\n    * to determine if it is present.\n    */\n   @Delegate\n   Optional<SecurityGroupApi> getSecurityGroupApi(\n         @EndpointParam(parser = RegionToEndpoint.class) String region);\n\n   /**\n    * Provides access to Key Pair features.\n    *\n    * <h3>NOTE</h3>\n    * This API is an extension that may or may not be present in your OpenStack cloud. Use the Optional return type\n    * to determine if it is present.\n    */\n   @Delegate\n   Optional<KeyPairApi> getKeyPairApi(\n         @EndpointParam(parser = RegionToEndpoint.class) String region);\n\n   /**\n    * Provides access to Host Administration features.\n    *\n    * <h3>NOTE</h3>\n    * This API is an extension that may or may not be present in your OpenStack cloud. Use the Optional return type\n    * to determine if it is present.\n    */\n   @Delegate\n   Optional<HostAdministrationApi> getHostAdministrationApi(\n         @EndpointParam(parser = RegionToEndpoint.class) String region);\n\n   /**\n    * Provides access to Simple Tenant Usage features.\n    *\n    * <h3>NOTE</h3>\n    * This API is an extension that may or may not be present in your OpenStack cloud. Use the Optional return type\n    * to determine if it is present.\n    */\n   @Delegate\n   Optional<SimpleTenantUsageApi> getSimpleTenantUsageApi(\n         @EndpointParam(parser = RegionToEndpoint.class) String region);\n\n   /**\n    * Provides access to Virtual Interface features.\n    *\n    * <h3>NOTE</h3>\n    * This API is an extension that may or may not be present in your OpenStack cloud. Use the Optional return type\n    * to determine if it is present.\n    */\n   @Delegate\n   Optional<VirtualInterfaceApi> getVirtualInterfaceApi(\n         @EndpointParam(parser = RegionToEndpoint.class) String region);\n\n   /**\n    * Provides access to Server Extra Data features.\n    *\n    * <h3>NOTE</h3>\n    * This API is an extension that may or may not be present in your OpenStack cloud. Use the Optional return type\n    * to determine if it is present.\n    */\n   @Delegate\n   Optional<ServerWithSecurityGroupsApi> getServerWithSecurityGroupsApi(\n         @EndpointParam(parser = RegionToEndpoint.class) String region);\n\n   /**\n    * Provides access to Server Admin Actions features.\n    *\n    * <h3>NOTE</h3>\n    * This API is an extension that may or may not be present in your OpenStack cloud. Use the Optional return type\n    * to determine if it is present.\n    */\n   @Delegate\n   Optional<ServerAdminApi> getServerAdminApi(\n         @EndpointParam(parser = RegionToEndpoint.class) String region);\n\n   /**\n    * Provides access to Aggregate features.\n    *\n    * <h3>NOTE</h3>\n    * This API is an extension that may or may not be present in your OpenStack cloud. Use the Optional return type\n    * to determine if it is present.\n    */\n   @Delegate\n   Optional<HostAggregateApi> getHostAggregateApi(\n         @EndpointParam(parser = RegionToEndpoint.class) String region);\n\n   /**\n    * Provides access to Flavor extra specs features.\n    *\n    * <h3>NOTE</h3>\n    * This API is an extension that may or may not be present in your OpenStack cloud. Use the Optional return type\n    * to determine if it is present.\n    */\n   @Delegate\n   Optional<FlavorExtraSpecsApi> getFlavorExtraSpecsApi(\n         @EndpointParam(parser = RegionToEndpoint.class) String region);\n\n   /**\n    * Provides access to Quota features.\n    *\n    * <h3>NOTE</h3>\n    * This API is an extension that may or may not be present in your OpenStack cloud. Use the Optional return type\n    * to determine if it is present.\n    */\n   @Delegate\n   Optional<QuotaApi> getQuotaApi(\n         @EndpointParam(parser = RegionToEndpoint.class) String region);\n\n   /**\n    * Provides access to Hypervisor features.\n    *\n    * <h3>NOTE</h3>\n    * This API is an extension that may or may not be present in your OpenStack cloud. Use the Optional return type\n    * to determine if it is present.\n    */\n   @Delegate\n   Optional<HypervisorApi> getHypervisorApi(\n         @EndpointParam(parser = RegionToEndpoint.class) String region);\n\n   /**\n    * Provides access to Volume features.\n    *\n    * <h3>NOTE</h3>\n    * This API is an extension that may or may not be present in your OpenStack cloud. Use the Optional return type\n    * to determine if it is present.\n    */\n   @Delegate\n   Optional<VolumeApi> getVolumeApi(\n         @EndpointParam(parser = RegionToEndpoint.class) String region);\n\n   /**\n    * Provides access to Volume Attachment features.\n    *\n    * <h3>NOTE</h3>\n    * This API is an extension that may or may not be present in your OpenStack cloud. Use the Optional return type\n    * to determine if it is present.\n    */\n   @Delegate\n   Optional<VolumeAttachmentApi> getVolumeAttachmentApi(\n         @EndpointParam(parser = RegionToEndpoint.class) String region);\n\n   /**\n    * Provides access to Volume Type features.\n    *\n    * <h3>NOTE</h3>\n    * This API is an extension that may or may not be present in your OpenStack cloud. Use the Optional return type\n    * to determine if it is present.\n    */\n   @Delegate\n   Optional<VolumeTypeApi> getVolumeTypeApi(\n         @EndpointParam(parser = RegionToEndpoint.class) String region);\n\n   /**\n    * Provides access to Console features.\n    *\n    * <h3>NOTE</h3>\n    * This API is an extension that may or may not be present in your OpenStack cloud. Use the Optional return type\n    * to determine if it is present.\n    */\n   @Delegate\n   Optional<ConsolesApi> getConsolesApi(\n         @EndpointParam(parser = RegionToEndpoint.class) String region);\n\n   /**\n    * Provides access to Floating IP Pool features.\n    *\n    * <h3>NOTE</h3>\n    * This API is an extension that may or may not be present in your OpenStack cloud. Use the Optional return type\n    * to determine if it is present.\n    */\n   @Delegate\n   Optional<FloatingIPPoolApi> getFloatingIPPoolApi(\n         @EndpointParam(parser = RegionToEndpoint.class) String region);\n\n   /**\n    * Provides access to attach interface features.\n    */\n   @Delegate\n   Optional<AttachInterfaceApi> getAttachInterfaceApi(\n         @EndpointParam(parser = RegionToEndpoint.class) String region);\n\n   /**\n    * @return the Zone codes configured\n    * @deprecated Please use {@link #getConfiguredRegions()} instead. To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   @Provides\n   @Region\n   Set<String> getConfiguredZones();\n\n   /**\n    * Provides access to Server features.\n    * @deprecated Please use {@link #getServerApi(String)} instead. To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   @Delegate\n   ServerApi getServerApiForZone(\n         @EndpointParam(parser = RegionToEndpoint.class) String zone);\n\n   /**\n    * Provides access to Flavor features.\n    * @deprecated Please use {@link #getFlavorApi(String)} instead. To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   @Delegate\n   FlavorApi getFlavorApiForZone(\n         @EndpointParam(parser = RegionToEndpoint.class) String zone);\n\n   /**\n    * Provides access to Extension features.\n    * @deprecated Please use {@link #getExtensionApi(String region)} instead. To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   @Delegate\n   ExtensionApi getExtensionApiForZone(\n         @EndpointParam(parser = RegionToEndpoint.class) String zone);\n\n   /**\n    * Provides access to Image features.\n    * @deprecated Please use {@link #getImageApi(String region)} instead. To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   @Delegate\n   ImageApi getImageApiForZone(\n         @EndpointParam(parser = RegionToEndpoint.class) String zone);\n\n   /**\n    * Provides access to Floating IP features.\n    * @deprecated Please use {@link #getFloatingIPApi(String region)} instead. To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   @Delegate\n   Optional<? extends FloatingIPApi> getFloatingIPExtensionForZone(\n         @EndpointParam(parser = RegionToEndpoint.class) String zone);\n\n   /**\n    * Provides access to Security Group features.\n    * @deprecated Please use {@link #getSecurityGroupApi(String region)} instead. To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   @Delegate\n   Optional<? extends SecurityGroupApi> getSecurityGroupExtensionForZone(\n         @EndpointParam(parser = RegionToEndpoint.class) String zone);\n\n   /**\n    * Provides access to Key Pair features.\n    * @deprecated Please use {@link #getKeyPairApi(String region)} instead. To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   @Delegate\n   Optional<? extends KeyPairApi> getKeyPairExtensionForZone(\n         @EndpointParam(parser = RegionToEndpoint.class) String zone);\n\n   /**\n    * Provides access to Host Administration features.\n    * @deprecated Please use {@link #getHostAdministrationApi(String region)} instead. To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   @Delegate\n   Optional<? extends HostAdministrationApi> getHostAdministrationExtensionForZone(\n         @EndpointParam(parser = RegionToEndpoint.class) String zone);\n\n   /**\n    * Provides access to Simple Tenant Usage features.\n    * @deprecated Please use {@link #getSimpleTenantUsageApi(String region)} instead. To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   @Delegate\n   Optional<? extends SimpleTenantUsageApi> getSimpleTenantUsageExtensionForZone(\n         @EndpointParam(parser = RegionToEndpoint.class) String zone);\n\n   /**\n    * Provides access to Virtual Interface features.\n    * @deprecated Please use {@link #getVirtualInterfaceApi(String region)} instead. To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   @Delegate\n   Optional<? extends VirtualInterfaceApi> getVirtualInterfaceExtensionForZone(\n         @EndpointParam(parser = RegionToEndpoint.class) String zone);\n\n   /**\n    * Provides access to Server Extra Data features.\n    * @deprecated Please use {@link #getServerWithSecurityGroupsApi(String region)} instead. To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   @Delegate\n   Optional<? extends ServerWithSecurityGroupsApi> getServerWithSecurityGroupsExtensionForZone(\n         @EndpointParam(parser = RegionToEndpoint.class) String zone);\n\n   /**\n    * Provides access to Server Admin Actions features.\n    * @deprecated Please use {@link #getServerAdminApi(String region)} instead. To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   @Delegate\n   Optional<? extends ServerAdminApi> getServerAdminExtensionForZone(\n         @EndpointParam(parser = RegionToEndpoint.class) String zone);\n\n   /**\n    * Provides access to Aggregate features.\n    * @deprecated Please use {@link #getHostAggregateApi(String region)} instead. To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   @Delegate\n   Optional<? extends HostAggregateApi> getHostAggregateExtensionForZone(\n         @EndpointParam(parser = RegionToEndpoint.class) String zone);\n\n   /**\n    * Provides access to Flavor extra specs features.\n    * @deprecated Please use {@link #getFlavorExtraSpecsApi(String)} instead. To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   @Delegate\n   Optional<? extends FlavorExtraSpecsApi> getFlavorExtraSpecsExtensionForZone(\n         @EndpointParam(parser = RegionToEndpoint.class) String zone);\n\n   /**\n    * Provides access to Quota features.\n    * @deprecated Please use {@link #getQuotaApi(String region)} instead. To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   @Delegate\n   Optional<? extends QuotaApi> getQuotaExtensionForZone(\n         @EndpointParam(parser = RegionToEndpoint.class) String zone);\n\n   /**\n    * Provides access to Volume features.\n    * @deprecated Please use {@link #getVolumeApi(String region)} instead. To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   @Delegate\n   Optional<? extends VolumeApi> getVolumeExtensionForZone(\n         @EndpointParam(parser = RegionToEndpoint.class) String zone);\n\n   /**\n    * Provides access to Volume Attachment features.\n    * @deprecated Please use {@link #getVolumeAttachmentApi(String region)} instead. To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   @Delegate\n   Optional<? extends VolumeAttachmentApi> getVolumeAttachmentExtensionForZone(\n         @EndpointParam(parser = RegionToEndpoint.class) String zone);\n\n   /**\n    * Provides access to Volume Type features.\n    * @deprecated Please use {@link #getVolumeTypeApi(String region)} instead. To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   @Delegate\n   Optional<? extends VolumeTypeApi> getVolumeTypeExtensionForZone(\n         @EndpointParam(parser = RegionToEndpoint.class) String zone);\n\n   /**\n    * Provides access to Console features.\n    * @deprecated Please use {@link #getConsolesApi(String region)} instead. To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   @Delegate\n   Optional<? extends ConsolesApi> getConsolesExtensionForZone(\n         @EndpointParam(parser = RegionToEndpoint.class) String zone);\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/NovaApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0;\n\nimport static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TEMPLATE;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.CREDENTIAL_TYPE;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.KEYSTONE_VERSION;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.SERVICE_TYPE;\nimport static org.jclouds.openstack.nova.v2_0.config.NovaProperties.AUTO_ALLOCATE_FLOATING_IPS;\nimport static org.jclouds.openstack.nova.v2_0.config.NovaProperties.AUTO_GENERATE_KEYPAIRS;\nimport static org.jclouds.openstack.nova.v2_0.config.NovaProperties.TIMEOUT_SECURITYGROUP_PRESENT;\nimport static org.jclouds.reflect.Reflection2.typeToken;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.openstack.keystone.auth.config.AuthenticationModule;\nimport org.jclouds.openstack.keystone.auth.config.CredentialTypes;\nimport org.jclouds.openstack.keystone.catalog.config.ServiceCatalogModule;\nimport org.jclouds.openstack.keystone.catalog.config.ServiceCatalogModule.RegionModule;\nimport org.jclouds.openstack.nova.v2_0.compute.config.NovaComputeServiceContextModule;\nimport org.jclouds.openstack.nova.v2_0.config.NovaHttpApiModule;\nimport org.jclouds.openstack.nova.v2_0.config.NovaParserModule;\nimport org.jclouds.openstack.v2_0.ServiceType;\nimport org.jclouds.rest.internal.BaseHttpApiMetadata;\n\nimport com.google.auto.service.AutoService;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n/**\n * Implementation of {@link ApiMetadata} for Nova 2.0 API\n */\n@AutoService(ApiMetadata.class)\npublic class NovaApiMetadata extends BaseHttpApiMetadata<NovaApi>  {\n\n   @Override\n   public Builder toBuilder() {\n      return new Builder().fromApiMetadata(this);\n   }\n\n   public NovaApiMetadata() {\n      this(new Builder());\n   }\n\n   protected NovaApiMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = BaseHttpApiMetadata.defaultProperties();\n      // auth fail can happen while cloud-init applies keypair updates\n      properties.setProperty(\"jclouds.ssh.max-retries\", \"7\");\n      properties.setProperty(\"jclouds.ssh.retry-auth\", \"true\");\n      properties.setProperty(SERVICE_TYPE, ServiceType.COMPUTE);\n      properties.setProperty(CREDENTIAL_TYPE, CredentialTypes.PASSWORD_CREDENTIALS);\n      properties.setProperty(KEYSTONE_VERSION, \"2\");\n      properties.setProperty(AUTO_ALLOCATE_FLOATING_IPS, \"false\");\n      properties.setProperty(AUTO_GENERATE_KEYPAIRS, \"false\");\n      properties.setProperty(TIMEOUT_SECURITYGROUP_PRESENT, \"500\");\n      // Keystone 1.1 expires tokens after 24 hours and allows renewal 1 hour\n      // before expiry by default.  We choose a value less than the latter\n      // since the former persists between jclouds invocations.\n      properties.setProperty(PROPERTY_SESSION_INTERVAL, 30 * 60 + \"\");\n      properties.put(TEMPLATE, \"osFamily=UBUNTU,os64Bit=true,osVersionMatches=16.*\");\n      return properties;\n   }\n\n   public static class Builder extends BaseHttpApiMetadata.Builder<NovaApi, Builder> {\n\n      protected Builder() {\n          id(\"openstack-nova\")\n         .name(\"OpenStack Nova Diablo+ API\")\n         .identityName(\"${tenantName}:${userName} or ${userName}, if your keystone supports a default tenant\")\n         .credentialName(\"${password}\")\n         .endpointName(\"Keystone base url ending in /v2.0/\")\n         .documentation(URI.create(\"http://api.openstack.org/\"))\n         .version(\"2\")\n         .defaultEndpoint(\"http://localhost:5000/v2.0/\")\n         .defaultProperties(NovaApiMetadata.defaultProperties())\n         .view(typeToken(ComputeServiceContext.class))\n         .defaultModules(ImmutableSet.<Class<? extends Module>>builder()\n                                     .add(AuthenticationModule.class)\n                                     .add(ServiceCatalogModule.class)\n                                     .add(RegionModule.class)\n                                     .add(NovaParserModule.class)\n                                     .add(NovaHttpApiModule.class)\n                                     .add(NovaComputeServiceContextModule.class).build());\n      }\n\n      @Override\n      public NovaApiMetadata build() {\n         return new NovaApiMetadata(this);\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/binders/BindConsoleToJsonPayload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.binders;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.json.Json;\nimport org.jclouds.openstack.nova.v2_0.domain.Console;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSortedMap;\n\n@Singleton\npublic class BindConsoleToJsonPayload extends BindToJsonPayload {\n\n   @Inject\n   public BindConsoleToJsonPayload(Json jsonBinder) {\n      super(jsonBinder);\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      String action;\n\n      Console.Type type = (Console.Type) postParams.get(\"type\");\n\n      switch (type) {\n         case NOVNC:\n         case XVPVNC:\n            action = \"os-getVNCConsole\";\n            break;\n         case SPICE_HTML5:\n            action = \"os-getSPICEConsole\";\n            break;\n         case RDP_HTML5:\n            action = \"os-getRDPConsole\";\n            break;\n         default:\n            throw new IllegalArgumentException(\"Invalid type: \" + type);\n      }\n\n      return bindToRequest(request, ImmutableMap.of(action, ImmutableSortedMap.copyOf(postParams)));\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/binders/BindKeyPairToJsonPayload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.binders;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.json.Json;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSortedMap;\n\n@Singleton\npublic class BindKeyPairToJsonPayload extends BindToJsonPayload {\n\n   @Inject\n   public BindKeyPairToJsonPayload(Json jsonBinder) {\n      super(jsonBinder);\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      return bindToRequest(request, (Object) ImmutableMap.of(\"keypair\", ImmutableSortedMap.copyOf(postParams)));\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/binders/BindMetadataToJsonPayload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.binders;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.json.Json;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport com.google.common.collect.ImmutableMap;\n\n@Singleton\npublic class BindMetadataToJsonPayload extends BindToJsonPayload {\n\n   @Inject\n   public BindMetadataToJsonPayload(Json jsonBinder) {\n      super(jsonBinder);\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      return bindToRequest(request,\n               (Object) ImmutableMap.of(\"metadata\", ImmutableMap.of(postParams.get(\"key\"), postParams.get(\"value\"))));\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/binders/BindSecurityGroupRuleToJsonPayload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Predicates.instanceOf;\nimport static com.google.common.collect.Iterables.find;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.json.Json;\nimport org.jclouds.openstack.nova.v2_0.domain.Ingress;\nimport org.jclouds.rest.MapBinder;\nimport org.jclouds.rest.binders.BindToJsonPayload;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMap.Builder;\n\n@Singleton\npublic class BindSecurityGroupRuleToJsonPayload extends BindToJsonPayload implements MapBinder {\n   @Inject\n   public BindSecurityGroupRuleToJsonPayload(Json jsonBinder) {\n      super(jsonBinder);\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      Builder<String, Object> payload = ImmutableMap.builder();\n      payload.putAll(postParams);\n      checkArgument(checkNotNull(request, \"request\") instanceof GeneratedHttpRequest,\n               \"this binder is only valid for GeneratedHttpRequests!\");\n      GeneratedHttpRequest gRequest = (GeneratedHttpRequest) request;\n\n      Ingress ingress = Ingress.class.cast(find(gRequest.getInvocation().getArgs(), instanceOf(Ingress.class)));\n      payload.put(\"ip_protocol\", ingress.getIpProtocol().toString());\n      payload.put(\"from_port\", ingress.getFromPort() + \"\");\n      payload.put(\"to_port\", ingress.getToPort() + \"\");\n\n      return super.bindToRequest(request, ImmutableMap.of(\"security_group_rule\", payload.build()));\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/NovaComputeService.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.compute;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_RUNNING;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_SUSPENDED;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_TERMINATED;\n\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Provider;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Constants;\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.compute.callables.RunScriptOnNode;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.TemplateBuilder;\nimport org.jclouds.compute.extensions.ImageExtension;\nimport org.jclouds.compute.extensions.SecurityGroupExtension;\nimport org.jclouds.compute.extensions.internal.DelegatingImageExtension;\nimport org.jclouds.compute.internal.BaseComputeService;\nimport org.jclouds.compute.internal.PersistNodeCredentials;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.compute.strategy.CreateNodesInGroupThenAddToSet;\nimport org.jclouds.compute.strategy.DestroyNodeStrategy;\nimport org.jclouds.compute.strategy.GetImageStrategy;\nimport org.jclouds.compute.strategy.GetNodeMetadataStrategy;\nimport org.jclouds.compute.strategy.InitializeRunScriptOnNodeOrPlaceInBadMap;\nimport org.jclouds.compute.strategy.ListNodesStrategy;\nimport org.jclouds.compute.strategy.RebootNodeStrategy;\nimport org.jclouds.compute.strategy.ResumeNodeStrategy;\nimport org.jclouds.compute.strategy.SuspendNodeStrategy;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.domain.Location;\nimport org.jclouds.openstack.nova.v2_0.compute.functions.CleanupResources;\nimport org.jclouds.openstack.nova.v2_0.compute.options.NovaTemplateOptions;\nimport org.jclouds.scriptbuilder.functions.InitAdminAccess;\n\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.util.concurrent.ListeningExecutorService;\n\n@Singleton\npublic class NovaComputeService extends BaseComputeService {\n   protected final CleanupResources cleanupResources;\n\n   @Inject\n   protected NovaComputeService(ComputeServiceContext context, Map<String, Credentials> credentialStore,\n         @Memoized Supplier<Set<? extends Image>> images, @Memoized Supplier<Set<? extends Hardware>> sizes,\n         @Memoized Supplier<Set<? extends Location>> locations, ListNodesStrategy listNodesStrategy,\n         GetImageStrategy getImageStrategy, GetNodeMetadataStrategy getNodeMetadataStrategy,\n         CreateNodesInGroupThenAddToSet runNodesAndAddToSetStrategy, RebootNodeStrategy rebootNodeStrategy,\n         DestroyNodeStrategy destroyNodeStrategy, ResumeNodeStrategy startNodeStrategy,\n         SuspendNodeStrategy stopNodeStrategy, Provider<TemplateBuilder> templateBuilderProvider,\n         @Named(\"DEFAULT\") Provider<TemplateOptions> templateOptionsProvider,\n         @Named(TIMEOUT_NODE_RUNNING) Predicate<AtomicReference<NodeMetadata>> nodeRunning,\n         @Named(TIMEOUT_NODE_TERMINATED) Predicate<AtomicReference<NodeMetadata>> nodeTerminated,\n         @Named(TIMEOUT_NODE_SUSPENDED) Predicate<AtomicReference<NodeMetadata>> nodeSuspended,\n         InitializeRunScriptOnNodeOrPlaceInBadMap.Factory initScriptRunnerFactory,\n         RunScriptOnNode.Factory runScriptOnNodeFactory, InitAdminAccess initAdminAccess,\n         PersistNodeCredentials persistNodeCredentials,\n         @Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor,\n         CleanupResources cleanupResources, Optional<ImageExtension> imageExtension,\n         Optional<SecurityGroupExtension> securityGroupExtension,\n         DelegatingImageExtension.Factory delegatingImageExtension) {\n      super(context, credentialStore, images, sizes, locations, listNodesStrategy, getImageStrategy,\n            getNodeMetadataStrategy, runNodesAndAddToSetStrategy, rebootNodeStrategy, destroyNodeStrategy,\n            startNodeStrategy, stopNodeStrategy, templateBuilderProvider, templateOptionsProvider, nodeRunning,\n            nodeTerminated, nodeSuspended, initScriptRunnerFactory, initAdminAccess, runScriptOnNodeFactory,\n            persistNodeCredentials, userExecutor, imageExtension, securityGroupExtension, delegatingImageExtension);\n      this.cleanupResources = checkNotNull(cleanupResources, \"cleanupResources\");\n\n   }\n\n   @Override\n   protected void cleanUpIncidentalResourcesOfDeadNodes(Set<? extends NodeMetadata> deadNodes) {\n      for (NodeMetadata deadNode : deadNodes) {\n         cleanupResources.apply(deadNode);\n      }\n   }\n\n   /**\n    * returns template options, except of type {@link NovaTemplateOptions}.\n    */\n   @Override\n   public NovaTemplateOptions templateOptions() {\n      return NovaTemplateOptions.class.cast(super.templateOptions());\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/NovaComputeServiceAdapter.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.compute;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.common.collect.Iterables.contains;\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.transform;\nimport static java.lang.String.format;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_RUNNING;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_TERMINATED;\nimport static org.jclouds.compute.util.ComputeServiceUtils.metadataAndTagsAsCommaDelimitedValue;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\n\nimport org.jclouds.compute.ComputeServiceAdapter;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.location.Region;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.openstack.nova.v2_0.NovaApi;\nimport org.jclouds.openstack.nova.v2_0.compute.functions.CleanupResources;\nimport org.jclouds.openstack.nova.v2_0.compute.functions.RemoveFloatingIpFromNodeAndDeallocate;\nimport org.jclouds.openstack.nova.v2_0.compute.options.NovaTemplateOptions;\nimport org.jclouds.openstack.nova.v2_0.compute.strategy.ApplyNovaTemplateOptionsCreateNodesWithGroupEncodedIntoNameThenAddToSet;\nimport org.jclouds.openstack.nova.v2_0.domain.Flavor;\nimport org.jclouds.openstack.nova.v2_0.domain.Image;\nimport org.jclouds.openstack.nova.v2_0.domain.RebootType;\nimport org.jclouds.openstack.nova.v2_0.domain.Server;\nimport org.jclouds.openstack.nova.v2_0.domain.ServerCreated;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.FlavorInRegion;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.ImageInRegion;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.RegionAndId;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.ServerInRegion;\nimport org.jclouds.openstack.nova.v2_0.options.CreateServerOptions;\nimport org.jclouds.openstack.nova.v2_0.predicates.ImagePredicates;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Splitter;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\nimport com.google.common.collect.Sets;\n\n/**\n * The adapter used by the NovaComputeServiceContextModule to interface the nova-specific domain\n * model to the computeService generic domain model.\n */\npublic class NovaComputeServiceAdapter implements\n         ComputeServiceAdapter<ServerInRegion, FlavorInRegion, ImageInRegion, Location> {\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   protected final NovaApi novaApi;\n   protected final Supplier<Set<String>> regionIds;\n   protected final RemoveFloatingIpFromNodeAndDeallocate removeFloatingIpFromNodeAndDeallocate;\n   private final Predicate<RegionAndId> serverRunningPredicate;\n   private final Predicate<RegionAndId> serverTerminatedPredicate;\n   private final CleanupResources cleanupResources;\n\n   @Inject\n   public NovaComputeServiceAdapter(NovaApi novaApi, @Region Supplier<Set<String>> regionIds,\n                                    RemoveFloatingIpFromNodeAndDeallocate removeFloatingIpFromNodeAndDeallocate,\n                                    @Named(TIMEOUT_NODE_RUNNING) Predicate<RegionAndId> serverRunningPredicate,\n                                    @Named(TIMEOUT_NODE_TERMINATED) Predicate<RegionAndId> serverTerminatedPredicate,\n                                    CleanupResources cleanupResources) {\n      this.novaApi = checkNotNull(novaApi, \"novaApi\");\n      this.regionIds = checkNotNull(regionIds, \"regionIds\");\n      this.removeFloatingIpFromNodeAndDeallocate = checkNotNull(removeFloatingIpFromNodeAndDeallocate,\n               \"removeFloatingIpFromNodeAndDeallocate\");\n      this.serverRunningPredicate = serverRunningPredicate;\n      this.serverTerminatedPredicate = serverTerminatedPredicate;\n      this.cleanupResources = cleanupResources;\n   }\n\n   /**\n    * Note that we do not validate extensions here, on basis that\n    * {@link ApplyNovaTemplateOptionsCreateNodesWithGroupEncodedIntoNameThenAddToSet} has already\n    * done so.\n    */\n   @Override\n   public NodeAndInitialCredentials<ServerInRegion> createNodeWithGroupEncodedIntoName(String group, String name,\n            Template template) {\n      final String regionId = template.getLocation().getId();\n      String imageId = template.getImage().getProviderId();\n      String flavorId = template.getHardware().getProviderId();\n      NovaTemplateOptions templateOptions = template.getOptions().as(NovaTemplateOptions.class);\n\n      CreateServerOptions options = new CreateServerOptions();\n      Map<String, String> metadataAndTagsAsCommaDelimitedValue = metadataAndTagsAsCommaDelimitedValue(template.getOptions());\n      options.metadata(metadataAndTagsAsCommaDelimitedValue);\n      if (!templateOptions.getGroups().isEmpty()) options.securityGroupNames(templateOptions.getGroups());\n      options.userData(templateOptions.getUserData());\n      options.diskConfig(templateOptions.getDiskConfig());\n      options.configDrive(templateOptions.getConfigDrive());\n      options.availabilityZone(templateOptions.getAvailabilityZone());\n      \n      if (templateOptions.getNovaNetworks() != null) {\n         options.novaNetworks(templateOptions.getNovaNetworks());\n      }\n      if (templateOptions.getNetworks() != null) {\n         options.networks(templateOptions.getNetworks());\n      }\n\n      if (templateOptions.getKeyPairName() != null) {\n         options.keyPairName(templateOptions.getKeyPairName());\n      }\n      if (!templateOptions.getBlockDeviceMappings().isEmpty()) options.blockDeviceMappings(templateOptions.getBlockDeviceMappings());\n\n      logger.debug(\">> creating new server region(%s) name(%s) image(%s) flavor(%s) options(%s)\", regionId, name, imageId, flavorId, options);\n      final ServerCreated lightweightServer = novaApi.getServerApi(regionId).create(name, imageId, flavorId, options);\n      if (!serverRunningPredicate.apply(RegionAndId.fromRegionAndId(regionId, lightweightServer.getId()))) {\n         final String message = format(\"Server %s was not created within %sms. The resources created for it will be destroyed\", name, \"30 * 60\");\n         logger.warn(message);\n         String tagString = metadataAndTagsAsCommaDelimitedValue.get(\"jclouds_tags\");\n         Set<String> tags = Sets.newHashSet(Splitter.on(',').split(tagString));\n         cleanupResources.removeSecurityGroupCreatedByJcloudsAndInvalidateCache(tags);\n         throw new IllegalStateException(message);\n      }\n      logger.trace(\"<< server(%s)\", lightweightServer.getId());\n\n      Server server = novaApi.getServerApi(regionId).get(lightweightServer.getId());\n      ServerInRegion serverInRegion = new ServerInRegion(server, regionId);\n\n      LoginCredentials.Builder credentialsBuilder = LoginCredentials.builder();\n      if (templateOptions.getLoginPrivateKey() != null) {\n         credentialsBuilder.privateKey(templateOptions.getLoginPrivateKey());\n      } \n      if (lightweightServer.getAdminPass().isPresent()) {\n         credentialsBuilder.password(lightweightServer.getAdminPass().get());\n      }\n      return new NodeAndInitialCredentials<ServerInRegion>(serverInRegion, serverInRegion.slashEncode(), credentialsBuilder\n               .build());\n   }\n\n  @Override\n   public Iterable<FlavorInRegion> listHardwareProfiles() {\n      Builder<FlavorInRegion> builder = ImmutableSet.builder();\n      for (final String regionId : regionIds.get()) {\n         builder.addAll(transform(novaApi.getFlavorApi(regionId).listInDetail().concat(),\n                  new Function<Flavor, FlavorInRegion>() {\n\n                     @Override\n                     public FlavorInRegion apply(Flavor arg0) {\n                        return new FlavorInRegion(arg0, regionId);\n                     }\n\n                  }));\n      }\n      return builder.build();\n   }\n\n   @Override\n   public Iterable<ImageInRegion> listImages() {\n      Builder<ImageInRegion> builder = ImmutableSet.builder();\n      Set<String> regions = regionIds.get();\n      checkState(!regions.isEmpty(), \"no regions found in supplier %s\", regionIds);\n      for (final String regionId : regions) {\n         Set<? extends Image> images = novaApi.getImageApi(regionId).listInDetail().concat().toSet();\n         if (images.isEmpty()) {\n            logger.debug(\"no images found in region %s\", regionId);\n            continue;\n         }\n         Iterable<? extends Image> active = filter(images, ImagePredicates.statusEquals(Image.Status.ACTIVE));\n         if (images.isEmpty()) {\n            logger.debug(\"no images with status active in region %s; non-active: %s\", regionId,\n                     transform(active, new Function<Image, String>() {\n\n                        @Override\n                        public String apply(Image input) {\n                           return MoreObjects.toStringHelper(\"\").add(\"id\", input.getId()).add(\"status\", input.getStatus())\n                                    .toString();\n                        }\n\n                     }));\n            continue;\n         }\n         builder.addAll(transform(active, new Function<Image, ImageInRegion>() {\n\n            @Override\n            public ImageInRegion apply(Image arg0) {\n               return new ImageInRegion(arg0, regionId);\n            }\n\n         }));\n      }\n      return builder.build();\n   }\n\n   @Override\n   public Iterable<ServerInRegion> listNodes() {\n      Builder<ServerInRegion> builder = ImmutableSet.builder();\n      for (final String regionId : regionIds.get()) {\n         builder.addAll(novaApi.getServerApi(regionId).listInDetail().concat()\n                  .transform(new Function<Server, ServerInRegion>() {\n\n                     @Override\n                     public ServerInRegion apply(Server arg0) {\n                        return new ServerInRegion(arg0, regionId);\n                     }\n\n                  }));\n      }\n      return builder.build();\n   }\n\n   @Override\n   public Iterable<ServerInRegion> listNodesByIds(final Iterable<String> ids) {\n      return filter(listNodes(), new Predicate<ServerInRegion>() {\n\n            @Override\n            public boolean apply(ServerInRegion server) {\n               return contains(ids, server.slashEncode());\n            }\n         });\n   }\n\n   @Override\n   public Iterable<Location> listLocations() {\n      // locations provided by keystone\n      return ImmutableSet.of();\n   }\n\n   @Override\n   public ServerInRegion getNode(String id) {\n      RegionAndId regionAndId = RegionAndId.fromSlashEncoded(id);\n      Server server = novaApi.getServerApi(regionAndId.getRegion()).get(regionAndId.getId());\n      return server == null ? null : new ServerInRegion(server, regionAndId.getRegion());\n   }\n\n   @Override\n   public ImageInRegion getImage(String id) {\n      RegionAndId regionAndId = RegionAndId.fromSlashEncoded(id);\n      Image image = novaApi.getImageApi(regionAndId.getRegion()).get(regionAndId.getId());\n      return image == null ? null : new ImageInRegion(image, regionAndId.getRegion());\n   }\n\n   @Override\n   public void destroyNode(String id) {\n      RegionAndId regionAndId = RegionAndId.fromSlashEncoded(id);\n      novaApi.getServerApi(regionAndId.getRegion()).delete(regionAndId.getId());\n      checkState(serverTerminatedPredicate.apply(regionAndId), \"server was not destroyed in the configured timeout\");\n   }\n\n   @Override\n   public void rebootNode(String id) {\n      RegionAndId regionAndId = RegionAndId.fromSlashEncoded(id);\n      novaApi.getServerApi(regionAndId.getRegion()).reboot(regionAndId.getId(), RebootType.HARD);\n   }\n\n   @Override\n   public void resumeNode(String id) {\n      RegionAndId regionAndId = RegionAndId.fromSlashEncoded(id);\n      if (novaApi.getServerAdminApi(regionAndId.getRegion()).isPresent()) {\n         novaApi.getServerAdminApi(regionAndId.getRegion()).get().resume(regionAndId.getId());\n      } else {\n         throw new UnsupportedOperationException(\"resume requires installation of the Admin Actions extension\");\n      }\n   }\n\n   @Override\n   public void suspendNode(String id) {\n      RegionAndId regionAndId = RegionAndId.fromSlashEncoded(id);\n      if (novaApi.getServerAdminApi(regionAndId.getRegion()).isPresent()) {\n         novaApi.getServerAdminApi(regionAndId.getRegion()).get().suspend(regionAndId.getId());\n      } else {\n         throw new UnsupportedOperationException(\"suspend requires installation of the Admin Actions extension\");\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/config/NovaComputeServiceContextModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.compute.config;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_RUNNING;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_TERMINATED;\nimport static org.jclouds.openstack.nova.v2_0.config.NovaProperties.AUTO_ALLOCATE_FLOATING_IPS;\nimport static org.jclouds.openstack.nova.v2_0.config.NovaProperties.AUTO_GENERATE_KEYPAIRS;\nimport static org.jclouds.util.Predicates2.retry;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport com.google.inject.Inject;\nimport com.google.inject.Provider;\nimport com.google.inject.assistedinject.FactoryModuleBuilder;\nimport org.jclouds.Context;\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.ComputeService;\nimport org.jclouds.compute.ComputeServiceAdapter;\nimport org.jclouds.compute.config.ComputeServiceAdapterContextModule;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.SecurityGroup;\nimport org.jclouds.compute.extensions.ImageExtension;\nimport org.jclouds.compute.extensions.SecurityGroupExtension;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.compute.strategy.impl.CreateNodesWithGroupEncodedIntoNameThenAddToSet;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.functions.IdentityFunction;\nimport org.jclouds.openstack.nova.v2_0.NovaApi;\nimport org.jclouds.openstack.nova.v2_0.compute.NovaComputeService;\nimport org.jclouds.openstack.nova.v2_0.compute.NovaComputeServiceAdapter;\nimport org.jclouds.openstack.nova.v2_0.compute.extensions.NeutronSecurityGroupExtension;\nimport org.jclouds.openstack.nova.v2_0.compute.extensions.NovaImageExtension;\nimport org.jclouds.openstack.nova.v2_0.compute.extensions.NovaSecurityGroupExtension;\nimport org.jclouds.openstack.nova.v2_0.compute.functions.CleanupResources;\nimport org.jclouds.openstack.nova.v2_0.compute.functions.CreateSecurityGroupIfNeeded;\nimport org.jclouds.openstack.nova.v2_0.compute.functions.FlavorInRegionToHardware;\nimport org.jclouds.openstack.nova.v2_0.compute.functions.ImageInRegionToImage;\nimport org.jclouds.openstack.nova.v2_0.compute.functions.ImageToOperatingSystem;\nimport org.jclouds.openstack.nova.v2_0.compute.functions.NeutronSecurityGroupToSecurityGroup;\nimport org.jclouds.openstack.nova.v2_0.compute.functions.NovaSecurityGroupInRegionToSecurityGroup;\nimport org.jclouds.openstack.nova.v2_0.compute.functions.NovaSecurityGroupToSecurityGroup;\nimport org.jclouds.openstack.nova.v2_0.compute.functions.OrphanedGroupsByRegionId;\nimport org.jclouds.openstack.nova.v2_0.compute.functions.ServerInRegionToNodeMetadata;\nimport org.jclouds.openstack.nova.v2_0.compute.loaders.FindSecurityGroupOrCreate;\nimport org.jclouds.openstack.nova.v2_0.compute.loaders.LoadFloatingIpsForInstance;\nimport org.jclouds.openstack.nova.v2_0.compute.options.NovaTemplateOptions;\nimport org.jclouds.openstack.nova.v2_0.compute.strategy.ApplyNovaTemplateOptionsCreateNodesWithGroupEncodedIntoNameThenAddToSet;\nimport org.jclouds.openstack.nova.v2_0.domain.FloatingIpForServer;\nimport org.jclouds.openstack.nova.v2_0.domain.Server;\nimport org.jclouds.openstack.nova.v2_0.domain.Server.Status;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.FlavorInRegion;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.ImageInRegion;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.RegionAndId;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.RegionAndName;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.RegionSecurityGroupNameAndPorts;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.SecurityGroupInRegion;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.ServerInRegion;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Maps;\nimport com.google.common.collect.Multimap;\nimport com.google.inject.Injector;\nimport com.google.inject.Key;\nimport com.google.inject.Provides;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.name.Names;\n\n/**\n * Module for building a compute service context for Nova\n */\npublic class NovaComputeServiceContextModule extends\n         ComputeServiceAdapterContextModule<ServerInRegion, FlavorInRegion, ImageInRegion, Location> {\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   protected void configure() {\n      super.configure();\n      bind(new TypeLiteral<ComputeServiceAdapter<ServerInRegion, FlavorInRegion, ImageInRegion, Location>>() {\n      }).to(NovaComputeServiceAdapter.class);\n\n      bind(ComputeService.class).to(NovaComputeService.class);\n\n      bind(new TypeLiteral<Function<ServerInRegion, NodeMetadata>>() {\n      }).to(ServerInRegionToNodeMetadata.class);\n\n      bind(new TypeLiteral<Function<SecurityGroupInRegion, SecurityGroup>>() {\n      }).to(NovaSecurityGroupInRegionToSecurityGroup.class);\n\n      bind(new TypeLiteral<Function<Set<? extends NodeMetadata>,  Multimap<String, String>>>() {\n      }).to(OrphanedGroupsByRegionId.class);\n\n      bind(new TypeLiteral<Function<ImageInRegion, Image>>() {\n      }).to(ImageInRegionToImage.class);\n      bind(new TypeLiteral<Function<org.jclouds.openstack.nova.v2_0.domain.Image, OperatingSystem>>() {\n      }).to(ImageToOperatingSystem.class);\n\n      bind(new TypeLiteral<Function<FlavorInRegion, Hardware>>() {\n      }).to(FlavorInRegionToHardware.class);\n\n      // we aren't converting location from a provider-specific type\n      bind(new TypeLiteral<Function<Location, Location>>() {\n      }).to(Class.class.cast(IdentityFunction.class));\n\n      bind(TemplateOptions.class).to(NovaTemplateOptions.class);\n\n      bind(new TypeLiteral<CacheLoader<RegionAndId, Iterable<? extends FloatingIpForServer>>>() {\n      }).annotatedWith(Names.named(\"FLOATINGIP\")).to(LoadFloatingIpsForInstance.class);\n\n      bind(new TypeLiteral<Function<RegionSecurityGroupNameAndPorts, SecurityGroup>>() {\n      }).to(CreateSecurityGroupIfNeeded.class);\n\n      bind(new TypeLiteral<CacheLoader<RegionAndName, SecurityGroup>>() {\n      }).to(FindSecurityGroupOrCreate.class);\n\n      bind(CreateNodesWithGroupEncodedIntoNameThenAddToSet.class).to(\n               ApplyNovaTemplateOptionsCreateNodesWithGroupEncodedIntoNameThenAddToSet.class);\n\n      bind(new TypeLiteral<ImageExtension>() {\n      }).to(NovaImageExtension.class);\n\n      bind(new TypeLiteral<Function<NodeMetadata, Boolean>>() {\n      }).to(CleanupResources.class);\n\n      install(new FactoryModuleBuilder().build(NeutronSecurityGroupToSecurityGroup.Factory.class));\n      install(new FactoryModuleBuilder().build(NovaSecurityGroupToSecurityGroup.Factory.class));\n\n      bind(new TypeLiteral<SecurityGroupExtension>() {\n      }).toProvider(SecurityGroupExtensionProvider.class);\n\n   }\n\n   @Singleton\n   public static class SecurityGroupExtensionProvider implements Provider<SecurityGroupExtension> {\n      @Inject(optional = true)\n      @Named(\"openstack-neutron\")\n      protected Supplier<Context> neutronApiContextSupplier;\n\n      private final NeutronSecurityGroupExtension neutronSecurityGroupExtension;\n      private final NovaSecurityGroupExtension novaSecurityGroupExtension;\n\n      @Inject\n      SecurityGroupExtensionProvider(NeutronSecurityGroupExtension neutronSecurityGroupExtension,\n                                            NovaSecurityGroupExtension novaSecurityGroupExtension) {\n         this.neutronSecurityGroupExtension = neutronSecurityGroupExtension;\n         this.novaSecurityGroupExtension = novaSecurityGroupExtension;\n      }\n\n      @Override\n      public SecurityGroupExtension get() {\n         return neutronApiContextSupplier != null ? neutronSecurityGroupExtension : novaSecurityGroupExtension;\n      }\n   }\n\n   @Override\n   protected TemplateOptions provideTemplateOptions(Injector injector, TemplateOptions options) {\n      return options.as(NovaTemplateOptions.class)\n            .autoAssignFloatingIp(injector.getInstance(\n                  Key.get(boolean.class, Names.named(AUTO_ALLOCATE_FLOATING_IPS))))\n            .generateKeyPair(injector.getInstance(\n                  Key.get(boolean.class, Names.named(AUTO_GENERATE_KEYPAIRS))));\n   }\n\n   @Provides\n   @com.google.inject.name.Named(TIMEOUT_NODE_RUNNING)\n   protected Predicate<RegionAndId> provideServerRunningPredicate(final NovaApi api,\n                                                             ComputeServiceConstants.Timeouts timeouts,\n                                                             ComputeServiceConstants.PollPeriod pollPeriod) {\n      return retry(new ServerInStatusPredicate(api, Status.ACTIVE), timeouts.nodeRunning,\n              pollPeriod.pollInitialPeriod, pollPeriod.pollMaxPeriod);\n   }\n\n   @Provides\n   @com.google.inject.name.Named(TIMEOUT_NODE_TERMINATED)\n   protected Predicate<RegionAndId> provideServerTerminatedPredicate(final NovaApi api, ComputeServiceConstants.Timeouts timeouts,\n                                                                ComputeServiceConstants.PollPeriod pollPeriod) {\n      return retry(new ServerTerminatedPredicate(api), timeouts.nodeTerminated, pollPeriod.pollInitialPeriod,\n              pollPeriod.pollMaxPeriod);\n   }\n\n   @Provides\n   @Singleton\n   @Named(\"FLOATINGIP\")\n   protected final LoadingCache<RegionAndId, Iterable<? extends FloatingIpForServer>> instanceToFloatingIps(\n            @Named(\"FLOATINGIP\") CacheLoader<RegionAndId, Iterable<? extends FloatingIpForServer>> in) {\n      return CacheBuilder.newBuilder().build(in);\n   }\n\n   @Provides\n   @Singleton\n   protected final LoadingCache<RegionAndName, SecurityGroup> securityGroupMap(\n           CacheLoader<RegionAndName, SecurityGroup> in) {\n      return CacheBuilder.newBuilder().build(in);\n   }\n\n   @Override\n   protected Map<OsFamily, LoginCredentials> osFamilyToCredentials(Injector injector) {\n      return ImmutableMap.of(OsFamily.WINDOWS, LoginCredentials.builder().user(\"Administrator\").build(),\n               OsFamily.UBUNTU, LoginCredentials.builder().user(\"ubuntu\").build());\n   }\n\n   @Provides\n   @Singleton\n   protected final Supplier<Map<String, Location>> createLocationIndexedById(\n            @Memoized Supplier<Set<? extends Location>> locations) {\n      return Suppliers.compose(new Function<Set<? extends Location>, Map<String, Location>>() {\n\n         @SuppressWarnings(\"unchecked\")\n         @Override\n         public Map<String, Location> apply(Set<? extends Location> arg0) {\n            // TODO: find a nice way to get rid of this cast.\n            Iterable<Location> locations = (Iterable<Location>) arg0;\n            return Maps.uniqueIndex(locations, new Function<Location, String>() {\n\n               @Override\n               public String apply(Location arg0) {\n                  return arg0.getId();\n               }\n\n            });\n         }\n      }, locations);\n\n   }\n\n   @VisibleForTesting\n   public static final Map<Status, NodeMetadata.Status> toPortableNodeStatus = ImmutableMap\n            .<Status, NodeMetadata.Status> builder()\n            .put(Status.ACTIVE, NodeMetadata.Status.RUNNING)\n            .put(Status.BUILD, NodeMetadata.Status.PENDING)\n            .put(Status.DELETED, NodeMetadata.Status.TERMINATED)\n            .put(Status.ERROR, NodeMetadata.Status.ERROR)\n            .put(Status.HARD_REBOOT, NodeMetadata.Status.PENDING)\n            .put(Status.MIGRATING, NodeMetadata.Status.PENDING)\n            .put(Status.PASSWORD, NodeMetadata.Status.PENDING)\n            .put(Status.PAUSED, NodeMetadata.Status.SUSPENDED)\n            .put(Status.REBOOT, NodeMetadata.Status.PENDING)\n            .put(Status.REBUILD, NodeMetadata.Status.PENDING)\n            .put(Status.RESCUE, NodeMetadata.Status.PENDING)\n            .put(Status.RESIZE, NodeMetadata.Status.PENDING)\n            .put(Status.REVERT_RESIZE, NodeMetadata.Status.PENDING)\n            .put(Status.SHELVED, NodeMetadata.Status.SUSPENDED)\n            .put(Status.SHELVED_OFFLOADED, NodeMetadata.Status.SUSPENDED)\n            .put(Status.SHUTOFF, NodeMetadata.Status.SUSPENDED)\n            .put(Status.SOFT_DELETED, NodeMetadata.Status.TERMINATED)\n            .put(Status.STOPPED, NodeMetadata.Status.SUSPENDED)\n            .put(Status.SUSPENDED, NodeMetadata.Status.SUSPENDED)\n            .put(Status.UNKNOWN, NodeMetadata.Status.UNRECOGNIZED)\n            .put(Status.UNRECOGNIZED, NodeMetadata.Status.UNRECOGNIZED)\n            .put(Status.VERIFY_RESIZE, NodeMetadata.Status.PENDING)\n            .build();\n\n   @Singleton\n   @Provides\n   protected final Map<Status, NodeMetadata.Status> toPortableNodeStatus() {\n      return toPortableNodeStatus;\n   }\n\n   @VisibleForTesting\n   public static final Map<org.jclouds.openstack.nova.v2_0.domain.Image.Status, Image.Status> toPortableImageStatus = ImmutableMap\n            .<org.jclouds.openstack.nova.v2_0.domain.Image.Status, Image.Status> builder()\n            .put(org.jclouds.openstack.nova.v2_0.domain.Image.Status.ACTIVE, Image.Status.AVAILABLE)\n            .put(org.jclouds.openstack.nova.v2_0.domain.Image.Status.SAVING, Image.Status.PENDING)\n            .put(org.jclouds.openstack.nova.v2_0.domain.Image.Status.DELETED, Image.Status.DELETED)\n            .put(org.jclouds.openstack.nova.v2_0.domain.Image.Status.ERROR, Image.Status.ERROR)\n            .put(org.jclouds.openstack.nova.v2_0.domain.Image.Status.UNKNOWN, Image.Status.UNRECOGNIZED)\n            .put(org.jclouds.openstack.nova.v2_0.domain.Image.Status.UNRECOGNIZED, Image.Status.UNRECOGNIZED).build();\n\n\n   @VisibleForTesting\n   static class ServerInStatusPredicate implements Predicate<RegionAndId> {\n\n      private final NovaApi api;\n      private final Status status;\n\n      public ServerInStatusPredicate(NovaApi api, Status status) {\n         this.api = checkNotNull(api, \"api must not be null\");\n         this.status = checkNotNull(status, \"status must not be null\");\n      }\n\n      @Override\n      public boolean apply(RegionAndId regionAndId) {\n         checkNotNull(regionAndId, \"serverId\");\n         Server server = api.getServerApi(regionAndId.getRegion()).get(regionAndId.getId());\n         if (server == null) {\n            throw new IllegalStateException(String.format(\"Server %s not found.\", regionAndId.getId()));\n         }\n         return status.equals(server.getStatus());      \n      }\n   }\n\n   @VisibleForTesting\n   static class ServerTerminatedPredicate implements Predicate<RegionAndId> {\n\n      private final NovaApi api;\n\n      public ServerTerminatedPredicate(NovaApi api) {\n         this.api = checkNotNull(api, \"api must not be null\");\n      }\n\n      @Override\n      public boolean apply(RegionAndId regionAndId) {\n         checkNotNull(regionAndId, \"serverId\");\n         Server server = api.getServerApi(regionAndId.getRegion()).get(regionAndId.getId());\n         return server == null;\n      }\n   }\n\n   @Singleton\n   @Provides\n   protected final Map<org.jclouds.openstack.nova.v2_0.domain.Image.Status, Image.Status> toPortableImageStatus() {\n      return toPortableImageStatus;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/extensions/NeutronSecurityGroupExtension.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.compute.extensions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Predicates.notNull;\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.transform;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\n\nimport org.jclouds.Context;\nimport org.jclouds.compute.domain.SecurityGroup;\nimport org.jclouds.compute.extensions.SecurityGroupExtension;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.domain.Location;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.location.Region;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.net.domain.IpPermission;\nimport org.jclouds.net.domain.IpProtocol;\nimport org.jclouds.openstack.neutron.v2.NeutronApi;\nimport org.jclouds.openstack.neutron.v2.domain.Rule;\nimport org.jclouds.openstack.neutron.v2.domain.RuleDirection;\nimport org.jclouds.openstack.neutron.v2.domain.RuleEthertype;\nimport org.jclouds.openstack.neutron.v2.domain.RuleProtocol;\nimport org.jclouds.openstack.neutron.v2.features.SecurityGroupApi;\nimport org.jclouds.openstack.nova.v2_0.NovaApi;\nimport org.jclouds.openstack.nova.v2_0.compute.functions.NeutronSecurityGroupToSecurityGroup;\nimport org.jclouds.openstack.nova.v2_0.compute.functions.NovaSecurityGroupToSecurityGroup;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.RegionAndId;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.RegionAndName;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.RegionSecurityGroupNameAndPorts;\nimport org.jclouds.rest.ApiContext;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Multimap;\nimport com.google.common.collect.Sets;\nimport com.google.inject.Inject;\n\n/**\n * An extension to compute service to allow for the manipulation of {@link org.jclouds.compute.domain.SecurityGroup}s. Implementation\n * is optional by providers.\n */\npublic class NeutronSecurityGroupExtension implements SecurityGroupExtension {\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   private final NovaApi api;\n   private final Supplier<Set<String>> regionIds;\n   private final GroupNamingConvention.Factory namingConvention;\n   private final LoadingCache<RegionAndName, SecurityGroup> groupCreator;\n   private final Supplier<Map<String, Location>> locationIndex;\n   private final NeutronSecurityGroupToSecurityGroup.Factory neutronSecurityGroupToSecurityGroup;\n   private final NovaSecurityGroupToSecurityGroup.Factory novaSecurityGroupToSecurityGroup;\n\n   @Inject(optional = true)\n   @Named(\"openstack-neutron\")\n   private Supplier<Context> neutronContextSupplier;\n\n   @Inject\n   NeutronSecurityGroupExtension(NovaApi api,\n                                 @Region Supplier<Set<String>> regionIds,\n                                 GroupNamingConvention.Factory namingConvention, LoadingCache<RegionAndName, SecurityGroup> groupCreator,\n                                 Supplier<Map<String, Location>> locationIndex,\n                                 NeutronSecurityGroupToSecurityGroup.Factory neutronSecurityGroupToSecurityGroup,\n                                 NovaSecurityGroupToSecurityGroup.Factory novaSecurityGroupToSecurityGroup) {\n      this.api = api;\n      this.regionIds = checkNotNull(regionIds, \"regionIds\");\n      this.namingConvention = checkNotNull(namingConvention, \"namingConvention\");\n      this.groupCreator = groupCreator;\n      this.locationIndex = locationIndex;\n      this.neutronSecurityGroupToSecurityGroup = neutronSecurityGroupToSecurityGroup;\n      this.novaSecurityGroupToSecurityGroup = novaSecurityGroupToSecurityGroup;\n   }\n\n   @Override\n   public SecurityGroup createSecurityGroup(String name, Location location) {\n      String region = location.getId();\n      if (region == null) {\n         return null;\n      }\n      logger.debug(\">> creating security group %s in %s...\", name, location);\n\n      String markerGroup = namingConvention.create().sharedNameForGroup(name);\n      RegionSecurityGroupNameAndPorts regionAndName = new RegionSecurityGroupNameAndPorts(region, markerGroup, ImmutableSet.<Integer> of());\n      return groupCreator.getUnchecked(regionAndName);\n   }\n\n   @Override\n   public Set<SecurityGroup> listSecurityGroups() {\n      Set<SecurityGroup> securityGroups = Sets.newHashSet();\n\n      for (String regionId : regionIds.get()) {\n         Location location = locationIndex.get().get(regionId);\n         securityGroups.addAll(listSecurityGroupsInLocation(location));\n      }\n      return ImmutableSet.copyOf(securityGroups);\n   }\n\n\n   @Override\n   public Set<SecurityGroup> listSecurityGroupsInLocation(final Location location) {\n      String region = location.getId();\n      if (region == null) {\n         return ImmutableSet.of();\n      }\n      return getSecurityGroupApi(region).listSecurityGroups().concat().transform(neutronSecurityGroupToSecurityGroup.create(location)).toSet();\n   }\n\n   @Override\n   public Set<SecurityGroup> listSecurityGroupsForNode(String id) {\n      RegionAndId regionAndId = RegionAndId.fromSlashEncoded(checkNotNull(id, \"id\"));\n      String region = regionAndId.getRegion();\n      Location location = locationIndex.get().get(region);\n      Set<org.jclouds.openstack.nova.v2_0.domain.SecurityGroup> allGroups = api.getServerApi(region).listSecurityGroupForServer(regionAndId.getId());\n      return ImmutableSet.copyOf(transform(filter(allGroups, notNull()), novaSecurityGroupToSecurityGroup.create(location)));\n   }\n\n   @Override\n   public SecurityGroup getSecurityGroupById(String id) {\n      RegionAndId regionAndId = RegionAndId.fromSlashEncoded(checkNotNull(id, \"id\"));\n      String region = regionAndId.getRegion();\n      String groupId = regionAndId.getId();\n\n      SecurityGroupApi securityGroupApi = getSecurityGroupApi(region);\n\n      Location location = locationIndex.get().get(region);\n      return neutronSecurityGroupToSecurityGroup.create(location).apply(securityGroupApi.getSecurityGroup(groupId));\n   }\n\n   @Override\n   public boolean removeSecurityGroup(String id) {\n      checkNotNull(id, \"id\");\n      RegionAndId regionAndId = RegionAndId.fromSlashEncoded(id);\n      String region = regionAndId.getRegion();\n      String groupId = regionAndId.getId();\n\n      SecurityGroupApi securityGroupApi = getSecurityGroupApi(region);\n\n      // Would be nice to delete the group and invalidate the cache atomically - i.e. use a mutex.\n      // Will make sure that a create operation in parallel won't see inconsistent state.\n\n      boolean deleted = securityGroupApi.deleteSecurityGroup(groupId);\n\n      for (SecurityGroup cachedSg : groupCreator.asMap().values()) {\n         if (id.equals(cachedSg.getId())) {\n            String groupName = cachedSg.getName();\n            groupCreator.invalidate(new RegionSecurityGroupNameAndPorts(region, groupName, ImmutableSet.<Integer>of()));\n            break;\n         }\n      }\n\n      return deleted;\n   }\n\n   @Override\n   public SecurityGroup addIpPermission(IpPermission ipPermission, SecurityGroup group) {\n      String region = group.getLocation().getId();\n      RegionAndId groupRegionAndId = RegionAndId.fromSlashEncoded(group.getId());\n      String id = groupRegionAndId.getId();\n      SecurityGroupApi securityGroupApi = getSecurityGroupApi(region);\n\n      if (!ipPermission.getCidrBlocks().isEmpty()) {\n         for (String cidr : ipPermission.getCidrBlocks()) {\n            securityGroupApi.create(Rule.CreateRule.createBuilder(RuleDirection.INGRESS, group.getProviderId())\n                    .protocol(RuleProtocol.fromValue(ipPermission.getIpProtocol().name()))\n                    .ethertype(RuleEthertype.IPV4)\n                    .portRangeMin(ipPermission.getFromPort())\n                    .portRangeMax(ipPermission.getToPort())\n                    .remoteIpPrefix(cidr)\n                    .build());\n         }\n      }\n\n      if (!ipPermission.getGroupIds().isEmpty()) {\n         for (String regionAndGroupRaw : ipPermission.getGroupIds()) {\n            RegionAndId regionAndId = RegionAndId.fromSlashEncoded(regionAndGroupRaw);\n            String groupId = regionAndId.getId();\n            securityGroupApi.create(Rule.CreateRule.createBuilder(RuleDirection.INGRESS, groupId)\n                    .protocol(RuleProtocol.fromValue(ipPermission.getIpProtocol().name()))\n                    .ethertype(RuleEthertype.IPV4)\n                    .portRangeMin(ipPermission.getFromPort())\n                    .portRangeMax(ipPermission.getToPort())\n                    .remoteGroupId(groupId)\n                    .build());\n         }\n      }\n\n      return getSecurityGroupById(RegionAndId.fromRegionAndId(region, id).slashEncode());\n   }\n\n   @Override\n   public SecurityGroup addIpPermission(IpProtocol protocol, int startPort, int endPort,\n                                        Multimap<String, String> tenantIdGroupNamePairs,\n                                        Iterable<String> ipRanges,\n                                        Iterable<String> groupIds, SecurityGroup group) {\n      IpPermission.Builder permBuilder = IpPermission.builder();\n      permBuilder.ipProtocol(protocol);\n      permBuilder.fromPort(startPort);\n      permBuilder.toPort(endPort);\n      permBuilder.tenantIdGroupNamePairs(tenantIdGroupNamePairs);\n      permBuilder.cidrBlocks(ipRanges);\n      permBuilder.groupIds(groupIds);\n\n      return addIpPermission(permBuilder.build(), group);\n   }\n\n   @Override\n   public SecurityGroup removeIpPermission(final IpPermission ipPermission, SecurityGroup group) {\n      String region = group.getLocation().getId();\n      RegionAndId groupRegionAndId = RegionAndId.fromSlashEncoded(group.getId());\n      String id = groupRegionAndId.getId();\n\n      SecurityGroupApi securityGroupApi = getSecurityGroupApi(region);\n\n      org.jclouds.openstack.neutron.v2.domain.SecurityGroup securityGroup = securityGroupApi.getSecurityGroup(id);\n\n      if (!ipPermission.getCidrBlocks().isEmpty()) {\n         for (final String cidr : ipPermission.getCidrBlocks()) {\n            for (Rule rule : filter(securityGroup.getRules(),\n                    new Predicate<Rule>() {\n                       @Override\n                       public boolean apply(@Nullable Rule input) {\n                          return input.getRemoteIpPrefix() != null && input.getRemoteIpPrefix().equals(cidr) &&\n                                 input.getProtocol() != null && input.getProtocol().name().equals(ipPermission.getIpProtocol().name()) &&\n                                 input.getPortRangeMin() != null && input.getPortRangeMin() == ipPermission.getFromPort() &&\n                                 input.getPortRangeMax() != null && input.getPortRangeMax() == ipPermission.getToPort();\n                       }\n                    })) {\n               securityGroupApi.deleteRule(rule.getId());\n            }\n         }\n      }\n\n      if (!ipPermission.getGroupIds().isEmpty()) {\n         for (final String groupId : ipPermission.getGroupIds()) {\n            for (Rule rule : filter(securityGroup.getRules(),\n                    new Predicate<Rule>() {\n                       @Override\n                       public boolean apply(@Nullable Rule input) {\n                          return input.getRemoteGroupId() != null && input.getRemoteGroupId().equals(groupId) &&\n                                 input.getProtocol() != null && input.getProtocol().name().equals(ipPermission.getIpProtocol().name()) &&\n                                 input.getPortRangeMin() != null && input.getPortRangeMin() == ipPermission.getFromPort() &&\n                                 input.getPortRangeMax() != null && input.getPortRangeMax() == ipPermission.getToPort();\n                       }\n                    })) {\n               securityGroupApi.deleteRule(rule.getId());\n            }\n         }\n      }\n\n      return getSecurityGroupById(RegionAndId.fromRegionAndId(region, id).slashEncode());\n   }\n\n   @Override\n   public SecurityGroup removeIpPermission(IpProtocol protocol, int startPort, int endPort,\n                                           Multimap<String, String> tenantIdGroupNamePairs,\n                                           Iterable<String> ipRanges,\n                                           Iterable<String> groupIds, SecurityGroup group) {\n      IpPermission.Builder permBuilder = IpPermission.builder();\n      permBuilder.ipProtocol(protocol);\n      permBuilder.fromPort(startPort);\n      permBuilder.toPort(endPort);\n      permBuilder.tenantIdGroupNamePairs(tenantIdGroupNamePairs);\n      permBuilder.cidrBlocks(ipRanges);\n      permBuilder.groupIds(groupIds);\n\n      return removeIpPermission(permBuilder.build(), group);\n   }\n\n   @Override\n   public boolean supportsTenantIdGroupNamePairs() {\n      return false;\n   }\n\n   @Override\n   public boolean supportsTenantIdGroupIdPairs() {\n      return false;\n   }\n\n   @Override\n   public boolean supportsGroupIds() {\n      return true;\n   }\n\n   @Override\n   public boolean supportsPortRangesForGroups() {\n      return false;\n   }\n\n   @Override\n   public boolean supportsExclusionCidrBlocks() {\n      return false;\n   }\n\n   private SecurityGroupApi getSecurityGroupApi(String region) {\n      return ((ApiContext<NeutronApi>) neutronContextSupplier.get()).getApi().getSecurityGroupApi(region);\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/extensions/NovaImageExtension.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.compute.extensions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.common.collect.Iterables.find;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_IMAGE_AVAILABLE;\nimport static org.jclouds.location.predicates.LocationPredicates.idEquals;\n\nimport java.util.NoSuchElementException;\nimport java.util.Set;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Constants;\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.domain.CloneImageTemplate;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.ImageBuilder;\nimport org.jclouds.compute.domain.ImageTemplate;\nimport org.jclouds.compute.domain.ImageTemplateBuilder;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.extensions.ImageExtension;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.domain.Location;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.openstack.nova.v2_0.NovaApi;\nimport org.jclouds.openstack.nova.v2_0.domain.Server;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.RegionAndId;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.util.concurrent.Atomics;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.common.util.concurrent.UncheckedTimeoutException;\n\n/**\n * Nova implementation of {@link ImageExtension}\n */\n@Singleton\npublic class NovaImageExtension implements ImageExtension {\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   private final NovaApi novaApi;\n   private final ListeningExecutorService userExecutor;\n   private final Supplier<Set<? extends Location>> locations;\n   private final Predicate<AtomicReference<Image>> imageAvailablePredicate;\n\n   @Inject\n   public NovaImageExtension(NovaApi novaApi, @Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor,\n         @Memoized Supplier<Set<? extends Location>> locations,\n         @Named(TIMEOUT_IMAGE_AVAILABLE) Predicate<AtomicReference<Image>> imageAvailablePredicate) {\n      this.novaApi = checkNotNull(novaApi, \"novaApi\");\n      this.userExecutor = checkNotNull(userExecutor, \"userExecutor\");\n      this.locations = checkNotNull(locations, \"locations\");\n      this.imageAvailablePredicate = checkNotNull(imageAvailablePredicate, \"imageAvailablePredicate\");\n   }\n\n   @Override\n   public ImageTemplate buildImageTemplateFromNode(String name, final String id) {\n      RegionAndId regionAndId = RegionAndId.fromSlashEncoded(id);\n      Server server = novaApi.getServerApi(regionAndId.getRegion()).get(regionAndId.getId());\n      if (server == null)\n         throw new NoSuchElementException(\"Cannot find server with id: \" + regionAndId);\n      CloneImageTemplate template = new ImageTemplateBuilder.CloneImageTemplateBuilder().nodeId(id).name(name).build();\n      return template;\n   }\n\n   @Override\n   public ListenableFuture<Image> createImage(ImageTemplate template) {\n      checkState(template instanceof CloneImageTemplate,\n               \" openstack-nova only supports creating images through cloning.\");\n      CloneImageTemplate cloneTemplate = (CloneImageTemplate) template;\n      RegionAndId sourceImageRegionAndId = RegionAndId.fromSlashEncoded(cloneTemplate.getSourceNodeId());\n\n      String newImageId = novaApi.getServerApi(sourceImageRegionAndId.getRegion()).createImageFromServer(\n               cloneTemplate.getName(), sourceImageRegionAndId.getId());\n\n      final RegionAndId targetImageRegionAndId = RegionAndId.fromRegionAndId(sourceImageRegionAndId.getRegion(), newImageId);\n\n      logger.info(\">> Registered new Image %s, waiting for it to become available.\", newImageId);\n\n      final AtomicReference<Image> image = Atomics.newReference(new ImageBuilder()\n            .location(find(locations.get(), idEquals(targetImageRegionAndId.getRegion())))\n            .id(targetImageRegionAndId.slashEncode())\n            .providerId(targetImageRegionAndId.getId())\n            .description(cloneTemplate.getName())\n            .operatingSystem(OperatingSystem.builder().description(cloneTemplate.getName()).build())\n            .status(Image.Status.PENDING).build());\n\n      return userExecutor.submit(new Callable<Image>() {\n         @Override\n         public Image call() throws Exception {\n            if (imageAvailablePredicate.apply(image))\n               return image.get();\n            // TODO: get rid of the expectation that the image will be available, as it is very brittle\n            throw new UncheckedTimeoutException(\"Image was not created within the time limit: \" + image.get());\n         }\n      });\n   }\n\n   @Override\n   public boolean deleteImage(String id) {\n      RegionAndId regionAndId = RegionAndId.fromSlashEncoded(id);\n      try {\n         this.novaApi.getImageApi(regionAndId.getRegion()).delete(regionAndId.getId());\n      } catch (Exception e) {\n         return false;\n      }\n      return true;\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/extensions/NovaSecurityGroupExtension.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.compute.extensions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Predicates.and;\nimport static com.google.common.base.Predicates.notNull;\nimport static com.google.common.collect.Iterables.concat;\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.transform;\nimport static org.jclouds.openstack.nova.v2_0.predicates.SecurityGroupPredicates.ruleCidr;\nimport static org.jclouds.openstack.nova.v2_0.predicates.SecurityGroupPredicates.ruleEndPort;\nimport static org.jclouds.openstack.nova.v2_0.predicates.SecurityGroupPredicates.ruleGroup;\nimport static org.jclouds.openstack.nova.v2_0.predicates.SecurityGroupPredicates.ruleProtocol;\nimport static org.jclouds.openstack.nova.v2_0.predicates.SecurityGroupPredicates.ruleStartPort;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\n\nimport com.google.inject.Inject;\nimport org.jclouds.Constants;\nimport org.jclouds.compute.domain.SecurityGroup;\nimport org.jclouds.compute.extensions.SecurityGroupExtension;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.domain.Location;\nimport org.jclouds.location.Region;\nimport org.jclouds.net.domain.IpPermission;\nimport org.jclouds.net.domain.IpProtocol;\nimport org.jclouds.openstack.nova.v2_0.NovaApi;\nimport org.jclouds.openstack.nova.v2_0.domain.Ingress;\nimport org.jclouds.openstack.nova.v2_0.domain.SecurityGroupRule;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.RegionAndId;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.RegionAndName;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.RegionSecurityGroupNameAndPorts;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.SecurityGroupInRegion;\nimport org.jclouds.openstack.nova.v2_0.extensions.SecurityGroupApi;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Multimap;\nimport com.google.common.util.concurrent.ListeningExecutorService;\n\n/**\n * An extension to compute service to allow for the manipulation of {@link org.jclouds.compute.domain.SecurityGroup}s. Implementation\n * is optional by providers.\n */\npublic class NovaSecurityGroupExtension implements SecurityGroupExtension {\n\n   protected final NovaApi api;\n   protected final ListeningExecutorService userExecutor;\n   protected final Supplier<Set<String>> regionIds;\n   protected final Function<SecurityGroupInRegion, SecurityGroup> groupConverter;\n   protected final LoadingCache<RegionAndName, SecurityGroup> groupCreator;\n   protected final GroupNamingConvention.Factory namingConvention;\n\n   @Inject\n   public NovaSecurityGroupExtension(NovaApi api,\n                                    @Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor,\n                                    @Region Supplier<Set<String>> regionIds,\n                                    Function<SecurityGroupInRegion, SecurityGroup> groupConverter,\n                                    LoadingCache<RegionAndName, SecurityGroup> groupCreator,\n                                    GroupNamingConvention.Factory namingConvention) {\n\n      this.api = checkNotNull(api, \"api\");\n      this.userExecutor = checkNotNull(userExecutor, \"userExecutor\");\n      this.regionIds = checkNotNull(regionIds, \"regionIds\");\n      this.groupConverter = checkNotNull(groupConverter, \"groupConverter\");\n      this.groupCreator = checkNotNull(groupCreator, \"groupCreator\");\n      this.namingConvention = checkNotNull(namingConvention, \"namingConvention\");\n   }\n\n   @Override\n   public Set<SecurityGroup> listSecurityGroups() {\n      Iterable<? extends SecurityGroupInRegion> rawGroups = pollSecurityGroups();\n      Iterable<SecurityGroup> groups = transform(filter(rawGroups, notNull()),\n              groupConverter);\n      return ImmutableSet.copyOf(groups);\n   }\n\n\n   @Override\n   public Set<SecurityGroup> listSecurityGroupsInLocation(final Location location) {\n      String region = location.getId();\n      if (region == null) {\n         return ImmutableSet.of();\n      }\n      return listSecurityGroupsInLocation(region);\n   }\n\n   public Set<SecurityGroup> listSecurityGroupsInLocation(String region) {\n      Iterable<? extends SecurityGroupInRegion> rawGroups = pollSecurityGroupsByRegion(region);\n      Iterable<SecurityGroup> groups = transform(filter(rawGroups, notNull()),\n              groupConverter);\n      return ImmutableSet.copyOf(groups);\n   }\n\n   @Override\n   public Set<SecurityGroup> listSecurityGroupsForNode(String id) {\n      RegionAndId regionAndId = RegionAndId.fromSlashEncoded(checkNotNull(id, \"id\"));\n      String region = regionAndId.getRegion();\n      Set<org.jclouds.openstack.nova.v2_0.domain.SecurityGroup> allGroups = api.getServerApi(region).listSecurityGroupForServer(regionAndId.getId());\n      Set<? extends SecurityGroupInRegion> rawGroups =\n              FluentIterable.from(allGroups).transform(groupToGroupInRegion(allGroups, region)).toSet();\n      return ImmutableSet.copyOf(transform(filter(rawGroups, notNull()), groupConverter));\n   }\n\n   @Override\n   public SecurityGroup getSecurityGroupById(String id) {\n      RegionAndId regionAndId = RegionAndId.fromSlashEncoded(checkNotNull(id, \"id\"));\n      String region = regionAndId.getRegion();\n      String groupId = regionAndId.getId();\n\n      Optional<? extends SecurityGroupApi> sgApi = api.getSecurityGroupApi(region);\n\n      if (!sgApi.isPresent()) {\n         return null;\n      }\n\n      final FluentIterable<org.jclouds.openstack.nova.v2_0.domain.SecurityGroup> allGroups = sgApi.get().list();\n      SecurityGroupInRegion rawGroup = new SecurityGroupInRegion(sgApi.get().get(groupId), region, allGroups);\n\n      return groupConverter.apply(rawGroup);\n   }\n\n   @Override\n   public SecurityGroup createSecurityGroup(String name, Location location) {\n      String region = location.getId();\n      if (region == null) {\n         return null;\n      }\n      return createSecurityGroup(name, region);\n   }\n\n   public SecurityGroup createSecurityGroup(String name, String region) {\n      String markerGroup = namingConvention.create().sharedNameForGroup(name);\n      RegionSecurityGroupNameAndPorts regionAndName = new RegionSecurityGroupNameAndPorts(region, markerGroup, ImmutableSet.<Integer> of());\n\n      SecurityGroup rawGroup = groupCreator.getUnchecked(regionAndName);\n      return rawGroup;\n   }\n\n   @Override\n   public boolean removeSecurityGroup(String id) {\n      checkNotNull(id, \"id\");\n      RegionAndId regionAndId = RegionAndId.fromSlashEncoded(id);\n      String region = regionAndId.getRegion();\n      String groupId = regionAndId.getId();\n\n      Optional<? extends SecurityGroupApi> sgApi = api.getSecurityGroupApi(region);\n\n      if (!sgApi.isPresent()) {\n         return false;\n      }\n\n      // Would be nice to delete the group and invalidate the cache atomically - i.e. use a mutex.\n      // Will make sure that a create operation in parallel won't see inconsistent state.\n\n      boolean deleted = sgApi.get().delete(groupId);\n\n      for (SecurityGroup cachedSg : groupCreator.asMap().values()) {\n         if (id.equals(cachedSg.getId())) {\n            String groupName = cachedSg.getName();\n            groupCreator.invalidate(new RegionSecurityGroupNameAndPorts(region, groupName, ImmutableSet.<Integer>of()));\n            break;\n         }\n      }\n\n      return deleted;\n   }\n\n   @Override\n   public SecurityGroup addIpPermission(IpPermission ipPermission, SecurityGroup group) {\n      String region = group.getLocation().getId();\n      RegionAndId groupRegionAndId = RegionAndId.fromSlashEncoded(group.getId());\n      String id = groupRegionAndId.getId();\n      Optional<? extends SecurityGroupApi> sgApi = api.getSecurityGroupApi(region);\n\n      if (!sgApi.isPresent()) {\n         return null;\n      }\n\n      if (!ipPermission.getCidrBlocks().isEmpty()) {\n         for (String cidr : ipPermission.getCidrBlocks()) {\n            sgApi.get().createRuleAllowingCidrBlock(id,\n                    Ingress.builder()\n                            .ipProtocol(ipPermission.getIpProtocol())\n                            .fromPort(ipPermission.getFromPort())\n                            .toPort(ipPermission.getToPort())\n                            .build(),\n                    cidr);\n         }\n      }\n\n      if (!ipPermission.getGroupIds().isEmpty()) {\n         for (String regionAndGroupRaw : ipPermission.getGroupIds()) {\n            RegionAndId regionAndId = RegionAndId.fromSlashEncoded(regionAndGroupRaw);\n            String groupId = regionAndId.getId();\n            sgApi.get().createRuleAllowingSecurityGroupId(id,\n                    Ingress.builder()\n                            .ipProtocol(ipPermission.getIpProtocol())\n                            .fromPort(ipPermission.getFromPort())\n                            .toPort(ipPermission.getToPort())\n                            .build(),\n                    groupId);\n         }\n      }\n\n      return getSecurityGroupById(RegionAndId.fromRegionAndId(region, id).slashEncode());\n   }\n\n   @Override\n   public SecurityGroup addIpPermission(IpProtocol protocol, int startPort, int endPort,\n                                        Multimap<String, String> tenantIdGroupNamePairs,\n                                        Iterable<String> ipRanges,\n                                        Iterable<String> groupIds, SecurityGroup group) {\n      IpPermission.Builder permBuilder = IpPermission.builder();\n      permBuilder.ipProtocol(protocol);\n      permBuilder.fromPort(startPort);\n      permBuilder.toPort(endPort);\n      permBuilder.tenantIdGroupNamePairs(tenantIdGroupNamePairs);\n      permBuilder.cidrBlocks(ipRanges);\n      permBuilder.groupIds(groupIds);\n\n      return addIpPermission(permBuilder.build(), group);\n   }\n\n   @Override\n   public SecurityGroup removeIpPermission(IpPermission ipPermission, SecurityGroup group) {\n      String region = group.getLocation().getId();\n      RegionAndId groupRegionAndId = RegionAndId.fromSlashEncoded(group.getId());\n      String id = groupRegionAndId.getId();\n\n      Optional<? extends SecurityGroupApi> sgApi = api.getSecurityGroupApi(region);\n\n      if (!sgApi.isPresent()) {\n         return null;\n      }\n\n      org.jclouds.openstack.nova.v2_0.domain.SecurityGroup securityGroup = sgApi.get().get(id);\n\n      if (!ipPermission.getCidrBlocks().isEmpty()) {\n         for (String cidr : ipPermission.getCidrBlocks()) {\n            for (SecurityGroupRule rule : filter(securityGroup.getRules(),\n                    and(ruleCidr(cidr), ruleProtocol(ipPermission.getIpProtocol()),\n                            ruleStartPort(ipPermission.getFromPort()),\n                            ruleEndPort(ipPermission.getToPort())))) {\n               sgApi.get().deleteRule(rule.getId());\n            }\n         }\n      }\n\n      if (!ipPermission.getGroupIds().isEmpty()) {\n         for (String groupId : ipPermission.getGroupIds()) {\n            for (SecurityGroupRule rule : filter(securityGroup.getRules(),\n                    and(ruleGroup(groupId), ruleProtocol(ipPermission.getIpProtocol()),\n                            ruleStartPort(ipPermission.getFromPort()),\n                            ruleEndPort(ipPermission.getToPort())))) {\n               sgApi.get().deleteRule(rule.getId());\n            }\n\n         }\n      }\n\n      return getSecurityGroupById(RegionAndId.fromRegionAndId(region, id).slashEncode());\n   }\n\n   @Override\n   public SecurityGroup removeIpPermission(IpProtocol protocol, int startPort, int endPort,\n                                           Multimap<String, String> tenantIdGroupNamePairs,\n                                           Iterable<String> ipRanges,\n                                           Iterable<String> groupIds, SecurityGroup group) {\n      IpPermission.Builder permBuilder = IpPermission.builder();\n      permBuilder.ipProtocol(protocol);\n      permBuilder.fromPort(startPort);\n      permBuilder.toPort(endPort);\n      permBuilder.tenantIdGroupNamePairs(tenantIdGroupNamePairs);\n      permBuilder.cidrBlocks(ipRanges);\n      permBuilder.groupIds(groupIds);\n\n      return removeIpPermission(permBuilder.build(), group);\n   }\n\n   @Override\n   public boolean supportsTenantIdGroupNamePairs() {\n      return false;\n   }\n\n   @Override\n   public boolean supportsTenantIdGroupIdPairs() {\n      return false;\n   }\n\n   @Override\n   public boolean supportsGroupIds() {\n      return true;\n   }\n\n   @Override\n   public boolean supportsPortRangesForGroups() {\n      return false;\n   }\n\n   @Override\n   public boolean supportsExclusionCidrBlocks() {\n       return false;\n   }\n\n   protected Iterable<? extends SecurityGroupInRegion> pollSecurityGroups() {\n      Iterable<? extends Set<? extends SecurityGroupInRegion>> groups\n              = transform(regionIds.get(), allSecurityGroupsInRegion());\n\n      return concat(groups);\n   }\n\n\n   protected Iterable<? extends SecurityGroupInRegion> pollSecurityGroupsByRegion(String region) {\n      return allSecurityGroupsInRegion().apply(region);\n   }\n\n   protected Function<String, Set<? extends SecurityGroupInRegion>> allSecurityGroupsInRegion() {\n      return new Function<String, Set<? extends SecurityGroupInRegion>>() {\n\n         @Override\n         public Set<? extends SecurityGroupInRegion> apply(final String from) {\n            Optional<? extends SecurityGroupApi> sgApi = api.getSecurityGroupApi(from);\n\n            if (!sgApi.isPresent()) {\n               return ImmutableSet.of();\n            }\n\n\n             final FluentIterable<org.jclouds.openstack.nova.v2_0.domain.SecurityGroup> allGroups = sgApi.get().list();\n             return allGroups.transform(groupToGroupInRegion(allGroups, from)).toSet();\n         }\n\n      };\n   }\n\n   protected Function<org.jclouds.openstack.nova.v2_0.domain.SecurityGroup, SecurityGroupInRegion> groupToGroupInRegion(\n       final Iterable<org.jclouds.openstack.nova.v2_0.domain.SecurityGroup> allGroups, final String region) {\n\n      return new Function<org.jclouds.openstack.nova.v2_0.domain.SecurityGroup, SecurityGroupInRegion>() {\n         @Override\n         public SecurityGroupInRegion apply(org.jclouds.openstack.nova.v2_0.domain.SecurityGroup group) {\n            return new SecurityGroupInRegion(group, region, allGroups);\n         }\n      };\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/functions/AllocateAndAddFloatingIpToNode.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.compute.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_RUNNING;\n\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\n\nimport com.google.common.collect.Sets;\nimport org.jclouds.Context;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadataBuilder;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.openstack.neutron.v2.NeutronApi;\nimport org.jclouds.openstack.neutron.v2.domain.Network;\nimport org.jclouds.openstack.neutron.v2.domain.Networks;\nimport org.jclouds.openstack.neutron.v2.domain.Port;\nimport org.jclouds.openstack.neutron.v2.features.NetworkApi;\nimport org.jclouds.openstack.neutron.v2.features.PortApi;\nimport org.jclouds.openstack.nova.v2_0.NovaApi;\nimport org.jclouds.openstack.nova.v2_0.compute.options.NodeAndNovaTemplateOptions;\nimport org.jclouds.openstack.nova.v2_0.domain.FloatingIP;\nimport org.jclouds.openstack.nova.v2_0.domain.FloatingIpForServer;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.RegionAndId;\nimport org.jclouds.openstack.nova.v2_0.extensions.FloatingIPApi;\nimport org.jclouds.rest.ApiContext;\nimport org.jclouds.rest.InsufficientResourcesException;\nimport org.jclouds.rest.ResourceNotFoundException;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Lists;\nimport com.google.inject.Inject;\n\n/**\n * A function for adding and allocating an ip to a node\n */\npublic class AllocateAndAddFloatingIpToNode\n      implements Function<AtomicReference<NodeAndNovaTemplateOptions>, AtomicReference<NodeMetadata>> {\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   @Inject(optional = true)\n   @Named(\"openstack-neutron\")\n   private Supplier<Context> neutronContextSupplier;\n\n   private final Predicate<AtomicReference<NodeMetadata>> nodeRunning;\n   private final NovaApi novaApi;\n   private final LoadingCache<RegionAndId, Iterable<? extends FloatingIpForServer>> floatingIpCache;\n   private final CleanupResources cleanupResources;\n\n   @Inject\n   public AllocateAndAddFloatingIpToNode(\n         @Named(TIMEOUT_NODE_RUNNING) Predicate<AtomicReference<NodeMetadata>> nodeRunning, NovaApi novaApi,\n         @Named(\"FLOATINGIP\") LoadingCache<RegionAndId, Iterable<? extends FloatingIpForServer>> floatingIpCache,\n         CleanupResources cleanupResources) {\n      this.nodeRunning = checkNotNull(nodeRunning, \"nodeRunning\");\n      this.novaApi = checkNotNull(novaApi, \"novaApi\");\n      this.floatingIpCache = checkNotNull(floatingIpCache, \"floatingIpCache\");\n      this.cleanupResources = checkNotNull(cleanupResources, \"cleanupResources\");\n   }\n\n   @Override\n   public AtomicReference<NodeMetadata> apply(AtomicReference<NodeAndNovaTemplateOptions> input) {\n      checkState(nodeRunning.apply(input.get().getNodeMetadata()), \"node never achieved state running %s\", input.get().getNodeMetadata());\n      final NodeMetadata node = input.get().getNodeMetadata().get();\n      // node's location is a host\n      String regionId = node.getLocation().getParent().getId();\n      Optional<Set<String>> poolNames = input.get().getNovaTemplateOptions().get().getFloatingIpPoolNames();\n\n      String availabilityZone = getAvailabilityZoneFromTemplateOptionsOrDefault(input, regionId);\n\n      if (isNeutronLinked()) {\n         org.jclouds.openstack.neutron.v2.features.FloatingIPApi neutronFloatingApi = getFloatingIPApi(regionId);\n            final Optional<Port> optionalPort = getPortApi(regionId).list().concat().firstMatch(new Predicate<Port>() {\n               @Override\n               public boolean apply(@Nullable Port input) {\n                  return input.getDeviceId().equals(node.getProviderId());\n               }\n            });\n            if (optionalPort.isPresent()) {\n               Optional<org.jclouds.openstack.neutron.v2.domain.FloatingIP> floatingIPOptional = tryFindExistingFloatingIp(neutronFloatingApi, availabilityZone);\n               org.jclouds.openstack.neutron.v2.domain.FloatingIP floatingIP;\n               if (floatingIPOptional.isPresent()) {\n                  floatingIP = floatingIPOptional.get();\n               } else {\n                  floatingIP = createFloatingIpUsingNeutron(neutronFloatingApi, node, poolNames, availabilityZone);\n               }\n\n               org.jclouds.openstack.neutron.v2.domain.FloatingIP ip = neutronFloatingApi.update(floatingIP.getId(),\n                       org.jclouds.openstack.neutron.v2.domain.FloatingIP.UpdateFloatingIP\n                               .updateBuilder()\n                               .portId(optionalPort.get().getId())\n                               .build());\n\n               input.get().getNodeMetadata().set(NodeMetadataBuilder.fromNodeMetadata(node).publicAddresses(ImmutableSet.of(ip.getFloatingIpAddress())).build());\n            } else {\n               logger.error(\"Node %s doesn't have a port to attach a floating IP\", node);\n               throw new IllegalStateException(\"Missing required port in node: \" + node);\n            }\n      } else { // try nova\n         FloatingIPApi floatingIpApi = novaApi.getFloatingIPApi(regionId).get();\n\n         Optional<FloatingIP> ip = allocateFloatingIPForNodeOnNova(floatingIpApi, poolNames, node.getId());\n         if (!ip.isPresent()) {\n            cleanupResources.apply(node);\n            throw new InsufficientResourcesException(\"Failed to allocate a FloatingIP for node(\" + node.getId() + \")\");\n         }\n         logger.debug(\">> adding floatingIp(%s) to node(%s)\", ip.get().getIp(), node.getId());\n\n         floatingIpApi.addToServer(ip.get().getIp(), node.getProviderId());\n         input.get().getNodeMetadata().set(NodeMetadataBuilder.fromNodeMetadata(node).publicAddresses(ImmutableSet.of(ip.get().getIp())).build());\n         floatingIpCache.asMap().put(RegionAndId.fromSlashEncoded(node.getId()), ImmutableList.of(FloatingIpForServer.create(RegionAndId.fromSlashEncoded(node.getId()), ip.get().getId(), ip.get().getIp())));\n      }\n      return input.get().getNodeMetadata();\n   }\n\n   private String getAvailabilityZoneFromTemplateOptionsOrDefault(AtomicReference<NodeAndNovaTemplateOptions> input, String regionId) {\n      return MoreObjects.firstNonNull(input.get().getNovaTemplateOptions().get().getAvailabilityZone(),\n              Iterables.get(novaApi.getAvailabilityZoneApi(regionId).get().listAvailabilityZones(), 0).getName());\n   }\n\n   /**\n    * Allocates a FloatingIP for a given Node\n    *\n    * @param floatingIpApi\n    *           FloatingIPApi to create or query for a valid FloatingIP\n    * @param poolNames\n    *           optional set of pool names from which we will attempt to allocate\n    *           an IP from. Most cases this is null\n    * @param nodeID\n    *           optional id of the Node we are trying to allocate a FloatingIP for.\n    *           Used here only for logging purposes\n    * @return Optional<FloatingIP>\n    */\n   private synchronized Optional<FloatingIP> allocateFloatingIPForNodeOnNova(FloatingIPApi floatingIpApi,\n         Optional<Set<String>> poolNames, String nodeID) {\n\n      FloatingIP ip;\n\n      // 1.) Attempt to allocate from optionally passed poolNames\n      if (poolNames.isPresent()) {\n         for (String poolName : poolNames.get()) {\n            try {\n               logger.debug(\">> allocating floating IP from pool %s for node(%s)\", poolName, nodeID);\n               ip = floatingIpApi.allocateFromPool(poolName);\n               return Optional.of(ip);\n            } catch (ResourceNotFoundException ex) {\n               logger.trace(\"<< [%s] failed to allocate floating IP from pool %s for node(%s)\", ex.getMessage(),\n                     poolName, nodeID);\n            } catch (InsufficientResourcesException ire) {\n               logger.trace(\"<< [%s] failed to allocate floating IP from pool %s for node(%s)\", ire.getMessage(),\n                     poolName, nodeID);\n            }\n         }\n      }\n\n      // 2.) Attempt to allocate, if necessary, via 'create()' call\n      try {\n         logger.debug(\">> creating floating IP for node(%s)\", nodeID);\n         ip = floatingIpApi.create();\n         return Optional.of(ip);\n      } catch (ResourceNotFoundException ex) {\n         logger.trace(\"<< [%s] failed to create floating IP for node(%s)\", ex.getMessage(), nodeID);\n      } catch (InsufficientResourcesException ire) {\n         logger.trace(\"<< [%s] failed to create floating IP for node(%s)\", ire.getMessage(), nodeID);\n      }\n\n      // 3.) If no IP was found make final attempt by searching through list of\n      // available IP's\n      logger.trace(\">> searching for existing, unassigned floating IP for node(%s)\", nodeID);\n      List<FloatingIP> unassignedIps = Lists\n            .newArrayList(Iterables.filter(floatingIpApi.list(), new Predicate<FloatingIP>() {\n\n               @Override\n               public boolean apply(FloatingIP arg0) {\n                  return arg0.getFixedIp() == null;\n               }\n\n            }));\n      // try to prevent multiple parallel launches from choosing the same ip.\n      if (unassignedIps.isEmpty()) {\n         return Optional.absent();\n      }\n      Collections.shuffle(unassignedIps);\n      ip = Iterables.getLast(unassignedIps);\n      return Optional.fromNullable(ip);\n   }\n\n   private Optional<org.jclouds.openstack.neutron.v2.domain.FloatingIP> tryFindExistingFloatingIp(org.jclouds.openstack.neutron.v2.features.FloatingIPApi neutronFloatingApi, final String availabilityZone) {\n      Optional<org.jclouds.openstack.neutron.v2.domain.FloatingIP> floatingIPOptional = neutronFloatingApi.list().concat().firstMatch(new Predicate<org.jclouds.openstack.neutron.v2.domain.FloatingIP>() {\n         @Override\n         public boolean apply(@Nullable org.jclouds.openstack.neutron.v2.domain.FloatingIP input) {\n            return input.getPortId() == null && input.getAvailabilityZone().equals(availabilityZone);\n         }\n      });\n      return floatingIPOptional;\n   }\n\n   private org.jclouds.openstack.neutron.v2.domain.FloatingIP createFloatingIpUsingNeutron(org.jclouds.openstack.neutron.v2.features.FloatingIPApi neutronFloatingApi,\n                                                                                           NodeMetadata node, Optional<Set<String>> poolNames, final String availabilityZone) {\n      String regionId = node.getLocation().getParent().getId();\n      List<Network> networks = getSuitableNetworks(regionId, availabilityZone, poolNames.or(Sets.<String>newHashSet()));\n      org.jclouds.openstack.neutron.v2.domain.FloatingIP floatingIP = null;\n      for (Network network : networks) {\n         try {\n            logger.debug(\">> allocating floating IP from network %s for node(%s)\", network, node);\n            org.jclouds.openstack.neutron.v2.domain.FloatingIP createFloatingIP = org.jclouds.openstack.neutron.v2.domain.FloatingIP.CreateFloatingIP.createBuilder(network.getId()).availabilityZone(network.getAvailabilityZone()).build();\n            floatingIP = neutronFloatingApi.create((org.jclouds.openstack.neutron.v2.domain.FloatingIP.CreateFloatingIP) createFloatingIP);\n            logger.debug(\">> allocated floating IP(%s) from network(%s) for node(%s)\", floatingIP, network, node);\n            floatingIpCache.asMap().put(RegionAndId.fromSlashEncoded(node.getId()), ImmutableList.of(FloatingIpForServer.create(RegionAndId.fromSlashEncoded(node.getId()), floatingIP.getId(), floatingIP.getFloatingIpAddress())));\n            return floatingIP;\n         } catch (Exception ex) {\n            logger.trace(\"<< [%s] failed to allocate a floating IP from network %s for node(%s)\", ex.getMessage(), network, node);\n         }\n      }\n\n      throw new IllegalStateException(\"Failed to allocate a floating IP for node \" + node + \".\\n\" +\n            \"Failed to find suitable external networks or to allocate from poolNames specified: \"\n            + Iterables.toString(poolNames.get()));\n\n   }\n\n\n   /**\n    * Get all suitable networks to allocate a floating ip\n    *\n    * It will prefer networks specified using the poolNames first and then the external networks in the given availability zone\n    */\n   private List<Network> getSuitableNetworks(String regionId, final String availabilityZone, final Set<String> poolNames) {\n      List<Network> allNetworks = getNetworkApi(regionId).list().concat().toList();\n      Iterable<Network> externalNetworks = Iterables.filter(allNetworks, Networks.Predicates.externalNetworks(availabilityZone));\n      Iterable<Network> networksFromPoolName = Iterables.filter(allNetworks, Networks.Predicates.namedNetworks(poolNames));\n      return Lists.newArrayList(Iterables.concat(networksFromPoolName, externalNetworks));\n   }\n\n   private boolean isNeutronLinked() {\n      return neutronContextSupplier != null && neutronContextSupplier.get() != null;\n   }\n\n   private org.jclouds.openstack.neutron.v2.features.FloatingIPApi getFloatingIPApi(String region) {\n      return ((ApiContext<NeutronApi>) neutronContextSupplier.get()).getApi().getFloatingIPApi(region);\n   }\n\n   private PortApi getPortApi(String regionId) {\n      return ((ApiContext<NeutronApi>) neutronContextSupplier.get()).getApi().getPortApi(regionId);\n   }\n\n   private NetworkApi getNetworkApi(String regionId) {\n      return ((ApiContext<NeutronApi>) neutronContextSupplier.get()).getApi().getNetworkApi(regionId);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(\"AllocateAndAddFloatingIpToNode\").toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/functions/CleanupResources.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.compute.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.openstack.nova.v2_0.compute.strategy.ApplyNovaTemplateOptionsCreateNodesWithGroupEncodedIntoNameThenAddToSet.JCLOUDS_SG_PREFIX;\n\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.SecurityGroup;\nimport org.jclouds.compute.extensions.SecurityGroupExtension;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.RegionAndId;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.RegionAndName;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.FluentIterable;\n\n@Singleton\npublic class CleanupResources implements Function<NodeMetadata, Boolean> {\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   protected final RemoveFloatingIpFromNodeAndDeallocate removeFloatingIpFromNodeAndDeallocate;\n   protected final LoadingCache<RegionAndName, SecurityGroup> securityGroupMap;\n\n   private final SecurityGroupExtension securityGroupExtension;\n\n   @Inject\n   public CleanupResources(RemoveFloatingIpFromNodeAndDeallocate removeFloatingIpFromNodeAndDeallocate,\n         LoadingCache<RegionAndName, SecurityGroup> securityGroupMap, SecurityGroupExtension securityGroupExtension) {\n      this.removeFloatingIpFromNodeAndDeallocate = removeFloatingIpFromNodeAndDeallocate;\n      this.securityGroupMap = checkNotNull(securityGroupMap, \"securityGroupMap\");\n      this.securityGroupExtension = securityGroupExtension;\n   }\n\n   @Override\n   public Boolean apply(NodeMetadata node) {\n      final RegionAndId regionAndId = RegionAndId.fromSlashEncoded(node.getId());\n      removeFloatingIpFromNodeifAny(regionAndId);\n      return removeSecurityGroupCreatedByJcloudsAndInvalidateCache(node.getTags());\n   }\n\n   public boolean removeSecurityGroupCreatedByJcloudsAndInvalidateCache(Set<String> tags) {\n      String securityGroupIdCreatedByJclouds = getSecurityGroupIdCreatedByJclouds(tags);\n      if (securityGroupIdCreatedByJclouds == null) return true;\n      return securityGroupExtension.removeSecurityGroup(securityGroupIdCreatedByJclouds);\n   }\n\n   private void removeFloatingIpFromNodeifAny(RegionAndId regionAndId) {\n      try {\n         removeFloatingIpFromNodeAndDeallocate.apply(regionAndId);\n      } catch (RuntimeException e) {\n         logger.warn(e, \"<< error removing and deallocating ip from node(%s): %s\", regionAndId, e.getMessage());\n      }\n   }\n\n   private String getSecurityGroupIdCreatedByJclouds(Set<String> tags) {\n      return FluentIterable.from(tags).filter(new Predicate<String>() {\n         @Override\n         public boolean apply(String input) {\n            return input.startsWith(JCLOUDS_SG_PREFIX);\n         }\n      }).transform(new Function<String, String>() {\n         @Override\n         public String apply(String input) {\n            return input.substring(JCLOUDS_SG_PREFIX.length() + 1);\n         }\n      }).first().orNull();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/functions/CreateSecurityGroupIfNeeded.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.compute.functions;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.collect.Iterables.find;\nimport static org.jclouds.openstack.nova.v2_0.predicates.SecurityGroupPredicates.nameEquals;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport org.jclouds.Context;\nimport org.jclouds.compute.domain.SecurityGroup;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.domain.Location;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.net.domain.IpProtocol;\nimport org.jclouds.openstack.neutron.v2.NeutronApi;\nimport org.jclouds.openstack.neutron.v2.domain.Rule;\nimport org.jclouds.openstack.neutron.v2.domain.RuleDirection;\nimport org.jclouds.openstack.neutron.v2.domain.RuleProtocol;\nimport org.jclouds.openstack.neutron.v2.features.SecurityGroupApi;\nimport org.jclouds.openstack.nova.v2_0.NovaApi;\nimport org.jclouds.openstack.nova.v2_0.domain.Ingress;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.RegionAndId;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.RegionSecurityGroupNameAndPorts;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.SecurityGroupInRegion;\nimport org.jclouds.rest.ApiContext;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.FluentIterable;\nimport com.google.inject.Inject;\n\n@Singleton\npublic class CreateSecurityGroupIfNeeded implements Function<RegionSecurityGroupNameAndPorts, SecurityGroup> {\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   protected final NovaApi novaApi;\n   private final Supplier<Map<String, Location>> locationIndex;\n   private final Function<SecurityGroupInRegion, SecurityGroup> securityGroupInRegionSecurityGroupFunction;\n   private final NeutronSecurityGroupToSecurityGroup.Factory neutronSecurityGroupToSecurityGroup;\n\n   @Inject(optional = true)\n   @Named(\"openstack-neutron\")\n   Supplier<Context> neutronContextSupplier;\n\n   @Inject\n   @VisibleForTesting\n   public CreateSecurityGroupIfNeeded(NovaApi novaApi, Supplier<Map<String, Location>> locationIndex,\n                               Function<SecurityGroupInRegion, SecurityGroup> securityGroupInRegionSecurityGroupFunction,\n                               NeutronSecurityGroupToSecurityGroup.Factory neutronSecurityGroupToSecurityGroup) {\n      this.novaApi = novaApi;\n      this.locationIndex = locationIndex;\n      this.securityGroupInRegionSecurityGroupFunction = securityGroupInRegionSecurityGroupFunction;\n      this.neutronSecurityGroupToSecurityGroup = neutronSecurityGroupToSecurityGroup;\n   }\n\n   @Override\n   public SecurityGroup apply(final RegionSecurityGroupNameAndPorts regionSecurityGroupNameAndPorts) {\n      String regionId = regionSecurityGroupNameAndPorts.getRegion();\n      Location location = locationIndex.get().get(regionId);\n\n      logger.debug(\">> creating securityGroup %s\", regionSecurityGroupNameAndPorts);\n\n      SecurityGroupApi securityGroupApi = getNeutronSecurityGroupApi(regionId);\n      if (securityGroupApi != null) {\n         org.jclouds.openstack.neutron.v2.domain.SecurityGroup group = securityGroupApi\n               .create(org.jclouds.openstack.neutron.v2.domain.SecurityGroup.CreateSecurityGroup.createBuilder()\n                     .name(regionSecurityGroupNameAndPorts.getName()).description(\"security group created by jclouds\")\n                     .build());\n         return createSecurityGroupFrom(group, location, regionSecurityGroupNameAndPorts.getPorts());\n      } else {\n         // try to use Nova\n         Optional<? extends org.jclouds.openstack.nova.v2_0.extensions.SecurityGroupApi> api = novaApi\n               .getSecurityGroupApi(regionId);\n         checkArgument(api.isPresent(),\n               \"Security groups are required, but the extension is not available in region %s!\", regionId);\n         final FluentIterable<org.jclouds.openstack.nova.v2_0.domain.SecurityGroup> allGroups = api.get().list();\n         logger.debug(\">> creating securityGroup %s\", regionSecurityGroupNameAndPorts);\n         try {\n            org.jclouds.openstack.nova.v2_0.domain.SecurityGroup novaSecurityGroup = api.get().createWithDescription(\n                  regionSecurityGroupNameAndPorts.getName(), regionSecurityGroupNameAndPorts.getName());\n\n            logger.debug(\"<< created securityGroup(%s)\", novaSecurityGroup);\n            for (int port : regionSecurityGroupNameAndPorts.getPorts()) {\n               authorizeGroupToItselfAndAllIPsToTCPPort(api.get(), novaSecurityGroup, port);\n            }\n            return securityGroupInRegionSecurityGroupFunction\n                  .apply(new SecurityGroupInRegion(api.get().get(novaSecurityGroup.getId()), regionId, allGroups));\n         } catch (IllegalStateException e) {\n            logger.trace(\"<< trying to find securityGroup(%s): %s\", regionSecurityGroupNameAndPorts, e.getMessage());\n            org.jclouds.openstack.nova.v2_0.domain.SecurityGroup group = find(allGroups,\n                  nameEquals(regionSecurityGroupNameAndPorts.getName()));\n            logger.debug(\"<< reused securityGroup(%s)\", group.getId());\n            return securityGroupInRegionSecurityGroupFunction\n                  .apply(new SecurityGroupInRegion(group, regionId, allGroups));\n         }\n      }\n   }\n\n   private SecurityGroup createSecurityGroupFrom(final org.jclouds.openstack.neutron.v2.domain.SecurityGroup group,\n         Location location, Set<Integer> ports) {\n      SecurityGroup securityGroup = neutronSecurityGroupToSecurityGroup.create(location).apply(group);\n      logger.debug(\"<< created securityGroup(%s)\", securityGroup);\n\n      SecurityGroupApi securityGroupApi = getNeutronSecurityGroupApi(location.getId());\n      try {\n         for (int inboundPort : ports) {\n            logger.debug(\">> authorizing securityGroup(%s) permission to 0.0.0.0/0 on port %d\", securityGroup, inboundPort);\n            securityGroupApi.create(\n                  Rule.CreateRule.createBuilder(RuleDirection.INGRESS, RegionAndId.fromSlashEncoded(securityGroup.getId()).getId()).protocol(RuleProtocol.TCP)\n                        .portRangeMin(inboundPort).portRangeMax(inboundPort).remoteIpPrefix(\"0.0.0.0/0\").build());\n            logger.debug(\"<< authorized securityGroup(%s) permission to 0.0.0.0/0 on port %d\", securityGroup, inboundPort);\n         }\n         return securityGroup;\n      } catch (IllegalStateException e) {\n         logger.trace(\"<< trying to find securityGroup(%s): %s\", group, e.getMessage());\n\n         return securityGroupApi.listSecurityGroups().concat()\n               .filter(new Predicate<org.jclouds.openstack.neutron.v2.domain.SecurityGroup>() {\n                  @Override\n                  public boolean apply(@Nullable org.jclouds.openstack.neutron.v2.domain.SecurityGroup input) {\n                     return input.getName().equals(group.getName());\n                  }\n               }).transform(neutronSecurityGroupToSecurityGroup.create(location)).first().orNull();\n      }\n   }\n\n   private SecurityGroupApi getNeutronSecurityGroupApi(String region) {\n      if (neutronContextSupplier == null)\n         return null;\n      return ((ApiContext<NeutronApi>) neutronContextSupplier.get()).getApi().getSecurityGroupApi(region);\n   }\n\n   private void authorizeGroupToItselfAndAllIPsToTCPPort(\n         org.jclouds.openstack.nova.v2_0.extensions.SecurityGroupApi securityGroupApi,\n         org.jclouds.openstack.nova.v2_0.domain.SecurityGroup securityGroup, int port) {\n      logger.debug(\">> authorizing securityGroup(%s) permission to 0.0.0.0/0 on port %d\", securityGroup, port);\n      securityGroupApi.createRuleAllowingCidrBlock(securityGroup.getId(),\n            Ingress.builder().ipProtocol(IpProtocol.TCP).fromPort(port).toPort(port).build(), \"0.0.0.0/0\");\n      logger.debug(\"<< authorized securityGroup(%s) permission to 0.0.0.0/0 on port %d\", securityGroup, port);\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/functions/FlavorInRegionToHardware.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.compute.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.HardwareBuilder;\nimport org.jclouds.compute.domain.Processor;\nimport org.jclouds.compute.domain.internal.VolumeImpl;\nimport org.jclouds.domain.Location;\nimport org.jclouds.openstack.nova.v2_0.domain.Flavor;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.FlavorInRegion;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\n\n/**\n * A function for transforming the nova specific FlavorInRegion object to the generic Hardware object.\n */\npublic class FlavorInRegionToHardware implements Function<FlavorInRegion, Hardware> {\n\n   private final Supplier<Map<String, Location>> locationIndex;\n\n   @Inject\n   public FlavorInRegionToHardware(Supplier<Map<String, Location>> locationIndex) {\n      this.locationIndex = checkNotNull(locationIndex, \"locationIndex\");\n   }\n\n   @Override\n   public Hardware apply(FlavorInRegion flavorInRegion) {\n      Location location = locationIndex.get().get(flavorInRegion.getRegion());\n      checkState(location != null, \"location %s not in locationIndex: %s\", flavorInRegion.getRegion(), locationIndex.get());\n      Flavor flavor = flavorInRegion.getFlavor();\n      return new HardwareBuilder().id(flavorInRegion.slashEncode()).providerId(flavor.getId()).name(flavor.getName())\n               .ram(flavor.getRam()).processor(new Processor(flavor.getVcpus(), 1.0)).volume(\n                        new VolumeImpl(Float.valueOf(flavor.getDisk()), true, true)).location(location).build();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/functions/ImageInRegionToImage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.compute.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.ImageBuilder;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.domain.Location;\nimport org.jclouds.openstack.nova.v2_0.domain.Image.Status;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.ImageInRegion;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Supplier;\n\n/**\n * A function for transforming a nova-specific Image into a generic Image object.\n */\npublic class ImageInRegionToImage implements Function<ImageInRegion, Image> {\n   private final Map<Status, org.jclouds.compute.domain.Image.Status> toPortableImageStatus;\n   private final Function<org.jclouds.openstack.nova.v2_0.domain.Image, OperatingSystem> imageToOs;\n   private final Supplier<Map<String, Location>> locationIndex;\n\n   @Inject\n   public ImageInRegionToImage(Map<org.jclouds.openstack.nova.v2_0.domain.Image.Status, Image.Status> toPortableImageStatus,\n            Function<org.jclouds.openstack.nova.v2_0.domain.Image, OperatingSystem> imageToOs,\n            Supplier<Map<String, Location>> locationIndex) {\n      this.toPortableImageStatus = checkNotNull(toPortableImageStatus, \"toPortableImageStatus\");\n      this.imageToOs = checkNotNull(imageToOs, \"imageToOs\");\n      this.locationIndex = checkNotNull(locationIndex, \"locationIndex\");\n   }\n\n   @Override\n   public Image apply(ImageInRegion imageInRegion) {\n      Location location = locationIndex.get().get(imageInRegion.getRegion());\n      checkState(location != null, \"location %s not in locationIndex: %s\", imageInRegion.getRegion(), locationIndex.get());\n      org.jclouds.openstack.nova.v2_0.domain.Image image = imageInRegion.getImage();\n      return new ImageBuilder().id(imageInRegion.slashEncode()).providerId(image.getId()).name(image.getName())\n               .userMetadata(image.getMetadata()).operatingSystem(imageToOs.apply(image)).description(image.getName())\n               .location(location).status(toPortableImageStatus.get(image.getStatus())).build();\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).toString();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/functions/ImageToOperatingSystem.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.compute.functions;\n\nimport static com.google.common.base.Predicates.containsPattern;\nimport static com.google.common.base.Predicates.equalTo;\nimport static com.google.common.base.Predicates.not;\nimport static com.google.common.collect.Iterables.any;\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.find;\n\nimport java.util.Arrays;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\n\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.compute.util.ComputeServiceUtils;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.openstack.nova.v2_0.domain.Image;\n\nimport com.google.common.base.CharMatcher;\nimport com.google.common.base.Function;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Splitter;\n\n/**\n * A function for transforming a nova specific Image into a generic OperatingSystem object.\n */\npublic class ImageToOperatingSystem implements Function<Image, OperatingSystem> {\n   public static final Pattern DEFAULT_PATTERN = Pattern.compile(\"(([^ ]*) ([0-9.]+) ?.*)\");\n   // Windows Server 2008 R2 x64\n   public static final Pattern WINDOWS_PATTERN = Pattern.compile(\"Windows (.*) (x[86][64])\");\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   protected final Map<OsFamily, Map<String, String>> osVersionMap;\n\n   @Inject\n   public ImageToOperatingSystem(Map<OsFamily, Map<String, String>> osVersionMap) {\n      this.osVersionMap = osVersionMap;\n   }\n\n   public OperatingSystem apply(final Image from) {\n      OsFamily osFamily = null;\n      String osVersion = null;\n\n      String imageName = MoreObjects.firstNonNull(from.getName(), \"unspecified\");\n\n      boolean is64Bit = true;\n\n      if (imageName.indexOf(\"Windows\") != -1) {\n         osFamily = OsFamily.WINDOWS;\n         Matcher matcher = WINDOWS_PATTERN.matcher(from.getName());\n         if (matcher.find()) {\n            osVersion = ComputeServiceUtils.parseVersionOrReturnEmptyString(osFamily, matcher.group(1), osVersionMap);\n            is64Bit = matcher.group(2).equals(\"x64\");\n         }\n      } else {\n         if (imageName.contains(\"Red Hat\")) {\n            osFamily = OsFamily.RHEL;\n         } else if (imageName.contains(\"Oracle\")) {\n            osFamily = OsFamily.OEL;\n         } else {\n            final Iterable<String> imageNameParts = Splitter.on(CharMatcher.whitespace()).trimResults().split(\n                     imageName.toLowerCase());\n\n            try {\n               osFamily = find(Arrays.asList(OsFamily.values()), new Predicate<OsFamily>() {\n                  @Override\n                  public boolean apply(OsFamily osFamily) {\n                     return any(imageNameParts, equalTo(osFamily.name().toLowerCase()));\n                  }\n               });\n            } catch (NoSuchElementException e) {\n               String ubuntuVersion = startsWithUbuntuVersion(imageNameParts);\n               if (ubuntuVersion != null) {\n                  osFamily = OsFamily.UBUNTU;\n                  osVersion = ubuntuVersion;\n               } else {\n                  logger.trace(\"could not parse operating system family for image(%s): %s\", from.getId(), imageNameParts);\n                  osFamily = OsFamily.UNRECOGNIZED;\n               }\n            }\n         }\n         Matcher matcher = DEFAULT_PATTERN.matcher(imageName);\n         if (matcher.find() && matcher.groupCount() >= 3) {\n            osVersion = ComputeServiceUtils.parseVersionOrReturnEmptyString(osFamily, matcher.group(3), osVersionMap);\n         }\n      }\n      return new OperatingSystem(osFamily, imageName, osVersion, null, imageName, is64Bit);\n   }\n\n   String startsWithUbuntuVersion(final Iterable<String> imageNameParts) {\n      Map<String, String> ubuntuVersions = osVersionMap.get(OsFamily.UBUNTU);\n      for (String ubuntuKey : filter(ubuntuVersions.keySet(), not(equalTo(\"\")))) {\n         if (any(imageNameParts, containsPattern(\"^\" + ubuntuKey + \".*\"))) {\n            return ubuntuVersions.get(ubuntuKey);\n         }\n      }\n      return null;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/functions/NeutronSecurityGroupToSecurityGroup.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.compute.functions;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicates;\nimport com.google.inject.assistedinject.Assisted;\nimport org.jclouds.compute.domain.SecurityGroup;\nimport org.jclouds.compute.domain.SecurityGroupBuilder;\nimport org.jclouds.domain.Location;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.net.domain.IpPermission;\nimport org.jclouds.net.domain.IpProtocol;\nimport org.jclouds.openstack.neutron.v2.domain.Rule;\nimport org.jclouds.openstack.neutron.v2.domain.RuleDirection;\n\nimport jakarta.inject.Inject;\n\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.transform;\n\npublic class NeutronSecurityGroupToSecurityGroup implements Function<org.jclouds.openstack.neutron.v2.domain.SecurityGroup, SecurityGroup> {\n\n    public interface Factory {\n        NeutronSecurityGroupToSecurityGroup create(Location location);\n    }\n\n    private final Location location;\n\n    @Inject\n    public NeutronSecurityGroupToSecurityGroup(@Assisted Location location) {\n        this.location = location;\n    }\n\n    @Override\n    public SecurityGroup apply(@Nullable org.jclouds.openstack.neutron.v2.domain.SecurityGroup group) {\n        SecurityGroupBuilder builder = new SecurityGroupBuilder();\n        builder.providerId(group.getId());\n        builder.ownerId(group.getTenantId());\n        builder.name(group.getName());\n        final String regionId = location.getId();\n        builder.location(location);\n\n        builder.id(regionId + \"/\" + group.getId());\n        if (group.getRules() != null) {\n            builder.ipPermissions(filter(transform(group.getRules(), new Function<Rule, IpPermission>() {\n                @Override\n                public IpPermission apply(Rule from) {\n                    if (from.getDirection() == RuleDirection.EGRESS) return null;\n                    IpPermission.Builder builder = IpPermission.builder();\n                    if (from.getProtocol() != null) {\n                        builder.ipProtocol(IpProtocol.fromValue(from.getProtocol().name()));\n                    } else {\n                        builder.ipProtocol(IpProtocol.TCP);\n                    }\n                    if (from.getPortRangeMin() != null) builder.fromPort(from.getPortRangeMin());\n                    if (from.getPortRangeMax() != null) builder.toPort(from.getPortRangeMax());\n                    if (from.getRemoteGroupId() != null) {\n                        builder.groupId(regionId + \"/\" + from.getRemoteGroupId());\n                    } else if (from.getRemoteIpPrefix() != null){\n                        builder.cidrBlock(from.getRemoteIpPrefix());\n                    }\n\n                    return builder.build();\n                }\n            }), Predicates.notNull()));\n        }\n\n        return builder.build();\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/functions/NovaSecurityGroupInRegionToSecurityGroup.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.compute.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.transform;\n\nimport java.util.Collection;\nimport java.util.Map;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.domain.SecurityGroup;\nimport org.jclouds.compute.domain.SecurityGroupBuilder;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.domain.Location;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.net.domain.IpPermission;\nimport org.jclouds.openstack.nova.v2_0.domain.SecurityGroupRule;\nimport org.jclouds.openstack.nova.v2_0.domain.TenantIdAndName;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.SecurityGroupInRegion;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicates;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.Iterables;\nimport com.google.inject.Inject;\n\n\n/**\n * A function for transforming a Nova-specific SecurityGroup into a generic\n * SecurityGroup object.\n */\n@Singleton\npublic class NovaSecurityGroupInRegionToSecurityGroup implements Function<SecurityGroupInRegion, SecurityGroup> {\n    @Resource\n    @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n    protected Logger logger = Logger.NULL;\n\n    protected final Supplier<Map<String, Location>> locationIndex;\n\n    @Inject\n    public NovaSecurityGroupInRegionToSecurityGroup(Supplier<Map<String, Location>> locationIndex) {\n        this.locationIndex = checkNotNull(locationIndex, \"locationIndex\");\n    }\n\n    @Override\n    public SecurityGroup apply(final SecurityGroupInRegion groupInRegion) {\n        SecurityGroupBuilder builder = new SecurityGroupBuilder();\n\n        final org.jclouds.openstack.nova.v2_0.domain.SecurityGroup group = groupInRegion.getSecurityGroup();\n        builder.id(group.getId());\n        builder.providerId(group.getId());\n        builder.ownerId(group.getTenantId());\n        builder.name(group.getName());\n        if (group.getRules() != null) {\n           builder.ipPermissions(filter(transform(group.getRules(), new Function<SecurityGroupRule, IpPermission>() {\n              @Override\n              public IpPermission apply(SecurityGroupRule input) {\n                 return securityGroupRuleToIpPermission(groupInRegion, input);\n              }\n           }), Predicates.notNull()));\n        }\n\n        final String regionId = groupInRegion.getRegion();\n        Location region = locationIndex.get().get(regionId);\n        checkState(region != null, \"location %s not in locationIndex: %s\", regionId, locationIndex.get());\n\n        builder.location(region);\n\n        builder.id(regionId + \"/\" + group.getId());\n\n        return builder.build();\n    }\n\n    private IpPermission securityGroupRuleToIpPermission(SecurityGroupInRegion groupInRegion, SecurityGroupRule rule) {\n        IpPermission.Builder builder = IpPermission.builder();\n        builder.ipProtocol(rule.getIpProtocol());\n        builder.fromPort(rule.getFromPort());\n        builder.toPort(rule.getToPort());\n        final TenantIdAndName ruleGroup = rule.getGroup();\n        if (ruleGroup != null) {\n           final org.jclouds.openstack.nova.v2_0.domain.SecurityGroup owningGroup =\n              groupInRegion.getSecurityGroup();\n           final Collection<org.jclouds.openstack.nova.v2_0.domain.SecurityGroup> referredGroup =\n              groupInRegion.getGroupsByName().get(ruleGroup);\n           if (null == referredGroup) {\n              logger.warn(\"Unknown group %s used in security rule, refusing to add it to %s (%s)\",\n                 ruleGroup, owningGroup.getName(), owningGroup.getId());\n              return null;\n           }\n           /*  Checking referredGroup.size(), see comments on SecurityGroupInRegion.getGroupsByName(). If there are\n               duplicate groups with the same tenant-id-and-name as that of ruleGroup then it is not possible\n               with the Nova /v2/12345/os-security-groups API to know which group is intended, as the only\n               information it returns about referred groups is the tenant id and name:\n                        \"group\": {\n                           \"tenant_id\": \"a0ade3ca76784719845363979dc1014e\",\n                           \"name\": \"jclouds-qa-scheduler-docker-entity\"\n                        },\n              Rather than pick one group at random and risk using the wrong group, here we fall back to the\n              least-worst option(?) and refuse to add any rule.\n\n              See https://issues.apache.org/jira/browse/JCLOUDS-1234.\n           */\n           if (referredGroup.size() != 1) {\n              logger.warn(\"Ambiguous group %s used in security rule, refusing to add it to %s (%s)\",\n                 ruleGroup, owningGroup.getName(), owningGroup.getId());\n              return null;\n           }\n           builder.groupId(groupInRegion.getRegion() + \"/\" + Iterables.getOnlyElement(referredGroup).getId());\n        }\n        if (rule.getIpRange() != null) {\n            builder.cidrBlock(rule.getIpRange());\n        }\n        return builder.build();\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/functions/NovaSecurityGroupToSecurityGroup.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.compute.functions;\n\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.transform;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\n\nimport org.jclouds.compute.domain.SecurityGroup;\nimport org.jclouds.compute.domain.SecurityGroupBuilder;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.domain.Location;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.net.domain.IpPermission;\nimport org.jclouds.openstack.nova.v2_0.domain.SecurityGroupRule;\nimport org.jclouds.openstack.nova.v2_0.domain.TenantIdAndName;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicates;\nimport com.google.inject.assistedinject.Assisted;\n\n/**\n * A function for transforming a Nova-specific SecurityGroup into a generic\n * SecurityGroup object.\n */\npublic class NovaSecurityGroupToSecurityGroup\n      implements Function<org.jclouds.openstack.nova.v2_0.domain.SecurityGroup, SecurityGroup> {\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   public interface Factory {\n      NovaSecurityGroupToSecurityGroup create(Location location);\n   }\n\n   private final Location location;\n\n   @Inject\n   public NovaSecurityGroupToSecurityGroup(@Assisted Location location) {\n      this.location = location;\n   }\n\n   @Override\n   public SecurityGroup apply(@Nullable org.jclouds.openstack.nova.v2_0.domain.SecurityGroup group) {\n      SecurityGroupBuilder builder = new SecurityGroupBuilder();\n      builder.providerId(group.getId());\n      builder.ownerId(group.getTenantId());\n      builder.name(group.getName());\n      final String regionId = location.getId();\n      builder.location(location);\n\n      builder.id(regionId + \"/\" + group.getId());\n      if (group.getRules() != null) {\n         builder.ipPermissions(filter(transform(group.getRules(), new Function<SecurityGroupRule, IpPermission>() {\n            @Override\n            public IpPermission apply(SecurityGroupRule input) {\n               return securityGroupRuleToIpPermission(input);\n            }\n         }), Predicates.notNull()));\n      }\n      return builder.build();\n   }\n\n   private IpPermission securityGroupRuleToIpPermission(SecurityGroupRule rule) {\n      IpPermission.Builder builder = IpPermission.builder();\n      builder.ipProtocol(rule.getIpProtocol());\n      builder.fromPort(rule.getFromPort());\n      builder.toPort(rule.getToPort());\n      final TenantIdAndName ruleGroup = rule.getGroup();\n      if (ruleGroup != null) {\n         builder.groupId(location.getId() + \"/\" + ruleGroup.getTenantId());\n      }\n      if (rule.getIpRange() != null) {\n         builder.cidrBlock(rule.getIpRange());\n      }\n      return builder.build();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/functions/OrphanedGroupsByRegionId.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.compute.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.transform;\nimport static com.google.common.collect.Sets.filter;\n\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.compute.ComputeService;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.predicates.NodePredicates;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.openstack.nova.v2_0.compute.predicates.AllNodesInGroupTerminated;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.RegionAndName;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Multimap;\nimport com.google.common.collect.Multimaps;\n\npublic class OrphanedGroupsByRegionId implements Function<Set<? extends NodeMetadata>, Multimap<String, String>> {\n   private final Predicate<RegionAndName> allNodesInGroupTerminated;\n\n   @Inject\n   protected OrphanedGroupsByRegionId(ComputeService computeService) {\n      this(new AllNodesInGroupTerminated(checkNotNull(computeService, \"computeService\")));\n   }\n\n   @VisibleForTesting\n   OrphanedGroupsByRegionId(Predicate<RegionAndName> allNodesInGroupTerminated) {\n      this.allNodesInGroupTerminated = checkNotNull(allNodesInGroupTerminated, \"allNodesInGroupTerminated\");\n   }\n\n   public Multimap<String, String> apply(Set<? extends NodeMetadata> deadNodes) {\n      Iterable<? extends NodeMetadata> nodesWithGroup = filter(deadNodes, NodePredicates.hasGroup());\n      Set<RegionAndName> regionAndGroupNames = ImmutableSet.copyOf(filter(transform(nodesWithGroup,\n               new Function<NodeMetadata, RegionAndName>() {\n\n                  @Override\n                  public RegionAndName apply(NodeMetadata input) {\n                     String regionId = input.getLocation().getScope() == LocationScope.HOST ? input.getLocation()\n                              .getParent().getId() : input.getLocation().getId();\n                     return RegionAndName.fromRegionAndName(regionId, input.getGroup());\n                  }\n\n               }), allNodesInGroupTerminated));\n      Multimap<String, String> regionToRegionAndGroupNames = Multimaps.transformValues(Multimaps.index(regionAndGroupNames,\n               RegionAndName.REGION_FUNCTION), RegionAndName.NAME_FUNCTION);\n      return regionToRegionAndGroupNames;\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/functions/RemoveFloatingIpFromNodeAndDeallocate.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.compute.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\n\nimport com.google.common.base.Supplier;\nimport com.google.inject.Inject;\nimport org.jclouds.Context;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.openstack.neutron.v2.NeutronApi;\nimport org.jclouds.openstack.nova.v2_0.NovaApi;\nimport org.jclouds.openstack.nova.v2_0.domain.FloatingIpForServer;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.RegionAndId;\nimport org.jclouds.openstack.nova.v2_0.extensions.FloatingIPApi;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.cache.LoadingCache;\nimport org.jclouds.rest.ApiContext;\n\n/**\n * A function for removing and deallocating an ip address from a node\n */\npublic class RemoveFloatingIpFromNodeAndDeallocate implements Function<RegionAndId, RegionAndId> {\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   @Inject(optional = true)\n   @Named(\"openstack-neutron\")\n   private Supplier<Context> neutronContextSupplier;\n\n   private final NovaApi novaApi;\n   private final LoadingCache<RegionAndId, Iterable<? extends FloatingIpForServer>> floatingIpCache;\n\n   @Inject\n   public RemoveFloatingIpFromNodeAndDeallocate(NovaApi novaApi,\n            @Named(\"FLOATINGIP\") LoadingCache<RegionAndId, Iterable<? extends FloatingIpForServer>> floatingIpCache) {\n      this.novaApi = checkNotNull(novaApi, \"novaApi\");\n      this.floatingIpCache = checkNotNull(floatingIpCache, \"floatingIpCache\");\n   }\n\n   @Override\n   public RegionAndId apply(RegionAndId id) {\n      if (isNeutronLinked()) {\n         for (FloatingIpForServer floatingIpForServer : floatingIpCache.getUnchecked(id)) {\n            logger.debug(\">> deallocating floatingIp(%s)\", floatingIpForServer);\n            getFloatingIPApi(id.getRegion()).delete(floatingIpForServer.floatingIpId());\n         }\n      } else { // try nova\n         FloatingIPApi floatingIpApi = novaApi.getFloatingIPApi(id.getRegion()).get();\n         for (FloatingIpForServer floatingIpForServer : floatingIpCache.getUnchecked(id)) {\n            logger.debug(\">> removing floatingIp(%s) from node(%s)\", floatingIpForServer, id);\n            floatingIpApi.removeFromServer(floatingIpForServer.ip(), id.getId());\n            logger.debug(\">> deallocating floatingIp(%s)\", floatingIpForServer);\n            floatingIpApi.delete(floatingIpForServer.floatingIpId());\n         }\n      }\n      floatingIpCache.invalidate(id);\n      return id;\n   }\n\n   // FIXME remove duplications from AllocateAndAddFloatingIpToNode\n   private boolean isNeutronLinked() {\n      return neutronContextSupplier != null && neutronContextSupplier.get() != null;\n   }\n\n   private org.jclouds.openstack.neutron.v2.features.FloatingIPApi getFloatingIPApi(String region) {\n      return ((ApiContext<NeutronApi>) neutronContextSupplier.get()).getApi().getFloatingIPApi(region);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(\"RemoveFloatingIpFromNodeAndDeallocate\").toString();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/functions/ServerInRegionToNodeMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.compute.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.common.base.Predicates.and;\nimport static com.google.common.base.Predicates.not;\nimport static com.google.common.base.Predicates.or;\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.find;\nimport static com.google.common.collect.Iterables.transform;\nimport static com.google.common.collect.Sets.newHashSet;\nimport static org.jclouds.compute.util.ComputeServiceUtils.addMetadataAndParseTagsFromCommaDelimitedValue;\nimport static org.jclouds.compute.util.ComputeServiceUtils.groupFromMapOrName;\nimport static org.jclouds.openstack.nova.v2_0.domain.Address.createV4;\nimport static org.jclouds.openstack.nova.v2_0.domain.Address.createV6;\n\nimport java.net.Inet4Address;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\n\nimport com.google.common.base.Optional;\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.domain.ComputeMetadata;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadataBuilder;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.openstack.nova.v2_0.domain.Address;\nimport org.jclouds.openstack.nova.v2_0.domain.Server;\nimport org.jclouds.openstack.nova.v2_0.domain.Server.Status;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.RegionAndId;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.ServerInRegion;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.util.InetAddresses2;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.net.InetAddresses;\n\n/**\n * A function for transforming a nova-specific Server into a generic\n * NodeMetadata object.\n */\npublic class ServerInRegionToNodeMetadata implements Function<ServerInRegion, NodeMetadata> {\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   protected Map<Status, org.jclouds.compute.domain.NodeMetadata.Status> toPortableNodeStatus;\n   protected final Supplier<Map<String, Location>> locationIndex;\n   protected final Supplier<Set<? extends Image>> images;\n   protected final Supplier<Set<? extends Hardware>> hardwares;\n   protected final GroupNamingConvention nodeNamingConvention;\n\n   @Inject\n   public ServerInRegionToNodeMetadata(Map<Server.Status, NodeMetadata.Status> toPortableNodeStatus,\n            Supplier<Map<String, Location>> locationIndex, @Memoized Supplier<Set<? extends Image>> images,\n            @Memoized Supplier<Set<? extends Hardware>> hardwares, GroupNamingConvention.Factory namingConvention) {\n      this.toPortableNodeStatus = checkNotNull(toPortableNodeStatus, \"toPortableNodeStatus\");\n      this.nodeNamingConvention = checkNotNull(namingConvention, \"namingConvention\").createWithoutPrefix();\n      this.locationIndex = checkNotNull(locationIndex, \"locationIndex\");\n      this.images = checkNotNull(images, \"images\");\n      this.hardwares = checkNotNull(hardwares, \"hardwares\");\n   }\n\n   @Override\n   public NodeMetadata apply(ServerInRegion serverInRegion) {\n      Location region = locationIndex.get().get(serverInRegion.getRegion());\n      checkState(region != null, \"location %s not in locationIndex: %s\", serverInRegion.getRegion(), locationIndex.get());\n      Server from = serverInRegion.getServer();\n\n      NodeMetadataBuilder builder = new NodeMetadataBuilder();\n      builder.id(serverInRegion.slashEncode());\n      builder.providerId(from.getId());\n      builder.name(from.getName());\n      builder.hostname(from.getName());\n      builder.location(from.getHostId() != null ? new LocationBuilder().scope(LocationScope.HOST).id(from.getHostId())\n            .description(from.getHostId()).parent(region).build() : region);\n      builder.group(groupFromMapOrName(from.getMetadata(), from.getName(), nodeNamingConvention));\n      addMetadataAndParseTagsFromCommaDelimitedValue(builder, from.getMetadata());\n\n      if (from.getImage() != null) {\n         builder.imageId(RegionAndId.fromRegionAndId(serverInRegion.getRegion(), from.getImage().getId()).slashEncode());\n      }\n\n      builder.operatingSystem(findOperatingSystemForServerOrNull(serverInRegion));\n      builder.hardware(findHardwareForServerOrNull(serverInRegion));\n      builder.status(toPortableNodeStatus.get(from.getStatus()));\n\n      Set<Address> addresses = newHashSet(from.getAddresses().values());\n      if (from.getAccessIPv4() != null) {\n         addresses.add(createV4(from.getAccessIPv4()));\n      }\n      if (from.getAccessIPv6() != null) {\n         addresses.add(createV6(from.getAccessIPv6()));\n      }\n\n      builder.publicAddresses(\n            filter(\n                  transform(\n                        filter(addresses, or(isFloatingAddress, not(isPrivateAddress))),\n                        AddressToStringTransformationFunction.INSTANCE),\n                  isInet4Address));\n\n      builder.privateAddresses(\n            filter(\n                  transform(\n                        filter(addresses, and(not(isFloatingAddress), isPrivateAddress)),\n                        AddressToStringTransformationFunction.INSTANCE),\n                  isInet4Address));\n\n      for (Link link : from.getLinks()) {\n         if (link.getRelation().equals(Link.Relation.SELF)) {\n            builder.uri(link.getHref());\n         }\n      }\n\n      return builder.build();\n   }\n\n   public static final Predicate<Address> isFloatingAddress = new Predicate<Address>() {\n      public boolean apply(Address in) {\n         final Optional<String> addrType = in.getType();\n         return addrType.isPresent() && \"floating\".equals(addrType.get());\n      }\n   };\n\n   public static final Predicate<Address> isPrivateAddress = new Predicate<Address>() {\n      public boolean apply(Address in) {\n         return InetAddresses2.IsPrivateIPAddress.INSTANCE.apply(in.getAddr());\n      }\n   };\n\n   public static final Predicate<String> isInet4Address = new Predicate<String>() {\n      @Override\n      public boolean apply(String input) {\n         try {\n            // Note we can do this, as InetAddress is now on the white list\n            return InetAddresses.forString(input) instanceof Inet4Address;\n         } catch (IllegalArgumentException e) {\n            // could be a hostname\n            return true;\n         }\n      }\n\n   };\n\n   public enum AddressToStringTransformationFunction implements Function<Address, String> {\n      INSTANCE;\n      @Override\n      public String apply(Address address) {\n         return address.getAddr();\n      }\n   }\n\n   protected Hardware findHardwareForServerOrNull(ServerInRegion serverInRegion) {\n      return findObjectOfTypeForServerOrNull(hardwares.get(), \"hardware\", serverInRegion.getServer().getFlavor().getId(),\n            serverInRegion);\n   }\n\n   protected OperatingSystem findOperatingSystemForServerOrNull(ServerInRegion serverInRegion) {\n      if (serverInRegion.getServer().getImage() != null) {\n         Image image = findObjectOfTypeForServerOrNull(\n               images.get(), \"image\", serverInRegion.getServer().getImage().getId(), serverInRegion);\n\n         return (image != null) ? image.getOperatingSystem() : null;\n      } else {\n         return null;\n      }\n\n   }\n\n   public <T extends ComputeMetadata> T findObjectOfTypeForServerOrNull(Set<? extends T> supply, String type,\n         final String objectId, final RegionAndId serverInRegion) {\n      try {\n         return find(supply, new Predicate<T>() {\n            @Override\n            public boolean apply(T input) {\n               return input.getId().equals(RegionAndId.fromRegionAndId(serverInRegion.getRegion(), objectId).slashEncode());\n            }\n         });\n      } catch (NoSuchElementException e) {\n         logger.trace(\"could not find %s with id(%s) for server(%s)\", type, objectId, serverInRegion);\n      }\n      return null;\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/loaders/FindSecurityGroupOrCreate.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.compute.loaders;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.compute.domain.SecurityGroup;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.RegionAndName;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.RegionSecurityGroupNameAndPorts;\n\nimport com.google.common.base.Function;\nimport com.google.common.cache.CacheLoader;\n\npublic class FindSecurityGroupOrCreate extends CacheLoader<RegionAndName, SecurityGroup> {\n\n   protected final Function<RegionSecurityGroupNameAndPorts, SecurityGroup> groupCreator;\n\n   @Inject\n   public FindSecurityGroupOrCreate(\n            Function<RegionSecurityGroupNameAndPorts, SecurityGroup> groupCreator) {\n      this.groupCreator = checkNotNull(groupCreator, \"groupCreator\");\n   }\n\n   @Override\n   public SecurityGroup load(RegionAndName in) {\n         return createNewSecurityGroup(in);\n   }\n\n   private SecurityGroup createNewSecurityGroup(RegionAndName in) {\n      checkState(\n               checkNotNull(in, \"regionSecurityGroupNameAndPorts\") instanceof RegionSecurityGroupNameAndPorts,\n               \"programming error: when issuing get to this cacheloader, you need to pass an instance of RegionSecurityGroupNameAndPorts, not %s\",\n               in);\n      RegionSecurityGroupNameAndPorts regionSecurityGroupNameAndPorts = RegionSecurityGroupNameAndPorts.class.cast(in);\n      return groupCreator.apply(regionSecurityGroupNameAndPorts);\n   }\n\n   @Override\n   public String toString() {\n      return \"returnExistingSecurityGroupInRegionOrCreateAsNeeded()\";\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/loaders/LoadFloatingIpsForInstance.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.compute.loaders;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport com.google.common.base.Function;\nimport org.jclouds.openstack.nova.v2_0.NovaApi;\nimport org.jclouds.openstack.nova.v2_0.domain.FloatingIP;\nimport org.jclouds.openstack.nova.v2_0.domain.FloatingIpForServer;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.RegionAndId;\nimport org.jclouds.openstack.nova.v2_0.extensions.FloatingIPApi;\n\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Each region may or may not have the floating ip function present. In order to safely proceed, we\n * must allow the user to determine if a region has floating ip services before attempting to use\n * them.\n */\n@Singleton\npublic class LoadFloatingIpsForInstance extends CacheLoader<RegionAndId, Iterable<? extends FloatingIpForServer>> {\n   private final NovaApi api;\n\n   @Inject\n   public LoadFloatingIpsForInstance(NovaApi api) {\n      this.api = api;\n   }\n\n   @Override\n   public Iterable<? extends FloatingIpForServer> load(final RegionAndId key) throws Exception {\n      String region = key.getRegion();\n      Optional<? extends FloatingIPApi> ipApiOptional = api.getFloatingIPApi(region);\n      if (ipApiOptional.isPresent()) {\n         return ipApiOptional.get().list().filter(\n                  new Predicate<FloatingIP>() {\n                     @Override\n                     public boolean apply(FloatingIP input) {\n                        return key.getId().equals(input.getInstanceId());\n                     }\n                  })\n                 .transform(new Function<FloatingIP, FloatingIpForServer>() {\n                     @Override\n                     public FloatingIpForServer apply(FloatingIP input) {\n                         return FloatingIpForServer.create(key, input.getId(), input.getIp());\n                     }\n                 });\n      }\n      return ImmutableSet.of();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/options/NodeAndNovaTemplateOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.compute.options;\n\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport org.jclouds.compute.domain.NodeMetadata;\n\nimport com.google.common.util.concurrent.Atomics;\n\n/**\n * Simple data-structure for holding a NodeMetadata object along with a\n * corresponding NovaTemplateOptions object.\n */\npublic class NodeAndNovaTemplateOptions {\n\n   private final AtomicReference<NodeMetadata> nodeMetadata;\n   private final AtomicReference<NovaTemplateOptions> novaTemplateOptions;\n\n   protected NodeAndNovaTemplateOptions(AtomicReference<NodeMetadata> nodeMetadata, AtomicReference<NovaTemplateOptions> novaTemplateOptions) {\n      this.nodeMetadata = nodeMetadata;\n      this.novaTemplateOptions = novaTemplateOptions;\n   }\n\n   public AtomicReference<NodeMetadata> getNodeMetadata() {\n      return nodeMetadata;\n   }\n\n   public AtomicReference<NovaTemplateOptions> getNovaTemplateOptions() {\n      return novaTemplateOptions;\n   }\n\n   public static NodeAndNovaTemplateOptions newReference(AtomicReference<NodeMetadata> node, AtomicReference<NovaTemplateOptions> options) {\n      return new NodeAndNovaTemplateOptions(node, options);\n   }\n\n   public static AtomicReference<NodeAndNovaTemplateOptions> newAtomicReference(AtomicReference<NodeMetadata> node, AtomicReference<NovaTemplateOptions> options) {\n      return Atomics.newReference(NodeAndNovaTemplateOptions.newReference(node, options));\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/options/NovaTemplateOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.compute.options;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Strings.emptyToNull;\n\nimport java.util.Arrays;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.openstack.nova.v2_0.NovaApi;\nimport org.jclouds.openstack.nova.v2_0.domain.BlockDeviceMapping;\nimport org.jclouds.openstack.nova.v2_0.domain.Network;\nimport org.jclouds.openstack.nova.v2_0.options.CreateServerOptions;\nimport org.jclouds.scriptbuilder.domain.Statement;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Contains options supported in the {@code ComputeService#runNode} operation on the\n * \"openstack-nova\" provider. <h2>Usage</h2> The recommended way to instantiate a\n * NovaTemplateOptions object is to statically import NovaTemplateOptions.* and invoke a static\n * creation method followed by an instance mutator (if needed):\n * <p/>\n * <code>\n * import static org.jclouds.aws.ec2.compute.options.NovaTemplateOptions.Builder.*;\n * <p/>\n * ComputeService api = // get connection\n * templateBuilder.options(inboundPorts(22, 80, 8080, 443));\n * Set<? extends NodeMetadata> set = api.createNodesInGroup(tag, 2, templateBuilder.build());\n * <code>\n */\npublic class NovaTemplateOptions extends TemplateOptions implements Cloneable {\n   @Override\n   public NovaTemplateOptions clone() {\n      NovaTemplateOptions options = new NovaTemplateOptions();\n      copyTo(options);\n      return options;\n   }\n\n   @Override\n   public void copyTo(TemplateOptions to) {\n      super.copyTo(to);\n      if (to instanceof NovaTemplateOptions) {\n         NovaTemplateOptions eTo = NovaTemplateOptions.class.cast(to);\n         eTo.autoAssignFloatingIp(shouldAutoAssignFloatingIp());\n         if (getFloatingIpPoolNames().isPresent())\n            eTo.floatingIpPoolNames(getFloatingIpPoolNames().get());\n         eTo.generateKeyPair(shouldGenerateKeyPair());\n         eTo.keyPairName(getKeyPairName());\n         if (getUserData() != null) {\n            eTo.userData(getUserData());\n         }\n         if (getDiskConfig() != null) {\n            eTo.diskConfig(getDiskConfig());\n         }\n\n         eTo.configDrive(getConfigDrive());\n         eTo.novaNetworks(getNovaNetworks());\n         eTo.availabilityZone(getAvailabilityZone());\n         eTo.blockDeviceMappings(getBlockDeviceMappings());\n      }\n   }\n\n   protected boolean autoAssignFloatingIp = false;\n   protected Optional<Set<String>> floatingIpPoolNames = Optional.absent();\n   protected boolean generateKeyPair = false;\n   protected String keyPairName;\n   protected byte[] userData;\n   protected String diskConfig;\n   protected boolean configDrive;\n   protected Set<Network> novaNetworks;\n   protected String availabilityZone;\n   // TODO move up to TemplateOptions as SoftLayer also have something similar?\n   protected Set<BlockDeviceMapping> blockDeviceMappings = ImmutableSet.of();\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o)\n         return true;\n      if (o == null || getClass() != o.getClass())\n         return false;\n      NovaTemplateOptions that = NovaTemplateOptions.class.cast(o);\n      return super.equals(that) && equal(this.autoAssignFloatingIp, that.autoAssignFloatingIp)\n            && equal(this.floatingIpPoolNames, that.floatingIpPoolNames)\n            && equal(this.generateKeyPair, that.generateKeyPair)\n            && equal(this.keyPairName, that.keyPairName)\n            && Arrays.equals(this.userData, that.userData)\n            && equal(this.diskConfig, that.diskConfig)\n            && equal(this.configDrive, that.configDrive)\n            && equal(this.novaNetworks, that.novaNetworks)\n            && equal(this.availabilityZone, that.availabilityZone)\n            && equal(this.blockDeviceMappings, that.blockDeviceMappings);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(super.hashCode(), autoAssignFloatingIp, floatingIpPoolNames, generateKeyPair, keyPairName, \n              Arrays.hashCode(userData), diskConfig, configDrive, novaNetworks, availabilityZone, blockDeviceMappings);\n   }\n\n   @Override\n   public ToStringHelper string() {\n      ToStringHelper toString = super.string();\n      if (!autoAssignFloatingIp)\n         toString.add(\"autoAssignFloatingIp\", autoAssignFloatingIp);\n      if (floatingIpPoolNames.isPresent())\n         toString.add(\"floatingIpPoolNames\", floatingIpPoolNames.get());\n      if (generateKeyPair)\n         toString.add(\"generateKeyPair\", generateKeyPair);\n      toString.add(\"keyPairName\", keyPairName);\n      toString.add(\"userData\", userData);\n      toString.add(\"diskConfig\", diskConfig);\n      toString.add(\"configDrive\", configDrive);\n      toString.add(\"novaNetworks\", novaNetworks);\n      toString.add(\"availabilityZone\", availabilityZone);\n      toString.add(\"blockDeviceMappings\", blockDeviceMappings);\n      return toString;\n   }\n\n   /**\n    * @see #getFloatingIpPoolNames()\n    */\n   public NovaTemplateOptions autoAssignFloatingIp(boolean enable) {\n      this.autoAssignFloatingIp = enable;\n      return this;\n   }\n\n   /**\n    * @see #getFloatingIpPoolNames()\n    */\n   public NovaTemplateOptions floatingIpPoolNames(String... floatingIpPoolNames) {\n      return floatingIpPoolNames(ImmutableSet.copyOf(checkNotNull(floatingIpPoolNames, \"floatingIpPoolNames\")));\n   }\n\n   /**\n    * @see #getFloatingIpPoolNames()\n    */\n   public NovaTemplateOptions floatingIpPoolNames(Iterable<String> floatingIpPoolNames) {\n      for (String groupName : checkNotNull(floatingIpPoolNames, \"floatingIpPoolNames\"))\n        checkNotNull(emptyToNull(groupName), \"all floating-ip-pool-names must be non-empty\");\n      this.floatingIpPoolNames = Optional.<Set<String>> of(ImmutableSet.copyOf(floatingIpPoolNames));\n      return this;\n   }\n\n   /**\n    * @see #shouldGenerateKeyPair()\n    */\n   public NovaTemplateOptions generateKeyPair(boolean enable) {\n      this.generateKeyPair = enable;\n      return this;\n   }\n\n   /**\n    * @see #shouldGenerateKeyPair()\n    */\n   public NovaTemplateOptions keyPairName(String keyPairName) {\n      this.keyPairName = keyPairName;\n      return this;\n   }\n\n   /**\n    * <h3>Note</h3>\n    *\n    * This requires that {@link NovaApi#getExtensionApi(String)} to return\n    * {@link Optional#isPresent present}\n    *\n    * @return true if auto assignment of a floating ip to each vm is enabled\n    */\n   public boolean shouldAutoAssignFloatingIp() {\n      return autoAssignFloatingIp;\n   }\n\n   /**\n    * @see CreateServerOptions#getAvailabilityZone()\n    */\n   public NovaTemplateOptions availabilityZone(String availabilityZone) {\n      this.availabilityZone = availabilityZone;\n      return this;\n   }\n\n   /**\n    * @see #getBlockDeviceMappings()\n    */\n   public NovaTemplateOptions blockDeviceMappings(BlockDeviceMapping... blockDeviceMappings) {\n      return blockDeviceMappings(ImmutableSet.copyOf(checkNotNull(blockDeviceMappings, \"blockDeviceMappings\")));\n   }\n\n   /**\n    * @see #getBlockDeviceMappings()\n    */\n   public NovaTemplateOptions blockDeviceMappings(Iterable<BlockDeviceMapping> blockDeviceMappings) {\n      this.blockDeviceMappings = ImmutableSet.copyOf(blockDeviceMappings);\n      return this;\n   }\n\n   /**\n    * The floating IP pool name(s) to use when allocating a FloatingIP. Applicable\n    * only if #shouldAutoAssignFloatingIp() returns true. If not set will attempt to\n    * use whatever FloatingIP(s) can be found regardless of which pool they originated\n    * from\n    *\n    * @return floating-ip-pool names to use\n    */\n   public Optional<Set<String>> getFloatingIpPoolNames() {\n      return floatingIpPoolNames;\n   }\n\n   /**\n    * Specifies the keypair used to run instances with\n    * @return the keypair to be used\n    */\n   public String getKeyPairName() {\n      return keyPairName;\n   }\n\n   /**\n    * <h3>Note</h3>\n    *\n    * This requires that {@link NovaApi#getKeyPairApi(String)} to return\n    * {@link Optional#isPresent present}\n    *\n    * @return true if auto generation of keypairs is enabled\n    */\n   public boolean shouldGenerateKeyPair() {\n      return generateKeyPair;\n   }\n\n   public byte[] getUserData() {\n      return userData;\n   }\n\n   /**\n    * @see CreateServerOptions#getDiskConfig()\n    */\n   public String getDiskConfig() {\n      return diskConfig;\n   }\n\n   /**\n    * @see CreateServerOptions#getConfigDrive()\n    */\n   public boolean getConfigDrive() {\n      return configDrive;\n   }\n\n   /**\n    * @see CreateServerOptions#getNetworks()\n    */\n   public Set<Network> getNovaNetworks() {\n      return novaNetworks;\n   }\n\n   /**\n    * @see CreateServerOptions#getAvailabilityZone()\n    */\n   public String getAvailabilityZone() {\n      return availabilityZone;\n   }\n\n   public Set<BlockDeviceMapping> getBlockDeviceMappings() {\n      return blockDeviceMappings;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see NovaTemplateOptions#shouldAutoAssignFloatingIp()\n       */\n      public static NovaTemplateOptions autoAssignFloatingIp(boolean enable) {\n         return new NovaTemplateOptions().autoAssignFloatingIp(enable);\n      }\n\n      /**\n       * @see #getFloatingIpPoolNames()\n       */\n      public NovaTemplateOptions floatingIpPoolNames(String... floatingIpPoolNames) {\n         NovaTemplateOptions options = new NovaTemplateOptions();\n         return NovaTemplateOptions.class.cast(options.floatingIpPoolNames(floatingIpPoolNames));\n      }\n\n      /**\n       * @see #getFloatingIpPoolNames()\n       */\n      public NovaTemplateOptions floatingIpPoolNames(Iterable<String> floatingIpPoolNames) {\n         NovaTemplateOptions options = new NovaTemplateOptions();\n         return NovaTemplateOptions.class.cast(options.floatingIpPoolNames(floatingIpPoolNames));\n      }\n\n      /**\n       * @see NovaTemplateOptions#shouldGenerateKeyPair()\n       */\n      public static NovaTemplateOptions generateKeyPair(boolean enable) {\n         return new NovaTemplateOptions().generateKeyPair(enable);\n      }\n\n      /**\n       * @see NovaTemplateOptions#getKeyPairName()\n       */\n      public static NovaTemplateOptions keyPairName(String keyPairName) {\n         return new NovaTemplateOptions().keyPairName(keyPairName);\n      }\n\n      // methods that only facilitate returning the correct object type\n\n      /**\n       * @see TemplateOptions#inboundPorts\n       */\n      public static NovaTemplateOptions inboundPorts(int... ports) {\n         NovaTemplateOptions options = new NovaTemplateOptions();\n         return NovaTemplateOptions.class.cast(options.inboundPorts(ports));\n      }\n\n      /**\n       * @see TemplateOptions#port\n       */\n      public static NovaTemplateOptions blockOnPort(int port, int seconds) {\n         NovaTemplateOptions options = new NovaTemplateOptions();\n         return NovaTemplateOptions.class.cast(options.blockOnPort(port, seconds));\n      }\n\n      /**\n       * @see TemplateOptions#installPrivateKey\n       */\n      public static NovaTemplateOptions installPrivateKey(String rsaKey) {\n         NovaTemplateOptions options = new NovaTemplateOptions();\n         return NovaTemplateOptions.class.cast(options.installPrivateKey(rsaKey));\n      }\n\n      /**\n       * @see TemplateOptions#authorizePublicKey\n       */\n      public static NovaTemplateOptions authorizePublicKey(String rsaKey) {\n         NovaTemplateOptions options = new NovaTemplateOptions();\n         return NovaTemplateOptions.class.cast(options.authorizePublicKey(rsaKey));\n      }\n\n      /**\n       * @see TemplateOptions#userMetadata\n       */\n      public static NovaTemplateOptions userMetadata(Map<String, String> userMetadata) {\n         NovaTemplateOptions options = new NovaTemplateOptions();\n         return NovaTemplateOptions.class.cast(options.userMetadata(userMetadata));\n      }\n\n      /**\n       * @see TemplateOptions#nodeNames(Iterable)\n       */\n      public static NovaTemplateOptions nodeNames(Iterable<String> nodeNames) {\n         NovaTemplateOptions options = new NovaTemplateOptions();\n         return NovaTemplateOptions.class.cast(options.nodeNames(nodeNames));\n      }\n\n      /**\n       * @see TemplateOptions#networks(Iterable)\n       */\n      public static NovaTemplateOptions networks(Iterable<String> networks) {\n         NovaTemplateOptions options = new NovaTemplateOptions();\n         return NovaTemplateOptions.class.cast(options.networks(networks));\n      }\n\n      /**\n       * @see TemplateOptions#overrideLoginUser\n       */\n      public static NovaTemplateOptions overrideLoginUser(String user) {\n         NovaTemplateOptions options = new NovaTemplateOptions();\n         return options.overrideLoginUser(user);\n      }\n\n      /**\n       * @see TemplateOptions#overrideLoginPassword\n       */\n      public static NovaTemplateOptions overrideLoginPassword(String password) {\n         NovaTemplateOptions options = new NovaTemplateOptions();\n         return options.overrideLoginPassword(password);\n      }\n\n      /**\n       * @see TemplateOptions#overrideLoginPrivateKey\n       */\n      public static NovaTemplateOptions overrideLoginPrivateKey(String privateKey) {\n         NovaTemplateOptions options = new NovaTemplateOptions();\n         return options.overrideLoginPrivateKey(privateKey);\n      }\n\n      /**\n       * @see TemplateOptions#overrideAuthenticateSudo\n       */\n      public static NovaTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo) {\n         NovaTemplateOptions options = new NovaTemplateOptions();\n         return options.overrideAuthenticateSudo(authenticateSudo);\n      }\n\n      /**\n       * @see TemplateOptions#overrideLoginCredentials\n       */\n      public static NovaTemplateOptions overrideLoginCredentials(LoginCredentials credentials) {\n         NovaTemplateOptions options = new NovaTemplateOptions();\n         return options.overrideLoginCredentials(credentials);\n      }\n\n      /**\n       * @see TemplateOptions#blockUntilRunning\n       */\n      public static NovaTemplateOptions blockUntilRunning(boolean blockUntilRunning) {\n         NovaTemplateOptions options = new NovaTemplateOptions();\n         return options.blockUntilRunning(blockUntilRunning);\n      }\n\n      /**\n       * @see NovaTemplateOptions#userData\n       */\n      public static NovaTemplateOptions userData(byte[] userData) {\n         NovaTemplateOptions options = new NovaTemplateOptions();\n         return NovaTemplateOptions.class.cast(options.userData(userData));\n      }\n\n      /**\n       * @see org.jclouds.openstack.nova.v2_0.options.CreateServerOptions#getDiskConfig()\n       */\n      public static NovaTemplateOptions diskConfig(String diskConfig) {\n         NovaTemplateOptions options = new NovaTemplateOptions();\n         return NovaTemplateOptions.class.cast(options.diskConfig(diskConfig));\n      }\n\n      /**\n       * @see org.jclouds.openstack.nova.v2_0.options.CreateServerOptions#getConfigDrive()\n       */\n      public static NovaTemplateOptions configDrive(boolean configDrive) {\n         NovaTemplateOptions options = new NovaTemplateOptions();\n         return NovaTemplateOptions.class.cast(options.configDrive(configDrive));\n      }\n\n      /**\n       * @see org.jclouds.openstack.nova.v2_0.options.CreateServerOptions#getNetworks()\n       */\n      public static NovaTemplateOptions novaNetworks(Set<Network> novaNetworks) {\n         NovaTemplateOptions options = new NovaTemplateOptions();\n         return NovaTemplateOptions.class.cast(options.novaNetworks(novaNetworks));\n      }\n\n      /**\n       * @see NovaTemplateOptions#getAvailabilityZone()\n       */\n      public static NovaTemplateOptions availabilityZone(String availabilityZone) {\n         NovaTemplateOptions options = new NovaTemplateOptions();\n         return options.availabilityZone(availabilityZone);\n      }\n   }\n\n   // methods that only facilitate returning the correct object type\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public NovaTemplateOptions blockOnPort(int port, int seconds) {\n      return NovaTemplateOptions.class.cast(super.blockOnPort(port, seconds));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public NovaTemplateOptions inboundPorts(int... ports) {\n      return NovaTemplateOptions.class.cast(super.inboundPorts(ports));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public NovaTemplateOptions authorizePublicKey(String publicKey) {\n      return NovaTemplateOptions.class.cast(super.authorizePublicKey(publicKey));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public NovaTemplateOptions installPrivateKey(String privateKey) {\n      return NovaTemplateOptions.class.cast(super.installPrivateKey(privateKey));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public NovaTemplateOptions blockUntilRunning(boolean blockUntilRunning) {\n      return NovaTemplateOptions.class.cast(super.blockUntilRunning(blockUntilRunning));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public NovaTemplateOptions dontAuthorizePublicKey() {\n      return NovaTemplateOptions.class.cast(super.dontAuthorizePublicKey());\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public NovaTemplateOptions nameTask(String name) {\n      return NovaTemplateOptions.class.cast(super.nameTask(name));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public NovaTemplateOptions runAsRoot(boolean runAsRoot) {\n      return NovaTemplateOptions.class.cast(super.runAsRoot(runAsRoot));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public NovaTemplateOptions runScript(Statement script) {\n      return NovaTemplateOptions.class.cast(super.runScript(script));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public NovaTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials) {\n      return NovaTemplateOptions.class.cast(super.overrideLoginCredentials(overridingCredentials));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public NovaTemplateOptions overrideLoginPassword(String password) {\n      return NovaTemplateOptions.class.cast(super.overrideLoginPassword(password));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public NovaTemplateOptions overrideLoginPrivateKey(String privateKey) {\n      return NovaTemplateOptions.class.cast(super.overrideLoginPrivateKey(privateKey));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public NovaTemplateOptions overrideLoginUser(String loginUser) {\n      return NovaTemplateOptions.class.cast(super.overrideLoginUser(loginUser));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public NovaTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo) {\n      return NovaTemplateOptions.class.cast(super.overrideAuthenticateSudo(authenticateSudo));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public NovaTemplateOptions userMetadata(Map<String, String> userMetadata) {\n      return NovaTemplateOptions.class.cast(super.userMetadata(userMetadata));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public NovaTemplateOptions userMetadata(String key, String value) {\n      return NovaTemplateOptions.class.cast(super.userMetadata(key, value));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public NovaTemplateOptions nodeNames(Iterable<String> nodeNames) {\n      return NovaTemplateOptions.class.cast(super.nodeNames(nodeNames));\n   }\n\n   /**\n    * <br>Ensures NovaTemplateOptions can work with networks specified as Strings.\n    * Also provides for compatibility with the abstraction layer.\n    */\n   @Override\n   public NovaTemplateOptions networks(Iterable<String> networks) {\n      return NovaTemplateOptions.class.cast(super.networks(networks));\n   }\n\n   /**\n    * <br>Ensures NovaTemplateOptions can work with networks specified as Strings.\n    * Also provides for compatibility with the abstraction layer.\n    */\n   @Override\n   public NovaTemplateOptions networks(String... networks) {\n      return NovaTemplateOptions.class.cast(super.networks(networks));\n   }\n\n   /**\n    * User data as bytes (not base64-encoded)\n    */\n   public NovaTemplateOptions userData(byte[] userData) {\n      // This limit may not be needed for nova\n      checkArgument(checkNotNull(userData, \"userData\").length <= 16 * 1024,\n            \"userData cannot be larger than 16kb\");\n      this.userData = userData;\n      return this;\n   }\n\n   /**\n    * @see CreateServerOptions#getDiskConfig()\n    */\n   public NovaTemplateOptions diskConfig(String diskConfig) {\n      this.diskConfig = diskConfig;\n      return this;\n   }\n\n   /**\n    * OpenStack can be configured to write metadata to a special configuration drive that will be\n    * attached to the instance when it boots. The instance can retrieve any information that would\n    * normally be available through the metadata service by mounting this disk and reading files from it.\n    * To enable the config drive, set this parameter to \"true\".\n    * This has to be enabled for user data cases.\n    * @see CreateServerOptions#getConfigDrive()\n    */\n   public NovaTemplateOptions configDrive(boolean configDrive) {\n      this.configDrive = configDrive;\n      return this;\n   }\n\n   /**\n    * @param novaNetworks The list of network declarations.\n    * Nova-specific network declarations allow for specifying network UUIDs, port UUIDs, and fixed IPs.\n    * Unline {@link #networks(Iterable)} this supports setting additional network parameters and not just network UUIDs.\n    * @see CreateServerOptions#getNetworks()\n    */\n   public NovaTemplateOptions novaNetworks(Set<Network> novaNetworks) {\n      this.novaNetworks = novaNetworks;\n      return this;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/predicates/AllNodesInGroupTerminated.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.compute.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.all;\nimport static org.jclouds.compute.predicates.NodePredicates.TERMINATED;\nimport static org.jclouds.compute.predicates.NodePredicates.inGroup;\nimport static org.jclouds.compute.predicates.NodePredicates.locationId;\nimport static org.jclouds.compute.predicates.NodePredicates.parentLocationId;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.compute.ComputeService;\nimport org.jclouds.compute.domain.ComputeMetadata;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.RegionAndName;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Predicates;\n\npublic class AllNodesInGroupTerminated implements Predicate<RegionAndName> {\n   private final ComputeService computeService;\n\n\n   //TODO: TESTME\n   @Inject\n   public AllNodesInGroupTerminated(ComputeService computeService) {\n      this.computeService = checkNotNull(computeService, \"computeService\");\n   }\n\n   @Override\n   public boolean apply(RegionAndName input) {\n      // new nodes can have the region as their location, existing nodes, the parent is the\n      // location\n      return all(computeService.listNodesDetailsMatching(Predicates.<ComputeMetadata> or(locationId(input.getRegion()),\n               parentLocationId(input.getRegion()))), Predicates.and(inGroup(input.getName()), TERMINATED));\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/strategy/ApplyNovaTemplateOptionsCreateNodesWithGroupEncodedIntoNameThenAddToSet.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.compute.strategy;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\n\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Constants;\nimport org.jclouds.compute.config.CustomizationResponse;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.SecurityGroup;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.extensions.SecurityGroupExtension;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.compute.strategy.CreateNodeWithGroupEncodedIntoName;\nimport org.jclouds.compute.strategy.CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap;\nimport org.jclouds.compute.strategy.ListNodesStrategy;\nimport org.jclouds.compute.strategy.impl.CreateNodesWithGroupEncodedIntoNameThenAddToSet;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.nova.v2_0.NovaApi;\nimport org.jclouds.openstack.nova.v2_0.compute.functions.AllocateAndAddFloatingIpToNode;\nimport org.jclouds.openstack.nova.v2_0.compute.options.NodeAndNovaTemplateOptions;\nimport org.jclouds.openstack.nova.v2_0.compute.options.NovaTemplateOptions;\nimport org.jclouds.openstack.nova.v2_0.domain.KeyPair;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.RegionAndName;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.RegionSecurityGroupNameAndPorts;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Strings;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Multimap;\nimport com.google.common.primitives.Ints;\nimport com.google.common.util.concurrent.Atomics;\nimport com.google.common.util.concurrent.FutureCallback;\nimport com.google.common.util.concurrent.Futures;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.common.util.concurrent.MoreExecutors;\n\n@Singleton\npublic class ApplyNovaTemplateOptionsCreateNodesWithGroupEncodedIntoNameThenAddToSet extends\n         CreateNodesWithGroupEncodedIntoNameThenAddToSet {\n\n   public static final String JCLOUDS_SG_PREFIX = \"jclouds_sg\";\n\n   private final AllocateAndAddFloatingIpToNode createAndAddFloatingIpToNode;\n   private final LoadingCache<RegionAndName, SecurityGroup> securityGroupCache;\n   private final NovaApi novaApi;\n   private final SecurityGroupExtension securityGroupExtension;\n\n   @Inject\n   protected ApplyNovaTemplateOptionsCreateNodesWithGroupEncodedIntoNameThenAddToSet(\n            CreateNodeWithGroupEncodedIntoName addNodeWithTagStrategy,\n            ListNodesStrategy listNodesStrategy,\n            GroupNamingConvention.Factory namingConvention,\n            CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap.Factory customizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapFactory,\n            @Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor,\n            AllocateAndAddFloatingIpToNode createAndAddFloatingIpToNode,\n            LoadingCache<RegionAndName, SecurityGroup> securityGroupCache,\n            NovaApi novaApi,\n            SecurityGroupExtension securityGroupExtension) {\n      super(addNodeWithTagStrategy, listNodesStrategy, namingConvention, userExecutor,\n               customizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapFactory);\n      this.securityGroupCache = checkNotNull(securityGroupCache, \"securityGroupCache\");\n      this.createAndAddFloatingIpToNode = checkNotNull(createAndAddFloatingIpToNode,\n               \"createAndAddFloatingIpToNode\");\n      this.novaApi = checkNotNull(novaApi, \"novaApi\");\n      this.securityGroupExtension = securityGroupExtension;\n   }\n\n   @Override\n   public Map<?, ListenableFuture<Void>> execute(String group, int count, Template template, Set<NodeMetadata> goodNodes,\n            Map<NodeMetadata, Exception> badNodes, Multimap<NodeMetadata, CustomizationResponse> customizationResponses) {\n\n      NovaTemplateOptions templateOptions = NovaTemplateOptions.class.cast(template.getOptions());\n      final String region = template.getLocation().getId();\n\n      if (templateOptions.shouldAutoAssignFloatingIp()) {\n         checkArgument(novaApi.getFloatingIPApi(region).isPresent(),\n                 \"Floating IPs are required by options, but the extension is not available! options: %s\",\n                 templateOptions);\n      }\n      if (templateOptions.shouldGenerateKeyPair() || templateOptions.getKeyPairName() != null) {\n         checkArgument(novaApi.getKeyPairApi(region).isPresent(),\n                 \"Key Pairs are required by options, but the extension is not available! options: %s\", templateOptions);\n      }\n      final List<Integer> inboundPorts = Ints.asList(templateOptions.getInboundPorts());\n\n      KeyPair keyPair = null;\n      if (templateOptions.shouldGenerateKeyPair()) {\n         keyPair = generateKeyPair(region, namingConvention.create().sharedNameForGroup(group));\n         // If a private key has not been explicitly set, configure the auto-generated one\n         if (Strings.isNullOrEmpty(templateOptions.getLoginPrivateKey())) {\n            templateOptions.overrideLoginPrivateKey(keyPair.getPrivateKey());\n         }\n      } else if (templateOptions.getKeyPairName() != null) {\n         keyPair = checkNotNull(novaApi.getKeyPairApi(region).get().get(templateOptions.getKeyPairName()), \n                     \"keypair %s doesn't exist\", templateOptions.getKeyPairName());\n      }\n      if (keyPair != null) {\n         templateOptions.keyPairName(keyPair.getName());\n      }\n\n      ImmutableList.Builder<String> tagsBuilder = ImmutableList.builder();\n\n      if (!templateOptions.getGroups().isEmpty()) {\n         Iterable<String> securityGroupNames = Iterables.transform(securityGroupExtension.listSecurityGroups(), new Function<org.jclouds.compute.domain.SecurityGroup, String>() {\n            @Override\n            public String apply(@Nullable org.jclouds.compute.domain.SecurityGroup input) {\n               return input.getName();\n            }\n         });\n         for (String securityGroupName : templateOptions.getGroups()) {\n            checkState(Iterables.contains(securityGroupNames, securityGroupName), \"Cannot find security group with name \" + securityGroupName + \". \\nSecurity groups available are: \\n\" + Iterables.toString(securityGroupNames)); // {\n         }\n\n      } else if (!inboundPorts.isEmpty()) {\n         String securityGroupName = namingConvention.create().sharedNameForGroup(group);\n\n         // populate the security group cache with existing security groups\n         for (SecurityGroup existingSecurityGroup : securityGroupExtension.listSecurityGroupsInLocation(template.getLocation())) {\n            securityGroupCache.put(new RegionSecurityGroupNameAndPorts(region, existingSecurityGroup.getName(), inboundPorts), existingSecurityGroup);\n         }\n\n         SecurityGroup securityGroup = securityGroupCache.getUnchecked(new RegionSecurityGroupNameAndPorts(region, securityGroupName, inboundPorts));\n         templateOptions.securityGroups(securityGroup.getName());\n         tagsBuilder.add(String.format(\"%s-%s\", JCLOUDS_SG_PREFIX, securityGroup.getId()));\n      }\n\n      templateOptions.tags(tagsBuilder.build());\n\n      Map<?, ListenableFuture<Void>> responses = super.execute(group, count, template, goodNodes, badNodes,\n              customizationResponses);\n\n      // Key pairs in Openstack are only required to create the Server. They aren't used anymore so it is better\n      // to delete the auto-generated key pairs at this point where we know exactly which ones have been\n      // auto-generated by jclouds.\n      if (templateOptions.shouldGenerateKeyPair() && keyPair != null) {\n         registerAutoGeneratedKeyPairCleanupCallbacks(responses, region, keyPair.getName());\n      }\n      return responses;\n   }\n\n   private KeyPair generateKeyPair(String region, String prefix) {\n      logger.debug(\">> creating default keypair for node...\");\n      KeyPair keyPair = novaApi.getKeyPairApi(region).get().create(namingConvention.createWithoutPrefix().uniqueNameForGroup(prefix));\n      logger.debug(\">> keypair created! %s\", keyPair.getName());\n      return keyPair;\n   }\n\n   @Override\n   protected ListenableFuture<AtomicReference<NodeMetadata>> createNodeInGroupWithNameAndTemplate(String group,\n            final String name, Template template) {\n\n      ListenableFuture<AtomicReference<NodeMetadata>> future = super.createNodeInGroupWithNameAndTemplate(group, name, template);\n      final NovaTemplateOptions templateOptions = NovaTemplateOptions.class.cast(template.getOptions());\n      if (templateOptions.shouldAutoAssignFloatingIp()) {\n\n         ListenableFuture<AtomicReference<NodeAndNovaTemplateOptions>> nodeAndNovaTemplateOptions = Futures.transform(future,\n               new Function<AtomicReference<NodeMetadata>, AtomicReference<NodeAndNovaTemplateOptions>>() {\n\n                  @Override\n                  public AtomicReference<NodeAndNovaTemplateOptions> apply(AtomicReference<NodeMetadata> input) {\n                     return NodeAndNovaTemplateOptions.newAtomicReference(input, Atomics.newReference(templateOptions));\n                  }\n               }, MoreExecutors.directExecutor());\n         return Futures.transform(nodeAndNovaTemplateOptions, createAndAddFloatingIpToNode, userExecutor);\n      } else {\n         return future;\n      }\n   }\n\n   private void registerAutoGeneratedKeyPairCleanupCallbacks(final Map<?, ListenableFuture<Void>> responses,\n                                                             final String region, final String generatedKeyPairName) {\n      // The Futures.allAsList fails immediately if some of the futures fail. The Futures.successfulAsList, however,\n      // returns a list containing the results or 'null' for those futures that failed. We want to wait for all them\n      // (even if they fail), so better use the latter form.\n      ListenableFuture<List<Void>> aggregatedResponses = Futures.successfulAsList(responses.values());\n\n      // Key pairs must be cleaned up after all futures completed (even if some failed).\n      Futures.addCallback(aggregatedResponses, new FutureCallback<List<Void>>() {\n         @Override\n         public void onSuccess(List<Void> result) {\n            cleanupAutoGeneratedKeyPair(generatedKeyPairName);\n         }\n\n         @Override\n         public void onFailure(Throwable t) {\n            cleanupAutoGeneratedKeyPair(generatedKeyPairName);\n         }\n\n         private void cleanupAutoGeneratedKeyPair(String keyPairName) {\n            logger.debug(\">> cleaning up auto-generated key pairs...\");\n               try {\n                  novaApi.getKeyPairApi(region).get().delete(keyPairName);\n               } catch (Exception ex) {\n                  logger.warn(\">> could not delete key pair %s: %s\", keyPairName, ex.getMessage());\n               }\n         }\n\n      }, userExecutor);\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/config/NovaHttpApiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.config;\n\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.inject.Provides;\nimport com.google.inject.multibindings.MapBinder;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.annotation.ClientError;\nimport org.jclouds.http.annotation.Redirection;\nimport org.jclouds.http.annotation.ServerError;\nimport org.jclouds.openstack.nova.v2_0.NovaApi;\nimport org.jclouds.openstack.nova.v2_0.extensions.ExtensionNamespaces;\nimport org.jclouds.openstack.nova.v2_0.handlers.NovaErrorHandler;\nimport org.jclouds.openstack.v2_0.domain.Extension;\nimport org.jclouds.openstack.v2_0.functions.PresentWhenExtensionAnnotationMatchesExtensionSet;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.config.HttpApiModule;\nimport org.jclouds.rest.functions.ImplicitOptionalConverter;\n\nimport jakarta.inject.Provider;\nimport jakarta.inject.Singleton;\nimport java.net.URI;\nimport java.util.Set;\nimport java.util.concurrent.TimeUnit;\n\nimport static org.jclouds.openstack.keystone.v2_0.config.KeystoneHttpApiModule.namespaceAliasBinder;\n\n/**\n * Configures the Nova connection.\n *\n */\n@ConfiguresHttpApi\npublic class NovaHttpApiModule extends HttpApiModule<NovaApi> {\n\n   public NovaHttpApiModule() {\n   }\n\n   @Override\n   protected void configure() {\n      bind(ImplicitOptionalConverter.class).to(PresentWhenExtensionAnnotationMatchesExtensionSet.class);\n      super.configure();\n      bindDefaultAliases();\n   }\n\n   // Intentionally private so subclasses use the Guice multibindings to contribute their aliases\n   private void bindDefaultAliases() {\n      MapBinder<URI, URI> aliases = namespaceAliasBinder(binder());\n      aliases.addBinding(URI.create(ExtensionNamespaces.SECURITY_GROUPS)).toInstance(\n            URI.create(\"http://docs.openstack.org/compute/ext/securitygroups/api/v1.1\"));\n      aliases.addBinding(URI.create(ExtensionNamespaces.FLOATING_IPS)).toInstance(\n            URI.create(\"http://docs.openstack.org/compute/ext/floating_ips/api/v1.1\"));\n      aliases.addBinding(URI.create(ExtensionNamespaces.KEYPAIRS)).toInstance(\n            URI.create(\"http://docs.openstack.org/compute/ext/keypairs/api/v1.1\"));\n      aliases.addBinding(URI.create(ExtensionNamespaces.SIMPLE_TENANT_USAGE)).toInstance(\n            URI.create(\"http://docs.openstack.org/compute/ext/os-simple-tenant-usage/api/v1.1\"));\n      aliases.addBinding(URI.create(ExtensionNamespaces.HOSTS)).toInstance(\n            URI.create(\"http://docs.openstack.org/compute/ext/hosts/api/v1.1\"));\n      aliases.addBinding(URI.create(ExtensionNamespaces.VOLUMES)).toInstance(\n            URI.create(\"http://docs.openstack.org/compute/ext/volumes/api/v1.1\"));\n      aliases.addBinding(URI.create(ExtensionNamespaces.VIRTUAL_INTERFACES)).toInstance(\n            URI.create(\"http://docs.openstack.org/compute/ext/virtual_interfaces/api/v1.1\"));\n      aliases.addBinding(URI.create(ExtensionNamespaces.CREATESERVEREXT)).toInstance(\n            URI.create(\"http://docs.openstack.org/compute/ext/createserverext/api/v1.1\"));\n      aliases.addBinding(URI.create(ExtensionNamespaces.ADMIN_ACTIONS)).toInstance(\n            URI.create(\"http://docs.openstack.org/compute/ext/admin-actions/api/v1.1\"));\n      aliases.addBinding(URI.create(ExtensionNamespaces.AGGREGATES)).toInstance(\n            URI.create(\"http://docs.openstack.org/compute/ext/aggregates/api/v1.1\"));\n      aliases.addBinding(URI.create(ExtensionNamespaces.FLAVOR_EXTRA_SPECS)).toInstance(\n            URI.create(\"http://docs.openstack.org/compute/ext/flavor_extra_specs/api/v1.1\"));\n      aliases.addBinding(URI.create(ExtensionNamespaces.QUOTAS)).toInstance(\n            URI.create(\"http://docs.openstack.org/compute/ext/quotas-sets/api/v1.1\"));\n      aliases.addBinding(URI.create(ExtensionNamespaces.VOLUME_TYPES)).toInstance(\n            URI.create(\"http://docs.openstack.org/compute/ext/volume_types/api/v1.1\"));\n      aliases.addBinding(URI.create(ExtensionNamespaces.AVAILABILITY_ZONE)).toInstance(\n            URI.create(\"http://docs.openstack.org/compute/ext/availabilityzone/api/v1.1\"));\n      aliases.addBinding(URI.create(ExtensionNamespaces.VOLUME_ATTACHMENTS)).toInstance(\n            URI.create(\"http://docs.openstack.org/compute/ext/os-volume-attachment-update/api/v2\"));\n      aliases.addBinding(URI.create(ExtensionNamespaces.ATTACH_INTERFACES)).toInstance(\n            URI.create(\"http://docs.openstack.org/compute/ext/interfaces/api/v1.1\"));\n      aliases.addBinding(URI.create(ExtensionNamespaces.HYPERVISORS)).toInstance(\n            URI.create(\"http://docs.openstack.org/compute/ext/hypervisors/api/v1.1\"));\n   }\n\n   @Provides\n   @Singleton\n   public final LoadingCache<String, Set<? extends Extension>> provideExtensionsByRegion(final Provider<NovaApi> novaApi) {\n      return CacheBuilder.newBuilder().expireAfterWrite(23, TimeUnit.HOURS)\n            .build(new CacheLoader<String, Set<? extends Extension>>() {\n               @Override\n               public Set<? extends Extension> load(final String key) throws Exception {\n                  return novaApi.get().getExtensionApi(key).list();\n               }\n            });\n   }\n\n   @Override\n   protected void bindErrorHandlers() {\n      bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(NovaErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(NovaErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(NovaErrorHandler.class);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/config/NovaParserModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.config;\n\nimport java.beans.ConstructorProperties;\nimport java.lang.reflect.Type;\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.TreeMap;\n\nimport jakarta.inject.Singleton;\n\nimport com.google.common.collect.Maps;\nimport com.google.gson.JsonObject;\nimport com.google.gson.reflect.TypeToken;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.json.config.GsonModule.DateAdapter;\nimport org.jclouds.openstack.nova.v2_0.domain.Address;\nimport org.jclouds.openstack.nova.v2_0.domain.BlockDeviceMapping;\nimport org.jclouds.openstack.nova.v2_0.domain.HostResourceUsage;\nimport org.jclouds.openstack.nova.v2_0.domain.Image;\nimport org.jclouds.openstack.nova.v2_0.domain.Server;\nimport org.jclouds.openstack.nova.v2_0.domain.ServerExtendedAttributes;\nimport org.jclouds.openstack.nova.v2_0.domain.ServerExtendedStatus;\nimport org.jclouds.openstack.nova.v2_0.domain.ServerWithSecurityGroups;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.Resource;\n\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Multimap;\nimport com.google.common.collect.Sets;\nimport com.google.gson.JsonArray;\nimport com.google.gson.JsonDeserializationContext;\nimport com.google.gson.JsonDeserializer;\nimport com.google.gson.JsonElement;\nimport com.google.gson.JsonParseException;\nimport com.google.gson.JsonSerializationContext;\nimport com.google.gson.JsonSerializer;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Provides;\n\npublic class NovaParserModule extends AbstractModule {\n\n   @Provides\n   @Singleton\n   public final Map<Type, Object> provideCustomAdapterBindings() {\n      return ImmutableMap.<Type, Object>of(\n              HostResourceUsage.class, new HostResourceUsageAdapter(),\n              ServerWithSecurityGroups.class, new ServerWithSecurityGroupsAdapter(),\n              Server.class, new ServerAdapter(),\n              Image.class, new ImageAdapter()\n      );\n   }\n\n   @Override\n   protected void configure() {\n      bind(DateAdapter.class).to(GsonModule.Iso8601DateAdapter.class);\n   }\n\n   @Singleton\n   public static class HostResourceUsageAdapter implements JsonSerializer<HostResourceUsage>, JsonDeserializer<HostResourceUsage> {\n      public HostResourceUsage apply(HostResourceUsageView in) {\n         return in.resource.toBuilder().build();\n      }\n\n      @Override\n      public HostResourceUsage deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context) throws JsonParseException {\n         return apply((HostResourceUsageView) context.deserialize(jsonElement, HostResourceUsageView.class));\n      }\n\n      @Override\n      public JsonElement serialize(HostResourceUsage hostResourceUsage, Type type, JsonSerializationContext context) {\n         return context.serialize(hostResourceUsage);\n      }\n\n      private static class HostResourceUsageView {\n         protected HostResourceUsageInternal resource;\n      }\n\n      private static class HostResourceUsageInternal extends HostResourceUsage {\n\n         @ConstructorProperties({\n                 \"host\", \"project\", \"memory_mb\", \"cpu\", \"disk_gb\"\n         })\n         protected HostResourceUsageInternal(String host, @Nullable String project, int memoryMb, int cpu, int diskGb) {\n            super(host, project, memoryMb, cpu, diskGb);\n         }\n      }\n   }\n\n   @Singleton\n   public static class ServerWithSecurityGroupsAdapter implements JsonDeserializer<ServerWithSecurityGroups> {\n      @Override\n      public ServerWithSecurityGroups deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context)\n              throws JsonParseException {\n         Server server = context.deserialize(jsonElement, Server.class);\n         ServerWithSecurityGroups.Builder<?> result = ServerWithSecurityGroups.builder().fromServer(server);\n         Set<String> names = Sets.newLinkedHashSet();\n         if (jsonElement.getAsJsonObject().get(\"security_groups\") != null) {\n            JsonArray x = jsonElement.getAsJsonObject().get(\"security_groups\").getAsJsonArray();\n            for (JsonElement y : x) {\n               names.add(y.getAsJsonObject().get(\"name\").getAsString());\n            }\n            result.securityGroupNames(names);\n         }\n         return result.build();\n      }\n   }\n\n   @Singleton\n   public static class ServerAdapter implements JsonDeserializer<Server> {\n      @Override\n      public Server deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context)\n              throws JsonParseException {\n         Server serverBase;\n\n         // Servers can be created without an image so test if an image object is returned\n         if (jsonElement.getAsJsonObject().get(\"image\").isJsonObject()) {\n            serverBase = apply((ServerInternal) context.deserialize(jsonElement, ServerInternal.class));\n         } else {\n            serverBase = apply((ServerInternalWithoutImage) context.deserialize(jsonElement, ServerInternalWithoutImage.class));\n         }\n\n         Server.Builder<?> result = Server.builder().fromServer(serverBase);\n         ServerExtendedStatus extendedStatus = context.deserialize(jsonElement, ServerExtendedStatus.class);\n         if (!Objects.equal(extendedStatus, ServerExtendedStatus.builder().build())) {\n            result.extendedStatus(extendedStatus);\n         }\n         ServerExtendedAttributes extraAttributes = context.deserialize(jsonElement, ServerExtendedAttributes.class);\n         if (!Objects.equal(extraAttributes, ServerExtendedAttributes.builder().build())) {\n            result.extendedAttributes(extraAttributes);\n         }\n         return result.build();\n      }\n\n      public Server apply(Server in) {\n         return in.toBuilder().build();\n      }\n\n      private static class ServerInternal extends Server {\n         @ConstructorProperties({\"id\", \"name\", \"links\", \"uuid\", \"tenant_id\", \"user_id\", \"updated\", \"created\", \"hostId\", \"accessIPv4\", \"accessIPv6\", \"status\", \"image\", \"flavor\", \"key_name\", \"config_drive\", \"addresses\", \"metadata\", \"extendedStatus\", \"extendedAttributes\", \"OS-DCF:diskConfig\", \"OS-EXT-AZ:availability_zone\"})\n         protected ServerInternal(String id, @Nullable String name, java.util.Set<Link> links, @Nullable String uuid, String tenantId,\n                                  String userId, Date updated, Date created, @Nullable String hostId, @Nullable String accessIPv4,\n                                  @Nullable String accessIPv6, Server.Status status, Resource image, Resource flavor, @Nullable String keyName,\n                                  @Nullable String configDrive, Multimap<String, Address> addresses, Map<String, String> metadata,\n                                  @Nullable ServerExtendedStatus extendedStatus, @Nullable ServerExtendedAttributes extendedAttributes, @Nullable String diskConfig, @Nullable String availabilityZone) {\n            super(id, name, links, uuid, tenantId, userId, updated, created, hostId, accessIPv4, accessIPv6, status, image, flavor, keyName, configDrive, addresses, metadata, extendedStatus, extendedAttributes, diskConfig, availabilityZone);\n         }\n      }\n\n      private static class ServerInternalWithoutImage extends Server {\n         @ConstructorProperties({\"id\", \"name\", \"links\", \"uuid\", \"tenant_id\", \"user_id\", \"updated\", \"created\", \"hostId\", \"accessIPv4\", \"accessIPv6\", \"status\", \"flavor\", \"key_name\", \"config_drive\", \"addresses\", \"metadata\", \"extendedStatus\", \"extendedAttributes\", \"OS-DCF:diskConfig\", \"OS-EXT-AZ:availability_zone\"})\n         protected ServerInternalWithoutImage(String id, @Nullable String name, java.util.Set<Link> links, @Nullable String uuid, String tenantId,\n                                  String userId, Date updated, Date created, @Nullable String hostId, @Nullable String accessIPv4,\n                                  @Nullable String accessIPv6, Server.Status status, Resource flavor, @Nullable String keyName,\n                                  @Nullable String configDrive, Multimap<String, Address> addresses, Map<String, String> metadata,\n                                  @Nullable ServerExtendedStatus extendedStatus, @Nullable ServerExtendedAttributes extendedAttributes, @Nullable String diskConfig, @Nullable String availabilityZone) {\n            super(id, name, links, uuid, tenantId, userId, updated, created, hostId, accessIPv4, accessIPv6, status, null, flavor, keyName, configDrive, addresses, metadata, extendedStatus, extendedAttributes, diskConfig, availabilityZone);\n         }\n      }\n   }\n\n   @Singleton\n   public static class ImageAdapter implements JsonDeserializer<Image> {\n      public static final String METADATA = \"metadata\";\n      public static final String BLOCK_DEVICE_MAPPING = \"block_device_mapping\";\n\n      @Override\n      public Image deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context)\n              throws JsonParseException {\n         JsonObject json = jsonElement.getAsJsonObject();\n         Map<String, String> metadata = null;\n         List<BlockDeviceMapping> blockDeviceMapping = null;\n\n         JsonElement meta = json.get(METADATA);\n         if (meta != null && meta.isJsonObject()) {\n            metadata = Maps.newTreeMap();\n            for (Map.Entry<String, JsonElement> e : meta.getAsJsonObject().entrySet()) {\n               Object value;\n               if (e.getValue().isJsonArray()) {\n                  value = context.deserialize(e.getValue().getAsJsonArray(), ArrayList.class);\n               } else if (e.getValue().isJsonObject()) {\n                  value = context.deserialize(e.getValue().getAsJsonObject(), TreeMap.class);\n               } else if (e.getValue().isJsonPrimitive()) {\n                  value = e.getValue().getAsJsonPrimitive().getAsString();\n               } else {\n                  continue;\n               }\n\n               //keep non-string members out of normal metadata\n               if (value instanceof String) {\n                  metadata.put(e.getKey(), (String) value);\n               } else if (value instanceof List && BLOCK_DEVICE_MAPPING.equals(e.getKey())) {\n                  blockDeviceMapping = context.deserialize(e.getValue(), new TypeToken<List<BlockDeviceMapping>>(){}.getType());\n               }\n            }\n            json.remove(METADATA);\n         }\n\n         return apply(context.<ImageInternal>deserialize(json, ImageInternal.class), metadata, blockDeviceMapping);\n      }\n\n      public Image apply(ImageInternal in, Map<String, String> metadata, List<BlockDeviceMapping> blockDeviceMapping) {\n         return in.toBuilder().metadata(metadata).blockDeviceMapping(blockDeviceMapping).build();\n      }\n\n      private static class ImageInternal extends Image {\n         @ConstructorProperties({\n                 \"id\", \"name\", \"links\", \"updated\", \"created\", \"tenant_id\", \"user_id\", \"status\", \"progress\", \"minDisk\", \"minRam\", \"blockDeviceMapping\", \"server\", \"metadata\"\n         })\n         protected ImageInternal(String id, @Nullable String name, java.util.Set<Link> links, @Nullable Date updated, @Nullable Date created,\n                                 String tenantId, @Nullable String userId, @Nullable Status status, int progress, int minDisk, int minRam,\n                                 @Nullable List<BlockDeviceMapping> blockDeviceMapping, @Nullable Resource server, @Nullable Map<String, String> metadata) {\n            super(id, name, links, updated, created, tenantId, userId, status, progress, minDisk, minRam, blockDeviceMapping, server, metadata);\n\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/config/NovaProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.config;\n\n/**\n * Configuration properties and constants used in openstack Nova connections.\n */\npublic class NovaProperties {\n\n   /**\n    * Eventual consistency delay for retrieving a security group after it is created (in ms)\n    */\n   public static final String TIMEOUT_SECURITYGROUP_PRESENT = \"jclouds.openstack-nova.timeout.securitygroup-present\";\n\n   /**\n    * Whenever a node is created, automatically create and assign a floating ip address, also\n    * delete when the node is destroyed.\n    */\n   public static final String AUTO_ALLOCATE_FLOATING_IPS = \"jclouds.openstack-nova.auto-create-floating-ips\";\n\n   /**\n    * Whenever a node is created, automatically generate keypairs for groups, as needed, also\n    * delete the keypair(s) when the last node in the group is destroyed.\n    */\n   public static final String AUTO_GENERATE_KEYPAIRS = \"jclouds.openstack-nova.auto-generate-keypairs\";\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/Address.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.base.Optional;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport jakarta.inject.Named;\n\n/**\n * IP address\n * \n*/\npublic class Address {\n\n   public static Builder<?> builder() { \n      return new ConcreteBuilder();\n   }\n   \n   public Builder<?> toBuilder() { \n      return new ConcreteBuilder().fromAddress(this);\n   }\n\n   public static Address createV4(String addr) {\n      return builder().version(4).addr(addr).build();\n   }\n\n   public static Address createV6(String addr) {\n      return builder().version(6).addr(addr).build();\n   }\n\n   public abstract static class Builder<T extends Builder<T>>  {\n      protected abstract T self();\n\n      protected String addr;\n      protected int version;\n      protected String macAddr;\n      protected String type;\n\n\n      /** \n       * @see Address#getAddr()\n       */\n      public T addr(String addr) {\n         this.addr = addr;\n         return self();\n      }\n\n      /** \n       * @see Address#getVersion()\n       */\n      public T version(int version) {\n         this.version = version;\n         return self();\n      }\n\n      public T macAddr(String macAddr) {\n         this.macAddr = macAddr;\n         return self();\n      }\n\n      public T type(String type) {\n         this.type = type;\n         return self();\n      }\n\n      public Address build() {\n         return new Address(addr, version, macAddr, type);\n      }\n      \n      public T fromAddress(Address in) {\n         return this\n                  .addr(in.getAddr())\n                  .version(in.getVersion())\n                  .macAddr(in.getMacAddr().orNull())\n                  .type(in.getType().orNull());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String addr;\n   private final int version;\n   @Named(\"OS-EXT-IPS-MAC:mac_addr\")\n   private final Optional<String> macAddr;\n   @Named(\"OS-EXT-IPS:type\")\n   private final Optional<String> type;\n\n   @ConstructorProperties({\n      \"addr\", \"version\", \"OS-EXT-IPS-MAC:mac_addr\", \"OS-EXT-IPS:type\"\n   })\n   protected Address(String addr, int version, @Nullable String macAddr, @Nullable String type) {\n      this.addr = checkNotNull(addr, \"addr\");\n      this.version = version;\n      this.macAddr = Optional.fromNullable(macAddr);\n      this.type = Optional.fromNullable(type);\n   }\n\n   /**\n    * @return the ip address\n    */\n   public String getAddr() {\n      return this.addr;\n   }\n\n   /**\n    * @return the IP version, ex. 4\n    */\n   public int getVersion() {\n      return this.version;\n   }\n\n   public Optional<String> getMacAddr() {\n      return this.macAddr;\n   }\n\n   public Optional<String> getType() {\n      return this.type;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(addr, version, macAddr, type);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Address that = Address.class.cast(obj);\n      return Objects.equal(this.addr, that.addr)\n               && Objects.equal(this.version, that.version)\n               && Objects.equal(this.macAddr, that.macAddr)\n               && Objects.equal(this.type, that.type);\n   }\n   \n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"addr\", addr).add(\"version\", version).add(\"macAddr\", macAddr.or(\"\")).add(\"type\", type.or(\"\"));\n   }\n   \n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/BackupType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.CaseFormat;\n\npublic enum BackupType {\n   DAILY, WEEKLY;\n\n   public String value() {\n      return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_HYPHEN, name());\n   }\n\n   @Override\n   public String toString() {\n      return value();\n   }\n\n   public static BackupType fromValue(String backupType) {\n      return valueOf(CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_UNDERSCORE, checkNotNull(backupType, \"backupType\")));\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/BlockDeviceMapping.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * A representation of a block device that can be used to boot a Nova instance.\n */\npublic class BlockDeviceMapping {\n\n   private String uuid;\n   @Named(\"device_name\")\n   private String deviceName;\n   @Named(\"device_type\")\n   private String deviceType;\n   @Named(\"volume_size\")\n   private Integer volumeSize;\n   @Named(\"source_type\")\n   private String sourceType;\n   @Named(\"destination_type\")\n   private String destinationType;\n   @Named(\"disk_bus\")\n   private String diskBus;\n   @Named(\"no_device\")\n   private Boolean noDevice;\n   @Named(\"guest_format\")\n   private String guestFormat;\n   @Named(\"boot_index\")\n   private Integer bootIndex;\n   @Named(\"delete_on_termination\")\n   private Boolean deleteOnTermination;\n\n   @ConstructorProperties({\"uuid\", \"device_name\", \"device_type\", \"volume_size\", \"source_type\", \"destination_type\",\n      \"disk_bus\", \"no_device\", \"guest_format\", \"boot_index\", \"delete_on_termination\"})\n   protected BlockDeviceMapping(String uuid, String deviceName, String deviceType, Integer volumeSize,\n         String sourceType, String destinationType, String diskBus, Boolean noDevice, String guestFormat,\n         Integer bootIndex, Boolean deleteOnTermination) {\n      this.uuid = uuid;\n      this.deviceName = deviceName;\n      this.deviceType = deviceType;\n      this.volumeSize = volumeSize;\n      this.sourceType = sourceType;\n      this.destinationType = destinationType;\n      this.diskBus = diskBus;\n      this.noDevice = noDevice;\n      this.guestFormat = guestFormat;\n      this.bootIndex = bootIndex;\n      this.deleteOnTermination = deleteOnTermination;\n   }\n\n   /**\n    * @return the uuid of the volume\n    */\n   @Nullable\n   public String getUuid() {\n      return uuid;\n   }\n\n   /**\n    * @return the device name\n    */\n   @Nullable\n   public String getDeviceName() {\n      return deviceName;\n   }\n\n   /**\n    * @return the device type\n    */\n   @Nullable\n   public String getDeviceType() {\n      return deviceType;\n   }\n\n   /**\n    * @return the size of the volume\n    */\n   @Nullable\n   public Integer getVolumeSize() {\n      return volumeSize;\n   }\n\n   /**\n    * @return the source type of the block device\n    */\n   @Nullable\n   public String getSourceType() {\n      return sourceType;\n   }\n\n   /**\n    * @return the destination type of the block device\n    */\n   @Nullable\n   public String getDestinationType() {\n      return destinationType;\n   }\n\n   /**\n    * @return the disk bus of the block device\n    */\n   @Nullable\n   public String getDiskBus() {\n      return diskBus;\n   }\n\n   /**\n    * @return true if there is no block device\n    */\n   @Nullable\n   public Boolean getNoDevice() {\n      return noDevice;\n   }\n\n   /**\n    * @return the guest format of the block device\n    */\n   @Nullable\n   public String getGuestFormat() {\n      return guestFormat;\n   }\n\n   /**\n    * @return the boot index of the block device\n    */\n   @Nullable\n   public Integer getBootIndex() {\n      return bootIndex;\n   }\n\n   /**\n    * @return true if the block device should terminate on deletion\n    */\n   @Nullable\n   public Boolean getDeleteOnTermination() {\n      return deleteOnTermination;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(uuid, deviceName, deviceType, volumeSize, sourceType, destinationType, diskBus,\n            noDevice, guestFormat, bootIndex, deleteOnTermination);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      BlockDeviceMapping that = BlockDeviceMapping.class.cast(obj);\n      return Objects.equal(this.uuid, that.uuid)\n            && Objects.equal(this.deviceName, that.deviceName)\n            && Objects.equal(this.deviceType, that.deviceType)\n            && Objects.equal(this.volumeSize, that.volumeSize)\n            && Objects.equal(this.sourceType, that.sourceType)\n            && Objects.equal(this.destinationType, that.destinationType)\n            && Objects.equal(this.diskBus, that.diskBus)\n            && Objects.equal(this.noDevice, that.noDevice)\n            && Objects.equal(this.guestFormat, that.guestFormat)\n            && Objects.equal(this.bootIndex, that.bootIndex)\n            && Objects.equal(this.deleteOnTermination, that.deleteOnTermination);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"uuid\", uuid)\n            .add(\"deviceName\", deviceName)\n            .add(\"deviceType\", deviceType)\n            .add(\"volumeSize\", volumeSize)\n            .add(\"sourceType\", sourceType)\n            .add(\"destinationType\", destinationType)\n            .add(\"diskBus\", diskBus)\n            .add(\"noDevice\", noDevice)\n            .add(\"guestFormat\", guestFormat)\n            .add(\"bootIndex\", bootIndex)\n            .add(\"deleteOnTermination\", deleteOnTermination);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().fromBlockDeviceMapping(this);\n   }\n\n   public static class Builder {\n      protected String uuid;\n      protected String deviceName;\n      protected String deviceType;\n      protected Integer volumeSize;\n      protected String sourceType;\n      protected String destinationType;\n      protected String diskBus;\n      protected Boolean noDevice;\n      protected String guestFormat;\n      protected Integer bootIndex;\n      protected Boolean deleteOnTermination;\n\n      public Builder uuid(String uuid) {\n         this.uuid = uuid;\n         return this;\n      }\n\n      public Builder deviceName(String deviceName) {\n         this.deviceName = deviceName;\n         return this;\n      }\n\n      public Builder deviceType(String deviceType) {\n         this.deviceType = deviceType;\n         return this;\n      }\n\n      public Builder volumeSize(Integer volumeSize) {\n         this.volumeSize = volumeSize;\n         return this;\n      }\n\n      public Builder sourceType(String sourceType) {\n         this.sourceType = sourceType;\n         return this;\n      }\n\n      public Builder destinationType(String destinationType) {\n         this.destinationType = destinationType;\n         return this;\n      }\n\n      public Builder diskBus(String diskBus) {\n         this.diskBus = diskBus;\n         return this;\n      }\n\n      public Builder noDevice(Boolean noDevice) {\n         this.noDevice = noDevice;\n         return this;\n      }\n\n      public Builder guestFormat(String guestFormat) {\n         this.guestFormat = guestFormat;\n         return this;\n      }\n\n      public Builder bootIndex(Integer bootIndex) {\n         this.bootIndex = bootIndex;\n         return this;\n      }\n\n      public Builder deleteOnTermination(Boolean deleteOnTermination) {\n         this.deleteOnTermination = deleteOnTermination;\n         return this;\n      }\n\n      public BlockDeviceMapping build() {\n         return new BlockDeviceMapping(uuid, deviceName, deviceType, volumeSize, sourceType, destinationType, diskBus,\n               noDevice, guestFormat, bootIndex, deleteOnTermination);\n      }\n\n      public Builder fromBlockDeviceMapping(BlockDeviceMapping in) {\n         return this\n               .uuid(in.getUuid())\n               .deviceName(in.getDeviceName())\n               .deviceType(in.getDeviceType())\n               .volumeSize(in.getVolumeSize())\n               .sourceType(in.getSourceType())\n               .destinationType(in.getDestinationType())\n               .diskBus(in.getDiskBus())\n               .noDevice(in.getNoDevice())\n               .bootIndex(in.getBootIndex())\n               .deleteOnTermination(in.getDeleteOnTermination())\n               .guestFormat(in.getGuestFormat());\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/Console.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain;\n\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.net.URI;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Represents an Openstack Console.\n */\npublic class Console {\n   public enum Type {\n      NOVNC(\"novnc\"),\n      XVPVNC(\"xvpvnc\"),\n      SPICE_HTML5(\"spice-html5\"),\n      RDP_HTML5(\"rdp-html5\"),\n      UNRECOGNIZED(\"unrecognized\");\n\n      private final String type;\n\n      Type(String type) {\n         this.type = type;\n      }\n\n      public String type() {\n         return type;\n      }\n\n      /**\n       * Used from jclouds builtin deserializer.\n       */\n      public static Type fromValue(String type) {\n          if (type != null) {\n             for (Type value : Type.values()) {\n                if (type.equals(value.type)) {\n                   return value;\n                }\n             }\n             return UNRECOGNIZED;\n          }\n          return null;\n      }\n\n      @Override\n      public String toString() {\n          return type();\n      }\n   }\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromConsole(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected URI url;\n      protected Type type;\n\n      /**\n       * @see Console#getUrl()\n       */\n      public T url(URI url) {\n         this.url = checkNotNull(url, \"url\");\n         return self();\n      }\n\n      /**\n       * @see Console#getType()\n       */\n      public T type(Type type) {\n         this.type = type;\n         return self();\n      }\n\n      public Console build() {\n         return new Console(url, type);\n      }\n\n      public T fromConsole(Console in) {\n         return this.url(in.getUrl()).type(in.getType());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final URI url;\n   private final Type type;\n\n   @ConstructorProperties({ \"url\", \"type\" })\n   protected Console(URI url, Type type) {\n      this.url = checkNotNull(url, \"url\");\n      this.type = checkNotNull(type, \"type\");\n   }\n\n   /**\n    * @return the url to use to connect to the server.\n    */\n   public URI getUrl() {\n      return this.url;\n   }\n\n   /**\n    * @return the type of the url\n    */\n   public Type getType() {\n      return this.type;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(url, type);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Console that = Console.class.cast(obj);\n      return Objects.equal(this.url, that.url)\n         && Objects.equal(this.type, that.type);\n   }\n\n   protected ToStringHelper string() {\n      return toStringHelper(this).add(\"url\", url).add(\"type\", type);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/FixedIP.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport jakarta.inject.Named;\nimport java.beans.ConstructorProperties;\n\n/**\n * Describes an fixed IP address\n */\npublic class FixedIP {\n\n   @Named(\"ip_address\")\n   protected final String ipAddress;\n   @Named(\"subnet_id\")\n   protected final String subnetId;\n\n   @ConstructorProperties({ \"ip_address\", \"subnet_id\" })\n   protected FixedIP(String ipAddress, String subnetId) {\n      this.ipAddress = ipAddress;\n      this.subnetId = subnetId;\n   }\n\n   /**\n    * @return the ipAddress of the IP\n    */\n   @Nullable\n   public String getIpAddress() {\n      return ipAddress;\n   }\n\n   /**\n    * @return the subnetId of the IP\n    */\n   @Nullable\n   public String getSubnetId() {\n      return subnetId;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(ipAddress, subnetId);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      FixedIP that = FixedIP.class.cast(obj);\n      return Objects.equal(this.ipAddress, that.ipAddress) && Objects.equal(this.subnetId, that.subnetId);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).add(\"ipAddress\", ipAddress).add(\"subnetId\", subnetId);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   /**\n    * @return the Builder for IP\n    */\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   /**\n    * Gets a Builder configured as this object.\n    */\n   public Builder toBuilder() {\n      return new Builder().fromIP(this);\n   }\n\n   public static class Builder {\n      protected String ipAddress;\n      protected String subnetId;\n\n      /**\n       * Provide the ipAddress to the IP's Builder.\n       *\n       * @return the Builder.\n       * @see FixedIP#getIpAddress()\n       */\n      public Builder ipAddress(String ipAddress) {\n         this.ipAddress = ipAddress;\n         return this;\n      }\n\n      /**\n       * Provide the subnetId to the IP's Builder.\n       *\n       * @return the Builder.\n       * @see FixedIP#getSubnetId()\n       */\n      public Builder subnetId(String subnetId) {\n         this.subnetId = subnetId;\n         return this;\n      }\n\n      /**\n       * @return a IP constructed with this Builder.\n       */\n      public FixedIP build() {\n         return new FixedIP(ipAddress, subnetId);\n      }\n\n      /**\n       * @return a Builder from another IP.\n       */\n      public Builder fromIP(FixedIP in) {\n         return this.ipAddress(in.getIpAddress()).subnetId(in.getSubnetId());\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/Flavor.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.Resource;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.base.Optional;\n\n/**\n * A flavor is an available hardware configuration for a server. Each flavor has\n * a unique combination of disk space and memory capacity.\n * \n * @see <a href=\n      \"http://docs.openstack.org/api/openstack-compute/2/content/List_Flavors-d1e4188.html\"\n      />\n*/\npublic class Flavor extends Resource {\n\n   public static Builder<?> builder() { \n      return new ConcreteBuilder();\n   }\n   \n   public Builder<?> toBuilder() { \n      return new ConcreteBuilder().fromFlavor(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> extends Resource.Builder<T>  {\n      protected int ram;\n      protected int disk;\n      protected int vcpus;\n      protected String swap;\n      protected Double rxtxFactor;\n      protected Integer ephemeral;\n   \n      /** \n       * @see Flavor#getRam()\n       */\n      public T ram(int ram) {\n         this.ram = ram;\n         return self();\n      }\n\n      /** \n       * @see Flavor#getDisk()\n       */\n      public T disk(int disk) {\n         this.disk = disk;\n         return self();\n      }\n\n      /** \n       * @see Flavor#getVcpus()\n       */\n      public T vcpus(int vcpus) {\n         this.vcpus = vcpus;\n         return self();\n      }\n\n      /** \n       * @see Flavor#getSwap()\n       */\n      public T swap(String swap) {\n         this.swap = swap;\n         return self();\n      }\n\n      /** \n       * @see Flavor#getRxtxFactor()\n       */\n      public T rxtxFactor(Double rxtxFactor) {\n         this.rxtxFactor = rxtxFactor;\n         return self();\n      }\n\n      /** \n       * @see Flavor#getEphemeral()\n       */\n      public T ephemeral(Integer ephemeral) {\n         this.ephemeral = ephemeral;\n         return self();\n      }\n\n      public Flavor build() {\n         return new Flavor(id, name, links, ram, disk, vcpus, swap, rxtxFactor, ephemeral);\n      }\n      \n      public T fromFlavor(Flavor in) {\n         return super.fromResource(in)\n                  .ram(in.getRam())\n                  .disk(in.getDisk())\n                  .vcpus(in.getVcpus())\n                  .swap(in.getSwap().orNull())\n                  .rxtxFactor(in.getRxtxFactor().orNull())\n                  .ephemeral(in.getEphemeral().orNull());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final int ram;\n   private final int disk;\n   private final int vcpus;\n   private final Optional<String> swap;\n   @Named(\"rxtx_factor\")\n   private final Optional<Double> rxtxFactor;\n   @Named(\"OS-FLV-EXT-DATA:ephemeral\")\n   private final Optional<Integer> ephemeral;\n\n   @ConstructorProperties({\n      \"id\", \"name\", \"links\", \"ram\", \"disk\", \"vcpus\", \"swap\", \"rxtx_factor\", \"OS-FLV-EXT-DATA:ephemeral\"\n   })\n   protected Flavor(String id, String name, java.util.Set<Link> links, int ram, int disk, int vcpus,\n                    @Nullable String swap, @Nullable Double rxtxFactor, @Nullable Integer ephemeral) {\n      super(id, checkNotNull(name, \"name\"), links);\n      checkArgument(ram > 0, \"Value of ram has to greater than 0\");\n      checkArgument(vcpus > 0,  \"Value of vcpus has to greater than 0\");\n      this.ram = ram;\n      this.disk = disk;\n      this.vcpus = vcpus;\n      this.swap = Optional.fromNullable(swap);\n      this.rxtxFactor = Optional.fromNullable(rxtxFactor);\n      this.ephemeral = Optional.fromNullable(ephemeral);\n   }\n   \n   public int getRam() {\n      return this.ram;\n   }\n\n   public int getDisk() {\n      return this.disk;\n   }\n\n   public int getVcpus() {\n      return this.vcpus;\n   }\n\n   public Optional<String> getSwap() {\n      return this.swap;\n   }\n\n   public Optional<Double> getRxtxFactor() {\n      return this.rxtxFactor;\n   }\n\n   /**\n    * Retrieves ephemeral disk space in GB\n    * <p/>\n    * NOTE: This field is only present if the Flavor Extra Data extension is installed (alias \"OS-FLV-EXT-DATA\").\n    * \n    * @see org.jclouds.openstack.nova.v2_0.features.ExtensionApi#getExtensionByAlias\n    * @see org.jclouds.openstack.nova.v2_0.extensions.ExtensionNamespaces#FLAVOR_EXTRA_DATA\n    */\n   public Optional<Integer> getEphemeral() {\n      return this.ephemeral;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(ram, disk, vcpus, swap, rxtxFactor, ephemeral);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Flavor that = Flavor.class.cast(obj);\n      return super.equals(that) && Objects.equal(this.ram, that.ram)\n               && Objects.equal(this.disk, that.disk)\n               && Objects.equal(this.vcpus, that.vcpus)\n               && Objects.equal(this.swap, that.swap)\n               && Objects.equal(this.rxtxFactor, that.rxtxFactor)\n               && Objects.equal(this.ephemeral, that.ephemeral);\n   }\n   \n   protected ToStringHelper string() {\n      return super.string()\n            .add(\"ram\", ram).add(\"disk\", disk).add(\"vcpus\", vcpus).add(\"swap\", swap).add(\"rxtxFactor\", rxtxFactor).add(\"ephemeral\", ephemeral);\n   }\n   \n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/FloatingIP.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * A Floating IP is an IP address that can be created and associated with a\n * Server instance. Floating IPs can also be disassociated and deleted from a\n * Server instance.\n */\npublic class FloatingIP implements Comparable<FloatingIP> {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() { \n      return new ConcreteBuilder().fromFloatingIP(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String id;\n      protected String ip;\n      protected String fixedIp;\n      protected String instanceId;\n      protected String pool;\n\n      /** \n       * @see FloatingIP#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /** \n       * @see FloatingIP#getIp()\n       */\n      public T ip(String ip) {\n         this.ip = ip;\n         return self();\n      }\n\n      /** \n       * @see FloatingIP#getFixedIp()\n       */\n      public T fixedIp(String fixedIp) {\n         this.fixedIp = fixedIp;\n         return self();\n      }\n\n      /** \n       * @see FloatingIP#getInstanceId()\n       */\n      public T instanceId(String instanceId) {\n         this.instanceId = instanceId;\n         return self();\n      }\n\n      /** \n       * @see FloatingIP#getPool()\n       */\n      public T pool(String pool) {\n         this.pool = pool;\n         return self();\n      }\n\n      public FloatingIP build() {\n         return new FloatingIP(id, ip, fixedIp, instanceId, pool);\n      }\n      \n      public T fromFloatingIP(FloatingIP in) {\n         return this\n                  .id(in.getId())\n                  .ip(in.getIp())\n                  .fixedIp(in.getFixedIp())\n                  .instanceId(in.getInstanceId())\n                  .pool(in.getPool());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final String ip;\n   @Named(\"fixed_ip\")\n   private final String fixedIp;\n   @Named(\"instance_id\")\n   private final String instanceId;\n   private final String pool;\n\n   @ConstructorProperties({\n      \"id\", \"ip\", \"fixed_ip\", \"instance_id\", \"pool\"\n   })\n   protected FloatingIP(String id, String ip, @Nullable String fixedIp, @Nullable String instanceId, @Nullable String pool) {\n      this.id = checkNotNull(id, \"id\");\n      this.ip = checkNotNull(ip, \"ip\");\n      this.fixedIp = fixedIp;\n      this.instanceId = instanceId;\n      this.pool = pool;\n   }\n\n   public String getId() {\n      return this.id;\n   }\n\n   public String getIp() {\n      return this.ip;\n   }\n\n   @Nullable\n   public String getFixedIp() {\n      return this.fixedIp;\n   }\n\n   @Nullable\n   public String getInstanceId() {\n      return this.instanceId;\n   }\n\n   @Nullable\n   public String getPool() {\n      return this.pool;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, ip, fixedIp, instanceId, pool);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      FloatingIP that = FloatingIP.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n               && Objects.equal(this.ip, that.ip)\n               && Objects.equal(this.fixedIp, that.fixedIp)\n               && Objects.equal(this.instanceId, that.instanceId)\n               && Objects.equal(this.pool, that.pool);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"ip\", ip).add(\"fixedIp\", fixedIp).add(\"instanceId\", instanceId).add(\"pool\", pool);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int compareTo(FloatingIP o) {\n      return this.id.compareTo(o.getId());\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/FloatingIPPool.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\n/**\n * A pool that holds a collection of floating IP's that can be allocated from it.\n */\npublic class FloatingIPPool implements Comparable<FloatingIPPool> {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return new Builder().fromFloatingIPPool(this);\n   }\n\n   public static class Builder {\n\n      protected String name;\n\n      /**\n       * @see FloatingIPPool#getName()\n       */\n      public Builder name(String name) {\n         this.name = name;\n         return this;\n      }\n\n      public FloatingIPPool build() {\n         return new FloatingIPPool(name);\n      }\n\n      public Builder fromFloatingIPPool(FloatingIPPool in) {\n         return this\n               .name(in.getName());\n      }\n   }\n\n\n   private final String name;\n\n\n   @ConstructorProperties({\n         \"name\"\n   })\n   protected FloatingIPPool(String name) {\n      this.name = name;\n   }\n\n   public String getName() {\n      return this.name;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(name);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      FloatingIPPool that = FloatingIPPool.class.cast(obj);\n      return Objects.equal(this.name, that.name);\n   }\n\n   protected MoreObjects.ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"name\", name);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int compareTo(FloatingIPPool o) {\n      return this.name.compareTo(o.getName());\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/FloatingIpForServer.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain;\n\nimport com.google.auto.value.AutoValue;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.RegionAndId;\n\n@AutoValue\npublic abstract class FloatingIpForServer {\n\n   public abstract RegionAndId serverId();\n   public abstract String floatingIpId();\n   public abstract String ip();\n\n   public static FloatingIpForServer create(RegionAndId serverId,\n                               String floatingIpId,\n                               String ip\n   ) {\n      return new AutoValue_FloatingIpForServer(serverId, floatingIpId, ip);\n   }\n\n   FloatingIpForServer() {\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/Host.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Class Host\n*/\npublic class Host {\n\n   public static Builder<?> builder() { \n      return new ConcreteBuilder();\n   }\n   \n   public Builder<?> toBuilder() { \n      return new ConcreteBuilder().fromHost(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>>  {\n      protected abstract T self();\n\n      protected String name;\n      protected String service;\n      protected String zone;\n   \n      /** \n       * @see Host#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /** \n       * @see Host#getService()\n       */\n      public T service(String service) {\n         this.service = service;\n         return self();\n      }\n\n      /**\n       * @see Host#getZone()\n       */\n      public T zone(String zone) {\n         this.zone = zone;\n         return self();\n      }\n\n      public Host build() {\n         return new Host(name, service, zone);\n      }\n      \n      public T fromHost(Host in) {\n         return this\n                  .name(in.getName())\n                  .service(in.getService())\n                  .zone(in.getZone());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   @Named(\"host_name\")\n   private final String name;\n   private final String service;\n   private final String zone;\n\n   @ConstructorProperties({\n      \"host_name\", \"service\", \"zone\"\n   })\n   protected Host(@Nullable String name, @Nullable String service, @Nullable String zone) {\n      this.name = name;\n      this.service = service;\n      this.zone = zone;\n   }\n\n   @Nullable\n   public String getName() {\n      return this.name;\n   }\n\n   @Nullable\n   public String getService() {\n      return this.service;\n   }\n\n   @Nullable\n   public String getZone() {\n      return this.zone;\n   }\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(name, service, zone);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Host that = Host.class.cast(obj);\n      return Objects.equal(this.name, that.name)\n               && Objects.equal(this.service, that.service)\n               && Objects.equal(this.zone, that.zone);\n   }\n   \n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"name\", name).add(\"service\", service).add(\"zone\", zone);\n   }\n   \n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/HostAggregate.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Aggregates can be manipulated using the Aggregate Extension to Nova (alias \"OS-AGGREGATES\")\n *\n * @see org.jclouds.openstack.nova.v2_0.extensions.HostAggregateApi\n*/\npublic class HostAggregate {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromHostAggregate(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>>  {\n      protected abstract T self();\n\n      protected String id;\n      protected String name;\n      protected String availabilityZone;\n      protected Set<String> hosts = ImmutableSet.of();\n      protected String state;\n      protected Date created;\n      protected Date updated;\n      protected Map<String, String> metadata = ImmutableMap.of();\n\n      /**\n       * @see HostAggregate#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see HostAggregate#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /**\n       * @see HostAggregate#getAvailabilityZone()\n       */\n      public T availabilityZone(String availabilityZone) {\n         this.availabilityZone = availabilityZone;\n         return self();\n      }\n\n      /**\n       * @see HostAggregate#getHosts()\n       */\n      public T hosts(Set<String> hosts) {\n         this.hosts = ImmutableSet.copyOf(checkNotNull(hosts, \"hosts\"));\n         return self();\n      }\n\n      public T hosts(String... in) {\n         return hosts(ImmutableSet.copyOf(in));\n      }\n\n      /**\n       * @see HostAggregate#getState()\n       */\n      public T state(String state) {\n         this.state = state;\n         return self();\n      }\n\n      /**\n       * @see HostAggregate#getCreated()\n       */\n      public T created(Date created) {\n         this.created = created;\n         return self();\n      }\n\n      /**\n       * @see HostAggregate#getUpdated()\n       */\n      public T updated(Date updated) {\n         this.updated = updated;\n         return self();\n      }\n\n      /**\n       * @see HostAggregate#getMetadata()\n       */\n      public T metadata(Map<String, String> metadata) {\n         this.metadata = ImmutableMap.copyOf(checkNotNull(metadata, \"metadata\"));\n         return self();\n      }\n\n      public HostAggregate build() {\n         return new HostAggregate(id, name, availabilityZone, hosts, state, created, updated, metadata);\n      }\n\n      public T fromHostAggregate(HostAggregate in) {\n         return this\n                  .id(in.getId())\n                  .name(in.getName())\n                  .availabilityZone(in.getAvailabilityZone())\n                  .hosts(in.getHosts())\n                  .state(in.getState())\n                  .created(in.getCreated())\n                  .updated(in.getUpdated().get())\n                  .metadata(in.getMetadata());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final String name;\n   @Named(\"availability_zone\")\n   private final String availabilityZone;\n   private final Set<String> hosts;\n   @Named(\"operational_state\")\n   private final String state;\n   @Named(\"created_at\")\n   private final Date created;\n   @Named(\"updated_at\")\n   private final Optional<Date> updated;\n   private final Map<String, String> metadata;\n\n   @ConstructorProperties({\n      \"id\", \"name\", \"availability_zone\", \"hosts\", \"operational_state\", \"created_at\", \"updated_at\", \"metadata\"\n   })\n   protected HostAggregate(String id, String name, @Nullable String availabilityZone, @Nullable Set<String> hosts, @Nullable String state, Date created,\n                           @Nullable Date updated, @Nullable Map<String, String> metadata) {\n      this.id = checkNotNull(id, \"id\");\n      this.name = checkNotNull(name, \"name\");\n      this.availabilityZone = availabilityZone;\n      this.hosts = hosts == null ? ImmutableSet.<String>of() : ImmutableSet.copyOf(hosts);      \n      this.state = state;\n      this.created = checkNotNull(created, \"created\");\n      this.updated = Optional.fromNullable(updated);\n      this.metadata = metadata == null ? ImmutableMap.<String, String>of() : ImmutableMap.copyOf(metadata);\n   }\n\n   public String getId() {\n      return this.id;\n   }\n\n   public String getName() {\n      return this.name;\n   }\n\n   /**\n    * @return the availability zone this aggregate is in\n    */\n   public String getAvailabilityZone() {\n      return this.availabilityZone;\n   }\n\n   public Set<String> getHosts() {\n      return this.hosts;\n   }\n\n   public String getState() {\n      return this.state;\n   }\n\n   public Date getCreated() {\n      return this.created;\n   }\n\n   public Optional<Date> getUpdated() {\n      return this.updated;\n   }\n\n   public Map<String, String> getMetadata() {\n      return this.metadata;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, name, availabilityZone, hosts, state, created, updated, metadata);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      HostAggregate that = HostAggregate.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n               && Objects.equal(this.name, that.name)\n               && Objects.equal(this.availabilityZone, that.availabilityZone)\n               && Objects.equal(this.hosts, that.hosts)\n               && Objects.equal(this.state, that.state)\n               && Objects.equal(this.created, that.created)\n               && Objects.equal(this.updated, that.updated)\n               && Objects.equal(this.metadata, that.metadata);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"name\", name).add(\"availabilityZone\", availabilityZone).add(\"hosts\", hosts).add(\"state\", state).add(\"created\", created).add(\"updated\", updated).add(\"metadata\", metadata);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/HostResourceUsage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Class HostResourceUsage\n*/\npublic class HostResourceUsage {\n\n   public static Builder<?> builder() { \n      return new ConcreteBuilder();\n   }\n   \n   public Builder<?> toBuilder() { \n      return new ConcreteBuilder().fromHostResourceUsage(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>>  {\n      protected abstract T self();\n\n      protected String host;\n      protected String project;\n      protected int memoryMb;\n      protected int cpu;\n      protected int diskGb;\n   \n      /** \n       * @see HostResourceUsage#getHost()\n       */\n      public T host(String host) {\n         this.host = host;\n         return self();\n      }\n\n      /** \n       * @see HostResourceUsage#getProject()\n       */\n      public T project(String project) {\n         this.project = project;\n         return self();\n      }\n\n      /** \n       * @see HostResourceUsage#getMemoryMb()\n       */\n      public T memoryMb(int memoryMb) {\n         this.memoryMb = memoryMb;\n         return self();\n      }\n\n      /** \n       * @see HostResourceUsage#getCpu()\n       */\n      public T cpu(int cpu) {\n         this.cpu = cpu;\n         return self();\n      }\n\n      /** \n       * @see HostResourceUsage#getDiskGb()\n       */\n      public T diskGb(int diskGb) {\n         this.diskGb = diskGb;\n         return self();\n      }\n\n      public HostResourceUsage build() {\n         return new HostResourceUsage(host, project, memoryMb, cpu, diskGb);\n      }\n      \n      public T fromHostResourceUsage(HostResourceUsage in) {\n         return this\n                  .host(in.getHost())\n                  .project(in.getProject())\n                  .memoryMb(in.getMemoryMb())\n                  .cpu(in.getCpu())\n                  .diskGb(in.getDiskGb());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String host;\n   private final String project;\n   @Named(\"memory_mb\")\n   private final int memoryMb;\n   private final int cpu;\n   @Named(\"disk_gb\")\n   private final int diskGb;\n\n   @ConstructorProperties({\n      \"host\", \"project\", \"memory_mb\", \"cpu\", \"disk_gb\"\n   })\n   protected HostResourceUsage(String host, @Nullable String project, int memoryMb, int cpu, int diskGb) {\n      this.host = checkNotNull(host, \"host\");\n      this.project = project;\n      this.memoryMb = memoryMb;\n      this.cpu = cpu;\n      this.diskGb = diskGb;\n   }\n\n   public String getHost() {\n      return this.host;\n   }\n\n   @Nullable\n   public String getProject() {\n      return this.project;\n   }\n\n   public int getMemoryMb() {\n      return this.memoryMb;\n   }\n\n   public int getCpu() {\n      return this.cpu;\n   }\n\n   public int getDiskGb() {\n      return this.diskGb;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(host, project, memoryMb, cpu, diskGb);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      HostResourceUsage that = HostResourceUsage.class.cast(obj);\n      return Objects.equal(this.host, that.host)\n               && Objects.equal(this.project, that.project)\n               && Objects.equal(this.memoryMb, that.memoryMb)\n               && Objects.equal(this.cpu, that.cpu)\n               && Objects.equal(this.diskGb, that.diskGb);\n   }\n   \n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"host\", host).add(\"project\", project).add(\"memoryMb\", memoryMb).add(\"cpu\", cpu).add(\"diskGb\", diskGb);\n   }\n   \n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/Image.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Map;\n\nimport jakarta.inject.Named;\n\nimport com.google.common.collect.ImmutableList;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.Resource;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * An image is a collection of files you use to create or rebuild a server. Operators provide\n * pre-built OS images by default. You may also create custom images.\n * \n * @see <a href= \"http://docs.openstack.org/api/openstack-compute/1.1/content/Images-d1e4427.html\"\n      />\n*/\npublic class Image extends Resource {\n\n   /**\n    * In-flight images will have the status attribute set to SAVING and the conditional progress\n    * element (0-100% completion) will also be returned. Other possible values for the status\n    * attribute include: UNKNOWN, ACTIVE, SAVING, ERROR, and DELETED. Images with an ACTIVE status\n    * are available for install. The optional minDisk and minRam attributes set the minimum disk and\n    * RAM requirements needed to create a server with the image.\n    * \n    */\n   public static enum Status {\n      \n      UNRECOGNIZED, UNKNOWN, ACTIVE, SAVING, ERROR, DELETED;\n      \n      public String value() {\n      return name();\n      }\n      \n      public static Status fromValue(String v) {\n      try {\n      return valueOf(v);\n      } catch (IllegalArgumentException e) {\n      return UNRECOGNIZED;\n      }\n      }\n      \n   }\n\n   public static Builder<?> builder() { \n      return new ConcreteBuilder();\n   }\n   \n   public Builder<?> toBuilder() { \n      return new ConcreteBuilder().fromImage(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> extends Resource.Builder<T>  {\n      protected Date updated;\n      protected Date created;\n      protected String tenantId;\n      protected String userId;\n      protected Image.Status status;\n      protected int progress;\n      protected int minDisk;\n      protected int minRam;\n      protected Resource server;\n      protected List<BlockDeviceMapping> blockDeviceMapping = ImmutableList.of();\n      protected Map<String, String> metadata = ImmutableMap.of();\n   \n      /** \n       * @see Image#getUpdated()\n       */\n      public T updated(Date updated) {\n         this.updated = updated;\n         return self();\n      }\n\n      /** \n       * @see Image#getCreated()\n       */\n      public T created(Date created) {\n         this.created = created;\n         return self();\n      }\n\n      /** \n       * @see Image#getTenantId()\n       */\n      public T tenantId(String tenantId) {\n         this.tenantId = tenantId;\n         return self();\n      }\n\n      /** \n       * @see Image#getUserId()\n       */\n      public T userId(String userId) {\n         this.userId = userId;\n         return self();\n      }\n\n      /** \n       * @see Image#getStatus()\n       */\n      public T status(Image.Status status) {\n         this.status = status;\n         return self();\n      }\n\n      /** \n       * @see Image#getProgress()\n       */\n      public T progress(int progress) {\n         this.progress = progress;\n         return self();\n      }\n\n      /** \n       * @see Image#getMinDisk()\n       */\n      public T minDisk(int minDisk) {\n         this.minDisk = minDisk;\n         return self();\n      }\n\n      /** \n       * @see Image#getMinRam()\n       */\n      public T minRam(int minRam) {\n         this.minRam = minRam;\n         return self();\n      }\n\n      /** \n       * @see Image#getServer()\n       */\n      public T server(Resource server) {\n         this.server = server;\n         return self();\n      }\n\n      public T blockDeviceMapping(List<BlockDeviceMapping> blockDeviceMapping){\n         this.blockDeviceMapping = blockDeviceMapping;\n         return self();\n      }\n\n      /** \n       * @see Image#getMetadata()\n       */\n      public T metadata(Map<String, String> metadata) {\n         this.metadata = ImmutableMap.copyOf(checkNotNull(metadata, \"metadata\"));     \n         return self();\n      }\n\n      public Image build() {\n         return new Image(id, name, links, updated, created, tenantId, userId, status, progress, minDisk, minRam, blockDeviceMapping, server, metadata);\n      }\n      \n      public T fromImage(Image in) {\n         return super.fromResource(in)\n                  .updated(in.getUpdated())\n                  .created(in.getCreated())\n                  .tenantId(in.getTenantId())\n                  .userId(in.getUserId())\n                  .status(in.getStatus())\n                  .progress(in.getProgress())\n                  .minDisk(in.getMinDisk())\n                  .minRam(in.getMinRam())\n                  .server(in.getServer())\n                  .metadata(in.getMetadata());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final Date updated;\n   private final Date created;\n   @Named(\"tenant_id\")\n   private final String tenantId;\n   @Named(\"user_id\")\n   private final String userId;\n   private final Image.Status status;\n   private final int progress;\n   private final int minDisk;\n   private final int minRam;\n   private final List<BlockDeviceMapping> blockDeviceMapping;\n   private final Resource server;\n   private final Map<String, String> metadata;\n\n   @ConstructorProperties({\n      \"id\", \"name\", \"links\", \"updated\", \"created\", \"tenant_id\", \"user_id\", \"status\", \"progress\", \"minDisk\", \"minRam\", \"server\", \"blockDeviceMapping\", \"metadata\"\n   })\n   protected Image(String id, @Nullable String name, java.util.Set<Link> links, @Nullable Date updated, @Nullable Date created,\n                   String tenantId, @Nullable String userId, @Nullable Status status, int progress, int minDisk, int minRam,\n                   @Nullable List<BlockDeviceMapping> blockDeviceMapping, @Nullable Resource server, @Nullable Map<String, String> metadata) {\n      super(id, name, links);\n      this.updated = updated;\n      this.created = created;\n      this.tenantId = tenantId;\n      this.userId = userId;\n      this.status = status;\n      this.progress = progress;\n      this.minDisk = minDisk;\n      this.minRam = minRam;\n      this.blockDeviceMapping = blockDeviceMapping == null ? ImmutableList.<BlockDeviceMapping>of() : blockDeviceMapping;\n      this.server = server;\n      this.metadata = metadata == null ? ImmutableMap.<String, String>of() : ImmutableMap.copyOf(metadata);\n   }\n\n   @Nullable\n   public Date getUpdated() {\n      return this.updated;\n   }\n\n   @Nullable\n   public Date getCreated() {\n      return this.created;\n   }\n\n   @Nullable\n   public String getTenantId() {\n      return this.tenantId;\n   }\n\n   @Nullable\n   public String getUserId() {\n      return this.userId;\n   }\n\n   @Nullable\n   public Status getStatus() {\n      return this.status;\n   }\n\n   public int getProgress() {\n      return this.progress;\n   }\n\n   public int getMinDisk() {\n      return this.minDisk;\n   }\n\n   public int getMinRam() {\n      return this.minRam;\n   }\n\n   @Nullable\n   public List<BlockDeviceMapping> getBlockDeviceMapping(){\n      return this.blockDeviceMapping;\n   }\n\n   @Nullable\n   public Resource getServer() {\n      return this.server;\n   }\n\n   public Map<String, String> getMetadata() {\n      return this.metadata;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(updated, created, tenantId, userId, status, progress, minDisk, minRam, server, metadata);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Image that = Image.class.cast(obj);\n      return super.equals(that) && Objects.equal(this.updated, that.updated)\n               && Objects.equal(this.created, that.created)\n               && Objects.equal(this.tenantId, that.tenantId)\n               && Objects.equal(this.userId, that.userId)\n               && Objects.equal(this.status, that.status)\n               && Objects.equal(this.progress, that.progress)\n               && Objects.equal(this.minDisk, that.minDisk)\n               && Objects.equal(this.minRam, that.minRam)\n               && Objects.equal(this.server, that.server)\n               && Objects.equal(this.metadata, that.metadata);\n   }\n   \n   protected ToStringHelper string() {\n      return super.string()\n            .add(\"updated\", updated).add(\"created\", created).add(\"tenantId\", tenantId).add(\"userId\", userId).add(\"status\", status).add(\"progress\", progress).add(\"minDisk\", minDisk).add(\"minRam\", minRam).add(\"server\", server).add(\"metadata\", metadata);\n   }\n   \n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/Ingress.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.net.domain.IpProtocol;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Ingress access to a destination protocol on particular ports\n * \n*/\n@Beta\npublic class Ingress {\n\n   public static Builder<?> builder() { \n      return new ConcreteBuilder();\n   }\n   \n   public Builder<?> toBuilder() { \n      return new ConcreteBuilder().fromIngress(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>>  {\n      protected abstract T self();\n\n      protected IpProtocol ipProtocol;\n      protected int fromPort;\n      protected int toPort;\n   \n      /** \n       * @see Ingress#getIpProtocol()\n       */\n      public T ipProtocol(IpProtocol ipProtocol) {\n         this.ipProtocol = ipProtocol;\n         return self();\n      }\n\n      /** \n       * @see Ingress#getFromPort()\n       */\n      public T fromPort(int fromPort) {\n         this.fromPort = fromPort;\n         return self();\n      }\n\n      /** \n       * @see Ingress#getToPort()\n       */\n      public T toPort(int toPort) {\n         this.toPort = toPort;\n         return self();\n      }\n\n      public Ingress build() {\n         return new Ingress(ipProtocol, fromPort, toPort);\n      }\n      \n      public T fromIngress(Ingress in) {\n         return this\n                  .ipProtocol(in.getIpProtocol())\n                  .fromPort(in.getFromPort())\n                  .toPort(in.getToPort());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   @Named(\"ip_protocol\")\n   private final IpProtocol ipProtocol;\n   @Named(\"from_port\")\n   private final int fromPort;\n   @Named(\"to_port\")\n   private final int toPort;\n\n   @ConstructorProperties({\n      \"ip_protocol\", \"from_port\", \"to_port\"\n   })\n   protected Ingress(@Nullable IpProtocol ipProtocol, int fromPort, int toPort) {\n      this.ipProtocol = ipProtocol == null ? IpProtocol.UNRECOGNIZED : ipProtocol;\n      this.fromPort = fromPort;\n      this.toPort = toPort;\n   }\n\n   /**\n    * destination IP protocol\n    */\n   public IpProtocol getIpProtocol() {\n      return this.ipProtocol;\n   }\n\n   /**\n    * Start of destination port range for the TCP and UDP protocols, or an ICMP type number. An ICMP\n    * type number of -1 indicates a wildcard (i.e., any ICMP type number).\n    */\n   public int getFromPort() {\n      return this.fromPort;\n   }\n\n   /**\n    * End of destination port range for the TCP and UDP protocols, or an ICMP code. An ICMP code of\n    * -1 indicates a wildcard (i.e., any ICMP code).\n    */\n   public int getToPort() {\n      return this.toPort;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(ipProtocol, fromPort, toPort);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Ingress that = Ingress.class.cast(obj);\n      return Objects.equal(this.ipProtocol, that.ipProtocol)\n               && Objects.equal(this.fromPort, that.fromPort)\n               && Objects.equal(this.toPort, that.toPort);\n   }\n   \n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"ipProtocol\", ipProtocol).add(\"fromPort\", fromPort).add(\"toPort\", toPort);\n   }\n   \n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/InterfaceAttachment.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.openstack.nova.v2_0.domain;\n\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Named;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ImmutableSet;\n\npublic class InterfaceAttachment {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromInterfaceAttachment(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      private String networkId;\n      private String portId;\n      private PortState portState;\n      private String macAddress;\n      private ImmutableSet<FixedIP> fixedIps;\n\n      /**\n       * @see InterfaceAttachment#getNetworkId()\n       */\n      public T networkId(String networkId) {\n         this.networkId = networkId;\n         return self();\n      }\n\n      /**\n       * @see InterfaceAttachment#getPortId()\n       */\n      public T portId(String portId) {\n         this.portId = portId;\n         return self();\n      }\n\n      /**\n       * @see InterfaceAttachment#getPortState()\n       */\n      public T portState(PortState portState) {\n         this.portState = portState;\n         return self();\n      }\n\n      /**\n       * @see InterfaceAttachment#getMacAddress()\n       */\n      public T macAddress(String macAddress) {\n         this.macAddress = macAddress;\n         return self();\n      }\n\n      /**\n       * @see InterfaceAttachment#getFixedIps()\n       */\n      public T fixedIps(ImmutableSet<FixedIP> fixedIps) {\n         this.fixedIps = fixedIps;\n         return self();\n      }\n\n      public InterfaceAttachment build() {\n         return new InterfaceAttachment(networkId, portId, portState, macAddress, fixedIps);\n      }\n\n      public T fromInterfaceAttachment(InterfaceAttachment in) {\n         return this.networkId(in.getNetworkId()).portId(in.getPortId()).portState(in.getPortState())\n               .macAddress(in.getMacAddress()).fixedIps(in.getFixedIps());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   @Named(\"net_id\")\n   private String networkId;\n   @Named(\"port_id\")\n   private String portId;\n   @Named(\"port_state\")\n   private PortState portState;\n   @Named(\"mac_addr\")\n   private String macAddress;\n   @Named(\"fixed_ips\")\n   private ImmutableSet<FixedIP> fixedIps;\n\n   @ConstructorProperties({ \"net_id\", \"port_id\", \"port_state\", \"mac_addr\", \"fixed_ips\" })\n   protected InterfaceAttachment(String networkId, String portId, PortState portState,\n         String macAddress, ImmutableSet<FixedIP> fixedIps) {\n      this.networkId = networkId;\n      this.portId = checkNotNull(portId, \"portId\");\n      this.portState = portState;\n      this.macAddress = macAddress;\n      this.fixedIps = fixedIps;\n   }\n\n   public String getNetworkId() {\n      return this.networkId;\n   }\n\n   public String getPortId() {\n      return this.portId;\n   }\n\n   public PortState getPortState() {\n      return this.portState;\n   }\n\n   public String getMacAddress() {\n      return this.macAddress;\n   }\n\n   public ImmutableSet<FixedIP> getFixedIps() {\n      return this.fixedIps;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(networkId, portId, portState, macAddress, fixedIps);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      InterfaceAttachment that = InterfaceAttachment.class.cast(obj);\n      return Objects.equal(this.networkId, that.networkId) && Objects.equal(this.portId, that.portId)\n            && Objects.equal(this.portState, that.portState) && Objects.equal(this.macAddress, that.macAddress)\n            && Objects.equal(this.fixedIps, that.fixedIps);\n   }\n\n   protected MoreObjects.ToStringHelper string() {\n      return toStringHelper(this).add(\"networkId\", networkId).add(\"portId\", portId).add(\"portState\", portState)\n            .add(\"macAddress\", macAddress).add(\"fixedIps\", fixedIps);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/KeyPair.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Class KeyPair\n*/\npublic class KeyPair {\n\n   public static Builder<?> builder() { \n      return new ConcreteBuilder();\n   }\n   \n   public Builder<?> toBuilder() { \n      return new ConcreteBuilder().fromKeyPair(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>>  {\n      protected abstract T self();\n\n      protected String publicKey;\n      protected String privateKey;\n      protected String userId;\n      protected String name;\n      protected String fingerprint;\n   \n      /** \n       * @see KeyPair#getPublicKey()\n       */\n      public T publicKey(String publicKey) {\n         this.publicKey = publicKey;\n         return self();\n      }\n\n      /** \n       * @see KeyPair#getPrivateKey()\n       */\n      public T privateKey(String privateKey) {\n         this.privateKey = privateKey;\n         return self();\n      }\n\n      /** \n       * @see KeyPair#getUserId()\n       */\n      public T userId(String userId) {\n         this.userId = userId;\n         return self();\n      }\n\n      /** \n       * @see KeyPair#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /** \n       * @see KeyPair#getFingerprint()\n       */\n      public T fingerprint(String fingerprint) {\n         this.fingerprint = fingerprint;\n         return self();\n      }\n\n      public KeyPair build() {\n         return new KeyPair(publicKey, privateKey, userId, name, fingerprint);\n      }\n      \n      public T fromKeyPair(KeyPair in) {\n         return this\n                  .publicKey(in.getPublicKey())\n                  .privateKey(in.getPrivateKey())\n                  .userId(in.getUserId())\n                  .name(in.getName())\n                  .fingerprint(in.getFingerprint());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   @Named(\"public_key\")\n   private final String publicKey;\n   @Named(\"private_key\")\n   private final String privateKey;\n   @Named(\"user_id\")\n   private final String userId;\n   private final String name;\n   private final String fingerprint;\n\n   @ConstructorProperties({\n      \"public_key\", \"private_key\", \"user_id\", \"name\", \"fingerprint\"\n   })\n   protected KeyPair(@Nullable String publicKey, @Nullable String privateKey, @Nullable String userId, String name, @Nullable String fingerprint) {\n      this.publicKey = publicKey;\n      this.privateKey = privateKey;\n      this.userId = userId;\n      this.name = checkNotNull(name, \"name\");\n      this.fingerprint = fingerprint;\n   }\n\n   @Nullable\n   public String getPublicKey() {\n      return this.publicKey;\n   }\n\n   @Nullable\n   public String getPrivateKey() {\n      return this.privateKey;\n   }\n\n   @Nullable\n   public String getUserId() {\n      return this.userId;\n   }\n\n   public String getName() {\n      return this.name;\n   }\n\n   @Nullable\n   public String getFingerprint() {\n      return this.fingerprint;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(publicKey, privateKey, userId, name, fingerprint);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      KeyPair that = KeyPair.class.cast(obj);\n      return Objects.equal(this.publicKey, that.publicKey)\n               && Objects.equal(this.privateKey, that.privateKey)\n               && Objects.equal(this.userId, that.userId)\n               && Objects.equal(this.name, that.name)\n               && Objects.equal(this.fingerprint, that.fingerprint);\n   }\n   \n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(\"\")\n            .omitNullValues()\n            .add(\"public_key\", publicKey)\n            .add(\"private_key\", privateKey)\n            .add(\"user_id\", userId)\n            .add(\"name\", name)\n            .add(\"fingerprint\", fingerprint);\n   }\n   \n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/Network.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain;\n\nimport static com.google.common.base.Preconditions.checkArgument;\n\nimport java.beans.ConstructorProperties;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Nova (or Neutron) network definition\n * Used to provide support for network, port, and fixed_ip when booting Nova servers.\n * OpenStack will support either a Nova Network or Neutron, but not both at the same time.\n * Specifying a port is only possible with Neutron.\n */\npublic class Network implements Comparable<Network> {\n   private final String networkUuid;\n   private final String portUuid;\n   private final String fixedIp;\n\n   @ConstructorProperties({\n      \"networkUuid\", \"portUuid\", \"fixedIp\"\n   })\n   protected Network(String networkUuid, String portUuid, String fixedIp) {\n      checkArgument(networkUuid != null || portUuid != null, \"At least one of networkUuid or portUuid should be specified\");\n      this.networkUuid = networkUuid;\n      this.portUuid = portUuid;\n      this.fixedIp = fixedIp;\n   }\n\n   /**\n    * @return the network uuid - Neutron or Nova\n    */\n   public String getNetworkUuid() {\n      return this.networkUuid;\n   }\n\n   /**\n    * @return the port uuid - Neutron only\n    */\n   public String getPortUuid() {\n      return this.portUuid;\n   }\n   \n   /**\n    * @return the fixed IP address - Neutron or Nova\n    */\n   public String getFixedIp() {\n      return this.fixedIp;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(networkUuid, portUuid, fixedIp);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Network that = Network.class.cast(obj);\n      return Objects.equal(this.networkUuid, that.networkUuid) && \n            Objects.equal(this.portUuid, that.portUuid) &&\n            Objects.equal(this.fixedIp, that.fixedIp);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"networkUuid\", networkUuid)\n            .add(\"portUuid\", portUuid)\n            .add(\"fixedIp\", fixedIp);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   /**\n    * @return A new builder object\n    */\n   public static Builder builder() { \n      return new Builder();\n   }\n\n   /**\n    * @return A new Builder object from another Network\n    */\n   public Builder toBuilder() { \n      return new Builder().fromNetwork(this);\n   }\n\n   /**\n    * Implements the Builder pattern for this class\n    */\n   public static class Builder {\n      protected String networkUuid;\n      protected String portUuid;\n      protected String fixedIp;\n\n      /** \n       * @param networkUuid The UUID for the Nova network or Neutron subnet to be attached. \n       * @return The builder object.\n       * @see Network#getNetworkUuid()\n       */\n      public Builder networkUuid(String networkUuid) {\n         this.networkUuid = networkUuid;\n         return this;\n      }\n\n      /** \n       * @param portUuid The port UUID for this Neutron Network.\n       * @return The builder object.\n       * @see Network#getPortUuid()\n       */\n      public Builder portUuid(String portUuid) {\n         this.portUuid = portUuid;\n         return this;\n      }\n      \n      /** \n       * @param fixedIp The fixed IP address for this Network (if any). \n       * Service automatically assigns IP address if this is not provided.\n       * Fixed IP is compatible with both Nova Network and Neutron.\n       * @return The builder object.\n       * @see Network#getFixedIp()\n       */\n      public Builder fixedIp(String fixedIp) {\n         this.fixedIp = fixedIp;\n         return this;\n      }\n\n      /**\n       * @return A new Network object.\n       */\n      public Network build() {\n         return new Network(networkUuid, portUuid, fixedIp);\n      }\n\n      /**\n       * @param in The target Network\n       * @return A Builder from the provided Network\n       */\n      public Builder fromNetwork(Network in) {\n         return this\n               .networkUuid(in.getNetworkUuid())\n               .portUuid(in.getPortUuid())\n               .fixedIp(in.getFixedIp());\n      }        \n   }\n\n   @Override\n   public int compareTo(Network that) {\n      return this.toString().compareTo(that.toString());\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/PortInterface.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.base.Enums;\nimport com.google.common.base.Joiner;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableList;\nimport org.jclouds.json.SerializedNames;\n\nimport java.util.List;\n\nimport static com.google.common.base.Preconditions.checkArgument;\n\n@AutoValue\npublic abstract class PortInterface {\n\n    public enum State {\n        PROVISIONING, QUEUED, ACTIVE;\n\n        public static State fromValue(String value) {\n            Optional<State> state = Enums.getIfPresent(State.class, value.toUpperCase());\n            checkArgument(state.isPresent(), \"Expected one of %s but was %s\", Joiner.on(',').join(State.values()), value);\n            return state.get();\n        }\n    }\n\n    public abstract String portId();\n    public abstract String netId();\n    public abstract State portState();\n    public abstract List<FixedIP> fixedIPS();\n\n    @SerializedNames({\"port_id\", \"net_id\", \"port_state\", \"fixed_ips\"})\n    public static PortInterface create(String portId, String netId, State portState, List<FixedIP> fixedIPS) {\n        return new AutoValue_PortInterface(portId, netId, portState,\n                fixedIPS == null ? ImmutableList.<FixedIP> of() : ImmutableList.copyOf(fixedIPS)\n        );\n    }\n\n    PortInterface() {}\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/PortState.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.openstack.nova.v2_0.domain;\n\npublic enum PortState {\n   ACTIVE(\"active\"),\n   DOWN(\"down\"),\n   BUILD(\"build\"),\n   ERROR(\"error\"),\n   /**\n    * Used by jclouds when the service returns an unknown value other than null.\n    */\n   UNRECOGNIZED(\"unrecognized\");\n\n   private final String name;\n\n   private PortState(String name) {\n      this.name = name;\n   }\n\n   @Override\n   public String toString() {\n      return name();\n   }\n\n   /**\n    * This provides GSON enum support in jclouds.\n    * @param name The string representation of this enum value.\n    * @return The corresponding enum value.\n    */\n   public static PortState fromValue(String name) {\n      if (name != null) {\n         for (PortState value : PortState.values()) {\n           if (name.equalsIgnoreCase(value.name)) {\n             return value;\n           }\n         }\n         return UNRECOGNIZED;\n       }\n       return null;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/Quota.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Named;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Represents the set of limits (quotas) returned by the Quota Extension\n * \n * @see org.jclouds.openstack.nova.v2_0.extensions.QuotaApi\n*/\npublic class Quota {\n\n   public static Builder<?> builder() { \n      return new ConcreteBuilder();\n   }\n   \n   public Builder<?> toBuilder() { \n      return new ConcreteBuilder().fromQuotas(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>>  {\n      protected abstract T self();\n\n      protected String id;\n      protected int metadataItems;\n      protected int injectedFileContentBytes;\n      protected int volumes;\n      protected int gigabytes;\n      protected int ram;\n      protected int floatingIps;\n      protected int instances;\n      protected int injectedFiles;\n      protected int cores;\n      protected int securityGroups;\n      protected int securityGroupRules;\n      protected int keyPairs;\n   \n      /** \n       * @see Quota#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /** \n       * @see Quota#getMetadatas()\n       */\n      public T metadataItems(int metadataItems) {\n         this.metadataItems = metadataItems;\n         return self();\n      }\n\n      /** \n       * @see Quota#getInjectedFileContentBytes()\n       */\n      public T injectedFileContentBytes(int injectedFileContentBytes) {\n         this.injectedFileContentBytes = injectedFileContentBytes;\n         return self();\n      }\n\n      /** \n       * @see Quota#getVolumes()\n       */\n      public T volumes(int volumes) {\n         this.volumes = volumes;\n         return self();\n      }\n\n      /** \n       * @see Quota#getGigabytes()\n       */\n      public T gigabytes(int gigabytes) {\n         this.gigabytes = gigabytes;\n         return self();\n      }\n\n      /** \n       * @see Quota#getRam()\n       */\n      public T ram(int ram) {\n         this.ram = ram;\n         return self();\n      }\n\n      /** \n       * @see Quota#getFloatingIps()\n       */\n      public T floatingIps(int floatingIps) {\n         this.floatingIps = floatingIps;\n         return self();\n      }\n\n      /** \n       * @see Quota#getInstances()\n       */\n      public T instances(int instances) {\n         this.instances = instances;\n         return self();\n      }\n\n      /** \n       * @see Quota#getInjectedFiles()\n       */\n      public T injectedFiles(int injectedFiles) {\n         this.injectedFiles = injectedFiles;\n         return self();\n      }\n\n      /** \n       * @see Quota#getCores()\n       */\n      public T cores(int cores) {\n         this.cores = cores;\n         return self();\n      }\n\n      /** \n       * @see Quota#getSecurityGroups()\n       */\n      public T securityGroups(int securityGroups) {\n         this.securityGroups = securityGroups;\n         return self();\n      }\n\n      /** \n       * @see Quota#getSecurityGroupRules()\n       */\n      public T securityGroupRules(int securityGroupRules) {\n         this.securityGroupRules = securityGroupRules;\n         return self();\n      }\n\n      /** \n       * @see Quota#getKeyPairs()\n       */\n      public T keyPairs(int keyPairs) {\n         this.keyPairs = keyPairs;\n         return self();\n      }\n\n      public Quota build() {\n         return new Quota(id, metadataItems, injectedFileContentBytes, volumes, gigabytes, ram, floatingIps, instances, injectedFiles, cores, securityGroups, securityGroupRules, keyPairs);\n      }\n      \n      public T fromQuotas(Quota in) {\n         return this\n                  .id(in.getId())\n                  .metadataItems(in.getMetadatas())\n                  .injectedFileContentBytes(in.getInjectedFileContentBytes())\n                  .volumes(in.getVolumes())\n                  .gigabytes(in.getGigabytes())\n                  .ram(in.getRam())\n                  .floatingIps(in.getFloatingIps())\n                  .instances(in.getInstances())\n                  .injectedFiles(in.getInjectedFiles())\n                  .cores(in.getCores())\n                  .securityGroups(in.getSecurityGroups())\n                  .securityGroupRules(in.getSecurityGroupRules())\n                  .keyPairs(in.getKeyPairs());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   @Named(\"metadata_items\")\n   private final int metadataItems;\n   @Named(\"injected_file_content_bytes\")\n   private final int injectedFileContentBytes;\n   private final int volumes;\n   private final int gigabytes;\n   private final int ram;\n   @Named(\"floating_ips\")\n   private final int floatingIps;\n   private final int instances;\n   @Named(\"injected_files\")\n   private final int injectedFiles;\n   private final int cores;\n   @Named(\"security_groups\")\n   private final int securityGroups;\n   @Named(\"security_group_rules\")\n   private final int securityGroupRules;\n   @Named(\"key_pairs\")\n   private final int keyPairs;\n\n   @ConstructorProperties({\n      \"id\", \"metadata_items\", \"injected_file_content_bytes\", \"volumes\", \"gigabytes\", \"ram\", \"floating_ips\", \"instances\", \"injected_files\", \"cores\", \"security_groups\", \"security_group_rules\", \"key_pairs\"\n   })\n   protected Quota(String id, int metadataItems, int injectedFileContentBytes, int volumes, int gigabytes, int ram, int floatingIps, int instances, int injectedFiles, int cores, int securityGroups, int securityGroupRules, int keyPairs) {\n      this.id = checkNotNull(id, \"id\");\n      this.metadataItems = metadataItems;\n      this.injectedFileContentBytes = injectedFileContentBytes;\n      this.volumes = volumes;\n      this.gigabytes = gigabytes;\n      this.ram = ram;\n      this.floatingIps = floatingIps;\n      this.instances = instances;\n      this.injectedFiles = injectedFiles;\n      this.cores = cores;\n      this.securityGroups = securityGroups;\n      this.securityGroupRules = securityGroupRules;\n      this.keyPairs = keyPairs;\n   }\n\n   /**\n    * The id of the tenant this set of limits applies to\n    */\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * The limit of the number of metadata items for the tenant\n    */\n   public int getMetadatas() {\n      return this.metadataItems;\n   }\n\n   public int getInjectedFileContentBytes() {\n      return this.injectedFileContentBytes;\n   }\n\n   /**\n    * The limit of the number of volumes that can be created for the tenant\n    */\n   public int getVolumes() {\n      return this.volumes;\n   }\n\n   /**\n    * The limit of the total size of all volumes for the tenant\n    */\n   public int getGigabytes() {\n      return this.gigabytes;\n   }\n\n   /**\n    * The limit of total ram available to the tenant\n    */\n   public int getRam() {\n      return this.ram;\n   }\n\n   /**\n    * The limit of the number of floating ips for the tenant\n    */\n   public int getFloatingIps() {\n      return this.floatingIps;\n   }\n\n   /**\n    * The limit of the number of instances that can be created for the tenant\n    */\n   public int getInstances() {\n      return this.instances;\n   }\n\n   public int getInjectedFiles() {\n      return this.injectedFiles;\n   }\n\n   /**\n    * The limit of the number of cores that can be used by the tenant\n    */\n   public int getCores() {\n      return this.cores;\n   }\n\n   /**\n    * @return the limit of the number of security groups that can be created for the tenant\n    * @see org.jclouds.openstack.nova.v2_0.extensions.SecurityGroupApi\n    */\n   public int getSecurityGroups() {\n      return this.securityGroups;\n   }\n\n   /**\n    * @return the limit of the number of security group rules that can be created for the tenant\n    * @see org.jclouds.openstack.nova.v2_0.extensions.SecurityGroupApi\n    */\n   public int getSecurityGroupRules() {\n      return this.securityGroupRules;\n   }\n\n   /**\n    * @return the limit of the number of key pairs that can be created for the tenant\n    * @see org.jclouds.openstack.nova.v2_0.extensions.KeyPairApi\n    */\n   public int getKeyPairs() {\n      return this.keyPairs;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, metadataItems, injectedFileContentBytes, volumes, gigabytes, ram, floatingIps, instances, injectedFiles, cores, securityGroups, securityGroupRules, keyPairs);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Quota that = Quota.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n               && Objects.equal(this.metadataItems, that.metadataItems)\n               && Objects.equal(this.injectedFileContentBytes, that.injectedFileContentBytes)\n               && Objects.equal(this.volumes, that.volumes)\n               && Objects.equal(this.gigabytes, that.gigabytes)\n               && Objects.equal(this.ram, that.ram)\n               && Objects.equal(this.floatingIps, that.floatingIps)\n               && Objects.equal(this.instances, that.instances)\n               && Objects.equal(this.injectedFiles, that.injectedFiles)\n               && Objects.equal(this.cores, that.cores)\n               && Objects.equal(this.securityGroups, that.securityGroups)\n               && Objects.equal(this.securityGroupRules, that.securityGroupRules)\n               && Objects.equal(this.keyPairs, that.keyPairs);\n   }\n   \n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"metadataItems\", metadataItems).add(\"injectedFileContentBytes\", injectedFileContentBytes).add(\"volumes\", volumes).add(\"gigabytes\", gigabytes).add(\"ram\", ram).add(\"floatingIps\", floatingIps).add(\"instances\", instances).add(\"injectedFiles\", injectedFiles).add(\"cores\", cores).add(\"securityGroups\", securityGroups).add(\"securityGroupRules\", securityGroupRules).add(\"keyPairs\", keyPairs);\n   }\n   \n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/RebootType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain;\n\npublic enum RebootType {\n\n   HARD, SOFT;\n\n   public String value() {\n      return name();\n   }\n\n   public static RebootType fromValue(String v) {\n      return valueOf(v);\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/SecurityGroup.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Set;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Defines a security group\n*/\npublic class SecurityGroup {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromSecurityGroup(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>>  {\n      protected abstract T self();\n\n      protected String id;\n      protected String tenantId;\n      protected String name;\n      protected String description;\n      protected Set<SecurityGroupRule> rules = ImmutableSet.of();\n\n      /**\n       * @see SecurityGroup#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see SecurityGroup#getTenantId()\n       */\n      public T tenantId(String tenantId) {\n         this.tenantId = tenantId;\n         return self();\n      }\n\n      /**\n       * @see SecurityGroup#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /**\n       * @see SecurityGroup#getDescription()\n       */\n      public T description(String description) {\n         this.description = description;\n         return self();\n      }\n\n      /**\n       * @see SecurityGroup#getRules()\n       */\n      public T rules(Set<SecurityGroupRule> rules) {\n         this.rules = ImmutableSet.copyOf(checkNotNull(rules, \"rules\"));\n         return self();\n      }\n\n      public T rules(SecurityGroupRule... in) {\n         return rules(ImmutableSet.copyOf(in));\n      }\n\n      public SecurityGroup build() {\n         return new SecurityGroup(id, tenantId, name, description, rules);\n      }\n\n      public T fromSecurityGroup(SecurityGroup in) {\n         return this\n                  .id(in.getId())\n                  .tenantId(in.getTenantId())\n                  .name(in.getName())\n                  .description(in.getDescription())\n                  .rules(in.getRules());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   @Named(\"tenant_id\")\n   private final String tenantId;\n   private final String name;\n   private final String description;\n   private final Set<SecurityGroupRule> rules;\n\n   @ConstructorProperties({\n      \"id\", \"tenant_id\", \"name\", \"description\", \"rules\"\n   })\n   protected SecurityGroup(String id, @Nullable String tenantId, @Nullable String name, @Nullable String description, Set<SecurityGroupRule> rules) {\n      this.id = checkNotNull(id, \"id\");\n      this.tenantId = tenantId;\n      this.name = name;\n      this.description = description;\n      // if empty, leave null so this doesn't serialize to json\n      this.rules = checkNotNull(rules, \"rules\").isEmpty() ? null : ImmutableSet.copyOf(rules);\n   }\n\n   public String getId() {\n      return this.id;\n   }\n\n   @Nullable\n   public String getTenantId() {\n      return this.tenantId;\n   }\n\n   @Nullable\n   public String getName() {\n      return this.name;\n   }\n\n   @Nullable\n   public String getDescription() {\n      return this.description;\n   }\n\n   public Set<SecurityGroupRule> getRules() {\n      return this.rules;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, tenantId, name, description, rules);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      SecurityGroup that = SecurityGroup.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n               && Objects.equal(this.tenantId, that.tenantId)\n               && Objects.equal(this.name, that.name)\n               && Objects.equal(this.description, that.description)\n               && Objects.equal(this.rules, that.rules);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"tenantId\", tenantId).add(\"name\", name).add(\"description\", description).add(\"rules\", rules);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/SecurityGroupRule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.net.domain.IpProtocol;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ForwardingObject;\n\n/**\n * Defines a security group rule\n */\npublic class SecurityGroupRule extends Ingress {\n\n   public static class Cidr extends ForwardingObject {\n      private String cidr;\n\n      @ConstructorProperties(\"cidr\")\n      protected Cidr(String cidr) {\n         this.cidr = checkNotNull(cidr);\n      }\n\n      @Override\n      protected Object delegate() {\n         return cidr;\n      }\n   }\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromSecurityGroupRule(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> extends Ingress.Builder<T> {\n      protected String id;\n      protected TenantIdAndName group;\n      protected String parentGroupId;\n      protected String ipRange;\n\n      /**\n       * @see SecurityGroupRule#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see SecurityGroupRule#getGroup()\n       */\n      public T group(TenantIdAndName group) {\n         this.group = group;\n         return self();\n      }\n\n      /**\n       * @see SecurityGroupRule#getParentGroupId()\n       */\n      public T parentGroupId(String parentGroupId) {\n         this.parentGroupId = parentGroupId;\n         return self();\n      }\n\n      /**\n       * @see SecurityGroupRule#getIpRange()\n       */\n      public T ipRange(String ipRange) {\n         this.ipRange = ipRange;\n         return self();\n      }\n\n      public SecurityGroupRule build() {\n         return new SecurityGroupRule(ipProtocol, fromPort, toPort, id, group, parentGroupId, ipRange == null ? null : new Cidr(ipRange));\n      }\n\n      public T fromSecurityGroupRule(SecurityGroupRule in) {\n         return super.fromIngress(in)\n               .id(in.getId())\n               .group(in.getGroup())\n               .parentGroupId(in.getParentGroupId())\n               .ipRange(in.getIpRange());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final TenantIdAndName group;\n   @Named(\"parent_group_id\")\n   private final String parentGroupId;\n   @Named(\"ip_range\")\n   private final SecurityGroupRule.Cidr ipRange;\n\n   @ConstructorProperties({\n         \"ip_protocol\", \"from_port\", \"to_port\", \"id\", \"group\", \"parent_group_id\", \"ip_range\"\n   })\n   protected SecurityGroupRule(IpProtocol ipProtocol, int fromPort, int toPort, String id, @Nullable TenantIdAndName group, String parentGroupId, @Nullable Cidr ipRange) {\n      super(ipProtocol, fromPort, toPort);\n      this.id = checkNotNull(id, \"id\");\n      this.group = group;\n      this.parentGroupId = checkNotNull(parentGroupId, \"parentGroupId\");\n      this.ipRange = ipRange;\n   }\n\n   public String getId() {\n      return this.id;\n   }\n\n   @Nullable\n   public TenantIdAndName getGroup() {\n      return this.group;\n   }\n\n   public String getParentGroupId() {\n      return this.parentGroupId;\n   }\n\n   @Nullable\n   public String getIpRange() {\n      return ipRange == null ? null : ipRange.cidr;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, group, parentGroupId, ipRange);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      SecurityGroupRule that = SecurityGroupRule.class.cast(obj);\n      return super.equals(that) && Objects.equal(this.id, that.id)\n            && Objects.equal(this.group, that.group)\n            && Objects.equal(this.parentGroupId, that.parentGroupId)\n            && Objects.equal(this.ipRange, that.ipRange);\n   }\n\n   protected ToStringHelper string() {\n      return super.string()\n            .add(\"id\", id).add(\"group\", group).add(\"parentGroupId\", parentGroupId).add(\"ipRange\", ipRange);\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/Server.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\nimport java.util.Map;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.Resource;\n\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Strings;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.Multimap;\n\n/**\n * A server is a virtual machine instance in the compute system. Flavor and image are requisite\n * elements when creating a server.\n *\n * @see <a href=\n *      \"http://docs.openstack.org/api/openstack-compute/1.1/content/Get_Server_Details-d1e2623.html\"\n *      />\n */\npublic class Server extends Resource {\n   public static final String DISK_CONFIG_MANUAL = \"MANUAL\";\n   public static final String DISK_CONFIG_AUTO = \"AUTO\";\n\n   /**\n    * Servers contain a status attribute that can be used as an indication of the current server\n    * state. Servers with an ACTIVE status are available for use.\n    * <p/>\n    * Other possible values for the status attribute include: BUILD, REBUILD, SUSPENDED, RESIZE,\n    * VERIFY_RESIZE, REVERT_RESIZE, PASSWORD, REBOOT, HARD_REBOOT, DELETED, UNKNOWN, and ERROR.\n    *\n    */\n   public static enum Status {\n\n      ACTIVE, BUILD, REBUILD, SUSPENDED, PAUSED, RESIZE, VERIFY_RESIZE, REVERT_RESIZE, PASSWORD, REBOOT, HARD_REBOOT,\n      DELETED, UNKNOWN, ERROR,\n\n      /**\n       * @deprecated please use {@code Status.SHUTOFF} instead. To be removed in jclouds 2.0.\n       */\n      @Deprecated STOPPED,\n\n      UNRECOGNIZED, MIGRATING, SHUTOFF, RESCUE, SOFT_DELETED, SHELVED, SHELVED_OFFLOADED;\n\n      public String value() {\n         return name();\n      }\n\n      public static Status fromValue(String v) {\n         try {\n            return valueOf(v.replaceAll(\"\\\\(.*\", \"\"));\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n   }\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromServer(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> extends Resource.Builder<T> {\n      protected String uuid;\n      protected String tenantId;\n      protected String userId;\n      protected Date updated;\n      protected Date created;\n      protected String hostId;\n      protected String accessIPv4;\n      protected String accessIPv6;\n      protected Server.Status status;\n      protected Resource image;\n      protected Resource flavor;\n      protected String keyName;\n      protected String configDrive;\n      protected Multimap<String, Address> addresses = ImmutableMultimap.of();\n      protected Map<String, String> metadata = ImmutableMap.of();\n      protected ServerExtendedStatus extendedStatus;\n      protected ServerExtendedAttributes extendedAttributes;\n      protected String diskConfig;\n      protected String availabilityZone;\n\n      /**\n       * @see Server#getUuid()\n       */\n      public T uuid(String uuid) {\n         this.uuid = uuid;\n         return self();\n      }\n\n      /**\n       * @see Server#getTenantId()\n       */\n      public T tenantId(String tenantId) {\n         this.tenantId = tenantId;\n         return self();\n      }\n\n      /**\n       * @see Server#getUserId()\n       */\n      public T userId(String userId) {\n         this.userId = userId;\n         return self();\n      }\n\n      /**\n       * @see Server#getUpdated()\n       */\n      public T updated(Date updated) {\n         this.updated = updated;\n         return self();\n      }\n\n      /**\n       * @see Server#getCreated()\n       */\n      public T created(Date created) {\n         this.created = created;\n         return self();\n      }\n\n      /**\n       * @see Server#getHostId()\n       */\n      public T hostId(String hostId) {\n         this.hostId = hostId;\n         return self();\n      }\n\n      /**\n       * @see Server#getAccessIPv4()\n       */\n      public T accessIPv4(String accessIPv4) {\n         this.accessIPv4 = accessIPv4;\n         return self();\n      }\n\n      /**\n       * @see Server#getAccessIPv6()\n       */\n      public T accessIPv6(String accessIPv6) {\n         this.accessIPv6 = accessIPv6;\n         return self();\n      }\n\n      /**\n       * @see Server#getStatus()\n       */\n      public T status(Server.Status status) {\n         this.status = status;\n         return self();\n      }\n\n      /**\n       * @see Server#getImage()\n       */\n      public T image(Resource image) {\n         this.image = image;\n         return self();\n      }\n\n      /**\n       * @see Server#getFlavor()\n       */\n      public T flavor(Resource flavor) {\n         this.flavor = flavor;\n         return self();\n      }\n\n      /**\n       * @see Server#getKeyName()\n       */\n      public T keyName(String keyName) {\n         this.keyName = keyName;\n         return self();\n      }\n\n      /**\n       * @see Server#getConfigDrive()\n       */\n      public T configDrive(String configDrive) {\n         this.configDrive = configDrive;\n         return self();\n      }\n\n      /**\n       * @see Server#getAddresses()\n       */\n      public T addresses(Multimap<String, Address> addresses) {\n         this.addresses = addresses;\n         return self();\n      }\n\n      /**\n       * @see Server#getMetadata()\n       */\n      public T metadata(Map<String, String> metadata) {\n         this.metadata = ImmutableMap.copyOf(checkNotNull(metadata, \"metadata\"));\n         return self();\n      }\n\n      /**\n       * @see Server#getExtendedStatus()\n       */\n      public T extendedStatus(ServerExtendedStatus extendedStatus) {\n         this.extendedStatus = extendedStatus;\n         return self();\n      }\n\n      /**\n       * @see Server#getExtendedAttributes()\n       */\n      public T extendedAttributes(ServerExtendedAttributes extendedAttributes) {\n         this.extendedAttributes = extendedAttributes;\n         return self();\n      }\n\n      /**\n       * @see Server#getDiskConfig()\n       */\n      public T diskConfig(String diskConfig) {\n         this.diskConfig = diskConfig;\n         return self();\n      }\n\n      /**\n       * @see Server#getAvailabilityZone()\n       */\n      public T availabilityZone(String availabilityZone) {\n         this.availabilityZone = availabilityZone;\n         return self();\n      }\n\n      public Server build() {\n         return new Server(id, name, links, uuid, tenantId, userId, updated, created, hostId, accessIPv4, accessIPv6,\n               status, image, flavor, keyName, configDrive, addresses, metadata, extendedStatus,\n               extendedAttributes, diskConfig, availabilityZone);\n      }\n\n      public T fromServer(Server in) {\n         return super.fromResource(in)\n               .uuid(in.getUuid())\n               .tenantId(in.getTenantId())\n               .userId(in.getUserId())\n               .updated(in.getUpdated())\n               .created(in.getCreated())\n               .hostId(in.getHostId())\n               .accessIPv4(in.getAccessIPv4())\n               .accessIPv6(in.getAccessIPv6())\n               .status(in.getStatus())\n               .image(in.getImage())\n               .flavor(in.getFlavor())\n               .keyName(in.getKeyName())\n               .configDrive(in.getConfigDrive())\n               .addresses(in.getAddresses())\n               .metadata(in.getMetadata())\n               .extendedStatus(in.getExtendedStatus().orNull())\n               .extendedAttributes(in.getExtendedAttributes().orNull())\n               .diskConfig(in.getDiskConfig().orNull())\n               .availabilityZone(in.getAvailabilityZone().orNull());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String uuid;\n   @Named(\"tenant_id\")\n   private final String tenantId;\n   @Named(\"user_id\")\n   private final String userId;\n   private final Date updated;\n   private final Date created;\n   private final String hostId;\n   private final String accessIPv4;\n   private final String accessIPv6;\n   private final Server.Status status;\n   private final Resource image;\n   private final Resource flavor;\n   @Named(\"key_name\")\n   private final String keyName;\n   @Named(\"config_drive\")\n   private final String configDrive;\n   private final Multimap<String, Address> addresses;\n   private final Map<String, String> metadata;\n   private final Optional<ServerExtendedStatus> extendedStatus;\n   private final Optional<ServerExtendedAttributes> extendedAttributes;\n   @Named(\"OS-DCF:diskConfig\")\n   private final Optional<String> diskConfig;\n   @Named(\"OS-EXT-AZ:availability_zone\")\n   private final Optional<String> availabilityZone;\n\n   @ConstructorProperties({\"id\", \"name\", \"links\", \"uuid\", \"tenant_id\", \"user_id\", \"updated\", \"created\", \"hostId\", \"accessIPv4\", \"accessIPv6\", \"status\", \"image\", \"flavor\", \"key_name\", \"config_drive\", \"addresses\", \"metadata\", \"extendedStatus\", \"extendedAttributes\", \"OS-DCF:diskConfig\", \"OS-EXT-AZ:availability_zone\"})\n   protected Server(String id, @Nullable String name, java.util.Set<Link> links, @Nullable String uuid, String tenantId,\n                    String userId, @Nullable Date updated, Date created, @Nullable String hostId, @Nullable String accessIPv4,\n                    @Nullable String accessIPv6, Server.Status status, @Nullable Resource image, Resource flavor, @Nullable String keyName,\n                    @Nullable String configDrive, Multimap<String, Address> addresses, Map<String, String> metadata,\n                    @Nullable ServerExtendedStatus extendedStatus, @Nullable ServerExtendedAttributes extendedAttributes,\n                    @Nullable String diskConfig, @Nullable String availabilityZone) {\n      super(id, name, links);\n      this.uuid = uuid;\n      this.tenantId = checkNotNull(tenantId, \"tenantId\");\n      this.userId = checkNotNull(userId, \"userId\");\n      this.updated = updated;\n      this.created = checkNotNull(created, \"created\");\n      this.hostId = Strings.emptyToNull(hostId);\n      this.accessIPv4 = Strings.emptyToNull(accessIPv4);\n      this.accessIPv6 = Strings.emptyToNull(accessIPv6);\n      this.status = checkNotNull(status, \"status\");\n      this.image = image;\n      this.flavor = checkNotNull(flavor, \"flavor\");\n      this.keyName = Strings.emptyToNull(keyName);\n      this.configDrive = Strings.emptyToNull(configDrive);\n      this.addresses = ImmutableMultimap.copyOf(checkNotNull(addresses, \"addresses\"));\n      this.metadata = ImmutableMap.copyOf(checkNotNull(metadata, \"metadata\"));\n      this.extendedStatus = Optional.fromNullable(extendedStatus);\n      this.extendedAttributes = Optional.fromNullable(extendedAttributes);\n      this.diskConfig = Optional.fromNullable(diskConfig);\n      this.availabilityZone = Optional.fromNullable(availabilityZone);\n   }\n\n   /**\n    * only present until the id is in uuid form\n    *\n    * @return uuid, if id is an integer val\n    */\n   @Nullable\n   public String getUuid() {\n      return this.uuid;\n   }\n\n   public String getTenantId() {\n      return this.tenantId;\n   }\n\n   public String getUserId() {\n      return this.userId;\n   }\n\n   @Nullable\n   public Date getUpdated() {\n      return this.updated;\n   }\n\n   public Date getCreated() {\n      return this.created;\n   }\n\n   /**\n    * @return host identifier, or null if in {@link Status#BUILD}\n    */\n   @Nullable\n   public String getHostId() {\n      return this.hostId;\n   }\n\n   @Nullable\n   public String getAccessIPv4() {\n      return this.accessIPv4;\n   }\n\n   @Nullable\n   public String getAccessIPv6() {\n      return this.accessIPv6;\n   }\n\n   public Status getStatus() {\n      return this.status;\n   }\n\n   @Nullable\n   public String getConfigDrive() {\n      return this.configDrive;\n   }\n\n   public Resource getImage() {\n      return this.image;\n   }\n\n   public Resource getFlavor() {\n      return this.flavor;\n   }\n\n   public Map<String, String> getMetadata() {\n      return metadata;\n   }\n\n   /**\n    * @return the ip addresses assigned to the server\n    */\n   public Multimap<String, Address> getAddresses() {\n      return addresses;\n   }\n\n   /**\n    * @return keyName if extension is present and there is a value for this server\n    * @see KeyPairApi\n    */\n   @Nullable\n   public String getKeyName() {\n      return keyName;\n   }\n\n   /**\n    * Retrieves the extended server status fields (alias \"OS-EXT-STS\")\n    * <p/>\n    * NOTE: This field is only present if the Extended Status extension is installed.\n    *\n    * @see org.jclouds.openstack.nova.v2_0.features.ExtensionApi#getExtensionByAlias\n    * @see org.jclouds.openstack.nova.v2_0.extensions.ExtensionNamespaces#EXTENDED_STATUS\n    */\n   public Optional<ServerExtendedStatus> getExtendedStatus() {\n      return this.extendedStatus;\n   }\n\n   /**\n    * Retrieves the extended server attributes fields (alias \"OS-EXT-SRV-ATTR\")\n    * <p/>\n    * NOTE: This field is only present if the The Extended Server Attributes API extension is installed.\n    *\n    * @see org.jclouds.openstack.nova.v2_0.features.ExtensionApi#getExtensionByAlias\n    * @see org.jclouds.openstack.nova.v2_0.extensions.ExtensionNamespaces#EXTENDED_STATUS\n    */\n   public Optional<ServerExtendedAttributes> getExtendedAttributes() {\n      return this.extendedAttributes;\n   }\n\n   /**\n    * Disk config attribute from the Disk Config Extension (alias \"OS-DCF\").\n    * One of {@link Server#DISK_CONFIG_AUTO} or {@link Server#DISK_CONFIG_MANUAL}.\n    * This field is only present if the Disk Config extension is installed.\n    * <p/>\n    * NOTE: Typically a field like this would be implemented as an enum but this field was\n    * originally implmented as a String and {@link Server#DISK_CONFIG_AUTO} and \n    * {@link Server#DISK_CONFIG_MANUAL} were added later as Strings to preserve backwards\n    * compatibility.\n    *\n    * @see org.jclouds.openstack.nova.v2_0.features.ExtensionApi#getExtensionByAlias\n    * @see org.jclouds.openstack.nova.v2_0.extensions.ExtensionNamespaces#DISK_CONFIG\n    * @see CreateServerOptions#getDiskConfig()\n    */\n   public Optional<String> getDiskConfig() {\n      return this.diskConfig;\n   }\n\n   /**\n    * return the Availability Zone of a server\n    * @see org.jclouds.openstack.nova.v2_0.extensions.ExtensionNamespaces#AVAILABILITY_ZONE\n    */\n   @Nullable\n   public Optional<String> getAvailabilityZone() {\n      return this.availabilityZone;\n   }\n\n   // hashCode/equals from super is ok\n\n   @Override\n   protected ToStringHelper string() {\n      return super.string()\n            .add(\"uuid\", uuid).add(\"tenantId\", tenantId).add(\"userId\", userId).add(\"updated\", updated).add(\"created\", created)\n            .add(\"hostId\", hostId).add(\"accessIPv4\", accessIPv4).add(\"accessIPv6\", accessIPv6).add(\"status\", status).add(\"image\", image)\n            .add(\"flavor\", flavor).add(\"keyName\", keyName).add(\"configDrive\", configDrive).add(\"addresses\", addresses)\n            .add(\"metadata\", metadata).add(\"extendedStatus\", extendedStatus).add(\"extendedAttributes\", extendedAttributes)\n            .add(\"diskConfig\", diskConfig)\n            .add(\"availabilityZone\", availabilityZone);\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/ServerCreated.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.Resource;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.base.Optional;\n\n/**\n * Server Resource with administrative password returned by ServerApi#CreateServer calls\n * \n * @see <a href=\n      \"http://docs.openstack.org/api/openstack-compute/1.1/content/Get_Server_Details-d1e2623.html\"\n      />\n*/\npublic class ServerCreated extends Resource {\n\n   public static Builder builder() { \n      return new Builder();\n   }\n   \n   public Builder toBuilder() { \n      return builder().fromServerCreated(this);\n   }\n\n   public static final class Builder extends Resource.Builder<Builder>  {\n      protected String adminPass;\n      protected String diskConfig;\n   \n      /** \n       * @see ServerCreated#getAdminPass()\n       */\n      public Builder adminPass(String adminPass) {\n         this.adminPass = adminPass;\n         return self();\n      }\n      \n      /** \n       * @see ServerCreated#getDiskConfig()\n       */\n      public Builder diskConfig(String diskConfig) {\n         this.diskConfig = diskConfig;\n         return self();\n      }\n\n      public ServerCreated build() {\n         return new ServerCreated(id, name, links, adminPass, diskConfig);\n      }\n      \n      public Builder fromServerCreated(ServerCreated in) {\n         return super.fromResource(in).adminPass(in.getAdminPass().orNull()).diskConfig(in.getDiskConfig().orNull());\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n   }\n\n   private final Optional<String> adminPass;\n   private final Optional<String> diskConfig;\n\n   @ConstructorProperties({\n      \"id\", \"name\", \"links\", \"adminPass\", \"OS-DCF:diskConfig\" \n   })\n   protected ServerCreated(String id, @Nullable String name, Set<Link> links, @Nullable String adminPass, \n         @Nullable String diskConfig) {\n      super(id, name, links);\n      this.adminPass = Optional.fromNullable(adminPass);\n      this.diskConfig = Optional.fromNullable(diskConfig);\n   }\n\n   /**\n    * present unless the nova install was configured with the option {@code enable_instance_password=false}\n    */\n   public Optional<String> getAdminPass() {\n      return this.adminPass;\n   }\n\n   /**\n    * @see CreateServerOptions#getDiskConfig()\n    */\n   public Optional<String> getDiskConfig() {\n      return this.diskConfig;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(adminPass, diskConfig);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      ServerCreated that = ServerCreated.class.cast(obj);\n      return super.equals(that) && Objects.equal(this.adminPass, that.adminPass)\n            && Objects.equal(this.diskConfig, that.diskConfig);\n   }\n\n   @Override\n   protected ToStringHelper string() {\n      return super.string().add(\"adminPass\", adminPass.orNull()).add(\"diskConfig\", diskConfig.orNull());\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/ServerExtendedAttributes.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Additional attributes delivered by Extended Server Attributes extension (alias \"OS-EXT-SRV-ATTR\")\n * \n * @see <a href=\n        \"http://nova.openstack.org/api/nova.api.openstack.compute.contrib.extended_server_attributes.html\"\n       />\n * @see org.jclouds.openstack.nova.v2_0.features.ExtensionApi#getExtensionByAlias\n * @see org.jclouds.openstack.nova.v2_0.extensions.ExtensionNamespaces#EXTENDED_STATUS\n*/\npublic class ServerExtendedAttributes {\n\n   public static Builder builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder toBuilder() {\n      return new ConcreteBuilder().fromServerExtendedAttributes(this);\n   }\n\n   public static class Builder {\n\n      protected String instanceName;\n      protected String hostName;\n      protected String hypervisorHostName;\n\n      /** \n       * @see ServerExtendedAttributes#getInstanceName()\n       */\n      public Builder  instanceName(String instanceName) {\n         this.instanceName = instanceName;\n         return self();\n      }\n\n      /** \n       * @see ServerExtendedAttributes#getHostName()\n       */\n      public Builder  hostName(String hostName) {\n         this.hostName = hostName;\n         return self();\n      }\n\n      /** \n       * @see ServerExtendedAttributes#getHypervisorHostName()\n       */\n      public Builder  hypervisorHostName(String hypervisorHostName) {\n         this.hypervisorHostName = hypervisorHostName;\n         return self();\n      }\n\n      public ServerExtendedAttributes build() {\n         return new ServerExtendedAttributes(instanceName, hostName, hypervisorHostName);\n      }\n      \n      public Builder  fromServerExtendedAttributes(ServerExtendedAttributes in) {\n         return this\n               .instanceName(in.getInstanceName())\n               .hostName(in.getHostName())\n               .hypervisorHostName(in.getHypervisorHostName());\n      }\n\n      protected Builder self(){\n         return this;\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   @Named(\"OS-EXT-SRV-ATTR:instance_name\")\n   private final String instanceName;\n   @Named(\"OS-EXT-SRV-ATTR:host\")\n   private final String hostName;\n   @Named(\"OS-EXT-SRV-ATTR:hypervisor_hostname\")\n   private final String hypervisorHostName;\n\n   @ConstructorProperties({\"OS-EXT-SRV-ATTR:instance_name\", \"OS-EXT-SRV-ATTR:host\", \"OS-EXT-SRV-ATTR:hypervisor_hostname\"})\n   protected ServerExtendedAttributes(@Nullable String instanceName, @Nullable String hostName, @Nullable String hypervisorHostName) {\n      this.instanceName = instanceName;\n      this.hostName = hostName;\n      this.hypervisorHostName = hypervisorHostName;\n   }\n\n   @Nullable\n   public String getInstanceName() {\n      return this.instanceName;\n   }\n\n   @Nullable\n   public String getHostName() {\n      return this.hostName;\n   }\n\n   @Nullable\n   public String getHypervisorHostName() {\n      return this.hypervisorHostName;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(instanceName, hostName, hypervisorHostName);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      ServerExtendedAttributes that = ServerExtendedAttributes.class.cast(obj);\n      return Objects.equal(this.instanceName, that.instanceName)\n               && Objects.equal(this.hostName, that.hostName)\n               && Objects.equal(this.hypervisorHostName, that.hypervisorHostName);\n   }\n   \n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"instanceName\", instanceName).add(\"hostName\", hostName).add(\"hypervisorHostName\", hypervisorHostName);\n   }\n   \n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/ServerExtendedStatus.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Additional attributes delivered by Extended Server Status extension (alias \"OS-EXT-STS\")\n * \n * @see <a href=\n       \"http://nova.openstack.org/api/nova.api.openstack.compute.contrib.extended_status.html\"\n       />\n * @see org.jclouds.openstack.nova.v2_0.features.ExtensionApi#getExtensionByAlias\n * @see org.jclouds.openstack.nova.v1_1.extensions.ExtensionNamespaces#EXTENDED_STATUS (extended status?)\n*/\npublic class ServerExtendedStatus {\n\n   public static Builder<?> builder() { \n      return new ConcreteBuilder();\n   }\n   \n   public Builder<?> toBuilder() { \n      return new ConcreteBuilder().fromServerExtendedStatus(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>>  {\n      protected abstract T self();\n\n      protected String taskState;\n      protected String vmState;\n      protected int powerState;\n   \n      /** \n       * @see ServerExtendedStatus#getTaskState()\n       */\n      public T taskState(String taskState) {\n         this.taskState = taskState;\n         return self();\n      }\n\n      /** \n       * @see ServerExtendedStatus#getVmState()\n       */\n      public T vmState(String vmState) {\n         this.vmState = vmState;\n         return self();\n      }\n\n      /** \n       * @see ServerExtendedStatus#getPowerState()\n       */\n      public T powerState(int powerState) {\n         this.powerState = powerState;\n         return self();\n      }\n\n      public ServerExtendedStatus build() {\n         return new ServerExtendedStatus(taskState, vmState, powerState);\n      }\n      \n      public T fromServerExtendedStatus(ServerExtendedStatus in) {\n         return this\n                  .taskState(in.getTaskState())\n                  .vmState(in.getVmState())\n                  .powerState(in.getPowerState());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   @Named(\"OS-EXT-STS:task_state\")\n   private final String taskState;\n   @Named(\"OS-EXT-STS:vm_state\")\n   private final String vmState;\n   @Named(\"OS-EXT-STS:power_state\")\n   private final int powerState;\n\n   @ConstructorProperties({\n      \"OS-EXT-STS:task_state\", \"OS-EXT-STS:vm_state\", \"OS-EXT-STS:power_state\"\n   })\n   protected ServerExtendedStatus(@Nullable String taskState, @Nullable String vmState, int powerState) {\n      this.taskState = taskState;\n      this.vmState = vmState;\n      this.powerState = powerState;\n   }\n\n   @Nullable\n   public String getTaskState() {\n      return this.taskState;\n   }\n\n   @Nullable\n   public String getVmState() {\n      return this.vmState;\n   }\n\n   public int getPowerState() {\n      return this.powerState;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(taskState, vmState, powerState);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      ServerExtendedStatus that = ServerExtendedStatus.class.cast(obj);\n      return Objects.equal(this.taskState, that.taskState)\n               && Objects.equal(this.vmState, that.vmState)\n               && Objects.equal(this.powerState, that.powerState);\n   }\n   \n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"taskState\", taskState).add(\"vmState\", vmState).add(\"powerState\", powerState);\n   }\n   \n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/ServerWithSecurityGroups.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.Resource;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Multimap;\n\n/**\n * Extended server returned by ServerWithSecurityGroupsApi\n * \n * @see <a href=\n\"http://docs.openstack.org/api/openstack-compute/1.1/content/Get_Server_Details-d1e2623.html\"\n/>\n*/\npublic class ServerWithSecurityGroups extends Server {\n\n   public static Builder<?> builder() { \n      return new ConcreteBuilder();\n   }\n   \n   public Builder<?> toBuilder() { \n      return new ConcreteBuilder().fromServerWithSecurityGroups(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> extends Server.Builder<T>  {\n      protected Set<String> securityGroupNames = ImmutableSet.of();\n   \n      /** \n       * @see ServerWithSecurityGroups#getSecurityGroupNames()\n       */\n      public T securityGroupNames(Set<String> securityGroupNames) {\n         this.securityGroupNames = ImmutableSet.copyOf(checkNotNull(securityGroupNames, \"securityGroupNames\"));      \n         return self();\n      }\n\n      public T securityGroupNames(String... in) {\n         return securityGroupNames(ImmutableSet.copyOf(in));\n      }\n\n      public ServerWithSecurityGroups build() {\n         return new ServerWithSecurityGroups(id, name, links, uuid, tenantId, userId, updated, created, hostId,\n               accessIPv4, accessIPv6, status, image, flavor, keyName, configDrive, addresses,\n               metadata, extendedStatus, extendedAttributes, diskConfig, securityGroupNames, availabilityZone);\n      }\n      \n      public T fromServerWithSecurityGroups(ServerWithSecurityGroups in) {\n         return super.fromServer(in)\n                  .securityGroupNames(in.getSecurityGroupNames());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   @Named(\"security_groups\")\n   private final Set<String> securityGroupNames;\n\n   @ConstructorProperties({\"id\", \"name\", \"links\", \"uuid\", \"tenant_id\", \"user_id\", \"updated\", \"created\", \"hostId\", \"accessIPv4\", \"accessIPv6\", \"status\", \"image\", \"flavor\", \"key_name\", \"config_drive\", \"addresses\", \"metadata\", \"extendedStatus\", \"extendedAttributes\", \"OS-DCF:diskConfig\", \"security_groups\", \"OS-EXT-AZ:availability_zone\"})\n   protected ServerWithSecurityGroups(String id, @Nullable String name, Set<Link> links, @Nullable String uuid,\n                                      String tenantId, String userId, Date updated, Date created, @Nullable String hostId,\n                                      @Nullable String accessIPv4, @Nullable String accessIPv6, Server.Status status, Resource image,\n                                      Resource flavor, @Nullable String keyName, @Nullable String configDrive,\n                                      Multimap<String, Address> addresses, Map<String, String> metadata, \n                                      @Nullable ServerExtendedStatus extendedStatus, @Nullable ServerExtendedAttributes extendedAttributes,\n                                      @Nullable String diskConfig, Set<String> securityGroupNames, @Nullable String availabilityZone) {\n      super(id, name, links, uuid, tenantId, userId, updated, created, hostId, accessIPv4, accessIPv6, status, image, flavor, keyName, configDrive, addresses, metadata, extendedStatus, extendedAttributes, diskConfig, availabilityZone);\n      this.securityGroupNames = ImmutableSet.copyOf(checkNotNull(securityGroupNames, \"securityGroupNames\"));      \n   }\n\n   public Set<String> getSecurityGroupNames() {\n      return this.securityGroupNames;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(securityGroupNames);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      ServerWithSecurityGroups that = ServerWithSecurityGroups.class.cast(obj);\n      return super.equals(that) && Objects.equal(this.securityGroupNames, that.securityGroupNames);\n   }\n   \n   protected ToStringHelper string() {\n      return super.string()\n            .add(\"securityGroupNames\", securityGroupNames);\n   }\n   \n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/SimpleServerUsage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Information the SimpleTenantUsage extension return data about each Server\n * \n*/\npublic class SimpleServerUsage {\n\n   /**\n    */\n   public static enum Status {\n      \n      UNRECOGNIZED, ACTIVE;\n      \n      public String value() {\n      return name();\n      }\n      \n      public static Status fromValue(String v) {\n      try {\n      return valueOf(v.toUpperCase());\n      } catch (IllegalArgumentException e) {\n      return UNRECOGNIZED;\n      }\n      }\n      \n   }\n\n   public static Builder<?> builder() { \n      return new ConcreteBuilder();\n   }\n   \n   public Builder<?> toBuilder() { \n      return new ConcreteBuilder().fromSimpleServerUsage(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>>  {\n      protected abstract T self();\n\n      protected String instanceName;\n      protected double hours;\n      protected double flavorMemoryMb;\n      protected double flavorLocalGb;\n      protected double flavorVcpus;\n      protected String tenantId;\n      protected String flavorName;\n      protected Date instanceCreated;\n      protected Date instanceTerminated;\n      protected SimpleServerUsage.Status instanceStatus;\n      protected long uptime;\n   \n      /** \n       * @see SimpleServerUsage#getInstanceName()\n       */\n      public T instanceName(String instanceName) {\n         this.instanceName = instanceName;\n         return self();\n      }\n\n      /** \n       * @see SimpleServerUsage#getHours()\n       */\n      public T hours(double hours) {\n         this.hours = hours;\n         return self();\n      }\n\n      /** \n       * @see SimpleServerUsage#getFlavorMemoryMb()\n       */\n      public T flavorMemoryMb(double flavorMemoryMb) {\n         this.flavorMemoryMb = flavorMemoryMb;\n         return self();\n      }\n\n      /** \n       * @see SimpleServerUsage#getFlavorLocalGb()\n       */\n      public T flavorLocalGb(double flavorLocalGb) {\n         this.flavorLocalGb = flavorLocalGb;\n         return self();\n      }\n\n      /** \n       * @see SimpleServerUsage#getFlavorVcpus()\n       */\n      public T flavorVcpus(double flavorVcpus) {\n         this.flavorVcpus = flavorVcpus;\n         return self();\n      }\n\n      /** \n       * @see SimpleServerUsage#getTenantId()\n       */\n      public T tenantId(String tenantId) {\n         this.tenantId = tenantId;\n         return self();\n      }\n\n      /** \n       * @see SimpleServerUsage#getFlavorName()\n       */\n      public T flavorName(String flavorName) {\n         this.flavorName = flavorName;\n         return self();\n      }\n\n      /** \n       * @see SimpleServerUsage#getInstanceCreated()\n       */\n      public T instanceCreated(Date instanceCreated) {\n         this.instanceCreated = instanceCreated;\n         return self();\n      }\n\n      /** \n       * @see SimpleServerUsage#getInstanceTerminated()\n       */\n      public T instanceTerminated(Date instanceTerminated) {\n         this.instanceTerminated = instanceTerminated;\n         return self();\n      }\n\n      /** \n       * @see SimpleServerUsage#getInstanceStatus()\n       */\n      public T instanceStatus(SimpleServerUsage.Status instanceStatus) {\n         this.instanceStatus = instanceStatus;\n         return self();\n      }\n\n      /** \n       * @see SimpleServerUsage#getUptime()\n       */\n      public T uptime(long uptime) {\n         this.uptime = uptime;\n         return self();\n      }\n\n      public SimpleServerUsage build() {\n         return new SimpleServerUsage(instanceName, hours, flavorMemoryMb, flavorLocalGb, flavorVcpus, tenantId, flavorName, instanceCreated, instanceTerminated, instanceStatus, uptime);\n      }\n      \n      public T fromSimpleServerUsage(SimpleServerUsage in) {\n         return this\n                  .instanceName(in.getInstanceName())\n                  .hours(in.getHours())\n                  .flavorMemoryMb(in.getFlavorMemoryMb())\n                  .flavorLocalGb(in.getFlavorLocalGb())\n                  .flavorVcpus(in.getFlavorVcpus())\n                  .tenantId(in.getTenantId())\n                  .flavorName(in.getFlavorName())\n                  .instanceCreated(in.getInstanceCreated())\n                  .instanceTerminated(in.getInstanceTerminated())\n                  .instanceStatus(in.getInstanceStatus())\n                  .uptime(in.getUptime());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   @Named(\"name\")\n   private final String instanceName;\n   private final double hours;\n   @Named(\"memory_mb\")\n   private final double flavorMemoryMb;\n   @Named(\"local_gb\")\n   private final double flavorLocalGb;\n   @Named(\"vcpus\")\n   private final double flavorVcpus;\n   @Named(\"tenant_id\")\n   private final String tenantId;\n   @Named(\"flavor\")\n   private final String flavorName;\n   @Named(\"started_at\")\n   private final Date instanceCreated;\n   @Named(\"ended_at\")\n   private final Date instanceTerminated;\n   @Named(\"state\")\n   private final SimpleServerUsage.Status instanceStatus;\n   private final long uptime;\n\n   @ConstructorProperties({\n      \"name\", \"hours\", \"memory_mb\", \"local_gb\", \"vcpus\", \"tenant_id\", \"flavor\", \"started_at\", \"ended_at\", \"state\", \"uptime\"\n   })\n   protected SimpleServerUsage(String instanceName, double hours, double flavorMemoryMb, double flavorLocalGb, double flavorVcpus, String tenantId, String flavorName, Date instanceCreated, @Nullable Date instanceTerminated, SimpleServerUsage.Status instanceStatus, long uptime) {\n      this.instanceName = checkNotNull(instanceName, \"instanceName\");\n      this.hours = hours;\n      this.flavorMemoryMb = flavorMemoryMb;\n      this.flavorLocalGb = flavorLocalGb;\n      this.flavorVcpus = flavorVcpus;\n      this.tenantId = checkNotNull(tenantId, \"tenantId\");\n      this.flavorName = checkNotNull(flavorName, \"flavorName\");\n      this.instanceCreated = checkNotNull(instanceCreated, \"instanceCreated\");\n      this.instanceTerminated = instanceTerminated;\n      this.instanceStatus = checkNotNull(instanceStatus, \"instanceStatus\");\n      this.uptime = uptime;\n   }\n\n   public String getInstanceName() {\n      return this.instanceName;\n   }\n\n   public double getHours() {\n      return this.hours;\n   }\n\n   public double getFlavorMemoryMb() {\n      return this.flavorMemoryMb;\n   }\n\n   public double getFlavorLocalGb() {\n      return this.flavorLocalGb;\n   }\n\n   public double getFlavorVcpus() {\n      return this.flavorVcpus;\n   }\n\n   public String getTenantId() {\n      return this.tenantId;\n   }\n\n   public String getFlavorName() {\n      return this.flavorName;\n   }\n\n   public Date getInstanceCreated() {\n      return this.instanceCreated;\n   }\n\n   @Nullable\n   public Date getInstanceTerminated() {\n      return this.instanceTerminated;\n   }\n\n   public SimpleServerUsage.Status getInstanceStatus() {\n      return this.instanceStatus;\n   }\n\n   public long getUptime() {\n      return this.uptime;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(instanceName, hours, flavorMemoryMb, flavorLocalGb, flavorVcpus, tenantId, flavorName, instanceCreated, instanceTerminated, instanceStatus, uptime);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      SimpleServerUsage that = SimpleServerUsage.class.cast(obj);\n      return Objects.equal(this.instanceName, that.instanceName)\n               && Objects.equal(this.hours, that.hours)\n               && Objects.equal(this.flavorMemoryMb, that.flavorMemoryMb)\n               && Objects.equal(this.flavorLocalGb, that.flavorLocalGb)\n               && Objects.equal(this.flavorVcpus, that.flavorVcpus)\n               && Objects.equal(this.tenantId, that.tenantId)\n               && Objects.equal(this.flavorName, that.flavorName)\n               && Objects.equal(this.instanceCreated, that.instanceCreated)\n               && Objects.equal(this.instanceTerminated, that.instanceTerminated)\n               && Objects.equal(this.instanceStatus, that.instanceStatus)\n               && Objects.equal(this.uptime, that.uptime);\n   }\n   \n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"instanceName\", instanceName).add(\"hours\", hours).add(\"flavorMemoryMb\", flavorMemoryMb).add(\"flavorLocalGb\", flavorLocalGb).add(\"flavorVcpus\", flavorVcpus).add(\"tenantId\", tenantId).add(\"flavorName\", flavorName).add(\"instanceCreated\", instanceCreated).add(\"instanceTerminated\", instanceTerminated).add(\"instanceStatus\", instanceStatus).add(\"uptime\", uptime);\n   }\n   \n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/SimpleTenantUsage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\nimport java.util.Set;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Information the SimpleTenantUsage extension returns data about each tenant\n * \n*/\npublic class SimpleTenantUsage {\n\n   public static Builder<?> builder() { \n      return new ConcreteBuilder();\n   }\n   \n   public Builder<?> toBuilder() { \n      return new ConcreteBuilder().fromSimpleTenantUsage(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>>  {\n      protected abstract T self();\n\n      protected String tenantId;\n      protected double totalLocalGbUsage;\n      protected double totalVcpusUsage;\n      protected double totalMemoryMbUsage;\n      protected double totalHours;\n      protected Date start;\n      protected Date stop;\n      protected Set<SimpleServerUsage> serverUsages = ImmutableSet.of();\n   \n      /** \n       * @see SimpleTenantUsage#getTenantId()\n       */\n      public T tenantId(String tenantId) {\n         this.tenantId = tenantId;\n         return self();\n      }\n\n      /** \n       * @see SimpleTenantUsage#getTotalLocalGbUsage()\n       */\n      public T totalLocalGbUsage(double totalLocalGbUsage) {\n         this.totalLocalGbUsage = totalLocalGbUsage;\n         return self();\n      }\n\n      /** \n       * @see SimpleTenantUsage#getTotalVcpusUsage()\n       */\n      public T totalVcpusUsage(double totalVcpusUsage) {\n         this.totalVcpusUsage = totalVcpusUsage;\n         return self();\n      }\n\n      /** \n       * @see SimpleTenantUsage#getTotalMemoryMbUsage()\n       */\n      public T totalMemoryMbUsage(double totalMemoryMbUsage) {\n         this.totalMemoryMbUsage = totalMemoryMbUsage;\n         return self();\n      }\n\n      /** \n       * @see SimpleTenantUsage#getTotalHours()\n       */\n      public T totalHours(double totalHours) {\n         this.totalHours = totalHours;\n         return self();\n      }\n\n      /** \n       * @see SimpleTenantUsage#getStart()\n       */\n      public T start(Date start) {\n         this.start = start;\n         return self();\n      }\n\n      /** \n       * @see SimpleTenantUsage#getStop()\n       */\n      public T stop(Date stop) {\n         this.stop = stop;\n         return self();\n      }\n\n      /** \n       * @see SimpleTenantUsage#getServerUsages()\n       */\n      public T serverUsages(Set<SimpleServerUsage> serverUsages) {\n         this.serverUsages = ImmutableSet.copyOf(checkNotNull(serverUsages, \"serverUsages\"));      \n         return self();\n      }\n\n      public T serverUsages(SimpleServerUsage... in) {\n         return serverUsages(ImmutableSet.copyOf(in));\n      }\n\n      public SimpleTenantUsage build() {\n         return new SimpleTenantUsage(tenantId, totalLocalGbUsage, totalVcpusUsage, totalMemoryMbUsage, totalHours, start, stop, serverUsages);\n      }\n      \n      public T fromSimpleTenantUsage(SimpleTenantUsage in) {\n         return this\n                  .tenantId(in.getTenantId())\n                  .totalLocalGbUsage(in.getTotalLocalGbUsage())\n                  .totalVcpusUsage(in.getTotalVcpusUsage())\n                  .totalMemoryMbUsage(in.getTotalMemoryMbUsage())\n                  .totalHours(in.getTotalHours())\n                  .start(in.getStart())\n                  .stop(in.getStop())\n                  .serverUsages(in.getServerUsages());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   @Named(\"tenant_id\")\n   private final String tenantId;\n   @Named(\"total_local_gb_usage\")\n   private final double totalLocalGbUsage;\n   @Named(\"total_vcpus_usage\")\n   private final double totalVcpusUsage;\n   @Named(\"total_memory_mb_usage\")\n   private final double totalMemoryMbUsage;\n   @Named(\"total_hours\")\n   private final double totalHours;\n   private final Date start;\n   private final Date stop;\n   @Named(\"server_usages\")\n   private final Set<SimpleServerUsage> serverUsages;\n\n   @ConstructorProperties({\n      \"tenant_id\", \"total_local_gb_usage\", \"total_vcpus_usage\", \"total_memory_mb_usage\", \"total_hours\", \"start\", \"stop\", \"server_usages\"\n   })\n   protected SimpleTenantUsage(String tenantId, double totalLocalGbUsage, double totalVcpusUsage, double totalMemoryMbUsage, double totalHours, @Nullable Date start, @Nullable Date stop, @Nullable Set<SimpleServerUsage> serverUsages) {\n      this.tenantId = checkNotNull(tenantId, \"tenantId\");\n      this.totalLocalGbUsage = totalLocalGbUsage;\n      this.totalVcpusUsage = totalVcpusUsage;\n      this.totalMemoryMbUsage = totalMemoryMbUsage;\n      this.totalHours = totalHours;\n      this.start = start;\n      this.stop = stop;\n      this.serverUsages = serverUsages == null ? ImmutableSet.<SimpleServerUsage>of() : ImmutableSet.copyOf(serverUsages);      \n   }\n\n   public String getTenantId() {\n      return this.tenantId;\n   }\n\n   public double getTotalLocalGbUsage() {\n      return this.totalLocalGbUsage;\n   }\n\n   public double getTotalVcpusUsage() {\n      return this.totalVcpusUsage;\n   }\n\n   public double getTotalMemoryMbUsage() {\n      return this.totalMemoryMbUsage;\n   }\n\n   public double getTotalHours() {\n      return this.totalHours;\n   }\n\n   @Nullable\n   public Date getStart() {\n      return this.start;\n   }\n\n   @Nullable\n   public Date getStop() {\n      return this.stop;\n   }\n\n   public Set<SimpleServerUsage> getServerUsages() {\n      return this.serverUsages;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(tenantId, totalLocalGbUsage, totalVcpusUsage, totalMemoryMbUsage, totalHours, start, stop, serverUsages);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      SimpleTenantUsage that = SimpleTenantUsage.class.cast(obj);\n      return Objects.equal(this.tenantId, that.tenantId)\n               && Objects.equal(this.totalLocalGbUsage, that.totalLocalGbUsage)\n               && Objects.equal(this.totalVcpusUsage, that.totalVcpusUsage)\n               && Objects.equal(this.totalMemoryMbUsage, that.totalMemoryMbUsage)\n               && Objects.equal(this.totalHours, that.totalHours)\n               && Objects.equal(this.start, that.start)\n               && Objects.equal(this.stop, that.stop)\n               && Objects.equal(this.serverUsages, that.serverUsages);\n   }\n   \n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"tenantId\", tenantId).add(\"totalLocalGbUsage\", totalLocalGbUsage).add(\"totalVcpusUsage\", totalVcpusUsage).add(\"totalMemoryMbUsage\", totalMemoryMbUsage).add(\"totalHours\", totalHours).add(\"start\", start).add(\"stop\", stop).add(\"serverUsages\", serverUsages);\n   }\n   \n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/TenantIdAndName.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Named;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Class TenantIdAndName\n * \n*/\npublic class TenantIdAndName {\n\n   public static Builder<?> builder() { \n      return new ConcreteBuilder();\n   }\n   \n   public Builder<?> toBuilder() { \n      return new ConcreteBuilder().fromTenantIdAndName(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>>  {\n      protected abstract T self();\n\n      protected String tenantId;\n      protected String name;\n   \n      /** \n       * @see TenantIdAndName#getTenantId()\n       */\n      public T tenantId(String tenantId) {\n         this.tenantId = tenantId;\n         return self();\n      }\n\n      /** \n       * @see TenantIdAndName#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      public TenantIdAndName build() {\n         return new TenantIdAndName(tenantId, name);\n      }\n      \n      public T fromTenantIdAndName(TenantIdAndName in) {\n         return this\n                  .tenantId(in.getTenantId())\n                  .name(in.getName());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   @Named(\"tenant_id\")\n   private final String tenantId;\n   private final String name;\n\n   @ConstructorProperties({\n      \"tenant_id\", \"name\"\n   })\n   protected TenantIdAndName(String tenantId, String name) {\n      this.tenantId = checkNotNull(tenantId, \"tenantId\");\n      this.name = checkNotNull(name, \"name\");\n   }\n\n   public String getTenantId() {\n      return this.tenantId;\n   }\n\n   public String getName() {\n      return this.name;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(tenantId, name);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      TenantIdAndName that = TenantIdAndName.class.cast(obj);\n      return Objects.equal(this.tenantId, that.tenantId)\n               && Objects.equal(this.name, that.name);\n   }\n   \n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"tenantId\", tenantId).add(\"name\", name);\n   }\n   \n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/VirtualInterface.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Named;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Represents a Virtual Interface (VIF)\n * \n * @see org.jclouds.openstack.nova.v2_0.extensions.VirtualInterfaceApi\n*/\npublic class VirtualInterface {\n\n   public static Builder<?> builder() { \n      return new ConcreteBuilder();\n   }\n   \n   public Builder<?> toBuilder() { \n      return new ConcreteBuilder().fromVirtualInterface(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>>  {\n      protected abstract T self();\n\n      protected String id;\n      protected String macAddress;\n   \n      /** \n       * @see VirtualInterface#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /** \n       * @see VirtualInterface#getMacAddress()\n       */\n      public T macAddress(String macAddress) {\n         this.macAddress = macAddress;\n         return self();\n      }\n\n      public VirtualInterface build() {\n         return new VirtualInterface(id, macAddress);\n      }\n      \n      public T fromVirtualInterface(VirtualInterface in) {\n         return this\n                  .id(in.getId())\n                  .macAddress(in.getMacAddress());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   @Named(\"mac_address\")\n   private final String macAddress;\n\n   @ConstructorProperties({\n      \"id\", \"mac_address\"\n   })\n   protected VirtualInterface(String id, String macAddress) {\n      this.id = checkNotNull(id, \"id\");\n      this.macAddress = checkNotNull(macAddress, \"macAddress\");\n   }\n\n   public String getId() {\n      return this.id;\n   }\n\n   public String getMacAddress() {\n      return this.macAddress;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, macAddress);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      VirtualInterface that = VirtualInterface.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n               && Objects.equal(this.macAddress, that.macAddress);\n   }\n   \n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"macAddress\", macAddress);\n   }\n   \n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/Volume.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.CaseFormat;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * An OpenStack Nova Volume\n*/\npublic class Volume {\n\n   /**\n    */\n   public static enum Status {\n      CREATING, AVAILABLE, IN_USE, DELETING, ERROR, UNRECOGNIZED;\n      public String value() {\n      return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_HYPHEN, name());\n      }\n      \n      @Override\n      public String toString() {\n      return value();\n      }\n      \n      public static Status fromValue(String status) {\n      try {\n      return valueOf(CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_UNDERSCORE, checkNotNull(status, \"status\")));\n      } catch (IllegalArgumentException e) {\n      return UNRECOGNIZED;\n      }\n      }\n   }\n\n   public static Builder<?> builder() { \n      return new ConcreteBuilder();\n   }\n   \n   public Builder<?> toBuilder() { \n      return new ConcreteBuilder().fromVolume(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>>  {\n      protected abstract T self();\n\n      protected String id;\n      protected Volume.Status status;\n      protected int size;\n      protected String zone;\n      protected Date created;\n      protected Set<VolumeAttachment> attachments = ImmutableSet.of();\n      protected String volumeType;\n      protected String snapshotId;\n      protected String name;\n      protected String description;\n      protected Map<String, String> metadata = ImmutableMap.of();\n   \n      /** \n       * @see Volume#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /** \n       * @see Volume#getStatus()\n       */\n      public T status(Volume.Status status) {\n         this.status = status;\n         return self();\n      }\n\n      /** \n       * @see Volume#getSize()\n       */\n      public T size(int size) {\n         this.size = size;\n         return self();\n      }\n\n      /** \n       * @see Volume#getZone()\n       */\n      public T zone(String zone) {\n         this.zone = zone;\n         return self();\n      }\n\n      /** \n       * @see Volume#getCreated()\n       */\n      public T created(Date created) {\n         this.created = created;\n         return self();\n      }\n\n      /** \n       * @see Volume#getAttachments()\n       */\n      public T attachments(Set<VolumeAttachment> attachments) {\n         this.attachments = ImmutableSet.copyOf(checkNotNull(attachments, \"attachments\"));      \n         return self();\n      }\n\n      public T attachments(VolumeAttachment... in) {\n         return attachments(ImmutableSet.copyOf(in));\n      }\n\n      /** \n       * @see Volume#getVolumeType()\n       */\n      public T volumeType(String volumeType) {\n         this.volumeType = volumeType;\n         return self();\n      }\n\n      /** \n       * @see Volume#getSnapshotId()\n       */\n      public T snapshotId(String snapshotId) {\n         this.snapshotId = snapshotId;\n         return self();\n      }\n\n      /** \n       * @see Volume#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /** \n       * @see Volume#getDescription()\n       */\n      public T description(String description) {\n         this.description = description;\n         return self();\n      }\n\n      /** \n       * @see Volume#getMetadata()\n       */\n      public T metadata(Map<String, String> metadata) {\n         this.metadata = ImmutableMap.copyOf(checkNotNull(metadata, \"metadata\"));     \n         return self();\n      }\n\n      public Volume build() {\n         return new Volume(id, status, size, zone, created, attachments, volumeType, snapshotId, name, description, metadata);\n      }\n      \n      public T fromVolume(Volume in) {\n         return this\n                  .id(in.getId())\n                  .status(in.getStatus())\n                  .size(in.getSize())\n                  .zone(in.getZone())\n                  .created(in.getCreated())\n                  .attachments(in.getAttachments())\n                  .volumeType(in.getVolumeType())\n                  .snapshotId(in.getSnapshotId())\n                  .name(in.getName())\n                  .description(in.getDescription())\n                  .metadata(in.getMetadata());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final Volume.Status status;\n   private final int size;\n   @Named(\"availabilityZone\")\n   private final String zone;\n   @Named(\"createdAt\")\n   private final Date created;\n   private final Set<VolumeAttachment> attachments;\n   private final String volumeType;\n   private final String snapshotId;\n   @Named(\"displayName\")\n   private final String name;\n   @Named(\"displayDescription\")\n   private final String description;\n   private final Map<String, String> metadata;\n\n   @ConstructorProperties({\n      \"id\", \"status\", \"size\", \"availabilityZone\", \"createdAt\", \"attachments\", \"volumeType\", \"snapshotId\", \"displayName\", \"displayDescription\", \"metadata\"\n   })\n   protected Volume(String id, Volume.Status status, int size, String zone, Date created, @Nullable Set<VolumeAttachment> attachments, @Nullable String volumeType, @Nullable String snapshotId, @Nullable String name, @Nullable String description, @Nullable Map<String, String> metadata) {\n      this.id = checkNotNull(id, \"id\");\n      this.status = checkNotNull(status, \"status\");\n      this.size = size;\n      this.zone = checkNotNull(zone, \"zone\");\n      this.created = checkNotNull(created, \"created\");\n      this.attachments = attachments == null ? ImmutableSet.<VolumeAttachment>of() : ImmutableSet.copyOf(attachments);      \n      this.volumeType = volumeType;\n      this.snapshotId = snapshotId;\n      this.name = name;\n      this.description = description;\n      this.metadata = metadata == null ? ImmutableMap.<String, String>of() : ImmutableMap.copyOf(metadata);      \n   }\n\n   /**\n    * @return the id of this volume\n    */\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * @return the status of this volume\n    */\n   public Volume.Status getStatus() {\n      return this.status;\n   }\n\n   /**\n    * @return the size in GB of this volume\n    */\n   public int getSize() {\n      return this.size;\n   }\n\n   /**\n    * @return the availabilityZone containing this volume\n    */\n   public String getZone() {\n      return this.zone;\n   }\n\n   /**\n    * @return the time this volume was created\n    */\n   public Date getCreated() {\n      return this.created;\n   }\n\n   /**\n    * @return the set of attachments (to Servers)\n    */\n   public Set<VolumeAttachment> getAttachments() {\n      return this.attachments;\n   }\n\n   /**\n    * @return the type of this volume\n    */\n   @Nullable\n   public String getVolumeType() {\n      return this.volumeType;\n   }\n\n   @Nullable\n   public String getSnapshotId() {\n      return this.snapshotId;\n   }\n\n   /**\n    * @return the name of this volume - as displayed in the openstack console\n    */\n   @Nullable\n   public String getName() {\n      return this.name;\n   }\n\n   /**\n    * @return the description of this volume - as displayed in the openstack console\n    */\n   @Nullable\n   public String getDescription() {\n      return this.description;\n   }\n\n   public Map<String, String> getMetadata() {\n      return this.metadata;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, status, size, zone, created, attachments, volumeType, snapshotId, name, description, metadata);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Volume that = Volume.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n               && Objects.equal(this.status, that.status)\n               && Objects.equal(this.size, that.size)\n               && Objects.equal(this.zone, that.zone)\n               && Objects.equal(this.created, that.created)\n               && Objects.equal(this.attachments, that.attachments)\n               && Objects.equal(this.volumeType, that.volumeType)\n               && Objects.equal(this.snapshotId, that.snapshotId)\n               && Objects.equal(this.name, that.name)\n               && Objects.equal(this.description, that.description)\n               && Objects.equal(this.metadata, that.metadata);\n   }\n   \n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"status\", status).add(\"size\", size).add(\"zone\", zone).add(\"created\", created).add(\"attachments\", attachments).add(\"volumeType\", volumeType).add(\"snapshotId\", snapshotId).add(\"name\", name).add(\"description\", description).add(\"metadata\", metadata);\n   }\n   \n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/VolumeAttachment.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * An OpenStack Nova Volume Attachment (describes how Volumes are attached to Servers)\n*/\npublic class VolumeAttachment {\n\n   public static Builder<?> builder() { \n      return new ConcreteBuilder();\n   }\n   \n   public Builder<?> toBuilder() { \n      return new ConcreteBuilder().fromVolumeAttachment(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>>  {\n      protected abstract T self();\n\n      protected String id;\n      protected String volumeId;\n      protected String serverId;\n      protected String device;\n   \n      /** \n       * @see VolumeAttachment#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /** \n       * @see VolumeAttachment#getVolumeId()\n       */\n      public T volumeId(String volumeId) {\n         this.volumeId = volumeId;\n         return self();\n      }\n\n      /** \n       * @see VolumeAttachment#getServerId()\n       */\n      public T serverId(String serverId) {\n         this.serverId = serverId;\n         return self();\n      }\n\n      /** \n       * @see VolumeAttachment#getDevice()\n       */\n      public T device(String device) {\n         this.device = device;\n         return self();\n      }\n\n      public VolumeAttachment build() {\n         return new VolumeAttachment(id, volumeId, serverId, device);\n      }\n      \n      public T fromVolumeAttachment(VolumeAttachment in) {\n         return this\n                  .id(in.getId())\n                  .volumeId(in.getVolumeId())\n                  .serverId(in.getServerId())\n                  .device(in.getDevice());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final String volumeId;\n   private final String serverId;\n   private final String device;\n\n   @ConstructorProperties({\n      \"id\", \"volumeId\", \"serverId\", \"device\"\n   })\n   protected VolumeAttachment(String id, String volumeId, @Nullable String serverId, @Nullable String device) {\n      this.id = checkNotNull(id, \"id\");\n      this.volumeId = checkNotNull(volumeId, \"volumeId\");\n      this.serverId = serverId;\n      this.device = device;\n   }\n\n   /**\n    * @return the attachment id (typically the same as #getVolumeId())\n    */\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * @return the id of the volume attached\n    */\n   public String getVolumeId() {\n      return this.volumeId;\n   }\n\n   /**\n    * @return the id of the server the volume is attached to\n    */\n   @Nullable\n   public String getServerId() {\n      return this.serverId;\n   }\n\n   /**\n    * @return the device name (e.g. \"/dev/vdc\")\n    */\n   @Nullable\n   public String getDevice() {\n      return this.device;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, volumeId, serverId, device);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      VolumeAttachment that = VolumeAttachment.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n               && Objects.equal(this.volumeId, that.volumeId)\n               && Objects.equal(this.serverId, that.serverId)\n               && Objects.equal(this.device, that.device);\n   }\n   \n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"volumeId\", volumeId).add(\"serverId\", serverId).add(\"device\", device);\n   }\n   \n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/VolumeSnapshot.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * An OpenStack Nova Volume Snapshot\n*/\npublic class VolumeSnapshot {\n\n   public static Builder<?> builder() { \n      return new ConcreteBuilder();\n   }\n   \n   public Builder<?> toBuilder() { \n      return new ConcreteBuilder().fromVolumeSnapshot(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>>  {\n      protected abstract T self();\n\n      protected String id;\n      protected String volumeId;\n      protected Volume.Status status;\n      protected int size;\n      protected Date created;\n      protected String name;\n      protected String description;\n   \n      /** \n       * @see VolumeSnapshot#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /** \n       * @see VolumeSnapshot#getVolumeId()\n       */\n      public T volumeId(String volumeId) {\n         this.volumeId = volumeId;\n         return self();\n      }\n\n      /** \n       * @see VolumeSnapshot#getStatus()\n       */\n      public T status(Volume.Status status) {\n         this.status = status;\n         return self();\n      }\n\n      /** \n       * @see VolumeSnapshot#getSize()\n       */\n      public T size(int size) {\n         this.size = size;\n         return self();\n      }\n\n      /** \n       * @see VolumeSnapshot#getCreated()\n       */\n      public T created(Date created) {\n         this.created = created;\n         return self();\n      }\n\n      /** \n       * @see VolumeSnapshot#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /** \n       * @see VolumeSnapshot#getDescription()\n       */\n      public T description(String description) {\n         this.description = description;\n         return self();\n      }\n\n      public VolumeSnapshot build() {\n         return new VolumeSnapshot(id, volumeId, status, size, created, name, description);\n      }\n      \n      public T fromVolumeSnapshot(VolumeSnapshot in) {\n         return this\n                  .id(in.getId())\n                  .volumeId(in.getVolumeId())\n                  .status(in.getStatus())\n                  .size(in.getSize())\n                  .created(in.getCreated())\n                  .name(in.getName())\n                  .description(in.getDescription());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final String volumeId;\n   private final Volume.Status status;\n   private final int size;\n   @Named(\"createdAt\")\n   private final Date created;\n   @Named(\"displayName\")\n   private final String name;\n   @Named(\"displayDescription\")\n   private final String description;\n\n   @ConstructorProperties({\n      \"id\", \"volumeId\", \"status\", \"size\", \"createdAt\", \"displayName\", \"displayDescription\"\n   })\n   protected VolumeSnapshot(String id, String volumeId, Volume.Status status, int size, @Nullable Date created, @Nullable String name, @Nullable String description) {\n      this.id = checkNotNull(id, \"id\");\n      this.volumeId = checkNotNull(volumeId, \"volumeId\");\n      this.status = checkNotNull(status, \"status\");\n      this.size = size;\n      this.created = created;\n      this.name = name;\n      this.description = description;\n   }\n\n   /**\n    * @return the id of this snapshot\n    */\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * @return the id of the Volume this snapshot was taken from\n    */\n   public String getVolumeId() {\n      return this.volumeId;\n   }\n\n   /**\n    * @return the status of this snapshot\n    */\n   public Volume.Status getStatus() {\n      return this.status;\n   }\n\n   /**\n    * @return the size in GB of the volume this snapshot was taken from\n    */\n   public int getSize() {\n      return this.size;\n   }\n\n   /**\n    * @return the data the snapshot was taken\n    */\n   @Nullable\n   public Date getCreated() {\n      return this.created;\n   }\n\n   /**\n    * @return the name of this snapshot - as displayed in the openstack console\n    */\n   @Nullable\n   public String getName() {\n      return this.name;\n   }\n\n   /**\n    * @return the description of this snapshot - as displayed in the openstack console\n    */\n   @Nullable\n   public String getDescription() {\n      return this.description;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, volumeId, status, size, created, name, description);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      VolumeSnapshot that = VolumeSnapshot.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n               && Objects.equal(this.volumeId, that.volumeId)\n               && Objects.equal(this.status, that.status)\n               && Objects.equal(this.size, that.size)\n               && Objects.equal(this.created, that.created)\n               && Objects.equal(this.name, that.name)\n               && Objects.equal(this.description, that.description);\n   }\n   \n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"volumeId\", volumeId).add(\"status\", status).add(\"size\", size).add(\"created\", created).add(\"name\", name).add(\"description\", description);\n   }\n   \n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/VolumeType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\nimport java.util.Map;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Volume Type used in the Volume Type Extension for Nova\n * \n * @see org.jclouds.openstack.nova.v2_0.extensions.VolumeTypeApi\n*/\npublic class VolumeType {\n\n   public static Builder<?> builder() { \n      return new ConcreteBuilder();\n   }\n   \n   public Builder<?> toBuilder() { \n      return new ConcreteBuilder().fromVolumeType(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>>  {\n      protected abstract T self();\n\n      protected String id;\n      protected String name;\n      protected Date created;\n      protected Date updated;\n      protected Map<String, String> extraSpecs = ImmutableMap.of();\n   \n      /** \n       * @see VolumeType#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /** \n       * @see VolumeType#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /** \n       * @see VolumeType#getCreated()\n       */\n      public T created(Date created) {\n         this.created = created;\n         return self();\n      }\n\n      /** \n       * @see VolumeType#getUpdated()\n       */\n      public T updated(Date updated) {\n         this.updated = updated;\n         return self();\n      }\n\n      /** \n       * @see VolumeType#getExtraSpecs()\n       */\n      public T extraSpecs(Map<String, String> extraSpecs) {\n         this.extraSpecs = ImmutableMap.copyOf(checkNotNull(extraSpecs, \"extraSpecs\"));     \n         return self();\n      }\n\n      public VolumeType build() {\n         return new VolumeType(id, name, created, updated, extraSpecs);\n      }\n      \n      public T fromVolumeType(VolumeType in) {\n         return this\n                  .id(in.getId())\n                  .name(in.getName())\n                  .created(in.getCreated())\n                  .updated(in.getUpdated().orNull())\n                  .extraSpecs(in.getExtraSpecs());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final String name;\n   @Named(\"created_at\")\n   private final Date created;\n   @Named(\"updated_at\")\n   private final Optional<Date> updated;\n   @Named(\"extra_specs\")\n   private final Map<String, String> extraSpecs;\n\n   @ConstructorProperties({\n      \"id\", \"name\", \"created_at\", \"updated_at\", \"extra_specs\"\n   })\n   protected VolumeType(String id, String name, Date created, @Nullable Date updated, Map<String, String> extraSpecs) {\n      this.id = checkNotNull(id, \"id\");\n      this.name = checkNotNull(name, \"name\");\n      this.created = checkNotNull(created, \"created\");\n      this.updated = Optional.fromNullable(updated);\n      this.extraSpecs = ImmutableMap.copyOf(checkNotNull(extraSpecs, \"extraSpecs\"));     \n   }\n\n   public String getId() {\n      return this.id;\n   }\n\n   public String getName() {\n      return this.name;\n   }\n\n   /**\n    * The Date the VolumeType was created\n    */\n   public Date getCreated() {\n      return this.created;\n   }\n\n   /**\n    * The Date the VolumeType as last updated - absent if no updates have taken place\n    */\n   public Optional<Date> getUpdated() {\n      return this.updated;\n   }\n\n   public Map<String, String> getExtraSpecs() {\n      return this.extraSpecs;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, name, created, updated, extraSpecs);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      VolumeType that = VolumeType.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n               && Objects.equal(this.name, that.name)\n               && Objects.equal(this.created, that.created)\n               && Objects.equal(this.updated, that.updated)\n               && Objects.equal(this.extraSpecs, that.extraSpecs);\n   }\n   \n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"name\", name).add(\"created\", created).add(\"updated\", updated).add(\"extraSpecs\", extraSpecs);\n   }\n   \n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/regionscoped/AvailabilityZone.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain.regionscoped;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.gson.annotations.SerializedName;\n\nimport java.beans.ConstructorProperties;\n\n/**\n * Availability Zone which shows name and state\n */\npublic class AvailabilityZone {\n\n   @SerializedName(\"zoneName\")\n   private final String name;\n   private final ZoneState state;\n\n   @ConstructorProperties({\"zoneName\", \"zoneState\"})\n   protected AvailabilityZone(String name, ZoneState state) {\n      this.name = name;\n      this.state = state;\n   }\n\n   public String getName() {\n      return name;\n   }\n\n   public ZoneState getState() {\n      return state;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(name, state);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this != obj)\n         return false;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      AvailabilityZone that = AvailabilityZone.class.cast(obj);\n      return Objects.equal(this.name, that.name) && Objects.equal(this.state, that.state);\n   }\n\n   protected MoreObjects.ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"name\", name)\n            .add(\"state\", state);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/regionscoped/AvailabilityZoneDetails.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain.regionscoped;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.gson.annotations.SerializedName;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\nimport java.util.Map;\n\n/**\n * Availability Zone which show name, state and host information.\n *\n * Host information includes the host name and the services running on the hosts.\n */\npublic class AvailabilityZoneDetails {\n\n   public static final class HostService {\n\n      private final boolean available;\n      private final boolean active;\n      @SerializedName(\"updated_at\")\n      private final Date updated;\n\n      @ConstructorProperties({\"available\", \"active\", \"updated_at\"})\n      protected HostService(boolean available, boolean active, Date updated) {\n         this.available = available;\n         this.active = active;\n         this.updated = updated;\n      }\n\n      public boolean isAvailable() { return available; }\n\n      public boolean isActive() { return active; }\n\n      public Date getUpdated() { return updated; }\n\n      protected MoreObjects.ToStringHelper string() {\n         return MoreObjects.toStringHelper(this)\n               .add(\"available\", available)\n               .add(\"active\", active)\n               .add(\"updated\", updated);\n      }\n\n      @Override\n      public String toString() {\n         return string().toString();\n      }\n   }\n\n   @SerializedName(\"zoneName\")\n   private final String name;\n   private final ZoneState state;\n   private final Map<String, Map<String, HostService>> hosts;\n\n   @ConstructorProperties({\"zoneName\", \"zoneState\", \"hosts\"})\n   protected AvailabilityZoneDetails(String name, ZoneState state, Map<String, Map<String, HostService>> hosts) {\n      this.name = name;\n      this.state = state;\n      this.hosts = hosts == null ? ImmutableMap.<String, Map<String, HostService>>of() : ImmutableMap.copyOf(hosts);\n   }\n\n   public String getName() {\n      return name;\n   }\n\n   public ZoneState getState() {\n      return state;\n   }\n\n   /**\n    * @return returns a map of host name and Host service objects\n    */\n   public Map<String, Map<String, HostService>> getHosts() {\n      return this.hosts;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(name, state, hosts);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this != obj)\n         return false;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      AvailabilityZoneDetails that = AvailabilityZoneDetails.class.cast(obj);\n      return Objects.equal(this.name, that.name) && Objects.equal(this.state, that.state) && Objects.equal(this.hosts,\n            that.hosts);\n   }\n\n   protected MoreObjects.ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"name\", name)\n            .add(\"state\", state)\n            .add(\"Hosts\", hosts);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/regionscoped/FlavorInRegion.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain.regionscoped;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.openstack.nova.v2_0.domain.Flavor;\n\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\npublic class FlavorInRegion extends RegionAndId {\n   protected final Flavor flavor;\n\n   public FlavorInRegion(Flavor flavor, String regionId) {\n      super(regionId, checkNotNull(flavor, \"flavor\").getId());\n      this.flavor = flavor;\n   }\n\n   public Flavor getFlavor() {\n      return flavor;\n   }\n\n   // superclass hashCode/equals are good enough, and help us use RegionAndId and FlavorInRegion\n   // interchangeably as Map keys\n\n   @Override\n   protected ToStringHelper string() {\n      return super.string().add(\"flavor\", flavor);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/regionscoped/Hypervisor.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain.regionscoped;\n\nimport com.google.auto.value.AutoValue;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\n/**\n * Hypervisor which shows id and name\n */\n@AutoValue\npublic abstract class Hypervisor {\n\n   public abstract String getId();\n\n   @Nullable\n   public abstract String getName();\n\n   @SerializedNames({\"id\", \"hypervisor_hostname\"})\n   private static Hypervisor create(String id, String name) {\n      return new AutoValue_Hypervisor(id, name);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/regionscoped/HypervisorDetails.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain.regionscoped;\n\nimport com.google.auto.value.AutoValue;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\n/**\n * Hypervisor which shows id, name and other details\n */\n@AutoValue\npublic abstract class HypervisorDetails {\n\n   public abstract String getId();\n\n   @Nullable\n   public abstract String getName();\n\n   @Nullable\n   public abstract Integer getCurrentWorkload();\n\n   @Nullable\n   public abstract Integer getDiskAvailableLeast();\n\n   @Nullable\n   public abstract Integer getFreeDiskGb();\n\n   @Nullable\n   public abstract Integer getFreeRamMb();\n\n   public abstract String getHypervisorType();\n\n   public abstract int getHypervisorVersion();\n\n   public abstract int getLocalGb();\n\n   public abstract int getLocalGbUsed();\n\n   public abstract int getMemoryMb();\n\n   public abstract int getMemoryMbUsed();\n\n   @Nullable\n   public abstract Integer getRunningVms();\n\n   public abstract int getVcpus();\n\n   public abstract int getVcpusUsed();\n\n   @Nullable\n   public abstract String getCpuInfo();\n\n   @SerializedNames({ \"id\", \"hypervisor_hostname\", \"current_workload\", \"disk_available_least\", \"free_disk_gb\", \"free_ram_mb\", \"hypervisor_type\",\n         \"hypervisor_version\", \"local_gb\", \"local_gb_used\", \"memory_mb\", \"memory_mb_used\", \"running_vms\", \"vcpus\", \"vcpus_used\",\n         \"cpu_info\" })\n   private static HypervisorDetails create(String id, String name, int currentWorkload, int diskAvailableLeast, int freeDiskGb, int freeRamMb,\n         String hypervisorType, int hypervisorVersion, int localGb, int localGbUsed, int memoryMb, int memoryMbUsed, int runningVms,\n         int vcpus, int vcpusUsed, String cpuInfo) {\n      return new AutoValue_HypervisorDetails(id, name, currentWorkload, diskAvailableLeast, freeDiskGb, freeRamMb, hypervisorType, hypervisorVersion,\n            localGb, localGbUsed, memoryMb, memoryMbUsed, runningVms, vcpus, vcpusUsed, cpuInfo);\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/regionscoped/ImageInRegion.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain.regionscoped;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.openstack.nova.v2_0.domain.Image;\n\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\npublic class ImageInRegion extends RegionAndId {\n   protected final Image image;\n\n   public ImageInRegion(Image image, String regionId) {\n      super(regionId, checkNotNull(image, \"image\").getId());\n      this.image = image;\n   }\n\n   public Image getImage() {\n      return image;\n   }\n\n   // superclass hashCode/equals are good enough, and help us use RegionAndId and ImageInRegion\n   // interchangeably as Map keys\n\n   @Override\n   protected ToStringHelper string() {\n      return super.string().add(\"image\", image);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/regionscoped/NeutronSecurityGroupInRegion.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain.regionscoped;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Collection;\nimport java.util.Map;\n\nimport org.jclouds.openstack.neutron.v2.domain.SecurityGroup;\nimport org.jclouds.openstack.nova.v2_0.domain.TenantIdAndName;\n\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.HashMultimap;\nimport com.google.common.collect.Multimap;\n\npublic class NeutronSecurityGroupInRegion extends RegionAndName {\n   protected final SecurityGroup securityGroup;\n\n   protected final Multimap<TenantIdAndName, SecurityGroup> groupsByName;\n\n   public NeutronSecurityGroupInRegion(SecurityGroup securityGroup, String regionId, Iterable<SecurityGroup> allGroupsInRegion) {\n      super(regionId, checkNotNull(securityGroup, \"securityGroup\").getName());\n      this.securityGroup = securityGroup;\n      this.groupsByName = HashMultimap.create();\n      for (SecurityGroup groupInRegion : allGroupsInRegion) {\n         final TenantIdAndName tenantIdAndName = TenantIdAndName.builder()\n            .tenantId(groupInRegion.getTenantId())\n            .name(groupInRegion.getName())\n            .build();\n         this.groupsByName.put(tenantIdAndName, groupInRegion);\n      }\n   }\n\n   public SecurityGroup getSecurityGroup() {\n      return securityGroup;\n   }\n\n   /**\n    * Returns a map of group {@link TenantIdAndName}s to groups.\n    *\n    * The returned value is a collection, to take into account the possibility that certain clouds\n    * may permit duplicate group names.\n    *\n    * @return The map of names to (collections of) groups.\n    */\n   public Map<TenantIdAndName, Collection<SecurityGroup>> getGroupsByName() {\n       return groupsByName.asMap();\n   }\n\n   // superclass hashCode/equals are good enough, and help us use RegionAndName and SecurityGroupInRegion\n   // interchangeably as Map keys\n\n   @Override\n   protected ToStringHelper string() {\n      return super.string()\n          .add(\"securityGroup\", securityGroup)\n          .add(\"groupsByName\", groupsByName);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/regionscoped/RegionAndId.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain.regionscoped;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.Iterables;\n\npublic class RegionAndId {\n\n   public static RegionAndId fromSlashEncoded(String id) {\n      Iterable<String> parts = Splitter.on('/').split(checkNotNull(id, \"id\"));\n      checkArgument(Iterables.size(parts) == 2, \"id must be in format regionId/id\");\n      return new RegionAndId(Iterables.get(parts, 0), Iterables.get(parts, 1));\n   }\n\n   public static RegionAndId fromRegionAndId(String regionId, String id) {\n      return new RegionAndId(regionId, id);\n   }\n\n   private static String slashEncodeRegionAndId(String regionId, String id) {\n      return checkNotNull(regionId, \"regionId\") + \"/\" + checkNotNull(id, \"id\");\n   }\n\n   public String slashEncode() {\n      return slashEncodeRegionAndId(regionId, id);\n   }\n\n   protected final String regionId;\n   protected final String id;\n\n   protected RegionAndId(String regionId, String id) {\n      this.regionId = checkNotNull(regionId, \"regionId\");\n      this.id = checkNotNull(id, \"id\");\n   }\n\n   public String getRegion() {\n      return regionId;\n   }\n\n   public String getId() {\n      return id;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(regionId, id);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      RegionAndId other = (RegionAndId) obj;\n      return Objects.equal(regionId, other.regionId) && Objects.equal(id, other.id);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).add(\"regionId\", regionId).add(\"id\", id);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/regionscoped/RegionAndName.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain.regionscoped;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.Iterables;\n\n/**\n * Helpful when looking for resources by region and name\n */\npublic class RegionAndName {\n\n   public static final Function<RegionAndName, String> NAME_FUNCTION = new Function<RegionAndName, String>() {\n      @Override\n      public String apply(RegionAndName input) {\n         return input.getName();\n      }\n   };\n\n   public static final Function<RegionAndName, String> REGION_FUNCTION = new Function<RegionAndName, String>() {\n      @Override\n      public String apply(RegionAndName input) {\n         return input.getRegion();\n      }\n   };\n\n   public static RegionAndName fromSlashEncoded(String name) {\n      Iterable<String> parts = Splitter.on('/').split(checkNotNull(name, \"name\"));\n      checkArgument(Iterables.size(parts) == 2, \"name must be in format regionId/name\");\n      return new RegionAndName(Iterables.get(parts, 0), Iterables.get(parts, 1));\n   }\n\n   public static RegionAndName fromRegionAndName(String regionId, String name) {\n      return new RegionAndName(regionId, name);\n   }\n\n   private static String slashEncodeRegionAndName(String regionId, String name) {\n      return checkNotNull(regionId, \"regionId\") + \"/\" + checkNotNull(name, \"name\");\n   }\n\n   public String slashEncode() {\n      return slashEncodeRegionAndName(regionId, name);\n   }\n\n   protected final String regionId;\n   protected final String name;\n\n   protected RegionAndName(String regionId, String name) {\n      this.regionId = checkNotNull(regionId, \"regionId\");\n      this.name = checkNotNull(name, \"name\");\n   }\n\n   public String getRegion() {\n      return regionId;\n   }\n\n   public String getName() {\n      return name;\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o)\n         return true;\n      if (o == null || getClass() != o.getClass())\n         return false;\n      RegionAndName that = RegionAndName.class.cast(o);\n      return equal(this.regionId, that.regionId) && equal(this.name, that.name);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(regionId, name);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).add(\"regionId\", regionId).add(\"name\", name);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/regionscoped/RegionSecurityGroupNameAndPorts.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain.regionscoped;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Set;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableSet;\n\npublic class RegionSecurityGroupNameAndPorts extends RegionAndName {\n   protected final Set<Integer> ports;\n\n   public RegionSecurityGroupNameAndPorts(String regionId, String name, Iterable<Integer> ports) {\n      super(regionId, name);\n      this.ports = ImmutableSet.<Integer> copyOf(checkNotNull(ports, \"ports\"));\n   }\n\n   public Set<Integer> getPorts() {\n      return ports;\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o)\n         return true;\n      if (o == null || getClass() != o.getClass())\n         return false;\n      RegionSecurityGroupNameAndPorts that = RegionSecurityGroupNameAndPorts.class.cast(o);\n      return super.equals(that) && equal(this.ports, that.ports);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(super.hashCode(), ports);\n   }\n\n   @Override\n   protected ToStringHelper string() {\n      return super.string().add(\"ports\", ports);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/regionscoped/SecurityGroupInRegion.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain.regionscoped;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Collection;\nimport java.util.Map;\n\nimport org.jclouds.openstack.nova.v2_0.domain.SecurityGroup;\nimport org.jclouds.openstack.nova.v2_0.domain.TenantIdAndName;\n\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.HashMultimap;\nimport com.google.common.collect.Multimap;\n\npublic class SecurityGroupInRegion extends RegionAndName {\n   protected final SecurityGroup securityGroup;\n\n   protected final Multimap<TenantIdAndName, SecurityGroup> groupsByName;\n\n   public SecurityGroupInRegion(SecurityGroup securityGroup, String regionId, Iterable<SecurityGroup> allGroupsInRegion) {\n      super(regionId, checkNotNull(securityGroup, \"securityGroup\").getName());\n      this.securityGroup = securityGroup;\n      this.groupsByName = HashMultimap.create();\n      for (SecurityGroup groupInRegion : allGroupsInRegion) {\n         final TenantIdAndName tenantIdAndName = TenantIdAndName.builder()\n            .tenantId(groupInRegion.getTenantId())\n            .name(groupInRegion.getName())\n            .build();\n         this.groupsByName.put(tenantIdAndName, groupInRegion);\n      }\n   }\n\n   public SecurityGroup getSecurityGroup() {\n      return securityGroup;\n   }\n\n   /**\n    * Returns a map of group {@link TenantIdAndName}s to groups.\n    *\n    * The returned value is a collection, to take into account the possibility that certain clouds\n    * may permit duplicate group names.\n    *\n    * @return The map of names to (collections of) groups.\n    */\n   public Map<TenantIdAndName, Collection<SecurityGroup>> getGroupsByName() {\n       return groupsByName.asMap();\n   }\n\n   // superclass hashCode/equals are good enough, and help us use RegionAndName and SecurityGroupInRegion\n   // interchangeably as Map keys\n\n   @Override\n   protected ToStringHelper string() {\n      return super.string()\n          .add(\"securityGroup\", securityGroup)\n          .add(\"groupsByName\", groupsByName);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/regionscoped/ServerInRegion.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain.regionscoped;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.openstack.nova.v2_0.domain.Server;\n\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\npublic class ServerInRegion extends RegionAndId {\n   protected final Server server;\n\n   public ServerInRegion(Server server, String regionId) {\n      super(regionId, checkNotNull(server, \"server\").getId());\n      this.server = server;\n   }\n\n   public Server getServer() {\n      return server;\n   }\n\n   // superclass hashCode/equals are good enough, and help us use RegionAndId and ServerInRegion\n   // interchangeably as Map keys\n\n   @Override\n   protected ToStringHelper string() {\n      return super.string().add(\"server\", server);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/regionscoped/ZoneState.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain.regionscoped;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\npublic class ZoneState {\n\n   private final boolean available;\n\n   protected ZoneState(boolean available) { this.available = available; }\n\n   public boolean isAvailable() { return this.available; }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(available);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this != obj) return false;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      ZoneState that = ZoneState.class.cast(obj);\n      return Objects.equal(this.available, that.available);\n   }\n\n   protected MoreObjects.ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"available\", available);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/zonescoped/AvailabilityZone.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain.zonescoped;\n\nimport java.beans.ConstructorProperties;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.gson.annotations.SerializedName;\n\n/**\n * @deprecated This package has been replaced with {@link org.jclouds.openstack.nova.v2_0.domain.regionscoped}.\n *             Please use {@link org.jclouds.openstack.nova.v2_0.domain.regionscoped.AvailabilityZone AvailabilityZone}\n *             instead. To be removed in jclouds 2.0.\n */\n@Deprecated\npublic class AvailabilityZone {\n\n   @SerializedName(\"zoneName\")\n   private final String name;\n   private final ZoneState state;\n\n   @ConstructorProperties({\"zoneName\", \"zoneState\"})\n   protected AvailabilityZone(String name, ZoneState state) {\n      this.name = name;\n      this.state = state;\n   }\n\n   public String getName() {\n      return name;\n   }\n\n   public ZoneState getState() {\n      return state;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(name, state);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this != obj) return false;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      AvailabilityZone that = AvailabilityZone.class.cast(obj);\n      return Objects.equal(this.name, that.name) && Objects.equal(this.state, that.state);\n   }\n\n   protected MoreObjects.ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"name\", name)\n            .add(\"state\", state);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/zonescoped/FlavorInRegion.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain.zonescoped;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.openstack.nova.v2_0.domain.Flavor;\n\n/**\n * @deprecated This package has been replaced with {@link org.jclouds.openstack.nova.v2_0.domain.regionscoped}.\n *             Please use {@link org.jclouds.openstack.nova.v2_0.domain.regionscoped.FlavorInRegion FlavorInRegion}\n *             instead. To be removed in jclouds 2.0.\n */\n@Deprecated\npublic class FlavorInRegion extends RegionAndId {\n   protected final Flavor flavor;\n\n   public FlavorInRegion(Flavor flavor, String regionId) {\n      super(regionId, checkNotNull(flavor, \"image\").getId());\n      this.flavor = flavor;\n   }\n\n   public Flavor getFlavor() {\n      return flavor;\n   }\n\n   // superclass hashCode/equals are good enough, and help us use RegionAndId and FlavorInRegion\n   // interchangeably as Map keys\n\n   @Override\n   public String toString() {\n      return \"[flavor=\" + flavor + \", regionId=\" + regionId + \"]\";\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/zonescoped/ImageInRegion.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain.zonescoped;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.openstack.nova.v2_0.domain.Image;\n\n/**\n * @deprecated This package has been replaced with {@link org.jclouds.openstack.nova.v2_0.domain.regionscoped}.\n *             Please use {@link org.jclouds.openstack.nova.v2_0.domain.regionscoped.ImageInRegion ImageInRegion}\n *             instead. To be removed in jclouds 2.0.\n */\n@Deprecated\npublic class ImageInRegion extends RegionAndId {\n   protected final Image image;\n\n   public ImageInRegion(Image image, String regionId) {\n      super(regionId, checkNotNull(image, \"image\").getId());\n      this.image = image;\n   }\n\n   public Image getImage() {\n      return image;\n   }\n\n   // superclass hashCode/equals are good enough, and help us use RegionAndId and ImageInRegion\n   // interchangeably as Map keys\n\n   @Override\n   public String toString() {\n      return \"[image=\" + image + \", regionId=\" + regionId + \"]\";\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/zonescoped/RegionAndId.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain.zonescoped;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.Iterables;\n\n/**\n * @deprecated This package has been replaced with {@link org.jclouds.openstack.nova.v2_0.domain.regionscoped}.\n *             Please use {@link org.jclouds.openstack.nova.v2_0.domain.regionscoped.RegionAndId RegionAndId}\n *             instead. To be removed in jclouds 2.0.\n */\n@Deprecated\npublic class RegionAndId {\n   public static RegionAndId fromSlashEncoded(String id) {\n      Iterable<String> parts = Splitter.on('/').split(checkNotNull(id, \"id\"));\n      checkArgument(Iterables.size(parts) == 2, \"id must be in format regionId/id\");\n      return new RegionAndId(Iterables.get(parts, 0), Iterables.get(parts, 1));\n   }\n\n   public static RegionAndId fromRegionAndId(String regionId, String id) {\n      return new RegionAndId(regionId, id);\n   }\n\n   private static String slashEncodeRegionAndId(String regionId, String id) {\n      return checkNotNull(regionId, \"regionId\") + \"/\" + checkNotNull(id, \"id\");\n   }\n\n   public String slashEncode() {\n      return slashEncodeRegionAndId(regionId, id);\n   }\n\n   protected final String regionId;\n   protected final String id;\n\n   protected RegionAndId(String regionId, String id) {\n      this.regionId = checkNotNull(regionId, \"regionId\");\n      this.id = checkNotNull(id, \"id\");\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(regionId, id);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      RegionAndId other = (RegionAndId) obj;\n      return Objects.equal(regionId, other.regionId) && Objects.equal(id, other.id);\n   }\n\n   public String getRegion() {\n      return regionId;\n   }\n\n   public String getId() {\n      return id;\n   }\n\n   @Override\n   public String toString() {\n      return \"[regionId=\" + regionId + \", id=\" + id + \"]\";\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/zonescoped/RegionAndName.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain.zonescoped;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.Iterables;\n\n/**\n * Helpful when looking for resources by region and name\n *\n * @deprecated This package has been replaced with {@link org.jclouds.openstack.nova.v2_0.domain.regionscoped}.\n *             Please use {@link org.jclouds.openstack.nova.v2_0.domain.regionscoped.RegionAndName RegionAndName}\n *             instead. To be removed in jclouds 2.0.\n */\n@Deprecated\npublic class RegionAndName {\n\n   public static final Function<RegionAndName, String> NAME_FUNCTION = new Function<RegionAndName, String>() {\n\n      @Override\n      public String apply(RegionAndName input) {\n         return input.getName();\n      }\n\n   };\n\n   public static final Function<RegionAndName, String> REGION_FUNCTION = new Function<RegionAndName, String>() {\n\n      @Override\n      public String apply(RegionAndName input) {\n         return input.getRegion();\n      }\n\n   };\n\n   public static RegionAndName fromSlashEncoded(String name) {\n      Iterable<String> parts = Splitter.on('/').split(checkNotNull(name, \"name\"));\n      checkArgument(Iterables.size(parts) == 2, \"name must be in format regionId/name\");\n      return new RegionAndName(Iterables.get(parts, 0), Iterables.get(parts, 1));\n   }\n\n   public static RegionAndName fromRegionAndName(String regionId, String name) {\n      return new RegionAndName(regionId, name);\n   }\n\n   private static String slashEncodeRegionAndName(String regionId, String name) {\n      return checkNotNull(regionId, \"regionId\") + \"/\" + checkNotNull(name, \"name\");\n   }\n\n   public String slashEncode() {\n      return slashEncodeRegionAndName(regionId, name);\n   }\n\n   protected final String regionId;\n   protected final String name;\n\n   protected RegionAndName(String regionId, String name) {\n      this.regionId = checkNotNull(regionId, \"regionId\");\n      this.name = checkNotNull(name, \"name\");\n   }\n\n   public String getRegion() {\n      return regionId;\n   }\n\n   public String getName() {\n      return name;\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o)\n         return true;\n      if (o == null || getClass() != o.getClass())\n         return false;\n      RegionAndName that = RegionAndName.class.cast(o);\n      return equal(this.regionId, that.regionId) && equal(this.name, that.name);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(regionId, name);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(\"\").add(\"regionId\", regionId).add(\"name\", name);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/zonescoped/RegionSecurityGroupNameAndPorts.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain.zonescoped;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Set;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * @deprecated This package has been replaced with {@link org.jclouds.openstack.nova.v2_0.domain.regionscoped}.\n *             Please use {@link org.jclouds.openstack.nova.v2_0.domain.regionscoped.RegionSecurityGroupNameAndPorts RegionSecurityGroupNameAndPorts}\n *             instead. To be removed in jclouds 2.0.\n */\n@Deprecated\npublic class RegionSecurityGroupNameAndPorts extends RegionAndName {\n   protected final Set<Integer> ports;\n\n   public RegionSecurityGroupNameAndPorts(String regionId, String name, Iterable<Integer> ports) {\n      super(regionId, name);\n      this.ports = ImmutableSet.<Integer> copyOf(checkNotNull(ports, \"ports\"));\n   }\n\n   public Set<Integer> getPorts() {\n      return ports;\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o)\n         return true;\n      if (o == null || getClass() != o.getClass())\n         return false;\n      RegionSecurityGroupNameAndPorts that = RegionSecurityGroupNameAndPorts.class.cast(o);\n      return super.equals(that) && equal(this.ports, that.ports);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(super.hashCode(), ports);\n   }\n\n   @Override\n   public ToStringHelper string() {\n      return super.string().add(\"ports\", ports);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/zonescoped/SecurityGroupInRegion.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain.zonescoped;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.openstack.nova.v2_0.domain.SecurityGroup;\n\n/**\n * @deprecated This package has been replaced with {@link org.jclouds.openstack.nova.v2_0.domain.regionscoped}.\n *             Please use {@link org.jclouds.openstack.nova.v2_0.domain.regionscoped.SecurityGroupInRegion SecurityGroupInRegion}\n *             instead. To be removed in jclouds 2.0.\n */\n@Deprecated\npublic class SecurityGroupInRegion extends RegionAndName {\n   protected final SecurityGroup securityGroup;\n\n   public SecurityGroupInRegion(SecurityGroup securityGroup, String regionId) {\n      super(regionId, checkNotNull(securityGroup, \"securityGroup\").getName());\n      this.securityGroup = securityGroup;\n   }\n\n   public SecurityGroup getSecurityGroup() {\n      return securityGroup;\n   }\n\n   // superclass hashCode/equals are good enough, and help us use RegionAndName and ServerInRegion\n   // interchangeably as Map keys\n\n   @Override\n   public String toString() {\n      return \"[securityGroup=\" + securityGroup + \", regionId=\" + regionId + \"]\";\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/zonescoped/ServerInRegion.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain.zonescoped;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.openstack.nova.v2_0.domain.Server;\n\n/**\n * @deprecated This package has been replaced with {@link org.jclouds.openstack.nova.v2_0.domain.regionscoped}.\n *             Please use {@link org.jclouds.openstack.nova.v2_0.domain.regionscoped.ServerInRegion ServerInRegion}\n *             instead. To be removed in jclouds 2.0.\n */\n@Deprecated\npublic class ServerInRegion extends RegionAndId {\n   protected final Server server;\n\n   public ServerInRegion(Server server, String regionId) {\n      super(regionId, checkNotNull(server, \"server\").getId());\n      this.server = server;\n   }\n\n   public Server getServer() {\n      return server;\n   }\n\n   // superclass hashCode/equals are good enough, and help us use RegionAndId and ServerInRegion\n   // interchangeably as Map keys\n\n   @Override\n   public String toString() {\n      return \"[server=\" + server + \", regionId=\" + regionId + \"]\";\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/zonescoped/ZoneState.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.domain.zonescoped;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\n/**\n * @deprecated This package has been replaced with {@link org.jclouds.openstack.nova.v2_0.domain.regionscoped}.\n *             Please use {@link org.jclouds.openstack.nova.v2_0.domain.regionscoped.ZoneState ZoneState}\n *             instead. To be removed in jclouds 2.0.\n */\n@Deprecated\npublic class ZoneState {\n\n   private final boolean available;\n\n   protected ZoneState(boolean available) {\n      this.available = available;\n   }\n\n   public boolean available() {\n      return this.available;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(available);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this != obj) return false;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      ZoneState that = ZoneState.class.cast(obj);\n      return Objects.equal(this.available, that.available);\n   }\n\n   protected MoreObjects.ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"available\", available);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/AttachInterfaceApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.nova.v2_0.domain.InterfaceAttachment;\nimport org.jclouds.openstack.v2_0.ServiceType;\nimport org.jclouds.openstack.v2_0.services.Extension;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.collect.FluentIterable;\n\n/**\n * Provides access to the OpenStack Compute (Nova) Attach Interfaces API.\n */\n@Beta\n@Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.ATTACH_INTERFACES,\n      name = ExtensionNames.ATTACH_INTERFACES, alias = ExtensionAliases.ATTACH_INTERFACES)\n@RequestFilters(AuthenticateRequest.class)\n@Consumes(MediaType.APPLICATION_JSON)\n@Path(\"/servers\")\npublic interface AttachInterfaceApi {\n\n   /**\n    * Returns list of port interfaces for given server\n    *\n    * @param serverId\n    *           The Server ID\n    * @return list of port interfaces for given server\n    */\n   @Named(\"attachInterface:list\")\n   @GET\n   @Path(\"/{serverId}/os-interface\")\n   @SelectJson(\"interfaceAttachments\")\n   @Fallback(Fallbacks.EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<InterfaceAttachment> list(@PathParam(\"serverId\") String serverId);\n\n   /**\n    * Returns information about a specified port interface for given server\n    *\n    * @param serverId\n    *           The Server ID\n    * @param attachmentId\n    *           The interface ID\n    * @return information about a specified port interface for given server\n    */\n   @Named(\"attachInterface:get\")\n   @GET\n   @Path(\"/{serverId}/os-interface/{attachmentId}\")\n   @SelectJson(\"interfaceAttachment\")\n   @Fallback(Fallbacks.NullOnNotFoundOr404.class)\n   @Nullable\n   InterfaceAttachment get(@PathParam(\"serverId\") String serverId, @PathParam(\"attachmentId\") String attachmentId);\n\n   /**\n    * Creates a new port interface and associate with the given port\n    *\n    * @param portId\n    *           The port ID\n    * @return newly created port interface\n    */\n   @Named(\"attachInterface:create\")\n   @POST\n   @Path(\"/{serverId}/os-interface\")\n   @SelectJson(\"interfaceAttachment\")\n   @Payload(\"%7B\\\"interfaceAttachment\\\":%7B\\\"port_id\\\":\\\"{portId}\\\"%7D%7D\")\n   @Produces(MediaType.APPLICATION_JSON)\n   InterfaceAttachment create(@PathParam(\"serverId\") String serverId, @PayloadParam(\"portId\") String portId);\n\n   /**\n    * Deletes a port interface for given server, return true if successful,\n    * false if server or interface not found\n    *\n    * @param serverId\n    *           The Server ID\n    * @param attachmentId\n    *           The interface ID\n    * @return true if successful, false if server or interface not found\n    */\n   @Named(\"attachInterface:delete\")\n   @DELETE\n   @Path(\"/{serverId}/os-interface/{attachmentId}\")\n   @Fallback(Fallbacks.FalseOnNotFoundOr404.class)\n   boolean delete(@PathParam(\"serverId\") String serverId, @PathParam(\"attachmentId\") String attachmentId);\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/AvailabilityZoneApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyFluentIterableOnNotFoundOr404;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.AvailabilityZone;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.AvailabilityZoneDetails;\nimport org.jclouds.openstack.v2_0.ServiceType;\nimport org.jclouds.openstack.v2_0.services.Extension;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.collect.FluentIterable;\n\n/**\n * Provides access to the OpenStack Compute (Nova) Availability Zone Extension API.\n */\n@Beta\n@Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.AVAILABILITY_ZONE,\n      name = ExtensionNames.AVAILABILITY_ZONE, alias = ExtensionAliases.AVAILABILITY_ZONE)\n@RequestFilters(AuthenticateRequest.class)\n@Consumes(MediaType.APPLICATION_JSON)\n@Path(\"/os-availability-zone\")\npublic interface AvailabilityZoneApi {\n\n   /**\n    * @return all availability zones\n    * @deprecated Please use {@link #listAvailabilityZones()} instead. To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   @Named(\"availabilityZone:list\")\n   @GET\n   @SelectJson(\"availabilityZoneInfo\")\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<org.jclouds.openstack.nova.v2_0.domain.zonescoped.AvailabilityZone> list();\n\n   @Named(\"availabilityZone:list\")\n   @GET\n   @SelectJson(\"availabilityZoneInfo\")\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<AvailabilityZone> listAvailabilityZones();\n\n   @Named(\"availabilityZone:list\")\n   @GET\n   @Path(\"/detail\")\n   @SelectJson(\"availabilityZoneInfo\")\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<AvailabilityZoneDetails> listInDetail();\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/ConsolesApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.fallbacks.MapHttp4xxCodesToExceptions;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.nova.v2_0.binders.BindConsoleToJsonPayload;\nimport org.jclouds.openstack.nova.v2_0.domain.Console;\nimport org.jclouds.openstack.v2_0.ServiceType;\nimport org.jclouds.openstack.v2_0.services.Extension;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\nimport com.google.common.annotations.Beta;\n\n/**\n * Provides access to the OpenStack Compute (Nova) Consoles Extension API.\n * <p/>\n *\n */\n@Beta\n@Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.CONSOLES,\n      name = ExtensionNames.CONSOLES, alias = ExtensionAliases.CONSOLES)\n@RequestFilters(AuthenticateRequest.class)\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface ConsolesApi {\n   /**\n    * Gets the specified server Console.\n    *\n    * @param serverId Server id\n    * @param type see {@link Console.Type}\n    * @return a Console object containing the console url and type.\n    */\n   @Named(\"consoles:getConsole\")\n   @POST\n   @Path(\"/servers/{serverId}/action\")\n   @SelectJson(\"console\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @Fallback(MapHttp4xxCodesToExceptions.class)\n   @MapBinder(BindConsoleToJsonPayload.class)\n   Console getConsole(@PathParam(\"serverId\") String serverId, @PayloadParam(\"type\") Console.Type type);\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/ExtensionAliases.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\n/**\n * OpenStack Nova Extension Aliases\n */\npublic final class ExtensionAliases {\n   public static final String FLOATING_IPS = \"os-floating-ips\";\n   public static final String ATTACH_INTERFACES = \"os-attach-interfaces\";\n   public static final String AVAILABILITY_ZONE = \"os-availability-zone\";\n   public static final String CONSOLES = \"os-consoles\";\n   public static final String CREATESERVEREXT = \"os-create-server-ext\";\n   public static final String FLAVOR_EXTRA_SPECS = \"os-flavor-extra-specs\";\n   public static final String HOST_ADMINISTRATION = \"os-hosts\";\n   public static final String HOST_AGGREGATE = \"os-aggregates\";\n   public static final String HYPERVISORS = \"os-hypervisors\";\n   public static final String KEYPAIRS = \"os-keypairs\";\n   public static final String QUOTAS = \"os-quota-sets\";\n   public static final String SECURITY_GROUPS = \"os-security-groups\";\n   public static final String SERVER_ADMIN = \"os-admin-actions\";\n   public static final String VIRTUAL_INTERFACES = \"os-virtual-interfaces\";\n   public static final String SIMPLE_TENANT_USAGE = \"os-simple-tenant-usage\";\n   public static final String VOLUME_ATTACHMENT = \"os-volumes\";\n   public static final String FLOATING_IP_POOLS = \"os-floating-ip-pools\";\n   public static final String VOLUMES = \"os-volumes\";\n\n   private ExtensionAliases() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/ExtensionNames.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\n/**\n * OpenStack Nova Extension Names\n */\npublic final class ExtensionNames {\n   public static final String FLOATING_IPS = \"FloatingIps\";\n   public static final String ATTACH_INTERFACES = \"AttachInterfaces\";\n   public static final String AVAILABILITY_ZONE = \"AvailabilityZone\";\n   public static final String CONSOLES = \"Consoles\";\n   public static final String CREATESERVEREXT = \"Createserverext\";\n   public static final String FLAVOR_EXTRA_SPECS = \"FlavorExtraSpecs\";\n   public static final String HOST_ADMINISTRATION = \"Hosts\";\n   public static final String HOST_AGGREGATE = \"Aggregates\";\n   public static final String HYPERVISORS = \"Hypervisors\";\n   public static final String KEYPAIRS = \"Keypairs\";\n   public static final String QUOTAS = \"Quotas\";\n   public static final String SECURITY_GROUPS = \"SecurityGroups\";\n   public static final String SERVER_ADMIN = \"AdminActions\";\n   public static final String VIRTUAL_INTERFACES = \"VirtualInterfaces\";\n   public static final String SIMPLE_TENANT_USAGE = \"SimpleTenantUsage\";\n   public static final String VOLUME_ATTACHMENT = \"VolumeAttachmentUpdate\";\n   public static final String FLOATING_IP_POOLS = \"FloatingIpPools\";\n   public static final String VOLUMES = \"Volumes\";\n\n   private ExtensionNames() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/ExtensionNamespaces.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\n/**\n * OpenStack Nova Extension Namespaces\n */\npublic final class ExtensionNamespaces {\n   /**\n    * Keypair Support\n    */\n   public static final String KEYPAIRS = \"http://docs.openstack.org/ext/keypairs/api/v1.1\";\n   /**\n    * Volumes support\n    */\n   public static final String VOLUMES = \"http://docs.openstack.org/ext/volumes/api/v1.1\";\n   /**\n    * Volume attachment support\n    */\n   public static final String VOLUME_ATTACHMENTS = \"http://docs.openstack.org/compute/ext/os-volume-attachment-update/api/v2\";\n   /**\n    * Volume types support\n    */\n   public static final String VOLUME_TYPES = \"http://docs.openstack.org/ext/volume_types/api/v1.1\";\n   /**\n    * Security group support\n    */\n   public static final String SECURITY_GROUPS = \"http://docs.openstack.org/ext/securitygroups/api/v1.1\";\n   /**\n    * Floating IPs support\n    */\n   public static final String FLOATING_IPS = \"http://docs.openstack.org/ext/floating_ips/api/v1.1\";\n   /**\n    * Multiple network support\n    */\n   public static final String MULTINIC = \"http://docs.openstack.org/ext/multinic/api/v1.1\";\n   /**\n    * Host administration\n    */\n   public static final String HOSTS = \"http://docs.openstack.org/ext/hosts/api/v1.1\";\n   /**\n    * Quotas management support\n    */\n   public static final String QUOTAS = \"http://docs.openstack.org/ext/quotas-sets/api/v1.1\";\n   /**\n    * Instance type (flavor) extra specs\n    */\n   public static final String FLAVOR_EXTRA_SPECS = \"http://docs.openstack.org/ext/flavor_extra_specs/api/v1.1\";\n   /**\n    * Provide additional data for flavors\n    */\n   public static final String FLAVOR_EXTRA_DATA = \"http://docs.openstack.org/ext/flavor_extra_data/api/v1.1\";\n   /**\n    * Virtual interface support\n    */\n   public static final String VIRTUAL_INTERFACES = \"http://docs.openstack.org/ext/virtual_interfaces/api/v1.1\";\n   /**\n    * Availability zone extensions\n    */\n   public static final String AVAILABILITY_ZONE = \"http://docs.openstack.org/compute/ext/availabilityzone/api/v1.1\";\n   /**\n    * Extended support to the Create Server v1.1 API\n    */\n   public static final String CREATESERVEREXT = \"http://docs.openstack.org/ext/createserverext/api/v1.1\";\n   /**\n    * Virtual Storage Arrays support\n    */\n   public static final String VSA = \"http://docs.openstack.org/ext/vsa/api/v1.1\";\n   /**\n    * Simple tenant usage extension\n    */\n   public static final String SIMPLE_TENANT_USAGE = \"http://docs.openstack.org/ext/os-simple-tenant-usage/api/v1.1\";\n   /**\n    * Instance rescue mode\n    */\n   public static final String RESCUE = \"http://docs.openstack.org/ext/rescue/api/v1.1\";\n   /**\n    * Admin Action extension\n    */\n   public static final String ADMIN_ACTIONS = \"http://docs.openstack.org/ext/admin-actions/api/v1.1\";\n   /**\n    * Extended Server Status extension\n    */\n   public static final String EXTENDED_STATUS = \"http://docs.openstack.org/compute/ext/extended_status/api/v1.1\";\n   /**\n    * Disk Config extension\n    */\n   public static final String DISK_CONFIG = \"http://docs.openstack.org/compute/ext/disk_config/api/v1.1\";\n   /**\n    * Aggregates extension\n    */\n   public static final String AGGREGATES = \"http://docs.openstack.org/ext/aggregates/api/v1.1\";\n   /**\n    * Consoles extension\n    */\n   public static final String CONSOLES = \"http://docs.openstack.org/compute/ext/os-consoles/api/v2\";\n   /**\n    * Block Device Mapping v2 Boot Extension\n    */\n   public static final String BLOCK_DEVICE_MAPPING_V2_BOOT =\n         \"http://docs.openstack.org/compute/ext/block_device_mapping_v2_boot/api/v2\";\n   /**\n    * Floating IP pools support\n    */\n   public static final String FLOATING_IP_POOLS = \"http://docs.openstack.org/compute/ext/floating_ip_pools/api/v1.1\";\n   /**\n    * Attach interfaces extension\n    */\n   public static final String ATTACH_INTERFACES = \"http://docs.openstack.org/compute/ext/interfaces/api/v1.1\";\n   /**\n    * Hypervisor support\n    */\n   public static final String HYPERVISORS = \"http://docs.openstack.org/compute/ext/hypervisors/api/v1.1\";\n\n   private ExtensionNamespaces() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/FlavorExtraSpecsApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport java.util.Map;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyMapOnNotFoundOr404;\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.v2_0.ServiceType;\nimport org.jclouds.openstack.v2_0.services.Extension;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.Unwrap;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport com.google.common.annotations.Beta;\n\n/**\n * Provides access to the OpenStack Compute (Nova) Flavor Extra Specs Extension API.\n *\n * @see org.jclouds.openstack.nova.v2_0.features.FlavorApi\n */\n@Beta\n@Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.FLAVOR_EXTRA_SPECS,\n      name = ExtensionNames.FLAVOR_EXTRA_SPECS, alias = ExtensionAliases.FLAVOR_EXTRA_SPECS)\n@RequestFilters(AuthenticateRequest.class)\n@Consumes(MediaType.APPLICATION_JSON)\n@Path(\"/flavors\")\npublic interface FlavorExtraSpecsApi {\n   /**\n    * Retrieves all extra specs for a flavor\n    *\n    * @return the set of extra metadata for the flavor\n    */\n   @Named(\"flavorExtraSpecs:getMetadata\")\n   @GET\n   @Path(\"/{id}/os-extra_specs\")\n   @SelectJson(\"extra_specs\")\n   @Fallback(EmptyMapOnNotFoundOr404.class)\n   Map<String, String> getMetadata(@PathParam(\"id\") String flavorId);\n\n   /**\n    * Creates or updates the extra specs for a given flavor\n    *\n    * @param flavorId   the id of the flavor to modify\n    * @param specs      the extra specs to apply\n    */\n   @Named(\"flavorExtraSpecs:updateMetadata\")\n   @POST\n   @Path(\"/{id}/os-extra_specs\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @MapBinder(BindToJsonPayload.class)\n   void updateMetadata(@PathParam(\"id\") String flavorId,\n         @PayloadParam(\"extra_specs\") Map<String, String> specs);\n\n   /**\n    * Return a single extra spec value\n    *\n    * @param flavorId   the id of the flavor to modify\n    * @param key        the extra spec key to retrieve\n    */\n   @Named(\"flavorExtraSpecs:getMetadataKey\")\n   @GET\n   @Path(\"/{id}/os-extra_specs/{key}\")\n   @Unwrap\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   String getMetadataKey(@PathParam(\"id\") String flavorId, @PathParam(\"key\") String key);\n\n   /**\n    * Creates or updates a single extra spec value\n    *\n    * @param flavorId   the id of the flavor to modify\n    * @param key        the extra spec key (when creating ensure this does not include whitespace or\n    *                   other difficult characters)\n    * @param value      the value to associate with the key\n    */\n   @Named(\"flavorExtraSpecs:updateMetadataEntry\")\n   @PUT\n   @Path(\"/{id}/os-extra_specs/{key}\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @Payload(\"%7B\\\"{key}\\\":\\\"{value}\\\"%7D\")\n   void updateMetadataEntry(@PathParam(\"id\") String flavorId,\n         @PathParam(\"key\") @PayloadParam(\"key\") String key, @PayloadParam(\"value\") String value);\n\n   /**\n    * Deletes an extra spec\n    *\n    * @param flavorId   the id of the flavor to modify\n    * @param key        the extra spec key to delete\n    */\n   @Named(\"flavorExtraSpecs:deleteMetadataKey\")\n   @DELETE\n   @Path(\"/{id}/os-extra_specs/{key}\")\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean deleteMetadataKey(@PathParam(\"id\") String flavorId, @PathParam(\"key\") String key);\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/FloatingIPApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyFluentIterableOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.nova.v2_0.domain.FloatingIP;\nimport org.jclouds.openstack.v2_0.ServiceType;\nimport org.jclouds.openstack.v2_0.services.Extension;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.collect.FluentIterable;\n\n/**\n * Provides access to the OpenStack Compute (Nova) Floating IP extension API.\n */\n@Beta\n@Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.FLOATING_IPS,\n      name = ExtensionNames.FLOATING_IPS, alias = ExtensionAliases.FLOATING_IPS)\n@RequestFilters(AuthenticateRequest.class)\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface FloatingIPApi {\n   /**\n    * Lists all Floating IP addresses\n    *\n    * @return all Floating IPs\n    */\n   @Named(\"floatingIP:list\")\n   @GET\n   @Path(\"/os-floating-ips\")\n   @SelectJson(\"floating_ips\")\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<FloatingIP> list();\n\n   /**\n    * Gets a specific Floating IP address\n    *\n    * @return all Floating IPs\n    */\n   @Named(\"floatingIP:get\")\n   @GET\n   @Path(\"/os-floating-ips/{id}\")\n   @SelectJson(\"floating_ip\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   FloatingIP get(@PathParam(\"id\") String id);\n\n   /**\n    * Allocates a Floating IP address\n    *\n    * @return a newly created FloatingIP\n    */\n   @Named(\"floatingIP:create\")\n   @POST\n   @Path(\"/os-floating-ips\")\n   @SelectJson(\"floating_ip\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @Payload(\"{}\")\n   @Nullable\n   FloatingIP create();\n\n   /**\n    * Allocates a Floating IP address from a pool\n    *\n    * @param pool\n    *         Pool to allocate IP address from\n    * @return a newly created FloatingIP\n    */\n   @Named(\"floatingIP:allocateFromPool\")\n   @POST\n   @Path(\"/os-floating-ips\")\n   @SelectJson(\"floating_ip\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @Payload(\"%7B\\\"pool\\\":\\\"{pool}\\\"%7D\")\n   @Nullable\n   FloatingIP allocateFromPool(@PayloadParam(\"pool\") String pool);\n\n   /**\n    * Deletes a Floating IP address\n    *\n    * @param id\n    *           the Floating IP id\n    */\n   @Named(\"floatingIP:delete\")\n   @DELETE\n   @Path(\"/os-floating-ips/{id}\")\n   void delete(@PathParam(\"id\") String id);\n\n   /**\n    * Adds a Floating IP address to a Server\n    *\n    * @param serverId\n    *           the server id\n    * @param address\n    *           the IP address to add\n    *\n    *           NOTE: Possibly move this to ServerApi?\n    */\n   @Named(\"floatingIP:add\")\n   @POST\n   @Path(\"/servers/{id}/action\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @Payload(\"%7B\\\"addFloatingIp\\\":%7B\\\"address\\\":\\\"{address}\\\"%7D%7D\")\n   void addToServer(@PayloadParam(\"address\") String address, @PathParam(\"id\") String serverId);\n\n   /**\n    * Removes a Floating IP address from a Server\n    *\n    * @param serverId\n    *           the server id\n    * @param address\n    *           the IP address to remove\n    *\n    *           NOTE: Possibly move this to ServerApi?\n    */\n   @Named(\"floatingIP:remove\")\n   @POST\n   @Path(\"/servers/{id}/action\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @Payload(\"%7B\\\"removeFloatingIp\\\":%7B\\\"address\\\":\\\"{address}\\\"%7D%7D\")\n   void removeFromServer(@PayloadParam(\"address\") String address, @PathParam(\"id\") String serverId);\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/FloatingIPPoolApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.nova.v2_0.domain.FloatingIPPool;\nimport org.jclouds.openstack.v2_0.ServiceType;\nimport org.jclouds.openstack.v2_0.services.Extension;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.collect.FluentIterable;\n\n@Beta\n@Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.FLOATING_IP_POOLS,\n      name = ExtensionNames.FLOATING_IP_POOLS, alias = ExtensionAliases.FLOATING_IP_POOLS)\n@Consumes(MediaType.APPLICATION_JSON)\n@Path(\"/os-floating-ip-pools\")\n@RequestFilters(AuthenticateRequest.class)\npublic interface FloatingIPPoolApi {\n\n   /**\n    * Lists all Floating IP Pools\n    *\n    * @return all Floating IP Pools\n    */\n   @GET\n   @SelectJson(\"floating_ip_pools\")\n   @Fallback(Fallbacks.EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<? extends FloatingIPPool> list();\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/HostAdministrationApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyFluentIterableOnNotFoundOr404;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.nova.v2_0.domain.Host;\nimport org.jclouds.openstack.nova.v2_0.domain.HostResourceUsage;\nimport org.jclouds.openstack.nova.v2_0.functions.FieldValueResponseParsers.MaintenanceModeDisabledResponseParser;\nimport org.jclouds.openstack.nova.v2_0.functions.FieldValueResponseParsers.MaintenanceModeEnabledResponseParser;\nimport org.jclouds.openstack.nova.v2_0.functions.FieldValueResponseParsers.PowerIsRebootResponseParser;\nimport org.jclouds.openstack.nova.v2_0.functions.FieldValueResponseParsers.PowerIsShutdownResponseParser;\nimport org.jclouds.openstack.nova.v2_0.functions.FieldValueResponseParsers.PowerIsStartupResponseParser;\nimport org.jclouds.openstack.nova.v2_0.functions.FieldValueResponseParsers.StatusDisabledResponseParser;\nimport org.jclouds.openstack.nova.v2_0.functions.FieldValueResponseParsers.StatusEnabledResponseParser;\nimport org.jclouds.openstack.v2_0.ServiceType;\nimport org.jclouds.openstack.v2_0.services.Extension;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.collect.FluentIterable;\n\n/**\n * Provides access to OpenStack Compute (Nova) Host Administration extension API.\n */\n@Beta\n@Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.HOSTS,\n      name = ExtensionNames.HOST_ADMINISTRATION, alias = ExtensionAliases.HOST_ADMINISTRATION)\n@RequestFilters(AuthenticateRequest.class)\n@Consumes(MediaType.APPLICATION_JSON)\n@Path(\"/os-hosts\")\npublic interface HostAdministrationApi {\n   /**\n    * Returns the list of hosts\n    *\n    * @return the usage information\n    */\n   @Named(\"hostAdmin:list\")\n   @GET\n   @SelectJson(\"hosts\")\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<Host> list();\n\n   /**\n    * Retrieves the physical/usage resource on a specific host\n    *\n    * @return the usage information\n    */\n   @Named(\"hostAdmin:listResourceUsage\")\n   @GET\n   @Path(\"/{id}\")\n   @SelectJson(\"host\")\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<HostResourceUsage> listResourceUsage(@PathParam(\"id\") String hostId);\n\n   /**\n    * Allow the specified host to accept new instances.\n    *\n    * @return true if successful\n    */\n   @Named(\"hostAdmin:enable\")\n   @PUT\n   @Path(\"/{id}\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @Payload(\"{\\\"status\\\":\\\"enable\\\"}\")\n   @ResponseParser(StatusEnabledResponseParser.class)\n   boolean enable(@PathParam(\"id\") String hostId);\n\n   /**\n    * Prevent the specified host from accepting new instances.\n    *\n    * @return true if successful\n    */\n   @Named(\"hostAdmin:disable\")\n   @PUT\n   @Path(\"/{id}\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @Payload(\"{\\\"status\\\":\\\"disable\\\"}\")\n   @ResponseParser(StatusDisabledResponseParser.class)\n   boolean disable(@PathParam(\"id\") String hostId);\n\n   /**\n    * Start host maintenance window.\n    * <p/>\n    * Note: this triggers guest VMs evacuation.\n    *\n    * @return true if successful\n    */\n   @Named(\"hostAdmin:startMaintenance\")\n   @PUT\n   @Path(\"/{id}\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @Payload(\"{\\\"maintenance_mode\\\":\\\"enable\\\"}\")\n   @ResponseParser(MaintenanceModeEnabledResponseParser.class)\n   boolean startMaintenance(@PathParam(\"id\") String hostId);\n\n   /**\n    * Stop host maintenance window.\n    *\n    * @return true if successful\n    */\n   @Named(\"hostAdmin:stopMaintenance\")\n   @PUT\n   @Path(\"/{id}\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @Payload(\"{\\\"maintenance_mode\\\":\\\"disable\\\"}\")\n   @ResponseParser(MaintenanceModeDisabledResponseParser.class)\n   boolean stopMaintenance(@PathParam(\"id\") String hostId);\n\n   /**\n    * Startup a host.\n    *\n    * @return true if successful\n    */\n   @Named(\"hostAdmin:startup\")\n   @GET\n   @Path(\"/{id}/startup\")\n   @ResponseParser(PowerIsStartupResponseParser.class)\n   boolean startup(@PathParam(\"id\") String hostId);\n\n   /**\n    * Shutdown a host.\n    *\n    * @return true if successful\n    */\n   @Named(\"hostAdmin:shutdown\")\n   @GET\n   @Path(\"/{id}/shutdown\")\n   @ResponseParser(PowerIsShutdownResponseParser.class)\n   boolean shutdown(@PathParam(\"id\") String hostId);\n\n   /**\n    * Reboot a host.\n    *\n    * @return true if successful\n    */\n   @Named(\"hostAdmin:reboot\")\n   @GET\n   @Path(\"/{id}/reboot\")\n   @ResponseParser(PowerIsRebootResponseParser.class)\n   boolean reboot(@PathParam(\"id\") String hostId);\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/HostAggregateApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport java.util.Map;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyFluentIterableOnNotFoundOr404;\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.nova.v2_0.domain.HostAggregate;\nimport org.jclouds.openstack.v2_0.ServiceType;\nimport org.jclouds.openstack.v2_0.services.Extension;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.WrapWith;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.collect.FluentIterable;\n\n/**\n * Provide access to the OpenStack Compute (Nova) Host Aggregates extension API.\n */\n@Beta\n@Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.AGGREGATES,\n      name = ExtensionNames.HOST_AGGREGATE, alias = ExtensionAliases.HOST_AGGREGATE)\n@RequestFilters(AuthenticateRequest.class)\n@Consumes(MediaType.APPLICATION_JSON)\n@Path(\"/os-aggregates\")\npublic interface HostAggregateApi {\n   /**\n    * Lists all host aggregates.\n    *\n    * @return the set of host aggregates.\n    */\n   @Named(\"hostAggregate:list\")\n   @GET\n   @SelectJson(\"aggregates\")\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<HostAggregate> list();\n\n   /**\n    * Retrieves the details of an aggregate, hosts and metadata included.\n    *\n    * @return the details of the aggregate requested.\n    */\n   @Named(\"hostAggregate:get\")\n   @GET\n   @Path(\"/{id}\")\n   @SelectJson(\"aggregate\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   HostAggregate get(@PathParam(\"id\") String id);\n\n   /**\n    * Creates an aggregate, given its name and availability zone.\n    *\n    * @return the newly created Aggregate\n    */\n   @Named(\"hostAggregate:create\")\n   @POST\n   @SelectJson(\"aggregate\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @WrapWith(\"aggregate\")\n   HostAggregate createInAvailabilityZone(@PayloadParam(\"name\") String name,\n         @PayloadParam(\"availability_zone\") String availabilityZone);\n\n   /**\n    * Updates the name of an aggregate.\n    */\n   @Named(\"hostAggregate:update\")\n   @POST\n   @Path(\"/{id}\")\n   @SelectJson(\"aggregate\")\n   @WrapWith(\"aggregate\")\n   HostAggregate updateName(@PathParam(\"id\") String id, @PayloadParam(\"name\") String name);\n\n   /**\n    * Updates the availability zone for an aggregate.\n    */\n   @Named(\"hostAggregate:update\")\n   @POST\n   @Path(\"/{id}\")\n   @SelectJson(\"aggregate\")\n   @WrapWith(\"aggregate\")\n   HostAggregate updateAvailabilityZone(@PathParam(\"id\") String id,\n         @PayloadParam(\"availability_zone\") String availabilityZone);\n\n   /**\n    * Removes an aggregate.\n    */\n   @Named(\"hostAggregate:delete\")\n   @DELETE\n   @Path(\"/{id}\")\n   @Fallback(FalseOnNotFoundOr404.class)\n   Boolean delete(@PathParam(\"id\") String id);\n\n   /**\n    * Adds a host to an aggregate\n    */\n   @Named(\"hostAggregate:addHost\")\n   @POST\n   @Path(\"/{id}/action\")\n   @SelectJson(\"aggregate\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @WrapWith(\"add_host\")\n   HostAggregate addHost(@PathParam(\"id\") String id, @PayloadParam(\"host\") String host);\n\n   /**\n    * Removes a host from an aggregate\n    */\n   @Named(\"hostAggregate:removeHost\")\n   @POST\n   @Path(\"/{id}/action\")\n   @SelectJson(\"aggregate\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @WrapWith(\"remove_host\")\n   HostAggregate removeHost(@PathParam(\"id\") String id, @PayloadParam(\"host\") String host);\n\n   /**\n    * Adds metadata to an aggregate\n    */\n   @Named(\"hostAggregate:setMetadata\")\n   @POST\n   @Path(\"/{id}/action\")\n   @SelectJson(\"aggregate\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @WrapWith(\"set_metadata\")\n   HostAggregate setMetadata(@PathParam(\"id\") String id,\n         @PayloadParam(\"metadata\") Map<String, String> metadata);\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/HypervisorApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyFluentIterableOnNotFoundOr404;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.Hypervisor;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.HypervisorDetails;\nimport org.jclouds.openstack.v2_0.ServiceType;\nimport org.jclouds.openstack.v2_0.services.Extension;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.collect.FluentIterable;\n\n/**\n * Provides access to the OpenStack Compute (Nova) Hypervisor Extension API.\n */\n@Beta\n@Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.HYPERVISORS,\n      name = ExtensionNames.HYPERVISORS, alias = ExtensionAliases.HYPERVISORS)\n@RequestFilters(AuthenticateRequest.class)\n@Consumes(MediaType.APPLICATION_JSON)\n@Path(\"/os-hypervisors\")\npublic interface HypervisorApi {\n\n   @Named(\"hypervisors:list\")\n   @GET\n   @SelectJson(\"hypervisors\")\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<Hypervisor> list();\n\n   @Named(\"hypervisors:list\")\n   @GET\n   @Path(\"/detail\")\n   @SelectJson(\"hypervisors\")\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<HypervisorDetails> listInDetail();\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/KeyPairApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyFluentIterableOnNotFoundOr404;\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.nova.v2_0.binders.BindKeyPairToJsonPayload;\nimport org.jclouds.openstack.nova.v2_0.domain.KeyPair;\nimport org.jclouds.openstack.nova.v2_0.functions.internal.ParseKeyPairs;\nimport org.jclouds.openstack.v2_0.ServiceType;\nimport org.jclouds.openstack.v2_0.services.Extension;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.collect.FluentIterable;\n\n/**\n * Provides access to the OpenStack Compute (Nova) Key Pair Extension API.\n */\n@Beta\n@Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.KEYPAIRS,\n      name = ExtensionNames.KEYPAIRS, alias = ExtensionAliases.KEYPAIRS)\n@RequestFilters(AuthenticateRequest.class)\n@Consumes(MediaType.APPLICATION_JSON)\n@Path(\"/os-keypairs\")\npublic interface KeyPairApi {\n   /**\n    * Lists all Key Pairs.\n    *\n    * @return all Key Pairs\n    */\n   @Named(\"keypair:list\")\n   @GET\n   @ResponseParser(ParseKeyPairs.class)\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<KeyPair> list();\n\n   /**\n    * Creates a {@link KeyPair}.\n    *\n    * @return the created {@link KeyPair}.\n    */\n   @Named(\"keypair:create\")\n   @POST\n   @SelectJson(\"keypair\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @Payload(\"%7B\\\"keypair\\\":%7B\\\"name\\\":\\\"{name}\\\"%7D%7D\")\n   KeyPair create(@PayloadParam(\"name\") String name);\n\n\n   /**\n    * Creates a {@link KeyPair} with a public key.\n    *\n    * @return the created {@link KeyPair}.\n    */\n   @Named(\"keypair:create\")\n   @POST\n   @SelectJson(\"keypair\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @MapBinder(BindKeyPairToJsonPayload.class)\n   KeyPair createWithPublicKey(@PayloadParam(\"name\") String name,\n         @PayloadParam(\"public_key\") String publicKey);\n\n   /**\n    * Gets a specific {@link KeyPair} by name.\n    *\n    * @param name\n    *           the name of the {@link KeyPair}\n    *\n    * @return the specified {@link KeyPair}, otherwise null.\n    */\n   @Named(\"keypair:get\")\n   @GET\n   @Path(\"/{name}\")\n   @SelectJson(\"keypair\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   KeyPair get(@PathParam(\"name\") String name);\n\n   /**\n    * Deletes a {@link KeyPair}.\n    *\n    * @param name\n    *           the name of the {@link KeyPair}\n    *\n    * @return {@code true} if the {@link KeyPair} was deleted, otherwise {@code false}.\n    */\n   @Named(\"keypair:delete\")\n   @DELETE\n   @Path(\"/{name}\")\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean delete(@PathParam(\"name\") String name);\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/QuotaApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.nova.v2_0.domain.Quota;\nimport org.jclouds.openstack.v2_0.ServiceType;\nimport org.jclouds.openstack.v2_0.services.Extension;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport com.google.common.annotations.Beta;\n\n/**\n * Provide access to OpenStack Compute (Nova) Quota Extension API.\n * <p/>\n * The quotas extension enables limiters placed on the resources used per tenant (project) for virtual instances. It is\n * used with the OpenStack Compute API 1.1 for administrators who need to control the amount of volumes, memory, floating\n * IP addresses, instances, or cores allowed within a defined tenant or project.\n * <p/>\n * To use this extension, you need to have administrative rights to the tenants upon which you are placing quotas.\n *\n */\n@Beta\n@Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.QUOTAS,\n      name = ExtensionNames.QUOTAS, alias = ExtensionAliases.QUOTAS)\n@RequestFilters(AuthenticateRequest.class)\n@Consumes(MediaType.APPLICATION_JSON)\n@Path(\"/os-quota-sets\")\npublic interface QuotaApi {\n   /**\n    * @return the quota settings for the tenant\n    */\n   @Named(\"quota:get\")\n   @GET\n   @SelectJson(\"quota_set\")\n   @Path(\"/{id}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Quota getByTenant(@PathParam(\"id\") String tenantId);\n\n   /**\n    * Update the quotas for a given tenant\n    *\n    * @return true if successful\n    */\n   @Named(\"quota:update\")\n   @PUT\n   @Path(\"/{id}\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @MapBinder(BindToJsonPayload.class)\n   boolean updateQuotaOfTenant(@PayloadParam(\"quota_set\") Quota quota,\n         @PathParam(\"id\") String tenantId);\n\n   /**\n    * @return the set of default quotas for the tenant\n    */\n   @Named(\"quota:get\")\n   @GET\n   @SelectJson(\"quota_set\")\n   @Path(\"/{id}/defaults\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Quota getDefaultsForTenant(@PathParam(\"id\") String tenantId);\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/SecurityGroupApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyFluentIterableOnNotFoundOr404;\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.nova.v2_0.binders.BindSecurityGroupRuleToJsonPayload;\nimport org.jclouds.openstack.nova.v2_0.domain.Ingress;\nimport org.jclouds.openstack.nova.v2_0.domain.SecurityGroup;\nimport org.jclouds.openstack.nova.v2_0.domain.SecurityGroupRule;\nimport org.jclouds.openstack.v2_0.ServiceType;\nimport org.jclouds.openstack.v2_0.services.Extension;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.collect.FluentIterable;\n\n/**\n * Provides access to the OpenStack Compute (Nova) Security Group extension API.\n */\n@Beta\n@Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.SECURITY_GROUPS,\n      name = ExtensionNames.SECURITY_GROUPS, alias = ExtensionAliases.SECURITY_GROUPS)\n@RequestFilters(AuthenticateRequest.class)\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface SecurityGroupApi {\n   /**\n    * List all Security Groups.\n    *\n    * @return all Security Groups\n    */\n   @Named(\"securityGroup:list\")\n   @GET\n   @Path(\"/os-security-groups\")\n   @SelectJson(\"security_groups\")\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<SecurityGroup> list();\n\n   /**\n    * Get a specific Security Group\n    *\n    * @return a specific Security Group\n    */\n   @Named(\"securityGroup:get\")\n   @GET\n   @Path(\"/os-security-groups/{id}\")\n   @SelectJson(\"security_group\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   SecurityGroup get(@PathParam(\"id\") String id);\n\n   /**\n    * Create a Security Group\n    *\n    * @return a new Security Group\n    */\n   @Named(\"securityGroup:create\")\n   @POST\n   @Path(\"/os-security-groups\")\n   @SelectJson(\"security_group\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @Payload(\"%7B\\\"security_group\\\":%7B\\\"name\\\":\\\"{name}\\\",\\\"description\\\":\\\"{description}\\\"%7D%7D\")\n   @Nullable\n   SecurityGroup createWithDescription(@PayloadParam(\"name\") String name,\n         @PayloadParam(\"description\") String description);\n\n   /**\n    * Delete a Security Group.\n    *\n    * @return\n    */\n   @Named(\"securityGroup:delete\")\n   @DELETE\n   @Path(\"/os-security-groups/{id}\")\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean delete(@PathParam(\"id\") String id);\n\n   /**\n    * Create a Security Group Rule.\n    *\n    * @return a new Security Group Rule\n    */\n   @Named(\"securityGroup:create\")\n   @POST\n   @Path(\"/os-security-group-rules\")\n   @SelectJson(\"security_group_rule\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @MapBinder(BindSecurityGroupRuleToJsonPayload.class)\n   @Nullable\n   SecurityGroupRule createRuleAllowingCidrBlock(\n         @PayloadParam(\"parent_group_id\") String parentGroup, Ingress ip_protocol,\n         @PayloadParam(\"cidr\") String sourceCidr);\n\n   /**\n    * Create a Security Group Rule.\n    *\n    * @return a new Security Group Rule\n    */\n   @Named(\"securityGroup:create\")\n   @POST\n   @Path(\"/os-security-group-rules\")\n   @SelectJson(\"security_group_rule\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @MapBinder(BindSecurityGroupRuleToJsonPayload.class)\n   @Nullable\n   SecurityGroupRule createRuleAllowingSecurityGroupId(\n         @PayloadParam(\"parent_group_id\") String parentGroup, Ingress ip_protocol,\n         @PayloadParam(\"group_id\") String groupId);\n\n   /**\n    * Delete a Security Group Rule.\n    *\n    * @return\n    */\n   @Named(\"securityGroup:delete\")\n   @DELETE\n   @Path(\"/os-security-group-rules/{id}\")\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean deleteRule(@PathParam(\"id\") String ruleId);\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/ServerAdminApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.fallbacks.MapHttp4xxCodesToExceptions;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.nova.v2_0.domain.BackupType;\nimport org.jclouds.openstack.nova.v2_0.functions.ParseImageIdFromLocationHeader;\nimport org.jclouds.openstack.nova.v2_0.options.CreateBackupOfServerOptions;\nimport org.jclouds.openstack.v2_0.ServiceType;\nimport org.jclouds.openstack.v2_0.services.Extension;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.WrapWith;\n\nimport com.google.common.annotations.Beta;\n\n/**\n * Provide access to the OpenStack Compute (Nova) Admin Server Actions Extension API.\n *\n * Provide additional actions for servers:\n * 'suspend', 'resume', 'migrate', 'lock', 'unlock', 'resetNetwork', 'createBackup', 'pause', 'migrateLive',\n * 'injectNetworkInfo', 'unpause'\n *\n */\n@Beta\n@Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.ADMIN_ACTIONS,\n      name = ExtensionNames.SERVER_ADMIN, alias = ExtensionAliases.SERVER_ADMIN)\n@RequestFilters(AuthenticateRequest.class)\n@Consumes(MediaType.APPLICATION_JSON)\n@Path(\"/servers/{id}/action\")\npublic interface ServerAdminApi {\n   /**\n    * Suspend a server.\n    *\n    * @param id id of the server\n    */\n   @Named(\"serverAdmin:suspend\")\n   @POST\n   @Produces(MediaType.APPLICATION_JSON)\n   @Payload(\"{\\\"suspend\\\":null}\")\n   void suspend(@PathParam(\"id\") String id);\n\n   /**\n    * Resume a server.\n    *\n    * @param id id of the server\n    */\n   @Named(\"serverAdmin:resume\")\n   @POST\n   @Produces(MediaType.APPLICATION_JSON)\n   @Payload(\"{\\\"resume\\\":null}\")\n   void resume(@PathParam(\"id\") String id);\n\n   /**\n    * Migrate a server.\n    *\n    * @param id id of the server\n    */\n   @Named(\"serverAdmin:migrate\")\n   @POST\n   @Produces(MediaType.APPLICATION_JSON)\n   @Payload(\"{\\\"migrate\\\":null}\")\n   void migrate(@PathParam(\"id\") String id);\n\n   /**\n    * Lock a server.\n    *\n    * @param id id of the server\n    */\n   @Named(\"serverAdmin:lock\")\n   @POST\n   @Produces(MediaType.APPLICATION_JSON)\n   @Payload(\"{\\\"lock\\\":null}\")\n   void lock(@PathParam(\"id\") String id);\n\n   /**\n    * Unlock a server.\n    *\n    * @param id id of the server\n    */\n   @Named(\"serverAdmin:unlock\")\n   @POST\n   @Produces(MediaType.APPLICATION_JSON)\n   @Payload(\"{\\\"unlock\\\":null}\")\n   void unlock(@PathParam(\"id\") String id);\n\n   /**\n    * Reset network of a server.\n    *\n    * @param id id of the server\n    */\n   @Named(\"serverAdmin:resetNetwork\")\n   @POST\n   @Produces(MediaType.APPLICATION_JSON)\n   @Payload(\"{\\\"resetNetwork\\\":null}\")\n   void resetNetwork(@PathParam(\"id\") String id);\n\n   /**\n    * Create backup of a server.\n    *\n    * @param id         id of the server\n    * @param imageName  the name of the image to create\n    * @param backupType the type of backup\n    * @param rotation   the number of images to retain (0 to simply overwrite)\n    * @param options    optional rotation and/or metadata parameters\n    * @return the id of the newly created image\n    */\n   @Named(\"serverAdmin:createBackup\")\n   @POST\n   @Produces(MediaType.APPLICATION_JSON)\n   @WrapWith(\"createBackup\")\n   @ResponseParser(ParseImageIdFromLocationHeader.class)\n   @Fallback(MapHttp4xxCodesToExceptions.class)\n   String createBackup(@PathParam(\"id\") String id, @PayloadParam(\"name\") String imageName,\n         @PayloadParam(\"backup_type\") BackupType backupType, @PayloadParam(\"rotation\") int rotation,\n         CreateBackupOfServerOptions... options);\n\n   /**\n    * Pause a server.\n    *\n    * @param id id of the server\n    */\n   @Named(\"serverAdmin:pause\")\n   @POST\n   @Produces(MediaType.APPLICATION_JSON)\n   @Payload(\"{\\\"pause\\\":null}\")\n   void pause(@PathParam(\"id\") String id);\n\n   /**\n    * Unpause a server.\n    *\n    * @param id id of the server\n    */\n   @Named(\"serverAdmin:unpause\")\n   @POST\n   @Produces(MediaType.APPLICATION_JSON)\n   @Payload(\"{\\\"unpause\\\":null}\")\n   void unpause(@PathParam(\"id\") String id);\n\n   /**\n    * Live migrate a server.\n    *\n    * @param id id of the server\n    */\n   @Named(\"serverAdmin:liveMigrate\")\n   @POST\n   @Produces(MediaType.APPLICATION_JSON)\n   @WrapWith(\"os-migrateLive\")\n   void liveMigrate(@PathParam(\"id\") String id, @PayloadParam(\"host\") String host,\n         @PayloadParam(\"block_migration\") boolean blockMigration,\n         @PayloadParam(\"disk_over_commit\") boolean diskOverCommit);\n\n   /**\n    * Inject network info into a server.\n    *\n    * @param id id of the server\n    */\n   @Named(\"serverAdmin:injectNetwork\")\n   @POST\n   @Produces(MediaType.APPLICATION_JSON)\n   @Payload(\"{\\\"injectNetworkInfo\\\":null}\")\n   void injectNetworkInfo(@PathParam(\"id\") String id);\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/ServerWithSecurityGroupsApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.nova.v2_0.domain.ServerWithSecurityGroups;\nimport org.jclouds.openstack.v2_0.ServiceType;\nimport org.jclouds.openstack.v2_0.services.Extension;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\nimport com.google.common.annotations.Beta;\n\n/**\n * Provides access to the OpenStack Compute (Nova) Create Server extension API.\n *\n * This provides details including the security groups associated with a Server.\n * <p/>\n *\n * NOTE: the equivalent to listServersInDetail() isn't available at the other end, so not\n * extending ServerApi at this time.\n *\n * @see org.jclouds.openstack.nova.v2_0.features.ServerApi\n */\n@Beta\n@Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.CREATESERVEREXT,\n      name = ExtensionNames.CREATESERVEREXT, alias = ExtensionAliases.CREATESERVEREXT)\n@RequestFilters(AuthenticateRequest.class)\n@Consumes(MediaType.APPLICATION_JSON)\n@Path(\"/os-create-server-ext\")\npublic interface ServerWithSecurityGroupsApi {\n   /**\n    * Retrieve details of the specified server, including security groups\n    *\n    * @param id id of the server\n    * @return server or null if not found\n    */\n   @Named(\"server:get\")\n   @GET\n   @SelectJson(\"server\")\n   @Path(\"/{id}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   ServerWithSecurityGroups get(@PathParam(\"id\") String id);\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/SimpleTenantUsageApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyFluentIterableOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.nova.v2_0.domain.SimpleTenantUsage;\nimport org.jclouds.openstack.v2_0.ServiceType;\nimport org.jclouds.openstack.v2_0.services.Extension;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.collect.FluentIterable;\n\n/**\n * Provides access to the OpenStack Compute (Nova) Simple Tenant Usage extension API.\n */\n@Beta\n@Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.SIMPLE_TENANT_USAGE,\n      name = ExtensionNames.SIMPLE_TENANT_USAGE, alias = ExtensionAliases.SIMPLE_TENANT_USAGE)\n@RequestFilters(AuthenticateRequest.class)\n@Consumes(MediaType.APPLICATION_JSON)\n@Path(\"/os-simple-tenant-usage\")\npublic interface SimpleTenantUsageApi {\n   /**\n    * Retrieve tenant usage for all tenants.\n    *\n    * @return the set of TenantUsage reports\n    */\n   @Named(\"tenantUsage:list\")\n   @GET\n   @SelectJson(\"tenant_usages\")\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<SimpleTenantUsage> list();\n\n   /**\n    * Retrieve tenant_usage for a specified tenant\n    *\n    * @return the requested tenant usage\n    */\n   @Named(\"tenantUsage:get\")\n   @GET\n   @Path(\"/{id}\")\n   @SelectJson(\"tenant_usage\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   SimpleTenantUsage get(@PathParam(\"id\") String tenantId);\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/VirtualInterfaceApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyFluentIterableOnNotFoundOr404;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.nova.v2_0.domain.VirtualInterface;\nimport org.jclouds.openstack.v2_0.ServiceType;\nimport org.jclouds.openstack.v2_0.services.Extension;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.collect.FluentIterable;\n\n/**\n * Provides access to the OpenStack Compute (Nova) Virtual Interface (VIFs) extension API.\n */\n@Beta\n@Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.VIRTUAL_INTERFACES,\n      name = ExtensionNames.VIRTUAL_INTERFACES, alias = ExtensionAliases.VIRTUAL_INTERFACES)\n@RequestFilters(AuthenticateRequest.class)\n@Consumes(MediaType.APPLICATION_JSON)\n@Path(\"/servers\")\npublic interface VirtualInterfaceApi {\n   /**\n    * Returns the list of Virtual Interfaces for a given instance.\n    *\n    * @return the list of virtual interfaces\n    */\n   @Named(\"virtualInterface:list\")\n   @GET\n   @Path(\"/{id}/os-virtual-interfaces\")\n   @SelectJson(\"virtual_interfaces\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<VirtualInterface> listOnServer(@PathParam(\"id\") String serverId);\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/VolumeApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyFluentIterableOnNotFoundOr404;\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.nova.v2_0.domain.Volume;\nimport org.jclouds.openstack.nova.v2_0.domain.VolumeSnapshot;\nimport org.jclouds.openstack.nova.v2_0.options.CreateVolumeOptions;\nimport org.jclouds.openstack.nova.v2_0.options.CreateVolumeSnapshotOptions;\nimport org.jclouds.openstack.v2_0.ServiceType;\nimport org.jclouds.openstack.v2_0.services.Extension;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.collect.FluentIterable;\n\n/**\n * Provides access to the OpenStack Compute (Nova) Volume extension API.\n *\n * @deprecated Please use {@link org.jclouds.openstack.cinder.v1.features.VolumeApi} or\n *             {@link org.jclouds.openstack.cinder.v1.features.VolumeApi} instead. To be removed in jclouds 2.0.\n */\n@Deprecated\n@Beta\n@Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.VOLUMES,\n      name = ExtensionNames.VOLUMES, alias = ExtensionAliases.VOLUMES)\n@RequestFilters(AuthenticateRequest.class)\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface VolumeApi {\n   /**\n    * Returns a summary list of snapshots.\n    *\n    * @deprecated Please use {@link org.jclouds.openstack.cinder.v1.features.VolumeApi#list()} instead.\n    *             To be removed in jclouds 2.0.\n    * @return the list of snapshots\n    */\n   @Deprecated\n   @Named(\"volume:list\")\n   @GET\n   @Path(\"/os-volumes\")\n   @SelectJson(\"volumes\")\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<Volume> list();\n\n   /**\n    * Returns a detailed list of volumes.\n    *\n    * @deprecated Please use {@link org.jclouds.openstack.cinder.v1.features.VolumeApi#listInDetail()} instead.\n    *             To be removed in jclouds 2.0.\n    * @return the list of volumes.\n    */\n   @Deprecated\n   @Named(\"volume:list\")\n   @GET\n   @Path(\"/os-volumes/detail\")\n   @SelectJson(\"volumes\")\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<Volume> listInDetail();\n\n   /**\n    * Return data about the given volume.\n    *\n    * @deprecated Please use {@link org.jclouds.openstack.cinder.v1.features.VolumeApi#get(String)} instead.\n    *             To be removed in jclouds 2.0.\n    * @return details of a specific snapshot.\n    */\n   @Deprecated\n   @Named(\"volume:get\")\n   @GET\n   @Path(\"/os-volumes/{id}\")\n   @SelectJson(\"volume\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Volume get(@PathParam(\"id\") String volumeId);\n\n   /**\n    * Creates a new Snapshot\n    *\n    * @deprecated Please use {@link org.jclouds.openstack.cinder.v1.features.VolumeApi#create(int, CreateVolumeOptions)} instead.\n    *             To be removed in jclouds 2.0.\n    * @return the new Snapshot\n    */\n   @Deprecated\n   @Named(\"volume:create\")\n   @POST\n   @Path(\"/os-volumes\")\n   @SelectJson(\"volume\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @MapBinder(CreateVolumeOptions.class)\n   Volume create(@PayloadParam(\"size\") int sizeGB, CreateVolumeOptions... options);\n\n   /**\n    * Delete a snapshot.\n    *\n    * @deprecated Please use {@link org.jclouds.openstack.cinder.v1.features.VolumeApi#delete(String)} instead.\n    *             To be removed in jclouds 2.0.\n    * @return true if successful\n    */\n   @Deprecated\n   @Named(\"volume:delete\")\n   @DELETE\n   @Path(\"/os-volumes/{volumeId}\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean delete(@PathParam(\"volumeId\") String volumeId);\n\n\n   /**\n    * Returns a summary list of snapshots.\n    *\n    * @deprecated Please use {@link org.jclouds.openstack.cinder.v1.features.SnapshotApi#list()} instead.\n    *             To be removed in jclouds 2.0.\n    * @return the list of snapshots\n    */\n   @Deprecated\n   @Named(\"volume:listSnapshots\")\n   @GET\n   @Path(\"/os-snapshots\")\n   @SelectJson(\"snapshots\")\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<VolumeSnapshot> listSnapshots();\n\n   /**\n    * Returns a summary list of snapshots.\n    *\n    * @deprecated Please use {@link org.jclouds.openstack.cinder.v1.features.SnapshotApi#listInDetail()} instead.\n    *             To be removed in jclouds 2.0.\n    * @return the list of snapshots\n    */\n   @Deprecated\n   @Named(\"volume:listSnapshots\")\n   @GET\n   @Path(\"/os-snapshots/detail\")\n   @SelectJson(\"snapshots\")\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<VolumeSnapshot> listSnapshotsInDetail();\n\n   /**\n    * Return data about the given snapshot.\n    *\n    * @deprecated Please use {@link org.jclouds.openstack.cinder.v1.features.SnapshotApi#get(String)} instead.\n    *             To be removed in jclouds 2.0.\n    * @return details of a specific snapshot.\n    */\n   @Deprecated\n   @Named(\"volume:getSnapshot\")\n   @GET\n   @Path(\"/os-snapshots/{id}\")\n   @SelectJson(\"snapshot\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   VolumeSnapshot getSnapshot(@PathParam(\"id\") String snapshotId);\n\n   /**\n    * Creates a new Snapshot.\n    *\n    * @deprecated Please use {@link org.jclouds.openstack.cinder.v1.features.SnapshotApi#create(String, CreateVolumeSnapshotOptions)} instead.\n    *             To be removed in jclouds 2.0.\n    * @return the new Snapshot\n    */\n   @Deprecated\n   @Named(\"volume:createSnapshot\")\n   @POST\n   @Path(\"/os-snapshots\")\n   @SelectJson(\"snapshot\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @MapBinder(CreateVolumeSnapshotOptions.class)\n   VolumeSnapshot createSnapshot(@PayloadParam(\"volume_id\") String volumeId, CreateVolumeSnapshotOptions... options);\n\n   /**\n    * Delete a snapshot.\n    *\n    * @deprecated Please use {@link org.jclouds.openstack.cinder.v1.features.SnapshotApi#delete(String)} instead.\n    *             To be removed in jclouds 2.0.\n    * @return true if successful\n    */\n   @Deprecated\n   @Named(\"volume:deleteSnapshot\")\n   @DELETE\n   @Path(\"/os-snapshots/{id}\")\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean deleteSnapshot(@PathParam(\"id\") String snapshotId);\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/VolumeAttachmentApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyFluentIterableOnNotFoundOr404;\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.nova.v2_0.domain.VolumeAttachment;\nimport org.jclouds.openstack.v2_0.ServiceType;\nimport org.jclouds.openstack.v2_0.services.Extension;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.WrapWith;\n\nimport com.google.common.collect.FluentIterable;\n\n/**\n * Provides access to the OpenStack Compute (Nova) Volume Attachments Extension API.\n *\n * This API strictly handles attaching Volumes to Servers. To create and manage Volumes you need to use the Cinder API.\n * @see org.jclouds.openstack.cinder.v1.features.VolumeApi\n */\n@Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.VOLUME_ATTACHMENTS,\n      name = ExtensionNames.VOLUME_ATTACHMENT, alias = ExtensionAliases.VOLUME_ATTACHMENT)\n@RequestFilters(AuthenticateRequest.class)\n@Consumes(MediaType.APPLICATION_JSON)\n@Path(\"/servers\")\npublic interface VolumeAttachmentApi {\n   /**\n    * Lists Volume Attachments for a given Server.\n    *\n    * @param serverId The ID of the Server\n    * @return All VolumeAttachments for the Server\n    */\n   @Named(\"volumeAttachment:list\")\n   @GET\n   @Path(\"/{serverId}/os-volume_attachments\")\n   @SelectJson(\"volumeAttachments\")\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<VolumeAttachment> listAttachmentsOnServer(@PathParam(\"serverId\") String serverId);\n\n   /**\n    * Gets a specific Volume Attachment for a Volume and Server.\n    *\n    * @param volumeId The ID of the Volume\n    * @param serverId The ID of the Server\n    * @return The Volume Attachment.\n    */\n   @Named(\"volumeAttachment:get\")\n   @GET\n   @Path(\"/{serverId}/os-volume_attachments/{id}\")\n   @SelectJson(\"volumeAttachment\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   VolumeAttachment getAttachmentForVolumeOnServer(@PathParam(\"id\") String volumeId,\n         @PathParam(\"serverId\") String serverId);\n\n   /**\n    * Attaches a Volume to a Server.\n    *\n    * Note: If you are using KVM as your hypervisor then the actual device name in the Server will be different than\n    * the one specified. When the Server sees a new device, it picks the next available name (which in most cases is\n    * /dev/vdc) and the disk shows up there on the Server.\n    *\n    * @param serverId The ID of the Server\n    * @param volumeId The ID of the Volume\n    * @param device The name of the device this Volume will be identified as in the Server (e.g. /dev/vdc)\n    * @return The Volume Attachment.\n    */\n   @Named(\"volumeAttachment:attach\")\n   @POST\n   @Path(\"/{serverId}/os-volume_attachments\")\n   @SelectJson(\"volumeAttachment\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @WrapWith(\"volumeAttachment\")\n   VolumeAttachment attachVolumeToServerAsDevice(@PayloadParam(\"volumeId\") String volumeId,\n         @PathParam(\"serverId\") String serverId, @PayloadParam(\"device\") String device);\n\n   /**\n    * Detaches a Volume from a server.\n    *\n    * Note: Make sure you've unmounted the volume first. Failure to do so could result in failure or data loss.\n    *\n    * @param volumeId The ID of the Volume\n    * @param serverId The ID of the Server\n    * @return true if successful\n    */\n   @Named(\"volumeAttachment:detach\")\n   @DELETE\n   @Path(\"/{serverId}/os-volume_attachments/{id}\")\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean detachVolumeFromServer(@PathParam(\"id\") String volumeId,\n         @PathParam(\"serverId\") String serverId);\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/VolumeTypeApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport java.util.Map;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyFluentIterableOnNotFoundOr404;\nimport org.jclouds.Fallbacks.EmptyMapOnNotFoundOr404;\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.nova.v2_0.domain.VolumeType;\nimport org.jclouds.openstack.nova.v2_0.options.CreateVolumeTypeOptions;\nimport org.jclouds.openstack.v2_0.ServiceType;\nimport org.jclouds.openstack.v2_0.services.Extension;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.Unwrap;\nimport org.jclouds.rest.annotations.WrapWith;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.collect.FluentIterable;\n\n/**\n * Provides access to the OpenStack Compute (Nova) Volume Type extension API.\n * This extension is no longer supported in OpenStack Liberty.\n * You can use the Block Storage API and endpoint to list volume types,\n * see <a href=\"http://developer.openstack.org/api-ref-blockstorage-v2.html#volumes-v2-types\">volume types v2</a>.\n * @see VolumeApi\n */\n@Beta\n@Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.VOLUME_TYPES)\n@RequestFilters(AuthenticateRequest.class)\n@Consumes(MediaType.APPLICATION_JSON)\n@Path(\"/os-volume-types\")\npublic interface VolumeTypeApi {\n   /**\n    * @return set of all volume types\n    */\n   @Named(\"volumeType:list\")\n   @GET\n   @SelectJson(\"volume_types\")\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<VolumeType> list();\n\n   /**\n    * Gets a volume type\n    *\n    * @param id the id of the volume type to retrieve\n    * @return the requested volume type\n    */\n   @Named(\"volumeType:get\")\n   @GET\n   @Path(\"/{id}\")\n   @SelectJson(\"volume_type\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   VolumeType get(@PathParam(\"id\") String id);\n\n   /**\n    * Creates a new volume type\n    *\n    * @param name    the name of the new volume type\n    * @param options optional settings for the new volume type\n    * @return the new volume type\n    */\n   @Named(\"volumeType:create\")\n   @POST\n   @SelectJson(\"volume_type\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @WrapWith(\"volume_type\")\n   VolumeType create(@PayloadParam(\"name\") String name, CreateVolumeTypeOptions... options);\n\n   /**\n    * Deletes a volume type\n    *\n    * @param id the id of the volume type to delete\n    */\n   @Named(\"volumeType:delete\")\n   @DELETE\n   @Path(\"/{id}\")\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean delete(@PathParam(\"id\") String id);\n\n   /**\n    * Gets the extra specs for a volume type\n    *\n    * @param id the id of the volume type\n    * @return the set of extra metadata for the flavor\n    */\n   @Named(\"volumeType:getExtraSpecs\")\n   @GET\n   @Path(\"/{id}/extra_specs\")\n   @SelectJson(\"extra_specs\")\n   @Fallback(EmptyMapOnNotFoundOr404.class)\n   Map<String, String> getExtraSpecs(@PathParam(\"id\") String id);\n\n   /**\n    * Creates or updates the extra metadata for a given flavor\n    */\n   @Named(\"volumeType:updateExtraSpecs\")\n   @POST\n   @Path(\"/{id}/extra_specs\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @MapBinder(BindToJsonPayload.class)\n   void updateExtraSpecs(@PathParam(\"id\") String id, @PayloadParam(\"extra_specs\") Map<String, String> specs);\n\n   /**\n    * Retrieve a single extra spec value\n    *\n    * @param id  the id of the volume type\n    * @param key the key of the extra spec item to retrieve\n    */\n   @Named(\"volumeType:getExtraSpec\")\n   @GET\n   @Path(\"/{id}/extra_specs/{key}\")\n   @Unwrap\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   String getExtraSpec(@PathParam(\"id\") String id, @PathParam(\"key\") String key);\n\n   /**\n    * Creates or updates a single extra spec value\n    *\n    * @param id    the id of the volume type\n    * @param key   the extra spec key (when creating ensure this does not include whitespace or other difficult characters)\n    * @param value the new value to store associate with the key\n    */\n   @Named(\"volumeType:updateExtraSpec\")\n   @PUT\n   @Path(\"/{id}/extra_specs/{key}\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @Payload(\"%7B\\\"{key}\\\":\\\"{value}\\\"%7D\")\n   void updateExtraSpec(@PathParam(\"id\") String id,\n         @PathParam(\"key\") @PayloadParam(\"key\") String key,\n         @PayloadParam(\"value\") String value);\n\n   /**\n    * Deletes an existing extra spec\n    *\n    * @param id  the id of the volume type\n    * @param key the key of the extra spec to delete\n    */\n   @Named(\"volumeType:deleteExtraSpec\")\n   @DELETE\n   @Path(\"/{id}/extra_specs/{key}\")\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean deleteExtraSpec(@PathParam(\"id\") String id, @PathParam(\"key\") String key);\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/features/FlavorApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyPagedIterableOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.collect.PagedIterable;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.keystone.v2_0.KeystoneFallbacks.EmptyPaginatedCollectionOnNotFoundOr404;\nimport org.jclouds.openstack.nova.v2_0.domain.Flavor;\nimport org.jclouds.openstack.nova.v2_0.functions.internal.ParseFlavorDetails;\nimport org.jclouds.openstack.nova.v2_0.functions.internal.ParseFlavors;\nimport org.jclouds.openstack.v2_0.domain.PaginatedCollection;\nimport org.jclouds.openstack.v2_0.domain.Resource;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.Transform;\nimport org.jclouds.rest.annotations.Unwrap;\nimport org.jclouds.rest.annotations.WrapWith;\n\n/**\n * Provides access to the OpenStack Compute (Nova) Flavor API.\n * <p/>\n *\n */\n@RequestFilters(AuthenticateRequest.class)\n@Consumes(MediaType.APPLICATION_JSON)\n@Path(\"/flavors\")\npublic interface FlavorApi {\n   /**\n    * List all flavors (IDs, names, links)\n    *\n    * @return all flavors (IDs, names, links)\n    */\n   @Named(\"flavor:list\")\n   @GET\n   @ResponseParser(ParseFlavors.class)\n   @Transform(ParseFlavors.ToPagedIterable.class)\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   PagedIterable<Resource> list();\n\n   @Named(\"flavor:list\")\n   @GET\n   @ResponseParser(ParseFlavors.class)\n   @Fallback(EmptyPaginatedCollectionOnNotFoundOr404.class)\n   PaginatedCollection<Resource> list(PaginationOptions options);\n\n   /**\n    * List all flavors (all details)\n    *\n    * @return all flavors (all details)\n    */\n   @Named(\"flavor:list\")\n   @GET\n   @Path(\"/detail\")\n   @ResponseParser(ParseFlavorDetails.class)\n   @Transform(ParseFlavorDetails.ToPagedIterable.class)\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   PagedIterable<Flavor> listInDetail();\n\n   @Named(\"flavor:list\")\n   @GET\n   @Path(\"/detail\")\n   @ResponseParser(ParseFlavorDetails.class)\n   @Fallback(EmptyPaginatedCollectionOnNotFoundOr404.class)\n   PaginatedCollection<Flavor> listInDetail(PaginationOptions options);\n\n   /**\n    * List details of the specified flavor\n    *\n    * @param id\n    *           id of the flavor\n    * @return flavor or null if not found\n    */\n   @Named(\"flavor:get\")\n   @GET\n   @Path(\"/{id}\")\n   @SelectJson(\"flavor\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Flavor get(@PathParam(\"id\") String id);\n\n   /**\n    * Create flavor according to the provided object\n    *\n    * @param flavor - flavor object\n    * @return newly created flavor\n    */\n   @Named(\"flavor:create\")\n   @POST\n   @Unwrap\n   @Produces(MediaType.APPLICATION_JSON)\n   Flavor create(@WrapWith(\"flavor\") Flavor flavor);\n\n   /**\n    * Delete flavor with a given id\n    *\n    * @param id - flavor id\n    */\n   @Named(\"flavor:delete\")\n   @DELETE\n   @Path(\"/{id}\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void delete(@PathParam(\"id\") String id);\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/features/ImageApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.features;\n\nimport java.util.Map;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyMapOnNotFoundOr404;\nimport org.jclouds.Fallbacks.EmptyPagedIterableOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.collect.PagedIterable;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.v2_0.domain.PaginatedCollection;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.keystone.v2_0.KeystoneFallbacks.EmptyPaginatedCollectionOnNotFoundOr404;\nimport org.jclouds.openstack.nova.v2_0.binders.BindMetadataToJsonPayload;\nimport org.jclouds.openstack.nova.v2_0.domain.Image;\nimport org.jclouds.openstack.nova.v2_0.functions.internal.OnlyMetadataValueOrNull;\nimport org.jclouds.openstack.nova.v2_0.functions.internal.ParseImageDetails;\nimport org.jclouds.openstack.nova.v2_0.functions.internal.ParseImages;\nimport org.jclouds.openstack.v2_0.domain.Resource;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.Transform;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\n/**\n * Provides access to the OpenStack Compute (Nova) Image API.\n */\n@RequestFilters(AuthenticateRequest.class)\n@Consumes(MediaType.APPLICATION_JSON)\n@Path(\"/images\")\npublic interface ImageApi {\n   /**\n    * List all images (IDs, names, links)\n    *\n    * @return all images (IDs, names, links)\n    */\n   @Named(\"image:list\")\n   @GET\n   @ResponseParser(ParseImages.class)\n   @Transform(ParseImages.ToPagedIterable.class)\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   PagedIterable<Resource> list();\n\n   @Named(\"image:list\")\n   @GET\n   @ResponseParser(ParseImages.class)\n   @Fallback(EmptyPaginatedCollectionOnNotFoundOr404.class)\n   PaginatedCollection<Resource> list(PaginationOptions options);\n\n   /**\n    * List all images (all details)\n    *\n    * @return all images (all details)\n    */\n   @Named(\"image:list\")\n   @GET\n   @Path(\"/detail\")\n   @ResponseParser(ParseImageDetails.class)\n   @Transform(ParseImageDetails.ToPagedIterable.class)\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   PagedIterable<Image> listInDetail();\n\n   @Named(\"image:list\")\n   @GET\n   @Path(\"/detail\")\n   @ResponseParser(ParseImageDetails.class)\n   @Fallback(EmptyPaginatedCollectionOnNotFoundOr404.class)\n   PaginatedCollection<Image> listInDetail(PaginationOptions options);\n\n   /**\n    * List details of the specified image\n    *\n    * @param id\n    *           id of the server\n    * @return server or null if not found\n    */\n   @Named(\"image:get\")\n   @GET\n   @Path(\"/{id}\")\n   @SelectJson(\"image\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Image get(@PathParam(\"id\") String id);\n\n   /**\n    * Delete the specified image\n    *\n    * @param id id of the image\n    */\n   @Named(\"image:delete\")\n   @DELETE\n   @Path(\"/{id}\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void delete(@PathParam(\"id\") String id);\n\n   /**\n    * List all metadata for an image.\n    *\n    * @param id\n    *           id of the image\n    * @return the metadata as a Map<String, String>\n    */\n   @Named(\"image:getMetadata\")\n   @GET\n   @Path(\"/{id}/metadata\")\n   @SelectJson(\"metadata\")\n   @Fallback(EmptyMapOnNotFoundOr404.class)\n   Map<String, String> getMetadata(@PathParam(\"id\") String id);\n\n   /**\n    * Sets the metadata for an image.\n    *\n    * @param id\n    *           id of the image\n    * @param metadata\n    *           a Map containing the metadata\n    * @return the metadata as a Map<String, String>\n    */\n   @Named(\"image:setMetadata\")\n   @PUT\n   @Path(\"/{id}/metadata\")\n   @SelectJson(\"metadata\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @MapBinder(BindToJsonPayload.class)\n   Map<String, String> setMetadata(@PathParam(\"id\") String id, @PayloadParam(\"metadata\") Map<String, String> metadata);\n\n   /**\n    * Update the metadata for a server.\n    *\n    * @param id\n    *           id of the image\n    * @param metadata\n    *           a Map containing the metadata\n    * @return the metadata as a Map<String, String>\n    */\n   @Named(\"image:updateMetadata\")\n   @POST\n   @Path(\"/{id}/metadata\")\n   @SelectJson(\"metadata\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @MapBinder(BindToJsonPayload.class)\n   Map<String, String> updateMetadata(@PathParam(\"id\") String id, @PayloadParam(\"metadata\") Map<String, String> metadata);\n\n   /**\n    * Update the metadata for an image.\n    *\n    * @param id\n    *           id of the image\n    * @param metadata\n    *           a Map containing the metadata\n    * @return the value or null if not present\n    */\n   @Named(\"image:getMetadata\")\n   @GET\n   @Path(\"/{id}/metadata/{key}\")\n   @ResponseParser(OnlyMetadataValueOrNull.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   String getMetadata(@PathParam(\"id\") String id, @PathParam(\"key\") String key);\n\n   /**\n    * Set a metadata item for an image.\n    *\n    * @param id\n    *           id of the image\n    * @param key\n    *           the name of the metadata item\n    * @param value\n    *           the value of the metadata item\n    * @return the value you updated\n    */\n   @Named(\"image:updateMetadata\")\n   @PUT\n   @Path(\"/{id}/metadata/{key}\")\n   @ResponseParser(OnlyMetadataValueOrNull.class)\n   @MapBinder(BindMetadataToJsonPayload.class)\n   @Nullable\n   String updateMetadata(@PathParam(\"id\") String id, @PathParam(\"key\") @PayloadParam(\"key\") String key,\n         @PathParam(\"value\") @PayloadParam(\"value\") String value);\n\n   /**\n    * Delete a metadata item from an image.\n    *\n    * @param id\n    *           id of the image\n    * @param key\n    *           the name of the metadata item\n    */\n   @Named(\"image:deleteMetadata\")\n   @DELETE\n   @Path(\"/{id}/metadata/{key}\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void deleteMetadata(@PathParam(\"id\") String id, @PathParam(\"key\") String key);\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/features/ServerApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.features;\n\nimport com.google.common.base.Optional;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks;\nimport org.jclouds.Fallbacks.AbsentOn403Or404Or500;\nimport org.jclouds.Fallbacks.EmptyMapOnNotFoundOr404;\nimport org.jclouds.Fallbacks.EmptyPagedIterableOnNotFoundOr404;\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.collect.PagedIterable;\nimport org.jclouds.fallbacks.MapHttp4xxCodesToExceptions;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.nova.v2_0.domain.PortInterface;\nimport org.jclouds.openstack.nova.v2_0.domain.SecurityGroup;\nimport org.jclouds.openstack.v2_0.domain.PaginatedCollection;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.keystone.v2_0.KeystoneFallbacks.EmptyPaginatedCollectionOnNotFoundOr404;\nimport org.jclouds.openstack.nova.v2_0.binders.BindMetadataToJsonPayload;\nimport org.jclouds.openstack.nova.v2_0.domain.RebootType;\nimport org.jclouds.openstack.nova.v2_0.domain.Server;\nimport org.jclouds.openstack.nova.v2_0.domain.ServerCreated;\nimport org.jclouds.openstack.nova.v2_0.functions.ParseImageIdFromLocationHeader;\nimport org.jclouds.openstack.nova.v2_0.functions.internal.OnlyMetadataValueOrNull;\nimport org.jclouds.openstack.nova.v2_0.functions.internal.ParseDiagnostics;\nimport org.jclouds.openstack.nova.v2_0.functions.internal.ParseServerDetails;\nimport org.jclouds.openstack.nova.v2_0.functions.internal.ParseServers;\nimport org.jclouds.openstack.nova.v2_0.options.CreateServerOptions;\nimport org.jclouds.openstack.nova.v2_0.options.RebuildServerOptions;\nimport org.jclouds.openstack.v2_0.domain.Resource;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.Transform;\nimport org.jclouds.rest.annotations.Unwrap;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\n/**\n * Provides access to the OpenStack Compute (Nova) Server API.\n */\n@RequestFilters(AuthenticateRequest.class)\n@Consumes(MediaType.APPLICATION_JSON)\n@Path(\"/servers\")\npublic interface ServerApi {\n   /**\n    * List all servers (IDs, names, links)\n    *\n    * @return all servers (IDs, names, links)\n    */\n   @Named(\"server:list\")\n   @GET\n   @ResponseParser(ParseServers.class)\n   @Transform(ParseServers.ToPagedIterable.class)\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   PagedIterable<Resource> list();\n\n   @Named(\"server:list\")\n   @GET\n   @ResponseParser(ParseServers.class)\n   @Fallback(EmptyPaginatedCollectionOnNotFoundOr404.class)\n   PaginatedCollection<Resource> list(PaginationOptions options);\n\n   /**\n    * List all servers (all details)\n    *\n    * @return all servers (all details)\n    */\n   @Named(\"server:list\")\n   @GET\n   @Path(\"/detail\")\n   @ResponseParser(ParseServerDetails.class)\n   @Transform(ParseServerDetails.ToPagedIterable.class)\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   PagedIterable<Server> listInDetail();\n\n   @Named(\"server:list\")\n   @GET\n   @Path(\"/detail\")\n   @ResponseParser(ParseServerDetails.class)\n   @Fallback(EmptyPaginatedCollectionOnNotFoundOr404.class)\n   PaginatedCollection<Server> listInDetail(PaginationOptions options);\n\n   /**\n    * List details of the specified server\n    *\n    * @param id\n    *           id of the server\n    * @return server or null if not found\n    */\n   @Named(\"server:get\")\n   @GET\n   @Path(\"/{id}\")\n   @SelectJson(\"server\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Server get(@PathParam(\"id\") String id);\n\n   /**\n    * Create a new server\n    *\n    * @param name\n    *           name of the server to create\n    * @param imageRef\n    *           reference to the image for the server to use\n    * @param flavorRef\n    *           reference to the flavor to use when creating the server\n    * @param options\n    *           optional parameters to be passed into the server creation\n    *           request\n    * @return the newly created server\n    */\n   @Named(\"server:create\")\n   @POST\n   @Unwrap\n   @MapBinder(CreateServerOptions.class)\n   ServerCreated create(@PayloadParam(\"name\") String name, @PayloadParam(\"imageRef\") String imageRef,\n         @PayloadParam(\"flavorRef\") String flavorRef, CreateServerOptions... options);\n\n   /**\n    * Terminate and delete a server.\n    *\n    * @param id\n    *           id of the server\n    * @return True if successful, False otherwise\n    */\n   @Named(\"server:delete\")\n   @DELETE\n   @Path(\"/{id}\")\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean delete(@PathParam(\"id\") String id);\n\n   /**\n    * Start a server\n    *\n    * @param id\n    *           id of the server\n    */\n   @Named(\"server:start\")\n   @POST\n   @Path(\"/{id}/action\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @Payload(\"{\\\"os-start\\\":null}\")\n   void start(@PathParam(\"id\") String id);\n\n   /**\n    * Stop a server\n    *\n    * @param id\n    *           id of the server\n    */\n   @Named(\"server:stop\")\n   @POST\n   @Path(\"/{id}/action\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @Payload(\"{\\\"os-stop\\\":null}\")\n   void stop(@PathParam(\"id\") String id);\n\n   /**\n    * Reboot a server.\n    *\n    * @param id\n    *           id of the server\n    * @param rebootType\n    *           The type of reboot to perform (Hard/Soft)\n    */\n   @Named(\"server:reboot\")\n   @POST\n   @Path(\"/{id}/action\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @Payload(\"%7B\\\"reboot\\\":%7B\\\"type\\\":\\\"{type}\\\"%7D%7D\")\n   void reboot(@PathParam(\"id\") String id, @PayloadParam(\"type\") RebootType rebootType);\n\n   /**\n    * Resize a server to a new flavor size.\n    *\n    * @param id\n    *           id of the server\n    * @param flavorId\n    *           id of the new flavor to use\n    */\n   @Named(\"server:resize\")\n   @POST\n   @Path(\"/{id}/action\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @Payload(\"%7B\\\"resize\\\":%7B\\\"flavorRef\\\":{flavorId}%7D%7D\")\n   void resize(@PathParam(\"id\") String id, @PayloadParam(\"flavorId\") String flavorId);\n\n   /**\n    * Confirm a resize operation.\n    *\n    * @param id\n    *           id of the server\n    */\n   @Named(\"server:confirmResize\")\n   @POST\n   @Path(\"/{id}/action\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @Payload(\"{\\\"confirmResize\\\":null}\")\n   void confirmResize(@PathParam(\"id\") String id);\n\n   /**\n    * Revert a resize operation.\n    *\n    * @param id\n    *           id of the server\n    */\n   @Named(\"server:revertResize\")\n   @POST\n   @Path(\"/{id}/action\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @Payload(\"{\\\"revertResize\\\":null}\")\n   void revertResize(@PathParam(\"id\") String id);\n\n   /**\n    * Rebuild a server.\n    *\n    * @param id\n    *           id of the server\n    * @param options\n    *           Optional parameters to the rebuilding operation.\n    */\n   @Named(\"server:rebuild\")\n   @POST\n   @Path(\"/{id}/action\")\n   @MapBinder(RebuildServerOptions.class)\n   void rebuild(@PathParam(\"id\") String id, RebuildServerOptions... options);\n\n   /**\n    * Change the administrative password to a server.\n    *\n    * @param id\n    *           id of the server\n    * @param adminPass\n    *           The new administrative password to use\n    */\n   @Named(\"server:changeAdminPass\")\n   @POST\n   @Path(\"/{id}/action\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @Payload(\"%7B\\\"changePassword\\\":%7B\\\"adminPass\\\":\\\"{adminPass}\\\"%7D%7D\")\n   void changeAdminPass(@PathParam(\"id\") String id, @PayloadParam(\"adminPass\") String adminPass);\n\n   /**\n    * Rename a server.\n    *\n    * @param id\n    *           id of the server\n    * @param newName\n    *           The new name for the server\n    */\n   @Named(\"server:rename\")\n   @PUT\n   @Path(\"/{id}\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @Payload(\"%7B\\\"server\\\":%7B\\\"name\\\":\\\"{name}\\\"%7D%7D\")\n   void rename(@PathParam(\"id\") String id, @PayloadParam(\"name\") String newName);\n\n   /**\n    * Create an image from a server.\n    *\n    * @param name\n    *           The name of the new image\n    * @param id\n    *           id of the server\n    *\n    * @return ID of the new / updated image\n    */\n   @Named(\"server:createImageFromServer\")\n   @POST\n   @Path(\"/{id}/action\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @Payload(\"%7B\\\"createImage\\\":%7B\\\"name\\\":\\\"{name}\\\", \\\"metadata\\\": %7B%7D%7D%7D\")\n   @ResponseParser(ParseImageIdFromLocationHeader.class)\n   @Fallback(MapHttp4xxCodesToExceptions.class)\n   String createImageFromServer(@PayloadParam(\"name\") String name, @PathParam(\"id\") String id);\n\n   /**\n    * List all metadata for a server.\n    *\n    * @param id\n    *           id of the server\n    *\n    * @return the metadata as a Map<String, String>\n    */\n   @Named(\"server:getMetadata\")\n   @GET\n   @Path(\"/{id}/metadata\")\n   @SelectJson(\"metadata\")\n   @Fallback(EmptyMapOnNotFoundOr404.class)\n   Map<String, String> getMetadata(@PathParam(\"id\") String id);\n\n   /**\n    * Set the metadata for a server.\n    *\n    * @param id\n    *           id of the server\n    * @param metadata\n    *           a Map containing the metadata\n    * @return the metadata as a Map<String, String>\n    */\n   @Named(\"server:setMetadata\")\n   @PUT\n   @Path(\"/{id}/metadata\")\n   @SelectJson(\"metadata\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @MapBinder(BindToJsonPayload.class)\n   Map<String, String> setMetadata(@PathParam(\"id\") String id,\n         @PayloadParam(\"metadata\") Map<String, String> metadata);\n\n   /**\n    * Update the metadata for a server.\n    *\n    * @param id\n    *           id of the server\n    * @param metadata\n    *           a Map containing the metadata\n    * @return the metadata as a Map<String, String>\n    */\n   @Named(\"server:updateMetadata\")\n   @POST\n   @Path(\"/{id}/metadata\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @SelectJson(\"metadata\")\n   @MapBinder(BindToJsonPayload.class)\n   Map<String, String> updateMetadata(@PathParam(\"id\") String id,\n         @PayloadParam(\"metadata\") Map<String, String> metadata);\n\n   /**\n    * Update the metadata for a server.\n    *\n    * @param id\n    *           id of the image\n    * @param key\n    *           a key containing the metadata\n    * @return the value or null if not present\n    */\n   @Named(\"server:getMetadata\")\n   @GET\n   @Path(\"/{id}/metadata/{key}\")\n   @ResponseParser(OnlyMetadataValueOrNull.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   String getMetadata(@PathParam(\"id\") String id, @PathParam(\"key\") String key);\n\n   /**\n    * Set a metadata item for a server.\n    *\n    * @param id\n    *           id of the image\n    * @param key\n    *           the name of the metadata item\n    * @param value\n    *           the value of the metadata item\n    * @return the value you updated\n    */\n   @Named(\"server:updateMetadata\")\n   @PUT\n   @Path(\"/{id}/metadata/{key}\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @ResponseParser(OnlyMetadataValueOrNull.class)\n   @MapBinder(BindMetadataToJsonPayload.class)\n   String updateMetadata(@PathParam(\"id\") String id, @PathParam(\"key\") @PayloadParam(\"key\") String key,\n         @PathParam(\"value\") @PayloadParam(\"value\") String value);\n\n   /**\n    * Delete a metadata item from a server.\n    *\n    * @param id\n    *           id of the image\n    * @param key\n    *           the name of the metadata item\n    */\n   @Named(\"server:deleteMetadata\")\n   @DELETE\n   @Path(\"/{id}/metadata/{key}\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void deleteMetadata(@PathParam(\"id\") String id, @PathParam(\"key\") String key);\n\n   /**\n    * Get usage information about the server such as CPU usage, Memory and IO.\n    * The information returned by this method is dependent on the hypervisor\n    * in use by the OpenStack installation and whether that hypervisor supports\n    * this method. More information can be found in the\n    * <a href=\"http://api.openstack.org/api-ref.html\"> OpenStack API\n    * reference</a>. <br/>\n    * At the moment the returned response is a generic map. In future versions\n    * of OpenStack this might be subject to change.\n    *\n    * @param id\n    *           id of the server\n    * @return A Map containing the collected values organized by key - value.\n    */\n   @Named(\"server:getDiagnostics\")\n   @GET\n   @Path(\"/{id}/diagnostics\")\n   @ResponseParser(ParseDiagnostics.class)\n   @Fallback(AbsentOn403Or404Or500.class)\n   Optional<Map<String, String>> getDiagnostics(@PathParam(\"id\") String id);\n\n   /**\n    * Lists Security Groups for a server.\n\n    * @param id\n    *           id of the server\n    * @return a list of security groups attached to the server\n    */\n   @Named(\"server:getSecurityGroups\")\n   @GET\n   @Path(\"/{id}/os-security-groups\")\n   @SelectJson(\"security_groups\")\n   @Fallback(Fallbacks.EmptySetOnNotFoundOr404.class)\n   Set<SecurityGroup> listSecurityGroupForServer(@PathParam(\"id\") String id);\n\n   /**\n    * Lists port interfaces that are attached to a server.\n    *\n    * @param id\n    *           id of the server\n    * @return a list of ports attached to the server\n    */\n   @Named(\"server:getPortInterfaces\")\n   @GET\n   @Path(\"/{id}/os-interface\")\n   @SelectJson(\"interfaceAttachments\")\n   @Fallback(Fallbacks.EmptySetOnNotFoundOr404.class)\n   Set<PortInterface> listPortInterfaces(@PathParam(\"id\") String id);\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/functions/FieldValueResponseParsers.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.functions;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseFirstJsonValueNamed;\nimport org.jclouds.json.internal.GsonWrapper;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Objects;\nimport com.google.inject.Inject;\nimport com.google.inject.Singleton;\nimport com.google.inject.TypeLiteral;\n\n/**\n * Parsers for extracting a single field value from a response and comparing it to an expected value\n */\npublic class FieldValueResponseParsers {\n   @Singleton\n   public static class StatusEnabledResponseParser extends FieldValueResponseParser<String> {\n      @Inject\n      public StatusEnabledResponseParser(GsonWrapper wrapper) {\n         super(wrapper, \"status\", \"enabled\");\n      }\n   }\n\n   @Singleton\n   public static class StatusDisabledResponseParser extends FieldValueResponseParser<String> {\n      @Inject\n      public StatusDisabledResponseParser(GsonWrapper wrapper) {\n         super(wrapper, \"status\", \"disabled\");\n      }\n   }\n\n   @Singleton\n   public static class MaintenanceModeEnabledResponseParser extends FieldValueResponseParser<String> {\n      @Inject\n      public MaintenanceModeEnabledResponseParser(GsonWrapper wrapper) {\n         super(wrapper, \"maintenance_mode\", \"on_maintenance\");\n      }\n   }\n\n   @Singleton\n   public static class MaintenanceModeDisabledResponseParser extends FieldValueResponseParser<String> {\n      @Inject\n      public MaintenanceModeDisabledResponseParser(GsonWrapper wrapper) {\n         super(wrapper, \"maintenance_mode\", \"off_maintenance\");\n      }\n   }\n\n   @Singleton\n   public static class PowerIsStartupResponseParser extends FieldValueResponseParser<String> {\n      @Inject\n      public PowerIsStartupResponseParser(GsonWrapper wrapper) {\n         super(wrapper, \"power_action\", \"startup\");\n      }\n   }\n\n   @Singleton\n   public static class PowerIsShutdownResponseParser extends FieldValueResponseParser<String> {\n      @Inject\n      public PowerIsShutdownResponseParser(GsonWrapper wrapper) {\n         super(wrapper, \"power_action\", \"shutdown\");\n      }\n   }\n\n   @Singleton\n   public static class PowerIsRebootResponseParser extends FieldValueResponseParser<String> {\n      @Inject\n      public PowerIsRebootResponseParser(GsonWrapper wrapper) {\n         super(wrapper, \"power_action\", \"reboot\");\n      }\n   }\n\n   public abstract static class FieldValueResponseParser<T> implements Function<HttpResponse, Boolean> {\n      private final T expectedValue;\n      private final ParseFirstJsonValueNamed<T> valueParser;\n\n      public FieldValueResponseParser(GsonWrapper wrapper, String fieldName, T expectedValue) {\n         valueParser = new ParseFirstJsonValueNamed<T>(wrapper, new TypeLiteral<T>() {\n         }, fieldName);\n         this.expectedValue = expectedValue;\n      }\n\n      @Override\n      public Boolean apply(HttpResponse response) {\n         return Objects.equal(expectedValue, valueParser.apply(response));\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/functions/OverLimitParser.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\n\nimport org.jclouds.json.Json;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * \n * The expected body contains the time as in this (real) response\n * \n * <pre>\n *   {\n * \"overLimit\" : {\n *  \"code\" : 413,\n *  \"message\" : \"OverLimit Retry...\",\n *  \"details\" : \"Error Details...\",\n *  \"retryAt\" : \"2012-11-14T21:51:28UTC\"\n *  }\n * }\n * </pre>\n * \n * or\n * \n * <pre>\n *    {\n *      \"overLimit\": {\n *        \"message\": \"This request was rate-limited.\",\n *        \"code\": 413,\n *        \"retryAfter\": \"54\",\n *        \"details\": \"Only 1 POST request(s) can be made to \\\"*\\\" every minute.\"\n *      }\n *    }\n * </pre>\n */\npublic class OverLimitParser implements Function<String, Map<String, String>> {\n   \n   @Resource\n   private Logger logger = Logger.NULL;\n   private final Json json;\n\n   @Inject\n   public OverLimitParser(Json json) {\n      this.json = checkNotNull(json, \"json\");\n   }\n\n   private static class Holder {\n      Map<String, String> overLimit = ImmutableMap.of();\n   }\n\n   /**\n    * parses or returns an empty map.\n    */\n   @Override\n   public Map<String, String> apply(String in) {\n      try {\n         return json.fromJson(in, OverLimitParser.Holder.class).overLimit;\n      } catch (RuntimeException e) {\n         // an error was raised during parsing -which can include badly\n         // formatted fields.\n         logger.error(\"Failed to parse \" + in + \"\", e);\n         return ImmutableMap.of();\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/functions/ParseImageIdFromLocationHeader.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.functions;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpResponse;\n\nimport com.google.common.base.Function;\nimport com.google.common.net.HttpHeaders;\n\n/**\n * This parses {@link Image} from the body of the link in the Location header of the HTTPResponse.\n */\n@Singleton\npublic class ParseImageIdFromLocationHeader implements Function<HttpResponse, String> {\n\n\tpublic String apply(HttpResponse response) {\n        String location = response.getFirstHeaderOrNull(HttpHeaders.LOCATION);\n        String[] parts = location.split(\"/\");\n        return parts[parts.length - 1];\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/functions/internal/OnlyMetadataValueOrNull.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.functions.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.internal.GsonWrapper;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.Iterables;\nimport com.google.inject.Inject;\nimport com.google.inject.TypeLiteral;\n\n@Singleton\npublic class OnlyMetadataValueOrNull implements Function<HttpResponse, String> {\n   private final ParseJson<Wrapper> parser;\n\n   private static class Wrapper implements Supplier<String> {\n      private Map<String, String> metadata;\n\n      @Override\n      public String get() {\n         return metadata == null ? null : Iterables.get(metadata.values(), 0, null);\n      }\n\n   }\n\n   @Inject\n   public OnlyMetadataValueOrNull(GsonWrapper gsonView) {\n      this.parser = new ParseJson<Wrapper>(checkNotNull(gsonView, \"gsonView\"), new TypeLiteral<Wrapper>() {\n      });\n   }\n\n   public String apply(HttpResponse response) {\n      checkNotNull(response, \"response\");\n      return parser.apply(response).get();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/functions/internal/ParseDiagnostics.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.functions.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseJson;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.inject.Inject;\nimport java.util.Map;\n\npublic class ParseDiagnostics implements Function<HttpResponse, Optional <Map<String, String>>> {\n\n\n   private final ParseJson<Optional <Map<String, String>>> parser;\n   \n   @Inject\n   public ParseDiagnostics(ParseJson<Optional <Map<String, String>>> parser) {\n      this.parser = parser;\n   }\n\n   @Override\n   public Optional <Map<String, String>> apply(HttpResponse response) {\n      checkNotNull(response, \"response\");\n      return parser.apply(response);\n   }\n    \n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/functions/internal/ParseFlavorDetails.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.functions.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.internal.Arg0ToPagedIterable;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\nimport org.jclouds.openstack.nova.v2_0.NovaApi;\nimport org.jclouds.openstack.nova.v2_0.domain.Flavor;\nimport org.jclouds.openstack.nova.v2_0.features.FlavorApi;\nimport org.jclouds.openstack.nova.v2_0.functions.internal.ParseFlavorDetails.Flavors;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.PaginatedCollection;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.inject.TypeLiteral;\n\n/**\n * boiler plate until we determine a better way\n */\n@Beta\n@Singleton\npublic class ParseFlavorDetails extends ParseJson<Flavors> {\n   static class Flavors extends PaginatedCollection<Flavor> {\n\n      @ConstructorProperties({ \"flavors\", \"flavors_links\" })\n      protected Flavors(Iterable<Flavor> flavors, Iterable<Link> flavors_links) {\n         super(flavors, flavors_links);\n      }\n\n   }\n\n   @Inject\n   public ParseFlavorDetails(Json json) {\n      super(json, TypeLiteral.get(Flavors.class));\n   }\n\n   public static class ToPagedIterable extends Arg0ToPagedIterable.FromCaller<Flavor, ToPagedIterable> {\n\n      private final NovaApi api;\n\n      @Inject\n      protected ToPagedIterable(NovaApi api) {\n         this.api = checkNotNull(api, \"api\");\n      }\n\n      @Override\n      protected Function<Object, IterableWithMarker<Flavor>> markerToNextForArg0(Optional<Object> arg0) {\n         String region = arg0.get().toString();\n         final FlavorApi flavorApi = api.getFlavorApi(region);\n         return new Function<Object, IterableWithMarker<Flavor>>() {\n\n            @SuppressWarnings(\"unchecked\")\n            @Override\n            public IterableWithMarker<Flavor> apply(Object input) {\n               PaginationOptions paginationOptions = PaginationOptions.class.cast(input);\n               return IterableWithMarker.class.cast(flavorApi.listInDetail(paginationOptions));\n            }\n\n            @Override\n            public String toString() {\n               return \"listFlavorsInDetail()\";\n            }\n         };\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/functions/internal/ParseFlavors.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.functions.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport com.google.common.base.Optional;\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.internal.Arg0ToPagedIterable;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\nimport org.jclouds.openstack.v2_0.domain.PaginatedCollection;\nimport org.jclouds.openstack.nova.v2_0.NovaApi;\nimport org.jclouds.openstack.nova.v2_0.features.FlavorApi;\nimport org.jclouds.openstack.nova.v2_0.functions.internal.ParseFlavors.Flavors;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.Resource;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Function;\nimport com.google.inject.TypeLiteral;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\n\n/**\n * boiler plate until we determine a better way\n */\n@Beta\n@Singleton\npublic class ParseFlavors extends ParseJson<Flavors> {\n   static class Flavors extends PaginatedCollection<Resource> {\n\n      @ConstructorProperties({ \"flavors\", \"flavors_links\" })\n      protected Flavors(Iterable<Resource> flavors, Iterable<Link> flavors_links) {\n         super(flavors, flavors_links);\n      }\n\n   }\n\n   @Inject\n   public ParseFlavors(Json json) {\n      super(json, TypeLiteral.get(Flavors.class));\n   }\n\n   public static class ToPagedIterable extends Arg0ToPagedIterable.FromCaller<Resource, ToPagedIterable> {\n\n      private final NovaApi api;\n\n      @Inject\n      protected ToPagedIterable(NovaApi api) {\n         this.api = checkNotNull(api, \"api\");\n      }\n\n      @Override\n      protected Function<Object, IterableWithMarker<Resource>> markerToNextForArg0(Optional<Object> arg0) {\n         String region = arg0.get().toString();\n         final FlavorApi flavorApi = api.getFlavorApi(region);\n         return new Function<Object, IterableWithMarker<Resource>>() {\n\n            @SuppressWarnings(\"unchecked\")\n            @Override\n            public IterableWithMarker<Resource> apply(Object input) {\n               PaginationOptions paginationOptions = PaginationOptions.class.cast(input);\n               return IterableWithMarker.class.cast(flavorApi.list(paginationOptions));\n            }\n\n            @Override\n            public String toString() {\n               return \"listFlavors()\";\n            }\n         };\n      }\n\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/functions/internal/ParseImageDetails.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.functions.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport com.google.common.base.Optional;\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.internal.Arg0ToPagedIterable;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\nimport org.jclouds.openstack.v2_0.domain.PaginatedCollection;\nimport org.jclouds.openstack.nova.v2_0.NovaApi;\nimport org.jclouds.openstack.nova.v2_0.domain.Image;\nimport org.jclouds.openstack.nova.v2_0.features.ImageApi;\nimport org.jclouds.openstack.nova.v2_0.functions.internal.ParseImageDetails.Images;\nimport org.jclouds.openstack.v2_0.domain.Link;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Function;\nimport com.google.inject.TypeLiteral;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\n\n/**\n * boiler plate until we determine a better way\n */\n@Beta\n@Singleton\npublic class ParseImageDetails extends ParseJson<Images> {\n   static class Images extends PaginatedCollection<Image> {\n\n      @ConstructorProperties({ \"images\", \"images_links\" })\n      protected Images(Iterable<Image> images, Iterable<Link> images_links) {\n         super(images, images_links);\n      }\n\n   }\n\n   @Inject\n   public ParseImageDetails(Json json) {\n      super(json, TypeLiteral.get(Images.class));\n   }\n\n   public static class ToPagedIterable extends Arg0ToPagedIterable.FromCaller<Image, ToPagedIterable> {\n\n      private final NovaApi api;\n\n      @Inject\n      protected ToPagedIterable(NovaApi api) {\n         this.api = checkNotNull(api, \"api\");\n      }\n\n      @Override\n      protected Function<Object, IterableWithMarker<Image>> markerToNextForArg0(Optional<Object> arg0) {\n         String region = arg0.get().toString();\n         final ImageApi imageApi = api.getImageApi(region);\n         return new Function<Object, IterableWithMarker<Image>>() {\n\n            @SuppressWarnings(\"unchecked\")\n            @Override\n            public IterableWithMarker<Image> apply(Object input) {\n               PaginationOptions paginationOptions = PaginationOptions.class.cast(input);\n               return IterableWithMarker.class.cast(imageApi.listInDetail(paginationOptions));\n            }\n\n            @Override\n            public String toString() {\n               return \"listInDetail()\";\n            }\n         };\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/functions/internal/ParseImages.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.functions.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.internal.Arg0ToPagedIterable;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\nimport org.jclouds.openstack.nova.v2_0.NovaApi;\nimport org.jclouds.openstack.nova.v2_0.features.ImageApi;\nimport org.jclouds.openstack.nova.v2_0.functions.internal.ParseImages.Images;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.PaginatedCollection;\nimport org.jclouds.openstack.v2_0.domain.Resource;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.inject.TypeLiteral;\n\n/**\n * boiler plate until we determine a better way\n */\n@Beta\n@Singleton\npublic class ParseImages extends ParseJson<Images> {\n   static class Images extends PaginatedCollection<Resource> {\n\n      @ConstructorProperties({ \"images\", \"images_links\" })\n      protected Images(Iterable<Resource> images, Iterable<Link> images_links) {\n         super(images, images_links);\n      }\n\n   }\n\n   @Inject\n   public ParseImages(Json json) {\n      super(json, TypeLiteral.get(Images.class));\n   }\n\n   public static class ToPagedIterable extends Arg0ToPagedIterable.FromCaller<Resource, ToPagedIterable> {\n\n      private final NovaApi api;\n\n      @Inject\n      protected ToPagedIterable(NovaApi api) {\n         this.api = checkNotNull(api, \"api\");\n      }\n\n      @Override\n      protected Function<Object, IterableWithMarker<Resource>> markerToNextForArg0(Optional<Object> arg0) {\n         String region = arg0.get().toString();\n         final ImageApi imageApi = api.getImageApi(region);\n         return new Function<Object, IterableWithMarker<Resource>>() {\n\n            @SuppressWarnings(\"unchecked\")\n            @Override\n            public IterableWithMarker<Resource> apply(Object input) {\n               PaginationOptions paginationOptions = PaginationOptions.class.cast(input);\n               return IterableWithMarker.class.cast(imageApi.list(paginationOptions));\n            }\n\n            @Override\n            public String toString() {\n               return \"list()\";\n            }\n         };\n      }\n\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/functions/internal/ParseKeyPairs.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.functions.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseFirstJsonValueNamed;\nimport org.jclouds.json.internal.GsonWrapper;\nimport org.jclouds.openstack.nova.v2_0.domain.KeyPair;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.FluentIterable;\nimport com.google.inject.Inject;\nimport com.google.inject.TypeLiteral;\n\n@Singleton\npublic class ParseKeyPairs implements Function<HttpResponse, FluentIterable<? extends KeyPair>> {\n   private final ParseFirstJsonValueNamed<FluentIterable<Wrapper>> parser;\n\n   private static class Wrapper implements Supplier<KeyPair> {\n      private KeyPair keypair;\n\n      @Override\n      public KeyPair get() {\n         return keypair;\n      }\n\n   }\n\n   @Inject\n   public ParseKeyPairs(GsonWrapper gsonView) {\n      this.parser = new ParseFirstJsonValueNamed<FluentIterable<Wrapper>>(checkNotNull(gsonView, \"gsonView\"),\n               new TypeLiteral<FluentIterable<Wrapper>>() {\n               }, \"keypairs\");\n   }\n\n   public FluentIterable<? extends KeyPair> apply(HttpResponse response) {\n      checkNotNull(response, \"response\");\n      return parser.apply(response).transform(Suppliers.<KeyPair> supplierFunction());\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/functions/internal/ParseServerDetails.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.functions.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport com.google.common.base.Optional;\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.internal.Arg0ToPagedIterable;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\nimport org.jclouds.openstack.v2_0.domain.PaginatedCollection;\nimport org.jclouds.openstack.nova.v2_0.NovaApi;\nimport org.jclouds.openstack.nova.v2_0.domain.Server;\nimport org.jclouds.openstack.nova.v2_0.features.ServerApi;\nimport org.jclouds.openstack.nova.v2_0.functions.internal.ParseServerDetails.Servers;\nimport org.jclouds.openstack.v2_0.domain.Link;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Function;\nimport com.google.inject.TypeLiteral;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\n\n/**\n * boiler plate until we determine a better way\n */\n@Beta\n@Singleton\npublic class ParseServerDetails extends ParseJson<Servers> {\n   static class Servers extends PaginatedCollection<Server> {\n\n      @ConstructorProperties({ \"servers\", \"servers_links\" })\n      protected Servers(Iterable<Server> servers, Iterable<Link> servers_links) {\n         super(servers, servers_links);\n      }\n\n   }\n\n   @Inject\n   public ParseServerDetails(Json json) {\n      super(json, TypeLiteral.get(Servers.class));\n   }\n\n   public static class ToPagedIterable extends Arg0ToPagedIterable.FromCaller<Server, ToPagedIterable> {\n\n      private final NovaApi api;\n\n      @Inject\n      protected ToPagedIterable(NovaApi api) {\n         this.api = checkNotNull(api, \"api\");\n      }\n\n      @Override\n      protected Function<Object, IterableWithMarker<Server>> markerToNextForArg0(Optional<Object> arg0) {\n         String region = arg0.get().toString();\n         final ServerApi serverApi = api.getServerApi(region);\n         return new Function<Object, IterableWithMarker<Server>>() {\n\n            @SuppressWarnings(\"unchecked\")\n            @Override\n            public IterableWithMarker<Server> apply(Object input) {\n               PaginationOptions paginationOptions = PaginationOptions.class.cast(input);\n               return IterableWithMarker.class.cast(serverApi.listInDetail(paginationOptions));\n            }\n\n            @Override\n            public String toString() {\n               return \"listInDetail()\";\n            }\n         };\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/functions/internal/ParseServers.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.functions.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.internal.Arg0ToPagedIterable;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\nimport org.jclouds.openstack.nova.v2_0.NovaApi;\nimport org.jclouds.openstack.nova.v2_0.features.ServerApi;\nimport org.jclouds.openstack.nova.v2_0.functions.internal.ParseServers.Servers;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.PaginatedCollection;\nimport org.jclouds.openstack.v2_0.domain.Resource;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.inject.TypeLiteral;\n\n/**\n * boiler plate until we determine a better way\n */\n@Beta\n@Singleton\npublic class ParseServers extends ParseJson<Servers> {\n   static class Servers extends PaginatedCollection<Resource> {\n\n      @ConstructorProperties({ \"servers\", \"servers_links\" })\n      protected Servers(Iterable<Resource> servers, Iterable<Link> servers_links) {\n         super(servers, servers_links);\n      }\n\n   }\n\n   @Inject\n   public ParseServers(Json json) {\n      super(json, TypeLiteral.get(Servers.class));\n   }\n\n   public static class ToPagedIterable extends Arg0ToPagedIterable.FromCaller<Resource, ToPagedIterable> {\n\n      private final NovaApi api;\n\n      @Inject\n      protected ToPagedIterable(NovaApi api) {\n         this.api = checkNotNull(api, \"api\");\n      }\n\n      @Override\n      protected Function<Object, IterableWithMarker<Resource>> markerToNextForArg0(Optional<Object> arg0) {\n         String region = arg0.get().toString();\n         final ServerApi serverApi = api.getServerApi(region);\n         return new Function<Object, IterableWithMarker<Resource>>() {\n\n            @SuppressWarnings(\"unchecked\")\n            @Override\n            public IterableWithMarker<Resource> apply(Object input) {\n               PaginationOptions paginationOptions = PaginationOptions.class.cast(input);\n               return IterableWithMarker.class.cast(serverApi.list(paginationOptions));\n            }\n\n            @Override\n            public String toString() {\n               return \"list()\";\n            }\n         };\n      }\n\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/handlers/NovaErrorHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.handlers;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Predicates.in;\nimport static com.google.common.base.Strings.emptyToNull;\nimport static com.google.common.collect.Maps.filterKeys;\nimport static org.jclouds.http.HttpUtils.closeClientButKeepContentStream;\n\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Constants;\nimport org.jclouds.date.DateCodecFactory;\nimport org.jclouds.fallbacks.HeaderToRetryAfterException;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.openstack.nova.v2_0.functions.OverLimitParser;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.InsufficientResourcesException;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.jclouds.rest.RetryAfterException;\n\nimport com.google.common.base.Optional;\nimport com.google.common.base.Ticker;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * This will parse and set an appropriate exception on the command object.\n */\n// TODO: is there error spec someplace? let's type errors, etc.\n@Singleton\npublic class NovaErrorHandler implements HttpErrorHandler {\n\n   @com.google.inject.Inject(optional = true)\n   @Named(Constants.PROPERTY_LOGGER_WIRE_LOG_SENSITIVE_INFO)\n   private boolean logSensitiveInformation = false;\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n   protected final HeaderToRetryAfterException retryAfterParser;\n   protected final OverLimitParser overLimitParser;\n\n   protected NovaErrorHandler(HeaderToRetryAfterException retryAfterParser, OverLimitParser overLimitParser) {\n      this.retryAfterParser = checkNotNull(retryAfterParser, \"retryAfterParser\");\n      this.overLimitParser = checkNotNull(overLimitParser, \"overLimitParser\");\n   }\n\n   /**\n    * in current format, retryAt has a value of {@code 2012-11-14T21:51:28UTC}, which is an ISO-8601 seconds (not milliseconds) format.\n    */\n   @Inject\n   public NovaErrorHandler(DateCodecFactory factory, OverLimitParser overLimitParser) {\n      this(HeaderToRetryAfterException.create(Ticker.systemTicker(), factory.iso8601Seconds()), overLimitParser);\n   }\n\n   public void handleError(HttpCommand command, HttpResponse response) {\n      // it is important to always read fully and close streams\n      byte[] data = closeClientButKeepContentStream(response);\n      String content = data != null ? emptyToNull(new String(data)) : null;\n\n      Exception exception = content != null ? new HttpResponseException(command, response, content)\n            : new HttpResponseException(command, response, logSensitiveInformation);\n      String requestLine = command.getCurrentRequest().getRequestLine();\n      String message = content != null ? content : String.format(\"%s -> %s\", requestLine, response.getStatusLine());\n      switch (response.getStatusCode()) {\n         case 400:\n            if (message.indexOf(\"quota exceeded\") != -1)\n               exception = new InsufficientResourcesException(message, exception);\n            else if (message.indexOf(\"has no fixed_ips\") != -1)\n               exception = new IllegalStateException(message, exception);\n            else if (message.indexOf(\"already exists\") != -1)\n               exception = new IllegalStateException(message, exception);\n            break;\n         case 401:\n         case 403:\n            exception = new AuthorizationException(message, exception);\n            break;\n         case 404:\n            if (!command.getCurrentRequest().getMethod().equals(\"DELETE\")) {\n               exception = new ResourceNotFoundException(message, exception);\n            }\n            break;\n         case 500:\n            // this is needed as FloatingIPApi.allocateFromPool returns 500 when floating ips are over quota\n            if (command.getCurrentRequest().getMethod().equals(\"POST\") &&\n                    message.indexOf(\"The server has either erred or is incapable of performing the requested operation.\") != -1 &&\n                    command.getCurrentRequest().getEndpoint().getPath().indexOf(\"os-floating-ips\") != -1) {\n             exception = new InsufficientResourcesException(message, exception);\n           }\n           break;\n         case 413:\n            if (content == null) {\n               exception = new InsufficientResourcesException(message, exception);\n               break;\n            }\n            exception = parseAndBuildRetryException(content, message, exception);\n      }\n      command.setException(exception);\n   }\n\n   /**\n    * Build an exception from the response. If it contains the JSON payload then\n    * that is parsed to create a {@link RetryAfterException}, otherwise a\n    * {@link InsufficientResourcesException} is returned\n    *\n    */\n   private Exception parseAndBuildRetryException(String json, String message, Exception exception) {\n      Set<String> retryFields = ImmutableSet.of(\"retryAfter\", \"retryAt\");\n      for (String value : filterKeys(overLimitParser.apply(json), in(retryFields)).values()) {\n         Optional<RetryAfterException> retryException = retryAfterParser.tryCreateRetryAfterException(exception, value);\n         if (retryException.isPresent())\n            return retryException.get();\n      }\n      return new InsufficientResourcesException(message, exception);\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/options/CreateBackupOfServerOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.options;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.MapBinder;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Maps;\n\npublic class CreateBackupOfServerOptions implements MapBinder {\n   public static final CreateBackupOfServerOptions NONE = new CreateBackupOfServerOptions();\n\n   @Inject\n   protected BindToJsonPayload jsonBinder;\n\n   private Map<String, String> metadata = ImmutableMap.of();\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      Map<String, Object> data = Maps.newHashMap();\n      data.putAll(postParams);\n      data.put(\"metadata\", metadata);\n      return jsonBinder.bindToRequest(request, ImmutableMap.of(\"createBackup\", data));\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object toBind) {\n      throw new IllegalStateException(\"createBackup is a POST operation\");\n   }\n\n   @Override\n   public boolean equals(Object object) {\n      if (this == object) {\n         return true;\n      }\n      if (!(object instanceof CreateBackupOfServerOptions)) return false;\n      final CreateBackupOfServerOptions other = CreateBackupOfServerOptions.class.cast(object);\n      return equal(metadata, other.metadata);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(metadata);\n   }\n\n   protected ToStringHelper string() {\n      return toStringHelper(\"\").add(\"metadata\", metadata);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   /** @see #getMetadata() */\n   public CreateBackupOfServerOptions metadata(Map<String, String> metadata) {\n      this.metadata = metadata;\n      return this;\n   }\n\n   /**\n    * Extra image properties to include\n    */\n   public Map<String, String> getMetadata() {\n      return metadata;\n   }\n\n   public static class Builder {\n      /**\n       * @see CreateBackupOfServerOptions#getMetadata()\n       */\n      public static CreateBackupOfServerOptions metadata(Map<String, String> metadata) {\n         return new CreateBackupOfServerOptions().metadata(metadata);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/options/CreateServerOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.options;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Strings.emptyToNull;\nimport static com.google.common.io.BaseEncoding.base64;\n\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.openstack.nova.v2_0.domain.BlockDeviceMapping;\nimport org.jclouds.openstack.nova.v2_0.domain.Network;\nimport org.jclouds.rest.MapBinder;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ForwardingObject;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Lists;\nimport com.google.common.collect.Sets;\n\npublic class CreateServerOptions implements MapBinder {\n   @Inject\n   private BindToJsonPayload jsonBinder;\n\n   static class File {\n      private final String path;\n      private final String contents;\n\n      public File(String path, byte[] contents) {\n         this.path = checkNotNull(path, \"path\");\n         this.contents = base64().encode(checkNotNull(contents, \"contents\"));\n         checkArgument(\n               path.getBytes().length < 255,\n               String.format(\"maximum length of path is 255 bytes.  Path specified %s is %d bytes\", path,\n                     path.getBytes().length));\n      }\n\n      public String getContents() {\n         return contents;\n      }\n\n      public String getPath() {\n         return path;\n      }\n\n      @Override\n      public boolean equals(Object object) {\n         if (this == object) {\n            return true;\n         }\n         if (object instanceof File) {\n            final File other = File.class.cast(object);\n            return equal(path, other.path);\n         } else {\n            return false;\n         }\n      }\n\n      @Override\n      public int hashCode() {\n         return Objects.hashCode(path);\n      }\n\n      @Override\n      public String toString() {\n         return toStringHelper(\"file\").add(\"path\", path).toString();\n      }\n\n   }\n\n   private String keyName;\n   private String adminPass;\n   private Set<String> securityGroupNames = ImmutableSet.of();\n   private Map<String, String> metadata = ImmutableMap.of();\n   private List<File> personality = Lists.newArrayList();\n   private byte[] userData;\n   private String diskConfig;\n   private List<String> networks = ImmutableList.of();\n   private List<Network> novaNetworks = ImmutableList.of();\n   private String availabilityZone;\n   private boolean configDrive;\n   private Set<BlockDeviceMapping> blockDeviceMappings = ImmutableSet.of();\n\n   @Override\n   public boolean equals(Object object) {\n      if (this == object) {\n         return true;\n      }\n      if (object instanceof CreateServerOptions) {\n         final CreateServerOptions other = CreateServerOptions.class.cast(object);\n         return equal(keyName, other.keyName) && equal(adminPass, other.adminPass)\n               && equal(securityGroupNames, other.securityGroupNames) && equal(metadata, other.metadata)\n               && equal(personality, other.personality)\n               && equal(diskConfig, other.diskConfig)\n               && equal(networks, other.networks)\n               && equal(availabilityZone, other.availabilityZone)\n               && equal(configDrive, other.configDrive)\n               && equal(blockDeviceMappings, other.blockDeviceMappings);\n      } else {\n         return false;\n      }\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(keyName, adminPass, securityGroupNames, metadata, personality, networks, availabilityZone,\n            configDrive, blockDeviceMappings);\n   }\n\n   protected String formatPossiblyGzipped(final byte [] data) {\n      if (data.length > 10 && data[0] == 31 && data[1] == -117) {\n         return String.format(\"<gzipped data (%d bytes)>\", data.length);\n      }\n      return new String(data);\n   }\n\n   protected ToStringHelper string() {\n      ToStringHelper toString = MoreObjects.toStringHelper(this);\n      toString.add(\"keyName\", keyName);\n      if (!securityGroupNames.isEmpty())\n         toString.add(\"securityGroupNames\", securityGroupNames);\n      if (!metadata.isEmpty())\n         toString.add(\"metadata\", metadata);\n      if (!personality.isEmpty())\n         toString.add(\"personality\", personality);\n      if (adminPass != null)\n         toString.add(\"adminPassPresent\", true);\n      if (diskConfig != null)\n         toString.add(\"diskConfig\", diskConfig);\n      toString.add(\"userData\", userData == null ? null : formatPossiblyGzipped(userData));\n      if (!networks.isEmpty())\n         toString.add(\"networks\", networks);\n      toString.add(\"availabilityZone\", availabilityZone == null ? null : availabilityZone);\n      toString.add(\"configDrive\", configDrive);\n      if (!blockDeviceMappings.isEmpty())\n         toString.add(\"blockDeviceMappings\", blockDeviceMappings);\n      return toString;\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   static class ServerRequest {\n      final String name;\n      final String imageRef;\n      final String flavorRef;\n      @Named(\"availability_zone\")\n      String availabilityZone;\n      String adminPass;\n      Map<String, String> metadata;\n      List<File> personality;\n      String key_name;\n      @Named(\"security_groups\")\n      Set<NamedThingy> securityGroupNames;\n      String user_data;\n      @Named(\"OS-DCF:diskConfig\")\n      String diskConfig;\n      List<Map<String, String>> networks;\n      @Named(\"config_drive\")\n      String configDrive;\n      @Named(\"block_device_mapping_v2\")\n      Set<BlockDeviceMapping> blockDeviceMappings;\n\n      private ServerRequest(String name, String imageRef, String flavorRef) {\n         this.name = name;\n         this.imageRef = imageRef;\n         this.flavorRef = flavorRef;\n      }\n\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      ServerRequest server = new ServerRequest(checkNotNull(postParams.get(\"name\"), \"name parameter not present\").toString(),\n            checkNotNull(postParams.get(\"imageRef\"), \"imageRef parameter not present\").toString(),\n            checkNotNull(postParams.get(\"flavorRef\"), \"flavorRef parameter not present\").toString());\n      if (!metadata.isEmpty())\n         server.metadata = metadata;\n      if (!personality.isEmpty())\n         server.personality = personality;\n      if (keyName != null)\n         server.key_name = keyName;\n      if (availabilityZone != null)\n         server.availabilityZone = availabilityZone;\n      if (userData != null)\n         server.user_data = base64().encode(userData);\n      if (configDrive)\n         server.configDrive = \"true\";\n      if (!securityGroupNames.isEmpty()) {\n         server.securityGroupNames = Sets.newLinkedHashSet();\n         for (String groupName : securityGroupNames) {\n            server.securityGroupNames.add(new NamedThingy(groupName));\n         }\n      }\n      if (adminPass != null) {\n         server.adminPass = adminPass;\n      }\n      if (diskConfig != null) {\n         server.diskConfig = diskConfig;\n      }\n      if (!networks.isEmpty() || !novaNetworks.isEmpty()) {\n         server.networks = Lists.newArrayList(); // ensures ordering is preserved - helps testing and more intuitive for users.\n         for (Network network : novaNetworks) {\n            // Avoid serializing null values, which are common here.\n            ImmutableMap.Builder<String, String> networkMap = new ImmutableMap.Builder<String, String>();\n            if (network.getNetworkUuid() != null) {\n               networkMap.put(\"uuid\", network.getNetworkUuid());\n            }\n            if (network.getPortUuid() != null) {\n               networkMap.put(\"port\", network.getPortUuid());\n            }\n            if (network.getFixedIp() != null) {\n               networkMap.put(\"fixed_ip\", network.getFixedIp());\n            }\n            server.networks.add(networkMap.build());\n         }\n         for (String network : networks) {\n            server.networks.add(ImmutableMap.of(\"uuid\", network));\n         }\n      }\n      if (!blockDeviceMappings.isEmpty()) {\n         server.blockDeviceMappings = blockDeviceMappings;\n      }\n\n      return bindToRequest(request, (Object) ImmutableMap.of(\"server\", server));\n   }\n\n   private static class NamedThingy extends ForwardingObject {\n      private String name;\n\n      private NamedThingy(String name) {\n         this.name = name;\n      }\n\n      @Override\n      protected Object delegate() {\n         return name;\n      }\n   }\n\n   /**\n    * You may further customize a cloud server by injecting data into the file\n    * system of the cloud server itself. This is useful, for example, for\n    * inserting ssh keys, setting configuration files, or storing data that you\n    * want to retrieve from within the instance itself. It is intended to\n    * provide a minimal amount of launch-time personalization. If significant\n    * customization is required, a custom image should be created. The max size\n    * of the file path data is 255 bytes while the max size of the file contents\n    * is determined by provider quotas(default size is 10KB). Note that the file\n    * contents should be encoded as a Base64 string and the size limit refers to\n    * the number of bytes in the decoded data not the number of characters in the\n    * encoded data. The maximum number of file path/content pairs that can be supplied\n    * is determined by provider quotas(default is 5). Any existing files that match\n    * the specified file will be renamed to include the extension bak followed by a\n    * time stamp.\n    * For example, the file /etc/passwd will be backed\n    * up as /etc/passwd.bak.1246036261.5785. All files will have root and the\n    * root group as owner and group owner, respectively and will allow user and\n    * group read access only (-r--r-----).\n    */\n   public CreateServerOptions writeFileToPath(byte[] contents, String path) {\n      personality.add(new File(path, contents));\n      return this;\n   }\n\n   public CreateServerOptions adminPass(String adminPass) {\n      checkNotNull(adminPass, \"adminPass\");\n      this.adminPass = adminPass;\n      return this;\n   }\n\n   /**\n    * Custom cloud server metadata can also be supplied at launch time. This\n    * metadata is stored in the API system where it is retrievable by querying\n    * the API for server status. The maximum size of the metadata key and value\n    * is each 255 bytes.\n    */\n   public CreateServerOptions metadata(Map<String, String> metadata) {\n      checkNotNull(metadata, \"metadata\");\n      for (Entry<String, String> entry : metadata.entrySet()) {\n         checkArgument(\n               entry.getKey().getBytes().length < 255,\n               String.format(\"maximum length of metadata key is 255 bytes.  Key specified %s is %d bytes\",\n                     entry.getKey(), entry.getKey().getBytes().length));\n         checkArgument(entry.getKey().getBytes().length < 255, String.format(\n               \"maximum length of metadata value is 255 bytes.  Value specified for %s (%s) is %d bytes\",\n               entry.getKey(), entry.getValue(), entry.getValue().getBytes().length));\n      }\n      this.metadata = ImmutableMap.copyOf(metadata);\n      return this;\n   }\n\n   /**\n    * Custom user-data can be also be supplied at launch time.\n    * It is retrievable by the instance and is often used for launch-time configuration\n    * by instance scripts.\n    * Pass userData unencoded, as the value will be base64 encoded automatically.\n    */\n   public CreateServerOptions userData(byte[] userData) {\n      this.userData = userData;\n      return this;\n   }\n\n   /**\n    * Set to true to use a config drive for metadata.\n    * This is a separate configuration drive that can be used separately from the metadata service.\n    * This needs to be set to \"true\" when trying to use user data for cloud-init.\n    * @see http://docs.openstack.org/grizzly/openstack-compute/admin/content/config-drive.html\n    */\n   public CreateServerOptions configDrive(boolean configDrive) {\n      this.configDrive = configDrive;\n      return this;\n   }\n\n   /**\n    * A keypair name can be defined when creating a server. This key will be\n    * linked to the server and used to SSH connect to the machine\n    * @see #getKeyPairName()\n    */\n   public CreateServerOptions keyPairName(String keyName) {\n      this.keyName = keyName;\n      return this;\n   }\n\n   /**\n    * @see #getAvailabilityZone()\n    */\n   public CreateServerOptions availabilityZone(String availabilityZone) {\n      this.availabilityZone = availabilityZone;\n      return this;\n   }\n\n   /**\n    * @see #getSecurityGroupNames()\n    */\n   public CreateServerOptions securityGroupNames(String... securityGroupNames) {\n      return securityGroupNames(ImmutableSet.copyOf(checkNotNull(securityGroupNames, \"securityGroupNames\")));\n   }\n\n   public CreateServerOptions securityGroupNames(Iterable<String> securityGroupNames) {\n      for (String groupName : checkNotNull(securityGroupNames, \"securityGroupNames\"))\n         checkNotNull(emptyToNull(groupName), \"all security groups must be non-empty\");\n      this.securityGroupNames = ImmutableSet.copyOf(securityGroupNames);\n      return this;\n   }\n\n   /**\n    * @see #getDiskConfig()\n    */\n   public CreateServerOptions diskConfig(String diskConfig) {\n      this.diskConfig = diskConfig;\n      return this;\n   }\n\n   /**\n    * @see #getNetworks()\n    */\n   public CreateServerOptions networks(Iterable<String> networks) {\n      this.networks = ImmutableList.copyOf(networks);\n      return this;\n   }\n\n   /**\n    * @see #getNetworks()\n    * Overwrites networks supplied by {@link #networks(Iterable)}\n    */\n   public CreateServerOptions novaNetworks(Iterable<Network> networks) {\n      this.novaNetworks = ImmutableList.copyOf(networks);\n      return this;\n   }\n\n   /**\n    * @see #getNetworks()\n    */\n   public CreateServerOptions networks(String... networks) {\n      return networks(ImmutableList.copyOf(networks));\n   }\n\n   /**\n    * @see #getBlockDeviceMappings()\n    */\n   public CreateServerOptions blockDeviceMappings(Set<BlockDeviceMapping> blockDeviceMappings) {\n      this.blockDeviceMappings = ImmutableSet.copyOf(blockDeviceMappings);\n      return this;\n   }\n\n   /**\n    * A keypair name can be defined when creating a server. This key will be\n    * linked to the server and used to SSH connect to the machine\n    */\n   public String getKeyPairName() {\n      return keyName;\n   }\n\n   public String getAvailabilityZone() {\n      return availabilityZone;\n   }\n\n   /**\n    * Security groups the user specified to run servers with.\n    * <p/>\n    * <h3>Note</h3>\n    * <p/>\n    * This requires that {@link NovaApi#getSecurityGroupExtensionApi(String)} to return\n    * {@link Optional#isPresent present}\n    */\n   public Set<String> getSecurityGroupNames() {\n      return securityGroupNames;\n   }\n\n   /**\n    * Get custom networks specified for the server.\n    *\n    * @return A list of uuids defined by Neutron (previously Quantum)\n    * @see <a href=\"https://wiki.openstack.org/wiki/Neutron/APIv2-specification#Network\">Neutron Networks<a/>\n    */\n   public List<String> getNetworks() {\n      return networks;\n   }\n\n   /**\n    * Get custom networks specified for the server.\n    *\n    * @return A list of uuids defined by Neutron (previously Quantum)\n    * @see <a href=\"https://wiki.openstack.org/wiki/Neutron/APIv2-specification#Network\">Neutron Networks<a/>\n    */\n   public List<Network> getNovaNetworks() {\n      return novaNetworks;\n   }\n\n   /**\n    * When you create a server from an image with the diskConfig value set to\n    * {@link Server#DISK_CONFIG_AUTO}, the server is built with a single partition that is expanded to\n    * the disk size of the flavor selected. When you set the diskConfig attribute to\n    * {@link Server#DISK_CONFIG_MANUAL}, the server is built by using the partition scheme and file\n    * system that is in the source image.\n    * <p/>\n    * If the target flavor disk is larger, remaining disk space is left unpartitioned. A server inherits the diskConfig\n    * attribute from the image from which it is created. However, you can override the diskConfig value when you create\n    * a server. This field is only present if the Disk Config extension is installed in your OpenStack deployment.\n    */\n   public String getDiskConfig() {\n      return diskConfig;\n   }\n\n   /**\n    * Determines if a configuration drive will be attached to the server or not.\n    * This can be used for cloud-init or other configuration purposes.\n    */\n   public boolean getConfigDrive() {\n      return configDrive;\n   }\n\n   /**\n    * Block devices that should be attached to the instance at boot time.\n    */\n   public Set<BlockDeviceMapping> getBlockDeviceMappings() {\n      return blockDeviceMappings;\n   }\n\n   public static class Builder {\n      /**\n       * @see CreateServerOptions#writeFileToPath(byte[], String)\n       */\n      public static CreateServerOptions writeFileToPath(byte[] contents, String path) {\n         CreateServerOptions options = new CreateServerOptions();\n         return options.writeFileToPath(contents, path);\n      }\n\n      /**\n       * @see CreateServerOptions#adminPass(String)\n       */\n      public static CreateServerOptions adminPass(String adminPass) {\n         CreateServerOptions options = new CreateServerOptions();\n         return options.adminPass(adminPass);\n      }\n\n      /**\n       * @see CreateServerOptions#metadata(Map<String, String>)\n       */\n      public static CreateServerOptions metadata(Map<String, String> metadata) {\n         CreateServerOptions options = new CreateServerOptions();\n         return options.metadata(metadata);\n      }\n\n      /**\n       * @see CreateServerOptions#keyPairName(String)\n       */\n      public static CreateServerOptions keyPairName(String keyName) {\n         CreateServerOptions options = new CreateServerOptions();\n         return options.keyPairName(keyName);\n      }\n\n      /**\n       * @see CreateServerOptions#securityGroupNames(String...)\n       */\n      public static CreateServerOptions securityGroupNames(String... groupNames) {\n         CreateServerOptions options = new CreateServerOptions();\n         if (new CreateServerOptions().securityGroupNames(groupNames) == CreateServerOptions.class.cast(options.securityGroupNames(groupNames)))\n            System.out.println(\"They are fucking equal, dump the cast!!!\");\n         return CreateServerOptions.class.cast(options.securityGroupNames(groupNames));\n      }\n\n      /**\n       * @see CreateServerOptions#securityGroupNames(Iterable)\n       */\n      public static CreateServerOptions securityGroupNames(Iterable<String> groupNames) {\n         return CreateServerOptions.class.cast(new CreateServerOptions().securityGroupNames(groupNames));\n      }\n\n      /**\n       * @see CreateServerOptions#diskConfig(String)\n       */\n      public static CreateServerOptions diskConfig(String diskConfig) {\n         return CreateServerOptions.class.cast(new CreateServerOptions().diskConfig(diskConfig));\n      }\n\n      /**\n       * @see CreateServerOptions#networks(String...)\n       */\n      public static CreateServerOptions networks(String... networks) {\n         return CreateServerOptions.class.cast(new CreateServerOptions().networks(networks));\n      }\n\n      /**\n       * @see CreateServerOptions#networks(Iterable)\n       */\n      public static CreateServerOptions networks(Iterable<String> networks) {\n         return CreateServerOptions.class.cast(new CreateServerOptions().networks(networks));\n      }\n\n      /**\n       * @see CreateServerOptions#novaNetworks(Iterable)\n       */\n      public static CreateServerOptions novaNetworks(Iterable<Network> networks) {\n         return CreateServerOptions.class.cast(new CreateServerOptions().novaNetworks(networks));\n      }\n\n      /**\n       * @see CreateServerOptions#availabilityZone(String)\n       */\n      public static CreateServerOptions availabilityZone(String availabilityZone) {\n         return new CreateServerOptions().availabilityZone(availabilityZone);\n      }\n\n      /**\n       * @see CreateServerOptions#blockDeviceMappings(Set)\n       */\n      public static CreateServerOptions blockDeviceMappings(Set<BlockDeviceMapping> blockDeviceMappings) {\n         return new CreateServerOptions().blockDeviceMappings(blockDeviceMappings);\n      }\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      return jsonBinder.bindToRequest(request, input);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/options/CreateVolumeOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.options;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\nimport java.util.Map.Entry;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.MapBinder;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Maps;\n\npublic class CreateVolumeOptions implements MapBinder {\n   public static final CreateVolumeOptions NONE = new CreateVolumeOptions();\n\n   @Inject\n   private BindToJsonPayload jsonBinder;\n\n   protected String name;\n   protected String description;\n   protected String volumeType;\n   protected String availabilityZone;\n   protected String snapshotId;\n   protected Map<String, String> metadata = ImmutableMap.of();\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      Map<String, Object> image = Maps.newHashMap();\n      image.putAll(postParams);\n      if (name != null)\n         image.put(\"display_name\", name);\n      if (description != null)\n         image.put(\"display_description\", description);\n      if (volumeType != null)\n         image.put(\"volume_type\", volumeType);\n      if (availabilityZone != null)\n         image.put(\"availability_zone\", availabilityZone);\n      if (snapshotId != null)\n         image.put(\"snapshot_id\", snapshotId);\n      if (!metadata.isEmpty())\n         image.put(\"metadata\", metadata);\n      return jsonBinder.bindToRequest(request, ImmutableMap.of(\"volume\", image));\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object toBind) {\n      throw new IllegalStateException(\"CreateVolume is a POST operation\");\n   }\n\n   @Override\n   public boolean equals(Object object) {\n      if (this == object) {\n         return true;\n      }\n      if (!(object instanceof CreateVolumeOptions)) return false;\n      final CreateVolumeOptions other = CreateVolumeOptions.class.cast(object);\n      return equal(volumeType, other.volumeType) && equal(availabilityZone, other.availabilityZone) && equal(snapshotId, other.snapshotId)\n            && equal(name, other.name) && equal(description, other.description) && equal(metadata, other.metadata);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(volumeType, availabilityZone, snapshotId, name, description, metadata);\n   }\n\n   protected ToStringHelper string() {\n      return toStringHelper(\"\").add(\"volumeType\", volumeType).add(\"availabilityZone\", availabilityZone)\n            .add(\"snapshotId\", snapshotId).add(\"name\", name).add(\"description\", description).add(\"metadata\", metadata);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   /**\n    * Custom cloud server metadata can also be supplied at launch time. This\n    * metadata is stored in the API system where it is retrievable by querying\n    * the API for server status. The maximum size of the metadata key and value\n    * is each 255 bytes and the maximum number of key-value pairs that can be\n    * supplied per volume is 5.\n    */\n   public CreateVolumeOptions metadata(Map<String, String> metadata) {\n      checkNotNull(metadata, \"metadata\");\n      checkArgument(metadata.size() <= 5,\n            \"you cannot have more then 5 metadata values.  You specified: \" + metadata.size());\n      for (Entry<String, String> entry : metadata.entrySet()) {\n         checkArgument(\n               entry.getKey().getBytes().length < 255,\n               String.format(\"maximum length of metadata key is 255 bytes.  Key specified %s is %d bytes\",\n                     entry.getKey(), entry.getKey().getBytes().length));\n         checkArgument(entry.getKey().getBytes().length < 255, String.format(\n               \"maximum length of metadata value is 255 bytes.  Value specified for %s (%s) is %d bytes\",\n               entry.getKey(), entry.getValue(), entry.getValue().getBytes().length));\n      }\n      this.metadata = ImmutableMap.copyOf(metadata);\n      return this;\n   }\n\n   public CreateVolumeOptions name(String name) {\n      this.name = name;\n      return this;\n   }\n\n   public CreateVolumeOptions description(String description) {\n      this.description = description;\n      return this;\n   }\n\n   public CreateVolumeOptions volumeType(String volumeType) {\n      this.volumeType = volumeType;\n      return this;\n   }\n\n   public CreateVolumeOptions availabilityZone(String availabilityZone) {\n      this.availabilityZone = availabilityZone;\n      return this;\n   }\n\n   public CreateVolumeOptions snapshotId(String snapshotId) {\n      this.snapshotId = snapshotId;\n      return this;\n   }\n\n   public String getVolumeType() {\n      return volumeType;\n   }\n\n   public String getAvailabilityZone() {\n      return availabilityZone;\n   }\n\n   public String getSnapshotId() {\n      return snapshotId;\n   }\n\n   public String getName() {\n      return name;\n   }\n\n   public String getDescription() {\n      return description;\n   }\n\n   public Map<String, String> getMetadata() {\n      return metadata;\n   }\n\n   public static class Builder {\n      /**\n       * @see CreateVolumeOptions#getName()\n       */\n      public static CreateVolumeOptions name(String name) {\n         return new CreateVolumeOptions().name(name);\n      }\n      /**\n       * @see CreateVolumeOptions#getDescription()\n       */\n      public static CreateVolumeOptions description(String description) {\n         return new CreateVolumeOptions().description(description);\n      }\n\n      /**\n       * @see CreateVolumeOptions#getVolumeType()\n       */\n      public static CreateVolumeOptions volumeType(String volumeType) {\n         return new CreateVolumeOptions().volumeType(volumeType);\n      }\n\n      /**\n       * @see CreateVolumeOptions#getAvailabilityZone()\n       */\n      public static CreateVolumeOptions availabilityZone(String availabilityZone) {\n         return new CreateVolumeOptions().availabilityZone(availabilityZone);\n      }\n\n      /**\n       * @see CreateVolumeOptions#getSnapshotId()\n       */\n      public static CreateVolumeOptions snapshotId(String snapshotId) {\n         return new CreateVolumeOptions().snapshotId(snapshotId);\n      }\n\n      /**\n       * @see CreateVolumeOptions#getMetadata()\n       */\n      public static CreateVolumeOptions metadata(Map<String, String> metadata) {\n         return new CreateVolumeOptions().metadata(metadata);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/options/CreateVolumeSnapshotOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.options;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.MapBinder;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Maps;\n\npublic class CreateVolumeSnapshotOptions implements MapBinder {\n   public static final CreateVolumeSnapshotOptions NONE = new CreateVolumeSnapshotOptions();\n\n   @Inject\n   private BindToJsonPayload jsonBinder;\n\n   private String name;\n   private String description;\n   private boolean force = false;\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      Map<String, Object> data = Maps.newHashMap(postParams);\n      if (name != null)\n         data.put(\"display_name\", name);\n      if (description != null)\n         data.put(\"display_description\", description);\n      if (force)\n         data.put(\"force\", \"true\");\n      return jsonBinder.bindToRequest(request, ImmutableMap.of(\"snapshot\", data));\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object toBind) {\n      throw new IllegalStateException(\"CreateSnapshot is a POST operation\");\n   }\n\n   @Override\n   public boolean equals(Object object) {\n      if (this == object) {\n         return true;\n      }\n      if (!(object instanceof CreateVolumeSnapshotOptions)) return false;\n      final CreateVolumeSnapshotOptions other = CreateVolumeSnapshotOptions.class.cast(object);\n      return equal(name, other.name) && equal(description, other.description);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(name, description);\n   }\n\n   protected ToStringHelper string() {\n      return toStringHelper(\"\").add(\"name\", name).add(\"description\", description);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   public CreateVolumeSnapshotOptions name(String name) {\n      this.name = name;\n      return this;\n   }\n\n   public CreateVolumeSnapshotOptions description(String description) {\n      this.description = description;\n      return this;\n   }\n\n   public CreateVolumeSnapshotOptions force() {\n      this.force = true;\n      return this;\n   }\n   \n   public String getName() {\n      return name;\n   }\n\n   public String getDescription() {\n      return description;\n   }\n\n   public boolean isForce() {\n      return force;\n   }\n\n   public static class Builder {\n      /**\n       * @see CreateVolumeSnapshotOptions#getName()\n       */\n      public static CreateVolumeSnapshotOptions name(String name) {\n         return new CreateVolumeSnapshotOptions().name(name);\n      }\n      /**\n       * @see CreateVolumeSnapshotOptions#getDescription()\n       */\n      public static CreateVolumeSnapshotOptions description(String description) {\n         return new CreateVolumeSnapshotOptions().description(description);\n      }\n\n      /**\n       * @see CreateVolumeSnapshotOptions#isForce()\n       */\n      public static CreateVolumeSnapshotOptions force() {\n         return new CreateVolumeSnapshotOptions().force();\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/options/CreateVolumeTypeOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.options;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.MapBinder;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Maps;\n\npublic class CreateVolumeTypeOptions implements MapBinder {\n   public static final CreateVolumeTypeOptions NONE = new CreateVolumeTypeOptions();\n\n   @Inject\n   protected BindToJsonPayload jsonBinder;\n\n   protected Map<String, String> specs = ImmutableMap.of();\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      Map<String, Object> data = Maps.newHashMap();\n      data.putAll(postParams);\n      data.put(\"extra_specs\", specs);\n      return jsonBinder.bindToRequest(request, ImmutableMap.of(\"volume_type\", data));\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object toBind) {\n      throw new IllegalStateException(\"CreateWithExtraSpecs are POST operations\");\n   }\n\n   @Override\n   public boolean equals(Object object) {\n      if (this == object) {\n         return true;\n      }\n      if (!(object instanceof CreateVolumeTypeOptions)) return false;\n      final CreateVolumeTypeOptions other = CreateVolumeTypeOptions.class.cast(object);\n      return equal(specs, other.specs);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(specs);\n   }\n\n   protected ToStringHelper string() {\n      return toStringHelper(\"\").add(\"specs\", specs);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   public CreateVolumeTypeOptions specs(Map<String, String> specs) {\n      this.specs = specs;\n      return this;\n   }\n\n   public Map<String, String> getSpecs() {\n      return specs;\n   }\n\n   public static class Builder {\n      /**\n       * @see CreateVolumeTypeOptions#getSpecs()\n       */\n      public static CreateVolumeTypeOptions specs(Map<String, String> specs) {\n         return new CreateVolumeTypeOptions().specs(specs);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/options/ListOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Date;\n\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\n\n/**\n * Options used to control the amount of detail in the request.\n *\n * @see PaginationOptions\n */\npublic class ListOptions extends PaginationOptions {\n\n   public static final ListOptions NONE = new ListOptions();\n\n   /**\n    * Provides detailed results for list operations.\n    */\n   public ListOptions withDetails() {\n      this.pathSuffix = \"/detail\";\n      return this;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ListOptions limit(int limit) {\n      super.limit(limit);\n      return this;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ListOptions marker(String marker) {\n      super.marker(marker);\n      return this;\n   }\n\n   /**\n    * Checks for any changes since the given date.\n    */\n   public ListOptions changesSince(Date changesSince) {\n      this.queryParameters.put(\"changes-since\", checkNotNull(changesSince, \"changesSince\").getTime() / 1000 + \"\");\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see ListOptions#withDetails()\n       */\n      public static ListOptions withDetails() {\n         ListOptions options = new ListOptions();\n         return options.withDetails();\n      }\n\n      /**\n       * @see PaginationOptions#marker(String)\n       */\n      public static ListOptions marker(String marker) {\n         ListOptions options = new ListOptions();\n         return options.marker(marker);\n      }\n\n      /**\n       * @see PaginationOptions#limit(int)\n       */\n      public static ListOptions limit(int limit) {\n         ListOptions options = new ListOptions();\n         return options.limit(limit);\n      }\n\n      /**\n       *\n       * @see PaginationOptions#limit(int)\n       * @deprecated Please use {@link #limit(int)} instead. To be removed in jclouds 2.0.\n       */\n      @Deprecated\n      public static ListOptions maxResults(int maxKeys) {\n         return limit(maxKeys);\n      }\n\n      /**\n       * @see ListOptions#changesSince(Date)\n       */\n      public static ListOptions changesSince(Date since) {\n         ListOptions options = new ListOptions();\n         return options.changesSince(since);\n      }\n\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/options/RebuildServerOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.options;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.MapBinder;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Maps;\n\npublic class RebuildServerOptions implements MapBinder {\n   @Inject\n   private BindToJsonPayload jsonBinder;\n   String imageRef;\n   String name;\n   String adminPass;\n   String accessIPv4;\n   String accessIPv6;\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      Map<String, String> image = Maps.newHashMap();\n      if (imageRef != null)\n         image.put(\"imageRef\", imageRef);\n      if (name != null)\n         image.put(\"name\", name);\n      if (adminPass != null)\n         image.put(\"adminPass\", adminPass);\n      if (accessIPv4 != null)\n         image.put(\"accessIPv4\", accessIPv4);\n      if (accessIPv6 != null)\n         image.put(\"accessIPv6\", accessIPv6);\n\n\n      return jsonBinder.bindToRequest(request, ImmutableMap.of(\"rebuild\", image));\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object toBind) {\n      throw new IllegalStateException(\"RebuildServer is a POST operation\");\n   }\n\n   /**\n    * @param ref\n    *           - reference of the image to rebuild the server with.\n    */\n   public RebuildServerOptions withImage(String ref) {\n      checkNotNull(ref, \"image reference should not be null\");\n      checkArgument(!ref.isEmpty(), \"image reference should not be empty\");\n      this.imageRef = ref;\n      return this;\n   }\n\n   public RebuildServerOptions name(String name) {\n      this.name = name;\n      return this;\n   }\n\n   public RebuildServerOptions adminPass(String adminPass) {\n      this.adminPass = adminPass;\n      return this;\n   }\n\n   public RebuildServerOptions ipv4Address(String ipv4Address) {\n      this.accessIPv4 = ipv4Address;\n      return this;\n   }\n\n   public RebuildServerOptions ipv6Address(String iPv6Address) {\n      this.accessIPv6 = iPv6Address;\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see RebuildServerOptions#withImage(String)\n       */\n      public static RebuildServerOptions withImage(String ref) {\n         RebuildServerOptions options = new RebuildServerOptions();\n         return options.withImage(ref);\n      }\n\n      /**\n       * @see RebuildServerOptions#name(String)\n       */\n      public static RebuildServerOptions name(String name) {\n         RebuildServerOptions options = new RebuildServerOptions();\n         return options.name(name);\n      }\n\n      /**\n       * @see RebuildServerOptions#adminPass(String)\n       */\n      public static RebuildServerOptions adminPass(String adminPass) {\n         RebuildServerOptions options = new RebuildServerOptions();\n         return options.adminPass(adminPass);\n      }\n\n      /**\n       * @see RebuildServerOptions#ipv4Address(String)\n       */\n      public static RebuildServerOptions ipv4Address(String ipv4Address) {\n         RebuildServerOptions options = new RebuildServerOptions();\n         return options.ipv4Address(ipv4Address);\n      }\n\n      /**\n       * @see RebuildServerOptions#ipv6Address(String)\n       */\n      public static RebuildServerOptions ipv6Address(String ipv6Address) {\n         RebuildServerOptions options = new RebuildServerOptions();\n         return options.ipv6Address(ipv6Address);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/predicates/FindSecurityGroupWithNameAndReturnTrue.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.predicates;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.NoSuchElementException;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.logging.Logger;\nimport org.jclouds.openstack.nova.v2_0.NovaApi;\nimport org.jclouds.openstack.nova.v2_0.domain.SecurityGroup;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.RegionAndName;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.SecurityGroupInRegion;\nimport org.jclouds.openstack.nova.v2_0.extensions.SecurityGroupApi;\nimport org.jclouds.rest.ResourceNotFoundException;\n\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.Iterables;\nimport com.google.inject.Inject;\n\n/**\n * AtomicReference is so that we can return the securityGroup that matched.\n */\n@Singleton\npublic class FindSecurityGroupWithNameAndReturnTrue implements Predicate<AtomicReference<RegionAndName>> {\n\n   private final NovaApi novaApi;\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   @Inject\n   public FindSecurityGroupWithNameAndReturnTrue(NovaApi novaApi) {\n      this.novaApi = checkNotNull(novaApi, \"novaApi\");\n   }\n\n   public boolean apply(AtomicReference<RegionAndName> securityGroupInRegionRef) {\n      checkNotNull(securityGroupInRegionRef, \"securityGroupRef\");\n      final RegionAndName securityGroupInRegion = checkNotNull(securityGroupInRegionRef.get(), \"securityGroupInRegion\");\n\n      Optional<? extends SecurityGroupApi> api = novaApi.getSecurityGroupApi(securityGroupInRegion.getRegion());\n      checkArgument(api.isPresent(), \"Security groups are required, but the extension is not available!\");\n\n      logger.trace(\"looking for security group %s\", securityGroupInRegion.slashEncode());\n      try {\n         final FluentIterable<SecurityGroup> allGroups = api.get().list();\n         SecurityGroup returnVal = Iterables.find(allGroups, new Predicate<SecurityGroup>() {\n\n            @Override\n            public boolean apply(SecurityGroup input) {\n               return input.getName().equals(securityGroupInRegion.getName());\n            }\n\n         });\n         securityGroupInRegionRef.set(new SecurityGroupInRegion(returnVal, securityGroupInRegion.getRegion(), allGroups));\n         return true;\n      } catch (ResourceNotFoundException e) {\n         return false;\n      } catch (NoSuchElementException e) {\n         return false;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/predicates/ImagePredicates.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.openstack.nova.v2_0.domain.Image;\nimport org.jclouds.openstack.nova.v2_0.domain.Image.Status;\n\nimport com.google.common.base.Predicate;\n\n/**\n * Predicates handy when working with Images\n */\n\npublic class ImagePredicates {\n\n   /**\n    * matches status of the given image\n    * \n    * @param status\n    * @return predicate that matches status\n    */\n   public static Predicate<Image> statusEquals(final Status status) {\n      checkNotNull(status, \"status must be defined\");\n\n      return new Predicate<Image>() {\n         @Override\n         public boolean apply(Image image) {\n            return status.equals(image.getStatus());\n         }\n\n         @Override\n         public String toString() {\n            return \"statusEquals(\" + status + \")\";\n         }\n      };\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/predicates/KeyPairPredicates.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.openstack.nova.v2_0.domain.KeyPair;\n\nimport com.google.common.base.Predicate;\n\n/**\n * Predicates handy when working with KeyPairs\n */\n\npublic class KeyPairPredicates {\n\n\n   /**\n    * matches name of the given key pair\n    * \n    * @param name\n    * @return predicate that matches name\n    */\n   public static Predicate<KeyPair> nameMatches(final Predicate<String> name) {\n      checkNotNull(name, \"name must be defined\");\n\n      return new Predicate<KeyPair>() {\n         @Override\n         public boolean apply(KeyPair ext) {\n            return name.apply(ext.getName());\n         }\n\n         @Override\n         public String toString() {\n            return \"nameMatches(\" + name + \")\";\n         }\n      };\n   }\n   \n   /**\n    * matches name of the given keypair starts with the specified prefix\n    *\n    * @param name the prefix you are looking for\n    * @return the predicate\n    */\n   public static Predicate<KeyPair> nameEquals(final String name) {\n      checkNotNull(name, \"name must be defined\");\n\n      return new Predicate<KeyPair>() {\n         @Override\n         public boolean apply(KeyPair ext) {\n            return ext.getName() != null && ext.getName().equals(name);\n         }\n\n         @Override\n         public String toString() {\n            return \"nameEquals(\" + name + \")\";\n         }\n      };\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/predicates/SecurityGroupPredicates.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Set;\n\nimport org.jclouds.net.domain.IpProtocol;\nimport org.jclouds.openstack.nova.v2_0.domain.SecurityGroup;\nimport org.jclouds.openstack.nova.v2_0.domain.SecurityGroupRule;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Predicates;\n\n/**\n * Predicates handy when working with SecurityGroups\n */\n\npublic class SecurityGroupPredicates {\n\n   /**\n    * matches name of the given security group\n    *\n    * @param name\n    * @return predicate that matches name\n    */\n   public static Predicate<SecurityGroup> nameEquals(final String name) {\n      checkNotNull(name, \"name must be defined\");\n\n      return new Predicate<SecurityGroup>() {\n         @Override\n         public boolean apply(SecurityGroup ext) {\n            return name.equals(ext.getName());\n         }\n\n         @Override\n         public String toString() {\n            return \"nameEquals(\" + name + \")\";\n         }\n      };\n   }\n\n   /**\n    * matches name of the given security group against a list\n    *\n    * @param names\n    * @return predicate that matches one of the names\n    */\n   public static Predicate<SecurityGroup> nameIn(final Set<String> names) {\n      checkNotNull(names, \"names must be defined\");\n\n      return new Predicate<SecurityGroup>() {\n         @Override\n         public boolean apply(SecurityGroup ext) {\n            return Predicates.in(names).apply(ext.getName());\n         }\n\n         @Override\n         public String toString() {\n            return \"nameIn(\" + names + \")\";\n         }\n      };\n   }\n\n   /**\n    * matches name of the given security group\n    * \n    * @param name\n    * @return predicate that matches name\n    */\n   public static Predicate<SecurityGroup> nameMatches(final Predicate<String> name) {\n      checkNotNull(name, \"name must be defined\");\n\n      return new Predicate<SecurityGroup>() {\n         @Override\n         public boolean apply(SecurityGroup ext) {\n            return name.apply(ext.getName());\n         }\n\n         @Override\n         public String toString() {\n            return \"nameMatches(\" + name + \")\";\n         }\n      };\n   }\n\n   /**\n    * matches a security group rule by its cidr\n    *\n    * @param cidr\n    * @return predicate that matches cidr\n    */\n   public static Predicate<SecurityGroupRule> ruleCidr(final String cidr) {\n      checkNotNull(cidr, \"cidr must be defined\");\n\n      return new Predicate<SecurityGroupRule>() {\n         @Override\n         public boolean apply(SecurityGroupRule ext) {\n            return cidr.equals(ext.getIpRange());\n         }\n\n         @Override\n         public String toString() {\n            return \"cidr(\" + cidr + \")\";\n         }\n      };\n   }\n\n   /**\n    * matches a security group rule by the security group it allows\n    *\n    * @param groupName\n    * @return predicate that matches group\n    */\n   public static Predicate<SecurityGroupRule> ruleGroup(final String groupName) {\n      checkNotNull(groupName, \"groupName must be defined\");\n\n      return new Predicate<SecurityGroupRule>() {\n         @Override\n         public boolean apply(SecurityGroupRule ext) {\n            return ext.getGroup() != null && groupName.equals(ext.getGroup().getName());\n         }\n\n         @Override\n         public String toString() {\n            return \"ruleGroup(\" + groupName + \")\";\n         }\n      };\n   }\n\n   /**\n    * matches a security group rule by the protocol\n    *\n    * @param protocol\n    * @return predicate that matches protocol\n    */\n   public static Predicate<SecurityGroupRule> ruleProtocol(final IpProtocol protocol) {\n      checkNotNull(protocol, \"protocol must be defined\");\n\n      return new Predicate<SecurityGroupRule>() {\n         @Override\n         public boolean apply(SecurityGroupRule ext) {\n            return protocol.equals(ext.getIpProtocol());\n         }\n\n         @Override\n         public String toString() {\n            return \"ruleProtocol(\" + protocol + \")\";\n         }\n      };\n   }\n\n   /**\n    * matches a security group rule by the start port\n    *\n    * @param startPort\n    * @return predicate that matches startPort\n    */\n   public static Predicate<SecurityGroupRule> ruleStartPort(final int startPort) {\n      return new Predicate<SecurityGroupRule>() {\n         @Override\n         public boolean apply(SecurityGroupRule ext) {\n            return startPort == ext.getFromPort();\n         }\n\n         @Override\n         public String toString() {\n            return \"ruleStartPort(\" + startPort + \")\";\n         }\n      };\n   }\n\n   /**\n    * matches a security group rule by the end port\n    *\n    * @param endPort\n    * @return predicate that matches endPort\n    */\n   public static Predicate<SecurityGroupRule> ruleEndPort(final int endPort) {\n      return new Predicate<SecurityGroupRule>() {\n         @Override\n         public boolean apply(SecurityGroupRule ext) {\n            return endPort == ext.getToPort();\n         }\n\n         @Override\n         public String toString() {\n            return \"ruleEndPort(\" + endPort + \")\";\n         }\n      };\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/AccessKeyAndSecretKeyAndTenantIdAuthenticationExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Properties;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.keystone.v2_0.internal.KeystoneFixture;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiExpectTest;\nimport org.jclouds.openstack.nova.v2_0.parse.ParseServerListTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n *\n * @see org.jclouds.openstack.keystone.config.KeystoneProperties#CREDENTIAL_TYPE\n */\n@Test(groups = \"unit\", testName = \"AccessKeyAndSecretKeyAndTenantIdAuthenticationExpectTest\")\npublic class AccessKeyAndSecretKeyAndTenantIdAuthenticationExpectTest extends BaseNovaApiExpectTest {\n   public AccessKeyAndSecretKeyAndTenantIdAuthenticationExpectTest() {\n      identity = identityWithTenantId;\n   }\n\n   /**\n    * this reflects the properties that a user would pass to createContext\n    */\n   @Override\n   protected Properties setupProperties() {\n      Properties contextProperties = super.setupProperties();\n      contextProperties.setProperty(\"jclouds.keystone.credential-type\", \"apiAccessKeyCredentials\");\n      contextProperties.setProperty(\"jclouds.keystone.tenant-id\", KeystoneFixture.INSTANCE.getTenantId());\n      return contextProperties;\n   }\n\n   public void testListServersWhenResponseIs2xx() throws Exception {\n      HttpRequest listServers = HttpRequest\n            .builder()\n            .method(\"GET\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken).build();\n\n      HttpResponse listServersResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResource(\"/server_list.json\")).build();\n\n      NovaApi apiWhenServersExist = requestsSendResponses(keystoneAuthWithAccessKeyAndSecretKeyAndTenantId,\n            responseWithKeystoneAccess, listServers, listServersResponse);\n\n      assertEquals(apiWhenServersExist.getConfiguredRegions(), ImmutableSet.of(\"az-1.region-a.geo-1\", \"az-2.region-a.geo-1\", \"az-3.region-a.geo-1\"));\n\n      assertEquals(apiWhenServersExist.getServerApi(\"az-1.region-a.geo-1\").list().concat().toString(),\n            new ParseServerListTest().expected().toString());\n   }\n\n}\n\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/AccessKeyAndSecretKeyAndTenantNamePropertyAuthenticationExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Properties;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.keystone.v2_0.internal.KeystoneFixture;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiExpectTest;\nimport org.jclouds.openstack.nova.v2_0.parse.ParseServerListTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n *\n * @see KeystoneProperties#CREDENTIAL_TYPE\n */\n@Test(groups = \"unit\", testName = \"AccessKeyAndSecretKeyAndTenantNamePropertyAuthenticationExpectTest\")\npublic class AccessKeyAndSecretKeyAndTenantNamePropertyAuthenticationExpectTest extends BaseNovaApiExpectTest {\n   public AccessKeyAndSecretKeyAndTenantNamePropertyAuthenticationExpectTest() {\n      identity = \"identity\";\n   }\n\n   /**\n    * this reflects the properties that a user would pass to createContext\n    */\n   @Override\n   protected Properties setupProperties() {\n      Properties contextProperties = super.setupProperties();\n      contextProperties.setProperty(\"jclouds.keystone.credential-type\", \"apiAccessKeyCredentials\");\n      contextProperties.setProperty(\"jclouds.keystone.tenant-name\", KeystoneFixture.INSTANCE.getTenantName());\n      return contextProperties;\n   }\n\n   public void testListServersWhenResponseIs2xx() throws Exception {\n      HttpRequest listServers = HttpRequest\n            .builder()\n            .method(\"GET\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken).build();\n\n      HttpResponse listServersResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResource(\"/server_list.json\")).build();\n\n      NovaApi apiWhenServersExist = requestsSendResponses(keystoneAuthWithAccessKeyAndSecretKeyAndTenantName,\n            responseWithKeystoneAccess, listServers, listServersResponse);\n\n      assertEquals(apiWhenServersExist.getConfiguredRegions(), ImmutableSet.of(\"az-1.region-a.geo-1\", \"az-2.region-a.geo-1\", \"az-3.region-a.geo-1\"));\n\n      assertEquals(apiWhenServersExist.getServerApi(\"az-1.region-a.geo-1\").list().concat().toString(),\n            new ParseServerListTest().expected().toString());\n   }\n\n}\n\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/AccessKeyAndSecretKeyAuthenticationExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Properties;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiExpectTest;\nimport org.jclouds.openstack.nova.v2_0.parse.ParseServerListTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n *\n * @see org.jclouds.openstack.keystone.config.KeystoneProperties#CREDENTIAL_TYPE\n */\n@Test(groups = \"unit\", testName = \"AccessKeyAndSecretKeyAuthenticationExpectTest\")\npublic class AccessKeyAndSecretKeyAuthenticationExpectTest extends BaseNovaApiExpectTest {\n\n   /**\n    * this reflects the properties that a user would pass to createContext\n    */\n   @Override\n   protected Properties setupProperties() {\n      Properties contextProperties = super.setupProperties();\n      contextProperties.setProperty(\"jclouds.keystone.credential-type\", \"apiAccessKeyCredentials\");\n      return contextProperties;\n   }\n\n   public void testListServersWhenResponseIs2xx() throws Exception {\n      HttpRequest listServers = HttpRequest\n            .builder()\n            .method(\"GET\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken).build();\n\n      HttpResponse listServersResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResource(\"/server_list.json\")).build();\n\n      NovaApi apiWhenServersExist = requestsSendResponses(keystoneAuthWithAccessKeyAndSecretKeyAndTenantName,\n            responseWithKeystoneAccess, listServers, listServersResponse);\n\n      assertEquals(apiWhenServersExist.getConfiguredRegions(), ImmutableSet.of(\"az-1.region-a.geo-1\", \"az-2.region-a.geo-1\", \"az-3.region-a.geo-1\"));\n\n      assertEquals(apiWhenServersExist.getServerApi(\"az-1.region-a.geo-1\").list().concat().toString(),\n            new ParseServerListTest().expected().toString());\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/EndpointIdIsRandomExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0;\n\nimport static org.jclouds.Constants.PROPERTY_ENDPOINT;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Properties;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiExpectTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests to ensure that we can pick the only endpoint of a service\n */\n@Test(groups = \"unit\", testName = \"EndpointIdIsRandomExpectTest\")\npublic class EndpointIdIsRandomExpectTest extends BaseNovaApiExpectTest {\n\n   public EndpointIdIsRandomExpectTest() {\n      this.identity = \"demo:demo\";\n      this.credential = \"password\";\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties overrides = super.setupProperties();\n      overrides.setProperty(PROPERTY_ENDPOINT, \"http://10.10.10.10:5000/v2.0/\");\n      return overrides;\n   }\n\n   public void testVersionMatchOnConfiguredRegionsWhenResponseIs2xx() {\n\n      HttpRequest authenticate = HttpRequest\n            .builder()\n            .method(\"POST\")\n            .endpoint(\"http://10.10.10.10:5000/v2.0/tokens\")\n            .addHeader(\"Accept\", \"application/json\")\n            .payload(\n                  payloadFromStringWithContentType(\n                        \"{\\\"auth\\\":{\\\"passwordCredentials\\\":{\\\"username\\\":\\\"demo\\\",\\\"password\\\":\\\"password\\\"},\\\"tenantName\\\":\\\"demo\\\"}}\",\n                        \"application/json\")).build();\n\n      HttpResponse authenticationResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResourceWithContentType(\"/access_version_uids.json\", \"application/json\")).build();\n\n      NovaApi whenNovaRegionExists = requestSendsResponse(authenticate, authenticationResponse);\n\n      assertEquals(whenNovaRegionExists.getConfiguredRegions(), ImmutableSet.of(\"RegionOne\"));\n\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/NovaApiMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0;\n\nimport org.jclouds.compute.internal.BaseComputeServiceApiMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"NovaApiMetadataTest\")\npublic class NovaApiMetadataTest extends BaseComputeServiceApiMetadataTest {\n\n   public NovaApiMetadataTest() {\n      super(new NovaApiMetadata());\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/PasswordAuthenticationExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiExpectTest;\nimport org.jclouds.openstack.nova.v2_0.parse.ParseServerListTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n *\n * @see org.jclouds.openstack.keystone.config.KeystoneProperties#CREDENTIAL_TYPE\n */\n@Test(groups = \"unit\", testName = \"PasswordAuthenticationExpectTest\")\npublic class PasswordAuthenticationExpectTest extends BaseNovaApiExpectTest {\n   public PasswordAuthenticationExpectTest() {\n      identity = \"identity\";\n   }\n\n   public void testListServersWhenResponseIs2xx() throws Exception {\n      HttpRequest listServers = HttpRequest\n            .builder()\n            .method(\"GET\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken).build();\n\n      HttpResponse listServersResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResource(\"/server_list.json\")).build();\n\n      NovaApi apiWhenServersExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword,\n            responseWithKeystoneAccess, listServers, listServersResponse);\n\n      assertEquals(apiWhenServersExist.getConfiguredRegions(), ImmutableSet.of(\"az-1.region-a.geo-1\", \"az-2.region-a.geo-1\", \"az-3.region-a.geo-1\"));\n\n      assertEquals(apiWhenServersExist.getServerApi(\"az-1.region-a.geo-1\").list().concat().toString(),\n            new ParseServerListTest().expected().toString());\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/PasswordAuthenticationWithTenantNameExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Properties;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiExpectTest;\nimport org.jclouds.openstack.nova.v2_0.parse.ParseServerListTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n *\n * @see org.jclouds.openstack.keystone.config.KeystoneProperties#CREDENTIAL_TYPE\n */\n@Test(groups = \"unit\", testName = \"PasswordAuthenticationWithTenantNameExpectTest\")\npublic class PasswordAuthenticationWithTenantNameExpectTest extends BaseNovaApiExpectTest {\n\n   /**\n    * this reflects the properties that a user would pass to createContext\n    */\n   @Override\n   protected Properties setupProperties() {\n      Properties contextProperties = super.setupProperties();\n      contextProperties.setProperty(\"jclouds.keystone.credential-type\", \"passwordCredentials\");\n      return contextProperties;\n   }\n\n   public void testListServersWhenResponseIs2xx() throws Exception {\n      HttpRequest listServers = HttpRequest\n            .builder()\n            .method(\"GET\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken).build();\n\n      HttpResponse listServersResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResource(\"/server_list.json\")).build();\n\n      NovaApi apiWhenServersExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, listServers, listServersResponse);\n\n      assertEquals(apiWhenServersExist.getConfiguredRegions(), ImmutableSet.of(\"az-1.region-a.geo-1\", \"az-2.region-a.geo-1\", \"az-3.region-a.geo-1\"));\n\n      assertEquals(apiWhenServersExist.getServerApi(\"az-1.region-a.geo-1\").list().concat().toString(),\n            new ParseServerListTest().expected().toString());\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/compute/NovaComputeServiceAdapterExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.compute;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\n\nimport java.util.Map;\nimport java.util.Properties;\n\nimport org.jclouds.compute.ComputeService;\nimport org.jclouds.compute.ComputeServiceAdapter.NodeAndInitialCredentials;\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.domain.TemplateBuilder;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.nova.v2_0.compute.options.NovaTemplateOptions;\nimport org.jclouds.openstack.nova.v2_0.domain.Network;\nimport org.jclouds.openstack.nova.v2_0.domain.Server;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.ServerInRegion;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaComputeServiceContextExpectTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Injector;\n\n/**\n * Tests the compute service abstraction of the nova api.\n */\n@Test(groups = \"unit\", testName = \"NovaComputeServiceAdapterExpectTest\")\npublic class NovaComputeServiceAdapterExpectTest extends BaseNovaComputeServiceContextExpectTest<Injector> {\n   HttpRequest serverDetail = HttpRequest\n         .builder()\n         .method(\"GET\")\n         .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers/71752\")\n         .addHeader(\"Accept\", \"application/json\")\n         .addHeader(\"X-Auth-Token\", authToken).build();\n\n   HttpResponse serverDetailResponse = HttpResponse.builder().statusCode(200)\n         .payload(payloadFromResource(\"/server_details.json\")).build();\n\n   public void testCreateNodeWithGroupEncodedIntoNameWithNetworks() throws Exception {\n\n      HttpRequest createServer = HttpRequest\n         .builder()\n         .method(\"POST\")\n         .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers\")\n         .addHeader(\"Accept\", \"application/json\")\n         .addHeader(\"X-Auth-Token\", authToken)\n         .payload(payloadFromStringWithContentType(\n                  \"{\\\"server\\\":{\\\"name\\\":\\\"test-e92\\\",\\\"imageRef\\\":\\\"2235\\\",\\\"flavorRef\\\":\\\"100\\\",\\\"networks\\\":[{\\\"uuid\\\":\\\"4ebd35cf-bfe7-4d93-b0d8-eb468ce2245a\\\"}]}}\", \"application/json\"))\n         .build();\n\n      HttpResponse createServerResponse = HttpResponse.builder().statusCode(202).message(\"HTTP/1.1 202 Accepted\")\n         .payload(payloadFromResourceWithContentType(\"/new_server_networks_response.json\", \"application/json; charset=UTF-8\")).build();\n\n      Map<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder()\n               .put(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess)\n               .put(extensionsOfNovaRequest, extensionsOfNovaResponse)\n               .put(listDetail, listDetailResponse)\n               .put(listFlavorsDetail, listFlavorsDetailResponse)\n               .put(createServer, createServerResponse)\n               .put(serverDetail, serverDetailResponse).build();\n\n      Injector forNetworks = requestsSendResponses(requestResponseMap);\n\n      Template template = forNetworks.getInstance(TemplateBuilder.class).build();\n      template.getOptions().as(NovaTemplateOptions.class).networks(\"4ebd35cf-bfe7-4d93-b0d8-eb468ce2245a\");\n\n      NovaComputeServiceAdapter adapter = forNetworks.getInstance(NovaComputeServiceAdapter.class);\n\n      NodeAndInitialCredentials<ServerInRegion> server = adapter.createNodeWithGroupEncodedIntoName(\"test\", \"test-e92\", template);\n      assertNotNull(server);\n      // Response irrelevant in this expect test - just verifying the request.\n   }\n\n   public void testCreateNodeWithGroupEncodedIntoNameWithDiskConfig() throws Exception {\n\n      HttpRequest createServer = HttpRequest\n         .builder()\n         .method(\"POST\")\n         .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers\")\n         .addHeader(\"Accept\", \"application/json\")\n         .addHeader(\"X-Auth-Token\", authToken)\n         .payload(payloadFromStringWithContentType(\n                  \"{\\\"server\\\":{\\\"name\\\":\\\"test-e92\\\",\\\"imageRef\\\":\\\"2235\\\",\\\"flavorRef\\\":\\\"100\\\",\\\"OS-DCF:diskConfig\\\":\\\"AUTO\\\"}}\", \"application/json\"))\n         .build();\n\n      HttpResponse createServerResponse = HttpResponse.builder().statusCode(202).message(\"HTTP/1.1 202 Accepted\")\n         .payload(payloadFromResourceWithContentType(\"/new_server_disk_config_auto.json\", \"application/json; charset=UTF-8\")).build();\n\n      Map<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder()\n               .put(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess)\n               .put(extensionsOfNovaRequest, extensionsOfNovaResponse)\n               .put(listDetail, listDetailResponse)\n               .put(listFlavorsDetail, listFlavorsDetailResponse)\n               .put(createServer, createServerResponse)\n               .put(serverDetail, serverDetailResponse).build();\n\n      Injector forDiskConfig = requestsSendResponses(requestResponseMap);\n\n      Template template = forDiskConfig.getInstance(TemplateBuilder.class).build();\n      template.getOptions().as(NovaTemplateOptions.class).diskConfig(Server.DISK_CONFIG_AUTO);\n\n      NovaComputeServiceAdapter adapter = forDiskConfig.getInstance(NovaComputeServiceAdapter.class);\n\n      NodeAndInitialCredentials<ServerInRegion> server = adapter.createNodeWithGroupEncodedIntoName(\"test\", \"test-e92\", template);\n      assertNotNull(server);\n      assertEquals(server.getNode().getServer().getDiskConfig().orNull(), Server.DISK_CONFIG_AUTO);\n   }\n\n   public void testCreateNodeWithGroupEncodedIntoNameWithConfigDrive() throws Exception {\n\n      HttpRequest createServer = HttpRequest\n         .builder()\n         .method(\"POST\")\n         .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers\")\n         .addHeader(\"Accept\", \"application/json\")\n         .addHeader(\"X-Auth-Token\", authToken)\n         .payload(payloadFromStringWithContentType(\n                  \"{\\\"server\\\":{\\\"name\\\":\\\"test-e92\\\",\\\"imageRef\\\":\\\"2235\\\",\\\"flavorRef\\\":\\\"100\\\",\\\"config_drive\\\":\\\"true\\\"}}\", \"application/json\"))\n         .build();\n\n      HttpResponse createServerResponse = HttpResponse.builder().statusCode(202).message(\"HTTP/1.1 202 Accepted\")\n         .payload(payloadFromResourceWithContentType(\"/new_server_config_drive.json\", \"application/json; charset=UTF-8\")).build();\n\n      Map<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder()\n               .put(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess)\n               .put(extensionsOfNovaRequest, extensionsOfNovaResponse)\n               .put(listDetail, listDetailResponse)\n               .put(listFlavorsDetail, listFlavorsDetailResponse)\n               .put(createServer, createServerResponse)\n               .put(serverDetail, serverDetailResponse).build();\n\n      Injector forConfigDrive = requestsSendResponses(requestResponseMap);\n\n      Template template = forConfigDrive.getInstance(TemplateBuilder.class).build();\n      template.getOptions().as(NovaTemplateOptions.class).configDrive(true);\n\n      NovaComputeServiceAdapter adapter = forConfigDrive.getInstance(NovaComputeServiceAdapter.class);\n\n      NodeAndInitialCredentials<ServerInRegion> server = adapter.createNodeWithGroupEncodedIntoName(\"test\", \"test-e92\", template);\n      assertNotNull(server);\n   }\n\n   public void testCreateNodeWithGroupEncodedIntoNameWithNovaNetworks() throws Exception {\n\n      HttpRequest createServer = HttpRequest\n         .builder()\n         .method(\"POST\")\n         .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers\")\n         .addHeader(\"Accept\", \"application/json\")\n         .addHeader(\"X-Auth-Token\", authToken)\n         .payload(payloadFromStringWithContentType(\n                  \"{\\\"server\\\":{\\\"name\\\":\\\"test-e92\\\",\\\"imageRef\\\":\\\"2235\\\",\\\"flavorRef\\\":\\\"100\\\",\\\"networks\\\":[{\\\"uuid\\\":\\\"12345\\\",\\\"port\\\":\\\"67890\\\",\\\"fixed_ip\\\":\\\"192.168.0.1\\\"},{\\\"uuid\\\":\\\"54321\\\",\\\"port\\\":\\\"09876\\\",\\\"fixed_ip\\\":\\\"192.168.0.2\\\"},{\\\"uuid\\\":\\\"non-nova-uuid\\\"}]}}\", \"application/json\"))\n         .build();\n\n      HttpResponse createServerResponse = HttpResponse.builder().statusCode(202).message(\"HTTP/1.1 202 Accepted\")\n         .payload(payloadFromResourceWithContentType(\"/new_server_nova_networks.json\", \"application/json; charset=UTF-8\")).build();\n\n      Map<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder()\n               .put(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess)\n               .put(extensionsOfNovaRequest, extensionsOfNovaResponse)\n               .put(listDetail, listDetailResponse)\n               .put(listFlavorsDetail, listFlavorsDetailResponse)\n               .put(createServer, createServerResponse)\n               .put(serverDetail, serverDetailResponse).build();\n\n      Injector forNovaNetworks = requestsSendResponses(requestResponseMap);\n\n      Template template = forNovaNetworks.getInstance(TemplateBuilder.class).build();\n      template.getOptions().as(NovaTemplateOptions.class)\n         .networks(\"non-nova-uuid\")\n         .novaNetworks(\n               ImmutableSet.of(\n                     Network.builder()\n                        .networkUuid(\"12345\")\n                        .portUuid(\"67890\")\n                        .fixedIp(\"192.168.0.1\")\n                        .build(),\n                     Network.builder()\n                        .networkUuid(\"54321\")\n                        .portUuid(\"09876\")\n                        .fixedIp(\"192.168.0.2\")\n                        .build()));\n\n      NovaComputeServiceAdapter adapter = forNovaNetworks.getInstance(NovaComputeServiceAdapter.class);\n\n      NodeAndInitialCredentials<ServerInRegion> server = adapter.createNodeWithGroupEncodedIntoName(\"test\", \"test-e92\", template);\n      assertNotNull(server);\n   }\n\n   public void testCreateNodeWithGroupEncodedIntoNameWhenSecurityGroupsArePresent() throws Exception {\n\n      HttpRequest createServer = HttpRequest\n         .builder()\n         .method(\"POST\")\n         .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers\")\n         .addHeader(\"Accept\", \"application/json\")\n         .addHeader(\"X-Auth-Token\", authToken)\n         .payload(payloadFromStringWithContentType(\n                  \"{\\\"server\\\":{\\\"name\\\":\\\"test-e92\\\",\\\"imageRef\\\":\\\"2235\\\",\\\"flavorRef\\\":\\\"100\\\",\\\"security_groups\\\":[{\\\"name\\\":\\\"group1\\\"},{\\\"name\\\":\\\"group2\\\"}]}}\", \"application/json\"))\n         .build();\n\n      HttpResponse createServerResponse = HttpResponse.builder().statusCode(202).message(\"HTTP/1.1 202 Accepted\")\n         .payload(payloadFromResourceWithContentType(\"/new_server.json\", \"application/json; charset=UTF-8\")).build();\n\n      Map<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder()\n               .put(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess)\n               .put(extensionsOfNovaRequest, extensionsOfNovaResponse)\n               .put(listDetail, listDetailResponse)\n               .put(listFlavorsDetail, listFlavorsDetailResponse)\n               .put(createServer, createServerResponse)\n               .put(serverDetail, serverDetailResponse).build();\n\n      Injector forSecurityGroups = requestsSendResponses(requestResponseMap);\n\n      Template template = forSecurityGroups.getInstance(TemplateBuilder.class).build();\n      template.getOptions().as(NovaTemplateOptions.class).securityGroups(\"group1\", \"group2\");\n\n      NovaComputeServiceAdapter adapter = forSecurityGroups.getInstance(NovaComputeServiceAdapter.class);\n\n      NodeAndInitialCredentials<ServerInRegion> server = adapter.createNodeWithGroupEncodedIntoName(\"test\", \"test-e92\",\n               template);\n      assertNotNull(server);\n      assertEquals(server.getCredentials(), LoginCredentials.builder().password(\"ZWuHcmTMQ7eXoHeM\").build());\n   }\n\n   /**\n    * We need to choose the correct credential for attempts to start the server. cloud-init or the\n    * like will set the ssh key as the login credential, and not necessarily will password\n    * authentication even be available.\n    */\n   public void testWhenKeyPairPresentWeUsePrivateKeyAsCredentialNotPassword() throws Exception {\n\n      HttpRequest createServer = HttpRequest\n         .builder()\n         .method(\"POST\")\n         .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers\")\n         .addHeader(\"Accept\", \"application/json\")\n         .addHeader(\"X-Auth-Token\", authToken)\n         .payload(payloadFromStringWithContentType(\n                  \"{\\\"server\\\":{\\\"name\\\":\\\"test-e92\\\",\\\"imageRef\\\":\\\"2235\\\",\\\"flavorRef\\\":\\\"100\\\",\\\"key_name\\\":\\\"foo\\\"}}\", \"application/json\"))\n         .build();\n\n\n      HttpResponse createServerResponse = HttpResponse.builder().statusCode(202).message(\"HTTP/1.1 202 Accepted\")\n         .payload(payloadFromResourceWithContentType(\"/new_server_no_adminpass.json\", \"application/json; charset=UTF-8\")).build();\n\n      Map<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder()\n               .put(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess)\n               .put(extensionsOfNovaRequest, extensionsOfNovaResponse)\n               .put(listDetail, listDetailResponse)\n               .put(listFlavorsDetail, listFlavorsDetailResponse)\n               .put(createServer, createServerResponse)\n               .put(serverDetail, serverDetailResponse).build();\n\n      Injector forSecurityGroups = requestsSendResponses(requestResponseMap);\n\n      Template template = forSecurityGroups.getInstance(TemplateBuilder.class).build();\n      template.getOptions().as(NovaTemplateOptions.class).keyPairName(\"foo\").overrideLoginPrivateKey(\"privateKey\");\n\n      NovaComputeServiceAdapter adapter = forSecurityGroups.getInstance(NovaComputeServiceAdapter.class);\n\n      NodeAndInitialCredentials<ServerInRegion> server = adapter.createNodeWithGroupEncodedIntoName(\"test\", \"test-e92\",\n               template);\n      assertNotNull(server);\n      assertEquals(server.getCredentials(), LoginCredentials.builder().privateKey(\"privateKey\").build());\n   }\n\n\n   /**\n    * When enable_instance_password is false, then no admin pass is generated.\n    * However in this case if you don't specify the name of the SSH keypair to\n    * inject, then you simply cannot log in to the server.\n    */\n   public void testNoKeyPairOrAdminPass() throws Exception {\n\n      HttpRequest createServer = HttpRequest\n         .builder()\n         .method(\"POST\")\n         .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers\")\n         .addHeader(\"Accept\", \"application/json\")\n         .addHeader(\"X-Auth-Token\", authToken)\n         .payload(payloadFromStringWithContentType(\n                  \"{\\\"server\\\":{\\\"name\\\":\\\"test-e92\\\",\\\"imageRef\\\":\\\"2235\\\",\\\"flavorRef\\\":\\\"100\\\"}}\", \"application/json\"))\n         .build();\n\n      HttpResponse createServerResponse = HttpResponse.builder().statusCode(202).message(\"HTTP/1.1 202 Accepted\")\n         .payload(payloadFromResourceWithContentType(\"/new_server_no_adminpass.json\", \"application/json; charset=UTF-8\")).build();\n\n      Map<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder()\n               .put(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess)\n               .put(extensionsOfNovaRequest, extensionsOfNovaResponse)\n               .put(listDetail, listDetailResponse)\n               .put(listFlavorsDetail, listFlavorsDetailResponse)\n               .put(createServer, createServerResponse)\n               .put(serverDetail, serverDetailResponse).build();\n\n      Injector forSecurityGroups = requestsSendResponses(requestResponseMap);\n\n      Template template = forSecurityGroups.getInstance(TemplateBuilder.class).build();\n\n      NovaComputeServiceAdapter adapter = forSecurityGroups.getInstance(NovaComputeServiceAdapter.class);\n\n      NodeAndInitialCredentials<ServerInRegion> server = adapter.createNodeWithGroupEncodedIntoName(\"test\", \"test-e92\",\n            template);\n      assertNotNull(server);\n      assertNull(server.getCredentials());\n   }\n\n   /**\n    * Test successful suspend/resume via ComputeService which depends on\n    * Admin extension being installed in OpenStack\n    */\n   public void testSuspendWithAdminExtensionSucceeds() throws Exception {\n\n      HttpRequest suspendServer = HttpRequest\n         .builder()\n         .method(\"POST\")\n         .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers/71752/action\")\n         .addHeader(\"Accept\", \"application/json\")\n         .addHeader(\"X-Auth-Token\", authToken)\n         .payload(payloadFromStringWithContentType(\n                  \"{\\\"suspend\\\":null}\", \"application/json\"))\n         .build();\n\n      HttpResponse suspendServerResponse = HttpResponse.builder()\n            .statusCode(202)\n            .build();\n\n      HttpResponse serverDetailSuspendedResponse = HttpResponse.builder().statusCode(200)\n              .payload(payloadFromResource(\"/server_details_suspended.json\")).build();\n      \n      Map<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder()\n               .put(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess)\n               .put(extensionsOfNovaRequest, extensionsOfNovaResponse)\n               .put(listDetail, listDetailResponse)\n               .put(listFlavorsDetail, listFlavorsDetailResponse)\n               .put(suspendServer, suspendServerResponse)\n               .put(serverDetail, serverDetailSuspendedResponse).build();\n\n      Injector forAdminExtension = requestsSendResponses(requestResponseMap);\n\n      ComputeService computeService = forAdminExtension.getInstance(ComputeService.class);\n\n      computeService.suspendNode(\"az-1.region-a.geo-1/71752\");\n   }\n\n   /**\n    * Test failed suspend/resume via ComputeService which depends on\n    * Admin extension being installed in OpenStack. Throws UOE if extension is missing.\n    */\n   @Test(expectedExceptions =  UnsupportedOperationException.class)\n   public void testSuspendWithoutAdminExtensionThrowsUOE() throws Exception {\n\n      HttpRequest suspendServer = HttpRequest\n            .builder()\n            .method(\"POST\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers/71752/action\")\n            .addHeader(\"X-Auth-Token\", authToken)\n            .payload(payloadFromStringWithContentType(\n                  \"{\\\"suspend\\\":null}\", \"application/json\"))\n            .build();\n\n      HttpResponse suspendServerResponse = HttpResponse.builder()\n            .statusCode(202)\n            .build();\n\n      HttpResponse serverDetailSuspendedResponse = HttpResponse.builder().statusCode(200)\n              .payload(payloadFromResource(\"/server_details_suspended.json\")).build();\n\n      Map<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder()\n            .put(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess)\n            .put(extensionsOfNovaRequest, unmatchedExtensionsOfNovaResponse)\n            .put(listDetail, listDetailResponse)\n            .put(listFlavorsDetail, listFlavorsDetailResponse)\n            .put(suspendServer, suspendServerResponse)\n            .put(serverDetail, serverDetailSuspendedResponse).build();\n\n      Injector forAdminExtension = requestsSendResponses(requestResponseMap);\n\n      ComputeService compute = forAdminExtension.getInstance(ComputeService.class);\n\n      compute.suspendNode(\"az-1.region-a.geo-1/71752\");\n   }\n\n   @Override\n   public Injector apply(ComputeServiceContext input) {\n      return input.utils().injector();\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties overrides = super.setupProperties();\n      // only specify one region so that we don't have to configure requests for multiple regions\n      overrides.setProperty(\"jclouds.regions\", \"az-1.region-a.geo-1\");\n      return overrides;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/compute/NovaComputeServiceExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.compute;\n\nimport static org.jclouds.compute.util.ComputeServiceUtils.getCores;\nimport static org.jclouds.openstack.nova.v2_0.compute.options.NovaTemplateOptions.Builder.blockUntilRunning;\nimport static org.jclouds.openstack.nova.v2_0.compute.options.NovaTemplateOptions.Builder.keyPairName;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.Set;\nimport java.util.concurrent.atomic.AtomicInteger;\n\nimport org.jclouds.compute.ComputeService;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.domain.Location;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaComputeServiceExpectTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMap.Builder;\nimport com.google.common.collect.Iterables;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.TypeLiteral;\n\n/**\n * Tests the compute service abstraction of the nova api.\n */\n@Test(groups = \"unit\", testName = \"NovaComputeServiceExpectTest\")\npublic class NovaComputeServiceExpectTest extends BaseNovaComputeServiceExpectTest {\n\n   @Override\n   protected Properties setupProperties() {\n      Properties overrides = super.setupProperties();\n      // only specify limited regions so that we don't have to configure requests for multiple regions.\n      // since we are doing tests with keystone responses from hpcloud and also openstack, we have\n      // to whitelist one region from each\n      overrides.setProperty(\"jclouds.regions\", \"az-1.region-a.geo-1,RegionOne\");\n      return overrides;\n   }\n\n   public void testListLocationsWhenResponseIs2xx() throws Exception {\n\n      Map<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder()\n            .put(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess)\n            .put(extensionsOfNovaRequest, extensionsOfNovaResponse).put(listDetail, listDetailResponse)\n            .put(listServers, listServersResponse).put(listFlavorsDetail, listFlavorsDetailResponse).build();\n\n      ComputeService apiWhenServersExist = requestsSendResponses(requestResponseMap);\n\n      Set<? extends Location> locations = apiWhenServersExist.listAssignableLocations();\n      assertNotNull(locations);\n      assertEquals(locations.size(), 1);\n      assertEquals(locations.iterator().next().getId(), \"az-1.region-a.geo-1\");\n\n      assertNotNull(apiWhenServersExist.listNodes());\n      assertEquals(apiWhenServersExist.listNodes().size(), 1);\n      assertEquals(apiWhenServersExist.listNodes().iterator().next().getId(),\n            \"az-1.region-a.geo-1/71752\");\n      assertEquals(apiWhenServersExist.listNodes().iterator().next().getName(), \"sample-server\");\n   }\n\n   Map<HttpRequest, HttpResponse> defaultTemplateOpenStack = ImmutableMap\n         .<HttpRequest, HttpResponse> builder()\n         .put(keystoneAuthWithUsernameAndPasswordAndTenantName,\n               HttpResponse\n                     .builder()\n                     .statusCode(200)\n                     .message(\"HTTP/1.1 200\")\n                     .payload(\n                           payloadFromResourceWithContentType(\"/keystoneAuthResponse_openstack.json\", \"application/json\"))\n                     .build())\n         .put(extensionsOfNovaRequest.toBuilder()\n               .endpoint(\"https://nova-api.openstack.org:9774/v2/3456/extensions\").build(),\n               HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/extension_list_openstack.json\"))\n                     .build())\n         .put(listDetail.toBuilder()\n               .endpoint(\"https://nova-api.openstack.org:9774/v2/3456/images/detail\").build(),\n               HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/image_list_detail_openstack.json\"))\n                     .build())\n         .put(listServers.toBuilder()\n               .endpoint(\"https://nova-api.openstack.org:9774/v2/3456/servers/detail\").build(),\n               listServersResponse)\n         .put(listFlavorsDetail.toBuilder()\n               .endpoint(\"https://nova-api.openstack.org:9774/v2/3456/flavors/detail\").build(),\n               HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/flavor_list_detail_openstack.json\"))\n                     .build()).build();\n\n   public void testDefaultTemplateOpenStack() throws Exception {\n\n      ComputeService apiForOpenStack = requestsSendResponses(defaultTemplateOpenStack);\n\n      Template defaultTemplate = apiForOpenStack.templateBuilder().imageId(\"RegionOne/15\").build();\n      checkTemplate(defaultTemplate);\n      checkTemplate(apiForOpenStack.templateBuilder().fromTemplate(defaultTemplate).build());\n\n   }\n\n   private void checkTemplate(Template defaultTemplate) {\n      assertEquals(defaultTemplate.getImage().getId(), \"RegionOne/15\");\n      assertEquals(defaultTemplate.getImage().getProviderId(), \"15\");\n      assertEquals(defaultTemplate.getHardware().getId(), \"RegionOne/1\");\n      assertEquals(defaultTemplate.getHardware().getProviderId(), \"1\");\n      assertEquals(defaultTemplate.getLocation().getId(), \"RegionOne\");\n      assertEquals(getCores(defaultTemplate.getHardware()), 1.0d);\n   }\n\n   HttpRequest list = HttpRequest\n         .builder()\n         .method(\"GET\")\n         .endpoint(\"https://nova-api.openstack.org:9774/v2/3456/os-security-groups\")\n         .addHeader(\"Accept\", \"application/json\")\n         .addHeader(\"X-Auth-Token\", authToken).build();\n\n   HttpResponse notFound = HttpResponse.builder().statusCode(404).build();\n\n   HttpRequest createWithPrefixOnGroup = HttpRequest\n         .builder()\n         .method(\"POST\")\n         .endpoint(\"https://nova-api.openstack.org:9774/v2/3456/os-security-groups\")\n         .addHeader(\"Accept\", \"application/json\")\n         .addHeader(\"X-Auth-Token\", authToken)\n         .payload(\n               payloadFromStringWithContentType(\n                     \"{\\\"security_group\\\":{\\\"name\\\":\\\"jclouds-test\\\",\\\"description\\\":\\\"jclouds-test\\\"}}\",\n                     \"application/json\")).build();\n\n   HttpResponse securityGroupCreated = HttpResponse.builder().statusCode(200)\n         .payload(payloadFromResource(\"/securitygroup_created.json\")).build();\n\n   HttpRequest createRuleForDefaultPort22 = HttpRequest\n         .builder()\n         .method(\"POST\")\n         .endpoint(\"https://nova-api.openstack.org:9774/v2/3456/os-security-group-rules\")\n         .addHeader(\"Accept\", \"application/json\")\n         .addHeader(\"X-Auth-Token\", authToken)\n         .payload(\n               payloadFromStringWithContentType(\n                     \"{\\\"security_group_rule\\\":{\\\"parent_group_id\\\":\\\"160\\\",\\\"cidr\\\":\\\"0.0.0.0/0\\\",\\\"ip_protocol\\\":\\\"tcp\\\",\\\"from_port\\\":\\\"22\\\",\\\"to_port\\\":\\\"22\\\"}}\",\n                     \"application/json\")).build();\n\n   HttpResponse securityGroupRuleCreated = HttpResponse.builder().statusCode(200)\n         .payload(payloadFromResource(\"/securitygrouprule_created.json\")).build();\n\n   HttpRequest getSecurityGroup = HttpRequest\n         .builder()\n         .method(\"GET\")\n         .endpoint(\"https://nova-api.openstack.org:9774/v2/3456/os-security-groups/160\")\n         .addHeader(\"Accept\", \"application/json\")\n         .addHeader(\"X-Auth-Token\", authToken).build();\n\n   HttpResponse securityGroupWithPort22 = HttpResponse.builder().statusCode(200)\n         .payload(payloadFromResource(\"/securitygroup_details_port22.json\")).build();\n\n   HttpRequest createKeyPair = HttpRequest\n         .builder()\n         .method(\"POST\")\n         .endpoint(\"https://nova-api.openstack.org:9774/v2/3456/os-keypairs\")\n         .addHeader(\"Accept\", \"application/json\")\n         .addHeader(\"X-Auth-Token\", authToken)\n         .payload(\n               payloadFromStringWithContentType(\n                     \"{\\\"keypair\\\":{\\\"name\\\":\\\"jclouds-test-0\\\"}}\",\n                     \"application/json\")).build();\n\n   HttpResponse keyPairWithPrivateKey = HttpResponse.builder().statusCode(200)\n         .payload(payloadFromResource(\"/keypair_created_computeservice.json\")).build();\n\n   HttpRequest getKeyPair = HttpRequest\n           .builder()\n           .method(\"GET\")\n           .endpoint(\"https://nova-api.openstack.org:9774/v2/3456/os-keypairs/fooPair\")\n           .addHeader(\"Accept\", \"application/json\")\n           .addHeader(\"X-Auth-Token\", authToken).build();\n\n   HttpResponse keyPairDetails = HttpResponse.builder().statusCode(200)\n           .payload(payloadFromResource(\"/keypair_details.json\")).build();\n   \n   HttpRequest serverDetail = HttpRequest\n         .builder()\n         .method(\"GET\")\n         .endpoint(\"https://nova-api.openstack.org:9774/v2/3456/servers/71752\")\n         .addHeader(\"Accept\", \"application/json\")\n         .addHeader(\"X-Auth-Token\", authToken).build();\n\n   HttpResponse serverDetailResponse = HttpResponse.builder().statusCode(200)\n         .payload(payloadFromResource(\"/server_details.json\")).build();\n\n   @Test\n   public void testCreateNodeWithGeneratedKeyPair() throws Exception {\n      Builder<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder()\n            .putAll(defaultTemplateOpenStack);\n      requestResponseMap.put(createKeyPair, keyPairWithPrivateKey);\n      requestResponseMap.put(list, notFound);\n      requestResponseMap.put(createWithPrefixOnGroup, securityGroupCreated);\n      requestResponseMap.put(createRuleForDefaultPort22, securityGroupRuleCreated);\n      requestResponseMap.put(getSecurityGroup, securityGroupWithPort22);\n      \n      HttpRequest createServerWithGeneratedKeyPair = HttpRequest\n            .builder()\n            .method(\"POST\")\n            .endpoint(\"https://nova-api.openstack.org:9774/v2/3456/servers\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken)\n            .payload(\n                  payloadFromStringWithContentType(\n                        \"{\\\"server\\\":{\\\"name\\\":\\\"test-1\\\",\\\"imageRef\\\":\\\"2235\\\",\\\"flavorRef\\\":\\\"1\\\",\\\"metadata\\\":{\\\"jclouds_tags\\\":\\\"jclouds_sg-RegionOne/2769\\\"},\\\"key_name\\\":\\\"jclouds-test-0\\\",\\\"security_groups\\\":[{\\\"name\\\":\\\"jclouds-test\\\"}]}}\",\n                        \"application/json\")).build();\n\n      HttpResponse createdServer = HttpResponse.builder().statusCode(202).message(\"HTTP/1.1 202 Accepted\")\n            .payload(payloadFromResourceWithContentType(\"/new_server.json\", \"application/json; charset=UTF-8\")).build();\n\n      requestResponseMap.put(createServerWithGeneratedKeyPair, createdServer);\n      requestResponseMap.put(serverDetail, serverDetailResponse);\n\n      ComputeService apiThatCreatesNode = requestsSendResponses(requestResponseMap.build(), new AbstractModule() {\n\n         @Override\n         protected void configure() {\n            // predicatable node names\n            final AtomicInteger suffix = new AtomicInteger();\n            bind(new TypeLiteral<Supplier<String>>() {\n            }).toInstance(new Supplier<String>() {\n\n               @Override\n               public String get() {\n                  return suffix.getAndIncrement() + \"\";\n               }\n\n            });\n         }\n\n      });\n\n      NodeMetadata node = Iterables.getOnlyElement(apiThatCreatesNode.createNodesInGroup(\"test\", 1,\n            blockUntilRunning(false).generateKeyPair(true)));\n      assertTrue(node.getCredentials().getOptionalPrivateKey().isPresent());\n   }\n\n   @Test\n   public void testCreateNodeWhileUserSpecifiesKeyPair() throws Exception {\n      Builder<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder()\n            .putAll(defaultTemplateOpenStack);\n      requestResponseMap.put(list, notFound);\n\n      requestResponseMap.put(getKeyPair, keyPairDetails);\n      \n      requestResponseMap.put(createWithPrefixOnGroup, securityGroupCreated);\n\n      requestResponseMap.put(createRuleForDefaultPort22, securityGroupRuleCreated);\n\n      requestResponseMap.put(getSecurityGroup, securityGroupWithPort22);\n\n      HttpRequest createServerWithSuppliedKeyPair = HttpRequest\n            .builder()\n            .method(\"POST\")\n            .endpoint(\"https://nova-api.openstack.org:9774/v2/3456/servers\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken)\n            .payload(\n                  payloadFromStringWithContentType(\n                        \"{\\\"server\\\":{\\\"name\\\":\\\"test-0\\\",\\\"imageRef\\\":\\\"2235\\\",\\\"flavorRef\\\":\\\"1\\\",\\\"metadata\\\":{\\\"jclouds_tags\\\":\\\"jclouds_sg-RegionOne/2769\\\"},\\\"key_name\\\":\\\"testkeypair\\\",\\\"security_groups\\\":[{\\\"name\\\":\\\"jclouds-test\\\"}]}}\",\n                        \"application/json\")).build();\n\n      HttpResponse createdServer = HttpResponse.builder().statusCode(202).message(\"HTTP/1.1 202 Accepted\")\n            .payload(payloadFromResourceWithContentType(\"/new_server.json\", \"application/json; charset=UTF-8\")).build();\n\n      requestResponseMap.put(createServerWithSuppliedKeyPair, createdServer);\n      requestResponseMap.put(serverDetail, serverDetailResponse);\n\n      ComputeService apiThatCreatesNode = requestsSendResponses(requestResponseMap.build(), new AbstractModule() {\n\n         @Override\n         protected void configure() {\n            // predictable node names\n            final AtomicInteger suffix = new AtomicInteger();\n            bind(new TypeLiteral<Supplier<String>>() {\n            }).toInstance(new Supplier<String>() {\n\n               @Override\n               public String get() {\n                  return suffix.getAndIncrement() + \"\";\n               }\n\n            });\n         }\n\n      });\n\n      NodeMetadata node = Iterables.getOnlyElement(apiThatCreatesNode.createNodesInGroup(\"test\", 1,\n            keyPairName(\"fooPair\").overrideLoginPrivateKey(\"privateKey\").blockUntilRunning(false)));\n      // we don't have access to this private key\n      assertTrue(node.getCredentials().getOptionalPrivateKey().isPresent());\n   }\n\n   @Test\n   public void testCreateNodeWhileUserSpecifiesKeyPairAndUserSpecifiedGroups() throws Exception {\n      Builder<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder()\n            .putAll(defaultTemplateOpenStack);\n      requestResponseMap.put(list, HttpResponse.builder().statusCode(200)\n              .payload(payloadFromResource(\"/securitygroup_list.json\")).build());\n\n      requestResponseMap.put(getKeyPair, keyPairDetails);\n\n      requestResponseMap.put(createWithPrefixOnGroup, securityGroupCreated);\n\n      requestResponseMap.put(createRuleForDefaultPort22, securityGroupRuleCreated);\n\n      requestResponseMap.put(getSecurityGroup, securityGroupWithPort22);\n\n      HttpRequest getSecurityGroup = HttpRequest\n              .builder()\n              .method(\"GET\")\n              .endpoint(\"https://nova-api.openstack.org:9774/v2/3456/os-security-groups/mygroup\")\n              .addHeader(\"Accept\", \"application/json\")\n              .addHeader(\"X-Auth-Token\", authToken).build();\n\n      HttpResponse securityGroupWDetails = HttpResponse.builder().statusCode(200)\n              .payload(payloadFromResource(\"/securitygroup_details_port22.json\")).build();\n\n      requestResponseMap.put(getSecurityGroup, securityGroupWDetails);\n      \n      HttpRequest createServerWithSuppliedKeyPairAndGroup = HttpRequest\n            .builder()\n            .method(\"POST\")\n            .endpoint(\"https://nova-api.openstack.org:9774/v2/3456/servers\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken)\n            .payload(\n                  payloadFromStringWithContentType(\n                        \"{\\\"server\\\":{\\\"name\\\":\\\"test-0\\\",\\\"imageRef\\\":\\\"2235\\\",\\\"flavorRef\\\":\\\"1\\\",\\\"key_name\\\":\\\"testkeypair\\\",\\\"security_groups\\\":[{\\\"name\\\":\\\"name1\\\"}]}}\",\n                        \"application/json\")).build();\n\n      HttpResponse createdServer = HttpResponse.builder().statusCode(202).message(\"HTTP/1.1 202 Accepted\")\n            .payload(payloadFromResourceWithContentType(\"/new_server.json\", \"application/json; charset=UTF-8\")).build();\n\n      requestResponseMap.put(createServerWithSuppliedKeyPairAndGroup, createdServer);\n      \n      requestResponseMap.put(serverDetail, serverDetailResponse);\n\n      ComputeService apiThatCreatesNode = requestsSendResponses(requestResponseMap.build(), new AbstractModule() {\n\n         @Override\n         protected void configure() {\n            // predictable node names\n            final AtomicInteger suffix = new AtomicInteger();\n            bind(new TypeLiteral<Supplier<String>>() {\n            }).toInstance(new Supplier<String>() {\n\n               @Override\n               public String get() {\n                  return suffix.getAndIncrement() + \"\";\n               }\n\n            });\n         }\n\n      });\n\n      NodeMetadata node = Iterables.getOnlyElement(apiThatCreatesNode.createNodesInGroup(\"test\", 1,\n            keyPairName(\"fooPair\").securityGroups(\"name1\").blockUntilRunning(false)));\n      // we don't have access to this private key\n      assertTrue(!node.getCredentials().getOptionalPrivateKey().isPresent());\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/compute/NovaComputeServiceLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.compute;\n\nimport static java.util.logging.Logger.getAnonymousLogger;\n\nimport java.util.Properties;\n\nimport org.jclouds.compute.internal.BaseComputeServiceLiveTest;\nimport org.jclouds.openstack.keystone.config.KeystoneProperties;\nimport org.jclouds.openstack.nova.v2_0.config.NovaProperties;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.sshj.config.SshjSshClientModule;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Module;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"NovaComputeServiceLiveTest\")\npublic class NovaComputeServiceLiveTest extends BaseComputeServiceLiveTest {\n\n   public NovaComputeServiceLiveTest() {\n      provider = \"openstack-nova\";\n   }\n\n   @Override\n   protected Module getSshModule() {\n      return new SshjSshClientModule();\n   }\n   \n   @Override\n   public void testOptionToNotBlock() {\n      // start call is blocking anyway.\n   }\n\n   @Test(enabled = true, dependsOnMethods = \"testReboot\")\n   public void testSuspendResume() throws Exception {\n      try {\n         // may fail because of lack of AdminActions extension or non-admin user, so log and continue\n         super.testSuspendResume();\n      } catch (AuthorizationException e) {\n         getAnonymousLogger().info(\"testSuspendResume() threw, probably due to lack of privileges: \" + e.getMessage());\n      } catch (UnsupportedOperationException e) {\n         getAnonymousLogger().info(\"testSuspendResume() threw, probably due to unavailable AdminActions extension: \" + e.getMessage());\n      }\n   }\n\n   @Test(enabled = true, dependsOnMethods = \"testSuspendResume\")\n   @Override\n   public void testGetNodesWithDetails() throws Exception {\n      super.testGetNodesWithDetails();\n   }\n\n   @Test(enabled = true, dependsOnMethods = \"testSuspendResume\")\n   @Override\n   public void testListNodes() throws Exception {\n      super.testListNodes();\n   }\n\n   @Test(enabled = true, dependsOnMethods = \"testSuspendResume\")\n   @Override\n   public void testListNodesByIds() throws Exception {\n      super.testListNodesByIds();\n   }\n\n   @Test(enabled = true, dependsOnMethods = { \"testListNodes\", \"testGetNodesWithDetails\", \"testListNodesByIds\" })\n   @Override\n   public void testDestroyNodes() {\n      super.testDestroyNodes();\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      setIfTestSystemPropertyPresent(props, KeystoneProperties.CREDENTIAL_TYPE);\n      setIfTestSystemPropertyPresent(props, NovaProperties.AUTO_ALLOCATE_FLOATING_IPS);\n      return props;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/compute/NovaWithNeutronComputeServiceLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.compute;\n\nimport static java.util.logging.Logger.getAnonymousLogger;\n\nimport java.util.Properties;\n\nimport com.google.common.collect.ImmutableSet;\nimport org.jclouds.Context;\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.compute.internal.BaseComputeServiceLiveTest;\nimport org.jclouds.config.ContextLinking;\nimport org.jclouds.encryption.bouncycastle.config.BouncyCastleCryptoModule;\nimport org.jclouds.logging.config.LoggingModule;\nimport org.jclouds.logging.slf4j.config.SLF4JLoggingModule;\nimport org.jclouds.openstack.keystone.config.KeystoneProperties;\nimport org.jclouds.openstack.nova.v2_0.config.NovaProperties;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.sshj.config.SshjSshClientModule;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Module;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"NovaWithNeutronComputeServiceLiveTest\")\npublic class NovaWithNeutronComputeServiceLiveTest extends BaseComputeServiceLiveTest {\n\n   private Context neutronApiContext;\n\n   public NovaWithNeutronComputeServiceLiveTest() {\n      provider = \"openstack-nova\";\n\n      Properties overrides = setupProperties();\n      neutronApiContext = ContextBuilder.newBuilder(\"openstack-neutron\")\n              .endpoint(setIfTestSystemPropertyPresent(overrides,\n                      \"openstack-nova.endpoint\"))\n              .credentials(setIfTestSystemPropertyPresent(overrides,\n                      \"openstack-nova.identity\"),\n                      setIfTestSystemPropertyPresent(overrides, \"openstack-nova.credential\"))\n              .modules(ImmutableSet.<Module>of(\n                      new SshjSshClientModule(),\n                      new SLF4JLoggingModule(),\n                      new BouncyCastleCryptoModule())\n              )\n              .build();\n   }\n\n   @Override\n   protected Module getSshModule() {\n      return new SshjSshClientModule();\n   }\n\n   @Override\n   protected LoggingModule getLoggingModule() {\n      return new SLF4JLoggingModule();\n   }\n\n   @Override\n   protected Iterable<Module> setupModules() {\n      return ImmutableSet.of(\n              ContextLinking.linkContext(neutronApiContext),\n              getLoggingModule(),\n              credentialStoreModule,\n              getSshModule()\n      );\n   }\n   \n   @Override\n   public void testOptionToNotBlock() {\n      // start call is blocking anyway.\n   }\n\n   @Test(enabled = true, dependsOnMethods = \"testReboot\")\n   public void testSuspendResume() throws Exception {\n      try {\n         // may fail because of lack of AdminActions extension or non-admin user, so log and continue\n         super.testSuspendResume();\n      } catch (AuthorizationException e) {\n         getAnonymousLogger().info(\"testSuspendResume() threw, probably due to lack of privileges: \" + e.getMessage());\n      } catch (UnsupportedOperationException e) {\n         getAnonymousLogger().info(\"testSuspendResume() threw, probably due to unavailable AdminActions extension: \" + e.getMessage());\n      }\n   }\n\n   @Test(enabled = true, dependsOnMethods = \"testSuspendResume\")\n   @Override\n   public void testGetNodesWithDetails() throws Exception {\n      super.testGetNodesWithDetails();\n   }\n\n   @Test(enabled = true, dependsOnMethods = \"testSuspendResume\")\n   @Override\n   public void testListNodes() throws Exception {\n      super.testListNodes();\n   }\n\n   @Test(enabled = true, dependsOnMethods = \"testSuspendResume\")\n   @Override\n   public void testListNodesByIds() throws Exception {\n      super.testListNodesByIds();\n   }\n\n   @Test(enabled = true, dependsOnMethods = { \"testListNodes\", \"testGetNodesWithDetails\", \"testListNodesByIds\" })\n   @Override\n   public void testDestroyNodes() {\n      super.testDestroyNodes();\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      setIfTestSystemPropertyPresent(props, KeystoneProperties.CREDENTIAL_TYPE);\n      setIfTestSystemPropertyPresent(props, NovaProperties.AUTO_ALLOCATE_FLOATING_IPS);\n      return props;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/compute/extensions/NeutronSecurityGroupExtensionLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.compute.extensions;\n\nimport java.util.Properties;\nimport java.util.concurrent.ExecutionException;\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\n\nimport com.google.common.base.Optional;\nimport org.jclouds.Context;\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.compute.ComputeService;\nimport org.jclouds.compute.RunNodesException;\nimport org.jclouds.compute.domain.SecurityGroup;\nimport org.jclouds.compute.extensions.SecurityGroupExtension;\nimport org.jclouds.compute.extensions.internal.BaseSecurityGroupExtensionLiveTest;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.config.ContextLinking;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.logging.slf4j.config.SLF4JLoggingModule;\nimport org.jclouds.openstack.neutron.v2.NeutronApi;\nimport org.jclouds.rest.ApiContext;\nimport org.jclouds.sshj.config.SshjSshClientModule;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.reflect.TypeToken;\nimport com.google.inject.Module;\n\nimport static org.testng.Assert.assertTrue;\n\n/**\n * Live test for openstack-neutron {@link SecurityGroupExtension} implementation.\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"NeutronSecurityGroupExtensionLiveTest\")\npublic class NeutronSecurityGroupExtensionLiveTest extends BaseSecurityGroupExtensionLiveTest {\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.CONSOLE;\n\n   private Context neutronApiContext;\n\n   public NeutronSecurityGroupExtensionLiveTest() {\n      provider = \"openstack-nova\";\n\n      Properties overrides = setupProperties();\n      neutronApiContext = ContextBuilder.newBuilder(\"openstack-neutron\")\n               .endpoint(setIfTestSystemPropertyPresent(overrides,\n               \"openstack-nova.endpoint\"))\n               .credentials(setIfTestSystemPropertyPresent(overrides,\n               \"openstack-nova.identity\"),\n               setIfTestSystemPropertyPresent(overrides, \"openstack-nova.credential\"))\n              .modules(ImmutableSet.<Module>of(\n                      new SshjSshClientModule(),\n                      new SLF4JLoggingModule())\n              )\n              .build(new TypeToken<ApiContext<NeutronApi>>() {});\n   }\n\n\n   @Test(groups = { \"integration\", \"live\" }, singleThreaded = true)\n   public void testListSecurityGroups() throws RunNodesException, InterruptedException, ExecutionException {\n      skipIfSecurityGroupsNotSupported();\n      ComputeService computeService = view.getComputeService();\n\n      Optional<SecurityGroupExtension> securityGroupExtension = computeService.getSecurityGroupExtension();\n      assertTrue(securityGroupExtension.isPresent(), \"security extension was not present\");\n\n      for (SecurityGroup securityGroup : securityGroupExtension.get().listSecurityGroups()) {\n         logger.info(securityGroup.toString());\n      }\n\n   }\n\n   @Test(groups = { \"integration\", \"live\" }, singleThreaded = true)\n   public void testListSecurityGroupsForNode() throws RunNodesException, InterruptedException, ExecutionException {\n      skipIfSecurityGroupsNotSupported();\n      ComputeService computeService = view.getComputeService();\n\n      Optional<SecurityGroupExtension> securityGroupExtension = computeService.getSecurityGroupExtension();\n      assertTrue(securityGroupExtension.isPresent(), \"security extension was not present\");\n\n      for (SecurityGroup securityGroup : securityGroupExtension.get().listSecurityGroupsForNode(\"uk-1/97374b9f-c706-4c4a-ae5a-48b6d2e58db9\")) {\n         logger.info(securityGroup.toString());\n      }\n\n   }\n\n   @AfterClass\n   @Override\n   protected void tearDownContext() {\n      super.tearDownContext();\n   }\n\n   @Override\n   protected Iterable<Module> setupModules() {\n      return ImmutableSet.<Module> of(ContextLinking.linkContext(neutronApiContext), getLoggingModule(), credentialStoreModule, getSshModule());\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/compute/extensions/NovaImageExtensionExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.compute.extensions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Properties;\n\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.ImageTemplate;\nimport org.jclouds.compute.extensions.ImageExtension;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaComputeServiceExpectTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMap.Builder;\nimport com.google.common.util.concurrent.Futures;\n\n@Test(groups = \"unit\", testName = \"NovaImageExtensionExpectTest\")\npublic class NovaImageExtensionExpectTest extends BaseNovaComputeServiceExpectTest {\n\n   @Override\n   protected Properties setupProperties() {\n      Properties overrides = super.setupProperties();\n      overrides.setProperty(\"jclouds.regions\", \"az-1.region-a.geo-1\");\n      return overrides;\n   }\n\n   HttpRequest serverDetail = HttpRequest.builder().method(\"GET\")\n         .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers/71752\")\n         .addHeader(\"Accept\", \"application/json\")\n         .addHeader(\"X-Auth-Token\", authToken).build();\n\n   HttpResponse serverDetailResponse = HttpResponse.builder().statusCode(200)\n         .payload(payloadFromResource(\"/server_details.json\")).build();\n\n   HttpRequest createImage = HttpRequest.builder().method(\"POST\")\n         .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers/71752/action\")\n         .addHeader(\"Accept\", \"application/json\")\n         .addHeader(\"X-Auth-Token\", authToken)\n         .payload(\n               payloadFromStringWithContentType(\n                     \"{\\\"createImage\\\":{\\\"name\\\":\\\"test\\\", \\\"metadata\\\": {}}}\",\n                     \"application/json\")).build();\n\n   HttpResponse createImageResponse = HttpResponse.builder().statusCode(202)\n         .addHeader(\"Location\", \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/images/52415800-8b69-11e0-9b19-734f5736d2a2\")\n         .build();\n\n   HttpRequest getImage = HttpRequest.builder().method(\"GET\")\n         .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/images/52415800-8b69-11e0-9b19-734f5736d2a2\")\n         .addHeader(\"Accept\", \"application/json\")\n         .addHeader(\"X-Auth-Token\", authToken).build();\n\n   HttpResponse getImageResponse = HttpResponse.builder().statusCode(200)\n         .payload(payloadFromResource(\"/image_active.json\")).build();\n\n   public void testCreateImage() {\n      Builder<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder();\n      requestResponseMap.put(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess);\n      requestResponseMap.put(serverDetail, serverDetailResponse);\n      requestResponseMap.put(createImage, createImageResponse);\n      requestResponseMap.put(getImage, getImageResponse);\n\n      ImageExtension apiThatCreatesImage = requestsSendResponses(requestResponseMap.build()).getImageExtension().get();\n\n      ImageTemplate newImageTemplate = apiThatCreatesImage.buildImageTemplateFromNode(\"test\", \"az-1.region-a.geo-1/71752\");\n\n      Image image = Futures.getUnchecked(apiThatCreatesImage.createImage(newImageTemplate));\n      assertEquals(image.getId(), \"az-1.region-a.geo-1/52415800-8b69-11e0-9b19-734f5736d2a2\");\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/compute/extensions/NovaImageExtensionLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.compute.extensions;\n\nimport org.jclouds.compute.extensions.internal.BaseImageExtensionLiveTest;\nimport org.jclouds.sshj.config.SshjSshClientModule;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Module;\n\n/**\n * Live test for openstack-nova {@link ImageExtension} implementation.\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"NovaImageExtensionLiveTest\")\npublic class NovaImageExtensionLiveTest extends BaseImageExtensionLiveTest {\n\n   public NovaImageExtensionLiveTest() {\n      provider = \"openstack-nova\";\n   }\n\n   @Override\n   protected Module getSshModule() {\n      return new SshjSshClientModule();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/compute/extensions/NovaSecurityGroupExtensionExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.compute.extensions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.SecurityGroup;\nimport org.jclouds.compute.extensions.SecurityGroupExtension;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.net.domain.IpPermission;\nimport org.jclouds.net.domain.IpProtocol;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaComputeServiceExpectTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMap.Builder;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.LinkedHashMultimap;\nimport com.google.common.collect.Multimap;\nimport com.google.common.collect.Sets;\n\n@Test(groups = \"unit\", testName = \"NovaSecurityGroupExtensionExpectTest\")\npublic class NovaSecurityGroupExtensionExpectTest extends BaseNovaComputeServiceExpectTest {\n\n   protected String region = \"az-1.region-a.geo-1\";\n   protected HttpRequest list = HttpRequest.builder().method(\"GET\").endpoint(\n           URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-security-groups\")).headers(\n           ImmutableMultimap.<String, String> builder().put(\"Accept\", \"application/json\").put(\"X-Auth-Token\",\n                   authToken).build()).build();\n\n   protected HttpResponse listResponse = HttpResponse.builder().statusCode(200).payload(\n           payloadFromResource(\"/securitygroup_list_extension.json\")).build();\n\n   @Override\n   protected Properties setupProperties() {\n      Properties overrides = super.setupProperties();\n      overrides.setProperty(\"jclouds.regions\", region);\n      return overrides;\n   }\n\n   public void testListSecurityGroups() {\n\n\n      Builder<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder();\n      requestResponseMap.put(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess);\n      requestResponseMap.put(extensionsOfNovaRequest, extensionsOfNovaResponse);\n      requestResponseMap.put(list, listResponse);\n\n      SecurityGroupExtension extension = requestsSendResponses(requestResponseMap.build()).getSecurityGroupExtension().get();\n\n      Set<SecurityGroup> groups = extension.listSecurityGroups();\n      assertEquals(groups.size(), 1);\n   }\n\n   public void testListSecurityGroupsInLocation() {\n      HttpRequest list = HttpRequest.builder().method(\"GET\").endpoint(\n              URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-security-groups\")).headers(\n              ImmutableMultimap.<String, String> builder().put(\"Accept\", \"application/json\").put(\"X-Auth-Token\",\n                      authToken).build()).build();\n\n      HttpResponse listResponse = HttpResponse.builder().statusCode(200).payload(\n              payloadFromResource(\"/securitygroup_list.json\")).build();\n\n\n      Builder<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder();\n      requestResponseMap.put(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess);\n      requestResponseMap.put(extensionsOfNovaRequest, extensionsOfNovaResponse);\n      requestResponseMap.put(list, listResponse);\n\n      SecurityGroupExtension extension = requestsSendResponses(requestResponseMap.build()).getSecurityGroupExtension().get();\n\n      Set<SecurityGroup> groups = extension.listSecurityGroupsInLocation(new LocationBuilder()\n              .scope(LocationScope.REGION)\n              .id(region)\n              .description(\"region\")\n              .build());\n      assertEquals(groups.size(), 1);\n   }\n\n   public void testListSecurityGroupsForNode() {\n      HttpRequest serverReq = HttpRequest.builder().method(\"GET\").endpoint(\n              URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-create-server-ext/8d0a6ca5-8849-4b3d-b86e-f24c92490ebb\"))\n              .headers(\n                      ImmutableMultimap.<String, String> builder().put(\"Accept\", \"application/json\").put(\"X-Auth-Token\",\n                              authToken).build()).build();\n\n      HttpResponse serverResponse = HttpResponse.builder().statusCode(200).payload(\n              payloadFromResource(\"/server_with_security_groups_extension.json\")).build();\n\n      HttpRequest list = HttpRequest.builder().method(\"GET\").endpoint(\n              URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers/8d0a6ca5-8849-4b3d-b86e-f24c92490ebb/os-security-groups\")).headers(\n              ImmutableMultimap.<String, String> builder().put(\"Accept\", \"application/json\").put(\"X-Auth-Token\",\n                      authToken).build()).build();\n\n      HttpResponse listResponse = HttpResponse.builder().statusCode(200).payload(\n              payloadFromResource(\"/securitygroup_list.json\")).build();\n\n      Builder<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder();\n      requestResponseMap.put(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess);\n      requestResponseMap.put(extensionsOfNovaRequest, extensionsOfNovaResponse);\n      requestResponseMap.put(serverReq, serverResponse);\n      requestResponseMap.put(list, listResponse);\n\n      SecurityGroupExtension extension = requestsSendResponses(requestResponseMap.build()).getSecurityGroupExtension().get();\n\n      Set<SecurityGroup> groups = extension.listSecurityGroupsForNode(region + \"/8d0a6ca5-8849-4b3d-b86e-f24c92490ebb\");\n      assertEquals(groups.size(), 1);\n   }\n\n   public void testGetSecurityGroupById() {\n      HttpRequest getSecurityGroup = HttpRequest.builder().method(\"GET\").endpoint(\n              URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-security-groups/160\")).headers(\n              ImmutableMultimap.<String, String> builder().put(\"Accept\", \"application/json\").put(\"X-Auth-Token\",\n                      authToken).build()).build();\n\n      HttpResponse getSecurityGroupResponse = HttpResponse.builder().statusCode(200).payload(\n              payloadFromResource(\"/securitygroup_details_extension.json\")).build();\n\n      Builder<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder();\n      requestResponseMap.put(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess);\n      requestResponseMap.put(extensionsOfNovaRequest, extensionsOfNovaResponse);\n      requestResponseMap.put(getSecurityGroup, getSecurityGroupResponse);\n      requestResponseMap.put(list, listResponse);\n\n      SecurityGroupExtension extension = requestsSendResponses(requestResponseMap.build()).getSecurityGroupExtension().get();\n\n      SecurityGroup group = extension.getSecurityGroupById(region + \"/160\");\n      assertEquals(group.getId(), region + \"/160\");\n   }\n\n   public void testCreateSecurityGroup() {\n      HttpRequest getSecurityGroup = HttpRequest.builder().method(\"GET\").endpoint(\n              URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-security-groups/160\")).headers(\n              ImmutableMultimap.<String, String> builder().put(\"Accept\", \"application/json\").put(\"X-Auth-Token\",\n                      authToken).build()).build();\n\n      HttpResponse getSecurityGroupResponse = HttpResponse.builder().statusCode(200).payload(\n              payloadFromResource(\"/securitygroup_details_extension.json\")).build();\n\n      HttpRequest create = HttpRequest.builder().method(\"POST\").endpoint(\n              URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-security-groups\")).headers(\n              ImmutableMultimap.<String, String> builder().put(\"Accept\", \"application/json\").put(\"X-Auth-Token\",\n                      authToken).build())\n              .payload(\n                      payloadFromStringWithContentType(\n                              \"{\\\"security_group\\\":{\\\"name\\\":\\\"jclouds-test\\\",\\\"description\\\":\\\"jclouds-test\\\"}}\",\n                              \"application/json\")).build();\n\n      HttpResponse createResponse = HttpResponse.builder().statusCode(200).payload(\n              payloadFromResource(\"/securitygroup_created.json\")).build();\n\n      HttpRequest list = HttpRequest.builder().method(\"GET\").endpoint(\n              URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-security-groups\")).headers(\n              ImmutableMultimap.<String, String>builder().put(\"Accept\", \"application/json\").put(\"X-Auth-Token\",\n                      authToken).build()).build();\n\n      HttpResponse listResponse = HttpResponse.builder().statusCode(200).payload(\n              payloadFromResource(\"/securitygroup_list_extension.json\")).build();\n\n      Builder<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder();\n      requestResponseMap.put(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess);\n      requestResponseMap.put(extensionsOfNovaRequest, extensionsOfNovaResponse);\n      requestResponseMap.put(create, createResponse);\n      requestResponseMap.put(list, listResponse);\n      requestResponseMap.put(getSecurityGroup, getSecurityGroupResponse);\n\n      SecurityGroupExtension extension = requestsSendResponses(requestResponseMap.build()).getSecurityGroupExtension().get();\n\n      SecurityGroup group = extension.createSecurityGroup(\"test\", new LocationBuilder()\n              .scope(LocationScope.REGION)\n              .id(region)\n              .description(\"region\")\n              .build());\n      assertEquals(group.getId(), region + \"/160\");\n   }\n\n   public void testRemoveSecurityGroup() {\n      HttpRequest delete = HttpRequest.builder().method(\"DELETE\").endpoint(\n              URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-security-groups/160\"))\n              .headers(\n                      ImmutableMultimap.<String, String>builder().put(\"Accept\", \"application/json\")\n                              .put(\"X-Auth-Token\", authToken).build()).build();\n\n      HttpResponse deleteResponse = HttpResponse.builder().statusCode(202).build();\n\n      HttpRequest getSecurityGroup = HttpRequest.builder().method(\"GET\").endpoint(\n              URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-security-groups/160\")).headers(\n              ImmutableMultimap.<String, String> builder().put(\"Accept\", \"application/json\").put(\"X-Auth-Token\",\n                      authToken).build()).build();\n\n      HttpResponse getSecurityGroupResponse = HttpResponse.builder().statusCode(200).payload(\n              payloadFromResource(\"/securitygroup_details_extension.json\")).build();\n\n      Builder<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder();\n      requestResponseMap.put(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess);\n      requestResponseMap.put(extensionsOfNovaRequest, extensionsOfNovaResponse);\n      requestResponseMap.put(getSecurityGroup, getSecurityGroupResponse);\n      requestResponseMap.put(delete, deleteResponse);\n\n      SecurityGroupExtension extension = requestsSendResponses(requestResponseMap.build()).getSecurityGroupExtension().get();\n\n      assertTrue(extension.removeSecurityGroup(region + \"/160\"), \"Expected removal of securitygroup to be successful\");\n   }\n\n   public void testAddIpPermissionCidrFromIpPermission() {\n      HttpRequest createRule = HttpRequest\n              .builder()\n              .method(\"POST\")\n              .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-security-group-rules\")\n              .addHeader(\"Accept\", \"application/json\")\n              .addHeader(\"X-Auth-Token\", authToken)\n              .payload(\n                      payloadFromStringWithContentType(\n                              \"{\\\"security_group_rule\\\":{\\\"parent_group_id\\\":\\\"160\\\",\\\"cidr\\\":\\\"10.2.6.0/24\\\",\\\"ip_protocol\\\":\\\"tcp\\\",\\\"from_port\\\":\\\"22\\\",\\\"to_port\\\":\\\"22\\\"}}\",\n                              \"application/json\")).build();\n\n      HttpResponse createRuleResponse = HttpResponse.builder().statusCode(200).payload(\n              payloadFromResource(\"/securitygrouprule_created_cidr.json\")).build();\n\n      HttpRequest getSecurityGroup = HttpRequest.builder().method(\"GET\").endpoint(\n              URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-security-groups/160\")).headers(\n              ImmutableMultimap.<String, String> builder().put(\"Accept\", \"application/json\").put(\"X-Auth-Token\",\n                      authToken).build()).build();\n\n      HttpResponse getSecurityGroupNoRulesResponse = HttpResponse.builder().statusCode(200).payload(\n              payloadFromResource(\"/securitygroup_details_extension_norules.json\")).build();\n\n      HttpResponse getSecurityGroupResponse = HttpResponse.builder().statusCode(200).payload(\n              payloadFromResource(\"/securitygroup_details_extension.json\")).build();\n\n\n      SecurityGroupExtension extension = orderedRequestsSendResponses(\n         ImmutableList.of(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            extensionsOfNovaRequest,\n            list,\n            getSecurityGroup,\n            createRule,\n            list,\n            getSecurityGroup),\n         ImmutableList.of(\n            responseWithKeystoneAccess,\n            extensionsOfNovaResponse,\n            listResponse,\n            getSecurityGroupNoRulesResponse,\n            createRuleResponse,\n            listResponse,\n            getSecurityGroupResponse)).getSecurityGroupExtension().get();\n\n      IpPermission.Builder builder = IpPermission.builder();\n\n      builder.ipProtocol(IpProtocol.TCP);\n      builder.fromPort(22);\n      builder.toPort(22);\n      builder.cidrBlock(\"10.2.6.0/24\");\n\n      IpPermission perm = builder.build();\n\n      SecurityGroup origGroup = extension.getSecurityGroupById(region + \"/160\");\n\n      assertNotNull(origGroup);\n      SecurityGroup newGroup = extension.addIpPermission(perm, origGroup);\n\n      assertNotNull(newGroup);\n   }\n\n   public void testAddIpPermissionCidrFromParams() {\n      HttpRequest createRule = HttpRequest\n              .builder()\n              .method(\"POST\")\n              .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-security-group-rules\")\n              .addHeader(\"Accept\", \"application/json\")\n              .addHeader(\"X-Auth-Token\", authToken)\n              .payload(\n                      payloadFromStringWithContentType(\n                              \"{\\\"security_group_rule\\\":{\\\"parent_group_id\\\":\\\"160\\\",\\\"cidr\\\":\\\"10.2.6.0/24\\\",\\\"ip_protocol\\\":\\\"tcp\\\",\\\"from_port\\\":\\\"22\\\",\\\"to_port\\\":\\\"22\\\"}}\",\n                              \"application/json\")).build();\n\n      HttpResponse createRuleResponse = HttpResponse.builder().statusCode(200).payload(\n              payloadFromResource(\"/securitygrouprule_created_cidr.json\")).build();\n\n      HttpRequest getSecurityGroup = HttpRequest.builder().method(\"GET\").endpoint(\n              URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-security-groups/160\")).headers(\n              ImmutableMultimap.<String, String> builder().put(\"Accept\", \"application/json\").put(\"X-Auth-Token\",\n                      authToken).build()).build();\n\n      HttpResponse getSecurityGroupNoRulesResponse = HttpResponse.builder().statusCode(200).payload(\n              payloadFromResource(\"/securitygroup_details_extension_norules.json\")).build();\n\n      HttpResponse getSecurityGroupResponse = HttpResponse.builder().statusCode(200).payload(\n              payloadFromResource(\"/securitygroup_details_extension.json\")).build();\n\n\n      SecurityGroupExtension extension = orderedRequestsSendResponses(\n         ImmutableList.of(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            extensionsOfNovaRequest,\n            list,\n            getSecurityGroup,\n            createRule,\n            list,\n            getSecurityGroup),\n         ImmutableList.of(\n            responseWithKeystoneAccess,\n            extensionsOfNovaResponse,\n            listResponse,\n            getSecurityGroupNoRulesResponse,\n            createRuleResponse,\n            listResponse,\n            getSecurityGroupResponse))\n         .getSecurityGroupExtension().get();\n\n      SecurityGroup origGroup = extension.getSecurityGroupById(region + \"/160\");\n\n      assertNotNull(origGroup);\n      SecurityGroup newGroup = extension.addIpPermission(IpProtocol.TCP,\n              22,\n              22,\n              emptyMultimap(),\n              ImmutableSet.of(\"10.2.6.0/24\"),\n              emptyStringSet(),\n              origGroup);\n\n      assertNotNull(newGroup);\n   }\n\n   public void testAddIpPermissionGroupFromIpPermission() {\n      HttpRequest createRule = HttpRequest\n              .builder()\n              .method(\"POST\")\n              .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-security-group-rules\")\n              .addHeader(\"Accept\", \"application/json\")\n              .addHeader(\"X-Auth-Token\", authToken)\n              .payload(\n                      payloadFromStringWithContentType(\n                              \"{\\\"security_group_rule\\\":{\\\"group_id\\\":\\\"11111\\\",\\\"parent_group_id\\\":\\\"160\\\",\\\"ip_protocol\\\":\\\"tcp\\\",\\\"from_port\\\":\\\"22\\\",\\\"to_port\\\":\\\"22\\\"}}\",\n                              \"application/json\")).build();\n\n      HttpResponse createRuleResponse = HttpResponse.builder().statusCode(200).payload(\n              payloadFromResource(\"/securitygrouprule_created_group.json\")).build();\n\n      HttpRequest getSecurityGroup = HttpRequest.builder().method(\"GET\").endpoint(\n              URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-security-groups/160\")).headers(\n              ImmutableMultimap.<String, String> builder().put(\"Accept\", \"application/json\").put(\"X-Auth-Token\",\n                      authToken).build()).build();\n\n      HttpResponse getSecurityGroupNoRulesResponse = HttpResponse.builder().statusCode(200).payload(\n              payloadFromResource(\"/securitygroup_details_extension_norules.json\")).build();\n\n      HttpResponse getSecurityGroupResponse = HttpResponse.builder().statusCode(200).payload(\n              payloadFromResource(\"/securitygroup_details_extension.json\")).build();\n\n      SecurityGroupExtension extension = orderedRequestsSendResponses(\n         ImmutableList.of(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            extensionsOfNovaRequest,\n            list,\n            getSecurityGroup,\n            createRule,\n            list,\n            getSecurityGroup),\n         ImmutableList.of(\n            responseWithKeystoneAccess,\n            extensionsOfNovaResponse,\n            listResponse,\n            getSecurityGroupNoRulesResponse,\n            createRuleResponse,\n            listResponse,\n            getSecurityGroupResponse)).getSecurityGroupExtension().get();\n\n      IpPermission.Builder builder = IpPermission.builder();\n\n      builder.ipProtocol(IpProtocol.TCP);\n      builder.fromPort(22);\n      builder.toPort(22);\n      builder.groupId(\"admin/11111\");\n\n      IpPermission perm = builder.build();\n\n      SecurityGroup origGroup = extension.getSecurityGroupById(region + \"/160\");\n\n      assertNotNull(origGroup);\n      SecurityGroup newGroup = extension.addIpPermission(perm, origGroup);\n\n      assertNotNull(newGroup);\n   }\n\n   public void testAddIpPermissionGroupFromParams() {\n      HttpRequest createRule = HttpRequest\n              .builder()\n              .method(\"POST\")\n              .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-security-group-rules\")\n              .addHeader(\"Accept\", \"application/json\")\n              .addHeader(\"X-Auth-Token\", authToken)\n              .payload(\n                      payloadFromStringWithContentType(\n                              \"{\\\"security_group_rule\\\":{\\\"group_id\\\":\\\"11111\\\",\\\"parent_group_id\\\":\\\"160\\\",\\\"ip_protocol\\\":\\\"tcp\\\",\\\"from_port\\\":\\\"22\\\",\\\"to_port\\\":\\\"22\\\"}}\",\n                              \"application/json\")).build();\n\n      HttpResponse createRuleResponse = HttpResponse.builder().statusCode(200).payload(\n              payloadFromResource(\"/securitygrouprule_created_group.json\")).build();\n\n      HttpRequest getSecurityGroup = HttpRequest.builder().method(\"GET\").endpoint(\n              URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-security-groups/160\")).headers(\n              ImmutableMultimap.<String, String> builder().put(\"Accept\", \"application/json\").put(\"X-Auth-Token\",\n                      authToken).build()).build();\n\n      HttpResponse getSecurityGroupNoRulesResponse = HttpResponse.builder().statusCode(200).payload(\n              payloadFromResource(\"/securitygroup_details_extension_norules.json\")).build();\n\n      HttpResponse getSecurityGroupResponse = HttpResponse.builder().statusCode(200).payload(\n              payloadFromResource(\"/securitygroup_details_extension.json\")).build();\n\n\n      SecurityGroupExtension extension = orderedRequestsSendResponses(\n         ImmutableList.of(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            extensionsOfNovaRequest,\n            list,\n            getSecurityGroup,\n            createRule,\n            list,\n            getSecurityGroup),\n         ImmutableList.of(\n            responseWithKeystoneAccess,\n            extensionsOfNovaResponse,\n            listResponse,\n            getSecurityGroupNoRulesResponse,\n            createRuleResponse,\n            listResponse,\n            getSecurityGroupResponse))\n         .getSecurityGroupExtension().get();\n\n      SecurityGroup origGroup = extension.getSecurityGroupById(region + \"/160\");\n\n      assertNotNull(origGroup);\n      SecurityGroup newGroup = extension.addIpPermission(IpProtocol.TCP,\n              22,\n              22,\n              emptyMultimap(),\n              emptyStringSet(),\n              ImmutableSet.of(\"admin/11111\"),\n              origGroup);\n\n      assertNotNull(newGroup);\n   }\n\n   private Multimap<String, String> emptyMultimap() {\n      return LinkedHashMultimap.create();\n   }\n\n   private Set<String> emptyStringSet() {\n      return Sets.newLinkedHashSet();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/compute/extensions/NovaSecurityGroupExtensionLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.compute.extensions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Date;\nimport java.util.Random;\nimport java.util.Set;\nimport java.util.concurrent.TimeUnit;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\n\nimport org.jclouds.compute.ComputeService;\nimport org.jclouds.compute.domain.SecurityGroup;\nimport org.jclouds.compute.extensions.SecurityGroupExtension;\nimport org.jclouds.compute.extensions.internal.BaseSecurityGroupExtensionLiveTest;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.logging.Logger;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Iterables;\n\n/**\n * Live test for openstack-nova {@link org.jclouds.compute.extensions.SecurityGroupExtension} implementation.\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"NovaSecurityGroupExtensionLiveTest\")\npublic class NovaSecurityGroupExtensionLiveTest extends BaseSecurityGroupExtensionLiveTest {\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.CONSOLE;\n\n   public NovaSecurityGroupExtensionLiveTest() {\n      provider = \"openstack-nova\";\n   }\n\n   @Test(groups = {\"integration\", \"live\"}, singleThreaded = true)\n   public void testListSecurityGroups() throws Exception {\n      skipIfSecurityGroupsNotSupported();\n\n      final long begin = new Date().getTime();\n      ComputeService computeService = view.getComputeService();\n      Optional<SecurityGroupExtension> securityGroupExtension = computeService.getSecurityGroupExtension();\n      assertTrue(securityGroupExtension.isPresent(), \"security extension was not present\");\n\n      logger.info(\"Loading security groups\");\n      final SecurityGroupExtension security = securityGroupExtension.get();\n      Set<SecurityGroup> beforeAdd = security.listSecurityGroups();\n      int countBeforeAdd = beforeAdd.size();\n      logger.info(\"Found %d security groups\", countBeforeAdd);\n\n      String someUnlikelyName = String.valueOf(new Random().nextInt(1000000) + 1000000);\n      logger.info(\"Adding security group %s\", someUnlikelyName);\n      final SecurityGroup testGroup = security.createSecurityGroup(someUnlikelyName, getNodeTemplate().getLocation());\n\n      try {\n         verifyAndDeleteSecurityGroup(security, countBeforeAdd, testGroup);\n      } catch (Exception e) {\n         logger.error(e, \"Exception caught, live test leaking security group %s\", testGroup.getName());\n         throw e;\n      }\n\n      final long end = new Date().getTime();\n\n      assertTrue(end - begin < TimeUnit.MINUTES.toMillis(5)); // see https://issues.apache.org/jira/browse/JCLOUDS-1235\n\n   }\n\n   private void verifyAndDeleteSecurityGroup(SecurityGroupExtension security, int countBeforeAdd,\n                                             final SecurityGroup testGroup) {\n      logger.info(\"Loading security groups\");\n      Set<SecurityGroup> afterAdd = security.listSecurityGroups();\n      final int countAfterAdd = afterAdd.size();\n      logger.info(\"Found %d security groups\", countAfterAdd);\n\n      assertEquals(countAfterAdd, countBeforeAdd + 1);\n      final Predicate<SecurityGroup> findTestGroup = new Predicate<SecurityGroup>() {\n         @Override\n         public boolean apply(SecurityGroup input) {\n            return input.getName().equals(testGroup.getName());\n         }\n      };\n      final SecurityGroup created = Iterables.find(afterAdd, findTestGroup);\n      assertNotNull(created, \"Did not find security group created as expected\");\n\n      logger.info(\"Removing %s\", testGroup.getName());\n      security.removeSecurityGroup(testGroup.getId());\n\n      logger.info(\"Loading security groups\");\n      Set<SecurityGroup> afterRemove = security.listSecurityGroups();\n      final int sizeAfterRemove = afterRemove.size();\n      logger.info(\"Found %d security groups\", sizeAfterRemove);\n      assertEquals(sizeAfterRemove, countBeforeAdd);\n      final Optional<SecurityGroup> removed = Iterables.tryFind(afterRemove, findTestGroup);\n      assertTrue(!removed.isPresent(), \"Did not remove test security group as expected\");\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/compute/functions/AllocateAndAddFloatingIpToNodeExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.compute.functions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.net.URI;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadata.Status;\nimport org.jclouds.compute.domain.NodeMetadataBuilder;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.nova.v2_0.compute.options.NodeAndNovaTemplateOptions;\nimport org.jclouds.openstack.nova.v2_0.compute.options.NovaTemplateOptions;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaComputeServiceExpectTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.util.concurrent.Atomics;\n\n/**\n * Tests the compute service abstraction of the nova api.\n */\n@Test(groups = \"unit\", testName = \"AllocateAndAddFloatingIpToNodeTest\")\npublic class AllocateAndAddFloatingIpToNodeExpectTest extends BaseNovaComputeServiceExpectTest {\n   final Location provider = new LocationBuilder().scope(LocationScope.PROVIDER).id(\"openstack-nova\").description(\n            \"openstack-nova\").build();\n   final Location region = new LocationBuilder().id(\"az-1.region-a.geo-1\").description(\"az-1.region-a.geo-1\").scope(\n            LocationScope.REGION).parent(provider).build();\n   final Location host = new LocationBuilder().scope(LocationScope.HOST).id(\"hostId\").description(\"hostId\")\n            .parent(region).build();\n   final NodeMetadata node = new NodeMetadataBuilder().id(\"az-1.region-a.geo-1/71592\").providerId(\"71592\").location(\n            host).name(\"Server 71592\").status(Status.RUNNING).privateAddresses(ImmutableSet.of(\"10.4.27.237\"))\n            .credentials(LoginCredentials.builder().password(\"foo\").build()).build();\n   final NovaTemplateOptions options = NovaTemplateOptions.Builder.autoAssignFloatingIp(false);\n\n   HttpRequest createFloatingIP = HttpRequest.builder().method(\"POST\").endpoint(\n            URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-floating-ips\")).headers(\n            ImmutableMultimap.<String, String> builder().put(\"Accept\", \"application/json\").put(\"X-Auth-Token\",\n                     authToken).build()).payload(payloadFromStringWithContentType(\"{}\", \"application/json\")).build();\n\n   HttpResponse addFloatingIPResponse = HttpResponse.builder().statusCode(200).build();\n\n   public void testAllocateWhenAllocationReturnsIpIsAddedToServerAndUpdatesNodeMetadataButSavesCredentials() throws Exception {\n      HttpResponse createFloatingIPResponse = HttpResponse.builder().statusCode(200).payload(\n               payloadFromResource(\"/floatingip_details.json\")).build();\n\n      HttpRequest listAZs = HttpRequest.builder().method(\"GET\").endpoint(\n              URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-availability-zone\")).headers(\n              ImmutableMultimap.<String, String> builder().put(\"Accept\", \"application/json\")\n                      .put(\"X-Auth-Token\", authToken)\n                      .build())\n              .build();\n\n      HttpResponse listAZsResponseForUnassigned = HttpResponse.builder().statusCode(200).payload(\n              payloadFromResource(\"/availability_zone_list.json\")).build();\n\n      HttpRequest addFloatingIPRequest = addFloatingIPForAddress(\"10.0.0.3\");\n\n      AllocateAndAddFloatingIpToNode fn = requestsSendResponses(\n               ImmutableMap.<HttpRequest, HttpResponse> builder()\n                       .put(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess)\n                       .put(listAZs, listAZsResponseForUnassigned)\n                       .put(extensionsOfNovaRequest, extensionsOfNovaResponse)\n                       .put(createFloatingIP, createFloatingIPResponse)\n                       .put(addFloatingIPRequest, addFloatingIPResponse).build())\n              .getContext().utils().injector()\n              .getInstance(AllocateAndAddFloatingIpToNode.class);\n\n      AtomicReference<NodeMetadata> nodeRef = Atomics.newReference(node);\n      AtomicReference<NovaTemplateOptions> optionsRef = Atomics.newReference(options);\n      AtomicReference<NodeAndNovaTemplateOptions> nodeNovaRef = NodeAndNovaTemplateOptions.newAtomicReference(nodeRef, optionsRef);\n\n      fn.apply(nodeNovaRef);\n      NodeMetadata node1 = nodeRef.get();\n      assertNotNull(node1);\n      assertNotNull(optionsRef.get());\n      assertEquals(node1.getPublicAddresses(), ImmutableSet.of(\"10.0.0.3\"));\n      assertEquals(node1.getCredentials(), node.getCredentials());\n\n   }\n\n   private HttpRequest addFloatingIPForAddress(String address) {\n      HttpRequest addFloatingIPRequest = HttpRequest.builder().method(\"POST\").endpoint(\n               URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers/71592/action\"))\n               .headers(\n                        ImmutableMultimap.<String, String> builder().put(\"Accept\", \"application/json\")\n                                 .put(\"X-Auth-Token\", authToken).build()).payload(\n                        payloadFromStringWithContentType(\"{\\\"addFloatingIp\\\":{\\\"address\\\":\\\"\" + address + \"\\\"}}\",\n                                 \"application/json\")).build();\n      return addFloatingIPRequest;\n   }\n\n   public void testAllocateWhenAllocationFailsOn400LookupUnusedIpAddToServerAndUpdatesNodeMetadata() throws Exception {\n      HttpResponse createFloatingIPResponse = HttpResponse\n               .builder()\n               .statusCode(400)\n               .payload(\n                        payloadFromStringWithContentType(\n                                 \"{\\\"badRequest\\\": {\\\"message\\\": \\\"AddressLimitExceeded: Address quota exceeded. You cannot create any more addresses\\\", \\\"code\\\": 400}}\",\n                                 \"application/json\")).build();\n\n      HttpRequest listAZs = HttpRequest.builder().method(\"GET\").endpoint(\n              URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-availability-zone\")).headers(\n              ImmutableMultimap.<String, String> builder().put(\"Accept\", \"application/json\")\n                      .put(\"X-Auth-Token\", authToken)\n                      .build())\n              .build();\n\n      HttpResponse listAZsResponseForUnassigned = HttpResponse.builder().statusCode(200).payload(\n              payloadFromResource(\"/availability_zone_list.json\")).build();\n\n      HttpRequest list = HttpRequest.builder().method(\"GET\").endpoint(\n               URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-floating-ips\")).headers(\n               ImmutableMultimap.<String, String> builder().put(\"Accept\", \"application/json\").put(\"X-Auth-Token\",\n                        authToken).build()).build();\n\n      HttpResponse listResponseForUnassigned = HttpResponse.builder().statusCode(200).payload(\n               payloadFromResource(\"/floatingip_list.json\")).build();\n\n      HttpRequest addFloatingIPRequest = addFloatingIPForAddress(\"10.0.0.5\");\n\n      AllocateAndAddFloatingIpToNode fn = requestsSendResponses(\n               ImmutableMap.<HttpRequest, HttpResponse> builder()\n                       .put(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess)\n                       .put(listAZs, listAZsResponseForUnassigned)\n                       .put(extensionsOfNovaRequest, extensionsOfNovaResponse)\n                       .put(createFloatingIP, createFloatingIPResponse)\n                       .put(addFloatingIPRequest, addFloatingIPResponse)\n                       .put(list, listResponseForUnassigned)\n                       .build())\n              .getContext().utils().injector()\n              .getInstance(AllocateAndAddFloatingIpToNode.class);\n\n      AtomicReference<NodeMetadata> nodeRef = Atomics.newReference(node);\n      AtomicReference<NovaTemplateOptions> optionsRef = Atomics.newReference(options);\n      AtomicReference<NodeAndNovaTemplateOptions> nodeNovaRef = NodeAndNovaTemplateOptions.newAtomicReference(nodeRef, optionsRef);\n\n      fn.apply(nodeNovaRef);\n      NodeMetadata node1 = nodeRef.get();\n      assertNotNull(node1);\n      assertNotNull(optionsRef.get());\n      assertEquals(node1.getPublicAddresses(), ImmutableSet.of(\"10.0.0.5\"));\n   }\n\n   public void testAllocateWhenAllocationFailsOn404LookupUnusedIpAddToServerAndUpdatesNodeMetadata() throws Exception {\n      HttpResponse createFloatingIPResponse = HttpResponse\n               .builder()\n               .statusCode(404)\n               .payload(\n                        payloadFromStringWithContentType(\n                                 \"{\\\"badRequest\\\": {\\\"message\\\": \\\"AddressLimitExceeded: Address quota exceeded. You cannot create any more addresses\\\", \\\"code\\\": 404}}\",\n                                 \"application/json\")).build();\n\n      HttpRequest listAZs = HttpRequest.builder().method(\"GET\").endpoint(\n              URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-availability-zone\")).headers(\n              ImmutableMultimap.<String, String> builder().put(\"Accept\", \"application/json\")\n                      .put(\"X-Auth-Token\", authToken)\n                      .build())\n              .build();\n\n      HttpResponse listAZsResponseForUnassigned = HttpResponse.builder().statusCode(200).payload(\n              payloadFromResource(\"/availability_zone_list.json\")).build();\n\n      HttpRequest list = HttpRequest.builder().method(\"GET\").endpoint(\n               URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-floating-ips\")).headers(\n               ImmutableMultimap.<String, String> builder().put(\"Accept\", \"application/json\").put(\"X-Auth-Token\",\n                        authToken).build()).build();\n\n      HttpResponse listResponseForUnassigned = HttpResponse.builder().statusCode(200).payload(\n               payloadFromResource(\"/floatingip_list.json\")).build();\n\n      HttpRequest addFloatingIPRequest = addFloatingIPForAddress(\"10.0.0.5\");\n\n      AllocateAndAddFloatingIpToNode fn = requestsSendResponses(\n               ImmutableMap.<HttpRequest, HttpResponse> builder()\n                       .put(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess)\n                       .put(listAZs, listAZsResponseForUnassigned)\n                       .put(extensionsOfNovaRequest, extensionsOfNovaResponse)\n                       .put(createFloatingIP, createFloatingIPResponse)\n                       .put(addFloatingIPRequest, addFloatingIPResponse)\n                       .put(list, listResponseForUnassigned).build())\n              .getContext().utils().injector()\n              .getInstance(AllocateAndAddFloatingIpToNode.class);\n\n      AtomicReference<NodeMetadata> nodeRef = Atomics.newReference(node);\n      AtomicReference<NovaTemplateOptions> optionsRef = Atomics.newReference(options);\n      AtomicReference<NodeAndNovaTemplateOptions> nodeNovaRef = NodeAndNovaTemplateOptions.newAtomicReference(nodeRef, optionsRef);\n\n      fn.apply(nodeNovaRef);\n      NodeMetadata node1 = nodeRef.get();\n      assertNotNull(node1);\n      assertNotNull(optionsRef.get());\n      assertEquals(node1.getPublicAddresses(), ImmutableSet.of(\"10.0.0.5\"));\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/compute/functions/FlavorInRegionToHardwareTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.compute.functions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.Map;\nimport java.util.UUID;\n\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.openstack.nova.v2_0.domain.Flavor;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.FlavorInRegion;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Tests the function used to transform Flavor objects into Hardware objects\n */\n@Test(testName = \"FlavorInRegionToHardwareTest\")\npublic class FlavorInRegionToHardwareTest {\n   Location provider = new LocationBuilder().scope(LocationScope.PROVIDER).id(\"openstack-nova\").description(\n            \"openstack-nova\").build();\n   Location region = new LocationBuilder().id(\"az-1.region-a.geo-1\").description(\"az-1.region-a.geo-1\").scope(\n            LocationScope.REGION).parent(provider).build();\n   Supplier<Map<String, Location>> locationIndex = Suppliers.<Map<String, Location>> ofInstance(ImmutableMap\n            .<String, Location> of(\"az-1.region-a.geo-1\", region));\n\n   @Test\n   public void testConversionWhereLocationFound() {\n\n      UUID id = UUID.randomUUID();\n\n      FlavorInRegion flavorInRegionToConvert = new FlavorInRegion(Flavor.builder().id(id.toString())\n               .name(\"Test Flavor \" + id).ram(262144).disk(10000).vcpus(16).build(), \"az-1.region-a.geo-1\");\n\n      Hardware converted = new FlavorInRegionToHardware(locationIndex).apply(flavorInRegionToConvert);\n\n      Flavor flavorToConvert = flavorInRegionToConvert.getFlavor();\n      assertEquals(converted.getName(), flavorToConvert.getName());\n      assertEquals(converted.getId(), flavorInRegionToConvert.slashEncode());\n      assertEquals(converted.getProviderId(), flavorToConvert.getId());\n      assertEquals(converted.getLocation(), locationIndex.get().get(\"az-1.region-a.geo-1\"));\n\n      assertEquals(converted.getRam(), flavorToConvert.getRam());\n\n      assertNotNull(converted.getProcessors());\n      assertFalse(converted.getProcessors().isEmpty());\n      assertEquals(converted.getProcessors().iterator().next().getCores(), (double) flavorToConvert.getVcpus());\n\n      assertNotNull(converted.getVolumes());\n      assertFalse(converted.getVolumes().isEmpty());\n      assertEquals(converted.getVolumes().iterator().next().getSize(), Float.valueOf(flavorToConvert.getDisk()));\n\n   }\n\n   @Test(expectedExceptions = IllegalStateException.class)\n   public void testConversionWhereLocationNotFound() {\n\n      UUID id = UUID.randomUUID();\n\n      FlavorInRegion flavorInRegionToConvert = new FlavorInRegion(Flavor.builder().id(id.toString())\n               .name(\"Test Flavor \" + id).ram(262144).disk(10000).vcpus(16).build(), \"South\");\n      new FlavorInRegionToHardware(locationIndex).apply(flavorInRegionToConvert);\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/compute/functions/ImageInRegionToImageTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.compute.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Map;\nimport java.util.UUID;\n\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.openstack.nova.v2_0.compute.config.NovaComputeServiceContextModule;\nimport org.jclouds.openstack.nova.v2_0.domain.Image;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.ImageInRegion;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Functions;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Tests the function that transforms nova-specific images to generic images.\n */\n@Test(testName = \"ImageInRegionToHardwareTest\")\npublic class ImageInRegionToImageTest {\n\n   Location provider = new LocationBuilder().scope(LocationScope.PROVIDER).id(\"openstack-nova\").description(\n            \"openstack-nova\").build();\n   Location region = new LocationBuilder().id(\"az-1.region-a.geo-1\").description(\"az-1.region-a.geo-1\").scope(\n            LocationScope.REGION).parent(provider).build();\n   Supplier<Map<String, Location>> locationIndex = Suppliers.<Map<String, Location>> ofInstance(ImmutableMap\n            .<String, Location> of(\"az-1.region-a.geo-1\", region));\n\n   @Test\n   public void testConversionWhereLocationFound() {\n      UUID id = UUID.randomUUID();\n      Image novaImageToConvert = Image.builder().id(id.toString()).name(\"Test Image \" + id).status(Image.Status.DELETED).build();\n      OperatingSystem operatingSystem = new OperatingSystem(OsFamily.UBUNTU, \"My Test OS\", \"My Test Version\", \"x86\",\n               \"My Test OS\", true);\n      ImageInRegionToImage converter = new ImageInRegionToImage(NovaComputeServiceContextModule.toPortableImageStatus,\n               constant(operatingSystem), locationIndex);\n\n      ImageInRegion novaImageInRegionToConvert = new ImageInRegion(novaImageToConvert, \"az-1.region-a.geo-1\");\n\n      org.jclouds.compute.domain.Image convertedImage = converter.apply(novaImageInRegionToConvert);\n\n      assertEquals(convertedImage.getId(), novaImageInRegionToConvert.slashEncode());\n      assertEquals(convertedImage.getProviderId(), novaImageToConvert.getId());\n      assertEquals(convertedImage.getLocation(), locationIndex.get().get(\"az-1.region-a.geo-1\"));\n\n      assertEquals(convertedImage.getName(), novaImageToConvert.getName());\n      assertEquals(convertedImage.getStatus(), org.jclouds.compute.domain.Image.Status.DELETED);\n      assertEquals(convertedImage.getOperatingSystem(), operatingSystem);\n   }\n\n   @Test(expectedExceptions = IllegalStateException.class)\n   public void testConversionWhereLocationNotFound() {\n      UUID id = UUID.randomUUID();\n      Image novaImageToConvert = Image.builder().id(id.toString()).name(\"Test Image \" + id).build();\n      OperatingSystem operatingSystem = new OperatingSystem(OsFamily.UBUNTU, \"My Test OS\", \"My Test Version\", \"x86\",\n               \"My Test OS\", true);\n      ImageInRegionToImage converter = new ImageInRegionToImage(NovaComputeServiceContextModule.toPortableImageStatus,\n               constant(operatingSystem), locationIndex);\n\n      ImageInRegion novaImageInRegionToConvert = new ImageInRegion(novaImageToConvert, \"South\");\n\n      converter.apply(novaImageInRegionToConvert);\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   private static Function<Image, OperatingSystem> constant(OperatingSystem operatingSystem) {\n      return Function.class.cast(Functions.constant(operatingSystem));\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/compute/functions/ImageToOperatingSystemTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.compute.functions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.openstack.nova.v2_0.domain.Image;\nimport org.testng.annotations.DataProvider;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Maps;\n\n/**\n * Tests for the function for transforming a nova specific Image into a generic\n * OperatingSystem object.\n */\npublic class ImageToOperatingSystemTest {\n\n   @Test(dataProvider = \"getOsFamilyValues\")\n   public void testOsFamilyValues(OsFamily family) {\n\n      Image imageToConvert = Image.builder().id(\"id-\" + family.name()).name(family.name()).build();\n\n      ImageToOperatingSystem converter = new ImageToOperatingSystem(\n            new HashMap<OsFamily, Map<String, String>>());\n\n      OperatingSystem convertedOs = converter.apply(imageToConvert);\n\n      assertEquals(convertedOs.getName(), imageToConvert.getName());\n      assertEquals(convertedOs.getFamily(), family);\n      assertEquals(convertedOs.getDescription(), imageToConvert.getName());\n      assertEquals(convertedOs.getVersion(), null);\n      assertEquals(convertedOs.getArch(), null);\n      assertTrue(convertedOs.is64Bit());\n   }\n\n   @DataProvider\n   public Object[][] getOsFamilyValues() {\n      return Iterables.toArray(\n            Iterables.transform(Arrays.asList(OsFamily.values()), new Function<OsFamily, Object[]>() {\n               @Override\n               public Object[] apply(OsFamily osFamily) {\n                  return new Object[] { osFamily };\n               }\n            }), Object[].class);\n   }\n\n   @Test\n   public void testWindowsServer2008R2x64() {\n      String name = \"Windows Server 2008 R2 x64\";\n\n      Image imageToConvert = Image.builder().id(\"id-\" + name).name(name).build();\n\n      Map<OsFamily, Map<String, String>> osFamilyMap = Maps.newHashMap();\n      osFamilyMap.put(OsFamily.WINDOWS, ImmutableMap.of(\"Server 2008 R2\", \"Server-2008-R2\"));\n\n      ImageToOperatingSystem converter = new ImageToOperatingSystem(osFamilyMap);\n\n      OperatingSystem convertedOs = converter.apply(imageToConvert);\n\n      assertEquals(convertedOs.getName(), imageToConvert.getName());\n      assertEquals(convertedOs.getFamily(), OsFamily.WINDOWS);\n      assertEquals(convertedOs.getDescription(), imageToConvert.getName());\n      assertEquals(convertedOs.getVersion(), \"Server-2008-R2\");\n      assertEquals(convertedOs.getArch(), null);\n      assertTrue(convertedOs.is64Bit());\n   }\n\n   @Test\n   public void testWindows98x86() {\n      String name = \"Windows 98 x86\";\n\n      Image imageToConvert = Image.builder().id(\"id-\" + name).name(name).build();\n\n      Map<OsFamily, Map<String, String>> osFamilyMap = Maps.newHashMap();\n      osFamilyMap.put(OsFamily.WINDOWS, ImmutableMap.of(\"98\", \"98\"));\n\n      ImageToOperatingSystem converter = new ImageToOperatingSystem(osFamilyMap);\n\n      OperatingSystem convertedOs = converter.apply(imageToConvert);\n\n      assertEquals(convertedOs.getName(), imageToConvert.getName());\n      assertEquals(convertedOs.getFamily(), OsFamily.WINDOWS);\n      assertEquals(convertedOs.getDescription(), imageToConvert.getName());\n      assertEquals(convertedOs.getVersion(), \"98\");\n      assertEquals(convertedOs.getArch(), null);\n      assertFalse(convertedOs.is64Bit());\n   }\n\n   @Test\n   public void testRHEL() {\n      String name = \"Red Hat EL\";\n\n      Image imageToConvert = Image.builder().id(\"id-\" + name).name(name).build();\n\n      ImageToOperatingSystem converter = new ImageToOperatingSystem(\n            new HashMap<OsFamily, Map<String, String>>());\n\n      OperatingSystem convertedOs = converter.apply(imageToConvert);\n\n      assertEquals(convertedOs.getName(), imageToConvert.getName());\n      assertEquals(convertedOs.getFamily(), OsFamily.RHEL);\n      assertEquals(convertedOs.getDescription(), imageToConvert.getName());\n      assertEquals(convertedOs.getVersion(), null);\n      assertEquals(convertedOs.getArch(), null);\n      assertTrue(convertedOs.is64Bit());\n   }\n\n   @Test\n   public void testOEL() {\n      String name = \"Oracle EL\";\n\n      Image imageToConvert = Image.builder().id(\"id-\" + name).name(name).build();\n\n      ImageToOperatingSystem converter = new ImageToOperatingSystem(\n            new HashMap<OsFamily, Map<String, String>>());\n\n      OperatingSystem convertedOs = converter.apply(imageToConvert);\n\n      assertEquals(convertedOs.getName(), imageToConvert.getName());\n      assertEquals(convertedOs.getFamily(), OsFamily.OEL);\n      assertEquals(convertedOs.getDescription(), imageToConvert.getName());\n      assertEquals(convertedOs.getVersion(), null);\n      assertEquals(convertedOs.getArch(), null);\n      assertTrue(convertedOs.is64Bit());\n   }\n   \n\n   ImageToOperatingSystem converterForUbuntu = new ImageToOperatingSystem(ImmutableMap.<OsFamily, Map<String, String>> of(\n            OsFamily.UBUNTU, ImmutableMap.of(\"lucid\", \"10.04\", \"maverick\", \"10.10\", \"natty\", \"11.04\", \"oneiric\",\n                     \"11.10\")));\n   @Test\n   public void testTryStackOneric() {\n      \n      String name = \"oneiric-server-cloudimg-amd64\";\n\n      Image imageToConvert = Image.builder().id(\"id-\" + name).name(name).build();\n      \n      OperatingSystem convertedOs = converterForUbuntu.apply(imageToConvert);\n\n      assertEquals(convertedOs.getName(), imageToConvert.getName());\n      assertEquals(convertedOs.getFamily(), OsFamily.UBUNTU);\n      assertEquals(convertedOs.getDescription(), imageToConvert.getName());\n      assertEquals(convertedOs.getVersion(), \"11.10\");\n      assertEquals(convertedOs.getArch(), null);\n      assertTrue(convertedOs.is64Bit());\n   }\n   \n   @Test\n   public void testTryStackNatty() {\n      \n      String name = \"natty-server-cloudimg-amd64\";\n\n      Image imageToConvert = Image.builder().id(\"id-\" + name).name(name).build();\n      \n      OperatingSystem convertedOs = converterForUbuntu.apply(imageToConvert);\n\n      assertEquals(convertedOs.getName(), imageToConvert.getName());\n      assertEquals(convertedOs.getFamily(), OsFamily.UBUNTU);\n      assertEquals(convertedOs.getDescription(), imageToConvert.getName());\n      assertEquals(convertedOs.getVersion(), \"11.04\");\n      assertEquals(convertedOs.getArch(), null);\n      assertTrue(convertedOs.is64Bit());\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/compute/functions/NovaSecurityGroupInRegionToSecurityGroupTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.compute.functions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Map;\n\nimport org.jclouds.compute.domain.SecurityGroup;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.net.domain.IpPermission;\nimport org.jclouds.net.domain.IpProtocol;\nimport org.jclouds.openstack.nova.v2_0.domain.SecurityGroupRule;\nimport org.jclouds.openstack.nova.v2_0.domain.TenantIdAndName;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.SecurityGroupInRegion;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\n\n\n@Test(groups = \"unit\", testName = \"NovaSecurityGroupInRegionToSecurityGroupTest\")\npublic class NovaSecurityGroupInRegionToSecurityGroupTest {\n\n   Location provider = new LocationBuilder().scope(LocationScope.PROVIDER).id(\"openstack-nova\")\n           .description(\"openstack-nova\").build();\n   Location region = new LocationBuilder().id(\"az-1.region-a.geo-1\").description(\"az-1.region-a.geo-1\")\n           .scope(LocationScope.REGION).parent(provider).build();\n   Supplier<Map<String, Location>> locationIndex = Suppliers.<Map<String, Location>> ofInstance(ImmutableMap\n           .<String, Location>of(\"az-1.region-a.geo-1\", region));\n\n   public static final String SOME_GROUP_ID = \"some-group-id\";\n   public static final String SOME_OTHER_GROUP_ID = \"some-other-group-id\";\n   public static final String IP_RANGE = \"0.0.0.0/0\";\n   public static final String SOME_OTHER_GROUP = \"some-other-group\";\n   public static final String SOME_GROUP = \"some-group\";\n\n   public static final ImmutableList<org.jclouds.openstack.nova.v2_0.domain.SecurityGroup> allGroups =\n      ImmutableList.of(securityGroupWithGroup(), securityGroupWithCidr());\n\n   public static org.jclouds.openstack.nova.v2_0.domain.SecurityGroup securityGroupWithGroup() {\n      TenantIdAndName group = TenantIdAndName.builder().tenantId(\"tenant\").name(SOME_OTHER_GROUP).build();\n\n      SecurityGroupRule ruleToConvert = SecurityGroupRule.builder()\n         .id(\"some-rule-id\")\n         .ipProtocol(IpProtocol.TCP)\n         .fromPort(10)\n         .toPort(20)\n         .group(group)\n         .parentGroupId(SOME_GROUP_ID)\n         .build();\n\n      org.jclouds.openstack.nova.v2_0.domain.SecurityGroup origGroup =\n         org.jclouds.openstack.nova.v2_0.domain.SecurityGroup.builder()\n            .tenantId(\"tenant\")\n            .id(SOME_GROUP_ID)\n            .name(SOME_GROUP)\n            .description(\"some-description\")\n            .rules(ruleToConvert)\n            .build();\n\n      return origGroup;\n   }\n\n   public static org.jclouds.openstack.nova.v2_0.domain.SecurityGroup securityGroupWithCidr() {\n      SecurityGroupRule ruleToConvert = SecurityGroupRule.builder()\n         .id(\"some-other-rule-id\")\n         .ipProtocol(IpProtocol.TCP)\n         .fromPort(10)\n         .toPort(20)\n         .ipRange(IP_RANGE)\n         .parentGroupId(SOME_OTHER_GROUP_ID)\n         .build();\n\n      org.jclouds.openstack.nova.v2_0.domain.SecurityGroup origGroup =\n         org.jclouds.openstack.nova.v2_0.domain.SecurityGroup.builder()\n            .tenantId(\"tenant\")\n            .id(SOME_OTHER_GROUP_ID)\n            .name(SOME_OTHER_GROUP)\n            .description(\"some-description\")\n            .rules(ruleToConvert)\n            .build();\n\n      return origGroup;\n   }\n\n   @Test\n   public void testApplyWithGroup() {\n      NovaSecurityGroupInRegionToSecurityGroup parser = createGroupParser();\n\n      final org.jclouds.openstack.nova.v2_0.domain.SecurityGroup otherGroup = securityGroupWithCidr();\n      SecurityGroupInRegion origGroup = new SecurityGroupInRegion(securityGroupWithGroup(), region.getId(), allGroups);\n\n      SecurityGroup newGroup = parser.apply(origGroup);\n\n      assertEquals(newGroup.getId(), origGroup.getRegion() + \"/\" + origGroup.getSecurityGroup().getId());\n      assertEquals(newGroup.getProviderId(), origGroup.getSecurityGroup().getId());\n      assertEquals(newGroup.getName(), origGroup.getSecurityGroup().getName());\n      assertEquals(newGroup.getOwnerId(), origGroup.getSecurityGroup().getTenantId());\n      final IpPermission permission = Iterables.getOnlyElement(newGroup.getIpPermissions());\n      assertEquals(Iterables.getOnlyElement(permission.getGroupIds()), region.getId() + \"/\" + otherGroup.getId());\n      assertEquals(permission.getFromPort(), 10);\n      assertEquals(permission.getToPort(), 20);\n      assertTrue(permission.getCidrBlocks().isEmpty());\n      assertEquals(newGroup.getLocation().getId(), origGroup.getRegion());\n   }\n\n   @Test\n   public void testApplyWithCidr() {\n\n      NovaSecurityGroupInRegionToSecurityGroup parser = createGroupParser();\n\n      SecurityGroupInRegion origGroup = new SecurityGroupInRegion(securityGroupWithCidr(), region.getId(), allGroups);\n\n      SecurityGroup newGroup = parser.apply(origGroup);\n\n      assertEquals(newGroup.getId(), origGroup.getRegion() + \"/\" + origGroup.getSecurityGroup().getId());\n      assertEquals(newGroup.getProviderId(), origGroup.getSecurityGroup().getId());\n      assertEquals(newGroup.getName(), origGroup.getSecurityGroup().getName());\n      assertEquals(newGroup.getOwnerId(), origGroup.getSecurityGroup().getTenantId());\n      final IpPermission permission = Iterables.getOnlyElement(newGroup.getIpPermissions());\n      assertEquals(permission.getFromPort(), 10);\n      assertEquals(permission.getToPort(), 20);\n      assertEquals(Iterables.getOnlyElement(permission.getCidrBlocks()), IP_RANGE);\n      assertTrue(permission.getGroupIds().isEmpty());\n      assertEquals(newGroup.getLocation().getId(), origGroup.getRegion());\n   }\n\n   private NovaSecurityGroupInRegionToSecurityGroup createGroupParser() {\n\n      NovaSecurityGroupInRegionToSecurityGroup parser = new NovaSecurityGroupInRegionToSecurityGroup(locationIndex);\n\n      return parser;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/compute/functions/OrphanedGroupsByRegionIdTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.compute.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.openstack.nova.v2_0.compute.config.NovaComputeServiceContextModule;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.RegionAndName;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.ServerInRegion;\nimport org.jclouds.openstack.nova.v2_0.parse.ParseServerTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicates;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\n\n@Test(testName = \"OrphanedGroupsByRegionIdTest\")\npublic class OrphanedGroupsByRegionIdTest {\n\n   Location provider = new LocationBuilder().scope(LocationScope.PROVIDER).id(\"openstack-nova\").description(\n            \"openstack-nova\").build();\n   Location region = new LocationBuilder().id(\"az-1.region-a.geo-1\").description(\"az-1.region-a.geo-1\").scope(\n            LocationScope.REGION).parent(provider).build();\n   Supplier<Map<String, Location>> locationIndex = Suppliers.<Map<String, Location>> ofInstance(ImmutableMap\n            .<String, Location> of(\"az-1.region-a.geo-1\", region));\n\n   GroupNamingConvention.Factory namingConvention = Guice.createInjector().getInstance(GroupNamingConvention.Factory.class);\n\n   @Test\n   public void testWhenComputeServiceSaysAllNodesAreDeadBothGroupsAreReturned() {\n\n      ServerInRegion withoutHost = new ServerInRegion(new ServerInRegionToNodeMetadataTest().expectedServer(), \"az-1.region-a.geo-1\");\n      ServerInRegion withHost = new ServerInRegion(new ParseServerTest().expected(), \"az-1.region-a.geo-1\");\n\n      ServerInRegionToNodeMetadata converter = new ServerInRegionToNodeMetadata(\n               NovaComputeServiceContextModule.toPortableNodeStatus, locationIndex, Suppliers\n               .<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of()), Suppliers\n               .<Set<? extends Hardware>> ofInstance(ImmutableSet.<Hardware> of()), namingConvention);\n\n      Set<? extends NodeMetadata> set = ImmutableSet.of(converter.apply(withHost), converter.apply(withoutHost));\n\n      assertEquals(new OrphanedGroupsByRegionId(Predicates.<RegionAndName> alwaysTrue()).apply(set), ImmutableMultimap\n               .<String, String> builder().putAll(\"az-1.region-a.geo-1\", \"sample\", \"test\").build());\n   }\n\n   @Test\n   public void testWhenComputeServiceSaysAllNodesAreDeadNoGroupsAreReturned() {\n\n      ServerInRegion withoutHost = new ServerInRegion(new ServerInRegionToNodeMetadataTest().expectedServer(), \"az-1.region-a.geo-1\");\n      ServerInRegion withHost = new ServerInRegion(new ParseServerTest().expected(), \"az-1.region-a.geo-1\");\n\n      ServerInRegionToNodeMetadata converter = new ServerInRegionToNodeMetadata(\n               NovaComputeServiceContextModule.toPortableNodeStatus, locationIndex, Suppliers\n                        .<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of()), Suppliers\n                        .<Set<? extends Hardware>> ofInstance(ImmutableSet.<Hardware> of()), namingConvention);\n\n      Set<? extends NodeMetadata> set = ImmutableSet.of(converter.apply(withHost), converter.apply(withoutHost));\n\n      assertEquals(new OrphanedGroupsByRegionId(Predicates.<RegionAndName> alwaysFalse()).apply(set), ImmutableMultimap\n               .<String, String> of());\n\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/compute/functions/ServerInRegionToNodeMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.compute.functions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\n\nimport java.net.URI;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.HardwareBuilder;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.ImageBuilder;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.openstack.nova.v2_0.compute.config.NovaComputeServiceContextModule;\nimport org.jclouds.openstack.nova.v2_0.domain.Server;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.ServerInRegion;\nimport org.jclouds.openstack.nova.v2_0.parse.ParseServerTest;\nimport org.jclouds.openstack.nova.v2_0.parse.ParseServerWithAddressExtensionsTest;\nimport org.jclouds.openstack.nova.v2_0.parse.ParseServerWithoutImageTest;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.Resource;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\n\n/**\n * Tests for the function for transforming a nova specific Server into a generic\n * NodeMetadata object.\n */\n@Test(testName = \"ServerInRegionToNodeMetadataTest\")\npublic class ServerInRegionToNodeMetadataTest {\n\n   Location provider = new LocationBuilder().scope(LocationScope.PROVIDER).id(\"openstack-nova\")\n         .description(\"openstack-nova\").build();\n   Location region = new LocationBuilder().id(\"az-1.region-a.geo-1\").description(\"az-1.region-a.geo-1\")\n         .scope(LocationScope.REGION).parent(provider).build();\n   Supplier<Map<String, Location>> locationIndex = Suppliers.<Map<String, Location>> ofInstance(ImmutableMap\n         .<String, Location> of(\"az-1.region-a.geo-1\", region));\n\n   GroupNamingConvention.Factory namingConvention = Guice.createInjector().getInstance(GroupNamingConvention.Factory.class);\n\n   @Test\n   public void testWhenNoHardwareOrImageMatchServerScopedIdsImageIdIsStillSet() {\n\n      Hardware existingHardware = new HardwareBuilder().id(\"az-1.region-a.geo-1/FOOOOOOOO\").providerId(\"FOOOOOOOO\")\n            .location(region).build();\n      Image existingImage = new ImageBuilder().id(\"az-1.region-a.geo-1/FOOOOOOOO\")\n            .operatingSystem(OperatingSystem.builder().family(OsFamily.LINUX).description(\"foobuntu\").build())\n            .providerId(\"FOOOOOOOO\").description(\"foobuntu\").location(region).status(Image.Status.AVAILABLE).build();\n\n      checkHardwareAndImageStatus(null, existingHardware, \"az-1.region-a.geo-1/52415800-8b69-11e0-9b19-734f6f006e54\",\n            null, existingImage);\n   }\n\n   @Test\n   public void testWhenNoHardwareAndImageMatchServerScopedIdsHardwareOperatingSystemAndImageIdAreSet() {\n\n      Hardware existingHardware = new HardwareBuilder().id(\"az-1.region-a.geo-1/52415800-8b69-11e0-9b19-734f216543fd\")\n            .providerId(\"52415800-8b69-11e0-9b19-734f216543fd\").location(region).build();\n      Image existingImage = new ImageBuilder().id(\"az-1.region-a.geo-1/52415800-8b69-11e0-9b19-734f6f006e54\")\n            .operatingSystem(OperatingSystem.builder().family(OsFamily.LINUX).description(\"foobuntu\").build())\n            .providerId(\"52415800-8b69-11e0-9b19-734f6f006e54\").description(\"foobuntu\").status(Image.Status.AVAILABLE)\n            .location(region).build();\n\n      checkHardwareAndImageStatus(existingHardware, existingHardware, existingImage.getId(),\n            existingImage.getOperatingSystem(), existingImage);\n   }\n\n   @Test\n   public void testNullAccessIPs() {\n      Hardware existingHardware = new HardwareBuilder().id(\"az-1.region-a.geo-1/52415800-8b69-11e0-9b19-734f216543fd\")\n            .providerId(\"52415800-8b69-11e0-9b19-734f216543fd\").location(region).build();\n      Image existingImage = new ImageBuilder().id(\"az-1.region-a.geo-1/52415800-8b69-11e0-9b19-734f6f006e54\")\n            .operatingSystem(OperatingSystem.builder().family(OsFamily.LINUX).description(\"foobuntu\").build())\n            .providerId(\"52415800-8b69-11e0-9b19-734f6f006e54\").description(\"foobuntu\").status(Image.Status.AVAILABLE)\n            .location(region).build();\n\n      Set<Image> images = existingImage == null ? ImmutableSet.<Image> of() : ImmutableSet.of(existingImage);\n      Set<Hardware> hardwares = existingHardware == null ? ImmutableSet.<Hardware> of() : ImmutableSet\n            .of(existingHardware);\n      Server serverToConvert = new ParseServerTest().expected().toBuilder()\n            .accessIPv4(null)\n            .accessIPv6(null)\n            .build();\n\n      ServerInRegion serverInRegionToConvert = new ServerInRegion(serverToConvert, \"az-1.region-a.geo-1\");\n\n      ServerInRegionToNodeMetadata converter = new ServerInRegionToNodeMetadata(\n            NovaComputeServiceContextModule.toPortableNodeStatus, locationIndex, Suppliers\n            .<Set<? extends Image>> ofInstance(images), Suppliers\n            .<Set<? extends Hardware>> ofInstance(hardwares), namingConvention);\n\n      NodeMetadata convertedNodeMetadata = converter.apply(serverInRegionToConvert);\n\n      assertNotNull(convertedNodeMetadata.getPrivateAddresses());\n      assertEquals(convertedNodeMetadata.getPrivateAddresses(), ImmutableSet.of(\"10.176.42.16\"));\n\n      assertNotNull(convertedNodeMetadata.getPublicAddresses());\n      // note jclouds doesn't yet support ipv6 b/c not tested yet\n      assertEquals(convertedNodeMetadata.getPublicAddresses(), ImmutableSet.of(\"67.23.10.132\", \"67.23.10.131\"));\n   }\n\n   @Test\n   public void testDuplicateAccessIPs() {\n      Hardware existingHardware = new HardwareBuilder().id(\"az-1.region-a.geo-1/52415800-8b69-11e0-9b19-734f216543fd\")\n            .providerId(\"52415800-8b69-11e0-9b19-734f216543fd\").location(region).build();\n      Image existingImage = new ImageBuilder().id(\"az-1.region-a.geo-1/52415800-8b69-11e0-9b19-734f6f006e54\")\n            .operatingSystem(OperatingSystem.builder().family(OsFamily.LINUX).description(\"foobuntu\").build())\n            .providerId(\"52415800-8b69-11e0-9b19-734f6f006e54\").description(\"foobuntu\").status(Image.Status.AVAILABLE)\n            .location(region).build();\n\n      Set<Image> images = existingImage == null ? ImmutableSet.<Image> of() : ImmutableSet.of(existingImage);\n      Set<Hardware> hardwares = existingHardware == null ? ImmutableSet.<Hardware> of() : ImmutableSet\n            .of(existingHardware);\n      Server serverToConvert = new ParseServerTest().expected().toBuilder()\n            .accessIPv4(\"67.23.10.132\")\n            .accessIPv6(\"::babe:67.23.10.132\")\n            .build();\n\n      ServerInRegion serverInRegionToConvert = new ServerInRegion(serverToConvert, \"az-1.region-a.geo-1\");\n\n      ServerInRegionToNodeMetadata converter = new ServerInRegionToNodeMetadata(\n            NovaComputeServiceContextModule.toPortableNodeStatus, locationIndex, Suppliers\n            .<Set<? extends Image>> ofInstance(images), Suppliers\n            .<Set<? extends Hardware>> ofInstance(hardwares), namingConvention);\n\n      NodeMetadata convertedNodeMetadata = converter.apply(serverInRegionToConvert);\n\n      assertNotNull(convertedNodeMetadata.getPrivateAddresses());\n      assertEquals(convertedNodeMetadata.getPrivateAddresses(), ImmutableSet.of(\"10.176.42.16\"));\n\n      assertNotNull(convertedNodeMetadata.getPublicAddresses());\n      // note jclouds doesn't yet support ipv6 b/c not tested yet\n      assertEquals(convertedNodeMetadata.getPublicAddresses(), ImmutableSet.of(\"67.23.10.132\", \"67.23.10.131\"));\n   }\n\n   @Test\n   public void testAlternateAccessIPs() {\n      Hardware existingHardware = new HardwareBuilder().id(\"az-1.region-a.geo-1/52415800-8b69-11e0-9b19-734f216543fd\")\n            .providerId(\"52415800-8b69-11e0-9b19-734f216543fd\").location(region).build();\n      Image existingImage = new ImageBuilder().id(\"az-1.region-a.geo-1/52415800-8b69-11e0-9b19-734f6f006e54\")\n            .operatingSystem(OperatingSystem.builder().family(OsFamily.LINUX).description(\"foobuntu\").build())\n            .providerId(\"52415800-8b69-11e0-9b19-734f6f006e54\").description(\"foobuntu\").status(Image.Status.AVAILABLE)\n            .location(region).build();\n\n      Set<Image> images = existingImage == null ? ImmutableSet.<Image> of() : ImmutableSet.of(existingImage);\n      Set<Hardware> hardwares = existingHardware == null ? ImmutableSet.<Hardware> of() : ImmutableSet\n            .of(existingHardware);\n      Server serverToConvert = new ParseServerTest().expected().toBuilder()\n            .accessIPv4(\"76.32.1.231\")\n            .accessIPv6(\"::babe:76.32.1.231\")\n            .build();\n\n      ServerInRegion serverInRegionToConvert = new ServerInRegion(serverToConvert, \"az-1.region-a.geo-1\");\n\n      ServerInRegionToNodeMetadata converter = new ServerInRegionToNodeMetadata(\n            NovaComputeServiceContextModule.toPortableNodeStatus, locationIndex, Suppliers\n            .<Set<? extends Image>> ofInstance(images), Suppliers\n            .<Set<? extends Hardware>> ofInstance(hardwares), namingConvention);\n\n      NodeMetadata convertedNodeMetadata = converter.apply(serverInRegionToConvert);\n\n      assertNotNull(convertedNodeMetadata.getPrivateAddresses());\n      assertEquals(convertedNodeMetadata.getPrivateAddresses(), ImmutableSet.of(\"10.176.42.16\"));\n\n      assertNotNull(convertedNodeMetadata.getPublicAddresses());\n      // note jclouds doesn't yet support ipv6 b/c not tested yet\n      assertEquals(convertedNodeMetadata.getPublicAddresses(), ImmutableSet.of(\"67.23.10.132\", \"67.23.10.131\", \"76.32.1.231\"));\n   }\n\n   @Test\n   public void testPortableNodeStatusNotNull() {\n      for (Server.Status serverStatus : Server.Status.values()) {\n         assertNotNull(NovaComputeServiceContextModule.toPortableNodeStatus.get(serverStatus));\n      }\n   }\n\n   @Test\n   public void testServerWithoutImage() {\n      Hardware existingHardware = new HardwareBuilder().id(\"az-1.region-a.geo-1/52415800-8b69-11e0-9b19-734f216543fd\")\n            .providerId(\"52415800-8b69-11e0-9b19-734f216543fd\").location(region).build();\n      Image existingImage = new ImageBuilder().id(\"az-1.region-a.geo-1/52415800-8b69-11e0-9b19-734f6f006e54\")\n            .operatingSystem(OperatingSystem.builder().family(OsFamily.LINUX).description(\"foobuntu\").build())\n            .providerId(\"52415800-8b69-11e0-9b19-734f6f006e54\").description(\"foobuntu\").status(Image.Status.AVAILABLE)\n            .location(region).build();\n\n      Server serverToConvert = new ParseServerWithoutImageTest().expected();\n      ServerInRegion serverInRegionToConvert = new ServerInRegion(serverToConvert, \"az-1.region-a.geo-1\");\n\n      ServerInRegionToNodeMetadata converter = new ServerInRegionToNodeMetadata(\n            NovaComputeServiceContextModule.toPortableNodeStatus, locationIndex,\n            Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.of(existingImage)),\n            Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet.of(existingHardware)),\n            namingConvention);\n\n      NodeMetadata convertedNodeMetadata = converter.apply(serverInRegionToConvert);\n\n      assertNull(convertedNodeMetadata.getImageId());\n   }\n\n   @Test\n   public void testFloatingIp() {\n      Hardware existingHardware = new HardwareBuilder().id(\"az-1.region-a.geo-1/52415800-8b69-11e0-9b19-734f216543fd\")\n              .providerId(\"52415800-8b69-11e0-9b19-734f216543fd\").location(region).build();\n      Image existingImage = new ImageBuilder().id(\"az-1.region-a.geo-1/52415800-8b69-11e0-9b19-734f6f006e54\")\n              .operatingSystem(OperatingSystem.builder().family(OsFamily.LINUX).description(\"foobuntu\").build())\n              .providerId(\"52415800-8b69-11e0-9b19-734f6f006e54\").description(\"foobuntu\").status(Image.Status.AVAILABLE)\n              .location(region).build();\n\n      Server serverToConvert = new ParseServerWithAddressExtensionsTest().expected();\n      ServerInRegion serverInRegionToConvert = new ServerInRegion(serverToConvert, \"az-1.region-a.geo-1\");\n\n      ServerInRegionToNodeMetadata converter = new ServerInRegionToNodeMetadata(\n              NovaComputeServiceContextModule.toPortableNodeStatus, locationIndex,\n              Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.of(existingImage)),\n              Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet.of(existingHardware)),\n              namingConvention);\n\n      NodeMetadata convertedNodeMetadata = converter.apply(serverInRegionToConvert);\n\n      assertEquals(convertedNodeMetadata.getPrivateAddresses(), ImmutableSet.of(\"172.16.130.24\"));\n      assertEquals(convertedNodeMetadata.getPublicAddresses(), ImmutableSet.of(\"10.8.54.75\"));\n   }\n\n   // TODO: clean up this syntax\n   private void checkHardwareAndImageStatus(Hardware expectedHardware, Hardware existingHardware,\n         String expectedImageId, OperatingSystem expectedOs, Image existingImage) {\n\n      Set<Image> images = existingImage == null ? ImmutableSet.<Image> of() : ImmutableSet.of(existingImage);\n      Set<Hardware> hardwares = existingHardware == null ? ImmutableSet.<Hardware> of() : ImmutableSet\n            .of(existingHardware);\n      Server serverToConvert = new ParseServerTest().expected();\n\n      ServerInRegion serverInRegionToConvert = new ServerInRegion(serverToConvert, \"az-1.region-a.geo-1\");\n\n      ServerInRegionToNodeMetadata converter = new ServerInRegionToNodeMetadata(\n               NovaComputeServiceContextModule.toPortableNodeStatus, locationIndex, Suppliers\n                        .<Set<? extends Image>> ofInstance(images), Suppliers\n                        .<Set<? extends Hardware>> ofInstance(hardwares), namingConvention);\n\n      NodeMetadata convertedNodeMetadata = converter.apply(serverInRegionToConvert);\n\n      assertEquals(serverInRegionToConvert.slashEncode(), convertedNodeMetadata.getId());\n      assertEquals(serverToConvert.getId(), convertedNodeMetadata.getProviderId());\n\n      assertEquals(convertedNodeMetadata.getLocation().getScope(), LocationScope.HOST);\n      assertEquals(convertedNodeMetadata.getLocation().getId(), \"e4d909c290d0fb1ca068ffaddf22cbd0\");\n\n      assertEquals(convertedNodeMetadata.getLocation().getParent(), locationIndex.get().get(\"az-1.region-a.geo-1\"));\n\n      assertEquals(serverToConvert.getName(), convertedNodeMetadata.getName());\n      assertEquals(convertedNodeMetadata.getGroup(), \"sample\");\n\n      assertEquals(convertedNodeMetadata.getImageId(), expectedImageId);\n      assertEquals(convertedNodeMetadata.getOperatingSystem(), expectedOs);\n\n      assertEquals(convertedNodeMetadata.getHardware(), expectedHardware);\n\n      assertEquals(NovaComputeServiceContextModule.toPortableNodeStatus.get(serverToConvert.getStatus()),\n               convertedNodeMetadata.getStatus());\n\n      assertNotNull(convertedNodeMetadata.getPrivateAddresses());\n      assertEquals(convertedNodeMetadata.getPrivateAddresses(), ImmutableSet.of(\"10.176.42.16\"));\n\n      assertNotNull(convertedNodeMetadata.getPublicAddresses());\n      // note jclouds doesn't yet support ipv6 b/c not tested yet\n      assertEquals(convertedNodeMetadata.getPublicAddresses(), ImmutableSet.of(\"67.23.10.132\", \"67.23.10.131\"));\n\n      assertNotNull(convertedNodeMetadata.getUserMetadata());\n      assertEquals(convertedNodeMetadata.getUserMetadata(),\n            ImmutableMap.<String, String> of(\"Server Label\", \"Web Head 1\", \"Image Version\", \"2.1\"));\n\n      URI expectedURI = URI.create(\"http://servers.api.openstack.org/v2/1234/servers/71752\");\n      assertEquals(convertedNodeMetadata.getUri(), expectedURI);\n   }\n\n   @Test\n   public void testNewServerWithoutHostIdSetsRegionAsLocation() {\n\n      Set<Image> images = ImmutableSet.<Image> of();\n      Set<Hardware> hardwares = ImmutableSet.<Hardware> of();\n\n      Server serverToConvert = expectedServer();\n\n      ServerInRegion serverInRegionToConvert = new ServerInRegion(serverToConvert, \"az-1.region-a.geo-1\");\n\n      ServerInRegionToNodeMetadata converter = new ServerInRegionToNodeMetadata(\n               NovaComputeServiceContextModule.toPortableNodeStatus, locationIndex, Suppliers\n                        .<Set<? extends Image>> ofInstance(images), Suppliers\n                        .<Set<? extends Hardware>> ofInstance(hardwares), namingConvention);\n\n      NodeMetadata convertedNodeMetadata = converter.apply(serverInRegionToConvert);\n\n      assertEquals(serverInRegionToConvert.slashEncode(), convertedNodeMetadata.getId());\n      assertEquals(serverToConvert.getId(), convertedNodeMetadata.getProviderId());\n\n      assertEquals(convertedNodeMetadata.getLocation(), region);\n\n      URI expectedURI = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/37936628937291/servers/71752\");\n      assertEquals(convertedNodeMetadata.getUri(), expectedURI);\n   }\n\n   public Server expectedServer() {\n      return Server\n            .builder()\n            .id(\"71752\")\n            .uuid(\"47491020-6a78-4f63-9475-23195ac4515c\")\n            .tenantId(\"37936628937291\")\n            .userId(\"54297837463082\")\n            .name(\"test-e92\")\n            .updated(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2012-03-19T06:21:13Z\"))\n            .created(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2012-03-19T06:21:13Z\"))\n            .status(Server.Status.BUILD)\n            .image(\n                  Resource\n                        .builder()\n                        .id(\"1241\")\n                        .links(\n                              Link.create(\n                                    Link.Relation.BOOKMARK,\n                                    URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/images/1241\")))\n                        .build())\n            .flavor(\n                  Resource\n                        .builder()\n                        .id(\"100\")\n                        .links(\n                              Link.create(\n                                    Link.Relation.BOOKMARK,\n                                    URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/flavors/100\")))\n                        .build())\n            .links(\n                  Link.create(Link.Relation.SELF, URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/37936628937291/servers/71752\")),\n                  Link.create(Link.Relation.BOOKMARK, URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/servers/71752\"))).build();\n\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/compute/loaders/FindSecurityGroupInRegionOrCreateTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.compute.loaders;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.fail;\n\nimport org.jclouds.compute.domain.SecurityGroup;\nimport org.jclouds.compute.domain.SecurityGroupBuilder;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.RegionAndName;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.RegionSecurityGroupNameAndPorts;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.SecurityGroupInRegion;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Functions;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\", singleThreaded = true, testName = \"FindSecurityGroupInRegionOrCreateTest\")\npublic class FindSecurityGroupInRegionOrCreateTest {\n\n   @Test\n   public void testWhenNotFoundCreatesANewSecurityGroup() throws Exception {\n      SecurityGroup securityGroup = createMock(SecurityGroup.class);\n\n      RegionSecurityGroupNameAndPorts input = new RegionSecurityGroupNameAndPorts(\"region\", \"groupName\", ImmutableSet\n               .<Integer> of(22, 8080));\n\n      Function<RegionSecurityGroupNameAndPorts, SecurityGroup> groupCreator = Functions.forMap(ImmutableMap\n               .of(input, securityGroup));\n\n      FindSecurityGroupOrCreate parser = new FindSecurityGroupOrCreate(groupCreator);\n\n      assertEquals(parser.load(input), securityGroup);\n\n   }\n\n   @Test(enabled = false) // TODO does it apply now?\n   public void testWhenFoundReturnsSecurityGroupFromAtomicReferenceValueUpdatedDuringPredicateCheck() throws Exception {\n      SecurityGroup expected = new SecurityGroupBuilder().id(\"region/id\").name(\"name\").build();\n      final SecurityGroupInRegion securityGroupInRegion = createMock(SecurityGroupInRegion.class);\n      final org.jclouds.openstack.nova.v2_0.domain.SecurityGroup novaSecurityGroup = createMock(org.jclouds.openstack.nova.v2_0.domain.SecurityGroup.class);\n\n\n      expect(novaSecurityGroup.getId()).andReturn(\"id\").anyTimes();\n      expect(novaSecurityGroup.getName()).andReturn(\"name\");\n      replay(novaSecurityGroup);\n\n      expect(securityGroupInRegion.getRegion()).andReturn(\"region\");\n      expect(securityGroupInRegion.getSecurityGroup()).andReturn(novaSecurityGroup).anyTimes();\n      replay(securityGroupInRegion);\n\n      RegionAndName input = RegionAndName.fromRegionAndName(\"region\", \"groupName\");\n\n      Function<RegionSecurityGroupNameAndPorts, SecurityGroup> groupCreator = new Function<RegionSecurityGroupNameAndPorts, SecurityGroup>() {\n\n         @Override\n         public SecurityGroup apply(RegionSecurityGroupNameAndPorts input) {\n            fail();\n            return null;\n         }\n\n      };\n\n      FindSecurityGroupOrCreate parser = new FindSecurityGroupOrCreate(groupCreator);\n\n      assertEquals(parser.load(input), expected);\n\n   }\n\n\n   @Test(expectedExceptions = IllegalStateException.class, enabled = false) // TODO does it apply now?\n   public void testWhenFoundPredicateMustUpdateAtomicReference() throws Exception {\n\n      RegionAndName input = RegionAndName.fromRegionAndName(\"region\", \"groupName\");\n\n      Function<RegionSecurityGroupNameAndPorts, SecurityGroup> groupCreator = new Function<RegionSecurityGroupNameAndPorts, SecurityGroup>() {\n\n         @Override\n         public SecurityGroup apply(RegionSecurityGroupNameAndPorts input) {\n            fail();\n            return null;\n         }\n\n      };\n\n      FindSecurityGroupOrCreate parser = new FindSecurityGroupOrCreate(groupCreator);\n\n      parser.load(input);\n\n   }\n\n   @Test(expectedExceptions = IllegalStateException.class)\n   public void testWhenNotFoundInputMustBeRegionSecurityGroupNameAndPorts() throws Exception {\n\n      RegionAndName input = RegionAndName.fromRegionAndName(\"region\", \"groupName\");\n\n      Function<RegionSecurityGroupNameAndPorts, SecurityGroup> groupCreator = new Function<RegionSecurityGroupNameAndPorts, SecurityGroup>() {\n\n         @Override\n         public SecurityGroup apply(RegionSecurityGroupNameAndPorts input) {\n            fail();\n            return null;\n         }\n\n      };\n\n      FindSecurityGroupOrCreate parser = new FindSecurityGroupOrCreate(groupCreator);\n\n      parser.load(input);\n\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/compute/loaders/LoadFloatingIpsForInstanceTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.compute.loaders;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.AssertJUnit.assertFalse;\n\nimport org.jclouds.openstack.nova.v2_0.NovaApi;\nimport org.jclouds.openstack.nova.v2_0.domain.FloatingIP;\nimport org.jclouds.openstack.nova.v2_0.domain.FloatingIpForServer;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.RegionAndId;\nimport org.jclouds.openstack.nova.v2_0.extensions.FloatingIPApi;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\", singleThreaded = true, testName = \"LoadFloatingIpsForInstanceTest\")\npublic class LoadFloatingIpsForInstanceTest {\n\n   @Test\n   public void testReturnsPublicIpOnMatch() throws Exception {\n      NovaApi api = createMock(NovaApi.class);\n      FloatingIPApi ipApi = createMock(FloatingIPApi.class);\n      FloatingIP testIp = FloatingIP.builder().id(\"1\").ip(\"1.1.1.1\").fixedIp(\"10.1.1.1\").instanceId(\"i-blah\").build();\n\n      expect(api.getFloatingIPApi(\"RegionOne\")).andReturn((Optional) Optional.of(ipApi)).atLeastOnce();\n      expect(ipApi.list()).andReturn((FluentIterable) FluentIterable.from(ImmutableSet.<FloatingIP> of(testIp)))\n               .atLeastOnce();\n\n      replay(api);\n      replay(ipApi);\n\n      LoadFloatingIpsForInstance parser = new LoadFloatingIpsForInstance(api);\n      FloatingIpForServer floatingIpForServer = FloatingIpForServer.create(RegionAndId.fromRegionAndId(\"RegionOne\", \"i-blah\"), \"1\", \"1.1.1.1\");\n      assertEquals(ImmutableSet.copyOf(parser.load(RegionAndId.fromRegionAndId(\"RegionOne\", \"i-blah\"))), ImmutableSet.of(floatingIpForServer));\n\n      verify(api);\n      verify(ipApi);\n   }\n\n   @Test\n   public void testReturnsNullWhenNotFound() throws Exception {\n      NovaApi api = createMock(NovaApi.class);\n      FloatingIPApi ipApi = createMock(FloatingIPApi.class);\n\n      expect(api.getFloatingIPApi(\"region\")).andReturn((Optional) Optional.of(ipApi)).atLeastOnce();\n\n      expect(ipApi.list()).andReturn((FluentIterable) FluentIterable.from(ImmutableSet.<FloatingIP> of()))\n      .atLeastOnce();\n\n      replay(api);\n      replay(ipApi);\n\n      LoadFloatingIpsForInstance parser = new LoadFloatingIpsForInstance(api);\n\n      assertFalse(parser.load(RegionAndId.fromRegionAndId(\"region\", \"i-blah\")).iterator().hasNext());\n\n      verify(api);\n      verify(ipApi);\n\n   }\n\n   @Test\n   public void testReturnsNullWhenNotAssigned() throws Exception {\n      NovaApi api = createMock(NovaApi.class);\n      FloatingIPApi ipApi = createMock(FloatingIPApi.class);\n\n      expect(api.getFloatingIPApi(\"region\")).andReturn((Optional) Optional.of(ipApi)).atLeastOnce();\n\n      expect(ipApi.list()).andReturn((FluentIterable) FluentIterable.from(ImmutableSet.<FloatingIP> of(FloatingIP.builder().id(\"1\").ip(\"1.1.1.1\").build())))\n      .atLeastOnce();\n\n      replay(api);\n      replay(ipApi);\n\n      LoadFloatingIpsForInstance parser = new LoadFloatingIpsForInstance(api);\n\n      assertFalse(parser.load(RegionAndId.fromRegionAndId(\"region\", \"i-blah\")).iterator().hasNext());\n\n      verify(api);\n      verify(ipApi);\n\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/compute/options/NovaTemplateOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.compute.options;\n\nimport static org.jclouds.openstack.nova.v2_0.compute.options.NovaTemplateOptions.Builder.authorizePublicKey;\nimport static org.jclouds.openstack.nova.v2_0.compute.options.NovaTemplateOptions.Builder.autoAssignFloatingIp;\nimport static org.jclouds.openstack.nova.v2_0.compute.options.NovaTemplateOptions.Builder.blockOnPort;\nimport static org.jclouds.openstack.nova.v2_0.compute.options.NovaTemplateOptions.Builder.generateKeyPair;\nimport static org.jclouds.openstack.nova.v2_0.compute.options.NovaTemplateOptions.Builder.inboundPorts;\nimport static org.jclouds.openstack.nova.v2_0.compute.options.NovaTemplateOptions.Builder.installPrivateKey;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\n\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.openstack.nova.v2_0.domain.Server;\nimport org.testng.annotations.Test;\n\n/**\n * Tests possible uses of NovaTemplateOptions and NovaTemplateOptions.Builder.*\n */\n@Test(testName = \"NovaTemplateOptionsTest\")\npublic class NovaTemplateOptionsTest {\n\n   public void testAs() {\n      TemplateOptions options = new NovaTemplateOptions();\n      assertEquals(options.as(NovaTemplateOptions.class), options);\n   }\n\n   @Test\n   public void testautoAssignFloatingIpDefault() {\n      NovaTemplateOptions options = new NovaTemplateOptions();\n      assert !options.shouldAutoAssignFloatingIp();\n   }\n\n   @Test\n   public void testautoAssignFloatingIp() {\n      NovaTemplateOptions options = new NovaTemplateOptions().autoAssignFloatingIp(true);\n      assert options.shouldAutoAssignFloatingIp();\n   }\n\n   @Test\n   public void testautoAssignFloatingIpStatic() {\n      NovaTemplateOptions options = autoAssignFloatingIp(true);\n      assert options.shouldAutoAssignFloatingIp();\n   }\n\n   @Test\n   public void testGenerateKeyPairDefault() {\n      NovaTemplateOptions options = new NovaTemplateOptions();\n      assert !options.shouldGenerateKeyPair();\n   }\n\n   @Test\n   public void testGenerateKeyPair() {\n      NovaTemplateOptions options = new NovaTemplateOptions().generateKeyPair(true);\n      assert options.shouldGenerateKeyPair();\n   }\n\n   @Test\n   public void testGenerateKeyPairStatic() {\n      NovaTemplateOptions options = generateKeyPair(true);\n      assert options.shouldGenerateKeyPair();\n   }\n\n   // superclass tests\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testinstallPrivateKeyBadFormat() {\n      NovaTemplateOptions options = new NovaTemplateOptions();\n      options.installPrivateKey(\"whompy\");\n   }\n\n   @Test\n   public void testinstallPrivateKey() throws IOException {\n      NovaTemplateOptions options = new NovaTemplateOptions();\n      options.installPrivateKey(\"-----BEGIN RSA PRIVATE KEY-----\");\n      assertEquals(options.getPrivateKey(), \"-----BEGIN RSA PRIVATE KEY-----\");\n   }\n\n   @Test\n   public void testNullinstallPrivateKey() {\n      NovaTemplateOptions options = new NovaTemplateOptions();\n      assertEquals(options.getPrivateKey(), null);\n   }\n\n   @Test\n   public void testinstallPrivateKeyStatic() throws IOException {\n      NovaTemplateOptions options = installPrivateKey(\"-----BEGIN RSA PRIVATE KEY-----\");\n      assertEquals(options.getPrivateKey(), \"-----BEGIN RSA PRIVATE KEY-----\");\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testinstallPrivateKeyNPE() {\n      installPrivateKey(null);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testauthorizePublicKeyBadFormat() {\n      NovaTemplateOptions options = new NovaTemplateOptions();\n      options.authorizePublicKey(\"whompy\");\n   }\n\n   @Test\n   public void testauthorizePublicKey() throws IOException {\n      NovaTemplateOptions options = new NovaTemplateOptions();\n      options.authorizePublicKey(\"ssh-rsa\");\n      assertEquals(options.getPublicKey(), \"ssh-rsa\");\n   }\n\n   @Test\n   public void testNullauthorizePublicKey() {\n      NovaTemplateOptions options = new NovaTemplateOptions();\n      assertEquals(options.getPublicKey(), null);\n   }\n\n   @Test\n   public void testauthorizePublicKeyStatic() throws IOException {\n      NovaTemplateOptions options = authorizePublicKey(\"ssh-rsa\");\n      assertEquals(options.getPublicKey(), \"ssh-rsa\");\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testauthorizePublicKeyNPE() {\n      authorizePublicKey(null);\n   }\n\n   @Test\n   public void testUserData() {\n       NovaTemplateOptions options = new NovaTemplateOptions();\n       options.userData(\"test\".getBytes());\n       assertEquals(new String(options.getUserData()), \"test\");\n   }\n\n   @Test\n   public void testAvailabilityZone() {\n      NovaTemplateOptions options = new NovaTemplateOptions();\n      options.availabilityZone(\"nova\");\n      assertEquals(options.getAvailabilityZone(), \"nova\");\n   }\n\n   @Test\n   public void testDiskConfig() {\n       NovaTemplateOptions options = new NovaTemplateOptions();\n       options.diskConfig(Server.DISK_CONFIG_AUTO);\n       assertEquals(options.getDiskConfig(), Server.DISK_CONFIG_AUTO);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testblockOnPortBadFormat() {\n      NovaTemplateOptions options = new NovaTemplateOptions();\n      options.blockOnPort(-1, -1);\n   }\n\n   @Test\n   public void testblockOnPort() {\n      NovaTemplateOptions options = new NovaTemplateOptions();\n      options.blockOnPort(22, 30);\n      assertEquals(options.getPort(), 22);\n      assertEquals(options.getSeconds(), 30);\n\n   }\n\n   @Test\n   public void testNullblockOnPort() {\n      NovaTemplateOptions options = new NovaTemplateOptions();\n      assertEquals(options.getPort(), -1);\n      assertEquals(options.getSeconds(), -1);\n   }\n\n   @Test\n   public void testblockOnPortStatic() {\n      NovaTemplateOptions options = blockOnPort(22, 30);\n      assertEquals(options.getPort(), 22);\n      assertEquals(options.getSeconds(), 30);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testinboundPortsBadFormat() {\n      NovaTemplateOptions options = new NovaTemplateOptions();\n      options.inboundPorts(-1, -1);\n   }\n\n   @Test\n   public void testinboundPorts() {\n      NovaTemplateOptions options = new NovaTemplateOptions();\n      options.inboundPorts(22, 30);\n      assertEquals(options.getInboundPorts()[0], 22);\n      assertEquals(options.getInboundPorts()[1], 30);\n\n   }\n\n   @Test\n   public void testDefaultOpen22() {\n      NovaTemplateOptions options = new NovaTemplateOptions();\n      assertEquals(options.getInboundPorts()[0], 22);\n   }\n\n   @Test\n   public void testinboundPortsStatic() {\n      NovaTemplateOptions options = inboundPorts(22, 30);\n      assertEquals(options.getInboundPorts()[0], 22);\n      assertEquals(options.getInboundPorts()[1], 30);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/config/ImageAdapterTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.config;\n\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.io.IOException;\n\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.openstack.nova.v2_0.domain.Image;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.io.Resources;\nimport com.google.gson.Gson;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\")\npublic class ImageAdapterTest {\n\n   private Gson gson;\n\n   @BeforeTest\n   public void setup() {\n      Injector injector = Guice.createInjector(new GsonModule(), new NovaParserModule());\n      gson = injector.getInstance(Gson.class);\n   }\n\n   public void testDeserializeWithBlockDeviceMappingAndMetadata() throws Exception {\n      ImageContainer container = gson.fromJson(stringFromResource(\"image_details_with_block_device_mapping.json\"), ImageContainer.class);\n\n      // Note that the block device mapping keys are removed from the metadata by the adapter.\n      assertNotNull(container.image.getMetadata());\n      assertEquals(container.image.getMetadata().size(), 2);\n      assertEquals(\"Gold\", container.image.getMetadata().get(\"ImageType\"));\n      assertEquals(\"1.5\", container.image.getMetadata().get(\"ImageVersion\"));\n\n      assertNotNull(container.image.getBlockDeviceMapping());\n      assertEquals(container.image.getBlockDeviceMapping().size(), 1);\n      assertEquals(Integer.valueOf(2), getOnlyElement(container.image.getBlockDeviceMapping()).getBootIndex());\n      assertEquals(\"snapshot\", getOnlyElement(container.image.getBlockDeviceMapping()).getSourceType());\n   }\n\n   public void testDeserializeWithoutBlockDeviceMapping() throws Exception {\n      ImageContainer container = gson.fromJson(stringFromResource(\"image_details.json\"), ImageContainer.class);\n\n      assertNotNull(container.image.getMetadata());\n      assertEquals(container.image.getMetadata().size(), 2);\n      assertEquals(\"Gold\", container.image.getMetadata().get(\"ImageType\"));\n      assertEquals(\"1.5\", container.image.getMetadata().get(\"ImageVersion\"));\n\n      assertNotNull(container.image.getBlockDeviceMapping());\n      assertEquals(0, container.image.getBlockDeviceMapping().size());\n   }\n\n   public void testDeserializeWithoutBlockDeviceMappingOrMetadata() throws Exception {\n      ImageContainer container = gson.fromJson(stringFromResource(\"image_details_without_metadata.json\"), ImageContainer.class);\n\n      assertNotNull(container.image.getMetadata());\n      assertEquals(container.image.getMetadata().size(), 0);\n      assertNotNull(container.image.getBlockDeviceMapping());\n      assertEquals(0, container.image.getBlockDeviceMapping().size());\n   }\n\n   private String stringFromResource(String resource) throws IOException {\n      return Resources.toString(Resources.getResource(resource), Charsets.UTF_8);\n   }\n\n   // Note that the ImageApi methods use the \"@SelectJson\" annotation to unwrap the object inside the \"image\" key\n   // We use this container to deserialize the Image object to simulate that behavior and use a *real* json\n   // in the tests.\n   public static class ImageContainer {\n      public Image image;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/AdminActionsApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.nova.v2_0.domain.BackupType;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiExpectTest;\nimport org.jclouds.openstack.nova.v2_0.options.CreateBackupOfServerOptions;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Tests parsing and guice wiring of AdminActionsApi\n */\n@Test(groups = \"unit\", testName = \"AdminActionsApiExpectTest\")\npublic class AdminActionsApiExpectTest extends BaseNovaApiExpectTest {\n\n   public void testSuspend() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers/1/action\");\n      ServerAdminApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            standardActionRequestBuilderVoidResponse(endpoint, \"suspend\").build(),\n            HttpResponse.builder().statusCode(202).build()\n      ).getServerAdminApi(\"az-1.region-a.geo-1\").get();\n\n      api.suspend(\"1\");\n   }\n\n   public void testResume() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers/1/action\");\n      ServerAdminApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            standardActionRequestBuilderVoidResponse(endpoint, \"resume\").build(),\n            HttpResponse.builder().statusCode(202).build()\n      ).getServerAdminApi(\"az-1.region-a.geo-1\").get();\n\n      api.resume(\"1\");\n   }\n\n   public void testLock() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers/1/action\");\n      ServerAdminApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            standardActionRequestBuilderVoidResponse(endpoint, \"lock\").build(),\n            HttpResponse.builder().statusCode(202).build()\n      ).getServerAdminApi(\"az-1.region-a.geo-1\").get();\n\n      api.lock(\"1\");\n   }\n\n   public void testUnlock() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers/1/action\");\n      ServerAdminApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            standardActionRequestBuilderVoidResponse(endpoint, \"unlock\").build(),\n            HttpResponse.builder().statusCode(202).build()\n      ).getServerAdminApi(\"az-1.region-a.geo-1\").get();\n\n      api.unlock(\"1\");\n   }\n\n   public void testPause() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers/1/action\");\n      ServerAdminApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            standardActionRequestBuilderVoidResponse(endpoint, \"pause\").build(),\n            HttpResponse.builder().statusCode(202).build()\n      ).getServerAdminApi(\"az-1.region-a.geo-1\").get();\n\n      api.pause(\"1\");\n   }\n\n   public void testUnpause() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers/1/action\");\n      ServerAdminApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            standardActionRequestBuilderVoidResponse(endpoint, \"unpause\").build(),\n            HttpResponse.builder().statusCode(202).build()\n      ).getServerAdminApi(\"az-1.region-a.geo-1\").get();\n\n      api.unpause(\"1\");\n   }\n\n   public void testMigrateServer() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers/1/action\");\n      ServerAdminApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            standardActionRequestBuilderVoidResponse(endpoint, \"migrate\").build(),\n            HttpResponse.builder().statusCode(202).build()\n      ).getServerAdminApi(\"az-1.region-a.geo-1\").get();\n\n      api.migrate(\"1\");\n   }\n\n   public void testResetNetworkOfServer() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers/1/action\");\n      ServerAdminApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            standardActionRequestBuilderVoidResponse(endpoint, \"resetNetwork\").build(),\n            HttpResponse.builder().statusCode(202).build()\n      ).getServerAdminApi(\"az-1.region-a.geo-1\").get();\n\n      api.resetNetwork(\"1\");\n   }\n\n   public void testInjectNetworkInfoIntoServer() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers/1/action\");\n      ServerAdminApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            standardActionRequestBuilderVoidResponse(endpoint, \"injectNetworkInfo\").build(),\n            HttpResponse.builder().statusCode(202).build()\n      ).getServerAdminApi(\"az-1.region-a.geo-1\").get();\n\n      api.injectNetworkInfo(\"1\");\n   }\n\n   public void testBackupServer() {\n      ServerAdminApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            authenticatedGET().endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers/1/action\").method(\"POST\")\n                  .payload(payloadFromStringWithContentType(\"{\\\"createBackup\\\":{\\\"backup_type\\\":\\\"weekly\\\",\\\"rotation\\\":3,\\\"name\\\":\\\"mybackup\\\",\\\"metadata\\\":{\\\"some\\\":\\\"data or other\\\"}}}\", MediaType.APPLICATION_JSON)).build(),\n            HttpResponse.builder().statusCode(202).addHeader(\"Location\", \"http://172.16.89.149:8774/v2/images/1976b3b3-409a-468d-b16c-a9172c341b46\").build()\n      ).getServerAdminApi(\"az-1.region-a.geo-1\").get();\n\n      String imageId = api.createBackup(\"1\", \"mybackup\", BackupType.WEEKLY, 3, CreateBackupOfServerOptions.Builder.metadata(ImmutableMap.of(\"some\", \"data or other\")));\n      assertEquals(imageId, \"1976b3b3-409a-468d-b16c-a9172c341b46\");\n   }\n\n   public void testLiveMigrateServer() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers/1/action\");\n      ServerAdminApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            standardActionRequestBuilderVoidResponse(endpoint, \"GONNAOVERWRITE\")\n                  .payload(payloadFromStringWithContentType(\"{\\\"os-migrateLive\\\":{\\\"host\\\":\\\"bighost\\\",\\\"block_migration\\\":true,\\\"disk_over_commit\\\":false}}\", MediaType.APPLICATION_JSON)).build(),\n            HttpResponse.builder().statusCode(202).build()\n      ).getServerAdminApi(\"az-1.region-a.geo-1\").get();\n\n      api.liveMigrate(\"1\", \"bighost\", true, false);\n   }\n\n   protected HttpRequest.Builder<?> standardActionRequestBuilderVoidResponse(URI endpoint, String actionName) {\n      return HttpRequest.builder()\n                        .method(\"POST\")\n                        .addHeader(\"X-Auth-Token\", authToken)\n                        .addHeader(\"Accept\", \"application/json\")\n                        .payload(payloadFromStringWithContentType(\"{\\\"\" + actionName + \"\\\":null}\", MediaType.APPLICATION_JSON))\n                        .endpoint(endpoint);\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/AdminActionsApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.Assert.fail;\n\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.openstack.nova.v2_0.domain.BackupType;\nimport org.jclouds.openstack.nova.v2_0.domain.Image;\nimport org.jclouds.openstack.nova.v2_0.domain.Server.Status;\nimport org.jclouds.openstack.nova.v2_0.features.ImageApi;\nimport org.jclouds.openstack.nova.v2_0.features.ServerApi;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiLiveTest;\nimport org.jclouds.openstack.nova.v2_0.options.CreateBackupOfServerOptions;\nimport org.jclouds.openstack.v2_0.features.ExtensionApi;\nimport org.testng.SkipException;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.AfterMethod;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\n\n/**\n * Tests behavior of HostAdministrationApi\n *\n * TODO test migration methods\n */\n@Test(groups = \"live\", testName = \"AdminActionsApiLiveTest\", singleThreaded = true)\npublic class AdminActionsApiLiveTest extends BaseNovaApiLiveTest {\n   private ImageApi imageApi;\n   private ServerApi serverApi;\n   private ExtensionApi extensionApi;\n   private Optional<? extends ServerAdminApi> apiOption;\n   private String region;\n\n   private String testServerId;\n   private String backupImageId;\n\n   @BeforeClass(groups = {\"integration\", \"live\"})\n   @Override\n   public void setup() {\n      super.setup();\n      region = Iterables.getLast(api.getConfiguredRegions(), \"nova\");\n      serverApi = api.getServerApi(region);\n      extensionApi = api.getExtensionApi(region);\n      imageApi = api.getImageApi(region);\n      apiOption = api.getServerAdminApi(region);\n      if (apiOption.isPresent()) {\n         testServerId = createServerInRegion(region).getId();\n      }\n   }\n\n   @AfterClass(groups = { \"integration\", \"live\" })\n   @Override\n   protected void tearDown() {\n      if (apiOption.isPresent()) {\n         if (testServerId != null) {\n            assertTrue(api.getServerApi(region).delete(testServerId));\n         }\n         if (backupImageId != null) {\n            imageApi.delete(backupImageId);\n         }\n      }\n      super.tearDown();\n   }\n\n   protected void skipOnAdminExtensionAbsent() {\n      if (!apiOption.isPresent()) {\n         throw new SkipException(\"Test depends on ServerAdminApi extension\");\n      }\n   }\n\n   @AfterMethod(alwaysRun = true)\n   public void ensureServerIsActiveAgain() {\n      if (apiOption.isPresent())\n         blockUntilServerInState(testServerId, serverApi, Status.ACTIVE);\n   }\n\n   public void testSuspendAndResume() {\n      skipOnAdminExtensionAbsent();\n      ServerAdminApi api = apiOption.get();\n\n      // Suspend-resume\n      try {\n         api.resume(testServerId);\n         fail(\"Resumed an active server!\");\n      } catch (HttpResponseException e) {\n      }\n      api.suspend(testServerId);\n      blockUntilServerInState(testServerId, serverApi, Status.SUSPENDED);\n      try {\n         api.suspend(testServerId);\n         fail(\"Suspended an already suspended server!\");\n      } catch (HttpResponseException e) {\n      }\n      api.resume(testServerId);\n      blockUntilServerInState(testServerId, serverApi, Status.ACTIVE);\n      try {\n         api.resume(testServerId);\n         fail(\"Resumed an already resumed server!\");\n      } catch (HttpResponseException e) {\n      }\n\n   }\n\n   public void testLockAndUnlock() {\n      skipOnAdminExtensionAbsent();\n      ServerAdminApi api = apiOption.get();\n\n      // TODO should we be able to double-lock (as it were)\n      api.unlock(testServerId);\n      api.unlock(testServerId);\n      api.lock(testServerId);\n      api.lock(testServerId);\n      api.unlock(testServerId);\n      api.unlock(testServerId);\n\n   }\n\n   public void testResetNetworkAndInjectNetworkInfo() {\n      skipOnAdminExtensionAbsent();\n      ServerAdminApi api = apiOption.get();\n      api.resetNetwork(testServerId);\n      api.injectNetworkInfo(testServerId);\n   }\n\n   @Test\n   public void testPauseAndUnpause() {\n      skipOnAdminExtensionAbsent();\n      ServerAdminApi api = apiOption.get();\n\n      // Unlock and lock (double-checking error contitions too)\n      try {\n         api.unpause(testServerId);\n         fail(\"Unpaused active server!\");\n      } catch (HttpResponseException e) {\n      }\n      api.pause(testServerId);\n      blockUntilServerInState(testServerId, serverApi, Status.PAUSED);\n      try {\n         api.pause(testServerId);\n         fail(\"paused a paused server!\");\n      } catch (HttpResponseException e) {\n      }\n      api.unpause(testServerId);\n      blockUntilServerInState(testServerId, serverApi, Status.ACTIVE);\n      try {\n         api.unpause(testServerId);\n         fail(\"Unpaused a server we just unpaused!\");\n      } catch (HttpResponseException e) {\n      }\n\n   }\n\n   @Test\n   public void testCreateBackupOfServer() throws InterruptedException {\n      skipOnAdminExtensionAbsent();\n      backupImageId = apiOption.get().createBackup(testServerId, \"jclouds-test-backup\", BackupType.DAILY, 0,\n               CreateBackupOfServerOptions.Builder.metadata(ImmutableMap.of(\"test\", \"metadata\")));\n\n      assertNotNull(backupImageId);\n\n      // If we don't have extended task status, we'll have to wait here!\n      if (extensionApi.get(\"OS-EXT-STS\") == null) {\n         Thread.sleep(30000);\n      }\n\n      blockUntilServerInState(testServerId, serverApi, Status.ACTIVE);\n\n      Image backupImage = imageApi.get(backupImageId);\n      assertEquals(backupImage.getId(), backupImageId);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/AttachInterfaceApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport com.google.common.base.Optional;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableSet;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.nova.v2_0.NovaApi;\nimport org.jclouds.openstack.nova.v2_0.domain.FixedIP;\nimport org.jclouds.openstack.nova.v2_0.domain.InterfaceAttachment;\nimport org.jclouds.openstack.nova.v2_0.domain.PortState;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiExpectTest;\nimport org.testng.annotations.Test;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\n@Test(groups = \"unit\", testName = \"AttachInterfaceApiExpectTest\")\npublic class AttachInterfaceApiExpectTest extends BaseNovaApiExpectTest {\n\n   public void testAttachInterfacesList() throws Exception {\n      HttpRequest list = HttpRequest.builder().method(\"GET\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers/instance-1/os-interface\")\n            .addHeader(\"Accept\", \"application/json\").addHeader(\"X-Auth-Token\", authToken).build();\n\n      HttpResponse listResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResource(\"/attach_interfaces_list.json\")).build();\n\n      NovaApi novaApi = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, list, listResponse);\n\n      FluentIterable<InterfaceAttachment> interfaceAttachments = novaApi.getAttachInterfaceApi(\"az-1.region-a.geo-1\")\n            .get().list(\"instance-1\");\n\n      Optional<? extends InterfaceAttachment> interfaceAttachment = interfaceAttachments.first();\n\n      assertTrue(interfaceAttachment.isPresent(), \"Couldn't find interface attachment\");\n      assertEquals(interfaceAttachment.get(), testInterfaceAttachment());\n   }\n\n   public void testAttachInterfaceGet() throws Exception {\n      HttpRequest list = HttpRequest\n            .builder()\n            .method(\"GET\")\n            .endpoint(\n                  \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers/instance-1/os-interface/ce531f90-199f-48c0-816c-13e38010b442\")\n            .addHeader(\"Accept\", \"application/json\").addHeader(\"X-Auth-Token\", authToken).build();\n\n      HttpResponse listResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResource(\"/attach_interface_details.json\")).build();\n\n      NovaApi novaApi = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, list, listResponse);\n\n      InterfaceAttachment interfaceAttachment = novaApi.getAttachInterfaceApi(\"az-1.region-a.geo-1\").get()\n            .get(\"instance-1\", \"ce531f90-199f-48c0-816c-13e38010b442\");\n\n      assertEquals(interfaceAttachment, testInterfaceAttachment());\n   }\n\n   private InterfaceAttachment testInterfaceAttachment() {\n      return InterfaceAttachment\n            .builder()\n            .portId(\"ce531f90-199f-48c0-816c-13e38010b442\")\n            .networkId(\"3cb9bc59-5699-4588-a4b1-b87f96708bc6\")\n            .portState(PortState.ACTIVE)\n            .macAddress(\"fa:16:3e:4c:2c:30\")\n            .fixedIps(\n                  ImmutableSet.of(FixedIP.builder().ipAddress(\"192.168.1.3\")\n                        .subnetId(\"f8a6e8f8-c2ec-497c-9f23-da9616de54ef\").build())).build();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/AvailabilityZoneApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport com.google.common.base.Optional;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableSet;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.nova.v2_0.NovaApi;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.AvailabilityZone;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.AvailabilityZoneDetails;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.AvailabilityZoneDetails.HostService;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiExpectTest;\nimport org.testng.annotations.Test;\n\nimport java.util.Date;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.Assert.assertFalse;\n\n@Test(groups = \"unit\", testName = \"AvailabilityZoneApiExpectTest\")\npublic class AvailabilityZoneApiExpectTest extends BaseNovaApiExpectTest {\n\n   public void testWhenNamespaceInExtensionsListAvailabilityZonesPresent() throws Exception {\n\n      NovaApi apiWhenExtensionInList = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse);\n\n      assertEquals(apiWhenExtensionInList.getConfiguredRegions(), ImmutableSet.of(\"az-1.region-a.geo-1\", \"az-2.region-a.geo-1\", \"az-3.region-a.geo-1\"));\n\n      assertTrue(apiWhenExtensionInList.getFloatingIPApi(\"az-1.region-a.geo-1\").isPresent());\n\n   }\n\n   public void testWhenNamespaceNotInExtensionsListAvailabilityZonesPresent() throws Exception {\n\n      NovaApi apiWhenExtensionNotInList = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, unmatchedExtensionsOfNovaResponse);\n\n      assertEquals(apiWhenExtensionNotInList.getConfiguredRegions(), ImmutableSet.of(\"az-1.region-a.geo-1\", \"az-2.region-a.geo-1\", \"az-3.region-a.geo-1\"));\n\n      assertFalse(apiWhenExtensionNotInList.getFloatingIPApi(\"az-1.region-a.geo-1\").isPresent());\n\n   }\n\n   public void testListAvailabilityZones() throws Exception {\n      HttpRequest list = HttpRequest\n            .builder()\n            .method(\"GET\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-availability-zone\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken).build();\n\n      HttpResponse listResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResource(\"/listAvailabilityZones.json\")).build();\n\n      NovaApi availabilityZonesApi = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess,\n            extensionsOfNovaRequest, extensionsOfNovaResponse, list, listResponse);\n\n      assertEquals(availabilityZonesApi.getConfiguredRegions(), ImmutableSet.of(\"az-1.region-a.geo-1\", \"az-2.region-a.geo-1\", \"az-3.region-a.geo-1\"));\n\n      FluentIterable<? extends AvailabilityZone> zones = availabilityZonesApi.getAvailabilityZoneApi(\"az-1.region-a.geo-1\").get().listAvailabilityZones();\n\n      Optional<? extends AvailabilityZone> zone = zones.first();\n\n      assertTrue(zone.isPresent(), \"Couldn't find zone\");\n      assertEquals(zone.get().getName(), \"internal\", \"Expected zone name to be internal but it was: \" + zone.get().getName());\n      assertTrue(zone.get().getState().isAvailable(), \"Zone: \" + zone.get().getName() + \" is not available.\");\n   }\n\n   public void testListInDetail() throws Exception {\n      HttpRequest list = HttpRequest\n            .builder()\n            .method(\"GET\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-availability-zone/detail\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken).build();\n\n      HttpResponse listResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResource(\"/listAvailabilityZones.json\")).build();\n\n      NovaApi availabilityZonesApi = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, list, listResponse);\n\n      assertEquals(availabilityZonesApi.getConfiguredRegions(), ImmutableSet.of(\"az-1.region-a.geo-1\", \"az-2.region-a.geo-1\", \"az-3.region-a.geo-1\"));\n\n      FluentIterable<? extends AvailabilityZoneDetails> zones = availabilityZonesApi.getAvailabilityZoneApi(\"az-1.region-a.geo-1\").get().listInDetail();\n\n      Optional<? extends AvailabilityZoneDetails> zone = zones.first();\n\n      assertTrue(zone.isPresent(), \"Couldn't find zone\");\n      assertEquals(zone.get()\n            .getName(), \"internal\", \"Expected zone name to be internal but it was: \" + zone.get()\n            .getName());\n      assertTrue(zone.get()\n            .getState()\n            .isAvailable(), \"Zone: \" + zone.get()\n            .getName() + \" is not available.\");\n      String hostName = zone.get().getHosts().keySet().iterator().next();\n      assertEquals(hostName, \"os-controller\", \"Expected host name to be os-controller but it was: \" + hostName);\n      String hostServiceName = zone.get().getHosts().get(hostName).keySet().iterator().next();\n      assertEquals(hostServiceName, \"nova-conductor\",\n            \"Expected host service name to be nova-conductor but it was: \" + hostServiceName);\n      HostService hostService = zone.get().getHosts().get(hostName).get(hostServiceName);\n      assertTrue(hostService.isAvailable(), \"Couldn't find host service availability\");\n      assertTrue(hostService.isActive(), \"Couldn't find host service state\");\n      assertEquals(hostService.getUpdated(), new Date(1436509815000L),\n            \"Expected Updated time: \" + new Date(1436509815000L) + \" does match Updated time : \" + hostService.getUpdated());\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/AvailabilityZonesApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport com.google.common.base.Optional;\nimport com.google.common.collect.FluentIterable;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.AvailabilityZone;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.AvailabilityZoneDetails;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.AvailabilityZoneDetails.HostService;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiLiveTest;\nimport org.testng.annotations.Test;\n\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\n@Test(groups = \"live\", testName = \"AvailabilityZonesApiLiveTest\")\npublic class AvailabilityZonesApiLiveTest extends BaseNovaApiLiveTest {\n\n   @Test\n   public void testListAvailabilityZones() throws Exception {\n\n      Optional<? extends AvailabilityZoneApi> availabilityZoneApi = api.getAvailabilityZoneApi(\"RegionOne\");\n      if (availabilityZoneApi.isPresent()) {\n         FluentIterable<? extends AvailabilityZone> zones = availabilityZoneApi.get().listAvailabilityZones();\n\n         for (AvailabilityZone zone : zones) {\n            assertNotNull(zone.getName());\n            assertTrue(zone.getState().isAvailable(), \"zone: \" + zone.getName() + \" is not available.\");\n         }\n      }\n   }\n\n   @Test\n   public void testListInDetail() throws Exception {\n\n      Optional<? extends AvailabilityZoneApi> availabilityZoneApi = api.getAvailabilityZoneApi(\"RegionOne\");\n      if (availabilityZoneApi.isPresent()) {\n         FluentIterable<? extends AvailabilityZoneDetails> zones = availabilityZoneApi.get().listInDetail();\n\n         for (AvailabilityZoneDetails zone : zones) {\n            assertNotNull(zone.getName());\n            assertTrue(zone.getState()\n                  .isAvailable(), \"zone: \" + zone.getName() + \" is not available.\");\n            String hostName = zone.getHosts().keySet().iterator().next();\n            assertNotNull(hostName, \"Expected host name to be not null\");\n            String hostServiceName = zone.getHosts().get(hostName).keySet().iterator().next();\n            assertNotNull(hostServiceName, \"Expected host service name to be not null\");\n            HostService hostService = zone.getHosts().get(hostName).get(hostServiceName);\n            assertTrue(hostService.isAvailable(), \"Couldn't find host service availability\");\n            assertTrue(hostService.isActive(), \"Couldn't find host service state\");\n            assertNotNull(hostService.getUpdated(), \"Expected Updated time, but none received \");\n\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/ConsolesApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.openstack.nova.v2_0.domain.Console;\nimport org.jclouds.openstack.nova.v2_0.domain.Server;\nimport org.jclouds.openstack.nova.v2_0.features.ServerApi;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\n\n/**\n * Tests behavior of {@code ConsolesApi}\n */\n@Test(groups = \"live\", testName = \"ConsolesApiLiveTest\")\npublic class ConsolesApiLiveTest extends BaseNovaApiLiveTest {\n\n   public void testGetNOVNCConsole() {\n      testGetConsole(Console.Type.NOVNC);\n   }\n\n   public void testGetXVPVNCConsole() {\n      testGetConsole(Console.Type.XVPVNC);\n   }\n\n   private void testGetConsole(Console.Type consoleType) {\n      for (String regionId : api.getConfiguredRegions()) {\n         Optional<? extends ConsolesApi> apiOption = api.getConsolesApi(regionId);\n         if (!apiOption.isPresent()) {\n            System.err.println(\"Consoles extension not present in server.\");\n            continue;\n         }\n\n         ConsolesApi api = apiOption.get();\n         ServerApi serverApi = this.api.getServerApi(regionId);\n         Server server = createServerInRegion(regionId);\n         Console console = api.getConsole(server.getId(), consoleType);\n         assertNotNull(console.getType());\n         assertTrue(consoleType.equals(console.getType()));\n         assertNotNull(console.getUrl());\n         assertTrue(console.getUrl().toString().startsWith(\"http\"));\n         serverApi.delete(server.getId());\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/ConsolesApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport static com.google.common.collect.Iterables.getFirst;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\n\nimport org.jclouds.openstack.nova.v2_0.NovaApi;\nimport org.jclouds.openstack.nova.v2_0.domain.Console;\nimport org.jclouds.openstack.nova.v2_0.parse.ParseNOVNCConsoleTest;\nimport org.jclouds.openstack.nova.v2_0.parse.ParseRDPConsoleTest;\nimport org.jclouds.openstack.nova.v2_0.parse.ParseSPICEConsoleTest;\nimport org.jclouds.openstack.nova.v2_0.parse.ParseXVPVNCConsoleTest;\nimport org.jclouds.openstack.v2_0.internal.BaseOpenStackMockTest;\nimport org.testng.annotations.Test;\n\n\n/**\n * Tests ConsolesApi Guice wiring and parsing\n */\n@Test(groups = \"unit\", testName = \"ConsolesApiMockTest\", enabled = false)\npublic class ConsolesApiMockTest extends BaseOpenStackMockTest<NovaApi> {\n\n   public void testNullConsoleType() {\n      assertNull(Console.Type.fromValue(null));\n   }\n\n   public void testUnrecognizedConsoleType() {\n      assertEquals(Console.Type.UNRECOGNIZED, Console.Type.fromValue(\"invalid type\"));\n   }\n\n   public void getNOVNCConsole() throws Exception {\n      getConsole(Console.Type.NOVNC, \"/novnc_console.json\", new ParseNOVNCConsoleTest().expected());\n   }\n\n   public void getXVPVNCConsole() throws Exception {\n      getConsole(Console.Type.XVPVNC, \"/xvpvnc_console.json\", new ParseXVPVNCConsoleTest().expected());\n   }\n\n   public void getSPICEConsole() throws Exception {\n      getConsole(Console.Type.SPICE_HTML5, \"/spice_console.json\", new ParseSPICEConsoleTest().expected());\n   }\n\n   public void getRDPConsole() throws Exception {\n      getConsole(Console.Type.RDP_HTML5, \"/rdp_console.json\", new ParseRDPConsoleTest().expected());\n   }\n\n   private void getConsole(Console.Type consoleType, String responseResource, Console expected) throws Exception {\n      String serverId = \"5f64fca7-879b-4173-bf9c-8fa88330a4dc\";\n\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/keystoneAuthResponse.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/extension_list_full.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(responseResource))));\n\n      try {\n         NovaApi novaApi = api(server.url(\"/\").toString(), \"openstack-nova\");\n\n         String regionId = getFirst(novaApi.getConfiguredRegions(), \"RegionTwo\");\n\n         ConsolesApi consolesApi = novaApi.getConsolesApi(regionId).get();\n\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertEquals(server.takeRequest().getRequestLine(),\n                 \"GET /v2/da0d12be20394afb851716e10a49e4a7/extensions HTTP/1.1\");\n         assertEquals(consolesApi.getConsole(serverId, consoleType), expected);\n\n      } finally {\n         server.shutdown();\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/DeprecatedAvailabilityZoneApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport com.google.common.base.Optional;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableSet;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.nova.v2_0.NovaApi;\nimport org.jclouds.openstack.nova.v2_0.domain.zonescoped.AvailabilityZone;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiExpectTest;\nimport org.testng.annotations.Test;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\n@Test(groups = \"unit\", testName = \"DeprecatedAvailabilityZoneApiExpectTest\")\npublic class DeprecatedAvailabilityZoneApiExpectTest extends BaseNovaApiExpectTest {\n\n   public void testAvailabilityZonesList() throws Exception {\n      HttpRequest list = HttpRequest\n            .builder()\n            .method(\"GET\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-availability-zone\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken).build();\n\n      HttpResponse listResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResource(\"/listAvailabilityZones.json\")).build();\n\n      NovaApi availabilityZonesApi = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, list, listResponse);\n\n      assertEquals(availabilityZonesApi.getConfiguredRegions(), ImmutableSet.of(\"az-1.region-a.geo-1\", \"az-2.region-a.geo-1\", \"az-3.region-a.geo-1\"));\n\n      FluentIterable<? extends AvailabilityZone> zones = availabilityZonesApi.getAvailabilityZoneApi(\"az-1.region-a.geo-1\").get().list();\n\n      Optional<? extends AvailabilityZone> zone = zones.first();\n\n      assertTrue(zone.isPresent(), \"Couldn't find zone\");\n      assertEquals(zone.get().getName(), \"internal\",\n            \"Expected zone name to be internal but it was: \" + zone.get().getName());\n      assertTrue(zone.get().getState().available(), \"Zone: \" + zone.get().getName() + \" is not available.\");\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/DeprecatedAvailabilityZonesApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport com.google.common.base.Optional;\nimport com.google.common.collect.FluentIterable;\nimport org.jclouds.openstack.nova.v2_0.domain.zonescoped.AvailabilityZone;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiLiveTest;\nimport org.testng.annotations.Test;\n\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\n@Test(groups = \"live\", testName = \"DeprecatedAvailabilityZonesApiLiveTest\")\npublic class DeprecatedAvailabilityZonesApiLiveTest extends BaseNovaApiLiveTest {\n\n   @Test\n   public void testListAvailabilityZones() throws Exception {\n\n      Optional<? extends AvailabilityZoneApi> availabilityZoneApi = api.getAvailabilityZoneApi(\"RegionOne\");\n      if (availabilityZoneApi.isPresent()) {\n         FluentIterable<? extends AvailabilityZone> zones = availabilityZoneApi.get().list();\n\n         for (AvailabilityZone zone : zones) {\n            assertNotNull(zone.getName());\n            assertTrue(zone.getState().available(), \"zone: \" + zone.getName() + \" is not available.\");\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/ExtendedAvailabilityZoneExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.nova.v2_0.NovaApi;\nimport org.jclouds.openstack.nova.v2_0.domain.Server;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiExpectTest;\nimport org.testng.annotations.Test;\n\nimport static org.testng.Assert.assertNotNull;\n\n@Test(groups = \"unit\", testName = \"ExtendedAvailabilityZoneExpectTest\")\npublic class ExtendedAvailabilityZoneExpectTest extends BaseNovaApiExpectTest{\n\n   public void testAvailabilityZoneInServerDetails() throws Exception {\n      String serverId = \"71752\";\n\n      HttpRequest serverDetail = HttpRequest\n            .builder()\n            .method(\"GET\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers/\" + serverId)\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken).build();\n\n      HttpResponse serverDetailResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResource(\"/server_details.json\")).build();\n\n      NovaApi apiWhenServerExists = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, serverDetail, serverDetailResponse);\n\n      Server server = apiWhenServerExists.getServerApi(\"az-1.region-a.geo-1\").get(serverId);\n      assertNotNull(server.getAvailabilityZone());\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/ExtendedAvailabilityZoneLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport org.jclouds.openstack.nova.v2_0.domain.Server;\nimport org.jclouds.openstack.nova.v2_0.features.ServerApi;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiLiveTest;\nimport org.testng.annotations.Test;\n\nimport static org.testng.Assert.assertNotNull;\n\n\n@Test(groups = \"live\", testName = \"ExtendedAvailabilityZoneLiveTest\")\npublic class ExtendedAvailabilityZoneLiveTest extends BaseNovaApiLiveTest {\n\n   public void testListServersInDetailsReturnAvalibiltyZone() throws Exception {\n      for (String regionId : regions) {\n         ServerApi serverApi = api.getServerApi(regionId);\n         for (Server server : serverApi.listInDetail().concat()) {\n            if (server.getAvailabilityZone().isPresent()) {\n               assertNotNull(server.getAvailabilityZone().get());\n            }\n         }\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/FlavorExtraSpecsApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiExpectTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Tests guice wiring and parsing of FlavorExtraSpecsApi\n */\n@Test(groups = \"unit\", testName = \"FlavorExtraSpecsApiExpectTest\")\npublic class FlavorExtraSpecsApiExpectTest extends BaseNovaApiExpectTest {\n\n   public void testGetAllExtraSpecs() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/flavors/9/os-extra_specs\");\n      FlavorExtraSpecsApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/volume_type_extra_specs.json\")).build()\n      ).getFlavorExtraSpecsApi(\"az-1.region-a.geo-1\").get();\n\n      assertEquals(api.getMetadata(\"9\"), ImmutableMap.of(\"test\", \"value1\"));\n   }\n\n   public void testSetAllExtraSpecs() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/flavors/9/os-extra_specs\");\n      FlavorExtraSpecsApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            authenticatedGET().endpoint(endpoint)\n                  .method(\"POST\")\n                  .payload(payloadFromStringWithContentType(\"{\\\"extra_specs\\\":{\\\"test1\\\":\\\"somevalue\\\"}}\", MediaType.APPLICATION_JSON)).build(),\n            HttpResponse.builder().statusCode(200).build()\n      ).getFlavorExtraSpecsApi(\"az-1.region-a.geo-1\").get();\n\n      api.updateMetadata(\"9\", ImmutableMap.of(\"test1\", \"somevalue\"));\n   }\n\n   public void testSetExtraSpec() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/flavors/5/os-extra_specs/test1\");\n      FlavorExtraSpecsApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            authenticatedGET().endpoint(endpoint)\n                  .method(\"PUT\")\n                  .payload(payloadFromStringWithContentType(\"{\\\"test1\\\":\\\"somevalue\\\"}\", MediaType.APPLICATION_JSON)).build(),\n            HttpResponse.builder().statusCode(200).build()\n      ).getFlavorExtraSpecsApi(\"az-1.region-a.geo-1\").get();\n\n      api.updateMetadataEntry(\"5\", \"test1\", \"somevalue\");\n   }\n\n   public void testGetExtraSpec() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/flavors/5/os-extra_specs/test1\");\n      FlavorExtraSpecsApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromStringWithContentType(\"{\\\"test1\\\":\\\"another value\\\"}\", MediaType.APPLICATION_JSON)).build()\n      ).getFlavorExtraSpecsApi(\"az-1.region-a.geo-1\").get();\n\n      assertEquals(api.getMetadataKey(\"5\", \"test1\"), \"another value\");\n   }\n\n   public void testDeleteExtraSpec() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/flavors/5/os-extra_specs/test1\");\n      FlavorExtraSpecsApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            authenticatedGET().endpoint(endpoint).method(\"DELETE\").build(),\n            HttpResponse.builder().statusCode(200).build()\n      ).getFlavorExtraSpecsApi(\"az-1.region-a.geo-1\").get();\n\n      assertTrue(api.deleteMetadataKey(\"5\", \"test1\"));\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/FlavorExtraSpecsApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Map;\n\nimport org.jclouds.openstack.nova.v2_0.features.FlavorApi;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiLiveTest;\nimport org.jclouds.openstack.v2_0.domain.Resource;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Maps;\n\n/**\n * Tests behavior of FlavorExtraSpecsApi\n */\n@Test(groups = \"live\", testName = \"FlavorExtraSpecsApiLiveTest\", singleThreaded = true)\npublic class FlavorExtraSpecsApiLiveTest extends BaseNovaApiLiveTest {\n   private FlavorApi flavorApi;\n   private Optional<? extends FlavorExtraSpecsApi> apiOption;\n   private String region;\n\n   private Resource testFlavor;\n   private Map<String, String> testSpecs = ImmutableMap.of(\"jclouds-test\", \"some data\", \"jclouds-test2\", \"more data!\");\n\n   @BeforeClass(groups = {\"integration\", \"live\"})\n   @Override\n   public void setup() {\n      super.setup();\n      region = Iterables.getLast(api.getConfiguredRegions(), \"nova\");\n      flavorApi = api.getFlavorApi(region);\n      apiOption = api.getFlavorExtraSpecsApi(region);\n   }\n\n   @AfterClass(groups = { \"integration\", \"live\" })\n   @Override\n   protected void tearDown() {\n      if (apiOption.isPresent() && testFlavor != null) {\n         for (String key : testSpecs.keySet()) {\n            assertTrue(apiOption.get().deleteMetadataKey(testFlavor.getId(), key));\n         }\n      }\n      super.tearDown();\n   }\n\n   public void testCreateExtraSpecs() {\n      if (apiOption.isPresent()) {\n         FlavorExtraSpecsApi api = apiOption.get();\n         testFlavor = Iterables.getLast(flavorApi.list().concat());\n         Map<String, String> before = api.getMetadata(testFlavor.getId());\n         assertNotNull(before);\n         Map<String, String> specs = Maps.newHashMap(before);\n         specs.putAll(testSpecs);\n         api.updateMetadata(testFlavor.getId(), specs);\n         assertEquals(api.getMetadata(testFlavor.getId()), specs);\n         for (Map.Entry<String, String> entry : specs.entrySet()) {\n            assertEquals(api.getMetadataKey(testFlavor.getId(), entry.getKey()), entry.getValue());\n         }\n      }\n   }\n\n   @Test(dependsOnMethods = \"testCreateExtraSpecs\")\n   public void testListExtraSpecs() {\n      if (apiOption.isPresent()) {\n         FlavorExtraSpecsApi api = apiOption.get();\n         for (String key : testSpecs.keySet()) {\n            assertTrue(api.getMetadata(testFlavor.getId()).containsKey(key));\n         }\n         for (Resource flavor : flavorApi.list().concat()) {\n            Map<String, String> specs = api.getMetadata(flavor.getId());\n            assertNotNull(specs);\n            for (Map.Entry<String, String> entry : specs.entrySet()) {\n               assertEquals(api.getMetadataKey(flavor.getId(), entry.getKey()), entry.getValue());\n            }\n         }\n      }\n   }\n\n   @Test(dependsOnMethods = \"testCreateExtraSpecs\")\n   public void testTwiddleIndividualSpecs() {\n      if (apiOption.isPresent()) {\n         FlavorExtraSpecsApi api = apiOption.get();\n         for (String key : testSpecs.keySet()) {\n            api.updateMetadataEntry(testFlavor.getId(), key, \"new value\");\n         }\n         for (String key : testSpecs.keySet()) {\n            assertEquals(api.getMetadataKey(testFlavor.getId(), key), \"new value\");\n         }\n         for (Resource flavor : flavorApi.list().concat()) {\n            Map<String, String> specs = api.getMetadata(flavor.getId());\n            assertNotNull(specs);\n            for (Map.Entry<String, String> entry : specs.entrySet()) {\n               assertEquals(api.getMetadataKey(flavor.getId(), entry.getKey()), entry.getValue());\n            }\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/FloatingIPApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.nova.v2_0.NovaApi;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiExpectTest;\nimport org.jclouds.openstack.nova.v2_0.parse.ParseFloatingIPListTest;\nimport org.jclouds.openstack.nova.v2_0.parse.ParseFloatingIPTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests annotation parsing of {@code FloatingIPApi}\n */\n@Test(groups = \"unit\", testName = \"FloatingIPApiExpectTest\")\npublic class FloatingIPApiExpectTest extends BaseNovaApiExpectTest {\n   public void testWhenNamespaceInExtensionsListFloatingIpPresent() throws Exception {\n\n      NovaApi apiWhenExtensionNotInList = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse);\n\n      assertEquals(apiWhenExtensionNotInList.getConfiguredRegions(), ImmutableSet.of(\"az-1.region-a.geo-1\", \"az-2.region-a.geo-1\", \"az-3.region-a.geo-1\"));\n\n      assertTrue(apiWhenExtensionNotInList.getFloatingIPApi(\"az-1.region-a.geo-1\").isPresent());\n\n   }\n\n   public void testWhenNamespaceNotInExtensionsListFloatingIpNotPresent() throws Exception {\n\n      NovaApi apiWhenExtensionNotInList = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, unmatchedExtensionsOfNovaResponse);\n\n      assertEquals(apiWhenExtensionNotInList.getConfiguredRegions(), ImmutableSet.of(\"az-1.region-a.geo-1\", \"az-2.region-a.geo-1\", \"az-3.region-a.geo-1\"));\n\n      assertFalse(apiWhenExtensionNotInList.getFloatingIPApi(\"az-1.region-a.geo-1\").isPresent());\n\n   }\n\n   public void testNamespaceMissingNameFallback() throws Exception {\n\n      NovaApi apiWhenExtensionNotInList = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, unmatchedExtensionsOfNovaResponseWithNoNamespace);\n\n      assertEquals(apiWhenExtensionNotInList.getConfiguredRegions(), ImmutableSet.of(\"az-1.region-a.geo-1\", \"az-2.region-a.geo-1\", \"az-3.region-a.geo-1\"));\n\n      assertTrue(apiWhenExtensionNotInList.getFloatingIPApi(\"az-1.region-a.geo-1\").isPresent());\n\n   }\n\n   public void testListFloatingIPsWhenResponseIs2xx() throws Exception {\n      HttpRequest list = HttpRequest\n            .builder()\n            .method(\"GET\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-floating-ips\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken).build();\n\n      HttpResponse listResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResource(\"/floatingip_list.json\")).build();\n\n      NovaApi apiWhenFloatingIPsExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, list, listResponse);\n\n      assertEquals(apiWhenFloatingIPsExist.getConfiguredRegions(), ImmutableSet.of(\"az-1.region-a.geo-1\", \"az-2.region-a.geo-1\", \"az-3.region-a.geo-1\"));\n\n      assertEquals(apiWhenFloatingIPsExist.getFloatingIPApi(\"az-1.region-a.geo-1\").get().list()\n            .toString(), new ParseFloatingIPListTest().expected().toString());\n   }\n\n   public void testGetFloatingIPWhenResponseIs2xx() throws Exception {\n      HttpRequest get = HttpRequest\n            .builder()\n            .method(\"GET\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-floating-ips/1\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken).build();\n\n      HttpResponse getResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResource(\"/floatingip_details.json\")).build();\n\n      NovaApi apiWhenFloatingIPsExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, get, getResponse);\n\n      assertEquals(apiWhenFloatingIPsExist.getFloatingIPApi(\"az-1.region-a.geo-1\").get().get(\"1\")\n            .toString(), new ParseFloatingIPTest().expected().toString());\n   }\n\n   public void testAllocateWhenResponseIs2xx() throws Exception {\n      HttpRequest createFloatingIP = HttpRequest\n            .builder()\n            .method(\"POST\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-floating-ips\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken)\n            .payload(payloadFromStringWithContentType(\"{}\", \"application/json\")).build();\n\n      HttpResponse createFloatingIPResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResource(\"/floatingip_details.json\")).build();\n\n      NovaApi apiWhenFloatingIPsExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, createFloatingIP,\n            createFloatingIPResponse);\n\n      assertEquals(apiWhenFloatingIPsExist.getFloatingIPApi(\"az-1.region-a.geo-1\").get().create().toString(),\n            new ParseFloatingIPTest().expected().toString());\n\n   }\n\n   public void testAllocateWithPoolNameWhenResponseIs2xx() throws Exception {\n      HttpRequest createFloatingIP = HttpRequest\n            .builder()\n            .method(\"POST\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-floating-ips\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken)\n            .payload(payloadFromStringWithContentType(\"{\\\"pool\\\":\\\"myPool\\\"}\", \"application/json\")).build();\n\n      HttpResponse createFloatingIPResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResource(\"/floatingip_details.json\")).build();\n\n      NovaApi apiWhenFloatingIPsExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, createFloatingIP,\n            createFloatingIPResponse);\n\n      assertEquals(apiWhenFloatingIPsExist.getFloatingIPApi(\"az-1.region-a.geo-1\").get().allocateFromPool(\"myPool\").toString(),\n            new ParseFloatingIPTest().expected().toString());\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/FloatingIPApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\n\nimport org.jclouds.openstack.nova.v2_0.domain.Address;\nimport org.jclouds.openstack.nova.v2_0.domain.FloatingIP;\nimport org.jclouds.openstack.nova.v2_0.domain.Server;\nimport org.jclouds.openstack.nova.v2_0.features.ServerApi;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.collect.Multimap;\n\n/**\n * Tests the behavior of the {@link FloatingIPApi}\n */\n@Test(groups = \"live\", testName = \"FloatingIPApiLiveTest\")\npublic class FloatingIPApiLiveTest extends BaseNovaApiLiveTest {\n\n   private static final int INCONSISTENCY_WINDOW = 5000;\n\n   @Test\n   public void testListFloatingIPs() throws Exception {\n      for (String regionId : api.getConfiguredRegions()) {\n         Optional<? extends FloatingIPApi> apiOption = api.getFloatingIPApi(regionId);\n         if (!apiOption.isPresent())\n            continue;\n         FloatingIPApi api = apiOption.get();\n         Set<? extends FloatingIP> response = api.list().toSet();\n         assert null != response;\n         assertTrue(response.size() > 0);\n         for (FloatingIP ip : response) {\n            FloatingIP newDetails = api.get(ip.getId());\n\n            assertEquals(newDetails.getId(), ip.getId());\n            assertEquals(newDetails.getIp(), ip.getIp());\n            assertEquals(newDetails.getFixedIp(), ip.getFixedIp());\n            assertEquals(newDetails.getInstanceId(), ip.getInstanceId());\n            assertEquals(newDetails.getPool(), ip.getPool());\n         }\n      }\n   }\n\n   @Test\n   public void testAllocateAndDecreateFloatingIPs() throws Exception {\n      for (String regionId : api.getConfiguredRegions()) {\n         Optional<? extends FloatingIPApi> apiOption = api.getFloatingIPApi(regionId);\n         if (!apiOption.isPresent())\n            continue;\n         FloatingIPApi api = apiOption.get();\n         FloatingIP floatingIP = api.create();\n         assertNotNull(floatingIP);\n\n         Set<? extends FloatingIP> response = api.list().toSet();\n         boolean ipInSet = false;\n         for (FloatingIP ip : response) {\n            if (ip.getId().equals(floatingIP.getId()))\n               ipInSet = true;\n         }\n         assertTrue(ipInSet);\n\n         api.delete(floatingIP.getId());\n\n         response = api.list().toSet();\n         ipInSet = false;\n         for (FloatingIP ip : response) {\n            if (ip.getId().equals(floatingIP.getId())) {\n               ipInSet = true;\n            }\n         }\n         assertFalse(ipInSet);\n      }\n   }\n\n   @Test\n   public void testAddAndRemoveFloatingIp() throws Exception {\n      for (String regionId : api.getConfiguredRegions()) {\n         Optional<? extends FloatingIPApi> apiOption = api.getFloatingIPApi(regionId);\n         if (!apiOption.isPresent())\n            continue;\n         FloatingIPApi api = apiOption.get();\n         ServerApi serverApi = this.api.getServerApi(regionId);\n         Server server = createServerInRegion(regionId);\n         FloatingIP floatingIP = api.create();\n         assertNotNull(floatingIP);\n         try {\n            api.addToServer(floatingIP.getIp(), server.getId());\n            assertEventually(new ServerHasFloatingIP(serverApi, server.getId(), floatingIP.getIp()));\n         } finally {\n            api.removeFromServer(floatingIP.getIp(), server.getId());\n            serverApi.delete(server.getId());\n         }\n      }\n   }\n\n   protected static void assertEventually(Runnable assertion) {\n      long start = System.currentTimeMillis();\n      AssertionError error = null;\n      for (int i = 0; i < 30; i++) {\n         try {\n            assertion.run();\n            if (i > 0)\n               System.err.printf(\"%d attempts and %dms asserting %s%n\", i + 1, System.currentTimeMillis() - start,\n                     assertion.getClass().getSimpleName());\n            return;\n         } catch (AssertionError e) {\n            error = e;\n         }\n         try {\n            Thread.sleep(INCONSISTENCY_WINDOW / 30);\n         } catch (InterruptedException e) {\n         }\n      }\n      if (error != null)\n         throw error;\n\n   }\n\n   public static final class ServerHasFloatingIP implements Runnable {\n      private final ServerApi api;\n      private final String serverId;\n      private final String floatingIP;\n\n      public ServerHasFloatingIP(ServerApi serverApi, String serverId, String floatingIP) {\n         this.api = serverApi;\n         this.serverId = serverId;\n         this.floatingIP = floatingIP;\n      }\n\n      public void run() {\n         try {\n            Server server = api.get(serverId);\n            boolean ipInServerAddresses = false;\n            Multimap<String, Address> addresses = server.getAddresses();\n            for (Address address : addresses.values()) {\n               if (address.getAddr().equals(floatingIP)) {\n                  ipInServerAddresses = true;\n               }\n            }\n            assertTrue(ipInServerAddresses);\n         } catch (Exception e) {\n            throw new AssertionError(e);\n         }\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/FloatingIPPoolApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.nova.v2_0.NovaApi;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiExpectTest;\nimport org.jclouds.openstack.nova.v2_0.parse.ParseFloatingIPPoolListTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests annotation parsing of {@code FloatingIPPoolApi}\n */\n@Test(groups = \"unit\", testName = \"FloatingIPPoolApiExpectTest\")\npublic class FloatingIPPoolApiExpectTest extends BaseNovaApiExpectTest {\n   public void testWhenNamespaceInExtensionsListFloatingIpPoolPresent() throws Exception {\n\n      NovaApi apiWhenExtensionNotInList = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse);\n\n      assertEquals(apiWhenExtensionNotInList.getConfiguredRegions(),\n            ImmutableSet.of(\"az-1.region-a.geo-1\", \"az-2.region-a.geo-1\", \"az-3.region-a.geo-1\"));\n\n      assertTrue(apiWhenExtensionNotInList.getFloatingIPPoolApi(\"az-1.region-a.geo-1\").isPresent());\n\n   }\n\n   public void testWhenNamespaceNotInExtensionsListFloatingIpPoolNotPresent() throws Exception {\n\n      NovaApi apiWhenExtensionNotInList = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, unmatchedExtensionsOfNovaResponse);\n\n      assertEquals(apiWhenExtensionNotInList.getConfiguredRegions(), ImmutableSet.of(\"az-1.region-a.geo-1\", \"az-2.region-a.geo-1\", \"az-3.region-a.geo-1\"));\n\n      assertFalse(apiWhenExtensionNotInList.getFloatingIPPoolApi(\"az-1.region-a.geo-1\").isPresent());\n\n   }\n\n   public void testListFloatingIPPoolWhenResponseIs2xx() throws Exception {\n      HttpRequest list = HttpRequest\n            .builder()\n            .method(\"GET\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-floating-ip-pools\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken).build();\n\n      HttpResponse listResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResource(\"/floatingippool_list.json\")).build();\n\n      NovaApi apiWhenFloatingIPPoolExists = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, list, listResponse);\n\n      assertEquals(apiWhenFloatingIPPoolExists.getConfiguredRegions(), ImmutableSet.of(\"az-1.region-a.geo-1\", \"az-2.region-a.geo-1\", \"az-3.region-a.geo-1\"));\n\n      assertEquals(apiWhenFloatingIPPoolExists.getFloatingIPPoolApi(\"az-1.region-a.geo-1\").get().list()\n            .toString(), new ParseFloatingIPPoolListTest().expected().toString());\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/FloatingIPPoolApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport com.google.common.base.Optional;\nimport com.google.common.collect.FluentIterable;\nimport org.jclouds.openstack.nova.v2_0.domain.FloatingIPPool;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiLiveTest;\nimport org.testng.annotations.Test;\n\nimport static org.testng.Assert.assertTrue;\n\n/**\n * Tests for the {@code FloatingIPPoolApi}\n */\n@Test(groups = \"live\", testName = \"FloatingIPPoolApiLiveTest\")\npublic class FloatingIPPoolApiLiveTest extends BaseNovaApiLiveTest {\n\n   @Test\n   public void testListFloatingIPPools() throws Exception {\n      for (String region : regions) {\n         Optional<? extends FloatingIPPoolApi> apiOption = api.getFloatingIPPoolApi(region);\n\n         if (!apiOption.isPresent()) {\n            continue;\n         }\n\n         FloatingIPPoolApi api = apiOption.get();\n         FluentIterable<? extends FloatingIPPool> response = api.list();\n         assertTrue(!response.toSet().isEmpty());\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/HostAdministrationApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.Set;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.nova.v2_0.domain.Host;\nimport org.jclouds.openstack.nova.v2_0.domain.HostResourceUsage;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiExpectTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\n\n/**\n * Tests HostAdministrationApi guice wiring and parsing (including the Response parsers in FieldValueResponseParsers)\n */\n@Test(groups = \"unit\", testName = \"HostAdministrationApiExpectTest\")\npublic class HostAdministrationApiExpectTest extends BaseNovaApiExpectTest {\n\n\n   public void testList() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-hosts\");\n      HostAdministrationApi api = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            HttpRequest.builder().method(\"GET\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"X-Auth-Token\", authToken)\n                  .endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/hosts_list.json\")).build()).getHostAdministrationApi(\"az-1.region-a.geo-1\").get();\n\n      Host expected = Host.builder().name(\"ubuntu\").service(\"compute\").zone(\"nova\").build();\n\n      Set<? extends Host> result = api.list().toSet();\n      Host host = Iterables.getOnlyElement(result);\n      assertEquals(host.getName(), \"ubuntu\");\n      assertEquals(host.getService(), \"compute\");\n      assertEquals(host.getZone(), \"nova\");\n\n      assertEquals(host, expected);\n   }\n\n   public void testGet() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-hosts/xyz\");\n      HostAdministrationApi api = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            HttpRequest.builder().method(\"GET\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"X-Auth-Token\", authToken)\n                  .endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/host.json\")).build()).getHostAdministrationApi(\"az-1.region-a.geo-1\").get();\n\n      Set<HostResourceUsage> expected = ImmutableSet.of(\n            HostResourceUsage.builder().memoryMb(16083).project(\"(total)\").cpu(4).diskGb(181).host(\"ubuntu\").build(),\n            HostResourceUsage.builder().memoryMb(3396).project(\"(used_now)\").cpu(3).diskGb(5).host(\"ubuntu\").build(),\n            HostResourceUsage.builder().memoryMb(6144).project(\"(used_max)\").cpu(3).diskGb(80).host(\"ubuntu\").build(),\n            HostResourceUsage.builder().memoryMb(6144).project(\"f8535069c3fb404cb61c873b1a0b4921\").cpu(3).diskGb(80).host(\"ubuntu\").build()\n      );\n\n      assertEquals(api.listResourceUsage(\"xyz\").toSet(), expected);\n   }\n\n   public void testEnableHost() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-hosts/ubuntu\");\n      HostAdministrationApi api = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            HttpRequest.builder().method(\"PUT\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"X-Auth-Token\", authToken)\n                  .payload(payloadFromStringWithContentType(\"{\\\"status\\\":\\\"enable\\\"}\", MediaType.APPLICATION_JSON))\n                  .endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200)\n                  .payload(payloadFromStringWithContentType(\"{\\\"host\\\":\\\"ubuntu\\\",\\\"status\\\":\\\"enabled\\\"}\", MediaType.APPLICATION_JSON))\n                  .build()).getHostAdministrationApi(\"az-1.region-a.geo-1\").get();\n      assertTrue(api.enable(\"ubuntu\"));\n   }\n\n   public void testEnableHostFailNotEnabled() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-hosts/ubuntu\");\n      HostAdministrationApi api = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            HttpRequest.builder().method(\"PUT\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"X-Auth-Token\", authToken)\n                  .payload(payloadFromStringWithContentType(\"{\\\"status\\\":\\\"enable\\\"}\", MediaType.APPLICATION_JSON))\n                  .endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200)\n                  .payload(payloadFromStringWithContentType(\"{\\\"host\\\":\\\"ubuntu\\\",\\\"status\\\":\\\"disabled\\\"}\", MediaType.APPLICATION_JSON))\n                  .build()).getHostAdministrationApi(\"az-1.region-a.geo-1\").get();\n      assertFalse(api.enable(\"ubuntu\"));\n   }\n\n   public void testDisableHost() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-hosts/ubuntu\");\n      HostAdministrationApi api = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            HttpRequest.builder().method(\"PUT\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"X-Auth-Token\", authToken)\n                  .payload(payloadFromStringWithContentType(\"{\\\"status\\\":\\\"disable\\\"}\", MediaType.APPLICATION_JSON))\n                  .endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200)\n                  .payload(payloadFromStringWithContentType(\"{\\\"host\\\":\\\"ubuntu\\\",\\\"status\\\":\\\"disabled\\\"}\", MediaType.APPLICATION_JSON))\n                  .build()).getHostAdministrationApi(\"az-1.region-a.geo-1\").get();\n      assertTrue(api.disable(\"ubuntu\"));\n   }\n\n   public void testStartMaintenance() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-hosts/ubuntu\");\n      HostAdministrationApi api = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            HttpRequest.builder().method(\"PUT\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"X-Auth-Token\", authToken)\n                  .payload(payloadFromStringWithContentType(\"{\\\"maintenance_mode\\\":\\\"enable\\\"}\", MediaType.APPLICATION_JSON))\n                  .endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200)\n                  .payload(payloadFromStringWithContentType(\"{\\\"host\\\":\\\"ubuntu\\\",\\\"maintenance_mode\\\":\\\"on_maintenance\\\"}\", MediaType.APPLICATION_JSON))\n                  .build()).getHostAdministrationApi(\"az-1.region-a.geo-1\").get();\n      assertTrue(api.startMaintenance(\"ubuntu\"));\n   }\n\n   public void testStopMaintenance() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-hosts/ubuntu\");\n      HostAdministrationApi api = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            HttpRequest.builder().method(\"PUT\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"X-Auth-Token\", authToken)\n                  .payload(payloadFromStringWithContentType(\"{\\\"maintenance_mode\\\":\\\"disable\\\"}\", MediaType.APPLICATION_JSON))\n                  .endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200)\n                  .payload(payloadFromStringWithContentType(\"{\\\"host\\\":\\\"ubuntu\\\",\\\"maintenance_mode\\\":\\\"off_maintenance\\\"}\", MediaType.APPLICATION_JSON))\n                  .build()).getHostAdministrationApi(\"az-1.region-a.geo-1\").get();\n      assertTrue(api.stopMaintenance(\"ubuntu\"));\n   }\n\n   public void testStartupHost() {\n      HostAdministrationApi api = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            HttpRequest.builder().method(\"GET\")\n                        .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-hosts/ubuntu/startup\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"X-Auth-Token\", authToken).build(),\n            HttpResponse.builder().statusCode(200)\n                  .payload(payloadFromStringWithContentType(\"{\\\"host\\\":\\\"ubuntu\\\",\\\"power_action\\\":\\\"startup\\\"}\", MediaType.APPLICATION_JSON))\n                  .build()).getHostAdministrationApi(\"az-1.region-a.geo-1\").get();\n      assertTrue(api.startup(\"ubuntu\"));\n   }\n\n   public void testStartupHostFailWrongActionInProgress() {\n      HostAdministrationApi api = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            HttpRequest.builder().method(\"GET\")\n                       .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-hosts/ubuntu/startup\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"X-Auth-Token\", authToken).build(),\n            HttpResponse.builder().statusCode(200)\n                  .payload(payloadFromStringWithContentType(\"{\\\"host\\\":\\\"ubuntu\\\",\\\"power_action\\\":\\\"shutdown\\\"}\", MediaType.APPLICATION_JSON))\n                  .build()).getHostAdministrationApi(\"az-1.region-a.geo-1\").get();\n      assertFalse(api.startup(\"ubuntu\"));\n   }\n\n   public void testShutdownHost() {\n      HostAdministrationApi api = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            HttpRequest.builder().method(\"GET\")\n                       .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-hosts/ubuntu/shutdown\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"X-Auth-Token\", authToken).build(),\n            HttpResponse.builder().statusCode(200)\n                  .payload(payloadFromStringWithContentType(\"{\\\"host\\\":\\\"ubuntu\\\",\\\"power_action\\\":\\\"shutdown\\\"}\", MediaType.APPLICATION_JSON))\n                  .build()).getHostAdministrationApi(\"az-1.region-a.geo-1\").get();\n      assertTrue(api.shutdown(\"ubuntu\"));\n   }\n\n   public void testRebootHost() {\n      HostAdministrationApi api = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            HttpRequest.builder().method(\"GET\")\n                       .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-hosts/ubuntu/reboot\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"X-Auth-Token\", authToken).build(),\n            HttpResponse.builder().statusCode(200)\n                  .payload(payloadFromStringWithContentType(\"{\\\"host\\\":\\\"ubuntu\\\",\\\"power_action\\\":\\\"reboot\\\"}\", MediaType.APPLICATION_JSON))\n                  .build()).getHostAdministrationApi(\"az-1.region-a.geo-1\").get();\n      assertTrue(api.reboot(\"ubuntu\"));\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/HostAdministrationApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\n\nimport org.jclouds.openstack.nova.v2_0.domain.Host;\nimport org.jclouds.openstack.nova.v2_0.domain.HostResourceUsage;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiLiveTest;\nimport org.testng.annotations.BeforeGroups;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Iterables;\n\n/**\n * Tests behavior of HostAdministrationApi\n */\n@Test(groups = \"live\", testName = \"HostAdministrationApiLiveTest\", singleThreaded = true)\npublic class HostAdministrationApiLiveTest extends BaseNovaApiLiveTest {\n   private Optional<? extends HostAdministrationApi> optApi = Optional.absent();\n\n   Predicate<Host> isComputeHost = new Predicate<Host>() {\n      @Override\n      public boolean apply(Host input) {\n         return Objects.equal(\"compute\", input.getService());\n      }\n   };\n\n   @BeforeGroups(groups = {\"integration\", \"live\"})\n   @Override\n   public void setup() {\n      super.setup();\n\n      if (identity.endsWith(\":admin\")) {\n         String region = Iterables.getLast(api.getConfiguredRegions(), \"nova\");\n         optApi = api.getHostAdministrationApi(region);\n      }\n   }\n\n   public void testListAndGet() throws Exception {\n      if (optApi.isPresent()) {\n         HostAdministrationApi api = optApi.get();\n         Set<? extends Host> hosts = api.list().toSet();\n         assertNotNull(hosts);\n         for (Host host : hosts) {\n            for (HostResourceUsage usage : api.listResourceUsage(host.getName())) {\n               assertEquals(usage.getHost(), host.getName());\n               assertNotNull(usage);\n            }\n         }\n      }\n   }\n\n   @Test(enabled = false)\n   public void testEnableDisable() throws Exception {\n      if (optApi.isPresent()) {\n         HostAdministrationApi api = optApi.get();\n         Host host = Iterables.find(api.list(), isComputeHost);\n\n         assertTrue(api.disable(host.getName()));\n         assertTrue(api.enable(host.getName()));\n      }\n   }\n\n   @Test(enabled = false)\n   public void testMaintenanceMode() throws Exception {\n      if (optApi.isPresent()) {\n         HostAdministrationApi api = optApi.get();\n         Host host = Iterables.find(api.list(), isComputeHost);\n         assertTrue(api.startMaintenance(host.getName()));\n         assertTrue(api.stopMaintenance(host.getName()));\n      }\n   }\n\n   @Test(enabled = false)\n   public void testReboot() throws Exception {\n      if (optApi.isPresent()) {\n         HostAdministrationApi api = optApi.get();\n         Host host = Iterables.find(api.list(), isComputeHost);\n         assertTrue(api.reboot(host.getName()));\n      }\n   }\n\n   @Test(enabled = false)\n   public void testShutdownAndStartup() throws Exception {\n      if (optApi.isPresent()) {\n         HostAdministrationApi api = optApi.get();\n         Host host = Iterables.find(api.list(), isComputeHost);\n         assertTrue(api.shutdown(host.getName()));\n         assertTrue(api.startup(host.getName()));\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/HostAggregateApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.nova.v2_0.domain.HostAggregate;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiExpectTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\n\n/**\n * Tests HostAggregateApi guice wiring and parsing\n */\n@Test(groups = \"unit\", testName = \"HostAggregateApiExpectTest\")\npublic class HostAggregateApiExpectTest extends BaseNovaApiExpectTest {\n   private DateService dateService = new SimpleDateFormatDateService();\n\n   public void testList() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-aggregates\");\n      HostAggregateApi api = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/host_aggregate_list.json\")).build())\n            .getHostAggregateApi(\"az-1.region-a.geo-1\").get();\n\n      HostAggregate result = Iterables.getOnlyElement(api.list());\n      assertEquals(result, exampleHostAggregate());\n   }\n\n   public void testGet() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-aggregates/1\");\n      HostAggregateApi api = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/host_aggregate_with_host_details.json\")).build())\n            .getHostAggregateApi(\"az-1.region-a.geo-1\").get();\n\n      assertEquals(api.get(\"1\"), exampleHostAggregateWithHost());\n   }\n\n   public void testCreateAggregate() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-aggregates\");\n      HostAggregateApi api = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            authenticatedGET().endpoint(endpoint).method(\"POST\")\n                  .payload(payloadFromStringWithContentType(\"{\\\"aggregate\\\":{\\\"name\\\":\\\"ubuntu1\\\",\\\"availability_zone\\\":\\\"nova\\\"}}\", MediaType.APPLICATION_JSON))\n                  .endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/host_aggregate_details.json\")).build())\n            .getHostAggregateApi(\"az-1.region-a.geo-1\").get();\n\n      assertEquals(api.createInAvailabilityZone(\"ubuntu1\", \"nova\"), exampleHostAggregate());\n   }\n\n   public void testDeleteAggregate() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-aggregates/1\");\n      HostAggregateApi api = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            authenticatedGET().endpoint(endpoint).method(\"DELETE\").build(),\n            HttpResponse.builder().statusCode(200).build()).getHostAggregateApi(\"az-1.region-a.geo-1\").get();\n\n      assertTrue(api.delete(\"1\"));\n   }\n\n   public void testUpdateName() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-aggregates/1\");\n      HostAggregateApi api = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            authenticatedGET().endpoint(endpoint).method(\"POST\")\n                  .payload(payloadFromStringWithContentType(\"{\\\"aggregate\\\":{\\\"name\\\":\\\"newaggregatename\\\"}}\", MediaType.APPLICATION_JSON)).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/host_aggregate_details.json\")).build()).getHostAggregateApi(\"az-1.region-a.geo-1\").get();\n\n      assertEquals(api.updateName(\"1\", \"newaggregatename\"), exampleHostAggregate());\n   }\n\n   public void testUpdateAvailabilityZone() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-aggregates/1\");\n      HostAggregateApi api = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            authenticatedGET().endpoint(endpoint).method(\"POST\")\n                  .payload(payloadFromStringWithContentType(\"{\\\"aggregate\\\":{\\\"availability_zone\\\":\\\"zone1\\\"}}\", MediaType.APPLICATION_JSON)).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/host_aggregate_details.json\")).build()).getHostAggregateApi(\"az-1.region-a.geo-1\").get();\n\n      assertEquals(api.updateAvailabilityZone(\"1\", \"zone1\"), exampleHostAggregate());\n   }\n\n   public void testAddHost() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-aggregates/1/action\");\n      HostAggregateApi api = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            authenticatedGET().endpoint(endpoint).method(\"POST\")\n                  .payload(payloadFromStringWithContentType(\"{\\\"add_host\\\":{\\\"host\\\":\\\"ubuntu\\\"}}\", MediaType.APPLICATION_JSON)).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/host_aggregate_details.json\")).build()).getHostAggregateApi(\"az-1.region-a.geo-1\").get();\n\n      assertEquals(api.addHost(\"1\", \"ubuntu\"), exampleHostAggregate());\n   }\n\n   public void testRemoveHost() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-aggregates/1/action\");\n      HostAggregateApi api = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            authenticatedGET().endpoint(endpoint).method(\"POST\")\n                  .payload(payloadFromStringWithContentType(\"{\\\"remove_host\\\":{\\\"host\\\":\\\"ubuntu\\\"}}\", MediaType.APPLICATION_JSON)).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/host_aggregate_details.json\")).build()).getHostAggregateApi(\"az-1.region-a.geo-1\").get();\n\n      assertEquals(api.removeHost(\"1\", \"ubuntu\"), exampleHostAggregate());\n   }\n\n\n   public void testSetMetadata() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-aggregates/1/action\");\n      HostAggregateApi api = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            authenticatedGET().endpoint(endpoint).method(\"POST\")\n                  .payload(payloadFromStringWithContentType(\"{\\\"set_metadata\\\":{\\\"metadata\\\":{\\\"mykey\\\":\\\"some value or other\\\"}}}\", MediaType.APPLICATION_JSON)).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/host_aggregate_details.json\")).build()).getHostAggregateApi(\"az-1.region-a.geo-1\").get();\n\n      assertEquals(api.setMetadata(\"1\", ImmutableMap.of(\"mykey\", \"some value or other\")), exampleHostAggregate());\n   }\n\n   public HostAggregate exampleHostAggregate() {\n      return HostAggregate.builder().name(\"jclouds-test-a\").availabilityZone(\"nova\")\n            .created(dateService.iso8601SecondsDateParse(\"2012-05-11 11:40:17\"))\n            .updated(dateService.iso8601SecondsDateParse(\"2012-05-11 11:46:44\"))\n            .state(\"created\").id(\"1\").metadata(ImmutableMap.of(\"somekey\", \"somevalue\", \"anotherkey\", \"another val\")).build();\n   }\n\n   public HostAggregate exampleHostAggregateWithHost() {\n      return exampleHostAggregate().toBuilder().hosts(\"ubuntu\").build();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/HostAggregateApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.openstack.nova.v2_0.domain.Host;\nimport org.jclouds.openstack.nova.v2_0.domain.HostAggregate;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiLiveTest;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\n\n/**\n * Tests behavior of AggregateApi\n */\n@Test(groups = \"live\", testName = \"AggregateApiLiveTest\", singleThreaded = true)\npublic class HostAggregateApiLiveTest extends BaseNovaApiLiveTest {\n   private Optional<? extends HostAggregateApi> apiOption;\n   private Optional<? extends HostAdministrationApi> hostAdminOption;\n\n   private HostAggregate testAggregate;\n\n   @BeforeClass(groups = {\"integration\", \"live\"})\n   @Override\n   public void setup() {\n      super.setup();\n      String region = Iterables.getLast(api.getConfiguredRegions(), \"nova\");\n      apiOption = api.getHostAggregateApi(region);\n      hostAdminOption = api.getHostAdministrationApi(region);\n   }\n\n   @AfterClass(groups = { \"integration\", \"live\" })\n   @Override\n   protected void tearDown() {\n      if (testAggregate != null) {\n         assertTrue(apiOption.get().delete(testAggregate.getId()));\n      }\n      super.tearDown();\n   }\n\n   public void testCreateAggregate() {\n      if (apiOption.isPresent()) {\n         // TODO assuming \"nova\" availability zone is present\n         testAggregate = apiOption.get().createInAvailabilityZone(\"jclouds-test-a\", \"nova\");\n      }\n   }\n\n   @Test(dependsOnMethods = \"testCreateAggregate\")\n   public void testListAndGetAggregate() {\n      if (apiOption.isPresent()) {\n         HostAggregateApi api = apiOption.get();\n         Set<? extends HostAggregate> aggregates = api.list().toSet();\n         for (HostAggregate aggregate : aggregates) {\n            assertNotNull(aggregate.getId());\n            assertNotNull(aggregate.getName());\n            assertNotNull(aggregate.getAvailabilityZone());\n\n            HostAggregate details = api.get(aggregate.getId());\n            assertEquals(details.getId(), aggregate.getId());\n            assertEquals(details.getName(), aggregate.getName());\n            assertEquals(details.getAvailabilityZone(), aggregate.getAvailabilityZone());\n            assertEquals(details.getHosts(), aggregate.getHosts());\n         }\n      }\n   }\n\n   @Test(dependsOnMethods = \"testCreateAggregate\")\n   public void testModifyMetadata() {\n      if (apiOption.isPresent()) {\n         HostAggregateApi api = apiOption.get();\n         for (Map<String, String> theMetaData : ImmutableSet.of(\n               ImmutableMap.of(\"somekey\", \"somevalue\"),\n               ImmutableMap.of(\"somekey\", \"some other value\", \"anotherkey\", \"another val\")\n         )) {\n            // Apply changes\n            HostAggregate details = api.setMetadata(testAggregate.getId(), theMetaData);\n\n            //  bug in openstack - metadata values are never removed, so we just checking what we've set\n            for (Map.Entry<String, String> entry : theMetaData.entrySet()) {\n               assertEquals(details.getMetadata().get(entry.getKey()), entry.getValue());\n            }\n\n            // Re-fetch to double-check\n            details = api.get(testAggregate.getId());\n            for (Map.Entry<String, String> entry : theMetaData.entrySet()) {\n               assertEquals(details.getMetadata().get(entry.getKey()), entry.getValue());\n            }\n         }\n      }\n   }\n\n   // Note the host will be added, but cannot remove it til\n   @Test(enabled = false, dependsOnMethods = \"testCreateAggregate\")\n   public void testModifyHosts() {\n      if (apiOption.isPresent() && hostAdminOption.isPresent()) {\n         HostAggregateApi api = apiOption.get();\n         Host host = Iterables.getFirst(hostAdminOption.get().list(), null);\n         assertNotNull(host);\n\n         String host_id = host.getName();\n         assertNotNull(host_id);\n         HostAggregate details;\n\n         try {\n            details = api.addHost(testAggregate.getId(), host_id);\n\n            assertEquals(details.getHosts(), ImmutableSet.of(host_id));\n\n            // re-fetch to double-check\n            details = api.get(testAggregate.getId());\n            assertEquals(details.getHosts(), ImmutableSet.of(host_id));\n\n            // TODO wait until status of aggregate isn't CHANGING (hostAdministration.shutdown?)\n         } finally {\n            details = api.removeHost(testAggregate.getId(), host_id);\n         }\n\n         assertEquals(details.getHosts(), ImmutableSet.of());\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/HypervisorApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport com.google.common.base.Optional;\nimport com.google.common.collect.FluentIterable;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.Hypervisor;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.HypervisorDetails;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiLiveTest;\nimport org.testng.annotations.Test;\n\nimport static org.testng.Assert.assertNotNull;\n\n@Test(groups = \"live\", testName = \"HypervisorApiLiveTest\")\npublic class HypervisorApiLiveTest extends BaseNovaApiLiveTest {\n\n   @Test\n   public void testList() throws Exception {\n\n      Optional<? extends HypervisorApi> hypervisorApi = api.getHypervisorApi(\"RegionOne\");\n      if (hypervisorApi.isPresent()) {\n         FluentIterable<? extends Hypervisor> hypervisors = hypervisorApi.get().list();\n\n         for (Hypervisor hypervisor : hypervisors) {\n            assertNotNull(hypervisor.getName());\n            assertNotNull(hypervisor.getId(), \"hypervisor: \" + hypervisor.getName() + \" has invalid id\");\n         }\n      }\n   }\n\n   @Test\n   public void testListInDetail() throws Exception {\n\n      Optional<? extends HypervisorApi> hypervisorApi = api.getHypervisorApi(\"RegionOne\");\n      if (hypervisorApi.isPresent()) {\n         FluentIterable<? extends HypervisorDetails> hypervisors = hypervisorApi.get().listInDetail();\n\n         for (HypervisorDetails hypervisorDetails : hypervisors) {\n            assertNotNull(hypervisorDetails.getId(), \"Expected hypervisor id\");\n            assertNotNull(hypervisorDetails.getName(), \"Expected hypervisor name\");\n            assertNotNull(hypervisorDetails.getCurrentWorkload(), \"Expected CurrentWorkload\");\n            assertNotNull(hypervisorDetails.getDiskAvailableLeast(), \"Expected Disk Available Least\");\n            assertNotNull(hypervisorDetails.getFreeDiskGb(), \"Expected Free Disk Gb\");\n            assertNotNull(hypervisorDetails.getFreeRamMb(), \"Expected Free Ram Mb\");\n            assertNotNull(hypervisorDetails.getHypervisorType(), \"Expected Hypervisor Type\");\n            assertNotNull(hypervisorDetails.getHypervisorVersion(), \"Expected Hypervisor Version\");\n            assertNotNull(hypervisorDetails.getLocalGb(), \"Expected Local Gb\");\n            assertNotNull(hypervisorDetails.getLocalGbUsed(), \"Expected Local Gb Used\");\n            assertNotNull(hypervisorDetails.getMemoryMb(), \"Expected Memory Mb \");\n            assertNotNull(hypervisorDetails.getMemoryMbUsed(), \"Expected Memory Mb Used\");\n            assertNotNull(hypervisorDetails.getRunningVms(), \"Expected Running Vms\");\n            assertNotNull(hypervisorDetails.getVcpus(), \"Expected Vcpus\");\n            assertNotNull(hypervisorDetails.getVcpusUsed(), \"Expected Vcpus Used\");\n            assertNotNull(hypervisorDetails.getCpuInfo(), \"Eexpected Cpu Info\");\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/HypervisorApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport com.google.common.base.Optional;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableSet;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\n\nimport org.jclouds.openstack.nova.v2_0.NovaApi;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.Hypervisor;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.HypervisorDetails;\nimport org.jclouds.openstack.v2_0.internal.BaseOpenStackMockTest;\nimport org.testng.annotations.AfterMethod;\nimport org.testng.annotations.BeforeMethod;\nimport org.testng.annotations.Test;\n\nimport java.io.IOException;\nimport java.lang.reflect.Method;\nimport java.util.Map;\nimport java.util.concurrent.ConcurrentHashMap;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\n@Test(groups = \"unit\", testName = \"HypervisorApiMockTest\")\npublic class HypervisorApiMockTest extends BaseOpenStackMockTest<NovaApi> {\n\n   private static Map<String, MockWebServer> servers = new ConcurrentHashMap<String, MockWebServer>();\n\n   @BeforeMethod\n   public void setupMockServer(Method method) throws IOException {\n      servers.put(method.getName(), mockOpenStackServer());\n      servers.get(method.getName()).enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n   }\n\n   @AfterMethod\n   public void tearDownMockServer(Method method) throws IOException {\n      servers.get(method.getName()).shutdown();\n   }\n\n   public void testWhenNamespaceInExtensionsListHypervisorPresent(Method method) throws Exception {\n      MockWebServer server = servers.get(method.getName());\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/extension_list_full.json\"))));\n\n      NovaApi novaApi = api(server.url(\"/\").toString(), \"openstack-nova\");\n      assertEquals(novaApi.getConfiguredRegions(), ImmutableSet.of(\"RegionOne\", \"RegionTwo\", \"RegionThree\"));\n\n      Optional<HypervisorApi> hypervisorApi = novaApi.getHypervisorApi(\"RegionOne\");\n\n      assertTrue(hypervisorApi.isPresent());\n\n      assertRequests(server, 2, null);\n   }\n\n   public void testWhenNamespaceNotInExtensionsListHypervisorPresent(Method method) throws Exception {\n      MockWebServer server = servers.get(method.getName());\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/extension_list.json\"))));\n\n      NovaApi novaApi = api(server.url(\"/\").toString(), \"openstack-nova\");\n      assertEquals(novaApi.getConfiguredRegions(), ImmutableSet.of(\"RegionOne\", \"RegionTwo\", \"RegionThree\"));\n\n      Optional<HypervisorApi> hypervisorApi = novaApi.getHypervisorApi(\"RegionOne\");\n\n      assertFalse(hypervisorApi.isPresent());\n\n      assertRequests(server, 2, null);\n   }\n\n   public void testListHypervisor(Method method) throws Exception {\n      MockWebServer server = servers.get(method.getName());\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/extension_list_full.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/hypervisor_list.json\"))));\n\n      NovaApi novaApi = api(server.url(\"/\").toString(), \"openstack-nova\");\n      assertEquals(novaApi.getConfiguredRegions(), ImmutableSet.of(\"RegionOne\", \"RegionTwo\", \"RegionThree\"));\n\n      FluentIterable<? extends Hypervisor> hypervisors = novaApi.getHypervisorApi(\"RegionOne\").get().list();\n\n      Optional<? extends Hypervisor> hypervisor = hypervisors.first();\n\n      assertTrue(hypervisor.isPresent(), \"Couldn't find hypervisor\");\n      assertEquals(hypervisor.get().getId(), \"1\", \"Expected hypervisor id to be 1 but it was: \" + hypervisor.get().getId());\n      assertEquals(hypervisor.get().getName(), \"os-compute1\", \"Expected hypervisor name to be os-compute1 but it was: \" + hypervisor.get().getName());\n\n      assertRequests(server, 3, \"/os-hypervisors\");\n   }\n\n   public void testListInDetail(Method method) throws Exception {\n      MockWebServer server = servers.get(method.getName());\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/extension_list_full.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/hypervisor_details.json\"))));\n\n      NovaApi novaApi = api(server.url(\"/\").toString(), \"openstack-nova\");\n      assertEquals(novaApi.getConfiguredRegions(), ImmutableSet.of(\"RegionOne\", \"RegionTwo\", \"RegionThree\"));\n\n      FluentIterable<? extends HypervisorDetails> hypervisors = novaApi.getHypervisorApi(\"RegionOne\").get().listInDetail();\n\n      Optional<? extends HypervisorDetails> hypervisorDetailsOptional = hypervisors.first();\n\n      assertTrue(hypervisorDetailsOptional.isPresent(), \"Couldn't find Hypervisor Details\");\n      HypervisorDetails hypervisorDetails = hypervisorDetailsOptional.get();\n      assertEquals(hypervisorDetails.getId(), \"1\", \"Expected hypervisor id to be 1 but it was: \" + hypervisorDetails.getId());\n      assertEquals(hypervisorDetails.getName(), \"os-compute1\",\n            \"Expected hypervisor name to be os-compute1 but it was: \" + hypervisorDetails.getName());\n      assertEquals(hypervisorDetails.getCurrentWorkload(), Integer.valueOf(0),\n            \"Expected CurrentWorkload to be 0 but it was: \" + hypervisorDetails.getCurrentWorkload());\n      assertEquals(hypervisorDetails.getDiskAvailableLeast(), Integer.valueOf(131),\n            \"Expected Disk Available Least to be 131 but it was: \" + hypervisorDetails.getDiskAvailableLeast());\n      assertEquals(hypervisorDetails.getFreeDiskGb(), Integer.valueOf(144),\n            \"Expected Free Disk Gb to be 144 but it was: \" + hypervisorDetails.getFreeDiskGb());\n      assertEquals(hypervisorDetails.getFreeRamMb(), Integer.valueOf(12911),\n            \"Expected Free Ram Mb to be 12911 but it was: \" + hypervisorDetails.getFreeRamMb());\n      assertEquals(hypervisorDetails.getHypervisorType(), \"QEMU\",\n            \"Expected Hypervisor Type to be QEMU but it was: \" + hypervisorDetails.getHypervisorType());\n      assertEquals(hypervisorDetails.getHypervisorVersion(), 2000000,\n            \"Expected Hypervisor Version to be 2000000 but it was: \" + hypervisorDetails.getHypervisorVersion());\n      assertEquals(hypervisorDetails.getLocalGb(), 195, \"Expected Local Gb to be 195 but it was: \" + hypervisorDetails.getLocalGb());\n      assertEquals(hypervisorDetails.getLocalGbUsed(), 51, \"Expected Local Gb Used to be 51 but it was: \" + hypervisorDetails.getLocalGbUsed());\n      assertEquals(hypervisorDetails.getMemoryMb(), 20079, \"Expected Memory Mb to be 20079 but it was: \" + hypervisorDetails.getMemoryMb());\n      assertEquals(hypervisorDetails.getMemoryMbUsed(), 7168,\n            \"Expected Memory Mb Used to be 7168 but it was: \" + hypervisorDetails.getMemoryMbUsed());\n      assertEquals(hypervisorDetails.getRunningVms(), Integer.valueOf(2),\n            \"Expected Running Vms to be 2 but it was: \" + hypervisorDetails.getRunningVms());\n      assertEquals(hypervisorDetails.getVcpus(), 16, \"Expected Vcpus to be 16 but it was: \" + hypervisorDetails.getVcpus());\n      assertEquals(hypervisorDetails.getVcpusUsed(), 5, \"Expected Vcpus Used to be 5 but it was: \" + hypervisorDetails.getVcpusUsed());\n      assertEquals(hypervisorDetails.getCpuInfo(),\n            \"{\\\"vendor\\\": \\\"Intel\\\", \\\"model\\\": \\\"Westmere\\\", \\\"arch\\\": \\\"x86_64\\\", \\\"features\\\": [\\\"pge\\\", \\\"avx\\\", \\\"clflush\\\", \\\"sep\\\", \"\n                  + \"\\\"syscall\\\", \\\"vme\\\", \\\"tsc\\\", \\\"xsave\\\", \\\"vmx\\\", \\\"cmov\\\", \\\"ssse3\\\", \\\"pat\\\", \\\"lm\\\", \\\"msr\\\", \\\"nx\\\", \\\"fxsr\\\", \\\"sse4.1\\\", \"\n                  + \"\\\"pae\\\", \\\"sse4.2\\\", \\\"pclmuldq\\\", \\\"mmx\\\", \\\"osxsave\\\", \\\"cx8\\\", \\\"mce\\\", \\\"de\\\", \\\"aes\\\", \\\"ht\\\", \\\"pse\\\", \\\"lahf_lm\\\",\"\n                  + \" \\\"popcnt\\\", \\\"mca\\\", \\\"apic\\\", \\\"sse\\\", \\\"ds\\\", \\\"pni\\\", \\\"rdtscp\\\", \\\"sse2\\\", \\\"ss\\\", \\\"hypervisor\\\", \\\"pcid\\\", \\\"fpu\\\",\"\n                  + \" \\\"cx16\\\", \\\"pse36\\\", \\\"mtrr\\\", \\\"x2apic\\\"], \\\"topology\\\": {\\\"cores\\\": 4, \\\"threads\\\": 1, \\\"sockets\\\": 1}}\",\n            \"Unexpected Cpu Info it was: \" + hypervisorDetails.getCpuInfo());\n\n      assertRequests(server, 3, \"/os-hypervisors/detail\");\n   }\n\n   private void assertRequests(MockWebServer server, int requestCount, String requestPath) throws InterruptedException {\n      assertEquals(server.getRequestCount(), requestCount);\n      assertAuthentication(server);\n      assertExtensions(server, \"/v2/da0d12be20394afb851716e10a49e4a7\");\n      if (requestPath != null) {\n         assertRequest(server.takeRequest(), \"GET\", \"/v2/da0d12be20394afb851716e10a49e4a7\" + requestPath);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/KeyPairApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.nova.v2_0.NovaApi;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiExpectTest;\nimport org.jclouds.openstack.nova.v2_0.parse.ParseKeyPairListTest;\nimport org.jclouds.openstack.nova.v2_0.parse.ParseKeyPairTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests annotation parsing of {@code KeyPairApi}\n */\n@Test(groups = \"unit\", testName = \"KeyPairApiExpectTest\")\npublic class KeyPairApiExpectTest extends BaseNovaApiExpectTest {\n\n   public void testListKeyPairsWhenResponseIs2xx() throws Exception {\n      HttpRequest list = HttpRequest\n            .builder()\n            .method(\"GET\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-keypairs\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken).build();\n\n      HttpResponse listResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResource(\"/keypair_list.json\")).build();\n\n      NovaApi apiWhenServersExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, list, listResponse);\n\n      assertEquals(apiWhenServersExist.getConfiguredRegions(), ImmutableSet.of(\"az-1.region-a.geo-1\", \"az-2.region-a.geo-1\", \"az-3.region-a.geo-1\"));\n\n      // NOTE this required a change to the KeyPair domain object toString method\n      assertEquals(apiWhenServersExist.getKeyPairApi(\"az-1.region-a.geo-1\").get().list().toString(),\n            new ParseKeyPairListTest().expected().toString());\n   }\n\n   public void testCreateKeyPair() throws Exception {\n      HttpRequest create = HttpRequest\n            .builder()\n            .method(\"POST\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-keypairs\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken)\n            .payload(payloadFromStringWithContentType(\"{\\\"keypair\\\":{\\\"name\\\":\\\"testkeypair\\\"}}\", \"application/json\"))\n            .build();\n\n      HttpResponse createResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResource(\"/keypair_details.json\")).build();\n\n      NovaApi apiWhenServersExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, create, createResponse);\n\n      assertEquals(apiWhenServersExist.getKeyPairApi(\"az-1.region-a.geo-1\").get().create(\"testkeypair\")\n            .toString(), new ParseKeyPairTest().expected().toString());\n\n   }\n\n   public void testCreateKeyPairWithPublicKey() throws Exception {\n      HttpRequest create = HttpRequest\n            .builder()\n            .method(\"POST\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-keypairs\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken)\n            .payload(\n                  payloadFromStringWithContentType(\n                        \"{\\\"keypair\\\":{\\\"name\\\":\\\"testkeypair\\\",\\\"public_key\\\":\\\"ssh-rsa AAAXB3NzaC1yc2EAAAADAQABAAAAgQDFNyGjgs6c9akgmZ2ou/fJf7Pdrc23hC95/gM/33OrG4GZABACE4DTioa/PGN+7rHv9YUavUCtXrWayhGniKq/wCuI5fo5TO4AmDNv7/sCGHIHFumADSIoLx0vFhGJIetXEWxL9r0lfFC7//6yZM2W3KcGjbMtlPXqBT9K9PzdyQ== nova@nv-aw2az1-api0001\\n\\\"}}\",\n                        \"application/json\")).build();\n\n      HttpResponse createResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResource(\"/keypair_details.json\")).build();\n\n      NovaApi apiWhenServersExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, create, createResponse);\n\n      assertEquals(\n            apiWhenServersExist\n                  .getKeyPairApi(\"az-1.region-a.geo-1\")\n                  .get()\n                  .createWithPublicKey(\n                        \"testkeypair\",\n                        \"ssh-rsa AAAXB3NzaC1yc2EAAAADAQABAAAAgQDFNyGjgs6c9akgmZ2ou/fJf7Pdrc23hC95/gM/33OrG4GZABACE4DTioa/PGN+7rHv9YUavUCtXrWayhGniKq/wCuI5fo5TO4AmDNv7/sCGHIHFumADSIoLx0vFhGJIetXEWxL9r0lfFC7//6yZM2W3KcGjbMtlPXqBT9K9PzdyQ== nova@nv-aw2az1-api0001\\n\")\n                  .toString(), new ParseKeyPairTest().expected().toString());\n   }\n\n   public void testDeleteKeyPair() throws Exception {\n      HttpRequest delete = HttpRequest\n            .builder()\n            .method(\"DELETE\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-keypairs/testkeypair\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken).build();\n\n      HttpResponse deleteResponse = HttpResponse.builder().statusCode(202).build();\n\n      NovaApi apiWhenServersExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, delete, deleteResponse);\n\n      assertTrue(apiWhenServersExist.getKeyPairApi(\"az-1.region-a.geo-1\").get().delete(\"testkeypair\"));\n   }\n\n   public void testGetKeyPairWhenResponseIs2xx() throws Exception {\n      HttpRequest get = HttpRequest\n            .builder()\n            .method(\"GET\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-keypairs/testkeypair\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken).build();\n\n      HttpResponse getResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResource(\"/keypair_details.json\")).build();\n\n      NovaApi apiWhenKeyPairExists = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, get, getResponse);\n\n      assertEquals(apiWhenKeyPairExists.getKeyPairApi(\"az-1.region-a.geo-1\").get().get(\"testkeypair\"),\n            new ParseKeyPairTest().expected());\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/KeyPairApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport org.jclouds.openstack.nova.v2_0.domain.KeyPair;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.FluentIterable;\n\n/**\n * Tests live behavior of {@code KeyPairApi}\n */\n@Test(groups = \"live\", testName = \"KeyPairApiLiveTest\")\npublic class KeyPairApiLiveTest extends BaseNovaApiLiveTest {\n\n   private static final String KEYPAIR_NAME = \"testkp\";\n   private static final String PUBLIC_KEY = \"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQCrrBREFxz3002l1HuXz0+UOdJQ/mOYD5DiJwwB/TOybwIKQJPOxJWA9gBoo4k9dthTKBTaEYbzrll7iZcp59E80S6mNiAr3mUgi+x5Y8uyXeJ2Ws+h6peVyFVUu9epkwpcTd1GVfdcVWsTajwDz9+lxCDhl0RZKDFoT0scTxbj/w== nova@nv-aw2az2-api0002\";\n\n   public void testListKeyPairs() throws Exception {\n      for (String regionId : api.getConfiguredRegions()) {\n         KeyPairApi keyPairApi = api.getKeyPairApi(regionId).get();\n         FluentIterable<? extends KeyPair> keyPairsList = keyPairApi.list();\n         assertNotNull(keyPairsList);\n      }\n   }\n\n   public void testCreateAndGetAndDeleteKeyPair() throws Exception {\n      for (String regionId : api.getConfiguredRegions()) {\n         KeyPairApi keyPairApi = api.getKeyPairApi(regionId).get();\n         KeyPair createdKeyPair = null;\n         try {\n            createdKeyPair = keyPairApi.create(KEYPAIR_NAME);\n            assertNotNull(createdKeyPair);\n\n            KeyPair keyPair = keyPairApi.get(KEYPAIR_NAME);\n            assertEquals(keyPair.getName(), createdKeyPair.getName());\n            assertEquals(keyPair.getFingerprint(), createdKeyPair.getFingerprint());\n            assertEquals(keyPair.getPublicKey(), createdKeyPair.getPublicKey());\n         } finally {\n            if (createdKeyPair != null) {\n               keyPairApi.delete(KEYPAIR_NAME);\n            }\n         }\n      }\n   }\n\n   public void testCreateAndDeleteKeyPairWithPublicKey() throws Exception {\n      for (String regionId : api.getConfiguredRegions()) {\n         KeyPairApi keyPairApi = api.getKeyPairApi(regionId).get();\n         KeyPair createdKeyPair = null;\n         try {\n            createdKeyPair = keyPairApi.createWithPublicKey(KEYPAIR_NAME, PUBLIC_KEY);\n            assertNotNull(createdKeyPair);\n\n            KeyPair keyPair = keyPairApi.get(KEYPAIR_NAME);\n            assertEquals(keyPair.getName(), createdKeyPair.getName());\n            assertEquals(keyPair.getFingerprint(), createdKeyPair.getFingerprint());\n            assertEquals(keyPair.getPublicKey(), createdKeyPair.getPublicKey());\n         } finally {\n            if (createdKeyPair != null) {\n               keyPairApi.delete(KEYPAIR_NAME);\n            }\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/QuotaApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.nova.v2_0.domain.Quota;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiExpectTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests HostAdministrationApi guice wiring and parsing\n */\n@Test(groups = \"unit\", testName = \"QuotaApiExpectTest\")\npublic class QuotaApiExpectTest extends BaseNovaApiExpectTest {\n\n   public void testGetQuotas() throws Exception {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-quota-sets/demo\");\n      QuotaApi api = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/quotas.json\")).build()).getQuotaApi(\"az-1.region-a.geo-1\").get();\n\n      assertEquals(api.getByTenant(\"demo\"), getTestQuotas());\n   }\n\n   public void testGetDefaultQuotas() throws Exception {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-quota-sets/demo/defaults\");\n      QuotaApi api = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/quotas.json\")).build()).getQuotaApi(\"az-1.region-a.geo-1\").get();\n\n      assertEquals(api.getDefaultsForTenant(\"demo\"), getTestQuotas());\n   }\n\n   public void testUpdateQuotas() throws Exception {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-quota-sets/demo\");\n      QuotaApi api = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            HttpRequest.builder().endpoint(endpoint).method(\"PUT\")\n                  .addHeader(\"X-Auth-Token\", authToken)\n                  .addHeader(\"Accept\", \"application/json\")\n                  .payload(payloadFromResourceWithContentType(\"/quotas.json\", MediaType.APPLICATION_JSON))\n                  .build(),\n            HttpResponse.builder().statusCode(200).build()).getQuotaApi(\"az-1.region-a.geo-1\").get();\n\n      assertTrue(api.updateQuotaOfTenant(getTestQuotas(), \"demo\"));\n   }\n\n   public static Quota getTestQuotas() {\n      return Quota.builder()\n            .metadataItems(128)\n            .injectedFileContentBytes(10240)\n            .injectedFiles(5)\n            .gigabytes(1000)\n            .ram(51200)\n            .floatingIps(10)\n            .securityGroups(10)\n            .securityGroupRules(20)\n            .instances(10)\n            .keyPairs(100)\n            .volumes(10)\n            .cores(20)\n            .id(\"demo\").build();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/QuotaApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.openstack.nova.v2_0.domain.Quota;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiLiveTest;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.collect.Iterables;\n\n/**\n * Tests behavior of QuotaApi\n */\n@Test(groups = \"live\", testName = \"QuotaApiLiveTest\", singleThreaded = true)\npublic class QuotaApiLiveTest extends BaseNovaApiLiveTest {\n   private Optional<? extends QuotaApi> apiOption;\n   private String tenant;\n\n   @BeforeClass(groups = {\"integration\", \"live\"})\n   @Override\n   public void setup() {\n      super.setup();\n      tenant = identity.split(\":\")[0];\n      String region = Iterables.getLast(api.getConfiguredRegions(), \"nova\");\n      apiOption = api.getQuotaApi(region);\n   }\n\n   public void testGetQuotasForCurrentTenant() {\n      if (apiOption.isPresent()) {\n         Quota quota = apiOption.get().getByTenant(tenant);\n         assertQuotasIsValid(quota);\n      }\n   }\n\n   public void testGetDefaultQuotasForCurrentTenant() {\n      if (apiOption.isPresent()) {\n         Quota quota = apiOption.get().getDefaultsForTenant(tenant);\n         assertQuotasIsValid(quota);\n      }\n   }\n\n   public void testUpdateQuotasOfCurrentTenantThenReset() {\n      if (apiOption.isPresent()) {\n         QuotaApi api = apiOption.get();\n         Quota before = api.getByTenant(tenant);\n         assertQuotasIsValid(before);\n\n         Quota modified = before.toBuilder()\n               .cores(before.getCores() - 1)\n               .instances(before.getInstances() - 1)\n               .metadataItems(before.getMetadatas() - 1)\n               .ram(before.getRam() - 1)\n               .volumes(before.getVolumes() - 1)\n               .build();\n\n         assertTrue(api.updateQuotaOfTenant(modified, tenant));\n\n         assertEquals(api.getByTenant(tenant), modified);\n\n         assertTrue(api.updateQuotaOfTenant(before, tenant));\n\n         assertEquals(api.getByTenant(tenant), before);\n      }\n   }\n\n   protected void assertQuotasIsValid(Quota quota) {\n      assertTrue(quota.getCores() > 0);\n      assertTrue(quota.getFloatingIps() >= 0);\n      assertTrue(quota.getGigabytes() > 0);\n      assertTrue(quota.getInjectedFileContentBytes() >= 0);\n      assertTrue(quota.getInjectedFiles() >= 0);\n      assertTrue(quota.getInstances() > 0);\n      assertTrue(quota.getKeyPairs() > 0);\n      assertTrue(quota.getRam() > 0);\n      assertTrue(quota.getSecurityGroups() > 0);\n      assertTrue(quota.getSecurityGroupRules() > 0);\n      assertTrue(quota.getVolumes() > 0);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/SecurityGroupApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.net.domain.IpProtocol;\nimport org.jclouds.openstack.nova.v2_0.NovaApi;\nimport org.jclouds.openstack.nova.v2_0.domain.Ingress;\nimport org.jclouds.openstack.nova.v2_0.domain.SecurityGroup;\nimport org.jclouds.openstack.nova.v2_0.domain.SecurityGroupRule;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiExpectTest;\nimport org.jclouds.openstack.nova.v2_0.parse.ParseSecurityGroupListTest;\nimport org.jclouds.openstack.nova.v2_0.parse.ParseSecurityGroupTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests annotation parsing of {@code SecurityGroupApi}\n */\n@Test(groups = \"unit\", testName = \"SecurityGroupApiExpectTest\")\npublic class SecurityGroupApiExpectTest extends BaseNovaApiExpectTest {\n   public void testListSecurityGroupsWhenResponseIs2xx() throws Exception {\n      HttpRequest list = HttpRequest.builder().method(\"GET\").endpoint(\n               URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-security-groups\")).headers(\n               ImmutableMultimap.<String, String> builder().put(\"Accept\", \"application/json\").put(\"X-Auth-Token\",\n                        authToken).build()).build();\n\n      HttpResponse listResponse = HttpResponse.builder().statusCode(200).payload(\n               payloadFromResource(\"/securitygroup_list.json\")).build();\n\n      NovaApi apiWhenSecurityGroupsExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n               responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, list,\n               listResponse);\n\n      assertEquals(apiWhenSecurityGroupsExist.getConfiguredRegions(), ImmutableSet.of(\"az-1.region-a.geo-1\", \"az-2.region-a.geo-1\", \"az-3.region-a.geo-1\"));\n\n      assertEquals(apiWhenSecurityGroupsExist.getSecurityGroupApi(\"az-1.region-a.geo-1\").get()\n               .list().toString(), new ParseSecurityGroupListTest().expected().toString());\n   }\n\n   public void testGetSecurityGroupWhenResponseIs2xx() throws Exception {\n\n      HttpRequest getSecurityGroup = HttpRequest.builder().method(\"GET\").endpoint(\n               URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-security-groups/0\")).headers(\n               ImmutableMultimap.<String, String> builder().put(\"Accept\", \"application/json\").put(\"X-Auth-Token\",\n                        authToken).build()).build();\n\n      HttpResponse getSecurityGroupResponse = HttpResponse.builder().statusCode(200).payload(\n               payloadFromResource(\"/securitygroup_details.json\")).build();\n\n      NovaApi apiWhenSecurityGroupsExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n               responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, getSecurityGroup,\n               getSecurityGroupResponse);\n\n      assertEquals(apiWhenSecurityGroupsExist.getSecurityGroupApi(\"az-1.region-a.geo-1\").get()\n               .get(\"0\").toString(), new ParseSecurityGroupTest().expected().toString());\n   }\n\n   public void testCreateSecurityGroupWhenResponseIs2xx() throws Exception {\n      HttpRequest create = HttpRequest.builder().method(\"POST\").endpoint(\n               URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-security-groups\")).headers(\n               ImmutableMultimap.<String, String> builder().put(\"Accept\", \"application/json\").put(\"X-Auth-Token\",\n                        authToken).build())\n               .payload(\n                        payloadFromStringWithContentType(\n                                 \"{\\\"security_group\\\":{\\\"name\\\":\\\"jclouds-test\\\",\\\"description\\\":\\\"jclouds-test\\\"}}\",\n                                 \"application/json\")).build();\n\n      HttpResponse createResponse = HttpResponse.builder().statusCode(200).payload(\n               payloadFromResource(\"/securitygroup_created.json\")).build();\n\n      NovaApi apiWhenSecurityGroupsExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n               responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, create,\n               createResponse);\n\n      assertEquals(apiWhenSecurityGroupsExist.getSecurityGroupApi(\"az-1.region-a.geo-1\").get()\n               .createWithDescription(\"jclouds-test\", \"jclouds-test\").toString(),\n               createExpected().toString());\n   }\n\n   public void testDeleteSecurityGroupWhenResponseIs2xx() throws Exception {\n      HttpRequest delete = HttpRequest.builder().method(\"DELETE\").endpoint(\n               URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-security-groups/160\"))\n               .headers(\n                        ImmutableMultimap.<String, String> builder().put(\"Accept\", \"application/json\")\n                                 .put(\"X-Auth-Token\", authToken).build()).build();\n\n      HttpResponse deleteResponse = HttpResponse.builder().statusCode(202).build();\n\n      NovaApi apiWhenServersExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n               responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, delete,\n               deleteResponse);\n\n      assertTrue(apiWhenServersExist.getSecurityGroupApi(\"az-1.region-a.geo-1\").get()\n               .delete(\"160\"));\n\n   }\n\n   public void testCreateSecurityGroupRuleForCidrBlockWhenResponseIs2xx() throws Exception {\n      HttpRequest createRule = HttpRequest\n               .builder()\n               .method(\"POST\")\n               .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-security-group-rules\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken)\n               .payload(\n                        payloadFromStringWithContentType(\n                                 \"{\\\"security_group_rule\\\":{\\\"parent_group_id\\\":\\\"161\\\",\\\"cidr\\\":\\\"0.0.0.0/0\\\",\\\"ip_protocol\\\":\\\"tcp\\\",\\\"from_port\\\":\\\"80\\\",\\\"to_port\\\":\\\"8080\\\"}}\",\n                                 \"application/json\")).build();\n\n      HttpResponse createRuleResponse = HttpResponse.builder().statusCode(200).payload(\n               payloadFromResource(\"/securitygrouprule_created.json\")).build();\n\n      NovaApi apiWhenSecurityGroupsExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n               responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, createRule,\n               createRuleResponse);\n\n      assertEquals(apiWhenSecurityGroupsExist.getSecurityGroupApi(\"az-1.region-a.geo-1\").get()\n               .createRuleAllowingCidrBlock(\"161\",\n                        Ingress.builder().ipProtocol(IpProtocol.TCP).fromPort(80).toPort(8080).build(), \"0.0.0.0/0\")\n               .toString(), createRuleExpected().toString());\n   }\n\n   public void testCreateSecurityGroupRuleForSecurityGroupIdWhenResponseIs2xx() throws Exception {\n      HttpRequest createRule = HttpRequest\n               .builder()\n               .method(\"POST\")\n               .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-security-group-rules\")\n               .addHeader(\"Accept\", \"application/json\")\n               .addHeader(\"X-Auth-Token\", authToken)\n               .payload(\n                        payloadFromStringWithContentType(\n                                 \"{\\\"security_group_rule\\\":{\\\"group_id\\\":\\\"999\\\",\\\"parent_group_id\\\":\\\"161\\\",\\\"ip_protocol\\\":\\\"tcp\\\",\\\"from_port\\\":\\\"80\\\",\\\"to_port\\\":\\\"8080\\\"}}\",\n                                 \"application/json\")).build();\n\n      HttpResponse createRuleResponse = HttpResponse.builder().statusCode(200).payload(\n               payloadFromResource(\"/securitygrouprule_created.json\")).build();\n\n      NovaApi apiWhenSecurityGroupsExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n               responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, createRule,\n               createRuleResponse);\n\n      assertEquals(apiWhenSecurityGroupsExist.getSecurityGroupApi(\"az-1.region-a.geo-1\").get()\n               .createRuleAllowingSecurityGroupId(\"161\",\n                        Ingress.builder().ipProtocol(IpProtocol.TCP).fromPort(80).toPort(8080).build(), \"999\")\n               .toString(), createRuleExpected().toString());\n   }\n\n   public void testDeleteSecurityGroupRuleWhenResponseIs2xx() throws Exception {\n      HttpRequest deleteRule = HttpRequest.builder().method(\"DELETE\").endpoint(\n               URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-security-group-rules/161\"))\n               .headers(\n                        ImmutableMultimap.<String, String> builder().put(\"Accept\", \"application/json\")\n                                 .put(\"X-Auth-Token\", authToken).build()).build();\n\n      HttpResponse deleteRuleResponse = HttpResponse.builder().statusCode(202).build();\n\n      NovaApi apiWhenSecurityGroupsExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n               responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, deleteRule,\n               deleteRuleResponse);\n\n      assertTrue(apiWhenSecurityGroupsExist.getSecurityGroupApi(\"az-1.region-a.geo-1\").get()\n               .deleteRule(\"161\"));\n\n   }\n\n   private SecurityGroup createExpected() {\n      return SecurityGroup.builder().description(\"jclouds-test\").id(\"160\").name(\"jclouds-test\").rules(\n               ImmutableSet.<SecurityGroupRule> of()).tenantId(\"dev_16767499955063\").build();\n   }\n\n   private SecurityGroupRule createRuleExpected() {\n      return SecurityGroupRule.builder().fromPort(80).id(\"218\").ipProtocol(\n               IpProtocol.TCP).ipRange(\"0.0.0.0/0\").parentGroupId(\"161\").toPort(8080).build();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/SecurityGroupApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.Set;\n\nimport org.jclouds.net.domain.IpProtocol;\nimport org.jclouds.openstack.nova.v2_0.domain.Ingress;\nimport org.jclouds.openstack.nova.v2_0.domain.SecurityGroup;\nimport org.jclouds.openstack.nova.v2_0.domain.SecurityGroupRule;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code SecurityGroupApi}\n */\n@Test(groups = \"live\", testName = \"SecurityGroupApiLiveTest\", singleThreaded = true)\npublic class SecurityGroupApiLiveTest extends BaseNovaApiLiveTest {\n\n   public static final String SECURITY_GROUP_NAME = \"testsg\";\n\n   public void list() throws Exception {\n      for (String regionId : api.getConfiguredRegions()) {\n         SecurityGroupApi securityGroupApi = api.getSecurityGroupApi(regionId).get();\n         Set<? extends SecurityGroup> securityGroupsList = securityGroupApi.list().toSet();\n         assertNotNull(securityGroupsList);\n      }\n   }\n\n   public void createGetAndDeleteSecurityGroup() throws Exception {\n      for (String regionId : api.getConfiguredRegions()) {\n         SecurityGroupApi securityGroupApi = api.getSecurityGroupApi(regionId).get();\n         SecurityGroup securityGroup = null;\n         String id;\n         try {\n            securityGroup = securityGroupApi\n                     .createWithDescription(SECURITY_GROUP_NAME, \"test security group\");\n            assertNotNull(securityGroup);\n            id = securityGroup.getId();\n            SecurityGroup theGroup = securityGroupApi.get(id);\n            assertNotNull(theGroup);\n         } finally {\n            if (securityGroup != null) {\n               securityGroupApi.delete(securityGroup.getId());\n            }\n         }\n      }\n   }\n\n   public void createAndDeleteSecurityGroupRule() throws Exception {\n      for (String regionId : api.getConfiguredRegions()) {\n         SecurityGroupApi securityGroupApi = api.getSecurityGroupApi(regionId).get();\n         SecurityGroup securityGroup = null;\n\n         try {\n            securityGroup = securityGroupApi.createWithDescription(SECURITY_GROUP_NAME, \"test security group\");\n            assertNotNull(securityGroup);\n\n            for (int port : ImmutableSet.of(22, 8080)) {\n               SecurityGroupRule rule = securityGroupApi.createRuleAllowingCidrBlock(securityGroup.getId(), Ingress\n                        .builder().ipProtocol(IpProtocol.TCP).fromPort(port).toPort(port).build(), \"0.0.0.0/0\");\n               assertNotNull(rule);\n\n               SecurityGroupRule rule2 = securityGroupApi.createRuleAllowingSecurityGroupId(securityGroup.getId(),\n                        Ingress.builder().ipProtocol(IpProtocol.TCP).fromPort(port).toPort(port).build(), securityGroup\n                                 .getId());\n\n               assertNotNull(rule2);\n            }\n            securityGroup = securityGroupApi.get(securityGroup.getId());\n\n         } finally {\n            if (securityGroup != null) {\n               securityGroupApi.delete(securityGroup.getId());\n            }\n         }\n      }\n\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/ServerWithSecurityGroupsApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.nova.v2_0.domain.ServerWithSecurityGroups;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiExpectTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests parsing and guice wiring of ServerWithSecurityGroupsApi\n */\n@Test(groups = \"unit\", testName = \"ServerWithSecurityGroupsApiExpectTest\")\npublic class ServerWithSecurityGroupsApiExpectTest extends BaseNovaApiExpectTest {\n\n   public void testGetServerWithSecurityGroups() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-create-server-ext/8d0a6ca5-8849-4b3d-b86e-f24c92490ebb\");\n      ServerWithSecurityGroupsApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/server_with_security_groups.json\")).build()\n      ).getServerWithSecurityGroupsApi(\"az-1.region-a.geo-1\").get();\n\n      ServerWithSecurityGroups server = api.get(\"8d0a6ca5-8849-4b3d-b86e-f24c92490ebb\");\n      assertEquals(server.getId(), \"8d0a6ca5-8849-4b3d-b86e-f24c92490ebb\");\n      assertEquals(server.getSecurityGroupNames(), ImmutableSet.of(\"default\", \"group1\"));\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/ServerWithSecurityGroupsApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport org.jclouds.openstack.nova.v2_0.domain.Server;\nimport org.jclouds.openstack.nova.v2_0.domain.ServerWithSecurityGroups;\nimport org.jclouds.openstack.nova.v2_0.features.ServerApi;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiLiveTest;\nimport org.jclouds.openstack.v2_0.domain.Resource;\nimport org.testng.annotations.BeforeGroups;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\n\n/**\n * Tests behavior of ServerWithSecurityGroupsApi\n */\n@Test(groups = \"live\", testName = \"ServerWithSecurityGroupsApiLiveTest\", singleThreaded = true)\npublic class ServerWithSecurityGroupsApiLiveTest extends BaseNovaApiLiveTest {\n   private ServerApi serverApi;\n   private Optional<? extends ServerWithSecurityGroupsApi> apiOption;\n   private String region;\n\n   @BeforeGroups(groups = {\"integration\", \"live\"})\n   @Override\n   public void setup() {\n      super.setup();\n      region = Iterables.getLast(api.getConfiguredRegions(), \"nova\");\n      serverApi = api.getServerApi(region);\n      apiOption = api.getServerWithSecurityGroupsApi(region);\n   }\n\n   public void testGetServer() {\n      if (apiOption.isPresent()) {\n\n         for (Resource server : serverApi.list().concat()) {\n            ServerWithSecurityGroups serverWithGroups = apiOption.get().get(server.getId());\n            assertEquals(serverWithGroups.getId(), server.getId());\n            assertEquals(serverWithGroups.getName(), server.getName());\n            assertNotNull(serverWithGroups.getSecurityGroupNames());\n         }\n\n         // Create a new server to verify the groups work as expected\n         Server testServer = null;\n         try {\n            testServer = createServerInRegion(region);\n\n            ServerWithSecurityGroups results = apiOption.get().get(testServer.getId());\n            assertEquals(results.getId(), testServer.getId());\n            assertEquals(results.getSecurityGroupNames(), ImmutableSet.of(\"default\"));\n         } finally {\n            if (testServer != null) {\n               serverApi.delete(testServer.getId());\n            }\n         }\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/SimpleTenantUsageApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.Set;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.nova.v2_0.domain.SimpleServerUsage;\nimport org.jclouds.openstack.nova.v2_0.domain.SimpleTenantUsage;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiExpectTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\n\n/**\n * Tests SimpleTenantUsageApi guice wiring and parsing\n */\n@Test(groups = \"unit\", testName = \"SimpleTenantUsageApiExpectTest\")\npublic class SimpleTenantUsageApiExpectTest extends BaseNovaApiExpectTest {\n   private DateService dateService = new SimpleDateFormatDateService();\n\n   public void testList() throws Exception {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-simple-tenant-usage\");\n      SimpleTenantUsageApi api = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            HttpRequest.builder().method(\"GET\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"X-Auth-Token\", authToken)\n            .endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200)\n                  .payload(payloadFromResource(\"/simple_tenant_usages.json\")).build())\n            .getSimpleTenantUsageApi(\"az-1.region-a.geo-1\").get();\n\n      Set<? extends SimpleTenantUsage> results = api.list().toSet();\n\n      SimpleTenantUsage usage = Iterables.getOnlyElement(results);\n      assertEquals(usage.getTenantId(), \"f8535069c3fb404cb61c873b1a0b4921\");\n      assertEquals(usage.getTotalHours(), 4.888888888888889e-07);\n      assertEquals(usage.getTotalLocalGbUsage(), 1.9555555555555557e-05);\n      assertEquals(usage.getTotalMemoryMbUsage(), 0.0015018666666666667);\n      assertEquals(usage.getTotalVcpusUsage(), 7.333333333333333e-07);\n      assertEquals(usage.getStart(), dateService.iso8601DateParse(\"2012-04-18 12:18:39.702411\"));\n      assertEquals(usage.getStop(), dateService.iso8601DateParse(\"2012-04-18 12:18:39.702499\"));\n      assertNotNull(usage.getServerUsages());\n      assertTrue(usage.getServerUsages().isEmpty());\n   }\n\n   public void testGet() throws Exception {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-simple-tenant-usage/test-1234\");\n      SimpleTenantUsageApi api = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            HttpRequest.builder().method(\"GET\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"X-Auth-Token\", authToken)\n                  .endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200)\n                  .payload(payloadFromResource(\"/simple_tenant_usage.json\")).build())\n            .getSimpleTenantUsageApi(\"az-1.region-a.geo-1\").get();\n\n      SimpleTenantUsage usage = api.get(\"test-1234\");\n      assertEquals(usage.getTenantId(), \"f8535069c3fb404cb61c873b1a0b4921\");\n\n      SimpleTenantUsage expected = SimpleTenantUsage.builder().tenantId(\"f8535069c3fb404cb61c873b1a0b4921\").totalHours(4.833333333333333E-7).totalLocalGbUsage(1.933333333333333E-05)\n            .start(dateService.iso8601DateParse(\"2012-04-18 13:32:07.255743\")).stop(dateService.iso8601DateParse(\"2012-04-18 13:32:07.255743\"))\n            .totalMemoryMbUsage(0.0014847999999999999).totalVcpusUsage(7.249999999999999E-07).serverUsages(\n            ImmutableSet.of(\n                  SimpleServerUsage.builder().hours(2.4166666666666665e-07).uptime(91149).flavorLocalGb(50).instanceName(\"test1\").tenantId(\"f8535069c3fb404cb61c873b1a0b4921\").flavorVcpus(2).flavorMemoryMb(4096).instanceStatus(SimpleServerUsage.Status.ACTIVE).flavorName(\"m1.medium\").instanceCreated(this.dateService.iso8601SecondsDateParse(\"2012-04-17T12:12:58\")).build(),\n                  SimpleServerUsage.builder().hours(2.4166666666666665e-07).uptime(84710).flavorLocalGb(30).instanceName(\"mish_test\").tenantId(\"f8535069c3fb404cb61c873b1a0b4921\").flavorVcpus(1).flavorMemoryMb(2048).instanceStatus(SimpleServerUsage.Status.ACTIVE).flavorName(\"m1.small\").instanceCreated(this.dateService.iso8601SecondsDateParse(\"2012-04-17T14:00:17\")).build()\n            )).build();\n\n      assertEquals(usage, expected);\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/SimpleTenantUsageApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.Set;\n\nimport org.jclouds.openstack.nova.v2_0.domain.SimpleTenantUsage;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\n\n/**\n * Tests behavior of SimpleTenantUsageApi\n */\n@Test(groups = \"live\", testName = \"SimpleTenantUsageApiLiveTest\")\npublic class SimpleTenantUsageApiLiveTest extends BaseNovaApiLiveTest {\n\n   public void testList() throws Exception {\n      for (String regionId : api.getConfiguredRegions()) {\n         Optional<? extends SimpleTenantUsageApi> optApi = api.getSimpleTenantUsageApi(regionId);\n         if (optApi.isPresent() && identity.endsWith(\":admin\")) {\n            SimpleTenantUsageApi api = optApi.get();\n            Set<? extends SimpleTenantUsage> usages = api.list().toSet();\n            assertNotNull(usages);\n            for (SimpleTenantUsage usage : usages) {\n               SimpleTenantUsage details = api.get(usage.getTenantId());\n               assertNotNull(details);\n            }\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/VirtualInterfaceApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.nova.v2_0.domain.VirtualInterface;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiExpectTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Iterables;\n\n/**\n * Tests parsing and guice wiring of VirtualInterfaceApi\n */\n@Test(groups = \"live\", testName = \"VirtualInterfaceApiLiveTest\")\npublic class VirtualInterfaceApiExpectTest extends BaseNovaApiExpectTest {\n\n   public void testListVirtualInterfaces() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers/1/os-virtual-interfaces\");\n      VirtualInterfaceApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/virtual_interfaces_list.json\")).build()\n      ).getVirtualInterfaceApi(\"az-1.region-a.geo-1\").get();\n\n      VirtualInterface vif = Iterables.getOnlyElement(api.listOnServer(\"1\"));\n      assertEquals(vif.getId(), \"02315827-b05c-4668-9c05-75c68838074a\");\n      assertEquals(vif.getMacAddress(), \"fa:16:3e:09:71:34\");\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/VirtualInterfaceApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.Set;\n\nimport org.jclouds.openstack.nova.v2_0.domain.Server;\nimport org.jclouds.openstack.nova.v2_0.domain.VirtualInterface;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiLiveTest;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.collect.Iterables;\n\n/**\n * Tests behavior of VirtualInterfaceApi\n */\n@Test(groups = \"live\", testName = \"VirtualInterfaceApiLiveTest\", singleThreaded = true)\npublic class VirtualInterfaceApiLiveTest extends BaseNovaApiLiveTest {\n   private Optional<? extends VirtualInterfaceApi> apiOption;\n   private String region;\n\n   @BeforeClass(groups = {\"integration\", \"live\"})\n   @Override\n   public void setup() {\n      super.setup();\n      region = Iterables.getLast(api.getConfiguredRegions(), \"nova\");\n      apiOption = api.getVirtualInterfaceApi(region);\n   }\n\n   public void testListVirtualInterfaces() {\n      if (apiOption.isPresent()) {\n         Server testServer = null;\n         try {\n            testServer = createServerInRegion(region);\n            Set<? extends VirtualInterface> results = apiOption.get().listOnServer(testServer.getId()).toSet();\n            for (VirtualInterface vif : results) {\n               assertNotNull(vif.getId());\n               assertNotNull(vif.getMacAddress());\n            }\n         } finally {\n            if (testServer != null) {\n               api.getServerApi(region).delete(testServer.getId());\n            }\n         }\n   }\n}\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/VolumeApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.Set;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.nova.v2_0.domain.Volume;\nimport org.jclouds.openstack.nova.v2_0.domain.VolumeAttachment;\nimport org.jclouds.openstack.nova.v2_0.domain.VolumeSnapshot;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiExpectTest;\nimport org.jclouds.openstack.nova.v2_0.options.CreateVolumeOptions;\nimport org.jclouds.openstack.nova.v2_0.options.CreateVolumeSnapshotOptions;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\n\n/**\n * Tests VolumeApi guice wiring and parsing\n */\n@Test(groups = \"unit\", testName = \"VolumeApiExpectTest\")\npublic class VolumeApiExpectTest extends BaseNovaApiExpectTest {\n   private DateService dateService = new SimpleDateFormatDateService();\n\n   public void testListVolumes() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-volumes\");\n      VolumeApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/volume_list.json\")).build()\n      ).getVolumeApi(\"az-1.region-a.geo-1\").get();\n\n      Set<? extends Volume> volumes = api.list().toSet();\n      assertEquals(volumes, ImmutableSet.of(testVolume()));\n   }\n\n   public void testListVolumesInDetail() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-volumes/detail\");\n      VolumeApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/volume_list_detail.json\")).build()\n      ).getVolumeApi(\"az-1.region-a.geo-1\").get();\n\n      Set<? extends Volume> volumes = api.listInDetail().toSet();\n      assertEquals(volumes, ImmutableSet.of(testVolume()));\n   }\n\n   public void testCreateVolume() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-volumes\");\n      VolumeApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            authenticatedGET().endpoint(endpoint)\n                  .method(\"POST\")\n                  .payload(payloadFromStringWithContentType(\"{\\\"volume\\\":{\\\"display_name\\\":\\\"jclouds-test-volume\\\",\\\"display_description\\\":\\\"description of test volume\\\",\\\"size\\\":1}}\", MediaType.APPLICATION_JSON))\n                  .build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/volume_details.json\")).build()\n      ).getVolumeApi(\"az-1.region-a.geo-1\").get();\n\n      Volume volume = api.create(1, CreateVolumeOptions.Builder.name(\"jclouds-test-volume\").description(\"description of test volume\"));\n      assertEquals(volume, testVolume());\n   }\n\n   public void testGetVolume() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-volumes/1\");\n      VolumeApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/volume_details.json\")).build()\n      ).getVolumeApi(\"az-1.region-a.geo-1\").get();\n\n      Volume volume = api.get(\"1\");\n      assertEquals(volume, testVolume());\n      // double-check equals()\n      assertEquals(volume.getStatus(), Volume.Status.IN_USE);\n      assertEquals(volume.getDescription(), \"This is a test volume\");\n      assertEquals(volume.getZone(), \"nova\");\n      assertEquals(volume.getName(), \"test\");\n      assertEquals(volume.getStatus(), Volume.Status.IN_USE);\n      assertEquals(Iterables.getOnlyElement(volume.getAttachments()), testAttachment());\n   }\n\n   public void testDeleteVolume() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-volumes/1\");\n      VolumeApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            authenticatedGET().endpoint(endpoint).method(\"DELETE\").build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/attachment_details.json\")).build()\n      ).getVolumeApi(\"az-1.region-a.geo-1\").get();\n\n      assertTrue(api.delete(\"1\"));\n   }\n\n   public void testListSnapshots() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-snapshots\");\n      VolumeApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/snapshot_list.json\")).build()\n      ).getVolumeApi(\"az-1.region-a.geo-1\").get();\n\n      Set<? extends VolumeSnapshot> snapshots = api.listSnapshots().toSet();\n      assertEquals(snapshots, ImmutableSet.of(testSnapshot()));\n   }\n\n   public void testGetSnapshot() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-snapshots/1\");\n      VolumeApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/snapshot_details.json\")).build()\n      ).getVolumeApi(\"az-1.region-a.geo-1\").get();\n\n      VolumeSnapshot snapshot = api.getSnapshot(\"1\");\n      assertEquals(snapshot, testSnapshot());\n   }\n\n   public void testListSnapshotsInDetail() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-snapshots/detail\");\n      VolumeApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/snapshot_list_detail.json\")).build()\n      ).getVolumeApi(\"az-1.region-a.geo-1\").get();\n\n      Set<? extends VolumeSnapshot> snapshots = api.listSnapshotsInDetail().toSet();\n      assertEquals(snapshots, ImmutableSet.of(testSnapshot()));\n\n      // double-check individual fields\n      VolumeSnapshot snappy = Iterables.getOnlyElement(snapshots);\n      assertEquals(snappy.getId(), \"7\");\n      assertEquals(snappy.getVolumeId(), \"9\");\n      assertEquals(snappy.getStatus(), Volume.Status.AVAILABLE);\n      assertEquals(snappy.getDescription(), \"jclouds live test snapshot\");\n      assertEquals(snappy.getName(), \"jclouds-live-test\");\n      assertEquals(snappy.getSize(), 1);\n   }\n\n   public void testCreateSnapshot() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-snapshots\");\n      VolumeApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            authenticatedGET().endpoint(endpoint)\n                  .method(\"POST\")\n                  .payload(payloadFromStringWithContentType(\"{\\\"snapshot\\\":{\\\"display_name\\\":\\\"jclouds-live-test\\\",\\\"volume_id\\\":\\\"13\\\",\\\"display_description\\\":\\\"jclouds live test snapshot\\\",\\\"force\\\":\\\"true\\\"}}\", MediaType.APPLICATION_JSON))\n                  .build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/snapshot_details.json\")).build()\n      ).getVolumeApi(\"az-1.region-a.geo-1\").get();\n\n      VolumeSnapshot snapshot = api.createSnapshot(\"13\", CreateVolumeSnapshotOptions.Builder.name(\"jclouds-live-test\").description(\"jclouds live test snapshot\").force());\n      assertEquals(snapshot, testSnapshot());\n   }\n\n   public void testDeleteSnapshot() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-snapshots/1\");\n      VolumeApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            authenticatedGET().endpoint(endpoint).method(\"DELETE\").build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/snapshot_details.json\")).build()\n      ).getVolumeApi(\"az-1.region-a.geo-1\").get();\n\n      assertTrue(api.deleteSnapshot(\"1\"));\n   }\n\n   protected Volume testVolume() {\n      return Volume.builder().status(Volume.Status.IN_USE).description(\"This is a test volume\").zone(\"nova\").name(\"test\")\n            .attachments(ImmutableSet.of(testAttachment())).size(1).id(\"1\").created(dateService.iso8601SecondsDateParse(\"2012-04-23 12:16:45\")).build();\n   }\n\n   protected VolumeAttachment testAttachment() {\n      return VolumeAttachment.builder().device(\"/dev/vdc\").serverId(\"b4785058-cb80-491b-baa3-e4ee6546450e\").id(\"1\").volumeId(\"1\").build();\n   }\n\n   protected VolumeSnapshot testSnapshot() {\n      return VolumeSnapshot.builder().id(\"7\").volumeId(\"9\").description(\"jclouds live test snapshot\").status(Volume.Status.AVAILABLE)\n            .name(\"jclouds-live-test\").size(1).created(dateService.iso8601SecondsDateParse(\"2012-04-24 13:34:42\")).build();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/VolumeApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport static org.jclouds.util.Predicates2.retry;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\n\nimport org.jclouds.openstack.nova.v2_0.domain.Volume;\nimport org.jclouds.openstack.nova.v2_0.domain.VolumeSnapshot;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiLiveTest;\nimport org.jclouds.openstack.nova.v2_0.options.CreateVolumeOptions;\nimport org.jclouds.openstack.nova.v2_0.options.CreateVolumeSnapshotOptions;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Iterables;\n\n/**\n * Tests behavior of VolumeApi\n */\n@Test(groups = \"live\", testName = \"VolumeApiLiveTest\", singleThreaded = true)\npublic class VolumeApiLiveTest extends BaseNovaApiLiveTest {\n\n   private Optional<? extends VolumeApi> volumeOption;\n   private String region;\n   private String availabilityZone;\n\n   private Volume testVolume;\n   private VolumeSnapshot testSnapshot;\n\n   @BeforeClass(groups = {\"integration\", \"live\"})\n   @Override\n   public void setup() {\n      super.setup();\n      region = Iterables.getLast(api.getConfiguredRegions(), \"nova\");\n      volumeOption = api.getVolumeApi(region);\n\n      Optional<? extends AvailabilityZoneApi> availabilityZoneApi = api.getAvailabilityZoneApi(region);\n      availabilityZone = availabilityZoneApi.isPresent() ? Iterables.getLast(availabilityZoneApi.get().list()).getName() : region;\n   }\n\n   @AfterClass(groups = { \"integration\", \"live\" })\n   @Override\n   protected void tearDown() {\n      if (volumeOption.isPresent()) {\n         if (testSnapshot != null) {\n            final String snapshotId = testSnapshot.getId();\n            assertTrue(volumeOption.get().deleteSnapshot(snapshotId));\n            assertTrue(retry(new Predicate<VolumeApi>() {\n               public boolean apply(VolumeApi volumeApi) {\n                  return volumeOption.get().getSnapshot(snapshotId) == null;\n               }\n            }, 30 * 1000L).apply(volumeOption.get()));\n         }\n         if (testVolume != null) {\n            final String volumeId = testVolume.getId();\n            assertTrue(volumeOption.get().delete(volumeId));\n            assertTrue(retry(new Predicate<VolumeApi>() {\n               public boolean apply(VolumeApi volumeApi) {\n                  return volumeOption.get().get(volumeId) == null;\n               }\n            }, 180 * 1000L).apply(volumeOption.get()));\n         }\n      }\n      super.tearDown();\n   }\n\n   public void testCreateVolume() {\n      if (volumeOption.isPresent()) {\n         testVolume = volumeOption.get().create(\n               1,\n               CreateVolumeOptions.Builder.name(\"jclouds-test-volume\").description(\"description of test volume\")\n                     .availabilityZone(availabilityZone));\n         assertTrue(retry(new Predicate<VolumeApi>() {\n            public boolean apply(VolumeApi volumeApi) {\n               return volumeOption.get().get(testVolume.getId()).getStatus() == Volume.Status.AVAILABLE;\n            }\n         }, 180 * 1000L).apply(volumeOption.get()));\n      }\n   }\n\n   @Test(dependsOnMethods = \"testCreateVolume\")\n   public void testListVolumes() {\n      if (volumeOption.isPresent()) {\n         Set<? extends Volume> volumes = volumeOption.get().list().toSet();\n         assertNotNull(volumes);\n         boolean foundIt = false;\n         for (Volume vol : volumes) {\n            Volume details = volumeOption.get().get(vol.getId());\n            assertNotNull(details);\n            if (Objects.equal(details.getId(), testVolume.getId())) {\n               foundIt = true;\n            }\n         }\n         assertTrue(foundIt, \"Failed to find the volume we created in list() response\");\n      }\n   }\n\n   @Test(dependsOnMethods = \"testCreateVolume\")\n   public void testListVolumesInDetail() {\n      if (volumeOption.isPresent()) {\n         Set<? extends Volume> volumes = volumeOption.get().listInDetail().toSet();\n         assertNotNull(volumes);\n         boolean foundIt = false;\n         for (Volume vol : volumes) {\n            Volume details = volumeOption.get().get(vol.getId());\n            assertNotNull(details);\n            assertNotNull(details.getId());\n            assertNotNull(details.getCreated());\n            assertTrue(details.getSize() > -1);\n\n            assertEquals(details.getId(), vol.getId());\n            assertEquals(details.getSize(), vol.getSize());\n            assertEquals(details.getName(), vol.getName());\n            assertEquals(details.getDescription(), vol.getDescription());\n            assertEquals(details.getCreated(), vol.getCreated());\n            if (Objects.equal(details.getId(), testVolume.getId())) {\n               foundIt = true;\n            }\n         }\n         assertTrue(foundIt, \"Failed to find the volume we previously created in listInDetail() response\");\n      }\n   }\n\n   @Test(dependsOnMethods = \"testCreateVolume\")\n   public void testCreateSnapshot() {\n      if (volumeOption.isPresent()) {\n         testSnapshot = volumeOption.get().createSnapshot(\n                  testVolume.getId(),\n                  CreateVolumeSnapshotOptions.Builder.name(\"jclouds-live-test\").description(\n                           \"jclouds live test snapshot\").force());\n         assertNotNull(testSnapshot);\n         assertNotNull(testSnapshot.getId());\n         final String snapshotId = testSnapshot.getId();\n         assertNotNull(testSnapshot.getStatus());\n         assertTrue(testSnapshot.getSize() > -1);\n         assertNotNull(testSnapshot.getCreated());\n\n         assertTrue(retry(new Predicate<VolumeApi>() {\n            public boolean apply(VolumeApi volumeApi) {\n               return volumeOption.get().getSnapshot(snapshotId).getStatus() == Volume.Status.AVAILABLE;\n            }\n         }, 30 * 1000L).apply(volumeOption.get()));\n      }\n   }\n\n   @Test(dependsOnMethods = \"testCreateSnapshot\")\n   public void testListSnapshots() {\n      if (volumeOption.isPresent()) {\n         Set<? extends VolumeSnapshot> snapshots = volumeOption.get().listSnapshots().toSet();\n         assertNotNull(snapshots);\n         boolean foundIt = false;\n         for (VolumeSnapshot snap : snapshots) {\n            VolumeSnapshot details = volumeOption.get().getSnapshot(snap.getId());\n            if (Objects.equal(snap.getVolumeId(), testVolume.getId())) {\n               foundIt = true;\n            }\n            assertNotNull(details);\n            assertEquals(details.getId(), snap.getId());\n            assertEquals(details.getVolumeId(), snap.getVolumeId());\n         }\n         assertTrue(foundIt, \"Failed to find the snapshot we previously created in listSnapshots() response\");\n      }\n   }\n\n   @Test(dependsOnMethods = \"testCreateSnapshot\")\n   public void testListSnapshotsInDetail() {\n      if (volumeOption.isPresent()) {\n         Set<? extends VolumeSnapshot> snapshots = volumeOption.get().listSnapshotsInDetail().toSet();\n         assertNotNull(snapshots);\n         boolean foundIt = false;\n         for (VolumeSnapshot snap : snapshots) {\n            VolumeSnapshot details = volumeOption.get().getSnapshot(snap.getId());\n            if (Objects.equal(snap.getVolumeId(), testVolume.getId())) {\n               foundIt = true;\n               assertSame(details, testSnapshot);\n            }\n            assertSame(details, snap);\n         }\n\n         assertTrue(foundIt, \"Failed to find the snapshot we created in listSnapshotsInDetail() response\");\n      }\n   }\n\n   private void assertSame(VolumeSnapshot a, VolumeSnapshot b) {\n      assertNotNull(a);\n      assertNotNull(b);\n      assertEquals(a.getId(), b.getId());\n      assertEquals(a.getDescription(), b.getDescription());\n      assertEquals(a.getName(), b.getName());\n      assertEquals(a.getVolumeId(), b.getVolumeId());\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/VolumeAttachmentApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.Set;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.nova.v2_0.domain.Volume;\nimport org.jclouds.openstack.nova.v2_0.domain.VolumeAttachment;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiExpectTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\n\n/**\n * Tests VolumeAttachmentApi Guice wiring and parsing\n */\n@Test(groups = \"unit\", testName = \"VolumeAttachmentApiExpectTest\")\npublic class VolumeAttachmentApiExpectTest extends BaseNovaApiExpectTest {\n   private DateService dateService = new SimpleDateFormatDateService();\n\n   public void testListAttachments() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers/instance-1/os-volume_attachments\");\n      VolumeAttachmentApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/attachment_list.json\")).build()\n      ).getVolumeAttachmentApi(\"az-1.region-a.geo-1\").get();\n\n      Set<? extends VolumeAttachment> attachments = api.listAttachmentsOnServer(\"instance-1\").toSet();\n      assertEquals(attachments, ImmutableSet.of(testAttachment()));\n      // double-check individual fields\n      VolumeAttachment attachment = Iterables.getOnlyElement(attachments);\n      assertEquals(attachment.getDevice(), \"/dev/vdc\");\n      assertEquals(attachment.getServerId(), \"b4785058-cb80-491b-baa3-e4ee6546450e\");\n      assertEquals(attachment.getId(), \"1\");\n      assertEquals(attachment.getVolumeId(), \"1\");\n   }\n\n   public void testGetAttachment() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers/instance-1/os-volume_attachments/1\");\n      VolumeAttachmentApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/attachment_details.json\")).build()\n      ).getVolumeAttachmentApi(\"az-1.region-a.geo-1\").get();\n\n      VolumeAttachment attachment = api.getAttachmentForVolumeOnServer(\"1\", \"instance-1\");\n      assertEquals(attachment, testAttachment());\n   }\n\n   public void testAttachVolume() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers/instance-1/os-volume_attachments\");\n      VolumeAttachmentApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            authenticatedGET().endpoint(endpoint).method(\"POST\")\n                  .payload(payloadFromStringWithContentType(\"{\\\"volumeAttachment\\\":{\\\"volumeId\\\":\\\"1\\\",\\\"device\\\":\\\"/dev/vdc\\\"}}\", MediaType.APPLICATION_JSON)).endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/attachment_details.json\")).build()\n      ).getVolumeAttachmentApi(\"az-1.region-a.geo-1\").get();\n\n      VolumeAttachment result = api.attachVolumeToServerAsDevice(\"1\", \"instance-1\", \"/dev/vdc\");\n      assertEquals(result, testAttachment());\n   }\n\n   public void testDetachVolume() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers/instance-1/os-volume_attachments/1\");\n      VolumeAttachmentApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            authenticatedGET().endpoint(endpoint).method(\"DELETE\").build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/attachment_details.json\")).build()\n      ).getVolumeAttachmentApi(\"az-1.region-a.geo-1\").get();\n\n      assertTrue(api.detachVolumeFromServer(\"1\", \"instance-1\"));\n   }\n\n   protected Volume testVolume() {\n      return Volume.builder().status(Volume.Status.IN_USE).description(\"This is a test volume\").zone(\"nova\").name(\"test\")\n            .attachments(ImmutableSet.of(testAttachment())).size(1).id(\"1\").created(dateService.iso8601SecondsDateParse(\"2012-04-23 12:16:45\")).build();\n   }\n\n   protected VolumeAttachment testAttachment() {\n      return VolumeAttachment.builder().device(\"/dev/vdc\").serverId(\"b4785058-cb80-491b-baa3-e4ee6546450e\").id(\"1\").volumeId(\"1\").build();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/VolumeAttachmentApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\n\nimport java.util.Properties;\nimport java.util.concurrent.TimeoutException;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.openstack.cinder.v1.CinderApi;\nimport org.jclouds.openstack.cinder.v1.CinderApiMetadata;\nimport org.jclouds.openstack.cinder.v1.domain.Volume;\nimport org.jclouds.openstack.cinder.v1.features.VolumeApi;\nimport org.jclouds.openstack.cinder.v1.options.CreateVolumeOptions;\nimport org.jclouds.openstack.cinder.v1.predicates.VolumePredicates;\nimport org.jclouds.openstack.nova.v2_0.domain.Server;\nimport org.jclouds.openstack.nova.v2_0.domain.VolumeAttachment;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiLiveTest;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.FluentIterable;\n\n/**\n * Tests behavior of Volume Attachment API\n */\n@Test(groups = \"live\", testName = \"VolumeAttachmentApiLiveTest\", singleThreaded = true)\npublic class VolumeAttachmentApiLiveTest extends BaseNovaApiLiveTest {\n   private VolumeApi volumeApi;\n   private VolumeAttachmentApi volumeAttachmentApi;\n\n   private Volume volume;\n   private Server server;\n\n   protected String volumeProvider;\n   protected String volumeProviderVersion;\n   protected int volumeSizeGB;\n   protected String deviceId = \"/dev/wtf\";\n\n   @Override\n   protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      volumeProvider = setIfTestSystemPropertyPresent(props, provider + \".volume-provider\", \"openstack-cinder\");\n      volumeProviderVersion = setIfTestSystemPropertyPresent(props, provider + \".volume-provider-version\",\n          new CinderApiMetadata().getVersion());\n      volumeSizeGB = Integer.parseInt(setIfTestSystemPropertyPresent(props, provider + \".volume-size-gb\", \"1\"));\n      singleRegion = setIfTestSystemPropertyPresent(props, provider + \".region\", \"RegionOne\");\n      return props;\n   }\n\n   @BeforeClass(groups = {\"integration\", \"live\"})\n   @Override\n   public void setup() {\n      super.setup();\n\n      CinderApi cinderApi;\n\n      if (\"openstack-cinder\".equals(volumeProvider)) {\n         cinderApi = ContextBuilder.newBuilder(volumeProvider)\n               .endpoint(endpoint)\n               .apiVersion(volumeProviderVersion)\n               .credentials(identity, credential)\n               .buildApi(CinderApi.class);\n      }\n      else {\n         cinderApi = ContextBuilder.newBuilder(volumeProvider)\n               .credentials(identity, credential)\n               .buildApi(CinderApi.class);\n      }\n\n      volumeApi = cinderApi.getVolumeApi(singleRegion);\n      volumeAttachmentApi = api.getVolumeAttachmentApi(singleRegion).get();\n\n      CreateVolumeOptions options = CreateVolumeOptions.Builder\n            .name(\"jclouds-test-volume\")\n            .description(\"description of test volume\");\n\n      volume = volumeApi.create(volumeSizeGB, options);\n      VolumePredicates.awaitAvailable(volumeApi).apply(volume);\n\n      server = createServerInRegion(singleRegion);\n   }\n\n   @AfterClass(groups = {\"integration\", \"live\"})\n   @Override\n   public void tearDown() {\n      volumeApi.delete(volume.getId());\n      api.getServerApi(singleRegion).delete(server.getId());\n\n      super.tearDown();\n   }\n\n   @Test\n   public void testAttachVolume() throws TimeoutException {\n      VolumeAttachment volumeAttachment = volumeAttachmentApi\n               .attachVolumeToServerAsDevice(volume.getId(), server.getId(), deviceId);\n\n      // Wait for the volume to become Attached (aka In Use) before moving on\n      if (!VolumePredicates.awaitInUse(volumeApi).apply(volume)) {\n         throw new TimeoutException(\"Timeout on volume: \" + volume);\n      }\n\n      assertEquals(volumeAttachment.getVolumeId(), volume.getId());\n      assertEquals(volumeAttachment.getServerId(), server.getId());\n      // we can't assert the device because, depending on the implementation, the passed in device may be ignored\n      // and the implementation just picks a device itself\n   }\n\n   @Test(dependsOnMethods = \"testAttachVolume\")\n   public void testListAttachments() {\n      FluentIterable<VolumeAttachment> volumeAttachments = volumeAttachmentApi\n            .listAttachmentsOnServer(server.getId());\n\n      assertEquals(volumeAttachments.size(), 1);\n\n      VolumeAttachment volumeAttachment = volumeAttachments.get(0);\n\n      assertEquals(volumeAttachment.getVolumeId(), volume.getId());\n      assertEquals(volumeAttachment.getServerId(), server.getId());\n   }\n\n   @Test(dependsOnMethods = \"testListAttachments\")\n   public void testGetAttachment() {\n      VolumeAttachment volumeAttachment = volumeAttachmentApi\n            .getAttachmentForVolumeOnServer(volume.getId(), server.getId());\n\n      assertEquals(volumeAttachment.getVolumeId(), volume.getId());\n      assertEquals(volumeAttachment.getServerId(), server.getId());\n   }\n\n\n   @Test(dependsOnMethods = \"testGetAttachment\")\n   public void testDetachVolume() throws TimeoutException {\n      volumeAttachmentApi.detachVolumeFromServer(volume.getId(), server.getId());\n\n      // Wait for the volume to become Detached (aka Available) before moving on\n      if (!VolumePredicates.awaitAvailable(volumeApi).apply(volume)) {\n         throw new TimeoutException(\"Timeout on volume: \" + volume);\n      }\n\n      VolumeAttachment volumeAttachment = volumeAttachmentApi\n            .getAttachmentForVolumeOnServer(volume.getId(), server.getId());\n\n      assertNull(volumeAttachment);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/VolumeTypeApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.Set;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.nova.v2_0.domain.VolumeType;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiExpectTest;\nimport org.jclouds.openstack.nova.v2_0.options.CreateVolumeTypeOptions;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests guice wiring and parsing of VolumeTypeApi\n */\n@Test(groups = \"unit\", testName = \"VolumeTypeApiExpectTest\")\npublic class VolumeTypeApiExpectTest extends BaseNovaApiExpectTest {\n   private DateService dateService = new SimpleDateFormatDateService();\n\n   public void testListVolumeTypes() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-volume-types\");\n      VolumeTypeApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/volume_type_list.json\")).build()\n      ).getVolumeTypeApi(\"az-1.region-a.geo-1\").get();\n\n      Set<? extends VolumeType> types = api.list().toSet();\n      assertEquals(types, ImmutableSet.of(testVolumeType()));\n   }\n\n   public void testGetVolumeType() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-volume-types/8\");\n      VolumeTypeApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/volume_type.json\")).build()\n      ).getVolumeTypeApi(\"az-1.region-a.geo-1\").get();\n\n      VolumeType type = api.get(\"8\");\n      assertEquals(type, testVolumeType());\n   }\n\n   public void testCreateVolumeType() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-volume-types\");\n      VolumeTypeApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            authenticatedGET().endpoint(endpoint).method(\"POST\")\n                  .payload(payloadFromStringWithContentType(\"{\\\"volume_type\\\":{\\\"name\\\":\\\"jclouds-test-1\\\"}}\", MediaType.APPLICATION_JSON))\n                  .build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/volume_type.json\")).build()\n      ).getVolumeTypeApi(\"az-1.region-a.geo-1\").get();\n\n      VolumeType type = api.create(\"jclouds-test-1\");\n      assertEquals(type, testVolumeType());\n   }\n\n   public void testCreateVolumeTypeWithOptsNONE() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-volume-types\");\n      VolumeTypeApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            authenticatedGET().endpoint(endpoint).method(\"POST\")\n                  .payload(payloadFromStringWithContentType(\"{\\\"volume_type\\\":{\\\"name\\\":\\\"jclouds-test-1\\\",\\\"extra_specs\\\":{}}}\", MediaType.APPLICATION_JSON))\n                  .build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/volume_type.json\")).build()\n      ).getVolumeTypeApi(\"az-1.region-a.geo-1\").get();\n\n      VolumeType type = api.create(\"jclouds-test-1\", CreateVolumeTypeOptions.NONE);\n      assertEquals(type, testVolumeType());\n   }\n\n   public void testCreateVolumeTypeWithOptsSet() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-volume-types\");\n      VolumeTypeApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            authenticatedGET().endpoint(endpoint).method(\"POST\")\n                  .payload(payloadFromStringWithContentType(\"{\\\"volume_type\\\":{\\\"name\\\":\\\"jclouds-test-1\\\",\\\"extra_specs\\\":{\\\"x\\\": \\\"y\\\"}}}\", MediaType.APPLICATION_JSON))\n                  .build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/volume_type.json\")).build()\n      ).getVolumeTypeApi(\"az-1.region-a.geo-1\").get();\n\n      VolumeType type = api.create(\"jclouds-test-1\", CreateVolumeTypeOptions.Builder.specs(ImmutableMap.of(\"x\", \"y\")));\n      assertEquals(type, testVolumeType());\n   }\n\n   public void testDeleteVolumeType() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-volume-types/8\");\n      VolumeTypeApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            authenticatedGET().endpoint(endpoint).method(\"DELETE\").build(),\n            HttpResponse.builder().statusCode(200).build()\n      ).getVolumeTypeApi(\"az-1.region-a.geo-1\").get();\n\n      assertTrue(api.delete(\"8\"));\n   }\n\n   public void testGetAllExtraSpecs() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-volume-types/9/extra_specs\");\n      VolumeTypeApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/volume_type_extra_specs.json\")).build()\n      ).getVolumeTypeApi(\"az-1.region-a.geo-1\").get();\n\n      assertEquals(api.getExtraSpecs(\"9\"), ImmutableMap.of(\"test\", \"value1\"));\n   }\n\n   public void testSetAllExtraSpecs() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-volume-types/9/extra_specs\");\n      VolumeTypeApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            authenticatedGET().endpoint(endpoint)\n                  .method(\"POST\")\n                  .payload(payloadFromStringWithContentType(\"{\\\"extra_specs\\\":{\\\"test1\\\":\\\"somevalue\\\"}}\", MediaType.APPLICATION_JSON)).build(),\n            HttpResponse.builder().statusCode(200).build()\n      ).getVolumeTypeApi(\"az-1.region-a.geo-1\").get();\n\n      api.updateExtraSpecs(\"9\", ImmutableMap.of(\"test1\", \"somevalue\"));\n   }\n\n   public void testSetExtraSpec() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-volume-types/5/extra_specs/test1\");\n      VolumeTypeApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            authenticatedGET().endpoint(endpoint)\n                  .method(\"PUT\")\n                  .payload(payloadFromStringWithContentType(\"{\\\"test1\\\":\\\"somevalue\\\"}\", MediaType.APPLICATION_JSON)).build(),\n            HttpResponse.builder().statusCode(200).build()\n      ).getVolumeTypeApi(\"az-1.region-a.geo-1\").get();\n\n      api.updateExtraSpec(\"5\", \"test1\", \"somevalue\");\n   }\n\n   public void testGetExtraSpec() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-volume-types/5/extra_specs/test1\");\n      VolumeTypeApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromStringWithContentType(\"{\\\"test1\\\":\\\"another value\\\"}\", MediaType.APPLICATION_JSON)).build()\n      ).getVolumeTypeApi(\"az-1.region-a.geo-1\").get();\n\n      assertEquals(api.getExtraSpec(\"5\", \"test1\"), \"another value\");\n   }\n\n   public void testDeleteExtraSpec() {\n      URI endpoint = URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-volume-types/5/extra_specs/test1\");\n      VolumeTypeApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse,\n            authenticatedGET().endpoint(endpoint).method(\"DELETE\").build(),\n            HttpResponse.builder().statusCode(200).build()\n      ).getVolumeTypeApi(\"az-1.region-a.geo-1\").get();\n\n      assertTrue(api.deleteExtraSpec(\"5\", \"test1\"));\n   }\n\n   public VolumeType testVolumeType() {\n      return VolumeType.builder().id(\"8\").name(\"jclouds-test-1\").created(dateService.iso8601SecondsDateParse(\"2012-05-10 12:33:06\")).extraSpecs(ImmutableMap.of(\"test\", \"value1\", \"test1\", \"wibble\")).build();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/VolumeTypeApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.extensions;\n\nimport static org.jclouds.util.Predicates2.retry;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\n\nimport org.jclouds.openstack.nova.v2_0.domain.VolumeType;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiLiveTest;\nimport org.jclouds.openstack.nova.v2_0.options.CreateVolumeTypeOptions;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeGroups;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\n\n/**\n * Tests behavior of VolumeTypeApi\n */\n@Test(groups = \"live\", testName = \"VolumeTypeApiLiveTest\", singleThreaded = true)\npublic class VolumeTypeApiLiveTest extends BaseNovaApiLiveTest {\n\n   private Optional<? extends VolumeTypeApi> volumeTypeOption;\n   private String region;\n\n   private VolumeType testVolumeType;\n\n   @BeforeGroups(groups = {\"integration\", \"live\"})\n   @Override\n   public void setup() {\n      super.setup();\n      region = Iterables.getLast(api.getConfiguredRegions(), \"nova\");\n      volumeTypeOption = api.getVolumeTypeApi(region);\n   }\n\n\n   @AfterClass(groups = { \"integration\", \"live\" })\n   @Override\n   protected void tearDown() {\n      if (volumeTypeOption.isPresent()) {\n         if (testVolumeType != null) {\n            final String id = testVolumeType.getId();\n            assertTrue(volumeTypeOption.get().delete(id));\n            assertTrue(retry(new Predicate<VolumeTypeApi>() {\n               public boolean apply(VolumeTypeApi volumeApi) {\n                  return volumeApi.get(id) == null;\n               }\n            }, 5 * 1000L).apply(volumeTypeOption.get()));\n         }\n      }\n      super.tearDown();\n   }\n\n   public void testCreateVolumeType() {\n      if (volumeTypeOption.isPresent()) {\n         testVolumeType = volumeTypeOption.get().create(\n               \"jclouds-test-1\", CreateVolumeTypeOptions.Builder.specs(ImmutableMap.of(\"test\", \"value1\")));\n         assertTrue(retry(new Predicate<VolumeTypeApi>() {\n            public boolean apply(VolumeTypeApi volumeTypeApi) {\n               return volumeTypeApi.get(testVolumeType.getId()) != null;\n            }\n         }, 180 * 1000L).apply(volumeTypeOption.get()));\n\n         assertEquals(volumeTypeOption.get().get(testVolumeType.getId()).getName(), \"jclouds-test-1\");\n         assertEquals(volumeTypeOption.get().get(testVolumeType.getId()).getExtraSpecs(), ImmutableMap.of(\"test\", \"value1\"));\n      }\n   }\n\n   @Test(dependsOnMethods = \"testCreateVolumeType\")\n   public void testListVolumeTypes() {\n      if (volumeTypeOption.isPresent()) {\n         Set<? extends VolumeType> volumeTypes = volumeTypeOption.get().list().toSet();\n         assertNotNull(volumeTypes);\n         boolean foundIt = false;\n         for (VolumeType vt : volumeTypes) {\n            VolumeType details = volumeTypeOption.get().get(vt.getId());\n            assertNotNull(details);\n            if (Objects.equal(details.getId(), testVolumeType.getId())) {\n               foundIt = true;\n            }\n         }\n         assertTrue(foundIt, \"Failed to find the volume type we created in list() response\");\n      }\n   }\n\n   @Test(dependsOnMethods = \"testCreateVolumeType\")\n   public void testExtraSpecs() {\n      if (volumeTypeOption.isPresent()) {\n         assertEquals(volumeTypeOption.get().getExtraSpecs(testVolumeType.getId()), ImmutableMap.of(\"test\", \"value1\"));\n         assertEquals(volumeTypeOption.get().getExtraSpec(testVolumeType.getId(), \"test\"),  \"value1\");\n         volumeTypeOption.get().updateExtraSpecs(testVolumeType.getId(), ImmutableMap.of(\"test1\", \"wibble\"));\n      }\n   }\n\n   @Test(dependsOnMethods = \"testCreateVolumeType\")\n   public void testUpdateIndividualSpec() {\n      if (volumeTypeOption.isPresent()) {\n         volumeTypeOption.get().updateExtraSpec(testVolumeType.getId(), \"test1\", \"freddy\");\n         assertEquals(volumeTypeOption.get().getExtraSpec(testVolumeType.getId(), \"test1\"), \"freddy\");\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/features/ExtensionApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.features;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.nova.v2_0.NovaApi;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiExpectTest;\nimport org.jclouds.openstack.nova.v2_0.parse.ParseExtensionListTest;\nimport org.jclouds.openstack.nova.v2_0.parse.ParseExtensionTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests annotation parsing of {@code ExtensionApi}\n */\n@Test(groups = \"unit\", testName = \"ExtensionApiExpectTest\")\npublic class ExtensionApiExpectTest extends BaseNovaApiExpectTest {\n\n   public void testListExtensionsWhenResponseIs2xx() throws Exception {\n      HttpRequest listExtensions = HttpRequest.builder()\n            .method(\"GET\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/extensions\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken)\n            .build();\n\n      HttpResponse listExtensionsResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResource(\"/extension_list.json\")).build();\n\n      NovaApi apiWhenExtensionsExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, listExtensions, listExtensionsResponse);\n\n      assertEquals(apiWhenExtensionsExist.getConfiguredRegions(), ImmutableSet.of(\"az-1.region-a.geo-1\", \"az-2.region-a.geo-1\", \"az-3.region-a.geo-1\"));\n\n      assertEquals(apiWhenExtensionsExist.getExtensionApi(\"az-1.region-a.geo-1\").list().toString(),\n            new ParseExtensionListTest().expected().toString());\n   }\n\n   // TODO: gson deserializer for Multimap\n   public void testGetExtensionByAliasWhenResponseIs2xx() throws Exception {\n      HttpRequest getExtension = HttpRequest.builder()\n            .method(\"GET\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/extensions/RS-PIE\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken)\n            .build();\n\n      HttpResponse getExtensionResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResource(\"/extension_details.json\")).build();\n\n      NovaApi apiWhenExtensionsExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, getExtension, getExtensionResponse);\n\n      assertEquals(apiWhenExtensionsExist.getExtensionApi(\"az-1.region-a.geo-1\").get(\"RS-PIE\")\n            .toString(), new ParseExtensionTest().expected().toString());\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/features/ExtensionApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.Set;\n\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiLiveTest;\nimport org.jclouds.openstack.v2_0.domain.Extension;\nimport org.jclouds.openstack.v2_0.features.ExtensionApi;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@link ExtensionApi}\n */\n@Test(groups = \"live\", testName = \"ExtensionApiLiveTest\")\npublic class ExtensionApiLiveTest extends BaseNovaApiLiveTest {\n\n    /**\n     * Tests the listing of Extensions.\n     *\n     * @throws Exception\n     */\n    @Test(description = \"GET /v${apiVersion}/{tenantId}/extensions\")\n    public void testListExtensions() throws Exception {\n       for (String regionId : regions) {\n          ExtensionApi extensionApi = api.getExtensionApi(regionId);\n          Set<? extends Extension> response = extensionApi.list();\n          assertNotNull(response);\n          assertFalse(response.isEmpty());\n           for (Extension extension : response) {\n              assertNotNull(extension.getId());\n              assertNotNull(extension.getName());\n              assertNotNull(extension.getDescription());\n              assertNotNull(extension.getLinks());\n              // Namespace and updated fields are nullable\n           }\n       }\n    }\n\n    /**\n     * Tests retrieval of Extensions using their alias.\n     *\n     * @throws Exception\n     */\n    @Test(description = \"GET /v${apiVersion}/{tenantId}/extensions/{alias}\", dependsOnMethods = { \"testListExtensions\" })\n    public void testGetExtensionByAlias() throws Exception {\n       for (String regionId : regions) {\n           ExtensionApi extensionApi = api.getExtensionApi(regionId);\n           Set<? extends Extension> response = extensionApi.list();\n           for (Extension extension : response) {\n              Extension details = extensionApi.get(extension.getId());\n              assertNotNull(details);\n              assertEquals(details.getId(), extension.getId());\n              assertEquals(details.getName(), extension.getName());\n              assertEquals(details.getDescription(), extension.getDescription());\n              assertEquals(details.getNamespace(), extension.getNamespace());\n              assertEquals(details.getUpdated(), extension.getUpdated());\n              assertEquals(details.getLinks(), extension.getLinks());\n           }\n        }\n    }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/features/FlavorApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.features;\n\nimport static org.testng.Assert.assertEquals;\n\nimport jakarta.ws.rs.HttpMethod;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.nova.v2_0.NovaApi;\nimport org.jclouds.openstack.nova.v2_0.domain.Flavor;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiExpectTest;\nimport org.jclouds.openstack.nova.v2_0.parse.ParseCreateFlavorTest;\nimport org.jclouds.openstack.nova.v2_0.parse.ParseFlavorListTest;\nimport org.jclouds.openstack.nova.v2_0.parse.ParseFlavorTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.net.HttpHeaders;\n\n/**\n * Tests annotation parsing of {@code FlavorApi}\n */\n@Test(groups = \"unit\", testName = \"FlavorApiExpectTest\")\npublic class FlavorApiExpectTest extends BaseNovaApiExpectTest {\n\n   public void testListFlavorsWhenResponseIs2xx() throws Exception {\n      HttpRequest listFlavors = HttpRequest.builder()\n            .method(\"GET\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/flavors\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken)\n            .build();\n\n      HttpResponse listFlavorsResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResource(\"/flavor_list.json\")).build();\n\n      NovaApi apiWhenFlavorsExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, listFlavors, listFlavorsResponse);\n\n      assertEquals(apiWhenFlavorsExist.getConfiguredRegions(), ImmutableSet.of(\"az-1.region-a.geo-1\", \"az-2.region-a.geo-1\", \"az-3.region-a.geo-1\"));\n\n      assertEquals(apiWhenFlavorsExist.getFlavorApi(\"az-1.region-a.geo-1\").list().concat().toString(),\n            new ParseFlavorListTest().expected().toString());\n   }\n\n   // TODO: gson deserializer for Multimap\n   public void testGetFlavorWhenResponseIs2xx() throws Exception {\n      HttpRequest getFlavor = HttpRequest.builder()\n            .method(\"GET\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/flavors/52415800-8b69-11e0-9b19-734f1195ff37\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken)\n            .build();\n\n      HttpResponse getFlavorResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResource(\"/flavor_details.json\")).build();\n\n      NovaApi apiWhenFlavorsExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, getFlavor, getFlavorResponse);\n\n      assertEquals(\n            apiWhenFlavorsExist.getFlavorApi(\"az-1.region-a.geo-1\").get(\"52415800-8b69-11e0-9b19-734f1195ff37\")\n                  .toString(), new ParseFlavorTest().expected().toString());\n   }\n\n   public void testCreateFlavor200() throws Exception {\n      ParseCreateFlavorTest parser = new ParseCreateFlavorTest();\n      HttpRequest listFlavors = HttpRequest.builder()\n            .method(HttpMethod.POST)\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/flavors\")\n            .addHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON)\n            .addHeader(\"X-Auth-Token\", authToken)\n            .payload(payloadFromResource(parser.resource())).build();\n\n      HttpResponse listFlavorsResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResource(parser.resource())).build();\n\n      NovaApi api = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, listFlavors, listFlavorsResponse);\n\n      assertEquals(\n            api.getFlavorApi(\"az-1.region-a.geo-1\").create(Flavor.builder()\n                  .id(\"1cb47a44-9b84-4da4-bf81-c1976e8414ab\")\n                  .name(\"128 MB Server\").ram(128).vcpus(1)\n                  .disk(10).build())\n                  .toString(), parser.expected().toString());\n   }\n\n   public void testDeleteFlavor202() throws Exception {\n      String flavorId = \"1cb47a44-9b84-4da4-bf81-c1976e8414ab\";\n      HttpRequest updateMetadata = HttpRequest.builder()\n            .method(HttpMethod.DELETE)\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/flavors/\" + flavorId)\n            .addHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON)\n            .addHeader(\"X-Auth-Token\", authToken)\n            .build();\n\n      HttpResponse updateMetadataResponse = HttpResponse.builder().statusCode(204).build();\n\n      NovaApi api = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n               responseWithKeystoneAccess, updateMetadata, updateMetadataResponse);\n\n      api.getFlavorApi(\"az-1.region-a.geo-1\").delete(flavorId);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/features/FlavorApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\n\nimport org.jclouds.openstack.nova.v2_0.domain.Flavor;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiLiveTest;\nimport org.jclouds.openstack.v2_0.domain.Resource;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@link FlavorApi}\n */\n@Test(groups = \"live\", testName = \"FlavorApiLiveTest\")\npublic class FlavorApiLiveTest extends BaseNovaApiLiveTest {\n\n   /**\n    * Tests the listing of Flavors.\n    *\n    * @throws Exception\n    */\n   @Test(description = \"GET /v${apiVersion}/{tenantId}/flavors\")\n   public void testListFlavors() throws Exception {\n      for (String regionId : regions) {\n         FlavorApi flavorApi = api.getFlavorApi(regionId);\n         Set<? extends Resource> response = flavorApi.list().concat().toSet();\n         assertNotNull(response);\n         assertFalse(response.isEmpty());\n         for (Resource flavor : response) {\n            assertNotNull(flavor.getId());\n            assertNotNull(flavor.getName());\n            assertNotNull(flavor.getLinks());\n         }\n      }\n   }\n\n   /**\n    * Tests the listing of Flavors in detail.\n    *\n    * @throws Exception\n    */\n   @Test(description = \"GET /v${apiVersion}/{tenantId}/flavors/detail\")\n   public void testListFlavorsInDetail() throws Exception {\n      for (String regionId : regions) {\n         FlavorApi flavorApi = api.getFlavorApi(regionId);\n         Set<? extends Flavor> response = flavorApi.listInDetail().concat().toSet();\n         assertNotNull(response);\n         assertFalse(response.isEmpty());\n         for (Flavor flavor : response) {\n            assertNotNull(flavor.getId());\n            assertNotNull(flavor.getName());\n            assertNotNull(flavor.getLinks());\n            assertTrue(flavor.getRam() > 0);\n            // Some flavors can potentially have 0 system disk sizes.\n            assertTrue(flavor.getDisk() >= 0);\n            assertTrue(flavor.getVcpus() > 0);\n         }\n      }\n   }\n\n   /**\n    * Tests getting Flavors by id.\n    *\n    * @throws Exception\n    */\n   @Test(description = \"GET /v${apiVersion}/{tenantId}/flavors/{id}\", dependsOnMethods = { \"testListFlavorsInDetail\" })\n   public void testGetFlavorById() throws Exception {\n      for (String regionId : regions) {\n         FlavorApi flavorApi = api.getFlavorApi(regionId);\n         Set<? extends Flavor> response = flavorApi.listInDetail().concat().toSet();\n         for (Flavor flavor : response) {\n            Flavor details = flavorApi.get(flavor.getId());\n            assertNotNull(details);\n            assertEquals(details.getId(), flavor.getId());\n            assertEquals(details.getName(), flavor.getName());\n            assertEquals(details.getLinks(), flavor.getLinks());\n            assertEquals(details.getRam(), flavor.getRam());\n            assertEquals(details.getDisk(), flavor.getDisk());\n            assertEquals(details.getVcpus(), flavor.getVcpus());\n         }\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/features/ImageApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.features;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.nova.v2_0.NovaApi;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiExpectTest;\nimport org.jclouds.openstack.nova.v2_0.parse.ParseImageListTest;\nimport org.jclouds.openstack.nova.v2_0.parse.ParseImageTest;\nimport org.jclouds.openstack.nova.v2_0.parse.ParseMetadataListTest;\nimport org.jclouds.openstack.nova.v2_0.parse.ParseMetadataUpdateTest;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests annotation parsing of {@code ImageApi}\n */\n@Test(groups = \"unit\", testName = \"ImageApiExpectTest\")\npublic class ImageApiExpectTest extends BaseNovaApiExpectTest {\n\n   public void testListImagesWhenResponseIs2xx() throws Exception {\n      HttpRequest list = HttpRequest.builder()\n            .method(\"GET\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/images\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken)\n            .build();\n\n      HttpResponse listResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResource(\"/image_list.json\")).build();\n\n      NovaApi apiWhenImagesExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, list, listResponse);\n\n      assertEquals(apiWhenImagesExist.getConfiguredRegions(), ImmutableSet.of(\"az-1.region-a.geo-1\", \"az-2.region-a.geo-1\", \"az-3.region-a.geo-1\"));\n\n      assertEquals(apiWhenImagesExist.getImageApi(\"az-1.region-a.geo-1\").list().concat().toString(),\n            new ParseImageListTest().expected().toString());\n   }\n\n   public void testGetImageWhenResponseIs2xx() throws Exception {\n\n      HttpRequest getImage = HttpRequest.builder()\n            .method(\"GET\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/images/52415800-8b69-11e0-9b19-734f5736d2a2\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken)\n            .build();\n\n      HttpResponse getImageResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResource(\"/image_details.json\")).build();\n\n      NovaApi apiWhenImagesExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, getImage, getImageResponse);\n\n      assertEquals(\n            apiWhenImagesExist.getImageApi(\"az-1.region-a.geo-1\").get(\"52415800-8b69-11e0-9b19-734f5736d2a2\")\n                  .toString(), new ParseImageTest().expected().toString());\n   }\n\n   public void testListMetadataWhenResponseIs2xx() throws Exception {\n      String imageId = \"52415800-8b69-11e0-9b19-734f5736d2a2\";\n      HttpRequest getMetadata = HttpRequest.builder()\n            .method(\"GET\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/images/\" + imageId + \"/metadata\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken)\n            .build();\n\n      HttpResponse getMetadataResponse = HttpResponse.builder().statusCode(200)\n              .payload(payloadFromResource(\"/metadata_list.json\")).build();\n\n      NovaApi apiWhenServerExists = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n               responseWithKeystoneAccess, getMetadata, getMetadataResponse);\n\n      assertEquals(apiWhenServerExists.getImageApi(\"az-1.region-a.geo-1\").getMetadata(imageId).toString(),\n             new ParseMetadataListTest().expected().toString());\n   }\n\n   public void testSetMetadataWhenResponseIs2xx() throws Exception {\n      String imageId = \"52415800-8b69-11e0-9b19-734f5736d2a2\";\n      ImmutableMap<String, String> metadata = new ImmutableMap.Builder<String, String>()\n              .put(\"Server Label\", \"Web Head 1\")\n              .put(\"Image Version\", \"2.1\")\n              .build();\n\n      HttpRequest setMetadata = HttpRequest.builder()\n            .method(\"PUT\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/images/\" + imageId + \"/metadata\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken)\n            .payload(payloadFromStringWithContentType(\n                  \"{\\\"metadata\\\":{\\\"Server Label\\\":\\\"Web Head 1\\\",\\\"Image Version\\\":\\\"2.1\\\"}}\", \"application/json\"))\n            .build();\n\n      HttpResponse setMetadataResponse = HttpResponse.builder().statusCode(200)\n              .payload(payloadFromResource(\"/metadata_list.json\")).build();\n\n      NovaApi apiWhenImageExists = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n               responseWithKeystoneAccess, setMetadata, setMetadataResponse);\n\n      assertEquals(apiWhenImageExists.getImageApi(\"az-1.region-a.geo-1\").setMetadata(imageId, metadata).toString(),\n             new ParseMetadataListTest().expected().toString());\n   }\n\n   public void testUpdateMetadataWhenResponseIs2xx() throws Exception {\n      String imageId = \"52415800-8b69-11e0-9b19-734f5736d2a2\";\n      ImmutableMap<String, String> metadata = new ImmutableMap.Builder<String, String>()\n              .put(\"Server Label\", \"Web Head 2\")\n              .put(\"Server Description\", \"Simple Server\")\n              .build();\n\n      HttpRequest setMetadata = HttpRequest.builder()\n            .method(\"POST\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/images/\" + imageId + \"/metadata\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken)\n            .payload(payloadFromStringWithContentType(\n                  \"{\\\"metadata\\\":{\\\"Server Label\\\":\\\"Web Head 2\\\",\\\"Server Description\\\":\\\"Simple Server\\\"}}\", \"application/json\"))\n            .build();\n\n      HttpResponse setMetadataResponse = HttpResponse.builder().statusCode(200)\n              .payload(payloadFromResource(\"/metadata_updated.json\")).build();\n\n      NovaApi apiWhenServerExists = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n               responseWithKeystoneAccess, setMetadata, setMetadataResponse);\n\n      assertEquals(apiWhenServerExists.getImageApi(\"az-1.region-a.geo-1\").updateMetadata(imageId, metadata).toString(),\n             new ParseMetadataUpdateTest().expected().toString());\n   }\n\n   public void testGetMetadataItemWhenResponseIs2xx() throws Exception {\n      String imageId = \"52415800-8b69-11e0-9b19-734f5736d2a2\";\n      String key = \"Image Version\";\n\n      HttpRequest getMetadata = HttpRequest.builder()\n            .method(\"GET\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/images/\" + imageId + \"/metadata/\" +\n                  Strings2.urlEncode(key))\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken)\n            .build();\n\n      HttpResponse getMetadataResponse = HttpResponse.builder().statusCode(200)\n              .payload(payloadFromString(\"{\\\"metadata\\\":{\\\"Image Version\\\":\\\"2.5\\\"}}\")).build();\n\n      NovaApi apiWhenServerExists = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n               responseWithKeystoneAccess, getMetadata, getMetadataResponse);\n\n      assertEquals(apiWhenServerExists.getImageApi(\"az-1.region-a.geo-1\").getMetadata(imageId, \"Image Version\").toString(),\n             \"2.5\");\n   }\n\n   public void testSetMetadataItemWhenResponseIs2xx() throws Exception {\n      String imageId = \"52415800-8b69-11e0-9b19-734f5736d2a2\";\n      String key = \"Image Version\";\n\n      HttpRequest updateMetadata = HttpRequest.builder()\n            .method(\"PUT\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/images/\" + imageId + \"/metadata/\" + \"Image%20Version\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken)\n            .payload(payloadFromStringWithContentType(\"{\\\"metadata\\\":{\\\"Image Version\\\":\\\"2.5\\\"}}\", \"application/json\"))\n            .build();\n\n      HttpResponse updateMetadataResponse = HttpResponse.builder().statusCode(200)\n              .payload(payloadFromStringWithContentType(\"{\\\"metadata\\\":{\\\"Image Version\\\":\\\"2.5\\\"}}\", \"application/json\")).build();\n\n      NovaApi apiWhenServerExists = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n               responseWithKeystoneAccess, updateMetadata, updateMetadataResponse);\n\n      assertEquals(apiWhenServerExists.getImageApi(\"az-1.region-a.geo-1\").updateMetadata(imageId, key, \"2.5\").toString(),\n             \"2.5\");\n   }\n\n   public void testDeleteMetadataItemWhenResponseIs2xx() throws Exception {\n      String imageId = \"52415800-8b69-11e0-9b19-734f5736d2a2\";\n      String key = \"Image Version\";\n\n      HttpRequest deleteMetadata = HttpRequest.builder()\n            .method(\"DELETE\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/images/\" + imageId + \"/metadata/\" +\n                  Strings2.urlEncode(key))\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken)\n            .build();\n\n      HttpResponse deleteMetadataResponse = HttpResponse.builder().statusCode(204).build();\n\n      NovaApi apiWhenImageExists = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n               responseWithKeystoneAccess, deleteMetadata, deleteMetadataResponse);\n\n      apiWhenImageExists.getImageApi(\"az-1.region-a.geo-1\").deleteMetadata(imageId, key);\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/features/ImageApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\n\nimport org.jclouds.openstack.nova.v2_0.domain.Image;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiLiveTest;\nimport org.jclouds.openstack.v2_0.domain.Resource;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@link ImageApi}\n */\n@Test(groups = \"live\", testName = \"ImageApiLiveTest\")\npublic class ImageApiLiveTest extends BaseNovaApiLiveTest {\n\n   @Test(description = \"GET /v${apiVersion}/{tenantId}/images\")\n   public void testListImages() throws Exception {\n      for (String regionId : regions) {\n         ImageApi imageApi = api.getImageApi(regionId);\n         Set<? extends Resource> response = imageApi.list().concat().toSet();\n         assertNotNull(response);\n         assertFalse(response.isEmpty());\n         for (Resource image : response) {\n            assertNotNull(image.getId());\n            assertNotNull(image.getName());\n            assertNotNull(image.getLinks());\n         }\n      }\n   }\n\n   @Test(description = \"GET /v${apiVersion}/{tenantId}/images/detail\")\n   public void testListImagesInDetail() throws Exception {\n      for (String regionId : api.getConfiguredRegions()) {\n         ImageApi imageApi = api.getImageApi(regionId);\n         Set<? extends Image> response = imageApi.listInDetail().concat().toSet();\n         assertNotNull(response);\n         assertFalse(response.isEmpty());\n         for (Image image : response) {\n            assertNotNull(image.getId());\n            assertNotNull(image.getName());\n            assertNotNull(image.getLinks());\n            assertNotNull(image.getCreated());\n            // image.getMinDisk() can be zero\n            // image.getMinRam() can be zero\n            assertTrue(image.getProgress() >= 0 && image.getProgress() <= 100);\n            assertNotNull(image.getStatus());\n            // image.getServer() can be null\n            // image.getTenantId() can be null\n            // image.getUpdated() can be null\n            // image.getUserId() can be null\n         }\n      }\n   }\n\n   @Test(description = \"GET /v${apiVersion}/{tenantId}/images/{id}\", dependsOnMethods = { \"testListImagesInDetail\" })\n   public void testGetImageById() throws Exception {\n      for (String regionId : api.getConfiguredRegions()) {\n         ImageApi imageApi = api.getImageApi(regionId);\n         Set<? extends Image> response = imageApi.listInDetail().concat().toSet();\n         for (Image image : response) {\n            Image details = imageApi.get(image.getId());\n            assertNotNull(details);\n            assertEquals(details.getId(), image.getId());\n            assertEquals(details.getName(), image.getName());\n            assertEquals(details.getLinks(), image.getLinks());\n            assertEquals(details.getCreated(), image.getCreated());\n            assertEquals(details.getMinDisk(), image.getMinDisk());\n            assertEquals(details.getMinRam(), image.getMinRam());\n            assertEquals(details.getProgress(), image.getProgress());\n            assertEquals(details.getStatus(), image.getStatus());\n            assertEquals(details.getServer(), image.getServer());\n            assertEquals(details.getTenantId(), image.getTenantId());\n            assertEquals(details.getUpdated(), image.getUpdated());\n            assertEquals(details.getUserId(), image.getUserId());\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/features/ImageApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.features;\n\nimport com.google.common.collect.FluentIterable;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\n\nimport org.jclouds.openstack.nova.v2_0.NovaApi;\nimport org.jclouds.openstack.nova.v2_0.domain.BlockDeviceMapping;\nimport org.jclouds.openstack.nova.v2_0.domain.Image;\nimport org.jclouds.openstack.v2_0.internal.BaseOpenStackMockTest;\nimport org.testng.annotations.Test;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\n@Test(groups = \"unit\")\npublic class ImageApiMockTest extends BaseOpenStackMockTest<NovaApi> {\n   public void testImageWithBlockDeviceMapping() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/image_list_with_block_device_mapping.json\"))));\n\n      try {\n         NovaApi novaApi = api(server.url(\"/\").toString(), \"openstack-nova\");\n         ImageApi imageApi = novaApi.getImageApiForZone(\"RegionOne\");\n\n         FluentIterable<? extends Image> images = imageApi.listInDetail().concat();\n\n         Image img = images.get(0);\n         assertNotNull(img.getMetadata());\n         assertEquals(10, img.getMetadata().size());\n         assertNotNull(img.getBlockDeviceMapping());\n         assertEquals(1, img.getBlockDeviceMapping().size());\n         BlockDeviceMapping blockDeviceMapping = img.getBlockDeviceMapping().get(0);\n         assertEquals(\"snapshot\", blockDeviceMapping.getSourceType());\n         assertEquals(Integer.valueOf(2), blockDeviceMapping.getBootIndex());\n      } finally {\n         server.shutdown();\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/features/ServerApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport com.google.common.collect.Iterables;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.nova.v2_0.NovaApi;\nimport org.jclouds.openstack.nova.v2_0.domain.BlockDeviceMapping;\nimport org.jclouds.openstack.nova.v2_0.domain.Server;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiExpectTest;\nimport org.jclouds.openstack.nova.v2_0.options.CreateServerOptions;\nimport org.jclouds.openstack.nova.v2_0.options.RebuildServerOptions;\nimport org.jclouds.openstack.nova.v2_0.parse.ParseCreatedServerTest;\nimport org.jclouds.openstack.nova.v2_0.parse.ParseMetadataListTest;\nimport org.jclouds.openstack.nova.v2_0.parse.ParseMetadataUpdateTest;\nimport org.jclouds.openstack.nova.v2_0.parse.ParseSecurityGroupListTest;\nimport org.jclouds.openstack.nova.v2_0.parse.ParseServerDetailsStatesTest;\nimport org.jclouds.openstack.nova.v2_0.parse.ParseServerDiagnostics;\nimport org.jclouds.openstack.nova.v2_0.parse.ParseServerListTest;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests annotation parsing of {@code ServerApi}\n */\n@Test(groups = \"unit\", testName = \"ServerApiExpectTest\")\npublic class ServerApiExpectTest extends BaseNovaApiExpectTest {\n\n   public void testListServersWhenResponseIs2xx() throws Exception {\n      HttpRequest listServers = HttpRequest.builder()\n            .method(\"GET\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken).build();\n\n      HttpResponse listServersResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResource(\"/server_list.json\")).build();\n\n      NovaApi apiWhenServersExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, listServers, listServersResponse);\n\n      assertEquals(apiWhenServersExist.getConfiguredRegions(), ImmutableSet.of(\"az-1.region-a.geo-1\", \"az-2.region-a.geo-1\", \"az-3.region-a.geo-1\"));\n\n      assertEquals(apiWhenServersExist.getServerApi(\"az-1.region-a.geo-1\").list().concat().toString(),\n            new ParseServerListTest().expected().toString());\n   }\n\n   public void testListInDetailServersWhenResponseIs2xx() throws Exception {\n      HttpRequest listServers = HttpRequest\n              .builder()\n              .method(\"GET\")\n              .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers/detail\")\n              .addHeader(\"Accept\", \"application/json\")\n              .addHeader(\"X-Auth-Token\", authToken).build();\n\n      HttpResponse listInDetailServersResponse = HttpResponse.builder().statusCode(200)\n              .payload(payloadFromResource(\"/server_list_details_states.json\")).build();\n\n      NovaApi apiWhenServersExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n              responseWithKeystoneAccess, listServers, listInDetailServersResponse);\n\n      assertEquals(apiWhenServersExist.getConfiguredRegions(), ImmutableSet.of(\"az-1.region-a.geo-1\", \"az-2.region-a.geo-1\", \"az-3.region-a.geo-1\"));\n\n      assertEquals(apiWhenServersExist.getServerApi(\"az-1.region-a.geo-1\").listInDetail().concat().toString(),\n              new ParseServerDetailsStatesTest().expected().toString());\n   }\n\n   public void testCreateServerWhenResponseIs202() throws Exception {\n      HttpRequest createServer = HttpRequest.builder()\n            .method(\"POST\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken)\n            .payload(payloadFromStringWithContentType(\n                  \"{\\\"server\\\":{\\\"name\\\":\\\"test-e92\\\",\\\"imageRef\\\":\\\"1241\\\",\\\"flavorRef\\\":\\\"100\\\"}}\", \"application/json\"))\n            .build();\n\n      HttpResponse createServerResponse = HttpResponse.builder().statusCode(202).message(\"HTTP/1.1 202 Accepted\")\n            .payload(payloadFromResourceWithContentType(\"/new_server.json\", \"application/json; charset=UTF-8\")).build();\n\n      NovaApi apiWithNewServer = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, createServer, createServerResponse);\n\n      assertEquals(apiWithNewServer.getServerApi(\"az-1.region-a.geo-1\").create(\"test-e92\", \"1241\", \"100\").toString(),\n              new ParseCreatedServerTest().expected().toString());\n   }\n\n   public void testCreateServerInAvailabilityZoneWhenResponseIs202() throws Exception {\n      HttpRequest createServer = HttpRequest.builder()\n            .method(\"POST\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken)\n            .payload(payloadFromStringWithContentType(\n                  \"{\\\"server\\\":{\\\"name\\\":\\\"test-e92\\\",\\\"imageRef\\\":\\\"1241\\\",\\\"flavorRef\\\":\\\"100\\\",\\\"availability_zone\\\":\\\"nova\\\"}}\", \"application/json\"))\n            .build();\n\n      HttpResponse createServerResponse = HttpResponse.builder().statusCode(202).message(\"HTTP/1.1 202 Accepted\")\n            .payload(payloadFromResourceWithContentType(\"/new_server_in_zone.json\", \"application/json; charset=UTF-8\")).build();\n\n      NovaApi apiWithNewServer = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, createServer, createServerResponse);\n\n      CreateServerOptions options = new CreateServerOptions().availabilityZone(\"nova\");\n\n      assertEquals(apiWithNewServer.getServerApi(\"az-1.region-a.geo-1\").create(\"test-e92\", \"1241\", \"100\", options).toString(),\n            new ParseCreatedServerTest().expected().toString());\n   }\n\n   public void testCreateServerWithSecurityGroupsWhenResponseIs202() throws Exception {\n      HttpRequest createServer = HttpRequest.builder()\n         .method(\"POST\")\n         .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers\")\n         .addHeader(\"Accept\", \"application/json\")\n         .addHeader(\"X-Auth-Token\", authToken)\n         .payload(payloadFromStringWithContentType(\n               \"{\\\"server\\\":{\\\"name\\\":\\\"test-e92\\\",\\\"imageRef\\\":\\\"1241\\\",\\\"flavorRef\\\":\\\"100\\\",\\\"security_groups\\\":[{\\\"name\\\":\\\"group1\\\"},{\\\"name\\\":\\\"group2\\\"}]}}\", \"application/json\"))\n         .build();\n\n      HttpResponse createServerResponse = HttpResponse.builder().statusCode(202).message(\"HTTP/1.1 202 Accepted\")\n         .payload(payloadFromResourceWithContentType(\"/new_server.json\", \"application/json; charset=UTF-8\")).build();\n\n      NovaApi apiWithNewServer = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, createServer, createServerResponse);\n\n      assertEquals(apiWithNewServer.getServerApi(\"az-1.region-a.geo-1\").create(\"test-e92\", \"1241\",\n               \"100\", new CreateServerOptions().securityGroupNames(\"group1\", \"group2\")).toString(),\n              new ParseCreatedServerTest().expected().toString());\n   }\n\n   public void testCreateServerWithNetworksWhenResponseIs202() throws Exception {\n      HttpRequest createServer = HttpRequest.builder()\n         .method(\"POST\")\n         .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers\")\n         .addHeader(\"Accept\", \"application/json\")\n         .addHeader(\"X-Auth-Token\", authToken)\n         .payload(payloadFromStringWithContentType(\n               \"{\\\"server\\\":{\\\"name\\\":\\\"test-e92\\\",\\\"imageRef\\\":\\\"1241\\\",\\\"flavorRef\\\":\\\"100\\\",\\\"networks\\\":[{\\\"uuid\\\":\\\"b3856ac0-f481-11e2-b778-0800200c9a66\\\"},{\\\"uuid\\\":\\\"bf0f0f90-f481-11e2-b778-0800200c9a66\\\"}]}}\", \"application/json\"))\n         .build();\n\n      HttpResponse createServerResponse = HttpResponse.builder().statusCode(202).message(\"HTTP/1.1 202 Accepted\")\n         .payload(payloadFromResourceWithContentType(\"/new_server.json\", \"application/json; charset=UTF-8\")).build();\n\n      NovaApi apiWithNewServer = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, createServer, createServerResponse);\n\n      assertEquals(apiWithNewServer.getServerApi(\"az-1.region-a.geo-1\").create(\"test-e92\", \"1241\",\n               \"100\", new CreateServerOptions().networks(\"b3856ac0-f481-11e2-b778-0800200c9a66\", \"bf0f0f90-f481-11e2-b778-0800200c9a66\")).toString(),\n              new ParseCreatedServerTest().expected().toString());\n   }\n\n   public void testCreateServerWithBootVolumeWhenResponseIs202() throws Exception {\n      HttpRequest createServer = HttpRequest\n         .builder()\n         .method(\"POST\")\n         .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers\")\n         .addHeader(\"Accept\", \"application/json\")\n         .addHeader(\"X-Auth-Token\", authToken)\n         .payload(payloadFromStringWithContentType(\n                  \"{\\\"server\\\":{\\\"name\\\":\\\"test-e92\\\",\\\"imageRef\\\":\\\"\\\",\\\"flavorRef\\\":\\\"12345\\\",\\\"block_device_mapping_v2\\\":[{\\\"volume_size\\\":100,\\\"uuid\\\":\\\"f0c907a5-a26b-48ba-b803-83f6b7450ba5\\\",\\\"destination_type\\\":\\\"volume\\\",\\\"source_type\\\":\\\"image\\\"}]}}\", \"application/json\"))\n         .build();\n\n      HttpResponse createServerResponse = HttpResponse.builder().statusCode(202).message(\"HTTP/1.1 202 Accepted\")\n         .payload(payloadFromResourceWithContentType(\"/new_server.json\", \"application/json; charset=UTF-8\")).build();\n\n\n      NovaApi apiWithNewServer = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, createServer, createServerResponse);\n\n      BlockDeviceMapping blockDeviceMapping = BlockDeviceMapping.builder()\n            .uuid(\"f0c907a5-a26b-48ba-b803-83f6b7450ba5\").sourceType(\"image\").destinationType(\"volume\")\n            .volumeSize(100).build();\n\n      assertEquals(apiWithNewServer.getServerApi(\"az-1.region-a.geo-1\").create(\"test-e92\", \"\",\n               \"12345\", new CreateServerOptions().blockDeviceMappings(ImmutableSet.of(blockDeviceMapping))).toString(),\n              new ParseCreatedServerTest().expected().toString());\n   }\n\n   public void testCreateServerWithDiskConfigAuto() throws Exception {\n      HttpRequest createServer = HttpRequest.builder()\n         .method(\"POST\")\n         .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers\")\n         .addHeader(\"Accept\", \"application/json\")\n         .addHeader(\"X-Auth-Token\", authToken)\n         .payload(payloadFromStringWithContentType(\n               \"{\\\"server\\\":{\\\"name\\\":\\\"test-e92\\\",\\\"imageRef\\\":\\\"1241\\\",\\\"flavorRef\\\":\\\"100\\\",\\\"OS-DCF:diskConfig\\\":\\\"AUTO\\\"}}\", \"application/json\"))\n         .build();\n\n      HttpResponse createServerResponse = HttpResponse.builder().statusCode(202).message(\"HTTP/1.1 202 Accepted\")\n         .payload(payloadFromResourceWithContentType(\"/new_server_disk_config_auto.json\", \"application/json; charset=UTF-8\")).build();\n\n      NovaApi apiWithNewServer = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess,\n            createServer, createServerResponse);\n\n      assertEquals(apiWithNewServer.getServerApi(\"az-1.region-a.geo-1\").create(\"test-e92\", \"1241\",\n               \"100\", new CreateServerOptions().diskConfig(Server.DISK_CONFIG_AUTO)).toString(),\n              new ParseCreatedServerTest().expectedWithDiskConfig(Server.DISK_CONFIG_AUTO).toString());\n   }\n\n   public void testCreateServerWithDiskConfigManual() throws Exception {\n      HttpRequest createServer = HttpRequest.builder()\n         .method(\"POST\")\n         .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers\")\n         .addHeader(\"Accept\", \"application/json\")\n         .addHeader(\"X-Auth-Token\", authToken)\n         .payload(payloadFromStringWithContentType(\n               \"{\\\"server\\\":{\\\"name\\\":\\\"test-e92\\\",\\\"imageRef\\\":\\\"1241\\\",\\\"flavorRef\\\":\\\"100\\\",\\\"OS-DCF:diskConfig\\\":\\\"MANUAL\\\"}}\", \"application/json\"))\n         .build();\n\n      HttpResponse createServerResponse = HttpResponse.builder().statusCode(202).message(\"HTTP/1.1 202 Accepted\")\n         .payload(payloadFromResourceWithContentType(\"/new_server_disk_config_manual.json\", \"application/json; charset=UTF-8\")).build();\n\n      NovaApi apiWithNewServer = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess,\n            createServer, createServerResponse);\n\n      assertEquals(apiWithNewServer.getServerApi(\"az-1.region-a.geo-1\").create(\"test-e92\", \"1241\",\n               \"100\", new CreateServerOptions().diskConfig(Server.DISK_CONFIG_MANUAL)).toString(),\n              new ParseCreatedServerTest().expectedWithDiskConfig(Server.DISK_CONFIG_MANUAL).toString());\n   }\n\n   public void testRebuildServerWhenResponseIs202() throws Exception {\n      String serverId = \"52415800-8b69-11e0-9b19-734f565bc83b\";\n      HttpRequest rebuildServer = HttpRequest.builder()\n            .method(\"POST\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers/\" + serverId + \"/action\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken)\n            .payload(payloadFromStringWithContentType(\n                  \"{\\\"rebuild\\\":{\\\"adminPass\\\":\\\"password\\\",\\\"imageRef\\\":\\\"1234\\\",\\\"name\\\":\\\"newName\\\",\\\"accessIPv4\\\":\\\"1.1.1.1\\\",\\\"accessIPv6\\\":\\\"fe80::100\\\"}}\", \"application/json\"))\n            .build();\n\n      HttpResponse rebuildServerResponse = HttpResponse.builder().statusCode(202).build();\n\n      NovaApi apiRebuildServer = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, rebuildServer, rebuildServerResponse);\n\n      RebuildServerOptions options = new RebuildServerOptions().withImage(\"1234\").name(\"newName\").adminPass(\"password\").ipv4Address(\"1.1.1.1\").ipv6Address(\"fe80::100\");\n\n      apiRebuildServer.getServerApi(\"az-1.region-a.geo-1\").rebuild(serverId, options);\n   }\n\n   public void testCreateImageWhenResponseIs2xx() throws Exception {\n      String serverId = \"123\";\n      String imageId = \"456\";\n      String imageName = \"foo\";\n\n      HttpRequest createImage = HttpRequest.builder()\n            .method(\"POST\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers/\" + serverId + \"/action\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken)\n            .payload(payloadFromStringWithContentType(\n                  \"{\\\"createImage\\\":{\\\"name\\\":\\\"\" + imageName + \"\\\", \\\"metadata\\\": {}}}\", \"application/json\"))\n            .build();\n\n      HttpResponse createImageResponse = HttpResponse.builder()\n            .statusCode(200)\n            .headers(ImmutableMultimap.<String, String> builder()\n                  .put(\"Location\", \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/images/\" + imageId).build()).build();\n\n      NovaApi apiWhenServerExists = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n               responseWithKeystoneAccess, createImage, createImageResponse);\n\n      assertEquals(apiWhenServerExists.getServerApi(\"az-1.region-a.geo-1\").createImageFromServer(imageName, serverId),\n            imageId);\n   }\n\n   public void testStopServerWhenResponseIs2xx() throws Exception {\n      String serverId = \"123\";\n      HttpRequest stopServer = HttpRequest.builder()\n            .method(\"POST\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers/\" + serverId + \"/action\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken)\n            .payload(payloadFromStringWithContentType(\n                  \"{\\\"os-stop\\\":null}\", \"application/json\"))\n            .build();\n\n      HttpResponse stopServerResponse = HttpResponse.builder().statusCode(202).build();\n\n      NovaApi apiWhenServerExists = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n               responseWithKeystoneAccess, stopServer, stopServerResponse);\n\n      apiWhenServerExists.getServerApi(\"az-1.region-a.geo-1\").stop(serverId);\n   }\n\n   public void testStartServerWhenResponseIs2xx() throws Exception {\n      String serverId = \"123\";\n      HttpRequest startServer = HttpRequest\n            .builder()\n            .method(\"POST\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers/\" + serverId + \"/action\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken)\n            .payload(payloadFromStringWithContentType(\n                  \"{\\\"os-start\\\":null}\", \"application/json\"))\n            .build();\n\n      HttpResponse startServerResponse = HttpResponse.builder().statusCode(202).build();\n\n      NovaApi apiWhenServerExists = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n               responseWithKeystoneAccess, startServer, startServerResponse);\n\n      apiWhenServerExists.getServerApi(\"az-1.region-a.geo-1\").start(serverId);\n   }\n\n   public void testListMetadataWhenResponseIs2xx() throws Exception {\n      String serverId = \"123\";\n      HttpRequest getMetadata = HttpRequest.builder()\n            .method(\"GET\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers/\" + serverId + \"/metadata\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken)\n            .build();\n\n      HttpResponse getMetadataResponse = HttpResponse.builder().statusCode(200)\n              .payload(payloadFromResource(\"/metadata_list.json\")).build();\n\n      NovaApi apiWhenServerExists = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n               responseWithKeystoneAccess, getMetadata, getMetadataResponse);\n\n      assertEquals(apiWhenServerExists.getServerApi(\"az-1.region-a.geo-1\").getMetadata(serverId).toString(),\n             new ParseMetadataListTest().expected().toString());\n   }\n\n   public void testSetMetadataWhenResponseIs2xx() throws Exception {\n      String serverId = \"123\";\n      ImmutableMap<String, String> metadata = new ImmutableMap.Builder<String, String>()\n              .put(\"Server Label\", \"Web Head 1\")\n              .put(\"Image Version\", \"2.1\")\n              .build();\n\n      HttpRequest setMetadata = HttpRequest.builder()\n            .method(\"PUT\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers/\" + serverId + \"/metadata\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken)\n            .payload(payloadFromStringWithContentType(\n                  \"{\\\"metadata\\\":{\\\"Server Label\\\":\\\"Web Head 1\\\",\\\"Image Version\\\":\\\"2.1\\\"}}\", \"application/json\"))\n            .build();\n\n      HttpResponse setMetadataResponse = HttpResponse.builder().statusCode(200)\n              .payload(payloadFromResource(\"/metadata_list.json\")).build();\n\n      NovaApi apiWhenServerExists = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n               responseWithKeystoneAccess, setMetadata, setMetadataResponse);\n\n      assertEquals(apiWhenServerExists.getServerApi(\"az-1.region-a.geo-1\").setMetadata(serverId, metadata).toString(),\n             new ParseMetadataListTest().expected().toString());\n   }\n\n   public void testUpdateMetadataWhenResponseIs2xx() throws Exception {\n      String serverId = \"123\";\n      ImmutableMap<String, String> metadata = new ImmutableMap.Builder<String, String>()\n              .put(\"Server Label\", \"Web Head 2\")\n              .put(\"Server Description\", \"Simple Server\")\n              .build();\n\n      HttpRequest setMetadata = HttpRequest.builder()\n            .method(\"POST\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers/\" + serverId + \"/metadata\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken)\n            .payload(payloadFromStringWithContentType(\n                  \"{\\\"metadata\\\":{\\\"Server Label\\\":\\\"Web Head 2\\\",\\\"Server Description\\\":\\\"Simple Server\\\"}}\", \"application/json\"))\n            .build();\n\n      HttpResponse setMetadataResponse = HttpResponse.builder().statusCode(200)\n              .payload(payloadFromResource(\"/metadata_updated.json\")).build();\n\n      NovaApi apiWhenServerExists = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n               responseWithKeystoneAccess, setMetadata, setMetadataResponse);\n\n      assertEquals(apiWhenServerExists.getServerApi(\"az-1.region-a.geo-1\").updateMetadata(serverId, metadata).toString(),\n             new ParseMetadataUpdateTest().expected().toString());\n   }\n\n   public void testGetMetadataItemWhenResponseIs2xx() throws Exception {\n      String serverId = \"123\";\n      String key = \"Server Label\";\n\n      HttpRequest getMetadata = HttpRequest\n            .builder()\n            .method(\"GET\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers/\" + serverId + \"/metadata/\"\n                  + Strings2.urlEncode(key))\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken)\n            .build();\n\n      HttpResponse getMetadataResponse = HttpResponse.builder().statusCode(200)\n              .payload(payloadFromResource(\"/metadata_item.json\")).build();\n\n      NovaApi apiWhenServerExists = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n               responseWithKeystoneAccess, getMetadata, getMetadataResponse);\n\n      assertEquals(apiWhenServerExists.getServerApi(\"az-1.region-a.geo-1\").getMetadata(serverId, key).toString(),\n             \"Web Head 1\");\n   }\n\n   public void testSetMetadataItemWhenResponseIs2xx() throws Exception {\n      String serverId = \"123\";\n      ImmutableMap<String, String> metadata = new ImmutableMap.Builder<String, String>()\n              .put(\"Server Label\", \"Web Head 2\")\n              .put(\"Server Description\", \"Simple Server\")\n              .build();\n\n      HttpRequest setMetadata = HttpRequest.builder()\n            .method(\"POST\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers/\" + serverId + \"/metadata\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken)\n            .payload(payloadFromStringWithContentType(\n                  \"{\\\"metadata\\\":{\\\"Server Label\\\":\\\"Web Head 2\\\",\\\"Server Description\\\":\\\"Simple Server\\\"}}\", \"application/json\"))\n            .build();\n\n      HttpResponse setMetadataResponse = HttpResponse.builder().statusCode(200)\n              .payload(payloadFromResource(\"/metadata_updated.json\")).build();\n\n      NovaApi apiWhenServerExists = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n               responseWithKeystoneAccess, setMetadata, setMetadataResponse);\n\n      assertEquals(apiWhenServerExists.getServerApi(\"az-1.region-a.geo-1\").updateMetadata(serverId, metadata).toString(),\n             new ParseMetadataUpdateTest().expected().toString());\n   }\n\n   public void testDeleteMetadataItemWhenResponseIs2xx() throws Exception {\n      String serverId = \"123\";\n      String key = \"Server Label\";\n\n      HttpRequest updateMetadata = HttpRequest.builder()\n            .method(\"DELETE\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers/\" + serverId + \"/metadata/\" +\n                  Strings2.urlEncode(key))\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken)\n            .build();\n\n      HttpResponse updateMetadataResponse = HttpResponse.builder().statusCode(204).build();\n\n      NovaApi apiWhenServerExists = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n               responseWithKeystoneAccess, updateMetadata, updateMetadataResponse);\n\n      apiWhenServerExists.getServerApi(\"az-1.region-a.geo-1\").deleteMetadata(serverId, key);\n   }\n\n   public void testGetDiagnosticsWhenResponseIs200() throws Exception {\n       String serverId = \"123\";\n       HttpRequest getDiagnostics = HttpRequest.builder()\n            .method(\"GET\")\n            .addHeader(\"Accept\", \"application/json\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers/\" + serverId + \"/diagnostics\")\n            .addHeader(\"X-Auth-Token\", authToken)\n            .build();\n\n      HttpResponse serverDiagnosticsResponse = HttpResponse.builder().statusCode(202).message(\"HTTP/1.1 202 Accepted\")\n            .payload(payloadFromResourceWithContentType(\"/server_diagnostics.json\", \"application/json; charset=UTF-8\")).build();\n\n      NovaApi apiWithNewServer = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess, getDiagnostics, serverDiagnosticsResponse);\n      assertEquals(apiWithNewServer.getServerApi(\"az-1.region-a.geo-1\").getDiagnostics(serverId),\n             new ParseServerDiagnostics().expected());\n   }\n\n   public void testGetDiagnosticsWhenResponseIs403Or404Or500() throws Exception {\n       String serverId = \"123\";\n       HttpRequest getDiagnostics = HttpRequest.builder()\n            .method(\"GET\")\n            .addHeader(\"Accept\", \"application/json\")\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers/\" + serverId + \"/diagnostics\")\n            .addHeader(\"X-Auth-Token\", authToken)\n            .build();\n\n      for (int statusCode : ImmutableSet.of(403, 404, 500)) {\n        assertTrue(!requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, getDiagnostics,\n            HttpResponse.builder().statusCode(statusCode).build()).getServerApi(\"az-1.region-a.geo-1\").getDiagnostics(serverId).isPresent());\n      }\n   }\n\n   public void testListSecurityGroupsForServerWhenResponseIs200() throws Exception {\n      String serverId = \"123\";\n      HttpRequest getDiagnostics = HttpRequest.builder()\n              .method(\"GET\")\n              .addHeader(\"Accept\", \"application/json\")\n              .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers/\" + serverId + \"/os-security-groups\")\n              .addHeader(\"X-Auth-Token\", authToken)\n              .build();\n\n      HttpResponse serverDiagnosticsResponse = HttpResponse.builder().statusCode(202).message(\"HTTP/1.1 202 Accepted\")\n              .payload(payloadFromResourceWithContentType(\"/securitygroup_list.json\", \"application/json; charset=UTF-8\")).build();\n\n      NovaApi apiWithNewServer = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n              responseWithKeystoneAccess, getDiagnostics, serverDiagnosticsResponse);\n      assertEquals(Iterables.toString(apiWithNewServer.getServerApi(\"az-1.region-a.geo-1\").listSecurityGroupForServer(serverId)),\n              Iterables.toString(new ParseSecurityGroupListTest().expected()));\n   }\n\n   public void testListSecurityGroupsForServerWhenResponseIs404() throws Exception {\n      String serverId = \"123\";\n      HttpRequest getSecurityGroups = HttpRequest.builder()\n              .method(\"GET\")\n              .addHeader(\"Accept\", \"application/json\")\n              .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers/\" + serverId + \"/os-security-groups\")\n              .addHeader(\"X-Auth-Token\", authToken)\n              .build();\n\n      assertTrue(requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, getSecurityGroups,\n              HttpResponse.builder().statusCode(404).build()).getServerApi(\"az-1.region-a.geo-1\").listSecurityGroupForServer(serverId).isEmpty());\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/features/ServerApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.features;\n\nimport static org.jclouds.openstack.nova.v2_0.domain.Server.Status.ACTIVE;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.openstack.nova.v2_0.domain.BlockDeviceMapping;\nimport org.jclouds.openstack.nova.v2_0.domain.Network;\nimport org.jclouds.openstack.nova.v2_0.domain.SecurityGroup;\nimport org.jclouds.openstack.nova.v2_0.domain.Server;\nimport org.jclouds.openstack.nova.v2_0.domain.ServerCreated;\nimport org.jclouds.openstack.nova.v2_0.extensions.AvailabilityZoneApi;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiLiveTest;\nimport org.jclouds.openstack.nova.v2_0.options.CreateServerOptions;\nimport org.jclouds.openstack.nova.v2_0.options.RebuildServerOptions;\nimport org.jclouds.openstack.v2_0.domain.Link.Relation;\nimport org.jclouds.openstack.v2_0.domain.Resource;\nimport org.jclouds.openstack.v2_0.features.ExtensionApi;\nimport org.jclouds.openstack.v2_0.predicates.LinkPredicates;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\n\n/**\n * Tests behavior of {@link ServerApi}\n */\n@Test(groups = \"live\", testName = \"ServerApiLiveTest\")\npublic class ServerApiLiveTest extends BaseNovaApiLiveTest {\n\n   @Test(description = \"GET /v${apiVersion}/{tenantId}/servers\")\n   public void testListServers() throws Exception {\n      for (String regionId : regions) {\n         ServerApi serverApi = api.getServerApi(regionId);\n         for (Resource server : serverApi.list().concat()) {\n            checkResource(server);\n         }\n      }\n   }\n\n   @Test(description = \"GET /v${apiVersion}/{tenantId}/servers/detail\")\n   public void testListServersInDetail() throws Exception {\n      for (String regionId : regions) {\n         ServerApi serverApi = api.getServerApi(regionId);\n         for (Server server : serverApi.listInDetail().concat()) {\n            checkServer(server);\n         }\n      }\n   }\n\n   @Test(description = \"GET /v${apiVersion}/{tenantId}/servers/{id}\", dependsOnMethods = {\"testListServersInDetail\"})\n   public void testGetServerById() throws Exception {\n      for (String regionId : regions) {\n         ServerApi serverApi = api.getServerApi(regionId);\n         for (Resource server : serverApi.list().concat()) {\n            Server details = serverApi.get(server.getId());\n            assertEquals(details.getId(), server.getId());\n            assertEquals(details.getName(), server.getName());\n            assertEquals(details.getLinks(), server.getLinks());\n            checkServer(details);\n         }\n      }\n   }\n\n   @Test\n   public void testCreateInAvailabilityZone() {\n      String serverId = null;\n      String availabilityZone;\n\n      for (String regionId : regions) {\n         ServerApi serverApi = api.getServerApi(regionId);\n         Optional<? extends AvailabilityZoneApi> availabilityZoneApi = api.getAvailabilityZoneApi(regionId);\n         availabilityZone = availabilityZoneApi.isPresent() ? Iterables.get(availabilityZoneApi.get().list(), 0).getName() : \"nova\";\n         try {\n            serverId = createServer(regionId, availabilityZone).getId();\n            Server server = serverApi.get(serverId);\n            assertEquals(server.getStatus(), ACTIVE);\n         } finally {\n            if (serverId != null) {\n               serverApi.delete(serverId);\n            }\n         }\n      }\n   }\n\n   /**\n    * This needs to be supported by the provider, and is usually not supported.\n    * However this can be tested on devstack:\n    * In apis/openstack-nova:\n    * mvn -Plive clean install \"-Dtest.openstack-nova.endpoint=http://localhost:5000/v2.0\" \"-Dtest.openstack-nova.identity=demo:demo\" \"-Dtest.openstack-nova.credential=devstack\" \"-Dtest=org.jclouds.openstack.nova.v2_0.features.ServerApiLiveTest#testCreateWithNetworkOptions\"\n    */\n   @Test(enabled = false)\n   public void testCreateWithNetworkOptions() {\n      String serverId = null;\n      for (String regionId : regions) {\n         ServerApi serverApi = api.getServerApi(regionId);\n         try {\n            CreateServerOptions options = CreateServerOptions.Builder.novaNetworks(\n                  // This network UUID must match an existing network.\n                  ImmutableSet.of(Network.builder().networkUuid(\"bc4cfa2b-2b27-4671-8e8f-73009623def0\").fixedIp(\"192.168.55.56\").build())\n            );\n            ServerCreated server = serverApi.create(hostName, imageId(regionId), \"1\", options);\n            serverId = server.getId();\n\n            Server serverCheck = serverApi.get(serverId);\n            assertEquals(serverCheck.getStatus(), ACTIVE);\n         } finally {\n            if (serverId != null) {\n               serverApi.delete(serverId);\n            }\n         }\n      }\n   }\n\n   /**\n    * This test creates a new server with a boot device from an image.\n    * <p/>\n    * This needs to be supported by the provider, and is usually not supported.\n    * <p/>\n    * TODO: Configurable system properties for flavor/image refs.\n    */\n   @Test\n   public void testCreateWithBlockDeviceMapping() {\n      String serverId = null;\n      // Rackspace Performance Flavor\n      String flavorRef = \"performance1-2\";\n      // Rackspace CentOS 6.5 image\n      String imageRef = \"3ab30cc6-c503-41d3-8a37-106fda7848a7\";\n      for (String regionId : regions) {\n         ServerApi serverApi = api.getServerApi(regionId);\n         ExtensionApi extensionApi = api.getExtensionApi(regionId);\n\n         // check for the existence of the block mapping v2 boot extension\n         if (extensionApi.get(\"os-block-device-mapping-v2-boot\") != null) {\n            try {\n               BlockDeviceMapping blockDeviceMappings = BlockDeviceMapping.builder()\n                     .uuid(imageRef).sourceType(\"image\").destinationType(\"volume\")\n                     .volumeSize(100).bootIndex(0).build();\n\n               CreateServerOptions options = CreateServerOptions.Builder\n                     .blockDeviceMappings(ImmutableSet.of(blockDeviceMappings));\n\n               ServerCreated server = serverApi.create(hostName, \"\", flavorRef, options);\n               serverId = server.getId();\n               Server serverCheck = serverApi.get(serverId);\n               assertEquals(serverCheck.getStatus(), ACTIVE);\n            } finally {\n               if (serverId != null) {\n                  serverApi.delete(serverId);\n               }\n            }\n         }\n      }\n   }\n\n   @Test\n   public void testCreateInWrongAvailabilityZone() {\n      String serverId = null;\n      for (String regionId : regions) {\n         ServerApi serverApi = api.getServerApi(regionId);\n         try {\n            serverId = createServer(regionId, \"err\").getId();\n         } catch (HttpResponseException e) {\n            // Here is an implementation detail difference between OpenStack and some providers.\n            // Some providers accept a bad availability zone and create the server in the zoneId.\n            // Vanilla OpenStack will error out with a 400 Bad Request\n            assertEquals(e.getResponse().getStatusCode(), 400);\n         } finally {\n            if (serverId != null) {\n               serverApi.delete(serverId);\n            }\n         }\n      }\n   }\n\n   @Test\n   public void testRebuildServer() {\n      String serverId = null;\n      for (String regionId : regions) {\n         ServerApi serverApi = api.getServerApi(regionId);\n         try {\n            serverId = createServer(regionId, null).getId();\n\n            Server server = serverApi.get(serverId);\n\n            assertEquals(server.getStatus(), ACTIVE);\n\n            RebuildServerOptions options = new RebuildServerOptions().\n                  withImage(server.getImage().getId()).\n                  name(\"newName\").\n                  adminPass(\"password\").\n                  ipv4Address(\"1.1.1.1\").\n                  ipv6Address(\"fe80::100\");\n\n            serverApi.rebuild(serverId, options);\n\n            Server rebuiltServer = serverApi.get(serverId);\n\n            assertEquals(\"newName\", rebuiltServer.getName());\n            assertEquals(\"1.1.1.1\", rebuiltServer.getAccessIPv4());\n            assertEquals(\"fe80::100\", rebuiltServer.getAccessIPv6());\n\n         } finally {\n            if (serverId != null) {\n               serverApi.delete(serverId);\n            }\n         }\n      }\n   }\n\n   @Test(description = \"GET /v${apiVersion}/servers/{id}/os-security-groups\")\n   public void testListSecurityGroupForServer() throws Exception {\n      for (String regionId : regions) {\n         ServerApi serverApi = api.getServerApi(regionId);\n         for (Resource server : serverApi.list().concat()) {\n            for (SecurityGroup securityGroup : serverApi.listSecurityGroupForServer(server.getId())) {\n               checkSecurityGroup(securityGroup);\n            }\n         }\n      }\n   }\n\n   private Server createServer(String regionId, String availabilityZoneId) {\n      ServerApi serverApi = api.getServerApi(regionId);\n\n      CreateServerOptions options = new CreateServerOptions();\n      if (availabilityZoneId != null) {\n         options = options.availabilityZone(availabilityZoneId);\n      }\n\n      ServerCreated server = serverApi.create(hostName, imageId(regionId), flavorId(regionId), options);\n\n      return serverApi.get(server.getId());\n   }\n\n   private void checkResource(Resource resource) {\n      assertNotNull(resource.getId());\n      assertNotNull(resource.getName());\n      assertNotNull(resource.getLinks());\n      assertTrue(Iterables.any(resource.getLinks(), LinkPredicates.relationEquals(Relation.SELF)));\n   }\n\n   private void checkServer(Server server) {\n      checkResource(server);\n      assertNotNull(server.getFlavor());\n   }\n\n   private void checkSecurityGroup(SecurityGroup securityGroup) {\n      assertNotNull(securityGroup.getId());\n      assertNotNull(securityGroup.getName());\n      assertNotNull(securityGroup.getRules());\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/functions/CreateSecurityGroupIfNeededTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\nimport java.util.Map;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Functions;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.inject.Injector;\nimport org.jclouds.compute.domain.SecurityGroupBuilder;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.net.domain.IpPermission;\nimport org.jclouds.net.domain.IpProtocol;\nimport org.jclouds.openstack.nova.v2_0.NovaApi;\nimport org.jclouds.openstack.nova.v2_0.compute.functions.CreateSecurityGroupIfNeeded;\nimport org.jclouds.openstack.nova.v2_0.compute.functions.NeutronSecurityGroupToSecurityGroup;\nimport org.jclouds.openstack.nova.v2_0.compute.functions.NovaSecurityGroupInRegionToSecurityGroup;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.RegionSecurityGroupNameAndPorts;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.SecurityGroupInRegion;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiExpectTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMap.Builder;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\", testName = \"CreateSecurityGroupIfNeededTest\")\npublic class CreateSecurityGroupIfNeededTest extends BaseNovaApiExpectTest {\n   HttpRequest create = HttpRequest.builder().method(\"POST\").endpoint(\n            URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-security-groups\")).headers(\n            ImmutableMultimap.<String, String> builder().put(\"Accept\", \"application/json\").put(\"X-Auth-Token\",\n                     authToken).build())\n            .payload(\n                     payloadFromStringWithContentType(\n                              \"{\\\"security_group\\\":{\\\"name\\\":\\\"jclouds_mygroup\\\",\\\"description\\\":\\\"jclouds_mygroup\\\"}}\",\n                              \"application/json\")).build();\n\n   Location provider = new LocationBuilder().scope(LocationScope.PROVIDER).id(\"openstack-nova\").description(\n           \"openstack-nova\").build();\n   Location region = new LocationBuilder().id(\"az-1.region-a.geo-1\").description(\"az-1.region-a.geo-1\").scope(\n           LocationScope.REGION).parent(provider).build();\n   Supplier<Map<String, Location>> locationIndex = Suppliers.<Map<String, Location>> ofInstance(ImmutableMap\n           .<String, Location> of(\"az-1.region-a.geo-1\", region));\n\n   Function<SecurityGroupInRegion, org.jclouds.compute.domain.SecurityGroup> securityGroupInRegionSecurityGroupFunction = new NovaSecurityGroupInRegionToSecurityGroup(locationIndex);\n\n   Injector injector = createInjector(Functions.forMap(ImmutableMap.<HttpRequest, HttpResponse>of()), createModule(), setupProperties());\n   NeutronSecurityGroupToSecurityGroup.Factory factory = injector.getInstance(NeutronSecurityGroupToSecurityGroup.Factory.class);\n\n   private final int groupId = 2769;\n\n   public void testCreateNewGroup() throws Exception {\n\n      Builder<HttpRequest, HttpResponse> builder = ImmutableMap.builder();\n\n      builder.put(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess);\n      builder.put(extensionsOfNovaRequest, extensionsOfNovaResponse);\n\n      HttpResponse createResponse = HttpResponse.builder().statusCode(200)\n               .payload(\n                        payloadFromStringWithContentType(\n                                 String.format(\"{\\\"security_group\\\": {\\\"rules\\\": [], \\\"tenant_id\\\": \\\"37936628937291\\\", \\\"id\\\": %s, \\\"name\\\": \\\"jclouds_mygroup\\\", \\\"description\\\": \\\"jclouds_mygroup\\\"}}\", groupId),\n                                 \"application/json; charset=UTF-8\")).build();\n\n      builder.put(create, createResponse);\n\n      int ruleId = 10331;\n\n      for (int port : ImmutableList.of(22, 8080)) {\n\n         HttpRequest createCidrRule = HttpRequest.builder().method(\"POST\").endpoint(\n                  URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-security-group-rules\")).headers(\n                  ImmutableMultimap.<String, String> builder().put(\"Accept\", \"application/json\").put(\"X-Auth-Token\",\n                           authToken).build())\n                  .payload(\n                           payloadFromStringWithContentType(\n                                    String.format(\"{\\\"security_group_rule\\\":{\\\"parent_group_id\\\":\\\"%s\\\",\\\"cidr\\\":\\\"0.0.0.0/0\\\",\\\"ip_protocol\\\":\\\"tcp\\\",\\\"from_port\\\":\\\"%d\\\",\\\"to_port\\\":\\\"%d\\\"}}\",\n                                                      groupId, port, port), \"application/json\")).build();\n\n         HttpResponse createCidrRuleResponse = HttpResponse.builder().statusCode(200)\n                  .payload(\n                           payloadFromStringWithContentType(\n                                    String.format(\"{\\\"security_group_rule\\\": {\\\"from_port\\\": %d, \\\"group\\\": {}, \\\"ip_protocol\\\": \\\"tcp\\\", \\\"to_port\\\": %d, \\\"parent_group_id\\\": %d, \\\"ip_range\\\": {\\\"cidr\\\": \\\"0.0.0.0/0\\\"}, \\\"id\\\": %d}}\",\n                                             port, port, groupId, ruleId++), \"application/json; charset=UTF-8\")).build();\n\n         builder.put(createCidrRule, createCidrRuleResponse);\n\n         HttpRequest createSelfRule = HttpRequest.builder().method(\"POST\").endpoint(\n                  URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-security-group-rules\")).headers(\n                  ImmutableMultimap.<String, String> builder().put(\"Accept\", \"application/json\").put(\"X-Auth-Token\",\n                           authToken).build())\n                  .payload(\n                           payloadFromStringWithContentType(\n                                    String.format(\"{\\\"security_group_rule\\\":{\\\"group_id\\\":\\\"%d\\\",\\\"parent_group_id\\\":\\\"%d\\\",\\\"ip_protocol\\\":\\\"tcp\\\",\\\"from_port\\\":\\\"%d\\\",\\\"to_port\\\":\\\"%d\\\"}}\",\n                                                      groupId, groupId, port, port), \"application/json\")).build();\n\n         // note server responds with group name in the rule!!\n         HttpResponse createSelfRuleResponse = HttpResponse.builder().statusCode(200)\n                  .payload(\n                           payloadFromStringWithContentType(\n                                    String.format(\"{\\\"security_group_rule\\\": {\\\"from_port\\\": %d, \\\"group\\\": {\\\"tenant_id\\\": \\\"37936628937291\\\", \\\"name\\\": \\\"jclouds_mygroup\\\"}, \\\"ip_protocol\\\": \\\"tcp\\\", \\\"to_port\\\": %d, \\\"parent_group_id\\\": %d, \\\"ip_range\\\": {}, \\\"id\\\": %d}}\",\n                                             port, port, groupId, ruleId++), \"application/json; charset=UTF-8\")).build();\n\n         builder.put(createSelfRule, createSelfRuleResponse);\n      }\n\n      HttpRequest getSecurityGroup = HttpRequest.builder().method(\"GET\").endpoint(\n               URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-security-groups/\" + groupId)).headers(\n               ImmutableMultimap.<String, String> builder().put(\"Accept\", \"application/json\").put(\"X-Auth-Token\",\n                        authToken).build()).build();\n\n      HttpResponse getSecurityGroupResponse = HttpResponse.builder().statusCode(200).payload(\n               payloadFromResource(\"/securitygroup_details_computeservice_typical.json\")).build();\n\n      builder.put(getSecurityGroup, getSecurityGroupResponse);\n\n\n      HttpRequest listSecurityGroups = HttpRequest.builder().method(\"GET\").endpoint(\n         URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-security-groups\")).headers(\n         ImmutableMultimap.<String, String> builder().put(\"Accept\", \"application/json\").put(\"X-Auth-Token\",\n            authToken).build()).build();\n      HttpResponse listSecurityGroupsResponse = HttpResponse.builder().statusCode(200).payload(\n         payloadFromResource(\"/securitygroup_list_details_computeservice_typical.json\")).build();\n      builder.put(listSecurityGroups, listSecurityGroupsResponse);\n\n      NovaApi apiCanCreateSecurityGroup = requestsSendResponses(builder.build());\n\n      CreateSecurityGroupIfNeeded fn = new CreateSecurityGroupIfNeeded(apiCanCreateSecurityGroup, locationIndex, securityGroupInRegionSecurityGroupFunction, factory);\n\n      // we can find it\n      org.jclouds.compute.domain.SecurityGroup expected = new SecurityGroupBuilder()\n              .id(\"az-1.region-a.geo-1/2769\")\n              .providerId(\"2769\")\n              .name(\"jclouds_mygroup\")\n              .location(locationIndex.get().get(\"az-1.region-a.geo-1\"))\n              .ipPermissions(ImmutableList.of(\n                      IpPermission.builder()\n                      .ipProtocol(IpProtocol.TCP)\n                      .fromPort(22)\n                      .toPort(22)\n                      .cidrBlock(\"0.0.0.0/0\")\n                      .build(),\n                      IpPermission.builder()\n                              .ipProtocol(IpProtocol.TCP)\n                              .fromPort(22)\n                              .toPort(22)\n                              .groupIds(ImmutableList.of(\"az-1.region-a.geo-1/2769\"))\n                              .build(),\n                      IpPermission.builder()\n                              .ipProtocol(IpProtocol.TCP)\n                              .fromPort(8080)\n                              .toPort(8080)\n                              .cidrBlock(\"0.0.0.0/0\")\n                              .build(),\n                      IpPermission.builder()\n                              .ipProtocol(IpProtocol.TCP)\n                              .fromPort(8080)\n                              .toPort(8080)\n                              .groupIds(ImmutableList.of(\"az-1.region-a.geo-1/2769\"))\n                              .build()\n              )\n      )\n      .build();\n\n      assertEquals(\n              fn.apply(new RegionSecurityGroupNameAndPorts(\"az-1.region-a.geo-1\", \"jclouds_mygroup\", ImmutableSet.of(22, 8080))).toString(),\n              expected.toString().trim());\n\n   }\n\n   public void testReturnExistingGroupOnAlreadyExists() throws Exception {\n\n      Builder<HttpRequest, HttpResponse> builder = ImmutableMap.builder();\n\n      builder.put(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess);\n      builder.put(extensionsOfNovaRequest, extensionsOfNovaResponse);\n\n      HttpResponse createResponse = HttpResponse.builder().statusCode(400)\n               .payload(\n                        payloadFromStringWithContentType(\n                                 \"{\\\"badRequest\\\": {\\\"message\\\": \\\"Security group test already exists\\\", \\\"code\\\": 400}}\",\n                                 \"application/json; charset=UTF-8\")).build();\n\n      builder.put(create, createResponse);\n\n      HttpRequest list = HttpRequest.builder().method(\"GET\").endpoint(\n               URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-security-groups\")).headers(\n               ImmutableMultimap.<String, String> builder().put(\"Accept\", \"application/json\").put(\"X-Auth-Token\",\n                        authToken).build()).build();\n\n      HttpResponse listResponse = HttpResponse.builder().statusCode(200).payload(\n               payloadFromResource(\"/securitygroup_list_details_computeservice_typical.json\")).build();\n\n      builder.put(list, listResponse);\n\n      NovaApi apiWhenSecurityGroupsExist = requestsSendResponses(builder.build());\n\n      CreateSecurityGroupIfNeeded fn = new CreateSecurityGroupIfNeeded(apiWhenSecurityGroupsExist, locationIndex, securityGroupInRegionSecurityGroupFunction, factory);\n\n      // we can find it\n      org.jclouds.compute.domain.SecurityGroup expected = new SecurityGroupBuilder()\n              .id(\"az-1.region-a.geo-1/2769\")\n              .providerId(\"2769\")\n              .name(\"jclouds_mygroup\")\n              .location(locationIndex.get().get(\"az-1.region-a.geo-1\"))\n              .ipPermissions(ImmutableList.of(\n                      IpPermission.builder()\n                              .ipProtocol(IpProtocol.TCP)\n                              .fromPort(22)\n                              .toPort(22)\n                              .cidrBlock(\"0.0.0.0/0\")\n                              .build(),\n                      IpPermission.builder()\n                              .ipProtocol(IpProtocol.TCP)\n                              .fromPort(22)\n                              .toPort(22)\n                              .groupIds(ImmutableList.of(\"az-1.region-a.geo-1/2769\"))\n                              .build(),\n                      IpPermission.builder()\n                              .ipProtocol(IpProtocol.TCP)\n                              .fromPort(8080)\n                              .toPort(8080)\n                              .cidrBlock(\"0.0.0.0/0\")\n                              .build(),\n                      IpPermission.builder()\n                              .ipProtocol(IpProtocol.TCP)\n                              .fromPort(8080)\n                              .toPort(8080)\n                              .groupIds(ImmutableList.of(\"az-1.region-a.geo-1/2769\"))\n                              .build()\n                      )\n              )\n              .build();\n      assertEquals(\n              fn.apply(new RegionSecurityGroupNameAndPorts(\"az-1.region-a.geo-1\", \"jclouds_mygroup\", ImmutableSet.of(22, 8080))).toString(),\n              expected.toString().trim()\n      );\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/functions/FindSecurityGroupWithNameAndReturnTrueExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.functions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.Set;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.nova.v2_0.NovaApi;\nimport org.jclouds.openstack.nova.v2_0.domain.SecurityGroup;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.RegionAndName;\nimport org.jclouds.openstack.nova.v2_0.domain.regionscoped.SecurityGroupInRegion;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiExpectTest;\nimport org.jclouds.openstack.nova.v2_0.parse.ParseSecurityGroupListTest;\nimport org.jclouds.openstack.nova.v2_0.predicates.FindSecurityGroupWithNameAndReturnTrue;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.Iterables;\nimport com.google.common.util.concurrent.Atomics;\n\n@Test(groups = \"unit\", testName = \"FindSecurityGroupWithNameAndReturnTrueExpectTest\")\npublic class FindSecurityGroupWithNameAndReturnTrueExpectTest extends BaseNovaApiExpectTest {\n\n   public void testUpdateReferenceWhenSecurityGroupListContainsGroupName() throws Exception {\n      HttpRequest list = HttpRequest.builder().method(\"GET\").endpoint(\n               URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-security-groups\")).headers(\n               ImmutableMultimap.<String, String> builder().put(\"Accept\", \"application/json\").put(\"X-Auth-Token\",\n                        authToken).build()).build();\n\n      HttpResponse listResponse = HttpResponse.builder().statusCode(200).payload(\n               payloadFromResource(\"/securitygroup_list.json\")).build();\n\n      NovaApi apiWhenSecurityGroupsExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n               responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, list,\n               listResponse);\n\n      FindSecurityGroupWithNameAndReturnTrue predicate = new FindSecurityGroupWithNameAndReturnTrue(\n               apiWhenSecurityGroupsExist);\n\n      AtomicReference<RegionAndName> securityGroupInRegionRef = Atomics.newReference(RegionAndName\n               .fromRegionAndName(\"az-1.region-a.geo-1\", \"name1\"));\n\n      // we can find it\n      assertTrue(predicate.apply(securityGroupInRegionRef));\n\n      // the reference is now up to date, and includes the actual group found.\n      final Set<SecurityGroup> expected = new ParseSecurityGroupListTest().expected();\n      assertEquals(\n         securityGroupInRegionRef.get().toString(),\n         new SecurityGroupInRegion(Iterables.getOnlyElement(expected), \"az-1.region-a.geo-1\", expected).toString());\n   }\n\n   public void testDoesNotUpdateReferenceWhenSecurityGroupListMissingGroupName() throws Exception {\n      HttpRequest list = HttpRequest.builder().method(\"GET\").endpoint(\n               URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-security-groups\")).headers(\n               ImmutableMultimap.<String, String> builder().put(\"Accept\", \"application/json\").put(\"X-Auth-Token\",\n                        authToken).build()).build();\n\n      HttpResponse listResponse = HttpResponse.builder().statusCode(200).payload(\n               payloadFromResource(\"/securitygroup_list.json\")).build();\n\n      NovaApi apiWhenSecurityGroupsExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName,\n               responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, list,\n               listResponse);\n\n      FindSecurityGroupWithNameAndReturnTrue predicate = new FindSecurityGroupWithNameAndReturnTrue(\n               apiWhenSecurityGroupsExist);\n\n      RegionAndName regionAndGroup = RegionAndName.fromRegionAndName(\"az-1.region-a.geo-1\", \"name2\");\n\n      AtomicReference<RegionAndName> securityGroupInRegionRef = Atomics.newReference(regionAndGroup);\n\n      // we cannot find it\n      assertFalse(predicate.apply(securityGroupInRegionRef));\n\n      // the reference is the same\n      assertEquals(securityGroupInRegionRef.get(), regionAndGroup);\n\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/functions/InternalURLLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.functions;\n\nimport static org.jclouds.Constants.PROPERTY_CONNECTION_TIMEOUT;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.Properties;\n\nimport org.jclouds.openstack.keystone.catalog.config.InternalUrlModule;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiLiveTest;\nimport org.testng.Assert;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n/**\n * Simple live test to check the correct loading of the internal endpoint\n * services.\n *\n *\n */\n@Test(groups = \"live\", testName = \"InternalURLLiveTest\")\npublic class InternalURLLiveTest extends BaseNovaApiLiveTest {\n\n   @Test(description = \"InternalUrl service endpoints loader\")\n   public void testGetInternalUrlServiceEndpoint() throws Exception {\n      String region = api.getConfiguredRegions().iterator().next();\n      // List current servers to ensure that can reach nova with internalUrl ip\n      try {\n         assertNotNull(api.getServerApi(region).list().concat().toList());\n      } catch (Exception e) {\n         Assert.fail(\"Could not retrieve servers list using the internalUrl\", e);\n      }\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties properties = super.setupProperties();\n      properties.setProperty(PROPERTY_CONNECTION_TIMEOUT, \"5000\");\n      return properties;\n   }\n\n   @Override\n   protected Iterable<Module> setupModules() {\n      return ImmutableSet.<Module> of(getLoggingModule(), new InternalUrlModule());\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/handlers/NovaErrorHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.handlers;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.concurrent.TimeUnit;\n\nimport org.jclouds.date.DateCodec;\nimport org.jclouds.date.internal.DateServiceDateCodecFactory.DateServiceIso8601SecondsCodec;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.fallbacks.HeaderToRetryAfterException;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.json.internal.GsonWrapper;\nimport org.jclouds.openstack.nova.v2_0.functions.OverLimitParser;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.InsufficientResourcesException;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.jclouds.rest.RetryAfterException;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Ticker;\nimport com.google.gson.Gson;\n\n@Test(groups = \"unit\", testName = \"NovaErrorHandlerTest\", singleThreaded = true)\npublic class NovaErrorHandlerTest {\n   \n   private HttpCommand command;\n\n   @BeforeTest\n   void setupCommand() {\n      command = command();\n   }\n   \n   @Test\n   public void test401MakesAuthorizationException() {\n      fn.handleError(command, HttpResponse.builder().statusCode(401).message(\"Unauthorized\").build());\n\n      assertEquals(command.getException().getClass(), AuthorizationException.class);\n      assertEquals(command.getException().getMessage(),\n            \"POST https://nova/v2/servers HTTP/1.1 -> HTTP/1.1 401 Unauthorized\");\n   }\n   \n   @Test\n   public void test404MakesResourceNotFoundException() {\n      fn.handleError(command, HttpResponse.builder().statusCode(404).message(\"Not Found\").build());\n\n      assertEquals(command.getException().getClass(), ResourceNotFoundException.class);\n      assertEquals(command.getException().getMessage(),\n            \"POST https://nova/v2/servers HTTP/1.1 -> HTTP/1.1 404 Not Found\");\n   }\n\n   // should wait until ips are associated w/the server\n   HttpResponse noFixedIps = HttpResponse.builder().statusCode(400)\n         .message(\"HTTP/1.1 400 Bad Request\")\n         .payload(\"{\\\"badRequest\\\": {\\\"message\\\": \" +\n                  \"\\\"instance |71554| has no fixed_ips. unable to associate floating ip\\\", \\\"code\\\": 400}}\")\n         .build();\n   \n   @Test\n   public void test400MakesIllegalStateExceptionOnQuotaExceededOnNoFixedIps() {\n      fn.handleError(command, noFixedIps);\n\n      assertEquals(command.getException().getClass(), IllegalStateException.class);\n      assertEquals(command.getException().getMessage(), noFixedIps.getPayload().getRawContent());\n   }\n   \n   HttpResponse alreadyExists = HttpResponse.builder().statusCode(400)\n         .message(\"HTTP/1.1 400 Bad Request\")\n         .payload(\"{\\\"badRequest\\\": {\\\"message\\\": \\\"Server with the name 'test' already exists\\\", \\\"code\\\": 400}}\")\n         .build();\n   \n   @Test\n   public void test400MakesIllegalStateExceptionOnAlreadyExists() {\n      fn.handleError(command, alreadyExists);\n\n      assertEquals(command.getException().getClass(), IllegalStateException.class);\n      assertEquals(command.getException().getMessage(), alreadyExists.getPayload().getRawContent());\n   }\n   \n   HttpResponse quotaExceeded = HttpResponse.builder().statusCode(400)\n         .message(\"HTTP/1.1 400 Bad Request\")\n         .payload(\"{\\\"badRequest\\\": {\\\"message\\\": \\\"AddressLimitExceeded: Address quota exceeded. \" +\n                  \"You cannot create any more addresses\\\", \\\"code\\\": 400}}\")\n         .build();\n   \n   @Test\n   public void test400MakesInsufficientResourcesExceptionOnQuotaExceeded() {\n      fn.handleError(command, quotaExceeded);\n\n      assertEquals(command.getException().getClass(), InsufficientResourcesException.class);\n      assertEquals(command.getException().getMessage(), quotaExceeded.getPayload().getRawContent());\n   }\n   \n   HttpResponse tooLarge = HttpResponse.builder().statusCode(413)\n         .message(\"HTTP/1.1 413 Request Entity Too Large\")\n         .payload(\"{\\\"badRequest\\\": {\\\"message\\\": \\\"Volume quota exceeded. You cannot create a volume of size 1G\\\", \" +\n                  \"\\\"code\\\": 413, \\\"retryAfter\\\": 0}}\")\n         .build();\n   \n   @Test\n   public void test413MakesInsufficientResourcesException() {\n      fn.handleError(command, tooLarge);\n\n      assertEquals(command.getException().getClass(), InsufficientResourcesException.class);\n      assertEquals(command.getException().getMessage(), tooLarge.getPayload().getRawContent());\n   }\n   \n   /**\n    * Reponse received from Rackspace UK on November 14, 2012.\n    */\n   HttpResponse retryAt = HttpResponse.builder().statusCode(413)\n         .message(\"HTTP/1.1 413 Request Entity Too Large\")\n         .payload(\"{ 'overLimit' : { 'code' : 413,\"\n                 + \" 'message' : 'OverLimit Retry...', \" \n                 + \" 'details' : 'Error Details...',\"\n                 + \" 'retryAt' : '2012-11-14T21:51:28UTC' }}\")\n         .build();\n   \n   @Test\n   public void test413WithRetryAtExceptionParsesDelta() {\n      fn.handleError(command, retryAt);\n\n      assertEquals(command.getException().getClass(), RetryAfterException.class);\n      assertEquals(command.getException().getMessage(), \"retry in 3600 seconds\");\n   }\n   \n   /**\n    * Folsom response. This contains a delta in seconds to retry after, not a\n    * fixed time.\n    * \n    */\n   HttpResponse retryAfter = HttpResponse.builder().statusCode(413)\n         .message(\"HTTP/1.1 413 Request Entity Too Large\")\n         .payload(\"{ 'overLimit': { 'message': 'This request was rate-limited.', \"\n                 + \" 'retryAfter': '54', \"\n                 + \" 'details': 'Only 1 POST request(s) can be made to \\\\'*\\\\' every minute.'\" + \" }}\")\n         .build();\n   \n   @Test\n   public void test413WithRetryAfterExceptionFolsom() {\n      fn.handleError(command, retryAfter);\n\n      assertEquals(command.getException().getClass(), RetryAfterException.class);\n      assertEquals(command.getException().getMessage(), \"retry in 54 seconds\");\n   }\n   \n   /**\n    * Folsom response with a retryAt field inserted -at a different date. This\n    * can be used to verify that the retryAfter field is picked up first\n    */\n   HttpResponse retryAfterTrumps = HttpResponse.builder().statusCode(413)\n         .message(\"HTTP/1.1 413 Request Entity Too Large\")\n         .payload(\"{ 'overLimit': {\"\n                 + \" 'message': 'This request was rate-limited.', \" \n                 + \" 'retryAfter': '54', \"\n                 + \" 'retryAt' : '2012-11-14T21:51:28UTC',\"\n                 + \" 'details': 'Only 1 POST request(s) can be made to \\\\'*\\\\' every minute.' }}\")\n         .build();\n   \n   @Test\n   public void test413WithRetryAfterTrumpsRetryAt() {\n      fn.handleError(command, retryAfterTrumps);\n\n      assertEquals(command.getException().getClass(), RetryAfterException.class);\n      assertEquals(command.getException().getMessage(), \"retry in 54 seconds\");\n   }\n   \n   HttpResponse badRetryAt = HttpResponse.builder().statusCode(413)\n         .message(\"HTTP/1.1 413 Request Entity Too Large\")\n         .payload(\"{ 'overLimit' : { 'code' : 413,\"\n                 + \" 'message' : 'OverLimit Retry...', \" \n                 + \" 'details' : 'Error Details...',\"\n                 + \" 'retryAt' : '2012-11-~~~:51:28UTC' }}\")\n         .build();\n   \n   @Test\n   public void test413WithBadRetryAtFormatFallsBack() {\n      fn.handleError(command, badRetryAt);\n\n      assertEquals(command.getException().getClass(), InsufficientResourcesException.class);\n      assertEquals(command.getException().getMessage(), badRetryAt.getPayload().getRawContent());\n   }\n   \n   \n   DateCodec iso8601Seconds = new DateServiceIso8601SecondsCodec(new SimpleDateFormatDateService());\n   \n   Ticker y2k = new Ticker() {\n\n      @Override\n      public long read() {\n         return TimeUnit.MILLISECONDS.toNanos(iso8601Seconds.toDate(\"2012-11-14T20:51:28UTC\").getTime());\n      }\n      \n   };\n   \n   NovaErrorHandler fn = new NovaErrorHandler(HeaderToRetryAfterException.create(y2k, iso8601Seconds),\n         new OverLimitParser(new GsonWrapper(new Gson())));\n\n   private HttpCommand command() {\n      return new HttpCommand(HttpRequest.builder().method(\"POST\").endpoint(\"https://nova/v2/servers\").build());\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/internal/BaseNovaApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.internal;\n\nimport org.jclouds.openstack.nova.v2_0.NovaApi;\n\n/**\n * Base class for writing KeyStone Rest Api Expect tests\n */\npublic class BaseNovaApiExpectTest extends BaseNovaExpectTest<NovaApi> {\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/internal/BaseNovaApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.internal;\n\nimport java.util.Properties;\nimport java.util.Set;\n\nimport org.jclouds.apis.BaseApiLiveTest;\nimport org.jclouds.openstack.keystone.config.KeystoneProperties;\nimport org.jclouds.openstack.nova.v2_0.NovaApi;\nimport org.jclouds.openstack.nova.v2_0.config.NovaProperties;\nimport org.jclouds.openstack.nova.v2_0.domain.Flavor;\nimport org.jclouds.openstack.nova.v2_0.domain.Server;\nimport org.jclouds.openstack.nova.v2_0.domain.Server.Status;\nimport org.jclouds.openstack.nova.v2_0.domain.ServerCreated;\nimport org.jclouds.openstack.nova.v2_0.features.FlavorApi;\nimport org.jclouds.openstack.nova.v2_0.features.ImageApi;\nimport org.jclouds.openstack.nova.v2_0.features.ServerApi;\nimport org.jclouds.openstack.nova.v2_0.options.CreateServerOptions;\nimport org.jclouds.openstack.v2_0.domain.Resource;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Throwables;\nimport com.google.common.collect.ComparisonChain;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Ordering;\n\n/**\n * Tests behavior of {@code NovaApi}\n */\n@Test(groups = \"live\")\npublic class BaseNovaApiLiveTest extends BaseApiLiveTest<NovaApi> {\n   protected String hostName = System.getProperty(\"user.name\").replace('.', '-').toLowerCase();\n\n   public BaseNovaApiLiveTest() {\n      provider = \"openstack-nova\";\n   }\n\n   protected Set<String> regions;\n   protected String singleRegion;\n\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   @Override\n   public void setup() {\n      super.setup();\n\n      if (singleRegion != null) {\n         regions = ImmutableSet.of(singleRegion);\n      } else {\n         regions = api.getConfiguredRegions();\n      }\n\n      for (String region : regions) {\n         ServerApi serverApi = api.getServerApi(region);\n         for (Resource server : serverApi.list().concat()) {\n            if (server.getName().equals(hostName))\n               serverApi.delete(server.getId());\n         }\n      }\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      setIfTestSystemPropertyPresent(props, KeystoneProperties.CREDENTIAL_TYPE);\n      setIfTestSystemPropertyPresent(props, NovaProperties.AUTO_ALLOCATE_FLOATING_IPS);\n      singleRegion = setIfTestSystemPropertyPresent(props, provider + \".region\");\n      return props;\n   }\n\n   protected Server createServerInRegion(String regionId) {\n      return createServerInRegion(regionId, new CreateServerOptions());\n   }\n\n   protected Server createServerInRegion(String regionId, CreateServerOptions options) {\n      ServerApi serverApi = api.getServerApi(regionId);\n      ServerCreated server = serverApi.create(hostName, imageId(regionId), flavorId(regionId), options);\n      blockUntilServerInState(server.getId(), serverApi, Status.ACTIVE);\n      return serverApi.get(server.getId());\n   }\n\n   /**\n    * Will block until the requested server is in the correct state, if Extended Server Status extension is loaded\n    * this will continue to block while any task is in progress.\n    */\n   protected void blockUntilServerInState(String serverId, ServerApi api, Status status) {\n      Server currentDetails = null;\n      for (currentDetails = api.get(serverId); currentDetails.getStatus() != status\n               || ((currentDetails.getExtendedStatus().isPresent() && currentDetails.getExtendedStatus().get()\n                        .getTaskState() != null)); currentDetails = api.get(serverId)) {\n         System.out.printf(\"blocking on status %s%n%s%n\", status, currentDetails);\n         try {\n            Thread.sleep(15 * 1000);\n         } catch (InterruptedException e) {\n            throw Throwables.propagate(e);\n         }\n      }\n   }\n\n   protected String imageId(String regionId) {\n      String imageIdKey = \"test.\" + provider + \".image-id\";\n\n      if (System.getProperties().containsKey(imageIdKey)) {\n         return System.getProperty(imageIdKey);\n      }\n      else {\n         ImageApi imageApi = api.getImageApi(regionId);\n\n         // Get the first image from the list as it tends to be \"lighter\" and faster to start\n         return Iterables.get(imageApi.list().concat(), 0).getId();\n      }\n   }\n\n   protected String flavorId(String regionId) {\n      String imageIdKey = \"test.\" + provider + \".flavor-id\";\n\n      if (System.getProperties().containsKey(imageIdKey)) {\n         return System.getProperty(imageIdKey);\n      }\n      else {\n         FlavorApi flavorApi = api.getFlavorApi(regionId);\n         return DEFAULT_FLAVOR_ORDERING.min(flavorApi.listInDetail().concat().filter(new Predicate<Flavor>() {\n            @Override\n            public boolean apply(Flavor in) {\n               return in.getDisk() >= 10 && in.getRam() >= 4 && in.getVcpus() >= 2;\n            }\n         })).getId();\n      }\n   }\n\n   static final Ordering<Flavor> DEFAULT_FLAVOR_ORDERING = new Ordering<Flavor>() {\n      public int compare(Flavor left, Flavor right) {\n         return ComparisonChain.start().compare(left.getVcpus(), right.getVcpus()).compare(left.getRam(), right.getRam())\n               .compare(left.getDisk(), right.getDisk()).result();\n      }\n   };\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/internal/BaseNovaComputeServiceContextExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.internal;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.nova.v2_0.NovaApiMetadata;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.inject.Module;\n\n/**\n\n * Base class for writing Keystone Expect tests with the ComputeService abstraction\n *\n */\npublic abstract class BaseNovaComputeServiceContextExpectTest<T> extends BaseNovaExpectTest<T> implements\n         Function<ComputeServiceContext, T> {\n\n   protected final HttpRequest listDetail = HttpRequest.builder().method(\"GET\").endpoint(\n            URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/images/detail\")).headers(\n            ImmutableMultimap.<String, String> builder().put(\"Accept\", \"application/json\").put(\"X-Auth-Token\",\n                     authToken).build()).build();\n\n   protected final HttpResponse listDetailResponse = HttpResponse.builder().statusCode(200).payload(\n            payloadFromResource(\"/image_list_detail.json\")).build();\n\n   protected final HttpRequest listFlavorsDetail = HttpRequest.builder().method(\"GET\").endpoint(\n            URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/flavors/detail\")).headers(\n            ImmutableMultimap.<String, String> builder().put(\"Accept\", \"application/json\").put(\"X-Auth-Token\",\n                     authToken).build()).build();\n\n   protected final HttpResponse listFlavorsDetailResponse = HttpResponse.builder().statusCode(200).payload(\n            payloadFromResource(\"/flavor_list_detail.json\")).build();\n\n   protected final HttpRequest listServers = HttpRequest.builder().method(\"GET\").endpoint(\n            URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/servers/detail\")).headers(\n            ImmutableMultimap.<String, String> builder().put(\"Accept\", \"application/json\").put(\"X-Auth-Token\",\n                     authToken).build()).build();\n\n   protected final HttpResponse listServersResponse = HttpResponse.builder().statusCode(200).payload(\n            payloadFromResource(\"/server_list_details.json\")).build();\n\n   protected final HttpRequest listFloatingIps = HttpRequest.builder().method(\"GET\").endpoint(\n            URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/os-floating-ips\")).headers(\n            ImmutableMultimap.<String, String> builder().put(\"Accept\", \"application/json\").put(\"X-Auth-Token\",\n                     authToken).build()).build();\n\n   protected final HttpResponse listFloatingIpsResponse = HttpResponse.builder().statusCode(200).payload(\n            payloadFromResource(\"/floatingip_list.json\")).build();\n\n   @Override\n   public T createClient(Function<HttpRequest, HttpResponse> fn, Module module, Properties props) {\n      return apply(createComputeServiceContext(fn, module, props));\n   }\n\n   private ComputeServiceContext createComputeServiceContext(Function<HttpRequest, HttpResponse> fn, Module module,\n         Properties props) {\n      return createInjector(fn, module, props).getInstance(ComputeServiceContext.class);\n   }\n\n   @Override\n   protected ApiMetadata createApiMetadata() {\n      return new NovaApiMetadata();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/internal/BaseNovaComputeServiceExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.internal;\n\nimport org.jclouds.compute.ComputeService;\nimport org.jclouds.compute.ComputeServiceContext;\n\n/**\n * Base class for writing KeyStone Expect tests with the ComputeService\n * abstraction\n */\npublic class BaseNovaComputeServiceExpectTest extends BaseNovaComputeServiceContextExpectTest<ComputeService> {\n\n   @Override\n   public ComputeService apply(ComputeServiceContext input) {\n      return input.getComputeService();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/internal/BaseNovaExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.internal;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.keystone.v2_0.internal.KeystoneFixture;\nimport org.jclouds.rest.internal.BaseRestApiExpectTest;\n\n/**\n * Base class for writing Nova Expect tests\n */\npublic class BaseNovaExpectTest<T> extends BaseRestApiExpectTest<T> {\n   protected HttpRequest keystoneAuthWithUsernameAndPassword;\n   protected HttpRequest keystoneAuthWithUsernameAndPasswordAndTenantName;\n   protected HttpRequest keystoneAuthWithAccessKeyAndSecretKeyAndTenantName;\n   protected String authToken;\n   protected HttpResponse responseWithKeystoneAccess;\n   protected HttpRequest extensionsOfNovaRequest;\n   protected HttpResponse extensionsOfNovaResponse;\n   protected HttpResponse unmatchedExtensionsOfNovaResponse;\n   protected HttpResponse unmatchedExtensionsOfNovaResponseWithNoNamespace;\n   protected HttpRequest keystoneAuthWithAccessKeyAndSecretKeyAndTenantId;\n   protected String identityWithTenantId;\n\n   public BaseNovaExpectTest() {\n      provider = \"openstack-nova\";\n      keystoneAuthWithUsernameAndPassword = KeystoneFixture.INSTANCE.initialAuthWithUsernameAndPassword(identity,\n            credential);\n      keystoneAuthWithUsernameAndPasswordAndTenantName = KeystoneFixture.INSTANCE.initialAuthWithUsernameAndPasswordAndTenantName(identity,\n            credential);\n      keystoneAuthWithAccessKeyAndSecretKeyAndTenantName = KeystoneFixture.INSTANCE.initialAuthWithAccessKeyAndSecretKeyAndTenantName(identity,\n            credential);\n      keystoneAuthWithAccessKeyAndSecretKeyAndTenantId = KeystoneFixture.INSTANCE.initialAuthWithAccessKeyAndSecretKeyAndTenantId(identity,\n              credential);\n\n      authToken = KeystoneFixture.INSTANCE.getAuthToken();\n      responseWithKeystoneAccess = KeystoneFixture.INSTANCE.responseWithAccess();\n      // now, createContext arg will need tenant prefix\n      identityWithTenantId = KeystoneFixture.INSTANCE.getTenantId() + \":\" + identity;\n      identity = KeystoneFixture.INSTANCE.getTenantName() + \":\" + identity;\n\n      extensionsOfNovaRequest = HttpRequest.builder().method(\"GET\")\n             // NOTE THIS IS NOVA, NOT KEYSTONE\n            .endpoint(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/3456/extensions\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"X-Auth-Token\", authToken).build();\n\n      extensionsOfNovaResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResource(\"/extension_list_full.json\")).build();\n\n      unmatchedExtensionsOfNovaResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResource(\"/extension_list.json\")).build();\n\n      unmatchedExtensionsOfNovaResponseWithNoNamespace = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResource(\"/extension_list_full_no_namespaces.json\")).build();\n   }\n\n   @Override\n   protected HttpRequestComparisonType compareHttpRequestAsType(HttpRequest input) {\n      return HttpRequestComparisonType.JSON;\n   }\n\n   protected HttpRequest.Builder<?> authenticatedGET() {\n      return HttpRequest.builder()\n                        .method(\"GET\")\n                        .addHeader(\"Accept\", MediaType.APPLICATION_JSON)\n                        .addHeader(\"X-Auth-Token\", authToken);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/options/CreateServerOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.options;\n\nimport static org.testng.Assert.assertTrue;\n\nimport com.google.common.io.BaseEncoding;\n\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code CreateServerOptions#toString()} regarding userData\n */\n@Test(groups = \"unit\")\npublic class CreateServerOptionsTest {\n\n   private static final byte[] PLAINTEXT = \"This is plain Text\".getBytes();\n   private static final byte[] GZIPTOOSHORT = BaseEncoding.base16().lowerCase().decode(\"1f8b0000\");\n   private static final byte[] GZIPOK = BaseEncoding.base16().lowerCase().decode(\"1f8b0800b6a9a45800034be4020007a1eadd02000000\");\n   private static final byte[] OTHERBIN = BaseEncoding.base16().lowerCase().decode(\"f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff\");\n\n   public void testPlainText() {\n      CreateServerOptions o = new CreateServerOptions().userData(PLAINTEXT);\n      assertTrue(o.toString().contains(\"userData=\" + new String(PLAINTEXT)));\n   }\n\n   public void testGzipOk() {\n      CreateServerOptions o = new CreateServerOptions().userData(GZIPOK);\n      assertTrue(o.toString().contains(String.format(\"<gzipped data (%d bytes)>\", GZIPOK.length)));\n   }\n\n   public void testGzipTooShort() {\n      CreateServerOptions o = new CreateServerOptions().userData(GZIPTOOSHORT);\n      assertTrue(o.toString().contains(\"userData=\" + new String(GZIPTOOSHORT)));\n   }\n\n   public void testOtherBin() {\n      CreateServerOptions o = new CreateServerOptions().userData(OTHERBIN);\n      assertTrue(o.toString().contains(\"userData=\" + new String(OTHERBIN)));\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/options/ListOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.options;\n\nimport static org.jclouds.openstack.nova.v2_0.options.ListOptions.Builder.changesSince;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Date;\n\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tests behavior of {@code ListOptions}\n */\n@Test(groups = \"unit\")\npublic class ListOptionsTest {\n\n   public void testChangesSince() {\n      Date ifModifiedSince = new Date();\n      ListOptions options = new ListOptions().changesSince(ifModifiedSince);\n      assertEquals(ImmutableList.of(ifModifiedSince.getTime() / 1000 + \"\"),\n            options.buildQueryParameters().get(\"changes-since\"));\n   }\n\n   public void testChangesSinceStatic() {\n      Date ifModifiedSince = new Date();\n      PaginationOptions options = changesSince(ifModifiedSince);\n      assertEquals(ImmutableList.of(ifModifiedSince.getTime() / 1000 + \"\"),\n               options.buildQueryParameters().get(\"changes-since\"));\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseComputeServiceTypicalSecurityGroupTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.parse;\n\nimport java.util.Set;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.net.domain.IpProtocol;\nimport org.jclouds.openstack.nova.v2_0.config.NovaParserModule;\nimport org.jclouds.openstack.nova.v2_0.domain.SecurityGroup;\nimport org.jclouds.openstack.nova.v2_0.domain.SecurityGroupRule;\nimport org.jclouds.openstack.nova.v2_0.domain.TenantIdAndName;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\", testName = \"ParseSecurityGroupTest\")\npublic class ParseComputeServiceTypicalSecurityGroupTest extends BaseItemParserTest<SecurityGroup> {\n\n   @Override\n   public String resource() {\n      return \"/securitygroup_details_computeservice_typical.json\";\n   }\n\n   @Override\n   @SelectJson(\"security_group\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public SecurityGroup expected() {\n\n      Set<SecurityGroupRule> securityGroupRules = ImmutableSet.of(\n            SecurityGroupRule.builder().fromPort(22).ipProtocol(IpProtocol.TCP).toPort(22).parentGroupId(\"2769\")\n                  .ipRange(\"0.0.0.0/0\").id(\"10331\").build(),\n            SecurityGroupRule.builder().fromPort(22)\n                  .group(TenantIdAndName.builder().tenantId(\"37936628937291\").name(\"jclouds_mygroup\").build())\n                  .ipProtocol(IpProtocol.TCP).toPort(22).parentGroupId(\"2769\").id(\"10332\").build(),\n            SecurityGroupRule.builder().fromPort(8080).ipProtocol(IpProtocol.TCP).toPort(8080).parentGroupId(\"2769\")\n                  .ipRange(\"0.0.0.0/0\").id(\"10333\").build(),\n            SecurityGroupRule.builder().fromPort(8080)\n                  .group(TenantIdAndName.builder().tenantId(\"37936628937291\").name(\"jclouds_mygroup\").build())\n                  .ipProtocol(IpProtocol.TCP).toPort(8080).parentGroupId(\"2769\").id(\"10334\").build());\n\n      return SecurityGroup.builder().description(\"jclouds_mygroup\").id(\"2769\").tenantId(\"37936628937291\")\n            .rules(securityGroupRules).name(\"jclouds_mygroup\").build();\n   }\n\n   protected Injector injector() {\n      return Guice.createInjector(new NovaParserModule(), new GsonModule());\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseCreateFlavorTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.parse;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.openstack.nova.v2_0.config.NovaParserModule;\nimport org.jclouds.openstack.nova.v2_0.domain.Flavor;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n/**\n * @see FlavorApiExpectTest\n */\n@Test(groups = \"unit\", testName = \"ParseCreateFlavorTest\")\npublic class ParseCreateFlavorTest extends BaseItemParserTest<Flavor> {\n\n   @Override\n   public String resource() {\n      return \"/flavor_new.json\";\n   }\n\n   @Override\n   @SelectJson(\"flavor\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Flavor expected() {\n      return Flavor.builder().id(\"1cb47a44-9b84-4da4-bf81-c1976e8414ab\").name(\"128 MB Server\")\n            .ram(128).vcpus(1).disk(10).build();\n   }\n\n   @Override\n   protected Injector injector() {\n      return Guice.createInjector(new NovaParserModule(), new GsonModule());\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseCreatedServerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.parse;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.openstack.nova.v2_0.config.NovaParserModule;\nimport org.jclouds.openstack.nova.v2_0.domain.ServerCreated;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.Link.Relation;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\", testName = \"ParseCreatedServerTest\")\npublic class ParseCreatedServerTest extends BaseItemParserTest<ServerCreated> {\n\n   @Override\n   public String resource() {\n      return \"/new_server.json\";\n   }\n\n   @Override\n   @SelectJson(\"server\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public ServerCreated expected() {\n      return ServerCreated\n            .builder()\n            .id(\"71752\")\n            .name(\"test-e92\")\n            .adminPass(\"ZWuHcmTMQ7eXoHeM\")\n            .links(\n                     Link.create(Relation.SELF, URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/37936628937291/servers/71752\")),\n                     Link.create(Relation.BOOKMARK, URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/servers/71752\"))).build();\n\n   }\n\n   @SelectJson(\"server\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public ServerCreated expectedWithDiskConfig(String diskConfig) {\n      return ServerCreated\n            .builder()\n            .id(\"71752\")\n            .name(\"test-e92\")\n            .adminPass(\"ZWuHcmTMQ7eXoHeM\")\n            .diskConfig(diskConfig)\n            .links(\n                     Link.create(Relation.SELF, URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/37936628937291/servers/71752\")),\n                     Link.create(Relation.BOOKMARK, URI.create(\"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/servers/71752\"))).build();\n\n   }\n\n   protected Injector injector() {\n      return Guice.createInjector(new NovaParserModule(), new GsonModule());\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseExtensionListNormalTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.parse;\n\nimport java.net.URI;\nimport java.util.Set;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.json.BaseSetParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.openstack.nova.v2_0.config.NovaParserModule;\nimport org.jclouds.openstack.v2_0.domain.Extension;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\", testName = \"ParseExtensionListNormalTest\")\npublic class ParseExtensionListNormalTest extends BaseSetParserTest<Extension> {\n\n   @Override\n   public String resource() {\n      return \"/extension_list_normal.json\";\n   }\n\n   @Override\n   @SelectJson(\"extensions\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Set<Extension> expected() {\n      return ImmutableSet.of(\n            Extension.builder().alias(\"os-keypairs\").name(\"Keypairs\").namespace(URI.create(\"http://docs.openstack.org/ext/keypairs/api/v1.1\"))\n                  .updated(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2011-08-08T00:00:00+00:00\")).description(\"Keypair Support\")\n                  .links(Link.builder().relation(Link.Relation.SELF).href(URI.create(\"http://docs.openstack.org/ext/keypairs/api/v1.1\")).build())\n                  .build(),\n            Extension.builder().alias(\"os-volumes\").name(\"Volumes\").namespace(URI.create(\"http://docs.openstack.org/ext/volumes/api/v1.1\"))\n                  .updated(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2011-03-25T00:00:00+00:00\")).description(\"Volumes support\")\n                  .links(Link.builder().relation(Link.Relation.SELF).href(URI.create(\"http://docs.openstack.org/ext/volumes/api/v1.1\")).build())\n                  .build(),\n            Extension.builder().alias(\"security_groups\").name(\"SecurityGroups\")\n                  .namespace(URI.create(\"http://docs.openstack.org/ext/securitygroups/api/v1.1\"))\n                  .updated(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2011-07-21T00:00:00+00:00\"))\n                  .description(\"Security group support\")\n                  .links(Link.builder().relation(Link.Relation.SELF).href(URI.create(\"http://docs.openstack.org/ext/securitygroups/api/v1.1\")).build())\n                  .build(),\n            Extension.builder().alias(\"os-floating-ips\").name(\"Floating_ips\")\n                  .namespace(URI.create(\"http://docs.openstack.org/ext/floating_ips/api/v1.1\"))\n                  .updated(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2011-06-16T00:00:00+00:00\")).description(\"Floating IPs support\")\n                  .links(Link.builder().relation(Link.Relation.SELF).href(URI.create(\"http://docs.openstack.org/ext/floating_ips/api/v1.1\")).build())\n                  .build());\n   }\n\n   protected Injector injector() {\n      return Guice.createInjector(new NovaParserModule(), new GsonModule());\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseExtensionListTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.parse;\n\nimport java.net.URI;\nimport java.util.Set;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.json.BaseSetParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.openstack.nova.v2_0.config.NovaParserModule;\nimport org.jclouds.openstack.v2_0.domain.Extension;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.Link.Relation;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\", testName = \"ParseExtensionListTest\")\npublic class ParseExtensionListTest extends BaseSetParserTest<Extension> {\n\n   @Override\n   public String resource() {\n      return \"/extension_list.json\";\n   }\n\n   @Override\n   @SelectJson(\"extensions\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Set<Extension> expected() {\n      return ImmutableSet\n            .of(Extension\n                  .builder()\n                  .alias(\"RAX-PIE\")\n                  .name(\"Public Image Extension\")\n                  .namespace(URI.create(\"http://docs.rackspacecloud.com/servers/api/ext/pie/v1.0\"))\n                  .updated(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2011-01-22T13:25:27-06:00\"))\n                  .description(\"Adds the capability to share an image with other users.\")\n                  .links(\n                        ImmutableSet.of(\n                              Link.create(Relation.DESCRIBEDBY, \"application/pdf\",\n                                    URI.create(\"http://docs.rackspacecloud.com/servers/api/ext/cs-pie-20111111.pdf\")),\n                              Link.create(Relation.DESCRIBEDBY, \"application/vnd.sun.wadl+xml\",\n                                    URI.create(\"http://docs.rackspacecloud.com/servers/api/ext/cs-pie.wadl\")))).build(),\n                  Extension\n                        .builder()\n                        .alias(\"RAX-CBS\")\n                        .name(\"Cloud Block Storage\")\n                        .namespace(URI.create(\"http://docs.rackspacecloud.com/servers/api/ext/cbs/v1.0\"))\n                        .updated(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2011-01-12T11:22:33-06:00\"))\n                        .description(\"Allows mounting cloud block storage volumes.\")\n                        .links(\n                              ImmutableSet.of(Link.create(Relation.DESCRIBEDBY, \"application/pdf\",\n                                    URI.create(\"http://docs.rackspacecloud.com/servers/api/ext/cs-cbs-20111201.pdf\")),\n                                    Link.create(Relation.DESCRIBEDBY, \"application/vnd.sun.wadl+xml\",\n                                          URI.create(\"http://docs.rackspacecloud.com/servers/api/ext/cs-cbs.wadl\"))))\n                        .build());\n   }\n\n   protected Injector injector() {\n      return Guice.createInjector(new NovaParserModule(), new GsonModule());\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseExtensionTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.parse;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.openstack.nova.v2_0.config.NovaParserModule;\nimport org.jclouds.openstack.v2_0.domain.Extension;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.Link.Relation;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\", testName = \"ParseExtensionTest\")\npublic class ParseExtensionTest extends BaseItemParserTest<Extension> {\n\n   @Override\n   public String resource() {\n      return \"/extension_details.json\";\n   }\n\n   @Override\n   @SelectJson(\"extension\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Extension expected() {\n      return Extension\n            .builder()\n            .alias(\"RS-PIE\")\n            .name(\"Public Image Extension\")\n            .namespace(URI.create(\"http://docs.rackspacecloud.com/servers/api/ext/pie/v1.0\"))\n            .updated(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2011-01-22T13:25:27-06:00\"))\n            .description(\"Adds the capability to share an image with other users.\")\n            .links(\n                  ImmutableSet.of(\n                        Link.create(Relation.DESCRIBEDBY, \"application/pdf\",\n                              URI.create(\"http://docs.rackspacecloud.com/servers/api/ext/cs-pie-20111111.pdf\")),\n                        Link.create(Relation.DESCRIBEDBY, \"application/vnd.sun.wadl+xml\",\n                              URI.create(\"http://docs.rackspacecloud.com/servers/api/ext/cs-pie.wadl\")))).build();\n   }\n\n   protected Injector injector() {\n      return Guice.createInjector(new NovaParserModule(), new GsonModule());\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseFlavorListTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.parse;\n\nimport java.net.URI;\nimport java.util.Set;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.json.BaseSetParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.openstack.nova.v2_0.config.NovaParserModule;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.Link.Relation;\nimport org.jclouds.openstack.v2_0.domain.Resource;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\", testName = \"ParseFlavorListTest\")\npublic class ParseFlavorListTest extends BaseSetParserTest<Resource> {\n\n   @Override\n   public String resource() {\n      return \"/flavor_list.json\";\n   }\n\n   @Override\n   @SelectJson(\"flavors\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Set<Resource> expected() {\n      return ImmutableSet\n            .of(Resource\n                  .builder()\n                  .id(\"52415800-8b69-11e0-9b19-734f1195ff37\")\n                  .name(\"256 MB Server\")\n                  .links(\n                        Link.create(\n                              Relation.SELF,\n                              URI.create(\"http://servers.api.openstack.org/v2/1234/flavors/52415800-8b69-11e0-9b19-734f1195ff37\")),\n                        Link.create(\n                              Relation.BOOKMARK,\n                              URI.create(\"http://servers.api.openstack.org/1234/flavors/52415800-8b69-11e0-9b19-734f1195ff37\")))\n                  .build(),\n                  Resource\n                        .builder()\n                        .id(\"52415800-8b69-11e0-9b19-734f216543fd\")\n                        .name(\"512 MB Server\")\n                        .links(\n                              Link.create(\n                                    Relation.SELF,\n                                    URI.create(\"http://servers.api.openstack.org/v2/1234/flavors/52415800-8b69-11e0-9b19-734f216543fd\")),\n                              Link.create(\n                                    Relation.BOOKMARK,\n                                    URI.create(\"http://servers.api.openstack.org/1234/flavors/52415800-8b69-11e0-9b19-734f216543fd\")))\n                        .build());\n   }\n\n   protected Injector injector() {\n      return Guice.createInjector(new NovaParserModule(), new GsonModule());\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseFlavorTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.parse;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.openstack.nova.v2_0.config.NovaParserModule;\nimport org.jclouds.openstack.nova.v2_0.domain.Flavor;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.Link.Relation;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\", testName = \"ParseFlavorTest\")\npublic class ParseFlavorTest extends BaseItemParserTest<Flavor> {\n\n   @Override\n   public String resource() {\n      return \"/flavor_details.json\";\n   }\n\n   @Override\n   @SelectJson(\"flavor\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Flavor expected() {\n      return Flavor\n            .builder()\n            .id(\"52415800-8b69-11e0-9b19-734f1195ff37\")\n            .name(\"256 MB Server\")\n            .links(\n                  ImmutableSet.of(\n                        Link.create(\n                              Relation.SELF,\n                              URI.create(\"http://servers.api.openstack.org/v2/1234/flavors/52415800-8b69-11e0-9b19-734f1195ff37\")),\n                        Link.create(\n                              Relation.BOOKMARK,\n                              URI.create(\"http://servers.api.openstack.org/1234/flavors/52415800-8b69-11e0-9b19-734f1195ff37\"))))\n            .ram(256).disk(10).vcpus(1).build();\n   }\n\n   protected Injector injector() {\n      return Guice.createInjector(new NovaParserModule(), new GsonModule());\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseFloatingIPListTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.parse;\n\nimport java.util.Set;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.json.BaseSetParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.openstack.nova.v2_0.config.NovaParserModule;\nimport org.jclouds.openstack.nova.v2_0.domain.FloatingIP;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n/**\n * Tests parsing of {@link FloatingIP} JSON data.\n */\n@Test(groups = \"unit\", testName = \"ParseFloatingIPListTest\")\npublic class ParseFloatingIPListTest extends BaseSetParserTest<FloatingIP> {\n\n   @Override\n   public String resource() {\n      return \"/floatingip_list.json\";\n   }\n\n   @Override\n   @SelectJson(\"floating_ips\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Set<FloatingIP> expected() {\n      return ImmutableSet.of(\n            FloatingIP.builder().id(\"1\").instanceId(\"12\").ip(\"10.0.0.3\").fixedIp(\"11.0.0.1\").pool(\"nova\").build(),\n            FloatingIP.builder().id(\"2\").instanceId(null).ip(\"10.0.0.5\").fixedIp(null).pool(\"nova\").build(),\n            FloatingIP.builder().id(\"3\").instanceId(\"13\").ip(\"10.0.0.13\").fixedIp(\"11.0.0.3\").build(),\n            FloatingIP.builder().id(\"4\").instanceId(\"14\").ip(\"10.0.0.14\").fixedIp(\"11.0.0.4\").pool(null).build());\n   }\n\n   protected Injector injector() {\n      return Guice.createInjector(new NovaParserModule(), new GsonModule());\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseFloatingIPPoolListTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.parse;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport org.jclouds.json.BaseSetParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.openstack.nova.v2_0.config.NovaParserModule;\nimport org.jclouds.openstack.nova.v2_0.domain.FloatingIPPool;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\nimport java.util.Set;\n\n@Test(groups = \"unit\", testName = \"ParseFloatingIPPoolListTest\")\npublic class ParseFloatingIPPoolListTest extends BaseSetParserTest<FloatingIPPool> {\n\n   @Override\n   public String resource() {\n      return \"/floatingippool_list.json\";\n   }\n\n   @Override\n   @SelectJson(\"floating_ip_pools\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Set<FloatingIPPool> expected() {\n      return ImmutableSet.of(FloatingIPPool.builder().name(\"VLAN867\").build());\n   }\n\n   protected Injector injector() {\n      return Guice.createInjector(new NovaParserModule(), new GsonModule());\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseFloatingIPTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.parse;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.openstack.nova.v2_0.config.NovaParserModule;\nimport org.jclouds.openstack.nova.v2_0.domain.FloatingIP;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n/**\n * Test to parse a {@link FloatingIP}\n */\n@Test(groups = \"unit\", testName = \"ParseFloatingIPTest\")\npublic class ParseFloatingIPTest extends BaseItemParserTest<FloatingIP> {\n\n   @Override\n   public String resource() {\n      return \"/floatingip_details.json\";\n   }\n\n   @Override\n   @SelectJson(\"floating_ip\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public FloatingIP expected() {\n      return FloatingIP.builder().id(\"1\").instanceId(\"123\").fixedIp(\"10.0.0.2\").ip(\"10.0.0.3\").pool(\"nova\").build();\n   }\n\n   protected Injector injector() {\n      return Guice.createInjector(new NovaParserModule(), new GsonModule());\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseImageListTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.parse;\n\nimport java.net.URI;\nimport java.util.Set;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.json.BaseSetParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.openstack.nova.v2_0.config.NovaParserModule;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.Link.Relation;\nimport org.jclouds.openstack.v2_0.domain.Resource;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\", testName = \"ParseImageListTest\")\npublic class ParseImageListTest extends BaseSetParserTest<Resource> {\n\n   @Override\n   public String resource() {\n      return \"/image_list.json\";\n   }\n\n   @Override\n   @SelectJson(\"images\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Set<Resource> expected() {\n      return ImmutableSet\n            .of(Resource\n                  .builder()\n                  .id(\"52415800-8b69-11e0-9b19-734f6f006e54\")\n                  .name(\"CentOS 5.2\")\n                  .links(\n                        Link.create(\n                              Relation.SELF,\n                              URI.create(\"http://servers.api.openstack.org/v2/1234/images/52415800-8b69-11e0-9b19-734f6f006e54\")),\n                        Link.create(\n                              Relation.BOOKMARK,\n                              URI.create(\"http://servers.api.openstack.org/1234/images/52415800-8b69-11e0-9b19-734f6f006e54\")))\n                  .build(),\n                  Resource\n                        .builder()\n                        .id(\"52415800-8b69-11e0-9b19-734f5736d2a2\")\n                        .name(\"My Server Backup\")\n                        .links(\n                              Link.create(\n                                    Relation.SELF,\n                                    URI.create(\"http://servers.api.openstack.org/v2/1234/images/52415800-8b69-11e0-9b19-734f5736d2a2\")),\n                              Link.create(\n                                    Relation.BOOKMARK,\n                                    URI.create(\"http://servers.api.openstack.org/1234/images/52415800-8b69-11e0-9b19-734f5736d2a2\")))\n                        .build());\n   }\n\n   protected Injector injector() {\n      return Guice.createInjector(new NovaParserModule(), new GsonModule());\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseImageTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.parse;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.openstack.nova.v2_0.config.NovaParserModule;\nimport org.jclouds.openstack.nova.v2_0.domain.Image;\nimport org.jclouds.openstack.nova.v2_0.domain.Image.Status;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.Link.Relation;\nimport org.jclouds.openstack.v2_0.domain.Resource;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\", testName = \"ParseImageTest\")\npublic class ParseImageTest extends BaseItemParserTest<Image> {\n\n   @Override\n   public String resource() {\n      return \"/image_details.json\";\n   }\n\n   @Override\n   @SelectJson(\"image\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Image expected() {\n      return Image\n            .builder()\n            .id(\"52415800-8b69-11e0-9b19-734f5736d2a2\")\n            .name(\"My Server Backup\")\n            .updated(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2010-10-10T12:00:00Z\"))\n            .created(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2010-08-10T12:00:00Z\"))\n            .tenantId(\"12345\")\n            .userId(\"joe\")\n            .status(Status.SAVING)\n            .progress(80)\n            .minDisk(5)\n            .minRam(256)\n            .metadata(\n                  new ImmutableMap.Builder<String, String>().put(\"ImageType\", \"Gold\").put(\"ImageVersion\", \"1.5\")\n                        .build())\n            .server(\n                  Resource\n                        .builder()\n                        .id(\"52415800-8b69-11e0-9b19-734f335aa7b3\")\n                        .name(\"null\")\n                        .links(\n                              Link.create(\n                                    Relation.SELF,\n                                    URI.create(\"http://servers.api.openstack.org/v2/1234/servers/52415800-8b69-11e0-9b19-734f335aa7b3\")),\n                              Link.create(\n                                    Relation.BOOKMARK,\n                                    URI.create(\"http://servers.api.openstack.org/1234/servers/52415800-8b69-11e0-9b19-734f335aa7b3\")))\n                        .build())\n            .links(\n                  ImmutableSet.of(\n                        Link.create(\n                              Relation.SELF,\n                              URI.create(\"http://servers.api.openstack.org/v2/1234/images/52415800-8b69-11e0-9b19-734f5736d2a2\")),\n                        Link.create(\n                              Relation.BOOKMARK,\n                              URI.create(\"http://servers.api.openstack.org/1234/images/52415800-8b69-11e0-9b19-734f5736d2a2\"))))\n            .build();\n   }\n\n   protected Injector injector() {\n      return Guice.createInjector(new NovaParserModule(), new GsonModule());\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseKeyPairListTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.parse;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.openstack.nova.v2_0.config.NovaParserModule;\nimport org.jclouds.openstack.nova.v2_0.domain.KeyPair;\nimport org.jclouds.openstack.nova.v2_0.functions.internal.ParseKeyPairs;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\", testName = \"ParseKeyPairListTest\")\npublic class ParseKeyPairListTest extends BaseItemParserTest<FluentIterable<? extends KeyPair>> {\n\n   @Override\n   public String resource() {\n      return \"/keypair_list.json\";\n   }\n\n   @Override\n   @ResponseParser(ParseKeyPairs.class)\n   @Consumes(MediaType.APPLICATION_JSON)\n   public FluentIterable<? extends KeyPair> expected() {\n      return FluentIterable.from(ImmutableSet.of(\n            KeyPair\n                  .builder()\n                  .publicKey(\n                        \"ssh-rsa AAAXB3NzaC1yc2EAAAADAQABAAAAgQCy9EC3O7Ff80vPEfAHDQob61PGwcpYc5KE7tEZnZhrB9n0NyHPRm0E0M+ls3fcTa04HDi+R0DzmRwoyhHQJyI658v8kWZZcuvFjKCcsgsSh/dzdX0xTreLIzSOzt5U7RnZYfshP5cmxtF99yrEY3M/swdin0L+fXsTSkR1B42STQ== nova@nv-aw2az1-api0001\")\n                  .name(\"default\").fingerprint(\"ab:0c:f4:f3:54:c0:5d:3f:ed:62:ad:d3:94:7c:79:7c\").build(),\n            KeyPair\n                  .builder()\n                  .publicKey(\n                        \"ssh-rsa AAAXB3NzaC1yc2EAAAADAQABAAAAgQDFNyGjgs6c9akgmZ2ou/fJf7Pdrc23hC95/gM/33OrG4GZABACE4DTioa/PGN+7rHv9YUavUCtXrWayhGniKq/wCuI5fo5TO4AmDNv7/sCGHIHFumADSIoLx0vFhGJIetXEWxL9r0lfFC7//6yZM2W3KcGjbMtlPXqBT9K9PzdyQ== nova@nv-aw2az1-api0001\")\n                  .name(\"testkeypair\").fingerprint(\"d2:1f:c9:2b:d8:90:77:5f:15:64:27:e3:9f:77:1d:e4\").build()));\n   }\n\n   protected Injector injector() {\n      return Guice.createInjector(new NovaParserModule(), new GsonModule());\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseKeyPairTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.parse;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.openstack.nova.v2_0.config.NovaParserModule;\nimport org.jclouds.openstack.nova.v2_0.domain.KeyPair;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n/**\n * Tests parsing of a {@link KeyPair}.\n */\n@Test(groups = \"unit\", testName = \"ParseKeyPairTest\")\npublic class ParseKeyPairTest extends BaseItemParserTest<KeyPair> {\n\n   @Override\n   public String resource() {\n      return \"/keypair_details.json\";\n   }\n\n   @Override\n   @SelectJson(\"keypair\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public KeyPair expected() {\n      return KeyPair\n            .builder()\n            .publicKey(\n                  \"ssh-rsa AAAXB3NzaC1yc2EAAAADAQABAAAAgQDFNyGjgs6c9akgmZ2ou/fJf7Pdrc23hC95/gM/33OrG4GZABACE4DTioa/PGN+7rHv9YUavUCtXrWayhGniKq/wCuI5fo5TO4AmDNv7/sCGHIHFumADSIoLx0vFhGJIetXEWxL9r0lfFC7//6yZM2W3KcGjbMtlPXqBT9K9PzdyQ== nova@nv-aw2az1-api0001\\n\")\n            .privateKey(\n                  \"-----BEGIN RSA PRIVATE KEY-----\\nMIICXQIAAAKBgQDFNyGjgs6c9akgmZ2ou/fJf7Pdrc23hC95/gM/33OrG4GZABAC\\nE4DTioa/PGN+7rHv9YUavUCtXrWayhGniKq/wCuI5fo5TO4AmDNv7/sCGHIHFumA\\nDSIoLx0vFhGJIetXEWxL9r0lfFC7//6yZM2W3KcGjbMtlPXqBT9K9PzdyQIDAQAB\\nAoGAW8Ww+KbpQK8smcgCTr/RqcmsSI8VeL2hXjJvDq0L5WbyYuFdkanDvCztUVZn\\nsmyfDtwAqZXB4Ct/dN1tY7m8QpdyRaKRW4Q+hghGCAQpsG7rYDdvwdEyvMaW5RA4\\ntucQyajMNyQ/tozU3wMx/v8A7RvGcE9tqoG0WK1C3kBu95UCQQDrOd+joYDkvccz\\nFIVu5gNPMXEh3fGGzDxk225UlvESquYLzfz4TfmuUjH4Z1BL3wRiwfJsrrjFkm33\\njIidDE8PAkEA1qHjxuaIS1yz/rfzErmcOVNlbFHMP4ihjGTTvh1ZctXlNeLwzENQ\\nEDaQV3IpUY1KQR6rxcWb5AXgfF9D9PYFpwJBANucAqGAbRgh3lJgPFtXP4u2O0tF\\nLPOOxmvbOdybt6KYD4LB5AXmts77SlACFMNhCXUyYaT6UuOSXDyb5gfJsB0CQQC3\\nFaGXKU9Z+doQjhlq/6mjvN/nZl80Uvh7Kgb1RVPoAU1kihGeLE0/h0vZTCiyyDNv\\nGRqtucMg32J+tUTi0HpBAkAwHiCZMHMeJWHUwIwlRQY/dnR86FWobRl98ViF2rCL\\nDHkDVOeIser3Q6zSqU5/m99lX6an5g8pAh/R5LqnOQZC\\n-----END RSA PRIVATE KEY-----\\n\")\n            .name(\"testkeypair\").userId(\"65649731189278\")\n            .fingerprint(\"d2:1f:c9:2b:d8:90:77:5f:15:64:27:e3:9f:77:1d:e4\").build();\n   }\n\n   protected Injector injector() {\n      return Guice.createInjector(new NovaParserModule(), new GsonModule());\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseMetadataItemTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.parse;\n\nimport java.util.Map;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.openstack.nova.v2_0.config.NovaParserModule;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\", testName = \"ParseMetadataItemTest\")\npublic class ParseMetadataItemTest extends BaseItemParserTest<Map<String, String>> {\n\n   @Override\n   public String resource() {\n      return \"/metadata_item.json\";\n   }\n\n   @Override\n   @SelectJson(\"metadata\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Map<String, String> expected() {\n      ImmutableMap<String, String> metadata = ImmutableMap.of(\"Server Label\", \"Web Head 1\");\n      return metadata;\n   }\n\n   protected Injector injector() {\n      return Guice.createInjector(new NovaParserModule(), new GsonModule());\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseMetadataListTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.parse;\n\nimport java.util.Map;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.openstack.nova.v2_0.config.NovaParserModule;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\", testName = \"ParseMetadataListTest\")\npublic class ParseMetadataListTest extends BaseItemParserTest<Map<String, String>> {\n\n   @Override\n   public String resource() {\n      return \"/metadata_list.json\";\n   }\n\n   @Override\n   @SelectJson(\"metadata\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Map<String, String> expected() {\n\t  ImmutableMap<String, String> metadata =\n         new ImmutableMap.Builder<String, String>()\n               .put(\"Server Label\", \"Web Head 1\")\n               .put(\"Image Version\", \"2.1\")\n               .build();\n\t  \n      return metadata;\n   }\n\n   protected Injector injector() {\n      return Guice.createInjector(new NovaParserModule(), new GsonModule());\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseMetadataUpdateTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.parse;\n\nimport java.util.Map;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.openstack.nova.v2_0.config.NovaParserModule;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\", testName = \"ParseMetadataUpdateTest\")\npublic class ParseMetadataUpdateTest extends BaseItemParserTest<Map<String, String>> {\n\n   @Override\n   public String resource() {\n      return \"/metadata_updated.json\";\n   }\n\n   @Override\n   @SelectJson(\"metadata\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Map<String, String> expected() {\n      ImmutableMap<String, String> metadata =\n         new ImmutableMap.Builder<String, String>()\n               .put(\"Server Label\", \"Web Head 2\")\n               .put(\"Image Version\", \"2.1\")\n               .put(\"Server Description\", \"Simple Server\")\n               .build();\n  \n      return metadata;\n   }\n\n   protected Injector injector() {\n      return Guice.createInjector(new NovaParserModule(), new GsonModule());\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseNOVNCConsoleTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.parse;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.openstack.nova.v2_0.config.NovaParserModule;\nimport org.jclouds.openstack.nova.v2_0.domain.Console;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Throwables;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n/**\n * Tests parsing of vnc console response. \n */\n@Test(groups = \"unit\", testName = \"ParseNOVNCConsoleTest\")\npublic class ParseNOVNCConsoleTest extends BaseItemParserTest<Console> {\n\n   @Override\n   public String resource() {\n      return \"/novnc_console.json\";\n   }\n\n   @Override\n   @SelectJson(\"console\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Console expected() {\n      Console console = null;\n      try {\n         console = Console\n            .builder()\n            .url(new URI(\"http://example.com:6080/vnc_auto.html?token=f9906a48-b71e-4f18\"\n                     + \"-baca-c987da3ebdb3&title=dafa(75ecef58-3b8e-4659-ab3b-5501454188e9)\"))\n            .type(Console.Type.NOVNC)\n            .build();\n      } catch (Exception e) {\n         Throwables.propagate(e);\n      }\n\n      return console;\n   }\n\n   protected Injector injector() {\n      return Guice.createInjector(new NovaParserModule(), new GsonModule());\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseRDPConsoleTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.parse;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.openstack.nova.v2_0.config.NovaParserModule;\nimport org.jclouds.openstack.nova.v2_0.domain.Console;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Throwables;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n/**\n * Tests parsing of RDP console response.\n */\n@Test(groups = \"unit\", testName = \"ParseRDPConsoleTest\")\npublic class ParseRDPConsoleTest extends BaseItemParserTest<Console> {\n\n   @Override\n   public String resource() {\n      return \"/rdp_console.json\";\n   }\n\n   @Override\n   @SelectJson(\"console\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Console expected() {\n      Console console = null;\n\n      try {\n         console = Console\n            .builder()\n            .url(new URI(\"http://example.com:6083/?token=f9906a48-b71e-4f18-baca-\"\n                     + \"c987da3ebdb3&title=dafa(75ecef58-3b8e-4659-ab3b-5501454188e9)\"))\n            .type(Console.Type.RDP_HTML5)\n            .build();\n      } catch (Exception e) {\n         Throwables.propagate(e);\n      }\n\n      return console;\n   }\n\n   protected Injector injector() {\n      return Guice.createInjector(new NovaParserModule(), new GsonModule());\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseSPICEConsoleTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.parse;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.openstack.nova.v2_0.config.NovaParserModule;\nimport org.jclouds.openstack.nova.v2_0.domain.Console;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Throwables;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n/**\n * Tests parsing of spice console response.\n */\n@Test(groups = \"unit\", testName = \"ParseSPICEConsoleTest\")\npublic class ParseSPICEConsoleTest extends BaseItemParserTest<Console> {\n\n   @Override\n   public String resource() {\n      return \"/spice_console.json\";\n   }\n\n   @Override\n   @SelectJson(\"console\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Console expected() {\n      Console console = null;\n\n      try {\n         console = Console\n            .builder()\n            .url(new URI(\"http://example.com:6080/spice_auto.html?token=f9906a48-b71e\"\n                     + \"-4f18-baca-c987da3ebdb3&title=dafa(75ecef58-3b8e-4659-ab3b-5501454188e9)\"))\n            .type(Console.Type.SPICE_HTML5)\n            .build();\n      } catch (Exception e) {\n         Throwables.propagate(e);\n      }\n\n      return console;\n   }\n\n   protected Injector injector() {\n      return Guice.createInjector(new NovaParserModule(), new GsonModule());\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseSecurityGroupListTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.parse;\n\nimport java.util.Set;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.json.BaseSetParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.net.domain.IpProtocol;\nimport org.jclouds.openstack.nova.v2_0.config.NovaParserModule;\nimport org.jclouds.openstack.nova.v2_0.domain.SecurityGroup;\nimport org.jclouds.openstack.nova.v2_0.domain.SecurityGroupRule;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\", testName = \"ParseSecurityGroupListTest\")\npublic class ParseSecurityGroupListTest extends BaseSetParserTest<SecurityGroup> {\n\n   @Override\n   public String resource() {\n      return \"/securitygroup_list.json\";\n   }\n\n   @Override\n   @SelectJson(\"security_groups\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Set<SecurityGroup> expected() {\n\n      Set<SecurityGroupRule> securityGroupRules = ImmutableSet.<SecurityGroupRule> of(\n            SecurityGroupRule.builder().fromPort(22)\n                  .ipProtocol(IpProtocol.TCP).toPort(22).parentGroupId(\"3\").ipRange(\"0.0.0.0/0\")\n                  .id(\"107\").build(),\n            SecurityGroupRule.builder().fromPort(7600)\n                  .ipProtocol(IpProtocol.TCP).toPort(7600).parentGroupId(\"3\").ipRange(\"0.0.0.0/0\")\n                  .id(\"118\").build(),\n            SecurityGroupRule.builder().fromPort(8084)\n                  .ipProtocol(IpProtocol.TCP).toPort(8084).parentGroupId(\"3\").ipRange(\"0.0.0.0/0\")\n                  .id(\"119\").build());\n\n      return ImmutableSet.of(SecurityGroup.builder().description(\"description1\").id(\"1\").tenantId(\"tenant1\")\n            .rules(securityGroupRules).name(\"name1\").build());\n   }\n\n   protected Injector injector() {\n      return Guice.createInjector(new NovaParserModule(), new GsonModule());\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseSecurityGroupTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.parse;\n\nimport java.util.Set;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.net.domain.IpProtocol;\nimport org.jclouds.openstack.nova.v2_0.config.NovaParserModule;\nimport org.jclouds.openstack.nova.v2_0.domain.SecurityGroup;\nimport org.jclouds.openstack.nova.v2_0.domain.SecurityGroupRule;\nimport org.jclouds.openstack.nova.v2_0.domain.TenantIdAndName;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\", testName = \"ParseSecurityGroupTest\")\npublic class ParseSecurityGroupTest extends BaseItemParserTest<SecurityGroup> {\n   @Override\n   public String resource() {\n      return \"/securitygroup_details.json\";\n   }\n\n   @Override\n   @SelectJson(\"security_group\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public SecurityGroup expected() {\n\n      Set<SecurityGroupRule> securityGroupRules = ImmutableSet.<SecurityGroupRule> of(\n            SecurityGroupRule.builder().fromPort(22)\n                  .ipProtocol(IpProtocol.TCP).toPort(22).parentGroupId(\"28\")\n                  .ipRange(\"10.2.6.0/24\").id(\"108\").build(),\n            SecurityGroupRule.builder().fromPort(22).group(TenantIdAndName.builder().name(\"11111\").tenantId(\"admin\").build())\n                  .ipProtocol(IpProtocol.TCP).toPort(22).parentGroupId(\"28\")\n                  .id(\"109\").build());\n\n      return SecurityGroup.builder().description(\"description0\").id(\"0\").tenantId(\"tenant0\").rules(securityGroupRules)\n            .name(\"name0\").build();\n   }\n   \n   protected Injector injector() {\n      return Guice.createInjector(new NovaParserModule(), new GsonModule());\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseServerDetailsEssexTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.parse;\n\nimport java.net.URI;\nimport java.util.Set;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.json.BaseSetParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.openstack.nova.v2_0.config.NovaParserModule;\nimport org.jclouds.openstack.nova.v2_0.domain.Address;\nimport org.jclouds.openstack.nova.v2_0.domain.Server;\nimport org.jclouds.openstack.nova.v2_0.domain.Server.Status;\nimport org.jclouds.openstack.nova.v2_0.domain.ServerExtendedStatus;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.Link.Relation;\nimport org.jclouds.openstack.v2_0.domain.Resource;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\", testName = \"ParseServerDetailsEssexTest\")\npublic class ParseServerDetailsEssexTest extends BaseSetParserTest<Server> {\n\n   @Override\n   public String resource() {\n      return \"/server_list_details_essex.json\";\n   }\n\n   @Override\n   @SelectJson(\"servers\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Set<Server> expected() {\n      return ImmutableSet.<Server>of(\n            Server.builder()\n                  .addresses(ImmutableMultimap.<String, Address>builder()\n                        .putAll(\"Net TenantA Front-Middle\", Address.createV4(\"172.16.11.5\"))\n                        .putAll(\"Public network\", Address.createV4(\"172.16.1.13\"), Address.createV4(\"10.193.112.119\")).build())\n                  .links(\n                        Link.create(\n                              Relation.SELF,\n                              URI.create(\"http://nova:8774/v2/8d10e6646d5d4585937395b04839a353/servers/0c80b392-db30-4736-ae02-4480090f1207\")),\n                        Link.create(\n                              Relation.BOOKMARK,\n                              URI.create(\"http://nova:8774/8d10e6646d5d4585937395b04839a353/servers/0c80b392-db30-4736-ae02-4480090f1207\")))\n                  .image(\n                        Resource.builder()\n                              .id(\"416af940-2d3c-4a7c-977c-a9030685ad5e\")\n                              .links(\n                                    Link.create(\n                                          Relation.BOOKMARK,\n                                          URI.create(\"http://nova:8774/8d10e6646d5d4585937395b04839a353/images/416af940-2d3c-4a7c-977c-a9030685ad5e\"))).build())\n                  .flavor(\n                        Resource.builder()\n                              .id(\"1\")\n                              .links(\n                                    Link.create(\n                                          Relation.BOOKMARK,\n                                          URI.create(\"http://nova:8774/8d10e6646d5d4585937395b04839a353/flavors/1\"))).build())\n                  .id(\"0c80b392-db30-4736-ae02-4480090f1207\")\n                  .userId(\"df13814f6c354d00a8acf66502836323\")\n                  .status(Status.ACTIVE)\n                  .updated(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2012-04-12T11:21:33Z\"))\n                  .hostId(\"03d796ebb52b1b555e5f6d9262f7dbd52b3f7c181e3aa89b34ca5408\")\n                  .name(\"VM proxy\")\n                  .created(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2012-04-12T11:21:23Z\"))\n                  .tenantId(\"8d10e6646d5d4585937395b04839a353\")\n                  .extendedStatus(ServerExtendedStatus.builder().vmState(\"active\").powerState(1).build())\n                  .diskConfig(\"MANUAL\").build(),\n            Server.builder()\n                  .addresses(ImmutableMultimap.<String, Address>builder()\n                        .putAll(\"Net TenantA Front-Middle\", Address.createV4(\"172.16.11.4\"))\n                        .putAll(\"Net TenantA Middle-Back\", Address.createV4(\"172.16.12.5\")).build())\n                  .links(\n                        Link.create(\n                              Relation.SELF,\n                              URI.create(\"http://nova:8774/v2/8d10e6646d5d4585937395b04839a353/servers/b332b5cd-535e-4677-b68e-fc8badc13236\")),\n                        Link.create(\n                              Relation.BOOKMARK,\n                              URI.create(\"http://nova:8774/8d10e6646d5d4585937395b04839a353/servers/b332b5cd-535e-4677-b68e-fc8badc13236\")))\n                  .image(\n                        Resource.builder()\n                              .id(\"416af940-2d3c-4a7c-977c-a9030685ad5e\")\n                              .links(\n                                    Link.create(\n                                          Relation.BOOKMARK,\n                                          URI.create(\"http://nova:8774/8d10e6646d5d4585937395b04839a353/images/416af940-2d3c-4a7c-977c-a9030685ad5e\"))).build())\n                  .flavor(\n                        Resource.builder()\n                              .id(\"1\")\n                              .links(\n                                    Link.create(\n                                          Relation.BOOKMARK,\n                                          URI.create(\"http://nova:8774/8d10e6646d5d4585937395b04839a353/flavors/1\"))).build())\n                  .id(\"b332b5cd-535e-4677-b68e-fc8badc13236\")\n                  .userId(\"df13814f6c354d00a8acf66502836323\")\n                  .status(Status.ACTIVE)\n                  .updated(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2012-04-12T11:18:58Z\"))\n                  .hostId(\"e5bbff80bebacfe1db63951e787b5341427060a602d33abfefb6a1bc\")\n                  .name(\"VM blog\")\n                  .created(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2012-04-12T11:18:48Z\"))\n                  .tenantId(\"8d10e6646d5d4585937395b04839a353\")\n                  .extendedStatus(ServerExtendedStatus.builder().vmState(\"active\").powerState(1).build())\n                  .diskConfig(\"MANUAL\").build(),\n            Server.builder()\n                  .addresses(ImmutableMultimap.<String, Address>builder()\n                        .putAll(\"Net TenantA Middle-Back\", Address.createV4(\"172.16.12.4\")).build())\n                  .links(\n                        Link.create(\n                              Relation.SELF,\n                              URI.create(\"http://nova:8774/v2/8d10e6646d5d4585937395b04839a353/servers/f9d43436-4572-4c9b-9b74-5fa6890a2f21\")),\n                        Link.create(\n                              Relation.BOOKMARK,\n                              URI.create(\"http://nova:8774/8d10e6646d5d4585937395b04839a353/servers/f9d43436-4572-4c9b-9b74-5fa6890a2f21\")))\n                  .image(\n                        Resource.builder()\n                              .id(\"416af940-2d3c-4a7c-977c-a9030685ad5e\")\n                              .links(\n                                    Link.create(\n                                          Relation.BOOKMARK,\n                                          URI.create(\"http://nova:8774/8d10e6646d5d4585937395b04839a353/images/416af940-2d3c-4a7c-977c-a9030685ad5e\"))).build())\n                  .flavor(\n                        Resource.builder()\n                              .id(\"1\")\n                              .links(\n                                    Link.create(\n                                          Relation.BOOKMARK,\n                                          URI.create(\"http://nova:8774/8d10e6646d5d4585937395b04839a353/flavors/1\"))).build())\n                  .id(\"f9d43436-4572-4c9b-9b74-5fa6890a2f21\")\n                  .userId(\"df13814f6c354d00a8acf66502836323\")\n                  .status(Status.ACTIVE)\n                  .updated(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2012-04-12T11:15:09Z\"))\n                  .hostId(\"03d796ebb52b1b555e5f6d9262f7dbd52b3f7c181e3aa89b34ca5408\")\n                  .name(\"VM MySQL\")\n                  .created(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2012-04-12T11:14:56Z\"))\n                  .tenantId(\"8d10e6646d5d4585937395b04839a353\")\n                  .extendedStatus(ServerExtendedStatus.builder().vmState(\"active\").powerState(1).build())\n                  .diskConfig(\"MANUAL\").build());\n   }\n  \n\n   protected Injector injector() {\n      return Guice.createInjector(new NovaParserModule(), new GsonModule());\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseServerDetailsStatesTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.parse;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport java.net.URI;\nimport java.util.Set;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.json.BaseSetParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.openstack.nova.v2_0.config.NovaParserModule;\nimport org.jclouds.openstack.nova.v2_0.domain.Address;\nimport org.jclouds.openstack.nova.v2_0.domain.Server;\nimport org.jclouds.openstack.nova.v2_0.domain.Server.Status;\nimport org.jclouds.openstack.nova.v2_0.domain.ServerExtendedAttributes;\nimport org.jclouds.openstack.nova.v2_0.domain.ServerExtendedStatus;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.Link.Relation;\nimport org.jclouds.openstack.v2_0.domain.Resource;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ParseServerDetailsStatesTest\")\npublic class ParseServerDetailsStatesTest extends BaseSetParserTest<Server> {\n\n   @Override\n   public String resource() {\n      return \"/server_list_details_states.json\";\n   }\n\n   @Override\n   @SelectJson(\"servers\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Set<Server> expected() {\n      return ImmutableSet.<Server>of(\n            Server.builder()\n                  .links(\n                        Link.create(\n                              Relation.SELF,\n                              URI.create(\"http://openstack:8774/v2/4e1900cf21924a098709c23480e157c0/servers/56d51a88-0066-4976-91b6-d1b453be603f\")),\n                        Link.create(\n                              Relation.BOOKMARK,\n                              URI.create(\"http://openstack:8774/4e1900cf21924a098709c23480e157c0/servers/56d51a88-0066-4976-91b6-d1b453be603f\"))\n                  )\n                  .image(Resource.builder()\n                        .id(\"e3f84189-964e-4dc3-8ac6-832c2b7553d4\")\n                        .links(Link.create(\n                              Relation.BOOKMARK,\n                              URI.create(\"http://openstack:8774/4e1900cf21924a098709c23480e157c0/images/e3f84189-964e-4dc3-8ac6-832c2b7553d4\")))\n                        .build())\n                  .flavor(Resource.builder()\n                        .id(\"6\")\n                        .links(Link.create(\n                              Relation.BOOKMARK,\n                              URI.create(\"http://openstack:8774/4e1900cf21924a098709c23480e157c0/flavors/6\")))\n                        .build())\n                  .id(\"56d51a88-0066-4976-91b6-d1b453be603f\")\n                  .userId(\"08ba127f0d6842279f9db8e8bc6977e9\")\n                  .status(Status.BUILD)\n                  .updated(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2014-03-19T11:54:59Z\"))\n                  .hostId(\"0bc453b1c10348e9dc398fed7a5b06f996964ae1643fe460a85a23d8\")\n                  .name(\"machine_5\")\n                  .created(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2014-03-19T11:54:57Z\"))\n                  .tenantId(\"4e1900cf21924a098709c23480e157c0\")\n                  .extendedStatus(ServerExtendedStatus.builder().vmState(\"building\").powerState(0).taskState(\"spawning\")\n                        .build())\n                  .diskConfig(\"MANUAL\")\n                  .availabilityZone(\"nova\")\n                  .extendedAttributes(\n                        ServerExtendedAttributes.builder()\n                              .instanceName(\"instance-0000000b\")\n                              .hostName(\"rdohavana.localdomain\")\n                              .hypervisorHostName(\"rdohavana.localdomain\").build()\n                  ).build(),\n            Server.builder()\n                  .links(\n                        Link.create(\n                              Relation.SELF,\n                              URI.create(\"http://openstack:8774/v2/4e1900cf21924a098709c23480e157c0/servers/3bc8ab03-52e7-4d2b-ba88-73f9ecadf003\")),\n                        Link.create(\n                              Relation.BOOKMARK,\n                              URI.create(\"http://openstack:8774/4e1900cf21924a098709c23480e157c0/servers/3bc8ab03-52e7-4d2b-ba88-73f9ecadf003\"))\n                  )\n                  .image(Resource.builder()\n                        .id(\"e3f84189-964e-4dc3-8ac6-832c2b7553d4\")\n                        .links(Link.create(\n                              Relation.BOOKMARK,\n                              URI.create(\"http://openstack:8774/4e1900cf21924a098709c23480e157c0/images/e3f84189-964e-4dc3-8ac6-832c2b7553d4\")))\n                        .build())\n                  .flavor(Resource.builder()\n                        .id(\"6\")\n                        .links(Link.create(\n                              Relation.BOOKMARK,\n                              URI.create(\"http://openstack:8774/4e1900cf21924a098709c23480e157c0/flavors/6\")))\n                        .build())\n                  .id(\"3bc8ab03-52e7-4d2b-ba88-73f9ecadf003\")\n                  .userId(\"08ba127f0d6842279f9db8e8bc6977e9\")\n                  .status(Status.ACTIVE)\n                  .updated(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2014-03-19T11:52:21Z\"))\n                  .hostId(\"0bc453b1c10348e9dc398fed7a5b06f996964ae1643fe460a85a23d8\")\n                  .name(\"machine_4\")\n                  .created(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2014-03-19T11:51:53Z\"))\n                  .tenantId(\"4e1900cf21924a098709c23480e157c0\")\n                  .extendedStatus(ServerExtendedStatus.builder().vmState(\"active\").powerState(1).build())\n                  .diskConfig(\"MANUAL\")\n                  .availabilityZone(\"nova\")\n                  .extendedAttributes(\n                        ServerExtendedAttributes.builder()\n                              .instanceName(\"instance-00000009\")\n                              .hostName(\"rdohavana.localdomain\")\n                              .hypervisorHostName(\"rdohavana.localdomain\").build()\n                  )\n                  .addresses(ImmutableMultimap.<String, Address>builder()\n                              .putAll(\"public\", Address.builder().addr(\"172.24.4.232\").version(4)\n                                      .macAddr(\"fa:16:3e:df:22:1b\").type(\"fixed\").build()).build()\n                  ).build(),\n            Server.builder()\n                  .links(\n                        Link.create(\n                              Relation.SELF,\n                              URI.create(\"http://openstack:8774/v2/4e1900cf21924a098709c23480e157c0/servers/cad76945-8851-489a-99e1-f1049e02c769\")),\n                        Link.create(\n                              Relation.BOOKMARK,\n                              URI.create(\"http://openstack:8774/4e1900cf21924a098709c23480e157c0/servers/cad76945-8851-489a-99e1-f1049e02c769\"))\n                  )\n                  .image(Resource.builder()\n                        .id(\"e3f84189-964e-4dc3-8ac6-832c2b7553d4\")\n                        .links(Link.create(\n                              Relation.BOOKMARK,\n                              URI.create(\"http://openstack:8774/4e1900cf21924a098709c23480e157c0/images/e3f84189-964e-4dc3-8ac6-832c2b7553d4\")))\n                        .build())\n                  .flavor(Resource.builder()\n                        .id(\"6\")\n                        .links(Link.create(\n                              Relation.BOOKMARK,\n                              URI.create(\"http://openstack:8774/4e1900cf21924a098709c23480e157c0/flavors/6\")))\n                        .build())\n                  .id(\"cad76945-8851-489a-99e1-f1049e02c769\")\n                  .userId(\"08ba127f0d6842279f9db8e8bc6977e9\")\n                  .status(Status.SHELVED_OFFLOADED)\n                  .updated(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2014-03-19T11:38:05Z\"))\n                  .name(\"machine_3\")\n                  .created(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2014-03-19T11:33:27Z\"))\n                  .tenantId(\"4e1900cf21924a098709c23480e157c0\")\n                  .extendedStatus(ServerExtendedStatus.builder().vmState(\"shelved_offloaded\").powerState(4).build())\n                  .diskConfig(\"MANUAL\")\n                  .availabilityZone(\"nova\")\n                  .extendedAttributes(\n                        ServerExtendedAttributes.builder()\n                              .instanceName(\"instance-00000006\").build()\n                  )\n                  .addresses(ImmutableMultimap.<String, Address>builder()\n                              .putAll(\"public\", Address.builder().addr(\"172.24.4.229\").version(4)\n                                      .macAddr(\"fa:16:3e:cb:56:d6\").type(\"fixed\").build()).build()\n                  ).build(),\n            Server.builder()\n                  .links(\n                        Link.create(\n                              Relation.SELF,\n                              URI.create(\"http://openstack:8774/v2/4e1900cf21924a098709c23480e157c0/servers/89142a4f-f58c-4205-8571-65f4a2be2bc9\")),\n                        Link.create(\n                              Relation.BOOKMARK,\n                              URI.create(\"http://openstack:8774/4e1900cf21924a098709c23480e157c0/servers/89142a4f-f58c-4205-8571-65f4a2be2bc9\"))\n                  )\n                  .image(Resource.builder()\n                        .id(\"e3f84189-964e-4dc3-8ac6-832c2b7553d4\")\n                        .links(Link.create(\n                              Relation.BOOKMARK,\n                              URI.create(\"http://openstack:8774/4e1900cf21924a098709c23480e157c0/images/e3f84189-964e-4dc3-8ac6-832c2b7553d4\")))\n                        .build())\n                  .flavor(Resource.builder()\n                        .id(\"6\")\n                        .links(Link.create(\n                              Relation.BOOKMARK,\n                              URI.create(\"http://openstack:8774/4e1900cf21924a098709c23480e157c0/flavors/6\")))\n                        .build())\n                  .id(\"89142a4f-f58c-4205-8571-65f4a2be2bc9\")\n                  .userId(\"08ba127f0d6842279f9db8e8bc6977e9\")\n                  .status(Status.RESCUE)\n                  .updated(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2014-03-19T11:36:05Z\"))\n                  .hostId(\"0bc453b1c10348e9dc398fed7a5b06f996964ae1643fe460a85a23d8\")\n                  .name(\"machine_2\")\n                  .created(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2014-03-19T11:31:19Z\"))\n                  .tenantId(\"4e1900cf21924a098709c23480e157c0\")\n                  .extendedStatus(ServerExtendedStatus.builder().vmState(\"rescued\").powerState(1).build())\n                  .diskConfig(\"MANUAL\")\n                  .availabilityZone(\"nova\")\n                  .extendedAttributes(\n                        ServerExtendedAttributes.builder()\n                              .instanceName(\"instance-00000005\")\n                              .hostName(\"rdohavana.localdomain\")\n                              .hypervisorHostName(\"rdohavana.localdomain\").build()\n                  )\n                  .addresses(ImmutableMultimap.<String, Address>builder()\n                              .putAll(\"public\", Address.builder().addr(\"172.24.4.227\").version(4)\n                                      .macAddr(\"fa:16:3e:18:fe:c8\").type(\"fixed\").build()).build()\n                  ).build(),\n            Server.builder()\n                  .links(\n                        Link.create(\n                              Relation.SELF,\n                              URI.create(\"http://openstack:8774/v2/4e1900cf21924a098709c23480e157c0/servers/fac50d26-bb38-455f-ad92-eba790187c00\")),\n                        Link.create(\n                              Relation.BOOKMARK,\n                              URI.create(\"http://openstack:8774/4e1900cf21924a098709c23480e157c0/servers/fac50d26-bb38-455f-ad92-eba790187c00\"))\n                  )\n                  .image(Resource.builder()\n                        .id(\"e3f84189-964e-4dc3-8ac6-832c2b7553d4\")\n                        .links(Link.create(\n                              Relation.BOOKMARK,\n                              URI.create(\"http://openstack:8774/4e1900cf21924a098709c23480e157c0/images/e3f84189-964e-4dc3-8ac6-832c2b7553d4\")))\n                        .build())\n                  .flavor(Resource.builder()\n                        .id(\"6\")\n                        .links(Link.create(\n                              Relation.BOOKMARK,\n                              URI.create(\"http://openstack:8774/4e1900cf21924a098709c23480e157c0/flavors/6\")))\n                        .build())\n                  .id(\"fac50d26-bb38-455f-ad92-eba790187c00\")\n                  .userId(\"08ba127f0d6842279f9db8e8bc6977e9\")\n                  .status(Status.SHUTOFF)\n                  .updated(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2014-03-19T11:35:26Z\"))\n                  .hostId(\"0bc453b1c10348e9dc398fed7a5b06f996964ae1643fe460a85a23d8\")\n                  .name(\"machine_1\")\n                  .created(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2014-03-19T11:28:56Z\"))\n                  .tenantId(\"4e1900cf21924a098709c23480e157c0\")\n                  .extendedStatus(ServerExtendedStatus.builder().vmState(\"stopped\").powerState(4).build())\n                  .diskConfig(\"MANUAL\")\n                  .availabilityZone(\"nova\")\n                  .extendedAttributes(\n                        ServerExtendedAttributes.builder()\n                              .instanceName(\"instance-00000004\")\n                              .hostName(\"rdohavana.localdomain\")\n                              .hypervisorHostName(\"rdohavana.localdomain\").build()\n                  )\n                  .addresses(ImmutableMultimap.<String, Address>builder()\n                              .putAll(\"public\", Address.builder().addr(\"172.24.4.228\").version(4)\n                                      .macAddr(\"fa:16:3e:64:1a:d5\").type(\"fixed\").build()).build()\n                  ).build()\n      );\n   }\n\n\n   protected Injector injector() {\n      return Guice.createInjector(new NovaParserModule(), new GsonModule());\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseServerDiagnostics.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/*\n * To change this template, choose Tools | Templates\n * and open the template in the editor.\n */\npackage org.jclouds.openstack.nova.v2_0.parse;\n\nimport java.util.Map;\n\nimport org.jclouds.json.BaseItemParserTest;\n\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableMap;\n\npublic class ParseServerDiagnostics extends BaseItemParserTest<Optional<Map<String, String>>> {\n\n\n    @Override\n    public Optional<Map<String, String>> expected() {\n        return Optional.<Map<String, String>>of(\n                new ImmutableMap.Builder<String, String>()\n                .put(\"vnet0_tx_errors\", \"0\")\n                .put(\"vda_read\", \"77364736\")\n                .put(\"vda_write\", \"415446016\")\n                .put(\"vnet0_tx_packets\", \"9701\")\n                .put(\"vda_write_req\", \"47278\")\n                .put(\"cpu0_time\", \"143150000000\")\n                .put(\"vnet0_tx\", \"1691221\")\n                .put(\"vnet0_rx_drop\", \"0\")\n                .put(\"vda_errors\", \"-1\")\n                .put(\"vnet0_rx_errors\", \"0\")\n                .put(\"memory\", \"524288\")\n                .put(\"vnet0_rx_packets\", \"11271\")\n                .put(\"vda_read_req\", \"9551\")\n                .put(\"vnet0_rx\", \"1805288\")\n                .put(\"vnet0_tx_drop\", \"0\").build());\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseServerListTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.parse;\n\nimport java.net.URI;\nimport java.util.Set;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.json.BaseSetParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.openstack.nova.v2_0.config.NovaParserModule;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.Link.Relation;\nimport org.jclouds.openstack.v2_0.domain.Resource;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\", testName = \"ParseServerListTest\")\npublic class ParseServerListTest extends BaseSetParserTest<Resource> {\n\n   @Override\n   public String resource() {\n      return \"/server_list.json\";\n   }\n\n   @Override\n   @SelectJson(\"servers\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Set<Resource> expected() {\n      return ImmutableSet\n            .of(Resource\n                  .builder()\n                  .id(\"52415800-8b69-11e0-9b19-734f6af67565\")\n                  .name(\"sample-server\")\n                  .links(\n                        Link.create(\n                              Relation.SELF,\n                              URI.create(\"http://servers.api.openstack.org/v2/1234/servers/52415800-8b69-11e0-9b19-734f6af67565\")),\n                        Link.create(\n                              Relation.BOOKMARK,\n                              URI.create(\"http://servers.api.openstack.org/1234/servers/52415800-8b69-11e0-9b19-734f6af67565\")))\n                  .build(),\n                  Resource\n                        .builder()\n                        .id(\"52415800-8b69-11e0-9b19-734f1f1350e5\")\n                        .name(\"sample-server2\")\n                        .links(\n                              Link.create(\n                                    Relation.SELF,\n                                    URI.create(\"http://servers.api.openstack.org/v2/1234/servers/52415800-8b69-11e0-9b19-734f1f1350e5\")),\n                              Link.create(\n                                    Relation.BOOKMARK,\n                                    URI.create(\"http://servers.api.openstack.org/1234/servers/52415800-8b69-11e0-9b19-734f1f1350e5\")))\n                        .build());\n   }\n\n   protected Injector injector() {\n      return Guice.createInjector(new NovaParserModule(), new GsonModule());\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseServerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.parse;\n\nimport static org.jclouds.openstack.nova.v2_0.domain.Address.createV4;\nimport static org.jclouds.openstack.nova.v2_0.domain.Address.createV6;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.openstack.nova.v2_0.config.NovaParserModule;\nimport org.jclouds.openstack.nova.v2_0.domain.Address;\nimport org.jclouds.openstack.nova.v2_0.domain.Server;\nimport org.jclouds.openstack.nova.v2_0.domain.Server.Status;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.Link.Relation;\nimport org.jclouds.openstack.v2_0.domain.Resource;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\", testName = \"ParseServerTest\")\npublic class ParseServerTest extends BaseItemParserTest<Server> {\n\n   @Override\n   public String resource() {\n      return \"/server_details.json\";\n   }\n\n   @Override\n   @SelectJson(\"server\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Server expected() {\n      return Server\n            .builder()\n            .id(\"71752\")\n            .tenantId(\"1234\")\n            .userId(\"5678\")\n            .name(\"sample-f352\")\n            .updated(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2010-10-10T12:00:00Z\"))\n            .created(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2010-08-10T12:00:00Z\"))\n            .hostId(\"e4d909c290d0fb1ca068ffaddf22cbd0\")\n            .accessIPv4(\"67.23.10.132\")\n            .accessIPv6(\"::babe:67.23.10.132\")\n            .status(Status.ACTIVE)\n            .diskConfig(Server.DISK_CONFIG_AUTO)\n            .availabilityZone(\"nova\")\n            .image(\n                  Resource\n                        .builder()\n                        .id(\"52415800-8b69-11e0-9b19-734f6f006e54\")\n                        .name(\"null\")\n                        .links(\n                              Link.create(\n                                    Relation.SELF,\n                                    URI.create(\"http://servers.api.openstack.org/v2/1234/images/52415800-8b69-11e0-9b19-734f6f006e54\")),\n                              Link.create(\n                                    Relation.BOOKMARK,\n                                    URI.create(\"http://servers.api.openstack.org/1234/images/52415800-8b69-11e0-9b19-734f6f006e54\"))\n                        )\n                        .build()\n            )\n            .flavor(\n                  Resource\n                        .builder()\n                        .id(\"52415800-8b69-11e0-9b19-734f216543fd\")\n                        .name(\"null\")\n                        .links(\n                              Link.create(\n                                    Relation.SELF,\n                                    URI.create(\"http://servers.api.openstack.org/v2/1234/flavors/52415800-8b69-11e0-9b19-734f216543fd\")),\n                              Link.create(\n                                    Relation.BOOKMARK,\n                                    URI.create(\"http://servers.api.openstack.org/1234/flavors/52415800-8b69-11e0-9b19-734f216543fd\"))\n                        )\n                        .build()\n            )\n            .metadata(\n                  new ImmutableMap.Builder<String, String>().put(\"Server Label\", \"Web Head 1\")\n                        .put(\"Image Version\", \"2.1\").build()\n            )\n            .addresses(ImmutableMultimap.<String, Address>builder()\n                  .putAll(\"public\", createV4(\"67.23.10.132\"), createV6(\"::babe:67.23.10.132\"), createV4(\"67.23.10.131\"), createV6(\"::babe:4317:0A83\"))\n                  .putAll(\"private\", createV4(\"10.176.42.16\"), createV6(\"::babe:10.176.42.16\"))\n                  .build())\n            .links(Link.create(\n                        Relation.SELF, URI.create(\"http://servers.api.openstack.org/v2/1234/servers/71752\")),\n                  Link.create(\n                        Relation.BOOKMARK,\n                        URI.create(\"http://servers.api.openstack.org/1234/servers/71752\"))\n            )\n            .build();\n   }\n\n   protected Injector injector() {\n      return Guice.createInjector(new NovaParserModule(), new GsonModule());\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseServerWithAddressExtensionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.parse;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.openstack.nova.v2_0.config.NovaParserModule;\nimport org.jclouds.openstack.nova.v2_0.domain.Address;\nimport org.jclouds.openstack.nova.v2_0.domain.Server;\nimport org.jclouds.openstack.nova.v2_0.domain.Server.Status;\nimport org.jclouds.openstack.nova.v2_0.domain.ServerExtendedStatus;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.Link.Relation;\nimport org.jclouds.openstack.v2_0.domain.Resource;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\nimport java.net.URI;\n\n@Test(groups = \"unit\", testName = \"ParseServerWithAddressExtensionsTest\")\npublic class ParseServerWithAddressExtensionsTest extends BaseItemParserTest<Server> {\n\n   @Override\n   public String resource() {\n      return \"/server_details_with_address_ext.json\";\n   }\n\n   @Override\n   @SelectJson(\"server\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Server expected() {\n      return Server\n         .builder()\n         .id(\"0bdc3a8d-3a96-4ccc-bb40-715537a7df7b\")\n         .tenantId(\"cac29c920a6149aabe499757b6ba81c7\")\n         .userId(\"ed15e338032f4a2c85b7fa80e40b9917\")\n         .name(\"cloudts-f07\")\n         .updated(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2016-02-17T14:48:00Z\"))\n         .created(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2016-02-17T14:46:13Z\"))\n         .hostId(\"18a9cd55f76c520dcad6c31d5b2b8f4c921979629c0274c0f7d2de39\")\n         .status(Status.ACTIVE)\n         .image(\n            Resource\n               .builder()\n               .id(\"9a9f496a-f5c2-4286-81a4-98189a48777a\")\n               .links(\n                  Link.create(\n                     Relation.BOOKMARK,\n                     URI.create(\"http://openstack:8774/cac29c920a6149aabe499757b6ba81c7/images/9a9f496a-f5c2-4286-81a4-98189a48777a\")))\n               .build())\n         .flavor(\n            Resource\n               .builder()\n               .id(\"3\")\n               .links(\n                  Link.create(\n                     Relation.BOOKMARK,\n                     URI.create(\"http://openstack:8774/cac29c920a6149aabe499757b6ba81c7/flavors/3\")))\n                .build())\n         .links(\n            Link.create(\n               Relation.SELF,\n               URI.create(\"http://openstack:8774/v2/cac29c920a6149aabe499757b6ba81c7/servers/0bdc3a8d-3a96-4ccc-bb40-715537a7df7b\")),\n            Link.create(\n               Relation.BOOKMARK,\n               URI.create(\"http://openstack:8774/cac29c920a6149aabe499757b6ba81c7/servers/0bdc3a8d-3a96-4ccc-bb40-715537a7df7b\")))\n         .metadata(ImmutableMap.<String, String>of(\"jclouds-group\", \"cloudts\"))\n         .addresses(ImmutableMultimap.<String, Address>builder()\n            .putAll(\"jenkins\",\n               Address.builder().version(4).addr(\"172.16.130.24\").macAddr(\"fa:16:3e:bf:82:43\").type(\"fixed\").build(),\n               Address.builder().version(4).addr(\"10.8.54.75\").macAddr(\"fa:16:3e:bf:82:43\").type(\"floating\").build())\n            .build())\n         .diskConfig(\"MANUAL\")\n         .configDrive(\"\")\n         .availabilityZone(\"nova\")\n         .accessIPv4(\"\")\n         .accessIPv6(\"\")\n         .keyName(\"jenkins\")\n         .extendedStatus(ServerExtendedStatus.builder().vmState(\"active\").powerState(1).build())\n         .build();\n   }\n\n   protected Injector injector() {\n      return Guice.createInjector(new NovaParserModule(), new GsonModule());\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseServerWithAllExtensionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.parse;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.openstack.nova.v2_0.config.NovaParserModule;\nimport org.jclouds.openstack.nova.v2_0.domain.Address;\nimport org.jclouds.openstack.nova.v2_0.domain.Server;\nimport org.jclouds.openstack.nova.v2_0.domain.Server.Status;\nimport org.jclouds.openstack.nova.v2_0.domain.ServerExtendedAttributes;\nimport org.jclouds.openstack.nova.v2_0.domain.ServerExtendedStatus;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.Link.Relation;\nimport org.jclouds.openstack.v2_0.domain.Resource;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\", testName = \"ParseServerWithAllExtensionsTest\")\npublic class ParseServerWithAllExtensionsTest extends BaseItemParserTest<Server> {\n\n   @Override\n   public String resource() {\n      return \"/server_details_devstack.json\";\n   }\n\n   @Override\n   @SelectJson(\"server\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Server expected() {\n      return Server\n            .builder()\n            .id(\"141b775f-7ac1-45f0-9a95-146260f33a53\")\n            .tenantId(\"7f312675f9b84c97bff8f5054e181419\")\n            .userId(\"89c01b67395d4bea945f7f5bfd7f344a\")\n            .name(\"test\")\n            .updated(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2012-05-04T15:07:48Z\"))\n            .created(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2012-05-04T15:07:36Z\"))\n            .hostId(\"eab9a77d1c44b8833e4a3dc6d2d9d50de556e780a319f184d8c82d9b\")\n            .status(Status.PAUSED)\n            .image(\n                  Resource\n                        .builder()\n                        .id(\"8e6f5bc4-a210-45b2-841f-c510eae14300\")\n                        .links(\n                              Link.create(\n                                    Relation.BOOKMARK,\n                                    URI.create(\"http://172.16.89.149:8774/7f312675f9b84c97bff8f5054e181419/images/8e6f5bc4-a210-45b2-841f-c510eae14300\")))\n                        .build())\n            .flavor(\n                  Resource\n                        .builder()\n                        .id(\"1\")\n                        .links(\n                              Link.create(\n                                    Relation.BOOKMARK,\n                                    URI.create(\"http://172.16.89.149:8774/7f312675f9b84c97bff8f5054e181419/flavors/1\")))\n                        .build())\n            .links(\n                  Link.create(\n                        Relation.SELF,\n                        URI.create(\"http://172.16.89.149:8774/v2/7f312675f9b84c97bff8f5054e181419/servers/141b775f-7ac1-45f0-9a95-146260f33a53\")),\n                  Link.create(\n                        Relation.BOOKMARK,\n                        URI.create(\"http://172.16.89.149:8774/7f312675f9b84c97bff8f5054e181419/servers/141b775f-7ac1-45f0-9a95-146260f33a53\")))\n            .addresses(ImmutableMultimap.of(\"private\", Address.createV4(\"10.0.0.8\")))\n            .diskConfig(\"MANUAL\")\n            .extendedStatus(ServerExtendedStatus.builder().vmState(\"paused\").powerState(3).build())\n            .extendedAttributes(ServerExtendedAttributes.builder().instanceName(\"instance-00000014\").hostName(\"ubuntu\").build())\n            .build();\n   }\n  \n\n   protected Injector injector() {\n      return Guice.createInjector(new NovaParserModule(), new GsonModule());\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseServerWithInternetAddressesTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.parse;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.openstack.nova.v2_0.config.NovaParserModule;\nimport org.jclouds.openstack.nova.v2_0.domain.Address;\nimport org.jclouds.openstack.nova.v2_0.domain.Server;\nimport org.jclouds.openstack.nova.v2_0.domain.Server.Status;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.Link.Relation;\nimport org.jclouds.openstack.v2_0.domain.Resource;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\", testName = \"ParseServerTest\")\npublic class ParseServerWithInternetAddressesTest extends BaseItemParserTest<Server> {\n\n   @Override\n   public String resource() {\n      return \"/server_details_openstack.json\";\n   }\n\n   @Override\n   @SelectJson(\"server\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Server expected() {\n      return Server\n            .builder()\n            .id(\"1459\")\n            .uuid(\"2443c9c7-9791-412e-ac09-a6d55ec25335\")\n            .tenantId(\"37\")\n            .userId(\"508151008\")\n            .name(\"mygroup-72c\")\n            .updated(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2012-03-23T01:30:26Z\"))\n            .created(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2012-03-23T01:30:26Z\"))\n            .hostId(\"881706597197955ac7cc4b353bc7ec884e13fa280de9cc82057796cb\")\n            .status(Status.ACTIVE)\n            .image(\n                  Resource\n                        .builder()\n                        .id(\"14\")\n                        .links(\n                              Link.create(\n                                    Relation.BOOKMARK,\n                                    URI.create(\"https://nova-api.openstack.org:9774/37/images/14\")))\n                        .build())\n            .flavor(\n                  Resource\n                        .builder()\n                        .id(\"1\")\n                        .links(\n                              Link.create(\n                                    Relation.BOOKMARK,\n                                    URI.create(\"https://nova-api.openstack.org:9774/37/flavors/1\")))\n                        .build())\n            .links(\n                  Link.create(\n                         Relation.SELF,\n                         URI.create(\"https://nova-api.openstack.org:9774/v2/37/servers/1459\")),\n                  Link.create(\n                         Relation.BOOKMARK,\n                         URI.create(\"https://nova-api.openstack.org:9774/37/servers/1459\")))\n            .addresses(ImmutableMultimap.of(\"internet\", Address.createV4(\"8.21.28.47\"))).build();\n   }\n  \n\n   protected Injector injector() {\n      return Guice.createInjector(new NovaParserModule(), new GsonModule());\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseServerWithoutImageTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.parse;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.openstack.nova.v2_0.config.NovaParserModule;\nimport org.jclouds.openstack.nova.v2_0.domain.Address;\nimport org.jclouds.openstack.nova.v2_0.domain.Server;\nimport org.jclouds.openstack.nova.v2_0.domain.Server.Status;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.Link.Relation;\nimport org.jclouds.openstack.v2_0.domain.Resource;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\nimport java.net.URI;\n\nimport static org.jclouds.openstack.nova.v2_0.domain.Address.createV4;\nimport static org.jclouds.openstack.nova.v2_0.domain.Address.createV6;\n\n@Test(groups = \"unit\", testName = \"ParseServerWithoutImageTest\")\npublic class ParseServerWithoutImageTest extends BaseItemParserTest<Server> {\n\n   @Override\n   public String resource() {\n      return \"/server_details_without_image.json\";\n   }\n\n   @Override\n   @SelectJson(\"server\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Server expected() {\n      return Server\n            .builder()\n            .id(\"71752\")\n            .tenantId(\"1234\")\n            .userId(\"5678\")\n            .name(\"sample-f352\")\n            .updated(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2010-10-10T12:00:00Z\"))\n            .created(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2010-08-10T12:00:00Z\"))\n            .hostId(\"e4d909c290d0fb1ca068ffaddf22cbd0\")\n            .accessIPv4(\"67.23.10.132\")\n            .accessIPv6(\"::babe:67.23.10.132\")\n            .status(Status.BUILD)\n            .diskConfig(Server.DISK_CONFIG_AUTO)\n            .flavor(\n                  Resource\n                        .builder()\n                        .id(\"52415800-8b69-11e0-9b19-734f216543fd\")\n                        .name(\"null\")\n                        .links(\n                              Link.create(\n                                    Relation.SELF,\n                                    URI.create(\"http://servers.api.openstack.org/v1.1/1234/flavors/52415800-8b69-11e0-9b19-734f216543fd\")),\n                              Link.create(\n                                    Relation.BOOKMARK,\n                                    URI.create(\"http://servers.api.openstack.org/1234/flavors/52415800-8b69-11e0-9b19-734f216543fd\")))\n                        .build())\n            .metadata(\n                  new ImmutableMap.Builder<String, String>().put(\"Server Label\", \"Web Head 1\")\n                        .put(\"Image Version\", \"2.1\").build())\n            .addresses(ImmutableMultimap.<String, Address>builder()\n                  .putAll(\"public\", createV4(\"67.23.10.132\"), createV6(\"::babe:67.23.10.132\"), createV4(\"67.23.10.131\"), createV6(\"::babe:4317:0A83\"))\n                  .putAll(\"private\", createV4(\"10.176.42.16\"), createV6(\"::babe:10.176.42.16\"))\n                  .build())\n            .links(Link.create(\n                        Relation.SELF, URI.create(\"http://servers.api.openstack.org/v2/1234/servers/71752\")),\n                   Link.create(\n                        Relation.BOOKMARK,\n                        URI.create(\"http://servers.api.openstack.org/1234/servers/71752\")))\n            .build();\n   }\n\n   protected Injector injector() {\n      return Guice.createInjector(new NovaParserModule(), new GsonModule());\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseXVPVNCConsoleTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.parse;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.openstack.nova.v2_0.config.NovaParserModule;\nimport org.jclouds.openstack.nova.v2_0.domain.Console;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Throwables;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n/**\n * Tests parsing of vnc console response. \n */\n@Test(groups = \"unit\", testName = \"ParseXVPVNCConsoleTest\")\npublic class ParseXVPVNCConsoleTest extends BaseItemParserTest<Console> {\n\n   @Override\n   public String resource() {\n      return \"/xvpvnc_console.json\";\n   }\n\n   @Override\n   @SelectJson(\"console\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Console expected() {\n      Console console = null;\n      try {\n         console = Console\n            .builder()\n            .url(new URI(\"http://example.com:6081/console?token=2abbe0b2-dcf1-479d-8d58-88e82b477865\"))\n            .type(Console.Type.XVPVNC)\n            .build();\n      } catch (Exception e) {\n         Throwables.propagate(e);\n      }\n\n      return console;\n   }\n\n   protected Injector injector() {\n      return Guice.createInjector(new NovaParserModule(), new GsonModule());\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/PublicIpsInPrivateAddressBlockExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.parse;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.openstack.nova.v2_0.config.NovaParserModule;\nimport org.jclouds.openstack.nova.v2_0.domain.Address;\nimport org.jclouds.openstack.nova.v2_0.domain.Server;\nimport org.jclouds.openstack.nova.v2_0.domain.Server.Status;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.Link.Relation;\nimport org.jclouds.openstack.v2_0.domain.Resource;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\", testName = \"ParseCreatedServerTest\")\npublic class PublicIpsInPrivateAddressBlockExpectTest extends BaseItemParserTest<Server> {\n\n   @Override\n   public String resource() {\n      return \"/server_public_ip_in_private.json\";\n   }\n\n   @Override\n   @SelectJson(\"server\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Server expected() {\n      return Server\n            .builder()\n            .id(\"59662\")\n            .hostId(\"cb0d9e5004bef8c21270a0b09f7624f4c387f3a523f3aaa4c5694a61\")\n            .uuid(\"7aed8e05-1daf-476a-87b2-640e8f7dcafd\")\n            .tenantId(\"37936628937291\")\n            .userId(\"54297837463082\")\n            .name(\"hpcloud-computes-38d\")\n            .updated(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2012-03-22T22:11:55Z\"))\n            .created(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2012-03-22T22:11:19Z\"))\n            .status(Status.ACTIVE)\n            .keyName(\"jclouds_hpcloud-computes_77\")\n            .image(\n                  Resource\n                        .builder()\n                        .id(\"229\")\n                        .links(\n                              Link.create(\n                                    Relation.BOOKMARK,\n                                    URI.create(\"https://az-2.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/images/229\")))\n                        .build())\n            .flavor(\n                  Resource\n                        .builder()\n                        .id(\"100\")\n                        .links(\n                              Link.create(\n                                    Relation.BOOKMARK,\n                                    URI.create(\"https://az-2.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/flavors/100\")))\n                        .build())\n            .metadata(ImmutableMap.of(\"Name\", \"hpcloud-computes\"))\n            .addresses(ImmutableMultimap.<String, Address>builder()\n                  .putAll(\"private\", Address.createV4(\"10.6.39.189\"), Address.createV4(\"15.185.181.94\")).build())\n            .links(\n                     Link.create(Relation.SELF, URI.create(\"https://az-2.region-a.geo-1.compute.hpcloudsvc.com/v2/37936628937291/servers/59662\")),\n                     Link.create(Relation.BOOKMARK, URI.create(\"https://az-2.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/servers/59662\"))).build();\n\n   }\n\n   protected Injector injector() {\n      return Guice.createInjector(new NovaParserModule(), new GsonModule());\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/predicates/ImagePredicatesTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.predicates;\n\nimport static org.jclouds.openstack.nova.v2_0.predicates.ImagePredicates.statusEquals;\n\nimport org.jclouds.openstack.nova.v2_0.domain.Image;\nimport org.jclouds.openstack.nova.v2_0.domain.Image.Status;\nimport org.jclouds.openstack.nova.v2_0.parse.ParseImageTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ImagePredicatesTest\")\npublic class ImagePredicatesTest {\n   Image ref = new ParseImageTest().expected();\n\n   @Test\n   public void teststatusEqualsWhenEqual() {\n      assert statusEquals(Status.SAVING).apply(ref);\n   }\n\n   @Test\n   public void teststatusEqualsWhenNotEqual() {\n      assert !statusEquals(Status.DELETED).apply(ref);\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/predicates/SecurityGroupPredicatesTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.v2_0.predicates;\n\nimport static org.jclouds.openstack.nova.v2_0.predicates.SecurityGroupPredicates.nameEquals;\nimport static org.jclouds.openstack.nova.v2_0.predicates.SecurityGroupPredicates.nameIn;\nimport static org.jclouds.openstack.nova.v2_0.predicates.SecurityGroupPredicates.ruleCidr;\nimport static org.jclouds.openstack.nova.v2_0.predicates.SecurityGroupPredicates.ruleEndPort;\nimport static org.jclouds.openstack.nova.v2_0.predicates.SecurityGroupPredicates.ruleGroup;\nimport static org.jclouds.openstack.nova.v2_0.predicates.SecurityGroupPredicates.ruleProtocol;\nimport static org.jclouds.openstack.nova.v2_0.predicates.SecurityGroupPredicates.ruleStartPort;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.net.domain.IpProtocol;\nimport org.jclouds.openstack.nova.v2_0.domain.SecurityGroup;\nimport org.jclouds.openstack.nova.v2_0.domain.SecurityGroupRule;\nimport org.jclouds.openstack.nova.v2_0.domain.TenantIdAndName;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\", testName = \"SecurityGroupPredicatesTest\")\npublic class SecurityGroupPredicatesTest {\n   SecurityGroup ref = SecurityGroup.builder().id(\"12345\").name(\"jclouds\").description(\"description\").build();\n   SecurityGroupRule ruleRef = SecurityGroupRule.builder().id(\"6789\").parentGroupId(\"12345\").ipRange(\"0.0.0.0/0\")\n           .fromPort(10).toPort(20).ipProtocol(IpProtocol.TCP)\n           .group(TenantIdAndName.builder().tenantId(\"11111111\").name(\"abcd\").build())\n           .build();\n\n   public void testnameEqualsWhenEqual() {\n      assertTrue(nameEquals(\"jclouds\").apply(ref), \"expected 'jclouds' as the name of \" + ref);\n   }\n\n   @Test\n   public void testnameEqualsWhenNotEqual() {\n      assertTrue(!nameEquals(\"foo\").apply(ref), \"expected 'foo' not to be the name of \" + ref);\n   }\n\n   @Test\n   public void testNameInWhenIn() {\n      assertTrue(nameIn(ImmutableSet.of(\"jclouds\", \"pants\")).apply(ref),\n              \"expected the name of \" + ref + \" to be one of 'jclouds' or 'pants'\");\n   }\n\n   @Test\n   public void testNameInWhenNotIn() {\n      assertTrue(!nameIn(ImmutableSet.of(\"foo\", \"pants\")).apply(ref),\n              \"expected the name of \" + ref + \" to not be either of 'foo' or 'pants'\");\n\n   }\n\n   @Test\n   public void testRuleCidrWhenEqual() {\n      assertTrue(ruleCidr(\"0.0.0.0/0\").apply(ruleRef),\n              \"expected the CIDR to be '0.0.0.0/0' for \" + ruleRef);\n   }\n\n   @Test\n   public void testRuleCidrWhenNotEqual() {\n      assertTrue(!ruleCidr(\"1.1.1.1/0\").apply(ruleRef),\n              \"expected the CIDR to not be '1.1.1.1/0' for \" + ruleRef);\n   }\n\n   @Test\n   public void testRuleGroupWhenEqual() {\n      assertTrue(ruleGroup(\"abcd\").apply(ruleRef),\n              \"expected the group to be equal to 'abcd' for \" + ruleRef);\n   }\n\n   @Test\n   public void testRuleGroupWhenNotEqual() {\n      assertTrue(!ruleGroup(\"pants\").apply(ruleRef),\n              \"expected the group to not be equal to 'pants' for \" + ruleRef);\n   }\n\n   @Test\n   public void testRuleProtocolWhenEqual() {\n      assertTrue(ruleProtocol(IpProtocol.TCP).apply(ruleRef),\n              \"expected TCP for \" + ruleRef);\n   }\n\n   @Test\n   public void testRuleProtocolWhenNotEqual() {\n      assertTrue(!ruleProtocol(IpProtocol.UDP).apply(ruleRef),\n              \"expected not UDP for \" + ruleRef);\n   }\n\n   @Test\n   public void testRuleStartPortWhenEqual() {\n      assertTrue(ruleStartPort(10).apply(ruleRef),\n              \"expected start port 10 for \" + ruleRef);\n   }\n\n   @Test\n   public void testRuleStartPortWhenNotEqual() {\n      assertTrue(!ruleStartPort(50).apply(ruleRef),\n              \"expected start port not to be 50 for \" + ruleRef);\n   }\n\n   @Test\n   public void testRuleEndPortWhenEqual() {\n      assertTrue(ruleEndPort(20).apply(ruleRef),\n              \"expected end port 20 for \" + ruleRef);\n   }\n\n   @Test\n   public void testRuleEndPortWhenNotEqual() {\n      assertTrue(!ruleEndPort(50).apply(ruleRef),\n              \"expected end port not to be 50 for \" + ruleRef);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/access.json",
    "content": "{\n    \"access\": {\n        \"metadata\": {\n            \"roles\": [\n                \"9fe2ff9ee4384b1894a90878d3e92bab\",\n                \"b926cb0f4e2642678735f86c2b06205e\",\n                \"33484487e73d4da0918a19b9c7e1f8ae\",\n                \"f2e54c2105fb49e29479af047115cebc\"\n            ],\n            \"is_admin\": 0\n        },\n        \"user\": {\n            \"name\": \"joe\",\n            \"roles\": [\n                {\n                    \"name\": \"_member_\"\n                },\n                {\n                    \"name\": \"anotherrole\"\n                },\n                {\n                    \"name\": \"heat_stack_owner\"\n                },\n                {\n                    \"name\": \"Member\"\n                }\n            ],\n            \"id\": \"8fbf8e68d36e4ac7bcf912a26213bd49\",\n            \"roles_links\": [],\n            \"username\": \"joe\"\n        },\n        \"serviceCatalog\": [\n            {\n                \"name\": \"nova\",\n                \"type\": \"compute\",\n                \"endpoints_links\": [],\n                \"endpoints\": [\n                    {\n                        \"publicURL\": \"URL/v2/da0d12be20394afb851716e10a49e4a7\",\n                        \"id\": \"2122bcaa704343c19ad2578410d4961d\",\n                        \"internalURL\": \"URL/v2/da0d12be20394afb851716e10a49e4a7\",\n                        \"region\": \"RegionOne\",\n                        \"adminURL\": \"URL/v2/da0d12be20394afb851716e10a49e4a7\"\n                    },\n                    {\n                        \"publicURL\": \"URL/v2/ba0d12be20394afb851716e10a49e4a8\",\n                        \"id\": \"2122bcaa704343c19ad2578410d4961d\",\n                        \"internalURL\": \"URL/v2/ba0d12be20394afb851716e10a49e4a8\",\n                        \"region\": \"RegionTwo\",\n                        \"adminURL\": \"URL/v2/ba0d12be20394afb851716e10a49e4a8\"\n                    },\n                    {\n                        \"publicURL\": \"URL/v2/ca0d12be20394afb851716e10a49e4a9\",\n                        \"id\": \"2122bcaa704343c19ad2578410d4961d\",\n                        \"internalURL\": \"URL/v2/ca0d12be20394afb851716e10a49e4a9\",\n                        \"region\": \"RegionThree\",\n                        \"adminURL\": \"URL/v2/ca0d12be20394afb851716e10a49e4a9\"\n                    }\n                ]\n            },\n            {\n                \"name\": \"neutron\",\n                \"type\": \"network\",\n                \"endpoints_links\": [],\n                \"endpoints\": [\n                    {\n                        \"publicURL\": \"URL/\",\n                        \"id\": \"65a4d3f13cfb49a6a57a04e205cc2158\",\n                        \"internalURL\": \"URL/\",\n                        \"region\": \"RegionOne\",\n                        \"adminURL\": \"URL/\"\n                    }\n                ]\n            },\n            {\n                \"name\": \"cinderv2\",\n                \"type\": \"volumev2\",\n                \"endpoints_links\": [],\n                \"endpoints\": [\n                    {\n                        \"publicURL\": \"URL/v2/da0d12be20394afb851716e10a49e4a7\",\n                        \"id\": \"31fe4d92eac44044b05be21c6f44cebc\",\n                        \"internalURL\": \"URL/v2/da0d12be20394afb851716e10a49e4a7\",\n                        \"region\": \"RegionOne\",\n                        \"adminURL\": \"URL/v2/da0d12be20394afb851716e10a49e4a7\"\n                    }\n                ]\n            },\n            {\n                \"name\": \"trove\",\n                \"type\": \"database\",\n                \"endpoints_links\": [],\n                \"endpoints\": [\n                    {\n                        \"publicURL\": \"URL/v1.0/da0d12be20394afb851716e10a49e4a7\",\n                        \"id\": \"06b7a7dbd25c4a01819c879700a9712a\",\n                        \"internalURL\": \"URL/v1.0/da0d12be20394afb851716e10a49e4a7\",\n                        \"region\": \"RegionOne\",\n                        \"adminURL\": \"URL/v1.0/da0d12be20394afb851716e10a49e4a7\"\n                    }\n                ]\n            },\n            {\n                \"name\": \"s3\",\n                \"type\": \"s3\",\n                \"endpoints_links\": [],\n                \"endpoints\": [\n                    {\n                        \"publicURL\": \"URL\",\n                        \"id\": \"93b0b67091324e8ba01b62ee0584994c\",\n                        \"internalURL\": \"URL\",\n                        \"region\": \"RegionOne\",\n                        \"adminURL\": \"URL\"\n                    }\n                ]\n            },\n            {\n                \"name\": \"glance\",\n                \"type\": \"image\",\n                \"endpoints_links\": [],\n                \"endpoints\": [\n                    {\n                        \"publicURL\": \"URL\",\n                        \"id\": \"a542e91bcfa046bfa1bf2397356d1414\",\n                        \"internalURL\": \"URL\",\n                        \"region\": \"RegionOne\",\n                        \"adminURL\": \"URL\"\n                    }\n                ]\n            },\n            {\n                \"name\": \"novav3\",\n                \"type\": \"computev3\",\n                \"endpoints_links\": [],\n                \"endpoints\": [\n                    {\n                        \"publicURL\": \"URL/v3\",\n                        \"id\": \"9c3e8abb576d483db93bcef70c67bc1d\",\n                        \"internalURL\": \"URL/v3\",\n                        \"region\": \"RegionOne\",\n                        \"adminURL\": \"URL/v3\"\n                    }\n                ]\n            },\n            {\n                \"name\": \"heat\",\n                \"type\": \"cloudformation\",\n                \"endpoints_links\": [],\n                \"endpoints\": [\n                    {\n                        \"publicURL\": \"URL/v1\",\n                        \"id\": \"6f4ca5ca9698425b85c300b3fc176c39\",\n                        \"internalURL\": \"URL/v1\",\n                        \"region\": \"RegionOne\",\n                        \"adminURL\": \"URL/v1\"\n                    }\n                ]\n            },\n            {\n                \"name\": \"cinder\",\n                \"type\": \"volume\",\n                \"endpoints_links\": [],\n                \"endpoints\": [\n                    {\n                        \"publicURL\": \"URL/v1/da0d12be20394afb851716e10a49e4a7\",\n                        \"id\": \"037039c676694a35aa28d34fce09e51d\",\n                        \"internalURL\": \"URL/v1/da0d12be20394afb851716e10a49e4a7\",\n                        \"region\": \"RegionOne\",\n                        \"adminURL\": \"URL/v1/da0d12be20394afb851716e10a49e4a7\"\n                    }\n                ]\n            },\n            {\n                \"name\": \"ec2\",\n                \"type\": \"ec2\",\n                \"endpoints_links\": [],\n                \"endpoints\": [\n                    {\n                        \"publicURL\": \"URL/services/Cloud\",\n                        \"id\": \"1d242631bccb4ff4ba7a395dbcb51648\",\n                        \"internalURL\": \"URL/services/Cloud\",\n                        \"region\": \"RegionOne\",\n                        \"adminURL\": \"URL/services/Admin\"\n                    }\n                ]\n            },\n            {\n                \"name\": \"heat\",\n                \"type\": \"orchestration\",\n                \"endpoints_links\": [],\n                \"endpoints\": [\n                    {\n                        \"publicURL\": \"URL/v1/da0d12be20394afb851716e10a49e4a7\",\n                        \"id\": \"199d00075e4a40308a6ad2aa8980d0cd\",\n                        \"internalURL\": \"URL/v1/da0d12be20394afb851716e10a49e4a7\",\n                        \"region\": \"RegionOne\",\n                        \"adminURL\": \"URL/v1/da0d12be20394afb851716e10a49e4a7\"\n                    }\n                ]\n            },\n            {\n                \"name\": \"swift\",\n                \"type\": \"object-store\",\n                \"endpoints_links\": [],\n                \"endpoints\": [\n                    {\n                        \"publicURL\": \"URL/v1/AUTH_da0d12be20394afb851716e10a49e4a7\",\n                        \"id\": \"26b2cb1efb044193b847fc3f2fb12e82\",\n                        \"internalURL\": \"URL/v1/AUTH_da0d12be20394afb851716e10a49e4a7\",\n                        \"region\": \"RegionOne\",\n                        \"adminURL\": \"URL\"\n                    }\n                ]\n            },\n            {\n                \"name\": \"keystone\",\n                \"type\": \"identity\",\n                \"endpoints_links\": [],\n                \"endpoints\": [\n                    {\n                        \"publicURL\": \"URL/v2.0\",\n                        \"id\": \"1bbfe80b50df4c4a84040aa782e42140\",\n                        \"internalURL\": \"URL/v2.0\",\n                        \"region\": \"RegionOne\",\n                        \"adminURL\": \"URL/v2.0\"\n                    }\n                ]\n            }\n        ],\n        \"token\": {\n            \"tenant\": {\n                \"name\": \"jclouds\",\n                \"id\": \"da0d12be20394afb851716e10a49e4a7\",\n                \"enabled\": true,\n                \"description\": null\n            },\n            \"id\": \"TOKEN\",\n            \"expires\": \"2014-04-28T22:48:24Z\",\n            \"issued_at\": \"2014-04-28T21:48:24.972896\"\n        }\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/attach_interface_details.json",
    "content": "{\n    \"interfaceAttachment\": {\n        \"port_state\": \"ACTIVE\",\n        \"fixed_ips\": [\n            {\n                \"subnet_id\": \"f8a6e8f8-c2ec-497c-9f23-da9616de54ef\",\n                \"ip_address\": \"192.168.1.3\"\n            }\n        ],\n        \"net_id\": \"3cb9bc59-5699-4588-a4b1-b87f96708bc6\",\n        \"port_id\": \"ce531f90-199f-48c0-816c-13e38010b442\",\n        \"mac_addr\": \"fa:16:3e:4c:2c:30\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/attach_interfaces_list.json",
    "content": "{\n    \"interfaceAttachments\": [\n        {\n            \"port_state\": \"ACTIVE\",\n            \"fixed_ips\": [\n                {\n                    \"subnet_id\": \"f8a6e8f8-c2ec-497c-9f23-da9616de54ef\",\n                    \"ip_address\": \"192.168.1.3\"\n                }\n            ],\n            \"net_id\": \"3cb9bc59-5699-4588-a4b1-b87f96708bc6\",\n            \"port_id\": \"ce531f90-199f-48c0-816c-13e38010b442\",\n            \"mac_addr\": \"fa:16:3e:4c:2c:30\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/attachment_details.json",
    "content": "{\n    \"volumeAttachment\": {\n        \"device\": \"/dev/vdc\",\n        \"serverId\": \"b4785058-cb80-491b-baa3-e4ee6546450e\",\n        \"id\": 1,\n        \"volumeId\": 1\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/attachment_list.json",
    "content": "{\n    \"volumeAttachments\": [\n        {\n            \"device\": \"/dev/vdc\",\n            \"serverId\": \"b4785058-cb80-491b-baa3-e4ee6546450e\",\n            \"id\": 1,\n            \"volumeId\": 1\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/availability_zone_list.json",
    "content": "{\n  \"availabilityZoneInfo\": [\n    {\n      \"zoneState\": {\n        \"available\": true\n      },\n      \"hosts\": null,\n      \"zoneName\": \"uk-1a\"\n    },\n    {\n      \"zoneState\": {\n        \"available\": true\n      },\n      \"hosts\": null,\n      \"zoneName\": \"uk-1b\"\n    }\n  ]\n}"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/extension_details.json",
    "content": "{\n    \"extension\": {\n        \"name\": \"Public Image Extension\",\n        \"namespace\": \"http://docs.rackspacecloud.com/servers/api/ext/pie/v1.0\",\n        \"alias\": \"RS-PIE\",\n        \"updated\": \"2011-01-22T13:25:27-06:00\",\n        \"description\": \"Adds the capability to share an image with other users.\",\n        \"links\": [\n            {\n                \"rel\": \"describedby\",\n                \"type\": \"application/pdf\",\n                \"href\": \"http://docs.rackspacecloud.com/servers/api/ext/cs-pie-20111111.pdf\"\n            },\n            {\n                \"rel\": \"describedby\",\n                \"type\": \"application/vnd.sun.wadl+xml\",\n                \"href\": \"http://docs.rackspacecloud.com/servers/api/ext/cs-pie.wadl\"\n            }\n        ]\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/extension_list.json",
    "content": "{\n    \"extensions\": [\n        {\n            \"name\": \"Public Image Extension\",\n            \"namespace\": \"http://docs.rackspacecloud.com/servers/api/ext/pie/v1.0\",\n            \"alias\": \"RAX-PIE\",\n            \"updated\": \"2011-01-22T13:25:27-06:00\",\n            \"description\": \"Adds the capability to share an image with other users.\",\n            \"links\": [\n                {\n                    \"rel\": \"describedby\",\n                    \"type\": \"application/pdf\",\n                    \"href\": \"http://docs.rackspacecloud.com/servers/api/ext/cs-pie-20111111.pdf\"\n                },\n                {\n                    \"rel\": \"describedby\",\n                    \"type\": \"application/vnd.sun.wadl+xml\",\n                    \"href\": \"http://docs.rackspacecloud.com/servers/api/ext/cs-pie.wadl\"\n                }\n            ]\n        },\n        {\n            \"name\": \"Cloud Block Storage\",\n            \"namespace\": \"http://docs.rackspacecloud.com/servers/api/ext/cbs/v1.0\",\n            \"alias\": \"RAX-CBS\",\n            \"updated\": \"2011-01-12T11:22:33-06:00\",\n            \"description\": \"Allows mounting cloud block storage volumes.\",\n            \"links\": [\n                {\n                    \"rel\": \"describedby\",\n                    \"type\": \"application/pdf\",\n                    \"href\": \"http://docs.rackspacecloud.com/servers/api/ext/cs-cbs-20111201.pdf\"\n                },\n                {\n                    \"rel\": \"describedby\",\n                    \"type\": \"application/vnd.sun.wadl+xml\",\n                    \"href\": \"http://docs.rackspacecloud.com/servers/api/ext/cs-cbs.wadl\"\n                }\n            ]\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/extension_list_full.json",
    "content": "{\n    \"extensions\": [\n        {\n            \"updated\": \"2011-09-27T00:00:00+00:00\",\n            \"name\": \"DiskConfig\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/compute/ext/disk_config/api/v1.1\",\n            \"alias\": \"OS-DCF\",\n            \"description\": \"Disk Management Extension\"\n        },\n        {\n            \"updated\": \"2011-06-29T00:00:00+00:00\",\n            \"name\": \"Hosts\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/compute/ext/hosts/api/v1.1\",\n            \"alias\": \"os-hosts\",\n            \"description\": \"Admin-only host administration\"\n        },\n        {\n            \"updated\": \"2011-07-19T00:00:00+00:00\",\n            \"name\": \"SchedulerHints\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/compute/ext/scheduler-hints/api/v2\",\n            \"alias\": \"os-scheduler-hints\",\n            \"description\": \"Pass arbitrary key/value pairs to the scheduler\"\n        },\n        {\n            \"updated\": \"2011-08-08T00:00:00+00:00\",\n            \"name\": \"Quotas\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/compute/ext/quotas-sets/api/v1.1\",\n            \"alias\": \"os-quota-sets\",\n            \"description\": \"Quotas management support\"\n        },\n        {\n            \"updated\": \"2011-12-23T00:00:00+00:00\",\n            \"name\": \"Floating_ip_dns\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/ext/floating_ip_dns/api/v1.1\",\n            \"alias\": \"os-floating-ip-dns\",\n            \"description\": \"Floating IP DNS support\"\n        },\n        {\n            \"updated\": \"2011-09-14T00:00:00+00:00\",\n            \"name\": \"FlavorExtraData\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/compute/ext/flavor_extra_data/api/v1.1\",\n            \"alias\": \"OS-FLV-EXT-DATA\",\n            \"description\": \"Provide additional data for flavors\"\n        },\n        {\n            \"updated\": \"2011-06-23T00:00:00+00:00\",\n            \"name\": \"FlavorExtraSpecs\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/compute/ext/flavor_extra_specs/api/v1.1\",\n            \"alias\": \"os-flavor-extra-specs\",\n            \"description\": \"Instance type (flavor) extra specs\"\n        },\n        {\n            \"updated\": \"2011-08-17T00:00:00+00:00\",\n            \"name\": \"VirtualInterfaces\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/compute/ext/virtual_interfaces/api/v1.1\",\n            \"alias\": \"virtual_interfaces\",\n            \"description\": \"Virtual interface support\"\n        },\n        {\n            \"updated\": \"2011-12-23T00:00:00+00:00\",\n            \"name\": \"Accounts\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/compute/ext/accounts/api/v1.1\",\n            \"alias\": \"os-accounts\",\n            \"description\": \"Admin-only access to accounts\"\n        },\n        {\n            \"updated\": \"2011-03-25T00:00:00+00:00\",\n            \"name\": \"Volumes\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/compute/ext/volumes/api/v1.1\",\n            \"alias\": \"os-volumes\",\n            \"description\": \"Volumes support\"\n        },\n        {\n            \"updated\": \"2011-11-03T00:00:00+00:00\",\n            \"name\": \"ExtendedStatus\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/compute/ext/extended_status/api/v1.1\",\n            \"alias\": \"OS-EXT-STS\",\n            \"description\": \"Extended Status support\"\n        },\n        {\n            \"updated\": \"2011-12-23T00:00:00+00:00\",\n            \"name\": \"Consoles\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/compute/ext/os-consoles/api/v2\",\n            \"alias\": \"os-consoles\",\n            \"description\": \"Interactive Console support.\"\n        },\n        {\n            \"updated\": \"2011-07-21T00:00:00+00:00\",\n            \"name\": \"SecurityGroups\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/compute/ext/securitygroups/api/v1.1\",\n            \"alias\": \"security_groups\",\n            \"description\": \"Security group support\"\n        },\n        {\n            \"updated\": \"2012-01-12T00:00:00+00:00\",\n            \"name\": \"Aggregates\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/compute/ext/aggregates/api/v1.1\",\n            \"alias\": \"os-aggregates\",\n            \"description\": \"Admin-only aggregate administration\"\n        },\n        {\n            \"updated\": \"2011-07-19T00:00:00+00:00\",\n            \"name\": \"Createserverext\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/compute/ext/createserverext/api/v1.1\",\n            \"alias\": \"os-create-server-ext\",\n            \"description\": \"Extended support to the Create Server v1.1 API\"\n        },\n        {\n            \"updated\": \"2011-09-01T00:00:00+00:00\",\n            \"name\": \"DeferredDelete\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/compute/ext/deferred-delete/api/v1.1\",\n            \"alias\": \"os-deferred-delete\",\n            \"description\": \"Instance deferred delete\"\n        },\n        {\n            \"updated\": \"2011-12-21T00:00:00+00:00\",\n            \"name\": \"ServerDiagnostics\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/compute/ext/server-diagnostics/api/v1.1\",\n            \"alias\": \"os-server-diagnostics\",\n            \"description\": \"Allow Admins to view server diagnostics through server action\"\n        },\n        {\n            \"updated\": \"2011-12-23T00:00:00+00:00\",\n            \"name\": \"Networks\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/compute/ext/networks/api/v1.1\",\n            \"alias\": \"os-networks\",\n            \"description\": \"Admin-only Network Management Extension\"\n        },\n        {\n            \"updated\": \"2011-11-03T00:00:00+00:00\",\n            \"name\": \"ExtendedServerAttributes\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/compute/ext/extended_status/api/v1.1\",\n            \"alias\": \"OS-EXT-SRV-ATTR\",\n            \"description\": \"Extended Server Attributes support.\"\n        },\n        {\n            \"updated\": \"2011-08-08T00:00:00+00:00\",\n            \"name\": \"Keypairs\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/compute/ext/keypairs/api/v1.1\",\n            \"alias\": \"os-keypairs\",\n            \"description\": \"Keypair Support\"\n        },\n        {\n            \"updated\": \"2011-08-24T00:00:00+00:00\",\n            \"name\": \"VolumeTypes\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/compute/ext/volume_types/api/v1.1\",\n            \"alias\": \"os-volume-types\",\n            \"description\": \"Volume types support\"\n        },\n        {\n            \"updated\": \"2011-08-19T00:00:00+00:00\",\n            \"name\": \"SimpleTenantUsage\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/compute/ext/os-simple-tenant-usage/api/v1.1\",\n            \"alias\": \"os-simple-tenant-usage\",\n            \"description\": \"Simple tenant usage extension\"\n        },\n        {\n            \"updated\": \"2012-01-04T00:00:00+00:00\",\n            \"name\": \"Floating_ip_pools\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/compute/ext/floating_ip_pools/api/v1.1\",\n            \"alias\": \"os-floating-ip-pools\",\n            \"description\": \"Floating IPs support\"\n        },\n        {\n            \"updated\": \"2012-01-23T00:00:00+00:00\",\n            \"name\": \"ServerStartStop\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/compute/ext/servers/api/v1.1\",\n            \"alias\": \"os-server-start-stop\",\n            \"description\": \"Start/Stop instance compute API support\"\n        },\n        {\n            \"updated\": \"2012-01-19T00:00:00+00:00\",\n            \"name\": \"Certificates\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/compute/ext/certificates/api/v1.1\",\n            \"alias\": \"os-certificates\",\n            \"description\": \"Certificates support\"\n        },\n        {\n            \"updated\": \"2011-08-18T00:00:00+00:00\",\n            \"name\": \"Rescue\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/compute/ext/rescue/api/v1.1\",\n            \"alias\": \"os-rescue\",\n            \"description\": \"Instance rescue mode\"\n        },\n        {\n            \"updated\": \"2012-01-19T00:00:00+00:00\",\n            \"name\": \"FlavorManage\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/compute/ext/flavor_manage/api/v1.1\",\n            \"alias\": \"os-flavor-manage\",\n            \"description\": \"\\n    Flavor create/delete API support\\n    \"\n        },\n        {\n            \"updated\": \"2011-12-16T00:00:00+00:00\",\n            \"name\": \"Cloudpipe\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/compute/ext/cloudpipe/api/v1.1\",\n            \"alias\": \"os-cloudpipe\",\n            \"description\": \"Adds actions to create cloudpipe instances.\\n\\n    When running with the Vlan network mode, you need a mechanism to route\\n    from the public Internet to your vlans.  This mechanism is known as a\\n    cloudpipe.\\n\\n    At the time of creating this class, only OpenVPN is supported.  Support for\\n    a SSH Bastion host is forthcoming.\\n    \"\n        },\n        {\n            \"updated\": \"2011-06-09T00:00:00+00:00\",\n            \"name\": \"Multinic\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/compute/ext/multinic/api/v1.1\",\n            \"alias\": \"NMN\",\n            \"description\": \"Multiple network support\"\n        },\n        {\n            \"updated\": \"2011-08-08T00:00:00+00:00\",\n            \"name\": \"Users\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/compute/ext/users/api/v1.1\",\n            \"alias\": \"os-users\",\n            \"description\": \"Allow admins to acces user information\"\n        },\n        {\n            \"updated\": \"2011-09-20T00:00:00+00:00\",\n            \"name\": \"AdminActions\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/compute/ext/admin-actions/api/v1.1\",\n            \"alias\": \"os-admin-actions\",\n            \"description\": \"Enable admin-only server actions\\n\\n    Actions include: pause,unpause, suspend, resume, migrate,\\n resetNetwork, injectNetworkInfo, lock, unlock, createBackup\\n    \"\n        },\n        {\n            \"updated\": \"2011-12-21T00:00:00+00:00\",\n            \"name\": \"ServerActionList\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/compute/ext/server-actions-list/api/v1.1\",\n            \"alias\": \"os-server-action-list\",\n            \"description\": \"Allow Admins to view pending server actions\"\n        },\n        {\n            \"updated\": \"2011-12-08T00:00:00+00:00\",\n            \"name\": \"Console_output\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/compute/ext/os-console-output/api/v2\",\n            \"alias\": \"os-console-output\",\n            \"description\": \"Console log output support, with tailing ability.\"\n        },\n        {\n            \"updated\": \"2011-06-16T00:00:00+00:00\",\n            \"name\": \"Floating_ips\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/compute/ext/floating_ips/api/v1.1\",\n            \"alias\": \"os-floating-ips\",\n            \"description\": \"Floating IPs support\"\n        },\n        {\n            \"updated\": \"2012-12-21T00:00:00+00:00\",\n            \"name\": \"AvailabilityZone\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/compute/ext/availabilityzone/api/v1.1\",\n            \"alias\": \"os-availability-zone\",\n            \"description\": \"1. Add availability_zone to the Create Server v1.1 API.\\n       2. Add availability zones describing.\\n    \"\n        },\n        {\n            \"updated\": \"2013-07-08T00:00:00+00:00\",\n            \"name\": \"BlockDeviceMappingV2Boot\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/compute/ext/block_device_mapping_v2_boot/api/v2\",\n            \"alias\": \"os-block-device-mapping-v2-boot\",\n            \"description\": \"Allow boot with the new BDM data format.\"\n        },\n        {\n            \"alias\": \"os-volume-attachment-update\",\n            \"description\": \"Support for updating a volume attachment.\",\n            \"links\": [],\n            \"name\": \"VolumeAttachmentUpdate\",\n            \"namespace\": \"http://docs.openstack.org/compute/ext/os-volume-attachment-update/api/v2\",\n            \"updated\": \"2013-06-20T00:00:00Z\"\n        },\n        {\n            \"updated\": \"2012-07-22T00:00:00Z\",\n            \"name\": \"AttachInterfaces\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/compute/ext/interfaces/api/v1.1\",\n            \"alias\": \"os-attach-interfaces\",\n            \"description\": \"Attach interface support.\"\n        },\n        {\n          \"updated\": \"2012-06-21T00:00:00Z\",\n          \"name\": \"Hypervisors\",\n          \"links\": [],\n          \"namespace\": \"http://docs.openstack.org/compute/ext/hypervisors/api/v1.1\",\n          \"alias\": \"os-hypervisors\",\n          \"description\": \"Admin-only hypervisor administration.\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/extension_list_full_no_namespaces.json",
    "content": "{\n    \"extensions\": [\n        {\n            \"updated\": \"2011-09-27T00:00:00+00:00\",\n            \"name\": \"DiskConfig\",\n            \"links\": [],\n            \"namespace\": \"http://fake.org\",\n            \"alias\": \"OS-DCF\",\n            \"description\": \"Disk Management Extension\"\n        },\n        {\n            \"updated\": \"2011-06-29T00:00:00+00:00\",\n            \"name\": \"Hosts\",\n            \"links\": [],\n            \"namespace\": \"http://fake.org\",\n            \"alias\": \"os-hosts\",\n            \"description\": \"Admin-only host administration\"\n        },\n        {\n            \"updated\": \"2011-07-19T00:00:00+00:00\",\n            \"name\": \"SchedulerHints\",\n            \"links\": [],\n            \"namespace\": \"http://fake.org\",\n            \"alias\": \"os-scheduler-hints\",\n            \"description\": \"Pass arbitrary key/value pairs to the scheduler\"\n        },\n        {\n            \"updated\": \"2011-08-08T00:00:00+00:00\",\n            \"name\": \"Quotas\",\n            \"links\": [],\n            \"namespace\": \"http://fake.org\",\n            \"alias\": \"os-quota-sets\",\n            \"description\": \"Quotas management support\"\n        },\n        {\n            \"updated\": \"2011-12-23T00:00:00+00:00\",\n            \"name\": \"Floating_ip_dns\",\n            \"links\": [],\n            \"namespace\": \"http://fake.org\",\n            \"alias\": \"os-floating-ip-dns\",\n            \"description\": \"Floating IP DNS support\"\n        },\n        {\n            \"updated\": \"2011-09-14T00:00:00+00:00\",\n            \"name\": \"FlavorExtraData\",\n            \"links\": [],\n            \"namespace\": \"http://fake.org\",\n            \"alias\": \"OS-FLV-EXT-DATA\",\n            \"description\": \"Provide additional data for flavors\"\n        },\n        {\n            \"updated\": \"2011-06-23T00:00:00+00:00\",\n            \"name\": \"FlavorExtraSpecs\",\n            \"links\": [],\n            \"namespace\": \"http://fake.org\",\n            \"alias\": \"os-flavor-extra-specs\",\n            \"description\": \"Instance type (flavor) extra specs\"\n        },\n        {\n            \"updated\": \"2011-08-17T00:00:00+00:00\",\n            \"name\": \"VirtualInterfaces\",\n            \"links\": [],\n            \"namespace\": \"http://fake.org\",\n            \"alias\": \"virtual_interfaces\",\n            \"description\": \"Virtual interface support\"\n        },\n        {\n            \"updated\": \"2011-12-23T00:00:00+00:00\",\n            \"name\": \"Accounts\",\n            \"links\": [],\n            \"namespace\": \"http://fake.org\",\n            \"alias\": \"os-accounts\",\n            \"description\": \"Admin-only access to accounts\"\n        },\n        {\n            \"updated\": \"2011-03-25T00:00:00+00:00\",\n            \"name\": \"Volumes\",\n            \"links\": [],\n            \"namespace\": \"http://fake.org\",\n            \"alias\": \"os-volumes\",\n            \"description\": \"Volumes support\"\n        },\n        {\n            \"updated\": \"2011-11-03T00:00:00+00:00\",\n            \"name\": \"ExtendedStatus\",\n            \"links\": [],\n            \"namespace\": \"http://fake.org\",\n            \"alias\": \"OS-EXT-STS\",\n            \"description\": \"Extended Status support\"\n        },\n        {\n            \"updated\": \"2011-12-23T00:00:00+00:00\",\n            \"name\": \"Consoles\",\n            \"links\": [],\n            \"namespace\": \"http://fake.org\",\n            \"alias\": \"os-consoles\",\n            \"description\": \"Interactive Console support.\"\n        },\n        {\n            \"updated\": \"2011-07-21T00:00:00+00:00\",\n            \"name\": \"SecurityGroups\",\n            \"links\": [],\n            \"namespace\": \"http://fake.org\",\n            \"alias\": \"security_groups\",\n            \"description\": \"Security group support\"\n        },\n        {\n            \"updated\": \"2012-01-12T00:00:00+00:00\",\n            \"name\": \"Aggregates\",\n            \"links\": [],\n            \"namespace\": \"http://fake.org\",\n            \"alias\": \"os-aggregates\",\n            \"description\": \"Admin-only aggregate administration\"\n        },\n        {\n            \"updated\": \"2011-07-19T00:00:00+00:00\",\n            \"name\": \"Createserverext\",\n            \"links\": [],\n            \"namespace\": \"http://fake.org\",\n            \"alias\": \"os-create-server-ext\",\n            \"description\": \"Extended support to the Create Server v1.1 API\"\n        },\n        {\n            \"updated\": \"2011-09-01T00:00:00+00:00\",\n            \"name\": \"DeferredDelete\",\n            \"links\": [],\n            \"namespace\": \"http://fake.org\",\n            \"alias\": \"os-deferred-delete\",\n            \"description\": \"Instance deferred delete\"\n        },\n        {\n            \"updated\": \"2011-12-21T00:00:00+00:00\",\n            \"name\": \"ServerDiagnostics\",\n            \"links\": [],\n            \"namespace\": \"http://fake.org\",\n            \"alias\": \"os-server-diagnostics\",\n            \"description\": \"Allow Admins to view server diagnostics through server action\"\n        },\n        {\n            \"updated\": \"2011-12-23T00:00:00+00:00\",\n            \"name\": \"Networks\",\n            \"links\": [],\n            \"namespace\": \"http://fake.org\",\n            \"alias\": \"os-networks\",\n            \"description\": \"Admin-only Network Management Extension\"\n        },\n        {\n            \"updated\": \"2011-11-03T00:00:00+00:00\",\n            \"name\": \"ExtendedServerAttributes\",\n            \"links\": [],\n            \"namespace\": \"http://fake.org\",\n            \"alias\": \"OS-EXT-SRV-ATTR\",\n            \"description\": \"Extended Server Attributes support.\"\n        },\n        {\n            \"updated\": \"2011-08-08T00:00:00+00:00\",\n            \"name\": \"Keypairs\",\n            \"links\": [],\n            \"namespace\": \"http://fake.org\",\n            \"alias\": \"os-keypairs\",\n            \"description\": \"Keypair Support\"\n        },\n        {\n            \"updated\": \"2011-08-24T00:00:00+00:00\",\n            \"name\": \"VolumeTypes\",\n            \"links\": [],\n            \"namespace\": \"http://fake.org\",\n            \"alias\": \"os-volume-types\",\n            \"description\": \"Volume types support\"\n        },\n        {\n            \"updated\": \"2011-08-19T00:00:00+00:00\",\n            \"name\": \"SimpleTenantUsage\",\n            \"links\": [],\n            \"namespace\": \"http://fake.org\",\n            \"alias\": \"os-simple-tenant-usage\",\n            \"description\": \"Simple tenant usage extension\"\n        },\n        {\n            \"updated\": \"2012-01-04T00:00:00+00:00\",\n            \"name\": \"Floating_ip_pools\",\n            \"links\": [],\n            \"namespace\": \"http://fake.org\",\n            \"alias\": \"os-floating-ip-pools\",\n            \"description\": \"Floating IPs support\"\n        },\n        {\n            \"updated\": \"2012-01-23T00:00:00+00:00\",\n            \"name\": \"ServerStartStop\",\n            \"links\": [],\n            \"namespace\": \"http://fake.org\",\n            \"alias\": \"os-server-start-stop\",\n            \"description\": \"Start/Stop instance compute API support\"\n        },\n        {\n            \"updated\": \"2012-01-19T00:00:00+00:00\",\n            \"name\": \"Certificates\",\n            \"links\": [],\n            \"namespace\": \"http://fake.org\",\n            \"alias\": \"os-certificates\",\n            \"description\": \"Certificates support\"\n        },\n        {\n            \"updated\": \"2011-08-18T00:00:00+00:00\",\n            \"name\": \"Rescue\",\n            \"links\": [],\n            \"namespace\": \"http://fake.org\",\n            \"alias\": \"os-rescue\",\n            \"description\": \"Instance rescue mode\"\n        },\n        {\n            \"updated\": \"2012-01-19T00:00:00+00:00\",\n            \"name\": \"FlavorManage\",\n            \"links\": [],\n            \"namespace\": \"http://fake.org\",\n            \"alias\": \"os-flavor-manage\",\n            \"description\": \"\\n    Flavor create/delete API support\\n    \"\n        },\n        {\n            \"updated\": \"2011-12-16T00:00:00+00:00\",\n            \"name\": \"Cloudpipe\",\n            \"links\": [],\n            \"namespace\": \"http://fake.org\",\n            \"alias\": \"os-cloudpipe\",\n            \"description\": \"Adds actions to create cloudpipe instances.\\n\\n    When running with the Vlan network mode, you need a mechanism to route\\n    from the public Internet to your vlans.  This mechanism is known as a\\n    cloudpipe.\\n\\n    At the time of creating this class, only OpenVPN is supported.  Support for\\n    a SSH Bastion host is forthcoming.\\n    \"\n        },\n        {\n            \"updated\": \"2011-06-09T00:00:00+00:00\",\n            \"name\": \"Multinic\",\n            \"links\": [],\n            \"namespace\": \"http://fake.org\",\n            \"alias\": \"NMN\",\n            \"description\": \"Multiple network support\"\n        },\n        {\n            \"updated\": \"2011-08-08T00:00:00+00:00\",\n            \"name\": \"Users\",\n            \"links\": [],\n            \"namespace\": \"http://fake.org\",\n            \"alias\": \"os-users\",\n            \"description\": \"Allow admins to acces user information\"\n        },\n        {\n            \"updated\": \"2011-09-20T00:00:00+00:00\",\n            \"name\": \"AdminActions\",\n            \"links\": [],\n            \"namespace\": \"http://fake.org\",\n            \"alias\": \"os-admin-actions\",\n            \"description\": \"Enable admin-only server actions\\n\\n    Actions include: pause,unpause, suspend, resume, migrate,\\n resetNetwork, injectNetworkInfo, lock, unlock, createBackup\\n    \"\n        },\n        {\n            \"updated\": \"2011-12-21T00:00:00+00:00\",\n            \"name\": \"ServerActionList\",\n            \"links\": [],\n            \"namespace\": \"http://fake.org\",\n            \"alias\": \"os-server-action-list\",\n            \"description\": \"Allow Admins to view pending server actions\"\n        },\n        {\n            \"updated\": \"2011-12-08T00:00:00+00:00\",\n            \"name\": \"Console_output\",\n            \"links\": [],\n            \"namespace\": \"http://fake.org\",\n            \"alias\": \"os-console-output\",\n            \"description\": \"Console log output support, with tailing ability.\"\n        },\n        {\n            \"updated\": \"2011-06-16T00:00:00+00:00\",\n            \"name\": \"FloatingIps\",\n            \"links\": [],\n            \"namespace\": \"http://fake.org\",\n            \"alias\": \"os-floating-ips\",\n            \"description\": \"Floating IPs support\"\n        },\n        {\n            \"updated\": \"2012-12-21T00:00:00+00:00\",\n            \"name\": \"AvailabilityZone\",\n            \"links\": [],\n            \"namespace\": \"http://fake.org\",\n            \"alias\": \"os-availability-zone\",\n            \"description\": \"1. Add availability_zone to the Create Server v1.1 API.\\n       2. Add availability zones describing.\\n    \"\n        },\n        {\n            \"updated\": \"2013-07-08T00:00:00+00:00\",\n            \"name\": \"BlockDeviceMappingV2Boot\",\n            \"links\": [],\n            \"namespace\": \"http://fake.org\",\n            \"alias\": \"os-block-device-mapping-v2-boot\",\n            \"description\": \"Allow boot with the new BDM data format.\"\n        },\n        {\n            \"alias\": \"os-volume-attachment-update\",\n            \"description\": \"Support for updating a volume attachment.\",\n            \"links\": [],\n            \"name\": \"VolumeAttachmentUpdate\",\n            \"namespace\": \"http://fake.org\",\n            \"updated\": \"2013-06-20T00:00:00Z\"\n        },\n        {\n            \"updated\": \"2012-07-22T00:00:00Z\",\n            \"name\": \"AttachInterfaces\",\n            \"links\": [],\n            \"namespace\": \"http://fake.org\",\n            \"alias\": \"os-attach-interfaces\",\n            \"description\": \"Attach interface support.\"\n        },\n        {\n          \"updated\": \"2012-06-21T00:00:00Z\",\n          \"name\": \"Hypervisors\",\n          \"links\": [],\n          \"namespace\": \"http://fake.org\",\n          \"alias\": \"os-hypervisors\",\n          \"description\": \"Admin-only hypervisor administration.\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/extension_list_normal.json",
    "content": "{\n    \"extensions\": [\n        {\n            \"updated\": \"2011-08-08T00:00:00+00:00\",\n            \"name\": \"Keypairs\",\n            \"links\": [\n                {\n                    \"rel\": \"self\",\n                    \"href\": \"http://docs.openstack.org/ext/keypairs/api/v1.1\"\n                }\n            ],\n            \"namespace\": \"http://docs.openstack.org/ext/keypairs/api/v1.1\",\n            \"alias\": \"os-keypairs\",\n            \"description\": \"Keypair Support\"\n        },\n        {\n            \"updated\": \"2011-03-25T00:00:00+00:00\",\n            \"name\": \"Volumes\",\n            \"links\": [\n                {\n                    \"rel\": \"self\",\n                    \"href\": \"http://docs.openstack.org/ext/volumes/api/v1.1\"\n                }\n            ],\n            \"namespace\": \"http://docs.openstack.org/ext/volumes/api/v1.1\",\n            \"alias\": \"os-volumes\",\n            \"description\": \"Volumes support\"\n        },\n        {\n            \"updated\": \"2011-07-21T00:00:00+00:00\",\n            \"name\": \"SecurityGroups\",\n            \"links\": [\n                {\n                    \"rel\": \"self\",\n                    \"href\": \"http://docs.openstack.org/ext/securitygroups/api/v1.1\"\n                }\n            ],\n            \"namespace\": \"http://docs.openstack.org/ext/securitygroups/api/v1.1\",\n            \"alias\": \"security_groups\",\n            \"description\": \"Security group support\"\n        },\n        {\n            \"updated\": \"2011-06-16T00:00:00+00:00\",\n            \"name\": \"Floating_ips\",\n            \"links\": [\n                {\n                    \"rel\": \"self\",\n                    \"href\": \"http://docs.openstack.org/ext/floating_ips/api/v1.1\"\n                }\n            ],\n            \"namespace\": \"http://docs.openstack.org/ext/floating_ips/api/v1.1\",\n            \"alias\": \"os-floating-ips\",\n            \"description\": \"Floating IPs support\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/extension_list_openstack.json",
    "content": "{\n    \"extensions\": [\n        {\n            \"updated\": \"2011-06-09T00:00:00+00:00\",\n            \"name\": \"Multinic\",\n            \"links\": [],\n            \"namespace\": \"https://docs.openstack.org/ext/multinic/api/v1.1\",\n            \"alias\": \"NMN\",\n            \"description\": \"Multiple network support\"\n        },\n        {\n            \"updated\": \"2011-06-29T00:00:00+00:00\",\n            \"name\": \"Hosts\",\n            \"links\": [],\n            \"namespace\": \"https://docs.openstack.org/ext/hosts/api/v1.1\",\n            \"alias\": \"os-hosts\",\n            \"description\": \"Host administration\"\n        },\n        {\n            \"updated\": \"2011-03-25T00:00:00+00:00\",\n            \"name\": \"Volumes\",\n            \"links\": [],\n            \"namespace\": \"https://docs.openstack.org/ext/volumes/api/v1.1\",\n            \"alias\": \"os-volumes\",\n            \"description\": \"Volumes support\"\n        },\n        {\n            \"updated\": \"2011-05-25 16:12:21.656723\",\n            \"name\": \"Admin Controller\",\n            \"links\": [],\n            \"namespace\": \"https:TODO/\",\n            \"alias\": \"ADMIN\",\n            \"description\": \"The Admin API Extension\"\n        },\n        {\n            \"updated\": \"2011-08-08T00:00:00+00:00\",\n            \"name\": \"Quotas\",\n            \"links\": [],\n            \"namespace\": \"https://docs.openstack.org/ext/quotas-sets/api/v1.1\",\n            \"alias\": \"os-quota-sets\",\n            \"description\": \"Quotas management support\"\n        },\n        {\n            \"updated\": \"2011-08-24T00:00:00+00:00\",\n            \"name\": \"VolumeTypes\",\n            \"links\": [],\n            \"namespace\": \"https://docs.openstack.org/ext/volume_types/api/v1.1\",\n            \"alias\": \"os-volume-types\",\n            \"description\": \"Volume types support\"\n        },\n        {\n            \"updated\": \"2011-06-23T00:00:00+00:00\",\n            \"name\": \"FlavorExtraSpecs\",\n            \"links\": [],\n            \"namespace\": \"https://docs.openstack.org/ext/flavor_extra_specs/api/v1.1\",\n            \"alias\": \"os-flavor-extra-specs\",\n            \"description\": \"Instance type (flavor) extra specs\"\n        },\n        {\n            \"updated\": \"2011-09-14T00:00:00+00:00\",\n            \"name\": \"FlavorExtraData\",\n            \"links\": [],\n            \"namespace\": \"https://docs.openstack.org/ext/flavor_extra_data/api/v1.1\",\n            \"alias\": \"os-flavor-extra-data\",\n            \"description\": \"Provide additional data for flavors\"\n        },\n        {\n            \"updated\": \"2011-08-17T00:00:00+00:00\",\n            \"name\": \"VirtualInterfaces\",\n            \"links\": [],\n            \"namespace\": \"https://docs.openstack.org/ext/virtual_interfaces/api/v1.1\",\n            \"alias\": \"virtual_interfaces\",\n            \"description\": \"Virtual interface support\"\n        },\n        {\n            \"updated\": \"2011-07-19T00:00:00+00:00\",\n            \"name\": \"Createserverext\",\n            \"links\": [],\n            \"namespace\": \"https://docs.openstack.org/ext/createserverext/api/v1.1\",\n            \"alias\": \"os-create-server-ext\",\n            \"description\": \"Extended support to the Create Server v1.1 API\"\n        },\n        {\n            \"updated\": \"2011-08-08T00:00:00+00:00\",\n            \"name\": \"Keypairs\",\n            \"links\": [],\n            \"namespace\": \"https://docs.openstack.org/ext/keypairs/api/v1.1\",\n            \"alias\": \"os-keypairs\",\n            \"description\": \"Keypair Support\"\n        },\n        {\n            \"updated\": \"2011-08-25T00:00:00+00:00\",\n            \"name\": \"VSAs\",\n            \"links\": [],\n            \"namespace\": \"https://docs.openstack.org/ext/vsa/api/v1.1\",\n            \"alias\": \"zadr-vsa\",\n            \"description\": \"Virtual Storage Arrays support\"\n        },\n        {\n            \"updated\": \"2011-08-19T00:00:00+00:00\",\n            \"name\": \"SimpleTenantUsage\",\n            \"links\": [],\n            \"namespace\": \"https://docs.openstack.org/ext/os-simple-tenant-usage/api/v1.1\",\n            \"alias\": \"os-simple-tenant-usage\",\n            \"description\": \"Simple tenant usage extension\"\n        },\n        {\n            \"updated\": \"2011-08-18T00:00:00+00:00\",\n            \"name\": \"Rescue\",\n            \"links\": [],\n            \"namespace\": \"https://docs.openstack.org/ext/rescue/api/v1.1\",\n            \"alias\": \"os-rescue\",\n            \"description\": \"Instance rescue mode\"\n        },\n        {\n            \"updated\": \"2011-07-21T00:00:00+00:00\",\n            \"name\": \"SecurityGroups\",\n            \"links\": [],\n            \"namespace\": \"https://docs.openstack.org/ext/securitygroups/api/v1.1\",\n            \"alias\": \"security_groups\",\n            \"description\": \"Security group support\"\n        },\n        {\n            \"updated\": \"2011-06-16T00:00:00+00:00\",\n            \"name\": \"Floating_ips\",\n            \"links\": [],\n            \"namespace\": \"https://docs.openstack.org/ext/floating_ips/api/v1.1\",\n            \"alias\": \"os-floating-ips\",\n            \"description\": \"Floating IPs support\"\n        },\n        {\n            \"updated\": \"2012-12-21T00:00:00+00:00\",\n            \"name\": \"AvailabilityZone\",\n            \"links\": [],\n            \"namespace\": \"http://docs.openstack.org/compute/ext/availabilityzone/api/v1.1\",\n            \"alias\": \"os-availability-zone\",\n            \"description\": \"1. Add availability_zone to the Create Server v1.1 API.\\n       2. Add availability zones describing.\\n    \"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/flavor_details.json",
    "content": "{\n    \"flavor\": {\n        \"id\": \"52415800-8b69-11e0-9b19-734f1195ff37\",\n        \"name\": \"256 MB Server\",\n        \"ram\": 256,\n        \"disk\": 10,\n        \"vcpus\": 1,\n        \"links\": [\n            {\n                \"rel\": \"self\",\n                \"href\": \"http://servers.api.openstack.org/v2/1234/flavors/52415800-8b69-11e0-9b19-734f1195ff37\"\n            },\n            {\n                \"rel\": \"bookmark\",\n                \"href\": \"http://servers.api.openstack.org/1234/flavors/52415800-8b69-11e0-9b19-734f1195ff37\"\n            }\n        ]\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/flavor_list.json",
    "content": "{\n    \"flavors\": [\n        {\n            \"id\": \"52415800-8b69-11e0-9b19-734f1195ff37\",\n            \"name\": \"256 MB Server\",\n            \"links\": [\n                {\n                    \"rel\": \"self\",\n                    \"href\": \"http://servers.api.openstack.org/v2/1234/flavors/52415800-8b69-11e0-9b19-734f1195ff37\"\n                },\n                {\n                    \"rel\": \"bookmark\",\n                    \"href\": \"http://servers.api.openstack.org/1234/flavors/52415800-8b69-11e0-9b19-734f1195ff37\"\n                }\n            ]\n        },\n        {\n            \"id\": \"52415800-8b69-11e0-9b19-734f216543fd\",\n            \"name\": \"512 MB Server\",\n            \"links\": [\n                {\n                    \"rel\": \"self\",\n                    \"href\": \"http://servers.api.openstack.org/v2/1234/flavors/52415800-8b69-11e0-9b19-734f216543fd\"\n                },\n                {\n                    \"rel\": \"bookmark\",\n                    \"href\": \"http://servers.api.openstack.org/1234/flavors/52415800-8b69-11e0-9b19-734f216543fd\"\n                }\n            ]\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/flavor_list_detail.json",
    "content": "{\n    \"flavors\": [\n        {\n            \"rxtx_quota\": 0,\n            \"name\": \"standard.xsmall\",\n            \"links\": [\n                {\n                    \"href\": \"https://az-2.region-a.geo-1.compute.hpcloudsvc.com/v2/37936628937291/flavors/100\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"https://az-2.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/flavors/100\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"ram\": 1024,\n            \"vcpus\": 1,\n            \"rxtx_cap\": 0,\n            \"swap\": 0,\n            \"disk\": 30,\n            \"id\": 100\n        },\n        {\n            \"rxtx_quota\": 0,\n            \"name\": \"standard.small\",\n            \"links\": [\n                {\n                    \"href\": \"https://az-2.region-a.geo-1.compute.hpcloudsvc.com/v2/37936628937291/flavors/101\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"https://az-2.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/flavors/101\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"ram\": 2048,\n            \"vcpus\": 2,\n            \"rxtx_cap\": 0,\n            \"swap\": 0,\n            \"disk\": 60,\n            \"id\": 101\n        },\n        {\n            \"rxtx_quota\": 0,\n            \"name\": \"standard.2xlarge\",\n            \"links\": [\n                {\n                    \"href\": \"https://az-2.region-a.geo-1.compute.hpcloudsvc.com/v2/37936628937291/flavors/105\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"https://az-2.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/flavors/105\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"ram\": 32768,\n            \"vcpus\": 8,\n            \"rxtx_cap\": 0,\n            \"swap\": 0,\n            \"disk\": 960,\n            \"id\": 105\n        },\n        {\n            \"rxtx_quota\": 0,\n            \"name\": \"standard.large\",\n            \"links\": [\n                {\n                    \"href\": \"https://az-2.region-a.geo-1.compute.hpcloudsvc.com/v2/37936628937291/flavors/103\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"https://az-2.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/flavors/103\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"ram\": 8192,\n            \"vcpus\": 4,\n            \"rxtx_cap\": 0,\n            \"swap\": 0,\n            \"disk\": 240,\n            \"id\": 103\n        },\n        {\n            \"rxtx_quota\": 0,\n            \"name\": \"standard.medium\",\n            \"links\": [\n                {\n                    \"href\": \"https://az-2.region-a.geo-1.compute.hpcloudsvc.com/v2/37936628937291/flavors/102\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"https://az-2.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/flavors/102\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"ram\": 4096,\n            \"vcpus\": 2,\n            \"rxtx_cap\": 0,\n            \"swap\": 0,\n            \"disk\": 120,\n            \"id\": 102\n        },\n        {\n            \"rxtx_quota\": 0,\n            \"name\": \"standard.xlarge\",\n            \"links\": [\n                {\n                    \"href\": \"https://az-2.region-a.geo-1.compute.hpcloudsvc.com/v2/37936628937291/flavors/104\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"https://az-2.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/flavors/104\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"ram\": 16384,\n            \"vcpus\": 4,\n            \"rxtx_cap\": 0,\n            \"swap\": 0,\n            \"disk\": 480,\n            \"id\": 104\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/flavor_list_detail_openstack.json",
    "content": "{\n    \"flavors\": [\n        {\n            \"rxtx_quota\": 0,\n            \"name\": \"m1.medium\",\n            \"links\": [\n                {\n                    \"href\": \"https://nova-api.openstack.org:9774/v2/37/flavors/3\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"https://nova-api.openstack.org:9774/37/flavors/3\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"ram\": 4096,\n            \"vcpus\": 2,\n            \"rxtx_cap\": 0,\n            \"swap\": 0,\n            \"disk\": 40,\n            \"id\": 3\n        },\n        {\n            \"rxtx_quota\": 0,\n            \"name\": \"m1.large\",\n            \"links\": [\n                {\n                    \"href\": \"https://nova-api.openstack.org:9774/v2/37/flavors/4\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"https://nova-api.openstack.org:9774/37/flavors/4\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"ram\": 8192,\n            \"vcpus\": 4,\n            \"rxtx_cap\": 0,\n            \"swap\": 0,\n            \"disk\": 80,\n            \"id\": 4\n        },\n        {\n            \"rxtx_quota\": 0,\n            \"name\": \"m1.tiny\",\n            \"links\": [\n                {\n                    \"href\": \"https://nova-api.openstack.org:9774/v2/37/flavors/1\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"https://nova-api.openstack.org:9774/37/flavors/1\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"ram\": 512,\n            \"vcpus\": 1,\n            \"rxtx_cap\": 0,\n            \"swap\": 0,\n            \"disk\": 0,\n            \"id\": 1\n        },\n        {\n            \"rxtx_quota\": 0,\n            \"name\": \"m1.xlarge\",\n            \"links\": [\n                {\n                    \"href\": \"https://nova-api.openstack.org:9774/v2/37/flavors/5\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"https://nova-api.openstack.org:9774/37/flavors/5\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"ram\": 16384,\n            \"vcpus\": 8,\n            \"rxtx_cap\": 0,\n            \"swap\": 0,\n            \"disk\": 160,\n            \"id\": 5\n        },\n        {\n            \"rxtx_quota\": 0,\n            \"name\": \"m1.small\",\n            \"links\": [\n                {\n                    \"href\": \"https://nova-api.openstack.org:9774/v2/37/flavors/2\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"https://nova-api.openstack.org:9774/37/flavors/2\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"ram\": 2048,\n            \"vcpus\": 1,\n            \"rxtx_cap\": 0,\n            \"swap\": 0,\n            \"disk\": 20,\n            \"id\": 2\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/flavor_new.json",
    "content": "{\n    \"flavor\": {\n        \"id\": \"1cb47a44-9b84-4da4-bf81-c1976e8414ab\",\n        \"name\": \"128 MB Server\",\n        \"ram\": 128,\n        \"disk\": 10,\n        \"vcpus\": 1\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/floatingip_details.json",
    "content": "{\n    \"floating_ip\": {\n        \"id\": 1,\n        \"ip\": \"10.0.0.3\",\n        \"fixed_ip\": \"10.0.0.2\",\n        \"instance_id\": 123,\n        \"pool\": \"nova\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/floatingip_list.json",
    "content": "{\n    \"floating_ips\": [\n        {\n            \"instance_id\": 12,\n            \"ip\": \"10.0.0.3\",\n            \"fixed_ip\": \"11.0.0.1\",\n            \"id\" : 1,\n            \"pool\": \"nova\"\n        },\n        {\n            \"instance_id\": null,\n            \"ip\": \"10.0.0.5\",\n            \"fixed_ip\": null,\n            \"id\": 2,\n            \"pool\": \"nova\"\n        },\n        {\n            \"instance_id\": 13,\n            \"ip\": \"10.0.0.13\",\n            \"fixed_ip\": \"11.0.0.3\",\n            \"id\": 3\n        },\n        {\n            \"instance_id\": 14,\n            \"ip\": \"10.0.0.14\",\n            \"fixed_ip\": \"11.0.0.4\",\n            \"id\": 4\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/floatingippool_list.json",
    "content": "{\n    \"floating_ip_pools\": [\n        {\n            \"name\": \"VLAN867\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/host.json",
    "content": "{\n    \"host\": [\n        {\n            \"resource\": {\n                \"project\": \"(total)\",\n                \"memory_mb\": 16083,\n                \"host\": \"ubuntu\",\n                \"cpu\": 4,\n                \"disk_gb\": 181\n            }\n        },\n        {\n            \"resource\": {\n                \"project\": \"(used_now)\",\n                \"memory_mb\": 3396,\n                \"host\": \"ubuntu\",\n                \"cpu\": 3,\n                \"disk_gb\": 5\n            }\n        },\n        {\n            \"resource\": {\n                \"project\": \"(used_max)\",\n                \"memory_mb\": 6144,\n                \"host\": \"ubuntu\",\n                \"cpu\": 3,\n                \"disk_gb\": 80\n            }\n        },\n        {\n            \"resource\": {\n                \"project\": \"f8535069c3fb404cb61c873b1a0b4921\",\n                \"memory_mb\": 6144,\n                \"host\": \"ubuntu\",\n                \"cpu\": 3,\n                \"disk_gb\": 80\n            }\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/host_aggregate_details.json",
    "content": "{\n    \"aggregate\": {\n        \"name\": \"jclouds-test-a\",\n        \"availability_zone\": \"nova\",\n        \"deleted\": false,\n        \"created_at\": \"2012-05-11 11:40:17\",\n        \"updated_at\": \"2012-05-11 11:46:44\",\n        \"operational_state\": \"created\",\n        \"hosts\": [],\n        \"deleted_at\": null,\n        \"id\": 1,\n        \"metadata\": {\n            \"somekey\": \"somevalue\",\n            \"anotherkey\": \"another val\"\n        }\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/host_aggregate_list.json",
    "content": "{\n    \"aggregates\": [\n        {\n            \"name\": \"jclouds-test-a\",\n            \"availability_zone\": \"nova\",\n            \"deleted\": false,\n            \"created_at\": \"2012-05-11 11:40:17\",\n            \"updated_at\": \"2012-05-11 11:46:44\",\n            \"operational_state\": \"created\",\n            \"hosts\": [],\n            \"deleted_at\": null,\n            \"id\": 1,\n            \"metadata\": {\n                \"somekey\": \"somevalue\",\n                \"anotherkey\": \"another val\"\n            }\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/host_aggregate_with_host_details.json",
    "content": "{\n    \"aggregate\": {\n        \"name\": \"jclouds-test-a\",\n        \"availability_zone\": \"nova\",\n        \"deleted\": false,\n        \"created_at\": \"2012-05-11 11:40:17\",\n        \"updated_at\": \"2012-05-11 11:46:44\",\n        \"operational_state\": \"created\",\n        \"hosts\": [\n            \"ubuntu\"\n        ],\n        \"deleted_at\": null,\n        \"id\": 1,\n        \"metadata\": {\n            \"somekey\": \"somevalue\",\n            \"anotherkey\": \"another val\"\n        }\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/hosts_list.json",
    "content": "{\n    \"hosts\": [\n        {\n            \"zone\": \"nova\",\n            \"host_name\": \"ubuntu\",\n            \"service\": \"compute\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/hypervisor_details.json",
    "content": "{\n  \"hypervisors\": [\n    {\n      \"vcpus_used\": 5,\n      \"hypervisor_type\": \"QEMU\",\n      \"local_gb_used\": 51,\n      \"vcpus\": 16,\n      \"hypervisor_hostname\": \"os-compute1\",\n      \"memory_mb_used\": 7168,\n      \"memory_mb\": 20079,\n      \"current_workload\": 0,\n      \"cpu_info\": \"{\\\"vendor\\\": \\\"Intel\\\", \\\"model\\\": \\\"Westmere\\\", \\\"arch\\\": \\\"x86_64\\\", \\\"features\\\": [\\\"pge\\\", \\\"avx\\\", \\\"clflush\\\", \\\"sep\\\", \\\"syscall\\\", \\\"vme\\\", \\\"tsc\\\", \\\"xsave\\\", \\\"vmx\\\", \\\"cmov\\\", \\\"ssse3\\\", \\\"pat\\\", \\\"lm\\\", \\\"msr\\\", \\\"nx\\\", \\\"fxsr\\\", \\\"sse4.1\\\", \\\"pae\\\", \\\"sse4.2\\\", \\\"pclmuldq\\\", \\\"mmx\\\", \\\"osxsave\\\", \\\"cx8\\\", \\\"mce\\\", \\\"de\\\", \\\"aes\\\", \\\"ht\\\", \\\"pse\\\", \\\"lahf_lm\\\", \\\"popcnt\\\", \\\"mca\\\", \\\"apic\\\", \\\"sse\\\", \\\"ds\\\", \\\"pni\\\", \\\"rdtscp\\\", \\\"sse2\\\", \\\"ss\\\", \\\"hypervisor\\\", \\\"pcid\\\", \\\"fpu\\\", \\\"cx16\\\", \\\"pse36\\\", \\\"mtrr\\\", \\\"x2apic\\\"], \\\"topology\\\": {\\\"cores\\\": 4, \\\"threads\\\": 1, \\\"sockets\\\": 1}}\",\n      \"running_vms\": 2,\n      \"free_disk_gb\": 144,\n      \"hypervisor_version\": 2000000,\n      \"disk_available_least\": 131,\n      \"local_gb\": 195,\n      \"free_ram_mb\": 12911,\n      \"id\": 1\n    },\n    {\n      \"vcpus_used\": 8,\n      \"hypervisor_type\": \"QEMU\",\n      \"local_gb_used\": 130,\n      \"vcpus\": 16,\n      \"hypervisor_hostname\": \"os-compute02\",\n      \"memory_mb_used\": 14848,\n      \"memory_mb\": 20079,\n      \"current_workload\": 0,\n      \"cpu_info\": \"{\\\"vendor\\\": \\\"Intel\\\", \\\"model\\\": \\\"Westmere\\\", \\\"arch\\\": \\\"x86_64\\\", \\\"features\\\": [\\\"pge\\\", \\\"avx\\\", \\\"clflush\\\", \\\"sep\\\", \\\"syscall\\\", \\\"vme\\\", \\\"tsc\\\", \\\"xsave\\\", \\\"vmx\\\", \\\"cmov\\\", \\\"ssse3\\\", \\\"pat\\\", \\\"lm\\\", \\\"msr\\\", \\\"nx\\\", \\\"fxsr\\\", \\\"sse4.1\\\", \\\"pae\\\", \\\"sse4.2\\\", \\\"pclmuldq\\\", \\\"mmx\\\", \\\"osxsave\\\", \\\"cx8\\\", \\\"mce\\\", \\\"de\\\", \\\"aes\\\", \\\"ht\\\", \\\"pse\\\", \\\"lahf_lm\\\", \\\"popcnt\\\", \\\"mca\\\", \\\"apic\\\", \\\"sse\\\", \\\"ds\\\", \\\"pni\\\", \\\"rdtscp\\\", \\\"sse2\\\", \\\"ss\\\", \\\"hypervisor\\\", \\\"pcid\\\", \\\"fpu\\\", \\\"cx16\\\", \\\"pse36\\\", \\\"mtrr\\\", \\\"x2apic\\\"], \\\"topology\\\": {\\\"cores\\\": 4, \\\"threads\\\": 1, \\\"sockets\\\": 1}}\",\n      \"running_vms\": 3,\n      \"free_disk_gb\": 65,\n      \"hypervisor_version\": 2000000,\n      \"disk_available_least\": 38,\n      \"local_gb\": 195,\n      \"free_ram_mb\": 5231,\n      \"id\": 4\n    }\n  ]\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/hypervisor_list.json",
    "content": "{\n  \"hypervisors\": [\n    {\n      \"id\": 1,\n      \"hypervisor_hostname\": \"os-compute1\"\n    },\n    {\n      \"id\": 4,\n      \"hypervisor_hostname\": \"os-compute02\"\n    }\n  ]\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/image_active.json",
    "content": "{\n    \"image\": {\n        \"id\": \"52415800-8b69-11e0-9b19-734f5736d2a2\",\n        \"name\": \"My Server Backup\",\n        \"updated\": \"2010-10-10T12:00:00Z\",\n        \"created\": \"2010-08-10T12:00:00Z\",\n        \"tenant_id\": \"12345\",\n        \"user_id\": \"joe\",\n        \"status\": \"ACTIVE\",\n        \"progress\": 80,\n        \"minDisk\": 5,\n        \"minRam\": 256,\n        \"metadata\": {\n            \"ImageType\": \"Gold\",\n            \"ImageVersion\": \"1.5\"\n        },\n        \"server\": {\n            \"id\": \"52415800-8b69-11e0-9b19-734f335aa7b3\",\n            \"links\": [\n                {\n                    \"rel\": \"self\",\n                    \"href\": \"http://servers.api.openstack.org/v2/1234/servers/52415800-8b69-11e0-9b19-734f335aa7b3\"\n                },\n                {\n                    \"rel\": \"bookmark\",\n                    \"href\": \"http://servers.api.openstack.org/1234/servers/52415800-8b69-11e0-9b19-734f335aa7b3\"\n                }\n            ]\n        },\n        \"links\": [\n            {\n                \"rel\": \"self\",\n                \"href\": \"http://servers.api.openstack.org/v2/1234/images/52415800-8b69-11e0-9b19-734f5736d2a2\"\n            },\n            {\n                \"rel\": \"bookmark\",\n                \"href\": \"http://servers.api.openstack.org/1234/images/52415800-8b69-11e0-9b19-734f5736d2a2\"\n            }\n        ]\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/image_details.json",
    "content": "{\n    \"image\": {\n        \"id\": \"52415800-8b69-11e0-9b19-734f5736d2a2\",\n        \"name\": \"My Server Backup\",\n        \"updated\": \"2010-10-10T12:00:00Z\",\n        \"created\": \"2010-08-10T12:00:00Z\",\n        \"tenant_id\": \"12345\",\n        \"user_id\": \"joe\",\n        \"status\": \"SAVING\",\n        \"progress\": 80,\n        \"minDisk\": 5,\n        \"minRam\": 256,\n        \"metadata\": {\n            \"ImageType\": \"Gold\",\n            \"ImageVersion\": \"1.5\"\n        },\n        \"server\": {\n            \"id\": \"52415800-8b69-11e0-9b19-734f335aa7b3\",\n            \"links\": [\n                {\n                    \"rel\": \"self\",\n                    \"href\": \"http://servers.api.openstack.org/v2/1234/servers/52415800-8b69-11e0-9b19-734f335aa7b3\"\n                },\n                {\n                    \"rel\": \"bookmark\",\n                    \"href\": \"http://servers.api.openstack.org/1234/servers/52415800-8b69-11e0-9b19-734f335aa7b3\"\n                }\n            ]\n        },\n        \"links\": [\n            {\n                \"rel\": \"self\",\n                \"href\": \"http://servers.api.openstack.org/v2/1234/images/52415800-8b69-11e0-9b19-734f5736d2a2\"\n            },\n            {\n                \"rel\": \"bookmark\",\n                \"href\": \"http://servers.api.openstack.org/1234/images/52415800-8b69-11e0-9b19-734f5736d2a2\"\n            }\n        ]\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/image_details_with_block_device_mapping.json",
    "content": "{\n    \"image\": {\n        \"id\": \"52415800-8b69-11e0-9b19-734f5736d2a2\",\n        \"name\": \"My Server Backup\",\n        \"updated\": \"2010-10-10T12:00:00Z\",\n        \"created\": \"2010-08-10T12:00:00Z\",\n        \"tenant_id\": \"12345\",\n        \"user_id\": \"joe\",\n        \"status\": \"SAVING\",\n        \"progress\": 80,\n        \"minDisk\": 5,\n        \"minRam\": 256,\n        \"metadata\": {\n            \"ImageType\": \"Gold\",\n            \"ImageVersion\": 1.5,\n            \"block_device_mapping\": [\n                {\n                    \"guest_format\": null,\n                    \"boot_index\": 2,\n                    \"no_device\": null,\n                    \"volume_id\": null,\n                    \"volume_size\": null,\n                    \"disk_bus\": null,\n                    \"image_id\": null,\n                    \"source_type\": \"snapshot\",\n                    \"device_type\": null,\n                    \"snapshot_id\": \"a900a56c-61b7-4438-9150-76312fa1aa10\",\n                    \"destination_type\": \"volume\",\n                    \"delete_on_termination\": null\n                }\n            ]\n        },\n        \"server\": {\n            \"id\": \"52415800-8b69-11e0-9b19-734f335aa7b3\",\n            \"links\": [\n                {\n                    \"rel\": \"self\",\n                    \"href\": \"http://servers.api.openstack.org/v2/1234/servers/52415800-8b69-11e0-9b19-734f335aa7b3\"\n                },\n                {\n                    \"rel\": \"bookmark\",\n                    \"href\": \"http://servers.api.openstack.org/1234/servers/52415800-8b69-11e0-9b19-734f335aa7b3\"\n                }\n            ]\n        },\n        \"links\": [\n            {\n                \"rel\": \"self\",\n                \"href\": \"http://servers.api.openstack.org/v2/1234/images/52415800-8b69-11e0-9b19-734f5736d2a2\"\n            },\n            {\n                \"rel\": \"bookmark\",\n                \"href\": \"http://servers.api.openstack.org/1234/images/52415800-8b69-11e0-9b19-734f5736d2a2\"\n            }\n        ]\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/image_details_without_metadata.json",
    "content": "{\n    \"image\": {\n        \"id\": \"52415800-8b69-11e0-9b19-734f5736d2a2\",\n        \"name\": \"My Server Backup\",\n        \"updated\": \"2010-10-10T12:00:00Z\",\n        \"created\": \"2010-08-10T12:00:00Z\",\n        \"tenant_id\": \"12345\",\n        \"user_id\": \"joe\",\n        \"status\": \"SAVING\",\n        \"progress\": 80,\n        \"minDisk\": 5,\n        \"minRam\": 256,\n        \"metadata\": {},\n        \"server\": {\n            \"id\": \"52415800-8b69-11e0-9b19-734f335aa7b3\",\n            \"links\": [\n                {\n                    \"rel\": \"self\",\n                    \"href\": \"http://servers.api.openstack.org/v2/1234/servers/52415800-8b69-11e0-9b19-734f335aa7b3\"\n                },\n                {\n                    \"rel\": \"bookmark\",\n                    \"href\": \"http://servers.api.openstack.org/1234/servers/52415800-8b69-11e0-9b19-734f335aa7b3\"\n                }\n            ]\n        },\n        \"links\": [\n            {\n                \"rel\": \"self\",\n                \"href\": \"http://servers.api.openstack.org/v2/1234/images/52415800-8b69-11e0-9b19-734f5736d2a2\"\n            },\n            {\n                \"rel\": \"bookmark\",\n                \"href\": \"http://servers.api.openstack.org/1234/images/52415800-8b69-11e0-9b19-734f5736d2a2\"\n            }\n        ]\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/image_list.json",
    "content": "{\n    \"images\": [\n        {\n            \"id\": \"52415800-8b69-11e0-9b19-734f6f006e54\",\n            \"name\": \"CentOS 5.2\",\n            \"links\": [\n                {\n                    \"rel\": \"self\",\n                    \"href\": \"http://servers.api.openstack.org/v2/1234/images/52415800-8b69-11e0-9b19-734f6f006e54\"\n                },\n                {\n                    \"rel\": \"bookmark\",\n                    \"href\": \"http://servers.api.openstack.org/1234/images/52415800-8b69-11e0-9b19-734f6f006e54\"\n                }\n            ]\n        },\n        {\n            \"id\": \"52415800-8b69-11e0-9b19-734f5736d2a2\",\n            \"name\": \"My Server Backup\",\n            \"links\": [\n                {\n                    \"rel\": \"self\",\n                    \"href\": \"http://servers.api.openstack.org/v2/1234/images/52415800-8b69-11e0-9b19-734f5736d2a2\"\n                },\n                {\n                    \"rel\": \"bookmark\",\n                    \"href\": \"http://servers.api.openstack.org/1234/images/52415800-8b69-11e0-9b19-734f5736d2a2\"\n                }\n            ]\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/image_list_detail.json",
    "content": "{\n    \"images\": [\n        {\n            \"status\": \"ACTIVE\",\n            \"updated\": \"2012-03-12T07:52:30Z\",\n            \"name\": \"Debian Squeeze 6.0.3 Server 64-bit 20120123\",\n            \"links\": [\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/37936628937291/images/1361\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/images/1361\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"created\": \"2012-02-21T14:13:55Z\",\n            \"progress\": 100,\n            \"id\": \"1361\",\n            \"metadata\": {\n                \"hp_image_type\": \"machine\",\n                \"image_location\": \"local\",\n                \"image_state\": \"available\",\n                \"project_id\": \"None\",\n                \"hp_md_version\": \"1\",\n                \"kernel_id\": \"1359\",\n                \"min_ram\": 0,\n                \"ramdisk_id\": \"1360\",\n                \"hp_image_id\": \"c89dee3bca7a62103f7d88d2a02f4dc8\",\n                \"owner\": null,\n                \"hp_image_builddate\": \"20120123\",\n                \"architecture\": \"amd64\",\n                \"min_disk\": 0,\n                \"hp_image_version\": \"1hp1.1\"\n            }\n        },\n        {\n            \"status\": \"ACTIVE\",\n            \"updated\": \"2012-03-12T07:52:17Z\",\n            \"name\": \"Debian Squeeze 6.0.3 Server 64-bit 20120123 (Ramdisk)\",\n            \"links\": [\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/37936628937291/images/1360\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/images/1360\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"created\": \"2012-02-21T14:13:53Z\",\n            \"progress\": 100,\n            \"id\": \"1360\",\n            \"metadata\": {\n                \"hp_image_type\": \"ramdisk\",\n                \"image_location\": \"local\",\n                \"image_state\": \"available\",\n                \"project_id\": \"None\",\n                \"hp_md_version\": \"1\",\n                \"min_ram\": 0,\n                \"hp_image_id\": \"c89dee3bca7a62103f7d88d2a02f4dc8\",\n                \"owner\": null,\n                \"hp_image_builddate\": \"20120123\",\n                \"architecture\": \"amd64\",\n                \"min_disk\": 0,\n                \"hp_image_version\": \"1hp1.1\"\n            }\n        },\n        {\n            \"status\": \"ACTIVE\",\n            \"updated\": \"2012-03-12T07:52:09Z\",\n            \"name\": \"Debian Squeeze 6.0.3 Server 64-bit 20120123 (Kernel)\",\n            \"links\": [\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/37936628937291/images/1359\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/images/1359\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"created\": \"2012-02-21T14:13:52Z\",\n            \"progress\": 100,\n            \"id\": \"1359\",\n            \"metadata\": {\n                \"hp_image_type\": \"kernel\",\n                \"image_location\": \"local\",\n                \"image_state\": \"available\",\n                \"project_id\": \"None\",\n                \"hp_md_version\": \"1\",\n                \"min_ram\": 0,\n                \"hp_image_id\": \"c89dee3bca7a62103f7d88d2a02f4dc8\",\n                \"owner\": null,\n                \"hp_image_builddate\": \"20120123\",\n                \"architecture\": \"amd64\",\n                \"min_disk\": 0,\n                \"hp_image_version\": \"1hp1.1\"\n            }\n        },\n        {\n            \"status\": \"ACTIVE\",\n            \"updated\": \"2012-03-12T07:51:52Z\",\n            \"name\": \"CentOS 6.2 Server 64-bit 20120125\",\n            \"links\": [\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/37936628937291/images/1358\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/images/1358\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"created\": \"2012-02-21T13:58:51Z\",\n            \"progress\": 100,\n            \"id\": \"1358\",\n            \"metadata\": {\n                \"hp_image_type\": \"machine\",\n                \"image_location\": \"local\",\n                \"image_state\": \"available\",\n                \"project_id\": \"None\",\n                \"hp_md_version\": \"1\",\n                \"kernel_id\": \"1356\",\n                \"min_ram\": 0,\n                \"ramdisk_id\": \"1357\",\n                \"hp_image_id\": \"f2fbb1bf37a13e7c5da897c7082684df\",\n                \"owner\": null,\n                \"hp_image_builddate\": \"20120125\",\n                \"architecture\": \"x86_64\",\n                \"min_disk\": 0,\n                \"hp_image_version\": \"1hp1\"\n            }\n        },\n        {\n            \"status\": \"ACTIVE\",\n            \"updated\": \"2012-03-12T07:51:37Z\",\n            \"name\": \"CentOS 6.2 Server 64-bit 20120125 (Ramdisk)\",\n            \"links\": [\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/37936628937291/images/1357\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/images/1357\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"created\": \"2012-02-21T13:58:49Z\",\n            \"progress\": 100,\n            \"id\": \"1357\",\n            \"metadata\": {\n                \"hp_image_type\": \"ramdisk\",\n                \"image_location\": \"local\",\n                \"image_state\": \"available\",\n                \"project_id\": \"None\",\n                \"hp_md_version\": \"1\",\n                \"min_ram\": 0,\n                \"hp_image_id\": \"f2fbb1bf37a13e7c5da897c7082684df\",\n                \"owner\": null,\n                \"hp_image_builddate\": \"20120125\",\n                \"architecture\": \"x86_64\",\n                \"min_disk\": 0,\n                \"hp_image_version\": \"1hp1\"\n            }\n        },\n        {\n            \"status\": \"ACTIVE\",\n            \"updated\": \"2012-03-12T07:51:28Z\",\n            \"name\": \"CentOS 6.2 Server 64-bit 20120125 (Kernel)\",\n            \"links\": [\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/37936628937291/images/1356\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/images/1356\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"created\": \"2012-02-21T13:58:47Z\",\n            \"progress\": 100,\n            \"id\": \"1356\",\n            \"metadata\": {\n                \"hp_image_type\": \"kernel\",\n                \"image_location\": \"local\",\n                \"image_state\": \"available\",\n                \"project_id\": \"None\",\n                \"hp_md_version\": \"1\",\n                \"min_ram\": 0,\n                \"hp_image_id\": \"f2fbb1bf37a13e7c5da897c7082684df\",\n                \"owner\": null,\n                \"hp_image_builddate\": \"20120125\",\n                \"architecture\": \"x86_64\",\n                \"min_disk\": 0,\n                \"hp_image_version\": \"1hp1\"\n            }\n        },\n        {\n            \"status\": \"ACTIVE\",\n            \"updated\": \"2012-03-12T07:51:04Z\",\n            \"name\": \"Ubuntu Oneiric 11.10 Server 64-bit 20111212\",\n            \"links\": [\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/37936628937291/images/1242\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/images/1242\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"created\": \"2011-12-21T11:57:15Z\",\n            \"progress\": 100,\n            \"id\": \"1242\",\n            \"metadata\": {\n                \"image_location\": \"local\",\n                \"image_state\": \"available\",\n                \"kernel_id\": \"1241\",\n                \"min_ram\": 0,\n                \"min_disk\": 0,\n                \"architecture\": \"amd64\",\n                \"owner\": null,\n                \"project_id\": \"None\"\n            }\n        },\n        {\n            \"status\": \"ACTIVE\",\n            \"updated\": \"2012-03-12T07:50:58Z\",\n            \"name\": \"Ubuntu Oneiric 11.10 Server 64-bit 20111212 (Kernel)\",\n            \"links\": [\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/37936628937291/images/1241\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/images/1241\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"created\": \"2011-12-21T11:57:07Z\",\n            \"progress\": 100,\n            \"id\": \"1241\",\n            \"metadata\": {\n                \"image_location\": \"local\",\n                \"image_state\": \"available\",\n                \"min_ram\": 0,\n                \"min_disk\": 0,\n                \"architecture\": \"amd64\",\n                \"owner\": null,\n                \"project_id\": \"None\"\n            }\n        },\n        {\n            \"status\": \"ACTIVE\",\n            \"updated\": \"2012-03-12T07:50:52Z\",\n            \"name\": \"Ubuntu Natty 11.04 Server 64-bit 20111212\",\n            \"links\": [\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/37936628937291/images/1240\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/images/1240\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"created\": \"2011-12-21T11:55:03Z\",\n            \"progress\": 100,\n            \"id\": \"1240\",\n            \"metadata\": {\n                \"image_location\": \"local\",\n                \"image_state\": \"available\",\n                \"kernel_id\": \"1239\",\n                \"min_ram\": 0,\n                \"min_disk\": 0,\n                \"architecture\": \"amd64\",\n                \"owner\": null,\n                \"project_id\": \"None\"\n            }\n        },\n        {\n            \"status\": \"ACTIVE\",\n            \"updated\": \"2012-03-12T07:50:45Z\",\n            \"name\": \"Ubuntu Natty 11.04 Server 64-bit 20111212 (Kernel)\",\n            \"links\": [\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/37936628937291/images/1239\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/images/1239\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"created\": \"2011-12-21T11:55:02Z\",\n            \"progress\": 100,\n            \"id\": \"1239\",\n            \"metadata\": {\n                \"image_location\": \"local\",\n                \"image_state\": \"available\",\n                \"min_ram\": 0,\n                \"min_disk\": 0,\n                \"architecture\": \"amd64\",\n                \"owner\": null,\n                \"project_id\": \"None\"\n            }\n        },\n        {\n            \"status\": \"ACTIVE\",\n            \"updated\": \"2012-03-12T07:50:32Z\",\n            \"name\": \"Ubuntu Maverick 10.10 Server 64-bit 20111212\",\n            \"links\": [\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/37936628937291/images/1238\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/images/1238\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"created\": \"2011-12-21T11:52:34Z\",\n            \"progress\": 100,\n            \"id\": \"1238\",\n            \"metadata\": {\n                \"image_location\": \"local\",\n                \"image_state\": \"available\",\n                \"kernel_id\": \"1237\",\n                \"min_ram\": 0,\n                \"min_disk\": 0,\n                \"architecture\": \"amd64\",\n                \"owner\": null,\n                \"project_id\": \"None\"\n            }\n        },\n        {\n            \"status\": \"ACTIVE\",\n            \"updated\": \"2012-03-12T07:50:24Z\",\n            \"name\": \"Ubuntu Maverick 10.10 Server 64-bit 20111212 (Kernel)\",\n            \"links\": [\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/37936628937291/images/1237\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/images/1237\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"created\": \"2011-12-21T11:52:27Z\",\n            \"progress\": 100,\n            \"id\": \"1237\",\n            \"metadata\": {\n                \"image_location\": \"local\",\n                \"image_state\": \"available\",\n                \"min_ram\": 0,\n                \"min_disk\": 0,\n                \"architecture\": \"amd64\",\n                \"owner\": null,\n                \"project_id\": \"None\"\n            }\n        },\n        {\n            \"status\": \"ACTIVE\",\n            \"updated\": \"2012-03-12T07:49:30Z\",\n            \"name\": \"Ubuntu Lucid 10.04 LTS Server 64-bit 20111212\",\n            \"links\": [\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/37936628937291/images/1236\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/images/1236\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"created\": \"2011-12-21T11:40:17Z\",\n            \"progress\": 100,\n            \"id\": \"1236\",\n            \"metadata\": {\n                \"image_location\": \"local\",\n                \"image_state\": \"available\",\n                \"kernel_id\": \"1235\",\n                \"min_ram\": 0,\n                \"min_disk\": 0,\n                \"architecture\": \"amd64\",\n                \"owner\": null,\n                \"project_id\": \"None\"\n            }\n        },\n        {\n            \"status\": \"ACTIVE\",\n            \"updated\": \"2012-03-12T07:49:23Z\",\n            \"name\": \"Ubuntu Lucid 10.04 LTS Server 64-bit 20111212 (Kernel)\",\n            \"links\": [\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/37936628937291/images/1235\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/images/1235\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"created\": \"2011-12-21T11:39:58Z\",\n            \"progress\": 100,\n            \"id\": \"1235\",\n            \"metadata\": {\n                \"image_location\": \"local\",\n                \"image_state\": \"available\",\n                \"min_ram\": 0,\n                \"min_disk\": 0,\n                \"architecture\": \"amd64\",\n                \"owner\": null,\n                \"project_id\": \"None\"\n            }\n        },\n        {\n            \"status\": \"ACTIVE\",\n            \"updated\": \"2012-03-12T07:49:23Z\",\n            \"name\": \"Ubuntu Lucid 16.04 LTS Server 64-bit (Kernel)\",\n            \"links\": [\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/37936628937291/images/1235\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/images/1235\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"created\": \"2011-12-21T11:39:58Z\",\n            \"progress\": 100,\n            \"id\": \"2235\",\n            \"metadata\": {\n                \"image_location\": \"local\",\n                \"image_state\": \"available\",\n                \"min_ram\": 0,\n                \"min_disk\": 0,\n                \"architecture\": \"amd64\",\n                \"owner\": null,\n                \"project_id\": \"None\"\n            }\n        },\n        {\n            \"status\": \"ACTIVE\",\n            \"updated\": \"2012-03-12T07:49:05Z\",\n            \"name\": \"CentOS 5.6 Server 64-bit 20111207\",\n            \"links\": [\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/37936628937291/images/1234\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/images/1234\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"created\": \"2011-12-21T11:07:09Z\",\n            \"progress\": 100,\n            \"id\": \"1234\",\n            \"metadata\": {\n                \"image_location\": \"local\",\n                \"image_state\": \"available\",\n                \"kernel_id\": \"1232\",\n                \"min_ram\": 0,\n                \"ramdisk_id\": \"1233\",\n                \"min_disk\": 0,\n                \"architecture\": \"x86_64\",\n                \"owner\": null,\n                \"project_id\": \"None\"\n            }\n        },\n        {\n            \"status\": \"ACTIVE\",\n            \"updated\": \"2012-03-12T07:48:59Z\",\n            \"name\": \"CentOS 5.6 Server 64-bit 20111207 (Ramdisk)\",\n            \"links\": [\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/37936628937291/images/1233\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/images/1233\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"created\": \"2011-12-21T11:07:08Z\",\n            \"progress\": 100,\n            \"id\": \"1233\",\n            \"metadata\": {\n                \"image_location\": \"local\",\n                \"image_state\": \"available\",\n                \"min_ram\": 0,\n                \"min_disk\": 0,\n                \"architecture\": \"x86_64\",\n                \"owner\": null,\n                \"project_id\": \"None\"\n            }\n        },\n        {\n            \"status\": \"ACTIVE\",\n            \"updated\": \"2012-03-12T07:48:39Z\",\n            \"name\": \"CentOS 5.6 Server 64-bit 20111207 (Kernel)\",\n            \"links\": [\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/37936628937291/images/1232\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/images/1232\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"created\": \"2011-12-21T11:07:07Z\",\n            \"progress\": 100,\n            \"id\": \"1232\",\n            \"metadata\": {\n                \"image_location\": \"local\",\n                \"image_state\": \"available\",\n                \"min_ram\": 0,\n                \"min_disk\": 0,\n                \"architecture\": \"x86_64\",\n                \"owner\": null,\n                \"project_id\": \"None\"\n            }\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/image_list_detail_imageextension.json",
    "content": "{\n    \"images\": [\n        {\n            \"status\": \"UNRECOGNIZED\",\n            \"updated\": \"2012-02-02T19:11:00Z\",\n            \"name\": \"oneiric-server-cloudimg-amd64\",\n            \"links\": [\n                {\n                    \"href\": \"https://nova-api.openstack.org:9774/v2/37/images/15\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"https://nova-api.openstack.org:9774/37/images/15\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"created\": \"2012-02-02T19:10:52Z\",\n            \"progress\": 100,\n            \"id\": \"15\",\n            \"metadata\": {\n                \"kernel_id\": \"14\",\n                \"min_disk\": 0,\n                \"min_ram\": 0,\n                \"owner\": \"1\"\n            }\n        },\n        {\n            \"status\": \"UNKNOWN\",\n            \"updated\": \"2012-02-02T19:10:51Z\",\n            \"name\": \"oneiric-server-cloudimg-amd64-kernel\",\n            \"links\": [\n                {\n                    \"href\": \"https://nova-api.openstack.org:9774/v2/37/images/14\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"https://nova-api.openstack.org:9774/37/images/14\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"created\": \"2012-02-02T19:10:50Z\",\n            \"progress\": 100,\n            \"id\": \"14\",\n            \"metadata\": {\n                \"min_disk\": 0,\n                \"owner\": \"1\",\n                \"min_ram\": 0\n            }\n        },\n        {\n            \"status\": \"ACTIVE\",\n            \"updated\": \"2012-02-02T19:10:41Z\",\n            \"name\": \"natty-server-cloudimg-amd64\",\n            \"links\": [\n                {\n                    \"href\": \"https://nova-api.openstack.org:9774/v2/37/images/13\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"https://nova-api.openstack.org:9774/37/images/13\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"created\": \"2012-02-02T19:10:33Z\",\n            \"progress\": 100,\n            \"id\": \"13\",\n            \"metadata\": {\n                \"kernel_id\": \"12\",\n                \"min_disk\": 0,\n                \"min_ram\": 0,\n                \"owner\": \"1\"\n            }\n        },\n        {\n            \"status\": \"SAVING\",\n            \"updated\": \"2012-02-02T19:10:33Z\",\n            \"name\": \"natty-server-cloudimg-amd64-kernel\",\n            \"links\": [\n                {\n                    \"href\": \"https://nova-api.openstack.org:9774/v2/37/images/12\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"https://nova-api.openstack.org:9774/37/images/12\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"created\": \"2012-02-02T19:10:32Z\",\n            \"progress\": 100,\n            \"id\": \"12\",\n            \"metadata\": {\n                \"min_disk\": 0,\n                \"owner\": \"1\",\n                \"min_ram\": 0\n            }\n        },\n        {\n            \"status\": \"ERROR\",\n            \"updated\": \"2012-02-02T19:10:41Z\",\n            \"name\": \"natty-server-cloudimg-amd64\",\n            \"links\": [\n                {\n                    \"href\": \"https://nova-api.openstack.org:9774/v2/37/images/11\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"https://nova-api.openstack.org:9774/37/images/11\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"created\": \"2012-02-02T19:10:33Z\",\n            \"progress\": 100,\n            \"id\": \"11\",\n            \"metadata\": {\n                \"kernel_id\": \"12\",\n                \"min_disk\": 0,\n                \"min_ram\": 0,\n                \"owner\": \"1\"\n            }\n        },\n        {\n            \"status\": \"ERROR\",\n            \"updated\": \"2012-02-02T19:10:41Z\",\n            \"name\": \"natty-server-cloudimg-amd64\",\n            \"links\": [\n                {\n                    \"href\": \"https://nova-api.openstack.org:9774/v2/37/images/10\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"https://nova-api.openstack.org:9774/37/images/10\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"created\": \"2012-02-02T19:10:33Z\",\n            \"progress\": 100,\n            \"id\": \"10\",\n            \"metadata\": {\n                \"kernel_id\": \"12\",\n                \"min_disk\": 0,\n                \"min_ram\": 0,\n                \"owner\": \"1\"\n            }\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/image_list_detail_openstack.json",
    "content": "{\n    \"images\": [\n        {\n            \"status\": \"ACTIVE\",\n            \"updated\": \"2012-02-02T19:11:00Z\",\n            \"name\": \"oneiric-server-cloudimg-amd64\",\n            \"links\": [\n                {\n                    \"href\": \"https://nova-api.openstack.org:9774/v2/37/images/15\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"https://nova-api.openstack.org:9774/37/images/15\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"created\": \"2012-02-02T19:10:52Z\",\n            \"progress\": 100,\n            \"id\": \"15\",\n            \"metadata\": {\n                \"kernel_id\": \"14\",\n                \"min_disk\": 0,\n                \"min_ram\": 0,\n                \"owner\": \"1\"\n            }\n        },\n        {\n            \"status\": \"ACTIVE\",\n            \"updated\": \"2012-02-02T19:10:51Z\",\n            \"name\": \"oneiric-server-cloudimg-amd64-kernel\",\n            \"links\": [\n                {\n                    \"href\": \"https://nova-api.openstack.org:9774/v2/37/images/14\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"https://nova-api.openstack.org:9774/37/images/14\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"created\": \"2012-02-02T19:10:50Z\",\n            \"progress\": 100,\n            \"id\": \"14\",\n            \"metadata\": {\n                \"min_disk\": 0,\n                \"owner\": \"1\",\n                \"min_ram\": 0\n            }\n        },\n        {\n            \"status\": \"ACTIVE\",\n            \"updated\": \"2012-02-02T19:10:41Z\",\n            \"name\": \"natty-server-cloudimg-amd64\",\n            \"links\": [\n                {\n                    \"href\": \"https://nova-api.openstack.org:9774/v2/37/images/13\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"https://nova-api.openstack.org:9774/37/images/13\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"created\": \"2012-02-02T19:10:33Z\",\n            \"progress\": 100,\n            \"id\": \"13\",\n            \"metadata\": {\n                \"kernel_id\": \"12\",\n                \"min_disk\": 0,\n                \"min_ram\": 0,\n                \"owner\": \"1\"\n            }\n        },\n        {\n            \"status\": \"ACTIVE\",\n            \"updated\": \"2012-03-12T07:49:23Z\",\n            \"name\": \"Ubuntu Lucid 16.04 LTS Server 64-bit (Kernel)\",\n            \"links\": [\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/37936628937291/images/1235\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/images/1235\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"created\": \"2011-12-21T11:39:58Z\",\n            \"progress\": 100,\n            \"id\": \"2235\",\n            \"metadata\": {\n                \"image_location\": \"local\",\n                \"image_state\": \"available\",\n                \"min_ram\": 0,\n                \"min_disk\": 0,\n                \"architecture\": \"amd64\",\n                \"owner\": null,\n                \"project_id\": \"None\"\n            }\n        },\n        {\n            \"status\": \"ACTIVE\",\n            \"updated\": \"2012-02-02T19:10:33Z\",\n            \"name\": \"natty-server-cloudimg-amd64-kernel\",\n            \"links\": [\n                {\n                    \"href\": \"https://nova-api.openstack.org:9774/v2/37/images/12\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"https://nova-api.openstack.org:9774/37/images/12\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"created\": \"2012-02-02T19:10:32Z\",\n            \"progress\": 100,\n            \"id\": \"12\",\n            \"metadata\": {\n                \"min_disk\": 0,\n                \"owner\": \"1\",\n                \"min_ram\": 0\n            }\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/image_list_with_block_device_mapping.json",
    "content": "{\n  \"images\": [\n    {\n      \"status\": \"ACTIVE\",\n      \"updated\": \"2014-08-08T04:43:36Z\",\n      \"links\": [\n        {\n          \"href\": \"http://192.168.24.16:8774/v2/d312a9d1acee46499e04fc2c0cd7e540/images/cd9d57a9-0978-45f3-9cbc-edb99347be6b\",\n          \"rel\": \"self\"\n        },\n        {\n          \"href\": \"http://192.168.24.16:8774/d312a9d1acee46499e04fc2c0cd7e540/images/cd9d57a9-0978-45f3-9cbc-edb99347be6b\",\n          \"rel\": \"bookmark\"\n        },\n        {\n          \"href\": \"http://192.168.24.16:9292/d312a9d1acee46499e04fc2c0cd7e540/images/cd9d57a9-0978-45f3-9cbc-edb99347be6b\",\n          \"type\": \"application/vnd.openstack.image\",\n          \"rel\": \"alternate\"\n        }\n      ],\n      \"id\": \"cd9d57a9-0978-45f3-9cbc-edb99347be6b\",\n      \"OS-EXT-IMG-SIZE:size\": 0,\n      \"name\": \"t11\",\n      \"created\": \"2014-08-08T04:43:36Z\",\n      \"minDisk\": 0,\n      \"progress\": 100,\n      \"minRam\": 0,\n      \"metadata\": {\n        \"block_device_mapping\": [\n          {\n            \"guest_format\": null,\n            \"boot_index\": 2,\n            \"no_device\": null,\n            \"volume_id\": null,\n            \"volume_size\": null,\n            \"disk_bus\": null,\n            \"image_id\": null,\n            \"source_type\": \"snapshot\",\n            \"device_type\": null,\n            \"snapshot_id\": \"a900a56c-61b7-4438-9150-76312fa1aa10\",\n            \"destination_type\": \"volume\",\n            \"delete_on_termination\": null\n          }\n        ],\n        \"checksum\": \"32c08d302f9206668030d47789b77858\",\n        \"min_ram\": \"1\",\n        \"disk_format\": \"qcow2\",\n        \"image_name\": \"Ubuntu LTS 14.04\",\n        \"bdm_v2\": \"True\",\n        \"image_id\": \"cfefefc1-eba2-4b1e-9b07-a8c74a872d65\",\n        \"root_device_name\": \"/dev/vda\",\n        \"container_format\": \"bare\",\n        \"min_disk\": \"8\",\n        \"size\": \"254149120\"\n      }\n    }\n  ]\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/keypair_created_computeservice.json",
    "content": "{\n    \"keypair\": {\n        \"public_key\": \"ssh-rsa AAAXB3NzaC1yc2EAAAADAQABAAAAgQDFNyGjgs6c9akgmZ2ou/fJf7Pdrc23hC95/gM/33OrG4GZABACE4DTioa/PGN+7rHv9YUavUCtXrWayhGniKq/wCuI5fo5TO4AmDNv7/sCGHIHFumADSIoLx0vFhGJIetXEWxL9r0lfFC7//6yZM2W3KcGjbMtlPXqBT9K9PzdyQ== nova@nv-aw2az1-api0001\\n\",\n        \"private_key\": \"-----BEGIN RSA PRIVATE KEY-----\\nMIICXQIAAAKBgQDFNyGjgs6c9akgmZ2ou/fJf7Pdrc23hC95/gM/33OrG4GZABAC\\nE4DTioa/PGN+7rHv9YUavUCtXrWayhGniKq/wCuI5fo5TO4AmDNv7/sCGHIHFumA\\nDSIoLx0vFhGJIetXEWxL9r0lfFC7//6yZM2W3KcGjbMtlPXqBT9K9PzdyQIDAQAB\\nAoGAW8Ww+KbpQK8smcgCTr/RqcmsSI8VeL2hXjJvDq0L5WbyYuFdkanDvCztUVZn\\nsmyfDtwAqZXB4Ct/dN1tY7m8QpdyRaKRW4Q+hghGCAQpsG7rYDdvwdEyvMaW5RA4\\ntucQyajMNyQ/tozU3wMx/v8A7RvGcE9tqoG0WK1C3kBu95UCQQDrOd+joYDkvccz\\nFIVu5gNPMXEh3fGGzDxk225UlvESquYLzfz4TfmuUjH4Z1BL3wRiwfJsrrjFkm33\\njIidDE8PAkEA1qHjxuaIS1yz/rfzErmcOVNlbFHMP4ihjGTTvh1ZctXlNeLwzENQ\\nEDaQV3IpUY1KQR6rxcWb5AXgfF9D9PYFpwJBANucAqGAbRgh3lJgPFtXP4u2O0tF\\nLPOOxmvbOdybt6KYD4LB5AXmts77SlACFMNhCXUyYaT6UuOSXDyb5gfJsB0CQQC3\\nFaGXKU9Z+doQjhlq/6mjvN/nZl80Uvh7Kgb1RVPoAU1kihGeLE0/h0vZTCiyyDNv\\nGRqtucMg32J+tUTi0HpBAkAwHiCZMHMeJWHUwIwlRQY/dnR86FWobRl98ViF2rCL\\nDHkDVOeIser3Q6zSqU5/m99lX6an5g8pAh/R5LqnOQZC\\n-----END RSA PRIVATE KEY-----\\n\",\n        \"user_id\": \"65649731189278\",\n        \"name\": \"jclouds-test-0\",\n        \"fingerprint\": \"d2:1f:c9:2b:d8:90:77:5f:15:64:27:e3:9f:77:1d:e4\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/keypair_details.json",
    "content": "{\n    \"keypair\": {\n        \"public_key\": \"ssh-rsa AAAXB3NzaC1yc2EAAAADAQABAAAAgQDFNyGjgs6c9akgmZ2ou/fJf7Pdrc23hC95/gM/33OrG4GZABACE4DTioa/PGN+7rHv9YUavUCtXrWayhGniKq/wCuI5fo5TO4AmDNv7/sCGHIHFumADSIoLx0vFhGJIetXEWxL9r0lfFC7//6yZM2W3KcGjbMtlPXqBT9K9PzdyQ== nova@nv-aw2az1-api0001\\n\",\n        \"private_key\": \"-----BEGIN RSA PRIVATE KEY-----\\nMIICXQIAAAKBgQDFNyGjgs6c9akgmZ2ou/fJf7Pdrc23hC95/gM/33OrG4GZABAC\\nE4DTioa/PGN+7rHv9YUavUCtXrWayhGniKq/wCuI5fo5TO4AmDNv7/sCGHIHFumA\\nDSIoLx0vFhGJIetXEWxL9r0lfFC7//6yZM2W3KcGjbMtlPXqBT9K9PzdyQIDAQAB\\nAoGAW8Ww+KbpQK8smcgCTr/RqcmsSI8VeL2hXjJvDq0L5WbyYuFdkanDvCztUVZn\\nsmyfDtwAqZXB4Ct/dN1tY7m8QpdyRaKRW4Q+hghGCAQpsG7rYDdvwdEyvMaW5RA4\\ntucQyajMNyQ/tozU3wMx/v8A7RvGcE9tqoG0WK1C3kBu95UCQQDrOd+joYDkvccz\\nFIVu5gNPMXEh3fGGzDxk225UlvESquYLzfz4TfmuUjH4Z1BL3wRiwfJsrrjFkm33\\njIidDE8PAkEA1qHjxuaIS1yz/rfzErmcOVNlbFHMP4ihjGTTvh1ZctXlNeLwzENQ\\nEDaQV3IpUY1KQR6rxcWb5AXgfF9D9PYFpwJBANucAqGAbRgh3lJgPFtXP4u2O0tF\\nLPOOxmvbOdybt6KYD4LB5AXmts77SlACFMNhCXUyYaT6UuOSXDyb5gfJsB0CQQC3\\nFaGXKU9Z+doQjhlq/6mjvN/nZl80Uvh7Kgb1RVPoAU1kihGeLE0/h0vZTCiyyDNv\\nGRqtucMg32J+tUTi0HpBAkAwHiCZMHMeJWHUwIwlRQY/dnR86FWobRl98ViF2rCL\\nDHkDVOeIser3Q6zSqU5/m99lX6an5g8pAh/R5LqnOQZC\\n-----END RSA PRIVATE KEY-----\\n\",\n        \"user_id\": \"65649731189278\",\n        \"name\": \"testkeypair\",\n        \"fingerprint\": \"d2:1f:c9:2b:d8:90:77:5f:15:64:27:e3:9f:77:1d:e4\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/keypair_list.json",
    "content": "{\n    \"keypairs\": [\n        {\n            \"keypair\": {\n                \"public_key\": \"ssh-rsa AAAXB3NzaC1yc2EAAAADAQABAAAAgQCy9EC3O7Ff80vPEfAHDQob61PGwcpYc5KE7tEZnZhrB9n0NyHPRm0E0M+ls3fcTa04HDi+R0DzmRwoyhHQJyI658v8kWZZcuvFjKCcsgsSh/dzdX0xTreLIzSOzt5U7RnZYfshP5cmxtF99yrEY3M/swdin0L+fXsTSkR1B42STQ== nova@nv-aw2az1-api0001\",\n                \"name\": \"default\",\n                \"fingerprint\": \"ab:0c:f4:f3:54:c0:5d:3f:ed:62:ad:d3:94:7c:79:7c\"\n            }\n        },\n        {\n            \"keypair\": {\n                \"public_key\": \"ssh-rsa AAAXB3NzaC1yc2EAAAADAQABAAAAgQDFNyGjgs6c9akgmZ2ou/fJf7Pdrc23hC95/gM/33OrG4GZABACE4DTioa/PGN+7rHv9YUavUCtXrWayhGniKq/wCuI5fo5TO4AmDNv7/sCGHIHFumADSIoLx0vFhGJIetXEWxL9r0lfFC7//6yZM2W3KcGjbMtlPXqBT9K9PzdyQ== nova@nv-aw2az1-api0001\",\n                \"name\": \"testkeypair\",\n                \"fingerprint\": \"d2:1f:c9:2b:d8:90:77:5f:15:64:27:e3:9f:77:1d:e4\"\n            }\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/listAvailabilityZones.json",
    "content": "{\n    \"availabilityZoneInfo\": [\n        {\n            \"zoneState\": {\n                \"available\": true\n            },\n            \"hosts\": {\n                \"os-controller\": {\n                    \"nova-conductor\": {\n                        \"available\": true,\n                        \"active\": true,\n                        \"updated_at\": \"2015-07-10T06:30:15.000000\"\n                    },\n                    \"nova-consoleauth\": {\n                        \"available\": true,\n                        \"active\": true,\n                        \"updated_at\": \"2015-07-10T06:30:20.000000\"\n                    },\n                    \"nova-cert\": {\n                        \"available\": true,\n                        \"active\": true,\n                        \"updated_at\": \"2015-07-10T06:30:19.000000\"\n                    },\n                    \"nova-scheduler\": {\n                        \"available\": true,\n                        \"active\": true,\n                        \"updated_at\": \"2015-07-10T06:30:12.000000\"\n                    }\n                }\n            },\n            \"zoneName\": \"internal\"\n        },\n        {\n            \"zoneState\": {\n                \"available\": true\n            },\n            \"hosts\": {\n                \"os-compute02\": {\n                    \"nova-compute\": {\n                        \"available\": true,\n                        \"active\": true,\n                        \"updated_at\": \"2015-07-10T06:30:16.000000\"\n                    }\n                },\n                \"os-compute01\": {\n                    \"nova-compute\": {\n                        \"available\": true,\n                        \"active\": true,\n                        \"updated_at\": \"2015-07-10T06:30:12.000000\"\n                    }\n                }\n            },\n            \"zoneName\": \"nova\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/logback-test.xml",
    "content": "<?xml version=\"1.0\"?>\n<configuration scan=\"false\">\n    <appender name=\"FILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds.log</file>\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n    <appender name=\"WIREFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds-wire.log</file>\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n    <appender name=\"COMPUTEFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds-compute.log</file>\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <logger name=\"org.jclouds\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"FILE\" />\n    </logger>\n    <logger name=\"jclouds.compute\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"COMPUTEFILE\" />\n    </logger>\n    <logger name=\"jclouds.wire\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n    <logger name=\"jclouds.headers\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n    \n    <root>\n        <level value=\"INFO\" />\n    </root>\n</configuration>"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/metadata_item.json",
    "content": "{\n    \"metadata\": {\n        \"Server Label\": \"Web Head 1\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/metadata_list.json",
    "content": "{\n    \"metadata\": {\n        \"Server Label\": \"Web Head 1\",\n        \"Image Version\": \"2.1\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/metadata_updated.json",
    "content": "{\n    \"metadata\": {\n        \"Server Label\": \"Web Head 2\",\n        \"Image Version\": \"2.1\",\n        \"Server Description\": \"Simple Server\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/new_server.json",
    "content": "{\n    \"server\": {\n        \"status\": \"BUILD(scheduling)\",\n        \"updated\": \"2012-03-19T06:21:13Z\",\n        \"hostId\": \"\",\n        \"user_id\": \"54297837463082\",\n        \"name\": \"test-e92\",\n        \"links\": [\n            {\n                \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/37936628937291/servers/71752\",\n                \"rel\": \"self\"\n            },\n            {\n                \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/servers/71752\",\n                \"rel\": \"bookmark\"\n            }\n        ],\n        \"addresses\": {},\n        \"tenant_id\": \"37936628937291\",\n        \"image\": {\n            \"id\": \"1241\",\n            \"links\": [\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/images/1241\",\n                    \"rel\": \"bookmark\"\n                }\n            ]\n        },\n        \"created\": \"2012-03-19T06:21:13Z\",\n        \"uuid\": \"47491020-6a78-4f63-9475-23195ac4515c\",\n        \"accessIPv4\": \"\",\n        \"accessIPv6\": \"\",\n        \"key_name\": null,\n        \"adminPass\": \"ZWuHcmTMQ7eXoHeM\",\n        \"flavor\": {\n            \"id\": \"100\",\n            \"links\": [\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/flavors/100\",\n                    \"rel\": \"bookmark\"\n                }\n            ]\n        },\n        \"config_drive\": \"\",\n        \"id\": 71752,\n        \"metadata\": {}\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/new_server_config_drive.json",
    "content": "{\n    \"server\": {\n        \"status\": \"BUILD(scheduling)\",\n        \"updated\": \"2012-03-19T06:21:13Z\",\n        \"hostId\": \"\",\n        \"user_id\": \"54297837463082\",\n        \"name\": \"test-e92\",\n        \"links\": [{\n            \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/37936628937291/servers/71752\",\n            \"rel\": \"self\"\n        }, {\n            \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/servers/71752\",\n            \"rel\": \"bookmark\"\n        }],\n        \"addresses\": {},\n        \"tenant_id\": \"37936628937291\",\n        \"image\": {\n            \"id\": \"1241\",\n            \"links\": [{\n                \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/images/1241\",\n                \"rel\": \"bookmark\"\n            }]\n        },\n        \"created\": \"2012-03-19T06:21:13Z\",\n        \"uuid\": \"47491020-6a78-4f63-9475-23195ac4515c\",\n        \"accessIPv4\": \"\",\n        \"accessIPv6\": \"\",\n        \"key_name\": null,\n        \"adminPass\": \"ZWuHcmTMQ7eXoHeM\",\n        \"flavor\": {\n            \"id\": \"100\",\n            \"links\": [{\n                \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/flavors/100\",\n                \"rel\": \"bookmark\"\n            }]\n        },\n        \"config_drive\": \"true\",\n        \"id\": 71752,\n        \"metadata\": {},\n        \"OS-DCF:diskConfig\": \"AUTO\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/new_server_disk_config_auto.json",
    "content": "{\n    \"server\": {\n        \"status\": \"BUILD(scheduling)\",\n        \"updated\": \"2012-03-19T06:21:13Z\",\n        \"hostId\": \"\",\n        \"user_id\": \"54297837463082\",\n        \"name\": \"test-e92\",\n        \"links\": [\n            {\n                \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/37936628937291/servers/71752\",\n                \"rel\": \"self\"\n            },\n            {\n                \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/servers/71752\",\n                \"rel\": \"bookmark\"\n            }\n        ],\n        \"addresses\": {},\n        \"tenant_id\": \"37936628937291\",\n        \"image\": {\n            \"id\": \"1241\",\n            \"links\": [\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/images/1241\",\n                    \"rel\": \"bookmark\"\n                }\n            ]\n        },\n        \"created\": \"2012-03-19T06:21:13Z\",\n        \"uuid\": \"47491020-6a78-4f63-9475-23195ac4515c\",\n        \"accessIPv4\": \"\",\n        \"accessIPv6\": \"\",\n        \"key_name\": null,\n        \"adminPass\": \"ZWuHcmTMQ7eXoHeM\",\n        \"flavor\": {\n            \"id\": \"100\",\n            \"links\": [\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/flavors/100\",\n                    \"rel\": \"bookmark\"\n                }\n            ]\n        },\n        \"config_drive\": \"\",\n        \"id\": 71752,\n        \"metadata\": {},\n        \"OS-DCF:diskConfig\": \"AUTO\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/new_server_disk_config_manual.json",
    "content": "{\n    \"server\": {\n        \"status\": \"BUILD(scheduling)\",\n        \"updated\": \"2012-03-19T06:21:13Z\",\n        \"hostId\": \"\",\n        \"user_id\": \"54297837463082\",\n        \"name\": \"test-e92\",\n        \"links\": [\n            {\n                \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/37936628937291/servers/71752\",\n                \"rel\": \"self\"\n            },\n            {\n                \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/servers/71752\",\n                \"rel\": \"bookmark\"\n            }\n        ],\n        \"addresses\": {},\n        \"tenant_id\": \"37936628937291\",\n        \"image\": {\n            \"id\": \"1241\",\n            \"links\": [\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/images/1241\",\n                    \"rel\": \"bookmark\"\n                }\n            ]\n        },\n        \"created\": \"2012-03-19T06:21:13Z\",\n        \"uuid\": \"47491020-6a78-4f63-9475-23195ac4515c\",\n        \"accessIPv4\": \"\",\n        \"accessIPv6\": \"\",\n        \"key_name\": null,\n        \"adminPass\": \"ZWuHcmTMQ7eXoHeM\",\n        \"flavor\": {\n            \"id\": \"100\",\n            \"links\": [\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/flavors/100\",\n                    \"rel\": \"bookmark\"\n                }\n            ]\n        },\n        \"config_drive\": \"\",\n        \"id\": 71752,\n        \"metadata\": {},\n        \"OS-DCF:diskConfig\": \"MANUAL\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/new_server_in_zone.json",
    "content": "{\n    \"server\": {\n        \"status\": \"BUILD(scheduling)\",\n        \"updated\": \"2012-03-19T06:21:13Z\",\n        \"hostId\": \"\",\n        \"user_id\": \"54297837463082\",\n        \"name\": \"test-e92\",\n        \"links\": [\n            {\n                \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/37936628937291/servers/71752\",\n                \"rel\": \"self\"\n            },\n            {\n                \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/servers/71752\",\n                \"rel\": \"bookmark\"\n            }\n        ],\n        \"addresses\": {},\n        \"tenant_id\": \"37936628937291\",\n        \"image\": {\n            \"id\": \"1241\",\n            \"links\": [\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/images/1241\",\n                    \"rel\": \"bookmark\"\n                }\n            ]\n        },\n        \"created\": \"2012-03-19T06:21:13Z\",\n        \"uuid\": \"47491020-6a78-4f63-9475-23195ac4515c\",\n        \"accessIPv4\": \"\",\n        \"accessIPv6\": \"\",\n        \"key_name\": null,\n        \"adminPass\": \"ZWuHcmTMQ7eXoHeM\",\n        \"flavor\": {\n            \"id\": \"100\",\n            \"links\": [\n                {\n                    \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/flavors/100\",\n                    \"rel\": \"bookmark\"\n                }\n            ]\n        },\n        \"config_drive\": \"\",\n        \"id\": 71752,\n        \"metadata\": {}\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/new_server_networks_response.json",
    "content": "{\n    \"server\": {\n        \"status\": \"BUILD(scheduling)\",\n        \"updated\": \"2012-03-19T06:21:13Z\",\n        \"hostId\": \"\",\n        \"user_id\": \"54297837463082\",\n        \"name\": \"test-e92\",\n        \"links\": [{\n            \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/37936628937291/servers/71752\",\n            \"rel\": \"self\"\n        }, {\n            \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/servers/71752\",\n            \"rel\": \"bookmark\"\n        }],\n        \"addresses\": {},\n        \"tenant_id\": \"37936628937291\",\n        \"image\": {\n            \"id\": \"1241\",\n            \"links\": [{\n                \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/images/1241\",\n                \"rel\": \"bookmark\"\n            }]\n        },\n        \"created\": \"2012-03-19T06:21:13Z\",\n        \"uuid\": \"47491020-6a78-4f63-9475-23195ac4515c\",\n        \"accessIPv4\": \"\",\n        \"accessIPv6\": \"\",\n        \"key_name\": null,\n        \"adminPass\": \"ZWuHcmTMQ7eXoHeM\",\n        \"flavor\": {\n            \"id\": \"100\",\n            \"links\": [{\n                \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/flavors/100\",\n                \"rel\": \"bookmark\"\n            }]\n        },\n        \"config_drive\": \"\",\n        \"id\": 71752,\n        \"metadata\": {},\n        \"OS-DCF:diskConfig\": \"AUTO\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/new_server_no_adminpass.json",
    "content": "{\n    \"server\": {\n        \"status\": \"BUILD(scheduling)\",\n        \"updated\": \"2012-03-19T06:21:13Z\",\n        \"hostId\": \"\",\n        \"user_id\": \"54297837463082\",\n        \"name\": \"test-e92\",\n        \"links\": [{\n            \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v2/37936628937291/servers/71752\",\n            \"rel\": \"self\"\n        }, {\n            \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/servers/71752\",\n            \"rel\": \"bookmark\"\n        }],\n        \"addresses\": {},\n        \"tenant_id\": \"37936628937291\",\n        \"image\": {\n            \"id\": \"1241\",\n            \"links\": [{\n                \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/images/1241\",\n                \"rel\": \"bookmark\"\n            }]\n        },\n        \"created\": \"2012-03-19T06:21:13Z\",\n        \"uuid\": \"47491020-6a78-4f63-9475-23195ac4515c\",\n        \"accessIPv4\": \"\",\n        \"accessIPv6\": \"\",\n        \"key_name\": null,\n        \"flavor\": {\n            \"id\": \"100\",\n            \"links\": [{\n                \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/flavors/100\",\n                \"rel\": \"bookmark\"\n            }]\n        },\n        \"config_drive\": \"\",\n        \"id\": 71752,\n        \"metadata\": {}\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/new_server_nova_networks.json",
    "content": "{\n    \"server\": {\n        \"status\": \"BUILD(scheduling)\",\n        \"updated\": \"2012-03-19T06:21:13Z\",\n        \"hostId\": \"\",\n        \"user_id\": \"54297837463082\",\n        \"name\": \"test-e92\",\n        \"links\": [{\n            \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/37936628937291/servers/71752\",\n            \"rel\": \"self\"\n        }, {\n            \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/servers/71752\",\n            \"rel\": \"bookmark\"\n        }],\n        \"addresses\": {},\n        \"tenant_id\": \"37936628937291\",\n        \"image\": {\n            \"id\": \"1241\",\n            \"links\": [{\n                \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/images/1241\",\n                \"rel\": \"bookmark\"\n            }]\n        },\n        \"created\": \"2012-03-19T06:21:13Z\",\n        \"uuid\": \"47491020-6a78-4f63-9475-23195ac4515c\",\n        \"accessIPv4\": \"\",\n        \"accessIPv6\": \"\",\n        \"key_name\": null,\n        \"adminPass\": \"ZWuHcmTMQ7eXoHeM\",\n        \"flavor\": {\n            \"id\": \"100\",\n            \"links\": [{\n                \"href\": \"https://az-1.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/flavors/100\",\n                \"rel\": \"bookmark\"\n            }]\n        },\n        \"id\": 71752,\n        \"metadata\": {},\n        \"OS-DCF:diskConfig\": \"AUTO\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/novnc_console.json",
    "content": "{\n    \"console\": {\n        \"type\": \"novnc\",\n        \"url\": \"http://example.com:6080/vnc_auto.html?token=f9906a48-b71e-4f18-baca-c987da3ebdb3&title=dafa(75ecef58-3b8e-4659-ab3b-5501454188e9)\"\n    }\n}\n\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/quotas.json",
    "content": "{\n    \"quota_set\": {\n        \"metadata_items\": 128,\n        \"injected_file_content_bytes\": 10240,\n        \"injected_files\": 5,\n        \"gigabytes\": 1000,\n        \"ram\": 51200,\n        \"floating_ips\": 10,\n        \"security_group_rules\": 20,\n        \"instances\": 10,\n        \"key_pairs\": 100,\n        \"volumes\": 10,\n        \"cores\": 20,\n        \"id\": \"demo\",\n        \"security_groups\": 10\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/rdp_console.json",
    "content": "{\n    \"console\": {\n        \"type\": \"rdp-html5\",\n        \"url\": \"http://example.com:6083/?token=f9906a48-b71e-4f18-baca-c987da3ebdb3&title=dafa(75ecef58-3b8e-4659-ab3b-5501454188e9)\"\n    }\n}\n\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/securitygroup_created.json",
    "content": "{\n    \"security_group\": {\n        \"rules\": [],\n        \"tenant_id\": \"dev_16767499955063\",\n        \"id\": 160,\n        \"name\": \"jclouds-test\",\n        \"description\": \"jclouds-test\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/securitygroup_details.json",
    "content": "{\n    \"security_group\": {\n        \"rules\": [\n            {\n                \"from_port\": 22,\n                \"group\": {},\n                \"ip_protocol\": \"tcp\",\n                \"to_port\": 22,\n                \"parent_group_id\": 28,\n                \"ip_range\": {\n                    \"cidr\": \"10.2.6.0/24\"\n                },\n                \"id\": 108\n            },\n            {\n                \"from_port\": 22,\n                \"group\": {\n                    \"tenant_id\": \"admin\",\n                    \"name\": \"11111\"\n                },\n                \"ip_protocol\": \"tcp\",\n                \"to_port\": 22,\n                \"parent_group_id\": 28,\n                \"ip_range\": {},\n                \"id\": 109\n            }\n        ],\n        \"tenant_id\": \"tenant0\",\n        \"id\": 0,\n        \"name\": \"name0\",\n        \"description\": \"description0\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/securitygroup_details_computeservice_typical.json",
    "content": "{\n    \"security_group\": {\n        \"rules\": [\n            {\n                \"from_port\": 22,\n                \"group\": {},\n                \"ip_protocol\": \"tcp\",\n                \"to_port\": 22,\n                \"parent_group_id\": 2769,\n                \"ip_range\": {\n                    \"cidr\": \"0.0.0.0/0\"\n                },\n                \"id\": 10331\n            },\n            {\n                \"from_port\": 22,\n                \"group\": {\n                    \"tenant_id\": \"37936628937291\",\n                    \"name\": \"jclouds_mygroup\"\n                },\n                \"ip_protocol\": \"tcp\",\n                \"to_port\": 22,\n                \"parent_group_id\": 2769,\n                \"ip_range\": {},\n                \"id\": 10332\n            },\n            {\n                \"from_port\": 8080,\n                \"group\": {},\n                \"ip_protocol\": \"tcp\",\n                \"to_port\": 8080,\n                \"parent_group_id\": 2769,\n                \"ip_range\": {\n                    \"cidr\": \"0.0.0.0/0\"\n                },\n                \"id\": 10333\n            },\n            {\n                \"from_port\": 8080,\n                \"group\": {\n                    \"tenant_id\": \"37936628937291\",\n                    \"name\": \"jclouds_mygroup\"\n                },\n                \"ip_protocol\": \"tcp\",\n                \"to_port\": 8080,\n                \"parent_group_id\": 2769,\n                \"ip_range\": {},\n                \"id\": 10334\n            }\n        ],\n        \"tenant_id\": \"37936628937291\",\n        \"id\": 2769,\n        \"name\": \"jclouds_mygroup\",\n        \"description\": \"jclouds_mygroup\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/securitygroup_details_extension.json",
    "content": "{\n    \"security_group\": {\n        \"rules\": [\n            {\n                \"from_port\": 22,\n                \"group\": {},\n                \"ip_protocol\": \"tcp\",\n                \"to_port\": 22,\n                \"parent_group_id\": 160,\n                \"ip_range\": {\n                    \"cidr\": \"10.2.6.0/24\"\n                },\n                \"id\": 108\n            },\n            {\n                \"from_port\": 22,\n                \"group\": {\n                    \"tenant_id\": \"tenant0\",\n                    \"name\": \"name0\"\n                },\n                \"ip_protocol\": \"tcp\",\n                \"to_port\": 22,\n                \"parent_group_id\": 160,\n                \"ip_range\": {},\n                \"id\": 109\n            }\n        ],\n        \"tenant_id\": \"tenant0\",\n        \"id\": 160,\n        \"name\": \"name0\",\n        \"description\": \"description0\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/securitygroup_details_extension_norules.json",
    "content": "{\n    \"security_group\": {\n        \"rules\": [],\n        \"tenant_id\": \"tenant0\",\n        \"id\": 160,\n        \"name\": \"name0\",\n        \"description\": \"description0\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/securitygroup_details_port22.json",
    "content": "{\n    \"security_group\": {\n        \"rules\": [\n            {\n                \"from_port\": 22,\n                \"group\": {},\n                \"ip_protocol\": \"tcp\",\n                \"to_port\": 22,\n                \"parent_group_id\": 2769,\n                \"ip_range\": {\n                    \"cidr\": \"0.0.0.0/0\"\n                },\n                \"id\": 10331\n            }\n        ],\n        \"tenant_id\": \"37936628937291\",\n        \"id\": 2769,\n        \"name\": \"jclouds-test\",\n        \"description\": \"jclouds-test\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/securitygroup_list.json",
    "content": "{\n    \"security_groups\": [\n        {\n            \"rules\": [\n                {\n                    \"from_port\": 22,\n                    \"group\": {},\n                    \"ip_protocol\": \"tcp\",\n                    \"to_port\": 22,\n                    \"parent_group_id\": 3,\n                    \"ip_range\": {\n                        \"cidr\": \"0.0.0.0/0\"\n                    },\n                    \"id\": 107\n                },\n                {\n                    \"from_port\": 7600,\n                    \"group\": {},\n                    \"ip_protocol\": \"tcp\",\n                    \"to_port\": 7600,\n                    \"parent_group_id\": 3,\n                    \"ip_range\": {\n                        \"cidr\": \"0.0.0.0/0\"\n                    },\n                    \"id\": 118\n                },\n                {\n                    \"from_port\": 8084,\n                    \"group\": {},\n                    \"ip_protocol\": \"tcp\",\n                    \"to_port\": 8084,\n                    \"parent_group_id\": 3,\n                    \"ip_range\": {\n                        \"cidr\": \"0.0.0.0/0\"\n                    },\n                    \"id\": 119\n                }\n            ],\n            \"tenant_id\": \"tenant1\",\n            \"id\": 1,\n            \"name\": \"name1\",\n            \"description\": \"description1\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/securitygroup_list_details_computeservice_typical.json",
    "content": "{\n    \"security_groups\": [\n        {\n            \"rules\": [\n                {\n                    \"from_port\": 22,\n                    \"group\": {},\n                    \"ip_protocol\": \"tcp\",\n                    \"to_port\": 22,\n                    \"parent_group_id\": 2769,\n                    \"ip_range\": {\n                        \"cidr\": \"0.0.0.0/0\"\n                    },\n                    \"id\": 10331\n                },\n                {\n                    \"from_port\": 22,\n                    \"group\": {\n                        \"tenant_id\": \"37936628937291\",\n                        \"name\": \"jclouds_mygroup\"\n                    },\n                    \"ip_protocol\": \"tcp\",\n                    \"to_port\": 22,\n                    \"parent_group_id\": 2769,\n                    \"ip_range\": {},\n                    \"id\": 10332\n                },\n                {\n                    \"from_port\": 8080,\n                    \"group\": {},\n                    \"ip_protocol\": \"tcp\",\n                    \"to_port\": 8080,\n                    \"parent_group_id\": 2769,\n                    \"ip_range\": {\n                        \"cidr\": \"0.0.0.0/0\"\n                    },\n                    \"id\": 10333\n                },\n                {\n                    \"from_port\": 8080,\n                    \"group\": {\n                        \"tenant_id\": \"37936628937291\",\n                        \"name\": \"jclouds_mygroup\"\n                    },\n                    \"ip_protocol\": \"tcp\",\n                    \"to_port\": 8080,\n                    \"parent_group_id\": 2769,\n                    \"ip_range\": {},\n                    \"id\": 10334\n                }\n            ],\n            \"tenant_id\": \"37936628937291\",\n            \"id\": 2769,\n            \"name\": \"jclouds_mygroup\",\n            \"description\": \"jclouds_mygroup\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/securitygroup_list_extension.json",
    "content": "{\n    \"security_groups\": [\n        {\n            \"rules\": [\n                {\n                    \"from_port\": 22,\n                    \"group\": {},\n                    \"ip_protocol\": \"tcp\",\n                    \"to_port\": 22,\n                    \"parent_group_id\": 3,\n                    \"ip_range\": {\n                        \"cidr\": \"0.0.0.0/0\"\n                    },\n                    \"id\": 107\n                },\n                {\n                    \"from_port\": 7600,\n                    \"group\": {},\n                    \"ip_protocol\": \"tcp\",\n                    \"to_port\": 7600,\n                    \"parent_group_id\": 3,\n                    \"ip_range\": {\n                        \"cidr\": \"0.0.0.0/0\"\n                    },\n                    \"id\": 118\n                },\n                {\n                    \"from_port\": 8084,\n                    \"group\": {},\n                    \"ip_protocol\": \"tcp\",\n                    \"to_port\": 8084,\n                    \"parent_group_id\": 3,\n                    \"ip_range\": {\n                        \"cidr\": \"0.0.0.0/0\"\n                    },\n                    \"id\": 119\n                }\n            ],\n            \"tenant_id\": \"tenant0\",\n            \"id\": 160,\n            \"name\": \"name0\",\n            \"description\": \"description0\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/securitygrouprule_created.json",
    "content": "{\n    \"security_group_rule\": {\n        \"from_port\": 80,\n        \"group\": {},\n        \"ip_protocol\": \"tcp\",\n        \"to_port\": 8080,\n        \"parent_group_id\": 161,\n        \"ip_range\": {\n            \"cidr\": \"0.0.0.0/0\"\n        },\n        \"id\": 218\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/securitygrouprule_created_cidr.json",
    "content": "{\n    \"security_group_rule\": {\n        \"from_port\": 22,\n        \"group\": {},\n        \"ip_protocol\": \"tcp\",\n        \"to_port\": 22,\n        \"parent_group_id\": 160,\n        \"ip_range\": {\n            \"cidr\": \"10.2.6.0/24\"\n        },\n        \"id\": 108\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/securitygrouprule_created_group.json",
    "content": "{\n    \"security_group_rule\": {\n        \"from_port\": 22,\n        \"group\": {\n            \"tenant_id\": \"admin\",\n            \"name\": \"11111\"\n        },\n        \"ip_protocol\": \"tcp\",\n        \"to_port\": 22,\n        \"parent_group_id\": 160,\n        \"ip_range\": {},\n        \"id\": 109\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/server_details.json",
    "content": "{\n    \"server\": {\n        \"id\": \"71752\",\n        \"tenant_id\": \"1234\",\n        \"user_id\": \"5678\",\n        \"name\": \"sample-f352\",\n        \"updated\": \"2010-10-10T12:00:00Z\",\n        \"created\": \"2010-08-10T12:00:00Z\",\n        \"hostId\": \"e4d909c290d0fb1ca068ffaddf22cbd0\",\n        \"accessIPv4\": \"67.23.10.132\",\n        \"accessIPv6\": \"::babe:67.23.10.132\",\n        \"status\": \"ACTIVE\",\n        \"progress\": 60,\n        \"OS-DCF:diskConfig\": \"AUTO\",\n        \"OS-EXT-AZ:availability_zone\": \"nova\",\n        \"image\": {\n            \"id\": \"52415800-8b69-11e0-9b19-734f6f006e54\",\n            \"links\": [\n                {\n                    \"rel\": \"self\",\n                    \"href\": \"http://servers.api.openstack.org/v2/1234/images/52415800-8b69-11e0-9b19-734f6f006e54\"\n                },\n                {\n                    \"rel\": \"bookmark\",\n                    \"href\": \"http://servers.api.openstack.org/1234/images/52415800-8b69-11e0-9b19-734f6f006e54\"\n                }\n            ]\n        },\n        \"flavor\": {\n            \"id\": \"52415800-8b69-11e0-9b19-734f216543fd\",\n            \"links\": [\n                {\n                    \"rel\": \"self\",\n                    \"href\": \"http://servers.api.openstack.org/v2/1234/flavors/52415800-8b69-11e0-9b19-734f216543fd\"\n                },\n                {\n                    \"rel\": \"bookmark\",\n                    \"href\": \"http://servers.api.openstack.org/1234/flavors/52415800-8b69-11e0-9b19-734f216543fd\"\n                }\n            ]\n        },\n        \"addresses\": {\n            \"public\": [\n                {\n                    \"version\": 4,\n                    \"addr\": \"67.23.10.132\"\n                },\n                {\n                    \"version\": 6,\n                    \"addr\": \"::babe:67.23.10.132\"\n                },\n                {\n                    \"version\": 4,\n                    \"addr\": \"67.23.10.131\"\n                },\n                {\n                    \"version\": 6,\n                    \"addr\": \"::babe:4317:0A83\"\n                }\n            ],\n            \"private\": [\n                {\n                    \"version\": 4,\n                    \"addr\": \"10.176.42.16\"\n                },\n                {\n                    \"version\": 6,\n                    \"addr\": \"::babe:10.176.42.16\"\n                }\n            ]\n        },\n        \"metadata\": {\n            \"Server Label\": \"Web Head 1\",\n            \"Image Version\": \"2.1\"\n        },\n        \"links\": [\n            {\n                \"rel\": \"self\",\n                \"href\": \"http://servers.api.openstack.org/v2/1234/servers/71752\"\n            },\n            {\n                \"rel\": \"bookmark\",\n                \"href\": \"http://servers.api.openstack.org/1234/servers/71752\"\n            }\n        ]\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/server_details_devstack.json",
    "content": "{\n    \"server\": {\n        \"OS-EXT-STS:task_state\": null,\n        \"addresses\": {\n            \"private\": [\n                {\n                    \"version\": 4,\n                    \"addr\": \"10.0.0.8\"\n                }\n            ]\n        },\n        \"links\": [\n            {\n                \"href\": \"http://172.16.89.149:8774/v2/7f312675f9b84c97bff8f5054e181419/servers/141b775f-7ac1-45f0-9a95-146260f33a53\",\n                \"rel\": \"self\"\n            },\n            {\n                \"href\": \"http://172.16.89.149:8774/7f312675f9b84c97bff8f5054e181419/servers/141b775f-7ac1-45f0-9a95-146260f33a53\",\n                \"rel\": \"bookmark\"\n            }\n        ],\n        \"image\": {\n            \"id\": \"8e6f5bc4-a210-45b2-841f-c510eae14300\",\n            \"links\": [\n                {\n                    \"href\": \"http://172.16.89.149:8774/7f312675f9b84c97bff8f5054e181419/images/8e6f5bc4-a210-45b2-841f-c510eae14300\",\n                    \"rel\": \"bookmark\"\n                }\n            ]\n        },\n        \"OS-EXT-STS:vm_state\": \"paused\",\n        \"OS-EXT-SRV-ATTR:instance_name\": \"instance-00000014\",\n        \"flavor\": {\n            \"id\": \"1\",\n            \"links\": [\n                {\n                    \"href\": \"http://172.16.89.149:8774/7f312675f9b84c97bff8f5054e181419/flavors/1\",\n                    \"rel\": \"bookmark\"\n                }\n            ]\n        },\n        \"id\": \"141b775f-7ac1-45f0-9a95-146260f33a53\",\n        \"user_id\": \"89c01b67395d4bea945f7f5bfd7f344a\",\n        \"OS-DCF:diskConfig\": \"MANUAL\",\n        \"accessIPv4\": \"\",\n        \"accessIPv6\": \"\",\n        \"OS-EXT-STS:power_state\": 3,\n        \"config_drive\": \"\",\n        \"status\": \"PAUSED\",\n        \"updated\": \"2012-05-04T15:07:48Z\",\n        \"hostId\": \"eab9a77d1c44b8833e4a3dc6d2d9d50de556e780a319f184d8c82d9b\",\n        \"OS-EXT-SRV-ATTR:host\": \"ubuntu\",\n        \"key_name\": \"\",\n        \"OS-EXT-SRV-ATTR:hypervisor_hostname\": null,\n        \"name\": \"test\",\n        \"created\": \"2012-05-04T15:07:36Z\",\n        \"tenant_id\": \"7f312675f9b84c97bff8f5054e181419\",\n        \"metadata\": {}\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/server_details_openstack.json",
    "content": "{\n    \"server\": {\n        \"status\": \"ACTIVE\",\n        \"updated\": \"2012-03-23T01:30:26Z\",\n        \"hostId\": \"881706597197955ac7cc4b353bc7ec884e13fa280de9cc82057796cb\",\n        \"user_id\": \"508151008\",\n        \"name\": \"mygroup-72c\",\n        \"links\": [\n            {\n                \"href\": \"https://nova-api.openstack.org:9774/v2/37/servers/1459\",\n                \"rel\": \"self\"\n            },\n            {\n                \"href\": \"https://nova-api.openstack.org:9774/37/servers/1459\",\n                \"rel\": \"bookmark\"\n            }\n        ],\n        \"addresses\": {\n            \"internet\": [\n                {\n                    \"version\": 4,\n                    \"addr\": \"8.21.28.47\"\n                }\n            ]\n        },\n        \"tenant_id\": \"37\",\n        \"image\": {\n            \"id\": \"14\",\n            \"links\": [\n                {\n                    \"href\": \"https://nova-api.openstack.org:9774/37/images/14\",\n                    \"rel\": \"bookmark\"\n                }\n            ]\n        },\n        \"created\": \"2012-03-23T01:30:26Z\",\n        \"uuid\": \"2443c9c7-9791-412e-ac09-a6d55ec25335\",\n        \"accessIPv4\": \"\",\n        \"accessIPv6\": \"\",\n        \"key_name\": null,\n        \"progress\": 100,\n        \"flavor\": {\n            \"id\": \"1\",\n            \"links\": [\n                {\n                    \"href\": \"https://nova-api.openstack.org:9774/37/flavors/1\",\n                    \"rel\": \"bookmark\"\n                }\n            ]\n        },\n        \"config_drive\": \"\",\n        \"id\": 1459,\n        \"metadata\": {}\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/server_details_suspended.json",
    "content": "{\n    \"server\": {\n        \"id\": \"71752\",\n        \"tenant_id\": \"1234\",\n        \"user_id\": \"5678\",\n        \"name\": \"sample-f352\",\n        \"updated\": \"2010-10-10T12:00:00Z\",\n        \"created\": \"2010-08-10T12:00:00Z\",\n        \"hostId\": \"e4d909c290d0fb1ca068ffaddf22cbd0\",\n        \"accessIPv4\": \"67.23.10.132\",\n        \"accessIPv6\": \"::babe:67.23.10.132\",\n        \"status\": \"SUSPENDED\",\n        \"progress\": 60,\n        \"OS-DCF:diskConfig\": \"AUTO\",\n        \"OS-EXT-AZ:availability_zone\": \"nova\",\n        \"image\": {\n            \"id\": \"52415800-8b69-11e0-9b19-734f6f006e54\",\n            \"links\": [\n                {\n                    \"rel\": \"self\",\n                    \"href\": \"http://servers.api.openstack.org/v2/1234/images/52415800-8b69-11e0-9b19-734f6f006e54\"\n                },\n                {\n                    \"rel\": \"bookmark\",\n                    \"href\": \"http://servers.api.openstack.org/1234/images/52415800-8b69-11e0-9b19-734f6f006e54\"\n                }\n            ]\n        },\n        \"flavor\": {\n            \"id\": \"52415800-8b69-11e0-9b19-734f216543fd\",\n            \"links\": [\n                {\n                    \"rel\": \"self\",\n                    \"href\": \"http://servers.api.openstack.org/v2/1234/flavors/52415800-8b69-11e0-9b19-734f216543fd\"\n                },\n                {\n                    \"rel\": \"bookmark\",\n                    \"href\": \"http://servers.api.openstack.org/1234/flavors/52415800-8b69-11e0-9b19-734f216543fd\"\n                }\n            ]\n        },\n        \"addresses\": {\n            \"public\": [\n                {\n                    \"version\": 4,\n                    \"addr\": \"67.23.10.132\"\n                },\n                {\n                    \"version\": 6,\n                    \"addr\": \"::babe:67.23.10.132\"\n                },\n                {\n                    \"version\": 4,\n                    \"addr\": \"67.23.10.131\"\n                },\n                {\n                    \"version\": 6,\n                    \"addr\": \"::babe:4317:0A83\"\n                }\n            ],\n            \"private\": [\n                {\n                    \"version\": 4,\n                    \"addr\": \"10.176.42.16\"\n                },\n                {\n                    \"version\": 6,\n                    \"addr\": \"::babe:10.176.42.16\"\n                }\n            ]\n        },\n        \"metadata\": {\n            \"Server Label\": \"Web Head 1\",\n            \"Image Version\": \"2.1\"\n        },\n        \"links\": [\n            {\n                \"rel\": \"self\",\n                \"href\": \"http://servers.api.openstack.org/v2/1234/servers/71752\"\n            },\n            {\n                \"rel\": \"bookmark\",\n                \"href\": \"http://servers.api.openstack.org/1234/servers/71752\"\n            }\n        ]\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/server_details_with_address_ext.json",
    "content": "{\n    \"server\": {\n        \"OS-DCF:diskConfig\": \"MANUAL\",\n        \"OS-EXT-AZ:availability_zone\": \"nova\",\n        \"OS-EXT-STS:power_state\": 1,\n        \"OS-EXT-STS:task_state\": null,\n        \"OS-EXT-STS:vm_state\": \"active\",\n        \"OS-SRV-USG:launched_at\": \"2016-02-17T14:48:00.000000\",\n        \"OS-SRV-USG:terminated_at\": null,\n        \"accessIPv4\": \"\",\n        \"accessIPv6\": \"\",\n        \"addresses\": {\n            \"jenkins\": [\n                {\n                    \"OS-EXT-IPS-MAC:mac_addr\": \"fa:16:3e:bf:82:43\",\n                    \"OS-EXT-IPS:type\": \"fixed\",\n                    \"addr\": \"172.16.130.24\",\n                    \"version\": 4\n                },\n                {\n                    \"OS-EXT-IPS-MAC:mac_addr\": \"fa:16:3e:bf:82:43\",\n                    \"OS-EXT-IPS:type\": \"floating\",\n                    \"addr\": \"10.8.54.75\",\n                    \"version\": 4\n                }\n            ]\n        },\n        \"config_drive\": \"\",\n        \"created\": \"2016-02-17T14:46:13Z\",\n        \"flavor\": {\n            \"id\": \"3\",\n            \"links\": [\n                {\n                    \"href\": \"http://openstack:8774/cac29c920a6149aabe499757b6ba81c7/flavors/3\",\n                    \"rel\": \"bookmark\"\n                }\n            ]\n        },\n        \"hostId\": \"18a9cd55f76c520dcad6c31d5b2b8f4c921979629c0274c0f7d2de39\",\n        \"id\": \"0bdc3a8d-3a96-4ccc-bb40-715537a7df7b\",\n        \"image\": {\n            \"id\": \"9a9f496a-f5c2-4286-81a4-98189a48777a\",\n            \"links\": [\n                {\n                    \"href\": \"http://openstack:8774/cac29c920a6149aabe499757b6ba81c7/images/9a9f496a-f5c2-4286-81a4-98189a48777a\",\n                    \"rel\": \"bookmark\"\n                }\n            ]\n        },\n        \"key_name\": \"jenkins\",\n        \"links\": [\n            {\n                \"href\": \"http://openstack:8774/v2/cac29c920a6149aabe499757b6ba81c7/servers/0bdc3a8d-3a96-4ccc-bb40-715537a7df7b\",\n                \"rel\": \"self\"\n            },\n            {\n                \"href\": \"http://openstack:8774/cac29c920a6149aabe499757b6ba81c7/servers/0bdc3a8d-3a96-4ccc-bb40-715537a7df7b\",\n                \"rel\": \"bookmark\"\n            }\n        ],\n        \"metadata\": {\n            \"jclouds-group\": \"cloudts\"\n        },\n        \"name\": \"cloudts-f07\",\n        \"os-extended-volumes:volumes_attached\": [],\n        \"progress\": 0,\n        \"security_groups\": [\n            {\n                \"name\": \"allow-all\"\n            }\n        ],\n        \"status\": \"ACTIVE\",\n        \"tenant_id\": \"cac29c920a6149aabe499757b6ba81c7\",\n        \"updated\": \"2016-02-17T14:48:00Z\",\n        \"user_id\": \"ed15e338032f4a2c85b7fa80e40b9917\"\n    }\n}"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/server_details_without_image.json",
    "content": "{\n    \"server\": {\n        \"id\": \"71752\",\n        \"tenant_id\": \"1234\",\n        \"user_id\": \"5678\",\n        \"name\": \"sample-f352\",\n        \"updated\": \"2010-10-10T12:00:00Z\",\n        \"created\": \"2010-08-10T12:00:00Z\",\n        \"hostId\": \"e4d909c290d0fb1ca068ffaddf22cbd0\",\n        \"accessIPv4\" : \"67.23.10.132\",\n        \"accessIPv6\" : \"::babe:67.23.10.132\",\n        \"status\": \"BUILD(scheduling)\",\n        \"progress\": 60,\n        \"OS-DCF:diskConfig\": \"AUTO\",\n        \"image\" : \"\",\n        \"flavor\" : {\n            \"id\": \"52415800-8b69-11e0-9b19-734f216543fd\",\n            \"links\": [\n                {\n                    \"rel\": \"self\",\n                    \"href\": \"http://servers.api.openstack.org/v1.1/1234/flavors/52415800-8b69-11e0-9b19-734f216543fd\"\n                },\n                {\n                    \"rel\": \"bookmark\",\n                    \"href\": \"http://servers.api.openstack.org/1234/flavors/52415800-8b69-11e0-9b19-734f216543fd\"\n                }\n            ]\n        },\n        \"addresses\":  {\n            \"public\" : [\n                {\n                    \"version\": 4,\n                    \"addr\": \"67.23.10.132\"\n                },\n                {\n                    \"version\": 6,\n                    \"addr\": \"::babe:67.23.10.132\"\n                },\n                {\n                    \"version\": 4,\n                    \"addr\": \"67.23.10.131\"\n                },\n                {\n                    \"version\": 6,\n                    \"addr\": \"::babe:4317:0A83\"\n                }\n            ],\n            \"private\" : [\n                {\n                    \"version\": 4,\n                    \"addr\": \"10.176.42.16\"\n                },\n                {\n                    \"version\": 6,\n                    \"addr\": \"::babe:10.176.42.16\"\n                }\n            ]\n        },\n        \"metadata\": {\n            \"Server Label\": \"Web Head 1\",\n            \"Image Version\": \"2.1\"\n        },\n        \"links\": [\n           {\n               \"rel\": \"self\",\n               \"href\": \"http://servers.api.openstack.org/v2/1234/servers/71752\"\n           },\n           {\n               \"rel\": \"bookmark\",\n               \"href\": \"http://servers.api.openstack.org/1234/servers/71752\"\n           }\n       ]\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/server_diagnostics.json",
    "content": "{\n    \"vnet0_tx_errors\": 0,\n    \"vda_read\": 77364736,\n    \"vda_write\": 415446016,\n    \"vnet0_tx_packets\": 9701,\n    \"vda_write_req\": 47278,\n    \"cpu0_time\": 143150000000,\n    \"vnet0_tx\": 1691221,\n    \"vnet0_rx_drop\": 0,\n    \"vda_errors\": -1,\n    \"vnet0_rx_errors\": 0,\n    \"memory\": 524288,\n    \"vnet0_rx_packets\": 11271,\n    \"vda_read_req\": 9551,\n    \"vnet0_rx\": 1805288,\n    \"vnet0_tx_drop\": 0\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/server_list.json",
    "content": "{\n    \"servers\": [\n        {\n            \"id\": \"52415800-8b69-11e0-9b19-734f6af67565\",\n            \"name\": \"sample-server\",\n            \"links\": [\n                {\n                    \"rel\": \"self\",\n                    \"href\": \"http://servers.api.openstack.org/v2/1234/servers/52415800-8b69-11e0-9b19-734f6af67565\"\n                },\n                {\n                    \"rel\": \"bookmark\",\n                    \"href\": \"http://servers.api.openstack.org/1234/servers/52415800-8b69-11e0-9b19-734f6af67565\"\n                }\n            ]\n        },\n        {\n            \"id\": \"52415800-8b69-11e0-9b19-734f1f1350e5\",\n            \"name\": \"sample-server2\",\n            \"links\": [\n                {\n                    \"rel\": \"self\",\n                    \"href\": \"http://servers.api.openstack.org/v2/1234/servers/52415800-8b69-11e0-9b19-734f1f1350e5\"\n                },\n                {\n                    \"rel\": \"bookmark\",\n                    \"href\": \"http://servers.api.openstack.org/1234/servers/52415800-8b69-11e0-9b19-734f1f1350e5\"\n                }\n            ]\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/server_list_details.json",
    "content": "{\n    \"servers\": [\n        {\n            \"id\": \"71752\",\n            \"tenant_id\": \"1234\",\n            \"user_id\": \"5678\",\n            \"name\": \"sample-server\",\n            \"updated\": \"2010-10-10T12:00:00Z\",\n            \"created\": \"2010-08-10T12:00:00Z\",\n            \"hostId\": \"e4d909c290d0fb1ca068ffaddf22cbd0\",\n            \"accessIPv4\": \"67.23.10.132\",\n            \"accessIPv6\": \"::babe:67.23.10.132\",\n            \"status\": \"BUILD\",\n            \"progress\": 60,\n            \"image\": {\n                \"id\": \"52415800-8b69-11e0-9b19-734f6f006e54\",\n                \"links\": [\n                    {\n                        \"rel\": \"self\",\n                        \"href\": \"http://servers.api.openstack.org/v2/1234/images/52415800-8b69-11e0-9b19-734f6f006e54\"\n                    },\n                    {\n                        \"rel\": \"bookmark\",\n                        \"href\": \"http://servers.api.openstack.org/1234/images/52415800-8b69-11e0-9b19-734f6f006e54\"\n                    }\n                ]\n            },\n            \"flavor\": {\n                \"id\": \"52415800-8b69-11e0-9b19-734f216543fd\",\n                \"links\": [\n                    {\n                        \"rel\": \"self\",\n                        \"href\": \"http://servers.api.openstack.org/v2/1234/flavors/52415800-8b69-11e0-9b19-734f216543fd\"\n                    },\n                    {\n                        \"rel\": \"bookmark\",\n                        \"href\": \"http://servers.api.openstack.org/1234/flavors/52415800-8b69-11e0-9b19-734f216543fd\"\n                    }\n                ]\n            },\n            \"addresses\": {\n                \"public\": [\n                    {\n                        \"version\": 4,\n                        \"addr\": \"67.23.10.132\"\n                    },\n                    {\n                        \"version\": 6,\n                        \"addr\": \"::babe:67.23.10.132\"\n                    },\n                    {\n                        \"version\": 4,\n                        \"addr\": \"67.23.10.131\"\n                    },\n                    {\n                        \"version\": 6,\n                        \"addr\": \"::babe:4317:0A83\"\n                    }\n                ],\n                \"private\": [\n                    {\n                        \"version\": 4,\n                        \"addr\": \"10.176.42.16\"\n                    },\n                    {\n                        \"version\": 6,\n                        \"addr\": \"::babe:10.176.42.16\"\n                    }\n                ]\n            },\n            \"metadata\": {\n                \"Server Label\": \"Web Head 1\",\n                \"Image Version\": \"2.1\"\n            },\n            \"links\": []\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/server_list_details_essex.json",
    "content": "{\n    \"servers\": [\n        {\n            \"OS-EXT-STS:task_state\": null,\n            \"addresses\": {\n                \"Net TenantA Front-Middle\": [\n                    {\n                        \"version\": 4,\n                        \"addr\": \"172.16.11.5\"\n                    }\n                ],\n                \"Public network\": [\n                    {\n                        \"version\": 4,\n                        \"addr\": \"172.16.1.13\"\n                    },\n                    {\n                        \"version\": 4,\n                        \"addr\": \"10.193.112.119\"\n                    }\n                ]\n            },\n            \"links\": [\n                {\n                    \"href\": \"http://nova:8774/v2/8d10e6646d5d4585937395b04839a353/servers/0c80b392-db30-4736-ae02-4480090f1207\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"http://nova:8774/8d10e6646d5d4585937395b04839a353/servers/0c80b392-db30-4736-ae02-4480090f1207\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"image\": {\n                \"id\": \"416af940-2d3c-4a7c-977c-a9030685ad5e\",\n                \"links\": [\n                    {\n                        \"href\": \"http://nova:8774/8d10e6646d5d4585937395b04839a353/images/416af940-2d3c-4a7c-977c-a9030685ad5e\",\n                        \"rel\": \"bookmark\"\n                    }\n                ]\n            },\n            \"OS-EXT-STS:vm_state\": \"active\",\n            \"flavor\": {\n                \"id\": \"1\",\n                \"links\": [\n                    {\n                        \"href\": \"http://nova:8774/8d10e6646d5d4585937395b04839a353/flavors/1\",\n                        \"rel\": \"bookmark\"\n                    }\n                ]\n            },\n            \"id\": \"0c80b392-db30-4736-ae02-4480090f1207\",\n            \"user_id\": \"df13814f6c354d00a8acf66502836323\",\n            \"OS-DCF:diskConfig\": \"MANUAL\",\n            \"accessIPv4\": \"\",\n            \"accessIPv6\": \"\",\n            \"progress\": 0,\n            \"OS-EXT-STS:power_state\": 1,\n            \"config_drive\": \"\",\n            \"status\": \"ACTIVE\",\n            \"updated\": \"2012-04-12T11:21:33Z\",\n            \"hostId\": \"03d796ebb52b1b555e5f6d9262f7dbd52b3f7c181e3aa89b34ca5408\",\n            \"key_name\": \"\",\n            \"name\": \"VM proxy\",\n            \"created\": \"2012-04-12T11:21:23Z\",\n            \"tenant_id\": \"8d10e6646d5d4585937395b04839a353\",\n            \"metadata\": {}\n        },\n        {\n            \"OS-EXT-STS:task_state\": null,\n            \"addresses\": {\n                \"Net TenantA Front-Middle\": [\n                    {\n                        \"version\": 4,\n                        \"addr\": \"172.16.11.4\"\n                    }\n                ],\n                \"Net TenantA Middle-Back\": [\n                    {\n                        \"version\": 4,\n                        \"addr\": \"172.16.12.5\"\n                    }\n                ]\n            },\n            \"links\": [\n                {\n                    \"href\": \"http://nova:8774/v2/8d10e6646d5d4585937395b04839a353/servers/b332b5cd-535e-4677-b68e-fc8badc13236\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"http://nova:8774/8d10e6646d5d4585937395b04839a353/servers/b332b5cd-535e-4677-b68e-fc8badc13236\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"image\": {\n                \"id\": \"416af940-2d3c-4a7c-977c-a9030685ad5e\",\n                \"links\": [\n                    {\n                        \"href\": \"http://nova:8774/8d10e6646d5d4585937395b04839a353/images/416af940-2d3c-4a7c-977c-a9030685ad5e\",\n                        \"rel\": \"bookmark\"\n                    }\n                ]\n            },\n            \"OS-EXT-STS:vm_state\": \"active\",\n            \"flavor\": {\n                \"id\": \"1\",\n                \"links\": [\n                    {\n                        \"href\": \"http://nova:8774/8d10e6646d5d4585937395b04839a353/flavors/1\",\n                        \"rel\": \"bookmark\"\n                    }\n                ]\n            },\n            \"id\": \"b332b5cd-535e-4677-b68e-fc8badc13236\",\n            \"user_id\": \"df13814f6c354d00a8acf66502836323\",\n            \"OS-DCF:diskConfig\": \"MANUAL\",\n            \"accessIPv4\": \"\",\n            \"accessIPv6\": \"\",\n            \"progress\": 0,\n            \"OS-EXT-STS:power_state\": 1,\n            \"config_drive\": \"\",\n            \"status\": \"ACTIVE\",\n            \"updated\": \"2012-04-12T11:18:58Z\",\n            \"hostId\": \"e5bbff80bebacfe1db63951e787b5341427060a602d33abfefb6a1bc\",\n            \"key_name\": \"\",\n            \"name\": \"VM blog\",\n            \"created\": \"2012-04-12T11:18:48Z\",\n            \"tenant_id\": \"8d10e6646d5d4585937395b04839a353\",\n            \"metadata\": {}\n        },\n        {\n            \"OS-EXT-STS:task_state\": null,\n            \"addresses\": {\n                \"Net TenantA Middle-Back\": [\n                    {\n                        \"version\": 4,\n                        \"addr\": \"172.16.12.4\"\n                    }\n                ]\n            },\n            \"links\": [\n                {\n                    \"href\": \"http://nova:8774/v2/8d10e6646d5d4585937395b04839a353/servers/f9d43436-4572-4c9b-9b74-5fa6890a2f21\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"http://nova:8774/8d10e6646d5d4585937395b04839a353/servers/f9d43436-4572-4c9b-9b74-5fa6890a2f21\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"image\": {\n                \"id\": \"416af940-2d3c-4a7c-977c-a9030685ad5e\",\n                \"links\": [\n                    {\n                        \"href\": \"http://nova:8774/8d10e6646d5d4585937395b04839a353/images/416af940-2d3c-4a7c-977c-a9030685ad5e\",\n                        \"rel\": \"bookmark\"\n                    }\n                ]\n            },\n            \"OS-EXT-STS:vm_state\": \"active\",\n            \"flavor\": {\n                \"id\": \"1\",\n                \"links\": [\n                    {\n                        \"href\": \"http://nova:8774/8d10e6646d5d4585937395b04839a353/flavors/1\",\n                        \"rel\": \"bookmark\"\n                    }\n                ]\n            },\n            \"id\": \"f9d43436-4572-4c9b-9b74-5fa6890a2f21\",\n            \"user_id\": \"df13814f6c354d00a8acf66502836323\",\n            \"OS-DCF:diskConfig\": \"MANUAL\",\n            \"accessIPv4\": \"\",\n            \"accessIPv6\": \"\",\n            \"progress\": 0,\n            \"OS-EXT-STS:power_state\": 1,\n            \"config_drive\": \"\",\n            \"status\": \"ACTIVE\",\n            \"updated\": \"2012-04-12T11:15:09Z\",\n            \"hostId\": \"03d796ebb52b1b555e5f6d9262f7dbd52b3f7c181e3aa89b34ca5408\",\n            \"key_name\": \"\",\n            \"name\": \"VM MySQL\",\n            \"created\": \"2012-04-12T11:14:56Z\",\n            \"tenant_id\": \"8d10e6646d5d4585937395b04839a353\",\n            \"metadata\": {}\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/server_list_details_states.json",
    "content": "{\n    \"servers\": [\n        {\n            \"OS-DCF:diskConfig\": \"MANUAL\",\n            \"OS-EXT-AZ:availability_zone\": \"nova\",\n            \"OS-EXT-SRV-ATTR:host\": \"rdohavana.localdomain\",\n            \"OS-EXT-SRV-ATTR:hypervisor_hostname\": \"rdohavana.localdomain\",\n            \"OS-EXT-SRV-ATTR:instance_name\": \"instance-0000000b\",\n            \"OS-EXT-STS:power_state\": 0,\n            \"OS-EXT-STS:task_state\": \"spawning\",\n            \"OS-EXT-STS:vm_state\": \"building\",\n            \"OS-SRV-USG:launched_at\": null,\n            \"OS-SRV-USG:terminated_at\": null,\n            \"accessIPv4\": \"\",\n            \"accessIPv6\": \"\",\n            \"addresses\": {},\n            \"config_drive\": \"\",\n            \"created\": \"2014-03-19T11:54:57Z\",\n            \"flavor\": {\n                \"id\": \"6\",\n                \"links\": [\n                    {\n                        \"href\": \"http://openstack:8774/4e1900cf21924a098709c23480e157c0/flavors/6\",\n                        \"rel\": \"bookmark\"\n                    }\n                ]\n            },\n            \"hostId\": \"0bc453b1c10348e9dc398fed7a5b06f996964ae1643fe460a85a23d8\",\n            \"id\": \"56d51a88-0066-4976-91b6-d1b453be603f\",\n            \"image\": {\n                \"id\": \"e3f84189-964e-4dc3-8ac6-832c2b7553d4\",\n                \"links\": [\n                    {\n                        \"href\": \"http://openstack:8774/4e1900cf21924a098709c23480e157c0/images/e3f84189-964e-4dc3-8ac6-832c2b7553d4\",\n                        \"rel\": \"bookmark\"\n                    }\n                ]\n            },\n            \"key_name\": null,\n            \"links\": [\n                {\n                    \"href\": \"http://openstack:8774/v2/4e1900cf21924a098709c23480e157c0/servers/56d51a88-0066-4976-91b6-d1b453be603f\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"http://openstack:8774/4e1900cf21924a098709c23480e157c0/servers/56d51a88-0066-4976-91b6-d1b453be603f\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"metadata\": {},\n            \"name\": \"machine_5\",\n            \"os-extended-volumes:volumes_attached\": [],\n            \"progress\": 0,\n            \"security_groups\": [\n                {\n                    \"name\": \"default\"\n                }\n            ],\n            \"status\": \"BUILD\",\n            \"tenant_id\": \"4e1900cf21924a098709c23480e157c0\",\n            \"updated\": \"2014-03-19T11:54:59Z\",\n            \"user_id\": \"08ba127f0d6842279f9db8e8bc6977e9\"\n        },\n        {\n            \"OS-DCF:diskConfig\": \"MANUAL\",\n            \"OS-EXT-AZ:availability_zone\": \"nova\",\n            \"OS-EXT-SRV-ATTR:host\": \"rdohavana.localdomain\",\n            \"OS-EXT-SRV-ATTR:hypervisor_hostname\": \"rdohavana.localdomain\",\n            \"OS-EXT-SRV-ATTR:instance_name\": \"instance-00000009\",\n            \"OS-EXT-STS:power_state\": 1,\n            \"OS-EXT-STS:task_state\": null,\n            \"OS-EXT-STS:vm_state\": \"active\",\n            \"OS-SRV-USG:launched_at\": \"2014-03-19T11:52:21.000000\",\n            \"OS-SRV-USG:terminated_at\": null,\n            \"accessIPv4\": \"\",\n            \"accessIPv6\": \"\",\n            \"addresses\": {\n                \"public\": [\n                    {\n                        \"OS-EXT-IPS-MAC:mac_addr\": \"fa:16:3e:df:22:1b\",\n                        \"OS-EXT-IPS:type\": \"fixed\",\n                        \"addr\": \"172.24.4.232\",\n                        \"version\": 4\n                    }\n                ]\n            },\n            \"config_drive\": \"\",\n            \"created\": \"2014-03-19T11:51:53Z\",\n            \"flavor\": {\n                \"id\": \"6\",\n                \"links\": [\n                    {\n                        \"href\": \"http://openstack:8774/4e1900cf21924a098709c23480e157c0/flavors/6\",\n                        \"rel\": \"bookmark\"\n                    }\n                ]\n            },\n            \"hostId\": \"0bc453b1c10348e9dc398fed7a5b06f996964ae1643fe460a85a23d8\",\n            \"id\": \"3bc8ab03-52e7-4d2b-ba88-73f9ecadf003\",\n            \"image\": {\n                \"id\": \"e3f84189-964e-4dc3-8ac6-832c2b7553d4\",\n                \"links\": [\n                    {\n                        \"href\": \"http://openstack:8774/4e1900cf21924a098709c23480e157c0/images/e3f84189-964e-4dc3-8ac6-832c2b7553d4\",\n                        \"rel\": \"bookmark\"\n                    }\n                ]\n            },\n            \"key_name\": null,\n            \"links\": [\n                {\n                    \"href\": \"http://openstack:8774/v2/4e1900cf21924a098709c23480e157c0/servers/3bc8ab03-52e7-4d2b-ba88-73f9ecadf003\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"http://openstack:8774/4e1900cf21924a098709c23480e157c0/servers/3bc8ab03-52e7-4d2b-ba88-73f9ecadf003\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"metadata\": {},\n            \"name\": \"machine_4\",\n            \"os-extended-volumes:volumes_attached\": [],\n            \"progress\": 0,\n            \"security_groups\": [\n                {\n                    \"name\": \"default\"\n                }\n            ],\n            \"status\": \"ACTIVE\",\n            \"tenant_id\": \"4e1900cf21924a098709c23480e157c0\",\n            \"updated\": \"2014-03-19T11:52:21Z\",\n            \"user_id\": \"08ba127f0d6842279f9db8e8bc6977e9\"\n        },\n        {\n            \"OS-DCF:diskConfig\": \"MANUAL\",\n            \"OS-EXT-AZ:availability_zone\": \"nova\",\n            \"OS-EXT-SRV-ATTR:host\": null,\n            \"OS-EXT-SRV-ATTR:hypervisor_hostname\": null,\n            \"OS-EXT-SRV-ATTR:instance_name\": \"instance-00000006\",\n            \"OS-EXT-STS:power_state\": 4,\n            \"OS-EXT-STS:task_state\": null,\n            \"OS-EXT-STS:vm_state\": \"shelved_offloaded\",\n            \"OS-SRV-USG:launched_at\": \"2014-03-19T11:33:52.000000\",\n            \"OS-SRV-USG:terminated_at\": null,\n            \"accessIPv4\": \"\",\n            \"accessIPv6\": \"\",\n            \"addresses\": {\n                \"public\": [\n                    {\n                        \"OS-EXT-IPS-MAC:mac_addr\": \"fa:16:3e:cb:56:d6\",\n                        \"OS-EXT-IPS:type\": \"fixed\",\n                        \"addr\": \"172.24.4.229\",\n                        \"version\": 4\n                    }\n                ]\n            },\n            \"config_drive\": \"\",\n            \"created\": \"2014-03-19T11:33:27Z\",\n            \"flavor\": {\n                \"id\": \"6\",\n                \"links\": [\n                    {\n                        \"href\": \"http://openstack:8774/4e1900cf21924a098709c23480e157c0/flavors/6\",\n                        \"rel\": \"bookmark\"\n                    }\n                ]\n            },\n            \"hostId\": \"\",\n            \"id\": \"cad76945-8851-489a-99e1-f1049e02c769\",\n            \"image\": {\n                \"id\": \"e3f84189-964e-4dc3-8ac6-832c2b7553d4\",\n                \"links\": [\n                    {\n                        \"href\": \"http://openstack:8774/4e1900cf21924a098709c23480e157c0/images/e3f84189-964e-4dc3-8ac6-832c2b7553d4\",\n                        \"rel\": \"bookmark\"\n                    }\n                ]\n            },\n            \"key_name\": null,\n            \"links\": [\n                {\n                    \"href\": \"http://openstack:8774/v2/4e1900cf21924a098709c23480e157c0/servers/cad76945-8851-489a-99e1-f1049e02c769\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"http://openstack:8774/4e1900cf21924a098709c23480e157c0/servers/cad76945-8851-489a-99e1-f1049e02c769\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"metadata\": {},\n            \"name\": \"machine_3\",\n            \"os-extended-volumes:volumes_attached\": [],\n            \"security_groups\": [\n                {\n                    \"name\": \"default\"\n                }\n            ],\n            \"status\": \"SHELVED_OFFLOADED\",\n            \"tenant_id\": \"4e1900cf21924a098709c23480e157c0\",\n            \"updated\": \"2014-03-19T11:38:05Z\",\n            \"user_id\": \"08ba127f0d6842279f9db8e8bc6977e9\"\n        },\n        {\n            \"OS-DCF:diskConfig\": \"MANUAL\",\n            \"OS-EXT-AZ:availability_zone\": \"nova\",\n            \"OS-EXT-SRV-ATTR:host\": \"rdohavana.localdomain\",\n            \"OS-EXT-SRV-ATTR:hypervisor_hostname\": \"rdohavana.localdomain\",\n            \"OS-EXT-SRV-ATTR:instance_name\": \"instance-00000005\",\n            \"OS-EXT-STS:power_state\": 1,\n            \"OS-EXT-STS:task_state\": null,\n            \"OS-EXT-STS:vm_state\": \"rescued\",\n            \"OS-SRV-USG:launched_at\": \"2014-03-19T11:36:05.000000\",\n            \"OS-SRV-USG:terminated_at\": null,\n            \"accessIPv4\": \"\",\n            \"accessIPv6\": \"\",\n            \"addresses\": {\n                \"public\": [\n                    {\n                        \"OS-EXT-IPS-MAC:mac_addr\": \"fa:16:3e:18:fe:c8\",\n                        \"OS-EXT-IPS:type\": \"fixed\",\n                        \"addr\": \"172.24.4.227\",\n                        \"version\": 4\n                    }\n                ]\n            },\n            \"config_drive\": \"\",\n            \"created\": \"2014-03-19T11:31:19Z\",\n            \"flavor\": {\n                \"id\": \"6\",\n                \"links\": [\n                    {\n                        \"href\": \"http://openstack:8774/4e1900cf21924a098709c23480e157c0/flavors/6\",\n                        \"rel\": \"bookmark\"\n                    }\n                ]\n            },\n            \"hostId\": \"0bc453b1c10348e9dc398fed7a5b06f996964ae1643fe460a85a23d8\",\n            \"id\": \"89142a4f-f58c-4205-8571-65f4a2be2bc9\",\n            \"image\": {\n                \"id\": \"e3f84189-964e-4dc3-8ac6-832c2b7553d4\",\n                \"links\": [\n                    {\n                        \"href\": \"http://openstack:8774/4e1900cf21924a098709c23480e157c0/images/e3f84189-964e-4dc3-8ac6-832c2b7553d4\",\n                        \"rel\": \"bookmark\"\n                    }\n                ]\n            },\n            \"key_name\": null,\n            \"links\": [\n                {\n                    \"href\": \"http://openstack:8774/v2/4e1900cf21924a098709c23480e157c0/servers/89142a4f-f58c-4205-8571-65f4a2be2bc9\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"http://openstack:8774/4e1900cf21924a098709c23480e157c0/servers/89142a4f-f58c-4205-8571-65f4a2be2bc9\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"metadata\": {},\n            \"name\": \"machine_2\",\n            \"os-extended-volumes:volumes_attached\": [],\n            \"security_groups\": [\n                {\n                    \"name\": \"default\"\n                }\n            ],\n            \"status\": \"RESCUE\",\n            \"tenant_id\": \"4e1900cf21924a098709c23480e157c0\",\n            \"updated\": \"2014-03-19T11:36:05Z\",\n            \"user_id\": \"08ba127f0d6842279f9db8e8bc6977e9\"\n        },\n        {\n            \"OS-DCF:diskConfig\": \"MANUAL\",\n            \"OS-EXT-AZ:availability_zone\": \"nova\",\n            \"OS-EXT-SRV-ATTR:host\": \"rdohavana.localdomain\",\n            \"OS-EXT-SRV-ATTR:hypervisor_hostname\": \"rdohavana.localdomain\",\n            \"OS-EXT-SRV-ATTR:instance_name\": \"instance-00000004\",\n            \"OS-EXT-STS:power_state\": 4,\n            \"OS-EXT-STS:task_state\": null,\n            \"OS-EXT-STS:vm_state\": \"stopped\",\n            \"OS-SRV-USG:launched_at\": \"2014-03-19T11:30:33.000000\",\n            \"OS-SRV-USG:terminated_at\": null,\n            \"accessIPv4\": \"\",\n            \"accessIPv6\": \"\",\n            \"addresses\": {\n                \"public\": [\n                    {\n                        \"OS-EXT-IPS-MAC:mac_addr\": \"fa:16:3e:64:1a:d5\",\n                        \"OS-EXT-IPS:type\": \"fixed\",\n                        \"addr\": \"172.24.4.228\",\n                        \"version\": 4\n                    }\n                ]\n            },\n            \"config_drive\": \"\",\n            \"created\": \"2014-03-19T11:28:56Z\",\n            \"flavor\": {\n                \"id\": \"6\",\n                \"links\": [\n                    {\n                        \"href\": \"http://openstack:8774/4e1900cf21924a098709c23480e157c0/flavors/6\",\n                        \"rel\": \"bookmark\"\n                    }\n                ]\n            },\n            \"hostId\": \"0bc453b1c10348e9dc398fed7a5b06f996964ae1643fe460a85a23d8\",\n            \"id\": \"fac50d26-bb38-455f-ad92-eba790187c00\",\n            \"image\": {\n                \"id\": \"e3f84189-964e-4dc3-8ac6-832c2b7553d4\",\n                \"links\": [\n                    {\n                        \"href\": \"http://openstack:8774/4e1900cf21924a098709c23480e157c0/images/e3f84189-964e-4dc3-8ac6-832c2b7553d4\",\n                        \"rel\": \"bookmark\"\n                    }\n                ]\n            },\n            \"key_name\": null,\n            \"links\": [\n                {\n                    \"href\": \"http://openstack:8774/v2/4e1900cf21924a098709c23480e157c0/servers/fac50d26-bb38-455f-ad92-eba790187c00\",\n                    \"rel\": \"self\"\n                },\n                {\n                    \"href\": \"http://openstack:8774/4e1900cf21924a098709c23480e157c0/servers/fac50d26-bb38-455f-ad92-eba790187c00\",\n                    \"rel\": \"bookmark\"\n                }\n            ],\n            \"metadata\": {},\n            \"name\": \"machine_1\",\n            \"os-extended-volumes:volumes_attached\": [],\n            \"security_groups\": [\n                {\n                    \"name\": \"default\"\n                }\n            ],\n            \"status\": \"SHUTOFF\",\n            \"tenant_id\": \"4e1900cf21924a098709c23480e157c0\",\n            \"updated\": \"2014-03-19T11:35:26Z\",\n            \"user_id\": \"08ba127f0d6842279f9db8e8bc6977e9\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/server_public_ip_in_private.json",
    "content": "{\n    \"server\": {\n        \"status\": \"ACTIVE\",\n        \"updated\": \"2012-03-22T22:11:55Z\",\n        \"hostId\": \"cb0d9e5004bef8c21270a0b09f7624f4c387f3a523f3aaa4c5694a61\",\n        \"user_id\": \"54297837463082\",\n        \"name\": \"hpcloud-computes-38d\",\n        \"links\": [\n            {\n                \"href\": \"https://az-2.region-a.geo-1.compute.hpcloudsvc.com/v2/37936628937291/servers/59662\",\n                \"rel\": \"self\"\n            },\n            {\n                \"href\": \"https://az-2.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/servers/59662\",\n                \"rel\": \"bookmark\"\n            }\n        ],\n        \"addresses\": {\n            \"private\": [\n                {\n                    \"version\": 4,\n                    \"addr\": \"10.6.39.189\"\n                },\n                {\n                    \"version\": 4,\n                    \"addr\": \"15.185.181.94\"\n                }\n            ]\n        },\n        \"tenant_id\": \"37936628937291\",\n        \"image\": {\n            \"id\": \"229\",\n            \"links\": [\n                {\n                    \"href\": \"https://az-2.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/images/229\",\n                    \"rel\": \"bookmark\"\n                }\n            ]\n        },\n        \"created\": \"2012-03-22T22:11:19Z\",\n        \"uuid\": \"7aed8e05-1daf-476a-87b2-640e8f7dcafd\",\n        \"accessIPv4\": \"\",\n        \"accessIPv6\": \"\",\n        \"key_name\": \"jclouds_hpcloud-computes_77\",\n        \"progress\": 100,\n        \"flavor\": {\n            \"id\": \"100\",\n            \"links\": [\n                {\n                    \"href\": \"https://az-2.region-a.geo-1.compute.hpcloudsvc.com/37936628937291/flavors/100\",\n                    \"rel\": \"bookmark\"\n                }\n            ]\n        },\n        \"config_drive\": \"\",\n        \"id\": 59662,\n        \"metadata\": {\n            \"Name\": \"hpcloud-computes\"\n        }\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/server_with_security_groups.json",
    "content": "{\n    \"server\": {\n        \"status\": \"ACTIVE\",\n        \"updated\": \"2012-05-04T12:15:01Z\",\n        \"hostId\": \"02c7c81e36024d2bfdb473cb762900138bc07777922479d3d4f8f690\",\n        \"user_id\": \"1e8a56719e0d4ab4b7edb85c77f7290f\",\n        \"name\": \"test\",\n        \"links\": [\n            {\n                \"href\": \"http://172.16.89.148:8774/v2/4287930c796741aa898425f40832cb3c/servers/8d0a6ca5-8849-4b3d-b86e-f24c92490ebb\",\n                \"rel\": \"self\"\n            },\n            {\n                \"href\": \"http://172.16.89.148:8774/4287930c796741aa898425f40832cb3c/servers/8d0a6ca5-8849-4b3d-b86e-f24c92490ebb\",\n                \"rel\": \"bookmark\"\n            }\n        ],\n        \"created\": \"2012-05-04T12:14:57Z\",\n        \"tenant_id\": \"4287930c796741aa898425f40832cb3c\",\n        \"image\": {\n            \"id\": \"ea17cc36-f7c9-40cd-b6bf-a952b74870f2\",\n            \"links\": [\n                {\n                    \"href\": \"http://172.16.89.148:8774/4287930c796741aa898425f40832cb3c/images/ea17cc36-f7c9-40cd-b6bf-a952b74870f2\",\n                    \"rel\": \"bookmark\"\n                }\n            ]\n        },\n        \"addresses\": {\n            \"private\": [\n                {\n                    \"version\": 4,\n                    \"addr\": \"10.0.0.8\"\n                }\n            ]\n        },\n        \"accessIPv4\": \"\",\n        \"accessIPv6\": \"\",\n        \"key_name\": \"\",\n        \"progress\": 0,\n        \"flavor\": {\n            \"id\": \"1\",\n            \"links\": [\n                {\n                    \"href\": \"http://172.16.89.148:8774/4287930c796741aa898425f40832cb3c/flavors/1\",\n                    \"rel\": \"bookmark\"\n                }\n            ]\n        },\n        \"config_drive\": \"\",\n        \"id\": \"8d0a6ca5-8849-4b3d-b86e-f24c92490ebb\",\n        \"security_groups\": [\n            {\n                \"name\": \"default\"\n            },\n            {\n                \"name\": \"group1\"\n            }\n        ],\n        \"metadata\": {}\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/server_with_security_groups_extension.json",
    "content": "{\n    \"server\": {\n        \"status\": \"ACTIVE\",\n        \"updated\": \"2012-05-04T12:15:01Z\",\n        \"hostId\": \"02c7c81e36024d2bfdb473cb762900138bc07777922479d3d4f8f690\",\n        \"user_id\": \"1e8a56719e0d4ab4b7edb85c77f7290f\",\n        \"name\": \"test\",\n        \"links\": [\n            {\n                \"href\": \"http://172.16.89.148:8774/v2/4287930c796741aa898425f40832cb3c/servers/8d0a6ca5-8849-4b3d-b86e-f24c92490ebb\",\n                \"rel\": \"self\"\n            },\n            {\n                \"href\": \"http://172.16.89.148:8774/4287930c796741aa898425f40832cb3c/servers/8d0a6ca5-8849-4b3d-b86e-f24c92490ebb\",\n                \"rel\": \"bookmark\"\n            }\n        ],\n        \"created\": \"2012-05-04T12:14:57Z\",\n        \"tenant_id\": \"4287930c796741aa898425f40832cb3c\",\n        \"image\": {\n            \"id\": \"ea17cc36-f7c9-40cd-b6bf-a952b74870f2\",\n            \"links\": [\n                {\n                    \"href\": \"http://172.16.89.148:8774/4287930c796741aa898425f40832cb3c/images/ea17cc36-f7c9-40cd-b6bf-a952b74870f2\",\n                    \"rel\": \"bookmark\"\n                }\n            ]\n        },\n        \"addresses\": {\n            \"private\": [\n                {\n                    \"version\": 4,\n                    \"addr\": \"10.0.0.8\"\n                }\n            ]\n        },\n        \"accessIPv4\": \"\",\n        \"accessIPv6\": \"\",\n        \"key_name\": \"\",\n        \"progress\": 0,\n        \"flavor\": {\n            \"id\": \"1\",\n            \"links\": [\n                {\n                    \"href\": \"http://172.16.89.148:8774/4287930c796741aa898425f40832cb3c/flavors/1\",\n                    \"rel\": \"bookmark\"\n                }\n            ]\n        },\n        \"config_drive\": \"\",\n        \"id\": \"8d0a6ca5-8849-4b3d-b86e-f24c92490ebb\",\n        \"security_groups\": [\n            {\n                \"name\": \"name1\"\n            }\n        ],\n        \"metadata\": {}\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/simple_tenant_usage.json",
    "content": "{\n    \"tenant_usage\": {\n        \"total_memory_mb_usage\": 0.0014847999999999999,\n        \"total_vcpus_usage\": 7.249999999999999e-7,\n        \"total_hours\": 4.833333333333333e-7,\n        \"tenant_id\": \"f8535069c3fb404cb61c873b1a0b4921\",\n        \"stop\": \"2012-04-18 13:32:07.255830\",\n        \"server_usages\": [\n            {\n                \"hours\": 2.4166666666666665e-7,\n                \"uptime\": 91149,\n                \"local_gb\": 50,\n                \"ended_at\": null,\n                \"name\": \"test1\",\n                \"tenant_id\": \"f8535069c3fb404cb61c873b1a0b4921\",\n                \"vcpus\": 2,\n                \"memory_mb\": 4096,\n                \"state\": \"active\",\n                \"flavor\": \"m1.medium\",\n                \"started_at\": \"2012-04-17 12:12:58\"\n            },\n            {\n                \"hours\": 2.4166666666666665e-7,\n                \"uptime\": 84710,\n                \"local_gb\": 30,\n                \"ended_at\": null,\n                \"name\": \"mish_test\",\n                \"tenant_id\": \"f8535069c3fb404cb61c873b1a0b4921\",\n                \"vcpus\": 1,\n                \"memory_mb\": 2048,\n                \"state\": \"active\",\n                \"flavor\": \"m1.small\",\n                \"started_at\": \"2012-04-17 14:00:17\"\n            }\n        ],\n        \"start\": \"2012-04-18 13:32:07.255743\",\n        \"total_local_gb_usage\": 0.00001933333333333333\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/simple_tenant_usages.json",
    "content": "{\n    \"tenant_usages\": [\n        {\n            \"total_memory_mb_usage\": 0.0015018666666666667,\n            \"total_vcpus_usage\": 7.333333333333333e-7,\n            \"start\": \"2012-04-18 12:18:39.702411\",\n            \"tenant_id\": \"f8535069c3fb404cb61c873b1a0b4921\",\n            \"stop\": \"2012-04-18 12:18:39.702499\",\n            \"total_hours\": 4.888888888888889e-7,\n            \"total_local_gb_usage\": 0.000019555555555555557\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/snapshot_details.json",
    "content": "{\n    \"snapshot\": {\n        \"status\": \"available\",\n        \"displayDescription\": \"jclouds live test snapshot\",\n        \"displayName\": \"jclouds-live-test\",\n        \"volumeId\": 9,\n        \"id\": 7,\n        \"createdAt\": \"2012-04-24 13:34:42\",\n        \"size\": 1\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/snapshot_list.json",
    "content": "{\n    \"snapshots\": [\n        {\n            \"status\": \"available\",\n            \"displayDescription\": \"jclouds live test snapshot\",\n            \"displayName\": \"jclouds-live-test\",\n            \"volumeId\": 9,\n            \"id\": 7,\n            \"createdAt\": \"2012-04-24 13:34:42\",\n            \"size\": 1\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/snapshot_list_detail.json",
    "content": "{\n    \"snapshots\": [\n        {\n            \"status\": \"available\",\n            \"displayDescription\": \"jclouds live test snapshot\",\n            \"displayName\": \"jclouds-live-test\",\n            \"volumeId\": 9,\n            \"id\": 7,\n            \"createdAt\": \"2012-04-24 13:34:42\",\n            \"size\": 1\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/spice_console.json",
    "content": "{\n    \"console\": {\n        \"type\": \"spice-html5\",\n        \"url\": \"http://example.com:6080/spice_auto.html?token=f9906a48-b71e-4f18-baca-c987da3ebdb3&title=dafa(75ecef58-3b8e-4659-ab3b-5501454188e9)\"\n    }\n}\n\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/virtual_interfaces_list.json",
    "content": "{\n    \"virtual_interfaces\": [\n        {\n            \"id\": \"02315827-b05c-4668-9c05-75c68838074a\",\n            \"mac_address\": \"fa:16:3e:09:71:34\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/volume_details.json",
    "content": "{\n    \"volume\": {\n        \"status\": \"in-use\",\n        \"displayDescription\": \"This is a test volume\",\n        \"availabilityZone\": \"nova\",\n        \"displayName\": \"test\",\n        \"attachments\": [\n            {\n                \"device\": \"/dev/vdc\",\n                \"serverId\": \"b4785058-cb80-491b-baa3-e4ee6546450e\",\n                \"id\": 1,\n                \"volumeId\": 1\n            }\n        ],\n        \"volumeType\": null,\n        \"snapshotId\": null,\n        \"size\": 1,\n        \"id\": 1,\n        \"createdAt\": \"2012-04-23 12:16:45\",\n        \"metadata\": {}\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/volume_list.json",
    "content": "{\n    \"volumes\": [\n        {\n            \"status\": \"in-use\",\n            \"displayDescription\": \"This is a test volume\",\n            \"availabilityZone\": \"nova\",\n            \"displayName\": \"test\",\n            \"attachments\": [\n                {\n                    \"device\": \"/dev/vdc\",\n                    \"serverId\": \"b4785058-cb80-491b-baa3-e4ee6546450e\",\n                    \"id\": 1,\n                    \"volumeId\": 1\n                }\n            ],\n            \"volumeType\": null,\n            \"snapshotId\": null,\n            \"size\": 1,\n            \"id\": 1,\n            \"createdAt\": \"2012-04-23 12:16:45\",\n            \"metadata\": {}\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/volume_list_detail.json",
    "content": "{\n    \"volumes\": [\n        {\n            \"status\": \"in-use\",\n            \"displayDescription\": \"This is a test volume\",\n            \"availabilityZone\": \"nova\",\n            \"displayName\": \"test\",\n            \"attachments\": [\n                {\n                    \"device\": \"/dev/vdc\",\n                    \"serverId\": \"b4785058-cb80-491b-baa3-e4ee6546450e\",\n                    \"id\": 1,\n                    \"volumeId\": 1\n                }\n            ],\n            \"volumeType\": null,\n            \"snapshotId\": null,\n            \"size\": 1,\n            \"id\": 1,\n            \"createdAt\": \"2012-04-23 12:16:45\",\n            \"metadata\": {}\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/volume_type.json",
    "content": "{\n    \"volume_type\": {\n        \"name\": \"jclouds-test-1\",\n        \"deleted\": false,\n        \"created_at\": \"2012-05-10 12:33:06\",\n        \"updated_at\": null,\n        \"extra_specs\": {\n            \"test\": \"value1\",\n            \"test1\": \"wibble\"\n        },\n        \"deleted_at\": null,\n        \"id\": 8\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/volume_type_extra_specs.json",
    "content": "{\n    \"extra_specs\": {\n        \"test\": \"value1\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/volume_type_list.json",
    "content": "{\n    \"volume_types\": [\n        {\n            \"name\": \"jclouds-test-1\",\n            \"deleted\": false,\n            \"created_at\": \"2012-05-10 12:33:06\",\n            \"updated_at\": null,\n            \"extra_specs\": {\n                \"test\": \"value1\",\n                \"test1\": \"wibble\"\n            },\n            \"deleted_at\": null,\n            \"id\": 8\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-nova/src/test/resources/xvpvnc_console.json",
    "content": "{\n    \"console\": {\n        \"type\": \"xvpvnc\",\n        \"url\": \"http://example.com:6081/console?token=2abbe0b2-dcf1-479d-8d58-88e82b477865\"\n    }\n}\n\n"
  },
  {
    "path": "apis/openstack-nova-ec2/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.openstack.nova.ec2.*;version=\"${project.version}\";-noimport:=true"
  },
  {
    "path": "apis/openstack-nova-ec2/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.api</groupId>\n  <artifactId>openstack-nova-ec2</artifactId>\n  <name>jclouds openstack-nova-ec2 api</name>\n  <description>EC2 interface to OpenStack Nova</description>\n\n  <properties>\n    <test.openstack-nova-ec2.endpoint>http://localhost:8773/services/Cloud</test.openstack-nova-ec2.endpoint>\n    <test.openstack-nova-ec2.api-version>2010-06-15</test.openstack-nova-ec2.api-version>\n    <test.openstack-nova-ec2.build-version />\n    <test.openstack-nova-ec2.identity>FIXME_IDENTITY</test.openstack-nova-ec2.identity>\n    <test.openstack-nova-ec2.credential>FIXME_CREDENTIAL</test.openstack-nova-ec2.credential>\n    <test.openstack-nova-ec2.template />\n    <test.openstack-nova-ec2.ebs-template />\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-nova</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>ec2</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>ec2</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-log4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-sshj</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.openstack-nova-ec2.endpoint>${test.openstack-nova-ec2.endpoint}</test.openstack-nova-ec2.endpoint>\n                    <test.openstack-nova-ec2.api-version>${test.openstack-nova-ec2.api-version}</test.openstack-nova-ec2.api-version>\n                    <test.openstack-nova-ec2.build-version>${test.openstack-nova-ec2.build-version}</test.openstack-nova-ec2.build-version>\n                    <test.openstack-nova-ec2.identity>${test.openstack-nova-ec2.identity}</test.openstack-nova-ec2.identity>\n                    <test.openstack-nova-ec2.credential>${test.openstack-nova-ec2.credential}</test.openstack-nova-ec2.credential>\n                    <test.openstack-nova-ec2.template>${test.openstack-nova-ec2.template}</test.openstack-nova-ec2.template>\n                    <test.openstack-nova-ec2.ebs-template>${test.openstack-nova-ec2.ebs-template}</test.openstack-nova-ec2.ebs-template>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n\n"
  },
  {
    "path": "apis/openstack-nova-ec2/src/main/java/org/jclouds/openstack/nova/ec2/NovaEC2Api.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.ec2;\n\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.location.functions.RegionToEndpointOrProviderIfNull;\nimport org.jclouds.openstack.nova.ec2.features.NovaEC2KeyPairApi;\nimport org.jclouds.rest.annotations.Delegate;\nimport org.jclouds.rest.annotations.EndpointParam;\n\nimport com.google.common.base.Optional;\n\n/**\n * Provides access to EC2 services.\n */\npublic interface NovaEC2Api extends EC2Api {\n\n   /**\n    * {@inheritDoc}\n    */\n   @Delegate\n   @Override\n   Optional<? extends NovaEC2KeyPairApi> getKeyPairApi();\n\n   @Delegate\n   @Override\n   Optional<? extends NovaEC2KeyPairApi> getKeyPairApiForRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) String region);\n\n}\n"
  },
  {
    "path": "apis/openstack-nova-ec2/src/main/java/org/jclouds/openstack/nova/ec2/NovaEC2ApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.ec2;\n\nimport static org.jclouds.Constants.PROPERTY_RELAX_HOSTNAME;\nimport static org.jclouds.Constants.PROPERTY_TRUST_ALL_CERTS;\nimport static org.jclouds.compute.config.ComputeServiceProperties.RESOURCENAME_DELIMITER;\nimport static org.jclouds.ec2.reference.EC2Constants.PROPERTY_EC2_AMI_OWNERS;\nimport static org.jclouds.ec2.reference.EC2Constants.PROPERTY_EC2_AUTO_ALLOCATE_ELASTIC_IPS;\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_REGIONS;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.ec2.EC2ApiMetadata;\nimport org.jclouds.ec2.compute.EC2ComputeServiceContext;\nimport org.jclouds.ec2.compute.config.EC2ResolveImagesModule;\nimport org.jclouds.openstack.nova.ec2.config.HyphenToNullIso8601Module;\nimport org.jclouds.openstack.nova.ec2.config.NovaEC2ComputeServiceContextModule;\nimport org.jclouds.openstack.nova.ec2.config.NovaEC2HttpApiModule;\nimport org.jclouds.rest.internal.BaseHttpApiMetadata;\n\nimport com.google.auto.service.AutoService;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n@AutoService(ApiMetadata.class)\npublic final class NovaEC2ApiMetadata extends BaseHttpApiMetadata<NovaEC2Api> {\n\n   @Override\n   public Builder toBuilder() {\n      return new Builder().fromApiMetadata(this);\n   }\n\n   public NovaEC2ApiMetadata() {\n      super(new Builder());\n   }\n\n   protected NovaEC2ApiMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = EC2ApiMetadata.defaultProperties();\n      properties.setProperty(PROPERTY_REGIONS, \"nova\");\n      properties.setProperty(PROPERTY_EC2_AMI_OWNERS, \"admin\");\n      // hash characters are banned\n      properties.setProperty(RESOURCENAME_DELIMITER, \"-\");\n      // often, we are dealing with IP addresses, not hostnames\n      properties.setProperty(PROPERTY_RELAX_HOSTNAME, \"true\");\n      properties.setProperty(PROPERTY_TRUST_ALL_CERTS, \"true\");\n      properties.setProperty(PROPERTY_EC2_AUTO_ALLOCATE_ELASTIC_IPS, \"true\");\n      // auth fail sometimes happens in EC2, as the rc.local script that injects the\n      // authorized key executes after ssh has started.  \n      properties.setProperty(\"jclouds.ssh.max-retries\", \"7\");\n      properties.setProperty(\"jclouds.ssh.retry-auth\", \"true\");\n      return properties;\n   }\n\n   public static final class Builder extends BaseHttpApiMetadata.Builder<NovaEC2Api, Builder> {\n      public Builder() {\n         id(\"openstack-nova-ec2\")\n         .name(\"OpenStack Nova's EC2-clone API\")\n         .version(\"2009-04-04\")\n         .identityName(\"Access Key ID\")\n         .credentialName(\"Secret Access Key\")\n         .defaultEndpoint(\"http://localhost:8773/services/Cloud\")\n         .documentation(URI.create(\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference\"))\n         .defaultProperties(NovaEC2ApiMetadata.defaultProperties())\n         .view(EC2ComputeServiceContext.class)\n         .defaultModules(ImmutableSet.<Class<? extends Module>>builder()\n                                     .add(NovaEC2HttpApiModule.class)\n                                     .add(EC2ResolveImagesModule.class)\n                                     .add(NovaEC2ComputeServiceContextModule.class)\n                                     .add(HyphenToNullIso8601Module.class).build());\n      }\n\n      @Override\n      public NovaEC2ApiMetadata build() {\n         return new NovaEC2ApiMetadata(this);\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova-ec2/src/main/java/org/jclouds/openstack/nova/ec2/config/HyphenToNullIso8601Module.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.ec2.config;\n\n\nimport org.jclouds.date.internal.DateServiceDateCodecFactory.DateServiceIso8601Codec;\nimport org.jclouds.openstack.nova.ec2.internal.HyphenToNullIso8601Codec;\n\nimport com.google.inject.AbstractModule;\n\npublic class HyphenToNullIso8601Module extends AbstractModule {\n\n   @Override\n   protected void configure() {\n      bind(DateServiceIso8601Codec.class).to(HyphenToNullIso8601Codec.class);\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova-ec2/src/main/java/org/jclouds/openstack/nova/ec2/config/NovaEC2ComputeServiceContextModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.ec2.config;\n\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.ec2.compute.config.EC2ComputeServiceContextModule;\nimport org.jclouds.ec2.compute.loaders.CreateSecurityGroupIfNeeded;\nimport org.jclouds.ec2.compute.strategy.ReviseParsedImage;\nimport org.jclouds.openstack.nova.ec2.loaders.NovaCreateSecurityGroupIfNeeded;\nimport org.jclouds.openstack.nova.ec2.strategy.NovaReviseParsedImage;\nimport org.jclouds.openstack.nova.v2_0.compute.functions.ImageToOperatingSystem;\n\nimport com.google.common.base.Function;\nimport com.google.inject.TypeLiteral;\n\npublic class NovaEC2ComputeServiceContextModule extends EC2ComputeServiceContextModule {\n\n   @Override\n   protected void configure() {\n      super.configure();\n      bind(new TypeLiteral<Function<org.jclouds.openstack.nova.v2_0.domain.Image, OperatingSystem>>() {\n      }).to(ImageToOperatingSystem.class);\n      bind(ReviseParsedImage.class).to(NovaReviseParsedImage.class);\n      bind(CreateSecurityGroupIfNeeded.class).to(NovaCreateSecurityGroupIfNeeded.class);\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova-ec2/src/main/java/org/jclouds/openstack/nova/ec2/config/NovaEC2HttpApiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.ec2.config;\n\n\n\n\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.config.BaseEC2HttpApiModule;\nimport org.jclouds.ec2.suppliers.DescribeAvailabilityZonesInRegion;\nimport org.jclouds.ec2.xml.CreateVolumeResponseHandler;\nimport org.jclouds.ec2.xml.DescribeImagesResponseHandler;\nimport org.jclouds.location.config.LocationModule;\nimport org.jclouds.location.suppliers.RegionIdToZoneIdsSupplier;\nimport org.jclouds.location.suppliers.ZoneIdsSupplier;\nimport org.jclouds.location.suppliers.derived.ZoneIdsFromRegionIdToZoneIdsValues;\nimport org.jclouds.openstack.nova.ec2.NovaEC2Api;\nimport org.jclouds.openstack.nova.ec2.xml.NovaCreateVolumeResponseHandler;\nimport org.jclouds.openstack.nova.ec2.xml.NovaDescribeImagesResponseHandler;\nimport org.jclouds.rest.ConfiguresHttpApi;\n\nimport com.google.inject.Scopes;\n\n@ConfiguresHttpApi\npublic class NovaEC2HttpApiModule extends BaseEC2HttpApiModule<NovaEC2Api> {\n\n   public NovaEC2HttpApiModule() {\n      super(NovaEC2Api.class);\n   }\n   \n   @Override\n   protected void configure() {\n      bind(EC2Api.class).to(NovaEC2Api.class);\n      super.configure();\n      bind(CreateVolumeResponseHandler.class).to(NovaCreateVolumeResponseHandler.class).in(Scopes.SINGLETON);\n      bind(DescribeImagesResponseHandler.class).to(NovaDescribeImagesResponseHandler.class);\n   }\n\n   @Override\n   protected void installLocations() {\n      install(new LocationModule());\n      bind(RegionIdToZoneIdsSupplier.class).to(DescribeAvailabilityZonesInRegion.class).in(Scopes.SINGLETON);\n      // there is only one region, and its endpoint is the same as the provider\n      bind(ZoneIdsSupplier.class).to(ZoneIdsFromRegionIdToZoneIdsValues.class).in(Scopes.SINGLETON);\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova-ec2/src/main/java/org/jclouds/openstack/nova/ec2/features/NovaEC2KeyPairApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.ec2.features;\n\nimport static org.jclouds.aws.reference.FormParameters.ACTION;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.FormParam;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\n\nimport org.jclouds.aws.filters.FormSigner;\nimport org.jclouds.ec2.domain.KeyPair;\nimport org.jclouds.ec2.features.KeyPairApi;\nimport org.jclouds.ec2.functions.EncodedRSAPublicKeyToBase64;\nimport org.jclouds.ec2.xml.KeyPairResponseHandler;\nimport org.jclouds.location.functions.RegionToEndpointOrProviderIfNull;\nimport org.jclouds.rest.annotations.EndpointParam;\nimport org.jclouds.rest.annotations.FormParams;\nimport org.jclouds.rest.annotations.ParamParser;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.VirtualHost;\nimport org.jclouds.rest.annotations.XMLResponseParser;\n\n@RequestFilters(FormSigner.class)\n@VirtualHost\npublic interface NovaEC2KeyPairApi extends KeyPairApi {\n\n   /**\n    * Imports the public key from an RSA key pair that you created with a third-party tool. Compare\n    * this with CreateKeyPair, in which AWS creates the key pair and gives the keys to you (Nova\n    * keeps a copy of the public key). With ImportKeyPair, you create the key pair and give Nova just\n    * the public key. The private key is never transferred between you and Nova.\n    *\n    * <p/>\n    * You can easily create an RSA key pair on Windows and Linux using the ssh-keygen command line\n    * tool (provided with the standard OpenSSH installation). Standard library support for RSA key\n    * pair creation is also available in Java, Ruby, Python, and many other programming languages.\n    *\n    * <p/>\n    * <h4>Supported Formats</h4>\n    * <ul>\n    * <li>OpenSSH public key format (e.g., the format in ~/.ssh/authorized_keys)</li>\n    * <li>Base64 encoded DER format</li>\n    * <li>SSH public key file format as specified in RFC4716</li>\n    * </ul>\n    * DSA keys are not supported. Make sure your key generator is set up to create RSA keys.\n    * <p/>\n    * Supported lengths: 1024, 2048, and 4096.\n    * <p/>\n    *\n    * @param region\n    *           region to import the key into\n    * @param keyName\n    *           A unique name for the key pair. Accepts alphanumeric characters, spaces, dashes, and\n    *           underscores.\n    * @param publicKeyMaterial\n    *           The public key\n    * @return imported key including fingerprint\n    */\n   @Named(\"keypair:import\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"ImportKeyPair\")\n   @XMLResponseParser(KeyPairResponseHandler.class)\n   KeyPair importKeyPairInRegion(\n         @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) String region,\n         @FormParam(\"KeyName\") String keyName,\n         @FormParam(\"PublicKeyMaterial\") @ParamParser(EncodedRSAPublicKeyToBase64.class) String publicKeyMaterial);\n}\n"
  },
  {
    "path": "apis/openstack-nova-ec2/src/main/java/org/jclouds/openstack/nova/ec2/internal/HyphenToNullIso8601Codec.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.ec2.internal;\n\nimport java.util.Date;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.internal.DateServiceDateCodecFactory.DateServiceIso8601Codec;\n\nimport com.google.common.base.Objects;\nimport com.google.inject.Inject;\n\n@Singleton\npublic class HyphenToNullIso8601Codec extends DateServiceIso8601Codec {\n\n   @Inject\n   public HyphenToNullIso8601Codec(DateService dateService) {\n      super(dateService);\n   }\n\n   @Override\n   public Date toDate(String date) throws IllegalArgumentException {\n      if (Objects.equal(\"-\", date))\n         return null;\n      return super.toDate(date);\n   }\n\n   @Override\n   public String toString() {\n      return \"hyphenToNullIso8601()\";\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova-ec2/src/main/java/org/jclouds/openstack/nova/ec2/loaders/NovaCreateSecurityGroupIfNeeded.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.ec2.loaders;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.AWSResponseException;\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.compute.loaders.CreateSecurityGroupIfNeeded;\n\nimport com.google.common.base.Predicate;\n\n@Singleton\npublic class NovaCreateSecurityGroupIfNeeded extends CreateSecurityGroupIfNeeded {\n\n   @Inject\n   public NovaCreateSecurityGroupIfNeeded(EC2Api ec2Client,\n            @Named(\"SECURITY\") Predicate<RegionAndName> securityGroupEventualConsistencyDelay) {\n      super(checkNotNull(ec2Client, \"ec2Client\").getSecurityGroupApi().get(), securityGroupEventualConsistencyDelay);\n   }\n\n   protected void authorizeGroupToItself(String region, String name) {\n      try {\n         super.authorizeGroupToItself(region, name);\n      } catch (AWSResponseException e) {\n         logger.warn(e, \"<< error authorizing securityGroup(%s)\", name);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova-ec2/src/main/java/org/jclouds/openstack/nova/ec2/strategy/NovaReviseParsedImage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.ec2.strategy;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.domain.ImageBuilder;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.ec2.compute.strategy.ReviseParsedImage;\nimport org.jclouds.openstack.nova.v2_0.domain.Image;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class NovaReviseParsedImage implements ReviseParsedImage {\n\n   private final Function<Image, OperatingSystem> imageToOs;\n\n   @Inject\n   public NovaReviseParsedImage(Function<Image, OperatingSystem> imageToOs) {\n      this.imageToOs = checkNotNull(imageToOs, \"imageToOs\");\n   }\n\n   @Override\n   public void reviseParsedImage(org.jclouds.ec2.domain.Image from, ImageBuilder builder, OsFamily family,\n            OperatingSystem.Builder osBuilder) {\n      Image image = Image.builder().id(from.getId()).name(from.getName()).build();\n      OperatingSystem os = imageToOs.apply(image);\n      osBuilder.description(os.getDescription());\n      osBuilder.family(os.getFamily());\n      osBuilder.name(os.getName());\n      osBuilder.is64Bit(os.is64Bit());\n      osBuilder.version(os.getVersion());\n      // arch is accurate already\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova-ec2/src/main/java/org/jclouds/openstack/nova/ec2/xml/NovaCreateVolumeResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.ec2.xml;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.ec2.domain.Attachment;\nimport org.jclouds.ec2.domain.Volume;\nimport org.jclouds.ec2.xml.CreateVolumeResponseHandler;\nimport org.jclouds.location.Region;\nimport org.jclouds.location.Zone;\n\nimport com.google.common.base.Supplier;\n\npublic class NovaCreateVolumeResponseHandler extends CreateVolumeResponseHandler {\n\n   @Inject\n   protected NovaCreateVolumeResponseHandler(DateService dateService, @Region Supplier<String> defaultRegion,\n            @Zone Supplier<Map<String, Supplier<Set<String>>>> regionToZonesSupplier,\n            @Zone Supplier<Set<String>> zonesSupplier) {\n      super(dateService, defaultRegion, regionToZonesSupplier, zonesSupplier);\n   }\n   \n   public void endElement(String uri, String name, String qName) {\n      if (qName.equals(\"status\")) {\n         String statusString = currentText.toString().trim();\n         if (statusString.contains(\" \")) {\n            statusString = statusString.substring(0, statusString.indexOf(' '));\n         }\n         if (inAttachmentSet) {\n            attachmentStatus = Attachment.Status.fromValue(statusString);\n         } else {\n            volumeStatus = Volume.Status.fromValue(statusString);\n         }\n         currentText.setLength(0);\n      } else {\n         super.endElement(uri, name, qName);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova-ec2/src/main/java/org/jclouds/openstack/nova/ec2/xml/NovaDescribeImagesResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.ec2.xml;\n\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.ec2.domain.Image;\nimport org.jclouds.ec2.domain.Image.ImageType;\nimport org.jclouds.ec2.xml.DescribeImagesResponseHandler;\nimport org.jclouds.ec2.xml.TagSetHandler;\nimport org.jclouds.location.Region;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\n\n/**\n * Adjusted to filter out non-MACHINE images\n */\npublic class NovaDescribeImagesResponseHandler extends DescribeImagesResponseHandler {\n   @Inject\n   public NovaDescribeImagesResponseHandler(@Region Supplier<String> defaultRegion, TagSetHandler tagSetHandler) {\n      super(defaultRegion, tagSetHandler);\n   }\n\n   public Set<Image> getResult() {\n      return ImmutableSet.copyOf(Iterables.filter(contents, new Predicate<Image>() {\n         @Override\n         public boolean apply(Image image) {\n            return image.getImageType() == ImageType.MACHINE;\n         }\n      }));\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova-ec2/src/test/java/org/jclouds/openstack/nova/ec2/NovaEC2ApiMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.ec2;\n\nimport org.jclouds.compute.internal.BaseComputeServiceApiMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"NovaEC2ApiMetadataTest\")\npublic class NovaEC2ApiMetadataTest extends BaseComputeServiceApiMetadataTest {\n\n   public NovaEC2ApiMetadataTest() {\n      super(new NovaEC2ApiMetadata());\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova-ec2/src/test/java/org/jclouds/openstack/nova/ec2/NovaEC2ContextBuilderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.ec2;\n\nimport static org.jclouds.reflect.Reflection2.typeToken;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.View;\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.ec2.EC2Api;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"NovaEC2ContextBuilderTest\")\npublic class NovaEC2ContextBuilderTest {\n\n   public void testAssignability() {\n      View view = ContextBuilder.newBuilder(new NovaEC2ApiMetadata()).credentials(\"foo\", \"bar\")\n              .buildView(typeToken(ComputeServiceContext.class));\n      view.unwrapApi(EC2Api.class);\n      view.unwrapApi(NovaEC2Api.class);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova-ec2/src/test/java/org/jclouds/openstack/nova/ec2/compute/NovaEC2ComputeServiceLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.ec2.compute;\n\nimport org.jclouds.compute.domain.ExecResponse;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.ec2.compute.EC2ComputeServiceLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"NovaEC2ComputeServiceLiveTest\")\npublic class NovaEC2ComputeServiceLiveTest extends EC2ComputeServiceLiveTest {\n\n   public NovaEC2ComputeServiceLiveTest() {\n      provider = \"openstack-nova-ec2\";\n   }\n   \n   protected void checkResponseEqualsHostname(ExecResponse execResponse, NodeMetadata node1) {\n      // hostname is not predictable based on node metadata\n      assert execResponse.getOutput().trim().equals(\"ubuntu\");\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova-ec2/src/test/java/org/jclouds/openstack/nova/ec2/features/NovaEC2AMIApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.ec2.features;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Set;\n\nimport org.jclouds.ec2.domain.Image;\nimport org.jclouds.ec2.features.AMIApi;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.nova.ec2.internal.BaseNovaEC2RestApiExpectTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"NovaEC2ElasticBlockStoreApiTest\")\npublic class NovaEC2AMIApiExpectTest extends BaseNovaEC2RestApiExpectTest {\n\n   public void testDescribeImagesWithNonMachineTypes() {\n      AMIApi client = requestsSendResponses(\n            describeAvailabilityZonesRequest,\n            describeAvailabilityZonesResponse,\n            HttpRequest.builder().method(\"POST\")\n                  .endpoint(\"http://localhost:8773/services/Cloud/\")\n                  .addHeader(\"Host\", \"localhost:8773\")\n                  .payload(payloadFromStringWithContentType(\"Action=DescribeImages&Signature=Z3q3jSutwlfgvbcINT0Ed3AjrjxM4WMvQloXu/1kd40%3D&SignatureMethod=HmacSHA256&SignatureVersion=2&Timestamp=2012-04-16T15%3A54%3A08.897Z&Version=2009-04-04&AWSAccessKeyId=identity\", \"application/x-www-form-urlencoded\")).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/nova_ec2_images_with_ramdisk.xml\")).build()\n                                               ).getAMIApi().get();\n\n      Set<? extends Image> images = client.describeImagesInRegion(\"nova\");\n      \n      assertEquals(images.size(), 1);\n      \n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova-ec2/src/test/java/org/jclouds/openstack/nova/ec2/features/NovaEC2AMIApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.ec2.features;\n\nimport org.jclouds.ec2.features.AMIApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"NovaEC2AMIApiLiveTest\")\npublic class NovaEC2AMIApiLiveTest extends AMIApiLiveTest {\n   public NovaEC2AMIApiLiveTest() {\n      provider = \"openstack-nova-ec2\";\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova-ec2/src/test/java/org/jclouds/openstack/nova/ec2/features/NovaEC2AvailabilityZoneAndRegionApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.ec2.features;\n\nimport org.jclouds.ec2.features.AvailabilityZoneAndRegionApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"NovaEC2AvailabilityZoneAndRegionApiLiveTest\")\npublic class NovaEC2AvailabilityZoneAndRegionApiLiveTest extends AvailabilityZoneAndRegionApiLiveTest {\n   public NovaEC2AvailabilityZoneAndRegionApiLiveTest() {\n      provider = \"openstack-nova-ec2\";\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova-ec2/src/test/java/org/jclouds/openstack/nova/ec2/features/NovaEC2ElasticBlockStoreApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.ec2.features;\n\nimport org.jclouds.ec2.features.ElasticBlockStoreApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"NovaEC2ElasticBlockStoreApiLiveTest\")\npublic class NovaEC2ElasticBlockStoreApiLiveTest extends ElasticBlockStoreApiLiveTest {\n   public NovaEC2ElasticBlockStoreApiLiveTest() {\n      provider = \"openstack-nova-ec2\";\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova-ec2/src/test/java/org/jclouds/openstack/nova/ec2/features/NovaEC2ElasticBlockStoreExpectApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.ec2.features;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Set;\n\nimport org.jclouds.ec2.domain.Attachment;\nimport org.jclouds.ec2.domain.Volume;\nimport org.jclouds.ec2.features.ElasticBlockStoreApi;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.nova.ec2.internal.BaseNovaEC2RestApiExpectTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\", testName = \"NovaEC2ElasticBlockStoreApiTest\")\npublic class NovaEC2ElasticBlockStoreExpectApiTest extends BaseNovaEC2RestApiExpectTest {\n\n   public void testDescribeVolumesWithNovaEC2Status() {\n      ElasticBlockStoreApi client = requestsSendResponses(\n            describeAvailabilityZonesRequest,\n            describeAvailabilityZonesResponse,\n            HttpRequest.builder().method(\"POST\")\n                  .endpoint(\"http://localhost:8773/services/Cloud/\")\n                  .addHeader(\"Host\", \"localhost:8773\")\n                  .payload(payloadFromStringWithContentType(\"Action=DescribeVolumes&Signature=AvRznSzGExM%2Buaj2JJj66wq4v4f%2BakicyLooRDtC0t0%3D&SignatureMethod=HmacSHA256&SignatureVersion=2&Timestamp=2012-04-16T15%3A54%3A08.897Z&Version=2009-04-04&AWSAccessKeyId=identity\", \"application/x-www-form-urlencoded\")).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/nova_ec2_describe_volumes.xml\")).build()\n                                                          ).getElasticBlockStoreApi().get();\n\n      Set<Volume> expected = ImmutableSet.of(Volume\n            .builder()\n            .status(Volume.Status.AVAILABLE)\n            .availabilityZone(\"nova\")\n            .region(\"nova\")\n            .id(\"vol-00000007\")\n            .size(1)\n            .attachments(Attachment.builder().region(\"nova\").build())\n            .createTime(dateService.iso8601SecondsDateParse(\"2012-04-10T10:39:52Z\"))\n            .build());\n\n      assertEquals(client.describeVolumesInRegion(\"nova\"), expected);\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova-ec2/src/test/java/org/jclouds/openstack/nova/ec2/features/NovaEC2ElasticIPAddressApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.ec2.features;\n\nimport org.jclouds.ec2.features.ElasticIPAddressApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"NovaEC2ElasticIPAddressApiLiveTest\")\npublic class NovaEC2ElasticIPAddressApiLiveTest extends ElasticIPAddressApiLiveTest {\n   public NovaEC2ElasticIPAddressApiLiveTest() {\n      provider = \"openstack-nova-ec2\";\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova-ec2/src/test/java/org/jclouds/openstack/nova/ec2/features/NovaEC2InstanceApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.ec2.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNull;\n\nimport java.util.Set;\n\nimport org.jclouds.ec2.domain.BlockDevice;\nimport org.jclouds.ec2.domain.Reservation;\nimport org.jclouds.ec2.domain.RunningInstance;\nimport org.jclouds.ec2.features.InstanceApi;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.nova.ec2.internal.BaseNovaEC2RestApiExpectTest;\n\nimport com.google.common.collect.Iterables;\n\npublic class NovaEC2InstanceApiExpectTest extends BaseNovaEC2RestApiExpectTest {\n\n   public void testDescribeInstancesWithDashesInPlaceOfNullDates() {\n      InstanceApi client = requestsSendResponses(\n            describeAvailabilityZonesRequest,\n            describeAvailabilityZonesResponse,\n            HttpRequest.builder().method(\"POST\")\n                  .endpoint(\"http://localhost:8773/services/Cloud/\")\n                  .addHeader(\"Host\", \"localhost:8773\")\n                  .payload(payloadFromStringWithContentType(\"Action=DescribeInstances&Signature=kkCE1HzyntmkICEidOizw50B9yjLdNZvAWUXVse1c8o%3D&SignatureMethod=HmacSHA256&SignatureVersion=2&Timestamp=2012-04-16T15%3A54%3A08.897Z&Version=2009-04-04&AWSAccessKeyId=identity\", \"application/x-www-form-urlencoded\")).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/nova_ec2_describe_instances.xml\")).build()\n                                                    ).getInstanceApi().get();\n\n      Set<? extends Reservation<? extends RunningInstance>> response = client.describeInstancesInRegion(\"nova\");\n      \n      assertEquals(response.size(), 3);\n\n      Reservation<? extends RunningInstance> target = Iterables.get(response, 2);\n      RunningInstance runningInstance = Iterables.getOnlyElement(target);\n      BlockDevice bd = Iterables.getOnlyElement(runningInstance.getEbsBlockDevices().values());\n      \n      // this is a '-' in the nova_ec2_describe_instances.xml\n      assertNull(bd.getAttachTime());\n\n      // double-check the other fields\n      assertFalse(bd.isDeleteOnTermination());\n      assertEquals(bd.getVolumeId(), \"1\");\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova-ec2/src/test/java/org/jclouds/openstack/nova/ec2/features/NovaEC2InstanceApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.ec2.features;\n\nimport org.jclouds.ec2.features.InstanceApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"NovaEC2InstanceApiLiveTest\")\npublic class NovaEC2InstanceApiLiveTest extends InstanceApiLiveTest {\n   public NovaEC2InstanceApiLiveTest() {\n      provider = \"openstack-nova-ec2\";\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova-ec2/src/test/java/org/jclouds/openstack/nova/ec2/features/NovaEC2KeyPairApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.ec2.features;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.ec2.domain.KeyPair;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.nova.ec2.internal.BaseNovaEC2RestApiExpectTest;\nimport org.testng.annotations.Test;\n\npublic class NovaEC2KeyPairApiExpectTest extends BaseNovaEC2RestApiExpectTest {\n\n   public void testImportKeyPair() {\n      NovaEC2KeyPairApi client = requestsSendResponses(\n            describeAvailabilityZonesRequest,\n            describeAvailabilityZonesResponse,\n            HttpRequest.builder().method(\"POST\")\n                  .endpoint(\"http://localhost:8773/services/Cloud/\")\n                  .addHeader(\"Host\", \"localhost:8773\")\n                  .payload(payloadFromStringWithContentType(\"Action=ImportKeyPair&KeyName=mykey&PublicKeyMaterial=c3NoLXJzYSBBQQ%3D%3D&Signature=wOOKOlDfJezRkx7NKcyOyaBQuY7PoVE3HFa9495RL7s%3D&SignatureMethod=HmacSHA256&SignatureVersion=2&Timestamp=2012-04-16T15%3A54%3A08.897Z&Version=2009-04-04&AWSAccessKeyId=identity\", \"application/x-www-form-urlencoded\")).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/nova_ec2_import_keypair_response.xml\")).build()\n      ).getKeyPairApi().get();\n\n      KeyPair result = client.importKeyPairInRegion(null, \"mykey\", \"ssh-rsa AA\");\n      assertEquals(result.getKeyName(), \"aplowe-nova-ec22\");\n      assertEquals(result.getSha1OfPrivateKey(), \"e3:fd:de:f6:4c:36:7d:9b:8f:2f:4c:20:f8:ae:b0:ea\");\n   }\n\n   @Test(expectedExceptions = IllegalStateException.class)\n   public void testImportKeyPairFailsAlreadyExists() {\n      NovaEC2KeyPairApi client = requestsSendResponses(\n            describeAvailabilityZonesRequest,\n            describeAvailabilityZonesResponse,\n            HttpRequest.builder().method(\"POST\")\n                  .endpoint(\"http://localhost:8773/services/Cloud/\")\n                  .addHeader(\"Host\", \"localhost:8773\")\n                  .payload(payloadFromStringWithContentType(\"Action=ImportKeyPair&KeyName=mykey&PublicKeyMaterial=c3NoLXJzYSBBQQ%3D%3D&Signature=wOOKOlDfJezRkx7NKcyOyaBQuY7PoVE3HFa9495RL7s%3D&SignatureMethod=HmacSHA256&SignatureVersion=2&Timestamp=2012-04-16T15%3A54%3A08.897Z&Version=2009-04-04&AWSAccessKeyId=identity\", \"application/x-www-form-urlencoded\")).build(),\n            HttpResponse.builder().statusCode(409).build()\n      ).getKeyPairApi().get();\n\n      client.importKeyPairInRegion(null, \"mykey\", \"ssh-rsa AA\");\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova-ec2/src/test/java/org/jclouds/openstack/nova/ec2/features/NovaEC2KeyPairApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.ec2.features;\n\nimport static com.google.common.collect.Sets.newTreeSet;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.fail;\n\nimport java.io.IOException;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.SortedSet;\n\nimport org.jclouds.compute.ComputeTestUtils;\nimport org.jclouds.compute.internal.BaseComputeServiceContextLiveTest;\nimport org.jclouds.ec2.domain.KeyPair;\nimport org.jclouds.openstack.nova.ec2.NovaEC2Api;\nimport org.jclouds.ssh.SshKeys;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code NovaKeyPairApi}\n */\n@Test(groups = \"live\", singleThreaded = true)\npublic class NovaEC2KeyPairApiLiveTest extends BaseComputeServiceContextLiveTest {\n\n   public static final String PREFIX = System.getProperty(\"user.name\") + \"-nova-ec2\";\n\n   public NovaEC2KeyPairApiLiveTest() {\n      provider = \"openstack-nova-ec2\";\n   }\n\n   private NovaEC2KeyPairApi client;\n   private Set<String> regions;\n   \n   @Override\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   public void setupContext() {\n      super.setupContext();\n      client = view.unwrapApi(NovaEC2Api.class).getKeyPairApi().get();\n      regions = view.unwrapApi(NovaEC2Api.class).getAvailabilityZoneAndRegionApi().get().describeRegions().keySet();\n   }\n\n   @Test\n   void testDescribeKeyPairs() {\n      for (String region : regions) {\n         SortedSet<KeyPair> allResults = newTreeSet(client.describeKeyPairsInRegion(region));\n         assertNotNull(allResults);\n         if (allResults.size() >= 1) {\n            KeyPair pair = allResults.last();\n            SortedSet<KeyPair> result = newTreeSet(client.describeKeyPairsInRegion(region, pair.getKeyName()));\n            assertNotNull(result);\n            KeyPair compare = result.last();\n            assertEquals(compare, pair);\n         }\n      }\n   }\n\n   @Test\n   void testCreateKeyPair() {\n      String keyName = PREFIX + \"1\";\n      cleanupKeyPair(keyName);\n      try {\n         KeyPair keyPair = client.createKeyPairInRegion(null, keyName);\n         checkKeyPair(keyName, keyPair);\n         assertNotNull(keyPair.getKeyMaterial());\n      } finally {\n         cleanupKeyPair(keyName);\n      }\n   }\n\n   protected void cleanupKeyPair(String keyName) {\n      try {\n         client.deleteKeyPairInRegion(null, keyName);\n      } catch (Exception e) {\n\n      }\n      client.deleteKeyPairInRegion(null, keyName);\n   }\n\n   @Test\n   void testImportKeyPair() throws IOException {\n      String keyName = PREFIX + \"2\";\n      cleanupKeyPair(keyName);\n      Map<String, String> myKey = ComputeTestUtils.setupKeyPair();\n      try {\n         KeyPair keyPair = client.importKeyPairInRegion(null, keyName, myKey.get(\"public\"));\n         checkKeyPair(keyName, keyPair);\n\n         // check the fingerprint of public key (in the sha10OfPrivateKey field)\n         assertEquals(keyPair.getSha1OfPrivateKey(), SshKeys.fingerprintPublicKey(myKey.get(\"public\")));\n\n         // try again to see if there's an error\n         try {\n            client.importKeyPairInRegion(null, keyName, myKey.get(\"public\"));\n            fail(\"Duplicate call importKeyPairInRegion should have failed!\");\n         } catch (IllegalStateException e) {\n         }\n      } finally {\n         cleanupKeyPair(keyName);\n      }\n   }\n\n   protected void checkKeyPair(String keyName, KeyPair keyPair) {\n      assertNotNull(keyPair);\n      assertNotNull(keyPair.getSha1OfPrivateKey());\n      assertEquals(keyPair.getKeyName(), keyName);\n\n      Set<KeyPair> twoResults = client.describeKeyPairsInRegion(null, keyName);\n      assertNotNull(twoResults);\n      assertEquals(twoResults.size(), 1);\n      KeyPair listPair = twoResults.iterator().next();\n      assertEquals(listPair.getKeyName(), keyPair.getKeyName());\n      assertEquals(listPair.getSha1OfPrivateKey(), keyPair.getSha1OfPrivateKey());\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova-ec2/src/test/java/org/jclouds/openstack/nova/ec2/features/NovaEC2SecurityGroupApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.ec2.features;\n\nimport org.jclouds.ec2.features.SecurityGroupApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"NovaEC2SecurityGroupApiLiveTest\")\npublic class NovaEC2SecurityGroupApiLiveTest extends SecurityGroupApiLiveTest {\n   public NovaEC2SecurityGroupApiLiveTest() {\n      provider = \"openstack-nova-ec2\";\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova-ec2/src/test/java/org/jclouds/openstack/nova/ec2/features/NovaSubnetApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.ec2.features;\n\nimport org.jclouds.ec2.features.SubnetApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"NovaSubnetApiLiveTest\")\npublic class NovaSubnetApiLiveTest extends SubnetApiLiveTest {\n   public NovaSubnetApiLiveTest() {\n      provider = \"cloudstack-ec2\";\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova-ec2/src/test/java/org/jclouds/openstack/nova/ec2/internal/BaseNovaEC2RestApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.ec2.internal;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.nova.ec2.NovaEC2Api;\nimport org.jclouds.openstack.nova.ec2.config.NovaEC2HttpApiModule;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.internal.BaseRestApiExpectTest;\n\nimport com.google.inject.Module;\n\npublic abstract class BaseNovaEC2RestApiExpectTest extends BaseRestApiExpectTest<NovaEC2Api> {\n   protected static final String CONSTANT_DATE = \"2012-04-16T15:54:08.897Z\";\n   \n   protected DateService dateService = new SimpleDateFormatDateService();\n   protected URI endpoint = URI.create(\"http://localhost:8773/services/Cloud/\");\n\n   protected HttpRequest describeAvailabilityZonesRequest = HttpRequest\n            .builder()\n            .method(\"POST\")\n            .endpoint(endpoint)\n            .addHeader(\"Host\", \"localhost:8773\")\n            .payload(payloadFromStringWithContentType(\n                     \"Action=DescribeAvailabilityZones&Signature=S3fa5fybw4KAq4o11IpKHlqwx3cVJdKfeAKw3FIJYvM%3D&SignatureMethod=HmacSHA256&SignatureVersion=2&Timestamp=2012-04-16T15%3A54%3A08.897Z&Version=2009-04-04&AWSAccessKeyId=identity\",\n                     MediaType.APPLICATION_FORM_URLENCODED)).build();\n   protected HttpResponse describeAvailabilityZonesResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResourceWithContentType(\"/nova_ec2_availabilityZones.xml\", MediaType.APPLICATION_XML))\n            .build();\n\n   public BaseNovaEC2RestApiExpectTest() {\n      provider = \"openstack-nova-ec2\";\n   }\n\n   @ConfiguresHttpApi\n   private static final class TestNovaEC2HttpApiModule extends NovaEC2HttpApiModule {\n\n      @Override\n      protected String provideTimeStamp(DateService dateService) {\n         return CONSTANT_DATE;\n      }\n   }\n\n   @Override\n   protected Module createModule() {\n      return new TestNovaEC2HttpApiModule();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-nova-ec2/src/test/java/org/jclouds/openstack/nova/ec2/strategy/NovaReviseParsedImageTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.nova.ec2.strategy;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.compute.config.BaseComputeServiceContextModule;\nimport org.jclouds.compute.domain.ImageBuilder;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.ec2.compute.config.EC2ComputeServiceDependenciesModule;\nimport org.jclouds.ec2.compute.functions.EC2ImageParser;\nimport org.jclouds.ec2.compute.strategy.EC2PopulateDefaultLoginCredentialsForImageStrategy;\nimport org.jclouds.ec2.domain.Image;\nimport org.jclouds.ec2.xml.DescribeImagesResponseHandlerTest;\nimport org.jclouds.json.Json;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.openstack.nova.v2_0.compute.functions.ImageToOperatingSystem;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicates;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Sets;\nimport com.google.inject.Guice;\n\n@Test(groups = \"unit\", testName = \"NovaReviseParsedImageTest\")\npublic class NovaReviseParsedImageTest {\n\n   public void test() {\n\n      Set<org.jclouds.compute.domain.Image> result = convertImages(\"/nova_ec2_images.xml\");\n      assertEquals(result.size(), 7);\n\n      assertEquals(\n            Iterables.get(result, 4).toString(),\n            new ImageBuilder()\n                  .operatingSystem(\n                        OperatingSystem.builder().family(OsFamily.UBUNTU).arch(\"paravirtual\").version(\"10.10\")\n                              .name(\"Ubuntu Maverick 10.10 Server 64-bit 20111212\")\n                              .description(\"Ubuntu Maverick 10.10 Server 64-bit 20111212\").is64Bit(true)\n                              .build())\n                  .name(\"Ubuntu Maverick 10.10 Server 64-bit 20111212\")\n                  .description(\"\")\n                  .defaultCredentials(LoginCredentials.builder().user(\"root\").build())\n                  .id(\"us-east-1/ami-000004d6\")\n                  .providerId(\"ami-000004d6\")\n                  .location(defaultLocation)\n                  .status(org.jclouds.compute.domain.Image.Status.AVAILABLE)\n                  .backendStatus(\"available\")\n                  .userMetadata(\n                        ImmutableMap.of(\"owner\", \"\", \"rootDeviceType\", \"instance-store\", \"virtualizationType\",\n                              \"paravirtual\", \"hypervisor\", \"xen\")).build().toString());\n      assertEquals(Iterables.get(result, 4).getStatus(), org.jclouds.compute.domain.Image.Status.AVAILABLE);\n   }\n\n   static Location defaultLocation = new LocationBuilder().scope(LocationScope.REGION).id(\"us-east-1\").description(\n            \"us-east-1\").build();\n\n   public static Set<org.jclouds.compute.domain.Image> convertImages(String resource) {\n\n      Map<OsFamily, Map<String, String>> map = new BaseComputeServiceContextModule() {\n      }.provideOsVersionMap(new ComputeServiceConstants.ReferenceData(), Guice.createInjector(new GsonModule())\n               .getInstance(Json.class));\n\n      Set<Image> result = DescribeImagesResponseHandlerTest.parseImages(resource);\n      EC2ImageParser parser = new EC2ImageParser(EC2ComputeServiceDependenciesModule.toPortableImageStatus,\n               new EC2PopulateDefaultLoginCredentialsForImageStrategy(), map, Suppliers\n                        .<Set<? extends Location>> ofInstance(ImmutableSet.<Location> of(defaultLocation)), Suppliers\n                        .ofInstance(defaultLocation), new NovaReviseParsedImage(new ImageToOperatingSystem(map)));\n      return Sets.newLinkedHashSet(Iterables.filter(Iterables.transform(result, parser), Predicates.notNull()));\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-nova-ec2/src/test/resources/nova_ec2_availabilityZones.xml",
    "content": "<?xml version=\"1.0\" ?>\n<DescribeAvailabilityZonesResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-04-04/\">\n    <requestId>req-a6cd42f8-b5e5-4c94-a1e0-41d21ea0a032</requestId>\n    <availabilityZoneInfo>\n        <item>\n            <zoneState>available</zoneState>\n            <zoneName>nova</zoneName>\n        </item>\n    </availabilityZoneInfo>\n</DescribeAvailabilityZonesResponse>"
  },
  {
    "path": "apis/openstack-nova-ec2/src/test/resources/nova_ec2_describe_instances.xml",
    "content": "<?xml version=\"1.0\" ?>\n<DescribeInstancesResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-04-04/\">\n    <requestId>req-a68563bb-034e-4a32-aac7-5126e041cf91</requestId>\n    <reservationSet>\n        <item>\n            <ownerId>2b25129754c145de8426896b09a42106</ownerId>\n            <groupSet>\n                <item>\n                    <groupId>default</groupId>\n                </item>\n            </groupSet>\n            <reservationId>r-1jywe5ye</reservationId>\n            <instancesSet>\n                <item>\n                    <placement>\n                        <availabilityZone>nova</availabilityZone>\n                    </placement>\n                    <rootDeviceType>instance-store</rootDeviceType>\n                    <keyName>None (2b25129754c145de8426896b09a42106, ubuntu)</keyName>\n                    <instanceId>i-00000003</instanceId>\n                    <instanceState>\n                        <code>16</code>\n                        <name>running</name>\n                    </instanceState>\n                    <publicDnsName/>\n                    <imageId>ami-00000001</imageId>\n                    <productCodesSet/>\n                    <privateDnsName>mishdemo</privateDnsName>\n                    <dnsName>mishdemo</dnsName>\n                    <launchTime>2012-05-02T06:59:59.000Z</launchTime>\n                    <amiLaunchIndex>0</amiLaunchIndex>\n                    <rootDeviceName>/dev/vda</rootDeviceName>\n                    <kernelId>aki-00000002</kernelId>\n                    <ramdiskId>ari-00000003</ramdiskId>\n                    <ipAddress>10.77.22.4</ipAddress>\n                    <instanceType>m1.small</instanceType>\n                    <privateIpAddress>10.77.22.4</privateIpAddress>\n                </item>\n            </instancesSet>\n        </item>\n        <item>\n            <ownerId>d8f0cd49971a44d187b454e14921056d</ownerId>\n            <groupSet>\n                <item>\n                    <groupId>default</groupId>\n                </item>\n            </groupSet>\n            <reservationId>r-pctvv0ey</reservationId>\n            <instancesSet>\n                <item>\n                    <placement>\n                        <availabilityZone>nova</availabilityZone>\n                    </placement>\n                    <rootDeviceType>instance-store</rootDeviceType>\n                    <keyName>None (d8f0cd49971a44d187b454e14921056d, ubuntu)</keyName>\n                    <instanceId>i-00000001</instanceId>\n                    <instanceState>\n                        <code>16</code>\n                        <name>running</name>\n                    </instanceState>\n                    <publicDnsName/>\n                    <imageId>ami-00000001</imageId>\n                    <productCodesSet/>\n                    <privateDnsName>avi-server1</privateDnsName>\n                    <dnsName>avi-server1</dnsName>\n                    <launchTime>2012-05-01T09:18:37.000Z</launchTime>\n                    <amiLaunchIndex>0</amiLaunchIndex>\n                    <rootDeviceName>/dev/vda</rootDeviceName>\n                    <kernelId>aki-00000002</kernelId>\n                    <ramdiskId>ari-00000003</ramdiskId>\n                    <ipAddress>10.77.22.2</ipAddress>\n                    <instanceType>m1.tiny</instanceType>\n                    <privateIpAddress>10.77.22.2</privateIpAddress>\n                </item>\n            </instancesSet>\n        </item>\n        <item>\n            <ownerId>d8f0cd49971a44d187b454e14921056d</ownerId>\n            <groupSet>\n                <item>\n                    <groupId>default</groupId>\n                </item>\n                <item>\n                    <groupId>avi-sg1</groupId>\n                </item>\n            </groupSet>\n            <reservationId>r-0iwpw2u8</reservationId>\n            <instancesSet>\n                <item>\n                    <blockDeviceMapping>\n                        <item>\n                            <deviceName>/dev/vdc</deviceName>\n                            <ebs>\n                                <status>in-use</status>\n                                <deleteOnTermination>false</deleteOnTermination>\n                                <volumeId>1</volumeId>\n                                <attachTime>-</attachTime>\n                            </ebs>\n                        </item>\n                    </blockDeviceMapping>\n                    <placement>\n                        <availabilityZone>nova</availabilityZone>\n                    </placement>\n                    <rootDeviceType>instance-store</rootDeviceType>\n                    <keyName>avi-kp1 (d8f0cd49971a44d187b454e14921056d, ubuntu)</keyName>\n                    <instanceId>i-00000002</instanceId>\n                    <instanceState>\n                        <code>16</code>\n                        <name>running</name>\n                    </instanceState>\n                    <publicDnsName/>\n                    <imageId>ami-00000001</imageId>\n                    <productCodesSet/>\n                    <privateDnsName>avi-server2</privateDnsName>\n                    <dnsName>avi-server2</dnsName>\n                    <launchTime>2012-05-01T09:22:26.000Z</launchTime>\n                    <amiLaunchIndex>0</amiLaunchIndex>\n                    <rootDeviceName>/dev/vda</rootDeviceName>\n                    <kernelId>aki-00000002</kernelId>\n                    <ramdiskId>ari-00000003</ramdiskId>\n                    <ipAddress>10.77.22.3</ipAddress>\n                    <instanceType>m1.tiny</instanceType>\n                    <privateIpAddress>10.77.22.3</privateIpAddress>\n                </item>\n            </instancesSet>\n        </item>\n    </reservationSet>\n</DescribeInstancesResponse>"
  },
  {
    "path": "apis/openstack-nova-ec2/src/test/resources/nova_ec2_describe_volumes.xml",
    "content": "<?xml version=\"1.0\" ?>\n<DescribeVolumesResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-04-04/\">\n    <requestId>req-9e45299b-980d-4893-a475-a574b1a94ed5</requestId>\n    <volumeSet>\n        <item>\n            <status>available (f06de98af01446b2ae6bd79f5fbf3b2a, att-openstack1, None, None)</status>\n            <availabilityZone>nova</availabilityZone>\n            <volumeId>vol-00000007</volumeId>\n            <attachmentSet>\n                <item/>\n            </attachmentSet>\n            <snapshotId/>\n            <createTime>2012-04-10T10:39:52.000Z</createTime>\n            <size>1</size>\n        </item>\n    </volumeSet>\n</DescribeVolumesResponse>"
  },
  {
    "path": "apis/openstack-nova-ec2/src/test/resources/nova_ec2_images.xml",
    "content": "<?xml version=\"1.0\" ?>\n<DescribeImagesResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-04-04/\">\n    <requestId>b5ad23de-f77d-\n        4b66-bfc2-ab01ceccb97b</requestId>\n    <imagesSet>\n        <item>\n            <displayName>Debian Squeeze 6.0.3 Server 64-bit 20120123</displayName>\n            <description />\n            <imageOwnerId />\n            <isPublic>true</isPublic>\n            <imageId>ami-00000551</imageId>\n            <imageState>available</imageState>\n            <rootDeviceType>instance-store</rootDeviceType>\n            <architecture>amd64</architecture>\n            <imageLocation>local (Debian Squeeze 6.0.3 Server 64-bit\n                20120123)</imageLocation>\n            <kernelId>aki-0000054f</kernelId>\n            <ramdiskId>ari-00000550</ramdiskId>\n            <rootDeviceName>/dev/sda1</rootDeviceName>\n            <imageType>machine</imageType>\n        </item>\n        <item>\n            <displayName>Debian Squeeze 6.0.3 Server 64-bit 20120123\n                (Ramdisk)</displayName>\n            <description />\n            <imageOwnerId />\n            <isPublic>true</isPublic>\n            <imageId>ari-00000550</imageId>\n            <imageState>available</imageState>\n            <architecture>amd64</architecture>\n            <imageLocation>local (Debian Squeeze 6.0.3 Server 64-bit\n                20120123 (Ramdisk))</imageLocation>\n            <rootDeviceType>instance-store</rootDeviceType>\n            <rootDeviceName>/dev/sda1</rootDeviceName>\n            <imageType>ramdisk</imageType>\n        </item>\n        <item>\n            <displayName>Debian Squeeze 6.0.3 Server 64-bit 20120123\n                (Kernel)</displayName>\n            <description />\n            <imageOwnerId />\n            <isPublic>true</isPublic>\n            <imageId>aki-0000054f</imageId>\n            <imageState>available</imageState>\n            <architecture>amd64</architecture>\n            <imageLocation>local (Debian Squeeze 6.0.3 Server 64-bit\n                20120123 (Kernel))</imageLocation>\n            <rootDeviceType>instance-store</rootDeviceType>\n            <rootDeviceName>/dev/sda1</rootDeviceName>\n            <imageType>kernel</imageType>\n        </item>\n        <item>\n            <displayName>CentOS 6.2 Server 64-bit 20120125</displayName>\n            <description />\n            <imageOwnerId />\n            <isPublic>true</isPublic>\n            <imageId>ami-0000054e</imageId>\n            <imageState>available</imageState>\n            <rootDeviceType>instance-store</rootDeviceType>\n            <architecture>x86_64</architecture>\n            <imageLocation>local (CentOS 6.2 Server 64-bit 20120125)</imageLocation>\n            <kernelId>aki-0000054c</kernelId>\n            <ramdiskId>ari-0000054d</ramdiskId>\n            <rootDeviceName>/dev/sda1</rootDeviceName>\n            <imageType>machine</imageType>\n        </item>\n        <item>\n            <displayName>CentOS 6.2 Server 64-bit 20120125 (Ramdisk)</displayName>\n            <description />\n            <imageOwnerId />\n            <isPublic>true</isPublic>\n            <imageId>ari-0000054d</imageId>\n            <imageState>available</imageState>\n            <architecture>x86_64</architecture>\n            <imageLocation>local (CentOS 6.2 Server 64-bit 20120125\n                (Ramdisk))</imageLocation>\n            <rootDeviceType>instance-store</rootDeviceType>\n            <rootDeviceName>/dev/sda1</rootDeviceName>\n            <imageType>ramdisk</imageType>\n        </item>\n        <item>\n            <displayName>CentOS 6.2 Server 64-bit 20120125 (Kernel)</displayName>\n            <description />\n            <imageOwnerId />\n            <isPublic>true</isPublic>\n            <imageId>aki-0000054c</imageId>\n            <imageState>available</imageState>\n            <architecture>x86_64</architecture>\n            <imageLocation>local (CentOS 6.2 Server 64-bit 20120125\n                (Kernel))</imageLocation>\n            <rootDeviceType>instance-store</rootDeviceType>\n            <rootDeviceName>/dev/sda1</rootDeviceName>\n            <imageType>kernel</imageType>\n        </item>\n        <item>\n            <displayName>Ubuntu Oneiric 11.10 Server 64-bit 20111212</displayName>\n            <description />\n            <imageOwnerId />\n            <isPublic>true</isPublic>\n            <imageId>ami-000004da</imageId>\n            <imageState>available</imageState>\n            <rootDeviceType>instance-store</rootDeviceType>\n            <architecture>amd64</architecture>\n            <imageLocation>local (Ubuntu Oneiric 11.10 Server 64-bit\n                20111212)</imageLocation>\n            <kernelId>aki-000004d9</kernelId>\n            <rootDeviceName>/dev/sda1</rootDeviceName>\n            <imageType>machine</imageType>\n        </item>\n        <item>\n            <displayName>Ubuntu Oneiric 11.10 Server 64-bit 20111212\n                (Kernel)</displayName>\n            <description />\n            <imageOwnerId />\n            <isPublic>true</isPublic>\n            <imageId>aki-000004d9</imageId>\n            <imageState>available</imageState>\n            <architecture>amd64</architecture>\n            <imageLocation>local (Ubuntu Oneiric 11.10 Server 64-bit\n                20111212 (Kernel))</imageLocation>\n            <rootDeviceType>instance-store</rootDeviceType>\n            <rootDeviceName>/dev/sda1</rootDeviceName>\n            <imageType>kernel</imageType>\n        </item>\n        <item>\n            <displayName>Ubuntu Natty 11.04 Server 64-bit 20111212</displayName>\n            <description />\n            <imageOwnerId />\n            <isPublic>true</isPublic>\n            <imageId>ami-000004d8</imageId>\n            <imageState>available</imageState>\n            <rootDeviceType>instance-store</rootDeviceType>\n            <architecture>amd64</architecture>\n            <imageLocation>local (Ubuntu Natty 11.04 Server 64-bit\n                20111212)</imageLocation>\n            <kernelId>aki-000004d7</kernelId>\n            <rootDeviceName>/dev/sda1</rootDeviceName>\n            <imageType>machine</imageType>\n        </item>\n        <item>\n            <displayName>Ubuntu Natty 11.04 Server 64-bit 20111212\n                (Kernel)</displayName>\n            <description />\n            <imageOwnerId />\n            <isPublic>true</isPublic>\n            <imageId>aki-000004d7</imageId>\n            <imageState>available</imageState>\n            <architecture>amd64</architecture>\n            <imageLocation>local (Ubuntu Natty 11.04 Server 64-bit\n                20111212 (Kernel))</imageLocation>\n            <rootDeviceType>instance-store</rootDeviceType>\n            <rootDeviceName>/dev/sda1</rootDeviceName>\n            <imageType>kernel</imageType>\n        </item>\n        <item>\n            <displayName>Ubuntu Maverick 10.10 Server 64-bit 20111212</displayName>\n            <description />\n            <imageOwnerId />\n            <isPublic>true</isPublic>\n            <imageId>ami-000004d6</imageId>\n            <imageState>available</imageState>\n            <rootDeviceType>instance-store</rootDeviceType>\n            <architecture>amd64</architecture>\n            <imageLocation>local (Ubuntu Maverick 10.10 Server 64-bit\n                20111212)</imageLocation>\n            <kernelId>aki-000004d5</kernelId>\n            <rootDeviceName>/dev/sda1</rootDeviceName>\n            <imageType>machine</imageType>\n        </item>\n        <item>\n            <displayName>Ubuntu Maverick 10.10 Server 64-bit 20111212\n                (Kernel)</displayName>\n            <description />\n            <imageOwnerId />\n            <isPublic>true</isPublic>\n            <imageId>aki-000004d5</imageId>\n            <imageState>available</imageState>\n            <architecture>amd64</architecture>\n            <imageLocation>local (Ubuntu Maverick 10.10 Server 64-bit\n                20111212 (Kernel))</imageLocation>\n            <rootDeviceType>instance-store</rootDeviceType>\n            <rootDeviceName>/dev/sda1</rootDeviceName>\n            <imageType>kernel</imageType>\n        </item>\n        <item>\n            <displayName>Ubuntu Lucid 10.04 LTS Server 64-bit 20111212</displayName>\n            <description />\n            <imageOwnerId />\n            <isPublic>true</isPublic>\n            <imageId>ami-000004d4</imageId>\n            <imageState>available</imageState>\n            <rootDeviceType>instance-store</rootDeviceType>\n            <architecture>amd64</architecture>\n            <imageLocation>local (Ubuntu Lucid 10.04 LTS Server 64-bit\n                20111212)</imageLocation>\n            <kernelId>aki-000004d3</kernelId>\n            <rootDeviceName>/dev/sda1</rootDeviceName>\n            <imageType>machine</imageType>\n        </item>\n        <item>\n            <displayName>Ubuntu Lucid 10.04 LTS Server 64-bit 20111212\n                (Kernel)</displayName>\n            <description />\n            <imageOwnerId />\n            <isPublic>true</isPublic>\n            <imageId>aki-000004d3</imageId>\n            <imageState>available</imageState>\n            <architecture>amd64</architecture>\n            <imageLocation>local (Ubuntu Lucid 10.04 LTS Server 64-bit\n                20111212 (Kernel))</imageLocation>\n            <rootDeviceType>instance-store</rootDeviceType>\n            <rootDeviceName>/dev/sda1</rootDeviceName>\n            <imageType>kernel</imageType>\n        </item>\n        <item>\n            <displayName>CentOS 5.6 Server 64-bit 20111207</displayName>\n            <description />\n            <imageOwnerId />\n            <isPublic>true</isPublic>\n            <imageId>ami-000004d2</imageId>\n            <imageState>available</imageState>\n            <rootDeviceType>instance-store</rootDeviceType>\n            <architecture>x86_64</architecture>\n            <imageLocation>local (CentOS 5.6 Server 64-bit 20111207)</imageLocation>\n            <kernelId>aki-000004d0</kernelId>\n            <ramdiskId>ari-000004d1</ramdiskId>\n            <rootDeviceName>/dev/sda1</rootDeviceName>\n            <imageType>machine</imageType>\n        </item>\n        <item>\n            <displayName>CentOS 5.6 Server 64-bit 20111207 (Ramdisk)</displayName>\n            <description />\n            <imageOwnerId />\n            <isPublic>true</isPublic>\n            <imageId>ari-000004d1</imageId>\n            <imageState>available</imageState>\n            <architecture>x86_64</architecture>\n            <imageLocation>local (CentOS 5.6 Server 64-bit 20111207\n                (Ramdisk))</imageLocation>\n            <rootDeviceType>instance-store</rootDeviceType>\n            <rootDeviceName>/dev/sda1</rootDeviceName>\n            <imageType>ramdisk</imageType>\n        </item>\n        <item>\n            <displayName>CentOS 5.6 Server 64-bit 20111207 (Kernel)</displayName>\n            <description />\n            <imageOwnerId />\n            <isPublic>true</isPublic>\n            <imageId>aki-000004d0</imageId>\n            <imageState>available</imageState>\n            <architecture>x86_64</architecture>\n            <imageLocation>local (CentOS 5.6 Server 64-bit 20111207\n                (Kernel))</imageLocation>\n            <rootDeviceType>instance-store</rootDeviceType>\n            <rootDeviceName>/dev/sda1</rootDeviceName>\n            <imageType>kernel</imageType>\n        </item>\n    </imagesSet>\n</DescribeImagesResponse>"
  },
  {
    "path": "apis/openstack-nova-ec2/src/test/resources/nova_ec2_images_with_ramdisk.xml",
    "content": "<?xml version=\"1.0\" ?>\n<DescribeImagesResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-04-04/\">\n    <requestId>req-bfdac708-c6c4-48fb-9cba-be5bb0a05b49</requestId>\n    <imagesSet>\n        <item>\n            <description/>\n            <imageOwnerId/>\n            <isPublic>true</isPublic>\n            <imageId>aki-00000002</imageId>\n            <imageState>available</imageState>\n            <architecture/>\n            <imageLocation>None (cirros-0.3.0-x86_64-blank-kernel)</imageLocation>\n            <rootDeviceType>instance-store</rootDeviceType>\n            <rootDeviceName>/dev/sda1</rootDeviceName>\n            <imageType>kernel</imageType>\n            <name>cirros-0.3.0-x86_64-blank-kernel</name>\n        </item>\n        <item>\n            <description/>\n            <imageOwnerId/>\n            <isPublic>true</isPublic>\n            <imageId>ari-00000003</imageId>\n            <imageState>available</imageState>\n            <architecture/>\n            <imageLocation>None (cirros-0.3.0-x86_64-blank-ramdisk)</imageLocation>\n            <rootDeviceType>instance-store</rootDeviceType>\n            <rootDeviceName>/dev/sda1</rootDeviceName>\n            <imageType>ramdisk</imageType>\n            <name>cirros-0.3.0-x86_64-blank-ramdisk</name>\n        </item>\n        <item>\n            <name>cirros-0.3.0-x86_64-blank</name>\n            <imageOwnerId/>\n            <isPublic>true</isPublic>\n            <imageId>ami-00000001</imageId>\n            <imageState>available</imageState>\n            <rootDeviceType>instance-store</rootDeviceType>\n            <architecture/>\n            <imageLocation>None (cirros-0.3.0-x86_64-blank)</imageLocation>\n            <kernelId>aki-00000002</kernelId>\n            <ramdiskId>ari-00000003</ramdiskId>\n            <rootDeviceName>/dev/sda1</rootDeviceName>\n            <imageType>machine</imageType>\n            <description/>\n        </item>\n    </imagesSet>\n</DescribeImagesResponse>"
  },
  {
    "path": "apis/openstack-nova-ec2/src/test/resources/nova_ec2_import_keypair_response.xml",
    "content": "<?xml version=\"1.0\" ?>\n<ImportKeyPairResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-04-04/\">\n    <requestId>req-dd54edc5-4beb-4b40-9694-0209fcf50459</requestId>\n    <keyName>aplowe-nova-ec22</keyName>\n    <keyFingerprint>e3:fd:de:f6:4c:36:7d:9b:8f:2f:4c:20:f8:ae:b0:ea</keyFingerprint>\n</ImportKeyPairResponse>\n"
  },
  {
    "path": "apis/openstack-swift/README.md",
    "content": "OpenStack Swift\n===============\n\nSwift is a distributed object storage system designed to scale from a single machine to thousands of servers.\n\nProduction ready?\nBeta\n\nThis API is new to jclouds and hence is in Beta. That means we need people to use it and give us feedback. Based on that feedback, minor changes to the interfaces may happen. This code will replace org.jclouds.openstack.swift.SwiftClient in jclouds 2.0 and it is recommended you adopt it sooner than later.\n\n"
  },
  {
    "path": "apis/openstack-swift/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.openstack.swift.v1.*;version=\"${project.version}\";-noimport:=true"
  },
  {
    "path": "apis/openstack-swift/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n\n  <groupId>org.apache.jclouds.api</groupId>\n  <artifactId>openstack-swift</artifactId>\n  <name>jclouds openstack-swift api</name>\n  <description>jclouds components to access an implementation of OpenStack Swift</description>\n\n  <properties>\n    <!-- keystone endpoint -->\n    <test.openstack-swift.endpoint>http://localhost:5000/v2.0/</test.openstack-swift.endpoint>\n    <test.openstack-swift.api-version>1.0</test.openstack-swift.api-version>\n    <test.openstack-swift.build-version />\n    <test.openstack-swift.identity>FIXME_IDENTITY</test.openstack-swift.identity>\n    <test.openstack-swift.credential>FIXME_CREDENTIALS</test.openstack-swift.credential>\n    <test.jclouds.keystone.credential-type>passwordCredentials</test.jclouds.keystone.credential-type>\n    <jclouds.blobstore.httpstream.url>https://archive.apache.org/dist/commons/logging/binaries/commons-logging-1.1.1-bin.tar.gz</jclouds.blobstore.httpstream.url>\n    <jclouds.blobstore.httpstream.md5>e5de09672af9b386c30a311654d8541a</jclouds.blobstore.httpstream.md5>\n    <test.blobstore.await-consistency-timeout-seconds>30</test.blobstore.await-consistency-timeout-seconds>\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-keystone</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-blobstore</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-keystone</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-blobstore</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.jboss.shrinkwrap</groupId>\n      <artifactId>shrinkwrap-depchain</artifactId>\n      <version>1.2.0</version>\n      <type>pom</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-slf4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>ch.qos.logback</groupId>\n      <artifactId>logback-classic</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.squareup.okhttp3</groupId>\n      <artifactId>mockwebserver</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.value</groupId>\n      <artifactId>auto-value</artifactId>\n      <scope>provided</scope>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.openstack-swift.endpoint>${test.openstack-swift.endpoint}</test.openstack-swift.endpoint>\n                    <test.openstack-swift.api-version>${test.openstack-swift.api-version}</test.openstack-swift.api-version>\n                    <test.openstack-swift.build-version>${test.openstack-swift.build-version}</test.openstack-swift.build-version>\n                    <test.openstack-swift.identity>${test.openstack-swift.identity}</test.openstack-swift.identity>\n                    <test.openstack-swift.credential>${test.openstack-swift.credential}</test.openstack-swift.credential>\n                    <test.jclouds.keystone.credential-type>${test.jclouds.keystone.credential-type}</test.jclouds.keystone.credential-type>\n                    <jclouds.blobstore.httpstream.url>${jclouds.blobstore.httpstream.url}</jclouds.blobstore.httpstream.url>\n                    <jclouds.blobstore.httpstream.md5>${jclouds.blobstore.httpstream.md5}</jclouds.blobstore.httpstream.md5>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/SwiftApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1;\n\nimport java.io.Closeable;\nimport java.util.Set;\n\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\n\nimport org.jclouds.location.Region;\nimport org.jclouds.location.functions.RegionToEndpoint;\nimport org.jclouds.openstack.swift.v1.features.AccountApi;\nimport org.jclouds.openstack.swift.v1.features.BulkApi;\nimport org.jclouds.openstack.swift.v1.features.ContainerApi;\nimport org.jclouds.openstack.swift.v1.features.DynamicLargeObjectApi;\nimport org.jclouds.openstack.swift.v1.features.ObjectApi;\nimport org.jclouds.openstack.swift.v1.features.StaticLargeObjectApi;\nimport org.jclouds.rest.annotations.Delegate;\nimport org.jclouds.rest.annotations.EndpointParam;\n\nimport com.google.common.annotations.Beta;\nimport com.google.inject.Provides;\n\n/**\n * Provides access to the OpenStack Object Storage (Swift) API.\n * <p/>\n * OpenStack Object Storage is an object-based storage system that stores content and metadata\n * as objects. You create, modify, and get objects and metadata using this API.\n * <p/>\n */\n@Beta\npublic interface SwiftApi extends Closeable {\n\n   @Provides\n   @Region\n   Set<String> getConfiguredRegions();\n\n   @Delegate\n   AccountApi getAccountApi(@EndpointParam(parser = RegionToEndpoint.class) String region);\n\n   @Delegate\n   BulkApi getBulkApi(@EndpointParam(parser = RegionToEndpoint.class) String region);\n\n   @Delegate\n   ContainerApi getContainerApi(@EndpointParam(parser = RegionToEndpoint.class) String region);\n\n   @Delegate\n   @Path(\"/{containerName}\")\n   ObjectApi getObjectApi(@EndpointParam(parser = RegionToEndpoint.class) String region,\n         @PathParam(\"containerName\") String containerName);\n\n   @Delegate\n   @Path(\"/{containerName}\")\n   StaticLargeObjectApi getStaticLargeObjectApi(@EndpointParam(parser = RegionToEndpoint.class) String region,\n         @PathParam(\"containerName\") String containerName);\n\n   @Delegate\n   @Path(\"/{containerName}\")\n   DynamicLargeObjectApi getDynamicLargeObjectApi(@EndpointParam(parser = RegionToEndpoint.class) String region,\n         @PathParam(\"containerName\") String containerName);\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/SwiftApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1;\n\nimport static org.jclouds.Constants.PROPERTY_IDEMPOTENT_METHODS;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.CREDENTIAL_TYPE;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.KEYSTONE_VERSION;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.SERVICE_TYPE;\nimport static org.jclouds.openstack.swift.v1.reference.TempAuthHeaders.DEFAULT_HEADER_PASS;\nimport static org.jclouds.openstack.swift.v1.reference.TempAuthHeaders.DEFAULT_HEADER_USER;\nimport static org.jclouds.openstack.swift.v1.reference.TempAuthHeaders.TEMP_AUTH_HEADER_PASS;\nimport static org.jclouds.openstack.swift.v1.reference.TempAuthHeaders.TEMP_AUTH_HEADER_USER;\nimport static org.jclouds.reflect.Reflection2.typeToken;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.openstack.keystone.auth.config.CredentialTypes;\nimport org.jclouds.openstack.keystone.catalog.config.ServiceCatalogModule;\nimport org.jclouds.openstack.keystone.catalog.config.ServiceCatalogModule.RegionModule;\nimport org.jclouds.openstack.swift.v1.blobstore.RegionScopedBlobStoreContext;\nimport org.jclouds.openstack.swift.v1.blobstore.config.SignUsingTemporaryUrls;\nimport org.jclouds.openstack.swift.v1.blobstore.config.SwiftBlobStoreContextModule;\nimport org.jclouds.openstack.swift.v1.config.SwiftAuthenticationModule;\nimport org.jclouds.openstack.swift.v1.config.SwiftHttpApiModule;\nimport org.jclouds.openstack.swift.v1.config.SwiftTypeAdapters;\nimport org.jclouds.openstack.v2_0.ServiceType;\nimport org.jclouds.rest.internal.BaseHttpApiMetadata;\n\nimport com.google.auto.service.AutoService;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n@AutoService(ApiMetadata.class)\npublic class SwiftApiMetadata extends BaseHttpApiMetadata<SwiftApi> {\n\n   @Override\n   public Builder toBuilder() {\n      return new Builder().fromApiMetadata(this);\n   }\n\n   public SwiftApiMetadata() {\n      this(new Builder());\n   }\n\n   protected SwiftApiMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = BaseHttpApiMetadata.defaultProperties();\n      properties.setProperty(SERVICE_TYPE, ServiceType.OBJECT_STORE);\n      properties.setProperty(KEYSTONE_VERSION, \"2\");\n      properties.setProperty(PROPERTY_IDEMPOTENT_METHODS, \"DELETE,GET,HEAD,OPTIONS,POST,PUT\");\n      // Can alternatively be set to \"tempAuthCredentials\"\n      properties.setProperty(CREDENTIAL_TYPE, CredentialTypes.PASSWORD_CREDENTIALS);\n      properties.setProperty(TEMP_AUTH_HEADER_USER, DEFAULT_HEADER_USER);\n      properties.setProperty(TEMP_AUTH_HEADER_PASS, DEFAULT_HEADER_PASS);\n      return properties;\n   }\n\n   public static class Builder extends BaseHttpApiMetadata.Builder<SwiftApi, Builder> {\n\n      protected Builder() {\n          id(\"openstack-swift\")\n         .name(\"OpenStack Swift API\")\n         .identityName(\"${tenantName}:${userName} or ${userName}, if your keystone supports a default tenant\")\n         .credentialName(\"${password}\")\n         .documentation(URI.create(\"http://docs.openstack.org/api/openstack-object-storage/1.0/content/ch_object-storage-dev-overview.html\"))\n         .version(\"1\")\n         .endpointName(\"Keystone base url ending in /v2.0/ or TempAuth url ending in auth/v1.0/\")\n         .defaultEndpoint(\"http://localhost:5000/v2.0/\")\n         .defaultProperties(SwiftApiMetadata.defaultProperties())\n         .view(typeToken(RegionScopedBlobStoreContext.class))\n         .defaultModules(ImmutableSet.<Class<? extends Module>>builder()\n                                     .add(SwiftAuthenticationModule.class)\n                                     .add(ServiceCatalogModule.class)\n                                     .add(RegionModule.class)\n                                     .add(SwiftTypeAdapters.class)\n                                     .add(SwiftHttpApiModule.class)\n                                     .add(SwiftBlobStoreContextModule.class)\n                                     .add(SignUsingTemporaryUrls.class).build());\n      }\n\n      @Override\n      public SwiftApiMetadata build() {\n         return new SwiftApiMetadata(this);\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/SwiftFallbacks.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Predicates.equalTo;\nimport static com.google.common.base.Throwables.propagate;\nimport static org.jclouds.http.HttpUtils.contains404;\nimport static org.jclouds.http.HttpUtils.returnValueOnCodeOrNull;\n\nimport org.jclouds.Fallback;\n\npublic final class SwiftFallbacks {\n\n   public static final class TrueOn404FalseOn409 implements Fallback<Boolean> {\n      @Override\n      public Boolean createOrPropagate(Throwable t) throws Exception {\n         if (contains404(checkNotNull(t, \"throwable\")))\n            return true;\n         if (returnValueOnCodeOrNull(t, false, equalTo(409)) != null)\n            return false;\n         throw propagate(t);\n      }\n   }\n\n   private SwiftFallbacks() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/TemporaryUrlSigner.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.common.base.Suppliers.memoizeWithExpiration;\nimport static com.google.common.base.Throwables.propagate;\nimport static com.google.common.io.BaseEncoding.base16;\nimport static java.lang.String.format;\nimport static java.util.concurrent.TimeUnit.SECONDS;\n\nimport javax.crypto.Mac;\nimport javax.crypto.spec.SecretKeySpec;\n\nimport org.jclouds.openstack.swift.v1.features.AccountApi;\n\nimport com.google.common.base.Supplier;\n\n/**\n * Use this utility to create temporary urls.\n */\npublic class TemporaryUrlSigner {\n\n   public static TemporaryUrlSigner checkApiEvery(final AccountApi api, long seconds) {\n      Supplier<String> keySupplier = memoizeWithExpiration(new TemporaryUrlKeyFromAccount(api), seconds, SECONDS);\n      return new TemporaryUrlSigner(keySupplier);\n   }\n\n   private final Supplier<String> keySupplier;\n\n   TemporaryUrlSigner(Supplier<String> keySupplier) {\n      this.keySupplier = keySupplier;\n   }\n\n   public String sign(String method, String path, long expirationTimestampSeconds) {\n      checkNotNull(method, \"method\");\n      checkNotNull(path, \"path\");\n      checkArgument(expirationTimestampSeconds > 0, \"expirationTimestamp must be a unix epoch timestamp\");\n      String hmacBody = format(\"%s\\n%s\\n%s\", method, expirationTimestampSeconds, path);\n      return base16().lowerCase().encode(hmacSHA1(hmacBody));\n   }\n\n   byte[] hmacSHA1(String data) {\n      try {\n         String key = keySupplier.get();\n         checkState(key != null, \"%s returned a null temporaryUrlKey!\", keySupplier);\n         Mac mac = Mac.getInstance(\"HmacSHA1\");\n         mac.init(new SecretKeySpec(key.getBytes(UTF_8), \"HmacSHA1\"));\n         return mac.doFinal(data.getBytes(UTF_8));\n      } catch (Exception e) {\n         throw propagate(e);\n      }\n   }\n\n   static class TemporaryUrlKeyFromAccount implements Supplier<String> {\n      private final AccountApi api;\n\n      private TemporaryUrlKeyFromAccount(AccountApi api) {\n         this.api = checkNotNull(api, \"accountApi\");\n      }\n\n      @Override\n      public String get() {\n         return api.get().getTemporaryUrlKey().orNull();\n      }\n\n      @Override\n      public String toString() {\n         return format(\"get().getTemporaryUrlKey() using %s\", api);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/binders/BindMetadataToHeaders.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.binders;\n\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.ACCOUNT_METADATA_PREFIX;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.CONTAINER_METADATA_PREFIX;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.OBJECT_METADATA_PREFIX;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\nimport java.util.Map.Entry;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableMultimap.Builder;\n\n/**\n * Will lower-case header keys due to a swift implementation to return headers\n * in a different case than sent. ex.\n *\n * <pre>\n * >> X-Account-Meta-MyDelete1: foo\n * >> X-Account-Meta-MyDelete2: bar\n * </pre>\n *\n * results in:\n *\n * <pre>\n * << X-Account-Meta-Mydelete1: foo\n * << X-Account-Meta-Mydelete2: bar\n * </pre>\n *\n * <h4>Note</h4> <br/>\n * HTTP response headers keys are known to be case-insensitive, but this\n * practice of mixing up case will prevent metadata keys such as those in\n * Turkish from working.\n */\npublic class BindMetadataToHeaders implements Binder {\n\n   public static class BindAccountMetadataToHeaders extends BindMetadataToHeaders {\n      BindAccountMetadataToHeaders() {\n         super(ACCOUNT_METADATA_PREFIX);\n      }\n   }\n\n   public static class BindRemoveAccountMetadataToHeaders extends BindMetadataToHeaders.ForRemoval {\n      BindRemoveAccountMetadataToHeaders() {\n         super(ACCOUNT_METADATA_PREFIX);\n      }\n   }\n\n   public static class BindContainerMetadataToHeaders extends BindMetadataToHeaders {\n      BindContainerMetadataToHeaders() {\n         super(CONTAINER_METADATA_PREFIX);\n      }\n   }\n\n   public static class BindRemoveContainerMetadataToHeaders extends BindMetadataToHeaders.ForRemoval {\n      BindRemoveContainerMetadataToHeaders() {\n         super(CONTAINER_METADATA_PREFIX);\n      }\n   }\n\n   public static class BindObjectMetadataToHeaders extends BindMetadataToHeaders {\n      BindObjectMetadataToHeaders() {\n         super(OBJECT_METADATA_PREFIX);\n      }\n   }\n\n   public static class BindRemoveObjectMetadataToHeaders extends BindMetadataToHeaders.ForRemoval {\n      BindRemoveObjectMetadataToHeaders() {\n         super(OBJECT_METADATA_PREFIX);\n      }\n   }\n\n   /**\n    * @see <a\n    *      href=\"http://docs.openstack.org/api/openstack-object-storage/1.0/content/delete-account-metadata.html\">documentation</a>\n    */\n   public abstract static class ForRemoval extends BindMetadataToHeaders {\n      ForRemoval(String metadataPrefix) {\n         super(metadataPrefix);\n      }\n\n      @Override\n      protected void putMetadata(Builder<String, String> headers, String key, String value) {\n         headers.put(String.format(\"x-remove%s\", key.substring(1)), \"ignored\");\n      }\n   }\n\n   private final String metadataPrefix;\n\n   public BindMetadataToHeaders(String metadataPrefix) {\n      this.metadataPrefix = checkNotNull(metadataPrefix, \"metadataPrefix\");\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkNotNull(request, \"request\");\n      checkArgument(input instanceof Map<?, ?>, \"input must be a non-null java.util.Map!\");\n      Map<String, String> metadata = Map.class.cast(input);\n      ImmutableMultimap<String, String> headers = toHeaders(metadata);\n      return (R) request.toBuilder().replaceHeaders(headers).build();\n   }\n\n   protected void putMetadata(Builder<String, String> headers, String key, String value) {\n      headers.put(key, value);\n   }\n\n   public ImmutableMultimap<String, String> toHeaders(Map<String, String> metadata) {\n      Builder<String, String> builder = ImmutableMultimap.<String, String> builder();\n      for (Entry<String, String> keyVal : metadata.entrySet()) {\n         String keyInLowercase = keyVal.getKey().toLowerCase();\n         if (keyVal.getKey().startsWith(metadataPrefix)) {\n            putMetadata(builder, keyInLowercase, keyVal.getValue());\n         } else {\n            putMetadata(builder, String.format(\"%s%s\", metadataPrefix, keyInLowercase), keyVal.getValue());\n         }\n      }\n      return builder.build();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/binders/BindToHeaders.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.io.MutableContentMetadata;\nimport org.jclouds.rest.Binder;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableMultimap.Builder;\n\n/**\n * Will bind to headers, as needed, and will process content-* headers in a jclouds-compatible fashion.\n */\npublic class BindToHeaders implements Binder {\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkNotNull(request, \"request\");\n      checkArgument(input instanceof Map<?, ?>, \"input must be a non-null java.util.Map!\");\n      // Input map\n      Map<String, String> headers = Map.class.cast(input);\n\n      // Content map\n      if (request.getPayload() == null) {\n         request.setPayload(\"\");\n      }\n      MutableContentMetadata contentMetadata = request.getPayload().getContentMetadata();\n\n      // Regular headers map\n      Builder<String, String> builder = ImmutableMultimap.<String, String> builder();\n\n      for (Entry<String, String> keyVal : headers.entrySet()) {\n         String keyInLowercase = keyVal.getKey().toLowerCase();\n\n         if (keyInLowercase.equals(\"content-type\")) {\n            contentMetadata.setContentType(keyVal.getValue());\n            continue;\n         }\n         if (keyInLowercase.equals(\"content-disposition\")) {\n            contentMetadata.setContentDisposition(keyVal.getValue());\n            continue;\n         }\n         if (keyInLowercase.equals(\"content-encoding\")) {\n            contentMetadata.setContentEncoding(keyVal.getValue());\n            continue;\n         }\n         if (keyInLowercase.equals(\"content-language\")) {\n            contentMetadata.setContentLanguage(keyVal.getValue());\n            continue;\n         }\n         if (keyInLowercase.equals(\"content-length\")) {\n            contentMetadata.setContentLength(Long.parseLong(keyVal.getValue()));\n            continue;\n         }\n         builder.put(keyInLowercase, keyVal.getValue());\n      }\n      request.getPayload().setContentMetadata(contentMetadata);\n      return (R) request.toBuilder().replaceHeaders(builder.build()).build();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/binders/SetPayload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.io.BaseEncoding.base16;\nimport static com.google.common.net.HttpHeaders.ETAG;\nimport static com.google.common.net.HttpHeaders.TRANSFER_ENCODING;\nimport static java.util.concurrent.TimeUnit.MILLISECONDS;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.OBJECT_DELETE_AT;\n\nimport java.util.Date;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpRequest.Builder;\nimport org.jclouds.io.Payload;\nimport org.jclouds.rest.Binder;\n\nimport com.google.common.hash.HashCode;\n\npublic class SetPayload implements Binder {\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      Builder<?> builder = request.toBuilder();\n      Payload payload = Payload.class.cast(input);\n\n      if (payload.getContentMetadata().getContentType() == null) {\n         // TODO: use `X-Detect-Content-Type` here. Should be configurable via a property.\n         payload.getContentMetadata().setContentType(MediaType.APPLICATION_OCTET_STREAM);\n      }\n\n      Long contentLength = payload.getContentMetadata().getContentLength();\n      if (contentLength != null && contentLength >= 0) {\n         checkArgument(contentLength <= 5L * 1024 * 1024 * 1024, \"maximum size for put object is 5GB, %s\",\n               contentLength);\n      } else {\n         builder.replaceHeader(TRANSFER_ENCODING, \"chunked\").build();\n      }\n\n      HashCode md5 = payload.getContentMetadata().getContentMD5AsHashCode();\n      if (md5 != null) {\n         // Swift will validate the md5, if placed as an ETag header\n         builder.replaceHeader(ETAG, base16().lowerCase().encode(md5.asBytes()));\n      }\n\n      Date expires = payload.getContentMetadata().getExpires();\n      if (expires != null) {\n         builder.addHeader(OBJECT_DELETE_AT,\n               String.valueOf(MILLISECONDS.toSeconds(expires.getTime()))).build();\n      }\n\n      return (R) builder.payload(payload).build();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/binders/TempAuthBinder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.openstack.swift.v1.reference.TempAuthHeaders.TEMP_AUTH_HEADER_USER;\nimport static org.jclouds.openstack.swift.v1.reference.TempAuthHeaders.TEMP_AUTH_HEADER_PASS;\n\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\nimport com.google.inject.Inject;\nimport com.google.inject.name.Named;\n\n/**\n * Binder to the tempAuthAuthentication\n *\n */\npublic final class TempAuthBinder implements Binder{\n   private final String identityHeaderNameUser;\n   private final String identityHeaderNamePass;\n\n   @Inject\n   TempAuthBinder(@Named(TEMP_AUTH_HEADER_USER) String identityHeaderNameUser, @Named(TEMP_AUTH_HEADER_PASS) String identityHeaderNamePass) {\n      this.identityHeaderNameUser = identityHeaderNameUser;\n      this.identityHeaderNamePass = identityHeaderNamePass;\n   }\n\n   @Override \n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkNotNull(request, \"request\");\n      checkArgument(input instanceof Credentials, \"input must be a non-null org.jclouds.domain.Credentials\");\n      return (R) request.toBuilder().replaceHeader(identityHeaderNameUser, ((Credentials) input).identity)\n\t      \t\t.replaceHeader(identityHeaderNamePass, ((Credentials) input).credential).build();\n   }\n}\n\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/blobstore/RegionScopedBlobStoreContext.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.blobstore;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.Context;\nimport org.jclouds.blobstore.BlobRequestSigner;\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.BlobStoreContext;\nimport org.jclouds.blobstore.attr.ConsistencyModel;\nimport org.jclouds.internal.BaseView;\nimport org.jclouds.location.Provider;\nimport org.jclouds.location.Region;\nimport org.jclouds.rest.Utils;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.reflect.TypeToken;\n\n/**\n * Implementation of {@link BlobStoreContext} which allows you to employ\n * multiple regions.\n *\n * Example.\n *\n * <pre>\n * ctx = contextBuilder.buildView(RegionScopedBlobStoreContext.class);\n *\n * Set&lt;String&gt; regionIds = ctx.getConfiguredRegions();\n *\n * // isolated to a specific region\n * BlobStore texasBlobStore = ctx.getBlobStore(&quot;US-TX&quot;);\n * BlobStore virginiaBlobStore = ctx.getBlobStore(&quot;US-VA&quot;);\n * </pre>\n */\npublic class RegionScopedBlobStoreContext extends BaseView implements BlobStoreContext {\n\n   /**\n    * @return regions supported in this context.\n    */\n   public Set<String> getConfiguredRegions() {\n      return regionIds.get();\n   }\n\n   /**\n    * @param regionId\n    *           valid region id from {@link #getConfiguredRegions()}\n    * @throws IllegalArgumentException\n    *            if {@code regionId} was invalid.\n    */\n   public BlobStore getBlobStore(String regionId) {\n      checkRegionId(regionId);\n      return blobStore.apply(regionId);\n   }\n\n   /**\n    * @param regionId\n    *           valid region id from {@link #getConfiguredRegions()}\n    * @throws IllegalArgumentException\n    *            if {@code regionId} was invalid.\n    */\n   public BlobRequestSigner getSigner(String regionId) {\n      checkRegionId(regionId);\n      return blobRequestSigner.apply(regionId);\n   }\n\n   protected void checkRegionId(String regionId) {\n      checkArgument(getConfiguredRegions().contains(checkNotNull(regionId, \"regionId was null\")), \"region %s not in %s\",\n            regionId, getConfiguredRegions());\n   }\n\n   private final Supplier<Set<String>> regionIds;\n   private final Supplier<String> implicitRegionId;\n   // factory functions are decoupled so that you can exchange how requests are\n   // signed or decorate without a class hierarchy dependency\n   private final Function<String, BlobStore> blobStore;\n   private final Function<String, BlobRequestSigner> blobRequestSigner;\n   private final Utils utils;\n   private final ConsistencyModel consistencyModel;\n\n   @Inject\n   public RegionScopedBlobStoreContext(@Provider Context backend, @Provider TypeToken<? extends Context> backendType,\n         @Region Supplier<Set<String>> regionIds, @Region Supplier<String> implicitRegionId,\n         Function<String, BlobStore> blobStore, Function<String, BlobRequestSigner> blobRequestSigner, Utils utils,\n         ConsistencyModel consistencyModel) {\n      super(backend, backendType);\n      this.regionIds = checkNotNull(regionIds, \"regionIds\");\n      this.implicitRegionId = checkNotNull(implicitRegionId, \"implicitRegionId\");\n      this.blobStore = checkNotNull(blobStore, \"blobStore\");\n      this.blobRequestSigner = checkNotNull(blobRequestSigner, \"blobRequestSigner\");\n      this.utils = checkNotNull(utils, \"utils\");\n      this.consistencyModel = checkNotNull(consistencyModel, \"consistencyModel\");\n   }\n\n   @Override\n   public ConsistencyModel getConsistencyModel() {\n      return consistencyModel;\n   }\n\n   @Override\n   public BlobStore getBlobStore() {\n      return getBlobStore(implicitRegionId.get());\n   }\n\n   @Override\n   public BlobRequestSigner getSigner() {\n      return getSigner(implicitRegionId.get());\n   }\n\n   @Override\n   public Utils utils() {\n      return utils;\n   }\n\n   @Override\n   public void close() {\n      delegate().close();\n   }\n\n   public int hashCode() {\n      return delegate().hashCode();\n   }\n\n   @Override\n   public String toString() {\n      return delegate().toString();\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      return delegate().equals(obj);\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/blobstore/RegionScopedSwiftBlobStore.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.blobstore;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.tryFind;\nimport static com.google.common.collect.Lists.transform;\nimport static org.jclouds.Constants.PROPERTY_USER_THREADS;\nimport static org.jclouds.blobstore.options.ListContainerOptions.Builder.recursive;\nimport static org.jclouds.location.predicates.LocationPredicates.idEquals;\nimport static org.jclouds.openstack.swift.v1.options.PutOptions.Builder.metadata;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.PipedInputStream;\nimport java.io.PipedOutputStream;\nimport java.io.RandomAccessFile;\nimport java.lang.reflect.Method;\nimport java.nio.MappedByteBuffer;\nimport java.nio.channels.FileChannel;\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Locale;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.UUID;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.LinkedBlockingQueue;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\n\nimport org.jclouds.Constants;\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.BlobStoreContext;\nimport org.jclouds.blobstore.KeyNotFoundException;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.BlobAccess;\nimport org.jclouds.blobstore.domain.BlobBuilder;\nimport org.jclouds.blobstore.domain.BlobMetadata;\nimport org.jclouds.blobstore.domain.ContainerAccess;\nimport org.jclouds.blobstore.domain.MultipartPart;\nimport org.jclouds.blobstore.domain.MultipartUpload;\nimport org.jclouds.blobstore.domain.MutableBlobMetadata;\nimport org.jclouds.blobstore.domain.PageSet;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.domain.StorageType;\nimport org.jclouds.blobstore.domain.internal.BlobBuilderImpl;\nimport org.jclouds.blobstore.domain.internal.BlobImpl;\nimport org.jclouds.blobstore.domain.internal.PageSetImpl;\nimport org.jclouds.blobstore.functions.BlobToHttpGetOptions;\nimport org.jclouds.blobstore.options.CopyOptions;\nimport org.jclouds.blobstore.options.CreateContainerOptions;\nimport org.jclouds.blobstore.options.GetOptions;\nimport org.jclouds.blobstore.options.ListContainerOptions;\nimport org.jclouds.blobstore.options.PutOptions;\nimport org.jclouds.blobstore.strategy.ClearListStrategy;\nimport org.jclouds.blobstore.strategy.internal.MultipartUploadSlicingAlgorithm;\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.domain.Location;\nimport org.jclouds.io.ContentMetadata;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.PayloadSlicer;\nimport org.jclouds.io.payloads.ByteSourcePayload;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.openstack.swift.v1.SwiftApi;\nimport org.jclouds.openstack.swift.v1.blobstore.functions.ToBlobMetadata;\nimport org.jclouds.openstack.swift.v1.blobstore.functions.ToListContainerOptions;\nimport org.jclouds.openstack.swift.v1.blobstore.functions.ToResourceMetadata;\nimport org.jclouds.openstack.swift.v1.domain.Container;\nimport org.jclouds.openstack.swift.v1.domain.DeleteStaticLargeObjectResponse;\nimport org.jclouds.openstack.swift.v1.domain.ObjectList;\nimport org.jclouds.openstack.swift.v1.domain.Segment;\nimport org.jclouds.openstack.swift.v1.domain.SwiftObject;\nimport org.jclouds.openstack.swift.v1.features.BulkApi;\nimport org.jclouds.openstack.swift.v1.features.ObjectApi;\nimport org.jclouds.openstack.swift.v1.options.UpdateContainerOptions;\nimport org.jclouds.openstack.swift.v1.reference.SwiftHeaders;\nimport org.jclouds.util.Closeables2;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMap.Builder;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Maps;\nimport com.google.common.io.ByteSource;\nimport com.google.common.io.ByteStreams;\nimport com.google.common.io.Closeables;\nimport com.google.common.net.HttpHeaders;\nimport com.google.common.util.concurrent.Futures;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.common.util.concurrent.MoreExecutors;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Injector;\nimport com.google.inject.assistedinject.Assisted;\n\npublic class RegionScopedSwiftBlobStore implements BlobStore {\n\n   @Inject\n   protected RegionScopedSwiftBlobStore(Injector baseGraph, BlobStoreContext context, SwiftApi api,\n         @Memoized Supplier<Set<? extends Location>> locations, @Assisted String regionId,\n         PayloadSlicer slicer, @Named(PROPERTY_USER_THREADS) ListeningExecutorService userExecutor) {\n      checkNotNull(regionId, \"regionId\");\n      Optional<? extends Location> found = tryFind(locations.get(), idEquals(regionId));\n      checkArgument(found.isPresent(), \"region %s not in %s\", regionId, locations.get());\n      this.region = found.get();\n      this.regionId = regionId;\n      this.slicer = slicer;\n      this.toResourceMetadata = new ToResourceMetadata(found.get());\n      this.context = context;\n      this.api = api;\n      this.userExecutor = userExecutor;\n      // until we parameterize ClearListStrategy with a factory\n      this.clearList = baseGraph.createChildInjector(new AbstractModule() {\n         @Override\n         protected void configure() {\n            bind(BlobStore.class).toInstance(RegionScopedSwiftBlobStore.this);\n         }\n      }).getInstance(ClearListStrategy.class);\n   }\n\n   private final BlobStoreContext context;\n   private final ClearListStrategy clearList;\n   private final SwiftApi api;\n   private final Location region;\n   private final String regionId;\n   private final BlobToHttpGetOptions toGetOptions = new BlobToHttpGetOptions();\n   private final ToListContainerOptions toListContainerOptions = new ToListContainerOptions();\n   private final ToResourceMetadata toResourceMetadata;\n   protected final PayloadSlicer slicer;\n   protected final ListeningExecutorService userExecutor;\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   @Override\n   public Set<? extends Location> listAssignableLocations() {\n      return ImmutableSet.of(region);\n   }\n\n   @Override\n   public PageSet<? extends StorageMetadata> list() {\n      // TODO: there may eventually be >10k containers..\n      FluentIterable<StorageMetadata> containers = api.getContainerApi(regionId).list()\n            .transform(toResourceMetadata);\n      return new PageSetImpl<StorageMetadata>(containers, null);\n   }\n\n   @Override\n   public boolean containerExists(String container) {\n      Container val = api.getContainerApi(regionId).get(container);\n      containerCache.put(container, Optional.fromNullable(val));\n      return val != null;\n   }\n\n   @Override\n   public boolean createContainerInLocation(Location location, String container) {\n      return createContainerInLocation(location, container, CreateContainerOptions.NONE);\n   }\n\n   @Override\n   public boolean createContainerInLocation(Location location, String container, CreateContainerOptions options) {\n      checkArgument(location == null || location.equals(region), \"location must be null or %s\", region);\n      boolean containerCreated = api.getContainerApi(regionId).create(container, options.isPublicRead() ? ANYBODY_READ : BASIC_CONTAINER);\n\n      if (containerCreated) {\n         containerCache.put(container, Optional.fromNullable(api.getContainerApi(regionId).get(container)));\n      }\n      return containerCreated;\n   }\n\n   @Override\n   public ContainerAccess getContainerAccess(String name) {\n      Container container = api.getContainerApi(regionId).get(name);\n      if (container.getAnybodyRead().get()) {\n         return ContainerAccess.PUBLIC_READ;\n      } else {\n         return ContainerAccess.PRIVATE;\n      }\n   }\n\n   @Override\n   public void setContainerAccess(String name, ContainerAccess access) {\n      UpdateContainerOptions options = new UpdateContainerOptions();\n      if (access == ContainerAccess.PUBLIC_READ) {\n         options.anybodyRead();\n      } else {\n         options.headers(ImmutableMultimap.of(SwiftHeaders.CONTAINER_READ, SwiftHeaders.CONTAINER_ACL_PRIVATE));\n      }\n      api.getContainerApi(regionId).update(name, options);\n   }\n\n   private static final org.jclouds.openstack.swift.v1.options.CreateContainerOptions BASIC_CONTAINER = new org.jclouds.openstack.swift.v1.options.CreateContainerOptions();\n   private static final org.jclouds.openstack.swift.v1.options.CreateContainerOptions ANYBODY_READ = new org.jclouds.openstack.swift.v1.options.CreateContainerOptions()\n         .anybodyRead();\n\n   @Override\n   public PageSet<? extends StorageMetadata> list(String container) {\n      return list(container, ListContainerOptions.NONE);\n   }\n\n   @Override\n   public PageSet<? extends StorageMetadata> list(final String container, ListContainerOptions options) {\n      ObjectApi objectApi = api.getObjectApi(regionId, container);\n      ObjectList objects = objectApi.list(toListContainerOptions.apply(options));\n      if (objects == null) {\n         containerCache.put(container, Optional.<Container> absent());\n         return new PageSetImpl<StorageMetadata>(ImmutableList.<StorageMetadata> of(), null);\n      } else {\n         containerCache.put(container, Optional.of(objects.getContainer()));\n         List<? extends StorageMetadata> list = transform(objects, toBlobMetadata(container));\n         int limit = Optional.fromNullable(options.getMaxResults()).or(10000);\n         String marker = null;\n         if (!list.isEmpty() && list.size() == limit) {\n            marker = list.get(limit - 1).getName();\n         }\n         // TODO: we should probably deprecate this option\n         if (options.isDetailed()) {\n            list = transform(list, new Function<StorageMetadata, StorageMetadata>() {\n               @Override\n               public StorageMetadata apply(StorageMetadata input) {\n                  if (input.getType() != StorageType.BLOB) {\n                     return input;\n                  }\n                  return blobMetadata(container, input.getName());\n               }\n            });\n         }\n         return new PageSetImpl<StorageMetadata>(list, marker);\n      }\n   }\n\n   @Override\n   public boolean blobExists(String container, String name) {\n      return blobMetadata(container, name) != null;\n   }\n\n   @Override\n   public String putBlob(String container, Blob blob) {\n      return putBlob(container, blob, PutOptions.NONE);\n   }\n\n   @Override\n   public String putBlob(String container, Blob blob, PutOptions options) {\n      if (options.getBlobAccess() != BlobAccess.PRIVATE) {\n         throw new UnsupportedOperationException(\"blob access not supported by swift\");\n      }\n      if (options.isMultipart()) {\n         return putMultipartBlob(container, blob, options);\n      }\n      ObjectApi objectApi = api.getObjectApi(regionId, container);\n      return objectApi.put(blob.getMetadata().getName(), blob.getPayload(), metadata(blob.getMetadata().getUserMetadata()));\n   }\n\n   @Override\n   public String copyBlob(String fromContainer, String fromName, String toContainer, String toName,\n         CopyOptions options) {\n      ObjectApi objectApi = api.getObjectApi(regionId, toContainer);\n\n      org.jclouds.openstack.swift.v1.options.CopyOptions swiftOptions = new org.jclouds.openstack.swift.v1.options.CopyOptions();\n\n      if (options.ifMatch() != null) {\n         swiftOptions.ifMatch(options.ifMatch());\n      }\n      if (options.ifNoneMatch() != null) {\n         throw new UnsupportedOperationException(\"Swift does not support ifNoneMatch\");\n      }\n      if (options.ifModifiedSince() != null) {\n         swiftOptions.ifModifiedSince(options.ifModifiedSince());\n      }\n      if (options.ifUnmodifiedSince() != null) {\n         swiftOptions.ifUnmodifiedSince(options.ifUnmodifiedSince());\n      }\n\n      Map<String, String> systemMetadata = Maps.newHashMap();\n      ContentMetadata contentMetadata = options.contentMetadata();\n      Map<String, String> userMetadata = options.userMetadata();\n\n      if (contentMetadata != null || userMetadata != null) {\n         if (contentMetadata != null) {\n            String contentDisposition = contentMetadata.getContentDisposition();\n            if (contentDisposition != null) {\n               systemMetadata.put(HttpHeaders.CONTENT_DISPOSITION, contentDisposition);\n            }\n\n            String contentEncoding = contentMetadata.getContentEncoding();\n            if (contentEncoding != null) {\n               systemMetadata.put(HttpHeaders.CONTENT_ENCODING, contentEncoding);\n            }\n\n            String contentLanguage = contentMetadata.getContentLanguage();\n            if (contentLanguage != null) {\n               systemMetadata.put(HttpHeaders.CONTENT_LANGUAGE, contentLanguage);\n            }\n\n            String contentType = contentMetadata.getContentType();\n            if (contentType != null) {\n               systemMetadata.put(HttpHeaders.CONTENT_TYPE, contentType);\n            }\n         }\n         if (userMetadata == null) {\n            userMetadata = Maps.newHashMap();\n         }\n      } else {\n         SwiftObject metadata = api.getObjectApi(regionId, fromContainer).getWithoutBody(fromName);\n         if (metadata == null) {\n            throw new KeyNotFoundException(fromContainer, fromName, \"Swift could not find the specified source key\");\n         }\n         contentMetadata = metadata.getPayload().getContentMetadata();\n         String contentDisposition = contentMetadata.getContentDisposition();\n         if (contentDisposition != null) {\n            systemMetadata.put(HttpHeaders.CONTENT_DISPOSITION, contentDisposition);\n         }\n         String contentEncoding = contentMetadata.getContentEncoding();\n         if (contentEncoding != null) {\n            systemMetadata.put(HttpHeaders.CONTENT_ENCODING, contentEncoding);\n         }\n         String contentLanguage = contentMetadata.getContentLanguage();\n         if (contentLanguage != null) {\n            systemMetadata.put(HttpHeaders.CONTENT_LANGUAGE, contentLanguage);\n         }\n         String contentType = contentMetadata.getContentType();\n         if (contentType != null) {\n            systemMetadata.put(HttpHeaders.CONTENT_TYPE, contentType);\n         }\n         userMetadata = metadata.getMetadata();\n      }\n\n      objectApi.copy(toName, fromContainer, fromName, userMetadata, systemMetadata, swiftOptions);\n\n      // TODO: Swift copy object *appends* user metadata, does not overwrite\n      return objectApi.getWithoutBody(toName).getETag();\n   }\n\n   @Override\n   public BlobMetadata blobMetadata(String container, String name) {\n      SwiftObject object = api.getObjectApi(regionId, container).getWithoutBody(name);\n      if (object == null) {\n         return null;\n      }\n      return toBlobMetadata(container).apply(object);\n   }\n\n   @Override\n   public Blob getBlob(String container, String key) {\n      return getBlob(container, key, GetOptions.NONE);\n   }\n\n   @Override\n   public Blob getBlob(String container, String name, GetOptions options) {\n      ObjectApi objectApi = api.getObjectApi(regionId, container);\n      SwiftObject object = objectApi.get(name, toGetOptions.apply(options));\n      if (object == null) {\n         return null;\n      }\n      Blob blob = new BlobImpl(toBlobMetadata(container).apply(object));\n      blob.setPayload(object.getPayload());\n      blob.setAllHeaders(object.getHeaders());\n      return blob;\n   }\n\n   @Override\n   public void removeBlob(String container, String name) {\n      // Multipart objects have a manifest which points to subobjects.  Normally\n      // deleting a object only deletes the manifest, leaving the subobjects.\n      // We first try a multipart delete and if that fails since the object is\n      // not an MPU we fall back to single-part delete.\n      DeleteStaticLargeObjectResponse response = api.getStaticLargeObjectApi(regionId, container).delete(name);\n      if (!response.status().equals(\"200 OK\")) {\n         api.getObjectApi(regionId, container).delete(name);\n      }\n   }\n\n   /**\n    * Delete multiple single-part objects.  Note that this does not remove the\n    * subobjects of a multi-part upload.\n    */\n   @Override\n   public void removeBlobs(String container, Iterable<String> names) {\n      BulkApi bulkApi = api.getBulkApi(regionId);\n      for (List<String> partition : Iterables.partition(names, 1000)) {\n         ImmutableList.Builder<String> builder = ImmutableList.builder();\n         for (String name : partition) {\n            builder.add(container + \"/\" + name);\n         }\n         bulkApi.bulkDelete(builder.build());\n      }\n   }\n\n   @Override\n   public BlobAccess getBlobAccess(String container, String name) {\n      return BlobAccess.PRIVATE;\n   }\n\n   @Override\n   public void setBlobAccess(String container, String name, BlobAccess access) {\n      throw new UnsupportedOperationException(\"unsupported in swift\");\n   }\n\n   @Override\n   public BlobStoreContext getContext() {\n      return context;\n   }\n\n   @Override\n   public BlobBuilder blobBuilder(String name) {\n      return new BlobBuilderImpl().name(name);\n   }\n\n   @Override\n   public boolean directoryExists(String containerName, String directory) {\n      return api.getObjectApi(regionId, containerName)\n            .get(directory) != null;\n   }\n\n   @Override\n   public void createDirectory(String containerName, String directory) {\n      api.getObjectApi(regionId, containerName)\n            .put(directory, directoryPayload);\n   }\n\n   private final Payload directoryPayload = new ByteSourcePayload(ByteSource.wrap(new byte[] {})) {\n      {\n         getContentMetadata().setContentType(\"application/directory\");\n      }\n   };\n\n   @Override\n   public void deleteDirectory(String containerName, String directory) {\n      api.getObjectApi(regionId, containerName).delete(directory);\n   }\n\n   @Override\n   public long countBlobs(String containerName) {\n      Container container = api.getContainerApi(regionId).get(containerName);\n      // undefined if container doesn't exist, so default to zero\n      return container != null && container.getObjectCount() != null ? container.getObjectCount() : 0;\n   }\n\n   @Override\n   public MultipartUpload initiateMultipartUpload(String container, BlobMetadata blobMetadata, PutOptions options) {\n      if (options.getBlobAccess() != BlobAccess.PRIVATE) {\n         throw new UnsupportedOperationException(\"blob ACLs not supported in swift\");\n      }\n      return initiateMultipartUpload(container, blobMetadata, 0, options);\n   }\n\n   private MultipartUpload initiateMultipartUpload(String container, BlobMetadata blobMetadata, long partSize, PutOptions options) {\n      Long contentLength = blobMetadata.getContentMetadata().getContentLength();\n      String uploadId = String.format(Locale.ENGLISH, \"%s/slo/%.6f/%s/%s\", blobMetadata.getName(),\n              System.currentTimeMillis() / 1000.0, contentLength == null ? Long.valueOf(0) : contentLength,\n              partSize);\n      return MultipartUpload.create(container, blobMetadata.getName(), uploadId, blobMetadata, options);\n   }\n\n   @Override\n   public void abortMultipartUpload(MultipartUpload mpu) {\n      ImmutableList.Builder<String> names = ImmutableList.builder();\n      for (MultipartPart part : listMultipartUpload(mpu)) {\n         names.add(getMPUPartName(mpu, part.partNumber()));\n      }\n      removeBlobs(mpu.containerName(), names.build());\n   }\n\n   private ImmutableMap<String, String> getContentMetadataForManifest(ContentMetadata contentMetadata) {\n      Builder<String, String> mapBuilder = ImmutableMap.builder();\n      if (contentMetadata.getContentType() != null) {\n         mapBuilder.put(\"content-type\", contentMetadata.getContentType());\n      }\n      /**\n       * Do not set content-length. Set automatically to manifest json string length by BindToJsonPayload\n       */\n      if (contentMetadata.getContentDisposition() != null) {\n         mapBuilder.put(\"content-disposition\", contentMetadata.getContentDisposition());\n      }\n      if (contentMetadata.getContentEncoding() != null) {\n         mapBuilder.put(\"content-encoding\", contentMetadata.getContentEncoding());\n      }\n      if (contentMetadata.getContentLanguage() != null) {\n         mapBuilder.put(\"content-language\", contentMetadata.getContentLanguage());\n      }\n      return mapBuilder.build();\n   }\n\n   private String getMPUPartName(MultipartUpload mpu, int partNumber) {\n      return String.format(\"%s/%08d\", mpu.id(), partNumber);\n   }\n\n   @Override\n   public String completeMultipartUpload(MultipartUpload mpu, List<MultipartPart> parts) {\n      ImmutableList.Builder<Segment> builder = ImmutableList.builder();\n      for (MultipartPart part : parts) {\n         String path = mpu.containerName() + \"/\" + getMPUPartName(mpu, part.partNumber());\n         builder.add(Segment.builder().path(path).etag(part.partETag()).sizeBytes(part.partSize()).build());\n      }\n\n      return api.getStaticLargeObjectApi(regionId, mpu.containerName()).replaceManifest(mpu.blobName(),\n            builder.build(), mpu.blobMetadata().getUserMetadata(), getContentMetadataForManifest(mpu.blobMetadata().getContentMetadata()));\n   }\n\n   @Override\n   public MultipartPart uploadMultipartPart(MultipartUpload mpu, int partNumber, Payload payload) {\n      String partName = getMPUPartName(mpu, partNumber);\n      String eTag = api.getObjectApi(regionId, mpu.containerName()).put(partName, payload);\n      long partSize = payload.getContentMetadata().getContentLength();\n      Date lastModified = null;  // Swift does not return Last-Modified\n      return MultipartPart.create(partNumber, partSize, eTag, lastModified);\n   }\n\n   @Override\n   public List<MultipartPart> listMultipartUpload(MultipartUpload mpu) {\n      ImmutableList.Builder<MultipartPart> parts = ImmutableList.builder();\n      PageSet<? extends StorageMetadata> pageSet = list(mpu.containerName(),\n            new ListContainerOptions().prefix(mpu.id() + \"/\"));\n      // TODO: pagination\n      for (StorageMetadata sm : pageSet) {\n         int lastSlash = sm.getName().lastIndexOf('/');\n         int partNumber = Integer.parseInt(sm.getName().substring(lastSlash + 1));\n         parts.add(MultipartPart.create(partNumber, sm.getSize(), sm.getETag(), sm.getLastModified()));\n      }\n      return parts.build();\n   }\n\n   @Override\n   public List<MultipartUpload> listMultipartUploads(String container) {\n      throw new UnsupportedOperationException();\n   }\n\n   @Override\n   public long getMinimumMultipartPartSize() {\n      return 1024 * 1024 + 1;\n   }\n\n   @Override\n   public long getMaximumMultipartPartSize() {\n      return 5L * 1024L * 1024L * 1024L;\n   }\n\n   @Override\n   public int getMaximumNumberOfParts() {\n      return Integer.MAX_VALUE;\n   }\n\n   @Override\n   public void clearContainer(String containerName) {\n      clearContainer(containerName, recursive());\n   }\n\n   @Override\n   public void clearContainer(String containerName, ListContainerOptions options) {\n      // this could be implemented to use bulk delete\n      clearList.execute(containerName, options);\n   }\n\n   @Override\n   public void deleteContainer(String container) {\n      clearContainer(container, recursive());\n      api.getContainerApi(regionId).deleteIfEmpty(container);\n      containerCache.invalidate(container);\n   }\n\n   @Override\n   public boolean deleteContainerIfEmpty(String container) {\n      boolean deleted = api.getContainerApi(regionId).deleteIfEmpty(container);\n      if (deleted) {\n         containerCache.invalidate(container);\n      }\n      return deleted;\n   }\n\n   protected final LoadingCache<String, Optional<Container>> containerCache = CacheBuilder.newBuilder().build(\n         new CacheLoader<String, Optional<Container>>() {\n            public Optional<Container> load(String container) {\n               return Optional.fromNullable(api.getContainerApi(regionId).get(container));\n            }\n         });\n\n   protected Function<SwiftObject, MutableBlobMetadata> toBlobMetadata(String container) {\n      return new ToBlobMetadata(containerCache.getUnchecked(container).get());\n   }\n\n   @Override\n   public long countBlobs(String containerName, ListContainerOptions options) {\n      throw new UnsupportedOperationException();\n   }\n\n   @com.google.inject.Inject(optional = true)\n   @Named(Constants.PROPERTY_MAX_RETRIES)\n   protected int retryCountLimit = 5;\n\n   /**\n    * Upload using a user-provided executor, or the jclouds userExecutor\n    *\n    * @param container\n    * @param blob\n    * @param overrides\n    * @return the multipart blob etag\n    */\n   @Beta\n   protected String putMultipartBlob(String container, Blob blob, PutOptions overrides) {\n      if (overrides.getUseCustomExecutor()) {\n         return putMultipartBlob(container, blob, overrides, overrides.getCustomExecutor());\n      } else {\n         return putMultipartBlob(container, blob, overrides, userExecutor);\n      }\n   }\n\n   @Beta\n   protected String putMultipartBlob(String container, Blob blob, PutOptions overrides, ListeningExecutorService executor) {\n      ArrayList<ListenableFuture<MultipartPart>> parts = new ArrayList<ListenableFuture<MultipartPart>>();\n\n      long contentLength = checkNotNull(blob.getMetadata().getContentMetadata().getContentLength(),\n            \"must provide content-length to use multi-part upload\");\n      MultipartUploadSlicingAlgorithm algorithm = new MultipartUploadSlicingAlgorithm(\n            getMinimumMultipartPartSize(), getMaximumMultipartPartSize(), getMaximumNumberOfParts());\n      long partSize = algorithm.calculateChunkSize(contentLength);\n      MultipartUpload mpu = initiateMultipartUpload(container, blob.getMetadata(), partSize, overrides);\n      int partNumber = 0;\n\n      for (Payload payload : slicer.slice(blob.getPayload(), partSize)) {\n         BlobUploader b =\n               new BlobUploader(mpu, partNumber++, payload);\n         parts.add(executor.submit(b));\n      }\n\n      return completeMultipartUpload(mpu, Futures.getUnchecked(Futures.allAsList(parts)));\n   }\n\n   private final class BlobUploader implements Callable<MultipartPart> {\n      private final MultipartUpload mpu;\n      private final int partNumber;\n      private final Payload payload;\n\n      BlobUploader(MultipartUpload mpu, int partNumber, Payload payload) {\n         this.mpu = mpu;\n         this.partNumber = partNumber;\n         this.payload = payload;\n      }\n\n      @Override\n      public MultipartPart call() {\n         return uploadMultipartPart(mpu, partNumber, payload);\n      }\n   }\n\n   @Override\n   @Beta\n   public void downloadBlob(String container, String name, File destination) {\n      downloadBlob(container, name, destination, userExecutor);\n   }\n\n   @Override\n   @Beta\n   public void downloadBlob(String container, String name, File destination, ExecutorService executor) {\n\n      ListeningExecutorService listeningExecutor = MoreExecutors.listeningDecorator(executor);\n      RandomAccessFile raf = null;\n      File tempFile = new File(destination + \".\" + UUID.randomUUID());\n      try {\n         long contentLength = api\n               .getObjectApi(regionId, container)\n               .getWithoutBody(name)\n               .getPayload()\n               .getContentMetadata()\n               .getContentLength();\n\n         // Reserve space for performance reasons\n         raf = new RandomAccessFile(tempFile, \"rw\");\n         raf.seek(contentLength - 1);\n         raf.write(0);\n\n         // Determine download buffer size, smaller means less memory usage; larger is faster as long as threads are saturated\n         long partSize = getMinimumMultipartPartSize();\n\n         // Loop through ranges within the file\n         long from;\n         long to;\n         List<ListenableFuture<Void>> results = new ArrayList<ListenableFuture<Void>>();\n\n         for (from = 0; from < contentLength; from = from + partSize) {\n            to = (from + partSize >= contentLength) ? contentLength - 1 : from + partSize - 1;\n            BlobDownloader b = new BlobDownloader(regionId, container, name, raf, from, to);\n            results.add(listeningExecutor.submit(b));\n         }\n\n         Futures.getUnchecked(Futures.allAsList(results));\n\n         raf.getChannel().force(true);\n         raf.getChannel().close();\n         raf.close();\n\n         if (destination.exists()) {\n            destination.delete();\n         }\n         if (!tempFile.renameTo(destination)) {\n            throw new RuntimeException(\"Could not move temporary downloaded file to destination \" + destination);\n         }\n         tempFile = null;\n      } catch (IOException e) {\n         throw new RuntimeException(e);\n      } finally {\n         Closeables2.closeQuietly(raf);\n         if (tempFile != null) {\n            tempFile.delete();\n         }\n      }\n   }\n\n   private final class BlobDownloader implements Callable<Void> {\n      String regionId;\n      String containerName;\n      String objectName;\n      private final RandomAccessFile raf;\n      private final long begin;\n      private final long end;\n\n      BlobDownloader(String regionId, String containerName, String objectName, RandomAccessFile raf, long begin, long end) {\n         this.regionId = regionId;\n         this.containerName = containerName;\n         this.objectName = objectName;\n         this.raf = raf;\n         this.begin = begin;\n         this.end = end;\n      }\n\n      @Override\n      public Void call() {\n         IOException lastException = null;\n         for (int retry = 0; retry < retryCountLimit; retry++) {\n            try {\n               SwiftObject object = api.getObjectApi(regionId, containerName)\n                     .get(objectName, org.jclouds.http.options.GetOptions.Builder.range(begin, end));\n               // Download first, this is the part that usually fails\n               byte[] targetArray;\n               InputStream is = object.getPayload().openStream();\n               try {\n                  targetArray = ByteStreams.toByteArray(is);\n               } finally {\n                  Closeables.closeQuietly(is);\n               }\n               // Map file region\n               MappedByteBuffer out = raf.getChannel().map(FileChannel.MapMode.READ_WRITE, begin, end - begin + 1);\n               out.put(targetArray);\n               out.force();\n\n               // JDK-4715154 ; TODO: Java 8 FileChannels\n               if (System.getProperty(\"os.name\").toLowerCase().contains(\"windows\")) {\n                  closeDirectBuffer(out);\n               }\n            } catch (IOException e) {\n               lastException = e;\n               continue;\n            }\n               // Success!\n               return null;\n            }\n         throw new RuntimeException(\"After \" + retryCountLimit + \" retries: \" + lastException);\n      }\n\n      // JDK-4715154\n      private void closeDirectBuffer(MappedByteBuffer mbb) {\n         if ( mbb == null || !mbb.isDirect() )\n            return;\n\n         try {\n            Method cleaner = mbb.getClass().getMethod(\"cleaner\");\n            cleaner.setAccessible(true);\n            Method clean = Class.forName(\"sun.misc.Cleaner\").getMethod(\"clean\");\n            clean.setAccessible(true);\n            clean.invoke(cleaner.invoke(mbb));\n         } catch (Exception e) {\n            logger.warn(e.toString());\n         }\n      }\n   }\n\n   @Beta\n   @Override\n   public InputStream streamBlob(final String container, final String name) {\n      return streamBlob(container, name, userExecutor);\n   }\n\n   @Beta\n   @Override\n   public InputStream streamBlob(final String container, final String name, final ExecutorService executor) {\n\n      final ListeningExecutorService listeningExecutor = MoreExecutors.listeningDecorator(executor);\n      // User will receive the Input end of the piped stream\n      final PipedOutputStream output;\n      final PipedInputStream input;\n      try {\n         output = new PipedOutputStream();\n         input = new PipedInputStream(output,\n               getMinimumMultipartPartSize() * 5 > Integer.MAX_VALUE ?\n                     Integer.MAX_VALUE : (int) getMinimumMultipartPartSize() * 5);\n      } catch (IOException e) {\n         throw new RuntimeException(e);\n      }\n\n      // The total length of the file to download is needed to determine ranges\n      // It has to be obtainable without downloading the whole file\n      final long contentLength = api\n            .getObjectApi(regionId, container)\n            .getWithoutBody(name)\n            .getPayload()\n            .getContentMetadata()\n            .getContentLength();\n\n      // Determine download buffer size, smaller means less memory usage; larger is faster as long as threads are saturated\n      final long partSize = getMinimumMultipartPartSize();\n\n      // Used to communicate between the producer and consumer threads\n      final LinkedBlockingQueue<ListenableFuture<byte[]>> results = new LinkedBlockingQueue<ListenableFuture<byte[]>>();\n\n      listeningExecutor.submit(new Runnable() {\n         @Override\n         public void run() {\n            ListenableFuture<byte[]> result;\n            long from;\n            try {\n               for (from = 0; from < contentLength; from = from + partSize) {\n                  logger.debug(Thread.currentThread() + \" writing to output\");\n                  result = results.take();\n                  if (result == null) {\n                     output.close();\n                     input.close();\n                     throw new RuntimeException(\"Error downloading file part to stream\");\n                  }\n                  output.write(result.get());\n               }\n            } catch (Exception e) {\n               logger.debug(e.toString());\n               // Close pipe so client is notified of an exception\n               Closeables2.closeQuietly(input);\n               throw new RuntimeException(e);\n            } finally {\n               // Finished writing results to stream\n               Closeables2.closeQuietly(output);\n            }\n         }\n      });\n\n      listeningExecutor.submit(new Runnable() {\n         @Override\n         public void run() {\n            long from;\n            long to;\n            // Loop through ranges within the file\n            for (from = 0; from < contentLength; from = from + partSize) {\n               to = (from + partSize >= contentLength) ? contentLength - 1 : from + partSize - 1;\n               BlobStreamDownloader b = new BlobStreamDownloader(container, name, from, to);\n               results.add(listeningExecutor.submit(b));\n            }\n         }\n      });\n      return input;\n   }\n\n   private final class BlobStreamDownloader implements Callable<byte[]> {\n      String containerName;\n      String objectName;\n      private final long begin;\n      private final long end;\n\n      BlobStreamDownloader(String containerName, String objectName, long begin, long end) {\n         this.containerName = containerName;\n         this.objectName = objectName;\n         this.begin = begin;\n         this.end = end;\n      }\n\n      @Override\n      public byte[] call() {\n         IOException lastException = null;\n         for (int retry = 0; retry < retryCountLimit; retry++) {\n            try {\n               long time = System.nanoTime();\n               SwiftObject object = api.getObjectApi(regionId, containerName)\n                     .get(objectName, org.jclouds.http.options.GetOptions.Builder.range(begin, end));\n               byte[] downloadedBlock;\n               InputStream is = object.getPayload().openStream();\n               try {\n                  downloadedBlock = ByteStreams.toByteArray(is);\n               } finally {\n                  Closeables.closeQuietly(is);\n               }\n               return downloadedBlock;\n            } catch (IOException e) {\n               logger.debug(e.toString());\n               lastException = e;\n               continue;\n            }\n         }\n         throw new RuntimeException(\"After \" + retryCountLimit + \" retries: \" + lastException);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/blobstore/RegionScopedTemporaryUrlBlobSigner.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.blobstore;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL;\n\nimport java.net.URI;\nimport java.util.Map;\nimport java.util.concurrent.TimeUnit;\n\nimport jakarta.inject.Provider;\n\nimport org.jclouds.blobstore.BlobRequestSigner;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.functions.BlobToHttpGetOptions;\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.Uris;\nimport org.jclouds.http.options.GetOptions;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.location.Region;\nimport org.jclouds.openstack.swift.v1.SwiftApi;\nimport org.jclouds.openstack.swift.v1.TemporaryUrlSigner;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.net.HttpHeaders;\nimport com.google.inject.Inject;\nimport com.google.inject.assistedinject.Assisted;\nimport com.google.inject.name.Named;\n\n/**\n * Uses {@link TemporaryUrlSigner} to sign requests for access to blobs. If no\n * interval is supplied, it defaults to a 15 minutes.\n */\npublic class RegionScopedTemporaryUrlBlobSigner implements BlobRequestSigner {\n\n   @Inject\n   protected RegionScopedTemporaryUrlBlobSigner(@Region Supplier<Map<String, Supplier<URI>>> regionToUris,\n         @Named(PROPERTY_SESSION_INTERVAL) long seconds, @TimeStamp Provider<Long> timestamp, SwiftApi api,\n         @Assisted String regionId) {\n      checkNotNull(regionId, \"regionId\");\n      this.timestamp = timestamp;\n      this.signer = TemporaryUrlSigner.checkApiEvery(api.getAccountApi(regionId), seconds);\n      this.storageUrl = regionToUris.get().get(regionId).get();\n   }\n\n   private static final long DEFAULT_SIGNING_TIMEOUT = TimeUnit.MINUTES.toSeconds(15);\n   private final BlobToHttpGetOptions toGetOptions = new BlobToHttpGetOptions();\n   private final Provider<Long> timestamp;\n   private final TemporaryUrlSigner signer;\n   private final URI storageUrl;\n\n   @Override\n   public HttpRequest signGetBlob(String container, String name) {\n      return signGetBlob(container, name, DEFAULT_SIGNING_TIMEOUT);\n   }\n\n   @Override\n   public HttpRequest signGetBlob(String container, String name, long timeInSeconds) {\n      return sign(\"GET\", container, name, GetOptions.NONE, timestamp.get() + timeInSeconds, null);\n   }\n\n   @Override\n   public HttpRequest signGetBlob(String container, String name, org.jclouds.blobstore.options.GetOptions options) {\n      return sign(\"GET\", container, name, toGetOptions.apply(options), timestamp.get() + DEFAULT_SIGNING_TIMEOUT, null);\n   }\n\n   @Override\n   public HttpRequest signPutBlob(String container, Blob blob) {\n      return signPutBlob(container, blob, DEFAULT_SIGNING_TIMEOUT);\n   }\n\n   @Override\n   public HttpRequest signPutBlob(String container, Blob blob, long timeInSeconds) {\n      return sign(\"PUT\", container, blob.getMetadata().getName(), GetOptions.NONE, timestamp.get() + timeInSeconds, blob.getMetadata().getContentMetadata().getContentType());\n   }\n\n   private HttpRequest sign(String method, String container, String name, GetOptions options, long expires, @Nullable String contentType) {\n      checkNotNull(container, \"container\");\n      checkNotNull(name, \"name\");\n      URI url = Uris.uriBuilder(storageUrl).appendPath(container).appendPath(name).build();\n      String signature = signer.sign(method, url.getPath(), expires);\n      HttpRequest.Builder builder = HttpRequest.builder()\n                        .method(method)\n                        .endpoint(url)\n                        .addQueryParams(options.buildQueryParameters())\n                        .addQueryParam(\"temp_url_sig\", signature)\n                        .addQueryParam(\"temp_url_expires\", String.valueOf(expires))\n                        .headers(options.buildRequestHeaders());\n      if (contentType != null) {\n         builder.replaceHeader(HttpHeaders.CONTENT_TYPE, contentType);\n      }\n      return builder.build();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/blobstore/config/SignUsingTemporaryUrls.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.blobstore.config;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.blobstore.BlobRequestSigner;\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.openstack.swift.v1.blobstore.RegionScopedTemporaryUrlBlobSigner;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ForwardingObject;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Provides;\nimport com.google.inject.assistedinject.FactoryModuleBuilder;\n\npublic class SignUsingTemporaryUrls extends AbstractModule {\n\n   @Override\n   protected void configure() {\n      install(new FactoryModuleBuilder().build(Factory.class));\n   }\n\n   interface Factory {\n      RegionScopedTemporaryUrlBlobSigner create(String in);\n   }\n\n   @Provides\n   Function<String, BlobRequestSigner> blobRequestSigner(FactoryFunction in) {\n      return in;\n   }\n\n   static class FactoryFunction extends ForwardingObject implements Function<String, BlobRequestSigner> {\n      @Inject\n      Factory delegate;\n\n      @Override\n      protected Factory delegate() {\n         return delegate;\n      }\n\n      @Override\n      public BlobRequestSigner apply(String in) {\n         return delegate.create(in);\n      }\n   }\n\n   @Provides\n   @TimeStamp\n   protected Long unixEpochTimestamp() {\n      return System.currentTimeMillis() / 1000;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/blobstore/config/SwiftBlobStoreContextModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.blobstore.config;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.BlobStoreContext;\nimport org.jclouds.blobstore.attr.ConsistencyModel;\nimport org.jclouds.openstack.swift.v1.blobstore.RegionScopedBlobStoreContext;\nimport org.jclouds.openstack.swift.v1.blobstore.RegionScopedSwiftBlobStore;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ForwardingObject;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Provides;\nimport com.google.inject.assistedinject.FactoryModuleBuilder;\n\npublic class SwiftBlobStoreContextModule extends AbstractModule {\n\n   @Override\n   protected void configure() {\n      bind(ConsistencyModel.class).toInstance(ConsistencyModel.EVENTUAL);\n      bind(BlobStoreContext.class).to(RegionScopedBlobStoreContext.class);\n      install(new FactoryModuleBuilder().build(Factory.class));\n   }\n\n   public interface Factory {\n      RegionScopedSwiftBlobStore create(String in);\n   }\n\n   @Provides\n   final Function<String, BlobStore> blobStore(FactoryFunction in) {\n      return in;\n   }\n\n   public static class FactoryFunction extends ForwardingObject implements Function<String, BlobStore> {\n      @Inject\n      Factory delegate;\n\n      @Override\n      protected Factory delegate() {\n         return delegate;\n      }\n\n      @Override\n      public BlobStore apply(String in) {\n         return delegate.create(in);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/blobstore/functions/ToBlobMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.blobstore.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.blobstore.domain.MutableBlobMetadata;\nimport org.jclouds.blobstore.domain.StorageType;\nimport org.jclouds.blobstore.domain.Tier;\nimport org.jclouds.blobstore.domain.internal.MutableBlobMetadataImpl;\nimport org.jclouds.openstack.swift.v1.domain.Container;\nimport org.jclouds.openstack.swift.v1.domain.SwiftObject;\nimport org.jclouds.openstack.swift.v1.functions.ParseObjectListFromResponse;\n\nimport com.google.common.base.Function;\n\npublic class ToBlobMetadata implements Function<SwiftObject, MutableBlobMetadata> {\n\n   private final Container container;\n\n   public ToBlobMetadata(Container container) {\n      this.container = checkNotNull(container, \"container\");\n   }\n\n   @Override\n   public MutableBlobMetadata apply(SwiftObject from) {\n      if (from == null)\n         return null;\n      MutableBlobMetadata to = new MutableBlobMetadataImpl();\n      to.setContainer(container.getName());\n      if (container.getAnybodyRead().isPresent()) {\n         to.setPublicUri(from.getUri());\n      }\n      String eTag = from.getETag();\n      to.setUri(from.getUri());\n      to.setETag(eTag);\n      to.setName(from.getName());\n      to.setLastModified(from.getLastModified());\n      to.setContentMetadata(from.getPayload().getContentMetadata());\n      to.getContentMetadata().setContentMD5(from.getPayload().getContentMetadata().getContentMD5AsHashCode());\n      to.getContentMetadata().setExpires(from.getPayload().getContentMetadata().getExpires());\n      to.setUserMetadata(from.getMetadata());\n      if (eTag != null && eTag.equals(ParseObjectListFromResponse.SUBDIR_ETAG)) {\n         to.setType(StorageType.FOLDER);\n      } else {\n         to.setType(StorageType.BLOB);\n      }\n      to.setSize(from.getPayload().getContentMetadata().getContentLength());\n      to.setTier(Tier.STANDARD);\n      return to;\n   }\n\n   @Override\n   public String toString() {\n      return \"ObjectToBlobMetadata(\" + container + \")\";\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/blobstore/functions/ToListContainerOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.blobstore.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.blobstore.options.ListContainerOptions;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Strings;\n\npublic class ToListContainerOptions implements\n      Function<ListContainerOptions, org.jclouds.openstack.swift.v1.options.ListContainerOptions> {\n\n   @Override\n   public org.jclouds.openstack.swift.v1.options.ListContainerOptions apply(ListContainerOptions from) {\n      checkNotNull(from, \"set options to instance NONE instead of passing null\");\n      if (from.getDir() != null && from.getPrefix() != null) {\n         throw new IllegalArgumentException(\"Cannot set both directory and prefix\");\n      }\n      if ((from.getDir() != null || from.isRecursive()) && (from.getDelimiter() != null)) {\n         throw new IllegalArgumentException(\"Cannot set both delimiter and recursive or directory\");\n      }\n      org.jclouds.openstack.swift.v1.options.ListContainerOptions options = new org.jclouds.openstack.swift.v1.options.ListContainerOptions();\n\n      if (from.getDir() != null) {\n         if (from.isRecursive()) {\n            options.prefix(from.getDir().endsWith(\"/\") ? from.getDir() : from.getDir() + \"/\");\n         } else {\n            options.path(from.getDir());\n         }\n      } else if (!from.isRecursive()) {\n         options.delimiter('/');\n      }\n      if (!Strings.isNullOrEmpty(from.getDelimiter())) {\n         if (from.getDelimiter().length() != 1) {\n            throw new IllegalArgumentException(\"Delimiter must be a single character\");\n         }\n         options.delimiter(from.getDelimiter().charAt(0));\n      }\n      if (from.getPrefix() != null) {\n         options.prefix(from.getPrefix());\n      }\n      if (from.getMarker() != null) {\n         options.marker(from.getMarker());\n      }\n      if (from.getMaxResults() != null) {\n         options.limit(from.getMaxResults());\n      }\n      return options;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/blobstore/functions/ToResourceMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.blobstore.functions;\n\nimport org.jclouds.blobstore.domain.MutableStorageMetadata;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.domain.StorageType;\nimport org.jclouds.blobstore.domain.internal.MutableStorageMetadataImpl;\nimport org.jclouds.domain.Location;\nimport org.jclouds.openstack.swift.v1.domain.Container;\n\nimport com.google.common.base.Function;\n\npublic class ToResourceMetadata implements Function<Container, StorageMetadata> {\n   private Location region;\n\n   public ToResourceMetadata(Location region) {\n      this.region = region;\n   }\n\n   @Override\n   public StorageMetadata apply(Container from) {\n      MutableStorageMetadata to = new MutableStorageMetadataImpl();\n      to.setName(from.getName());\n      to.setLocation(region);\n      to.setType(StorageType.CONTAINER);\n      to.setUserMetadata(from.getMetadata());\n      return to;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/config/BaseSwiftHttpApiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.config;\n\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.annotation.ClientError;\nimport org.jclouds.http.annotation.Redirection;\nimport org.jclouds.http.annotation.ServerError;\nimport org.jclouds.openstack.swift.v1.SwiftApi;\nimport org.jclouds.openstack.swift.v1.handlers.SwiftErrorHandler;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.config.HttpApiModule;\n\n@ConfiguresHttpApi\npublic abstract class BaseSwiftHttpApiModule<A extends SwiftApi> extends HttpApiModule<A> {\n\n   protected BaseSwiftHttpApiModule(Class<A> api) {\n      super(api);\n   }\n\n   @Override\n   protected void configure() {\n      super.configure();\n   }\n\n   @Override\n   protected void bindErrorHandlers() {\n      bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(SwiftErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(SwiftErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(SwiftErrorHandler.class);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/config/SwiftAuthenticationModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.config;\n\nimport static org.jclouds.http.HttpUtils.releasePayload;\nimport static org.jclouds.http.Uris.uriBuilder;\nimport static org.jclouds.openstack.keystone.auth.AuthHeaders.AUTH_TOKEN;\nimport static org.jclouds.openstack.swift.v1.reference.TempAuthHeaders.STORAGE_URL;\nimport static org.jclouds.openstack.swift.v1.reference.TempAuthHeaders.TEMP_AUTH_HEADER_USER;\nimport static org.jclouds.openstack.v2_0.ServiceType.OBJECT_STORE;\nimport static org.jclouds.rest.config.BinderUtils.bindHttpApi;\n\nimport java.io.Closeable;\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.Map;\nimport java.util.concurrent.TimeUnit;\n\nimport jakarta.inject.Inject;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.keystone.auth.config.AuthenticationModule;\nimport org.jclouds.openstack.keystone.auth.domain.AuthInfo;\nimport org.jclouds.openstack.keystone.v2_0.domain.Access;\nimport org.jclouds.openstack.keystone.v2_0.domain.Endpoint;\nimport org.jclouds.openstack.keystone.v2_0.domain.Service;\nimport org.jclouds.openstack.keystone.v2_0.domain.Token;\nimport org.jclouds.openstack.keystone.v2_0.domain.User;\nimport org.jclouds.openstack.swift.v1.binders.TempAuthBinder;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.InvocationContext;\nimport org.jclouds.rest.annotations.ApiVersion;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.VirtualHost;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.inject.Injector;\nimport com.google.inject.name.Named;\n\n/**\n * When {@link org.jclouds.openstack.keystone.config.KeystoneProperties#CREDENTIAL_TYPE} is set to {@code\n * tempAuthCredentials}, do not use Keystone. Instead, bridge TempAuth to Keystone by faking a service catalog out of\n * the storage url. The {@link ContextBuilder#endpoint(String) endpoint} must be set to the TempAuth url, usually ending\n * in {@code auth/v1.0/}.\n */\npublic final class SwiftAuthenticationModule extends AuthenticationModule {\n   @Override\n   protected void configure() {\n      super.configure();\n      bindHttpApi(binder(), TempAuthApi.class);\n   }\n\n   @Override\n   protected Map<String, Function<Credentials, AuthInfo>> authenticationMethods(Injector i) {\n      return ImmutableMap.<String, Function<Credentials, AuthInfo>> builder()\n            .putAll(super.authenticationMethods(i))\n            .put(\"tempAuthCredentials\", i.getInstance(TempAuth.class))\n            .build();\n   }\n   \n   static final class TempAuth implements Function<Credentials, AuthInfo> {\n      private final TempAuthApi delegate;\n\n      @Inject TempAuth(TempAuthApi delegate) {\n         this.delegate = delegate;\n      }\n\n      @Override public AuthInfo apply(Credentials input) {\n         return delegate.auth(input);\n      }\n   }\n\n   @VirtualHost\n   interface TempAuthApi  extends Closeable {\n\n      @Named(\"TempAuth\")\n      @GET\n      @Consumes\n      @ResponseParser(AdaptTempAuthResponseToAccess.class)\n      Access auth(@BinderParam(TempAuthBinder.class) Credentials credentials);\n   }\n\n   static final class AdaptTempAuthResponseToAccess\n         implements Function<HttpResponse, Access>, InvocationContext<AdaptTempAuthResponseToAccess> {\n\n      private final String identityHeaderNameUser;\n\n      private final String apiVersion;\n\n      private String host;\n      private String username;\n\n      @Inject AdaptTempAuthResponseToAccess(@ApiVersion String apiVersion, @Named(TEMP_AUTH_HEADER_USER) String identityHeaderNameUser) {\n         this.apiVersion = apiVersion;\n         this.identityHeaderNameUser = identityHeaderNameUser;\n      }\n\n      @Override public Access apply(HttpResponse from) {\n         releasePayload(from);\n         URI storageUrl = null;\n         String authToken = null;\n         for (Map.Entry<String, String> entry : from.getHeaders().entries()) {\n            String header = entry.getKey();\n            if (header.equalsIgnoreCase(STORAGE_URL)) {\n               storageUrl = getURI(entry.getValue());\n            } else if (header.equalsIgnoreCase(AUTH_TOKEN)) {\n               authToken = entry.getValue();\n            }\n         }\n         if (storageUrl == null || authToken == null) {\n            throw new AuthorizationException(\"Invalid headers in TempAuth response \" + from);\n         }\n         // For portability with keystone, based on common knowledge that these tokens tend to expire in 24 hours\n         // http://docs.openstack.org/api/openstack-object-storage/1.0/content/authentication-object-dev-guide.html\n         Date expires = new Date(System.currentTimeMillis() + TimeUnit.HOURS.toMillis(24));\n         return Access.builder()\n               .user(User.builder().id(username).name(username).build())\n               .token(Token.builder().id(authToken).expires(expires).build())\n               .service(Service.builder().name(\"Object Storage\").type(OBJECT_STORE)\n               .endpoint(Endpoint.builder().publicURL(storageUrl).id(apiVersion).region(storageUrl.getHost()).build())\n               .build()).build();\n      }\n\n      // TODO: find the swift configuration or bug related to returning localhost\n      private URI getURI(String headerValue) {\n         if (headerValue == null)\n            return null;\n         URI toReturn = URI.create(headerValue);\n         if (!\"127.0.0.1\".equals(toReturn.getHost()))\n            return toReturn;\n         return uriBuilder(toReturn).host(host).build();\n      }\n\n      @Override\n      public AdaptTempAuthResponseToAccess setContext(HttpRequest request) {\n         String host = request.getEndpoint().getHost();\n         this.host = host;\n         this.username = request.getFirstHeaderOrNull(identityHeaderNameUser);\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/config/SwiftHttpApiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.config;\nimport org.jclouds.openstack.swift.v1.SwiftApi;\nimport org.jclouds.rest.ConfiguresHttpApi;\n\n@ConfiguresHttpApi\npublic class SwiftHttpApiModule extends BaseSwiftHttpApiModule<SwiftApi> {\n\n   public SwiftHttpApiModule() {\n      super(SwiftApi.class);\n   }\n\n   @Override\n   protected void configure() {\n      super.configure();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/config/SwiftTypeAdapters.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.config;\n\nimport java.io.IOException;\nimport java.lang.reflect.Type;\nimport java.net.URI;\nimport java.util.Map;\n\nimport org.jclouds.json.config.GsonModule.DateAdapter;\nimport org.jclouds.json.config.GsonModule.Iso8601DateAdapter;\nimport org.jclouds.openstack.swift.v1.domain.BulkDeleteResponse;\nimport org.jclouds.openstack.swift.v1.domain.ExtractArchiveResponse;\nimport org.jclouds.openstack.swift.v1.domain.DeleteStaticLargeObjectResponse;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMap.Builder;\nimport com.google.gson.TypeAdapter;\nimport com.google.gson.stream.JsonReader;\nimport com.google.gson.stream.JsonWriter;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Provides;\n\npublic class SwiftTypeAdapters extends AbstractModule {\n\n   @Override\n   protected void configure() {\n      bind(DateAdapter.class).to(Iso8601DateAdapter.class);\n   }\n\n   @Provides\n   public Map<Type, Object> provideCustomAdapterBindings() {\n      return ImmutableMap.<Type, Object> builder()\n            .put(ExtractArchiveResponse.class, new ExtractArchiveResponseAdapter())\n            .put(BulkDeleteResponse.class, new BulkDeleteResponseAdapter())\n            .put(DeleteStaticLargeObjectResponse.class, new StaticLargeObjectResponseAdapter())\n            .build();\n   }\n\n   static class ExtractArchiveResponseAdapter extends TypeAdapter<ExtractArchiveResponse> {\n\n      @Override\n      public ExtractArchiveResponse read(JsonReader reader) throws IOException {\n         int created = 0;\n         Builder<String, String> errors = ImmutableMap.<String, String> builder();\n         reader.beginObject();\n         while (reader.hasNext()) {\n            String key = reader.nextName();\n            if (key.equals(\"Number Files Created\")) {\n               created = reader.nextInt();\n            } else if (key.equals(\"Errors\")) {\n               readErrors(reader, errors);\n            } else {\n               reader.skipValue();\n            }\n         }\n         reader.endObject();\n         return ExtractArchiveResponse.create(created, errors.build());\n      }\n\n      @Override\n      public void write(JsonWriter arg0, ExtractArchiveResponse arg1) throws IOException {\n         throw new UnsupportedOperationException();\n      }\n   }\n\n   static class BulkDeleteResponseAdapter extends TypeAdapter<BulkDeleteResponse> {\n\n      @Override\n      public BulkDeleteResponse read(JsonReader reader) throws IOException {\n         int deleted = 0;\n         int notFound = 0;\n         Builder<String, String> errors = ImmutableMap.<String, String> builder();\n         reader.beginObject();\n         while (reader.hasNext()) {\n            String key = reader.nextName();\n            if (key.equals(\"Number Deleted\")) {\n               deleted = reader.nextInt();\n            } else if (key.equals(\"Number Not Found\")) {\n               notFound = reader.nextInt();\n            } else if (key.equals(\"Errors\")) {\n               readErrors(reader, errors);\n            } else {\n               reader.skipValue();\n            }\n         }\n         reader.endObject();\n         return BulkDeleteResponse.create(deleted, notFound, errors.build());\n      }\n\n      @Override\n      public void write(JsonWriter arg0, BulkDeleteResponse arg1) throws IOException {\n         throw new UnsupportedOperationException();\n      }\n   }\n\n   static final class StaticLargeObjectResponseAdapter extends TypeAdapter<DeleteStaticLargeObjectResponse> {\n\n      @Override\n      public DeleteStaticLargeObjectResponse read(JsonReader reader) throws IOException {\n         String status = \"\";\n         int deleted = 0;\n         int notFound = 0;\n         Builder<String, String> errors = ImmutableMap.<String, String> builder();\n         reader.beginObject();\n         while (reader.hasNext()) {\n            String key = reader.nextName();\n            if (key.equals(\"Response Status\")) {\n               status = reader.nextString();\n            } else if (key.equals(\"Number Deleted\")) {\n               deleted = reader.nextInt();\n            } else if (key.equals(\"Number Not Found\")) {\n               notFound = reader.nextInt();\n            } else if (key.equals(\"Errors\")) {\n               readErrors(reader, errors);\n            } else {\n               // Response Body\n               reader.skipValue();\n            }\n         }\n         reader.endObject();\n         return DeleteStaticLargeObjectResponse.create(status, deleted, notFound, errors.build());\n      }\n\n      @Override\n      public void write(JsonWriter arg0, DeleteStaticLargeObjectResponse arg1) throws IOException {\n         throw new UnsupportedOperationException();\n      }\n   }\n\n   static void readErrors(JsonReader reader, Builder<String, String> errors) throws IOException {\n      reader.beginArray();\n      while (reader.hasNext()) {\n         reader.beginArray();\n         String decodedPath = URI.create(reader.nextString()).getPath();\n         errors.put(decodedPath, reader.nextString());\n         reader.endArray();\n      }\n      reader.endArray();\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/domain/Account.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\nimport java.util.Map.Entry;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.Multimap;\n\n/**\n * Represents an Account in OpenStack Object Storage.\n * \n * @see org.jclouds.openstack.swift.v1.features.AccountApi\n */\npublic class Account {\n\n   private final long containerCount;\n   private final long objectCount;\n   private final long bytesUsed;\n   private final Map<String, String> metadata;\n   private final Multimap<String, String> headers;\n\n   // parsed from headers, so ConstructorProperties here would be misleading\n   protected Account(long containerCount, long objectCount, long bytesUsed, Map<String, String> metadata,\n         Multimap<String, String> headers) {\n      this.containerCount = containerCount;\n      this.objectCount = objectCount;\n      this.bytesUsed = bytesUsed;\n      this.metadata = metadata == null ? ImmutableMap.<String, String> of() : metadata;\n      this.headers = headers == null ? ImmutableMultimap.<String, String> of() : headers;\n   }\n\n   /**\n    * @return The count of containers for this account.\n    */\n   public long getContainerCount() {\n      return containerCount;\n   }\n\n   /**\n    * @return The count of objects for this account.\n    */\n   public long getObjectCount() {\n      return objectCount;\n   }\n\n   /**\n    * @return The number of bytes used by this account.\n    */\n   public long getBytesUsed() {\n      return bytesUsed;\n   }\n\n   /**\n    * @return The {@link Optional&lt;String&gt;} temporary URL key for this account.\n    */\n   public Optional<String> getTemporaryUrlKey() {\n      return Optional.fromNullable(metadata.get(\"temp-url-key\"));\n   }\n\n   /**\n    * <h3>NOTE</h3>\n    * In current swift implementations, headers keys are lower-cased. This means\n    * characters such as turkish will probably not work out well.\n    *\n    * @return a {@code Map<String, String>} containing the account metadata.\n    */\n   public Map<String, String> getMetadata() {\n      return metadata;\n   }\n\n   /**\n    * @return The HTTP headers for this account.\n    */\n   public Multimap<String, String> getHeaders() {\n      return headers;\n   }\n\n   @Override\n   public boolean equals(Object object) {\n      if (this == object) {\n         return true;\n      }\n      if (object instanceof Account) {\n         Account that = Account.class.cast(object);\n         return equal(getContainerCount(), that.getContainerCount())\n               && equal(getObjectCount(), that.getObjectCount())\n               && equal(getBytesUsed(), that.getBytesUsed())\n               && equal(getMetadata(), that.getMetadata());\n      } else {\n         return false;\n      }\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(getContainerCount(), getObjectCount(), getBytesUsed(), getMetadata());\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   protected ToStringHelper string() {\n      return toStringHelper(this)\n            .add(\"containerCount\", getContainerCount())\n            .add(\"objectCount\", getObjectCount())\n            .add(\"bytesUsed\", getBytesUsed())\n            .add(\"metadata\", getMetadata());\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().fromAccount(this);\n   }\n\n   public static class Builder {\n      protected long containerCount;\n      protected long objectCount;\n      protected long bytesUsed;\n      protected Multimap<String, String> headers = ImmutableMultimap.of();\n      protected Map<String, String> metadata = ImmutableMap.of();\n\n      /**\n       * @param containerCount  the count of containers for this account.\n       *\n       * @see Account#getContainerCount()\n       */\n      public Builder containerCount(long containerCount) {\n         this.containerCount = containerCount;\n         return this;\n      }\n\n      /**\n       * @param objectCount  the count of objects for this account.\n       *\n       * @see Account#getObjectCount()\n       */\n      public Builder objectCount(long objectCount) {\n         this.objectCount = objectCount;\n         return this;\n      }\n\n      /**\n       * @param bytesUsed  the number of bytes used by this account.\n       *\n       * @see Account#getBytesUsed()\n       */\n      public Builder bytesUsed(long bytesUsed) {\n         this.bytesUsed = bytesUsed;\n         return this;\n      }\n\n      /**\n       * <h3>NOTE</h3>\n       * This method will lower-case all metadata keys due to a Swift implementation\n       * decision.\n       *\n       * @param metadata  the metadata for this account. \n       *\n       * @see Account#getMetadata()\n       */\n      public Builder metadata(Map<String, String> metadata) {\n         ImmutableMap.Builder<String, String> builder = ImmutableMap.<String, String> builder();\n         for (Entry<String, String> entry : checkNotNull(metadata, \"metadata\").entrySet()) {\n            builder.put(entry.getKey().toLowerCase(), entry.getValue());\n         }\n         this.metadata = builder.build();\n         return this;\n      }\n\n      /**\n       * @see Account#getHeaders()\n       */\n      public Builder headers(Multimap<String, String> headers) {\n        this.headers = headers;\n        return this;\n      }\n\n      public Account build() {\n         return new Account(containerCount, objectCount, bytesUsed, metadata, headers);\n      }\n\n      public Builder fromAccount(Account from) {\n         return containerCount(from.getContainerCount())\n               .objectCount(from.getObjectCount())\n               .bytesUsed(from.getBytesUsed())\n               .metadata(from.getMetadata())\n               .headers(from.getHeaders());\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/domain/BulkDeleteResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Represents a response from a Bulk Delete request.\n * \n * @see org.jclouds.openstack.swift.v1.features.BulkApi\n */\npublic class BulkDeleteResponse {\n   public static BulkDeleteResponse create(int deleted, int notFound, Map<String, String> errors) {\n      return new BulkDeleteResponse(deleted, notFound, errors);\n   }\n\n   private final int deleted;\n   private final int notFound;\n   private final Map<String, String> errors;\n\n   private BulkDeleteResponse(int deleted, int notFound, Map<String, String> errors) {\n      this.deleted = deleted;\n      this.notFound = notFound;\n      this.errors = checkNotNull(errors, \"errors\");\n   }\n\n   /** \n    * @return The number of files deleted.\n    * */\n   public int getDeleted() {\n      return deleted;\n   }\n\n   /** \n    * @return The number of files not found.\n    */\n   public int getNotFound() {\n      return notFound;\n   }\n\n   /** \n    * @return a {@code Map<String, String>} containing each path that failed \n    *         to be deleted and its corresponding error response.\n    */\n   public Map<String, String> getErrors() {\n      return errors;\n   }\n\n   @Override\n   public boolean equals(Object object) {\n      if (this == object) {\n         return true;\n      }\n      if (object instanceof BulkDeleteResponse) {\n         BulkDeleteResponse that = BulkDeleteResponse.class.cast(object);\n         return equal(getDeleted(), that.getDeleted())\n               && equal(getNotFound(), that.getNotFound())\n               && equal(getErrors(), that.getErrors());\n      } else {\n         return false;\n      }\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(getDeleted(), getNotFound(), getErrors());\n   }\n\n   protected ToStringHelper string() {\n      return toStringHelper(this)\n            .add(\"deleted\", getDeleted())\n            .add(\"notFound\", getNotFound())\n            .add(\"errors\", getErrors());\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/domain/Container.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.Multimap;\n\n/**\n * Represents a Container in OpenStack Object Storage.\n * \n * @see org.jclouds.openstack.swift.v1.features.ContainerApi\n */\npublic class Container implements Comparable<Container> {\n\n   private final String name;\n   private final Long objectCount;\n   private final Long bytesUsed;\n   private final Optional<Boolean> anybodyRead;\n   private final Map<String, String> metadata;\n   private final Multimap<String, String> headers;\n\n   @ConstructorProperties({ \"name\", \"count\", \"bytes\", \"anybodyRead\", \"metadata\", \"headers\"})\n   protected Container(String name, Long objectCount, Long bytesUsed, Optional<Boolean> anybodyRead,\n         Map<String, String> metadata, Multimap<String, String> headers) {\n      this.name = checkNotNull(name, \"name\");\n      this.objectCount = objectCount;\n      this.bytesUsed = bytesUsed;\n      this.anybodyRead = anybodyRead == null ? Optional.<Boolean> absent() : anybodyRead;\n      this.metadata = metadata == null ? ImmutableMap.<String, String> of() : metadata;\n      this.headers = headers == null ? ImmutableMultimap.<String, String> of() : headers;\n   }\n\n   /**\n    * @return The name of this container.\n    */\n   public String getName() {\n      return name;\n   }\n\n   /**\n    * @return The count of objects for this container.\n    */\n   public Long getObjectCount() {\n      return objectCount;\n   }\n\n   /**\n    * @return The number of bytes used by this container.\n    */\n   public Long getBytesUsed() {\n      return bytesUsed;\n   }\n\n   /**\n    * Absent except in {@link ContainerApi#get(String) Get Container} commands.\n    * \n    * @return true  if this container is publicly readable, false otherwise.\n    * \n    * @see org.jclouds.openstack.swift.v1.options.CreateContainerOptions#anybodyRead()\n    */\n   public Optional<Boolean> getAnybodyRead() {\n      return anybodyRead;\n   }\n\n   /**\n    * <h3>NOTE</h3>\n    * In current swift implementations, headers keys are lower-cased. This means\n    * characters such as turkish will probably not work out well.\n    * \n    * @return a {@code Map<String, String>} containing this container's metadata.\n    */\n   public Map<String, String> getMetadata() {\n      return metadata;\n   }\n\n   /**\n    * @return The HTTP headers for this account.\n    */\n   public Multimap<String, String> getHeaders() {\n      return headers;\n   }\n\n   @Override\n   public boolean equals(Object object) {\n      if (this == object) {\n         return true;\n      }\n      if (object instanceof Container) {\n         final Container that = Container.class.cast(object);\n         return equal(getName(), that.getName())\n               && equal(getObjectCount(), that.getObjectCount())\n               && equal(getBytesUsed(), that.getBytesUsed())\n               && equal(getMetadata(), that.getMetadata());\n      } else {\n         return false;\n      }\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(getName(), getObjectCount(), getBytesUsed(), getAnybodyRead(), getMetadata());\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   protected ToStringHelper string() {\n      return toStringHelper(this).omitNullValues()\n            .add(\"name\", getName())\n            .add(\"objectCount\", getObjectCount())\n            .add(\"bytesUsed\", getBytesUsed())\n            .add(\"anybodyRead\", getAnybodyRead().orNull())\n            .add(\"metadata\", getMetadata());\n   }\n\n   @Override\n   public int compareTo(Container that) {\n      if (that == null)\n         return 1;\n      if (this == that)\n         return 0;\n      return this.getName().compareTo(that.getName());\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().fromContainer(this);\n   }\n\n   public static class Builder {\n      protected String name;\n      protected Long objectCount;\n      protected Long bytesUsed;\n      protected Optional<Boolean> anybodyRead = Optional.absent();\n      protected Map<String, String> metadata = ImmutableMap.of();\n      protected Multimap<String, String> headers = ImmutableMultimap.of();\n\n      /**\n       * @see Container#getName()\n       */\n      public Builder name(String name) {\n         this.name = checkNotNull(name, \"name\");\n         return this;\n      }\n\n      /**\n       * @see Container#getObjectCount()\n       */\n      public Builder objectCount(Long objectCount) {\n         this.objectCount = objectCount;\n         return this;\n      }\n\n      /**\n       * @see Container#getBytesUsed()\n       */\n      public Builder bytesUsed(Long bytesUsed) {\n         this.bytesUsed = bytesUsed;\n         return this;\n      }\n\n      /**\n       * @see Container#getAnybodyRead()\n       */\n      public Builder anybodyRead(Boolean anybodyRead) {\n         this.anybodyRead = Optional.fromNullable(anybodyRead);\n         return this;\n      }\n\n      /**\n       * <h3>NOTE</h3>\n       * This method will lower-case all metadata keys.\n       * \n       * @see Container#getMetadata()\n       */\n      public Builder metadata(Map<String, String> metadata) {\n         ImmutableMap.Builder<String, String> builder = ImmutableMap.<String, String> builder();\n         for (Entry<String, String> entry : checkNotNull(metadata, \"metadata\").entrySet()) {\n            builder.put(entry.getKey().toLowerCase(), entry.getValue());\n         }\n         this.metadata = builder.build();\n         return this;\n      }\n\n      /**\n       * @see Container#getHeaders()\n       */\n      public Builder headers(Multimap<String, String> headers) {\n         this.headers = headers;\n         return this;\n      }\n\n      public Container build() {\n         return new Container(name, objectCount, bytesUsed, anybodyRead, metadata, headers);\n      }\n\n      public Builder fromContainer(Container from) {\n         return name(from.getName())\n               .objectCount(from.getObjectCount())\n               .bytesUsed(from.getBytesUsed())\n               .anybodyRead(from.getAnybodyRead().orNull())\n               .metadata(from.getMetadata())\n               .headers(from.getHeaders());\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/domain/DeleteStaticLargeObjectResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.openstack.swift.v1.domain;\n\nimport java.util.Map;\n\nimport com.google.auto.value.AutoValue;\n\n/**\n * Represents a response from a Static Large Object Delete request.\n *\n * @see org.jclouds.openstack.swift.v1.features.StaticLargeObjectApi\n */\n@AutoValue\npublic abstract class DeleteStaticLargeObjectResponse {\n   public static DeleteStaticLargeObjectResponse create(String status, int deleted, int notFound, Map<String, String> errors) {\n      return new AutoValue_DeleteStaticLargeObjectResponse(status, deleted, notFound, errors);\n   }\n\n   public abstract String status();\n   public abstract int deleted();\n   public abstract int notFound();\n   public abstract Map<String, String> errors();\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/domain/ExtractArchiveResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Represents a response from an Extract Archive request.\n *\n * @see org.jclouds.openstack.swift.v1.features.BulkApi\n */\npublic class ExtractArchiveResponse {\n   public static ExtractArchiveResponse create(int created, Map<String, String> errors) {\n      return new ExtractArchiveResponse(created, errors);\n   }\n\n   private final int created;\n   private final Map<String, String> errors;\n\n   private ExtractArchiveResponse(int created, Map<String, String> errors) {\n      this.created = created;\n      this.errors = checkNotNull(errors, \"errors\");\n   }\n\n   /** \n    * @return The number of files created.\n    */\n   public int getCreated() {\n      return created;\n   }\n\n   /** \n    * @return a {@code Map<String, String>} containing each path that failed \n    *         to be created and its corresponding error response.\n    */\n   public Map<String, String> getErrors() {\n      return errors;\n   }\n\n   @Override\n   public boolean equals(Object object) {\n      if (this == object) {\n         return true;\n      }\n      if (object instanceof ExtractArchiveResponse) {\n         ExtractArchiveResponse that = ExtractArchiveResponse.class.cast(object);\n         return equal(getCreated(), that.getCreated())\n               && equal(getErrors(), that.getErrors());\n      } else {\n         return false;\n      }\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(getCreated(), getErrors());\n   }\n\n   protected ToStringHelper string() {\n      return toStringHelper(this)\n            .add(\"created\", getCreated())\n            .add(\"errors\", getErrors());\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/domain/ObjectList.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.List;\n\nimport com.google.common.collect.ForwardingList;\n\n/**\n * Represents a list of objects in a container.\n * \n * @see Container \n * @see SwiftObject\n * @see org.jclouds.openstack.swift.v1.features.ObjectApi#list()\n */\npublic class ObjectList extends ForwardingList<SwiftObject> {\n\n   public static ObjectList create(List<SwiftObject> objects, Container container) {\n      return new ObjectList(objects, container);\n   }\n\n   private final List<SwiftObject> objects;\n   private final Container container;\n\n   protected ObjectList(List<SwiftObject> objects, Container container) {\n      this.objects = checkNotNull(objects, \"objects\");\n      this.container = checkNotNull(container, \"container\");\n   }\n\n   /**\n    * @return the parent {@link Container} the objects reside in.\n    */\n   public Container getContainer() {\n      return container;\n   }\n\n   @Override\n   protected List<SwiftObject> delegate() {\n      return objects;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/domain/Segment.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Named;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Represents a single segment of a multi-part upload.\n * \n * @see org.jclouds.openstack.swift.v1.features.StaticLargeObjectApi\n */\npublic class Segment {\n\n   private final String path;\n   private final String etag;\n   @Named(\"size_bytes\")\n   private final long sizeBytes;\n\n   private Segment(String path, String etag, long sizeBytes) {\n      this.path = checkNotNull(path, \"path\");\n      this.etag = checkNotNull(etag, \"etag of %s\", path);\n      this.sizeBytes = sizeBytes;\n   }\n\n   /**\n    * @return The container and object name in the format: {@code <container-name>/<object-name>}\n    */\n   public String getPath() {\n      return path;\n   }\n\n   /**\n    * @return The ETag of the content of the segment object.\n    */\n   public String getETag() {\n      return etag;\n   }\n\n   /**\n    * @return The size of the segment object.\n    */\n   public long getSizeBytes() {\n      return sizeBytes;\n   }\n\n   @Override\n   public boolean equals(Object object) {\n      if (this == object) {\n         return true;\n      }\n      if (object instanceof Segment) {\n         Segment that = Segment.class.cast(object);\n         return equal(getPath(), that.getPath())\n               && equal(getETag(), that.getETag())\n               && equal(getSizeBytes(), that.getSizeBytes());\n      } else {\n         return false;\n      }\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(getPath(), getETag(), getSizeBytes());\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   protected ToStringHelper string() {\n      return toStringHelper(this)\n            .add(\"path\", getPath())\n            .add(\"etag\", getETag())\n            .add(\"sizeBytes\", getSizeBytes());\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n      protected String path;\n      protected String etag;\n      protected long sizeBytes;\n\n      /**\n       * @see Segment#getPath()\n       */\n      public Builder path(String path) {\n         this.path = path;\n         return this;\n      }\n\n      /**\n       * @see Segment#getEtag()\n       */\n      public Builder etag(String etag) {\n         this.etag = etag;\n         return this;\n      }\n\n      /**\n       * @see Segment#getSizeBytes()\n       */\n      public Builder sizeBytes(long sizeBytes) {\n         this.sizeBytes = sizeBytes;\n         return this;\n      }\n\n      public Segment build() {\n         return new Segment(path, etag, sizeBytes);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/domain/SwiftObject.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\nimport org.jclouds.io.Payload;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.Multimap;\n\n/**\n * Represents an object in OpenStack Object Storage.\n * \n * \n * @see ObjectApi\n */\npublic class SwiftObject implements Comparable<SwiftObject> {\n\n   private final String name;\n   private final URI uri;\n   private final String etag;\n   private final Date lastModified;\n   private final Multimap<String, String> headers;\n   private final Map<String, String> metadata;\n   private final Payload payload;\n\n   protected SwiftObject(String name, URI uri, String etag, Date lastModified,\n         Multimap<String, String> headers, Map<String, String> metadata, Payload payload) {\n      this.name = checkNotNull(name, \"name\");\n      this.uri = checkNotNull(uri, \"uri of %s\", name);\n      this.etag = etag != null ? etag.replace(\"\\\"\", \"\") : null;\n      this.lastModified = checkNotNull(lastModified, \"lastModified of %s\", name);\n      this.headers = headers == null ? ImmutableMultimap.<String, String> of() : checkNotNull(headers, \"headers of %s\", name);\n      this.metadata = metadata == null ? ImmutableMap.<String, String> of() : metadata;\n      this.payload = checkNotNull(payload, \"payload of %s\", name);\n   }\n\n   /**\n    * @return The name of this object.\n    */\n   public String getName() {\n      return name;\n   }\n\n   /**\n    * @return The {@link URI} for this object.\n    */\n   public URI getUri() {\n      return uri;\n   }\n\n   /**\n    * @return The ETag of the content of this object.\n    * @deprecated Please use {@link #getETag()} instead. To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   public String getEtag() {\n      return etag;\n   }\n\n   /**\n    * @return The ETag of the content of this object.\n    */\n   public String getETag() {\n      return etag;\n   }\n\n   /**\n    * @return The {@link Date} that this object was last modified.\n    */\n   public Date getLastModified() {\n      return lastModified;\n   }\n\n   /**\n    * @return The HTTP headers for this object.\n    */\n   public Multimap<String, String> getHeaders() {\n      return headers;\n   }\n\n   /**\n    * <h3>NOTE</h3>\n    * In current swift implementations, headers keys are lower-cased. This means\n    * characters such as turkish will probably not work out well.\n    * \n    * @return a {@code Map<String, String>} containing this object's metadata. The map is empty\n    *         except in {@link ObjectApi#head(String) GetObjectMetadata} or\n    *         {@link ObjectApi#get(String) GetObject} commands.\n    */\n   public Map<String, String> getMetadata() {\n      return metadata;\n   }\n\n   /**\n    * <h3>NOTE</h3>\n    * The object will only have a {@link Payload#getInput()} when retrieved via the\n    * {@link ObjectApi#get(String) GetObject} command.\n    * \n    * @return The {@link Payload} for this object.\n    */\n   public Payload getPayload() {\n      return payload;\n   }\n\n   @Override\n   public boolean equals(Object object) {\n      if (this == object) {\n         return true;\n      }\n      if (object instanceof SwiftObject) {\n         final SwiftObject that = SwiftObject.class.cast(object);\n         return equal(getName(), that.getName())\n               && equal(getUri(), that.getUri())\n               && equal(getETag(), that.getETag());\n      } else {\n         return false;\n      }\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(getName(), getUri(), getETag());\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   protected ToStringHelper string() {\n      return toStringHelper(this)\n            .add(\"name\", getName())\n            .add(\"uri\", getUri())\n            .add(\"etag\", getETag())\n            .add(\"lastModified\", getLastModified())\n            .add(\"metadata\", getMetadata());\n   }\n\n   @Override\n   public int compareTo(SwiftObject that) {\n      if (that == null)\n         return 1;\n      if (this == that)\n         return 0;\n      return this.getName().compareTo(that.getName());\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().fromObject(this);\n   }\n\n   public static class Builder {\n      protected String name;\n      protected URI uri;\n      protected String etag;\n      protected Date lastModified;\n      protected Payload payload;\n      protected Multimap<String, String> headers = ImmutableMultimap.of();\n      protected Map<String, String> metadata = ImmutableMap.of();\n\n      /**\n       * @see SwiftObject#getName()\n       */\n      public Builder name(String name) {\n         this.name = checkNotNull(name, \"name\");\n         return this;\n      }\n\n      /**\n       * @see SwiftObject#getUri()\n       */\n      public Builder uri(URI uri) {\n         this.uri = checkNotNull(uri, \"uri\");\n         return this;\n      }\n\n      /**\n       * @see SwiftObject#getETag()\n       */\n      public Builder etag(String etag) {\n         this.etag = etag;\n         return this;\n      }\n\n      /**\n       * @see SwiftObject#getLastModified()\n       */\n      public Builder lastModified(Date lastModified) {\n         this.lastModified = lastModified;\n         return this;\n      }\n\n      /**\n       * @see SwiftObject#getPayload()\n       */\n      public Builder payload(Payload payload) {\n         this.payload = payload;\n         return this;\n      }\n\n      /**\n       * @see SwiftObject#getHeaders()\n       */\n      public Builder headers(Multimap<String, String> headers) {\n         this.headers = headers;\n         return this;\n      }\n\n      /**\n       * Will lower-case all metadata keys due to a swift implementation\n       * decision.\n       * \n       * @see SwiftObject#getMetadata()\n       */\n      public Builder metadata(Map<String, String> metadata) {\n         ImmutableMap.Builder<String, String> builder = ImmutableMap.<String, String> builder();\n         for (Entry<String, String> entry : checkNotNull(metadata, \"metadata\").entrySet()) {\n            builder.put(entry.getKey().toLowerCase(), entry.getValue());\n         }\n         this.metadata = builder.build();\n         return this;\n      }\n\n      public SwiftObject build() {\n         return new SwiftObject(name, uri, etag, lastModified, headers, metadata, payload);\n      }\n\n      public Builder fromObject(SwiftObject from) {\n         return name(from.getName())\n               .uri(from.getUri())\n               .etag(from.getETag())\n               .lastModified(from.getLastModified())\n               .headers(from.getHeaders())\n               .metadata(from.getMetadata())\n               .payload(from.getPayload());\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/features/AccountApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.ACCOUNT_TEMPORARY_URL_KEY;\n\nimport java.util.Map;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.HEAD;\nimport jakarta.ws.rs.HeaderParam;\nimport jakarta.ws.rs.POST;\n\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.swift.v1.binders.BindMetadataToHeaders.BindAccountMetadataToHeaders;\nimport org.jclouds.openstack.swift.v1.binders.BindMetadataToHeaders.BindRemoveAccountMetadataToHeaders;\nimport org.jclouds.openstack.swift.v1.domain.Account;\nimport org.jclouds.openstack.swift.v1.functions.ParseAccountFromHeaders;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\n\nimport com.google.common.annotations.Beta;\n\n/**\n * Provides access to the OpenStack Object Storage (Swift) Account API features.\n *\n * <p/>\n * Account metadata prefixed with {@code X-Account-Meta-} will be converted\n * appropriately using a binder/parser.\n * <p/>\n * This API is new to jclouds and hence is in Beta. That means we need people to use it and give us feedback. Based\n * on that feedback, minor changes to the interfaces may happen. This code will replace\n * org.jclouds.openstack.swift.SwiftClient in jclouds 2.0 and it is recommended you adopt it sooner than later.\n *\n *\n * @see {@link Account}\n */\n@Beta\n@RequestFilters(AuthenticateRequest.class)\n@Consumes(APPLICATION_JSON)\npublic interface AccountApi {\n\n   /**\n    * Gets the {@link Account}.\n    *\n    * @return The {@link Account} object.\n    */\n   @Named(\"account:get\")\n   @HEAD\n   @ResponseParser(ParseAccountFromHeaders.class)\n   Account get();\n\n   /**\n    * Creates or updates the {@link Account} metadata.\n    *\n    * @param metadata  the metadata to create or update.\n    */\n   @Named(\"account:updateMetadata\")\n   @POST\n   void updateMetadata(@BinderParam(BindAccountMetadataToHeaders.class) Map<String, String> metadata);\n\n   /**\n    * Replaces the temporary URL key for the {@link Account}.\n    *\n    * @param temporaryUrlKey  the temporary URL key to update.\n    */\n   @Named(\"account:updateTemporaryUrlKey\")\n   @POST\n   void updateTemporaryUrlKey(@HeaderParam(ACCOUNT_TEMPORARY_URL_KEY) String temporaryUrlKey);\n\n   /**\n    * Deletes metadata from the {@link Account}.\n    *\n    * @param metadata  the metadata to delete.\n    *\n    * @return {@code true} if the metadata was successfully deleted,\n    *         {@code false} if not.\n    */\n   @Named(\"account:deleteMetadata\")\n   @POST\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean deleteMetadata(@BinderParam(BindRemoveAccountMetadataToHeaders.class) Map<String, String> metadata);\n\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/features/BulkApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.features;\n\nimport static com.google.common.collect.Iterables.transform;\nimport static com.google.common.net.UrlEscapers.urlFragmentEscaper;\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\nimport static jakarta.ws.rs.core.MediaType.TEXT_PLAIN;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.QueryParam;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.swift.v1.binders.SetPayload;\nimport org.jclouds.openstack.swift.v1.domain.BulkDeleteResponse;\nimport org.jclouds.openstack.swift.v1.domain.ExtractArchiveResponse;\nimport org.jclouds.rest.Binder;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Joiner;\n\n/**\n * Provides access to the OpenStack Object Storage (Swift) Bulk API features.\n * <p/>\n * This API is new to jclouds and hence is in Beta. That means we need people to use it and give us feedback. Based\n * on that feedback, minor changes to the interfaces may happen. This code will replace\n * org.jclouds.openstack.swift.SwiftClient in jclouds 2.0 and it is recommended you adopt it sooner than later.\n */\n@Beta\n@RequestFilters(AuthenticateRequest.class)\n@Consumes(APPLICATION_JSON)\npublic interface BulkApi {\n\n   /**\n    * Extracts a tar archive at the path specified as {@code path}.\n    *\n    * @param path\n    *           the path to extract under.\n    * @param payload\n    *           the {@link Payload payload} archive.\n    * @param format\n    *           one of {@code tar}, {@code tar.gz}, or {@code tar.bz2}\n    *\n    * @return {@link BulkDeleteResponse#getErrors()} are empty on success.\n    */\n   @Named(\"bulk:extractArchive\")\n   @PUT\n   @Path(\"/{path}\")\n   ExtractArchiveResponse extractArchive(@PathParam(\"path\") String path,\n         @BinderParam(SetPayload.class) Payload payload, @QueryParam(\"extract-archive\") String format);\n\n   /**\n    * Deletes multiple objects or containers, if present.\n    *\n    * @param paths\n    *           format of {@code container}, for an empty container, or\n    *           {@code container/object} for an object.\n    *\n    * @return {@link BulkDeleteResponse#getErrors()} are empty on success.\n    */\n   @Named(\"bulk:delete\")\n   @DELETE\n   @QueryParams(keys = \"bulk-delete\")\n   BulkDeleteResponse bulkDelete(@BinderParam(UrlEncodeAndJoinOnNewline.class) Iterable<String> paths);\n\n   // NOTE: this cannot be tested on MWS and is also brittle, as it relies on\n   // sending a body on DELETE.\n   // https://bugs.launchpad.net/swift/+bug/1232787\n   static class UrlEncodeAndJoinOnNewline implements Binder {\n      @SuppressWarnings(\"unchecked\")\n      @Override\n      public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n         String encodedAndNewlineDelimited = Joiner.on('\\n').join(\n               transform(Iterable.class.cast(input), urlFragmentEscaper().asFunction()));\n         Payload payload = Payloads.newStringPayload(encodedAndNewlineDelimited);\n         payload.getContentMetadata().setContentType(TEXT_PLAIN);\n         return (R) request.toBuilder().payload(payload).build();\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/features/ContainerApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.util.Map;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.HEAD;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\n\nimport org.jclouds.Fallbacks.EmptyFluentIterableOnNotFoundOr404;\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.swift.v1.SwiftFallbacks.TrueOn404FalseOn409;\nimport org.jclouds.openstack.swift.v1.binders.BindMetadataToHeaders.BindContainerMetadataToHeaders;\nimport org.jclouds.openstack.swift.v1.binders.BindMetadataToHeaders.BindRemoveContainerMetadataToHeaders;\nimport org.jclouds.openstack.swift.v1.domain.Container;\nimport org.jclouds.openstack.swift.v1.functions.FalseOnAccepted;\nimport org.jclouds.openstack.swift.v1.functions.ParseContainerFromHeaders;\nimport org.jclouds.openstack.swift.v1.options.CreateContainerOptions;\nimport org.jclouds.openstack.swift.v1.options.ListContainerOptions;\nimport org.jclouds.openstack.swift.v1.options.UpdateContainerOptions;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.collect.FluentIterable;\n\n/**\n * Provides access to the OpenStack Object Storage (Swift) Container API features.\n * <p/>\n * This API is new to jclouds and hence is in Beta. That means we need people to use it and give us feedback. Based\n * on that feedback, minor changes to the interfaces may happen. This code will replace\n * {@code org.jclouds.openstack.swift.SwiftClient} in jclouds 2.0 and it is recommended you adopt it sooner than later.\n */\n@Beta\n@RequestFilters(AuthenticateRequest.class)\n@Consumes(APPLICATION_JSON)\npublic interface ContainerApi {\n\n   /**\n    * Lists up to 10,000 containers.\n    *\n    * <h3>NOTE</h3>\n    * This method returns a list of {@link Container} objects <b>without</b> metadata. To retrieve\n    * the {@link Container} metadata, use the {@link #get(String)} method.\n    * <p/>\n    *\n    * @return a list of {@link Container containers} ordered by name.\n    */\n   @Named(\"container:list\")\n   @GET\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   @QueryParams(keys = \"format\", values = \"json\")\n   FluentIterable<Container> list();\n\n   /**\n    * Lists containers with the supplied {@link ListContainerOptions}.\n    *\n    * <h3>NOTE</h3>\n    * This method returns a list of {@link Container} objects <b>without</b> metadata. To retrieve\n    * the {@link Container} metadata, use the {@link #get(String)} method.\n    * <p/>\n    *\n    * @param options\n    *          the options to control the output list.\n    *\n    * @return a list of {@link Container containers} ordered by name.\n    */\n   @Named(\"container:list\")\n   @GET\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   @QueryParams(keys = \"format\", values = \"json\")\n   FluentIterable<Container> list(ListContainerOptions options);\n\n   /**\n    * Creates a container, if not already present.\n    *\n    * @param containerName\n    *           corresponds to {@link Container#getName()}.\n    *\n    * @return {@code true} if the container was created, {@code false} if the container already existed.\n    */\n   @Named(\"container:create\")\n   @PUT\n   @Path(\"/{containerName}\")\n   @ResponseParser(FalseOnAccepted.class)\n   boolean create(@PathParam(\"containerName\") String containerName);\n\n   /**\n    * Creates a container, if not already present.\n    *\n    * @param containerName\n    *           corresponds to {@link Container#getName()}.\n    * @param options\n    *           the options to use when creating the container.\n    *\n    * @return {@code true} if the container was created, {@code false} if the container already existed.\n    */\n   @Named(\"container:create\")\n   @PUT\n   @Path(\"/{containerName}\")\n   @ResponseParser(FalseOnAccepted.class)\n   boolean create(@PathParam(\"containerName\") String containerName, CreateContainerOptions options);\n\n   /**\n    * Gets the {@link Container}.\n    *\n    * @param containerName\n    *           corresponds to {@link Container#getName()}.\n    *\n    * @return the {@link Container}, or {@code null} if not found.\n    */\n   @Named(\"container:get\")\n   @HEAD\n   @Path(\"/{containerName}\")\n   @ResponseParser(ParseContainerFromHeaders.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Container get(@PathParam(\"containerName\") String containerName);\n\n   /**\n    * Updates the {@link Container}.\n    *\n    * @param containerName\n    *           the container name corresponding to {@link Container#getName()}.\n    * @param options\n    *           the container options to update.\n    */\n   @Named(\"container:update\")\n   @POST\n   @Path(\"/{containerName}\")\n   void update(@PathParam(\"containerName\") String containerName, UpdateContainerOptions options);\n\n   /**\n    * Creates or updates the {@link Container} metadata.\n    *\n    * @param containerName\n    *           the container name corresponding to {@link Container#getName()}.\n    * @param metadata\n    *           the container metadata to create or update.\n    */\n   @Named(\"container:updateMetadata\")\n   @POST\n   @Path(\"/{containerName}\")\n   void updateMetadata(@PathParam(\"containerName\") String containerName,\n         @BinderParam(BindContainerMetadataToHeaders.class) Map<String, String> metadata);\n\n   /**\n    * Deletes {@link Container} metadata.\n    *\n    * @param containerName\n    *           corresponds to {@link Container#getName()}.\n    * @param metadata\n    *           the container metadata to delete.\n    *\n    * @return {@code true} if the container metadata was successfully deleted,\n    *         {@code false} if not.\n    */\n   @Named(\"container:deleteMetadata\")\n   @POST\n   @Path(\"/{containerName}\")\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean deleteMetadata(@PathParam(\"containerName\") String containerName,\n         @BinderParam(BindRemoveContainerMetadataToHeaders.class) Map<String, String> metadata);\n\n   /**\n    * Deletes a {@link Container}, if empty.\n    *\n    * @param containerName\n    *           corresponds to {@link Container#getName()}.\n    *\n    * @return {@code true} if the container was deleted or not present.\n    *\n    * @throws IllegalStateException if the container was not empty.\n    */\n   @Named(\"container:deleteIfEmpty\")\n   @DELETE\n   @Path(\"/{containerName}\")\n   @Fallback(TrueOn404FalseOn409.class)\n   boolean deleteIfEmpty(@PathParam(\"containerName\") String containerName) throws IllegalStateException;\n\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/features/DynamicLargeObjectApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.util.Map;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\n\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.swift.v1.binders.BindMetadataToHeaders.BindObjectMetadataToHeaders;\nimport org.jclouds.openstack.swift.v1.binders.BindToHeaders;\nimport org.jclouds.openstack.swift.v1.domain.SwiftObject;\nimport org.jclouds.openstack.swift.v1.functions.ETagHeader;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Headers;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\n\nimport com.google.common.annotations.Beta;\n\n/**\n * Provides access to the OpenStack Object Storage (Swift) Dynamic Large Object\n * API features.\n * <p/>\n * This API is new to jclouds and hence is in Beta.\n */\n@Beta\n@RequestFilters(AuthenticateRequest.class)\n@Consumes(APPLICATION_JSON)\n@Path(\"/{objectName}\")\npublic interface DynamicLargeObjectApi {\n   /**\n    * Creates or updates a dynamic large object's manifest.\n    *\n    * @param objectName\n    *           corresponds to {@link SwiftObject#getName()}.\n    * @param metadata\n    *           corresponds to {@link SwiftObject#getMetadata()}.\n    * @param headers\n    *           Binds the map to headers, without prefixing/escaping the header\n    *           name/key.\n    *\n    * @return {@link SwiftObject#getEtag()} of the object, which is the MD5\n    *         checksum of the concatenated ETag values of the {@code segments}.\n    *         \n    * @see {@code StaticLargeObjectApi}\n    */\n   @Deprecated\n   @Named(\"dynamicLargeObject:putManifest\")\n   @PUT\n   @ResponseParser(ETagHeader.class)\n   @Headers(keys = \"X-Object-Manifest\", values = \"{containerName}/{objectName}/\")\n   String putManifest(@PathParam(\"objectName\") String objectName,\n         @BinderParam(BindObjectMetadataToHeaders.class) Map<String, String> metadata,\n         @BinderParam(BindToHeaders.class) Map<String, String> headers);\n\n   /**\n    * Creates or updates a dynamic large object's manifest.\n    *\n    * @param objectName\n    *           corresponds to {@link SwiftObject#getName()}.\n    * @param metadata\n    *           corresponds to {@link SwiftObject#getMetadata()}.\n    *\n    * @return {@link SwiftObject#getEtag()} of the object, which is the etag\n    *         of 0 sized object.\n    *         \n    * @see {@code StaticLargeObjectApi}\n    */\n   @Deprecated\n   @Named(\"dynamicLargeObject:putManifest\")\n   @PUT\n   @ResponseParser(ETagHeader.class)\n   @Headers(keys = \"X-Object-Manifest\", values = \"{containerName}/{objectName}/\")\n   String putManifest(@PathParam(\"objectName\") String objectName,\n         @BinderParam(BindObjectMetadataToHeaders.class) Map<String, String> metadata);\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/features/ObjectApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.features;\n\nimport static com.google.common.net.HttpHeaders.EXPECT;\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.OBJECT_COPY_FRESH_METADATA;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.OBJECT_COPY_FROM;\n\nimport java.util.Map;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.HEAD;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\n\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.blobstore.KeyNotFoundException;\nimport org.jclouds.http.options.GetOptions;\nimport org.jclouds.io.Payload;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.swift.v1.binders.BindMetadataToHeaders.BindObjectMetadataToHeaders;\nimport org.jclouds.openstack.swift.v1.binders.BindMetadataToHeaders.BindRemoveObjectMetadataToHeaders;\nimport org.jclouds.openstack.swift.v1.binders.BindToHeaders;\nimport org.jclouds.openstack.swift.v1.binders.SetPayload;\nimport org.jclouds.openstack.swift.v1.domain.ObjectList;\nimport org.jclouds.openstack.swift.v1.domain.SwiftObject;\nimport org.jclouds.openstack.swift.v1.functions.ETagHeader;\nimport org.jclouds.openstack.swift.v1.functions.ParseObjectFromResponse;\nimport org.jclouds.openstack.swift.v1.functions.ParseObjectListFromResponse;\nimport org.jclouds.openstack.swift.v1.options.CopyOptions;\nimport org.jclouds.openstack.swift.v1.options.ListContainerOptions;\nimport org.jclouds.openstack.swift.v1.options.PutOptions;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.Headers;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\n\nimport com.google.common.annotations.Beta;\n\n/**\n * Provides access to the OpenStack Object Storage (Swift) Object API features.\n * <p/>\n * This API is new to jclouds and hence is in Beta. That means we need people to use it and give us feedback. Based\n * on that feedback, minor changes to the interfaces may happen. This code will replace\n * org.jclouds.openstack.swift.SwiftClient in jclouds 2.0 and it is recommended you adopt it sooner than later.\n */\n@Beta\n@RequestFilters(AuthenticateRequest.class)\npublic interface ObjectApi {\n\n   /**\n    * Lists up to 10,000 objects.\n    *\n    * @return an {@link ObjectList} of {@link SwiftObject} ordered by name or {@code null}.\n    */\n   @Consumes(APPLICATION_JSON)\n   @Named(\"object:list\")\n   @GET\n   @ResponseParser(ParseObjectListFromResponse.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   @QueryParams(keys = \"format\", values = \"json\")\n   @Nullable\n   ObjectList list();\n\n   /**\n    * Lists up to 10,000 objects. To control a large list of containers beyond\n    * 10,000 objects, use the {@code marker} and {@code endMarker} parameters in the\n    * {@link ListContainerOptions} class.\n    *\n    * @param options\n    *           the {@link ListContainerOptions} for controlling the returned list.\n    *\n    * @return an {@link ObjectList} of {@link SwiftObject} ordered by name or {@code null}.\n    */\n   @Consumes(APPLICATION_JSON)\n   @Named(\"object:list\")\n   @GET\n   @ResponseParser(ParseObjectListFromResponse.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   @QueryParams(keys = \"format\", values = \"json\")\n   @Nullable\n   ObjectList list(ListContainerOptions options);\n\n   /**\n    * Creates or updates a {@link SwiftObject}.\n    *\n    * @param objectName\n    *           corresponds to {@link SwiftObject#getName()}.\n    * @param payload\n    *           corresponds to {@link SwiftObject#getPayload()}.\n    *\n    * @return {@link SwiftObject#getETag()} of the object.\n    */\n   @Named(\"object:put\")\n   @PUT\n   @Path(\"/{objectName}\")\n   @Headers(keys = EXPECT, values = \"100-continue\")\n   @ResponseParser(ETagHeader.class)\n   String put(@PathParam(\"objectName\") String objectName, @BinderParam(SetPayload.class) Payload payload);\n\n   /**\n    * Creates or updates a {@link SwiftObject}.\n    *\n    * @param objectName\n    *           corresponds to {@link SwiftObject#getName()}.\n    * @param payload\n    *           corresponds to {@link SwiftObject#getPayload()}.\n    * @param options\n    *           {@link PutOptions options} to control creating the {@link SwiftObject}.\n    *\n    * @return {@link SwiftObject#getETag()} of the object.\n    */\n   @Named(\"object:put\")\n   @PUT\n   @Path(\"/{objectName}\")\n   @Headers(keys = EXPECT, values = \"100-continue\")\n   @ResponseParser(ETagHeader.class)\n   String put(@PathParam(\"objectName\") String objectName, @BinderParam(SetPayload.class) Payload payload,\n         PutOptions options);\n\n   /**\n    * Gets the {@link SwiftObject} metadata without its {@link Payload#openStream() body}.\n    *\n    * @param objectName\n    *           corresponds to {@link SwiftObject#getName()}.\n    *\n    * @return the {@link SwiftObject} or {@code null}, if not found.\n    */\n   @Named(\"object:getWithoutBody\")\n   @HEAD\n   @Path(\"/{objectName}\")\n   @ResponseParser(ParseObjectFromResponse.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   SwiftObject getWithoutBody(@PathParam(\"objectName\") String objectName);\n\n   /**\n    * Gets the {@link SwiftObject} including its {@link Payload#openStream() body}.\n    *\n    * @param objectName\n    *           corresponds to {@link SwiftObject#getName()}.\n    *\n    * @return the {@link SwiftObject} or {@code null}, if not found.\n    */\n   @Named(\"object:get\")\n   @GET\n   @Path(\"/{objectName}\")\n   @ResponseParser(ParseObjectFromResponse.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   SwiftObject get(@PathParam(\"objectName\") String objectName);\n\n   /**\n    * Gets the {@link SwiftObject} including its {@link Payload#openStream() body}.\n    *\n    * @param objectName\n    *           corresponds to {@link SwiftObject#getName()}.\n    * @param options\n    *           options to control the download.\n    *\n    * @return the {@link SwiftObject} or {@code null}, if not found.\n    */\n   @Named(\"object:get\")\n   @GET\n   @Path(\"/{objectName}\")\n   @ResponseParser(ParseObjectFromResponse.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   SwiftObject get(@PathParam(\"objectName\") String objectName, GetOptions options);\n\n   /**\n    * Creates or updates the metadata for a {@link SwiftObject}.\n    *\n    * @param objectName\n    *           corresponds to {@link SwiftObject#getName()}.\n    * @param metadata\n    *           the metadata to create or update.\n    */\n   @Named(\"object:updateMetadata\")\n   @POST\n   @Path(\"/{objectName}\")\n   @Produces(\"\")\n   void updateMetadata(@PathParam(\"objectName\") String objectName,\n         @BinderParam(BindObjectMetadataToHeaders.class) Map<String, String> metadata);\n\n   /**\n    * Creates or updates the metadata for a {@link SwiftObject} without escaping the key.\n    * This will also update metadata such as content-disposition.\n    *\n    * @param objectName\n    *           corresponds to {@link SwiftObject#getName()}.\n    * @param metadata\n    *           the metadata to create or update.\n    *\n    */\n   @Named(\"object:updateMetadata\")\n   @POST\n   @Path(\"/{objectName}\")\n   @Produces(\"\")\n   void updateHeaders(@PathParam(\"objectName\") String objectName,\n         @BinderParam(BindToHeaders.class) Map<String, String> metadata);\n\n   /**\n    * Deletes the metadata from a {@link SwiftObject}.\n    *\n    * @param objectName\n    *           corresponds to {@link SwiftObject#getName()}.\n    * @param metadata\n    *           corresponds to {@link SwiftObject#getMetadata()}.\n    *\n    * @return {@code true} if the metadata was successfully deleted,\n    *         {@code false} if not.\n    */\n   @Named(\"object:deleteMetadata\")\n   @POST\n   @Path(\"/{objectName}\")\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean deleteMetadata(@PathParam(\"objectName\") String objectName,\n         @BinderParam(BindRemoveObjectMetadataToHeaders.class) Map<String, String> metadata);\n\n   /**\n    * Deletes an object, if present.\n    *\n    * @param objectName\n    *           corresponds to {@link SwiftObject#getName()}.\n    */\n   @Named(\"object:delete\")\n   @DELETE\n   @Path(\"/{objectName}\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void delete(@PathParam(\"objectName\") String objectName);\n\n   /**\n    * Copies an object from one container to another.\n    *\n    * <h3>NOTE</h3>\n    * This is a server side copy.\n    *\n    * @param destinationObject\n    *           the destination object name.\n    * @param sourceContainer\n    *           the source container name.\n    * @param sourceObject\n    *           the source object name.\n    *\n    * @deprecated call copy(String, String, String, CopyOptions) instead\n    * @throws KeyNotFoundException if the source or destination container do not exist.\n    */\n   @Deprecated\n   @Named(\"object:copy\")\n   @PUT\n   @Path(\"/{destinationObject}\")\n   @Headers(keys = OBJECT_COPY_FROM, values = \"/{sourceContainer}/{sourceObject}\")\n   void copy(@PathParam(\"destinationObject\") String destinationObject,\n                @PathParam(\"sourceContainer\") String sourceContainer,\n                @PathParam(\"sourceObject\") String sourceObject);\n\n   /**\n    * Copies an object from one container to another.\n    *\n    * <h3>NOTE</h3>\n    * This is a server side copy.\n    *\n    * @param destinationObject\n    *           the destination object name.\n    * @param sourceContainer\n    *           the source container name.\n    * @param sourceObject\n    *           the source object name.\n    * @param options\n    *           conditional copy\n    *\n    * @throws KeyNotFoundException if the source or destination container do not exist.\n    */\n   @Named(\"object:copy\")\n   @PUT\n   @Path(\"/{destinationObject}\")\n   @Headers(keys = OBJECT_COPY_FROM, values = \"/{sourceContainer}/{sourceObject}\")\n   void copy(@PathParam(\"destinationObject\") String destinationObject,\n                @PathParam(\"sourceContainer\") String sourceContainer,\n                @PathParam(\"sourceObject\") String sourceObject,\n                CopyOptions options);\n\n   /**\n    * Copies an object from one container to another, replacing metadata.\n    *\n    * <h3>NOTE</h3>\n    * This is a server side copy.\n    *\n    * @param destinationObject\n    *           the destination object name.\n    * @param sourceContainer\n    *           the source container name.\n    * @param sourceObject\n    *           the source object name.\n    * @param userMetadata\n    *           Freeform metadata for the object, automatically prefixed/escaped\n    * @param objectMetadata\n    *           Unprefixed/unescaped metadata, such as Content-Disposition\n    *\n    * @deprecated call copy(String, String, String, Map, Map, CopyOptions) instead\n    * @throws KeyNotFoundException if the source or destination container do not exist.\n    */\n   @Deprecated\n   @Named(\"object:copy\")\n   @PUT\n   @Path(\"/{destinationObject}\")\n   @Headers(keys = {OBJECT_COPY_FROM, OBJECT_COPY_FRESH_METADATA}, values = {\"/{sourceContainer}/{sourceObject}\", \"True\"})\n   void copy(@PathParam(\"destinationObject\") String destinationObject,\n         @PathParam(\"sourceContainer\") String sourceContainer,\n         @PathParam(\"sourceObject\") String sourceObject,\n         @BinderParam(BindObjectMetadataToHeaders.class) Map<String, String> userMetadata,\n         @BinderParam(BindToHeaders.class) Map<String, String> objectMetadata);\n\n   /**\n    * Copies an object from one container to another, replacing metadata.\n    *\n    * <h3>NOTE</h3>\n    * This is a server side copy.\n    *\n    * @param destinationObject\n    *           the destination object name.\n    * @param sourceContainer\n    *           the source container name.\n    * @param sourceObject\n    *           the source object name.\n    * @param userMetadata\n    *           Freeform metadata for the object, automatically prefixed/escaped\n    * @param objectMetadata\n    *           Unprefixed/unescaped metadata, such as Content-Disposition\n    * @param options\n    *           conditional copy\n    *\n    * @throws KeyNotFoundException if the source or destination container do not exist.\n    */\n   @Named(\"object:copy\")\n   @PUT\n   @Path(\"/{destinationObject}\")\n   @Headers(keys = {OBJECT_COPY_FROM, OBJECT_COPY_FRESH_METADATA}, values = {\"/{sourceContainer}/{sourceObject}\", \"True\"})\n   void copy(@PathParam(\"destinationObject\") String destinationObject,\n         @PathParam(\"sourceContainer\") String sourceContainer,\n         @PathParam(\"sourceObject\") String sourceObject,\n         @BinderParam(BindObjectMetadataToHeaders.class) Map<String, String> userMetadata,\n         @BinderParam(BindToHeaders.class) Map<String, String> objectMetadata,\n         CopyOptions options);\n\n   /**\n    * Copies an object from one container to another, appending metadata.\n    *\n    * <h3>NOTE</h3>\n    * This is a server side copy.\n    *\n    * @param destinationObject\n    *           the destination object name.\n    * @param sourceContainer\n    *           the source container name.\n    * @param sourceObject\n    *           the source object name.\n    * @param userMetadata\n    *           Freeform metadata for the object, automatically prefixed/escaped\n    * @param objectMetadata\n    *           Unprefixed/unescaped metadata, such as Content-Disposition\n    *\n    * @deprecated call copyAppendMetadata(String, String, String, Map, Map, CopyOptions) instead\n    * @throws KeyNotFoundException if the source or destination container do not exist.\n    */\n   @Deprecated\n   @Named(\"object:copy\")\n   @PUT\n   @Path(\"/{destinationObject}\")\n   @Headers(keys = OBJECT_COPY_FROM, values = \"/{sourceContainer}/{sourceObject}\")\n   void copyAppendMetadata(@PathParam(\"destinationObject\") String destinationObject,\n         @PathParam(\"sourceContainer\") String sourceContainer,\n         @PathParam(\"sourceObject\") String sourceObject,\n         @BinderParam(BindObjectMetadataToHeaders.class) Map<String, String> userMetadata,\n         @BinderParam(BindToHeaders.class) Map<String, String> objectMetadata);\n\n   /**\n    * Copies an object from one container to another, appending metadata.\n    *\n    * <h3>NOTE</h3>\n    * This is a server side copy.\n    *\n    * @param destinationObject\n    *           the destination object name.\n    * @param sourceContainer\n    *           the source container name.\n    * @param sourceObject\n    *           the source object name.\n    * @param userMetadata\n    *           Freeform metadata for the object, automatically prefixed/escaped\n    * @param objectMetadata\n    *           Unprefixed/unescaped metadata, such as Content-Disposition\n    * @param options\n    *           conditional copy\n    *\n    * @throws KeyNotFoundException if the source or destination container do not exist.\n    */\n   @Named(\"object:copy\")\n   @PUT\n   @Path(\"/{destinationObject}\")\n   @Headers(keys = OBJECT_COPY_FROM, values = \"/{sourceContainer}/{sourceObject}\")\n   void copyAppendMetadata(@PathParam(\"destinationObject\") String destinationObject,\n         @PathParam(\"sourceContainer\") String sourceContainer,\n         @PathParam(\"sourceObject\") String sourceObject,\n         @BinderParam(BindObjectMetadataToHeaders.class) Map<String, String> userMetadata,\n         @BinderParam(BindToHeaders.class) Map<String, String> objectMetadata,\n         CopyOptions options);\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/features/StaticLargeObjectApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\n\nimport org.jclouds.Fallbacks.EmptyListOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.swift.v1.binders.BindMetadataToHeaders.BindObjectMetadataToHeaders;\nimport org.jclouds.openstack.swift.v1.binders.BindToHeaders;\nimport org.jclouds.openstack.swift.v1.domain.DeleteStaticLargeObjectResponse;\nimport org.jclouds.openstack.swift.v1.domain.Segment;\nimport org.jclouds.openstack.swift.v1.domain.SwiftObject;\nimport org.jclouds.openstack.swift.v1.functions.ETagHeader;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport com.google.common.annotations.Beta;\n\n/**\n * Provides access to the OpenStack Object Storage (Swift) Static Large Object API features.\n * <p/>\n * This API is new to jclouds and hence is in Beta. That means we need people to use it and give us feedback. Based\n * on that feedback, minor changes to the interfaces may happen. This code will replace\n * org.jclouds.openstack.swift.SwiftClient in jclouds 2.0 and it is recommended you adopt it sooner than later.\n */\n@Beta\n@RequestFilters(AuthenticateRequest.class)\n@Consumes(APPLICATION_JSON)\n@Path(\"/{objectName}\")\npublic interface StaticLargeObjectApi {\n\n   /**\n    * Creates or updates a static large object's manifest.\n    *\n    * @param objectName\n    *           corresponds to {@link SwiftObject#getName()}.\n    * @param segments\n    *           ordered parts which will be concatenated upon download.\n    * @param metadata\n    *           corresponds to {@link SwiftObject#getMetadata()}.\n    *\n    * @return {@link SwiftObject#getEtag()} of the object, which is the MD5\n    *         checksum of the concatenated ETag values of the {@code segments}.\n    */\n   @Named(\"staticLargeObject:replaceManifest\")\n   @PUT\n   @ResponseParser(ETagHeader.class)\n   @QueryParams(keys = \"multipart-manifest\", values = \"put\")\n   String replaceManifest(@PathParam(\"objectName\") String objectName,\n         @BinderParam(BindToJsonPayload.class) List<Segment> segments,\n         @BinderParam(BindObjectMetadataToHeaders.class) Map<String, String> metadata);\n\n   /**\n    * Creates or updates a static large object's manifest.\n    *\n    * @param objectName\n    *           corresponds to {@link SwiftObject#getName()}.\n    * @param segments\n    *           ordered parts which will be concatenated upon download.\n    * @param metadata\n    *           corresponds to {@link SwiftObject#getMetadata()}.\n    * @param headers\n    *           Binds the map to headers, without prefixing/escaping the header name/key.\n    *\n    * @return {@link SwiftObject#getEtag()} of the object, which is the MD5\n    *         checksum of the concatenated ETag values of the {@code segments}.\n    */\n   @Named(\"staticLargeObject:replaceManifest\")\n   @PUT\n   @ResponseParser(ETagHeader.class)\n   @QueryParams(keys = \"multipart-manifest\", values = \"put\")\n   String replaceManifest(@PathParam(\"objectName\") String objectName,\n         @BinderParam(BindToJsonPayload.class) List<Segment> segments,\n         @BinderParam(BindObjectMetadataToHeaders.class) Map<String, String> metadata,\n         @BinderParam(BindToHeaders.class) Map<String, String> headers);\n\n   /**\n    * Deletes a static large object, if present, including all of its segments.\n    *\n    * @param objectName\n    *           corresponds to {@link SwiftObject#getName()}.\n    */\n   @Named(\"staticLargeObject:delete\")\n   @DELETE\n   @Fallback(VoidOnNotFoundOr404.class)\n   @QueryParams(keys = \"multipart-manifest\", values = \"delete\")\n   DeleteStaticLargeObjectResponse delete(@PathParam(\"objectName\") String objectName);\n\n   /**\n    * Get a static large object's manifest.\n    *\n    * @param objectName\n    *           corresponds to {@link SwiftObject#getName()}.\n    *\n    * @return A list of the multipart segments\n    */\n   @Named(\"staticLargeObject:getManifest\")\n   @GET\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   @QueryParams(keys = {\"format\", \"multipart-manifest\"}, values = {\"json\", \"get\"})\n   List<Segment> getManifest(@PathParam(\"objectName\") String objectName);\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/functions/ETagHeader.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.functions;\n\nimport static com.google.common.net.HttpHeaders.ETAG;\n\nimport org.jclouds.http.HttpResponse;\n\nimport com.google.common.base.Function;\n\npublic class ETagHeader implements Function<HttpResponse, String> {\n\n   @Override\n   public String apply(HttpResponse from) {\n      String etag = from.getFirstHeaderOrNull(ETAG);\n      return etag != null ? etag.replace(\"\\\"\", \"\") : null;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/functions/EntriesWithoutMetaPrefix.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.functions;\n\nimport java.util.Map;\nimport java.util.Map.Entry;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Multimap;\n\n/**\n * Extracts entries whose keys start with {@code .*-Meta-}.\n * \n * @param from\n *           a {@link Multimap} containing the prefixed headers.\n * \n * @return the extracted metadata without the prefixed keys. \n */\npublic enum EntriesWithoutMetaPrefix implements Function<Multimap<String, String>, Map<String, String>> {\n   INSTANCE;\n\n   @Override\n   public Map<String, String> apply(Multimap<String, String> arg0) {\n      ImmutableMap.Builder<String, String> metadata = ImmutableMap.builder();\n      for (Entry<String, String> header : arg0.entries()) {\n         int index = header.getKey().toLowerCase().indexOf(\"-meta-\");\n         if (index != -1) {\n            metadata.put(header.getKey().substring(index + 6), header.getValue());\n         }\n      }\n      return metadata.build();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/functions/FalseOnAccepted.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.functions;\n\nimport org.jclouds.http.HttpResponse;\n\nimport com.google.common.base.Function;\n\n/** Returns {@code false} on HTTP 202 {@code Accepted}. */\npublic class FalseOnAccepted implements Function<HttpResponse, Boolean> {\n\n   @Override\n   public Boolean apply(HttpResponse from) {\n      return from.getStatusCode() == 202 ? false : true;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/functions/MetadataFromHeaders.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.functions;\n\nimport java.util.Map;\n\nimport org.jclouds.http.HttpResponse;\n\nimport com.google.common.base.Function;\n\n/** Extracts metadata entries from http response headers. */\npublic class MetadataFromHeaders implements Function<HttpResponse, Map<String, String>> {\n   @Override\n   public Map<String, String> apply(HttpResponse from) {\n      return EntriesWithoutMetaPrefix.INSTANCE.apply(from.getHeaders());\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/functions/ParseAccountFromHeaders.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.functions;\n\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.ACCOUNT_BYTES_USED;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.ACCOUNT_CONTAINER_COUNT;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.ACCOUNT_OBJECT_COUNT;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.swift.v1.domain.Account;\n\nimport com.google.common.base.Function;\n\npublic class ParseAccountFromHeaders implements Function<HttpResponse, Account> {\n\n   @Override\n   public Account apply(HttpResponse from) {\n      return Account.builder()\n            .bytesUsed(Long.parseLong(from.getFirstHeaderOrNull(ACCOUNT_BYTES_USED)))\n            .containerCount(Long.parseLong(from.getFirstHeaderOrNull(ACCOUNT_CONTAINER_COUNT)))\n            .objectCount(Long.parseLong(from.getFirstHeaderOrNull(ACCOUNT_OBJECT_COUNT)))\n            .metadata(EntriesWithoutMetaPrefix.INSTANCE.apply(from.getHeaders())).build();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/functions/ParseContainerFromHeaders.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.functions;\n\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.CONTAINER_ACL_ANYBODY_READ;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.CONTAINER_BYTES_USED;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.CONTAINER_OBJECT_COUNT;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.CONTAINER_READ;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.swift.v1.domain.Container;\nimport org.jclouds.rest.InvocationContext;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\n\nimport com.google.common.base.Function;\n\npublic class ParseContainerFromHeaders implements Function<HttpResponse, Container>,\n      InvocationContext<ParseContainerFromHeaders> {\n\n   String name;\n\n   @Override\n   public Container apply(HttpResponse from) {\n      String bytesUsed = from.getFirstHeaderOrNull(CONTAINER_BYTES_USED);\n      String objectCount = from.getFirstHeaderOrNull(CONTAINER_OBJECT_COUNT);\n      Container c = \n      Container.builder()\n            .name(name)\n            .bytesUsed(bytesUsed != null ? Long.valueOf(bytesUsed) : null)\n            .objectCount(objectCount != null ? Long.valueOf(objectCount) : null)\n            .anybodyRead(CONTAINER_ACL_ANYBODY_READ.equals(from.getFirstHeaderOrNull(CONTAINER_READ)))\n            .metadata(EntriesWithoutMetaPrefix.INSTANCE.apply(from.getHeaders())).build();\n      return c;\n   }\n\n   @Override\n   public ParseContainerFromHeaders setContext(HttpRequest request) {\n      this.name = GeneratedHttpRequest.class.cast(request).getInvocation().getArgs().get(0).toString();\n      return this;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/functions/ParseObjectFromResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.functions;\n\nimport static com.google.common.io.BaseEncoding.base16;\nimport static com.google.common.net.HttpHeaders.ETAG;\nimport static com.google.common.net.HttpHeaders.LAST_MODIFIED;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.OBJECT_DELETE_AT;\n\nimport java.net.URI;\nimport java.util.Date;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.io.MutableContentMetadata;\nimport org.jclouds.io.Payload;\nimport org.jclouds.openstack.swift.v1.domain.SwiftObject;\nimport org.jclouds.rest.InvocationContext;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\n\nimport com.google.common.base.Function;\nimport com.google.common.hash.HashCode;\n\npublic class ParseObjectFromResponse implements Function<HttpResponse, SwiftObject>,\n      InvocationContext<ParseObjectFromResponse> {\n   private final DateService dates;\n\n   @Inject\n   ParseObjectFromResponse(DateService dates) {\n      this.dates = dates;\n   }\n\n   private String uri;\n   private String name;\n\n   @Override\n   public SwiftObject apply(HttpResponse from) {\n\n      Payload payload = from.getPayload();\n      MutableContentMetadata contentMeta = payload.getContentMetadata();\n\n      String deleteAt = from.getFirstHeaderOrNull(OBJECT_DELETE_AT);\n      if (deleteAt != null) {\n         long fromEpoch = Long.parseLong(from.getFirstHeaderOrNull(OBJECT_DELETE_AT)) * 1000;\n         contentMeta.setExpires(new Date(fromEpoch));\n         payload.setContentMetadata(contentMeta);\n      }\n\n      String etag = from.getFirstHeaderOrNull(ETAG);\n      if (etag != null) {\n         if (etag.startsWith(\"\\\"\") && etag.endsWith(\"\\\"\") && etag.length() > 1) {\n            etag = etag.substring(1, etag.length() - 1);\n         }\n         payload.getContentMetadata().setContentMD5(HashCode.fromBytes(base16().lowerCase().decode(etag)));\n      }\n\n      return SwiftObject.builder()\n            .uri(URI.create(uri))\n            .name(name)\n            .etag(etag)\n            .payload(payload)\n            .lastModified(dates.rfc822DateParse(from.getFirstHeaderOrNull(LAST_MODIFIED)))\n            .headers(from.getHeaders())\n            .metadata(EntriesWithoutMetaPrefix.INSTANCE.apply(from.getHeaders())).build();\n   }\n\n   @Override\n   public ParseObjectFromResponse setContext(HttpRequest request) {\n      this.uri = request.getEndpoint().toString();\n      this.name = GeneratedHttpRequest.class.cast(request).getInvocation().getArgs().get(0).toString();\n      return this;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/functions/ParseObjectListFromResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.functions;\n\nimport static com.google.common.io.BaseEncoding.base16;\nimport static org.jclouds.http.Uris.uriBuilder;\nimport static org.jclouds.util.Strings2.urlEncode;\n\nimport java.util.Date;\nimport java.util.List;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.openstack.swift.v1.domain.Container;\nimport org.jclouds.openstack.swift.v1.domain.ObjectList;\nimport org.jclouds.openstack.swift.v1.domain.SwiftObject;\nimport org.jclouds.rest.InvocationContext;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Strings;\nimport com.google.common.collect.Lists;\nimport com.google.common.hash.HashCode;\nimport com.google.common.io.ByteSource;\n\npublic class ParseObjectListFromResponse implements Function<HttpResponse, ObjectList>,\n      InvocationContext<ParseObjectListFromResponse> {\n\n   public static final String SUBDIR_ETAG = \"deadbeef\";\n\n   private static final class InternalObject {\n      String name;\n      String hash;\n      String subdir;\n      long bytes;\n      String content_type;\n      Date last_modified;\n      Date expires;\n   }\n\n   private final ParseJson<List<InternalObject>> json;\n   private final ParseContainerFromHeaders parseContainer;\n\n   @Inject\n   ParseObjectListFromResponse(ParseJson<List<InternalObject>> json, ParseContainerFromHeaders parseContainer) {\n      this.json = json;\n      this.parseContainer = parseContainer;\n   }\n\n   private ToSwiftObject toSwiftObject;\n\n   @Override\n   public ObjectList apply(HttpResponse from) {\n      List<SwiftObject> objects = Lists.transform(json.apply(from), toSwiftObject);\n\n      Container container = parseContainer.apply(from);\n      return ObjectList.create(objects, container);\n   }\n\n   static class ToSwiftObject implements Function<InternalObject, SwiftObject> {\n      private final String containerUri;\n\n      ToSwiftObject(String containerUri) {\n         this.containerUri = containerUri;\n      }\n\n      @Override\n      public SwiftObject apply(InternalObject input) {\n         if (input.subdir != null) {\n            return SwiftObject.builder()\n                  .uri(uriBuilder(containerUri).clearQuery().appendPath(urlEncode(input.subdir)).build())\n                  .name(input.subdir)\n                  .etag(SUBDIR_ETAG)\n                  .payload(payload(input.bytes, input.hash, \"application/directory\", input.expires))\n                  .lastModified(new Date(0)).build();\n         }\n         String name = Strings.nullToEmpty(input.name);\n         String etag = Strings.nullToEmpty(input.hash);\n         Date lastModified = input.last_modified == null ? new Date() : input.last_modified;\n         return SwiftObject.builder()\n               .uri(uriBuilder(containerUri).clearQuery().appendPath(urlEncode(input.name)).build())\n               .name(name)\n               .etag(etag)\n               .payload(payload(input.bytes, etag, input.content_type, input.expires))\n               .lastModified(lastModified).build();\n      }\n   }\n\n   @Override\n   public ParseObjectListFromResponse setContext(HttpRequest request) {\n      parseContainer.name = GeneratedHttpRequest.class.cast(request).getCaller().get().getArgs().get(1).toString();\n      String containerUri = request.getEndpoint().toString();\n      int queryIndex = containerUri.indexOf('?');\n      if (queryIndex != -1) {\n         containerUri = containerUri.substring(0, queryIndex);\n      }\n      toSwiftObject = new ToSwiftObject(containerUri);\n      return this;\n   }\n\n   private static Payload payload(long bytes, String hash, String contentType, Date expires) {\n      Payload payload = Payloads.newByteSourcePayload(ByteSource.empty());\n      payload.getContentMetadata().setContentLength(bytes);\n      payload.getContentMetadata().setContentType(contentType);\n      payload.getContentMetadata().setExpires(expires);\n      if (hash != null) {\n         payload.getContentMetadata().setContentMD5(HashCode.fromBytes(base16().lowerCase().decode(hash)));\n      }\n      return payload;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/handlers/SwiftErrorHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.handlers;\n\nimport static org.jclouds.http.HttpUtils.closeClientButKeepContentStream;\n\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport org.jclouds.blobstore.ContainerNotFoundException;\nimport org.jclouds.blobstore.KeyNotFoundException;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.openstack.swift.v1.reference.SwiftHeaders;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.InsufficientResourcesException;\n\n// TODO: is there error spec someplace? let's type errors, etc.\npublic class SwiftErrorHandler implements HttpErrorHandler {\n   public static final String PREFIX = \"^/v[0-9][^/]*/[a-zA-Z]+_[^/]+/\";\n   public static final Pattern CONTAINER_PATH = Pattern.compile(PREFIX + \"([^/]+)$\");\n   public static final Pattern CONTAINER_KEY_PATH = Pattern.compile(PREFIX + \"([^/]+)/(.*)\");\n\n   public void handleError(HttpCommand command, HttpResponse response) {\n      // it is important to always read fully and close streams\n      byte[] data = closeClientButKeepContentStream(response);\n      String message = data != null ? new String(data) : null;\n\n      Exception exception = message != null ? new HttpResponseException(command, response, message)\n               : new HttpResponseException(command, response);\n      message = message != null ? message : String.format(\"%s -> %s\", command.getCurrentRequest().getRequestLine(),\n               response.getStatusLine());\n      switch (response.getStatusCode()) {\n         case 401:\n            exception = new AuthorizationException(exception.getMessage(), exception);\n            break;\n         case 404:\n            Exception oldException = exception;\n            String sourcePath = command.getCurrentRequest().getFirstHeaderOrNull(SwiftHeaders.OBJECT_COPY_FROM);\n            if (sourcePath != null) {\n               exception = new KeyNotFoundException(oldException);\n            } else if (!command.getCurrentRequest().getMethod().equals(\"DELETE\")) {\n               String path = command.getCurrentRequest().getEndpoint().getPath();\n               Matcher matcher = CONTAINER_PATH.matcher(path);\n\n               if (matcher.find()) {\n                  exception = new ContainerNotFoundException(matcher.group(1), message);\n                  exception.initCause(oldException);\n               } else {\n                  matcher = CONTAINER_KEY_PATH.matcher(path);\n                  if (matcher.find()) {\n                     exception = new KeyNotFoundException(matcher.group(1), matcher.group(2), message);\n                     exception.initCause(oldException);\n                  }\n               }\n            }\n            break;\n         case 409:\n            exception = new IllegalStateException(exception.getMessage(), exception);\n            break;\n         case 413:\n            exception = new InsufficientResourcesException(exception.getMessage(), exception);\n            break;\n      }\n      command.setException(exception);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/options/CopyOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.options;\n\nimport java.util.Date;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.net.HttpHeaders;\n\npublic final class CopyOptions extends BaseHttpRequestOptions {\n   public static final CopyOptions NONE = new CopyOptions();\n\n   private static final DateService dateService = new SimpleDateFormatDateService();\n\n   public CopyOptions ifMatch(String ifMatch) {\n      this.headers.put(HttpHeaders.IF_MATCH, ifMatch);\n      return this;\n   }\n\n   // Swift only supports If-None-Match: * which is not useful for copy\n\n   public CopyOptions ifModifiedSince(Date ifModifiedSince) {\n      this.headers.put(HttpHeaders.IF_MODIFIED_SINCE, dateService.rfc822DateFormat(ifModifiedSince));\n      return this;\n   }\n\n   public CopyOptions ifUnmodifiedSince(Date ifUnmodifiedSince) {\n      this.headers.put(HttpHeaders.IF_UNMODIFIED_SINCE, dateService.rfc822DateFormat(ifUnmodifiedSince));\n      return this;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/options/CreateContainerOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.options;\n\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.CONTAINER_ACL_ANYBODY_READ;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.CONTAINER_METADATA_PREFIX;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.CONTAINER_READ;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.VERSIONS_LOCATION;\n\nimport java.util.Map;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\nimport org.jclouds.openstack.swift.v1.binders.BindMetadataToHeaders;\n\nimport com.google.common.collect.Multimap;\n\n/**\n * Options for creating a {@link Container} \n * \n * @see ContainerApi#create(String, CreateContainerOptions)\n */\npublic class CreateContainerOptions extends BaseHttpRequestOptions {\n\n   public static final CreateContainerOptions NONE = new CreateContainerOptions();\n\n   /** \n    * Sets the headers on a container at creation.\n    */\n   public CreateContainerOptions headers(Multimap<String, String> headers) {\n      this.headers.putAll(headers);\n      return this;\n   }\n\n   /**\n    * Sets the metadata on a container at creation. \n    */\n   public CreateContainerOptions metadata(Map<String, String> metadata) {\n      this.headers.putAll(bindMetadataToHeaders.toHeaders(metadata));\n      return this;\n   }\n\n   /**\n    * Sets the public ACL on the container so that anybody can read it.\n    */\n   public CreateContainerOptions anybodyRead() {\n      this.headers.put(CONTAINER_READ, CONTAINER_ACL_ANYBODY_READ);\n      return this;\n   }\n\n   /**\n    * Sets the container that will contain object versions.\n    */\n   public CreateContainerOptions versionsLocation(String containerName) {\n      this.headers.put(VERSIONS_LOCATION, containerName);\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see CreateContainerOptions#anybodyRead\n       */\n      public static CreateContainerOptions anybodyRead() {\n         CreateContainerOptions options = new CreateContainerOptions();\n         return options.anybodyRead();\n      }\n\n      /**\n       * @see CreateContainerOptions#headers\n       */\n      public static CreateContainerOptions headers(Multimap<String, String> headers) {\n         CreateContainerOptions options = new CreateContainerOptions();\n         return options.headers(headers);\n      }\n\n      /**\n       * @see CreateContainerOptions#metadata\n       */\n      public static CreateContainerOptions metadata(Map<String, String> metadata) {\n         CreateContainerOptions options = new CreateContainerOptions();\n         return options.metadata(metadata);\n      }\n\n      /**\n       * @see CreateContainerOptions#versionsLocation\n       */\n      public static CreateContainerOptions versionsLocation(String containerName) {\n         CreateContainerOptions options = new CreateContainerOptions();\n         return options.versionsLocation(containerName);\n      }\n   }\n\n   private static final BindMetadataToHeaders bindMetadataToHeaders = new BindMetadataToHeaders(CONTAINER_METADATA_PREFIX);\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/options/ListContainerOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\n/**\n * Options for listing containers. \n * \n * @see ContainerApi#list(ListContainerOptions)\n */\npublic class ListContainerOptions extends BaseHttpRequestOptions {\n   public static final ListContainerOptions NONE = new ListContainerOptions();\n\n   /** \n    * list operation returns no more than this amount. \n    */\n   public ListContainerOptions limit(int limit) {\n      checkState(limit >= 0, \"limit must be >= 0\");\n      checkState(limit <= 10000, \"limit must be <= 10000\");\n      queryParameters.put(\"limit\", Integer.toString(limit));\n      return this;\n   }\n\n   /** \n    * object names greater in value than the specified marker are returned.\n    */\n   public ListContainerOptions marker(String marker) {\n      queryParameters.put(\"marker\", checkNotNull(marker, \"marker\"));\n      return this;\n   }\n\n   /** \n    * object names less in value than the specified marker are returned.\n    */\n   public ListContainerOptions endMarker(String endMarker) {\n      queryParameters.put(\"end_marker\", checkNotNull(endMarker, \"endMarker\"));\n      return this;\n   }\n\n   /** \n    * object names beginning with this substring are returned.\n    */\n   public ListContainerOptions prefix(String prefix) {\n      queryParameters.put(\"prefix\", checkNotNull(prefix, \"prefix\"));\n      return this;\n   }\n\n   /** \n    * object names nested in the container are returned.\n    */\n   public ListContainerOptions delimiter(char delimiter) {\n      queryParameters.put(\"delimiter\", Character.toString(delimiter));\n      return this;\n   }\n\n   /** \n    * object names nested in the pseudo path are returned.\n    */\n   public ListContainerOptions path(String path) {\n      queryParameters.put(\"path\", checkNotNull(path, \"path\"));\n      return this;\n   }\n\n   public static class Builder {\n\n      /** \n       * @see ListContainerOptions#limit\n       */\n      public static ListContainerOptions limit(int limit) {\n         ListContainerOptions options = new ListContainerOptions();\n         return options.limit(limit);\n      }\n\n      /** \n       * @see ListContainerOptions#marker\n       */\n      public static ListContainerOptions marker(String marker) {\n         ListContainerOptions options = new ListContainerOptions();\n         return options.marker(marker);\n      }\n\n      /** \n       * @see ListContainerOptions#endMarker\n       */\n      public static ListContainerOptions endMarker(String endMarker) {\n         ListContainerOptions options = new ListContainerOptions();\n         return options.endMarker(endMarker);\n      }\n\n      /** \n       * @see ListContainerOptions#prefix \n       */\n      public static ListContainerOptions prefix(String prefix) {\n         ListContainerOptions options = new ListContainerOptions();\n         return options.prefix(prefix);\n      }\n\n      /** \n       * @see ListContainerOptions#delimiter \n       */\n      public static ListContainerOptions delimiter(char delimiter) {\n         ListContainerOptions options = new ListContainerOptions();\n         return options.delimiter(delimiter);\n      }\n\n      /** \n       * @see ListContainerOptions#path \n       */\n      public static ListContainerOptions path(String path) {\n         ListContainerOptions options = new ListContainerOptions();\n         return options.path(path);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/options/PutOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.options;\n\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.OBJECT_METADATA_PREFIX;\n\nimport java.util.Map;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\nimport org.jclouds.openstack.swift.v1.binders.BindMetadataToHeaders;\n\nimport com.google.common.collect.Multimap;\n\n/**\n * Options for creating an Object. \n */\npublic class PutOptions extends BaseHttpRequestOptions {\n\n   public static final PutOptions NONE = new PutOptions();\n\n   /**\n    * Sets the metadata on a container at creation.\n    */\n   public PutOptions metadata(Map<String, String> metadata) {\n      this.headers.putAll(bindMetadataToHeaders.toHeaders(metadata));\n      return this;\n   }\n\n   /**\n    * Sets the headers on a container at creation.\n    */\n   public PutOptions headers(Multimap<String, String> headers) {\n      this.headers.putAll(headers);\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see PutOptions#headers\n       */\n      public static PutOptions headers(Multimap<String, String> headers) {\n         PutOptions options = new PutOptions();\n         return options.headers(headers);\n      }\n\n      /**\n       * @see PutOptions#metadata\n       */\n      public static PutOptions metadata(Map<String, String> metadata) {\n         PutOptions options = new PutOptions();\n         return options.metadata(metadata);\n      }\n   }\n\n   private static final BindMetadataToHeaders bindMetadataToHeaders = new BindMetadataToHeaders(OBJECT_METADATA_PREFIX);\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/options/UpdateContainerOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.options;\n\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.CONTAINER_ACL_ANYBODY_READ;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.CONTAINER_METADATA_PREFIX;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.CONTAINER_READ;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.VERSIONS_LOCATION;\n\nimport java.util.Map;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\nimport org.jclouds.openstack.swift.v1.binders.BindMetadataToHeaders;\n\nimport com.google.common.collect.Multimap;\n\n/**\n * Options for updating a {@link Container}.\n *\n * @see org.jclouds.openstack.swift.v1.features.ContainerApi#update(String, UpdateContainerOptions)\n */\npublic class UpdateContainerOptions extends BaseHttpRequestOptions {\n   public static final UpdateContainerOptions NONE = new UpdateContainerOptions();\n\n   /**\n    * Sets the headers on a container at creation.\n    */\n   public UpdateContainerOptions headers(Multimap<String, String> headers) {\n      this.headers.putAll(headers);\n      return this;\n   }\n\n   /**\n    * Sets the metadata on a container at creation.\n    */\n   public UpdateContainerOptions metadata(Map<String, String> metadata) {\n      this.headers.putAll(bindMetadataToHeaders.toHeaders(metadata));\n      return this;\n   }\n\n   /**\n    * Sets the public ACL on the container so that anybody can read it.\n    */\n   public UpdateContainerOptions anybodyRead() {\n      this.headers.put(CONTAINER_READ, CONTAINER_ACL_ANYBODY_READ);\n      return this;\n   }\n\n   /**\n    * Sets the container that will contain object versions.\n    */\n   public UpdateContainerOptions versionsLocation(String containerName) {\n      this.headers.put(VERSIONS_LOCATION, containerName);\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see UpdateContainerOptions#anybodyRead\n       */\n      public static UpdateContainerOptions anybodyRead() {\n         UpdateContainerOptions options = new UpdateContainerOptions();\n         return options.anybodyRead();\n      }\n\n      /**\n       * @see UpdateContainerOptions#headers\n       */\n      public static UpdateContainerOptions headers(Multimap<String, String> headers) {\n         UpdateContainerOptions options = new UpdateContainerOptions();\n         return options.headers(headers);\n      }\n\n      /**\n       * @see UpdateContainerOptions#metadata\n       */\n      public static UpdateContainerOptions metadata(Map<String, String> metadata) {\n         UpdateContainerOptions options = new UpdateContainerOptions();\n         return options.metadata(metadata);\n      }\n\n      /**\n       * @see UpdateContainerOptions#versionsLocation\n       */\n      public static UpdateContainerOptions versionsLocation(String containerName) {\n         UpdateContainerOptions options = new UpdateContainerOptions();\n         return options.versionsLocation(containerName);\n      }\n   }\n\n   private static final BindMetadataToHeaders bindMetadataToHeaders = new BindMetadataToHeaders(CONTAINER_METADATA_PREFIX);\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/reference/SwiftHeaders.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.reference;\n\n/**\n * Common headers in Swift.\n */\npublic final class SwiftHeaders {\n\n   // Common Metadata Prefixes\n   public static final String ACCOUNT_METADATA_PREFIX = \"X-Account-Meta-\";\n   public static final String CONTAINER_METADATA_PREFIX = \"X-Container-Meta-\";\n   public static final String OBJECT_METADATA_PREFIX = \"X-Object-Meta-\";\n   public static final String USER_METADATA_PREFIX = OBJECT_METADATA_PREFIX;\n   \n   // Metadata Removal Prefixes\n   public static final String ACCOUNT_REMOVE_METADATA_PREFIX = \"X-Remove-Account-Meta-\";\n   public static final String CONTAINER_REMOVE_METADATA_PREFIX = \"X-Remove-Container-Meta-\";\n   public static final String OBJECT_REMOVE_METADATA_PREFIX = \"X-Remove-Object-Meta-\";\n   \n   // TempURL\n   public static final String ACCOUNT_TEMPORARY_URL_KEY = ACCOUNT_METADATA_PREFIX + \"Temp-Url-Key\";\n   public static final String ACCOUNT_TEMPORARY_URL_KEY_2 = ACCOUNT_TEMPORARY_URL_KEY + \"-2\";\n\n   // Account Headers\n   public static final String ACCOUNT_BYTES_USED = \"X-Account-Bytes-Used\";\n   public static final String ACCOUNT_CONTAINER_COUNT = \"X-Account-Container-Count\";\n   public static final String ACCOUNT_OBJECT_COUNT = \"X-Account-Object-Count\";\n\n   // Container Headers\n   public static final String CONTAINER_BYTES_USED = \"X-Container-Bytes-Used\";\n   public static final String CONTAINER_OBJECT_COUNT = \"X-Container-Object-Count\";\n\n   // Public access - not supported in all Swift Impls\n   public static final String CONTAINER_READ = \"X-Container-Read\";\n   public static final String CONTAINER_WRITE = \"X-Container-Write\";\n   public static final String CONTAINER_ACL_ANYBODY_READ = \".r:*,.rlistings\";\n   public static final String CONTAINER_ACL_PRIVATE = \"\";\n   \n   // CORS\n   public static final String CONTAINER_ACCESS_CONTROL_ALLOW_ORIGIN = CONTAINER_METADATA_PREFIX + \"Access-Control-Allow-Origin\";\n   public static final String CONTAINER_ACCESS_CONTROL_MAX_AGE = CONTAINER_METADATA_PREFIX + \"Access-Control-Max-Age\";\n   public static final String CONTAINER_ACCESS_CONTROL_EXPOSE_HEADERS = CONTAINER_METADATA_PREFIX + \"Access-Control-Expose-Headers\";\n\n   // Container Quota\n   public static final String CONTAINER_QUOTA_BYTES = CONTAINER_METADATA_PREFIX + \"Quota-Bytes\";\n   public static final String CONTAINER_QUOTA_COUNT = CONTAINER_METADATA_PREFIX + \"Quota-Count\";\n\n   // Container Sync\n   public static final String CONTAINER_SYNC_KEY = \"X-Container-Sync-Key\";\n   public static final String CONTAINER_SYNC_TO = \"X-Container-Sync-To\";\n\n   // Versioning\n   public static final String VERSIONS_LOCATION = \"X-Versions-Location\";\n\n   // Misc functionality\n   public static final String CONTAINER_WEB_MODE = \"X-Web-Mode\";\n\n   public static final String OBJECT_COPY_FROM = \"X-Copy-From\";\n   public static final String OBJECT_COPY_FRESH_METADATA = \"X-Fresh-Metadata\";\n   public static final String OBJECT_DELETE_AFTER = \"X-Delete-After\";\n   public static final String OBJECT_DELETE_AT = \"X-Delete-At\";\n   public static final String OBJECT_MANIFEST = \"X-Object-Manifest\";\n   /** Get the newest version of the object for GET and HEAD requests */\n   public static final String OBJECT_NEWEST = \"X-Newest\";\n\n   // Static Large Object\n   public static final String STATIC_LARGE_OBJECT = \"X-Static-Large-Object\";\n\n   // Static Web\n   public static final String STATIC_WEB_INDEX = CONTAINER_METADATA_PREFIX + \"Web-Index\";\n   public static final String STATIC_WEB_DIRECTORY_TYPE = CONTAINER_METADATA_PREFIX + \"Web-Directory-Type\";\n   public static final String STATIC_WEB_ERROR = CONTAINER_METADATA_PREFIX + \"Web-Error\";\n   public static final String STATIC_WEB_LISTINGS = CONTAINER_METADATA_PREFIX + \"Web-Listings\";\n   public static final String STATIC_WEB_LISTINGS_CSS = CONTAINER_METADATA_PREFIX + \"Web-Listings-CSS\";\n\n   private SwiftHeaders() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/reference/TempAuthHeaders.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.reference;\n\n/**\n * Headers for TempAuth authentication\n */\npublic final class TempAuthHeaders {\n   public static final String TEMP_AUTH_HEADER_USER = \"jclouds.swift.tempAuth.headerUser\";\n   public static final String TEMP_AUTH_HEADER_PASS = \"jclouds.swift.tempAuth.headerPass\";\n\n   public static final String DEFAULT_HEADER_USER = \"X-Storage-User\";\n   public static final String DEFAULT_HEADER_PASS = \"X-Storage-Pass\";\n   public static final String STORAGE_URL = \"X-Storage-Url\";\n\n   private TempAuthHeaders() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/AuthenticationMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1;\n\nimport static org.jclouds.openstack.swift.v1.features.AccountApiMockTest.accountResponse;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Properties;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\nimport okhttp3.mockwebserver.RecordedRequest;\n\nimport org.jclouds.openstack.v2_0.internal.BaseOpenStackMockTest;\nimport org.testng.annotations.DataProvider;\nimport org.testng.annotations.Test;\n\n\n/**\n * @see KeystoneProperties#CREDENTIAL_TYPE\n */\n@Test\npublic class AuthenticationMockTest extends BaseOpenStackMockTest<SwiftApi> {\n\n   @DataProvider(name = \"jclouds.keystone.credential-type\")\n   Object[][] credentialTypeToPostBody() {\n      Object[][] credentialTypeToPostBody = new Object[2][2];\n      credentialTypeToPostBody[0][0] = \"apiAccessKeyCredentials\";\n      credentialTypeToPostBody[0][1] = \"{\\\"auth\\\":{\\\"apiAccessKeyCredentials\\\":{\\\"accessKey\\\":\\\"joe\\\",\\\"secretKey\\\":\\\"letmein\\\"},\\\"tenantName\\\":\\\"jclouds\\\"}}\";\n      credentialTypeToPostBody[1][0] = \"passwordCredentials\";\n      credentialTypeToPostBody[1][1] = \"{\\\"auth\\\":{\\\"passwordCredentials\\\":{\\\"username\\\":\\\"joe\\\",\\\"password\\\":\\\"letmein\\\"},\\\"tenantName\\\":\\\"jclouds\\\"}}\";\n      return credentialTypeToPostBody;\n   }\n\n   @Test(dataProvider = \"jclouds.keystone.credential-type\")\n   public void authenticateCredentialType(String credentialType, String expectedPost) throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(accountResponse()));\n\n      try {\n         Properties overrides = new Properties();\n         overrides.setProperty(\"jclouds.keystone.credential-type\", credentialType);\n\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\", overrides);\n\n         api.getAccountApi(\"DFW\").get();\n\n         assertEquals(server.getRequestCount(), 2);\n         RecordedRequest authRequest = server.takeRequest();\n         assertEquals(authRequest.getRequestLine(), \"POST /tokens HTTP/1.1\");\n         assertEquals(authRequest.getBody().readUtf8(), expectedPost);\n      } finally {\n         server.shutdown();\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/SwiftApiMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1;\n\nimport org.jclouds.View;\nimport org.jclouds.apis.internal.BaseApiMetadataTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.reflect.TypeToken;\n\n@Test(groups = \"unit\", testName = \"SwiftApiMetadataTest\")\n// public class SwiftApiMetadataTest extends BaseBlobStoreApiMetadataTest {\npublic class SwiftApiMetadataTest extends BaseApiMetadataTest {\n   public SwiftApiMetadataTest() {\n      super(new SwiftApiMetadata(), ImmutableSet.<TypeToken<? extends View>> of());\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/SwiftErrorHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.reportMatcher;\nimport static org.easymock.EasyMock.verify;\nimport static org.jclouds.io.Payloads.newByteSourcePayload;\n\nimport java.net.URI;\n\nimport org.easymock.IArgumentMatcher;\nimport org.jclouds.blobstore.ContainerNotFoundException;\nimport org.jclouds.blobstore.KeyNotFoundException;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.swift.v1.handlers.SwiftErrorHandler;\nimport org.testng.annotations.Test;\n\nimport com.google.common.io.ByteSource;\n\n/**\n * Tests the {@link SwiftErrorHandler}\n */\n@Test(groups = \"unit\", testName = \"SwiftErrorHandlerTest\")\npublic class SwiftErrorHandlerTest {\n\n   @Test\n   public void test404SetsKeyNotFoundExceptionMosso() {\n      assertCodeMakes(\"HEAD\", URI\n               .create(\"http://host/v1/MossoCloudFS_7064cdb1d49d4dcba3c899ac33e8409d/adriancole-blobstore1/key\"), 404,\n               \"Not Found\", \"\", KeyNotFoundException.class);\n   }\n\n   @Test\n   public void test404SetsKeyNotFoundExceptionSwift() {\n      assertCodeMakes(\"HEAD\", URI\n               .create(\"http://67.202.39.175:8080/v1/AUTH_7064cdb1d49d4dcba3c899ac33e8409d/adriancole-blobstore1/key\"),\n               404, \"Not Found\", \"\", KeyNotFoundException.class);\n   }\n\n   @Test\n   public void test404SetsContainerNotFoundExceptionMosso() {\n      assertCodeMakes(\"HEAD\", URI\n               .create(\"http://host/v1/MossoCloudFS_7064cdb1d49d4dcba3c899ac33e8409d/adriancole-blobstore1\"), 404,\n               \"Not Found\", \"\", ContainerNotFoundException.class);\n   }\n\n   @Test\n   public void test404SetsContainerNotFoundExceptionSwift() {\n      assertCodeMakes(\"HEAD\", URI\n               .create(\"http://67.202.39.175:8080/v1/AUTH_7064cdb1d49d4dcba3c899ac33e8409d/adriancole-blobstore1\"),\n               404, \"Not Found\", \"\", ContainerNotFoundException.class);\n   }\n\n   private void assertCodeMakes(String method, URI uri, int statusCode, String message, String content,\n            Class<? extends Exception> expected) {\n      assertCodeMakes(method, uri, statusCode, message, \"text/plain\", content, expected);\n   }\n\n   private void assertCodeMakes(String method, URI uri, int statusCode, String message, String contentType,\n            String content, Class<? extends Exception> expected) {\n\n      SwiftErrorHandler function = new SwiftErrorHandler();\n\n      HttpCommand command = createMock(HttpCommand.class);\n      HttpRequest request = HttpRequest.builder().method(method).endpoint(uri).build();\n      HttpResponse response = HttpResponse.builder().statusCode(statusCode).message(message)\n                                 .payload(newByteSourcePayload(ByteSource.wrap(content.getBytes()))).build();\n      response.getPayload().getContentMetadata().setContentType(contentType);\n\n      expect(command.getCurrentRequest()).andReturn(request).atLeastOnce();\n      command.setException(classEq(expected));\n\n      replay(command);\n\n      function.handleError(command, response);\n\n      verify(command);\n   }\n\n   public static Exception classEq(final Class<? extends Exception> in) {\n      reportMatcher(new IArgumentMatcher() {\n\n         @Override\n         public void appendTo(StringBuffer buffer) {\n            buffer.append(\"classEq(\");\n            buffer.append(in);\n            buffer.append(\")\");\n         }\n\n         @Override\n         public boolean matches(Object arg) {\n            return arg.getClass() == in;\n         }\n\n      });\n      return null;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/TempAuthMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1;\n\nimport static com.google.common.util.concurrent.MoreExecutors.newDirectExecutorService;\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.CREDENTIAL_TYPE;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.util.Properties;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\nimport okhttp3.mockwebserver.RecordedRequest;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.concurrent.config.ExecutorServiceModule;\nimport org.jclouds.openstack.swift.v1.reference.TempAuthHeaders;\nimport org.testng.annotations.AfterMethod;\nimport org.testng.annotations.BeforeMethod;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n\n@Test(groups = \"unit\", testName = \"TempAuthMockTest\", singleThreaded = true)\npublic class TempAuthMockTest {\n\n   private MockWebServer swiftServer;\n   private MockWebServer tempAuthServer;\n\n   public void testTempAuthRequestWithCustomHeader() throws Exception {\n     final String headerName = \"X-Auth-User\";\n     final String headerPass = \"X-Auth-Pass\";\n     Properties overrides = new Properties();\n     overrides.setProperty(TempAuthHeaders.TEMP_AUTH_HEADER_USER, headerName);\n     overrides.setProperty(TempAuthHeaders.TEMP_AUTH_HEADER_PASS, headerPass);\n     // with specific Header Name values\n     test(overrides, headerName, headerPass);\n   }\n\n   public void testTempAuthRequest() throws Exception {\n     Properties overrides = new Properties();\n     // with default values\n     test(overrides, \"X-Storage-User\", \"X-Storage-Pass\");\n  }\n   \n   private void test(Properties overrides, String identityHeaderName, String identityHeaderPass) throws Exception{\n       tempAuthServer.enqueue(new MockResponse().setResponseCode(204)\n            .addHeader(\"X-Auth-Token\", \"token\")\n            .addHeader(\"X-Storage-Url\", swiftServer.url(\"\").toString()));\n\n      swiftServer.enqueue(new MockResponse().setBody(\"[{\\\"name\\\":\\\"test_container_1\\\",\\\"count\\\":2,\\\"bytes\\\":78}]\"));\n\n      SwiftApi api = api(tempAuthServer.url(\"\").toString(), overrides);\n\n      // Region name is derived from the swift server host.\n      assertEquals(api.getConfiguredRegions(), ImmutableSet.of(tempAuthServer.getHostName()));\n\n      assertTrue(api.getContainerApi(tempAuthServer.getHostName()).list().iterator().hasNext());\n\n      RecordedRequest auth = tempAuthServer.takeRequest();\n      assertEquals(auth.getMethod(), \"GET\");\n      assertEquals(auth.getHeader(identityHeaderName), \"user\");\n      assertEquals(auth.getHeader(identityHeaderPass), \"password\");\n\n      // list request went to the destination specified in X-Storage-Url.\n      RecordedRequest listContainers = swiftServer.takeRequest();\n      assertEquals(listContainers.getMethod(), \"GET\");\n      assertThat(listContainers.getPath().contains(\"?format=json\"));\n      assertEquals(listContainers.getHeader(\"Accept\"), APPLICATION_JSON);\n      assertEquals(listContainers.getHeader(\"X-Auth-Token\"), \"token\");\n   }\n\n   private SwiftApi api(String authUrl, Properties overrides) throws IOException {\n      overrides.setProperty(CREDENTIAL_TYPE, \"tempAuthCredentials\");\n      return ContextBuilder.newBuilder(new SwiftApiMetadata())\n            .credentials(\"user\", \"password\")\n            .endpoint(authUrl)\n            .overrides(overrides)\n            .modules(ImmutableSet.of(new ExecutorServiceModule(newDirectExecutorService())))\n            .buildApi(SwiftApi.class);\n   }\n\n   @BeforeMethod\n   public void start() throws IOException {\n      tempAuthServer = new MockWebServer();\n      tempAuthServer.start();\n\n      swiftServer = new MockWebServer();\n      swiftServer.start();\n   }\n\n   @AfterMethod(alwaysRun = true)\n   public void stop() throws IOException {\n      tempAuthServer.shutdown();\n      swiftServer.shutdown();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/TemporaryUrlSignerLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1;\n\nimport static java.lang.String.format;\nimport static org.jclouds.io.Payloads.newByteSourcePayload;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.fail;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.net.URI;\nimport java.util.UUID;\n\nimport org.jclouds.openstack.swift.v1.domain.SwiftObject;\nimport org.jclouds.openstack.swift.v1.internal.BaseSwiftApiLiveTest;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.AfterMethod;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.io.ByteSource;\n\n@Test(groups = \"live\", testName = \"TemporaryUrlSignerLiveTest\")\npublic class TemporaryUrlSignerLiveTest extends BaseSwiftApiLiveTest {\n\n   private String name = getClass().getSimpleName();\n   private String containerName = getClass().getSimpleName() + \"Container\";\n\n   public void signForPublicAccess() throws Exception {\n      for (String regionId : getApi().getConfiguredRegions()) {\n         SwiftObject object = getApi().getObjectApi(regionId, containerName).get(name);\n\n         long expires = System.currentTimeMillis() / 1000 + 5;\n         String signature = TemporaryUrlSigner.checkApiEvery(getApi().getAccountApi(regionId), 5)\n               .sign(\"GET\", object.getUri().getPath(), expires);\n\n         URI signed = URI.create(format(\"%s?temp_url_sig=%s&temp_url_expires=%s\", object.getUri(), signature, expires));\n\n         InputStream publicStream = signed.toURL().openStream();\n         assertEquals(Strings2.toStringAndClose(publicStream), \"swifty\");\n\n         // let it expire\n         Thread.sleep(5000);\n         try {\n            signed.toURL().openStream();\n            fail(\"should have expired!\");\n         } catch (IOException e) {\n         }\n      }\n   }\n\n   @Override\n   @BeforeClass(groups = \"live\")\n   public void setup() {\n      super.setup();\n      String key = UUID.randomUUID().toString();\n      for (String regionId : getApi().getConfiguredRegions()) {\n         getApi().getAccountApi(regionId).updateTemporaryUrlKey(key);\n         getApi().getContainerApi(regionId).create(containerName);\n         getApi().getObjectApi(regionId, containerName)\n               .put(name, newByteSourcePayload(ByteSource.wrap(\"swifty\".getBytes())));\n      }\n   }\n\n   @AfterMethod\n   @AfterClass(groups = \"live\")\n   public void tearDown() {\n      for (String regionId : getApi().getConfiguredRegions()) {\n         getApi().getObjectApi(regionId, containerName).delete(name);\n         getApi().getContainerApi(regionId).deleteIfEmpty(containerName);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/TemporaryUrlSignerMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1;\n\nimport static org.jclouds.openstack.swift.v1.features.AccountApiMockTest.accountResponse;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.ACCOUNT_TEMPORARY_URL_KEY;\nimport static org.testng.Assert.assertEquals;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\n\nimport org.jclouds.openstack.v2_0.internal.BaseOpenStackMockTest;\nimport org.testng.annotations.Test;\n\n\n@Test(groups = \"unit\", testName = \"TemporaryUrlSignerMockTest\")\npublic class TemporaryUrlSignerMockTest extends BaseOpenStackMockTest<SwiftApi> {\n\n   @Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = \"accountApi\")\n   public void whenAccountApiIsNull() {\n      TemporaryUrlSigner.checkApiEvery(null, 10000);\n   }\n\n   public void whenAccountApiHasKey() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(accountResponse().addHeader(ACCOUNT_TEMPORARY_URL_KEY, \"mykey\")));\n\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         String signature = TemporaryUrlSigner.checkApiEvery(api.getAccountApi(\"DFW\"), 10000)\n               .sign(\"GET\", \"/v1/AUTH_account/container/object\", 1323479485L);\n\n         assertEquals(signature, \"d9fc2067e52b06598421664cf6610bfc8fc431f6\");\n\n         assertEquals(server.getRequestCount(), 2);\n         assertEquals(server.takeRequest().getRequestLine(), \"POST /tokens HTTP/1.1\");\n         assertEquals(server.takeRequest().getRequestLine(),\n               \"HEAD /v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9 HTTP/1.1\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   @Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = \".*returned a null temporaryUrlKey!\")\n   public void whenAccountApiDoesntHaveKey() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(accountResponse()));\n\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         TemporaryUrlSigner.checkApiEvery(api.getAccountApi(\"DFW\"), 10000)\n            .sign(\"GET\", \"/v1/AUTH_account/container/object\", 1323479485L);\n      } finally {\n         assertEquals(server.getRequestCount(), 2);\n         assertEquals(server.takeRequest().getRequestLine(), \"POST /tokens HTTP/1.1\");\n         assertEquals(server.takeRequest().getRequestLine(),\n               \"HEAD /v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9 HTTP/1.1\");\n         server.shutdown();\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/blobstore/RegionScopedBlobStoreContextLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.blobstore;\n\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.CREDENTIAL_TYPE;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.fail;\n\nimport java.io.IOException;\nimport java.util.Properties;\nimport java.util.Set;\nimport java.util.UUID;\nimport java.util.concurrent.ExecutionException;\n\nimport org.jclouds.blobstore.BlobRequestSigner;\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.PageSet;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.integration.internal.BaseBlobStoreIntegrationTest;\nimport org.jclouds.domain.Location;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.io.ByteStreams2;\nimport org.jclouds.io.MutableContentMetadata;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.rest.HttpClient;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Iterables;\nimport com.google.common.io.ByteSource;\nimport com.google.common.hash.Hashing;\nimport com.google.common.net.MediaType;\nimport com.google.common.net.HttpHeaders;\n\n@Test(groups = \"live\")\npublic class RegionScopedBlobStoreContextLiveTest extends BaseBlobStoreIntegrationTest {\n\n   public RegionScopedBlobStoreContextLiveTest() {\n      provider = \"openstack-swift\";\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      setIfTestSystemPropertyPresent(props, CREDENTIAL_TYPE);\n      return props;\n   }\n\n   @Test\n   public void testRegionsAreNotEmpty() {\n      assertFalse(RegionScopedBlobStoreContext.class.cast(view).getConfiguredRegions().isEmpty());\n   }\n\n   @Test\n   public void testLocationsMatch() {\n      RegionScopedBlobStoreContext ctx = RegionScopedBlobStoreContext.class.cast(view);\n      for (String regionId : ctx.getConfiguredRegions()) {\n         Set<? extends Location> locations = ctx.getBlobStore(regionId).listAssignableLocations();\n         assertEquals(locations.size(), 1, \"expected one region \" + regionId + \" \" + locations);\n         Location location = locations.iterator().next();\n         assertEquals(location.getId(), regionId, \"region id \" + regionId + \" didn't match getId(): \" + location);\n      }\n   }\n\n   @Test\n   public void testListBlobs() throws InterruptedException, ExecutionException {\n      RegionScopedBlobStoreContext ctx = RegionScopedBlobStoreContext.class.cast(view);\n      for (String regionId : ctx.getConfiguredRegions()) {\n         ctx.getBlobStore(regionId).list();\n      }\n   }\n\n   @Test\n   public void testSign() throws InterruptedException, ExecutionException,\n         IOException {\n      RegionScopedBlobStoreContext ctx = RegionScopedBlobStoreContext.class.cast(view);\n      for (String regionId : ctx.getConfiguredRegions()) {\n         BlobStore region = ctx.getBlobStore(regionId);\n         PageSet<? extends StorageMetadata> containers = region.list();\n         if (containers.isEmpty()) {\n            continue;\n         }\n         String containerName = Iterables.getLast(containers).getName();\n\n         final ByteSource input = ByteSource.wrap(\"str\".getBytes());\n         final HttpClient client = ctx.utils().http();\n\n         // test signed put\n         String blobName = \"test-\" + UUID.randomUUID();\n         Blob blob2 = region.blobBuilder(blobName).forSigning()\n               .contentLength(input.size())\n               .contentMD5(input.hash(Hashing.md5()).asBytes())\n               .contentType(MediaType.OCTET_STREAM.toString()).build();\n         BlobRequestSigner signer = ctx.getSigner(regionId);\n         HttpResponse response;\n         try {\n            HttpRequest putRequest;\n            putRequest = signer.signPutBlob(containerName, blob2, 600);\n            MutableContentMetadata metadata = blob2.getMetadata()\n                  .getContentMetadata();\n            HttpRequest.Builder<?> putRequestBuilder = putRequest.toBuilder()\n                  .addHeader(HttpHeaders.CONTENT_TYPE,\n                        metadata.getContentType());\n            putRequestBuilder.addHeader(HttpHeaders.CONTENT_LENGTH,\n                  String.valueOf(input.size()));\n            putRequestBuilder.payload(input);\n            putRequest = putRequestBuilder.build();\n            Payload payload = Payloads.newPayload(input.read());\n            putRequest.setPayload(payload);\n            assertNotNull(putRequest, \"regionId=\" + regionId + \", container=\"\n                  + containerName + \", blob=\" + blobName);\n            response = client.invoke(putRequest);\n            if (response.getStatusCode() != 200\n                  && response.getStatusCode() != 201) {\n               fail(\"Signed PUT expected to return 200 or 201 but returned \"\n                     + response.getStatusCode());\n            }\n         } catch (Exception e) {\n            fail(\"Failed signed put test: \" + e);\n         }\n\n         // test signed get\n         try {\n            HttpRequest getRequest = signer.signGetBlob(containerName,\n                  blobName);\n            assertNotNull(getRequest, \"regionId=\" + regionId + \", container=\"\n                  + containerName + \", blob=\" + blobName);\n            response = client.invoke(getRequest);\n            if (response.getStatusCode() != 200) {\n               fail(\"Signed GET expected to return 200 but returned \"\n                     + response.getStatusCode());\n            }\n            Payload payload = response.getPayload();\n            assertEquals(ByteStreams2.toByteArrayAndClose(payload.openStream()), input.read(),\n                  \"Data with signed GET not identical to what was put\");\n         } catch (Exception e) {\n            fail(\"Failed signed GET test: \" + e);\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/blobstore/RegionScopedSwiftBlobStoreParallelLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.blobstore;\n\nimport static org.assertj.core.util.Files.delete;\nimport static org.jclouds.blobstore.options.PutOptions.Builder.multipart;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.CREDENTIAL_TYPE;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.RandomAccessFile;\nimport java.nio.MappedByteBuffer;\nimport java.nio.channels.FileChannel;\nimport java.util.Properties;\nimport java.util.Random;\nimport java.util.UUID;\nimport java.util.concurrent.ArrayBlockingQueue;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.ThreadPoolExecutor;\nimport java.util.concurrent.TimeUnit;\n\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.integration.internal.BaseBlobStoreIntegrationTest;\nimport org.jclouds.io.payloads.FilePayload;\nimport org.jclouds.util.Closeables2;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.hash.HashCode;\nimport com.google.common.hash.Hasher;\nimport com.google.common.hash.Hashing;\nimport com.google.common.io.Files;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.common.util.concurrent.MoreExecutors;\n\n// TODO: Rolls tests up to BaseBlobStoreIntegrationTest\n@Test(groups = \"live\", singleThreaded = true)\npublic class RegionScopedSwiftBlobStoreParallelLiveTest extends BaseBlobStoreIntegrationTest {\n\n   private File bigFile = new File(\"random.dat\");\n   private static final long SIZE = 10 * 1000 * 1000;\n   private BlobStore blobStore;\n   private String etag;\n   private ListeningExecutorService executor =\n         MoreExecutors.listeningDecorator(\n               MoreExecutors.getExitingExecutorService(\n                     new ThreadPoolExecutor(5, 5,\n                           5000L, TimeUnit.MILLISECONDS,\n                           new ArrayBlockingQueue<Runnable>(10, true), new ThreadPoolExecutor.CallerRunsPolicy())));\n\n   private static final String CONTAINER = \"jcloudsparalleltest\" + UUID.randomUUID();\n\n   public RegionScopedSwiftBlobStoreParallelLiveTest() {\n      provider = \"openstack-swift\";\n      try {\n         bigFile = File.createTempFile(\"random\", \"dat\");\n      } catch (IOException ioe) {\n         throw new RuntimeException(ioe);\n      }\n   }\n\n   // Override as needed for the right region\n   protected BlobStore getBlobStore() {\n      RegionScopedBlobStoreContext ctx = RegionScopedBlobStoreContext.class.cast(view);\n      return ctx.getBlobStore(ctx.getConfiguredRegions().iterator().next());\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      setIfTestSystemPropertyPresent(props, CREDENTIAL_TYPE);\n      return props;\n   }\n\n   @BeforeClass\n   public void setup() throws IOException, InterruptedException {\n      blobStore = getBlobStore();\n      createRandomFile(SIZE, bigFile);\n      HashCode hashCode = Files.hash(bigFile, Hashing.md5());\n      etag = hashCode.toString();\n      blobStore.createContainerInLocation(null, CONTAINER);\n      System.out.println(\"generated file md5: \" + etag);\n   }\n\n   @AfterClass\n   public void cleanupFiles() {\n      // Delete local file\n      delete(bigFile);\n      delete(new File(bigFile + \".downloaded\"));\n\n      // Delete uploaded file\n      blobStore.clearContainer(CONTAINER);\n      blobStore.deleteContainer(CONTAINER);\n   }\n\n   @Test\n   public void uploadMultipartBlob() {\n      Blob blob = blobStore.blobBuilder(bigFile.getName())\n            .payload(new FilePayload(bigFile))\n            .build();\n      // configure the blobstore to use multipart uploading of the file\n      String eTag = blobStore.putBlob(CONTAINER, blob, multipart(executor));\n      // assertEquals(eTag, etag);\n      // The etag returned by Swift is not the md5 of the Blob uploaded\n      // It is the md5 of the concatenated segment md5s\n   }\n\n   @Test(dependsOnMethods = \"uploadMultipartBlob\", singleThreaded = true)\n   public void downloadParallelBlob() throws IOException {\n      final File downloadedFile = new File(bigFile + \".downloaded\");\n      blobStore.downloadBlob(CONTAINER, bigFile.getName(), downloadedFile, executor);\n      String eTag = Files.hash(downloadedFile, Hashing.md5()).toString();\n      assertEquals(eTag, etag);\n   }\n\n   @Test(dependsOnMethods = \"uploadMultipartBlob\", singleThreaded = true)\n   public void streamParallelBlob() throws IOException {\n      InputStream is = blobStore.streamBlob(CONTAINER, bigFile.getName(), executor);\n      byte[] segment = new byte[1000000];\n\n      Hasher hasher = Hashing.md5().newHasher();\n\n      int read;\n      while ( (read = is.read(segment)) > 0) {\n         System.out.println(\"Read \" + read + \" bytes from input stream.\");\n         hasher.putBytes(segment, 0, read);\n      }\n\n      is.close();\n      assertEquals(hasher.hash().toString(), etag);\n   }\n\n   private void createRandomFile(long size, File file) throws IOException, InterruptedException {\n      RandomAccessFile raf = null;\n\n      // Reserve space for performance reasons\n      raf = new RandomAccessFile(file.getAbsoluteFile(), \"rw\");\n      try {\n         raf.seek(size - 1);\n         raf.write(0);\n\n         // Loop through ranges within the file\n         long from;\n         long to;\n         long partSize = 1000000;\n\n         ExecutorService threadPool = Executors.newFixedThreadPool(16);\n\n         for (from = 0; from < size; from = from + partSize) {\n            to = (from + partSize >= size) ? size - 1 : from + partSize - 1;\n            RandomFileWriter writer = new RandomFileWriter(raf, from, to);\n            threadPool.submit(writer);\n         }\n\n         threadPool.shutdown();\n         threadPool.awaitTermination(1, TimeUnit.DAYS);\n      } finally {\n         Closeables2.closeQuietly(raf);\n      }\n   }\n\n   private static final class RandomFileWriter implements Runnable {\n      private final RandomAccessFile raf;\n      private final long begin;\n      private final long end;\n\n      RandomFileWriter(RandomAccessFile raf, long begin, long end) {\n         this.raf = raf;\n         this.begin = begin;\n         this.end = end;\n      }\n\n      @Override\n      public void run() {\n         try {\n            byte[] targetArray = new byte[(int) (end - begin + 1)];\n            Random random = new Random();\n            random.nextBytes(targetArray);\n            // Map file region\n            MappedByteBuffer out = raf.getChannel().map(FileChannel.MapMode.READ_WRITE, begin, end - begin + 1);\n            out.put(targetArray);\n            out.force();\n         } catch (IOException e) {\n            throw new RuntimeException(e);\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/blobstore/integration/SwiftBlobIntegrationLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.blobstore.integration;\n\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.CREDENTIAL_TYPE;\n\nimport java.util.Properties;\n\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.BlobMetadata;\nimport org.jclouds.blobstore.domain.Tier;\nimport org.jclouds.blobstore.integration.internal.BaseBlobIntegrationTest;\nimport org.testng.SkipException;\nimport org.testng.annotations.DataProvider;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"SwiftBlobIntegrationLiveTest\")\npublic class SwiftBlobIntegrationLiveTest extends BaseBlobIntegrationTest {\n\n   public SwiftBlobIntegrationLiveTest() {\n      provider = \"openstack-swift\";\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      setIfTestSystemPropertyPresent(props, CREDENTIAL_TYPE);\n      return props;\n   }\n\n   // Object/Container name contains forbidden chars from \"<>\n   @Override\n   @DataProvider(name = \"delete\")\n   public Object[][] createData() {\n      return new Object[][] { { \"normal\" }, { \"sp ace\" }, { \"qu?stion\" }, { \"unic₪de\" }, { \"path/foo\" }, { \"colon:\" },\n            { \"asteri*k\" }, { \"p|pe\" } };\n   }\n\n   @Override\n   public void testGetTwoRanges() {\n      throw new SkipException(\"unsupported in swift\");\n   }\n\n   @Override\n   public void testCreateBlobWithExpiry() throws InterruptedException {\n      throw new SkipException(\"unsupported in swift\");\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testGetIfUnmodifiedSince() throws InterruptedException {\n      throw new SkipException(\"unsupported in swift\");\n   }\n\n   @Override\n   protected int getIncorrectContentMD5StatusCode() {\n      return 422;\n   }\n\n   // not supported\n   @Override\n   protected void checkCacheControl(Blob blob, String cacheControl) {\n      assertThat(blob.getPayload().getContentMetadata().getCacheControl()).isNull();\n      assertThat(blob.getMetadata().getContentMetadata().getCacheControl()).isNull();\n   }\n\n   // not supported\n   @Override\n   protected void checkContentLanguage(Blob blob, String contentLanguage) {\n      assert blob.getPayload().getContentMetadata().getContentLanguage() == null;\n      assert blob.getMetadata().getContentMetadata().getContentLanguage() == null;\n   }\n\n   @Override\n   public void testSetBlobAccess() throws Exception {\n      throw new SkipException(\"unsupported in swift\");\n   }\n\n   @Override\n   @Test(expectedExceptions = UnsupportedOperationException.class)\n   public void testPutBlobAccess() throws Exception {\n      super.testPutBlobAccess();\n   }\n\n   @Override\n   @Test(expectedExceptions = UnsupportedOperationException.class)\n   public void testPutBlobAccessMultipart() throws Exception {\n      super.testPutBlobAccessMultipart();\n   }\n\n   @Override\n   @Test(expectedExceptions = UnsupportedOperationException.class)\n   public void testCopyIfNoneMatch() throws Exception {\n      super.testCopyIfNoneMatch();\n   }\n\n   @Override\n   @Test(expectedExceptions = UnsupportedOperationException.class)\n   public void testCopyIfNoneMatchNegative() throws Exception {\n      super.testCopyIfNoneMatchNegative();\n   }\n\n   @Override\n   public void testListMultipartUploads() throws Exception {\n      try {\n         super.testListMultipartUploads();\n         failBecauseExceptionWasNotThrown(UnsupportedOperationException.class);\n      } catch (UnsupportedOperationException uoe) {\n         throw new SkipException(\"Swift does not support listing multipart uploads\", uoe);\n      }\n   }\n\n   // TODO: testCopyIfModifiedSinceNegative throws HTTP 304 not 412 error\n\n   @Override\n   protected long getMinimumMultipartBlobSize() {\n      return 1;\n   }\n\n   @Override\n   protected void checkTier(BlobMetadata metadata, Tier expected) {\n      // Swift maps all tiers to STANDARD\n      assertThat(metadata.getTier()).isEqualTo(Tier.STANDARD);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/blobstore/integration/SwiftBlobLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.blobstore.integration;\n\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.CREDENTIAL_TYPE;\n\nimport java.util.Properties;\n\nimport org.jclouds.blobstore.integration.internal.BaseBlobLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"SwiftBlobLiveTest\")\npublic class SwiftBlobLiveTest extends BaseBlobLiveTest {\n\n   public SwiftBlobLiveTest() {\n      provider = \"openstack-swift\";\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      setIfTestSystemPropertyPresent(props, CREDENTIAL_TYPE);\n      return props;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/blobstore/integration/SwiftBlobSignerLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.blobstore.integration;\n\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.CREDENTIAL_TYPE;\n\nimport java.util.Properties;\n\nimport org.jclouds.blobstore.integration.internal.BaseBlobSignerLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"SwiftBlobSignerLiveTest\")\npublic class SwiftBlobSignerLiveTest extends BaseBlobSignerLiveTest {\n\n   public SwiftBlobSignerLiveTest() {\n      provider = \"openstack-swift\";\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      setIfTestSystemPropertyPresent(props, CREDENTIAL_TYPE);\n      return props;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/blobstore/integration/SwiftContainerIntegrationLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.blobstore.integration;\n\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.CREDENTIAL_TYPE;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Properties;\n\nimport org.jclouds.blobstore.integration.internal.BaseContainerIntegrationTest;\nimport org.testng.SkipException;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"SwiftContainerIntegrationLiveTest\")\npublic class SwiftContainerIntegrationLiveTest extends BaseContainerIntegrationTest {\n\n   public SwiftContainerIntegrationLiveTest() {\n      provider = \"openstack-swift\";\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      setIfTestSystemPropertyPresent(props, CREDENTIAL_TYPE);\n      return props;\n   }\n\n   @Override\n   public void testListRootUsesDelimiter() throws InterruptedException {\n      try {\n         super.testListRootUsesDelimiter();\n      } catch (AssertionError e) {\n         // swift doesn't have the \"common prefixes\" in the response that s3\n         // does. If we wanted this to pass, we'd need to create\n         // pseudo-directories implicitly, which is costly and troublesome. It\n         // is better to fail this assertion.\n         assertTrue(e.getMessage().matches(\".*16.* but .*15.*\"), e.getMessage());\n         // ^^ squishy regex to deal with various formats of testng messages.\n      }\n   }\n\n   @Override\n   public void testDirectory() {\n      // The test fails with swift, where the marker blob for the directory is removed, as part of the call to\n      // clearContainer\n      throw new SkipException(\"Swift marker blob is removed when clearing a directory\");\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/blobstore/integration/SwiftContainerLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.blobstore.integration;\n\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.CREDENTIAL_TYPE;\n\nimport java.util.Properties;\n\nimport org.jclouds.blobstore.integration.internal.BaseContainerLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"SwiftContainerLiveTest\")\npublic class SwiftContainerLiveTest extends BaseContainerLiveTest {\n\n   public SwiftContainerLiveTest() {\n      provider = \"openstack-swift\";\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      setIfTestSystemPropertyPresent(props, CREDENTIAL_TYPE);\n      return props;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/blobstore/integration/SwiftServiceIntegrationLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.blobstore.integration;\n\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.CREDENTIAL_TYPE;\n\nimport java.util.Properties;\n\nimport org.jclouds.blobstore.integration.internal.BaseServiceIntegrationTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"SwiftServiceIntegrationLiveTest\")\npublic class SwiftServiceIntegrationLiveTest extends BaseServiceIntegrationTest {\n\n   public SwiftServiceIntegrationLiveTest() {\n      provider = \"openstack-swift\";\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      setIfTestSystemPropertyPresent(props, CREDENTIAL_TYPE);\n      return props;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/config/SwiftTypeAdaptersTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.config;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.openstack.swift.v1.config.SwiftTypeAdapters.BulkDeleteResponseAdapter;\nimport org.jclouds.openstack.swift.v1.config.SwiftTypeAdapters.ExtractArchiveResponseAdapter;\nimport org.jclouds.openstack.swift.v1.domain.BulkDeleteResponse;\nimport org.jclouds.openstack.swift.v1.domain.ExtractArchiveResponse;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.gson.Gson;\nimport com.google.gson.GsonBuilder;\n\n@Test\npublic class SwiftTypeAdaptersTest {\n   Gson gson = new GsonBuilder()\n         .registerTypeAdapter(ExtractArchiveResponse.class, new ExtractArchiveResponseAdapter())\n         .registerTypeAdapter(BulkDeleteResponse.class, new BulkDeleteResponseAdapter())\n         .create();\n\n   public void extractArchiveWithoutErrors() {\n      assertEquals(gson.fromJson(\"\"\n            + \"{\\n\"\n            + \"  \\\"Response Status\\\": \\\"201 Created\\\",\\n\"\n            + \"  \\\"Response Body\\\": \\\"\\\",\\n\"\n            + \"  \\\"Errors\\\": [],\\n\"\n            + \"  \\\"Number Files Created\\\": 10\\n\"\n            + \"}\", ExtractArchiveResponse.class), ExtractArchiveResponse.create(10, ImmutableMap.<String, String> of()));\n   }\n\n   public void extractArchiveWithErrorsAndDecodesPaths() {\n      assertEquals(\n            gson.fromJson(\"\"\n                  + \"{\\n\"\n                  + \"  \\\"Response Status\\\": \\\"201 Created\\\",\\n\"\n                  + \"  \\\"Response Body\\\": \\\"\\\",\\n\"\n                  + \"  \\\"Errors\\\": [\\n\"\n                  + \"    [\\\"/v1/12345678912345/mycontainer/home/xx%3Cyy\\\", \\\"400 Bad Request\\\"],\\n\"\n                  + \"    [\\\"/v1/12345678912345/mycontainer/../image.gif\\\", \\\"400 Bad Request\\\"]\\n\"\n                  + \"  ],\\n\"\n                  + \"  \\\"Number Files Created\\\": 8\\n\"\n                  + \"}\", ExtractArchiveResponse.class),\n            ExtractArchiveResponse.create(\n                  8,\n                  ImmutableMap.<String, String> builder()\n                        .put(\"/v1/12345678912345/mycontainer/home/xx<yy\", \"400 Bad Request\")\n                        .put(\"/v1/12345678912345/mycontainer/../image.gif\", \"400 Bad Request\").build()));\n   }\n\n   public void bulkDeleteWithoutErrors() {\n      assertEquals(gson.fromJson(\"\"\n            + \"{\\n\"\n            + \"  \\\"Response Status\\\": \\\"200 OK\\\",\\n\"\n            + \"  \\\"Response Body\\\": \\\"\\\",\\n\"\n            + \"  \\\"Errors\\\": [],\\n\"\n            + \"  \\\"Number Not Found\\\": 1,\\n\"\n            + \"  \\\"Number Deleted\\\": 9\\n\"\n            + \"}\", BulkDeleteResponse.class), BulkDeleteResponse.create(9, 1, ImmutableMap.<String, String> of()));\n   }\n\n   public void bulkDeleteWithErrorsAndDecodesPaths() {\n      assertEquals(gson.fromJson(\"\"\n            + \"{\\n\"\n            + \"  \\\"Response Status\\\": \\\"400 Bad Request\\\",\\n\"\n            + \"  \\\"Response Body\\\": \\\"\\\",\\n\"\n            + \"  \\\"Errors\\\": [\\n\"\n            + \"    [\\\"/v1/12345678912345/Not%20Empty\\\", \\\"409 Conflict\\\"]\"\n            + \"  ],\\n\"\n            + \"  \\\"Number Deleted\\\": 0\\n\"\n            + \"}\", BulkDeleteResponse.class),\n            BulkDeleteResponse.create(0, 0, ImmutableMap.of(\"/v1/12345678912345/Not Empty\", \"409 Conflict\")));\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/features/AccountApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.UUID;\n\nimport org.jclouds.openstack.swift.v1.domain.Account;\nimport org.jclouds.openstack.swift.v1.internal.BaseSwiftApiLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\n\n@Test(groups = \"live\", testName = \"AccountApiLiveTest\")\npublic class AccountApiLiveTest extends BaseSwiftApiLiveTest {\n\n   public void testGet() throws Exception {\n      for (String regionId : regions) {\n         AccountApi accountApi = getApi().getAccountApi(regionId);\n         Account account = accountApi.get();\n\n         assertNotNull(account);\n         assertTrue(account.getContainerCount() >= 0);\n         assertTrue(account.getObjectCount() >= 0);\n         assertTrue(account.getBytesUsed() >= 0);\n      }\n   }\n\n   public void testUpdateMetadata() throws Exception {\n      for (String regionId : regions) {\n         AccountApi accountApi = getApi().getAccountApi(regionId);\n\n         Map<String, String> meta = ImmutableMap.of(\"MyAdd1\", \"foo\", \"MyAdd2\", \"bar\");\n\n         accountApi.updateMetadata(meta);\n\n         accountHasMetadata(accountApi, meta);\n      }\n   }\n\n   public void testDeleteMetadata() throws Exception {\n      for (String regionId : regions) {\n         AccountApi accountApi = getApi().getAccountApi(regionId);\n\n         Map<String, String> meta = ImmutableMap.of(\"MyDelete1\", \"foo\", \"MyDelete2\", \"bar\");\n\n         accountApi.updateMetadata(meta);\n         accountHasMetadata(accountApi, meta);\n\n         assertTrue(accountApi.deleteMetadata(meta));\n         Account account = accountApi.get();\n         for (Entry<String, String> entry : meta.entrySet()) {\n            // note keys are returned in lower-case!\n            assertFalse(account.getMetadata().containsKey(entry.getKey().toLowerCase()));\n         }\n      }\n   }\n\n   static void accountHasMetadata(AccountApi accountApi, Map<String, String> meta) {\n      Account account = accountApi.get();\n      for (Entry<String, String> entry : meta.entrySet()) {\n         // note keys are returned in lower-case!\n         assertEquals(account.getMetadata().get(entry.getKey().toLowerCase()), entry.getValue(),\n               account + \" didn't have metadata: \" + entry);\n      }\n   }\n\n   public void testUpdateTemporaryUrlKey() throws Exception {\n      for (String regionId : regions) {\n         AccountApi accountApi = getApi().getAccountApi(regionId);\n\n         String key = UUID.randomUUID().toString();\n\n         accountApi.updateTemporaryUrlKey(key);\n\n         assertTrue(accountApi.get().getMetadata().containsKey(\"temp-url-key\"));\n         assertTrue(accountApi.get().getMetadata().get(\"temp-url-key\").equals(key));\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/features/AccountApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.features;\n\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.ACCOUNT_BYTES_USED;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.ACCOUNT_CONTAINER_COUNT;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.ACCOUNT_METADATA_PREFIX;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.ACCOUNT_OBJECT_COUNT;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.ACCOUNT_REMOVE_METADATA_PREFIX;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.ACCOUNT_TEMPORARY_URL_KEY;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Map;\nimport java.util.Map.Entry;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\nimport okhttp3.mockwebserver.RecordedRequest;\n\nimport org.jclouds.openstack.swift.v1.SwiftApi;\nimport org.jclouds.openstack.swift.v1.domain.Account;\nimport org.jclouds.openstack.v2_0.internal.BaseOpenStackMockTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\n\n\n@Test(groups = \"unit\", testName = \"AccountApiMockTest\")\npublic class AccountApiMockTest extends BaseOpenStackMockTest<SwiftApi> {\n\n   /** upper-cases first char, and lower-cases rest!! **/\n   public void getKnowingServerMessesWithMetadataKeyCaseFormat() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(accountResponse()\n            // note silly casing\n            .addHeader(ACCOUNT_METADATA_PREFIX + \"Apiname\", \"swift\")\n            .addHeader(ACCOUNT_METADATA_PREFIX + \"Apiversion\", \"v1.1\")));\n\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         Account account = api.getAccountApi(\"DFW\").get();\n         assertEquals(account.getContainerCount(), 3L);\n         assertEquals(account.getObjectCount(), 42L);\n         assertEquals(account.getBytesUsed(), 323479L);\n         for (Entry<String, String> entry : metadata.entrySet()) {\n            assertEquals(account.getMetadata().get(entry.getKey().toLowerCase()), entry.getValue());\n         }\n\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"HEAD\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void updateMetadata() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(accountResponse()\n            .addHeader(ACCOUNT_METADATA_PREFIX + \"ApiName\", \"swift\")\n            .addHeader(ACCOUNT_METADATA_PREFIX + \"ApiVersion\", \"v1.1\")));\n\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         api.getAccountApi(\"DFW\").updateMetadata(metadata);\n\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n\n         RecordedRequest replaceRequest = server.takeRequest();\n         assertRequest(replaceRequest, \"POST\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\");\n         for (Entry<String, String> entry : metadata.entrySet()) {\n            assertEquals(replaceRequest.getHeader(ACCOUNT_METADATA_PREFIX + entry.getKey().toLowerCase()), entry.getValue());\n         }\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void updateTemporaryUrlKey() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(accountResponse()));\n\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         api.getAccountApi(\"DFW\").updateTemporaryUrlKey(\"foobar\");\n\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n\n         RecordedRequest replaceRequest = server.takeRequest();\n         assertRequest(replaceRequest, \"POST\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\");\n         assertEquals(replaceRequest.getHeader(ACCOUNT_TEMPORARY_URL_KEY), \"foobar\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void deleteMetadata() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(accountResponse()));\n\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         assertTrue(api.getAccountApi(\"DFW\").deleteMetadata(metadata));\n\n         assertEquals(server.getRequestCount(), 2);\n         assertEquals(server.takeRequest().getRequestLine(), \"POST /tokens HTTP/1.1\");\n         RecordedRequest deleteRequest = server.takeRequest();\n         assertEquals(deleteRequest.getRequestLine(),\n               \"POST /v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9 HTTP/1.1\");\n         for (String key : metadata.keySet()) {\n            assertEquals(deleteRequest.getHeader(ACCOUNT_REMOVE_METADATA_PREFIX + key.toLowerCase()), \"ignored\");\n         }\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   private static final Map<String, String> metadata = ImmutableMap.of(\"ApiName\", \"swift\", \"ApiVersion\", \"v1.1\");\n\n   public static MockResponse accountResponse() {\n      return new MockResponse()\n            .addHeader(ACCOUNT_CONTAINER_COUNT, \"3\")\n            .addHeader(ACCOUNT_OBJECT_COUNT, \"42\")\n            .addHeader(ACCOUNT_BYTES_USED, \"323479\");\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/features/BulkApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.util.List;\nimport java.util.UUID;\n\nimport org.jboss.shrinkwrap.api.GenericArchive;\nimport org.jboss.shrinkwrap.api.ShrinkWrap;\nimport org.jboss.shrinkwrap.api.asset.StringAsset;\nimport org.jboss.shrinkwrap.api.exporter.TarGzExporter;\nimport org.jclouds.io.ByteStreams2;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.payloads.ByteSourcePayload;\nimport org.jclouds.openstack.swift.v1.domain.BulkDeleteResponse;\nimport org.jclouds.openstack.swift.v1.domain.ExtractArchiveResponse;\nimport org.jclouds.openstack.swift.v1.internal.BaseSwiftApiLiveTest;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Throwables;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Lists;\nimport com.google.common.io.ByteSource;\n\n@Test(groups = \"live\", testName = \"BulkApiLiveTest\")\npublic class BulkApiLiveTest extends BaseSwiftApiLiveTest {\n\n   private static final int OBJECT_COUNT = 10;\n   private String containerName = getClass().getSimpleName();\n   List<String> paths = Lists.newArrayList();\n   byte[] tarGz;\n\n   public void testNotPresentWhenDeleting() throws Exception {\n      for (String regionId : regions) {\n         BulkDeleteResponse deleteResponse = getApi().getBulkApi(regionId).bulkDelete(\n               ImmutableList.of(UUID.randomUUID().toString()));\n         assertEquals(deleteResponse.getDeleted(), 0);\n         assertEquals(deleteResponse.getNotFound(), 1);\n         assertTrue(deleteResponse.getErrors().isEmpty());\n      }\n   }\n\n   public void testExtractArchive() throws Exception {\n      for (String regionId : regions) {\n         Payload payload = new ByteSourcePayload(ByteSource.wrap(tarGz));\n\n         ExtractArchiveResponse extractResponse = getApi().getBulkApi(regionId)\n                                                     .extractArchive(containerName, payload, \"tar.gz\");\n         assertEquals(extractResponse.getCreated(), OBJECT_COUNT);\n         assertTrue(extractResponse.getErrors().isEmpty());\n         assertEquals(getApi().getContainerApi(regionId).get(containerName).getObjectCount(), Long.valueOf(OBJECT_COUNT));\n\n         // repeat the command\n         extractResponse = getApi().getBulkApi(regionId).extractArchive(containerName, payload, \"tar.gz\");\n         assertEquals(extractResponse.getCreated(), OBJECT_COUNT);\n         assertTrue(extractResponse.getErrors().isEmpty());\n      }\n   }\n\n   @Test(dependsOnMethods = \"testExtractArchive\")\n   public void testBulkDelete() throws Exception {\n      for (String regionId : regions) {\n         BulkDeleteResponse deleteResponse = getApi().getBulkApi(regionId).bulkDelete(paths);\n         assertEquals(deleteResponse.getDeleted(), OBJECT_COUNT);\n         assertEquals(deleteResponse.getNotFound(), 0);\n         assertTrue(deleteResponse.getErrors().isEmpty());\n         assertEquals(getApi().getContainerApi(regionId).get(containerName).getObjectCount(), Long.valueOf(0));\n      }\n   }\n\n   @Override\n   @BeforeClass(groups = \"live\")\n   public void setup() {\n      super.setup();\n      for (String regionId : regions) {\n         boolean created = getApi().getContainerApi(regionId).create(containerName);\n         if (!created) {\n            deleteAllObjectsInContainer(regionId, containerName);\n         }\n      }\n      GenericArchive files = ShrinkWrap.create(GenericArchive.class, \"files.tar.gz\");\n      StringAsset content = new StringAsset(\"foo\");\n      for (int i = 0; i < OBJECT_COUNT; i++) {\n         paths.add(containerName + \"/file\" + i);\n         files.add(content, \"/file\" + i);\n      }\n\n      try {\n         tarGz = ByteStreams2.toByteArrayAndClose(files.as(TarGzExporter.class).exportAsInputStream());\n      } catch (IOException e) {\n         throw Throwables.propagate(e);\n      }\n   }\n\n   @AfterClass(groups = \"live\")\n   public void tearDown() {\n      for (String regionId : regions) {\n         deleteAllObjectsInContainer(regionId, containerName);\n         getApi().getContainerApi(regionId).deleteIfEmpty(containerName);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/features/BulkApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\nimport okhttp3.mockwebserver.RecordedRequest;\n\nimport org.jboss.shrinkwrap.api.GenericArchive;\nimport org.jboss.shrinkwrap.api.ShrinkWrap;\nimport org.jboss.shrinkwrap.api.asset.StringAsset;\nimport org.jboss.shrinkwrap.api.exporter.TarGzExporter;\nimport org.jclouds.io.ByteStreams2;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.openstack.swift.v1.SwiftApi;\nimport org.jclouds.openstack.swift.v1.domain.ExtractArchiveResponse;\nimport org.jclouds.openstack.v2_0.internal.BaseOpenStackMockTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.io.ByteSource;\n\n\n@Test(groups = \"unit\", testName = \"BulkApiMockTest\")\npublic class BulkApiMockTest extends BaseOpenStackMockTest<SwiftApi> {\n\n   public void testExtractArchive() throws Exception {\n      GenericArchive files = ShrinkWrap.create(GenericArchive.class, \"files.tar.gz\");\n      StringAsset content = new StringAsset(\"foo\");\n      for (int i = 0; i < 10; i++) {\n         files.add(content, \"/file\" + i);\n      }\n\n      byte[] tarGz = ByteStreams2.toByteArrayAndClose(files.as(TarGzExporter.class).exportAsInputStream());\n\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(201).setBody(\"{\\\"Number Files Created\\\": 10, \\\"Errors\\\": []}\")));\n\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         Payload payload = Payloads.newByteSourcePayload(ByteSource.wrap(tarGz));\n         ExtractArchiveResponse response = api.getBulkApi(\"DFW\").extractArchive(\"myContainer\", payload, \"tar.gz\");\n\n         assertEquals(response.getCreated(), 10);\n         assertTrue(response.getErrors().isEmpty());\n\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         RecordedRequest extractRequest = server.takeRequest();\n         assertRequest(extractRequest, \"PUT\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/myContainer?extract-archive=tar.gz\");\n         assertEquals(extractRequest.getBody().readByteArray(), tarGz);\n      } finally {\n         server.shutdown();\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/features/ContainerApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.features;\n\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Map;\nimport java.util.Map.Entry;\n\nimport org.jclouds.openstack.swift.v1.domain.Container;\nimport org.jclouds.openstack.swift.v1.internal.BaseSwiftApiLiveTest;\nimport org.jclouds.openstack.swift.v1.options.CreateContainerOptions;\nimport org.jclouds.openstack.swift.v1.options.ListContainerOptions;\nimport org.jclouds.openstack.swift.v1.options.UpdateContainerOptions;\nimport org.jclouds.openstack.swift.v1.reference.SwiftHeaders;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMultimap;\n\n/**\n * Provides live tests for the {@link ContainerApi}.\n */\n@Test(groups = \"live\", testName = \"ContainerApiLiveTest\", singleThreaded = true)\npublic class ContainerApiLiveTest extends BaseSwiftApiLiveTest {\n\n   private String name = getClass().getSimpleName();\n\n   public void testCreateWithOptions() throws Exception {\n      for (String regionId : regions) {\n         ImmutableMultimap<String, String> headers =\n               ImmutableMultimap.of(SwiftHeaders.STATIC_WEB_INDEX, \"__index.html\",\n                                    SwiftHeaders.STATIC_WEB_ERROR, \"__error.html\");\n         CreateContainerOptions opts = new CreateContainerOptions().headers(headers);\n\n         assertNotNull(getApi().getContainerApi(regionId).create(name, opts));\n\n         Container container = getApi().getContainerApi(regionId).get(name);\n         assertNotNull(container);\n         assertEquals(container.getName(), name);\n         assertEquals(container.getMetadata().size(), 2);\n         assertEquals(container.getMetadata().get(\"web-index\"), \"__index.html\");\n         assertEquals(container.getMetadata().get(\"web-error\"), \"__error.html\");\n\n         assertTrue(getApi().getContainerApi(regionId).deleteIfEmpty(name));\n         assertTrue(getApi().getContainerApi(regionId).create(name));\n      }\n   }\n\n   public void testCreateWithSpacesAndSpecialCharacters() throws Exception {\n      final String nameWithSpaces = \"container # ! special\";\n\n      for (String regionId : regions) {\n         assertTrue(getApi().getContainerApi(regionId).create(nameWithSpaces));\n         Container container = getApi().getContainerApi(regionId).get(nameWithSpaces);\n         assertNotNull(container);\n         assertEquals(container.getName(), nameWithSpaces);\n\n         assertTrue(getApi().getContainerApi(regionId).deleteIfEmpty(nameWithSpaces));\n      }\n   }\n\n   public void testList() throws Exception {\n      for (String regionId : regions) {\n         ContainerApi containerApi = getApi().getContainerApi(regionId);\n         FluentIterable<Container> response = containerApi.list();\n         assertNotNull(response);\n         for (Container container : response) {\n            assertNotNull(container.getName());\n            assertTrue(container.getObjectCount() >= 0);\n            assertTrue(container.getBytesUsed() >= 0);\n         }\n      }\n   }\n\n   public void testListWithOptions() throws Exception {\n      String lexicographicallyBeforeName = name.substring(0, name.length() - 1);\n      for (String regionId : regions) {\n         ListContainerOptions options = ListContainerOptions.Builder.marker(lexicographicallyBeforeName);\n         Container container = getApi().getContainerApi(regionId).list(options).firstMatch(new Predicate<Container>() {\n            @Override\n            public boolean apply(Container container) {\n               return container.getName().equals(name);\n            }\n         }).get();\n         assertTrue(container.getObjectCount() == 0);\n         assertTrue(container.getBytesUsed() == 0);\n      }\n   }\n\n   public void testUpdate() throws Exception {\n      for (String regionId : regions) {\n         ImmutableMultimap<String, String> headers =\n               ImmutableMultimap.of(SwiftHeaders.STATIC_WEB_INDEX, \"__index.html\",\n                                    SwiftHeaders.STATIC_WEB_ERROR, \"__error.html\");\n         UpdateContainerOptions opts = new UpdateContainerOptions().headers(headers);\n\n         assertNotNull(getApi().getContainerApi(regionId).create(name));\n\n         Container container = getApi().getContainerApi(regionId).get(name);\n         assertNotNull(container);\n         assertEquals(container.getName(), name);\n         assertTrue(container.getMetadata().isEmpty());\n\n         getApi().getContainerApi(regionId).update(name, opts);\n\n         Container updatedContainer = getApi().getContainerApi(regionId).get(name);\n         assertNotNull(updatedContainer);\n         assertEquals(updatedContainer.getName(), name);\n         assertEquals(updatedContainer.getMetadata().size(), 2);\n         assertEquals(updatedContainer.getMetadata().get(\"web-index\"), \"__index.html\");\n         assertEquals(updatedContainer.getMetadata().get(\"web-error\"), \"__error.html\");\n\n         assertTrue(getApi().getContainerApi(regionId).deleteIfEmpty(name));\n         assertTrue(getApi().getContainerApi(regionId).create(name));\n      }\n   }\n\n   public void testUpdateContainer() throws Exception {\n      for (String regionId : regions) {\n         ContainerApi containerApi = getApi().getContainerApi(regionId);\n         // The container should exist, as it was created in the setup() method\n         assertThat(containerApi.get(name).getAnybodyRead().get()).isFalse();\n\n         containerApi.update(name, new UpdateContainerOptions().anybodyRead());\n         assertThat(containerApi.get(name).getAnybodyRead().get()).isTrue();\n\n         assertThat(containerApi.deleteIfEmpty(name)).isTrue();\n         assertThat(containerApi.create(name)).isTrue();\n      }\n   }\n\n   public void testGet() throws Exception {\n      for (String regionId : regions) {\n         Container container = getApi().getContainerApi(regionId).get(name);\n         assertEquals(container.getName(), name);\n         assertTrue(container.getObjectCount() == 0);\n         assertTrue(container.getBytesUsed() == 0);\n      }\n   }\n\n   public void testUpdateMetadata() throws Exception {\n      Map<String, String> meta = ImmutableMap.of(\"MyAdd1\", \"foo\", \"MyAdd2\", \"bar\");\n\n      for (String regionId : regions) {\n         ContainerApi containerApi = getApi().getContainerApi(regionId);\n         containerApi.updateMetadata(name, meta);\n         containerHasMetadata(containerApi, name, meta);\n      }\n   }\n\n   public void testDeleteMetadata() throws Exception {\n      Map<String, String> meta = ImmutableMap.of(\"MyDelete1\", \"foo\", \"MyDelete2\", \"bar\");\n\n      for (String regionId : regions) {\n         ContainerApi containerApi = getApi().getContainerApi(regionId);\n         // update\n         containerApi.updateMetadata(name, meta);\n         containerHasMetadata(containerApi, name, meta);\n         // delete\n         assertTrue(containerApi.deleteMetadata(name, meta));\n         Container container = containerApi.get(name);\n         for (Entry<String, String> entry : meta.entrySet()) {\n            // note keys are returned in lower-case!\n            assertFalse(container.getMetadata().containsKey(entry.getKey().toLowerCase()));\n         }\n      }\n   }\n\n   static void containerHasMetadata(ContainerApi containerApi, String name, Map<String, String> meta) {\n      Container container = containerApi.get(name);\n      for (Entry<String, String> entry : meta.entrySet()) {\n         // note keys are returned in lower-case!\n         assertEquals(container.getMetadata().get(entry.getKey().toLowerCase()), entry.getValue(),\n               container + \" didn't have metadata: \" + entry);\n      }\n   }\n\n   @Override\n   @BeforeClass(groups = \"live\")\n   public void setup() {\n      super.setup();\n      for (String regionId : regions) {\n         getApi().getContainerApi(regionId).create(name);\n      }\n   }\n\n   @AfterClass(groups = \"live\")\n   public void tearDown() {\n      for (String regionId : regions) {\n         getApi().getContainerApi(regionId).deleteIfEmpty(name);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/features/ContainerApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.features;\n\nimport static org.jclouds.openstack.swift.v1.options.CreateContainerOptions.Builder.anybodyRead;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.CONTAINER_ACL_ANYBODY_READ;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.CONTAINER_BYTES_USED;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.CONTAINER_METADATA_PREFIX;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.CONTAINER_OBJECT_COUNT;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.CONTAINER_READ;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.CONTAINER_REMOVE_METADATA_PREFIX;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Map;\nimport java.util.Map.Entry;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\nimport okhttp3.mockwebserver.RecordedRequest;\n\nimport org.jclouds.blobstore.ContainerNotFoundException;\nimport org.jclouds.openstack.swift.v1.SwiftApi;\nimport org.jclouds.openstack.swift.v1.domain.Container;\nimport org.jclouds.openstack.swift.v1.options.ListContainerOptions;\nimport org.jclouds.openstack.v2_0.internal.BaseOpenStackMockTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\n\n\n@Test(groups = \"unit\", testName = \"ContainerApiMockTest\")\npublic class ContainerApiMockTest extends BaseOpenStackMockTest<SwiftApi> {\n\n   public void testList() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/container_list.json\"))));\n\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         ImmutableList<Container> containers = api.getContainerApi(\"DFW\").list().toList();\n         assertEquals(containers, ImmutableList.of(\n               Container.builder()\n                     .name(\"test_container_1\")\n                     .objectCount(2L)\n                     .bytesUsed(78L).build(),\n               Container.builder()\n                     .name(\"test_container_2\")\n                     .objectCount(1L)\n                     .bytesUsed(17L).build()));\n\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"GET\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9?format=json\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testListWithOptions() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/container_list.json\"))));\n\n      ListContainerOptions options = ListContainerOptions.Builder.marker(\"test\");\n      assertNotNull(options);\n\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         ImmutableList<Container> containers = api.getContainerApi(\"DFW\").list(options).toList();\n         assertEquals(containers, ImmutableList.of(\n               Container.builder()\n                     .name(\"test_container_1\")\n                     .objectCount(2L)\n                     .bytesUsed(78L).build(),\n               Container.builder()\n                     .name(\"test_container_2\")\n                     .objectCount(1L)\n                     .bytesUsed(17L).build()));\n\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"GET\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9?format=json&marker=test\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testContainerExists() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(201)));\n      server.enqueue(addCommonHeaders(containerResponse()\n            .addHeader(CONTAINER_METADATA_PREFIX + \"ApiName\", \"swift\")\n            .addHeader(CONTAINER_METADATA_PREFIX + \"ApiVersion\", \"v1.1\")));\n\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         assertTrue(api.getContainerApi(\"DFW\").create(\"myContainer\", anybodyRead().metadata(metadata)));\n\n         Container container = api.getContainerApi(\"DFW\").get(\"myContainer\");\n         assertEquals(container.getName(), \"myContainer\");\n         assertEquals(container.getObjectCount(), Long.valueOf(42L));\n         assertEquals(container.getBytesUsed(), Long.valueOf(323479L));\n         for (Entry<String, String> entry : container.getMetadata().entrySet()) {\n            assertEquals(container.getMetadata().get(entry.getKey().toLowerCase()), entry.getValue());\n         }\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"PUT\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/myContainer\");\n         assertRequest(server.takeRequest(), \"HEAD\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/myContainer\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   @Test(expectedExceptions = ContainerNotFoundException.class)\n   public void testContainerDoesNotExist() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(404)));\n\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         assertTrue(api.getContainerApi(\"DFW\").create(\"myContainer\", anybodyRead().metadata(metadata)));\n\n         // the head call will throw the ContainerNotFoundException\n         api.getContainerApi(\"DFW\").get(\"myContainer\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testCreate() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(201)));\n\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         assertTrue(api.getContainerApi(\"DFW\").create(\"myContainer\"));\n\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"PUT\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/myContainer\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testCreateWithOptions() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(201)));\n\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         assertTrue(api.getContainerApi(\"DFW\").create(\"myContainer\", anybodyRead().metadata(metadata)));\n\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n\n         RecordedRequest createRequest = server.takeRequest();\n         assertRequest(createRequest, \"PUT\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/myContainer\");\n\n         assertEquals(createRequest.getHeader(CONTAINER_READ), CONTAINER_ACL_ANYBODY_READ);\n\n         for (Entry<String, String> entry : metadata.entrySet()) {\n            assertEquals(createRequest.getHeader(CONTAINER_METADATA_PREFIX + entry.getKey().toLowerCase()), entry.getValue());\n         }\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testCreateWithSpacesAndSpecialCharacters() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(201)));\n\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         assertTrue(api.getContainerApi(\"DFW\").create(\"container # ! special\"));\n\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"PUT\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/container%20%23%20%21%20special\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testAlreadyCreated() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(202)));\n\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         assertFalse(api.getContainerApi(\"DFW\").create(\"myContainer\"));\n\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"PUT\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/myContainer\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   /** upper-cases first char, and lower-cases rest!! **/\n   public void testGetKnowingServerMessesWithMetadataKeyCaseFormat() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(containerResponse()\n            // note silly casing\n            .addHeader(CONTAINER_METADATA_PREFIX + \"Apiname\", \"swift\")\n            .addHeader(CONTAINER_METADATA_PREFIX + \"Apiversion\", \"v1.1\")));\n\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         Container container = api.getContainerApi(\"DFW\").get(\"myContainer\");\n         assertEquals(container.getName(), \"myContainer\");\n         assertEquals(container.getObjectCount(), Long.valueOf(42L));\n         assertEquals(container.getBytesUsed(), Long.valueOf(323479L));\n         for (Entry<String, String> entry : container.getMetadata().entrySet()) {\n            assertEquals(container.getMetadata().get(entry.getKey().toLowerCase()), entry.getValue());\n         }\n\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"HEAD\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/myContainer\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testUpdateMetadata() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(containerResponse()\n            .addHeader(CONTAINER_METADATA_PREFIX + \"ApiName\", \"swift\")\n            .addHeader(CONTAINER_METADATA_PREFIX + \"ApiVersion\", \"v1.1\")));\n\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         api.getContainerApi(\"DFW\").updateMetadata(\"myContainer\", metadata);\n\n         assertEquals(server.getRequestCount(), 2);\n         assertEquals(server.takeRequest().getRequestLine(), \"POST /tokens HTTP/1.1\");\n         RecordedRequest replaceRequest = server.takeRequest();\n         assertEquals(replaceRequest.getRequestLine(),\n               \"POST /v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/myContainer HTTP/1.1\");\n         for (Entry<String, String> entry : metadata.entrySet()) {\n            assertEquals(replaceRequest.getHeader(CONTAINER_METADATA_PREFIX + entry.getKey().toLowerCase()), entry.getValue());\n         }\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testDeleteMetadata() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(containerResponse()));\n\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         assertTrue(api.getContainerApi(\"DFW\").deleteMetadata(\"myContainer\", metadata));\n\n         assertEquals(server.getRequestCount(), 2);\n         assertEquals(server.takeRequest().getRequestLine(), \"POST /tokens HTTP/1.1\");\n         RecordedRequest deleteRequest = server.takeRequest();\n         assertEquals(deleteRequest.getRequestLine(),\n               \"POST /v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/myContainer HTTP/1.1\");\n         for (String key : metadata.keySet()) {\n            assertEquals(deleteRequest.getHeader(CONTAINER_REMOVE_METADATA_PREFIX + key.toLowerCase()), \"ignored\");\n         }\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testDeleteIfEmpty() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(204)));\n\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         assertTrue(api.getContainerApi(\"DFW\").deleteIfEmpty(\"myContainer\"));\n\n         assertEquals(server.getRequestCount(), 2);\n         assertEquals(server.takeRequest().getRequestLine(), \"POST /tokens HTTP/1.1\");\n         RecordedRequest deleteRequest = server.takeRequest();\n         assertEquals(deleteRequest.getRequestLine(),\n               \"DELETE /v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/myContainer HTTP/1.1\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testDeleteWhenNotEmpty() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(409)));\n\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         assertFalse(api.getContainerApi(\"DFW\").deleteIfEmpty(\"myContainer\"));\n\n      } finally {\n         assertEquals(server.getRequestCount(), 2);\n         assertEquals(server.takeRequest().getRequestLine(), \"POST /tokens HTTP/1.1\");\n         RecordedRequest deleteRequest = server.takeRequest();\n         assertEquals(deleteRequest.getRequestLine(),\n               \"DELETE /v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/myContainer HTTP/1.1\");\n         server.shutdown();\n      }\n   }\n\n   private static final Map<String, String> metadata = ImmutableMap.of(\"ApiName\", \"swift\", \"ApiVersion\", \"v1.1\");\n\n   static MockResponse containerResponse() {\n      return new MockResponse()\n            .addHeader(CONTAINER_OBJECT_COUNT, \"42\")\n            .addHeader(CONTAINER_BYTES_USED, \"323479\");\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/features/CreatePublicContainerLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.features;\n\nimport static org.jclouds.openstack.swift.v1.options.CreateContainerOptions.Builder.anybodyRead;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.openstack.swift.v1.internal.BaseSwiftApiLiveTest;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"CreatePublicContainerLiveTest\")\npublic class CreatePublicContainerLiveTest extends BaseSwiftApiLiveTest {\n\n   private String name = getClass().getSimpleName();\n\n   public void testAnybodyReadUpdatesMetadata() throws Exception {\n      for (String regionId : getApi().getConfiguredRegions()) {\n         getApi().getContainerApi(regionId).create(name, anybodyRead());\n         assertTrue(getApi().getContainerApi(regionId).get(name).getAnybodyRead().get());\n      }\n   }\n\n   @AfterClass(groups = \"live\")\n   public void tearDown() {\n      for (String regionId : getApi().getConfiguredRegions()) {\n         getApi().getContainerApi(regionId).deleteIfEmpty(name);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/features/DynamicLargeObjectApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.features;\n\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.jclouds.io.Payloads.newByteSourcePayload;\nimport static org.testng.Assert.assertNotNull;\n\nimport org.jclouds.openstack.swift.v1.domain.SwiftObject;\nimport org.jclouds.openstack.swift.v1.internal.BaseSwiftApiLiveTest;\nimport org.jclouds.utils.TestUtils;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.io.ByteSource;\n\n@Test(groups = \"live\", testName = \"DynamicLargeObjectApiLiveTest\", singleThreaded = true)\npublic class DynamicLargeObjectApiLiveTest extends BaseSwiftApiLiveTest {\n\n   private String containerName = getClass().getSimpleName();\n   private static final ByteSource megOf1s = TestUtils.randomByteSource().slice(0, 1024 * 1024);\n   private static final ByteSource megOf2s = TestUtils.randomByteSource().slice(0, 1024 * 1024);\n   private String objectName = \"myObject\";\n   private String name = \"foo\";\n\n   @Override\n   @BeforeClass(groups = \"live\")\n   public void setup() {\n      super.setup();\n      for (String regionId : regions) {\n         getApi().getContainerApi(regionId).create(containerName);\n      }\n   }\n\n   @AfterClass(groups = \"live\")\n   public void tearDown() {\n      for (String regionId : regions) {\n         deleteAllObjectsInContainer(regionId, containerName);\n         getApi().getContainerApi(regionId).deleteIfEmpty(containerName);\n      }\n   }\n\n   @SuppressWarnings(\"deprecation\")\n   @Test\n   protected void assertReplaceManifest() throws Exception {\n      for (String regionId : regions) {\n         ObjectApi objectApi = getApi().getObjectApi(regionId, containerName);\n\n         String etag1s = objectApi.put(name + \"/1\", newByteSourcePayload(megOf1s));\n         awaitConsistency();\n         assertMegabyteAndETagMatches(regionId, containerName, name + \"/1\", etag1s);\n\n         String etag2s = objectApi.put(name + \"/2\", newByteSourcePayload(megOf2s));\n         awaitConsistency();\n         assertMegabyteAndETagMatches(regionId, containerName, name + \"/2\", etag2s);\n\n         awaitConsistency();\n         String etagOfEtags = getApi().getDynamicLargeObjectApi(regionId, containerName).putManifest(name,\n               ImmutableMap.of(\"myfoo\", \"Bar\"));\n\n         assertNotNull(etagOfEtags);\n\n         awaitConsistency();\n\n         SwiftObject bigObject = getApi().getObjectApi(regionId, containerName).get(name);\n         assertThat(bigObject.getPayload().getContentMetadata().getContentLength()).isEqualTo(Long.valueOf(2 * 1024L * 1024L));\n         assertThat(bigObject.getMetadata()).isEqualTo(ImmutableMap.of(\"myfoo\", \"Bar\"));\n         // segments are visible\n         assertThat(getApi().getContainerApi(regionId).get(containerName).getObjectCount()).isEqualTo(Long.valueOf(3));\n      }\n   }\n\n   protected void assertMegabyteAndETagMatches(String regionId, String containerName, String name, String etag1s) {\n      SwiftObject object1s = getApi().getObjectApi(regionId, containerName).get(name);\n      assertThat(object1s.getETag()).isEqualTo(etag1s);\n      assertThat(object1s.getPayload().getContentMetadata().getContentLength()).isEqualTo(Long.valueOf(1024L * 1024L));\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/features/DynamicLargeObjectApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.openstack.swift.v1.features;\n\nimport static com.google.common.net.HttpHeaders.ETAG;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.OBJECT_METADATA_PREFIX;\nimport static org.testng.Assert.assertEquals;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\nimport okhttp3.mockwebserver.RecordedRequest;\n\nimport org.jclouds.io.Payloads;\nimport org.jclouds.openstack.swift.v1.SwiftApi;\nimport org.jclouds.openstack.v2_0.internal.BaseOpenStackMockTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.net.HttpHeaders;\n\n\n@Test(groups = \"unit\", testName = \"DynamicLargeObjectApiMockTest\")\npublic final class DynamicLargeObjectApiMockTest extends BaseOpenStackMockTest<SwiftApi> {\n\n   String containerName = \"myContainer\";\n   String objectName = \"myObjectTest\";\n\n   @SuppressWarnings(\"deprecation\")\n   @Test\n   public void uploadLargeFile() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(new MockResponse().setBody(\"\").addHeader(ETAG, \"89d903bc35dede724fd52c51437ff5fd\"));\n      server.enqueue(new MockResponse().setBody(\"\").addHeader(ETAG, \"d41d8cd98f00b204e9800998ecf8427e\"));\n      server.enqueue(addCommonHeaders(new MockResponse().addHeader(\"X-Object-Manifest\", \"myContainer/myObject\")));\n\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         assertEquals(api.getObjectApi(\"DFW\", containerName).put(objectName.concat(\"1\"), Payloads.newPayload(\"data1\")),\n               \"89d903bc35dede724fd52c51437ff5fd\");\n         assertEquals(api.getDynamicLargeObjectApi(\"DFW\", containerName).putManifest(objectName,\n               ImmutableMap.of(\"MyFoo\", \"Bar\"), ImmutableMap.of(\"MyFoo\", \"Bar\")), \"d41d8cd98f00b204e9800998ecf8427e\");\n\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n\n         RecordedRequest uploadRequest = server.takeRequest();\n         assertEquals(uploadRequest.getRequestLine(),\n               \"PUT /v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/myContainer/myObjectTest1 HTTP/1.1\");\n         assertEquals(uploadRequest.getBody().readUtf8(), \"data1\");\n\n         RecordedRequest uploadRequestManifest = server.takeRequest();\n         assertRequest(uploadRequestManifest, \"PUT\",\n               \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/myContainer/myObjectTest\");\n         assertEquals(uploadRequestManifest.getHeader(OBJECT_METADATA_PREFIX + \"MyFoo\"), \"Bar\");\n\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   @SuppressWarnings(\"deprecation\")\n   public void testReplaceManifest() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().addHeader(HttpHeaders.ETAG, \"\\\"abcd\\\"\")));\n      server.enqueue(addCommonHeaders(new MockResponse().addHeader(\"X-Object-Manifest\", \"myContainer/myObject\")));\n\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         assertEquals(api.getDynamicLargeObjectApi(\"DFW\", \"myContainer\").putManifest(\"myObject\",\n               ImmutableMap.of(\"MyFoo\", \"Bar\"), ImmutableMap.of(\"MyFoo\", \"Bar\")), \"abcd\");\n\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n\n         RecordedRequest replaceRequest = server.takeRequest();\n         assertRequest(replaceRequest, \"PUT\",\n               \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/myContainer/myObject\");\n         assertEquals(replaceRequest.getHeader(OBJECT_METADATA_PREFIX + \"myfoo\"), \"Bar\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   @SuppressWarnings(\"deprecation\")\n   public void testReplaceManifestUnicodeUTF8() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().addHeader(HttpHeaders.ETAG, \"\\\"abcd\\\"\")));\n      server.enqueue(addCommonHeaders(new MockResponse().addHeader(\"X-Object-Manifest\", \"myContainer/myObject\")));\n\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         assertEquals(api.getDynamicLargeObjectApi(\"DFW\", \"myContainer\").putManifest(\"unic₪de\",\n               ImmutableMap.of(\"MyFoo\", \"Bar\"), ImmutableMap.of(\"MyFoo\", \"Bar\")), \"abcd\");\n\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n\n         RecordedRequest replaceRequest = server.takeRequest();\n         assertRequest(replaceRequest, \"PUT\",\n               \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/myContainer/unic%E2%82%AAde\");\n         assertEquals(replaceRequest.getHeader(OBJECT_METADATA_PREFIX + \"myfoo\"), \"Bar\");\n      } finally {\n         server.shutdown();\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/features/ObjectApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.features;\n\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.jclouds.http.options.GetOptions.Builder.tail;\nimport static org.jclouds.io.Payloads.newByteSourcePayload;\nimport static org.jclouds.openstack.swift.v1.options.ListContainerOptions.Builder.marker;\nimport static org.jclouds.util.Strings2.toStringAndClose;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.Assert.fail;\n\nimport java.io.IOException;\nimport java.util.Date;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.concurrent.TimeUnit;\n\nimport org.assertj.core.api.Fail;\nimport org.jclouds.blobstore.KeyNotFoundException;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.http.options.GetOptions;\nimport org.jclouds.io.Payload;\nimport org.jclouds.openstack.swift.v1.domain.ObjectList;\nimport org.jclouds.openstack.swift.v1.domain.SwiftObject;\nimport org.jclouds.openstack.swift.v1.internal.BaseSwiftApiLiveTest;\nimport org.jclouds.openstack.swift.v1.options.CopyOptions;\nimport org.jclouds.openstack.swift.v1.options.ListContainerOptions;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Multimap;\nimport com.google.common.io.ByteSource;\n\n/**\n * Provides live tests for the {@link ObjectApi}.\n */\n@Test(groups = \"live\", testName = \"ObjectApiLiveTest\", singleThreaded = true)\npublic class ObjectApiLiveTest extends BaseSwiftApiLiveTest {\n\n   private String name = getClass().getSimpleName();\n   private String containerName = getClass().getSimpleName() + \"Container\";\n   static final Payload PAYLOAD = newByteSourcePayload(ByteSource.wrap(\"swifty\".getBytes()));\n\n   protected void assertCanCreateReadUpdateDeleteList(String regionId, String containerName, String objectName) throws Exception {\n      assertNotNull(getApi().getContainerApi(regionId).create(containerName));\n      assertNotNull(getApi().getObjectApi(regionId, containerName).put(objectName, PAYLOAD));\n\n      SwiftObject object = getApi().getObjectApi(regionId, containerName).get(objectName);\n      assertEquals(object.getName(), objectName);\n      checkObject(object);\n      assertEquals(toStringAndClose(object.getPayload().openStream()), \"swifty\");\n\n      String lexicographicallyBeforeName = objectName.substring(0, objectName.length() - 1);\n      object = getApi().getObjectApi(regionId, containerName)\n          .list(marker(lexicographicallyBeforeName)).get(0);\n      assertEquals(object.getName(), objectName);\n      checkObject(object);\n\n      getApi().getObjectApi(regionId, containerName).delete(objectName);\n      getApi().getContainerApi(regionId).deleteIfEmpty(containerName);\n   }\n\n   public void testCreateWithSpacesAndSpecialCharacters() throws Exception {\n      final String containerName = \"container # ! special\";\n      final String objectName = \"object # ! special\";\n\n      for (String regionId : regions) {\n         assertCanCreateReadUpdateDeleteList(regionId, containerName, objectName);\n      }\n   }\n\n   public void testCreateAndListWithUnicodeCharacters() throws Exception {\n      final String containerName = \"container-unic₪de\";\n      final String objectName = \"object-unic₪de\";\n\n      for (String regionId : regions) {\n         assertCanCreateReadUpdateDeleteList(regionId, containerName, objectName);\n      }\n   }\n\n   public void testPutWithExpiration() throws Exception {\n      String objectName = \"test-expiration\";\n\n      long expireMillis = new Date().getTime() + 1000 * 60 * 60 * 24;\n      Date expireAt = new Date(expireMillis);\n\n      Payload payload = newByteSourcePayload(ByteSource.wrap(\"swifty\".getBytes()));\n      payload.getContentMetadata().setExpires(expireAt);\n\n      for (String regionId : regions) {\n         String etag = getApi().getObjectApi(regionId, containerName).put(objectName, payload);\n         assertNotNull(etag);\n\n         SwiftObject object = getApi().getObjectApi(regionId, containerName).get(objectName);\n         assertEquals(object.getName(), objectName);\n         checkObject(object);\n         assertEquals(toStringAndClose(object.getPayload().openStream()), \"swifty\");\n\n         getApi().getObjectApi(regionId, containerName).delete(objectName);\n      }\n   }\n\n   public void testCopyObject() throws Exception {\n      for (String regionId : regions) {\n         // source\n         String sourceContainer = \"src\" + containerName;\n         String sourceObjectName = \"original.txt\";\n         String badSource = \"badSource\";\n\n         // destination\n         String destinationContainer = \"dest\" + containerName;\n         String destinationObject = \"copy.txt\";\n         String destinationPath = \"/\" + destinationContainer + \"/\" + destinationObject;\n\n         ContainerApi containerApi = getApi().getContainerApi(regionId);\n\n         // create source and destination dirs\n         containerApi.create(sourceContainer);\n         containerApi.create(destinationContainer);\n\n         // get the api for this region and container\n         ObjectApi srcApi = getApi().getObjectApi(regionId, sourceContainer);\n         ObjectApi destApi = getApi().getObjectApi(regionId, destinationContainer);\n\n         // Create source object\n         assertNotNull(srcApi.put(sourceObjectName, PAYLOAD));\n         SwiftObject sourceObject = srcApi.get(sourceObjectName);\n         checkObject(sourceObject);\n\n         // Create the destination object\n         assertNotNull(destApi.put(destinationObject, PAYLOAD));\n         SwiftObject object = destApi.get(destinationObject);\n         checkObject(object);\n\n         // check the copy operation\n         destApi.copy(destinationObject, sourceContainer, sourceObjectName);\n         assertNotNull(destApi.get(destinationObject));\n\n         // now get a real SwiftObject\n         SwiftObject destSwiftObject = destApi.get(destinationObject);\n         assertEquals(toStringAndClose(destSwiftObject.getPayload().openStream()), \"swifty\");\n\n         // test exception thrown on bad source name\n         try {\n            destApi.copy(destinationObject, badSource, sourceObjectName);\n         } catch (KeyNotFoundException e) {\n            continue;\n         } finally {\n            deleteAllObjectsInContainer(regionId, sourceContainer);\n            containerApi.deleteIfEmpty(sourceContainer);\n\n            deleteAllObjectsInContainer(regionId, destinationContainer);\n            containerApi.deleteIfEmpty(destinationContainer);\n         }\n         fail(\"Expected KeyNotFoundException\");\n      }\n   }\n\n   public void testCopyObjectWithMetadata() throws Exception {\n      for (String regionId : regions) {\n         // source\n         String sourceContainer = \"src\" + containerName;\n         String sourceObjectName = \"original.txt\";\n         String badSource = \"badSource\";\n\n         // destination\n         String destinationContainer = \"dest\" + containerName;\n         String destinationObject = \"copy.txt\";\n         String destinationPath = \"/\" + destinationContainer + \"/\" + destinationObject;\n\n         ContainerApi containerApi = getApi().getContainerApi(regionId);\n\n         // create source and destination dirs\n         containerApi.create(sourceContainer);\n         containerApi.create(destinationContainer);\n\n         // get the api for this region and container\n         ObjectApi srcApi = getApi().getObjectApi(regionId, sourceContainer);\n         ObjectApi destApi = getApi().getObjectApi(regionId, destinationContainer);\n\n         // Create source object\n         assertNotNull(srcApi.put(sourceObjectName, PAYLOAD));\n         SwiftObject sourceObject = srcApi.get(sourceObjectName);\n         checkObject(sourceObject);\n\n         srcApi.updateMetadata(sourceObjectName,\n               ImmutableMap.of(\"userProvidedMetadataKey\", \"userProvidedMetadataValue\"));\n\n         // Create the destination object\n         assertNotNull(destApi.put(destinationObject, PAYLOAD));\n         SwiftObject object = destApi.get(destinationObject);\n         checkObject(object);\n\n         // check the copy append metadata operation\n         destApi.copyAppendMetadata(destinationObject, sourceContainer, sourceObjectName,\n               ImmutableMap.<String, String>of(\"additionalUserMetakey\", \"additionalUserMetavalue\"),\n               ImmutableMap.of(\"Content-Disposition\", \"attachment; filename=\\\"updatedname.txt\\\"\"));\n\n         // now get a real SwiftObject\n         SwiftObject destSwiftObject = destApi.get(destinationObject);\n         assertEquals(toStringAndClose(destSwiftObject.getPayload().openStream()), \"swifty\");\n\n         /**\n          * Make sure all src metadata is in dest\n          * Make sure the new content disposition is in dest\n          */\n         Multimap<String, String> srcHeaders = null;\n         Multimap<String, String> destHeaders = null;\n         srcHeaders = srcApi.getWithoutBody(sourceObjectName).getHeaders();\n         destHeaders = destSwiftObject.getHeaders();\n         for (Entry<String, String> header : srcHeaders.entries()) {\n            if (header.getKey().equals(\"Date\"))continue;\n            if (header.getKey().equals(\"Last-Modified\"))continue;\n            if (header.getKey().equals(\"X-Trans-Id\"))continue;\n            if (header.getKey().equals(\"X-Timestamp\"))continue;\n            if (header.getKey().equals(\"X-Openstack-Request-Id\"))continue;\n            assertTrue(destHeaders.containsEntry(header.getKey(), header.getValue()), \"Could not find: \" + header);\n         }\n         assertEquals(destSwiftObject.getPayload().getContentMetadata().getContentDisposition(), \"attachment; filename=\\\"updatedname.txt\\\"\");\n\n         // check the copy replace metadata operation\n         destApi.copy(destinationObject, sourceContainer, sourceObjectName,\n               ImmutableMap.<String, String>of(\"key3\", \"value3\"),\n               ImmutableMap.of(\"Content-Disposition\", \"attachment; filename=\\\"updatedname.txt\\\"\"));\n\n         // now get a real SwiftObject\n         destSwiftObject = destApi.get(destinationObject);\n         assertEquals(toStringAndClose(destSwiftObject.getPayload().openStream()), \"swifty\");\n\n         destHeaders = destSwiftObject.getHeaders();\n         assertThat(destHeaders.get(\"X-Object-Meta-Key3\")).containsExactly(\"value3\");\n         assertEquals(destSwiftObject.getPayload().getContentMetadata().getContentDisposition(), \"attachment; filename=\\\"updatedname.txt\\\"\");\n\n         // test exception thrown on bad source name\n         try {\n            destApi.copy(destinationObject, badSource, sourceObjectName);\n         } catch (KeyNotFoundException e) {\n            continue;\n         } finally {\n            deleteAllObjectsInContainer(regionId, sourceContainer);\n            containerApi.deleteIfEmpty(sourceContainer);\n\n            deleteAllObjectsInContainer(regionId, destinationContainer);\n            containerApi.deleteIfEmpty(destinationContainer);\n         }\n         fail(\"Expected KeyNotFoundException\");\n      }\n   }\n\n   public void testCopyObjectConditional() throws Exception {\n      for (String regionId : regions) {\n         // source\n         String sourceContainer = \"src\" + containerName;\n         String sourceObjectName = \"original.txt\";\n         String badSource = \"badSource\";\n\n         // destination\n         String destinationContainer = \"dest\" + containerName;\n         String destinationObject = \"copy.txt\";\n         String destinationPath = \"/\" + destinationContainer + \"/\" + destinationObject;\n\n         ContainerApi containerApi = getApi().getContainerApi(regionId);\n\n         // create source and destination dirs\n         containerApi.create(sourceContainer);\n         containerApi.create(destinationContainer);\n\n         // get the api for this region and container\n         ObjectApi srcApi = getApi().getObjectApi(regionId, sourceContainer);\n         ObjectApi destApi = getApi().getObjectApi(regionId, destinationContainer);\n\n         // Create source object\n         assertNotNull(srcApi.put(sourceObjectName, PAYLOAD));\n         SwiftObject sourceObject = srcApi.get(sourceObjectName);\n         checkObject(sourceObject);\n\n         destApi.copy(destinationObject, sourceContainer, sourceObjectName, new CopyOptions().ifMatch(sourceObject.getETag()));\n         try {\n            destApi.copy(destinationObject, sourceContainer, sourceObjectName, new CopyOptions().ifMatch(\"fake-etag\"));\n            Fail.failBecauseExceptionWasNotThrown(HttpResponseException.class);\n         } catch (HttpResponseException hre) {\n            assertThat(hre.getResponse().getStatusCode()).isEqualTo(412);\n         }\n\n         long now = System.currentTimeMillis();\n         Date before = new Date(now - 1000 * 1000);\n         Date after = new Date(now + 1000 * 1000);\n\n         destApi.copy(destinationObject, sourceContainer, sourceObjectName, new CopyOptions().ifModifiedSince(before));\n         try {\n            destApi.copy(destinationObject, sourceContainer, sourceObjectName, new CopyOptions().ifModifiedSince(after));\n            Fail.failBecauseExceptionWasNotThrown(HttpResponseException.class);\n         } catch (HttpResponseException hre) {\n            assertThat(hre.getResponse().getStatusCode()).isEqualTo(304);\n         }\n\n         try {\n            destApi.copy(destinationObject, sourceContainer, sourceObjectName, new CopyOptions().ifUnmodifiedSince(before));\n            Fail.failBecauseExceptionWasNotThrown(HttpResponseException.class);\n         } catch (HttpResponseException hre) {\n            assertThat(hre.getResponse().getStatusCode()).isEqualTo(412);\n         }\n         destApi.copy(destinationObject, sourceContainer, sourceObjectName, new CopyOptions().ifUnmodifiedSince(after));\n      }\n   }\n\n   public void testList() throws Exception {\n      for (String regionId : regions) {\n         ObjectApi objectApi = getApi().getObjectApi(regionId, containerName);\n         ObjectList response = objectApi.list();\n         assertEquals(response.getContainer(), getApi().getContainerApi(regionId).get(containerName));\n         for (SwiftObject object : response) {\n            checkObject(object);\n         }\n      }\n   }\n\n   public void testListWithOptions() throws Exception {\n      for (String regionId : regions) {\n         ObjectApi objectApi = getApi().getObjectApi(regionId, containerName);\n         ObjectList response = objectApi.list(ListContainerOptions.NONE);\n         assertEquals(response.getContainer(), getApi().getContainerApi(regionId).get(containerName));\n         for (SwiftObject object : response) {\n            checkObject(object);\n         }\n      }\n   }\n\n   public void testMetadata() throws Exception {\n      for (String regionId : regions) {\n         SwiftObject object = getApi().getObjectApi(regionId, containerName).get(name);\n         assertEquals(object.getName(), name);\n         checkObject(object);\n         assertEquals(toStringAndClose(object.getPayload().openStream()), \"swifty\");\n      }\n   }\n\n   public void testUpdateMetadata() throws Exception {\n      for (String regionId : regions) {\n         ObjectApi objectApi = getApi().getObjectApi(regionId, containerName);\n\n         Map<String, String> meta = ImmutableMap.of(\"MyAdd1\", \"foo\", \"MyAdd2\", \"bar\");\n         objectApi.updateMetadata(name, meta);\n\n         SwiftObject object = objectApi.get(name);\n         for (Entry<String, String> entry : meta.entrySet()) {\n            // note keys are returned in lower-case!\n            assertEquals(object.getMetadata().get(entry.getKey().toLowerCase()), entry.getValue(),\n                  object + \" didn't have metadata: \" + entry);\n         }\n      }\n   }\n\n   public void testGet() throws Exception {\n      for (String regionId : regions) {\n         SwiftObject object = getApi().getObjectApi(regionId, containerName).get(name, GetOptions.NONE);\n         assertEquals(object.getName(), name);\n         checkObject(object);\n         assertEquals(toStringAndClose(object.getPayload().openStream()), \"swifty\");\n      }\n   }\n\n   public void testPrivateByDefault() throws Exception {\n      for (String regionId : regions) {\n         SwiftObject object = getApi().getObjectApi(regionId, containerName).get(name);\n         try {\n            object.getUri().toURL().openStream();\n            fail(\"shouldn't be able to access \" + object);\n         } catch (IOException expected) {\n         }\n      }\n   }\n\n   public void testGetOptions() throws Exception {\n      for (String regionId : regions) {\n         SwiftObject object = getApi().getObjectApi(regionId, containerName).get(name, tail(1));\n         assertEquals(object.getName(), name);\n         checkObject(object);\n         assertEquals(toStringAndClose(object.getPayload().openStream()), \"y\");\n      }\n   }\n\n   public void testListOptions() throws Exception {\n      String lexicographicallyBeforeName = name.substring(0, name.length() - 1);\n      for (String regionId : regions) {\n         SwiftObject object = getApi().getObjectApi(regionId, containerName)\n               .list(marker(lexicographicallyBeforeName)).get(0);\n         assertEquals(object.getName(), name);\n         checkObject(object);\n      }\n   }\n\n   public void testDeleteMetadata() throws Exception {\n      for (String regionId : regions) {\n         ObjectApi objectApi = getApi().getObjectApi(regionId, containerName);\n\n         Map<String, String> meta = ImmutableMap.of(\"MyDelete1\", \"foo\", \"MyDelete2\", \"bar\");\n\n         objectApi.updateMetadata(name, meta);\n         assertFalse(objectApi.get(name).getMetadata().isEmpty());\n\n         assertTrue(objectApi.deleteMetadata(name, meta));\n         assertTrue(objectApi.get(name).getMetadata().isEmpty());\n      }\n   }\n\n   @Override\n   @BeforeClass(groups = \"live\")\n   public void setup() {\n      super.setup();\n      for (String regionId : regions) {\n         getApi().getContainerApi(regionId).create(containerName);\n         getApi().getObjectApi(regionId, containerName).put(name, PAYLOAD);\n      }\n   }\n\n   @AfterClass(groups = \"live\")\n   public void tearDown() {\n      for (String regionId : regions) {\n         deleteAllObjectsInContainer(regionId, containerName);\n         getApi().getObjectApi(regionId, containerName).delete(name);\n         getApi().getContainerApi(regionId).deleteIfEmpty(containerName);\n      }\n   }\n\n   static void checkObject(SwiftObject object) {\n      assertNotNull(object.getName());\n      assertNotNull(object.getUri());\n      assertNotNull(object.getETag());\n      assertTrue(object.getLastModified().getTime() <= System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(5));\n      assertNotNull(object.getPayload().getContentMetadata().getContentLength());\n      assertNotNull(object.getPayload().getContentMetadata().getContentType());\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/features/ObjectApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.features;\n\nimport static com.google.common.io.BaseEncoding.base16;\nimport static com.google.common.net.HttpHeaders.EXPIRES;\nimport static org.jclouds.Constants.PROPERTY_MAX_RETRIES;\nimport static org.jclouds.Constants.PROPERTY_RETRY_DELAY_START;\nimport static org.jclouds.Constants.PROPERTY_SO_TIMEOUT;\nimport static org.jclouds.http.options.GetOptions.Builder.tail;\nimport static org.jclouds.io.Payloads.newByteSourcePayload;\nimport static org.jclouds.openstack.swift.v1.features.ContainerApiMockTest.containerResponse;\nimport static org.jclouds.openstack.swift.v1.options.ListContainerOptions.Builder.marker;\nimport static org.jclouds.openstack.swift.v1.options.PutOptions.Builder.metadata;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.CONTAINER_ACL_ANYBODY_READ;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.CONTAINER_READ;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.OBJECT_METADATA_PREFIX;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.OBJECT_REMOVE_METADATA_PREFIX;\nimport static org.jclouds.util.Strings2.toStringAndClose;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.Assert.fail;\n\nimport java.io.IOException;\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.Properties;\n\nimport okhttp3.Headers;\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\nimport okhttp3.mockwebserver.RecordedRequest;\n\nimport org.jclouds.blobstore.KeyNotFoundException;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.payloads.ByteSourcePayload;\nimport org.jclouds.openstack.swift.v1.SwiftApi;\nimport org.jclouds.openstack.swift.v1.domain.ObjectList;\nimport org.jclouds.openstack.swift.v1.domain.SwiftObject;\nimport org.jclouds.openstack.swift.v1.options.CopyOptions;\nimport org.jclouds.openstack.swift.v1.options.ListContainerOptions;\nimport org.jclouds.openstack.swift.v1.reference.SwiftHeaders;\nimport org.jclouds.openstack.v2_0.internal.BaseOpenStackMockTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.io.ByteSource;\n\n\n/**\n * Provides mock tests for the {@link ObjectApi}.\n */\n@Test(groups = \"unit\", testName = \"ObjectApiMockTest\")\npublic class ObjectApiMockTest extends BaseOpenStackMockTest<SwiftApi> {\n   SimpleDateFormatDateService dates = new SimpleDateFormatDateService();\n\n   static final Payload PAYLOAD = newByteSourcePayload(ByteSource.wrap(\"swifty\".getBytes()));\n\n   protected ImmutableList<SwiftObject> parsedObjectsForUrl(String baseUri) {\n      baseUri += \"v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/myContainer\";\n      return ImmutableList.of(\n            SwiftObject.builder()\n                  .name(\"test_obj_1\")\n                  .uri(URI.create(baseUri + \"/test_obj_1\"))\n                  .etag(\"4281c348eaf83e70ddce0e07221c3d28\")\n                  .payload(payload(14, \"application/octet-stream\", new Date(1406243553)))\n                  .lastModified(dates.iso8601DateParse(\"2009-02-03T05:26:32.612278\")).build(),\n            SwiftObject.builder()\n                  .name(\"test_obj_2\")\n                  .uri(URI.create(baseUri + \"/test_obj_2\"))\n                  .etag(\"b039efe731ad111bc1b0ef221c3849d0\")\n                  .payload(payload(64L, \"application/octet-stream\", null))\n                  .lastModified(dates.iso8601DateParse(\"2009-02-03T05:26:32.612278\")).build(),\n            SwiftObject.builder()\n                  .name(\"test obj 3 %$.\")\n                  .uri(URI.create(baseUri + \"/test%20obj%203%20%25%24.\"))\n                  .etag(\"0b2e80bd0744d9ebb20484149a57c82e\")\n                  .payload(payload(14, \"application/octet-stream\", new Date()))\n                  .lastModified(dates.iso8601DateParse(\"2014-05-20T05:26:32.612278\")).build());\n   }\n\n   public void testList() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(containerResponse()\n            .addHeader(CONTAINER_READ, CONTAINER_ACL_ANYBODY_READ)\n            .setBody(stringFromResource(\"/object_list.json\"))));\n\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         ObjectList objects = api.getObjectApi(\"DFW\", \"myContainer\").list();\n         assertEquals(objects, parsedObjectsForUrl(server.url(\"/\").toString()));\n         assertEquals(objects.getContainer().getName(), \"myContainer\");\n         assertTrue(objects.getContainer().getAnybodyRead().get());\n\n         // Check MD5 is parsed from the ETag header.\n         SwiftObject object1 = objects.get(1);\n         assertEquals(base16().lowerCase().decode(object1.getETag()),\n               object1.getPayload().getContentMetadata().getContentMD5AsHashCode().asBytes());\n\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"GET\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/myContainer?format=json\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testListWithOptions() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(containerResponse()\n            .addHeader(CONTAINER_READ, CONTAINER_ACL_ANYBODY_READ)\n            .setBody(stringFromResource(\"/object_list.json\"))));\n\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         ObjectList objects = api.getObjectApi(\"DFW\", \"myContainer\").list(new ListContainerOptions());\n         assertEquals(objects, parsedObjectsForUrl(server.url(\"/\").toString()));\n         assertEquals(objects.getContainer().getName(), \"myContainer\");\n         assertTrue(objects.getContainer().getAnybodyRead().get());\n\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"GET\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/myContainer?format=json\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testListOptions() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(containerResponse().setBody(stringFromResource(\"/object_list.json\"))));\n\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         ObjectList objects = api.getObjectApi(\"DFW\", \"myContainer\").list(marker(\"test\"));\n         assertEquals(objects, parsedObjectsForUrl(server.url(\"/\").toString()));\n\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"GET\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/myContainer?format=json&marker=test\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testCreate() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse()\n            .setResponseCode(201)\n            .addHeader(\"ETag\", \"d9f5eb4bba4e2f2f046e54611bc8196b\"))\n            .addHeader(\"Expires\", \"1406243553\"));\n\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         assertEquals(\n               api.getObjectApi(\"DFW\", \"myContainer\").put(\"myObject\", PAYLOAD,\n                     metadata(metadata)), \"d9f5eb4bba4e2f2f046e54611bc8196b\");\n\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         RecordedRequest replace = server.takeRequest();\n         assertRequest(replace, \"PUT\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/myContainer/myObject\");\n\n         assertEquals(replace.getBody().readUtf8(), \"swifty\");\n         for (Entry<String, String> entry : metadata.entrySet()) {\n            assertEquals(replace.getHeader(OBJECT_METADATA_PREFIX + entry.getKey().toLowerCase()), entry.getValue());\n         }\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testCreateWithSpacesAndSpecialCharacters() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(\n            new MockResponse().setResponseCode(201).addHeader(\"ETag\", \"d9f5eb4bba4e2f2f046e54611bc8196b\")));\n\n      final String containerName = \"container # ! special\";\n      final String objectName = \"object # ! special\";\n\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         assertEquals(\n               api.getObjectApi(\"DFW\", containerName).put(objectName, PAYLOAD,\n                     metadata(metadata)), \"d9f5eb4bba4e2f2f046e54611bc8196b\");\n\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         RecordedRequest replace = server.takeRequest();\n         assertRequest(replace, \"PUT\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/container%20%23%20%21%20special/object%20%23%20%21%20special\");\n\n         assertEquals(replace.getBody().readUtf8(), \"swifty\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testCreateWith408Retry() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(408))); // 1\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(408))); // 2\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(408))); // 3\n\n      // Finally success\n      server.enqueue(addCommonHeaders(new MockResponse()\n            .setResponseCode(201)\n            .addHeader(\"ETag\", \"d9f5eb4bba4e2f2f046e54611bc8196b\")));\n\n      try {\n         Properties overrides = new Properties();\n         overrides.setProperty(PROPERTY_MAX_RETRIES, 5 + \"\");\n\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\", overrides);\n         assertEquals(\n               api.getObjectApi(\"DFW\", \"myContainer\").put(\"myObject\", PAYLOAD,\n                     metadata(metadata)), \"d9f5eb4bba4e2f2f046e54611bc8196b\");\n\n         assertEquals(server.getRequestCount(), 5);\n         assertAuthentication(server);\n         RecordedRequest replace = server.takeRequest();\n         // This should take a while.\n         assertRequest(replace, \"PUT\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/myContainer/myObject\");\n\n         assertEquals(replace.getBody().readUtf8(), \"swifty\");\n         for (Entry<String, String> entry : metadata.entrySet()) {\n            assertEquals(replace.getHeader(OBJECT_METADATA_PREFIX + entry.getKey().toLowerCase()), entry.getValue());\n         }\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testCreateWith401Retry() throws Exception {\n      // TODO: requires upgrade to okhttp mockwebserver 3.6\n\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n\n      // PUT 1 - establishes auth tokens\n      // Respond to request\n      // This part will work in mockwebserver 3.6+\n      // server.enqueue(new MockResponse().setResponseCode(100).setStatus(\"Continue\"));\n\n      // Finish request\n      server.enqueue(addCommonHeaders(new MockResponse()\n            .setResponseCode(201)\n            .addHeader(\"ETag\", \"d9f5eb4bba4e2f2f046e54611bc8196b\")));\n\n      // PUT 2\n      // Respond to request\n      // server.enqueue(new MockResponse().setStatus(\"HTTP/1.1 100 Continue\").clearHeaders());\n      // token expired!\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(401).setBody(\"401 Unauthorized\")));\n      // re-auth\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access2.json\"))));\n\n      // Finally success\n      server.enqueue(addCommonHeaders(new MockResponse()\n            .setResponseCode(201)\n            .addHeader(\"ETag\", \"d9f5eb4bba4e2f2f046e54611bc8196b\")));\n\n      try {\n         Properties overrides = new Properties();\n         overrides.setProperty(PROPERTY_MAX_RETRIES, 5 + \"\");\n\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\", overrides);\n         assertEquals(\n               api.getObjectApi(\"DFW\", \"myContainer\").put(\"myObject1\", PAYLOAD,\n                     metadata(metadata)), \"d9f5eb4bba4e2f2f046e54611bc8196b\");\n\n         assertEquals(\n               api.getObjectApi(\"DFW\", \"myContainer\").put(\"myObject2\", PAYLOAD,\n                     metadata(metadata)), \"d9f5eb4bba4e2f2f046e54611bc8196b\");\n\n         assertEquals(server.getRequestCount(), 5);\n\n         //////\n\n         // First auth (auth cache empty\n         assertAuthentication(server);\n\n         // PUT 1 request\n         RecordedRequest replace = server.takeRequest();\n         assertRequest(replace, \"PUT\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/myContainer/myObject1\");\n\n         // token expired\n\n         // PUT 2 request\n         replace = server.takeRequest();\n         assertRequest(replace, \"PUT\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/myContainer/myObject2\");\n\n         // PUT 2 request re-auth\n         assertAuthentication(server);\n\n         // PUT 2 request retry\n         replace = server.takeRequest();\n         assertRequest(replace, \"PUT\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/myContainer/myObject2\");\n\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   /** upper-cases first char, and lower-cases rest!! **/\n   public void testGetWithoutKnowingServerMessesWithMetadataKeyCaseFormat() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(objectResponse()\n            // note silly casing\n            .addHeader(OBJECT_METADATA_PREFIX + \"Apiname\", \"swift\")\n            .addHeader(OBJECT_METADATA_PREFIX.toLowerCase() + \"apiversion\", \"v1.1\")));\n\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         SwiftObject object = api.getObjectApi(\"DFW\", \"myContainer\").getWithoutBody(\"myObject\");\n         assertEquals(object.getName(), \"myObject\");\n         assertEquals(object.getETag(), \"8a964ee2a5e88be344f36c22562a6486\");\n\n         // Check MD5 is parsed from the ETag header.\n         assertEquals(base16().lowerCase().decode(object.getETag()),\n               object.getPayload().getContentMetadata().getContentMD5AsHashCode().asBytes());\n\n         assertEquals(object.getLastModified(), dates.rfc822DateParse(\"Fri, 12 Jun 2010 13:40:18 GMT\"));\n         assertEquals(object.getMetadata().size(), 2);\n         for (Entry<String, String> entry : object.getMetadata().entrySet()) {\n            assertEquals(object.getMetadata().get(entry.getKey().toLowerCase()), entry.getValue());\n         }\n         assertEquals(object.getPayload().getContentMetadata().getContentType(), \"text/plain; charset=UTF-8\");\n         assertEquals(toStringAndClose(object.getPayload().openStream()), \"\");\n\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"HEAD\",\n               \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/myContainer/myObject\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGet() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(objectResponse()\n            // note silly casing\n            .addHeader(OBJECT_METADATA_PREFIX + \"Apiname\", \"swift\")\n            .addHeader(OBJECT_METADATA_PREFIX + \"Apiversion\", \"v1.1\")));\n\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         SwiftObject object = api.getObjectApi(\"DFW\", \"myContainer\").get(\"myObject\", tail(1));\n         assertEquals(object.getName(), \"myObject\");\n         assertEquals(object.getETag(), \"8a964ee2a5e88be344f36c22562a6486\");\n         assertEquals(object.getLastModified(), dates.rfc822DateParse(\"Fri, 12 Jun 2010 13:40:18 GMT\"));\n         for (Entry<String, String> entry : object.getMetadata().entrySet()) {\n            assertEquals(object.getMetadata().get(entry.getKey().toLowerCase()), entry.getValue());\n         }\n\n         Payload payload = object.getPayload();\n         assertEquals(payload.getContentMetadata().getContentLength(), Long.valueOf(4));\n         assertEquals(payload.getContentMetadata().getContentType(), \"text/plain; charset=UTF-8\");\n         assertEquals(payload.getContentMetadata().getExpires(), dates.rfc822DateParse(\"Wed, 23 Jul 2014 14:00:00 GMT\"));\n\n         assertEquals(toStringAndClose(payload.openStream()), \"ABCD\");\n\n         assertEquals(server.getRequestCount(), 2);\n         assertEquals(server.takeRequest().getRequestLine(), \"POST /tokens HTTP/1.1\");\n         RecordedRequest get = server.takeRequest();\n         assertEquals(get.getRequestLine(),\n               \"GET /v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/myContainer/myObject HTTP/1.1\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   @Test(expectedExceptions = HttpResponseException.class, timeOut = 20000)\n   public void testCreateWithTimeout() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      // Typically we would enqueue a response for the put. However, in this case, test the timeout by not providing one.\n\n      try {\n         Properties overrides = new Properties();\n\n         overrides.setProperty(PROPERTY_SO_TIMEOUT, 5000 + \"\"); // This time-outs the connection\n         overrides.setProperty(PROPERTY_MAX_RETRIES, 0 + \"\"); // 0 retries == 1 try. Semantics.\n         overrides.setProperty(PROPERTY_RETRY_DELAY_START, 0 + \"\"); // exponential backoff already working for this call. This is the delay BETWEEN attempts.\n\n         final SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\", overrides);\n\n         api.getObjectApi(\"DFW\", \"myContainer\").put(\"myObject\", new ByteSourcePayload(ByteSource.wrap(\"swifty\".getBytes())), metadata(metadata));\n\n         fail(\"testReplaceTimeout test should have failed with an HttpResponseException.\");\n      } finally {\n         try {\n            server.shutdown();\n         } catch (IOException e) {\n            // MockWebServer 2.1.0 introduces an active wait for its executor termination.\n            // That active wait is a hardcoded value and throws an IOE if the executor has not\n            // terminated in that timeout. It is safe to ignore this exception as the functionality\n            // has been properly verified.\n         }\n      }\n   }\n\n   public void testUpdateMetadata() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(objectResponse()\n            .addHeader(OBJECT_METADATA_PREFIX + \"ApiName\", \"swift\")\n            .addHeader(OBJECT_METADATA_PREFIX + \"ApiVersion\", \"v1.1\")));\n\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         api.getObjectApi(\"DFW\", \"myContainer\").updateMetadata(\"myObject\", metadata);\n\n         assertEquals(server.getRequestCount(), 2);\n         assertEquals(server.takeRequest().getRequestLine(), \"POST /tokens HTTP/1.1\");\n         RecordedRequest replaceRequest = server.takeRequest();\n         assertEquals(replaceRequest.getRequestLine(),\n               \"POST /v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/myContainer/myObject HTTP/1.1\");\n         for (Entry<String, String> entry : metadata.entrySet()) {\n            assertEquals(replaceRequest.getHeader(OBJECT_METADATA_PREFIX + entry.getKey().toLowerCase()), entry.getValue());\n         }\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testUpdateMetadataContentType() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(objectResponse()\n            .addHeader(OBJECT_METADATA_PREFIX + \"ApiName\", \"swift\")\n            .addHeader(OBJECT_METADATA_PREFIX + \"ApiVersion\", \"v1.1\")));\n\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         api.getObjectApi(\"DFW\", \"myContainer\").updateMetadata(\"myObject\", metadata);\n\n         assertEquals(server.getRequestCount(), 2);\n         assertEquals(server.takeRequest().getRequestLine(), \"POST /tokens HTTP/1.1\");\n         RecordedRequest replaceRequest = server.takeRequest();\n         assertEquals(replaceRequest.getHeader(\"Content-Type\"), \"\", \"updateMetadata should send an empty content-type header, but sent \"\n               + replaceRequest.getHeader(\"Content-Type\"));\n\n         assertEquals(replaceRequest.getRequestLine(),\n               \"POST /v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/myContainer/myObject HTTP/1.1\");\n         for (Entry<String, String> entry : metadata.entrySet()) {\n            assertEquals(replaceRequest.getHeader(OBJECT_METADATA_PREFIX + entry.getKey().toLowerCase()), entry.getValue());\n         }\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testDeleteMetadata() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(objectResponse()));\n\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         assertTrue(api.getObjectApi(\"DFW\", \"myContainer\").deleteMetadata(\"myObject\", metadata));\n\n         assertEquals(server.getRequestCount(), 2);\n         assertEquals(server.takeRequest().getRequestLine(), \"POST /tokens HTTP/1.1\");\n         RecordedRequest deleteRequest = server.takeRequest();\n         assertEquals(deleteRequest.getRequestLine(),\n               \"POST /v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/myContainer/myObject HTTP/1.1\");\n         for (String key : metadata.keySet()) {\n            assertEquals(deleteRequest.getHeader(OBJECT_REMOVE_METADATA_PREFIX + key.toLowerCase()), \"ignored\");\n         }\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testDelete() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(204)));\n\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         api.getObjectApi(\"DFW\", \"myContainer\").delete(\"myObject\");\n\n         assertEquals(server.getRequestCount(), 2);\n         assertEquals(server.takeRequest().getRequestLine(), \"POST /tokens HTTP/1.1\");\n         RecordedRequest deleteRequest = server.takeRequest();\n         assertEquals(deleteRequest.getRequestLine(),\n               \"DELETE /v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/myContainer/myObject HTTP/1.1\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testAlreadyDeleted() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(404)));\n\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         api.getObjectApi(\"DFW\", \"myContainer\").delete(\"myObject\");\n\n         assertEquals(server.getRequestCount(), 2);\n         assertEquals(server.takeRequest().getRequestLine(), \"POST /tokens HTTP/1.1\");\n         RecordedRequest deleteRequest = server.takeRequest();\n         assertEquals(deleteRequest.getRequestLine(),\n               \"DELETE /v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/myContainer/myObject HTTP/1.1\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testCopyObject() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(201)\n            .addHeader(SwiftHeaders.OBJECT_COPY_FROM, \"/bar/foo.txt\")));\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         api.getObjectApi(\"DFW\", \"foo\").copy(\"bar.txt\", \"bar\", \"foo.txt\");\n\n         assertEquals(server.getRequestCount(), 2);\n         assertEquals(server.takeRequest().getRequestLine(), \"POST /tokens HTTP/1.1\");\n\n         RecordedRequest copyRequest = server.takeRequest();\n         assertEquals(copyRequest.getRequestLine(),\n               \"PUT /v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/foo/bar.txt HTTP/1.1\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testCopyObjectConditional() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(201)\n            .addHeader(SwiftHeaders.OBJECT_COPY_FROM, \"/bar/foo.txt\")));\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         api.getObjectApi(\"DFW\", \"foo\").copy(\"bar.txt\", \"bar\", \"foo.txt\", new CopyOptions().ifMatch(\"fakeetag\"));\n\n         assertEquals(server.getRequestCount(), 2);\n         assertEquals(server.takeRequest().getRequestLine(), \"POST /tokens HTTP/1.1\");\n\n         RecordedRequest copyRequest = server.takeRequest();\n         assertEquals(copyRequest.getRequestLine(),\n               \"PUT /v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/foo/bar.txt HTTP/1.1\");\n\n         Headers requestHeaders = copyRequest.getHeaders();\n         assertEquals(requestHeaders.get(\"If-Match\"), \"fakeetag\");\n         assertEquals(requestHeaders.get(SwiftHeaders.OBJECT_COPY_FROM), \"/bar/foo.txt\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   @Test(expectedExceptions = KeyNotFoundException.class)\n   public void testCopyObjectFail() throws InterruptedException, IOException {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(404)\n            .addHeader(SwiftHeaders.OBJECT_COPY_FROM, \"/bogus/foo.txt\")));\n\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         // the following line will throw the KeyNotFoundException\n         api.getObjectApi(\"DFW\", \"foo\").copy(\"bar.txt\", \"bogus\", \"foo.txt\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testCopyObjectWithMetadata() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(201)\n            .addHeader(SwiftHeaders.OBJECT_COPY_FROM, \"/bar/foo.txt\")));\n\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         api.getObjectApi(\"DFW\", \"foo\")\n               .copy(\"bar.txt\", \"bar\", \"foo.txt\", ImmutableMap.of(\"someUserHeader\", \"someUserMetadataValue\"),\n                     ImmutableMap.of(\"Content-Disposition\", \"attachment; filename=\\\"fname.ext\\\"\"));\n\n         assertEquals(server.getRequestCount(), 2);\n         assertEquals(server.takeRequest().getRequestLine(), \"POST /tokens HTTP/1.1\");\n\n         RecordedRequest copyRequest = server.takeRequest();\n         assertEquals(copyRequest.getRequestLine(),\n               \"PUT /v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/foo/bar.txt HTTP/1.1\");\n\n         Headers requestHeaders = copyRequest.getHeaders();\n         assertEquals(requestHeaders.get(\"X-Object-Meta-someuserheader\"), \"someUserMetadataValue\");\n         assertEquals(requestHeaders.get(\"Content-Disposition\"), \"attachment; filename=\\\"fname.ext\\\"\");\n         assertEquals(requestHeaders.get(SwiftHeaders.OBJECT_COPY_FROM), \"/bar/foo.txt\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   @Test(expectedExceptions = KeyNotFoundException.class)\n   public void testCopyObjectWithMetadataFail() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(404)\n            .addHeader(SwiftHeaders.OBJECT_COPY_FROM, \"/bar/foo.txt\")));\n\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         api.getObjectApi(\"DFW\", \"foo\")\n               .copy(\"bar.txt\", \"bar\", \"foo.txt\", ImmutableMap.of(\"someUserHeader\", \"someUserMetadataValue\"),\n                     ImmutableMap.of(\"Content-Disposition\", \"attachment; filename=\\\"fname.ext\\\"\"));\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   private static final Map<String, String> metadata = ImmutableMap.of(\"ApiName\", \"swift\", \"ApiVersion\", \"v1.1\");\n\n   static MockResponse objectResponse() {\n      return new MockResponse()\n            .addHeader(\"Last-Modified\", \"Fri, 12 Jun 2010 13:40:18 GMT\")\n            .addHeader(\"ETag\", \"8a964ee2a5e88be344f36c22562a6486\")\n            // TODO: MWS doesn't allow you to return content length w/o content\n            // on HEAD!\n            .setBody(\"ABCD\")\n            .addHeader(\"Content-Length\", \"4\")\n            .addHeader(\"Content-Type\", \"text/plain; charset=UTF-8\")\n            .addHeader(EXPIRES, \"Wed, 23 Jul 2014 14:00:00 GMT\");\n   }\n\n   static Payload payload(long bytes, String contentType, Date expires) {\n      Payload payload = newByteSourcePayload(ByteSource.empty());\n      payload.getContentMetadata().setContentLength(bytes);\n      payload.getContentMetadata().setContentType(contentType);\n      payload.getContentMetadata().setExpires(expires);\n      return payload;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/features/StaticLargeObjectApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.features;\n\nimport static java.lang.String.format;\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.jclouds.io.Payloads.newByteSourcePayload;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.UUID;\n\nimport org.jclouds.openstack.swift.v1.domain.DeleteStaticLargeObjectResponse;\nimport org.jclouds.openstack.swift.v1.domain.Segment;\nimport org.jclouds.openstack.swift.v1.domain.SwiftObject;\nimport org.jclouds.openstack.swift.v1.internal.BaseSwiftApiLiveTest;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.io.ByteSource;\n\n@Test(groups = \"live\", testName = \"StaticLargeObjectApiLiveTest\", singleThreaded = true)\npublic class StaticLargeObjectApiLiveTest extends BaseSwiftApiLiveTest {\n\n   private String defaultName = getClass().getSimpleName();\n   private String defaultContainerName = getClass().getSimpleName() + \"Container\";\n   private String unicodeName = getClass().getSimpleName() + \"unic₪de\";\n   private String unicodeContainerName = getClass().getSimpleName() + \"unic₪deContainer\";\n   private byte[] megOf1s;\n   private byte[] megOf2s;\n\n   public void testNotPresentWhenDeleting() throws Exception {\n      for (String regionId : regions) {\n         DeleteStaticLargeObjectResponse resp = getApi().getStaticLargeObjectApi(regionId, defaultContainerName).delete(UUID.randomUUID().toString());\n         assertThat(resp.status()).isEqualTo(\"200 OK\");\n         assertThat(resp.deleted()).isZero();\n         assertThat(resp.notFound()).isEqualTo(1);\n         assertThat(resp.errors()).isEmpty();\n      }\n   }\n\n   @Test\n   public void testReplaceManifest() throws Exception {\n      for (String regionId : regions) {\n         assertReplaceManifest(regionId, defaultContainerName, defaultName);\n      }\n   }\n\n   @Test(dependsOnMethods = \"testReplaceManifest\")\n   public void testDelete() throws Exception {\n      for (String regionId : regions) {\n         assertDelete(regionId, defaultContainerName, defaultName);\n      }\n   }\n\n   @Test\n   public void testReplaceManifestUnicode() throws Exception {\n      for (String regionId : regions) {\n         assertReplaceManifest(regionId, unicodeContainerName, unicodeName);\n      }\n   }\n\n   @Test(dependsOnMethods = \"testReplaceManifestUnicode\")\n   public void testDeleteUnicode() throws Exception {\n      for (String regionId : regions) {\n         assertDelete(regionId, unicodeContainerName, unicodeName);\n      }\n   }\n\n   public void testDeleteSinglePartObjectWithMultiPartDelete() throws Exception {\n      String objectName = \"testDeleteSinglePartObjectWithMultiPartDelete\";\n      for (String regionId : regions) {\n         getApi().getObjectApi(regionId, defaultContainerName).put(objectName, newByteSourcePayload(ByteSource.wrap(\"swifty\".getBytes())));\n         DeleteStaticLargeObjectResponse resp = getApi().getStaticLargeObjectApi(regionId, defaultContainerName).delete(objectName);\n         assertThat(resp.status()).isEqualTo(\"400 Bad Request\");\n         assertThat(resp.deleted()).isZero();\n         assertThat(resp.notFound()).isZero();\n         assertThat(resp.errors()).hasSize(1);\n         getApi().getObjectApi(regionId, defaultContainerName).delete(objectName);\n      }\n   }\n\n   protected void assertReplaceManifest(String regionId, String containerName, String name) {\n      ObjectApi objectApi = getApi().getObjectApi(regionId, containerName);\n\n      String etag1s = objectApi.put(name + \"/1\", newByteSourcePayload(ByteSource.wrap(megOf1s)));\n      awaitConsistency();\n      assertMegabyteAndETagMatches(regionId, containerName, name + \"/1\", etag1s);\n\n      String etag2s = objectApi.put(name + \"/2\", newByteSourcePayload(ByteSource.wrap(megOf2s)));\n      awaitConsistency();\n      assertMegabyteAndETagMatches(regionId, containerName, name + \"/2\", etag2s);\n\n      List<Segment> segments = ImmutableList.<Segment> builder()\n          .add(Segment.builder()\n              .path(format(\"%s/%s/1\", containerName, name)).etag(etag1s).sizeBytes(1024 * 1024)\n              .build())\n          .add(Segment.builder()\n              .path(format(\"%s/%s/2\", containerName, name)).etag(etag2s).sizeBytes(1024 * 1024)\n              .build())\n          .build();\n\n      awaitConsistency();\n      String etagOfEtags = getApi().getStaticLargeObjectApi(regionId, containerName).replaceManifest(\n          name, segments, ImmutableMap.of(\"myfoo\", \"Bar\"));\n\n      assertNotNull(etagOfEtags);\n\n      awaitConsistency();\n\n      SwiftObject bigObject = getApi().getObjectApi(regionId, containerName).get(name);\n      assertEquals(bigObject.getETag(), etagOfEtags);\n      assertEquals(bigObject.getPayload().getContentMetadata().getContentLength(), Long.valueOf(2 * 1024 * 1024));\n      assertEquals(bigObject.getMetadata(), ImmutableMap.of(\"myfoo\", \"Bar\"));\n\n      // segments are visible\n      assertEquals(getApi().getContainerApi(regionId).get(containerName).getObjectCount(), Long.valueOf(3));\n   }\n\n   protected void assertDelete(String regionId, String containerName, String name) {\n      DeleteStaticLargeObjectResponse resp = getApi().getStaticLargeObjectApi(regionId, containerName).delete(name);\n      assertThat(resp.status()).isEqualTo(\"200 OK\");\n      assertThat(resp.deleted()).isEqualTo(3);\n      assertThat(resp.notFound()).isZero();\n      assertThat(resp.errors()).isEmpty();\n      assertEquals(getApi().getContainerApi(regionId).get(containerName).getObjectCount(), Long.valueOf(0));\n   }\n\n   protected void assertMegabyteAndETagMatches(String regionId, String containerName, String name, String etag1s) {\n      SwiftObject object1s = getApi().getObjectApi(regionId, containerName).get(name);\n      assertEquals(object1s.getETag(), etag1s);\n      assertEquals(object1s.getPayload().getContentMetadata().getContentLength(), Long.valueOf(1024 * 1024));\n   }\n\n   @Override\n   @BeforeClass(groups = \"live\")\n   public void setup() {\n      super.setup();\n      for (String regionId : regions) {\n         boolean created = getApi().getContainerApi(regionId).create(defaultContainerName);\n         if (!created) {\n            deleteAllObjectsInContainer(regionId, defaultContainerName);\n         }\n\n         created = getApi().getContainerApi(regionId).create(unicodeContainerName);\n         if (!created) {\n            deleteAllObjectsInContainer(regionId, unicodeContainerName);\n         }\n      }\n\n      megOf1s = new byte[1024 * 1024];\n      megOf2s = new byte[1024 * 1024];\n\n      Arrays.fill(megOf1s, (byte) 1);\n      Arrays.fill(megOf2s, (byte) 2);\n   }\n\n   @AfterClass(groups = \"live\")\n   public void tearDown() {\n      for (String regionId : regions) {\n         deleteAllObjectsInContainer(regionId, defaultContainerName);\n         getApi().getContainerApi(regionId).deleteIfEmpty(defaultContainerName);\n         deleteAllObjectsInContainer(regionId, unicodeContainerName);\n         getApi().getContainerApi(regionId).deleteIfEmpty(unicodeContainerName);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/features/StaticLargeObjectApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.features;\n\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.OBJECT_METADATA_PREFIX;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotEquals;\n\nimport java.util.List;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\nimport okhttp3.mockwebserver.RecordedRequest;\n\nimport org.jclouds.openstack.swift.v1.SwiftApi;\nimport org.jclouds.openstack.swift.v1.domain.DeleteStaticLargeObjectResponse;\nimport org.jclouds.openstack.swift.v1.domain.Segment;\nimport org.jclouds.openstack.v2_0.internal.BaseOpenStackMockTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.net.HttpHeaders;\n\n\n@Test(groups = \"unit\", testName = \"StaticLargeObjectApiMockTest\")\npublic class StaticLargeObjectApiMockTest extends BaseOpenStackMockTest<SwiftApi> {\n\n   public void testReplaceManifest() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().addHeader(HttpHeaders.ETAG, \"\\\"abcd\\\"\")));\n\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         assertEquals(\n               api.getStaticLargeObjectApi(\"DFW\", \"myContainer\").replaceManifest(\n                     \"myObject\",\n                     ImmutableList\n                           .<Segment> builder()\n                           .add(Segment.builder().path(\"/mycontainer/objseg1\").etag(\"0228c7926b8b642dfb29554cd1f00963\")\n                                 .sizeBytes(1468006).build())\n                           .add(Segment.builder().path(\"/mycontainer/pseudodir/seg-obj2\")\n                                 .etag(\"5bfc9ea51a00b790717eeb934fb77b9b\").sizeBytes(1572864).build())\n                           .add(Segment.builder().path(\"/other-container/seg-final\")\n                                 .etag(\"b9c3da507d2557c1ddc51f27c54bae51\").sizeBytes(256).build()).build(),\n                     ImmutableMap.of(\"MyFoo\", \"Bar\")), \"abcd\");\n\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n\n         RecordedRequest replaceRequest = server.takeRequest();\n         assertRequest(replaceRequest, \"PUT\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/myContainer/myObject?multipart-manifest=put\");\n         assertEquals(replaceRequest.getHeader(OBJECT_METADATA_PREFIX + \"myfoo\"), \"Bar\");\n         assertEquals(\n               replaceRequest.getBody().readUtf8(),\n         \"[{\\\"path\\\":\\\"/mycontainer/objseg1\\\",\\\"etag\\\":\\\"0228c7926b8b642dfb29554cd1f00963\\\",\\\"size_bytes\\\":1468006},\" +\n          \"{\\\"path\\\":\\\"/mycontainer/pseudodir/seg-obj2\\\",\\\"etag\\\":\\\"5bfc9ea51a00b790717eeb934fb77b9b\\\",\\\"size_bytes\\\":1572864},\" +\n          \"{\\\"path\\\":\\\"/other-container/seg-final\\\",\\\"etag\\\":\\\"b9c3da507d2557c1ddc51f27c54bae51\\\",\\\"size_bytes\\\":256}]\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testReplaceManifestUnicodeUTF8() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().addHeader(HttpHeaders.ETAG, \"\\\"abcd\\\"\")));\n\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         assertEquals(\n             api.getStaticLargeObjectApi(\"DFW\", \"myContainer\").replaceManifest(\n                 \"unic₪de\",\n                 ImmutableList\n                     .<Segment> builder()\n                     .add(Segment.builder().path(\"/mycontainer/unic₪de/slo/1\").etag(\"0228c7926b8b642dfb29554cd1f00963\")\n                         .sizeBytes(1468006).build())\n                     .add(Segment.builder().path(\"/mycontainer/unic₪de/slo/2\")\n                         .etag(\"5bfc9ea51a00b790717eeb934fb77b9b\").sizeBytes(1572864).build())\n                     .add(Segment.builder().path(\"/mycontainer/unic₪de/slo/3\")\n                         .etag(\"b9c3da507d2557c1ddc51f27c54bae51\").sizeBytes(256).build()).build(),\n                 ImmutableMap.of(\"MyFoo\", \"Bar\")), \"abcd\");\n\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n\n         RecordedRequest replaceRequest = server.takeRequest();\n         assertRequest(replaceRequest, \"PUT\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/myContainer/unic%E2%82%AAde?multipart-manifest=put\");\n         assertEquals(replaceRequest.getHeader(OBJECT_METADATA_PREFIX + \"myfoo\"), \"Bar\");\n\n         String expectedManifest =\n             \"[{\\\"path\\\":\\\"/mycontainer/unic₪de/slo/1\\\",\\\"etag\\\":\\\"0228c7926b8b642dfb29554cd1f00963\\\",\\\"size_bytes\\\":1468006},\" +\n             \"{\\\"path\\\":\\\"/mycontainer/unic₪de/slo/2\\\",\\\"etag\\\":\\\"5bfc9ea51a00b790717eeb934fb77b9b\\\",\\\"size_bytes\\\":1572864},\" +\n             \"{\\\"path\\\":\\\"/mycontainer/unic₪de/slo/3\\\",\\\"etag\\\":\\\"b9c3da507d2557c1ddc51f27c54bae51\\\",\\\"size_bytes\\\":256}]\";\n\n         long characterLength = expectedManifest.length();\n         long byteLength = expectedManifest.getBytes(Charsets.UTF_8).length;\n\n         assertNotEquals(characterLength, byteLength);\n         assertEquals(replaceRequest.getHeader(\"content-length\"), Long.toString(byteLength));\n\n         assertEquals(\n             replaceRequest.getBody().readUtf8(),\n             expectedManifest);\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testReplaceManifestWithHeaders() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().addHeader(HttpHeaders.ETAG, \"\\\"abcd\\\"\")));\n\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         assertEquals(\n               api.getStaticLargeObjectApi(\"DFW\", \"myContainer\").replaceManifest(\n                     \"myObject\",\n                     ImmutableList\n                           .<Segment>builder()\n                           .add(Segment.builder().path(\"/mycontainer/objseg1\").etag(\"0228c7926b8b642dfb29554cd1f00963\")\n                                 .sizeBytes(1468006).build())\n                           .add(Segment.builder().path(\"/mycontainer/pseudodir/seg-obj2\")\n                                 .etag(\"5bfc9ea51a00b790717eeb934fb77b9b\").sizeBytes(1572864).build())\n                           .add(Segment.builder().path(\"/other-container/seg-final\")\n                                 .etag(\"b9c3da507d2557c1ddc51f27c54bae51\").sizeBytes(256).build()).build(),\n                     ImmutableMap.of(\"MyFoo\", \"Bar\"),\n                     ImmutableMap.of(\n                           \"content-language\", \"en\",\n                           \"some-header1\", \"some-header-value\")), \"abcd\");\n\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n\n         RecordedRequest replaceRequest = server.takeRequest();\n         assertRequest(replaceRequest, \"PUT\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/myContainer/myObject?multipart-manifest=put\");\n         assertEquals(replaceRequest.getHeader(OBJECT_METADATA_PREFIX + \"myfoo\"), \"Bar\");\n\n         // Content-length is automatically determined based on manifest size\n         // Setting it will result in an error\n         assertEquals(replaceRequest.getHeader(\"content-language\"), \"en\");\n         assertEquals(replaceRequest.getHeader(\"some-header1\"), \"some-header-value\");\n\n         assertEquals(\n               replaceRequest.getBody().readUtf8(),\n               \"[{\\\"path\\\":\\\"/mycontainer/objseg1\\\",\\\"etag\\\":\\\"0228c7926b8b642dfb29554cd1f00963\\\",\\\"size_bytes\\\":1468006},\" +\n                     \"{\\\"path\\\":\\\"/mycontainer/pseudodir/seg-obj2\\\",\\\"etag\\\":\\\"5bfc9ea51a00b790717eeb934fb77b9b\\\",\\\"size_bytes\\\":1572864},\" +\n                     \"{\\\"path\\\":\\\"/other-container/seg-final\\\",\\\"etag\\\":\\\"b9c3da507d2557c1ddc51f27c54bae51\\\",\\\"size_bytes\\\":256}]\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGetManifest() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200).setBody(\n            stringFromResource(\"/manifest_get_response.json\")) ));\n\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         List<Segment> manifest = api.getStaticLargeObjectApi(\"DFW\", \"myContainer\").getManifest(\"myObject\");\n\n         // Check response\n         assertEquals(manifest.size(), 3);\n         assertEquals(manifest.get(1).getSizeBytes(), 1572864);\n         assertEquals(manifest.get(1).getETag(), \"5bfc9ea51a00b790717eeb934fb77b9b\");\n         assertEquals(manifest.get(1).getPath(), \"/mycontainer/pseudodir/seg-obj2\");\n\n         // Check request\n         assertAuthentication(server);\n         RecordedRequest getRequest = server.takeRequest();\n         assertRequest(getRequest, \"GET\",\n               \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/myContainer/myObject?format=json&multipart-manifest=get\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGetManifestFail() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(404).setBody(stringFromResource(\"/manifest_get_response.json\")) ));\n\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         List<Segment> manifest = api.getStaticLargeObjectApi(\"DFW\", \"myContainer\").getManifest(\"myObject\");\n\n         // Check response\n         assertEquals(manifest.size(), 0);\n\n         // Check request\n         assertAuthentication(server);\n         RecordedRequest getRequest = server.takeRequest();\n         assertRequest(getRequest, \"GET\",\n               \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/myContainer/myObject?format=json&multipart-manifest=get\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testDelete() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200)\n            .setBody(\"{\\\"Number Not Found\\\": 0, \\\"Response Status\\\": \\\"200 OK\\\", \\\"Errors\\\": [], \\\"Number Deleted\\\": 6, \\\"Response Body\\\": \\\"\\\"}\")));\n\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         DeleteStaticLargeObjectResponse response = api.getStaticLargeObjectApi(\"DFW\", \"myContainer\").delete(\"myObject\");\n\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"DELETE\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/myContainer/myObject?multipart-manifest=delete\");\n         assertThat(response.status()).isEqualTo(\"200 OK\");\n         assertThat(response.deleted()).isEqualTo(6);\n         assertThat(response.notFound()).isZero();\n         assertThat(response.errors()).isEmpty();\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testAlreadyDeleted() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(200)\n            .setBody(\"{\\\"Number Not Found\\\": 1, \\\"Response Status\\\": \\\"200 OK\\\", \\\"Errors\\\": [], \\\"Number Deleted\\\": 0, \\\"Response Body\\\": \\\"\\\"}\")));\n\n      try {\n         SwiftApi api = api(server.url(\"/\").toString(), \"openstack-swift\");\n         DeleteStaticLargeObjectResponse response = api.getStaticLargeObjectApi(\"DFW\", \"myContainer\").delete(\"myObject\");\n\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"DELETE\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/myContainer/myObject?multipart-manifest=delete\");\n         assertThat(response.status()).isEqualTo(\"200 OK\");\n         assertThat(response.deleted()).isZero();\n         assertThat(response.notFound()).isEqualTo(1);\n         assertThat(response.errors()).isEmpty();\n      } finally {\n         server.shutdown();\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/features/UrlEncodeAndJoinOnNewlineTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.features;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.openstack.swift.v1.features.BulkApi.UrlEncodeAndJoinOnNewline;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"UrlEncodeAndJoinOnNewlineTest\")\npublic class UrlEncodeAndJoinOnNewlineTest {\n   UrlEncodeAndJoinOnNewline binder = new UrlEncodeAndJoinOnNewline();\n\n   public void urlEncodesPaths() {\n      HttpRequest request = HttpRequest.builder()\n                                       .method(\"DELETE\")\n                                       .endpoint(\"https://storage101.dfw1.clouddrive.com/v1/MossoCloudFS_XXXXXX/\")\n                                       .addQueryParam(\"bulk-delete\").build();\n\n      request = binder.bindToRequest(request, ImmutableList.<String> builder()\n            .add(\"/v1/12345678912345/mycontainer/home/xx<yy\")\n            .add(\"/v1/12345678912345/mycontainer/../image.gif\").build());\n\n      assertEquals(request.getPayload().getRawContent(), \"/v1/12345678912345/mycontainer/home/xx%3Cyy\\n\"\n            + \"/v1/12345678912345/mycontainer/../image.gif\");\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/internal/BaseSwiftApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.internal;\n\nimport static com.google.common.base.Preconditions.checkState;\n\nimport java.util.List;\nimport java.util.Properties;\nimport java.util.Set;\nimport java.util.concurrent.TimeUnit;\n\nimport org.jclouds.blobstore.integration.internal.BaseBlobStoreIntegrationTest;\nimport org.jclouds.location.reference.LocationConstants;\nimport org.jclouds.openstack.keystone.config.KeystoneProperties;\nimport org.jclouds.openstack.swift.v1.SwiftApi;\nimport org.jclouds.openstack.swift.v1.domain.BulkDeleteResponse;\nimport org.jclouds.openstack.swift.v1.domain.ObjectList;\nimport org.jclouds.openstack.swift.v1.domain.SwiftObject;\nimport org.jclouds.openstack.swift.v1.options.ListContainerOptions;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Lists;\nimport com.google.common.util.concurrent.Uninterruptibles;\n\n@Test(groups = \"live\", testName = \"BaseSwiftApiLiveTest\")\npublic abstract class BaseSwiftApiLiveTest extends BaseBlobStoreIntegrationTest {\n\n   protected BaseSwiftApiLiveTest() {\n      provider = \"openstack-swift\";\n   }\n\n   public SwiftApi getApi() {\n      return view.unwrapApi(SwiftApi.class);\n   }\n\n   protected Set<String> regions;\n\n   protected static final int AWAIT_CONSISTENCY_TIMEOUT_SECONDS = Integer.parseInt(System.getProperty(\n         \"test.blobstore.await-consistency-timeout-seconds\", \"10\"));\n\n   protected void awaitConsistency() {\n      Uninterruptibles.sleepUninterruptibly(AWAIT_CONSISTENCY_TIMEOUT_SECONDS, TimeUnit.SECONDS);\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      setIfTestSystemPropertyPresent(props, KeystoneProperties.CREDENTIAL_TYPE);\n      setIfTestSystemPropertyPresent(props, LocationConstants.PROPERTY_REGION);\n      return props;\n   }\n\n   protected void deleteAllObjectsInContainer(String regionId, final String containerName) {\n      Uninterruptibles.sleepUninterruptibly(10, TimeUnit.SECONDS);\n\n      ObjectList objects = getApi().getObjectApi(regionId, containerName).list(new ListContainerOptions());\n      if (objects == null) {\n         return;\n      }\n      List<String> pathsToDelete = Lists.transform(objects, new Function<SwiftObject, String>() {\n         public String apply(SwiftObject input) {\n            return containerName + \"/\" + input.getName();\n         }\n      });\n      if (!pathsToDelete.isEmpty()) {\n         BulkDeleteResponse response = getApi().getBulkApi(regionId).bulkDelete(pathsToDelete);\n         checkState(response.getErrors().isEmpty(), \"Errors deleting paths %s: %s\", pathsToDelete, response);\n      }\n   }\n\n   @BeforeClass(groups = \"live\")\n   public void setup() {\n           String providedRegion = System.getProperty(\"test.\" + LocationConstants.PROPERTY_REGION);\n           if (providedRegion != null) {\n                regions = ImmutableSet.of(providedRegion);\n              } else {\n                regions = getApi().getConfiguredRegions();\n              }\n        }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/options/CreateContainerOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.options;\n\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.CONTAINER_ACL_ANYBODY_READ;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.CONTAINER_METADATA_PREFIX;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.CONTAINER_READ;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.VERSIONS_LOCATION;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.CONTAINER_QUOTA_BYTES;\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.Multimap;\n\n/**\n * Tests behavior of {@link CreateContainerOptions}.\n */\n@Test(groups = \"unit\")\npublic class CreateContainerOptionsTest {\n\n   public void testMetadata() {\n      CreateContainerOptions options =\n            new CreateContainerOptions().metadata(ImmutableMap.of(\"ApiName\", \"swift\", \"metaKey2\", \"Value2\", \"METAKEY3\", \"VALUE 3 \"));\n\n      Multimap<String, String> headers = options.buildRequestHeaders();\n      assertEquals(headers.get(CONTAINER_METADATA_PREFIX + \"apiname\"), ImmutableList.of(\"swift\"));\n      assertEquals(headers.get(CONTAINER_METADATA_PREFIX + \"metakey2\"), ImmutableList.of(\"Value2\"));\n      assertEquals(headers.get(CONTAINER_METADATA_PREFIX + \"metakey3\"), ImmutableList.of(\"VALUE 3 \"));\n   }\n\n   public void testHeaders() {\n      CreateContainerOptions options =\n            new CreateContainerOptions().headers(ImmutableMultimap.of(CONTAINER_QUOTA_BYTES, \"5120\", CONTAINER_METADATA_PREFIX + \"apiname\", \"swift\"));\n\n      Multimap<String, String> headers = options.buildRequestHeaders();\n      assertEquals(headers.get(CONTAINER_QUOTA_BYTES), ImmutableList.of(\"5120\"));\n      assertEquals(headers.get(CONTAINER_METADATA_PREFIX + \"apiname\"), ImmutableList.of(\"swift\"));\n   }\n\n   public void testAnybodyRead() {\n      CreateContainerOptions options =\n            new CreateContainerOptions().headers(ImmutableMultimap.of(CONTAINER_READ, CONTAINER_ACL_ANYBODY_READ));\n      assertEquals(options.buildRequestHeaders().get(CONTAINER_READ), ImmutableList.of(CONTAINER_ACL_ANYBODY_READ));\n   }\n\n   public void testVersionsLocation() {\n      CreateContainerOptions options =\n            new CreateContainerOptions().headers(ImmutableMultimap.of(VERSIONS_LOCATION, \"containerWithVersions\"));\n      assertEquals(options.buildRequestHeaders().get(VERSIONS_LOCATION), ImmutableList.of(\"containerWithVersions\"));\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/options/PutOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.options;\n\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.OBJECT_METADATA_PREFIX;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.OBJECT_DELETE_AT;\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMultimap;\n\n/**\n * Tests behavior of {@link PutOptions}.\n */\n@Test(groups = \"unit\")\npublic class PutOptionsTest {\n\n   public void testPutMetadata() {\n      PutOptions options = \n            new PutOptions().metadata(ImmutableMap.of(\"ApiName\", \"swift\"));\n      assertEquals(options.buildRequestHeaders().get(OBJECT_METADATA_PREFIX + \"apiname\"), ImmutableList.of(\"swift\"));\n\n   }\n\n   public void testPutHeaders() {\n      PutOptions options = \n            new PutOptions().headers(ImmutableMultimap.of(OBJECT_DELETE_AT, \"123456789\"));\n      assertEquals(options.buildRequestHeaders().get(OBJECT_DELETE_AT), ImmutableList.of(\"123456789\"));\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/options/UpdateContainerOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.swift.v1.options;\n\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.CONTAINER_ACL_ANYBODY_READ;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.CONTAINER_METADATA_PREFIX;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.CONTAINER_QUOTA_BYTES;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.CONTAINER_READ;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.VERSIONS_LOCATION;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.STATIC_WEB_DIRECTORY_TYPE;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.STATIC_WEB_ERROR;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.STATIC_WEB_INDEX;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.STATIC_WEB_LISTINGS;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.STATIC_WEB_LISTINGS_CSS;\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.Multimap;\nimport com.google.common.net.MediaType;\n\n/**\n * Tests behavior of {@link UpdateContainerOptions}.\n */\n@Test(groups = \"unit\")\npublic class UpdateContainerOptionsTest {\n\n   public void testAnybodyRead() {\n      UpdateContainerOptions options = new UpdateContainerOptions().anybodyRead();\n      assertEquals(options.buildRequestHeaders().get(CONTAINER_READ), ImmutableList.of(CONTAINER_ACL_ANYBODY_READ));\n   }\n\n   public void testAnybodyReadViaHeaders() {\n      UpdateContainerOptions options =\n            new UpdateContainerOptions().headers(ImmutableMultimap.of(CONTAINER_READ, CONTAINER_ACL_ANYBODY_READ));\n      assertEquals(options.buildRequestHeaders().get(CONTAINER_READ), ImmutableList.of(CONTAINER_ACL_ANYBODY_READ));\n   }\n\n   public void testVersionsLocation() {\n      UpdateContainerOptions options = new UpdateContainerOptions().versionsLocation(\"containerWithVersions\");\n      assertEquals(options.buildRequestHeaders().get(VERSIONS_LOCATION), ImmutableList.of(\"containerWithVersions\"));\n   }\n\n   public void testVersionsLocationViaHeaders() {\n      UpdateContainerOptions options =\n            new UpdateContainerOptions().headers(ImmutableMultimap.of(VERSIONS_LOCATION, \"containerWithVersions\"));\n      assertEquals(options.buildRequestHeaders().get(VERSIONS_LOCATION), ImmutableList.of(\"containerWithVersions\"));\n   }\n\n   public void testMetadata() {\n      UpdateContainerOptions options =\n            new UpdateContainerOptions().metadata(ImmutableMap.of(\"ApiName\", \"swift\", \"metaKey2\", \"Value2\", \"METAKEY3\", \"VALUE 3 \"));\n\n      Multimap<String, String> headers = options.buildRequestHeaders();\n      assertEquals(headers.get(CONTAINER_METADATA_PREFIX + \"apiname\"), ImmutableList.of(\"swift\"));\n      assertEquals(headers.get(CONTAINER_METADATA_PREFIX + \"metakey2\"), ImmutableList.of(\"Value2\"));\n      assertEquals(headers.get(CONTAINER_METADATA_PREFIX + \"metakey3\"), ImmutableList.of(\"VALUE 3 \"));\n   }\n\n   public void testHeaders() {\n      UpdateContainerOptions options =\n            new UpdateContainerOptions().headers(ImmutableMultimap.of(CONTAINER_QUOTA_BYTES, \"5120\", CONTAINER_METADATA_PREFIX + \"apiname\", \"swift\"));\n\n      Multimap<String, String> headers = options.buildRequestHeaders();\n      assertEquals(headers.get(CONTAINER_QUOTA_BYTES), ImmutableList.of(\"5120\"));\n      assertEquals(headers.get(CONTAINER_METADATA_PREFIX + \"apiname\"), ImmutableList.of(\"swift\"));\n   }\n\n   public void testStaticWebsiteDirectoryType() {\n      MediaType appDir = MediaType.create(\"application\", \"directory\");\n      Multimap<String, String> headers = ImmutableMultimap.of(STATIC_WEB_DIRECTORY_TYPE, appDir.toString());\n      UpdateContainerOptions options = new UpdateContainerOptions().headers(headers);\n      assertEquals(options.buildRequestHeaders().get(STATIC_WEB_DIRECTORY_TYPE), ImmutableList.of(appDir.toString()));\n   }\n\n   public void testStaticWebsiteIndexPage() {\n      Multimap<String, String> headers = ImmutableMultimap.of(STATIC_WEB_INDEX, \"index.html\");\n      UpdateContainerOptions options = new UpdateContainerOptions().headers(headers);\n      assertEquals(options.buildRequestHeaders().get(STATIC_WEB_INDEX), ImmutableList.of(\"index.html\"));\n   }\n\n   public void testStaticWebsiteErrorPage() {\n      Multimap<String, String> headers = ImmutableMultimap.of(STATIC_WEB_ERROR, \"error.html\");\n      UpdateContainerOptions options = new UpdateContainerOptions().headers(headers);\n      assertEquals(options.buildRequestHeaders().get(STATIC_WEB_ERROR), ImmutableList.of(\"error.html\"));\n   }\n\n   public void testEnableStaticWebsiteListings() {\n      Multimap<String, String> headers = ImmutableMultimap.of(STATIC_WEB_LISTINGS, \"true\");\n      UpdateContainerOptions options = new UpdateContainerOptions().headers(headers);\n      assertEquals(options.buildRequestHeaders().get(STATIC_WEB_LISTINGS), ImmutableList.of(\"true\"));\n   }\n\n   public void testDiableStaticWebsiteListings() {\n      Multimap<String, String> headers = ImmutableMultimap.of(STATIC_WEB_LISTINGS, \"false\");\n      UpdateContainerOptions options = new UpdateContainerOptions().headers(headers);\n      assertEquals(options.buildRequestHeaders().get(STATIC_WEB_LISTINGS), ImmutableList.of(\"false\"));\n   }\n\n   public void testStaticWebsiteListingsCSS() {\n      Multimap<String, String> headers = ImmutableMultimap.of(STATIC_WEB_LISTINGS_CSS, \"listings.css\");\n      UpdateContainerOptions options = new UpdateContainerOptions().headers(headers);\n      assertEquals(options.buildRequestHeaders().get(STATIC_WEB_LISTINGS_CSS), ImmutableList.of(\"listings.css\"));\n   }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/test/resources/access.json",
    "content": "{\n    \"access\":{\n        \"token\":{\n            \"id\":\"bb03a23aa8271291a7aaa9aaa2aaaaaa\",\n            \"expires\":\"2013-08-02T16:55:24.229-05:00\",\n            \"tenant\":{\n                \"id\":\"888888\",\n                \"name\":\"888888\"\n            },\n            \"RAX-AUTH:authenticatedBy\":[\n                \"PASSWORD\"\n            ]\n        },\n        \"serviceCatalog\":[\n            {\n                \"name\":\"cloudFilesCDN\",\n                \"endpoints\":[\n                    {\n                        \"region\":\"ORD\",\n                        \"tenantId\":\"MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\",\n                        \"publicURL\":\"URL/v1\\/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\"\n                    },\n                    {\n                        \"region\":\"DFW\",\n                        \"tenantId\":\"MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\",\n                        \"publicURL\":\"URL/v1\\/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\"\n                    },\n                    {\n                        \"region\":\"SYD\",\n                        \"tenantId\":\"MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\",\n                        \"publicURL\":\"URL/v1\\/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\"\n                    }\n                ],\n                \"type\":\"rax:object-cdn\"\n            },\n            {\n                \"name\":\"cloudFiles\",\n                \"endpoints\":[\n                    {\n                        \"region\":\"ORD\",\n                        \"tenantId\":\"MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\",\n                        \"publicURL\":\"URL/v1\\/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\",\n                        \"internalURL\":\"URL/v1\\/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\"\n                    },\n                    {\n                        \"region\":\"DFW\",\n                        \"tenantId\":\"MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\",\n                        \"publicURL\":\"URL/v1\\/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\",\n                        \"internalURL\":\"URL/v1\\/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\"\n                    },\n                    {\n                        \"region\":\"SYD\",\n                        \"tenantId\":\"MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\",\n                        \"publicURL\":\"URL/v1\\/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\",\n                        \"internalURL\":\"URL/v1\\/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\"\n                    }\n                ],\n                \"type\":\"object-store\"\n            },\n            {\n                \"name\":\"cloudLoadBalancers\",\n                \"endpoints\":[\n                    {\n                        \"region\":\"SYD\",\n                        \"tenantId\":\"888888\",\n                        \"publicURL\":\"URL/v1.0\\/888888\"\n                    },\n                    {\n                        \"region\":\"DFW\",\n                        \"tenantId\":\"888888\",\n                        \"publicURL\":\"URL/v1.0\\/888888\"\n                    },\n                    {\n                        \"region\":\"ORD\",\n                        \"tenantId\":\"888888\",\n                        \"publicURL\":\"URL/v1.0\\/888888\"\n                    }\n                ],\n                \"type\":\"rax:load-balancer\"\n            },\n            {\n                \"name\":\"cloudDatabases\",\n                \"endpoints\":[\n                    {\n                        \"region\":\"SYD\",\n                        \"tenantId\":\"888888\",\n                        \"publicURL\":\"URL/v1.0\\/888888\"\n                    },\n                    {\n                        \"region\":\"DFW\",\n                        \"tenantId\":\"888888\",\n                        \"publicURL\":\"URL/v1.0\\/888888\"\n                    },\n                    {\n                        \"region\":\"ORD\",\n                        \"tenantId\":\"888888\",\n                        \"publicURL\":\"URL/v1.0\\/888888\"\n                    }\n                ],\n                \"type\":\"rax:database\"\n            },\n            {\n                \"name\":\"cloudBlockStorage\",\n                \"endpoints\":[\n                    {\n                        \"region\":\"SYD\",\n                        \"tenantId\":\"888888\",\n                        \"publicURL\":\"URL/v1\\/888888\"\n                    },\n                    {\n                        \"region\":\"DFW\",\n                        \"tenantId\":\"888888\",\n                        \"publicURL\":\"URL/v1\\/888888\"\n                    },\n                    {\n                        \"region\":\"ORD\",\n                        \"tenantId\":\"888888\",\n                        \"publicURL\":\"URL/v1\\/888888\"\n                    }\n                ],\n                \"type\":\"volume\"\n            },\n            {\n                \"name\":\"cloudServersOpenStack\",\n                \"endpoints\":[\n                    {\n                        \"region\":\"SYD\",\n                        \"tenantId\":\"888888\",\n                        \"publicURL\":\"URL/v2\\/888888\",\n                        \"versionInfo\":\"https:\\/\\/syd.servers.api.rackspacecloud.com\\/v2\",\n                        \"versionList\":\"https:\\/\\/syd.servers.api.rackspacecloud.com\\/\",\n                        \"versionId\":\"2\"\n                    },\n                    {\n                        \"region\":\"DFW\",\n                        \"tenantId\":\"888888\",\n                        \"publicURL\":\"URL/v2\\/888888\",\n                        \"versionInfo\":\"https:\\/\\/dfw.servers.api.rackspacecloud.com\\/v2\",\n                        \"versionList\":\"https:\\/\\/dfw.servers.api.rackspacecloud.com\\/\",\n                        \"versionId\":\"2\"\n                    },\n                    {\n                        \"region\":\"ORD\",\n                        \"tenantId\":\"888888\",\n                        \"publicURL\":\"URL/v2\\/888888\",\n                        \"versionInfo\":\"https:\\/\\/ord.servers.api.rackspacecloud.com\\/v2\",\n                        \"versionList\":\"https:\\/\\/ord.servers.api.rackspacecloud.com\\/\",\n                        \"versionId\":\"2\"\n                    }\n                ],\n                \"type\":\"compute\"\n            },\n            {\n                \"name\":\"autoscale\",\n                \"endpoints\":[\n                    {\n                        \"region\":\"ORD\",\n                        \"tenantId\":\"888888\",\n                        \"publicURL\":\"URL/v1.0\\/888888\",\n                        \"versionInfo\":null,\n                        \"versionList\":null,\n                        \"versionId\":\"1.0\"\n                    },\n                    {\n                        \"region\":\"DFW\",\n                        \"tenantId\":\"888888\",\n                        \"publicURL\":\"URL/v1.0\\/888888\",\n                        \"versionInfo\":null,\n                        \"versionList\":null,\n                        \"versionId\":\"1.0\"\n                    }\n                ],\n                \"type\":\"rax:autoscale\"\n            },\n            {\n                \"name\":\"cloudMonitoring\",\n                \"endpoints\":[\n                    {\n                        \"tenantId\":\"888888\",\n                        \"publicURL\":\"URL/v1.0\\/888888\"\n                    }\n                ],\n                \"type\":\"rax:monitor\"\n            },\n            {\n                \"name\":\"cloudBackup\",\n                \"endpoints\":[\n                    {\n                        \"tenantId\":\"888888\",\n                        \"publicURL\":\"URL/v1.0\\/888888\"\n                    }\n                ],\n                \"type\":\"rax:backup\"\n            },\n            {\n                \"name\":\"cloudServers\",\n                \"endpoints\":[\n                    {\n                        \"tenantId\":\"888888\",\n                        \"publicURL\":\"URL/v1.0\\/888888\",\n                        \"versionInfo\":\"https:\\/\\/servers.api.rackspacecloud.com\\/v1.0\",\n                        \"versionList\":\"https:\\/\\/servers.api.rackspacecloud.com\\/\",\n                        \"versionId\":\"1.0\"\n                    }\n                ],\n                \"type\":\"compute\"\n            },\n            {\n                \"name\":\"cloudDNS\",\n                \"endpoints\":[\n                    {\n                        \"tenantId\":\"888888\",\n                        \"publicURL\":\"URL/v1.0\\/888888\"\n                    }\n                ],\n                \"type\":\"rax:dns\"\n            }\n        ],\n        \"user\":{\n            \"id\":\"335853\",\n            \"roles\":[\n                {\n                    \"id\":\"10000150\",\n                    \"description\":\"Checkmate Access role\",\n                    \"name\":\"checkmate\"\n                },\n                {\n                    \"tenantId\":\"MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\",\n                    \"id\":\"5\",\n                    \"description\":\"A Role that allows a user access to keystone Service methods\",\n                    \"name\":\"object-store:default\"\n                },\n                {\n                    \"tenantId\":\"888888\",\n                    \"id\":\"6\",\n                    \"description\":\"A Role that allows a user access to keystone Service methods\",\n                    \"name\":\"compute:default\"\n                },\n                {\n                    \"id\":\"3\",\n                    \"description\":\"User Admin Role.\",\n                    \"name\":\"identity:user-admin\"\n                }\n            ],\n            \"name\":\"test\",\n            \"RAX-AUTH:defaultRegion\":\"ORD\"\n        }\n    }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/test/resources/access2.json",
    "content": "{\n    \"access\":{\n        \"token\":{\n            \"id\":\"bb03a23aa8271291a7bbb9bbb2aaaaaa\",\n            \"expires\":\"2013-08-02T16:55:24.229-05:00\",\n            \"tenant\":{\n                \"id\":\"888888\",\n                \"name\":\"888888\"\n            },\n            \"RAX-AUTH:authenticatedBy\":[\n                \"PASSWORD\"\n            ]\n        },\n        \"serviceCatalog\":[\n            {\n                \"name\":\"cloudFilesCDN\",\n                \"endpoints\":[\n                    {\n                        \"region\":\"ORD\",\n                        \"tenantId\":\"MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\",\n                        \"publicURL\":\"URL/v1\\/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\"\n                    },\n                    {\n                        \"region\":\"DFW\",\n                        \"tenantId\":\"MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\",\n                        \"publicURL\":\"URL/v1\\/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\"\n                    },\n                    {\n                        \"region\":\"SYD\",\n                        \"tenantId\":\"MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\",\n                        \"publicURL\":\"URL/v1\\/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\"\n                    }\n                ],\n                \"type\":\"rax:object-cdn\"\n            },\n            {\n                \"name\":\"cloudFiles\",\n                \"endpoints\":[\n                    {\n                        \"region\":\"ORD\",\n                        \"tenantId\":\"MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\",\n                        \"publicURL\":\"URL/v1\\/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\",\n                        \"internalURL\":\"URL/v1\\/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\"\n                    },\n                    {\n                        \"region\":\"DFW\",\n                        \"tenantId\":\"MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\",\n                        \"publicURL\":\"URL/v1\\/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\",\n                        \"internalURL\":\"URL/v1\\/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\"\n                    },\n                    {\n                        \"region\":\"SYD\",\n                        \"tenantId\":\"MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\",\n                        \"publicURL\":\"URL/v1\\/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\",\n                        \"internalURL\":\"URL/v1\\/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\"\n                    }\n                ],\n                \"type\":\"object-store\"\n            },\n            {\n                \"name\":\"cloudLoadBalancers\",\n                \"endpoints\":[\n                    {\n                        \"region\":\"SYD\",\n                        \"tenantId\":\"888888\",\n                        \"publicURL\":\"URL/v1.0\\/888888\"\n                    },\n                    {\n                        \"region\":\"DFW\",\n                        \"tenantId\":\"888888\",\n                        \"publicURL\":\"URL/v1.0\\/888888\"\n                    },\n                    {\n                        \"region\":\"ORD\",\n                        \"tenantId\":\"888888\",\n                        \"publicURL\":\"URL/v1.0\\/888888\"\n                    }\n                ],\n                \"type\":\"rax:load-balancer\"\n            },\n            {\n                \"name\":\"cloudDatabases\",\n                \"endpoints\":[\n                    {\n                        \"region\":\"SYD\",\n                        \"tenantId\":\"888888\",\n                        \"publicURL\":\"URL/v1.0\\/888888\"\n                    },\n                    {\n                        \"region\":\"DFW\",\n                        \"tenantId\":\"888888\",\n                        \"publicURL\":\"URL/v1.0\\/888888\"\n                    },\n                    {\n                        \"region\":\"ORD\",\n                        \"tenantId\":\"888888\",\n                        \"publicURL\":\"URL/v1.0\\/888888\"\n                    }\n                ],\n                \"type\":\"rax:database\"\n            },\n            {\n                \"name\":\"cloudBlockStorage\",\n                \"endpoints\":[\n                    {\n                        \"region\":\"SYD\",\n                        \"tenantId\":\"888888\",\n                        \"publicURL\":\"URL/v1\\/888888\"\n                    },\n                    {\n                        \"region\":\"DFW\",\n                        \"tenantId\":\"888888\",\n                        \"publicURL\":\"URL/v1\\/888888\"\n                    },\n                    {\n                        \"region\":\"ORD\",\n                        \"tenantId\":\"888888\",\n                        \"publicURL\":\"URL/v1\\/888888\"\n                    }\n                ],\n                \"type\":\"volume\"\n            },\n            {\n                \"name\":\"cloudServersOpenStack\",\n                \"endpoints\":[\n                    {\n                        \"region\":\"SYD\",\n                        \"tenantId\":\"888888\",\n                        \"publicURL\":\"URL/v2\\/888888\",\n                        \"versionInfo\":\"https:\\/\\/syd.servers.api.rackspacecloud.com\\/v2\",\n                        \"versionList\":\"https:\\/\\/syd.servers.api.rackspacecloud.com\\/\",\n                        \"versionId\":\"2\"\n                    },\n                    {\n                        \"region\":\"DFW\",\n                        \"tenantId\":\"888888\",\n                        \"publicURL\":\"URL/v2\\/888888\",\n                        \"versionInfo\":\"https:\\/\\/dfw.servers.api.rackspacecloud.com\\/v2\",\n                        \"versionList\":\"https:\\/\\/dfw.servers.api.rackspacecloud.com\\/\",\n                        \"versionId\":\"2\"\n                    },\n                    {\n                        \"region\":\"ORD\",\n                        \"tenantId\":\"888888\",\n                        \"publicURL\":\"URL/v2\\/888888\",\n                        \"versionInfo\":\"https:\\/\\/ord.servers.api.rackspacecloud.com\\/v2\",\n                        \"versionList\":\"https:\\/\\/ord.servers.api.rackspacecloud.com\\/\",\n                        \"versionId\":\"2\"\n                    }\n                ],\n                \"type\":\"compute\"\n            },\n            {\n                \"name\":\"autoscale\",\n                \"endpoints\":[\n                    {\n                        \"region\":\"ORD\",\n                        \"tenantId\":\"888888\",\n                        \"publicURL\":\"URL/v1.0\\/888888\",\n                        \"versionInfo\":null,\n                        \"versionList\":null,\n                        \"versionId\":\"1.0\"\n                    },\n                    {\n                        \"region\":\"DFW\",\n                        \"tenantId\":\"888888\",\n                        \"publicURL\":\"URL/v1.0\\/888888\",\n                        \"versionInfo\":null,\n                        \"versionList\":null,\n                        \"versionId\":\"1.0\"\n                    }\n                ],\n                \"type\":\"rax:autoscale\"\n            },\n            {\n                \"name\":\"cloudMonitoring\",\n                \"endpoints\":[\n                    {\n                        \"tenantId\":\"888888\",\n                        \"publicURL\":\"URL/v1.0\\/888888\"\n                    }\n                ],\n                \"type\":\"rax:monitor\"\n            },\n            {\n                \"name\":\"cloudBackup\",\n                \"endpoints\":[\n                    {\n                        \"tenantId\":\"888888\",\n                        \"publicURL\":\"URL/v1.0\\/888888\"\n                    }\n                ],\n                \"type\":\"rax:backup\"\n            },\n            {\n                \"name\":\"cloudServers\",\n                \"endpoints\":[\n                    {\n                        \"tenantId\":\"888888\",\n                        \"publicURL\":\"URL/v1.0\\/888888\",\n                        \"versionInfo\":\"https:\\/\\/servers.api.rackspacecloud.com\\/v1.0\",\n                        \"versionList\":\"https:\\/\\/servers.api.rackspacecloud.com\\/\",\n                        \"versionId\":\"1.0\"\n                    }\n                ],\n                \"type\":\"compute\"\n            },\n            {\n                \"name\":\"cloudDNS\",\n                \"endpoints\":[\n                    {\n                        \"tenantId\":\"888888\",\n                        \"publicURL\":\"URL/v1.0\\/888888\"\n                    }\n                ],\n                \"type\":\"rax:dns\"\n            }\n        ],\n        \"user\":{\n            \"id\":\"335853\",\n            \"roles\":[\n                {\n                    \"id\":\"10000150\",\n                    \"description\":\"Checkmate Access role\",\n                    \"name\":\"checkmate\"\n                },\n                {\n                    \"tenantId\":\"MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\",\n                    \"id\":\"5\",\n                    \"description\":\"A Role that allows a user access to keystone Service methods\",\n                    \"name\":\"object-store:default\"\n                },\n                {\n                    \"tenantId\":\"888888\",\n                    \"id\":\"6\",\n                    \"description\":\"A Role that allows a user access to keystone Service methods\",\n                    \"name\":\"compute:default\"\n                },\n                {\n                    \"id\":\"3\",\n                    \"description\":\"User Admin Role.\",\n                    \"name\":\"identity:user-admin\"\n                }\n            ],\n            \"name\":\"test\",\n            \"RAX-AUTH:defaultRegion\":\"ORD\"\n        }\n    }\n}\n"
  },
  {
    "path": "apis/openstack-swift/src/test/resources/container_list.json",
    "content": "[\n    {\n        \"name\": \"test_container_1\",\n        \"count\": 2,\n        \"bytes\": 78\n    },\n    {\n        \"name\": \"test_container_2\",\n        \"count\": 1,\n        \"bytes\": 17\n    }\n]\n"
  },
  {
    "path": "apis/openstack-swift/src/test/resources/logback.xml",
    "content": "<?xml version=\"1.0\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<configuration scan=\"false\">\n    <appender name=\"FILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <appender name=\"WIREFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds-wire.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <appender name=\"BLOBSTOREFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds-blobstore.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n    \n    <root>\n        <level value=\"warn\" />\n    </root>\n\n    <logger name=\"org.jclouds\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"FILE\" />\n    </logger>\n\n<!--\n    <logger name=\"jclouds.wire\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n-->\n\n    <logger name=\"jclouds.headers\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n\n    <logger name=\"jclouds.blobstore\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"BLOBSTOREFILE\" />\n    </logger>\n\n</configuration>\n"
  },
  {
    "path": "apis/openstack-swift/src/test/resources/manifest_get_response.json",
    "content": "[\n  {\n    \"path\": \"/mycontainer/objseg1\",\n    \"etag\": \"0228c7926b8b642dfb29554cd1f00963\",\n    \"size_bytes\": 1468006\n  },\n  {\n    \"path\": \"/mycontainer/pseudodir/seg-obj2\",\n    \"etag\": \"5bfc9ea51a00b790717eeb934fb77b9b\",\n    \"size_bytes\": 1572864\n  },\n  {\n    \"path\": \"/other-container/seg-final\",\n    \"etag\": \"b9c3da507d2557c1ddc51f27c54bae51\",\n    \"size_bytes\": 256\n  }\n]\n"
  },
  {
    "path": "apis/openstack-swift/src/test/resources/object_list.json",
    "content": "[\n    {\n        \"name\": \"test_obj_1\",\n        \"hash\": \"4281c348eaf83e70ddce0e07221c3d28\",\n        \"bytes\": 14,\n        \"content_type\": \"application/octet-stream\",\n        \"last_modified\": \"2009-02-03T05:26:32.612278\"\n    },\n    {\n        \"name\": \"test_obj_2\",\n        \"hash\": \"b039efe731ad111bc1b0ef221c3849d0\",\n        \"bytes\": 64,\n        \"content_type\": \"application/octet-stream\",\n        \"last_modified\": \"2009-02-03T05:26:32.612278\"\n    },\n    {\n        \"name\": \"test obj 3 %$.\",\n        \"hash\": \"0b2e80bd0744d9ebb20484149a57c82e\",\n        \"bytes\": 123,\n        \"content_type\": \"application/octet-stream\",\n        \"last_modified\": \"2014-05-20T05:26:32.612278\"\n    }\n]\n"
  },
  {
    "path": "apis/openstack-trove/README.md",
    "content": "OpenStack Trove\n===============\n\nTrove is Database as a Service for OpenStack.\n\nProduction ready?\nYes\n"
  },
  {
    "path": "apis/openstack-trove/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.openstack.trove.v1.*;version=\"${project.version}\";-noimport:=true"
  },
  {
    "path": "apis/openstack-trove/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.api</groupId>\n  <artifactId>openstack-trove</artifactId>\n  <name>jclouds openstack-trove api</name>\n  <description>jclouds components to access an implementation of OpenStack Trove</description>\n\n  <properties>\n    <test.openstack-trove.endpoint>http://localhost:5000/v2.0/</test.openstack-trove.endpoint>\n    <test.openstack-trove.api-version>1.0</test.openstack-trove.api-version>\n    <test.openstack-trove.build-version />\n    <test.openstack-trove.identity>FIXME_IDENTITY</test.openstack-trove.identity>\n    <test.openstack-trove.credential>FIXME_CREDENTIALS</test.openstack-trove.credential>\n    <test.jclouds.keystone.credential-type>passwordCredentials</test.jclouds.keystone.credential-type>\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-keystone</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-keystone</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-slf4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>ch.qos.logback</groupId>\n      <artifactId>logback-classic</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <forkCount>5</forkCount>\n                  <reuseForks>true</reuseForks>\n                  <parallel>classes</parallel>\n                  <systemPropertyVariables>\n                    <test.openstack-trove.endpoint>${test.openstack-trove.endpoint}</test.openstack-trove.endpoint>\n                    <test.openstack-trove.api-version>${test.openstack-trove.api-version}</test.openstack-trove.api-version>\n                    <test.openstack-trove.build-version>${test.openstack-trove.build-version}</test.openstack-trove.build-version>\n                    <test.openstack-trove.identity>${test.openstack-trove.identity}</test.openstack-trove.identity>\n                    <test.openstack-trove.credential>${test.openstack-trove.credential}</test.openstack-trove.credential>\n                    <test.jclouds.keystone.credential-type>${test.jclouds.keystone.credential-type}</test.jclouds.keystone.credential-type>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n"
  },
  {
    "path": "apis/openstack-trove/src/main/java/org/jclouds/openstack/trove/v1/TroveApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.trove.v1;\n\nimport java.io.Closeable;\nimport java.util.Set;\n\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\n\nimport org.jclouds.location.Region;\nimport org.jclouds.location.functions.RegionToEndpoint;\nimport org.jclouds.openstack.trove.v1.features.DatabaseApi;\nimport org.jclouds.openstack.trove.v1.features.FlavorApi;\nimport org.jclouds.openstack.trove.v1.features.InstanceApi;\nimport org.jclouds.openstack.trove.v1.features.UserApi;\nimport org.jclouds.rest.annotations.Delegate;\nimport org.jclouds.rest.annotations.EndpointParam;\n\nimport com.google.common.base.Optional;\nimport com.google.inject.Provides;\n\n/**\n * Provides access to the OpenStack Trove (Database) v2 API.\n *\n */\npublic interface TroveApi extends Closeable {\n   /**\n    * Provides a set of all regions available.\n    *\n    * @return the Region codes configured\n    */\n   @Provides\n   @Region\n   Set<String> getConfiguredRegions();\n\n   /**\n    * Provides access to Flavor features.\n    */\n   @Delegate\n   FlavorApi getFlavorApi(@EndpointParam(parser = RegionToEndpoint.class) String region);\n\n   /**\n    * Provides access to Instance features.\n    */\n   @Delegate\n   InstanceApi getInstanceApi(@EndpointParam(parser = RegionToEndpoint.class) String region);\n\n   /**\n    * Provides access to User features.\n    */\n   @Delegate\n   @Path(\"/instances/{instanceId}\")\n   UserApi getUserApi(@EndpointParam(parser = RegionToEndpoint.class) String region,\n         @PathParam(\"instanceId\") String instanceId);\n\n   /**\n    * Provides access to Database features.\n    */\n   @Delegate\n   @Path(\"/instances/{instanceId}\")\n   DatabaseApi getDatabaseApi(@EndpointParam(parser = RegionToEndpoint.class) String region,\n         @PathParam(\"instanceId\") String instanceId);\n\n   /**\n    * Provides a set of all zones available.\n    *\n    * @return the Zone codes configured\n    * @deprecated Please use {@link #getConfiguredRegions()} instead. To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   @Provides\n   @Region\n   Set<String> getConfiguredZones();\n\n   /**\n    * Provides access to Flavor features.\n    * @deprecated Please use {@link #getFlavorApi(String region)} instead. To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   @Delegate\n   FlavorApi getFlavorApiForZone(\n         @EndpointParam(parser = RegionToEndpoint.class) String zone);\n\n   /**\n    * Provides access to Instance features.\n    * @deprecated Please use {@link #getInstanceApi(String region)} instead. To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   @Delegate\n   InstanceApi getInstanceApiForZone(\n         @EndpointParam(parser = RegionToEndpoint.class) String zone);\n\n   /**\n    * Provides access to User features.\n    * @deprecated Please use {@link #getUserApi(String region, String instanceId)} instead.\n    *             To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   @Delegate\n   @Path(\"/instances/{instanceId}\")\n   UserApi getUserApiForZoneAndInstance(@EndpointParam(parser = RegionToEndpoint.class) String zone,\n         @PathParam(\"instanceId\") String instanceId);\n\n   /**\n    * Provides access to Database features.\n    * @deprecated Please use {@link #getDatabaseApi(String region, String instanceId)} instead.\n    *             To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   @Delegate\n   @Path(\"/instances/{instanceId}\")\n   DatabaseApi getDatabaseApiForZoneAndInstance(@EndpointParam(parser = RegionToEndpoint.class) String zone,\n         @PathParam(\"instanceId\") String instanceId);\n\n   /**\n    * Provides the Tenant.\n    */\n   @Provides\n   Optional<String> getCurrentTenantId();\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/main/java/org/jclouds/openstack/trove/v1/TroveApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.trove.v1;\n\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.CREDENTIAL_TYPE;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.KEYSTONE_VERSION;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.SERVICE_TYPE;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.openstack.keystone.auth.config.AuthenticationModule;\nimport org.jclouds.openstack.keystone.auth.config.CredentialTypes;\nimport org.jclouds.openstack.keystone.catalog.config.ServiceCatalogModule;\nimport org.jclouds.openstack.keystone.catalog.config.ServiceCatalogModule.RegionModule;\nimport org.jclouds.openstack.trove.v1.config.TroveHttpApiModule;\nimport org.jclouds.openstack.trove.v1.config.TroveParserModule;\nimport org.jclouds.openstack.v2_0.ServiceType;\nimport org.jclouds.rest.internal.BaseHttpApiMetadata;\n\nimport com.google.auto.service.AutoService;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n/**\n * Implementation of {@link ApiMetadata} for the OpenStack Trove v1 API.\n */\n@AutoService(ApiMetadata.class)\npublic class TroveApiMetadata extends BaseHttpApiMetadata<TroveApi> {\n\n   @Override\n   public Builder toBuilder() {\n      return new Builder().fromApiMetadata(this);\n   }\n\n   public TroveApiMetadata() {\n      this(new Builder());\n   }\n\n   protected TroveApiMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = BaseHttpApiMetadata.defaultProperties();\n      properties.setProperty(SERVICE_TYPE, ServiceType.DATABASE);\n      properties.setProperty(KEYSTONE_VERSION, \"2\");\n      properties.setProperty(CREDENTIAL_TYPE, CredentialTypes.PASSWORD_CREDENTIALS);\n      return properties;\n   }\n\n   public static class Builder extends BaseHttpApiMetadata.Builder<TroveApi, Builder> {\n\n      protected Builder() {\n          id(\"openstack-trove\")\n         .name(\"OpenStack Trove API\")\n         .identityName(\"${tenantName}:${userName} or ${userName}, if your keystone supports a default tenant\")\n         .credentialName(\"${password}\")\n         .endpointName(\"Keystone base URL ending in /v2.0/\")\n         .documentation(URI.create(\"http://api.openstack.org/\"))\n         .version(\"1.0\")\n         .defaultEndpoint(\"http://localhost:5000/v2.0/\")\n         .defaultProperties(TroveApiMetadata.defaultProperties())\n         .defaultModules(ImmutableSet.<Class<? extends Module>>builder()\n                                     .add(AuthenticationModule.class)\n                                     .add(ServiceCatalogModule.class)\n                                     .add(RegionModule.class)\n                                     .add(TroveParserModule.class)\n                                     .add(TroveHttpApiModule.class)\n                                     .build());\n      }\n\n      @Override\n      public TroveApiMetadata build() {\n         return new TroveApiMetadata(this);\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/main/java/org/jclouds/openstack/trove/v1/binders/BindCreateDatabaseToJson.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.trove.v1.binders;\n\nimport java.util.Map;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.MapBinder;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMap.Builder;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Inject;\n\npublic class BindCreateDatabaseToJson implements MapBinder {\n\n   @Inject\n   private BindToJsonPayload jsonBinder;\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      Builder<String, String> databaseBuilder = ImmutableMap.builder();\n\n      databaseBuilder.put(\"name\", (String) postParams.get(\"database\"));\n\n      if (postParams.get(\"character_set\") != null) {\n         databaseBuilder.put(\"character_set\", (String) postParams.get(\"character_set\"));\n      }\n      if (postParams.get(\"collate\") != null) {\n         databaseBuilder.put(\"collate\", (String) postParams.get(\"collate\"));\n      }\n\n      return jsonBinder.bindToRequest(request, ImmutableMap.of(\"databases\", ImmutableSet.of(databaseBuilder.build())));\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object toBind) {\n      throw new IllegalStateException(\"Create database is a POST operation\");\n   }\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/main/java/org/jclouds/openstack/trove/v1/binders/BindCreateInstanceToJson.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.trove.v1.binders;\n\nimport java.util.Map;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.openstack.trove.v1.internal.Volume;\nimport org.jclouds.rest.MapBinder;\nimport org.jclouds.rest.binders.BindToJsonPayload;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Maps;\nimport com.google.inject.Inject;\n\npublic class BindCreateInstanceToJson implements MapBinder {\n    \n    @Inject\n    private BindToJsonPayload jsonBinder;\n    \n    @Override    \n    public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n       Map<String, Object> databaseInstance = Maps.newHashMap();\n       databaseInstance.put(\"flavorRef\", postParams.get(\"flavorRef\"));\n       databaseInstance.put(\"volume\", new Volume((Integer) postParams.get(\"size\")));\n       if (postParams.get(\"name\") != null)\n           databaseInstance.put(\"name\", postParams.get(\"name\"));\n       return jsonBinder.bindToRequest(request, ImmutableMap.of(\"instance\", databaseInstance));\n    }\n\n    @Override\n    public <R extends HttpRequest> R bindToRequest(R request, Object toBind) {\n       throw new IllegalStateException(\"CreateInstance is a POST operation\");\n    }    \n}\n"
  },
  {
    "path": "apis/openstack-trove/src/main/java/org/jclouds/openstack/trove/v1/binders/BindCreateUserToJson.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.trove.v1.binders;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.openstack.trove.v1.domain.User;\nimport org.jclouds.openstack.trove.v1.domain.User.Builder;\nimport org.jclouds.rest.MapBinder;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Sets;\nimport com.google.inject.Inject;\n\npublic class BindCreateUserToJson implements MapBinder {\n\n   @Inject\n   private BindToJsonPayload jsonBinder;\n\n   @SuppressWarnings(\"unchecked\")\n   @Override    \n   public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      Set<User> users = Sets.newHashSet();\n      if (postParams.get(\"name\") != null) {\n         Set<String> databases = Sets.newHashSet();\n         if (postParams.get(\"databaseName\") != null)\n            databases.add((String) postParams.get(\"databaseName\"));\n         \n         Builder builder = User.builder();\n         builder.name((String) postParams.get(\"name\"))\n                .password((String) postParams.get(\"password\"));\n         \n         builder.host((String) postParams.get(\"host\"));\n         builder.databases(databases);\n         \n         User user = builder.build();\n         users.add(user);\n      }\n      else if (postParams.get(\"users\") != null) {\n         users = (Set<User>) postParams.get(\"users\");\n      }\n      return jsonBinder.bindToRequest(request, ImmutableMap.of(\"users\", users));\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object toBind) {\n      throw new IllegalStateException(\"Create user is a POST operation\");\n   }    \n}\n"
  },
  {
    "path": "apis/openstack-trove/src/main/java/org/jclouds/openstack/trove/v1/binders/BindGrantUserToJson.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.trove.v1.binders;\n\nimport java.util.List;\nimport java.util.Map;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.MapBinder;\nimport org.jclouds.rest.binders.BindToJsonPayload;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Lists;\nimport com.google.common.collect.Maps;\nimport com.google.inject.Inject;\n\npublic class BindGrantUserToJson implements MapBinder {\n    \n    @Inject\n    private BindToJsonPayload jsonBinder;\n    \n    @SuppressWarnings(\"unchecked\")\n    @Override    \n    public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n       List<String> databases = Lists.newArrayList();\n       if (postParams.get(\"databaseName\") != null) {\n          databases.add((String)postParams.get(\"databaseName\"));\n       }\n       else if (postParams.get(\"databases\") != null) {\n          databases = (List<String>) postParams.get(\"databases\");\n       }\n       \n       List<Map<String, String>> databaseList = Lists.newArrayList();\n       for (String databaseName : databases) {\n           Map<String, String> singleDatabase = Maps.newHashMap();\n           singleDatabase.put(\"name\", databaseName);\n           databaseList.add(singleDatabase);\n       }\n       return jsonBinder.bindToRequest(request, ImmutableMap.of(\"databases\", databaseList));\n    }\n\n    @Override\n    public <R extends HttpRequest> R bindToRequest(R request, Object toBind) {\n       throw new IllegalStateException(\"Grant user is a PUT operation\");\n    }    \n}\n"
  },
  {
    "path": "apis/openstack-trove/src/main/java/org/jclouds/openstack/trove/v1/config/TroveHttpApiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.trove.v1.config;\n\nimport java.net.URI;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.annotation.ClientError;\nimport org.jclouds.http.annotation.Redirection;\nimport org.jclouds.http.annotation.ServerError;\nimport org.jclouds.json.config.GsonModule.DateAdapter;\nimport org.jclouds.json.config.GsonModule.Iso8601DateAdapter;\nimport org.jclouds.openstack.keystone.auth.domain.AuthInfo;\nimport org.jclouds.openstack.keystone.v2_0.domain.Access;\nimport org.jclouds.openstack.keystone.v2_0.domain.Tenant;\nimport org.jclouds.openstack.keystone.v3.domain.Token;\nimport org.jclouds.openstack.trove.v1.TroveApi;\nimport org.jclouds.openstack.trove.v1.handlers.TroveErrorHandler;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.config.HttpApiModule;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.Multimap;\nimport com.google.inject.Provides;\n\n/**\n * Configures the Trove connection.\n */\n@ConfiguresHttpApi\npublic class TroveHttpApiModule extends HttpApiModule<TroveApi> {\n   \n   @Override\n   protected void configure() {\n      bind(DateAdapter.class).to(Iso8601DateAdapter.class);\n      super.configure();\n   }\n   \n   @Provides\n   @Singleton\n   public final Multimap<URI, URI> aliases() {\n      return ImmutableMultimap.<URI, URI>builder().build();\n   }\n\n   @Override\n   protected void bindErrorHandlers() {\n      bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(TroveErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(TroveErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(TroveErrorHandler.class);\n   }\n   \n   @Provides\n   final Supplier<Optional<String>> supplyTenant(Supplier<AuthInfo> access) {\n      return Suppliers.compose(GetTenant.INSTANCE, access);\n   }\n   \n   private static enum GetTenant implements Function<AuthInfo, Optional<String>> {\n      INSTANCE;\n      public Optional<String> apply(AuthInfo in) {\n         if (in instanceof Access) {\n            return Access.class.cast(in).getToken().getTenant().transform(new Function<Tenant, String>() {\n               @Override\n               public String apply(Tenant input) {\n                  return input.getId();\n               }\n            });\n         } else if (in instanceof Token) {\n            // FIXME: What if user authenticated scoped to another project?\n            return Optional.of(Token.class.cast(in).user().defaultProjectId());\n         }\n         return Optional.absent();\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/main/java/org/jclouds/openstack/trove/v1/config/TroveParserModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.trove.v1.config;\n\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.json.config.GsonModule.DateAdapter;\n\nimport com.google.inject.AbstractModule;\n\npublic class TroveParserModule extends AbstractModule {\n   @Override\n   protected void configure() {\n      bind(DateAdapter.class).to(GsonModule.Iso8601DateAdapter.class);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/main/java/org/jclouds/openstack/trove/v1/domain/Flavor.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.trove.v1.domain;\n\nimport java.beans.ConstructorProperties;\nimport java.util.List;\n\nimport org.jclouds.openstack.v2_0.domain.Link;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableList;\n\n/**\n * An Openstack Trove Flavor.\n */\npublic class Flavor implements Comparable<Flavor>{\n\n   private final int id;\n   private final Optional<String> name;\n   private final int ram;\n   private final List<Link> links;\n\n   @ConstructorProperties({\n      \"id\", \"name\", \"ram\", \"links\"\n   })\n   protected Flavor(int id, String name, int ram, List<Link> links) {\n      this.id = id;\n      this.name = Optional.fromNullable(name);\n      this.ram = ram;\n      this.links = links;\n   }\n\n   /**\n    * @return the id of this flavor.\n    */\n   public int getId() {\n      return this.id;\n   }\n\n   /**\n    * @return the name of this flavor.\n    */\n   public String getName() {\n      return this.name.orNull();\n   }\n\n   /**\n    * @return the RAM amount for this flavor.\n    */\n   public int getRam() {\n      return this.ram;\n   }\n\n   /**\n    * @return the flavor links for this flavor. These are used during database instance creation.\n    */\n   public List<Link> getLinks() {\n      return this.links;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Flavor that = Flavor.class.cast(obj);\n      return Objects.equal(this.id, that.id);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"name\", name).add(\"ram\", ram);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int compareTo(Flavor that) {\n      if (that == null)\n         return 1;\n      if (this == that)\n         return 0;\n      return this.getId() > that.getId() ? +1 : this.getId() < that.getId() ? -1 : 0;\n   }\n\n   public static Builder builder() { \n      return new Builder();\n   }\n\n   public Builder toBuilder() { \n      return new Builder().fromFlavor(this);\n   }    \n\n   public static class Builder {\n      protected int id;\n      protected String name;\n      protected int ram;\n      protected List<Link> links;\n\n      /** \n       * @see Flavor#getId()\n       */\n      public Builder id(int id) {\n         this.id = id;\n         return this;\n      }\n\n      /** \n       * @see Flavor#getName()\n       */\n      public Builder name(String name) {\n         this.name = name;\n         return this;\n      }\n\n      /** \n       * @see Flavor#getRam()\n       */\n      public Builder ram(int ram) {\n         this.ram = ram;\n         return this;\n      }\n\n      /** \n       * @see Flavor#getLinks()\n       */\n      public Builder links(List<Link> links) {\n         this.links = ImmutableList.copyOf(links);\n         return this;\n      }\n\n      public Flavor build() {\n         return new Flavor(id, name, ram, links);\n      }\n\n      public Builder fromFlavor(Flavor in) {\n         return this\n               .id(in.getId())\n               .name(in.getName())\n               .ram(in.getRam())\n               .links(in.getLinks());\n      }\n   }    \n}\n"
  },
  {
    "path": "apis/openstack-trove/src/main/java/org/jclouds/openstack/trove/v1/domain/Instance.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.trove.v1.domain;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport java.beans.ConstructorProperties;\nimport java.util.List;\n\nimport org.jclouds.openstack.trove.v1.internal.Volume;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableList;\n\n/**\n * An Openstack Trove Database Instance.\n */\npublic class Instance implements Comparable<Instance>{\n\n   private final String id;\n   private final String name;\n   private final Flavor flavor;\n   private final Volume volume;\n   private final Status status;\n   private final List<Link> links;\n   private final String hostname;\n\n   @ConstructorProperties({\n      \"id\", \"name\", \"flavor\", \"volume\", \"status\", \"links\", \"hostname\"\n   })\n   protected Instance(String id, String name, Flavor flavor, Volume volume, Status status, List<Link> links, String hostname) {\n      this.id = checkNotNull(id, \"id required\");\n      this.name = checkNotNull(name, \"name required\");\n      this.flavor = checkNotNull(flavor, \"flavor required\");\n      this.volume =  checkNotNull(volume, \"volume required\");\n      checkArgument(volume.getSize() > 0, \"Size must be greater than 0\");\n      this.status = checkNotNull(status, \"status required\");\n      this.links = checkNotNull(links, \"links required\");\n      this.hostname = hostname; // Hostname is sometimes null. See Instance#getHostname() for details\n   }\n\n   /**\n    * @return the id of this instance.\n    */\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * @return the name of this instance.\n    * @see Instance.Builder#name(String)\n    */\n   public String getName() {\n      return this.name;\n   }\n\n   /**\n    * @return the flavor of this instance.\n    * @see Instance.Builder#flavor(Flavor)\n    */\n   public Flavor getFlavor() {\n      return this.flavor;\n   }\n\n   /**\n    * @return the volume size for this instance in gigabytes (GB).\n    * @see Instance.Builder#size(int)\n    */\n   public int getSize() {\n      return this.volume.getSize();\n   }\n\n   /**\n    * @return the status for this instance.\n    * @see Instance.Builder#status(Instance.Status)\n    */\n   public Status getStatus() {\n      return this.status;\n   }\n\n   /**\n    * @return the Links for this instance.\n    * @see Instance.Builder#links(ImmutableList)\n    */\n   public List<Link> getLinks() {\n      return this.links;\n   }\n   \n   /**\n    * @return the hostname of this instance. The hostname is null unless this Instance was obtained with {@link InstanceApi#get(String)}.\n    * @see Instance.Builder#hostname(String)\n    */\n   public String getHostname() {\n      return this.hostname;\n   }\n\n   /**\n    * Lists possible Instance status.\n    *\n    */\n   public enum Status {\n      /**\n       * The database instance is being provisioned.\n       * */\n      BUILD, \n      /**\n       * The database instance is rebooting.\n       */\n      REBOOT,\n      /**\n       * The database instance is online and available to take requests.\n       * */\n      ACTIVE,\n      /**\n       * The database instance is unresponsive at the moment.\n       */\n      BLOCKED,\n      /**\n       * The database instance is being resized at the moment.\n       */\n      RESIZE,\n      /**\n       * The database instance is terminating services. Also, SHUTDOWN is returned if for any reason the instance is shut down but not the actual server.\n       */\n      SHUTDOWN, \n      /**\n       * Unrecognized status response.\n       */\n      UNRECOGNIZED;\n\n      public String value() {\n         return name();\n      }\n\n      @Override\n      public String toString() {\n         return value();\n      }\n\n      public static Status fromValue(String status) {\n         try {\n            return valueOf(checkNotNull(status, \"type\"));\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, name, volume.getSize(), flavor, status, links, hostname);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Instance that = Instance.class.cast(obj);\n      return Objects.equal(this.id, that.id);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"name\", name).add(\"flavor\", flavor).add(\"volume size\", volume.getSize()).add(\"links\", links).add(\"hostname\", hostname);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   public static Builder builder() { \n      return new Builder();\n   }\n\n   public Builder toBuilder() { \n      return new Builder().fromInstance(this);\n   }\n\n   public static class Builder {\n      protected String id;\n      protected String name;\n      protected int size;\n      protected Flavor flavor;\n      protected Status status;\n      protected ImmutableList<Link> links;\n      protected String hostname;\n\n      /** \n       * @param id The id of this instance.\n       * @return The builder object.\n       * @see Instance#getId()\n       */\n      public Builder id(String id) {\n         this.id = id;\n         return this;\n      }\n\n      /** \n       * @param name The name of this instance.\n       * @return The builder object.\n       * @see Instance#getName()\n       */\n      public Builder name(String name) {\n         this.name = name;\n         return this;\n      }\n\n      /** \n       * @param size Specifies the volume size in gigabytes (GB).\n       * @return The builder object.\n       * @see Instance#getSize()\n       */\n      public Builder size(int size) {\n         this.size = size;\n         return this;\n      }\n\n      /** \n       * @param flavor The Flavor of this instance as specified in the response from the List Flavors API call.\n       * @return The builder object.\n       * @see Instance#getFlavor()\n       */\n      public Builder flavor(Flavor flavor) {\n         this.flavor = flavor;\n         return this;\n      }\n\n      /** \n       * @param status The status of this instance.\n       * @return The builder object.\n       * @see Instance#getStatus()\n       */\n      public Builder status(Status status) {\n         this.status = status;\n         return this;\n      }\n\n      /** \n       * @param links The links to this instance.\n       * @return The builder object.\n       * @see Instance#getLinks()\n       */\n      public Builder links(ImmutableList<Link> links) {\n         this.links = links;\n         return this;\n      }\n      \n      /** \n       * @param name The hostname of this instance.\n       * @return The builder object.\n       * @see Instance#getHostname()\n       */\n      public Builder hostname(String hostname) {\n         this.hostname = hostname;\n         return this;\n      }\n\n      /**\n       * \n       * @return A new Instance object.\n       */\n      public Instance build() {\n         return new Instance(id, name, flavor, new Volume(size), status, links, hostname);\n      }\n\n      public Builder fromInstance(Instance in) {\n         return this\n               .id(in.getId())\n               .name(in.getName())\n               .flavor(in.getFlavor())\n               .size(in.getSize())\n               .status(in.getStatus())\n               .links(links)\n               .hostname(hostname);\n      }        \n   }\n\n   @Override\n   public int compareTo(Instance that) {\n      return this.getId().compareTo(that.getId());\n   }   \n}\n"
  },
  {
    "path": "apis/openstack-trove/src/main/java/org/jclouds/openstack/trove/v1/domain/User.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.trove.v1.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport java.beans.ConstructorProperties;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Lists;\nimport com.google.common.collect.Maps;\n\n/**\n * An Openstack Trove Database User.\n */\npublic class User implements Comparable<User>{\n   private final String name;\n   private final String password;\n   private final String host;\n   private final List<Map<String, String>> databases;\n\n   @ConstructorProperties({\n      \"name\", \"password\", \"host\", \"databases\"\n   })\n   protected User(String name, String password, String host, List<Map<String, String>> databases) {\n      this.name = checkNotNull(name, \"name required\");\n      this.password = password;\n      this.host = host;\n      // Set databases to an empty list instead of null\n      if (databases == null) {\n         this.databases = Lists.newArrayList();\n      }\n      else {\n         this.databases = databases;\n      }\n   }    \n\n   protected User(String name, String password, String host, Set<String> databases) {\n      this.name = checkNotNull(name, \"name required\");\n      this.password = password;\n      this.host = host;\n      // Set databases to an empty list instead of null\n      if (databases == null) {\n         this.databases = Lists.newArrayList();\n      }\n      else {\n         // Using List<Map<String, String>> as the internal representation makes it easy to serialize properly\n         // with less code; this code is to present databases as List<String> to the user.\n         List<Map<String, String>> databaseList = Lists.newArrayList();\n         for (String databaseName : databases) {\n            Map<String, String> singleDatabase = Maps.newHashMap();\n            singleDatabase.put(\"name\", databaseName);\n            databaseList.add(singleDatabase);\n         }\n         this.databases = ImmutableList.copyOf(databaseList);\n      }\n   }   \n\n   /**\n    * @return the name of this user. The name is not a unique or even sufficient identifier in some cases.\n    * @see User#getIdentifier()\n    * @see User.Builder#name(String)\n    */\n   public String getName() {\n      return this.name;\n   }   \n   \n   /**\n    * @return the password for this user.\n    * @see User.Builder#password(String)\n    */\n   public String getPassword() {\n      return this.password;\n   }\n   \n   /**\n    * @return the host for this user.\n    * @see User.Builder#host(String)\n    */\n   public String getHost() {\n      return this.host;\n   }\n   \n   /**\n    * @return a unique identifier for this user. In most cases, this is just the name. If the user is restricted to connections from a specific host, the hostname must be appended to the user name with a \"@\".\n    */\n   public String getIdentifier() {\n      if (host == null || \"%\".equals(host))\n         return name;\n      else \n         return name + \"@\" + host;\n   }\n\n   /**\n    * @return the databases for this user.\n    * @see User.Builder#databases(String)\n    */\n   public List<String> getDatabases() {\n      List<String> databaseList = Lists.newArrayList();\n      for (Map<String, String> database : this.databases) {\n         databaseList.add(database.get(\"name\"));\n      }\n      return ImmutableList.copyOf(databaseList);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(name, password, databases);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      User that = User.class.cast(obj);\n      return Objects.equal(this.name, that.name) && \n            Objects.equal(this.password, that.password) &&\n            Objects.equal(this.host, that.host) &&\n            Objects.equal(this.databases, that.databases);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"name\", name)\n            .add(\"password\", password)\n            .add(\"host\", host)\n            .add(\"databases\", databases);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   public static Builder builder() { \n      return new Builder();\n   }\n\n   public Builder toBuilder() { \n      return new Builder().fromUser(this);\n   }\n\n   public static class Builder {\n      protected String name;\n      protected String password;\n      protected String host;\n      protected Set<String> databases;\n      \n      /** \n       * @param name The name of this user.\n       * @return The builder object.\n       * @see User#getName()\n       */\n      public Builder name(String name) {\n         this.name = name;\n         return this;\n      }\n\n      /** \n       * @param name The password for this user.\n       * @return The builder object.\n       * @see User#getPassword()\n       */\n      public Builder password(String password) {\n         this.password = password;\n         return this;\n      }\n      \n      /** \n       * @param host Specifies the host from which a user is allowed to connect to the database. \n       * Possible values are a string containing an IPv4 address or \"%\" to allow connecting from any host. \n       * Refer to Section 3.11.1, “User Access Restriction by Host” in the Rackspace Cloud Databases Developer Guide for details.\n       * If host is not specified, it defaults to \"%\".\n       * @return The builder object.\n       * @see <a href=\"http://docs.rackspace.com/cdb/api/v1.0/cdb-devguide/content/user_access_restrict_by_host-dle387.html\">User Access Restriction by Host</a>\n       * @see User#getHost()\n       */\n      public Builder host(String host) {\n         this.host = host;\n         return this;\n      }\n\n      /** \n       * @param name The databases for this user.\n       * @return The builder object.\n       * @see User#getDatabases()\n       */\n      public Builder databases(Set<String> databases) {\n         this.databases = databases;\n         return this;\n      }\n\n      /**\n       * \n       * @return A new User object.\n       */\n      public User build() {\n         return new User(name, password, host, databases);\n      }\n\n      public Builder fromUser(User in) {\n         return this\n               .name(in.getName())\n               .password(in.getPassword())\n               .host(in.getHost())\n               .databases(ImmutableSet.copyOf( in.getDatabases() ));\n      }        \n   }\n\n   @Override\n   public int compareTo(User that) {\n      return this.getName().compareTo(that.getName());\n   }\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/main/java/org/jclouds/openstack/trove/v1/features/DatabaseApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.trove.v1.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyFluentIterableOnNotFoundOr404;\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.trove.v1.binders.BindCreateDatabaseToJson;\nimport org.jclouds.openstack.trove.v1.functions.ParseDatabaseListForUser;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SkipEncoding;\n\nimport com.google.common.collect.FluentIterable;\n\n/**\n * This API is for creating, listing, and deleting a Database\n *\n */\n@SkipEncoding({'/', '='})\n@RequestFilters(AuthenticateRequest.class)\npublic interface DatabaseApi {\n\n   /**\n    * Same as create(String, null, null)\n    * @see DatabaseApi#create(String, String, String)\n    */\n   @Named(\"database:create\")\n   @POST\n   @Path(\"/databases\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @MapBinder(BindCreateDatabaseToJson.class)\n   void create(@PayloadParam(\"database\") String database);\n\n   /**\n    * This operation creates a new database within the specified instance.\n    *\n    * @param database The name of the database to be created\n    * @param character_set Optional. Set of symbols and encodings. The default character set is utf8.\n    * @param collate Optional. Set of rules for comparing characters in a character set. The default value for collate is utf8_general_ci.\n    * @return true if successful.\n    */\n   @Named(\"database:create\")\n   @POST\n   @Path(\"/databases\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @MapBinder(BindCreateDatabaseToJson.class)\n   void create(@PayloadParam(\"database\") String database, @PayloadParam(\"character_set\") String character_set, @PayloadParam(\"collate\") String collate);\n\n   /**\n    * This operation deletes the specified database for the specified database instance.\n    *\n    * @param databaseName The name for the specified database.\n    * @return true if successful.\n    */\n   @Named(\"databases:delete\")\n   @DELETE\n   @Path(\"/databases/{name}\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean delete(@PathParam(\"name\") String databaseName);\n\n   /**\n    * This operation lists the databases for the specified database instance.\n    *\n    * @return The list of Databases.\n    */\n   @Named(\"database:list\")\n   @GET\n   @Path(\"/databases\")\n   @ResponseParser(ParseDatabaseListForUser.class)\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<String> list();\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/main/java/org/jclouds/openstack/trove/v1/features/FlavorApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.trove.v1.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyFluentIterableOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.trove.v1.domain.Flavor;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.SkipEncoding;\n\nimport com.google.common.collect.FluentIterable;\n\n/**\n * This API strictly for listing and retrieving Flavor. Flavors cannot be created or deleted.\n *\n * @see Flavor\n */\n@SkipEncoding({'/', '='})\n@RequestFilters(AuthenticateRequest.class)\npublic interface FlavorApi {\n   /**\n    * Returns a summary list of Flavors.\n    *\n    * @return The list of Flavors.\n    */\n   @Named(\"flavor:list\")\n   @GET\n   @Path(\"/flavors\")\n   @SelectJson(\"flavors\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<Flavor> list();\n\n   /**\n    * Returns a Flavor by id.\n    *\n    * @param flavorId The id of the Flavor.\n    * @return Flavor The Flavor for the specified id.\n    */\n   @Named(\"flavors:get/{id}\")\n   @GET\n   @Path(\"/flavors/{id}\")\n   @SelectJson(\"flavor\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   Flavor get(@PathParam(\"id\") int flavorId);\n\n   /**\n    * Returns a list of Flavors by Account ID (Tenant Id).\n    *\n    * @param flavorId The id of the tenant.\n    * @return The list of Flavors for Account/Tenant Id.\n    */\n   @Named(\"flavors:get/{id}\")\n   @GET\n   @Path(\"/flavors/{id}\")\n   @SelectJson(\"flavors\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<Flavor> list(@PathParam(\"id\") String accountId);\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/main/java/org/jclouds/openstack/trove/v1/features/InstanceApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.trove.v1.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyFluentIterableOnNotFoundOr404;\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.trove.v1.binders.BindCreateInstanceToJson;\nimport org.jclouds.openstack.trove.v1.domain.Instance;\nimport org.jclouds.openstack.trove.v1.functions.ParsePasswordFromRootedInstance;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.SkipEncoding;\n\nimport com.google.common.collect.FluentIterable;\n\n/**\n * This API is for creating, listing, and deleting an Instance, and allows enabling a root user.\n\n * @see Instance\n */\n@SkipEncoding({'/', '='})\n@RequestFilters(AuthenticateRequest.class)\npublic interface InstanceApi {\n\n   /**\n    * Same as {@link #create(String, int, String)} but accept an integer Flavor ID.\n    *\n    * @param flavor The flavor ID.\n    * @param volumeSize The size in GB of the instance volume.\n    * @param name The name of the instance.\n    * @return The instance created.\n    *\n    * @see InstanceApi#create(String, int, String)\n    */\n   @Named(\"instance:create\")\n   @POST\n   @Path(\"/instances\")\n   @SelectJson(\"instance\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @MapBinder(BindCreateInstanceToJson.class)\n   Instance create(@PayloadParam(\"flavorRef\") int flavor, @PayloadParam(\"size\") int volumeSize, @PayloadParam(\"name\") String name);\n\n   /**\n    * Create a database instance by flavor type and volume size.\n    *\n    * @param flavor The flavor URL or flavor id as string.\n    * @param volumeSize The size in GB of the instance volume.\n    * @param name The name of the instance.\n    * @return The instance created.\n    */\n   @Named(\"instance:create\")\n   @POST\n   @Path(\"/instances\")\n   @SelectJson(\"instance\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @MapBinder(BindCreateInstanceToJson.class)\n   Instance create(@PayloadParam(\"flavorRef\") String flavor, @PayloadParam(\"size\") int volumeSize, @PayloadParam(\"name\") String name);\n\n   /**\n    * Deletes an Instance by id.\n    *\n    * @param instanceId The instance id.\n    * @return true if successful.\n    */\n   @Named(\"instances:delete/{id}\")\n   @DELETE\n   @Path(\"/instances/{id}\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean delete(@PathParam(\"id\") String instanceId);\n\n   /**\n    * Enables root for an instance.\n    *\n    * @param instanceId The instance id.\n    * @return String The password for the root user.\n    */\n   @Named(\"instances/{id}/root\")\n   @POST\n   @Path(\"/instances/{id}/root\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @ResponseParser(ParsePasswordFromRootedInstance.class)\n   String enableRoot(@PathParam(\"id\") String instanceId);\n\n   /**\n    * Checks to see if root is enabled for an instance.\n    *\n    * @param instanceId The instance id.\n    * @throws ResourceNotFoundException\n    * @return boolean True if root is enabled.\n    */\n   @Named(\"instances/{id}/root\")\n   @GET\n   @Path(\"/instances/{id}/root\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @SelectJson(\"rootEnabled\")\n   boolean isRooted(@PathParam(\"id\") String instanceId);\n\n   /**\n    * Returns a summary list of Instances.\n    *\n    * @return The list of Instances.\n    */\n   @Named(\"instance:list\")\n   @GET\n   @Path(\"/instances\")\n   @SelectJson(\"instances\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<Instance> list();\n\n   /**\n    * Returns an Instance by id.\n    *\n    * @param instanceId The instance id.\n    * @return Instance or Null on not found.\n    */\n   @Named(\"instances:get/{id}\")\n   @GET\n   @Path(\"/instances/{id}\")\n   @SelectJson(\"instance\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Instance get(@PathParam(\"id\") String instanceId);\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/main/java/org/jclouds/openstack/trove/v1/features/UserApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.trove.v1.features;\n\nimport java.util.List;\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyFluentIterableOnNotFoundOr404;\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.trove.v1.binders.BindCreateUserToJson;\nimport org.jclouds.openstack.trove.v1.binders.BindGrantUserToJson;\nimport org.jclouds.openstack.trove.v1.domain.User;\nimport org.jclouds.openstack.trove.v1.filters.EncodeDotsForUserGet;\nimport org.jclouds.openstack.trove.v1.functions.ParseDatabaseListForUser;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.SkipEncoding;\n\nimport com.google.common.collect.FluentIterable;\n\n/**\n * This API is for creating, listing, and deleting a User. Also allows listing, granting, and revoking access permissions for users.\n *\n * @see User\n */\n@SkipEncoding({'/', '='})\n@RequestFilters(AuthenticateRequest.class)\npublic interface UserApi {\n\n   /**\n    * Create database users.\n    * A user is granted all privileges on the specified databases.\n    * The following user name is reserved and cannot be used for creating users: root.\n    * This method can be used to create users with access restrictions by host\n    *\n    * @param users List of users to be created.\n    * @return true if successful.\n    * @see <a href=\"http://docs.rackspace.com/cdb/api/v1.0/cdb-devguide/content/user_access_restrict_by_host-dle387.html\">User Access Restriction by Host</a>\n    */\n   @Named(\"user:create\")\n   @POST\n   @Path(\"/users\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @MapBinder(BindCreateUserToJson.class)\n   void create(@PayloadParam(\"users\") Set<User> users);\n\n   /**\n    * Create a database user by name, password, and database name. Simpler overload for {@link #create(String, Set)}.\n    *\n    * @param userName Name of the user for the database.\n    * @param password User password for database access.\n    * @param databaseName Name of the database that the user can access.\n    * @return true if successful.\n    */\n   @Named(\"user:create\")\n   @POST\n   @Path(\"/users\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @MapBinder(BindCreateUserToJson.class)\n   void create(@PayloadParam(\"name\") String userName, @PayloadParam(\"password\") String password, @PayloadParam(\"databaseName\") String databaseName);\n\n   /**\n    * Create a database user by name, password, and database name. Simpler overload for {@link #create(String, Set)}.\n    *\n    * @param userName Name of the user for the database.\n    * @param password User password for database access.\n    * @param host Specifies the host from which a user is allowed to connect to the database. Possible values are a string containing an IPv4 address or \"%\" to allow connecting from any host. Refer to Section 3.11.1, “User Access Restriction by Host” for details. If host is not specified, it defaults to \"%\".\n    * @param databaseName Name of the database that the user can access.\n    * @return true if successful.\n    */\n   @Named(\"user:create\")\n   @POST\n   @Path(\"/users\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @MapBinder(BindCreateUserToJson.class)\n   void create(@PayloadParam(\"name\") String userName, @PayloadParam(\"password\") String password, @PayloadParam(\"host\") String host, @PayloadParam(\"databaseName\") String databaseName);\n\n   /**\n    * This operation grants access for the specified user to a database for the specified instance.\n    * The user is granted all privileges.\n    *\n    * @param userName The name of the specified user.\n    * @param databases List of the databases that the user should be granted access to.\n    * @return true if successful.\n    */\n   @Named(\"user:grant\")\n   @PUT\n   @Path(\"/users/{name}/databases\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @MapBinder(BindGrantUserToJson.class)\n   void grant(@PathParam(\"name\") String userName, @PayloadParam(\"databases\") List<String> databases);\n\n   /**\n    * This operation grants access for the specified user to a database for the specified instance. Simpler overload for {@link #create(String, Set)}.\n    * The user is granted all privileges.\n    *\n    * @param userName Name of the user for the database.\n    * @param databaseName Name of the database that the user can access.\n    * @return true if successful.\n    */\n   @Named(\"user:grant\")\n   @PUT\n   @Path(\"/users/{name}/databases\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @MapBinder(BindGrantUserToJson.class)\n   void grant(@PathParam(\"name\") String userName, @PayloadParam(\"databaseName\") String databaseName);\n\n   /**\n    * This operation grants access for the specified user to a database for the specified instance.\n    * The user is granted all privileges.\n    *\n    * @param userName Name of the user for the database.\n    * @param databaseName Name of the database that the user can access.\n    * @return true if successful.\n    */\n   @Named(\"user:revoke\")\n   @DELETE\n   @Path(\"/users/{name}/databases/{databaseName}\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean revoke(@PathParam(\"name\") String userName, @PathParam(\"databaseName\") String databaseName);\n\n   /**\n    * This operation deletes the specified user for the specified database instance.\n    *\n    * @param userName The name for the specified user.\n    * @return true if successful.\n    */\n   @Named(\"users:delete/{name}\")\n   @DELETE\n   @Path(\"/users/{name}\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean delete(@PathParam(\"name\") String userName);\n\n   /**\n    * This operation lists the users in the specified database instance.\n    * This operation does not return the system users (database administrators that administer the health of the database). Also, this operation returns the \"root\" user only if \"root\" user has been enabled.\n    *\n    * @return The list of Users.\n    */\n   @Named(\"user:list\")\n   @GET\n   @Path(\"/users\")\n   @SelectJson(\"users\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<User> list();\n\n   /**\n    * This operation shows a list of all databases to which a user has access.\n    *\n    * @param instanceId The instance ID for the specified database instance.\n    * @param userName The name for the specified user.\n    * @return The list of Users.\n    */\n   @Named(\"user:getDatabaseList/{name}\")\n   @GET\n   @Path(\"/users/{name}/databases\")\n   @ResponseParser(ParseDatabaseListForUser.class)\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<String> getDatabaseList(@PathParam(\"name\") String userName);\n\n   /**\n    * Returns a User by identifier.\n    *\n    * @param name The name or identifier for the specified user.\n    * @return User or Null on not found.\n    */\n   @Named(\"user:get/{name}\")\n   @GET\n   @Path(\"/users/{name}\")\n   @RequestFilters(EncodeDotsForUserGet.class)\n   @SelectJson(\"user\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   User get(@PathParam(\"name\") String name);\n\n   /**\n    * Returns a User by name and allowed host.\n    *\n    * @param name The name for the specified user.\n    * @param host The associated hostname.\n    * @return User or Null on not found.\n    */\n   @Named(\"user:get/{name}@{hostname}\")\n   @GET\n   @Path(\"/users/{name}@{hostname}\")\n   @RequestFilters(EncodeDotsForUserGet.class)\n   @SelectJson(\"user\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   User get(@PathParam(\"name\") String name, @PathParam(\"hostname\") String hostname);\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/main/java/org/jclouds/openstack/trove/v1/filters/EncodeDotsForUserGet.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.trove.v1.filters;\n\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpRequestFilter;\n\n/**\n * Encodes \".\" as %2e when getting a user with restricted hostname\n */\n@Singleton\npublic class EncodeDotsForUserGet implements HttpRequestFilter {\n   private final Pattern pattern = Pattern.compile(\"/[^/]*$\"); // From last / to the end of the line \n   \n   @Override\n   public HttpRequest filter(HttpRequest request) throws HttpException {\n      String endpoint = request.getEndpoint().toString();      \n      Matcher matcher = pattern.matcher(endpoint);\n      if (!matcher.find())\n         return request; // do not modify if not found. This however is not expected to happen.\n      String encodable = matcher.group();\n      String encoded = encodable.replace(\".\", \"%2e\");\n      String newEndpoint = matcher.replaceFirst(encoded);\n      return request.toBuilder().endpoint(newEndpoint).build();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/main/java/org/jclouds/openstack/trove/v1/functions/ParseDatabaseListForUser.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.trove.v1.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport java.util.List;\nimport java.util.Map;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseJson;\nimport com.google.common.base.Function;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.Lists;\nimport com.google.inject.Inject;\n\n/**\n * This parses the list of databases\n */\npublic class ParseDatabaseListForUser implements Function<HttpResponse, FluentIterable<String>> {\n\n   private final ParseJson<Map<String, List<Map<String, String>>>> json;\n\n   @Inject\n   ParseDatabaseListForUser(ParseJson<Map<String, List<Map<String, String>>>> json) {\n      this.json = checkNotNull(json, \"json\");\n   }\n\n   /**\n    * Parses the database list from the json response\n    */\n   public FluentIterable<String> apply(HttpResponse from) {\n      List<String> resultDatabases = Lists.newArrayList();\n      Map<String, List<Map<String, String>>> result = json.apply(from);\n      for (Map<String, String> database : result.get(\"databases\")) {\n         resultDatabases.add(database.get(\"name\"));\n      }\n      return FluentIterable.from(resultDatabases);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/main/java/org/jclouds/openstack/trove/v1/functions/ParsePasswordFromRootedInstance.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.trove.v1.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport java.util.Map;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseJson;\nimport com.google.common.base.Function;\nimport com.google.inject.Inject;\n\n/**\n * This parses the password\n */\npublic class ParsePasswordFromRootedInstance implements Function<HttpResponse, String> {\n\n   private final ParseJson<Map<String, Map<String, String>>> json;\n\n   @Inject\n   ParsePasswordFromRootedInstance(ParseJson<Map<String, Map<String, String>>> json) {\n      this.json = checkNotNull(json, \"json\");\n   }\n\n   /**\n    * Extracts the user password from the json response\n    */\n   public String apply(HttpResponse from) {\n      Map<String, Map<String, String>> result = json.apply(from);\n      if (result.get(\"user\") == null)\n         return null;\n      return result.get(\"user\").get(\"password\");\n   }\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/main/java/org/jclouds/openstack/trove/v1/handlers/TroveErrorHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.trove.v1.handlers;\n\nimport static org.jclouds.http.HttpUtils.closeClientButKeepContentStream;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.InsufficientResourcesException;\nimport org.jclouds.rest.ResourceNotFoundException;\n\n/**\n * This will parse and set an appropriate exception on the command object.\n */\n@Singleton\npublic class TroveErrorHandler implements HttpErrorHandler {\n\n   public void handleError(HttpCommand command, HttpResponse response) {\n      // it is important to always read fully and close streams\n      byte[] data = closeClientButKeepContentStream(response);\n      String message = data != null ? new String(data) : null;\n\n      Exception exception = message != null ? new HttpResponseException(command, response, message)\n               : new HttpResponseException(command, response);\n      message = message != null ? message : String.format(\"%s -> %s\", command.getCurrentRequest().getRequestLine(),\n               response.getStatusLine());\n      switch (response.getStatusCode()) {\n         case 400:\n            if (message.contains(\"quota exceeded\"))\n               exception = new InsufficientResourcesException(message, exception);\n            break;\n         case 401:\n         case 403:\n            exception = new AuthorizationException(message, exception);\n            break;\n         case 404:\n            if (!command.getCurrentRequest().getMethod().equals(\"DELETE\")) {\n               exception = new ResourceNotFoundException(message, exception);\n            }\n            break;\n         case 413:\n            exception = new InsufficientResourcesException(message, exception);\n            break;\n      }\n      command.setException(exception);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/main/java/org/jclouds/openstack/trove/v1/internal/Volume.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.trove.v1.internal;\n\npublic class Volume{\n   private final int size;\n   \n   public Volume(int size){\n      this.size = size;\n   }\n\n   /**\n    * @return the size\n    */\n   public int getSize() {\n      return size;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/main/java/org/jclouds/openstack/trove/v1/predicates/InstancePredicates.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.trove.v1.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static org.jclouds.util.Predicates2.retry;\nimport org.jclouds.openstack.trove.v1.domain.Instance;\nimport org.jclouds.openstack.trove.v1.domain.Instance.Status;\nimport org.jclouds.openstack.trove.v1.features.InstanceApi;\n\nimport com.google.common.base.Predicate;\n\n/**\n * Tests to see if instance has reached status. This class is most useful when paired with a RetryablePredicate as\n * in the code below. This class can be used to block execution until the Instance status has reached a desired state.\n * This is useful when your Instance needs to be 100% ready before you can continue with execution.\n *\n * <pre>\n * {@code\n * Instance instance = instanceApi.create(100);\n *\n * RetryablePredicate<String> awaitAvailable = RetryablePredicate.create(\n *    InstancePredicates.available(instanceApi), 600, 10, 10, TimeUnit.SECONDS);\n *\n * if (!awaitAvailable.apply(instance.getId())) {\n *    throw new TimeoutException(\"Timeout on instance: \" + instance);\n * }\n * }\n * </pre>\n *\n * You can also use the static convenience methods as follows.\n *\n * <pre>\n * {@code\n * Instance instance = instanceApi.create(100);\n *\n * if (!InstancePredicates.awaitAvailable(instanceApi).apply(instance.getId())) {\n *    throw new TimeoutException(\"Timeout on instance: \" + instance);\n * }\n * }\n * </pre>\n */\npublic class InstancePredicates {\n   /**\n    * Wait until an Instance is Available.\n    *\n    * @param instanceApi The InstanceApi in the region where your Instance resides.\n    * @return RetryablePredicate That will check the status every 5 seconds for a maxiumum of 10 minutes.\n    */\n   public static Predicate<Instance> awaitAvailable(InstanceApi instanceApi) {\n      StatusUpdatedPredicate statusPredicate = new StatusUpdatedPredicate(instanceApi, Instance.Status.ACTIVE);\n      return retry(statusPredicate, 600, 5, 5, SECONDS);\n   }\n\n   /**\n    * Wait until an Instance no longer exists.\n    *\n    * @param instanceApi The InstanceApi in the region where your Instance resides.\n    * @return RetryablePredicate That will check whether the Instance exists.\n    * every 5 seconds for a maxiumum of 10 minutes.\n    */\n   public static Predicate<Instance> awaitDeleted(InstanceApi instanceApi) {\n      DeletedPredicate deletedPredicate = new DeletedPredicate(instanceApi);\n      return retry(deletedPredicate, 600, 5, 5, SECONDS);\n   }\n\n   /**\n    * Wait until instance is in the status specified.\n    *\n    * @param instanceApi The InstanceApi in the region where your Instance resides.\n    * @param status Wait until instance in in this status.\n    * @param maxWaitInSec Maximum time to wait.\n    * @param periodInSec Interval between retries.\n    * @return RetryablePredicate That will check whether the Instance exists.\n    */\n   public static Predicate<Instance> awaitStatus(\n         InstanceApi instanceApi, Instance.Status status, long maxWaitInSec, long periodInSec) {\n      StatusUpdatedPredicate statusPredicate = new StatusUpdatedPredicate(instanceApi, status);\n      return retry(statusPredicate, maxWaitInSec, periodInSec, periodInSec, SECONDS);\n   }\n\n   private static class StatusUpdatedPredicate implements Predicate<Instance> {\n      private InstanceApi instanceApi;\n      private Status status;\n\n      public StatusUpdatedPredicate(InstanceApi instanceApi, Instance.Status status) {\n         this.instanceApi = checkNotNull(instanceApi, \"instanceApi must be defined\");\n         this.status = checkNotNull(status, \"status must be defined\");\n      }\n\n      /**\n       * @return boolean Return true when the instance reaches status, false otherwise.\n       */\n      @Override\n      public boolean apply(Instance instance) {\n         checkNotNull(instance, \"instance must be defined\");\n\n         if (status.equals(instance.getStatus())) {\n            return true;\n         }\n         else {\n            Instance instanceUpdated = instanceApi.get(instance.getId());\n            checkNotNull(instanceUpdated, \"Instance %s not found.\", instance.getId());\n\n            return status.equals(instanceUpdated.getStatus());\n         }\n      }\n   }\n\n   private static class DeletedPredicate implements Predicate<Instance> {\n      private InstanceApi instanceApi;\n\n      public DeletedPredicate(InstanceApi instanceApi) {\n         this.instanceApi = checkNotNull(instanceApi, \"instanceApi must be defined\");\n      }\n\n      /**\n       * @return boolean Return true when the snapshot is deleted, false otherwise.\n       */\n      @Override\n      public boolean apply(Instance instance) {\n         checkNotNull(instance, \"instance must be defined\");\n\n         return instanceApi.get(instance.getId()) == null;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/main/java/org/jclouds/openstack/trove/v1/utils/TroveUtils.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.trove.v1.utils;\n\nimport java.util.Arrays;\nimport java.util.UUID;\nimport java.util.concurrent.TimeUnit;\n\nimport jakarta.annotation.Resource;\n\nimport org.jclouds.openstack.trove.v1.TroveApi;\nimport org.jclouds.openstack.trove.v1.domain.Instance;\nimport org.jclouds.openstack.trove.v1.features.InstanceApi;\nimport org.jclouds.openstack.trove.v1.predicates.InstancePredicates;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.util.concurrent.Uninterruptibles;\n\n/**\n *\n * Helper methods for dealing with instances that get created with errors.\n */\npublic class TroveUtils {\n   private final TroveApi api;\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   public TroveUtils(TroveApi api) {\n      this.api = api;\n   }\n\n   /**\n    * Create an ACTIVE operational instance.\n    *\n    * @see InstanceApi#create(String, int, String)\n    *\n    * @param region\n    *           The instance region.\n    * @param name\n    *           Instance name.\n    * @param flavorId\n    *           Id of the flavor to be used when creating the instance.\n    * @param size\n    *           Size of the instance.\n    * @return Instance object in active state or NULL.\n    */\n   public Instance getWorkingInstance(String region, String name, String flavorId, int size) {\n      InstanceApi instanceApi = api.getInstanceApi(region);\n      for (int retries = 0; retries < 10; retries++) {\n         Instance instance = null;\n         try {\n            instance = instanceApi.create(flavorId, size, name);\n         } catch (Exception e) {\n\n            Uninterruptibles.sleepUninterruptibly(15, TimeUnit.SECONDS);\n\n            logger.error(Arrays.toString(e.getStackTrace()));\n            continue;\n         }\n\n         Instance updatedInstance = awaitAvailable(instance, instanceApi);\n         if (updatedInstance != null) {\n            return updatedInstance;\n         }\n         instanceApi.delete(instance.getId());\n         InstancePredicates.awaitDeleted(instanceApi).apply(instance);\n\n      }\n      return null;\n   }\n\n   /**\n    * This will return a small working instance.\n    *\n    * @param region The region where the instance should be created.\n    * @return A working database instance.\n    */\n   public Instance getWorkingInstance(String region) {\n      return getWorkingInstance(region, UUID.randomUUID().toString(), \"1\", 1);\n   }\n\n   private Instance awaitAvailable(Instance instance, InstanceApi iapi) {\n      for (int n = 0; n < 100; n = n + 1) {\n         Instance updatedInstance = iapi.get(instance.getId());\n         if (updatedInstance.getStatus() == Instance.Status.ACTIVE)\n            return updatedInstance;\n         if (updatedInstance.getStatus() == Instance.Status.UNRECOGNIZED)\n            return null; // fast fail\n         Uninterruptibles.sleepUninterruptibly(15, TimeUnit.SECONDS);\n      }\n      return null;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/test/java/org/jclouds/openstack/trove/v1/domain/FlavorTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.trove.v1.domain;\n\nimport org.jclouds.http.Uris;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.Link.Relation;\nimport org.testng.annotations.Test;\nimport com.google.common.collect.ImmutableList;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\n\n@Test(groups = \"unit\", testName = \"FlavorTest\")\npublic class FlavorTest {\n   public void testFlavorForId() {\n      Flavor flavor1 = forId(1);\n      Flavor flavor2 = forId(2);\n      assertEquals(flavor1.getId(), 1);\n      assertEquals(flavor1.getName(), \"small\");\n      assertFalse(flavor1.equals(flavor2));\n   }\n\n   /**\n    * Creates a dummy Flavor when you need a Flavor with just the flavorId.\n    *\n    * 1. name  = small\n    * 2. ram   = 512\n    * 3. links = self, bookmark\n    */\n   public static Flavor forId(int flavorId) {\n       return Flavor.builder()\n               .id(flavorId)\n               .name(\"small\")\n               .ram(512)\n               .links(\n                       ImmutableList.of(\n                               Link.create(Relation.SELF, Uris.uriBuilder(\"http://test1\").build() ),\n                               Link.create(Relation.BOOKMARK, Uris.uriBuilder(\"http://test2\").build() )\n                               ) ).build();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/test/java/org/jclouds/openstack/trove/v1/domain/InstanceTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.trove.v1.domain;\n\nimport org.jclouds.http.Uris;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.Link.Relation;\nimport org.testng.annotations.Test;\nimport com.google.common.collect.ImmutableList;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\n\n@Test(groups = \"unit\", testName = \"InstanceTest\")\npublic class InstanceTest {\n   public void testInstanceForId() {\n      Instance instance1 = forId(\"1\");\n      Instance instance2 = forId(\"2\");\n      assertEquals(instance1.getId(), \"1\");\n      assertEquals(instance1.getName(), \"json\");\n      assertFalse(instance1.equals(instance2));\n   }\n\n   /**\n    * Creates a dummy Instance when you need an Instance with just the instanceId.\n    */\n   public static Instance forId(String instanceId) {\n       return Instance.builder()\n               .id(instanceId)\n               .name(\"json\")\n               .status(Instance.Status.ACTIVE)\n               .size(2)\n               .flavor( FlavorTest.forId(1) )\n               .links(\n                       ImmutableList.of(\n                               Link.create(Relation.SELF, Uris.uriBuilder(\"http://test1\").build() ),\n                               Link.create(Relation.BOOKMARK, Uris.uriBuilder(\"http://test2\").build() )\n                               ) ).build();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/test/java/org/jclouds/openstack/trove/v1/domain/UserTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.trove.v1.domain;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport org.testng.annotations.Test;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\", testName = \"UserTest\")\npublic class UserTest {\n   public void testUserForName() {\n      User user1 = forName(\"1\");\n      User user2 = forName(\"2\");\n      assertEquals(user1.getName(), \"1\");\n      assertEquals(user2.getName(), \"2\");\n      assertFalse(user1.equals(user2));\n   }\n\n   /**\n    * Creates a dummy User when you need an User with just the userName.\n    */\n   public static User forName(String userName) {\n       return User.builder()\n               .name(userName)\n               .password(\"password\")\n               .databases(\n                       ImmutableSet.of(\n                               \"db1\",\n                               \"db2\"\n                               ) ).build();\n   }\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/test/java/org/jclouds/openstack/trove/v1/features/DatabaseApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.trove.v1.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.trove.v1.internal.BaseTroveApiExpectTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests DatabaseApi Guice wiring and parsing\n */\n@Test(groups = \"unit\", testName = \"DatabaseApiExpectTest\")\npublic class DatabaseApiExpectTest extends BaseTroveApiExpectTest {\n\n   public void testCreateDatabaseSimple() {\n      URI endpoint = URI.create(\"http://172.16.0.1:8776/v1/3456/instances/instanceId-1234-5678/databases\");\n      DatabaseApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint)\n            .method(\"POST\")\n            .payload(payloadFromResourceWithContentType(\"/database_create_simple_request.json\", MediaType.APPLICATION_JSON))\n            .build(),\n            HttpResponse.builder().statusCode(202).build() // response\n            ).getDatabaseApi(\"RegionOne\", \"instanceId-1234-5678\");\n\n      api.create(\"testingdb\");\n   }\n\n   public void testCreateDatabase() {\n      URI endpoint = URI.create(\"http://172.16.0.1:8776/v1/3456/instances/instanceId-1234-5678/databases\");\n      DatabaseApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint)\n            .method(\"POST\")\n            .payload(payloadFromResourceWithContentType(\"/database_create_request.json\", MediaType.APPLICATION_JSON))\n            .build(),\n            HttpResponse.builder().statusCode(202).build() // response\n            ).getDatabaseApi(\"RegionOne\", \"instanceId-1234-5678\");\n\n      api.create(\"testingdb\", \"utf8\", \"utf8_general_ci\");\n   }\n   \n   public void testDeleteDatabase() {\n      URI endpoint = URI.create(\"http://172.16.0.1:8776/v1/3456/instances/instanceId-1234-5678/databases/db1\");\n      DatabaseApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint) \n            .method(\"DELETE\")\n            .build(),\n            HttpResponse.builder().statusCode(202).build() // response\n            ).getDatabaseApi(\"RegionOne\", \"instanceId-1234-5678\");\n\n      boolean result = api.delete(\"db1\");\n      assertTrue(result);\n   }\n   \n   public void testListDatabases() {\n      URI endpoint = URI.create(\"http://172.16.0.1:8776/v1/3456/instances/instanceId-1234-5678/databases\");\n      DatabaseApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/database_list.json\")).build()\n      ).getDatabaseApi(\"RegionOne\", \"instanceId-1234-5678\");\n\n      List<String> databases = api.list().toList();\n      assertEquals(databases.size(), 5);\n      assertEquals(databases.iterator().next(), \"anotherdb\");\n   }\n   \n}\n"
  },
  {
    "path": "apis/openstack-trove/src/test/java/org/jclouds/openstack/trove/v1/features/DatabaseApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.trove.v1.features;\n\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.openstack.trove.v1.domain.Instance;\nimport org.jclouds.openstack.trove.v1.internal.BaseTroveApiLiveTest;\nimport org.jclouds.openstack.trove.v1.utils.TroveUtils;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Lists;\nimport com.google.common.collect.Maps;\n\n@Test(groups = \"live\", testName = \"DatabaseApiLiveTest\")\npublic class DatabaseApiLiveTest extends BaseTroveApiLiveTest {\n\n   // region to instance\n   private static Map<String, List<Instance>> instancesToDelete = Maps.newHashMap();\n   // not deleting databases. they will be deleted when instances are deleted\n\n   @Override\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   public void setup() {\n      super.setup();\n      TroveUtils utils = new TroveUtils(api);\n      for (String region : api.getConfiguredRegions()) {\n         // create instances\n         List<Instance> instanceList = Lists.newArrayList();\n         Instance first = utils.getWorkingInstance(region, \"first_database_testing_\" + region, \"1\", 1);\n         Instance second = utils.getWorkingInstance(region, \"second_database_testing_\" + region, \"1\", 1);\n         instanceList.add(first);\n         instanceList.add(second);\n         instancesToDelete.put(region, instanceList);\n\n         DatabaseApi databaseApiFirst = api.getDatabaseApi(region, first.getId());\n         DatabaseApi databaseApiSecond = api.getDatabaseApi(region, second.getId());\n         databaseApiFirst.create(\"livetest_db1\");\n         databaseApiFirst.create(\"livetest_db2\");\n         databaseApiSecond.create(\"livetest_db3\");\n      }\n   }\n\n   @Override\n   @AfterClass(groups = { \"integration\", \"live\" })\n   public void tearDown(){\n      for (String region : api.getConfiguredRegions()) {\n         InstanceApi instanceApi = api.getInstanceApi(region);\n         for (Instance instance : instancesToDelete.get(region)) {\n            if (!instanceApi.delete(instance.getId()))\n               throw new RuntimeException(\"Could not delete a database instance after tests!\");\n         }\n      }\n      super.tearDown();\n   }\n\n   @Test\n   public void testListDatabases() {\n      for (String region : api.getConfiguredRegions()) {\n         InstanceApi instanceApi = api.getInstanceApi(region);\n         assertTrue(instanceApi.list().size() >= 2);\n         for (Instance instance : instancesToDelete.get(region)) {\n            DatabaseApi databaseApi = api.getDatabaseApi(region, instance.getId());\n            if (!instance.getName().contains(\"database_testing\"))\n               continue;\n            assertTrue(databaseApi.list().size() >= 1);\n            for (String database : databaseApi.list()) {\n               assertNotNull(database);\n            }\n         }\n      }\n   }\n\n   @Test\n   public void testDeleteDatabases() {\n      for (String region : api.getConfiguredRegions()) {\n         InstanceApi instanceApi = api.getInstanceApi(region);\n         assertTrue(instanceApi.list().size() >= 2);\n         for (Instance instance : instancesToDelete.get(region)) {\n            DatabaseApi databaseApi = api.getDatabaseApi(region, instance.getId());\n            if (!instance.getName().contains(\"database_testing\"))\n               continue;\n            assertTrue(databaseApi.list().size() >= 1);\n            for (String database : databaseApi.list()) {\n               assertNotNull(database);\n               assertTrue(database.equals(\"livetest_db1\") || database.equals(\"livetest_db2\") || database.equals(\"livetest_db3\") );\n               assertTrue(databaseApi.delete(database));\n               databaseApi.create(database);\n            }\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/test/java/org/jclouds/openstack/trove/v1/features/FlavorApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.trove.v1.features;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\nimport java.util.Set;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.trove.v1.TroveApi;\nimport org.jclouds.openstack.trove.v1.domain.Flavor;\nimport org.jclouds.openstack.trove.v1.internal.BaseTroveApiExpectTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests FlavorApi Guice wiring and parsing\n */\n@Test(groups = \"unit\", testName = \"FlavorApiExpectTest\")\npublic class FlavorApiExpectTest extends BaseTroveApiExpectTest {\n\n   public void testListFlavors() {\n      URI endpoint = URI.create(\"http://172.16.0.1:8776/v1/3456/flavors\");\n      FlavorApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/flavor_list.json\")).build()\n      ).getFlavorApi(\"RegionOne\");\n\n      Set<? extends Flavor> flavors = api.list().toSet();\n      assertEquals(flavors.size(), 6);\n      assertEquals(flavors.iterator().next().getRam(), 512);\n   }\n\n   public void testGetFlavor() {\n      URI endpoint = URI.create(\"http://172.16.0.1:8776/v1/3456/flavors/1\");\n      FlavorApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/flavor_get.json\")).build()\n      ).getFlavorApi(\"RegionOne\");\n\n      Flavor flavor = api.get(1);\n      assertEquals(flavor.getName(), \"512MB Instance\");\n      assertEquals(flavor.getId(), 1);\n      assertEquals(flavor.getRam(), 512);\n      assertEquals(flavor.getLinks().size(), 2);\n   }\n\n   public void testGetFlavorByAccountId() {\n      URI endpoint = URI.create(\"http://172.16.0.1:8776/v1/3456/flavors/40806637803162\");\n      TroveApi troveApi = requestsSendResponses(\n      keystoneAuthWithUsernameAndPasswordAndTenantName,\n      responseWithKeystoneAccess,\n      authenticatedGET().endpoint(endpoint).build(),\n      HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/flavor_list.json\")).build() );\n      FlavorApi api = troveApi.getFlavorApi(\"RegionOne\");\n\n      Set<? extends Flavor> flavors = api.list(troveApi.getCurrentTenantId().get()).toSet();\n      Flavor flavor = flavors.iterator().next();\n      assertEquals(flavor.getName(), \"512MB Instance\");\n      assertEquals(flavor.getId(), 1);\n      assertEquals(flavor.getRam(), 512);\n      assertEquals(flavor.getLinks().size(), 2);\n   }\n\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/test/java/org/jclouds/openstack/trove/v1/features/FlavorApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.trove.v1.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\nimport org.jclouds.openstack.trove.v1.domain.Flavor;\nimport org.jclouds.openstack.trove.v1.internal.BaseTroveApiLiveTest;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\nimport com.google.common.collect.FluentIterable;\n\n@Test(groups = \"live\", testName = \"FlavorApiLiveTest\")\npublic class FlavorApiLiveTest extends BaseTroveApiLiveTest {\n\n    @Override\n    @BeforeClass(groups = { \"integration\", \"live\" })\n    public void setup() {\n        super.setup();\n    }\n\n    private void checkFlavor(Flavor flavor) {\n        assertNotNull(flavor.getId(), \"Id cannot be null for \" + flavor);\n        assertNotNull(flavor.getName(), \"Name cannot be null for \" + flavor);\n    }\n\n    @Test\n    public void testListFlavorsByAccount() {\n        for (String region : api.getConfiguredRegions()) {\n            FlavorApi flavorApi = api.getFlavorApi(region);\n\n            FluentIterable<Flavor> response = flavorApi.list( api.getCurrentTenantId().get()); // tenant id, but referred to as account id.\n            for (Flavor flavor : response) {\n                checkFlavor(flavor);\n            }\n        }\n    }\n\n    @Test\n    public void testListFlavorsByAccountWhenAccountIdNotFound() {\n        for (String region : api.getConfiguredRegions()) {\n            FlavorApi flavorApi = api.getFlavorApi(region);\n            assertTrue(flavorApi.list(\"9999\").isEmpty());\n        }\n    }\n\n    @Test\n    public void testGetFlavor() {\n        for (String region : api.getConfiguredRegions()) {\n            FlavorApi flavorApi = api.getFlavorApi(region);\n            for (Flavor flavor : flavorApi.list()) {\n                Flavor flavorFromGet = flavorApi.get(flavor.getId());\n                assertEquals(flavorFromGet.getId(), flavor.getId());\n                assertEquals(flavorFromGet.getRam(), flavor.getRam());\n                assertEquals(flavorFromGet.getName(), flavor.getName());\n                assertEquals(flavorFromGet.getLinks(), flavor.getLinks());\n            }\n        }\n    }\n\n    @Test\n    public void testGetFlavorWhenNotFound() {\n        for (String region : api.getConfiguredRegions()) {\n            FlavorApi flavorApi = api.getFlavorApi(region);\n            assertNull(flavorApi.get(9999));\n        }\n    }\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/test/java/org/jclouds/openstack/trove/v1/features/InstanceApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.trove.v1.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.Set;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.trove.v1.domain.Instance;\nimport org.jclouds.openstack.trove.v1.internal.BaseTroveApiExpectTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests InstanceApi Guice wiring and parsing\n */\n@Test(groups = \"unit\", testName = \"InstanceApiExpectTest\")\npublic class InstanceApiExpectTest extends BaseTroveApiExpectTest {\n    \n    public void testCreateInstance() {\n        URI endpoint = URI.create(\"http://172.16.0.1:8776/v1/3456/instances\");\n        InstanceApi api = requestsSendResponses(\n                keystoneAuthWithUsernameAndPasswordAndTenantName,\n                responseWithKeystoneAccess,\n                authenticatedGET().endpoint(endpoint) // bad naming convention, you should not be able to change the method to POST\n                .method(\"POST\")\n                .payload(payloadFromResourceWithContentType(\"/instance_create_request.json\", MediaType.APPLICATION_JSON))\n                .build(),\n                HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/instance_create.json\")).build() // response\n                ).getInstanceApi(\"RegionOne\");\n\n        Instance instance = api.create(\"1\", 2, \"json_rack_instance\");\n        assertEquals(instance.getSize(), 2);\n        assertEquals(instance.getName(), \"json_rack_instance\");  \n    }\n    \n    public void testDeleteInstance() {\n        URI endpoint = URI.create(\"http://172.16.0.1:8776/v1/3456/instances/098653ba-218b-47ce-936a-e0b749101f81\");\n        InstanceApi api = requestsSendResponses(\n                keystoneAuthWithUsernameAndPasswordAndTenantName,\n                responseWithKeystoneAccess,\n                authenticatedGET().endpoint(endpoint).method(\"DELETE\").build(),\n                HttpResponse.builder().statusCode(202).build() // response\n                ).getInstanceApi(\"RegionOne\");\n\n        assertTrue( api.delete(\"098653ba-218b-47ce-936a-e0b749101f81\") );\n    }\n    \n   public void testListInstances() {\n      URI endpoint = URI.create(\"http://172.16.0.1:8776/v1/3456/instances\");\n      InstanceApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/instance_list.json\")).build()\n      ).getInstanceApi(\"RegionOne\");\n\n      Set<? extends Instance> instances = api.list().toSet();\n      assertEquals(instances.size(), 2);\n      assertEquals(instances.iterator().next().getSize(), 2);\n   }\n\n   public void testGetInstance() {\n      URI endpoint = URI.create(\"http://172.16.0.1:8776/v1/3456/instances/44b277eb-39be-4921-be31-3d61b43651d7\");\n      InstanceApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/instance_get.json\")).build()\n      ).getInstanceApi(\"RegionOne\");\n\n      Instance instance = api.get(\"44b277eb-39be-4921-be31-3d61b43651d7\");\n      assertEquals(instance.getName(), \"json_rack_instance\");\n      assertEquals(instance.getId(), \"44b277eb-39be-4921-be31-3d61b43651d7\");\n      assertEquals(instance.getLinks().size(), 2);\n      assertEquals(instance.getHostname(), \"e09ad9a3f73309469cf1f43d11e79549caf9acf2.rackspaceclouddb.com\");\n   }\n   \n   public void testEnableRootOnInstance() {\n       URI endpoint = URI.create(\"http://172.16.0.1:8776/v1/3456/instances/44b277eb-39be-4921-be31-3d61b43651d7/root\");\n       InstanceApi api = requestsSendResponses(\n             keystoneAuthWithUsernameAndPasswordAndTenantName,\n             responseWithKeystoneAccess,\n             authenticatedGET().method(\"POST\").endpoint(endpoint).build(),\n             HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/instance_root.json\")).build()\n       ).getInstanceApi(\"RegionOne\");\n\n       String password = api.enableRoot(\"44b277eb-39be-4921-be31-3d61b43651d7\");\n       assertEquals(password, \"12345\");\n    }\n   \n   public void testIsRootInstance() {\n       URI endpoint = URI.create(\"http://172.16.0.1:8776/v1/3456/instances/44b277eb-39be-4921-be31-3d61b43651d7/root\");\n       InstanceApi api = requestsSendResponses(\n             keystoneAuthWithUsernameAndPasswordAndTenantName,\n             responseWithKeystoneAccess,\n             authenticatedGET().endpoint(endpoint).build(),\n             HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/instance_is_rooted.json\")).build()\n       ).getInstanceApi(\"RegionOne\");\n\n       boolean rooted = api.isRooted(\"44b277eb-39be-4921-be31-3d61b43651d7\");\n       assertEquals(rooted, true);\n    }\n   \n   public void testIsRootInstanceFalse() {\n       URI endpoint = URI.create(\"http://172.16.0.1:8776/v1/3456/instances/44b277eb-39be-4921-be31-3d61b43651d7/root\");\n       InstanceApi api = requestsSendResponses(\n             keystoneAuthWithUsernameAndPasswordAndTenantName,\n             responseWithKeystoneAccess,\n             authenticatedGET().endpoint(endpoint).build(),\n             HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/instance_is_rooted_false.json\")).build()\n       ).getInstanceApi(\"RegionOne\");\n\n       Boolean rooted = api.isRooted(\"44b277eb-39be-4921-be31-3d61b43651d7\");\n       assertEquals(rooted.booleanValue(), false);\n    }\n   \n}\n"
  },
  {
    "path": "apis/openstack-trove/src/test/java/org/jclouds/openstack/trove/v1/features/InstanceApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.trove.v1.features;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.openstack.trove.v1.domain.Instance;\nimport org.jclouds.openstack.trove.v1.internal.BaseTroveApiLiveTest;\nimport org.jclouds.openstack.trove.v1.utils.TroveUtils;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.Lists;\nimport com.google.common.collect.Maps;\n\n@Test(groups = \"live\", testName = \"InstanceApiLiveTest\")\npublic class InstanceApiLiveTest extends BaseTroveApiLiveTest {\n\n    private static Map<String, List<Instance>> created = Maps.newHashMap();\n\n    @Override\n    @BeforeClass(groups = { \"integration\", \"live\" })\n    public void setup() {\n        super.setup();\n        TroveUtils utils = new TroveUtils(api);\n        for (String region : api.getConfiguredRegions()) {\n            List<Instance> regionList = Lists.newArrayList();\n            InstanceApi instanceApi = api.getInstanceApi(region);\n            regionList.add(utils.getWorkingInstance(region, \"first_instance_testing_\" + region, \"1\", 1));\n            Instance second = utils.getWorkingInstance(region, \"second_instance_testing_\" + region, \"1\", 1);\n            instanceApi.enableRoot(second.getId());\n            regionList.add(second);\n            created.put(region, regionList);\n        }\n    }\n\n    @Override\n    @AfterClass(groups = { \"integration\", \"live\" })\n    public void tearDown(){\n        for (String region : api.getConfiguredRegions()) {\n            InstanceApi instanceApi = api.getInstanceApi(region);\n            for (Instance instance : created.get(region)){\n                if (!instanceApi.delete(instance.getId()))\n                    throw new RuntimeException(\"Could not delete a database instance after tests!\");\n            }\n        }\n        super.tearDown();\n    }\n\n    private void checkInstance(Instance instance) {\n        assertNotNull(instance.getId(), \"Id cannot be null for \" + instance);\n        checkArgument(instance.getSize() > 0, \"Size must not be 0\");\n    }\n\n    @Test\n    public void testListInstances() {\n        for (String region : api.getConfiguredRegions()) {\n            InstanceApi instanceApi = api.getInstanceApi(region);\n            FluentIterable<Instance> response = instanceApi.list();\n            assertFalse(response.isEmpty());\n            for (Instance instance : response) {\n                checkInstance(instance);\n            }\n        }\n    }\n\n    @Test\n    public void testGetInstance() {\n        for (String region : api.getConfiguredRegions()) {\n            InstanceApi instanceApi = api.getInstanceApi(region);\n            for (Instance instance : instanceApi.list()) {\n                Instance instanceFromGet = instanceApi.get(instance.getId());\n                assertNotNull(instanceFromGet.getHostname());\n                assertNull(instance.getHostname());\n                assertEquals(instanceFromGet.getId(), instance.getId());\n                assertEquals(instanceFromGet.getName(), instance.getName());\n                assertEquals(instanceFromGet.getStatus(), instance.getStatus());\n                assertEquals(instanceFromGet.getFlavor(), instance.getFlavor());\n                assertEquals(instanceFromGet.getSize(), instance.getSize());\n                assertEquals(instanceFromGet.getLinks(), instance.getLinks());\n            }\n        }\n    }\n\n    @Test\n    public void testGetInstanceWhenNotFound() {\n        for (String region : api.getConfiguredRegions()) {\n            InstanceApi instanceApi = api.getInstanceApi(region);\n            assertNull(instanceApi.get(\"9999\"));\n        }\n    }\n\n    @Test\n    public void testGetRootStatus() {\n        for (String region : api.getConfiguredRegions()) {\n            InstanceApi instanceApi = api.getInstanceApi(region);\n            Iterator<Instance> iterator = instanceApi.list().iterator();\n            Instance first;\n            Instance second;\n            do {\n               first = iterator.next();\n            } while(!first.getName().contains(\"instance_testing\"));\n            do {\n               second = iterator.next();\n            } while(!second.getName().contains(\"instance_testing\"));\n            assertTrue(instanceApi.isRooted(first.getId()) || instanceApi.isRooted(second.getId()));\n        }\n    }\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/test/java/org/jclouds/openstack/trove/v1/features/UserApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.trove.v1.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.List;\nimport java.util.Set;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.trove.v1.domain.User;\nimport org.jclouds.openstack.trove.v1.internal.BaseTroveApiExpectTest;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.testng.annotations.Test;\nimport org.testng.collections.Lists;\n\nimport com.google.common.collect.ImmutableSortedSet;\nimport com.google.common.collect.ImmutableSortedSet.Builder;\nimport com.google.common.collect.Sets;\n\n/**\n * Tests UserApi Guice wiring and parsing\n */\n@Test(groups = \"unit\", testName = \"UserApiExpectTest\")\npublic class UserApiExpectTest extends BaseTroveApiExpectTest {\n\n   public void testCreateUserSimple() {\n      URI endpoint = URI.create(\"http://172.16.0.1:8776/v1/3456/instances/instanceId-1234-5678/users\");\n      UserApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint) // bad naming convention, you should not be able to change the method to POST\n            .method(\"POST\")\n            .payload(payloadFromResourceWithContentType(\"/user_create_simple_request.json\", MediaType.APPLICATION_JSON))\n            .build(),\n            HttpResponse.builder().statusCode(202).build() // response\n            ).getUserApi(\"RegionOne\", \"instanceId-1234-5678\");\n\n      api.create(\"dbuser1\", \"password\", \"databaseA\");\n   }\n\n   public void testCreateUserSimpleWithHost() {\n      URI endpoint = URI.create(\"http://172.16.0.1:8776/v1/3456/instances/instanceId-1234-5678/users\");\n      UserApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint) // bad naming convention, you should not be able to change the method to POST\n            .method(\"POST\")\n            .payload(payloadFromResourceWithContentType(\"/user_create_with_host_simple_request.json\", MediaType.APPLICATION_JSON))\n            .build(),\n            HttpResponse.builder().statusCode(202).build() // response\n            ).getUserApi(\"RegionOne\", \"instanceId-1234-5678\");\n\n      api.create(\"dbuser1\", \"password\", \"192.168.64.64\", \"databaseA\");\n   }\n   \n   public void testCreateUser() {\n      URI endpoint = URI.create(\"http://172.16.0.1:8776/v1/3456/instances/instanceId-1234-5678/users\");\n      UserApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint) // bad naming convention, you should not be able to change the method to POST\n            .method(\"POST\")\n            .payload(payloadFromResourceWithContentType(\"/user_create_request.json\", MediaType.APPLICATION_JSON))\n            .build(),\n            HttpResponse.builder().statusCode(202).build() // response\n            ).getUserApi(\"RegionOne\", \"instanceId-1234-5678\");\n\n      Set<String> databases1 = Sets.newHashSet();\n      databases1.add( \"databaseA\" );      \n      Builder<String> databases2builder = ImmutableSortedSet.<String>naturalOrder();\n      databases2builder.add( \"databaseB\" );\n      databases2builder.add( \"databaseC\" );\n      Set<String> databases2 = databases2builder.build();\n      Set<String> databases3 = Sets.newHashSet();\n      databases3.add( \"databaseD\" );\n      User user1 = User.builder().databases( databases1 ).name(\"dbuser1\").password(\"password\").build();\n      User user2 = User.builder().databases( databases2 ).name(\"dbuser2\").password(\"password\").build();\n      User user3 = User.builder().databases( databases3 ).name(\"dbuser3\").password(\"password\").host(\"192.168.64.64\").build();\n      Set<User> users = Sets.newHashSet();\n      users.add(user1);\n      users.add(user2);\n      users.add(user3);\n      \n      api.create(ImmutableSortedSet.<User>naturalOrder().addAll(users).build());\n   }\n\n   @Test(expectedExceptions = ResourceNotFoundException.class)\n   public void testCreateUserFail() {\n      URI endpoint = URI.create(\"http://172.16.0.1:8776/v1/3456/instances/instanceId-1234-5678/users\");\n      UserApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint) // bad naming convention, you should not be able to change the method to POST\n            .method(\"POST\")\n            .payload(payloadFromResourceWithContentType(\"/user_create_request.json\", MediaType.APPLICATION_JSON))\n            .build(),\n            HttpResponse.builder().statusCode(404).build() // response\n            ).getUserApi(\"RegionOne\", \"instanceId-1234-5678\");\n\n      Set<String> databases1 = Sets.newHashSet();\n      databases1.add( \"databaseA\" );\n      Builder<String> databases2builder = ImmutableSortedSet.<String>naturalOrder();\n      databases2builder.add( \"databaseB\" );\n      databases2builder.add( \"databaseC\" );\n      Set<String> databases2 = databases2builder.build();\n      Set<String> databases3 = Sets.newHashSet();\n      databases3.add( \"databaseD\" );\n      User user1 = User.builder().databases( databases1 ).name(\"dbuser1\").password(\"password\").build();\n      User user2 = User.builder().databases( databases2 ).name(\"dbuser2\").password(\"password\").build();\n      User user3 = User.builder().databases( databases3 ).name(\"dbuser3\").password(\"password\").host(\"192.168.64.64\").build();\n      Set<User> users = Sets.newHashSet();\n      users.add(user1);\n      users.add(user2);\n      users.add(user3);\n      \n      api.create( ImmutableSortedSet.<User>naturalOrder().addAll(users).build());\n   }\n\n   public void testGrantUserSimple() {\n      URI endpoint = URI.create(\"http://172.16.0.1:8776/v1/3456/instances/instanceId-1234-5678/users/dbuser1/databases\");\n      UserApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint) // bad naming convention, you should not be able to change the method to POST\n            .method(\"PUT\")\n            .payload(payloadFromResourceWithContentType(\"/user_grant_simple_request.json\", MediaType.APPLICATION_JSON))\n            .build(),\n            HttpResponse.builder().statusCode(202).build() // response\n            ).getUserApi(\"RegionOne\", \"instanceId-1234-5678\");\n\n      api.grant(\"dbuser1\", \"databaseZ\");\n   }\n\n   public void testGrantUser() {\n      URI endpoint = URI.create(\"http://172.16.0.1:8776/v1/3456/instances/instanceId-1234-5678/users/dbuser1/databases\");\n      UserApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint) // bad naming convention, you should not be able to change the method to POST\n            .method(\"PUT\")\n            .payload(payloadFromResourceWithContentType(\"/user_grant_request.json\", MediaType.APPLICATION_JSON))\n            .build(),\n            HttpResponse.builder().statusCode(202).build() // response\n            ).getUserApi(\"RegionOne\", \"instanceId-1234-5678\");\n\n      List<String> databases = Lists.newArrayList();\n      databases.add( \"databaseC\" );\n      databases.add( \"databaseD\" );\n      \n      api.grant(\"dbuser1\", databases);\n   }\n\n   public void testRevokeUser() {\n      URI endpoint = URI.create(\"http://172.16.0.1:8776/v1/3456/instances/instanceId-1234-5678/users/dbuser1/databases/databaseA\");\n      UserApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint) // bad naming convention, you should not be able to change the method to POST\n            .method(\"DELETE\")\n            .build(),\n            HttpResponse.builder().statusCode(202).build() // response\n            ).getUserApi(\"RegionOne\", \"instanceId-1234-5678\");\n\n      boolean result = api.revoke(\"dbuser1\", \"databaseA\");\n      assertTrue(result);\n   }\n   \n   public void testDeleteUser() {\n      URI endpoint = URI.create(\"http://172.16.0.1:8776/v1/3456/instances/instanceId-1234-5678/users/dbuser1\");\n      UserApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint) // bad naming convention, you should not be able to change the method to POST\n            .method(\"DELETE\")\n            .build(),\n            HttpResponse.builder().statusCode(202).build() // response\n            ).getUserApi(\"RegionOne\", \"instanceId-1234-5678\");\n\n      boolean result = api.delete(\"dbuser1\");\n      assertTrue(result);\n   }\n   \n   public void testListUsers() {\n      URI endpoint = URI.create(\"http://172.16.0.1:8776/v1/3456/instances/instanceId-1234-5678/users\");\n      UserApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/trove_user_list.json\")).build()\n      ).getUserApi(\"RegionOne\", \"instanceId-1234-5678\");\n\n      Set<User> users = api.list().toSet();\n      assertEquals(users.size(), 4);\n      assertTrue(users.iterator().next().getDatabases().isEmpty());\n      assertEquals(users.iterator().next().getName(), \"dbuser1\");\n   }\n   \n   public void testUserGetDatabaseList() {\n      URI endpoint = URI.create(\"http://172.16.0.1:8776/v1/3456/instances/instanceId-1234-5678/users/dbuser1/databases\");\n      UserApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/user_list_access.json\")).build()\n      ).getUserApi(\"RegionOne\", \"instanceId-1234-5678\");\n\n      List<String> databases = api.getDatabaseList(\"dbuser1\").toList();\n      assertEquals(databases.size(), 2);\n      assertEquals(databases.iterator().next(), \"databaseA\");\n   }\n   \n   public void testGetUser() {\n      URI endpoint = URI.create(\"http://172.16.0.1:8776/v1/3456/instances/instanceId-1234-5678/users/exampleuser\");\n      UserApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/user_get.json\")).build()\n      ).getUserApi(\"RegionOne\", \"instanceId-1234-5678\");\n\n      User user = api.get(\"exampleuser\");\n      assertEquals(user.getName(), \"exampleuser\");\n      assertEquals(user.getHost(), \"%\");\n      assertEquals(user.getDatabases().size(), 2);\n      assertEquals(user.getDatabases().iterator().next(), \"databaseA\");\n   }\n   \n   public void testGetUserWithHostname() {\n      URI endpoint = URI.create(\"http://172.16.0.1:8776/v1/3456/instances/instanceId-1234-5678/users/example%2euser%40192%2e168%2e64%2e64\");\n      UserApi api = requestsSendResponses(\n            keystoneAuthWithUsernameAndPasswordAndTenantName,\n            responseWithKeystoneAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/user_get_withhost.json\")).build()\n      ).getUserApi(\"RegionOne\", \"instanceId-1234-5678\");\n\n      User user = api.get(\"example.user\", \"192.168.64.64\");\n      assertEquals(user.getName(), \"example.user\");\n      assertEquals(user.getHost(), \"192.168.64.64\");\n      assertEquals(user.getIdentifier(), \"example.user@192.168.64.64\");\n      assertEquals(user.getDatabases().size(), 2);\n      assertEquals(user.getDatabases().iterator().next(), \"databaseA\");\n   }\n   \n}\n"
  },
  {
    "path": "apis/openstack-trove/src/test/java/org/jclouds/openstack/trove/v1/features/UserApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.trove.v1.features;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.UUID;\n\nimport org.jclouds.openstack.trove.v1.domain.Instance;\nimport org.jclouds.openstack.trove.v1.domain.User;\nimport org.jclouds.openstack.trove.v1.internal.BaseTroveApiLiveTest;\nimport org.jclouds.openstack.trove.v1.utils.TroveUtils;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Lists;\nimport com.google.common.collect.Maps;\n\n@Test(groups = \"live\", testName = \"UserApiLiveTest\")\npublic class UserApiLiveTest extends BaseTroveApiLiveTest {\n\n   // region to instance\n   private static Map<String, List<Instance>> instancesToDelete = Maps.newHashMap();\n   // not deleting users. they will be deleted when instances are deleted\n\n   @Override\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   public void setup() {\n      super.setup();\n      TroveUtils utils = new TroveUtils(api);\n      for (String region : api.getConfiguredRegions()) {\n         // create instances\n         List<Instance> instanceList = Lists.newArrayList();\n         Instance first = utils.getWorkingInstance(region, \"first_user_trove_live_testing_\" + region, \"1\", 1);\n         Instance second = utils.getWorkingInstance(region, \"second_user_trove_live_testing_\" + region, \"1\", 1);\n         instanceList.add(first);\n         instanceList.add(second);\n         instancesToDelete.put(region, instanceList);\n         // create users\n         User user1 = User.builder()\n               .name(\"user1\")\n               .password(UUID.randomUUID().toString())\n               .databases(ImmutableSet.of(\n                     \"u1db1\",\n                     \"u1db2\")).build();\n         User user2 = User.builder()\n               .name(\"user2\")\n               .password(UUID.randomUUID().toString())\n               .databases(ImmutableSet.of(\n                     \"u2db1\",\n                     \"u2db2\")).build();\n         User user3 = User.builder()\n               .name(\"user3\")\n               .password(UUID.randomUUID().toString())\n               .host(\"173.203.44.122\")\n               .databases(ImmutableSet.of(\n                     \"u3db1\",\n                     \"u3db2\")).build();\n         UserApi userApiFirst = api.getUserApi(region, first.getId());\n         UserApi userApiSecond = api.getUserApi(region, second.getId());\n         userApiFirst.create(ImmutableSet.of(user1, user2));\n         userApiSecond.create(ImmutableSet.of(user3));\n      }\n   }\n\n   @Override\n   @AfterClass(groups = { \"integration\", \"live\" })\n   public void tearDown(){\n      for (String region : api.getConfiguredRegions()) {\n         InstanceApi instanceApi = api.getInstanceApi(region);\n         for (Instance instance : instancesToDelete.get(region)) {\n            if (!instanceApi.delete(instance.getId()))\n               throw new RuntimeException(\"Could not delete a database instance after tests!\");\n         }\n      }\n      super.tearDown();\n   }\n\n   private void checkUser(User user) {\n      assertNotNull(user.getName(), \"Name cannot be null for \" + user);\n      assertNotNull(user.getHost(), \"Host cannot be null (should be '%' if default) for \" + user);\n      checkArgument(!user.getDatabases().isEmpty(), \"Number of databases must not be 0\");\n   }\n\n   @Test\n   public void testListUsers() {\n      for (String region : api.getConfiguredRegions()) {\n         InstanceApi instanceApi = api.getInstanceApi(region);\n         assertTrue(instanceApi.list().size() >= 2);\n         for (Instance instance : instancesToDelete.get(region)) {\n            UserApi userApi = api.getUserApi(region, instance.getId());\n            if (!instance.getName().contains(\"user_trove_live_testing\"))\n               continue;\n            assertTrue(userApi.list().size() >= 1);\n            for (User user : userApi.list()) {\n               checkUser(user);\n            }\n         }\n      }\n   }\n\n   @Test\n   public void testGetUser() {\n      for (String region : api.getConfiguredRegions()) {\n         InstanceApi instanceApi = api.getInstanceApi(region);\n         assertTrue(instanceApi.list().size() >= 2);\n         for (Instance instance : instancesToDelete.get(region)) {\n            UserApi userApi = api.getUserApi(region, instance.getId());\n            if (!instance.getName().contains(\"user_trove_live_testing\"))\n               continue;\n            assertTrue(userApi.list().size() >= 1);\n            for (User user : userApi.list()) {\n               User userFromGet = userApi.get(user.getIdentifier());\n               assertEquals(userFromGet.getName(), user.getName());\n               assertEquals(userFromGet.getHost(), user.getHost());\n               assertEquals(userFromGet.getIdentifier(), user.getIdentifier());\n               assertEquals(userFromGet.getDatabases(), user.getDatabases());\n               assertEquals(userFromGet, user);\n            }\n         }\n      }\n   }\n\n   @Test\n   public void testGetDatabaseListForUser() {\n      for (String region : api.getConfiguredRegions()) {\n         InstanceApi instanceApi = api.getInstanceApi(region);\n         assertTrue(instanceApi.list().size() >= 2 );\n         for (Instance instance : instancesToDelete.get(region)) {\n            UserApi userApi = api.getUserApi(region, instance.getId());\n            if (!instance.getName().contains(\"user_trove_live_testing\"))\n               continue;\n            assertTrue(userApi.list().size() >= 1);\n            for (User user : userApi.list()) {\n               assertFalse(userApi.getDatabaseList(user.getIdentifier()).isEmpty());\n            }\n         }\n      }\n   }\n\n   @Test\n   public void testGrantAndRevokeAcccessForUser() {\n      for (String region : api.getConfiguredRegions()) {\n         InstanceApi instanceApi = api.getInstanceApi(region);\n         assertTrue(instanceApi.list().size() >= 2);\n         for (Instance instance : instancesToDelete.get(region)) {\n            UserApi userApi = api.getUserApi(region, instance.getId());\n            if (!instance.getName().contains(\"user_trove_live_testing\"))\n               continue;\n            assertTrue(userApi.list().size() >= 1);\n            for (User user : userApi.list()) {\n               userApi.grant(user.getIdentifier(), \"dbA\");\n               userApi.grant(user.getIdentifier(), ImmutableList.of(\n                     \"dbB\",\n                     \"dbC\"));\n\n               Set<String> databases = userApi.getDatabaseList(user.getIdentifier()).toSet();\n               assertTrue(databases.contains(\"dbA\"));\n               assertTrue(databases.contains(\"dbB\"));\n               assertTrue(databases.contains(\"dbC\"));\n\n               userApi.revoke(user.getIdentifier(), \"dbA\");\n               userApi.revoke(user.getIdentifier(), \"dbB\");\n               userApi.revoke(user.getIdentifier(), \"dbC\");\n\n               databases = userApi.getDatabaseList(user.getIdentifier()).toSet();\n               assertFalse(databases.contains(\"dbA\"));\n               assertFalse(databases.contains(\"dbB\"));\n               assertFalse(databases.contains(\"dbC\"));\n            }\n         }\n      }\n   }\n\n   @Test\n   public void testGetUserWhenNotFound() {\n      for (String region : api.getConfiguredRegions()) {\n         String instanceId = instancesToDelete.get(region).iterator().next().getId();\n         UserApi userApi = api.getUserApi(region, instanceId);\n         assertNull(userApi.get(\"9999\"));\n      }\n   }\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/test/java/org/jclouds/openstack/trove/v1/internal/BaseTroveApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.trove.v1.internal;\n\nimport org.jclouds.openstack.trove.v1.TroveApi;\n\n/**\n * Base class for writing Trove Rest Api Expect tests\n */\npublic class BaseTroveApiExpectTest extends BaseTroveExpectTest<TroveApi> {\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/test/java/org/jclouds/openstack/trove/v1/internal/BaseTroveApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.trove.v1.internal;\n\nimport java.util.Properties;\n\nimport org.jclouds.apis.BaseApiLiveTest;\nimport org.jclouds.openstack.keystone.config.KeystoneProperties;\nimport org.jclouds.openstack.trove.v1.TroveApi;\n\n/**\n * Tests behavior of TroveApi\n */\npublic class BaseTroveApiLiveTest extends BaseApiLiveTest<TroveApi> {\n\n   public BaseTroveApiLiveTest() {\n      provider = \"openstack-trove\";\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      setIfTestSystemPropertyPresent(props, KeystoneProperties.CREDENTIAL_TYPE);\n      setIfTestSystemPropertyPresent(props, KeystoneProperties.SERVICE_TYPE);\n      return props;\n   }\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/test/java/org/jclouds/openstack/trove/v1/internal/BaseTroveExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.trove.v1.internal;\n\nimport jakarta.ws.rs.core.MediaType;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.keystone.v2_0.internal.KeystoneFixture;\nimport org.jclouds.rest.internal.BaseRestApiExpectTest;\n\n/**\n * Base class for writing Nova Expect tests\n */\npublic class BaseTroveExpectTest<T> extends BaseRestApiExpectTest<T> {\n   protected HttpRequest keystoneAuthWithUsernameAndPassword;\n   protected HttpRequest keystoneAuthWithUsernameAndPasswordAndTenantName;\n   protected HttpRequest keystoneAuthWithAccessKeyAndSecretKeyAndTenantName;\n   protected String authToken;\n   protected HttpResponse responseWithKeystoneAccess;\n   protected HttpRequest extensionsOfNovaRequest;\n   protected HttpResponse extensionsOfNovaResponse;\n   protected HttpResponse unmatchedExtensionsOfNovaResponse;\n   protected HttpRequest keystoneAuthWithAccessKeyAndSecretKeyAndTenantId;\n   protected String identityWithTenantId;\n\n   public BaseTroveExpectTest() {\n      provider = \"openstack-trove\";\n      keystoneAuthWithUsernameAndPassword = KeystoneFixture.INSTANCE.initialAuthWithUsernameAndPassword(identity,\n            credential);\n      keystoneAuthWithUsernameAndPasswordAndTenantName = KeystoneFixture.INSTANCE.initialAuthWithUsernameAndPasswordAndTenantName(identity,\n            credential);\n      keystoneAuthWithAccessKeyAndSecretKeyAndTenantName = KeystoneFixture.INSTANCE.initialAuthWithAccessKeyAndSecretKeyAndTenantName(identity,\n            credential);\n      keystoneAuthWithAccessKeyAndSecretKeyAndTenantId = KeystoneFixture.INSTANCE.initialAuthWithAccessKeyAndSecretKeyAndTenantId(identity,\n              credential);\n      \n      authToken = KeystoneFixture.INSTANCE.getAuthToken();\n      responseWithKeystoneAccess = KeystoneFixture.INSTANCE.responseWithAccess();\n      // now, createContext arg will need tenant prefix\n      identityWithTenantId = KeystoneFixture.INSTANCE.getTenantId() + \":\" + identity;\n      identity = KeystoneFixture.INSTANCE.getTenantName() + \":\" + identity;\n   }\n\n   @Override\n   protected HttpRequestComparisonType compareHttpRequestAsType(HttpRequest input) {\n      return HttpRequestComparisonType.JSON;\n   }\n   \n   protected HttpRequest.Builder<?> authenticatedGET() {\n      return HttpRequest.builder()\n                        .method(\"GET\")\n                        .addHeader(\"Accept\", MediaType.APPLICATION_JSON)\n                        .addHeader(\"X-Auth-Token\", authToken);\n   }\n   \n   protected HttpRequest.Builder<?> authenticatedPOST() {\n      return HttpRequest.builder()\n                        .method(\"POST\")\n                        .addHeader(\"Accept\", MediaType.APPLICATION_JSON)\n                        .addHeader(\"X-Auth-Token\", authToken);\n   }\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/test/java/org/jclouds/openstack/trove/v1/parse/ParseFlavorListTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.trove.v1.parse;\n\nimport java.util.Set;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.http.Uris;\nimport org.jclouds.json.BaseSetParserTest;\nimport org.jclouds.openstack.trove.v1.domain.Flavor;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.Link.Relation;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\n\n\n@Test(groups = \"unit\", testName = \"ParseFlavorTest\")\npublic class ParseFlavorListTest extends BaseSetParserTest<Flavor> {\n\n   @Override\n   public String resource() {\n      return \"/flavor_list.json\";\n   }\n\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   @SelectJson(\"flavors\")\n   public Set<Flavor> expected() {\n      return ImmutableSet\n            .of(Flavor.builder()\n                  .id(1)\n                  .name(\"512MB Instance\")\n                  .ram(512)\n                  .links(ImmutableList.of(\n                          Link.create(Relation.SELF, Uris.uriBuilder(\"https://localhost:8778/v1.0/811050/flavors/1\").build() ),\n                          Link.create(Relation.BOOKMARK, Uris.uriBuilder(\"https://localhost:8778/flavors/1\").build() )\n                          ))\n                  .build(),\n                  Flavor.builder()\n                  .id(2)\n                  .name(\"1GB Instance\")\n                  .ram(1024)\n                  .links(ImmutableList.of(\n                          Link.create(Relation.SELF, Uris.uriBuilder(\"https://localhost:8778/v1.0/811050/flavors/2\").build() ),\n                          Link.create(Relation.BOOKMARK, Uris.uriBuilder(\"https://localhost:8778/flavors/2\").build() )\n                          ))\n                  .build(),\n                  Flavor.builder()\n                  .id(3)\n                  .name(\"2GB Instance\")\n                  .ram(2048)\n                  .links(ImmutableList.of(\n                          Link.create(Relation.SELF, Uris.uriBuilder(\"https://localhost:8778/v1.0/811050/flavors/3\").build() ),\n                          Link.create(Relation.BOOKMARK, Uris.uriBuilder(\"https://localhost:8778/flavors/3\").build() )\n                          ))\n                  .build(),\n                  Flavor.builder()\n                  .id(4)\n                  .name(\"4GB Instance\")\n                  .ram(4096)\n                  .links(ImmutableList.of(\n                          Link.create(Relation.SELF, Uris.uriBuilder(\"https://localhost:8778/v1.0/811050/flavors/4\").build() ),\n                          Link.create(Relation.BOOKMARK, Uris.uriBuilder(\"https://localhost:8778/flavors/4\").build() )\n                          ))\n                  .build(),\n                  Flavor.builder()\n                  .id(5)\n                  .name(\"8GB Instance\")\n                  .ram(8192)\n                  .links(ImmutableList.of(\n                          Link.create(Relation.SELF, Uris.uriBuilder(\"https://localhost:8778/v1.0/811050/flavors/5\").build() ),\n                          Link.create(Relation.BOOKMARK, Uris.uriBuilder(\"https://localhost:8778/flavors/5\").build() )\n                          ))\n                  .build(),\n                  Flavor.builder()\n                  .id(6)\n                  .name(\"16GB Instance\")\n                  .ram(16384)\n                  .links(ImmutableList.of(\n                          Link.create(Relation.SELF, Uris.uriBuilder(\"https://localhost:8778/v1.0/811050/flavors/6\").build() ),\n                          Link.create(Relation.BOOKMARK, Uris.uriBuilder(\"https://localhost:8778/flavors/6\").build() )\n                          ))\n                  .build());\n   }\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/test/java/org/jclouds/openstack/trove/v1/parse/ParseInstanceListTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.trove.v1.parse;\n\nimport java.util.Set;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.http.Uris;\nimport org.jclouds.json.BaseSetParserTest;\nimport org.jclouds.openstack.trove.v1.domain.Flavor;\nimport org.jclouds.openstack.trove.v1.domain.Instance;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.Link.Relation;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\n\n\n@Test(groups = \"unit\", testName = \"ParseInstanceTest\")\npublic class ParseInstanceListTest extends BaseSetParserTest<Instance> {\n\n   @Override\n   public String resource() {\n      return \"/instance_list.json\";\n   }\n\n   /*\n    * The instance needs to be comparable for this test to work \n    * */\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   @SelectJson(\"instances\")\n   public Set<Instance> expected() {\n      return ImmutableSet\n            .of(Instance.builder()\n                  .id(\"098653ba-218b-47ce-936a-e0b749101f81\")\n                  .name(\"xml_rack_instance\")\n                  .size(2)\n                  .flavor(\n                          Flavor.builder()\n                              .id(1)\n                              .links(ImmutableList.of(\n                                              Link.create(Relation.SELF, Uris.uriBuilder(\"https://ord.databases.api.rackspacecloud.com/v1.0/1234/flavors/1\").build() ),\n                                              Link.create(Relation.BOOKMARK, Uris.uriBuilder(\"https://ord.databases.api.rackspacecloud.com/flavors/1\").build())))\n                              .build()\n                         )\n                  .status(Instance.Status.ACTIVE)\n                  .links(ImmutableList.of(\n                          Link.create(Relation.SELF, Uris.uriBuilder(\"https://ord.databases.api.rackspacecloud.com/v1.0/1234/instances/098653ba-218b-47ce-936a-e0b749101f81\").build() ),\n                          Link.create(Relation.BOOKMARK, Uris.uriBuilder(\"https://ord.databases.api.rackspacecloud.com/instances/098653ba-218b-47ce-936a-e0b749101f81\").build() )\n                          ))\n                  .build(),\n                  Instance.builder()\n                  .id(\"44b277eb-39be-4921-be31-3d61b43651d7\")\n                  .name(\"json_rack_instance\")\n                  .size(2)\n                  .flavor(\n                          Flavor.builder()\n                              .id(1)\n                              .links(ImmutableList.of(\n                                              Link.create(Relation.SELF, Uris.uriBuilder(\"https://ord.databases.api.rackspacecloud.com/v1.0/1234/flavors/1\").build() ),\n                                              Link.create(Relation.BOOKMARK, Uris.uriBuilder(\"https://ord.databases.api.rackspacecloud.com/flavors/1\").build())))\n                              .build()\n                         )\n                  .status(Instance.Status.ACTIVE)\n                  .links(ImmutableList.of(\n                          Link.create(Relation.SELF, Uris.uriBuilder(\"https://ord.databases.api.rackspacecloud.com/v1.0/1234/instances/44b277eb-39be-4921-be31-3d61b43651d7\").build() ),\n                          Link.create(Relation.BOOKMARK, Uris.uriBuilder(\"https://ord.databases.api.rackspacecloud.com/instances/44b277eb-39be-4921-be31-3d61b43651d7\").build() )\n                          ))\n                  .build() \n                  );\n   }\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/test/java/org/jclouds/openstack/trove/v1/parse/ParseUserListTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.trove.v1.parse;\n\nimport java.util.Set;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\nimport org.jclouds.json.BaseSetParserTest;\nimport org.jclouds.openstack.trove.v1.domain.User;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\nimport com.google.common.collect.ImmutableSet;\n\n\n@Test(groups = \"unit\", testName = \"ParseUserTest\")\npublic class ParseUserListTest extends BaseSetParserTest<User> {\n\n   @Override\n   public String resource() {\n      return \"/trove_user_list.json\";\n   }\n\n   /*\n    * The user needs to be comparable for this test to work \n    * */\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   @SelectJson(\"users\")\n   public Set<User> expected() {\n      return ImmutableSet\n            .of(User.builder()\n                  .name(\"dbuser1\")\n                  .host(\"%\")\n                  .build(),\n                  User.builder()\n                  .name(\"dbuser2\")\n                  .host(\"%\")\n                  .databases( ImmutableSet.of( \n                          \"databaseB\",\n                          \"databaseC\") )\n                  .build(),\n                  User.builder().name(\"dbuser3\").host(\"%\").build(),\n                  User.builder().name(\"demouser\").host(\"%\").databases(\n                          ImmutableSet.of(\"sampledb\"))\n                          .build()\n                  );\n   }\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/test/java/org/jclouds/openstack/trove/v1/utils/TroveUtilsExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.trove.v1.utils;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.trove.v1.TroveApi;\nimport org.jclouds.openstack.trove.v1.domain.Instance;\nimport org.jclouds.openstack.trove.v1.internal.BaseTroveApiExpectTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tests TroveUtils\n */\n@Test(groups = \"unit\", testName = \"InstanceApiExpectTest\")\npublic class TroveUtilsExpectTest extends BaseTroveApiExpectTest {\n    \n    public void testHelperCreateInstance() {\n        HttpRequest createInstance = authenticatedGET().endpoint(URI.create(\"http://172.16.0.1:8776/v1/3456/instances\"))\n                                                       .method(\"POST\")\n                                                       .payload(payloadFromResourceWithContentType(\"/instance_create_request.json\", MediaType.APPLICATION_JSON))\n                                                       .build();\n        HttpResponse createInstanceSuccess = HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/instance_create.json\")).build();\n        HttpResponse createInstanceFail = HttpResponse.builder().statusCode(404).payload(payloadFromResource(\"/instance_create.json\")).build();\n        HttpRequest getInstance = authenticatedGET().endpoint(URI.create(\"http://172.16.0.1:8776/v1/3456/instances/44b277eb-39be-4921-be31-3d61b43651d7\")).build();\n        HttpResponse badStatus = HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/instance_get_bad_instance.json\")).build();\n        HttpResponse goodStatus = HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/instance_get.json\")).build();\n        HttpResponse deletedStatus = HttpResponse.builder().statusCode(404).payload(payloadFromResource(\"/instance_get.json\")).build();\n        HttpRequest deleteInstance = authenticatedGET().endpoint(URI.create(\"http://172.16.0.1:8776/v1/3456/instances/44b277eb-39be-4921-be31-3d61b43651d7\")).method(\"DELETE\").build();\n        HttpResponse deleteInstanceResponse = HttpResponse.builder().statusCode(202).build();\n\n        List<HttpRequest> requests = ImmutableList.of(  keystoneAuthWithUsernameAndPasswordAndTenantName, createInstance,     createInstance,     createInstance,        getInstance, deleteInstance,         getInstance,   createInstance,     createInstance,        getInstance);\n        List<HttpResponse> responses = ImmutableList.of(responseWithKeystoneAccess,                       createInstanceFail, createInstanceFail, createInstanceSuccess, badStatus,   deleteInstanceResponse, deletedStatus, createInstanceFail, createInstanceSuccess, goodStatus); \n\n        TroveApi api = orderedRequestsSendResponses(requests, responses);\n\n        TroveUtils utils = new TroveUtils(api);\n        Instance instance = utils.getWorkingInstance(\"RegionOne\", \"json_rack_instance\", \"1\", 2);\n        assertEquals(instance.getSize(), 2);\n        assertEquals(instance.getName(), \"json_rack_instance\");  \n    }\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/test/resources/access_rax_us.json",
    "content": "{\n    \"access\": {\n        \"token\": {\n            \"id\": \"myToken\",\n            \"expires\": \"2012-09-30T17:15:32.000-05:00\",\n            \"tenant\": {\n                \"id\": \"717071\",\n                \"name\": \"717071\"\n            }\n        },\n        \"serviceCatalog\": [\n            {\n                \"endpoints\": [\n                    {\n                        \"tenantId\": \"717071\",\n                        \"publicURL\": \"https://dns.api.rackspacecloud.com/v1.0/717071\"\n                    }\n                ],\n                \"name\": \"cloudDNS\",\n                \"type\": \"rax:dns\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"tenantId\": \"717071\",\n                        \"publicURL\": \"https://monitoring.api.rackspacecloud.com/v1.0/717071\"\n                    }\n                ],\n                \"name\": \"cloudMonitoring\",\n                \"type\": \"rax:monitor\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"region\": \"DFW\",\n                        \"tenantId\": \"717071\",\n                        \"publicURL\": \"https://dfw.servers.api.rackspacecloud.com/v2/717071\",\n                        \"versionInfo\": \"https://dfw.servers.api.rackspacecloud.com/v2\",\n                        \"versionList\": \"https://dfw.servers.api.rackspacecloud.com/\",\n                        \"versionId\": \"2\"\n                    },\n                    {\n                        \"region\": \"ORD\",\n                        \"tenantId\": \"717071\",\n                        \"publicURL\": \"https://ord.servers.api.rackspacecloud.com/v2/717071\",\n                        \"versionInfo\": \"https://ord.servers.api.rackspacecloud.com/v2\",\n                        \"versionList\": \"https://ord.servers.api.rackspacecloud.com/\",\n                        \"versionId\": \"2\"\n                    }\n                ],\n                \"name\": \"cloudServersOpenStack\",\n                \"type\": \"compute\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"region\": \"ORD\",\n                        \"tenantId\": \"717071\",\n                        \"publicURL\": \"https://ord.loadbalancers.api.rackspacecloud.com/v1.0/717071\"\n                    },\n                    {\n                        \"region\": \"DFW\",\n                        \"tenantId\": \"717071\",\n                        \"publicURL\": \"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/717071\"\n                    }\n                ],\n                \"name\": \"cloudLoadBalancers\",\n                \"type\": \"rax:load-balancer\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"region\": \"DFW\",\n                        \"tenantId\": \"717071\",\n                        \"publicURL\": \"https://dfw.databases.api.rackspacecloud.com/v1.0/717071\"\n                    },\n                    {\n                        \"region\": \"ORD\",\n                        \"tenantId\": \"717071\",\n                        \"publicURL\": \"https://ord.databases.api.rackspacecloud.com/v1.0/717071\"\n                    },\n                    {\n                        \"region\": \"SYD\",\n                        \"tenantId\": \"717071\",\n                        \"publicURL\": \"https://syd.databases.api.rackspacecloud.com/v1.0/717071\"\n                    }\n                ],\n                \"name\": \"cloudDatabases\",\n                \"type\": \"rax:database\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"region\": \"DFW\",\n                        \"tenantId\": \"MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\",\n                        \"publicURL\": \"https://storage101.dfw1.clouddrive.com/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\",\n                        \"internalURL\": \"https://snet-storage101.dfw1.clouddrive.com/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\"\n                    },\n                    {\n                        \"region\": \"ORD\",\n                        \"tenantId\": \"MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\",\n                        \"publicURL\": \"https://storage101.ord1.clouddrive.com/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\",\n                        \"internalURL\": \"https://snet-storage101.ord1.clouddrive.com/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\"\n                    }\n                ],\n                \"name\": \"cloudFiles\",\n                \"type\": \"object-store\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"region\": \"DFW\",\n                        \"tenantId\": \"MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\",\n                        \"publicURL\": \"https://cdn1.clouddrive.com/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\"\n                    },\n                    {\n                        \"region\": \"ORD\",\n                        \"tenantId\": \"MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\",\n                        \"publicURL\": \"https://cdn2.clouddrive.com/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\"\n                    }\n                ],\n                \"name\": \"cloudFilesCDN\",\n                \"type\": \"rax:object-cdn\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"tenantId\": \"717071\",\n                        \"publicURL\": \"https://servers.api.rackspacecloud.com/v1.0/717071\",\n                        \"versionInfo\": \"https://servers.api.rackspacecloud.com/v1.0\",\n                        \"versionList\": \"https://servers.api.rackspacecloud.com/\",\n                        \"versionId\": \"1.0\"\n                    }\n                ],\n                \"name\": \"cloudServers\",\n                \"type\": \"compute\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                         \"publicURL\": \"https://ord.blockstorage.api.rackspacecloud.com/v1/717071\",\n                         \"tenantId\": \"717071\",\n                         \"region\": \"ORD\"\n                    },\n                    {\n                        \"region\": \"DFW\",\n                        \"tenantId\": \"717071\",\n                        \"publicURL\": \"https://dfw.blockstorage.api.rackspacecloud.com/v1/717071\"\n                    }\n                ],\n                \"name\": \"cloudBlockStorage\",\n                \"type\": \"volume\"\n            }\n        ],\n        \"user\": {\n            \"id\": \"224085\",\n            \"roles\": [\n                {\n                    \"id\": \"3\",\n                    \"description\": \"User Admin Role.\",\n                    \"name\": \"identity:user-admin\"\n                }\n            ],\n            \"name\": \"myUsername\",\n            \"RAX-AUTH:defaultRegion\": \"DFW\"\n        }\n    }\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/test/resources/database_create_request.json",
    "content": "{\n    \"databases\": [\n        {    \n            \"character_set\": \"utf8\", \n            \"collate\": \"utf8_general_ci\", \n            \"name\": \"testingdb\"\n        } \n    ]\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/test/resources/database_create_simple_request.json",
    "content": "{\n    \"databases\": [\n        {   \n            \"name\": \"testingdb\"\n        } \n    ]\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/test/resources/database_list.json",
    "content": "{\n    \"databases\": [\n        {\n            \"name\": \"anotherdb\"\n        }, \n        {\n            \"name\": \"nextround\"\n        }, \n        {\n            \"name\": \"oneMoreDB\"\n        }, \n        {\n            \"name\": \"sampledb\"\n        }, \n        {\n            \"name\": \"testingdb\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/test/resources/flavor_get.json",
    "content": "{\n    \"flavor\":{\n        \"id\":1,\n        \"links\":[\n            {\n                \"href\":\"https://ord.databases.api.rackspacecloud.com/v1.0/1234/flavors/1\",\n                \"rel\":\"self\"\n            },\n            {\n                \"href\":\"https://ord.databases.api.rackspacecloud.com/flavors/1\",\n                \"rel\":\"bookmark\"\n            }\n        ],\n        \"name\":\"512MB Instance\",\n        \"ram\":512\n    }\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/test/resources/flavor_list.json",
    "content": "{\n    \"flavors\":[\n        {\n            \"ram\":512,\n            \"id\":1,\n            \"links\":[\n                {\n                    \"href\":\"https://localhost:8778/v1.0/811050/flavors/1\",\n                    \"rel\":\"self\"\n                },\n                {\n                    \"href\":\"https://localhost:8778/flavors/1\",\n                    \"rel\":\"bookmark\"\n                }\n            ],\n            \"name\":\"512MB Instance\"\n        },\n        {\n            \"ram\":1024,\n            \"id\":2,\n            \"links\":[\n                {\n                    \"href\":\"https://localhost:8778/v1.0/811050/flavors/2\",\n                    \"rel\":\"self\"\n                },\n                {\n                    \"href\":\"https://localhost:8778/flavors/2\",\n                    \"rel\":\"bookmark\"\n                }\n            ],\n            \"name\":\"1GB Instance\"\n        },\n        {\n            \"ram\":2048,\n            \"id\":3,\n            \"links\":[\n                {\n                    \"href\":\"https://localhost:8778/v1.0/811050/flavors/3\",\n                    \"rel\":\"self\"\n                },\n                {\n                    \"href\":\"https://localhost:8778/flavors/3\",\n                    \"rel\":\"bookmark\"\n                }\n            ],\n            \"name\":\"2GB Instance\"\n        },\n        {\n            \"ram\":4096,\n            \"id\":4,\n            \"links\":[\n                {\n                    \"href\":\"https://localhost:8778/v1.0/811050/flavors/4\",\n                    \"rel\":\"self\"\n                },\n                {\n                    \"href\":\"https://localhost:8778/flavors/4\",\n                    \"rel\":\"bookmark\"\n                }\n            ],\n            \"name\":\"4GB Instance\"\n        },\n        {\n            \"ram\":8192,\n            \"id\":5,\n            \"links\":[\n                {\n                    \"href\":\"https://localhost:8778/v1.0/811050/flavors/5\",\n                    \"rel\":\"self\"\n                },\n                {\n                    \"href\":\"https://localhost:8778/flavors/5\",\n                    \"rel\":\"bookmark\"\n                }\n            ],\n            \"name\":\"8GB Instance\"\n        },\n        {\n            \"ram\":16384,\n            \"id\":6,\n            \"links\":[\n                {\n                    \"href\":\"https://localhost:8778/v1.0/811050/flavors/6\",\n                    \"rel\":\"self\"\n                },\n                {\n                    \"href\":\"https://localhost:8778/flavors/6\",\n                    \"rel\":\"bookmark\"\n                }\n            ],\n            \"name\":\"16GB Instance\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/test/resources/instance_create.json",
    "content": "{\n    \"instance\": {\n        \"created\": \"2013-03-18T19:09:17\", \n        \"flavor\": {\n            \"id\": \"1\", \n            \"links\": [\n                {\n                    \"href\": \"https://ord.databases.api.rackspacecloud.com/v1.0/1234/flavors/1\", \n                    \"rel\": \"self\"\n                }, \n                {\n                    \"href\": \"https://ord.databases.api.rackspacecloud.com/flavors/1\", \n                    \"rel\": \"bookmark\"\n                }\n            ]\n        }, \n        \"id\": \"44b277eb-39be-4921-be31-3d61b43651d7\", \n        \"links\": [\n            {\n                \"href\": \"https://ord.databases.api.rackspacecloud.com/v1.0/1234/instances/44b277eb-39be-4921-be31-3d61b43651d7\", \n                \"rel\": \"self\"\n            }, \n            {\n                \"href\": \"https://ord.databases.api.rackspacecloud.com/instances/44b277eb-39be-4921-be31-3d61b43651d7\", \n                \"rel\": \"bookmark\"\n            }\n        ], \n        \"name\": \"json_rack_instance\", \n        \"status\": \"BUILD\", \n        \"updated\": \"2013-03-18T19:09:17\", \n        \"volume\": {\n            \"size\": 2\n        }\n    }\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/test/resources/instance_create_request.json",
    "content": "{\n    \"instance\":{\n        \"name\":\"json_rack_instance\",\n        \"volume\":{\n            \"size\":2\n        },\n        \"flavorRef\":\"1\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/test/resources/instance_get.json",
    "content": "{\n    \"instance\": {\n        \"created\": \"2013-03-18T19:09:17\", \n        \"flavor\": {\n            \"id\": \"1\", \n            \"links\": [\n                {\n                    \"href\": \"https://ord.databases.api.rackspacecloud.com/v1.0/1234/flavors/1\", \n                    \"rel\": \"self\"\n                }, \n                {\n                    \"href\": \"https://ord.databases.api.rackspacecloud.com/flavors/1\", \n                    \"rel\": \"bookmark\"\n                }\n            ]\n        }, \n        \"hostname\": \"e09ad9a3f73309469cf1f43d11e79549caf9acf2.rackspaceclouddb.com\",\n        \"id\": \"44b277eb-39be-4921-be31-3d61b43651d7\", \n        \"links\": [\n            {\n                \"href\": \"https://ord.databases.api.rackspacecloud.com/v1.0/1234/instances/44b277eb-39be-4921-be31-3d61b43651d7\", \n                \"rel\": \"self\"\n            }, \n            {\n                \"href\": \"https://ord.databases.api.rackspacecloud.com/instances/44b277eb-39be-4921-be31-3d61b43651d7\", \n                \"rel\": \"bookmark\"\n            }\n        ], \n        \"name\": \"json_rack_instance\", \n        \"status\": \"ACTIVE\", \n        \"updated\": \"2013-03-18T19:09:17\", \n        \"volume\": {\n            \"size\": 2, \n            \"used\": 0.16368598397821188\n        }\n    }\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/test/resources/instance_get_bad_instance.json",
    "content": "{\n    \"instance\": {\n        \"created\": \"2013-03-18T19:09:17\", \n        \"flavor\": {\n            \"id\": \"1\", \n            \"links\": [\n                {\n                    \"href\": \"https://ord.databases.api.rackspacecloud.com/v1.0/1234/flavors/1\", \n                    \"rel\": \"self\"\n                }, \n                {\n                    \"href\": \"https://ord.databases.api.rackspacecloud.com/flavors/1\", \n                    \"rel\": \"bookmark\"\n                }\n            ]\n        }, \n        \"hostname\": \"e09ad9a3f73309469cf1f43d11e79549caf9acf2.rackspaceclouddb.com\",\n        \"id\": \"44b277eb-39be-4921-be31-3d61b43651d7\", \n        \"links\": [\n            {\n                \"href\": \"https://ord.databases.api.rackspacecloud.com/v1.0/1234/instances/44b277eb-39be-4921-be31-3d61b43651d7\", \n                \"rel\": \"self\"\n            }, \n            {\n                \"href\": \"https://ord.databases.api.rackspacecloud.com/instances/44b277eb-39be-4921-be31-3d61b43651d7\", \n                \"rel\": \"bookmark\"\n            }\n        ], \n        \"name\": \"json_rack_instance\", \n        \"status\": \"ERROR\", \n        \"updated\": \"2013-03-18T19:09:17\", \n        \"volume\": {\n            \"size\": 2, \n            \"used\": 0.16368598397821188\n        }\n    }\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/test/resources/instance_is_rooted.json",
    "content": "{\n    \"rootEnabled\": true\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/test/resources/instance_is_rooted_false.json",
    "content": "{\n    \"rootEnabled\": false\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/test/resources/instance_list.json",
    "content": "{\n    \"instances\": [\n        {\n            \"flavor\": {\n                \"id\": \"1\", \n                \"links\": [\n                    {\n                        \"href\": \"https://ord.databases.api.rackspacecloud.com/v1.0/1234/flavors/1\", \n                        \"rel\": \"self\"\n                    }, \n                    {\n                        \"href\": \"https://ord.databases.api.rackspacecloud.com/flavors/1\", \n                        \"rel\": \"bookmark\"\n                    }\n                ]\n            }, \n            \"id\": \"098653ba-218b-47ce-936a-e0b749101f81\", \n            \"links\": [\n                {\n                    \"href\": \"https://ord.databases.api.rackspacecloud.com/v1.0/1234/instances/098653ba-218b-47ce-936a-e0b749101f81\", \n                    \"rel\": \"self\"\n                }, \n                {\n                    \"href\": \"https://ord.databases.api.rackspacecloud.com/instances/098653ba-218b-47ce-936a-e0b749101f81\", \n                    \"rel\": \"bookmark\"\n                }\n            ], \n            \"name\": \"xml_rack_instance\", \n            \"status\": \"ACTIVE\", \n            \"volume\": {\n                \"size\": 2\n            }\n        }, \n        {\n            \"flavor\": {\n                \"id\": \"1\", \n                \"links\": [\n                    {\n                        \"href\": \"https://ord.databases.api.rackspacecloud.com/v1.0/1234/flavors/1\", \n                        \"rel\": \"self\"\n                    }, \n                    {\n                        \"href\": \"https://ord.databases.api.rackspacecloud.com/flavors/1\", \n                        \"rel\": \"bookmark\"\n                    }\n                ]\n            }, \n            \"id\": \"44b277eb-39be-4921-be31-3d61b43651d7\", \n            \"links\": [\n                {\n                    \"href\": \"https://ord.databases.api.rackspacecloud.com/v1.0/1234/instances/44b277eb-39be-4921-be31-3d61b43651d7\", \n                    \"rel\": \"self\"\n                }, \n                {\n                    \"href\": \"https://ord.databases.api.rackspacecloud.com/instances/44b277eb-39be-4921-be31-3d61b43651d7\", \n                    \"rel\": \"bookmark\"\n                }\n            ], \n            \"name\": \"json_rack_instance\", \n            \"status\": \"ACTIVE\", \n            \"volume\": {\n                \"size\": 2\n            }\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/test/resources/instance_root.json",
    "content": "{\n    \"user\": {\n        \"name\": \"root\", \n        \"password\": \"12345\"\n    }\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/test/resources/logback-test.xml",
    "content": "<?xml version=\"1.0\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<configuration scan=\"false\">\n    <appender name=\"FILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <appender name=\"WIREFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds-wire.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <root>\n        <level value=\"warn\" />\n    </root>\n\n    <logger name=\"org.jclouds\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"FILE\" />\n    </logger>\n\n    <logger name=\"jclouds.wire\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n\n    <logger name=\"jclouds.headers\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n\n</configuration>\n"
  },
  {
    "path": "apis/openstack-trove/src/test/resources/logback.xml",
    "content": "<?xml version=\"1.0\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<configuration scan=\"false\">\n    <appender name=\"FILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <appender name=\"WIREFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds-wire.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <root>\n        <level value=\"warn\" />\n    </root>\n\n    <logger name=\"org.jclouds\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"FILE\" />\n    </logger>\n\n    <logger name=\"jclouds.wire\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n\n    <logger name=\"jclouds.headers\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n\n</configuration>\n"
  },
  {
    "path": "apis/openstack-trove/src/test/resources/trove_user_list.json",
    "content": "{\n    \"users\": [\n        {\n            \"databases\": [],\n            \"host\": \"%\", \n            \"name\": \"dbuser1\"\n        }, \n        {\n            \"databases\": [\n                {\n                    \"name\": \"databaseB\"\n                }, \n                {\n                    \"name\": \"databaseC\"\n                }\n            ],\n            \"host\": \"%\",\n            \"name\": \"dbuser2\"\n        }, \n        {\n            \"databases\": [], \n            \"name\": \"dbuser3\",\n            \"host\": \"%\"\n        }, \n        {\n            \"databases\": [\n                {\n                    \"name\": \"sampledb\"\n                }\n            ],\n            \"host\": \"%\",\n            \"name\": \"demouser\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/test/resources/user_create_request.json",
    "content": "{\n    \"users\":[\n        {\n            \"databases\":[\n                {\n                    \"name\":\"databaseA\"\n                }\n            ],\n            \"name\":\"dbuser1\",\n            \"password\":\"password\"\n        },\n        {\n            \"databases\":[\n                {\n                    \"name\":\"databaseB\"\n                },\n                {\n                    \"name\":\"databaseC\"\n                }\n            ],\n            \"name\":\"dbuser2\",\n            \"password\":\"password\"\n        },\n        {\n            \"databases\":[\n                {\n                    \"name\":\"databaseD\"\n                }\n            ],\n            \"name\":\"dbuser3\",\n            \"host\":\"192.168.64.64\",\n            \"password\":\"password\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/test/resources/user_create_simple_request.json",
    "content": "{\n    \"users\":[\n        {\n            \"databases\":[\n                {\n                    \"name\":\"databaseA\"\n                }\n            ],\n            \"name\":\"dbuser1\",\n            \"password\":\"password\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/test/resources/user_create_with_host_simple_request.json",
    "content": "{\n    \"users\":[\n        {\n            \"databases\":[\n                {\n                    \"name\":\"databaseA\"\n                }\n            ],\n            \"name\":\"dbuser1\",\n            \"password\":\"password\",\n            \"host\":\"192.168.64.64\"\n        }\n    ]\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/test/resources/user_get.json",
    "content": "{\n   \"user\": {\n      \"name\": \"exampleuser\",\n      \"host\": \"%\",\n      \"databases\": [\n         {\n            \"name\": \"databaseA\"\n         },\n         {\n            \"name\": \"databaseB\"\n         }\n      ]\n   }\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/test/resources/user_get_withhost.json",
    "content": "{\n   \"user\": {\n      \"name\": \"example.user\",\n      \"host\": \"192.168.64.64\",\n      \"databases\": [\n         {\n            \"name\": \"databaseA\"\n         },\n         {\n            \"name\": \"databaseB\"\n         }\n      ]\n   }\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/test/resources/user_grant_request.json",
    "content": "{\n   \"databases\": [\n      {\n         \"name\": \"databaseC\"\n      },\n      {\n         \"name\": \"databaseD\"\n      }\n   ]\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/test/resources/user_grant_simple_request.json",
    "content": "{\n   \"databases\": [\n      {\n         \"name\": \"databaseZ\"\n      }\n   ]\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/test/resources/user_list_access.json",
    "content": "{\n   \"databases\": [\n      {\n         \"name\": \"databaseA\"\n      },\n      {\n         \"name\": \"databaseB\"\n      }\n   ]\n}\n"
  },
  {
    "path": "apis/openstack-trove/src/test/resources/user_password_request.json",
    "content": "{\n   \"users\": [\n      {\n          \"name\": \"dbuser1\",\n          \"password\": \"newpassword\"\n      },\n      {\n           \"name\": \"dbuser2\",\n           \"password\": \"anotherpassword\"\n      }\n   ]\n}\n"
  },
  {
    "path": "apis/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <artifactId>jclouds-project</artifactId>\n    <groupId>org.apache.jclouds</groupId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.api</groupId>\n  <artifactId>jclouds-apis-project</artifactId>\n  <packaging>pom</packaging>\n  <name>jclouds apis project</name>\n  <modules>\n    <module>atmos</module>\n    <module>byon</module>\n    <module>chef</module>\n    <module>cloudstack</module>\n    <module>cloudwatch</module>\n    <module>docker</module>\n    <module>ec2</module>\n    <module>elasticstack</module>\n    <module>filesystem</module>\n    <module>glacier</module>\n    <module>oauth</module>\n    <module>openstack-cinder</module>\n    <module>openstack-keystone</module>\n    <module>openstack-nova-ec2</module>\n    <module>openstack-nova</module>\n    <module>openstack-neutron</module>\n    <module>openstack-swift</module>\n    <module>openstack-trove</module>\n    <module>rackspace-clouddns</module>\n    <module>rackspace-cloudfiles</module>\n    <module>rackspace-cloudidentity</module>\n    <module>rackspace-cloudloadbalancers</module>\n    <module>route53</module>\n    <module>s3</module>\n    <module>sqs</module>\n    <module>sts</module>\n  </modules>\n</project>\n"
  },
  {
    "path": "apis/rackspace-clouddns/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.rackspace.clouddns.v1.*;version=\"${project.version}\";-noimport:=true"
  },
  {
    "path": "apis/rackspace-clouddns/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.api</groupId>\n  <artifactId>rackspace-clouddns</artifactId>\n  <name>jclouds rackspace clouddns api</name>\n  <description>jclouds components for Rackspace Cloud DNS</description>\n\n  <properties>\n    <test.rackspace-clouddns.endpoint>https://identity.api.rackspacecloud.com/v2.0/</test.rackspace-clouddns.endpoint>\n    <test.rackspace-clouddns.api-version>1.0</test.rackspace-clouddns.api-version>\n    <test.rackspace-clouddns.build-version />\n    <test.rackspace-clouddns.identity>${test.rackspace-us.identity}</test.rackspace-clouddns.identity>\n    <test.rackspace-clouddns.credential>${test.rackspace-us.credential}</test.rackspace-clouddns.credential>\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-keystone</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>rackspace-cloudidentity</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-keystone</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-nova</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>rackspace-cloudidentity</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.provider</groupId>\n      <artifactId>rackspace-cloudservers-us</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-slf4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>ch.qos.logback</groupId>\n      <artifactId>logback-classic</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n  \n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <!-- TODO: remove when multiple jobs/session are supported -->\n                  <threadCount>1</threadCount>\n                  <systemPropertyVariables>\n                    <test.rackspace-clouddns.endpoint>${test.rackspace-clouddns.endpoint}</test.rackspace-clouddns.endpoint>\n                    <test.rackspace-clouddns.api-version>${test.rackspace-clouddns.api-version}</test.rackspace-clouddns.api-version>\n                    <test.rackspace-clouddns.build-version>${test.rackspace-clouddns.build-version}</test.rackspace-clouddns.build-version>\n                    <test.rackspace-clouddns.identity>${test.rackspace-clouddns.identity}</test.rackspace-clouddns.identity>\n                    <test.rackspace-clouddns.credential>${test.rackspace-clouddns.credential}</test.rackspace-clouddns.credential>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/main/java/org/jclouds/rackspace/clouddns/v1/CloudDNSApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.io.Closeable;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.rackspace.clouddns.v1.config.CloudDNS;\nimport org.jclouds.rackspace.clouddns.v1.domain.Job;\nimport org.jclouds.rackspace.clouddns.v1.features.DomainApi;\nimport org.jclouds.rackspace.clouddns.v1.features.LimitApi;\nimport org.jclouds.rackspace.clouddns.v1.features.RecordApi;\nimport org.jclouds.rackspace.clouddns.v1.features.ReverseDNSApi;\nimport org.jclouds.rackspace.clouddns.v1.functions.ParseJob;\nimport org.jclouds.rackspace.clouddns.v1.predicates.JobPredicates;\nimport org.jclouds.rest.annotations.Delegate;\nimport org.jclouds.rest.annotations.Endpoint;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\n\n/**\n * Provides access to the Rackspace Cloud DNS API.\n * <p/>\n * See <a href=\"http://docs.rackspace.com/cdns/api/v1.0/cdns-devguide/content/index.html\">Cloud DNS Developer Guide</a>\n */\npublic interface CloudDNSApi extends Closeable {\n\n   /**\n    * Returns the current status of a job.\n    * </p>\n    * Operations that create, update, or delete resources may take some time to process. Therefore they return\n    * a Job containing information, which allows the status and response information of the job to be\n    * retrieved at a later point in time.\n    * </p>\n    * You likely won't need to use this method directly. Use {@link JobPredicates#awaitComplete(CloudDNSApi, Job)}.\n    *\n    * @return null, if not found.\n    */\n   @Named(\"job:get\")\n   @Endpoint(CloudDNS.class)\n   @RequestFilters(AuthenticateRequest.class)\n   @GET\n   @Consumes(APPLICATION_JSON)\n   @ResponseParser(ParseJob.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   @QueryParams(keys = \"showDetails\", values = \"true\")\n   @Path(\"/status/{jobId}\")\n   @Nullable\n   <T> Job<T> getJob(@PathParam(\"jobId\") String jobId);\n\n   /**\n    * Provides access to Limit features.\n    */\n   @Delegate\n   LimitApi getLimitApi();\n\n   /**\n    * Provides access to Domain features.\n    */\n   @Delegate\n   DomainApi getDomainApi();\n\n   /**\n    * Provides access to Record features.\n    */\n   @Delegate\n   @Path(\"/domains/{domainId}\")\n   RecordApi getRecordApi(@PathParam(\"domainId\") int domainId);\n\n   /**\n    * Provides access to Reverse DNS features.\n    */\n   @Delegate\n   ReverseDNSApi getReverseDNSApi(@PayloadParam(\"serviceName\") @PathParam(\"serviceName\") String serviceName);\n\n   /**\n    * Provides access to Record features.\n    * @deprecated Please use {@link #getRecordApi(int)} instead. To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   @Delegate\n   @Path(\"/domains/{domainId}\")\n   RecordApi getRecordApiForDomain(@PathParam(\"domainId\") int domainId);\n\n   /**\n    * Provides access to Reverse DNS features.\n    * @deprecated Please use {@link #getReverseDNSApi(String)} instead. To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   @Delegate\n   ReverseDNSApi getReverseDNSApiForService(@PayloadParam(\"serviceName\") @PathParam(\"serviceName\") String serviceName);\n\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/main/java/org/jclouds/rackspace/clouddns/v1/CloudDNSApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1;\n\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.CREDENTIAL_TYPE;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.KEYSTONE_VERSION;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.SERVICE_TYPE;\nimport static org.jclouds.rackspace.cloudidentity.v2_0.ServiceType.DNS;\nimport static org.jclouds.rackspace.cloudidentity.v2_0.config.CloudIdentityCredentialTypes.API_KEY_CREDENTIALS;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.openstack.keystone.catalog.config.ServiceCatalogModule;\nimport org.jclouds.openstack.keystone.catalog.config.ServiceCatalogModule.ProviderModule;\nimport org.jclouds.rackspace.clouddns.v1.config.CloudDNSHttpApiModule;\nimport org.jclouds.rackspace.cloudidentity.v2_0.config.CloudIdentityAuthenticationModule;\nimport org.jclouds.rest.internal.BaseHttpApiMetadata;\n\nimport com.google.auto.service.AutoService;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n/**\n * Implementation of {@link ApiMetadata} for Rackspace Cloud DNS 1.0 API\n */\n@AutoService(ApiMetadata.class)\npublic class CloudDNSApiMetadata extends BaseHttpApiMetadata<CloudDNSApi> {\n\n   @Override\n   public Builder toBuilder() {\n      return new Builder().fromApiMetadata(this);\n   }\n\n   public CloudDNSApiMetadata() {\n      this(new Builder());\n   }\n\n   protected CloudDNSApiMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = BaseHttpApiMetadata.defaultProperties();\n      properties.setProperty(SERVICE_TYPE, DNS);\n      properties.setProperty(CREDENTIAL_TYPE, API_KEY_CREDENTIALS);\n      properties.setProperty(KEYSTONE_VERSION, \"2\");\n      return properties;\n   }\n\n   public static class Builder extends BaseHttpApiMetadata.Builder<CloudDNSApi, Builder> {\n\n      protected Builder() {\n         id(\"rackspace-clouddns\")\n         .name(\"Rackspace Cloud DNS API\")\n         .identityName(\"Username\")\n         .credentialName(\"API Key\")\n         .documentation(URI.create(\"http://docs.rackspace.com/cdns/api/v1.0/cdns-devguide/content/index.html\"))\n         .version(\"1.0\")\n         .defaultEndpoint(\"https://identity.api.rackspacecloud.com/v2.0/\")\n         .defaultProperties(CloudDNSApiMetadata.defaultProperties())\n         .defaultModules(ImmutableSet.<Class<? extends Module>> builder()\n                                     .add(CloudIdentityAuthenticationModule.class)\n                                     .add(ServiceCatalogModule.class)\n                                     .add(ProviderModule.class)\n                                     .add(CloudDNSHttpApiModule.class)\n                                     .build());\n      }\n\n      @Override\n      public CloudDNSApiMetadata build() {\n         return new CloudDNSApiMetadata(this);\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/main/java/org/jclouds/rackspace/clouddns/v1/CloudDNSExceptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.rackspace.clouddns.v1.domain.Job;\n\n/**\n * Exceptions likely to be encountered when using {@link CloudDNSApi}\n */\npublic final class CloudDNSExceptions {\n   private CloudDNSExceptions() {\n      throw new AssertionError(\"intentionally not implemented\");\n   }\n\n   /**\n    * A Job errored out.\n    */\n   public static class JobErrorException extends RuntimeException {\n      private static final long serialVersionUID = 1L;\n      private final Job.Error jobError;\n\n      public JobErrorException(Job.Error jobError) {\n         super(jobError.toString());\n         this.jobError = checkNotNull(jobError, \"jobError\");\n      }\n\n      public Job.Error getJobError() {\n         return jobError;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/main/java/org/jclouds/rackspace/clouddns/v1/binders/CreateReverseDNSToJSON.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.net.URI;\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.json.Json;\nimport org.jclouds.rackspace.clouddns.v1.domain.Record;\nimport org.jclouds.rest.MapBinder;\n\nimport com.google.common.collect.ImmutableMap;\n\npublic class CreateReverseDNSToJSON implements MapBinder {\n   private final Json jsonBinder;\n\n   @Inject\n   public CreateReverseDNSToJSON(Json jsonBinder) {\n      this.jsonBinder = checkNotNull(jsonBinder, \"jsonBinder\");\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      checkArgument(checkNotNull(postParams.get(\"href\"), \"href\") instanceof URI, \"href is only valid for a URI!\");\n      checkArgument(checkNotNull(postParams.get(\"records\"), \"records\") instanceof Iterable,\n            \"records is only valid for an Iterable!\");\n      checkNotNull(postParams.get(\"serviceName\"), \"serviceName\");\n\n      Iterable<Record> records = Iterable.class.cast(postParams.get(\"records\"));\n      URI deviceURI = URI.class.cast(postParams.get(\"href\"));\n      String serviceName = postParams.get(\"serviceName\").toString();\n\n      String json = toJSON(records, deviceURI, serviceName);\n      request.setPayload(json);\n      request.getPayload().getContentMetadata().setContentType(MediaType.APPLICATION_JSON);\n\n      return (R) request.toBuilder().payload(json).build();\n   }\n\n   private String toJSON(Iterable<Record> records, URI deviceURI, String serviceName) {\n      return jsonBinder.toJson(ImmutableMap.<String, Object> of(\n            \"recordsList\", ImmutableMap.of(\"records\", records),\n            \"link\", ImmutableMap.<String, Object> of(\n                  \"href\", deviceURI, \n                  \"rel\", serviceName)));\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      throw new UnsupportedOperationException(\"use map form\");\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/main/java/org/jclouds/rackspace/clouddns/v1/binders/FormatAndContentsToJSON.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1.binders;\n\nimport static java.lang.String.format;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.MapBinder;\n\nimport com.google.common.base.Joiner;\n\npublic class FormatAndContentsToJSON implements MapBinder {\n   private static final String template = \"{\\\"domains\\\":[{\\\"contentType\\\":\\\"%s\\\",\\\"contents\\\":\\\"%s\\\"}]}\";\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      String format = postParams.get(\"format\").toString();\n      List<String> contents = List.class.cast(postParams.get(\"contents\"));\n\n      return (R) request.toBuilder().payload(toJSON(format, contents)).build();\n   }\n\n   private String toJSON(String format, List<String> contents) {\n      String contentsAsOneString = Joiner.on(\"\\\\n\").join(contents);\n\n      return format(template, format, contentsAsOneString);\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      throw new UnsupportedOperationException(\"use map form\");\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/main/java/org/jclouds/rackspace/clouddns/v1/binders/UpdateDomainsToJSON.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1.binders;\n\nimport static java.lang.String.format;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.MapBinder;\n\nimport com.google.common.base.Joiner;\nimport com.google.common.collect.Lists;\n\npublic class UpdateDomainsToJSON implements MapBinder {\n   private static final String template = \"{\\\"domains\\\":[%s]}\";\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      Iterable<Integer> ids = Iterable.class.cast(postParams.get(\"ids\"));\n      String key;\n      String value;\n      String updateTemplate;\n      \n      if (postParams.get(\"emailAddress\") != null) {\n         updateTemplate = \"{\\\"id\\\":%s,\\\"%s\\\":\\\"%s\\\"}\";\n         key = \"emailAddress\";\n      } else if (postParams.get(\"ttl\") != null) {\n         updateTemplate = \"{\\\"id\\\":%s,\\\"%s\\\":%s}\";\n         key = \"ttl\";\n      } else {\n         throw new IllegalStateException(\"emailAddress or ttl not found in \" + postParams);\n      }\n      \n      value = postParams.get(key).toString();\n      return (R) request.toBuilder().payload(toJSON(ids, updateTemplate, key, value)).build();\n   }\n\n   private String toJSON(Iterable<Integer> ids, String updateTemplate, String key, String value) {\n      List<String> json = Lists.newArrayList();\n\n      for (Integer id : ids) {\n         json.add(format(updateTemplate, id, key, value));\n      }\n      \n      String contentsAsOneString = Joiner.on(\",\").join(json);\n\n      return format(template, contentsAsOneString);\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      throw new UnsupportedOperationException(\"use map form\");\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/main/java/org/jclouds/rackspace/clouddns/v1/binders/UpdateRecordsToJSON.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.json.Json;\nimport org.jclouds.rackspace.clouddns.v1.domain.Record;\nimport org.jclouds.rest.Binder;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Lists;\n\n/**\n * Binds the Records to the request as a JSON payload.\n */\n@Singleton\npublic class UpdateRecordsToJSON implements Binder {\n\n   private final Json jsonBinder;\n\n   @Inject\n   public UpdateRecordsToJSON(Json jsonBinder) {\n      this.jsonBinder = checkNotNull(jsonBinder, \"jsonBinder\");\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkArgument(checkNotNull(input, \"input\") instanceof Map, \"This binder is only valid for Map<String, Record>\");\n      checkNotNull(request, \"request\");\n\n      Map<String, Record> idsToRecords = (Map<String, Record>) input;      \n      List<UpdateRecord> updateRecords = toUpdateRecordList(idsToRecords);\n      \n      String json = jsonBinder.toJson(ImmutableMap.of(\"records\", updateRecords));\n      request.setPayload(json);\n      request.getPayload().getContentMetadata().setContentType(MediaType.APPLICATION_JSON);\n      \n      return request;\n   }\n   \n   static List<UpdateRecord> toUpdateRecordList(Map<String, Record> idsToRecords) {\n      List<UpdateRecord> updateRecords = Lists.newArrayList();\n\n      for (Map.Entry<String, Record> entry : idsToRecords.entrySet()) {\n         String recordId = entry.getKey();\n         Record record = entry.getValue();\n         \n         UpdateRecord updateRecord = new UpdateRecord();\n         updateRecord.id = recordId;\n         updateRecord.name = record.getName();\n         updateRecord.ttl = record.getTTL().isPresent() ? record.getTTL().get() : null;\n         updateRecord.data = record.getData();\n         updateRecord.priority = record.getPriority();\n         updateRecord.comment = record.getComment();\n         \n         updateRecords.add(updateRecord);\n      }\n      \n      return updateRecords;\n   }\n   \n   static final class UpdateRecord {\n      public String id;\n      public String name;\n      public Integer ttl;\n      public String data;\n      public Integer priority;\n      public String comment;\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/main/java/org/jclouds/rackspace/clouddns/v1/binders/UpdateReverseDNSToJSON.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.net.URI;\nimport java.util.List;\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.json.Json;\nimport org.jclouds.rackspace.clouddns.v1.binders.UpdateRecordsToJSON.UpdateRecord;\nimport org.jclouds.rackspace.clouddns.v1.domain.Record;\nimport org.jclouds.rest.MapBinder;\n\nimport com.google.common.collect.ImmutableMap;\n\npublic class UpdateReverseDNSToJSON implements MapBinder {\n   private final Json jsonBinder;\n\n   @Inject\n   public UpdateReverseDNSToJSON(Json jsonBinder) {\n      this.jsonBinder = checkNotNull(jsonBinder, \"jsonBinder\");\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      checkArgument(checkNotNull(postParams.get(\"href\"), \"href\") instanceof URI,\n            \"href is only valid for a URI!\");\n      checkArgument(checkNotNull(postParams.get(\"idsToRecords\"), \"idsToRecords\") instanceof Map,\n            \"records is only valid for a Map!\");\n      checkNotNull(postParams.get(\"serviceName\"), \"serviceName\");\n      \n      Map<String, Record> idsToRecords = Map.class.cast(postParams.get(\"idsToRecords\"));\n      List<UpdateRecord> updateRecords = UpdateRecordsToJSON.toUpdateRecordList(idsToRecords);\n      URI deviceURI = URI.class.cast(postParams.get(\"href\"));\n      String serviceName = postParams.get(\"serviceName\").toString();\n\n      String json = toJSON(updateRecords, deviceURI, serviceName);\n      request.setPayload(json);\n      request.getPayload().getContentMetadata().setContentType(MediaType.APPLICATION_JSON);\n\n      return (R) request.toBuilder().payload(json).build();\n   }\n\n   private String toJSON(Iterable<UpdateRecord> records, URI deviceURI, String serviceName) {\n      return jsonBinder.toJson(ImmutableMap.<String, Object> of(\n            \"recordsList\", ImmutableMap.of(\"records\", records),\n            \"link\", ImmutableMap.<String, Object> of(\n                  \"href\", deviceURI, \n                  \"rel\", serviceName)));\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      throw new UnsupportedOperationException(\"use map form\");\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/main/java/org/jclouds/rackspace/clouddns/v1/config/CloudDNS.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1.config;\n\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\nimport jakarta.inject.Qualifier;\n\n/**\n * Represents a component related to Rackspace Cloud DNS.\n */\n@Retention(value = RetentionPolicy.RUNTIME)\n@Target(value = { ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })\n@Qualifier\npublic @interface CloudDNS {\n\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/main/java/org/jclouds/rackspace/clouddns/v1/config/CloudDNSHttpApiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1.config;\n\nimport java.net.URI;\n\nimport org.jclouds.json.config.GsonModule.DateAdapter;\nimport org.jclouds.json.config.GsonModule.Iso8601DateAdapter;\nimport org.jclouds.rackspace.clouddns.v1.CloudDNSApi;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.config.HttpApiModule;\n\nimport com.google.common.base.Supplier;\nimport com.google.inject.TypeLiteral;\n\n/**\n * Configures Rackspace Cloud DNS.\n */\n@ConfiguresHttpApi\npublic class CloudDNSHttpApiModule extends HttpApiModule<CloudDNSApi> {\n\n   @Override\n   protected void configure() {\n      bind(new TypeLiteral<Supplier<URI>>() {}).annotatedWith(CloudDNS.class).to(new TypeLiteral<Supplier<URI>>() {});\n      bind(DateAdapter.class).to(Iso8601DateAdapter.class);\n      super.configure();\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/main/java/org/jclouds/rackspace/clouddns/v1/domain/CreateDomain.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Create a Domain or Subdomain.\n */\npublic class CreateDomain {\n   private final String name;\n   private final String emailAddress;\n   private final Optional<Integer> ttl;\n   private final Optional<String> comment;\n   // subdomains is an ImmutableMap for serialization\n   private final ImmutableMap<String, Iterable<CreateSubdomain>> subdomains;\n   // recordList is an ImmutableMap for serialization\n   private final ImmutableMap<String, Iterable<Record>> recordsList;\n\n   private CreateDomain(String name, String email, Optional<Integer> ttl, Optional<String> comment,\n         ImmutableMap<String, Iterable<CreateSubdomain>> subdomains,\n         ImmutableMap<String, Iterable<Record>> recordsList) {\n      this.name = checkNotNull(name, \"name required\");\n      this.emailAddress = checkNotNull(email, \"email required\");\n      this.ttl = ttl;\n      this.comment = comment;\n      this.subdomains = subdomains != null ? subdomains : ImmutableMap.<String, Iterable<CreateSubdomain>> of();\n      this.recordsList = recordsList != null ? recordsList : ImmutableMap.<String, Iterable<Record>> of();\n   }\n\n   /**\n    * @see Builder#name(String)\n    */\n   public String getName() {\n      return name;\n   }\n\n   /**\n    * @see Builder#email(String)\n    */\n   public String getEmail() {\n      return emailAddress;\n   }\n\n   /**\n    * @see Builder#ttl(Integer)\n    */\n   public Optional<Integer> getTTL() {\n      return ttl;\n   }\n\n   /**\n    * @see Builder#comment(String)\n    */\n   public Optional<String> getComment() {\n      return comment;\n   }\n\n   /**\n    * @see Builder#subdomains(Iterable)\n    */\n   public Iterable<CreateSubdomain> getSubdomains() {\n      return subdomains.get(\"domains\");\n   }\n\n   /**\n    * @see Builder#records(Iterable)\n    */\n   public Iterable<Record> getRecords() {\n      return recordsList.get(\"records\");\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(name);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      CreateDomain that = CreateDomain.class.cast(obj);\n\n      return Objects.equal(this.name, that.name);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"name\", name).add(\"email\", emailAddress)\n            .add(\"ttl\", ttl.orNull()).add(\"comment\", comment.orNull()).add(\"subdomains\", subdomains)\n            .add(\"records\", recordsList);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   public static class Builder {\n      private String name;\n      private String emailAddress;\n      private Optional<Integer> ttl = Optional.absent();\n      private Optional<String> comment = Optional.absent();\n      private ImmutableMap<String, Iterable<CreateSubdomain>> subdomains;\n      private ImmutableMap<String, Iterable<Record>> records;\n\n      /**\n       * The name for the domain or subdomain. Must be a fully qualified domain name (FQDN) that doesn't end in a '.'.\n       */\n      public Builder name(String name) {\n         this.name = name;\n         return this;\n      }\n\n      /**\n       * Email address to use for contacting the domain administrator. Used as the email-addr (rname) in the SOA record.\n       */\n      public Builder email(String email) {\n         this.emailAddress = email;\n         return this;\n      }\n\n      /**\n       * The duration in seconds that the record may be cached by clients. If specified, must be greater than 300. The\n       * default value, if not specified, is 3600.\n       */\n      public Builder ttl(Integer ttl) {\n         this.ttl = Optional.fromNullable(ttl);\n         return this;\n      }\n\n      /**\n       * If included, its length must be less than or equal to 160 characters.\n       */\n      public Builder comment(String comment) {\n         this.comment = Optional.fromNullable(comment);\n         return this;\n      }\n\n      /**\n       * Create Subdomains of this Domain.\n       */\n      public Builder subdomains(Iterable<CreateSubdomain> subdomains) {\n         if (subdomains != null) {\n            this.subdomains = ImmutableMap.of(\"domains\", subdomains);\n         }\n\n         return this;\n      }\n\n      /**\n       * Create Records for this Domain.\n       * </p>\n       * See <a href=\"http://docs.rackspace.com/cdns/api/v1.0/cdns-devguide/content/supported_record_types.html\">\n       * Supported Record Types</a>\n       */\n      public Builder records(Iterable<Record> records) {\n         if (records != null) {\n            this.records = ImmutableMap.of(\"records\", records);\n         }\n\n         return this;\n      }\n\n      public CreateDomain build() {\n         return new CreateDomain(name, emailAddress, ttl, comment, subdomains, records);\n      }\n\n      public Builder from(CreateDomain in) {\n         return this.name(in.getName()).email(in.getEmail()).ttl(in.getTTL().orNull())\n               .comment(in.getComment().orNull()).subdomains(in.getSubdomains()).records(in.getRecords());\n      }\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return new Builder().from(this);\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/main/java/org/jclouds/rackspace/clouddns/v1/domain/CreateSubdomain.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.base.Optional;\n\npublic class CreateSubdomain {\n   private final String name;\n   private final String emailAddress;\n   private final Optional<Integer> ttl;\n   private final Optional<String> comment;\n\n   private CreateSubdomain(String name, String email, Optional<Integer> ttl, Optional<String> comment) {\n      this.name = checkNotNull(name, \"name required\");\n      this.emailAddress = checkNotNull(email, \"email required\");\n      this.ttl = ttl;\n      this.comment = comment;\n   }\n\n   /**\n    * @see Builder#name(String)\n    */\n   public String getName() {\n      return name;\n   }\n\n   /**\n    * @see Builder#email(String)\n    */\n   public String getEmail() {\n      return emailAddress;\n   }\n\n   /**\n    * @see Builder#ttl(Integer)\n    */\n   public Optional<Integer> getTTL() {\n      return ttl;\n   }\n\n   /**\n    * @see Builder#comment(String)\n    */\n   public Optional<String> getComment() {\n      return comment;\n   }\n   \n   @Override\n   public int hashCode() {\n      return Objects.hashCode(name);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      CreateSubdomain that = CreateSubdomain.class.cast(obj);\n\n      return Objects.equal(this.name, that.name);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"name\", name).add(\"email\", emailAddress)\n            .add(\"ttl\", ttl.orNull()).add(\"comment\", comment.orNull());\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   public static class Builder {\n      private String name;\n      private String emailAddress;\n      private Optional<Integer> ttl = Optional.absent();\n      private Optional<String> comment = Optional.absent();\n\n      /**\n       * The name for the subdomain. Must be a fully qualified domain name (FQDN) that doesn't end in a '.'.\n       */\n      public Builder name(String name) {\n         this.name = name;\n         return this;\n      }\n\n      /**\n       * Email address to use for contacting the domain administrator. Used as the email-addr (rname) in the SOA record.\n       */\n      public Builder email(String email) {\n         this.emailAddress = email;\n         return this;\n      }\n\n      /**\n       * The duration in seconds that the record may be cached. If specified, must be greater than 300. The default\n       * value, if not specified, is 3600.\n       */\n      public Builder ttl(Integer ttl) {\n         this.ttl = Optional.fromNullable(ttl);\n         return this;\n      }\n\n      /**\n       * If included, its length must be less than or equal to 160 characters.\n       */\n      public Builder comment(String comment) {\n         this.comment = Optional.fromNullable(comment);\n         return this;\n      }\n\n      public CreateSubdomain build() {\n         return new CreateSubdomain(name, emailAddress, ttl, comment);\n      }\n\n      public Builder from(CreateSubdomain in) {\n         return this.name(in.getName()).email(in.getEmail()).ttl(in.getTTL().orNull())\n               .comment(in.getComment().orNull());\n      }\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return new Builder().from(this);\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/main/java/org/jclouds/rackspace/clouddns/v1/domain/Domain.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * A domain is an entity/container of all DNS-related information containing one or more records. Within Rackspace DNS,\n * the account which creates the domain is the domain owner.\n */\npublic class Domain {\n   private final int id;\n   private final String name;\n   private final String email;\n   private final Optional<String> comment;\n   private final Date created;\n   private final Date updated;\n   private final int accountId;\n   private final int ttl;\n   private final Set<String> nameservers;\n   private final Set<Subdomain> subdomains;\n   private final Set<RecordDetail> records;\n\n   @ConstructorProperties({ \"id\", \"name\", \"emailAddress\", \"comment\", \"created\", \"updated\", \"accountId\", \"ttl\",\n         \"nameservers\", \"subdomains\", \"recordsList\" })\n   protected Domain(int id, String name, String email, @Nullable String comment, Date created, Date updated,\n         int accountId, int ttl, @Nullable Set<String> nameservers, @Nullable Set<Subdomain> nameToSubdomain,\n         @Nullable Set<RecordDetail> records) {\n      this.id = id;\n      this.name = name;\n      this.email = email;\n      this.comment = Optional.fromNullable(comment);\n      this.created = created;\n      this.updated = updated;\n      this.accountId = accountId;\n      this.ttl = ttl;\n      this.nameservers = nameservers != null ? nameservers : ImmutableSet.<String> of();\n      this.subdomains = nameToSubdomain != null ? nameToSubdomain : ImmutableSet.<Subdomain> of();\n      this.records = records != null ? records : ImmutableSet.<RecordDetail> of();\n   }\n\n   public int getId() {\n      return id;\n   }\n\n   public String getName() {\n      return name;\n   }\n\n   public String getEmail() {\n      return email;\n   }\n\n   public Optional<String> getComment() {\n      return comment;\n   }\n\n   public Date getCreated() {\n      return created;\n   }\n\n   public Date getUpdated() {\n      return updated;\n   }\n\n   public int getAccountId() {\n      return accountId;\n   }\n\n   public int getTTL() {\n      return ttl;\n   }\n\n   public Set<String> getNameservers() {\n      return nameservers;\n   }\n\n   public Set<Subdomain> getSubdomains() {\n      return subdomains;\n   }\n\n   public Set<RecordDetail> getRecords() {\n      return records;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      Domain that = Domain.class.cast(obj);\n\n      return Objects.equal(this.id, that.id);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"id\", id).add(\"name\", name).add(\"email\", email)\n            .add(\"comment\", comment.orNull()).add(\"created\", created).add(\"updated\", updated)\n            .add(\"accountId\", accountId).add(\"ttl\", ttl).add(\"nameservers\", nameservers)\n            .add(\"subdomains\", subdomains).add(\"records\", records);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   protected Domain from(Domain in) {\n      return new Domain(in.getId(), in.getName(), in.getEmail(), in.getComment().orNull(), in.getCreated(),\n            in.getUpdated(), in.getAccountId(), in.getTTL(), in.getNameservers(), in.getSubdomains(), in.getRecords());\n   }\n\n   public enum Format {\n      BIND_9,\n\n      UNRECOGNIZED;\n\n      public static Format fromValue(String format) {\n         try {\n            return valueOf(checkNotNull(format, \"format\").toUpperCase());\n         }\n         catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/main/java/org/jclouds/rackspace/clouddns/v1/domain/DomainChange.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1.domain;\n\nimport static com.google.common.base.Objects.equal;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\nimport java.util.List;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\npublic class DomainChange {\n   private final Date from;\n   private final Date to;\n   private final List<Change> changes;\n\n   @ConstructorProperties({ \"from\", \"to\", \"changes\" })\n   private DomainChange(Date from, Date to, List<Change> changes) {\n      this.from = from;\n      this.to = to;\n      this.changes = changes;\n   }\n\n   public Date getFrom() {\n      return from;\n   }\n\n   public Date getTo() {\n      return to;\n   }\n\n   public List<Change> getChanges() {\n      return changes;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(from, to, changes);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      DomainChange that = DomainChange.class.cast(obj);\n      return equal(this.from, that.from) && equal(this.to, that.to) && equal(this.changes, that.changes);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"from\", from).add(\"to\", to).add(\"changes\", changes)\n            .toString();\n   }\n\n   public static class Change {\n      private final String domain;\n      private final String action;\n      private final String targetType;\n      private final int accountId;\n      private final int targetId;\n      private final List<ChangeDetail> changeDetails;\n\n      @ConstructorProperties({ \"domain\", \"action\", \"targetType\", \"accountId\", \"targetId\", \"changeDetails\" })\n      protected Change(String domain, String action, String targetType, int accountId, int targetId,\n            List<ChangeDetail> changeDetails) {\n         this.domain = domain;\n         this.action = action;\n         this.targetType = targetType;\n         this.accountId = accountId;\n         this.targetId = targetId;\n         this.changeDetails = changeDetails;\n      }\n\n      public String getDomain() {\n         return domain;\n      }\n\n      public String getAction() {\n         return action;\n      }\n\n      public String getTargetType() {\n         return targetType;\n      }\n\n      public int getAccountId() {\n         return accountId;\n      }\n\n      public int getTargetId() {\n         return targetId;\n      }\n\n      public List<ChangeDetail> getChangeDetails() {\n         return changeDetails;\n      }\n\n      @Override\n      public int hashCode() {\n         return Objects.hashCode(domain, action, targetType, accountId, targetId, changeDetails);\n      }\n\n      @Override\n      public boolean equals(Object obj) {\n         if (this == obj)\n            return true;\n         if (obj == null || getClass() != obj.getClass())\n            return false;\n         Change that = Change.class.cast(obj);\n         return equal(this.domain, that.domain) && equal(this.action, that.action)\n               && equal(this.targetType, that.targetType) && equal(this.accountId, that.accountId)\n               && equal(this.targetId, that.targetId) && equal(this.changeDetails, that.changeDetails);\n      }\n\n      @Override\n      public String toString() {\n         return MoreObjects.toStringHelper(this).omitNullValues().add(\"domain\", domain).add(\"action\", action)\n               .add(\"targetType\", targetType).add(\"accountId\", accountId).add(\"targetId\", targetId)\n               .add(\"changeDetails\", changeDetails).toString();\n      }\n   }\n\n   public static class ChangeDetail {\n      private final String field;\n      private final String originalValue;\n      private final String newValue;\n\n      @ConstructorProperties({ \"field\", \"originalValue\", \"newValue\" })\n      protected ChangeDetail(String field, String originalValue, String newValue) {\n         this.field = field;\n         this.originalValue = originalValue;\n         this.newValue = newValue;\n      }\n\n      public String getField() {\n         return field;\n      }\n\n      public String getOriginalValue() {\n         return originalValue;\n      }\n\n      public String getNewValue() {\n         return newValue;\n      }\n\n      @Override\n      public int hashCode() {\n         return Objects.hashCode(field, originalValue, newValue);\n      }\n\n      @Override\n      public boolean equals(Object obj) {\n         if (this == obj)\n            return true;\n         if (obj == null || getClass() != obj.getClass())\n            return false;\n         ChangeDetail that = ChangeDetail.class.cast(obj);\n         return equal(this.field, that.field) && equal(this.originalValue, that.originalValue)\n               && equal(this.newValue, that.newValue);\n      }\n\n      @Override\n      public String toString() {\n         return MoreObjects.toStringHelper(this).omitNullValues().add(\"field\", field).add(\"originalValue\", originalValue)\n               .add(\"newValue\", newValue).toString();\n      }\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/main/java/org/jclouds/rackspace/clouddns/v1/domain/Job.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1.domain;\n\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\n\nimport com.google.common.base.Optional;\n\n/**\n * @see CloudDNSApi#getJob(String)\n */\npublic class Job<T> {\n   private final String id;\n   private final Status status;\n   private final Optional<Error> error;\n   private final Optional<T> resource;\n   \n   private Job(String id, Status status, Optional<Error> error, Optional<T> resource) {\n      this.id = id;\n      this.status = status;\n      this.error = error;\n      this.resource = resource;\n   }\n\n   public String getId() {\n      return id;\n   }\n\n   public Status getStatus() {\n      return status;\n   }\n\n   public Optional<Error> getError() {\n      return error;\n   }\n\n   public Optional<T> getResource() {\n      return resource;\n   }\n\n   public enum Status {\n      /**\n       * INITIALIZED is the status that immediately precedes RUNNING and is the first possible state of a job. \n       * It indicates acceptance of the job.\n       */\n      INITIALIZED,\n\n      RUNNING, COMPLETED, ERROR, UNRECOGNIZED;\n\n      public static Status fromValue(String status) {\n         try {\n            return valueOf(checkNotNull(status, \"status\").toUpperCase());\n         }\n         catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n   }\n   \n   public static <T> Builder<T> builder() {\n      return new Builder<T>();\n   }\n\n   public static class Builder<T> {\n      private String id;\n      private Status status;\n      private Optional<Error> error = Optional.absent();\n      private Optional<T> resource = Optional.absent();\n\n      public Builder<T> id(String id) {\n         this.id = id;\n         return this;\n      }\n\n      public Builder<T> status(Status status) {\n         this.status = status;\n         return this;\n      }\n\n      public Builder<T> error(Error error) {\n         this.error = Optional.fromNullable(error);\n         return this;\n      }\n\n      public Builder<T> resource(T resource) {\n         this.resource = Optional.fromNullable(resource);\n         return this;\n      }\n      \n      public Job<T> build() {\n         return new Job<T>(id, status, error, resource);\n      }\n   }\n\n   public static final class Error {\n\n      private final int code;\n      private final String message;\n      private final String details;\n\n      @ConstructorProperties({ \"code\", \"message\", \"details\" })\n      protected Error(int code, String message, String details) {\n         this.code = code;\n         this.message = message;\n         this.details = details;\n      }\n\n      public int getCode() {\n         return code;\n      }\n\n      public String getMessage() {\n         return message;\n      }\n\n      public String getDetails() {\n         return details;\n      }\n\n      @Override\n      public String toString() {\n         return toStringHelper(this).add(\"code\", code).add(\"message\", message).add(\"details\", details).toString();\n      }\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/main/java/org/jclouds/rackspace/clouddns/v1/domain/Record.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.base.Optional;\n\npublic class Record {\n   private final String name;\n   private final String type;\n   private final Optional<Integer> ttl;\n   private final String data;\n   private final Integer priority;\n   private final String comment;\n\n   private Record(@Nullable String name, @Nullable String type, Optional<Integer> ttl, @Nullable String data,\n         @Nullable Integer priority, @Nullable String comment) {\n      this.name = name;\n      this.type = type;\n      this.ttl = ttl;\n      this.data = data;\n      this.priority = priority;\n      this.comment = comment;\n   }\n\n   /**\n    * @see Record.Builder#name(String)\n    */\n   public String getName() {\n      return name;\n   }\n\n   /**\n    * @see Record.Builder#type(String)\n    */\n   public String getType() {\n      return type;\n   }\n\n   /**\n    * @see Record.Builder#ttl(Integer)\n    */\n   public Optional<Integer> getTTL() {\n      return ttl;\n   }\n\n   /**\n    * @see Record.Builder#data(String)\n    */\n   public String getData() {\n      return data;\n   }\n\n   /**\n    * @see Record.Builder#priority(Integer)\n    */\n   @Nullable\n   public Integer getPriority() {\n      return priority;\n   }\n\n   /**\n    * @see Record.Builder#comment(String)\n    */\n   @Nullable\n   public String getComment() {\n      return comment;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(name, type, ttl, data, priority, comment);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      Record that = Record.class.cast(obj);\n\n      return equal(this.name, that.name) && equal(this.type, that.type) && equal(this.ttl, that.ttl)\n            && equal(this.data, that.data) && equal(this.priority, that.priority) && equal(this.comment, that.comment);\n   }\n\n   protected ToStringHelper string() {\n      return toStringHelper(this).omitNullValues().add(\"name\", name).add(\"type\", type).add(\"ttl\", ttl)\n            .add(\"data\", data).add(\"priority\", priority).add(\"comment\", comment);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   public static final class Builder {\n      private String name;\n      private String type;\n      private Optional<Integer> ttl = Optional.absent();\n      private String data;\n      private Integer priority;\n      private String comment;\n\n      /**\n       * The name for the domain or subdomain. Must be a fully qualified domain name (FQDN) that doesn't end in a '.'.\n       * </p>\n       * Users can add one or more wildcard records to any domain or sub-domain on their account. For information on the\n       * intent and use of wildcard records, see the DNS literature including RFC 1034, section 4.3.3, and RFC 4595.\n       * </p>\n       * Wildcards are supported for A, AAAA, CNAME, MX, SRV and TXT record types.\n       * </p>\n       * A valid wildcard DNS record is specified by using an asterisk (\"*\") as the leftmost part of a record name, for\n       * example *.example.com. An asterisk in any other part of a record name is invalid. Only the asterisk (\"*\") is\n       * accepted as a wildcard character.\n       * </p>\n       * For SRV records, this specifies the entire service name, which is made up of the service, protocol, and domain\n       * name to which the record belongs. The service and protocol fields of the service name can be modified but not\n       * the domain name field.\n       */\n      public Builder name(String name) {\n         this.name = name;\n         return this;\n      }\n\n      /**\n       * The record type to add.\n       * </p>\n       * See <a href=\"http://docs.rackspace.com/cdns/api/v1.0/cdns-devguide/content/supported_record_types.html\">\n       * Supported Record Types</a>\n       */\n      public Builder type(String type) {\n         this.type = type;\n         return this;\n      }\n\n      /**\n       * The duration in seconds that the record may be cached by clients. If specified, must be greater than 300. The\n       * default value, if not specified, is 3600.\n       */\n      public Builder ttl(int ttl) {\n         this.ttl = Optional.fromNullable(ttl);\n         return this;\n      }\n\n      /**\n       * @see Builder#ttl(int)\n       */\n      public Builder ttl(Optional<Integer> ttl) {\n         this.ttl = ttl;\n         return this;\n      }\n\n      /**\n       * The data field for PTR, A, and AAAA records must be a valid IPv4 or IPv6 IP address.\n       */\n      public Builder data(String data) {\n         this.data = data;\n         return this;\n      }\n\n      /**\n       * Required for MX and SRV records, but forbidden for other record types. If specified, must be an integer from 0\n       * to 65535.\n       */\n      public Builder priority(Integer priority) {\n         this.priority = priority;\n         return this;\n      }\n\n      /**\n       * If included, its length must be less than or equal to 160 characters.\n       */\n      public Builder comment(String comment) {\n         this.comment = comment;\n         return this;\n      }\n\n      public Record build() {\n         return new Record(name, type, ttl, data, priority, comment);\n      }\n\n      public Builder from(Record in) {\n         return name(in.getName()).type(in.getType()).ttl(in.getTTL()).data(in.getData()).priority(in.getPriority())\n               .comment(in.getComment());\n      }\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().from(this);\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/main/java/org/jclouds/rackspace/clouddns/v1/domain/RecordDetail.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Date;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\npublic class RecordDetail {\n   private final String id;\n   private final Date created;\n   private final Date updated;\n   private final Record record;\n\n   private RecordDetail(String id, Date created, Date updated, Record record) {\n      this.id = checkNotNull(id, \"id required\");\n      this.created = checkNotNull(created, \"created required\");\n      this.updated = checkNotNull(updated, \"updated required\");\n      this.record = checkNotNull(record, \"record required\");\n   }\n\n   public String getId() {\n      return id;\n   }\n\n   /**\n    * When this record was created.\n    */\n   public Date getCreated() {\n      return created;\n   }\n\n   /**\n    * When this record was updated.\n    */\n   public Date getUpdated() {\n      return updated;\n   }\n\n   /**\n    * The Record.\n    */\n   public Record getRecord() {\n      return record;\n   }\n\n   /**\n    * @see Record.Builder#name(String)\n    */\n   public String getName() {\n      return record.getName();\n   }\n\n   /**\n    * @see Record.Builder#type(String)\n    */\n   public String getType() {\n      return record.getType();\n   }\n\n   /**\n    * @see Record.Builder#ttl(Integer)\n    */\n   public int getTTL() {\n      return record.getTTL().get();\n   }\n\n   /**\n    * @see Record.Builder#data(String)\n    */\n   public String getData() {\n      return record.getData();\n   }\n\n   /**\n    * @see Record.Builder#priority(Integer)\n    */\n   public Integer getPriority() {\n      return record.getPriority();\n   }\n\n   /**\n    * @see Record.Builder#comment(String)\n    */\n   public String getComment() {\n      return record.getComment();\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      RecordDetail that = RecordDetail.class.cast(obj);\n\n      return equal(this.id, that.id);\n   }\n\n   protected ToStringHelper string() {\n      return toStringHelper(this).omitNullValues().add(\"id\", id).add(\"created\", created).add(\"updated\", updated)\n            .add(\"record\", record);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   public static final class Builder {\n      private String id;\n      private Date created;\n      private Date updated;\n      private Record record;\n\n      public Builder id(String id) {\n         this.id = id;\n         return this;\n      }\n\n      public Builder created(Date created) {\n         this.created = created;\n         return this;\n      }\n\n      public Builder updated(Date updated) {\n         this.updated = updated;\n         return this;\n      }\n\n      public Builder record(Record record) {\n         this.record = record;\n         return this;\n      }\n\n      public Builder record(Record.Builder recordBuilder) {\n         this.record = recordBuilder.build();\n         return this;\n      }\n\n      public RecordDetail build() {\n         return new RecordDetail(id, created, updated, record);\n      }\n\n      public Builder from(RecordDetail in) {\n         return this.id(in.getId()).created(in.getCreated()).updated(in.getUpdated()).record(in.getRecord());\n      }\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().from(this);\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/main/java/org/jclouds/rackspace/clouddns/v1/domain/Subdomain.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1.domain;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.Optional;\n\n/**\n * Subdomains are domains within a parent domain. Subdomains allow you to delegate domains. Subdomains can themselves\n * have subdomains, so third-level, fourth-level, fifth-level, and deeper levels of nesting are possible.\n */\npublic class Subdomain {\n   private final int id;\n   private final String name;\n   private final String emailAddress;\n   private final Optional<String> comment;\n   private final Date created;\n   private final Date updated;\n\n   @ConstructorProperties({ \"id\", \"name\", \"emailAddress\", \"comment\", \"created\", \"updated\" })\n   private Subdomain(int id, String name, String email, @Nullable String comment, Date created, Date updated) {\n      this.id = id;\n      this.name = name;\n      this.emailAddress = email;\n      this.comment = Optional.fromNullable(comment);\n      this.created = created;\n      this.updated = updated;\n   }\n\n   public int getId() {\n      return id;\n   }\n\n   public String getName() {\n      return name;\n   }\n\n   public String getEmail() {\n      return emailAddress;\n   }\n\n   public Optional<String> getComment() {\n      return comment;\n   }\n\n   public Date getCreated() {\n      return created;\n   }\n\n   public Date getUpdated() {\n      return updated;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      Subdomain that = Subdomain.class.cast(obj);\n\n      return Objects.equal(this.id, that.id);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"id\", id).add(\"name\", name).add(\"email\", emailAddress)\n            .add(\"comment\", comment.orNull()).add(\"created\", created).add(\"updated\", updated).toString();\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/main/java/org/jclouds/rackspace/clouddns/v1/domain/UpdateDomain.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1.domain;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.base.Optional;\n\n/**\n * Update a Domain or Subdomain.\n */\npublic class UpdateDomain {\n   private final Optional<String> emailAddress;\n   private final Optional<Integer> ttl;\n   private final Optional<String> comment;\n\n   private UpdateDomain(Optional<String> email, Optional<Integer> ttl, Optional<String> comment) {\n      this.emailAddress = email;\n      this.ttl = ttl;\n      this.comment = comment;\n   }\n\n   public Optional<String> getEmail() {\n      return emailAddress;\n   }\n\n   public Optional<Integer> getTTL() {\n      return ttl;\n   }\n\n   public Optional<String> getComment() {\n      return comment;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(emailAddress, ttl, comment);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      UpdateDomain that = UpdateDomain.class.cast(obj);\n\n      return Objects.equal(this.emailAddress, that.emailAddress) && Objects.equal(this.ttl, that.ttl)\n            && Objects.equal(this.comment, that.comment);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"email\", emailAddress.orNull()).add(\"ttl\", ttl.orNull())\n            .add(\"comment\", comment.orNull());\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   public static class Builder {\n      private Optional<String> emailAddress = Optional.absent();\n      private Optional<Integer> ttl = Optional.absent();\n      private Optional<String> comment = Optional.absent();\n\n      /**\n       * Email address to use for contacting the domain administrator.\n       */\n      public Builder email(String email) {\n         this.emailAddress = Optional.fromNullable(email);\n         return this;\n      }\n\n      /**\n       * If specified, must be greater than 300.\n       */\n      public Builder ttl(Integer ttl) {\n         this.ttl = Optional.fromNullable(ttl);\n         return this;\n      }\n\n      /**\n       * If included, its length must be less than or equal to 160 characters.\n       */\n      public Builder comment(String comment) {\n         this.comment = Optional.fromNullable(comment);\n         return this;\n      }\n\n      public UpdateDomain build() {\n         return new UpdateDomain(emailAddress, ttl, comment);\n      }\n\n      public Builder from(UpdateDomain in) {\n         return this.email(in.getEmail().orNull()).ttl(in.getTTL().orNull()).comment(in.getComment().orNull());\n      }\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return new Builder().from(this);\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/main/java/org/jclouds/rackspace/clouddns/v1/features/DomainApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1.features;\n\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyPagedIterableOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.collect.PagedIterable;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.keystone.v2_0.KeystoneFallbacks.EmptyPaginatedCollectionOnNotFoundOr404;\nimport org.jclouds.openstack.v2_0.domain.PaginatedCollection;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\nimport org.jclouds.rackspace.clouddns.v1.CloudDNSApi;\nimport org.jclouds.rackspace.clouddns.v1.binders.FormatAndContentsToJSON;\nimport org.jclouds.rackspace.clouddns.v1.binders.UpdateDomainsToJSON;\nimport org.jclouds.rackspace.clouddns.v1.config.CloudDNS;\nimport org.jclouds.rackspace.clouddns.v1.domain.CreateDomain;\nimport org.jclouds.rackspace.clouddns.v1.domain.Domain;\nimport org.jclouds.rackspace.clouddns.v1.domain.DomainChange;\nimport org.jclouds.rackspace.clouddns.v1.domain.Job;\nimport org.jclouds.rackspace.clouddns.v1.domain.Subdomain;\nimport org.jclouds.rackspace.clouddns.v1.domain.UpdateDomain;\nimport org.jclouds.rackspace.clouddns.v1.functions.DomainsToPagedIterable;\nimport org.jclouds.rackspace.clouddns.v1.functions.ParseDomain;\nimport org.jclouds.rackspace.clouddns.v1.functions.ParseDomains;\nimport org.jclouds.rackspace.clouddns.v1.functions.ParseJob;\nimport org.jclouds.rackspace.clouddns.v1.functions.ParseSubdomains;\nimport org.jclouds.rackspace.clouddns.v1.functions.SubdomainsToPagedIterable;\nimport org.jclouds.rackspace.clouddns.v1.predicates.JobPredicates;\nimport org.jclouds.rackspace.cloudidentity.v2_0.functions.DateParser;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Endpoint;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.ParamParser;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.Transform;\nimport org.jclouds.rest.annotations.WrapWith;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\n@Endpoint(CloudDNS.class)\n@RequestFilters(AuthenticateRequest.class)\npublic interface DomainApi {\n   /**\n    * Provisions one or more new DNS domains based on the configuration defined in CreateDomain. If the domain\n    * creation cannot be fulfilled due to insufficient or invalid data, Job with an ERROR status will\n    * be returned with information regarding the nature of the failure in the body of the Job. Failures in the\n    * validation process are non-recoverable and require the caller to correct the cause of the failure.\n    * This is an atomic operation: if there is a failure in creation of even a single record, the entire process\n    * will fail.\n    * </p>\n    * When a domain is created, and no Time To Live (TTL) is specified, the SOA minTTL (3600 seconds) is used as the\n    * default. When a record is added without a specified TTL, it will receive the domain TTL by default. When the\n    * domain and/or record TTL is supplied by the user, either via a create or update call, the TTL values must be 300\n    * seconds or more.\n    * </p>\n    * To wait for this call to complete use {@link JobPredicates#awaitComplete(CloudDNSApi, Job)}.\n    */\n   @Named(\"domain:create\")\n   @POST\n   @Consumes(MediaType.APPLICATION_JSON)\n   @ResponseParser(ParseJob.class)\n   @Path(\"/domains\")\n   Job<Set<Domain>> create(@WrapWith(\"domains\") Iterable<CreateDomain> createDomains);\n\n   /**\n    * The resulting list is flat, and does not break the domains down hierarchically by subdomain. All representative\n    * domains are included in the list, even if a domain is conceptually a subdomain of another domain in the list.\n    * Records are not included.\n    */\n   @Named(\"domain:list\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @ResponseParser(ParseDomains.class)\n   @Transform(DomainsToPagedIterable.class)\n   @Path(\"/domains\")\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   PagedIterable<Domain> list();\n\n   /**\n    * Filtering the search to limit the results returned can be performed by using the nameFilter parameter. For\n    * example, \"hoola.com\" matches hoola.com and similar names such as main.hoola.com and sub.hoola.com.\n    * </p>\n    * Filter criteria may consist of:\n    * <ul>\n    * <li>Any letter (A-Za-z)</li>\n    * <li>Numbers (0-9)</li>\n    * <li>Hyphen (\"-\")</li>\n    * <li>1 to 63 characters</li>\n    * </ul>\n    * Filter criteria should not include any of the following characters: ' + , | ! \" £ $ % & / ( ) = ? ^ * ç ° § ; : _\n    * > ] [ @ à, é, ò\n    */\n   @Named(\"domain:list\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @ResponseParser(ParseDomains.class)\n   @Transform(DomainsToPagedIterable.class)\n   @Path(\"/domains\")\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   PagedIterable<Domain> listWithFilterByNamesMatching(@QueryParam(\"name\") String nameFilter);\n\n   /**\n    * The resulting list is flat, and does not break the domains down hierarchically by subdomain.\n    */\n   @Named(\"domain:list\")\n   @GET\n   @ResponseParser(ParseDomains.class)\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptyPaginatedCollectionOnNotFoundOr404.class)\n   @Path(\"/domains\")\n   PaginatedCollection<Domain> list(PaginationOptions options);\n\n   /**\n    * List the subdomains of a domain.\n    */\n   @Named(\"domain:list\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @ResponseParser(ParseSubdomains.class)\n   @Transform(SubdomainsToPagedIterable.class)\n   @Path(\"/domains/{domainId}/subdomains\")\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   @Nullable\n   PagedIterable<Subdomain> listSubdomains(@PathParam(\"domainId\") int domainId);\n\n   /**\n    * List the subdomains of a domain and manually control pagination.\n    */\n   @Named(\"domain:list\")\n   @GET\n   @ResponseParser(ParseSubdomains.class)\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptyPaginatedCollectionOnNotFoundOr404.class)\n   @Path(\"/domains/{domainId}/subdomains\")\n   PaginatedCollection<Subdomain> listSubdomains(@PathParam(\"domainId\") int domainId,\n         PaginationOptions options);\n\n   /**\n    * Shows all changes to the specified domain since the specified date/time.\n    */\n   @Named(\"domain:list\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Path(\"/domains/{id}/changes\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   DomainChange listChanges(@PathParam(\"id\") int id,\n         @ParamParser(DateParser.class) @QueryParam(\"changes\") Date since);\n\n   /**\n    * Get all information for a Domain, including records and subdomains.\n    */\n   @Named(\"domain:get\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Path(\"/domains/{id}\")\n   @QueryParams(keys = { \"showRecords\", \"showSubdomains\" }, values = { \"true\", \"true\" })\n   @ResponseParser(ParseDomain.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Domain get(@PathParam(\"id\") int id);\n\n   /**\n    * This call modifies the domain attributes only. Records cannot be added, modified, or removed.\n    * </p>\n    * To wait for this call to complete use {@link JobPredicates#awaitComplete(CloudDNSApi, Job)}.\n    * \n    * @see RecordApi\n    */\n   @Named(\"domain:update\")\n   @PUT\n   @Produces(MediaType.APPLICATION_JSON)\n   @Consumes(MediaType.APPLICATION_JSON)\n   @ResponseParser(ParseJob.class)\n   @Path(\"/domains/{id}\")\n   Job<Void> update(@PathParam(\"id\") int id, @BinderParam(BindToJsonPayload.class) UpdateDomain updateDomain);\n\n   /**\n    * This call modifies the domain's TTL only.\n    * </p>\n    * To wait for this call to complete use {@link JobPredicates#awaitComplete(CloudDNSApi, Job)}.\n    */\n   @Named(\"domain:update\")\n   @PUT\n   @Produces(MediaType.APPLICATION_JSON)\n   @Consumes(MediaType.APPLICATION_JSON)\n   @ResponseParser(ParseJob.class)\n   @Path(\"/domains\")\n   @MapBinder(UpdateDomainsToJSON.class)\n   Job<Void> updateTTL(@PayloadParam(\"ids\") Iterable<Integer> ids, @PayloadParam(\"ttl\") int ttl);\n\n   /**\n    * This call modifies the domain's email only.\n    * </p>\n    * To wait for this call to complete use {@link JobPredicates#awaitComplete(CloudDNSApi, Job)}.\n    */\n   @Named(\"domain:update\")\n   @PUT\n   @Produces(MediaType.APPLICATION_JSON)\n   @Consumes(MediaType.APPLICATION_JSON)\n   @ResponseParser(ParseJob.class)\n   @Path(\"/domains\")\n   @MapBinder(UpdateDomainsToJSON.class)\n   Job<Void> updateEmail(@PayloadParam(\"ids\") Iterable<Integer> ids, @PayloadParam(\"emailAddress\") String email);\n\n   /**\n    * This call removes one or more specified domains from the account; when a domain is deleted, its immediate resource\n    * records are also deleted from the account. By default, if a deleted domain had subdomains, each subdomain becomes\n    * a root domain and is not deleted; this can be overridden by the optional deleteSubdomains parameter. Utilizing the\n    * optional deleteSubdomains parameter on domains without subdomains does not result in a failure. When a domain is\n    * deleted, any and all domain data is immediately purged and is not recoverable via the API.\n    * </p>\n    * To wait for this call to complete use {@link JobPredicates#awaitComplete(CloudDNSApi, Job)}.\n    */\n   @Named(\"domain:delete\")\n   @DELETE\n   @Fallback(VoidOnNotFoundOr404.class)\n   @ResponseParser(ParseJob.class)\n   @Path(\"/domains\")\n   @Consumes(\"*/*\")\n   Job<Void> delete(@QueryParam(\"id\") Iterable<Integer> ids,\n         @QueryParam(\"deleteSubdomains\") boolean deleteSubdomains);\n\n   /**\n    * This call provides the BIND (Berkeley Internet Name Domain) 9 formatted contents of the requested domain. This\n    * call is for a single domain only, and as such, does not traverse up or down the domain hierarchy for details (that\n    * is, no subdomain information is provided).\n    * </p>\n    * To wait for this call to complete use {@link JobPredicates#awaitComplete(CloudDNSApi, Job)}.\n    */\n   @Named(\"domain:export\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @ResponseParser(ParseJob.class)\n   @Path(\"/domains/{id}/export\")\n   // format is ignored because the Cloud DNS API doesn't use it but other formats (e.g. BIND 10) may be supported in\n   // the future and we don't want this interface to change\n   Job<List<String>> exportFormat(@PathParam(\"id\") int id, Domain.Format format);\n\n   /**\n    * This call provisions a new DNS domain under the account specified by the BIND 9 formatted file configuration\n    * contents. If the corresponding request cannot be fulfilled due to insufficient or invalid data, an exception will\n    * be thrown with information regarding the nature of the failure in the body of the response. Failures in the\n    * validation process are non-recoverable and require the caller to correct the cause of the failure and call again.\n    * </p>\n    * To wait for this call to complete use {@link JobPredicates#awaitComplete(CloudDNSApi, Job)}.\n    */\n   @Named(\"domain:import\")\n   @POST\n   @Produces(MediaType.APPLICATION_JSON)\n   @Consumes(MediaType.APPLICATION_JSON)\n   @ResponseParser(ParseJob.class)\n   @MapBinder(FormatAndContentsToJSON.class)\n   @Path(\"/domains/import\")\n   Job<Domain> importFormat(\n         @PayloadParam(\"contents\") List<String> contents,\n         @PayloadParam(\"format\") Domain.Format format);\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/main/java/org/jclouds/rackspace/clouddns/v1/features/LimitApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.v2_0.domain.Limits;\nimport org.jclouds.rackspace.clouddns.v1.config.CloudDNS;\nimport org.jclouds.rest.annotations.Endpoint;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\n/**\n * All accounts, by default, have a preconfigured set of thresholds (or limits) to manage capacity and prevent abuse\n * of the system. The system recognizes two kinds of limits: rate limits and absolute limits. Rate limits are \n * thresholds that are reset after a certain amount of time passes. Absolute limits are fixed.\n */\n@Endpoint(CloudDNS.class)\n@RequestFilters(AuthenticateRequest.class)\npublic interface LimitApi {\n   /**\n    * Provides a list of all applicable limits.\n    */\n   @Named(\"limits:list\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @SelectJson(\"limits\")\n   @Path(\"/limits\")\n   Limits list();\n\n   /**\n    * All applicable limit types.\n    */\n   @Named(\"limits:list\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @SelectJson(\"limitTypes\")\n   @Path(\"/limits/types\")\n   Iterable<String> listTypes();\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/main/java/org/jclouds/rackspace/clouddns/v1/features/RecordApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1.features;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyPagedIterableOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.collect.PagedIterable;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.keystone.v2_0.KeystoneFallbacks;\nimport org.jclouds.openstack.v2_0.domain.PaginatedCollection;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\nimport org.jclouds.rackspace.clouddns.v1.CloudDNSApi;\nimport org.jclouds.rackspace.clouddns.v1.binders.UpdateRecordsToJSON;\nimport org.jclouds.rackspace.clouddns.v1.config.CloudDNS;\nimport org.jclouds.rackspace.clouddns.v1.domain.Job;\nimport org.jclouds.rackspace.clouddns.v1.domain.Record;\nimport org.jclouds.rackspace.clouddns.v1.domain.RecordDetail;\nimport org.jclouds.rackspace.clouddns.v1.functions.ParseJob;\nimport org.jclouds.rackspace.clouddns.v1.functions.ParseOnlyRecord;\nimport org.jclouds.rackspace.clouddns.v1.functions.ParseRecord;\nimport org.jclouds.rackspace.clouddns.v1.functions.ParseRecords;\nimport org.jclouds.rackspace.clouddns.v1.functions.RecordsToPagedIterable;\nimport org.jclouds.rackspace.clouddns.v1.predicates.JobPredicates;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Endpoint;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.Transform;\nimport org.jclouds.rest.annotations.WrapWith;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\n@Endpoint(CloudDNS.class)\n@RequestFilters(AuthenticateRequest.class)\npublic interface RecordApi {\n\n   /**\n    * Create Records for a Domain or Subdomain.\n    * </p>\n    * See <a href=\"http://docs.rackspace.com/cdns/api/v1.0/cdns-devguide/content/supported_record_types.html\">\n    * Supported Record Types</a>\n    * </p>\n    * To wait for this call to complete use {@link JobPredicates#awaitComplete(CloudDNSApi, Job)}.\n    */\n   @Named(\"record:create\")\n   @POST\n   @Consumes(MediaType.APPLICATION_JSON)\n   @ResponseParser(ParseJob.class)\n   @Path(\"/records\")\n   Job<Set<RecordDetail>> create(@WrapWith(\"records\") Iterable<Record> createRecords);\n\n   /**\n    * This call lists all records configured for the specified domain.\n    */\n   @Named(\"record:list\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @ResponseParser(ParseRecords.class)\n   @Transform(RecordsToPagedIterable.class)\n   @Path(\"/records\")\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   PagedIterable<RecordDetail> list();\n\n   /**\n    * RecordDetails filtered by type.\n    */\n   @Named(\"record:list\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @ResponseParser(ParseRecords.class)\n   @Transform(RecordsToPagedIterable.class)\n   @Path(\"/records\")\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   PagedIterable<RecordDetail> listByType(\n         @QueryParam(\"type\") String typeFilter);\n\n   /**\n    * RecordDetails filtered by type and data.\n    */\n   @Named(\"record:list\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @ResponseParser(ParseRecords.class)\n   @Transform(RecordsToPagedIterable.class)\n   @Path(\"/records\")\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   PagedIterable<RecordDetail> listByTypeAndData(\n         @QueryParam(\"type\") String typeFilter,\n         @QueryParam(\"data\") String dataFilter);\n\n   /**\n    * RecordDetails filtered by name and type.\n    */\n   @Named(\"record:list\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @ResponseParser(ParseRecords.class)\n   @Transform(RecordsToPagedIterable.class)\n   @Path(\"/records\")\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   PagedIterable<RecordDetail> listByNameAndType(\n         @QueryParam(\"name\") String nameFilter,\n         @QueryParam(\"type\") String typeFilter);\n\n   /**\n    * Use PaginationOptions to manually control the list of RecordDetail pages returned.\n    */\n   @Named(\"record:list\")\n   @GET\n   @ResponseParser(ParseRecords.class)\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(KeystoneFallbacks.EmptyPaginatedCollectionOnNotFoundOr404.class)\n   @Path(\"/records\")\n   PaginatedCollection<RecordDetail> list(PaginationOptions options);\n\n   /**\n    * RecordDetails filtered by name and type and data.\n    */\n   @Named(\"record:get\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @ResponseParser(ParseOnlyRecord.class)\n   @Path(\"/records\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   RecordDetail getByNameAndTypeAndData(\n         @QueryParam(\"name\") String nameFilter,\n         @QueryParam(\"type\") String typeFilter,\n         @QueryParam(\"data\") String dataFilter);\n\n   /**\n    * Get the details for the specified record in the specified domain.\n    */\n   @Named(\"record:get\")\n   @GET\n   @ResponseParser(ParseRecord.class)\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Path(\"/records/{recordId}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   RecordDetail get(@PathParam(\"recordId\") String recordId);\n\n   /**\n    * Update the configuration of the specified record in the specified domain.\n    * </p>\n    * To wait for this call to complete use {@link JobPredicates#awaitComplete(CloudDNSApi, Job)}.\n    */\n   @Named(\"record:update\")\n   @PUT\n   @Consumes(MediaType.APPLICATION_JSON)\n   @ResponseParser(ParseJob.class)\n   @Path(\"/records/{recordId}\")\n   Job<Void> update(\n         @PathParam(\"recordId\") String recordId,\n         @BinderParam(BindToJsonPayload.class) Record record);\n\n   /**\n    * Update the configuration of the specified records in the specified domain.\n    * </p>\n    * To wait for this call to complete use {@link JobPredicates#awaitComplete(CloudDNSApi, Job)}.\n    */\n   @Named(\"record:update\")\n   @PUT\n   @Consumes(MediaType.APPLICATION_JSON)\n   @ResponseParser(ParseJob.class)\n   @Path(\"/records\")\n   Job<Void> update(\n         @BinderParam(UpdateRecordsToJSON.class) Map<String, Record> idsToRecords);\n\n   /**\n    * Delete the specified record in the specified domain.\n    * </p>\n    * To wait for this call to complete use {@link JobPredicates#awaitComplete(CloudDNSApi, Job)}.\n    */\n   @Named(\"record:delete\")\n   @DELETE\n   @Fallback(VoidOnNotFoundOr404.class)\n   @ResponseParser(ParseJob.class)\n   @Path(\"/records/{recordId}\")\n   @Consumes(\"*/*\")\n   Job<Void> delete(@PathParam(\"recordId\") String recordId);\n\n   /**\n    * Delete the specified records in the specified domain.\n    * </p>\n    * To wait for this call to complete use {@link JobPredicates#awaitComplete(CloudDNSApi, Job)}.\n    */\n   @Named(\"record:delete\")\n   @DELETE\n   @Fallback(VoidOnNotFoundOr404.class)\n   @ResponseParser(ParseJob.class)\n   @Path(\"/records\")\n   @Consumes(\"*/*\")\n   Job<Void> delete(@QueryParam(\"id\") Iterable<String> recordId);\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/main/java/org/jclouds/rackspace/clouddns/v1/features/ReverseDNSApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1.features;\n\nimport java.net.URI;\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyPagedIterableOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.collect.PagedIterable;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.rackspace.clouddns.v1.CloudDNSApi;\nimport org.jclouds.rackspace.clouddns.v1.binders.CreateReverseDNSToJSON;\nimport org.jclouds.rackspace.clouddns.v1.binders.UpdateReverseDNSToJSON;\nimport org.jclouds.rackspace.clouddns.v1.config.CloudDNS;\nimport org.jclouds.rackspace.clouddns.v1.domain.Job;\nimport org.jclouds.rackspace.clouddns.v1.domain.Record;\nimport org.jclouds.rackspace.clouddns.v1.domain.RecordDetail;\nimport org.jclouds.rackspace.clouddns.v1.functions.ParseJob;\nimport org.jclouds.rackspace.clouddns.v1.functions.ParseRecord;\nimport org.jclouds.rackspace.clouddns.v1.functions.ParseRecords;\nimport org.jclouds.rackspace.clouddns.v1.functions.RecordsToPagedIterable;\nimport org.jclouds.rackspace.clouddns.v1.predicates.JobPredicates;\nimport org.jclouds.rest.annotations.Endpoint;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.Transform;\n\n/**\n * Cloud DNS supports the management of reverse DNS (PTR) records for Rackspace Cloud devices such as Cloud Load\n * Balancers and Cloud Servers (both first generation and next generation). In order to manage the PTR records for\n * Rackspace Cloud devices, the service as well as the device resource URI must be specified along with record details.\n */\n@Endpoint(CloudDNS.class)\n@RequestFilters(AuthenticateRequest.class)\npublic interface ReverseDNSApi {\n   /**\n    * List all of the Reverse DNS (PTR) records for a device.\n    */\n   @Named(\"rdns:list\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @ResponseParser(ParseRecords.class)\n   @Transform(RecordsToPagedIterable.class)\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   @Path(\"/rdns/{serviceName}\")\n   PagedIterable<RecordDetail> list(\n         @QueryParam(\"href\") URI deviceURI);\n\n   /**\n    * List all of the Reverse DNS (PTR) records for a device.\n    */\n   @Named(\"rdns:list\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @ResponseParser(ParseRecord.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   @Path(\"/rdns/{serviceName}/{recordId}\")\n   RecordDetail get(\n         @QueryParam(\"href\") URI deviceURI,\n         @PathParam(\"recordId\") String recordId);\n\n   /**\n    * Create Reverse DNS (PTR) records for a device.\n    * </p>\n    * To wait for this call to complete use {@link JobPredicates#awaitComplete(CloudDNSApi, Job)}.\n    */\n   @Named(\"rdns:create\")\n   @POST\n   @Produces(MediaType.APPLICATION_JSON)\n   @Consumes(MediaType.APPLICATION_JSON)\n   @ResponseParser(ParseJob.class)\n   @MapBinder(CreateReverseDNSToJSON.class)\n   @Path(\"/rdns\")\n   Job<Set<RecordDetail>> create(\n         @PayloadParam(\"href\") URI deviceURI,\n         @PayloadParam(\"records\") Iterable<Record> records);\n\n   /**\n    * Update Reverse DNS (PTR) records for a device.\n    * </p>\n    * To wait for this call to complete use {@link JobPredicates#awaitComplete(CloudDNSApi, Job)}.\n    */\n   @Named(\"rdns:update\")\n   @PUT\n   @Produces(MediaType.APPLICATION_JSON)\n   @Consumes(MediaType.APPLICATION_JSON)\n   @ResponseParser(ParseJob.class)\n   @MapBinder(UpdateReverseDNSToJSON.class)\n   @Path(\"/rdns\")\n   Job<Void> update(\n         @PayloadParam(\"href\") URI deviceURI,\n         @PayloadParam(\"idsToRecords\") Map<String, Record> idsToRecords);\n\n   /**\n    * Delete the Reverse DNS (PTR) record with the specified IP address for a device.\n    * </p>\n    * To wait for this call to complete use {@link JobPredicates#awaitComplete(CloudDNSApi, Job)}.\n    */\n   @Named(\"rdns:delete\")\n   @DELETE\n   @Fallback(VoidOnNotFoundOr404.class)\n   @ResponseParser(ParseJob.class)\n   @Path(\"/rdns/{serviceName}\")\n   @Consumes(\"*/*\")\n   Job<Void> delete(@QueryParam(\"href\") URI deviceURI, @QueryParam(\"ip\") String ipAddress);\n\n   /**\n    * Delete all Reverse DNS (PTR) records for a device.\n    * </p>\n    * To wait for this call to complete use {@link JobPredicates#awaitComplete(CloudDNSApi, Job)}.\n    */\n   @Named(\"rdns:delete\")\n   @DELETE\n   @Fallback(VoidOnNotFoundOr404.class)\n   @ResponseParser(ParseJob.class)\n   @Path(\"/rdns/{serviceName}\")\n   @Consumes(\"*/*\")\n   Job<Void> deleteAll(@QueryParam(\"href\") URI deviceURI);\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/main/java/org/jclouds/rackspace/clouddns/v1/functions/DomainFunctions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1.functions;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.rackspace.clouddns.v1.domain.Domain;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.Maps;\n\n/**\n * Functions for working with Domains.\n */\npublic class DomainFunctions {\n\n   /**\n    * Take a Set of Domains and return a Map of domain name to the Domain.\n    */\n   public static Map<String, Domain> toDomainMap(Set<Domain> domains) {\n      return Maps.uniqueIndex(domains, DomainFunctions.GET_DOMAIN_NAME);\n   }\n\n   /**\n    * Take a Domain and return its name.\n    */\n   public static final Function<Domain, String> GET_DOMAIN_NAME = new Function<Domain, String>() {\n      public String apply(Domain domain) {\n         return domain.getName();\n      }\n   };\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/main/java/org/jclouds/rackspace/clouddns/v1/functions/DomainsToPagedIterable.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.internal.Arg0ToPagedIterable;\nimport org.jclouds.openstack.v2_0.domain.PaginatedCollection;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\nimport org.jclouds.rackspace.clouddns.v1.CloudDNSApi;\nimport org.jclouds.rackspace.clouddns.v1.domain.Domain;\nimport org.jclouds.rackspace.clouddns.v1.features.DomainApi;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\n\n@Beta\npublic class DomainsToPagedIterable extends Arg0ToPagedIterable<Domain, DomainsToPagedIterable> {\n\n   private final DomainApi api;\n\n   @Inject\n   protected DomainsToPagedIterable(CloudDNSApi api) {\n      this.api = checkNotNull(api, \"api\").getDomainApi();\n   }\n\n   @Override\n   protected Function<Object, IterableWithMarker<Domain>> markerToNextForArg0(Optional<Object> arg0) {\n      return new ListDomainsAtMarker(api);\n   }\n\n   private static class ListDomainsAtMarker implements Function<Object, IterableWithMarker<Domain>> {\n      private final DomainApi api;\n\n      @Inject\n      protected ListDomainsAtMarker(DomainApi api) {\n         this.api = checkNotNull(api, \"api\");\n      }\n\n      public PaginatedCollection<Domain> apply(Object input) {\n         PaginationOptions paginationOptions = (PaginationOptions) input;\n\n         return api.list(paginationOptions);\n      }\n\n      public String toString() {\n         return \"ListDomainsAtMarker\";\n      }\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/main/java/org/jclouds/rackspace/clouddns/v1/functions/ParseDomain.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.rackspace.clouddns.v1.functions.ParseRecord.toRecordDetails;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.rackspace.clouddns.v1.domain.Domain;\nimport org.jclouds.rackspace.clouddns.v1.domain.RecordDetail;\nimport org.jclouds.rackspace.clouddns.v1.domain.Subdomain;\nimport org.jclouds.rackspace.clouddns.v1.functions.ParseRecord.RawRecord;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\n\npublic class ParseDomain implements Function<HttpResponse, Domain> {\n\n   private final ParseJson<RawDomain> json;\n\n   @Inject\n   ParseDomain(ParseJson<RawDomain> json) {\n      this.json = checkNotNull(json, \"json\");\n   }\n\n   @Override\n   public Domain apply(HttpResponse response) {\n      RawDomain rawDomain = json.apply(response);\n\n      if (rawDomain == null)\n         return null;\n\n      return rawDomain.getDomain();\n   }\n\n   /**\n    * This class is here only to deal with the domain JSON format in Cloud DNS.\n    */\n   static class RawDomain extends Domain {\n      @ConstructorProperties({ \"id\", \"name\", \"emailAddress\", \"comment\", \"created\", \"updated\", \"accountId\", \"ttl\",\n            \"nameservers\", \"subdomains\", \"recordsList\" })\n      protected RawDomain(int id, String name, String emailAddress, String comment, Date created, Date updated,\n            int accountId, int ttl, Iterable<Map<String, String>> nameservers,\n            SubdomainsWithTotalEntries subdomainsWTE, RecordsWithTotalEntries recordsWTE) {\n         super(id, name, emailAddress, comment, created, updated, accountId, ttl, transform(nameservers),\n               transform(subdomainsWTE), transform(recordsWTE));\n      }\n\n      public Domain getDomain() {\n         return from(this);\n      }\n\n      private static Set<String> transform(Iterable<Map<String, String>> nameserversNasty) {\n         Builder<String> nameservers = ImmutableSet.builder();\n\n         for (Map<String, String> nameToNameserver : nameserversNasty) {\n            nameservers.add(nameToNameserver.get(\"name\"));\n         }\n\n         return nameservers.build();\n      }\n\n      private static Set<Subdomain> transform(SubdomainsWithTotalEntries subdomainsWTE) {\n         if (subdomainsWTE == null) {\n            return null;\n         }\n         else {\n            return ImmutableSet.<Subdomain> copyOf(subdomainsWTE.subdomains);\n         }\n      }\n\n      private static Set<RecordDetail> transform(RecordsWithTotalEntries recordsWTE) {\n         if (recordsWTE == null) {\n            return null;\n         }\n         else {\n            Set<RecordDetail> recordDetails = FluentIterable.from(recordsWTE.records).transform(toRecordDetails).toSet();\n            return recordDetails;\n         }\n      }\n\n      /**\n       * This class is here only to deal with the domain JSON format in Cloud DNS.\n       */\n      private static class SubdomainsWithTotalEntries {\n         // ignore \"totalEntries\" in the JSON as it can just be derived form the size of subdomains\n         @Named(\"domains\")\n         private Iterable<Subdomain> subdomains;\n\n         @ConstructorProperties({ \"domains\" })\n         protected SubdomainsWithTotalEntries(Iterable<Subdomain> subdomains) {\n            this.subdomains = subdomains;\n         }\n      }\n\n      /**\n       * This class is here only to deal with the domain JSON format in Cloud DNS.\n       */\n      private static class RecordsWithTotalEntries {\n         // ignore \"totalEntries\" in the JSON as it can just be derived form the size of records\n         private Set<RawRecord> records;\n\n         @ConstructorProperties({ \"records\" })\n         protected RecordsWithTotalEntries(Set<RawRecord> records) {\n            this.records = records;\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/main/java/org/jclouds/rackspace/clouddns/v1/functions/ParseDomains.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.PaginatedCollection;\nimport org.jclouds.rackspace.clouddns.v1.domain.Domain;\n\nimport com.google.common.base.Function;\n\npublic class ParseDomains implements Function<HttpResponse, PaginatedCollection<Domain>> {\n\n   private final ParseJson<Domains> json;\n\n   @Inject\n   ParseDomains(ParseJson<Domains> json) {\n      this.json = checkNotNull(json, \"json\");\n   }\n\n   @Override\n   public PaginatedCollection<Domain> apply(HttpResponse response) {\n      Domains domains = json.apply(response);\n\n      return domains;\n   }\n\n   private static class Domains extends PaginatedCollection<Domain> {\n\n      @ConstructorProperties({ \"domains\", \"links\", \"totalEntries\" })\n      protected Domains(Iterable<Domain> domains, Iterable<Link> links, int totalEntries) {\n         super(domains, links, totalEntries);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/main/java/org/jclouds/rackspace/clouddns/v1/functions/ParseJob.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.rackspace.clouddns.v1.functions.ParseRecord.toRecordDetails;\n\nimport java.lang.reflect.Type;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.domain.JsonBall;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\nimport org.jclouds.rackspace.clouddns.v1.domain.Domain;\nimport org.jclouds.rackspace.clouddns.v1.domain.Job;\nimport org.jclouds.rackspace.clouddns.v1.domain.RecordDetail;\nimport org.jclouds.rackspace.clouddns.v1.functions.ParseDomain.RawDomain;\nimport org.jclouds.rackspace.clouddns.v1.functions.ParseRecord.RawRecord;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Iterators;\nimport com.google.common.collect.Lists;\nimport com.google.inject.TypeLiteral;\n\npublic class ParseJob implements Function<HttpResponse, Job<?>> {\n\n   private final ParseJson<RawJob> parseJson;\n   private final Json json;\n   private boolean isCreateSingleRecord;\n\n   @Inject\n   ParseJob(Json json, ParseJson<RawJob> parseJson) {\n      this.json = checkNotNull(json, \"json\");\n      this.parseJson = checkNotNull(parseJson, \"parseJson\");\n   }\n\n   @Override\n   public Job<?> apply(HttpResponse response) {\n      RawJob rawJob = parseJson.apply(response);\n\n      if (rawJob == null)\n         return null;\n\n      return toJob(rawJob);\n   }\n\n   public Job<?> toJob(RawJob in) {\n      return Job.builder().id(in.jobId).status(in.status).error(in.error)\n            .resource(parseResponse(in.requestUrl, in.response)).build();\n   }\n\n   protected Object parseResponse(String requestUrl, JsonBall response) {\n      if (response == null) {\n         return null;\n      }\n      else if (requestUrl.contains(\"import\")) {\n         Type type = new TypeLiteral<Map<String, Set<ParseDomain.RawDomain>>>() { }.getType();\n         Map<String, Set<RawDomain>> domainMap = json.fromJson(response.toString(), type);\n         Domain domain = Iterators.getOnlyElement(domainMap.get(\"domains\").iterator()).getDomain();\n\n         return domain;\n      }\n      else if (requestUrl.contains(\"export\")) {\n         Type type = new TypeLiteral<Map<String, String>>() { }.getType();\n         Map<String, String> exportMap = json.fromJson(response.toString(), type);\n         String contents = exportMap.get(\"contents\");\n         List<String> contentsAsList = Lists.newArrayList(Splitter.on(\"\\n\").omitEmptyStrings().split(contents));\n\n         return contentsAsList;\n      }\n      else if (response.toString().contains(\"domains\")) {\n         Type type = new TypeLiteral<Map<String, Set<RawDomain>>>() { }.getType();\n         Map<String, Set<RawDomain>> domainMap = json.fromJson(response.toString(), type);\n         Set<Domain> domains = FluentIterable.from(domainMap.get(\"domains\")).transform(toDomain).toSet();\n\n         return domains;\n      }\n      else if (response.toString().contains(\"records\")) {\n         Type type = new TypeLiteral<Map<String, Set<RawRecord>>>() { }.getType();\n         Map<String, Set<RawRecord>> recordMap = json.fromJson(response.toString(), type);\n         Set<RecordDetail> records = FluentIterable.from(recordMap.get(\"records\")).transform(toRecordDetails).toSet();\n         \n         if (isCreateSingleRecord) {\n            return Iterables.getOnlyElement(records);\n         } else {\n            return records;\n         }\n      }\n      else {\n         throw new IllegalStateException(\"Job parsing problem. Did not recognize any type in job response.\\n\"\n               + response.toString());\n      }\n   }\n\n   private static class RawJob {\n      private String jobId;\n      private Job.Status status;\n      private Job.Error error;\n      private String requestUrl;\n      private JsonBall response;\n   }\n\n   private static final Function<RawDomain, Domain> toDomain = new Function<RawDomain, Domain>() {\n      public Domain apply(RawDomain domain) {\n         return domain.getDomain();\n      }\n   };\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/main/java/org/jclouds/rackspace/clouddns/v1/functions/ParseOnlyRecord.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.rackspace.clouddns.v1.functions.ParseRecord.toRecordDetails;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.rackspace.clouddns.v1.domain.RecordDetail;\nimport org.jclouds.rackspace.clouddns.v1.functions.ParseRecord.RawRecord;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.Iterables;\n\npublic class ParseOnlyRecord implements Function<HttpResponse, RecordDetail> {\n\n   private final ParseJson<Map<String, List<RawRecord>>> json;\n\n   @Inject\n   ParseOnlyRecord(ParseJson<Map<String, List<RawRecord>>> json) {\n      this.json = checkNotNull(json, \"json\");\n   }\n\n   @Override\n   public RecordDetail apply(HttpResponse response) {\n      Map<String, List<RawRecord>> records = json.apply(response);\n\n      if (records == null)\n         return null;\n      \n      RawRecord rawRecord = Iterables.getOnlyElement(records.get(\"records\"));\n\n      return toRecordDetails.apply(rawRecord);\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/main/java/org/jclouds/rackspace/clouddns/v1/functions/ParseRecord.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.rackspace.clouddns.v1.domain.Record;\nimport org.jclouds.rackspace.clouddns.v1.domain.RecordDetail;\n\nimport com.google.common.base.Function;\n\npublic class ParseRecord implements Function<HttpResponse, RecordDetail> {\n\n   private final ParseJson<RawRecord> json;\n\n   @Inject\n   ParseRecord(ParseJson<RawRecord> json) {\n      this.json = checkNotNull(json, \"json\");\n   }\n\n   @Override\n   public RecordDetail apply(HttpResponse response) {\n      RawRecord rawRecord = json.apply(response);\n\n      if (rawRecord == null)\n         return null;\n\n      return toRecordDetails.apply(rawRecord);\n   }\n\n   static class RawRecord {\n      public String id;\n      public String name;\n      public String type;\n      public int ttl;\n      public String data;\n      public Integer priority;\n      public String comment;\n      public Date created;\n      public Date updated;\n\n      @ConstructorProperties({ \"id\", \"name\", \"type\", \"ttl\", \"data\", \"priority\", \"comment\", \"created\", \"updated\" })\n      protected RawRecord(String id, String name, String type, int ttl, String data, Integer priority, String comment,\n            Date created, Date updated) {\n         super();\n         this.id = id;\n         this.name = name;\n         this.type = type;\n         this.ttl = ttl;\n         this.data = data;\n         this.priority = priority;\n         this.comment = comment;\n         this.created = created;\n         this.updated = updated;\n      }\n   }\n\n   static final Function<RawRecord, RecordDetail> toRecordDetails = new Function<RawRecord, RecordDetail>() {\n      @Override\n      public RecordDetail apply(RawRecord rawRecord) {\n         Record record = Record.builder().name(rawRecord.name).type(rawRecord.type).ttl(rawRecord.ttl)\n               .data(rawRecord.data).priority(rawRecord.priority).comment(rawRecord.comment).build();\n         RecordDetail recordDetails = RecordDetail.builder().id(rawRecord.id).created(rawRecord.created)\n               .updated(rawRecord.updated).record(record).build();\n\n         return recordDetails;\n      }\n   };\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/main/java/org/jclouds/rackspace/clouddns/v1/functions/ParseRecords.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.rackspace.clouddns.v1.functions.ParseRecord.toRecordDetails;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.PaginatedCollection;\nimport org.jclouds.rackspace.clouddns.v1.domain.RecordDetail;\nimport org.jclouds.rackspace.clouddns.v1.functions.ParseRecord.RawRecord;\n\nimport com.google.common.base.Function;\n\npublic class ParseRecords implements Function<HttpResponse, PaginatedCollection<RecordDetail>> {\n\n   private final ParseJson<RawRecords> json;\n\n   @Inject\n   ParseRecords(ParseJson<RawRecords> json) {\n      this.json = checkNotNull(json, \"json\");\n   }\n\n   @Override\n   public PaginatedCollection<RecordDetail> apply(HttpResponse response) {\n      RawRecords rawRecords = json.apply(response);\n      Iterable<RecordDetail> records = rawRecords.transform(toRecordDetails);\n\n      return new Records(records, rawRecords.getLinks(), rawRecords.getTotalEntries().get());\n   }\n\n   private static class RawRecords extends PaginatedCollection<RawRecord> {\n\n      @ConstructorProperties({ \"records\", \"links\", \"totalEntries\" })\n      protected RawRecords(Iterable<RawRecord> records, Iterable<Link> links, int totalEntries) {\n         super(records, links, totalEntries);\n      }\n   }\n\n   private static class Records extends PaginatedCollection<RecordDetail> {\n\n      protected Records(Iterable<RecordDetail> records, Iterable<Link> links, int totalEntries) {\n         super(records, links, totalEntries);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/main/java/org/jclouds/rackspace/clouddns/v1/functions/ParseSubdomains.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.domain.PaginatedCollection;\nimport org.jclouds.rackspace.clouddns.v1.domain.Subdomain;\nimport org.jclouds.rest.InvocationContext;\n\nimport com.google.common.base.Function;\n\npublic class ParseSubdomains implements Function<HttpResponse, PaginatedCollection<Subdomain>>, InvocationContext<ParseSubdomains> {\n\n   private final ParseJson<Subdomains> json;\n\n   @Inject\n   ParseSubdomains(ParseJson<Subdomains> json) {\n      this.json = checkNotNull(json, \"json\");\n   }\n\n   @Override\n   public PaginatedCollection<Subdomain> apply(HttpResponse response) {\n      Subdomains subdomains = json.apply(response);\n\n      return subdomains;\n   }\n\n   @Override\n   public ParseSubdomains setContext(HttpRequest request) {\n      return this;\n   }\n\n   static class Subdomains extends PaginatedCollection<Subdomain> {\n\n      @ConstructorProperties({ \"domains\", \"links\", \"totalEntries\" })\n      protected Subdomains(Iterable<Subdomain> domains, Iterable<Link> links, int totalEntries) {\n         super(domains, links, totalEntries);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/main/java/org/jclouds/rackspace/clouddns/v1/functions/RecordFunctions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1.functions;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.rackspace.clouddns.v1.domain.Record;\nimport org.jclouds.rackspace.clouddns.v1.domain.RecordDetail;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.Maps;\n\n/**\n * Functions for working with Records.\n */\npublic class RecordFunctions {\n   \n   private RecordFunctions() {\n   }\n\n   /**\n    * Take a Set of RecordDetails and return a Map of record id to the Record.\n    */\n   public static Map<String, Record> toRecordMap(Set<RecordDetail> recordDetails) {\n      Map<String, RecordDetail> idsToRecordDetails = Maps.uniqueIndex(recordDetails, RecordFunctions.GET_RECORD_ID);\n      return Maps.transformValues(idsToRecordDetails, RecordFunctions.GET_RECORD);\n   }\n   \n   /**\n    * Take a RecordDetail and return its id.\n    */\n   public static final Function<RecordDetail, String> GET_RECORD_ID = new Function<RecordDetail, String>() {\n      public String apply(RecordDetail recordDetail) {\n         return recordDetail.getId();\n      }\n   };\n   /**\n    * Take a RecordDetail and return its Record.\n    */\n   public static final Function<RecordDetail, Record> GET_RECORD = new Function<RecordDetail, Record>() {\n      public Record apply(RecordDetail recordDetail) {\n         return recordDetail.getRecord();\n      }\n   };   \n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/main/java/org/jclouds/rackspace/clouddns/v1/functions/RecordsToPagedIterable.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.internal.Arg0ToPagedIterable;\nimport org.jclouds.openstack.v2_0.domain.PaginatedCollection;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\nimport org.jclouds.rackspace.clouddns.v1.CloudDNSApi;\nimport org.jclouds.rackspace.clouddns.v1.domain.RecordDetail;\nimport org.jclouds.rackspace.clouddns.v1.features.RecordApi;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\n\n@Beta\npublic class RecordsToPagedIterable extends Arg0ToPagedIterable.FromCaller<RecordDetail, RecordsToPagedIterable> {\n\n   private final CloudDNSApi api;\n\n   @Inject\n   protected RecordsToPagedIterable(CloudDNSApi api) {\n      this.api = checkNotNull(api, \"api\");\n   }\n\n   @Override\n   protected Function<Object, IterableWithMarker<RecordDetail>> markerToNextForArg0(Optional<Object> arg0) {\n      int domainId = Integer.class.cast(arg0.get());\n      return new ListRecordsAtMarker(api.getRecordApi(domainId));\n   }\n\n   private static class ListRecordsAtMarker implements Function<Object, IterableWithMarker<RecordDetail>> {\n      private final RecordApi api;\n\n      @Inject\n      protected ListRecordsAtMarker(RecordApi api) {\n         this.api = checkNotNull(api, \"api\");\n      }\n\n      public PaginatedCollection<RecordDetail> apply(Object input) {\n         PaginationOptions paginationOptions = (PaginationOptions) input;\n\n         return api.list(paginationOptions);\n      }\n\n      public String toString() {\n         return \"ListRecordsAtMarker\";\n      }\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/main/java/org/jclouds/rackspace/clouddns/v1/functions/SubdomainsToPagedIterable.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.internal.Arg0ToPagedIterable;\nimport org.jclouds.openstack.v2_0.domain.PaginatedCollection;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\nimport org.jclouds.rackspace.clouddns.v1.CloudDNSApi;\nimport org.jclouds.rackspace.clouddns.v1.domain.Subdomain;\nimport org.jclouds.rackspace.clouddns.v1.features.DomainApi;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\n\n@Beta\npublic class SubdomainsToPagedIterable extends Arg0ToPagedIterable<Subdomain, SubdomainsToPagedIterable> {\n\n   private final DomainApi api;\n\n   @Inject\n   protected SubdomainsToPagedIterable(CloudDNSApi api) {\n      this.api = checkNotNull(api, \"api\").getDomainApi();\n   }\n\n   @Override\n   protected Function<Object, IterableWithMarker<Subdomain>> markerToNextForArg0(Optional<Object> domainId) {\n      return new ListSubdomainsUnderDomainIdAtMarker(api, Integer.parseInt(domainId.get().toString()));\n   }\n\n   private static class ListSubdomainsUnderDomainIdAtMarker implements Function<Object, IterableWithMarker<Subdomain>> {\n      private final DomainApi api;\n      private final int domainId;\n\n      @Inject\n      protected ListSubdomainsUnderDomainIdAtMarker(DomainApi api, int domainId) {\n         this.api = checkNotNull(api, \"api\");\n         this.domainId = domainId;\n      }\n\n      public PaginatedCollection<Subdomain> apply(Object input) {\n         PaginationOptions paginationOptions = (PaginationOptions) input;\n\n         return api.listSubdomains(domainId, paginationOptions);\n      }\n\n      public String toString() {\n         return \"ListSubdomainsUnderDomainIdAtMarker(\" + domainId + \")\";\n      }\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/main/java/org/jclouds/rackspace/clouddns/v1/predicates/JobPredicates.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static org.jclouds.util.Predicates2.retry;\n\nimport java.util.concurrent.TimeoutException;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport org.jclouds.rackspace.clouddns.v1.CloudDNSApi;\nimport org.jclouds.rackspace.clouddns.v1.CloudDNSExceptions;\nimport org.jclouds.rackspace.clouddns.v1.domain.Job;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.util.concurrent.Atomics;\n\n/**\n * Useful Predicates for dealing with Jobs.\n */\npublic class JobPredicates {\n   \n   private JobPredicates() {\n   }\n\n   /**\n    * Tests to see if a Job has completed.\n    *\n    * <pre>\n    * {@code\n    * CreateDomain createDomain1 = CreateDomain.builder()\n    *    .name(\"jclouds-example.org\")\n    *    .email(\"jclouds@jclouds-example.org\")\n    *    .ttl(600001)\n    *    .comment(\"Hello Domain 1\")\n    *    .build();\n    *\n    * Iterable<CreateDomain> createDomains = ImmutableList.of(createDomain1);      \n    * Set<Domain> domains = awaitComplete(api, api.getDomainApi().create(createDomains));\n    * }\n    * </pre>\n    */\n   public static <T> T awaitComplete(CloudDNSApi api, Job<T> job)\n         throws TimeoutException {\n      AtomicReference<Job<T>> jobRef = Atomics.newReference(job);\n\n      if (!retry(jobCompleted(api), 600, 2, 2, SECONDS).apply(jobRef)) {\n         throw new TimeoutException(\"Timeout on: \" + jobRef.get());\n      }\n\n      return jobRef.get().getResource().orNull();\n   }\n   \n   @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n   private static Predicate<AtomicReference<? extends Job<?>>> jobCompleted(CloudDNSApi cloudDNSApi) {\n      return new JobStatusPredicate(cloudDNSApi, Job.Status.COMPLETED);\n   }\n   \n   private static class JobStatusPredicate<T> implements Predicate<AtomicReference<Job<?>>> {\n      private CloudDNSApi cloudDNSApi;\n      private Job.Status status;\n\n      private JobStatusPredicate(CloudDNSApi cloudDNSApi, Job.Status status) {\n         this.cloudDNSApi = checkNotNull(cloudDNSApi, \"domainApi must be defined\");\n         this.status = checkNotNull(status, \"status must be defined\");\n      }\n      \n      /**\n       * @return boolean Return true when the Job reaches status, false otherwise.\n       */\n      @Override\n      public boolean apply(AtomicReference<Job<?>> jobRef) {\n         checkNotNull(jobRef, \"job must be defined\");\n\n         if (status.equals(jobRef.get().getStatus())) {\n            return true;\n         }\n         else {\n            jobRef.set(cloudDNSApi.getJob(jobRef.get().getId()));\n            checkNotNull(jobRef.get(), \"Job %s not found.\", jobRef.get().getId());\n            \n            if (jobRef.get().getError().isPresent()) {\n               throw new CloudDNSExceptions.JobErrorException(jobRef.get().getError().get());\n            }\n            \n            return status.equals(jobRef.get().getStatus());\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/java/org/jclouds/rackspace/clouddns/v1/features/CloudDNSApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\n\nimport java.net.URI;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rackspace.clouddns.v1.CloudDNSApi;\nimport org.jclouds.rackspace.clouddns.v1.domain.Domain;\nimport org.jclouds.rackspace.clouddns.v1.domain.Job;\nimport org.jclouds.rackspace.clouddns.v1.internal.BaseCloudDNSApiExpectTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class CloudDNSApiExpectTest extends BaseCloudDNSApiExpectTest<CloudDNSApi> {\n   public void testGetJobDomainExport() {\n      URI endpoint = URI.create(\"https://dns.api.rackspacecloud.com/v1.0/123123/status/bfbd6ec8-5d4c-49f8-97b5-aa5bfd3e95a4?showDetails=true\");\n      CloudDNSApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey, \n            responseWithAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/job.json\")).build());\n\n      Job<Domain> job = api.getJob(\"bfbd6ec8-5d4c-49f8-97b5-aa5bfd3e95a4\");\n      assertEquals(job.getStatus(), Job.Status.RUNNING);\n      assertFalse(job.getResource().isPresent());\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/java/org/jclouds/rackspace/clouddns/v1/features/DomainApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1.features;\n\nimport static jakarta.ws.rs.HttpMethod.POST;\nimport static jakarta.ws.rs.HttpMethod.PUT;\nimport static jakarta.ws.rs.core.Response.Status.OK;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.Calendar;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.SimpleTimeZone;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rackspace.clouddns.v1.CloudDNSApi;\nimport org.jclouds.rackspace.clouddns.v1.domain.CreateDomain;\nimport org.jclouds.rackspace.clouddns.v1.domain.CreateSubdomain;\nimport org.jclouds.rackspace.clouddns.v1.domain.Domain;\nimport org.jclouds.rackspace.clouddns.v1.domain.DomainChange;\nimport org.jclouds.rackspace.clouddns.v1.domain.Job;\nimport org.jclouds.rackspace.clouddns.v1.domain.Record;\nimport org.jclouds.rackspace.clouddns.v1.domain.Subdomain;\nimport org.jclouds.rackspace.clouddns.v1.domain.UpdateDomain;\nimport org.jclouds.rackspace.clouddns.v1.functions.DomainFunctions;\nimport org.jclouds.rackspace.clouddns.v1.internal.BaseCloudDNSApiExpectTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\")\npublic class DomainApiExpectTest extends BaseCloudDNSApiExpectTest<CloudDNSApi> {\n   private static final String JCLOUDS_EXAMPLE = \"jclouds-example.com\";\n\n   public void testCreateDomain() {\n      URI endpoint = URI.create(\"https://dns.api.rackspacecloud.com/v1.0/123123/domains\");\n      DomainApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey, \n            responseWithAccess,\n            authenticatedGET()\n               .method(POST)\n               .payload(payloadFromResource(\"/domain-create.json\"))\n               .endpoint(endpoint)\n               .build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/domain-create-response.json\")).build())\n            .getDomainApi();\n\n      Record createMXRecord = Record.builder()\n            .type(\"MX\")\n            .name(JCLOUDS_EXAMPLE)\n            .data(\"mail.\" + JCLOUDS_EXAMPLE)\n            .priority(11235)\n            .build();\n      \n      Record createARecord = Record.builder()\n            .type(\"A\")\n            .name(JCLOUDS_EXAMPLE)\n            .data(\"10.0.0.1\")\n            .build();\n      \n      List<Record> createRecords = ImmutableList.of(createMXRecord, createARecord);\n      \n      CreateSubdomain createSubdomain1 = CreateSubdomain.builder()\n            .name(\"dev.\" + JCLOUDS_EXAMPLE)\n            .email(\"jclouds@\" + JCLOUDS_EXAMPLE)\n            .comment(\"Hello dev subdomain\")\n            .build();\n      \n      CreateSubdomain createSubdomain2 = CreateSubdomain.builder()\n            .name(\"test.\" + JCLOUDS_EXAMPLE)\n            .email(\"jclouds@\" + JCLOUDS_EXAMPLE)\n            .comment(\"Hello test subdomain\")\n            .build();\n      \n      List<CreateSubdomain> createSubdomains = ImmutableList.of(createSubdomain1, createSubdomain2);\n\n      CreateDomain createDomain1 = CreateDomain.builder()\n            .name(JCLOUDS_EXAMPLE)\n            .email(\"jclouds@\" + JCLOUDS_EXAMPLE)\n            .ttl(600000)\n            .comment(\"Hello Domain\")\n            .subdomains(createSubdomains)\n            .records(createRecords)\n            .build();\n\n      CreateDomain createDomain2 = CreateDomain.builder()\n            .name(\"x\" + JCLOUDS_EXAMPLE)\n            .email(\"jclouds@\" + JCLOUDS_EXAMPLE)\n            .ttl(600000)\n            .comment(\"Hello Domain\")\n            .build();\n\n      Iterable<CreateDomain> createDomains = ImmutableList.of(createDomain1, createDomain2);\n      Job<Set<Domain>> job = api.create(createDomains);\n      \n      assertEquals(job.getStatus(), Job.Status.COMPLETED);\n      assertTrue(job.getResource().isPresent());\n      \n      Map<String, Domain> domains = DomainFunctions.toDomainMap(job.getResource().get());\n      \n      assertEquals(domains.get(JCLOUDS_EXAMPLE).getId(), 3650906);\n      assertEquals(domains.get(JCLOUDS_EXAMPLE).getEmail(), \"jclouds@jclouds-example.com\");\n      assertEquals(domains.get(JCLOUDS_EXAMPLE).getSubdomains().size(), 2);\n      assertEquals(domains.get(JCLOUDS_EXAMPLE).getRecords().size(), 2);\n      assertEquals(domains.get(\"x\" + JCLOUDS_EXAMPLE).getId(), 3650909);\n   }\n\n   public void testListDomains() {\n      URI endpoint = URI.create(\"https://dns.api.rackspacecloud.com/v1.0/123123/domains\");\n      DomainApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey, \n            responseWithAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/domain-list.json\")).build())\n            .getDomainApi();\n\n      ImmutableList<Domain> domains = api.list().concat().toList();\n      assertEquals(domains.size(), 4);\n      \n      for (Domain domain : domains) {\n         assertTrue(domain.getName().contains(JCLOUDS_EXAMPLE));\n      }\n   }\n\n   public void testListDomainsPaginated() {\n      URI endpointPage1 = URI.create(\"https://dns.api.rackspacecloud.com/v1.0/123123/domains\");\n      URI endpointPage2 = URI.create(\"https://dns.api.rackspacecloud.com/v1.0/123123/domains?limit=4&offset=4\");\n      DomainApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey, \n            responseWithAccess,\n            authenticatedGET().endpoint(endpointPage1).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/domain-list-page1.json\")).build(),\n            authenticatedGET().endpoint(endpointPage2).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/domain-list-page2.json\")).build())\n            .getDomainApi();\n\n      ImmutableList<Domain> domains = api.list().concat().toList();\n      assertEquals(domains.size(), 8);\n      \n      for (Domain domain : domains) {\n         assertTrue(domain.getName().contains(JCLOUDS_EXAMPLE));\n      }\n   }\n\n   public void testListSubdomains() {\n      URI endpoint = URI.create(\"https://dns.api.rackspacecloud.com/v1.0/123123/domains/3650908/subdomains\");\n      DomainApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey, \n            responseWithAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/subdomain-list.json\")).build())\n            .getDomainApi();\n\n      ImmutableList<Subdomain> subdomains = api.listSubdomains(3650908).concat().toList();\n      assertEquals(subdomains.size(), 4);\n      \n      for (Subdomain subdomain : subdomains) {\n         assertTrue(subdomain.getName().contains(JCLOUDS_EXAMPLE));\n      }\n   }\n\n   public void testListSubdomainsPaginated() {\n      URI endpointPage1 = URI.create(\"https://dns.api.rackspacecloud.com/v1.0/123123/domains/3650908/subdomains\");\n      URI endpointPage2 = URI.create(\"https://dns.api.rackspacecloud.com/v1.0/123123/domains/3650908/subdomains?limit=4&offset=4\");\n      DomainApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey, \n            responseWithAccess,\n            authenticatedGET().endpoint(endpointPage1).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/subdomain-list-page1.json\")).build(),\n            authenticatedGET().endpoint(endpointPage2).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/subdomain-list-page2.json\")).build())\n            .getDomainApi();\n\n      ImmutableList<Subdomain> subdomains = api.listSubdomains(3650908).concat().toList();\n      assertEquals(subdomains.size(), 8);\n      \n      for (Subdomain subdomain : subdomains) {\n         assertTrue(subdomain.getName().contains(JCLOUDS_EXAMPLE));\n      }\n   }\n\n   public void testListWithFilterByNamesMatching() {\n      URI endpoint = URI.create(\"https://dns.api.rackspacecloud.com/v1.0/123123/domains?name=test.jclouds-example.com\");\n      DomainApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey, \n            responseWithAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/domain-list-with-filter.json\")).build())\n            .getDomainApi();\n\n      ImmutableList<Domain> domains = api.listWithFilterByNamesMatching(\"test.\" + JCLOUDS_EXAMPLE).concat().toList();\n      assertEquals(domains.size(), 1);\n      assertEquals(domains.get(0).getId(), 3650908);\n      assertEquals(domains.get(0).getName(), \"test.\" + JCLOUDS_EXAMPLE);\n   }\n\n   public void testListDomainChanges() {\n      URI endpoint = URI.create(\"https://dns.api.rackspacecloud.com/v1.0/123123/domains/3650908/changes?changes=2013-03-22T03%3A39%3A31Z\");\n      DomainApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey, \n            responseWithAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/domain-list-changes.json\")).build())\n            .getDomainApi();\n\n      Calendar cal = Calendar.getInstance(new SimpleTimeZone(0, \"GMT\"));\n      cal.set(2013, 2, 22, 3, 39, 31);\n      DomainChange domainChange = api.listChanges(3650908, cal.getTime());\n      \n      assertEquals(domainChange.getChanges().size(), 25);\n   }\n\n   public void testGetDomain() {\n      URI endpoint = URI.create(\"https://dns.api.rackspacecloud.com/v1.0/123123/domains/3650908?showRecords=true&showSubdomains=true\");\n      DomainApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey, \n            responseWithAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/domain-get.json\")).build())\n            .getDomainApi();\n\n      Domain domain = api.get(3650908);\n      assertEquals(domain.getName(), \"test.\" + JCLOUDS_EXAMPLE);\n      assertEquals(domain.getRecords().size(), 2);\n      assertEquals(domain.getComment().get(), \"Hello test subdomain\");\n      assertEquals(domain.getTTL(), 3600);\n   }\n   \n   @SuppressWarnings(\"rawtypes\")\n   public void testUpdateDomain() {\n      URI endpoint = URI.create(\"https://dns.api.rackspacecloud.com/v1.0/123123/domains/3650908\");\n      DomainApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey, \n            responseWithAccess,\n            authenticatedGET()\n               .method(PUT)\n               .payload(payloadFromResourceWithContentType(\"/domain-update.json\", MediaType.APPLICATION_JSON))\n               .endpoint(endpoint)\n               .build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/domain-update-response.json\")).build())\n            .getDomainApi();\n\n      UpdateDomain updateDomain = UpdateDomain.builder()\n            .email(\"everett@\" + JCLOUDS_EXAMPLE)\n            .ttl(600001)\n            .comment(\"Hello Domain Update\")\n            .build();\n\n      Job job = api.update(3650908, updateDomain);\n      \n      assertEquals(job.getStatus(), Job.Status.COMPLETED);\n   }\n   \n   @SuppressWarnings(\"rawtypes\")\n   public void testUpdateDomainsTTL() {\n      URI endpoint = URI.create(\"https://dns.api.rackspacecloud.com/v1.0/123123/domains\");\n      DomainApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey, \n            responseWithAccess,\n            authenticatedGET()\n               .method(PUT)\n               .payload(payloadFromResource(\"/domain-update-ttl.json\"))\n               .endpoint(endpoint)\n               .build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/domain-update-response.json\")).build())\n            .getDomainApi();\n\n      List<Integer> ids = ImmutableList.of(3650906, 3650908);\n      Job job = api.updateTTL(ids, 1234567);\n      \n      assertEquals(job.getStatus(), Job.Status.COMPLETED);\n   }\n   \n   @SuppressWarnings(\"rawtypes\")\n   public void testUpdateDomainsEmail() {\n      URI endpoint = URI.create(\"https://dns.api.rackspacecloud.com/v1.0/123123/domains\");\n      DomainApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey, \n            responseWithAccess,\n            authenticatedGET()\n               .method(PUT)\n               .payload(payloadFromResource(\"/domain-update-email.json\"))\n               .endpoint(endpoint)\n               .build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/domain-update-response.json\")).build())\n            .getDomainApi();\n\n      List<Integer> ids = ImmutableList.of(3650906, 3650908);\n      Job job = api.updateEmail(ids, \"everett@\" + JCLOUDS_EXAMPLE);\n      \n      assertEquals(job.getStatus(), Job.Status.COMPLETED);\n   }\n\n   @SuppressWarnings(\"rawtypes\")\n   public void testDeleteDomains() {\n      URI endpoint = URI.create(\"https://dns.api.rackspacecloud.com/v1.0/123123/domains?id=3650907&id=3650906&id=3650908&id=3650909&deleteSubdomains=true\");\n      DomainApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey, \n            responseWithAccess,\n            authenticatedGET().method(\"DELETE\").replaceHeader(\"Accept\", MediaType.WILDCARD).endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/domain-delete.json\")).build())\n            .getDomainApi();\n\n      List<Integer> domainIds = ImmutableList.<Integer> of(3650907, 3650906, 3650908, 3650909);      \n      Job job = api.delete(domainIds, true);\n\n      assertEquals(job.getStatus(), Job.Status.COMPLETED);\n   }\n\n   public void testExportDomain() {\n      URI endpoint = URI.create(\"https://dns.api.rackspacecloud.com/v1.0/123123/domains/3651323/export\");\n      DomainApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey, \n            responseWithAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/domain-export.json\")).build())\n            .getDomainApi();\n\n      Job<List<String>> job = api.exportFormat(3651323, Domain.Format.BIND_9);\n      assertEquals(job.getStatus(), Job.Status.COMPLETED);\n      assertEquals(job.getResource().get().size(), 5);\n   }\n\n   public void testImportDomain() {\n      URI endpoint = URI.create(\"https://dns.api.rackspacecloud.com/v1.0/123123/domains/import\");\n      DomainApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey, \n            responseWithAccess,\n            authenticatedGET()\n               .method(POST)\n               .payload(payloadFromResource(\"/domain-import.json\"))\n               .endpoint(endpoint)\n               .build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/domain-import-response.json\")).build())\n            .getDomainApi();\n\n      List<String> contents = ImmutableList.<String> of(\n            \"jclouds-example.com.      3600  IN SOA   ns.rackspace.com. jclouds.jclouds-example.com. 1363882703 3600 3600 3600 3600\",\n            \"jclouds-example.com.      600   IN A  50.56.174.152\"); \n\n      Job<Domain> job = api.importFormat(contents, Domain.Format.BIND_9);\n      assertEquals(job.getStatus(), Job.Status.COMPLETED);\n      assertEquals(job.getResource().get().getName(), JCLOUDS_EXAMPLE);\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/java/org/jclouds/rackspace/clouddns/v1/features/DomainApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1.features;\n\nimport static org.jclouds.rackspace.clouddns.v1.predicates.JobPredicates.awaitComplete;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.TimeoutException;\n\nimport org.jclouds.rackspace.clouddns.v1.domain.CreateDomain;\nimport org.jclouds.rackspace.clouddns.v1.domain.CreateSubdomain;\nimport org.jclouds.rackspace.clouddns.v1.domain.Domain;\nimport org.jclouds.rackspace.clouddns.v1.domain.Record;\nimport org.jclouds.rackspace.clouddns.v1.domain.RecordDetail;\nimport org.jclouds.rackspace.clouddns.v1.domain.Subdomain;\nimport org.jclouds.rackspace.clouddns.v1.domain.UpdateDomain;\nimport org.jclouds.rackspace.clouddns.v1.functions.DomainFunctions;\nimport org.jclouds.rackspace.clouddns.v1.internal.BaseCloudDNSApiLiveTest;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Lists;\nimport com.google.common.collect.Maps;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"DomainApiLiveTest\")\npublic class DomainApiLiveTest extends BaseCloudDNSApiLiveTest {\n\n   // just in case the username has a '.' we replace it to avoid creating subdomains\n   private static final String JCLOUDS_EXAMPLE = System.getProperty(\"user.name\").replace('.', '-') + \"-domaintest-jclouds.org\";\n   \n   private Map<String, Domain> testDomains;\n\n   @Test\n   public void testCreateDomainsWithSubdomainsAndRecords() throws Exception {\n      Record createMXRecord = Record.builder()\n            .type(\"MX\")\n            .name(JCLOUDS_EXAMPLE)\n            .data(\"mail.\" + JCLOUDS_EXAMPLE)\n            .priority(11235)\n            .comment(\"MX Record\")\n            .ttl(60000)\n            .build();\n      \n      Record createARecord = Record.builder()\n            .type(\"A\")\n            .name(JCLOUDS_EXAMPLE)\n            .data(\"10.0.0.1\")\n            .comment(\"A Record\")\n            .ttl(60000)\n            .build();\n      \n      List<Record> createRecords = ImmutableList.of(createMXRecord, createARecord);\n      \n      CreateSubdomain createSubdomain1 = CreateSubdomain.builder()\n            .name(\"dev.\" + JCLOUDS_EXAMPLE)\n            .email(\"jclouds@\" + JCLOUDS_EXAMPLE)\n            .comment(\"Hello dev subdomain\")\n            .build();\n      \n      CreateSubdomain createSubdomain2 = CreateSubdomain.builder()\n            .name(\"test.\" + JCLOUDS_EXAMPLE)\n            .email(\"jclouds@\" + JCLOUDS_EXAMPLE)\n            .comment(\"Hello test subdomain\")\n            .build();\n      \n      List<CreateSubdomain> createSubdomains = ImmutableList.of(createSubdomain1, createSubdomain2);\n\n      CreateDomain createDomain1 = CreateDomain.builder()\n            .name(JCLOUDS_EXAMPLE)\n            .email(\"jclouds1@\" + JCLOUDS_EXAMPLE)\n            .ttl(600001)\n            .comment(\"Hello Domain 1\")\n            .subdomains(createSubdomains)\n            .records(createRecords)\n            .build();\n\n      CreateDomain createDomain2 = CreateDomain.builder()\n            .name(\"alt-\" + JCLOUDS_EXAMPLE)\n            .email(\"jclouds2@\" + JCLOUDS_EXAMPLE)\n            .ttl(600002)\n            .comment(\"Hello Domain 2\")\n            .build();\n\n      Iterable<CreateDomain> createDomains = ImmutableList.of(createDomain1, createDomain2);      \n      testDomains = DomainFunctions.toDomainMap(awaitComplete(api, api.getDomainApi().create(createDomains)));\n\n      assertEquals(testDomains.size(), 2);\n\n      Domain jclouds = testDomains.get(JCLOUDS_EXAMPLE);\n      Domain altjclouds = testDomains.get(\"alt-\" + JCLOUDS_EXAMPLE);\n      \n      Thread.sleep(1000);\n      Date now = new Date();\n\n      assertTrue(jclouds.getId() > 0);\n      assertTrue(jclouds.getAccountId() > 0);\n      assertEquals(jclouds.getName(), JCLOUDS_EXAMPLE);\n      assertEquals(jclouds.getEmail(), \"jclouds1@\" + JCLOUDS_EXAMPLE);\n      assertEquals(jclouds.getComment().get(), \"Hello Domain 1\");\n      assertEquals(jclouds.getTTL(), 600001);\n      assertTrue(jclouds.getCreated().before(now));\n      assertTrue(jclouds.getUpdated().before(now));\n      \n      assertEquals(jclouds.getSubdomains().size(), 2);\n      \n      Subdomain devjclouds = null;\n      Subdomain testjclouds = null;\n      \n      for (Subdomain subdomain : jclouds.getSubdomains()) {\n         if (subdomain.getName().equals(\"dev.\" + JCLOUDS_EXAMPLE)) {\n            devjclouds = subdomain;\n         } else if (subdomain.getName().equals(\"test.\" + JCLOUDS_EXAMPLE)) {\n            testjclouds = subdomain;\n         }\n      }\n      \n      assertTrue(devjclouds.getId() > 0);\n      assertEquals(devjclouds.getName(), \"dev.\" + JCLOUDS_EXAMPLE);\n      assertEquals(devjclouds.getEmail(), \"jclouds@\" + JCLOUDS_EXAMPLE);\n      assertEquals(devjclouds.getComment().get(), \"Hello dev subdomain\");\n      assertTrue(devjclouds.getCreated().before(now));\n      assertTrue(devjclouds.getUpdated().before(now));\n      \n      assertTrue(testjclouds.getId() > 0);\n      assertEquals(testjclouds.getName(), \"test.\" + JCLOUDS_EXAMPLE);\n      assertEquals(testjclouds.getEmail(), \"jclouds@\" + JCLOUDS_EXAMPLE);\n      assertEquals(testjclouds.getComment().get(), \"Hello test subdomain\");\n      assertTrue(testjclouds.getCreated().before(now));\n      assertTrue(testjclouds.getUpdated().before(now));\n      \n      assertEquals(jclouds.getRecords().size(), 2);\n      \n      RecordDetail mxRecord = null;\n      RecordDetail aRecord = null;\n      \n      for (RecordDetail record : jclouds.getRecords()) {\n         if (record.getType().equals(\"MX\")) {\n            mxRecord = record;\n         } else if (record.getType().equals(\"A\")) {\n            aRecord = record;\n         }\n      }\n      \n      assertNotNull(mxRecord.getId());\n      assertEquals(mxRecord.getType(), \"MX\");\n      assertEquals(mxRecord.getName(), JCLOUDS_EXAMPLE);\n      assertEquals(mxRecord.getPriority().intValue(), 11235);\n      assertEquals(mxRecord.getComment(), \"MX Record\");\n      assertEquals(mxRecord.getTTL(), 60000);\n      assertTrue(mxRecord.getCreated().before(now));\n      assertTrue(mxRecord.getUpdated().before(now));\n      \n      assertNotNull(aRecord.getId());\n      assertEquals(aRecord.getType(), \"A\");\n      assertEquals(aRecord.getName(), JCLOUDS_EXAMPLE);\n      assertNull(aRecord.getPriority());\n      assertEquals(aRecord.getComment(), \"A Record\");\n      assertEquals(aRecord.getTTL(), 60000);\n      assertTrue(aRecord.getCreated().before(now));\n      assertTrue(aRecord.getUpdated().before(now));\n      \n      assertTrue(altjclouds.getId() > 0);\n      assertTrue(altjclouds.getAccountId() > 0);\n      assertEquals(altjclouds.getName(), \"alt-\" + JCLOUDS_EXAMPLE);\n      assertEquals(altjclouds.getEmail(), \"jclouds2@\" + JCLOUDS_EXAMPLE);\n      assertEquals(altjclouds.getComment().get(), \"Hello Domain 2\");\n      assertEquals(altjclouds.getTTL(), 600002);\n      assertTrue(altjclouds.getCreated().before(now));\n      assertTrue(altjclouds.getUpdated().before(now));\n   }   \n\n   @Test(dependsOnMethods = \"testCreateDomainsWithSubdomainsAndRecords\")\n   public void testCreateSimpleDomain() throws Exception {\n      CreateDomain createDomain = CreateDomain.builder()\n            .name(\"simple-\" + JCLOUDS_EXAMPLE)\n            .email(\"simple-jclouds@\" + JCLOUDS_EXAMPLE)\n            .build();\n\n      Iterable<CreateDomain> createDomains = ImmutableList.of(createDomain);      \n      Domain domain = awaitComplete(api, api.getDomainApi().create(createDomains)).iterator().next();\n      \n      assertEquals(domain.getName(), \"simple-\" + JCLOUDS_EXAMPLE);\n      assertEquals(domain.getEmail(), \"simple-jclouds@\" + JCLOUDS_EXAMPLE);\n      \n      testDomains = Maps.newHashMap(testDomains);\n      testDomains.put(domain.getName(), domain);\n   }   \n\n   @Test(dependsOnMethods = \"testCreateSimpleDomain\")\n   public void testListDomains() throws Exception {\n      Set<Domain> domains = api.getDomainApi().list().concat().toSet();\n      assertEquals(domains.size(), 5);\n   }\n\n   @Test(dependsOnMethods = \"testListDomains\")\n   public void testListDomainsWithFilter() throws Exception {\n      Set<Domain> domains = api.getDomainApi().listWithFilterByNamesMatching(\"alt-\" + JCLOUDS_EXAMPLE).concat().toSet();\n      assertEquals(domains.size(), 1);\n   }\n\n   @Test(dependsOnMethods = \"testListDomainsWithFilter\")\n   public void testListSubdomains() throws Exception {\n      Domain domain = testDomains.get(JCLOUDS_EXAMPLE);\n      Set<Subdomain> subdomains = api.getDomainApi().listSubdomains(domain.getId()).concat().toSet();\n      assertEquals(subdomains.size(), 2);\n   }\n\n   @Test(dependsOnMethods = \"testListSubdomains\")\n   public void testGetDomain() throws Exception {\n      Domain domain = testDomains.get(JCLOUDS_EXAMPLE);\n      Domain jclouds = api.getDomainApi().get(domain.getId());\n\n      Thread.sleep(1000);\n      Date now = new Date();\n\n      assertTrue(jclouds.getId() > 0);\n      assertTrue(jclouds.getAccountId() > 0);\n      assertEquals(jclouds.getName(), JCLOUDS_EXAMPLE);\n      assertEquals(jclouds.getEmail(), \"jclouds1@\" + JCLOUDS_EXAMPLE);\n      assertEquals(jclouds.getComment().get(), \"Hello Domain 1\");\n      assertEquals(jclouds.getTTL(), 600001);\n      assertTrue(jclouds.getCreated().before(now));\n      assertTrue(jclouds.getUpdated().before(now));\n      \n      assertEquals(jclouds.getSubdomains().size(), 2);\n      \n      Subdomain devjclouds = null;\n      Subdomain testjclouds = null;\n      \n      for (Subdomain subdomain : jclouds.getSubdomains()) {\n         if (subdomain.getName().equals(\"dev.\" + JCLOUDS_EXAMPLE)) {\n            devjclouds = subdomain;\n         } else if (subdomain.getName().equals(\"test.\" + JCLOUDS_EXAMPLE)) {\n            testjclouds = subdomain;\n         }\n      }\n      \n      assertTrue(devjclouds.getId() > 0);\n      assertEquals(devjclouds.getName(), \"dev.\" + JCLOUDS_EXAMPLE);\n      assertEquals(devjclouds.getEmail(), \"jclouds@\" + JCLOUDS_EXAMPLE);\n      assertEquals(devjclouds.getComment().get(), \"Hello dev subdomain\");\n      assertTrue(devjclouds.getCreated().before(now));\n      assertTrue(devjclouds.getUpdated().before(now));\n      \n      assertTrue(testjclouds.getId() > 0);\n      assertEquals(testjclouds.getName(), \"test.\" + JCLOUDS_EXAMPLE);\n      assertEquals(testjclouds.getEmail(), \"jclouds@\" + JCLOUDS_EXAMPLE);\n      assertEquals(testjclouds.getComment().get(), \"Hello test subdomain\");\n      assertTrue(testjclouds.getCreated().before(now));\n      assertTrue(testjclouds.getUpdated().before(now));\n      \n      assertEquals(jclouds.getRecords().size(), 4); // 2 created above + 2 nameserver (NS) records\n      \n      RecordDetail mxRecord = null;\n      RecordDetail aRecord = null;\n      RecordDetail nsRecord = null;\n      \n      for (RecordDetail record : jclouds.getRecords()) {\n         if (record.getType().equals(\"MX\")) {\n            mxRecord = record;\n         } else if (record.getType().equals(\"A\")) {\n            aRecord = record;\n         } else if (record.getType().equals(\"NS\")) {\n            nsRecord = record; // don't care which one we get\n         }\n      }\n      \n      assertNotNull(mxRecord.getId());\n      assertEquals(mxRecord.getType(), \"MX\");\n      assertEquals(mxRecord.getName(), JCLOUDS_EXAMPLE);\n      assertEquals(mxRecord.getPriority().intValue(), 11235);\n      assertEquals(mxRecord.getComment(), \"MX Record\");\n      assertEquals(mxRecord.getTTL(), 60000);\n      assertTrue(mxRecord.getCreated().before(now));\n      assertTrue(mxRecord.getUpdated().before(now));\n      \n      assertNotNull(aRecord.getId());\n      assertEquals(aRecord.getType(), \"A\");\n      assertEquals(aRecord.getName(), JCLOUDS_EXAMPLE);\n      assertNull(aRecord.getPriority());\n      assertEquals(aRecord.getComment(), \"A Record\");\n      assertEquals(aRecord.getTTL(), 60000);\n      assertTrue(aRecord.getCreated().before(now));\n      assertTrue(aRecord.getUpdated().before(now));\n\n      assertNotNull(nsRecord.getId());\n      assertEquals(nsRecord.getType(), \"NS\");\n      assertEquals(nsRecord.getName(), JCLOUDS_EXAMPLE);\n      assertEquals(nsRecord.getTTL(), 600001);\n      assertTrue(nsRecord.getCreated().before(now));\n      assertTrue(nsRecord.getUpdated().before(now));\n   }\n   \n   @Test(dependsOnMethods = \"testGetDomain\")\n   public void testUpdateDomain() throws Exception {\n      UpdateDomain updateDomain = UpdateDomain.builder()\n            .email(\"jclouds3@\" + JCLOUDS_EXAMPLE)\n            .ttl(600003)\n            .comment(\"Hello Domain Update 3\")\n            .build();\n\n      awaitComplete(api, api.getDomainApi().update(testDomains.get(JCLOUDS_EXAMPLE).getId(), updateDomain));\n      Domain jclouds = api.getDomainApi().get(testDomains.get(JCLOUDS_EXAMPLE).getId());\n      \n      assertEquals(jclouds.getEmail(), \"jclouds3@\" + JCLOUDS_EXAMPLE);\n      assertEquals(jclouds.getComment().get(), \"Hello Domain Update 3\");\n      assertEquals(jclouds.getTTL(), 600003);\n   }\n\n   @Test(dependsOnMethods = \"testUpdateDomain\")\n   public void testUpdateDomainsTTL() throws Exception {\n      List<Integer> ids = ImmutableList.of(\n            testDomains.get(JCLOUDS_EXAMPLE).getId(), testDomains.get(\"alt-\" + JCLOUDS_EXAMPLE).getId());\n      awaitComplete(api, api.getDomainApi().updateTTL(ids, 1234567));\n      \n      Domain jclouds = api.getDomainApi().get(testDomains.get(JCLOUDS_EXAMPLE).getId());\n      Domain altjclouds = api.getDomainApi().get(testDomains.get(\"alt-\" + JCLOUDS_EXAMPLE).getId());\n      \n      assertEquals(jclouds.getTTL(), 1234567);\n      assertEquals(altjclouds.getTTL(), 1234567);\n   }\n\n   @Test(dependsOnMethods = \"testUpdateDomainsTTL\")\n   public void testUpdateDomainsEmail() throws Exception {\n      List<Integer> ids = ImmutableList.of(\n            testDomains.get(JCLOUDS_EXAMPLE).getId(), testDomains.get(\"alt-\" + JCLOUDS_EXAMPLE).getId());\n      awaitComplete(api, api.getDomainApi().updateEmail(ids, \"jclouds-up@\" + JCLOUDS_EXAMPLE));\n\n      Domain jclouds = api.getDomainApi().get(testDomains.get(JCLOUDS_EXAMPLE).getId());\n      Domain altjclouds = api.getDomainApi().get(testDomains.get(\"alt-\" + JCLOUDS_EXAMPLE).getId());\n\n      assertEquals(jclouds.getEmail(), \"jclouds-up@\" + JCLOUDS_EXAMPLE);\n      assertEquals(altjclouds.getEmail(), \"jclouds-up@\" + JCLOUDS_EXAMPLE);\n   }\n\n   @Test(dependsOnMethods = \"testUpdateDomainsEmail\")\n   public void testExportDomain() throws Exception {\n      Domain domain = testDomains.get(JCLOUDS_EXAMPLE);\n      List<String> domainExport = awaitComplete(api, api.getDomainApi().exportFormat(domain.getId(), Domain.Format.BIND_9)); \n      \n      assertTrue(domainExport.get(0).contains(JCLOUDS_EXAMPLE));\n   }\n\n   @Test(dependsOnMethods = \"testExportDomain\")\n   public void testImportDomain() throws Exception {\n      List<String> contents = ImmutableList.<String> of(\n            \"imp-\" + JCLOUDS_EXAMPLE + \".      3600  IN SOA   ns.rackspace.com. jclouds.imp-\" + JCLOUDS_EXAMPLE + \". 1363882703 3600 3600 3600 3600\",\n            \"imp-\" + JCLOUDS_EXAMPLE + \".      600   IN A  50.56.174.152\"); \n\n      Domain domain = awaitComplete(api, api.getDomainApi().importFormat(contents, Domain.Format.BIND_9));\n      RecordDetail record = domain.getRecords().iterator().next();\n      \n      assertEquals(domain.getName(), \"imp-\" + JCLOUDS_EXAMPLE);\n      assertEquals(domain.getEmail(), \"jclouds@imp-\" + JCLOUDS_EXAMPLE);\n      assertEquals(record.getType(), \"A\");\n      assertEquals(record.getData(), \"50.56.174.152\");\n      assertEquals(record.getTTL(), 600);\n      \n      testDomains = Maps.newHashMap(testDomains);\n      testDomains.put(domain.getName(), domain);\n   }\n\n   @Override\n   @AfterClass(groups = { \"integration\", \"live\" })\n   protected void tearDown() {\n      List<Integer> domainIds = Lists.newArrayList();\n      \n      for (Domain domain : testDomains.values()) {\n         domainIds.add(domain.getId());\n      }\n\n      try {\n         awaitComplete(api, api.getDomainApi().delete(domainIds, true));\n      }\n      catch (TimeoutException e) {\n         e.printStackTrace();\n      }\n      super.tearDown();\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/java/org/jclouds/rackspace/clouddns/v1/features/LimitApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1.features;\n\nimport static jakarta.ws.rs.core.Response.Status.OK;\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.v2_0.domain.Limits;\nimport org.jclouds.openstack.v2_0.domain.RateLimit;\nimport org.jclouds.rackspace.clouddns.v1.CloudDNSApi;\nimport org.jclouds.rackspace.clouddns.v1.internal.BaseCloudDNSApiExpectTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Iterables;\n\n@Test(groups = \"unit\")\npublic class LimitApiExpectTest extends BaseCloudDNSApiExpectTest<CloudDNSApi> {\n   public void testListLimits() {\n      URI endpoint = URI.create(\"https://dns.api.rackspacecloud.com/v1.0/123123/limits\");\n      LimitApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess, \n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/limit-list.json\")).build()\n      ).getLimitApi();\n\n      Limits limits = api.list();\n      assertEquals(limits.getAbsoluteLimits().get(\"records per domain\"), Integer.valueOf(500));\n      assertEquals(limits.getAbsoluteLimits().get(\"domains\"), Integer.valueOf(500));\n      assertEquals(Iterables.size(limits.getRateLimits()), 2);\n      \n      RateLimit statusRateLimit = Iterables.tryFind(limits.getRateLimits(), isStatusRateLimit()).orNull();\n      assertEquals(statusRateLimit.getRegex(), \".*/v\\\\d+\\\\.\\\\d+/(\\\\d+/status).*\");\n      assertEquals(Iterables.get(statusRateLimit.getLimits(), 0).getVerb(), \"GET\");\n      assertEquals(Iterables.get(statusRateLimit.getLimits(), 0).getValue(), 5);\n      assertEquals(Iterables.get(statusRateLimit.getLimits(), 0).getRemaining().get(), Integer.valueOf(5));\n      assertEquals(Iterables.get(statusRateLimit.getLimits(), 0).getUnit(), \"SECOND\");\n   }\n   \n   public void testListLimitTypes() {\n      URI endpoint = URI.create(\"https://dns.api.rackspacecloud.com/v1.0/123123/limits/types\");\n      LimitApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess, \n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/limit-types-list.json\")).build()\n      ).getLimitApi();\n\n      Iterable<String> limitTypes = api.listTypes();\n      assertEquals(Iterables.size(limitTypes), 3);\n   }\n   \n   private static Predicate<RateLimit> isStatusRateLimit() {\n      return new Predicate<RateLimit>() {\n         @Override\n         public boolean apply(RateLimit rateLimit) {\n            return rateLimit.getUri().contains(\"status\");\n         }\n      };\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/java/org/jclouds/rackspace/clouddns/v1/features/LimitApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1.features;\n\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.openstack.v2_0.domain.Limits;\nimport org.jclouds.rackspace.clouddns.v1.internal.BaseCloudDNSApiLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Iterables;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"LimitApiLiveTest\")\npublic class LimitApiLiveTest extends BaseCloudDNSApiLiveTest {\n   @Test\n   public void testList() throws Exception {\n      Limits limits = api.getLimitApi().list();\n      assertNotNull(limits.getAbsoluteLimits());\n      assertNotNull(limits.getRateLimits());\n      assertTrue(limits.getAbsoluteLimits().size() > 1);\n      assertTrue(Iterables.size(limits.getRateLimits()) > 1);\n   }\n   \n   @Test\n   public void testListTypes() throws Exception {\n      Iterable<String> limitTypes = api.getLimitApi().listTypes();\n      assertNotNull(limitTypes);\n      assertTrue(Iterables.size(limitTypes) > 1);\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/java/org/jclouds/rackspace/clouddns/v1/features/RecordApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1.features;\n\nimport static jakarta.ws.rs.HttpMethod.POST;\nimport static jakarta.ws.rs.HttpMethod.PUT;\nimport static jakarta.ws.rs.core.Response.Status.OK;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rackspace.clouddns.v1.CloudDNSApi;\nimport org.jclouds.rackspace.clouddns.v1.domain.Job;\nimport org.jclouds.rackspace.clouddns.v1.domain.Record;\nimport org.jclouds.rackspace.clouddns.v1.domain.RecordDetail;\nimport org.jclouds.rackspace.clouddns.v1.internal.BaseCloudDNSApiExpectTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\n\n@Test(groups = \"unit\")\npublic class RecordApiExpectTest extends BaseCloudDNSApiExpectTest<CloudDNSApi> {\n   private static final String JCLOUDS_EXAMPLE = \"jclouds-example.com\";\n\n   public void testAddRecord() {\n      URI endpoint = URI.create(\"https://dns.api.rackspacecloud.com/v1.0/123123/domains/3650908/records\");\n      RecordApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey, \n            responseWithAccess,\n            authenticatedGET()\n               .method(POST)\n               .payload(payloadFromResource(\"/record-create.json\"))\n               .endpoint(endpoint)\n               .build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/record-create-response.json\")).build())\n            .getRecordApi(3650908);\n\n      Record createMXRecord = Record.builder()\n            .type(\"MX\")\n            .name(JCLOUDS_EXAMPLE)\n            .data(\"mail.\" + JCLOUDS_EXAMPLE)\n            .comment(\"MX Record\")\n            .priority(11235)\n            .build();\n      \n      Record createARecord = Record.builder()\n            .type(\"A\")\n            .name(JCLOUDS_EXAMPLE)\n            .data(\"10.0.0.1\")\n            .build();\n      \n      List<Record> createRecords = ImmutableList.of(createMXRecord, createARecord);      \n      Job<Set<RecordDetail>> job = api.create(createRecords);\n      \n      assertEquals(job.getStatus(), Job.Status.COMPLETED);\n      assertTrue(job.getResource().isPresent());\n      \n      Set<RecordDetail> records = job.getResource().get();\n      Date now = new Date();\n      RecordDetail mxRecord = null;\n      RecordDetail aRecord = null;\n      \n      for (RecordDetail record : records) {\n         if (record.getType().equals(\"MX\")) {\n            mxRecord = record;\n         } else if (record.getType().equals(\"A\")) {\n            aRecord = record;\n         }\n      }\n      \n      assertNotNull(mxRecord.getId());\n      assertEquals(mxRecord.getType(), \"MX\");\n      assertEquals(mxRecord.getName(), JCLOUDS_EXAMPLE);\n      assertEquals(mxRecord.getPriority().intValue(), 11235);\n      assertEquals(mxRecord.getComment(), \"MX Record\");\n      assertEquals(mxRecord.getTTL(), 60000);\n      assertTrue(mxRecord.getCreated().before(now));\n      assertTrue(mxRecord.getUpdated().before(now));\n      \n      assertNotNull(aRecord.getId());\n      assertEquals(aRecord.getType(), \"A\");\n      assertEquals(aRecord.getName(), JCLOUDS_EXAMPLE);\n      assertNull(aRecord.getPriority());\n      assertEquals(aRecord.getTTL(), 60000);\n      assertTrue(aRecord.getCreated().before(now));\n      assertTrue(aRecord.getUpdated().before(now));\n   }\n\n   public void testListRecords() {\n      URI endpoint = URI.create(\"https://dns.api.rackspacecloud.com/v1.0/123123/domains/3650908/records\");\n      RecordApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey, \n            responseWithAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/record-list.json\")).build())\n            .getRecordApi(3650908);\n\n      ImmutableList<RecordDetail> records = api.list().concat().toList();\n      assertEquals(records.size(), 4); // 2 created above + 2 nameserver (NS) records\n      \n      for (RecordDetail record : records) {\n         assertTrue(record.getName().contains(JCLOUDS_EXAMPLE));\n      }\n   }\n\n   public void testListRecordsPagination() {\n      URI endpointPage1 = URI.create(\"https://dns.api.rackspacecloud.com/v1.0/123123/domains/3650908/records\");\n      URI endpointPage2 = URI.create(\"https://dns.api.rackspacecloud.com/v1.0/123123/domains/3650908/records?limit=4&offset=4\");\n      RecordApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey, \n            responseWithAccess,\n            authenticatedGET().endpoint(endpointPage1).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/record-list-page1.json\")).build(),\n            authenticatedGET().endpoint(endpointPage2).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/record-list-page2.json\")).build())\n         .getRecordApi(3650908);\n\n      ImmutableList<RecordDetail> records = api.list().concat().toList();\n      assertEquals(records.size(), 8);\n      \n      for (RecordDetail record : records) {\n         assertTrue(record.getName().contains(JCLOUDS_EXAMPLE));\n      }\n   }\n\n   public void testListByType() {\n      URI endpoint = URI.create(\"https://dns.api.rackspacecloud.com/v1.0/123123/domains/3650908/records?type=A\");\n      RecordApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey, \n            responseWithAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/record-list-with-filter.json\")).build())\n            .getRecordApi(3650908);\n\n      ImmutableList<RecordDetail> records = api.listByType(\"A\").concat().toList();\n      Date now = new Date();\n      \n      assertEquals(records.size(), 1);\n      assertEquals(records.get(0).getId(), \"A-9846146\");\n      assertEquals(records.get(0).getName(), JCLOUDS_EXAMPLE);\n      assertEquals(records.get(0).getType(), \"A\");\n      assertEquals(records.get(0).getData(), \"10.0.1.0\");\n      assertEquals(records.get(0).getTTL(), 60000);\n      assertTrue(records.get(0).getCreated().before(now));\n      assertTrue(records.get(0).getUpdated().before(now));\n   }\n\n   public void testListByTypeAndData() {\n      URI endpoint = URI.create(\"https://dns.api.rackspacecloud.com/v1.0/123123/domains/3650908/records?type=A&data=10.0.1.0\");\n      RecordApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey, \n            responseWithAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/record-list-with-filter.json\")).build())\n            .getRecordApi(3650908);\n\n      ImmutableList<RecordDetail> records = api.listByTypeAndData(\"A\", \"10.0.1.0\").concat().toList();\n      Date now = new Date();\n      \n      assertEquals(records.size(), 1);\n      assertEquals(records.get(0).getId(), \"A-9846146\");\n      assertEquals(records.get(0).getName(), JCLOUDS_EXAMPLE);\n      assertEquals(records.get(0).getType(), \"A\");\n      assertEquals(records.get(0).getData(), \"10.0.1.0\");\n      assertEquals(records.get(0).getTTL(), 60000);\n      assertTrue(records.get(0).getCreated().before(now));\n      assertTrue(records.get(0).getUpdated().before(now));\n   }\n\n   public void testListByNameAndType() {\n      URI endpoint = URI.create(\"https://dns.api.rackspacecloud.com/v1.0/123123/domains/3650908/records?name=jclouds-example.com&type=A\");\n      RecordApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey, \n            responseWithAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/record-list-with-filter.json\")).build())\n            .getRecordApi(3650908);\n\n      ImmutableList<RecordDetail> records = api.listByNameAndType(JCLOUDS_EXAMPLE, \"A\").concat().toList();\n      Date now = new Date();\n      \n      assertEquals(records.size(), 1);\n      assertEquals(records.get(0).getId(), \"A-9846146\");\n      assertEquals(records.get(0).getName(), JCLOUDS_EXAMPLE);\n      assertEquals(records.get(0).getType(), \"A\");\n      assertEquals(records.get(0).getData(), \"10.0.1.0\");\n      assertEquals(records.get(0).getTTL(), 60000);\n      assertTrue(records.get(0).getCreated().before(now));\n      assertTrue(records.get(0).getUpdated().before(now));\n   }\n\n   public void testGetByNameAndTypeAndData() {\n      URI endpoint = URI.create(\"https://dns.api.rackspacecloud.com/v1.0/123123/domains/3650908/records?name=jclouds-example.com&type=A&data=10.0.1.0\");\n      RecordApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey, \n            responseWithAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/record-list-with-filter.json\")).build())\n            .getRecordApi(3650908);\n\n      RecordDetail record = api.getByNameAndTypeAndData(JCLOUDS_EXAMPLE, \"A\", \"10.0.1.0\");\n      Date now = new Date();\n      \n      assertEquals(record.getId(), \"A-9846146\");\n      assertEquals(record.getName(), JCLOUDS_EXAMPLE);\n      assertEquals(record.getType(), \"A\");\n      assertEquals(record.getData(), \"10.0.1.0\");\n      assertEquals(record.getTTL(), 60000);\n      assertTrue(record.getCreated().before(now));\n      assertTrue(record.getUpdated().before(now));\n   }\n\n   public void testGetRecord() {\n      URI endpoint = URI.create(\"https://dns.api.rackspacecloud.com/v1.0/123123/domains/3650908/records/A-9846146\");\n      RecordApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey, \n            responseWithAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/record-get.json\")).build())\n            .getRecordApi(3650908);\n\n      RecordDetail record = api.get(\"A-9846146\");\n      Date now = new Date();\n\n      assertEquals(record.getId(), \"A-9846146\");\n      assertEquals(record.getName(), JCLOUDS_EXAMPLE);\n      assertEquals(record.getType(), \"A\");\n      assertEquals(record.getData(), \"10.0.1.0\");\n      assertEquals(record.getTTL(), 60000);\n      assertTrue(record.getCreated().before(now));\n      assertTrue(record.getUpdated().before(now));\n   }\n   \n   public void testUpdateRecord() {\n      URI endpoint = URI.create(\"https://dns.api.rackspacecloud.com/v1.0/123123/domains/3650908/records/SRV-21858\");\n      RecordApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey, \n            responseWithAccess,\n            authenticatedGET()\n               .method(PUT)\n               .payload(payloadFromResourceWithContentType(\"/record-update.json\", MediaType.APPLICATION_JSON))\n               .endpoint(endpoint)\n               .build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/record-update-response.json\")).build())\n            .getRecordApi(3650908);\n\n      Record record = Record.builder()\n            .name(\"_sip._udp.\" + JCLOUDS_EXAMPLE)\n            .ttl(86401)\n            .data(\"1 3444 sip.\" + JCLOUDS_EXAMPLE) // weight port target\n            .priority(12358)\n            .comment(\"Updated Protocol to UDP\")\n            .build();\n\n      Job<Void> job = api.update(\"SRV-21858\", record);\n      \n      assertEquals(job.getStatus(), Job.Status.COMPLETED);\n   }\n   \n   public void testUpdateRecords() {\n      URI endpoint = URI.create(\"https://dns.api.rackspacecloud.com/v1.0/123123/domains/3650908/records\");\n      RecordApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey, \n            responseWithAccess,\n            authenticatedGET()\n               .method(PUT)\n               .payload(payloadFromResourceWithContentType(\"/records-update.json\", MediaType.APPLICATION_JSON))\n               .endpoint(endpoint)\n               .build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/records-update-response.json\")).build())\n            .getRecordApi(3650908);\n\n      Record updateARecord = Record.builder()\n            .comment(\"Multi-record Update\")\n            .build();\n\n      Record updateMXRecord = Record.builder()\n            .comment(\"Multi-record Update\")\n            .build();\n\n      Map<String, Record> updateRecords = ImmutableMap.<String, Record> of(\n            \"A-9846146\", updateARecord,\n            \"MX-9846146\", updateMXRecord);\n      \n      Job<?> job = api.update(updateRecords);\n      \n      assertEquals(job.getStatus(), Job.Status.COMPLETED);\n   }\n\n   public void testDeleteRecord() {\n      URI endpoint = URI.create(\"https://dns.api.rackspacecloud.com/v1.0/123123/domains/3650908/records/A-9846146\");\n      RecordApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey, \n            responseWithAccess,\n            authenticatedGET().method(\"DELETE\").replaceHeader(\"Accept\", MediaType.WILDCARD).endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/record-delete.json\")).build())\n            .getRecordApi(3650908);\n\n      Job<?> job = api.delete(\"A-9846146\");\n\n      assertEquals(job.getStatus(), Job.Status.COMPLETED);\n   }\n\n   public void testDeleteRecords() {\n      URI endpoint = URI.create(\"https://dns.api.rackspacecloud.com/v1.0/123123/domains/3650908/records?id=A-9846146&id=MX-9846146\");\n      RecordApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey, \n            responseWithAccess,\n            authenticatedGET().method(\"DELETE\").replaceHeader(\"Accept\", MediaType.WILDCARD).endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/records-delete.json\")).build())\n            .getRecordApi(3650908);\n\n      List<String> recordIds = ImmutableList.<String> of(\"A-9846146\", \"MX-9846146\");      \n      Job<?> job = api.delete(recordIds);\n\n      assertEquals(job.getStatus(), Job.Status.COMPLETED);\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/java/org/jclouds/rackspace/clouddns/v1/features/RecordApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1.features;\n\nimport static org.jclouds.rackspace.clouddns.v1.predicates.JobPredicates.awaitComplete;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.TimeoutException;\n\nimport org.jclouds.rackspace.clouddns.v1.domain.CreateDomain;\nimport org.jclouds.rackspace.clouddns.v1.domain.Domain;\nimport org.jclouds.rackspace.clouddns.v1.domain.Record;\nimport org.jclouds.rackspace.clouddns.v1.domain.RecordDetail;\nimport org.jclouds.rackspace.clouddns.v1.functions.RecordFunctions;\nimport org.jclouds.rackspace.clouddns.v1.internal.BaseCloudDNSApiLiveTest;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Maps;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"RecordApiLiveTest\")\npublic class RecordApiLiveTest extends BaseCloudDNSApiLiveTest {\n\n   // just in case the username has a '.' we replace it to avoid creating subdomains\n   private static final String JCLOUDS_EXAMPLE = System.getProperty(\"user.name\").replace('.', '-') + \"-recordtest-jclouds.org\";\n   \n   private int domainId;\n   private String aRecordId;\n   private String srvRecordId;\n   private String mxRecordId;\n\n   @Test\n   public void testCreateDomain() throws Exception {\n      CreateDomain createDomain = CreateDomain.builder()\n            .name(JCLOUDS_EXAMPLE)\n            .email(\"jclouds@\" + JCLOUDS_EXAMPLE)\n            .ttl(60000)\n            .build();\n\n      Iterable<CreateDomain> createDomains = ImmutableList.of(createDomain);      \n      Domain domain = awaitComplete(api, api.getDomainApi().create(createDomains)).iterator().next();\n      \n      assertEquals(domain.getName(), JCLOUDS_EXAMPLE);\n      assertEquals(domain.getEmail(), \"jclouds@\" + JCLOUDS_EXAMPLE);\n      assertTrue(domain.getRecords().isEmpty());\n      \n      domainId = domain.getId();\n   }   \n\n   @Test(dependsOnMethods = \"testCreateDomain\")\n   public void testCreateRecords() throws Exception {\n      Record createMXRecord = Record.builder()\n            .type(\"MX\")\n            .name(JCLOUDS_EXAMPLE)\n            .data(\"mail.\" + JCLOUDS_EXAMPLE)\n            .comment(\"MX Record\")\n            .priority(11235)\n            .build();\n      \n      Record createARecord = Record.builder()\n            .type(\"A\")\n            .name(JCLOUDS_EXAMPLE)\n            .data(\"10.0.0.1\")\n            .build();\n      \n      Record createSRVRecord = Record.builder()\n            .type(\"SRV\")\n            .name(\"_sip._tcp.\" + JCLOUDS_EXAMPLE)\n            .ttl(86400)\n            .data(\"1 3443 sip.\" + JCLOUDS_EXAMPLE) // weight port target\n            .priority(11235)\n            .comment(\"Updated Protocol to UDP\")\n            .build();\n\n      List<Record> createRecords = ImmutableList.of(createMXRecord, createARecord, createSRVRecord);\n      Set<RecordDetail> records = awaitComplete(api, api.getRecordApi(domainId).create(createRecords));\n\n      Thread.sleep(1000);\n      Date now = new Date();\n      \n      RecordDetail mxRecord = null;\n      RecordDetail aRecord = null;\n      RecordDetail srvRecord = null;\n      \n      for (RecordDetail record : records) {\n         if (record.getType().equals(\"MX\")) {\n            mxRecord = record;\n         } else if (record.getType().equals(\"A\")) {\n            aRecord = record;\n         } else if (record.getType().equals(\"SRV\")) {\n            srvRecord = record;\n         }\n      }\n      \n      assertNotNull(mxRecord.getId());\n      assertEquals(mxRecord.getType(), \"MX\");\n      assertEquals(mxRecord.getName(), JCLOUDS_EXAMPLE);\n      assertEquals(mxRecord.getPriority().intValue(), 11235);\n      assertEquals(mxRecord.getComment(), \"MX Record\");\n      assertEquals(mxRecord.getTTL(), 60000);\n      assertTrue(mxRecord.getCreated().before(now));\n      assertTrue(mxRecord.getUpdated().before(now));\n      \n      assertNotNull(aRecord.getId());\n      assertEquals(aRecord.getType(), \"A\");\n      assertEquals(aRecord.getName(), JCLOUDS_EXAMPLE);\n      assertEquals(aRecord.getData(), \"10.0.0.1\");\n      assertNull(aRecord.getPriority());\n      assertEquals(aRecord.getTTL(), 60000);\n      assertTrue(aRecord.getCreated().before(now));\n      assertTrue(aRecord.getUpdated().before(now));\n      \n      assertNotNull(srvRecord.getId());\n      assertEquals(srvRecord.getType(), \"SRV\");\n      assertEquals(srvRecord.getName(), \"_sip._tcp.\" + JCLOUDS_EXAMPLE);\n      assertEquals(srvRecord.getData(), \"1 3443 sip.\" + JCLOUDS_EXAMPLE);\n      assertEquals(srvRecord.getPriority().intValue(), 11235);\n      assertEquals(srvRecord.getTTL(), 86400);\n      assertTrue(srvRecord.getCreated().before(now));\n      assertTrue(srvRecord.getUpdated().before(now));\n   }\n\n   @Test(dependsOnMethods = \"testCreateRecords\")\n   public void testListRecords() throws Exception {\n      Set<RecordDetail> records = api.getRecordApi(domainId).list().concat().toSet();\n      assertEquals(records.size(), 5); // 3 created above + 2 nameserver (NS) records\n   }\n\n   @Test(dependsOnMethods = \"testListRecords\")\n   public void testListRecordsByCriteriaMethods() throws Exception {\n      List<RecordDetail> records = api.getRecordApi(domainId).listByType(\"SRV\").concat().toList();\n      assertEquals(records.size(), 1);\n      \n      srvRecordId = records.get(0).getId();\n\n      records = api.getRecordApi(domainId).listByTypeAndData(\"A\", \"10.0.0.1\").concat().toList();\n      assertEquals(records.size(), 1);\n      \n      aRecordId = records.get(0).getId();\n\n      records = api.getRecordApi(domainId).listByNameAndType(JCLOUDS_EXAMPLE, \"MX\").concat().toList();\n      assertEquals(records.size(), 1);\n      \n      mxRecordId = records.get(0).getId();\n   }\n\n   @Test(dependsOnMethods = \"testListRecordsByCriteriaMethods\")\n   public void testGetRecordByNameAndTypeAndData() throws Exception {\n      RecordDetail record = api.getRecordApi(domainId).getByNameAndTypeAndData(JCLOUDS_EXAMPLE, \"A\", \"10.0.0.1\");\n      Date now = new Date();\n      \n      assertNotNull(record.getId());\n      assertEquals(record.getName(), JCLOUDS_EXAMPLE);\n      assertEquals(record.getType(), \"A\");\n      assertEquals(record.getData(), \"10.0.0.1\");\n      assertEquals(record.getTTL(), 60000);\n      assertTrue(record.getCreated().before(now));\n      assertTrue(record.getUpdated().before(now));\n   }\n\n   @Test(dependsOnMethods = \"testGetRecordByNameAndTypeAndData\")\n   public void testGetRecord() throws Exception {\n      RecordDetail record = api.getRecordApi(domainId).get(aRecordId);\n      Date now = new Date();\n      \n      assertNotNull(record.getId());\n      assertEquals(record.getName(), JCLOUDS_EXAMPLE);\n      assertEquals(record.getType(), \"A\");\n      assertEquals(record.getData(), \"10.0.0.1\");\n      assertEquals(record.getTTL(), 60000);\n      assertTrue(record.getCreated().before(now));\n      assertTrue(record.getUpdated().before(now));\n   }\n\n   @Test(dependsOnMethods = \"testGetRecord\")\n   public void testUpdateRecord() throws Exception {      \n      Record record = Record.builder()\n            .name(\"_sip._udp.\" + JCLOUDS_EXAMPLE)\n            .ttl(86401)\n            .data(\"1 3444 sip.\" + JCLOUDS_EXAMPLE) // weight port target\n            .priority(12358)\n            .comment(\"Updated Protocol to UDP\")\n            .build();\n\n      awaitComplete(api, api.getRecordApi(domainId).update(srvRecordId, record));\n\n      RecordDetail srvRecord = api.getRecordApi(domainId).get(srvRecordId);\n      Date now = new Date();\n      \n      assertNotNull(srvRecord.getId());\n      assertEquals(srvRecord.getType(), \"SRV\");\n      assertEquals(srvRecord.getName(), \"_sip._udp.\" + JCLOUDS_EXAMPLE);\n      assertEquals(srvRecord.getData(), \"1 3444 sip.\" + JCLOUDS_EXAMPLE);\n      assertEquals(srvRecord.getPriority().intValue(), 12358);\n      assertEquals(srvRecord.getTTL(), 86401);\n      assertEquals(srvRecord.getComment(), \"Updated Protocol to UDP\");\n      assertTrue(srvRecord.getCreated().before(now));\n      assertTrue(srvRecord.getUpdated().before(now));      \n   }\n\n   @Test(dependsOnMethods = \"testUpdateRecord\")\n   public void testUpdateRecords() throws Exception {      \n      Set<RecordDetail> recordDetails = api.getRecordApi(domainId).list().concat().toSet();\n      Map<String, Record> idsToRecords = RecordFunctions.toRecordMap(recordDetails);\n      Map<String, Record> updateRecords = Maps.transformValues(idsToRecords, updateTTLAndComment(35813, \"New TTL\")); \n            \n      awaitComplete(api, api.getRecordApi(domainId).update(updateRecords));\n\n      RecordDetail record = api.getRecordApi(domainId).get(aRecordId);\n      Date now = new Date();\n      \n      assertNotNull(record.getId());\n      assertEquals(record.getName(), JCLOUDS_EXAMPLE);\n      assertEquals(record.getType(), \"A\");\n      assertEquals(record.getData(), \"10.0.0.1\");\n      assertEquals(record.getTTL(), 35813);\n      assertEquals(record.getComment(), \"New TTL\");\n      assertTrue(record.getCreated().before(now));\n      assertTrue(record.getUpdated().before(now));\n      \n      recordDetails = api.getRecordApi(domainId).list().concat().toSet();\n      \n      for (RecordDetail recordDetail : recordDetails) {\n         assertEquals(recordDetail.getTTL(), 35813);\n         assertEquals(recordDetail.getComment(), \"New TTL\");\n      }\n   }\n\n   private Function<Record, Record> updateTTLAndComment(final int ttl, final String comment) {\n      return new Function<Record, Record>() {\n         public Record apply(Record record) {\n            return record.toBuilder().ttl(ttl).comment(comment).build();\n         }\n      };\n   }\n\n   @Test(dependsOnMethods = \"testUpdateRecords\")\n   public void testDeleteRecord() throws Exception {      \n      awaitComplete(api, api.getRecordApi(domainId).delete(aRecordId));\n      \n      assertNull(api.getRecordApi(domainId).get(aRecordId));\n   }\n\n   @Test(dependsOnMethods = \"testDeleteRecord\")\n   public void testDeleteRecords() throws Exception {      \n      List<String> recordIds = ImmutableList.<String> of(srvRecordId, mxRecordId);\n      \n      awaitComplete(api, api.getRecordApi(domainId).delete(recordIds));\n      \n      assertNull(api.getRecordApi(domainId).get(srvRecordId));\n      assertNull(api.getRecordApi(domainId).get(mxRecordId));\n   }\n\n   @Override\n   @AfterClass(groups = { \"integration\", \"live\" })\n   protected void tearDown() {\n      try {\n         awaitComplete(api, api.getDomainApi().delete(ImmutableList.<Integer> of(domainId), true));\n      }\n      catch (TimeoutException e) {\n         e.printStackTrace();\n      }\n      super.tearDown();\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/java/org/jclouds/rackspace/clouddns/v1/features/ReverseDNSApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1.features;\n\nimport static jakarta.ws.rs.HttpMethod.DELETE;\nimport static jakarta.ws.rs.HttpMethod.POST;\nimport static jakarta.ws.rs.HttpMethod.PUT;\nimport static jakarta.ws.rs.core.Response.Status.OK;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rackspace.clouddns.v1.CloudDNSApi;\nimport org.jclouds.rackspace.clouddns.v1.domain.Job;\nimport org.jclouds.rackspace.clouddns.v1.domain.Record;\nimport org.jclouds.rackspace.clouddns.v1.domain.RecordDetail;\nimport org.jclouds.rackspace.clouddns.v1.internal.BaseCloudDNSApiExpectTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.net.HttpHeaders;\n\n@Test(groups = \"unit\")\npublic class ReverseDNSApiExpectTest extends BaseCloudDNSApiExpectTest<CloudDNSApi> {\n   public static final String CLOUD_SERVERS_OPEN_STACK = \"cloudServersOpenStack\";\n   private static final String JCLOUDS_EXAMPLE = \"jclouds-example.com\";\n   private static final URI SERVER_URI = URI.create(\"https://dfw.servers.api.rackspacecloud.com/v2/123123/servers/f5fb9334-b4f0-49d0-a2cc-57a5772dc7d1\");\n\n   public void testCreateReverseDNSRecord() {\n      URI endpoint = URI.create(\"https://dns.api.rackspacecloud.com/v1.0/123123/rdns\");\n      ReverseDNSApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey, \n            responseWithAccess,\n            authenticatedGET()\n               .method(POST)\n               .payload(payloadFromResource(\"/record-ptr-create.json\"))\n               .endpoint(endpoint)\n               .build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/record-ptr-create-response.json\")).build())\n            .getReverseDNSApi(CLOUD_SERVERS_OPEN_STACK);\n\n      Record createPTRRecordIPv4 = Record.builder()\n            .type(\"PTR\")\n            .name(JCLOUDS_EXAMPLE)\n            .data(\"166.78.146.80\")\n            .ttl(11235)\n            .build();\n\n      Record createPTRRecordIPv6 = Record.builder()\n            .type(\"PTR\")\n            .name(JCLOUDS_EXAMPLE)\n            .data(\"2001:4800:7812:0514:9a32:3c2a:ff04:aed2\")\n            .comment(\"Hello IPv6\")\n            .build();\n      \n      List<Record> createRecords = ImmutableList.of(createPTRRecordIPv4, createPTRRecordIPv6);      \n      Job<Set<RecordDetail>> job = api.create(SERVER_URI, createRecords);\n      \n      assertEquals(job.getStatus(), Job.Status.COMPLETED);\n      assertTrue(job.getResource().isPresent());\n      \n      Set<RecordDetail> records = job.getResource().get();\n      Date now = new Date();\n      RecordDetail ptrRecordIPv4 = null;\n      RecordDetail ptrRecordIPv6 = null;\n      \n      for (RecordDetail record : records) {\n         if (record.getData().startsWith(\"166\")) {\n            ptrRecordIPv4 = record;\n         } else if (record.getData().startsWith(\"2001\")) {\n            ptrRecordIPv6 = record;\n         }\n      }\n      \n      assertNotNull(ptrRecordIPv4.getId());\n      assertEquals(ptrRecordIPv4.getType(), \"PTR\");\n      assertEquals(ptrRecordIPv4.getName(), JCLOUDS_EXAMPLE);\n      assertEquals(ptrRecordIPv4.getData(), \"166.78.146.80\");\n      assertEquals(ptrRecordIPv4.getTTL(), 11235);\n      assertNull(ptrRecordIPv4.getPriority());\n      assertNull(ptrRecordIPv4.getComment());\n      assertTrue(ptrRecordIPv4.getCreated().before(now));\n      assertTrue(ptrRecordIPv4.getUpdated().before(now));\n      \n      assertNotNull(ptrRecordIPv6.getId());\n      assertEquals(ptrRecordIPv6.getType(), \"PTR\");\n      assertEquals(ptrRecordIPv6.getName(), JCLOUDS_EXAMPLE);\n      assertEquals(ptrRecordIPv6.getData(), \"2001:4800:7812:514:9a32:3c2a:ff04:aed2\"); // leading 0 in 0514 removed\n      assertTrue(ptrRecordIPv6.getTTL() > 0);\n      assertNull(ptrRecordIPv6.getPriority());\n      assertEquals(ptrRecordIPv6.getComment(), \"Hello IPv6\");\n      assertTrue(ptrRecordIPv6.getCreated().before(now));\n      assertTrue(ptrRecordIPv6.getUpdated().before(now));\n   }\n\n   public void testListReverseDNSRecords() {\n      URI endpoint = URI.create(\"https://dns.api.rackspacecloud.com/v1.0/123123/rdns/cloudServersOpenStack?href=https%3A//dfw.servers.api.rackspacecloud.com/v2/123123/servers/f5fb9334-b4f0-49d0-a2cc-57a5772dc7d1\");\n      ReverseDNSApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey, \n            responseWithAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/record-ptr-list.json\")).build())\n            .getReverseDNSApi(CLOUD_SERVERS_OPEN_STACK);\n\n      ImmutableList<RecordDetail> records = api.list(SERVER_URI).concat().toList();\n      assertEquals(records.size(), 2);\n      \n      for (RecordDetail record : records) {\n         assertTrue(record.getType().contains(\"PTR\"));\n         assertTrue(record.getName().contains(JCLOUDS_EXAMPLE));\n      }\n   }\n\n   public void testGetReverseDNSRecord() {\n      URI endpoint = URI.create(\"https://dns.api.rackspacecloud.com/v1.0/123123/rdns/cloudServersOpenStack/PTR-557437?href=https%3A//dfw.servers.api.rackspacecloud.com/v2/123123/servers/f5fb9334-b4f0-49d0-a2cc-57a5772dc7d1\");\n      ReverseDNSApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey, \n            responseWithAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/record-ptr-get.json\")).build())\n            .getReverseDNSApi(CLOUD_SERVERS_OPEN_STACK);\n\n      RecordDetail record = api.get(SERVER_URI, \"PTR-557437\");\n      Date now = new Date();\n\n      assertEquals(record.getId(), \"PTR-557437\");\n      assertEquals(record.getType(), \"PTR\");\n      assertEquals(record.getName(), JCLOUDS_EXAMPLE);\n      assertEquals(record.getData(), \"166.78.146.80\");\n      assertEquals(record.getTTL(), 11235);\n      assertNull(record.getPriority());\n      assertNull(record.getComment());\n      assertTrue(record.getCreated().before(now));\n      assertTrue(record.getUpdated().before(now));\n   }\n   \n   public void testUpdateReverseDNSRecord() {\n      URI endpoint = URI.create(\"https://dns.api.rackspacecloud.com/v1.0/123123/rdns\");\n      ReverseDNSApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey, \n            responseWithAccess,\n            authenticatedGET()\n               .method(PUT)\n               .payload(payloadFromResourceWithContentType(\"/record-ptr-update.json\", MediaType.APPLICATION_JSON))\n               .endpoint(endpoint)\n               .build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/record-ptr-update-response.json\")).build())\n            .getReverseDNSApi(CLOUD_SERVERS_OPEN_STACK);\n\n      Record updatePTRRecordIPv4 = Record.builder()\n            .type(\"PTR\")\n            .name(JCLOUDS_EXAMPLE)\n            .data(\"166.78.146.80\")\n            .ttl(12358)\n            .build();\n\n      Map<String, Record> idsToRecords = ImmutableMap.<String, Record> of(\"PTR-557437\", updatePTRRecordIPv4);\n\n      Job<Void> job = api.update(SERVER_URI, idsToRecords);\n      \n      assertEquals(job.getStatus(), Job.Status.COMPLETED);\n   }\n   \n   public void testDeleteReverseDNSRecord() {\n      URI endpoint = URI.create(\"https://dns.api.rackspacecloud.com/v1.0/123123/rdns/cloudServersOpenStack?href=https%3A//dfw.servers.api.rackspacecloud.com/v2/123123/servers/f5fb9334-b4f0-49d0-a2cc-57a5772dc7d1&ip=166.78.146.80\");\n      ReverseDNSApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey, \n            responseWithAccess,\n            authenticatedGET().method(DELETE).replaceHeader(HttpHeaders.ACCEPT, MediaType.WILDCARD).endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/record-ptr-delete.json\")).build())\n            .getReverseDNSApi(CLOUD_SERVERS_OPEN_STACK);\n\n      Job<Void> job = api.delete(SERVER_URI, \"166.78.146.80\");\n\n      assertEquals(job.getStatus(), Job.Status.COMPLETED);\n   }\n\n   public void testDeleteReverseDNSRecords() {\n      URI endpoint = URI.create(\"https://dns.api.rackspacecloud.com/v1.0/123123/rdns/cloudServersOpenStack?href=https%3A//dfw.servers.api.rackspacecloud.com/v2/123123/servers/f5fb9334-b4f0-49d0-a2cc-57a5772dc7d1\");\n      ReverseDNSApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey, \n            responseWithAccess,\n            authenticatedGET().method(DELETE).replaceHeader(\"Accept\", MediaType.WILDCARD).endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/records-ptr-delete.json\")).build())\n            .getReverseDNSApi(CLOUD_SERVERS_OPEN_STACK);\n\n      Job<Void> job = api.deleteAll(SERVER_URI);\n\n      assertEquals(job.getStatus(), Job.Status.COMPLETED);\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/java/org/jclouds/rackspace/clouddns/v1/features/ReverseDNSApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1.features;\n\nimport static org.jclouds.rackspace.clouddns.v1.features.ReverseDNSApiExpectTest.CLOUD_SERVERS_OPEN_STACK;\nimport static org.jclouds.rackspace.clouddns.v1.predicates.JobPredicates.awaitComplete;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.Set;\nimport java.util.concurrent.TimeoutException;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.compute.ComputeService;\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.compute.config.ComputeServiceProperties;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.openstack.nova.v2_0.NovaApi;\nimport org.jclouds.openstack.nova.v2_0.domain.Server;\nimport org.jclouds.openstack.nova.v2_0.features.ServerApi;\nimport org.jclouds.rackspace.clouddns.v1.domain.CreateDomain;\nimport org.jclouds.rackspace.clouddns.v1.domain.Domain;\nimport org.jclouds.rackspace.clouddns.v1.domain.Record;\nimport org.jclouds.rackspace.clouddns.v1.domain.RecordDetail;\nimport org.jclouds.rackspace.clouddns.v1.internal.BaseCloudDNSApiLiveTest;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"ReverseDNSApiLiveTest\")\npublic class ReverseDNSApiLiveTest extends BaseCloudDNSApiLiveTest {\n\n   // just in case the username has a '.' we replace it to avoid creating subdomains\n   private static final String JCLOUDS_EXAMPLE = System.getProperty(\"user.name\").replace('.', '-')\n         + \"-recordtest-jclouds.org\";\n\n   private ComputeService computeService;\n   private NovaApi nova;\n   private String serverId;\n   private URI serverURI;\n   private String serverIPv4;\n   private String serverIPv6;\n\n   private int domainId;\n   private String ptrRecordIPv4Id;\n   private String ptrRecordIPv6Id;\n\n   @Test\n   public void testCreateServer() throws Exception {\n      Properties overrides = new Properties();\n      overrides.setProperty(ComputeServiceProperties.POLL_INITIAL_PERIOD, \"10000\");\n      overrides.setProperty(ComputeServiceProperties.POLL_MAX_PERIOD, \"10000\");\n\n      ComputeServiceContext context = ContextBuilder.newBuilder(\"rackspace-cloudservers-us\")\n            .credentials(identity, credential)\n            .overrides(overrides)\n            .buildView(ComputeServiceContext.class);\n      computeService = context.getComputeService();\n      nova = context.unwrapApi(NovaApi.class);\n\n      Template template = computeService.templateBuilder().smallest().build();\n      NodeMetadata nodeMetadata = computeService.createNodesInGroup(\"jclouds-reverse-dns-test\", 1, template).iterator().next();\n      serverId = nodeMetadata.getId();\n      serverURI = nodeMetadata.getUri();\n\n      ServerApi serverApi = nova.getServerApi(nodeMetadata.getLocation().getParent().getId());\n      Server server = serverApi.get(nodeMetadata.getProviderId());\n      serverIPv4 = server.getAccessIPv4();\n      serverIPv6 = server.getAccessIPv6();\n\n      System.out.println(\"serverURI = \" + serverURI);\n      System.out.println(\"serverIPv4 = \" + serverIPv4);\n      System.out.println(\"serverIPv6 = \" + serverIPv6);\n   }\n\n   @Test(dependsOnMethods = \"testCreateServer\")\n   public void testCreateDomain() throws Exception {\n      CreateDomain createDomain = CreateDomain.builder().name(JCLOUDS_EXAMPLE).email(\"jclouds@\" + JCLOUDS_EXAMPLE)\n            .ttl(60000).build();\n\n      Iterable<CreateDomain> createDomains = ImmutableList.of(createDomain);\n      Domain domain = awaitComplete(api, api.getDomainApi().create(createDomains)).iterator().next();\n\n      assertEquals(domain.getName(), JCLOUDS_EXAMPLE);\n      assertEquals(domain.getEmail(), \"jclouds@\" + JCLOUDS_EXAMPLE);\n      assertTrue(domain.getRecords().isEmpty());\n\n      domainId = domain.getId();\n   }\n\n   @Test(dependsOnMethods = \"testCreateDomain\")\n   public void testCreateReverseDNSRecords() throws Exception {\n      Record createPTRRecordIPv4 = Record.builder().type(\"PTR\").name(JCLOUDS_EXAMPLE).data(serverIPv4).ttl(11235)\n            .build();\n\n      Record createPTRRecordIPv6 = Record.builder().type(\"PTR\").name(JCLOUDS_EXAMPLE).data(serverIPv6)\n            .comment(\"Hello IPv6\").build();\n\n      List<Record> createRecords = ImmutableList.of(createPTRRecordIPv4, createPTRRecordIPv6);\n      Set<RecordDetail> records = awaitComplete(api,\n            api.getReverseDNSApi(CLOUD_SERVERS_OPEN_STACK).create(serverURI, createRecords));\n\n      Date now = new Date();\n      RecordDetail ptrRecordIPv4 = null;\n      RecordDetail ptrRecordIPv6 = null;\n\n      for (RecordDetail record : records) {\n         if (record.getData().equals(serverIPv4)) {\n            ptrRecordIPv4 = record;\n            ptrRecordIPv4Id = record.getId();\n         }\n         else {\n            ptrRecordIPv6 = record;\n            ptrRecordIPv6Id = record.getId();\n         }\n      }\n\n      assertNotNull(ptrRecordIPv4.getId());\n      assertEquals(ptrRecordIPv4.getType(), \"PTR\");\n      assertEquals(ptrRecordIPv4.getName(), JCLOUDS_EXAMPLE);\n      assertEquals(ptrRecordIPv4.getData(), serverIPv4);\n      assertEquals(ptrRecordIPv4.getTTL(), 11235);\n      assertNull(ptrRecordIPv4.getPriority());\n      assertNull(ptrRecordIPv4.getComment());\n      assertTrue(ptrRecordIPv4.getCreated().before(now));\n      assertTrue(ptrRecordIPv4.getUpdated().before(now));\n\n      assertNotNull(ptrRecordIPv6.getId());\n      assertEquals(ptrRecordIPv6.getType(), \"PTR\");\n      assertEquals(ptrRecordIPv6.getName(), JCLOUDS_EXAMPLE);\n      // can't test equals for data as CDNS will remove leading 0s from IPv6 Addrs\n      assertNotNull(ptrRecordIPv6.getData());\n      assertTrue(ptrRecordIPv6.getTTL() > 0);\n      assertNull(ptrRecordIPv6.getPriority());\n      assertEquals(ptrRecordIPv6.getComment(), \"Hello IPv6\");\n      assertTrue(ptrRecordIPv6.getCreated().before(now));\n      assertTrue(ptrRecordIPv6.getUpdated().before(now));\n   }\n\n   @Test(dependsOnMethods = \"testCreateReverseDNSRecords\")\n   public void testListReverseDNSRecords() throws Exception {\n      Set<RecordDetail> records = api.getReverseDNSApi(CLOUD_SERVERS_OPEN_STACK).list(serverURI).concat()\n            .toSet();\n      assertEquals(records.size(), 2);\n   }\n\n   @Test(dependsOnMethods = \"testListReverseDNSRecords\")\n   public void testUpdateAndGetReverseDNSRecords() throws Exception {\n      Record updatePTRRecordIPv4 = Record.builder().type(\"PTR\").name(JCLOUDS_EXAMPLE).data(serverIPv4).ttl(12358)\n            .build();\n\n      Map<String, Record> idsToRecords = ImmutableMap.<String, Record> of(ptrRecordIPv4Id, updatePTRRecordIPv4);\n\n      awaitComplete(api, api.getReverseDNSApi(CLOUD_SERVERS_OPEN_STACK).update(serverURI, idsToRecords));\n\n      RecordDetail record = api.getReverseDNSApi(CLOUD_SERVERS_OPEN_STACK).get(serverURI, ptrRecordIPv4Id);\n      Date now = new Date();\n\n      assertNotNull(record.getId());\n      assertEquals(record.getType(), \"PTR\");\n      assertEquals(record.getName(), JCLOUDS_EXAMPLE);\n      assertEquals(record.getData(), serverIPv4);\n      assertEquals(record.getTTL(), 12358);\n      assertNull(record.getPriority());\n      assertNull(record.getComment());\n      assertTrue(record.getCreated().before(now));\n      assertTrue(record.getUpdated().before(now));\n   }\n\n   @Test(dependsOnMethods = \"testUpdateAndGetReverseDNSRecords\")\n   public void testDeleteReverseDNSRecord() throws Exception {\n      awaitComplete(api, api.getReverseDNSApi(CLOUD_SERVERS_OPEN_STACK).delete(serverURI, serverIPv4));\n\n      assertNull(api.getReverseDNSApi(CLOUD_SERVERS_OPEN_STACK).get(serverURI, ptrRecordIPv4Id));\n   }\n\n   @Test(dependsOnMethods = \"testUpdateAndGetReverseDNSRecords\")\n   public void testDeleteReverseDNSRecords() throws Exception {\n      awaitComplete(api, api.getReverseDNSApi(CLOUD_SERVERS_OPEN_STACK).deleteAll(serverURI));\n\n      assertNull(api.getReverseDNSApi(CLOUD_SERVERS_OPEN_STACK).get(serverURI, ptrRecordIPv6Id));\n   }\n\n   @Override\n   @AfterClass(groups = { \"integration\", \"live\" })\n   protected void tearDown() {\n      try {\n         computeService.destroyNode(serverId);\n         awaitComplete(api, api.getDomainApi().delete(ImmutableList.<Integer> of(domainId), true));\n      }\n      catch (TimeoutException e) {\n         e.printStackTrace();\n      }\n      super.tearDown();\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/java/org/jclouds/rackspace/clouddns/v1/internal/BaseCloudDNSApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1.internal;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rackspace.cloudidentity.v2_0.internal.RackspaceFixture;\nimport org.jclouds.rest.internal.BaseRestApiExpectTest;\n\npublic class BaseCloudDNSApiExpectTest<T> extends BaseRestApiExpectTest<T> {\n   protected HttpRequest rackspaceAuthWithUsernameAndApiKey;\n\n   protected String authToken;\n   protected HttpResponse responseWithAccess;\n\n   public BaseCloudDNSApiExpectTest() {\n      provider = \"rackspace-clouddns\";\n\n      rackspaceAuthWithUsernameAndApiKey = RackspaceFixture.INSTANCE\n            .initialAuthWithUsernameAndApiKey(identity, credential);\n      \n      authToken = RackspaceFixture.INSTANCE.getAuthToken();\n      responseWithAccess = RackspaceFixture.INSTANCE.responseWithAccess();\n   }\n\n   @Override\n   protected HttpRequestComparisonType compareHttpRequestAsType(HttpRequest input) {\n      return HttpRequestComparisonType.JSON;\n   }\n\n   protected HttpRequest.Builder<?> authenticatedGET() {\n      return HttpRequest.builder()\n            .method(\"GET\")\n            .addHeader(\"Accept\", MediaType.APPLICATION_JSON)\n            .addHeader(\"X-Auth-Token\", authToken);\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/java/org/jclouds/rackspace/clouddns/v1/internal/BaseCloudDNSApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.v1.internal;\n\nimport java.util.Properties;\n\nimport org.jclouds.apis.BaseApiLiveTest;\nimport org.jclouds.openstack.keystone.config.KeystoneProperties;\nimport org.jclouds.rackspace.clouddns.v1.CloudDNSApi;\n\npublic class BaseCloudDNSApiLiveTest extends BaseApiLiveTest<CloudDNSApi> {\n\n   public BaseCloudDNSApiLiveTest() {\n      provider = \"rackspace-clouddns\";\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      setIfTestSystemPropertyPresent(props, KeystoneProperties.CREDENTIAL_TYPE);\n      return props;\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/resources/domain-create-response.json",
    "content": "{\n  \"request\": \"{\\\"domains\\\":[{\\\"name\\\":\\\"jclouds-example.com\\\",\\\"emailAddress\\\":\\\"jclouds@jclouds-example.com\\\",\\\"ttl\\\":600000,\\\"comment\\\":\\\"Hello Domain\\\",\\\"subdomains\\\":{\\\"domains\\\":[{\\\"name\\\":\\\"dev.jclouds-example.com\\\",\\\"emailAddress\\\":\\\"jclouds@jclouds-example.com\\\",\\\"comment\\\":\\\"Hello dev subdomain\\\"},{\\\"name\\\":\\\"test.jclouds-example.com\\\",\\\"emailAddress\\\":\\\"jclouds@jclouds-example.com\\\",\\\"comment\\\":\\\"Hello test subdomain\\\"}]},\\\"recordsList\\\":{\\\"records\\\":[{\\\"name\\\":\\\"jclouds-example.com\\\",\\\"type\\\":\\\"MX\\\",\\\"data\\\":\\\"mail.jclouds-example.com\\\",\\\"priority\\\":11235},{\\\"name\\\":\\\"jclouds-example.com\\\",\\\"type\\\":\\\"A\\\",\\\"data\\\":\\\"10.0.0.1\\\"}]}},{\\\"name\\\":\\\"xjclouds-example.com\\\",\\\"emailAddress\\\":\\\"jclouds@jclouds-example.com\\\",\\\"ttl\\\":600000,\\\"comment\\\":\\\"Hello Domain\\\"}]}\",\n  \"response\": {\n    \"domains\": [\n      {\n        \"name\": \"jclouds-example.com\",\n        \"id\": 3650906,\n        \"comment\": \"Hello Domain\",\n        \"accountId\": 123123,\n        \"ttl\": 600000,\n        \"subdomains\": {\n          \"domains\": [\n            {\n              \"name\": \"dev.jclouds-example.com\",\n              \"id\": 3650907,\n              \"comment\": \"Hello dev subdomain\",\n              \"accountId\": 123123,\n              \"ttl\": 3600,\n              \"emailAddress\": \"jclouds@jclouds-example.com\",\n              \"nameservers\": [\n                {\n                  \"name\": \"dns1.stabletransit.com\"\n                },\n                {\n                  \"name\": \"dns2.stabletransit.com\"\n                }\n              ],\n              \"updated\": \"2013-03-22T03:04:15.000+0000\",\n              \"created\": \"2013-03-22T03:04:15.000+0000\"\n            },\n            {\n              \"name\": \"test.jclouds-example.com\",\n              \"id\": 3650908,\n              \"comment\": \"Hello test subdomain\",\n              \"accountId\": 123123,\n              \"ttl\": 3600,\n              \"emailAddress\": \"jclouds@jclouds-example.com\",\n              \"nameservers\": [\n                {\n                  \"name\": \"dns1.stabletransit.com\"\n                },\n                {\n                  \"name\": \"dns2.stabletransit.com\"\n                }\n              ],\n              \"updated\": \"2013-03-22T03:04:15.000+0000\",\n              \"created\": \"2013-03-22T03:04:15.000+0000\"\n            }\n          ]\n        },\n        \"recordsList\": {\n          \"records\": [\n            {\n              \"name\": \"jclouds-example.com\",\n              \"id\": \"MX-4328817\",\n              \"priority\": 11235,\n              \"type\": \"MX\",\n              \"data\": \"mail.jclouds-example.com\",\n              \"ttl\": 600000,\n              \"updated\": \"2013-03-22T03:04:13.000+0000\",\n              \"created\": \"2013-03-22T03:04:13.000+0000\"\n            },\n            {\n              \"name\": \"jclouds-example.com\",\n              \"id\": \"A-9785208\",\n              \"type\": \"A\",\n              \"data\": \"10.0.0.1\",\n              \"ttl\": 600000,\n              \"updated\": \"2013-03-22T03:04:14.000+0000\",\n              \"created\": \"2013-03-22T03:04:14.000+0000\"\n            }\n          ]\n        },\n        \"emailAddress\": \"jclouds@jclouds-example.com\",\n        \"nameservers\": [\n          {\n            \"name\": \"dns1.stabletransit.com\"\n          },\n          {\n            \"name\": \"dns2.stabletransit.com\"\n          }\n        ],\n        \"updated\": \"2013-03-22T03:04:12.000+0000\",\n        \"created\": \"2013-03-22T03:04:12.000+0000\"\n      },\n      {\n        \"name\": \"xjclouds-example.com\",\n        \"id\": 3650909,\n        \"comment\": \"Hello Domain\",\n        \"accountId\": 123123,\n        \"ttl\": 600000,\n        \"emailAddress\": \"jclouds@jclouds-example.com\",\n        \"nameservers\": [\n          {\n            \"name\": \"dns1.stabletransit.com\"\n          },\n          {\n            \"name\": \"dns2.stabletransit.com\"\n          }\n        ],\n        \"updated\": \"2013-03-22T03:04:16.000+0000\",\n        \"created\": \"2013-03-22T03:04:16.000+0000\"\n      }\n    ]\n  },\n  \"status\": \"COMPLETED\",\n  \"verb\": \"POST\",\n  \"jobId\": \"3f4be747-70b0-40e6-96fe-e445c3e12805\",\n  \"callbackUrl\": \"https://dns.api.rackspacecloud.com/v1.0/123123/status/3f4be747-70b0-40e6-96fe-e445c3e12805\",\n  \"requestUrl\": \"https://dns.api.rackspacecloud.com/v1.0/123123/domains\"\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/resources/domain-create.json",
    "content": "{\"domains\":[{\"name\":\"jclouds-example.com\",\"emailAddress\":\"jclouds@jclouds-example.com\",\"ttl\":600000,\"comment\":\"Hello Domain\",\"subdomains\":{\"domains\":[{\"name\":\"dev.jclouds-example.com\",\"emailAddress\":\"jclouds@jclouds-example.com\",\"comment\":\"Hello dev subdomain\"},{\"name\":\"test.jclouds-example.com\",\"emailAddress\":\"jclouds@jclouds-example.com\",\"comment\":\"Hello test subdomain\"}]},\"recordsList\":{\"records\":[{\"name\":\"jclouds-example.com\",\"type\":\"MX\",\"data\":\"mail.jclouds-example.com\",\"priority\":11235},{\"name\":\"jclouds-example.com\",\"type\":\"A\",\"data\":\"10.0.0.1\"}]}},{\"name\":\"xjclouds-example.com\",\"emailAddress\":\"jclouds@jclouds-example.com\",\"ttl\":600000,\"comment\":\"Hello Domain\",\"subdomains\":{},\"recordsList\":{}}]}"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/resources/domain-delete.json",
    "content": "{\n  \"status\": \"COMPLETED\",\n  \"verb\": \"DELETE\",\n  \"jobId\": \"769cffe7-407c-4146-bab5-3a6c4da3e374\",\n  \"callbackUrl\": \"https://dns.api.rackspacecloud.com/v1.0/123123/status/769cffe7-407c-4146-bab5-3a6c4da3e374\",\n  \"requestUrl\": \"https://dns.api.rackspacecloud.com/v1.0/123123/domainsid=3650909&deleteSubdomains=true\"\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/resources/domain-export.json",
    "content": "{\n  \"response\": {\n    \"id\": 3651323,\n    \"contentType\": \"BIND_9\",\n    \"contents\": \"jclouds-example.com.\\t600000\\tIN\\tSOA\\tns.rackspace.com. jclouds.jclouds-example.com. 1363960242 21600 3600 1814400 500\\njclouds-example.com.\\t600000\\tIN\\tA\\t10.0.0.1\\njclouds-example.com.\\t600000\\tIN\\tNS\\tdns1.stabletransit.com.\\njclouds-example.com.\\t600000\\tIN\\tNS\\tdns2.stabletransit.com.\\njclouds-example.com.\\t600000\\tIN\\tMX\\t11235 mail.jclouds-example.com.\\n\",\n    \"accountId\": 123123\n  },\n  \"status\": \"COMPLETED\",\n  \"verb\": \"GET\",\n  \"jobId\": \"526d518b-f1b1-4e25-9e19-9643cb030a1e\",\n  \"callbackUrl\": \"https://dns.api.rackspacecloud.com/v1.0/123123/status/526d518b-f1b1-4e25-9e19-9643cb030a1e\",\n  \"requestUrl\": \"https://dns.api.rackspacecloud.com/v1.0/123123/domains/3651323/export\"\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/resources/domain-get.json",
    "content": "{\n  \"name\": \"test.jclouds-example.com\",\n  \"id\": 3650908,\n  \"comment\": \"Hello test subdomain\",\n  \"accountId\": 123123,\n  \"ttl\": 3600,\n  \"recordsList\": {\n    \"records\": [\n      {\n        \"name\": \"test.jclouds-example.com\",\n        \"id\": \"NS-8646158\",\n        \"type\": \"NS\",\n        \"data\": \"dns1.stabletransit.com\",\n        \"ttl\": 3600,\n        \"updated\": \"2013-03-22T03:04:15.000+0000\",\n        \"created\": \"2013-03-22T03:04:15.000+0000\"\n      },\n      {\n        \"name\": \"test.jclouds-example.com\",\n        \"id\": \"NS-8646159\",\n        \"type\": \"NS\",\n        \"data\": \"dns2.stabletransit.com\",\n        \"ttl\": 3600,\n        \"updated\": \"2013-03-22T03:04:16.000+0000\",\n        \"created\": \"2013-03-22T03:04:16.000+0000\"\n      }\n    ],\n    \"totalEntries\": 2\n  },\n  \"emailAddress\": \"jclouds@jclouds-example.com\",\n  \"nameservers\": [\n    {\n      \"name\": \"dns1.stabletransit.com\"\n    },\n    {\n      \"name\": \"dns2.stabletransit.com\"\n    }\n  ],\n  \"updated\": \"2013-03-22T03:04:16.000+0000\",\n  \"created\": \"2013-03-22T03:04:15.000+0000\"\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/resources/domain-import-response.json",
    "content": "{\n  \"request\": \"{\\\"domains\\\":[{\\\"contentType\\\":\\\"BIND_9\\\",\\\"contents\\\":\\\"jclouds-example.com.      3600  IN SOA   ns.rackspace.com. jclouds.jclouds-example.com. 1363882703 3600 3600 3600 3600\\\\njclouds-example.com.      600   IN A  50.56.174.152\\\"}]}\",\n  \"response\": {\n    \"domains\": [\n      {\n        \"name\": \"jclouds-example.com\",\n        \"id\": 3653942,\n        \"accountId\": 123123,\n        \"ttl\": 3600,\n        \"recordsList\": {\n          \"records\": [\n            {\n              \"name\": \"jclouds-example.com\",\n              \"id\": \"A-9795196\",\n              \"type\": \"A\",\n              \"data\": \"50.56.174.152\",\n              \"ttl\": 600,\n              \"updated\": \"2013-03-25T15:15:09.000+0000\",\n              \"created\": \"2013-03-25T15:15:09.000+0000\"\n            }\n          ]\n        },\n        \"emailAddress\": \"jclouds@jclouds-example.com\",\n        \"nameservers\": [\n          {\n            \"name\": \"dns1.stabletransit.com\"\n          },\n          {\n            \"name\": \"dns2.stabletransit.com\"\n          }\n        ],\n        \"updated\": \"2013-03-25T15:15:08.000+0000\",\n        \"created\": \"2013-03-25T15:15:08.000+0000\"\n      }\n    ]\n  },\n  \"status\": \"COMPLETED\",\n  \"verb\": \"POST\",\n  \"jobId\": \"7729a749-7a16-41ee-a081-00ed71dce4bb\",\n  \"callbackUrl\": \"https://dns.api.rackspacecloud.com/v1.0/123123/status/7729a749-7a16-41ee-a081-00ed71dce4bb\",\n  \"requestUrl\": \"https://dns.api.rackspacecloud.com/v1.0/123123/domains/import\"\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/resources/domain-import.json",
    "content": "{\"domains\":[{\"contentType\":\"BIND_9\",\"contents\":\"jclouds-example.com.      3600  IN SOA   ns.rackspace.com. jclouds.jclouds-example.com. 1363882703 3600 3600 3600 3600\\njclouds-example.com.      600   IN A  50.56.174.152\"}]}"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/resources/domain-list-changes.json",
    "content": "{\n  \"changes\": [\n    {\n      \"domain\": \"test.jclouds-example.com\",\n      \"action\": \"update\",\n      \"targetType\": \"Domain\",\n      \"accountId\": 123123,\n      \"changeDetails\": [\n        {\n          \"field\": \"serial_number\",\n          \"newValue\": \"1363921456\",\n          \"originalValue\": \"1363921455\"\n        },\n        {\n          \"field\": \"updated_at\",\n          \"newValue\": \"Fri Mar 22 03:04:16 UTC 2013\",\n          \"originalValue\": \"Fri Mar 22 03:04:15 UTC 2013\"\n        }\n      ],\n      \"targetId\": 3650908\n    },\n    {\n      \"domain\": \"test.jclouds-example.com\",\n      \"action\": \"create\",\n      \"targetType\": \"NS Record\",\n      \"changeDetails\": [\n        {\n          \"field\": \"created_at\",\n          \"newValue\": \"Fri Mar 22 03:04:16 UTC 2013\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"fqdn\",\n          \"newValue\": \"test.jclouds-example.com\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"ttl\",\n          \"newValue\": \"3600\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"updated_at\",\n          \"newValue\": \"Fri Mar 22 03:04:16 UTC 2013\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"destination\",\n          \"newValue\": \"dns2.stabletransit.com\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"id\",\n          \"newValue\": \"8646159\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"zone_id\",\n          \"newValue\": \"3650908\",\n          \"originalValue\": \"\"\n        }\n      ],\n      \"targetId\": 8646159\n    },\n    {\n      \"domain\": \"test.jclouds-example.com\",\n      \"action\": \"update\",\n      \"targetType\": \"Domain\",\n      \"accountId\": 123123,\n      \"targetId\": 3650908\n    },\n    {\n      \"domain\": \"test.jclouds-example.com\",\n      \"action\": \"create\",\n      \"targetType\": \"NS Record\",\n      \"changeDetails\": [\n        {\n          \"field\": \"created_at\",\n          \"newValue\": \"Fri Mar 22 03:04:15 UTC 2013\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"fqdn\",\n          \"newValue\": \"test.jclouds-example.com\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"ttl\",\n          \"newValue\": \"3600\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"updated_at\",\n          \"newValue\": \"Fri Mar 22 03:04:15 UTC 2013\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"destination\",\n          \"newValue\": \"dns1.stabletransit.com\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"id\",\n          \"newValue\": \"8646158\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"zone_id\",\n          \"newValue\": \"3650908\",\n          \"originalValue\": \"\"\n        }\n      ],\n      \"targetId\": 8646158\n    },\n    {\n      \"domain\": \"test.jclouds-example.com\",\n      \"action\": \"create\",\n      \"targetType\": \"Domain\",\n      \"accountId\": 123123,\n      \"changeDetails\": [\n        {\n          \"field\": \"serial_number\",\n          \"newValue\": \"1363921455\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"comment\",\n          \"newValue\": \"Hello test subdomain\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"label\",\n          \"newValue\": \"test.jclouds-example.com\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"auth_name_server\",\n          \"newValue\": \"ns.rackspace.com\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"created_at\",\n          \"newValue\": \"Fri Mar 22 03:04:15 UTC 2013\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"owner_number\",\n          \"newValue\": \"DCO579619\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"ttl\",\n          \"newValue\": \"3600\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"responsible_email\",\n          \"newValue\": \"jclouds@jclouds-example.com\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"updated_at\",\n          \"newValue\": \"Fri Mar 22 03:04:15 UTC 2013\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"id\",\n          \"newValue\": \"3650908\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"reverse_label\",\n          \"newValue\": \"moc.elpmaxe-sduolcj.tset\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"refresh\",\n          \"newValue\": \"3600\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"type\",\n          \"newValue\": \"DefaultZone\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"minimum_ttl\",\n          \"newValue\": \"3600\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"expiry\",\n          \"newValue\": \"3600\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"update_retry\",\n          \"newValue\": \"300\",\n          \"originalValue\": \"\"\n        }\n      ],\n      \"targetId\": 3650908\n    },\n    {\n      \"domain\": \"test.jclouds-example.com\",\n      \"action\": \"destroy\",\n      \"targetType\": \"Domain\",\n      \"accountId\": 123123,\n      \"changeDetails\": [\n        {\n          \"field\": \"auth_name_server\",\n          \"newValue\": \"\",\n          \"originalValue\": \"ns.rackspace.com\"\n        },\n        {\n          \"field\": \"comment\",\n          \"newValue\": \"\",\n          \"originalValue\": \"Hello test subdomain\"\n        },\n        {\n          \"field\": \"label\",\n          \"newValue\": \"\",\n          \"originalValue\": \"test.jclouds-example.com\"\n        },\n        {\n          \"field\": \"serial_number\",\n          \"newValue\": \"\",\n          \"originalValue\": \"1363920596\"\n        },\n        {\n          \"field\": \"created_at\",\n          \"newValue\": \"\",\n          \"originalValue\": \"Fri Mar 22 02:49:55 UTC 2013\"\n        },\n        {\n          \"field\": \"owner_number\",\n          \"newValue\": \"\",\n          \"originalValue\": \"DCO579619\"\n        },\n        {\n          \"field\": \"responsible_email\",\n          \"newValue\": \"\",\n          \"originalValue\": \"jclouds@jclouds-example.com\"\n        },\n        {\n          \"field\": \"ttl\",\n          \"newValue\": \"\",\n          \"originalValue\": \"3600\"\n        },\n        {\n          \"field\": \"allow_indefinite_ttl_change\",\n          \"newValue\": \"\",\n          \"originalValue\": \"false\"\n        },\n        {\n          \"field\": \"updated_at\",\n          \"newValue\": \"\",\n          \"originalValue\": \"Fri Mar 22 02:49:56 UTC 2013\"\n        },\n        {\n          \"field\": \"id\",\n          \"newValue\": \"\",\n          \"originalValue\": \"3650900\"\n        },\n        {\n          \"field\": \"refresh\",\n          \"newValue\": \"\",\n          \"originalValue\": \"3600\"\n        },\n        {\n          \"field\": \"reverse_label\",\n          \"newValue\": \"\",\n          \"originalValue\": \"moc.elpmaxe-sduolcj.tset\"\n        },\n        {\n          \"field\": \"type\",\n          \"newValue\": \"\",\n          \"originalValue\": \"DefaultZone\"\n        },\n        {\n          \"field\": \"minimum_ttl\",\n          \"newValue\": \"\",\n          \"originalValue\": \"3600\"\n        },\n        {\n          \"field\": \"expiry\",\n          \"newValue\": \"\",\n          \"originalValue\": \"3600\"\n        },\n        {\n          \"field\": \"update_retry\",\n          \"newValue\": \"\",\n          \"originalValue\": \"300\"\n        }\n      ],\n      \"targetId\": 3650900\n    },\n    {\n      \"domain\": \"test.jclouds-example.com\",\n      \"action\": \"update\",\n      \"targetType\": \"Domain\",\n      \"accountId\": 123123,\n      \"targetId\": 3650900\n    },\n    {\n      \"domain\": \"test.jclouds-example.com\",\n      \"action\": \"destroy\",\n      \"targetType\": \"NS Record\",\n      \"changeDetails\": [\n        {\n          \"field\": \"created_at\",\n          \"newValue\": \"\",\n          \"originalValue\": \"Fri Mar 22 02:49:56 UTC 2013\"\n        },\n        {\n          \"field\": \"fqdn\",\n          \"newValue\": \"\",\n          \"originalValue\": \"test.jclouds-example.com\"\n        },\n        {\n          \"field\": \"ttl\",\n          \"newValue\": \"\",\n          \"originalValue\": \"3600\"\n        },\n        {\n          \"field\": \"destination\",\n          \"newValue\": \"\",\n          \"originalValue\": \"dns2.stabletransit.com\"\n        },\n        {\n          \"field\": \"updated_at\",\n          \"newValue\": \"\",\n          \"originalValue\": \"Fri Mar 22 02:49:56 UTC 2013\"\n        },\n        {\n          \"field\": \"id\",\n          \"newValue\": \"\",\n          \"originalValue\": \"8646143\"\n        },\n        {\n          \"field\": \"zone_id\",\n          \"newValue\": \"\",\n          \"originalValue\": \"3650900\"\n        }\n      ],\n      \"targetId\": 8646143\n    },\n    {\n      \"domain\": \"test.jclouds-example.com\",\n      \"action\": \"update\",\n      \"targetType\": \"Domain\",\n      \"accountId\": 123123,\n      \"changeDetails\": [\n        {\n          \"field\": \"serial_number\",\n          \"newValue\": \"1363921396\",\n          \"originalValue\": \"1363920596\"\n        },\n        {\n          \"field\": \"updated_at\",\n          \"newValue\": \"Fri Mar 22 03:03:16 UTC 2013\",\n          \"originalValue\": \"Fri Mar 22 02:49:56 UTC 2013\"\n        }\n      ],\n      \"targetId\": 3650900\n    },\n    {\n      \"domain\": \"test.jclouds-example.com\",\n      \"action\": \"destroy\",\n      \"targetType\": \"NS Record\",\n      \"changeDetails\": [\n        {\n          \"field\": \"created_at\",\n          \"newValue\": \"\",\n          \"originalValue\": \"Fri Mar 22 02:49:56 UTC 2013\"\n        },\n        {\n          \"field\": \"fqdn\",\n          \"newValue\": \"\",\n          \"originalValue\": \"test.jclouds-example.com\"\n        },\n        {\n          \"field\": \"ttl\",\n          \"newValue\": \"\",\n          \"originalValue\": \"3600\"\n        },\n        {\n          \"field\": \"destination\",\n          \"newValue\": \"\",\n          \"originalValue\": \"dns1.stabletransit.com\"\n        },\n        {\n          \"field\": \"updated_at\",\n          \"newValue\": \"\",\n          \"originalValue\": \"Fri Mar 22 02:49:56 UTC 2013\"\n        },\n        {\n          \"field\": \"id\",\n          \"newValue\": \"\",\n          \"originalValue\": \"8646141\"\n        },\n        {\n          \"field\": \"zone_id\",\n          \"newValue\": \"\",\n          \"originalValue\": \"3650900\"\n        }\n      ],\n      \"targetId\": 8646141\n    },\n    {\n      \"domain\": \"test.jclouds-example.com\",\n      \"action\": \"update\",\n      \"targetType\": \"Domain\",\n      \"accountId\": 123123,\n      \"targetId\": 3650900\n    },\n    {\n      \"domain\": \"test.jclouds-example.com\",\n      \"action\": \"create\",\n      \"targetType\": \"NS Record\",\n      \"changeDetails\": [\n        {\n          \"field\": \"created_at\",\n          \"newValue\": \"Fri Mar 22 02:49:56 UTC 2013\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"fqdn\",\n          \"newValue\": \"test.jclouds-example.com\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"ttl\",\n          \"newValue\": \"3600\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"updated_at\",\n          \"newValue\": \"Fri Mar 22 02:49:56 UTC 2013\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"destination\",\n          \"newValue\": \"dns2.stabletransit.com\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"id\",\n          \"newValue\": \"8646143\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"zone_id\",\n          \"newValue\": \"3650900\",\n          \"originalValue\": \"\"\n        }\n      ],\n      \"targetId\": 8646143\n    },\n    {\n      \"domain\": \"test.jclouds-example.com\",\n      \"action\": \"update\",\n      \"targetType\": \"Domain\",\n      \"accountId\": 123123,\n      \"changeDetails\": [\n        {\n          \"field\": \"serial_number\",\n          \"newValue\": \"1363920596\",\n          \"originalValue\": \"1363920595\"\n        },\n        {\n          \"field\": \"updated_at\",\n          \"newValue\": \"Fri Mar 22 02:49:56 UTC 2013\",\n          \"originalValue\": \"Fri Mar 22 02:49:55 UTC 2013\"\n        }\n      ],\n      \"targetId\": 3650900\n    },\n    {\n      \"domain\": \"test.jclouds-example.com\",\n      \"action\": \"create\",\n      \"targetType\": \"NS Record\",\n      \"changeDetails\": [\n        {\n          \"field\": \"created_at\",\n          \"newValue\": \"Fri Mar 22 02:49:56 UTC 2013\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"fqdn\",\n          \"newValue\": \"test.jclouds-example.com\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"ttl\",\n          \"newValue\": \"3600\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"updated_at\",\n          \"newValue\": \"Fri Mar 22 02:49:56 UTC 2013\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"destination\",\n          \"newValue\": \"dns1.stabletransit.com\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"id\",\n          \"newValue\": \"8646141\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"zone_id\",\n          \"newValue\": \"3650900\",\n          \"originalValue\": \"\"\n        }\n      ],\n      \"targetId\": 8646141\n    },\n    {\n      \"domain\": \"test.jclouds-example.com\",\n      \"action\": \"create\",\n      \"targetType\": \"Domain\",\n      \"accountId\": 123123,\n      \"changeDetails\": [\n        {\n          \"field\": \"serial_number\",\n          \"newValue\": \"1363920595\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"comment\",\n          \"newValue\": \"Hello test subdomain\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"label\",\n          \"newValue\": \"test.jclouds-example.com\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"auth_name_server\",\n          \"newValue\": \"ns.rackspace.com\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"created_at\",\n          \"newValue\": \"Fri Mar 22 02:49:55 UTC 2013\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"owner_number\",\n          \"newValue\": \"DCO579619\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"ttl\",\n          \"newValue\": \"3600\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"responsible_email\",\n          \"newValue\": \"jclouds@jclouds-example.com\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"updated_at\",\n          \"newValue\": \"Fri Mar 22 02:49:55 UTC 2013\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"id\",\n          \"newValue\": \"3650900\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"reverse_label\",\n          \"newValue\": \"moc.elpmaxe-sduolcj.tset\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"refresh\",\n          \"newValue\": \"3600\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"type\",\n          \"newValue\": \"DefaultZone\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"minimum_ttl\",\n          \"newValue\": \"3600\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"expiry\",\n          \"newValue\": \"3600\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"update_retry\",\n          \"newValue\": \"300\",\n          \"originalValue\": \"\"\n        }\n      ],\n      \"targetId\": 3650900\n    },\n    {\n      \"domain\": \"test.jclouds-example.com\",\n      \"action\": \"destroy\",\n      \"targetType\": \"Domain\",\n      \"accountId\": 123123,\n      \"changeDetails\": [\n        {\n          \"field\": \"auth_name_server\",\n          \"newValue\": \"\",\n          \"originalValue\": \"ns.rackspace.com\"\n        },\n        {\n          \"field\": \"comment\",\n          \"newValue\": \"\",\n          \"originalValue\": \"Hello test subdomain\"\n        },\n        {\n          \"field\": \"label\",\n          \"newValue\": \"\",\n          \"originalValue\": \"test.jclouds-example.com\"\n        },\n        {\n          \"field\": \"serial_number\",\n          \"newValue\": \"\",\n          \"originalValue\": \"1363919226\"\n        },\n        {\n          \"field\": \"created_at\",\n          \"newValue\": \"\",\n          \"originalValue\": \"Fri Mar 22 02:27:06 UTC 2013\"\n        },\n        {\n          \"field\": \"owner_number\",\n          \"newValue\": \"\",\n          \"originalValue\": \"DCO579619\"\n        },\n        {\n          \"field\": \"responsible_email\",\n          \"newValue\": \"\",\n          \"originalValue\": \"jclouds@jclouds-example.com\"\n        },\n        {\n          \"field\": \"ttl\",\n          \"newValue\": \"\",\n          \"originalValue\": \"3600\"\n        },\n        {\n          \"field\": \"allow_indefinite_ttl_change\",\n          \"newValue\": \"\",\n          \"originalValue\": \"false\"\n        },\n        {\n          \"field\": \"updated_at\",\n          \"newValue\": \"\",\n          \"originalValue\": \"Fri Mar 22 02:27:06 UTC 2013\"\n        },\n        {\n          \"field\": \"id\",\n          \"newValue\": \"\",\n          \"originalValue\": \"3650882\"\n        },\n        {\n          \"field\": \"refresh\",\n          \"newValue\": \"\",\n          \"originalValue\": \"3600\"\n        },\n        {\n          \"field\": \"reverse_label\",\n          \"newValue\": \"\",\n          \"originalValue\": \"moc.elpmaxe-sduolcj.tset\"\n        },\n        {\n          \"field\": \"type\",\n          \"newValue\": \"\",\n          \"originalValue\": \"DefaultZone\"\n        },\n        {\n          \"field\": \"minimum_ttl\",\n          \"newValue\": \"\",\n          \"originalValue\": \"3600\"\n        },\n        {\n          \"field\": \"expiry\",\n          \"newValue\": \"\",\n          \"originalValue\": \"3600\"\n        },\n        {\n          \"field\": \"update_retry\",\n          \"newValue\": \"\",\n          \"originalValue\": \"300\"\n        }\n      ],\n      \"targetId\": 3650882\n    },\n    {\n      \"domain\": \"test.jclouds-example.com\",\n      \"action\": \"update\",\n      \"targetType\": \"Domain\",\n      \"accountId\": 123123,\n      \"targetId\": 3650882\n    },\n    {\n      \"domain\": \"test.jclouds-example.com\",\n      \"action\": \"destroy\",\n      \"targetType\": \"NS Record\",\n      \"changeDetails\": [\n        {\n          \"field\": \"created_at\",\n          \"newValue\": \"\",\n          \"originalValue\": \"Fri Mar 22 02:27:06 UTC 2013\"\n        },\n        {\n          \"field\": \"fqdn\",\n          \"newValue\": \"\",\n          \"originalValue\": \"test.jclouds-example.com\"\n        },\n        {\n          \"field\": \"ttl\",\n          \"newValue\": \"\",\n          \"originalValue\": \"3600\"\n        },\n        {\n          \"field\": \"destination\",\n          \"newValue\": \"\",\n          \"originalValue\": \"dns2.stabletransit.com\"\n        },\n        {\n          \"field\": \"updated_at\",\n          \"newValue\": \"\",\n          \"originalValue\": \"Fri Mar 22 02:27:06 UTC 2013\"\n        },\n        {\n          \"field\": \"id\",\n          \"newValue\": \"\",\n          \"originalValue\": \"8646106\"\n        },\n        {\n          \"field\": \"zone_id\",\n          \"newValue\": \"\",\n          \"originalValue\": \"3650882\"\n        }\n      ],\n      \"targetId\": 8646106\n    },\n    {\n      \"domain\": \"test.jclouds-example.com\",\n      \"action\": \"update\",\n      \"targetType\": \"Domain\",\n      \"accountId\": 123123,\n      \"changeDetails\": [\n        {\n          \"field\": \"serial_number\",\n          \"newValue\": \"1363920514\",\n          \"originalValue\": \"1363919226\"\n        },\n        {\n          \"field\": \"updated_at\",\n          \"newValue\": \"Fri Mar 22 02:48:34 UTC 2013\",\n          \"originalValue\": \"Fri Mar 22 02:27:06 UTC 2013\"\n        }\n      ],\n      \"targetId\": 3650882\n    },\n    {\n      \"domain\": \"test.jclouds-example.com\",\n      \"action\": \"destroy\",\n      \"targetType\": \"NS Record\",\n      \"changeDetails\": [\n        {\n          \"field\": \"created_at\",\n          \"newValue\": \"\",\n          \"originalValue\": \"Fri Mar 22 02:27:06 UTC 2013\"\n        },\n        {\n          \"field\": \"fqdn\",\n          \"newValue\": \"\",\n          \"originalValue\": \"test.jclouds-example.com\"\n        },\n        {\n          \"field\": \"ttl\",\n          \"newValue\": \"\",\n          \"originalValue\": \"3600\"\n        },\n        {\n          \"field\": \"destination\",\n          \"newValue\": \"\",\n          \"originalValue\": \"dns1.stabletransit.com\"\n        },\n        {\n          \"field\": \"updated_at\",\n          \"newValue\": \"\",\n          \"originalValue\": \"Fri Mar 22 02:27:06 UTC 2013\"\n        },\n        {\n          \"field\": \"id\",\n          \"newValue\": \"\",\n          \"originalValue\": \"8646105\"\n        },\n        {\n          \"field\": \"zone_id\",\n          \"newValue\": \"\",\n          \"originalValue\": \"3650882\"\n        }\n      ],\n      \"targetId\": 8646105\n    },\n    {\n      \"domain\": \"test.jclouds-example.com\",\n      \"action\": \"update\",\n      \"targetType\": \"Domain\",\n      \"accountId\": 123123,\n      \"targetId\": 3650882\n    },\n    {\n      \"domain\": \"test.jclouds-example.com\",\n      \"action\": \"create\",\n      \"targetType\": \"NS Record\",\n      \"changeDetails\": [\n        {\n          \"field\": \"created_at\",\n          \"newValue\": \"Fri Mar 22 02:27:06 UTC 2013\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"fqdn\",\n          \"newValue\": \"test.jclouds-example.com\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"ttl\",\n          \"newValue\": \"3600\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"updated_at\",\n          \"newValue\": \"Fri Mar 22 02:27:06 UTC 2013\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"destination\",\n          \"newValue\": \"dns2.stabletransit.com\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"id\",\n          \"newValue\": \"8646106\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"zone_id\",\n          \"newValue\": \"3650882\",\n          \"originalValue\": \"\"\n        }\n      ],\n      \"targetId\": 8646106\n    },\n    {\n      \"domain\": \"test.jclouds-example.com\",\n      \"action\": \"update\",\n      \"targetType\": \"Domain\",\n      \"accountId\": 123123,\n      \"targetId\": 3650882\n    },\n    {\n      \"domain\": \"test.jclouds-example.com\",\n      \"action\": \"create\",\n      \"targetType\": \"NS Record\",\n      \"changeDetails\": [\n        {\n          \"field\": \"created_at\",\n          \"newValue\": \"Fri Mar 22 02:27:06 UTC 2013\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"fqdn\",\n          \"newValue\": \"test.jclouds-example.com\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"ttl\",\n          \"newValue\": \"3600\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"updated_at\",\n          \"newValue\": \"Fri Mar 22 02:27:06 UTC 2013\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"destination\",\n          \"newValue\": \"dns1.stabletransit.com\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"id\",\n          \"newValue\": \"8646105\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"zone_id\",\n          \"newValue\": \"3650882\",\n          \"originalValue\": \"\"\n        }\n      ],\n      \"targetId\": 8646105\n    },\n    {\n      \"domain\": \"test.jclouds-example.com\",\n      \"action\": \"create\",\n      \"targetType\": \"Domain\",\n      \"accountId\": 123123,\n      \"changeDetails\": [\n        {\n          \"field\": \"serial_number\",\n          \"newValue\": \"1363919226\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"comment\",\n          \"newValue\": \"Hello test subdomain\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"label\",\n          \"newValue\": \"test.jclouds-example.com\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"auth_name_server\",\n          \"newValue\": \"ns.rackspace.com\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"created_at\",\n          \"newValue\": \"Fri Mar 22 02:27:06 UTC 2013\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"owner_number\",\n          \"newValue\": \"DCO579619\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"ttl\",\n          \"newValue\": \"3600\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"responsible_email\",\n          \"newValue\": \"jclouds@jclouds-example.com\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"updated_at\",\n          \"newValue\": \"Fri Mar 22 02:27:06 UTC 2013\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"id\",\n          \"newValue\": \"3650882\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"reverse_label\",\n          \"newValue\": \"moc.elpmaxe-sduolcj.tset\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"refresh\",\n          \"newValue\": \"3600\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"type\",\n          \"newValue\": \"DefaultZone\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"minimum_ttl\",\n          \"newValue\": \"3600\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"expiry\",\n          \"newValue\": \"3600\",\n          \"originalValue\": \"\"\n        },\n        {\n          \"field\": \"update_retry\",\n          \"newValue\": \"300\",\n          \"originalValue\": \"\"\n        }\n      ],\n      \"targetId\": 3650882\n    }\n  ],\n  \"from\": \"2013-03-22T00:00:00.000+0000\",\n  \"to\": \"2013-03-22T03:22:47.000+0000\",\n  \"totalEntries\": 25\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/resources/domain-list-page1.json",
    "content": "{\n  \"domains\": [\n    {\n      \"name\": \"dev.jclouds-example.com\",\n      \"id\": 3650907,\n      \"comment\": \"Hello dev subdomain\",\n      \"accountId\": 123123,\n      \"emailAddress\": \"jclouds@jclouds-example.com\",\n      \"updated\": \"2013-03-22T03:04:15.000+0000\",\n      \"created\": \"2013-03-22T03:04:15.000+0000\"\n    },\n    {\n      \"name\": \"jclouds-example.com\",\n      \"id\": 3650906,\n      \"comment\": \"Hello Domain\",\n      \"accountId\": 123123,\n      \"emailAddress\": \"jclouds@jclouds-example.com\",\n      \"updated\": \"2013-03-22T03:04:14.000+0000\",\n      \"created\": \"2013-03-22T03:04:12.000+0000\"\n    },\n    {\n      \"name\": \"test.jclouds-example.com\",\n      \"id\": 3650908,\n      \"comment\": \"Hello test subdomain\",\n      \"accountId\": 123123,\n      \"emailAddress\": \"jclouds@jclouds-example.com\",\n      \"updated\": \"2013-03-22T03:04:16.000+0000\",\n      \"created\": \"2013-03-22T03:04:15.000+0000\"\n    },\n    {\n      \"name\": \"xjclouds-example.com\",\n      \"id\": 3650909,\n      \"comment\": \"Hello Domain\",\n      \"accountId\": 123123,\n      \"emailAddress\": \"jclouds@jclouds-example.com\",\n      \"updated\": \"2013-03-22T03:04:16.000+0000\",\n      \"created\": \"2013-03-22T03:04:16.000+0000\"\n    }\n  ],\n  \"totalEntries\": 8, \n  \"links\": [\n  \t{\n  \t  \"href\":\"https://dns.api.rackspacecloud.com/v1.0/123123/domains?limit=4&offset=4\",\n  \t  \"rel\":\"next\"\n  \t}\n  ]\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/resources/domain-list-page2.json",
    "content": "{\n  \"domains\": [\n    {\n      \"name\": \"dev.jclouds-example.com\",\n      \"id\": 3650907,\n      \"comment\": \"Hello dev subdomain\",\n      \"accountId\": 123123,\n      \"emailAddress\": \"jclouds@jclouds-example.com\",\n      \"updated\": \"2013-03-22T03:04:15.000+0000\",\n      \"created\": \"2013-03-22T03:04:15.000+0000\"\n    },\n    {\n      \"name\": \"jclouds-example.com\",\n      \"id\": 3650906,\n      \"comment\": \"Hello Domain\",\n      \"accountId\": 123123,\n      \"emailAddress\": \"jclouds@jclouds-example.com\",\n      \"updated\": \"2013-03-22T03:04:14.000+0000\",\n      \"created\": \"2013-03-22T03:04:12.000+0000\"\n    },\n    {\n      \"name\": \"test.jclouds-example.com\",\n      \"id\": 3650908,\n      \"comment\": \"Hello test subdomain\",\n      \"accountId\": 123123,\n      \"emailAddress\": \"jclouds@jclouds-example.com\",\n      \"updated\": \"2013-03-22T03:04:16.000+0000\",\n      \"created\": \"2013-03-22T03:04:15.000+0000\"\n    },\n    {\n      \"name\": \"xjclouds-example.com\",\n      \"id\": 3650909,\n      \"comment\": \"Hello Domain\",\n      \"accountId\": 123123,\n      \"emailAddress\": \"jclouds@jclouds-example.com\",\n      \"updated\": \"2013-03-22T03:04:16.000+0000\",\n      \"created\": \"2013-03-22T03:04:16.000+0000\"\n    }\n  ],\n  \"totalEntries\": 8, \n  \"links\": [\n  \t{\n  \t  \"href\":\"https://dns.api.rackspacecloud.com/v1.0/123123/domains?limit=4&offset=0\",\n  \t  \"rel\":\"previous\"\n  \t}\n  ]\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/resources/domain-list-with-filter.json",
    "content": "{\n  \"domains\": [\n    {\n      \"name\": \"test.jclouds-example.com\",\n      \"id\": 3650908,\n      \"comment\": \"Hello test subdomain\",\n      \"emailAddress\": \"jclouds@jclouds-example.com\",\n      \"updated\": \"2013-03-22T03:04:16.000+0000\",\n      \"created\": \"2013-03-22T03:04:15.000+0000\"\n    }\n  ],\n  \"totalEntries\": 1\n}"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/resources/domain-list.json",
    "content": "{\n  \"domains\": [\n    {\n      \"name\": \"dev.jclouds-example.com\",\n      \"id\": 3650907,\n      \"comment\": \"Hello dev subdomain\",\n      \"accountId\": 123123,\n      \"emailAddress\": \"jclouds@jclouds-example.com\",\n      \"updated\": \"2013-03-22T03:04:15.000+0000\",\n      \"created\": \"2013-03-22T03:04:15.000+0000\"\n    },\n    {\n      \"name\": \"jclouds-example.com\",\n      \"id\": 3650906,\n      \"comment\": \"Hello Domain\",\n      \"accountId\": 123123,\n      \"emailAddress\": \"jclouds@jclouds-example.com\",\n      \"updated\": \"2013-03-22T03:04:14.000+0000\",\n      \"created\": \"2013-03-22T03:04:12.000+0000\"\n    },\n    {\n      \"name\": \"test.jclouds-example.com\",\n      \"id\": 3650908,\n      \"comment\": \"Hello test subdomain\",\n      \"accountId\": 123123,\n      \"emailAddress\": \"jclouds@jclouds-example.com\",\n      \"updated\": \"2013-03-22T03:04:16.000+0000\",\n      \"created\": \"2013-03-22T03:04:15.000+0000\"\n    },\n    {\n      \"name\": \"xjclouds-example.com\",\n      \"id\": 3650909,\n      \"comment\": \"Hello Domain\",\n      \"accountId\": 123123,\n      \"emailAddress\": \"jclouds@jclouds-example.com\",\n      \"updated\": \"2013-03-22T03:04:16.000+0000\",\n      \"created\": \"2013-03-22T03:04:16.000+0000\"\n    }\n  ],\n  \"totalEntries\": 4\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/resources/domain-update-email.json",
    "content": "{\"domains\":[{\"id\":3650906,\"emailAddress\":\"everett@jclouds-example.com\"},{\"id\":3650908,\"emailAddress\":\"everett@jclouds-example.com\"}]}"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/resources/domain-update-response.json",
    "content": "{\n  \"request\": \"{\\\"domains\\\":[{\\\"id\\\":3650906,\\\"emailAddress\\\":\\\"everett@jclouds-example.com\\\",\\\"ttl\\\":600001,\\\"comment\\\":\\\"Hello Domain Update\\\"},{\\\"id\\\":3650908,\\\"emailAddress\\\":\\\"everett@jclouds-example.com\\\",\\\"ttl\\\":600002,\\\"comment\\\":\\\"Hello Domain Update\\\"}]}\",\n  \"status\": \"COMPLETED\",\n  \"verb\": \"PUT\",\n  \"jobId\": \"b7fca312-abb5-4e23-91b4-8a21599f0403\",\n  \"callbackUrl\": \"https://dns.api.rackspacecloud.com/v1.0/123123/status/b7fca312-abb5-4e23-91b4-8a21599f0403\",\n  \"requestUrl\": \"https://dns.api.rackspacecloud.com/v1.0/123123/domains\"\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/resources/domain-update-ttl.json",
    "content": "{\"domains\":[{\"id\":3650906,\"ttl\":1234567},{\"id\":3650908,\"ttl\":1234567}]}"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/resources/domain-update.json",
    "content": "{\"ttl\":600001,\"emailAddress\":\"everett@jclouds-example.com\",\"comment\":\"Hello Domain Update\"}"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/resources/job.json",
    "content": "{\n  \"status\": \"RUNNING\",\n  \"verb\": \"GET\",\n  \"jobId\": \"bfbd6ec8-5d4c-49f8-97b5-aa5bfd3e95a4\",\n  \"callbackUrl\": \"https://dns.api.rackspacecloud.com/v1.0/123123/status/bfbd6ec8-5d4c-49f8-97b5-aa5bfd3e95a4\",\n  \"requestUrl\": \"https://dns.api.rackspacecloud.com/v1.0/123123/domains/3650883/export\"\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/resources/limit-list.json",
    "content": "{\n    \"limits\": {\n        \"absolute\": {\n            \"records per domain\": 500,\n            \"domains\": 500\n        },\n        \"rate\": [\n            {\n                \"limit\": [\n                    {\n                        \"verb\": \"GET\",\n                        \"value\": 5,\n                        \"remaining\": 5,\n                        \"unit\": \"SECOND\",\n                        \"next-available\": \"2013-03-06T20:11:14.000Z\"\n                    }\n                ],\n                \"uri\": \"*/status/*\",\n                \"regex\": \".*/v\\\\d+\\\\.\\\\d+/(\\\\d+/status).*\"\n            },\n            {\n                \"limit\": [\n                    {\n                        \"verb\": \"GET\",\n                        \"value\": 100,\n                        \"remaining\": 100,\n                        \"unit\": \"MINUTE\",\n                        \"next-available\": \"2013-03-06T20:11:14.000Z\"\n                    },\n                    {\n                        \"verb\": \"POST\",\n                        \"value\": 25,\n                        \"remaining\": 25,\n                        \"unit\": \"MINUTE\",\n                        \"next-available\": \"2013-03-06T20:11:14.000Z\"\n                    },\n                    {\n                        \"verb\": \"PUT\",\n                        \"value\": 50,\n                        \"remaining\": 50,\n                        \"unit\": \"MINUTE\",\n                        \"next-available\": \"2013-03-06T20:11:14.000Z\"\n                    },\n                    {\n                        \"verb\": \"DELETE\",\n                        \"value\": 50,\n                        \"remaining\": 50,\n                        \"unit\": \"MINUTE\",\n                        \"next-available\": \"2013-03-06T20:11:14.000Z\"\n                    }\n                ],\n                \"uri\": \"*/domains*\",\n                \"regex\": \".*/v\\\\d+\\\\.\\\\d+/(\\\\d+/domains).*\"\n            }\n        ]\n    }\n}"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/resources/limit-types-list.json",
    "content": "{\n    \"limitTypes\": [\n        \"RATE_LIMIT\",\n        \"DOMAIN_LIMIT\",\n        \"DOMAIN_RECORD_LIMIT\"\n    ]\n}"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/resources/logback.xml",
    "content": "<?xml version=\"1.0\"?>\n<configuration scan=\"false\">\n    <appender name=\"FILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <appender name=\"WIREFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds-wire.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n    \n    <root>\n        <level value=\"warn\" />\n    </root>\n\n    <logger name=\"org.jclouds\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"FILE\" />\n    </logger>\n\n    <logger name=\"jclouds.wire\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n\n    <logger name=\"jclouds.headers\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n\n</configuration>\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/resources/record-create-response.json",
    "content": "{\n  \"request\": \"{\\\"records\\\":[{\\\"name\\\":\\\"jclouds-example.com\\\",\\\"type\\\":\\\"MX\\\",\\\"data\\\":\\\"mail.jclouds-example.com\\\",\\\"comment\\\":\\\"MX Record\\\",\\\"priority\\\":11235},{\\\"name\\\":\\\"jclouds-example.com\\\",\\\"type\\\":\\\"A\\\",\\\"data\\\":\\\"10.0.0.1\\\"}]}\",\n  \"response\": {\n    \"records\": [\n      {\n        \"name\": \"jclouds-example.com\",\n        \"id\": \"MX-4350353\",\n        \"priority\": 11235,\n        \"type\": \"MX\",\n        \"comment\":\"MX Record\",\n        \"data\": \"mail.jclouds-example.com\",\n        \"ttl\": 60000,\n        \"updated\": \"2013-04-05T19:53:18.000+0000\",\n        \"created\": \"2013-04-05T19:53:18.000+0000\"\n      },\n      {\n        \"name\": \"jclouds-example.com\",\n        \"id\": \"A-9844102\",\n        \"type\": \"A\",\n        \"data\": \"10.0.0.1\",\n        \"ttl\": 60000,\n        \"updated\": \"2013-04-05T19:53:19.000+0000\",\n        \"created\": \"2013-04-05T19:53:19.000+0000\"\n      }\n    ]\n  },\n  \"status\": \"COMPLETED\",\n  \"verb\": \"POST\",\n  \"jobId\": \"290bdc5b-f6fa-4c67-83d7-3b29d2abb8e0\",\n  \"callbackUrl\": \"https://dns.api.rackspacecloud.com/v1.0/123123/status/290bdc5b-f6fa-4c67-83d7-3b29d2abb8e0\",\n  \"requestUrl\": \"https://dns.api.rackspacecloud.com/v1.0/123123/domains/3668461/records\"\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/resources/record-create.json",
    "content": "{\"records\":[{\"name\":\"jclouds-example.com\",\"type\":\"MX\",\"data\":\"mail.jclouds-example.com\",\"comment\":\"MX Record\",\"priority\":11235},{\"name\":\"jclouds-example.com\",\"type\":\"A\",\"data\":\"10.0.0.1\"}]}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/resources/record-delete.json",
    "content": "{\n  \"status\": \"COMPLETED\",\n  \"verb\": \"DELETE\",\n  \"jobId\": \"2a5b0f28-05a1-4003-9cec-470c7602cc02\",\n  \"callbackUrl\": \"https://dns.api.rackspacecloud.com/v1.0/717071/status/2a5b0f28-05a1-4003-9cec-470c7602cc02\",\n  \"requestUrl\": \"https://dns.api.rackspacecloud.com/v1.0/717071/domains/3670431/records/A-9849792\"\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/resources/record-get.json",
    "content": "{\n  \"name\": \"jclouds-example.com\",\n  \"id\": \"A-9846146\",\n  \"type\": \"A\",\n  \"data\": \"10.0.1.0\",\n  \"ttl\": 60000,\n  \"updated\": \"2013-04-06T15:20:29.000+0000\",\n  \"created\": \"2013-04-06T15:20:29.000+0000\"\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/resources/record-list-page1.json",
    "content": "{\n  \"records\": [\n    {\n      \"name\": \"jclouds-example.com\",\n      \"id\": \"A-9846147\",\n      \"type\": \"A\",\n      \"data\": \"10.0.1.0\",\n      \"ttl\": 60000,\n      \"updated\": \"2013-04-06T15:20:29.000+0000\",\n      \"created\": \"2013-04-06T15:20:29.000+0000\"\n    },\n    {\n      \"name\": \"jclouds-example.com\",\n      \"id\": \"NS-8684719\",\n      \"type\": \"NS\",\n      \"data\": \"dns1.stabletransit.com\",\n      \"ttl\": 60000,\n      \"updated\": \"2013-04-06T15:19:20.000+0000\",\n      \"created\": \"2013-04-06T15:19:20.000+0000\"\n    },\n    {\n      \"name\": \"jclouds-example.com\",\n      \"id\": \"NS-8684720\",\n      \"type\": \"NS\",\n      \"data\": \"dns2.stabletransit.com\",\n      \"ttl\": 60000,\n      \"updated\": \"2013-04-06T15:19:20.000+0000\",\n      \"created\": \"2013-04-06T15:19:20.000+0000\"\n    },\n    {\n      \"name\": \"jclouds-example.com\",\n      \"id\": \"MX-4351045\",\n      \"priority\": 11235,\n      \"type\": \"MX\",\n      \"data\": \"mail.jclouds-example.com.com\",\n      \"ttl\": 60000,\n      \"updated\": \"2013-04-06T15:20:28.000+0000\",\n      \"created\": \"2013-04-06T15:20:28.000+0000\"\n    }\n  ],\n  \"totalEntries\": 8, \n  \"links\": [\n  \t{\n  \t  \"href\":\"https://dns.api.rackspacecloud.com/v1.0/123123/domains/3650908/records?limit=4&offset=4\",\n  \t  \"rel\":\"next\"\n  \t}\n  ]\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/resources/record-list-page2.json",
    "content": "{\n  \"records\": [\n    {\n      \"name\": \"jclouds-example.com\",\n      \"id\": \"A-9846146\",\n      \"type\": \"A\",\n      \"data\": \"10.0.1.0\",\n      \"ttl\": 60000,\n      \"updated\": \"2013-04-06T15:20:29.000+0000\",\n      \"created\": \"2013-04-06T15:20:29.000+0000\"\n    },\n    {\n      \"name\": \"jclouds-example.com\",\n      \"id\": \"NS-8684719\",\n      \"type\": \"NS\",\n      \"data\": \"dns1.stabletransit.com\",\n      \"ttl\": 60000,\n      \"updated\": \"2013-04-06T15:19:20.000+0000\",\n      \"created\": \"2013-04-06T15:19:20.000+0000\"\n    },\n    {\n      \"name\": \"jclouds-example.com\",\n      \"id\": \"NS-8684720\",\n      \"type\": \"NS\",\n      \"data\": \"dns2.stabletransit.com\",\n      \"ttl\": 60000,\n      \"updated\": \"2013-04-06T15:19:20.000+0000\",\n      \"created\": \"2013-04-06T15:19:20.000+0000\"\n    },\n    {\n      \"name\": \"jclouds-example.com\",\n      \"id\": \"MX-4351045\",\n      \"priority\": 11235,\n      \"type\": \"MX\",\n      \"data\": \"mail.jclouds-example.com.com\",\n      \"ttl\": 60000,\n      \"updated\": \"2013-04-06T15:20:28.000+0000\",\n      \"created\": \"2013-04-06T15:20:28.000+0000\"\n    }\n  ],\n  \"totalEntries\": 8, \n  \"links\": [\n  \t{\n  \t  \"href\":\"https://dns.api.rackspacecloud.com/v1.0/123123/domains/3650908/records?limit=4&offset=0\",\n  \t  \"rel\":\"previous\"\n  \t}\n  ]\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/resources/record-list-with-filter.json",
    "content": "{\n  \"records\": [\n    {\n      \"name\": \"jclouds-example.com\",\n      \"id\": \"A-9846146\",\n      \"type\": \"A\",\n      \"data\": \"10.0.1.0\",\n      \"ttl\": 60000,\n      \"updated\": \"2013-04-06T15:20:29.000+0000\",\n      \"created\": \"2013-04-06T15:20:29.000+0000\"\n    }\n  ]\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/resources/record-list.json",
    "content": "{\n  \"records\": [\n    {\n      \"name\": \"jclouds-example.com\",\n      \"id\": \"A-9846146\",\n      \"type\": \"A\",\n      \"data\": \"10.0.1.0\",\n      \"ttl\": 60000,\n      \"updated\": \"2013-04-06T15:20:29.000+0000\",\n      \"created\": \"2013-04-06T15:20:29.000+0000\"\n    },\n    {\n      \"name\": \"jclouds-example.com\",\n      \"id\": \"NS-8684719\",\n      \"type\": \"NS\",\n      \"data\": \"dns1.stabletransit.com\",\n      \"ttl\": 60000,\n      \"updated\": \"2013-04-06T15:19:20.000+0000\",\n      \"created\": \"2013-04-06T15:19:20.000+0000\"\n    },\n    {\n      \"name\": \"jclouds-example.com\",\n      \"id\": \"NS-8684720\",\n      \"type\": \"NS\",\n      \"data\": \"dns2.stabletransit.com\",\n      \"ttl\": 60000,\n      \"updated\": \"2013-04-06T15:19:20.000+0000\",\n      \"created\": \"2013-04-06T15:19:20.000+0000\"\n    },\n    {\n      \"name\": \"jclouds-example.com\",\n      \"id\": \"MX-4351045\",\n      \"priority\": 11235,\n      \"type\": \"MX\",\n      \"data\": \"mail.jclouds-example.com.com\",\n      \"ttl\": 60000,\n      \"updated\": \"2013-04-06T15:20:28.000+0000\",\n      \"created\": \"2013-04-06T15:20:28.000+0000\"\n    }\n  ],\n  \"totalEntries\": 4\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/resources/record-ptr-create-response.json",
    "content": "{\n  \"request\": \"{\\\"recordsList\\\":{\\\"records\\\":[{\\\"name\\\":\\\"jclouds-example.com\\\",\\\"type\\\":\\\"PTR\\\",\\\"ttl\\\":11235,\\\"data\\\":\\\"166.78.146.80\\\"},{\\\"name\\\":\\\"jclouds-example.com\\\",\\\"type\\\":\\\"PTR\\\",\\\"data\\\":\\\"2001:4800:7812:0514:9a32:3c2a:ff04:aed2\\\",\\\"comment\\\":\\\"Hello IPv6\\\"}]},\\\"link\\\":{\\\"href\\\":\\\"https://dfw.servers.api.rackspacecloud.com/v2/123123/servers/f5fb9334-b4f0-49d0-a2cc-57a5772dc7d1\\\",\\\"rel\\\":\\\"cloudServersOpenStack\\\"}}\",\n  \"response\": {\n    \"records\": [\n      {\n        \"name\": \"jclouds-example.com\",\n        \"id\": \"PTR-557432\",\n        \"type\": \"PTR\",\n        \"data\": \"166.78.146.80\",\n        \"ttl\": 11235,\n        \"updated\": \"2013-04-11T15:20:23.000+0000\",\n        \"created\": \"2013-04-11T15:20:23.000+0000\"\n      },\n      {\n        \"name\": \"jclouds-example.com\",\n        \"id\": \"PTR-557433\",\n        \"type\": \"PTR\",\n        \"data\": \"2001:4800:7812:514:9a32:3c2a:ff04:aed2\",\n        \"ttl\": 3600,\n        \"comment\": \"Hello IPv6\",\n        \"updated\": \"2013-04-11T15:20:25.000+0000\",\n        \"created\": \"2013-04-11T15:20:25.000+0000\"\n      }\n    ]\n  },\n  \"status\": \"COMPLETED\",\n  \"verb\": \"POST\",\n  \"jobId\": \"0e9aefac-476f-40ba-9626-66dd54c0a5c9\",\n  \"callbackUrl\": \"https://dns.api.rackspacecloud.com/v1.0/123123/status/0e9aefac-476f-40ba-9626-66dd54c0a5c9\",\n  \"requestUrl\": \"https://dns.api.rackspacecloud.com/v1.0/123123/rdns\"\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/resources/record-ptr-create.json",
    "content": "{\"recordsList\":{\"records\":[{\"name\":\"jclouds-example.com\",\"type\":\"PTR\",\"ttl\":11235,\"data\":\"166.78.146.80\"},{\"name\":\"jclouds-example.com\",\"type\":\"PTR\",\"data\":\"2001:4800:7812:0514:9a32:3c2a:ff04:aed2\",\"comment\":\"Hello IPv6\"}]},\"link\":{\"href\":\"https://dfw.servers.api.rackspacecloud.com/v2/123123/servers/f5fb9334-b4f0-49d0-a2cc-57a5772dc7d1\",\"rel\":\"cloudServersOpenStack\"}}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/resources/record-ptr-delete.json",
    "content": "{\n  \"status\": \"COMPLETED\",\n  \"verb\": \"DELETE\",\n  \"jobId\": \"4988d69c-37b5-406c-b82b-58ed099d68cd\",\n  \"callbackUrl\": \"https://dns.api.rackspacecloud.com/v1.0/123123/status/4988d69c-37b5-406c-b82b-58ed099d68cd\",\n  \"requestUrl\": \"https://dns.api.rackspacecloud.com/v1.0/123123/rdns/cloudServersOpenStackhref=https://dfw.servers.api.rackspacecloud.com/v2/123123/servers/f5fb9334-b4f0-49d0-a2cc-57a5772dc7d1&ip=166.78.146.80\"\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/resources/record-ptr-get.json",
    "content": "{\n  \"name\": \"jclouds-example.com\",\n  \"id\": \"PTR-557437\",\n  \"type\": \"PTR\",\n  \"data\": \"166.78.146.80\",\n  \"ttl\": 11235,\n  \"updated\": \"2013-04-11T15:35:34.000+0000\",\n  \"created\": \"2013-04-11T15:35:34.000+0000\"\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/resources/record-ptr-list.json",
    "content": "{\n  \"records\": [\n    {\n      \"name\": \"jclouds-example.com\",\n      \"id\": \"PTR-557437\",\n      \"type\": \"PTR\",\n      \"data\": \"166.78.146.80\",\n      \"ttl\": 11235,\n      \"updated\": \"2013-04-11T15:35:34.000+0000\",\n      \"created\": \"2013-04-11T15:35:34.000+0000\"\n    },\n    {\n      \"name\": \"jclouds-example.com\",\n      \"id\": \"PTR-557438\",\n      \"type\": \"PTR\",\n      \"comment\": \"Hello IPv6\",\n      \"data\": \"2001:4800:7812:514:9a32:3c2a:ff04:aed2\",\n      \"ttl\": 3600,\n      \"updated\": \"2013-04-11T15:35:37.000+0000\",\n      \"created\": \"2013-04-11T15:35:37.000+0000\"\n    }\n  ]\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/resources/record-ptr-update-response.json",
    "content": "{\n  \"request\": \"{\\\"recordsList\\\":{\\\"records\\\":[{\\\"id\\\":\\\"PTR-557437\\\",\\\"name\\\":\\\"jclouds-example.com\\\",\\\"ttl\\\":12358,\\\"data\\\":\\\"166.78.146.80\\\"}]},\\\"link\\\":{\\\"href\\\":\\\"https://dfw.servers.api.rackspacecloud.com/v2/123123/servers/f5fb9334-b4f0-49d0-a2cc-57a5772dc7d1\\\",\\\"rel\\\":\\\"cloudServersOpenStack\\\"}}\",\n  \"status\": \"COMPLETED\",\n  \"verb\": \"PUT\",\n  \"jobId\": \"8e9970a4-365e-4fd9-a243-71c0abcdf18f\",\n  \"callbackUrl\": \"https://dns.api.rackspacecloud.com/v1.0/123123/status/8e9970a4-365e-4fd9-a243-71c0abcdf18f\",\n  \"requestUrl\": \"https://dns.api.rackspacecloud.com/v1.0/123123/rdns\"\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/resources/record-ptr-update.json",
    "content": "{\"recordsList\":{\"records\":[{\"id\":\"PTR-557437\",\"name\":\"jclouds-example.com\",\"ttl\":12358,\"data\":\"166.78.146.80\"}]},\"link\":{\"href\":\"https://dfw.servers.api.rackspacecloud.com/v2/123123/servers/f5fb9334-b4f0-49d0-a2cc-57a5772dc7d1\",\"rel\":\"cloudServersOpenStack\"}}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/resources/record-update-response.json",
    "content": "{\n  \"request\": \"{\\\"name\\\":\\\"_sip._udp.jclouds-example.com\\\",\\\"ttl\\\":86401,\\\"data\\\":\\\"1 3444 sip.jclouds-example.com\\\",\\\"priority\\\":12358,\\\"comment\\\":\\\"Updated Protocol to UDP\\\"}\",\n  \"status\": \"COMPLETED\",\n  \"verb\": \"PUT\",\n  \"jobId\": \"90659522-915d-4b69-a806-0bc464f01cde\",\n  \"callbackUrl\": \"https://dns.api.rackspacecloud.com/v1.0/717071/status/90659522-915d-4b69-a806-0bc464f01cde\",\n  \"requestUrl\": \"https://dns.api.rackspacecloud.com/v1.0/717071/domains/3669444/records/SRV-21839\"\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/resources/record-update.json",
    "content": "{\"name\":\"_sip._udp.jclouds-example.com\",\"ttl\":86401,\"data\":\"1 3444 sip.jclouds-example.com\",\"priority\":12358,\"comment\":\"Updated Protocol to UDP\"}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/resources/records-delete.json",
    "content": "{\n  \"status\": \"COMPLETED\",\n  \"verb\": \"DELETE\",\n  \"jobId\": \"2ad9876f-74f8-4c1c-af9c-1641a72cab75\",\n  \"callbackUrl\": \"https://dns.api.rackspacecloud.com/v1.0/717071/status/2ad9876f-74f8-4c1c-af9c-1641a72cab75\",\n  \"requestUrl\": \"https://dns.api.rackspacecloud.com/v1.0/717071/domains/3670431/records?id=A-9846146&id=MX-9846146\"\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/resources/records-ptr-delete.json",
    "content": "{\n  \"status\": \"COMPLETED\",\n  \"verb\": \"DELETE\",\n  \"jobId\": \"ddeea5c4-cbec-4bc3-b37f-eb4f8c0771cc\",\n  \"callbackUrl\": \"https://dns.api.rackspacecloud.com/v1.0/123123/status/ddeea5c4-cbec-4bc3-b37f-eb4f8c0771cc\",\n  \"requestUrl\": \"https://dns.api.rackspacecloud.com/v1.0/123123/rdns/cloudServersOpenStackhref=https://dfw.servers.api.rackspacecloud.com/v2/123123/servers/f5fb9334-b4f0-49d0-a2cc-57a5772dc7d1\"\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/resources/records-update-response.json",
    "content": "{\n  \"request\": \"{\\\"records\\\":[{\\\"id\\\":\\\"A-9849792\\\",\\\"comment\\\":\\\"Multi-record Update\\\"},{\\\"id\\\":\\\"NS-8687533\\\",\\\"comment\\\":\\\"Multi-record Update\\\"},{\\\"id\\\":\\\"NS-8687534\\\",\\\"comment\\\":\\\"Multi-record Update\\\"},{\\\"id\\\":\\\"MX-4352374\\\",\\\"comment\\\":\\\"Multi-record Update\\\"}]}\",\n  \"status\": \"COMPLETED\",\n  \"verb\": \"PUT\",\n  \"jobId\": \"839768a9-102b-49cc-8227-b9de7485296a\",\n  \"callbackUrl\": \"https://dns.api.rackspacecloud.com/v1.0/717071/status/839768a9-102b-49cc-8227-b9de7485296a\",\n  \"requestUrl\": \"https://dns.api.rackspacecloud.com/v1.0/717071/domains/3670431/records\"\n}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/resources/records-update.json",
    "content": "{\"records\":[{\"id\":\"A-9846146\",\"comment\":\"Multi-record Update\"},{\"id\":\"MX-9846146\",\"comment\":\"Multi-record Update\"}]}\n"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/resources/subdomain-list-page1.json",
    "content": "{\n  \"domains\": [\n    {\n      \"name\": \"1of4.jclouds-example.com\",\n      \"id\": 3728279,\n      \"emailAddress\": \"jclouds@jclouds-example.com\",\n      \"updated\": \"2013-05-23T00:32:21.000+0000\",\n      \"created\": \"2013-05-23T00:32:21.000+0000\"\n    },\n    {\n      \"name\": \"2of4.jclouds-example.com\",\n      \"id\": 3728280,\n      \"emailAddress\": \"jclouds@jclouds-example.com\",\n      \"updated\": \"2013-05-23T00:32:21.000+0000\",\n      \"created\": \"2013-05-23T00:32:21.000+0000\"\n    },\n    {\n      \"name\": \"3of4.jclouds-example.com\",\n      \"id\": 3728281,\n      \"emailAddress\": \"jclouds@jclouds-example.com\",\n      \"updated\": \"2013-05-23T00:32:22.000+0000\",\n      \"created\": \"2013-05-23T00:32:22.000+0000\"\n    },\n    {\n      \"name\": \"4of4.jclouds-example.com\",\n      \"id\": 3728282,\n      \"emailAddress\": \"jclouds@jclouds-example.com\",\n      \"updated\": \"2013-05-23T00:32:22.000+0000\",\n      \"created\": \"2013-05-23T00:32:22.000+0000\"\n    }\n  ],\n  \"totalEntries\": 8, \n  \"links\": [\n  \t{\n  \t  \"href\":\"https://dns.api.rackspacecloud.com/v1.0/123123/domains/3650908/subdomains?limit=4&offset=4\",\n  \t  \"rel\":\"next\"\n  \t}\n  ]\n}"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/resources/subdomain-list-page2.json",
    "content": "{\n  \"domains\": [\n    {\n      \"name\": \"1of4.jclouds-example.com\",\n      \"id\": 3728279,\n      \"emailAddress\": \"jclouds@jclouds-example.com\",\n      \"updated\": \"2013-05-23T00:32:21.000+0000\",\n      \"created\": \"2013-05-23T00:32:21.000+0000\"\n    },\n    {\n      \"name\": \"2of4.jclouds-example.com\",\n      \"id\": 3728280,\n      \"emailAddress\": \"jclouds@jclouds-example.com\",\n      \"updated\": \"2013-05-23T00:32:21.000+0000\",\n      \"created\": \"2013-05-23T00:32:21.000+0000\"\n    },\n    {\n      \"name\": \"3of4.jclouds-example.com\",\n      \"id\": 3728281,\n      \"emailAddress\": \"jclouds@jclouds-example.com\",\n      \"updated\": \"2013-05-23T00:32:22.000+0000\",\n      \"created\": \"2013-05-23T00:32:22.000+0000\"\n    },\n    {\n      \"name\": \"4of4.jclouds-example.com\",\n      \"id\": 3728282,\n      \"emailAddress\": \"jclouds@jclouds-example.com\",\n      \"updated\": \"2013-05-23T00:32:22.000+0000\",\n      \"created\": \"2013-05-23T00:32:22.000+0000\"\n    }\n  ],\n  \"totalEntries\": 8, \n  \"links\": [\n  \t{\n  \t  \"href\":\"https://dns.api.rackspacecloud.com/v1.0/123123/domains/3650908/subdomains?limit=4&offset=0\",\n  \t  \"rel\":\"previous\"\n  \t}\n  ]\n}"
  },
  {
    "path": "apis/rackspace-clouddns/src/test/resources/subdomain-list.json",
    "content": "{\n  \"domains\": [\n    {\n      \"name\": \"1of4.jclouds-example.com\",\n      \"id\": 3728279,\n      \"emailAddress\": \"jclouds@jclouds-example.com\",\n      \"updated\": \"2013-05-23T00:32:21.000+0000\",\n      \"created\": \"2013-05-23T00:32:21.000+0000\"\n    },\n    {\n      \"name\": \"2of4.jclouds-example.com\",\n      \"id\": 3728280,\n      \"emailAddress\": \"jclouds@jclouds-example.com\",\n      \"updated\": \"2013-05-23T00:32:21.000+0000\",\n      \"created\": \"2013-05-23T00:32:21.000+0000\"\n    },\n    {\n      \"name\": \"3of4.jclouds-example.com\",\n      \"id\": 3728281,\n      \"emailAddress\": \"jclouds@jclouds-example.com\",\n      \"updated\": \"2013-05-23T00:32:22.000+0000\",\n      \"created\": \"2013-05-23T00:32:22.000+0000\"\n    },\n    {\n      \"name\": \"4of4.jclouds-example.com\",\n      \"id\": 3728282,\n      \"emailAddress\": \"jclouds@jclouds-example.com\",\n      \"updated\": \"2013-05-23T00:32:22.000+0000\",\n      \"created\": \"2013-05-23T00:32:22.000+0000\"\n    }\n  ],\n  \"totalEntries\": 4\n}"
  },
  {
    "path": "apis/rackspace-cloudfiles/README.md",
    "content": "Rackspace Cloud Files\n==========================\n\nThe new Rackspace Cloud Files multi-region based service API.\n\nThis new \"rackspace-cloudfiles\" API supercedes the jclouds \"cloudfiles\" API, which will eventually be deprecated.\n\nWith this multi-region support, each BlobStore can be isolated to a specific region:\n\n     RegionScopedBlobStoreContext ctx = \n     \tcontextBuilder.buildView(RegionScopedBlobStoreContext.class);\n \n     Set<String> regionIds = ctx.configuredRegions();\n \n     // isolated to a specific region\n     BlobStore dfwBlobStore = ctx.blobStoreInRegion(\"DFW\");\n     BlobStore iadBlobStore = ctx.blobStoreInRegion(\"IAD\");\n\nProduction ready?\nBeta\n\nThis API is new to jclouds and hence is in Beta. That means we need people to use it and give us feedback. Based on that feedback, minor changes to the interfaces may happen. This code will replace org.jclouds.openstack.swift.SwiftClient in jclouds 2.0 and it is recommended you adopt it sooner than later.\n"
  },
  {
    "path": "apis/rackspace-cloudfiles/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.rackspace.cloudfiles.v1.*;version=\"${project.version}\";-noimport:=true"
  },
  {
    "path": "apis/rackspace-cloudfiles/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  \n  <groupId>org.apache.jclouds.api</groupId>\n  <artifactId>rackspace-cloudfiles</artifactId>\n  <version>2.7.1-SNAPSHOT</version>\n  <name>jclouds rackspace-cloudfiles api</name>\n  <description>jclouds components to access Rackspace Cloud Files</description>\n\n  <properties>\n    <!-- identity endpoint -->\n    <test.rackspace-cloudfiles.endpoint>https://identity.api.rackspacecloud.com/v2.0/</test.rackspace-cloudfiles.endpoint>\n    <test.rackspace-cloudfiles.api-version>1</test.rackspace-cloudfiles.api-version>\n    <test.rackspace-cloudfiles.build-version />\n    <test.rackspace-cloudfiles.identity>FIXME_IDENTITY</test.rackspace-cloudfiles.identity>\n    <test.rackspace-cloudfiles.credential>FIXME_CREDENTIALS</test.rackspace-cloudfiles.credential>\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-swift</artifactId>\n      <version>${project.parent.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-swift</artifactId>\n      <version>${project.parent.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-keystone</artifactId>\n      <version>${project.parent.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-keystone</artifactId>\n      <version>${project.parent.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>rackspace-cloudidentity</artifactId>\n      <version>${project.parent.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.parent.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.parent.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-blobstore</artifactId>\n      <version>${project.parent.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.jboss.shrinkwrap</groupId>\n      <artifactId>shrinkwrap-depchain</artifactId>\n      <version>1.2.0</version>\n      <type>pom</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-slf4j</artifactId>\n      <version>${project.parent.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>ch.qos.logback</groupId>\n      <artifactId>logback-classic</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.squareup.okhttp3</groupId>\n      <artifactId>mockwebserver</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <scope>provided</scope>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <jclouds.blobstore.httpstream.url>${jclouds.blobstore.httpstream.url}</jclouds.blobstore.httpstream.url>\n                    <jclouds.blobstore.httpstream.md5>${jclouds.blobstore.httpstream.md5}</jclouds.blobstore.httpstream.md5>\n                    <test.rackspace-cloudfiles.endpoint>${test.rackspace-cloudfiles.endpoint}</test.rackspace-cloudfiles.endpoint>\n                    <test.rackspace-cloudfiles.api-version>${test.rackspace-cloudfiles.api-version}</test.rackspace-cloudfiles.api-version>\n                    <test.rackspace-cloudfiles.build-version>${test.rackspace-cloudfiles.build-version}</test.rackspace-cloudfiles.build-version>\n                    <test.rackspace-cloudfiles.identity>${test.rackspace-cloudfiles.identity}</test.rackspace-cloudfiles.identity>\n                    <test.rackspace-cloudfiles.credential>${test.rackspace-cloudfiles.credential}</test.rackspace-cloudfiles.credential>\n                    <jclouds.blobstore.httpstream.url>${jclouds.blobstore.httpstream.url}</jclouds.blobstore.httpstream.url>\n                    <jclouds.blobstore.httpstream.md5>${jclouds.blobstore.httpstream.md5}</jclouds.blobstore.httpstream.md5>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n"
  },
  {
    "path": "apis/rackspace-cloudfiles/src/main/java/org/jclouds/rackspace/cloudfiles/v1/CloudFilesApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.v1;\n\nimport org.jclouds.openstack.swift.v1.SwiftApi;\nimport org.jclouds.rackspace.cloudfiles.v1.features.CDNApi;\nimport org.jclouds.rackspace.cloudfiles.v1.functions.RegionToCDNEndpoint;\nimport org.jclouds.rest.annotations.Delegate;\nimport org.jclouds.rest.annotations.EndpointParam;\n\nimport com.google.common.annotations.Beta;\n\n/**\n * Rackspace Cloud Files is an affordable, redundant, scalable, and dynamic storage service\n * offering. The core storage system is designed to provide a secure, network-accessible way to\n * store an unlimited number of files. Each file can be as large as 5 gigabytes.\n * <p/>\n * Additionally, Cloud Files provides a simple yet powerful way to publish and distribute content\n * behind a Content Distribution Network.\n *\n * @see CDNApi\n * @see SwiftApi\n */\n@Beta\npublic interface CloudFilesApi extends SwiftApi {\n\n   /**\n    * Provides access to Cloud Files CDN features.\n    *\n    * @param region  the region to access the CDN API.\n    *\n    * @return the {@link CDNApi} for the specified region.\n    */\n   @Delegate\n   CDNApi getCDNApi(@EndpointParam(parser = RegionToCDNEndpoint.class) String region);\n\n}\n"
  },
  {
    "path": "apis/rackspace-cloudfiles/src/main/java/org/jclouds/rackspace/cloudfiles/v1/CloudFilesApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.v1;\n\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.CREDENTIAL_TYPE;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.KEYSTONE_VERSION;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.SERVICE_TYPE;\nimport static org.jclouds.reflect.Reflection2.typeToken;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.openstack.keystone.catalog.config.ServiceCatalogModule;\nimport org.jclouds.openstack.keystone.catalog.config.ServiceCatalogModule.RegionModule;\nimport org.jclouds.openstack.swift.v1.SwiftApiMetadata;\nimport org.jclouds.openstack.swift.v1.blobstore.RegionScopedBlobStoreContext;\nimport org.jclouds.openstack.swift.v1.blobstore.config.SignUsingTemporaryUrls;\nimport org.jclouds.openstack.swift.v1.blobstore.config.SwiftBlobStoreContextModule;\nimport org.jclouds.openstack.swift.v1.config.SwiftTypeAdapters;\nimport org.jclouds.openstack.v2_0.ServiceType;\nimport org.jclouds.rackspace.cloudfiles.v1.config.CloudFilesHttpApiModule;\nimport org.jclouds.rackspace.cloudidentity.v2_0.config.CloudIdentityAuthenticationModule;\nimport org.jclouds.rackspace.cloudidentity.v2_0.config.CloudIdentityCredentialTypes;\nimport org.jclouds.rest.internal.BaseHttpApiMetadata;\n\nimport com.google.auto.service.AutoService;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n/**\n * Implementation of {@link ApiMetadata} for Cloud Files.\n */\n@AutoService(ApiMetadata.class)\npublic class CloudFilesApiMetadata extends BaseHttpApiMetadata<CloudFilesApi> {\n\n   @Override\n   public Builder toBuilder() {\n      return new Builder().fromApiMetadata(this);\n   }\n\n   public CloudFilesApiMetadata() {\n      this(new Builder());\n   }\n\n   protected CloudFilesApiMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = SwiftApiMetadata.defaultProperties();\n      properties.setProperty(CREDENTIAL_TYPE, CloudIdentityCredentialTypes.API_KEY_CREDENTIALS);\n      properties.setProperty(KEYSTONE_VERSION, \"2\");\n      properties.setProperty(SERVICE_TYPE, ServiceType.OBJECT_STORE);\n      return properties;\n   }\n\n   public static class Builder extends BaseHttpApiMetadata.Builder<CloudFilesApi, Builder> {\n\n      protected Builder() {\n          id(\"rackspace-cloudfiles\")\n         .name(\"Rackspace Cloud Files API\")\n         .identityName(\"${userName}\")\n         .credentialName(\"${apiKey}\")\n         .documentation(URI.create(\"http://docs.rackspace.com/files/api/v1/cf-devguide/content/index.html\"))\n         .version(\"1.0\")\n         .endpointName(\"Rackspace Cloud Identity service URL ending in /v2.0/\")\n         .defaultEndpoint(\"https://identity.api.rackspacecloud.com/v2.0/\")\n         .defaultProperties(CloudFilesApiMetadata.defaultProperties())\n         .view(typeToken(RegionScopedBlobStoreContext.class))\n         .defaultModules(ImmutableSet.<Class<? extends Module>>builder()\n                                     .add(CloudIdentityAuthenticationModule.class)\n                                     .add(ServiceCatalogModule.class)\n                                     .add(RegionModule.class)\n                                     .add(SwiftTypeAdapters.class)\n                                     .add(CloudFilesHttpApiModule.class)\n                                     .add(SwiftBlobStoreContextModule.class)\n                                     .add(SignUsingTemporaryUrls.class)\n                                     .build());\n      }\n\n      @Override\n      public CloudFilesApiMetadata build() {\n         return new CloudFilesApiMetadata(this);\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudfiles/src/main/java/org/jclouds/rackspace/cloudfiles/v1/binders/BindCDNPurgeEmailAddressesToHeaders.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.v1.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.List;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rackspace.cloudfiles.v1.reference.CloudFilesHeaders;\nimport org.jclouds.rest.Binder;\n\nimport com.google.common.base.Joiner;\nimport com.google.common.collect.ImmutableMultimap;\n\n/**\n * Binds a list of email addresses to request headers. \n * \n * @see {@link CDNApi#purgeObject(String, String, Iterable)}\n */\n@Singleton\npublic class BindCDNPurgeEmailAddressesToHeaders implements Binder {\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkArgument(checkNotNull(input, \"input\") instanceof Iterable<?>, \"this binder is only valid for Iterable!\");\n      checkNotNull(request, \"request\");\n\n      Iterable<String> emails = (Iterable<String>) input;\n      String emailCSV = Joiner.on(\", \").join((List<String>) emails);\n      ImmutableMultimap<String, String> headers = \n            ImmutableMultimap.<String, String> of(CloudFilesHeaders.CDN_PURGE_OBJECT_EMAIL, emailCSV);\n      \n      return (R) request.toBuilder().replaceHeaders(headers).build();\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudfiles/src/main/java/org/jclouds/rackspace/cloudfiles/v1/config/CloudFilesHttpApiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.v1.config;\n\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.annotation.ClientError;\nimport org.jclouds.http.annotation.Redirection;\nimport org.jclouds.http.annotation.ServerError;\nimport org.jclouds.openstack.swift.v1.SwiftApi;\nimport org.jclouds.openstack.swift.v1.config.BaseSwiftHttpApiModule;\nimport org.jclouds.rackspace.cloudfiles.v1.CloudFilesApi;\nimport org.jclouds.rackspace.cloudfiles.v1.handlers.CloudFilesErrorHandler;\nimport org.jclouds.rest.ConfiguresHttpApi;\n\nimport com.google.inject.Scopes;\n\n@ConfiguresHttpApi\npublic class CloudFilesHttpApiModule extends BaseSwiftHttpApiModule<CloudFilesApi> {\n\n   public CloudFilesHttpApiModule() {\n      super(CloudFilesApi.class);\n   }\n\n   @Override\n   protected void configure() {\n      super.configure();\n      bind(SwiftApi.class).to(CloudFilesApi.class).in(Scopes.SINGLETON);\n   }\n   \n   @Override\n   protected void bindErrorHandlers() {\n      bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(CloudFilesErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(CloudFilesErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(CloudFilesErrorHandler.class);\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudfiles/src/main/java/org/jclouds/rackspace/cloudfiles/v1/domain/CDNContainer.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.v1.domain;\n\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.net.URI;\n\nimport jakarta.inject.Named;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Represents a CDN Container in Rackspace Cloud Files.\n */\npublic class CDNContainer implements Comparable<CDNContainer> {\n\n   private String name;\n   @Named(\"cdn_enabled\")\n   private boolean enabled;\n   @Named(\"log_retention\")\n   private boolean logRetention;\n   private int ttl;\n   @Named(\"cdn_uri\")\n   private URI uri;\n   @Named(\"cdn_ssl_uri\")\n   private URI sslUri;\n   @Named(\"cdn_streaming_uri\")\n   private URI streamingUri;\n   @Named(\"cdn_ios_uri\")\n   private URI iosUri;\n\n   @ConstructorProperties({ \"name\", \"cdn_enabled\", \"log_retention\", \"ttl\", \"cdn_uri\", \"cdn_ssl_uri\", \"cdn_streaming_uri\", \"cdn_ios_uri\"})\n   public CDNContainer(String name, boolean enabled, boolean logRetention, int ttl, URI uri, URI sslUri, URI streamingUri, URI iosUri) {\n      this.name = checkNotNull(name, \"name required\");\n      this.enabled = enabled;\n      this.logRetention = logRetention;\n      this.ttl = ttl;\n      this.uri = checkNotNull(uri, \"uri required\");\n      this.sslUri = checkNotNull(sslUri, \"sslUri required\");\n      this.streamingUri = checkNotNull(streamingUri, \"streamingUri required\");\n      this.iosUri = checkNotNull(iosUri, \"iosUri required\");\n   }\n\n   /**\n    * <h3>NOTE</h3>\n    * The container name is not available from HEAD CDN responses and will be null.\n    *\n    * @return The name of this CDN container.\n    */\n   public String getName() {\n      return name;\n   }\n\n   /**\n    * @return {@code true} if the container is CDN enabled, {@code false} if not.\n    */\n   public boolean isEnabled() {\n      return enabled;\n   }\n\n   /**\n    * @return {@code true} if the logs will be retained for this CDN container, {@code false} if not.\n    */\n   public boolean isLogRetentionEnabled() {\n      return logRetention;\n   }\n\n   /**\n    * @return the TTL for this CDN container.\n    */\n   public int getTtl() {\n      return ttl;\n   }\n\n   /**\n    * @return the {@link URI} for this CDN container.\n    */\n   public URI getUri() {\n      return uri;\n   }\n\n   /**\n    * @return the SSL {@link URI} for this CDN container.\n    */\n   public URI getSslUri() {\n      return sslUri;\n   }\n\n   /**\n    * @return the streaming {@link URI} for this CDN container.\n    */\n   public URI getStreamingUri() {\n      return streamingUri;\n   }\n\n   /**\n    * @return the iOS {@link URI} for this CDN container.\n    */\n   public URI getIosUri() {\n      return iosUri;\n   }\n   \n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      CDNContainer that = CDNContainer.class.cast(obj);\n      return Objects.equal(this.name, that.name)\n               && Objects.equal(this.enabled, that.enabled)\n               && Objects.equal(this.logRetention, that.logRetention)\n               && Objects.equal(this.ttl, that.ttl)\n               && Objects.equal(this.uri, that.uri)\n               && Objects.equal(this.sslUri, that.sslUri)\n               && Objects.equal(this.streamingUri, that.streamingUri)\n               && Objects.equal(this.iosUri, that.iosUri);\n   }\n   \n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(getName(), isEnabled(), isLogRetentionEnabled(), getTtl(), getUri(), getSslUri(), getStreamingUri(), getIosUri());\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   protected ToStringHelper string() {\n      return toStringHelper(\"\").omitNullValues()\n            .add(\"name\", getName())\n            .add(\"enabled\", isEnabled())\n            .add(\"logRetention\", isLogRetentionEnabled())\n            .add(\"ttl\", getTtl())\n            .add(\"uri\", getUri())\n            .add(\"sslUri\", getSslUri())\n            .add(\"streamingUri\", getStreamingUri())\n            .add(\"iosUri\", getIosUri());\n   }\n\n   @Override\n   public int compareTo(CDNContainer that) {\n      if (that == null)\n         return 1;\n      if (this == that)\n         return 0;\n      return this.getName().compareTo(that.getName());\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n      \n      private String name;\n      private boolean enabled;\n      private boolean logRetention;\n      private int ttl;\n      private URI uri;\n      private URI sslUri;\n      private URI streamingUri;\n      private URI iosUri;\n      \n      /**\n       * @see CDNContainer#getName()\n       */\n      public Builder name(String name) {\n         this.name = checkNotNull(name, \"name\");\n         return this;\n      }\n\n      /**\n       * @see CDNContainer#isEnabled()\n       */\n      public Builder enabled(boolean enabled) {\n         this.enabled = enabled;\n         return this;\n      }\n\n      /**\n       * @see CDNContainer#isLogRetentionEnabled()\n       */\n      public Builder logRetention(boolean logRetention) {\n         this.logRetention = logRetention;\n         return this;\n      }\n\n      /**\n       * @see CDNContainer#getTtl()\n       */\n      public Builder ttl(int ttl) {\n         this.ttl = ttl;\n         return this;\n      }\n\n      /**\n       * @see CDNContainer#getUri()\n       */\n      public Builder uri(URI uri) {\n         this.uri = uri;\n         return this;\n      }\n\n      /**\n       * @see CDNContainer#getSslUri()\n       */\n      public Builder sslUri(URI sslUri) {\n         this.sslUri = sslUri;\n         return this;\n      }\n\n      /**\n       * @see CDNContainer#getStreamingUri()\n       */\n      public Builder streamingUri(URI streamingUri) {\n         this.streamingUri = streamingUri;\n         return this;\n      }\n\n      /**\n       * @see CDNContainer#getIosUri()\n       */\n      public Builder iosUri(URI iosUri) {\n         this.iosUri = iosUri;\n         return this;\n      }\n\n      public CDNContainer build() {\n         return new CDNContainer(name, enabled, logRetention, ttl, uri, sslUri, streamingUri, iosUri);\n      }\n\n      public Builder fromContainer(CDNContainer from) {\n         return name(from.getName())\n               .enabled(from.isEnabled())\n               .logRetention(from.isLogRetentionEnabled())\n               .ttl(from.getTtl())\n               .uri(from.getUri())\n               .sslUri(from.getSslUri())\n               .streamingUri(from.getStreamingUri())\n               .iosUri(from.getIosUri());\n      }\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudfiles/src/main/java/org/jclouds/rackspace/cloudfiles/v1/features/CDNApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.v1.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\nimport static org.jclouds.rackspace.cloudfiles.v1.reference.CloudFilesHeaders.CDN_ENABLED;\nimport static org.jclouds.rackspace.cloudfiles.v1.reference.CloudFilesHeaders.CDN_TTL;\n\nimport java.io.Closeable;\nimport java.net.URI;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.HEAD;\nimport jakarta.ws.rs.HeaderParam;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\n\nimport org.jclouds.Fallbacks.EmptyFluentIterableOnNotFoundOr404;\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.rackspace.cloudfiles.v1.binders.BindCDNPurgeEmailAddressesToHeaders;\nimport org.jclouds.rackspace.cloudfiles.v1.domain.CDNContainer;\nimport org.jclouds.rackspace.cloudfiles.v1.functions.ParseCDNContainerFromHeaders;\nimport org.jclouds.rackspace.cloudfiles.v1.functions.ParseCDNContainerURIFromHeaders;\nimport org.jclouds.rackspace.cloudfiles.v1.options.ListCDNContainerOptions;\nimport org.jclouds.rackspace.cloudfiles.v1.options.UpdateCDNContainerOptions;\nimport org.jclouds.rackspace.cloudfiles.v1.reference.CloudFilesHeaders;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.Headers;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.collect.FluentIterable;\n/**\n * Provides access to the Rackspace Cloud Files CDN API features.\n *\n * <h3>NOTE</h3>\n * Before a container can be CDN enabled, it must exist in the storage system.\n * To CDN enable the container, perform PUT request against it using the <code>publicURL</code>\n * noted in the service catalog for Cloud Files during Authentication and set the\n * <code>X-CDN-Enabled</code> header to <code>true</code>.\n *\n * @see {@link org.jclouds.rackspace.cloudfiles.v1.CloudFilesApi#getCDNApi(String)}\n */\n@Beta\n@RequestFilters(AuthenticateRequest.class)\n@Consumes(APPLICATION_JSON)\npublic interface CDNApi extends Closeable {\n\n   /**\n    * Lists up to 10,000 CDN containers.\n    *\n    * @return a list of CDN enabled containers ordered by name.\n    */\n   @Named(\"cdn:list\")\n   @GET\n   @QueryParams(keys = {\"format\", \"enabled_only\"}, values = {\"json\", \"true\"})\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   @Path(\"/\")\n   FluentIterable<CDNContainer> list();\n\n   /**\n    * Lists CDN containers, with the given options.\n    *\n    * @param options\n    *           the options to control output.\n    *\n    * @return a list of CDN enabled containers ordered by name.\n    */\n   @Named(\"cdn:list\")\n   @GET\n   @QueryParams(keys = {\"format\", \"enabled_only\"}, values = {\"json\", \"true\"})\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   @Path(\"/\")\n   FluentIterable<CDNContainer> list(ListCDNContainerOptions options);\n\n   /**\n    * Gets the specified CDN Container.\n    *\n    * @param containerName\n    *           the name of the CDN Container\n    *\n    * @return the CDNContainer or null, if not found.\n    */\n   @Named(\"cdn:get\")\n   @HEAD\n   @ResponseParser(ParseCDNContainerFromHeaders.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   @Path(\"/{container}\")\n   @Nullable\n   CDNContainer get(@PathParam(\"container\") String containerName);\n\n   /**\n    * Enables the {@link CDNContainer}.\n    *\n    * @param containerName\n    *           corresponds to {@link CDNContainer#getName()}.\n    *\n    * @return the CDN container {@link URI} or {@code null}, if not found.\n    */\n   @Named(\"cdn:enable\")\n   @PUT\n   @ResponseParser(ParseCDNContainerURIFromHeaders.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   @Path(\"/{containerName}\")\n   @Headers(keys = CDN_ENABLED, values = \"true\")\n   @Nullable\n   URI enable(@PathParam(\"containerName\") String containerName);\n\n   /**\n    * Enables the {@link CDNContainer} with a TTL.\n    *\n    * @param containerName\n    *           corresponds to {@link CDNContainer#getName()}.\n    * @param ttl\n    *           the TTL for the CDN Container.\n    *\n    * @return the CDN container {@link URI} or {@code null}, if not found.\n    */\n   @Named(\"cdn:enable\")\n   @PUT\n   @ResponseParser(ParseCDNContainerURIFromHeaders.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   @Path(\"/{containerName}\")\n   @Headers(keys = CDN_ENABLED, values = \"true\")\n   @Nullable\n   URI enable(@PathParam(\"containerName\") String containerName,\n         @HeaderParam(CDN_TTL) int ttl);\n\n   /**\n    * Disables the {@link CDNContainer}.\n    *\n    * @param containerName\n    *           corresponds to {@link CDNContainer#getName()}.\n    *\n    * @return {@code true} if the container was disabled, {@code false} if not.\n    */\n   @Named(\"cdn:disable\")\n   @PUT\n   @Fallback(FalseOnNotFoundOr404.class)\n   @Path(\"/{containerName}\")\n   @Headers(keys = CDN_ENABLED, values = \"False\")\n   boolean disable(@PathParam(\"containerName\") String containerName);\n\n   /**\n    * Purges an object from the CDN.\n    *\n    * @param containerName\n    *           corresponds to {@link CDNContainer#getName()}.\n    * @param objectName\n    *           the object in the {@link CDNContainer} to purge.\n    * @param emails\n    *           the email addresses to notify after purging.\n    *\n    * @return {@code true} if the object was successfully purged, {@code false} if not.\n    */\n   @Named(\"cdn:purge\")\n   @DELETE\n   @Fallback(FalseOnNotFoundOr404.class)\n   @Path(\"/{containerName}/{objectName}\")\n   @Headers(keys = CloudFilesHeaders.CDN_PURGE_OBJECT_EMAIL, values = \"{email}\")\n   boolean purgeObject(@PathParam(\"containerName\") String containerName,\n         @PathParam(\"objectName\") String objectName,\n         @BinderParam(BindCDNPurgeEmailAddressesToHeaders.class) Iterable<String> emails);\n\n   /**\n    * Updates a CDN container with the supplied {@link UpdateCDNContainerOptions} options.\n    *\n    * @param containerName\n    *           corresponds to {@link CDNContainer#getName()}.\n    *\n    * @param options\n    *           the {@link UpdateCDNContainerOptions} options.\n    */\n   @Named(\"cdn:update\")\n   @POST\n   @Fallback(FalseOnNotFoundOr404.class)\n   @Path(\"/{containerName}\")\n   boolean update(@PathParam(\"containerName\") String containerName, UpdateCDNContainerOptions options);\n}\n"
  },
  {
    "path": "apis/rackspace-cloudfiles/src/main/java/org/jclouds/rackspace/cloudfiles/v1/functions/ParseCDNContainerFromHeaders.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.v1.functions;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Lists.newArrayList;\nimport static org.jclouds.rackspace.cloudfiles.v1.reference.CloudFilesHeaders.CDN_ENABLED;\nimport static org.jclouds.rackspace.cloudfiles.v1.reference.CloudFilesHeaders.CDN_IOS_URI;\nimport static org.jclouds.rackspace.cloudfiles.v1.reference.CloudFilesHeaders.CDN_LOG_RETENTION;\nimport static org.jclouds.rackspace.cloudfiles.v1.reference.CloudFilesHeaders.CDN_SSL_URI;\nimport static org.jclouds.rackspace.cloudfiles.v1.reference.CloudFilesHeaders.CDN_STREAMING_URI;\nimport static org.jclouds.rackspace.cloudfiles.v1.reference.CloudFilesHeaders.CDN_TTL;\nimport static org.jclouds.rackspace.cloudfiles.v1.reference.CloudFilesHeaders.CDN_URI;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rackspace.cloudfiles.v1.domain.CDNContainer;\nimport org.jclouds.rest.InvocationContext;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Splitter;\n\n/**\n * Parses the {@link CDNContainer} from the response headers.\n */\npublic class ParseCDNContainerFromHeaders implements Function<HttpResponse, CDNContainer>,\n      InvocationContext<ParseCDNContainerFromHeaders> {\n\n   private HttpRequest request;\n\n   /**\n    * parses the http response headers to create a new {@link CDNContainer} object.\n    */\n   public CDNContainer apply(final HttpResponse from) {\n      String uri = checkNotNull(from.getFirstHeaderOrNull(CDN_URI), CDN_URI);\n      String sslUri = checkNotNull(from.getFirstHeaderOrNull(CDN_SSL_URI), CDN_SSL_URI);\n      String streamingUri = checkNotNull(from.getFirstHeaderOrNull(CDN_STREAMING_URI), CDN_STREAMING_URI);\n      String iosUri = checkNotNull(from.getFirstHeaderOrNull(CDN_IOS_URI), CDN_IOS_URI);\n      String enabled = checkNotNull(from.getFirstHeaderOrNull(CDN_ENABLED), CDN_ENABLED);\n      String logRetention = checkNotNull(from.getFirstHeaderOrNull(CDN_LOG_RETENTION), CDN_LOG_RETENTION);\n      String ttl = checkNotNull(from.getFirstHeaderOrNull(CDN_TTL), CDN_TTL);\n\n      // just need the name from the path\n      List<String> parts = newArrayList(Splitter.on('/').split(request.getEndpoint().getPath()));\n      checkArgument(!parts.isEmpty());\n\n      return CDNContainer.builder().name(parts.get(parts.size() - 1))\n            .enabled(Boolean.parseBoolean(enabled))\n            .logRetention(Boolean.parseBoolean(logRetention))\n            .ttl(Integer.parseInt(ttl))\n            .uri(URI.create(uri))\n            .sslUri(URI.create(sslUri))\n            .streamingUri(URI.create(streamingUri))\n            .iosUri(URI.create(iosUri))\n            .build();\n   }\n\n   @Override\n   public ParseCDNContainerFromHeaders setContext(HttpRequest request) {\n      this.request = request;\n      return this;\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudfiles/src/main/java/org/jclouds/rackspace/cloudfiles/v1/functions/ParseCDNContainerURIFromHeaders.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.v1.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.net.URI;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rackspace.cloudfiles.v1.reference.CloudFilesHeaders;\n\nimport com.google.common.base.Function;\n\n/**\n * Parses the {@link CDNContainer} from the response headers.\n */\npublic class ParseCDNContainerURIFromHeaders implements Function<HttpResponse, URI> {\n\n   /**\n    * parses the http response headers to provide the CDN URI string.\n    */\n   public URI apply(final HttpResponse from) {\n      String cdnUri = checkNotNull(from.getFirstHeaderOrNull(CloudFilesHeaders.CDN_URI),\n               CloudFilesHeaders.CDN_URI);\n      return URI.create(cdnUri);\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudfiles/src/main/java/org/jclouds/rackspace/cloudfiles/v1/functions/RegionToCDNEndpoint.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.v1.functions;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkState;\n\nimport java.net.URI;\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.location.suppliers.RegionIdToURISupplier;\nimport org.jclouds.rackspace.cloudidentity.v2_0.ServiceType;\nimport org.jclouds.rest.annotations.ApiVersion;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\n\n/**\n * This class ensures that the correct Cloud Files CDN endpoint is retrieved from the endpoint\n * supplier. The CDN API should never be instantiated directly, but rather accessed through the\n * {@link CloudFilesApi#cdnApiInRegion(String)} API.\n * <p/>\n * <h3>NOTE</h3>\n * The Cloud Files Service Type will always default to OpenStack Object Storage (\"object-storage\").\n * <p/>\n *\n *\n * @see CloudFilesApi#cdnApiInRegion(String)\n * @see CDNApi\n * @see RegionToEndpoint\n * @see org.jclouds.openstack.v2_0.ServiceType#OBJECT_STORE\n * @see org.jclouds.rackspace.cloudidentity.v2_0.ServiceType#OBJECT_CDN\n * @see <a\n *      href=\"http://docs.rackspace.com/files/api/v1/cf-devguide/content/Service-Access-Endpoints-d1e003.html\">\n *      Service Access Endpoints</a>\n */\n@Singleton\npublic class RegionToCDNEndpoint implements Function<Object, URI> {\n\n   private final Supplier<Map<String, Supplier<URI>>> endpointsSupplier;\n\n   @Inject\n   public RegionToCDNEndpoint(@ApiVersion final String apiVersion, final RegionIdToURISupplier.Factory factory) {\n      this.endpointsSupplier = factory.createForApiTypeAndVersion(ServiceType.OBJECT_CDN, apiVersion);\n   }\n\n   public URI apply(@Nullable Object from) {\n      checkArgument(from != null && from instanceof String, \"you must specify a region, as a String argument\");\n      Map<String, Supplier<URI>> regionToEndpoint = endpointsSupplier.get();\n      checkState(!regionToEndpoint.isEmpty(), \"no region name to endpoint mappings configured!\");\n      checkArgument(regionToEndpoint.containsKey(from),\n            \"requested location %s, which is not in the configured locations: %s\", from, regionToEndpoint);\n      return regionToEndpoint.get(from).get();\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudfiles/src/main/java/org/jclouds/rackspace/cloudfiles/v1/handlers/CloudFilesErrorHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.v1.handlers;\n\nimport static org.jclouds.http.HttpUtils.closeClientButKeepContentStream;\n\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport org.jclouds.blobstore.ContainerNotFoundException;\nimport org.jclouds.blobstore.KeyNotFoundException;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.openstack.swift.v1.reference.SwiftHeaders;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.InsufficientResourcesException;\n\n// TODO: is there error spec someplace? let's type errors, etc.\npublic class CloudFilesErrorHandler implements HttpErrorHandler {\n   public static final String PREFIX = \"^/v[0-9][^/]*/[a-zA-Z]+_[^/]+/\";\n   public static final Pattern CONTAINER_PATH = Pattern.compile(PREFIX + \"([^/]+)$\");\n   public static final Pattern CONTAINER_KEY_PATH = Pattern.compile(PREFIX + \"([^/]+)/(.*)\");\n\n   public void handleError(HttpCommand command, HttpResponse response) {\n      // it is important to always read fully and close streams\n      byte[] data = closeClientButKeepContentStream(response);\n      String message = data != null ? new String(data) : null;\n\n      Exception exception = message != null ? new HttpResponseException(command, response, message)\n               : new HttpResponseException(command, response);\n      message = message != null ? message : String.format(\"%s -> %s\", command.getCurrentRequest().getRequestLine(),\n               response.getStatusLine());\n      switch (response.getStatusCode()) {\n         case 401:\n            exception = new AuthorizationException(exception.getMessage(), exception);\n            break;\n         case 404:\n            Exception oldException = exception;\n            String sourcePath = command.getCurrentRequest().getFirstHeaderOrNull(SwiftHeaders.OBJECT_COPY_FROM);\n            if (sourcePath != null) {\n               exception = new KeyNotFoundException(oldException);\n            } else if (!command.getCurrentRequest().getMethod().equals(\"DELETE\")) {\n               String path = command.getCurrentRequest().getEndpoint().getPath();\n               Matcher matcher = CONTAINER_PATH.matcher(path);\n\n               if (matcher.find()) {\n                  exception = new ContainerNotFoundException(matcher.group(1), message);\n                  exception.initCause(oldException);\n               } else {\n                  matcher = CONTAINER_KEY_PATH.matcher(path);\n                  if (matcher.find()) {\n                     exception = new KeyNotFoundException(matcher.group(1), matcher.group(2), message);\n                     exception.initCause(oldException);\n                  }\n               }\n            }\n            break;\n         case 409:\n            exception = new IllegalStateException(exception.getMessage(), exception);\n            break;\n         case 413:\n            exception = new InsufficientResourcesException(exception.getMessage(), exception);\n            break;\n      }\n      command.setException(exception);\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudfiles/src/main/java/org/jclouds/rackspace/cloudfiles/v1/options/ListCDNContainerOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.v1.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\n/**\n * Options for listing containers. \n * \n * @see {@link org.jclouds.rackspace.cloudfiles.v1.features.CDNAp#list(ListCDNContainerOptions) CDNApi.list(ListCDNContainerOptions)}\n */\npublic class ListCDNContainerOptions extends BaseHttpRequestOptions {\n\n   /** \n    * For an integer value <i>n</i>, limits the number of results to <i>n</n>. \n    */\n   public ListCDNContainerOptions limit(int limit) {\n      checkState(limit >= 0, \"limit must be >= 0\");\n      checkState(limit <= 10000, \"limit must be <= 10000\");\n      queryParameters.put(\"limit\", Integer.toString(limit));\n      return this;\n   }\n\n   /** \n    * Given a string value <i>x</i>, returns container names greater in value than the specified\n    * {@code marker}. Only strings using UTF-8 encoding are valid. Using {@code marker} provides\n    * a mechanism for iterating through the entire list of containers.\n    */\n   public ListCDNContainerOptions marker(String marker) {\n      queryParameters.put(\"marker\", checkNotNull(marker, \"marker\"));\n      return this;\n   }\n\n   /** \n    * Given a string value <i>x</i>, returns container names lesser in value than the specified \n    * end marker. Only strings using UTF-8 encoding are valid.\n    */\n   public ListCDNContainerOptions endMarker(String endMarker) {\n      queryParameters.put(\"end_marker\", checkNotNull(endMarker, \"endMarker\"));\n      return this;\n   }\n\n   public static class Builder {\n\n      /** \n       * @see ListCDNContainerOptions#limit\n       */\n      public static ListCDNContainerOptions limit(int limit) {\n         ListCDNContainerOptions options = new ListCDNContainerOptions();\n         return options.limit(limit);\n      }\n\n      /** \n       * @see ListCDNContainerOptions#marker\n       */\n      public static ListCDNContainerOptions marker(String marker) {\n         ListCDNContainerOptions options = new ListCDNContainerOptions();\n         return options.marker(marker);\n      }\n\n      /** \n       * @see ListCDNContainerOptions#endMarker\n       */\n      public static ListCDNContainerOptions endMarker(String endMarker) {\n         ListCDNContainerOptions options = new ListCDNContainerOptions();\n         return options.endMarker(endMarker);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudfiles/src/main/java/org/jclouds/rackspace/cloudfiles/v1/options/UpdateCDNContainerOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.v1.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.STATIC_WEB_DIRECTORY_TYPE;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.STATIC_WEB_ERROR;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.STATIC_WEB_INDEX;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.STATIC_WEB_LISTINGS;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.STATIC_WEB_LISTINGS_CSS;\nimport static org.jclouds.rackspace.cloudfiles.v1.reference.CloudFilesConstants.CDN_TTL_MAX;\nimport static org.jclouds.rackspace.cloudfiles.v1.reference.CloudFilesConstants.CDN_TTL_MIN;\nimport static org.jclouds.rackspace.cloudfiles.v1.reference.CloudFilesHeaders.CDN_ENABLED;\nimport static org.jclouds.rackspace.cloudfiles.v1.reference.CloudFilesHeaders.CDN_LOG_RETENTION;\nimport static org.jclouds.rackspace.cloudfiles.v1.reference.CloudFilesHeaders.CDN_TTL;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.net.MediaType;\n\n/**\n * Options supported for updating CDN containers.\n */\npublic class UpdateCDNContainerOptions extends BaseHttpRequestOptions {\n   public static final UpdateCDNContainerOptions NONE = new UpdateCDNContainerOptions();\n\n   /** \n    * Updates TTL\n    */\n   public UpdateCDNContainerOptions ttl(int ttl) {\n      checkState(ttl >= Integer.valueOf(CDN_TTL_MIN), \"ttl must be >= \" + CDN_TTL_MIN);\n      checkState(ttl <= Integer.valueOf(CDN_TTL_MAX), \"ttl must be <= \" + CDN_TTL_MAX);\n      headers.put(CDN_TTL, Integer.toString(ttl));\n      return this;\n   }\n\n   /** \n    * Enables or disables log retention\n    */\n   public UpdateCDNContainerOptions logRetention(boolean logRetention) {\n      headers.put(CDN_LOG_RETENTION, Boolean.toString(logRetention));\n      return this;\n   }\n\n   /** \n    * Enables or disables the CDN Container\n    */\n   public UpdateCDNContainerOptions enabled(boolean enabled) {\n      headers.put(CDN_ENABLED, Boolean.toString(enabled));\n      return this;\n   }\n\n   /**\n    * Sets the directory marker type for the Static Website.\n    */\n   public UpdateCDNContainerOptions staticWebsiteDirectoryType(MediaType directoryType) {\n      checkNotNull(directoryType, \"directoryType cannot be null\");\n      headers.put(STATIC_WEB_DIRECTORY_TYPE, directoryType.toString());\n      return this;\n   }\n\n   /**\n    * Sets the error page for the Static Website.\n    */\n   public UpdateCDNContainerOptions staticWebsiteErrorPage(String errorPage) {\n      checkNotNull(errorPage, \"error page cannot be null\");\n      headers.put(STATIC_WEB_ERROR, errorPage);\n      return this;\n   }\n\n   /**\n    * Sets the index page for the Static Website.\n    */\n   public UpdateCDNContainerOptions staticWebsiteIndexPage(String indexPage) {\n      checkNotNull(indexPage, \"index page cannot be null\");\n      headers.put(STATIC_WEB_INDEX, indexPage);\n      return this;\n   }\n\n   /**\n    * Enables or disables listings for the Static Website.\n    */\n   public UpdateCDNContainerOptions staticWebsiteListings(boolean listings) {\n      headers.put(STATIC_WEB_LISTINGS, Boolean.toString(listings));\n      return this;\n   }\n\n   /**\n    * Sets the listings CSS page for the Static Website.\n    */\n   public UpdateCDNContainerOptions staticWebsiteListingsCSS(String listingsCSS) {\n      checkNotNull(listingsCSS, \"listingsCSS page cannot be null\");\n      headers.put(STATIC_WEB_LISTINGS_CSS, listingsCSS);\n      return this;\n   }\n\n   public static class Builder {\n      /**\n       * @see UpdateCDNContainerOptions#ttl\n       */\n      public static UpdateCDNContainerOptions ttl(int ttl) {\n         UpdateCDNContainerOptions options = new UpdateCDNContainerOptions();\n         return options.ttl(ttl);\n      }\n\n      /**\n       * @see UpdateCDNContainerOptions#logRetention\n       */\n      public static UpdateCDNContainerOptions logRetention(boolean logRetention) {\n         UpdateCDNContainerOptions options = new UpdateCDNContainerOptions();\n         return options.logRetention(logRetention);\n      }\n\n      /**\n       * @see UpdateCDNContainerOptions#enabled\n       */\n      public static UpdateCDNContainerOptions enabled(boolean enabled) {\n         UpdateCDNContainerOptions options = new UpdateCDNContainerOptions();\n         return options.enabled(enabled);\n      }\n\n      /**\n       * @see UpdateCDNContainerOptions#staticWebsiteDirectoryType\n       */\n      public static UpdateCDNContainerOptions staticWebsiteDirectoryType(MediaType directoryType) {\n         UpdateCDNContainerOptions options = new UpdateCDNContainerOptions();\n         return options.staticWebsiteDirectoryType(directoryType);\n      }\n\n      /**\n       * @see UpdateCDNContainerOptions#staticWebsiteErrorPage\n       */\n      public static UpdateCDNContainerOptions staticWebsiteErrorPage(String errorPage) {\n         UpdateCDNContainerOptions options = new UpdateCDNContainerOptions();\n         return options.staticWebsiteErrorPage(errorPage);\n      }\n\n      /**\n       * @see UpdateCDNContainerOptions#staticWebsiteIndexPage\n       */\n      public static UpdateCDNContainerOptions staticWebsiteIndexPage(String indexPage) {\n         UpdateCDNContainerOptions options = new UpdateCDNContainerOptions();\n         return options.staticWebsiteIndexPage(indexPage);\n      }\n\n      /**\n       * @see UpdateCDNContainerOptions#staticWebsiteListings\n       */\n      public static UpdateCDNContainerOptions staticWebsiteListings(boolean enabled) {\n         UpdateCDNContainerOptions options = new UpdateCDNContainerOptions();\n         return options.staticWebsiteListings(enabled);\n      }\n\n      /**\n       * @see UpdateCDNContainerOptions#staticWebsiteListingsCSS\n       */\n      public static UpdateCDNContainerOptions staticWebsiteListingsCSS(String cssPage) {\n         UpdateCDNContainerOptions options = new UpdateCDNContainerOptions();\n         return options.staticWebsiteListingsCSS(cssPage);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudfiles/src/main/java/org/jclouds/rackspace/cloudfiles/v1/reference/CloudFilesConstants.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.v1.reference;\n\n\n/**\n * Constants specified by Rackspace Cloud Files.\n */\npublic final class CloudFilesConstants {\n   public static final int CDN_TTL_MIN = 900;\n   public static final int CDN_TTL_MAX = 31536000;\n   public static final int CDN_TTL_DEFAULT = 259200;\n\n   private CloudFilesConstants() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudfiles/src/main/java/org/jclouds/rackspace/cloudfiles/v1/reference/CloudFilesHeaders.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.v1.reference;\n\nimport org.jclouds.openstack.swift.v1.reference.SwiftHeaders;\n\n/**\n * Additional headers specified by Rackspace Cloud Files.\n */\npublic final class CloudFilesHeaders {\n   // Access logs\n   public static final String CONTAINER_ACCESS_LOG_DELIVERY = SwiftHeaders.CONTAINER_METADATA_PREFIX + \"Access-Log-Delivery\";\n\n   // Common CDN Headers\n   public static final String CDN_ENABLED = \"X-Cdn-Enabled\";\n   public static final String CDN_LOG_RETENTION = \"X-Log-Retention\";\n   public static final String CDN_TTL = \"X-Ttl\";\n   public static final String CDN_URI = \"X-Cdn-Uri\";\n   public static final String CDN_SSL_URI = \"X-Cdn-Ssl-Uri\";\n   public static final String CDN_STREAMING_URI = \"X-Cdn-Streaming-Uri\";\n   public static final String CDN_IOS_URI = \"X-Cdn-Ios-Uri\";\n\n   // CDN Purge\n   public static final String CDN_PURGE_OBJECT_EMAIL = \"X-Purge-Email\";\n   public static final String CDN_PURGE_OBJECT_FAILED = \"X-Purge-Failed-Reason\";\n\n   private CloudFilesHeaders() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudfiles/src/test/java/org/jclouds/rackspace/cloudfiles/v1/CloudFilesApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.v1;\n\nimport org.jclouds.rackspace.cloudfiles.v1.internal.BaseCloudFilesApiLiveTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests live behavior of {@code CloudFilesApi}.\n */\n@Test(groups = \"live\", testName = \"CloudFilesApiLiveTest\")\npublic class CloudFilesApiLiveTest extends BaseCloudFilesApiLiveTest {\n}\n"
  },
  {
    "path": "apis/rackspace-cloudfiles/src/test/java/org/jclouds/rackspace/cloudfiles/v1/CloudFilesApiMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.v1;\n\nimport org.jclouds.View;\nimport org.jclouds.apis.internal.BaseApiMetadataTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.reflect.TypeToken;\n\n/**\n * Tests the behavior of {@link CloudFilesApiMetadata}.\n */\n@Test(groups = \"unit\", testName = \"CloudFilesApiMetadataTest\")\npublic class CloudFilesApiMetadataTest extends BaseApiMetadataTest {\n   public CloudFilesApiMetadataTest() {\n      super(new CloudFilesApiMetadata(), ImmutableSet.<TypeToken<? extends View>> of());\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudfiles/src/test/java/org/jclouds/rackspace/cloudfiles/v1/binders/BindCDNPurgeEmailAddressesToHeadersMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.v1.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.List;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.openstack.v2_0.internal.BaseOpenStackMockTest;\nimport org.jclouds.rackspace.cloudfiles.v1.CloudFilesApi;\nimport org.jclouds.rackspace.cloudfiles.v1.reference.CloudFilesHeaders;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tests the behavior of {@code BindCDNPurgeEmailAddressesToHeaders}.\n */\n@Test(groups = \"unit\", testName = \"BindCDNPurgeEmailAddressesToHeadersMockTest\")\npublic class BindCDNPurgeEmailAddressesToHeadersMockTest extends BaseOpenStackMockTest<CloudFilesApi> {\n\n   BindCDNPurgeEmailAddressesToHeaders binder = new BindCDNPurgeEmailAddressesToHeaders();\n\n   public void testEmailBind() throws Exception {\n      List<String> emails = ImmutableList.of(\"foo@bar.com\", \"bar@foo.com\");\n\n      HttpRequest request = purgeRequest();\n      \n      HttpRequest actualRequest = binder.bindToRequest(request, emails);\n      \n      HttpRequest expectedRequest = HttpRequest.builder()\n            .method(\"DELETE\")\n            .endpoint(\"https://storage101.dfw1.clouddrive.com/v1/MossoCloudFS_XXXXXX/\")\n            .addHeader(CloudFilesHeaders.CDN_PURGE_OBJECT_EMAIL, \"foo@bar.com, bar@foo.com\")\n            .build();\n      \n      assertEquals(actualRequest, expectedRequest);\n      \n   }\n\n   @Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = \"input\")\n   public void testNullList() {\n      HttpRequest request = purgeRequest();\n      binder.bindToRequest(request, null);\n   }\n\n   @Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = \"request\")\n   public void testNullRequest() {\n      List<String> emails = ImmutableList.of(\"foo@bar.com\", \"bar@foo.com\");\n      binder.bindToRequest(null, emails);\n   }\n   \n   private static HttpRequest purgeRequest() {\n      return HttpRequest.builder()\n                .method(\"DELETE\")\n                .endpoint(\"https://storage101.dfw1.clouddrive.com/v1/MossoCloudFS_XXXXXX/\")\n                .build();\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudfiles/src/test/java/org/jclouds/rackspace/cloudfiles/v1/blobstore/CloudFilesRegionScopedBlobStoreContextLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.v1.blobstore;\n\nimport static org.jclouds.rackspace.cloudidentity.v2_0.config.CloudIdentityCredentialTypes.API_KEY_CREDENTIALS;\n\nimport java.util.Properties;\n\nimport org.jclouds.openstack.swift.v1.blobstore.RegionScopedBlobStoreContext;\nimport org.jclouds.openstack.swift.v1.blobstore.RegionScopedBlobStoreContextLiveTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests the live behavior of the {@link RegionScopedBlobStoreContext}.\n */\n@Test(groups = \"live\")\npublic class CloudFilesRegionScopedBlobStoreContextLiveTest extends RegionScopedBlobStoreContextLiveTest {\n\n   public CloudFilesRegionScopedBlobStoreContextLiveTest() {\n      provider = \"rackspace-cloudfiles\";\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      setIfTestSystemPropertyPresent(props, API_KEY_CREDENTIALS);\n      return props;\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudfiles/src/test/java/org/jclouds/rackspace/cloudfiles/v1/blobstore/CloudFilesRegionScopedSwiftBlobStoreParallelLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.rackspace.cloudfiles.v1.blobstore;\n\nimport static org.jclouds.rackspace.cloudidentity.v2_0.config.CloudIdentityCredentialTypes.API_KEY_CREDENTIALS;\n\nimport java.util.Properties;\n\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.openstack.swift.v1.blobstore.RegionScopedBlobStoreContext;\nimport org.jclouds.openstack.swift.v1.blobstore.RegionScopedSwiftBlobStoreParallelLiveTest;\nimport org.testng.annotations.Test;\n\n//Applies the RegionScopedSwiftBlobStoreIntegrationTest to rackspace\n@Test(groups = \"live\")\npublic class CloudFilesRegionScopedSwiftBlobStoreParallelLiveTest extends RegionScopedSwiftBlobStoreParallelLiveTest {\n\n   public CloudFilesRegionScopedSwiftBlobStoreParallelLiveTest() {\n      provider = \"rackspace-cloudfiles\";\n   }\n\n   @Override\n   protected BlobStore getBlobStore() {\n      RegionScopedBlobStoreContext ctx = RegionScopedBlobStoreContext.class.cast(view);\n      return ctx.getBlobStore(\"IAD\");\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      setIfTestSystemPropertyPresent(props, API_KEY_CREDENTIALS);\n      return props;\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudfiles/src/test/java/org/jclouds/rackspace/cloudfiles/v1/blobstore/integration/CloudFilesBlobIntegrationLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.v1.blobstore.integration;\n\nimport static org.jclouds.rackspace.cloudidentity.v2_0.config.CloudIdentityCredentialTypes.API_KEY_CREDENTIALS;\n\nimport java.util.Properties;\n\nimport org.jclouds.openstack.swift.v1.blobstore.integration.SwiftBlobIntegrationLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"CloudFilesBlobIntegrationLiveTest\")\npublic class CloudFilesBlobIntegrationLiveTest extends SwiftBlobIntegrationLiveTest {\n\n   public CloudFilesBlobIntegrationLiveTest() {\n      provider = \"rackspace-cloudfiles\";\n   }\n   \n   @Override\n   protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      setIfTestSystemPropertyPresent(props, API_KEY_CREDENTIALS);\n      return props;\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudfiles/src/test/java/org/jclouds/rackspace/cloudfiles/v1/blobstore/integration/CloudFilesBlobLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.v1.blobstore.integration;\n\nimport static org.jclouds.rackspace.cloudidentity.v2_0.config.CloudIdentityCredentialTypes.API_KEY_CREDENTIALS;\n\nimport java.util.Properties;\n\nimport org.jclouds.openstack.swift.v1.blobstore.integration.SwiftBlobLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"CloudFilesBlobLiveTest\")\npublic class CloudFilesBlobLiveTest extends SwiftBlobLiveTest {\n\n   public CloudFilesBlobLiveTest() {\n      provider = \"rackspace-cloudfiles\";\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      setIfTestSystemPropertyPresent(props, API_KEY_CREDENTIALS);\n      return props;\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudfiles/src/test/java/org/jclouds/rackspace/cloudfiles/v1/blobstore/integration/CloudFilesBlobSignerLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.v1.blobstore.integration;\n\nimport static org.jclouds.rackspace.cloudidentity.v2_0.config.CloudIdentityCredentialTypes.API_KEY_CREDENTIALS;\n\nimport java.util.Properties;\n\nimport org.jclouds.openstack.swift.v1.blobstore.integration.SwiftBlobSignerLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"CloudFilesBlobSignerLiveTest\")\npublic class CloudFilesBlobSignerLiveTest extends SwiftBlobSignerLiveTest {\n\n   public CloudFilesBlobSignerLiveTest() {\n      provider = \"rackspace-cloudfiles\";\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      setIfTestSystemPropertyPresent(props, API_KEY_CREDENTIALS);\n      return props;\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudfiles/src/test/java/org/jclouds/rackspace/cloudfiles/v1/blobstore/integration/CloudFilesContainerIntegrationLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.v1.blobstore.integration;\n\nimport static org.jclouds.rackspace.cloudidentity.v2_0.config.CloudIdentityCredentialTypes.API_KEY_CREDENTIALS;\n\nimport java.util.Properties;\n\nimport org.jclouds.openstack.swift.v1.blobstore.integration.SwiftContainerIntegrationLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"CloudFilesContainerIntegrationLiveTest\")\npublic class CloudFilesContainerIntegrationLiveTest extends SwiftContainerIntegrationLiveTest {\n\n   public CloudFilesContainerIntegrationLiveTest() {\n      provider = \"rackspace-cloudfiles\";\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      setIfTestSystemPropertyPresent(props, API_KEY_CREDENTIALS);\n      return props;\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudfiles/src/test/java/org/jclouds/rackspace/cloudfiles/v1/blobstore/integration/CloudFilesContainerLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.v1.blobstore.integration;\n\nimport static org.jclouds.rackspace.cloudidentity.v2_0.config.CloudIdentityCredentialTypes.API_KEY_CREDENTIALS;\n\nimport java.io.IOException;\nimport java.net.MalformedURLException;\nimport java.util.Properties;\n\nimport org.jclouds.openstack.swift.v1.blobstore.integration.SwiftContainerLiveTest;\nimport org.testng.SkipException;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"CloudFilesContainerLiveTest\")\npublic class CloudFilesContainerLiveTest extends SwiftContainerLiveTest {\n\n   public CloudFilesContainerLiveTest() {\n      provider = \"rackspace-cloudfiles\";\n   }\n\n   @Override\n   public void testPublicAccess() throws InterruptedException, MalformedURLException, IOException {\n      throw new SkipException(\"public access only supported through CDN\");\n   }\n   \n   @Override\n   public void testPublicAccessInNonDefaultLocationWithBigBlob() throws InterruptedException, MalformedURLException, IOException {\n      throw new SkipException(\"public access only supported through CDN\");\n   }\n   \n   public void testPublicAccessInNonDefaultLocation() throws InterruptedException, MalformedURLException, IOException {\n      throw new SkipException(\"public access only supported through CDN\");\n   }\n   \n   @Override\n   protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      setIfTestSystemPropertyPresent(props, API_KEY_CREDENTIALS);\n      return props;\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudfiles/src/test/java/org/jclouds/rackspace/cloudfiles/v1/blobstore/integration/CloudFilesServiceIntegrationLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.v1.blobstore.integration;\n\nimport static org.jclouds.rackspace.cloudidentity.v2_0.config.CloudIdentityCredentialTypes.API_KEY_CREDENTIALS;\n\nimport java.util.Properties;\n\nimport org.jclouds.openstack.swift.v1.blobstore.integration.SwiftServiceIntegrationLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"CloudFilesServiceIntegrationLiveTest\")\npublic class CloudFilesServiceIntegrationLiveTest extends SwiftServiceIntegrationLiveTest {\n\n   public CloudFilesServiceIntegrationLiveTest() {\n      provider = \"rackspace-cloudfiles\";\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      setIfTestSystemPropertyPresent(props, API_KEY_CREDENTIALS);\n      return props;\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudfiles/src/test/java/org/jclouds/rackspace/cloudfiles/v1/features/CloudFilesAccountApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.v1.features;\n\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.openstack.swift.v1.domain.Account;\nimport org.jclouds.openstack.swift.v1.features.AccountApi;\nimport org.jclouds.openstack.swift.v1.features.AccountApiLiveTest;\nimport org.jclouds.rackspace.cloudfiles.v1.CloudFilesApi;\nimport org.testng.annotations.Test;\n\n/**\n * Tests the live behavior of the OpenStack Object Storage {@link AccountApi}\n * via the {@link CloudFilesApi}.\n */\n@Test(groups = \"live\", testName = \"CloudFilesAccountApiLiveTest\")\npublic class CloudFilesAccountApiLiveTest extends AccountApiLiveTest {\n\n   public CloudFilesAccountApiLiveTest() {\n      provider = \"rackspace-cloudfiles\";\n   }\n\n   public void testUrlKeyExists() throws Exception {\n      for (String regionId : regions) {\n         Account account = getApi().getAccountApi(regionId).get();\n         assertTrue(account.getTemporaryUrlKey().isPresent());\n      }\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudfiles/src/test/java/org/jclouds/rackspace/cloudfiles/v1/features/CloudFilesBulkApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.v1.features;\n\nimport org.jclouds.openstack.swift.v1.features.BulkApiLiveTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests the live behavior of the OpenStack Object Storage {@link BulkApi}\n * via the {@link CloudFilesApi}.\n */\n@Test(groups = \"live\", testName = \"CloudFilesBulkApiLiveTest\")\npublic class CloudFilesBulkApiLiveTest extends BulkApiLiveTest {\n   public CloudFilesBulkApiLiveTest() {\n      provider = \"rackspace-cloudfiles\";\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudfiles/src/test/java/org/jclouds/rackspace/cloudfiles/v1/features/CloudFilesCDNApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.v1.features;\n\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.List;\n\nimport org.jclouds.http.options.GetOptions;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.openstack.swift.v1.features.ObjectApi;\nimport org.jclouds.rackspace.cloudfiles.v1.domain.CDNContainer;\nimport org.jclouds.rackspace.cloudfiles.v1.internal.BaseCloudFilesApiLiveTest;\nimport org.jclouds.rackspace.cloudfiles.v1.options.ListCDNContainerOptions;\nimport org.jclouds.rackspace.cloudfiles.v1.options.UpdateCDNContainerOptions;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.io.ByteSource;\n\n\n/**\n * Tests the live behavior of the {@code CloudFilesCDNApi}.\n */\n@Test(groups = \"live\", testName = \"CloudFilesCDNApiLiveTest\")\npublic class CloudFilesCDNApiLiveTest extends BaseCloudFilesApiLiveTest {\n\n   private String name = getClass().getSimpleName();\n\n   public CloudFilesCDNApiLiveTest() {\n      super();\n   }\n\n   public void testEnable() throws Exception {\n      for (String regionId : regions) {\n         assertNotNull(getApi().getCDNApi(regionId).enable(name));\n\n         CDNContainer container = getApi().getCDNApi(regionId).get(name);\n         assertCDNContainerNotNull(container);\n         assertTrue(container.isEnabled());\n      }\n   }\n\n   public void testEnableWithTTL() throws Exception {\n      for (String regionId : regions) {\n         assertNotNull(getApi().getCDNApi(regionId).enable(name, 777777));\n\n         CDNContainer container = getApi().getCDNApi(regionId).get(name);\n         assertCDNContainerNotNull(container);\n         assertTrue(container.isEnabled());\n         assertTrue(container.getTtl() == 777777);\n      }\n   }\n\n   public void testDisable() throws Exception {\n      for (String regionId : regions) {\n         assertTrue(getApi().getCDNApi(regionId).disable(name));\n\n         CDNContainer container = getApi().getCDNApi(regionId).get(name);\n         assertFalse(container.isEnabled());\n      }\n   }\n\n   public void testList() throws Exception {\n      for (String regionId : regions) {\n         List<CDNContainer> cdnResponse = getApi().getCDNApi(regionId).list().toList();\n         assertNotNull(cdnResponse);\n\n         for (CDNContainer cdnContainer : cdnResponse) {\n            assertCDNContainerNotNull(cdnContainer);\n            assertTrue(cdnContainer.isEnabled());\n         }\n      }\n   }\n\n   public void testListWithOptions() throws Exception {\n      String lexicographicallyBeforeName = name.substring(0, name.length() - 1);\n      for (String regionId : regions) {\n         ListCDNContainerOptions options = new ListCDNContainerOptions().marker(lexicographicallyBeforeName);\n\n         CDNContainer cdnContainer = getApi().getCDNApi(regionId).list(options).get(0);\n         assertCDNContainerNotNull(cdnContainer);\n         assertTrue(cdnContainer.isEnabled());\n      }\n   }\n\n   public void testGet() throws Exception {\n      for (String regionId : regions) {\n         CDNContainer container = getApi().getCDNApi(regionId).get(name);\n         assertCDNContainerNotNull(container);\n         assertTrue(container.isEnabled());\n      }\n   }\n\n   public void testPurgeObject() throws Exception {\n      for (String regionId : regions) {\n         String objectName = \"testPurge\";\n         Payload payload = Payloads.newByteSourcePayload(ByteSource.wrap(new byte[] {1, 2, 3}));\n         ObjectApi objectApi = getApi().getObjectApi(regionId, name);\n\n         // create a new object\n         objectApi.put(objectName, payload);\n\n         CDNApi cdnApi = getApi().getCDNApi(regionId);\n         assertTrue(cdnApi.purgeObject(name, \"testPurge\", ImmutableList.<String>of()));\n\n         // delete the object\n         objectApi.delete(objectName);\n         assertNull(objectApi.get(objectName, GetOptions.NONE));\n      }\n   }\n\n   public void testUpdate() throws Exception {\n      for (String regionId : regions) {\n         // enable with a ttl\n         assertNotNull(getApi().getCDNApi(regionId).enable(name, 777777));\n\n         // now get the container\n         CDNContainer original = getApi().getCDNApi(regionId).get(name);\n         assertTrue(original.isEnabled());\n         assertCDNContainerNotNull(original);\n\n         // update options\n         UpdateCDNContainerOptions opts = new UpdateCDNContainerOptions()\n                                                .ttl(1234567)\n                                                .logRetention(true)\n                                                .enabled(false);\n         // update the container\n         assertTrue(getApi().getCDNApi(regionId).update(name, opts));\n\n         // now get the updated container\n         CDNContainer updated = getApi().getCDNApi(regionId).get(name);\n         assertFalse(updated.isEnabled());\n         assertCDNContainerNotNull(updated);\n\n         assertNotEquals(original.getTtl(), updated.getTtl());\n         assertTrue(updated.isLogRetentionEnabled());\n      }\n   }\n\n   private static void assertCDNContainerNotNull(CDNContainer container) {\n      assertNotNull(container);\n      assertNotNull(container.getName());\n      assertNotNull(container.getTtl());\n      assertNotNull(container.getUri());\n      assertNotNull(container.getIosUri());\n      assertNotNull(container.getSslUri());\n      assertNotNull(container.getStreamingUri());\n      assertNotNull(container.isLogRetentionEnabled());\n   }\n\n   @BeforeClass(groups = \"live\")\n   public void setup() {\n      super.setup();\n      for (String regionId : regions) {\n         getApi().getContainerApi(regionId).create(name);\n      }\n   }\n\n   @AfterClass(groups = \"live\")\n   public void tearDown() {\n      for (String regionId : regions) {\n         getApi().getCDNApi(regionId).disable(name);\n         getApi().getContainerApi(regionId).deleteIfEmpty(name);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudfiles/src/test/java/org/jclouds/rackspace/cloudfiles/v1/features/CloudFilesCDNApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.v1.features;\n\nimport static com.google.common.net.HttpHeaders.CONTENT_LENGTH;\nimport static com.google.common.net.HttpHeaders.CONTENT_TYPE;\nimport static org.jclouds.rackspace.cloudfiles.v1.options.UpdateCDNContainerOptions.Builder.enabled;\nimport static org.jclouds.rackspace.cloudfiles.v1.reference.CloudFilesHeaders.CDN_ENABLED;\nimport static org.jclouds.rackspace.cloudfiles.v1.reference.CloudFilesHeaders.CDN_IOS_URI;\nimport static org.jclouds.rackspace.cloudfiles.v1.reference.CloudFilesHeaders.CDN_LOG_RETENTION;\nimport static org.jclouds.rackspace.cloudfiles.v1.reference.CloudFilesHeaders.CDN_SSL_URI;\nimport static org.jclouds.rackspace.cloudfiles.v1.reference.CloudFilesHeaders.CDN_STREAMING_URI;\nimport static org.jclouds.rackspace.cloudfiles.v1.reference.CloudFilesHeaders.CDN_TTL;\nimport static org.jclouds.rackspace.cloudfiles.v1.reference.CloudFilesHeaders.CDN_URI;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\n\nimport org.jclouds.openstack.v2_0.internal.BaseOpenStackMockTest;\nimport org.jclouds.rackspace.cloudfiles.v1.CloudFilesApi;\nimport org.jclouds.rackspace.cloudfiles.v1.domain.CDNContainer;\nimport org.jclouds.rackspace.cloudfiles.v1.options.ListCDNContainerOptions;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableList;\n\n\n/**\n * Tests the behavior of the {@link CloudFilesCDNApi}.\n */\n@Test(groups = \"unit\", testName = \"CloudFilesCDNApiMockTest\")\npublic class CloudFilesCDNApiMockTest extends BaseOpenStackMockTest<CloudFilesApi> {\n\n   List<String> emails = ImmutableList.of(\"foo@bar.com\", \"bar@foo.com\");\n\n   public void testList() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/cdn_container_list.json\"))));\n\n      try {\n         CloudFilesApi api = api(server.url(\"/\").toString(), \"rackspace-cloudfiles\");\n         CDNApi cdnApi = api.getCDNApi(\"DFW\");\n\n         ImmutableList<CDNContainer> cdnContainers = cdnApi.list().toList();\n\n         assertEquals(cdnContainers, mockContainers);\n\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"GET\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/?format=json&enabled_only=true\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testListIsEmpty() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(404)));\n\n      try {\n         CloudFilesApi api = api(server.url(\"/\").toString(), \"rackspace-cloudfiles\");\n         CDNApi cdnApi = api.getCDNApi(\"DFW\");\n\n         List<CDNContainer> cdnContainers = cdnApi.list().toList();\n\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"GET\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/?format=json&enabled_only=true\");\n\n         assertTrue(cdnContainers.isEmpty());\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testListWithOptions() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/cdn_container_list_at.json\"))));\n\n      try {\n         CloudFilesApi api = api(server.url(\"/\").toString(), \"rackspace-cloudfiles\");\n         ListCDNContainerOptions options = new ListCDNContainerOptions().marker(\"cdn-container-3\");\n         ImmutableList<CDNContainer> containers = api.getCDNApi(\"DFW\").list(options).toList();\n\n         for (CDNContainer container : containers) {\n            assertCDNContainerNotNull(container);\n         }\n\n         assertEquals(containers, mockContainers.subList(2, mockContainers.size()));\n\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"GET\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/?format=json&enabled_only=true&marker=cdn-container-3\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testListWithOptionsIsEmpty() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(404)));\n\n      try {\n         CloudFilesApi api = api(server.url(\"/\").toString(), \"rackspace-cloudfiles\");\n         ListCDNContainerOptions options = ListCDNContainerOptions.Builder.marker(\"cdn-container-3\");\n         FluentIterable<CDNContainer> containers = api.getCDNApi(\"DFW\").list(options);\n\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"GET\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/?format=json&enabled_only=true&marker=cdn-container-3\");\n\n         assertNotNull(containers);\n         assertTrue(containers.isEmpty());\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testEnable() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(enabledResponse().setResponseCode(201)));\n\n      try {\n         CloudFilesApi api = api(server.url(\"/\").toString(), \"rackspace-cloudfiles\");\n\n         // enable a CDN Container\n         URI enabledContainer = api.getCDNApi(\"DFW\").enable(\"container-1\");\n         assertNotNull(enabledContainer);\n\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"PUT\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/container-1\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testEnableFail() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(enabledResponse().setResponseCode(404)));\n\n      try {\n         CloudFilesApi api = api(server.url(\"/\").toString(), \"rackspace-cloudfiles\");\n         // enable a CDN Container\n         assertNull(api.getCDNApi(\"DFW\").enable(\"container-1\"));\n\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"PUT\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/container-1\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testEnableWithTTL() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(enabledResponse().setResponseCode(201)));\n\n      try {\n         CloudFilesApi api = api(server.url(\"/\").toString(), \"rackspace-cloudfiles\");\n\n         // enable a CDN Container with a TTL\n         URI enabledContainer = api.getCDNApi(\"DFW\").enable(\"container-1\", 777777);\n         assertNotNull(enabledContainer);\n\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"PUT\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/container-1\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testEnableWithTTLFail() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(enabledResponse().setResponseCode(404)));\n\n      try {\n         CloudFilesApi api = api(server.url(\"/\").toString(), \"rackspace-cloudfiles\");\n\n         // enable a CDN Container with a TTL\n         URI enabledContainer = api.getCDNApi(\"DFW\").enable(\"container-1\", 777777);\n         assertNull(enabledContainer);\n\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"PUT\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/container-1\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testDisable() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(enabledResponse().setResponseCode(201)));\n\n      try {\n         CloudFilesApi api = api(server.url(\"/\").toString(), \"rackspace-cloudfiles\");\n\n         // disable a CDN Container\n         assertTrue(api.getCDNApi(\"DFW\").disable(\"container-1\"));\n\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"PUT\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/container-1\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testDisableFail() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(enabledResponse().setResponseCode(404)));\n\n      try {\n         CloudFilesApi api = api(server.url(\"/\").toString(), \"rackspace-cloudfiles\");\n\n         // disable a CDN Container\n         boolean disbledContainer = api.getCDNApi(\"DFW\").disable(\"container-1\");\n         assertFalse(disbledContainer);\n\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"PUT\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/container-1\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGet() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(enabledResponse().setResponseCode(201)));\n\n      try {\n         CloudFilesApi api = api(server.url(\"/\").toString(), \"rackspace-cloudfiles\");\n\n         CDNContainer cdnContainer = api.getCDNApi(\"DFW\").get(\"container-1\");\n         assertCDNContainerNotNull(cdnContainer);\n         assertEquals(mockCDNContainer, cdnContainer);\n\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"HEAD\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/container-1\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGetCDNContainerWithSpaces() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(enabledResponse().setResponseCode(201)));\n\n      try {\n         CloudFilesApi api = api(server.url(\"/\").toString(), \"rackspace-cloudfiles\");\n\n         CDNContainer cdnContainer = api.getCDNApi(\"DFW\").get(\"cdn-container with spaces\");\n         assertCDNContainerNotNull(cdnContainer);\n         assertEquals(mockCDNContainerWithSpaces, cdnContainer);\n\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"HEAD\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/cdn-container%20with%20spaces\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGetFail() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(404)));\n\n      try {\n         CloudFilesApi api = api(server.url(\"/\").toString(), \"rackspace-cloudfiles\");\n\n         CDNContainer cdnContainer = api.getCDNApi(\"DFW\").get(\"container-1\");\n\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"HEAD\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/container-1\");\n         assertNull(cdnContainer);\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testPurgeObject() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(201)));\n\n      try {\n         CloudFilesApi api = api(server.url(\"/\").toString(), \"rackspace-cloudfiles\");\n\n         // purge the object\n         assertTrue(api.getCDNApi(\"DFW\").purgeObject(\"myContainer\", \"myObject\", emails));\n\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"DELETE\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/myContainer/myObject\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testPurgeObjectFail() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\"))));\n      server.enqueue(addCommonHeaders(new MockResponse().setResponseCode(404)));\n\n      try {\n         CloudFilesApi api = api(server.url(\"/\").toString(), \"rackspace-cloudfiles\");\n\n         // purge the object\n         assertFalse(api.getCDNApi(\"DFW\").purgeObject(\"myContainer\", \"myObject\", emails));\n\n         assertEquals(server.getRequestCount(), 2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"DELETE\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/myContainer/myObject\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testUpdate() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\")).setResponseCode(200)));\n      server.enqueue(addCommonHeaders(enabledResponse().setResponseCode(200)));\n      server.enqueue(addCommonHeaders(updatedResponse().setResponseCode(204)));\n      server.enqueue(addCommonHeaders(updatedResponse().setResponseCode(200)));\n\n      try {\n         CloudFilesApi api = api(server.url(\"/\").toString(), \"rackspace-cloudfiles\");\n\n         CDNContainer cdnContainer = api.getCDNApi(\"DFW\").get(\"container-1\");\n         assertCDNContainerNotNull(cdnContainer);\n\n         // update the CDN Container\n         assertTrue(api.getCDNApi(\"DFW\").update(\"container-1\", enabled(false).logRetention(true).ttl(7654321)));\n\n         cdnContainer = api.getCDNApi(\"DFW\").get(\"container-1\");\n         assertCDNContainerNotNull(cdnContainer);\n\n         CDNContainer updatedContainer = CDNContainer.builder()\n               .name(\"container-1\")\n               .enabled(false)\n               .logRetention(true)\n               .ttl(7654321)\n               .uri(URI.create(\"http://id-1.cdn.rackspace.com\"))\n               .sslUri(URI.create(\"https://ssl-id-1.ssl.rackspace.com\"))\n               .streamingUri(URI.create(\"http://streaming-id-1.stream.rackspace.com\"))\n               .iosUri(URI.create(\"http://ios-id-1.iosr.rackspace.com\"))\n               .build();\n\n         assertEquals(updatedContainer, cdnContainer);\n\n         assertEquals(server.getRequestCount(), 4);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"HEAD\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/container-1\");\n         assertRequest(server.takeRequest(), \"POST\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/container-1\");\n         assertRequest(server.takeRequest(), \"HEAD\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/container-1\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testUpdateFail() throws Exception {\n      MockWebServer server = mockOpenStackServer();\n      server.enqueue(addCommonHeaders(new MockResponse().setBody(stringFromResource(\"/access.json\")).setResponseCode(200)));\n      server.enqueue(addCommonHeaders(enabledResponse().setResponseCode(200)));\n      server.enqueue(addCommonHeaders(updatedResponse().setResponseCode(404)));\n\n      try {\n         CloudFilesApi api = api(server.url(\"/\").toString(), \"rackspace-cloudfiles\");\n\n         CDNContainer cdnContainer = api.getCDNApi(\"DFW\").get(\"container-1\");\n         assertCDNContainerNotNull(cdnContainer);\n\n         // update the CDN Container\n         assertFalse(api.getCDNApi(\"DFW\").update(\"container-1\", enabled(false).logRetention(true).ttl(7654321)));\n\n         assertEquals(server.getRequestCount(), 3);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"HEAD\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/container-1\");\n         assertRequest(server.takeRequest(), \"POST\", \"/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9/container-1\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   private static void assertCDNContainerNotNull(CDNContainer container) {\n      assertNotNull(container.getName());\n      assertNotNull(container.isEnabled());\n      assertNotNull(container.isLogRetentionEnabled());\n      assertNotNull(container.getTtl());\n      assertNotNull(container.getUri());\n      assertNotNull(container.getSslUri());\n      assertNotNull(container.getStreamingUri());\n      assertNotNull(container.getIosUri());\n   }\n\n   private static final CDNContainer mockCDNContainer = CDNContainer.builder()\n         .name(\"container-1\")\n         .enabled(true)\n         .logRetention(false)\n         .ttl(777777)\n         .uri(URI.create(\"http://id-1.cdn.rackspace.com\"))\n         .sslUri(URI.create(\"https://ssl-id-1.ssl.rackspace.com\"))\n         .streamingUri(URI.create(\"http://streaming-id-1.stream.rackspace.com\"))\n         .iosUri(URI.create(\"http://ios-id-1.iosr.rackspace.com\"))\n         .build();\n\n   private static final CDNContainer mockCDNContainerWithSpaces = CDNContainer.builder()\n         .name(\"cdn-container with spaces\")\n         .enabled(true)\n         .logRetention(false)\n         .ttl(777777)\n         .uri(URI.create(\"http://id-1.cdn.rackspace.com\"))\n         .sslUri(URI.create(\"https://ssl-id-1.ssl.rackspace.com\"))\n         .streamingUri(URI.create(\"http://streaming-id-1.stream.rackspace.com\"))\n         .iosUri(URI.create(\"http://ios-id-1.iosr.rackspace.com\"))\n         .build();\n\n   private static MockResponse enabledResponse() {\n      return new MockResponse()\n            .addHeader(CDN_ENABLED, \"true\")\n            .addHeader(CDN_LOG_RETENTION, \"false\")\n            .addHeader(CDN_TTL, \"777777\")\n            .addHeader(CDN_URI, \"http://id-1.cdn.rackspace.com\")\n            .addHeader(CDN_SSL_URI, \"https://ssl-id-1.ssl.rackspace.com\")\n            .addHeader(CDN_STREAMING_URI, \"http://streaming-id-1.stream.rackspace.com\")\n            .addHeader(CDN_IOS_URI, \"http://ios-id-1.iosr.rackspace.com\")\n            .addHeader(CONTENT_LENGTH, \"0\")\n            .addHeader(CONTENT_TYPE, \"text/plain; charset=UTF-8\");\n   }\n\n   private static MockResponse updatedResponse() {\n      return new MockResponse()\n            .addHeader(CDN_ENABLED, \"false\")\n            .addHeader(CDN_LOG_RETENTION, \"true\")\n            .addHeader(CDN_TTL, \"7654321\")\n            .addHeader(CDN_URI, \"http://id-1.cdn.rackspace.com\")\n            .addHeader(CDN_SSL_URI, \"https://ssl-id-1.ssl.rackspace.com\")\n            .addHeader(CDN_STREAMING_URI, \"http://streaming-id-1.stream.rackspace.com\")\n            .addHeader(CDN_IOS_URI, \"http://ios-id-1.iosr.rackspace.com\")\n            .addHeader(CONTENT_LENGTH, \"0\")\n            .addHeader(CONTENT_TYPE, \"text/plain; charset=UTF-8\");\n   }\n\n   private static final ImmutableList<CDNContainer> mockContainers = ImmutableList.of(\n         CDNContainer.builder()\n               .name(\"cdn-container-1\")\n               .enabled(true)\n               .logRetention(false)\n               .ttl(259200)\n               .uri(URI.create(\"http://id-1.cdn.rackspace.com\"))\n               .sslUri(URI.create(\"https://ssl-id-1.ssl.rackspace.com\"))\n               .streamingUri(URI.create(\"http://streaming-id-1.stream.rackspace.com\"))\n               .iosUri(URI.create(\"http://ios-id-1.iosr.rackspace.com\"))\n               .build(),\n         CDNContainer.builder()\n               .name(\"cdn-container-2\")\n               .enabled(true)\n               .logRetention(true)\n               .ttl(259200)\n               .uri(URI.create(\"http://id-2.cdn.rackspace.com\"))\n               .sslUri(URI.create(\"https://ssl-id-2.ssl.rackspace.com\"))\n               .streamingUri(URI.create(\"http://streaming-id-2.stream.rackspace.com\"))\n               .iosUri(URI.create(\"http://ios-id-2.iosr.rackspace.com\"))\n               .build(),\n         CDNContainer.builder()\n               .name(\"cdn-container-3\")\n               .enabled(true)\n               .logRetention(false)\n               .ttl(259200)\n               .uri(URI.create(\"http://id-3.cdn.rackspace.com\"))\n               .sslUri(URI.create(\"https://ssl-id-3.ssl.rackspace.com\"))\n               .streamingUri(URI.create(\"http://streaming-id-3.stream.rackspace.com\"))\n               .iosUri(URI.create(\"http://ios-id-3.iosr.rackspace.com\"))\n               .build(),\n         CDNContainer.builder()\n               .name(\"cdn-container-4 with spaces\")\n               .enabled(true)\n               .logRetention(true)\n               .ttl(777777)\n               .uri(URI.create(\"http://id-4.cdn.rackspace.com\"))\n               .sslUri(URI.create(\"https://ssl-id-4.ssl.rackspace.com\"))\n               .streamingUri(URI.create(\"http://streaming-id-4.stream.rackspace.com\"))\n               .iosUri(URI.create(\"http://ios-id-4.iosr.rackspace.com\"))\n               .build());\n}\n"
  },
  {
    "path": "apis/rackspace-cloudfiles/src/test/java/org/jclouds/rackspace/cloudfiles/v1/features/CloudFilesContainerApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.v1.features;\n\nimport org.jclouds.openstack.swift.v1.features.ContainerApiLiveTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests the live behavior of the OpenStack Object Storage {@link ContainerApi}\n * via the {@link CloudFilesApi}.\n */\n@Test(groups = \"live\", testName = \"CloudFilesContainerApiLiveTest\")\npublic class CloudFilesContainerApiLiveTest extends ContainerApiLiveTest {\n   public CloudFilesContainerApiLiveTest() {\n      provider = \"rackspace-cloudfiles\";\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudfiles/src/test/java/org/jclouds/rackspace/cloudfiles/v1/features/CloudFilesDynamicLargeObjectApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.v1.features;\n\nimport org.jclouds.openstack.swift.v1.features.DynamicLargeObjectApiLiveTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests the live behavior of the OpenStack Object Storage {@link DynamicLargeObjectApi}\n * via the {@link CloudFilesApi}.\n */\n@Test(groups = \"live\", testName = \"CloudFilesDynamicLargeObjectApiLiveTest\")\npublic class CloudFilesDynamicLargeObjectApiLiveTest extends DynamicLargeObjectApiLiveTest {\n   public CloudFilesDynamicLargeObjectApiLiveTest() {\n      provider = \"rackspace-cloudfiles\";\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudfiles/src/test/java/org/jclouds/rackspace/cloudfiles/v1/features/CloudFilesObjectApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.v1.features;\n\nimport org.jclouds.openstack.swift.v1.features.ObjectApiLiveTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests the live behavior of the OpenStack Object Storage {@link ObjectApi}\n * via the {@link CloudFilesApi}.\n */\n@Test(groups = \"live\", testName = \"CloudFilesObjectApiLiveTest\")\npublic class CloudFilesObjectApiLiveTest extends ObjectApiLiveTest {\n   public CloudFilesObjectApiLiveTest() {\n      provider = \"rackspace-cloudfiles\";\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudfiles/src/test/java/org/jclouds/rackspace/cloudfiles/v1/features/CloudFilesStaticLargeObjectApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.v1.features;\n\nimport org.jclouds.openstack.swift.v1.features.StaticLargeObjectApiLiveTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests the live behavior of the OpenStack Object Storage {@link StaticLargeObjectApi}\n * via the {@link CloudFilesApi}.\n */\n@Test(groups = \"live\", testName = \"CloudFilesStaticLargeObjectApiLiveTest\")\npublic class CloudFilesStaticLargeObjectApiLiveTest extends StaticLargeObjectApiLiveTest {\n   public CloudFilesStaticLargeObjectApiLiveTest() {\n      provider = \"rackspace-cloudfiles\";\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudfiles/src/test/java/org/jclouds/rackspace/cloudfiles/v1/internal/BaseCloudFilesApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.v1.internal;\n\nimport org.jclouds.openstack.swift.v1.internal.BaseSwiftApiLiveTest;\nimport org.jclouds.rackspace.cloudfiles.v1.CloudFilesApi;\nimport org.testng.annotations.Test;\n\n/**\n * Base class for all {@link CloudFilesApi} live tests.\n */\n@Test(groups = \"live\", testName = \"BaseCloudFilesApiLiveTest\")\npublic abstract class BaseCloudFilesApiLiveTest extends BaseSwiftApiLiveTest {\n\n   protected BaseCloudFilesApiLiveTest() {\n      provider = \"rackspace-cloudfiles\";\n   }\n\n   public CloudFilesApi getApi() {\n      return view.unwrapApi(CloudFilesApi.class);\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudfiles/src/test/java/org/jclouds/rackspace/cloudfiles/v1/options/UpdateCDNContainerOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.v1.options;\n\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.STATIC_WEB_DIRECTORY_TYPE;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.STATIC_WEB_ERROR;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.STATIC_WEB_INDEX;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.STATIC_WEB_LISTINGS;\nimport static org.jclouds.openstack.swift.v1.reference.SwiftHeaders.STATIC_WEB_LISTINGS_CSS;\nimport static org.jclouds.rackspace.cloudfiles.v1.reference.CloudFilesConstants.CDN_TTL_MAX;\nimport static org.jclouds.rackspace.cloudfiles.v1.reference.CloudFilesConstants.CDN_TTL_MIN;\nimport static org.jclouds.rackspace.cloudfiles.v1.reference.CloudFilesHeaders.CDN_LOG_RETENTION;\nimport static org.jclouds.rackspace.cloudfiles.v1.reference.CloudFilesHeaders.CDN_TTL;\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.net.MediaType;\n\n/**\n * Tests behavior of {@link UpdateCDNContainerOptions}.\n */\n@Test(groups = \"unit\")\npublic class UpdateCDNContainerOptionsTest {\n\n   public void testTTLInRange() {\n      UpdateCDNContainerOptions options = \n            new UpdateCDNContainerOptions().ttl(123456);\n      assertEquals(ImmutableList.of(\"123456\"), options.buildRequestHeaders().get(CDN_TTL));\n   }\n\n   @SuppressWarnings(\"CheckReturnValue\")\n   @Test(expectedExceptions = IllegalStateException.class)\n   public void testTTLLessThanMin() {\n      UpdateCDNContainerOptions options = \n            new UpdateCDNContainerOptions().ttl(CDN_TTL_MIN - 1);\n      options.buildRequestHeaders().get(CDN_TTL);\n   }\n\n   @SuppressWarnings(\"CheckReturnValue\")\n   @Test(expectedExceptions = IllegalStateException.class)\n   public void testTTLGreaterThanMax() {\n      UpdateCDNContainerOptions options = \n            new UpdateCDNContainerOptions().ttl(CDN_TTL_MAX + 1);\n      options.buildRequestHeaders().get(CDN_TTL);\n   }\n\n   public void testEnableLogRetention() {\n      UpdateCDNContainerOptions options = \n            new UpdateCDNContainerOptions().logRetention(true);\n      assertEquals(ImmutableList.of(\"true\"), options.buildRequestHeaders().get(CDN_LOG_RETENTION));\n   }\n\n   public void testDisableLogRetention() {\n      UpdateCDNContainerOptions options = \n            new UpdateCDNContainerOptions().logRetention(false);\n      assertEquals(ImmutableList.of(\"false\"), options.buildRequestHeaders().get(CDN_LOG_RETENTION));\n   }\n\n   public void testStaticWebsiteDirectoryType() {\n      MediaType appDir = MediaType.create(\"application\", \"directory\");\n      UpdateCDNContainerOptions options = \n            new UpdateCDNContainerOptions().staticWebsiteDirectoryType(appDir);\n      assertEquals(ImmutableList.of(appDir.toString()), options.buildRequestHeaders().get(STATIC_WEB_DIRECTORY_TYPE));\n   }\n\n   public void testStaticWebsiteIndexPage() {\n      UpdateCDNContainerOptions options = \n            new UpdateCDNContainerOptions().staticWebsiteIndexPage(\"index.html\");\n      assertEquals(ImmutableList.of(\"index.html\"), options.buildRequestHeaders().get(STATIC_WEB_INDEX));\n   }\n\n   public void testStaticWebsiteErrorPage() {\n      UpdateCDNContainerOptions options = \n            new UpdateCDNContainerOptions().staticWebsiteErrorPage(\"error.html\");\n      assertEquals(ImmutableList.of(\"error.html\"), options.buildRequestHeaders().get(STATIC_WEB_ERROR));\n   }\n\n   public void testEnableStaticWebsiteListings() {\n      UpdateCDNContainerOptions options = \n            new UpdateCDNContainerOptions().staticWebsiteListings(true);\n      assertEquals(ImmutableList.of(\"true\"), options.buildRequestHeaders().get(STATIC_WEB_LISTINGS));\n   }\n\n   public void testDiableStaticWebsiteListings() {\n      UpdateCDNContainerOptions options = \n            new UpdateCDNContainerOptions().staticWebsiteListings(false);\n      assertEquals(ImmutableList.of(\"false\"), options.buildRequestHeaders().get(STATIC_WEB_LISTINGS));\n   }\n\n   public void testStaticWebsiteListingsCSS() {\n      UpdateCDNContainerOptions options = \n            new UpdateCDNContainerOptions().staticWebsiteListingsCSS(\"listings.css\");\n      assertEquals(ImmutableList.of(\"listings.css\"), options.buildRequestHeaders().get(STATIC_WEB_LISTINGS_CSS));\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudfiles/src/test/resources/cdn_container_list.json",
    "content": "[\n    {\n        \"cdn_streaming_uri\": \"http://streaming-id-1.stream.rackspace.com\",\n        \"name\": \"cdn-container-1\",\n        \"cdn_ios_uri\": \"http://ios-id-1.iosr.rackspace.com\",\n        \"cdn_ssl_uri\": \"https://ssl-id-1.ssl.rackspace.com\",\n        \"cdn_enabled\": true,\n        \"ttl\": 259200,\n        \"log_retention\": false,\n        \"cdn_uri\": \"http://id-1.cdn.rackspace.com\"\n    },\n    {\n        \"cdn_streaming_uri\": \"http://streaming-id-2.stream.rackspace.com\",\n        \"name\": \"cdn-container-2\",\n        \"cdn_ios_uri\": \"http://ios-id-2.iosr.rackspace.com\",\n        \"cdn_ssl_uri\": \"https://ssl-id-2.ssl.rackspace.com\",\n        \"cdn_enabled\": true,\n        \"ttl\": 259200,\n        \"log_retention\": true,\n        \"cdn_uri\": \"http://id-2.cdn.rackspace.com\"\n    },\n    {\n        \"cdn_streaming_uri\": \"http://streaming-id-3.stream.rackspace.com\",\n        \"name\": \"cdn-container-3\",\n        \"cdn_ios_uri\": \"http://ios-id-3.iosr.rackspace.com\",\n        \"cdn_ssl_uri\": \"https://ssl-id-3.ssl.rackspace.com\",\n        \"cdn_enabled\": true,\n        \"ttl\": 259200,\n        \"log_retention\": false,\n        \"cdn_uri\": \"http://id-3.cdn.rackspace.com\"\n    },\n    {\n        \"cdn_streaming_uri\": \"http://streaming-id-4.stream.rackspace.com\",\n        \"name\": \"cdn-container-4 with spaces\",\n        \"cdn_ios_uri\": \"http://ios-id-4.iosr.rackspace.com\",\n        \"cdn_ssl_uri\": \"https://ssl-id-4.ssl.rackspace.com\",\n        \"cdn_enabled\": true,\n        \"ttl\": 777777,\n        \"log_retention\": true,\n        \"cdn_uri\": \"http://id-4.cdn.rackspace.com\"\n    }\n]\n"
  },
  {
    "path": "apis/rackspace-cloudfiles/src/test/resources/cdn_container_list_at.json",
    "content": "[\n    {\n        \"cdn_streaming_uri\": \"http://streaming-id-3.stream.rackspace.com\",\n        \"name\": \"cdn-container-3\",\n        \"cdn_ios_uri\": \"http://ios-id-3.iosr.rackspace.com\",\n        \"cdn_ssl_uri\": \"https://ssl-id-3.ssl.rackspace.com\",\n        \"cdn_enabled\": true,\n        \"ttl\": 259200,\n        \"log_retention\": false,\n        \"cdn_uri\": \"http://id-3.cdn.rackspace.com\"\n    },\n    {\n        \"cdn_streaming_uri\": \"http://streaming-id-4.stream.rackspace.com\",\n        \"name\": \"cdn-container-4 with spaces\",\n        \"cdn_ios_uri\": \"http://ios-id-4.iosr.rackspace.com\",\n        \"cdn_ssl_uri\": \"https://ssl-id-4.ssl.rackspace.com\",\n        \"cdn_enabled\": true,\n        \"ttl\": 777777,\n        \"log_retention\": true,\n        \"cdn_uri\": \"http://id-4.cdn.rackspace.com\"\n    }\n]"
  },
  {
    "path": "apis/rackspace-cloudfiles/src/test/resources/logback.xml",
    "content": "<?xml version=\"1.0\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<configuration scan=\"false\">\n    <appender name=\"FILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <appender name=\"WIREFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds-wire.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <appender name=\"BLOBSTOREFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds-blobstore.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n    \n    <root>\n        <level value=\"warn\" />\n    </root>\n\n    <logger name=\"org.jclouds\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"FILE\" />\n    </logger>\n\n<!--\n    <logger name=\"jclouds.wire\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n-->\n\n    <logger name=\"jclouds.headers\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n\n    <logger name=\"jclouds.blobstore\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"BLOBSTOREFILE\" />\n    </logger>\n\n</configuration>\n"
  },
  {
    "path": "apis/rackspace-cloudidentity/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.rackspace.cloudidentity.v2_0.*;version=\"${project.version}\";-noimport:=true"
  },
  {
    "path": "apis/rackspace-cloudidentity/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.api</groupId>\n  <artifactId>rackspace-cloudidentity</artifactId>\n  <name>jclouds rackspace cloudidentity api</name>\n  <description>jclouds components to access an implementation of Rackspace Cloud Identity</description>\n\n  <properties>\n    <!-- keystone endpoint -->\n    <test.rackspace-cloudidentity.endpoint>https://identity.api.rackspacecloud.com/v2.0/</test.rackspace-cloudidentity.endpoint>\n    <!-- keystone version -->\n    <test.rackspace-cloudidentity.api-version>2.0</test.rackspace-cloudidentity.api-version>\n    <test.rackspace-cloudidentity.build-version />\n    <test.rackspace-cloudidentity.identity>${test.rackspace-us.identity}</test.rackspace-cloudidentity.identity>\n    <test.rackspace-cloudidentity.credential>${test.rackspace-us.credential}</test.rackspace-cloudidentity.credential>\n    <test.jclouds.keystone.credential-type>RAX-KSKEY:apiKeyCredentials</test.jclouds.keystone.credential-type>\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-keystone</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-keystone</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-slf4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>ch.qos.logback</groupId>\n      <artifactId>logback-classic</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n  \n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.rackspace-cloudidentity.endpoint>${test.rackspace-cloudidentity.endpoint}</test.rackspace-cloudidentity.endpoint>\n                    <test.rackspace-cloudidentity.api-version>${test.rackspace-cloudidentity.api-version}</test.rackspace-cloudidentity.api-version>\n                    <test.rackspace-cloudidentity.build-version>${test.rackspace-cloudidentity.build-version}</test.rackspace-cloudidentity.build-version>\n                    <test.rackspace-cloudidentity.identity>${test.rackspace-cloudidentity.identity}</test.rackspace-cloudidentity.identity>\n                    <test.rackspace-cloudidentity.credential>${test.rackspace-cloudidentity.credential}</test.rackspace-cloudidentity.credential>\n                    <test.jclouds.keystone.credential-type>${test.jclouds.keystone.credential-type}</test.jclouds.keystone.credential-type>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n"
  },
  {
    "path": "apis/rackspace-cloudidentity/src/main/java/org/jclouds/rackspace/cloudidentity/v2_0/CloudIdentityApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudidentity.v2_0;\n\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.CREDENTIAL_TYPE;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.openstack.keystone.catalog.config.KeystoneAdminURLModule;\nimport org.jclouds.openstack.keystone.catalog.config.ServiceCatalogModule;\nimport org.jclouds.openstack.keystone.v2_0.KeystoneApiMetadata;\nimport org.jclouds.openstack.keystone.v2_0.config.KeystoneHttpApiModule;\nimport org.jclouds.openstack.keystone.v2_0.config.KeystoneParserModule;\nimport org.jclouds.rackspace.cloudidentity.v2_0.config.CloudIdentityAuthenticationModule;\nimport org.jclouds.rackspace.cloudidentity.v2_0.config.CloudIdentityCredentialTypes;\n\nimport com.google.auto.service.AutoService;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n/**\n * Implementation of {@link ApiMetadata} for the Rackspace Cloud Identity Service\n */\n@AutoService(ApiMetadata.class)\npublic class CloudIdentityApiMetadata extends KeystoneApiMetadata {\n\n   @Override\n   public Builder toBuilder() {\n      return new Builder().fromApiMetadata(this);\n   }\n\n   public CloudIdentityApiMetadata() {\n      this(new Builder());\n   }\n\n   protected CloudIdentityApiMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = KeystoneApiMetadata.defaultProperties();\n      properties.setProperty(CREDENTIAL_TYPE, CloudIdentityCredentialTypes.API_KEY_CREDENTIALS);\n      return properties;\n   }\n\n   public static class Builder extends KeystoneApiMetadata.Builder<Builder> {\n      protected Builder() {\n         id(\"rackspace-cloudidentity\")\n         .name(\"Rackspace Cloud Identity Service\")\n         .identityName(\"${userName}\")\n         .credentialName(\"${apiKey}\")\n         .defaultEndpoint(\"https://identity.api.rackspacecloud.com/v${jclouds.api-version}/\")\n         .endpointName(\"identity service url ending in /v${jclouds.api-version}/\")\n         .defaultProperties(CloudIdentityApiMetadata.defaultProperties())\n         .documentation(URI.create(\"http://docs.rackspace.com/auth/api/v2.0/auth-api-devguide/\"))\n         .defaultModules(ImmutableSet.<Class<? extends Module>>builder()\n                                     .add(CloudIdentityAuthenticationModule.class)\n                                     .add(ServiceCatalogModule.class)\n                                     .add(KeystoneAdminURLModule.class)\n                                     .add(KeystoneParserModule.class)\n                                     .add(KeystoneHttpApiModule.class).build());\n      }\n\n      @Override\n      public CloudIdentityApiMetadata build() {\n         return new CloudIdentityApiMetadata(this);\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudidentity/src/main/java/org/jclouds/rackspace/cloudidentity/v2_0/CloudIdentityAuthenticationApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudidentity.v2_0;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.openstack.keystone.auth.AuthenticationApi;\nimport org.jclouds.openstack.keystone.auth.domain.TenantOrDomainAndCredentials;\nimport org.jclouds.openstack.keystone.v2_0.binders.BindAuthToJsonPayload;\nimport org.jclouds.openstack.keystone.v2_0.domain.Access;\nimport org.jclouds.rackspace.cloudidentity.v2_0.domain.ApiKeyCredentials;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.SelectJson;\n\n/**\n * Provides access to the Rackspace Cloud Identity API.\n */\n@Consumes(MediaType.APPLICATION_JSON)\n@Path(\"/tokens\")\npublic interface CloudIdentityAuthenticationApi extends AuthenticationApi {\n\n   /**\n    * Authenticate to generate a token.\n    *\n    * @return access with token\n    */\n   @Named(\"authenticate\")\n   @POST\n   @SelectJson(\"access\")\n   @MapBinder(BindAuthToJsonPayload.class)\n   Access authenticateApiKey(TenantOrDomainAndCredentials<ApiKeyCredentials> credentials);\n\n}\n"
  },
  {
    "path": "apis/rackspace-cloudidentity/src/main/java/org/jclouds/rackspace/cloudidentity/v2_0/ServiceType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudidentity.v2_0;\n\n/**\n * An Rackspace service, such as Cloud Load Balancers, DNS, etc.\n * A service provides one or more endpoints through which users can access resources and perform operations.\n */\npublic final class ServiceType {\n   /**\n    * Cloud Load Balancers\n    */\n   public static final String LOAD_BALANCERS = \"rax:load-balancer\";\n\n   /**\n    * Cloud DNS\n    */\n   public static final String DNS = \"rax:dns\";\n\n   /**\n    * Cloud Queues\n    */\n   public static final String QUEUES = \"rax:queues\";\n\n   /**\n    * Cloud Files CDN\n    */\n   public static final String OBJECT_CDN = \"rax:object-cdn\";\n\n   /**\n    * Auto Scale\n    */\n   public static final String AUTO_SCALE = \"rax:autoscale\";\n\n   /**\n    * Cloud Backup\n    */\n   public static final String BACKUP = \"rax:backup\";\n\n   /**\n    * Cloud Databases\n    */\n   public static final String DATABASES = \"rax:database\";\n\n   /**\n    * Cloud Monitoring\n    */\n   public static final String MONITORING = \"rax:monitor\";\n\n   /**\n    * Cloud Big Data\n    */\n   public static final String BIG_DATA = \"rax:bigdata\";\n\n   /**\n    * CDN\n    */\n   public static final String CDN = \"rax:cdn\";\n\n   /**\n    * Orchestration (Openstack Heat)\n    */\n   public static final String ORCHESTRATION = \"orchestration\";\n\n   private ServiceType() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudidentity/src/main/java/org/jclouds/rackspace/cloudidentity/v2_0/config/CloudIdentityAuthenticationModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudidentity.v2_0.config;\n\nimport static org.jclouds.rest.config.BinderUtils.bindHttpApi;\n\nimport java.util.Map;\n\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.openstack.keystone.auth.AuthenticationApi;\nimport org.jclouds.openstack.keystone.auth.config.AuthenticationModule;\nimport org.jclouds.openstack.keystone.auth.config.CredentialTypes;\nimport org.jclouds.openstack.keystone.auth.domain.AuthInfo;\nimport org.jclouds.openstack.keystone.auth.functions.AuthenticatePasswordCredentials;\nimport org.jclouds.rackspace.cloudidentity.v2_0.CloudIdentityAuthenticationApi;\nimport org.jclouds.rackspace.cloudidentity.v2_0.functions.AuthenticateApiKeyCredentials;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\nimport com.google.common.collect.Maps;\nimport com.google.inject.Injector;\n\npublic class CloudIdentityAuthenticationModule extends AuthenticationModule {\n\n   @Override\n   protected void configure() {\n      super.configure();\n      bindHttpApi(binder(), CloudIdentityAuthenticationApi.class);\n   }\n\n   @Override\n   protected Map<String, AuthenticationApi> authenticationApis(Injector i) {\n      Map<String, AuthenticationApi> authenticationApis = Maps.newHashMap();\n      authenticationApis.put(\"2\", i.getInstance(CloudIdentityAuthenticationApi.class));\n      authenticationApis.put(\"3\", i.getInstance(CloudIdentityAuthenticationApi.class));\n      return authenticationApis;\n   }\n\n   @Override\n   protected Map<String, Function<Credentials, AuthInfo>> authenticationMethods(Injector i) {\n      Builder<Function<Credentials, AuthInfo>> fns = ImmutableSet.<Function<Credentials, AuthInfo>> builder();\n      fns.add(i.getInstance(AuthenticatePasswordCredentials.class));\n      fns.add(i.getInstance(AuthenticateApiKeyCredentials.class));\n      return CredentialTypes.indexByCredentialType(fns.build());\n   }\n\n}\n"
  },
  {
    "path": "apis/rackspace-cloudidentity/src/main/java/org/jclouds/rackspace/cloudidentity/v2_0/config/CloudIdentityCredentialTypes.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudidentity.v2_0.config;\n\nimport org.jclouds.openstack.keystone.auth.config.CredentialTypes;\n\n\npublic class CloudIdentityCredentialTypes extends CredentialTypes {\n\n   public static final String API_KEY_CREDENTIALS = \"RAX-KSKEY:apiKeyCredentials\";\n\n}\n"
  },
  {
    "path": "apis/rackspace-cloudidentity/src/main/java/org/jclouds/rackspace/cloudidentity/v2_0/domain/ApiKeyCredentials.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudidentity.v2_0.domain;\n\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.openstack.keystone.auth.config.CredentialType;\nimport org.jclouds.rackspace.cloudidentity.v2_0.config.CloudIdentityCredentialTypes;\n\nimport com.google.common.base.Objects;\n\n/**\n * ApiKey Credentials\n * \n * @see <a href=\"http://docs.rackspace.com/servers/api/v2/cs-devguide/content/curl_auth.html\">docs</a>\n\n */\n@CredentialType(CloudIdentityCredentialTypes.API_KEY_CREDENTIALS)\npublic class ApiKeyCredentials {\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().fromApiKeyCredentials(this);\n   }\n\n   public static ApiKeyCredentials createWithUsernameAndApiKey(String username, String apiKey) {\n      return builder().apiKey(apiKey).username(username).build();\n   }\n\n   public static class Builder {\n      protected String username;\n      protected String apiKey;\n\n      /**\n       * @see ApiKeyCredentials#getUsername()\n       */\n      protected Builder apiKey(String apiKey) {\n         this.apiKey = apiKey;\n         return this;\n      }\n\n      /**\n       * @see ApiKeyCredentials#getApiKey()\n       */\n      public Builder username(String username) {\n         this.username = username;\n         return this;\n      }\n\n      public ApiKeyCredentials build() {\n         return new ApiKeyCredentials(username, apiKey);\n      }\n\n      public Builder fromApiKeyCredentials(ApiKeyCredentials from) {\n         return username(from.getUsername()).apiKey(from.getApiKey());\n      }\n   }\n\n   protected final String username;\n   protected final String apiKey;\n\n   protected ApiKeyCredentials(String username, String apiKey) {\n      this.username = checkNotNull(username, \"username\");\n      this.apiKey = checkNotNull(apiKey, \"apiKey\");\n   }\n\n   /**\n    * @return the username\n    */\n   public String getUsername() {\n      return username;\n   }\n\n   /**\n    * @return the apiKey\n    */\n   public String getApiKey() {\n      return apiKey;\n   }\n\n   @Override\n   public boolean equals(Object object) {\n      if (this == object) {\n         return true;\n      }\n      if (object instanceof ApiKeyCredentials) {\n         final ApiKeyCredentials other = ApiKeyCredentials.class.cast(object);\n         return equal(username, other.username) && equal(apiKey, other.apiKey);\n      } else {\n         return false;\n      }\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(username, apiKey);\n   }\n\n   @Override\n   public String toString() {\n      return toStringHelper(\"\").add(\"username\", username).add(\"apiKey\", apiKey).toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/rackspace-cloudidentity/src/main/java/org/jclouds/rackspace/cloudidentity/v2_0/functions/AuthenticateApiKeyCredentials.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudidentity.v2_0.functions;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.openstack.keystone.auth.config.CredentialType;\nimport org.jclouds.openstack.keystone.auth.domain.AuthInfo;\nimport org.jclouds.openstack.keystone.auth.domain.TenantOrDomainAndCredentials;\nimport org.jclouds.openstack.keystone.auth.functions.BaseAuthenticator;\nimport org.jclouds.rackspace.cloudidentity.v2_0.CloudIdentityAuthenticationApi;\nimport org.jclouds.rackspace.cloudidentity.v2_0.config.CloudIdentityCredentialTypes;\nimport org.jclouds.rackspace.cloudidentity.v2_0.domain.ApiKeyCredentials;\n\n/**\n * \n * @see <a\n *      href=\"http://docs.rackspace.com/servers/api/v2/cs-devguide/content/curl_auth.html\">docs</a>\n */\n@CredentialType(CloudIdentityCredentialTypes.API_KEY_CREDENTIALS)\n@Singleton\npublic class AuthenticateApiKeyCredentials extends BaseAuthenticator<ApiKeyCredentials> {\n   protected final CloudIdentityAuthenticationApi api;\n\n   @Inject\n   AuthenticateApiKeyCredentials(CloudIdentityAuthenticationApi api) {\n      this.api = api;\n   }\n\n   @Override\n   public ApiKeyCredentials createCredentials(String identity, String credential) {\n      return ApiKeyCredentials.createWithUsernameAndApiKey(identity, credential);\n   }\n\n   @Override\n   public String toString() {\n      return \"authenticateApiKeyCredentials()\";\n   }\n\n   @Override\n   public AuthInfo authenticate(TenantOrDomainAndCredentials<ApiKeyCredentials> credentials) {\n      return api.authenticateApiKey(credentials);\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudidentity/src/main/java/org/jclouds/rackspace/cloudidentity/v2_0/functions/DateParser.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudidentity.v2_0.functions;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Date;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.date.DateService;\n\nimport com.google.common.base.Function;\n\n/**\n * Takes a Date and return a yyyy-MM-dd String.\n */\n@Singleton\npublic class DateParser implements Function<Object, String> {\n   \n   private final DateService dateService;\n   \n   @Inject\n   DateParser(DateService dateService) {\n      this.dateService = dateService;\n   }\n   \n   @Override\n   public String apply(Object input) {\n      checkArgument(checkNotNull(input, \"input\") instanceof Date, \"This function is only valid for Dates!\");\n      Date date = Date.class.cast(input);\n\n      return dateService.iso8601SecondsDateFormat(date);\n   }\n\n}\n"
  },
  {
    "path": "apis/rackspace-cloudidentity/src/test/java/org/jclouds/rackspace/cloudidentity/v2_0/CloudIdentityApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudidentity.v2_0;\n\nimport org.jclouds.openstack.keystone.v2_0.KeystoneApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"CloudIdentityApiLiveTest\", singleThreaded = true)\npublic class CloudIdentityApiLiveTest extends KeystoneApiLiveTest {\n   public CloudIdentityApiLiveTest() {\n      provider = \"rackspace-cloudidentity\";\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudidentity/src/test/java/org/jclouds/rackspace/cloudidentity/v2_0/CloudIdentityApiMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudidentity.v2_0;\n\nimport org.jclouds.View;\nimport org.jclouds.apis.internal.BaseApiMetadataTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.reflect.TypeToken;\n\n@Test(groups = \"unit\", testName = \"CloudIdentityApiMetadataTest\")\npublic class CloudIdentityApiMetadataTest extends BaseApiMetadataTest {\n\n   // no identity abstraction, yet\n   public CloudIdentityApiMetadataTest() {\n      super(new CloudIdentityApiMetadata(), ImmutableSet.<TypeToken<? extends View>> of());\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudidentity/src/test/java/org/jclouds/rackspace/cloudidentity/v2_0/features/CloudIdentityServiceApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudidentity.v2_0.features;\n\nimport org.jclouds.openstack.keystone.v2_0.features.ServiceApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"CloudIdentityServiceApiLiveTest\", singleThreaded = true)\npublic class CloudIdentityServiceApiLiveTest extends ServiceApiLiveTest {\n   public CloudIdentityServiceApiLiveTest() {\n      provider = \"rackspace-cloudidentity\";\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudidentity/src/test/java/org/jclouds/rackspace/cloudidentity/v2_0/internal/RackspaceFixture.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudidentity.v2_0.internal;\n\nimport static java.lang.String.format;\nimport static org.jclouds.rest.internal.BaseRestApiExpectTest.payloadFromStringWithContentType;\n\nimport java.io.IOException;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.io.Payload;\nimport org.jclouds.util.Strings2;\n\nimport com.google.common.base.Throwables;\nimport com.google.common.net.HttpHeaders;\n\npublic enum RackspaceFixture {\n   INSTANCE;\n\n   public String getTenantId() {\n      return \"123123\";\n   }\n\n   public String getTenantName() {\n      return \"123123\";\n   }\n\n   public HttpRequest initialAuthWithUsernameAndApiKey(String username, String apiKey) {\n      return HttpRequest\n            .builder()\n            .method(\"POST\")\n            .endpoint(\"https://identity.api.rackspacecloud.com/v2.0/tokens\")\n            .addHeader(HttpHeaders.ACCEPT, \"application/json\")\n            .payload(payloadFromStringWithContentType(\n                  format(\"{\\\"auth\\\":{\\\"RAX-KSKEY:apiKeyCredentials\\\":{\\\"username\\\":\\\"%s\\\",\\\"apiKey\\\":\\\"%s\\\"}}}\",\n                         username, apiKey), \"application/json\")).build();\n   }\n\n   public String getAuthToken() {\n      return \"cd562fe2-1f0f-43a7-a898-98cb8ede3eb3\";\n   }\n\n   public HttpResponse responseWithAccess() {\n      return HttpResponse.builder()\n            .statusCode(200)\n            .message(\"HTTP/1.1 200\")\n            .payload(payloadFromResourceWithContentType(\"/rackspaceAuthResponse.json\", \"application/json\"))\n            .build();\n   }\n\n   public Payload payloadFromResourceWithContentType(String resource, String contentType) {\n      try {\n         return payloadFromStringWithContentType(\n               Strings2.toStringAndClose(getClass().getResourceAsStream(resource)), contentType);\n      }\n      catch (IOException e) {\n         throw Throwables.propagate(e);\n      }\n\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudidentity/src/test/resources/rackspaceAuthResponse.json",
    "content": "{\n  \"access\": {\n    \"user\": {\n      \"RAX-AUTH:defaultRegion\": \"DFW\",\n      \"name\": \"user4jclouds\",\n      \"roles\": [\n        {\n          \"name\": \"identity:user-admin\",\n          \"description\": \"User Admin Role.\",\n          \"id\": \"3\"\n        }\n      ],\n      \"id\": \"224085\"\n    },\n    \"serviceCatalog\": [\n      {\n        \"type\": \"object-store\",\n        \"name\": \"cloudFiles\",\n        \"endpoints\": [\n          {\n            \"internalURL\": \"https://snet-storage101.dfw1.clouddrive.com/v1/MossoCloudFS_5bcf386e-39dd-45ff-93a1-712b9aba90a9\",\n            \"publicURL\": \"https://storage101.dfw1.clouddrive.com/v1/MossoCloudFS_5bcf386e-39dd-45ff-93a1-712b9aba90a9\",\n            \"tenantId\": \"MossoCloudFS_5bcf386e-39dd-45ff-93a1-712b9aba90a9\",\n            \"region\": \"DFW\"\n          },\n          {\n            \"internalURL\": \"https://snet-storage101.ord1.clouddrive.com/v1/MossoCloudFS_5bcf386e-39dd-45ff-93a1-712b9aba90a9\",\n            \"publicURL\": \"https://storage101.ord1.clouddrive.com/v1/MossoCloudFS_5bcf386e-39dd-45ff-93a1-712b9aba90a9\",\n            \"tenantId\": \"MossoCloudFS_5bcf386e-39dd-45ff-93a1-712b9aba90a9\",\n            \"region\": \"ORD\"\n          }\n        ]\n      },\n      {\n        \"type\": \"rax:load-balancer\",\n        \"name\": \"cloudLoadBalancers\",\n        \"endpoints\": [\n          {\n            \"publicURL\": \"https://ord.loadbalancers.api.rackspacecloud.com/v1.0/123123\",\n            \"tenantId\": \"123123\",\n            \"region\": \"ORD\"\n          },\n          {\n            \"publicURL\": \"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123\",\n            \"tenantId\": \"123123\",\n            \"region\": \"DFW\"\n          }\n        ]\n      },\n      {\n        \"type\": \"rax:dns\",\n        \"name\": \"cloudDNS\",\n        \"endpoints\": [\n          {\n            \"publicURL\": \"https://dns.api.rackspacecloud.com/v1.0/123123\",\n            \"tenantId\": \"123123\"\n          }\n        ]\n      },\n      {\n        \"type\": \"rax:database\",\n        \"name\": \"cloudDatabases\",\n        \"endpoints\": [\n          {\n            \"publicURL\": \"https://dfw.databases.api.rackspacecloud.com/v1.0/123123\",\n            \"tenantId\": \"123123\",\n            \"region\": \"DFW\"\n          },\n          {\n            \"publicURL\": \"https://ord.databases.api.rackspacecloud.com/v1.0/123123\",\n            \"tenantId\": \"123123\",\n            \"region\": \"ORD\"\n          }\n        ]\n      },\n      {\n        \"type\": \"rax:object-cdn\",\n        \"name\": \"cloudFilesCDN\",\n        \"endpoints\": [\n          {\n            \"publicURL\": \"https://cdn1.clouddrive.com/v1/MossoCloudFS_5bcf386e-39dd-45ff-93a1-712b9aba90a9\",\n            \"tenantId\": \"MossoCloudFS_5bcf386e-39dd-45ff-93a1-712b9aba90a9\",\n            \"region\": \"DFW\"\n          },\n          {\n            \"publicURL\": \"https://cdn2.clouddrive.com/v1/MossoCloudFS_5bcf386e-39dd-45ff-93a1-712b9aba90a9\",\n            \"tenantId\": \"MossoCloudFS_5bcf386e-39dd-45ff-93a1-712b9aba90a9\",\n            \"region\": \"ORD\"\n          }\n        ]\n      },\n      {\n        \"type\": \"rax:monitor\",\n        \"name\": \"cloudMonitoring\",\n        \"endpoints\": [\n          {\n            \"publicURL\": \"https://monitoring.api.rackspacecloud.com/v1.0/123123\",\n            \"tenantId\": \"123123\"\n          }\n        ]\n      },\n      {\n        \"type\": \"compute\",\n        \"name\": \"cloudServers\",\n        \"endpoints\": [\n          {\n            \"versionId\": \"1.0\",\n            \"versionList\": \"https://servers.api.rackspacecloud.com/\",\n            \"versionInfo\": \"https://servers.api.rackspacecloud.com/v1.0\",\n            \"publicURL\": \"https://servers.api.rackspacecloud.com/v1.0/123123\",\n            \"tenantId\": \"123123\"\n          }\n        ]\n      },\n      {\n        \"type\": \"compute\",\n        \"name\": \"cloudServersOpenStack\",\n        \"endpoints\": [\n          {\n            \"versionId\": \"2\",\n            \"versionList\": \"https://dfw.servers.api.rackspacecloud.com/\",\n            \"versionInfo\": \"https://dfw.servers.api.rackspacecloud.com/v2\",\n            \"publicURL\": \"https://dfw.servers.api.rackspacecloud.com/v2/123123\",\n            \"tenantId\": \"123123\",\n            \"region\": \"DFW\"\n          },\n          {\n            \"versionId\": \"2\",\n            \"versionList\": \"https://ord.servers.api.rackspacecloud.com/\",\n            \"versionInfo\": \"https://ord.servers.api.rackspacecloud.com/v2\",\n            \"publicURL\": \"https://ord.servers.api.rackspacecloud.com/v2/123123\",\n            \"tenantId\": \"123123\",\n            \"region\": \"ORD\"\n          }\n        ]\n      },\n      {\n        \"type\": \"volume\",\n        \"name\": \"cloudBlockStorage\",\n        \"endpoints\": [\n          {\n            \"publicURL\": \"https://ord.blockstorage.api.rackspacecloud.com/v1/123123\",\n            \"tenantId\": \"123123\",\n            \"region\": \"ORD\"\n          },\n          {\n            \"publicURL\": \"https://dfw.blockstorage.api.rackspacecloud.com/v1/123123\",\n            \"tenantId\": \"123123\",\n            \"region\": \"DFW\"\n          }\n        ]\n      },\n      {\n        \"type\": \"rax:queues\",\n        \"name\": \"cloudQueues\",\n        \"endpoints\": [\n          {\n            \"internalURL\": \"https://snet-ord.queues.api.rackspacecloud.com/v1/123123\",\n            \"publicURL\": \"https://ord.queues.api.rackspacecloud.com/v1/123123\",\n            \"tenantId\": \"123123\",\n            \"region\": \"ORD\"\n          },\n          {\n            \"internalURL\": \"https://snet-dfw.queues.api.rackspacecloud.com/v1/123123\",\n            \"publicURL\": \"https://dfw.queues.api.rackspacecloud.com/v1/123123\",\n            \"tenantId\": \"123123\",\n            \"region\": \"DFW\"\n          }\n        ]\n      }\n    ],\n    \"token\": {\n      \"tenant\": {\n        \"name\": \"123123\",\n        \"id\": \"123123\"\n      },\n      \"expires\": \"2012-12-01T17:07:47.000-06:00\",\n      \"id\": \"cd562fe2-1f0f-43a7-a898-98cb8ede3eb3\"\n    }\n  }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.rackspace.cloudloadbalancers.v1.*;version=\"${project.version}\";-noimport:=true"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.api</groupId>\n  <artifactId>rackspace-cloudloadbalancers</artifactId>\n  <name>jclouds Rackspace Cloud Load Balancers API</name>\n  <description>Cloud Load Balancers API for Rackspace</description>\n\n  <properties>\n    <test.rackspace-cloudloadbalancers.endpoint>https://identity.api.rackspacecloud.com/v2.0/</test.rackspace-cloudloadbalancers.endpoint>\n    <test.rackspace-cloudloadbalancers.api-version>1</test.rackspace-cloudloadbalancers.api-version>\n    <test.rackspace-cloudloadbalancers.build-version />\n    <test.rackspace-cloudloadbalancers.identity>${test.rackspace-us.identity}</test.rackspace-cloudloadbalancers.identity>\n    <test.rackspace-cloudloadbalancers.credential>${test.rackspace-us.credential}</test.rackspace-cloudloadbalancers.credential>\n  </properties>\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-loadbalancer</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-keystone</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>rackspace-cloudidentity</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-loadbalancer</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-keystone</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>rackspace-cloudidentity</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-slf4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>ch.qos.logback</groupId>\n      <artifactId>logback-classic</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.rackspace-cloudloadbalancers.endpoint>${test.rackspace-cloudloadbalancers.endpoint}</test.rackspace-cloudloadbalancers.endpoint>\n                    <test.rackspace-cloudloadbalancers.api-version>${test.rackspace-cloudloadbalancers.api-version}</test.rackspace-cloudloadbalancers.api-version>\n                    <test.rackspace-cloudloadbalancers.build-version>${test.rackspace-cloudloadbalancers.build-version}</test.rackspace-cloudloadbalancers.build-version>\n                    <test.rackspace-cloudloadbalancers.identity>${test.rackspace-cloudloadbalancers.identity}</test.rackspace-cloudloadbalancers.identity>\n                    <test.rackspace-cloudloadbalancers.credential>${test.rackspace-cloudloadbalancers.credential}</test.rackspace-cloudloadbalancers.credential>\n                    <test.jclouds.keystone.credential-type>${test.jclouds.keystone.credential-type}</test.jclouds.keystone.credential-type>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/CloudLoadBalancersApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1;\n\nimport java.io.Closeable;\nimport java.util.Set;\n\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\n\nimport org.jclouds.location.Region;\nimport org.jclouds.location.functions.RegionToEndpoint;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.features.AccessRuleApi;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.features.ConnectionApi;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.features.ContentCachingApi;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.features.ErrorPageApi;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.features.HealthMonitorApi;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.features.LoadBalancerApi;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.features.NodeApi;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.features.ReportApi;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.features.SSLTerminationApi;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.features.SessionPersistenceApi;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.features.VirtualIPApi;\nimport org.jclouds.rest.annotations.Delegate;\nimport org.jclouds.rest.annotations.EndpointParam;\n\nimport com.google.inject.Provides;\n\n/**\n * Provides access to Rackspace Cloud Load Balancers.\n * <p/>\n */\npublic interface CloudLoadBalancersApi extends Closeable {\n   /**\n    * @return the Region codes configured\n    */\n   @Provides\n   @Region\n   Set<String> getConfiguredRegions();\n\n   /**\n    * Provides access to Load Balancer features.\n    */\n   @Delegate\n   LoadBalancerApi getLoadBalancerApi(\n         @EndpointParam(parser = RegionToEndpoint.class) String region);\n\n   /**\n    * Provides access to Node features.\n    */\n   @Delegate\n   @Path(\"/loadbalancers/{lbId}\")\n   NodeApi getNodeApi(\n         @EndpointParam(parser = RegionToEndpoint.class) String region, @PathParam(\"lbId\") int lbId);\n\n   /**\n    * Provides access to Access Rule features.\n    */\n   @Delegate\n   @Path(\"/loadbalancers/{lbId}\")\n   AccessRuleApi getAccessRuleApi(\n         @EndpointParam(parser = RegionToEndpoint.class) String region, @PathParam(\"lbId\") int lbId);\n\n   /**\n    * Provides access to Virtual IP features.\n    */\n   @Delegate\n   @Path(\"/loadbalancers/{lbId}\")\n   VirtualIPApi getVirtualIPApi(\n         @EndpointParam(parser = RegionToEndpoint.class) String region, @PathParam(\"lbId\") int lbId);\n\n   /**\n    * Provides access to Connection features.\n    */\n   @Delegate\n   @Path(\"/loadbalancers/{lbId}\")\n   ConnectionApi getConnectionApi(\n         @EndpointParam(parser = RegionToEndpoint.class) String region, @PathParam(\"lbId\") int lbId);\n\n   /**\n    * Provides access to Health Monitor features.\n    */\n   @Delegate\n   @Path(\"/loadbalancers/{lbId}\")\n   HealthMonitorApi getHealthMonitorApi(\n         @EndpointParam(parser = RegionToEndpoint.class) String region, @PathParam(\"lbId\") int lbId);\n\n   /**\n    * Provides access to Session Persistence features.\n    */\n   @Delegate\n   @Path(\"/loadbalancers/{lbId}\")\n   SessionPersistenceApi getSessionPersistenceApi(\n         @EndpointParam(parser = RegionToEndpoint.class) String region, @PathParam(\"lbId\") int lbId);\n\n   /**\n    * Provides access to Content Caching features.\n    */\n   @Delegate\n   @Path(\"/loadbalancers/{lbId}\")\n   ContentCachingApi getContentCachingApi(\n         @EndpointParam(parser = RegionToEndpoint.class) String region, @PathParam(\"lbId\") int lbId);\n\n   /**\n    * Provides access to SSL Termination features.\n    */\n   @Delegate\n   @Path(\"/loadbalancers/{lbId}\")\n   SSLTerminationApi getSSLTerminationApi(\n         @EndpointParam(parser = RegionToEndpoint.class) String region, @PathParam(\"lbId\") int lbId);\n\n   /**\n    * Provides access to Error Page features.\n    */\n   @Delegate\n   @Path(\"/loadbalancers/{lbId}\")\n   ErrorPageApi getErrorPageApi(\n         @EndpointParam(parser = RegionToEndpoint.class) String region, @PathParam(\"lbId\") int lbId);\n\n   /**\n    * Provides access to Report features.\n    */\n   @Delegate\n   ReportApi getReportApi(@EndpointParam(parser = RegionToEndpoint.class) String region);\n\n   /**\n    * @return the Zone codes configured\n    * @deprecated Please use {@link #getConfiguredRegions()} instead. To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   @Provides\n   @Region\n   Set<String> getConfiguredZones();\n\n   /**\n    * Provides access to Load Balancer features.\n    * @deprecated Please use {@link #getLoadBalancerApi(String region)} instead. To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   @Delegate\n   LoadBalancerApi getLoadBalancerApiForZone(\n         @EndpointParam(parser = RegionToEndpoint.class) String zone);\n\n   /**\n    * Provides access to Node features.\n    * @deprecated Please use {@link #getNodeApi(String, int)} instead.\n    *             To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   @Delegate\n   @Path(\"/loadbalancers/{lbId}\")\n   NodeApi getNodeApiForZoneAndLoadBalancer(\n         @EndpointParam(parser = RegionToEndpoint.class) String zone, @PathParam(\"lbId\") int lbId);\n\n   /**\n    * Provides access to Access Rule features.\n    * @deprecated Please use {@link #getAccessRuleApi(String region, int lbId)} instead. To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   @Delegate\n   @Path(\"/loadbalancers/{lbId}\")\n   AccessRuleApi getAccessRuleApiForZoneAndLoadBalancer(\n         @EndpointParam(parser = RegionToEndpoint.class) String zone, @PathParam(\"lbId\") int lbId);\n\n   /**\n    * Provides access to Virtual IP features.\n    * @deprecated Please use {@link #getVirtualIPApi(String region, int lbId)} instead. To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   @Delegate\n   @Path(\"/loadbalancers/{lbId}\")\n   VirtualIPApi getVirtualIPApiForZoneAndLoadBalancer(\n         @EndpointParam(parser = RegionToEndpoint.class) String zone, @PathParam(\"lbId\") int lbId);\n\n   /**\n    * Provides access to Connection features.\n    * @deprecated Please use {@link #getConnectionApi(String region, int lbId)} instead. To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   @Delegate\n   @Path(\"/loadbalancers/{lbId}\")\n   ConnectionApi getConnectionApiForZoneAndLoadBalancer(\n         @EndpointParam(parser = RegionToEndpoint.class) String zone, @PathParam(\"lbId\") int lbId);\n\n   /**\n    * Provides access to Health Monitor features.\n    * @deprecated Please use {@link #getHealthMonitorApi(String region, int lbId)} instead. \n    *             To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   @Delegate\n   @Path(\"/loadbalancers/{lbId}\")\n   HealthMonitorApi getHealthMonitorApiForZoneAndLoadBalancer(\n         @EndpointParam(parser = RegionToEndpoint.class) String zone, @PathParam(\"lbId\") int lbId);\n\n   /**\n    * Provides access to Session Persistence features.\n    * @deprecated Please use {@link #getSessionPersistenceApi(String region, int lbId)} instead.\n    *             To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   @Delegate\n   @Path(\"/loadbalancers/{lbId}\")\n   SessionPersistenceApi getSessionPersistenceApiForZoneAndLoadBalancer(\n         @EndpointParam(parser = RegionToEndpoint.class) String zone, @PathParam(\"lbId\") int lbId);\n\n   /**\n    * Provides access to Content Caching features.\n    * @deprecated Please use {@link #getContentCachingApi(String region, int lbId)} instead.\n    *             To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   @Delegate\n   @Path(\"/loadbalancers/{lbId}\")\n   ContentCachingApi getContentCachingApiForZoneAndLoadBalancer(\n         @EndpointParam(parser = RegionToEndpoint.class) String zone, @PathParam(\"lbId\") int lbId);\n\n   /**\n    * Provides access to SSL Termination features.\n    * @deprecated Please use {@link #getSSLTerminationApi(String region, int lbId)} instead.\n    *             To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   @Delegate\n   @Path(\"/loadbalancers/{lbId}\")\n   SSLTerminationApi getSSLTerminationApiForZoneAndLoadBalancer(\n         @EndpointParam(parser = RegionToEndpoint.class) String zone, @PathParam(\"lbId\") int lbId);\n\n   /**\n    * Provides access to Error Page features.\n    * @deprecated Please use {@link #getErrorPageApi(String region, int lbId)} instead. To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   @Delegate\n   @Path(\"/loadbalancers/{lbId}\")\n   ErrorPageApi getErrorPageApiForZoneAndLoadBalancer(\n         @EndpointParam(parser = RegionToEndpoint.class) String zone, @PathParam(\"lbId\") int lbId);\n\n   /**\n    * Provides access to Report features.\n    * @deprecated Please use {@link #getReportApi(String region)} instead. To be removed in jclouds 2.0.\n    */\n   @Deprecated\n   @Delegate\n   ReportApi getReportApiForZone(\n         @EndpointParam(parser = RegionToEndpoint.class) String zone);\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/CloudLoadBalancersApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1;\n\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.CREDENTIAL_TYPE;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.KEYSTONE_VERSION;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.SERVICE_TYPE;\nimport static org.jclouds.reflect.Reflection2.typeToken;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.loadbalancer.LoadBalancerServiceContext;\nimport org.jclouds.openstack.keystone.catalog.config.ServiceCatalogModule;\nimport org.jclouds.openstack.keystone.catalog.config.ServiceCatalogModule.RegionModule;\nimport org.jclouds.rackspace.cloudidentity.v2_0.ServiceType;\nimport org.jclouds.rackspace.cloudidentity.v2_0.config.CloudIdentityAuthenticationModule;\nimport org.jclouds.rackspace.cloudidentity.v2_0.config.CloudIdentityCredentialTypes;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.config.CloudLoadBalancersHttpApiModule;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.loadbalancer.config.CloudLoadBalancersLoadBalancerContextModule;\nimport org.jclouds.rest.internal.BaseHttpApiMetadata;\n\nimport com.google.auto.service.AutoService;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n/**\n * Implementation of {@link ApiMetadata} for the Rackspace Cloud Load Balancers v1.0 API.\n */\n@AutoService(ApiMetadata.class)\npublic class CloudLoadBalancersApiMetadata extends BaseHttpApiMetadata<CloudLoadBalancersApi> {\n\n   @Override\n   public Builder toBuilder() {\n      return new Builder().fromApiMetadata(this);\n   }\n\n   public CloudLoadBalancersApiMetadata() {\n      this(new Builder());\n   }\n\n   protected CloudLoadBalancersApiMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = BaseHttpApiMetadata.defaultProperties();\n      properties.setProperty(SERVICE_TYPE, ServiceType.LOAD_BALANCERS);\n      properties.setProperty(CREDENTIAL_TYPE, CloudIdentityCredentialTypes.API_KEY_CREDENTIALS);\n      properties.setProperty(KEYSTONE_VERSION, \"2\");\n      return properties;\n   }\n\n   public static class Builder extends BaseHttpApiMetadata.Builder<CloudLoadBalancersApi, Builder> {\n\n      protected Builder() {\n         id(\"rackspace-cloudloadbalancers\")\n               .name(\"Rackspace Cloud Load Balancers API\")\n               .identityName(\"Username\")\n               .credentialName(\"API Key\")\n               .documentation(URI.create(\"http://docs.rackspace.com/loadbalancers/api/clb-devguide-latest/index.html\"))\n               .version(\"1.0\")\n               .defaultEndpoint(\"https://identity.api.rackspacecloud.com/v2.0/\")\n               .defaultProperties(CloudLoadBalancersApiMetadata.defaultProperties())\n               .view(typeToken(LoadBalancerServiceContext.class))\n               .defaultModules(ImmutableSet.<Class<? extends Module>>builder()\n                            .add(CloudIdentityAuthenticationModule.class)\n                            .add(ServiceCatalogModule.class)\n                            .add(RegionModule.class)\n                            .add(CloudLoadBalancersHttpApiModule.class)\n                            .add(CloudLoadBalancersLoadBalancerContextModule.class).build());\n      }\n\n      @Override\n      public CloudLoadBalancersApiMetadata build() {\n         return new CloudLoadBalancersApiMetadata(this);\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/binders/BindMetadataToJsonPayload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.json.Json;\nimport org.jclouds.rest.Binder;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Lists;\n\n/**\n * Binds the metadata to the request as a JSON payload.\n */\n@Singleton\npublic class BindMetadataToJsonPayload implements Binder {\n\n   protected final Json jsonBinder;\n\n   @Inject\n   public BindMetadataToJsonPayload(Json jsonBinder) {\n      this.jsonBinder = checkNotNull(jsonBinder, \"jsonBinder\");\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkArgument(checkNotNull(input, \"input\") instanceof Map, \"This binder is only valid for Map<String, String>\");\n      checkNotNull(request, \"request\");\n\n      Map<String, String> metadata = (Map<String, String>) input;\n      List<Map<String, String>> clbMetadata = Lists.newArrayList();\n      \n      for (Map.Entry<String, String> entry : metadata.entrySet()) {\n         clbMetadata.add(ImmutableMap.<String, String> of(\n               \"key\", entry.getKey(),\n               \"value\", entry.getValue()));\n      }\n      \n      String json = jsonBinder.toJson(ImmutableMap.of(\"metadata\", clbMetadata));\n      request.setPayload(json);\n      request.getPayload().getContentMetadata().setContentType(\"application/json\");\n      return request;\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/config/CloudLoadBalancersHttpApiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.config;\n\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.annotation.ClientError;\nimport org.jclouds.http.annotation.Redirection;\nimport org.jclouds.http.annotation.ServerError;\nimport org.jclouds.json.config.GsonModule.DateAdapter;\nimport org.jclouds.json.config.GsonModule.Iso8601DateAdapter;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.CloudLoadBalancersApi;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.functions.ConvertLB;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.handlers.ParseCloudLoadBalancersErrorFromHttpResponse;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.config.HttpApiModule;\n\nimport com.google.inject.assistedinject.FactoryModuleBuilder;\n\n/**\n * Configures the Rackspace Cloud Load Balancers connection.\n */\n@ConfiguresHttpApi\npublic class CloudLoadBalancersHttpApiModule extends HttpApiModule<CloudLoadBalancersApi> {\n\n   @Override\n   protected void configure() {\n      bind(DateAdapter.class).to(Iso8601DateAdapter.class);\n      install(new FactoryModuleBuilder().build(ConvertLB.Factory.class));\n      super.configure();\n   }\n\n   @Override\n   protected void bindErrorHandlers() {\n      bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(\n            ParseCloudLoadBalancersErrorFromHttpResponse.class);\n      bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(\n            ParseCloudLoadBalancersErrorFromHttpResponse.class);\n      bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(\n            ParseCloudLoadBalancersErrorFromHttpResponse.class);\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/domain/AccessRule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * The access rule management feature allows fine-grained network access controls to be applied to the load balancer's \n * virtual IP address. A single IP address, multiple IP addresses, or entire network subnets can be added as an access\n * rule. Rules that are configured with the ALLOW type will always take precedence over rules with the DENY type. To \n * reject traffic from all rules except for those with the ALLOW type, add an access rule with an address of \n * \"0.0.0.0/0\" and a DENY type.\n */\npublic class AccessRule {\n\n   private final Type type;\n   private final String address;\n   \n   /**\n    * Use this method to easily construct {@link Type#ALLOW} rules for the address.\n    */\n   public static AccessRule allow(String address) {\n      return new AccessRule(address, Type.ALLOW);\n   }\n   \n   /**\n    * Use this method to easily construct {@link Type#DENY} rules for the address.\n    */\n   public static AccessRule deny(String address) {\n      return new AccessRule(address, Type.DENY);\n   }\n\n   public AccessRule(String address, Type type) {\n      this.address = checkNotNull(address, \"address\");\n      this.type = checkNotNull(type, \"type\");\n   }\n\n   public String getAddress() {\n      return this.address;\n   }\n\n   public Type getType() {\n      return this.type;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(address);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      AccessRule that = AccessRule.class.cast(obj);\n      \n      return Objects.equal(this.address, that.address);\n   }\n   \n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).omitNullValues()\n            .add(\"address\", address).add(\"type\", type);\n   }\n   \n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   public static enum Type {\n      /**\n       * Specifies rules that will always take precedence over rules with the DENY type.\n       */\n      ALLOW, \n      \n      /**\n       * Specifies rules to which traffic can be denied.\n       */\n      DENY, \n      \n      UNRECOGNIZED;\n      \n      public static Type fromValue(String type) {\n         try {\n            return valueOf(checkNotNull(type, \"type\"));\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/domain/AccessRuleWithId.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.domain;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * The same as {@link AccessRule} but this will have an id as assigned by the Cloud Load Balancers service.\n */\npublic class AccessRuleWithId extends AccessRule {\n\n   private final int id;\n\n   public AccessRuleWithId(int id, String address, Type type) {\n      super(address, type);\n      this.id = id;\n   }\n\n   public int getId() {\n      return this.id;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      AccessRuleWithId that = AccessRuleWithId.class.cast(obj);\n      \n      return Objects.equal(this.id, that.id);\n   }\n   \n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).omitNullValues()\n            .add(\"id\", id).add(\"address\", getAddress()).add(\"type\", getType());\n   }\n   \n   @Override\n   public String toString() {\n      return string().toString();\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/domain/AccountUsage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.Optional;\n\npublic final class AccountUsage {\n   private final int numPublicVIPs;\n   private final int numServiceNetVIPs;\n   private final int numLoadBalancers;\n   private final Date startTime;\n   private final Optional<Date> endTime;\n\n   @ConstructorProperties({ \"numPublicVips\", \"numServicenetVips\", \"numLoadBalancers\", \"startTime\", \"endTime\" })\n   protected AccountUsage(int numPublicVIPs, int numServiceNetVIPs, int numLoadBalancers, Date startTime, Date endTime) {\n      this.numPublicVIPs = numPublicVIPs;\n      this.numServiceNetVIPs = numServiceNetVIPs;\n      this.numLoadBalancers = numLoadBalancers;\n      this.startTime = checkNotNull(startTime, \"startTime\");\n      this.endTime = Optional.fromNullable(endTime);\n   }\n\n   public int getNumPublicVIPs() {\n      return numPublicVIPs;\n   }\n\n   public int getNumServiceNetVIPs() {\n      return numServiceNetVIPs;\n   }\n\n   public int getNumLoadBalancers() {\n      return numLoadBalancers;\n   }\n\n   public Date getStartTime() {\n      return startTime;\n   }\n\n   public Optional<Date> getEndTime() {\n      return endTime;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(numPublicVIPs, numServiceNetVIPs, numLoadBalancers, startTime, endTime);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      AccountUsage that = AccountUsage.class.cast(obj);\n\n      return Objects.equal(this.numPublicVIPs, that.numPublicVIPs)\n            && Objects.equal(this.numServiceNetVIPs, that.numServiceNetVIPs)\n            && Objects.equal(this.numLoadBalancers, that.numLoadBalancers)\n            && Objects.equal(this.startTime, that.startTime)\n            && Objects.equal(this.endTime, that.endTime);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"numPublicVIPs\", numPublicVIPs)\n            .add(\"numServiceNetVIPs\", numServiceNetVIPs).add(\"numLoadBalancers\", numLoadBalancers)\n            .add(\"startTime\", startTime).add(\"endTime\", endTime.orNull()).toString();\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/domain/AddNode.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.domain;\n\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.internal.BaseNode;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * The nodes defined by the load balancer are responsible for servicing the requests received\n * through the load balancer's virtual IP. By default, the load balancer employs a basic health\n * check that ensures the node is listening on its defined port. The node is checked at the time of\n * addition and at regular intervals as defined by the load balancer health check configuration. If\n * a back-end node is not listening on its port or does not meet the conditions of the defined\n * active health check for the load balancer, then the load balancer will not forward connections\n * and its status will be listed as OFFLINE. Only nodes that are in an ONLINE status will receive\n * and be able to service traffic from the load balancer.\n * <p/>\n * All nodes have an associated status that indicates whether the node is ONLINE, OFFLINE, or\n * DRAINING. Only nodes that are in ONLINE status will receive and be able to service traffic from\n * the load balancer. The OFFLINE status represents a node that cannot accept or service traffic. A\n * node in DRAINING status represents a node that stops the traffic manager from sending any\n * additional new connections to the node, but honors established sessions. If the traffic manager\n * receives a request and session persistence requires that the node is used, the traffic manager\n * will use it. The status is determined by the passive or active health monitors.\n * <p/>\n * If the WEIGHTED_ROUND_ROBIN load balancer algorithm mode is selected, then the caller should\n * assign the relevant weights to the node as part of the weight attribute of the node element. When\n * the algorithm of the load balancer is changed to WEIGHTED_ROUND_ROBIN and the nodes do not\n * already have an assigned weight, the service will automatically set the weight to \"1\" for all\n * nodes.\n */\npublic class AddNode extends BaseNode<AddNode> {\n\n   // for serialization only\n   AddNode() {\n   }\n\n   public AddNode(String address, int port, Condition condition, Type type, Integer weight) {\n      super(address, port, condition, type, weight);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).omitNullValues()\n            .add(\"address\", address).add(\"port\", port).add(\"condition\", condition).add(\"type\", type).add(\"weight\", weight);\n   }\n   \n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(address, port);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n\n      AddNode that = AddNode.class.cast(obj);\n      return Objects.equal(this.address, that.address)\n            && Objects.equal(this.port, that.port);\n   }\n\n   public static class Builder extends BaseNode.Builder<AddNode> {\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder address(String address) {\n         return Builder.class.cast(super.address(address));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder condition(Condition condition) {\n         return Builder.class.cast(super.condition(condition));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder type(Type type) {\n         return Builder.class.cast(super.type(type));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder port(int port) {\n         return Builder.class.cast(super.port(port));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder weight(Integer weight) {\n         return Builder.class.cast(super.weight(weight));\n      }\n\n      @Override\n      public AddNode build() {\n         return new AddNode(address, port, condition, type, weight);\n      }\n      \n      @Override\n      public Builder from(AddNode in) {\n         return Builder.class.cast(super.from(in));\n      }\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Builder toBuilder() {\n      return new Builder().from(this);\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/domain/ConnectionThrottle.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.domain;\n\nimport static com.google.common.base.Preconditions.checkArgument;\n\nimport java.beans.ConstructorProperties;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * The connection throttling feature imposes limits on the number of connections per IP address to help mitigate \n * malicious or abusive traffic to your applications. The attributes in the table that follows can be configured \n * based on the traffic patterns for your sites.\n */\npublic class ConnectionThrottle {\n\n   private final int maxConnections;\n   private final int minConnections;\n   private final int maxConnectionRate;\n   private final int rateInterval;\n\n   @ConstructorProperties({\n      \"maxConnections\", \"minConnections\", \"maxConnectionRate\", \"rateInterval\"\n   })\n   protected ConnectionThrottle(Integer maxConnections, Integer minConnections, Integer maxConnectionRate, Integer rateInterval) {\n      this.maxConnections = maxConnections;\n      this.minConnections = minConnections;\n      this.maxConnectionRate = maxConnectionRate;\n      this.rateInterval = rateInterval;\n      checkArgument(isValid(), \n            \"At least one of maxConnections, minConnections, maxConnectionRate, or rateInterval must be set.\");\n   }\n\n   public int getMaxConnections() {\n      return this.maxConnections;\n   }\n\n   public int getMinConnections() {\n      return this.minConnections;\n   }\n\n   public int getMaxConnectionRate() {\n      return this.maxConnectionRate;\n   }\n\n   public int getRateInterval() {\n      return this.rateInterval;\n   }\n   \n   public boolean isValid() {\n      return maxConnections != 0 && minConnections != 0 && maxConnectionRate != 0 && rateInterval != 0;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(maxConnections, minConnections, maxConnectionRate, rateInterval);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      ConnectionThrottle that = ConnectionThrottle.class.cast(obj);\n\n      return Objects.equal(this.maxConnections, that.maxConnections)\n            && Objects.equal(this.minConnections, that.minConnections)\n            && Objects.equal(this.maxConnectionRate, that.maxConnectionRate)\n            && Objects.equal(this.rateInterval, that.rateInterval);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).add(\"maxConnections\", maxConnections).add(\"minConnections\", minConnections)\n            .add(\"maxConnectionRate\", maxConnectionRate).add(\"rateInterval\", rateInterval);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   public static class Builder {\n      private int maxConnections;\n      private int minConnections;\n      private int maxConnectionRate;\n      private int rateInterval;\n\n      /** \n       * Maximum number of connections to allow for a single IP address. Setting a value of 0 will allow unlimited \n       * simultaneous connections; otherwise set a value between 1 and 100000.\n       */\n      public Builder maxConnections(int maxConnections) {\n         this.maxConnections = maxConnections;\n         return this;\n      }\n\n      /** \n       * Allow at least this number of connections per IP address before applying throttling restrictions. Setting \n       * a value of 0 allows unlimited simultaneous connections; otherwise, set a value between 1 and 1000.\n       */\n      public Builder minConnections(int minConnections) {\n         this.minConnections = minConnections;\n         return this;\n      }\n\n      /** \n       * Maximum number of connections allowed from a single IP address in the defined rateInterval. Setting a value \n       * of 0 allows an unlimited connection rate; otherwise, set a value between 1 and 100000.\n       */\n      public Builder maxConnectionRate(int maxConnectionRate) {\n         this.maxConnectionRate = maxConnectionRate;\n         return this;\n      }\n\n      /** \n       * Frequency (in seconds) at which the maxConnectionRate is assessed. For example, a maxConnectionRate of 30 \n       * with a rateInterval of 60 would allow a maximum of 30 connections per minute for a single IP address. This \n       * value must be between 1 and 3600.\n       */\n      public Builder rateInterval(int rateInterval) {\n         this.rateInterval = rateInterval;\n         return this;\n      }\n\n      public ConnectionThrottle build() {\n         return new ConnectionThrottle(maxConnections, minConnections, maxConnectionRate, rateInterval);\n      }\n\n      public Builder from(ConnectionThrottle in) {\n         return this.maxConnections(in.getMaxConnections()).minConnections(in.getMinConnections())\n               .maxConnectionRate(in.getMaxConnectionRate()).rateInterval(in.getRateInterval());\n      }\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return new Builder().from(this);\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/domain/CreateLoadBalancer.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.domain;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.internal.BaseLoadBalancer;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Used to create Load Balancers.\n */\npublic class CreateLoadBalancer extends BaseLoadBalancer<AddNode, CreateLoadBalancer> {\n\n   private final Set<Map<String, String>> virtualIps;\n   private final Set<AccessRule> accessRules;\n   private final Map<String, String> metadata;\n\n   public CreateLoadBalancer(String name, String protocol, @Nullable Integer port, Set<AddNode> addNodes,\n         @Nullable Algorithm algorithm, @Nullable Integer timeout, @Nullable Boolean halfClosed,\n         @Nullable Map<String, SessionPersistence> sessionPersistenceType,\n         @Nullable Map<String, Boolean> connectionLogging, @Nullable ConnectionThrottle connectionThrottle,\n         @Nullable HealthMonitor healthMonitor, @Nullable Set<AccessRule> accessRules,\n         @Nullable Map<String, String> metadata, VirtualIP.Type virtualIPType, Integer virtualIPId) {\n      this(name, protocol, port, addNodes, algorithm, timeout, halfClosed, sessionPersistenceType, connectionLogging,\n            connectionThrottle, healthMonitor, accessRules, metadata, \n            getVirtualIPsFromOptions(virtualIPType, virtualIPId));\n   }\n\n   public CreateLoadBalancer(String name, String protocol, @Nullable Integer port, Set<AddNode> addNodes,\n         @Nullable Algorithm algorithm, @Nullable Integer timeout, @Nullable Boolean halfClosed,\n         @Nullable Map<String, SessionPersistence> sessionPersistenceType,\n         @Nullable Map<String, Boolean> connectionLogging, @Nullable ConnectionThrottle connectionThrottle,\n         @Nullable HealthMonitor healthMonitor, @Nullable Set<AccessRule> accessRules,\n         @Nullable Map<String, String> metadata, Set<Map<String, String>> virtualIPsFromOptions) {\n      super(name, protocol, port, addNodes, algorithm, timeout, halfClosed, sessionPersistenceType, connectionLogging,\n            connectionThrottle, healthMonitor);\n      this.virtualIps = checkNotNull(virtualIPsFromOptions, \"virtualIPsFromOptions\");\n      this.accessRules = accessRules;\n      this.metadata = metadata;\n   }   \n\n   public Map<String, String> getMetadata() {\n      return metadata != null ? metadata : ImmutableMap.<String, String> of();\n   }\n\n   public Set<AccessRule> getAccessRules() {\n      return accessRules != null ? accessRules : ImmutableSet.<AccessRule> of();\n   }\n\n   static Set<Map<String, String>> getVirtualIPsFromOptions(VirtualIP.Type virtualIPType, Integer virtualIPId) {\n      checkArgument(virtualIPType == null || virtualIPId == null,\n            \"virtualIPType and virtualIPId cannot both be specified\");\n      if (virtualIPType != null)\n         return ImmutableSet.<Map<String, String>> of(ImmutableMap.of(\"type\", virtualIPType.name()));\n      else if (virtualIPId != null)\n         return ImmutableSet.<Map<String, String>> of(ImmutableMap.of(\"id\", virtualIPId.toString()));\n      else\n         throw new IllegalArgumentException(\"virtualIPType or virtualIPId must be specified\");\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"name\", name).add(\"protocol\", protocol)\n            .add(\"port\", port).add(\"nodes\", nodes).add(\"timeout\", timeout).add(\"algorithm\", algorithm)\n            .add(\"timeout\", timeout).add(\"sessionPersistenceType\", getSessionPersistenceType())\n            .add(\"connectionLogging\", isConnectionLogging()).add(\"connectionThrottle\", connectionThrottle)\n            .add(\"healthMonitor\", healthMonitor).add(\"accessRules\", accessRules).add(\"metadata\", metadata)\n            .add(\"virtualIps\", virtualIps);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   public static class Builder extends BaseLoadBalancer.Builder<AddNode, CreateLoadBalancer> {\n      private VirtualIP.Type virtualIPType;\n      private Integer virtualIPId;\n      private Set<Map<String, String>> virtualIps;\n      private Set<AccessRule> accessRules;\n      private Map<String, String> metadata;\n\n      /**\n       * @see VirtualIP\n       */\n      public Builder virtualIPId(Integer virtualIPId) {\n         this.virtualIPId = virtualIPId;\n         return this;\n      }\n\n      /**\n       * @see VirtualIP\n       */\n      public Builder virtualIPType(VirtualIP.Type virtualIPType) {\n         this.virtualIPType = virtualIPType;\n         return this;\n      }\n\n      /**\n       * @see VirtualIP\n       */\n      private Builder virtualIPs(Set<Map<String, String>> virtualIPs) {\n         this.virtualIps = virtualIPs;\n         return this;\n      }\n\n      /**\n       * The access list management feature allows fine-grained network access controls to be applied to the load \n       * balancer's virtual IP address.\n       * \n       * @see AccessRule\n       */\n      public Builder accessRules(Iterable<AccessRule> accessRules) {\n         this.accessRules = ImmutableSet.<AccessRule> copyOf(checkNotNull(accessRules, \"accessRules\"));\n         return this;\n      }\n\n      /**\n       * Information (metadata) that can be associated with each load balancer for the client's personal use.\n       */\n      public Builder metadata(Map<String, String> metadata) {\n         this.metadata = ImmutableMap.<String, String> copyOf(checkNotNull(metadata, \"metadata\"));\n         return this;\n      }\n\n      public CreateLoadBalancer build() {\n         if (virtualIps == null) {\n            return new CreateLoadBalancer(name, protocol, port, nodes, algorithm, timeout, halfClosed,\n                  sessionPersistence, connectionLogging, connectionThrottle, healthMonitor, accessRules, metadata,\n                  virtualIPType, virtualIPId);\n         }\n         else {\n            return new CreateLoadBalancer(name, protocol, port, nodes, algorithm, timeout, halfClosed,\n                  sessionPersistence, connectionLogging, connectionThrottle, healthMonitor, accessRules, metadata,\n                  virtualIps);\n         }\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder nodes(Iterable<AddNode> addNodes) {\n         this.nodes = ImmutableSet.<AddNode> copyOf(checkNotNull(addNodes, \"addNodes\"));\n         return this;\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder node(AddNode node) {\n         this.nodes.add(checkNotNull(node, \"node\"));\n         return this;\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder algorithm(Algorithm algorithm) {\n         return Builder.class.cast(super.algorithm(algorithm));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder name(String name) {\n         return Builder.class.cast(super.name(name));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder port(Integer port) {\n         return Builder.class.cast(super.port(port));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder protocol(String protocol) {\n         return Builder.class.cast(super.protocol(protocol));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder from(CreateLoadBalancer in) {\n         return Builder.class.cast(super.from(in)).virtualIPs(in.virtualIps);\n      }\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return new Builder().from(this);\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/domain/HealthMonitor.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.base.Optional;\n\n/**\n * The load balancing service includes a health monitoring operation which periodically checks your back-end nodes to \n * ensure they are responding correctly. If a node is not responding, it is removed from rotation until the health \n * monitor determines that the node is functional. In addition to being performed periodically, the health check also \n * is performed against every node that is added to ensure that the node is operating properly before allowing it to \n * service traffic. Only one health monitor is allowed to be enabled on a load balancer at a time.\n * </p>\n * As part of your strategy for monitoring connections, you should consider defining secondary nodes that provide \n * failover for effectively routing traffic in case the primary node fails. This is an additional feature that will \n * ensure you remain up in case your primary node fails.\n * <p/>\n */\npublic class HealthMonitor {\n\n   private final Type type;\n   private final int delay;\n   private final int timeout;\n   private final int attemptsBeforeDeactivation;\n   private final Optional<String> bodyRegex;\n   private final Optional<String> statusRegex;\n   private final Optional<String> path;\n   private final Optional<String> hostHeader;\n\n   @ConstructorProperties({\n      \"type\", \"delay\", \"timeout\", \"attemptsBeforeDeactivation\", \"bodyRegex\", \"statusRegex\", \"path\", \"hostHeader\"\n   })\n   protected HealthMonitor(Type type, int delay, int timeout, int attemptsBeforeDeactivation, \n         @Nullable String bodyRegex, @Nullable String statusRegex, @Nullable String path, \n         @Nullable String hostHeader) {\n      this.type = checkNotNull(type, \"type\");\n      this.delay = delay;\n      this.timeout = timeout;\n      this.attemptsBeforeDeactivation = attemptsBeforeDeactivation;\n      this.bodyRegex = Optional.fromNullable(bodyRegex);\n      this.statusRegex = Optional.fromNullable(statusRegex);\n      this.path = Optional.fromNullable(path);\n      this.hostHeader = Optional.fromNullable(hostHeader);\n      \n      if (!isValid())\n         if (type.equals(Type.CONNECT))\n            throw new IllegalArgumentException(\"Only delay, timeout, and attemptsBeforeDeactivation must be set.\");\n         else\n            throw new IllegalArgumentException(\"At least delay, timeout, attemptsBeforeDeactivation, path and \" +\n            \t\t\"one or both of bodyRegex and statusRegex must be set.\");\n   }\n\n   public Type getType() {\n      return type;\n   }\n\n   public int getDelay() {\n      return delay;\n   }\n\n   public int getTimeout() {\n      return timeout;\n   }\n\n   public int getAttemptsBeforeDeactivation() {\n      return attemptsBeforeDeactivation;\n   }\n\n   public Optional<String> getBodyRegex() {\n      return bodyRegex;\n   }\n\n   public Optional<String> getStatusRegex() {\n      return statusRegex;\n   }\n\n   public Optional<String> getPath() {\n      return path;\n   }\n\n   public Optional<String> getHostHeader() {\n      return hostHeader;\n   }\n   \n   /**\n    * @return true if this HealthMonitor is valid, false otherwise\n    */\n   public boolean isValid() {\n      boolean required = delay != 0 && timeout != 0 && attemptsBeforeDeactivation != 0;\n      \n      if (type.equals(Type.CONNECT))\n         return required && !path.isPresent() && !statusRegex.isPresent() \n                && !bodyRegex.isPresent() && !hostHeader.isPresent();\n      else\n         return required && path.isPresent() && (statusRegex.isPresent() || bodyRegex.isPresent());\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(type, delay, timeout, attemptsBeforeDeactivation, bodyRegex, statusRegex, path, \n            hostHeader);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      HealthMonitor that = HealthMonitor.class.cast(obj);\n\n      return Objects.equal(this.type, that.type) && Objects.equal(this.delay, that.delay)\n            && Objects.equal(this.timeout, that.timeout)\n            && Objects.equal(this.attemptsBeforeDeactivation, that.attemptsBeforeDeactivation)\n            && Objects.equal(this.bodyRegex, that.bodyRegex) && Objects.equal(this.statusRegex, that.statusRegex)\n            && Objects.equal(this.path, that.path) && Objects.equal(this.hostHeader, that.hostHeader);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"type\", type).add(\"delay\", delay)\n            .add(\"timeout\", timeout).add(\"attemptsBeforeDeactivation\", attemptsBeforeDeactivation)\n            .add(\"bodyRegex\", bodyRegex.orNull()).add(\"statusRegex\", statusRegex.orNull()).add(\"path\", path.orNull())\n            .add(\"hostHeader\", hostHeader.orNull());\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   /**\n    * Every health monitor has a type attribute to signify what kind of monitor it is.\n    */\n   public static enum Type {\n      CONNECT, HTTP, HTTPS, UNRECOGNIZED;\n\n      public static Type fromValue(String type) {\n         try {\n            return valueOf(checkNotNull(type, \"type\"));\n         }\n         catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n   }\n\n   public static class Builder {\n      private Type type;\n      private int delay;\n      private int timeout;\n      private int attemptsBeforeDeactivation;\n      private String bodyRegex;\n      private String statusRegex;\n      private String path;\n      private String hostHeader;\n\n      /** \n       * Type of the health monitor. Must be specified as CONNECT to monitor connections.\n       */\n      public Builder type(Type type) {\n         this.type = type;\n         return this;\n      }\n\n      /** \n       * Required. The minimum number of seconds to wait before executing the health monitor. \n       * Must be a number between 1 and 3600.\n       */\n      public Builder delay(int delay) {\n         this.delay = delay;\n         return this;\n      }\n\n      /** \n       * Required. Maximum number of seconds to wait for a connection to be established before timing out. \n       * Must be a number between 1 and 300.\n       */\n      public Builder timeout(int timeout) {\n         this.timeout = timeout;\n         return this;\n      }\n\n      /** \n       * Required. Number of permissible monitor failures before removing a node from rotation. \n       * Must be a number between 1 and 10.\n       */\n      public Builder attemptsBeforeDeactivation(int attemptsBeforeDeactivation) {\n         this.attemptsBeforeDeactivation = attemptsBeforeDeactivation;\n         return this;\n      }\n\n      /**\n       * Required (if using HTTP/S). A regular expression that will be used to evaluate the contents of the body of \n       * the response.\n       */\n      public Builder bodyRegex(String bodyRegex) {\n         this.bodyRegex = bodyRegex;\n         return this;\n      }\n\n      /**\n       * Required (if using HTTP/S). A regular expression that will be used to evaluate the HTTP status code returned\n       * in the response.\n       */\n      public Builder statusRegex(String statusRegex) {\n         this.statusRegex = statusRegex;\n         return this;\n      }\n\n      /**\n       * Required (if using HTTP/S). The HTTP path that will be used in the sample request.\n       */\n      public Builder path(String path) {\n         this.path = path;\n         return this;\n      }\n\n      /**\n       * Optional (if using HTTP/S). The name of a host for which the health monitors will check.\n       */\n      public Builder hostHeader(String hostHeader) {\n         this.hostHeader = hostHeader;\n         return this;\n      }\n\n      public HealthMonitor build() {\n         return new HealthMonitor(type, delay, timeout, attemptsBeforeDeactivation, bodyRegex, statusRegex, path,\n               hostHeader);\n      }\n\n      public Builder from(HealthMonitor in) {\n         return this.type(in.getType()).delay(in.getDelay()).timeout(in.getTimeout())\n               .attemptsBeforeDeactivation(in.getAttemptsBeforeDeactivation()).bodyRegex(in.getBodyRegex().orNull())\n               .statusRegex(in.getStatusRegex().orNull()).path(in.getPath().orNull())\n               .hostHeader(in.getHostHeader().orNull());\n      }\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return new Builder().from(this);\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/domain/HistoricalUsage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Map;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.collect.Iterables;\n\npublic final class HistoricalUsage {\n   private final int accountId;\n   private final Map<String, Iterable<AccountUsage>> accountUsage;\n   private final Iterable<LoadBalancerInfo> loadBalancerUsages;\n\n   @ConstructorProperties({ \"accountId\", \"accountUsage\", \"loadBalancerUsages\" })\n   protected HistoricalUsage(int accountId, Map<String, Iterable<AccountUsage>> accountUsage,\n         Iterable<LoadBalancerInfo> loadBalancerUsages) {\n      this.accountId = accountId;\n      this.accountUsage = checkNotNull(accountUsage, \"accountUsage\");\n      this.loadBalancerUsages = checkNotNull(loadBalancerUsages, \"loadBalancerUsages\");\n   }\n\n   public int getAccountId() {\n      return accountId;\n   }\n\n   public Iterable<AccountUsage> getAccountUsage() {\n      return Iterables.get(accountUsage.values(), 0);\n   }\n\n   public Iterable<LoadBalancerInfo> getLoadBalancerInfo() {\n      return loadBalancerUsages;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(accountId);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      HistoricalUsage that = HistoricalUsage.class.cast(obj);\n\n      return Objects.equal(this.accountId, that.accountId);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"accountId\", accountId)\n            .add(\"accountUsage\", getAccountUsage()).add(\"loadBalancerInfo\", loadBalancerUsages).toString();\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/domain/LoadBalancer.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.domain;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.internal.BaseLoadBalancer;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableSet;\n\npublic class LoadBalancer extends BaseLoadBalancer<Node, LoadBalancer> {\n\n   private final String region;\n   private final int id;\n   private final Status status;\n   private final Set<VirtualIPWithId> virtualIPs;\n   private final String clusterName;\n   private final Date created;\n   private final Date updated;\n   private final boolean contentCaching;\n   private final int nodeCount;\n   private final SSLTermination sslTermination;\n   private final SourceAddresses sourceAddresses;\n   private final Set<AccessRuleWithId> accessRules;\n   private final Metadata metadata;\n   private final URI uri;\n\n   public LoadBalancer(String region, int id, String name, String protocol, @Nullable Integer port, Set<Node> nodes,\n         @Nullable Integer timeout, @Nullable Boolean halfClosed, @Nullable Algorithm algorithm, Status status,\n         Set<VirtualIPWithId> virtualIPs, @Nullable Map<String, SessionPersistence> sessionPersistenceType,\n         String clusterName, Date created, Date updated, @Nullable Map<String, Boolean> connectionLogging,\n         @Nullable ConnectionThrottle connectionThrottle, boolean contentCaching, int nodeCount,\n         @Nullable HealthMonitor healthMonitor, @Nullable SSLTermination sslTermination,\n         SourceAddresses sourceAddresses, Set<AccessRuleWithId> accessRules, Metadata metadata, URI uri) {\n      super(name, protocol, port, nodes, algorithm, timeout, halfClosed, sessionPersistenceType, connectionLogging,\n            connectionThrottle, healthMonitor);\n      this.region = checkNotNull(region, \"region\");\n      checkArgument(id != -1, \"id must be specified\");\n      this.id = id;\n      this.status = checkNotNull(status, \"status\");\n      this.virtualIPs = ImmutableSet.copyOf(checkNotNull(virtualIPs, \"virtualIPs\"));\n      this.clusterName = clusterName;\n      this.created = checkNotNull(created, \"created\");\n      this.updated = checkNotNull(updated, \"updated\");\n      this.contentCaching = contentCaching;\n      this.nodeCount = nodeCount;\n      this.sslTermination = sslTermination;\n      this.sourceAddresses = sourceAddresses;\n      this.accessRules = accessRules == null ? ImmutableSet.<AccessRuleWithId> of() : ImmutableSet.copyOf(accessRules);\n      this.metadata = metadata == null ? new Metadata() : metadata;\n      this.uri = uri;\n   }\n\n   public String getRegion() {\n      return region;\n   }\n\n   public int getId() {\n      return id;\n   }\n\n   /**\n    * @see Status\n    */\n   public Status getStatus() {\n      return status;\n   }\n\n   /**\n    * @see VirtualIP\n    */\n   public Set<VirtualIPWithId> getVirtualIPs() {\n      return virtualIPs;\n   }\n\n   /**\n    * Name of the cluster.\n    */\n   public String getClusterName() {\n      return clusterName;\n   }\n\n   /**\n    * When the load balancer was created.\n    */\n   public Date getCreated() {\n      return created;\n   }\n\n   /**\n    * When the load balancer was updated.\n    */\n   public Date getUpdated() {\n      return updated;\n   }\n\n   /**\n    * View the current content caching configuration.\n    */\n   public boolean isContentCaching() {\n      return contentCaching;\n   }\n\n   /**\n    * Broken out as a separate field because when LoadBalancers are returned from\n    * {@link LoadBalancerApi#list()}, no Nodes are returned (so you can't rely on getNodes().size())\n    * but a nodeCount is returned. When {@link LoadBalancerApi#get(int)} is called, nodes are\n    * returned but no nodeCount is returned.\n    *\n    * @return The number of Nodes in this LoadBalancer\n    */\n   public int getNodeCount() {\n      return !nodes.isEmpty() ? nodes.size() : nodeCount;\n   }\n\n   /**\n    * @see SSLTermination\n    */\n   @Nullable\n   public SSLTermination getSSLTermination() {\n      return sslTermination;\n   }\n\n   /**\n    * @see SourceAddresses\n    */\n   public SourceAddresses getSourceAddresses() {\n      return sourceAddresses;\n   }\n\n   /**\n    * @see AccessRule\n    */\n   public Set<AccessRuleWithId> getAccessRules() {\n      return accessRules;\n   }\n\n   /**\n    * @see Metadata\n    */\n   public Metadata getMetadata() {\n      return metadata;\n   }\n\n   public URI getUri() {\n      return uri;\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"id\", id).add(\"region\", region).add(\"status\", status)\n            .add(\"name\", name).add(\"protocol\", protocol).add(\"port\", port).add(\"nodeCount\", getNodeCount())\n            .add(\"nodes\", nodes).add(\"timeout\", timeout).add(\"algorithm\", algorithm).add(\"halfClosed\", halfClosed)\n            .add(\"clusterName\", clusterName).add(\"created\", created).add(\"updated\", updated)\n            .add(\"contentCaching\", contentCaching).add(\"sessionPersistenceType\", getSessionPersistenceType())\n            .add(\"sslTermination\", sslTermination).add(\"connectionLogging\", isConnectionLogging())\n            .add(\"connectionThrottle\", connectionThrottle).add(\"healthMonitor\", healthMonitor)\n            .add(\"accessRules\", accessRules).add(\"metadata\", getMetadata()).add(\"uri\", uri).add(\"sourceAddresses\", sourceAddresses)\n            .add(\"virtualIPs\", virtualIPs);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, region);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n\n      LoadBalancer that = LoadBalancer.class.cast(obj);\n      return Objects.equal(this.id, that.id) && Objects.equal(this.region, that.region);\n   }\n\n   /**\n    * All load balancers also have a status attribute to signify the current configuration status of\n    * the device. This status is immutable by the caller and is updated automatically based on state\n    * changes within the service. When a load balancer is first created, it will be placed into a\n    * BUILD status while the configuration is being generated and applied based on the request. Once\n    * the configuration is applied and finalized, it will be in an ACTIVE status. In the event of a\n    * configuration change or update, the status of the load balancer will change to PENDING_UPDATE\n    * to signify configuration changes are in progress but have not yet been finalized. Load\n    * balancers in a SUSPENDED status are configured to reject traffic and will not forward requests\n    * to back-end nodes.\n    */\n   public static enum Status {\n      /**\n       * Load balancer is being provisioned for the first time and configuration is being applied to\n       * bring the service online. The service will not yet be ready to serve incoming requests.\n       */\n      BUILD,\n      /**\n       * Load balancer is configured properly and ready to serve traffic to incoming requests via\n       * the configured virtual IPs.\n       */\n      ACTIVE,\n      /**\n       * Load balancer is online but configuration changes are being applied to update the service\n       * based on a previous request.\n       */\n      PENDING_UPDATE,\n      /**\n       * Load balancer has been taken offline and disabled; contact Support.\n       */\n      SUSPENDED,\n      /**\n       * Load balancer is online but configuration changes are being applied to begin deletion of\n       * the service based on a previous request.\n       */\n      PENDING_DELETE,\n      /**\n       * Load balancers in DELETED status can be displayed for at least 90 days after deletion.\n       */\n      DELETED,\n      /**\n       * The system encountered an error when attempting to configure the load balancer; contact\n       * Support.\n       */\n      ERROR, UNRECOGNIZED;\n\n      public static Status fromValue(String status) {\n         try {\n            return valueOf(checkNotNull(status, \"status\"));\n         }\n         catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n\n   }\n\n   public static class Builder extends BaseLoadBalancer.Builder<Node, LoadBalancer> {\n      private String region;\n      private int id = -1;\n      private Status status;\n      private Set<VirtualIPWithId> virtualIPs = ImmutableSet.<VirtualIPWithId> of();\n      private String clusterName;\n      private Date created;\n      private Date updated;\n      private boolean contentCaching;\n      private int nodeCount = 0;\n      private SSLTermination sslTermination;\n      private SourceAddresses sourceAddresses;\n      private Set<AccessRuleWithId> accessRules;\n      private Metadata metadata;\n      private URI uri;\n\n      public Builder region(String region) {\n         this.region = region;\n         return this;\n      }\n\n      public Builder id(int id) {\n         this.id = id;\n         return this;\n      }\n\n      public Builder status(Status status) {\n         this.status = status;\n         return this;\n      }\n\n      public Builder virtualIPs(Iterable<VirtualIPWithId> virtualIPs) {\n         this.virtualIPs = ImmutableSet.<VirtualIPWithId> copyOf(checkNotNull(virtualIPs, \"virtualIPs\"));\n         return this;\n      }\n\n      public Builder clusterName(String clusterName) {\n         this.clusterName = clusterName;\n         return this;\n      }\n\n      public Builder created(Date created) {\n         this.created = created;\n         return this;\n      }\n\n      public Builder updated(Date updated) {\n         this.updated = updated;\n         return this;\n      }\n\n      public Builder contentCaching(boolean contentCaching) {\n         this.contentCaching = contentCaching;\n         return this;\n      }\n\n      /**\n       * @see LoadBalancer#getNodeCount()\n       */\n      public Builder nodeCount(int nodeCount) {\n         this.nodeCount = nodeCount;\n         return this;\n      }\n\n      public Builder sslTermination(SSLTermination sslTermination) {\n         this.sslTermination = checkNotNull(sslTermination, \"sslTermination\");\n         return this;\n      }\n\n      public Builder sourceAddresses(SourceAddresses sourceAddresses) {\n         this.sourceAddresses = checkNotNull(sourceAddresses, \"sourceAddresses\");\n         return this;\n      }\n\n      public Builder accessRules(Iterable<AccessRuleWithId> accessRules) {\n         this.accessRules = ImmutableSet.copyOf(checkNotNull(accessRules, \"accessRules\"));\n         return this;\n      }\n\n      public Builder metadata(Metadata metadata) {\n         this.metadata = checkNotNull(metadata, \"metadata\");\n         return this;\n      }\n\n      public Builder uri(URI uri) {\n         this.uri = uri;\n         return this;\n      }\n\n      public LoadBalancer build() {\n         return new LoadBalancer(region, id, name, protocol, port, nodes, timeout, halfClosed, algorithm, status,\n               virtualIPs, sessionPersistence, clusterName, created, updated, connectionLogging, connectionThrottle,\n               contentCaching, nodeCount, healthMonitor, sslTermination, sourceAddresses, accessRules, metadata, uri);\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder nodes(Iterable<Node> nodes) {\n         this.nodes = ImmutableSet.<Node> copyOf(checkNotNull(nodes, \"nodes\"));\n         return this;\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder node(Node node) {\n         this.nodes.add(checkNotNull(node, \"nodes\"));\n         return this;\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder algorithm(Algorithm algorithm) {\n         return Builder.class.cast(super.algorithm(algorithm));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder name(String name) {\n         return Builder.class.cast(super.name(name));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder port(Integer port) {\n         return Builder.class.cast(super.port(port));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder protocol(String protocol) {\n         return Builder.class.cast(super.protocol(protocol));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder timeout(@Nullable Integer timeout) {\n         return Builder.class.cast(super.timeout(timeout));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder halfClosed(@Nullable Boolean halfClosed) {\n         return Builder.class.cast(super.halfClosed(halfClosed));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder sessionPersistenceType(@Nullable SessionPersistence sessionPersistenceType) {\n         return Builder.class.cast(super.sessionPersistenceType(sessionPersistenceType));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder connectionLogging(@Nullable Boolean connectionLogging) {\n         return Builder.class.cast(super.connectionLogging(connectionLogging));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder connectionThrottle(@Nullable ConnectionThrottle connectionThrottle) {\n         return Builder.class.cast(super.connectionThrottle(connectionThrottle));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder healthMonitor(@Nullable HealthMonitor healthMonitor) {\n         return Builder.class.cast(super.healthMonitor(healthMonitor));\n      }\n\n      @Override\n      public Builder from(LoadBalancer in) {\n         return Builder.class.cast(super.from(in)).region(in.getRegion()).id(in.getId()).status(in.getStatus())\n               .virtualIPs(in.getVirtualIPs()).clusterName(in.getClusterName()).created(in.getCreated())\n               .updated(in.getUpdated()).contentCaching(in.isContentCaching()).nodeCount(in.getNodeCount())\n               .sslTermination(in.getSSLTermination()).sourceAddresses(in.getSourceAddresses())\n               .accessRules(in.getAccessRules()).metadata(in.getMetadata()).uri(in.getUri());\n      }\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return new Builder().from(this);\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/domain/LoadBalancerInfo.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\npublic final class LoadBalancerInfo {\n   private final int loadBalancerId;\n   private final String loadBalancerName;\n   private final Iterable<LoadBalancerUsage> loadBalancerUsageRecords;\n\n   @ConstructorProperties({ \"loadBalancerId\", \"loadBalancerName\", \"loadBalancerUsageRecords\" })\n   protected LoadBalancerInfo(int id, String name, Iterable<LoadBalancerUsage> loadBalancerUsageRecords) {\n      this.loadBalancerId = id;\n      this.loadBalancerName = checkNotNull(name, \"name\");\n      this.loadBalancerUsageRecords = checkNotNull(loadBalancerUsageRecords, \"loadBalancerUsageRecords\");\n   }\n\n   public int getLoadBalancerId() {\n      return loadBalancerId;\n   }\n\n   public String getLoadBalancerName() {\n      return loadBalancerName;\n   }\n\n   public Iterable<LoadBalancerUsage> getLoadBalancerUsage() {\n      return loadBalancerUsageRecords;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(loadBalancerId);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      LoadBalancerInfo that = LoadBalancerInfo.class.cast(obj);\n\n      return Objects.equal(this.loadBalancerId, that.loadBalancerId);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"loadBalancerId\", loadBalancerId)\n            .add(\"loadBalancerName\", loadBalancerName).add(\"loadBalancerUsage\", loadBalancerUsageRecords).toString();\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/domain/LoadBalancerStats.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport com.google.common.base.MoreObjects;\n\npublic final class LoadBalancerStats {\n   private final int connectTimeOut;\n   private final int connectError;\n   private final int connectFailure;\n   private final int dataTimedOut;\n   private final int keepAliveTimedOut;\n   private final int maxConn;\n\n   @ConstructorProperties({ \"connectTimeOut\", \"connectError\", \"connectFailure\", \"dataTimedOut\", \"keepAliveTimedOut\",\n         \"maxConn\" })\n   protected LoadBalancerStats(int connectTimeOut, int connectError, int connectFailure, int dataTimedOut,\n         int keepAliveTimedOut, int maxConn) {\n      this.connectTimeOut = connectTimeOut;\n      this.connectError = connectError;\n      this.connectFailure = connectFailure;\n      this.dataTimedOut = dataTimedOut;\n      this.keepAliveTimedOut = keepAliveTimedOut;\n      this.maxConn = maxConn;\n   }\n\n   /**\n    * Connections closed by this load balancer because the 'connect_timeout' interval was exceeded.\n    */\n   public int getConnectTimeOut() {\n      return connectTimeOut;\n   }\n\n   /**\n    * Number of transaction or protocol errors in this load balancer.\n    */\n   public int getConnectError() {\n      return connectError;\n   }\n\n   /**\n    * Number of connection failures in this load balancer.\n    */\n   public int getConnectFailure() {\n      return connectFailure;\n   }\n\n   /**\n    * Connections closed by this load balancer because the 'timeout' interval was exceeded.\n    */\n   public int getDataTimedOut() {\n      return dataTimedOut;\n   }\n\n   /**\n    * Connections closed by this load balancer because the 'keepalive_timeout' interval was exceeded.\n    */\n   public int getKeepAliveTimedOut() {\n      return keepAliveTimedOut;\n   }\n\n   /**\n    * Maximum number of simultaneous TCP connections this load balancer has processed at any one time.\n    */\n   public int getMaxConn() {\n      return maxConn;\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"connectTimeOut\", connectTimeOut)\n            .add(\"connectError\", connectError).add(\"connectFailure\", connectFailure).add(\"dataTimedOut\", dataTimedOut)\n            .add(\"keepAliveTimedOut\", keepAliveTimedOut).add(\"maxConn\", maxConn).toString();\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/domain/LoadBalancerUsage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\n\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.VirtualIP.Type;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.Optional;\n\npublic final class LoadBalancerUsage {\n   private final int id;\n   private final float averageNumConnections;\n   private final float averageNumConnectionsSsl;\n   private final int incomingTransferInBytes;\n   private final int outgoingTransferInBytes;\n   private final int incomingTransferSslInBytes;\n   private final int outgoingTransferSslInBytes;\n   private final int numVIPs;\n   private final int numPolls;\n   private final Date startTime;\n   private final Date endTime;\n   private final VirtualIP.Type vipType;\n   private final String sslMode;\n   private final Optional<String> eventType;\n\n   @ConstructorProperties({ \"id\", \"averageNumConnections\", \"averageNumConnectionsSsl\", \"incomingTransfer\",\n         \"outgoingTransfer\", \"incomingTransferSsl\", \"outgoingTransferSsl\", \"numVips\", \"numPolls\", \"startTime\",\n         \"endTime\", \"vipType\", \"sslMode\", \"eventType\" })\n   protected LoadBalancerUsage(int id, float averageNumConnections, float averageNumConnectionsSsl,\n         int incomingTransferInBytes, int outgoingTransferInBytes, int incomingTransferSslInBytes,\n         int outgoingTransferSslInBytes, int numVIPs, int numPolls, Date startTime, Date endTime, Type vipType,\n         String sslMode, String eventType) {\n      this.id = id;\n      this.averageNumConnections = averageNumConnections;\n      this.averageNumConnectionsSsl = averageNumConnectionsSsl;\n      this.incomingTransferInBytes = incomingTransferInBytes;\n      this.outgoingTransferInBytes = outgoingTransferInBytes;\n      this.incomingTransferSslInBytes = incomingTransferSslInBytes;\n      this.outgoingTransferSslInBytes = outgoingTransferSslInBytes;\n      this.numVIPs = numVIPs;\n      this.numPolls = numPolls;\n      this.startTime = checkNotNull(startTime, \"startTime\");\n      this.endTime = checkNotNull(endTime, \"endTime\");\n      this.vipType = checkNotNull(vipType, \"vipType\");\n      this.sslMode = checkNotNull(sslMode, \"sslMode\");\n      this.eventType = Optional.fromNullable(eventType);\n   }\n\n   public int getId() {\n      return id;\n   }\n\n   public float getAverageNumConnections() {\n      return averageNumConnections;\n   }\n\n   public float getAverageNumConnectionsSsl() {\n      return averageNumConnectionsSsl;\n   }\n\n   public int getIncomingTransferInBytes() {\n      return incomingTransferInBytes;\n   }\n\n   public int getOutgoingTransferInBytes() {\n      return outgoingTransferInBytes;\n   }\n\n   public int getIncomingTransferSslInBytes() {\n      return incomingTransferSslInBytes;\n   }\n\n   public int getOutgoingTransferSslInBytes() {\n      return outgoingTransferSslInBytes;\n   }\n\n   public int getNumVIPs() {\n      return numVIPs;\n   }\n\n   public int getNumPolls() {\n      return numPolls;\n   }\n\n   public Date getStartTime() {\n      return startTime;\n   }\n\n   public Date getEndTime() {\n      return endTime;\n   }\n\n   public VirtualIP.Type getVIPType() {\n      return vipType;\n   }\n\n   public String getSSLMode() {\n      return sslMode;\n   }\n\n   public Optional<String> getEventType() {\n      return eventType;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      LoadBalancerUsage that = LoadBalancerUsage.class.cast(obj);\n\n      return Objects.equal(this.id, that.id);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).omitNullValues()\n            .add(\"averageNumConnections\", averageNumConnections)\n            .add(\"averageNumConnectionsSsl\", averageNumConnectionsSsl)\n            .add(\"incomingTransferInBytes\", incomingTransferInBytes)\n            .add(\"outgoingTransferInBytes\", outgoingTransferInBytes)\n            .add(\"incomingTransferSslInBytes\", incomingTransferSslInBytes)\n            .add(\"outgoingTransferSslInBytes\", outgoingTransferSslInBytes).add(\"numVIPs\", numVIPs)\n            .add(\"numPolls\", numPolls).add(\"startTime\", startTime).add(\"endTime\", endTime).add(\"vipType\", vipType)\n            .add(\"sslMode\", sslMode).add(\"eventType\", eventType.orNull()).toString();\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/domain/Metadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.domain;\n\nimport java.util.Map;\n\nimport com.google.common.collect.ForwardingMap;\nimport static com.google.common.collect.Maps.newLinkedHashMap;\nimport static com.google.common.collect.Sets.newHashSet;\n\n/**\n * Key and value must be 256 characters or less. All UTF-8 characters are valid.\n * </p>\n * Use the *Id methods when you need to get a metadata id for updating and removal.\n */\npublic class Metadata extends ForwardingMap<String, String> {\n   private final Map<String, String> metadata = newLinkedHashMap(); // Implementing class must be sorted.\n   private final Map<String, Integer> keyToId = newLinkedHashMap();\n   \n   public Metadata(Metadata metadata) {\n      super();\n      this.metadata.putAll(metadata);\n   }\n   \n   public Metadata() {\n      super();\n   }\n\n   @Override\n   protected Map<String, String> delegate() {\n      return metadata;\n   }\n   \n   public int getId(String key) {\n      return keyToId.get(key);\n   }\n   \n   public Integer putId(String key, int id) {\n      return keyToId.put(key, id);\n   }\n\n   public Iterable<Integer> getIds() {\n      return newHashSet(keyToId.values());\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/domain/Node.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.domain;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.internal.BaseNode;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * The nodes defined by the load balancer are responsible for servicing the requests received\n * through the load balancer's virtual IP. By default, the load balancer employs a basic health\n * check that ensures the node is listening on its defined port. The node is checked at the time of\n * addition and at regular intervals as defined by the load balancer health check configuration. If\n * a back-end node is not listening on its port or does not meet the conditions of the defined\n * active health check for the load balancer, then the load balancer will not forward connections\n * and its status will be listed as OFFLINE. Only nodes that are in an ONLINE status will receive\n * and be able to service traffic from the load balancer.\n * <p/>\n * All nodes have an associated status that indicates whether the node is ONLINE, OFFLINE, or\n * DRAINING. Only nodes that are in ONLINE status will receive and be able to service traffic from\n * the load balancer. The OFFLINE status represents a node that cannot accept or service traffic. A\n * node in DRAINING status represents a node that stops the traffic manager from sending any\n * additional new connections to the node, but honors established sessions. If the traffic manager\n * receives a request and session persistence requires that the node is used, the traffic manager\n * will use it. The status is determined by the passive or active health monitors.\n * <p/>\n * If the WEIGHTED_ROUND_ROBIN load balancer algorithm mode is selected, then the caller should\n * assign the relevant weights to the node as part of the weight attribute of the node element. When\n * the algorithm of the load balancer is changed to WEIGHTED_ROUND_ROBIN and the nodes do not\n * already have an assigned weight, the service will automatically set the weight to \"1\" for all\n * nodes.\n */\npublic class Node extends BaseNode<Node> {\n\n   private int id;\n   private Status status;\n   private Metadata metadata = new Metadata();\n   \n   // for serialization only\n   protected Node() {\n   }\n\n   public Node(String address, int port, Condition condition, Type type, Integer weight, int id, Status status, Metadata metadata) {\n      super(address, port, condition, type, weight);\n      checkArgument(id != -1, \"id must be specified\");\n      this.id = id;\n      this.status = checkNotNull(status, \"status\");\n      this.metadata = metadata != null ? metadata : this.metadata;\n   }\n\n   public int getId() {\n      return id;\n   }\n\n   public Status getStatus() {\n      return status;\n   }\n\n   public Metadata getMetadata() {\n      return metadata;\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).omitNullValues()\n            .add(\"id\", id).add(\"address\", address).add(\"port\", port).add(\"condition\", condition)\n            .add(\"type\", type).add(\"weight\", weight).add(\"status\", status).add(\"metadata\", metadata);\n   }\n   \n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n\n      Node that = Node.class.cast(obj);\n      return Objects.equal(this.id, that.id);\n   }\n\n   /**\n    * The status is determined by the passive or active health monitors.\n    */\n   public static enum Status {\n      /**\n       * Only nodes that are in an ONLINE status will receive and be able to service traffic from\n       * the load balancer.\n       */\n      ONLINE,\n\n      /**\n       * Represents a node that cannot accept or service traffic.\n       */\n      OFFLINE,\n\n      /**\n       * Represents a node that stops the traffic manager from sending any additional new\n       * connections to the node, but honors established sessions.\n       */\n      DRAINING,\n\n      UNRECOGNIZED;\n\n      public static Status fromValue(String status) {\n         try {\n            return valueOf(checkNotNull(status, \"status\"));\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n   }\n\n   public static class Builder extends BaseNode.Builder<Node> {\n      private int id = -1;\n      private Status status;\n      private Metadata metadata;\n\n      public Builder id(int id) {\n         this.id = id;\n         return this;\n      }\n\n      /**\n       * @see Status\n       */\n      public Builder status(Status status) {\n         this.status = status;\n         return this;\n      }\n\n      public Builder metadata(Metadata metadata) {\n         this.metadata = checkNotNull(metadata, \"metadata\");\n         return this;\n      }\n\n      @Override\n      public Node build() {\n         return new Node(address, port, condition, type, weight, id, status, metadata);\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder address(String address) {\n         return Builder.class.cast(super.address(address));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder condition(Condition condition) {\n         return Builder.class.cast(super.condition(condition));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder type(Type type) {\n         return Builder.class.cast(super.type(type));\n      }      \n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder port(int port) {\n         return Builder.class.cast(super.port(port));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder weight(Integer weight) {\n         return Builder.class.cast(super.weight(weight));\n      }\n      @Override\n      public Builder from(Node in) {\n         return Builder.class.cast(super.from(in)).id(in.getId()).status(in.getStatus()).metadata(in.getMetadata());\n      }\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return new Builder().from(this);\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/domain/Protocol.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\npublic final class Protocol {\n   private final String name;\n   private final int port;\n\n   @ConstructorProperties({ \"name\", \"port\" })\n   protected Protocol(String name, int port) {\n      this.name = checkNotNull(name, \"name\");\n      this.port = port;\n   }\n\n   public String getName() {\n      return name;\n   }\n\n   public int getPort() {\n      return port;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(name, port);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      Protocol that = Protocol.class.cast(obj);\n\n      return Objects.equal(this.name, that.name) && Objects.equal(this.port, that.port);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"name\", name).add(\"port\", port).toString();\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/domain/SSLTermination.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Named;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.base.Optional;\n\n/**\n * The SSL Termination feature allows a load balancer user to terminate SSL traffic at the load balancer layer versus \n * at the web server layer. A user may choose to configure SSL Termination using a key and an SSL certificate or an \n * (Intermediate) SSL certificate.\n * <p/> \n * When SSL Termination is configured on a load balancer, a secure shadow server is created that listens only for \n * secure traffic on a user-specified port. This shadow server is only visible to and manageable by the system. \n * Existing or updated attributes on a load balancer with SSL Termination will also apply to its shadow server. \n * For example, if Connection Logging is enabled on an SSL load balancer, it will also be enabled on the shadow server \n * and Cloud Files logs will contain log files for both.\n * <p/>\n * Notes\n * <ol>\n * <li>SSL Termination may only be configured on load balancers with non-secure protocols. For example, SSL Termination \n * can be applied to an HTTP load balancer, but not to an HTTPS load balancer.</li>\n * <li>SSL-terminated load balancers decrypt the traffic at the traffic manager and pass unencrypted traffic to the \n * back-end node. Because of this, the customer's back-end nodes don't know what protocol the client requested. \n * Therefore the X-Forwarded-Proto (XFP) header has been added for identifying the originating protocol of an HTTP \n * request as \"http\" or \"https\" depending on what protocol the client requested.</li>\n * <li>Not every service will return certificates in the proper order. Please verify that your chain of certificates \n * matches that of walking up the chain from the domain to the CA root.</li>\n * </ol>\n * \n * Warning\n * <ol>\n * <li>If SSL is enabled on a load balancer that is configured with nodes that are NOT in the same datacenter, then \n * decrypted traffic will be sent in clear text over the public internet to the external node(s) and will no longer \n * be secure.</li>\n * </ol>\n * \n * <table border=\"1\">\n *   <caption>\n *     Optional SSL Attributes\n *   </caption>\n *   <thead>\n *     <tr align=\"center\">\n *       <td>Optional SSL Attributes</td>\n *       <td>Non-SSL Traffic</td>\n *       <td>SSL Traffic</td>\n *     </tr>\n *   </thead>\n *   <tbody>\n *     <tr align=\"left\">\n *       <td><code class=\"code\">enabled</code> = <code class=\"code\">true</code> (default)</td>\n *       <td>Yes</td>\n *       <td>Yes</td>\n *     </tr>\n *     <tr align=\"left\">\n *       <td><code class=\"code\">enabled</code> = <code class=\"code\">false</code></td>\n *       <td>Yes</td>\n *       <td>No</td>\n *     </tr>\n *     <tr align=\"left\">\n *       <td><code class=\"code\">secureTrafficOnly</code> = <code class=\"code\">true</code></td>\n *       <td>No</td>\n *       <td>Yes</td>\n *     </tr>\n *     <tr align=\"left\">\n *       <td><code class=\"code\">secureTrafficOnly</code> = <code class=\"code\">false</code> (default)</td>\n *       <td>Yes</td>\n *       <td>Yes</td>\n *     </tr>\n *     <tr align=\"left\">\n *       <td>\n *         <p><code class=\"code\">enabled</code> = <code class=\"code\">true</code></p>\n *         <p><code class=\"code\">secureTrafficOnly</code> = <code class=\"code\">true</code></p>\n *     </td>\n *       <td>No</td>\n *       <td>Yes</td>\n *     </tr>\n *     <tr align=\"left\">\n *       <td>\n *         <p><code class=\"code\">enabled</code> = <code class=\"code\">true</code></p>\n *         <p><code class=\"code\">secureTrafficOnly</code> = <code class=\"code\">false</code></p>\n *       </td>\n *       <td>Yes</td>\n *       <td>Yes</td>\n *     </tr>\n *     <tr align=\"left\">\n *       <td>\n *         <p><code class=\"code\">enabled</code> = <code class=\"code\">false</code></p>\n *         <p><code class=\"code\">secureTrafficOnly</code> = <code class=\"code\">false</code></p>\n *       </td>\n *       <td>Yes</td>\n *       <td>No</td>\n *     </tr>\n *     <tr align=\"left\">\n *       <td>\n *         <p><code class=\"code\">enabled</code> = <code class=\"code\">false</code></p>\n *         <p><code class=\"code\">secureTrafficOnly</code> = <code class=\"code\">true</code></p>\n *       </td>\n *       <td>Yes</td>\n *       <td>No</td>\n *     </tr>\n *   </tbody>\n * </table>\n */\npublic class SSLTermination {\n   private final boolean enabled;\n   private final boolean secureTrafficOnly;\n   private final int securePort;\n   private final Optional<String> certificate;\n   @Named(\"privatekey\")\n   private final Optional<String> privateKey;\n   private final Optional<String> intermediateCertificate;\n\n   @ConstructorProperties({ \"enabled\", \"secureTrafficOnly\", \"securePort\", \"certificate\", \"privatekey\",\n         \"intermediateCertificate\" })\n   protected SSLTermination(boolean enabled, boolean secureTrafficOnly, int securePort, String certificate,\n         String privateKey, String intermediateCertificate) {\n      this.enabled = enabled;\n      this.secureTrafficOnly = secureTrafficOnly;\n      this.securePort = securePort;\n      this.certificate = Optional.fromNullable(certificate);\n      this.privateKey = Optional.fromNullable(privateKey);\n      this.intermediateCertificate = Optional.fromNullable(intermediateCertificate);\n   }\n\n   public boolean getEnabled() {\n      return this.enabled;\n   }\n\n   public boolean getSecureTrafficOnly() {\n      return this.secureTrafficOnly;\n   }\n\n   public int getSecurePort() {\n      return this.securePort;\n   }\n\n   public Optional<String> getCertificate() {\n      return this.certificate;\n   }\n\n   public Optional<String> getPrivateKey() {\n      return this.privateKey;\n   }\n\n   public Optional<String> getIntermediateCertificate() {\n      return this.intermediateCertificate;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(enabled, secureTrafficOnly, securePort, certificate, privateKey, intermediateCertificate);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      SSLTermination that = SSLTermination.class.cast(obj);\n\n      return Objects.equal(this.enabled, that.enabled) && Objects.equal(this.secureTrafficOnly, that.secureTrafficOnly)\n            && Objects.equal(this.securePort, that.securePort) && Objects.equal(this.certificate, that.certificate)\n            && Objects.equal(this.privateKey, that.privateKey)\n            && Objects.equal(this.intermediateCertificate, that.intermediateCertificate);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"enabled\", enabled)\n            .add(\"secureTrafficOnly\", secureTrafficOnly).add(\"securePort\", securePort)\n            .add(\"certificate\", certificate.orNull()).add(\"privateKey\", privateKey.orNull())\n            .add(\"intermediateCertificate\", intermediateCertificate.orNull());\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   public static class Builder {\n      private boolean enabled;\n      private boolean secureTrafficOnly;\n      private int securePort;\n      private String certificate;\n      private String privateKey;\n      private String intermediateCertificate;\n\n      /**\n       * Required. Determines if the load balancer is enabled to terminate SSL traffic.\n       * </p>\n       * If enabled = false, the load balancer will retain its specified SSL attributes, but will not terminate SSL traffic.\n       */\n      public Builder enabled(boolean enabled) {\n         this.enabled = enabled;\n         return this;\n      }\n\n      /**\n       * Required. Determines if the load balancer may accept only secure traffic.\n       * </p>\n       * If secureTrafficOnly = true, the load balancer will not accept non-secure traffic.\n       */\n      public Builder secureTrafficOnly(boolean secureTrafficOnly) {\n         this.secureTrafficOnly = secureTrafficOnly;\n         return this;\n      }\n\n      /**\n       * Required. The port on which the SSL termination load balancer will listen for secure traffic.\n       * </p>\n       * The securePort must be unique to the existing LB protocol/port combination. For example, port 443.\n       */\n      public Builder securePort(int securePort) {\n         this.securePort = securePort;\n         return this;\n      }\n\n      /**\n       * Required. The certificate used for SSL termination.\n       * </p>\n       * The certificate is validated and verified against the key and intermediate certificate if provided.\n       * </p>\n       * All requests to SSL termination require the key/certificates to be in \"proper\" format, meaning that all raw \n       * line feed characters should be wrapped in a newline character. So if the user pastes in the key from a \n       * mykey.key file, it will not properly handle the field. For example, use string.replaceAll(\"\\n\", \"\\\\n\").\n       */\n      public Builder certificate(String certificate) {\n         this.certificate = certificate;\n         return this;\n      }\n\n      /**\n       * Required. The private key for the SSL certificate.\n       * </p>\n       * The private key is validated and verified against the provided certificate(s).\n       * \n       * @see SSLTermination#certificate(String)\n       */\n      public Builder privatekey(String privateKey) {\n         this.privateKey = privateKey;\n         return this;\n      }\n\n      /**\n       * Optional only when configuring Intermediate SSL Termination. The user's intermediate certificate used for SSL\n       * termination.\n       * </p>\n       * The intermediate certificate is validated and verified against the key and certificate credentials provided.\n       * </p>\n       * A user may only provide an intermediateCertificate when accompanied by a certificate, private key, and \n       * securePort. It may not be added to an existing SSL configuration as a single attribute in a future request.\n       * \n       * @see SSLTermination#certificate(String)\n       */\n      public Builder intermediateCertificate(String intermediateCertificate) {\n         this.intermediateCertificate = intermediateCertificate;\n         return this;\n      }\n\n      public SSLTermination build() {\n         return new SSLTermination(enabled, secureTrafficOnly, securePort, certificate, privateKey,\n               intermediateCertificate);\n      }\n\n      public Builder from(SSLTermination in) {\n         return this.enabled(in.getEnabled()).secureTrafficOnly(in.getSecureTrafficOnly())\n               .securePort(in.getSecurePort()).certificate(in.getCertificate().orNull())\n               .privatekey(in.getPrivateKey().orNull())\n               .intermediateCertificate(in.getIntermediateCertificate().orNull());\n      }\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return new Builder().from(this);\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/domain/SessionPersistence.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\n/**\n * Session persistence is a feature of the load balancing service that forces multiple requests from clients to be\n * directed to the same node. This is common with many web applications that do not inherently share application\n * state between back-end servers.\n */\npublic enum SessionPersistence {\n   /**\n    * A session persistence mechanism that inserts an HTTP cookie and is used to determine the destination back-end\n    * node. This is supported for HTTP load balancing only.\n    */\n   HTTP_COOKIE,\n   /**\n    * A session persistence mechanism that will keep track of the source IP address that is mapped and is able to\n    * determine the destination back-end node. This is supported for HTTPS pass-through and non-HTTP load balancing\n    * only.\n    */\n   SOURCE_IP,\n\n   UNRECOGNIZED;\n\n   public static SessionPersistence fromValue(String sessionPersistence) {\n      try {\n         return valueOf(checkNotNull(sessionPersistence, \"sessionPersistence\"));\n      }\n      catch (IllegalArgumentException e) {\n         return UNRECOGNIZED;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/domain/SourceAddresses.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.domain;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * The load balancer source IP addresses are useful for customers who are automating the deployment of infrastructure \n * and need to determine the IP addresses of requests coming from our load balancers for the purpose of creating more \n * robust firewall rules.\n */\npublic class SourceAddresses {\n\n   private final String ipv6Public;\n   private final String ipv4Public;\n   private final String ipv4Servicenet;\n\n   protected SourceAddresses(String ipv6Public, String ipv4Public, String ipv4Servicenet) {\n      this.ipv6Public = ipv6Public;\n      this.ipv4Public = ipv4Public;\n      this.ipv4Servicenet = ipv4Servicenet;\n   }\n\n   public String getIPV6Public() {\n      return this.ipv6Public;\n   }\n\n   public String getIPV4Public() {\n      return this.ipv4Public;\n   }\n\n   public String getIPV4Servicenet() {\n      return this.ipv4Servicenet;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(ipv6Public, ipv4Public, ipv4Servicenet);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      SourceAddresses that = SourceAddresses.class.cast(obj);\n      return Objects.equal(this.ipv6Public, that.ipv6Public) && Objects.equal(this.ipv4Public, that.ipv4Public)\n            && Objects.equal(this.ipv4Servicenet, that.ipv4Servicenet);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).add(\"ipv6Public\", ipv6Public).add(\"ipv4Public\", ipv4Public)\n            .add(\"ipv4Servicenet\", ipv4Servicenet);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   public static class Builder {\n      private String ipv6Public;\n      private String ipv4Public;\n      private String ipv4Servicenet;\n\n      /** \n       * @see SourceAddresses#getIPV6Public()\n       */\n      public Builder ipv6Public(String ipv6Public) {\n         this.ipv6Public = ipv6Public;\n         return this;\n      }\n\n      /** \n       * @see SourceAddresses#getIPV4Public()\n       */\n      public Builder ipv4Public(String ipv4Public) {\n         this.ipv4Public = ipv4Public;\n         return this;\n      }\n\n      /** \n       * @see SourceAddresses#getIPV4Servicenet()\n       */\n      public Builder ipv4Servicenet(String ipv4Servicenet) {\n         this.ipv4Servicenet = ipv4Servicenet;\n         return this;\n      }\n\n      public SourceAddresses build() {\n         return new SourceAddresses(ipv6Public, ipv4Public, ipv4Servicenet);\n      }\n\n      public Builder from(SourceAddresses in) {\n         return this.ipv6Public(in.getIPV6Public()).ipv4Public(in.getIPV4Public())\n               .ipv4Servicenet(in.getIPV4Servicenet());\n      }\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return new Builder().from(this);\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/domain/UpdateLoadBalancer.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.domain;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.internal.BaseLoadBalancer.Algorithm;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Used to update Load Balancers.\n */\npublic class UpdateLoadBalancer {\n   private final String name;\n   private final String protocol;\n   private final Integer port;\n   private final Algorithm algorithm;\n   private final Integer timeout;\n   private final Boolean halfClosed;\n\n   protected UpdateLoadBalancer(@Nullable String name, @Nullable String protocol, @Nullable Integer port,\n         @Nullable Algorithm algorithm, @Nullable Integer timeout, @Nullable Boolean halfClosed) {\n      this.name = name;\n      this.protocol = protocol;\n      this.port = port;\n      this.algorithm = algorithm;\n      this.timeout = timeout;\n      this.halfClosed = halfClosed;\n   }\n\n   public String getName() {\n      return name;\n   }\n\n   public String getProtocol() {\n      return protocol;\n   }\n\n   public Integer getPort() {\n      return port;\n   }\n\n   public Algorithm getAlgorithm() {\n      return algorithm;\n   }\n\n   public Integer getTimeout() {\n      return timeout;\n   }\n\n   public Boolean isHalfClosed() {\n      return halfClosed;\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"name\", name).add(\"algorithm\", algorithm)\n            .add(\"port\", port).add(\"protocol\", protocol).add(\"timeout\", timeout).add(\"halfClosed\", halfClosed);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(name, algorithm, port, protocol, timeout, halfClosed);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n\n      UpdateLoadBalancer that = UpdateLoadBalancer.class.cast(obj);\n      return Objects.equal(this.name, that.name) && Objects.equal(this.algorithm, that.algorithm)\n            && Objects.equal(this.port, that.port) && Objects.equal(this.protocol, that.protocol)\n            && Objects.equal(this.timeout, that.timeout) && Objects.equal(this.halfClosed, that.halfClosed);\n   }\n\n   public static class Builder {\n      private String name;\n      private String protocol;\n      private Integer port;\n      private Algorithm algorithm;\n      private Integer timeout;\n      private Boolean halfClosed;\n\n      /**\n       * @see BaseLoadBalancer.Builder#name(String)\n       */\n      public Builder name(String name) {\n         this.name = name;\n         return this;\n      }\n\n      /**\n       * @see BaseLoadBalancer.Builder#protocol(String)\n       */\n      public Builder protocol(String protocol) {\n         this.protocol = protocol;\n         return this;\n      }\n\n      /**\n       * @see BaseLoadBalancer.Builder#port(Integer)\n       */\n      public Builder port(Integer port) {\n         this.port = port;\n         return this;\n      }\n\n      /**\n       * @see BaseLoadBalancer.Builder#algorithm(Algorithm)\n       */\n      public Builder algorithm(Algorithm algorithm) {\n         this.algorithm = algorithm;\n         return this;\n      }\n\n      /**\n       * @see BaseLoadBalancer.Builder#timeout(Integer)\n       */\n      public Builder timeout(Integer timeout) {\n         this.timeout = timeout;\n         return this;\n      }\n\n      /**\n       * @see BaseLoadBalancer.Builder#halfClosed(Boolean)\n       */\n      public Builder halfClosed(Boolean halfClosed) {\n         this.halfClosed = halfClosed;\n         return this;\n      }\n\n      public UpdateLoadBalancer build() {\n         return new UpdateLoadBalancer(name, protocol, port, algorithm, timeout, halfClosed);\n      }\n\n      public Builder from(UpdateLoadBalancer lb) {\n         return this.name(lb.getName()).port(lb.getPort()).protocol(lb.getProtocol()).algorithm(lb.getAlgorithm())\n               .timeout(lb.getTimeout()).halfClosed(lb.isHalfClosed());\n      }\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return new Builder().from(this);\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/domain/UpdateNode.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.domain;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.internal.BaseNode.Condition;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.internal.BaseNode.Type;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Used to update Nodes.\n */\npublic class UpdateNode {\n   private final Condition condition;\n   private final Type type;\n   private final Integer weight;\n   \n   protected UpdateNode(@Nullable Condition condition, @Nullable Type type, @Nullable Integer weight) {\n      this.condition = condition;\n      this.type = type;\n      this.weight = weight;\n   }\n\n   public Condition getCondition() {\n      return condition;\n   }\n\n   public Type getType() {\n      return type;\n   }\n\n   public Integer getWeight() {\n      return weight;\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).omitNullValues()\n            .add(\"condition\", condition).add(\"type\", type).add(\"weight\", weight);\n   }\n   \n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(condition, type, weight);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n\n      UpdateNode that = UpdateNode.class.cast(obj);\n      return Objects.equal(this.condition, that.condition)\n            && Objects.equal(this.type, that.type)\n            && Objects.equal(this.weight, that.weight);\n   }\n\n   public static class Builder {\n      private Condition condition;\n      private Type type;\n      private Integer weight;\n\n      /**\n       * @see BaseNode.Builder#condition(Condition)\n       */\n      public Builder condition(Condition condition) {\n         this.condition = condition;\n         return this;\n      }\n\n      /**\n       * @see BaseNode.Builder#type(Type)\n       */\n      public Builder type(Type type) {\n         this.type = type;\n         return this;\n      }\n\n      /**\n       * @see BaseNode.Builder#weight(Integer)\n       */\n      public Builder weight(Integer weight) {\n         this.weight = weight;\n         return this;\n      }\n      \n      public UpdateNode build() {\n         return new UpdateNode(condition, type, weight);\n      }\n\n      public Builder from(UpdateNode in) {\n         return this.condition(in.getCondition()).type(in.getType()).weight(in.getWeight());\n      }\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return new Builder().from(this);\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/domain/VirtualIP.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * A virtual IP (VIP) makes a load balancer accessible by clients. The load balancing service\n * supports either a public virtual IP, routable on the public Internet, or a ServiceNet address, routable\n * only within the region in which the load balancer resides.\n */\npublic class VirtualIP {\n\n   private final Type type;\n   private final IPVersion ipVersion;\n\n   /**\n    * Use this method to easily create virtual IPs. Only public IPv6 virtual IPs can be created.\n    */\n   public static VirtualIP publicIPv6() {\n      return new VirtualIP(Type.PUBLIC, IPVersion.IPV6);\n   }\n   \n   protected VirtualIP(Type type, IPVersion ipVersion) {\n      this.type = checkNotNull(type, \"type\");\n      this.ipVersion = checkNotNull(ipVersion, \"ipVersion\");\n   }\n\n   public Type getType() {\n      return type;\n   }\n\n   public IPVersion getIpVersion() {\n      return ipVersion;\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).omitNullValues()\n            .add(\"ipVersion\", ipVersion).add(\"type\", type);\n   }\n   \n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(ipVersion, type);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n\n      VirtualIP that = VirtualIP.class.cast(obj);\n      return Objects.equal(this.ipVersion, that.ipVersion)\n            && Objects.equal(this.type, that.type);\n   }\n\n   /**\n    * Virtual IP Types\n    */\n   public static enum Type {\n      /**\n       * An address that is routable on the public Internet.\n       */\n      PUBLIC,\n      /**\n       * An address that is routable only on the Rackspace ServiceNet.\n       */\n      SERVICENET, UNRECOGNIZED;\n\n      public static Type fromValue(String type) {\n         try {\n            return valueOf(checkNotNull(type, \"type\"));\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n\n   }\n\n   /**\n    * Virtual IP Versions\n    */\n   public static enum IPVersion {\n\n      IPV4, IPV6, UNRECOGNIZED;\n\n      public static IPVersion fromValue(String ipVersion) {\n         try {\n            return valueOf(checkNotNull(ipVersion, \"ipVersion\"));\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/domain/VirtualIPWithId.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * @see VirtualIP\n */\npublic class VirtualIPWithId extends VirtualIP {\n\n   private final int id;\n   private final String address;\n\n   public VirtualIPWithId(Type type, IPVersion ipVersion, int id, String address) {\n      super(type, ipVersion);\n      this.id = id;\n      this.address = checkNotNull(address, \"address\");\n   }\n\n   public int getId() {\n      return id;\n   }\n\n   public String getAddress() {\n      return address;\n   }\n   \n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).omitNullValues()\n            .add(\"id\", id).add(\"address\", address).add(\"ipVersion\", getIpVersion()).add(\"type\", getType());\n   }\n   \n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n\n      VirtualIPWithId that = VirtualIPWithId.class.cast(obj);\n      return Objects.equal(this.id, that.id);\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/domain/internal/BaseLoadBalancer.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.domain.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Collection;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.SortedSet;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.ConnectionThrottle;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.HealthMonitor;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.LoadBalancer;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.SessionPersistence;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSortedSet;\nimport com.google.common.collect.Maps;\nimport com.google.common.collect.Sets;\n\npublic class BaseLoadBalancer<N extends BaseNode<N>, T extends BaseLoadBalancer<N, T>> implements\n      Comparable<BaseLoadBalancer<N, T>> {\n\n   private static final String ENABLED = \"enabled\";\n   private static final String PERSISTENCE_TYPE = \"persistenceType\";\n   public static final Collection<Algorithm> WEIGHTED_ALGORITHMS = ImmutableSet.of(\n         Algorithm.WEIGHTED_LEAST_CONNECTIONS,\n         Algorithm.WEIGHTED_ROUND_ROBIN);\n\n   protected String name;\n   protected String protocol;\n   protected Integer port;\n   protected SortedSet<N> nodes = ImmutableSortedSet.of(); // so tests will come out consistently\n   protected Algorithm algorithm;\n   protected Integer timeout;\n   protected Boolean halfClosed;\n   protected Map<String, SessionPersistence> sessionPersistence;\n   protected Map<String, Boolean> connectionLogging;\n   protected ConnectionThrottle connectionThrottle;\n   protected HealthMonitor healthMonitor;\n\n   // for serialization only\n   protected BaseLoadBalancer() {\n   }\n\n   public BaseLoadBalancer(String name, @Nullable String protocol, @Nullable Integer port, Iterable<N> nodes,\n         @Nullable Algorithm algorithm, @Nullable Integer timeout, @Nullable Boolean halfClosed,\n         @Nullable Map<String, SessionPersistence> sessionPersistence,\n         @Nullable Map<String, Boolean> connectionLogging, @Nullable ConnectionThrottle connectionThrottle,\n         @Nullable HealthMonitor healthMonitor) {\n      this.name = checkNotNull(name, \"name\");\n      this.protocol = protocol;  // null on deleted LB\n      this.port = port;  // null on deleted LB\n      this.nodes = ImmutableSortedSet.copyOf(checkNotNull(nodes, \"nodes\"));\n      this.algorithm = algorithm;  // null on deleted LB\n      this.timeout = timeout;\n      this.halfClosed = halfClosed;\n      this.sessionPersistence = sessionPersistence;\n      this.connectionLogging = connectionLogging;\n      this.connectionThrottle = connectionThrottle;\n      this.healthMonitor = healthMonitor;\n   }\n\n   @Override\n   public int compareTo(BaseLoadBalancer<N, T> arg0) {\n      return name.compareTo(arg0.name);\n   }\n\n   public String getName() {\n      return name;\n   }\n\n   /**\n    * @return protocol, which may be null if the load balancer is deleted.\n    */\n   @Nullable\n   public String getProtocol() {\n      return protocol;\n   }\n\n   /**\n    * @return port, which may be null if port has not been set.\n    */\n   @Nullable\n   public Integer getPort() {\n      return port;\n   }\n\n   public Set<N> getNodes() {\n      return nodes;\n   }\n\n   /**\n    * @return algorithm, which may be null if the load balancer is deleted.\n    */\n   @Nullable\n   public Algorithm getAlgorithm() {\n      return algorithm;\n   }\n\n   /**\n    * @return timeout, which may be null if no timeout has been set.\n    */\n   @Nullable\n   public Integer getTimeout() {\n      return timeout;\n   }\n\n   /**\n    * @return halfClosed, which may be null if halfClosed has not been set.\n    */\n   @Nullable\n   public Boolean isHalfClosed() {\n      return halfClosed;\n   }\n\n   /**\n    * @return sessionPersistenceType, which may be null if sessionPersistenceType has not been set.\n    */\n   @Nullable\n   public SessionPersistence getSessionPersistenceType() {\n      return sessionPersistence == null ? null : sessionPersistence.get(PERSISTENCE_TYPE);\n   }\n\n   public boolean isConnectionLogging() {\n      return connectionLogging == null ? false : connectionLogging.get(ENABLED);\n   }\n\n   /**\n    * @return connectionThrottle, which may be null if connectionThrottle has not been set.\n    */\n   @Nullable\n   public ConnectionThrottle getConnectionThrottle() {\n      return connectionThrottle;\n   }\n\n   /**\n    * @return healthMonitor, which may be null if healthMonitor has not been set.\n    */\n   @Nullable\n   public HealthMonitor getHealthMonitor() {\n      return healthMonitor;\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"name\", name).add(\"protocol\", protocol)\n            .add(\"port\", port).add(\"nodes\", nodes).add(\"timeout\", timeout).add(\"algorithm\", algorithm)\n            .add(\"timeout\", timeout).add(\"sessionPersistenceType\", getSessionPersistenceType())\n            .add(\"connectionLogging\", connectionLogging).add(\"connectionThrottle\", connectionThrottle)\n            .add(\"healthMonitor\", healthMonitor);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(name);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n\n      LoadBalancer that = LoadBalancer.class.cast(obj);\n      return Objects.equal(this.name, that.name);\n   }\n\n   /**\n    * All load balancers utilize an algorithm that defines how traffic should be directed between\n    * back-end nodes. The default algorithm for newly created load balancers is RANDOM, which can be\n    * overridden at creation time or changed after the load balancer has been initially provisioned.\n    * The algorithm name is to be constant within a major revision of the load balancing API, though\n    * new algorithms may be created with a unique algorithm name within a given major revision of\n    * the service API.\n    */\n   public static enum Algorithm {\n      /**\n       * The node with the lowest number of connections will receive requests.\n       */\n      LEAST_CONNECTIONS,\n      /**\n       * Back-end servers are selected at random.\n       */\n      RANDOM,\n      /**\n       * Connections are routed to each of the back-end servers in turn.\n       */\n      ROUND_ROBIN,\n      /**\n       * Each request will be assigned to a node based on the number of concurrent connections to\n       * the node and its weight.\n       */\n      WEIGHTED_LEAST_CONNECTIONS,\n      /**\n       * A round robin algorithm, but with different proportions of traffic being directed to the\n       * back-end nodes. Weights must be defined as part of the load balancer's node configuration.\n       */\n      WEIGHTED_ROUND_ROBIN, UNRECOGNIZED;\n\n      public static Algorithm fromValue(String algorithm) {\n         try {\n            return valueOf(checkNotNull(algorithm, \"algorithm\"));\n         }\n         catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n   }\n\n   public static class Builder<N extends BaseNode<N>, T extends BaseLoadBalancer<N, T>> {\n      protected String name;\n      protected String protocol;\n      protected Integer port;\n      protected Set<N> nodes = Sets.newLinkedHashSet();\n      protected Algorithm algorithm;\n      protected Integer timeout;\n      protected Boolean halfClosed;\n      protected Map<String, SessionPersistence> sessionPersistence;\n      protected Map<String, Boolean> connectionLogging;\n      protected ConnectionThrottle connectionThrottle;\n      protected HealthMonitor healthMonitor;\n\n      /**\n       * Required. Name of the load balancer to create. The name must be 128 characters or less in length, and all \n       * UTF-8 characters are valid.\n       */\n      public Builder<N, T> name(String name) {\n         this.name = checkNotNull(name, \"name\");\n         return this;\n      }\n\n      /**\n       * Required. Protocol of the service which is being load balanced.\n       * \n       * @see ReportApi#listProtocols()\n       */\n      public Builder<N, T> protocol(String protocol) {\n         this.protocol = protocol;\n         return this;\n      }\n\n      /**\n       * Required if the protocol being used is not in {@link ReportApi#listProtocols()} or the protocol is in \n       * {@link ReportApi#listProtocols()} but port=0. Port number for the service you are load balancing.\n       */\n      public Builder<N, T> port(@Nullable Integer port) {\n         this.port = port;\n         return this;\n      }\n\n      /**\n       * Required. Nodes to be added to the load balancer.\n       */\n      public Builder<N, T> nodes(Iterable<N> nodes) {\n         this.nodes = ImmutableSet.<N> copyOf(checkNotNull(nodes, \"nodes\"));\n         return this;\n      }\n\n      @SuppressWarnings(\"unchecked\")\n      public Builder<N, T> node(N node) {\n         this.nodes.add((N) checkNotNull(nodes, \"nodes\"));\n         return this;\n      }\n\n      /**\n       * Algorithm that defines how traffic should be directed between back-end nodes. \n       * \n       * @see Algorithm\n       */\n      public Builder<N, T> algorithm(@Nullable Algorithm algorithm) {\n         this.algorithm = algorithm;\n         return this;\n      }\n\n      /**\n       * The timeout value for the load balancer and communications with its nodes. Defaults to 30 seconds with \n       * a maximum of 120 seconds.\n       */\n      public Builder<N, T> timeout(@Nullable Integer timeout) {\n         this.timeout = timeout;\n         return this;\n      }\n\n      /**\n       * Enable or Disable Half-Closed support for the load balancer. Half-Closed support provides the ability \n       * for one end of the connection to terminate its output, while still receiving data from the other end. \n       * Only available for TCP/TCP_CLIENT_FIRST protocols.\n       */\n      public Builder<N, T> halfClosed(@Nullable Boolean halfClosed) {\n         this.halfClosed = halfClosed;\n         return this;\n      }\n\n      /**\n       * Specifies whether multiple requests from clients are directed to the same node.\n       * \n       * @see SessionPersistence\n       */\n      public Builder<N, T> sessionPersistenceType(@Nullable SessionPersistence sessionPersistenceType) {\n         if (sessionPersistenceType != null) {\n            this.sessionPersistence = Maps.newHashMap();\n            this.sessionPersistence.put(PERSISTENCE_TYPE, sessionPersistenceType);\n         }\n         else {\n            this.sessionPersistence = null;\n         }\n\n         return this;\n      }\n\n      /**\n       * Current connection logging configuration. \n       */\n      public Builder<N, T> connectionLogging(@Nullable Boolean connectionLogging) {\n         if (connectionLogging != null) {\n            this.connectionLogging = Maps.newHashMap();\n            this.connectionLogging.put(ENABLED, connectionLogging);\n         }\n         else {\n            this.connectionLogging = null;\n         }\n\n         return this;\n      }\n\n      /**\n       * Specifies limits on the number of connections per IP address to help mitigate malicious or abusive \n       * traffic to your applications.\n       * \n       * @see ConnectionThrottle\n       */\n      public Builder<N, T> connectionThrottle(@Nullable ConnectionThrottle connectionThrottle) {\n         this.connectionThrottle = connectionThrottle;\n         return this;\n      }\n\n      /**\n       * The type of health monitor check to perform to ensure that the service is performing properly.\n       * \n       * @see HealthMonitor\n       */\n      public Builder<N, T> healthMonitor(@Nullable HealthMonitor healthMonitor) {\n         this.healthMonitor = healthMonitor;\n         return this;\n      }\n\n      public BaseLoadBalancer<N, T> build() {\n         return new BaseLoadBalancer<N, T>(name, protocol, port, nodes, algorithm, timeout, halfClosed,\n               sessionPersistence, connectionLogging, connectionThrottle, healthMonitor);\n      }\n\n      public Builder<N, T> from(T baseLB) {\n         return name(baseLB.getName()).protocol(baseLB.getProtocol()).port(baseLB.getPort())\n               .algorithm(baseLB.getAlgorithm()).timeout(baseLB.getTimeout()).halfClosed(baseLB.isHalfClosed())\n               .nodes(baseLB.getNodes()).sessionPersistenceType(baseLB.getSessionPersistenceType())\n               .connectionLogging(baseLB.isConnectionLogging()).connectionThrottle(baseLB.getConnectionThrottle())\n               .healthMonitor(baseLB.getHealthMonitor());\n      }\n   }\n\n   public static <N extends BaseNode<N>, T extends BaseLoadBalancer<N, T>> Builder<N, T> builder() {\n      return new Builder<N, T>();\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   public Builder<N, T> toBuilder() {\n      return new Builder<N, T>().from((T) this);\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/domain/internal/BaseNode.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.domain.internal;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * The nodes defined by the load balancer are responsible for servicing the requests received\n * through the load balancer's virtual IP. By default, the load balancer employs a basic health\n * check that ensures the node is listening on its defined port. The node is checked at the time of\n * addition and at regular intervals as defined by the load balancer health check configuration. If\n * a back-end node is not listening on its port or does not meet the conditions of the defined\n * active health check for the load balancer, then the load balancer will not forward connections\n * and its status will be listed as OFFLINE. Only nodes that are in an ONLINE status will receive\n * and be able to service traffic from the load balancer.\n * <p/>\n * All nodes have an associated status that indicates whether the node is ONLINE, OFFLINE, or\n * DRAINING. Only nodes that are in ONLINE status will receive and be able to service traffic from\n * the load balancer. The OFFLINE status represents a node that cannot accept or service traffic. A\n * node in DRAINING status represents a node that stops the traffic manager from sending any\n * additional new connections to the node, but honors established sessions. If the traffic manager\n * receives a request and session persistence requires that the node is used, the traffic manager\n * will use it. The status is determined by the passive or active health monitors.\n * <p/>\n * If the WEIGHTED_ROUND_ROBIN load balancer algorithm mode is selected, then the caller should\n * assign the relevant weights to the node as part of the weight attribute of the node element. When\n * the algorithm of the load balancer is changed to WEIGHTED_ROUND_ROBIN and the nodes do not\n * already have an assigned weight, the service will automatically set the weight to \"1\" for all\n * nodes.\n */\npublic class BaseNode<T extends BaseNode<T>> implements Comparable<BaseNode<T>> {\n\n   protected String address;\n   protected int port;\n   protected Condition condition;\n   protected Type type;\n   protected Integer weight;\n\n   // for serialization only\n   protected BaseNode() {\n   }\n\n   public BaseNode(String address, int port, Condition condition, Type type, Integer weight) {\n      this.address = checkNotNull(address, \"address\");\n      checkArgument(port != -1, \"port must be specified\");\n      this.port = port;\n      this.condition = checkNotNull(condition, \"condition\");\n      this.type = type;\n      this.weight = weight;\n   }\n\n   public String getAddress() {\n      return address;\n   }\n\n   public int getPort() {\n      return port;\n   }\n\n   public Condition getCondition() {\n      return condition;\n   }\n\n   public Type getType() {\n      return type;\n   }\n\n   /**\n    * the maximum weight of a node is 100.\n    */\n   public Integer getWeight() {\n      return weight;\n   }\n\n   @Override\n   public int compareTo(BaseNode<T> arg0) {\n      return address.compareTo(arg0.address);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"address\", address).add(\"port\", port)\n            .add(\"condition\", condition).add(\"type\", type).add(\"weight\", weight);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(address, port, condition);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n\n      BaseNode<?> that = BaseNode.class.cast(obj);\n      return Objects.equal(this.address, that.address) && Objects.equal(this.port, that.port)\n            && Objects.equal(this.condition, that.condition);\n   }\n\n   /**\n    * Virtual IP Conditions\n    */\n   public static enum Condition {\n      /**\n       * Node is permitted to accept new connections.\n       */\n      ENABLED,\n      /**\n       * Node is not permitted to accept any new connections regardless of session persistence\n       * configuration. Existing connections are forcibly terminated.\n       */\n      DISABLED,\n      /**\n       * Node is allowed to service existing established connections and connections that are being\n       * directed to it as a result of the session persistence configuration.\n       */\n      DRAINING,\n\n      UNRECOGNIZED;\n\n      public static Condition fromValue(String condition) {\n         try {\n            return valueOf(checkNotNull(condition, \"condition\"));\n         }\n         catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n\n   }\n\n   /**\n    * Type of node.\n    */\n   public static enum Type {\n      /**\n       * Nodes defined as PRIMARY are in the normal rotation to receive traffic from the load balancer.\n       */\n      PRIMARY,\n\n      /**\n       * Nodes defined as SECONDARY are only in the rotation to receive traffic from the load balancer when all the\n       * primary nodes fail. This provides a failover feature that automatically routes traffic to the secondary node\n       * in the event that the primary node is disabled or in a failing state. Note that active health monitoring must\n       * be enabled on the load balancer to enable the failover feature to the secondary node.\n       */\n      SECONDARY,\n\n      UNRECOGNIZED;\n\n      public static Type fromValue(String type) {\n         try {\n            return valueOf(checkNotNull(type, \"type\"));\n         }\n         catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n   }\n\n   public static class Builder<T extends BaseNode<T>> {\n      protected String address;\n      protected int port = -1;\n      protected Condition condition = Condition.ENABLED;\n      protected Type type;\n      protected Integer weight;\n\n      /**\n       * Required. IP address or domain name for the node.\n       */\n      public Builder<T> address(String address) {\n         this.address = address;\n         return this;\n      }\n\n      /**\n       * Required. Port number for the service you are load balancing.\n       */\n      public Builder<T> port(int port) {\n         this.port = port;\n         return this;\n      }\n\n      /**\n       * Required. Condition for the node, which determines its role within the load balancer.\n       * \n       * @see Condition\n       */\n      public Builder<T> condition(Condition condition) {\n         this.condition = condition;\n         return this;\n      }\n\n      /**\n       * Type of node to add.\n       * \n       * @see Type\n       */\n      public Builder<T> type(Type type) {\n         this.type = type;\n         return this;\n      }\n\n      /**\n       * Weight of node to add. If the {@link Algorithm#WEIGHTED_ROUND_ROBIN} load balancer algorithm mode is \n       * selected, then the user should assign the relevant weight to the node using the weight attribute for \n       * the node. Must be an integer from 1 to 100.\n       */\n      public Builder<T> weight(Integer weight) {\n         this.weight = weight;\n         return this;\n      }\n\n      public BaseNode<T> build() {\n         return new BaseNode<T>(address, port, condition, type, weight);\n      }\n\n      public Builder<T> from(T in) {\n         return address(in.getAddress()).port(in.getPort()).condition(in.getCondition()).type(in.getType())\n               .weight(in.getWeight());\n      }\n   }\n\n   public static <T extends BaseNode<T>> Builder<T> builder() {\n      return new Builder<T>();\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   public Builder<T> toBuilder() {\n      return new Builder<T>().from((T) this);\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/features/AccessRuleApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyPagedIterableOnNotFoundOr404;\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.AccessRule;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.AccessRuleWithId;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.WrapWith;\n\n/**\n * The access list management feature allows fine-grained network access controls to be applied to the load balancer's\n * virtual IP address.\n * <p/>\n */\n@RequestFilters(AuthenticateRequest.class)\npublic interface AccessRuleApi {\n   /**\n    * Create new access rules or append to existing access rules.\n    * \n    * When creating access rules, one or more AccessRules are required. If populated access rules already exist \n    * for the load balancer, it will be appended to with subsequent creates. One access list may include up to 100 \n    * AccessRules. A single address or subnet definition is considered unique and cannot be duplicated between rules\n    * in an access list.\n    */\n   @Named(\"accessrule:create\")\n   @POST\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(VoidOnNotFoundOr404.class)\n   @Path(\"/accesslist\")\n   void create(@WrapWith(\"accessList\") Iterable<AccessRule> accessRules);\n\n   /**\n    * List the AccessRules.\n    */\n   @Named(\"accessrule:list\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   @SelectJson(\"accessList\")\n   @Path(\"/accesslist\")\n   Iterable<AccessRuleWithId> list();\n   \n   /**\n    * Delete an access rule from the access list.\n    * \n    * @return true on a successful delete, false if the access rule was not found\n    */\n   @Named(\"accessrule:delete\")\n   @DELETE\n   @Fallback(FalseOnNotFoundOr404.class)\n   @Path(\"/accesslist/{id}\")\n   @Consumes(\"*/*\")\n   boolean delete(@PathParam(\"id\") int id);\n   \n   /**\n    * Batch delete the access rules given the specified ids.\n    * \n    * @return true on a successful delete, false if the access rule was not found\n    */\n   @Named(\"accessrule:delete\")\n   @DELETE\n   @Fallback(FalseOnNotFoundOr404.class)\n   @Path(\"/accesslist\")\n   @Consumes(\"*/*\")\n   boolean delete(@QueryParam(\"id\") Iterable<Integer> ids);\n   \n   /**\n    * Delete the entire access list.\n    * \n    * @return true on a successful delete, false if the access rule was not found\n    */\n   @Named(\"accessrule:delete\")\n   @DELETE\n   @Fallback(FalseOnNotFoundOr404.class)\n   @Path(\"/accesslist\")\n   @Consumes(\"*/*\")\n   boolean deleteAll();\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/features/ConnectionApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr422;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.ConnectionThrottle;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.functions.ParseNestedBoolean;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.WrapWith;\n\n/**\n * Connection management features.\n * <p/>\n */\n@RequestFilters(AuthenticateRequest.class)\npublic interface ConnectionApi {\n   /**\n    * The connection throttling feature imposes limits on the number of connections per IP address to help mitigate \n    * malicious or abusive traffic to your applications.\n    */\n   @Named(\"connectionthrottle:create\")\n   @PUT\n   @Consumes(MediaType.APPLICATION_JSON) \n   @Fallback(VoidOnNotFoundOr404.class)\n   @Path(\"/connectionthrottle\")\n   void createOrUpdateConnectionThrottle(\n         @WrapWith(\"connectionThrottle\") ConnectionThrottle connectionThrottle);\n\n   /**\n    * Get connection throttle.\n    */\n   @Named(\"connectionthrottle:get\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @SelectJson(\"connectionThrottle\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Path(\"/connectionthrottle\")\n   ConnectionThrottle getConnectionThrottle();\n   \n   /**\n    * Delete connection throttle.\n    * \n    * @return true on a successful delete, false if the connection throttle was not found.\n    */\n   @Named(\"connectionthrottle:delete\")\n   @DELETE\n   @Fallback(FalseOnNotFoundOr422.class)\n   @Path(\"/connectionthrottle\")\n   @Consumes(\"*/*\")\n   boolean deleteConnectionThrottle();\n   \n   /**\n    * Determine if the load balancer is logging connections.\n    */\n   @Named(\"connectionlogging:state\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @ResponseParser(ParseNestedBoolean.class)\n   @Fallback(FalseOnNotFoundOr404.class)\n   @Path(\"/connectionlogging\")\n   boolean isConnectionLogging();\n   \n   /**\n    * Enable logging connections.\n    */\n   @Named(\"connectionlogging:state\")\n   @PUT\n   @Produces(MediaType.APPLICATION_JSON)\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(VoidOnNotFoundOr404.class)\n   @Payload(\"{\\\"connectionLogging\\\":{\\\"enabled\\\":true}}\")\n   @Path(\"/connectionlogging\")\n   void enableConnectionLogging();\n   \n   /**\n    * Disable logging connections.\n    */\n   @Named(\"connectionlogging:state\")\n   @PUT\n   @Produces(MediaType.APPLICATION_JSON)\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(VoidOnNotFoundOr404.class)\n   @Payload(\"{\\\"connectionLogging\\\":{\\\"enabled\\\":false}}\")\n   @Path(\"/connectionlogging\")\n   void disableConnectionLogging();\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/features/ContentCachingApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.functions.ParseNestedBoolean;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\n\n/**\n * When content caching is enabled, recently-accessed files are stored on the load balancer for easy retrieval by web \n * clients. Content caching improves the performance of high traffic web sites by temporarily storing data that was \n * recently accessed. While it's cached, requests for that data will be served by the load balancer, which in turn \n * reduces load off the back end nodes. The result is improved response times for those requests and less load on the \n * web server.\n * <p/>\n */\n@RequestFilters(AuthenticateRequest.class)\npublic interface ContentCachingApi {\n   /**\n    * Determine if the load balancer is content caching.\n    */\n   @Named(\"contentcaching:state\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @ResponseParser(ParseNestedBoolean.class)\n   @Fallback(FalseOnNotFoundOr404.class)\n   @Path(\"/contentcaching\")\n   boolean isContentCaching();\n   \n   /**\n    * Enable content caching.\n    */\n   @Named(\"contentcaching:state\")\n   @PUT\n   @Produces(MediaType.APPLICATION_JSON)\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(VoidOnNotFoundOr404.class)\n   @Payload(\"{\\\"contentCaching\\\":{\\\"enabled\\\":true}}\")\n   @Path(\"/contentcaching\")\n   void enable();\n   \n   /**\n    * Disable content caching.\n    */\n   @Named(\"contentcaching:state\")\n   @PUT\n   @Produces(MediaType.APPLICATION_JSON)\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(VoidOnNotFoundOr404.class)\n   @Payload(\"{\\\"contentCaching\\\":{\\\"enabled\\\":false}}\")\n   @Path(\"/contentcaching\")\n   void disable();\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/features/ErrorPageApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.functions.ParseNestedString;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\n\n/**\n * An error page is the html file that is shown to an end user who is attempting to access a load balancer node that \n * is offline/unavailable. During provisioning, every load balancer is configured with a default error page that gets \n * displayed when traffic is requested for an offline node. A single custom error page may be added to a load \n * balancer with an HTTP-based protocol. Page updates will override existing content.\n * <p/>\n */\n@RequestFilters(AuthenticateRequest.class)\npublic interface ErrorPageApi {\n   /**\n    * Specify the HTML content for the custom error page. Must be 65536 characters or less.\n    */\n   @Named(\"errorpage:create\")\n   @PUT\n   @Consumes(MediaType.WILDCARD)\n   @Produces(MediaType.APPLICATION_JSON)\n   @Fallback(VoidOnNotFoundOr404.class)\n   @Payload(\"%7B\\\"errorpage\\\":%7B\\\"content\\\":\\\"{content}\\\"%7D%7D\")\n   @Path(\"/errorpage\")\n   void create(@PayloadParam(\"content\") String content);\n   \n   /**\n    * Get the error page HTML content.\n    */\n   @Named(\"errorpage:get\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @ResponseParser(ParseNestedString.class)\n   @Fallback(VoidOnNotFoundOr404.class)\n   @Path(\"/errorpage\")\n   String get();\n   \n   /**\n    * If a custom error page is deleted, or the load balancer is changed to a non-HTTP protocol, the default error \n    * page will be restored.\n    */\n   @Named(\"errorpage:delete\")\n   @DELETE\n   @Consumes(MediaType.WILDCARD)\n   @Fallback(FalseOnNotFoundOr404.class)\n   @Path(\"/errorpage\")\n   boolean delete();\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/features/HealthMonitorApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr422;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.HealthMonitor;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.WrapWith;\n\n/**\n * The load balancing service includes a health monitoring operation which periodically checks your back-end nodes to \n * ensure they are responding correctly. If a node is not responding, it is removed from rotation until the health \n * monitor determines that the node is functional. In addition to being performed periodically, the health check also \n * is performed against every node that is added to ensure that the node is operating properly before allowing it to \n * service traffic. Only one health monitor is allowed to be enabled on a load balancer at a time.\n * </p>\n * As part of your strategy for monitoring connections, you should consider defining secondary nodes that provide \n * failover for effectively routing traffic in case the primary node fails. This is an additional feature that will \n * ensure you remain up in case your primary node fails.\n * <p/>\n */\n@RequestFilters(AuthenticateRequest.class)\npublic interface HealthMonitorApi {\n   /**\n    * Create or update a health monitor.\n    */\n   @Named(\"healthmonitor:create\")\n   @PUT\n   @Consumes(MediaType.APPLICATION_JSON) \n   @Fallback(VoidOnNotFoundOr404.class)\n   @Path(\"/healthmonitor\")\n   void createOrUpdate(@WrapWith(\"healthMonitor\") HealthMonitor healthMonitor);\n\n   /**\n    * Get health monitor.\n    */\n   @Named(\"healthmonitor:get\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @SelectJson(\"healthMonitor\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Path(\"/healthmonitor\")\n   HealthMonitor get();\n   \n   /**\n    * Delete health monitor.\n    * \n    * @return true on a successful delete, false if the health monitor was not found\n    */\n   @Named(\"healthmonitor:delete\")\n   @DELETE\n   @Fallback(FalseOnNotFoundOr422.class)\n   @Path(\"/healthmonitor\")\n   @Consumes(\"*/*\")\n   boolean delete();\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/features/LoadBalancerApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.features;\n\nimport java.util.Map;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyMapOnNotFoundOr404;\nimport org.jclouds.Fallbacks.EmptyPagedIterableOnNotFoundOr404;\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.PagedIterable;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.keystone.v2_0.KeystoneFallbacks.EmptyPaginatedCollectionOnNotFoundOr404;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.binders.BindMetadataToJsonPayload;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.CreateLoadBalancer;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.LoadBalancer;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.Metadata;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.UpdateLoadBalancer;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.functions.ParseLoadBalancer;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.functions.ParseLoadBalancers;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.functions.ParseMetadata;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.Transform;\nimport org.jclouds.rest.annotations.WrapWith;\n\n/**\n * Provides access to CloudLoadBalancers LoadBalancer features.\n * <p/>\n */\n@RequestFilters(AuthenticateRequest.class)\npublic interface LoadBalancerApi {\n   /**\n    * Create a new load balancer with the configuration defined by the request.\n    * \n    * @return The object will contain a unique identifier and status of the request. Using the\n    *         identifier, the caller can check on the progress of the operation by performing a\n    *         {@link LoadBalancerApi#get}.\n    */\n   @Named(\"lb:create\")\n   @POST\n   @ResponseParser(ParseLoadBalancer.class)\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   @Path(\"/loadbalancers\")\n   LoadBalancer create(@WrapWith(\"loadBalancer\") CreateLoadBalancer createLB);\n\n   /**\n    * Update the properties of a load balancer.\n    * \n    * @return The object will contain a unique identifier and status of the request. Using the\n    *         identifier, the caller can check on the progress of the operation by performing a\n    *         {@link LoadBalancerApi#get}.\n    */\n   @Named(\"lb:update\")\n   @PUT\n   @ResponseParser(ParseLoadBalancer.class)\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Path(\"/loadbalancers/{id}\")\n   void update(@PathParam(\"id\") int id, @WrapWith(\"loadBalancer\") UpdateLoadBalancer updateLB);\n\n   /**\n    * List the load balancers.\n    */\n   @Named(\"lb:list\")\n   @GET\n   @ResponseParser(ParseLoadBalancers.class)\n   @Transform(ParseLoadBalancers.ToPagedIterable.class)\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Path(\"/loadbalancers\")\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   PagedIterable<LoadBalancer> list();\n   \n   /**\n    * List the load balancers with full control of pagination.\n    */\n   @Named(\"lb:list\")\n   @GET\n   @ResponseParser(ParseLoadBalancers.class)\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptyPaginatedCollectionOnNotFoundOr404.class)\n   @Path(\"/loadbalancers\")\n   IterableWithMarker<LoadBalancer> list(PaginationOptions options);\n\n   /**\n    * Get a load balancer.\n    */\n   @Named(\"lb:get\")\n   @GET\n   @ResponseParser(ParseLoadBalancer.class)\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   @Path(\"/loadbalancers/{id}\")\n   LoadBalancer get(@PathParam(\"id\") int id);\n\n   /**\n    * Delete a load balancer.\n    */\n   @Named(\"lb:delete\")\n   @DELETE\n   @Fallback(VoidOnNotFoundOr404.class)\n   @Path(\"/loadbalancers/{id}\")\n   @Consumes(\"*/*\")\n   void delete(@PathParam(\"id\") int id);\n   \n   /**\n    * When a metadata item is added, it is assigned a unique identifier that can be used for mutating operations such\n    * as changing the value attribute or removing it. Key and value must be 256 characters or less. \n    * All UTF-8 characters are valid.\n    */\n   @Named(\"lb:createmetadata\")\n   @POST\n   @Consumes(MediaType.APPLICATION_JSON)\n   @ResponseParser(ParseMetadata.class)\n   @Fallback(EmptyMapOnNotFoundOr404.class)\n   @Path(\"/loadbalancers/{id}/metadata\")\n   Metadata createMetadata(@PathParam(\"id\") int id, \n                           @BinderParam(BindMetadataToJsonPayload.class) Map<String, String> metadata);\n    \n   /**\n    * List a load balancer's metadata.\n    */\n   @Named(\"lb:getmetadata\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @ResponseParser(ParseMetadata.class)\n   @Fallback(EmptyMapOnNotFoundOr404.class)\n   @Path(\"/loadbalancers/{id}/metadata\")\n   Metadata getMetadata(@PathParam(\"id\") int id);\n   \n   /**\n    * Update metadatum. Key and value must be 256 characters or less. All UTF-8 characters are valid.\n    * \n    * @return true on a successful update, false if the metadatum was not found\n    */\n   @Named(\"lb:updatemetadatum\")\n   @PUT\n   @Produces(MediaType.APPLICATION_JSON)\n   @Consumes(\"*/*\")\n   @Fallback(FalseOnNotFoundOr404.class)\n   @Payload(\"%7B\\\"meta\\\":%7B\\\"value\\\":\\\"{value}\\\"%7D%7D\")\n   @Path(\"/loadbalancers/{id}/metadata/{metadatumId}\")\n   boolean updateMetadatum(@PathParam(\"id\") int id, \n                           @PathParam(\"metadatumId\") int metadatumId, \n                           @PayloadParam(\"value\") String value);\n\n   /**\n    * Delete metadatum.\n    * \n    * @see LoadBalancerApi#deleteMetadata(int, Iterable)\n    * \n    * @return true on a successful removal, false if the metadatum was not found\n    */\n   @Named(\"lb:deletemetadatum\")\n   @DELETE\n   @Fallback(FalseOnNotFoundOr404.class)\n   @Consumes(\"*/*\")\n   @Path(\"/loadbalancers/{id}/metadata/{metadatumId}\")\n   boolean deleteMetadatum(@PathParam(\"id\") int id, @PathParam(\"metadatumId\") int metadatumId);\n\n   \n   /**\n    * Batch delete metadata given the specified ids.\n    * \n    * The current default limit is ten ids per request. Any and all configuration data is immediately purged and is \n    * not recoverable. If one or more of the items in the list cannot be removed due to its current status, an \n    * exception is thrown along with the ids of the ones the system identified as potential failures for this request.\n    * \n    * @return true on a successful removal, false if the metadata was not found\n    */\n   @Named(\"lb:deletemetadata\")\n   @DELETE\n   @Fallback(FalseOnNotFoundOr404.class)\n   @Consumes(\"*/*\")\n   @Path(\"/loadbalancers/{id}/metadata\")\n   boolean deleteMetadata(@PathParam(\"id\") int id, \n                          @QueryParam(\"id\") Iterable<Integer> metadataIds);\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/features/NodeApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.features;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyMapOnNotFoundOr404;\nimport org.jclouds.Fallbacks.EmptyPagedIterableOnNotFoundOr404;\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.PagedIterable;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.keystone.v2_0.KeystoneFallbacks.EmptyPaginatedCollectionOnNotFoundOr404;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.binders.BindMetadataToJsonPayload;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.AddNode;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.Metadata;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.Node;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.UpdateNode;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.functions.ParseMetadata;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.functions.ParseNode;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.functions.ParseNodes;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.Transform;\nimport org.jclouds.rest.annotations.WrapWith;\n\n/**\n * Provides access to CloudLoadBalancers Node features.\n * <p/>\n */\n@RequestFilters(AuthenticateRequest.class)\npublic interface NodeApi {\n   /**\n    * Add a new node with the configuration defined by the request.\n    */\n   @Named(\"node:add\")\n   @POST\n   @SelectJson(\"nodes\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   @Path(\"/nodes\")\n   Set<Node> add(@WrapWith(\"nodes\") Iterable<AddNode> addNodes);\n\n   /**\n    * Update the attributes of a node.\n    */\n   @Named(\"node:update\")\n   @PUT\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Path(\"/nodes/{id}\")\n   void update(@PathParam(\"id\") int id, @WrapWith(\"node\") UpdateNode updateNode);\n\n   /**\n    * List the nodes.\n    */\n   @Named(\"node:list\")\n   @GET\n   @ResponseParser(ParseNodes.class)\n   @Transform(ParseNodes.ToPagedIterable.class)\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Path(\"/nodes\")\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   PagedIterable<Node> list();\n\n   /**\n    * List the nodes with full control of pagination.\n    */\n   @Named(\"node:list\")\n   @GET\n   @ResponseParser(ParseNodes.class)\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptyPaginatedCollectionOnNotFoundOr404.class)\n   @Path(\"/nodes\")\n   IterableWithMarker<Node> list(PaginationOptions options);\n\n   /**\n    * Get a node.\n    */\n   @Named(\"node:get\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @ResponseParser(ParseNode.class)\n   @Path(\"/nodes/{id}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   Node get(@PathParam(\"id\") int id);\n\n   /**\n    * Remove a node from the load balancer.\n    */\n   @Named(\"node:remove\")\n   @DELETE\n   @Path(\"/nodes/{id}\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   @Consumes(\"*/*\")\n   void remove(@PathParam(\"id\") int id);\n   \n   /**\n    * Batch remove nodes from the load balancer.\n    */\n   @Named(\"node:remove\")\n   @DELETE\n   @Path(\"/nodes\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   @Consumes(\"*/*\")\n   void remove(@QueryParam(\"id\") Iterable<Integer> ids);\n   \n   /**\n    * When a metadata item is added, it is assigned a unique identifier that can be used for mutating operations such\n    * as changing the value attribute or removing it. Key and value must be 256 characters or less. \n    * All UTF-8 characters are valid.\n    */\n   @Named(\"node:createmetadata\")\n   @POST\n   @Consumes(MediaType.APPLICATION_JSON)\n   @ResponseParser(ParseMetadata.class)\n   @Fallback(EmptyMapOnNotFoundOr404.class)\n   @Path(\"/nodes/{id}/metadata\")\n   Metadata createMetadata(@PathParam(\"id\") int id, \n                           @BinderParam(BindMetadataToJsonPayload.class) Map<String, String> metadata);\n    \n   /**\n    * List a load balancer's metadata.\n    */\n   @Named(\"node:getmetadata\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @ResponseParser(ParseMetadata.class)\n   @Fallback(EmptyMapOnNotFoundOr404.class)\n   @Path(\"/nodes/{id}/metadata\")\n   Metadata getMetadata(@PathParam(\"id\") int lb);\n\n   /**\n    * Update metadatum. Key and value must be 256 characters or less. All UTF-8 characters are valid.\n    * \n    * @return true on a successful update, false if the metadatum was not found\n    */\n   @Named(\"node:updatemetadatum\")\n   @PUT\n   @Produces(MediaType.APPLICATION_JSON)\n   @Consumes(\"*/*\")\n   @Fallback(FalseOnNotFoundOr404.class)\n   @Payload(\"%7B\\\"meta\\\":%7B\\\"value\\\":\\\"{value}\\\"%7D%7D\")\n   @Path(\"/nodes/{id}/metadata/{metadatumId}\")\n   boolean updateMetadatum(@PathParam(\"id\") int id, \n                           @PathParam(\"metadatumId\") int metadatumId, \n                           @PayloadParam(\"value\") String value);\n\n   /**\n    * Delete metadatum.\n    * \n    * @see NodeApi#deleteMetadata(int, Iterable)\n    * \n    * @return true on a successful removal, false if the metadatum was not found\n    */\n   @Named(\"node:deletemetadatum\")\n   @DELETE\n   @Fallback(FalseOnNotFoundOr404.class)\n   @Consumes(\"*/*\")\n   @Path(\"/nodes/{id}/metadata/{metadatumId}\")\n   boolean deleteMetadatum(@PathParam(\"id\") int id, @PathParam(\"metadatumId\") int metadatumId);\n   \n   /**\n    * Batch delete metadata given the specified ids.\n    * \n    * The current default limit is ten ids per request. Any and all configuration data is immediately purged and is \n    * not recoverable. If one or more of the items in the list cannot be removed due to its current status, an \n    * exception is thrown along with the ids of the ones the system identified as potential failures for this request.\n    * \n    * @return true on a successful removal, false if the metadata was not found\n    */\n   @Named(\"node:deletemetadata\")\n   @DELETE\n   @Fallback(FalseOnNotFoundOr404.class)\n   @Consumes(\"*/*\")\n   @Path(\"/nodes/{id}/metadata\")\n   boolean deleteMetadata(@PathParam(\"id\") int id, \n                          @QueryParam(\"id\") Iterable<Integer> metadataIds);\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/features/ReportApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.features;\n\nimport java.util.Date;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.PagedIterable;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.openstack.keystone.v2_0.KeystoneFallbacks.EmptyPaginatedCollectionOnNotFoundOr404;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.HistoricalUsage;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.LoadBalancer;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.LoadBalancerStats;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.LoadBalancerUsage;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.Protocol;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.functions.DateParser;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.functions.ParseAlgorithms;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.functions.ParseLoadBalancerUsages;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.functions.ParseLoadBalancers;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.ParamParser;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.Transform;\n\n/**\n * Reporting for load balancers.\n * <p/>\n */\n@RequestFilters(AuthenticateRequest.class)\npublic interface ReportApi {\n   /**\n    * List billable load balancers for the given date range.\n    */\n   @Named(\"report:list\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @ResponseParser(ParseLoadBalancers.class)\n   @Transform(ParseLoadBalancers.ToPagedIterable.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   @Path(\"/loadbalancers/billable\")\n   PagedIterable<LoadBalancer> listBillableLoadBalancers(\n         @ParamParser(DateParser.class) @QueryParam(\"startTime\") Date startTime, \n         @ParamParser(DateParser.class) @QueryParam(\"endTime\") Date endTime);\n   \n   @Named(\"report:list\")\n   @GET\n   @ResponseParser(ParseLoadBalancers.class)\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptyPaginatedCollectionOnNotFoundOr404.class)\n   @Path(\"/loadbalancers/billable\")\n   IterableWithMarker<LoadBalancer> listBillableLoadBalancers(PaginationOptions options);\n\n   /**\n    * View all transfer activity, average number of connections, and number of virtual IPs associated with the load\n    * balancing service. Historical usage data is available for up to 90 days of service activity.\n    */\n   @Named(\"report:list\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   @Path(\"/loadbalancers/usage\")\n   HistoricalUsage getHistoricalUsage(\n         @ParamParser(DateParser.class) @QueryParam(\"startTime\") Date startTime, \n         @ParamParser(DateParser.class) @QueryParam(\"endTime\") Date endTime);\n   \n   /**\n    * Historical usage data is available for up to 90 days of service activity.\n    */\n   @Named(\"report:list\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @ResponseParser(ParseLoadBalancerUsages.class)\n   @Transform(ParseLoadBalancerUsages.ToPagedIterable.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   @Path(\"/loadbalancers/{id}/usage\")\n   PagedIterable<LoadBalancerUsage> listLoadBalancerUsage(@PathParam(\"id\") int loadBalancerId,\n         @ParamParser(DateParser.class) @QueryParam(\"startTime\") Date startTime, \n         @ParamParser(DateParser.class) @QueryParam(\"endTime\") Date endTime);\n\n   @Named(\"report:list\")\n   @GET\n   @ResponseParser(ParseLoadBalancerUsages.class)\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptyPaginatedCollectionOnNotFoundOr404.class)\n   @Path(\"/loadbalancers/{id}/usage\")\n   IterableWithMarker<LoadBalancerUsage> listLoadBalancerUsage(PaginationOptions options);\n   \n   /**\n    * Current usage represents all usage recorded within the preceding 24 hours.\n    */\n   @Named(\"report:list\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @ResponseParser(ParseLoadBalancerUsages.class)\n   @Transform(ParseLoadBalancerUsages.ToPagedIterable.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   @Path(\"/loadbalancers/{id}/usage/current\")\n   PagedIterable<LoadBalancerUsage> listCurrentLoadBalancerUsage(@PathParam(\"id\") int loadBalancerId);\n\n   @Named(\"report:list\")\n   @GET\n   @ResponseParser(ParseLoadBalancerUsages.class)\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptyPaginatedCollectionOnNotFoundOr404.class)\n   @Path(\"/loadbalancers/{id}/usage/current\")\n   IterableWithMarker<LoadBalancerUsage> listCurrentLoadBalancerUsage(PaginationOptions options);\n   \n   /**\n    * Current usage represents all usage recorded within the preceding 24 hours.\n    */\n   @Named(\"report:list\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   @Path(\"/loadbalancers/{id}/stats\")\n   LoadBalancerStats getLoadBalancerStats(@PathParam(\"id\") int loadBalancerId);\n   \n   /**\n    * All load balancers must define the protocol of the service which is being load balanced. The protocol selection \n    * should be based on the protocol of the back-end nodes. When configuring a load balancer, the default port for \n    * the given protocol will be selected from this list unless otherwise specified.\n    */\n   @Named(\"report:list\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @SelectJson(\"protocols\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Path(\"/loadbalancers/protocols\")\n   Iterable<Protocol> listProtocols();\n   \n   /**\n    * Get all of the possible algorthims usable by load balancers.\n    */\n   @Named(\"report:list\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @ResponseParser(ParseAlgorithms.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   @Path(\"/loadbalancers/algorithms\")\n   Iterable<String> listAlgorithms();\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/features/SSLTerminationApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr422;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.SSLTermination;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.WrapWith;\n\n/**\n * The SSL Termination feature allows a load balancer user to terminate SSL traffic at the load balancer layer versus \n * at the web server layer. A user may choose to configure SSL Termination using a key and an SSL certificate or an \n * (Intermediate) SSL certificate.\n * <p/> \n * When SSL Termination is configured on a load balancer, a secure shadow server is created that listens only for \n * secure traffic on a user-specified port. This shadow server is only visible to and manageable by the system. \n * Existing or updated attributes on a load balancer with SSL Termination will also apply to its shadow server. \n * For example, if Connection Logging is enabled on an SSL load balancer, it will also be enabled on the shadow server \n * and Cloud Files logs will contain log files for both.\n * <p/>\n * Notes\n * <ol>\n * <li>SSL Termination may only be configured on load balancers with non-secure protocols. For example, SSL Termination \n * can be applied to an HTTP load balancer, but not to an HTTPS load balancer.</li>\n * <li>SSL-terminated load balancers decrypt the traffic at the traffic manager and pass unencrypted traffic to the \n * back-end node. Because of this, the customer's back-end nodes don't know what protocol the client requested. \n * Therefore the X-Forwarded-Proto (XFP) header has been added for identifying the originating protocol of an HTTP \n * request as \"http\" or \"https\" depending on what protocol the client requested.</li>\n * <li>Not every service will return certificates in the proper order. Please verify that your chain of certificates \n * matches that of walking up the chain from the domain to the CA root.</li>\n * </ol>\n * \n * Warning\n * <ol>\n * <li>If SSL is enabled on a load balancer that is configured with nodes that are NOT in the same datacenter, then \n * decrypted traffic will be sent in clear text over the public internet to the external node(s) and will no longer \n * be secure.</li>\n * </ol>\n */\n@RequestFilters(AuthenticateRequest.class)\npublic interface SSLTerminationApi {\n   /**\n    * Create or update SSL termination.\n    * </p>\n    * The following attributes may be updated without overwriting a load balancer's existing SSL certificate and key \n    * specifications:\n    * <ul>\n    * <li>enabled</li>\n    * <li>secureTrafficOnly</li>\n    * <li>securePort</li>\n    * </ul>\n    * These configurable attributes must be provided (individually or grouped) in a request without specifying any \n    * certificate/key combination if a user does not want the system to overwrite the existing SSL certificate/key \n    * configuration.\n    * </p>\n    * If a user wants to replace the existing SSL configuration, a new certificate, privatekey, and securePort \n    * combination must be provided instead of, or in addition to, the optional/editable attributes.\n    */\n   @Named(\"ssltermination:create\")\n   @PUT\n   @Consumes(MediaType.APPLICATION_JSON) \n   @Fallback(VoidOnNotFoundOr404.class)\n   @Path(\"/ssltermination\")\n   void createOrUpdate(@WrapWith(\"sslTermination\") SSLTermination sslTermination);\n\n   /**\n    * Get SSL termination info.\n    */\n   @Named(\"ssltermination:get\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @SelectJson(\"sslTermination\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Path(\"/ssltermination\")\n   SSLTermination get();\n   \n   /**\n    * Delete SSL termination.\n    * \n    * @return true on a successful delete, false if the SSL termination was not found\n    */\n   @Named(\"ssltermination:delete\")\n   @DELETE\n   @Fallback(FalseOnNotFoundOr422.class)\n   @Path(\"/ssltermination\")\n   @Consumes(\"*/*\")\n   boolean delete();\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/features/SessionPersistenceApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.SessionPersistence;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.functions.ParseSessionPersistence;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\n\n\n/**\n * Session persistence is a feature of the load balancing service that forces multiple requests from clients to be \n * directed to the same node. This is common with many web applications that do not inherently share application \n * state between back-end servers. Two session persistence modes are available, HTTP Cookie and Source IP.\n */\n@RequestFilters(AuthenticateRequest.class)\npublic interface SessionPersistenceApi {\n   /**\n    * Get the current session persistence.\n    * \n    * @see SessionPersistence\n    */\n   @Named(\"sessionpersistence:get\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @ResponseParser(ParseSessionPersistence.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   @Path(\"/sessionpersistence\")\n   SessionPersistence get();\n   \n   /**\n    * Create session persistence.\n    * \n    * @see SessionPersistence\n    */\n   @Named(\"sessionpersistence:create\")\n   @PUT\n   @Produces(MediaType.APPLICATION_JSON)\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(VoidOnNotFoundOr404.class)\n   @Payload(\"%7B\\\"sessionPersistence\\\":%7B\\\"persistenceType\\\":\\\"{sessionPersistence}\\\"%7D%7D\")\n   @Path(\"/sessionpersistence\")\n   void create(@PayloadParam(\"sessionPersistence\") SessionPersistence sessionPersistence);\n   \n   /**\n    * Delete session persistence.\n    * \n    * @see SessionPersistence\n    */\n   @Named(\"sessionpersistence:delete\")\n   @DELETE\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(VoidOnNotFoundOr404.class)\n   @Path(\"/sessionpersistence\")\n   void delete();\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/features/VirtualIPApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyPagedIterableOnNotFoundOr404;\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.openstack.keystone.auth.filters.AuthenticateRequest;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.VirtualIP;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.VirtualIPWithId;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\n/**\n * A virtual IP makes a load balancer accessible by clients. The load balancing service supports either a public VIP,\n * routable on the public Internet, or a ServiceNet address, routable only within the region in which the load balancer \n * resides.\n * <p/>\n */\n@RequestFilters(AuthenticateRequest.class)\npublic interface VirtualIPApi {\n   /**\n    * Create a new virtual IP.\n    */\n   @Named(\"virtualip:create\")\n   @POST\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   @Path(\"/virtualips\")\n   VirtualIPWithId create(@BinderParam(BindToJsonPayload.class) VirtualIP virtualIP);\n\n   /**\n    * List the virtual IPs.\n    */\n   @Named(\"virtualip:list\")\n   @GET\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   @SelectJson(\"virtualIps\")\n   @Path(\"/virtualips\")\n   Iterable<VirtualIPWithId> list();\n   \n   /**\n    * Delete a virtual IP.\n    * \n    * @see VirtualIPApi#delete(Iterable)\n    * \n    * @return true on a successful delete, false if the virtual IP was not found\n    */\n   @Named(\"virtualip:delete\")\n   @DELETE\n   @Fallback(FalseOnNotFoundOr404.class)\n   @Path(\"/virtualips/{id}\")\n   @Consumes(\"*/*\")\n   boolean delete(@PathParam(\"id\") int id);\n   \n   /**\n    * Batch delete virtual IPs given the specified ids.\n    * \n    * All load balancers must have at least one virtual IP associated with them at all times. Attempting to delete the\n    * last virtual IP will result in an exception. The current default limit is ten ids per request. Any \n    * and all configuration data is immediately purged and is not recoverable. If one or more of the items in the list \n    * cannot be removed due to its current status, an exception is thrown along with the ids of the ones the \n    * system identified as potential failures for this request.\n    * \n    * @return true on a successful delete, false if the virtual IP was not found\n    */\n   @Named(\"virtualip:delete\")\n   @DELETE\n   @Fallback(FalseOnNotFoundOr404.class)\n   @Path(\"/virtualips\")\n   @Consumes(\"*/*\")\n   boolean delete(@QueryParam(\"id\") Iterable<Integer> ids);\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/functions/ConvertLB.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.functions;\n\nimport java.net.URI;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\n\nimport org.jclouds.logging.Logger;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.AccessRuleWithId;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.LoadBalancer;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.LoadBalancer.Builder;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.Metadata;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.VirtualIPWithId;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.inject.assistedinject.Assisted;\n\npublic class ConvertLB implements Function<LB, LoadBalancer> {\n   private static final String LOAD_BALANCERS = \"loadbalancers\";\n\n   public interface Factory {\n      ConvertLB createForEndpointAndRegion(URI endpoint, String region);\n   }\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   private final String region;\n   private final URI endpoint;\n\n   @Inject\n   ConvertLB(@Assisted URI endpoint, @Assisted String region) {\n      this.endpoint = endpoint;\n      this.region = region.toUpperCase();\n   }\n\n   @Override\n   public LoadBalancer apply(LB lb) {\n      try {\n         Builder builder = LoadBalancer.builder().id(lb.id).region(region).status(lb.status).name(lb.getName())\n               .protocol(lb.getProtocol()).port(lb.getPort()).nodeCount(lb.nodeCount).nodes(lb.getNodes())\n               .timeout(lb.getTimeout()).algorithm(lb.getAlgorithm()).halfClosed(lb.isHalfClosed())\n               .sessionPersistenceType(lb.getSessionPersistenceType()).connectionLogging(lb.isConnectionLogging())\n               .connectionThrottle(lb.getConnectionThrottle()).healthMonitor(lb.getHealthMonitor());\n\n         if (lb.cluster.size() == 1)\n            builder.clusterName(Iterables.get(lb.cluster.values(), 0));\n         if (lb.created.size() == 1)\n            builder.created(Iterables.get(lb.created.values(), 0));\n         if (lb.updated.size() == 1)\n            builder.updated(Iterables.get(lb.updated.values(), 0));\n         if (lb.contentCaching.size() == 1)\n            builder.contentCaching(Iterables.get(lb.contentCaching.values(), 0));\n         if (lb.sslTermination != null)\n            builder.sslTermination(lb.sslTermination);\n         if (lb.sourceAddresses != null)\n            builder.sourceAddresses(lb.sourceAddresses);\n         if (lb.accessList == null)\n            builder.accessRules(ImmutableSet.<AccessRuleWithId> of());\n         else\n            builder.accessRules(lb.accessList);\n         if (lb.virtualIps == null)\n            builder.virtualIPs(ImmutableSet.<VirtualIPWithId> of());\n         else\n            builder.virtualIPs(lb.virtualIps);\n         if (lb.metadata == null)\n            builder.metadata(new Metadata());\n         else\n            builder.metadata(ParseMetadata.transformCLBMetadataToMetadata(lb.metadata));\n         \n         int indexOfLB = endpoint.toString().lastIndexOf(LOAD_BALANCERS); \n         String path = endpoint.toString().substring(0, indexOfLB + LOAD_BALANCERS.length()); \n         builder.uri(URI.create(path + \"/\" + lb.id));\n\n         return builder.build();\n      }\n      catch (NullPointerException e) {\n         logger.warn(e, \"nullpointer found parsing %s\", lb);\n         throw e;\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/functions/DateParser.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.functions;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\n\nimport jakarta.inject.Singleton;\n\nimport com.google.common.base.Function;\n\n/**\n * Takes a Date and return a yyyy-MM-dd String.\n */\n@Singleton\npublic class DateParser implements Function<Object, String> {\n   @Override\n   public String apply(Object input) {\n      checkArgument(checkNotNull(input, \"input\") instanceof Date, \"This function is only valid for Dates!\");\n      Date date = Date.class.cast(input);\n      \n      SimpleDateFormat format = new SimpleDateFormat(\"yyyy-MM-dd\");\n\n      return format.format(date);\n   }\n\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/functions/LB.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.functions;\n\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.AccessRuleWithId;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.Node;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.SSLTermination;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.SourceAddresses;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.VirtualIPWithId;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.LoadBalancer.Status;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.internal.BaseLoadBalancer;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.functions.ParseMetadata.CLBMetadata;\n\nimport com.google.common.base.Objects;\nimport com.google.common.collect.Maps;\nimport com.google.common.collect.Sets;\n\n/**\n * Only here as the datatype for cloudloadbalancers is awkward.\n */\nclass LB extends BaseLoadBalancer<Node, LB> {\n   int id;\n   int nodeCount;\n   Status status;\n   Set<VirtualIPWithId> virtualIps = Sets.newLinkedHashSet();\n   Map<String, String> cluster = Maps.newLinkedHashMap();\n   Map<String, Date> created = Maps.newLinkedHashMap();\n   Map<String, Date> updated = Maps.newLinkedHashMap();\n   Map<String, Boolean> contentCaching = Maps.newLinkedHashMap();\n   SSLTermination sslTermination;\n   SourceAddresses sourceAddresses;\n   Set<AccessRuleWithId> accessList;\n   List<CLBMetadata> metadata;\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      \n      LB that = LB.class.cast(obj);      \n      return Objects.equal(this.id, that.id);\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/functions/ParseAlgorithms.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.rest.InvocationContext;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Lists;\n\npublic class ParseAlgorithms implements Function<HttpResponse, List<String>>, InvocationContext<ParseAlgorithms> {\n\n   private final ParseJson<Map<String, List<Map<String, String>>>> json;\n\n   @Inject\n   ParseAlgorithms(ParseJson<Map<String, List<Map<String, String>>>> json) {\n      this.json = checkNotNull(json, \"json\");\n   }\n\n   @Override\n   public List<String> apply(HttpResponse response) {\n      Map<String, List<Map<String, String>>> map = json.apply(response);\n\n      if (map == null || map.isEmpty())\n         throw new HttpResponseException(\"Unexpected JSON format returned.\", null, response);\n\n      List<Map<String, String>> list = Iterables.get(map.values(), 0);\n      List<String> algorithms = Lists.newArrayList();\n\n      for (Map<String, String> nameAlgorithmPair : list) {\n         algorithms.add(Iterables.get(nameAlgorithmPair.values(), 0));\n      }\n\n      return algorithms;\n   }\n\n   @Override\n   public ParseAlgorithms setContext(HttpRequest request) {\n      return this;\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/functions/ParseLoadBalancer.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\n\nimport java.net.URI;\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.LoadBalancer;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.functions.ConvertLB.Factory;\nimport org.jclouds.rest.InvocationContext;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.Iterables;\n\npublic class ParseLoadBalancer implements Function<HttpResponse, LoadBalancer>, InvocationContext<ParseLoadBalancer> {\n\n   private final ParseJson<Map<String, LB>> json;\n   private final Factory factory;\n\n   private ConvertLB convertLB;\n\n   @Inject\n   ParseLoadBalancer(ParseJson<Map<String, LB>> json, ConvertLB.Factory factory) {\n      this.json = checkNotNull(json, \"json\");\n      this.factory = checkNotNull(factory, \"factory\");\n   }\n\n   @Override\n   public LoadBalancer apply(HttpResponse arg0) {\n      checkState(convertLB != null, \"convertLB should be set by InvocationContext\");\n      Map<String, LB> map = json.apply(arg0);\n      if (map == null || map.isEmpty())\n         return null;\n      LB lb = Iterables.get(map.values(), 0);\n      return convertLB.apply(lb);\n   }\n\n   @Override\n   public ParseLoadBalancer setContext(HttpRequest request) {\n      return setEndpointAndRegion(request.getEndpoint());\n   }\n\n   ParseLoadBalancer setEndpointAndRegion(URI endpoint) {\n      String region = endpoint.getHost().substring(0, endpoint.getHost().indexOf('.'));\n\n      this.convertLB = factory.createForEndpointAndRegion(endpoint, region);\n\n      return this;\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/functions/ParseLoadBalancerUsages.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.internal.Arg0ToPagedIterable;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\nimport org.jclouds.openstack.v2_0.domain.PaginatedCollection;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.CloudLoadBalancersApi;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.LoadBalancerUsage;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.features.ReportApi;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.functions.ParseLoadBalancerUsages.LoadBalancerUsages;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.inject.TypeLiteral;\n\n/**\n * boiler plate until we determine a better way\n */\n@Singleton\npublic class ParseLoadBalancerUsages extends ParseJson<LoadBalancerUsages> {\n\n   @Inject\n   public ParseLoadBalancerUsages(Json json) {\n      super(json, TypeLiteral.get(LoadBalancerUsages.class));\n   }\n\n   static class LoadBalancerUsages extends PaginatedCollection<LoadBalancerUsage> {\n\n      @ConstructorProperties({ \"loadBalancerUsageRecords\", \"links\" })\n      protected LoadBalancerUsages(Iterable<LoadBalancerUsage> loadBalancerUsageRecords, Iterable<Link> links) {\n         super(loadBalancerUsageRecords, links);\n      }\n   }\n\n   public static class ToPagedIterable extends Arg0ToPagedIterable.FromCaller<LoadBalancerUsage, ToPagedIterable> {\n\n      private final CloudLoadBalancersApi api;\n\n      @Inject\n      protected ToPagedIterable(CloudLoadBalancersApi api) {\n         this.api = checkNotNull(api, \"api\");\n      }\n\n      @Override\n      protected Function<Object, IterableWithMarker<LoadBalancerUsage>> markerToNextForArg0(Optional<Object> arg0) {\n         String region = arg0.get().toString();\n         final ReportApi reportApi = api.getReportApi(region);\n\n         return new Function<Object, IterableWithMarker<LoadBalancerUsage>>() {\n\n            @Override\n            public IterableWithMarker<LoadBalancerUsage> apply(Object input) {\n               PaginationOptions paginationOptions = PaginationOptions.class.cast(input);\n               IterableWithMarker<LoadBalancerUsage> list = reportApi.listLoadBalancerUsage(paginationOptions);\n               return list;\n            }\n\n            @Override\n            public String toString() {\n               return \"listLoadBalancerUsage()\";\n            }\n         };\n      }\n\n   }\n\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/functions/ParseLoadBalancers.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.net.URI;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.IterableWithMarkers;\nimport org.jclouds.collect.internal.Arg0ToPagedIterable;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.openstack.v2_0.domain.PaginatedCollection;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.CloudLoadBalancersApi;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.LoadBalancer;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.features.LoadBalancerApi;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.functions.ConvertLB.Factory;\nimport org.jclouds.rest.InvocationContext;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.Iterables;\n\npublic class ParseLoadBalancers implements Function<HttpResponse, IterableWithMarker<LoadBalancer>>,\n         InvocationContext<ParseLoadBalancers> {\n\n   private final ParseJson<LoadBalancers> json;\n   private final Factory factory;\n\n   private ConvertLB convertLB;\n\n   @Inject\n   ParseLoadBalancers(ParseJson<LoadBalancers> json, ConvertLB.Factory factory) {\n      this.json = checkNotNull(json, \"json\");\n      this.factory = checkNotNull(factory, \"factory\");\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public IterableWithMarker<LoadBalancer> apply(HttpResponse arg0) {\n      LoadBalancers lbs = json.apply(arg0);\n\n      if (lbs.isEmpty())\n         return IterableWithMarkers.EMPTY;\n\n      Iterable<LoadBalancer> transform = Iterables.transform(lbs, convertLB);\n      IterableWithMarker<LoadBalancer> iterableWithMarker = IterableWithMarkers.from(transform);\n\n      return iterableWithMarker;\n   }\n\n   @Override\n   public ParseLoadBalancers setContext(HttpRequest request) {\n      return setEndpointAndRegion(request.getEndpoint());\n   }\n\n   ParseLoadBalancers setEndpointAndRegion(URI endpoint) {\n      String region = endpoint.getHost().substring(0, endpoint.getHost().indexOf('.'));\n\n      this.convertLB = factory.createForEndpointAndRegion(endpoint, region);\n\n      return this;\n   }\n\n   static class LoadBalancers extends PaginatedCollection<LB> {\n\n      @ConstructorProperties({ \"loadBalancers\", \"loadBalancers_links\" })\n      protected LoadBalancers(Iterable<LB> loadBalancers, Iterable<Link> loadBalancers_links) {\n         super(loadBalancers, loadBalancers_links);\n      }\n\n   }\n\n   public static class ToPagedIterable extends Arg0ToPagedIterable.FromCaller<LoadBalancer, ToPagedIterable> {\n\n      private final CloudLoadBalancersApi api;\n\n      @Inject\n      protected ToPagedIterable(CloudLoadBalancersApi api) {\n         this.api = checkNotNull(api, \"api\");\n      }\n\n      @Override\n      protected Function<Object, IterableWithMarker<LoadBalancer>> markerToNextForArg0(Optional<Object> arg0) {\n         String region = arg0.get().toString();\n         final LoadBalancerApi loadBalancerApi = api.getLoadBalancerApi(region);\n\n         return new Function<Object, IterableWithMarker<LoadBalancer>>() {\n\n            @Override\n            public IterableWithMarker<LoadBalancer> apply(Object input) {\n               PaginationOptions paginationOptions = PaginationOptions.class.cast(input);\n               return loadBalancerApi.list(paginationOptions);\n            }\n\n            @Override\n            public String toString() {\n               return \"list()\";\n            }\n         };\n      }\n\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/functions/ParseMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.functions;\n\nimport static org.jclouds.http.HttpUtils.releasePayload;\n\nimport java.io.IOException;\nimport java.lang.reflect.Type;\nimport java.util.List;\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.Metadata;\n\nimport com.google.inject.TypeLiteral;\n\npublic class ParseMetadata extends ParseJson<Metadata> {\n\n   @Inject\n   public ParseMetadata(Json json, TypeLiteral<Metadata> type) {\n      super(json, type);\n   }\n\n   @Override\n   public Metadata apply(HttpResponse response) {\n      Map<String, List<CLBMetadata>> clbMetadata;\n      \n      try {\n         Type clbMetadataType = new TypeLiteral<Map<String, List<CLBMetadata>>>() {}.getType();\n         clbMetadata = apply(response.getPayload().getInput(), clbMetadataType);\n      }\n      catch (IOException e) {\n         StringBuilder message = new StringBuilder();\n         message.append(\"Error parsing response\");\n         logger.error(e, message.toString());\n         throw new HttpResponseException(message.toString() + \"\\n\" + response, null, response, e);\n      } \n      finally {\n         releasePayload(response);\n      }\n      \n      return transformCLBMetadataToMetadata(clbMetadata.get(\"metadata\"));\n   }\n   \n   public static Metadata transformCLBMetadataToMetadata(List<CLBMetadata> clbMetadatum) {\n      Metadata metadata = new Metadata();      \n      \n      for (CLBMetadata clbMetadata : clbMetadatum) {\n         metadata.put(clbMetadata.key, clbMetadata.value);\n         metadata.putId(clbMetadata.key, clbMetadata.id);\n      }\n      \n      return metadata;\n   }\n   \n   /**\n    * This class is here only to deal with the metadata format in CLB.\n    */\n   public static class CLBMetadata {\n      private int id;\n      private String key;\n      private String value;\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/functions/ParseNestedBoolean.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.rest.InvocationContext;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.Iterables;\n\npublic class ParseNestedBoolean implements Function<HttpResponse, Boolean>, InvocationContext<ParseNestedBoolean> {\n\n   private final ParseJson<Map<String, Map<String, Boolean>>> json;\n\n   @Inject\n   ParseNestedBoolean(ParseJson<Map<String, Map<String, Boolean>>> json) {\n      this.json = checkNotNull(json, \"json\");\n   }\n\n   @Override\n   public Boolean apply(HttpResponse response) {\n      Map<String, Map<String, Boolean>> map = json.apply(response);\n\n      if (map == null || map.isEmpty())\n         throw new HttpResponseException(\"Unexpected JSON format returned.\", null, response);\n\n      return Iterables.get(Iterables.get(map.values(), 0).values(), 0);\n   }\n\n   @Override\n   public ParseNestedBoolean setContext(HttpRequest request) {\n      return this;\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/functions/ParseNestedString.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.rest.InvocationContext;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.Iterables;\n\npublic class ParseNestedString implements Function<HttpResponse, String>, InvocationContext<ParseNestedString> {\n\n   private final ParseJson<Map<String, Map<String, String>>> json;\n\n   @Inject\n   ParseNestedString(ParseJson<Map<String, Map<String, String>>> json) {\n      this.json = checkNotNull(json, \"json\");\n   }\n\n   @Override\n   public String apply(HttpResponse response) {\n      Map<String, Map<String, String>> map = json.apply(response);\n      \n      if (map == null || map.isEmpty())\n         throw new HttpResponseException(\"Unexpected JSON format returned.\", null, response);\n      \n      return Iterables.get(Iterables.get(map.values(), 0).values(), 0);\n   }\n\n   @Override\n   public ParseNestedString setContext(HttpRequest request) {\n      return this;\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/functions/ParseNode.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.Node;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.Node.Status;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.internal.BaseNode;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.functions.ParseMetadata.CLBMetadata;\nimport org.jclouds.rest.InvocationContext;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.Iterables;\n\npublic class ParseNode implements Function<HttpResponse, Node>, InvocationContext<ParseNode> {\n\n   private final ParseJson<Map<String, NodeWithCLBMetadata>> json;\n\n   @Inject\n   ParseNode(ParseJson<Map<String, NodeWithCLBMetadata>> json) {\n      this.json = checkNotNull(json, \"json\");\n   }\n\n   @Override\n   public Node apply(HttpResponse response) {\n      Map<String, NodeWithCLBMetadata> map = json.apply(response);\n\n      if (map == null || map.isEmpty())\n         return null;\n\n      NodeWithCLBMetadata nodeWithCLBMetadata = Iterables.get(map.values(), 0);\n      Node node = Node.builder()\n            .address(nodeWithCLBMetadata.getAddress())\n            .port(nodeWithCLBMetadata.getPort())\n            .condition(nodeWithCLBMetadata.getCondition())\n            .type(nodeWithCLBMetadata.getType())\n            .weight(nodeWithCLBMetadata.getWeight())\n            .id(nodeWithCLBMetadata.id)\n            .status(nodeWithCLBMetadata.status)\n            .metadata(ParseMetadata.transformCLBMetadataToMetadata(nodeWithCLBMetadata.metadata))\n            .build();\n\n      return node;\n   }\n\n   @Override\n   public ParseNode setContext(HttpRequest request) {\n      return this;\n   }\n\n   /**\n    * This class is here only to deal with the metadata format in CLB.\n    */\n   private static class NodeWithCLBMetadata extends BaseNode<Node> {\n      private int id;\n      private Status status;\n      private List<CLBMetadata> metadata;\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/functions/ParseNodes.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.internal.Arg0ToPagedIterable;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\nimport org.jclouds.openstack.v2_0.domain.PaginatedCollection;\nimport org.jclouds.openstack.v2_0.domain.Link;\nimport org.jclouds.openstack.v2_0.options.PaginationOptions;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.CloudLoadBalancersApi;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.Node;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.features.NodeApi;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.functions.ParseNodes.Nodes;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.inject.TypeLiteral;\n\n/**\n * boiler plate until we determine a better way\n */\n@Beta\n@Singleton\npublic class ParseNodes extends ParseJson<Nodes> {\n   static class Nodes extends PaginatedCollection<Node> {\n\n      @ConstructorProperties({ \"nodes\", \"nodes_links\" })\n      protected Nodes(Iterable<Node> nodes, Iterable<Link> nodes_links) {\n         super(nodes, nodes_links);\n      }\n\n   }\n\n   @Inject\n   public ParseNodes(Json json) {\n      super(json, new TypeLiteral<Nodes>() { });\n   }\n\n   public static class ToPagedIterable extends Arg0ToPagedIterable.FromCaller<Node, ToPagedIterable> {\n\n      private final CloudLoadBalancersApi api;\n      private int lbId;\n\n      @Inject\n      protected ToPagedIterable(CloudLoadBalancersApi api) {\n         this.api = checkNotNull(api, \"api\");\n      }\n\n      @Override\n      public ToPagedIterable setContext(HttpRequest request) {\n         String path = request.getEndpoint().getPath();\n         int lastSlash = path.lastIndexOf('/');\n         int secondLastSlash = path.lastIndexOf('/', lastSlash - 1);\n\n         lbId = Integer.parseInt(path.substring(secondLastSlash + 1, lastSlash));\n\n         return super.setContext(request);\n      }\n\n      @Override\n      protected Function<Object, IterableWithMarker<Node>> markerToNextForArg0(Optional<Object> arg0) {\n         String region = arg0.get().toString();\n         final NodeApi nodeApi = api.getNodeApi(region, lbId);\n\n         return new Function<Object, IterableWithMarker<Node>>() {\n\n            @Override\n            public IterableWithMarker<Node> apply(Object input) {\n               PaginationOptions paginationOptions = PaginationOptions.class.cast(input);\n               return nodeApi.list(paginationOptions);\n            }\n\n            @Override\n            public String toString() {\n               return \"list()\";\n            }\n         };\n      }\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/functions/ParseSessionPersistence.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.SessionPersistence;\nimport org.jclouds.rest.InvocationContext;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.Iterables;\n\npublic class ParseSessionPersistence implements Function<HttpResponse, SessionPersistence>, InvocationContext<ParseSessionPersistence> {\n\n   private final ParseJson<Map<String, Map<String, SessionPersistence>>> json;\n\n   @Inject\n   ParseSessionPersistence(ParseJson<Map<String, Map<String, SessionPersistence>>> json) {\n      this.json = checkNotNull(json, \"json\");\n   }\n\n   @Override\n   public SessionPersistence apply(HttpResponse response) {\n      Map<String, Map<String, SessionPersistence>> map = json.apply(response);\n\n      if (map == null || map.isEmpty())\n         throw new HttpResponseException(\"Unexpected connection logging format returned.\", null, response);\n      else if (Iterables.get(map.values(), 0).isEmpty())\n         return null;\n      else\n         return Iterables.get(Iterables.get(map.values(), 0).values(), 0);\n   }\n\n   @Override\n   public ParseSessionPersistence setContext(HttpRequest request) {\n      return this;\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/handlers/ParseCloudLoadBalancersErrorFromHttpResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.handlers;\n\nimport static org.jclouds.http.HttpUtils.releasePayload;\n\nimport java.io.IOException;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.jclouds.util.Strings2;\n\n@Singleton\npublic class ParseCloudLoadBalancersErrorFromHttpResponse implements HttpErrorHandler {\n   @Resource\n   protected Logger logger = Logger.NULL;\n   public static final Pattern RESOURCE_PATTERN = Pattern.compile(\"^/v1[^/]*/[0-9]+/([^/]+)/([0-9]+)\");\n\n   public void handleError(HttpCommand command, HttpResponse response) {\n      Exception exception = new HttpResponseException(command, response);\n      try {\n         String content = parseErrorFromContentOrNull(command, response);\n         exception = content != null ? new HttpResponseException(command, response, content) : exception;\n         switch (response.getStatusCode()) {\n            case 401:\n               exception = new AuthorizationException(exception.getMessage(), exception);\n               break;\n            case 404:\n               if (!command.getCurrentRequest().getMethod().equals(\"DELETE\")) {\n                  String path = command.getCurrentRequest().getEndpoint().getPath();\n                  Matcher matcher = RESOURCE_PATTERN.matcher(path);\n                  String message;\n                  if (matcher.find()) {\n                     message = String.format(\"%s %s not found\", matcher.group(1), matcher.group(2));\n                  } else {\n                     message = path;\n                  }\n                  exception = new ResourceNotFoundException(message);\n               }\n               break;\n            case 409:\n               exception = new IllegalStateException(content);\n               break;\n            default:\n               exception = new HttpResponseException(command, response, content);\n               break;\n         }\n      } finally {\n         releasePayload(response);\n         command.setException(exception);\n      }\n   }\n\n   String parseErrorFromContentOrNull(HttpCommand command, HttpResponse response) {\n      if (response.getPayload() != null) {\n         try {\n            return Strings2.toStringAndClose(response.getPayload().openStream());\n         } catch (IOException e) {\n            logger.warn(e, \"exception reading error from response\", response);\n         }\n      }\n      return null;\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/loadbalancer/config/CloudLoadBalancersBindLoadBalancerStrategiesByClass.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.loadbalancer.config;\n\nimport org.jclouds.loadbalancer.config.BindLoadBalancerStrategiesByClass;\nimport org.jclouds.loadbalancer.strategy.DestroyLoadBalancerStrategy;\nimport org.jclouds.loadbalancer.strategy.GetLoadBalancerMetadataStrategy;\nimport org.jclouds.loadbalancer.strategy.ListLoadBalancersStrategy;\nimport org.jclouds.loadbalancer.strategy.LoadBalanceNodesStrategy;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.loadbalancer.strategy.CloudLoadBalancersDestroyLoadBalancerStrategy;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.loadbalancer.strategy.CloudLoadBalancersGetLoadBalancerMetadataStrategy;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.loadbalancer.strategy.CloudLoadBalancersListLoadBalancersStrategy;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.loadbalancer.strategy.CloudLoadBalancersLoadBalanceNodesStrategy;\n\npublic class CloudLoadBalancersBindLoadBalancerStrategiesByClass extends BindLoadBalancerStrategiesByClass {\n\n   @Override\n   protected Class<? extends LoadBalanceNodesStrategy> defineLoadBalanceNodesStrategy() {\n      return CloudLoadBalancersLoadBalanceNodesStrategy.class;\n   }\n\n   @Override\n   protected Class<? extends DestroyLoadBalancerStrategy> defineDestroyLoadBalancerStrategy() {\n      return CloudLoadBalancersDestroyLoadBalancerStrategy.class;\n   }\n\n   @Override\n   protected Class<? extends GetLoadBalancerMetadataStrategy> defineGetLoadBalancerMetadataStrategy() {\n      return CloudLoadBalancersGetLoadBalancerMetadataStrategy.class;\n   }\n\n   @Override\n   protected Class<? extends ListLoadBalancersStrategy> defineListLoadBalancersStrategy() {\n      return CloudLoadBalancersListLoadBalancersStrategy.class;\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/loadbalancer/config/CloudLoadBalancersLoadBalancerContextModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.loadbalancer.config;\n\nimport org.jclouds.loadbalancer.config.BaseLoadBalancerServiceContextModule;\n\n/**\n * Configures the CloudLoadBalancers connection.\n */\n\npublic class CloudLoadBalancersLoadBalancerContextModule extends BaseLoadBalancerServiceContextModule {\n\n   @Override\n   protected void configure() {\n      install(new CloudLoadBalancersBindLoadBalancerStrategiesByClass());\n      install(new CloudLoadBalancersLoadBalancerServiceDependenciesModule());\n      super.configure();\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/loadbalancer/config/CloudLoadBalancersLoadBalancerServiceDependenciesModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.loadbalancer.config;\n\nimport org.jclouds.loadbalancer.domain.LoadBalancerMetadata;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.LoadBalancer;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.loadbalancer.functions.LoadBalancerToLoadBalancerMetadata;\n\nimport com.google.common.base.Function;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.TypeLiteral;\n\npublic class CloudLoadBalancersLoadBalancerServiceDependenciesModule extends AbstractModule {\n\n   @Override\n   protected void configure() {\n      bind(new TypeLiteral<Function<LoadBalancer, LoadBalancerMetadata>>() {\n      }).to(LoadBalancerToLoadBalancerMetadata.class);\n   }\n\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/loadbalancer/functions/LoadBalancerToLoadBalancerMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.loadbalancer.functions;\n\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.domain.Location;\nimport org.jclouds.loadbalancer.domain.LoadBalancerMetadata;\nimport org.jclouds.loadbalancer.domain.LoadBalancerType;\nimport org.jclouds.loadbalancer.domain.internal.LoadBalancerMetadataImpl;\nimport org.jclouds.location.predicates.LocationPredicates;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.LoadBalancer;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.VirtualIPWithId;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\n\n@Singleton\npublic class LoadBalancerToLoadBalancerMetadata implements Function<LoadBalancer, LoadBalancerMetadata> {\n   protected final Supplier<Set<? extends Location>> locations;\n   protected final Supplier<Location> defaultLocationSupplier;\n\n   @Inject\n   public LoadBalancerToLoadBalancerMetadata(Supplier<Location> defaultLocationSupplier,\n            @Memoized Supplier<Set<? extends Location>> locations) {\n      this.locations = locations;\n      this.defaultLocationSupplier = defaultLocationSupplier;\n   }\n\n   @Override\n   public LoadBalancerMetadata apply(LoadBalancer input) {\n\n      Location location = Iterables.find(locations.get(), LocationPredicates.idEquals(input.getRegion()));\n\n      String id = input.getRegion() + \"/\" + input.getId();\n      // TODO Builder\n      return new LoadBalancerMetadataImpl(LoadBalancerType.LB, String.valueOf(input.getId()), input.getName(), id, location, null,\n               ImmutableMap.<String, String> of(), Iterables.transform(input.getVirtualIPs(),\n                        new Function<VirtualIPWithId, String>() {\n\n                           @Override\n                           public String apply(VirtualIPWithId arg0) {\n                              return arg0.getAddress();\n                           }\n\n                        }));\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/loadbalancer/strategy/CloudLoadBalancersDestroyLoadBalancerStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.loadbalancer.strategy;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.loadbalancer.domain.LoadBalancerMetadata;\nimport org.jclouds.loadbalancer.reference.LoadBalancerConstants;\nimport org.jclouds.loadbalancer.strategy.DestroyLoadBalancerStrategy;\nimport org.jclouds.loadbalancer.strategy.GetLoadBalancerMetadataStrategy;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.CloudLoadBalancersApi;\n\n@Singleton\npublic class CloudLoadBalancersDestroyLoadBalancerStrategy implements DestroyLoadBalancerStrategy {\n   @Resource\n   @Named(LoadBalancerConstants.LOADBALANCER_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   private final CloudLoadBalancersApi client;\n   private final GetLoadBalancerMetadataStrategy getLoadBalancer;\n\n   @Inject\n   protected CloudLoadBalancersDestroyLoadBalancerStrategy(CloudLoadBalancersApi client,\n            GetLoadBalancerMetadataStrategy getLoadBalancer) {\n      this.client = checkNotNull(client, \"client\");\n      this.getLoadBalancer = checkNotNull(getLoadBalancer, \"getLoadBalancer\");\n   }\n\n   @Override\n   public LoadBalancerMetadata destroyLoadBalancer(String id) {\n      String[] parts = checkNotNull(id, \"id\").split(\"/\");\n      String region = parts[0];\n      int lbId = Integer.parseInt(parts[1]);\n      client.getLoadBalancerApi(region).delete(lbId);\n      return getLoadBalancer.getLoadBalancer(id);\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/loadbalancer/strategy/CloudLoadBalancersGetLoadBalancerMetadataStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.loadbalancer.strategy;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.loadbalancer.domain.LoadBalancerMetadata;\nimport org.jclouds.loadbalancer.strategy.GetLoadBalancerMetadataStrategy;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.CloudLoadBalancersApi;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.LoadBalancer;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class CloudLoadBalancersGetLoadBalancerMetadataStrategy implements GetLoadBalancerMetadataStrategy {\n\n   private final org.jclouds.rackspace.cloudloadbalancers.v1.CloudLoadBalancersApi client;\n   private final Function<LoadBalancer, LoadBalancerMetadata> converter;\n\n   @Inject\n   protected CloudLoadBalancersGetLoadBalancerMetadataStrategy(CloudLoadBalancersApi client,\n            Function<LoadBalancer, LoadBalancerMetadata> converter) {\n      this.client = checkNotNull(client, \"client\");\n      this.converter = checkNotNull(converter, \"converter\");\n   }\n\n   @Override\n   public LoadBalancerMetadata getLoadBalancer(String id) {\n      String[] parts = checkNotNull(id, \"id\").split(\"/\");\n      String region = parts[0];\n      int lbId = Integer.parseInt(parts[1]);\n      return converter.apply(client.getLoadBalancerApi(region).get(lbId));\n   }\n\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/loadbalancer/strategy/CloudLoadBalancersListLoadBalancersStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.loadbalancer.strategy;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.loadbalancer.domain.LoadBalancerMetadata;\nimport org.jclouds.loadbalancer.strategy.ListLoadBalancersStrategy;\nimport org.jclouds.location.Region;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.CloudLoadBalancersApi;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.LoadBalancer;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\n\n@Singleton\npublic class CloudLoadBalancersListLoadBalancersStrategy implements ListLoadBalancersStrategy {\n\n   private final CloudLoadBalancersApi aclient;\n   private final Function<LoadBalancer, LoadBalancerMetadata> converter;\n   private final Supplier<Set<String>> regions;\n\n   @Inject\n   protected CloudLoadBalancersListLoadBalancersStrategy(CloudLoadBalancersApi aclient,\n         Function<LoadBalancer, LoadBalancerMetadata> converter, @Region Supplier<Set<String>> regions) {\n      this.aclient = checkNotNull(aclient, \"aclient\");\n      this.regions = checkNotNull(regions, \"regions\");\n      this.converter = checkNotNull(converter, \"converter\");\n   }\n\n   @Override\n   public Iterable<? extends LoadBalancerMetadata> listLoadBalancers() {\n      Builder<LoadBalancerMetadata> loadBalancers = ImmutableSet.<LoadBalancerMetadata> builder();\n      for (String region : regions.get()) { // TODO: parallel\n         loadBalancers.addAll(aclient.getLoadBalancerApi(region).list().concat().transform(converter));\n      }\n      return loadBalancers.build();\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/loadbalancer/strategy/CloudLoadBalancersLoadBalanceNodesStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.loadbalancer.strategy;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.domain.Location;\nimport org.jclouds.loadbalancer.domain.LoadBalancerMetadata;\nimport org.jclouds.loadbalancer.reference.LoadBalancerConstants;\nimport org.jclouds.loadbalancer.strategy.GetLoadBalancerMetadataStrategy;\nimport org.jclouds.loadbalancer.strategy.LoadBalanceNodesStrategy;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.CloudLoadBalancersApi;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.LoadBalancer;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.CreateLoadBalancer;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.AddNode;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.VirtualIP.Type;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.Iterables;\n\n@Singleton\npublic class CloudLoadBalancersLoadBalanceNodesStrategy implements LoadBalanceNodesStrategy {\n   @Resource\n   @Named(LoadBalancerConstants.LOADBALANCER_LOGGER)\n   protected Logger logger = Logger.NULL;\n   protected final CloudLoadBalancersApi client;\n   protected final GetLoadBalancerMetadataStrategy getLB;\n\n   @Inject\n   protected CloudLoadBalancersLoadBalanceNodesStrategy(CloudLoadBalancersApi client,\n            GetLoadBalancerMetadataStrategy getLB) {\n      this.client = checkNotNull(client, \"client\");\n      this.getLB = checkNotNull(getLB, \"getLB\");\n   }\n\n   @Override\n   public LoadBalancerMetadata createLoadBalancerInLocation(Location location, String name, String protocol,\n            int loadBalancerPort, final int instancePort, Iterable<? extends NodeMetadata> nodes) {\n      String region = checkNotNull(location, \"location\").getId();\n\n      // TODO need to query and update the LB per current design.\n      LoadBalancer lb = client.getLoadBalancerApi(region).create(\n               CreateLoadBalancer.builder().name(name).protocol(protocol.toUpperCase()).port(loadBalancerPort)\n                        .virtualIPType(Type.PUBLIC).nodes(\n                                 Iterables.transform(nodes, new Function<NodeMetadata, AddNode>() {\n\n                                    @Override\n                                    public AddNode apply(NodeMetadata arg0) {\n                                       return AddNode.builder().address(\n                                                Iterables.get(arg0.getPrivateAddresses(), 0)).port(instancePort)\n                                                .build();\n\n                                    }\n\n                                 })).build());\n      return getLB.getLoadBalancer(region + \"/\" + lb.getId());\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/options/ListOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.options;\n\nimport static com.google.common.base.Preconditions.checkArgument;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * To reduce load on the service, list operations will return a maximum of 100 items at a time. To\n * navigate the collection, the limit and marker parameters (for example, ?limit=50&marker=1 ) can\n * be set in the URI. If a marker beyond the end of a list is given, an empty list is returned. Note\n * that list operations never return 404 (itemNotFound) faults.\n * \n * @see <a\n *      href=\"http://docs.rackspacecloud.com/loadbalancers/api/v1.0/clb-devguide/content/ch03s06.html\"\n *      />\n */\npublic class ListOptions extends BaseHttpRequestOptions {\n   public static final ListOptions NONE = new ListOptions();\n\n   /**\n    * Indicates where to begin listing, if the previous list was larger than the limit.\n    */\n   public ListOptions marker(String marker) {\n      checkArgument(marker != null, \"marker cannot be null\");\n      queryParameters.replaceValues(\"marker\", ImmutableSet.of(marker));\n      return this;\n   }\n\n   /**\n    * To reduce load on the service, list operations will return a maximum of 100 items at a time.\n    * <p/>\n    * Note that list operations never return itemNotFound (404) faults.\n    */\n   public ListOptions limit(int limit) {\n      checkArgument(limit >= 0, \"limit must be >= 0\");\n      checkArgument(limit <= 10000, \"limit must be <= 10000\");\n      queryParameters.replaceValues(\"limit\", ImmutableSet.of(limit + \"\"));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see ListOptions#marker(marker)\n       */\n      public static ListOptions marker(String marker) {\n         ListOptions options = new ListOptions();\n         return options.marker(marker);\n      }\n\n      /**\n       * @see ListOptions#limit(long)\n       */\n      public static ListOptions limit(int limit) {\n         ListOptions options = new ListOptions();\n         return options.limit(limit);\n      }\n\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/main/java/org/jclouds/rackspace/cloudloadbalancers/v1/predicates/LoadBalancerPredicates.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static org.jclouds.util.Predicates2.retry;\n\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.LoadBalancer;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.features.LoadBalancerApi;\n\nimport com.google.common.base.Predicate;\n\n/**\n * Tests to see if loadBalancer has reached status. This class is most useful when paired with a RetryablePredicate as\n * in the code below. This class can be used to block execution until the LoadBalancer status has reached a desired state.\n * This is useful when your LoadBalancer needs to be 100% ready before you can continue with execution.\n * <br/>\n * <pre>\n * {@code\n * LoadBalancer loadBalancer = loadBalancerApi.create(loadBalancerRequest);\n *\n * RetryablePredicate<String> awaitAvailable = RetryablePredicate.create(\n *    LoadBalancerPredicates.available(loadBalancerApi), 600, 10, 10, TimeUnit.SECONDS);\n *\n * if (!awaitAvailable.apply(loadBalancer)) {\n *    throw new TimeoutException(\"Timeout on loadBalancer: \" + loadBalancer);\n * }\n * }\n * </pre>\n *\n * You can also use the static convenience methods as so.\n * <br/>\n * <pre>\n * {@code\n * LoadBalancer loadBalancer = loadBalancerApi.create(loadBalancerRequest);\n *\n * if (!LoadBalancerPredicates.awaitAvailable(loadBalancerApi).apply(loadBalancer)) {\n *    throw new TimeoutException(\"Timeout on loadBalancer: \" + loadBalancer);\n * }\n * }\n * </pre>\n */\npublic class LoadBalancerPredicates {\n   /**\n    * Wait until a LoadBalancer is Available.\n    *\n    * @param loadBalancerApi The LoadBalancerApi in the region where your LoadBalancer resides.\n    * @return RetryablePredicate That will check the status every 3 seconds for a maxiumum of 5 minutes.\n    */\n   public static Predicate<LoadBalancer> awaitAvailable(LoadBalancerApi loadBalancerApi) {\n      StatusUpdatedPredicate statusPredicate = new StatusUpdatedPredicate(loadBalancerApi, LoadBalancer.Status.ACTIVE);\n      return retry(statusPredicate, 300, 3, 3, SECONDS);\n   }\n\n   /**\n    * Wait until a LoadBalancer no longer exists.\n    *\n    * @param loadBalancerApi The LoadBalancerApi in the region where your LoadBalancer resides.\n    * @return RetryablePredicate That will check the whether the LoadBalancer exists\n    * every 3 seconds for a maxiumum of 5 minutes.\n    */\n   public static Predicate<LoadBalancer> awaitDeleted(LoadBalancerApi loadBalancerApi) {\n      DeletedPredicate deletedPredicate = new DeletedPredicate(loadBalancerApi);\n      return retry(deletedPredicate, 300, 3, 3, SECONDS);\n   }\n\n   public static Predicate<LoadBalancer> awaitStatus(\n         LoadBalancerApi loadBalancerApi, LoadBalancer.Status status, long maxWaitInSec, long periodInSec) {\n      StatusUpdatedPredicate statusPredicate = new StatusUpdatedPredicate(loadBalancerApi, status);\n      return retry(statusPredicate, maxWaitInSec, periodInSec, periodInSec, SECONDS);\n   }\n\n   private static class StatusUpdatedPredicate implements Predicate<LoadBalancer> {\n      private LoadBalancerApi loadBalancerApi;\n      private LoadBalancer.Status status;\n\n      public StatusUpdatedPredicate(LoadBalancerApi loadBalancerApi, LoadBalancer.Status status) {\n         this.loadBalancerApi = checkNotNull(loadBalancerApi, \"loadBalancerApi must be defined\");\n         this.status = checkNotNull(status, \"status must be defined\");\n      }\n\n      /**\n       * @return boolean Return true when the loadBalancer reaches status, false otherwise\n       */\n      @Override\n      public boolean apply(LoadBalancer loadBalancer) {\n         checkNotNull(loadBalancer, \"loadBalancer must be defined\");\n\n         LoadBalancer loadBalancerUpdated = loadBalancerApi.get(loadBalancer.getId());\n         checkNotNull(loadBalancerUpdated, \"LoadBalancer %s not found.\", loadBalancer.getId());\n\n         return status.equals(loadBalancerUpdated.getStatus());\n      }\n   }\n\n   private static class DeletedPredicate implements Predicate<LoadBalancer> {\n      private LoadBalancerApi loadBalancerApi;\n\n      public DeletedPredicate(LoadBalancerApi loadBalancerApi) {\n         this.loadBalancerApi = checkNotNull(loadBalancerApi, \"loadBalancerApi must be defined\");\n      }\n\n      /**\n       * @return boolean Return true when the snapshot is deleted, false otherwise\n       */\n      @Override\n      public boolean apply(LoadBalancer loadBalancer) {\n         checkNotNull(loadBalancer, \"loadBalancer must be defined\");\n         LoadBalancer loadBalancerUpdate = loadBalancerApi.get(loadBalancer.getId());\n\n         if (loadBalancerUpdate == null) {\n            return true;\n         }\n         else {\n            return loadBalancerUpdate.getStatus().equals(LoadBalancer.Status.DELETED);\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/java/org/jclouds/rackspace/cloudloadbalancers/v1/CloudLoadBalancersApiMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1;\n\nimport org.jclouds.loadbalancer.internal.BaseLoadBalancerServiceApiMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"CloudLoadBalancersApiMetadataTest\")\npublic class CloudLoadBalancersApiMetadataTest extends BaseLoadBalancerServiceApiMetadataTest {\n\n   public CloudLoadBalancersApiMetadataTest() {\n      super(new CloudLoadBalancersApiMetadata());\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/java/org/jclouds/rackspace/cloudloadbalancers/v1/features/AccessRuleApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.features;\nimport static com.google.common.net.HttpHeaders.ACCEPT;\nimport static jakarta.ws.rs.HttpMethod.DELETE;\nimport static jakarta.ws.rs.HttpMethod.POST;\nimport static jakarta.ws.rs.core.MediaType.WILDCARD;\nimport static jakarta.ws.rs.core.Response.Status.OK;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.CloudLoadBalancersApi;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.AccessRule;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.AccessRuleWithId;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.internal.BaseCloudLoadBalancerApiExpectTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\")\npublic class AccessRuleApiExpectTest extends BaseCloudLoadBalancerApiExpectTest<CloudLoadBalancersApi> {\n   public void testListAccessRules() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/accesslist\");\n      AccessRuleApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/accesslist-list.json\")).build()\n      ).getAccessRuleApi(\"DFW\", 2000);\n\n      Iterable<AccessRuleWithId> accessList = api.list();\n      assertEquals(accessList, getAccessRules());\n   }\n\n   public void testCreateAccessRules() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/accesslist\");\n      AccessRuleApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess,\n            authenticatedGET().method(POST).endpoint(endpoint).payload(payloadFromResource(\"/accesslist-create.json\")).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).build()\n      ).getAccessRuleApi(\"DFW\", 2000);\n\n      AccessRule accessRule1 = AccessRule.deny(\"206.160.163.21\");\n      AccessRule accessRule2 = AccessRule.deny(\"206.160.165.11\");\n      AccessRule accessRule3 = AccessRule.deny(\"206.160.163.22\");\n\n      List<AccessRule> accessList = ImmutableList.<AccessRule> of(accessRule1, accessRule2, accessRule3);\n      api.create(accessList);\n   }\n\n   public void testRemoveSingleAccessRule() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/accesslist/23\");\n      AccessRuleApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess,\n            authenticatedGET().method(DELETE).endpoint(endpoint).replaceHeader(ACCEPT, WILDCARD).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).build()\n      ).getAccessRuleApi(\"DFW\", 2000);\n\n      assertTrue(api.delete(23));\n   }\n\n   public void testRemoveManyAccessRules() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/accesslist?id=23&id=24\");\n      AccessRuleApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess,\n            authenticatedGET().method(DELETE).endpoint(endpoint).replaceHeader(ACCEPT, WILDCARD).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).build()\n      ).getAccessRuleApi(\"DFW\", 2000);\n\n      List<Integer> accessRuleIds = ImmutableList.<Integer> of(23, 24);\n      assertTrue(api.delete(accessRuleIds));\n   }\n\n   public void testRemoveAllAccessRules() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/accesslist\");\n      AccessRuleApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess,\n            authenticatedGET().method(DELETE).endpoint(endpoint).replaceHeader(ACCEPT, WILDCARD).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).build()\n      ).getAccessRuleApi(\"DFW\", 2000);\n\n      assertTrue(api.deleteAll());\n   }\n\n   private Iterable<AccessRuleWithId> getAccessRules() {\n      AccessRuleWithId accessRule1 = new AccessRuleWithId(23, \"206.160.163.21\", AccessRule.Type.DENY);\n      AccessRuleWithId accessRule2 = new AccessRuleWithId(24, \"206.160.165.11\", AccessRule.Type.DENY);\n      AccessRuleWithId accessRule3 = new AccessRuleWithId(25, \"206.160.163.22\", AccessRule.Type.DENY);\n\n      return ImmutableList.<AccessRuleWithId> of(accessRule1, accessRule2, accessRule3);\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/java/org/jclouds/rackspace/cloudloadbalancers/v1/features/AccessRuleApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.features;\n\nimport static org.jclouds.rackspace.cloudloadbalancers.v1.predicates.LoadBalancerPredicates.awaitAvailable;\nimport static org.jclouds.rackspace.cloudloadbalancers.v1.predicates.LoadBalancerPredicates.awaitDeleted;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.AccessRule;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.AccessRuleWithId;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.LoadBalancer;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.CreateLoadBalancer;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.AddNode;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.VirtualIP.Type;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.internal.BaseCloudLoadBalancersApiLiveTest;\nimport org.testng.annotations.AfterGroups;\nimport org.testng.annotations.BeforeGroups;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Maps;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"AccessListApiLiveTest\")\npublic class AccessRuleApiLiveTest extends BaseCloudLoadBalancersApiLiveTest {\n   private LoadBalancer lb;\n   private String region;\n   private AccessRule accessRule1;\n   private AccessRule accessRule2;\n   private AccessRule accessRule3;\n   private AccessRule accessRule4;\n   private Map<String, AccessRule> accessRules;\n\n   @Override\n   @BeforeGroups(groups = { \"live\" })\n   public void setup() {\n      super.setup();\n\n      accessRule1 = AccessRule.deny(\"206.160.163.21\");\n      accessRule2 = AccessRule.deny(\"206.160.165.11\");\n      accessRule3 = AccessRule.deny(\"206.160.163.22\");\n      accessRule4 = AccessRule.deny(\"206.160.168.22\");\n\n      accessRules = Maps.newHashMap();\n      accessRules.put(accessRule1.getAddress(), accessRule1);\n      accessRules.put(accessRule2.getAddress(), accessRule2);\n      accessRules.put(accessRule3.getAddress(), accessRule3);\n      accessRules.put(accessRule4.getAddress(), accessRule4);\n   }\n\n   public void testCreateLoadBalancer() {\n      AddNode addNode = AddNode.builder().address(\"192.168.1.1\").port(8080).build();\n      CreateLoadBalancer createLB = CreateLoadBalancer.builder()\n            .name(prefix + \"-jclouds\").protocol(\"HTTP\").port(80).virtualIPType(Type.PUBLIC).node(addNode).build();\n\n      region = \"ORD\";  //Iterables.getFirst(api.getConfiguredRegions(), null);\n      lb = api.getLoadBalancerApi(region).create(createLB);\n\n      assertTrue(awaitAvailable(api.getLoadBalancerApi(region)).apply(lb));\n   }\n\n   @Test(dependsOnMethods = \"testCreateLoadBalancer\")\n   public void testCreateAccessList() throws Exception {\n      api.getAccessRuleApi(region, lb.getId()).create(accessRules.values());\n      assertTrue(awaitAvailable(api.getLoadBalancerApi(region)).apply(lb));\n\n      assertExpectedAccessRules(accessRules);\n   }\n\n   @Test(dependsOnMethods = \"testCreateAccessList\")\n   public void testRemoveSingleAccessRule() throws Exception {\n      Iterable<AccessRuleWithId> actualAccessList = api.getAccessRuleApi(region, lb.getId()).list();\n      AccessRuleWithId removedAccessRule = Iterables.getFirst(actualAccessList, null);\n      accessRules.remove(removedAccessRule.getAddress());\n\n      assertTrue(api.getAccessRuleApi(region, lb.getId()).delete(removedAccessRule.getId()));\n      assertTrue(awaitAvailable(api.getLoadBalancerApi(region)).apply(lb));\n\n      assertExpectedAccessRules(accessRules);\n   }\n\n   @Test(dependsOnMethods = \"testRemoveSingleAccessRule\")\n   public void testRemoveManyAccessRules() throws Exception {\n      Iterable<AccessRuleWithId> actualAccessList = api.getAccessRuleApi(region, lb.getId()).list();\n      AccessRuleWithId removedAccessRule1 = Iterables.getFirst(actualAccessList, null);\n      AccessRuleWithId removedAccessRule2 = Iterables.getLast(actualAccessList);\n      List<Integer> removedAccessRuleIds = ImmutableList.<Integer> of(removedAccessRule1.getId(), removedAccessRule2.getId());\n      accessRules.remove(removedAccessRule1.getAddress());\n      accessRules.remove(removedAccessRule2.getAddress());\n\n      assertTrue(api.getAccessRuleApi(region, lb.getId()).delete(removedAccessRuleIds));\n      assertTrue(awaitAvailable(api.getLoadBalancerApi(region)).apply(lb));\n\n      assertExpectedAccessRules(accessRules);\n   }\n\n   @Test(dependsOnMethods = \"testRemoveManyAccessRules\")\n   public void testRemoveAllAccessRules() throws Exception {\n      assertTrue(api.getAccessRuleApi(region, lb.getId()).deleteAll());\n      assertTrue(awaitAvailable(api.getLoadBalancerApi(region)).apply(lb));\n\n      assertExpectedAccessRules(Maps.<String, AccessRule>newHashMap());\n   }\n\n   private void assertExpectedAccessRules(Map<String, AccessRule> expectedAccessList) {\n      Iterable<AccessRuleWithId> actualAccessList = api.getAccessRuleApi(region, lb.getId()).list();\n\n      for (AccessRule actualAccessRule : actualAccessList) {\n         assertEquals(expectedAccessList.containsKey(actualAccessRule.getAddress()), true,\n               \"The AccessRule \" + actualAccessRule + \" was not found in \" + expectedAccessList);\n      }\n   }\n\n   @Override\n   @AfterGroups(groups = \"live\")\n   protected void tearDown() {\n      assertTrue(awaitAvailable(api.getLoadBalancerApi(region)).apply(lb));\n      api.getLoadBalancerApi(region).delete(lb.getId());\n      assertTrue(awaitDeleted(api.getLoadBalancerApi(region)).apply(lb));\n      super.tearDown();\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/java/org/jclouds/rackspace/cloudloadbalancers/v1/features/ConnectionApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.features;\nimport static com.google.common.net.HttpHeaders.ACCEPT;\nimport static jakarta.ws.rs.HttpMethod.DELETE;\nimport static jakarta.ws.rs.HttpMethod.PUT;\nimport static jakarta.ws.rs.core.MediaType.WILDCARD;\nimport static jakarta.ws.rs.core.Response.Status.OK;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.CloudLoadBalancersApi;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.ConnectionThrottle;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.internal.BaseCloudLoadBalancerApiExpectTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class ConnectionApiExpectTest extends BaseCloudLoadBalancerApiExpectTest<CloudLoadBalancersApi> {\n   public void testGetConnectionThrottle() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/connectionthrottle\");\n      ConnectionApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/connectionthrottle-get.json\")).build()\n      ).getConnectionApi(\"DFW\", 2000);\n\n      ConnectionThrottle connectionThrottle = api.getConnectionThrottle();\n      assertEquals(connectionThrottle, getConnectionThrottle());\n   }\n\n   public void testGetDeletedConnectionThrottle() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/connectionthrottle\");\n      ConnectionApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/connectionthrottle-get-deleted.json\")).build()\n      ).getConnectionApi(\"DFW\", 2000);\n\n      ConnectionThrottle connectionThrottle = api.getConnectionThrottle();\n      assertNull(connectionThrottle);\n   }\n\n   public void testCreateConnectionThrottle() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/connectionthrottle\");\n      ConnectionApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess,\n            authenticatedGET().method(PUT).endpoint(endpoint).payload(payloadFromResource(\"/connectionthrottle-create.json\")).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).build()\n      ).getConnectionApi(\"DFW\", 2000);\n\n      api.createOrUpdateConnectionThrottle(getConnectionThrottle());\n   }\n\n   public void testValidConnectionThrottle() {\n      assertTrue(getConnectionThrottle().isValid());\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testInvalidConnectionThrottle() {\n      ConnectionThrottle.builder().build();\n   }\n\n   public void testRemoveConnectionThrottle() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/connectionthrottle\");\n      ConnectionApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess,\n            authenticatedGET().method(DELETE).endpoint(endpoint).replaceHeader(ACCEPT, WILDCARD).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).build()\n      ).getConnectionApi(\"DFW\", 2000);\n\n      assertTrue(api.deleteConnectionThrottle());\n   }\n\n   public void testIsConnectionLogging() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/connectionlogging\");\n      ConnectionApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/connectionlogging-enable.json\")).build()\n      ).getConnectionApi(\"DFW\", 2000);\n\n      assertTrue(api.isConnectionLogging());\n   }\n\n   public void testEnableConnectionLogging() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/connectionlogging\");\n      ConnectionApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess,\n            authenticatedGET().method(PUT).endpoint(endpoint).payload(payloadFromResource(\"/connectionlogging-enable.json\")).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).build()\n      ).getConnectionApi(\"DFW\", 2000);\n\n      api.enableConnectionLogging();\n   }\n\n   public void testDisableConnectionLogging() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/connectionlogging\");\n      ConnectionApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess,\n            authenticatedGET().method(PUT).endpoint(endpoint).payload(payloadFromResource(\"/connectionlogging-disable.json\")).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).build()\n      ).getConnectionApi(\"DFW\", 2000);\n\n      api.disableConnectionLogging();\n   }\n\n   public static ConnectionThrottle getConnectionThrottle() {\n      ConnectionThrottle connectionThrottle = ConnectionThrottle.builder()\n            .maxConnections(100)\n            .maxConnectionRate(100)\n            .minConnections(10)\n            .rateInterval(100)\n            .build();\n\n      return connectionThrottle;\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/java/org/jclouds/rackspace/cloudloadbalancers/v1/features/ConnectionApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.features;\n\nimport static org.jclouds.rackspace.cloudloadbalancers.v1.predicates.LoadBalancerPredicates.awaitAvailable;\nimport static org.jclouds.rackspace.cloudloadbalancers.v1.predicates.LoadBalancerPredicates.awaitDeleted;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.ConnectionThrottle;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.LoadBalancer;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.CreateLoadBalancer;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.AddNode;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.VirtualIP.Type;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.internal.BaseCloudLoadBalancersApiLiveTest;\nimport org.testng.annotations.AfterGroups;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Iterables;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"ConnectionApiLiveTest\")\npublic class ConnectionApiLiveTest extends BaseCloudLoadBalancersApiLiveTest {\n   private LoadBalancer lb;\n   private String region;\n\n   public void testCreateLoadBalancer() {\n      AddNode addNode = AddNode.builder().address(\"192.168.1.1\").port(8080).build();\n      CreateLoadBalancer createLB = CreateLoadBalancer.builder()\n            .name(prefix + \"-jclouds\").protocol(\"HTTP\").port(80).virtualIPType(Type.PUBLIC).node(addNode).build();\n\n      region = Iterables.getFirst(api.getConfiguredRegions(), null);\n      lb = api.getLoadBalancerApi(region).create(createLB);\n\n      assertTrue(awaitAvailable(api.getLoadBalancerApi(region)).apply(lb));\n   }\n\n   @Test(dependsOnMethods = \"testCreateLoadBalancer\")\n   public void testCreateAndGetConnectionThrottling() throws Exception {\n      api.getConnectionApi(region, lb.getId()).createOrUpdateConnectionThrottle(\n            ConnectionApiExpectTest.getConnectionThrottle());\n      assertTrue(awaitAvailable(api.getLoadBalancerApi(region)).apply(lb));\n\n      ConnectionThrottle connectionThrottle =\n            api.getConnectionApi(region, lb.getId()).getConnectionThrottle();\n\n      assertEquals(connectionThrottle, ConnectionApiExpectTest.getConnectionThrottle());\n   }\n\n   @Test(dependsOnMethods = \"testCreateAndGetConnectionThrottling\")\n   public void testRemoveAndGetConnectionThrottle() throws Exception {\n      assertTrue(api.getConnectionApi(region, lb.getId()).deleteConnectionThrottle());\n      assertTrue(awaitAvailable(api.getLoadBalancerApi(region)).apply(lb));\n\n      ConnectionThrottle connectionThrottle =\n            api.getConnectionApi(region, lb.getId()).getConnectionThrottle();\n\n      assertNull(connectionThrottle);\n   }\n\n   @Test(dependsOnMethods = \"testRemoveAndGetConnectionThrottle\")\n   public void testEnableAndIsConnectionLogging() throws Exception {\n      api.getConnectionApi(region, lb.getId()).enableConnectionLogging();\n      assertTrue(awaitAvailable(api.getLoadBalancerApi(region)).apply(lb));\n\n      boolean isConnectionLogging =\n            api.getConnectionApi(region, lb.getId()).isConnectionLogging();\n\n      assertTrue(isConnectionLogging);\n   }\n\n   @Test(dependsOnMethods = \"testEnableAndIsConnectionLogging\")\n   public void testDisableAndIsConnectionLogging() throws Exception {\n      api.getConnectionApi(region, lb.getId()).disableConnectionLogging();\n      assertTrue(awaitAvailable(api.getLoadBalancerApi(region)).apply(lb));\n\n      boolean isConnectionLogging =\n            api.getConnectionApi(region, lb.getId()).isConnectionLogging();\n\n      assertFalse(isConnectionLogging);\n   }\n\n   @Override\n   @AfterGroups(groups = \"live\")\n   protected void tearDown() {\n      assertTrue(awaitAvailable(api.getLoadBalancerApi(region)).apply(lb));\n      api.getLoadBalancerApi(region).delete(lb.getId());\n      assertTrue(awaitDeleted(api.getLoadBalancerApi(region)).apply(lb));\n      super.tearDown();\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/java/org/jclouds/rackspace/cloudloadbalancers/v1/features/ContentCachingApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.features;\nimport static jakarta.ws.rs.HttpMethod.PUT;\nimport static jakarta.ws.rs.core.Response.Status.OK;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.CloudLoadBalancersApi;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.internal.BaseCloudLoadBalancerApiExpectTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class ContentCachingApiExpectTest extends BaseCloudLoadBalancerApiExpectTest<CloudLoadBalancersApi> {\n   public void testIsContentCaching() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/contentcaching\");\n      ContentCachingApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/contentcaching-enable.json\")).build()\n      ).getContentCachingApi(\"DFW\", 2000);\n\n      assertTrue(api.isContentCaching());\n   }\n\n   public void testEnableContentCaching() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/contentcaching\");\n      ContentCachingApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess,\n            authenticatedGET().method(PUT).endpoint(endpoint).payload(payloadFromResource(\"/contentcaching-enable.json\")).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).build()\n      ).getContentCachingApi(\"DFW\", 2000);\n\n      api.enable();\n   }\n\n   public void testDisableContentCaching() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/contentcaching\");\n      ContentCachingApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess,\n            authenticatedGET().method(PUT).endpoint(endpoint).payload(payloadFromResource(\"/contentcaching-disable.json\")).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).build()\n      ).getContentCachingApi(\"DFW\", 2000);\n\n      api.disable();\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/java/org/jclouds/rackspace/cloudloadbalancers/v1/features/ContentCachingApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.features;\n\nimport static org.jclouds.rackspace.cloudloadbalancers.v1.predicates.LoadBalancerPredicates.awaitAvailable;\nimport static org.jclouds.rackspace.cloudloadbalancers.v1.predicates.LoadBalancerPredicates.awaitDeleted;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.LoadBalancer;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.CreateLoadBalancer;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.AddNode;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.VirtualIP.Type;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.internal.BaseCloudLoadBalancersApiLiveTest;\nimport org.testng.annotations.AfterGroups;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Iterables;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"ContentCachingApiLiveTest\")\npublic class ContentCachingApiLiveTest extends BaseCloudLoadBalancersApiLiveTest {\n   private LoadBalancer lb;\n   private String region;\n\n   public void testCreateLoadBalancer() {\n      AddNode addNode = AddNode.builder().address(\"192.168.1.1\").port(8080).build();\n      CreateLoadBalancer createLB = CreateLoadBalancer.builder()\n            .name(prefix + \"-jclouds\").protocol(\"HTTP\").port(80).virtualIPType(Type.PUBLIC).node(addNode).build();\n\n      region = Iterables.getFirst(api.getConfiguredRegions(), null);\n      lb = api.getLoadBalancerApi(region).create(createLB);\n\n      assertTrue(awaitAvailable(api.getLoadBalancerApi(region)).apply(lb));\n   }\n\n   @Test(dependsOnMethods = \"testCreateLoadBalancer\")\n   public void testEnableAndIsContentCaching() throws Exception {\n      api.getContentCachingApi(region, lb.getId()).enable();\n      assertTrue(awaitAvailable(api.getLoadBalancerApi(region)).apply(lb));\n\n      boolean isContentCaching =\n            api.getContentCachingApi(region, lb.getId()).isContentCaching();\n\n      assertTrue(isContentCaching);\n   }\n\n   @Test(dependsOnMethods = \"testEnableAndIsContentCaching\")\n   public void testDisableAndIsContentCaching() throws Exception {\n      api.getContentCachingApi(region, lb.getId()).disable();\n      assertTrue(awaitAvailable(api.getLoadBalancerApi(region)).apply(lb));\n\n      boolean isContentCaching =\n            api.getContentCachingApi(region, lb.getId()).isContentCaching();\n\n      assertFalse(isContentCaching);\n   }\n\n   @Override\n   @AfterGroups(groups = \"live\")\n   protected void tearDown() {\n      assertTrue(awaitAvailable(api.getLoadBalancerApi(region)).apply(lb));\n      api.getLoadBalancerApi(region).delete(lb.getId());\n      assertTrue(awaitDeleted(api.getLoadBalancerApi(region)).apply(lb));\n      super.tearDown();\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/java/org/jclouds/rackspace/cloudloadbalancers/v1/features/ErrorPageApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.features;\nimport static com.google.common.net.HttpHeaders.ACCEPT;\nimport static jakarta.ws.rs.HttpMethod.DELETE;\nimport static jakarta.ws.rs.HttpMethod.PUT;\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\nimport static jakarta.ws.rs.core.MediaType.WILDCARD;\nimport static jakarta.ws.rs.core.Response.Status.OK;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.net.URI;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.CloudLoadBalancersApi;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.internal.BaseCloudLoadBalancerApiExpectTest;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class ErrorPageApiExpectTest extends BaseCloudLoadBalancerApiExpectTest<CloudLoadBalancersApi> {\n   public String contentExpected;\n   public String contentEscaped;\n\n   public ErrorPageApiExpectTest() {\n      super();\n\n      contentExpected = getContentExpected();\n      contentEscaped = getContentEscaped();\n   }\n\n   public void testGetErrorPage() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/errorpage\");\n      ErrorPageApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder()\n               .statusCode(OK.getStatusCode())\n               .payload(payloadFromStringWithContentType(\"{\\\"errorpage\\\":{\\\"content\\\":\\\"\" + contentEscaped + \"\\\"}}\", APPLICATION_JSON))\n               .build()\n      ).getErrorPageApi(\"DFW\", 2000);\n\n      String content = api.get();\n      assertEquals(content, contentExpected);\n   }\n\n   public void testCreateErrorPage() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/errorpage\");\n      ErrorPageApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess,\n            authenticatedGET()\n               .method(PUT)\n               .endpoint(endpoint)\n               .replaceHeader(ACCEPT, WILDCARD)\n               .payload(payloadFromStringWithContentType(\"{\\\"errorpage\\\":{\\\"content\\\":\\\"\" + contentEscaped + \"\\\"}}\", APPLICATION_JSON))\n               .build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).build()\n      ).getErrorPageApi(\"DFW\", 2000);\n\n      api.create(contentEscaped);\n   }\n\n   public void testRemoveErrorPage() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/errorpage\");\n      ErrorPageApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess,\n            authenticatedGET().method(DELETE).endpoint(endpoint).replaceHeader(ACCEPT, WILDCARD).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).build()\n      ).getErrorPageApi(\"DFW\", 2000);\n\n      assertTrue(api.delete());\n   }\n\n   public static String getContentExpected() {\n      String contentExpected;\n\n      try {\n         contentExpected = Strings2.toStringAndClose(ErrorPageApiExpectTest.class.getResourceAsStream(\"/errorpage.html\"));\n      }\n      catch (IOException e) {\n         throw new RuntimeException(\"Could not read in /errorpage.html\", e);\n      }\n\n      return contentExpected;\n   }\n\n   public static String getContentEscaped() {\n      String contentEscaped = getContentExpected().replaceAll(\"\\\"\", \"\\\\\\\\\\\"\");\n      contentEscaped = contentEscaped.replaceAll(\"\\n\", \"\\\\\\\\n\");\n\n      return contentEscaped;\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/java/org/jclouds/rackspace/cloudloadbalancers/v1/features/ErrorPageApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.features;\n\nimport static org.jclouds.rackspace.cloudloadbalancers.v1.predicates.LoadBalancerPredicates.awaitAvailable;\nimport static org.jclouds.rackspace.cloudloadbalancers.v1.predicates.LoadBalancerPredicates.awaitDeleted;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.LoadBalancer;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.CreateLoadBalancer;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.AddNode;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.VirtualIP.Type;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.internal.BaseCloudLoadBalancersApiLiveTest;\nimport org.testng.annotations.AfterGroups;\nimport org.testng.annotations.BeforeGroups;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Iterables;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"ErrorPageApiLiveTest\")\npublic class ErrorPageApiLiveTest extends BaseCloudLoadBalancersApiLiveTest {\n   private LoadBalancer lb;\n   private String region;\n   private String contentExpected;\n   private String contentEscaped;\n\n   @Override\n   @BeforeGroups(groups = { \"live\" })\n   public void setup() {\n      super.setup();\n\n      contentExpected = ErrorPageApiExpectTest.getContentExpected();\n      contentEscaped = ErrorPageApiExpectTest.getContentEscaped();\n   }\n\n   public void testCreateLoadBalancer() {\n      AddNode addNode = AddNode.builder().address(\"192.168.1.1\").port(8080).build();\n      CreateLoadBalancer createLB = CreateLoadBalancer.builder()\n            .name(prefix + \"-jclouds\").protocol(\"HTTP\").port(80).virtualIPType(Type.PUBLIC).node(addNode).build();\n\n      region = Iterables.getFirst(api.getConfiguredRegions(), null);\n      lb = api.getLoadBalancerApi(region).create(createLB);\n\n      assertTrue(awaitAvailable(api.getLoadBalancerApi(region)).apply(lb));\n   }\n\n   @Test(dependsOnMethods = \"testCreateLoadBalancer\")\n   public void testCreateAndGetErrorPage() throws Exception {\n      api.getErrorPageApi(region, lb.getId()).create(contentEscaped);\n      assertTrue(awaitAvailable(api.getLoadBalancerApi(region)).apply(lb));\n\n      String content = api.getErrorPageApi(region, lb.getId()).get();\n\n      assertEquals(content, contentExpected);\n   }\n\n   @Test(dependsOnMethods = \"testCreateAndGetErrorPage\")\n   public void testRemoveAndGetErrorPage() throws Exception {\n      assertTrue(api.getErrorPageApi(region, lb.getId()).delete());\n      assertTrue(awaitAvailable(api.getLoadBalancerApi(region)).apply(lb));\n\n      String content = api.getErrorPageApi(region, lb.getId()).get();\n\n      assertTrue(content.contains(\"Service Unavailable\"));\n   }\n\n   @Override\n   @AfterGroups(groups = \"live\")\n   protected void tearDown() {\n      assertTrue(awaitAvailable(api.getLoadBalancerApi(region)).apply(lb));\n      api.getLoadBalancerApi(region).delete(lb.getId());\n      assertTrue(awaitDeleted(api.getLoadBalancerApi(region)).apply(lb));\n      super.tearDown();\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/java/org/jclouds/rackspace/cloudloadbalancers/v1/features/HealthMonitorApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.features;\nimport static com.google.common.net.HttpHeaders.ACCEPT;\nimport static jakarta.ws.rs.HttpMethod.DELETE;\nimport static jakarta.ws.rs.HttpMethod.PUT;\nimport static jakarta.ws.rs.core.MediaType.WILDCARD;\nimport static jakarta.ws.rs.core.Response.Status.OK;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.CloudLoadBalancersApi;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.HealthMonitor;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.internal.BaseCloudLoadBalancerApiExpectTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class HealthMonitorApiExpectTest extends BaseCloudLoadBalancerApiExpectTest<CloudLoadBalancersApi> {\n   public void testGetHealthMonitor() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/healthmonitor\");\n      HealthMonitorApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/healthmonitor-get.json\")).build()\n      ).getHealthMonitorApi(\"DFW\", 2000);\n\n      HealthMonitor healthMonitor = api.get();\n      assertEquals(healthMonitor, getConnectHealthMonitor());\n   }\n\n   public void testGetDeletedHealthMonitor() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/healthmonitor\");\n      HealthMonitorApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/healthmonitor-get-deleted.json\")).build()\n      ).getHealthMonitorApi(\"DFW\", 2000);\n\n      HealthMonitor healthMonitor = api.get();\n      assertNull(healthMonitor);\n   }\n\n   public void testCreateHealthMonitor() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/healthmonitor\");\n      HealthMonitorApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess,\n            authenticatedGET().method(PUT).endpoint(endpoint).payload(payloadFromResource(\"/healthmonitor-create.json\")).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).build()\n      ).getHealthMonitorApi(\"DFW\", 2000);\n\n      api.createOrUpdate(getConnectHealthMonitor());\n   }\n\n   public void testRemoveHealthMonitor() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/healthmonitor\");\n      HealthMonitorApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess,\n            authenticatedGET().method(DELETE).endpoint(endpoint).replaceHeader(ACCEPT, WILDCARD).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).build()\n      ).getHealthMonitorApi(\"DFW\", 2000);\n\n      assertTrue(api.delete());\n   }\n\n   public void testValidConnectHealthMonitor() {\n      assertTrue(getConnectHealthMonitor().isValid());\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testInvalidConnectHealthMonitorWithoutRequirements() {\n      HealthMonitor.builder().type(HealthMonitor.Type.CONNECT).build();\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testInvalidConnectHealthMonitorWithUnrequired() {\n      HealthMonitor.builder()\n            .type(HealthMonitor.Type.CONNECT)\n            .delay(3599)\n            .timeout(30)\n            .attemptsBeforeDeactivation(2)\n            .path(\"/foobar\")\n            .build();\n   }\n\n   public void testValidHTTPHealthMonitor() {\n      assertTrue(getHTTPHealthMonitor().isValid());\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testInvalidHTTPHealthMonitorWithoutRequirements() {\n      HealthMonitor.builder().type(HealthMonitor.Type.HTTP).build();\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testInvalidHTTPHealthMonitorWithoutUnrequired() {\n      HealthMonitor.builder()\n            .type(HealthMonitor.Type.HTTP)\n            .delay(3599)\n            .path(\"/foobar\")\n            .build();\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testInvalidHTTPHealthMonitorWithoutRegex() {\n      HealthMonitor.builder()\n      .type(HealthMonitor.Type.HTTP)\n      .delay(3599)\n      .timeout(30)\n      .attemptsBeforeDeactivation(2)\n      .path(\"/foobar\")\n      .build();\n   }\n\n   public static HealthMonitor getConnectHealthMonitor() {\n      HealthMonitor healthMonitor = HealthMonitor.builder()\n            .type(HealthMonitor.Type.CONNECT)\n            .delay(3599)\n            .timeout(30)\n            .attemptsBeforeDeactivation(2)\n            .build();\n\n      return healthMonitor;\n   }\n\n   public static HealthMonitor getHTTPHealthMonitor() {\n      HealthMonitor healthMonitor = HealthMonitor.builder()\n            .type(HealthMonitor.Type.HTTP)\n            .delay(3599)\n            .timeout(30)\n            .attemptsBeforeDeactivation(2)\n            .path(\"/foobar\")\n            .bodyRegex(\"foo.*bar\")\n            .build();\n\n      return healthMonitor;\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/java/org/jclouds/rackspace/cloudloadbalancers/v1/features/HealthMonitorApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.features;\n\nimport static org.jclouds.rackspace.cloudloadbalancers.v1.predicates.LoadBalancerPredicates.awaitAvailable;\nimport static org.jclouds.rackspace.cloudloadbalancers.v1.predicates.LoadBalancerPredicates.awaitDeleted;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.HealthMonitor;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.LoadBalancer;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.CreateLoadBalancer;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.AddNode;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.VirtualIP.Type;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.internal.BaseCloudLoadBalancersApiLiveTest;\nimport org.testng.annotations.AfterGroups;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Iterables;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"HealthMonitorApiLiveTest\")\npublic class HealthMonitorApiLiveTest extends BaseCloudLoadBalancersApiLiveTest {\n   private LoadBalancer lb;\n   private String region;\n\n   public void testCreateLoadBalancer() {\n      AddNode addNode = AddNode.builder().address(\"192.168.1.1\").port(8080).build();\n      CreateLoadBalancer createLB = CreateLoadBalancer.builder()\n            .name(prefix + \"-jclouds\").protocol(\"HTTP\").port(80).virtualIPType(Type.PUBLIC).node(addNode).build();\n\n      region = Iterables.getFirst(api.getConfiguredRegions(), null);\n      lb = api.getLoadBalancerApi(region).create(createLB);\n\n      assertTrue(awaitAvailable(api.getLoadBalancerApi(region)).apply(lb));\n   }\n\n   @Test(dependsOnMethods = \"testCreateLoadBalancer\")\n   public void testCreateAndGetHealthMonitor() throws Exception {\n      api.getHealthMonitorApi(region, lb.getId()).createOrUpdate(\n            HealthMonitorApiExpectTest.getConnectHealthMonitor());\n      assertTrue(awaitAvailable(api.getLoadBalancerApi(region)).apply(lb));\n\n      HealthMonitor healthMonitor =\n            api.getHealthMonitorApi(region, lb.getId()).get();\n\n      assertEquals(healthMonitor, HealthMonitorApiExpectTest.getConnectHealthMonitor());\n   }\n\n   @Test(dependsOnMethods = \"testCreateAndGetHealthMonitor\")\n   public void testRemoveAndGetHealthMonitor() throws Exception {\n      assertTrue(api.getHealthMonitorApi(region, lb.getId()).delete());\n      assertTrue(awaitAvailable(api.getLoadBalancerApi(region)).apply(lb));\n\n      HealthMonitor healthMonitor =\n            api.getHealthMonitorApi(region, lb.getId()).get();\n\n      assertNull(healthMonitor);\n   }\n\n   @Override\n   @AfterGroups(groups = \"live\")\n   protected void tearDown() {\n      assertTrue(awaitAvailable(api.getLoadBalancerApi(region)).apply(lb));\n      api.getLoadBalancerApi(region).delete(lb.getId());\n      assertTrue(awaitDeleted(api.getLoadBalancerApi(region)).apply(lb));\n      super.tearDown();\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/java/org/jclouds/rackspace/cloudloadbalancers/v1/features/LoadBalancerApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.features;\nimport static com.google.common.net.HttpHeaders.ACCEPT;\nimport static jakarta.ws.rs.HttpMethod.DELETE;\nimport static jakarta.ws.rs.HttpMethod.POST;\nimport static jakarta.ws.rs.HttpMethod.PUT;\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\nimport static jakarta.ws.rs.core.MediaType.WILDCARD;\nimport static jakarta.ws.rs.core.Response.Status.ACCEPTED;\nimport static jakarta.ws.rs.core.Response.Status.OK;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.Set;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.CloudLoadBalancersApi;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.AddNode;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.CreateLoadBalancer;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.LoadBalancer;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.Metadata;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.Node;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.UpdateLoadBalancer;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.VirtualIP;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.functions.ParseLoadBalancerTest;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.functions.ParseLoadBalancersTest;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.internal.BaseCloudLoadBalancerApiExpectTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Sets;\n\n@Test(groups = \"unit\")\npublic class LoadBalancerApiExpectTest extends BaseCloudLoadBalancerApiExpectTest<CloudLoadBalancersApi> {\n\n   public void testListLoadBalancers() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers\");\n      LoadBalancerApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess, \n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/loadbalancers-list.json\")).build()\n      ).getLoadBalancerApi(\"DFW\");\n\n      Set<LoadBalancer> loadBalancers = api.list().concat().toSet();\n      assertEquals(loadBalancers, getExpectedLoadBalancers());\n   }\n\n   public void testGetLoadBalancer() throws Exception {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000\");\n      LoadBalancerApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess, \n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/loadbalancer-get.json\")).build()\n      ).getLoadBalancerApi(\"DFW\");\n\n      LoadBalancer loadBalancer = api.get(2000);\n      assertEquals(loadBalancer, getExpectedLoadBalancer());\n   }\n\n   public void testCreateLoadBalancer() throws Exception {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers\");\n      LoadBalancerApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess, \n            authenticatedGET()\n                  .method(POST)\n                  .payload(payloadFromResource(\"/loadbalancer-create.json\"))\n                  .endpoint(endpoint)\n                  .build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/loadbalancer-get.json\")).build()\n      ).getLoadBalancerApi(\"DFW\");\n\n      AddNode addNode1 = AddNode.builder()\n            .address(\"10.1.1.1\")\n            .condition(Node.Condition.ENABLED)\n            .port(80)\n            .build();\n      \n      AddNode addNode2 = AddNode.builder()\n            .address(\"10.1.1.2\")\n            .condition(Node.Condition.ENABLED)\n            .port(80)\n            .build();\n      \n      Set<AddNode> addNodes = Sets.newHashSet(addNode1, addNode2);\n\n      CreateLoadBalancer createLB = CreateLoadBalancer.builder()\n            .name(\"sample-loadbalancer\")\n            .protocol(\"HTTP\")\n            .port(80)\n            .algorithm(LoadBalancer.Algorithm.RANDOM)\n            .virtualIPType(VirtualIP.Type.PUBLIC)\n            .nodes(addNodes)\n            .build();\n      \n      LoadBalancer loadBalancer = api.create(createLB);\n      \n      assertEquals(loadBalancer, getExpectedLoadBalancer());\n   }\n\n   public void testUpdateLoadBalancerAttributes() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000\");\n      LoadBalancerApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess, \n            authenticatedGET().method(PUT).payload(payloadFromResource(\"/loadbalancer-update.json\")).endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(ACCEPTED.getStatusCode()).payload(\"\").build()\n      ).getLoadBalancerApi(\"DFW\");\n\n      UpdateLoadBalancer updateLB = UpdateLoadBalancer.builder()\n            .name(\"foo\")\n            .protocol(\"HTTPS\")\n            .port(443)\n            .algorithm(LoadBalancer.Algorithm.RANDOM)\n            .build();\n\n      api.update(2000, updateLB);\n   }\n\n   public void testRemoveLoadBalancer() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000\");\n      LoadBalancerApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess, \n            authenticatedGET()\n                  .method(DELETE)\n                  .replaceHeader(ACCEPT, WILDCARD)\n                  .endpoint(endpoint)\n                  .build(),\n            HttpResponse.builder().statusCode(ACCEPTED.getStatusCode()).payload(\"\").build()\n      ).getLoadBalancerApi(\"DFW\");\n      \n      api.delete(2000);\n   }\n\n   public void testListMetadata() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/metadata\");\n      LoadBalancerApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess, \n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/metadata-list.json\")).build()\n      ).getLoadBalancerApi(\"DFW\");\n\n      Metadata metadata = api.getMetadata(2000);\n      assertEquals(metadata, getExpectedMetadataWithIds());\n   }\n\n   public void testCreateMetadata() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/metadata\");\n      LoadBalancerApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess, \n            authenticatedGET()\n               .method(POST)\n               .endpoint(endpoint)\n               .payload(payloadFromResourceWithContentType(\"/metadata-create.json\", APPLICATION_JSON)).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/metadata-list.json\")).build()\n      ).getLoadBalancerApi(\"DFW\");\n         \n      Metadata metadata = api.createMetadata(2000, getExpectedMetadata());\n      assertEquals(metadata, getExpectedMetadataWithIds());\n   }\n\n   public void testRemoveSingleMetadata() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/metadata/23\");\n      LoadBalancerApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess, \n            authenticatedGET().method(DELETE).endpoint(endpoint).replaceHeader(ACCEPT, WILDCARD).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).build()\n      ).getLoadBalancerApi(\"DFW\");\n\n      assertTrue(api.deleteMetadatum(2000, 23));\n   }\n\n   public void testRemoveManyMetadata() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/metadata?id=23&id=24\");\n      LoadBalancerApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess, \n            authenticatedGET().method(DELETE).endpoint(endpoint).replaceHeader(ACCEPT, WILDCARD).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).build()\n      ).getLoadBalancerApi(\"DFW\");\n      \n      \n      \n      assertTrue(api.deleteMetadata(2000, ImmutableList.<Integer> of(23, 24)));\n   }\n\n   private Object getExpectedLoadBalancer() {\n      return new ParseLoadBalancerTest().expected();\n   }\n\n   private Set<LoadBalancer> getExpectedLoadBalancers() {      \n      return new ParseLoadBalancersTest().data();\n   }   \n\n   private Metadata getExpectedMetadata() {\n      Metadata metadata = new Metadata();\n      metadata.put(\"os\", \"ubuntu\");\n      metadata.put(\"color\", \"red\");\n      metadata.put(\"label\", \"web-load-balancer\");\n\n      return metadata;\n   }\n\n   private Metadata getExpectedMetadataWithIds() {\n      Metadata metadata = getExpectedMetadata();\n      metadata.putId(\"color\", 1);\n      metadata.putId(\"label\", 2);\n      metadata.putId(\"os\", 3);\n\n      return metadata;\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/java/org/jclouds/rackspace/cloudloadbalancers/v1/features/LoadBalancerApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.features;\n\nimport static org.jclouds.rackspace.cloudloadbalancers.v1.predicates.LoadBalancerPredicates.awaitAvailable;\nimport static org.jclouds.rackspace.cloudloadbalancers.v1.predicates.LoadBalancerPredicates.awaitDeleted;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.logging.Logger;\n\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.LoadBalancer;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.UpdateLoadBalancer;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.CreateLoadBalancer;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.Metadata;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.AddNode;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.VirtualIP.Type;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.internal.BaseCloudLoadBalancersApiLiveTest;\nimport org.testng.annotations.AfterGroups;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Sets;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"LoadBalancerApiLiveTest\")\npublic class LoadBalancerApiLiveTest extends BaseCloudLoadBalancersApiLiveTest {\n   private Set<LoadBalancer> lbs = Sets.newLinkedHashSet();\n\n   @Override\n   @AfterGroups(groups = \"live\")\n   protected void tearDown() {\n      for (LoadBalancer lb : lbs) {\n         assertTrue(awaitAvailable(api.getLoadBalancerApi(lb.getRegion())).apply(lb));\n         api.getLoadBalancerApi(lb.getRegion()).delete(lb.getId());\n         assertTrue(awaitDeleted(api.getLoadBalancerApi(lb.getRegion())).apply(lb));\n      }\n      super.tearDown();\n   }\n\n   public void testCreateLoadBalancer() throws Exception {\n      for (String region : api.getConfiguredRegions()) {\n         Logger.getAnonymousLogger().info(\"starting lb in region \" + region);\n\n         LoadBalancer lb = api.getLoadBalancerApi(region).create(\n               CreateLoadBalancer.builder()\n                     .name(prefix + \"-\" + region)\n                     .protocol(\"HTTP\")\n                     .port(80)\n                     .virtualIPType(Type.PUBLIC)\n                     .node(AddNode.builder()\n                           .address(\"192.168.1.1\")\n                           .port(8080)\n                           .build())\n                     .build());\n         checkLBInRegion(region, lb, prefix + \"-\" + region);\n\n         assertEquals(lb.getStatus(), LoadBalancer.Status.BUILD);\n\n         lbs.add(lb);\n\n         assertTrue(awaitAvailable(api.getLoadBalancerApi(lb.getRegion())).apply(lb));\n\n         LoadBalancer newLb = api.getLoadBalancerApi(region).get(lb.getId());\n         checkLBInRegion(region, newLb, prefix + \"-\" + region);\n\n         assertEquals(newLb.getStatus(), LoadBalancer.Status.ACTIVE);\n      }\n   }\n\n   @Test(dependsOnMethods = \"testCreateLoadBalancer\")\n   public void testUpdateLoadBalancer() throws Exception {\n      for (LoadBalancer lb : lbs) {\n         api.getLoadBalancerApi(lb.getRegion()).update(lb.getId(),\n               UpdateLoadBalancer.builder().name(\"foo\" + \"-\" + lb.getRegion()).build());\n\n         assertTrue(awaitAvailable(api.getLoadBalancerApi(lb.getRegion())).apply(lb));\n\n         LoadBalancer newLb = api.getLoadBalancerApi(lb.getRegion()).get(lb.getId());\n         checkLBInRegion(newLb.getRegion(), newLb, \"foo\" + \"-\" + lb.getRegion());\n\n         assertEquals(newLb.getStatus(), LoadBalancer.Status.ACTIVE);\n      }\n   }\n\n   @Test(dependsOnMethods = \"testUpdateLoadBalancer\")\n   public void testListLoadBalancers() throws Exception {\n      for (String region : api.getConfiguredRegions()) {\n\n         Set<LoadBalancer> response = api.getLoadBalancerApi(region).list().concat().toSet();\n\n         assertNotNull(response);\n         assertTrue(response.size() > 0);\n\n         for (LoadBalancer lb : response) {\n            if (!lbs.contains(lb))\n               continue;\n            assert lb.getRegion() != null : lb;\n            assert lb.getName() != null : lb;\n            assert lb.getId() != -1 : lb;\n            assert lb.getProtocol() != null : lb;\n            assert lb.getPort() != -1 : lb;\n            assert lb.getStatus() != null : lb;\n            assert lb.getCreated() != null : lb;\n            assert lb.getUpdated() != null : lb;\n            assert !lb.getVirtualIPs().isEmpty() : lb;\n            // node info not available during list;\n            assert lb.getNodes().size() == 0 : lb;\n\n            LoadBalancer getDetails = api.getLoadBalancerApi(region).get(lb.getId());\n\n            try {\n               assertEquals(getDetails.getRegion(), lb.getRegion());\n               assertEquals(getDetails.getName(), lb.getName());\n               assertEquals(getDetails.getId(), lb.getId());\n               assertEquals(getDetails.getProtocol(), lb.getProtocol());\n               assertEquals(getDetails.getPort(), lb.getPort());\n               assertEquals(getDetails.getStatus(), lb.getStatus());\n               assertEquals(getDetails.getCreated(), lb.getCreated());\n               assertEquals(getDetails.getUpdated(), lb.getUpdated());\n               assertEquals(getDetails.getVirtualIPs(), lb.getVirtualIPs());\n               // node info not available during list;\n               assert !getDetails.getNodes().isEmpty() : lb;\n            } catch (AssertionError e) {\n               throw new AssertionError(String.format(\"%s\\n%s - %s\", e.getMessage(), getDetails, lb));\n            }\n         }\n      }\n   }\n\n   @Test(dependsOnMethods = \"testListLoadBalancers\")\n   public void testLoadBalancerMetadata() throws Exception {\n      for (LoadBalancer lb : lbs) {\n         Map<String, String> metadataMap = ImmutableMap.<String, String> of(\n               \"key1\", \"value1\",\n               \"key2\", \"value2\",\n               \"key3\", \"value3\");\n\n         Metadata metadata = api.getLoadBalancerApi(lb.getRegion()).createMetadata(lb.getId(), metadataMap);\n         assertEquals(metadata, getExpectedMetadata());\n         assertTrue(awaitAvailable(api.getLoadBalancerApi(lb.getRegion())).apply(lb));\n\n         metadata = api.getLoadBalancerApi(lb.getRegion()).getMetadata(lb.getId());\n         assertEquals(metadata, getExpectedMetadata());\n\n         assertTrue(api.getLoadBalancerApi(lb.getRegion()).updateMetadatum(lb.getId(), metadata.getId(\"key1\"), \"key1-updated\"));\n         assertTrue(awaitAvailable(api.getLoadBalancerApi(lb.getRegion())).apply(lb));\n         metadata = api.getLoadBalancerApi(lb.getRegion()).getMetadata(lb.getId());\n         assertEquals(metadata.get(\"key1\"), \"key1-updated\");\n\n         assertTrue(api.getLoadBalancerApi(lb.getRegion()).deleteMetadatum(lb.getId(), metadata.getId(\"key1\")));\n         assertTrue(awaitAvailable(api.getLoadBalancerApi(lb.getRegion())).apply(lb));\n         metadata = api.getLoadBalancerApi(lb.getRegion()).getMetadata(lb.getId());\n         assertNull(metadata.get(\"key1\"));\n\n         assertTrue(api.getLoadBalancerApi(lb.getRegion()).deleteMetadata(lb.getId(),\n               ImmutableList.<Integer> of(metadata.getId(\"key2\"), metadata.getId(\"key3\"))));\n         assertTrue(awaitAvailable(api.getLoadBalancerApi(lb.getRegion())).apply(lb));\n         metadata = api.getLoadBalancerApi(lb.getRegion()).getMetadata(lb.getId());\n         assertEquals(metadata.size(), 0);\n      }\n   }\n\n   private void checkLBInRegion(String region, LoadBalancer lb, String name) {\n      assertEquals(lb.getRegion(), region);\n      assertEquals(lb.getName(), name);\n      assertEquals(lb.getProtocol(), \"HTTP\");\n      assertEquals(lb.getPort(), Integer.valueOf(80));\n      assertEquals(Iterables.get(lb.getVirtualIPs(), 0).getType(), Type.PUBLIC);\n   }\n\n   private Metadata getExpectedMetadata() {\n      Metadata metadata = new Metadata();\n      metadata.put(\"key1\", \"value1\");\n      metadata.put(\"key2\", \"value2\");\n      metadata.put(\"key3\", \"value3\");\n\n      return metadata;\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/java/org/jclouds/rackspace/cloudloadbalancers/v1/features/NodeApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.features;\nimport static com.google.common.net.HttpHeaders.ACCEPT;\nimport static jakarta.ws.rs.HttpMethod.DELETE;\nimport static jakarta.ws.rs.HttpMethod.POST;\nimport static jakarta.ws.rs.HttpMethod.PUT;\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\nimport static jakarta.ws.rs.core.MediaType.WILDCARD;\nimport static jakarta.ws.rs.core.Response.Status.OK;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.Set;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.CloudLoadBalancersApi;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.AddNode;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.Metadata;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.Node;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.UpdateNode;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.internal.BaseCloudLoadBalancerApiExpectTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSortedSet;\n\n@Test(groups = \"unit\")\npublic class NodeApiExpectTest extends BaseCloudLoadBalancerApiExpectTest<CloudLoadBalancersApi> {\n   public void testListNodes() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/nodes\");\n      NodeApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess, \n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/nodes-list.json\")).build()\n      ).getNodeApi(\"DFW\", 2000);\n\n      Set<Node> nodes = api.list().concat().toSet();\n      assertEquals(nodes, getExpectedNodes());\n   }\n\n   public void testGetNodeInLoadBalancer() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/nodes/410\");\n      NodeApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess, \n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/node-get.json\")).build()\n      ).getNodeApi(\"DFW\", 2000);\n\n      Node node = api.get(410);\n      assertEquals(node, testNode());\n   }\n\n   public void testAddNodesInLoadBalancer() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/nodes\");\n      NodeApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess, \n            authenticatedGET()\n                  .method(POST)\n                  .payload(payloadFromResourceWithContentType(\"/nodes-add.json\", APPLICATION_JSON))\n                  .endpoint(endpoint)\n                  .build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/nodes-list.json\")).build()\n      ).getNodeApi(\"DFW\", 2000);\n\n      AddNode addNode1 = AddNode.builder()\n            .address(\"10.1.1.1\")\n            .condition(Node.Condition.ENABLED)\n            .port(80)\n            .weight(3)\n            .build();\n      \n      AddNode addNode2 = AddNode.builder()\n            .address(\"10.1.1.2\")\n            .condition(Node.Condition.ENABLED)\n            .type(Node.Type.SECONDARY)\n            .port(80)\n            .weight(8)\n            .build();\n\n      AddNode addNode3 = AddNode.builder()\n            .address(\"10.1.1.3\")\n            .condition(Node.Condition.DISABLED)\n            .port(80)\n            .weight(12)\n            .build();\n\n      Set<AddNode> addNodes = ImmutableSortedSet.<AddNode> of(addNode1, addNode2, addNode3);\n      \n      Set<Node> nodes = api.add(addNodes);\n      assertEquals(nodes, getExpectedNodes());\n   }\n\n   public void testUpdateAttributesForNodeInLoadBalancer() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/nodes/410\");\n      NodeApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess, \n            authenticatedGET().method(PUT).payload(payloadFromResource(\"/node-update.json\")).endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).build()\n      ).getNodeApi(\"DFW\", 2000);\n\n      UpdateNode updateNode = UpdateNode.builder()\n            .condition(Node.Condition.DISABLED)\n            .type(Node.Type.SECONDARY)\n            .weight(20)\n            .build();\n\n      api.update(410, updateNode);\n   }\n\n   public void testRemoveNodeFromLoadBalancer() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/nodes/410\");\n      NodeApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess, \n            authenticatedGET().method(DELETE).replaceHeader(ACCEPT, WILDCARD).endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).build()\n      ).getNodeApi(\"DFW\", 2000);\n\n      api.remove(410);\n   }\n\n   public void testRemoveNodesFromLoadBalancer() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/nodes?id=410&id=411\");\n      NodeApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess, \n            authenticatedGET().method(DELETE).replaceHeader(ACCEPT, WILDCARD).endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).build()\n      ).getNodeApi(\"DFW\", 2000);\n      \n      Set<Integer> nodeIds = ImmutableSortedSet.<Integer> of(410, 411);\n\n      api.remove(nodeIds);\n   }\n\n   public void testListMetadata() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/nodes/410/metadata\");\n      NodeApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess, \n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/metadata-list.json\")).build()\n      ).getNodeApi(\"DFW\", 2000);\n\n      Metadata metadata = api.getMetadata(410);\n      assertEquals(metadata, getExpectedMetadataWithIds());\n   }\n\n   public void testCreateMetadata() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/nodes/410/metadata\");\n      NodeApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess, \n            authenticatedGET()\n               .method(POST)\n               .endpoint(endpoint)\n               .payload(payloadFromResourceWithContentType(\"/metadata-create.json\", APPLICATION_JSON)).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/metadata-list.json\")).build()\n      ).getNodeApi(\"DFW\", 2000);\n         \n      Metadata metadata = api.createMetadata(410, getExpectedMetadata());\n      assertEquals(metadata, getExpectedMetadataWithIds());\n   }\n\n   public void testRemoveSingleMetadata() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/nodes/410/metadata/23\");\n      NodeApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess, \n            authenticatedGET().method(DELETE).endpoint(endpoint).replaceHeader(ACCEPT, WILDCARD).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).build()\n      ).getNodeApi(\"DFW\", 2000);\n\n      assertTrue(api.deleteMetadatum(410, 23));\n   }\n\n   public void testRemoveManyMetadata() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/nodes/410/metadata?id=23&id=24\");\n      NodeApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess, \n            authenticatedGET().method(DELETE).endpoint(endpoint).replaceHeader(ACCEPT, WILDCARD).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).build()\n      ).getNodeApi(\"DFW\", 2000);\n      \n      \n      \n      assertTrue(api.deleteMetadata(410, ImmutableList.<Integer> of(23, 24)));\n   }\n\n   private Metadata getExpectedMetadata() {\n      Metadata metadata = new Metadata();\n      metadata.put(\"os\", \"ubuntu\");\n      metadata.put(\"color\", \"red\");\n      metadata.put(\"label\", \"web-load-balancer\");\n\n      return metadata;\n   }\n\n   private Metadata getExpectedMetadataWithIds() {\n      Metadata metadata = getExpectedMetadata();\n      metadata.putId(\"color\", 1);\n      metadata.putId(\"label\", 2);\n      metadata.putId(\"os\", 3);\n\n      return metadata;\n   }\n\n   private Set<Node> getExpectedNodes() {\n      Node node1 = Node.builder()\n            .id(410)\n            .address(\"10.1.1.1\")\n            .port(80)\n            .condition(Node.Condition.ENABLED)\n            .type(Node.Type.PRIMARY)\n            .status(Node.Status.ONLINE)\n            .weight(3)\n            .build();\n\n      Node node2 = Node.builder()\n            .id(411)\n            .address(\"10.1.1.2\")\n            .port(80)\n            .condition(Node.Condition.ENABLED)\n            .type(Node.Type.SECONDARY)\n            .status(Node.Status.ONLINE)\n            .weight(8)\n            .build();\n\n      Node node3 = Node.builder()\n            .id(412)\n            .address(\"10.1.1.3\")\n            .port(80)\n            .condition(Node.Condition.DISABLED)\n            .type(Node.Type.PRIMARY)\n            .status(Node.Status.ONLINE)\n            .weight(12)\n            .build();\n\n      return ImmutableSet.<Node> of(node1, node2, node3);\n   }\n   \n   private Node testNode() {\n      return Node.builder()\n            .id(410)\n            .address(\"10.1.1.1\")\n            .port(80)\n            .condition(Node.Condition.ENABLED)\n            .type(Node.Type.PRIMARY)\n            .status(Node.Status.ONLINE)\n            .weight(12)\n            .build();\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/java/org/jclouds/rackspace/cloudloadbalancers/v1/features/NodeApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.features;\n\nimport static org.jclouds.rackspace.cloudloadbalancers.v1.predicates.LoadBalancerPredicates.awaitAvailable;\nimport static org.jclouds.rackspace.cloudloadbalancers.v1.predicates.LoadBalancerPredicates.awaitDeleted;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.HashSet;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.Map.Entry;\nimport java.util.logging.Logger;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Maps;\n\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.LoadBalancer;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.CreateLoadBalancer;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.Metadata;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.Node;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.UpdateNode;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.AddNode;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.LoadBalancer.Status;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.VirtualIP.Type;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.internal.BaseCloudLoadBalancersApiLiveTest;\nimport org.testng.annotations.AfterGroups;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"NodeClientLiveTest\")\npublic class NodeApiLiveTest extends BaseCloudLoadBalancersApiLiveTest {\n   private Map<LoadBalancer, Set<Node>> nodes = Maps.newHashMap();\n\n   public void testCreateLoadBalancers() {\n      assertTrue(!api.getConfiguredRegions().isEmpty(), \"Need to have some regions!\");\n      Logger.getAnonymousLogger().info(\"running against regions \" + api.getConfiguredRegions());\n      for (String region : api.getConfiguredRegions()) {\n         Logger.getAnonymousLogger().info(\"starting lb in region \" + region);\n         LoadBalancer lb = api.getLoadBalancerApi(region).create(\n                  CreateLoadBalancer.builder().name(prefix + \"-\" + region).protocol(\"HTTP\").port(80).virtualIPType(\n                           Type.PUBLIC).node(AddNode.builder().address(\"192.168.1.1\").port(8080).build()).build());\n         nodes.put(lb, new HashSet<Node>());\n\n         assertTrue(awaitAvailable(api.getLoadBalancerApi(lb.getRegion())).apply(lb));\n      }\n   }\n\n   @Test(dependsOnMethods = \"testCreateLoadBalancers\")\n   public void testAddNodes() throws Exception {\n      for (Map.Entry<LoadBalancer, Set<Node>> entry : nodes.entrySet()) {\n         LoadBalancer lb = entry.getKey();\n         Set<Node> nodeSet = entry.getValue();\n         String region = lb.getRegion();\n         Logger.getAnonymousLogger().info(\"starting node on loadbalancer \" + lb.getId() + \" in region \" + region);\n         Set<Node> newNodes = api.getNodeApi(region, lb.getId()).add(\n                  ImmutableSet.<AddNode> of(AddNode.builder().address(\"192.168.1.2\").port(8080).build()));\n\n         for (Node n : newNodes) {\n            assertEquals(n.getStatus(), Node.Status.ONLINE);\n            nodeSet.add(n);\n            assertEquals(api.getNodeApi(region, lb.getId()).get(n.getId()).getStatus(),\n                     Node.Status.ONLINE);\n         }\n\n         assertTrue(awaitAvailable(api.getLoadBalancerApi(lb.getRegion())).apply(lb));\n      }\n   }\n\n   @Test(dependsOnMethods = \"testAddNodes\")\n   public void testModifyNode() throws Exception {\n      for (Entry<LoadBalancer, Set<Node>> entry : nodes.entrySet()) {\n         for (Node n : entry.getValue()) {\n            String region = entry.getKey().getRegion();\n            api.getNodeApi(region, entry.getKey().getId()).update(n.getId(),\n                     UpdateNode.builder().weight(23).build());\n            assertEquals(api.getNodeApi(region, entry.getKey().getId()).get(n.getId())\n                     .getStatus(), Node.Status.ONLINE);\n\n            Node newNode = api.getNodeApi(region, entry.getKey().getId()).get(n.getId());\n            assertEquals(newNode.getStatus(), Node.Status.ONLINE);\n            assertEquals(newNode.getWeight(), (Integer) 23);\n         }\n      }\n   }\n\n   @Test(dependsOnMethods = \"testModifyNode\")\n   public void testListNodes() throws Exception {\n      for (LoadBalancer lb : nodes.keySet()) {\n         Set<Node> response = api.getNodeApi(lb.getRegion(), lb.getId()).list().concat().toSet();\n         assert null != response;\n         assertTrue(response.size() > 0);\n         for (Node n : response) {\n            assert n.getId() != -1 : n;\n            assert n.getCondition() != null : n;\n            assert n.getAddress() != null : n;\n            assert n.getPort() != -1 : n;\n            assert n.getStatus() != null : n;\n            assert !LoadBalancer.WEIGHTED_ALGORITHMS.contains(lb.getAlgorithm())\n                     || n.getWeight() != null : n;\n\n            Node getDetails = api.getNodeApi(lb.getRegion(), lb.getId()).get(n.getId());\n\n            try {\n               assertEquals(getDetails.getId(), n.getId());\n               assertEquals(getDetails.getCondition(), n.getCondition());\n               assertEquals(getDetails.getAddress(), n.getAddress());\n               assertEquals(getDetails.getPort(), n.getPort());\n               assertEquals(getDetails.getStatus(), n.getStatus());\n               if (LoadBalancer.WEIGHTED_ALGORITHMS.contains(lb.getAlgorithm())) {\n                  assertEquals(getDetails.getWeight(), n.getWeight());\n               }\n            } catch (AssertionError e) {\n               throw new AssertionError(String.format(\"%s\\n%s - %s\", e.getMessage(), getDetails, n));\n            }\n         }\n      }\n   }\n\n   @Test(dependsOnMethods = \"testListNodes\")\n   public void testNodeMetadata() throws Exception {\n      for (Entry<LoadBalancer, Set<Node>> entry : nodes.entrySet()) {\n         LoadBalancer lb = entry.getKey();\n         Node node = entry.getValue().iterator().next();\n         Map<String, String> metadataMap = ImmutableMap.<String, String> of(\n               \"key1\", \"value1\",\n               \"key2\", \"value2\",\n               \"key3\", \"value3\");\n\n         Metadata metadata = api.getNodeApi(lb.getRegion(), lb.getId()).createMetadata(node.getId(), metadataMap);\n         assertEquals(metadata, getExpectedMetadata());\n         assertTrue(awaitAvailable(api.getLoadBalancerApi(lb.getRegion())).apply(lb));\n\n         metadata = api.getNodeApi(lb.getRegion(), lb.getId()).getMetadata(node.getId());\n         assertEquals(metadata, getExpectedMetadata());\n\n         assertTrue(api.getNodeApi(lb.getRegion(), lb.getId()).updateMetadatum(node.getId(), metadata.getId(\"key1\"), \"key1-updated\"));\n         assertTrue(awaitAvailable(api.getLoadBalancerApi(lb.getRegion())).apply(lb));\n         metadata = api.getNodeApi(lb.getRegion(), lb.getId()).getMetadata(node.getId());\n         assertEquals(metadata.get(\"key1\"), \"key1-updated\");\n\n         assertTrue(api.getNodeApi(lb.getRegion(), lb.getId()).deleteMetadatum(node.getId(), metadata.getId(\"key1\")));\n         assertTrue(awaitAvailable(api.getLoadBalancerApi(lb.getRegion())).apply(lb));\n         metadata = api.getNodeApi(lb.getRegion(), lb.getId()).getMetadata(node.getId());\n         assertNull(metadata.get(\"key1\"));\n\n         assertTrue(api.getNodeApi(lb.getRegion(), lb.getId()).deleteMetadata(node.getId(),\n               ImmutableList.<Integer> of(metadata.getId(\"key2\"), metadata.getId(\"key3\"))));\n         assertTrue(awaitAvailable(api.getLoadBalancerApi(lb.getRegion())).apply(lb));\n         metadata = api.getNodeApi(lb.getRegion(), lb.getId()).getMetadata(node.getId());\n         assertEquals(metadata.size(), 0);\n      }\n   }\n\n   @Override\n   @AfterGroups(groups = \"live\")\n   protected void tearDown() {\n      for (Entry<LoadBalancer, Set<Node>> entry : nodes.entrySet()) {\n         LoadBalancer lb = entry.getKey();\n         LoadBalancerApi lbClient = api.getLoadBalancerApi(lb.getRegion());\n\n         if (lbClient.get(lb.getId()).getStatus() != Status.DELETED) {\n            assertTrue(awaitAvailable(api.getLoadBalancerApi(lb.getRegion())).apply(lb));\n            lbClient.delete(lb.getId());\n         }\n         assertTrue(awaitDeleted(api.getLoadBalancerApi(lb.getRegion())).apply(lb));\n      }\n      super.tearDown();\n   }\n\n   private Metadata getExpectedMetadata() {\n      Metadata metadata = new Metadata();\n      metadata.put(\"key1\", \"value1\");\n      metadata.put(\"key2\", \"value2\");\n      metadata.put(\"key3\", \"value3\");\n\n      return metadata;\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/java/org/jclouds/rackspace/cloudloadbalancers/v1/features/ReportApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.features;\nimport static jakarta.ws.rs.core.Response.Status.OK;\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\nimport java.util.Calendar;\nimport java.util.Date;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.CloudLoadBalancersApi;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.HistoricalUsage;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.LoadBalancer;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.LoadBalancerStats;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.LoadBalancerUsage;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.Protocol;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.functions.DateParser;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.internal.BaseCloudLoadBalancerApiExpectTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.Iterables;\n\n@Test(groups = \"unit\")\npublic class ReportApiExpectTest extends BaseCloudLoadBalancerApiExpectTest<CloudLoadBalancersApi> {\n   public void testListBillableLoadBalancers() {\n      Calendar calendar = Calendar.getInstance();\n      calendar.add(Calendar.DATE, -7);\n      Date aWeekAgo = calendar.getTime();\n      Date today = new Date();\n\n      String query = new StringBuilder()\n         .append(\"?startTime=\")\n         .append(new DateParser().apply(aWeekAgo))\n         .append(\"&endTime=\")\n         .append(new DateParser().apply(today))\n         .toString();\n\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/billable\" + query);\n      ReportApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/report-billable-list.json\")).build()\n      ).getReportApi(\"DFW\");\n\n      FluentIterable<LoadBalancer> loadBalancers = api.listBillableLoadBalancers(aWeekAgo, today).concat();\n\n      assertEquals(Iterables.size(loadBalancers), 2);\n   }\n\n   public void testGetHistoricalUsage() {\n      Calendar calendar = Calendar.getInstance();\n      calendar.add(Calendar.DATE, -7);\n      Date aWeekAgo = calendar.getTime();\n      Date today = new Date();\n\n      String query = new StringBuilder()\n         .append(\"?startTime=\")\n         .append(new DateParser().apply(aWeekAgo))\n         .append(\"&endTime=\")\n         .append(new DateParser().apply(today))\n         .toString();\n\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/usage\" + query);\n      ReportApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/report-historical-get.json\")).build()\n      ).getReportApi(\"DFW\");\n\n      HistoricalUsage historicalUsage = api.getHistoricalUsage(aWeekAgo, today);\n\n      assertEquals(historicalUsage.getAccountId(), 717071);\n      assertEquals(Iterables.get(historicalUsage.getAccountUsage(), 0).getNumLoadBalancers(), 2);\n      assertEquals(Iterables.size(historicalUsage.getLoadBalancerInfo()), 2);\n   }\n\n   public void testListLoadBalancerUsage() {\n      Calendar calendar = Calendar.getInstance();\n      calendar.add(Calendar.DATE, -7);\n      Date aWeekAgo = calendar.getTime();\n      Date today = new Date();\n\n      String query = new StringBuilder()\n         .append(\"?startTime=\")\n         .append(new DateParser().apply(aWeekAgo))\n         .append(\"&endTime=\")\n         .append(new DateParser().apply(today))\n         .toString();\n\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/usage\" + query);\n      ReportApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/report-loadbalancerusage-list.json\")).build()\n      ).getReportApi(\"DFW\");\n\n      FluentIterable<LoadBalancerUsage> loadBalancerUsages = api.listLoadBalancerUsage(2000, aWeekAgo, today).concat();\n\n      assertEquals(Iterables.size(loadBalancerUsages), 25);\n   }\n\n   public void testListCurrentLoadBalancerUsage() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/usage/current\");\n      ReportApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/report-loadbalancerusage-list.json\")).build()\n      ).getReportApi(\"DFW\");\n\n      FluentIterable<LoadBalancerUsage> loadBalancerUsages = api.listCurrentLoadBalancerUsage(2000).concat();\n\n      assertEquals(Iterables.size(loadBalancerUsages), 25);\n   }\n\n   public void testGetLoadBalancerStats() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/stats\");\n      ReportApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/report-loadbalancerstats-get.json\")).build()\n      ).getReportApi(\"DFW\");\n\n      LoadBalancerStats loadBalancerStats = api.getLoadBalancerStats(2000);\n\n      assertEquals(loadBalancerStats.getConnectTimeOut(), 2);\n      assertEquals(loadBalancerStats.getConnectError(), 0);\n      assertEquals(loadBalancerStats.getConnectFailure(), 0);\n      assertEquals(loadBalancerStats.getDataTimedOut(), 10);\n      assertEquals(loadBalancerStats.getKeepAliveTimedOut(), 0);\n      assertEquals(loadBalancerStats.getMaxConn(), 22);\n   }\n\n   public void testListProtocols() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/protocols\");\n      ReportApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/report-protocols-list.json\")).build()\n      ).getReportApi(\"DFW\");\n\n      Iterable<Protocol> protocols = api.listProtocols();\n\n      assertEquals(Iterables.size(protocols), 20);\n   }\n\n   public void testListAlgorithms() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/algorithms\");\n      ReportApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/report-algorithms-list.json\")).build()\n      ).getReportApi(\"DFW\");\n\n      Iterable<String> algorithms = api.listAlgorithms();\n\n      assertEquals(Iterables.size(algorithms), 5);\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/java/org/jclouds/rackspace/cloudloadbalancers/v1/features/ReportApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.features;\n\nimport static org.jclouds.rackspace.cloudloadbalancers.v1.predicates.LoadBalancerPredicates.awaitAvailable;\nimport static org.jclouds.rackspace.cloudloadbalancers.v1.predicates.LoadBalancerPredicates.awaitDeleted;\nimport static org.testng.Assert.assertNotEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Calendar;\nimport java.util.Date;\n\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.HistoricalUsage;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.LoadBalancer;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.CreateLoadBalancer;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.LoadBalancerStats;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.LoadBalancerUsage;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.AddNode;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.Protocol;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.VirtualIP.Type;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.internal.BaseCloudLoadBalancersApiLiveTest;\nimport org.testng.annotations.AfterGroups;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.Iterables;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"ReportApiLiveTest\")\npublic class ReportApiLiveTest extends BaseCloudLoadBalancersApiLiveTest {\n   private LoadBalancer lb;\n   private String region;\n\n   public void testCreateLoadBalancer() {\n      AddNode addNode = AddNode.builder().address(\"192.168.1.1\").port(8080).build();\n      CreateLoadBalancer createLB = CreateLoadBalancer.builder()\n            .name(prefix + \"-jclouds\").protocol(\"HTTP\").port(80).virtualIPType(Type.PUBLIC).node(addNode).build();\n\n      region = Iterables.getFirst(api.getConfiguredRegions(), null);\n      lb = api.getLoadBalancerApi(region).create(createLB);\n\n      assertTrue(awaitAvailable(api.getLoadBalancerApi(region)).apply(lb));\n   }\n\n   @Test(dependsOnMethods = \"testCreateLoadBalancer\")\n   public void testReports() throws Exception {\n      Calendar calendar = Calendar.getInstance();\n      calendar.add(Calendar.DATE, -1);\n      Date yesterday = calendar.getTime();\n      Date today = new Date();\n\n      FluentIterable<LoadBalancer> loadBalancers = api.getReportApi(region).listBillableLoadBalancers(yesterday, today).concat();\n      assertNotNull(loadBalancers);\n\n      HistoricalUsage historicalUsage = api.getReportApi(region).getHistoricalUsage(yesterday, today);\n      assertNotEquals(historicalUsage.getAccountId(), 0);\n\n      FluentIterable<LoadBalancerUsage> loadBalancerUsages = api.getReportApi(region).listLoadBalancerUsage(lb.getId(), yesterday, today).concat();\n      assertNotNull(loadBalancerUsages);\n\n      loadBalancerUsages = api.getReportApi(region).listCurrentLoadBalancerUsage(lb.getId()).concat();\n      assertNotNull(loadBalancerUsages);\n\n      try {\n         LoadBalancerStats loadBalancerStats = api.getReportApi(region).getLoadBalancerStats(lb.getId());\n         assertNotNull(loadBalancerStats);\n      }\n      catch (HttpResponseException e) {\n         // CLB sometimes doesn't like it when you get stats on a newly created LB so ignore a 500\n         if (e.getResponse().getStatusCode() != 500) {\n            throw e;\n         }\n      }\n\n      Iterable<Protocol> protocols = api.getReportApi(region).listProtocols();\n      assertTrue(!Iterables.isEmpty(protocols));\n\n      Iterable<String> algorithms = api.getReportApi(region).listAlgorithms();\n      assertTrue(!Iterables.isEmpty(algorithms));\n   }\n\n   @Override\n   @AfterGroups(groups = \"live\")\n   protected void tearDown() {\n      assertTrue(awaitAvailable(api.getLoadBalancerApi(region)).apply(lb));\n      api.getLoadBalancerApi(region).delete(lb.getId());\n      assertTrue(awaitDeleted(api.getLoadBalancerApi(region)).apply(lb));\n      super.tearDown();\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/java/org/jclouds/rackspace/cloudloadbalancers/v1/features/SSLTerminationApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.features;\nimport static com.google.common.net.HttpHeaders.ACCEPT;\nimport static jakarta.ws.rs.HttpMethod.DELETE;\nimport static jakarta.ws.rs.HttpMethod.PUT;\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\nimport static jakarta.ws.rs.core.MediaType.WILDCARD;\nimport static jakarta.ws.rs.core.Response.Status.NOT_FOUND;\nimport static jakarta.ws.rs.core.Response.Status.OK;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.net.URI;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.CloudLoadBalancersApi;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.SSLTermination;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.internal.BaseCloudLoadBalancerApiExpectTest;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class SSLTerminationApiExpectTest extends BaseCloudLoadBalancerApiExpectTest<CloudLoadBalancersApi> {\n\n   public void testGetSSLTermination() throws IOException {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/ssltermination\");\n      SSLTerminationApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/ssltermination-get.json\")).build()\n      ).getSSLTerminationApi(\"DFW\", 2000);\n\n      SSLTermination sslTermination = api.get();\n      assertEquals(sslTermination, getSSLTermination());\n   }\n\n   public void testGetDeletedSSLTermination() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/ssltermination\");\n      SSLTerminationApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(NOT_FOUND.getStatusCode()).build()\n      ).getSSLTerminationApi(\"DFW\", 2000);\n\n      SSLTermination sslTermination = api.get();\n      assertNull(sslTermination);\n   }\n\n   public void testCreateSSLTermination() throws IOException {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/ssltermination\");\n      SSLTerminationApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess,\n            authenticatedGET()\n               .method(PUT)\n               .endpoint(endpoint)\n               .payload(payloadFromResourceWithContentType(\"/ssltermination-create.json\", APPLICATION_JSON))\n               .build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).build()\n      ).getSSLTerminationApi(\"DFW\", 2000);\n\n      api.createOrUpdate(getSSLTermination());\n   }\n\n   public void testRemoveSSLTermination() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/ssltermination\");\n      SSLTerminationApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess,\n            authenticatedGET().method(DELETE).endpoint(endpoint).replaceHeader(ACCEPT, WILDCARD).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).build()\n      ).getSSLTerminationApi(\"DFW\", 2000);\n\n      assertTrue(api.delete());\n   }\n\n   public static SSLTermination getSSLTermination() throws IOException {\n      String certificate = Strings2.toStringAndClose(\n            SSLTerminationApiExpectTest.class.getResourceAsStream(\"/ssltermination-certificate.txt\"));\n      String privateKey = Strings2.toStringAndClose(\n            SSLTerminationApiExpectTest.class.getResourceAsStream(\"/ssltermination-privatekey.txt\"));\n      String intermediateCertificate = Strings2.toStringAndClose(\n            SSLTerminationApiExpectTest.class.getResourceAsStream(\"/ssltermination-intermediatecertificate.txt\"));\n\n      SSLTermination sslTermination = SSLTermination.builder()\n            .enabled(true)\n            .secureTrafficOnly(false)\n            .securePort(443)\n            .certificate(certificate)\n            .privatekey(privateKey)\n            .intermediateCertificate(intermediateCertificate)\n            .build();\n\n      return sslTermination;\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/java/org/jclouds/rackspace/cloudloadbalancers/v1/features/SSLTerminationApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.features;\n\nimport static org.jclouds.rackspace.cloudloadbalancers.v1.predicates.LoadBalancerPredicates.awaitAvailable;\nimport static org.jclouds.rackspace.cloudloadbalancers.v1.predicates.LoadBalancerPredicates.awaitDeleted;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.LoadBalancer;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.CreateLoadBalancer;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.AddNode;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.SSLTermination;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.VirtualIP.Type;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.internal.BaseCloudLoadBalancersApiLiveTest;\nimport org.testng.annotations.AfterGroups;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Iterables;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"SSLTerminationApiLiveTest\")\npublic class SSLTerminationApiLiveTest extends BaseCloudLoadBalancersApiLiveTest {\n   private LoadBalancer lb;\n   private String region;\n\n   public void testCreateLoadBalancer() {\n      AddNode addNode = AddNode.builder().address(\"192.168.1.1\").port(8080).build();\n      CreateLoadBalancer createLB = CreateLoadBalancer.builder()\n            .name(prefix + \"-jclouds\").protocol(\"HTTP\").port(80).virtualIPType(Type.PUBLIC).node(addNode).build();\n\n      region = Iterables.getFirst(api.getConfiguredRegions(), null);\n      lb = api.getLoadBalancerApi(region).create(createLB);\n\n      assertTrue(awaitAvailable(api.getLoadBalancerApi(region)).apply(lb));\n   }\n\n   @Test(dependsOnMethods = \"testCreateLoadBalancer\")\n   public void testCreateAndGetSSLTermination() throws Exception {\n      api.getSSLTerminationApi(region, lb.getId()).createOrUpdate(\n            SSLTerminationApiExpectTest.getSSLTermination());\n      assertTrue(awaitAvailable(api.getLoadBalancerApi(region)).apply(lb));\n\n      SSLTermination sslTermination =\n            api.getSSLTerminationApi(region, lb.getId()).get();\n\n      assertEquals(sslTermination, SSLTerminationApiExpectTest.getSSLTermination());\n   }\n\n   @Test(dependsOnMethods = \"testCreateAndGetSSLTermination\")\n   public void testRemoveAndGetSSLTermination() throws Exception {\n      assertTrue(api.getSSLTerminationApi(region, lb.getId()).delete());\n      assertTrue(awaitAvailable(api.getLoadBalancerApi(region)).apply(lb));\n\n      SSLTermination sslTermination =\n            api.getSSLTerminationApi(region, lb.getId()).get();\n\n      assertNull(sslTermination);\n   }\n\n   @Override\n   @AfterGroups(groups = \"live\")\n   protected void tearDown() {\n      assertTrue(awaitAvailable(api.getLoadBalancerApi(region)).apply(lb));\n      api.getLoadBalancerApi(region).delete(lb.getId());\n      assertTrue(awaitDeleted(api.getLoadBalancerApi(region)).apply(lb));\n      super.tearDown();\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/java/org/jclouds/rackspace/cloudloadbalancers/v1/features/SessionPersistenceApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.features;\nimport static jakarta.ws.rs.HttpMethod.DELETE;\nimport static jakarta.ws.rs.HttpMethod.PUT;\nimport static jakarta.ws.rs.core.Response.Status.OK;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\n\nimport java.net.URI;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.CloudLoadBalancersApi;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.SessionPersistence;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.internal.BaseCloudLoadBalancerApiExpectTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class SessionPersistenceApiExpectTest extends BaseCloudLoadBalancerApiExpectTest<CloudLoadBalancersApi> {\n   public void testGetSessionPersistence() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/sessionpersistence\");\n      SessionPersistenceApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/sessionpersistence-get.json\")).build()\n      ).getSessionPersistenceApi(\"DFW\", 2000);\n\n      SessionPersistence sessionPersistence = api.get();\n      assertEquals(sessionPersistence, SessionPersistence.HTTP_COOKIE);\n   }\n\n   public void testGetDeletedSessionPersistence() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/sessionpersistence\");\n      SessionPersistenceApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/sessionpersistence-get-deleted.json\")).build()\n      ).getSessionPersistenceApi(\"DFW\", 2000);\n\n      SessionPersistence sessionPersistence = api.get();\n      assertNull(sessionPersistence);\n   }\n\n   public void testCreateSessionPersistence() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/sessionpersistence\");\n      SessionPersistenceApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess,\n            authenticatedGET().method(PUT).endpoint(endpoint).payload(payloadFromResource(\"/sessionpersistence-create.json\")).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).build()\n      ).getSessionPersistenceApi(\"DFW\", 2000);\n\n      api.create(SessionPersistence.HTTP_COOKIE);\n   }\n\n   public void testRemoveSessionPersistence() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/sessionpersistence\");\n      SessionPersistenceApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess,\n            authenticatedGET().method(DELETE).endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).build()\n      ).getSessionPersistenceApi(\"DFW\", 2000);\n\n      api.delete();\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/java/org/jclouds/rackspace/cloudloadbalancers/v1/features/SessionPersistenceApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.features;\n\nimport static org.jclouds.rackspace.cloudloadbalancers.v1.predicates.LoadBalancerPredicates.awaitAvailable;\nimport static org.jclouds.rackspace.cloudloadbalancers.v1.predicates.LoadBalancerPredicates.awaitDeleted;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.LoadBalancer;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.CreateLoadBalancer;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.AddNode;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.SessionPersistence;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.VirtualIP.Type;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.internal.BaseCloudLoadBalancersApiLiveTest;\nimport org.testng.annotations.AfterGroups;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Iterables;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"SessionPersistenceApiLiveTest\")\npublic class SessionPersistenceApiLiveTest extends BaseCloudLoadBalancersApiLiveTest {\n   private LoadBalancer lb;\n   private String region;\n\n   public void testCreateLoadBalancer() {\n      AddNode addNode = AddNode.builder().address(\"192.168.1.1\").port(8080).build();\n      CreateLoadBalancer createLB = CreateLoadBalancer.builder()\n            .name(prefix + \"-jclouds\").protocol(\"HTTP\").port(80).virtualIPType(Type.PUBLIC).node(addNode).build();\n\n      region = Iterables.getFirst(api.getConfiguredRegions(), null);\n      lb = api.getLoadBalancerApi(region).create(createLB);\n\n      assertTrue(awaitAvailable(api.getLoadBalancerApi(region)).apply(lb));\n   }\n\n   @Test(dependsOnMethods = \"testCreateLoadBalancer\")\n   public void testCreateAndGetSessionPersistence() throws Exception {\n      api.getSessionPersistenceApi(region, lb.getId()).create(SessionPersistence.HTTP_COOKIE);\n      assertTrue(awaitAvailable(api.getLoadBalancerApi(region)).apply(lb));\n\n      SessionPersistence sessionPersistence =\n            api.getSessionPersistenceApi(region, lb.getId()).get();\n\n      assertEquals(sessionPersistence, SessionPersistence.HTTP_COOKIE);\n   }\n\n   @Test(dependsOnMethods = \"testCreateAndGetSessionPersistence\")\n   public void testRemoveAndGetSessionPersistence() throws Exception {\n      api.getSessionPersistenceApi(region, lb.getId()).delete();\n      assertTrue(awaitAvailable(api.getLoadBalancerApi(region)).apply(lb));\n\n      SessionPersistence sessionPersistence =\n            api.getSessionPersistenceApi(region, lb.getId()).get();\n\n      assertNull(sessionPersistence);\n   }\n\n   @Override\n   @AfterGroups(groups = \"live\")\n   protected void tearDown() {\n      assertTrue(awaitAvailable(api.getLoadBalancerApi(region)).apply(lb));\n      api.getLoadBalancerApi(region).delete(lb.getId());\n      assertTrue(awaitDeleted(api.getLoadBalancerApi(region)).apply(lb));\n      super.tearDown();\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/java/org/jclouds/rackspace/cloudloadbalancers/v1/features/VirtualIPApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.features;\nimport static com.google.common.net.HttpHeaders.ACCEPT;\nimport static jakarta.ws.rs.HttpMethod.DELETE;\nimport static jakarta.ws.rs.HttpMethod.POST;\nimport static jakarta.ws.rs.core.MediaType.WILDCARD;\nimport static jakarta.ws.rs.core.Response.Status.OK;\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.CloudLoadBalancersApi;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.VirtualIP;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.VirtualIPWithId;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.internal.BaseCloudLoadBalancerApiExpectTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\")\npublic class VirtualIPApiExpectTest extends BaseCloudLoadBalancerApiExpectTest<CloudLoadBalancersApi> {\n   public void testListVirtualIPs() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/virtualips\");\n      VirtualIPApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess,\n            authenticatedGET().endpoint(endpoint).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/virtualips-list.json\")).build()\n      ).getVirtualIPApi(\"DFW\", 2000);\n\n      Iterable<VirtualIPWithId> virtualIPs = api.list();\n      assertEquals(virtualIPs, getVirtualIPs());\n   }\n\n   public void testCreateVirtualIPs() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/virtualips\");\n      VirtualIPApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess,\n            authenticatedGET().method(POST).endpoint(endpoint).payload(payloadFromResource(\"/virtualips-create.json\")).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).payload(payloadFromResource(\"/virtualips-create-response.json\")).build()\n      ).getVirtualIPApi(\"DFW\", 2000);\n\n      api.create(VirtualIP.publicIPv6());\n   }\n\n   public void testRemoveSingleVirtualIP() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/virtualips/23\");\n      VirtualIPApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess,\n            authenticatedGET().method(DELETE).endpoint(endpoint).replaceHeader(ACCEPT, WILDCARD).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).build()\n      ).getVirtualIPApi(\"DFW\", 2000);\n\n      api.delete(23);\n   }\n\n   public void testRemoveManyVirtualIPs() {\n      URI endpoint = URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000/virtualips?id=23&id=24\");\n      VirtualIPApi api = requestsSendResponses(\n            rackspaceAuthWithUsernameAndApiKey,\n            responseWithAccess,\n            authenticatedGET().method(DELETE).endpoint(endpoint).replaceHeader(ACCEPT, WILDCARD).build(),\n            HttpResponse.builder().statusCode(OK.getStatusCode()).build()\n      ).getVirtualIPApi(\"DFW\", 2000);\n\n      List<Integer> virtualIPIds = ImmutableList.<Integer> of(23, 24);\n      api.delete(virtualIPIds);\n   }\n\n   private Iterable<VirtualIPWithId> getVirtualIPs() {\n      VirtualIPWithId virtualIP1 = new VirtualIPWithId(VirtualIP.Type.PUBLIC, VirtualIP.IPVersion.IPV4, 5557, \"166.78.34.87\");\n      VirtualIPWithId virtualIP2 = new VirtualIPWithId(VirtualIP.Type.PUBLIC, VirtualIP.IPVersion.IPV6, 9076419, \"2001:4800:7901:0000:9a32:3c2a:0000:0001\");\n      VirtualIPWithId virtualIP3 = new VirtualIPWithId(VirtualIP.Type.PUBLIC, VirtualIP.IPVersion.IPV6, 9079727, \"2001:4800:7901:0000:9a32:3c2a:0000:0002\");\n\n      return ImmutableList.<VirtualIPWithId> of(virtualIP1, virtualIP2, virtualIP3);\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/java/org/jclouds/rackspace/cloudloadbalancers/v1/features/VirtualIPApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.features;\n\nimport static org.jclouds.rackspace.cloudloadbalancers.v1.predicates.LoadBalancerPredicates.awaitAvailable;\nimport static org.jclouds.rackspace.cloudloadbalancers.v1.predicates.LoadBalancerPredicates.awaitDeleted;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.List;\n\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.LoadBalancer;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.CreateLoadBalancer;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.AddNode;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.VirtualIP;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.VirtualIPWithId;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.VirtualIP.Type;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.internal.BaseCloudLoadBalancersApiLiveTest;\nimport org.testng.annotations.AfterGroups;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Iterators;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"VirtualIPApiLiveTest\")\npublic class VirtualIPApiLiveTest extends BaseCloudLoadBalancersApiLiveTest {\n   private LoadBalancer lb;\n   private String region;\n\n   public void testCreateLoadBalancer() {\n      AddNode addNode = AddNode.builder().address(\"192.168.1.1\").port(8080).build();\n      CreateLoadBalancer createLB = CreateLoadBalancer.builder()\n            .name(prefix + \"-jclouds\").protocol(\"HTTP\").port(80).virtualIPType(Type.PUBLIC).node(addNode).build();\n\n      region = Iterables.getFirst(api.getConfiguredRegions(), null);\n      lb = api.getLoadBalancerApi(region).create(createLB);\n\n      assertTrue(awaitAvailable(api.getLoadBalancerApi(region)).apply(lb));\n   }\n\n   @Test(dependsOnMethods = \"testCreateLoadBalancer\")\n   public void testCreateVirtualIPs() throws Exception {\n      api.getVirtualIPApi(region, lb.getId()).create(VirtualIP.publicIPv6());\n      assertTrue(awaitAvailable(api.getLoadBalancerApi(region)).apply(lb));\n      api.getVirtualIPApi(region, lb.getId()).create(VirtualIP.publicIPv6());\n      assertTrue(awaitAvailable(api.getLoadBalancerApi(region)).apply(lb));\n      api.getVirtualIPApi(region, lb.getId()).create(VirtualIP.publicIPv6());\n      assertTrue(awaitAvailable(api.getLoadBalancerApi(region)).apply(lb));\n\n      Iterable<VirtualIPWithId> actualVirtualIPs = api.getVirtualIPApi(region, lb.getId()).list();\n\n      assertEquals(Iterators.size(actualVirtualIPs.iterator()), 5);\n   }\n\n   @Test(dependsOnMethods = \"testCreateVirtualIPs\")\n   public void testRemoveSingleVirtualIP() throws Exception {\n      Iterable<VirtualIPWithId> actualVirtualIPs = api.getVirtualIPApi(region, lb.getId()).list();\n      VirtualIPWithId removedVirtualIP = Iterables.getFirst(actualVirtualIPs, null);\n\n      assertTrue(api.getVirtualIPApi(region, lb.getId()).delete(removedVirtualIP.getId()));\n      assertTrue(awaitAvailable(api.getLoadBalancerApi(region)).apply(lb));\n\n      actualVirtualIPs = api.getVirtualIPApi(region, lb.getId()).list();\n\n      assertEquals(Iterators.size(actualVirtualIPs.iterator()), 4);\n   }\n\n   @Test(dependsOnMethods = \"testRemoveSingleVirtualIP\")\n   public void testRemoveManyVirtualIPs() throws Exception {\n      Iterable<VirtualIPWithId> actualVirtualIPs = api.getVirtualIPApi(region, lb.getId()).list();\n      VirtualIPWithId removedVirtualIP1 = Iterables.getFirst(actualVirtualIPs, null);\n      VirtualIPWithId removedVirtualIP2 = Iterables.getLast(actualVirtualIPs);\n      List<Integer> removedVirtualIPIds = ImmutableList.<Integer> of(removedVirtualIP1.getId(), removedVirtualIP2.getId());\n\n      assertTrue(api.getVirtualIPApi(region, lb.getId()).delete(removedVirtualIPIds));\n      assertTrue(awaitAvailable(api.getLoadBalancerApi(region)).apply(lb));\n\n      actualVirtualIPs = api.getVirtualIPApi(region, lb.getId()).list();\n\n      assertEquals(Iterators.size(actualVirtualIPs.iterator()), 2);\n   }\n\n   @Override\n   @AfterGroups(groups = \"live\")\n   protected void tearDown() {\n      assertTrue(awaitAvailable(api.getLoadBalancerApi(region)).apply(lb));\n      api.getLoadBalancerApi(region).delete(lb.getId());\n      assertTrue(awaitDeleted(api.getLoadBalancerApi(region)).apply(lb));\n      super.tearDown();\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/java/org/jclouds/rackspace/cloudloadbalancers/v1/functions/ParseLoadBalancerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.functions;\n\nimport java.net.URI;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.AccessRule;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.AccessRuleWithId;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.ConnectionThrottle;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.HealthMonitor;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.LoadBalancer;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.Metadata;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.Node;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.SSLTermination;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.SessionPersistence;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.SourceAddresses;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.VirtualIP;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.VirtualIPWithId;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.HealthMonitor.Type;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.LoadBalancer.Status;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.internal.BaseLoadBalancer.Algorithm;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Injector;\nimport com.google.inject.assistedinject.FactoryModuleBuilder;\n\n@Test(groups = \"unit\", testName = \"UnwrapLoadBalancerTest\")\npublic class ParseLoadBalancerTest extends BaseItemParserTest<LoadBalancer> {\n\n   @Override\n   public String resource() {\n      return \"/loadbalancer-get.json\";\n   }\n\n   @Override\n   public LoadBalancer expected() {\n      Metadata metadata = new Metadata();\n      metadata.put(\"color\", \"red\");\n      metadata.putId(\"color\", 1);\n      metadata.put(\"label\", \"web-load-balancer\");\n      metadata.putId(\"label\", 2);\n      \n      return LoadBalancer\n            .builder()\n            .region(\"DFW\")\n            .id(2000)\n            .name(\"sample-loadbalancer\")\n            .protocol(\"HTTP\")\n            .port(80)\n            .algorithm(Algorithm.RANDOM)\n            .status(Status.ACTIVE)\n            .connectionLogging(true)\n            .contentCaching(true)\n            .nodeCount(2)\n            .halfClosed(false)\n            .healthMonitor(HealthMonitor.builder().type(Type.CONNECT).delay(10).timeout(5).attemptsBeforeDeactivation(2).build())\n            .sslTermination(SSLTermination.builder().enabled(true).secureTrafficOnly(false).securePort(443).build())\n            .sourceAddresses(SourceAddresses.builder().ipv6Public(\"2001:4800:7901::5/64\").ipv4Public(\"174.143.139.137\").ipv4Servicenet(\"10.183.250.137\").build())\n            .connectionThrottle(ConnectionThrottle.builder().maxConnections(100).minConnections(10).maxConnectionRate(50).rateInterval(60).build())\n            .accessRules(ImmutableSet.of(\n                  new AccessRuleWithId(22215, \"1.2.3.4/32\", AccessRule.Type.DENY),\n                  new AccessRuleWithId(22217, \"12.0.0.0/8\", AccessRule.Type.ALLOW)))\n            .virtualIPs(ImmutableSet.of(\n                  new VirtualIPWithId(VirtualIP.Type.PUBLIC, VirtualIP.IPVersion.IPV4, 1000, \"206.10.10.210\"),\n                  new VirtualIPWithId(VirtualIP.Type.PUBLIC, VirtualIP.IPVersion.IPV6, 1001, \"2001:4800:7901:0000:9a32:3c2a:0000:0001\")))\n            .nodes(ImmutableSet.of(\n                  Node.builder().id(1041).address(\"10.1.1.1\").port(80).condition(Node.Condition.ENABLED).status(Node.Status.ONLINE).build(), \n                  Node.builder().id(1411).address(\"10.1.1.2\").port(80).condition(Node.Condition.ENABLED).status(Node.Status.ONLINE).build()))\n            .sessionPersistenceType(SessionPersistence.HTTP_COOKIE)\n            .clusterName(\"c1.dfw1\")\n            .created(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2010-11-30T03:23:42Z\"))\n            .updated(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2010-11-30T03:23:44Z\"))\n            .metadata(metadata)\n            .uri(URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000\")).build();\n   }\n\n   // add factory binding as this is not default\n   @Override\n   protected Injector injector() {\n      return super.injector().createChildInjector(new AbstractModule() {\n\n         @Override\n         protected void configure() {\n            install(new FactoryModuleBuilder().build(ConvertLB.Factory.class));\n         }\n\n      });\n\n   }\n\n   @Override\n   protected Function<HttpResponse, LoadBalancer> parser(Injector i) {\n      return i.getInstance(ParseLoadBalancer.class).setEndpointAndRegion(URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000\"));\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/java/org/jclouds/rackspace/cloudloadbalancers/v1/functions/ParseLoadBalancerWhenDeletedTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.functions;\n\nimport java.net.URI;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.LoadBalancer;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.LoadBalancer.Status;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Injector;\nimport com.google.inject.assistedinject.FactoryModuleBuilder;\n\n@Test(groups = \"unit\", testName = \"UnwrapLoadBalancerWhenDeletedTest\")\npublic class ParseLoadBalancerWhenDeletedTest extends BaseItemParserTest<LoadBalancer> {\n\n   @Override\n   public String resource() {\n      return \"/loadbalancer-get-deleted.json\";\n   }\n\n   @Override\n   public LoadBalancer expected() {\n      return LoadBalancer.builder().region(\"LON\").id(4865).name(\"adriancole-LON\").status(Status.DELETED).nodeCount(0)\n            .created(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2011-12-05T18:03:23Z\"))\n            .updated(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2011-12-05T18:04:04Z\"))\n            .uri(URI.create(\"https://lon.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/4865\")).build();\n   }\n\n   // add factory binding as this is not default\n   @Override\n   protected Injector injector() {\n      return super.injector().createChildInjector(new AbstractModule() {\n\n         @Override\n         protected void configure() {\n            install(new FactoryModuleBuilder().build(ConvertLB.Factory.class));\n         }\n\n      });\n\n   }\n\n   @Override\n   protected Function<HttpResponse, LoadBalancer> parser(Injector i) {\n      return i.getInstance(ParseLoadBalancer.class).setEndpointAndRegion(URI.create(\"https://lon.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/4865\"));\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/java/org/jclouds/rackspace/cloudloadbalancers/v1/functions/ParseLoadBalancersTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.functions;\n\nimport java.net.URI;\nimport java.util.Set;\n\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.IterableWithMarkers;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.json.BaseIterableWithMarkerParserTest;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.LoadBalancer;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.VirtualIP;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.VirtualIPWithId;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.LoadBalancer.Status;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.domain.internal.BaseLoadBalancer.Algorithm;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Injector;\nimport com.google.inject.assistedinject.FactoryModuleBuilder;\n\n@Test(groups = \"unit\")\npublic class ParseLoadBalancersTest extends BaseIterableWithMarkerParserTest<LoadBalancer> {\n\n   public Set<LoadBalancer> data() {\n      return ImmutableSet.of(\n            LoadBalancer\n                  .builder()\n                  .region(\"DFW\")\n                  .name(\"lb-site1\")\n                  .id(71)\n                  .protocol(\"HTTP\")\n                  .port(80)\n                  .algorithm(Algorithm.RANDOM)\n                  .status(Status.ACTIVE)\n                  .nodeCount(1)\n                  .virtualIPs(ImmutableSet.of(\n                        new VirtualIPWithId(VirtualIP.Type.PUBLIC, VirtualIP.IPVersion.IPV4, 403, \"206.55.130.1\")))\n                  .created(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2010-11-30T03:23:42Z\"))\n                  .updated(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2010-11-30T03:23:44Z\"))\n                  .uri(URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/71\")).build(),\n            LoadBalancer\n                  .builder()\n                  .region(\"DFW\")\n                  .name(\"lb-site2\")\n                  .id(166)\n                  .protocol(\"HTTP\")\n                  .port(80)\n                  .algorithm(Algorithm.RANDOM)\n                  .status(Status.ACTIVE)\n                  .nodeCount(1)\n                  .virtualIPs(ImmutableSet.of(\n                        new VirtualIPWithId(VirtualIP.Type.PUBLIC, VirtualIP.IPVersion.IPV4, 401, \"206.55.130.2\")))\n                  .created(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2010-11-30T03:23:42Z\"))\n                  .updated(new SimpleDateFormatDateService().iso8601SecondsDateParse(\"2010-11-30T03:23:44Z\"))\n                  .uri(URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/166\")).build());\n   }\n   \n   @Override\n   public String resource() {\n      return \"/loadbalancers-list.json\";\n   }\n\n   @Override\n   public IterableWithMarker<LoadBalancer> expected() {\n      return IterableWithMarkers.from(data());\n   }\n\n   // add factory binding as this is not default\n   @Override\n   protected Injector injector() {\n      return super.injector().createChildInjector(new AbstractModule() {\n\n         @Override\n         protected void configure() {\n            install(new FactoryModuleBuilder().build(ConvertLB.Factory.class));\n         }\n\n      });\n\n   }\n\n   @Override\n   protected Function<HttpResponse, IterableWithMarker<LoadBalancer>> parser(Injector i) {\n      return i.getInstance(ParseLoadBalancers.class).setEndpointAndRegion(URI.create(\"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers\"));\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/java/org/jclouds/rackspace/cloudloadbalancers/v1/handlers/ParseCloudLoadBalancersErrorFromHttpResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.handlers;\nimport static jakarta.ws.rs.HttpMethod.GET;\nimport static jakarta.ws.rs.core.Response.Status.NOT_FOUND;\n\nimport java.net.URI;\n\nimport org.jclouds.http.handlers.BaseHttpErrorHandlerTest;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.testng.annotations.Test;\n\n@Test(groups = { \"unit\" })\npublic class ParseCloudLoadBalancersErrorFromHttpResponseTest extends\n         BaseHttpErrorHandlerTest<ParseCloudLoadBalancersErrorFromHttpResponse> {\n   @Test\n   public void testNotFound() {\n      assertCodeMakes(\n               GET,\n               URI.create(\"https://ord.loadbalancers.api.rackspacecloud.com/v1.0/1234/loadbalancers/2000\"),\n               NOT_FOUND.getStatusCode(),\n               \"Not Found\",\n               \"<itemNotFound code=\\\"404\\\" xmlns=\\\"http://docs.openstack.org/loadbalancers/api/v1.0\\\">\\n    <message>Object not Found</message>\\n</itemNotFound>\",\n               ResourceNotFoundException.class, \"loadbalancers 2000 not found\");\n   }\n\n   @Override\n   protected Class<ParseCloudLoadBalancersErrorFromHttpResponse> getClassToTest() {\n      return ParseCloudLoadBalancersErrorFromHttpResponse.class;\n   }\n\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/java/org/jclouds/rackspace/cloudloadbalancers/v1/internal/BaseCloudLoadBalancerApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.internal;\nimport static com.google.common.net.HttpHeaders.ACCEPT;\nimport static jakarta.ws.rs.HttpMethod.GET;\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rackspace.cloudidentity.v2_0.internal.RackspaceFixture;\nimport org.jclouds.rest.internal.BaseRestApiExpectTest;\n\n/**\n * Base class for writing Cloud Load Balancer Expect tests\n */\npublic class BaseCloudLoadBalancerApiExpectTest<T> extends BaseRestApiExpectTest<T> {\n   protected HttpRequest rackspaceAuthWithUsernameAndApiKey;\n\n   protected String authToken;\n   protected HttpResponse responseWithAccess;\n\n   public BaseCloudLoadBalancerApiExpectTest() {\n      provider = \"rackspace-cloudloadbalancers\";\n\n      rackspaceAuthWithUsernameAndApiKey = RackspaceFixture.INSTANCE\n            .initialAuthWithUsernameAndApiKey(identity, credential);\n      \n      authToken = RackspaceFixture.INSTANCE.getAuthToken();\n      responseWithAccess = RackspaceFixture.INSTANCE.responseWithAccess();\n   }\n\n   @Override\n   protected HttpRequestComparisonType compareHttpRequestAsType(HttpRequest input) {\n      return HttpRequestComparisonType.JSON;\n   }\n\n   protected HttpRequest.Builder<?> authenticatedGET() {\n      return HttpRequest.builder()\n            .method(GET)\n            .addHeader(ACCEPT, APPLICATION_JSON)\n            .addHeader(\"X-Auth-Token\", authToken);\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/java/org/jclouds/rackspace/cloudloadbalancers/v1/internal/BaseCloudLoadBalancersApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.internal;\n\nimport java.util.Properties;\nimport java.util.logging.Logger;\n\nimport org.jclouds.apis.BaseApiLiveTest;\nimport org.jclouds.openstack.keystone.config.KeystoneProperties;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.CloudLoadBalancersApi;\nimport org.testng.annotations.BeforeGroups;\n\npublic class BaseCloudLoadBalancersApiLiveTest extends BaseApiLiveTest<CloudLoadBalancersApi> {\n\n   public BaseCloudLoadBalancersApiLiveTest() {\n      provider = \"rackspace-cloudloadbalancers\";\n   }\n\n   @BeforeGroups(groups = { \"integration\", \"live\" })\n   @Override\n   public void setup() {\n      super.setup();\n      Logger.getAnonymousLogger().info(\"running against regions \" + api.getConfiguredRegions());\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      setIfTestSystemPropertyPresent(props, KeystoneProperties.CREDENTIAL_TYPE);\n      return props;\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/java/org/jclouds/rackspace/cloudloadbalancers/v1/options/ListOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.v1.options;\n\nimport static org.jclouds.rackspace.cloudloadbalancers.v1.options.ListOptions.Builder.limit;\nimport static org.jclouds.rackspace.cloudloadbalancers.v1.options.ListOptions.Builder.marker;\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tests behavior of {@code ListOptions}\n */\n@Test(groups = \"unit\")\npublic class ListOptionsTest {\n\n   public void testMarker() {\n      ListOptions options = new ListOptions().marker(\"1\");\n      assertEquals(ImmutableList.of(\"1\"), options.buildQueryParameters().get(\"marker\"));\n   }\n\n   public void testLimit() {\n      int limit = 1;\n      ListOptions options = new ListOptions().limit(limit);\n      assertEquals(ImmutableList.of(\"1\"), options.buildQueryParameters().get(\"limit\"));\n   }\n\n   public void testMarkerStatic() {\n      ListOptions options = marker(\"1\");\n      assertEquals(ImmutableList.of(\"1\"), options.buildQueryParameters().get(\"marker\"));\n   }\n\n   public void testLimitStatic() {\n      ListOptions options = limit(1);\n      assertEquals(ImmutableList.of(\"1\"), options.buildQueryParameters().get(\"limit\"));\n   }\n}\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/resources/accesslist-create.json",
    "content": "{\"accessList\":[{\"address\":\"206.160.163.21\",\"type\":\"DENY\"},{\"address\":\"206.160.165.11\",\"type\":\"DENY\"},{\"address\":\"206.160.163.22\",\"type\":\"DENY\"}]}"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/resources/accesslist-list.json",
    "content": "{\n    \"accessList\": [\n        {\n            \"address\": \"206.160.163.21\",\n            \"id\": 23,\n            \"type\": \"DENY\"\n        },\n        {\n            \"address\": \"206.160.165.11\",\n            \"id\": 24,\n            \"type\": \"DENY\"\n        },\n        {\n            \"address\": \"206.160.163.22\",\n            \"id\": 25,\n            \"type\": \"DENY\"\n        }\n    ]\n}"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/resources/connectionlogging-disable.json",
    "content": "{\"connectionLogging\":{\"enabled\":false}}"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/resources/connectionlogging-enable.json",
    "content": "{\"connectionLogging\":{\"enabled\":true}}"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/resources/connectionthrottle-create.json",
    "content": "{\"connectionThrottle\":{\"maxConnections\":100,\"minConnections\":10,\"maxConnectionRate\":100,\"rateInterval\":100}}"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/resources/connectionthrottle-get-deleted.json",
    "content": "{\n    \"connectionThrottle\": {\n    }\n}"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/resources/connectionthrottle-get.json",
    "content": "{\n    \"connectionThrottle\": {\n        \"maxConnections\": 100,\n        \"minConnections\": 10,\n        \"maxConnectionRate\": 100,\n        \"rateInterval\": 100\n    }\n}"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/resources/contentcaching-disable.json",
    "content": "{\"contentCaching\":{\"enabled\":false}}"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/resources/contentcaching-enable.json",
    "content": "{\"contentCaching\":{\"enabled\":true}}"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/resources/errorpage.html",
    "content": "<!--\n\n Licensed to the Apache Software Foundation (ASF) under one\n or more contributor license agreements.  See the NOTICE file\n distributed with this work for additional information\n regarding copyright ownership.  The ASF licenses this file\n to you under the Apache License, Version 2.0 (the\n \"License\"); you may not use this file except in compliance\n with the License.  You may obtain a copy of the License at\n\n   http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing,\n software distributed under the License is distributed on an\n \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n KIND, either express or implied.  See the License for the\n specific language governing permissions and limitations\n under the License.\n\n-->\n\n<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 3.2//EN\">\n<html>\n    <head>\n        <title></title>\n    </head>\n    <body>\n        These are not the pages you're looking for.\n    </body>\n</html>\n"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/resources/healthmonitor-create.json",
    "content": "{\"healthMonitor\":{\"type\":\"CONNECT\",\"delay\":3599,\"timeout\":30,\"attemptsBeforeDeactivation\":2}}"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/resources/healthmonitor-get-deleted.json",
    "content": "{\n    \"healthMonitor\": {\n    }\n}"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/resources/healthmonitor-get.json",
    "content": "{\n    \"healthMonitor\": {\n        \"type\": \"CONNECT\",\n        \"delay\": 3599,\n        \"timeout\": 30,\n        \"attemptsBeforeDeactivation\": 2\n    }\n}"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/resources/loadbalancer-create.json",
    "content": "{\"loadBalancer\":{\"virtualIps\":[{\"type\":\"PUBLIC\"}],\"name\":\"sample-loadbalancer\",\"protocol\":\"HTTP\",\"port\":80,\"algorithm\":\"RANDOM\",\"nodes\":[{\"address\":\"10.1.1.1\",\"port\":80,\"condition\":\"ENABLED\"},{\"address\":\"10.1.1.2\",\"port\":80,\"condition\":\"ENABLED\"}]}}"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/resources/loadbalancer-get-deleted.json",
    "content": "{\"loadBalancer\":{\"name\":\"adriancole-LON\",\"id\":4865,\"status\":\"DELETED\",\"created\":{\"time\":\"2011-12-05T18:03:23Z\"},\"updated\":{\"time\":\"2011-12-05T18:04:04Z\"},\"nodeCount\":0}}"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/resources/loadbalancer-get.json",
    "content": "{\n    \"loadBalancer\": {\n        \"id\": 2000,\n        \"name\": \"sample-loadbalancer\",\n        \"protocol\": \"HTTP\",\n        \"port\": 80,\n        \"algorithm\": \"RANDOM\",\n        \"status\": \"ACTIVE\",\n        \"cluster\": {\n            \"name\": \"c1.dfw1\"\n        },\n        \"nodes\": [\n            {\n                \"id\": 1041,\n                \"address\": \"10.1.1.1\",\n                \"port\": 80,\n                \"condition\": \"ENABLED\",\n                \"status\": \"ONLINE\"\n            },\n            {\n                \"id\": 1411,\n                \"address\": \"10.1.1.2\",\n                \"port\": 80,\n                \"condition\": \"ENABLED\",\n                \"status\": \"ONLINE\"\n            }\n        ],\n        \"created\": {\n            \"time\": \"2010-11-30T03:23:42Z\"\n        },\n        \"healthMonitor\": {\n            \"type\": \"CONNECT\",\n            \"delay\": 10,\n            \"timeout\": 5,\n            \"attemptsBeforeDeactivation\": 2\n        },\n        \"sslTermination\": {\n            \"enabled\": true,\n            \"secureTrafficOnly\": false,\n            \"securePort\": 443\n        },\n        \"sessionPersistence\": {\n            \"persistenceType\": \"HTTP_COOKIE\"\n        },\n        \"virtualIps\": [\n            {\n                \"id\": 1000,\n                \"address\": \"206.10.10.210\",\n                \"type\": \"PUBLIC\",\n                \"ipVersion\": \"IPV4\"\n            },\n            {\n                \"id\": 1001,\n                \"address\": \"2001:4800:7901:0000:9a32:3c2a:0000:0001\",\n                \"type\": \"PUBLIC\",\n                \"ipVersion\": \"IPV6\"\n            }\n        ],\n        \"sourceAddresses\": {\n            \"ipv6Public\": \"2001:4800:7901::5/64\",\n            \"ipv4Servicenet\": \"10.183.250.137\",\n            \"ipv4Public\": \"174.143.139.137\"\n        },\n        \"updated\": {\n            \"time\": \"2010-11-30T03:23:44Z\"\n        },\n        \"halfClosed\": false,\n        \"accessList\": [\n            {\n                \"address\": \"1.2.3.4/32\",\n                \"id\": 22215,\n                \"type\": \"DENY\"\n            },\n            {\n                \"address\": \"12.0.0.0/8\",\n                \"id\": 22217,\n                \"type\": \"ALLOW\"\n            }\n        ],\n        \"connectionThrottle\": {\n            \"minConnections\": 10,\n            \"maxConnections\": 100,\n            \"maxConnectionRate\": 50,\n            \"rateInterval\": 60\n        },\n        \"connectionLogging\": {\n            \"enabled\": true\n        },\n        \"contentCaching\": {\n            \"enabled\": true\n        },\n        \"metadata\": [\n            {\n                \"id\": 1,\n                \"key\": \"color\",\n                \"value\": \"red\"\n            },\n            {\n                \"id\": 2,\n                \"key\": \"label\",\n                \"value\": \"web-load-balancer\"\n            }\n        ]\n    }\n}"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/resources/loadbalancer-update.json",
    "content": "{\"loadBalancer\":{\"name\":\"foo\",\"protocol\":\"HTTPS\",\"port\":443,\"algorithm\":\"RANDOM\"}}"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/resources/loadbalancers-list.json",
    "content": "{\n    \"loadBalancers\":[\n        {\n            \"name\":\"lb-site1\",\n            \"id\":\"71\",\n            \"protocol\":\"HTTP\",\n            \"port\":\"80\",\n            \"algorithm\":\"RANDOM\",\n            \"status\":\"ACTIVE\",\n            \"virtualIps\":[\n                {\n                    \"id\":\"403\",\n                    \"address\":\"206.55.130.1\",\n                    \"type\":\"PUBLIC\",\n                    \"ipVersion\":\"IPV4\"\n                }\n            ],\n            \"created\":{\n                \"time\":\"2010-11-30T03:23:42Z\"\n            },\n            \"updated\":{\n                \"time\":\"2010-11-30T03:23:44Z\"\n            },\n            \"nodeCount\":1\n        },\n        {\n            \"name\":\"lb-site2\",\n            \"id\":\"166\",\n            \"protocol\":\"HTTP\",\n            \"port\":\"80\",\n            \"algorithm\":\"RANDOM\",\n            \"status\":\"ACTIVE\",\n            \"virtualIps\":[\n                {\n                    \"id\":\"401\",\n                    \"address\":\"206.55.130.2\",\n                    \"type\":\"PUBLIC\",\n                    \"ipVersion\":\"IPV4\"\n                }\n            ],\n            \"created\":{\n                \"time\":\"2010-11-30T03:23:42Z\"\n            },\n            \"updated\":{\n                \"time\":\"2010-11-30T03:23:44Z\"\n            },\n            \"nodeCount\":1\n        }\n    ]\n}"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/resources/metadata-create.json",
    "content": "{\"metadata\":[{\"key\":\"os\",\"value\":\"ubuntu\"},{\"key\":\"color\",\"value\":\"red\"},{\"key\":\"label\",\"value\":\"web-load-balancer\"}]}"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/resources/metadata-list.json",
    "content": "{\n    \"metadata\": [\n        {\n            \"id\": \"1\",\n            \"key\": \"color\",\n            \"value\": \"red\"\n        },\n        {\n            \"id\": \"2\",\n            \"key\": \"label\",\n            \"value\": \"web-load-balancer\"\n        },\n        {\n            \"id\": \"3\",\n            \"key\": \"os\",\n            \"value\": \"ubuntu\"\n        }\n    ]\n}"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/resources/node-get.json",
    "content": "{\n    \"node\": {\n        \"id\": 410,\n        \"address\": \"10.1.1.1\",\n        \"port\": 80,\n        \"condition\": \"ENABLED\",\n        \"status\": \"ONLINE\",\n        \"weight\": 12,\n        \"type\": \"PRIMARY\",\n        \"metadata\": [\n            {\n                \"id\": 1,\n                \"key\": \"color\",\n                \"value\": \"red\"\n            },\n            {\n                \"id\": 2,\n                \"key\": \"label\",\n                \"value\": \"web-load-balancer\"\n            }\n        ]\n    }\n}"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/resources/node-update.json",
    "content": "{\"node\":{\"condition\":\"DISABLED\",\"type\":\"SECONDARY\",\"weight\":20}}"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/resources/nodes-add.json",
    "content": "{\"nodes\":[{\"address\":\"10.1.1.1\",\"port\":80,\"condition\":\"ENABLED\",\"weight\":3},{\"address\":\"10.1.1.2\",\"port\":80,\"condition\":\"ENABLED\",\"type\":\"SECONDARY\",\"weight\":8},{\"address\":\"10.1.1.3\",\"port\":80,\"condition\":\"DISABLED\",\"weight\":12}]}"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/resources/nodes-list.json",
    "content": "{\n    \"nodes\": [\n        {\n            \"id\":\"410\",\n            \"address\":\"10.1.1.1\",\n            \"port\":80,\n            \"condition\":\"ENABLED\",\n            \"status\":\"ONLINE\",\n            \"weight\":3\n        },\n        {\n            \"id\":\"411\",\n            \"address\":\"10.1.1.2\",\n            \"port\":80,\n            \"condition\":\"ENABLED\",\n            \"status\":\"ONLINE\",\n            \"weight\":8\n        },\n        {\n            \"id\":\"412\",\n            \"address\":\"10.1.1.3\",\n            \"port\":80,\n            \"condition\":\"DISABLED\",\n            \"status\":\"ONLINE\",\n            \"weight\":12\n        }\n    ]\n}"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/resources/report-algorithms-list.json",
    "content": "{\n  \"algorithms\": [\n    {\n      \"name\": \"LEAST_CONNECTIONS\"\n    },\n    {\n      \"name\": \"RANDOM\"\n    },\n    {\n      \"name\": \"ROUND_ROBIN\"\n    },\n    {\n      \"name\": \"WEIGHTED_LEAST_CONNECTIONS\"\n    },\n    {\n      \"name\": \"WEIGHTED_ROUND_ROBIN\"\n    }\n  ]\n}"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/resources/report-billable-list.json",
    "content": "{\n  \"loadBalancers\": [\n    {\n      \"name\": \"jclouds-app\",\n      \"id\": 85901,\n      \"protocol\": \"HTTP\",\n      \"port\": 80,\n      \"algorithm\": \"WEIGHTED_LEAST_CONNECTIONS\",\n      \"status\": \"ACTIVE\",\n      \"timeout\": 30,\n      \"created\": {\n        \"time\": \"2012-12-24T18:13:44Z\"\n      },\n      \"virtualIps\": [\n        {\n          \"address\": \"166.78.34.87\",\n          \"id\": 5557,\n          \"type\": \"PUBLIC\",\n          \"ipVersion\": \"IPV4\"\n        },\n        {\n          \"address\": \"2001:4800:7901:0000:9a32:3c2a:0000:0001\",\n          \"id\": 9080119,\n          \"type\": \"PUBLIC\",\n          \"ipVersion\": \"IPV6\"\n        }\n      ],\n      \"updated\": {\n        \"time\": \"2013-01-24T17:35:56Z\"\n      },\n      \"nodeCount\": 1\n    },\n    {\n      \"name\": \"jclouds-app\",\n      \"id\": 90903,\n      \"protocol\": \"HTTP\",\n      \"port\": 80,\n      \"algorithm\": \"WEIGHTED_LEAST_CONNECTIONS\",\n      \"status\": \"ACTIVE\",\n      \"timeout\": 30,\n      \"created\": {\n        \"time\": \"2013-01-20T20:53:29Z\"\n      },\n      \"virtualIps\": [\n        {\n          \"address\": \"166.78.34.184\",\n          \"id\": 5751,\n          \"type\": \"PUBLIC\",\n          \"ipVersion\": \"IPV4\"\n        },\n        {\n          \"address\": \"2001:4800:7901:0000:9a32:3c2a:0000:0002\",\n          \"id\": 9080915,\n          \"type\": \"PUBLIC\",\n          \"ipVersion\": \"IPV6\"\n        }\n      ],\n      \"updated\": {\n        \"time\": \"2013-01-24T21:32:42Z\"\n      },\n      \"nodeCount\": 2\n    }\n  ]\n}"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/resources/report-historical-get.json",
    "content": "{\n  \"accountId\": 717071,\n  \"accountUsage\": {\n    \"accountUsageRecords\": [\n      {\n        \"startTime\": \"2013-01-25T00:00:28Z\",\n        \"numLoadBalancers\": 2,\n        \"numPublicVips\": 2,\n        \"numServicenetVips\": 0\n      }\n    ],\n    \"links\": []\n  },\n  \"loadBalancerUsages\": [\n    {\n      \"loadBalancerId\": 85901,\n      \"loadBalancerName\": \"jclouds-app\",\n      \"links\": [],\n      \"loadBalancerUsageRecords\": [\n        {\n          \"id\": 17888041,\n          \"startTime\": \"2013-01-25T00:00:00Z\",\n          \"endTime\": \"2013-01-25T01:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 0,\n          \"outgoingTransfer\": 0,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 17895283,\n          \"startTime\": \"2013-01-25T01:00:00Z\",\n          \"endTime\": \"2013-01-25T02:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 0,\n          \"outgoingTransfer\": 0,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 17902527,\n          \"startTime\": \"2013-01-25T02:00:00Z\",\n          \"endTime\": \"2013-01-25T03:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 0,\n          \"outgoingTransfer\": 0,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 17909761,\n          \"startTime\": \"2013-01-25T03:00:00Z\",\n          \"endTime\": \"2013-01-25T04:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 0,\n          \"outgoingTransfer\": 0,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 17916995,\n          \"startTime\": \"2013-01-25T04:00:00Z\",\n          \"endTime\": \"2013-01-25T05:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 0,\n          \"outgoingTransfer\": 0,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 17924231,\n          \"startTime\": \"2013-01-25T05:00:00Z\",\n          \"endTime\": \"2013-01-25T06:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 0,\n          \"outgoingTransfer\": 0,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 17931467,\n          \"startTime\": \"2013-01-25T06:00:00Z\",\n          \"endTime\": \"2013-01-25T07:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 0,\n          \"outgoingTransfer\": 0,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 17938703,\n          \"startTime\": \"2013-01-25T07:00:00Z\",\n          \"endTime\": \"2013-01-25T08:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 0,\n          \"outgoingTransfer\": 0,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 17945951,\n          \"startTime\": \"2013-01-25T08:00:00Z\",\n          \"endTime\": \"2013-01-25T09:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 0,\n          \"outgoingTransfer\": 0,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 17953175,\n          \"startTime\": \"2013-01-25T09:00:00Z\",\n          \"endTime\": \"2013-01-25T10:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 0,\n          \"outgoingTransfer\": 0,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 11,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 17960399,\n          \"startTime\": \"2013-01-25T10:00:00Z\",\n          \"endTime\": \"2013-01-25T11:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 0,\n          \"outgoingTransfer\": 0,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 17967623,\n          \"startTime\": \"2013-01-25T11:00:00Z\",\n          \"endTime\": \"2013-01-25T12:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 0,\n          \"outgoingTransfer\": 0,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 17974855,\n          \"startTime\": \"2013-01-25T12:00:00Z\",\n          \"endTime\": \"2013-01-25T13:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 0,\n          \"outgoingTransfer\": 0,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 17982103,\n          \"startTime\": \"2013-01-25T13:00:00Z\",\n          \"endTime\": \"2013-01-25T14:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 0,\n          \"outgoingTransfer\": 0,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 17989349,\n          \"startTime\": \"2013-01-25T14:00:00Z\",\n          \"endTime\": \"2013-01-25T15:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 0,\n          \"outgoingTransfer\": 0,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 17996607,\n          \"startTime\": \"2013-01-25T15:00:00Z\",\n          \"endTime\": \"2013-01-25T16:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 46,\n          \"outgoingTransfer\": 368,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 18003887,\n          \"startTime\": \"2013-01-25T16:00:00Z\",\n          \"endTime\": \"2013-01-25T17:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 0,\n          \"outgoingTransfer\": 0,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 18011157,\n          \"startTime\": \"2013-01-25T17:00:00Z\",\n          \"endTime\": \"2013-01-25T18:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 0,\n          \"outgoingTransfer\": 0,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 18018437,\n          \"startTime\": \"2013-01-25T18:00:00Z\",\n          \"endTime\": \"2013-01-25T19:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 0,\n          \"outgoingTransfer\": 0,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 18025709,\n          \"startTime\": \"2013-01-25T19:00:00Z\",\n          \"endTime\": \"2013-01-25T20:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 0,\n          \"outgoingTransfer\": 0,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 18033013,\n          \"startTime\": \"2013-01-25T20:00:00Z\",\n          \"endTime\": \"2013-01-25T21:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 847,\n          \"outgoingTransfer\": 2328,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 18040267,\n          \"startTime\": \"2013-01-25T21:00:00Z\",\n          \"endTime\": \"2013-01-25T22:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 0,\n          \"outgoingTransfer\": 0,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 18047493,\n          \"startTime\": \"2013-01-25T22:00:00Z\",\n          \"endTime\": \"2013-01-25T23:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 0,\n          \"outgoingTransfer\": 0,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 18054719,\n          \"startTime\": \"2013-01-25T23:00:00Z\",\n          \"endTime\": \"2013-01-26T00:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 0,\n          \"outgoingTransfer\": 0,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        }\n      ]\n    },\n    {\n      \"loadBalancerId\": 90903,\n      \"loadBalancerName\": \"jclouds-app\",\n      \"links\": [],\n      \"loadBalancerUsageRecords\": [\n        {\n          \"id\": 17887647,\n          \"startTime\": \"2013-01-25T00:00:00Z\",\n          \"endTime\": \"2013-01-25T01:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 0,\n          \"outgoingTransfer\": 0,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 17894889,\n          \"startTime\": \"2013-01-25T01:00:00Z\",\n          \"endTime\": \"2013-01-25T02:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 0,\n          \"outgoingTransfer\": 0,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 17902133,\n          \"startTime\": \"2013-01-25T02:00:00Z\",\n          \"endTime\": \"2013-01-25T03:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 0,\n          \"outgoingTransfer\": 0,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 17909367,\n          \"startTime\": \"2013-01-25T03:00:00Z\",\n          \"endTime\": \"2013-01-25T04:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 0,\n          \"outgoingTransfer\": 0,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 17916601,\n          \"startTime\": \"2013-01-25T04:00:00Z\",\n          \"endTime\": \"2013-01-25T05:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 0,\n          \"outgoingTransfer\": 0,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 17923837,\n          \"startTime\": \"2013-01-25T05:00:00Z\",\n          \"endTime\": \"2013-01-25T06:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 0,\n          \"outgoingTransfer\": 0,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 17931073,\n          \"startTime\": \"2013-01-25T06:00:00Z\",\n          \"endTime\": \"2013-01-25T07:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 0,\n          \"outgoingTransfer\": 0,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 17938309,\n          \"startTime\": \"2013-01-25T07:00:00Z\",\n          \"endTime\": \"2013-01-25T08:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 0,\n          \"outgoingTransfer\": 0,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 17945557,\n          \"startTime\": \"2013-01-25T08:00:00Z\",\n          \"endTime\": \"2013-01-25T09:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 0,\n          \"outgoingTransfer\": 0,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 17952781,\n          \"startTime\": \"2013-01-25T09:00:00Z\",\n          \"endTime\": \"2013-01-25T10:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 0,\n          \"outgoingTransfer\": 0,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 17960005,\n          \"startTime\": \"2013-01-25T10:00:00Z\",\n          \"endTime\": \"2013-01-25T11:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 0,\n          \"outgoingTransfer\": 0,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 17967229,\n          \"startTime\": \"2013-01-25T11:00:00Z\",\n          \"endTime\": \"2013-01-25T12:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 0,\n          \"outgoingTransfer\": 0,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 17974461,\n          \"startTime\": \"2013-01-25T12:00:00Z\",\n          \"endTime\": \"2013-01-25T13:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 0,\n          \"outgoingTransfer\": 0,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 17981709,\n          \"startTime\": \"2013-01-25T13:00:00Z\",\n          \"endTime\": \"2013-01-25T14:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 0,\n          \"outgoingTransfer\": 0,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 17988955,\n          \"startTime\": \"2013-01-25T14:00:00Z\",\n          \"endTime\": \"2013-01-25T15:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 0,\n          \"outgoingTransfer\": 0,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 17996213,\n          \"startTime\": \"2013-01-25T15:00:00Z\",\n          \"endTime\": \"2013-01-25T16:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 46,\n          \"outgoingTransfer\": 306,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 18003493,\n          \"startTime\": \"2013-01-25T16:00:00Z\",\n          \"endTime\": \"2013-01-25T17:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 0,\n          \"outgoingTransfer\": 0,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 18010763,\n          \"startTime\": \"2013-01-25T17:00:00Z\",\n          \"endTime\": \"2013-01-25T18:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 0,\n          \"outgoingTransfer\": 0,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 18018043,\n          \"startTime\": \"2013-01-25T18:00:00Z\",\n          \"endTime\": \"2013-01-25T19:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 0,\n          \"outgoingTransfer\": 0,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 18025315,\n          \"startTime\": \"2013-01-25T19:00:00Z\",\n          \"endTime\": \"2013-01-25T20:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 0,\n          \"outgoingTransfer\": 0,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 18032619,\n          \"startTime\": \"2013-01-25T20:00:00Z\",\n          \"endTime\": \"2013-01-25T21:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 427,\n          \"outgoingTransfer\": 662,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 18039873,\n          \"startTime\": \"2013-01-25T21:00:00Z\",\n          \"endTime\": \"2013-01-25T22:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 0,\n          \"outgoingTransfer\": 0,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 18047099,\n          \"startTime\": \"2013-01-25T22:00:00Z\",\n          \"endTime\": \"2013-01-25T23:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 0,\n          \"outgoingTransfer\": 0,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        },\n        {\n          \"id\": 18054325,\n          \"startTime\": \"2013-01-25T23:00:00Z\",\n          \"endTime\": \"2013-01-26T00:00:00Z\",\n          \"numVips\": 1,\n          \"incomingTransfer\": 0,\n          \"outgoingTransfer\": 0,\n          \"incomingTransferSsl\": 0,\n          \"outgoingTransferSsl\": 0,\n          \"vipType\": \"PUBLIC\",\n          \"averageNumConnections\": 0.0,\n          \"averageNumConnectionsSsl\": 0.0,\n          \"numPolls\": 12,\n          \"sslMode\": \"OFF\"\n        }\n      ]\n    }\n  ]\n}"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/resources/report-loadbalancerstats-get.json",
    "content": "{\n  \"connectTimeOut\": 2,\n  \"connectError\": 0,\n  \"connectFailure\": 0,\n  \"dataTimedOut\": 10,\n  \"keepAliveTimedOut\": 0,\n  \"maxConn\": 22\n}"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/resources/report-loadbalancerusage-list.json",
    "content": "{\n  \"links\": [],\n  \"loadBalancerUsageRecords\": [\n    {\n      \"id\": 17887647,\n      \"startTime\": \"2013-01-25T00:00:00Z\",\n      \"endTime\": \"2013-01-25T01:00:00Z\",\n      \"numVips\": 1,\n      \"incomingTransfer\": 0,\n      \"outgoingTransfer\": 0,\n      \"incomingTransferSsl\": 0,\n      \"outgoingTransferSsl\": 0,\n      \"vipType\": \"PUBLIC\",\n      \"averageNumConnections\": 0.0,\n      \"averageNumConnectionsSsl\": 0.0,\n      \"numPolls\": 12,\n      \"sslMode\": \"OFF\"\n    },\n    {\n      \"id\": 17894889,\n      \"startTime\": \"2013-01-25T01:00:00Z\",\n      \"endTime\": \"2013-01-25T02:00:00Z\",\n      \"numVips\": 1,\n      \"incomingTransfer\": 0,\n      \"outgoingTransfer\": 0,\n      \"incomingTransferSsl\": 0,\n      \"outgoingTransferSsl\": 0,\n      \"vipType\": \"PUBLIC\",\n      \"averageNumConnections\": 0.0,\n      \"averageNumConnectionsSsl\": 0.0,\n      \"numPolls\": 12,\n      \"sslMode\": \"OFF\"\n    },\n    {\n      \"id\": 17902133,\n      \"startTime\": \"2013-01-25T02:00:00Z\",\n      \"endTime\": \"2013-01-25T03:00:00Z\",\n      \"numVips\": 1,\n      \"incomingTransfer\": 0,\n      \"outgoingTransfer\": 0,\n      \"incomingTransferSsl\": 0,\n      \"outgoingTransferSsl\": 0,\n      \"vipType\": \"PUBLIC\",\n      \"averageNumConnections\": 0.0,\n      \"averageNumConnectionsSsl\": 0.0,\n      \"numPolls\": 12,\n      \"sslMode\": \"OFF\"\n    },\n    {\n      \"id\": 17909367,\n      \"startTime\": \"2013-01-25T03:00:00Z\",\n      \"endTime\": \"2013-01-25T04:00:00Z\",\n      \"numVips\": 1,\n      \"incomingTransfer\": 0,\n      \"outgoingTransfer\": 0,\n      \"incomingTransferSsl\": 0,\n      \"outgoingTransferSsl\": 0,\n      \"vipType\": \"PUBLIC\",\n      \"averageNumConnections\": 0.0,\n      \"averageNumConnectionsSsl\": 0.0,\n      \"numPolls\": 12,\n      \"sslMode\": \"OFF\"\n    },\n    {\n      \"id\": 17916601,\n      \"startTime\": \"2013-01-25T04:00:00Z\",\n      \"endTime\": \"2013-01-25T05:00:00Z\",\n      \"numVips\": 1,\n      \"incomingTransfer\": 0,\n      \"outgoingTransfer\": 0,\n      \"incomingTransferSsl\": 0,\n      \"outgoingTransferSsl\": 0,\n      \"vipType\": \"PUBLIC\",\n      \"averageNumConnections\": 0.0,\n      \"averageNumConnectionsSsl\": 0.0,\n      \"numPolls\": 12,\n      \"sslMode\": \"OFF\"\n    },\n    {\n      \"id\": 17923837,\n      \"startTime\": \"2013-01-25T05:00:00Z\",\n      \"endTime\": \"2013-01-25T06:00:00Z\",\n      \"numVips\": 1,\n      \"incomingTransfer\": 0,\n      \"outgoingTransfer\": 0,\n      \"incomingTransferSsl\": 0,\n      \"outgoingTransferSsl\": 0,\n      \"vipType\": \"PUBLIC\",\n      \"averageNumConnections\": 0.0,\n      \"averageNumConnectionsSsl\": 0.0,\n      \"numPolls\": 12,\n      \"sslMode\": \"OFF\"\n    },\n    {\n      \"id\": 17931073,\n      \"startTime\": \"2013-01-25T06:00:00Z\",\n      \"endTime\": \"2013-01-25T07:00:00Z\",\n      \"numVips\": 1,\n      \"incomingTransfer\": 0,\n      \"outgoingTransfer\": 0,\n      \"incomingTransferSsl\": 0,\n      \"outgoingTransferSsl\": 0,\n      \"vipType\": \"PUBLIC\",\n      \"averageNumConnections\": 0.0,\n      \"averageNumConnectionsSsl\": 0.0,\n      \"numPolls\": 12,\n      \"sslMode\": \"OFF\"\n    },\n    {\n      \"id\": 17938309,\n      \"startTime\": \"2013-01-25T07:00:00Z\",\n      \"endTime\": \"2013-01-25T08:00:00Z\",\n      \"numVips\": 1,\n      \"incomingTransfer\": 0,\n      \"outgoingTransfer\": 0,\n      \"incomingTransferSsl\": 0,\n      \"outgoingTransferSsl\": 0,\n      \"vipType\": \"PUBLIC\",\n      \"averageNumConnections\": 0.0,\n      \"averageNumConnectionsSsl\": 0.0,\n      \"numPolls\": 12,\n      \"sslMode\": \"OFF\"\n    },\n    {\n      \"id\": 17945557,\n      \"startTime\": \"2013-01-25T08:00:00Z\",\n      \"endTime\": \"2013-01-25T09:00:00Z\",\n      \"numVips\": 1,\n      \"incomingTransfer\": 0,\n      \"outgoingTransfer\": 0,\n      \"incomingTransferSsl\": 0,\n      \"outgoingTransferSsl\": 0,\n      \"vipType\": \"PUBLIC\",\n      \"averageNumConnections\": 0.0,\n      \"averageNumConnectionsSsl\": 0.0,\n      \"numPolls\": 12,\n      \"sslMode\": \"OFF\"\n    },\n    {\n      \"id\": 17952781,\n      \"startTime\": \"2013-01-25T09:00:00Z\",\n      \"endTime\": \"2013-01-25T10:00:00Z\",\n      \"numVips\": 1,\n      \"incomingTransfer\": 0,\n      \"outgoingTransfer\": 0,\n      \"incomingTransferSsl\": 0,\n      \"outgoingTransferSsl\": 0,\n      \"vipType\": \"PUBLIC\",\n      \"averageNumConnections\": 0.0,\n      \"averageNumConnectionsSsl\": 0.0,\n      \"numPolls\": 12,\n      \"sslMode\": \"OFF\"\n    },\n    {\n      \"id\": 17960005,\n      \"startTime\": \"2013-01-25T10:00:00Z\",\n      \"endTime\": \"2013-01-25T11:00:00Z\",\n      \"numVips\": 1,\n      \"incomingTransfer\": 0,\n      \"outgoingTransfer\": 0,\n      \"incomingTransferSsl\": 0,\n      \"outgoingTransferSsl\": 0,\n      \"vipType\": \"PUBLIC\",\n      \"averageNumConnections\": 0.0,\n      \"averageNumConnectionsSsl\": 0.0,\n      \"numPolls\": 12,\n      \"sslMode\": \"OFF\"\n    },\n    {\n      \"id\": 17967229,\n      \"startTime\": \"2013-01-25T11:00:00Z\",\n      \"endTime\": \"2013-01-25T12:00:00Z\",\n      \"numVips\": 1,\n      \"incomingTransfer\": 0,\n      \"outgoingTransfer\": 0,\n      \"incomingTransferSsl\": 0,\n      \"outgoingTransferSsl\": 0,\n      \"vipType\": \"PUBLIC\",\n      \"averageNumConnections\": 0.0,\n      \"averageNumConnectionsSsl\": 0.0,\n      \"numPolls\": 12,\n      \"sslMode\": \"OFF\"\n    },\n    {\n      \"id\": 17974461,\n      \"startTime\": \"2013-01-25T12:00:00Z\",\n      \"endTime\": \"2013-01-25T13:00:00Z\",\n      \"numVips\": 1,\n      \"incomingTransfer\": 0,\n      \"outgoingTransfer\": 0,\n      \"incomingTransferSsl\": 0,\n      \"outgoingTransferSsl\": 0,\n      \"vipType\": \"PUBLIC\",\n      \"averageNumConnections\": 0.0,\n      \"averageNumConnectionsSsl\": 0.0,\n      \"numPolls\": 12,\n      \"sslMode\": \"OFF\"\n    },\n    {\n      \"id\": 17981709,\n      \"startTime\": \"2013-01-25T13:00:00Z\",\n      \"endTime\": \"2013-01-25T14:00:00Z\",\n      \"numVips\": 1,\n      \"incomingTransfer\": 0,\n      \"outgoingTransfer\": 0,\n      \"incomingTransferSsl\": 0,\n      \"outgoingTransferSsl\": 0,\n      \"vipType\": \"PUBLIC\",\n      \"averageNumConnections\": 0.0,\n      \"averageNumConnectionsSsl\": 0.0,\n      \"numPolls\": 12,\n      \"sslMode\": \"OFF\"\n    },\n    {\n      \"id\": 17988955,\n      \"startTime\": \"2013-01-25T14:00:00Z\",\n      \"endTime\": \"2013-01-25T15:00:00Z\",\n      \"numVips\": 1,\n      \"incomingTransfer\": 0,\n      \"outgoingTransfer\": 0,\n      \"incomingTransferSsl\": 0,\n      \"outgoingTransferSsl\": 0,\n      \"vipType\": \"PUBLIC\",\n      \"averageNumConnections\": 0.0,\n      \"averageNumConnectionsSsl\": 0.0,\n      \"numPolls\": 12,\n      \"sslMode\": \"OFF\"\n    },\n    {\n      \"id\": 17996213,\n      \"startTime\": \"2013-01-25T15:00:00Z\",\n      \"endTime\": \"2013-01-25T16:00:00Z\",\n      \"numVips\": 1,\n      \"incomingTransfer\": 46,\n      \"outgoingTransfer\": 306,\n      \"incomingTransferSsl\": 0,\n      \"outgoingTransferSsl\": 0,\n      \"vipType\": \"PUBLIC\",\n      \"averageNumConnections\": 0.0,\n      \"averageNumConnectionsSsl\": 0.0,\n      \"numPolls\": 12,\n      \"sslMode\": \"OFF\"\n    },\n    {\n      \"id\": 18003493,\n      \"startTime\": \"2013-01-25T16:00:00Z\",\n      \"endTime\": \"2013-01-25T17:00:00Z\",\n      \"numVips\": 1,\n      \"incomingTransfer\": 0,\n      \"outgoingTransfer\": 0,\n      \"incomingTransferSsl\": 0,\n      \"outgoingTransferSsl\": 0,\n      \"vipType\": \"PUBLIC\",\n      \"averageNumConnections\": 0.0,\n      \"averageNumConnectionsSsl\": 0.0,\n      \"numPolls\": 12,\n      \"sslMode\": \"OFF\"\n    },\n    {\n      \"id\": 18010763,\n      \"startTime\": \"2013-01-25T17:00:00Z\",\n      \"endTime\": \"2013-01-25T18:00:00Z\",\n      \"numVips\": 1,\n      \"incomingTransfer\": 0,\n      \"outgoingTransfer\": 0,\n      \"incomingTransferSsl\": 0,\n      \"outgoingTransferSsl\": 0,\n      \"vipType\": \"PUBLIC\",\n      \"averageNumConnections\": 0.0,\n      \"averageNumConnectionsSsl\": 0.0,\n      \"numPolls\": 12,\n      \"sslMode\": \"OFF\"\n    },\n    {\n      \"id\": 18018043,\n      \"startTime\": \"2013-01-25T18:00:00Z\",\n      \"endTime\": \"2013-01-25T19:00:00Z\",\n      \"numVips\": 1,\n      \"incomingTransfer\": 0,\n      \"outgoingTransfer\": 0,\n      \"incomingTransferSsl\": 0,\n      \"outgoingTransferSsl\": 0,\n      \"vipType\": \"PUBLIC\",\n      \"averageNumConnections\": 0.0,\n      \"averageNumConnectionsSsl\": 0.0,\n      \"numPolls\": 12,\n      \"sslMode\": \"OFF\"\n    },\n    {\n      \"id\": 18025315,\n      \"startTime\": \"2013-01-25T19:00:00Z\",\n      \"endTime\": \"2013-01-25T20:00:00Z\",\n      \"numVips\": 1,\n      \"incomingTransfer\": 0,\n      \"outgoingTransfer\": 0,\n      \"incomingTransferSsl\": 0,\n      \"outgoingTransferSsl\": 0,\n      \"vipType\": \"PUBLIC\",\n      \"averageNumConnections\": 0.0,\n      \"averageNumConnectionsSsl\": 0.0,\n      \"numPolls\": 12,\n      \"sslMode\": \"OFF\"\n    },\n    {\n      \"id\": 18032619,\n      \"startTime\": \"2013-01-25T20:00:00Z\",\n      \"endTime\": \"2013-01-25T21:00:00Z\",\n      \"numVips\": 1,\n      \"incomingTransfer\": 427,\n      \"outgoingTransfer\": 662,\n      \"incomingTransferSsl\": 0,\n      \"outgoingTransferSsl\": 0,\n      \"vipType\": \"PUBLIC\",\n      \"averageNumConnections\": 0.0,\n      \"averageNumConnectionsSsl\": 0.0,\n      \"numPolls\": 12,\n      \"sslMode\": \"OFF\"\n    },\n    {\n      \"id\": 18039873,\n      \"startTime\": \"2013-01-25T21:00:00Z\",\n      \"endTime\": \"2013-01-25T22:00:00Z\",\n      \"numVips\": 1,\n      \"incomingTransfer\": 0,\n      \"outgoingTransfer\": 0,\n      \"incomingTransferSsl\": 0,\n      \"outgoingTransferSsl\": 0,\n      \"vipType\": \"PUBLIC\",\n      \"averageNumConnections\": 0.0,\n      \"averageNumConnectionsSsl\": 0.0,\n      \"numPolls\": 12,\n      \"sslMode\": \"OFF\"\n    },\n    {\n      \"id\": 18047099,\n      \"startTime\": \"2013-01-25T22:00:00Z\",\n      \"endTime\": \"2013-01-25T23:00:00Z\",\n      \"numVips\": 1,\n      \"incomingTransfer\": 0,\n      \"outgoingTransfer\": 0,\n      \"incomingTransferSsl\": 0,\n      \"outgoingTransferSsl\": 0,\n      \"vipType\": \"PUBLIC\",\n      \"averageNumConnections\": 0.0,\n      \"averageNumConnectionsSsl\": 0.0,\n      \"numPolls\": 12,\n      \"sslMode\": \"OFF\"\n    },\n    {\n      \"id\": 18054325,\n      \"startTime\": \"2013-01-25T23:00:00Z\",\n      \"endTime\": \"2013-01-26T00:00:00Z\",\n      \"numVips\": 1,\n      \"incomingTransfer\": 0,\n      \"outgoingTransfer\": 0,\n      \"incomingTransferSsl\": 0,\n      \"outgoingTransferSsl\": 0,\n      \"vipType\": \"PUBLIC\",\n      \"averageNumConnections\": 0.0,\n      \"averageNumConnectionsSsl\": 0.0,\n      \"numPolls\": 12,\n      \"sslMode\": \"OFF\"\n    },\n    {\n      \"id\": 18061573,\n      \"startTime\": \"2013-01-26T00:00:00Z\",\n      \"endTime\": \"2013-01-26T01:00:00Z\",\n      \"numVips\": 1,\n      \"incomingTransfer\": 0,\n      \"outgoingTransfer\": 0,\n      \"incomingTransferSsl\": 0,\n      \"outgoingTransferSsl\": 0,\n      \"vipType\": \"PUBLIC\",\n      \"averageNumConnections\": 0.0,\n      \"averageNumConnectionsSsl\": 0.0,\n      \"numPolls\": 12,\n      \"sslMode\": \"OFF\"\n    }\n  ]\n}"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/resources/report-protocols-list.json",
    "content": "{\n  \"protocols\": [\n    {\n      \"name\": \"DNS_TCP\",\n      \"port\": 53\n    },\n    {\n      \"name\": \"DNS_UDP\",\n      \"port\": 53\n    },\n    {\n      \"name\": \"FTP\",\n      \"port\": 21\n    },\n    {\n      \"name\": \"HTTP\",\n      \"port\": 80\n    },\n    {\n      \"name\": \"HTTPS\",\n      \"port\": 443\n    },\n    {\n      \"name\": \"IMAPS\",\n      \"port\": 993\n    },\n    {\n      \"name\": \"IMAPv2\",\n      \"port\": 143\n    },\n    {\n      \"name\": \"IMAPv3\",\n      \"port\": 220\n    },\n    {\n      \"name\": \"IMAPv4\",\n      \"port\": 143\n    },\n    {\n      \"name\": \"LDAP\",\n      \"port\": 389\n    },\n    {\n      \"name\": \"LDAPS\",\n      \"port\": 636\n    },\n    {\n      \"name\": \"MYSQL\",\n      \"port\": 3306\n    },\n    {\n      \"name\": \"POP3\",\n      \"port\": 110\n    },\n    {\n      \"name\": \"POP3S\",\n      \"port\": 995\n    },\n    {\n      \"name\": \"SFTP\",\n      \"port\": 22\n    },\n    {\n      \"name\": \"SMTP\",\n      \"port\": 25\n    },\n    {\n      \"name\": \"TCP\",\n      \"port\": 0\n    },\n    {\n      \"name\": \"TCP_CLIENT_FIRST\",\n      \"port\": 0\n    },\n    {\n      \"name\": \"UDP\",\n      \"port\": 0\n    },\n    {\n      \"name\": \"UDP_STREAM\",\n      \"port\": 0\n    }\n  ]\n}"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/resources/sessionpersistence-create.json",
    "content": "{\"sessionPersistence\":{\"persistenceType\":\"HTTP_COOKIE\"}}"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/resources/sessionpersistence-get-deleted.json",
    "content": "{\n    \"sessionPersistence\": {\n    }\n}"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/resources/sessionpersistence-get.json",
    "content": "{\n    \"sessionPersistence\": {\n        \"persistenceType\": \"HTTP_COOKIE\"\n    }\n}"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/resources/ssltermination-certificate.txt",
    "content": "-----BEGIN CERTIFICATE-----\nMIICATCCAWoCCQCvn3QIv4NQODANBgkqhkiG9w0BAQUFADBFMQswCQYDVQQGEwJB\nVTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50ZXJuZXQgV2lkZ2l0\ncyBQdHkgTHRkMB4XDTEzMDEwMzIxNTMyMloXDTE0MDEwMzIxNTMyMlowRTELMAkG\nA1UEBhMCQVUxEzARBgNVBAgTClNvbWUtU3RhdGUxITAfBgNVBAoTGEludGVybmV0\nIFdpZGdpdHMgUHR5IEx0ZDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAw6IR\ntI/MQdQNsHT2UtUIXUbfu/7uxKqKIlbE6Bj5+lZFvUSrkTFRqgjgUADp2oFUYMRg\nYON8HEv0HzJOBujajUdy1sWQiDykhtlsMQ2KTnhYS7cBM798Dhpt2KzW/iULzTXN\nIum/CjCc7g1l0xxF9CvzPbdCn0obwMd1oecmHpcCAwEAATANBgkqhkiG9w0BAQUF\nAAOBgQAn3gwe8XBCz7mnEJ+qexcqCwXn3vJt2gdrMEWyW8SGI6FW3X01pJZYDuPe\nRhN3aaWzYDB7yKEKvvrWAL0ovcjmc/lbRY0dvX2/SS4UWg4B3Z5rbCK3CemOx4D5\nKz6inaEpLLrCmMBqIlOHTsFyB5Tv/SlCP22eS9C91MsoIJtRKQ==\n-----END CERTIFICATE-----"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/resources/ssltermination-create.json",
    "content": "{\"sslTermination\":{\"certificate\":\"-----BEGIN CERTIFICATE-----\\nMIICATCCAWoCCQCvn3QIv4NQODANBgkqhkiG9w0BAQUFADBFMQswCQYDVQQGEwJB\\nVTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50ZXJuZXQgV2lkZ2l0\\ncyBQdHkgTHRkMB4XDTEzMDEwMzIxNTMyMloXDTE0MDEwMzIxNTMyMlowRTELMAkG\\nA1UEBhMCQVUxEzARBgNVBAgTClNvbWUtU3RhdGUxITAfBgNVBAoTGEludGVybmV0\\nIFdpZGdpdHMgUHR5IEx0ZDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAw6IR\\ntI/MQdQNsHT2UtUIXUbfu/7uxKqKIlbE6Bj5+lZFvUSrkTFRqgjgUADp2oFUYMRg\\nYON8HEv0HzJOBujajUdy1sWQiDykhtlsMQ2KTnhYS7cBM798Dhpt2KzW/iULzTXN\\nIum/CjCc7g1l0xxF9CvzPbdCn0obwMd1oecmHpcCAwEAATANBgkqhkiG9w0BAQUF\\nAAOBgQAn3gwe8XBCz7mnEJ+qexcqCwXn3vJt2gdrMEWyW8SGI6FW3X01pJZYDuPe\\nRhN3aaWzYDB7yKEKvvrWAL0ovcjmc/lbRY0dvX2/SS4UWg4B3Z5rbCK3CemOx4D5\\nKz6inaEpLLrCmMBqIlOHTsFyB5Tv/SlCP22eS9C91MsoIJtRKQ==\\n-----END CERTIFICATE-----\",\"enabled\":true,\"secureTrafficOnly\":false,\"privatekey\":\"-----BEGIN RSA PRIVATE KEY-----\\nMIICWwIBAAKBgQDDohG0j8xB1A2wdPZS1QhdRt+7/u7EqooiVsToGPn6VkW9RKuR\\nMVGqCOBQAOnagVRgxGBg43wcS/QfMk4G6NqNR3LWxZCIPKSG2WwxDYpOeFhLtwEz\\nv3wOGm3YrNb+JQvNNc0i6b8KMJzuDWXTHEX0K/M9t0KfShvAx3Wh5yYelwIDAQAB\\nAoGAdKCD6Z7oaD4gwxeXWZ5C1EjSTOMYOQpqOzp7PNrW/BS+kq0DkxVR2Apen5NL\\n1sXPJbkss9YqQTxOluKIfboHv7J9mUSOisUnFVmjD3l5dik3vAPgIybr7aQvfVbF\\ns93N/WiTICLTwGHOjyYPttCxdKKW1noL5S8Pcni7F1TnlxECQQDunLeBNmtRK8lh\\nwG6FTNMtJSPYXhfhDQfLZj74ITC8sgd0a2Co6AK6v6JADTXujo+HJi6Bo9eqQ49F\\nmom+hXfjAkEA0eOVDQZ4XcWLGfhB/B5mUmHC0m+JAsds1slr+2B8mCGcaAsynPd0\\nj068seY3qsJuguO5OUzati8RQWWSNzu0vQJAIkHLsrheZfP0YJ1hALBL7UJUyB6S\\nLRRS1yfhyHvzZFPm8BbudLGCms8iezGqWYqMHqojqScdsmsqqaKLPhgpYwJAW1AH\\nqIMIGsO2oLXA/066dVzSxXqAwRTB5S/8KoDvs7/rq9gzTNbbfv1iWoMt9LxiF8+6\\n5ZLqFBimCS2HT0BKgQJAEDONaHND9mRLRaSAvh5zXM86FPPbjg9xjSufO6+ZnGwI\\nN5jdN55nrwoA1K4RvDc2tVGo+0EvvU/tmnNKLwEU2Q==\\n-----END RSA PRIVATE KEY-----\",\"intermediateCertificate\":\"-----BEGIN CERTIFICATE-----\\nMIICATCCAWoCCQCvn3QIv4NQODANBgkqhkiG9w0BAQUFADBFMQswCQYDVQQGEwJB\\nVTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50ZXJuZXQgV2lkZ2l0\\ncyBQdHkgTHRkMB4XDTEzMDEwMzIxNTMyMloXDTE0MDEwMzIxNTMyMlowRTELMAkG\\nA1UEBhMCQVUxEzARBgNVBAgTClNvbWUtU3RhdGUxITAfBgNVBAoTGEludGVybmV0\\nIFdpZGdpdHMgUHR5IEx0ZDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAw6IR\\ntI/MQdQNsHT2UtUIXUbfu/7uxKqKIlbE6Bj5+lZFvUSrkTFRqgjgUADp2oFUYMRg\\nYON8HEv0HzJOBujajUdy1sWQiDykhtlsMQ2KTnhYS7cBM798Dhpt2KzW/iULzTXN\\nIum/CjCc7g1l0xxF9CvzPbdCn0obwMd1oecmHpcCAwEAATANBgkqhkiG9w0BAQUF\\nAAOBgQAn3gwe8XBCz7mnEJ+qexcqCwXn3vJt2gdrMEWyW8SGI6FW3X01pJZYDuPe\\nRhN3aaWzYDB7yKEKvvrWAL0ovcjmc/lbRY0dvX2/SS4UWg4B3Z5rbCK3CemOx4D5\\nKz6inaEpLLrCmMBqIlOHTsFyB5Tv/SlCP22eS9C91MsoIJtRKQ==\\n-----END CERTIFICATE-----\",\"securePort\":443}}"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/resources/ssltermination-get.json",
    "content": "{\n  \"sslTermination\": {\n    \"certificate\": \"-----BEGIN CERTIFICATE-----\\nMIICATCCAWoCCQCvn3QIv4NQODANBgkqhkiG9w0BAQUFADBFMQswCQYDVQQGEwJB\\nVTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50ZXJuZXQgV2lkZ2l0\\ncyBQdHkgTHRkMB4XDTEzMDEwMzIxNTMyMloXDTE0MDEwMzIxNTMyMlowRTELMAkG\\nA1UEBhMCQVUxEzARBgNVBAgTClNvbWUtU3RhdGUxITAfBgNVBAoTGEludGVybmV0\\nIFdpZGdpdHMgUHR5IEx0ZDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAw6IR\\ntI/MQdQNsHT2UtUIXUbfu/7uxKqKIlbE6Bj5+lZFvUSrkTFRqgjgUADp2oFUYMRg\\nYON8HEv0HzJOBujajUdy1sWQiDykhtlsMQ2KTnhYS7cBM798Dhpt2KzW/iULzTXN\\nIum/CjCc7g1l0xxF9CvzPbdCn0obwMd1oecmHpcCAwEAATANBgkqhkiG9w0BAQUF\\nAAOBgQAn3gwe8XBCz7mnEJ+qexcqCwXn3vJt2gdrMEWyW8SGI6FW3X01pJZYDuPe\\nRhN3aaWzYDB7yKEKvvrWAL0ovcjmc/lbRY0dvX2/SS4UWg4B3Z5rbCK3CemOx4D5\\nKz6inaEpLLrCmMBqIlOHTsFyB5Tv/SlCP22eS9C91MsoIJtRKQ==\\n-----END CERTIFICATE-----\",\n    \"enabled\": true,\n    \"secureTrafficOnly\": false,\n    \"privatekey\": \"-----BEGIN RSA PRIVATE KEY-----\\nMIICWwIBAAKBgQDDohG0j8xB1A2wdPZS1QhdRt+7/u7EqooiVsToGPn6VkW9RKuR\\nMVGqCOBQAOnagVRgxGBg43wcS/QfMk4G6NqNR3LWxZCIPKSG2WwxDYpOeFhLtwEz\\nv3wOGm3YrNb+JQvNNc0i6b8KMJzuDWXTHEX0K/M9t0KfShvAx3Wh5yYelwIDAQAB\\nAoGAdKCD6Z7oaD4gwxeXWZ5C1EjSTOMYOQpqOzp7PNrW/BS+kq0DkxVR2Apen5NL\\n1sXPJbkss9YqQTxOluKIfboHv7J9mUSOisUnFVmjD3l5dik3vAPgIybr7aQvfVbF\\ns93N/WiTICLTwGHOjyYPttCxdKKW1noL5S8Pcni7F1TnlxECQQDunLeBNmtRK8lh\\nwG6FTNMtJSPYXhfhDQfLZj74ITC8sgd0a2Co6AK6v6JADTXujo+HJi6Bo9eqQ49F\\nmom+hXfjAkEA0eOVDQZ4XcWLGfhB/B5mUmHC0m+JAsds1slr+2B8mCGcaAsynPd0\\nj068seY3qsJuguO5OUzati8RQWWSNzu0vQJAIkHLsrheZfP0YJ1hALBL7UJUyB6S\\nLRRS1yfhyHvzZFPm8BbudLGCms8iezGqWYqMHqojqScdsmsqqaKLPhgpYwJAW1AH\\nqIMIGsO2oLXA/066dVzSxXqAwRTB5S/8KoDvs7/rq9gzTNbbfv1iWoMt9LxiF8+6\\n5ZLqFBimCS2HT0BKgQJAEDONaHND9mRLRaSAvh5zXM86FPPbjg9xjSufO6+ZnGwI\\nN5jdN55nrwoA1K4RvDc2tVGo+0EvvU/tmnNKLwEU2Q==\\n-----END RSA PRIVATE KEY-----\",\n    \"intermediateCertificate\": \"-----BEGIN CERTIFICATE-----\\nMIICATCCAWoCCQCvn3QIv4NQODANBgkqhkiG9w0BAQUFADBFMQswCQYDVQQGEwJB\\nVTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50ZXJuZXQgV2lkZ2l0\\ncyBQdHkgTHRkMB4XDTEzMDEwMzIxNTMyMloXDTE0MDEwMzIxNTMyMlowRTELMAkG\\nA1UEBhMCQVUxEzARBgNVBAgTClNvbWUtU3RhdGUxITAfBgNVBAoTGEludGVybmV0\\nIFdpZGdpdHMgUHR5IEx0ZDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAw6IR\\ntI/MQdQNsHT2UtUIXUbfu/7uxKqKIlbE6Bj5+lZFvUSrkTFRqgjgUADp2oFUYMRg\\nYON8HEv0HzJOBujajUdy1sWQiDykhtlsMQ2KTnhYS7cBM798Dhpt2KzW/iULzTXN\\nIum/CjCc7g1l0xxF9CvzPbdCn0obwMd1oecmHpcCAwEAATANBgkqhkiG9w0BAQUF\\nAAOBgQAn3gwe8XBCz7mnEJ+qexcqCwXn3vJt2gdrMEWyW8SGI6FW3X01pJZYDuPe\\nRhN3aaWzYDB7yKEKvvrWAL0ovcjmc/lbRY0dvX2/SS4UWg4B3Z5rbCK3CemOx4D5\\nKz6inaEpLLrCmMBqIlOHTsFyB5Tv/SlCP22eS9C91MsoIJtRKQ==\\n-----END CERTIFICATE-----\",\n    \"securePort\": 443\n  }\n}"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/resources/ssltermination-intermediatecertificate.txt",
    "content": "-----BEGIN CERTIFICATE-----\nMIICATCCAWoCCQCvn3QIv4NQODANBgkqhkiG9w0BAQUFADBFMQswCQYDVQQGEwJB\nVTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50ZXJuZXQgV2lkZ2l0\ncyBQdHkgTHRkMB4XDTEzMDEwMzIxNTMyMloXDTE0MDEwMzIxNTMyMlowRTELMAkG\nA1UEBhMCQVUxEzARBgNVBAgTClNvbWUtU3RhdGUxITAfBgNVBAoTGEludGVybmV0\nIFdpZGdpdHMgUHR5IEx0ZDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAw6IR\ntI/MQdQNsHT2UtUIXUbfu/7uxKqKIlbE6Bj5+lZFvUSrkTFRqgjgUADp2oFUYMRg\nYON8HEv0HzJOBujajUdy1sWQiDykhtlsMQ2KTnhYS7cBM798Dhpt2KzW/iULzTXN\nIum/CjCc7g1l0xxF9CvzPbdCn0obwMd1oecmHpcCAwEAATANBgkqhkiG9w0BAQUF\nAAOBgQAn3gwe8XBCz7mnEJ+qexcqCwXn3vJt2gdrMEWyW8SGI6FW3X01pJZYDuPe\nRhN3aaWzYDB7yKEKvvrWAL0ovcjmc/lbRY0dvX2/SS4UWg4B3Z5rbCK3CemOx4D5\nKz6inaEpLLrCmMBqIlOHTsFyB5Tv/SlCP22eS9C91MsoIJtRKQ==\n-----END CERTIFICATE-----"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/resources/ssltermination-privatekey.txt",
    "content": "-----BEGIN RSA PRIVATE KEY-----\nMIICWwIBAAKBgQDDohG0j8xB1A2wdPZS1QhdRt+7/u7EqooiVsToGPn6VkW9RKuR\nMVGqCOBQAOnagVRgxGBg43wcS/QfMk4G6NqNR3LWxZCIPKSG2WwxDYpOeFhLtwEz\nv3wOGm3YrNb+JQvNNc0i6b8KMJzuDWXTHEX0K/M9t0KfShvAx3Wh5yYelwIDAQAB\nAoGAdKCD6Z7oaD4gwxeXWZ5C1EjSTOMYOQpqOzp7PNrW/BS+kq0DkxVR2Apen5NL\n1sXPJbkss9YqQTxOluKIfboHv7J9mUSOisUnFVmjD3l5dik3vAPgIybr7aQvfVbF\ns93N/WiTICLTwGHOjyYPttCxdKKW1noL5S8Pcni7F1TnlxECQQDunLeBNmtRK8lh\nwG6FTNMtJSPYXhfhDQfLZj74ITC8sgd0a2Co6AK6v6JADTXujo+HJi6Bo9eqQ49F\nmom+hXfjAkEA0eOVDQZ4XcWLGfhB/B5mUmHC0m+JAsds1slr+2B8mCGcaAsynPd0\nj068seY3qsJuguO5OUzati8RQWWSNzu0vQJAIkHLsrheZfP0YJ1hALBL7UJUyB6S\nLRRS1yfhyHvzZFPm8BbudLGCms8iezGqWYqMHqojqScdsmsqqaKLPhgpYwJAW1AH\nqIMIGsO2oLXA/066dVzSxXqAwRTB5S/8KoDvs7/rq9gzTNbbfv1iWoMt9LxiF8+6\n5ZLqFBimCS2HT0BKgQJAEDONaHND9mRLRaSAvh5zXM86FPPbjg9xjSufO6+ZnGwI\nN5jdN55nrwoA1K4RvDc2tVGo+0EvvU/tmnNKLwEU2Q==\n-----END RSA PRIVATE KEY-----"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/resources/virtualips-create-response.json",
    "content": "{\n    \"address\": \"fd24:f480:ce44:91bc:1af2:15ff:0000:0002\",\n    \"id\": 9000134,\n    \"type\": \"PUBLIC\",\n    \"ipVersion\": \"IPV6\"\n}"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/resources/virtualips-create.json",
    "content": "{\"type\":\"PUBLIC\",\"ipVersion\":\"IPV6\"}"
  },
  {
    "path": "apis/rackspace-cloudloadbalancers/src/test/resources/virtualips-list.json",
    "content": "{\n    \"virtualIps\": [\n        {\n            \"address\": \"166.78.34.87\",\n            \"id\": 5557,\n            \"type\": \"PUBLIC\",\n            \"ipVersion\": \"IPV4\"\n        },\n        {\n            \"address\": \"2001:4800:7901:0000:9a32:3c2a:0000:0001\",\n            \"id\": 9076419,\n            \"type\": \"PUBLIC\",\n            \"ipVersion\": \"IPV6\"\n        },\n        {\n            \"address\": \"2001:4800:7901:0000:9a32:3c2a:0000:0002\",\n            \"id\": 9079727,\n            \"type\": \"PUBLIC\",\n            \"ipVersion\": \"IPV6\"\n        }\n    ]\n}"
  },
  {
    "path": "apis/route53/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.route53.*;version=\"${project.version}\";-noimport:=true"
  },
  {
    "path": "apis/route53/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.api</groupId>\n  <artifactId>route53</artifactId>\n  <name>jclouds route53 api</name>\n  <description>jclouds components to access an implementation of Route 53</description>\n\n  <properties>\n    <test.route53.endpoint>https://route53.amazonaws.com</test.route53.endpoint>\n    <test.route53.api-version>2012-02-29</test.route53.api-version>\n    <test.route53.build-version />\n    <test.route53.identity>${test.aws.identity}</test.route53.identity>\n    <test.route53.credential>${test.aws.credential}</test.route53.credential>\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>sts</artifactId>\n      <version>${project.version}</version>\n      <type>jar</type>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-slf4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>ch.qos.logback</groupId>\n      <artifactId>logback-classic</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.route53.endpoint>${test.route53.endpoint}</test.route53.endpoint>\n                    <test.route53.api-version>${test.route53.api-version}</test.route53.api-version>\n                    <test.route53.build-version>${test.route53.build-version}</test.route53.build-version>\n                    <test.route53.identity>${test.route53.identity}</test.route53.identity>\n                    <test.route53.credential>${test.route53.credential}</test.route53.credential>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n\n"
  },
  {
    "path": "apis/route53/src/main/java/org/jclouds/route53/InvalidChangeBatchException.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53;\n\nimport org.jclouds.http.HttpResponseException;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * @see <a href=\n *      \"http://docs.aws.amazon.com/Route53/latest/APIReference/API_ChangeResourceRecordSets.html\"\n *      />\n */\npublic class InvalidChangeBatchException extends IllegalArgumentException {\n   private static final long serialVersionUID = 1L;\n\n   private final ImmutableList<String> messages;\n\n   public InvalidChangeBatchException(ImmutableList<String> messages, HttpResponseException cause) {\n      super(messages.toString(), cause);\n      this.messages = messages;\n   }\n\n   public ImmutableList<String> getMessages() {\n      return messages;\n   }\n}\n"
  },
  {
    "path": "apis/route53/src/main/java/org/jclouds/route53/Route53Api.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53;\n\nimport java.io.Closeable;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.rest.annotations.Delegate;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.VirtualHost;\nimport org.jclouds.rest.annotations.XMLResponseParser;\nimport org.jclouds.route53.domain.Change;\nimport org.jclouds.route53.features.HostedZoneApi;\nimport org.jclouds.route53.features.ResourceRecordSetApi;\nimport org.jclouds.route53.filters.RestAuthentication;\nimport org.jclouds.route53.xml.ChangeHandler;\n\n/**\n * Provides access to Amazon Route53 via the Query API\n * <p/>\n * \n * @see <a href=\"http://docs.amazonwebservices.com/Route53/latest/APIReference\"\n *      />\n */\n@RequestFilters(RestAuthentication.class)\n@VirtualHost\n@Path(\"/{jclouds.api-version}\")\npublic interface Route53Api extends Closeable {\n\n   /**\n    * returns the current status of a change batch request.\n    * \n    * @param changeID\n    *           The ID of the change batch request.\n    * @return null, if not found\n    */\n   @Named(\"GetChange\")\n   @GET\n   @Path(\"/change/{changeId}\")\n   @XMLResponseParser(ChangeHandler.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Change getChange(@PathParam(\"changeId\") String changeID);\n\n   /**\n    * Provides access to Zone features.\n    */\n   @Delegate\n   HostedZoneApi getHostedZoneApi();\n   \n   /**\n    * Provides access to record set features.\n    */\n   @Delegate\n   @Path(\"/hostedzone/{zoneId}\")\n   ResourceRecordSetApi getResourceRecordSetApiForHostedZone(@PathParam(\"zoneId\") String zoneId);\n}\n"
  },
  {
    "path": "apis/route53/src/main/java/org/jclouds/route53/Route53ApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53;\n\nimport static org.jclouds.aws.reference.AWSConstants.PROPERTY_AUTH_TAG;\nimport static org.jclouds.aws.reference.AWSConstants.PROPERTY_HEADER_TAG;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.rest.internal.BaseHttpApiMetadata;\nimport org.jclouds.route53.config.Route53HttpApiModule;\n\nimport com.google.auto.service.AutoService;\n\n/**\n * Implementation of {@link ApiMetadata} for Amazon's Route53 api.\n */\n@AutoService(ApiMetadata.class)\npublic class Route53ApiMetadata extends BaseHttpApiMetadata<Route53Api> {\n\n   @Override\n   public Builder toBuilder() {\n      return new Builder().fromApiMetadata(this);\n   }\n\n   public Route53ApiMetadata() {\n      this(new Builder());\n   }\n\n   protected Route53ApiMetadata(Builder builder) {\n      super(Builder.class.cast(builder));\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = BaseHttpApiMetadata.defaultProperties();\n      properties.setProperty(PROPERTY_AUTH_TAG, \"AWS\");\n      properties.setProperty(PROPERTY_HEADER_TAG, \"amz\");\n      return properties;\n   }\n\n   public static class Builder extends BaseHttpApiMetadata.Builder<Route53Api, Builder> {\n\n      protected Builder() {\n         id(\"route53\")\n         .name(\"Amazon Route 53 Api\")\n         .identityName(\"Access Key ID\")\n         .credentialName(\"Secret Access Key\")\n         .version(\"2012-02-29\")\n         .documentation(URI.create(\"http://docs.aws.amazon.com/Route53/latest/APIReference/\"))\n         .defaultEndpoint(\"https://route53.amazonaws.com\")\n         .defaultProperties(Route53ApiMetadata.defaultProperties())\n         .defaultModule(Route53HttpApiModule.class);\n      }\n\n      @Override\n      public Route53ApiMetadata build() {\n         return new Route53ApiMetadata(this);\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/route53/src/main/java/org/jclouds/route53/binders/BindChangeBatch.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53.binders;\n\nimport static org.jclouds.io.Payloads.newStringPayload;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.io.Payload;\nimport org.jclouds.rest.Binder;\nimport org.jclouds.route53.domain.ChangeBatch;\nimport org.jclouds.route53.domain.ChangeBatch.ActionOnResourceRecordSet;\nimport org.jclouds.route53.functions.SerializeRRS;\n\n@Singleton\npublic class BindChangeBatch implements Binder {\n\n   private static final SerializeRRS xml = new SerializeRRS();\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object payload) {\n      ChangeBatch from = ChangeBatch.class.cast(payload);\n      StringBuilder b = new StringBuilder();\n      b.append(\"<ChangeResourceRecordSetsRequest xmlns=\\\"https://route53.amazonaws.com/doc/2012-02-29/\\\"><ChangeBatch>\");\n      if (from.getComment().isPresent())\n         b.append(\"<Comment>\").append(from.getComment().get()).append(\"</Comment>\");\n      b.append(\"<Changes>\");\n      for (ActionOnResourceRecordSet change : from)\n         b.append(\"<Change>\").append(\"<Action>\").append(change.getAction()).append(\"</Action>\")\n               .append(xml.apply(change.getRRS())).append(\"</Change>\");\n      b.append(\"</Changes>\");\n      b.append(\"</ChangeBatch></ChangeResourceRecordSetsRequest>\");\n      Payload xmlPayload = newStringPayload(b.toString());\n      xmlPayload.getContentMetadata().setContentType(\"application/xml\");\n      return (R) request.toBuilder().payload(xmlPayload).build();\n   }\n}\n"
  },
  {
    "path": "apis/route53/src/main/java/org/jclouds/route53/binders/BindNextRecord.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53.binders;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpRequest.Builder;\nimport org.jclouds.rest.Binder;\nimport org.jclouds.route53.domain.ResourceRecordSetIterable.NextRecord;\n\n@Singleton\npublic class BindNextRecord implements Binder {\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object payload) {\n      NextRecord from = NextRecord.class.cast(payload);\n      Builder<?> builder = request.toBuilder();\n      builder.addQueryParam(\"name\", from.getName());\n      if (from.getType().isPresent())\n         builder.addQueryParam(\"type\", from.getType().get());\n      if (from.getIdentifier().isPresent())\n         builder.addQueryParam(\"identifier\", from.getIdentifier().get());\n      return (R) builder.build();\n   }\n}\n"
  },
  {
    "path": "apis/route53/src/main/java/org/jclouds/route53/config/Route53HttpApiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53.config;\n\nimport java.util.Date;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.config.AWSHttpApiModule;\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.annotation.ClientError;\nimport org.jclouds.http.annotation.Redirection;\nimport org.jclouds.http.annotation.ServerError;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.RequestSigner;\nimport org.jclouds.route53.Route53Api;\nimport org.jclouds.route53.filters.RestAuthentication;\nimport org.jclouds.route53.handlers.Route53ErrorHandler;\n\nimport com.google.inject.Provides;\n\n/**\n * Configures the Route53 connection.\n */\n@ConfiguresHttpApi\npublic class Route53HttpApiModule extends AWSHttpApiModule<Route53Api> {\n   public Route53HttpApiModule() {\n   }\n\n   @Provides\n   @TimeStamp\n   protected final String guiceProvideTimeStamp(DateService dateService) {\n      return provideTimeStamp(dateService);\n   }\n\n   protected String provideTimeStamp(DateService dateService) {\n      return dateService.rfc1123DateFormat(new Date(System.currentTimeMillis()));\n   }\n\n   @Provides\n   @Singleton\n   final RequestSigner provideRequestSigner(RestAuthentication in) {\n      return in;\n   }\n\n   @Override\n   protected void bindErrorHandlers() {\n      bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(Route53ErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(Route53ErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(Route53ErrorHandler.class);\n   }\n}\n"
  },
  {
    "path": "apis/route53/src/main/java/org/jclouds/route53/domain/Change.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Date;\n\nimport com.google.common.base.Objects;\n\npublic final class Change {\n\n   private final String id;\n   private final Status status;\n   private final Date submittedAt;\n\n   private Change(String id, Status status, Date submittedAt) {\n      this.id = checkNotNull(id, \"id\");\n      this.status = checkNotNull(status, \"status for %s\", id);\n      this.submittedAt = checkNotNull(submittedAt, \"submittedAt for %s\", id);\n   }\n\n   /**\n    * The ID of the change batch.\n    */\n   public String getId() {\n      return id;\n   }\n\n   /**\n    * The current status of the change batch request.\n    */\n   public Status getStatus() {\n      return status;\n   }\n\n   /**\n    * The date and time that the change batch request was submitted.\n    */\n   public Date getSubmittedAt() {\n      return submittedAt;\n   }\n\n   public enum Status {\n      /**\n       * indicates that the changes in this request have not replicated to all\n       * Amazon Route 53 DNS servers.\n       */\n      PENDING,\n      /**\n       * indicates that the changes have replicated to all Amazon Route 53 DNS\n       * servers.\n       */\n      INSYNC, UNRECOGNIZED;\n\n      public static Status fromValue(String status) {\n         try {\n            return valueOf(checkNotNull(status, \"status\"));\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      Change that = Change.class.cast(obj);\n      return equal(this.id, that.id);\n   }\n\n   @Override\n   public String toString() {\n      return toStringHelper(this).add(\"id\", id).add(\"status\", status).add(\"submittedAt\", submittedAt).toString();\n   }\n\n   public static Change create(String id, Status status, Date submittedAt) {\n      return new Change(id, status, submittedAt);\n   }\n}\n"
  },
  {
    "path": "apis/route53/src/main/java/org/jclouds/route53/domain/ChangeBatch.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.List;\n\nimport org.jclouds.route53.domain.ChangeBatch.ActionOnResourceRecordSet;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ForwardingList;\nimport com.google.common.collect.ImmutableList;\n\npublic class ChangeBatch extends ForwardingList<ActionOnResourceRecordSet> {\n\n   public static ChangeBatch createAll(Iterable<ResourceRecordSet> toCreate) {\n      return builder().createAll(toCreate).build();\n   }\n\n   public static ChangeBatch deleteAll(Iterable<ResourceRecordSet> toDelete) {\n      return builder().deleteAll(toDelete).build();\n   }\n\n   private final Optional<String> comment;\n   private final List<ActionOnResourceRecordSet> changes;\n\n   public static enum Action {\n      CREATE, DELETE;\n   }\n\n   public static class ActionOnResourceRecordSet {\n      private final Action action;\n      private final ResourceRecordSet rrs;\n\n      private ActionOnResourceRecordSet(Action action, ResourceRecordSet rrs) {\n         this.action = action;\n         this.rrs = rrs;\n      }\n\n      public Action getAction() {\n         return action;\n      }\n\n      public ResourceRecordSet getRRS() {\n         return rrs;\n      }\n\n      @Override\n      public int hashCode() {\n         return Objects.hashCode(action, rrs);\n      }\n\n      @Override\n      public boolean equals(Object obj) {\n         if (this == obj)\n            return true;\n         if (obj == null || getClass() != obj.getClass())\n            return false;\n         ActionOnResourceRecordSet that = ActionOnResourceRecordSet.class.cast(obj);\n         return equal(this.action, that.action) && equal(this.rrs, that.rrs);\n      }\n\n      @Override\n      public String toString() {\n         return toStringHelper(\"\").omitNullValues().add(\"action\", action).add(\"rrs\", rrs).toString();\n      }\n   }\n\n   private ChangeBatch(Optional<String> comment, ImmutableList<ActionOnResourceRecordSet> changes) {\n      this.comment = checkNotNull(comment, \"comment\");\n      this.changes = checkNotNull(changes, \"changes%s\", comment.isPresent() ? \" for %s \" + comment.get() : \"\");\n      checkArgument(!changes.isEmpty(), \"no changes%s\", comment.isPresent() ? \" for %s \" + comment.get() : \"\");\n   }\n\n   /**\n    * Any comments you want to include about the changes in this change batch.\n    */\n   public Optional<String> getComment() {\n      return comment;\n   }\n\n   @Override\n   protected List<ActionOnResourceRecordSet> delegate() {\n      return changes;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(comment, changes);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      ChangeBatch that = ChangeBatch.class.cast(obj);\n      return equal(this.comment, that.comment) && equal(this.changes, that.changes);\n   }\n\n   @Override\n   public String toString() {\n      return toStringHelper(\"\").omitNullValues().add(\"comment\", comment.orNull()).add(\"changes\", changes).toString();\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static final class Builder {\n      private Optional<String> comment = Optional.absent();\n      private ImmutableList.Builder<ActionOnResourceRecordSet> changes = ImmutableList.builder();\n\n      /**\n       * @see ChangeBatch#getComment()\n       */\n      public Builder comment(String comment) {\n         this.comment = Optional.fromNullable(comment);\n         return this;\n      }\n\n      public Builder create(ResourceRecordSet rrs) {\n         this.changes.add(new ActionOnResourceRecordSet(Action.CREATE, rrs));\n         return this;\n      }\n\n      public Builder createAll(Iterable<ResourceRecordSet> toCreate) {\n         for (ResourceRecordSet rrs : toCreate)\n            create(rrs);\n         return this;\n      }\n\n      public Builder delete(ResourceRecordSet rrs) {\n         this.changes.add(new ActionOnResourceRecordSet(Action.DELETE, rrs));\n         return this;\n      }\n\n      public Builder deleteAll(Iterable<ResourceRecordSet> toDelete) {\n         for (ResourceRecordSet rrs : toDelete)\n            delete(rrs);\n         return this;\n      }\n\n      public ChangeBatch build() {\n         return new ChangeBatch(comment, changes.build());\n      }\n   }\n}\n"
  },
  {
    "path": "apis/route53/src/main/java/org/jclouds/route53/domain/HostedZone.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.Optional;\n\npublic final class HostedZone {\n\n   private final String id;\n   private final String name;\n   private final String callerReference;\n   private final int resourceRecordSetCount;\n   private final Optional<String> comment;\n\n   private HostedZone(String id, String name, String callerReference, int resourceRecordSetCount, Optional<String> comment) {\n      this.id = checkNotNull(id, \"id\");\n      this.name = checkNotNull(name, \"name\");\n      this.callerReference = checkNotNull(callerReference, \"callerReference for %s\", name);\n      this.resourceRecordSetCount = resourceRecordSetCount;\n      this.comment = checkNotNull(comment, \"comment for %s\", name);\n   }\n\n   /**\n    * The ID of the hosted zone.\n    */\n   public String getId() {\n      return id;\n   }\n\n   /**\n    * The name of the domain.\n    */\n   public String getName() {\n      return name;\n   }\n\n   /**\n    * A unique string that identifies the request to create the hosted zone.\n    */\n   public String getCallerReference() {\n      return callerReference;\n   }\n\n   /**\n    * count of record sets\n    */\n   public int getResourceRecordSetCount() {\n      return resourceRecordSetCount;\n   }\n\n   public Optional<String> getComment() {\n      return comment;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, name, callerReference);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      HostedZone that = HostedZone.class.cast(obj);\n      return equal(this.id, that.id) && equal(this.name, that.name)\n            && equal(this.callerReference, that.callerReference);\n   }\n\n   @Override\n   public String toString() {\n      return toStringHelper(this).omitNullValues().add(\"id\", id).add(\"name\", name)\n            .add(\"callerReference\", callerReference).add(\"resourceRecordSetCount\", resourceRecordSetCount)\n            .add(\"comment\", comment.orNull()).toString();\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().from(this);\n   }\n\n   public static final class Builder {\n      private String id;\n      private String name;\n      private String callerReference;\n      private int resourceRecordSetCount;\n      private Optional<String> comment = Optional.absent();\n\n      /**\n       * @see HostedZone#getId()\n       */\n      public Builder id(String id) {\n         this.id = id;\n         return this;\n      }\n\n      /**\n       * @see HostedZone#getName()\n       */\n      public Builder name(String name) {\n         this.name = name;\n         return this;\n      }\n\n      /**\n       * @see HostedZone#getCallerReference()\n       */\n      public Builder callerReference(String callerReference) {\n         this.callerReference = callerReference;\n         return this;\n      }\n\n      /**\n       * @see HostedZone#getResourceRecordSetCount()\n       */\n      public Builder resourceRecordSetCount(int resourceRecordSetCount) {\n         this.resourceRecordSetCount = resourceRecordSetCount;\n         return this;\n      }\n\n      /**\n       * @see HostedZone#getComment()\n       */\n      public Builder comment(String comment) {\n         this.comment = Optional.fromNullable(comment);\n         return this;\n      }\n\n      public HostedZone build() {\n         return new HostedZone(id, name, callerReference, resourceRecordSetCount, comment);\n      }\n\n      public Builder from(HostedZone in) {\n         return this.id(in.id).name(in.name).callerReference(in.callerReference)\n               .resourceRecordSetCount(in.resourceRecordSetCount).comment(in.comment.orNull());\n      }\n   }\n}\n"
  },
  {
    "path": "apis/route53/src/main/java/org/jclouds/route53/domain/HostedZoneAndNameServers.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ImmutableList;\n\npublic final class HostedZoneAndNameServers {\n\n   private final HostedZone zone;\n   private final ImmutableList<String> nameServers;\n\n   private HostedZoneAndNameServers(HostedZone zone, ImmutableList<String> nameServers) {\n      this.zone = checkNotNull(zone, \"zone\");\n      this.nameServers = checkNotNull(nameServers, \"nameServers for %s\", zone);\n   }\n\n   /**\n    * the hosted zone\n    */\n   public HostedZone getZone() {\n      return zone;\n   }\n\n   /**\n    * the authoritative name servers for the hosted zone\n    */\n   public ImmutableList<String> getNameServers() {\n      return nameServers;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(zone, nameServers);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      HostedZoneAndNameServers that = HostedZoneAndNameServers.class.cast(obj);\n      return equal(this.zone, that.zone) && equal(this.nameServers, that.nameServers);\n   }\n\n   @Override\n   public String toString() {\n      return toStringHelper(\"\").add(\"zone\", zone).add(\"nameServers\", nameServers).toString();\n   }\n\n   public static HostedZoneAndNameServers create(HostedZone zone, Iterable<String> nameServers) {\n      return new HostedZoneAndNameServers(zone, ImmutableList.<String> copyOf(checkNotNull(nameServers, \"nameServers\")));\n   }\n}\n"
  },
  {
    "path": "apis/route53/src/main/java/org/jclouds/route53/domain/NewHostedZone.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ImmutableList;\n\npublic final class NewHostedZone {\n\n   private final HostedZoneAndNameServers zone;\n   private final Change change;\n\n   private NewHostedZone(HostedZoneAndNameServers zone, Change change) {\n      this.zone = checkNotNull(zone, \"zone\");\n      this.change = checkNotNull(change, \"change of %s\", zone);\n   }\n\n   /**\n    * @see HostedZoneAndNameServers#getZone()\n    */\n   public HostedZone getZone() {\n      return zone.getZone();\n   }\n\n   /**\n    * @see HostedZoneAndNameServers#getNameServers()\n    */\n   public ImmutableList<String> getNameServers() {\n      return zone.getNameServers();\n   }\n\n   /**\n    * the zone creation event\n    */\n   public Change getChange() {\n      return change;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(zone);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      NewHostedZone that = NewHostedZone.class.cast(obj);\n      return equal(this.zone, that.zone);\n   }\n\n   @Override\n   public String toString() {\n      return toStringHelper(\"\").add(\"zone\", zone.getZone()).add(\"nameServers\", zone.getNameServers())\n            .add(\"change\", change).toString();\n   }\n\n   public static NewHostedZone create(HostedZoneAndNameServers zone, Change change) {\n      return new NewHostedZone(zone, change);\n   }\n}\n"
  },
  {
    "path": "apis/route53/src/main/java/org/jclouds/route53/domain/ResourceRecordSet.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.List;\n\nimport org.jclouds.route53.domain.ResourceRecordSet.RecordSubset.Latency;\nimport org.jclouds.route53.domain.ResourceRecordSet.RecordSubset.Weighted;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableList;\n\npublic class ResourceRecordSet {\n\n   protected final String name;\n   protected final String type;\n   protected final Optional<Integer> ttl;\n   protected final List<String> values;\n   protected final Optional<AliasTarget> aliasTarget;\n\n   /**\n    * In this case, the rrs is an alias, and it points to another Route53 hosted\n    * resource, such as an ELB, S3 bucket, or zone.\n    */\n   public static class AliasTarget {\n\n      public static AliasTarget dnsNameInZone(String dnsName, String zoneId) {\n         return new AliasTarget(dnsName, zoneId);\n      }\n\n      private final String dnsName;\n      private final String zoneId;\n\n      private AliasTarget(String dnsName, String zoneId) {\n         this.dnsName = checkNotNull(dnsName, \"dnsName\");\n         this.zoneId = checkNotNull(zoneId, \"zoneId of %s\", dnsName);\n      }\n\n      public String getDNSName() {\n         return dnsName;\n      }\n\n      public String getZoneId() {\n         return zoneId;\n      }\n\n      @Override\n      public int hashCode() {\n         return Objects.hashCode(zoneId, dnsName);\n      }\n\n      @Override\n      public boolean equals(Object obj) {\n         if (this == obj)\n            return true;\n         if (obj == null || getClass() != obj.getClass())\n            return false;\n         AliasTarget other = AliasTarget.class.cast(obj);\n         return equal(this.dnsName, other.dnsName) && equal(this.zoneId, other.zoneId);\n      }\n\n      @Override\n      public String toString() {\n         return toStringHelper(\"\").omitNullValues().add(\"dnsName\", dnsName).add(\"zoneId\", zoneId).toString();\n      }\n   }\n\n   /**\n    * A portion of a RRs who share the same name and type\n    */\n   public abstract static class RecordSubset extends ResourceRecordSet {\n      public static final class Weighted extends RecordSubset {\n\n         private final int weight;\n\n         private Weighted(String id, String name, String type, int weight, Optional<Integer> ttl, List<String> values,\n               Optional<AliasTarget> aliasTarget) {\n            super(id, name, type, ttl, values, aliasTarget);\n            this.weight = weight;\n         }\n\n         /**\n          * determines what portion of traffic for the current resource record\n          * set is routed to this subset.\n          */\n         public int getWeight() {\n            return weight;\n         }\n\n         @Override\n         ToStringHelper differentiate(ToStringHelper in) {\n            return in.add(\"weight\", weight);\n         }\n      }\n\n      public static final class Latency extends RecordSubset {\n\n         private final String region;\n\n         private Latency(String id, String name, String type, String region, Optional<Integer> ttl, List<String> values,\n               Optional<AliasTarget> aliasTarget) {\n            super(id, name, type, ttl, values, aliasTarget);\n            this.region = checkNotNull(region, \"region of %s\", name);\n         }\n\n         /**\n          * The Amazon EC2 region where the resource that is specified in this\n          * resource record set resides.\n          */\n         public String getRegion() {\n            return region;\n         }\n\n         @Override\n         ToStringHelper differentiate(ToStringHelper in) {\n            return in.add(\"region\", region);\n         }\n      }\n\n      private final String id;\n\n      private RecordSubset(String id, String name, String type, Optional<Integer> ttl, List<String> values,\n            Optional<AliasTarget> aliasTarget) {\n         super(name, type, ttl, values, aliasTarget);\n         this.id = checkNotNull(id, \"id of %s\", name);\n      }\n\n      /**\n       * The identifier that differentiates beyond {@code name} and {@code type}\n       */\n      public String getId() {\n         return id;\n      }\n\n      @Override\n      public int hashCode() {\n         return Objects.hashCode(super.hashCode(), id);\n      }\n\n      @Override\n      public boolean equals(Object obj) {\n         if (super.equals(obj) && obj instanceof RecordSubset) {\n            RecordSubset that = RecordSubset.class.cast(obj);\n            return equal(this.id, that.id);\n         }\n         return false;\n      }\n\n      abstract ToStringHelper differentiate(ToStringHelper in);\n\n      @Override\n      public String toString() {\n         return differentiate(toStringHelper(\"\").omitNullValues().add(\"id\", id).add(\"name\", name).add(\"type\", type))\n               .add(\"ttl\", ttl.orNull()).add(\"values\", values.isEmpty() ? null : values).add(\"aliasTarget\", aliasTarget.orNull())\n               .toString();\n      }\n   }\n\n   private ResourceRecordSet(String name, String type, Optional<Integer> ttl, List<String> values, Optional<AliasTarget> aliasTarget) {\n      this.name = checkNotNull(name, \"name\");\n      this.type = checkNotNull(type, \"type of %s\", name);\n      this.ttl = checkNotNull(ttl, \"ttl for %s\", name);\n      checkArgument(ttl.or(0) >= 0, \"ttl of %s must be unsigned\", name);\n      this.values = checkNotNull(values, \"values for %s\", name);\n      this.aliasTarget = checkNotNull(aliasTarget, \"aliasTarget for %s\", name);\n   }\n\n   /**\n    * The name of the domain.\n    */\n   public String getName() {\n      return name;\n   }\n\n   /**\n    * The resource record set type.\n    */\n   public String getType() {\n      return type;\n   }\n\n   /**\n    * Present in all resource record sets except aliases. The resource record\n    * cache time to live (TTL), in seconds.\n    */\n   public Optional<Integer> getTTL() {\n      return ttl;\n   }\n\n   /**\n    * Type-specific values that differentiates the RRs in this set. Empty if\n    * {@link #getType()} is {@code A} or {@code AAAA} and\n    * {@link #getAliasTarget} is present.\n    */\n   public List<String> getValues() {\n      return values;\n   }\n\n   /**\n    * When present, {@link #getType()} is {@code A} or {@code AAAA}.\n    * Instead of {@link #getValues()} containing the corresponding IP addresses,\n    * the server will follow this link and resolve one on-demand.\n    */\n   public Optional<AliasTarget> getAliasTarget() {\n      return aliasTarget;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(name, type);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      ResourceRecordSet other = ResourceRecordSet.class.cast(obj);\n      return equal(this.name, other.name) && equal(this.type, other.type);\n   }\n\n   @Override\n   public String toString() {\n      return toStringHelper(\"\").omitNullValues().add(\"name\", name).add(\"type\", type).add(\"ttl\", ttl.orNull())\n            .add(\"values\", values.isEmpty() ? null : values).add(\"aliasTarget\", aliasTarget.orNull()).toString();\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().from(this);\n   }\n\n   public static final class Builder {\n      private String id;\n      private String name;\n      private String type;\n      private Optional<Integer> ttl = Optional.absent();\n      private ImmutableList.Builder<String> values = ImmutableList.<String> builder();\n      private String dnsName;\n      private String zoneId;\n      private Integer weight;\n      private String region;\n\n      /**\n       * @see RecordSubset#getId()\n       */\n      public Builder id(String id) {\n         this.id = id;\n         return this;\n      }\n\n      /**\n       * @see ResourceRecordSet#getName()\n       */\n      public Builder name(String name) {\n         this.name = name;\n         return this;\n      }\n\n      /**\n       * @see ResourceRecordSet#getType()\n       */\n      public Builder type(String type) {\n         this.type = type;\n         return this;\n      }\n\n      /**\n       * @see ResourceRecordSet#getTTL()\n       */\n      public Builder ttl(int ttl) {\n         this.ttl = Optional.of(ttl);\n         return this;\n      }\n\n      /**\n       * @see ResourceRecordSet#getAliasTarget()\n       */\n      public Builder dnsName(String dnsName) {\n         this.dnsName = dnsName;\n         return this;\n      }\n\n      /**\n       * @see ResourceRecordSet#getAliasTarget()\n       */\n      public Builder zoneId(String zoneId) {\n         this.zoneId = zoneId;\n         return this;\n      }\n\n      /**\n       * @see ResourceRecordSet#getAliasTarget()\n       */\n      public Builder aliasTarget(AliasTarget aliasTarget) {\n         if (aliasTarget == null) {\n            dnsName = null;\n            zoneId = null;\n         } else {\n            dnsName = aliasTarget.dnsName;\n            zoneId = aliasTarget.zoneId;\n         }\n         return this;\n      }\n\n      /**\n       * @see ResourceRecordSet#getValues()\n       */\n      public Builder add(String values) {\n         this.values.add(values);\n         return this;\n      }\n\n      /**\n       * replaces current values\n       * \n       * @see ResourceRecordSet#getValues()\n       */\n      public Builder values(Iterable<String> values) {\n         this.values = ImmutableList.<String> builder().addAll(values);\n         return this;\n      }\n\n      /**\n       * @see ResourceRecordSet#getValues()\n       */\n      public Builder addAll(Iterable<String> values) {\n         this.values.addAll(values);\n         return this;\n      }\n\n      /**\n       * @see RecordSubset.Weighted\n       */\n      public Builder weight(int weight) {\n         this.weight = weight;\n         return this;\n      }\n\n      /**\n       * @see RecordSubset.Latency\n       */\n      public Builder region(String region) {\n         this.region = region;\n         return this;\n      }\n\n      public ResourceRecordSet build() {\n         Optional<AliasTarget> aliasTarget = dnsName != null ? Optional.fromNullable(AliasTarget.dnsNameInZone(dnsName, zoneId))\n               : Optional.<AliasTarget> absent();\n         if (weight != null) {\n            return new RecordSubset.Weighted(id, name, type, weight, ttl, values.build(), aliasTarget);\n         } else if (region != null) {\n            return new RecordSubset.Latency(id, name, type, region, ttl, values.build(), aliasTarget);\n         }\n         return new ResourceRecordSet(name, type, ttl, values.build(), aliasTarget);\n      }\n\n      public Builder from(ResourceRecordSet in) {\n         if (in instanceof RecordSubset)\n            id(RecordSubset.class.cast(in).id);\n         if (in instanceof Weighted) {\n            weight(Weighted.class.cast(in).weight);\n         } else if (in instanceof Latency) {\n            region(Latency.class.cast(in).region);\n         }\n         return this.name(in.name).type(in.type).ttl(in.ttl.orNull()).values(in.values)\n               .aliasTarget(in.aliasTarget.orNull());\n      }\n   }\n}\n"
  },
  {
    "path": "apis/route53/src/main/java/org/jclouds/route53/domain/ResourceRecordSetIterable.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Iterator;\n\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableList;\n\npublic class ResourceRecordSetIterable extends IterableWithMarker<ResourceRecordSet> {\n\n   private final Iterable<ResourceRecordSet> items;\n   private final Optional<NextRecord> nextRecord;\n\n   private ResourceRecordSetIterable(Iterable<ResourceRecordSet> items, @Nullable NextRecord nextRecord) {\n      this.items = checkNotNull(items, \"items\");\n      this.nextRecord = Optional.fromNullable(nextRecord);\n   }\n\n   /**\n    * present when the list is not truncated\n    */\n   public Optional<NextRecord> nextRecord() {\n      return nextRecord;\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public Optional<Object> nextMarker() {\n      return Optional.class.cast(nextRecord);\n   }\n\n   @Override\n   public Iterator<ResourceRecordSet> iterator() {\n      return items.iterator();\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(items, nextRecord);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      ResourceRecordSetIterable that = ResourceRecordSetIterable.class.cast(obj);\n      return equal(this.items, that.items) && equal(this.nextRecord, that.nextRecord);\n   }\n\n   @Override\n   public String toString() {\n      return toStringHelper(\"\").omitNullValues().add(\"items\", items).add(\"nextRecord\", nextRecord.orNull()).toString();\n   }\n\n   /**\n    * If the results were truncated, this holds the position of the next item.\n    */\n   public static class NextRecord {\n      public static NextRecord name(String name) {\n         return new NextRecord(name, null, null);\n      }\n\n      public static NextRecord nameAndType(String name, String type) {\n         return new NextRecord(name, type, null);\n      }\n\n      public static NextRecord nameTypeAndIdentifier(String name, String type, String identifier) {\n         return new NextRecord(name, type, identifier);\n      }\n\n      private final String name;\n      private final Optional<String> type;\n      private final Optional<String> identifier;\n\n      private NextRecord(String name, String type, String identifier) {\n         this.name = checkNotNull(name, \"name\");\n         this.type = Optional.fromNullable(type);\n         this.identifier = Optional.fromNullable(identifier);\n      }\n\n      /**\n       * If the results were truncated, the name of the next record in the list.\n       */\n      public String getName() {\n         return name;\n      }\n\n      /**\n       * the type of the next record in the list.\n       */\n      public Optional<String> getType() {\n         return type;\n      }\n\n      /**\n       * Weighted and latency resource record sets only.\n       */\n      public Optional<String> getIdentifier() {\n         return identifier;\n      }\n\n      @Override\n      public int hashCode() {\n         return Objects.hashCode(name, type, identifier);\n      }\n\n      @Override\n      public boolean equals(Object obj) {\n         if (this == obj)\n            return true;\n         if (obj == null || getClass() != obj.getClass())\n            return false;\n         NextRecord that = NextRecord.class.cast(obj);\n         return equal(this.name, that.name) && equal(this.type, that.type) && equal(this.identifier, that.identifier);\n      }\n\n      @Override\n      public String toString() {\n         return toStringHelper(\"\").omitNullValues().add(\"name\", name).add(\"type\", type.orNull())\n               .add(\"identifier\", identifier.orNull()).toString();\n      }\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static final class Builder {\n\n      private ImmutableList.Builder<ResourceRecordSet> items = ImmutableList.<ResourceRecordSet> builder();\n      private String nextRecordName;\n      private String nextRecordType;\n      private String nextRecordIdentifier;\n\n      public Builder add(ResourceRecordSet item) {\n         this.items.add(item);\n         return this;\n      }\n\n      public Builder addAll(Iterable<ResourceRecordSet> items) {\n         this.items.addAll(items);\n         return this;\n      }\n\n      public Builder nextRecordName(String nextRecordName) {\n         this.nextRecordName = nextRecordName;\n         return this;\n      }\n\n      public Builder nextRecordType(String nextRecordType) {\n         this.nextRecordType = nextRecordType;\n         return this;\n      }\n\n      public Builder nextRecordIdentifier(String nextRecordIdentifier) {\n         this.nextRecordIdentifier = nextRecordIdentifier;\n         return this;\n      }\n\n      public ResourceRecordSetIterable build() {\n         NextRecord nextRecord = nextRecordName != null ? new NextRecord(nextRecordName, nextRecordType,\n               nextRecordIdentifier) : null;\n         return new ResourceRecordSetIterable(items.build(), nextRecord);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/route53/src/main/java/org/jclouds/route53/features/HostedZoneApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_XML;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.QueryParam;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.PagedIterable;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.Transform;\nimport org.jclouds.rest.annotations.VirtualHost;\nimport org.jclouds.rest.annotations.XMLResponseParser;\nimport org.jclouds.route53.domain.Change;\nimport org.jclouds.route53.domain.HostedZone;\nimport org.jclouds.route53.domain.HostedZoneAndNameServers;\nimport org.jclouds.route53.domain.NewHostedZone;\nimport org.jclouds.route53.filters.RestAuthentication;\nimport org.jclouds.route53.functions.HostedZonesToPagedIterable;\nimport org.jclouds.route53.xml.ChangeHandler;\nimport org.jclouds.route53.xml.CreateHostedZoneResponseHandler;\nimport org.jclouds.route53.xml.GetHostedZoneResponseHandler;\nimport org.jclouds.route53.xml.ListHostedZonesResponseHandler;\n\n/**\n * @see <a href=\n *      \"http://docs.aws.amazon.com/Route53/latest/APIReference/ActionsOnHostedZones.html\"\n *      />\n */\n@RequestFilters(RestAuthentication.class)\n@VirtualHost\npublic interface HostedZoneApi {\n\n   /**\n    * This action creates a new hosted zone.\n    * \n    * <h4>Note</h4>\n    * \n    * You cannot create a hosted zone for a top-level domain (TLD).\n    * \n    * @param name\n    *           The name of the domain. ex. {@code  www.example.com.} The\n    *           trailing dot is optional.\n    * @param callerReference\n    *           A unique string that identifies the request and allows safe\n    *           retries. ex. {@code MyDNSMigration_01}\n    * @return the new zone in progress, in {@link Status#PENDING}.\n    */\n   @Named(\"CreateHostedZone\")\n   @POST\n   @Produces(APPLICATION_XML)\n   @Path(\"/hostedzone\")\n   @Payload(\"<CreateHostedZoneRequest xmlns=\\\"https://route53.amazonaws.com/doc/2012-02-29/\\\"><Name>{name}</Name><CallerReference>{callerReference}</CallerReference></CreateHostedZoneRequest>\")\n   @XMLResponseParser(CreateHostedZoneResponseHandler.class)\n   NewHostedZone createWithReference(@PayloadParam(\"name\") String name,\n         @PayloadParam(\"callerReference\") String callerReference);\n\n   /**\n    * like {@link #createWithReference(String, String)}, except you can specify\n    * a comment.\n    */\n   @Named(\"CreateHostedZone\")\n   @POST\n   @Produces(APPLICATION_XML)\n   @Path(\"/hostedzone\")\n   @Payload(\"<CreateHostedZoneRequest xmlns=\\\"https://route53.amazonaws.com/doc/2012-02-29/\\\"><Name>{name}</Name><CallerReference>{callerReference}</CallerReference><HostedZoneConfig><Comment>{comment}</Comment></HostedZoneConfig></CreateHostedZoneRequest>\")\n   @XMLResponseParser(CreateHostedZoneResponseHandler.class)\n   NewHostedZone createWithReferenceAndComment(@PayloadParam(\"name\") String name,\n         @PayloadParam(\"callerReference\") String callerReference, @PayloadParam(\"comment\") String comment);\n\n   /**\n    * returns all zones in order.\n    */\n   @Named(\"ListHostedZones\")\n   @GET\n   @Path(\"/hostedzone\")\n   @XMLResponseParser(ListHostedZonesResponseHandler.class)\n   @Transform(HostedZonesToPagedIterable.class)\n   PagedIterable<HostedZone> list();\n\n   /**\n    * retrieves up to 100 zones in order.\n    */\n   @Named(\"ListHostedZones\")\n   @GET\n   @Path(\"/hostedzone\")\n   @XMLResponseParser(ListHostedZonesResponseHandler.class)\n   IterableWithMarker<HostedZone> listFirstPage();\n\n   /**\n    * retrieves up to 100 zones in order, starting at {@code nextMarker}\n    */\n   @Named(\"ListHostedZones\")\n   @GET\n   @Path(\"/hostedzone\")\n   @XMLResponseParser(ListHostedZonesResponseHandler.class)\n   IterableWithMarker<HostedZone> listAt(@QueryParam(\"marker\") String nextMarker);\n\n   /**\n    * Retrieves information about the specified zone, including its nameserver\n    * configuration\n    * \n    * @param id\n    *           id of the zone to get information about. ex\n    *           {@code Z1PA6795UKMFR9}\n    * @return null if not found\n    */\n   @Named(\"GetHostedZone\")\n   @GET\n   @Path(\"/hostedzone/{zoneId}\")\n   @XMLResponseParser(GetHostedZoneResponseHandler.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   HostedZoneAndNameServers get(@PathParam(\"zoneId\") String zoneId);\n\n   /**\n    * This action deletes a hosted zone.\n    * \n    * @param id\n    *           id of the zone to delete. ex {@code Z1PA6795UKMFR9}\n    * @return null if not found or the change in progress\n    */\n   @Named(\"DeleteHostedZone\")\n   @DELETE\n   @Path(\"/hostedzone/{zoneId}\")\n   @XMLResponseParser(ChangeHandler.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Change delete(@PathParam(\"zoneId\") String zoneId);\n}\n"
  },
  {
    "path": "apis/route53/src/main/java/org/jclouds/route53/features/ResourceRecordSetApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_XML;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.Produces;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.collect.PagedIterable;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.ParamParser;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.Transform;\nimport org.jclouds.rest.annotations.VirtualHost;\nimport org.jclouds.rest.annotations.XMLResponseParser;\nimport org.jclouds.route53.binders.BindChangeBatch;\nimport org.jclouds.route53.binders.BindNextRecord;\nimport org.jclouds.route53.domain.Change;\nimport org.jclouds.route53.domain.ChangeBatch;\nimport org.jclouds.route53.domain.ResourceRecordSet;\nimport org.jclouds.route53.domain.ResourceRecordSetIterable;\nimport org.jclouds.route53.domain.ResourceRecordSetIterable.NextRecord;\nimport org.jclouds.route53.filters.RestAuthentication;\nimport org.jclouds.route53.functions.ResourceRecordSetIterableToPagedIterable;\nimport org.jclouds.route53.functions.SerializeRRS;\nimport org.jclouds.route53.xml.ChangeHandler;\nimport org.jclouds.route53.xml.ListResourceRecordSetsResponseHandler;\n\n/**\n * @see <a href=\n *      \"http://docs.aws.amazon.com/Route53/latest/APIReference/ActionsOnRRS.html\"\n *      />\n */\n@RequestFilters(RestAuthentication.class)\n@VirtualHost\npublic interface ResourceRecordSetApi {\n\n   /**\n    * schedules creation of the resource record set.\n    */\n   @Named(\"ChangeResourceRecordSets\")\n   @POST\n   @Produces(APPLICATION_XML)\n   @Path(\"/rrset\")\n   @Payload(\"<ChangeResourceRecordSetsRequest xmlns=\\\"https://route53.amazonaws.com/doc/2012-02-29/\\\"><ChangeBatch><Changes><Change><Action>CREATE</Action>{rrs}</Change></Changes></ChangeBatch></ChangeResourceRecordSetsRequest>\")\n   @XMLResponseParser(ChangeHandler.class)\n   Change create(@PayloadParam(\"rrs\") @ParamParser(SerializeRRS.class) ResourceRecordSet rrs);\n\n   /**\n    * applies a batch of changes atomically.\n    */\n   @Named(\"ChangeResourceRecordSets\")\n   @POST\n   @Produces(APPLICATION_XML)\n   @Path(\"/rrset\")\n   @XMLResponseParser(ChangeHandler.class)\n   Change apply(@BinderParam(BindChangeBatch.class) ChangeBatch changes);\n\n   /**\n    * returns all resource record sets in order.\n    */\n   @Named(\"ListResourceRecordSets\")\n   @GET\n   @Path(\"/rrset\")\n   @XMLResponseParser(ListResourceRecordSetsResponseHandler.class)\n   @Transform(ResourceRecordSetIterableToPagedIterable.class)\n   PagedIterable<ResourceRecordSet> list();\n\n   /**\n    * retrieves up to 100 resource record sets in order.\n    */\n   @Named(\"ListResourceRecordSets\")\n   @GET\n   @Path(\"/rrset\")\n   @XMLResponseParser(ListResourceRecordSetsResponseHandler.class)\n   ResourceRecordSetIterable listFirstPage();\n\n   /**\n    * retrieves up to 100 resource record sets in order, starting at\n    * {@code nextRecord}\n    */\n   @Named(\"ListResourceRecordSets\")\n   @GET\n   @Path(\"/rrset\")\n   @XMLResponseParser(ListResourceRecordSetsResponseHandler.class)\n   ResourceRecordSetIterable listAt(@BinderParam(BindNextRecord.class) NextRecord nextRecord);\n\n   /**\n    * This action deletes a resource record set.\n    * \n    * @param rrs\n    *           the resource record set to delete\n    * @return null if not found or the change in progress\n    */\n   @Named(\"ChangeResourceRecordSets\")\n   @POST\n   @Produces(APPLICATION_XML)\n   @Path(\"/rrset\")\n   @Payload(\"<ChangeResourceRecordSetsRequest xmlns=\\\"https://route53.amazonaws.com/doc/2012-02-29/\\\"><ChangeBatch><Changes><Change><Action>DELETE</Action>{rrs}</Change></Changes></ChangeBatch></ChangeResourceRecordSetsRequest>\")\n   @XMLResponseParser(ChangeHandler.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Change delete(@PayloadParam(\"rrs\") @ParamParser(SerializeRRS.class) ResourceRecordSet rrs);\n}\n"
  },
  {
    "path": "apis/route53/src/main/java/org/jclouds/route53/filters/RestAuthentication.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53.filters;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.base.Throwables.propagate;\nimport static com.google.common.io.BaseEncoding.base64;\nimport static com.google.common.net.HttpHeaders.DATE;\n\nimport java.security.InvalidKeyException;\nimport java.security.NoSuchAlgorithmException;\n\nimport javax.crypto.Mac;\nimport javax.crypto.spec.SecretKeySpec;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Provider;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.domain.SessionCredentials;\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpRequestFilter;\nimport org.jclouds.rest.RequestSigner;\n\nimport com.google.common.base.Supplier;\n\n/**\n * Signs the Route53 request.\n * \n * @see <a href=\n *      \"http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/RESTAuthentication.html#StringToSign\"\n *      />\n */\n@Singleton\npublic class RestAuthentication implements HttpRequestFilter, RequestSigner {\n\n   private final Supplier<Credentials> creds;\n   private final Provider<String> timeStampProvider;\n\n   @Inject\n   public RestAuthentication(@org.jclouds.location.Provider Supplier<Credentials> creds,\n         @TimeStamp Provider<String> timeStampProvider) {\n      this.creds = creds;\n      this.timeStampProvider = timeStampProvider;\n   }\n\n   public HttpRequest filter(HttpRequest request) throws HttpException {\n      Credentials current = creds.get();\n      if (current instanceof SessionCredentials) {\n         request = replaceSecurityTokenHeader(request, SessionCredentials.class.cast(current));\n      }\n      request = replaceDateHeader(request, timeStampProvider.get());\n      String signature = sign(createStringToSign(request));\n      return replaceAuthorizationHeader(request, signature);\n   }\n\n   private HttpRequest replaceSecurityTokenHeader(HttpRequest request, SessionCredentials current) {\n      return request.toBuilder().replaceHeader(\"x-amz-security-token\", current.getSessionToken()).build();\n   }\n\n   private HttpRequest replaceDateHeader(HttpRequest request, String timestamp) {\n      request = request.toBuilder().replaceHeader(DATE, timestamp).build();\n      return request;\n   }\n\n   @Override\n   public String createStringToSign(HttpRequest input) {\n      return input.getFirstHeaderOrNull(DATE);\n   }\n\n   /**\n    * signs {@code toSign} using {@code HmacSHA256} initialized with\n    * {@link Credentials#credential}.\n    *\n    * @param toSign\n    *           string to sign in UTF-8 encoding\n    *\n    * @return base-64 encoded signature.\n    */\n   @Override\n   public String sign(String toSign) {\n      try {\n         SecretKeySpec keySpec = new SecretKeySpec(creds.get().credential.getBytes(UTF_8), \"HmacSHA256\");\n         Mac mac = Mac.getInstance(\"HmacSHA256\");\n         mac.init(keySpec);\n         byte[] result = mac.doFinal(toSign.getBytes(UTF_8));\n         return base64().encode(result);\n      } catch (InvalidKeyException e) {\n         throw propagate(e);\n      } catch (NoSuchAlgorithmException e) {\n         throw propagate(e);\n      }\n   }\n\n   private HttpRequest replaceAuthorizationHeader(HttpRequest request, String signature) {\n      request = request\n            .toBuilder()\n            .replaceHeader(\"X-Amzn-Authorization\",\n                  \"AWS3-HTTPS AWSAccessKeyId=\" + creds.get().identity + \",Algorithm=HmacSHA256,Signature=\" + signature)\n            .build();\n      return request;\n   }\n\n\n}\n"
  },
  {
    "path": "apis/route53/src/main/java/org/jclouds/route53/functions/HostedZonesToPagedIterable.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.internal.CallerArg0ToPagedIterable;\nimport org.jclouds.route53.Route53Api;\nimport org.jclouds.route53.domain.HostedZone;\nimport org.jclouds.route53.features.HostedZoneApi;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Function;\n\n@Beta\npublic class HostedZonesToPagedIterable extends CallerArg0ToPagedIterable<HostedZone, HostedZonesToPagedIterable> {\n\n   private final Route53Api api;\n\n   @Inject\n   protected HostedZonesToPagedIterable(Route53Api api) {\n      this.api = checkNotNull(api, \"api\");\n   }\n\n   @Override\n   protected Function<Object, IterableWithMarker<HostedZone>> markerToNextForCallingArg0(String ignored) {\n      final HostedZoneApi zoneApi = api.getHostedZoneApi();\n      return new Function<Object, IterableWithMarker<HostedZone>>() {\n\n         @Override\n         public IterableWithMarker<HostedZone> apply(Object input) {\n            return zoneApi.listAt(input.toString());\n         }\n\n         @Override\n         public String toString() {\n            return \"listHostedZones()\";\n         }\n      };\n   }\n}\n"
  },
  {
    "path": "apis/route53/src/main/java/org/jclouds/route53/functions/ResourceRecordSetIterableToPagedIterable.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.internal.CallerArg0ToPagedIterable;\nimport org.jclouds.route53.Route53Api;\nimport org.jclouds.route53.domain.ResourceRecordSet;\nimport org.jclouds.route53.domain.ResourceRecordSetIterable.NextRecord;\nimport org.jclouds.route53.features.ResourceRecordSetApi;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Function;\n\n@Beta\npublic class ResourceRecordSetIterableToPagedIterable extends\n      CallerArg0ToPagedIterable<ResourceRecordSet, ResourceRecordSetIterableToPagedIterable> {\n\n   private final Route53Api api;\n\n   @Inject\n   protected ResourceRecordSetIterableToPagedIterable(Route53Api api) {\n      this.api = checkNotNull(api, \"api\");\n   }\n\n   @Override\n   protected Function<Object, IterableWithMarker<ResourceRecordSet>> markerToNextForCallingArg0(String zoneId) {\n      final ResourceRecordSetApi resourceResourceRecordSetApi = api.getResourceRecordSetApiForHostedZone(zoneId);\n      return new Function<Object, IterableWithMarker<ResourceRecordSet>>() {\n\n         @Override\n         public IterableWithMarker<ResourceRecordSet> apply(Object input) {\n            return resourceResourceRecordSetApi.listAt(NextRecord.class.cast(input));\n         }\n\n         @Override\n         public String toString() {\n            return \"listResourceRecordSets()\";\n         }\n      };\n   }\n}\n"
  },
  {
    "path": "apis/route53/src/main/java/org/jclouds/route53/functions/SerializeRRS.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.route53.domain.ResourceRecordSet;\nimport org.jclouds.route53.domain.ResourceRecordSet.RecordSubset;\nimport org.jclouds.route53.domain.ResourceRecordSet.RecordSubset.Latency;\nimport org.jclouds.route53.domain.ResourceRecordSet.RecordSubset.Weighted;\n\nimport com.google.common.base.Function;\n\npublic class SerializeRRS implements Function<Object, String> {\n   @Override\n   public String apply(Object in) {\n      ResourceRecordSet rrs = ResourceRecordSet.class.cast(checkNotNull(in, \"rrs\"));\n      StringBuilder builder = new StringBuilder().append(\"<ResourceRecordSet>\");\n      builder.append(\"<Name>\").append(rrs.getName()).append(\"</Name>\");\n      builder.append(\"<Type>\").append(rrs.getType()).append(\"</Type>\");\n      if (rrs instanceof RecordSubset) {\n         String id = RecordSubset.class.cast(rrs).getId();\n         builder.append(\"<SetIdentifier>\").append(id).append(\"</SetIdentifier>\");\n      }\n      if (rrs instanceof Weighted)\n         builder.append(\"<Weight>\").append(Weighted.class.cast(rrs).getWeight()).append(\"</Weight>\");\n      if (rrs instanceof Latency)\n         builder.append(\"<Region>\").append(Latency.class.cast(rrs).getRegion()).append(\"</Region>\");\n      if (rrs.getAliasTarget().isPresent()) {\n         builder.append(\"<AliasTarget>\");\n         builder.append(\"<HostedZoneId>\").append(rrs.getAliasTarget().get().getZoneId()).append(\"</HostedZoneId>\");\n         builder.append(\"<DNSName>\").append(rrs.getAliasTarget().get().getDNSName()).append(\"</DNSName>\");\n         builder.append(\"</AliasTarget>\");\n      } else {\n         // default ttl from the amazon console is 300\n         builder.append(\"<TTL>\").append(rrs.getTTL().or(300)).append(\"</TTL>\");\n         builder.append(\"<ResourceRecords>\");\n         for (String record : rrs.getValues())\n            builder.append(\"<ResourceRecord>\").append(\"<Value>\").append(record).append(\"</Value>\")\n                  .append(\"</ResourceRecord>\");\n         builder.append(\"</ResourceRecords>\");\n      }\n      return builder.append(\"</ResourceRecordSet>\").toString();\n   }\n}\n"
  },
  {
    "path": "apis/route53/src/main/java/org/jclouds/route53/handlers/Route53ErrorHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53.handlers;\n\nimport static org.jclouds.http.HttpUtils.closeClientButKeepContentStream;\nimport static org.jclouds.http.HttpUtils.releasePayload;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Provider;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.AWSResponseException;\nimport org.jclouds.aws.domain.AWSError;\nimport org.jclouds.aws.xml.ErrorHandler;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.http.functions.ParseSax.Factory;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.InsufficientResourcesException;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.jclouds.route53.InvalidChangeBatchException;\nimport org.jclouds.route53.xml.InvalidChangeBatchHandler;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\n\n@Singleton\npublic class Route53ErrorHandler implements HttpErrorHandler {\n\n   private final Factory factory;\n   private final Provider<ErrorHandler> handlers;\n   private final Provider<InvalidChangeBatchHandler> batchHandlers;\n\n   @Inject\n   Route53ErrorHandler(Factory factory, Provider<ErrorHandler> handlers,\n         Provider<InvalidChangeBatchHandler> batchHandlers) {\n      this.factory = factory;\n      this.handlers = handlers;\n      this.batchHandlers = batchHandlers;\n   }\n\n   public void handleError(HttpCommand command, HttpResponse response) {\n      Exception exception = new HttpResponseException(command, response);\n      try {\n         byte[] data = closeClientButKeepContentStream(response);\n         String message = data != null ? new String(data) : null;\n         if (message != null) {\n            exception = new HttpResponseException(command, response, message);\n            if (message.indexOf(\"ErrorResponse\") != -1) {\n               AWSError error = factory.create(handlers.get()).parse(message);\n               exception = refineException(new AWSResponseException(command, response, error));\n            } else if (message.indexOf(\"InvalidChangeBatch\") != -1) {\n               ImmutableList<String> errors = factory.create(batchHandlers.get()).parse(message);\n               exception = new InvalidChangeBatchException(errors, new HttpResponseException(command, response));\n            }\n         }\n      } finally {\n         releasePayload(response);\n         command.setException(exception);\n      }\n   }\n\n   private Exception refineException(AWSResponseException in) {\n      int statusCode = in.getResponse().getStatusCode();\n      String errorCode = in.getError().getCode();\n      String message = in.getError().getMessage();\n\n      if (statusCode == 403 || \"RequestExpired\".equals(errorCode))\n         return new AuthorizationException(message, in);\n      if (statusCode == 400) {\n         if (ImmutableSet.of(\"InvalidAction\", \"AccessDenied\").contains(errorCode))\n            return new UnsupportedOperationException(message, in);\n         else if (\"Throttling\".equals(errorCode))\n            return new InsufficientResourcesException(message, in);\n         else if (message.indexOf(\"not found\") != -1)\n            return new ResourceNotFoundException(message, in);\n         return new IllegalArgumentException(message, in);\n      }\n      return in;\n   }\n}\n"
  },
  {
    "path": "apis/route53/src/main/java/org/jclouds/route53/predicates/HostedZonePredicates.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.route53.domain.HostedZone;\n\nimport com.google.common.base.Predicate;\n\n/**\n * Predicates handy when working with HostedZones\n */\npublic class HostedZonePredicates {\n\n   /**\n    * matches zones of the given name\n    */\n   public static Predicate<HostedZone> nameEquals(final String name) {\n      checkNotNull(name, \"name must be defined\");\n\n      return new Predicate<HostedZone>() {\n         @Override\n         public boolean apply(HostedZone zone) {\n            return name.equals(zone.getName());\n         }\n\n         @Override\n         public String toString() {\n            return \"nameEquals(\" + name + \")\";\n         }\n      };\n   }\n}\n"
  },
  {
    "path": "apis/route53/src/main/java/org/jclouds/route53/predicates/ResourceRecordSetPredicates.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.route53.domain.ResourceRecordSet;\n\nimport com.google.common.base.Predicate;\n\n/**\n * Predicates handy when working with ResourceResourceRecordSet Types\n */\npublic class ResourceRecordSetPredicates {\n\n   /**\n    * matches zones of the given type\n    */\n   public static Predicate<ResourceRecordSet> typeEquals(final String type) {\n      checkNotNull(type, \"type must be defined\");\n\n      return new Predicate<ResourceRecordSet>() {\n         @Override\n         public boolean apply(ResourceRecordSet zone) {\n            return type.equals(zone.getType());\n         }\n\n         @Override\n         public String toString() {\n            return \"typeEquals(\" + type + \")\";\n         }\n      };\n   }\n}\n"
  },
  {
    "path": "apis/route53/src/main/java/org/jclouds/route53/xml/ChangeHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53.xml;\n\nimport static org.jclouds.util.SaxUtils.currentOrNull;\n\nimport java.util.Date;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.route53.domain.Change;\nimport org.jclouds.route53.domain.Change.Status;\nimport org.xml.sax.Attributes;\n\n/**\n * @see <a href=\n *      \"http://docs.aws.amazon.com/Route53/latest/APIReference/API_GetChange.html\"\n *      />\n */\npublic class ChangeHandler extends ParseSax.HandlerForGeneratedRequestWithResult<Change> {\n   private final DateService dateService;\n\n   @Inject\n   protected ChangeHandler(DateService dateService) {\n      this.dateService = dateService;\n   }\n\n   private StringBuilder currentText = new StringBuilder();\n\n   private String id;\n   private Status status;\n   private Date submittedAt;\n\n   @Override\n   public Change getResult() {\n      try {\n         return Change.create(id, status, submittedAt);\n      } finally {\n         id = null;\n         status = null;\n         submittedAt = null;\n      }\n   }\n\n   @Override\n   public void startElement(String url, String name, String qName, Attributes attributes) {\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) {\n      if (qName.equals(\"Id\")) {\n         id = currentOrNull(currentText).replace(\"/change/\", \"\");\n      } else if (qName.equals(\"Status\")) {\n         status = Status.fromValue(currentOrNull(currentText));\n      } else if (qName.equals(\"SubmittedAt\")) {\n         submittedAt = dateService.iso8601DateParse(currentOrNull(currentText));\n      }\n      currentText.setLength(0);\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n\n}\n"
  },
  {
    "path": "apis/route53/src/main/java/org/jclouds/route53/xml/CreateHostedZoneResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53.xml;\n\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.route53.domain.HostedZoneAndNameServers;\nimport org.jclouds.route53.domain.NewHostedZone;\nimport org.xml.sax.Attributes;\n\nimport com.google.inject.Inject;\n\n/**\n * @see <a href=\n *      \"http://docs.aws.amazon.com/Route53/latest/APIReference/API_CreateHostedZone.html\"\n *      />\n */\npublic class CreateHostedZoneResponseHandler extends ParseSax.HandlerForGeneratedRequestWithResult<NewHostedZone> {\n\n   private final GetHostedZoneResponseHandler zoneHandler;\n   private final ChangeHandler changeHandler;\n\n   private boolean inChange;\n\n   @Inject\n   public CreateHostedZoneResponseHandler(GetHostedZoneResponseHandler zoneHandler, ChangeHandler changeHandler) {\n      this.zoneHandler = zoneHandler;\n      this.changeHandler = changeHandler;\n   }\n\n   @Override\n   public NewHostedZone getResult() {\n      HostedZoneAndNameServers zone = zoneHandler.getResult();\n      return NewHostedZone.create(zone, changeHandler.getResult());\n   }\n\n   @Override\n   public void startElement(String url, String name, String qName, Attributes attributes) {\n      if (equalsOrSuffix(qName, \"ChangeInfo\")) {\n         inChange = true;\n      }\n      if (inChange) {\n         changeHandler.startElement(url, name, qName, attributes);\n      } else {\n         zoneHandler.startElement(url, name, qName, attributes);\n      }\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) {\n      if (inChange) {\n         if (qName.equals(\"ChangeInfo\")) {\n            inChange = false;\n         } else {\n            changeHandler.endElement(uri, name, qName);\n         }\n      } else {\n         zoneHandler.endElement(uri, name, qName);\n      }\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      if (inChange) {\n         changeHandler.characters(ch, start, length);\n      } else {\n         zoneHandler.characters(ch, start, length);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/route53/src/main/java/org/jclouds/route53/xml/GetHostedZoneResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53.xml;\n\nimport static org.jclouds.util.SaxUtils.currentOrNull;\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.route53.domain.HostedZone;\nimport org.jclouds.route53.domain.HostedZoneAndNameServers;\nimport org.xml.sax.Attributes;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableList.Builder;\nimport com.google.inject.Inject;\n\n/**\n * @see <a href=\n *      \"http://docs.aws.amazon.com/Route53/latest/APIReference/API_GetHostedZone.html\"\n *      />\n */\npublic class GetHostedZoneResponseHandler extends ParseSax.HandlerForGeneratedRequestWithResult<HostedZoneAndNameServers> {\n\n   private final HostedZoneHandler zoneHandler;\n\n   private StringBuilder currentText = new StringBuilder();\n   \n   private boolean inHostedZone;\n\n   private HostedZone zone;\n   private Builder<String> nameServers = ImmutableList.<String> builder();\n\n   @Inject\n   public GetHostedZoneResponseHandler(HostedZoneHandler zoneHandler) {\n      this.zoneHandler = zoneHandler;\n   }\n\n   @Override\n   public HostedZoneAndNameServers getResult() {\n      try {\n         return HostedZoneAndNameServers.create(zone, nameServers.build());\n      } finally {\n         zone = null;\n         nameServers = ImmutableList.<String> builder();\n      }\n   }\n\n   @Override\n   public void startElement(String url, String name, String qName, Attributes attributes) {\n      if (equalsOrSuffix(qName, \"HostedZone\")) {\n         inHostedZone = true;\n      }\n      if (inHostedZone) {\n         zoneHandler.startElement(url, name, qName, attributes);\n      }\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) {\n      if (inHostedZone) {\n         if (qName.equals(\"HostedZone\")) {\n            inHostedZone = false;\n            zone = zoneHandler.getResult();\n         } else {\n            zoneHandler.endElement(uri, name, qName);\n         }\n      } else if (qName.equals(\"NameServer\")) {\n         nameServers.add(currentOrNull(currentText));\n      }\n\n      currentText.setLength(0);\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      if (inHostedZone) {\n         zoneHandler.characters(ch, start, length);\n      } else {\n         currentText.append(ch, start, length);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/route53/src/main/java/org/jclouds/route53/xml/HostedZoneHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53.xml;\n\nimport static org.jclouds.util.SaxUtils.currentOrNull;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.route53.domain.HostedZone;\nimport org.xml.sax.Attributes;\n\n\npublic class HostedZoneHandler extends ParseSax.HandlerForGeneratedRequestWithResult<HostedZone> {\n\n   private StringBuilder currentText = new StringBuilder();\n   private HostedZone.Builder builder = HostedZone.builder();\n\n   @Override\n   public HostedZone getResult() {\n      try {\n         return builder.build();\n      } finally {\n         builder = HostedZone.builder();\n      }\n   }\n\n   @Override\n   public void startElement(String url, String name, String qName, Attributes attributes) {\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) {\n      if (qName.equals(\"Id\")) {\n         builder.id(currentOrNull(currentText).replace(\"/hostedzone/\", \"\"));\n      } else if (qName.equals(\"Name\")) {\n         builder.name(currentOrNull(currentText));\n      } else if (qName.equals(\"CallerReference\")) {\n         builder.callerReference(currentOrNull(currentText));\n      } else if (qName.equals(\"Comment\")) {\n         builder.comment(currentOrNull(currentText));\n      } else if (qName.equals(\"ResourceRecordSetCount\")) {\n         builder.resourceRecordSetCount(Integer.parseInt(currentOrNull(currentText)));\n      }\n      currentText.setLength(0);\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "apis/route53/src/main/java/org/jclouds/route53/xml/InvalidChangeBatchHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53.xml;\n\nimport static org.jclouds.util.SaxUtils.currentOrNull;\n\nimport org.jclouds.http.functions.ParseSax;\n\nimport com.google.common.collect.ImmutableList;\n\npublic class InvalidChangeBatchHandler extends ParseSax.HandlerForGeneratedRequestWithResult<ImmutableList<String>> {\n\n   private StringBuilder currentText = new StringBuilder();\n   private ImmutableList.Builder<String> builder = ImmutableList.builder();\n\n   @Override\n   public ImmutableList<String> getResult() {\n      return builder.build();\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) {\n      if (qName.equals(\"Message\")) {\n         builder.add(currentOrNull(currentText));\n      }\n      currentText.setLength(0);\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "apis/route53/src/main/java/org/jclouds/route53/xml/ListHostedZonesResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53.xml;\n\nimport static org.jclouds.util.SaxUtils.currentOrNull;\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.IterableWithMarkers;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.route53.domain.HostedZone;\nimport org.xml.sax.Attributes;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableList.Builder;\nimport com.google.inject.Inject;\n\n/**\n * @see <a href=\n *      \"http://docs.aws.amazon.com/Route53/latest/APIReference/API_ListHostedZones.html\"\n *      />\n */\npublic class ListHostedZonesResponseHandler extends\n      ParseSax.HandlerForGeneratedRequestWithResult<IterableWithMarker<HostedZone>> {\n\n   private final HostedZoneHandler zoneHandler;\n\n   private StringBuilder currentText = new StringBuilder();\n   private Builder<HostedZone> zones = ImmutableList.<HostedZone> builder();\n   private boolean inHostedZones;\n   private String afterMarker;\n\n   @Inject\n   public ListHostedZonesResponseHandler(HostedZoneHandler zoneHandler) {\n      this.zoneHandler = zoneHandler;\n   }\n\n   @Override\n   public IterableWithMarker<HostedZone> getResult() {\n      try {\n         return IterableWithMarkers.from(zones.build(), afterMarker);\n      } finally {\n         zones = ImmutableList.<HostedZone> builder();\n      }\n   }\n\n   @Override\n   public void startElement(String url, String name, String qName, Attributes attributes) {\n      if (equalsOrSuffix(qName, \"HostedZones\")) {\n         inHostedZones = true;\n      }\n      if (inHostedZones) {\n         zoneHandler.startElement(url, name, qName, attributes);\n      }\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) {\n      if (inHostedZones) {\n         if (qName.equals(\"HostedZones\")) {\n            inHostedZones = false;\n         } else if (qName.equals(\"HostedZone\")) {\n            zones.add(zoneHandler.getResult());\n         } else {\n            zoneHandler.endElement(uri, name, qName);\n         }\n      } else if (qName.equals(\"NextMarker\")) {\n         afterMarker = currentOrNull(currentText);\n      }\n\n      currentText.setLength(0);\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      if (inHostedZones) {\n         zoneHandler.characters(ch, start, length);\n      } else {\n         currentText.append(ch, start, length);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/route53/src/main/java/org/jclouds/route53/xml/ListResourceRecordSetsResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53.xml;\n\nimport static org.jclouds.util.SaxUtils.currentOrNull;\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.route53.domain.ResourceRecordSetIterable;\nimport org.jclouds.route53.domain.ResourceRecordSetIterable.Builder;\nimport org.xml.sax.Attributes;\n\nimport com.google.inject.Inject;\n\n/**\n * @see <a href=\n *      \"http://docs.aws.amazon.com/Route53/latest/APIReference/API_ListResourceRecordSets.html\"\n *      />\n */\npublic class ListResourceRecordSetsResponseHandler extends\n      ParseSax.HandlerForGeneratedRequestWithResult<ResourceRecordSetIterable> {\n\n   private final ResourceRecordSetHandler resourceRecordSetHandler;\n\n   private StringBuilder currentText = new StringBuilder();\n   private Builder builder = ResourceRecordSetIterable.builder();\n\n   private boolean inResourceRecordSets;\n\n   @Inject\n   public ListResourceRecordSetsResponseHandler(ResourceRecordSetHandler resourceRecordSetHandler) {\n      this.resourceRecordSetHandler = resourceRecordSetHandler;\n   }\n\n   @Override\n   public ResourceRecordSetIterable getResult() {\n      try {\n         return builder.build();\n      } finally {\n         builder = ResourceRecordSetIterable.builder();\n      }\n   }\n\n   @Override\n   public void startElement(String url, String name, String qName, Attributes attributes) {\n      if (equalsOrSuffix(qName, \"ResourceRecordSets\")) {\n         inResourceRecordSets = true;\n      }\n      if (inResourceRecordSets) {\n         resourceRecordSetHandler.startElement(url, name, qName, attributes);\n      }\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) {\n      if (inResourceRecordSets) {\n         if (qName.equals(\"ResourceRecordSets\")) {\n            inResourceRecordSets = false;\n         } else if (qName.equals(\"ResourceRecordSet\")) {\n            builder.add(resourceRecordSetHandler.getResult());\n         } else {\n            resourceRecordSetHandler.endElement(uri, name, qName);\n         }\n      } else if (qName.equals(\"NextRecordName\")) {\n         builder.nextRecordName(currentOrNull(currentText));\n      } else if (qName.equals(\"NextRecordType\")) {\n         builder.nextRecordType(currentOrNull(currentText));\n      } else if (qName.equals(\"NextRecordIdentifier\")) {\n         builder.nextRecordIdentifier(currentOrNull(currentText));\n      }\n      currentText.setLength(0);\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      if (inResourceRecordSets) {\n         resourceRecordSetHandler.characters(ch, start, length);\n      } else {\n         currentText.append(ch, start, length);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/route53/src/main/java/org/jclouds/route53/xml/ResourceRecordSetHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53.xml;\n\nimport static org.jclouds.util.SaxUtils.currentOrNull;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.route53.domain.ResourceRecordSet;\nimport org.xml.sax.Attributes;\n\n\npublic class ResourceRecordSetHandler extends ParseSax.HandlerForGeneratedRequestWithResult<ResourceRecordSet> {\n\n   private StringBuilder currentText = new StringBuilder();\n   private ResourceRecordSet.Builder builder = ResourceRecordSet.builder();\n\n   @Override\n   public ResourceRecordSet getResult() {\n      try {\n         return builder.build();\n      } finally {\n         builder = ResourceRecordSet.builder();\n      }\n   }\n\n   @Override\n   public void startElement(String url, String name, String qName, Attributes attributes) {\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) {\n      if (qName.equals(\"Name\")) {\n         builder.name(currentOrNull(currentText));\n      } else if (qName.equals(\"Type\")) {\n         builder.type(currentOrNull(currentText));\n      } else if (qName.equals(\"TTL\")) {\n         builder.ttl(Integer.parseInt(currentOrNull(currentText)));\n      } else if (qName.equals(\"Value\")) {\n         builder.add(currentOrNull(currentText));\n      } else if (qName.equals(\"HostedZoneId\")) {\n         builder.zoneId(currentOrNull(currentText));\n      } else if (qName.equals(\"SetIdentifier\")) {\n         builder.id(currentOrNull(currentText));\n      } else if (qName.equals(\"DNSName\")) {\n         builder.dnsName(currentOrNull(currentText));\n      } else if (qName.equals(\"Weight\")) {\n         builder.weight(Integer.parseInt(currentOrNull(currentText)));\n      } else if (qName.equals(\"Region\")) {\n         builder.region(currentOrNull(currentText));\n      }\n      currentText.setLength(0);\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "apis/route53/src/test/java/org/jclouds/route53/Route53ApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53;\n\nimport static com.google.common.net.HttpHeaders.DATE;\nimport static com.google.common.net.HttpHeaders.HOST;\nimport static jakarta.ws.rs.HttpMethod.GET;\nimport static jakarta.ws.rs.core.Response.Status.OK;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.route53.internal.BaseRoute53ApiExpectTest;\nimport org.jclouds.route53.parse.GetChangeResponseTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"Route53ApiExpectTest\")\npublic class Route53ApiExpectTest extends BaseRoute53ApiExpectTest {\n\n   HttpRequest getChange = HttpRequest.builder().method(GET)\n         .endpoint(\"https://route53.amazonaws.com/2012-02-29/change/C2682N5HXP0BZ4\")\n         .addHeader(HOST, \"route53.amazonaws.com\")\n         .addHeader(DATE, \"Mon, 21 Jan 02013 19:29:03 -0800\")\n         .addHeader(\"X-Amzn-Authorization\", authForDate)\n         .build();\n\n   HttpResponse getChangeResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/change.xml\", \"text/xml\")).build();\n\n   public void testGetChangeWhenResponseIs2xx() {\n      Route53Api api = requestSendsResponse(getChange, getChangeResponse);\n      assertEquals(api.getChange(\"C2682N5HXP0BZ4\").toString(), new GetChangeResponseTest().expected().toString());\n   }\n\n   public void testGetChangeNullWhenResponseIs404() {\n      Route53Api api = requestSendsResponse(getChange, notFound);\n      assertNull(api.getChange(\"C2682N5HXP0BZ4\"));\n   }\n}\n"
  },
  {
    "path": "apis/route53/src/test/java/org/jclouds/route53/Route53ApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53;\n\nimport static org.testng.Assert.assertNull;\n\nimport org.jclouds.route53.internal.BaseRoute53ApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"Route53ApiLiveTest\")\npublic class Route53ApiLiveTest extends BaseRoute53ApiLiveTest {\n\n   @Test\n   protected void testGetChangeReturnsNullOnNotFound() {\n      assertNull(api.getChange(\"FOOOBAR\"));\n   }\n}\n"
  },
  {
    "path": "apis/route53/src/test/java/org/jclouds/route53/Route53ApiMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53;\n\nimport org.jclouds.View;\nimport org.jclouds.rest.internal.BaseHttpApiMetadataTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.reflect.TypeToken;\n\n@Test(groups = \"unit\", testName = \"Route53ApiMetadataTest\")\npublic class Route53ApiMetadataTest extends BaseHttpApiMetadataTest {\n\n   // no dns abstraction, yet\n   public Route53ApiMetadataTest() {\n      super(new Route53ApiMetadata(), ImmutableSet.<TypeToken<? extends View>> of());\n   }\n}\n"
  },
  {
    "path": "apis/route53/src/test/java/org/jclouds/route53/features/HostedZoneApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53.features;\nimport static com.google.common.net.HttpHeaders.DATE;\nimport static com.google.common.net.HttpHeaders.HOST;\nimport static jakarta.ws.rs.HttpMethod.GET;\nimport static jakarta.ws.rs.HttpMethod.POST;\nimport static jakarta.ws.rs.core.Response.Status.OK;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.jclouds.route53.Route53Api;\nimport org.jclouds.route53.internal.BaseRoute53ApiExpectTest;\nimport org.jclouds.route53.parse.CreateHostedZoneResponseTest;\nimport org.jclouds.route53.parse.GetChangeResponseTest;\nimport org.jclouds.route53.parse.GetHostedZoneResponseTest;\nimport org.jclouds.route53.parse.ListHostedZonesResponseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\", testName = \"HostedZoneApiExpectTest\")\npublic class HostedZoneApiExpectTest extends BaseRoute53ApiExpectTest {\n   HttpRequest createWithReference = HttpRequest.builder().method(POST)\n         .endpoint(\"https://route53.amazonaws.com/2012-02-29/hostedzone\")\n         .addHeader(HOST, \"route53.amazonaws.com\")\n         .addHeader(DATE, \"Mon, 21 Jan 02013 19:29:03 -0800\")\n         .addHeader(\"X-Amzn-Authorization\", authForDate)\n         .payload(\n               payloadFromStringWithContentType(\n                     \"<CreateHostedZoneRequest xmlns=\\\"https://route53.amazonaws.com/doc/2012-02-29/\\\"><Name>jclouds.org.</Name><CallerReference>expect</CallerReference></CreateHostedZoneRequest>\",\n                     \"application/xml\")).build();\n   \n   HttpResponse createResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/new_zone.xml\", \"text/xml\")).build();\n\n   public void testCreateWithReferenceWhenResponseIs2xx() {\n      Route53Api success = requestSendsResponse(createWithReference, createResponse);\n      assertEquals(success.getHostedZoneApi().createWithReference(\"jclouds.org.\", \"expect\").toString(),\n            new CreateHostedZoneResponseTest().expected().toString());\n   }\n\n   HttpRequest createWithReferenceAndComment = HttpRequest.builder().method(POST)\n         .endpoint(\"https://route53.amazonaws.com/2012-02-29/hostedzone\")\n         .addHeader(HOST, \"route53.amazonaws.com\")\n         .addHeader(DATE, \"Mon, 21 Jan 02013 19:29:03 -0800\")\n         .addHeader(\"X-Amzn-Authorization\", authForDate)\n         .payload(\n               payloadFromStringWithContentType(\n                     \"<CreateHostedZoneRequest xmlns=\\\"https://route53.amazonaws.com/doc/2012-02-29/\\\"><Name>jclouds.org.</Name><CallerReference>expect</CallerReference><HostedZoneConfig><Comment>comment</Comment></HostedZoneConfig></CreateHostedZoneRequest>\",\n                     \"application/xml\")).build();\n\n   public void testCreateWithReferenceAndCommentWhenResponseIs2xx() {\n      Route53Api success = requestSendsResponse(createWithReferenceAndComment, createResponse);\n      assertEquals(success.getHostedZoneApi().createWithReferenceAndComment(\"jclouds.org.\", \"expect\", \"comment\").toString(),\n            new CreateHostedZoneResponseTest().expected().toString());\n   }\n\n   HttpRequest get = HttpRequest.builder().method(GET)\n         .endpoint(\"https://route53.amazonaws.com/2012-02-29/hostedzone/Z1XTHCPEFRWV1X\")\n         .addHeader(HOST, \"route53.amazonaws.com\")\n         .addHeader(DATE, \"Mon, 21 Jan 02013 19:29:03 -0800\")\n         .addHeader(\"X-Amzn-Authorization\", authForDate)\n         .build();\n   \n   HttpResponse getResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/hosted_zone.xml\", \"text/xml\")).build();\n\n   public void testGetWhenResponseIs2xx() {\n      Route53Api success = requestSendsResponse(get, getResponse);\n      assertEquals(success.getHostedZoneApi().get(\"Z1XTHCPEFRWV1X\").toString(), new GetHostedZoneResponseTest().expected()\n            .toString());\n   }\n\n   public void testGetWhenResponseIs404() {\n      Route53Api fail = requestSendsResponse(get, notFound);\n      assertNull(fail.getHostedZoneApi().get(\"Z1XTHCPEFRWV1X\"));\n   }\n\n   HttpRequest list = HttpRequest.builder().method(GET)\n         .endpoint(\"https://route53.amazonaws.com/2012-02-29/hostedzone\")\n         .addHeader(HOST, \"route53.amazonaws.com\")\n         .addHeader(DATE, \"Mon, 21 Jan 02013 19:29:03 -0800\")\n         .addHeader(\"X-Amzn-Authorization\", authForDate)\n         .build();\n\n   HttpResponse listResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/hosted_zones.xml\", \"text/xml\")).build();\n   \n   public void testListWhenResponseIs2xx() {\n      Route53Api success = requestSendsResponse(list, listResponse);\n      assertEquals(success.getHostedZoneApi().list().get(0).toString(), new ListHostedZonesResponseTest().expected()\n            .toString());\n   }\n\n   // TODO: this should really be an empty set\n   @Test(expectedExceptions = ResourceNotFoundException.class)\n   public void testListWhenResponseIs404() {\n      Route53Api fail = requestSendsResponse(list, notFound);\n      assertEquals(fail.getHostedZoneApi().list().get(0).toSet(), ImmutableSet.of());\n   }\n   \n   HttpRequest listAt = HttpRequest.builder().method(GET)\n         .endpoint(\"https://route53.amazonaws.com/2012-02-29/hostedzone?marker=Z333333YYYYYYY\")\n         .addHeader(HOST, \"route53.amazonaws.com\")\n         .addHeader(DATE, \"Mon, 21 Jan 02013 19:29:03 -0800\")\n         .addHeader(\"X-Amzn-Authorization\", authForDate)\n         .build();\n   \n   public void testListAtWhenResponseIs2xx() {\n      Route53Api apiWhenAtExist = requestSendsResponse(listAt, listResponse);\n      assertEquals(apiWhenAtExist.getHostedZoneApi().listAt(\"Z333333YYYYYYY\").toString(),\n            new ListHostedZonesResponseTest().expected().toString());\n   }\n   \n   public void testList2PagesWhenResponseIs2xx() {\n      HttpResponse noMore = HttpResponse.builder().statusCode(OK.getStatusCode())\n            .payload(payloadFromStringWithContentType(\"<ListHostedZonesResponse />\", \"text/xml\")).build();\n\n      Route53Api success = requestsSendResponses(list, listResponse, listAt, noMore);\n      assertEquals(success.getHostedZoneApi().list().concat().toString(), new ListHostedZonesResponseTest().expected()\n            .toString());\n   }\n\n   HttpRequest delete = HttpRequest.builder().method(\"DELETE\")\n         .endpoint(\"https://route53.amazonaws.com/2012-02-29/hostedzone/Z1XTHCPEFRWV1X\")\n         .addHeader(HOST, \"route53.amazonaws.com\")\n         .addHeader(DATE, \"Mon, 21 Jan 02013 19:29:03 -0800\")\n         .addHeader(\"X-Amzn-Authorization\", authForDate)\n         .build();\n   \n   HttpResponse deleteResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/change.xml\", \"text/xml\")).build();\n\n   public void testDeleteWhenResponseIs2xx() {\n      Route53Api success = requestSendsResponse(delete, deleteResponse);\n      assertEquals(success.getHostedZoneApi().delete(\"Z1XTHCPEFRWV1X\").toString(), new GetChangeResponseTest().expected().toString());\n   }\n\n   public void testDeleteWhenResponseIs404() {\n      Route53Api fail = requestSendsResponse(delete, notFound);\n      assertNull(fail.getHostedZoneApi().delete(\"Z1XTHCPEFRWV1X\"));\n   }\n}\n"
  },
  {
    "path": "apis/route53/src/test/java/org/jclouds/route53/features/HostedZoneApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53.features;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static java.lang.String.format;\nimport static java.util.logging.Logger.getAnonymousLogger;\nimport static org.jclouds.route53.domain.Change.Status.PENDING;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Date;\n\nimport org.jclouds.JcloudsVersion;\nimport org.jclouds.route53.domain.Change;\nimport org.jclouds.route53.domain.NewHostedZone;\nimport org.jclouds.route53.domain.HostedZone;\nimport org.jclouds.route53.internal.BaseRoute53ApiLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"live\", testName = \"HostedZoneApiLiveTest\")\npublic class HostedZoneApiLiveTest extends BaseRoute53ApiLiveTest {\n\n   private void checkHostedZone(HostedZone zone) {\n      getAnonymousLogger().info(format(\"zone %s rrs: %s\", zone.getName(), zone.getResourceRecordSetCount()));\n\n      checkNotNull(zone.getId(), \"Id: HostedZone %s\", zone);\n      checkNotNull(zone.getName(), \"Name: HostedZone %s\", zone);\n      checkNotNull(zone.getCallerReference(), \"CallerReference: HostedZone %s\", zone);\n      checkNotNull(zone.getComment(), \"While Comment can be null for a HostedZone, its Optional wrapper cannot %s\", zone);\n   }\n\n   @Test\n   protected void testListHostedZones() {\n      ImmutableList<HostedZone> zones = api().list().concat().toList();\n      getAnonymousLogger().info(\"zones: \" + zones.size());\n\n      for (HostedZone zone : zones) {\n         checkHostedZone(zone);\n         assertEquals(api().get(zone.getId()).getZone(), zone);\n      }\n   }\n\n   @Test\n   public void testGetHostedZoneWhenNotFound() {\n      assertNull(api().get(\"AAAAAAAAAAAAAAAA\"));\n   }\n\n   @Test\n   public void testDeleteHostedZoneWhenNotFound() {\n      assertNull(api().delete(\"AAAAAAAAAAAAAAAA\"));\n   }\n\n   @Test\n   public void testCreateAndDeleteHostedZone() {\n      String name = System.getProperty(\"user.name\").replace('.', '-') + \".zone.route53test.jclouds.org.\";\n      String nonce = name + \" @ \" + new Date();\n      String comment = name + \" for \" + JcloudsVersion.get();\n      NewHostedZone newHostedZone = api().createWithReferenceAndComment(name, nonce, comment);\n      getAnonymousLogger().info(\"created zone: \" + newHostedZone);\n      try {\n         checkHostedZone(newHostedZone.getZone());\n         assertEquals(newHostedZone.getChange().getStatus(), PENDING, \"invalid status on zone \" + newHostedZone);\n         assertTrue(!newHostedZone.getNameServers().isEmpty(), \"no name servers for zone \" + newHostedZone);\n         assertEquals(newHostedZone.getZone().getName(), name);\n         assertEquals(newHostedZone.getZone().getCallerReference(), nonce);\n         assertEquals(newHostedZone.getZone().getComment().get(), comment);\n\n         assertTrue(inSync.apply(newHostedZone.getChange()), \"zone didn't sync \" + newHostedZone);\n      } finally {\n         Change delete = api().delete(newHostedZone.getZone().getId());\n         assertTrue(inSync.apply(delete), \"delete didn't sync \" + delete);\n      }\n   }\n\n   protected HostedZoneApi api() {\n      return api.getHostedZoneApi();\n   }\n}\n"
  },
  {
    "path": "apis/route53/src/test/java/org/jclouds/route53/features/ResourceRecordSetApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53.features;\nimport static com.google.common.net.HttpHeaders.DATE;\nimport static com.google.common.net.HttpHeaders.HOST;\nimport static jakarta.ws.rs.HttpMethod.GET;\nimport static jakarta.ws.rs.HttpMethod.POST;\nimport static jakarta.ws.rs.core.Response.Status.BAD_REQUEST;\nimport static jakarta.ws.rs.core.Response.Status.OK;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.jclouds.route53.InvalidChangeBatchException;\nimport org.jclouds.route53.Route53Api;\nimport org.jclouds.route53.domain.ChangeBatch;\nimport org.jclouds.route53.domain.ResourceRecordSet;\nimport org.jclouds.route53.domain.ResourceRecordSetIterable.NextRecord;\nimport org.jclouds.route53.internal.BaseRoute53ApiExpectTest;\nimport org.jclouds.route53.parse.GetChangeResponseTest;\nimport org.jclouds.route53.parse.ListResourceRecordSetsResponseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\", testName = \"ResourceResourceRecordSetApiExpectTest\")\npublic class ResourceRecordSetApiExpectTest extends BaseRoute53ApiExpectTest {\n\n   HttpRequest create = HttpRequest.builder().method(POST)\n         .endpoint(\"https://route53.amazonaws.com/2012-02-29/hostedzone/Z1PA6795UKMFR9/rrset\")\n         .addHeader(HOST, \"route53.amazonaws.com\")\n         .addHeader(DATE, \"Mon, 21 Jan 02013 19:29:03 -0800\")\n         .addHeader(\"X-Amzn-Authorization\", authForDate)\n         .payload(payloadFromResourceWithContentType(\"/create_rrs_request.xml\", \"application/xml\")).build();\n   \n   HttpResponse jobResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/change.xml\", \"text/xml\")).build();\n\n   public void testCreateWhenResponseIs2xx() {\n      Route53Api success = requestSendsResponse(create, jobResponse);\n      assertEquals(success.getResourceRecordSetApiForHostedZone(\"Z1PA6795UKMFR9\").create(ResourceRecordSet.builder().name(\"jclouds.org.\").type(\"TXT\").add(\"my texts\").build()).toString(),\n            new GetChangeResponseTest().expected().toString());\n   }\n\n   HttpRequest apply = HttpRequest.builder().method(POST)\n         .endpoint(\"https://route53.amazonaws.com/2012-02-29/hostedzone/Z1PA6795UKMFR9/rrset\")\n         .addHeader(HOST, \"route53.amazonaws.com\")\n         .addHeader(DATE, \"Mon, 21 Jan 02013 19:29:03 -0800\")\n         .addHeader(\"X-Amzn-Authorization\", authForDate)\n         .payload(payloadFromResourceWithContentType(\"/batch_rrs_request.xml\", \"application/xml\")).build();\n\n   public void testApplyWhenResponseIs2xx() {\n      Route53Api success = requestSendsResponse(apply, jobResponse);\n      assertEquals(success.getResourceRecordSetApiForHostedZone(\"Z1PA6795UKMFR9\").apply(\n            ChangeBatch.builder()\n                       .delete(ResourceRecordSet.builder().name(\"jclouds.org.\").type(\"TXT\").add(\"my texts\").build())\n                       .create(ResourceRecordSet.builder().name(\"jclouds.org.\").type(\"TXT\").add(\"my better texts\").build())\n                       .build()).toString(),\n            new GetChangeResponseTest().expected().toString());\n   }\n\n   @Test(expectedExceptions = InvalidChangeBatchException.class, expectedExceptionsMessageRegExp = \"\\\\[Tried to create resource record set duplicate.example.com. type A, but it already exists, Tried to delete resource record set noexist.example.com. type A, but it was not found\\\\]\")\n   public void testApplyWhenResponseIs4xx() {\n      HttpResponse batchErrorFound = HttpResponse.builder().statusCode(BAD_REQUEST.getStatusCode())\n            .payload(payloadFromResourceWithContentType(\"/invalid_change_batch.xml\", \"application/xml\")).build();\n\n      Route53Api fails = requestSendsResponse(apply, batchErrorFound);\n      fails.getResourceRecordSetApiForHostedZone(\"Z1PA6795UKMFR9\").apply(\n            ChangeBatch.builder()\n                       .delete(ResourceRecordSet.builder().name(\"jclouds.org.\").type(\"TXT\").add(\"my texts\").build())\n                       .create(ResourceRecordSet.builder().name(\"jclouds.org.\").type(\"TXT\").add(\"my better texts\").build())\n                       .build());\n   }\n\n   HttpRequest list = HttpRequest.builder().method(GET)\n         .endpoint(\"https://route53.amazonaws.com/2012-02-29/hostedzone/Z1PA6795UKMFR9/rrset\")\n         .addHeader(HOST, \"route53.amazonaws.com\")\n         .addHeader(DATE, \"Mon, 21 Jan 02013 19:29:03 -0800\")\n         .addHeader(\"X-Amzn-Authorization\", authForDate).build();\n\n   HttpResponse listResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/rrsets.xml\", \"text/xml\")).build();\n   \n   public void testListWhenResponseIs2xx() {\n      Route53Api success = requestSendsResponse(list, listResponse);\n      assertEquals(success.getResourceRecordSetApiForHostedZone(\"Z1PA6795UKMFR9\").list().get(0).toString(),\n            new ListResourceRecordSetsResponseTest().expected().toString());\n   }\n\n   // TODO: this should really be an empty set\n   @Test(expectedExceptions = ResourceNotFoundException.class)\n   public void testListWhenResponseIs404() {\n      Route53Api fail = requestSendsResponse(list, notFound);\n      assertEquals(fail.getResourceRecordSetApiForHostedZone(\"Z1PA6795UKMFR9\").list().get(0).toSet(), ImmutableSet.of());\n   }\n\n   HttpRequest listAt = HttpRequest.builder().method(GET)\n         .endpoint(\"https://route53.amazonaws.com/2012-02-29/hostedzone/Z1PA6795UKMFR9/rrset?name=testdoc2.example.com\")\n         .addHeader(HOST, \"route53.amazonaws.com\")\n         .addHeader(DATE, \"Mon, 21 Jan 02013 19:29:03 -0800\")\n         .addHeader(\"X-Amzn-Authorization\", authForDate).build();\n\n   public void testListAtWhenResponseIs2xx() {\n      Route53Api apiWhenAtExist = requestSendsResponse(listAt, listResponse);\n      NextRecord next = NextRecord.name(\"testdoc2.example.com\");\n      assertEquals(apiWhenAtExist.getResourceRecordSetApiForHostedZone(\"Z1PA6795UKMFR9\").listAt(next).toString(),\n            new ListResourceRecordSetsResponseTest().expected().toString());\n   }\n\n   HttpRequest listAtNameAndType = HttpRequest.builder().method(GET)\n         .endpoint(\"https://route53.amazonaws.com/2012-02-29/hostedzone/Z1PA6795UKMFR9/rrset?name=testdoc2.example.com&type=NS\")\n         .addHeader(HOST, \"route53.amazonaws.com\")\n         .addHeader(DATE, \"Mon, 21 Jan 02013 19:29:03 -0800\")\n         .addHeader(\"X-Amzn-Authorization\", authForDate).build();\n   \n   public void testListAtNameAndTypeWhenResponseIs2xx() {\n      Route53Api apiWhenAtExist = requestSendsResponse(listAtNameAndType, listResponse);\n      NextRecord next = NextRecord.nameAndType(\"testdoc2.example.com\", \"NS\");\n      assertEquals(apiWhenAtExist.getResourceRecordSetApiForHostedZone(\"Z1PA6795UKMFR9\").listAt(next).toString(),\n            new ListResourceRecordSetsResponseTest().expected().toString());\n   }\n   \n   public void testList2PagesWhenResponseIs2xx() {\n      HttpResponse noMore = HttpResponse.builder().statusCode(OK.getStatusCode())\n            .payload(payloadFromStringWithContentType(\"<ListResourceRecordSetsResponse />\", \"text/xml\")).build();\n\n      Route53Api success = requestsSendResponses(list, listResponse, listAtNameAndType, noMore);\n      assertEquals(success.getResourceRecordSetApiForHostedZone(\"Z1PA6795UKMFR9\").list().concat().toSet(),\n            new ListResourceRecordSetsResponseTest().expected().toSet());\n   }\n\n   HttpRequest delete = HttpRequest.builder().method(POST)\n         .endpoint(\"https://route53.amazonaws.com/2012-02-29/hostedzone/Z1PA6795UKMFR9/rrset\")\n         .addHeader(HOST, \"route53.amazonaws.com\")\n         .addHeader(DATE, \"Mon, 21 Jan 02013 19:29:03 -0800\")\n         .addHeader(\"X-Amzn-Authorization\", authForDate)\n         .payload(payloadFromResourceWithContentType(\"/delete_rrs_request.xml\", \"application/xml\")).build();\n\n   public void testDeleteWhenResponseIs2xx() {\n      Route53Api success = requestSendsResponse(delete, jobResponse);\n      assertEquals(success.getResourceRecordSetApiForHostedZone(\"Z1PA6795UKMFR9\").create(ResourceRecordSet.builder()\n                                                                                                          .name(\"jclouds.org.\")\n                                                                                                          .type(\"TXT\")\n                                                                                                          .ttl(0)\n                                                                                                          .add(\"my texts\").build()).toString(),\n            new GetChangeResponseTest().expected().toString());\n   }\n}\n"
  },
  {
    "path": "apis/route53/src/test/java/org/jclouds/route53/features/ResourceRecordSetApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53.features;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Predicates.not;\nimport static com.google.common.base.Predicates.or;\nimport static java.util.logging.Logger.getAnonymousLogger;\nimport static org.jclouds.route53.domain.ChangeBatch.createAll;\nimport static org.jclouds.route53.domain.ChangeBatch.deleteAll;\nimport static org.jclouds.route53.predicates.HostedZonePredicates.nameEquals;\nimport static org.jclouds.route53.predicates.ResourceRecordSetPredicates.typeEquals;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Map.Entry;\nimport java.util.Set;\nimport java.util.concurrent.atomic.AtomicLong;\n\nimport org.jclouds.JcloudsVersion;\nimport org.jclouds.collect.PagedIterable;\nimport org.jclouds.route53.domain.Change;\nimport org.jclouds.route53.domain.HostedZone;\nimport org.jclouds.route53.domain.NewHostedZone;\nimport org.jclouds.route53.domain.ResourceRecordSet;\nimport org.jclouds.route53.domain.ResourceRecordSet.RecordSubset;\nimport org.jclouds.route53.domain.ResourceRecordSet.RecordSubset.Latency;\nimport org.jclouds.route53.domain.ResourceRecordSet.RecordSubset.Weighted;\nimport org.jclouds.route53.internal.BaseRoute53ApiLiveTest;\nimport org.testng.SkipException;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"live\", testName = \"ResourceResourceRecordSetApiLiveTest\")\npublic class ResourceRecordSetApiLiveTest extends BaseRoute53ApiLiveTest {\n\n   private void checkRRS(ResourceRecordSet rrs) {\n      checkNotNull(rrs.getName(), \"Name: ResourceRecordSet %s\", rrs);\n      checkNotNull(rrs.getType(), \"Type: ResourceRecordSet %s\", rrs);\n      checkNotNull(rrs.getTTL(), \"TTL: ResourceRecordSet %s\", rrs);\n      checkNotNull(rrs.getAliasTarget(), \"AliasTarget: ResourceRecordSet %s\", rrs);\n      if (rrs.getAliasTarget().isPresent()) {\n         assertTrue(rrs.getValues().isEmpty(), \"Values present on aliasTarget ResourceRecordSet: \" + rrs);\n      } else {\n         assertTrue(!rrs.getValues().isEmpty(), \"Values absent on ResourceRecordSet: \" + rrs);\n      }\n      if (rrs instanceof RecordSubset) {\n         checkNotNull(RecordSubset.class.cast(rrs).getId(), \"Id: ResourceRecordSubset %s\", rrs);\n      }\n      if (rrs instanceof Latency) {\n         checkNotNull(Latency.class.cast(rrs).getRegion(), \"Region: ResourceRecordSubset %s\", rrs);\n      }\n   }\n\n   AtomicLong zones = new AtomicLong();\n\n   @Test\n   private void testListRRSs() {\n      for (HostedZone zone : zones().concat()) {\n         zones.incrementAndGet();\n         checkAllRRs(zone.getId());\n      }\n   }\n\n   private void checkAllRRs(String zoneId) {\n      HostedZone zone = api.getHostedZoneApi().get(zoneId).getZone();\n      List<ResourceRecordSet> records = api(zone.getId()).list().concat().toList();\n      assertEquals(zone.getResourceRecordSetCount(), records.size());\n\n      for (ResourceRecordSet rrs : records) {\n         recordTypeCounts.getUnchecked(rrs.getType()).addAndGet(\n               rrs.getAliasTarget().isPresent() ? 1 : rrs.getValues().size());\n         checkRRS(rrs);\n      }\n   }\n\n   LoadingCache<String, AtomicLong> recordTypeCounts = CacheBuilder.newBuilder().build(\n         new CacheLoader<String, AtomicLong>() {\n            public AtomicLong load(String key) throws Exception {\n               return new AtomicLong();\n            }\n         });\n\n   @AfterClass\n   void logSummary() {\n      getAnonymousLogger().info(\"zoneCount: \" + zones);\n      for (Entry<String, AtomicLong> entry : recordTypeCounts.asMap().entrySet())\n         getAnonymousLogger().info(String.format(\"type: %s, count: %s\", entry.getKey(), entry.getValue()));\n   }\n\n   @Test\n   public void testDeleteRRSNotFound() {\n      for (HostedZone zone : zones().concat()) {\n         assertNull(api(zone.getId()).delete(\n               ResourceRecordSet.builder().name(\"krank.foo.bar.\").type(\"TXT\").add(\"kranko\").build()));\n      }\n   }\n\n   /**\n    * cannot delete a zone without at least one of each\n    */\n   private static final Predicate<ResourceRecordSet> requiredRRTypes = or(typeEquals(\"SOA\"), typeEquals(\"NS\"));\n\n   @Test\n   public void testCreateAndDeleteBulkRecords() {\n      String name = System.getProperty(\"user.name\").replace('.', '-') + \".bulk.route53test.jclouds.org.\";\n      try {\n         String zoneId = recreateZone(name);\n\n         ImmutableList<ResourceRecordSet> records = ImmutableList.<ResourceRecordSet> builder()\n               .add(ResourceRecordSet.builder().name(\"dom1.\" + name).type(\"TXT\").add(\"\\\"somehow\\\" \\\" somewhere\\\"\")\n                     .build())\n               .add(ResourceRecordSet.builder().name(\"dom2.\" + name).type(\"TXT\").add(\"\\\"goodies\\\"\").build()).build();\n\n         createAndDeleteRecordsInZone(records, zoneId);\n      } finally {\n         clearAndDeleteHostedZonesNamed(name);\n      }\n   }\n\n   @Test\n   public void testCreateAndDeleteWeightedRecords() {\n      String name = System.getProperty(\"user.name\").replace('.', '-') + \".weight.route53test.jclouds.org.\";\n      try {\n         String zoneId = recreateZone(name);\n\n         ImmutableList<ResourceRecordSet> records = ImmutableList.<ResourceRecordSet> builder()\n               .add(Weighted.builder().id(\"dom1\").weight(1).name(\"dom.\" + name).type(\"CNAME\").add(\"dom1.\" + name)\n                     .build())\n               .add(Weighted.builder().id(\"dom2\").weight(1).name(\"dom.\" + name).type(\"CNAME\").add(\"dom2.\" + name)\n                     .build()).build();\n\n         createAndDeleteRecordsInZone(records, zoneId);\n      } finally {\n         clearAndDeleteHostedZonesNamed(name);\n      }\n   }\n\n   private String recreateZone(String name) {\n      clearAndDeleteHostedZonesNamed(name);\n      String nonce = name + \" @ \" + new Date();\n      String comment = name + \" for \" + JcloudsVersion.get();\n      NewHostedZone newHostedZone = api.getHostedZoneApi()\n            .createWithReferenceAndComment(name, nonce, comment);\n      getAnonymousLogger().info(\"created zone: \" + newHostedZone);\n      assertTrue(inSync.apply(newHostedZone.getChange()), \"zone didn't sync \" + newHostedZone);\n      return newHostedZone.getZone().getId();\n   }\n\n   private void createAndDeleteRecordsInZone(ImmutableList<ResourceRecordSet> records, String zoneId) {\n      sync(api(zoneId).apply(createAll(records)));\n\n      checkAllRRs(zoneId);\n\n      sync(api(zoneId).apply(deleteAll(records)));\n\n      PagedIterable<ResourceRecordSet> refreshed = refresh(zoneId);\n      assertTrue(refreshed.concat().filter(not(requiredRRTypes)).isEmpty(), \"zone still has optional records: \"\n            + refreshed);\n   }\n\n   private void clearAndDeleteHostedZonesNamed(String name) {\n      for (HostedZone zone : api.getHostedZoneApi().list().concat().filter(nameEquals(name))) {\n         getAnonymousLogger().info(\"clearing and deleting zone: \" + zone);\n         Set<ResourceRecordSet> remaining = refresh(zone.getId()).concat().filter(not(requiredRRTypes)).toSet();\n         if (!remaining.isEmpty())\n            sync(api(zone.getId()).apply(deleteAll(remaining)));\n         sync(api.getHostedZoneApi().delete(zone.getId()));\n      }\n   }\n\n   private void sync(Change job) {\n      assertTrue(inSync.apply(job), \"job didn't sync \" + job);\n   }\n\n   private PagedIterable<ResourceRecordSet> refresh(String zoneId) {\n      return api(zoneId).list();\n   }\n\n   private PagedIterable<HostedZone> zones() {\n      PagedIterable<HostedZone> zones = api.getHostedZoneApi().list();\n      if (zones.get(0).isEmpty())\n         throw new SkipException(\"no zones in context: \" + identity);\n      return zones;\n   }\n\n   private ResourceRecordSetApi api(String zoneId) {\n      return api.getResourceRecordSetApiForHostedZone(zoneId);\n   }\n}\n"
  },
  {
    "path": "apis/route53/src/test/java/org/jclouds/route53/functions/SerializeRRSTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.route53.domain.ResourceRecordSet;\nimport org.jclouds.route53.domain.ResourceRecordSet.RecordSubset.Weighted;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class SerializeRRSTest {\n\n   @Test\n   void roundRobinRRSetToXML() {\n      assertEquals(\n            new SerializeRRS().apply(ResourceRecordSet.builder()\n                                                      .name(\"dom1.foo.com.\")\n                                                      .type(\"A\")\n                                                      .add(\"1.2.3.4\")\n                                                      .add(\"5.6.7.8\").build()),\n            \"<ResourceRecordSet><Name>dom1.foo.com.</Name><Type>A</Type><TTL>300</TTL><ResourceRecords><ResourceRecord><Value>1.2.3.4</Value></ResourceRecord><ResourceRecord><Value>5.6.7.8</Value></ResourceRecord></ResourceRecords></ResourceRecordSet>\");\n   }\n\n   @Test\n   void roundWeightedRRSetToXML() {\n      assertEquals(new SerializeRRS().apply(Weighted.builder()\n                                                    .id(\"dom1\")\n                                                    .weight(1)\n                                                    .name(\"dom.foo.com.\")\n                                                    .type(\"CNAME\")\n                                                    .add(\"dom1.foo.com.\").build()),\n            \"<ResourceRecordSet><Name>dom.foo.com.</Name><Type>CNAME</Type><SetIdentifier>dom1</SetIdentifier><Weight>1</Weight><TTL>300</TTL><ResourceRecords><ResourceRecord><Value>dom1.foo.com.</Value></ResourceRecord></ResourceRecords></ResourceRecordSet>\");\n   }\n}\n"
  },
  {
    "path": "apis/route53/src/test/java/org/jclouds/route53/handlers/Route53ErrorHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53.handlers;\nimport static com.google.common.base.Throwables.propagate;\nimport static com.google.common.net.HttpHeaders.DATE;\nimport static com.google.common.net.HttpHeaders.HOST;\nimport static jakarta.ws.rs.HttpMethod.POST;\nimport static jakarta.ws.rs.core.Response.Status.BAD_REQUEST;\nimport static org.jclouds.rest.internal.BaseRestApiExpectTest.payloadFromStringWithContentType;\nimport static org.jclouds.util.Strings2.toStringAndClose;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\n\nimport org.jclouds.aws.AWSResponseException;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.config.SaxParserModule;\nimport org.jclouds.io.Payload;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.jclouds.route53.InvalidChangeBatchException;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\n@Test(groups = \"unit\", singleThreaded = true, testName = \"Route53ErrorHandlerTest\" )\npublic class Route53ErrorHandlerTest {\n   Route53ErrorHandler function = Guice.createInjector(new SaxParserModule()).getInstance(Route53ErrorHandler.class);\n\n   HttpRequest request = HttpRequest.builder().method(POST)\n         .endpoint(\"https://route53.amazonaws.com/2012-02-29/hostedzone/Z1PA6795UKMFR9/rrset\")\n         .addHeader(HOST, \"route53.amazonaws.com\")\n         .addHeader(DATE, \"Mon, 21 Jan 02013 19:29:03 -0800\")\n         .addHeader(\"X-Amzn-Authorization\", \"AWS3-HTTPS AWSAccessKeyId=identity,Algorithm=HmacSHA256,Signature=pylxNiLcrsjNRZOsxyT161JCwytVPHyc2rFfmNCuZKI=\")\n         .payload(payloadFromResource(\"/batch_rrs_request.xml\")).build();\n   HttpCommand command = new HttpCommand(request);\n\n   @Test\n   public void testInvalidChangeBatchException() throws IOException {\n      HttpResponse response = HttpResponse.builder().statusCode(BAD_REQUEST.getStatusCode())\n                                                    .payload(payloadFromResource(\"/invalid_change_batch.xml\")).build();\n      function.handleError(command, response);\n\n      InvalidChangeBatchException exception = InvalidChangeBatchException.class.cast(command.getException());\n\n      assertEquals(exception.getMessages(), ImmutableSet.of(\n            \"Tried to create resource record set duplicate.example.com. type A, but it already exists\",\n            \"Tried to delete resource record set noexist.example.com. type A, but it was not found\"));\n   }\n\n   @Test\n   public void testDeleteNotFound() throws IOException {\n\n      HttpResponse response = HttpResponse.builder().statusCode(BAD_REQUEST.getStatusCode())\n            .payload(\n                  payloadFromStringWithContentType(\n                        \"<ErrorResponse><Error><Type>Sender</Type><Code>InvalidChangeBatch</Code>\"\n                              + \"<Message>Tried to delete resource record set krank.foo.bar., type TXT but it was not found</Message>\"\n                              + \"</Error></ErrorResponse>\", \"application/xml\")).build();\n\n      function.handleError(command, response);\n\n      assertEquals(command.getException().getClass(), ResourceNotFoundException.class);\n      assertEquals(command.getException().getMessage(), \"Tried to delete resource record set krank.foo.bar., type TXT but it was not found\");\n\n      AWSResponseException exception = AWSResponseException.class.cast(command.getException().getCause());\n\n      assertEquals(exception.getError().getCode(), \"InvalidChangeBatch\");\n   }\n\n   private Payload payloadFromResource(String resource) {\n      try {\n         return payloadFromStringWithContentType(toStringAndClose(getClass().getResourceAsStream(resource)),\n               \"application/xml\");\n      } catch (IOException e) {\n         throw propagate(e);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/route53/src/test/java/org/jclouds/route53/internal/BaseRoute53ApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53.internal;\n\nimport org.jclouds.route53.Route53Api;\n\npublic class BaseRoute53ApiExpectTest extends BaseRoute53ExpectTest<Route53Api> {\n}\n"
  },
  {
    "path": "apis/route53/src/test/java/org/jclouds/route53/internal/BaseRoute53ApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53.internal;\n\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static org.jclouds.route53.domain.Change.Status.INSYNC;\nimport static org.jclouds.util.Predicates2.retry;\n\nimport org.jclouds.apis.BaseApiLiveTest;\nimport org.jclouds.route53.Route53Api;\nimport org.jclouds.route53.domain.Change;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\n\n@Test(groups = \"live\")\npublic class BaseRoute53ApiLiveTest extends BaseApiLiveTest<Route53Api> {\n\n   public BaseRoute53ApiLiveTest() {\n      provider = \"route53\";\n   }\n\n   protected Predicate<Change> inSync;\n\n   @BeforeClass(groups = \"live\")\n   @Override\n   public void setup() {\n      super.setup();\n      inSync = retry(new Predicate<Change>() {\n         public boolean apply(Change input) {\n            Change change = api.getChange(input.getId());\n            return change != null && change.getStatus() == INSYNC;\n         }\n      }, 600, 1, 5, SECONDS);\n   }\n}\n"
  },
  {
    "path": "apis/route53/src/test/java/org/jclouds/route53/internal/BaseRoute53ExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53.internal;\n\nimport static jakarta.ws.rs.core.Response.Status.NOT_FOUND;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.internal.BaseRestApiExpectTest;\nimport org.jclouds.route53.config.Route53HttpApiModule;\n\nimport com.google.inject.Module;\npublic class BaseRoute53ExpectTest<T> extends BaseRestApiExpectTest<T> {\n\n   public BaseRoute53ExpectTest() {\n      provider = \"route53\";\n   }\n   \n   @ConfiguresHttpApi\n   private static final class TestRoute53HttpApiModule extends Route53HttpApiModule {\n\n      @Override\n      protected String provideTimeStamp(final DateService dateService) {\n         return \"Mon, 21 Jan 02013 19:29:03 -0800\";\n      }\n   }\n\n   protected final HttpResponse notFound = HttpResponse.builder().statusCode(NOT_FOUND.getStatusCode()).build();\n   protected final String authForDate = \"AWS3-HTTPS AWSAccessKeyId=identity,Algorithm=HmacSHA256,Signature=pylxNiLcrsjNRZOsxyT161JCwytVPHyc2rFfmNCuZKI=\";\n\n   @Override\n   protected Module createModule() {\n      return new TestRoute53HttpApiModule();\n   }\n}\n"
  },
  {
    "path": "apis/route53/src/test/java/org/jclouds/route53/parse/CreateHostedZoneResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53.parse;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.route53.domain.NewHostedZone;\nimport org.jclouds.route53.xml.CreateHostedZoneResponseHandler;\nimport org.testng.annotations.Test;\n\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"CreateHostedZoneResponseTest\")\npublic class CreateHostedZoneResponseTest extends BaseHandlerTest {\n\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/new_zone.xml\");\n\n      NewHostedZone expected = expected();\n\n      CreateHostedZoneResponseHandler handler = injector.getInstance(CreateHostedZoneResponseHandler.class);\n      NewHostedZone result = factory.create(handler).parse(is);\n\n      assertEquals(result, expected);\n   }\n\n   public NewHostedZone expected() {\n      return NewHostedZone.create(new GetHostedZoneResponseTest().expected(), new GetChangeResponseTest().expected());\n   }\n}\n"
  },
  {
    "path": "apis/route53/src/test/java/org/jclouds/route53/parse/GetChangeResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53.parse;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\nimport java.util.Date;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.route53.domain.Change;\nimport org.jclouds.route53.domain.Change.Status;\nimport org.jclouds.route53.xml.ChangeHandler;\nimport org.testng.annotations.Test;\n\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"GetChangeResponseTest\")\npublic class GetChangeResponseTest extends BaseHandlerTest {\n\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/change.xml\");\n\n      Change expected = expected();\n\n      ChangeHandler handler = injector.getInstance(ChangeHandler.class);\n      Change result = factory.create(handler).parse(is);\n\n      assertEquals(result, expected);\n      assertEquals(result.getStatus(), expected.getStatus());\n      assertEquals(result.getSubmittedAt(), expected.getSubmittedAt());\n   }\n\n   public Change expected() {\n      Date submittedAt = new SimpleDateFormatDateService().iso8601DateParse(\"2011-09-10T01:36:41.958Z\");\n      return Change.create(\"C2682N5HXP0BZ4\", Status.INSYNC, submittedAt);\n   }\n\n}\n"
  },
  {
    "path": "apis/route53/src/test/java/org/jclouds/route53/parse/GetHostedZoneResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53.parse;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.route53.domain.HostedZone;\nimport org.jclouds.route53.domain.HostedZoneAndNameServers;\nimport org.jclouds.route53.xml.GetHostedZoneResponseHandler;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"GetHostedZoneResponseTest\")\npublic class GetHostedZoneResponseTest extends BaseHandlerTest {\n\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/hosted_zone.xml\");\n\n      HostedZoneAndNameServers expected = expected();\n\n      GetHostedZoneResponseHandler handler = injector.getInstance(GetHostedZoneResponseHandler.class);\n      HostedZoneAndNameServers result = factory.create(handler).parse(is);\n\n      assertEquals(result, expected);\n   }\n\n   public HostedZoneAndNameServers expected() {\n      return HostedZoneAndNameServers.create(HostedZone.builder()\n                                           .id(\"Z21DW1QVGID6NG\")\n                                           .name(\"example.com.\")\n                                           .callerReference(\"a_unique_reference\")\n                                           .comment(\"Migrate an existing domain to Route 53\").build(),\n                                       ImmutableList.<String> builder()\n                                                    .add(\"ns-1638.awsdns-12.co.uk\")\n                                                    .add(\"ns-144.awsdns-18.com\")\n                                                    .add(\"ns-781.awsdns-33.net\")\n                                                    .add(\"ns-1478.awsdns-56.org\").build());\n   }\n}\n"
  },
  {
    "path": "apis/route53/src/test/java/org/jclouds/route53/parse/InvalidChangeBatchResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53.parse;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.route53.xml.InvalidChangeBatchHandler;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"InvalidChangeBatchResponseTest\")\npublic class InvalidChangeBatchResponseTest extends BaseHandlerTest {\n\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/invalid_change_batch.xml\");\n\n      InvalidChangeBatchHandler handler = injector.getInstance(InvalidChangeBatchHandler.class);\n      ImmutableList<String> result = factory.create(handler).parse(is);\n\n      assertEquals(result, ImmutableList.of(\n            \"Tried to create resource record set duplicate.example.com. type A, but it already exists\",\n            \"Tried to delete resource record set noexist.example.com. type A, but it was not found\"));\n   }\n}\n"
  },
  {
    "path": "apis/route53/src/test/java/org/jclouds/route53/parse/ListHostedZonesResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53.parse;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.IterableWithMarkers;\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.route53.domain.HostedZone;\nimport org.jclouds.route53.xml.ListHostedZonesResponseHandler;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"ListHostedZonesResponseTest\")\npublic class ListHostedZonesResponseTest extends BaseHandlerTest {\n\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/hosted_zones.xml\");\n\n      IterableWithMarker<HostedZone> expected = expected();\n\n      ListHostedZonesResponseHandler handler = injector.getInstance(ListHostedZonesResponseHandler.class);\n      IterableWithMarker<HostedZone> result = factory.create(handler).parse(is);\n\n      assertEquals(result.toString(), expected.toString());\n\n   }\n\n   public IterableWithMarker<HostedZone> expected() {\n      return IterableWithMarkers.from(\n            ImmutableSet.of(\n                  HostedZone.builder()\n                      .id(\"Z21DW1QVGID6NG\")\n                      .name(\"example.com.\")\n                      .callerReference(\"a_unique_reference\")\n                      .resourceRecordSetCount(17)\n                      .comment(\"Migrate an existing domain to Route 53\").build(),\n                  HostedZone.builder()\n                      .id(\"Z2682N5HXP0BZ4\")\n                      .name(\"example2.com.\")\n                      .callerReference(\"a_unique_reference2\")\n                      .resourceRecordSetCount(117)\n                      .comment(\"This is my 2nd hosted zone.\").build()), \"Z333333YYYYYYY\");\n   }\n}\n"
  },
  {
    "path": "apis/route53/src/test/java/org/jclouds/route53/parse/ListResourceRecordSetsResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53.parse;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.route53.domain.ResourceRecordSet;\nimport org.jclouds.route53.domain.ResourceRecordSetIterable;\nimport org.jclouds.route53.xml.ListResourceRecordSetsResponseHandler;\nimport org.testng.annotations.Test;\n\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"ListResourceRecordSetsResponseTest\")\npublic class ListResourceRecordSetsResponseTest extends BaseHandlerTest {\n\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/rrsets.xml\");\n\n      ResourceRecordSetIterable expected = expected();\n\n      ListResourceRecordSetsResponseHandler handler = injector.getInstance(ListResourceRecordSetsResponseHandler.class);\n      ResourceRecordSetIterable result = factory.create(handler).parse(is);\n\n      assertEquals(result.toString(), expected.toString());\n\n   }\n\n   public ResourceRecordSetIterable expected() {\n      return ResourceRecordSetIterable.builder()\n            .add(ResourceRecordSet.builder()\n                                  .name(\"example.com.\")\n                                  .type(\"SOA\")\n                                  .ttl(900)\n                                  .add(\"ns-2048.awsdns-64.net. hostmaster.awsdns.com. 1 7200 900 1209600 86400\")\n                                  .build())\n            .add(ResourceRecordSet.builder()\n                                  .name(\"example.com.\")\n                                  .type(\"NS\")\n                                  .ttl(172800)\n                                  .add(\"ns-2048.awsdns-64.com.\")\n                                  .add(\"ns-2049.awsdns-65.net.\")\n                                  .add(\"ns-2050.awsdns-66.org.\")\n                                  .add(\"ns-2051.awsdns-67.co.uk.\")\n                                  .build())\n            .nextRecordName(\"testdoc2.example.com\")\n            .nextRecordType(\"NS\").build();\n   }\n}\n"
  },
  {
    "path": "apis/route53/src/test/java/org/jclouds/route53/predicates/HostedZonePredicatesTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53.predicates;\n\nimport static org.jclouds.route53.predicates.HostedZonePredicates.nameEquals;\n\nimport org.jclouds.route53.domain.HostedZone;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"HostedZonePredicatesTest\")\npublic class HostedZonePredicatesTest {\n   HostedZone zone = HostedZone.builder().id(\"EEEFFFEEE\").callerReference(\"goog\").name(\"jclouds.org.\").build();\n\n   @Test\n   public void testNameEqualsWhenEqual() {\n      assert nameEquals(\"jclouds.org.\").apply(zone);\n   }\n\n   @Test\n   public void testNameEqualsWhenNotEqual() {\n      assert !nameEquals(\"kclouds.org.\").apply(zone);\n   }\n}\n"
  },
  {
    "path": "apis/route53/src/test/java/org/jclouds/route53/predicates/ResourceRecordSetPredicatesTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.route53.predicates;\n\nimport static org.jclouds.route53.predicates.ResourceRecordSetPredicates.typeEquals;\n\nimport org.jclouds.route53.domain.ResourceRecordSet;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ResourceRecordSetPredicatesTest\")\npublic class ResourceRecordSetPredicatesTest {\n   ResourceRecordSet rrs = ResourceRecordSet.builder().name(\"jclouds.org.\").type(\"NS\").add(\"ns-119.awsdns-14.com.\")\n         .build();\n\n   @Test\n   public void testTypeEqualsWhenEqual() {\n      assert typeEquals(\"NS\").apply(rrs);\n   }\n\n   @Test\n   public void testTypeEqualsWhenNotEqual() {\n      assert !typeEquals(\"AAAA\").apply(rrs);\n   }\n}\n"
  },
  {
    "path": "apis/route53/src/test/resources/batch_rrs_request.xml",
    "content": "<ChangeResourceRecordSetsRequest xmlns=\"https://route53.amazonaws.com/doc/2012-02-29/\"><ChangeBatch><Changes><Change><Action>DELETE</Action><ResourceRecordSet><Name>jclouds.org.</Name><Type>TXT</Type><TTL>300</TTL><ResourceRecords><ResourceRecord><Value>my texts</Value></ResourceRecord></ResourceRecords></ResourceRecordSet></Change><Change><Action>CREATE</Action><ResourceRecordSet><Name>jclouds.org.</Name><Type>TXT</Type><TTL>300</TTL><ResourceRecords><ResourceRecord><Value>my better texts</Value></ResourceRecord></ResourceRecords></ResourceRecordSet></Change></Changes></ChangeBatch></ChangeResourceRecordSetsRequest>"
  },
  {
    "path": "apis/route53/src/test/resources/change.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<GetChangeResponse xmlns=\"https://route53.amazonaws.com/doc/2012-02-29/\">\n   <ChangeInfo>\n      <Id>/change/C2682N5HXP0BZ4</Id>\n      <Status>INSYNC</Status>\n      <SubmittedAt>2011-09-10T01:36:41.958Z</SubmittedAt>\n   </ChangeInfo>\n</GetChangeResponse>"
  },
  {
    "path": "apis/route53/src/test/resources/create_hosted_zone.xml",
    "content": "<CreateHostedZoneResponse xmlns=\"https://route53.amazonaws.com/doc/2010-10-01/\">\n\t<HostedZone>\n\t\t<Id>/hostedzone/Z21DW1QVGID6NG</Id>\n\t\t<Name>example.com.</Name>\n\t\t<CallerReference>a_unique_reference</CallerReference>\n\t\t<Config>\n\t\t\t<Comment>Migrate an existing domain to Route 53</Comment>\n\t\t</Config>\n\t</HostedZone>\n\t<ChangeInfo>\n\t\t<Id>/change/C24LD0DUV5VOVE</Id>\n\t\t<Status>PENDING</Status>\n\t\t<SubmittedAt>2010-12-02T01:34:20.633Z</SubmittedAt>\n\t</ChangeInfo>\n\t<DelegationSet>\n\t\t<NameServers>\n\t\t\t<NameServer>ns-1638.awsdns-12.co.uk</NameServer>\n\t\t\t<NameServer>ns-144.awsdns-18.com</NameServer>\n\t\t\t<NameServer>ns-781.awsdns-33.net</NameServer>\n\t\t\t<NameServer>ns-1478.awsdns-56.org</NameServer>\n\t\t</NameServers>\n\t</DelegationSet>\n</CreateHostedZoneResponse>"
  },
  {
    "path": "apis/route53/src/test/resources/create_rrs_request.xml",
    "content": "<ChangeResourceRecordSetsRequest xmlns=\"https://route53.amazonaws.com/doc/2012-02-29/\"><ChangeBatch><Changes><Change><Action>CREATE</Action><ResourceRecordSet><Name>jclouds.org.</Name><Type>TXT</Type><TTL>300</TTL><ResourceRecords><ResourceRecord><Value>my texts</Value></ResourceRecord></ResourceRecords></ResourceRecordSet></Change></Changes></ChangeBatch></ChangeResourceRecordSetsRequest>"
  },
  {
    "path": "apis/route53/src/test/resources/delete_rrs_request.xml",
    "content": "<ChangeResourceRecordSetsRequest xmlns=\"https://route53.amazonaws.com/doc/2012-02-29/\"><ChangeBatch><Changes><Change><Action>CREATE</Action><ResourceRecordSet><Name>jclouds.org.</Name><Type>TXT</Type><TTL>0</TTL><ResourceRecords><ResourceRecord><Value>my texts</Value></ResourceRecord></ResourceRecords></ResourceRecordSet></Change></Changes></ChangeBatch></ChangeResourceRecordSetsRequest>"
  },
  {
    "path": "apis/route53/src/test/resources/hosted_zone.xml",
    "content": "<GetHostedZoneResponse xmlns=\"https://route53.amazonaws.com/doc/2012-02-29/\">\n\t<HostedZone>\n\t\t<Id>/hostedzone/Z21DW1QVGID6NG</Id>\n\t\t<Name>example.com.</Name>\n\t\t<CallerReference>a_unique_reference</CallerReference>\n\t\t<Config>\n\t\t\t<Comment>Migrate an existing domain to Route 53</Comment>\n\t\t</Config>\n\t</HostedZone>\n\t<DelegationSet>\n\t\t<NameServers>\n\t\t\t<NameServer>ns-1638.awsdns-12.co.uk</NameServer>\n\t\t\t<NameServer>ns-144.awsdns-18.com</NameServer>\n\t\t\t<NameServer>ns-781.awsdns-33.net</NameServer>\n\t\t\t<NameServer>ns-1478.awsdns-56.org</NameServer>\n\t\t</NameServers>\n\t</DelegationSet>\n</GetHostedZoneResponse>"
  },
  {
    "path": "apis/route53/src/test/resources/hosted_zones.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ListHostedZonesResponse xmlns=\"https://route53.amazonaws.com/doc/2012-02-29/\">\n\t<HostedZones>\n\t\t<HostedZone>\n\t\t\t<Id>/hostedzone/Z21DW1QVGID6NG</Id>\n\t\t\t<Name>example.com.</Name>\n\t\t\t<CallerReference>a_unique_reference</CallerReference>\n\t\t\t<Config>\n\t\t\t\t<Comment>Migrate an existing domain to Route 53</Comment>\n\t\t\t</Config>\n\t\t\t<ResourceRecordSetCount>17</ResourceRecordSetCount>\n\t\t</HostedZone>\n\t\t<HostedZone>\n\t\t\t<Id>/hostedzone/Z2682N5HXP0BZ4</Id>\n\t\t\t<Name>example2.com.</Name>\n\t\t\t<CallerReference>a_unique_reference2</CallerReference>\n\t\t\t<Config>\n\t\t\t\t<Comment>This is my 2nd hosted zone.</Comment>\n\t\t\t</Config>\n\t\t\t<ResourceRecordSetCount>117</ResourceRecordSetCount>\n\t\t</HostedZone>\n\t</HostedZones>\n\t<Marker>Z222222VVVVVVV</Marker>\n\t<IsTruncated>true</IsTruncated>\n\t<NextMarker>Z333333YYYYYYY</NextMarker>\n\t<MaxItems>10</MaxItems>\n</ListHostedZonesResponse>\n"
  },
  {
    "path": "apis/route53/src/test/resources/invalid_change_batch.xml",
    "content": "<?xml version=\"1.0\"?>\n<InvalidChangeBatch xmlns=\"https://route53.amazonaws.com/doc/2012-02-29/\">\n\t<Messages>\n\t\t<Message>Tried to create resource record set duplicate.example.com. type A, but it already exists</Message>\n\t\t<Message>Tried to delete resource record set noexist.example.com. type A, but it was not found</Message>\n\t</Messages>\n</InvalidChangeBatch>"
  },
  {
    "path": "apis/route53/src/test/resources/logback.xml",
    "content": "<?xml version=\"1.0\"?>\n<configuration scan=\"false\">\n    <appender name=\"FILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <appender name=\"WIREFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds-wire.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n    \n    <root>\n        <level value=\"warn\" />\n    </root>\n\n    <logger name=\"org.jclouds\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"FILE\" />\n    </logger>\n\n    <logger name=\"jclouds.wire\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n\n    <logger name=\"jclouds.headers\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n\n</configuration>\n"
  },
  {
    "path": "apis/route53/src/test/resources/new_zone.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<CreateHostedZoneResponse\n\txmlns=\"https://route53.amazonaws.com/doc/2012-02-29/\">\n\t<HostedZone>\n\t\t<Id>/hostedzone/Z21DW1QVGID6NG</Id>\n\t\t<Name>example.com.</Name>\n\t\t<CallerReference>a_unique_reference</CallerReference>\n\t\t<Config>\n\t\t\t<Comment>Migrate an existing domain to Route 53</Comment>\n\t\t</Config>\n\t</HostedZone>\n\t<ChangeInfo>\n\t\t<Id>C2682N5HXP0BZ4</Id>\n\t\t<Status>INSYNC</Status>\n\t\t<SubmittedAt>2011-09-10T01:36:41.958Z</SubmittedAt>\n\t</ChangeInfo>\n\t<DelegationSet>\n\t\t<NameServers>\n\t\t\t<NameServer>ns-1638.awsdns-12.co.uk</NameServer>\n\t\t\t<NameServer>ns-144.awsdns-18.com</NameServer>\n\t\t\t<NameServer>ns-781.awsdns-33.net</NameServer>\n\t\t\t<NameServer>ns-1478.awsdns-56.org</NameServer>\n\t\t</NameServers>\n\t</DelegationSet>\n</CreateHostedZoneResponse>"
  },
  {
    "path": "apis/route53/src/test/resources/rrsets.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ListResourceRecordSetsResponse\n\txmlns=\"https://route53.amazonaws.com/doc/2012-02-29/\">\n\t<ResourceRecordSets>\n\t\t<ResourceRecordSet>\n\t\t\t<Name>example.com.</Name>\n\t\t\t<Type>SOA</Type>\n\t\t\t<TTL>900</TTL>\n\t\t\t<ResourceRecords>\n\t\t\t\t<ResourceRecord>\n\t\t\t\t\t<Value>ns-2048.awsdns-64.net. hostmaster.awsdns.com. 1 7200 900 1209600 86400</Value>\n\t\t\t\t</ResourceRecord>\n\t\t\t</ResourceRecords>\n\t\t</ResourceRecordSet>\n\t\t<ResourceRecordSet>\n\t\t\t<Name>example.com.</Name>\n\t\t\t<Type>NS</Type>\n\t\t\t<TTL>172800</TTL>\n\t\t\t<ResourceRecords>\n\t\t\t\t<ResourceRecord>\n\t\t\t\t\t<Value>ns-2048.awsdns-64.com.</Value>\n\t\t\t\t</ResourceRecord>\n\t\t\t\t<ResourceRecord>\n\t\t\t\t\t<Value>ns-2049.awsdns-65.net.</Value>\n\t\t\t\t</ResourceRecord>\n\t\t\t\t<ResourceRecord>\n\t\t\t\t\t<Value>ns-2050.awsdns-66.org.</Value>\n\t\t\t\t</ResourceRecord>\n\t\t\t\t<ResourceRecord>\n\t\t\t\t\t<Value>ns-2051.awsdns-67.co.uk.</Value>\n\t\t\t\t</ResourceRecord>\n\t\t\t</ResourceRecords>\n\t\t</ResourceRecordSet>\n\t</ResourceRecordSets>\n\t<IsTruncated>true</IsTruncated>\n\t<MaxItems>3</MaxItems>\n\t<NextRecordName>testdoc2.example.com</NextRecordName>\n\t<NextRecordType>NS</NextRecordType>\n</ListResourceRecordSetsResponse>"
  },
  {
    "path": "apis/s3/README.txt",
    "content": "#\n# The jclouds API for Amazon's S3 (http://aws.amazon.com/s3/).\n#\n# TODO: Implementation status.\n# TODO: Supported features.\n# TODO: Usage example.\n"
  },
  {
    "path": "apis/s3/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.s3.*;version=\"${project.version}\";-noimport:=true"
  },
  {
    "path": "apis/s3/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.api</groupId>\n  <artifactId>s3</artifactId>\n  <name>jclouds s3 api</name>\n  <description>jclouds components to access an implementation of S3</description>\n\n  <properties>\n    <test.s3.endpoint>https://s3.amazonaws.com</test.s3.endpoint>\n    <test.s3.api-version>2006-03-01</test.s3.api-version>\n    <test.s3.build-version />\n    <test.s3.identity>${test.aws.identity}</test.s3.identity>\n    <test.s3.credential>${test.aws.credential}</test.s3.credential>\n    <test.s3.sessionToken>${test.aws.sessionToken}</test.s3.sessionToken>\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>sts</artifactId>\n      <version>${project.version}</version>\n      <type>jar</type>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-blobstore</artifactId>\n      <version>${project.version}</version>\n      <type>jar</type>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-blobstore</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-log4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-okhttp</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.logging.log4j</groupId>\n      <artifactId>log4j-core</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.squareup.okhttp3</groupId>\n      <artifactId>mockwebserver</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.value</groupId>\n      <artifactId>auto-value</artifactId>\n      <scope>provided</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.gaul</groupId>\n      <artifactId>modernizer-maven-annotations</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <jclouds.blobstore.httpstream.url>${jclouds.blobstore.httpstream.url}</jclouds.blobstore.httpstream.url>\n                    <jclouds.blobstore.httpstream.md5>${jclouds.blobstore.httpstream.md5}</jclouds.blobstore.httpstream.md5>\n                    <test.s3.endpoint>${test.s3.endpoint}</test.s3.endpoint>\n                    <test.s3.api-version>${test.s3.api-version}</test.s3.api-version>\n                    <test.s3.build-version>${test.s3.build-version}</test.s3.build-version>\n                    <test.s3.identity>${test.s3.identity}</test.s3.identity>\n                    <test.s3.credential>${test.s3.credential}</test.s3.credential>\n                    <test.s3.sessionToken>${test.s3.sessionToken}</test.s3.sessionToken>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n    <profile>\n      <id>s3proxy</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <excludedGroups>fails-on-s3proxy</excludedGroups>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/Bucket.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3;\n\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.ElementType.PARAMETER;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\nimport jakarta.inject.Qualifier;\n\n/**\n * Annotates the parameter that this is a bucket.\n */\n@Target({ PARAMETER, METHOD })\n@Retention(RUNTIME)\n@Qualifier\npublic @interface Bucket {\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/S3.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3;\n\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.IterableWithMarkers;\nimport org.jclouds.collect.PagedIterable;\nimport org.jclouds.collect.PagedIterables;\nimport org.jclouds.s3.domain.ListBucketResponse;\nimport org.jclouds.s3.domain.ObjectMetadata;\nimport org.jclouds.s3.options.ListBucketOptions;\n\nimport com.google.common.base.Function;\n\n/**\n * Utilities for using S3.\n */\npublic class S3 {\n\n   /**\n    * List all objects in a bucket, in a way that manages pagination, based on\n    * the criteria in the {@link ListBucketOptions} passed in.\n    *\n    * ex.\n    *\n    * <pre>\n    * continueAfterEachPage = listBucket(s3Client, bucket, options).concat();\n    *\n    * </pre>\n    *\n    * @param s3Client\n    *           the {@link S3Client} to use for the requests\n    * @param bucket\n    *           the bucket to list\n    * @param options\n    *           the {@link ListBucketOptions} describing the listBucket requests\n    *\n    * @return iterable of objects fitting the criteria\n    * @see PagedIterable\n    */\n   public static PagedIterable<ObjectMetadata> listBucket(final S3Client s3Client, final String bucket,\n         final ListBucketOptions options) {\n      return PagedIterables.advance(ToIterableWithMarker.INSTANCE.apply(s3Client.listBucket(bucket, options)),\n            new Function<Object, IterableWithMarker<ObjectMetadata>>() {\n\n               @Override\n               public IterableWithMarker<ObjectMetadata> apply(Object input) {\n                  return ToIterableWithMarker.INSTANCE.apply(s3Client.listBucket(bucket,\n                        options.clone().afterMarker(input.toString())));\n               }\n\n               @Override\n               public String toString() {\n                  return \"listBucket(\" + options + \")\";\n               }\n            });\n   }\n\n   private enum ToIterableWithMarker implements Function<ListBucketResponse, IterableWithMarker<ObjectMetadata>> {\n      INSTANCE;\n      @Override\n      public IterableWithMarker<ObjectMetadata> apply(ListBucketResponse in) {\n         return IterableWithMarkers.from(in, in.getNextMarker());\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/S3ApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3;\n\nimport static org.jclouds.Constants.PROPERTY_IDEMPOTENT_METHODS;\nimport static org.jclouds.Constants.PROPERTY_RELAX_HOSTNAME;\nimport static org.jclouds.aws.reference.AWSConstants.PROPERTY_AUTH_TAG;\nimport static org.jclouds.aws.reference.AWSConstants.PROPERTY_HEADER_TAG;\nimport static org.jclouds.blobstore.reference.BlobStoreConstants.PROPERTY_BLOBSTORE_DIRECTORY_SUFFIX;\nimport static org.jclouds.blobstore.reference.BlobStoreConstants.PROPERTY_USER_METADATA_PREFIX;\nimport static org.jclouds.reflect.Reflection2.typeToken;\nimport static org.jclouds.s3.reference.S3Constants.PROPERTY_JCLOUDS_S3_CHUNKED_SIZE;\nimport static org.jclouds.s3.reference.S3Constants.PROPERTY_S3_SERVICE_PATH;\nimport static org.jclouds.s3.reference.S3Constants.PROPERTY_S3_VIRTUAL_HOST_BUCKETS;\nimport static org.jclouds.s3.reference.S3Constants.PROPERTY_SIGNER_VERSION;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.rest.internal.BaseHttpApiMetadata;\nimport org.jclouds.s3.blobstore.S3BlobStoreContext;\nimport org.jclouds.s3.blobstore.config.S3BlobStoreContextModule;\nimport org.jclouds.s3.config.S3HttpApiModule;\nimport org.jclouds.s3.reference.S3Headers;\n\nimport com.google.auto.service.AutoService;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n/**\n * Implementation of {@link ApiMetadata} for Amazon's S3 api.\n * \n * <h3>note</h3>\n * <p/>\n * This class allows overriding of types {@code A}(api), so that children can\n * add additional methods not declared here, such as new features from AWS.\n * <p/>\n * \n * As this is a popular api, we also allow overrides for type {@code C}\n * (context). This allows subtypes to add in new feature groups or extensions,\n * not present in the base api. For example, you could make a subtype for\n * context, that exposes admin operations.\n */\n@AutoService(ApiMetadata.class)\npublic class S3ApiMetadata extends BaseHttpApiMetadata {\n\n   @Override\n   public Builder<?, ?> toBuilder() {\n      return new ConcreteBuilder().fromApiMetadata(this);\n   }\n\n   public S3ApiMetadata() {\n      this(new ConcreteBuilder());\n   }\n\n   protected S3ApiMetadata(Builder<?, ?> builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = BaseHttpApiMetadata.defaultProperties();\n      properties.setProperty(PROPERTY_AUTH_TAG, \"AWS\");\n      properties.setProperty(PROPERTY_HEADER_TAG, S3Headers.DEFAULT_AMAZON_HEADERTAG);\n      properties.setProperty(PROPERTY_S3_SERVICE_PATH, \"/\");\n      properties.setProperty(PROPERTY_S3_VIRTUAL_HOST_BUCKETS, \"false\");\n      properties.setProperty(PROPERTY_RELAX_HOSTNAME, \"true\");\n      properties.setProperty(PROPERTY_BLOBSTORE_DIRECTORY_SUFFIX, \"/\");\n      properties.setProperty(PROPERTY_USER_METADATA_PREFIX, String.format(\"x-${%s}-meta-\", PROPERTY_HEADER_TAG));\n      properties.setProperty(PROPERTY_IDEMPOTENT_METHODS, \"DELETE,GET,HEAD,OPTIONS,POST,PUT\");\n      properties.setProperty(PROPERTY_SIGNER_VERSION, \"2\");\n\n      // Chunk size must be at least 8 KB. We recommend a chunk size of a least 64 KB for better performance.\n      properties.setProperty(PROPERTY_JCLOUDS_S3_CHUNKED_SIZE, String.valueOf(64 * 1024));\n      return properties;\n   }\n   \n   public abstract static class Builder<A extends S3Client, T extends Builder<A, T>> extends\n         BaseHttpApiMetadata.Builder<A, T> {\n\n      protected Builder() {\n         this(Class.class.cast(S3Client.class));\n      }\n\n      protected Builder(Class<A> syncClient) {\n         super(syncClient);\n         id(\"s3\")\n         .name(\"Amazon Simple Storage Service (S3) API\")\n         .identityName(\"Access Key ID\")\n         .credentialName(\"Secret Access Key\")\n         .defaultEndpoint(\"http://localhost\")\n         .documentation(URI.create(\"http://docs.amazonwebservices.com/AmazonS3/latest/API\"))\n         .version(\"2006-03-01\")\n         .defaultProperties(S3ApiMetadata.defaultProperties())\n         .view(typeToken(S3BlobStoreContext.class))\n         .defaultModules(ImmutableSet.<Class<? extends Module>>of(S3HttpApiModule.class, S3BlobStoreContextModule.class));\n      }\n\n      @Override\n      public ApiMetadata build() {\n         return new S3ApiMetadata(this);\n      }\n   }\n   \n   private static class ConcreteBuilder extends Builder<S3Client, ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/S3Client.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3;\n\nimport static com.google.common.net.HttpHeaders.EXPECT;\nimport static org.jclouds.blobstore.attr.BlobScopes.CONTAINER;\n\nimport java.io.Closeable;\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.HEAD;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.blobstore.BlobStoreFallbacks.FalseOnContainerNotFound;\nimport org.jclouds.blobstore.BlobStoreFallbacks.FalseOnKeyNotFound;\nimport org.jclouds.blobstore.BlobStoreFallbacks.NullOnKeyNotFound;\nimport org.jclouds.blobstore.BlobStoreFallbacks.ThrowContainerNotFoundOn404;\nimport org.jclouds.blobstore.BlobStoreFallbacks.ThrowKeyNotFoundOn404;\nimport org.jclouds.blobstore.attr.BlobScope;\nimport org.jclouds.http.functions.ParseETagHeader;\nimport org.jclouds.http.options.GetOptions;\nimport org.jclouds.io.Payload;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Endpoint;\nimport org.jclouds.rest.annotations.EndpointParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.Headers;\nimport org.jclouds.rest.annotations.ParamParser;\nimport org.jclouds.rest.annotations.ParamValidators;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.VirtualHost;\nimport org.jclouds.rest.annotations.XMLResponseParser;\nimport org.jclouds.s3.S3Fallbacks.TrueOn404OrNotFoundFalseOnIllegalState;\nimport org.jclouds.s3.binders.BindACLToXMLPayload;\nimport org.jclouds.s3.binders.BindAsHostPrefixIfConfigured;\nimport org.jclouds.s3.binders.BindBucketLoggingToXmlPayload;\nimport org.jclouds.s3.binders.BindCannedAclToRequest;\nimport org.jclouds.s3.binders.BindIterableAsPayloadToDeleteRequest;\nimport org.jclouds.s3.binders.BindNoBucketLoggingToXmlPayload;\nimport org.jclouds.s3.binders.BindObjectMetadataToRequest;\nimport org.jclouds.s3.binders.BindOwnershipControlsToXMLPayload;\nimport org.jclouds.s3.binders.BindPartIdsAndETagsToRequest;\nimport org.jclouds.s3.binders.BindPayerToXmlPayload;\nimport org.jclouds.s3.binders.BindPublicAccessBlockConfigurationToXMLPayload;\nimport org.jclouds.s3.binders.BindS3ObjectMetadataToRequest;\nimport org.jclouds.s3.domain.AccessControlList;\nimport org.jclouds.s3.domain.BucketLogging;\nimport org.jclouds.s3.domain.BucketMetadata;\nimport org.jclouds.s3.domain.CannedAccessPolicy;\nimport org.jclouds.s3.domain.DeleteResult;\nimport org.jclouds.s3.domain.ListBucketResponse;\nimport org.jclouds.s3.domain.ListMultipartUploadResponse;\nimport org.jclouds.s3.domain.ListMultipartUploadsResponse;\nimport org.jclouds.s3.domain.ObjectMetadata;\nimport org.jclouds.s3.domain.Payer;\nimport org.jclouds.s3.domain.PublicAccessBlockConfiguration;\nimport org.jclouds.s3.domain.S3Object;\nimport org.jclouds.s3.fallbacks.FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists;\nimport org.jclouds.s3.filters.RequestAuthorizeSignature;\nimport org.jclouds.s3.functions.AssignCorrectHostnameForBucket;\nimport org.jclouds.s3.functions.BindRegionToXmlPayload;\nimport org.jclouds.s3.functions.DefaultEndpointThenInvalidateRegion;\nimport org.jclouds.s3.functions.ETagFromHttpResponseViaRegex;\nimport org.jclouds.s3.functions.ObjectKey;\nimport org.jclouds.s3.functions.ObjectMetadataKey;\nimport org.jclouds.s3.functions.ParseObjectFromHeadersAndHttpContent;\nimport org.jclouds.s3.functions.ParseObjectMetadataFromHeaders;\nimport org.jclouds.s3.functions.UploadIdFromHttpResponseViaRegex;\nimport org.jclouds.s3.options.CopyObjectOptions;\nimport org.jclouds.s3.options.ListBucketOptions;\nimport org.jclouds.s3.options.PutBucketOptions;\nimport org.jclouds.s3.options.PutObjectOptions;\nimport org.jclouds.s3.predicates.validators.BucketNameValidator;\nimport org.jclouds.s3.xml.AccessControlListHandler;\nimport org.jclouds.s3.xml.BucketLoggingHandler;\nimport org.jclouds.s3.xml.CopyObjectHandler;\nimport org.jclouds.s3.xml.DeleteResultHandler;\nimport org.jclouds.s3.xml.ListAllMyBucketsHandler;\nimport org.jclouds.s3.xml.ListBucketHandler;\nimport org.jclouds.s3.xml.ListMultipartUploadsHandler;\nimport org.jclouds.s3.xml.LocationConstraintHandler;\nimport org.jclouds.s3.xml.PartIdsFromHttpResponse;\nimport org.jclouds.s3.xml.PartIdsFromHttpResponseFull;\nimport org.jclouds.s3.xml.PayerHandler;\n\nimport com.google.common.annotations.Beta;\nimport com.google.inject.Provides;\n\n/**\n * Provides access to S3 via their REST API.\n */\n@RequestFilters(RequestAuthorizeSignature.class)\n@BlobScope(CONTAINER)\npublic interface S3Client extends Closeable {\n\n   /**\n    * Creates a default implementation of S3Object\n    */\n   @Provides\n   S3Object newS3Object();\n\n   /**\n    * Retrieves the S3Object associated with the Key or KeyNotFoundException if not available;\n    * \n    * <p/>\n    * To use GET, you must have READ access to the object. If READ access is granted to the\n    * anonymous user, you can request the object without an authorization header.\n    * \n    * <p />\n    * This command allows you to specify {@link GetOptions} to control delivery of content.\n    * \n    * <h2>Note</h2>\n    * If you specify any of the below options, you will receive partial content:\n    * <ul>\n    * <li>{@link GetOptions#range}</li>\n    * <li>{@link GetOptions#startAt}</li>\n    * <li>{@link GetOptions#tail}</li>\n    * </ul>\n    * \n    * @param bucketName\n    *           namespace of the object you are retrieving\n    * @param key\n    *           unique key in the s3Bucket identifying the object\n    * @return Future reference to a fully populated S3Object including data stored in S3\n    *         or null if not present.\n    * \n    * @throws org.jclouds.http.HttpResponseException\n    *            if the conditions requested set were not satisfied by the object on the server.\n    */\n   @Named(\"GetObject\")\n   @GET\n   @Path(\"/{key}\")\n   @Fallback(NullOnKeyNotFound.class)\n   @ResponseParser(ParseObjectFromHeadersAndHttpContent.class)\n   S3Object getObject(@Bucket @EndpointParam(parser = AssignCorrectHostnameForBucket.class) @BinderParam(\n         BindAsHostPrefixIfConfigured.class) @ParamValidators(BucketNameValidator.class) String bucketName,\n         @PathParam(\"key\") String key, GetOptions... options);\n\n   /**\n    * Retrieves the {@link org.jclouds.s3.domain.internal.BucketListObjectMetadata metadata} of\n    * the object associated with the key or null if not available.\n    * \n    * <p/>\n    * The HEAD operation is used to retrieve information about a specific object or object size,\n    * without actually fetching the object itself. This is useful if you're only interested in the\n    * object metadata, and don't want to waste bandwidth on the object data.\n    * \n    * \n    * @param bucketName namespace of the metadata you are retrieving\n    * @param key unique key in the s3Bucket identifying the object\n    * @return metadata associated with the key or null if not present.\n    */\n   @Named(\"GetObject\")\n   @HEAD\n   @Path(\"/{key}\")\n   @Fallback(NullOnKeyNotFound.class)\n   @ResponseParser(ParseObjectMetadataFromHeaders.class)\n   ObjectMetadata headObject(@Bucket @EndpointParam(parser = AssignCorrectHostnameForBucket.class) @BinderParam(\n         BindAsHostPrefixIfConfigured.class) @ParamValidators(BucketNameValidator.class) String bucketName,\n         @PathParam(\"key\") String key);\n\n   @Named(\"GetObject\")\n   @HEAD\n   @Path(\"/{key}\")\n   @Fallback(FalseOnKeyNotFound.class)\n   boolean objectExists(@Bucket @EndpointParam(parser = AssignCorrectHostnameForBucket.class) @BinderParam(\n         BindAsHostPrefixIfConfigured.class) @ParamValidators(BucketNameValidator.class) String bucketName,\n         @PathParam(\"key\") String key);\n\n   /**\n    * Removes the object and metadata associated with the key.\n    * <p/>\n    * The DELETE request operation removes the specified object from Amazon S3. Once deleted, there\n    * is no method to restore or undelete an object.\n    * \n    * \n    * @param bucketName\n    *           namespace of the object you are deleting\n    * @param key\n    *           unique key in the s3Bucket identifying the object\n    * @throws org.jclouds.http.HttpResponseException\n    *            if the bucket is not available\n    */\n   @Named(\"DeleteObject\")\n   @DELETE\n   @Path(\"/{key}\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void deleteObject(@Bucket @EndpointParam(parser = AssignCorrectHostnameForBucket.class) @BinderParam(\n         BindAsHostPrefixIfConfigured.class) @ParamValidators(BucketNameValidator.class) String bucketName,\n         @PathParam(\"key\") String key);\n\n   /**\n    * The Multi-Object Delete operation enables you to delete multiple objects from a bucket using a\n    * single HTTP request. If you know the object keys that you want to delete, then this operation\n    * provides a suitable alternative to sending individual delete requests (see DELETE Object),\n    * reducing per-request overhead.\n    *\n    * The Multi-Object Delete request contains a set of up to 1000 keys that you want to delete.\n    *\n    * If a key does not exist is considered to be deleted.\n    *\n    * The Multi-Object Delete operation supports two modes for the response; verbose and quiet.\n    * By default, the operation uses verbose mode in which the response includes the result of\n    * deletion of each key in your request.\n    *\n    * @param bucketName\n    *           namespace of the objects you are deleting\n    * @param keys\n    *           set of unique keys identifying objects\n    */\n   @Named(\"DeleteObject\")\n   @POST\n   @Path(\"/\")\n   @QueryParams(keys = \"delete\")\n   @XMLResponseParser(DeleteResultHandler.class)\n   DeleteResult deleteObjects(@Bucket @EndpointParam(parser = AssignCorrectHostnameForBucket.class) @BinderParam(\n         BindAsHostPrefixIfConfigured.class) @ParamValidators(BucketNameValidator.class) String bucketName,\n         @BinderParam(BindIterableAsPayloadToDeleteRequest.class) Iterable<String> keys);\n\n   /**\n    * Store data by creating or overwriting an object.\n    * <p/>\n    * This method will store the object with the default <code>private</code acl.\n    * \n    * <p/>\n    * This returns a byte[] of the eTag hash of what Amazon S3 received\n    * <p />\n    * \n    * @param bucketName\n    *           namespace of the object you are storing\n    * @param object\n    *           contains the data and metadata to create or overwrite\n    * @param options\n    *           options for creating the object\n    * @return ETag of the content uploaded\n    * @throws org.jclouds.http.HttpResponseException\n    *            if the conditions requested set are not satisfied by the object on the server.\n    * @see org.jclouds.s3.domain.CannedAccessPolicy#PRIVATE\n    */\n   @Named(\"PutObject\")\n   @PUT\n   @Path(\"/{key}\")\n   @Headers(keys = EXPECT, values = \"100-continue\")\n   @ResponseParser(ParseETagHeader.class)\n   String putObject(@Bucket @EndpointParam(parser = AssignCorrectHostnameForBucket.class) @BinderParam(\n         BindAsHostPrefixIfConfigured.class) @ParamValidators(BucketNameValidator.class) String bucketName,\n         @PathParam(\"key\") @ParamParser(ObjectKey.class) @BinderParam(BindS3ObjectMetadataToRequest.class)\n         S3Object object, PutObjectOptions... options);\n\n   /**\n    * Create and name your own bucket in which to store your objects.\n    * \n    * <p/>\n    * you can use {@link PutBucketOptions} to create the bucket in EU.\n    * <p/>\n    * The PUT request operation with a bucket URI creates a new bucket. Depending on your latency\n    * and legal requirements, you can specify a location constraint that will affect where your data\n    * physically resides. You can currently specify a Europe (EU) location constraint via\n    * {@link PutBucketOptions}.\n    * \n    * @param options\n    *           for creating your bucket\n    * @return true, if the bucket was created or false, if the container was already present\n    * \n    * @see PutBucketOptions\n    */\n   @Named(\"CreateBucket\")\n   @PUT\n   @Path(\"/\")\n   @Endpoint(Bucket.class)\n   @Fallback(FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists.class)\n   boolean putBucketInRegion(@BinderParam(BindRegionToXmlPayload.class) @Nullable String region,\n         @Bucket @EndpointParam(parser = AssignCorrectHostnameForBucket.class) \n         @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators(BucketNameValidator.class)\n         String bucketName, PutBucketOptions... options);\n\n   /**\n    * Deletes the bucket, if it is empty.\n    * <p/>\n    * The DELETE request operation deletes the bucket named in the URI. All objects in the bucket\n    * must be deleted before the bucket itself can be deleted.\n    * <p />\n    * Only the owner of a bucket can delete it, regardless of the bucket's access control policy.\n    * \n    * \n    * @param bucketName what to delete\n    * @return false, if the bucket was not empty and therefore not deleted\n    */\n   @Named(\"DeleteBucket\")\n   @DELETE\n   @Path(\"/\")\n   @Fallback(TrueOn404OrNotFoundFalseOnIllegalState.class)\n   boolean deleteBucketIfEmpty(@Bucket @EndpointParam(parser = DefaultEndpointThenInvalidateRegion.class) @BinderParam(\n         BindAsHostPrefixIfConfigured.class) @ParamValidators(BucketNameValidator.class) String bucketName);\n\n\n   /**\n    * Issues a HEAD command to determine if the bucket exists or not.\n    */\n   @Named(\"BucketExists\")\n   @HEAD\n   @Path(\"/\")\n   @Fallback(FalseOnContainerNotFound.class)\n   boolean bucketExists(@Bucket @EndpointParam(parser = AssignCorrectHostnameForBucket.class) @BinderParam(\n         BindAsHostPrefixIfConfigured.class) @ParamValidators(BucketNameValidator.class) String bucketName);\n\n   /**\n    * Retrieve a {@code S3Bucket} listing. A GET request operation using a bucket URI lists\n    * information about the objects in the bucket. You can use {@link ListBucketOptions} to control\n    * the amount of S3Objects to return.\n    * <p />\n    * To list the keys of a bucket, you must have READ access to the bucket.\n    * <p/>\n    * \n    * @param bucketName namespace of the objects you wish to list\n    * @return potentially empty or partial list of the bucket.\n    * @see ListBucketOptions\n    */\n   @Named(\"ListBucket\")\n   @GET\n   @Path(\"/\")\n   @XMLResponseParser(ListBucketHandler.class)\n   ListBucketResponse listBucket(@Bucket @EndpointParam(parser = AssignCorrectHostnameForBucket.class) @BinderParam(\n         BindAsHostPrefixIfConfigured.class) @ParamValidators(BucketNameValidator.class) String bucketName,\n         ListBucketOptions... options);\n\n   /**\n    * Returns a list of all of the buckets owned by the authenticated sender of the request.\n    * \n    * @return list of all of the buckets owned by the authenticated sender of the request.\n    */\n   @Named(\"ListAllMyBuckets\")\n   @GET\n   @XMLResponseParser(ListAllMyBucketsHandler.class)\n   @Path(\"/\")\n   @VirtualHost\n   Set<BucketMetadata> listOwnedBuckets();\n\n\n   /**\n    * Copies one object to another bucket, retaining UserMetadata from the source. The destination\n    * will have a private acl. The copy operation creates a copy of an object that is already stored\n    * in Amazon S3.\n    * <p/>\n    * When copying an object, you can preserve all metadata (default) or\n    * {@link CopyObjectOptions#overrideMetadataWith(java.util.Map)} specify new\n    * metadata}. However, the ACL is not preserved and is set to private for the user making the\n    * request. To override the default ACL setting,\n    * {@link CopyObjectOptions#overrideAcl(org.jclouds.s3.domain.CannedAccessPolicy) specify a\n    * new ACL} when generating a copy request.\n    * \n    * @return metadata populated with lastModified and eTag of the new object\n    * @throws org.jclouds.http.HttpResponseException\n    *            if the conditions requested set are not satisfied by the object on the server.\n    * @see CopyObjectOptions\n    * @see org.jclouds.s3.domain.CannedAccessPolicy\n    */\n   @Named(\"PutObject\")\n   @PUT\n   @Path(\"/{destinationObject}\")\n   @Headers(keys = \"x-amz-copy-source\", values = \"/{sourceBucket}/{sourceObject}\", urlEncode = true)\n   @XMLResponseParser(CopyObjectHandler.class)\n   ObjectMetadata copyObject(@PathParam(\"sourceBucket\") String sourceBucket,\n         @PathParam(\"sourceObject\") String sourceObject,\n         @Bucket @EndpointParam(parser = AssignCorrectHostnameForBucket.class) @BinderParam(\n               BindAsHostPrefixIfConfigured.class) @ParamValidators(BucketNameValidator.class) String destinationBucket,\n         @PathParam(\"destinationObject\") String destinationObject, CopyObjectOptions... options);\n\n\n   /**\n    * \n    * A GET request operation directed at an object or bucket URI with the \"acl\" parameter retrieves\n    * the Access Control List (ACL) settings for that S3 item.\n    * <p />\n    * To list a bucket's ACL, you must have READ_ACP access to the item.\n    * \n    * @return access permissions of the bucket\n    */\n   @Named(\"GetBucketAcl\")\n   @GET\n   @QueryParams(keys = \"acl\")\n   @XMLResponseParser(AccessControlListHandler.class)\n   @Fallback(ThrowContainerNotFoundOn404.class)\n   @Path(\"/\")\n   AccessControlList getBucketACL(@Bucket @EndpointParam(parser = AssignCorrectHostnameForBucket.class) @BinderParam(\n         BindAsHostPrefixIfConfigured.class) @ParamValidators(BucketNameValidator.class) String bucketName);\n\n\n   /**\n    * Update a bucket's Access Control List settings.\n    * <p/>\n    * A PUT request operation directed at a bucket URI with the \"acl\" parameter sets the Access\n    * Control List (ACL) settings for that S3 item.\n    * <p />\n    * To set a bucket or object's ACL, you must have WRITE_ACP or FULL_CONTROL access to the item.\n    * \n    * @param bucketName\n    *           the bucket whose Access Control List settings will be updated.\n    * @param acl\n    *           the ACL to apply to the bucket. This acl object <strong>must</strong include a valid\n    *           owner identifier string in {@link AccessControlList#getOwner()}.\n    * @return true if the bucket's Access Control List was updated successfully.\n    */\n   @Named(\"PutBucketAcl\")\n   @PUT\n   @Path(\"/\")\n   @QueryParams(keys = \"acl\")\n   boolean putBucketACL(@Bucket @EndpointParam(parser = AssignCorrectHostnameForBucket.class) @BinderParam(\n         BindAsHostPrefixIfConfigured.class) @ParamValidators(BucketNameValidator.class) String bucketName,\n         @BinderParam(BindACLToXMLPayload.class) AccessControlList acl);\n\n   /**\n    * Update a bucket's Access Control List settings.\n    * <p/>\n    * A PUT request operation directed at a bucket URI with the \"acl\" parameter sets the Access\n    * Control List (ACL) settings for that S3 item.\n    * <p />\n    * To set a bucket or object's ACL, you must have WRITE_ACP or FULL_CONTROL access to the item.\n    *\n    * @param bucketName\n    *           the bucket whose Access Control List settings will be updated.\n    * @param acl\n    *           the ACL to apply to the bucket.\n    * @return true if the bucket's Access Control List was updated successfully.\n    */\n   @Named(\"UpdateBucketCannedAcl\")\n   @PUT\n   @Path(\"/\")\n   @QueryParams(keys = \"acl\")\n   boolean updateBucketCannedACL(@Bucket @EndpointParam(parser = AssignCorrectHostnameForBucket.class) @BinderParam(\n         BindAsHostPrefixIfConfigured.class) @ParamValidators(BucketNameValidator.class) String bucketName,\n         @BinderParam(BindCannedAclToRequest.class) CannedAccessPolicy acl);\n\n   /**\n    * A GET request operation directed at an object or bucket URI with the \"acl\" parameter retrieves\n    * the Access Control List (ACL) settings for that S3 item.\n    * <p />\n    * To list a object's ACL, you must have READ_ACP access to the item.\n    * \n    * @return access permissions of the object\n    */\n   @Named(\"GetObjectAcl\")\n   @GET\n   @QueryParams(keys = \"acl\")\n   @Path(\"/{key}\")\n   @XMLResponseParser(AccessControlListHandler.class)\n   @Fallback(ThrowKeyNotFoundOn404.class)\n   AccessControlList getObjectACL(@Bucket @EndpointParam(parser = AssignCorrectHostnameForBucket.class) @BinderParam(\n         BindAsHostPrefixIfConfigured.class) @ParamValidators(BucketNameValidator.class) String bucketName,\n         @PathParam(\"key\") String key);\n\n   /**\n    * Update an object's Access Control List settings.\n    * <p/>\n    * A PUT request operation directed at an object URI with the \"acl\" parameter sets the Access\n    * Control List (ACL) settings for that S3 item.\n    * <p />\n    * To set a bucket or object's ACL, you must have WRITE_ACP or FULL_CONTROL access to the item.\n    * \n    * @param bucketName\n    *           the bucket containing the object to be updated\n    * @param key\n    *           the key of the object whose Access Control List settings will be updated.\n    * @param acl\n    *           the ACL to apply to the object. This acl object <strong>must</strong include a valid\n    *           owner identifier string in {@link AccessControlList#getOwner()}.\n    * @return true if the object's Access Control List was updated successfully.\n    */\n   @Named(\"PutObjectAcl\")\n   @PUT\n   @QueryParams(keys = \"acl\")\n   @Path(\"/{key}\")\n   boolean putObjectACL(@Bucket @EndpointParam(parser = AssignCorrectHostnameForBucket.class) @BinderParam(\n         BindAsHostPrefixIfConfigured.class) @ParamValidators(BucketNameValidator.class) String bucketName,\n         @PathParam(\"key\") String key, @BinderParam(BindACLToXMLPayload.class) AccessControlList acl);\n\n   /**\n    * Update an object's Access Control List settings.\n    * <p/>\n    * A PUT request operation directed at an object URI with the \"acl\" parameter sets the Access\n    * Control List (ACL) settings for that S3 item.\n    * <p />\n    * To set a bucket or object's ACL, you must have WRITE_ACP or FULL_CONTROL access to the item.\n    *\n    * @param bucketName\n    *           the bucket containing the object to be updated\n    * @param key\n    *           the key of the object whose Access Control List settings will be updated.\n    * @param acl\n    *           the ACL to apply to the object.\n    * @return true if the object's Access Control List was updated successfully.\n    */\n   @Named(\"UpdateObjectCannedAcl\")\n   @PUT\n   @QueryParams(keys = \"acl\")\n   @Path(\"/{key}\")\n   boolean updateObjectCannedACL(@Bucket @EndpointParam(parser = AssignCorrectHostnameForBucket.class) @BinderParam(\n         BindAsHostPrefixIfConfigured.class) @ParamValidators(BucketNameValidator.class) String bucketName,\n         @PathParam(\"key\") String key, @BinderParam(BindCannedAclToRequest.class) CannedAccessPolicy acl);\n\n   /**\n    * A GET location request operation using a bucket URI lists the location constraint of the\n    * bucket.\n    * <p/>\n    * To view the location constraint of a bucket, you must be the bucket owner.\n    * \n    * @param bucketName\n    *           the bucket you wish to know where exists\n    * \n    * @return location of the bucket\n    */\n   @Named(\"GetBucketLocation\")\n   @GET\n   @QueryParams(keys = \"location\")\n   @Path(\"/{bucket}\")\n   @Endpoint(Bucket.class)\n   @XMLResponseParser(LocationConstraintHandler.class)\n   String getBucketLocation(@Bucket @PathParam(\"bucket\") @ParamValidators(\n         BucketNameValidator.class) String bucketName);\n\n\n   /**\n    * A GET request operation on a requestPayment resource returns the request payment configuration\n    * of a bucket.\n    * <p/>\n    * Only the bucket owner has permissions to get this value.\n    * \n    * @param bucketName\n    *           the bucket you wish to know the payer status\n    * \n    * @return {@link Payer#REQUESTER} for a Requester Pays bucket, and {@link Payer#BUCKET_OWNER},\n    *         for a normal bucket.\n    */\n   @Named(\"GetBucketRequestPayment\")\n   @GET\n   @QueryParams(keys = \"requestPayment\")\n   @Path(\"/\")\n   @XMLResponseParser(PayerHandler.class)\n   Payer getBucketPayer(@Bucket @EndpointParam(parser = AssignCorrectHostnameForBucket.class) @BinderParam(\n         BindAsHostPrefixIfConfigured.class) @ParamValidators(BucketNameValidator.class) String bucketName);\n\n\n   /**\n    * The PUT request operation with a requestPayment URI configures an existing bucket to be\n    * Requester Pays or not. To make a bucket a Requester Pays bucket, make the Payer value\n    * Requester. Otherwise, make the value BucketOwner.\n    * <p/>\n    * Only a bucket owner is allowed to configure a bucket. As a result any requests for this\n    * resource should be signed with the bucket owner's credentials. Anonymous requests are never\n    * allowed to create Requester Pays buckets.\n    * \n    * @param bucketName\n    *           the bucket you wish to know the payer status\n    * \n    * @param payer\n    *           {@link Payer#REQUESTER} for a Requester Pays bucket, and {@link Payer#BUCKET_OWNER},\n    *           for a normal bucket.\n    */\n   @Named(\"PutBucketRequestPayment\")\n   @PUT\n   @QueryParams(keys = \"requestPayment\")\n   @Path(\"/\")\n   void setBucketPayer(\n         @Bucket @EndpointParam(parser = AssignCorrectHostnameForBucket.class) @BinderParam(\n               BindAsHostPrefixIfConfigured.class) @ParamValidators(BucketNameValidator.class) String bucketName,\n         @BinderParam(BindPayerToXmlPayload.class) Payer payer);\n\n\n\n   /**\n    * Inspects the logging status for a bucket.\n    * \n    * \n    * @param bucketName\n    *           the bucket you wish to know the logging status\n    * @return bucketLogging configuration or null, if not configured\n    */\n   @Named(\"GetBucketLogging\")\n   @GET\n   @QueryParams(keys = \"logging\")\n   @XMLResponseParser(BucketLoggingHandler.class)\n   @Fallback(ThrowContainerNotFoundOn404.class)\n   @Path(\"/\")\n   BucketLogging getBucketLogging(@Bucket @EndpointParam(parser = AssignCorrectHostnameForBucket.class) @BinderParam(\n         BindAsHostPrefixIfConfigured.class) @ParamValidators(BucketNameValidator.class) String bucketName);\n\n\n   /**\n    * Enables logging for a bucket.\n    * \n    * @param bucketName\n    *           the bucket you wish to enable logging for\n    * @param logging\n    *           configuration including destination, prefix, and access rules\n    */\n   @Named(\"PutBucketLogging\")\n   @PUT\n   @Path(\"/\")\n   @QueryParams(keys = \"logging\")\n   void enableBucketLogging(@Bucket @EndpointParam(parser = AssignCorrectHostnameForBucket.class) @BinderParam(\n         BindAsHostPrefixIfConfigured.class) @ParamValidators(BucketNameValidator.class) String bucketName,\n         @BinderParam(BindBucketLoggingToXmlPayload.class) BucketLogging logging);\n\n   /**\n    * Disables logging for a bucket.\n    * \n    * @param bucketName\n    *           the bucket you wish to disable logging for\n    */\n   @Named(\"PutBucketLogging\")\n   @PUT\n   @Path(\"/\")\n   @QueryParams(keys = \"logging\")\n   @Produces(MediaType.TEXT_XML)\n   void disableBucketLogging(@Bucket @EndpointParam(parser = AssignCorrectHostnameForBucket.class) @BinderParam(\n               BindNoBucketLoggingToXmlPayload.class) @ParamValidators(BucketNameValidator.class) String bucketName);\n\n   /**\n    * This operation initiates a multipart upload and returns an upload ID. This upload ID is used\n    * to associate all the parts in the specific multipart upload. You specify this upload ID in\n    * each of your subsequent upload part requests (see Upload Part). You also include this upload\n    * ID in the final request to either complete or abort the multipart upload request.\n    *\n    * <h4>Note</h4> If you create an object using the multipart upload APIs, currently you cannot\n    * copy the object between regions.\n    *\n    *\n    * @param bucketName\n    *           namespace of the object you are to upload\n    * @param objectMetadata\n    *           metadata around the object you wish to upload\n    * @param options\n    *           controls optional parameters such as canned ACL\n    * @return ID for the initiated multipart upload.\n    */\n   @Named(\"PutObject\")\n   @POST\n   @QueryParams(keys = \"uploads\")\n   @Path(\"/{key}\")\n   @ResponseParser(UploadIdFromHttpResponseViaRegex.class)\n   String initiateMultipartUpload(@Bucket @EndpointParam(parser = AssignCorrectHostnameForBucket.class) @BinderParam(\n         BindAsHostPrefixIfConfigured.class) @ParamValidators(BucketNameValidator.class) String bucketName,\n         @PathParam(\"key\") @ParamParser(ObjectMetadataKey.class) @BinderParam(BindObjectMetadataToRequest.class)\n         ObjectMetadata objectMetadata, PutObjectOptions... options);\n\n   /**\n    * This operation aborts a multipart upload. After a multipart upload is aborted, no additional\n    * parts can be uploaded using that upload ID. The storage consumed by any previously uploaded\n    * parts will be freed. However, if any part uploads are currently in progress, those part\n    * uploads might or might not succeed. As a result, it might be necessary to abort a given\n    * multipart upload multiple times in order to completely free all storage consumed by all parts.\n    *\n    *\n    * @param bucketName\n    *           namespace of the object you are deleting\n    * @param key\n    *           unique key in the s3Bucket identifying the object\n    * @param uploadId\n    *           id of the multipart upload in progress.\n    */\n   @Named(\"AbortMultipartUpload\")\n   @DELETE\n   @Path(\"/{key}\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void abortMultipartUpload(@Bucket @EndpointParam(parser = AssignCorrectHostnameForBucket.class) @BinderParam(\n         BindAsHostPrefixIfConfigured.class) @ParamValidators(BucketNameValidator.class) String bucketName,\n         @PathParam(\"key\") String key, @QueryParam(\"uploadId\") String uploadId);\n\n   /**\n    * This operation uploads a part in a multipart upload. You must initiate a multipart upload (see\n    * Initiate Multipart Upload) before you can upload any part. In response to your initiate\n    * request. Amazon S3 returns an upload ID, a unique identifier, that you must include in your\n    * upload part request.\n    *\n    * <p/>\n    * Part numbers can be any number from 1 to 10,000, inclusive. A part number uniquely identifies\n    * a part and also defines its position within the object being created. If you upload a new part\n    * using the same part number that was used with a previous part, the previously uploaded part is\n    * overwritten. Each part must be at least 5 MB in size, except the last part. There is no size\n    * limit on the last part of your multipart upload.\n    *\n    * <p/>\n    * To ensure that data is not corrupted when traversing the network, specify the Content-MD5\n    * header in the upload part request. Amazon S3 checks the part data against the provided MD5\n    * value. If they do not match, Amazon S3 returns an error.\n    *\n    *\n    * @param bucketName\n    *           namespace of the object you are storing\n    * @param key\n    *           unique key in the s3Bucket identifying the object\n    * @param partNumber\n    *           which part is this.\n    * @param uploadId\n    *           id of the multipart upload in progress.\n    * @param part\n    *           contains the data to create or overwrite\n    * @return ETag of the content uploaded\n    */\n   @Named(\"PutObject\")\n   @PUT\n   @Path(\"/{key}\")\n   @ResponseParser(ParseETagHeader.class)\n   String uploadPart(@Bucket @EndpointParam(parser = AssignCorrectHostnameForBucket.class) @BinderParam(\n         BindAsHostPrefixIfConfigured.class) @ParamValidators(BucketNameValidator.class) String bucketName,\n         @PathParam(\"key\") String key, @QueryParam(\"partNumber\") int partNumber,\n         @QueryParam(\"uploadId\") String uploadId, Payload part);\n\n   @Named(\"UploadPartCopy\")\n   @PUT\n   @Path(\"/{key}\")\n   @Headers(keys = {\"x-amz-copy-source\", \"x-amz-copy-source-range\"}, values = {\"/{sourceBucket}/{sourceObject}\", \"bytes={startOffset}-{endOffset}\"}, urlEncode = {true, false})\n   @ResponseParser(ETagFromHttpResponseViaRegex.class)\n   String uploadPartCopy(@Bucket @EndpointParam(parser = AssignCorrectHostnameForBucket.class) @BinderParam(\n         BindAsHostPrefixIfConfigured.class) @ParamValidators(BucketNameValidator.class) String bucketName,\n         @PathParam(\"key\") String key, @QueryParam(\"partNumber\") int partNumber,\n         @QueryParam(\"uploadId\") String uploadId,\n         @PathParam(\"sourceBucket\") String sourceBucket, @PathParam(\"sourceObject\") String sourceObject,\n         @PathParam(\"startOffset\") long startOffset, @PathParam(\"endOffset\") long endOffset);\n\n   /**\n    *\n    This operation completes a multipart upload by assembling previously uploaded parts.\n    * <p/>\n    * You first initiate the multipart upload and then upload all parts using the Upload Parts\n    * operation (see Upload Part). After successfully uploading all relevant parts of an upload, you\n    * call this operation to complete the upload. Upon receiving this request, Amazon S3\n    * concatenates all the parts in ascending order by part number to create a new object. In the\n    * Complete Multipart Upload request, you must provide the parts list. For each part in the list,\n    * you must provide the part number and the ETag header value, returned after that part was\n    * uploaded.\n    * <p/>\n    * Processing of a Complete Multipart Upload request could take several minutes to complete.\n    * After Amazon S3 begins processing the request, it sends an HTTP response header that specifies\n    * a 200 OK response. While processing is in progress, Amazon S3 periodically sends whitespace\n    * characters to keep the connection from timing out. Because a request could fail after the\n    * initial 200 OK response has been sent, it is important that you check the response body to\n    * determine whether the request succeeded.\n    * <p/>\n    * Note that if Complete Multipart Upload fails, applications should be prepared to retry the\n    * failed requests.\n    *\n    * @param bucketName\n    *           namespace of the object you are deleting\n    * @param key\n    *           unique key in the s3Bucket identifying the object\n    * @param uploadId\n    *           id of the multipart upload in progress.\n    * @param parts\n    *           a map of part id to eTag from the {@link #uploadPart} command.\n    * @return ETag of the content uploaded\n    */\n   @Named(\"PutObject\")\n   @POST\n   @Path(\"/{key}\")\n   @ResponseParser(ETagFromHttpResponseViaRegex.class)\n   String completeMultipartUpload(@Bucket @EndpointParam(parser = AssignCorrectHostnameForBucket.class) @BinderParam(\n         BindAsHostPrefixIfConfigured.class) @ParamValidators(BucketNameValidator.class) String bucketName,\n         @PathParam(\"key\") String key, @QueryParam(\"uploadId\") String uploadId,\n         @BinderParam(BindPartIdsAndETagsToRequest.class) Map<Integer, String> parts);\n\n   /** @deprecated see #listMultipartPartsFull */\n   @Deprecated\n   @Named(\"ListMultipartParts\")\n   @GET\n   @Path(\"/{key}\")\n   @XMLResponseParser(PartIdsFromHttpResponse.class)\n   Map<Integer, String> listMultipartParts(@Bucket @EndpointParam(parser = AssignCorrectHostnameForBucket.class)\n         @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators(BucketNameValidator.class) String bucketName,\n         @PathParam(\"key\") String key, @QueryParam(\"uploadId\") String uploadId);\n\n   @Beta\n   @Named(\"ListMultipartParts\")\n   @GET\n   @Path(\"/{key}\")\n   @XMLResponseParser(PartIdsFromHttpResponseFull.class)\n   Map<Integer, ListMultipartUploadResponse> listMultipartPartsFull(@Bucket @EndpointParam(parser = AssignCorrectHostnameForBucket.class)\n         @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators(BucketNameValidator.class) String bucketName,\n         @PathParam(\"key\") String key, @QueryParam(\"uploadId\") String uploadId);\n\n   @Named(\"ListMultipartUploads\")\n   @GET\n   @Path(\"/\")\n   @QueryParams(keys = \"uploads\")\n   @XMLResponseParser(ListMultipartUploadsHandler.class)\n   ListMultipartUploadsResponse listMultipartUploads(@Bucket @EndpointParam(parser = AssignCorrectHostnameForBucket.class)\n         @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators(BucketNameValidator.class) String bucketName,\n         @QueryParam(\"delimiter\") @Nullable String delimiter, @QueryParam(\"max-uploads\") @Nullable Integer maxUploads,\n         @QueryParam(\"key-marker\") @Nullable String keyMarker, @QueryParam(\"prefix\") @Nullable String prefix,\n         @QueryParam(\"upload-id-marker\") @Nullable String uploadIdMarker);\n\n   @Named(\"PutBucketOwnershipControls\")\n   @PUT\n   @Path(\"/\")\n   @QueryParams(keys = \"ownershipControls\")\n   void putBucketOwnershipControls(@Bucket @EndpointParam(parser = AssignCorrectHostnameForBucket.class) @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators(BucketNameValidator.class) String bucketName,\n         // BucketOwnerPreferred | ObjectWriter | BucketOwnerEnforced\n         @BinderParam(BindOwnershipControlsToXMLPayload.class) String objectOwnership);\n\n   @Named(\"PutPublicAccessBlock\")\n   @PUT\n   @Path(\"/\")\n   @QueryParams(keys = \"publicAccessBlock\")\n   void putPublicAccessBlock(@Bucket @EndpointParam(parser = AssignCorrectHostnameForBucket.class) @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators(BucketNameValidator.class) String bucketName,\n         @BinderParam(BindPublicAccessBlockConfigurationToXMLPayload.class) PublicAccessBlockConfiguration configuration);\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/S3Fallbacks.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Predicates.equalTo;\nimport static com.google.common.base.Throwables.propagate;\nimport static org.jclouds.http.HttpUtils.returnValueOnCodeOrNull;\nimport static org.jclouds.util.Throwables2.getFirstThrowableOfType;\n\nimport org.jclouds.Fallback;\nimport org.jclouds.blobstore.ContainerNotFoundException;\n\npublic final class S3Fallbacks {\n   private S3Fallbacks() {\n   }\n\n   public static final class TrueOn404OrNotFoundFalseOnIllegalState implements Fallback<Boolean> {\n      @Override\n      public Boolean createOrPropagate(Throwable t) throws Exception {\n         if (getFirstThrowableOfType(checkNotNull(t, \"throwable\"), IllegalStateException.class) != null)\n            return false;\n         if (getFirstThrowableOfType(t, ContainerNotFoundException.class) != null)\n            return true;\n         if (returnValueOnCodeOrNull(t, true, equalTo(404)) != null)\n            return true;\n         throw propagate(t);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/binders/BindACLToXMLPayload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.binders;\n\nimport static org.jclouds.s3.binders.BindBucketLoggingToXmlPayload.addGrants;\nimport static org.jclouds.s3.binders.XMLHelper.asString;\nimport static org.jclouds.s3.binders.XMLHelper.createDocument;\nimport static org.jclouds.s3.binders.XMLHelper.elem;\nimport static org.jclouds.s3.binders.XMLHelper.elemWithText;\n\nimport jakarta.inject.Singleton;\nimport jakarta.ws.rs.core.MediaType;\nimport javax.xml.parsers.FactoryConfigurationError;\nimport javax.xml.parsers.ParserConfigurationException;\nimport javax.xml.transform.TransformerException;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\nimport org.jclouds.s3.domain.AccessControlList;\nimport org.jclouds.s3.reference.S3Constants;\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\n\nimport com.google.common.base.Throwables;\n\n@Singleton\npublic class BindACLToXMLPayload implements Binder {\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object payload) {\n      AccessControlList from = (AccessControlList) payload;\n      try {\n         request.setPayload(generatePayload(from));\n         request.getPayload().getContentMetadata().setContentType(MediaType.TEXT_XML);\n         return request;\n      } catch (Exception e) {\n         Throwables.propagateIfPossible(e);\n         throw new RuntimeException(\"error transforming acl: \" + from, e);\n      }\n   }\n\n   protected String generatePayload(AccessControlList acl)\n         throws ParserConfigurationException, FactoryConfigurationError, TransformerException {\n      Document document = createDocument();\n      Element rootNode = elem(document, \"AccessControlPolicy\", document);\n      rootNode.setAttribute(\"xmlns\", S3Constants.S3_REST_API_XML_NAMESPACE);\n      if (acl.getOwner() != null) {\n         Element ownerNode = elem(rootNode, \"Owner\", document);\n         elemWithText(ownerNode, \"ID\", acl.getOwner().getId(), document);\n         String displayName = acl.getOwner().getDisplayName();\n         if (displayName != null) {\n            elemWithText(ownerNode, \"DisplayName\", displayName, document);\n         }\n      }\n      addGrants(elem(rootNode, \"AccessControlList\", document),\n                acl.getGrants(),\n                document);\n      return asString(document);\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/binders/BindAsHostPrefixIfConfigured.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.binders;\n\nimport static org.jclouds.s3.reference.S3Constants.PROPERTY_S3_SERVICE_PATH;\nimport static org.jclouds.s3.reference.S3Constants.PROPERTY_S3_VIRTUAL_HOST_BUCKETS;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\nimport org.jclouds.rest.binders.BindAsHostPrefix;\n\nimport com.google.common.net.HttpHeaders;\n\n@Singleton\npublic class BindAsHostPrefixIfConfigured implements Binder {\n\n   protected final BindAsHostPrefix bindAsHostPrefix;\n   protected final boolean isVhostStyle;\n   protected final String servicePath;\n\n   @Inject\n   public BindAsHostPrefixIfConfigured(BindAsHostPrefix bindAsHostPrefix,\n            @Named(PROPERTY_S3_VIRTUAL_HOST_BUCKETS) boolean isVhostStyle,\n            @Named(PROPERTY_S3_SERVICE_PATH) String servicePath) {\n      this.bindAsHostPrefix = bindAsHostPrefix;\n      this.isVhostStyle = isVhostStyle;\n      this.servicePath = servicePath;\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object payload) {\n      // If we have a payload/bucket/container that is not all lowercase, vhost-style URLs are not an option and must be\n      // automatically converted to their path-based equivalent.  This should only be possible for AWS-S3 since it is\n      // the only S3 implementation configured to allow uppercase payload/bucket/container names.\n      //\n      // http://code.google.com/p/jclouds/issues/detail?id=992\n      String payloadAsString = payload.toString();\n\n      if (isVhostStyle && payloadAsString.equals(payloadAsString.toLowerCase())) {\n         request = bindAsHostPrefix.bindToRequest(request, payload);\n         String host = request.getEndpoint().getHost();\n         if (request.getEndpoint().getPort() != -1) {\n            host += \":\" + request.getEndpoint().getPort();\n         }\n         return (R) request.toBuilder().replaceHeader(HttpHeaders.HOST, host).build();\n      } else {\n         StringBuilder path = new StringBuilder(request.getEndpoint().getRawPath());\n         if (servicePath.equals(\"/\")) {\n            if (path.toString().equals(\"/\"))\n               path.append(payloadAsString);\n            else \n               path.insert(0, \"/\" + payloadAsString);\n         } else {\n            int indexToInsert = 0;\n            indexToInsert = path.indexOf(servicePath);\n            indexToInsert = indexToInsert == -1 ? 0 : indexToInsert;\n            indexToInsert += servicePath.length();\n            path.insert(indexToInsert, \"/\" + payloadAsString);\n         }\n         return (R) request.toBuilder().replacePath(path.toString()).build();\n      }\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/binders/BindBucketLoggingToXmlPayload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.binders;\n\nimport static org.jclouds.s3.binders.XMLHelper.asString;\nimport static org.jclouds.s3.binders.XMLHelper.createDocument;\nimport static org.jclouds.s3.binders.XMLHelper.elem;\nimport static org.jclouds.s3.binders.XMLHelper.elemWithText;\n\nimport java.util.Collection;\n\nimport jakarta.inject.Singleton;\nimport jakarta.ws.rs.core.MediaType;\nimport javax.xml.parsers.FactoryConfigurationError;\nimport javax.xml.parsers.ParserConfigurationException;\nimport javax.xml.transform.TransformerException;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\nimport org.jclouds.s3.domain.AccessControlList.CanonicalUserGrantee;\nimport org.jclouds.s3.domain.AccessControlList.EmailAddressGrantee;\nimport org.jclouds.s3.domain.AccessControlList.Grant;\nimport org.jclouds.s3.domain.AccessControlList.GroupGrantee;\nimport org.jclouds.s3.domain.BucketLogging;\nimport org.jclouds.s3.reference.S3Constants;\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\n\nimport com.google.common.base.Throwables;\n\n@Singleton\npublic class BindBucketLoggingToXmlPayload implements Binder {\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object payload) {\n      BucketLogging from = (BucketLogging) payload;\n      try {\n         request.setPayload(generatePayload(from));\n         request.getPayload().getContentMetadata().setContentType(MediaType.TEXT_XML);\n         return request;\n      } catch (Exception e) {\n         Throwables.propagateIfPossible(e);\n         throw new RuntimeException(\"error transforming bucketLogging: \" + from, e);\n      }\n   }\n\n   private String generatePayload(BucketLogging bucketLogging)\n         throws ParserConfigurationException, FactoryConfigurationError, TransformerException {\n      Document document = createDocument();\n      Element rootNode = elem(document, \"BucketLoggingStatus\", document);\n      rootNode.setAttribute(\"xmlns\", S3Constants.S3_REST_API_XML_NAMESPACE);\n      Element loggingNode = elem(rootNode, \"LoggingEnabled\", document);\n      elemWithText(loggingNode, \"TargetBucket\", bucketLogging.getTargetBucket(), document);\n      elemWithText(loggingNode, \"TargetPrefix\", bucketLogging.getTargetPrefix(), document);\n      addGrants(elem(loggingNode, \"TargetGrants\", document),\n                bucketLogging.getTargetGrants(),\n                document);\n      return asString(document);\n   }\n\n   static void addGrants(Element grantsNode, Collection<Grant> grants, Document document) {\n      for (Grant grant : grants) {\n         Element grantNode = elem(grantsNode, \"Grant\", document);\n         Element granteeNode = elem(grantNode, \"Grantee\", document);\n         granteeNode.setAttribute(\"xmlns:xsi\", \"http://www.w3.org/2001/XMLSchema-instance\");\n\n         if (grant.getGrantee() instanceof GroupGrantee) {\n            granteeNode.setAttribute(\"xsi:type\", \"Group\");\n            elemWithText(granteeNode, \"URI\", grant.getGrantee().getIdentifier(), document);\n         } else if (grant.getGrantee() instanceof CanonicalUserGrantee) {\n            CanonicalUserGrantee grantee = (CanonicalUserGrantee) grant.getGrantee();\n            granteeNode.setAttribute(\"xsi:type\", \"CanonicalUser\");\n            elemWithText(granteeNode, \"ID\", grantee.getIdentifier(), document);\n            if (grantee.getDisplayName() != null) {\n               elemWithText(granteeNode, \"DisplayName\", grantee.getDisplayName(), document);\n            }\n         } else if (grant.getGrantee() instanceof EmailAddressGrantee) {\n            granteeNode.setAttribute(\"xsi:type\", \"AmazonCustomerByEmail\");\n            elemWithText(granteeNode, \"EmailAddress\", grant.getGrantee().getIdentifier(), document);\n         }\n         elemWithText(grantNode, \"Permission\", grant.getPermission(), document);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/binders/BindCannedAclToRequest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\nimport org.jclouds.s3.domain.CannedAccessPolicy;\n\npublic class BindCannedAclToRequest implements Binder {\n   public BindCannedAclToRequest() {\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkArgument(checkNotNull(input, \"input\") instanceof CannedAccessPolicy, \"this binder is only valid for CannedAccessPolicy!, not %s\", input);\n      checkNotNull(request, \"request\");\n\n      CannedAccessPolicy policy = (CannedAccessPolicy) input;\n\n      request = (R) request.toBuilder().replaceHeader(\"x-amz-acl\", policy.toString()).build();\n      return request;\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/binders/BindIterableAsPayloadToDeleteRequest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.binders;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.hash.Hashing.md5;\nimport static org.jclouds.s3.binders.XMLHelper.asString;\nimport static org.jclouds.s3.binders.XMLHelper.createDocument;\nimport static org.jclouds.s3.binders.XMLHelper.elem;\nimport static org.jclouds.s3.binders.XMLHelper.elemWithText;\n\nimport jakarta.ws.rs.core.MediaType;\nimport javax.xml.parsers.ParserConfigurationException;\nimport javax.xml.transform.TransformerException;\n\nimport com.google.common.base.Throwables;\nimport com.google.common.collect.Iterables;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.rest.Binder;\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\n\npublic class BindIterableAsPayloadToDeleteRequest implements Binder {\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkArgument(checkNotNull(input, \"input is null\") instanceof Iterable,\n         \"this binder is only valid for an Iterable\");\n      checkNotNull(request, \"request is null\");\n\n      Iterable<String> keys = (Iterable<String>) input;\n      checkArgument(!Iterables.isEmpty(keys), \"The list of keys should not be empty.\");\n\n      String content;\n      try {\n         Document document = createDocument();\n         Element rootNode = elem(document, \"Delete\", document);\n         for (String key : keys) {\n            Element objectNode = elem(rootNode, \"Object\", document);\n            elemWithText(objectNode, \"Key\", key, document);\n         }\n\n         content = \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\" + asString(document);\n      } catch (ParserConfigurationException | TransformerException pce) {\n         throw Throwables.propagate(pce);\n      }\n\n      Payload payload = Payloads.newStringPayload(content);\n      payload.getContentMetadata().setContentType(MediaType.TEXT_XML);\n      byte[] md5 = md5().hashString(content, UTF_8).asBytes();\n      payload.getContentMetadata().setContentMD5(md5);\n      request.setPayload(payload);\n      return request;\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/binders/BindNoBucketLoggingToXmlPayload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.binders;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\n@Singleton\npublic class BindNoBucketLoggingToXmlPayload implements Binder {\n   private final BindAsHostPrefixIfConfigured bindAsHostPrefixIfConfigured;\n\n   @Inject\n   BindNoBucketLoggingToXmlPayload(BindAsHostPrefixIfConfigured bindAsHostPrefixIfConfigured) {\n      this.bindAsHostPrefixIfConfigured = bindAsHostPrefixIfConfigured;\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object payload) {\n      request = bindAsHostPrefixIfConfigured.bindToRequest(request, payload);\n      String stringPayload = \"<BucketLoggingStatus xmlns=\\\"http://s3.amazonaws.com/doc/2006-03-01/\\\"/>\";\n      request.setPayload(stringPayload);\n      return request;\n   }\n\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/binders/BindObjectMetadataToRequest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.io.BaseEncoding.base64;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.blobstore.binders.BindMapToHeadersWithPrefix;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\nimport org.jclouds.s3.domain.ObjectMetadata;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableMultimap.Builder;\nimport com.google.common.net.HttpHeaders;\n\n@Singleton\npublic class BindObjectMetadataToRequest implements Binder {\n   protected final BindMapToHeadersWithPrefix metadataPrefixer;\n\n   @Inject\n   public BindObjectMetadataToRequest(BindMapToHeadersWithPrefix metadataPrefixer) {\n      this.metadataPrefixer = checkNotNull(metadataPrefixer, \"metadataPrefixer\");\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkArgument(checkNotNull(input, \"input\") instanceof ObjectMetadata,\n               \"this binder is only valid for ObjectMetadata!\");\n      checkNotNull(request, \"request\");\n\n      ObjectMetadata md = ObjectMetadata.class.cast(input);\n      checkArgument(md.getKey() != null, \"objectMetadata.getKey() must be set!\");\n\n      request = metadataPrefixer.bindToRequest(request, md.getUserMetadata());\n\n      Builder<String, String> headers = ImmutableMultimap.builder();\n      if (md.getContentMetadata().getCacheControl() != null) {\n         headers.put(HttpHeaders.CACHE_CONTROL, md.getContentMetadata().getCacheControl());\n      }\n\n      if (md.getContentMetadata().getContentDisposition() != null) {\n         headers.put(\"Content-Disposition\", md.getContentMetadata().getContentDisposition());\n      }\n\n      if (md.getContentMetadata().getContentEncoding() != null) {\n         headers.put(\"Content-Encoding\", md.getContentMetadata().getContentEncoding());\n      }\n\n      String contentLanguage = md.getContentMetadata().getContentLanguage();\n      if (contentLanguage != null) {\n         headers.put(HttpHeaders.CONTENT_LANGUAGE, contentLanguage);\n      }\n\n      if (md.getContentMetadata().getContentType() != null) {\n         headers.put(HttpHeaders.CONTENT_TYPE, md.getContentMetadata().getContentType());\n      } else {\n         headers.put(HttpHeaders.CONTENT_TYPE, \"binary/octet-stream\");\n      }\n\n      if (md.getContentMetadata().getContentMD5() != null) {\n         headers.put(\"Content-MD5\", base64().encode(md.getContentMetadata().getContentMD5()));\n      }\n\n      ObjectMetadata.StorageClass storageClass = md.getStorageClass();\n      if (storageClass != ObjectMetadata.StorageClass.STANDARD) {\n         headers.put(\"x-amz-storage-class\", storageClass.toString());\n      }\n\n      return (R) request.toBuilder().replaceHeaders(headers.build()).build();\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/binders/BindOwnershipControlsToXMLPayload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.binders;\n\nimport static org.jclouds.s3.binders.XMLHelper.asString;\nimport static org.jclouds.s3.binders.XMLHelper.createDocument;\nimport static org.jclouds.s3.binders.XMLHelper.elem;\nimport static org.jclouds.s3.binders.XMLHelper.elemWithText;\n\nimport jakarta.inject.Singleton;\nimport jakarta.ws.rs.core.MediaType;\nimport javax.xml.parsers.FactoryConfigurationError;\nimport javax.xml.parsers.ParserConfigurationException;\nimport javax.xml.transform.TransformerException;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\nimport org.jclouds.s3.reference.S3Constants;\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\n\nimport com.google.common.base.Throwables;\n\n@Singleton\npublic final class BindOwnershipControlsToXMLPayload implements Binder {\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object payload) {\n      String from = (String) payload;\n      try {\n         request.setPayload(generatePayload(from));\n         request.getPayload().getContentMetadata().setContentType(MediaType.TEXT_XML);\n         return request;\n      } catch (Exception e) {\n         Throwables.propagateIfPossible(e);\n         throw new RuntimeException(\"error transforming acl: \" + from, e);\n      }\n   }\n\n   protected String generatePayload(String objectOwnership)\n         throws ParserConfigurationException, FactoryConfigurationError, TransformerException {\n      Document document = createDocument();\n      Element rootNode = elem(document, \"OwnershipControls\", document);\n      rootNode.setAttribute(\"xmlns\", S3Constants.S3_REST_API_XML_NAMESPACE);\n      Element ruleNode = elem(rootNode, \"Rule\", document);\n      elemWithText(ruleNode, \"ObjectOwnership\", objectOwnership, document);\n      return asString(document);\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/binders/BindPartIdsAndETagsToRequest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\nimport java.util.Map.Entry;\n\nimport jakarta.inject.Singleton;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.rest.Binder;\n\n@Singleton\npublic class BindPartIdsAndETagsToRequest implements Binder {\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkArgument(checkNotNull(input, \"input\") instanceof Map, \"this binder is only valid for Map!\");\n      checkNotNull(request, \"request\");\n\n      Map<Integer, String> map = (Map<Integer, String>) input;\n      checkArgument(!map.isEmpty(), \"Please send parts\");\n      StringBuilder content = new StringBuilder();\n      content.append(\"<CompleteMultipartUpload>\");\n      for (Entry<Integer, String> entry : map.entrySet()) {\n         content.append(\"<Part>\");\n         content.append(\"<PartNumber>\").append(entry.getKey()).append(\"</PartNumber>\");\n         content.append(\"<ETag>\").append(entry.getValue()).append(\"</ETag>\");\n         content.append(\"</Part>\");\n      }\n      content.append(\"</CompleteMultipartUpload>\");\n      Payload payload = Payloads.newStringPayload(content.toString());\n      payload.getContentMetadata().setContentType(MediaType.TEXT_XML);\n      request.setPayload(payload);\n      return request;\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/binders/BindPayerToXmlPayload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Singleton;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\nimport org.jclouds.s3.domain.Payer;\n\n@Singleton\npublic class BindPayerToXmlPayload implements Binder {\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object toBind) {\n      checkArgument(checkNotNull(toBind, \"toBind\") instanceof Payer, \"this binder is only valid for Payer!\");\n      String text = String\n            .format(\n                  \"<RequestPaymentConfiguration xmlns=\\\"http://s3.amazonaws.com/doc/2006-03-01/\\\"><Payer>%s</Payer></RequestPaymentConfiguration>\",\n                  ((Payer) toBind).value());\n      request.setPayload(text);\n      request.getPayload().getContentMetadata().setContentType(MediaType.TEXT_XML);\n      return request;\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/binders/BindPublicAccessBlockConfigurationToXMLPayload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.binders;\n\nimport static org.jclouds.s3.binders.XMLHelper.asString;\nimport static org.jclouds.s3.binders.XMLHelper.createDocument;\nimport static org.jclouds.s3.binders.XMLHelper.elem;\nimport static org.jclouds.s3.binders.XMLHelper.elemWithText;\n\nimport jakarta.inject.Singleton;\nimport jakarta.ws.rs.core.MediaType;\nimport javax.xml.parsers.FactoryConfigurationError;\nimport javax.xml.parsers.ParserConfigurationException;\nimport javax.xml.transform.TransformerException;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\nimport org.jclouds.s3.domain.PublicAccessBlockConfiguration;\nimport org.jclouds.s3.reference.S3Constants;\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\n\nimport com.google.common.base.Throwables;\n\n@Singleton\npublic final class BindPublicAccessBlockConfigurationToXMLPayload implements Binder {\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object payload) {\n      PublicAccessBlockConfiguration configuration = (PublicAccessBlockConfiguration) payload;\n      try {\n         request.setPayload(generatePayload(configuration));\n         request.getPayload().getContentMetadata().setContentType(MediaType.TEXT_XML);\n         return request;\n      } catch (Exception e) {\n         Throwables.propagateIfPossible(e);\n         throw new RuntimeException(\"error transforming configuration: \" + configuration, e);\n      }\n   }\n\n   protected String generatePayload(PublicAccessBlockConfiguration configuration)\n         throws ParserConfigurationException, FactoryConfigurationError, TransformerException {\n      Document document = createDocument();\n      Element rootNode = elem(document, \"PublicAccessBlockConfiguration\", document);\n      rootNode.setAttribute(\"xmlns\", S3Constants.S3_REST_API_XML_NAMESPACE);\n      elemWithText(rootNode, \"BlockPublicAcls\", String.valueOf(configuration.blockPublicAcls()), document);\n      elemWithText(rootNode, \"IgnorePublicAcls\", String.valueOf(configuration.ignorePublicAcls()), document);\n      elemWithText(rootNode, \"BlockPublicPolicy\", String.valueOf(configuration.blockPublicPolicy()), document);\n      elemWithText(rootNode, \"RestrictPublicBuckets\", String.valueOf(configuration.restrictPublicBuckets()), document);\n      return asString(document);\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/binders/BindS3ObjectMetadataToRequest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.blobstore.binders.BindMapToHeadersWithPrefix;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\nimport org.jclouds.s3.domain.ObjectMetadata.StorageClass;\nimport org.jclouds.s3.domain.S3Object;\n\n@Singleton\npublic class BindS3ObjectMetadataToRequest implements Binder {\n   protected final BindMapToHeadersWithPrefix metadataPrefixer;\n\n   @Inject\n   public BindS3ObjectMetadataToRequest(BindMapToHeadersWithPrefix metadataPrefixer) {\n      this.metadataPrefixer = checkNotNull(metadataPrefixer, \"metadataPrefixer\");\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkArgument(checkNotNull(input, \"input\") instanceof S3Object, \"this binder is only valid for S3Object!, not %s\", input);\n      checkNotNull(request, \"request\");\n\n      S3Object s3Object = S3Object.class.cast(input);\n      checkArgument(s3Object.getMetadata().getKey() != null, \"s3Object.getMetadata().getKey() must be set!\");\n      checkArgument(s3Object.getPayload().getContentMetadata().getContentLength() != null,\n            \"contentLength must be set, streaming not supported\");\n      checkArgument(s3Object.getPayload().getContentMetadata().getContentLength() <= 5L * 1024 * 1024 * 1024,\n            \"maximum size for put object is 5GB\");\n\n      StorageClass storageClass = s3Object.getMetadata().getStorageClass();\n      if (storageClass != StorageClass.STANDARD) {\n         request = (R) request.toBuilder()\n               .replaceHeader(\"x-amz-storage-class\", storageClass.toString())\n               .build();\n      }\n\n      request = metadataPrefixer.bindToRequest(request, s3Object.getMetadata().getUserMetadata());\n\n      return request;\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/binders/XMLHelper.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.binders;\n\nimport java.io.StringWriter;\n\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.parsers.FactoryConfigurationError;\nimport javax.xml.parsers.ParserConfigurationException;\nimport javax.xml.transform.OutputKeys;\nimport javax.xml.transform.Transformer;\nimport javax.xml.transform.TransformerException;\nimport javax.xml.transform.TransformerFactory;\nimport javax.xml.transform.dom.DOMSource;\nimport javax.xml.transform.stream.StreamResult;\n\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\nimport org.w3c.dom.Node;\n\nfinal class XMLHelper {\n   static Document createDocument()\n         throws ParserConfigurationException, FactoryConfigurationError {\n      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\n      factory.setNamespaceAware(true);\n      disableExternalEntityParsing(factory);\n      return factory.newDocumentBuilder().newDocument();\n   }\n\n   /**\n    * Explicitly enable or disable the 'external-general-entities' and\n    * 'external-parameter-entities' features of the underlying\n    * DocumentBuilderFactory.\n    *\n    * TODO This is a naive approach that simply tries to apply all known\n    * feature name/URL values in turn until one succeeds, or none do.\n    *\n    * @param factory\n    * factory which will have external general and parameter entities enabled\n    * or disabled.\n    */\n   private static void disableExternalEntityParsing(DocumentBuilderFactory factory) {\n      // Feature list drawn from:\n      // https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing\n\n      /* Enable or disable external general entities */\n      String[] externalGeneralEntitiesFeatures = {\n            // General\n            \"http://xml.org/sax/features/external-general-entities\",\n            // Xerces 1\n            \"http://xerces.apache.org/xerces-j/features.html#external-general-entities\",\n            // Xerces 2\n            \"http://xerces.apache.org/xerces2-j/features.html#external-general-entities\",\n      };\n      disableFeatures(factory, externalGeneralEntitiesFeatures);\n\n      /* Enable or disable external parameter entities */\n      String[] externalParameterEntitiesFeatures = {\n            // General\n            \"http://xml.org/sax/features/external-parameter-entities\",\n            // Xerces 1\n            \"http://xerces.apache.org/xerces-j/features.html#external-parameter-entities\",\n            // Xerces 2\n            \"http://xerces.apache.org/xerces2-j/features.html#external-parameter-entities\",\n      };\n      disableFeatures(factory, externalParameterEntitiesFeatures);\n   }\n\n   private static void disableFeatures(DocumentBuilderFactory factory, String[] features) {\n      for (String feature : features) {\n         try {\n            factory.setFeature(feature, false);\n            break;\n         } catch (ParserConfigurationException e) {\n         }\n      }\n   }\n\n   static void elemWithText(Element node, String name, String text, Document document) {\n      text(elem(node, name, document),\n           text,\n           document);\n   }\n\n   static Element elem(Node node, String name, Document document) {\n      Element newNode = document.createElement(name);\n      node.appendChild(newNode);\n      return newNode;\n   }\n\n   private static void text(Element node, String value, Document document) {\n      if (value == null) {\n          // null text values cause exceptions on subsequent call to\n          // Transformer to render document, so fail-fast here on bad data.\n          throw new IllegalArgumentException(\"Illegal null text value\");\n      }\n      node.appendChild(document.createTextNode(value));\n   }\n\n   /** Serializes the XML document into a string. */\n   static String asString(Document document) throws TransformerException {\n      StringWriter writer = new StringWriter();\n      Transformer serializer = TransformerFactory.newInstance().newTransformer();\n      serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, \"yes\");\n      serializer.transform(new DOMSource(document), new StreamResult(writer));\n      return writer.toString();\n   }\n}\n\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/blobstore/S3BlobRequestSigner.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.blobstore;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.blobstore.util.BlobStoreUtils.cleanRequest;\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.blobstore.BlobRequestSigner;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.functions.BlobToHttpGetOptions;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.options.GetOptions;\nimport org.jclouds.reflect.Invocation;\nimport org.jclouds.rest.internal.RestAnnotationProcessor;\nimport org.jclouds.s3.S3Client;\nimport org.jclouds.s3.blobstore.functions.BlobToObject;\nimport org.jclouds.s3.domain.S3Object;\nimport org.jclouds.s3.filters.RequestAuthorizeSignature;\nimport org.jclouds.s3.options.PutObjectOptions;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.reflect.Invokable;\n\n@Singleton\npublic class S3BlobRequestSigner<T extends S3Client> implements BlobRequestSigner {\n   /** Matches Amazon default when Expiry parameter not present. */\n   private static final int DEFAULT_EXPIRY_SECONDS = 15 * 60;\n\n   private final RequestAuthorizeSignature authSigner;\n\n   protected final RestAnnotationProcessor processor;\n   protected final BlobToObject blobToObject;\n   protected final BlobToHttpGetOptions blob2HttpGetOptions;\n\n   protected final Invokable<?, ?> getMethod;\n   protected final Invokable<?, ?> deleteMethod;\n   protected final Invokable<?, ?> createMethod;\n\n   @Inject\n   public S3BlobRequestSigner(RestAnnotationProcessor processor, BlobToObject blobToObject,\n         BlobToHttpGetOptions blob2HttpGetOptions, Class<T> interfaceClass,\n         RequestAuthorizeSignature authSigner)\n         throws SecurityException, NoSuchMethodException {\n      this.processor = checkNotNull(processor, \"processor\");\n      this.blobToObject = checkNotNull(blobToObject, \"blobToObject\");\n      this.blob2HttpGetOptions = checkNotNull(blob2HttpGetOptions, \"blob2HttpGetOptions\");\n      this.getMethod = method(interfaceClass, \"getObject\", String.class, String.class, GetOptions[].class);\n      this.deleteMethod = method(interfaceClass, \"deleteObject\", String.class, String.class);\n      this.createMethod = method(interfaceClass, \"putObject\", String.class, S3Object.class, PutObjectOptions[].class);\n      this.authSigner = authSigner;\n   }\n\n   @Override\n   public HttpRequest signGetBlob(String container, String name) {\n      return signGetBlob(container, name, DEFAULT_EXPIRY_SECONDS);\n   }\n\n   @Override\n   public HttpRequest signGetBlob(String container, String name, long timeInSeconds) {\n      checkNotNull(container, \"container\");\n      checkNotNull(name, \"name\");\n      HttpRequest request = processor.apply(Invocation.create(getMethod, ImmutableList.<Object> of(container, name)));\n      return cleanRequest(authSigner.signForTemporaryAccess(request, timeInSeconds));\n   }\n\n   @Override\n   public HttpRequest signPutBlob(String container, Blob blob) {\n      return signPutBlob(container, blob, DEFAULT_EXPIRY_SECONDS);\n   }\n\n   @Override\n   public HttpRequest signPutBlob(String container, Blob blob, long timeInSeconds) {\n      checkNotNull(container, \"container\");\n      checkNotNull(blob, \"blob\");\n      HttpRequest request = processor.apply(Invocation.create(createMethod,\n         ImmutableList.<Object>of(container, blobToObject.apply(blob))));\n      return cleanRequest(authSigner.signForTemporaryAccess(request, timeInSeconds));\n   }\n\n   @Override\n   public HttpRequest signGetBlob(String container, String name, org.jclouds.blobstore.options.GetOptions options) {\n      checkNotNull(container, \"container\");\n      checkNotNull(name, \"name\");\n      return cleanRequest(processor.apply(Invocation.create(getMethod,\n            ImmutableList.of(container, name, blob2HttpGetOptions.apply(checkNotNull(options, \"options\"))))));\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/blobstore/S3BlobStore.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.blobstore;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static org.jclouds.util.Predicates2.retry;\n\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Provider;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.blobstore.BlobStoreContext;\nimport org.jclouds.blobstore.ContainerNotFoundException;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.BlobAccess;\nimport org.jclouds.blobstore.domain.BlobMetadata;\nimport org.jclouds.blobstore.domain.ContainerAccess;\nimport org.jclouds.blobstore.domain.MultipartPart;\nimport org.jclouds.blobstore.domain.MultipartUpload;\nimport org.jclouds.blobstore.domain.PageSet;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.functions.BlobToHttpGetOptions;\nimport org.jclouds.blobstore.internal.BaseBlobStore;\nimport org.jclouds.blobstore.options.CopyOptions;\nimport org.jclouds.blobstore.options.CreateContainerOptions;\nimport org.jclouds.blobstore.options.ListContainerOptions;\nimport org.jclouds.blobstore.options.PutOptions;\nimport org.jclouds.blobstore.strategy.internal.FetchBlobMetadata;\nimport org.jclouds.blobstore.util.BlobUtils;\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.domain.Location;\nimport org.jclouds.http.options.GetOptions;\nimport org.jclouds.io.ContentMetadata;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.PayloadSlicer;\nimport org.jclouds.s3.S3Client;\nimport org.jclouds.s3.blobstore.functions.BlobToObject;\nimport org.jclouds.s3.blobstore.functions.BlobToObjectMetadata;\nimport org.jclouds.s3.blobstore.functions.BucketToResourceList;\nimport org.jclouds.s3.blobstore.functions.ContainerToBucketListOptions;\nimport org.jclouds.s3.blobstore.functions.ObjectToBlob;\nimport org.jclouds.s3.blobstore.functions.ObjectToBlobMetadata;\nimport org.jclouds.s3.domain.AccessControlList;\nimport org.jclouds.s3.domain.AccessControlList.GroupGranteeURI;\nimport org.jclouds.s3.domain.AccessControlList.Permission;\nimport org.jclouds.s3.domain.BucketMetadata;\nimport org.jclouds.s3.domain.CannedAccessPolicy;\nimport org.jclouds.s3.domain.ListMultipartUploadResponse;\nimport org.jclouds.s3.domain.ListMultipartUploadsResponse;\nimport org.jclouds.s3.options.CopyObjectOptions;\nimport org.jclouds.s3.options.ListBucketOptions;\nimport org.jclouds.s3.options.PutBucketOptions;\nimport org.jclouds.s3.options.PutObjectOptions;\nimport org.jclouds.s3.util.S3Utils;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\n\n@Singleton\npublic class S3BlobStore extends BaseBlobStore {\n   private final S3Client sync;\n   private final Function<Set<BucketMetadata>, PageSet<? extends StorageMetadata>> convertBucketsToStorageMetadata;\n   private final ContainerToBucketListOptions container2BucketListOptions;\n   private final BucketToResourceList bucket2ResourceList;\n   private final ObjectToBlob object2Blob;\n   private final BlobToObject blob2Object;\n   private final ObjectToBlobMetadata object2BlobMd;\n   private final BlobToObjectMetadata blob2ObjectMetadata;\n   private final BlobToHttpGetOptions blob2ObjectGetOptions;\n   private final Provider<FetchBlobMetadata> fetchBlobMetadataProvider;\n\n   @Inject\n   protected S3BlobStore(BlobStoreContext context, BlobUtils blobUtils, Supplier<Location> defaultLocation,\n            @Memoized Supplier<Set<? extends Location>> locations, PayloadSlicer slicer, S3Client sync,\n            Function<Set<BucketMetadata>, PageSet<? extends StorageMetadata>> convertBucketsToStorageMetadata,\n            ContainerToBucketListOptions container2BucketListOptions, BucketToResourceList bucket2ResourceList,\n            ObjectToBlob object2Blob, BlobToHttpGetOptions blob2ObjectGetOptions, BlobToObject blob2Object,\n            BlobToObjectMetadata blob2ObjectMetadata,\n            ObjectToBlobMetadata object2BlobMd, Provider<FetchBlobMetadata> fetchBlobMetadataProvider) {\n      super(context, blobUtils, defaultLocation, locations, slicer);\n      this.blob2ObjectGetOptions = checkNotNull(blob2ObjectGetOptions, \"blob2ObjectGetOptions\");\n      this.sync = checkNotNull(sync, \"sync\");\n      this.convertBucketsToStorageMetadata = checkNotNull(convertBucketsToStorageMetadata, \"convertBucketsToStorageMetadata\");\n      this.container2BucketListOptions = checkNotNull(container2BucketListOptions, \"container2BucketListOptions\");\n      this.bucket2ResourceList = checkNotNull(bucket2ResourceList, \"bucket2ResourceList\");\n      this.object2Blob = checkNotNull(object2Blob, \"object2Blob\");\n      this.blob2Object = checkNotNull(blob2Object, \"blob2Object\");\n      this.object2BlobMd = checkNotNull(object2BlobMd, \"object2BlobMd\");\n      this.blob2ObjectMetadata = checkNotNull(blob2ObjectMetadata, \"blob2ObjectMetadata\");\n      this.fetchBlobMetadataProvider = checkNotNull(fetchBlobMetadataProvider, \"fetchBlobMetadataProvider\");\n   }\n\n   /**\n    * This implementation invokes {@link S3Client#listOwnedBuckets}\n    */\n   @Override\n   public PageSet<? extends StorageMetadata> list() {\n      return convertBucketsToStorageMetadata.apply(sync.listOwnedBuckets());\n   }\n\n   /**\n    * This implementation invokes {@link S3Client#bucketExists}\n    *\n    * @param container\n    *           bucket name\n    */\n   @Override\n   public boolean containerExists(String container) {\n      return sync.bucketExists(container);\n   }\n\n   /**\n    * This implementation invokes {@link S3Client#putBucketInRegion}\n    *\n    * @param location\n    *           corresponds to a Region\n    * @param container\n    *           bucket name\n    */\n   @Override\n   public boolean createContainerInLocation(Location location, String container) {\n      return createContainerInLocation(location, container, CreateContainerOptions.NONE);\n   }\n\n   @Override\n   public ContainerAccess getContainerAccess(String container) {\n      AccessControlList acl = sync.getBucketACL(container);\n      if (acl.hasPermission(GroupGranteeURI.ALL_USERS, Permission.READ)) {\n         return ContainerAccess.PUBLIC_READ;\n      } else {\n         return ContainerAccess.PRIVATE;\n      }\n   }\n\n   @Override\n   public void setContainerAccess(String container, ContainerAccess access) {\n      CannedAccessPolicy acl = CannedAccessPolicy.PRIVATE;\n      if (access == ContainerAccess.PUBLIC_READ) {\n         acl = CannedAccessPolicy.PUBLIC_READ;\n      }\n      sync.updateBucketCannedACL(container, acl);\n   }\n\n   /**\n    * This implementation invokes {@link S3Client#listBucket}\n    *\n    * @param container\n    *           bucket name\n    */\n   @Override\n   public PageSet<? extends StorageMetadata> list(String container, ListContainerOptions options) {\n      ListBucketOptions httpOptions = container2BucketListOptions.apply(options);\n      PageSet<? extends StorageMetadata> list = bucket2ResourceList.apply(sync.listBucket(container, httpOptions));\n      return options.isDetailed() ? fetchBlobMetadataProvider.get().setContainerName(container).apply(list) : list;\n   }\n\n   /**\n    * This implementation invokes {@link #clearContainer} then {@link S3Client#deleteBucketIfEmpty} until it is true.\n    */\n   @Override\n   protected void deletePathAndEnsureGone(String path) {\n      checkState(retry(new Predicate<String>() {\n         public boolean apply(String in) {\n            try {\n               clearContainer(in);\n               return sync.deleteBucketIfEmpty(in);\n            } catch (ContainerNotFoundException e) {\n               return true;\n            }\n         }\n      }, 30000).apply(path), \"%s still exists after deleting!\", path);\n   }\n\n   /**\n    * This implementation invokes {@link S3Client#objectExists}\n    *\n    * @param container\n    *           bucket name\n    * @param key\n    *           object key\n    */\n   @Override\n   public boolean blobExists(String container, String key) {\n      return sync.objectExists(container, key);\n   }\n\n   /**\n    * This implementation invokes {@link S3Client#headObject}\n    *\n    * @param container\n    *           bucket name\n    * @param key\n    *           object key\n    */\n   @Override\n   public BlobMetadata blobMetadata(String container, String key) {\n      return object2BlobMd.apply(sync.headObject(container, key));\n   }\n\n   /**\n    * This implementation invokes {@link S3Client#getObject}\n    *\n    * @param container\n    *           bucket name\n    * @param key\n    *           object key\n    */\n   @Override\n   public Blob getBlob(String container, String key, org.jclouds.blobstore.options.GetOptions optionsList) {\n      GetOptions httpOptions = blob2ObjectGetOptions.apply(optionsList);\n      return object2Blob.apply(sync.getObject(container, key, httpOptions));\n   }\n\n   /**\n    * This implementation invokes {@link S3Client#putObject}\n    *\n    * @param container\n    *           bucket name\n    * @param blob\n    *           object\n    */\n   @Override\n   public String putBlob(String container, Blob blob) {\n      return putBlob(container, blob, PutOptions.NONE);\n   }\n\n   /**\n    * This implementation invokes {@link S3Client#putObject}\n    *\n    * @param container\n    *           bucket name\n    * @param blob\n    *           object\n    */\n   @Override\n   public String putBlob(String container, Blob blob, PutOptions overrides) {\n      if (overrides.isMultipart()) {\n         return putMultipartBlob(container, blob, overrides);\n      }\n\n      PutObjectOptions options = new PutObjectOptions();\n      if (overrides.getBlobAccess() == BlobAccess.PUBLIC_READ) {\n         options = options.withAcl(CannedAccessPolicy.PUBLIC_READ);\n      }\n      return sync.putObject(container, blob2Object.apply(blob), options);\n   }\n\n   @Override\n   public String copyBlob(String fromContainer, String fromName, String toContainer, String toName,\n         CopyOptions options) {\n      CopyObjectOptions s3Options = new CopyObjectOptions();\n      if (options.ifMatch() != null) {\n         s3Options.ifSourceETagMatches(options.ifMatch());\n      }\n      if (options.ifNoneMatch() != null) {\n         s3Options.ifSourceETagDoesntMatch(options.ifNoneMatch());\n      }\n      if (options.ifModifiedSince() != null) {\n         s3Options.ifSourceModifiedSince(options.ifModifiedSince());\n      }\n      if (options.ifUnmodifiedSince() != null) {\n         s3Options.ifSourceUnmodifiedSince(options.ifUnmodifiedSince());\n      }\n\n      ContentMetadata contentMetadata = options.contentMetadata();\n      if (contentMetadata != null) {\n         String cacheControl = contentMetadata.getCacheControl();\n         if (cacheControl != null) {\n            s3Options.cacheControl(cacheControl);\n         }\n\n         String contentDisposition = contentMetadata.getContentDisposition();\n         if (contentDisposition != null) {\n            s3Options.contentDisposition(contentDisposition);\n         }\n\n         String contentEncoding = contentMetadata.getContentEncoding();\n         if (contentEncoding != null) {\n            s3Options.contentEncoding(contentEncoding);\n         }\n\n         String contentLanguage = contentMetadata.getContentLanguage();\n         if (contentLanguage != null) {\n            s3Options.contentLanguage(contentLanguage);\n         }\n\n         String contentType = contentMetadata.getContentType();\n         if (contentType != null) {\n            s3Options.contentType(contentType);\n         }\n      }\n\n      Map<String, String> userMetadata = options.userMetadata();\n      if (userMetadata != null) {\n         s3Options.overrideMetadataWith(userMetadata);\n      }\n\n      return sync.copyObject(fromContainer, fromName, toContainer, toName, s3Options).getETag();\n   }\n\n   /**\n    * This implementation invokes {@link S3Client#deleteObject}\n    *\n    * @param container\n    *           bucket name\n    * @param key\n    *           object key\n    */\n   @Override\n   public void removeBlob(String container, String key) {\n      sync.deleteObject(container, key);\n   }\n\n   @Override\n   public void removeBlobs(String container, Iterable<String> keys) {\n      for (List<String> partition : Iterables.partition(keys, 1000)) {\n         sync.deleteObjects(container, partition);\n      }\n   }\n\n   @Override\n   public BlobAccess getBlobAccess(String container, String name) {\n      AccessControlList acl = sync.getObjectACL(container, name);\n      if (acl.hasPermission(GroupGranteeURI.ALL_USERS, Permission.READ)) {\n         return BlobAccess.PUBLIC_READ;\n      } else {\n         return BlobAccess.PRIVATE;\n      }\n   }\n\n   @Override\n   public void setBlobAccess(String container, String name, BlobAccess access) {\n      CannedAccessPolicy acl = CannedAccessPolicy.PRIVATE;\n      if (access == BlobAccess.PUBLIC_READ) {\n         acl = CannedAccessPolicy.PUBLIC_READ;\n      }\n      sync.updateObjectCannedACL(container, name, acl);\n   }\n\n   @Override\n   public MultipartUpload initiateMultipartUpload(String container, BlobMetadata blobMetadata, PutOptions overrides) {\n      PutObjectOptions options = new PutObjectOptions();\n      if (overrides.getBlobAccess() == BlobAccess.PUBLIC_READ) {\n         options = options.withAcl(CannedAccessPolicy.PUBLIC_READ);\n      }\n      String id = sync.initiateMultipartUpload(container, blob2ObjectMetadata.apply(blobMetadata), options);\n      return MultipartUpload.create(container, blobMetadata.getName(), id, blobMetadata, overrides);\n   }\n\n   @Override\n   public void abortMultipartUpload(MultipartUpload mpu) {\n      sync.abortMultipartUpload(mpu.containerName(), mpu.blobName(), mpu.id());\n   }\n\n   @Override\n   public String completeMultipartUpload(MultipartUpload mpu, List<MultipartPart> parts) {\n      ImmutableMap.Builder<Integer, String> builder = ImmutableMap.builder();\n      for (MultipartPart part : parts) {\n         builder.put(part.partNumber(), part.partETag());\n      }\n      return sync.completeMultipartUpload(mpu.containerName(), mpu.blobName(), mpu.id(), builder.build());\n   }\n\n   @Override\n   public MultipartPart uploadMultipartPart(MultipartUpload mpu, int partNumber, Payload payload) {\n      long partSize = payload.getContentMetadata().getContentLength();\n      String eTag = sync.uploadPart(mpu.containerName(), mpu.blobName(), partNumber, mpu.id(), payload);\n      Date lastModified = null;  // S3 does not return Last-Modified\n      return MultipartPart.create(partNumber, partSize, eTag, lastModified);\n   }\n\n   @Override\n   public List<MultipartPart> listMultipartUpload(MultipartUpload mpu) {\n      ImmutableList.Builder<MultipartPart> parts = ImmutableList.builder();\n      Map<Integer, ListMultipartUploadResponse> s3Parts = sync.listMultipartPartsFull(mpu.containerName(), mpu.blobName(), mpu.id());\n      for (Map.Entry<Integer, ListMultipartUploadResponse> entry : s3Parts.entrySet()) {\n         ListMultipartUploadResponse response = entry.getValue();\n         parts.add(MultipartPart.create(entry.getKey(), response.size(), response.eTag(), response.lastModified()));\n      }\n      return parts.build();\n   }\n\n   @Override\n   public List<MultipartUpload> listMultipartUploads(String container) {\n      ImmutableList.Builder<MultipartUpload> builder = ImmutableList.builder();\n      String keyMarker = null;\n      String uploadIdMarker = null;\n      while (true) {\n         ListMultipartUploadsResponse response = sync.listMultipartUploads(container, null, null, keyMarker, null, uploadIdMarker);\n         for (ListMultipartUploadsResponse.Upload upload : response.uploads()) {\n            builder.add(MultipartUpload.create(container, upload.key(), upload.uploadId(), null, null));\n         }\n         keyMarker = response.keyMarker();\n         uploadIdMarker = response.uploadIdMarker();\n         if (response.uploads().isEmpty() || keyMarker == null || uploadIdMarker == null) {\n            break;\n         }\n      }\n      return builder.build();\n   }\n\n   @Override\n   public long getMinimumMultipartPartSize() {\n      return 5 * 1024 * 1024;\n   }\n\n   @Override\n   public long getMaximumMultipartPartSize() {\n      return 5L * 1024L * 1024L * 1024L;\n   }\n\n   @Override\n   public int getMaximumNumberOfParts() {\n      return 10 * 1000;\n   }\n\n   /**\n    * This implementation invokes {@link S3Utils#deleteAndVerifyContainerGone}\n    */\n   protected boolean deleteAndVerifyContainerGone(final String container) {\n      return S3Utils.deleteAndVerifyContainerGone(sync, container);\n   }\n\n   @Override\n   public boolean createContainerInLocation(Location location, String container, CreateContainerOptions options) {\n      PutBucketOptions putBucketOptions = new PutBucketOptions();\n      if (options.isPublicRead())\n         putBucketOptions.withBucketAcl(CannedAccessPolicy.PUBLIC_READ);\n      location = location != null ? location : defaultLocation.get();\n      return sync.putBucketInRegion(location.getId(), container, putBucketOptions);\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/blobstore/S3BlobStoreContext.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.blobstore;\n\nimport org.jclouds.blobstore.BlobStoreContext;\nimport org.jclouds.s3.blobstore.internal.S3BlobStoreContextImpl;\n\nimport com.google.inject.ImplementedBy;\n\n@ImplementedBy(S3BlobStoreContextImpl.class)\npublic interface S3BlobStoreContext extends BlobStoreContext {\n\n   @Override\n   S3BlobStore getBlobStore();\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/blobstore/config/S3BlobStoreContextModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.blobstore.config;\n\nimport static com.google.inject.Scopes.SINGLETON;\n\nimport java.util.concurrent.TimeUnit;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.blobstore.BlobRequestSigner;\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.attr.ConsistencyModel;\nimport org.jclouds.domain.Location;\nimport org.jclouds.s3.S3Client;\nimport org.jclouds.s3.blobstore.S3BlobRequestSigner;\nimport org.jclouds.s3.blobstore.S3BlobStore;\nimport org.jclouds.s3.blobstore.functions.LocationFromBucketName;\nimport org.jclouds.s3.blobstore.internal.BackoffOnNotFoundWhenGetBucketACL;\nimport org.jclouds.s3.domain.AccessControlList;\n\nimport com.google.common.base.Function;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.LoadingCache;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Provides;\nimport com.google.inject.TypeLiteral;\n\npublic class S3BlobStoreContextModule extends AbstractModule {\n\n   @Override\n   protected void configure() {\n      bind(ConsistencyModel.class).toInstance(ConsistencyModel.EVENTUAL);\n      bind(BlobStore.class).to(S3BlobStore.class).in(SINGLETON);\n      bind(new TypeLiteral<Function<String, Location>>() {\n      }).to(LocationFromBucketName.class);\n      bindRequestSigner();\n   }\n\n   protected void bindRequestSigner() {\n      bind(BlobRequestSigner.class).to(new TypeLiteral<S3BlobRequestSigner<S3Client>>() {\n      });\n   }\n\n   @Provides\n   @Singleton\n   protected final LoadingCache<String, AccessControlList> bucketAcls(BackoffOnNotFoundWhenGetBucketACL loader) {\n      return CacheBuilder.newBuilder().expireAfterWrite(30, TimeUnit.SECONDS).build(loader);\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/blobstore/functions/BlobToObject.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.blobstore.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.s3.domain.S3Object;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class BlobToObject implements Function<Blob, S3Object> {\n   private final BlobToObjectMetadata blob2ObjectMd;\n   private final S3Object.Factory objectProvider;\n\n   @Inject\n   BlobToObject(BlobToObjectMetadata blob2ObjectMd, S3Object.Factory objectProvider) {\n      this.blob2ObjectMd = blob2ObjectMd;\n      this.objectProvider = objectProvider;\n   }\n\n   public S3Object apply(Blob from) {\n      if (from == null)\n         return null;\n      S3Object object = objectProvider.create(blob2ObjectMd.apply(from.getMetadata()));\n      object.setPayload(checkNotNull(from.getPayload(), \"payload: \" + from));\n      object.setAllHeaders(from.getAllHeaders());\n      return object;\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/blobstore/functions/BlobToObjectMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.blobstore.functions;\n\nimport static com.google.common.base.Preconditions.checkArgument;\n\nimport java.util.Map.Entry;\n\nimport org.jclouds.blobstore.domain.BlobMetadata;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpUtils;\nimport org.jclouds.rest.InvocationContext;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.jclouds.s3.domain.MutableObjectMetadata;\nimport org.jclouds.s3.domain.ObjectMetadata.StorageClass;\nimport org.jclouds.s3.domain.internal.MutableObjectMetadataImpl;\n\nimport com.google.common.base.Function;\n\npublic class BlobToObjectMetadata implements Function<BlobMetadata, MutableObjectMetadata>,\n         InvocationContext<BlobToObjectMetadata> {\n   private String bucket;\n\n   public MutableObjectMetadata apply(BlobMetadata from) {\n      if (from == null)\n         return null;\n      MutableObjectMetadata to = new MutableObjectMetadataImpl();\n      HttpUtils.copy(from.getContentMetadata(), to.getContentMetadata());\n      to.setUri(from.getUri());\n      to.setETag(from.getETag());\n      to.setKey(from.getName());\n      to.setBucket(bucket);\n      to.setLastModified(from.getLastModified());\n      if (from.getUserMetadata() != null) {\n         for (Entry<String, String> entry : from.getUserMetadata().entrySet())\n            to.getUserMetadata().put(entry.getKey().toLowerCase(), entry.getValue());\n      }\n      if (from.getTier() != null) {\n         to.setStorageClass(StorageClass.fromTier(from.getTier()));\n      }\n      return to;\n   }\n\n   @Override\n   public BlobToObjectMetadata setContext(HttpRequest request) {\n      checkArgument(request instanceof GeneratedHttpRequest, \"note this handler requires a GeneratedHttpRequest\");\n      return setBucket(GeneratedHttpRequest.class.cast(request).getInvocation().getArgs().get(0).toString());\n   }\n\n   private BlobToObjectMetadata setBucket(String bucket) {\n      this.bucket = bucket;\n      return this;\n   }\n\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/blobstore/functions/BucketToResourceList.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.blobstore.functions;\n\nimport java.util.SortedSet;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.blobstore.domain.PageSet;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.domain.internal.PageSetImpl;\nimport org.jclouds.s3.domain.ListBucketResponse;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Sets;\n\n@Singleton\npublic class BucketToResourceList implements\n         Function<ListBucketResponse, PageSet<? extends StorageMetadata>> {\n   private final ObjectToBlobMetadata object2blobMd;\n   private final CommonPrefixesToResourceMetadata prefix2ResourceMd;\n\n   protected final Function<StorageMetadata, String> indexer = new Function<StorageMetadata, String>() {\n      @Override\n      public String apply(StorageMetadata from) {\n         return from.getName();\n      }\n   };\n\n   @Inject\n   public BucketToResourceList(ObjectToBlobMetadata object2blobMd,\n            CommonPrefixesToResourceMetadata prefix2ResourceMd) {\n      this.object2blobMd = object2blobMd;\n      this.prefix2ResourceMd = prefix2ResourceMd;\n   }\n\n   public PageSet<? extends StorageMetadata> apply(ListBucketResponse from) {\n      // S3 lists keys in sorted order; use sorted set to order relative paths correctly\n      SortedSet<StorageMetadata> contents = Sets.<StorageMetadata> newTreeSet(Iterables.transform(from,\n               object2blobMd));\n\n      for (String prefix : from.getCommonPrefixes()) {\n         contents.add(prefix2ResourceMd.apply(prefix));\n      }\n      return new PageSetImpl<StorageMetadata>(contents, from.getNextMarker());\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/blobstore/functions/BucketToResourceMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.blobstore.functions;\n\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.blobstore.domain.MutableStorageMetadata;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.domain.StorageType;\nimport org.jclouds.blobstore.domain.internal.MutableStorageMetadataImpl;\nimport org.jclouds.domain.Location;\nimport org.jclouds.s3.domain.BucketMetadata;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class BucketToResourceMetadata implements Function<BucketMetadata, StorageMetadata> {\n   private final Function<String, Location> locationOfBucket;\n\n   @Inject\n   BucketToResourceMetadata(Function<String, Location> locationOfBucket) {\n      this.locationOfBucket = locationOfBucket;\n   }\n\n   public StorageMetadata apply(BucketMetadata from) {\n      MutableStorageMetadata to = new MutableStorageMetadataImpl();\n      to.setName(from.getName());\n      to.setType(StorageType.CONTAINER);\n      to.setLocation(locationOfBucket.apply(from.getName()));\n      to.setCreationDate(from.getCreationDate());\n      return to;\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/blobstore/functions/BucketsToStorageMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.blobstore.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Set;\nimport java.util.concurrent.Callable;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Constants;\nimport org.jclouds.blobstore.domain.PageSet;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.domain.internal.PageSetImpl;\nimport org.jclouds.concurrent.FutureIterables;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.s3.domain.BucketMetadata;\n\nimport com.google.common.base.Function;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.ListeningExecutorService;\n\n@Singleton\npublic class BucketsToStorageMetadata implements\n         Function<Set<BucketMetadata>, PageSet<? extends StorageMetadata>> {\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n   \n   private final ListeningExecutorService userExecutor;\n   private final BucketToResourceMetadata bucket2ResourceMd;\n\n   @Inject\n   public BucketsToStorageMetadata(@Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor, BucketToResourceMetadata bucket2ResourceMd) {\n      this.userExecutor = checkNotNull(userExecutor, \"userExecutor\");\n      this.bucket2ResourceMd = checkNotNull(bucket2ResourceMd, \"bucket2ResourceMd\");\n   }\n\n\n   @Override\n   public PageSet<? extends StorageMetadata> apply(Set<BucketMetadata> input) {\n      // parallel as listing buckets is slow when looking up regions\n      Iterable<? extends StorageMetadata> buckets = FutureIterables\n               .<BucketMetadata, StorageMetadata> transformParallel(input,\n                        new Function<BucketMetadata, ListenableFuture<? extends StorageMetadata>>() {\n                           @Override\n                           public ListenableFuture<? extends StorageMetadata> apply(final BucketMetadata from) {\n                              return userExecutor.submit(new Callable<StorageMetadata>() {\n\n                                 @Override\n                                 public StorageMetadata call() throws Exception {\n                                    return bucket2ResourceMd.apply(from);\n                                 }\n\n                                 @Override\n                                 public String toString() {\n                                    return \"bucket2ResourceMd.apply(\" + from + \")\";\n                                 }\n                              });\n                           }\n\n                        }, userExecutor, null, logger, \"my buckets\");\n      return new PageSetImpl<StorageMetadata>(buckets, null);\n   }\n\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/blobstore/functions/CommonPrefixesToResourceMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.blobstore.functions;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.blobstore.domain.MutableStorageMetadata;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.domain.StorageType;\nimport org.jclouds.blobstore.domain.internal.MutableStorageMetadataImpl;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class CommonPrefixesToResourceMetadata implements Function<String, StorageMetadata> {\n\n   public StorageMetadata apply(String from) {\n      MutableStorageMetadata returnVal = new MutableStorageMetadataImpl();\n      returnVal.setType(StorageType.RELATIVE_PATH);\n      returnVal.setName(from);\n      return returnVal;\n   }\n\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/blobstore/functions/ContainerToBucketListOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.blobstore.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.blobstore.options.ListContainerOptions;\nimport org.jclouds.s3.options.ListBucketOptions;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class ContainerToBucketListOptions implements\n         Function<ListContainerOptions, ListBucketOptions> {\n   public ListBucketOptions apply(ListContainerOptions from) {\n      checkNotNull(from, \"set options to instance NONE instead of passing null\");\n      if (from.getPrefix() != null && from.getDir() != null) {\n         throw new IllegalArgumentException(\"Cannot set both directory and prefix options\");\n      }\n\n      ListBucketOptions httpOptions = new ListBucketOptions();\n      if (!from.isRecursive()) {\n         if (from.getDelimiter() != null) {\n            httpOptions.delimiter(from.getDelimiter().toString());\n         } else {\n            httpOptions.delimiter(\"/\");\n         }\n      }\n      if (from.getDir() != null) {// TODO unit test\n         String path = from.getDir();\n         if (from.getDelimiter() != null) {\n            if (!path.endsWith(from.getDelimiter().toString())) {\n               path += from.getDelimiter();\n            }\n         } else {\n            if (!path.endsWith(\"/\"))\n               path = path + \"/\";\n         }\n         httpOptions.withPrefix(path);\n      }\n      if (from.getPrefix() != null) {\n         httpOptions.withPrefix(from.getPrefix());\n      }\n      if (from.getMarker() != null) {\n         httpOptions.afterMarker(from.getMarker());\n      }\n      if (from.getMaxResults() != null) {\n         httpOptions.maxResults(from.getMaxResults());\n      }\n      return httpOptions;\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/blobstore/functions/LocationFromBucketName.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.blobstore.functions;\n\nimport static com.google.common.collect.Iterables.find;\nimport static com.google.common.collect.Iterables.get;\nimport static org.jclouds.location.predicates.LocationPredicates.idEquals;\n\nimport java.util.NoSuchElementException;\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.domain.Location;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.s3.Bucket;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Supplier;\n\n@Singleton\npublic class LocationFromBucketName implements Function<String, Location> {\n   private final Supplier<Set<? extends Location>> locations;\n   private final Function<String, Optional<String>> bucketToRegion;\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   @Inject\n   LocationFromBucketName(@Bucket Function<String, Optional<String>> bucketToRegion,\n            @Memoized Supplier<Set<? extends Location>> locations) {\n      this.bucketToRegion = bucketToRegion;\n      this.locations = locations;\n   }\n\n   public Location apply(String bucket) {\n      Set<? extends Location> locations = this.locations.get();\n      if (locations.size() == 1)\n         return get(locations, 0);\n      final Optional<String> region = bucketToRegion.apply(bucket);\n      if (region.isPresent()) {\n         try {\n            return find(locations, idEquals(region.get()));\n         } catch (NoSuchElementException e) {\n            logger.debug(\"could not get location for region %s in %s\", region, locations);\n         }\n      } else {\n         logger.debug(\"could not get region for %s\", bucket);\n      }\n      return null;\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/blobstore/functions/ObjectToBlob.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.blobstore.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.Blob.Factory;\nimport org.jclouds.s3.domain.S3Object;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class ObjectToBlob implements Function<S3Object, Blob> {\n   private final Factory blobFactory;\n   private final ObjectToBlobMetadata object2BlobMd;\n\n   @Inject\n   ObjectToBlob(Factory blobFactory, ObjectToBlobMetadata object2BlobMd) {\n      this.blobFactory = blobFactory;\n      this.object2BlobMd = object2BlobMd;\n   }\n\n   public Blob apply(S3Object from) {\n      if (from == null)\n         return null;\n      Blob blob = blobFactory.create(object2BlobMd.apply(from.getMetadata()));\n      blob.setPayload(checkNotNull(from.getPayload(), \"payload: \" + from));\n      blob.setAllHeaders(from.getAllHeaders());\n      return blob;\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/blobstore/functions/ObjectToBlobMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.blobstore.functions;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.blobstore.domain.MutableBlobMetadata;\nimport org.jclouds.blobstore.domain.StorageType;\nimport org.jclouds.blobstore.domain.internal.MutableBlobMetadataImpl;\nimport org.jclouds.domain.Location;\nimport org.jclouds.http.HttpUtils;\nimport org.jclouds.s3.domain.ObjectMetadata;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class ObjectToBlobMetadata implements Function<ObjectMetadata, MutableBlobMetadata> {\n   private final Function<String, Location> locationOfBucket;\n\n   @Inject\n   public ObjectToBlobMetadata(Function<String, Location> locationOfBucket) {\n      this.locationOfBucket = locationOfBucket;\n   }\n\n   public MutableBlobMetadata apply(ObjectMetadata from) {\n      if (from == null)\n         return null;\n      MutableBlobMetadata to = new MutableBlobMetadataImpl();\n      HttpUtils.copy(from.getContentMetadata(), to.getContentMetadata());\n      to.setUri(from.getUri());\n      to.setContainer(from.getBucket());\n      to.setETag(from.getETag());\n      to.setName(from.getKey());\n      to.setLastModified(from.getLastModified());\n      to.setUserMetadata(from.getUserMetadata());\n      to.setLocation(locationOfBucket.apply(from.getBucket()));\n      to.setType(StorageType.BLOB);\n      to.setSize(from.getContentMetadata().getContentLength());\n      to.setTier((from.getStorageClass() == null ? ObjectMetadata.StorageClass.STANDARD : from.getStorageClass()).toTier());\n      return to;\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/blobstore/internal/BackoffOnNotFoundWhenGetBucketACL.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.blobstore.internal;\n\nimport static com.google.common.base.Throwables.propagate;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.jclouds.s3.S3Client;\nimport org.jclouds.s3.domain.AccessControlList;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.cache.CacheLoader;\n\n\n@Beta\npublic class BackoffOnNotFoundWhenGetBucketACL extends CacheLoader<String, AccessControlList> {\n   private final S3Client client;\n   private static final int maxTries = 5;\n\n   @Inject\n   BackoffOnNotFoundWhenGetBucketACL(S3Client client) {\n      this.client = client;\n   }\n\n   @Override\n   public AccessControlList load(String bucketName) {\n      ResourceNotFoundException last = null;\n      for (int currentTries = 0; currentTries < maxTries; currentTries++) {\n         try {\n            return client.getBucketACL(bucketName);\n         } catch (ResourceNotFoundException e) {\n            imposeBackoffExponentialDelay(100L, 200L, 2, currentTries, maxTries);\n            last = e;\n         }\n      }\n      throw last;\n   }\n\n   private static void imposeBackoffExponentialDelay(long period, long maxPeriod, int pow, int failureCount, int max) {\n      long delayMs = (long) (period * Math.pow(failureCount, pow));\n      delayMs = delayMs > maxPeriod ? maxPeriod : delayMs;\n      try {\n         Thread.sleep(delayMs);\n      } catch (InterruptedException e) {\n         throw propagate(e);\n      }\n   }\n\n   @Override\n   public String toString() {\n      return \"getBucketAcl()\";\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/blobstore/internal/S3BlobStoreContextImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.blobstore.internal;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Context;\nimport org.jclouds.blobstore.BlobRequestSigner;\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.attr.ConsistencyModel;\nimport org.jclouds.blobstore.internal.BlobStoreContextImpl;\nimport org.jclouds.location.Provider;\nimport org.jclouds.rest.Utils;\nimport org.jclouds.s3.blobstore.S3BlobStore;\nimport org.jclouds.s3.blobstore.S3BlobStoreContext;\n\nimport com.google.common.reflect.TypeToken;\n\n@Singleton\npublic class S3BlobStoreContextImpl extends BlobStoreContextImpl implements S3BlobStoreContext {\n\n   @Inject\n   public S3BlobStoreContextImpl(@Provider Context backend, @Provider TypeToken<? extends Context> backendType,\n         Utils utils, ConsistencyModel consistencyModel, BlobStore blobStore, BlobRequestSigner blobRequestSigner) {\n      super(backend, backendType, utils, consistencyModel, blobStore, blobRequestSigner);\n   }\n\n   @Override\n   public S3BlobStore getBlobStore() {\n      return S3BlobStore.class.cast(super.getBlobStore());\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/blobstore/strategy/MultipartUpload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.blobstore.strategy;\n\npublic final class MultipartUpload {\n\n   /* Maximum number of parts per upload */\n   public static final int MAX_NUMBER_OF_PARTS = 10000;\n   /* Maximum number of parts returned for a list parts request */\n   public static final int MAX_LIST_PARTS_RETURNED = 1000;\n   /* Maximum number of multipart uploads returned in a list multipart uploads request */\n   public static final int MAX_LIST_MPU_RETURNED = 1000;\n\n   /*\n    * part size 5 MB to 5 GB, last part can be < 5 MB\n    */\n   public static final long MIN_PART_SIZE = 5242880L;\n   public static final long MAX_PART_SIZE = 5368709120L;\n\n   private MultipartUpload() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/config/S3HttpApiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.config;\n\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.Set;\nimport java.util.concurrent.TimeUnit;\n\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Constants;\nimport org.jclouds.aws.config.AWSHttpApiModule;\nimport org.jclouds.aws.handlers.AWSClientErrorRetryHandler;\nimport org.jclouds.aws.handlers.AWSServerErrorRetryHandler;\nimport org.jclouds.blobstore.ContainerNotFoundException;\nimport org.jclouds.blobstore.domain.PageSet;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpRetryHandler;\nimport org.jclouds.http.annotation.ClientError;\nimport org.jclouds.http.annotation.Redirection;\nimport org.jclouds.http.annotation.ServerError;\nimport org.jclouds.location.Region;\nimport org.jclouds.location.functions.RegionToEndpointOrProviderIfNull;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.RequestSigner;\nimport org.jclouds.s3.Bucket;\nimport org.jclouds.s3.S3Client;\nimport org.jclouds.s3.blobstore.functions.BucketsToStorageMetadata;\nimport org.jclouds.s3.domain.BucketMetadata;\nimport org.jclouds.s3.filters.RequestAuthorizeSignature;\nimport org.jclouds.s3.filters.RequestAuthorizeSignatureV2;\nimport org.jclouds.s3.filters.RequestAuthorizeSignatureV4;\nimport org.jclouds.s3.functions.GetRegionForBucket;\nimport org.jclouds.s3.handlers.ParseS3ErrorFromXmlContent;\nimport org.jclouds.s3.handlers.S3RedirectionRetryHandler;\nimport org.jclouds.s3.reference.S3Constants;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.Iterables;\nimport com.google.inject.Injector;\nimport com.google.inject.Provides;\nimport com.google.inject.TypeLiteral;\n\n/**\n * Configures the S3 connection, including logging and http transport.\n */\n@ConfiguresHttpApi\npublic class S3HttpApiModule<S extends S3Client> extends AWSHttpApiModule<S> {\n\n   @SuppressWarnings(\"unchecked\")\n   public S3HttpApiModule() {\n      this(Class.class.cast(S3Client.class));\n   }\n\n   protected S3HttpApiModule(Class<S> syncClientType) {\n      super(syncClientType);\n   }\n\n   @Provides\n   @Bucket\n   @Singleton\n   protected final CacheLoader<String, Optional<String>> provideBucketToRegion(@Region Supplier<Set<String>> regionSupplier,\n            final S3Client client) {\n      return bucketToRegion(regionSupplier, client);\n   }\n\n   protected CacheLoader<String, Optional<String>> bucketToRegion(@Region Supplier<Set<String>> regionSupplier,\n            final S3Client client) {\n      Set<String> regions = regionSupplier.get();\n      if (regions.isEmpty()) {\n         return new CacheLoader<String, Optional<String>>() {\n\n            @Override\n            public Optional<String> load(String bucket) {\n               return Optional.absent();\n            }\n\n            @Override\n            public String toString() {\n               return \"noRegions()\";\n            }\n         };\n      } else if (regions.size() == 1) {\n         final String onlyRegion = Iterables.getOnlyElement(regions);\n         return new CacheLoader<String, Optional<String>>() {\n            Optional<String> onlyRegionOption = Optional.of(onlyRegion);\n\n            @Override\n            public Optional<String> load(String bucket) {\n               return onlyRegionOption;\n            }\n\n            @Override\n            public String toString() {\n               return \"onlyRegion(\" + onlyRegion + \")\";\n            }\n         };\n      } else {\n         return new CacheLoader<String, Optional<String>>() {\n            @Override\n            public Optional<String> load(String bucket) {\n               try {\n                  return Optional.fromNullable(client.getBucketLocation(bucket));\n               } catch (ContainerNotFoundException e) {\n                  return Optional.absent();\n               }\n            }\n\n            @Override\n            public String toString() {\n               return \"bucketToRegion()\";\n            }\n         };\n      }\n   }\n\n   @Provides\n   @Bucket\n   @Singleton\n   protected final LoadingCache<String, Optional<String>> bucketToRegion(@Bucket CacheLoader<String, Optional<String>> loader) {\n      return CacheBuilder.newBuilder().build(loader);\n   }\n\n   @Provides\n   @Bucket\n   @Singleton\n   protected final Supplier<String> provideDefaultRegionForBucket(@Region Supplier<String> defaultRegion) {\n      return defaultRegionForBucket(defaultRegion);\n   }\n\n   protected Supplier<String> defaultRegionForBucket(@Region Supplier<String> defaultRegion) {\n      return defaultRegion;\n   }\n\n   @Provides\n   @Singleton\n   @Bucket\n   protected final Supplier<URI> provideBucketURI(@Bucket Supplier<String> defaultRegion,\n            RegionToEndpointOrProviderIfNull regionToEndpoint) {\n      return Suppliers.compose(regionToEndpoint, defaultRegion);\n   }\n\n   @Override\n   protected void configure() {\n      super.configure();\n      install(new S3ObjectModule());\n      install(new S3ParserModule());\n      bind(new TypeLiteral<Function<String, Optional<String>>>() {\n      }).annotatedWith(Bucket.class).to(GetRegionForBucket.class);\n      bind(new TypeLiteral<Function<Set<BucketMetadata>, PageSet<? extends StorageMetadata>>>() {\n      }).to(BucketsToStorageMetadata.class);\n   }\n\n   @Override\n   protected void bindErrorHandlers() {\n      bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(ParseS3ErrorFromXmlContent.class);\n      bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(ParseS3ErrorFromXmlContent.class);\n      bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(ParseS3ErrorFromXmlContent.class);\n   }\n\n   @Provides\n   @Singleton\n   protected final RequestAuthorizeSignature provideRequestAuthorizeSignature(Injector i, @Named(S3Constants.PROPERTY_SIGNER_VERSION) int version) {\n      return providesRequestAuthorizeSignature(i, version);\n   }\n\n   protected RequestAuthorizeSignature providesRequestAuthorizeSignature(Injector i, int version) {\n      switch (version) {\n      case 2:\n         return i.getInstance(RequestAuthorizeSignatureV2.class);\n      case 4:\n         return i.getInstance(RequestAuthorizeSignatureV4.class);\n      default:\n         throw new IllegalStateException(\"version must be 2 or 4, was: \" + version);\n      }\n   }\n\n   @Provides\n   @Singleton\n   protected final RequestSigner provideRequestSigner(RequestAuthorizeSignature in) {\n      if (in instanceof RequestSigner) {\n         return (RequestSigner) in;\n      }\n      return new RequestSigner() {\n         @Override\n         public String createStringToSign(HttpRequest input) {\n            return null;\n         }\n\n         @Override\n         public String sign(String toSign) {\n            return null;\n         }\n      };\n   }\n\n   @Override\n   protected void bindRetryHandlers() {\n      bind(HttpRetryHandler.class).annotatedWith(Redirection.class).to(S3RedirectionRetryHandler.class);\n      bind(HttpRetryHandler.class).annotatedWith(ClientError.class).to(AWSClientErrorRetryHandler.class);\n      bind(HttpRetryHandler.class).annotatedWith(ServerError.class).to(AWSServerErrorRetryHandler.class);\n   }\n\n   @Provides\n   @TimeStamp\n   protected final String guiceProvideTimeStamp(@TimeStamp Supplier<String> cache) {\n      return provideTimeStamp(cache);\n   }\n\n   protected String provideTimeStamp(@TimeStamp Supplier<String> cache) {\n      return cache.get();\n   }\n\n   /**\n    * borrowing concurrency code to ensure that caching takes place properly\n    */\n   @Provides\n   @TimeStamp\n   @Singleton\n   protected final Supplier<String> provideTimeStampCache(@Named(Constants.PROPERTY_SESSION_INTERVAL) long seconds,\n            final DateService dateService) {\n      return Suppliers.memoizeWithExpiration(new Supplier<String>() {\n         @Override\n         public String get() {\n            return dateService.rfc822DateFormat();\n         }\n      }, seconds, TimeUnit.SECONDS);\n   }\n\n   @Provides\n   @TimeStamp\n   protected Date provideTimeStampDate(@TimeStamp Supplier<Date> cache) {\n      return cache.get();\n   }\n\n    /**\n    * borrowing concurrency code to ensure that caching takes place properly\n    */\n   @Provides\n   @TimeStamp\n   @Singleton\n   protected final Supplier<Date> guiceProvideTimeStampCacheDate(\n      @Named(Constants.PROPERTY_SESSION_INTERVAL) long seconds,\n      @TimeStamp final Supplier<String> timestamp,\n      final DateService dateService) {\n      return provideTimeStampCacheDate(seconds, timestamp, dateService);\n   }\n\n   protected Supplier<Date> provideTimeStampCacheDate(\n      @Named(Constants.PROPERTY_SESSION_INTERVAL) long seconds,\n      @TimeStamp final Supplier<String> timestamp,\n      final DateService dateService) {\n      return Suppliers.memoizeWithExpiration(new Supplier<Date>() {\n         public Date get() {\n            return dateService.rfc822DateParse(timestamp.get());\n         }\n      }, seconds, TimeUnit.SECONDS);\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/config/S3ObjectModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.config;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Provider;\n\nimport org.jclouds.blobstore.config.BlobStoreObjectModule;\nimport org.jclouds.s3.domain.MutableObjectMetadata;\nimport org.jclouds.s3.domain.S3Object;\nimport org.jclouds.s3.domain.internal.S3ObjectImpl;\n\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Provides;\n\n/**\n * Configures the domain object mappings needed for all S3 implementations\n */\npublic class S3ObjectModule extends AbstractModule {\n\n   /**\n    * explicit factories are created here as it has been shown that Assisted Inject is extremely\n    * inefficient. http://code.google.com/p/google-guice/issues/detail?id=435\n    */\n   @Override\n   protected void configure() {\n      // for converters\n      install(new BlobStoreObjectModule());\n      bind(S3Object.Factory.class).to(S3ObjectFactory.class).asEagerSingleton();\n   }\n\n   private static class S3ObjectFactory implements S3Object.Factory {\n      @Inject\n      Provider<MutableObjectMetadata> metadataProvider;\n\n      public S3Object create(MutableObjectMetadata metadata) {\n         return new S3ObjectImpl(metadata != null ? metadata : metadataProvider.get());\n      }\n   }\n\n   @Provides\n   final S3Object provideS3Object(S3Object.Factory factory) {\n      return factory.create(null);\n   }\n\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/config/S3ParserModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.config;\n\nimport org.jclouds.json.config.GsonModule.DateAdapter;\nimport org.jclouds.json.config.GsonModule.Iso8601DateAdapter;\n\nimport com.google.inject.AbstractModule;\n\npublic class S3ParserModule extends AbstractModule {\n\n   @Override\n   protected void configure() {\n      bind(DateAdapter.class).to(Iso8601DateAdapter.class);\n   }\n\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/config/package-info.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * This package contains modules who manage the dependencies of the S3Context, S3Client, and S3 Map views.\n */\npackage org.jclouds.s3.config;\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/domain/AccessControlList.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.domain;\n\nimport java.net.URI;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Set;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Collections2;\nimport com.google.common.collect.Lists;\nimport com.google.common.collect.Sets;\n\n/**\n * An Access Control List (ACL) describes the access control settings for a bucket or object in S3.\n * \n * ACL settings comprise a set of {@link Grant}s, each of which specifies a {@link Permission} that\n * has been granted to a specific {@link Grantee}. If an payload tries to access or modify an item\n * in S3, the operation will be denied unless the item has ACL settings that explicitly permit that\n * payload to perform that action.\n */\npublic class AccessControlList {\n\n   private CanonicalUser owner;\n   private final List<Grant> grants = Lists.newArrayList();\n\n   public void setOwner(CanonicalUser owner) {\n      this.owner = owner;\n   }\n\n   public CanonicalUser getOwner() {\n      return owner;\n   }\n\n   /**\n    * @return an unmodifiable set of grants represented by this ACL.\n    */\n   public List<Grant> getGrants() {\n      return Collections.unmodifiableList(grants);\n   }\n\n   /**\n    * @return an unmodifiable set of grantees who have been assigned permissions in this ACL.\n    */\n   public Set<Grantee> getGrantees() {\n      Set<Grantee> grantees = Sets.newTreeSet();\n      for (Grant grant : getGrants()) {\n         grantees.add(grant.getGrantee());\n      }\n      return Collections.unmodifiableSet(grantees);\n   }\n\n   /**\n    * Add a permission for the given grantee.\n    * \n    * @param grantee\n    * @param permission\n    */\n   public AccessControlList addPermission(Grantee grantee, String permission) {\n      Grant grant = new Grant(grantee, permission);\n      grants.add(grant);\n      return this;\n   }\n\n   /**\n    * Add a permission for the given group grantee.\n    * \n    * @param groupGranteeURI\n    * @param permission\n    */\n   public AccessControlList addPermission(URI groupGranteeURI, String permission) {\n      return addPermission(new GroupGrantee(groupGranteeURI), permission);\n   }\n\n   /**\n    * Revoke a permission for the given grantee, if this specific permission was granted.\n    * \n    * Note that you must be very explicit about the permissions you revoke, you cannot revoke\n    * partial permissions and expect this class to determine the implied remaining permissions. For\n    * example, if you revoke the {@link Permission#READ} permission from a grantee with\n    * {@link Permission#FULL_CONTROL} access, <strong>the revocation will do nothing</strong> and\n    * the grantee will retain full access. To change the access settings for this grantee, you must\n    * first remove the {@link Permission#FULL_CONTROL} permission the add back the\n    * {@link Permission#READ} permission.\n    * \n    * @param grantee\n    * @param permission\n    */\n   public AccessControlList revokePermission(Grantee grantee, String permission) {\n      for (Iterator<Grant> it = grants.iterator(); it.hasNext();) {\n         Grant grant = it.next();\n         if (grant.getGrantee().equals(grantee) && grant.getPermission().equals(permission)) {\n            it.remove();\n         }\n      }\n      return this;\n   }\n\n   /**\n    * Revoke a permission for the given group grantee, if this specific permission was granted.\n    * \n    * Note that you must be very explicit about the permissions you revoke, you cannot revoke\n    * partial permissions and expect this class to determine the implied remaining permissions. For\n    * example, if you revoke the {@link Permission#READ} permission from a grantee with\n    * {@link Permission#FULL_CONTROL} access, <strong>the revocation will do nothing</strong> and\n    * the grantee will retain full access. To change the access settings for this grantee, you must\n    * first remove the {@link Permission#FULL_CONTROL} permission the add back the\n    * {@link Permission#READ} permission.\n    * \n    * @param groupGranteeURI\n    * @param permission\n    */\n   public AccessControlList revokePermission(URI groupGranteeURI, String permission) {\n      return revokePermission(new GroupGrantee(groupGranteeURI), permission);\n   }\n\n   /**\n    * Revoke all the permissions granted to the given grantee.\n    * \n    * @param grantee\n    */\n   public AccessControlList revokeAllPermissions(Grantee grantee) {\n      Collection<Grant> grantsForGrantee = findGrantsForGrantee(grantee.getIdentifier());\n      grants.removeAll(grantsForGrantee);\n      return this;\n   }\n\n   /**\n    * @param granteeId\n    * @return the permissions assigned to a grantee, as identified by the given ID.\n    */\n   public Collection<String> getPermissions(String granteeId) {\n      Collection<Grant> grantsForGrantee = findGrantsForGrantee(granteeId);\n      return Collections2.transform(grantsForGrantee, new Function<Grant, String>() {\n         public String apply(Grant g) {\n            return g.getPermission();\n         }\n      });\n   }\n\n   /**\n    * @param grantee\n    * @return the permissions assigned to a grantee.\n    */\n   public Collection<String> getPermissions(Grantee grantee) {\n      return getPermissions(grantee.getIdentifier());\n   }\n\n   /**\n    * @param granteeURI\n    * @return the permissions assigned to a group grantee.\n    */\n   public Collection<String> getPermissions(URI granteeURI) {\n      return getPermissions(granteeURI.toASCIIString());\n   }\n\n   /**\n    * @param granteeId\n    * @param permission\n    * @return true if the grantee has the given permission.\n    */\n   public boolean hasPermission(String granteeId, String permission) {\n      return getPermissions(granteeId).contains(permission);\n   }\n\n   /**\n    * @param grantee\n    * @param permission\n    * @return true if the grantee has the given permission.\n    */\n   public boolean hasPermission(Grantee grantee, String permission) {\n      return hasPermission(grantee.getIdentifier(), permission);\n   }\n\n   /**\n    * @param granteeURI\n    * @param permission\n    * @return true if the grantee has the given permission.\n    */\n   public boolean hasPermission(URI granteeURI, String permission) {\n      return getPermissions(granteeURI).contains(permission);\n   }\n\n   /**\n    * Find all the grants for a given grantee, identified by an ID which allows all Grantee types to\n    * be searched.\n    * \n    * @param granteeId\n    *           identifier of a canonical user, email address user, or group.\n    */\n   protected Collection<Grant> findGrantsForGrantee(final String granteeId) {\n      return Collections2.filter(grants, new Predicate<Grant>() {\n         @Override\n         public boolean apply(Grant g) {\n            return granteeId.equals(g.getGrantee().getIdentifier());\n         }\n      });\n   }\n\n   /**\n    * Converts a canned access control policy into the equivalent access control list.\n    * \n    * @param cannedAP\n    * @param ownerId\n    */\n   public static AccessControlList fromCannedAccessPolicy(CannedAccessPolicy cannedAP, String ownerId) {\n      AccessControlList acl = new AccessControlList();\n      acl.setOwner(new CanonicalUser(ownerId));\n\n      // Canned access policies always allow full control to the owner.\n      acl.addPermission(new CanonicalUserGrantee(ownerId), Permission.FULL_CONTROL);\n\n      if (CannedAccessPolicy.PRIVATE == cannedAP) {\n         // No more work to do.\n      } else if (CannedAccessPolicy.AUTHENTICATED_READ == cannedAP) {\n         acl.addPermission(GroupGranteeURI.AUTHENTICATED_USERS, Permission.READ);\n      } else if (CannedAccessPolicy.PUBLIC_READ == cannedAP) {\n         acl.addPermission(GroupGranteeURI.ALL_USERS, Permission.READ);\n      } else if (CannedAccessPolicy.PUBLIC_READ_WRITE == cannedAP) {\n         acl.addPermission(GroupGranteeURI.ALL_USERS, Permission.READ);\n         acl.addPermission(GroupGranteeURI.ALL_USERS, Permission.WRITE);\n      }\n      return acl;\n   }\n\n   // /////////////////////////////////////////////////////////////////////////////\n   // Class and Enum declarations to represent Grants, Grantees and Permissions //\n   // /////////////////////////////////////////////////////////////////////////////\n\n   public static final class Permission {\n      public static final String READ = \"READ\";\n      public static final String WRITE = \"WRITE\";\n      public static final String READ_ACP = \"READ_ACP\";\n      public static final String WRITE_ACP = \"WRITE_ACP\";\n      public static final String FULL_CONTROL = \"FULL_CONTROL\";\n\n      private Permission() {\n         throw new AssertionError(\"intentionally unimplemented\");\n      }\n   };\n\n   public static class Grant implements Comparable<Grant> {\n\n      private Grantee grantee;\n      private final String permission;\n\n      public Grant(Grantee grantee, String permission) {\n         this.grantee = grantee;\n         this.permission = permission;\n      }\n\n      public Grantee getGrantee() {\n         return grantee;\n      }\n\n      @VisibleForTesting\n      public void setGrantee(Grantee grantee) {\n         this.grantee = grantee;\n      }\n\n      public String getPermission() {\n         return permission;\n      }\n\n      @Override\n      public String toString() {\n         final StringBuilder sb = new StringBuilder();\n         sb.append(\"Grant\");\n         sb.append(\"{grantee=\").append(grantee);\n         sb.append(\", permission=\").append(permission);\n         sb.append('}');\n         return sb.toString();\n      }\n\n      public int compareTo(org.jclouds.s3.domain.AccessControlList.Grant o) {\n         if (this == o) {\n            return 0;\n         } else {\n            String myGranteeAndPermission = grantee.getIdentifier() + \"\\n\" + permission;\n            String otherGranteeAndPermission = o.grantee.getIdentifier() + \"\\n\" + o.permission;\n            return myGranteeAndPermission.compareTo(otherGranteeAndPermission);\n         }\n      }\n\n      @Override\n      public int hashCode() {\n         final int prime = 31;\n         int result = 1;\n         result = prime * result + ((grantee == null) ? 0 : grantee.hashCode());\n         result = prime * result + ((permission == null) ? 0 : permission.hashCode());\n         return result;\n      }\n\n      @Override\n      public boolean equals(Object obj) {\n         if (this == obj)\n            return true;\n         if (obj == null)\n            return false;\n         if (getClass() != obj.getClass())\n            return false;\n         Grant other = (Grant) obj;\n         if (grantee == null) {\n            if (other.grantee != null)\n               return false;\n         } else if (!grantee.equals(other.grantee))\n            return false;\n         if (permission == null) {\n            if (other.permission != null)\n               return false;\n         } else if (!permission.equals(other.permission))\n            return false;\n         return true;\n      }\n   }\n\n   public abstract static class Grantee implements Comparable<Grantee> {\n      private final String identifier;\n\n      protected Grantee(String identifier) {\n         this.identifier = identifier;\n      }\n\n      public String getIdentifier() {\n         return identifier;\n      }\n\n      @Override\n      public String toString() {\n         final StringBuilder sb = new StringBuilder();\n         sb.append(\"Grantee\");\n         sb.append(\"{identifier='\").append(identifier).append('\\'');\n         sb.append('}');\n         return sb.toString();\n      }\n\n      public int compareTo(org.jclouds.s3.domain.AccessControlList.Grantee o) {\n         return (this == o) ? 0 : getIdentifier().compareTo(o.getIdentifier());\n      }\n\n      @Override\n      public int hashCode() {\n         final int prime = 31;\n         int result = 1;\n         result = prime * result + ((identifier == null) ? 0 : identifier.hashCode());\n         return result;\n      }\n\n      @Override\n      public boolean equals(Object obj) {\n         if (this == obj)\n            return true;\n         if (obj == null)\n            return false;\n         if (getClass() != obj.getClass())\n            return false;\n         Grantee other = (Grantee) obj;\n         if (identifier == null) {\n            if (other.identifier != null)\n               return false;\n         } else if (!identifier.equals(other.identifier))\n            return false;\n         return true;\n      }\n   }\n\n   public static class EmailAddressGrantee extends Grantee {\n      public EmailAddressGrantee(String emailAddress) {\n         super(emailAddress);\n      }\n\n      public String getEmailAddress() {\n         return getIdentifier();\n      }\n   }\n\n   public static class CanonicalUserGrantee extends Grantee {\n      private final String displayName;\n\n      public CanonicalUserGrantee(String id, String displayName) {\n         super(id);\n         this.displayName = displayName;\n      }\n\n      public CanonicalUserGrantee(String id) {\n         this(id, null);\n      }\n\n      public String getDisplayName() {\n         return displayName;\n      }\n\n      public String toString() {\n         final StringBuilder sb = new StringBuilder();\n         sb.append(\"CanonicalUserGrantee\");\n         sb.append(\"{displayName='\").append(displayName).append('\\'');\n         sb.append(\", identifier='\").append(getIdentifier()).append('\\'');\n\n         sb.append('}');\n         return sb.toString();\n      }\n   }\n\n   public static final class GroupGranteeURI {\n      public static final URI ALL_USERS = URI.create(\"http://acs.amazonaws.com/groups/global/AllUsers\");\n      public static final URI AUTHENTICATED_USERS = URI\n               .create(\"http://acs.amazonaws.com/groups/global/AuthenticatedUsers\");\n      public static final URI LOG_DELIVERY = URI.create(\"http://acs.amazonaws.com/groups/s3/LogDelivery\");\n\n      private GroupGranteeURI() {\n         throw new AssertionError(\"intentionally unimplemented\");\n      }\n   }\n\n   public static class GroupGrantee extends Grantee {\n\n      public GroupGrantee(URI groupURI) {\n         super(groupURI.toASCIIString());\n      }\n   }\n\n   @Override\n   public String toString() {\n      final StringBuilder sb = new StringBuilder();\n      sb.append(\"AccessControlList\");\n      sb.append(\"{owner=\").append(owner);\n      sb.append(\", grants=\").append(grants);\n      sb.append('}');\n      return sb.toString();\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((grants == null) ? 0 : grants.hashCode());\n      result = prime * result + ((owner == null) ? 0 : owner.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      AccessControlList other = (AccessControlList) obj;\n      if (grants == null) {\n         if (other.grants != null)\n            return false;\n      } else if (!grants.equals(other.grants))\n         return false;\n      if (owner == null) {\n         if (other.owner != null)\n            return false;\n      } else if (!owner.equals(other.owner))\n         return false;\n      return true;\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/domain/BucketLogging.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.domain;\n\nimport java.util.Set;\n\nimport org.jclouds.s3.domain.AccessControlList.Grant;\n\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Sets;\n\n/**\n * Each Amazon S3 bucket has an associated XML sub-resource that you can read and write in order to\n * inspect or change the logging status for that bucket.\n */\npublic class BucketLogging {\n   private final String targetBucket;\n   private final String targetPrefix;\n   private final Set<Grant> targetGrants = Sets.newHashSet();\n\n   /**\n    * \n    * @param targetBucket\n    *           {@link #getTargetBucket}\n    * @param targetPrefix\n    *           {@link #getTargetPrefix}\n    * @param targetGrants\n    *           {@link #getTargetGrants}\n    */\n   public BucketLogging(String targetBucket, String targetPrefix, Iterable<Grant> targetGrants) {\n      this.targetBucket = targetBucket;\n      this.targetPrefix = targetPrefix;\n      Iterables.addAll(this.targetGrants, targetGrants);\n   }\n\n   /**\n    * \n    * @param targetBucket\n    *           {@link #getTargetBucket}\n    * @param targetPrefix\n    *           {@link #getTargetPrefix}\n    */\n   public BucketLogging(String targetBucket, String targetPrefix) {\n      this.targetBucket = targetBucket;\n      this.targetPrefix = targetPrefix;\n   }\n\n   /**\n    * The bucket owner is automatically granted FULL_CONTROL to all logs delivered to the bucket.\n    * This optional element enables you grant access to others. Any specified TargetGrants are added\n    * to the default ACL. For more information about ACLs, see Access Control Lists.\n    */\n   public Set<Grant> getTargetGrants() {\n      return targetGrants;\n   }\n\n   /**\n    * Specifies the bucket where server access logs will be delivered. You can have your logs\n    * delivered to any bucket that you own, including the same bucket that is being logged. You can\n    * also configure multiple buckets to deliver their logs to the same target bucket. In this case\n    * you should choose a different TargetPrefix for each source bucket so that the delivered log\n    * files can be distinguished by key.\n    * <p/>\n    * <h3>Note</h3>\n    * \n    * The source and the target buckets must be in the same location. For more information about\n    * bucket location constraints, see Buckets and Regions\n    */\n   public String getTargetBucket() {\n      return targetBucket;\n   }\n\n   /**\n    * This element lets you specify a prefix for the keys that the delivered log files will be\n    * stored under. For information on how the key name for log files is constructed, see Delivery\n    * of Server Access Logs.\n    */\n   public String getTargetPrefix() {\n      return targetPrefix;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((targetBucket == null) ? 0 : targetBucket.hashCode());\n      result = prime * result + ((targetGrants == null) ? 0 : targetGrants.hashCode());\n      result = prime * result + ((targetPrefix == null) ? 0 : targetPrefix.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      BucketLogging other = (BucketLogging) obj;\n      if (targetBucket == null) {\n         if (other.targetBucket != null)\n            return false;\n      } else if (!targetBucket.equals(other.targetBucket))\n         return false;\n      if (targetGrants == null) {\n         if (other.targetGrants != null)\n            return false;\n      } else if (!targetGrants.equals(other.targetGrants))\n         return false;\n      if (targetPrefix == null) {\n         if (other.targetPrefix != null)\n            return false;\n      } else if (!targetPrefix.equals(other.targetPrefix))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"BucketLogging [targetBucket=\" + targetBucket + \", targetGrants=\" + targetGrants\n               + \", targetPrefix=\" + targetPrefix + \"]\";\n   }\n\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/domain/BucketMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.domain;\n\nimport java.util.Date;\n\n/**\n * System metadata of the S3Bucket\n */\npublic class BucketMetadata implements Comparable<BucketMetadata> {\n   private final Date creationDate;\n   private final String name;\n   private final CanonicalUser owner;\n\n   public BucketMetadata(String name, Date creationDate, CanonicalUser owner) {\n      this.name = name;\n      this.creationDate = creationDate;\n      this.owner = owner;\n   }\n\n   /**\n    * Every bucket and object in Amazon S3 has an owner, the user that created the bucket or object.\n    * The owner of a bucket or object cannot be changed. However, if the object is overwritten by\n    * another user (deleted and rewritten), the new object will have a new owner.\n    */\n   public CanonicalUser getOwner() {\n      return owner;\n   }\n\n   public Date getCreationDate() {\n      return creationDate;\n   }\n\n   /**\n    * To comply with Amazon S3 requirements, bucket names must:\n    * <p/>\n    * Contain lowercase letters, numbers, periods (.), underscores (_), and dashes (-)\n    * <p/>\n    * Start with a number or letter\n    * <p/>\n    * Be between 3 and 255 characters long\n    * <p/>\n    * Not be in an IP address style (e.g., \"192.168.5.4\")\n    */\n   public String getName() {\n      return name;\n   }\n\n   public int compareTo(BucketMetadata o) {\n      return (this == o) ? 0 : getName().compareTo(o.getName());\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((name == null) ? 0 : name.hashCode());\n      result = prime * result + ((owner == null) ? 0 : owner.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      BucketMetadata other = (BucketMetadata) obj;\n      if (name == null) {\n         if (other.name != null)\n            return false;\n      } else if (!name.equals(other.name))\n         return false;\n      if (owner == null) {\n         if (other.owner != null)\n            return false;\n      } else if (!owner.equals(other.owner))\n         return false;\n      return true;\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/domain/CannedAccessPolicy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.domain;\n\nimport com.google.common.base.CaseFormat;\n\n/**\n * Description from Amazon's documentation:\n * \n * <p />\n * Because of restrictions in what can be sent via http headers, Amazon S3\n * supports the concept of canned access policies for REST. A canned access\n * policy can be included with the x-amz-acl header as part of a PUT operation\n * to provide shorthand representation of a full access policy. When Amazon S3\n * sees the x-amz-acl header as part of a PUT operation, it will assign the\n * respective access policy to the resource created as a result of the PUT. If\n * no x-amz-acl header is included with a PUT request, then the bucket or object\n * is written with the private access control policy (even if, in the case of an\n * object, the object already exists with some other pre-existing access control\n * policy).\n */\npublic enum CannedAccessPolicy {\n\n    /**\n     * Owner gets FULL_CONTROL. No one else has access rights (default).\n     */\n    PRIVATE,\n    /**\n     * Owner gets FULL_CONTROL and the anonymous identity is granted READ\n     * access. If this policy is used on an object, it can be read from a\n     * browser with no authentication.\n     */\n    PUBLIC_READ,\n    /**\n     * Owner gets FULL_CONTROL, the anonymous identity is granted READ and\n     * WRITE access. This can be a useful policy to apply to a bucket, but is\n     * generally not recommended.\n     */\n    PUBLIC_READ_WRITE,\n    /**\n     * Owner gets FULL_CONTROL. Amazon EC2 gets READ access to GET an Amazon\n     * Machine Image (AMI) bundle from Amazon S3.\n     */\n    AWS_EXEC_READ,\n    /**\n     * Owner gets FULL_CONTROL, and any identity authenticated as a registered\n     * Amazon S3 user is granted READ access.\n     */\n    AUTHENTICATED_READ,\n    /**\n     * Object owner gets FULL_CONTROL. Bucket owner gets READ access. If you\n     * specify this canned ACL when creating a bucket, Amazon S3 ignores it.\n     */\n    BUCKET_OWNER_READ,\n    /**\n     * Both the object owner and the bucket owner get FULL_CONTROL over the\n     * object. If you specify this canned ACL when creating a bucket, Amazon S3\n     * ignores it.\n     */\n    BUCKET_OWNER_FULL_CONTROL,\n    /**\n     * The LogDelivery group gets WRITE and READ_ACP permissions on the bucket.\n     * For more information about logs, see (Server Access Logging).\n     */\n    LOG_DELIVERY_WRITE;\n\n    @Override\n    public String toString() {\n       return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_HYPHEN, name());\n    }\n    \n    /**\n     * @param capHeader\n     * The value of the x-amz-acl HTTP Header returned by S3 when an\n     * object has a canned access policy.\n     * \n     * @return\n     * the canned access policy object corresponding to the header value,\n     * or null if the given header value does not represent a valid canned \n     * policy.\n     */\n    public static CannedAccessPolicy fromHeader(String capHeader) {\n       return valueOf(CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_UNDERSCORE, capHeader));\n    }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/domain/CanonicalUser.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.domain;\n\n/**\n * Every bucket and object in Amazon S3 has an owner, the user that created the bucket or object.\n * The owner of a bucket or object cannot be changed. However, if the object is overwritten by\n * another user (deleted and rewritten), the new object will have a new owner.\n * <p/>\n */\npublic class CanonicalUser {\n   private String id;\n   private String displayName;\n\n   public CanonicalUser() {}\n\n   public CanonicalUser(String id) {\n      this.id = id;\n   }\n\n   public CanonicalUser(String id, String displayName) {\n      this(id);\n      this.displayName = displayName;\n   }\n\n   /**\n    * To locate the CanonicalUser ID for a user, the user must perform the\n    * {@link org.jclouds.s3.blobstore.S3BlobStore#list(String)} and retrieve\n    * {@link BucketMetadata#getOwner()}\n    */\n   public String getId() {\n      return id;\n   }\n\n   public void setId(String id) { this.id = id; }\n\n   /**\n    * read-only as is maintained by Amazon.\n    */\n   public String getDisplayName() {\n      return displayName;\n   }\n\n   public void setDisplayName(String displayName) {\n      this.displayName = displayName;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((id == null) ? 0 : id.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      CanonicalUser other = (CanonicalUser) obj;\n      if (id == null) {\n         if (other.id != null)\n            return false;\n      } else if (!id.equals(other.id))\n         return false;\n      return true;\n   }\n\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/domain/DeleteResult.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ForwardingSet;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Multi-object delete API response\n * <p/>\n * Contains a list of the keys that were deleted\n */\npublic class DeleteResult extends ForwardingSet<String> {\n\n   public static class Error {\n\n      private final String code;\n      private final String message;\n\n      public Error(String code, String message) {\n         this.code = checkNotNull(code, \"code is null\");\n         this.message = checkNotNull(message, \"message is null\");\n      }\n\n      public String getCode() {\n         return code;\n      }\n\n      public String getMessage() {\n         return message;\n      }\n\n      @Override\n      public boolean equals(Object o) {\n         if (this == o) return true;\n         if (!(o instanceof Error)) return false;\n\n         Error that = (Error) o;\n\n         return Objects.equal(code, that.code)\n            && Objects.equal(message, that.message);\n      }\n\n      @Override\n      public int hashCode() {\n         return Objects.hashCode(code, message);\n      }\n\n      @Override\n      public String toString() {\n         return MoreObjects.toStringHelper(this).omitNullValues()\n            .add(\"code\", code).add(\"message\", message).toString();\n      }\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().fromDeleteResult(this);\n   }\n\n   public static class Builder {\n\n      private ImmutableSet.Builder<String> deleted = ImmutableSet.builder();\n      private ImmutableMap.Builder<String, Error> errors = ImmutableMap.builder();\n\n      /**\n       * @see DeleteResult#getErrors\n       */\n      public Builder putError(String key, Error error) {\n         this.errors.put(key, error);\n         return this;\n      }\n\n      /**\n       * @see DeleteResult#getErrors\n       */\n      public Builder errors(Map<String, Error> errors) {\n         this.errors = ImmutableMap.<String, Error>builder().putAll(errors);\n         return this;\n      }\n\n      /**\n       * @see DeleteResult#getDeleted\n       */\n      public Builder deleted(Iterable<String> deleted) {\n         this.deleted = ImmutableSet.<String>builder().addAll(deleted);\n         return this;\n      }\n\n      /**\n       * @see DeleteResult#getDeleted\n       */\n      public Builder add(String key) {\n         this.deleted.add(key);\n         return this;\n      }\n\n      /**\n       * @see DeleteResult#getDeleted\n       */\n      public Builder addAll(Iterable<String> key) {\n         this.deleted.addAll(key);\n         return this;\n      }\n\n      public DeleteResult build() {\n         return new DeleteResult(deleted.build(), errors.build());\n      }\n\n      public Builder fromDeleteResult(DeleteResult result) {\n         return addAll(result.getDeleted()).errors(result.getErrors());\n      }\n   }\n\n   private final Set<String> deleted;\n   private final Map<String, Error> errors;\n\n   public DeleteResult(Set<String> deleted, Map<String, Error> errors) {\n      this.deleted = ImmutableSet.copyOf(deleted);\n      this.errors = ImmutableMap.copyOf(errors);\n   }\n\n   /**\n    * Get the set of successfully deleted keys\n    */\n   public Set<String> getDeleted() {\n      return deleted;\n   }\n\n   /**\n    * Get a map with details about failed delete operations indexed by object name\n    */\n   public Map<String, Error> getErrors() {\n      return errors;\n   }\n\n   @Override\n   protected Set<String> delegate() {\n      return deleted;\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o) return true;\n      if (!(o instanceof DeleteResult)) return false;\n\n      DeleteResult that = (DeleteResult) o;\n\n      return Objects.equal(errors, that.errors)\n         && Objects.equal(deleted, that.deleted);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(deleted, errors);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).omitNullValues()\n         .add(\"deleted\", deleted).add(\"errors\", errors).toString();\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/domain/ListBucketResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.domain;\n\nimport java.util.Set;\n\n/**\n * A container that provides namespace, access control and aggregation of {@link S3Object}s\n * <p/>\n * <p/>\n * Every object stored in Amazon S3 is contained in a bucket. Buckets partition the namespace of\n * objects stored in Amazon S3 at the top level. Within a bucket, you can use any names for your\n * objects, but bucket names must be unique across all of Amazon S3.\n * <p/>\n * Buckets are similar to Internet domain names. Just as Amazon is the only owner of the domain name\n * Amazon.com, only one person or organization can own a bucket within Amazon S3. Once you create a\n * uniquely named bucket in Amazon S3, you can organize and name the objects within the bucket in\n * any way you like and the bucket will remain yours for as long as you like and as long as you have\n * the Amazon S3 identity.\n * <p/>\n * The similarities between buckets and domain names is not a coincidence there is a direct mapping\n * between Amazon S3 buckets and subdomains of s3.amazonaws.com. Objects stored in Amazon S3 are\n * addressable using the REST API under the domain bucketname.s3.amazonaws.com. For example, if the\n * object homepage.html?is stored in the Amazon S3 bucket mybucket its address would be\n * http://mybucket.s3.amazonaws.com/homepage.html?\n */\npublic interface ListBucketResponse extends Set<ObjectMetadata> {\n\n   /**\n    * Limits the response to keys which begin with the indicated prefix. You can use prefixes to\n    * separate a bucket into different sets of keys in a way similar to how a file system uses\n    * folders.\n    */\n   String getPrefix();\n\n   /**\n    * Indicates where in the bucket to begin listing. The list will only include keys that occur\n    * lexicographically after marker. This is convenient for pagination: To get the next page of\n    * results use the last key of the current page as the marker.\n    */\n   String getNextMarker();\n\n   String getMarker();\n\n   /**\n    * The maximum number of keys you'd like to see in the response body. The server might return\n    * fewer than this many keys, but will not return more.\n    */\n   int getMaxKeys();\n\n   /**\n    * There are more then maxKeys available\n    */\n   boolean isTruncated();\n\n   /**\n    * Causes keys that contain the same string between the prefix and the first occurrence of the\n    * delimiter to be rolled up into a single result element in the CommonPrefixes collection. These\n    * rolled-up keys are not returned elsewhere in the response.\n    * \n    */\n   String getDelimiter();\n\n   /**\n    * Example:\n    * <p/>\n    * if the following keys are in the bucket\n    * <p/>\n    * a/1/a<br/>\n    * a/1/b<br/>\n    * a/2/a<br/>\n    * a/2/b<br/>\n    * <p/>\n    * and prefix is set to <code>a/</code> and delimiter is set to <code>/</code> then\n    * commonprefixes would return 1,2\n    * \n    * @see org.jclouds.s3.options.ListBucketOptions#getPrefix()\n    */\n   Set<String> getCommonPrefixes();\n\n   /**\n    * name of the Bucket\n    */\n   String getName();\n\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/domain/ListMultipartUploadResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.domain;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Date;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.annotations.Beta;\nimport org.jclouds.javax.annotation.Nullable;\n\n@AutoValue\n@Beta\npublic abstract class ListMultipartUploadResponse {\n   public abstract int partNumber();\n   @Nullable public abstract Date lastModified();\n   public abstract String eTag();\n   public abstract long size();\n\n   public static ListMultipartUploadResponse create(int partNumber, @Nullable Date lastModified, String eTag, long size) {\n      checkArgument(partNumber > 0, \"partNumber must be greater than zero, was: %s\", partNumber);\n      checkNotNull(eTag, \"eTag\");\n      if (lastModified != null) {\n         lastModified = (Date) lastModified.clone();\n      }\n      checkArgument(size >= 0, \"size must be positive, was: %s\", size);\n      return new AutoValue_ListMultipartUploadResponse(partNumber, lastModified, eTag, size);\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/domain/ListMultipartUploadsResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.domain;\n\nimport java.util.Date;\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\n\n@AutoValue\npublic abstract class ListMultipartUploadsResponse {\n   public abstract String bucket();\n   @Nullable public abstract String keyMarker();\n   @Nullable public abstract String uploadIdMarker();\n   @Nullable public abstract String nextKeyMarker();\n   @Nullable public abstract String nextUploadIdMarker();\n   public abstract int maxUploads();\n   public abstract boolean isTruncated();\n   public abstract List<Upload> uploads();\n\n   public static ListMultipartUploadsResponse create(String bucket, @Nullable String keyMarker, @Nullable String uploadIdMarker, @Nullable String nextKeyMarker, @Nullable String nextUploadIdMarker, int maxUploads, boolean isTruncated, List<Upload> uploads) {\n      uploads = ImmutableList.copyOf(uploads);\n      return new AutoValue_ListMultipartUploadsResponse(bucket, keyMarker, uploadIdMarker, nextKeyMarker, nextUploadIdMarker, maxUploads, isTruncated, uploads);\n   }\n\n   @AutoValue\n   public abstract static class Upload {\n      public abstract String key();\n      public abstract String uploadId();\n      public abstract CanonicalUser initiator();\n      public abstract CanonicalUser owner();\n      public abstract ObjectMetadata.StorageClass storageClass();\n      public abstract Date initiated();\n\n      public static Upload create(String key, String uploadId, CanonicalUser initiator, CanonicalUser owner, ObjectMetadata.StorageClass storageClass, Date initiated) {\n         initiated = (Date) initiated.clone();\n         return new AutoValue_ListMultipartUploadsResponse_Upload(key, uploadId, initiator, owner, storageClass, initiated);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/domain/MutableObjectMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.domain;\n\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.Map;\n\nimport org.jclouds.io.MutableContentMetadata;\nimport org.jclouds.s3.domain.ObjectMetadata.StorageClass;\nimport org.jclouds.s3.domain.internal.MutableObjectMetadataImpl;\n\nimport com.google.inject.ImplementedBy;\n\n/**\n * /** Amazon S3 is designed to store objects. Objects are stored in {@link ListBucketResponse buckets}\n * and consist of a {@link S3Object#getPayload()} value}, a\n * {@link MutableObjectMetadata#getKey key}, {@link MutableObjectMetadata#getUserMetadata() metadata}, and an\n * access control policy.\n */\n@ImplementedBy(MutableObjectMetadataImpl.class)\npublic interface MutableObjectMetadata extends ObjectMetadata {\n\n   /**\n    * The key is the handle that you assign to an object that allows you retrieve it later. A key is\n    * a sequence of Unicode characters whose UTF-8 encoding is at most 1024 bytes long. Each object\n    * in a bucket must have a unique key.\n    */\n   void setKey(String key);\n\n   void setBucket(String bucket);\n\n   /**\n    * Every bucket and object in Amazon S3 has an owner, the user that created the bucket or object.\n    * The owner of a bucket or object cannot be changed. However, if the object is overwritten by\n    * another user (deleted and rewritten), the new object will have a new owner.\n    */\n   void setOwner(CanonicalUser owner);\n\n   /**\n    * Currently defaults to 'STANDARD' and not used.\n    */\n   void setStorageClass(StorageClass storageClass);\n\n   /**\n    * Can be used to specify caching behavior along the request/reply chain.\n    *\n    * @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html?sec14.9.\n    *\n    * @deprecated call getContentMetadata().setCacheControl(String) instead\n    */\n   @Deprecated\n   void setCacheControl(String cacheControl);\n\n   @Override\n   MutableContentMetadata getContentMetadata();\n\n   void setContentMetadata(MutableContentMetadata md);\n\n   void setLastModified(Date lastModified);\n\n   void setETag(String eTag);\n\n   void setUserMetadata(Map<String, String> userMetadata);\n\n   void setUri(URI uri);\n\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/domain/ObjectMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.Map;\n\nimport org.jclouds.blobstore.domain.Tier;\nimport org.jclouds.io.ContentMetadata;\n\n/**\n * Amazon S3 is designed to store objects. Objects are stored in {@link S3BucketListing buckets}\n * and consist of a {@link org.jclouds.s3.domain.S3Object#getData() value}, a\n * {@link S3Object#getKey key}, {@link ObjectMetadata#getUserMetadata() metadata}, and an access\n * control policy.\n */\npublic interface ObjectMetadata extends Comparable<ObjectMetadata> {\n\n   public enum StorageClass {\n      STANDARD(Tier.STANDARD),\n      STANDARD_IA(Tier.COOL),\n      ONEZONE_IA(Tier.COOL),\n      INTELLIGENT_TIERING(Tier.STANDARD),\n      REDUCED_REDUNDANCY(Tier.STANDARD),\n      GLACIER(Tier.ARCHIVE),\n      GLACIER_IR(Tier.COLD),\n      DEEP_ARCHIVE(Tier.ARCHIVE);\n\n      private final Tier tier;\n\n      private StorageClass(Tier tier) {\n         this.tier = checkNotNull(tier, \"tier\");\n      }\n\n      public static StorageClass fromTier(Tier tier) {\n         switch (tier) {\n         case STANDARD: return StorageClass.STANDARD;\n         case INFREQUENT: return StorageClass.STANDARD_IA;\n         case COOL: return StorageClass.STANDARD_IA;\n         case COLD: return StorageClass.GLACIER_IR;\n         case ARCHIVE: return StorageClass.DEEP_ARCHIVE;\n         }\n         throw new IllegalArgumentException(\"invalid tier: \" + tier);\n      }\n\n      public Tier toTier() {\n         return tier;\n      }\n   }\n\n   /**\n    * The key is the handle that you assign to an object that allows you retrieve it later. A key is\n    * a sequence of Unicode characters whose UTF-8 encoding is at most 1024 bytes long. Each object\n    * in a bucket must have a unique key.\n    * \n    * @see <a href= \"http://docs.amazonwebservices.com/AmazonHTTP/2006-03-01/UsingKeys.html\" />\n    */\n   String getKey();\n\n   String getBucket();\n\n   URI getUri();\n\n   /**\n    * Every bucket and object in Amazon S3 has an owner, the user that created the bucket or object.\n    * The owner of a bucket or object cannot be changed. However, if the object is overwritten by\n    * another user (deleted and rewritten), the new object will have a new owner.\n    */\n   CanonicalUser getOwner();\n\n   /**\n    * Currently defaults to 'STANDARD' and not used.\n    */\n   StorageClass getStorageClass();\n\n   /**\n    * Can be used to specify caching behavior along the request/reply chain.\n    * \n    * @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html?sec14.9.\n    *\n    * @deprecated call getContentMetadata().getCacheControl() instead\n    */\n   @Deprecated\n   String getCacheControl();\n\n   Date getLastModified();\n\n   String getETag();\n\n   Map<String, String> getUserMetadata();\n\n   ContentMetadata getContentMetadata();\n\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/domain/ObjectMetadataBuilder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.domain;\n\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.Map;\n\nimport org.jclouds.io.ContentMetadataBuilder;\nimport org.jclouds.io.payloads.BaseMutableContentMetadata;\nimport org.jclouds.s3.domain.ObjectMetadata.StorageClass;\nimport org.jclouds.s3.domain.internal.MutableObjectMetadataImpl;\n\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Allows you to create {@link ObjectMetadata} objects.\n */\npublic class ObjectMetadataBuilder {\n   public static ObjectMetadataBuilder create() {\n      return new ObjectMetadataBuilder();\n   }\n\n   private final ContentMetadataBuilder contentMetadataBuilder = new ContentMetadataBuilder()\n            .contentType(\"binary/octet-stream\");\n\n   private String key;\n   private String bucket;\n   private URI uri;\n   private StorageClass storageClass = StorageClass.STANDARD;\n   private Date lastModified;\n   private String eTag;\n   private CanonicalUser owner;\n   private Map<String, String> userMetadata = ImmutableMap.of();\n\n   public ObjectMetadataBuilder key(String key) {\n      this.key = key;\n      return this;\n   }\n\n   public ObjectMetadataBuilder bucket(String bucket) {\n      this.bucket = bucket;\n      return this;\n   }\n\n   public ObjectMetadataBuilder owner(CanonicalUser owner) {\n      this.owner = owner;\n      return this;\n   }\n\n   public ObjectMetadataBuilder eTag(String eTag) {\n      this.eTag = eTag;\n      return this;\n   }\n\n   public ObjectMetadataBuilder uri(URI uri) {\n      this.uri = uri;\n      return this;\n   }\n\n   public ObjectMetadataBuilder lastModified(Date lastModified) {\n      this.lastModified = lastModified;\n      return this;\n   }\n\n   public ObjectMetadataBuilder storageClass(StorageClass storageClass) {\n      this.storageClass = storageClass;\n      return this;\n   }\n\n   public ObjectMetadataBuilder cacheControl(String cacheControl) {\n      contentMetadataBuilder.cacheControl(cacheControl);\n      return this;\n   }\n\n   public ObjectMetadataBuilder userMetadata(Map<String, String> userMetadata) {\n      this.userMetadata = ImmutableMap.copyOf(userMetadata);\n      return this;\n   }\n\n   public ObjectMetadataBuilder contentDisposition(String contentDisposition) {\n      contentMetadataBuilder.contentDisposition(contentDisposition);\n      return this;\n   }\n\n   public ObjectMetadataBuilder contentEncoding(String contentEncoding) {\n      contentMetadataBuilder.contentEncoding(contentEncoding);\n      return this;\n\n   }\n\n   public ObjectMetadataBuilder contentLanguage(String contentLanguage) {\n      contentMetadataBuilder.contentLanguage(contentLanguage);\n      return this;\n\n   }\n\n   public ObjectMetadataBuilder contentLength(Long contentLength) {\n      contentMetadataBuilder.contentLength(contentLength);\n      return this;\n\n   }\n\n   public ObjectMetadataBuilder contentMD5(byte[] md5) {\n      contentMetadataBuilder.contentMD5(md5);\n      return this;\n\n   }\n\n   public ObjectMetadataBuilder contentType(String contentType) {\n      contentMetadataBuilder.contentType(contentType);\n      return this;\n   }\n\n   public ObjectMetadata build() {\n      MutableObjectMetadataImpl toReturn = new MutableObjectMetadataImpl();\n      toReturn.setContentMetadata(BaseMutableContentMetadata.fromContentMetadata(contentMetadataBuilder.build()));\n      toReturn.setKey(key);\n      toReturn.setBucket(bucket);\n      toReturn.setUri(uri);\n      toReturn.setETag(eTag);\n      toReturn.setOwner(owner);\n      toReturn.setStorageClass(storageClass);\n      toReturn.setUserMetadata(userMetadata);\n      toReturn.setLastModified(lastModified);\n      return toReturn;\n   }\n\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/domain/Payer.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.domain;\n\nimport com.google.common.base.CaseFormat;\n\n/**\n * Specifies who pays for the download and request fees.\n * <p/>\n * In general, bucket owners pay for all Amazon S3 storage and data transfer costs associated with\n * their bucket. A bucket owner, however, can configure a bucket to be a Requester Pays bucket. With\n * Requester Pays buckets, the requester instead of the bucket owner pays the cost of the request\n * and the data download from the bucket. The bucket owner always pays the cost of storing data.\n * <p/>\n * Typically, you configure buckets to be Requester Pays when you want to share data but not incur\n * charges associated with others accessing the data. You might, for example, use Requester Pays\n * buckets when making available large data sets, such as zip code directories, reference data,\n * geospatial information, or web crawling data.\n * <h3>Important</h3> If you enable Requester Pays on a bucket, anonymous access to that bucket is\n * not allowed.\n * <p/>\n * You must authenticate all requests involving Requester Pays buckets. The request authentication\n * enables Amazon S3 to identify and charge the requester for their use of the Requester Pays\n * bucket.\n * <p/>\n * After you configure a bucket to be a Requester Pays bucket, requesters must include\n * x-amz-request-payer in their requests either in the header, for POST and GET requests, or as a\n * parameter in a REST request to show that they understand that they will be charged for the\n * request and the data download.\n * <p/>\n * Requester Pays buckets do not support the following.\n * <ul>\n * <li>Anonymous requests</li>\n * <li>BitTorrent</li>\n * <li>SOAP requests</li>\n * </ul>\n * \n * You cannot use a Requester Pays bucket as the target bucket for end user logging, or vice versa.\n * However, you can turn on end user logging on a Requester Pays bucket where the target bucket is a\n * non Requester Pays bucket.\n */\npublic enum Payer {\n   REQUESTER, BUCKET_OWNER, UNRECOGNIZED;\n\n   public String value() {\n      return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name());\n   }\n\n   public static Payer fromValue(String payer) {\n      try {\n         return valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, payer));\n      } catch (IllegalArgumentException e) {\n         return UNRECOGNIZED;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/domain/PublicAccessBlockConfiguration.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.domain;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.annotations.Beta;\n\n@AutoValue\n@Beta\npublic abstract class PublicAccessBlockConfiguration {\n   public abstract boolean blockPublicAcls();\n   public abstract boolean ignorePublicAcls();\n   public abstract boolean blockPublicPolicy();\n   public abstract boolean restrictPublicBuckets();\n\n   public static PublicAccessBlockConfiguration create(boolean blockPublicAcls, boolean ignorePublicAcls, boolean blockPublicPolicy, boolean restrictPublicBuckets) {\n      return new AutoValue_PublicAccessBlockConfiguration(blockPublicAcls, ignorePublicAcls, blockPublicPolicy, restrictPublicBuckets);\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/domain/S3Object.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.domain;\n\nimport org.jclouds.io.PayloadEnclosing;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.collect.Multimap;\n\n/**\n * Amazon S3 is designed to store objects. Objects are stored in buckets and consist of a\n * {@link PayloadEnclosing#getPayload() value}, a {@link ObjectMetadata#getKey key},\n * {@link ObjectMetadata#getUserMetadata() metadata}, and an access control policy.\n */\npublic interface S3Object extends PayloadEnclosing, Comparable<S3Object> {\n   public interface Factory {\n      S3Object create(@Nullable MutableObjectMetadata metadata);\n   }\n\n   /**\n    * @return System and User metadata relevant to this object.\n    */\n   MutableObjectMetadata getMetadata();\n\n   Multimap<String, String> getAllHeaders();\n\n   void setAccessControlList(AccessControlList acl);\n\n   AccessControlList getAccessControlList();\n\n   void setAllHeaders(Multimap<String, String> allHeaders);\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/domain/internal/BucketListObjectMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.domain.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.Map;\n\nimport org.jclouds.io.ContentMetadata;\nimport org.jclouds.io.payloads.BaseImmutableContentMetadata;\nimport org.jclouds.s3.domain.CanonicalUser;\nimport org.jclouds.s3.domain.ObjectMetadata;\n\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Returns the metadata parsable from a bucket listing\n */\npublic class BucketListObjectMetadata implements ObjectMetadata {\n\n   private final String key;\n   private final String bucket;\n   private final URI uri;\n   private final Date lastModified;\n   private final String eTag;\n   private final CanonicalUser owner;\n   private final StorageClass storageClass;\n   private final ContentMetadata contentMetadata;\n\n   public BucketListObjectMetadata(String key, String bucket, URI uri, Date lastModified, String eTag, byte[] md5,\n            long contentLength, CanonicalUser owner, StorageClass storageClass) {\n      this.key = checkNotNull(key, \"key\");\n      this.bucket = checkNotNull(bucket, \"bucket\");\n      this.uri = checkNotNull(uri, \"uri\");\n      this.lastModified = lastModified;\n      this.eTag = eTag;\n      this.owner = owner;\n      this.contentMetadata = new BaseImmutableContentMetadata(null, contentLength, md5, null, null, null, null);\n      this.storageClass = storageClass;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public URI getUri() {\n      return uri;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public String getKey() {\n      return key;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public String getBucket() {\n      return bucket;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public CanonicalUser getOwner() {\n      return owner;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public StorageClass getStorageClass() {\n      return storageClass;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public String getCacheControl() {\n      return null;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public Date getLastModified() {\n      return lastModified;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public String getETag() {\n      return eTag;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public int compareTo(ObjectMetadata o) {\n      return (this == o) ? 0 : getUri().compareTo(o.getUri());\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public Map<String, String> getUserMetadata() {\n      return ImmutableMap.of();\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public ContentMetadata getContentMetadata() {\n      return contentMetadata;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((uri == null) ? 0 : uri.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      BucketListObjectMetadata other = (BucketListObjectMetadata) obj;\n      if (uri == null) {\n         if (other.uri != null)\n            return false;\n      } else if (!uri.equals(other.uri))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return String.format(\n               \"[uri=%s, key=%s, bucket=%s, contentMetadata=%s, eTag=%s, lastModified=%s, owner=%s, storageClass=%s]\",\n               uri, key, bucket, contentMetadata, eTag, lastModified, owner, storageClass);\n   }\n\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/domain/internal/CopyObjectResult.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.domain.internal;\n\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.Map;\n\nimport org.jclouds.io.ContentMetadata;\nimport org.jclouds.io.payloads.BaseImmutableContentMetadata;\nimport org.jclouds.s3.domain.CanonicalUser;\nimport org.jclouds.s3.domain.ObjectMetadata;\n\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Returns the metadata parsable from a bucket listing\n */\npublic class CopyObjectResult implements ObjectMetadata {\n\n   private final Date lastModified;\n   private final String eTag;\n   private final BaseImmutableContentMetadata contentMetadata;\n\n   public CopyObjectResult(Date lastModified, String eTag) {\n      this.lastModified = lastModified;\n      this.eTag = eTag;\n      this.contentMetadata = new BaseImmutableContentMetadata(null, null, null, null, null, null, null);\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public String getKey() {\n      return null;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public String getBucket() {\n      return null;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public URI getUri() {\n      return null;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public CanonicalUser getOwner() {\n      return null;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public StorageClass getStorageClass() {\n      return null;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public String getCacheControl() {\n      return null;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public Date getLastModified() {\n      return lastModified;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public String getETag() {\n      return eTag;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public int compareTo(ObjectMetadata o) {\n      return (this == o) ? 0 : getETag().compareTo(o.getETag());\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public Map<String, String> getUserMetadata() {\n      return ImmutableMap.of();\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public ContentMetadata getContentMetadata() {\n      return contentMetadata;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((eTag == null) ? 0 : eTag.hashCode());\n      result = prime * result + ((lastModified == null) ? 0 : lastModified.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      CopyObjectResult other = (CopyObjectResult) obj;\n      if (eTag == null) {\n         if (other.eTag != null)\n            return false;\n      } else if (!eTag.equals(other.eTag))\n         return false;\n      if (lastModified == null) {\n         if (other.lastModified != null)\n            return false;\n      } else if (!lastModified.equals(other.lastModified))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return String.format(\"[eTag=%s, lastModified=%s]\", eTag, lastModified);\n   }\n\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/domain/internal/ListBucketResponseImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.domain.internal;\n\nimport java.util.LinkedHashSet;\nimport java.util.Set;\n\nimport org.jclouds.s3.domain.ListBucketResponse;\nimport org.jclouds.s3.domain.ObjectMetadata;\n\nimport com.google.common.collect.Iterables;\n\npublic class ListBucketResponseImpl extends LinkedHashSet<ObjectMetadata> implements ListBucketResponse {\n\n   protected final String name;\n   protected final String prefix;\n   protected final int maxKeys;\n   protected final String delimiter;\n   protected final String marker;\n   protected final String nextMarker;\n   protected final Set<String> commonPrefixes;\n   protected final boolean truncated;\n\n   public ListBucketResponseImpl(String name, Iterable<ObjectMetadata> contents, String prefix, String marker,\n            String nextMarker, int maxKeys, String delimiter, boolean isTruncated, Set<String> commonPrefixes) {\n      Iterables.addAll(this, contents);\n      this.name = name;\n      this.prefix = prefix;\n      this.marker = marker;\n      this.nextMarker = nextMarker;\n      this.maxKeys = maxKeys;\n      this.truncated = isTruncated;\n      this.delimiter = delimiter;\n      this.commonPrefixes = commonPrefixes;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Set<String> getCommonPrefixes() {\n      return commonPrefixes;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getDelimiter() {\n      return delimiter;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getMarker() {\n      return marker;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getNextMarker() {\n      return nextMarker;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public int getMaxKeys() {\n      return maxKeys;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getPrefix() {\n      return prefix;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public boolean isTruncated() {\n      return truncated;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getName() {\n      return name;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = super.hashCode();\n      result = prime * result + ((commonPrefixes == null) ? 0 : commonPrefixes.hashCode());\n      result = prime * result + ((delimiter == null) ? 0 : delimiter.hashCode());\n      result = prime * result + ((marker == null) ? 0 : marker.hashCode());\n      result = prime * result + maxKeys;\n      result = prime * result + ((name == null) ? 0 : name.hashCode());\n      result = prime * result + ((prefix == null) ? 0 : prefix.hashCode());\n      result = prime * result + (truncated ? 1231 : 1237);\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (!super.equals(obj))\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      ListBucketResponseImpl other = (ListBucketResponseImpl) obj;\n      if (commonPrefixes == null) {\n         if (other.commonPrefixes != null)\n            return false;\n      } else if (!commonPrefixes.equals(other.commonPrefixes))\n         return false;\n      if (delimiter == null) {\n         if (other.delimiter != null)\n            return false;\n      } else if (!delimiter.equals(other.delimiter))\n         return false;\n      if (marker == null) {\n         if (other.marker != null)\n            return false;\n      } else if (!marker.equals(other.marker))\n         return false;\n      if (maxKeys != other.maxKeys)\n         return false;\n      if (name == null) {\n         if (other.name != null)\n            return false;\n      } else if (!name.equals(other.name))\n         return false;\n      if (prefix == null) {\n         if (other.prefix != null)\n            return false;\n      } else if (!prefix.equals(other.prefix))\n         return false;\n      if (truncated != other.truncated)\n         return false;\n      return true;\n   }\n\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/domain/internal/MutableObjectMetadataImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.domain.internal;\n\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.Map;\n\nimport org.jclouds.http.HttpUtils;\nimport org.jclouds.io.MutableContentMetadata;\nimport org.jclouds.io.payloads.BaseMutableContentMetadata;\nimport org.jclouds.s3.domain.CanonicalUser;\nimport org.jclouds.s3.domain.MutableObjectMetadata;\nimport org.jclouds.s3.domain.ObjectMetadata;\n\nimport com.google.common.collect.Maps;\n\n/**\n * Allows you to manipulate metadata.\n */\npublic class MutableObjectMetadataImpl implements MutableObjectMetadata {\n\n   private String key;\n   private String bucket;\n   private URI uri;\n   private Date lastModified;\n   private String eTag;\n   private CanonicalUser owner;\n   private StorageClass storageClass;\n   private String cacheControl;\n   private Map<String, String> userMetadata = Maps.newHashMap();\n   private MutableContentMetadata contentMetadata;\n\n   public MutableObjectMetadataImpl() {\n      this.storageClass = StorageClass.STANDARD;\n      this.contentMetadata = new BaseMutableContentMetadata();\n   }\n\n   public MutableObjectMetadataImpl(ObjectMetadata from) {\n      this.storageClass = StorageClass.STANDARD;\n      this.contentMetadata = new BaseMutableContentMetadata();\n      HttpUtils.copy(from.getContentMetadata(), this.contentMetadata);\n      this.key = from.getKey();\n      this.uri = from.getUri();\n      this.bucket = from.getBucket();\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public String getKey() {\n      return key;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public String getBucket() {\n      return bucket;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public URI getUri() {\n      return uri;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public void setUri(URI uri) {\n      this.uri = uri;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public CanonicalUser getOwner() {\n      return owner;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public StorageClass getStorageClass() {\n      return storageClass;\n   }\n\n   /**\n    * @deprecated call getContentMetadata().getCacheControl() instead\n    */\n   @Deprecated\n   @Override\n   public String getCacheControl() {\n      return contentMetadata.getCacheControl();\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public Date getLastModified() {\n      return lastModified;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public String getETag() {\n      return eTag;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public int compareTo(ObjectMetadata o) {\n      return (this == o) ? 0 : getKey().compareTo(o.getKey());\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public Map<String, String> getUserMetadata() {\n      return userMetadata;\n   }\n\n   /**\n    * @deprecated call getContentMetadata().setCacheControl(String) instead\n    */\n   @Deprecated\n   @Override\n   public void setCacheControl(String cacheControl) {\n      contentMetadata.setCacheControl(cacheControl);\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public void setETag(String eTag) {\n      this.eTag = eTag;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public void setKey(String key) {\n      this.key = key;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public void setBucket(String bucket) {\n      this.bucket = bucket;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public void setLastModified(Date lastModified) {\n      this.lastModified = lastModified;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public void setOwner(CanonicalUser owner) {\n      this.owner = owner;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public void setStorageClass(StorageClass storageClass) {\n      this.storageClass = storageClass;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public void setUserMetadata(Map<String, String> userMetadata) {\n      this.userMetadata = userMetadata;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public MutableContentMetadata getContentMetadata() {\n      return contentMetadata;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void setContentMetadata(MutableContentMetadata contentMetadata) {\n      this.contentMetadata = contentMetadata;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((uri == null) ? 0 : uri.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      MutableObjectMetadataImpl other = (MutableObjectMetadataImpl) obj;\n      if (uri == null) {\n         if (other.uri != null)\n            return false;\n      } else if (!uri.equals(other.uri))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return String\n               .format(\n                        \"[key=%s, bucket=%s, uri=%s, eTag=%s, cacheControl=%s, contentMetadata=%s, lastModified=%s, owner=%s, storageClass=%s, userMetadata=%s]\",\n                        key, bucket, uri, eTag, cacheControl, contentMetadata, lastModified, owner, storageClass,\n                        userMetadata);\n   }\n\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/domain/internal/S3ObjectImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.domain.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.http.internal.PayloadEnclosingImpl;\nimport org.jclouds.io.Payload;\nimport org.jclouds.s3.domain.AccessControlList;\nimport org.jclouds.s3.domain.MutableObjectMetadata;\nimport org.jclouds.s3.domain.S3Object;\n\nimport com.google.common.collect.LinkedHashMultimap;\nimport com.google.common.collect.Multimap;\n\n/**\n * Default Implementation of {@link S3Object}.\n */\npublic class S3ObjectImpl extends PayloadEnclosingImpl implements S3Object, Comparable<S3Object> {\n\n   private AccessControlList accessControlList;\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void setAccessControlList(AccessControlList acl) {\n      this.accessControlList = acl;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public AccessControlList getAccessControlList() {\n      return this.accessControlList;\n   }\n\n   private final MutableObjectMetadata metadata;\n   private Multimap<String, String> allHeaders = LinkedHashMultimap.create();\n\n   @Inject\n   public S3ObjectImpl(MutableObjectMetadata metadata) {\n      super();\n      this.metadata = metadata;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public MutableObjectMetadata getMetadata() {\n      return metadata;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Multimap<String, String> getAllHeaders() {\n      return allHeaders;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void setAllHeaders(Multimap<String, String> allHeaders) {\n      this.allHeaders = checkNotNull(allHeaders, \"allHeaders\");\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public int compareTo(S3Object o) {\n      if (getMetadata().getKey() == null)\n         return -1;\n      return (this == o) ? 0 : getMetadata().getKey().compareTo(o.getMetadata().getKey());\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = super.hashCode();\n      result = prime * result + ((metadata == null) ? 0 : metadata.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (!super.equals(obj))\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      S3ObjectImpl other = (S3ObjectImpl) obj;\n      if (metadata == null) {\n         if (other.metadata != null)\n            return false;\n      } else if (!metadata.equals(other.metadata))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"[metadata=\" + metadata + \"]\";\n   }\n\n   @Override\n   public void setPayload(Payload data) {\n      super.setPayload(data);\n      metadata.setContentMetadata(data.getContentMetadata());\n   }\n\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/domain/package-info.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * This package contains the core components of S3. \n */\npackage org.jclouds.s3.domain;\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/fallbacks/FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.fallbacks;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Throwables.propagate;\nimport static org.jclouds.s3.util.S3Utils.getBucketName;\nimport static org.jclouds.util.Throwables2.getFirstThrowableOfType;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.Fallback;\nimport org.jclouds.aws.AWSResponseException;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.rest.InvocationContext;\nimport org.jclouds.s3.S3Client;\n\npublic class FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists implements Fallback<Boolean>,\n      InvocationContext<FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists> {\n\n   private final S3Client client;\n   private String bucket;\n\n   @Inject\n   FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists(S3Client client) {\n      this.client = client;\n   }\n\n   @Override\n   public Boolean createOrPropagate(Throwable t) throws Exception {\n      AWSResponseException exception = getFirstThrowableOfType(checkNotNull(t, \"throwable\"), AWSResponseException.class);\n      if (exception != null && exception.getError() != null && exception.getError().getCode() != null) {\n         String code = exception.getError().getCode();\n         if (code.equals(\"BucketAlreadyOwnedByYou\"))\n            return false;\n         else if (code.equals(\"OperationAborted\") && bucket != null && client.bucketExists(bucket))\n            return false;\n      }\n      throw propagate(t);\n   }\n\n   @Override\n   public FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists setContext(@Nullable HttpRequest request) {\n      if (request != null)\n         this.bucket = getBucketName(request);\n      return this;\n   }\n\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/filters/Aws4SignerBase.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.filters;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.io.BaseEncoding.base16;\nimport static com.google.common.io.ByteStreams.readBytes;\nimport static org.jclouds.crypto.Macs.asByteProcessor;\nimport static org.jclouds.http.utils.Queries.queryParser;\nimport static org.jclouds.util.Strings2.toInputStream;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.net.URI;\nimport java.security.InvalidKeyException;\nimport java.text.DateFormat;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\nimport java.util.Iterator;\nimport java.util.Locale;\nimport java.util.Map;\nimport java.util.SortedMap;\nimport java.util.TimeZone;\n\nimport jakarta.inject.Inject;\n\nimport com.google.common.base.Joiner;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSortedMap;\nimport com.google.common.collect.Maps;\nimport com.google.common.collect.Multimap;\nimport com.google.common.escape.Escaper;\nimport com.google.common.hash.Hashing;\nimport com.google.common.hash.HashingInputStream;\nimport com.google.common.io.ByteProcessor;\nimport com.google.common.io.ByteSource;\nimport com.google.common.io.ByteStreams;\nimport com.google.common.net.HttpHeaders;\nimport com.google.common.net.PercentEscaper;\nimport com.google.inject.ImplementedBy;\nimport org.jclouds.crypto.Crypto;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.internal.SignatureWire;\nimport org.jclouds.io.Payload;\nimport org.jclouds.providers.ProviderMetadata;\n\n/**\n * Common methods and properties for all AWS4 signer variants\n */\npublic abstract class Aws4SignerBase {\n   private static final TimeZone GMT = TimeZone.getTimeZone(\"GMT\");\n   protected final DateFormat timestampFormat;\n   protected final DateFormat dateFormat;\n\n   // Do not URL-encode any of the unreserved characters that RFC 3986 defines:\n   // A-Z, a-z, 0-9, hyphen (-), underscore (_), period (.), and tilde (~).\n   private static final Escaper AWS_URL_PARAMETER_ESCAPER = new PercentEscaper(\"-_.~\", false);\n\n   private static final Escaper AWS_PATH_ESCAPER = new PercentEscaper(\"/-_.~\", false);\n\n   // Specifying a default for how to parse the service and region in this way allows\n   // tests or other downstream services to not have to use guice overrides.\n   @ImplementedBy(ServiceAndRegion.AWSServiceAndRegion.class)\n   public interface ServiceAndRegion {\n      String service();\n\n      String region(String host);\n\n      final class AWSServiceAndRegion implements ServiceAndRegion {\n         private final String service;\n\n         @Inject\n         AWSServiceAndRegion(ProviderMetadata provider) {\n            this(provider.getEndpoint());\n         }\n\n         AWSServiceAndRegion(String endpoint) {\n            this.service = AwsHostNameUtils.parseServiceName(URI.create(checkNotNull(endpoint, \"endpoint\")));\n         }\n\n         @Override\n         public String service() {\n            return service;\n         }\n\n         @Override\n         public String region(String host) {\n            return AwsHostNameUtils.parseRegionName(host, service());\n         }\n      }\n   }\n\n   protected final String headerTag;\n   protected final ServiceAndRegion serviceAndRegion;\n   protected final SignatureWire signatureWire;\n   protected final Supplier<Credentials> creds;\n   protected final Supplier<Date> timestampProvider;\n   protected final Crypto crypto;\n\n\n   protected Aws4SignerBase(SignatureWire signatureWire, String headerTag,\n         Supplier<Credentials> creds, Supplier<Date> timestampProvider,\n         ServiceAndRegion serviceAndRegion, Crypto crypto) {\n      this.signatureWire = signatureWire;\n      this.headerTag = headerTag;\n      this.creds = creds;\n      this.timestampProvider = timestampProvider;\n      this.serviceAndRegion = serviceAndRegion;\n      this.crypto = crypto;\n      this.timestampFormat = new SimpleDateFormat(\"yyyyMMdd'T'HHmmss'Z'\");\n      timestampFormat.setTimeZone(GMT);\n      this.dateFormat = new SimpleDateFormat(\"yyyyMMdd\");\n      dateFormat.setTimeZone(GMT);\n   }\n\n   protected static String hostHeaderFor(URI endpoint) {\n      String scheme = endpoint.getScheme();\n      String host = endpoint.getHost();\n      int port = endpoint.getPort();\n\n      // if the port is defined and doesn't match the URI scheme\n      if (port != -1) {\n         if ((\"http\".equalsIgnoreCase(scheme) && port != 80) ||\n                 (\"https\".equalsIgnoreCase(scheme) && port != 443)) {\n            host += \":\" + port; // append the port number to the hostname\n         }\n      }\n\n      return host; // else just use the original hostname\n   }\n\n   protected String getContentType(HttpRequest request) {\n      Payload payload = request.getPayload();\n\n      // Default Content Type\n      String contentType = request.getFirstHeaderOrNull(HttpHeaders.CONTENT_TYPE);\n      if (payload != null\n            && payload.getContentMetadata() != null\n            && payload.getContentMetadata().getContentType() != null) {\n         contentType = payload.getContentMetadata().getContentType();\n      }\n      return contentType;\n   }\n\n   protected String getContentLength(HttpRequest request) {\n      Payload payload = request.getPayload();\n\n      // Default Content Type\n      String contentLength = request.getFirstHeaderOrNull(HttpHeaders.CONTENT_LENGTH);\n      if (payload != null\n            && payload.getContentMetadata() != null\n            && payload.getContentMetadata().getContentType() != null) {\n         Long length = payload.getContentMetadata().getContentLength();\n         contentLength =\n               length == null ? contentLength : String.valueOf(payload.getContentMetadata().getContentLength());\n      }\n      return contentLength;\n   }\n\n   // append all of 'x-amz-*' headers\n   protected void appendAmzHeaders(HttpRequest request,\n         ImmutableMap.Builder<String, String> signedHeadersBuilder) {\n      for (Map.Entry<String, String> header : request.getHeaders().entries()) {\n         String key = header.getKey();\n         if (key.startsWith(\"x-\" + headerTag + \"-\")) {\n            signedHeadersBuilder.put(key.toLowerCase(), header.getValue());\n         }\n      }\n   }\n\n   /**\n    * caluclate AWS signature key.\n    * <p>\n    * <code>\n    * DateKey = hmacSHA256(datestamp, \"AWS4\"+ secretKey)\n    * <br>\n    * DateRegionKey = hmacSHA256(region, DateKey)\n    * <br>\n    * DateRegionServiceKey = hmacSHA256(service, DateRegionKey)\n    * <br>\n    * SigningKey = hmacSHA256(\"aws4_request\", DateRegionServiceKey)\n    * <br>\n    * <p/>\n    * </code>\n    * </p>\n    *\n    * @param secretKey AWS access secret key\n    * @param datestamp date yyyyMMdd\n    * @param region   AWS region\n    * @param service   AWS service\n    * @return SigningKey\n    */\n   protected byte[] signatureKey(String secretKey, String datestamp, String region, String service) {\n      byte[] kSecret = (\"AWS4\" + secretKey).getBytes(UTF_8);\n      byte[] kDate = hmacSHA256(datestamp, kSecret);\n      byte[] kRegion = hmacSHA256(region, kDate);\n      byte[] kService = hmacSHA256(service, kRegion);\n      byte[] kSigning = hmacSHA256(\"aws4_request\", kService);\n      return kSigning;\n   }\n\n   /**\n    * hmac sha256\n    *\n    * @param toSign string to sign\n    * @param key   hash key\n    */\n   protected byte[] hmacSHA256(String toSign, byte[] key) {\n      try {\n         return readBytes(toInputStream(toSign), hmacSHA256(crypto, key));\n      } catch (IOException e) {\n         throw new HttpException(\"read sign error\", e);\n      } catch (InvalidKeyException e) {\n         throw new HttpException(\"invalid key\", e);\n      }\n   }\n\n   public static ByteProcessor<byte[]> hmacSHA256(Crypto crypto, byte[] signatureKey) throws InvalidKeyException {\n      return asByteProcessor(crypto.hmacSHA256(signatureKey));\n   }\n\n   /**\n    * hash input with sha256\n    *\n    * @param input\n    * @return hash result\n    * @throws HttpException\n    */\n   public static byte[] hash(InputStream input) throws HttpException {\n      HashingInputStream his = new HashingInputStream(Hashing.sha256(), input);\n      try {\n         ByteStreams.copy(his, ByteStreams.nullOutputStream());\n         return his.hash().asBytes();\n      } catch (IOException e) {\n         throw new HttpException(\"Unable to compute hash while signing request: \" + e.getMessage(), e);\n      }\n   }\n\n   /**\n    * hash input with sha256\n    *\n    * @param bytes input bytes\n    * @return hash result\n    * @throws HttpException\n    */\n   public static byte[] hash(byte[] bytes) throws HttpException {\n      try {\n         return ByteSource.wrap(bytes).hash(Hashing.sha256()).asBytes();\n      } catch (IOException e) {\n         throw new HttpException(\"Unable to compute hash while signing request: \" + e.getMessage(), e);\n      }\n   }\n\n   /**\n    * hash string (encoding UTF_8) with sha256\n    *\n    * @param input input stream\n    * @return hash result\n    * @throws HttpException\n    */\n   public static byte[] hash(String input) throws HttpException {\n      return hash(new ByteArrayInputStream(input.getBytes(UTF_8)));\n   }\n\n   /**\n    * Examines the specified query string parameters and returns a\n    * canonicalized form.\n    * <p/>\n    * The canonicalized query string is formed by first sorting all the query\n    * string parameters, then URI encoding both the key and value and then\n    * joining them, in order, separating key value pairs with an '&'.\n    *\n    * @param queryString The query string parameters to be canonicalized.\n    * @return A canonicalized form for the specified query string parameters.\n    */\n   protected String getCanonicalizedQueryString(String queryString) {\n      Multimap<String, String> params = queryParser().apply(queryString);\n      SortedMap<String, String> sorted = Maps.newTreeMap();\n      if (params == null) {\n         return \"\";\n      }\n      Iterator<Map.Entry<String, String>> pairs = params.entries().iterator();\n      while (pairs.hasNext()) {\n         Map.Entry<String, String> pair = pairs.next();\n         String key = pair.getKey();\n         String value = pair.getValue();\n         sorted.put(urlEncode(key), urlEncode(value));\n      }\n\n      return Joiner.on(\"&\").withKeyValueSeparator(\"=\").join(sorted);\n   }\n\n   /**\n    * Encode a string for use in the path of a URL; uses URLEncoder.encode,\n    * (which encodes a string for use in the query portion of a URL), then\n    * applies some postfilters to fix things up per the RFC. Can optionally\n    * handle strings which are meant to encode a path (ie include '/'es\n    * which should NOT be escaped).\n    *\n    * @param value the value to encode\n    * @return the encoded value\n    */\n   public static String urlEncode(final String value) {\n      if (value == null) {\n         return \"\";\n      }\n      return AWS_URL_PARAMETER_ESCAPER.escape(value);\n   }\n\n   /**\n    * Lowercase base 16 encoding.\n    *\n    * @param bytes bytes\n    * @return base16 lower case hex string.\n    */\n   public static String hex(final byte[] bytes) {\n      return base16().lowerCase().encode(bytes);\n   }\n\n   /**\n    * Create a Canonical Request to sign\n    * <h4>Canonical Request</h4>\n    * <p>\n    * <code>\n    * &lt;HTTPMethod>\\n\n    * <br>\n    * &lt;CanonicalURI>\\n\n    * <br>\n    * &lt;CanonicalQueryString>\\n\n    * <br>\n    * &lt;CanonicalHeaders>\\n\n    * <br>\n    * &lt;SignedHeaders>\\n\n    * <br>\n    * &lt;HashedPayload>\n    * </code>\n    * </p>\n    * <p><b>HTTPMethod</b> is one of the HTTP methods, for example GET, PUT, HEAD, and DELETE.</p>\n    * <p><b>CanonicalURI</b> is the URI-encoded version of the absolute path component of the URI—everything starting\n    * with the \"/\" that follows the domain name and up to the end of the string or to the question mark character ('?')\n    * if you have query string parameters.</p>\n    * <p><b>CanonicalQueryString</b> specifies the URI-encoded query string parameters. You URI-encode name and values\n    * individually. You must also sort the parameters in the canonical query string alphabetically by key name.\n    * The sorting occurs after encoding.</p>\n    * <p><b>CanonicalHeaders</b> is a list of request headers with their values. Individual header name and value pairs are\n    * separated by the newline character (\"\\n\"). Header names must be in lowercase. Header value must be trim space.\n    * <br>\n    * The <b>CanonicalHeaders</b> list must include the following:\n    * HTTP host header.\n    * If the Content-Type header is present in the request, it must be added to the CanonicalHeaders list.\n    * Any x-amz-* headers that you plan to include in your request must also be added.</p>\n    * <p><b>SignedHeaders</b> is an alphabetically sorted, semicolon-separated list of lowercase request header names.\n    * The request headers in the list are the same headers that you included in the CanonicalHeaders string.</p>\n    * <p><b>HashedPayload</b> is the hexadecimal value of the SHA256 hash of the request payload. </p>\n    * <p>If there is no payload in the request, you compute a hash of the empty string as follows:\n    * <code>Hex(SHA256Hash(\"\"))</code> The hash returns the following value:\n    * e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855  </p>\n    *\n    * @param method           http request method\n    * @param endpoint         http request endpoing\n    * @param signedHeaders    signed headers\n    * @param timestamp        ISO8601 timestamp\n    * @param credentialScope  credential scope\n    * @return string to sign\n    */\n   protected String createStringToSign(String method, URI endpoint, Map<String, String> signedHeaders,\n         String timestamp, String credentialScope, String hashedPayload) {\n\n      // lower case header keys\n      Map<String, String> lowerCaseHeaders = lowerCaseNaturalOrderKeys(signedHeaders);\n\n      StringBuilder canonicalRequest = new StringBuilder();\n\n      // HTTPRequestMethod + '\\n' +\n      canonicalRequest.append(method).append(\"\\n\");\n\n      // CanonicalURI + '\\n' +\n      canonicalRequest.append(AWS_PATH_ESCAPER.escape(endpoint.getPath())).append(\"\\n\");\n\n      // CanonicalQueryString + '\\n' +\n      if (endpoint.getQuery() != null) {\n         canonicalRequest.append(getCanonicalizedQueryString(endpoint.getRawQuery()));\n      }\n      canonicalRequest.append(\"\\n\");\n\n      // CanonicalHeaders + '\\n' +\n      for (Map.Entry<String, String> entry : lowerCaseHeaders.entrySet()) {\n         canonicalRequest.append(entry.getKey()).append(':').append(entry.getValue()).append('\\n');\n      }\n      canonicalRequest.append(\"\\n\");\n\n      // SignedHeaders + '\\n' +\n      canonicalRequest.append(Joiner.on(';').join(lowerCaseHeaders.keySet())).append('\\n');\n\n      // HexEncode(Hash(Payload))\n      canonicalRequest.append(hashedPayload);\n\n      signatureWire.getWireLog().debug(\"<< \" + canonicalRequest);\n\n      // Create a String to Sign\n      StringBuilder toSign = new StringBuilder();\n      // Algorithm + '\\n' +\n      toSign.append(\"AWS4-HMAC-SHA256\").append('\\n');\n      // RequestDate + '\\n' +\n      toSign.append(timestamp).append('\\n');\n      // CredentialScope + '\\n' +\n      toSign.append(credentialScope).append('\\n');\n      // HexEncode(Hash(CanonicalRequest))\n      toSign.append(hex(hash(canonicalRequest.toString())));\n\n      return toSign.toString();\n   }\n\n   /**\n    * change the keys but keep the values in-tact.\n    *\n    * @param in input map to transform\n    * @return immutableSortedMap with the new lowercase keys.\n    */\n   protected static Map<String, String> lowerCaseNaturalOrderKeys(Map<String, String> in) {\n      checkNotNull(in, \"input map\");\n      ImmutableSortedMap.Builder<String, String> returnVal = ImmutableSortedMap.<String, String>naturalOrder();\n      for (Map.Entry<String, String> entry : in.entrySet())\n         returnVal.put(entry.getKey().toLowerCase(Locale.US), entry.getValue());\n      return returnVal.build();\n   }\n\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/filters/Aws4SignerForAuthorizationHeader.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.filters;\n\nimport com.google.common.base.Joiner;\nimport com.google.common.base.Strings;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSortedMap;\nimport com.google.common.hash.HashCode;\nimport com.google.common.io.BaseEncoding;\nimport com.google.common.net.HttpHeaders;\nimport com.google.inject.Inject;\nimport org.jclouds.aws.domain.SessionCredentials;\nimport org.jclouds.crypto.Crypto;\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.internal.SignatureWire;\nimport org.jclouds.io.Payload;\nimport org.jclouds.location.Provider;\nimport org.jclouds.util.Closeables2;\n\nimport jakarta.inject.Named;\nimport java.io.ByteArrayInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.Date;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.io.BaseEncoding.base16;\nimport static com.google.common.net.HttpHeaders.AUTHORIZATION;\nimport static com.google.common.net.HttpHeaders.CONTENT_MD5;\nimport static com.google.common.net.HttpHeaders.DATE;\nimport static org.jclouds.aws.reference.AWSConstants.PROPERTY_HEADER_TAG;\nimport static org.jclouds.s3.filters.AwsSignatureV4Constants.AMZ_ALGORITHM_HMAC_SHA256;\nimport static org.jclouds.s3.filters.AwsSignatureV4Constants.AMZ_CONTENT_SHA256_HEADER;\nimport static org.jclouds.s3.filters.AwsSignatureV4Constants.AMZ_DATE_HEADER;\nimport static org.jclouds.s3.filters.AwsSignatureV4Constants.AMZ_SECURITY_TOKEN_HEADER;\nimport static org.jclouds.s3.reference.S3Constants.PROPERTY_S3_VIRTUAL_HOST_BUCKETS;\n\n/**\n * AWS4 signer sign requests to Amazon S3 using an 'Authorization' header.\n */\npublic class Aws4SignerForAuthorizationHeader extends Aws4SignerBase {\n   @Inject\n   public Aws4SignerForAuthorizationHeader(SignatureWire signatureWire,\n         @Named(PROPERTY_S3_VIRTUAL_HOST_BUCKETS) boolean isVhostStyle,\n         @Named(PROPERTY_HEADER_TAG) String headerTag,\n         @Provider Supplier<Credentials> creds, @TimeStamp Supplier<Date> timestampProvider,\n         ServiceAndRegion serviceAndRegion, Crypto crypto) {\n      super(signatureWire, headerTag, creds, timestampProvider, serviceAndRegion, crypto);\n   }\n\n   protected HttpRequest sign(HttpRequest request) throws HttpException {\n      checkNotNull(request, \"request is not ready to sign\");\n      checkNotNull(request.getEndpoint(), \"request is not ready to sign, request.endpoint not present.\");\n\n      Payload payload = request.getPayload();\n\n      // get host & port from request endpoint.\n      String host = request.getEndpoint().getHost();\n\n      Date date = timestampProvider.get();\n      String timestamp = timestampFormat.format(date);\n      String datestamp = dateFormat.format(date);\n\n      String service = serviceAndRegion.service();\n      String region = serviceAndRegion.region(host);\n      String credentialScope = Joiner.on('/').join(datestamp, region, service, \"aws4_request\");\n\n      HttpRequest.Builder<?> requestBuilder = request.toBuilder() //\n            .removeHeader(AUTHORIZATION) // remove Authorization\n            .removeHeader(DATE); // remove date\n\n      ImmutableMap.Builder<String, String> signedHeadersBuilder = ImmutableSortedMap.<String, String>naturalOrder();\n\n      // Content Type\n      // content-type is not a required signing param. However, examples use this, so we include it to ease testing.\n      String contentType = getContentType(request);\n      if (!Strings.isNullOrEmpty(contentType)) {\n         requestBuilder.replaceHeader(HttpHeaders.CONTENT_TYPE, contentType);\n         signedHeadersBuilder.put(HttpHeaders.CONTENT_TYPE.toLowerCase(), contentType);\n      }\n\n      // Content-Length for PUT or POST request http method\n      String contentLength = getContentLength(request);\n      if (!Strings.isNullOrEmpty(contentLength)) {\n         requestBuilder.replaceHeader(HttpHeaders.CONTENT_LENGTH, contentLength);\n         signedHeadersBuilder.put(HttpHeaders.CONTENT_LENGTH.toLowerCase(), contentLength);\n      }\n\n      // Content MD5\n      String contentMD5 = request.getFirstHeaderOrNull(CONTENT_MD5);\n      if (payload != null) {\n         HashCode md5 = payload.getContentMetadata().getContentMD5AsHashCode();\n         if (md5 != null) {\n            contentMD5 = BaseEncoding.base64().encode(md5.asBytes());\n         }\n      }\n      if (contentMD5 != null) {\n         requestBuilder.replaceHeader(CONTENT_MD5, contentMD5);\n         signedHeadersBuilder.put(CONTENT_MD5.toLowerCase(), contentMD5);\n      }\n\n      // host\n      host = hostHeaderFor(request.getEndpoint());\n      requestBuilder.replaceHeader(HttpHeaders.HOST, host);\n      signedHeadersBuilder.put(HttpHeaders.HOST.toLowerCase(), host);\n\n      // user-agent\n      String userAgent = request.getFirstHeaderOrNull(HttpHeaders.USER_AGENT);\n      if (userAgent != null) {\n         signedHeadersBuilder.put(HttpHeaders.USER_AGENT.toLowerCase(), userAgent);\n      }\n\n      // all x-amz-* headers\n      appendAmzHeaders(request, signedHeadersBuilder);\n\n      // x-amz-security-token\n      Credentials credentials = creds.get();\n      if (credentials instanceof SessionCredentials) {\n         String token = SessionCredentials.class.cast(credentials).getSessionToken();\n         requestBuilder.replaceHeader(AMZ_SECURITY_TOKEN_HEADER, token);\n         signedHeadersBuilder.put(AMZ_SECURITY_TOKEN_HEADER.toLowerCase(), token);\n      }\n\n      // x-amz-content-sha256\n      String contentSha256 = getPayloadHash(request);\n      requestBuilder.replaceHeader(AMZ_CONTENT_SHA256_HEADER, contentSha256);\n      signedHeadersBuilder.put(AMZ_CONTENT_SHA256_HEADER.toLowerCase(), contentSha256);\n\n      // put x-amz-date\n      requestBuilder.replaceHeader(AMZ_DATE_HEADER, timestamp);\n      signedHeadersBuilder.put(AMZ_DATE_HEADER.toLowerCase(), timestamp);\n\n      ImmutableMap<String, String> signedHeaders = signedHeadersBuilder.build();\n\n      String stringToSign = createStringToSign(request.getMethod(), request.getEndpoint(), signedHeaders, timestamp,\n            credentialScope, contentSha256);\n      signatureWire.getWireLog().debug(\"<< \" + stringToSign);\n\n      byte[] signatureKey = signatureKey(credentials.credential, datestamp, region, service);\n      String signature = base16().lowerCase().encode(hmacSHA256(stringToSign, signatureKey));\n\n      StringBuilder authorization = new StringBuilder(AMZ_ALGORITHM_HMAC_SHA256).append(\" \");\n      authorization.append(\"Credential=\").append(Joiner.on(\"/\").join(credentials.identity, credentialScope))\n            .append(\", \");\n      authorization.append(\"SignedHeaders=\").append(Joiner.on(\";\").join(signedHeaders.keySet()))\n            .append(\", \");\n      authorization.append(\"Signature=\").append(signature);\n      return requestBuilder.replaceHeader(HttpHeaders.AUTHORIZATION, authorization.toString()).build();\n   }\n\n   protected String getPayloadHash(HttpRequest request) {\n      Payload payload = request.getPayload();\n      if (payload == null || \"0\".equals(getContentLength(request))) {\n         return getEmptyPayloadContentHash();\n      }\n      return calculatePayloadContentHash(payload);\n   }\n\n   /**\n    * The hash returns the following value: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\n    */\n   protected String getEmptyPayloadContentHash() {\n      return base16().lowerCase().encode(hash(new ByteArrayInputStream(new byte[0])));\n   }\n\n   /**\n    * in this time, payload ContentMetadata provided content hash md5, but aws required sha256.\n    */\n   protected String calculatePayloadContentHash(Payload payload) {\n      // use payload stream calculate content sha256\n      InputStream payloadStream;\n      try {\n         payloadStream = payload.openStream();\n      } catch (IOException e) {\n         throw new HttpException(\"unable to open payload stream to calculate AWS4 signature.\", e);\n      }\n      try {\n         return base16().lowerCase().encode(hash(payloadStream));\n      } finally {\n         closeOrResetPayloadStream(payloadStream, payload.isRepeatable());\n      }\n   }\n\n   // some times, when use Multipart Payload and a part can not be repeatable, will happen some error...\n   void closeOrResetPayloadStream(InputStream payloadStream, boolean repeatable) {\n      // if payload stream can repeatable.\n      if (repeatable) {\n         Closeables2.closeQuietly(payloadStream);\n      } else {\n         try {\n            // reset unrepeatable payload stream\n            payloadStream.reset();\n         } catch (IOException e) {\n            // reset payload stream\n            throw new HttpException(\n                  \"unable to reset unrepeatable payload stream after calculating AWS4 signature.\", e);\n         }\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/filters/Aws4SignerForChunkedUpload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.filters;\n\nimport static org.jclouds.aws.reference.AWSConstants.PROPERTY_HEADER_TAG;\nimport static org.jclouds.s3.filters.AwsSignatureV4Constants.AMZ_ALGORITHM_HMAC_SHA256;\nimport static org.jclouds.s3.filters.AwsSignatureV4Constants.AMZ_CONTENT_SHA256_HEADER;\nimport static org.jclouds.s3.filters.AwsSignatureV4Constants.AMZ_DATE_HEADER;\nimport static org.jclouds.s3.filters.AwsSignatureV4Constants.AMZ_DECODED_CONTENT_LENGTH_HEADER;\nimport static org.jclouds.s3.filters.AwsSignatureV4Constants.AMZ_SECURITY_TOKEN_HEADER;\nimport static org.jclouds.s3.filters.AwsSignatureV4Constants.CHUNK_SIGNATURE_HEADER;\nimport static org.jclouds.s3.filters.AwsSignatureV4Constants.CLRF;\nimport static org.jclouds.s3.filters.AwsSignatureV4Constants.CONTENT_ENCODING_HEADER_AWS_CHUNKED;\nimport static org.jclouds.s3.filters.AwsSignatureV4Constants.SIGNATURE_LENGTH;\nimport static org.jclouds.s3.filters.AwsSignatureV4Constants.STREAMING_BODY_SHA256;\nimport static org.jclouds.s3.reference.S3Constants.PROPERTY_JCLOUDS_S3_CHUNKED_SIZE;\nimport static org.jclouds.util.Strings2.toInputStream;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.io.ByteStreams.readBytes;\nimport static com.google.common.net.HttpHeaders.AUTHORIZATION;\nimport static com.google.common.net.HttpHeaders.CONTENT_LENGTH;\nimport static com.google.common.net.HttpHeaders.CONTENT_MD5;\nimport static com.google.common.net.HttpHeaders.DATE;\n\nimport java.io.IOException;\nimport java.security.InvalidKeyException;\nimport java.util.Date;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.aws.domain.SessionCredentials;\nimport org.jclouds.crypto.Crypto;\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.internal.SignatureWire;\nimport org.jclouds.io.Payload;\nimport org.jclouds.location.Provider;\n\nimport com.google.common.base.Joiner;\nimport com.google.common.base.Strings;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSortedMap;\nimport com.google.common.hash.HashCode;\nimport com.google.common.io.BaseEncoding;\nimport com.google.common.io.ByteProcessor;\nimport com.google.common.net.HttpHeaders;\nimport com.google.inject.Inject;\n\n/**\n * AWS4 signer sign 'chunked' uploads.\n */\npublic class Aws4SignerForChunkedUpload extends Aws4SignerBase {\n\n   private final int userDataBlockSize;\n\n   @Inject\n   public Aws4SignerForChunkedUpload(SignatureWire signatureWire,\n         @Named(PROPERTY_HEADER_TAG) String headerTag,\n         @Named(PROPERTY_JCLOUDS_S3_CHUNKED_SIZE) int userDataBlockSize,\n         @Provider Supplier<Credentials> creds, @TimeStamp Supplier<Date> timestampProvider,\n         ServiceAndRegion serviceAndRegion, Crypto crypto) {\n      super(signatureWire, headerTag, creds, timestampProvider, serviceAndRegion, crypto);\n      this.userDataBlockSize = userDataBlockSize;\n   }\n\n   protected HttpRequest sign(HttpRequest request) throws HttpException {\n      checkNotNull(request, \"request is not ready to sign\");\n      checkNotNull(request.getEndpoint(), \"request is not ready to sign, request.endpoint not present.\");\n\n      Payload payload = request.getPayload();\n      // chunked upload required content-length.\n      Long contentLength = payload.getContentMetadata().getContentLength();\n\n      // check contentLength not null\n      checkNotNull(contentLength, \"request is not ready to sign, payload contentLength not present.\");\n\n      // get host from request endpoint.\n      String host = request.getEndpoint().getHost();\n\n      Date date = timestampProvider.get();\n      String timestamp = timestampFormat.format(date);\n      String datestamp = dateFormat.format(date);\n\n      String service = serviceAndRegion.service();\n      String region = serviceAndRegion.region(host);\n      String credentialScope = Joiner.on('/').join(datestamp, region, service, \"aws4_request\");\n\n      HttpRequest.Builder<?> requestBuilder = request.toBuilder() //\n            .removeHeader(AUTHORIZATION) // remove Authorization\n            .removeHeader(DATE) // remove Date\n            .removeHeader(CONTENT_LENGTH); // remove Content-Length\n\n      ImmutableMap.Builder<String, String> signedHeadersBuilder = ImmutableSortedMap.<String, String>naturalOrder();\n\n      // content-encoding\n      String contentEncoding = CONTENT_ENCODING_HEADER_AWS_CHUNKED;\n      String originalContentEncoding = payload.getContentMetadata().getContentEncoding();\n      if (originalContentEncoding != null) {\n         contentEncoding += \",\" + originalContentEncoding;\n      }\n      requestBuilder.replaceHeader(HttpHeaders.CONTENT_ENCODING, contentEncoding);\n      signedHeadersBuilder.put(HttpHeaders.CONTENT_ENCODING.toLowerCase(), contentEncoding);\n\n\n      // x-amz-decoded-content-length\n      requestBuilder.replaceHeader(AMZ_DECODED_CONTENT_LENGTH_HEADER, contentLength.toString());\n      signedHeadersBuilder.put(AMZ_DECODED_CONTENT_LENGTH_HEADER.toLowerCase(), contentLength.toString());\n\n      // how big is the overall request stream going to be once we add the signature\n      // 'headers' to each chunk?\n      long totalLength = calculateChunkedContentLength(contentLength, userDataBlockSize);\n      requestBuilder.replaceHeader(CONTENT_LENGTH, Long.toString(totalLength));\n      signedHeadersBuilder.put(CONTENT_LENGTH.toLowerCase(), Long.toString(totalLength));\n\n      // Content MD5\n      String contentMD5 = request.getFirstHeaderOrNull(CONTENT_MD5);\n      if (payload != null) {\n         HashCode md5 = payload.getContentMetadata().getContentMD5AsHashCode();\n         if (md5 != null) {\n            contentMD5 = BaseEncoding.base64().encode(md5.asBytes());\n         }\n      }\n      if (contentMD5 != null) {\n         requestBuilder.replaceHeader(CONTENT_MD5, contentMD5);\n         signedHeadersBuilder.put(CONTENT_MD5.toLowerCase(), contentMD5);\n      }\n\n      // Content Type\n      // content-type is not a required signing param. However, examples use this, so we include it to ease testing.\n      String contentType = getContentType(request);\n      if (!Strings.isNullOrEmpty(contentType)) {\n         requestBuilder.replaceHeader(HttpHeaders.CONTENT_TYPE, contentType);\n         signedHeadersBuilder.put(HttpHeaders.CONTENT_TYPE.toLowerCase(), contentType);\n      } else {\n         requestBuilder.removeHeader(HttpHeaders.CONTENT_TYPE);\n      }\n\n      // host\n      host = hostHeaderFor(request.getEndpoint());\n      requestBuilder.replaceHeader(HttpHeaders.HOST, host);\n      signedHeadersBuilder.put(HttpHeaders.HOST.toLowerCase(), host);\n\n      // user-agent, not a required signing param\n      String userAgent = request.getFirstHeaderOrNull(HttpHeaders.USER_AGENT);\n      if (userAgent != null) {\n         signedHeadersBuilder.put(HttpHeaders.USER_AGENT.toLowerCase(), userAgent);\n      }\n\n      // all x-amz-* headers\n      appendAmzHeaders(request, signedHeadersBuilder);\n\n      // x-amz-security-token\n      Credentials credentials = creds.get();\n      if (credentials instanceof SessionCredentials) {\n         String token = SessionCredentials.class.cast(credentials).getSessionToken();\n         requestBuilder.replaceHeader(AMZ_SECURITY_TOKEN_HEADER, token);\n         signedHeadersBuilder.put(AMZ_SECURITY_TOKEN_HEADER.toLowerCase(), token);\n      }\n\n      // x-amz-content-sha256\n      String contentSha256 = getPayloadHash();\n      requestBuilder.replaceHeader(AMZ_CONTENT_SHA256_HEADER, contentSha256);\n      signedHeadersBuilder.put(AMZ_CONTENT_SHA256_HEADER.toLowerCase(), contentSha256);\n\n      // put x-amz-date\n      requestBuilder.replaceHeader(AMZ_DATE_HEADER, timestamp);\n      signedHeadersBuilder.put(AMZ_DATE_HEADER.toLowerCase(), timestamp);\n\n      ImmutableMap<String, String> signedHeaders = signedHeadersBuilder.build();\n\n      String stringToSign = createStringToSign(request.getMethod(), request.getEndpoint(), signedHeaders, timestamp,\n            credentialScope, contentSha256);\n      signatureWire.getWireLog().debug(\"<< \" + stringToSign);\n\n      byte[] signatureKey = signatureKey(credentials.credential, datestamp, region, service);\n\n      // init hmacSHA256 processor for seed signature and chunked block signature\n      ByteProcessor<byte[]> hmacSHA256;\n      try {\n         hmacSHA256 = hmacSHA256(crypto, signatureKey);\n      } catch (InvalidKeyException e) {\n         throw new ChunkedUploadException(\"invalid key\", e);\n      }\n\n      // Calculating the Seed Signature\n      String signature;\n      try {\n         signature = hex(readBytes(toInputStream(stringToSign), hmacSHA256));\n      } catch (IOException e) {\n         throw new ChunkedUploadException(\"hmac sha256 seed signature error\", e);\n      }\n\n      StringBuilder authorization = new StringBuilder(AMZ_ALGORITHM_HMAC_SHA256).append(\" \");\n      authorization.append(\"Credential=\").append(Joiner.on(\"/\").join(credentials.identity, credentialScope))\n            .append(\", \");\n      authorization.append(\"SignedHeaders=\").append(Joiner.on(\";\").join(signedHeaders.keySet()))\n            .append(\", \");\n      authorization.append(\"Signature=\").append(signature);\n\n      // replace request payload with chunked upload payload\n      ChunkedUploadPayload chunkedPayload = new ChunkedUploadPayload(payload, userDataBlockSize, timestamp,\n            credentialScope, hmacSHA256, signature);\n      chunkedPayload.getContentMetadata().setContentEncoding(null);\n\n      return requestBuilder\n            .replaceHeader(HttpHeaders.AUTHORIZATION, authorization.toString())\n            .payload(chunkedPayload)\n            .build();\n\n   }\n\n   // for seed signature, value: STREAMING-AWS4-HMAC-SHA256-PAYLOAD\n   protected String getPayloadHash() {\n      return STREAMING_BODY_SHA256;\n   }\n\n   /**\n    * Calculates the expanded payload size of our data when it is chunked\n    *\n    * @param originalLength The true size of the data payload to be uploaded\n    * @param chunkSize     The size of each chunk we intend to send; each chunk will be\n    *                  prefixed with signed header data, expanding the overall size\n    *                  by a determinable amount\n    * @return The overall payload size to use as content-length on a chunked\n    * upload\n    */\n   public static long calculateChunkedContentLength(long originalLength, long chunkSize) {\n      checkArgument(originalLength > 0, \"Nonnegative content length expected.\");\n\n      long maxSizeChunks = originalLength / chunkSize;\n      long remainingBytes = originalLength % chunkSize;\n      return maxSizeChunks * calculateChunkHeaderLength(chunkSize)\n            + (remainingBytes > 0 ? calculateChunkHeaderLength(remainingBytes) : 0)\n            + calculateChunkHeaderLength(0);\n   }\n\n   /**\n    * Returns the size of a chunk header, which only varies depending on the\n    * selected chunk size\n    *\n    * @param chunkDataSize The intended size of each chunk; this is placed into the chunk\n    *                 header\n    * @return The overall size of the header that will prefix the user data in\n    * each chunk\n    */\n   private static long calculateChunkHeaderLength(long chunkDataSize) {\n      return Long.toHexString(chunkDataSize).length()\n            + CHUNK_SIGNATURE_HEADER.length()\n            + SIGNATURE_LENGTH\n            + CLRF.length()\n            + chunkDataSize\n            + CLRF.length();\n   }\n\n\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/filters/Aws4SignerForQueryString.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.filters;\n\nimport static org.jclouds.aws.reference.AWSConstants.PROPERTY_HEADER_TAG;\nimport static org.jclouds.s3.filters.AwsSignatureV4Constants.AMZ_ALGORITHM_PARAM;\nimport static org.jclouds.s3.filters.AwsSignatureV4Constants.AMZ_CONTENT_SHA256_HEADER;\nimport static org.jclouds.s3.filters.AwsSignatureV4Constants.AMZ_CREDENTIAL_PARAM;\nimport static org.jclouds.s3.filters.AwsSignatureV4Constants.AMZ_DATE_HEADER;\nimport static org.jclouds.s3.filters.AwsSignatureV4Constants.AMZ_DATE_PARAM;\nimport static org.jclouds.s3.filters.AwsSignatureV4Constants.AMZ_EXPIRES_PARAM;\nimport static org.jclouds.s3.filters.AwsSignatureV4Constants.AMZ_SECURITY_TOKEN_PARAM;\nimport static org.jclouds.s3.filters.AwsSignatureV4Constants.AMZ_SIGNATURE_PARAM;\nimport static org.jclouds.s3.filters.AwsSignatureV4Constants.AMZ_SIGNEDHEADERS_PARAM;\nimport static org.jclouds.s3.filters.AwsSignatureV4Constants.AUTHORIZATION_HEADER;\nimport static org.jclouds.s3.filters.AwsSignatureV4Constants.UNSIGNED_PAYLOAD;\nimport static org.jclouds.s3.reference.S3Constants.PROPERTY_S3_VIRTUAL_HOST_BUCKETS;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.io.BaseEncoding.base16;\n\nimport java.util.Date;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.aws.domain.SessionCredentials;\nimport org.jclouds.crypto.Crypto;\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.Uris;\nimport org.jclouds.http.internal.SignatureWire;\nimport org.jclouds.location.Provider;\n\nimport com.google.common.base.Joiner;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSortedMap;\nimport com.google.inject.Inject;\n\n/**\n * AWS4 signer sign requests to Amazon S3 using query string parameters.\n */\npublic class Aws4SignerForQueryString extends Aws4SignerBase {\n   @Inject\n   public Aws4SignerForQueryString(SignatureWire signatureWire,\n         @Named(PROPERTY_S3_VIRTUAL_HOST_BUCKETS) boolean isVhostStyle,\n         @Named(PROPERTY_HEADER_TAG) String headerTag,\n         @Provider Supplier<Credentials> creds, @TimeStamp Supplier<Date> timestampProvider,\n         ServiceAndRegion serviceAndRegion, Crypto crypto) {\n      super(signatureWire, headerTag, creds, timestampProvider, serviceAndRegion, crypto);\n   }\n\n\n   protected HttpRequest sign(HttpRequest request, long timeInSeconds) throws HttpException {\n      checkNotNull(request, \"request is not ready to sign\");\n      checkNotNull(request.getEndpoint(), \"request is not ready to sign, request.endpoint not present.\");\n\n      // get host from request endpoint.\n      String host = request.getEndpoint().getHost();\n\n      Date date = timestampProvider.get();\n      String timestamp = timestampFormat.format(date);\n      String datestamp = dateFormat.format(date);\n\n      String service = serviceAndRegion.service();\n      String region = serviceAndRegion.region(host);\n      String credentialScope = Joiner.on('/').join(datestamp, region, service, \"aws4_request\");\n\n      // different with signature with Authorization header\n      HttpRequest.Builder<?> requestBuilder = request.toBuilder() //\n            // sign for temporary access use query string parameter:\n            // X-Amz-Algorithm, X-Amz-Credential, X-Amz-Date, X-Amz-Expires, X-Amz-SignedHeaders, X-Amz-Signature\n            // remove Authorization, x-amz-content-sha256, X-Amz-Date headers\n            .removeHeader(AUTHORIZATION_HEADER)\n            .removeHeader(AMZ_CONTENT_SHA256_HEADER)\n            .removeHeader(AMZ_DATE_HEADER);\n\n      ImmutableMap.Builder<String, String> signedHeadersBuilder = ImmutableSortedMap.<String, String>naturalOrder(); //\n      Uris.UriBuilder endpointBuilder = Uris.uriBuilder(request.getEndpoint());\n\n\n      // Canonical Headers\n      // must include the HTTP host header.\n      // If you plan to include any of the x-amz-* headers, these headers must also be added for signature calculation.\n      // You can optionally add all other headers that you plan to include in your request.\n      // For added security, you should sign as many headers as possible.\n\n      // HOST\n      host = hostHeaderFor(request.getEndpoint());\n      signedHeadersBuilder.put(\"host\", host);\n      ImmutableMap<String, String> signedHeaders = signedHeadersBuilder.build();\n\n      Credentials credentials = creds.get();\n\n      if (credentials instanceof SessionCredentials) {\n         String token = SessionCredentials.class.cast(credentials).getSessionToken();\n         // different with signature with Authorization header\n         endpointBuilder.replaceQuery(AMZ_SECURITY_TOKEN_PARAM, token);\n      }\n\n      // X-Amz-Algorithm=HMAC-SHA256\n      endpointBuilder.replaceQuery(AMZ_ALGORITHM_PARAM, AwsSignatureV4Constants.AMZ_ALGORITHM_HMAC_SHA256);\n\n      // X-Amz-Credential=<your-access-key-id>/<date>/<AWS-region>/<AWS-service>/aws4_request.\n      String credential = Joiner.on(\"/\").join(credentials.identity, credentialScope);\n      endpointBuilder.replaceQuery(AMZ_CREDENTIAL_PARAM, credential);\n\n      // X-Amz-Date=ISO 8601 format, for example, 20130721T201207Z\n      endpointBuilder.replaceQuery(AMZ_DATE_PARAM, timestamp);\n\n      // X-Amz-Expires=time in seconds\n      endpointBuilder.replaceQuery(AMZ_EXPIRES_PARAM, String.valueOf(timeInSeconds));\n\n      // X-Amz-SignedHeaders=HTTP host header is required.\n      endpointBuilder.replaceQuery(AMZ_SIGNEDHEADERS_PARAM, Joiner.on(';').join(signedHeaders.keySet()));\n\n      String stringToSign = createStringToSign(request.getMethod(), endpointBuilder.build(), signedHeaders, timestamp, credentialScope,\n            getPayloadHash());\n\n      signatureWire.getWireLog().debug(\"<< \" + stringToSign);\n\n\n      byte[] signatureKey = signatureKey(credentials.credential, datestamp, region, service);\n      String signature = base16().lowerCase().encode(hmacSHA256(stringToSign, signatureKey));\n\n      // X-Amz-Signature=Signature\n      endpointBuilder.replaceQuery(AMZ_SIGNATURE_PARAM, signature);\n\n      return requestBuilder.endpoint(endpointBuilder.build()).build();\n   }\n\n   protected String getPayloadHash() {\n      return UNSIGNED_PAYLOAD;\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/filters/AwsHostNameUtils.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.s3.filters;\n\nimport com.google.common.collect.ImmutableMap;\n\nimport java.net.URI;\nimport java.util.Map;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class AwsHostNameUtils {\n\n   private static final Pattern S3_ENDPOINT_PATTERN = Pattern.compile(\"^(?:.+\\\\.)?s3[.\\\\-]([a-z0-9-]+)(?>\\\\.[a-z0-9-]+)*$\");\n\n   private static final Pattern STANDARD_CLOUDSEARCH_ENDPOINT_PATTERN = Pattern.compile(\"^(?:.+\\\\.)?([a-z0-9-]+)\\\\.cloudsearch$\");\n\n   private static final Pattern EXTENDED_CLOUDSEARCH_ENDPOINT_PATTERN = Pattern.compile(\"^(?:.+\\\\.)?([a-z0-9-]+)\\\\.cloudsearch\\\\..+\");\n\n   private static final ImmutableMap<String, String> HOST_REGEX_TO_REGION_MAPPINGS = new ImmutableMap.Builder<String, String>()\n      .put(\"(.+\\\\.)?s3\\\\.amazonaws\\\\.com\", \"us-east-1\")\n      .put(\"(.+\\\\.)?s3-external-1\\\\.amazonaws\\\\.com\", \"us-east-1\")\n      .put(\"(.+\\\\.)?s3-fips-us-gov-west-1\\\\.amazonaws\\\\.com\", \"us-gov-west-1\")\n      .build();\n\n   /**\n    * Attempts to parse the region name from an endpoint based on conventions\n    * about the endpoint format.\n    *\n    * @param host      the hostname to parse\n    * @param serviceHint an optional hint about the service for the endpoint\n    * @return the region parsed from the hostname, or\n    * &quot;us-east-1&quot; if no region information\n    * could be found\n    */\n   public static String parseRegionName(final String host, final String serviceHint) {\n\n      String regionNameInInternalConfig = parseRegionNameByInternalConfig(host);\n      if (regionNameInInternalConfig != null) {\n         return regionNameInInternalConfig;\n      }\n\n      if (host.endsWith(\".amazonaws.com\")) {\n         int index = host.length() - \".amazonaws.com\".length();\n         return parseStandardRegionName(host.substring(0, index));\n      }\n\n      if (serviceHint != null) {\n         if (serviceHint.equals(\"cloudsearch\")\n            && !host.startsWith(\"cloudsearch.\")) {\n\n            // CloudSearch domains use the nonstandard domain format\n            // [domain].[region].cloudsearch.[suffix].\n\n            Matcher matcher = EXTENDED_CLOUDSEARCH_ENDPOINT_PATTERN\n               .matcher(host);\n\n            if (matcher.matches()) {\n               return matcher.group(1);\n            }\n         }\n\n         // If we have a service hint, look for 'service.[region]' or\n         // 'service-[region]' in the endpoint's hostname.\n         Pattern pattern = Pattern.compile(\n            \"^(?:.+\\\\.)?\"\n               + Pattern.quote(serviceHint)\n               + \"[.-]([a-z0-9-]+)\\\\.\"\n         );\n\n         Matcher matcher = pattern.matcher(host);\n         if (matcher.find()) {\n            return matcher.group(1);\n         }\n      }\n\n      // Endpoint is totally non-standard; guess us-east-1 for lack of a\n      // better option.\n\n      return \"us-east-1\";\n   }\n\n   /**\n    * Parses the region name from a standard (*.amazonaws.com) endpoint.\n    *\n    * @param fragment the portion of the endpoint excluding\n    *             &quot;.amazonaws.com&quot;\n    * @return the parsed region name (or &quot;us-east-1&quot; as a\n    * best guess if we can't tell for sure)\n    */\n   private static String parseStandardRegionName(final String fragment) {\n\n      Matcher matcher = S3_ENDPOINT_PATTERN.matcher(fragment);\n      if (matcher.matches()) {\n         // host was '[whatever].s3[.|-]-[region].[whatever].amazonaws.com\n         return matcher.group(1);\n      }\n\n      matcher = STANDARD_CLOUDSEARCH_ENDPOINT_PATTERN.matcher(fragment);\n      if (matcher.matches()) {\n         // host was 'domain.[region].cloudsearch.amazonaws.com'.\n         return matcher.group(1);\n      }\n\n      int index = fragment.lastIndexOf('.');\n      if (index == -1) {\n         // host was 'service.amazonaws.com', guess us-east-1\n         // for lack of a better option.\n         return \"us-east-1\";\n      }\n\n      // host was 'service.[region].amazonaws.com'.\n      String region = fragment.substring(index + 1);\n\n      // Special case for iam.us-gov.amazonaws.com, which is actually\n      // us-gov-west-1.\n      if (\"us-gov\".equals(region)) {\n         region = \"us-gov-west-1\";\n      }\n\n      return region;\n   }\n\n   /**\n    * @return the configured region name if the given host name matches any of\n    * the host-to-region mappings in the internal config; otherwise\n    * return null.\n    */\n   private static String parseRegionNameByInternalConfig(String host) {\n      for (Map.Entry<String, String> mapping : HOST_REGEX_TO_REGION_MAPPINGS.entrySet()) {\n         String hostNameRegex = mapping.getKey();\n         if (host.matches(hostNameRegex)) {\n            return mapping.getValue();\n         }\n      }\n\n      return null;\n   }\n\n   /**\n    * Parses the service name from an endpoint. Can only handle endpoints of\n    * the form 'service.[region.]amazonaws.com'.\n    * or\n    * bucket.s3.[region.]awazonaws.com\n    */\n   public static String parseServiceName(URI endpoint) {\n      String host = endpoint.getHost();\n\n      if (!host.endsWith(\".amazonaws.com\") && !host.endsWith(\".amazonaws.com.cn\")) {\n         return \"s3\";  // cannot parse name, assume s3\n      }\n\n      String serviceAndRegion = host.substring(0, host.indexOf(\".amazonaws.com\"));\n\n      // Special cases for S3 endpoints with bucket names embedded.\n      if (serviceAndRegion.endsWith(\".s3\") || S3_ENDPOINT_PATTERN.matcher(serviceAndRegion).matches()) {\n         return \"s3\";\n      }\n\n      char separator = '.';\n\n      // If we don't detect a separator between service name and region, then\n      // assume that the region is not included in the hostname, and it's only\n      // the service name (ex: \"http://iam.amazonaws.com\").\n      if (serviceAndRegion.indexOf(separator) == -1) {\n         return serviceAndRegion;\n      }\n\n      return serviceAndRegion.substring(0, serviceAndRegion.indexOf(separator));\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/filters/AwsSignatureV4Constants.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.filters;\n\n/**\n * AWS Signature Version 4 Constants.\n */\npublic abstract class AwsSignatureV4Constants {\n\n    /**\n     * AWS authorization header key\n     */\n   public static final String AUTHORIZATION_HEADER = \"Authorization\";\n\n   /**\n    * AWS content sha256 header key\n    */\n   public static final String AMZ_CONTENT_SHA256_HEADER = \"x-amz-content-sha256\";\n\n   /**\n    * AWS date header key\n    */\n   public static final String AMZ_DATE_HEADER = \"X-Amz-Date\";\n\n   /**\n    * AWS security token key\n    */\n   public static final String AMZ_SECURITY_TOKEN_HEADER = \"X-Amz-Security-Token\";\n\n   /**\n    * For AWS Signature Version 4, you set this parameter value to \"AWS4-HMAC-SHA256\".\n    */\n   public static final String AMZ_ALGORITHM_PARAM = \"X-Amz-Algorithm\";\n   /**\n    * This string identifies AWS Signature Version 4 (AWS4) and the HMAC-SHA256 algorithm (HMAC-SHA256).\n    */\n   public static final String AMZ_ALGORITHM_HMAC_SHA256 = \"AWS4-HMAC-SHA256\";\n\n   /**\n    * In addition to your access key ID, this parameter also provides scope information identifying the region and\n    * service for which the signature is valid.\n    * <p>This value should match the scope that you use to calculate the signing key, as discussed in the following section.</p>\n    * <p>The general form for this parameter value is as follows:</p>\n    * <code> &lt;your-access-key-id>/&lt;date>/&lt;AWS-region>/&lt;AWS-service>/aws4_request.</code>\n    * <p>\n    * For example:\n    * <code>AKIAIOSFODNN7EXAMPLE/20130721/us-east-1/s3/aws4_request.</code><br>\n    * For Amazon S3, the AWS-service string is \"s3\". For a list of AWS-region strings, go to Regions and Endpoints\n    * in the Amazon Web Services General Reference\n    * </p>\n    */\n   public static final String AMZ_CREDENTIAL_PARAM = \"X-Amz-Credential\";\n\n   /**\n    * This header can be used in the following scenarios:\n    * <ul>\n    * <li>Provide security tokens for Amazon DevPay operations—Each request that uses Amazon DevPay requires two\n    * x-amz-security-token headers: one for the product token and one for the user token. When Amazon S3 receives\n    * an authenticated request, it compares the computed signature with the provided signature.\n    * Improperly formatted multi-value headers used to calculate a signature can cause authentication issues</li>\n    * <li>Provide security token when using temporary security credentials—When making requests using temporary\n    * security credentials you obtained from IAM you must provide a security token using this header.\n    * To learn more about temporary security credentials, go to Making Requests.</li>\n    * </ul>\n    * This header is required for requests that use Amazon DevPay and requests that are signed using temporary security credentials.\n    */\n\n   public static final String AMZ_SECURITY_TOKEN_PARAM = AMZ_SECURITY_TOKEN_HEADER;\n\n   /**\n    * The date in ISO 8601 format, for example, 20130721T201207Z. This value must match the date value used to\n    * calculate the signature.\n    */\n   public static final String AMZ_DATE_PARAM = AMZ_DATE_HEADER;\n\n   /**\n    * Provides the time period, in seconds, for which the generated presigned URL is valid.\n    * <p> For example, 86400 (24 hours). This value is an integer. The minimum value you can set is 1,\n    * and the maximum is 604800 (seven days). </p>\n    * <p> A presigned URL can be valid for a maximum of seven days because the signing key you use in signature\n    * calculation is valid for up to seven days.</p>\n    */\n   public static final String AMZ_EXPIRES_PARAM = \"X-Amz-Expires\";\n\n   /**\n    * Lists the headers that you used to calculate the signature.\n    * <p> The HTTP host header is required. Any x-amz-* headers that you plan to add to the request are also required\n    * for signature calculation. </p>\n    * <p> In general, for added security, you should sign all the request headers that you plan to include in your\n    * request.</p>\n    */\n   public static final String AMZ_SIGNEDHEADERS_PARAM = \"X-Amz-SignedHeaders\";\n\n   /**\n    * X-Amz-Signature Provides the signature to authenticate your request.\n    * <p>This signature must match the signature Amazon S3 calculates; otherwise, Amazon S3 denies the request.\n    * For example, 733255ef022bec3f2a8701cd61d4b371f3f28c9f193a1f02279211d48d5193d7</p>\n    */\n   public static final String AMZ_SIGNATURE_PARAM = \"X-Amz-Signature\";\n\n   /**\n    * You don't include a payload hash in the Canonical Request, because when you create a presigned URL,\n    * <p> you don't know anything about the payload. Instead, you use a constant string \"UNSIGNED-PAYLOAD\".</p>\n    */\n   public static final String UNSIGNED_PAYLOAD = \"UNSIGNED-PAYLOAD\";\n\n   /**\n    * SHA256 substitute marker used in place of x-amz-content-sha256 when\n    * employing chunked uploads\n    */\n   public static final String STREAMING_BODY_SHA256 = \"STREAMING-AWS4-HMAC-SHA256-PAYLOAD\";\n   public static final String CHUNK_STRING_TO_SIGN_PREFIX = \"AWS4-HMAC-SHA256-PAYLOAD\";\n\n   public static final String CLRF = \"\\r\\n\";\n\n   public static final String CHUNK_SIGNATURE_HEADER = \";chunk-signature=\";\n   public static final int SIGNATURE_LENGTH = 64;\n   public static final byte[] FINAL_CHUNK = new byte[0];\n\n   /**\n    * Content-Encoding\n    * <p>\n    * Set the value to aws-chunked.<br>\n    * Amazon S3 supports multiple content encodings, for example,<br>\n    * Content-Encoding : aws-chunked, gzip<br>\n    * That is, you can specify your custom content-encoding when using Signature Version 4 streaming API.\n    * </p>\n    */\n   public static final String CONTENT_ENCODING_HEADER_AWS_CHUNKED = \"aws-chunked\";\n   /**\n    * 'x-amz-decoded-content-length' is used to transmit the actual\n    */\n   public static final String AMZ_DECODED_CONTENT_LENGTH_HEADER = \"x-amz-decoded-content-length\";\n\n   private AwsSignatureV4Constants() {\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/filters/ChunkedUploadException.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.filters;\n\npublic class ChunkedUploadException extends RuntimeException {\n   public ChunkedUploadException(String error, Exception e) {\n      super(error, e);\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/filters/ChunkedUploadPayload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.filters;\n\nimport com.google.common.io.ByteProcessor;\nimport com.google.common.io.ByteStreams;\nimport org.gaul.modernizer_maven_annotations.SuppressModernizer;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.io.MutableContentMetadata;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.payloads.BaseMutableContentMetadata;\nimport org.jclouds.io.payloads.BasePayload;\n\nimport java.io.BufferedInputStream;\nimport java.io.ByteArrayInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.SequenceInputStream;\nimport java.util.Enumeration;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.io.ByteStreams.readBytes;\nimport static org.jclouds.s3.filters.Aws4SignerBase.hash;\nimport static org.jclouds.s3.filters.Aws4SignerBase.hex;\nimport static org.jclouds.s3.filters.AwsSignatureV4Constants.CHUNK_SIGNATURE_HEADER;\nimport static org.jclouds.s3.filters.AwsSignatureV4Constants.CHUNK_STRING_TO_SIGN_PREFIX;\nimport static org.jclouds.s3.filters.AwsSignatureV4Constants.CLRF;\nimport static org.jclouds.s3.filters.AwsSignatureV4Constants.FINAL_CHUNK;\nimport static org.jclouds.util.Strings2.toInputStream;\n\npublic class ChunkedUploadPayload extends BasePayload<Payload> {\n   private static final byte[] TRAILER = CLRF.getBytes(UTF_8);\n\n   private final Payload payload;\n   private final int chunkedBlockSize;\n   private final String timestamp;\n   private final String scope;\n   private final ByteProcessor<byte[]> hmacSHA256;\n   private String lastComputedSignature;\n\n   public ChunkedUploadPayload(Payload payload, int blockSize, String timestamp, String scope,\n         ByteProcessor<byte[]> hmacSHA256, String seedSignature) {\n      super(payload);\n      this.payload = payload;\n      this.chunkedBlockSize = blockSize;\n      this.timestamp = timestamp;\n      this.scope = scope;\n      this.hmacSHA256 = hmacSHA256;\n      this.lastComputedSignature = seedSignature;\n\n      // init content metadata\n      MutableContentMetadata contentMetadata = BaseMutableContentMetadata.fromContentMetadata(\n            payload.getContentMetadata());\n      long totalLength = Aws4SignerForChunkedUpload.calculateChunkedContentLength(\n            payload.getContentMetadata().getContentLength(),\n            chunkedBlockSize);\n      contentMetadata.setContentLength(totalLength);\n      this.setContentMetadata(contentMetadata);\n   }\n\n   /**\n    * Returns a chunk for upload consisting of the signed 'header' or chunk\n    * prefix plus the user data. The signature of the chunk incorporates the\n    * signature of the previous chunk (or, if the first chunk, the signature of\n    * the headers portion of the request).\n    *\n    * @param userDataLen The length of the user data contained in userData\n    * @param userData   Contains the user data to be sent in the upload chunk\n    * @return A new buffer of data for upload containing the chunk header plus\n    * user data\n    */\n   protected byte[] constructSignedChunk(int userDataLen, byte[] userData) {\n      // to keep our computation routine signatures simple, if the userData\n      // buffer contains less data than it could, shrink it. Note the special case\n      // to handle the requirement that we send an empty chunk to complete\n      // our chunked upload.\n      byte[] dataToChunk;\n      if (userDataLen == 0) {\n         dataToChunk = FINAL_CHUNK;\n      } else {\n         if (userDataLen < userData.length) {\n            // shrink the chunkdata to fit\n            dataToChunk = new byte[userDataLen];\n            System.arraycopy(userData, 0, dataToChunk, 0, userDataLen);\n         } else {\n            dataToChunk = userData;\n         }\n      }\n\n      // string(IntHexBase(chunk-size)) + \";chunk-signature=\" + signature + \\r\\n + chunk-data + \\r\\n\n      StringBuilder chunkHeader = new StringBuilder();\n\n      // start with size of user data\n      // IntHexBase(chunk-size)\n      chunkHeader.append(Integer.toHexString(dataToChunk.length));\n\n      // chunk-signature\n\n      // nonsig-extension; we have none in these samples\n      String nonsigExtension = \"\";\n\n      // if this is the first chunk, we package it with the signing result\n      // of the request headers, otherwise we use the cached signature\n      // of the previous chunk\n\n      // sig-extension\n      StringBuilder buffer = new StringBuilder();\n      buffer.append(CHUNK_STRING_TO_SIGN_PREFIX);\n      buffer.append(\"\\n\");\n      buffer.append(timestamp).append(\"\\n\");\n      buffer.append(scope).append(\"\\n\");\n      buffer.append(lastComputedSignature).append(\"\\n\");\n      buffer.append(hex(hash(nonsigExtension))).append(\"\\n\");\n      buffer.append(hex(hash(dataToChunk)));\n\n      String chunkStringToSign = buffer.toString();\n\n      // compute the V4 signature for the chunk\n      String chunkSignature;\n      try {\n         chunkSignature = hex(readBytes(toInputStream(chunkStringToSign), hmacSHA256));\n      } catch (IOException e) {\n         throw new HttpException(\"hmac sha256 chunked signature error\");\n      }\n\n      // cache the signature to include with the next chunk's signature computation\n      lastComputedSignature = chunkSignature;\n\n      // construct the actual chunk, comprised of the non-signed extensions, the\n      // 'headers' we just signed and their signature, plus a newline then copy\n      // that plus the user's data to a payload to be written to the request stream\n      chunkHeader.append(nonsigExtension + CHUNK_SIGNATURE_HEADER + chunkSignature);\n      chunkHeader.append(CLRF);\n\n      byte[] header = chunkHeader.toString().getBytes(UTF_8);\n      byte[] signedChunk = new byte[header.length + dataToChunk.length + TRAILER.length];\n      System.arraycopy(header, 0, signedChunk, 0, header.length);\n      // chunk-data\n      System.arraycopy(dataToChunk, 0, signedChunk, header.length, dataToChunk.length);\n      System.arraycopy(TRAILER, 0, signedChunk, header.length + dataToChunk.length, TRAILER.length);\n\n      // this is the total data for the chunk that will be sent to the request stream\n      return signedChunk;\n   }\n\n   @Override\n   public void release() {\n      this.payload.release();\n   }\n\n   @Override\n   public boolean isRepeatable() {\n      return this.payload.isRepeatable();\n   }\n\n   @Override\n   public InputStream openStream() throws IOException {\n      return new SequenceInputStream(new ChunkedInputStreamEnumeration(this.payload.openStream(), chunkedBlockSize));\n   }\n\n   @SuppressModernizer  // for Enumeration\n   private class ChunkedInputStreamEnumeration implements Enumeration<InputStream> {\n      private final InputStream inputStream;\n      private boolean lastChunked;\n      private byte[] buffer;\n\n      ChunkedInputStreamEnumeration(InputStream inputStream, int chunkedBlockSize) {\n         this.inputStream = new BufferedInputStream(inputStream, chunkedBlockSize);\n         buffer = new byte[chunkedBlockSize];\n         lastChunked = false;\n      }\n\n      @Override\n      public boolean hasMoreElements() {\n         return !lastChunked;\n      }\n\n      @Override\n      public InputStream nextElement() {\n         int bytesRead;\n         try {\n            bytesRead = ByteStreams.read(inputStream, buffer, 0, buffer.length);\n         } catch (IOException e) {\n            // IO EXCEPTION\n            throw new ChunkedUploadException(\"read from input stream error\", e);\n         }\n\n         // buffer\n         byte[] chunk;\n\n         // ByteStreams.read(InputStream, byte[], int, int) returns the number of bytes read\n         // InputStream.read(byte[], int, int) returns -1 if the end of the stream has been reached.\n         if (bytesRead > 0) {\n            // process into a chunk\n            chunk = constructSignedChunk(bytesRead, buffer);\n         } else {\n            // construct last chunked block\n            chunk = constructSignedChunk(0, buffer);\n            lastChunked = true;\n         }\n         return new ByteArrayInputStream(chunk);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/filters/RequestAuthorizeSignature.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.filters;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpRequestFilter;\n\n/**\n * Signs the S3 request.\n */\n\npublic interface RequestAuthorizeSignature extends HttpRequestFilter {\n   HttpRequest signForTemporaryAccess(HttpRequest request, long timeInSeconds);\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/filters/RequestAuthorizeSignatureV2.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.filters;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.collect.Iterables.get;\nimport static com.google.common.io.BaseEncoding.base64;\nimport static com.google.common.io.ByteStreams.readBytes;\nimport static org.jclouds.aws.reference.AWSConstants.PROPERTY_AUTH_TAG;\nimport static org.jclouds.aws.reference.AWSConstants.PROPERTY_HEADER_TAG;\nimport static org.jclouds.crypto.Macs.asByteProcessor;\nimport static org.jclouds.http.utils.Queries.queryParser;\nimport static org.jclouds.s3.reference.S3Constants.PROPERTY_S3_SERVICE_PATH;\nimport static org.jclouds.s3.reference.S3Constants.PROPERTY_S3_VIRTUAL_HOST_BUCKETS;\nimport static org.jclouds.util.Strings2.toInputStream;\n\nimport java.util.Collection;\nimport java.util.Date;\nimport java.util.Locale;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.TimeUnit;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Provider;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Constants;\nimport org.jclouds.aws.domain.SessionCredentials;\nimport org.jclouds.crypto.Crypto;\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpRequestFilter;\nimport org.jclouds.http.HttpUtils;\nimport org.jclouds.http.internal.SignatureWire;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.rest.RequestSigner;\nimport org.jclouds.s3.reference.S3Constants;\nimport org.jclouds.s3.util.S3Utils;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Strings;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Multimap;\nimport com.google.common.collect.Ordering;\nimport com.google.common.collect.SortedSetMultimap;\nimport com.google.common.collect.TreeMultimap;\nimport com.google.common.io.ByteProcessor;\nimport com.google.common.net.HttpHeaders;\n\n/**\n * AWS Sign V2\n */\n@Singleton\npublic class RequestAuthorizeSignatureV2 implements RequestAuthorizeSignature, RequestSigner {\n   private static final Collection<String> FIRST_HEADERS_TO_SIGN = ImmutableList.of(HttpHeaders.DATE);\n\n   private static final Set<String> SIGNED_PARAMETERS = ImmutableSet.of(\"acl\", \"torrent\", \"logging\", \"location\",\n         \"policy\", \"requestPayment\", \"versioning\", \"versions\", \"versionId\", \"notification\", \"uploadId\", \"uploads\",\n         \"partNumber\", \"website\", \"response-content-type\", \"response-content-language\", \"response-expires\",\n         \"response-cache-control\", \"response-content-disposition\", \"response-content-encoding\", \"delete\");\n\n   private final SignatureWire signatureWire;\n   private final Supplier<Credentials> creds;\n   private final Provider<String> timeStampProvider;\n   private final Crypto crypto;\n   private final HttpUtils utils;\n\n   @Resource\n   @Named(Constants.LOGGER_SIGNATURE)\n   Logger signatureLog = Logger.NULL;\n\n   private final String authTag;\n   private final String headerTag;\n   private final String servicePath;\n   private final boolean isVhostStyle;\n   private final DateService dateService;\n\n   @Inject\n   public RequestAuthorizeSignatureV2(SignatureWire signatureWire, @Named(PROPERTY_AUTH_TAG) String authTag,\n         @Named(PROPERTY_S3_VIRTUAL_HOST_BUCKETS) boolean isVhostStyle,\n         @Named(PROPERTY_S3_SERVICE_PATH) String servicePath, @Named(PROPERTY_HEADER_TAG) String headerTag,\n         @org.jclouds.location.Provider Supplier<Credentials> creds,\n         @TimeStamp Provider<String> timeStampProvider, Crypto crypto, HttpUtils utils,\n         DateService dateService) {\n      this.isVhostStyle = isVhostStyle;\n      this.servicePath = servicePath;\n      this.headerTag = headerTag;\n      this.authTag = authTag;\n      this.signatureWire = signatureWire;\n      this.creds = creds;\n      this.timeStampProvider = timeStampProvider;\n      this.crypto = crypto;\n      this.utils = utils;\n      this.dateService = dateService;\n   }\n\n   public HttpRequest filter(HttpRequest request) throws HttpException {\n      request = replaceDateHeader(request);\n      Credentials current = creds.get();\n      if (current instanceof SessionCredentials) {\n         request = replaceSecurityTokenHeader(request, SessionCredentials.class.cast(current));\n      }\n      String signature = calculateSignature(createStringToSign(request));\n      request = replaceAuthorizationHeader(request, signature);\n      utils.logRequest(signatureLog, request, \"<<\");\n      return request;\n   }\n\n   HttpRequest replaceSecurityTokenHeader(HttpRequest request, SessionCredentials current) {\n      return request.toBuilder().replaceHeader(\"x-amz-security-token\", current.getSessionToken()).build();\n   }\n\n   protected HttpRequest replaceAuthorizationHeader(HttpRequest request, String signature) {\n      request = request.toBuilder()\n            .replaceHeader(HttpHeaders.AUTHORIZATION,\n                  authTag + \" \" + creds.get().identity + \":\" + signature).build();\n      return request;\n   }\n\n   HttpRequest replaceDateHeader(HttpRequest request) {\n      request = request.toBuilder().replaceHeader(HttpHeaders.DATE, timeStampProvider.get()).build();\n      return request;\n   }\n\n   public String createStringToSign(HttpRequest request) {\n      utils.logRequest(signatureLog, request, \">>\");\n      SortedSetMultimap<String, String> canonicalizedHeaders = TreeMultimap.create();\n      StringBuilder buffer = new StringBuilder();\n      // re-sign the request\n      appendMethod(request, buffer);\n      appendPayloadMetadata(request, buffer);\n      appendHttpHeaders(request, canonicalizedHeaders);\n\n      // Remove default date timestamp if \"x-amz-date\" is set.\n      if (canonicalizedHeaders.containsKey(\"x-\" + headerTag + \"-date\")) {\n         canonicalizedHeaders.removeAll(\"date\");\n      }\n\n      appendAmzHeaders(canonicalizedHeaders, buffer);\n      appendBucketName(request, buffer);\n      appendUriPath(request, buffer);\n      if (signatureWire.enabled()) {\n         signatureWire.output(buffer.toString());\n      }\n      return buffer.toString();\n   }\n\n   String calculateSignature(String toSign) throws HttpException {\n      String signature = sign(toSign);\n      if (signatureWire.enabled()) {\n         signatureWire.input(toInputStream(signature));\n      }\n      return signature;\n   }\n\n   public String sign(String toSign) {\n      try {\n         ByteProcessor<byte[]> hmacSHA1 = asByteProcessor(\n               crypto.hmacSHA1(creds.get().credential.getBytes(UTF_8)));\n         return base64().encode(readBytes(toInputStream(toSign), hmacSHA1));\n      } catch (Exception e) {\n         throw new HttpException(\"error signing request\", e);\n      }\n   }\n\n   void appendMethod(HttpRequest request, StringBuilder toSign) {\n      toSign.append(request.getMethod()).append(\"\\n\");\n   }\n\n   @VisibleForTesting\n   void appendAmzHeaders(SortedSetMultimap<String, String> canonicalizedHeaders, StringBuilder toSign) {\n      for (Map.Entry<String, String> header : canonicalizedHeaders.entries()) {\n         String key = header.getKey();\n         if (key.startsWith(\"x-\" + headerTag + \"-\")) {\n            toSign.append(String.format(\"%s:%s\\n\", key.toLowerCase(), header.getValue()));\n         }\n      }\n   }\n\n   void appendPayloadMetadata(HttpRequest request, StringBuilder buffer) {\n      // note that we fall back to headers, and some requests such as ?uploads do not have a\n      // payload, yet specify payload related parameters\n      buffer.append(\n            request.getPayload() == null ? Strings.nullToEmpty(request.getFirstHeaderOrNull(\"Content-MD5\")) :\n                  HttpUtils.nullToEmpty(\n                        request.getPayload() == null ? null : request.getPayload().getContentMetadata()\n                              .getContentMD5())).append(\"\\n\");\n      buffer.append(\n            Strings.nullToEmpty(\n                  request.getPayload() == null ? request.getFirstHeaderOrNull(HttpHeaders.CONTENT_TYPE)\n                        : request.getPayload().getContentMetadata().getContentType())).append(\"\\n\");\n      for (String header : FIRST_HEADERS_TO_SIGN)\n         buffer.append(HttpUtils.nullToEmpty(request.getHeaders().get(header))).append(\"\\n\");\n   }\n\n   @VisibleForTesting\n   void appendHttpHeaders(HttpRequest request, SortedSetMultimap<String, String> canonicalizedHeaders) {\n      Multimap<String, String> headers = request.getHeaders();\n      for (Map.Entry<String, String> header : headers.entries()) {\n         if (header.getKey() == null) {\n            continue;\n         }\n         String key = header.getKey().toString().toLowerCase(Locale.getDefault());\n         // Ignore any headers that are not particularly interesting.\n         if (key.equalsIgnoreCase(HttpHeaders.CONTENT_TYPE) || key.equalsIgnoreCase(\"Content-MD5\")\n               || key.equalsIgnoreCase(HttpHeaders.DATE) || key.startsWith(\"x-\" + headerTag + \"-\")) {\n            canonicalizedHeaders.put(key, header.getValue());\n         }\n      }\n   }\n\n   @VisibleForTesting\n   void appendBucketName(HttpRequest req, StringBuilder toSign) {\n      String bucketName = S3Utils.getBucketName(req);\n\n      // If we have a payload/bucket/container that is not all lowercase, vhost-style URLs are not an option and must be\n      // automatically converted to their path-based equivalent.  This should only be possible for AWS-S3 since it is\n      // the only S3 implementation configured to allow uppercase payload/bucket/container names.\n      //\n      // http://code.google.com/p/jclouds/issues/detail?id=992\n      if (isVhostStyle && bucketName != null && bucketName.equals(bucketName.toLowerCase())) {\n         toSign.append(servicePath).append(bucketName);\n      }\n   }\n\n   @VisibleForTesting\n   void appendUriPath(HttpRequest request, StringBuilder toSign) {\n\n      toSign.append(request.getEndpoint().getRawPath());\n\n      // ...however, there are a few exceptions that must be included in the\n      // signed URI.\n      if (request.getEndpoint().getQuery() != null) {\n         Multimap<String, String> params = queryParser().apply(request.getEndpoint().getRawQuery());\n         char separator = '?';\n         for (String paramName : Ordering.natural().sortedCopy(params.keySet())) {\n            // Skip any parameters that aren't part of the canonical signed string\n            if (!SIGNED_PARAMETERS.contains(paramName)) {\n               continue;\n            }\n            toSign.append(separator).append(paramName);\n            String paramValue = get(params.get(paramName), 0);\n            if (paramValue != null) {\n               toSign.append(\"=\").append(paramValue);\n            }\n            separator = '&';\n         }\n      }\n   }\n\n   @Override\n   public HttpRequest signForTemporaryAccess(HttpRequest request, long timeInSeconds) {\n      // Update the 'DATE' header\n      String dateString = request.getFirstHeaderOrNull(HttpHeaders.DATE);\n      if (dateString == null) {\n         dateString = timeStampProvider.get();\n      }\n      Date date = dateService.rfc1123DateParse(dateString);\n      String expiration = String.valueOf(TimeUnit.MILLISECONDS.toSeconds(date.getTime()) + timeInSeconds);\n      HttpRequest.Builder<?> builder = request.toBuilder()\n         .removeHeader(HttpHeaders.AUTHORIZATION)\n         .replaceHeader(HttpHeaders.DATE, expiration);\n      String stringToSign = createStringToSign(builder.build());\n      String signature = sign(stringToSign);\n      HttpRequest ret = builder\n         .addQueryParam(HttpHeaders.EXPIRES, expiration)\n         .addQueryParam(\"AWSAccessKeyId\", creds.get().identity)\n         // Signature MUST be the last parameter because if it isn't, even encoded '+' values in the\n         // signature will be converted to a space by a subsequent addQueryParameter.\n         // See HttpRequestTest.testAddBase64AndUrlEncodedQueryParams for more details.\n         .addQueryParam(S3Constants.TEMPORARY_SIGNATURE_PARAM, signature)\n         .removeHeader(HttpHeaders.DATE)\n         // remove signer created by RestAnnotationProcessor\n         .filters(ImmutableList.<HttpRequestFilter>of())\n         .build();\n      return ret;\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/filters/RequestAuthorizeSignatureV4.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.filters;\n\nimport com.google.common.reflect.TypeToken;\nimport com.google.inject.Singleton;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.io.Payload;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.jclouds.s3.S3Client;\n\nimport jakarta.inject.Inject;\n\n@Singleton\npublic class RequestAuthorizeSignatureV4 implements RequestAuthorizeSignature {\n\n   private static final String PUT_OBJECT_METHOD = \"putObject\";\n   private static final TypeToken<S3Client> S3_CLIENT_TYPE = new TypeToken<S3Client>() {\n   };\n\n   private final Aws4SignerForAuthorizationHeader signerForAuthorizationHeader;\n   private final Aws4SignerForChunkedUpload signerForChunkedUpload;\n   private final Aws4SignerForQueryString signerForQueryString;\n\n   @Inject\n   public RequestAuthorizeSignatureV4(Aws4SignerForAuthorizationHeader signerForAuthorizationHeader,\n         Aws4SignerForChunkedUpload signerForChunkedUpload,\n         Aws4SignerForQueryString signerForQueryString) {\n      this.signerForAuthorizationHeader = signerForAuthorizationHeader;\n      this.signerForChunkedUpload = signerForChunkedUpload;\n      this.signerForQueryString = signerForQueryString;\n   }\n\n   @Override\n   public HttpRequest filter(HttpRequest request) throws HttpException {\n      // request use chunked upload\n      if (useChunkedUpload(request)) {\n         return signForChunkedUpload(request);\n      }\n      return signForAuthorizationHeader(request);\n   }\n\n   /**\n    * returns true, if use AWS S3 chunked upload.\n    */\n   protected boolean useChunkedUpload(HttpRequest request) {\n      // only S3Client putObject method, payload not null, content-length > 0 and cannot repeatable\n      if (!GeneratedHttpRequest.class.isAssignableFrom(request.getClass())) {\n         return false;\n      }\n      GeneratedHttpRequest req = GeneratedHttpRequest.class.cast(request);\n\n      // s3 client type and method name is putObject\n      if (S3_CLIENT_TYPE.equals(req.getInvocation().getInvokable().getOwnerType()) &&\n            !PUT_OBJECT_METHOD.equals(req.getInvocation().getInvokable().getName())) {\n         return false;\n      }\n\n      Payload payload = req.getPayload();\n\n      // check payload null or payload.contentMetadata null\n      if (payload == null || payload.getContentMetadata() == null) {\n         return false;\n      }\n\n      Long contentLength = payload.getContentMetadata().getContentLength();\n\n      if (contentLength == null) {\n         return false;\n      }\n\n      return contentLength > 0L && !payload.isRepeatable();\n   }\n\n   protected HttpRequest signForAuthorizationHeader(HttpRequest request) {\n      return signerForAuthorizationHeader.sign(request);\n   }\n\n   protected HttpRequest signForChunkedUpload(HttpRequest request) {\n      return signerForChunkedUpload.sign(request);\n   }\n\n   // Authenticating Requests by Using Query Parameters (AWS Signature Version 4)\n\n   /**\n    * Using query parameters to authenticate requests is useful when you want to express a request entirely in a URL.\n    * This method is also referred as presigning a URL. Presigned URLs enable you to grant temporary access to your\n    * Amazon S3 resources. The end user can then enter the presigned URL in his or her browser to access the specific\n    * Amazon S3 resource. You can also use presigned URLs to embed clickable links in HTML.\n    * <p/>\n    * For example, you might store videos in an Amazon S3 bucket and make them available on your website by using presigned URLs.\n    * Identifies the version of AWS Signature and the algorithm that you used to calculate the signature.\n    */\n   @Override\n   public HttpRequest signForTemporaryAccess(HttpRequest request, long timeInSeconds) {\n      return signerForQueryString.sign(request, timeInSeconds);\n   }\n\n\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/filters/package-info.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * This package contains HttpRequestFilters needed to operate the REST api.\n */\npackage org.jclouds.s3.filters;\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/functions/AssignCorrectHostnameForBucket.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.functions;\n\nimport java.net.URI;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.location.functions.RegionToEndpointOrProviderIfNull;\nimport org.jclouds.s3.Bucket;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\n\npublic final class AssignCorrectHostnameForBucket implements Function<Object, URI> {\n\n   private final RegionToEndpointOrProviderIfNull delegate;\n   private final Function<String, Optional<String>> bucketToRegion;\n\n   @Inject\n   AssignCorrectHostnameForBucket(RegionToEndpointOrProviderIfNull delegate,\n            @Bucket Function<String, Optional<String>> bucketToRegion) {\n      this.bucketToRegion = bucketToRegion;\n      this.delegate = delegate;\n   }\n\n   @Override\n   public URI apply(Object from) {\n      String bucket = from.toString();\n      Optional<String> region = bucketToRegion.apply(bucket);\n      if (region.isPresent()) {\n         return delegate.apply(region.get());\n      }\n      return delegate.apply(null);\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/functions/BindRegionToXmlPayload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.functions;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.location.Region;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.rest.binders.BindToStringPayload;\nimport org.jclouds.s3.Bucket;\n\nimport com.google.common.base.Supplier;\n\n/**\n * \n * Depending on your latency and legal requirements, you can specify a location\n * constraint that will affect where your data physically resides.\n */\n@Singleton\npublic class BindRegionToXmlPayload extends BindToStringPayload {\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   private final Supplier<String> defaultRegionForEndpointSupplier;\n   private final Supplier<String> defaultRegionForServiceSupplier;\n   private final Supplier<Set<String>> regionsSupplier;\n\n   @Inject\n   public BindRegionToXmlPayload(@Region  Supplier<String> defaultRegionForEndpointSupplier,\n          @Bucket Supplier<String> defaultRegionForServiceSupplier, @Region Supplier<Set<String>> regionsSupplier) {\n      this.defaultRegionForEndpointSupplier = defaultRegionForEndpointSupplier;\n      this.defaultRegionForServiceSupplier = defaultRegionForServiceSupplier;\n      this.regionsSupplier = checkNotNull(regionsSupplier, \"regions\");\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      String defaultRegionForEndpoint = defaultRegionForEndpointSupplier.get();\n      if (defaultRegionForEndpoint == null)\n         return request;\n      input = input == null ? defaultRegionForEndpoint : input;\n      checkArgument(input instanceof String, \"this binder is only valid for Region!\");\n      String constraint = (String) input;\n      String value = null;\n      String defaultRegionForService = defaultRegionForServiceSupplier.get();\n      Set<String> regions = regionsSupplier.get();\n      if ((defaultRegionForService == null && constraint == null)\n            || (defaultRegionForService != null && defaultRegionForService.equals(constraint))) {\n         // nothing to bind as this is default.\n         return request;\n      } else if (regions.contains(constraint)) {\n         value = constraint;\n      } else {\n         logger.warn(\"region %s not in %s \", constraint, regions);\n         value = constraint;\n      }\n      String payload = String\n            .format(\n                  \"<CreateBucketConfiguration><LocationConstraint>%s</LocationConstraint></CreateBucketConfiguration>\",\n                  value);\n      request = super.bindToRequest(request, payload);\n      request.getPayload().getContentMetadata().setContentType(MediaType.TEXT_XML);\n      return request;\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/functions/DefaultEndpointThenInvalidateRegion.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.functions;\n\nimport java.net.URI;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.s3.Bucket;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.common.cache.LoadingCache;\n\npublic final class DefaultEndpointThenInvalidateRegion implements Function<Object, URI> {\n\n   private final Function<Object, URI> delegate;\n   private final LoadingCache<String, Optional<String>> bucketToRegionCache;\n\n   @Inject\n   DefaultEndpointThenInvalidateRegion(AssignCorrectHostnameForBucket delegate,\n         @Bucket LoadingCache<String, Optional<String>> bucketToRegionCache) {\n      this.delegate = delegate;\n      this.bucketToRegionCache = bucketToRegionCache;\n   }\n\n   @Override\n   public URI apply(@Nullable Object from) {\n      try {\n         return delegate.apply(from);\n      } finally {\n         bucketToRegionCache.invalidate(from.toString());\n      }\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/functions/ETagFromHttpResponseViaRegex.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.functions;\n\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ReturnStringIf2xx;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class ETagFromHttpResponseViaRegex implements Function<HttpResponse, String> {\n   private static final Pattern PATTERN = Pattern.compile(\"<ETag>([\\\\S&&[^<]]+)</ETag>\");\n   private static final String ESCAPED_QUOTE = \"&quot;\";\n   private final ReturnStringIf2xx returnStringIf200;\n\n   @Inject\n   ETagFromHttpResponseViaRegex(ReturnStringIf2xx returnStringIf200) {\n      this.returnStringIf200 = returnStringIf200;\n   }\n\n   @Override\n   public String apply(HttpResponse response) {\n      String value = null;\n      String content = returnStringIf200.apply(response);\n      if (content != null) {\n         Matcher matcher = PATTERN.matcher(content);\n         if (matcher.find()) {\n            value = matcher.group(1);\n            if (value.indexOf(ESCAPED_QUOTE) != -1) {\n               value = value.replace(ESCAPED_QUOTE, \"\\\"\");\n            }\n         }\n      }\n      return value;\n   }\n\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/functions/GetRegionForBucket.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.functions;\n\nimport java.util.concurrent.ExecutionException;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.logging.Logger;\nimport org.jclouds.s3.Bucket;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.common.cache.CacheLoader.InvalidCacheLoadException;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.util.concurrent.UncheckedExecutionException;\n\n@Singleton\npublic class GetRegionForBucket implements Function<String, Optional<String>> {\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   protected final LoadingCache<String, Optional<String>> bucketToRegion;\n\n   @Inject\n   public GetRegionForBucket(@Bucket LoadingCache<String, Optional<String>> bucketToRegion) {\n      this.bucketToRegion = bucketToRegion;\n   }\n\n   @Override\n   public Optional<String> apply(String bucket) {\n      try {\n         return bucketToRegion.get(bucket);\n      } catch (ExecutionException e) {\n         logger.debug(\"error looking up region for bucket %s: %s\", bucket, e);\n      } catch (UncheckedExecutionException e) {\n         logger.debug(\"error looking up region for bucket %s: %s\", bucket, e);\n      } catch (InvalidCacheLoadException e) {\n         logger.trace(\"bucket %s not found: %s\", bucket, e);\n      }\n      return Optional.absent();\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/functions/ObjectKey.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.functions;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.s3.domain.S3Object;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class ObjectKey implements Function<Object, String> {\n\n   public String apply(Object from) {\n      return ((S3Object) from).getMetadata().getKey();\n   }\n\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/functions/ObjectMetadataKey.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.functions;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.s3.domain.ObjectMetadata;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class ObjectMetadataKey implements Function<Object, String> {\n\n   public String apply(Object from) {\n      return ((ObjectMetadata) from).getKey();\n   }\n\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/functions/ParseObjectFromHeadersAndHttpContent.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.functions;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rest.InvocationContext;\nimport org.jclouds.s3.domain.MutableObjectMetadata;\nimport org.jclouds.s3.domain.S3Object;\n\nimport com.google.common.base.Function;\n\n/**\n * Parses response headers and creates a new S3Object from them and the HTTP content.\n * \n * @see ParseMetadataFromHeaders\n */\npublic class ParseObjectFromHeadersAndHttpContent implements Function<HttpResponse, S3Object>,\n      InvocationContext<ParseObjectFromHeadersAndHttpContent> {\n\n   private final ParseObjectMetadataFromHeaders metadataParser;\n   private final S3Object.Factory objectProvider;\n\n   @Inject\n   public ParseObjectFromHeadersAndHttpContent(ParseObjectMetadataFromHeaders metadataParser,\n         S3Object.Factory objectProvider) {\n      this.metadataParser = metadataParser;\n      this.objectProvider = objectProvider;\n   }\n\n   public S3Object apply(HttpResponse from) {\n      MutableObjectMetadata metadata = metadataParser.apply(from);\n      S3Object object = objectProvider.create(metadata);\n      object.getAllHeaders().putAll(from.getHeaders());\n      object.setPayload(from.getPayload());\n      return object;\n   }\n\n   @Override\n   public ParseObjectFromHeadersAndHttpContent setContext(HttpRequest request) {\n      metadataParser.setContext(request);\n      return this;\n   }\n\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/functions/ParseObjectMetadataFromHeaders.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.functions;\n\nimport static com.google.common.io.BaseEncoding.base16;\nimport static org.jclouds.blobstore.reference.BlobStoreConstants.PROPERTY_USER_METADATA_PREFIX;\n\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\n\nimport org.jclouds.blobstore.domain.BlobMetadata;\nimport org.jclouds.blobstore.functions.ParseSystemAndUserMetadataFromHeaders;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rest.InvocationContext;\nimport org.jclouds.s3.blobstore.functions.BlobToObjectMetadata;\nimport org.jclouds.s3.domain.MutableObjectMetadata;\nimport org.jclouds.s3.domain.ObjectMetadata.StorageClass;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Function;\n\n/** This parses {@ link MutableObjectMetadata} from HTTP headers. */\npublic class ParseObjectMetadataFromHeaders implements Function<HttpResponse, MutableObjectMetadata>,\n         InvocationContext<ParseObjectMetadataFromHeaders> {\n   private final ParseSystemAndUserMetadataFromHeaders blobMetadataParser;\n   private final BlobToObjectMetadata blobToObjectMetadata;\n   private final String userMdPrefix;\n\n   @Inject\n   public ParseObjectMetadataFromHeaders(ParseSystemAndUserMetadataFromHeaders blobMetadataParser,\n            BlobToObjectMetadata blobToObjectMetadata, @Named(PROPERTY_USER_METADATA_PREFIX) String userMdPrefix) {\n      this.blobMetadataParser = blobMetadataParser;\n      this.blobToObjectMetadata = blobToObjectMetadata;\n      this.userMdPrefix = userMdPrefix;\n   }\n\n   // eTag pattern can be \"a34d7e626b350d2e326196085dfa52f4-1\", which is opaque and shouldn't be\n   // used as content-md5, so filter etags that contain hyphens\n   static final Pattern MD5_FROM_ETAG = Pattern.compile(\"^\\\"?([0-9a-f]+)\\\"?$\");\n\n   /** parses the http response headers to create a new {@link MutableObjectMetadata} object. */\n   public MutableObjectMetadata apply(HttpResponse from) {\n      BlobMetadata base = blobMetadataParser.apply(from);\n      MutableObjectMetadata to = blobToObjectMetadata.apply(base);\n\n      addETagTo(from, to);\n      if (to.getContentMetadata().getContentMD5() == null && to.getETag() != null) {\n         Matcher md5Matcher = MD5_FROM_ETAG.matcher(to.getETag());\n         if (md5Matcher.find()) {\n            byte[] md5 = base16().lowerCase().decode(md5Matcher.group(1));\n            // it is possible others will look at the http payload directly\n            if (from.getPayload() != null)\n               from.getPayload().getContentMetadata().setContentMD5(md5);\n            to.getContentMetadata().setContentMD5(md5);\n         }\n      }\n      // amz has an etag, but matches syntax for usermetadata\n      to.getUserMetadata().remove(\"object-etag\");\n      to.setCacheControl(from.getPayload().getContentMetadata().getCacheControl());\n      String storageClass = from.getFirstHeaderOrNull(\"x-amz-storage-class\");\n      if (storageClass != null) {\n         to.setStorageClass(StorageClass.valueOf(storageClass));\n      }\n      return to;\n   }\n\n   /**\n    * ETag == Content-MD5\n    */\n   @VisibleForTesting\n   protected void addETagTo(HttpResponse from, MutableObjectMetadata metadata) {\n      if (metadata.getETag() == null) {\n         String eTagHeader = from.getFirstHeaderOrNull(userMdPrefix + \"object-eTag\");\n         if (eTagHeader != null) {\n            metadata.setETag(eTagHeader);\n         }\n      }\n   }\n\n   @Override\n   public ParseObjectMetadataFromHeaders setContext(HttpRequest request) {\n      blobMetadataParser.setContext(request);\n      blobToObjectMetadata.setContext(request);\n      return this;\n   }\n\n   public ParseObjectMetadataFromHeaders setKey(String key) {\n      blobMetadataParser.setName(key);\n      return this;\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/functions/UploadIdFromHttpResponseViaRegex.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.functions;\n\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ReturnStringIf2xx;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class UploadIdFromHttpResponseViaRegex implements Function<HttpResponse, String> {\n   Pattern pattern = Pattern.compile(\"<UploadId>([\\\\S&&[^<]]+)</UploadId>\");\n   private final ReturnStringIf2xx returnStringIf200;\n\n   @Inject\n   UploadIdFromHttpResponseViaRegex(ReturnStringIf2xx returnStringIf200) {\n      this.returnStringIf200 = returnStringIf200;\n   }\n\n   @Override\n   public String apply(HttpResponse response) {\n      String value = null;\n      String content = returnStringIf200.apply(response);\n      if (content != null) {\n         Matcher matcher = pattern.matcher(content);\n         if (matcher.find()) {\n            value = matcher.group(1);\n         }\n      }\n      return value;\n   }\n\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/functions/package-info.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * This package contains response handlers for S3 commands. \n */\npackage org.jclouds.s3.functions;\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/handlers/ParseS3ErrorFromXmlContent.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.handlers;\n\nimport static com.google.common.collect.Lists.newArrayList;\nimport static org.jclouds.s3.reference.S3Constants.PROPERTY_S3_SERVICE_PATH;\nimport static org.jclouds.s3.reference.S3Constants.PROPERTY_S3_VIRTUAL_HOST_BUCKETS;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.domain.AWSError;\nimport org.jclouds.aws.handlers.ParseAWSErrorFromXmlContent;\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.blobstore.ContainerNotFoundException;\nimport org.jclouds.blobstore.KeyNotFoundException;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.rest.ResourceNotFoundException;\n\nimport com.google.common.base.Joiner;\nimport com.google.common.base.Splitter;\n\n@Singleton\npublic class ParseS3ErrorFromXmlContent extends ParseAWSErrorFromXmlContent {\n\n   private final String servicePath;\n   private final boolean isVhostStyle;\n   private final ProviderMetadata providerMetadata;\n\n   @Inject\n   public ParseS3ErrorFromXmlContent(AWSUtils utils, @Named(PROPERTY_S3_VIRTUAL_HOST_BUCKETS) boolean isVhostStyle,\n            @Named(PROPERTY_S3_SERVICE_PATH) String servicePath, ProviderMetadata providerMetadata) {\n      super(utils);\n      this.servicePath = servicePath;\n      this.isVhostStyle = isVhostStyle;\n      this.providerMetadata = providerMetadata;\n   }\n\n   protected Exception refineException(HttpCommand command, HttpResponse response, Exception exception, AWSError error,\n            String message) {\n      switch (response.getStatusCode()) {\n         case 404:\n            if (!command.getCurrentRequest().getMethod().equals(\"DELETE\")) {\n               String errorCode = (error != null && error.getCode() != null) ? error.getCode() : null;\n               // If we have a payload/bucket/container that is not all lowercase, vhost-style URLs are not an option\n               // and must be automatically converted to their path-based equivalent.  This should only be possible for\n               // AWS-S3 since it is the only S3 implementation configured to allow uppercase payload/bucket/container\n               // names.\n               //\n               // http://code.google.com/p/jclouds/issues/detail?id=992\n               URI defaultS3Endpoint = URI.create(providerMetadata.getApiMetadata().getDefaultEndpoint().get());\n               URI requestEndpoint = command.getCurrentRequest().getEndpoint();\n               boolean wasPathBasedRequest = requestEndpoint.getHost().contains(defaultS3Endpoint.getHost()) &&\n                     requestEndpoint.getHost().equals(defaultS3Endpoint.getHost());\n\n               exception = new ResourceNotFoundException(message, exception);\n               if (isVhostStyle && !wasPathBasedRequest) {\n                  String container = command.getCurrentRequest().getEndpoint().getHost();\n                  String key = command.getCurrentRequest().getEndpoint().getPath();\n                  if (\"NoSuchBucket\".equals(errorCode) || key == null || key.equals(\"/\"))\n                     exception = new ContainerNotFoundException(container, message);\n                  else\n                     exception = new KeyNotFoundException(container, key, message);\n               } else if (command.getCurrentRequest().getEndpoint().getPath()\n                        .indexOf(servicePath.equals(\"/\") ? \"/\" : servicePath + \"/\") == 0) {\n                  String path = command.getCurrentRequest().getEndpoint().getPath().substring(servicePath.length());\n                  // TODO: could parse this out of error.getDetails() using BucketName and Key\n                  List<String> parts = newArrayList(Splitter.on('/').omitEmptyStrings().split(path));\n                  if (\"NoSuchBucket\".equals(errorCode) || parts.size() == 1) {\n                     exception = new ContainerNotFoundException(parts.get(0), message);\n                  } else if (parts.size() > 1) {\n                     exception = new KeyNotFoundException(parts.remove(0), Joiner.on('/').join(parts), message);\n                  }\n               }\n            }\n            return exception;\n         default:\n            return super.refineException(command, response, exception, error, message);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/handlers/S3RedirectionRetryHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.handlers;\n\nimport static org.jclouds.http.HttpUtils.closeClientButKeepContentStream;\nimport static org.jclouds.http.Uris.uriBuilder;\n\nimport java.net.URI;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.domain.AWSError;\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.handlers.BackoffLimitedRetryHandler;\nimport org.jclouds.http.handlers.RedirectionRetryHandler;\n\nimport com.google.common.net.HttpHeaders;\n\n/**\n * Handles Retryable responses with error codes in the 3xx range\n */\n@Singleton\npublic class S3RedirectionRetryHandler extends RedirectionRetryHandler {\n   private final AWSUtils utils;\n\n   @Inject\n   public S3RedirectionRetryHandler(BackoffLimitedRetryHandler backoffHandler, AWSUtils utils) {\n      super(backoffHandler);\n      this.utils = utils;\n   }\n\n   @Override\n   public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) {\n      if (response.getFirstHeaderOrNull(HttpHeaders.LOCATION) == null\n            && (response.getStatusCode() == 301 || response.getStatusCode() == 307)) {\n         command.incrementRedirectCount();\n         closeClientButKeepContentStream(response);\n         AWSError error = utils.parseAWSErrorFromContent(command.getCurrentRequest(), response);\n         String host = error == null ? null : error.getDetails().get(\"Endpoint\");\n         if (host != null) {\n            if (host.equals(command.getCurrentRequest().getEndpoint().getHost())) {\n               // must be an amazon error related to\n               // http://developer.amazonwebservices.com/connect/thread.jspa?messageID=72287&#72287\n               return backoffHandler.shouldRetryRequest(command, response);\n            } else {\n               URI newHost = uriBuilder(command.getCurrentRequest().getEndpoint()).host(host).build();\n               command.setCurrentRequest(command.getCurrentRequest().toBuilder().endpoint(newHost).build());\n            }\n            return true;\n         } else {\n            return false;\n         }\n      } else {\n         return super.shouldRetryRequest(command, response);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/options/CopyObjectOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static org.jclouds.aws.reference.AWSConstants.PROPERTY_HEADER_TAG;\nimport static org.jclouds.blobstore.reference.BlobStoreConstants.PROPERTY_USER_METADATA_PREFIX;\nimport static org.jclouds.s3.reference.S3Headers.CANNED_ACL;\nimport static org.jclouds.s3.reference.S3Headers.COPY_SOURCE_IF_MATCH;\nimport static org.jclouds.s3.reference.S3Headers.COPY_SOURCE_IF_MODIFIED_SINCE;\nimport static org.jclouds.s3.reference.S3Headers.COPY_SOURCE_IF_NO_MATCH;\nimport static org.jclouds.s3.reference.S3Headers.COPY_SOURCE_IF_UNMODIFIED_SINCE;\nimport static org.jclouds.s3.reference.S3Headers.DEFAULT_AMAZON_HEADERTAG;\nimport static org.jclouds.s3.reference.S3Headers.METADATA_DIRECTIVE;\n\nimport java.util.Date;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.http.options.BaseHttpRequestOptions;\nimport org.jclouds.s3.domain.CannedAccessPolicy;\n\nimport com.google.common.base.Preconditions;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.Multimap;\nimport com.google.common.net.HttpHeaders;\n\n/**\n * Contains options supported in the REST API for the COPY object operation.\n * <p/>\n * <h2>Usage</h2> The recommended way to instantiate a CopyObjectOptions object is to statically\n * import CopyObjectOptions.Builder.* and invoke a static creation method followed by an instance\n * mutator (if needed):\n * <p/>\n * <code>\n * import static org.jclouds.s3.commands.options.CopyObjectOptions.Builder.*\n * <p/>\n * S3Client connection = // get connection\n * <p/>\n * Multimap<String,String> metadata = LinkedHashMultimap.create();\n * metadata.put(\"x-amz-meta-adrian\", \"foo\");\n * <p/>\n * // this will copy the object, provided it wasn't modified since yesterday.\n * // it will not use metadata from the source, and instead use what we pass in.\n * Future<S3Object.Metadata> object = connection.copyObject(\"sourceBucket\", \"objectName\",\n * \"destinationBucket\", \"destinationName\",\n * overrideMetadataWith(meta).\n * ifSourceModifiedSince(new Date().minusDays(1))\n * );\n * <code>\n */\npublic class CopyObjectOptions extends BaseHttpRequestOptions {\n   private static final DateService dateService = new SimpleDateFormatDateService();\n   public static final CopyObjectOptions NONE = new CopyObjectOptions();\n   private String cacheControl;\n   private String contentDisposition;\n   private String contentEncoding;\n   private String contentLanguage;\n   private String contentType;\n   private Map<String, String> metadata;\n   private CannedAccessPolicy acl = CannedAccessPolicy.PRIVATE;\n\n   private String metadataPrefix;\n\n   @Inject\n   public void setMetadataPrefix(@Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix) {\n      this.metadataPrefix = metadataPrefix;\n   }\n\n   private String headerTag;\n\n   @Inject\n   public void setHeaderTag(@Named(PROPERTY_HEADER_TAG) String headerTag) {\n      this.headerTag = headerTag;\n   }\n\n   /**\n    * Override the default ACL (private) with the specified one.\n    * \n    * @see CannedAccessPolicy\n    */\n   public CopyObjectOptions overrideAcl(CannedAccessPolicy acl) {\n      this.acl = checkNotNull(acl, \"acl\");\n      if (!acl.equals(CannedAccessPolicy.PRIVATE))\n         this.replaceHeader(CANNED_ACL, acl.toString());\n      return this;\n   }\n\n   /**\n    * @see CopyObjectOptions#overrideAcl(CannedAccessPolicy)\n    */\n   public CannedAccessPolicy getAcl() {\n      return acl;\n   }\n\n   /**\n    * For use in the header x-amz-copy-source-if-unmodified-since\n    * <p/>\n    * Copies the object if it hasn't been modified since the specified time; otherwise returns a 412\n    * (precondition failed).\n    * <p/>\n    * This header can be used with x-amz-copy-source-if-match, but cannot be used with other\n    * conditional copy headers.\n    * \n    * @return valid HTTP date\n    * @see CopyObjectOptions#ifSourceModifiedSince(Date)\n    */\n   public String getIfModifiedSince() {\n      return getFirstHeaderOrNull(COPY_SOURCE_IF_MODIFIED_SINCE);\n   }\n\n   /**\n    * For use in the header x-amz-copy-source-if-modified-since\n    * <p/>\n    * Copies the object if it has been modified since the specified time; otherwise returns a 412\n    * (failed condition).\n    * <p/>\n    * This header can be used with x-amz-copy-source-if-none-match, but cannot be used with other\n    * conditional copy headers.\n    * \n    * @return valid HTTP date\n    * @see CopyObjectOptions#ifSourceUnmodifiedSince(Date)\n    */\n   public String getIfUnmodifiedSince() {\n      return getFirstHeaderOrNull(COPY_SOURCE_IF_UNMODIFIED_SINCE);\n   }\n\n   /**\n    * For use in the request header: x-amz-copy-source-if-match\n    * <p/>\n    * Copies the object if its payload tag (ETag) matches the specified tag; otherwise return a 412\n    * (precondition failed).\n    * <p/>\n    * This header can be used with x-amz-copy-source-if-unmodified-since, but cannot be used with\n    * other conditional copy headers.\n    * \n    * @see CopyObjectOptions#ifSourceETagMatches(String)\n    */\n   public String getIfMatch() {\n      return getFirstHeaderOrNull(COPY_SOURCE_IF_MATCH);\n   }\n\n   /**\n    * For use in the request header: x-amz-copy-source-if-none-match\n    * <p/>\n    * Copies the object if its payload tag (ETag) is different than the specified Etag; otherwise\n    * returns a 412 (failed condition).\n    * <p/>\n    * This header can be used with x-amz-copy-source-if-modified-since, but cannot be used with\n    * other conditional copy headers.\n    * \n    * @see CopyObjectOptions#ifSourceETagDoesntMatch(String)\n    */\n   public String getIfNoneMatch() {\n      return getFirstHeaderOrNull(COPY_SOURCE_IF_NO_MATCH);\n   }\n\n   /**\n    * When not null, contains the header [x-amz-copy-source-if-unmodified-since] -> [REPLACE] and\n    * metadata headers passed in from the users.\n    * \n    * @see #overrideMetadataWith(Multimap)\n    */\n   public Map<String, String> getMetadata() {\n      return metadata;\n   }\n\n   /**\n    * Only return the object if it has changed since this time.\n    * <p/>\n    * Not compatible with {@link #ifSourceETagMatches(String)} or\n    * {@link #ifSourceUnmodifiedSince(Date)}\n    */\n   public CopyObjectOptions ifSourceModifiedSince(Date ifModifiedSince) {\n      checkState(getIfMatch() == null, \"ifETagMatches() is not compatible with ifModifiedSince()\");\n      checkState(getIfUnmodifiedSince() == null, \"ifUnmodifiedSince() is not compatible with ifModifiedSince()\");\n      replaceHeader(COPY_SOURCE_IF_MODIFIED_SINCE, dateService.rfc822DateFormat(checkNotNull(ifModifiedSince,\n               \"ifModifiedSince\")));\n      return this;\n   }\n\n   /**\n    * Only return the object if it hasn't changed since this time.\n    * <p/>\n    * Not compatible with {@link #ifSourceETagDoesntMatch(String)} or\n    * {@link #ifSourceModifiedSince(Date)}\n    */\n   public CopyObjectOptions ifSourceUnmodifiedSince(Date ifUnmodifiedSince) {\n      checkState(getIfNoneMatch() == null, \"ifETagDoesntMatch() is not compatible with ifUnmodifiedSince()\");\n      checkState(getIfModifiedSince() == null, \"ifModifiedSince() is not compatible with ifUnmodifiedSince()\");\n      replaceHeader(COPY_SOURCE_IF_UNMODIFIED_SINCE, dateService.rfc822DateFormat(checkNotNull(ifUnmodifiedSince,\n               \"ifUnmodifiedSince\")));\n      return this;\n   }\n\n   /**\n    * The object's eTag hash should match the parameter <code>eTag</code>.\n    * <p/>\n    * <p/>\n    * Not compatible with {@link #ifSourceETagDoesntMatch(String)} or\n    * {@link #ifSourceModifiedSince(Date)}\n    * \n    * @param eTag\n    *           hash representing the payload\n    */\n   public CopyObjectOptions ifSourceETagMatches(String eTag) {\n      checkState(getIfNoneMatch() == null, \"ifETagDoesntMatch() is not compatible with ifETagMatches()\");\n      checkState(getIfModifiedSince() == null, \"ifModifiedSince() is not compatible with ifETagMatches()\");\n      replaceHeader(COPY_SOURCE_IF_MATCH, maybeQuoteETag(checkNotNull(eTag, \"eTag\")));\n      return this;\n   }\n\n   /**\n    * The object should not have a eTag hash corresponding with the parameter <code>eTag</code>.\n    * <p/>\n    * Not compatible with {@link #ifSourceETagMatches(String)} or\n    * {@link #ifSourceUnmodifiedSince(Date)}\n    * \n    * @param eTag\n    *           hash representing the payload\n    */\n   public CopyObjectOptions ifSourceETagDoesntMatch(String eTag) {\n      checkState(getIfMatch() == null, \"ifETagMatches() is not compatible with ifETagDoesntMatch()\");\n      Preconditions.checkState(getIfUnmodifiedSince() == null,\n               \"ifUnmodifiedSince() is not compatible with ifETagDoesntMatch()\");\n      replaceHeader(COPY_SOURCE_IF_NO_MATCH, maybeQuoteETag(checkNotNull(eTag, \"ifETagDoesntMatch\")));\n      return this;\n   }\n\n   @Override\n   public Multimap<String, String> buildRequestHeaders() {\n      checkState(headerTag != null, \"headerTag should have been injected!\");\n      checkState(metadataPrefix != null, \"metadataPrefix should have been injected!\");\n      ImmutableMultimap.Builder<String, String> returnVal = ImmutableMultimap.builder();\n      for (Entry<String, String> entry : headers.entries()) {\n         returnVal.put(entry.getKey().replace(DEFAULT_AMAZON_HEADERTAG, headerTag), entry.getValue());\n      }\n      boolean replace = false;\n      if (cacheControl != null) {\n         returnVal.put(HttpHeaders.CACHE_CONTROL, cacheControl);\n         replace = true;\n      }\n      if (contentDisposition != null) {\n         returnVal.put(HttpHeaders.CONTENT_DISPOSITION, contentDisposition);\n         replace = true;\n      }\n      if (contentEncoding != null) {\n         returnVal.put(HttpHeaders.CONTENT_ENCODING, contentEncoding);\n         replace = true;\n      }\n      if (contentLanguage != null) {\n         returnVal.put(HttpHeaders.CONTENT_LANGUAGE, contentLanguage);\n         replace = true;\n      }\n      if (contentType != null) {\n         returnVal.put(HttpHeaders.CONTENT_TYPE, contentType);\n         replace = true;\n      }\n      if (metadata != null) {\n         for (Map.Entry<String, String> entry : metadata.entrySet()) {\n            String key = entry.getKey();\n            returnVal.put(key.startsWith(metadataPrefix) ? key : metadataPrefix + key, entry.getValue());\n         }\n         replace = true;\n      }\n      if (replace) {\n         returnVal.put(METADATA_DIRECTIVE.replace(DEFAULT_AMAZON_HEADERTAG, headerTag), \"REPLACE\");\n      }\n      return returnVal.build();\n   }\n\n   public CopyObjectOptions cacheControl(String cacheControl) {\n      this.cacheControl = checkNotNull(cacheControl, \"cacheControl\");\n      return this;\n   }\n\n   public CopyObjectOptions contentDisposition(String contentDisposition) {\n      this.contentDisposition = checkNotNull(contentDisposition, \"contentDisposition\");\n      return this;\n   }\n\n   public CopyObjectOptions contentEncoding(String contentEncoding) {\n      this.contentEncoding = checkNotNull(contentEncoding, \"contentEncoding\");\n      return this;\n   }\n\n   public CopyObjectOptions contentLanguage(String contentLanguage) {\n      this.contentLanguage = checkNotNull(contentLanguage, \"contentLanguage\");\n      return this;\n   }\n\n   public CopyObjectOptions contentType(String contentType) {\n      this.contentType = checkNotNull(contentType, \"contentType\");\n      return this;\n   }\n\n   /**\n    * Use the provided metadata instead of what is on the source object.\n    */\n   public CopyObjectOptions overrideMetadataWith(Map<String, String> metadata) {\n      checkNotNull(metadata, \"metadata\");\n      this.metadata = metadata;\n      return this;\n   }\n\n   public static class Builder {\n      /**\n       * @see CopyObjectOptions#overrideAcl(CannedAccessPolicy)\n       */\n      public static CopyObjectOptions overrideAcl(CannedAccessPolicy acl) {\n         CopyObjectOptions options = new CopyObjectOptions();\n         return options.overrideAcl(acl);\n      }\n\n      /**\n       * @see CopyObjectOptions#getIfModifiedSince()\n       */\n      public static CopyObjectOptions ifSourceModifiedSince(Date ifModifiedSince) {\n         CopyObjectOptions options = new CopyObjectOptions();\n         return options.ifSourceModifiedSince(ifModifiedSince);\n      }\n\n      /**\n       * @see CopyObjectOptions#ifSourceUnmodifiedSince(Date)\n       */\n      public static CopyObjectOptions ifSourceUnmodifiedSince(Date ifUnmodifiedSince) {\n         CopyObjectOptions options = new CopyObjectOptions();\n         return options.ifSourceUnmodifiedSince(ifUnmodifiedSince);\n      }\n\n      /**\n       * @see CopyObjectOptions#ifSourceETagMatches(String)\n       */\n      public static CopyObjectOptions ifSourceETagMatches(String eTag) {\n         CopyObjectOptions options = new CopyObjectOptions();\n         return options.ifSourceETagMatches(eTag);\n      }\n\n      /**\n       * @see CopyObjectOptions#ifSourceETagDoesntMatch(String)\n       */\n      public static CopyObjectOptions ifSourceETagDoesntMatch(String eTag) {\n         CopyObjectOptions options = new CopyObjectOptions();\n         return options.ifSourceETagDoesntMatch(eTag);\n      }\n\n      public static CopyObjectOptions cacheControl(String cacheControl) {\n         CopyObjectOptions options = new CopyObjectOptions();\n         return options.cacheControl(cacheControl);\n      }\n\n      public static CopyObjectOptions contentDisposition(String contentDisposition) {\n         CopyObjectOptions options = new CopyObjectOptions();\n         return options.contentDisposition(contentDisposition);\n      }\n\n      public static CopyObjectOptions contentEncoding(String contentEncoding) {\n         CopyObjectOptions options = new CopyObjectOptions();\n         return options.contentEncoding(contentEncoding);\n      }\n\n      public static CopyObjectOptions contentLanguage(String contentLanguage) {\n         CopyObjectOptions options = new CopyObjectOptions();\n         return options.contentLanguage(contentLanguage);\n      }\n\n      public static CopyObjectOptions contentType(String contentType) {\n         CopyObjectOptions options = new CopyObjectOptions();\n         return options.contentType(contentType);\n      }\n\n      /**\n       * @see #overrideMetadataWith(Multimap)\n       */\n      public static CopyObjectOptions overrideMetadataWith(Map<String, String> metadata) {\n         CopyObjectOptions options = new CopyObjectOptions();\n         return options.overrideMetadataWith(metadata);\n      }\n   }\n\n   private static String maybeQuoteETag(String eTag) {\n      if (!eTag.startsWith(\"\\\"\") && !eTag.endsWith(\"\\\"\")) {\n         eTag = \"\\\"\" + eTag + \"\\\"\";\n      }\n      return eTag;\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/options/ListBucketOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\n/**\n * Contains options supported in the REST API for the GET bucket operation. <h2>\n * Usage</h2> The recommended way to instantiate a GetBucketOptions object is to statically import\n * GetBucketOptions.Builder.* and invoke a static creation method followed by an instance mutator\n * (if needed):\n * <p/>\n * <code>\n * import static org.jclouds.s3.commands.options.GetBucketOptions.Builder.*\n * <p/>\n * S3Client connection = // get connection\n * ListBucketResponse bucket = connection.listBucket(\"bucketName\",withPrefix(\"home/users\").maxKeys(1000));\n * <code>\n */\npublic class ListBucketOptions extends BaseHttpRequestOptions implements Cloneable {\n   public static final ListBucketOptions NONE = new ListBucketOptions();\n\n   /**\n    * Limits the response to keys which begin with the indicated prefix. You can use prefixes to\n    * separate a bucket into different sets of keys in a way similar to how a file system uses\n    * folders.\n    * \n    */\n   public ListBucketOptions withPrefix(String prefix) {\n      queryParameters.put(\"prefix\", checkNotNull(prefix, \"prefix\"));\n      return this;\n   }\n\n   public String getPrefix() {\n      return getFirstQueryOrNull(\"prefix\");\n   }\n\n   /**\n    * Indicates where in the bucket to begin listing. The list will only include keys that occur\n    * lexicographically after marker. This is convenient for pagination: To get the next page of\n    * results use the last key of the current page as the marker.\n    */\n   public ListBucketOptions afterMarker(String marker) {\n      queryParameters.put(\"marker\", checkNotNull(marker, \"marker\"));\n      return this;\n   }\n\n   public String getMarker() {\n      return getFirstQueryOrNull(\"marker\");\n   }\n\n   /**\n    * The maximum number of keys you'd like to see in the response body. The server might return\n    * fewer than this many keys, but will not return more.\n    */\n   public ListBucketOptions maxResults(int maxKeys) {\n      checkState(maxKeys >= 0, \"maxKeys must be >= 0\");\n      queryParameters.put(\"max-keys\", Long.toString(maxKeys));\n      return this;\n   }\n\n   public Integer getMaxResults() {\n      String returnVal = getFirstQueryOrNull(\"max-keys\");\n      return (returnVal != null) ? Integer.valueOf(returnVal) : null;\n   }\n\n   /**\n    * Causes keys that contain the same string between the prefix and the first occurrence of the\n    * delimiter to be rolled up into a single result element in the CommonPrefixes collection. These\n    * rolled-up keys are not returned elsewhere in the response.\n    * \n    */\n   public ListBucketOptions delimiter(String delimiter) {\n      queryParameters.put(\"delimiter\", checkNotNull(delimiter, \"delimiter\"));\n      return this;\n   }\n\n   public String getDelimiter() {\n      return getFirstQueryOrNull(\"delimiter\");\n   }\n\n   public static class Builder {\n\n      /**\n       * @see ListBucketOptions#withPrefix(String)\n       */\n      public static ListBucketOptions withPrefix(String prefix) {\n         ListBucketOptions options = new ListBucketOptions();\n         return options.withPrefix(prefix);\n      }\n\n      /**\n       * @see ListBucketOptions#afterMarker(String)\n       */\n      public static ListBucketOptions afterMarker(String marker) {\n         ListBucketOptions options = new ListBucketOptions();\n         return options.afterMarker(marker);\n      }\n\n      /**\n       * @see ListBucketOptions#maxResults(int)\n       */\n      public static ListBucketOptions maxResults(int maxKeys) {\n         ListBucketOptions options = new ListBucketOptions();\n         return options.maxResults(maxKeys);\n      }\n\n      /**\n       * @see ListBucketOptions#delimiter(String)\n       */\n      public static ListBucketOptions delimiter(String delimiter) {\n         ListBucketOptions options = new ListBucketOptions();\n         return options.delimiter(delimiter);\n      }\n\n   }\n\n   @Override\n   public ListBucketOptions clone() {\n      ListBucketOptions newOptions = new ListBucketOptions();\n      newOptions.queryParameters.putAll(queryParameters);\n      return newOptions;\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/options/PutBucketOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static org.jclouds.aws.reference.AWSConstants.PROPERTY_HEADER_TAG;\n\nimport java.util.Map.Entry;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\nimport org.jclouds.s3.domain.CannedAccessPolicy;\nimport org.jclouds.s3.reference.S3Headers;\n\nimport com.google.common.collect.LinkedHashMultimap;\nimport com.google.common.collect.Multimap;\n\n/**\n * Contains options supported in the REST API for the PUT bucket operation. <h2>\n * Usage</h2> The recommended way to instantiate a PutBucketOptions object is to statically import\n * PutBucketOptions.Builder.* and invoke a static creation method followed by an instance mutator\n * (if needed):\n * <p/>\n * <code>\n * import static org.jclouds.s3.commands.options.PutBucketOptions.Builder.*\n * import static org.jclouds.s3.domain.S3Bucket.Metadata.LocationConstraint.*;\n * import org.jclouds.s3.S3Client;\n * <p/>\n * S3Client connection = // get connection\n * boolean createdInEu = connection.putBucketIfNotExists(\"bucketName\",createIn(EU));\n * <code>\n */\npublic class PutBucketOptions extends BaseHttpRequestOptions {\n   private CannedAccessPolicy acl = CannedAccessPolicy.PRIVATE;\n\n   private String headerTag;\n\n   @Inject\n   public void setHeaderTag(@Named(PROPERTY_HEADER_TAG) String headerTag) {\n      this.headerTag = headerTag;\n   }\n\n   @Override\n   public Multimap<String, String> buildRequestHeaders() {\n      checkState(headerTag != null, \"headerTag should have been injected!\");\n      Multimap<String, String> returnVal = LinkedHashMultimap.create();\n      for (Entry<String, String> entry : headers.entries()) {\n         returnVal.put(entry.getKey().replace(\"aws\", headerTag), entry.getValue());\n      }\n      return returnVal;\n   }\n\n   /**\n    * Override the default ACL (private) with the specified one.\n    * \n    * @see CannedAccessPolicy\n    */\n   public PutBucketOptions withBucketAcl(CannedAccessPolicy acl) {\n      this.acl = checkNotNull(acl, \"acl\");\n      if (!acl.equals(CannedAccessPolicy.PRIVATE))\n         this.replaceHeader(S3Headers.CANNED_ACL, acl.toString());\n      return this;\n   }\n\n   /**\n    * @see PutBucketOptions#withBucketAcl\n    */\n   public CannedAccessPolicy getAcl() {\n      return acl;\n   }\n\n   public static class Builder {\n      /**\n       * @see PutBucketOptions#withBucketAcl\n       */\n      public static PutBucketOptions withBucketAcl(CannedAccessPolicy acl) {\n         PutBucketOptions options = new PutBucketOptions();\n         return options.withBucketAcl(acl);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/options/PutObjectOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static org.jclouds.aws.reference.AWSConstants.PROPERTY_HEADER_TAG;\nimport static org.jclouds.s3.reference.S3Headers.CANNED_ACL;\nimport static org.jclouds.s3.reference.S3Headers.DEFAULT_AMAZON_HEADERTAG;\n\nimport java.util.Map.Entry;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\nimport org.jclouds.s3.domain.CannedAccessPolicy;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.Multimap;\n\n/**\n * Contains options supported in the REST API for the PUT object operation.\n * <p/>\n * <h2>\n * Usage</h2> The recommended way to instantiate a PutObjectOptions object is to statically import\n * PutObjectOptions.Builder.* and invoke a static creation method followed by an instance mutator\n * (if needed):\n * <p/>\n * <code>\n * import static org.jclouds.s3.commands.options.PutObjectOptions.Builder.*\n * import org.jclouds.s3.S3Client;\n * \n * S3Client connection = // get connection\n * boolean publiclyReadable = connection.putObject(\"bucketName\",new S3Object(\"key\",\"value\"), withAcl(CannedAccessPolicy.PUBLIC_READ));\n * <code>\n */\npublic class PutObjectOptions extends BaseHttpRequestOptions {\n   public static final PutObjectOptions NONE = new PutObjectOptions();\n\n   private CannedAccessPolicy acl = CannedAccessPolicy.PRIVATE;\n\n   private String headerTag;\n\n   @Inject\n   public void setHeaderTag(@Named(PROPERTY_HEADER_TAG) String headerTag) {\n      this.headerTag = headerTag;\n   }\n\n   @Override\n   public Multimap<String, String> buildRequestHeaders() {\n      checkState(headerTag != null, \"headerTag should have been injected!\");\n      ImmutableMultimap.Builder<String, String> returnVal = ImmutableMultimap.builder();\n      for (Entry<String, String> entry : headers.entries()) {\n         returnVal.put(entry.getKey().replace(DEFAULT_AMAZON_HEADERTAG, headerTag), entry.getValue());\n      }\n      return returnVal.build();\n   }\n\n   /**\n    * Override the default ACL (private) with the specified one.\n    * \n    * @see CannedAccessPolicy\n    */\n   public PutObjectOptions withAcl(CannedAccessPolicy acl) {\n      this.acl = checkNotNull(acl, \"acl\");\n      if (!acl.equals(CannedAccessPolicy.PRIVATE))\n         this.replaceHeader(CANNED_ACL, acl.toString());\n      return this;\n   }\n\n   /**\n    * @see PutObjectOptions#withAcl(CannedAccessPolicy)\n    */\n   public CannedAccessPolicy getAcl() {\n      return acl;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see PutObjectOptions#withAcl(CannedAccessPolicy)\n       */\n      public static PutObjectOptions withAcl(CannedAccessPolicy acl) {\n         PutObjectOptions options = new PutObjectOptions();\n         return options.withAcl(acl);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/options/package-info.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * This package contains request options for S3 REST commands.\n */\npackage org.jclouds.s3.options;\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/package-info.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * This package contains an Amazon S3 client implemented by {@link org.jclouds.http.HttpCommandExecutorService} commands.\n */\npackage org.jclouds.s3;\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/predicates/validators/BucketNameValidator.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.predicates.validators;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.predicates.Validator;\n\nimport com.google.common.base.CharMatcher;\nimport com.google.inject.Singleton;\n\n/**\n * Validates name for S3 buckets. The complete requirements are listed at:\n * http://docs.amazonwebservices.com/AmazonS3/latest/index.html?BucketRestrictions.html\n * \n * @see org.jclouds.rest.InputParamValidator\n * @see org.jclouds.predicates.Validator\n */\n@Singleton\npublic class BucketNameValidator extends Validator<String> {\n   private static final CharMatcher MATCHER =\n         CharMatcher.inRange('a', 'z')\n         .or(CharMatcher.inRange('A', 'Z'))\n         .or(CharMatcher.inRange('0', '9'))\n         .or(CharMatcher.anyOf(\".-_\"));\n\n   @Inject\n   public BucketNameValidator() {\n   }\n\n   @Override\n   public void validate(String name) {\n      if (name == null) {\n         throw exception(\"\", \"Can't be null\");\n      } else if (name.length() < 3) {\n         throw exception(name, \"Can't be less than 3 characters\");\n      } else if (name.length() > 255) {\n         throw exception(name, \"Can't be over 255 characters\");\n      } else if (!MATCHER.matchesAllOf(name)) {\n         throw exception(name, \"Illegal character\");\n      }\n   }\n\n   private static IllegalArgumentException exception(String containerName, String reason) {\n      return new IllegalArgumentException(String.format(\n            \"Object '%s' doesn't match S3 bucket bucket naming convention. \" +\n            \"Reason: %s. For more info, please refer to https://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html\",\n            containerName, reason));\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/reference/S3Constants.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.reference;\n\n/**\n * Configuration properties and constants used in S3 connections.\n */\npublic final class S3Constants {\n\n   /**\n    * S3 service's XML Namespace, as used in XML request and response documents.\n    */\n   public static final String S3_REST_API_XML_NAMESPACE = \"http://s3.amazonaws.com/doc/2006-03-01/\";\n   public static final String PREFIX = \"prefix\";\n   public static final String MARKER = \"marker\";\n   public static final String MAX_KEYS = \"max-keys\";\n   public static final String DELIMITER = \"delimiter\";\n   public static final String PROPERTY_S3_SERVICE_PATH = \"jclouds.s3.service-path\";\n   public static final String PROPERTY_S3_VIRTUAL_HOST_BUCKETS = \"jclouds.s3.virtual-host-buckets\";\n   public static final String PROPERTY_JCLOUDS_S3_CHUNKED_SIZE = \"jclouds.s3.chunked.size\";\n   public static final String PROPERTY_SIGNER_VERSION = \"jclouds.s3.signer-version\";\n\n   public static final String TEMPORARY_SIGNATURE_PARAM = \"Signature\";\n\n   private S3Constants() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/reference/S3Headers.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.reference;\n\n/** Additional headers specified by Amazon S3 REST API. */\npublic final class S3Headers {\n\n   /**\n    * Amazon S3 has clones, which often replace this with their particular tag.\n    */\n   public static final String DEFAULT_AMAZON_HEADERTAG = \"amz\";\n\n   public static final String HEADER_PREFIX = \"x-\" + DEFAULT_AMAZON_HEADERTAG + \"-\";\n\n   /**\n    * The canned ACL to apply to the object. Options include private, public-read,\n    * public-read-write, and authenticated-read. For more information, see REST Access Control\n    * Policy.\n    */\n   public static final String CANNED_ACL = HEADER_PREFIX + \"acl\";\n\n   public static final String AMZ_ETAG = HEADER_PREFIX + \"meta-object-eTag\";\n\n   /**\n    * Amazon's alternative date header\n    */\n   public static final String ALTERNATE_DATE = HEADER_PREFIX + \"date\";\n\n   /**\n    * Prefix for user metadata\n    */\n   public static final String USER_METADATA_PREFIX = HEADER_PREFIX + \"meta-\";\n\n   /**\n    * version ID header\n    */\n   public static final String VERSION_ID = HEADER_PREFIX + \"version-id\";\n\n   /**\n    * Multi-Factor Authentication header\n    */\n   public static final String MFA = HEADER_PREFIX + \"mfa\";\n\n   /**\n    * response header for a request's AWS request ID\n    */\n   public static final String REQUEST_ID = HEADER_PREFIX + \"request-id\";\n\n   /**\n    * response header for a request's extended debugging ID\n    */\n   public static final String EXTENDED_REQUEST_ID = HEADER_PREFIX + \"id-2\";\n\n   /**\n    * request header indicating how to handle metadata when copying an object\n    */\n   public static final String METADATA_DIRECTIVE = HEADER_PREFIX + \"metadata-directive\";\n\n   /**\n    * DevPay token header\n    */\n   public static final String SECURITY_TOKEN = HEADER_PREFIX + \"security-token\";\n\n   /**\n    * Header describing what class of storage a user wants\n    */\n   public static final String STORAGE_CLASS = HEADER_PREFIX + \"storage-class\";\n\n   /**\n    * ETag matching constraint header for the copy object request\n    */\n   public static final String COPY_SOURCE_IF_MATCH = HEADER_PREFIX + \"copy-source-if-match\";\n\n   /**\n    * ETag non-matching constraint header for the copy object request\n    */\n   public static final String COPY_SOURCE_IF_NO_MATCH = HEADER_PREFIX + \"copy-source-if-none-match\";\n\n   /**\n    * Unmodified since constraint header for the copy object request\n    */\n   public static final String COPY_SOURCE_IF_UNMODIFIED_SINCE = HEADER_PREFIX + \"copy-source-if-unmodified-since\";\n\n   /**\n    * Modified since constraint header for the copy object request\n    */\n   public static final String COPY_SOURCE_IF_MODIFIED_SINCE = HEADER_PREFIX + \"copy-source-if-modified-since\";\n\n   /**\n    * Encrypted symmetric key header that is used in the envelope encryption mechanism\n    */\n   public static final String CRYPTO_KEY = HEADER_PREFIX + \"key\";\n\n   /**\n    * Initialization vector (IV) header that is used in the symmetric and envelope encryption\n    * mechanisms\n    */\n   public static final String CRYPTO_IV = HEADER_PREFIX + \"iv\";\n\n   /**\n    * JSON-encoded description of encryption materials used during encryption\n    */\n   public static final String MATERIALS_DESCRIPTION = HEADER_PREFIX + \"matdesc\";\n\n   /**\n    * Instruction file header to be placed in the metadata of instruction files\n    */\n   public static final String CRYPTO_INSTRUCTION_FILE = HEADER_PREFIX + \"crypto-instr-file\";\n\n   private S3Headers() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/reference/package-info.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * This package contains properties and reference data used in S3.\n */\npackage org.jclouds.s3.reference;\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/util/S3Utils.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.util;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.any;\n\nimport java.lang.annotation.Annotation;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.regex.Pattern;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.reflect.Reflection2;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.jclouds.s3.Bucket;\nimport org.jclouds.s3.S3Client;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.reflect.Parameter;\n\n/**\n * Encryption, Hashing, and IO Utilities needed to sign and verify S3 requests and responses.\n */\npublic class S3Utils {\n\n   private static final Pattern BUCKET_NAME_PATTERN = Pattern.compile(\"^[a-z0-9][-_.a-z0-9]+\");\n   private static final Pattern IP_PATTERN = Pattern.compile(\"b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).)\"\n         + \"{3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)b\");\n\n   // TODO add validatorparam so that this is actually used\n   public static String validateBucketName(String bucketName) {\n      checkNotNull(bucketName, \"bucketName\");\n      checkArgument(\n            BUCKET_NAME_PATTERN.matcher(bucketName).matches(),\n            \"bucketName name must start with a number or letter and  can only contain lowercase letters, numbers, periods (.), underscores (_), and dashes (-)\");\n      checkArgument(bucketName.length() > 2 && bucketName.length() < 256,\n            \"bucketName name must be between 3 and 255 characters long\");\n      checkArgument(!IP_PATTERN.matcher(bucketName).matches(), \"bucketName name cannot be ip address style\");\n      return bucketName;\n   }\n\n   /**\n    * This implementation invokes {@link S3Client#deleteBucketIfEmpty} followed by {@link S3Client#bucketExists} until\n    * it is true.\n    */\n   public static boolean deleteAndVerifyContainerGone(S3Client sync, String container) {\n      sync.deleteBucketIfEmpty(container);\n      return !sync.bucketExists(container);\n   }\n\n   private static final Predicate<Annotation> ANNOTATIONTYPE_BUCKET = new Predicate<Annotation>() {\n      public boolean apply(Annotation input) {\n         return input.annotationType().equals(Bucket.class);\n      }\n   };\n\n   public static String getBucketName(HttpRequest req) {\n      checkArgument(req instanceof GeneratedHttpRequest, \"this should be a generated http request\");\n      GeneratedHttpRequest request = GeneratedHttpRequest.class.cast(req);\n\n      String bucketName = null;\n\n      List<Parameter> parameters = Reflection2.getInvokableParameters(request.getInvocation().getInvokable());\n      for (int i = 0; i < parameters.size(); i++) {\n         if (any(Arrays.asList(parameters.get(i).getAnnotations()), ANNOTATIONTYPE_BUCKET)) {\n            bucketName = (String) request.getInvocation().getArgs().get(i);\n            break;\n         }\n      }\n\n      return bucketName;\n   }\n\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/util/package-info.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * This package contains utilities needed for S3.\n */\npackage org.jclouds.s3.util;\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/xml/AccessControlListHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.xml;\n\nimport static org.jclouds.util.SaxUtils.currentOrNull;\n\nimport java.net.URI;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.s3.domain.AccessControlList;\nimport org.jclouds.s3.domain.AccessControlList.CanonicalUserGrantee;\nimport org.jclouds.s3.domain.AccessControlList.EmailAddressGrantee;\nimport org.jclouds.s3.domain.AccessControlList.Grantee;\nimport org.jclouds.s3.domain.AccessControlList.GroupGrantee;\nimport org.jclouds.s3.domain.CanonicalUser;\nimport org.xml.sax.Attributes;\n\n/**\n * Parses the following XML document:\n * <p/>\n * AccessControlPolicy xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"\n */\npublic class AccessControlListHandler extends ParseSax.HandlerWithResult<AccessControlList> {\n   private AccessControlList acl = new AccessControlList();\n   private StringBuilder currentText = new StringBuilder();\n\n   public AccessControlListHandler() {\n   }\n\n   public AccessControlList getResult() {\n      return acl;\n   }\n\n   private String currentId;\n   private String currentDisplayName;\n   private String currentGranteeType;\n   private String currentPermission;\n   private Grantee currentGrantee;\n\n   public void startElement(String uri, String name, String qName, Attributes attrs) {\n      if (qName.equals(\"Grantee\")) {\n         currentGranteeType = attrs.getValue(\"xsi:type\");\n      }\n   }\n\n   public void endElement(String uri, String name, String qName) {\n      if (qName.equals(\"Owner\")) {\n         CanonicalUser owner = new CanonicalUser(currentId);\n         owner.setDisplayName(currentDisplayName);\n         acl.setOwner(owner);\n      } else if (qName.equals(\"Grantee\")) {\n         if (\"AmazonCustomerByEmail\".equals(currentGranteeType)) {\n            currentGrantee = new EmailAddressGrantee(currentId);\n         } else if (\"CanonicalUser\".equals(currentGranteeType)) {\n            currentGrantee = new CanonicalUserGrantee(currentId, currentDisplayName);\n         } else if (\"Group\".equals(currentGranteeType)) {\n            currentGrantee = new GroupGrantee(URI.create(currentId));\n         }\n      } else if (qName.equals(\"Grant\")) {\n         acl.addPermission(currentGrantee, currentPermission);\n      }\n\n      else if (qName.equals(\"ID\") || qName.equals(\"EmailAddress\") || qName.equals(\"URI\")) {\n         currentId = currentOrNull(currentText);\n      } else if (qName.equals(\"DisplayName\")) {\n         currentDisplayName = currentOrNull(currentText);\n      } else if (qName.equals(\"Permission\")) {\n         currentPermission = currentOrNull(currentText);\n      }\n      currentText.setLength(0);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/xml/BucketLoggingHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.xml;\n\nimport static org.jclouds.util.SaxUtils.currentOrNull;\n\nimport java.net.URI;\nimport java.util.Set;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.s3.domain.AccessControlList.CanonicalUserGrantee;\nimport org.jclouds.s3.domain.AccessControlList.EmailAddressGrantee;\nimport org.jclouds.s3.domain.AccessControlList.Grant;\nimport org.jclouds.s3.domain.AccessControlList.Grantee;\nimport org.jclouds.s3.domain.AccessControlList.GroupGrantee;\nimport org.jclouds.s3.domain.BucketLogging;\nimport org.xml.sax.Attributes;\n\nimport com.google.common.collect.Sets;\n\n/**\n * Parses the following XML document:\n * <p/>\n * BucketLoggingStatus xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"\n */\npublic class BucketLoggingHandler extends ParseSax.HandlerWithResult<BucketLogging> {\n   private Set<Grant> targetGrants = Sets.newHashSet();\n   private StringBuilder currentText = new StringBuilder();\n\n   public BucketLogging getResult() {\n      if (targetBucket == null)\n         return null;\n      return new BucketLogging(targetBucket, targetPrefix, targetGrants);\n   }\n\n   private String currentId;\n   private String currentDisplayName;\n   private String currentGranteeType;\n   private String currentPermission;\n   private Grantee currentGrantee;\n\n   private String targetBucket;\n   private String targetPrefix;\n\n   public void startElement(String uri, String name, String qName, Attributes attrs) {\n      if (qName.equals(\"Grantee\")) {\n         currentGranteeType = attrs.getValue(\"xsi:type\");\n      }\n   }\n\n   public void endElement(String uri, String name, String qName) {\n      if (qName.equals(\"TargetBucket\")) {\n         this.targetBucket = currentOrNull(currentText);\n      } else if (qName.equals(\"TargetPrefix\")) {\n         this.targetPrefix = currentOrNull(currentText);\n      } else if (qName.equals(\"Grantee\")) {\n         if (\"AmazonCustomerByEmail\".equals(currentGranteeType)) {\n            currentGrantee = new EmailAddressGrantee(currentId);\n         } else if (\"CanonicalUser\".equals(currentGranteeType)) {\n            currentGrantee = new CanonicalUserGrantee(currentId, currentDisplayName);\n         } else if (\"Group\".equals(currentGranteeType)) {\n            currentGrantee = new GroupGrantee(URI.create(currentId));\n         }\n      } else if (qName.equals(\"Grant\")) {\n         targetGrants.add(new Grant(currentGrantee, currentPermission));\n      } else if (qName.equals(\"ID\") || qName.equals(\"EmailAddress\") || qName.equals(\"URI\")) {\n         currentId = currentOrNull(currentText);\n      } else if (qName.equals(\"DisplayName\")) {\n         currentDisplayName = currentOrNull(currentText);\n      } else if (qName.equals(\"Permission\")) {\n         currentPermission = currentOrNull(currentText);\n      }\n      currentText.setLength(0);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/xml/CopyObjectHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.xml;\n\nimport static org.jclouds.util.SaxUtils.currentOrNull;\n\nimport java.util.Date;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.s3.domain.ObjectMetadata;\nimport org.jclouds.s3.domain.internal.CopyObjectResult;\n\n/**\n * Parses the response from Amazon S3 COPY Object command.\n * <p/>\n * CopyObjectResult is the document we expect to parse.\n */\npublic class CopyObjectHandler extends ParseSax.HandlerWithResult<ObjectMetadata> {\n\n   private CopyObjectResult metadata;\n   private StringBuilder currentText = new StringBuilder();\n   @Inject\n   private DateService dateParser;\n   private Date currentLastModified;\n   private String currentETag;\n\n   public ObjectMetadata getResult() {\n      return metadata;\n   }\n\n   public void endElement(String uri, String name, String qName) {\n      if (qName.equals(\"ETag\")) {\n         this.currentETag = currentOrNull(currentText);\n      } else if (qName.equals(\"LastModified\")) {\n         this.currentLastModified = dateParser\n             .iso8601DateOrSecondsDateParse(currentOrNull(currentText));\n      } else if (qName.equals(\"CopyObjectResult\")) {\n         metadata = new CopyObjectResult(currentLastModified, currentETag);\n      }\n      currentText.setLength(0);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/xml/DeleteResultHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.xml;\n\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport org.jclouds.s3.domain.DeleteResult;\nimport org.jclouds.http.functions.ParseSax;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\n\npublic class DeleteResultHandler extends ParseSax.HandlerForGeneratedRequestWithResult<DeleteResult> {\n\n   public static final String DELETED_TAG = \"Deleted\";\n   public static final String ERROR_TAG = \"Error\";\n\n   private final ErrorEntryHandler errorEntryHandler = new ErrorEntryHandler();\n\n   private StringBuilder deletedEntryAccumulator = new StringBuilder();\n\n   /**\n    * Accumulator for the set of successfully deleted files\n    */\n   private final ImmutableSet.Builder<String> deleted = ImmutableSet.builder();\n\n   /**\n    * Accumulator for the set of errors\n    */\n   private final ImmutableMap.Builder<String, DeleteResult.Error> errors = ImmutableMap.builder();\n\n   private boolean parsingDeletedEntry = false;\n   private boolean parsingErrorEntry = false;\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void startElement(String uri, String name, String qName, Attributes attributes)\n      throws SAXException {\n      if (equalsOrSuffix(qName, DELETED_TAG)) {\n         parsingDeletedEntry = true;\n      } else if (equalsOrSuffix(qName, ERROR_TAG)) {\n         parsingErrorEntry = true;\n      }\n\n      if (parsingDeletedEntry) {\n         deletedEntryAccumulator.setLength(0);\n      } else if (parsingErrorEntry) {\n         errorEntryHandler.startElement(uri, name, qName, attributes);\n      }\n   }\n\n   @Override\n   public void characters(char[] chars, int start, int length) throws SAXException {\n      if (parsingDeletedEntry) {\n         deletedEntryAccumulator.append(chars, start, length);\n      } else if (parsingErrorEntry) {\n         errorEntryHandler.characters(chars, start, length);\n      }\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void endElement(String uri, String name, String qName) throws SAXException {\n      if (equalsOrSuffix(qName, DELETED_TAG)) {\n         parsingDeletedEntry = false;\n         deleted.add(deletedEntryAccumulator.toString().trim());\n      } else if (equalsOrSuffix(qName, ERROR_TAG)) {\n         parsingErrorEntry = false;\n         errors.put(errorEntryHandler.getResult());\n      }\n\n      if (parsingErrorEntry) {\n         errorEntryHandler.endElement(uri, name, qName);\n      }\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public DeleteResult getResult() {\n      return new DeleteResult(deleted.build(), errors.build());\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/xml/ErrorEntryHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.xml;\n\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport java.util.Map;\n\nimport org.jclouds.s3.domain.DeleteResult;\nimport org.jclouds.http.functions.ParseSax;\nimport org.xml.sax.SAXException;\n\nimport com.google.common.collect.Maps;\n\npublic class ErrorEntryHandler extends ParseSax.HandlerForGeneratedRequestWithResult<Map.Entry<String, DeleteResult.Error>> {\n\n   private StringBuilder accumulator = new StringBuilder();\n\n   private String key;\n   private String code;\n   private String message;\n\n   @Override\n   public void characters(char[] chars, int start, int length) throws SAXException {\n      accumulator.append(chars, start, length);\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) throws SAXException {\n      if (equalsOrSuffix(qName, \"Key\")) {\n         key = accumulator.toString().trim();\n      } else if (equalsOrSuffix(qName, \"Code\")) {\n         code = accumulator.toString().trim();\n      } else if (equalsOrSuffix(qName, \"Message\")) {\n         message = accumulator.toString().trim();\n      }\n      accumulator.setLength(0);\n   }\n\n   @Override\n   public Map.Entry<String, DeleteResult.Error> getResult() {\n      return Maps.immutableEntry(key, new DeleteResult.Error(code, message));\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/xml/ListAllMyBucketsHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.xml;\n\nimport static org.jclouds.util.SaxUtils.currentOrNull;\n\nimport java.util.Date;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.s3.domain.BucketMetadata;\nimport org.jclouds.s3.domain.CanonicalUser;\n\nimport com.google.common.collect.Sets;\n\n/**\n * Parses the following XML document:\n * <p/>\n * SetAllMyBucketsResult xmlns=\"http://doc.s3.amazonaws.com/2006-03-01\"\n */\npublic class ListAllMyBucketsHandler extends ParseSax.HandlerWithResult<Set<BucketMetadata>> {\n\n   private Set<BucketMetadata> buckets = Sets.newLinkedHashSet();\n   private CanonicalUser currentOwner;\n   private String currentDisplayName;\n   private StringBuilder currentText = new StringBuilder();\n\n   private final DateService dateParser;\n   private String currentName;\n   private Date currentCreationDate;\n\n   @Inject\n   public ListAllMyBucketsHandler(DateService dateParser) {\n      this.dateParser = dateParser;\n      this.currentOwner =  new CanonicalUser();\n   }\n\n   public Set<BucketMetadata> getResult() {\n      return buckets;\n   }\n\n   public void endElement(String uri, String name, String qName) {\n      if (qName.equals(\"ID\")) { // owner stuff\n         currentOwner.setId(currentOrNull(currentText));\n      } else if (qName.equals(\"DisplayName\")) {\n         currentOwner.setDisplayName(currentOrNull(currentText));\n      } else if (qName.equals(\"Bucket\")) {\n         buckets.add(new BucketMetadata(currentName, currentCreationDate, currentOwner));\n      } else if (qName.equals(\"Name\")) {\n         currentName = currentOrNull(currentText);\n      } else if (qName.equals(\"CreationDate\")) {\n         currentCreationDate = dateParser\n               .iso8601DateOrSecondsDateParse(currentOrNull(currentText));\n      }\n      currentText.setLength(0);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/xml/ListBucketHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.xml;\n\nimport static com.google.common.io.BaseEncoding.base16;\nimport static org.jclouds.http.Uris.uriBuilder;\nimport static org.jclouds.util.SaxUtils.currentOrNull;\n\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.s3.domain.CanonicalUser;\nimport org.jclouds.s3.domain.ListBucketResponse;\nimport org.jclouds.s3.domain.ObjectMetadata;\nimport org.jclouds.s3.domain.ObjectMetadataBuilder;\nimport org.jclouds.s3.domain.internal.ListBucketResponseImpl;\nimport org.jclouds.util.Strings2;\nimport org.xml.sax.Attributes;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\n\n/**\n * Parses the following XML document:\n * <p/>\n * ListBucketResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01\"\n */\npublic class ListBucketHandler extends ParseSax.HandlerWithResult<ListBucketResponse> {\n   private Builder<ObjectMetadata> contents = ImmutableSet.builder();\n   private Builder<String> commonPrefixes = ImmutableSet.builder();\n   private CanonicalUser currentOwner;\n   private StringBuilder currentText = new StringBuilder();\n\n   private ObjectMetadataBuilder builder = new ObjectMetadataBuilder();\n\n   private final DateService dateParser;\n\n   private String bucketName;\n   private String prefix;\n   private String marker;\n   private int maxResults;\n   private String delimiter;\n   private boolean isTruncated;\n\n   /** Some blobs have a non-hex suffix when created by multi-part uploads such Amazon S3. */\n   private static final Pattern ETAG_CONTENT_MD5_PATTERN = Pattern.compile(\"\\\"([0-9a-f]+)\\\"\");\n\n   @Inject\n   public ListBucketHandler(DateService dateParser) {\n      this.dateParser = dateParser;\n      this.currentOwner = new CanonicalUser();\n   }\n\n   public ListBucketResponse getResult() {\n      return new ListBucketResponseImpl(bucketName, contents.build(), prefix, marker,\n               (isTruncated && nextMarker == null) ? currentKey : nextMarker, maxResults, delimiter, isTruncated,\n               commonPrefixes.build());\n   }\n\n   private boolean inCommonPrefixes;\n   private String currentKey;\n   private String nextMarker;\n\n   public void startElement(String uri, String name, String qName, Attributes attrs) {\n      if (qName.equals(\"CommonPrefixes\")) {\n         inCommonPrefixes = true;\n      }\n      currentText.setLength(0);\n   }\n\n   public void endElement(String uri, String name, String qName) {\n      if (qName.equals(\"ID\")) {\n    \t currentOwner.setId(currentOrNull(currentText));\n      } else if (qName.equals(\"DisplayName\")) {\n         currentOwner.setDisplayName(currentOrNull(currentText));\n      } else if (qName.equals(\"Key\")) { // content stuff\n         if (currentText.length() == 0) {\n            throw new RuntimeException(\"Object store returned empty key name\");\n         }\n         currentKey = currentText.toString();\n         builder.key(currentKey);\n         builder.uri(uriBuilder(getRequest().getEndpoint()).clearQuery().appendPath(Strings2.urlEncode(currentKey))\n               .build());\n      } else if (qName.equals(\"LastModified\")) {\n         builder.lastModified(dateParser\n               .iso8601DateOrSecondsDateParse(currentOrNull(currentText)));\n      } else if (qName.equals(\"ETag\")) {\n         String currentETag = currentOrNull(currentText);\n         builder.eTag(currentETag);\n         Matcher matcher = ETAG_CONTENT_MD5_PATTERN.matcher(currentETag);\n         if (matcher.matches()) {\n            builder.contentMD5(base16().lowerCase().decode(matcher.group(1)));\n         }\n      } else if (qName.equals(\"Size\")) {\n         builder.contentLength(Long.valueOf(currentOrNull(currentText)));\n      } else if (qName.equals(\"Owner\")) {\n         builder.owner(currentOwner);\n         currentOwner = new CanonicalUser();\n      } else if (qName.equals(\"StorageClass\")) {\n         builder.storageClass(ObjectMetadata.StorageClass.valueOf(currentOrNull(currentText)));\n      } else if (qName.equals(\"Contents\")) {\n         contents.add(builder.build());\n         builder = new ObjectMetadataBuilder().bucket(bucketName);\n      } else if (qName.equals(\"Name\")) {\n         this.bucketName = currentOrNull(currentText);\n         builder.bucket(bucketName);\n      } else if (qName.equals(\"Prefix\")) {\n         String prefix = currentOrNull(currentText);\n         if (inCommonPrefixes)\n            commonPrefixes.add(prefix);\n         else\n            this.prefix = prefix;\n      } else if (qName.equals(\"Delimiter\")) {\n         this.delimiter = currentOrNull(currentText);\n      } else if (qName.equals(\"Marker\")) {\n         this.marker = currentOrNull(currentText);\n      } else if (qName.equals(\"NextMarker\")) {\n         this.nextMarker = currentOrNull(currentText);\n      } else if (qName.equals(\"MaxKeys\")) {\n         this.maxResults = Integer.parseInt(currentOrNull(currentText));\n      } else if (qName.equals(\"IsTruncated\")) {\n         this.isTruncated = Boolean.parseBoolean(currentOrNull(currentText));\n      }\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/xml/ListMultipartUploadsHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.xml;\n\nimport static org.jclouds.util.SaxUtils.currentOrNull;\n\nimport java.util.Date;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.s3.domain.CanonicalUser;\nimport org.jclouds.s3.domain.ListMultipartUploadsResponse;\nimport org.jclouds.s3.domain.ObjectMetadata;\nimport org.xml.sax.Attributes;\n\nimport com.google.common.collect.ImmutableList;\n\npublic final class ListMultipartUploadsHandler extends ParseSax.HandlerWithResult<ListMultipartUploadsResponse> {\n   private String bucket;\n   private String keyMarker;\n   private String uploadIdMarker;\n   private String nextKeyMarker;\n   private String nextUploadIdMarker;\n   private int maxUploads;\n   private boolean isTruncated;\n   private final ImmutableList.Builder<ListMultipartUploadsResponse.Upload> uploads = ImmutableList.builder();\n\n   private String key;\n   private String uploadId;\n   private String id;\n   private String displayName;\n   private CanonicalUser initiator;\n   private CanonicalUser owner;\n   private ObjectMetadata.StorageClass storageClass;\n   private Date initiated;\n\n   private final DateService dateParser;\n   private final StringBuilder currentText = new StringBuilder();\n   private boolean inUpload;\n   private boolean inInitiator;\n   private boolean inOwner;\n\n   @Inject\n   public ListMultipartUploadsHandler(DateService dateParser) {\n      this.dateParser = dateParser;\n   }\n\n   public ListMultipartUploadsResponse getResult() {\n      return ListMultipartUploadsResponse.create(bucket, keyMarker, uploadIdMarker, nextKeyMarker, nextUploadIdMarker, maxUploads, isTruncated, uploads.build());\n   }\n\n   public void startElement(String uri, String name, String qName, Attributes attrs) {\n      if (qName.equals(\"Upload\")) {\n         inUpload = true;\n      } else if (qName.equals(\"Initiator\")) {\n         inInitiator = true;\n      } else if (qName.equals(\"Owner\")) {\n         inOwner = true;\n      }\n      currentText.setLength(0);\n   }\n\n   public void endElement(String uri, String name, String qName) {\n      if (qName.equals(\"Bucket\")) {\n         bucket = currentOrNull(currentText);\n      } else if (qName.equals(\"KeyMarker\")) {\n         keyMarker = currentOrNull(currentText);\n      } else if (qName.equals(\"UploadIdMarker\")) {\n         uploadIdMarker = currentOrNull(currentText);\n      } else if (qName.equals(\"NextKeyMarker\")) {\n         nextKeyMarker = currentOrNull(currentText);\n      } else if (qName.equals(\"NextUploadIdMarker\")) {\n         nextUploadIdMarker = currentOrNull(currentText);\n      } else if (qName.equals(\"MaxUploads\")) {\n         maxUploads = Integer.parseInt(currentOrNull(currentText));\n      } else if (qName.equals(\"IsTruncated\")) {\n         isTruncated = Boolean.parseBoolean(currentOrNull(currentText));\n      } else if (qName.equals(\"Key\")) {\n         key = currentOrNull(currentText);\n      } else if (qName.equals(\"UploadId\")) {\n         uploadId = currentOrNull(currentText);\n      } else if (qName.equals(\"StorageClass\")) {\n         String currentValue = currentOrNull(currentText);\n         storageClass = currentValue != null ? ObjectMetadata.StorageClass.valueOf(currentValue) : ObjectMetadata.StorageClass.STANDARD;\n      } else if (qName.equals(\"Initiated\")) {\n         initiated = dateParser.iso8601DateOrSecondsDateParse(currentOrNull(currentText));\n      } else if (qName.equals(\"Upload\")) {\n         uploads.add(ListMultipartUploadsResponse.Upload.create(key, uploadId, initiator, owner, storageClass, initiated));\n         key = null;\n         uploadId = null;\n         id = null;\n         displayName = null;\n         initiator = null;\n         owner = null;\n         storageClass = null;\n         initiated = null;\n         inUpload = false;\n      } else if (qName.equals(\"Initiator\")) {\n         initiator = new CanonicalUser(id, displayName);\n         id = null;\n         displayName = null;\n         inInitiator = false;\n      } else if (qName.equals(\"Owner\")) {\n         owner = new CanonicalUser(id, displayName);\n         id = null;\n         displayName = null;\n         inOwner = false;\n      }\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/xml/LocationConstraintHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.xml;\n\nimport static org.jclouds.util.SaxUtils.currentOrNull;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.aws.domain.Region;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.jclouds.s3.Bucket;\n\nimport com.google.common.base.Optional;\nimport com.google.common.cache.LoadingCache;\n\n/**\n * Parses the response from Amazon S3 GET Bucket Location\n * <p/>\n * Region is the document we expect to parse.\n */\npublic class LocationConstraintHandler extends ParseSax.HandlerWithResult<String> {\n   private final LoadingCache<String, Optional<String>> bucketToRegion;\n   private StringBuilder currentText = new StringBuilder();\n   private String region;\n   private String bucket;\n\n   @Inject\n   public LocationConstraintHandler(@Bucket LoadingCache<String, Optional<String>> bucketToRegion) {\n      this.bucketToRegion = bucketToRegion;\n   }\n\n   public String getResult() {\n      return region;\n   }\n\n   public void endElement(String uri, String name, String qName) {\n      region = fromValue(currentOrNull(currentText));\n      bucketToRegion.put(bucket, Optional.fromNullable(region));\n   }\n\n   @Override\n   public LocationConstraintHandler setContext(HttpRequest request) {\n      super.setContext(request);\n      setBucket(GeneratedHttpRequest.class.cast(getRequest()).getInvocation().getArgs().get(0).toString());\n      return this;\n   }\n\n   void setBucket(String bucket) {\n      this.bucket = bucket;\n   }\n\n   /**\n    * parses the value expected in xml documents from the S3 service.=\n    * <p/>\n    * {@code US_STANDARD} is returned as \"\" xml documents.\n    */\n   public static String fromValue(String v) {\n      if (v == null || \"\".equals(v))\n         return Region.US_STANDARD;\n      if (\"EU\".equals(v))\n         return \"eu-west-1\";\n      return v;\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/xml/PartIdsFromHttpResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.xml;\n\nimport static org.jclouds.util.SaxUtils.currentOrNull;\n\nimport java.util.Date;\nimport java.util.Map;\nimport java.util.regex.Pattern;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.http.functions.ParseSax;\n\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Parses the following XML document:\n * <p/>\n * ListBucketResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01\"\n *\n * @deprecated see PartIdsFromHttpResponseFull\n */\n@Deprecated\npublic class PartIdsFromHttpResponse extends ParseSax.HandlerWithResult<Map<Integer, String>> {\n   private final StringBuilder currentText = new StringBuilder();\n\n   private final DateService dateParser;\n\n   private int partNumber;\n   private Date lastModfied;\n   private String eTag;\n   private long size;\n\n   private final ImmutableMap.Builder<Integer, String> parts = ImmutableMap.builder();\n\n   /** Some blobs have a non-hex suffix when created by multi-part uploads such Amazon S3. */\n   private static final Pattern ETAG_CONTENT_MD5_PATTERN = Pattern.compile(\"\\\"([0-9a-f]+)\\\"\");\n\n   @Inject\n   public PartIdsFromHttpResponse(DateService dateParser) {\n      this.dateParser = dateParser;\n   }\n\n   public Map<Integer, String> getResult() {\n      return parts.build();\n   }\n\n   public void endElement(String uri, String name, String qName) {\n      if (qName.equals(\"PartNumber\")) {\n         partNumber = Integer.parseInt(currentText.toString().trim());\n      } else if (qName.equals(\"LastModified\")) {\n         lastModfied = dateParser.iso8601DateOrSecondsDateParse(currentOrNull(currentText));\n      } else if (qName.equals(\"ETag\")) {\n         eTag = currentText.toString().trim();\n      } else if (qName.equals(\"Size\")) {\n         size = Long.parseLong(currentText.toString().trim());\n      } else if (qName.equals(\"Part\")) {\n         parts.put(partNumber, eTag);\n      }\n      currentText.setLength(0);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/xml/PartIdsFromHttpResponseFull.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.xml;\n\nimport static org.jclouds.util.SaxUtils.currentOrNull;\n\nimport java.util.Date;\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.s3.domain.ListMultipartUploadResponse;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Parses the following XML document:\n * <p/>\n * ListBucketResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01\"\n */\n@Beta\npublic final class PartIdsFromHttpResponseFull extends ParseSax.HandlerWithResult<Map<Integer, ListMultipartUploadResponse>> {\n   private final StringBuilder currentText = new StringBuilder();\n\n   private final DateService dateParser;\n\n   private int partNumber;\n   private Date lastModfied;\n   private String eTag;\n   private long size;\n\n   private final ImmutableMap.Builder<Integer, ListMultipartUploadResponse> parts = ImmutableMap.builder();\n\n   @Inject\n   PartIdsFromHttpResponseFull(DateService dateParser) {\n      this.dateParser = dateParser;\n   }\n\n   public Map<Integer, ListMultipartUploadResponse> getResult() {\n      return parts.build();\n   }\n\n   public void endElement(String uri, String name, String qName) {\n      if (qName.equals(\"PartNumber\")) {\n         partNumber = Integer.parseInt(currentText.toString().trim());\n      } else if (qName.equals(\"LastModified\")) {\n         lastModfied = dateParser.iso8601DateOrSecondsDateParse(currentOrNull(currentText));\n      } else if (qName.equals(\"ETag\")) {\n         eTag = currentText.toString().trim();\n      } else if (qName.equals(\"Size\")) {\n         size = Long.parseLong(currentText.toString().trim());\n      } else if (qName.equals(\"Part\")) {\n         parts.put(partNumber, ListMultipartUploadResponse.create(partNumber, lastModfied, eTag, size));\n      }\n      currentText.setLength(0);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/xml/PayerHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.xml;\n\nimport static org.jclouds.util.SaxUtils.currentOrNull;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.s3.domain.Payer;\n\n/**\n * Parses the response from Amazon S3 GET Request Payment\n  * <p/>\n * RequestPaymentConfiguration is the document we expect to parse.\n */\npublic class PayerHandler extends ParseSax.HandlerWithResult<Payer> {\n   private StringBuilder currentText = new StringBuilder();\n   private Payer constraint;\n\n   public Payer getResult() {\n      return constraint;\n   }\n\n   public void endElement(String uri, String name, String qName) {\n      constraint = Payer.fromValue(currentOrNull(currentText));\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/main/java/org/jclouds/s3/xml/package-info.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * This package contains xml logic that parses S3 responses. \n */\npackage org.jclouds.s3.xml;\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/PathBasedS3ClientExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3;\n\nimport static org.jclouds.s3.reference.S3Constants.PROPERTY_S3_VIRTUAL_HOST_BUCKETS;\n\nimport java.util.Properties;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.s3.domain.S3Object;\nimport org.jclouds.s3.internal.BaseS3ClientExpectTest;\nimport org.testng.Assert;\nimport org.testng.annotations.Test;\n\nimport com.google.common.net.HttpHeaders;\n\n@Test(groups = \"unit\", testName = \"PathBasedS3ClientExpectTest\")\npublic class PathBasedS3ClientExpectTest extends BaseS3ClientExpectTest {\n\n   @Override\n   protected Properties setupProperties() {\n      Properties overrides = super.setupProperties();\n      overrides.setProperty(PROPERTY_S3_VIRTUAL_HOST_BUCKETS, \"false\");\n      return overrides;\n   }\n\n   @Test\n   public void testBucketExistsReturnsTrueOn200AndFalseOn404() {\n      \n      HttpRequest bucketFooExists = HttpRequest.builder().method(\"HEAD\")\n                                               .endpoint(\"http://localhost/foo\")\n                                               .addHeader(\"Date\", CONSTANT_DATE)\n                                               .addHeader(\"Authorization\", \"AWS identity:lLD0mzo2bZPIWhxlFDZoT09MKUQ=\")\n                                               .build();\n                                    \n      S3Client clientWhenBucketExists = requestSendsResponse(bucketFooExists, HttpResponse.builder().statusCode(200).build());\n      assert clientWhenBucketExists.bucketExists(\"foo\");\n      \n      S3Client clientWhenBucketDoesntExist = requestSendsResponse(bucketFooExists, HttpResponse.builder().statusCode(404).build());\n      assert !clientWhenBucketDoesntExist.bucketExists(\"foo\");\n      \n   }\n\n   @Test\n   public void testPutBucketReturnsTrueOn200() {\n      \n      HttpRequest bucketFooExists = HttpRequest.builder().method(\"PUT\")\n                                               .endpoint(\"http://localhost/foo\")\n                                               .addHeader(\"Date\", CONSTANT_DATE)\n                                               .addHeader(\"Authorization\", \"AWS identity:GeP4OqEL/eM+gQt+4Vtcm02gebc=\")\n                                               .build();\n                                    \n      S3Client clientWhenBucketExists = requestSendsResponse(bucketFooExists, HttpResponse.builder().statusCode(200).build());\n      assert clientWhenBucketExists.putBucketInRegion(null, \"foo\");\n      \n   }\n   \n\n   @Test\n   public void testPutObjectReturnsETagOn200() {\n      \n      HttpRequest bucketFooExists = HttpRequest.builder().method(\"PUT\")\n                                               .endpoint(\"http://localhost/bucket/object\")\n                                               .addHeader(\"Expect\", \"100-continue\")\n                                               .addHeader(\"Date\", CONSTANT_DATE)\n                                               .addHeader(\"Authorization\", \"AWS identity:6gC0m7SYFDPwkUqY5EHV/6i9DfM=\")\n                                               .payload(\"hello world\")\n                                               .build();\n                                    \n      S3Client clientWhenBucketExists = requestSendsResponse(bucketFooExists, HttpResponse.builder().statusCode(200).addHeader(HttpHeaders.ETAG, \"etag\").build());\n      S3Object object = clientWhenBucketExists.newS3Object();\n      object.getMetadata().setKey(\"object\");\n      object.setPayload(\"hello world\");\n      Assert.assertEquals(clientWhenBucketExists.putObject(\"bucket\", object), \"etag\");\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/S3ApiMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3;\n\nimport org.jclouds.blobstore.internal.BaseBlobStoreApiMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"S3ApiMetadataTest\")\npublic class S3ApiMetadataTest extends BaseBlobStoreApiMetadataTest {\n\n   public S3ApiMetadataTest() {\n      super(new S3ApiMetadata());\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/S3ClientExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.hash.Hashing.md5;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.net.URI;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.s3.domain.DeleteResult;\nimport org.jclouds.s3.internal.BaseS3ClientExpectTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\", testName = \"S3ClientExpectTest\")\npublic class S3ClientExpectTest extends BaseS3ClientExpectTest {\n\n   @Test\n   public void testBucketExistsReturnsTrueOn200AndFalseOn404() {\n      \n      HttpRequest bucketFooExists = HttpRequest.builder().method(\"HEAD\").endpoint(\n               URI.create(\"http://localhost/foo\")).headers(\n               ImmutableMultimap.<String, String> builder()\n                  .put(\"Date\", CONSTANT_DATE)\n                  .put(\"Authorization\", \"AWS identity:lLD0mzo2bZPIWhxlFDZoT09MKUQ=\")\n                  .build()).build();\n      \n      S3Client clientWhenBucketExists = requestSendsResponse(bucketFooExists, HttpResponse.builder().statusCode(200).build());\n      assert clientWhenBucketExists.bucketExists(\"foo\");\n      \n      S3Client clientWhenBucketDoesntExist = requestSendsResponse(bucketFooExists, HttpResponse.builder().statusCode(404).build());\n      assert !clientWhenBucketDoesntExist.bucketExists(\"foo\");\n      \n   }\n\n   @Test\n   public void testDeleteMultipleObjects() {\n      final String request = \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\" +\n         \"<Delete>\" +\n         \"<Object><Key>key1</Key></Object>\" +\n         \"<Object><Key>key2</Key></Object>\" +\n         \"</Delete>\";\n\n      final Payload requestPayload = Payloads.newStringPayload(request);\n      requestPayload.getContentMetadata().setContentType(\"text/xml\");\n      requestPayload.getContentMetadata().setContentMD5(md5().hashString(request, UTF_8));\n\n      final String response = \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\" +\n         \"<DeleteResult xmlns=\\\"http://s3.amazonaws.com/doc/2006-03-01/\\\">\\n\" +\n         \"  <Deleted>\\n\" +\n         \"    <Key>key1</Key>\\n\" +\n         \"  </Deleted>\\n\" +\n         \"  <Deleted>\\n\" +\n         \"    <Key>key1.1</Key>\\n\" +\n         \"  </Deleted>\\n\" +\n         \"  <Error>\\n\" +\n         \"    <Key>key2</Key>\\n\" +\n         \"    <Code>AccessDenied</Code>\\n\" +\n         \"    <Message>Access Denied</Message>\\n\" +\n         \"  </Error>\\n\" +\n         \"</DeleteResult>\";\n\n      final Payload responsePayload = Payloads.newStringPayload(response);\n      responsePayload.getContentMetadata().setContentType(\"text/xml\");\n\n      S3Client client = requestSendsResponse(\n         HttpRequest.builder()\n                    .method(\"POST\")\n                    .endpoint(\"http://localhost/test?delete\")\n                    .addHeader(\"Date\", CONSTANT_DATE)\n                    .addHeader(\"Authorization\", \"AWS identity:XptAJrBvfz68TEfPkhXj4R58uvE=\")\n                    .payload(requestPayload)\n                    .build(),\n         HttpResponse.builder()\n                     .statusCode(200)\n                     .addHeader(\"x-amz-request-id\", \"7A84C3CD4437A4C0\")\n                     .addHeader(\"Date\", CONSTANT_DATE)\n                     .addHeader(\"ETag\", \"437b930db84b8079c2dd804a71936b5f\")\n                     .addHeader(\"Server\", \"AmazonS3\")\n                     .payload(responsePayload)\n                     .build()\n      );\n\n      DeleteResult result = client.deleteObjects(\"test\", ImmutableSet.of(\"key1\", \"key2\"));\n      assertNotNull(result, \"result is null\");\n\n      assertEquals(result.getDeleted(), ImmutableSet.of(\"key1\", \"key1.1\"));\n      assertEquals(result.getErrors().size(), 1);\n\n      assertEquals(result.getErrors().get(\"key2\"), new DeleteResult.Error(\"AccessDenied\", \"Access Denied\"));\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/S3ClientLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3;\n\nimport static com.google.common.hash.Hashing.md5;\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.jclouds.io.Payloads.newByteArrayPayload;\nimport static org.jclouds.s3.options.CopyObjectOptions.Builder.ifSourceETagDoesntMatch;\nimport static org.jclouds.s3.options.CopyObjectOptions.Builder.ifSourceETagMatches;\nimport static org.jclouds.s3.options.CopyObjectOptions.Builder.ifSourceModifiedSince;\nimport static org.jclouds.s3.options.CopyObjectOptions.Builder.ifSourceUnmodifiedSince;\nimport static org.jclouds.s3.options.CopyObjectOptions.Builder.overrideAcl;\nimport static org.jclouds.s3.options.CopyObjectOptions.Builder.overrideMetadataWith;\nimport static org.jclouds.s3.options.PutObjectOptions.Builder.withAcl;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.Assert.fail;\n\nimport java.io.IOException;\nimport java.net.URI;\nimport java.net.URL;\nimport java.util.Date;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.Set;\nimport java.util.UUID;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.TimeoutException;\nimport java.util.concurrent.TimeUnit;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.aws.domain.SessionCredentials;\nimport org.jclouds.blobstore.KeyNotFoundException;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.PageSet;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.integration.internal.BaseBlobStoreIntegrationTest;\nimport org.jclouds.blobstore.options.ListContainerOptions;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.io.ByteStreams2;\nimport org.jclouds.io.Payload;\nimport org.jclouds.s3.domain.AccessControlList;\nimport org.jclouds.s3.domain.AccessControlList.CanonicalUserGrantee;\nimport org.jclouds.s3.domain.AccessControlList.EmailAddressGrantee;\nimport org.jclouds.s3.domain.AccessControlList.GroupGranteeURI;\nimport org.jclouds.s3.domain.AccessControlList.Permission;\nimport org.jclouds.s3.domain.CannedAccessPolicy;\nimport org.jclouds.s3.domain.DeleteResult;\nimport org.jclouds.s3.domain.ListMultipartUploadResponse;\nimport org.jclouds.s3.domain.ListMultipartUploadsResponse;\nimport org.jclouds.s3.domain.ObjectMetadata;\nimport org.jclouds.s3.domain.ObjectMetadataBuilder;\nimport org.jclouds.s3.domain.S3Object;\nimport org.jclouds.s3.options.PutObjectOptions;\nimport org.jclouds.util.Strings2;\nimport org.jclouds.utils.TestUtils;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Throwables;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Maps;\nimport com.google.common.hash.HashCode;\nimport com.google.common.io.ByteSource;\n\n@Test(groups = { \"integration\", \"live\" })\npublic class S3ClientLiveTest extends BaseBlobStoreIntegrationTest {\n   public static final String TEST_ACL_ID = \"1a405254c932b52e5b5caaa88186bc431a1bacb9ece631f835daddaf0c47677c\";\n   public static final String TEST_ACL_EMAIL = \"james@misterm.org\";\n   public static final String DEFAULT_OWNER_ID = \"abc123\";\n   private static final ByteSource oneHundredOneConstitutions = TestUtils.randomByteSource().slice(0, 5 * 1024 * 1024 + 1);\n\n   protected String sessionToken;\n\n   public S3ClientLiveTest() {\n      this.provider = \"s3\";\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties overrides = super.setupProperties();\n      sessionToken = setIfTestSystemPropertyPresent(overrides, provider + \".sessionToken\");\n      return overrides;\n   }\n\n   @Override\n   protected ContextBuilder newBuilder() {\n      ContextBuilder builder = super.newBuilder();\n      if (sessionToken != null) {\n         builder.credentialsSupplier(new Supplier<Credentials>() {\n            @Override\n            public Credentials get() {\n               return SessionCredentials.builder().identity(identity).credential(credential).sessionToken(sessionToken).build();\n            }\n         });\n      }\n      return builder;\n   }\n\n   public S3Client getApi() {\n      return view.unwrapApi(S3Client.class);\n   }\n\n   /**\n    * this method overrides containerName to ensure it isn't found\n    */\n   @Test(groups = { \"integration\", \"live\" })\n   public void deleteContainerIfEmptyNotFound() throws Exception {\n      assert getApi().deleteBucketIfEmpty(\"dbienf\");\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void deleteContainerIfEmptyButHasContents() throws Exception {\n      String containerName = getContainerName();\n      try {\n         addBlobToContainer(containerName, \"test\");\n         assert !getApi().deleteBucketIfEmpty(containerName);\n      } finally {\n         returnContainer(containerName);\n      }\n   }\n\n   protected URL getObjectURL(String containerName, String key) throws Exception {\n      URL url = new URL(String.format(\"http://%s.%s/%s\", containerName, URI.create(endpoint).getHost(), key));\n      return url;\n   }\n\n   @Test(groups = {\"fails-on-s3proxy\"})\n   public void testPutCannedAccessPolicyPublic() throws Exception {\n      String containerName = getContainerName();\n      try {\n         allowPublicReadable(containerName);\n\n         String key = \"hello\";\n         S3Object object = getApi().newS3Object();\n         object.getMetadata().setKey(key);\n         object.setPayload(TEST_STRING);\n         getApi().putObject(containerName, object,\n\n         withAcl(CannedAccessPolicy.PUBLIC_READ));\n\n         URL url = this.getObjectURL(containerName, key);\n         Strings2.toStringAndClose(url.openStream());\n      } finally {\n         returnContainer(containerName);\n      }\n\n   }\n\n   protected void allowPublicReadable(String containerName) {\n   }\n\n   @Test(groups = {\"fails-on-s3proxy\"})\n   public void testCopyCannedAccessPolicyPublic() throws Exception {\n      String containerName = getContainerName();\n      String destinationContainer = getContainerName();\n      try {\n         allowPublicReadable(destinationContainer);\n\n         addBlobToContainer(containerName, sourceKey);\n         validateContent(containerName, sourceKey);\n\n         getApi().copyObject(containerName, sourceKey, destinationContainer, destinationKey,\n                  overrideAcl(CannedAccessPolicy.PUBLIC_READ));\n\n         validateContent(destinationContainer, destinationKey);\n\n         URL url = getObjectURL(destinationContainer, destinationKey);\n         Strings2.toStringAndClose(url.openStream());\n\n      } finally {\n         returnContainer(containerName);\n         returnContainer(destinationContainer);\n      }\n   }\n\n   String sourceKey = \"apples\";\n   String destinationKey = \"pears\";\n\n   @Test(groups = {\"fails-on-s3proxy\"})\n   public void testPublicWriteOnObject() throws InterruptedException, ExecutionException, TimeoutException, IOException {\n      final String publicReadWriteObjectKey = \"public-read-write-acl\";\n      final String containerName = getContainerName();\n      try {\n         allowPublicReadable(containerName);\n         S3Object object = getApi().newS3Object();\n         object.getMetadata().setKey(publicReadWriteObjectKey);\n         object.setPayload(\"\");\n         // Public Read-Write object\n         getApi()\n                  .putObject(containerName, object,\n                           new PutObjectOptions().withAcl(CannedAccessPolicy.PUBLIC_READ_WRITE));\n\n         assertConsistencyAware(new Runnable() {\n            public void run() {\n               try {\n                  AccessControlList acl = getApi().getObjectACL(containerName, publicReadWriteObjectKey);\n                  assertEquals(acl.getGrants().size(), 3);\n                  assertEquals(acl.getPermissions(GroupGranteeURI.ALL_USERS).size(), 2);\n                  assertNotNull(acl.getOwner());\n                  String ownerId = acl.getOwner().getId();\n                  assertTrue(acl.hasPermission(ownerId, Permission.FULL_CONTROL));\n                  assertTrue(acl.hasPermission(GroupGranteeURI.ALL_USERS, Permission.READ));\n                  assertTrue(acl.hasPermission(GroupGranteeURI.ALL_USERS, Permission.WRITE));\n                  assertFalse(acl.hasPermission(GroupGranteeURI.ALL_USERS, Permission.READ_ACP));\n                  assertFalse(acl.hasPermission(GroupGranteeURI.ALL_USERS, Permission.WRITE_ACP));\n                  assertFalse(acl.hasPermission(GroupGranteeURI.ALL_USERS, Permission.FULL_CONTROL));\n               } catch (Exception e) {\n                  Throwables.propagateIfPossible(e);\n               }\n            }\n         });\n      } finally {\n         returnContainer(containerName);\n      }\n\n   }\n\n   @Test(groups = {\"fails-on-s3proxy\"})\n   public void testUpdateObjectACL() throws InterruptedException, ExecutionException, TimeoutException, IOException {\n      String containerName = getContainerName();\n      try {\n         allowPublicReadable(containerName);\n\n         String objectKey = \"private-acl\";\n\n         // Private object\n         addBlobToContainer(containerName, objectKey);\n         AccessControlList acl = getApi().getObjectACL(containerName, objectKey);\n         String ownerId = acl.getOwner().getId();\n\n         assertEquals(acl.getGrants().size(), 1);\n         assertTrue(acl.hasPermission(ownerId, Permission.FULL_CONTROL));\n\n         addGrantsToACL(acl);\n         assertEquals(acl.getGrants().size(), 4);\n         assertTrue(getApi().putObjectACL(containerName, objectKey, acl));\n\n         // Confirm that the updated ACL has stuck.\n         acl = getApi().getObjectACL(containerName, objectKey);\n         checkGrants(acl);\n\n         /*\n          * Revoke all of owner's permissions!\n          */\n         acl.revokeAllPermissions(new CanonicalUserGrantee(ownerId));\n         if (!ownerId.equals(TEST_ACL_ID))\n            acl.revokeAllPermissions(new CanonicalUserGrantee(TEST_ACL_ID));\n         assertEquals(acl.getGrants().size(), 1);\n         // Only public read permission should remain...\n         assertTrue(acl.hasPermission(GroupGranteeURI.ALL_USERS, Permission.READ));\n\n         // Update the object's ACL settings\n         assertTrue(getApi().putObjectACL(containerName, objectKey, acl));\n\n         // Confirm that the updated ACL has stuck\n         acl = getApi().getObjectACL(containerName, objectKey);\n         assertEquals(acl.getGrants().size(), 1);\n         assertEquals(acl.getPermissions(ownerId).size(), 0);\n         assertTrue(acl.hasPermission(GroupGranteeURI.ALL_USERS, Permission.READ), acl.toString());\n      } finally {\n         returnContainer(containerName);\n      }\n\n   }\n\n   public void testPrivateAclIsDefaultForObject() throws InterruptedException, ExecutionException, TimeoutException,\n            IOException {\n      String privateObjectKey = \"private-acl\";\n      String containerName = getContainerName();\n      try {\n         // Private object\n         addBlobToContainer(containerName, privateObjectKey);\n         AccessControlList acl = getApi().getObjectACL(containerName, privateObjectKey);\n\n         assertEquals(acl.getGrants().size(), 1);\n         assertNotNull(acl.getOwner());\n         String ownerId = acl.getOwner().getId();\n         assertTrue(acl.hasPermission(ownerId, Permission.FULL_CONTROL));\n      } finally {\n         returnContainer(containerName);\n      }\n\n   }\n\n   public void testPublicReadOnObject() throws InterruptedException, ExecutionException, TimeoutException, IOException {\n      final String publicReadObjectKey = \"public-read-acl\";\n      final String containerName = getContainerName();\n      try {\n         allowPublicReadable(containerName);\n         S3Object object = getApi().newS3Object();\n         object.getMetadata().setKey(publicReadObjectKey);\n         object.setPayload(\"\");\n         getApi().putObject(containerName, object, new PutObjectOptions().withAcl(CannedAccessPolicy.PUBLIC_READ));\n\n         assertConsistencyAware(new Runnable() {\n            public void run() {\n               try {\n                  AccessControlList acl = getApi().getObjectACL(containerName, publicReadObjectKey);\n\n                  assertEquals(acl.getGrants().size(), 2);\n                  assertEquals(acl.getPermissions(GroupGranteeURI.ALL_USERS).size(), 1);\n                  assertNotNull(acl.getOwner());\n                  String ownerId = acl.getOwner().getId();\n                  assertTrue(acl.hasPermission(ownerId, Permission.FULL_CONTROL));\n                  assertTrue(acl.hasPermission(GroupGranteeURI.ALL_USERS, Permission.READ));\n               } catch (Exception e) {\n                  Throwables.propagateIfPossible(e);\n               }\n            }\n         });\n\n      } finally {\n         returnContainer(containerName);\n      }\n\n   }\n\n   protected String addBlobToContainer(String sourceContainer, String key) {\n      S3Object sourceObject = getApi().newS3Object();\n      sourceObject.getMetadata().setKey(key);\n      sourceObject.getMetadata().getContentMetadata().setContentType(\"text/xml\");\n      sourceObject.setPayload(TEST_STRING);\n      return getApi().putObject(sourceContainer, sourceObject);\n   }\n\n   protected S3Object validateObject(String sourceContainer, String key) throws InterruptedException,\n            ExecutionException, TimeoutException, IOException {\n      assertConsistencyAwareContainerSize(sourceContainer, 1);\n      S3Object newObject = getApi().getObject(sourceContainer, key);\n      assert newObject != null;\n      assertEquals(Strings2.toStringAndClose(newObject.getPayload().openStream()), TEST_STRING);\n      return newObject;\n   }\n\n   public void testMetadataWithCacheControlAndContentDisposition() throws Exception {\n      String key = \"hello\";\n\n      S3Object object = getApi().newS3Object();\n      object.getMetadata().setKey(key);\n      object.setPayload(TEST_STRING);\n      object.getMetadata().setCacheControl(\"no-cache\");\n      object.getMetadata().getContentMetadata().setContentDisposition(\"attachment; filename=hello.txt\");\n      String containerName = getContainerName();\n      try {\n         getApi().putObject(containerName, object);\n\n         S3Object newObject = validateObject(containerName, key);\n         assertCacheControl(newObject, \"no-cache\");\n         assertEquals(newObject.getMetadata().getContentMetadata().getContentDisposition(),\n                  \"attachment; filename=hello.txt\");\n      } finally {\n         returnContainer(containerName);\n      }\n   }\n\n   protected void assertCacheControl(S3Object newObject, String string) {\n      assert newObject.getMetadata().getCacheControl().indexOf(string) != -1 : newObject.getMetadata()\n               .getCacheControl();\n   }\n\n   protected void assertContentEncoding(S3Object newObject, String string) {\n      assert newObject.getPayload().getContentMetadata().getContentEncoding().indexOf(string) != -1 : newObject\n               .getPayload().getContentMetadata().getContentEncoding();\n      assert newObject.getMetadata().getContentMetadata().getContentEncoding().indexOf(string) != -1 : newObject\n               .getMetadata().getContentMetadata().getContentEncoding();\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testMetadataContentEncoding() throws Exception {\n      String key = \"hello\";\n\n      S3Object object = getApi().newS3Object();\n      object.getMetadata().setKey(key);\n      object.setPayload(TEST_STRING);\n      object.getMetadata().getContentMetadata().setContentEncoding(\"x-compress\");\n      String containerName = getContainerName();\n      try {\n         getApi().putObject(containerName, object);\n         S3Object newObject = validateObject(containerName, key);\n         assertContentEncoding(newObject, \"x-compress\");\n      } finally {\n         returnContainer(containerName);\n      }\n   }\n\n   public void testCopyObject() throws Exception {\n      String containerName = getContainerName();\n      String destinationContainer = getContainerName();\n\n      try {\n         addToContainerAndValidate(containerName, sourceKey);\n\n         getApi().copyObject(containerName, sourceKey, destinationContainer, destinationKey);\n\n         validateContent(destinationContainer, destinationKey);\n      } finally {\n         returnContainer(containerName);\n         returnContainer(destinationContainer);\n\n      }\n   }\n\n   public void testCopyObjectWithSourceKeyRequiringEncoding() throws Exception {\n      String containerName = getContainerName();\n      String sourceKeyRequiringEncoding = \"apples#?:$&'\\\"<>čॐ\";\n      String destinationContainer = getContainerName();\n      try {\n         addToContainerAndValidate(containerName, sourceKeyRequiringEncoding);\n         getApi().copyObject(containerName, sourceKeyRequiringEncoding, destinationContainer, destinationKey);\n         validateContent(destinationContainer, destinationKey);\n      } finally {\n         returnContainer(containerName);\n         returnContainer(destinationContainer);\n      }\n   }\n\n   protected String addToContainerAndValidate(String containerName, String sourceKey) throws InterruptedException,\n            ExecutionException, TimeoutException, IOException {\n      String etag = addBlobToContainer(containerName, sourceKey);\n      validateContent(containerName, sourceKey);\n      return etag;\n   }\n\n   public void testCopyIfModifiedSince() throws InterruptedException, ExecutionException, TimeoutException, IOException {\n      String containerName = getContainerName();\n      String destinationContainer = getContainerName();\n      try {\n         Date before = new Date(System.currentTimeMillis() - 10 * 1000);\n         addToContainerAndValidate(containerName, sourceKey + \"mod\");\n         Date after = new Date(System.currentTimeMillis() + 10 * 1000);\n\n         getApi().copyObject(containerName, sourceKey + \"mod\", destinationContainer, destinationKey,\n                  ifSourceModifiedSince(before));\n         validateContent(destinationContainer, destinationKey);\n\n         // Sleep since Amazon returns 200 if the date is in the future:\n         // https://forums.aws.amazon.com/message.jspa?messageID=325930\n         TimeUnit.SECONDS.sleep(20);\n         try {\n            getApi().copyObject(containerName, sourceKey + \"mod\", destinationContainer, destinationKey,\n                     ifSourceModifiedSince(after));\n            fail(\"should have thrown HttpResponseException\");\n         } catch (HttpResponseException ex) {\n            assertEquals(ex.getResponse().getStatusCode(), 412);\n         }\n      } finally {\n         returnContainer(containerName);\n         returnContainer(destinationContainer);\n\n      }\n   }\n\n   public void testCopyIfUnmodifiedSince() throws InterruptedException, ExecutionException, TimeoutException,\n            IOException {\n      String containerName = getContainerName();\n      String destinationContainer = getContainerName();\n      try {\n         Date before = new Date(System.currentTimeMillis() - 10 * 1000);\n         addToContainerAndValidate(containerName, sourceKey + \"un\");\n         Date after = new Date(System.currentTimeMillis() + 10 * 1000);\n\n         getApi().copyObject(containerName, sourceKey + \"un\", destinationContainer, destinationKey,\n                  ifSourceUnmodifiedSince(after));\n         validateContent(destinationContainer, destinationKey);\n\n         try {\n            getApi().copyObject(containerName, sourceKey + \"un\", destinationContainer, destinationKey,\n                     ifSourceUnmodifiedSince(before));\n            fail(\"should have thrown HttpResponseException\");\n         } catch (HttpResponseException ex) {\n            assertEquals(ex.getResponse().getStatusCode(), 412);\n         }\n      } finally {\n         returnContainer(containerName);\n         returnContainer(destinationContainer);\n      }\n   }\n\n   public void testCopyIfMatch() throws InterruptedException, ExecutionException, TimeoutException, IOException {\n      String containerName = getContainerName();\n      String destinationContainer = getContainerName();\n      try {\n         String goodETag = addToContainerAndValidate(containerName, sourceKey);\n\n         getApi().copyObject(containerName, sourceKey, destinationContainer, destinationKey,\n                  ifSourceETagMatches(goodETag));\n         validateContent(destinationContainer, destinationKey);\n\n         try {\n            getApi().copyObject(containerName, sourceKey, destinationContainer, destinationKey,\n                     ifSourceETagMatches(\"setsds\"));\n         } catch (HttpResponseException ex) {\n            assertEquals(ex.getResponse().getStatusCode(), 412);\n         }\n      } finally {\n         returnContainer(containerName);\n         returnContainer(destinationContainer);\n      }\n   }\n\n   public void testCopyIfNoneMatch() throws IOException, InterruptedException, ExecutionException, TimeoutException {\n      String containerName = getContainerName();\n      String destinationContainer = getContainerName();\n      try {\n         String goodETag = addToContainerAndValidate(containerName, sourceKey);\n\n         getApi().copyObject(containerName, sourceKey, destinationContainer, destinationKey,\n                  ifSourceETagDoesntMatch(\"asfasdf\"));\n         validateContent(destinationContainer, destinationKey);\n\n         try {\n            getApi().copyObject(containerName, sourceKey, destinationContainer, destinationKey,\n                     ifSourceETagDoesntMatch(goodETag));\n         } catch (HttpResponseException ex) {\n            assertEquals(ex.getResponse().getStatusCode(), 412);\n         }\n      } finally {\n         returnContainer(containerName);\n         returnContainer(destinationContainer);\n      }\n   }\n\n   public void testCopyWithMetadata() throws InterruptedException, ExecutionException, TimeoutException, IOException {\n      String containerName = getContainerName();\n      String destinationContainer = getContainerName();\n      try {\n         addToContainerAndValidate(containerName, sourceKey);\n\n         Map<String, String> metadata = Maps.newHashMap();\n         metadata.put(\"adrian\", \"cole\");\n\n         getApi().copyObject(containerName, sourceKey, destinationContainer, destinationKey,\n                  overrideMetadataWith(metadata));\n\n         validateContent(destinationContainer, destinationKey);\n\n         ObjectMetadata objectMeta = getApi().headObject(destinationContainer, destinationKey);\n\n         assertEquals(objectMeta.getUserMetadata(), metadata);\n      } finally {\n         returnContainer(containerName);\n         returnContainer(destinationContainer);\n\n      }\n   }\n\n   // JCLOUDS-1401\n   public void testUnusualKeyCharacters() throws InterruptedException, ExecutionException, TimeoutException, IOException {\n      String containerName = getContainerName();\n      try {\n         String dirName = \"a%2Fb&xxx#?:$'\\\\\\\"<>čॐ\";\n         String fileName = \"foo%3Abar.xml\";\n         addToContainerAndValidate(containerName, dirName + '/' + fileName);\n         PageSet<? extends StorageMetadata> list = view.getBlobStore().list(containerName,\n                  ListContainerOptions.Builder.prefix(dirName + \"/\"));\n         assertEquals(list.size(), 1);\n         StorageMetadata md = list.iterator().next();\n         assertEquals(md.getName(), dirName + '/' + fileName);\n      } finally {\n         returnContainer(containerName);\n      }\n   }\n\n   public void testMultipartSynchronously() throws InterruptedException, IOException {\n      HashCode oneHundredOneConstitutionsMD5 = oneHundredOneConstitutions.hash(md5());\n      String containerName = getContainerName();\n      S3Object object = null;\n      try {\n         String key = \"constitution.txt\";\n         String uploadId = getApi().initiateMultipartUpload(containerName,\n                  ObjectMetadataBuilder.create().key(key).contentMD5(oneHundredOneConstitutionsMD5.asBytes()).build());\n         assertThat(getApi().listMultipartPartsFull(containerName, key, uploadId)).isEmpty();\n\n         byte[] buffer = oneHundredOneConstitutions.read();\n         assertEquals(oneHundredOneConstitutions.size(), (long) buffer.length);\n\n         Payload part1 = newByteArrayPayload(buffer);\n         part1.getContentMetadata().setContentLength((long) buffer.length);\n         part1.getContentMetadata().setContentMD5(oneHundredOneConstitutionsMD5);\n\n         String eTagOf1 = null;\n         try {\n            eTagOf1 = getApi().uploadPart(containerName, key, 1, uploadId, part1);\n         } catch (KeyNotFoundException e) {\n            // note that because of eventual consistency, the upload id may not be present yet\n            // we may wish to add this condition to the retry handler\n\n            // we may also choose to implement ListParts and wait for the uploadId to become\n            // available there.\n            eTagOf1 = getApi().uploadPart(containerName, key, 1, uploadId, part1);\n         }\n         Map<Integer, ListMultipartUploadResponse> map = getApi().listMultipartPartsFull(containerName, key, uploadId);\n         assertThat(map).containsOnlyKeys(1);\n         assertThat(map.get(1).eTag()).isEqualTo(eTagOf1);\n\n         getApi().completeMultipartUpload(containerName, key, uploadId, ImmutableMap.of(1, eTagOf1));\n\n         object = getApi().getObject(containerName, key);\n         assertEquals(ByteStreams2.toByteArrayAndClose(object.getPayload().openStream()), buffer);\n      } finally {\n         if (object != null)\n            object.getPayload().close();\n         returnContainer(containerName);\n      }\n   }\n\n   public void testMultipartCopy() throws Exception {\n      String containerName = getContainerName();\n      try {\n         String fromObject = \"fromObject\";\n         S3Object object = getApi().newS3Object();\n         object.getMetadata().setKey(fromObject);\n         object.setPayload(oneHundredOneConstitutions);\n         object.getMetadata().getContentMetadata().setContentLength(oneHundredOneConstitutions.size());\n         getApi().putObject(containerName, object);\n\n         String toObject = \"toObject\";\n         String uploadId = getApi().initiateMultipartUpload(containerName, ObjectMetadataBuilder.create().key(toObject).build());\n\n         String eTagOf1 = getApi().uploadPartCopy(containerName, toObject, 1, uploadId, containerName, fromObject, 1, oneHundredOneConstitutions.size() - 1);\n\n         getApi().completeMultipartUpload(containerName, toObject, uploadId, ImmutableMap.of(1, eTagOf1));\n\n         object = getApi().getObject(containerName, toObject);\n         assertEquals(ByteStreams2.toByteArrayAndClose(object.getPayload().openStream()), oneHundredOneConstitutions.slice(1, oneHundredOneConstitutions.size() - 1).read());\n      } finally {\n         returnContainer(containerName);\n      }\n   }\n\n   public void testListMultipartUploads() throws Exception {\n      String containerName = getContainerName();\n      String key = \"testListMultipartUploads\";\n      String uploadId = null;\n      try {\n         ListMultipartUploadsResponse response = getApi().listMultipartUploads(containerName, null, null, null, null, null);\n         assertThat(response.bucket()).isEqualTo(containerName);\n         assertThat(response.isTruncated()).isFalse();\n         assertThat(response.uploads()).isEmpty();\n\n         uploadId = getApi().initiateMultipartUpload(containerName, ObjectMetadataBuilder.create().key(key).build());\n\n         response = getApi().listMultipartUploads(containerName, null, null, null, null, null);\n         assertThat(response.bucket()).isEqualTo(containerName);\n         assertThat(response.isTruncated()).isFalse();\n         assertThat(response.uploads()).hasSize(1);\n\n         ListMultipartUploadsResponse.Upload upload = response.uploads().get(0);\n         assertThat(upload.key()).isEqualTo(key);\n         assertThat(upload.uploadId()).isEqualTo(uploadId);\n         assertThat(upload.storageClass()).isEqualTo(ObjectMetadata.StorageClass.STANDARD);\n      } finally {\n         if (uploadId != null) {\n            getApi().abortMultipartUpload(containerName, key, uploadId);\n         }\n         returnContainer(containerName);\n      }\n   }\n\n   public void testDeleteMultipleObjects() throws InterruptedException {\n      String container = getContainerName();\n      try {\n         ImmutableSet.Builder<String> builder = ImmutableSet.builder();\n         for (int i = 0; i < 5; i++) {\n            String key = UUID.randomUUID().toString();\n\n            Blob blob = view.getBlobStore().blobBuilder(key).payload(\"\").build();\n            view.getBlobStore().putBlob(container, blob);\n\n            builder.add(key);\n         }\n\n         Set<String> keys = builder.build();\n         DeleteResult result = getApi().deleteObjects(container, keys);\n\n         assertTrue(result.getDeleted().containsAll(keys));\n         assertEquals(result.getErrors().size(), 0);\n\n         for (String key : keys) {\n            assertConsistencyAwareBlobDoesntExist(container, key);\n         }\n\n      } finally {\n         returnContainer(container);\n      }\n   }\n\n   private void checkGrants(AccessControlList acl) {\n      String ownerId = acl.getOwner().getId();\n\n      assertEquals(acl.getGrants().size(), 4, acl.toString());\n\n      assertTrue(acl.hasPermission(ownerId, Permission.FULL_CONTROL), acl.toString());\n      assertTrue(acl.hasPermission(GroupGranteeURI.ALL_USERS, Permission.READ), acl.toString());\n      assertTrue(acl.hasPermission(ownerId, Permission.WRITE_ACP), acl.toString());\n      // EmailAddressGrantee is replaced by a CanonicalUserGrantee, so we cannot test by email addr\n      assertTrue(acl.hasPermission(TEST_ACL_ID, Permission.READ_ACP), acl.toString());\n   }\n\n   private void addGrantsToACL(AccessControlList acl) {\n      String ownerId = acl.getOwner().getId();\n      acl.addPermission(GroupGranteeURI.ALL_USERS, Permission.READ);\n      acl.addPermission(new EmailAddressGrantee(TEST_ACL_EMAIL), Permission.READ_ACP);\n      acl.addPermission(new CanonicalUserGrantee(ownerId), Permission.WRITE_ACP);\n   }\n\n   public void testUpdateBucketCannedACL() throws Exception {\n      String containerName = getContainerName();\n      try {\n         allowPublicReadable(containerName);\n         getApi().updateBucketCannedACL(containerName, CannedAccessPolicy.PUBLIC_READ);\n         AccessControlList acl = getApi().getBucketACL(containerName);\n         assertThat(acl.hasPermission(GroupGranteeURI.ALL_USERS, Permission.READ)).isTrue();\n\n         getApi().updateBucketCannedACL(containerName, CannedAccessPolicy.PRIVATE);\n         acl = getApi().getBucketACL(containerName);\n         assertThat(acl.hasPermission(GroupGranteeURI.ALL_USERS, Permission.READ)).isFalse();\n      } finally {\n         recycleContainerAndAddToPool(containerName);\n      }\n   }\n\n   public void testUpdateObjectCannedACL() throws Exception {\n      String containerName = getContainerName();\n      try {\n         allowPublicReadable(containerName);\n         String key = \"testUpdateObjectCannedACL\";\n         S3Object object = getApi().newS3Object();\n         object.getMetadata().setKey(key);\n         object.setPayload(TEST_STRING);\n         getApi().putObject(containerName, object);\n\n         getApi().updateObjectCannedACL(containerName, key, CannedAccessPolicy.PUBLIC_READ);\n         AccessControlList acl = getApi().getObjectACL(containerName, key);\n         assertThat(acl.hasPermission(GroupGranteeURI.ALL_USERS, Permission.READ)).isTrue();\n\n         getApi().updateObjectCannedACL(containerName, key, CannedAccessPolicy.PRIVATE);\n         acl = getApi().getObjectACL(containerName, key);\n         assertThat(acl.hasPermission(GroupGranteeURI.ALL_USERS, Permission.READ)).isFalse();\n\n         object = getApi().getObject(containerName, key);\n         assertThat(Strings2.toStringAndClose(object.getPayload().openStream())).isEqualTo(TEST_STRING);\n      } finally {\n         returnContainer(containerName);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/S3ClientMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3;\n\nimport static com.google.common.net.HttpHeaders.CONTENT_LENGTH;\nimport static com.google.common.net.HttpHeaders.ETAG;\nimport static com.google.common.net.HttpHeaders.EXPECT;\nimport static com.google.common.util.concurrent.MoreExecutors.newDirectExecutorService;\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.jclouds.Constants.PROPERTY_MAX_RETRIES;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.net.URL;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\nimport okhttp3.mockwebserver.RecordedRequest;\nimport okhttp3.mockwebserver.SocketPolicy;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.concurrent.config.ExecutorServiceModule;\nimport org.jclouds.http.okhttp.config.OkHttpCommandExecutorServiceModule;\nimport org.jclouds.s3.domain.S3Object;\nimport org.jclouds.s3.options.CopyObjectOptions;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n\n@Test(singleThreaded = true)\npublic class S3ClientMockTest {\n\n   private static final Set<Module> modules = ImmutableSet.<Module> of(new OkHttpCommandExecutorServiceModule(),\n         new ExecutorServiceModule(newDirectExecutorService()));\n\n   static S3Client getS3Client(URL server) {\n      Properties overrides = new Properties();\n      overrides.setProperty(PROPERTY_MAX_RETRIES, \"1\");\n      return ContextBuilder.newBuilder(\"s3\")\n                           .credentials(\"accessKey\", \"secretKey\")\n                           .endpoint(server.toString())\n                           .modules(modules)\n                           .overrides(overrides)\n                           .buildApi(S3Client.class);\n   }\n\n   public void testZeroLengthPutHasContentLengthHeader() throws IOException, InterruptedException {\n      MockWebServer server = new MockWebServer();\n      server.enqueue(new MockResponse().addHeader(ETAG, \"ABCDEF\"));\n      server.start();\n\n      S3Client client = getS3Client(server.url(\"/\").url());\n      S3Object nada = client.newS3Object();\n      nada.getMetadata().setKey(\"object\");\n      nada.setPayload(new byte[] {});\n\n      assertEquals(client.putObject(\"bucket\", nada), \"ABCDEF\");\n\n      RecordedRequest request = server.takeRequest();\n      assertEquals(request.getRequestLine(), \"PUT /bucket/object HTTP/1.1\");\n      assertEquals(request.getHeaders().values(CONTENT_LENGTH), ImmutableList.of(\"0\"));\n      assertThat(request.getHeader(EXPECT)).isNull();\n      server.shutdown();\n   }\n\n   public void testDirectorySeparator() throws IOException, InterruptedException {\n      MockWebServer server = new MockWebServer();\n      server.enqueue(new MockResponse().setBody(\"\").addHeader(ETAG, \"ABCDEF\").setSocketPolicy(SocketPolicy.EXPECT_CONTINUE));\n      server.start();\n\n      S3Client client = getS3Client(server.url(\"/\").url());\n      S3Object fileInDir = client.newS3Object();\n      fileInDir.getMetadata().setKey(\"someDir/fileName\");\n      fileInDir.setPayload(new byte[] { 1, 2, 3, 4 });\n\n      assertEquals(client.putObject(\"bucket\", fileInDir), \"ABCDEF\");\n\n      RecordedRequest request = server.takeRequest();\n      assertEquals(request.getRequestLine(), \"PUT /bucket/someDir/fileName HTTP/1.1\");\n      assertEquals(request.getHeaders().values(EXPECT), ImmutableList.of(\"100-continue\"));\n\n      server.shutdown();\n   }\n\n   public void testSourceEncodedOnCopy() throws IOException, InterruptedException {\n      MockWebServer server = new MockWebServer();\n      server.enqueue(new MockResponse().setBody(\"<CopyObjectResult>\\n\" +\n              \"   <LastModified>2009-10-28T22:32:00</LastModified>\\n\" +\n              \"   <ETag>\\\"9b2cf535f27731c974343645a3985328\\\"</ETag>\\n\" +\n              \" </CopyObjectResult>\"));\n      server.start();\n      S3Client client = getS3Client(server.url(\"/\").url());\n      client.copyObject(\"sourceBucket\", \"apples#?:$&'\\\"<>čॐ\", \"destinationBucket\", \"destinationObject\", CopyObjectOptions.NONE);\n      RecordedRequest request = server.takeRequest();\n      assertEquals(request.getHeaders().values(\"x-amz-copy-source\"), ImmutableList.of(\"/sourceBucket/apples%23%3F%3A%24%26%27%22%3C%3E%C4%8D%E0%A5%90\"));\n      server.shutdown();\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/S3ClientTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3;\n\nimport static org.jclouds.reflect.Reflection2.method;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.util.Arrays;\nimport java.util.Map;\n\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.aws.domain.Region;\nimport org.jclouds.blobstore.BlobStoreFallbacks.FalseOnContainerNotFound;\nimport org.jclouds.blobstore.BlobStoreFallbacks.FalseOnKeyNotFound;\nimport org.jclouds.blobstore.BlobStoreFallbacks.NullOnKeyNotFound;\nimport org.jclouds.blobstore.BlobStoreFallbacks.ThrowContainerNotFoundOn404;\nimport org.jclouds.blobstore.BlobStoreFallbacks.ThrowKeyNotFoundOn404;\nimport org.jclouds.blobstore.binders.BindBlobToMultipartFormTest;\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.fallbacks.MapHttp4xxCodesToExceptions;\nimport org.jclouds.http.functions.ParseETagHeader;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.http.functions.ReleasePayloadAndReturn;\nimport org.jclouds.http.functions.ReturnTrueIf2xx;\nimport org.jclouds.http.options.GetOptions;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.jclouds.s3.S3Fallbacks.TrueOn404OrNotFoundFalseOnIllegalState;\nimport org.jclouds.s3.config.S3HttpApiModule;\nimport org.jclouds.s3.domain.AccessControlList;\nimport org.jclouds.s3.domain.AccessControlList.EmailAddressGrantee;\nimport org.jclouds.s3.domain.AccessControlList.Grant;\nimport org.jclouds.s3.domain.AccessControlList.Permission;\nimport org.jclouds.s3.domain.BucketLogging;\nimport org.jclouds.s3.domain.CannedAccessPolicy;\nimport org.jclouds.s3.domain.ObjectMetadata;\nimport org.jclouds.s3.domain.ObjectMetadataBuilder;\nimport org.jclouds.s3.domain.Payer;\nimport org.jclouds.s3.domain.S3Object;\nimport org.jclouds.s3.fallbacks.FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists;\nimport org.jclouds.s3.functions.ETagFromHttpResponseViaRegex;\nimport org.jclouds.s3.functions.ParseObjectFromHeadersAndHttpContent;\nimport org.jclouds.s3.functions.ParseObjectMetadataFromHeaders;\nimport org.jclouds.s3.functions.UploadIdFromHttpResponseViaRegex;\nimport org.jclouds.s3.internal.BaseS3ClientTest;\nimport org.jclouds.s3.options.CopyObjectOptions;\nimport org.jclouds.s3.options.ListBucketOptions;\nimport org.jclouds.s3.options.PutBucketOptions;\nimport org.jclouds.s3.options.PutObjectOptions;\nimport org.jclouds.s3.xml.AccessControlListHandler;\nimport org.jclouds.s3.xml.BucketLoggingHandler;\nimport org.jclouds.s3.xml.CopyObjectHandler;\nimport org.jclouds.s3.xml.ListAllMyBucketsHandler;\nimport org.jclouds.s3.xml.ListBucketHandler;\nimport org.jclouds.s3.xml.ListMultipartUploadsHandler;\nimport org.jclouds.s3.xml.LocationConstraintHandler;\nimport org.jclouds.s3.xml.PayerHandler;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Lists;\nimport com.google.common.reflect.Invokable;\nimport com.google.inject.Module;\n/**\n * Tests behavior of {@code S3Client}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"S3ClientTest\")\npublic abstract class S3ClientTest<T extends S3Client> extends BaseS3ClientTest<T> {\n\n   protected String url = \"s3.amazonaws.com\";\n\n   public void testAllRegions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(S3Client.class, \"putBucketInRegion\", String.class, String.class,\n               PutBucketOptions[].class);\n      for (String region : Region.DEFAULT_S3) {\n         processor.createRequest(method, ImmutableList.<Object> of(region, \"bucket-\" + region));\n      }\n   }\n\n   public void testGetBucketLocation() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(S3Client.class, \"getBucketLocation\", String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"bucket\"));\n\n      assertRequestLineEquals(request, \"GET https://bucket.\" + url + \"/?location HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: bucket.\" + url + \"\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      request = (GeneratedHttpRequest) filter.filter(request);\n\n      assertRequestLineEquals(request, \"GET https://bucket.\" + url + \"/?location HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request,\n               \"Authorization: AWS identity:2fFTeYJTDwiJmaAkKj732RjNbOg=\\nDate: 2009-11-08T15:54:08.897Z\\nHost: bucket.\"\n                        + url + \"\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, LocationConstraintHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testGetBucketPayer() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(S3Client.class, \"getBucketPayer\", String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"bucket\"));\n\n      assertRequestLineEquals(request, \"GET https://bucket.\" + url + \"/?requestPayment HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: bucket.\" + url + \"\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, PayerHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testSetBucketPayerOwner() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(S3Client.class, \"setBucketPayer\", String.class, Payer.class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"bucket\", Payer.BUCKET_OWNER));\n\n      assertRequestLineEquals(request, \"PUT https://bucket.\" + url + \"/?requestPayment HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: bucket.\" + url + \"\\n\");\n      assertPayloadEquals(request, \"<RequestPaymentConfiguration xmlns=\\\"http://\" + url\n               + \"/doc/2006-03-01/\\\"><Payer>BucketOwner</Payer></RequestPaymentConfiguration>\", \"text/xml\", false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testSetBucketPayerRequester() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(S3Client.class, \"setBucketPayer\", String.class, Payer.class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"bucket\", Payer.REQUESTER));\n\n      assertRequestLineEquals(request, \"PUT https://bucket.\" + url + \"/?requestPayment HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: bucket.\" + url + \"\\n\");\n      assertPayloadEquals(request, \"<RequestPaymentConfiguration xmlns=\\\"http://\" + url\n               + \"/doc/2006-03-01/\\\"><Payer>Requester</Payer></RequestPaymentConfiguration>\", \"text/xml\", false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testListBucket() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(S3Client.class, \"listBucket\", String.class,\n               ListBucketOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"bucket\"));\n\n      assertRequestLineEquals(request, \"GET https://bucket.\" + url + \"/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: bucket.\" + url + \"\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, ListBucketHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testBucketExists() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(S3Client.class, \"bucketExists\", String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"bucket\"));\n\n      assertRequestLineEquals(request, \"HEAD https://bucket.\" + url + \"/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: bucket.\" + url + \"\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ReturnTrueIf2xx.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, FalseOnContainerNotFound.class);\n\n      checkFilters(request);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testCopyObjectInvalidName() throws ArrayIndexOutOfBoundsException, SecurityException,\n            IllegalArgumentException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(S3Client.class, \"copyObject\", String.class, String.class, String.class,\n               String.class, CopyObjectOptions[].class);\n      processor.createRequest(method, ImmutableList.<Object> of(\"sourceBucket\", \"sourceObject\", \"destinationBucket\", \"destinationObject\"));\n\n   }\n\n   public void testCopyObject() throws ArrayIndexOutOfBoundsException, SecurityException, IllegalArgumentException,\n            NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(S3Client.class, \"copyObject\", String.class, String.class, String.class,\n               String.class, CopyObjectOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"sourceBucket\", \"sourceObject\", \"destinationbucket\",\n               \"destinationObject\"));\n\n      assertRequestLineEquals(request, \"PUT https://destinationbucket.\" + url + \"/destinationObject HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: destinationbucket.\" + url\n               + \"\\nx-amz-copy-source: /sourceBucket/sourceObject\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, CopyObjectHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testDeleteBucketIfEmpty() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(S3Client.class, \"deleteBucketIfEmpty\", String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"bucket\"));\n\n      assertRequestLineEquals(request, \"DELETE https://bucket.\" + url + \"/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: bucket.\" + url + \"\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ReturnTrueIf2xx.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, TrueOn404OrNotFoundFalseOnIllegalState.class);\n\n      checkFilters(request);\n   }\n\n   public void testDeleteObject() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(S3Client.class, \"deleteObject\", String.class, String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"bucket\", \"object\"));\n\n      assertRequestLineEquals(request, \"DELETE https://bucket.\" + url + \"/object HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: bucket.\" + url + \"\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, VoidOnNotFoundOr404.class);\n\n      checkFilters(request);\n   }\n\n   public void testGetBucketACL() throws SecurityException, NoSuchMethodException, IOException {\n\n      Invokable<?, ?> method = method(S3Client.class, \"getBucketACL\", String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"bucket\"));\n\n      assertRequestLineEquals(request, \"GET https://bucket.\" + url + \"/?acl HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: bucket.\" + url + \"\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, AccessControlListHandler.class);\n      assertFallbackClassEquals(method, ThrowContainerNotFoundOn404.class);\n\n      checkFilters(request);\n   }\n\n   public void testGetObject() throws ArrayIndexOutOfBoundsException, SecurityException, IllegalArgumentException,\n            NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(S3Client.class, \"getObject\", String.class, String.class, GetOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"bucket\", \"object\"));\n\n      assertRequestLineEquals(request, \"GET https://bucket.\" + url + \"/object HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: bucket.\" + url + \"\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ParseObjectFromHeadersAndHttpContent.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnKeyNotFound.class);\n\n      checkFilters(request);\n   }\n\n   public void testGetObjectACL() throws SecurityException, NoSuchMethodException, IOException {\n\n      Invokable<?, ?> method = method(S3Client.class, \"getObjectACL\", String.class, String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"bucket\", \"object\"));\n\n      assertRequestLineEquals(request, \"GET https://bucket.\" + url + \"/object?acl HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: bucket.\" + url + \"\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, AccessControlListHandler.class);\n      assertFallbackClassEquals(method, ThrowKeyNotFoundOn404.class);\n\n      checkFilters(request);\n   }\n\n   public void testObjectExists() throws SecurityException, NoSuchMethodException, IOException {\n\n      Invokable<?, ?> method = method(S3Client.class, \"objectExists\", String.class, String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"bucket\", \"object\"));\n\n      assertRequestLineEquals(request, \"HEAD https://bucket.\" + url + \"/object HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: bucket.\" + url + \"\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ReturnTrueIf2xx.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, FalseOnKeyNotFound.class);\n\n      checkFilters(request);\n   }\n\n   public void testHeadObject() throws SecurityException, NoSuchMethodException, IOException {\n\n      Invokable<?, ?> method = method(S3Client.class, \"headObject\", String.class, String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"bucket\", \"object\"));\n\n      assertRequestLineEquals(request, \"HEAD https://bucket.\" + url + \"/object HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: bucket.\" + url + \"\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ParseObjectMetadataFromHeaders.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnKeyNotFound.class);\n\n      checkFilters(request);\n   }\n\n   public void testListOwnedBuckets() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(S3Client.class, \"listOwnedBuckets\");\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(request, \"GET https://\" + url + \"/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: \" + url + \"\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, ListAllMyBucketsHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testNewS3Object() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(S3Client.class, \"newS3Object\");\n      assertEquals(method.getReturnType().getRawType(), S3Object.class);\n   }\n\n   public void testPutBucketACL() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(S3Client.class, \"putBucketACL\", String.class, AccessControlList.class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"bucket\", AccessControlList.fromCannedAccessPolicy(\n               CannedAccessPolicy.PRIVATE, \"1234\")));\n\n      assertRequestLineEquals(request, \"PUT https://bucket.\" + url + \"/?acl HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: bucket.\" + url + \"\\n\");\n      assertPayloadEquals(\n               request,\n               \"<AccessControlPolicy xmlns=\\\"http://\"\n                        + url\n                        + \"/doc/2006-03-01/\\\"><Owner><ID>1234</ID></Owner><AccessControlList><Grant><Grantee xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xsi:type=\\\"CanonicalUser\\\"><ID>1234</ID></Grantee><Permission>FULL_CONTROL</Permission></Grant></AccessControlList></AccessControlPolicy>\",\n               \"text/xml\", false);\n\n      assertResponseParserClassEquals(method, request, ReturnTrueIf2xx.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testUpdateBucketCannedACL() throws Exception {\n      Invokable<?, ?> method = method(S3Client.class, \"updateBucketCannedACL\", String.class, CannedAccessPolicy.class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"bucket\", CannedAccessPolicy.PUBLIC_READ));\n\n      assertRequestLineEquals(request, \"PUT https://bucket.\" + url + \"/?acl HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request,\n            \"Host: bucket.\" + url + \"\\n\" +\n            \"x-amz-acl: public-read\\n\");\n      assertPayloadEquals(request, null, \"text/xml\", false);\n\n      assertResponseParserClassEquals(method, request, ReturnTrueIf2xx.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testPutBucketDefault() throws ArrayIndexOutOfBoundsException, SecurityException,\n            IllegalArgumentException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(S3Client.class, \"putBucketInRegion\", String.class, String.class,\n               PutBucketOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList((String) null, \"bucket\"));\n\n      assertRequestLineEquals(request, \"PUT https://bucket.\" + url + \"/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: bucket.\" + url + \"\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ReturnTrueIf2xx.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists.class);\n\n      checkFilters(request);\n   }\n\n   public void testPutObject() throws ArrayIndexOutOfBoundsException, SecurityException, IllegalArgumentException,\n            NoSuchMethodException, IOException {\n\n      Invokable<?, ?> method = method(S3Client.class, \"putObject\", String.class, S3Object.class, PutObjectOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"bucket\", blobToS3Object\n               .apply(BindBlobToMultipartFormTest.TEST_BLOB)));\n\n      assertRequestLineEquals(request, \"PUT https://bucket.\" + url + \"/hello HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: bucket.\" + url + \"\\n\");\n      assertPayloadEquals(request, \"hello\", \"text/plain\", false);\n\n      assertResponseParserClassEquals(method, request, ParseETagHeader.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testPutObjectACL() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(S3Client.class, \"putObjectACL\", String.class, String.class, AccessControlList.class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"bucket\", \"key\", AccessControlList.fromCannedAccessPolicy(\n               CannedAccessPolicy.PRIVATE, \"1234\")));\n\n      assertRequestLineEquals(request, \"PUT https://bucket.\" + url + \"/key?acl HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: bucket.\" + url + \"\\n\");\n      assertPayloadEquals(\n               request,\n               \"<AccessControlPolicy xmlns=\\\"http://\"\n                        + url\n                        + \"/doc/2006-03-01/\\\"><Owner><ID>1234</ID></Owner><AccessControlList><Grant><Grantee xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xsi:type=\\\"CanonicalUser\\\"><ID>1234</ID></Grantee><Permission>FULL_CONTROL</Permission></Grant></AccessControlList></AccessControlPolicy>\",\n               \"text/xml\", false);\n\n      assertResponseParserClassEquals(method, request, ReturnTrueIf2xx.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testUpdateObjectCannedACL() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(S3Client.class, \"updateObjectCannedACL\", String.class, String.class, CannedAccessPolicy.class);\n      GeneratedHttpRequest request = processor.createRequest(\n              method, ImmutableList.<Object> of(\"bucket\", \"key\", CannedAccessPolicy.PUBLIC_READ));\n\n      assertRequestLineEquals(request, \"PUT https://bucket.\" + url + \"/key?acl HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request,\n            \"Host: bucket.\" + url + \"\\n\" +\n            \"x-amz-acl: public-read\\n\");\n      assertPayloadEquals(request, null, \"text/xml\", false);\n\n      assertResponseParserClassEquals(method, request, ReturnTrueIf2xx.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testGetBucketLogging() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(S3Client.class, \"getBucketLogging\", String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"bucket\"));\n\n      assertRequestLineEquals(request, \"GET https://bucket.\" + url + \"/?logging HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: bucket.\" + url + \"\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, BucketLoggingHandler.class);\n      assertFallbackClassEquals(method, ThrowContainerNotFoundOn404.class);\n\n      checkFilters(request);\n   }\n\n   public void testDisableBucketLogging() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(S3Client.class, \"disableBucketLogging\", String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"bucket\"));\n\n      assertRequestLineEquals(request, \"PUT https://bucket.\" + url + \"/?logging HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: bucket.\" + url + \"\\n\");\n      assertPayloadEquals(request, \"<BucketLoggingStatus xmlns=\\\"http://\" + url + \"/doc/2006-03-01/\\\"/>\", \"text/xml\",\n               false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testEnableBucketLoggingOwner() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(S3Client.class, \"enableBucketLogging\", String.class, BucketLogging.class);\n      GeneratedHttpRequest request = processor\n               .createRequest(method, ImmutableList.<Object> of(\"bucket\", new BucketLogging(\"mylogs\", \"access_log-\", ImmutableSet\n                        .<Grant> of(new Grant(new EmailAddressGrantee(\"adrian@jclouds.org\"), Permission.FULL_CONTROL)))));\n\n      assertRequestLineEquals(request, \"PUT https://bucket.\" + url + \"/?logging HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: bucket.\" + url + \"\\n\");\n      assertPayloadEquals(request, Strings2.toStringAndClose(getClass().getResourceAsStream(\"/bucket_logging.xml\")),\n               \"text/xml\", false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testInitiateMultipartUpload() throws SecurityException, NegativeArraySizeException,\n         NoSuchMethodException {\n      Invokable<?, ?> method = method(S3Client.class, \"initiateMultipartUpload\", String.class, ObjectMetadata.class,\n            PutObjectOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"bucket\", ObjectMetadataBuilder.create().key(\"foo\")\n            .contentMD5(new byte[16]).build()));\n\n      assertRequestLineEquals(request, \"POST https://bucket.\" + url + \"/foo?uploads HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request,\n            \"Content-MD5: AAAAAAAAAAAAAAAAAAAAAA==\\n\" +\n            \"Content-Type: binary/octet-stream\\n\" +\n            \"Host: bucket.\" + url + \"\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      // as this is a payload-related command, but with no payload, be careful\n      // that we check\n      // filtering and do not ignore if this fails later.\n      request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);\n\n      assertRequestLineEquals(request, \"POST https://bucket.\" + url + \"/foo?uploads HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request,\n            \"Authorization: AWS identity:972m/Bqn2L5FIaB+wWDeY83mGvU=\\n\" +\n            \"Content-MD5: AAAAAAAAAAAAAAAAAAAAAA==\\n\" +\n            \"Content-Type: binary/octet-stream\\n\" +\n            \"Date: 2009-11-08T15:54:08.897Z\\n\" +\n            \"Host: bucket.\" + url + \"\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, UploadIdFromHttpResponseViaRegex.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(request);\n   }\n\n   public void testAbortMultipartUpload() throws SecurityException, NegativeArraySizeException, NoSuchMethodException {\n      Invokable<?, ?> method = method(S3Client.class, \"abortMultipartUpload\", String.class, String.class, String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"bucket\", \"foo\", \"asdsadasdas\", 1,\n            Payloads.newStringPayload(\"\")));\n\n      assertRequestLineEquals(request, \"DELETE https://bucket.\" + url + \"/foo?uploadId=asdsadasdas HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: bucket.\" + url + \"\\n\");\n      assertPayloadEquals(request, \"\", \"application/unknown\", false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, VoidOnNotFoundOr404.class);\n\n      checkFilters(request);\n   }\n\n   public void testUploadPart() throws SecurityException, NegativeArraySizeException, NoSuchMethodException {\n      Invokable<?, ?> method = method(S3Client.class, \"uploadPart\", String.class, String.class, int.class,\n            String.class, Payload.class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"bucket\", \"foo\", 1, \"asdsadasdas\",\n            Payloads.newStringPayload(\"\")));\n\n      assertRequestLineEquals(request, \"PUT https://bucket.\" + url + \"/foo?partNumber=1&uploadId=asdsadasdas HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: bucket.\" + url + \"\\n\");\n      assertPayloadEquals(request, \"\", \"application/unknown\", false);\n\n      assertResponseParserClassEquals(method, request, ParseETagHeader.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(request);\n   }\n\n   public void testUploadPartCopy() throws SecurityException, NegativeArraySizeException, NoSuchMethodException {\n      Invokable<?, ?> method = method(S3Client.class, \"uploadPartCopy\", String.class, String.class, int.class,\n            String.class, String.class, String.class, long.class, long.class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"bucket\", \"foo\", 1, \"asdsadasdas\",\n            \"anotherBucket\", \"anotherObject\", 2, 10 * 1024 * 1024));\n\n      assertRequestLineEquals(request, \"PUT https://bucket.\" + url + \"/foo?partNumber=1&uploadId=asdsadasdas HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: bucket.\" + url + \"\\n\" +\n            \"x-amz-copy-source: /anotherBucket/anotherObject\\n\" +\n            \"x-amz-copy-source-range: bytes=2-10485760\\n\");\n      assertPayloadEquals(request, null, \"application/unknown\", false);\n\n      assertResponseParserClassEquals(method, request, ETagFromHttpResponseViaRegex.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(request);\n   }\n\n   public void testCompleteMultipartUpload() throws SecurityException, NegativeArraySizeException,\n         NoSuchMethodException {\n      Invokable<?, ?> method = method(S3Client.class, \"completeMultipartUpload\", String.class, String.class,\n            String.class, Map.class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"bucket\", \"foo\", \"asdsadasdas\",\n            ImmutableMap.<Integer, String> of(1, \"\\\"a54357aff0632cce46d942af68356b38\\\"\")));\n\n      assertRequestLineEquals(request, \"POST https://bucket.\" + url + \"/foo?uploadId=asdsadasdas HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: bucket.\" + url + \"\\n\");\n      assertPayloadEquals(\n            request,\n            \"<CompleteMultipartUpload><Part><PartNumber>1</PartNumber><ETag>\\\"a54357aff0632cce46d942af68356b38\\\"</ETag></Part></CompleteMultipartUpload>\",\n            \"text/xml\", false);\n\n      assertResponseParserClassEquals(method, request, ETagFromHttpResponseViaRegex.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(request);\n   }\n\n   public void testListMultipartUploads() throws Exception {\n      Invokable<?, ?> method = method(S3Client.class, \"listMultipartUploads\", String.class, String.class,\n            Integer.class, String.class, String.class, String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Arrays.<Object> asList(\"bucket\", null, null, null, null, null));\n\n      assertRequestLineEquals(request, \"GET https://bucket.\" + url + \"/?uploads HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: bucket.\" + url + \"\\n\");\n      assertPayloadEquals(request, null, \"application/unknown\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, ListMultipartUploadsHandler.class);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n      checkFilters(request);\n   }\n\n   @ConfiguresHttpApi\n   private static final class TestS3HttpApiModule extends S3HttpApiModule<S3Client> {\n\n      @Override\n      protected String provideTimeStamp(@TimeStamp Supplier<String> cache) {\n         return \"2009-11-08T15:54:08.897Z\";\n      }\n   }\n\n   @Override\n   protected Module createModule() {\n      return new TestS3HttpApiModule();\n   }\n\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/S3Test.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.testng.Assert.assertEquals;\n\nimport org.easymock.EasyMock;\nimport org.jclouds.collect.PagedIterable;\nimport org.jclouds.s3.domain.ListBucketResponse;\nimport org.jclouds.s3.domain.ObjectMetadata;\nimport org.jclouds.s3.domain.internal.ListBucketResponseImpl;\nimport org.jclouds.s3.options.ListBucketOptions;\nimport org.jclouds.s3.xml.ListBucketHandlerTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code S3}.\n */\npublic class S3Test {\n\n   /**\n    * Tests {@link S3#listBucket(S3Client, String, ListBucketOptions)} where a\n    * single response returns all results.\n    *\n    * @throws Exception\n    *            if anything goes wrong\n    */\n   @Test\n   public void testSinglePageResult() throws Exception {\n      S3Client api = createMock(S3Client.class);\n      ListBucketOptions options = new ListBucketOptions();\n      ListBucketResponse response = new ListBucketHandlerTest().expected();\n\n      expect(api.listBucket(\"bucket\", options)).andReturn(response).once();\n\n      EasyMock.replay(api);\n\n      PagedIterable<ObjectMetadata> result = S3.listBucket(api, \"bucket\", options);\n\n      // number of pages\n      assertEquals(result.size(), 1);\n      // number of objects\n      assertEquals(result.get(0).size(), 10);\n   }\n\n   /**\n    * Tests {@link S3#listBucket(S3Client, String, ListBucketOptions)} where\n    * retrieving all results requires multiple requests.\n    *\n    * @throws Exception\n    *            if anything goes wrong\n    */\n   @Test\n   public void testMultiPageResult() throws Exception {\n      String nextMarker = \"FOO\";\n      S3Client api = createMock(S3Client.class);\n      ListBucketOptions options = new ListBucketOptions();\n      ListBucketResponse response2 = new ListBucketHandlerTest().expected();\n      ListBucketResponse response1 = new ListBucketResponseImpl(response2.getName(), response2, response2.getPrefix(),\n            null, nextMarker, response2.getMaxKeys(), response2.getDelimiter(), false, response2.getCommonPrefixes());\n\n      expect(api.listBucket(\"bucket\", options)).andReturn(response1).once();\n      expect(api.listBucket(\"bucket\", options.afterMarker(nextMarker))).andReturn(response2).once();\n\n      EasyMock.replay(api);\n\n      PagedIterable<ObjectMetadata> result = S3.listBucket(api, \"bucket\", options);\n\n      // number of objects\n      assertEquals(result.concat().size(), 20);\n   }\n\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/binders/BindACLToXMLPayloadTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.s3.domain.AccessControlList;\nimport org.jclouds.s3.domain.AccessControlList.EmailAddressGrantee;\nimport org.jclouds.s3.domain.AccessControlList.Permission;\nimport org.jclouds.s3.domain.CanonicalUser;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@link #BindACLToXMLPayload}\n */\n//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"BindBucketLoggingToXmlPayloadTest\")\npublic class BindACLToXMLPayloadTest  extends BaseHandlerTest {\n   public void testBindToRequest() throws IOException {\n\t   AccessControlList acl = new AccessControlList();\n\t   acl.setOwner(new CanonicalUser(\"jnrouvignac\", \"Jean-Noël Rouvignac\"));\n\t   acl.addPermission(new EmailAddressGrantee(\"adrian@jclouds.org\"),\n                        Permission.FULL_CONTROL);\n     \n      String expected = Strings2.toStringAndClose(getClass().getResourceAsStream(\n               \"/acl_to_xml.xml\"));\n      \n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://test\").build();\n      BindACLToXMLPayload binder = new BindACLToXMLPayload();\n\n      binder.bindToRequest(request, acl);\n      assertEquals(request.getPayload().getContentMetadata().getContentType(), \"text/xml\");\n      assertEquals(request.getPayload().getRawContent(), expected);\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/binders/BindAsHostPrefixIfConfiguredNoPathTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.binders;\nimport static org.jclouds.reflect.Reflection2.method;\nimport static org.jclouds.s3.reference.S3Constants.PROPERTY_S3_VIRTUAL_HOST_BUCKETS;\n\nimport java.io.IOException;\nimport java.util.Properties;\n\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.jclouds.s3.S3Client;\nimport org.jclouds.s3.internal.BaseS3ClientTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.reflect.Invokable;\n\n/**\n * Tests behavior of {@code BindAsHostPrefixIfConfigured}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"BindAsHostPrefixIfConfiguredNoPathTest\")\npublic class BindAsHostPrefixIfConfiguredNoPathTest extends BaseS3ClientTest<S3Client> {\n\n   public void testBucketWithHostnameStyle() throws IOException, SecurityException, NoSuchMethodException {\n\n      Invokable<?, ?> method = method(S3Client.class, \"deleteObject\", String.class, String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"testbucket.example.com\", \"test.jpg\"));\n      assertRequestLineEquals(request, \"DELETE http://localhost/testbucket.example.com/test.jpg HTTP/1.1\");\n   }\n\n\n   @Override\n   protected Properties setupProperties() {\n      Properties properties = super.setupProperties();\n      properties.setProperty(PROPERTY_S3_VIRTUAL_HOST_BUCKETS, \"false\");\n      return properties;\n   }\n\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/binders/BindAsHostPrefixIfConfiguredTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.binders;\n\nimport static org.jclouds.reflect.Reflection2.method;\nimport static org.jclouds.s3.reference.S3Constants.PROPERTY_S3_SERVICE_PATH;\nimport static org.jclouds.s3.reference.S3Constants.PROPERTY_S3_VIRTUAL_HOST_BUCKETS;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.util.Properties;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.s3.S3Client;\nimport org.jclouds.s3.internal.BaseS3ClientTest;\nimport org.testng.annotations.DataProvider;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.reflect.Invokable;\n/**\n * Tests behavior of {@code BindAsHostPrefixIfConfigured}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"BindAsHostPrefixIfConfiguredTest\")\npublic class BindAsHostPrefixIfConfiguredTest extends BaseS3ClientTest<S3Client> {\n\n   public void testBucket() throws IOException {\n\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://euc/services/Walrus\").build();\n      BindAsHostPrefixIfConfigured binder = injector.getInstance(BindAsHostPrefixIfConfigured.class);\n\n      request = binder.bindToRequest(request, \"bucket\");\n      assertEquals(request.getRequestLine(), \"GET http://euc/services/Walrus/bucket HTTP/1.1\");\n\n   }\n\n   public void testBucketWithHostnameStyle() throws IOException, SecurityException, NoSuchMethodException {\n\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://euc/services/Walrus\").build();\n      BindAsHostPrefixIfConfigured binder = injector.getInstance(BindAsHostPrefixIfConfigured.class);\n\n      request = binder.bindToRequest(request, \"testbucket.example.com\");\n      assertEquals(request.getRequestLine(), \"GET http://euc/services/Walrus/testbucket.example.com HTTP/1.1\");\n\n      Invokable<?, ?> method = method(S3Client.class, \"deleteObject\", String.class, String.class);\n      request = processor.createRequest(method, ImmutableList.<Object> of(\"testbucket.example.com\", \"test.jpg\"));\n\n      assertRequestLineEquals(request, \"DELETE http://euc/services/Walrus/testbucket.example.com/test.jpg HTTP/1.1\");\n   }\n\n   @Test(dataProvider = \"objects\")\n   public void testObject(String key) throws InterruptedException {\n\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://euc/services/Walrus/object\").build();\n      BindAsHostPrefixIfConfigured binder = injector.getInstance(BindAsHostPrefixIfConfigured.class);\n\n      request = binder.bindToRequest(request, \"bucket\");\n      assertEquals(request.getRequestLine(), \"GET http://euc/services/Walrus/bucket/object HTTP/1.1\");\n\n   }\n\n   @DataProvider(name = \"objects\")\n   public Object[][] createData() {\n      return new Object[][] { { \"normal\" }, { \"sp ace\" }, { \"qu?stion\" }, { \"unic₪de\" }, { \"path/foo\" }, { \"colon:\" },\n               { \"asteri*k\" }, { \"quote\\\"\" }, { \"{great<r}\" }, { \"lesst>en\" }, { \"p|pe\" } };\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties properties = super.setupProperties();\n      properties.setProperty(\"s3.endpoint\", \"http://euc/services/Walrus\");\n      properties.setProperty(PROPERTY_S3_SERVICE_PATH, \"/services/Walrus\");\n      properties.setProperty(PROPERTY_S3_VIRTUAL_HOST_BUCKETS, \"false\");\n      return properties;\n   }\n\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/binders/BindBucketLoggingToXmlPayloadTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.s3.domain.AccessControlList.EmailAddressGrantee;\nimport org.jclouds.s3.domain.AccessControlList.Grant;\nimport org.jclouds.s3.domain.AccessControlList.Permission;\nimport org.jclouds.s3.domain.BucketLogging;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@link #BindBucketLoggingToXmlPayload}\n */\n//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"BindBucketLoggingToXmlPayloadTest\")\npublic class BindBucketLoggingToXmlPayloadTest  extends BaseHandlerTest {\n   public void testApplyInputStream() throws IOException {\n      BucketLogging bucketLogging = new BucketLogging(\"mylogs\", \"access_log-\", ImmutableSet\n               .<Grant> of(new Grant(new EmailAddressGrantee(\"adrian@jclouds.org\"),\n                        Permission.FULL_CONTROL)));\n     \n      String expected = Strings2.toStringAndClose(getClass().getResourceAsStream(\n               \"/bucket_logging.xml\"));\n      \n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://test\").build();\n      BindBucketLoggingToXmlPayload binder = new BindBucketLoggingToXmlPayload();\n\n      binder.bindToRequest(request, bucketLogging);\n      assertEquals(request.getPayload().getContentMetadata().getContentType(), \"text/xml\");\n      assertEquals(request.getPayload().getRawContent(), expected);\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/binders/BindIterableAsPayloadToDeleteRequestTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\n\npublic class BindIterableAsPayloadToDeleteRequestTest {\n\n   private final BindIterableAsPayloadToDeleteRequest binder = new BindIterableAsPayloadToDeleteRequest();\n   private final HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost/\").build();\n\n   @Test\n   public void testWithASmallSet() {\n      HttpRequest result = binder.bindToRequest(request, ImmutableSet.of(\"key1\", \"key2\"));\n\n      Payload payload = Payloads\n         .newStringPayload(\"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n<Delete>\" +\n            \"<Object><Key>key1</Key></Object><Object><Key>key2</Key></Object></Delete>\");\n      payload.getContentMetadata().setContentType(MediaType.TEXT_XML);\n\n      assertEquals(result.getPayload(), payload);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testEmptySetThrowsException() {\n      binder.bindToRequest(request, ImmutableSet.of());\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testFailsOnNullSet() {\n      binder.bindToRequest(request, null);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testExpectedASetInstance() {\n      binder.bindToRequest(request, ImmutableList.of());\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/binders/BindNoBucketLoggingToXmlPayloadTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.s3.S3Client;\nimport org.jclouds.s3.internal.BaseS3ClientTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code BindNoBucketLoggingToXmlPayload}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"BindNoBucketLoggingToXmlPayloadTest\")\npublic class BindNoBucketLoggingToXmlPayloadTest extends BaseS3ClientTest<S3Client> {\n\n   public void testApplyInputStream() throws IOException {\n\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://test\").build();\n      BindNoBucketLoggingToXmlPayload binder = injector.getInstance(BindNoBucketLoggingToXmlPayload.class);\n\n      request = binder.bindToRequest(request, \"bucket\");\n      assertEquals(request.getPayload().getRawContent(),\n               \"<BucketLoggingStatus xmlns=\\\"http://s3.amazonaws.com/doc/2006-03-01/\\\"/>\");\n\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/binders/BindObjectMetadataToRequestTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.File;\n\nimport org.jclouds.blobstore.binders.BindMapToHeadersWithPrefix;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.s3.S3Client;\nimport org.jclouds.s3.domain.ObjectMetadata;\nimport org.jclouds.s3.domain.ObjectMetadataBuilder;\nimport org.jclouds.s3.internal.BaseS3ClientTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMultimap;\n\n/**\n * Tests behavior of {@code BindObjectMetadataToRequest}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"BindObjectMetadataToRequestTest\")\npublic class BindObjectMetadataToRequestTest extends BaseS3ClientTest<S3Client> {\n\n   @Test\n   public void testPassWithMinimumDetailsAndPayload5GB() {\n      ObjectMetadata md = ObjectMetadataBuilder.create().key(\"foo\").build();\n\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      BindObjectMetadataToRequest binder = injector.getInstance(BindObjectMetadataToRequest.class);\n\n      assertEquals(binder.bindToRequest(request, md), HttpRequest.builder().method(\"POST\")\n               .endpoint(\"http://localhost\").addHeader(\"Content-Type\", \"binary/octet-stream\").build());\n   }\n\n   @Test\n   public void testExtendedPropertiesBind() {\n      ObjectMetadata md = ObjectMetadataBuilder.create().key(\"foo\").cacheControl(\"no-cache\").userMetadata(\n               ImmutableMap.of(\"foo\", \"bar\")).build();\n\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      BindObjectMetadataToRequest binder = injector.getInstance(BindObjectMetadataToRequest.class);\n\n      assertEquals(binder.bindToRequest(request, md), HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").headers(\n               ImmutableMultimap.of(\"Cache-Control\", \"no-cache\", \"x-amz-meta-foo\", \"bar\", \"Content-Type\",\n                        \"binary/octet-stream\")).build());\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testNoKeyIsBad() {\n      ObjectMetadata md = ObjectMetadataBuilder.create().build();\n\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      BindObjectMetadataToRequest binder = injector.getInstance(BindObjectMetadataToRequest.class);\n      binder.bindToRequest(request, md);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testMustBeObjectMetadata() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      injector.getInstance(BindObjectMetadataToRequest.class).bindToRequest(request, new File(\"foo\"));\n   }\n\n   @Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class })\n   public void testNullIsBad() {\n      BindMapToHeadersWithPrefix binder = new BindMapToHeadersWithPrefix(\"prefix:\");\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").build();\n      binder.bindToRequest(request, null);\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/binders/BindPartIdsAndETagsToRequestTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.blobstore.binders.BindMapToHeadersWithPrefix;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Tests behavior of {@code BindPartIdsAndETagsToRequest}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"BindPartIdsAndETagsToRequestTest\")\npublic class BindPartIdsAndETagsToRequestTest {\n   BindPartIdsAndETagsToRequest binder = new BindPartIdsAndETagsToRequest();\n\n   @Test\n   public void testPassWithMinimumDetailsAndPayload5GB() {\n      HttpRequest request = HttpRequest.builder().method(\"PUT\").endpoint(\"http://localhost\").build();\n      Payload payload = Payloads\n               .newStringPayload(\"<CompleteMultipartUpload><Part><PartNumber>1</PartNumber><ETag>\\\"a54357aff0632cce46d942af68356b38\\\"</ETag></Part></CompleteMultipartUpload>\");\n      payload.getContentMetadata().setContentType(MediaType.TEXT_XML);\n      request = binder.bindToRequest(request, ImmutableMap.<Integer, String> of(1,\n               \"\\\"a54357aff0632cce46d942af68356b38\\\"\"));\n      assertEquals(request.getPayload().getRawContent(), payload.getRawContent());\n      assertEquals(request, HttpRequest.builder().method(\"PUT\").endpoint(\"http://localhost\").payload(\n               payload).build());\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testEmptyIsBad() {\n\n      HttpRequest request = HttpRequest.builder().method(\"PUT\").endpoint(\"http://localhost\").build();\n      binder.bindToRequest(request, ImmutableMap.<Integer, String> of());\n   }\n\n   @Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class })\n   public void testNullIsBad() {\n      BindMapToHeadersWithPrefix binder = new BindMapToHeadersWithPrefix(\"prefix:\");\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").build();\n      binder.bindToRequest(request, null);\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/binders/BindS3ObjectMetadataToRequestTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.File;\nimport java.net.URI;\n\nimport org.jclouds.blobstore.binders.BindMapToHeadersWithPrefix;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.s3.S3Client;\nimport org.jclouds.s3.domain.S3Object;\nimport org.jclouds.s3.internal.BaseS3ClientTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMultimap;\n\n/**\n * Tests behavior of {@code BindS3ObjectMetadataToRequest}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"BindS3ObjectMetadataToRequestTest\")\npublic class BindS3ObjectMetadataToRequestTest extends BaseS3ClientTest<S3Client> {\n\n   @Test\n   public void testPassWithMinimumDetailsAndPayload5GB() {\n      S3Object object = injector.getInstance(S3Object.Factory.class).create(null);\n      Payload payload = Payloads.newStringPayload(\"\");\n      payload.getContentMetadata().setContentLength(5368709120L);\n      object.setPayload(payload);\n      object.getMetadata().setKey(\"foo\");\n\n      HttpRequest request = HttpRequest.builder().method(\"PUT\").endpoint(\"http://localhost\").build();\n      BindS3ObjectMetadataToRequest binder = injector.getInstance(BindS3ObjectMetadataToRequest.class);\n\n      assertEquals(binder.bindToRequest(request, object), HttpRequest.builder().method(\"PUT\").endpoint(\n               URI.create(\"http://localhost\")).build());\n   }\n\n   @Test\n   public void testExtendedPropertiesBind() {\n      S3Object object = injector.getInstance(S3Object.Factory.class).create(null);\n      Payload payload = Payloads.newStringPayload(\"\");\n      payload.getContentMetadata().setContentLength(5368709120L);\n      object.setPayload(payload);\n      object.getMetadata().setKey(\"foo\");\n      object.getMetadata().setUserMetadata(ImmutableMap.of(\"foo\", \"bar\"));\n\n      HttpRequest request = HttpRequest.builder().method(\"PUT\").endpoint(\"http://localhost\").build();\n      BindS3ObjectMetadataToRequest binder = injector.getInstance(BindS3ObjectMetadataToRequest.class);\n\n      assertEquals(binder.bindToRequest(request, object), HttpRequest.builder().method(\"PUT\").endpoint(\n               URI.create(\"http://localhost\")).headers(\n               ImmutableMultimap.of(\"x-amz-meta-foo\", \"bar\")).build());\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testNoContentLengthIsBad() {\n      S3Object object = injector.getInstance(S3Object.Factory.class).create(null);\n      Payload payload = Payloads.newStringPayload(\"\");\n      payload.getContentMetadata().setContentLength(null);\n      object.setPayload(payload);\n      object.getMetadata().setKey(\"foo\");\n\n      HttpRequest request = HttpRequest.builder().method(\"PUT\").endpoint(\"http://localhost\").build();\n      BindS3ObjectMetadataToRequest binder = injector.getInstance(BindS3ObjectMetadataToRequest.class);\n      binder.bindToRequest(request, object);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testNoKeyIsBad() {\n      S3Object object = injector.getInstance(S3Object.Factory.class).create(null);\n      Payload payload = Payloads.newStringPayload(\"\");\n      payload.getContentMetadata().setContentLength(5368709120000L);\n      object.setPayload(payload);\n\n      HttpRequest request = HttpRequest.builder().method(\"PUT\").endpoint(\"http://localhost\").build();\n      BindS3ObjectMetadataToRequest binder = injector.getInstance(BindS3ObjectMetadataToRequest.class);\n      binder.bindToRequest(request, object);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testOver5GBIsBad() {\n      S3Object object = injector.getInstance(S3Object.Factory.class).create(null);\n      Payload payload = Payloads.newStringPayload(\"\");\n      payload.getContentMetadata().setContentLength(5368709120000L);\n      object.setPayload(payload);\n      object.getMetadata().setKey(\"foo\");\n\n      HttpRequest request = HttpRequest.builder().method(\"PUT\").endpoint(\"http://localhost\").build();\n      BindS3ObjectMetadataToRequest binder = injector.getInstance(BindS3ObjectMetadataToRequest.class);\n      binder.bindToRequest(request, object);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testMustBeS3Object() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      injector.getInstance(BindS3ObjectMetadataToRequest.class).bindToRequest(request, new File(\"foo\"));\n   }\n\n   @Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class })\n   public void testNullIsBad() {\n      BindMapToHeadersWithPrefix binder = new BindMapToHeadersWithPrefix(\"prefix:\");\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").build();\n      binder.bindToRequest(request, null);\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/blobstore/S3BlobSignerExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.blobstore;\n\nimport org.jclouds.blobstore.internal.BaseBlobSignerExpectTest;\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.s3.S3Client;\nimport org.jclouds.s3.config.S3HttpApiModule;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.inject.Module;\n\n/**\n * Tests behavior of {@code S3BlobRequestSigner}\n */\n@Test(groups = \"unit\", testName = \"S3BlobSignerExpectTest\")\npublic class S3BlobSignerExpectTest extends BaseBlobSignerExpectTest {\n\n   public S3BlobSignerExpectTest() {\n      provider = \"s3\";\n   }\n\n   @Override\n   protected HttpRequest getBlob() {\n      return HttpRequest.builder().method(\"GET\")\n                        .endpoint(\"http://localhost/container/name\")\n                        .addQueryParam(\"Expires\", \"1212684799\")\n                        .addQueryParam(\"AWSAccessKeyId\", \"identity\")\n                        .addQueryParam(\"Signature\", \"Z0UqrkQv83rykFxvI3f0dQtxEAM=\")\n                        .build();\n   }\n\n   @Override\n   protected HttpRequest getBlobWithTime() {\n      return HttpRequest.builder().method(\"GET\")\n            .endpoint(\"http://localhost/container/name\")\n            .addQueryParam(\"Expires\", \"1212683902\")\n            .addQueryParam(\"AWSAccessKeyId\", \"identity\")\n            .addQueryParam(\"Signature\", \"Y4Ac4sZfBemGZmgfG78F7IX+IFg=\")\n            .build();\n   }\n\n   @Override\n   protected HttpRequest getBlobWithOptions() {\n      return HttpRequest.builder().method(\"GET\")\n            .endpoint(\"http://localhost/container/name\")\n            .addHeader(\"Range\", \"bytes=0-1\")\n            .addHeader(\"Date\", \"Thu, 05 Jun 2008 16:38:19 GMT\")\n            .addHeader(\"Authorization\", \"AWS identity:0uvBv1wEskuhFHYJF/L6kEV9A7o=\").build();\n   }\n\n   @Override\n   protected HttpRequest putBlob() {\n      return HttpRequest.builder().method(\"PUT\")\n            .endpoint(\"http://localhost/container/name\")\n            .addQueryParam(\"Expires\", \"1212684799\")\n            .addQueryParam(\"AWSAccessKeyId\", \"identity\")\n            .addQueryParam(\"Signature\", \"N3+nS6ogzOqgT+YaThFN6RU/+xs=\")\n            .addHeader(\"Expect\", \"100-continue\")\n            .build();\n   }\n\n   @Override\n   protected HttpRequest putBlobWithTime() {\n      return HttpRequest.builder().method(\"PUT\")\n            .endpoint(\"http://localhost/container/name\")\n            .addQueryParam(\"Expires\", \"1212683902\")\n            .addQueryParam(\"AWSAccessKeyId\", \"identity\")\n            .addQueryParam(\"Signature\", \"genkB2vLxe3AWV/bPvRTMqQts7E=\")\n            .addHeader(\"Expect\", \"100-continue\")\n            .build();\n   }\n\n   @Override\n   protected HttpRequest removeBlob() {\n      return HttpRequest.builder().method(\"DELETE\")\n            .endpoint(\"http://localhost/container/name\")\n            .addHeader(\"Date\", \"Thu, 05 Jun 2008 16:38:19 GMT\")\n            .addHeader(\"Authorization\", \"AWS identity:4FnyjdX/ULdDMRbVlLNjZfEo9RQ=\").build();\n   }\n\n   @Override\n   protected Module createModule() {\n      return new TestS3HttpApiModule();\n   }\n\n   @ConfiguresHttpApi\n   private static final class TestS3HttpApiModule extends S3HttpApiModule<S3Client> {\n\n      @Override\n      protected String provideTimeStamp(@TimeStamp Supplier<String> cache) {\n         return \"Thu, 05 Jun 2008 16:38:19 GMT\";\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/blobstore/functions/BlobToHttpGetOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.blobstore.functions;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.blobstore.functions.BlobToHttpGetOptions;\nimport org.jclouds.http.options.GetOptions;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\")\npublic class BlobToHttpGetOptionsTest {\n\n   @Test\n   void testOneRange() {\n      BlobToHttpGetOptions converter = new BlobToHttpGetOptions();\n      org.jclouds.blobstore.options.GetOptions blobGet = new org.jclouds.blobstore.options.GetOptions()\n            .range(2, 5);\n      GetOptions httpGet = converter.apply(blobGet);\n      assertEquals(httpGet.buildRequestHeaders().get(\"Range\"), ImmutableSet\n            .of(\"bytes=2-5\"));\n\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/blobstore/functions/BucketToContainerListOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.blobstore.functions;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.blobstore.options.ListContainerOptions;\nimport org.jclouds.s3.options.ListBucketOptions;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class BucketToContainerListOptions implements Function<ListBucketOptions[], ListContainerOptions> {\n   public ListContainerOptions apply(ListBucketOptions[] optionsList) {\n      ListContainerOptions options = new ListContainerOptions();\n      if (optionsList.length != 0) {\n         if (optionsList[0].getDelimiter() == null) {\n            options.recursive();\n         } else {\n            options.delimiter(optionsList[0].getDelimiter());\n         }\n         if (optionsList[0].getMarker() != null) {\n            options.afterMarker(optionsList[0].getMarker());\n         }\n         if (optionsList[0].getMaxResults() != null) {\n            options.maxResults(optionsList[0].getMaxResults());\n         }\n         if (optionsList[0].getPrefix() != null) {\n            options.inDirectory(optionsList[0].getPrefix());\n         }\n      }\n      return options;\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/blobstore/functions/BucketsToStorageMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.blobstore.functions;\n\nimport static com.google.common.util.concurrent.MoreExecutors.newDirectExecutorService;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.blobstore.domain.MutableStorageMetadata;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.domain.StorageType;\nimport org.jclouds.blobstore.domain.internal.MutableStorageMetadataImpl;\nimport org.jclouds.blobstore.domain.internal.PageSetImpl;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.s3.domain.BucketMetadata;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Functions;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code BucketsToStorageMetadata}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"BucketsToStorageMetadataTest\")\npublic class BucketsToStorageMetadataTest {\n   protected Location provider = new LocationBuilder().scope(LocationScope.PROVIDER).id(\"aws-ec2\")\n            .description(\"aws-ec2\").build();\n\n   protected Location region = new LocationBuilder().scope(LocationScope.REGION).id(\"us-east-1\")\n            .description(\"us-east-1\").parent(provider).build();\n\n   public void test() {\n      BucketsToStorageMetadata fn = new BucketsToStorageMetadata(\n               newDirectExecutorService(),\n               new BucketToResourceMetadata(Functions.forMap(ImmutableMap.<String, Location> of(\"mycontainer\", region))));\n\n      MutableStorageMetadata expected = new MutableStorageMetadataImpl();\n      expected.setName(\"mycontainer\");\n      expected.setType(StorageType.CONTAINER);\n      expected.setLocation(region);\n      \n      assertEquals(\n               fn.apply(ImmutableSet.of(new BucketMetadata(\"mycontainer\", null, null))).toString(),\n               new PageSetImpl<StorageMetadata>(ImmutableSet.<StorageMetadata> of(expected), null).toString());\n\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/blobstore/functions/LocationFromBucketNameTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.blobstore.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Set;\n\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Functions;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code LocationFromBucketName}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"LocationFromBucketNameTest\")\npublic class LocationFromBucketNameTest {\n   protected Location provider = new LocationBuilder().scope(LocationScope.PROVIDER).id(\"aws-ec2\")\n            .description(\"aws-ec2\").build();\n\n   protected Location region = new LocationBuilder().scope(LocationScope.REGION).id(\"us-east-1\")\n            .description(\"us-east-1\").parent(provider).build();\n\n   protected Location region2 = new LocationBuilder().scope(LocationScope.REGION).id(\"eu-west-1\")\n            .description(\"eu-west-1\").parent(provider).build();\n\n   public void testOnlyLocationDoesntNeedMapping() {\n      LocationFromBucketName fn = new LocationFromBucketName(Functions.forMap(ImmutableMap\n               .<String, Optional<String>> of()), Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n               .of(provider)));\n\n      assertEquals(fn.apply(\"mybucket\"), provider);\n\n   }\n\n   public void testMapsToCorrectRegion() {\n      LocationFromBucketName fn = new LocationFromBucketName(Functions.forMap(ImmutableMap\n               .<String, Optional<String>> of(\"mybucket\", Optional.of(\"eu-west-1\"))),\n               Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet.of(region, region2)));\n\n      assertEquals(fn.apply(\"mybucket\"), region2);\n\n   }\n\n   public void testNullOnUnmatchedRegion() {\n      LocationFromBucketName fn = new LocationFromBucketName(Functions.forMap(ImmutableMap\n               .<String, Optional<String>> of(\"mybucket\", Optional.of(\"eu-west-2\"))),\n               Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet.of(region, region2)));\n\n      assertEquals(fn.apply(\"mybucket\"), null);\n\n   }\n\n   public void testNullOnAbsentData() {\n      LocationFromBucketName fn = new LocationFromBucketName(Functions.forMap(ImmutableMap\n               .<String, Optional<String>> of(\"mybucket\", Optional.<String> absent())),\n               Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet.of(region, region2)));\n\n      assertEquals(fn.apply(\"mybucket\"), null);\n\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/blobstore/functions/ResourceToBucketList.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.blobstore.functions;\n\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.blobstore.domain.BlobMetadata;\nimport org.jclouds.blobstore.domain.PageSet;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.domain.StorageType;\nimport org.jclouds.s3.domain.ListBucketResponse;\nimport org.jclouds.s3.domain.MutableObjectMetadata;\nimport org.jclouds.s3.domain.ObjectMetadata;\nimport org.jclouds.s3.domain.internal.ListBucketResponseImpl;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Sets;\n\n@Singleton\npublic class ResourceToBucketList implements\n         Function<PageSet<? extends StorageMetadata>, ListBucketResponse> {\n   private final BlobToObjectMetadata blob2ObjectMd;\n\n   @Inject\n   public ResourceToBucketList(BlobToObjectMetadata blob2ObjectMd) {\n      this.blob2ObjectMd = blob2ObjectMd;\n   }\n\n   public ListBucketResponse apply(PageSet<? extends StorageMetadata> list) {\n\n      Iterable<ObjectMetadata> contents = Iterables.transform(Iterables.filter(list,\n               new Predicate<StorageMetadata>() {\n\n                  public boolean apply(StorageMetadata input) {\n                     return input.getType() == StorageType.BLOB;\n                  }\n\n               }), new Function<StorageMetadata, ObjectMetadata>() {\n\n         public MutableObjectMetadata apply(StorageMetadata from) {\n            return blob2ObjectMd.apply((BlobMetadata) from);\n         }\n\n      });\n\n      Set<String> commonPrefixes = Sets.newLinkedHashSet(Iterables.transform(Iterables.filter(list,\n               new Predicate<StorageMetadata>() {\n\n                  public boolean apply(StorageMetadata input) {\n                     return input.getType() == StorageType.RELATIVE_PATH;\n                  }\n\n               }), new Function<StorageMetadata, String>() {\n\n         public String apply(StorageMetadata from) {\n            return from.getName();\n         }\n\n      }));\n      return new ListBucketResponseImpl(null, contents, null, null, list.getNextMarker(), 0, \"/\",\n               list.getNextMarker() != null, commonPrefixes);\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/blobstore/integration/S3BlobIntegrationLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.blobstore.integration;\n\nimport java.io.IOException;\nimport java.util.Properties;\nimport java.util.concurrent.ExecutionException;\n\nimport org.jclouds.blobstore.integration.internal.BaseBlobIntegrationTest;\nimport org.jclouds.blobstore.integration.internal.BaseBlobStoreIntegrationTest;\nimport org.jclouds.s3.blobstore.strategy.MultipartUpload;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"S3BlobIntegrationLiveTest\")\npublic class S3BlobIntegrationLiveTest extends BaseBlobIntegrationTest {\n\n   public S3BlobIntegrationLiveTest() {\n      provider = \"s3\";\n      BaseBlobStoreIntegrationTest.SANITY_CHECK_RETURNED_BUCKET_NAME = true;\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      props.setProperty(\"jclouds.mpu.parts.size\", String.valueOf(MultipartUpload.MIN_PART_SIZE));\n      return props;\n   }\n\n   @Override\n   protected long getMinimumMultipartBlobSize() {\n      return MultipartUpload.MIN_PART_SIZE + 1;\n   }\n\n   @Override\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testPutObjectStream() throws InterruptedException, IOException, ExecutionException {\n      super.testPutObjectStream();\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/blobstore/integration/S3BlobLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.blobstore.integration;\n\nimport org.jclouds.blobstore.integration.internal.BaseBlobLiveTest;\nimport org.jclouds.blobstore.integration.internal.BaseBlobStoreIntegrationTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"S3BlobLiveTest\")\npublic class S3BlobLiveTest extends BaseBlobLiveTest {\n\n   public S3BlobLiveTest() {\n      provider = \"s3\";\n      BaseBlobStoreIntegrationTest.SANITY_CHECK_RETURNED_BUCKET_NAME = true;\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/blobstore/integration/S3BlobSignerLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.blobstore.integration;\n\nimport java.io.IOException;\n\nimport org.jclouds.blobstore.integration.internal.BaseBlobSignerLiveTest;\nimport org.jclouds.blobstore.integration.internal.BaseBlobStoreIntegrationTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"S3BlobSignerLiveTest\")\npublic class S3BlobSignerLiveTest extends BaseBlobSignerLiveTest {\n\n   public S3BlobSignerLiveTest() {\n      provider = \"s3\";\n      BaseBlobStoreIntegrationTest.SANITY_CHECK_RETURNED_BUCKET_NAME = true;\n   }\n\n   @Test\n   public void testSignGetUrlWithTimeExpired() throws InterruptedException, IOException {\n      // Intentionally try with a timeout of 0. AWS signature v4 throws an error if\n      // the timeout is negative.\n      super.testSignGetUrlWithTime(/*timeout=*/ 0);\n   }\n\n   @Test\n   public void testSignPutUrlWithTimeExpired() throws Exception {\n      // Intentionally try with a timeout of 0. AWS signature v4 throws an error if\n      // the timeout is negative.\n      super.testSignPutUrlWithTime(/*timeout=*/ 0);\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/blobstore/integration/S3ContainerIntegrationLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.blobstore.integration;\n\nimport org.jclouds.blobstore.integration.internal.BaseBlobStoreIntegrationTest;\nimport org.jclouds.blobstore.integration.internal.BaseContainerIntegrationTest;\nimport org.testng.SkipException;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"S3ContainerIntegrationLiveTest\")\npublic class S3ContainerIntegrationLiveTest extends BaseContainerIntegrationTest {\n\n   public S3ContainerIntegrationLiveTest() {\n      provider = \"s3\";\n      BaseBlobStoreIntegrationTest.SANITY_CHECK_RETURNED_BUCKET_NAME = true;\n   }\n\n   @Override\n   public void testDirectory() throws InterruptedException {\n      // S3 does not support directories, rather it supports prefixes which look\n      // like directories.  We should filter out the fake RELATIVE_PATH.\n      throw new SkipException(\"not yet implemented\");\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/blobstore/integration/S3ContainerLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.blobstore.integration;\n\nimport java.io.IOException;\nimport java.net.MalformedURLException;\n\nimport org.jclouds.blobstore.integration.internal.BaseBlobStoreIntegrationTest;\nimport org.jclouds.blobstore.integration.internal.BaseContainerLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"S3ContainerLiveTest\")\npublic class S3ContainerLiveTest extends BaseContainerLiveTest {\n\n   public S3ContainerLiveTest() {\n      provider = \"s3\";\n      BaseBlobStoreIntegrationTest.SANITY_CHECK_RETURNED_BUCKET_NAME = true;\n   }\n\n   @Override\n   @Test(groups = {\"live\", \"fails-on-s3proxy\"})\n   public void testPublicAccess() throws InterruptedException, MalformedURLException, IOException {\n      super.testPublicAccess();\n   }\n\n   @Override\n   @Test(groups = {\"live\", \"fails-on-s3proxy\"}, dependsOnMethods = \"testPublicAccess\")\n   public void testPublicAccessInNonDefaultLocation() throws InterruptedException, MalformedURLException, IOException {\n      super.testPublicAccessInNonDefaultLocation();\n   }\n\n   @Override\n   @Test(groups = {\"live\", \"fails-on-s3proxy\"}, dependsOnMethods = \"testPublicAccess\")\n   public void testPublicAccessInNonDefaultLocationWithBigBlob() throws InterruptedException, MalformedURLException,\n            IOException {\n      super.testPublicAccessInNonDefaultLocationWithBigBlob();\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/blobstore/integration/S3ServiceIntegrationLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.blobstore.integration;\n\nimport org.jclouds.blobstore.integration.internal.BaseBlobStoreIntegrationTest;\nimport org.jclouds.blobstore.integration.internal.BaseServiceIntegrationTest;\n\npublic class S3ServiceIntegrationLiveTest extends BaseServiceIntegrationTest {\n\n   public S3ServiceIntegrationLiveTest() {\n      provider = \"s3\";\n      BaseBlobStoreIntegrationTest.SANITY_CHECK_RETURNED_BUCKET_NAME = true;\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/blobstore/internal/BackoffOnNotFoundWhenGetBucketACLTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.blobstore.internal;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertSame;\n\nimport java.util.concurrent.TimeoutException;\n\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.jclouds.s3.S3Client;\nimport org.jclouds.s3.domain.AccessControlList;\nimport org.testng.annotations.BeforeMethod;\nimport org.testng.annotations.Test;\n\nimport com.google.common.util.concurrent.UncheckedExecutionException;\n\n@Test(groups = \"unit\", singleThreaded = true, testName = \"BackoffOnNotFoundWhenGetBucketACLTest\")\npublic class BackoffOnNotFoundWhenGetBucketACLTest {\n   private S3Client mock;\n\n   @BeforeMethod\n   public void setUp() {\n      mock = createMock(S3Client.class);\n   }\n\n   @Test\n   void testMaxRetriesNotExceededReturnsValue() {\n      AccessControlList acl = createMock(AccessControlList.class);\n\n      int attempts = 5;\n      BackoffOnNotFoundWhenGetBucketACL backoff = new BackoffOnNotFoundWhenGetBucketACL(mock);\n\n      expect(mock.getBucketACL(\"foo\")).andThrow(new ResourceNotFoundException()).times(attempts - 1);\n      expect(mock.getBucketACL(\"foo\")).andReturn(acl);\n\n      replay(mock);\n      assertSame(backoff.load(\"foo\"), acl);\n      verify(mock);\n   }\n\n   @Test(expectedExceptions = ResourceNotFoundException.class)\n   void testMaxRetriesExceededThrowsException() {\n      int attempts = 5;\n      BackoffOnNotFoundWhenGetBucketACL backoff = new BackoffOnNotFoundWhenGetBucketACL(mock);\n\n      expect(mock.getBucketACL(\"foo\")).andThrow(new ResourceNotFoundException()).times(attempts);\n\n      replay(mock);\n      backoff.load(\"foo\");\n   }\n\n   @Test(expectedExceptions = UncheckedExecutionException.class)\n   void testDoesntCatchOtherExceptions() {\n      BackoffOnNotFoundWhenGetBucketACL backoff = new BackoffOnNotFoundWhenGetBucketACL(mock);\n\n      expect(mock.getBucketACL(\"foo\")).andThrow(new UncheckedExecutionException(new TimeoutException()));\n\n      replay(mock);\n      backoff.load(\"foo\");\n      verify(mock);\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/fallbacks/FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExistsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.fallbacks;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.jclouds.reflect.Reflection2.method;\nimport static org.testng.Assert.assertFalse;\n\nimport org.jclouds.aws.AWSResponseException;\nimport org.jclouds.aws.domain.AWSError;\nimport org.jclouds.reflect.Invocation;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.jclouds.s3.S3Client;\nimport org.jclouds.s3.options.PutBucketOptions;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Lists;\n\n@Test(testName = \"FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExistsTest\")\npublic class FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExistsTest {\n\n   GeneratedHttpRequest putBucket;\n\n   @BeforeClass\n   void setUp() throws SecurityException, NoSuchMethodException {\n      putBucket = GeneratedHttpRequest.builder()\n            .method(\"PUT\")\n            .endpoint(\"https://adriancole-blobstore113.s3.amazonaws.com/\")\n            .invocation(\n                  Invocation.create(method(S3Client.class, \"putBucketInRegion\", String.class,\n                        String.class, PutBucketOptions[].class), Lists.<Object> newArrayList(null, \"bucket\"))).build();\n   }\n\n   @Test\n   void testBucketAlreadyOwnedByYouIsOk() throws Exception {\n      S3Client client = createMock(S3Client.class);\n      replay(client);\n\n      Exception e = getErrorWithCode(\"BucketAlreadyOwnedByYou\");\n      assertFalse(new FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists(client).setContext(\n            putBucket).createOrPropagate(e));\n      verify(client);\n   }\n\n   @Test\n   void testOperationAbortedIsOkWhenBucketExists() throws Exception {\n      S3Client client = createMock(S3Client.class);\n      expect(client.bucketExists(\"bucket\")).andReturn(true);\n      replay(client);\n      Exception e = getErrorWithCode(\"OperationAborted\");\n      assertFalse(new FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists(client).setContext(\n            putBucket).createOrPropagate(e));\n      verify(client);\n   }\n\n   @Test(expectedExceptions = Exception.class)\n   void testOperationAbortedNotOkWhenBucketDoesntExist() throws Exception {\n      S3Client client = createMock(S3Client.class);\n      expect(client.bucketExists(\"bucket\")).andReturn(false);\n      replay(client);\n      Exception e = getErrorWithCode(\"OperationAborted\");\n      new FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists(client).setContext(putBucket)\n            .createOrPropagate(e);\n   }\n\n   @Test(expectedExceptions = IllegalStateException.class)\n   void testIllegalStateIsNotOk() throws Exception {\n      S3Client client = createMock(S3Client.class);\n      replay(client);\n\n      Exception e = new IllegalStateException();\n      new FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists(client).createOrPropagate(e);\n   }\n\n   @Test(expectedExceptions = AWSResponseException.class)\n   void testBlahIsNotOk() throws Exception {\n      S3Client client = createMock(S3Client.class);\n      replay(client);\n      Exception e = getErrorWithCode(\"blah\");\n      new FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists(client).createOrPropagate(e);\n   }\n\n   private Exception getErrorWithCode(String code) {\n      AWSError error = new AWSError();\n      error.setCode(code);\n      return new AWSResponseException(null, null, null, error);\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/filters/AwsHostNameUtilsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.filters;\n\nimport org.testng.Assert;\nimport org.testng.annotations.Test;\n\nimport java.net.URI;\n\n/**\n * Tests parser region and service\n */\npublic class AwsHostNameUtilsTest {\n   @Test\n   public void testParseRegion() {\n      Assert.assertEquals(\n         AwsHostNameUtils.parseRegionName(\"test.s3.cn-north-1.amazonaws.com.cn\", \"s3\"),\n         \"cn-north-1\"\n      );\n\n\n   }\n\n   @Test\n   // default region\n   public void testParseDefaultRegion() {\n      Assert.assertEquals(\n         AwsHostNameUtils.parseRegionName(\"s3.amazonaws.com\", \"s3\"),\n         \"us-east-1\"\n      );\n   }\n\n   @Test\n   // test s3 service\n   public void testParseService() {\n      Assert.assertEquals(\n         AwsHostNameUtils.parseServiceName(URI.create(\"https://s3.amazonaws.com\")),\n         \"s3\"\n      );\n\n      Assert.assertEquals(\n         AwsHostNameUtils.parseServiceName(URI.create(\"https://test-bucket.s3.cn-north-1.amazonaws.com.cn\")),\n         \"s3\"\n      );\n   }\n\n   @Test\n   // test s3 virtual private cloud URL\n   public void testVpcUrl() {\n      Assert.assertEquals(\n         AwsHostNameUtils.parseServiceName(\n              URI.create(\"https://bucket.vpce-0037af66cf9b0cc5e-zop31d9j.s3.us-east-1.vpce.amazonaws.com\")\n         ),\n         \"s3\"\n      );\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/filters/RequestAuthorizeSignatureV2Test.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.filters;\n\nimport static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL;\nimport static org.jclouds.reflect.Reflection2.method;\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.blobstore.binders.BindBlobToMultipartFormTest;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.jclouds.s3.S3Client;\nimport org.jclouds.s3.domain.AccessControlList;\nimport org.jclouds.s3.domain.CannedAccessPolicy;\nimport org.jclouds.s3.domain.S3Object;\nimport org.jclouds.s3.internal.BaseS3ClientTest;\nimport org.jclouds.s3.options.PutObjectOptions;\nimport org.jclouds.s3.reference.S3Headers;\nimport org.testng.annotations.DataProvider;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.SortedSetMultimap;\nimport com.google.common.collect.TreeMultimap;\nimport com.google.common.net.HttpHeaders;\n\n/**\n * Tests behavior of {@code RequestAuthorizeSignatureV2}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"RequestAuthorizeSignatureV2Test\")\npublic class RequestAuthorizeSignatureV2Test extends BaseS3ClientTest<S3Client> {\n   String bucketName = \"bucket\";\n\n   @DataProvider(parallel = true)\n   public Object[][] dataProvider() throws NoSuchMethodException {\n      return new Object[][]{{listOwnedBuckets()}, {putObject()}, {putBucketAcl()}\n\n      };\n   }\n\n   /**\n    * NOTE this test is dependent on how frequently the timestamp updates. At the time of writing,\n    * this was once per second. If this timestamp update interval is increased, it could make this\n    * test appear to hang for a long time.\n    */\n   @Test(threadPoolSize = 3, dataProvider = \"dataProvider\", timeOut = 10000)\n   void testIdempotent(HttpRequest request) {\n      request = filter.filter(request);\n      String signature = request.getFirstHeaderOrNull(HttpHeaders.AUTHORIZATION);\n      String date = request.getFirstHeaderOrNull(HttpHeaders.DATE);\n      int iterations = 1;\n      while (request.getFirstHeaderOrNull(HttpHeaders.DATE).equals(date)) {\n         date = request.getFirstHeaderOrNull(HttpHeaders.DATE);\n         request = filter.filter(request);\n         if (request.getFirstHeaderOrNull(HttpHeaders.DATE).equals(date))\n            assert signature.equals(request.getFirstHeaderOrNull(HttpHeaders.AUTHORIZATION)) : String.format(\n               \"sig: %s != %s on attempt %s\", signature, request.getFirstHeaderOrNull(HttpHeaders.AUTHORIZATION),\n               iterations);\n         else\n            iterations++;\n\n      }\n      System.out.printf(\"%s: %d iterations before the timestamp updated %n\", Thread.currentThread().getName(),\n         iterations);\n   }\n\n   @Test\n   void testAppendBucketNameHostHeader() throws SecurityException, NoSuchMethodException {\n      GeneratedHttpRequest request = processor.createRequest(\n         method(S3Client.class, \"getBucketLocation\", String.class),\n         ImmutableList.<Object>of(\"bucket\"));\n      StringBuilder builder = new StringBuilder();\n      ((RequestAuthorizeSignatureV2) filter).appendBucketName(request, builder);\n      assertEquals(builder.toString(), \"\");\n   }\n\n   @Test\n   void testAclQueryString() throws SecurityException, NoSuchMethodException {\n      HttpRequest request = putBucketAcl();\n      StringBuilder builder = new StringBuilder();\n      ((RequestAuthorizeSignatureV2) filter).appendUriPath(request, builder);\n      assertEquals(builder.toString(), \"/\" + bucketName + \"?acl\");\n   }\n\n   private GeneratedHttpRequest putBucketAcl() throws NoSuchMethodException {\n      return processor.createRequest(\n         method(S3Client.class, \"putBucketACL\", String.class, AccessControlList.class),\n         ImmutableList.<Object>of(\"bucket\",\n            AccessControlList.fromCannedAccessPolicy(CannedAccessPolicy.PRIVATE, \"1234\")));\n   }\n\n   // \"?acl\", \"?location\", \"?logging\", \"?uploads\", or \"?torrent\"\n\n   @Test\n   void testAppendBucketNameHostHeaderService() throws SecurityException, NoSuchMethodException {\n      HttpRequest request = listOwnedBuckets();\n      StringBuilder builder = new StringBuilder();\n      ((RequestAuthorizeSignatureV2) filter).appendBucketName(request, builder);\n      assertEquals(builder.toString(), \"\");\n   }\n\n   private GeneratedHttpRequest listOwnedBuckets() throws NoSuchMethodException {\n      return processor.createRequest(method(S3Client.class, \"listOwnedBuckets\"),\n         ImmutableList.of());\n   }\n\n   @Test\n   void testHeadersGoLowercase() throws SecurityException, NoSuchMethodException {\n      HttpRequest request = putObject();\n      SortedSetMultimap<String, String> canonicalizedHeaders = TreeMultimap.create();\n      ((RequestAuthorizeSignatureV2) filter).appendHttpHeaders(request, canonicalizedHeaders);\n      StringBuilder builder = new StringBuilder();\n      ((RequestAuthorizeSignatureV2) filter).appendAmzHeaders(canonicalizedHeaders, builder);\n      assertEquals(builder.toString(), S3Headers.USER_METADATA_PREFIX + \"adrian:foo\\n\");\n   }\n\n   private HttpRequest putObject() throws NoSuchMethodException {\n      S3Object object = blobToS3Object.apply(BindBlobToMultipartFormTest.TEST_BLOB);\n      object.getMetadata().getUserMetadata().put(\"Adrian\", \"foo\");\n      return processor.createRequest(method(S3Client.class, \"putObject\", String.class,\n         S3Object.class, PutObjectOptions[].class), ImmutableList.<Object>of(\"bucket\", object));\n   }\n\n   @Test\n   void testAppendBucketNameInURIPath() throws SecurityException, NoSuchMethodException {\n      GeneratedHttpRequest request = processor.createRequest(\n         method(S3Client.class, \"getBucketLocation\", String.class),\n         ImmutableList.<Object>of(bucketName));\n      URI uri = request.getEndpoint();\n      assertEquals(uri.getHost(), \"localhost\");\n      assertEquals(uri.getPath(), \"/\" + bucketName);\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties overrides = super.setupProperties();\n      overrides.setProperty(PROPERTY_SESSION_INTERVAL, 1 + \"\");\n      return overrides;\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/filters/RequestAuthorizeSignatureV4ChunkedUploadTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.filters;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.hash.Hasher;\nimport com.google.common.hash.Hashing;\nimport com.google.common.net.HttpHeaders;\nimport com.google.inject.Injector;\nimport com.google.inject.Module;\nimport org.jclouds.Constants;\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.logging.config.NullLoggingModule;\nimport org.jclouds.reflect.Invocation;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.internal.BaseRestApiTest;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.jclouds.s3.S3ApiMetadata;\nimport org.jclouds.s3.S3Client;\nimport org.jclouds.s3.config.S3HttpApiModule;\nimport org.jclouds.s3.domain.S3Object;\nimport org.jclouds.s3.options.PutObjectOptions;\nimport org.jclouds.util.Closeables2;\nimport org.testng.annotations.Test;\n\nimport jakarta.inject.Named;\nimport java.io.ByteArrayInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.nio.charset.Charset;\nimport java.util.Date;\n\nimport static com.google.common.io.BaseEncoding.base16;\nimport static org.jclouds.reflect.Reflection2.method;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.fail;\n\n/**\n * Tests behavior of {@code RequestAuthorizeSignature}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"RequestAuthorizeSignatureV4ChunkedUploadTest\")\npublic class RequestAuthorizeSignatureV4ChunkedUploadTest {\n   private static final String CONTENT_SEED =\n         \"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc tortor metus, sagittis eget augue ut,\\n\"\n               + \"feugiat vehicula risus. Integer tortor mauris, vehicula nec mollis et, consectetur eget tortor. In ut\\n\"\n               + \"elit sagittis, ultrices est ut, iaculis turpis. In hac habitasse platea dictumst. Donec laoreet tellus\\n\"\n               + \"at auctor tempus. Praesent nec diam sed urna sollicitudin vehicula eget id est. Vivamus sed laoreet\\n\"\n               + \"lectus. Aliquam convallis condimentum risus, vitae porta justo venenatis vitae. Phasellus vitae nunc\\n\"\n               + \"varius, volutpat quam nec, mollis urna. Donec tempus, nisi vitae gravida facilisis, sapien sem malesuada\\n\"\n               + \"purus, id semper libero ipsum condimentum nulla. Suspendisse vel mi leo. Morbi pellentesque placerat congue.\\n\"\n               + \"Nunc sollicitudin nunc diam, nec hendrerit dui commodo sed. Duis dapibus commodo elit, id commodo erat\\n\"\n               + \"congue id. Aliquam erat volutpat.\\n\";\n\n   private static final String CHUKED_UPLOAD_PAYLOAD_SHA256 = \"2b6da230b03189254b2ceafe689c5298cfdd288869e80b2b9369da8f8f0a3d99\";\n\n   private static final String PUT_OBJECT_AUTHORIZATION = \"AWS4-HMAC-SHA256 \"\n         + \"Credential=AKIAPAEBI3QI4EXAMPLE/20150203/cn-north-1/s3/aws4_request, \"\n         + \"SignedHeaders=content-encoding;content-length;content-type;host;x-amz-content-sha256;x-amz-date;x-amz-decoded-content-length;x-amz-storage-class, \"\n         + \"Signature=3db48b3d786d599e8e785ba66030e8a9249c678a52f2432bf6fd44c97cb3145f\";\n\n\n   private static final String IDENTITY = \"AKIAPAEBI3QI4EXAMPLE\";\n   private static final String CREDENTIAL = \"oHkkcPcOjJnoAXpjT8GXdNeBjo6Ru7QeFExAmPlE\";\n   private static final String TIMESTAMP = \"Thu, 03 Feb 2015 07:11:11 GMT\";\n\n   private static final String BUCKET_NAME = \"test-bucket\";\n   private static final String OBJECT_NAME = \"ExampleChunkedObject.txt\";\n\n   @ConfiguresHttpApi\n   private static final class TestS3HttpApiModule extends S3HttpApiModule<S3Client> {\n      @Override\n      protected String provideTimeStamp(@TimeStamp Supplier<String> cache) {\n         return TIMESTAMP;\n      }\n\n      @Override\n      protected Supplier<Date> provideTimeStampCacheDate(\n            @Named(Constants.PROPERTY_SESSION_INTERVAL) long seconds,\n            @TimeStamp final Supplier<String> timestamp,\n            final DateService dateService) {\n         return Suppliers.ofInstance(dateService.rfc822DateParse(TIMESTAMP));\n      }\n   }\n\n   public static Injector injector(Credentials creds) {\n      return ContextBuilder.newBuilder(new S3ApiMetadata())\n            .credentialsSupplier(Suppliers.<Credentials>ofInstance(creds))\n            .modules(ImmutableList.<Module>of(new BaseRestApiTest.MockModule(), new NullLoggingModule(),\n                  new TestS3HttpApiModule()))\n            .buildInjector();\n   }\n\n   public static RequestAuthorizeSignatureV4 filter(Credentials creds) {\n      return injector(creds).getInstance(RequestAuthorizeSignatureV4.class);\n   }\n\n   Credentials temporaryCredentials = new Credentials.Builder()\n         .identity(IDENTITY)\n         .credential(CREDENTIAL)\n         .build();\n\n\n   @Test\n   void testPutObjectWithChunkedUpload() {\n      Invocation invocation = Invocation.create(\n            method(S3Client.class, \"putObject\", String.class, S3Object.class, PutObjectOptions[].class),\n            ImmutableList.<Object>of(BUCKET_NAME));\n      byte[] content = make65KPayload().getBytes(Charset.forName(\"UTF-8\"));\n      HttpRequest putObject = GeneratedHttpRequest.builder().invocation(invocation)\n            .method(\"PUT\")\n            .endpoint(\"https://\" + BUCKET_NAME + \".s3.cn-north-1.amazonaws.com.cn/\" + OBJECT_NAME)\n            .addHeader(HttpHeaders.HOST, BUCKET_NAME + \".s3.cn-north-1.amazonaws.com.cn\")\n            .addHeader(\"x-amz-storage-class\", \"REDUCED_REDUNDANCY\")\n            .build();\n      Payload payload = Payloads.newInputStreamPayload(new ByteArrayInputStream(content));\n      payload.getContentMetadata().setContentLength((long) content.length);\n      payload.getContentMetadata().setContentType(\"text/plain\");\n      putObject.setPayload(payload);\n      HttpRequest filtered = filter(temporaryCredentials).filter(putObject);\n      assertEquals(filtered.getFirstHeaderOrNull(\"Authorization\"), PUT_OBJECT_AUTHORIZATION);\n      assertEquals(filtered.getPayload().getClass(), ChunkedUploadPayload.class);\n\n      InputStream is = null;\n      try {\n         is = filtered.getPayload().openStream();\n         assertEquals(base16().lowerCase().encode(hash(is)), CHUKED_UPLOAD_PAYLOAD_SHA256);\n      } catch (IOException e) {\n         fail(\"open stream error\", e);\n      } finally {\n         Closeables2.closeQuietly(is);\n      }\n   }\n\n   /**\n    * Want sample to upload 3 chunks for our selected chunk size of 64K; one\n    * full size chunk, one partial chunk and then the 0-byte terminator chunk.\n    * This routine just takes 1K of seed text and turns it into a 65K-or-so\n    * string for sample use.\n    */\n   private static String make65KPayload() {\n      StringBuilder oneKSeed = new StringBuilder();\n      while (oneKSeed.length() < 1024) {\n         oneKSeed.append(CONTENT_SEED);\n      }\n\n      // now scale up to meet/exceed our requirement\n      StringBuilder output = new StringBuilder();\n      for (int i = 0; i < 66; i++) {\n         output.append(oneKSeed);\n      }\n      return output.toString();\n   }\n\n   /**\n    * hash input with sha256\n    *\n    * @param input\n    * @return hash result\n    */\n   private static byte[] hash(InputStream input) {\n      try {\n         Hasher hasher = Hashing.sha256().newHasher();\n         byte[] buffer = new byte[4096];\n         int r;\n         while ((r = input.read(buffer)) != -1) {\n            hasher.putBytes(buffer, 0, r);\n         }\n         return hasher.hash().asBytes();\n      } catch (Exception e) {\n         throw new RuntimeException(\"Unable to compute hash while signing request: \" + e.getMessage(), e);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/filters/RequestAuthorizeSignatureV4Test.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.filters;\n\nimport static org.jclouds.reflect.Reflection2.method;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Date;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.Constants;\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.options.GetOptions;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.logging.config.NullLoggingModule;\nimport org.jclouds.reflect.Invocation;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.internal.BaseRestApiTest;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.jclouds.s3.S3ApiMetadata;\nimport org.jclouds.s3.S3Client;\nimport org.jclouds.s3.config.S3HttpApiModule;\nimport org.jclouds.s3.domain.S3Object;\nimport org.jclouds.s3.options.ListBucketOptions;\nimport org.jclouds.s3.options.PutObjectOptions;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.net.HttpHeaders;\nimport com.google.inject.Injector;\nimport com.google.inject.Module;\n\n/**\n * Tests behavior of {@code RequestAuthorizeSignature}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"RequestAuthorizeSignatureV4Test\")\npublic class RequestAuthorizeSignatureV4Test {\n   private static final String IDENTITY = \"AKIAPAEBI3QI4EXAMPLE\";\n   private static final String CREDENTIAL = \"oHkkcPcOjJnoAXpjT8GXdNeBjo6Ru7QeFExAmPlE\";\n   private static final String TIMESTAMP = \"Thu, 03 Feb 2015 07:11:11 GMT\";\n\n   private static final String GET_BUCKET_LOCATION_SIGNATURE_RESULT = \"AWS4-HMAC-SHA256 \"\n         + \"Credential=AKIAPAEBI3QI4EXAMPLE/20150203/cn-north-1/s3/aws4_request, \"\n         + \"SignedHeaders=host;x-amz-content-sha256;x-amz-date, \"\n         + \"Signature=5634847b3ad6a857887ab0ccff2fcaf3d35ef3dc549a3c27ebc0f584a80494c3\";\n\n   private static final String GET_OBJECT_RESULT = \"AWS4-HMAC-SHA256 \"\n         + \"Credential=AKIAPAEBI3QI4EXAMPLE/20150203/cn-north-1/s3/aws4_request, \"\n         + \"SignedHeaders=host;x-amz-content-sha256;x-amz-date, \"\n         + \"Signature=fbd1d0f04a72907fb20ecd771644afd62cb689f91d26e9471b7a234531ec4718\";\n\n   private static final String GET_OBJECT_ACL_RESULT = \"AWS4-HMAC-SHA256 \"\n         + \"Credential=AKIAPAEBI3QI4EXAMPLE/20150203/cn-north-1/s3/aws4_request, \"\n         + \"SignedHeaders=host;x-amz-content-sha256;x-amz-date, \"\n         + \"Signature=52d7f31d249032b59781fe69c8124ff4bf209be3f374b28657a60d906c752381\";\n\n   private static final String PUT_OBJECT_CONTENT = \"text sign\";\n\n   private static final String PUT_OBJECT_RESULT = \"AWS4-HMAC-SHA256 \"\n         + \"Credential=AKIAPAEBI3QI4EXAMPLE/20150203/cn-north-1/s3/aws4_request, \"\n         + \"SignedHeaders=content-length;content-type;host;x-amz-content-sha256;x-amz-date;x-amz-storage-class, \"\n         + \"Signature=090f1bb1db984221ae1a20c5d12a82820a0d74b4be85f20daa1431604f41df08\";\n\n   private static final String LIST_BUCKET_RESULT = \"AWS4-HMAC-SHA256 \"\n         + \"Credential=AKIAPAEBI3QI4EXAMPLE/20150203/cn-north-1/s3/aws4_request, \"\n         + \"SignedHeaders=host;x-amz-content-sha256;x-amz-date, \"\n         + \"Signature=6cc5d0758e2599be7cb172fd57cefab2828201a2b4d372972a83dc304de93958\";\n\n   protected static final String BUCKET_NAME = \"test-bucket\";\n   private static final String OBJECT_NAME = \"ExampleObject.txt\";\n\n   @ConfiguresHttpApi\n   private static final class TestS3HttpApiModule extends S3HttpApiModule<S3Client> {\n      @Override\n      protected String provideTimeStamp(@TimeStamp Supplier<String> cache) {\n         return TIMESTAMP;\n      }\n\n      @Override\n      protected Supplier<Date> provideTimeStampCacheDate(\n            @Named(Constants.PROPERTY_SESSION_INTERVAL) long seconds,\n            @TimeStamp final Supplier<String> timestamp,\n            final DateService dateService) {\n         return Suppliers.ofInstance(dateService.rfc822DateParse(TIMESTAMP));\n      }\n   }\n\n   public static Injector injector(Credentials creds) {\n      return ContextBuilder.newBuilder(new S3ApiMetadata())\n            .credentialsSupplier(Suppliers.<Credentials>ofInstance(creds))\n            .modules(ImmutableList.<Module>of(new BaseRestApiTest.MockModule(), new NullLoggingModule(),\n                  new TestS3HttpApiModule()))\n            .buildInjector();\n   }\n\n   public RequestAuthorizeSignatureV4 filter(Credentials creds) {\n      return injector(creds).getInstance(RequestAuthorizeSignatureV4.class);\n   }\n\n   protected Credentials temporaryCredentials = new Credentials.Builder()\n         .identity(IDENTITY)\n         .credential(CREDENTIAL)\n         .build();\n\n\n   @Test\n   void testGetBucketLocationSignature() {\n      Invocation invocation = Invocation.create(method(S3Client.class, \"getBucketLocation\", String.class),\n            ImmutableList.<Object>of(BUCKET_NAME));\n\n      HttpRequest getBucketLocation = GeneratedHttpRequest.builder().method(\"GET\")\n            .invocation(invocation)\n            .endpoint(\"https://\" + BUCKET_NAME + \".s3.cn-north-1.amazonaws.com.cn/\")\n            .addHeader(HttpHeaders.HOST, BUCKET_NAME + \".s3.cn-north-1.amazonaws.com.cn\")\n            .addQueryParam(\"location\", \"\")\n            .build();\n      HttpRequest filtered = filter(temporaryCredentials).filter(getBucketLocation);\n      assertEquals(filtered.getFirstHeaderOrNull(\"Authorization\"), GET_BUCKET_LOCATION_SIGNATURE_RESULT);\n   }\n\n   @Test\n   void testGetObjectSignature() {\n      Invocation invocation = Invocation.create(method(S3Client.class, \"getObject\", String.class,\n                  String.class, GetOptions[].class),\n            ImmutableList.<Object>of(BUCKET_NAME, OBJECT_NAME, new GetOptions[0]));\n\n      HttpRequest getObject = GeneratedHttpRequest.builder().method(\"GET\")\n            .invocation(invocation)\n            .endpoint(\"https://\" + BUCKET_NAME + \".s3.cn-north-1.amazonaws.com.cn/\" + OBJECT_NAME)\n            .addHeader(HttpHeaders.HOST, BUCKET_NAME + \".s3.cn-north-1.amazonaws.com.cn\")\n            .build();\n\n      HttpRequest filtered = filter(temporaryCredentials).filter(getObject);\n      assertEquals(filtered.getFirstHeaderOrNull(\"Authorization\"), GET_OBJECT_RESULT);\n\n   }\n\n   @Test\n   void testGetObjectACLSignature() {\n\n      Invocation invocation = Invocation.create(method(S3Client.class, \"getObjectACL\", String.class, String.class),\n            ImmutableList.<Object>of(BUCKET_NAME));\n\n      HttpRequest getObjectACL = GeneratedHttpRequest.builder().method(\"GET\")\n            .invocation(invocation)\n            .endpoint(\"https://\" + BUCKET_NAME + \".s3.cn-north-1.amazonaws.com.cn/\" + OBJECT_NAME)\n            .addHeader(HttpHeaders.HOST, BUCKET_NAME + \".s3.cn-north-1.amazonaws.com.cn\")\n            .addQueryParam(\"acl\", \"\")\n            .build();\n\n      HttpRequest filtered = filter(temporaryCredentials).filter(getObjectACL);\n      assertEquals(filtered.getFirstHeaderOrNull(\"Authorization\"), GET_OBJECT_ACL_RESULT);\n   }\n\n   @Test\n   void testPutObjectSignature() {\n      Invocation invocation = Invocation.create(method(S3Client.class, \"putObject\", String.class, S3Object.class,\n                  PutObjectOptions[].class),\n            ImmutableList.<Object>of(BUCKET_NAME));\n\n      Payload payload = Payloads.newStringPayload(PUT_OBJECT_CONTENT);\n      payload.getContentMetadata().setContentType(\"text/plain\");\n\n      HttpRequest putObject = GeneratedHttpRequest.builder().method(\"PUT\")\n            .invocation(invocation)\n            .endpoint(\"https://\" + BUCKET_NAME + \".s3.cn-north-1.amazonaws.com.cn/\" + OBJECT_NAME)\n            .addHeader(HttpHeaders.HOST, BUCKET_NAME + \".s3.cn-north-1.amazonaws.com.cn\")\n            .addHeader(\"x-amz-storage-class\", \"REDUCED_REDUNDANCY\")\n            .payload(payload)\n            .build();\n\n      HttpRequest filtered = filter(temporaryCredentials).filter(putObject);\n      assertEquals(filtered.getFirstHeaderOrNull(\"Authorization\"), PUT_OBJECT_RESULT);\n\n   }\n\n   // JCLOUDS-1401\n   @Test\n   void testListBucketFunnyCharactersSignature() {\n      Invocation invocation = Invocation.create(method(S3Client.class, \"listBucket\", String.class,\n                  ListBucketOptions[].class),\n            // Simulating ListBucketOptions.Builder.withPrefix(\"foo%2Fbar\") with manual endpoint:\n            ImmutableList.<Object>of(BUCKET_NAME, new ListBucketOptions[0]));\n\n      HttpRequest getObject = GeneratedHttpRequest.builder().method(\"GET\")\n            .invocation(invocation)\n            .endpoint(\"https://\" + BUCKET_NAME + \".s3.cn-north-1.amazonaws.com.cn/?delimiter=/&prefix=foo%252Fbar\")\n            .addHeader(HttpHeaders.HOST, BUCKET_NAME + \".s3.cn-north-1.amazonaws.com.cn\")\n            .build();\n\n      HttpRequest filtered = filter(temporaryCredentials).filter(getObject);\n      assertEquals(filtered.getFirstHeaderOrNull(\"Authorization\"), LIST_BUCKET_RESULT);\n   }\n\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/filters/RequestAuthorizeSignatureWithSessionCredentialsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.filters;\n\nimport static org.jclouds.reflect.Reflection2.method;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.aws.domain.SessionCredentials;\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.logging.config.NullLoggingModule;\nimport org.jclouds.reflect.Invocation;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.internal.BaseRestApiTest.MockModule;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.jclouds.s3.S3Client;\nimport org.jclouds.s3.config.S3HttpApiModule;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableList;\nimport com.google.inject.Injector;\nimport com.google.inject.Module;\n\n/**\n * Tests behavior of {@code RequestAuthorizeSignature}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"RequestAuthorizeSignatureWithSessionCredentialsTest\")\npublic class RequestAuthorizeSignatureWithSessionCredentialsTest {\n   public static Injector injector(Credentials creds) {\n      return ContextBuilder.newBuilder(\"s3\")\n            .credentialsSupplier(Suppliers.<Credentials> ofInstance(creds))\n            .modules(ImmutableList.<Module> of(new MockModule(), new NullLoggingModule(), new TestS3HttpApiModule())).buildInjector();\n   }\n\n   @ConfiguresHttpApi\n   private static final class TestS3HttpApiModule extends S3HttpApiModule<S3Client> {\n\n      @Override\n      protected String provideTimeStamp(@TimeStamp Supplier<String> cache) {\n         return \"2009-11-08T15:54:08.897Z\";\n      }\n   }\n   \n   public static RequestAuthorizeSignature filter(Credentials creds) {\n      return injector(creds).getInstance(RequestAuthorizeSignature.class);\n   }\n\n   SessionCredentials temporaryCredentials =  SessionCredentials.builder()\n      .accessKeyId(\"AKIAIOSFODNN7EXAMPLE\")\n      .secretAccessKey(\"wJalrXUtnFEMI/K7MDENG/bPxRfiCYzEXAMPLEKEY\")\n      .sessionToken(\"AQoEXAMPLEH4aoAH0gNCAPyJxz4BlCFFxWNE1OPTgk5TthT\")\n      .expiration(new SimpleDateFormatDateService().iso8601DateParse(\"2011-07-11T19:55:29.611Z\")).build();\n\n   Invocation invocation = Invocation.create(method(S3Client.class, \"bucketExists\", String.class),\n                                             ImmutableList.<Object> of(\"foo\"));\n\n   HttpRequest bucketFooExists = GeneratedHttpRequest.builder().method(\"GET\")\n                                            .invocation(invocation)\n                                            .endpoint(\"https://s3.amazonaws.com/foo?max-keys=0\")\n                                            .build();\n\n   @Test\n   void testAddsSecurityToken() {\n      HttpRequest filtered = filter(temporaryCredentials).filter(bucketFooExists);\n      assertEquals(filtered.getFirstHeaderOrNull(\"Authorization\"),\n            \"AWS AKIAIOSFODNN7EXAMPLE:sbAAy3Gh/sD1zwO7Ut75YJFCs4U=\");\n      assertEquals(filtered.getFirstHeaderOrNull(\"x-amz-security-token\"), temporaryCredentials.getSessionToken());\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/functions/AssignCorrectHostnameForBucketTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\nimport java.util.Map;\n\nimport org.jclouds.location.Provider;\nimport org.jclouds.location.Region;\nimport org.jclouds.location.functions.RegionToEndpointOrProviderIfNull;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Functions;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.inject.Binder;\nimport com.google.inject.Guice;\nimport com.google.inject.Module;\nimport com.google.inject.Provides;\n\n@Test\npublic class AssignCorrectHostnameForBucketTest {\n   static final RegionToEndpointOrProviderIfNull REGION_TO_ENDPOINT = Guice.createInjector(new Module() {\n      @Override public void configure(Binder binder) {\n         binder.bindConstant().annotatedWith(Provider.class).to(\"s3\");\n      }\n\n      @Provides @Provider Supplier<URI> defaultUri() {\n         return Suppliers.ofInstance(URI.create(\"https://s3.amazonaws.com\"));\n      }\n\n      @Provides @Region Supplier<Map<String, Supplier<URI>>> regionToEndpoints() {\n         Map<String, Supplier<URI>> regionToEndpoint = ImmutableMap.of( //\n               \"us-standard\", defaultUri(), //\n               \"us-west-1\", Suppliers.ofInstance(URI.create(\"https://s3-us-west-1.amazonaws.com\")));\n         return Suppliers.ofInstance(regionToEndpoint);\n      }\n   }).getInstance(RegionToEndpointOrProviderIfNull.class);\n\n   public void testWhenNoBucketRegionMappingInCache() {\n      AssignCorrectHostnameForBucket fn = new AssignCorrectHostnameForBucket(REGION_TO_ENDPOINT,\n            Functions.forMap(ImmutableMap.of(\"bucket\", Optional.<String>absent())));\n\n      assertEquals(fn.apply(\"bucket\"), URI.create(\"https://s3.amazonaws.com\"));\n   }\n\n   public void testWhenBucketRegionMappingInCache() {\n      AssignCorrectHostnameForBucket fn = new AssignCorrectHostnameForBucket(REGION_TO_ENDPOINT,\n            Functions.forMap(ImmutableMap.of(\"bucket\", Optional.of(\"us-west-1\"))));\n\n      assertEquals(fn.apply(\"bucket\"), URI.create(\"https://s3-us-west-1.amazonaws.com\"));\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/functions/DefaultEndpointThenInvalidateRegionTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.functions;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.jclouds.s3.functions.AssignCorrectHostnameForBucketTest.REGION_TO_ENDPOINT;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Functions;\nimport com.google.common.base.Optional;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableMap;\n\npublic class DefaultEndpointThenInvalidateRegionTest {\n   @SuppressWarnings(\"unchecked\")\n   @Test\n   public void testInvalidate() throws Exception {\n      LoadingCache<String, Optional<String>> bucketToRegionCache = createMock(LoadingCache.class);\n\n      bucketToRegionCache.invalidate(\"mybucket\");\n      replay(bucketToRegionCache);\n\n      AssignCorrectHostnameForBucket delegate = new AssignCorrectHostnameForBucket(REGION_TO_ENDPOINT,\n            Functions.forMap(ImmutableMap.of(\"mybucket\", Optional.of(\"us-west-1\"))));\n\n      new DefaultEndpointThenInvalidateRegion(delegate, bucketToRegionCache).apply(\"mybucket\");\n      verify(bucketToRegionCache);\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/functions/ETagFromHttpResponseViaRegexTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ReturnStringIf2xx;\nimport org.jclouds.io.Payloads;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code ETagFromHttpResponseViaRegex}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"ETagFromHttpResponseViaRegexTest\")\npublic class ETagFromHttpResponseViaRegexTest {\n\n   @Test\n   public void test() {\n\n      HttpResponse response = HttpResponse.builder().statusCode(200).payload(\n               Payloads.newInputStreamPayload(getClass().getResourceAsStream(\"/complete-multipart-upload.xml\")))\n               .build();\n      ETagFromHttpResponseViaRegex parser = new ETagFromHttpResponseViaRegex(new ReturnStringIf2xx());\n\n      assertEquals(parser.apply(response), \"\\\"3858f62230ac3c915f300c664312c11f-9\\\"\");\n   }\n\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/functions/GetRegionForBucketTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.functions;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.concurrent.ExecutionException;\n\nimport org.testng.annotations.DataProvider;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.cache.CacheLoader.InvalidCacheLoadException;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.util.concurrent.UncheckedExecutionException;\n\n@Test(testName = \"GetRegionForBucketTest\")\npublic class GetRegionForBucketTest {\n\n   @SuppressWarnings(\"unchecked\")\n   @Test\n   void test() throws Exception {\n      LoadingCache<String, Optional<String>> bucketToRegionCache = createMock(LoadingCache.class);\n\n      expect(bucketToRegionCache.get(\"bucket\")).andReturn(Optional.of(\"us-east-1\"));\n\n      replay(bucketToRegionCache);\n      GetRegionForBucket fn = new GetRegionForBucket(bucketToRegionCache);\n\n      assertEquals(fn.apply(\"bucket\"), Optional.of(\"us-east-1\"));\n\n      verify(bucketToRegionCache);\n\n   }\n\n   @SuppressWarnings(\"serial\")\n   @DataProvider(name = \"exceptions\")\n   public Object[][] createExceptions() {\n      return new Object[][] { { new ExecutionException() {\n      } }, { new UncheckedExecutionException() {\n      } }, { new InvalidCacheLoadException(\"foo\") } };\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Test(dataProvider = \"exceptions\")\n   void testGracefulOnException(Exception exception) throws Exception {\n      LoadingCache<String, Optional<String>> bucketToRegionCache = createMock(LoadingCache.class);\n\n      expect(bucketToRegionCache.get(\"bucket\")).andThrow(exception);\n\n      replay(bucketToRegionCache);\n      GetRegionForBucket fn = new GetRegionForBucket(bucketToRegionCache);\n\n      assertEquals(fn.apply(\"bucket\"), Optional.absent());\n\n      verify(bucketToRegionCache);\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/functions/ParseObjectMetadataFromHeadersTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.functions;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.jclouds.aws.reference.AWSConstants.PROPERTY_HEADER_TAG;\nimport static org.jclouds.blobstore.reference.BlobStoreConstants.PROPERTY_USER_METADATA_PREFIX;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Date;\nimport java.util.Map;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rest.RequestSigner;\nimport org.jclouds.s3.domain.MutableObjectMetadata;\nimport org.jclouds.s3.domain.ObjectMetadata.StorageClass;\nimport org.jclouds.s3.domain.internal.MutableObjectMetadataImpl;\nimport org.jclouds.s3.reference.S3Headers;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.hash.HashCode;\nimport com.google.common.net.HttpHeaders;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.name.Names;\n\n@Test(testName = \"s3.ParseObjectMetadataFromHeadersTest\")\npublic class ParseObjectMetadataFromHeadersTest {\n\n   @Test\n   void testNormalParsesETagIntoMD5AndMetadataHeaders() throws Exception {\n      HttpResponse http = HttpResponse.builder().statusCode(400).message(\"boa\").payload(\"\")\n                                      .addHeader(S3Headers.USER_METADATA_PREFIX + \"foo\", \"bar\")\n                                      .addHeader(HttpHeaders.LAST_MODIFIED, lastModified)\n                                      .addHeader(HttpHeaders.ETAG, \"\\\"00000000000000000000000000000000\\\"\")\n                                      .addHeader(HttpHeaders.CACHE_CONTROL, \"cacheControl\").build();\n      http.getPayload().getContentMetadata().setContentLength(1025L);\n      http.getPayload().getContentMetadata().setContentDisposition(\"contentDisposition\");\n      http.getPayload().getContentMetadata().setContentEncoding(\"encoding\");\n      http.getPayload().getContentMetadata().setContentType(MediaType.APPLICATION_OCTET_STREAM);\n\n      MutableObjectMetadata response = parser.apply(http);\n\n      HashCode hashCode = HashCode.fromBytes(new byte[16]);\n      MutableObjectMetadataImpl expects = new MutableObjectMetadataImpl();\n      expects.setCacheControl(\"cacheControl\");\n      expects.getContentMetadata().setContentDisposition(\"contentDisposition\");\n      expects.getContentMetadata().setContentEncoding(\"encoding\");\n      expects.getContentMetadata().setContentType(MediaType.APPLICATION_OCTET_STREAM);\n      expects.getContentMetadata().setContentLength(1025L);\n      expects.getContentMetadata().setContentMD5(hashCode);\n      expects.setETag(\"\\\"abcd\\\"\");\n      expects.setKey(\"key\");\n      expects.setLastModified(now);\n      expects.setOwner(null);\n      expects.setStorageClass(StorageClass.STANDARD);\n      expects.setUserMetadata(userMetadata);\n      assertEquals(response, expects);\n   }\n\n   @Test\n   void testMultipartDoesntAttemptToParseETagIntoMD5() throws Exception {\n      HttpResponse http = HttpResponse.builder().statusCode(400).message(\"boa\").payload(\"\")\n                                      .addHeader(S3Headers.USER_METADATA_PREFIX + \"foo\", \"bar\")\n                                      .addHeader(HttpHeaders.LAST_MODIFIED, lastModified)\n                                      .addHeader(HttpHeaders.ETAG, \"\\\"abcd-1\\\"\")\n                                      .addHeader(HttpHeaders.CACHE_CONTROL, \"cacheControl\").build();\n      http.getPayload().getContentMetadata().setContentLength(1025L);\n      http.getPayload().getContentMetadata().setContentDisposition(\"contentDisposition\");\n      http.getPayload().getContentMetadata().setContentEncoding(\"encoding\");\n      http.getPayload().getContentMetadata().setContentType(MediaType.APPLICATION_OCTET_STREAM);\n\n      MutableObjectMetadata response = parser.apply(http);\n\n      MutableObjectMetadataImpl expects = new MutableObjectMetadataImpl();\n      expects.setCacheControl(\"cacheControl\");\n      expects.getContentMetadata().setContentDisposition(\"contentDisposition\");\n      expects.getContentMetadata().setContentEncoding(\"encoding\");\n      expects.getContentMetadata().setContentType(MediaType.APPLICATION_OCTET_STREAM);\n      expects.getContentMetadata().setContentLength(1025L);\n      expects.setETag(\"\\\"abcd-1\\\"\");\n      expects.setKey(\"key\");\n      expects.setLastModified(now);\n      expects.setOwner(null);\n      expects.setStorageClass(StorageClass.STANDARD);\n      expects.setUserMetadata(userMetadata);\n      assertEquals(response, expects);\n   }\n\n   @Test\n   void testAmzEtagStillParsesToMD5AndDoesntMistakeAmzEtagForUserMetadata() throws Exception {\n      HttpResponse http = HttpResponse.builder().statusCode(400).message(\"boa\").payload(\"\")\n                                      .addHeader(S3Headers.USER_METADATA_PREFIX + \"foo\", \"bar\")\n                                      .addHeader(HttpHeaders.LAST_MODIFIED, lastModified)\n                                      .addHeader(S3Headers.AMZ_ETAG, \"\\\"00000000000000000000000000000000\\\"\")\n                                      .addHeader(HttpHeaders.CACHE_CONTROL, \"cacheControl\").build();\n      \n      http.getPayload().getContentMetadata().setContentLength(1025L);\n      http.getPayload().getContentMetadata().setContentDisposition(\"contentDisposition\");\n      http.getPayload().getContentMetadata().setContentEncoding(\"encoding\");\n      http.getPayload().getContentMetadata().setContentType(MediaType.APPLICATION_OCTET_STREAM);\n\n      MutableObjectMetadata response = parser.apply(http);\n\n      HashCode hashCode = HashCode.fromBytes(new byte[16]);\n      MutableObjectMetadataImpl expects = new MutableObjectMetadataImpl();\n      expects.setCacheControl(\"cacheControl\");\n      expects.getContentMetadata().setContentDisposition(\"contentDisposition\");\n      expects.getContentMetadata().setContentEncoding(\"encoding\");\n      expects.getContentMetadata().setContentMD5(hashCode);\n      expects.getContentMetadata().setContentType(MediaType.APPLICATION_OCTET_STREAM);\n      expects.getContentMetadata().setContentLength(1025L);\n      expects.setETag(\"\\\"abcd\\\"\");\n      expects.setKey(\"key\");\n      expects.setLastModified(now);\n      expects.setOwner(null);\n      expects.setStorageClass(StorageClass.STANDARD);\n      expects.setUserMetadata(userMetadata);\n\n      assertEquals(response, expects);\n   }\n\n   String lastModified = new SimpleDateFormatDateService().rfc822DateFormat(new Date());\n   // rfc isn't accurate down to nanos, so we'll parse back to ensure tests pass\n   Date now = new SimpleDateFormatDateService().rfc822DateParse(lastModified);\n\n   Map<String, String> userMetadata = ImmutableMap.of(\"foo\", \"bar\");\n   ParseObjectMetadataFromHeaders parser;\n\n   @BeforeTest\n   void setUp() {\n      parser = Guice.createInjector(new AbstractModule() {\n\n         @Override\n         protected void configure() {\n            bind(RequestSigner.class).toInstance(createMock(RequestSigner.class));\n            bindConstant().annotatedWith(Names.named(PROPERTY_HEADER_TAG)).to(S3Headers.DEFAULT_AMAZON_HEADERTAG);\n            bindConstant().annotatedWith(Names.named(PROPERTY_USER_METADATA_PREFIX)).to(S3Headers.USER_METADATA_PREFIX);\n\n         }\n\n      }).getInstance(ParseObjectMetadataFromHeaders.class).setKey(\"key\");\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/functions/UploadIdFromHttpResponseViaRegexTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ReturnStringIf2xx;\nimport org.jclouds.io.Payloads;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code UploadIdFromHttpResponseViaRegex}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"UploadIdFromHttpResponseViaRegexTest\")\npublic class UploadIdFromHttpResponseViaRegexTest {\n\n   @Test\n   public void test() {\n\n      HttpResponse response = HttpResponse.builder().statusCode(200).payload(\n               Payloads.newInputStreamPayload(getClass().getResourceAsStream(\"/initiate-multipart-upload.xml\")))\n               .build();\n      UploadIdFromHttpResponseViaRegex parser = new UploadIdFromHttpResponseViaRegex(new ReturnStringIf2xx());\n\n      assertEquals(parser.apply(response), \"VXBsb2FkIElEIGZvciA2aWWpbmcncyBteS1tb3ZpZS5tMnRzIHVwbG9hZA\");\n   }\n\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/handlers/ParseS3ErrorFromXmlContentTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.handlers;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.reportMatcher;\nimport static org.easymock.EasyMock.verify;\nimport static org.jclouds.aws.reference.AWSConstants.PROPERTY_HEADER_TAG;\nimport static org.jclouds.s3.reference.S3Constants.PROPERTY_S3_SERVICE_PATH;\nimport static org.jclouds.s3.reference.S3Constants.PROPERTY_S3_VIRTUAL_HOST_BUCKETS;\n\nimport java.net.URI;\n\nimport org.easymock.IArgumentMatcher;\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.blobstore.ContainerNotFoundException;\nimport org.jclouds.blobstore.KeyNotFoundException;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.config.SaxParserModule;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.rest.RequestSigner;\nimport org.jclouds.s3.reference.S3Headers;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.name.Names;\n\n@Test(groups = { \"unit\" })\npublic class ParseS3ErrorFromXmlContentTest {\n   private static final String SERVICE_PATH = \"/services/Walrus\";\n\n   @Test\n   public void test404ContainerNotFoundExceptionPath() {\n      assertCodeMakes(\"GET\", URI\n               .create(\"http://partnercloud.eucalyptus.com:8773/services/Walrus/adriancole-blobstore58/\"), 404,\n               \"HTTP/1.1 404 Not Found\", false, \"<Error><Code>Monster.NotFound</Code></Error>\",\n               ContainerNotFoundException.class);\n   }\n\n   @Test\n   public void test404KeyNotFoundExceptionPath() {\n      assertCodeMakes(\"GET\", URI\n               .create(\"http://partnercloud.eucalyptus.com:8773/services/Walrus/adriancole-blobstore58/apples\"), 404,\n               \"HTTP/1.1 404 Not Found\", false, \"<Error><Code>Monster.NotFound</Code></Error>\",\n               KeyNotFoundException.class);\n   }\n\n   private void assertCodeMakes(String method, URI uri, int statusCode, String message, final boolean virtualHost,\n            String content, Class<? extends Exception> expected) {\n\n      ApiMetadata apiMetadata = createMock(ApiMetadata.class);\n      expect(apiMetadata.getDefaultEndpoint()).andReturn(Optional.of(\"http://localhost\")).atLeastOnce();\n\n      final ProviderMetadata providerMetadata = createMock(ProviderMetadata.class);\n      expect(providerMetadata.getApiMetadata()).andReturn(apiMetadata).atLeastOnce();\n\n      ParseS3ErrorFromXmlContent function = Guice.createInjector(new SaxParserModule(), new AbstractModule() {\n\n         @Override\n         protected void configure() {\n            bind(RequestSigner.class).toInstance(createMock(RequestSigner.class));\n            bind(ProviderMetadata.class).toInstance(providerMetadata);\n            bindConstant().annotatedWith(Names.named(PROPERTY_HEADER_TAG)).to(S3Headers.DEFAULT_AMAZON_HEADERTAG);\n            bindConstant().annotatedWith(Names.named(PROPERTY_S3_SERVICE_PATH)).to(SERVICE_PATH);\n            bindConstant().annotatedWith(Names.named(PROPERTY_S3_VIRTUAL_HOST_BUCKETS)).to(virtualHost);\n         }\n\n      }).getInstance(ParseS3ErrorFromXmlContent.class);\n\n      HttpCommand command = createMock(HttpCommand.class);\n      HttpRequest request = HttpRequest.builder().method(method).endpoint(uri).build();\n      HttpResponse response = HttpResponse.builder().statusCode(statusCode).message(message).payload(content).build();\n      response.getPayload().getContentMetadata().setContentType(\"application/xml\");\n\n      expect(command.getCurrentRequest()).andReturn(request).atLeastOnce();\n      command.setException(classEq(expected));\n\n      replay(apiMetadata, providerMetadata, command);\n\n      function.handleError(command, response);\n\n      verify(command);\n   }\n\n   public static Exception classEq(final Class<? extends Exception> in) {\n      reportMatcher(new IArgumentMatcher() {\n\n         @Override\n         public void appendTo(StringBuffer buffer) {\n            buffer.append(\"classEq(\");\n            buffer.append(in);\n            buffer.append(\")\");\n         }\n\n         @Override\n         public boolean matches(Object arg) {\n            return arg.getClass() == in;\n         }\n\n      });\n      return null;\n   }\n\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/internal/BaseS3ClientExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.internal;\n\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.internal.BaseRestApiExpectTest;\nimport org.jclouds.s3.S3ApiMetadata;\nimport org.jclouds.s3.S3Client;\nimport org.jclouds.s3.config.S3HttpApiModule;\n\nimport com.google.common.base.Supplier;\nimport com.google.inject.Module;\n\npublic abstract class BaseS3ClientExpectTest extends BaseRestApiExpectTest<S3Client> {\n\n   protected static final String CONSTANT_DATE = \"2009-11-08T15:54:08.897Z\";\n\n   @ConfiguresHttpApi\n   private static final class TestS3HttpApiModule extends S3HttpApiModule<S3Client> {\n\n      @Override\n      protected String provideTimeStamp(@TimeStamp Supplier<String> cache) {\n         return CONSTANT_DATE;\n      }\n   }\n\n   @Override\n   protected Module createModule() {\n      return new TestS3HttpApiModule();\n   }\n   \n   @Override\n   public S3ApiMetadata createApiMetadata() {\n      return new S3ApiMetadata();\n   }\n\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/internal/BaseS3ClientTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.internal;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.internal.BaseRestAnnotationProcessingTest;\nimport org.jclouds.s3.S3ApiMetadata;\nimport org.jclouds.s3.S3Client;\nimport org.jclouds.s3.blobstore.functions.BlobToObject;\nimport org.jclouds.s3.filters.RequestAuthorizeSignature;\nimport org.jclouds.s3.filters.RequestAuthorizeSignatureV2;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic abstract class BaseS3ClientTest<T extends S3Client> extends BaseRestAnnotationProcessingTest<T> {\n\n   protected BlobToObject blobToS3Object;\n   protected RequestAuthorizeSignature filter;\n\n   @Override\n   protected void checkFilters(HttpRequest request) {\n      assertEquals(request.getFilters().size(), 1);\n      assertEquals(request.getFilters().get(0).getClass(), RequestAuthorizeSignature.class);\n   }\n\n\n   @BeforeClass\n   @Override\n   protected void setupFactory() throws IOException {\n      super.setupFactory();\n      blobToS3Object = injector.getInstance(BlobToObject.class);\n      filter = injector.getInstance(RequestAuthorizeSignatureV2.class);\n   }\n\n   public BaseS3ClientTest() {\n      super();\n   }\n\n   @Override\n   public S3ApiMetadata createApiMetadata() {\n      return new S3ApiMetadata();\n   }\n\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/options/CopyObjectOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.options;\n\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static org.jclouds.s3.options.CopyObjectOptions.Builder.ifSourceETagDoesntMatch;\nimport static org.jclouds.s3.options.CopyObjectOptions.Builder.ifSourceETagMatches;\nimport static org.jclouds.s3.options.CopyObjectOptions.Builder.ifSourceModifiedSince;\nimport static org.jclouds.s3.options.CopyObjectOptions.Builder.ifSourceUnmodifiedSince;\nimport static org.jclouds.s3.options.CopyObjectOptions.Builder.overrideAcl;\nimport static org.jclouds.s3.options.CopyObjectOptions.Builder.overrideMetadataWith;\nimport static org.jclouds.s3.reference.S3Headers.CANNED_ACL;\nimport static org.jclouds.s3.reference.S3Headers.COPY_SOURCE_IF_MODIFIED_SINCE;\nimport static org.jclouds.s3.reference.S3Headers.COPY_SOURCE_IF_NO_MATCH;\nimport static org.jclouds.s3.reference.S3Headers.DEFAULT_AMAZON_HEADERTAG;\nimport static org.jclouds.s3.reference.S3Headers.METADATA_DIRECTIVE;\nimport static org.jclouds.s3.reference.S3Headers.USER_METADATA_PREFIX;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Date;\nimport java.util.Map;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.s3.domain.CannedAccessPolicy;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Multimap;\n\n/**\n * Tests possible uses of CopyObjectOptions and CopyObjectOptions.Builder.*\n */\n@Test(groups = \"unit\")\npublic class CopyObjectOptionsTest {\n\n   private String etag;\n   private Date now;\n   private String nowExpected;\n   private Map<String, String> goodMeta;\n\n   @BeforeTest\n   void setUp() {\n      goodMeta = ImmutableMap.of(USER_METADATA_PREFIX + \"adrian\", \"foo\");\n      Date date = new Date();\n      nowExpected = new SimpleDateFormatDateService().rfc822DateFormat(date);\n      now = new SimpleDateFormatDateService().rfc822DateParse(nowExpected);\n      etag = \"mama\";\n   }\n\n   @Test\n   void testGoodMetaStatic() {\n      CopyObjectOptions options = overrideMetadataWith(goodMeta);\n      options.setMetadataPrefix(USER_METADATA_PREFIX);\n      options.setHeaderTag(DEFAULT_AMAZON_HEADERTAG);\n      assertGoodMeta(options);\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testMetaNPE() {\n      overrideMetadataWith(null);\n   }\n\n   private void assertGoodMeta(CopyObjectOptions options) {\n      assert options != null;\n      assert options.getMetadata() != null;\n      Multimap<String, String> headers = options.buildRequestHeaders();\n      assertEquals(headers.size(), 2);\n      assertEquals(headers.get(METADATA_DIRECTIVE).iterator().next(), \"REPLACE\");\n      assertEquals(options.getMetadata().size(), 1);\n      assertEquals(headers.get(USER_METADATA_PREFIX + \"adrian\").iterator().next(), \"foo\");\n      assertEquals(options.getMetadata().get(USER_METADATA_PREFIX + \"adrian\"), \"foo\");\n   }\n\n   @Test\n   void testGoodMeta() {\n      CopyObjectOptions options = new CopyObjectOptions();\n      options.setHeaderTag(DEFAULT_AMAZON_HEADERTAG);\n      options.setMetadataPrefix(USER_METADATA_PREFIX);\n      options.overrideMetadataWith(goodMeta);\n      assertGoodMeta(options);\n   }\n\n   @Test\n   public void testIfModifiedSince() {\n      CopyObjectOptions options = new CopyObjectOptions();\n      options.ifSourceModifiedSince(now);\n      assertEquals(options.getIfModifiedSince(), nowExpected);\n   }\n\n   @Test\n   public void testNullIfModifiedSince() {\n      CopyObjectOptions options = new CopyObjectOptions();\n      assertNull(options.getIfModifiedSince());\n   }\n\n   @Test\n   public void testIfModifiedSinceStatic() {\n      CopyObjectOptions options = ifSourceModifiedSince(now);\n      assertEquals(options.getIfModifiedSince(), nowExpected);\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testIfModifiedSinceNPE() {\n      ifSourceModifiedSince(null);\n   }\n\n   @Test\n   public void testIfUnmodifiedSince() {\n      CopyObjectOptions options = new CopyObjectOptions();\n      options.ifSourceUnmodifiedSince(now);\n      isNowExpected(options);\n   }\n\n   @Test\n   public void testNullIfUnmodifiedSince() {\n      CopyObjectOptions options = new CopyObjectOptions();\n      assertNull(options.getIfUnmodifiedSince());\n   }\n\n   @Test\n   public void testIfUnmodifiedSinceStatic() {\n      CopyObjectOptions options = ifSourceUnmodifiedSince(now);\n      isNowExpected(options);\n   }\n\n   private void isNowExpected(CopyObjectOptions options) {\n      assertEquals(options.getIfUnmodifiedSince(), nowExpected);\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testIfUnmodifiedSinceNPE() {\n      ifSourceUnmodifiedSince(null);\n   }\n\n   @Test\n   public void testIfETagMatches() {\n      CopyObjectOptions options = new CopyObjectOptions();\n      options.ifSourceETagMatches(etag);\n      matchesHex(options.getIfMatch());\n   }\n\n   @Test\n   public void testNullIfETagMatches() {\n      CopyObjectOptions options = new CopyObjectOptions();\n      assertNull(options.getIfMatch());\n   }\n\n   @Test\n   public void testIfETagMatchesStatic() {\n      CopyObjectOptions options = ifSourceETagMatches(etag);\n      matchesHex(options.getIfMatch());\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testIfETagMatchesNPE() {\n      ifSourceETagMatches(null);\n   }\n\n   @Test\n   public void testIfETagDoesntMatch() {\n      CopyObjectOptions options = new CopyObjectOptions();\n      options.ifSourceETagDoesntMatch(etag);\n      matchesHex(options.getIfNoneMatch());\n   }\n\n   @Test\n   public void testNullIfETagDoesntMatch() {\n      CopyObjectOptions options = new CopyObjectOptions();\n      assertNull(options.getIfNoneMatch());\n   }\n\n   @Test\n   public void testIfETagDoesntMatchStatic() {\n      CopyObjectOptions options = ifSourceETagDoesntMatch(etag);\n      matchesHex(options.getIfNoneMatch());\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testIfETagDoesntMatchNPE() {\n      ifSourceETagDoesntMatch(null);\n   }\n\n   private void matchesHex(String match) {\n      String expected = \"\\\"\" + etag + \"\\\"\";\n      assertEquals(match, expected);\n   }\n\n   @Test(expectedExceptions = IllegalStateException.class)\n   public void testIfUnmodifiedAfterModified() {\n      ifSourceModifiedSince(now).ifSourceUnmodifiedSince(now);\n\n   }\n\n   public void testIfUnmodifiedAfterETagMatches() {\n      ifSourceETagMatches(etag).ifSourceUnmodifiedSince(now);\n\n   }\n\n   @Test(expectedExceptions = IllegalStateException.class)\n   public void testIfUnmodifiedAfterETagDoesntMatch() {\n      ifSourceETagDoesntMatch(etag).ifSourceUnmodifiedSince(now);\n   }\n\n   @Test(expectedExceptions = IllegalStateException.class)\n   public void testIfModifiedAfterUnmodified() {\n      ifSourceUnmodifiedSince(now).ifSourceModifiedSince(now);\n\n   }\n\n   @Test(expectedExceptions = IllegalStateException.class)\n   public void testIfModifiedAfterETagMatches() {\n      ifSourceETagMatches(etag).ifSourceModifiedSince(now);\n\n   }\n\n   public void testIfModifiedAfterETagDoesntMatch() {\n      ifSourceETagDoesntMatch(etag).ifSourceModifiedSince(now);\n   }\n\n   @Test(expectedExceptions = IllegalStateException.class)\n   public void testETagMatchesAfterIfModified() {\n      ifSourceModifiedSince(now).ifSourceETagMatches(etag);\n\n   }\n\n   public void testETagMatchesAfterIfUnmodified() {\n      ifSourceUnmodifiedSince(now).ifSourceETagMatches(etag);\n\n   }\n\n   @Test(expectedExceptions = IllegalStateException.class)\n   public void testETagMatchesAfterETagDoesntMatch() {\n      ifSourceETagDoesntMatch(etag).ifSourceETagMatches(etag);\n   }\n\n   public void testETagDoesntMatchAfterIfModified() {\n      ifSourceModifiedSince(now).ifSourceETagDoesntMatch(etag);\n\n   }\n\n   @Test(expectedExceptions = IllegalStateException.class)\n   public void testETagDoesntMatchAfterIfUnmodified() {\n      ifSourceUnmodifiedSince(now).ifSourceETagDoesntMatch(etag);\n\n   }\n\n   @Test(expectedExceptions = IllegalStateException.class)\n   public void testETagDoesntMatchAfterETagMatches() {\n      ifSourceETagMatches(etag).ifSourceETagDoesntMatch(etag);\n   }\n\n   @Test\n   void testBuildRequestHeadersWhenMetadataNull() {\n      CopyObjectOptions options = new CopyObjectOptions();\n      options.setHeaderTag(DEFAULT_AMAZON_HEADERTAG);\n\n      options.setMetadataPrefix(USER_METADATA_PREFIX);\n      assert options.buildRequestHeaders() != null;\n   }\n\n   @Test\n   void testBuildRequestHeaders() {\n      CopyObjectOptions options = ifSourceModifiedSince(now).ifSourceETagDoesntMatch(etag).overrideMetadataWith(\n               goodMeta);\n      options.setHeaderTag(DEFAULT_AMAZON_HEADERTAG);\n\n      options.setMetadataPrefix(USER_METADATA_PREFIX);\n\n      Multimap<String, String> headers = options.buildRequestHeaders();\n      assertEquals(getOnlyElement(headers.get(COPY_SOURCE_IF_MODIFIED_SINCE)), new SimpleDateFormatDateService()\n               .rfc822DateFormat(now));\n      assertEquals(getOnlyElement(headers.get(COPY_SOURCE_IF_NO_MATCH)), \"\\\"\" + etag + \"\\\"\");\n      for (String value : goodMeta.values())\n         assertTrue(headers.containsValue(value));\n\n   }\n\n   @Test\n   public void testAclDefault() {\n      CopyObjectOptions options = new CopyObjectOptions();\n      assertEquals(options.getAcl(), CannedAccessPolicy.PRIVATE);\n   }\n\n   @Test\n   public void testAclStatic() {\n      CopyObjectOptions options = overrideAcl(CannedAccessPolicy.AUTHENTICATED_READ);\n      assertEquals(options.getAcl(), CannedAccessPolicy.AUTHENTICATED_READ);\n   }\n\n   @Test\n   void testBuildRequestHeadersACL() {\n      CopyObjectOptions options = overrideAcl(CannedAccessPolicy.AUTHENTICATED_READ);\n      options.setHeaderTag(DEFAULT_AMAZON_HEADERTAG);\n\n      options.setMetadataPrefix(USER_METADATA_PREFIX);\n\n      Multimap<String, String> headers = options.buildRequestHeaders();\n\n      assertEquals(headers.get(CANNED_ACL).iterator().next(), CannedAccessPolicy.AUTHENTICATED_READ.toString());\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/options/ListBucketOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.options;\n\nimport static org.jclouds.s3.options.ListBucketOptions.Builder.afterMarker;\nimport static org.jclouds.s3.options.ListBucketOptions.Builder.delimiter;\nimport static org.jclouds.s3.options.ListBucketOptions.Builder.maxResults;\nimport static org.jclouds.s3.options.ListBucketOptions.Builder.withPrefix;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.http.options.HttpRequestOptions;\nimport org.jclouds.s3.reference.S3Constants;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Multimap;\n\n/**\n * Tests possible uses of ListBucketOptions and ListBucketOptions.Builder.*\n */\npublic class ListBucketOptionsTest {\n\n   @Test\n   public void testAssignability() {\n      assert HttpRequestOptions.class.isAssignableFrom(ListBucketOptions.class);\n      assert !String.class.isAssignableFrom(ListBucketOptions.class);\n   }\n\n   @Test\n   public void testPrefix() {\n      ListBucketOptions options = new ListBucketOptions();\n      options.withPrefix(\"test\");\n      assertEquals(options.buildQueryParameters().get(S3Constants.PREFIX),\n               ImmutableList.of(\"test\"));\n   }\n\n   @Test\n   public void testNoOptionsQueryString() {\n      HttpRequestOptions options = new ListBucketOptions();\n      assertEquals(options.buildQueryParameters().size(), 0);\n   }\n\n   @Test\n   public void testOneOptionQueryString() {\n      ListBucketOptions options = new ListBucketOptions();\n      options.withPrefix(\"test\");\n      Multimap<String, String> map = options.buildQueryParameters();\n      assertEquals(map.size(), 1);\n      assertEquals(map.get(\"prefix\"), ImmutableList.of(\"test\"));\n   }\n\n   @Test\n   public void testTwoOptionQueryString() {\n      ListBucketOptions options = new ListBucketOptions();\n      options.withPrefix(\"test\").maxResults(1);\n      Multimap<String, String> map = options.buildQueryParameters();\n      assertEquals(map.size(), 2);\n      assertEquals(map.get(\"prefix\"), ImmutableList.of(\"test\"));\n      assertEquals(map.get(\"max-keys\"), ImmutableList.of(\"1\"));\n   }\n\n   @Test\n   public void testPrefixAndDelimiterUrlEncodingQueryString() {\n      ListBucketOptions options = new ListBucketOptions();\n      options.withPrefix(\"/test\").delimiter(\"/\");\n      Multimap<String, String> map = options.buildQueryParameters();\n      assertEquals(map.size(), 2);\n      assertEquals(map.get(\"prefix\"), ImmutableList.of(\"/test\"));\n      assertEquals(map.get(\"delimiter\"), ImmutableList.of(\"/\"));\n\n   }\n\n   @Test\n   public void testNullPrefix() {\n      ListBucketOptions options = new ListBucketOptions();\n      assertEquals(options.buildQueryParameters().get(S3Constants.PREFIX), ImmutableList.of());\n   }\n\n   @Test\n   public void testPrefixStatic() {\n      ListBucketOptions options = withPrefix(\"test\");\n      assertEquals(options.buildQueryParameters().get(S3Constants.PREFIX),\n               ImmutableList.of(\"test\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testPrefixNPE() {\n      withPrefix(null);\n   }\n\n   @Test\n   public void testMarker() {\n      ListBucketOptions options = new ListBucketOptions();\n      options.afterMarker(\"test\");\n      assertEquals(options.buildQueryParameters().get(S3Constants.MARKER),\n               ImmutableList.of(\"test\"));\n   }\n\n   @Test\n   public void testNullMarker() {\n      ListBucketOptions options = new ListBucketOptions();\n      assertEquals(options.buildQueryParameters().get(S3Constants.MARKER), ImmutableList.of());\n   }\n\n   @Test\n   public void testMarkerStatic() {\n      ListBucketOptions options = afterMarker(\"test\");\n      assertEquals(options.buildQueryParameters().get(S3Constants.MARKER),\n               ImmutableList.of(\"test\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testMarkerNPE() {\n      afterMarker(null);\n   }\n\n   @Test\n   public void testMaxKeys() {\n      ListBucketOptions options = new ListBucketOptions();\n      options.maxResults(1000);\n      assertEquals(options.buildQueryParameters().get(S3Constants.MAX_KEYS),\n               ImmutableList.of(\"1000\"));\n   }\n\n   @Test\n   public void testNullMaxKeys() {\n      ListBucketOptions options = new ListBucketOptions();\n      assertEquals(options.buildQueryParameters().get(S3Constants.MAX_KEYS), ImmutableList.of());\n   }\n\n   @Test\n   public void testMaxKeysStatic() {\n      ListBucketOptions options = maxResults(1000);\n      assertEquals(options.buildQueryParameters().get(S3Constants.MAX_KEYS),\n               ImmutableList.of(\"1000\"));\n   }\n\n   @Test(expectedExceptions = IllegalStateException.class)\n   public void testMaxKeysNegative() {\n      maxResults(-1);\n   }\n\n   @Test\n   public void testDelimiter() {\n      ListBucketOptions options = new ListBucketOptions();\n      options.delimiter(\"test\");\n      assertEquals(options.buildQueryParameters().get(S3Constants.DELIMITER),\n               ImmutableList.of(\"test\"));\n   }\n\n   @Test\n   public void testNullDelimiter() {\n      ListBucketOptions options = new ListBucketOptions();\n      assertEquals(options.buildQueryParameters().get(S3Constants.DELIMITER),\n               ImmutableList.of());\n   }\n\n   @Test\n   public void testDelimiterStatic() {\n      ListBucketOptions options = delimiter(\"test\");\n      assertEquals(options.buildQueryParameters().get(S3Constants.DELIMITER),\n               ImmutableList.of(\"test\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testDelimiterNPE() {\n      delimiter(null);\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/options/PutBucketOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.options;\n\nimport static org.jclouds.s3.options.PutBucketOptions.Builder.withBucketAcl;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.s3.domain.CannedAccessPolicy;\nimport org.jclouds.s3.reference.S3Headers;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Multimap;\n\n/**\n * Tests possible uses of PutBucketOptions and PutBucketOptions.Builder.*\n */\n@Test(groups = \"unit\")\npublic class PutBucketOptionsTest {\n\n   @Test\n   public void testAclDefault() {\n      PutBucketOptions options = new PutBucketOptions();\n      assertEquals(options.getAcl(), CannedAccessPolicy.PRIVATE);\n   }\n\n   @Test\n   public void testAclStatic() {\n      PutBucketOptions options = withBucketAcl(CannedAccessPolicy.AUTHENTICATED_READ);\n      assertEquals(options.getAcl(), CannedAccessPolicy.AUTHENTICATED_READ);\n   }\n\n   @Test\n   void testBuildRequestHeaders() {\n\n      PutBucketOptions options = withBucketAcl(CannedAccessPolicy.AUTHENTICATED_READ);\n\n      options.setHeaderTag(S3Headers.DEFAULT_AMAZON_HEADERTAG);\n      Multimap<String, String> headers = options.buildRequestHeaders();\n      assertEquals(headers.get(S3Headers.CANNED_ACL).iterator().next(),\n               CannedAccessPolicy.AUTHENTICATED_READ.toString());\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/options/PutObjectOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.options;\n\nimport static org.jclouds.s3.options.PutObjectOptions.Builder.withAcl;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.s3.domain.CannedAccessPolicy;\nimport org.jclouds.s3.reference.S3Headers;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Multimap;\n\n/**\n * Tests possible uses of PutObjectOptions and PutObjectOptions.Builder.*\n */\n@Test(groups = \"unit\")\npublic class PutObjectOptionsTest {\n\n   @Test\n   public void testAclDefault() {\n      PutObjectOptions options = new PutObjectOptions();\n      assertEquals(options.getAcl(), CannedAccessPolicy.PRIVATE);\n   }\n\n   @Test\n   public void testAclStatic() {\n      PutObjectOptions options = withAcl(CannedAccessPolicy.AUTHENTICATED_READ);\n      assertEquals(options.getAcl(), CannedAccessPolicy.AUTHENTICATED_READ);\n   }\n\n   @Test\n   void testBuildRequestHeaders() {\n\n      PutObjectOptions options = withAcl(CannedAccessPolicy.AUTHENTICATED_READ);\n      options.setHeaderTag(S3Headers.DEFAULT_AMAZON_HEADERTAG);\n\n      Multimap<String, String> headers = options.buildRequestHeaders();\n      assertEquals(headers.get(S3Headers.CANNED_ACL).iterator().next(),\n               CannedAccessPolicy.AUTHENTICATED_READ.toString());\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/services/BucketsLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.services;\n\nimport static org.jclouds.s3.S3ClientLiveTest.TEST_ACL_EMAIL;\nimport static org.jclouds.s3.S3ClientLiveTest.TEST_ACL_ID;\nimport static org.jclouds.s3.domain.AccessControlList.GroupGranteeURI.ALL_USERS;\nimport static org.jclouds.s3.domain.AccessControlList.GroupGranteeURI.LOG_DELIVERY;\nimport static org.jclouds.s3.domain.AccessControlList.Permission.FULL_CONTROL;\nimport static org.jclouds.s3.domain.AccessControlList.Permission.READ;\nimport static org.jclouds.s3.domain.AccessControlList.Permission.READ_ACP;\nimport static org.jclouds.s3.domain.AccessControlList.Permission.WRITE;\nimport static org.jclouds.s3.domain.AccessControlList.Permission.WRITE_ACP;\nimport static org.jclouds.s3.domain.Payer.BUCKET_OWNER;\nimport static org.jclouds.s3.domain.Payer.REQUESTER;\nimport static org.jclouds.s3.options.ListBucketOptions.Builder.afterMarker;\nimport static org.jclouds.s3.options.ListBucketOptions.Builder.delimiter;\nimport static org.jclouds.s3.options.ListBucketOptions.Builder.maxResults;\nimport static org.jclouds.s3.options.ListBucketOptions.Builder.withPrefix;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.net.URL;\nimport java.util.Date;\nimport java.util.Set;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.TimeoutException;\n\nimport org.jclouds.blobstore.integration.internal.BaseBlobStoreIntegrationTest;\nimport org.jclouds.s3.S3Client;\nimport org.jclouds.s3.domain.AccessControlList;\nimport org.jclouds.s3.domain.AccessControlList.CanonicalUserGrantee;\nimport org.jclouds.s3.domain.AccessControlList.EmailAddressGrantee;\nimport org.jclouds.s3.domain.AccessControlList.Grant;\nimport org.jclouds.s3.domain.BucketLogging;\nimport org.jclouds.s3.domain.BucketMetadata;\nimport org.jclouds.s3.domain.CannedAccessPolicy;\nimport org.jclouds.s3.domain.ListBucketResponse;\nimport org.jclouds.s3.domain.S3Object;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Throwables;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\n\n@Test(groups = { \"integration\", \"live\" })\npublic class BucketsLiveTest extends BaseBlobStoreIntegrationTest {\n\n   public BucketsLiveTest() {\n      this.provider = \"s3\";\n      BaseBlobStoreIntegrationTest.SANITY_CHECK_RETURNED_BUCKET_NAME = true;\n   }\n\n   public S3Client getApi() {\n      return view.unwrapApi(S3Client.class);\n   }\n\n   /**\n    * this method overrides bucketName to ensure it isn't found\n    */\n   @Test(groups = { \"integration\", \"live\" })\n   public void deleteBucketIfEmptyNotFound() throws Exception {\n      assert getApi().deleteBucketIfEmpty(\"dbienf\");\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void deleteBucketIfEmptyButHasContents() throws Exception {\n      String bucketName = getContainerName();\n      try {\n         addBlobToContainer(bucketName, \"test\");\n         assert !getApi().deleteBucketIfEmpty(bucketName);\n      } finally {\n         returnContainer(bucketName);\n      }\n   }\n\n   public void testPrivateAclIsDefaultForBucket() throws InterruptedException, ExecutionException, TimeoutException,\n         IOException {\n      String bucketName = getContainerName();\n      try {\n         AccessControlList acl = getApi().getBucketACL(bucketName);\n         assertEquals(acl.getGrants().size(), 1);\n         assertNotNull(acl.getOwner());\n         String ownerId = acl.getOwner().getId();\n         assertTrue(acl.hasPermission(ownerId, FULL_CONTROL));\n      } finally {\n         returnContainer(bucketName);\n      }\n\n   }\n\n   @Test(groups = {\"fails-on-s3proxy\"})\n   public void testUpdateBucketACL() throws InterruptedException, ExecutionException, TimeoutException, IOException,\n         Exception {\n      String bucketName = getContainerName();\n      try {\n         // Confirm the bucket is private\n         AccessControlList acl = getApi().getBucketACL(bucketName);\n         String ownerId = acl.getOwner().getId();\n         assertEquals(acl.getGrants().size(), 1);\n         assertTrue(acl.hasPermission(ownerId, FULL_CONTROL));\n\n         allowPublicReadable(bucketName);\n         addGrantsToACL(acl);\n         assertEquals(acl.getGrants().size(), 4);\n         assertTrue(getApi().putBucketACL(bucketName, acl));\n\n         // Confirm that the updated ACL has stuck.\n         acl = getApi().getBucketACL(bucketName);\n         checkGrants(acl);\n      } finally {\n         destroyContainer(bucketName);\n      }\n\n   }\n\n   private void checkGrants(AccessControlList acl) {\n      String ownerId = acl.getOwner().getId();\n\n      assertEquals(acl.getGrants().size(), 4, acl.toString());\n\n      assertTrue(acl.hasPermission(ownerId, FULL_CONTROL), acl.toString());\n      assertTrue(acl.hasPermission(ALL_USERS, READ), acl.toString());\n      assertTrue(acl.hasPermission(ownerId, WRITE_ACP), acl.toString());\n      // EmailAddressGrantee is replaced by a CanonicalUserGrantee, so we cannot test by email addr\n      assertTrue(acl.hasPermission(TEST_ACL_ID, READ_ACP), acl.toString());\n   }\n\n   private void addGrantsToACL(AccessControlList acl) {\n      String ownerId = acl.getOwner().getId();\n      acl.addPermission(ALL_USERS, READ);\n      acl.addPermission(new EmailAddressGrantee(TEST_ACL_EMAIL), READ_ACP);\n      acl.addPermission(new CanonicalUserGrantee(ownerId), WRITE_ACP);\n   }\n\n   public void testPublicReadAccessPolicy() throws Exception {\n      String bucketName = getScratchContainerName();\n      try {\n         getApi().putBucketInRegion(/*region=*/ null, bucketName);\n         allowPublicReadable(bucketName);\n         getApi().updateBucketCannedACL(bucketName, CannedAccessPolicy.PUBLIC_READ);\n         AccessControlList acl = getApi().getBucketACL(bucketName);\n         assertTrue(acl.hasPermission(ALL_USERS, READ), acl.toString());\n         // TODO: I believe that the following should work based on the above acl assertion passing.\n         // However, it fails on 403\n         // URL url = new URL(String.format(\"http://%s.s3.amazonaws.com\", bucketName));\n         // Utils.toStringAndClose(url.openStream());\n      } finally {\n         destroyContainer(bucketName);\n      }\n   }\n\n   @Test(expectedExceptions = IOException.class)\n   public void testDefaultAccessPolicy() throws Exception {\n      String bucketName = getContainerName();\n      try {\n         URL url = new URL(String.format(\"https://%s.s3.amazonaws.com\", bucketName));\n         Strings2.toStringAndClose(url.openStream());\n      } finally {\n         returnContainer(bucketName);\n      }\n\n   }\n\n   @Test(groups = {\"fails-on-s3proxy\"})\n   public void testBucketPayer() throws Exception {\n      final String bucketName = getContainerName();\n      try {\n         assertEquals(BUCKET_OWNER, getApi().getBucketPayer(bucketName));\n         getApi().setBucketPayer(bucketName, REQUESTER);\n         assertConsistencyAware(new Runnable() {\n            public void run() {\n               try {\n                  assertEquals(REQUESTER, getApi().getBucketPayer(bucketName));\n\n               } catch (Exception e) {\n                  Throwables.propagateIfPossible(e);\n               }\n            }\n         });\n         getApi().setBucketPayer(bucketName, BUCKET_OWNER);\n         assertConsistencyAware(new Runnable() {\n            public void run() {\n               try {\n                  assertEquals(BUCKET_OWNER, getApi().getBucketPayer(bucketName));\n               } catch (Exception e) {\n                  Throwables.propagateIfPossible(e);\n               }\n            }\n         });\n      } finally {\n         destroyContainer(bucketName);\n      }\n   }\n\n   protected void allowPublicReadable(String containerName) {\n   }\n\n   @Test(groups = {\"fails-on-s3proxy\"})\n   public void testBucketLogging() throws Exception {\n      final String bucketName = getContainerName();\n      final String targetBucket = getContainerName();\n      try {\n         allowPublicReadable(targetBucket);\n         assertNull(getApi().getBucketLogging(bucketName));\n\n         setupAclForBucketLoggingTarget(targetBucket);\n         final BucketLogging logging = new BucketLogging(targetBucket, \"access_log-\",\n               ImmutableSet.<Grant> of(new Grant(new EmailAddressGrantee(TEST_ACL_EMAIL), FULL_CONTROL)));\n\n         getApi().enableBucketLogging(bucketName, logging);\n\n         assertConsistencyAware(new Runnable() {\n            public void run() {\n               try {\n                  BucketLogging newLogging = getApi().getBucketLogging(bucketName);\n                  assert newLogging != null;\n                  AccessControlList acl = new AccessControlList();\n                  for (Grant grant : newLogging.getTargetGrants()) { // TODO: add permission\n                     // checking features to\n                     // bucketlogging\n                     acl.addPermission(grant.getGrantee(), grant.getPermission());\n                  }\n                  // EmailAddressGrantee is replaced by a CanonicalUserGrantee, so we cannot test by\n                  // email addr\n                  assertTrue(acl.hasPermission(TEST_ACL_ID, FULL_CONTROL), acl.toString());\n                  assertEquals(logging.getTargetBucket(), newLogging.getTargetBucket());\n                  assertEquals(logging.getTargetPrefix(), newLogging.getTargetPrefix());\n               } catch (Exception e) {\n                  Throwables.propagateIfPossible(e);\n               }\n            }\n         });\n         getApi().disableBucketLogging(bucketName);\n         assertConsistencyAware(new Runnable() {\n            public void run() {\n               try {\n                  assertNull(getApi().getBucketLogging(bucketName));\n               } catch (Exception e) {\n                  Throwables.propagateIfPossible(e);\n               }\n            }\n         });\n      } finally {\n         destroyContainer(bucketName);\n         destroyContainer(targetBucket);\n      }\n   }\n\n   private void setupAclForBucketLoggingTarget(final String targetBucket) {\n      AccessControlList acl = getApi().getBucketACL(targetBucket);\n      acl.addPermission(LOG_DELIVERY, WRITE);\n      acl.addPermission(LOG_DELIVERY, READ_ACP);\n      assertTrue(getApi().putBucketACL(targetBucket, acl));\n   }\n\n   void bucketExists() throws Exception {\n      String bucketName = getContainerName();\n      try {\n         Set<BucketMetadata> list = getApi().listOwnedBuckets();\n         BucketMetadata firstBucket = Iterables.get(list, 0);\n         BucketMetadata toMatch = new BucketMetadata(bucketName, new Date(), firstBucket.getOwner());\n         assert list.contains(toMatch);\n      } finally {\n         returnContainer(bucketName);\n      }\n   }\n\n   protected void addAlphabetUnderRoot(String bucketName) {\n      for (char letter = 'a'; letter <= 'z'; letter++) {\n         S3Object blob = getApi().newS3Object();\n         blob.getMetadata().setKey(letter + \"\");\n         blob.setPayload(letter + \"content\");\n         getApi().putObject(bucketName, blob);\n      }\n   }\n\n   public void testListBucketMarker() throws InterruptedException, ExecutionException, TimeoutException {\n      String bucketName = getContainerName();\n      try {\n         addAlphabetUnderRoot(bucketName);\n         ListBucketResponse bucket = getApi().listBucket(bucketName, afterMarker(\"y\"));\n         assertEquals(bucket.getMarker(), \"y\");\n         assert !bucket.isTruncated();\n         assertEquals(bucket.size(), 1);\n      } finally {\n         returnContainer(bucketName);\n      }\n   }\n\n   public void testListBucketDelimiter() throws InterruptedException, ExecutionException, TimeoutException {\n      String bucketName = getContainerName();\n      try {\n         String prefix = \"apps\";\n         addTenObjectsUnderPrefix(bucketName, prefix);\n         add15UnderRoot(bucketName);\n         ListBucketResponse bucket = getApi().listBucket(bucketName, delimiter(\"/\"));\n         assertEquals(bucket.getDelimiter(), \"/\");\n         assert !bucket.isTruncated();\n         assertEquals(bucket.size(), 15);\n         assertEquals(bucket.getCommonPrefixes().size(), 1);\n      } finally {\n         returnContainer(bucketName);\n      }\n\n   }\n\n   public void testListBucketPrefix() throws InterruptedException, ExecutionException, TimeoutException {\n      String bucketName = getContainerName();\n      try {\n         String prefix = \"apps\";\n         addTenObjectsUnderPrefix(bucketName, prefix);\n         add15UnderRoot(bucketName);\n\n         ListBucketResponse bucket = getApi().listBucket(bucketName, withPrefix(\"apps/\"));\n         assert !bucket.isTruncated();\n         assertEquals(bucket.size(), 10);\n         assertEquals(bucket.getPrefix(), \"apps/\");\n      } finally {\n         returnContainer(bucketName);\n      }\n\n   }\n\n   public void testListBucketMaxResults() throws InterruptedException, ExecutionException, TimeoutException {\n      String bucketName = getContainerName();\n      try {\n         addAlphabetUnderRoot(bucketName);\n         ListBucketResponse bucket = getApi().listBucket(bucketName, maxResults(5));\n         assertEquals(bucket.getMaxKeys(), 5);\n         assert bucket.isTruncated();\n         assertEquals(bucket.size(), 5);\n      } finally {\n         returnContainer(bucketName);\n      }\n   }\n\n   protected void add15UnderRoot(String bucketName) {\n      for (int i = 0; i < 15; i++) {\n         S3Object blob = getApi().newS3Object();\n         blob.getMetadata().setKey(i + \"\");\n         blob.setPayload(i + \"content\");\n         getApi().putObject(bucketName, blob);\n      }\n   }\n\n   protected void addTenObjectsUnderPrefix(String bucketName, String prefix) {\n      for (int i = 0; i < 10; i++) {\n         S3Object blob = getApi().newS3Object();\n         blob.getMetadata().setKey(prefix + \"/\" + i);\n         blob.setPayload(i + \"content\");\n         getApi().putObject(bucketName, blob);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/xml/AccessControlListHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.xml;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.s3.domain.AccessControlList;\nimport org.jclouds.s3.domain.AccessControlList.GroupGranteeURI;\nimport org.jclouds.s3.domain.AccessControlList.Permission;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code AccessControlListHandler}\n */\n//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"AccessControlListHandlerTest\")\npublic class AccessControlListHandlerTest extends BaseHandlerTest {\n   public static final String aclOwnerOnly = \"<AccessControlPolicy xmlns=\\\"http://s3.amazonaws.com/doc/2006-03-01/\\\"><Owner><ID>1a405254c932b52e5b5caaa88186bc431a1bacb9ece631f835daddaf0c47677c</ID><DisplayName>jamesmurty</DisplayName></Owner><AccessControlList><Grant><Grantee xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xsi:type=\\\"CanonicalUser\\\"><ID>1a405254c932b52e5b5caaa88186bc431a1bacb9ece631f835daddaf0c47677c</ID><DisplayName>jamesmurty</DisplayName></Grantee><Permission>FULL_CONTROL</Permission></Grant></AccessControlList></AccessControlPolicy>\";\n   public static final String aclExtreme = \"<AccessControlPolicy xmlns=\\\"http://s3.amazonaws.com/doc/2006-03-01/\\\"><Owner><ID>1a405254c932b52e5b5caaa88186bc431a1bacb9ece631f835daddaf0c47677c</ID><DisplayName>jamesmurty</DisplayName></Owner><AccessControlList><Grant><Grantee xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xsi:type=\\\"Group\\\"><URI>http://acs.amazonaws.com/groups/global/AuthenticatedUsers</URI></Grantee><Permission>WRITE</Permission></Grant><Grant><Grantee xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xsi:type=\\\"Group\\\"><URI>http://acs.amazonaws.com/groups/global/AuthenticatedUsers</URI></Grantee><Permission>READ_ACP</Permission></Grant><Grant><Grantee xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xsi:type=\\\"CanonicalUser\\\"><ID>1a405254c932b52e5b5caaa88186bc431a1bacb9ece631f835daddaf0c47677c</ID><DisplayName>jamesmurty</DisplayName></Grantee><Permission>WRITE</Permission></Grant><Grant><Grantee xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xsi:type=\\\"Group\\\"><URI>http://acs.amazonaws.com/groups/global/AuthenticatedUsers</URI></Grantee><Permission>WRITE_ACP</Permission></Grant><Grant><Grantee xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xsi:type=\\\"Group\\\"><URI>http://acs.amazonaws.com/groups/global/AllUsers</URI></Grantee><Permission>READ</Permission></Grant><Grant><Grantee xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xsi:type=\\\"Group\\\"><URI>http://acs.amazonaws.com/groups/global/AuthenticatedUsers</URI></Grantee><Permission>READ</Permission></Grant><Grant><Grantee xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xsi:type=\\\"Group\\\"><URI>http://acs.amazonaws.com/groups/s3/LogDelivery</URI></Grantee><Permission>WRITE</Permission></Grant><Grant><Grantee xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xsi:type=\\\"CanonicalUser\\\"><ID>1a405254c932b52e5b5caaa88186bc431a1bacb9ece631f835daddaf0c47677c</ID><DisplayName>jamesmurty</DisplayName></Grantee><Permission>READ</Permission></Grant><Grant><Grantee xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xsi:type=\\\"CanonicalUser\\\"><ID>1a405254c932b52e5b5caaa88186bc431a1bacb9ece631f835daddaf0c47677c</ID><DisplayName>jamesmurty</DisplayName></Grantee><Permission>FULL_CONTROL</Permission></Grant></AccessControlList></AccessControlPolicy>\";\n\n   ParseSax<AccessControlList> createParser() {\n      ParseSax<AccessControlList> parser = factory.create(injector\n               .getInstance(AccessControlListHandler.class));\n      return parser;\n   }\n\n   @Test\n   public void testAccessControlListOwnerOnly() throws HttpException {\n      String ownerId = \"1a405254c932b52e5b5caaa88186bc431a1bacb9ece631f835daddaf0c47677c\";\n      AccessControlList acl = createParser().parse(Strings2.toInputStream(aclOwnerOnly));\n      assertEquals(acl.getOwner().getId(), ownerId);\n      assertEquals(acl.getOwner().getDisplayName(), \"jamesmurty\");\n      assertEquals(acl.getPermissions(ownerId).size(), 1);\n      assertTrue(acl.hasPermission(ownerId, Permission.FULL_CONTROL));\n      assertEquals(acl.getGrants().size(), 1);\n      assertEquals(acl.getPermissions(GroupGranteeURI.ALL_USERS).size(), 0);\n      assertEquals(acl.getPermissions(GroupGranteeURI.AUTHENTICATED_USERS).size(), 0);\n      assertEquals(acl.getPermissions(GroupGranteeURI.LOG_DELIVERY).size(), 0);\n   }\n\n   @Test\n   public void testAccessControlListExtreme() throws HttpException {\n      String ownerId = \"1a405254c932b52e5b5caaa88186bc431a1bacb9ece631f835daddaf0c47677c\";\n      AccessControlList acl = createParser().parse(Strings2.toInputStream(aclExtreme));\n      assertEquals(acl.getOwner().getId(), ownerId);\n      assertEquals(acl.getOwner().getDisplayName(), \"jamesmurty\");\n      assertEquals(acl.getPermissions(ownerId).size(), 3);\n      assertTrue(acl.hasPermission(ownerId, Permission.FULL_CONTROL));\n      assertTrue(acl.hasPermission(ownerId, Permission.READ));\n      assertTrue(acl.hasPermission(ownerId, Permission.WRITE));\n      assertEquals(acl.getGrants().size(), 9);\n      assertTrue(acl.hasPermission(GroupGranteeURI.ALL_USERS, Permission.READ));\n      assertTrue(acl.hasPermission(GroupGranteeURI.AUTHENTICATED_USERS, Permission.READ));\n      assertTrue(acl.hasPermission(GroupGranteeURI.AUTHENTICATED_USERS, Permission.WRITE));\n      assertTrue(acl.hasPermission(GroupGranteeURI.AUTHENTICATED_USERS, Permission.READ_ACP));\n      assertTrue(acl.hasPermission(GroupGranteeURI.AUTHENTICATED_USERS, Permission.WRITE_ACP));\n      assertTrue(acl.hasPermission(GroupGranteeURI.LOG_DELIVERY, Permission.WRITE));\n   }\n\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/xml/BucketLoggingHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.xml;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.s3.domain.AccessControlList.EmailAddressGrantee;\nimport org.jclouds.s3.domain.AccessControlList.Grant;\nimport org.jclouds.s3.domain.AccessControlList.Permission;\nimport org.jclouds.s3.domain.BucketLogging;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code BucketLoggingHandler}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"BucketLoggingHandlerTest\")\npublic class BucketLoggingHandlerTest extends BaseHandlerTest {\n   public void testApplyInputStream() {\n      InputStream is = getClass().getResourceAsStream(\"/bucket_logging.xml\");\n\n      BucketLogging expected = new BucketLogging(\"mylogs\", \"access_log-\", ImmutableSet.<Grant> of(new Grant(\n            new EmailAddressGrantee(\"adrian@jclouds.org\"), Permission.FULL_CONTROL)));\n      BucketLoggingHandler handler = injector.getInstance(BucketLoggingHandler.class);\n      BucketLogging result = factory.create(handler).parse(is);\n\n      assertEquals(result.getTargetBucket(), expected.getTargetBucket());\n      assertEquals(result.getTargetGrants(), expected.getTargetGrants());\n      assertEquals(result.getTargetPrefix(), expected.getTargetPrefix());\n\n   }\n\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/xml/CopyObjectHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.xml;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.s3.domain.ObjectMetadata;\nimport org.jclouds.s3.domain.internal.CopyObjectResult;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code CopyObjectHandler}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"CopyObjectHandlerTest\")\npublic class CopyObjectHandlerTest extends BaseHandlerTest {\n\n   private DateService dateService;\n\n   private final String copyObjectResultWithSecondsDate = \"<CopyObjectResult xmlns=\\\"http://s3.amazonaws.com/doc/2006-03-01/\\\"><LastModified>2014-07-23T20:53:17+0000</LastModified><ETag>\\\"92836a3ea45a6984d1b4d23a747d46bb\\\"</ETag></CopyObjectResult>\";\n\n   @BeforeTest\n   @Override\n   protected void setUpInjector() {\n      super.setUpInjector();\n      dateService = injector.getInstance(DateService.class);\n      assert dateService != null;\n   }\n\n   public void testApplyInputStream() {\n      InputStream is = getClass().getResourceAsStream(\"/copy_object.xml\");\n      ObjectMetadata expected = new CopyObjectResult(new SimpleDateFormatDateService()\n               .iso8601DateParse(\"2009-03-19T13:23:27.000Z\"),\n               \"\\\"92836a3ea45a6984d1b4d23a747d46bb\\\"\");\n\n      ObjectMetadata result = factory.create(\n               injector.getInstance(CopyObjectHandler.class)).parse(is);\n\n      assertEquals(result, expected);\n   }\n\n   /**\n    * Verifies that the parser doesn't barf if the timestamp in the copy object\n    * xml has time zone designators.\n    */\n   public void testApplyInputStreamWithSecondsDate() {\n      InputStream is = Strings2.toInputStream(copyObjectResultWithSecondsDate);\n      ObjectMetadata expected = new CopyObjectResult(\n            new SimpleDateFormatDateService()\n                  .iso8601SecondsDateParse(\"2014-07-23T20:53:17+0000\"),\n            \"\\\"92836a3ea45a6984d1b4d23a747d46bb\\\"\");\n\n      ObjectMetadata result = factory.create(\n            injector.getInstance(CopyObjectHandler.class)).parse(is);\n\n      assertEquals(result, expected);\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/xml/DeleteResultHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.xml;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.s3.domain.DeleteResult;\nimport org.testng.annotations.Test;\n\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"DeleteResultHandlerTest\")\npublic class DeleteResultHandlerTest extends BaseHandlerTest {\n\n   @Test\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/delete-result.xml\");\n\n      DeleteResult expected = expected();\n\n      DeleteResultHandler handler = injector.getInstance(DeleteResultHandler.class);\n      DeleteResult result = factory.create(handler).parse(is);\n\n      assertEquals(result.toString(), expected.toString());\n   }\n\n   private DeleteResult expected() {\n      return DeleteResult.builder()\n         .add(\"key1\")\n         .add(\"key1.1\")\n         .putError(\"key2\", new DeleteResult.Error(\"AccessDenied\", \"Access Denied\"))\n         .build();\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/xml/ListBucketHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.xml;\n\nimport static com.google.common.io.BaseEncoding.base16;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\nimport java.net.URI;\nimport java.util.TreeSet;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.s3.domain.CanonicalUser;\nimport org.jclouds.s3.domain.ListBucketResponse;\nimport org.jclouds.s3.domain.ObjectMetadata;\nimport org.jclouds.s3.domain.ObjectMetadataBuilder;\nimport org.jclouds.s3.domain.internal.CopyObjectResult;\nimport org.jclouds.s3.domain.internal.ListBucketResponseImpl;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tests behavior of {@code ListBucketHandler}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"ListBucketHandlerTest\")\npublic class ListBucketHandlerTest extends BaseHandlerTest {\n   public static final String listBucketWithPrefixAppsSlash = \"<ListBucketResult xmlns=\\\"http://s3.amazonaws.com/doc/2006-03-01/\\\"><Name>adriancole.org.jclouds.s3.amazons3testdelimiter</Name><Prefix>apps/</Prefix><Marker></Marker><MaxKeys>1000</MaxKeys><IsTruncated>false</IsTruncated><Contents><Key>apps/0</Key><LastModified>2009-05-07T18:27:08.000Z</LastModified><ETag>&quot;c82e6a0025c31c5de5947fda62ac51ab&quot;</ETag><Size>8</Size><Owner><ID>e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0</ID><DisplayName>ferncam</DisplayName></Owner><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>apps/1</Key><LastModified>2009-05-07T18:27:09.000Z</LastModified><ETag>&quot;944fab2c5a9a6bacf07db5e688310d7a&quot;</ETag><Size>8</Size><Owner><ID>e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0</ID><DisplayName>ferncam</DisplayName></Owner><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>apps/2</Key><LastModified>2009-05-07T18:27:09.000Z</LastModified><ETag>&quot;a227b8888045c8fd159fb495214000f0&quot;</ETag><Size>8</Size><Owner><ID>e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0</ID><DisplayName>ferncam</DisplayName></Owner><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>apps/3</Key><LastModified>2009-05-07T18:27:09.000Z</LastModified><ETag>&quot;c9caa76c3dec53e2a192608ce73eef03&quot;</ETag><Size>8</Size><Owner><ID>e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0</ID><DisplayName>ferncam</DisplayName></Owner><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>apps/4</Key><LastModified>2009-05-07T18:27:09.000Z</LastModified><ETag>&quot;1ce5d0dcc6154a647ea90c7bdf82a224&quot;</ETag><Size>8</Size><Owner><ID>e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0</ID><DisplayName>ferncam</DisplayName></Owner><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>apps/5</Key><LastModified>2009-05-07T18:27:09.000Z</LastModified><ETag>&quot;79433524d87462ee05708a8ef894ed55&quot;</ETag><Size>8</Size><Owner><ID>e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0</ID><DisplayName>ferncam</DisplayName></Owner><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>apps/6</Key><LastModified>2009-05-07T18:27:10.000Z</LastModified><ETag>&quot;dd00a060b28ddca8bc5a21a49e306f67&quot;</ETag><Size>8</Size><Owner><ID>e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0</ID><DisplayName>ferncam</DisplayName></Owner><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>apps/7</Key><LastModified>2009-05-07T18:27:10.000Z</LastModified><ETag>&quot;8cd06eca6e819a927b07a285d750b100&quot;</ETag><Size>8</Size><Owner><ID>e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0</ID><DisplayName>ferncam</DisplayName></Owner><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>apps/8</Key><LastModified>2009-05-07T18:27:10.000Z</LastModified><ETag>&quot;174495094d0633b92cbe46603eee6bad&quot;</ETag><Size>8</Size><Owner><ID>e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0</ID><DisplayName>ferncam</DisplayName></Owner><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>apps/9</Key><LastModified>2009-05-07T18:27:10.000Z</LastModified><ETag>&quot;cd8a19b26fea8a827276df0ad11c580d&quot;</ETag><Size>8</Size><Owner><ID>e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0</ID><DisplayName>ferncam</DisplayName></Owner><StorageClass>STANDARD</StorageClass></Contents></ListBucketResult>\";\n   public static final String listBucketWithSecondsDate = \"<ListBucketResult xmlns=\\\"http://s3.amazonaws.com/doc/2006-03-01/\\\"><Name>adriancole.org.jclouds.s3.amazons3testdelimiter</Name><Prefix>apps/</Prefix><Marker></Marker><MaxKeys>1000</MaxKeys><IsTruncated>false</IsTruncated><Contents><Key>apps/9</Key><LastModified>2014-07-23T20:53:17+0000</LastModified><ETag>&quot;cd8a19b26fea8a827276df0ad11c580d&quot;</ETag><Size>8</Size><Owner><ID>e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0</ID><DisplayName>ferncam</DisplayName></Owner><StorageClass>STANDARD</StorageClass></Contents></ListBucketResult>\";\n   public static final String listBucketWithSlashDelimiterAndCommonPrefixApps = \"<ListBucketResult xmlns=\\\"http://s3.amazonaws.com/doc/2006-03-01/\\\"> <Delimiter>/</Delimiter> <CommonPrefixes><Prefix>apps/</Prefix></CommonPrefixes></ListBucketResult>\";\n   public static final String listBucketWithDisplayNameFirst = \"<ListBucketResult xmlns=\\\"http://s3.amazonaws.com/doc/2006-03-01/\\\"><Name>adriancole.org.jclouds.s3.amazons3testdelimiter</Name><Prefix>apps/</Prefix><Marker></Marker><MaxKeys>1000</MaxKeys><IsTruncated>false</IsTruncated><Contents><Key>apps/9</Key><LastModified>2014-07-23T20:53:17+0000</LastModified><ETag>&quot;cd8a19b26fea8a827276df0ad11c580d&quot;</ETag><Size>8</Size><Owner><DisplayName>ferncam</DisplayName><ID>e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0</ID></Owner><StorageClass>STANDARD</StorageClass></Contents></ListBucketResult>\";\n   private DateService dateService = new SimpleDateFormatDateService();\n\n   public void testApplyInputStream() {\n      InputStream is = getClass().getResourceAsStream(\"/list_bucket.xml\");\n\n      ListBucketResponse result = createParser().parse(is);\n\n      ListBucketResponse expected = expected();\n\n      assertEquals(result.toString(), expected.toString());\n   }\n\n   public ListBucketResponse expected() {\n      CanonicalUser owner = new CanonicalUser(\"e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0\",\n               \"ferncam\");\n      String bucket = \"adriancole.org.jclouds.aws.s3.amazons3testdelimiter\";\n      ListBucketResponse expected = new ListBucketResponseImpl(bucket, ImmutableList.<ObjectMetadata> of(\n               new ObjectMetadataBuilder().key(\"apps/0\").bucket(bucket).uri(URI.create(\"http://bucket.com/apps/0\"))\n                        .lastModified(dateService.iso8601DateParse(\"2009-05-07T18:27:08.000Z\")).eTag(\n                                 \"\\\"c82e6a0025c31c5de5947fda62ac51ab\\\"\").owner(owner).contentMD5(\n                                 base16().lowerCase().decode(\"c82e6a0025c31c5de5947fda62ac51ab\")).contentLength(8L).build(),\n               new ObjectMetadataBuilder().key(\"apps/1\").bucket(bucket).uri(URI.create(\"http://bucket.com/apps/1\"))\n                        .lastModified(dateService.iso8601DateParse(\"2009-05-07T18:27:09.000Z\")).eTag(\n                                 \"\\\"944fab2c5a9a6bacf07db5e688310d7a\\\"\").owner(owner).contentMD5(\n                                 base16().lowerCase().decode(\"944fab2c5a9a6bacf07db5e688310d7a\")).contentLength(8L).build(),\n               new ObjectMetadataBuilder().key(\"apps/2\").bucket(bucket).uri(URI.create(\"http://bucket.com/apps/2\"))\n                        .lastModified(dateService.iso8601DateParse(\"2009-05-07T18:27:09.000Z\")).eTag(\n                                 \"\\\"a227b8888045c8fd159fb495214000f0\\\"\").owner(owner).contentMD5(\n                                 base16().lowerCase().decode(\"a227b8888045c8fd159fb495214000f0\")).contentLength(8L).build(),\n               new ObjectMetadataBuilder().key(\"apps/3\").bucket(bucket).uri(URI.create(\"http://bucket.com/apps/3\"))\n                        .lastModified(dateService.iso8601DateParse(\"2009-05-07T18:27:09.000Z\")).eTag(\n                                 \"\\\"c9caa76c3dec53e2a192608ce73eef03\\\"\").owner(owner).contentMD5(\n                                 base16().lowerCase().decode(\"c9caa76c3dec53e2a192608ce73eef03\")).contentLength(8L).build(),\n               new ObjectMetadataBuilder().key(\"apps/4\").bucket(bucket).uri(URI.create(\"http://bucket.com/apps/4\"))\n                        .lastModified(dateService.iso8601DateParse(\"2009-05-07T18:27:09.000Z\")).eTag(\n                                 \"\\\"1ce5d0dcc6154a647ea90c7bdf82a224\\\"\").owner(owner).contentMD5(\n                                 base16().lowerCase().decode(\"1ce5d0dcc6154a647ea90c7bdf82a224\")).contentLength(8L).build(),\n               new ObjectMetadataBuilder().key(\"apps/5\").bucket(bucket).uri(URI.create(\"http://bucket.com/apps/5\"))\n                        .lastModified(dateService.iso8601DateParse(\"2009-05-07T18:27:09.000Z\")).eTag(\n                                 \"\\\"79433524d87462ee05708a8ef894ed55\\\"\").owner(owner).contentMD5(\n                                 base16().lowerCase().decode(\"79433524d87462ee05708a8ef894ed55\")).contentLength(8L).build(),\n               new ObjectMetadataBuilder().key(\"apps/6\").bucket(bucket).uri(URI.create(\"http://bucket.com/apps/6\"))\n                        .lastModified(dateService.iso8601DateParse(\"2009-05-07T18:27:10.000Z\")).eTag(\n                                 \"\\\"dd00a060b28ddca8bc5a21a49e306f67\\\"\").owner(owner).contentMD5(\n                                 base16().lowerCase().decode(\"dd00a060b28ddca8bc5a21a49e306f67\")).contentLength(8L).build(),\n               new ObjectMetadataBuilder().key(\"apps/7\").bucket(bucket).uri(URI.create(\"http://bucket.com/apps/7\"))\n                        .lastModified(dateService.iso8601DateParse(\"2009-05-07T18:27:10.000Z\")).eTag(\n                                 \"\\\"8cd06eca6e819a927b07a285d750b100\\\"\").owner(owner).contentMD5(\n                                 base16().lowerCase().decode(\"8cd06eca6e819a927b07a285d750b100\")).contentLength(8L).build(),\n               new ObjectMetadataBuilder().key(\"apps/8\").bucket(bucket).uri(URI.create(\"http://bucket.com/apps/8\"))\n                        .lastModified(dateService.iso8601DateParse(\"2009-05-07T18:27:10.000Z\")).eTag(\n                                 \"\\\"174495094d0633b92cbe46603eee6bad\\\"\").owner(owner).contentMD5(\n                                 base16().lowerCase().decode(\"174495094d0633b92cbe46603eee6bad\")).contentLength(8L).build(),\n               new ObjectMetadataBuilder().key(\"apps/9\").bucket(bucket).uri(URI.create(\"http://bucket.com/apps/9\"))\n                        .lastModified(dateService.iso8601DateParse(\"2009-05-07T18:27:10.000Z\")).eTag(\n                                 \"\\\"cd8a19b26fea8a827276df0ad11c580d\\\"\").owner(owner).contentMD5(\n                                 base16().lowerCase().decode(\"cd8a19b26fea8a827276df0ad11c580d\")).contentLength(8L).build()),\n               \"apps/\", null, null, 1000, null, false, new TreeSet<String>());\n      return expected;\n   }\n\n   ParseSax<ListBucketResponse> createParser() {\n      return factory.create(injector.getInstance(ListBucketHandler.class)).setContext(\n               HttpRequest.builder().method(\"GET\").endpoint(\"http://bucket.com\").build());\n   }\n\n   @Test\n   public void testListMyBucketsWithDelimiterSlashAndCommonPrefixesAppsSlash() throws HttpException {\n\n      ListBucketResponse bucket = createParser().parse(\n               Strings2.toInputStream(listBucketWithSlashDelimiterAndCommonPrefixApps));\n      assertEquals(bucket.getCommonPrefixes().iterator().next(), \"apps/\");\n      assertEquals(bucket.getDelimiter(), \"/\");\n      assert bucket.getMarker() == null;\n   }\n\n   @Test\n   public void testListMyBucketsWithPrefixAppsSlash() throws HttpException {\n\n      ListBucketResponse bucket = createParser().parse(Strings2.toInputStream(listBucketWithPrefixAppsSlash));\n      assertEquals(bucket.getPrefix(), \"apps/\");\n      assertEquals(bucket.getMaxKeys(), 1000);\n      assert bucket.getMarker() == null;\n   }\n\n   /**\n    * Verifies that the parser doesn't barf if the timestamp returned in the\n    * list bucket response has time zone designators in it.\n    */\n   @Test\n   public void testListMyBucketsWithSecondsDate() {\n      ListBucketResponse bucket = createParser().parse(\n            Strings2.toInputStream(listBucketWithSecondsDate));\n      ObjectMetadata expected = new CopyObjectResult(\n            new SimpleDateFormatDateService()\n                  .iso8601SecondsDateParse(\"2014-07-23T20:53:17+0000\"),\n            \"\\\"92836a3ea45a6984d1b4d23a747d46bb\\\"\");\n\n      // Verify that the date was parsed successfully.\n      ObjectMetadata metadata = bucket.iterator().next();\n      assertEquals(metadata.getLastModified(), expected.getLastModified());\n   }\n   \n   @Test\n   public void testListMyBucketsWithDisplayNameFirst() {\n      ListBucketResponse bucket = createParser().parse(\n            Strings2.toInputStream(listBucketWithDisplayNameFirst));\n      ObjectMetadata expected = new CopyObjectResult(\n            new SimpleDateFormatDateService()\n                  .iso8601SecondsDateParse(\"2014-07-23T20:53:17+0000\"),\n            \"\\\"92836a3ea45a6984d1b4d23a747d46bb\\\"\");\n\n      // Verify that the date was parsed successfully.\n      ObjectMetadata metadata = bucket.iterator().next();\n      assertEquals(metadata.getLastModified(), expected.getLastModified());\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/xml/PartIdsFromHttpResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.xml;\n\nimport static org.assertj.core.api.Assertions.assertThat;\n\nimport java.util.Map;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.http.functions.ParseSax;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Tests behavior of {@code PartIdsFromHttpResponse}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"PartIdsFromHttpResponseTest\")\npublic final class PartIdsFromHttpResponseTest extends BaseHandlerTest {\n   private final DateService dateService = new SimpleDateFormatDateService();\n\n   @Test\n   public void test() {\n      Map<Integer, String> actual = createParser().parse(getClass().getResourceAsStream(\n            \"/multipart-upload-list-parts.xml\"));\n\n      Map<Integer, String> expected = ImmutableMap.of(\n            2, \"\\\"7778aef83f66abc1fa1e8477f296d394\\\"\",\n            3, \"\\\"aaaa18db4cc2f85cedef654fccc4a4x8\\\"\");\n\n      assertThat(actual).isEqualTo(expected);\n   }\n\n   private ParseSax<Map<Integer, String>> createParser() {\n      return factory.create(injector.getInstance(PartIdsFromHttpResponse.class)).setContext(\n               HttpRequest.builder().method(\"GET\").endpoint(\"http://bucket.com\").build());\n   }\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/xml/PayerHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.xml;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.s3.domain.Payer;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code PayerHandler}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"PayerHandlerTest\")\npublic class PayerHandlerTest extends BaseHandlerTest {\n\n   ParseSax<Payer> createParser() {\n      ParseSax<Payer> parser = factory.create(injector\n               .getInstance(PayerHandler.class));\n      return parser;\n   }\n\n   @Test\n   public void testPayerRequester() throws HttpException {\n      Payer payer = createParser()\n               .parse(\n                        Strings2\n                                 .toInputStream(\"<RequestPaymentConfiguration xmlns=\\\"http://s3.amazonaws.com/doc/2006-03-01/\\\"><Payer>Requester</Payer></RequestPaymentConfiguration>\"));\n      assertEquals(payer, Payer.REQUESTER);\n\n   }\n\n   @Test\n   public void testPayerBucketOwner() throws HttpException {\n      Payer payer = createParser()\n               .parse(\n                        Strings2\n                                 .toInputStream(\"<RequestPaymentConfiguration xmlns=\\\"http://s3.amazonaws.com/doc/2006-03-01/\\\"><Payer>BucketOwner</Payer></RequestPaymentConfiguration>\"));\n      assertEquals(payer, Payer.BUCKET_OWNER);\n\n   }\n\n}\n"
  },
  {
    "path": "apis/s3/src/test/java/org/jclouds/s3/xml/S3ParserTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.s3.xml;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.util.Date;\nimport java.util.Set;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.CompletionService;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.ExecutorCompletionService;\n\nimport org.jclouds.PerformanceTest;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.http.functions.config.SaxParserModule;\nimport org.jclouds.s3.domain.BucketMetadata;\nimport org.jclouds.s3.domain.CanonicalUser;\nimport org.jclouds.s3.domain.ListBucketResponse;\nimport org.jclouds.s3.domain.ObjectMetadata;\nimport org.jclouds.s3.domain.ObjectMetadata.StorageClass;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.AfterTest;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\nimport org.xml.sax.SAXException;\n\nimport com.google.common.collect.Iterables;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n/**\n * Tests parsing of S3 responses\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"performance\", singleThreaded = true, timeOut = 2 * 60 * 1000, testName = \"S3ParserTest\")\npublic class S3ParserTest extends PerformanceTest {\n   Injector injector = null;\n   ParseSax.Factory factory;\n\n   @BeforeTest\n   protected void setUpInjector() {\n      injector = Guice.createInjector(new SaxParserModule());\n      factory = injector.getInstance(ParseSax.Factory.class);\n      assert factory != null;\n   }\n\n   @AfterTest\n   protected void tearDownInjector() {\n      factory = null;\n      injector = null;\n   }\n\n   public static final String listAllMyBucketsResultOn200 = \"<ListAllMyBucketsResult xmlns=\\\"http://s3.amazonaws.com/doc/callables/\\\"><Owner><ID>e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0</ID></Owner><Buckets><Bucket><Name>adrianjbosstest</Name><CreationDate>2009-03-12T02:00:07.000Z</CreationDate></Bucket><Bucket><Name>adrianjbosstest2</Name><CreationDate>2009-03-12T02:00:09.000Z</CreationDate></Bucket></Buckets></ListAllMyBucketsResult>\";\n   public static final String listAllMyBucketsResultOn200DisplayNameFirst = \"<ListAllMyBucketsResult xmlns=\\\"http://s3.amazonaws.com/doc/callables/\\\"><Owner><DisplayName>TestName</DisplayName><ID>e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0</ID></Owner><Buckets><Bucket><Name>adrianjbosstest</Name><CreationDate>2009-03-12T02:00:07.000Z</CreationDate></Bucket></Buckets></ListAllMyBucketsResult>\";\n   public static final String listAllMyBucketsResultOn200OwnerLast = \"<ListAllMyBucketsResult xmlns=\\\"http://s3.amazonaws.com/doc/callables/\\\"><Buckets><Bucket><Name>adrianjbosstest</Name><CreationDate>2009-03-12T02:00:07.000Z</CreationDate></Bucket></Buckets><Owner><DisplayName>TestName</DisplayName><ID>e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0</ID></Owner></ListAllMyBucketsResult>\";\n\n   @Test\n   void testParseListAllMyBucketsSerialResponseTime() throws HttpException {\n      for (int i = 0; i < LOOP_COUNT; i++)\n         runParseListAllMyBuckets();\n   }\n\n   private Set<BucketMetadata> runParseListAllMyBuckets() throws HttpException {\n      return factory.create(injector.getInstance(ListAllMyBucketsHandler.class)).parse(\n               Strings2.toInputStream(listAllMyBucketsResultOn200));\n   }\n\n   @Test\n   void testParseListAllMyBucketsParallelResponseTime() throws InterruptedException, ExecutionException {\n      CompletionService<Set<BucketMetadata>> completer = new ExecutorCompletionService<Set<BucketMetadata>>(exec);\n      for (int i = 0; i < LOOP_COUNT; i++)\n         completer.submit(new Callable<Set<BucketMetadata>>() {\n            public Set<BucketMetadata> call() throws IOException, SAXException, HttpException {\n               return runParseListAllMyBuckets();\n            }\n         });\n      for (int i = 0; i < LOOP_COUNT; i++)\n         assert completer.take().get() != null;\n   }\n\n   @Test\n   public void testCanParseListAllMyBuckets() throws HttpException {\n      Set<BucketMetadata> s3Buckets = runParseListAllMyBuckets();\n      BucketMetadata container1 = Iterables.get(s3Buckets, 0);\n      assert container1.getName().equals(\"adrianjbosstest\");\n      Date expectedDate1 = new SimpleDateFormatDateService().iso8601DateParse(\"2009-03-12T02:00:07.000Z\");\n      Date date1 = container1.getCreationDate();\n      assert date1.equals(expectedDate1);\n      BucketMetadata container2 = (BucketMetadata) s3Buckets.toArray()[1];\n      assert container2.getName().equals(\"adrianjbosstest2\");\n      Date expectedDate2 = new SimpleDateFormatDateService().iso8601DateParse(\"2009-03-12T02:00:09.000Z\");\n      Date date2 = container2.getCreationDate();\n      assert date2.equals(expectedDate2);\n      assert s3Buckets.size() == 2;\n      CanonicalUser owner = new CanonicalUser(\"e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0\");\n      assert container1.getOwner().equals(owner);\n      assert container2.getOwner().equals(owner);\n   }\n\n   @Test\n   public void testCanParseListAllMyBucketsDisplayNameFirst() throws HttpException {\n      Set<BucketMetadata> s3Buckets = factory.create(injector.getInstance(ListAllMyBucketsHandler.class)).parse(\n              Strings2.toInputStream(listAllMyBucketsResultOn200DisplayNameFirst));\n      BucketMetadata container = Iterables.get(s3Buckets, 0);\n      assert container.getName().equals(\"adrianjbosstest\");\n      Date expectedDate1 = new SimpleDateFormatDateService().iso8601DateParse(\"2009-03-12T02:00:07.000Z\");\n      Date date = container.getCreationDate();\n      assert date.equals(expectedDate1);\n      assert s3Buckets.size() == 1;\n      CanonicalUser owner = new CanonicalUser(\"e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0\",\n              \"TestName\");\n      assert container.getOwner().equals(owner);\n   }\n\n   @Test\n   public void testCanParseListAllMyBucketsOwnerLast() throws HttpException {\n      Set<BucketMetadata> s3Buckets = factory.create(injector.getInstance(ListAllMyBucketsHandler.class)).parse(\n              Strings2.toInputStream(listAllMyBucketsResultOn200OwnerLast));\n      BucketMetadata container = Iterables.get(s3Buckets, 0);\n      assert container.getName().equals(\"adrianjbosstest\");\n      Date expectedDate = new SimpleDateFormatDateService().iso8601DateParse(\"2009-03-12T02:00:07.000Z\");\n      Date date1 = container.getCreationDate();\n      assert date1.equals(expectedDate);\n      assert s3Buckets.size() == 1;\n      CanonicalUser owner = new CanonicalUser(\"e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0\",\n              \"TestName\");\n      assert container.getOwner().equals(owner);\n   }\n\n   public static final String listContainerResult = \"<ListContainerHandler xmlns=\\\"http://s3.amazonaws.com/doc/2006-03-01/\\\"><Name>adrianjbosstest</Name><Prefix></Prefix><Marker></Marker><MaxKeys>1000</MaxKeys><IsTruncated>false</IsTruncated><Contents><Key>3366</Key><LastModified>2009-03-12T02:00:13.000Z</LastModified><ETag>&quot;9d7bb64e8e18ee34eec06dd2cf37b766&quot;</ETag><Size>136</Size><Owner><ID>e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0</ID><DisplayName>ferncam</DisplayName></Owner><StorageClass>STANDARD</StorageClass></Contents></ListContainerHandler>\";\n\n   public void testCanParseListContainerResult() throws HttpException {\n      ListBucketResponse container = runParseListContainerResult();\n      assert !container.isTruncated();\n      assert container.getName().equals(\"adrianjbosstest\");\n      assert container.size() == 1;\n      ObjectMetadata object = container.iterator().next();\n      assert object.getKey().equals(\"3366\");\n      Date expected = new SimpleDateFormatDateService().iso8601DateParse(\"2009-03-12T02:00:13.000Z\");\n      assert object.getLastModified().equals(expected) : String.format(\"expected %1$s, but got %2$s\", expected, object\n               .getLastModified());\n      assertEquals(object.getETag(), \"\\\"9d7bb64e8e18ee34eec06dd2cf37b766\\\"\");\n      assert object.getContentMetadata().getContentLength() == 136;\n      CanonicalUser owner = new CanonicalUser(\"e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0\");\n      owner.setDisplayName(\"ferncam\");\n      assert object.getOwner().equals(owner);\n      assert object.getStorageClass().equals(StorageClass.STANDARD);\n   }\n\n   private ListBucketResponse runParseListContainerResult() throws HttpException {\n      return factory.create(injector.getInstance(ListBucketHandler.class)).setContext(\n               HttpRequest.builder().method(\"GET\").endpoint(\"http://bucket.com\").build()).parse(\n               Strings2.toInputStream(listContainerResult));\n   }\n\n   public static final String successfulCopyObject200 = \"<CopyObjectResult xmlns=\\\"http://s3.amazonaws.com/doc/2006-03-01/\\\"><LastModified>2009-03-19T13:23:27.000Z</LastModified><ETag>\\\"92836a3ea45a6984d1b4d23a747d46bb\\\"</ETag></CopyObjectResult>\";\n\n   private ObjectMetadata runParseCopyObjectResult() throws HttpException {\n      return factory.create(injector.getInstance(CopyObjectHandler.class)).parse(\n               Strings2.toInputStream(successfulCopyObject200));\n   }\n\n   public void testCanParseCopyObjectResult() throws HttpException {\n      ObjectMetadata metadata = runParseCopyObjectResult();\n      Date expected = new SimpleDateFormatDateService().iso8601DateParse(\"2009-03-19T13:23:27.000Z\");\n      assertEquals(metadata.getLastModified(), expected);\n      assertEquals(metadata.getETag(), \"\\\"92836a3ea45a6984d1b4d23a747d46bb\\\"\");\n   }\n\n   @Test\n   void testParseListContainerResultSerialResponseTime() throws HttpException {\n      for (int i = 0; i < LOOP_COUNT; i++)\n         runParseListContainerResult();\n   }\n\n   @Test\n   void testParseListContainerResultParallelResponseTime() throws InterruptedException, ExecutionException {\n      CompletionService<ListBucketResponse> completer = new ExecutorCompletionService<ListBucketResponse>(exec);\n      for (int i = 0; i < LOOP_COUNT; i++)\n         completer.submit(new Callable<ListBucketResponse>() {\n            public ListBucketResponse call() throws IOException, SAXException, HttpException {\n               return runParseListContainerResult();\n            }\n         });\n      for (int i = 0; i < LOOP_COUNT; i++)\n         assert completer.take().get() != null;\n   }\n\n}\n"
  },
  {
    "path": "apis/s3/src/test/resources/acl_to_xml.xml",
    "content": "<AccessControlPolicy xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"><Owner><ID>jnrouvignac</ID><DisplayName>Jean-Noël Rouvignac</DisplayName></Owner><AccessControlList><Grant><Grantee xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"AmazonCustomerByEmail\"><EmailAddress>adrian@jclouds.org</EmailAddress></Grantee><Permission>FULL_CONTROL</Permission></Grant></AccessControlList></AccessControlPolicy>"
  },
  {
    "path": "apis/s3/src/test/resources/bucket_logging.xml",
    "content": "<BucketLoggingStatus xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"><LoggingEnabled><TargetBucket>mylogs</TargetBucket><TargetPrefix>access_log-</TargetPrefix><TargetGrants><Grant><Grantee xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"AmazonCustomerByEmail\"><EmailAddress>adrian@jclouds.org</EmailAddress></Grantee><Permission>FULL_CONTROL</Permission></Grant></TargetGrants></LoggingEnabled></BucketLoggingStatus>"
  },
  {
    "path": "apis/s3/src/test/resources/complete-multipart-upload.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<CompleteMultipartUploadResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">\n  <Location>http://Example-Bucket.s3.amazonaws.com/Example-Object</Location>\n  <Bucket>Example-Bucket</Bucket>\n  <Key>Example-Object</Key>\n  <ETag>&quot;3858f62230ac3c915f300c664312c11f-9&quot;</ETag>\n</CompleteMultipartUploadResult>"
  },
  {
    "path": "apis/s3/src/test/resources/copy_object.xml",
    "content": "<CopyObjectResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">\n    <LastModified>2009-03-19T13:23:27.000Z</LastModified>\n    <ETag>\"92836a3ea45a6984d1b4d23a747d46bb\"</ETag>\n</CopyObjectResult>\n"
  },
  {
    "path": "apis/s3/src/test/resources/delete-result.xml",
    "content": "<?xml version=\"1.0\"  encoding=\"UTF-8\" ?>\n<DeleteResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">\n    <Deleted>\n        <Key>key1</Key>\n    </Deleted>\n    <Deleted>\n        <Key>key1.1</Key>\n    </Deleted>\n    <Error>\n        <Key>key2</Key>\n        <Code>AccessDenied</Code>\n        <Message>Access Denied</Message>\n    </Error>\n</DeleteResult>"
  },
  {
    "path": "apis/s3/src/test/resources/initiate-multipart-upload.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<InitiateMultipartUploadResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">\n  <Bucket>example-bucket</Bucket>\n  <Key>example-object</Key>\n  <UploadId>VXBsb2FkIElEIGZvciA2aWWpbmcncyBteS1tb3ZpZS5tMnRzIHVwbG9hZA</UploadId>\n</InitiateMultipartUploadResult>"
  },
  {
    "path": "apis/s3/src/test/resources/list_bucket.xml",
    "content": "<ListBucketResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">\n    <Name>adriancole.org.jclouds.aws.s3.amazons3testdelimiter</Name>\n    <Prefix>apps/</Prefix>\n    <Marker></Marker>\n    <MaxKeys>1000</MaxKeys>\n    <IsTruncated>false</IsTruncated>\n    <Contents>\n        <Key>apps/0</Key>\n        <LastModified>2009-05-07T18:27:08.000Z</LastModified>\n        <ETag>\"c82e6a0025c31c5de5947fda62ac51ab\"</ETag>\n        <Size>8</Size>\n        <Owner>\n            <ID>e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0\n            </ID>\n            <DisplayName>ferncam</DisplayName>\n        </Owner>\n        <StorageClass>STANDARD</StorageClass>\n    </Contents>\n    <Contents>\n        <Key>apps/1</Key>\n        <LastModified>2009-05-07T18:27:09.000Z</LastModified>\n        <ETag>\"944fab2c5a9a6bacf07db5e688310d7a\"</ETag>\n        <Size>8</Size>\n        <Owner>\n            <ID>e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0\n            </ID>\n            <DisplayName>ferncam</DisplayName>\n        </Owner>\n        <StorageClass>STANDARD</StorageClass>\n    </Contents>\n    <Contents>\n        <Key>apps/2</Key>\n        <LastModified>2009-05-07T18:27:09.000Z</LastModified>\n        <ETag>\"a227b8888045c8fd159fb495214000f0\"</ETag>\n        <Size>8</Size>\n        <Owner>\n            <ID>e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0\n            </ID>\n            <DisplayName>ferncam</DisplayName>\n        </Owner>\n        <StorageClass>STANDARD</StorageClass>\n    </Contents>\n    <Contents>\n        <Key>apps/3</Key>\n        <LastModified>2009-05-07T18:27:09.000Z</LastModified>\n        <ETag>\"c9caa76c3dec53e2a192608ce73eef03\"</ETag>\n        <Size>8</Size>\n        <Owner>\n            <ID>e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0\n            </ID>\n            <DisplayName>ferncam</DisplayName>\n        </Owner>\n        <StorageClass>STANDARD</StorageClass>\n    </Contents>\n    <Contents>\n        <Key>apps/4</Key>\n        <LastModified>2009-05-07T18:27:09.000Z</LastModified>\n        <ETag>\"1ce5d0dcc6154a647ea90c7bdf82a224\"</ETag>\n        <Size>8</Size>\n        <Owner>\n            <ID>e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0\n            </ID>\n            <DisplayName>ferncam</DisplayName>\n        </Owner>\n        <StorageClass>STANDARD</StorageClass>\n    </Contents>\n    <Contents>\n        <Key>apps/5</Key>\n        <LastModified>2009-05-07T18:27:09.000Z</LastModified>\n        <ETag>\"79433524d87462ee05708a8ef894ed55\"</ETag>\n        <Size>8</Size>\n        <Owner>\n            <ID>e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0\n            </ID>\n            <DisplayName>ferncam</DisplayName>\n        </Owner>\n        <StorageClass>STANDARD</StorageClass>\n    </Contents>\n    <Contents>\n        <Key>apps/6</Key>\n        <LastModified>2009-05-07T18:27:10.000Z</LastModified>\n        <ETag>\"dd00a060b28ddca8bc5a21a49e306f67\"</ETag>\n        <Size>8</Size>\n        <Owner>\n            <ID>e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0\n            </ID>\n            <DisplayName>ferncam</DisplayName>\n        </Owner>\n        <StorageClass>STANDARD</StorageClass>\n    </Contents>\n    <Contents>\n        <Key>apps/7</Key>\n        <LastModified>2009-05-07T18:27:10.000Z</LastModified>\n        <ETag>\"8cd06eca6e819a927b07a285d750b100\"</ETag>\n        <Size>8</Size>\n        <Owner>\n            <ID>e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0\n            </ID>\n            <DisplayName>ferncam</DisplayName>\n        </Owner>\n        <StorageClass>STANDARD</StorageClass>\n    </Contents>\n    <Contents>\n        <Key>apps/8</Key>\n        <LastModified>2009-05-07T18:27:10.000Z</LastModified>\n        <ETag>\"174495094d0633b92cbe46603eee6bad\"</ETag>\n        <Size>8</Size>\n        <Owner>\n            <ID>e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0\n            </ID>\n            <DisplayName>ferncam</DisplayName>\n        </Owner>\n        <StorageClass>STANDARD</StorageClass>\n    </Contents>\n    <Contents>\n        <Key>apps/9</Key>\n        <LastModified>2009-05-07T18:27:10.000Z</LastModified>\n        <ETag>\"cd8a19b26fea8a827276df0ad11c580d\"</ETag>\n        <Size>8</Size>\n        <Owner>\n            <ID>e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0\n            </ID>\n            <DisplayName>ferncam</DisplayName>\n        </Owner>\n        <StorageClass>STANDARD</StorageClass>\n    </Contents>\n</ListBucketResult>\n"
  },
  {
    "path": "apis/s3/src/test/resources/log4j.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE log4j:configuration SYSTEM \"log4j.dtd\">\n\n    <!--\n        For more configuration infromation and examples see the Apache\n        Log4j website: http://logging.apache.org/log4j/\n    -->\n<log4j:configuration xmlns:log4j=\"http://jakarta.apache.org/log4j/\"\n    debug=\"false\">\n\n    <!-- A time/date based rolling appender -->\n    <appender name=\"WIREFILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds-wire.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n\n    <!-- A time/date based rolling appender -->\n    <appender name=\"FILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n    <!-- A time/date based rolling appender -->\n    <appender name=\"BLOBSTOREFILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds-blobstore.log\" />\n        <param name=\"Append\" value=\"true\" />\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n        <param name=\"Threshold\" value=\"TRACE\" />\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n        </layout>\n    </appender>\n\n    <appender name=\"ASYNC\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"FILE\" />\n    </appender>\n\n    <appender name=\"ASYNCWIRE\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"WIREFILE\" />\n    </appender>\n\n    <appender name=\"ASYNCBLOBSTORE\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"BLOBSTOREFILE\" />\n    </appender>\n    <!-- ================ -->\n    <!-- Limit categories -->\n    <!-- ================ -->\n\n    <category name=\"org.jclouds\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNC\" />\n    </category>\n\n    <category name=\"jclouds.headers\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNCWIRE\" />\n    </category>\n    <!--\n        NOTE enabling this will break stream tests <category\n        name=\"jclouds.wire\"> <priority value=\"DEBUG\" /> <appender-ref\n        ref=\"ASYNCWIRE\" /> </category>\n    -->\n    <category name=\"jclouds.blobstore\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNCBLOBSTORE\" />\n    </category>\n    <!-- ======================= -->\n    <!-- Setup the Root category -->\n    <!-- ======================= -->\n\n    <root>\n        <priority value=\"WARN\" />\n    </root>\n\n</log4j:configuration>\n"
  },
  {
    "path": "apis/s3/src/test/resources/multipart-upload-list-parts.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ListPartsResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">\n  <Bucket>example-bucket</Bucket>\n  <Key>example-object</Key>\n  <UploadId>XXBsb2FkIElEIGZvciBlbHZpbmcncyVcdS1tb3ZpZS5tMnRzEEEwbG9hZA</UploadId>\n  <Initiator>\n      <ID>arn:aws:iam::111122223333:user/some-user-11116a31-17b5-4fb7-9df5-b288870f11xx</ID>\n      <DisplayName>umat-user-11116a31-17b5-4fb7-9df5-b288870f11xx</DisplayName>\n  </Initiator>\n  <Owner>\n    <ID>75aa57f09aa0c8caeab4f8c24e99d10f8e7faeebf76c078efc7c6caea54ba06a</ID>\n    <DisplayName>someName</DisplayName>\n  </Owner>\n  <StorageClass>STANDARD</StorageClass>\n  <PartNumberMarker>1</PartNumberMarker>\n  <NextPartNumberMarker>3</NextPartNumberMarker>\n  <MaxParts>2</MaxParts>\n  <IsTruncated>true</IsTruncated>\n  <Part>\n    <PartNumber>2</PartNumber>\n    <LastModified>2010-11-10T20:48:34.000Z</LastModified>\n    <ETag>\"7778aef83f66abc1fa1e8477f296d394\"</ETag>\n    <Size>10485760</Size>\n  </Part>\n  <Part>\n    <PartNumber>3</PartNumber>\n    <LastModified>2010-11-10T20:48:33.000Z</LastModified>\n    <ETag>\"aaaa18db4cc2f85cedef654fccc4a4x8\"</ETag>\n    <Size>10485760</Size>\n  </Part>\n</ListPartsResult>\n"
  },
  {
    "path": "apis/sqs/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.sqs.*;version=\"${project.version}\";-noimport:=true"
  },
  {
    "path": "apis/sqs/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.api</groupId>\n  <artifactId>sqs</artifactId>\n  <name>jclouds sqs api</name>\n  <description>jclouds components to access an implementation of Simple Queue Service</description>\n\n  <properties>\n    <test.sqs.endpoint>https://sqs.us-east-1.amazonaws.com</test.sqs.endpoint>\n    <test.sqs.api-version>2011-10-01</test.sqs.api-version>\n    <test.sqs.build-version />\n    <test.sqs.identity>${test.aws.identity}</test.sqs.identity>\n    <test.sqs.credential>${test.aws.credential}</test.sqs.credential>\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>sts</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-log4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.sqs.endpoint>${test.sqs.endpoint}</test.sqs.endpoint>\n                    <test.sqs.api-version>${test.sqs.api-version}</test.sqs.api-version>\n                    <test.sqs.build-version>${test.sqs.build-version}</test.sqs.build-version>\n                    <test.sqs.identity>${test.sqs.identity}</test.sqs.identity>\n                    <test.sqs.credential>${test.sqs.credential}</test.sqs.credential>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/SQS.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkArgument;\n\nimport org.jclouds.collect.AdvanceUntilEmptyIterable;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.sqs.domain.Message;\nimport org.jclouds.sqs.features.MessageApi;\nimport org.jclouds.sqs.options.ReceiveMessageOptions;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.FluentIterable;\n\n/**\n * Utilities for interacting with SQS\n */\n@Beta\npublic class SQS {\n\n   /**\n    * Returns an iterable that lazy fetches messages until there are none left.\n    * Note that this method will make multiple network calls.\n    * \n    * @param api\n    *           api targeted at the queue in question\n    * @param messagesPerPage\n    *           how many messages to receive per request (current max: 10)\n    * @param options\n    *           controls attributes and visibility options\n    * @return an iterable that lazy fetches messages until there are none left\n    */\n   public static FluentIterable<Message> receiveAllAtRate(MessageApi api, int messagesPerPage,\n         ReceiveMessageOptions options) {\n      return AdvanceUntilEmptyIterable.create(new MoreMessages(api, messagesPerPage, options)).concat();\n   }\n\n   /**\n    * returns another response of messages on {@link MoreMessages#get}\n    * \n    */\n   private static class MoreMessages implements Supplier<FluentIterable<Message>> {\n\n      private static final ReceiveMessageOptions NO_OPTIONS = new ReceiveMessageOptions();\n      private MessageApi api;\n      private int max;\n      private ReceiveMessageOptions options;\n\n      private MoreMessages(MessageApi api, int max, @Nullable ReceiveMessageOptions options) {\n         this.api = checkNotNull(api, \"message api\");\n         checkArgument(max > 0, \"max messages per request must be a positive number\");\n         this.max = max;\n         this.options = MoreObjects.firstNonNull(options, NO_OPTIONS);\n      }\n\n      @Override\n      public FluentIterable<Message> get() {\n         return api.receive(max, options);\n      }\n\n   }\n}\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/SQSApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs;\n\nimport java.io.Closeable;\nimport java.net.URI;\nimport java.util.Set;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.location.Region;\nimport org.jclouds.location.functions.RegionToEndpointOrProviderIfNull;\nimport org.jclouds.rest.annotations.Delegate;\nimport org.jclouds.rest.annotations.EndpointParam;\nimport org.jclouds.sqs.features.MessageApi;\nimport org.jclouds.sqs.features.PermissionApi;\nimport org.jclouds.sqs.features.QueueApi;\n\nimport com.google.common.annotations.Beta;\nimport com.google.inject.Provides;\n\n/**\n * Provides access to SQS via their REST API.\n * <p/>\n */\n@Beta\npublic interface SQSApi extends Closeable {\n   \n   /**\n    * \n    * @return the Region codes configured\n    */\n   @Provides\n   @Region\n   Set<String> getConfiguredRegions();\n\n   /**\n    * Provides synchronous access to Queue features.\n    */\n   @Delegate\n   QueueApi getQueueApi();\n\n   @Delegate\n   QueueApi getQueueApiForRegion(@EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region);\n\n   /**\n    * Provides synchronous access to Message features.\n    */\n   @Delegate\n   MessageApi getMessageApiForQueue(@EndpointParam URI queue);\n\n   /**\n    * Provides synchronous access to Permission features.\n    */\n   @Delegate\n   PermissionApi getPermissionApiForQueue(@EndpointParam URI queue);\n\n}\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/SQSApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs;\n\nimport static org.jclouds.aws.reference.AWSConstants.PROPERTY_AUTH_TAG;\nimport static org.jclouds.aws.reference.AWSConstants.PROPERTY_HEADER_TAG;\nimport static org.jclouds.sqs.config.SQSProperties.CREATE_QUEUE_MAX_RETRIES;\nimport static org.jclouds.sqs.config.SQSProperties.CREATE_QUEUE_RETRY_INTERVAL;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.rest.internal.BaseHttpApiMetadata;\nimport org.jclouds.sqs.config.SQSHttpApiModule;\n\nimport com.google.auto.service.AutoService;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n/**\n * Implementation of {@link ApiMetadata} for Amazon's Simple Queue Service api.\n */\n@AutoService(ApiMetadata.class)\npublic class SQSApiMetadata extends BaseHttpApiMetadata {\n   \n   @Override\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromApiMetadata(this);\n   }\n\n   public SQSApiMetadata() {\n      this(new ConcreteBuilder());\n   }\n\n   protected SQSApiMetadata(Builder<?> builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = BaseHttpApiMetadata.defaultProperties();\n      properties.setProperty(CREATE_QUEUE_MAX_RETRIES, \"60\");\n      properties.setProperty(CREATE_QUEUE_RETRY_INTERVAL, \"1000\");\n      properties.setProperty(PROPERTY_AUTH_TAG, \"AWS\");\n      properties.setProperty(PROPERTY_HEADER_TAG, \"amz\");\n      return properties;\n   }\n   \n   public abstract static class Builder<T extends Builder<T>> extends BaseHttpApiMetadata.Builder<SQSApi, T> {\n\n      protected Builder() {\n         id(\"sqs\")\n         .name(\"Amazon Simple Queue Service API\")\n         .identityName(\"Access Key ID\")\n         .credentialName(\"Secret Access Key\")\n         .version(\"2011-10-01\")\n         .defaultProperties(SQSApiMetadata.defaultProperties())\n         .defaultEndpoint(\"https://sqs.us-east-1.amazonaws.com\")\n         .documentation(URI.create(\"http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/APIReference\"))\n         .defaultModules(ImmutableSet.<Class<? extends Module>>of(SQSHttpApiModule.class));\n      }\n\n      @Override\n      public SQSApiMetadata build() {\n         return new SQSApiMetadata(this);\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/binders/BindAttributeNamesToIndexedFormParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.binders;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableMultimap.Builder;\n\n/**\n * Binds the Iterable<String> to form parameters named with AttributeName.index\n */\n@Singleton\npublic class BindAttributeNamesToIndexedFormParams implements Binder {\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      Iterable<?> values = Iterable.class.cast(checkNotNull(input, \"attributeNames\"));\n      Builder<String, String> builder = ImmutableMultimap.builder();\n      int i = 0;\n      for (Object o : values) {\n         builder.put(\"AttributeName.\" + (i++ + 1), o.toString());\n      }\n      ImmutableMultimap<String, String> forms = builder.build();\n      return (R) (forms.isEmpty() ? request : request.toBuilder().replaceFormParams(forms).build());\n   }\n\n}\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/binders/BindChangeMessageVisibilityBatchRequestEntryToIndexedFormParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.binders;\n\nimport java.util.Map;\n\nimport org.jclouds.aws.binders.BindTableToIndexedFormParams;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.MapBinder;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableTable;\nimport com.google.common.collect.ImmutableTable.Builder;\nimport com.google.common.collect.Maps;\n\npublic class BindChangeMessageVisibilityBatchRequestEntryToIndexedFormParams extends BindTableToIndexedFormParams\n      implements MapBinder {\n\n   protected BindChangeMessageVisibilityBatchRequestEntryToIndexedFormParams() {\n      super(\"ChangeMessageVisibilityBatchRequestEntry.%d.Id\",\n            \"ChangeMessageVisibilityBatchRequestEntry.%d.ReceiptHandle\",\n            \"ChangeMessageVisibilityBatchRequestEntry.%d.VisibilityTimeout\");\n   }\n\n   public Map<String, String> idReceiptHandle(Iterable<String> input) {\n      return Maps.uniqueIndex(input, new Function<String, String>() {\n         int index = 1;\n\n         @Override\n         public String apply(String input) {\n            return index++ + \"\";\n         }\n      });\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      Map<String, String> idReceiptHandle = (Map<String, String>) postParams.get(\"idReceiptHandle\");\n      if (idReceiptHandle == null) {\n         idReceiptHandle = idReceiptHandle((Iterable<String>) postParams.get(\"receiptHandles\"));\n      }\n      int visibilityTimeout = (Integer) postParams.get(\"visibilityTimeout\");\n\n      Builder<Object, Object, Object> builder = ImmutableTable.builder();\n      for (Map.Entry<?, ?> entry : idReceiptHandle.entrySet())\n         builder.put(entry.getKey(), entry.getValue(), visibilityTimeout);\n      return bindToRequest(request, (Object) builder.build());\n   }\n}\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/binders/BindDeleteMessageBatchRequestEntryToIndexedFormParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.binders;\n\nimport org.jclouds.aws.binders.BindMapToIndexedFormParams;\n\npublic class BindDeleteMessageBatchRequestEntryToIndexedFormParams extends BindMapToIndexedFormParams {\n\n   protected BindDeleteMessageBatchRequestEntryToIndexedFormParams() {\n      super(\"DeleteMessageBatchRequestEntry.%d.Id\", \"DeleteMessageBatchRequestEntry.%d.ReceiptHandle\");\n   }\n}\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/binders/BindSendMessageBatchRequestEntryToIndexedFormParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.binders;\n\nimport org.jclouds.aws.binders.BindMapToIndexedFormParams;\n\npublic class BindSendMessageBatchRequestEntryToIndexedFormParams extends BindMapToIndexedFormParams {\n\n   protected BindSendMessageBatchRequestEntryToIndexedFormParams() {\n      super(\"SendMessageBatchRequestEntry.%d.Id\", \"SendMessageBatchRequestEntry.%d.MessageBody\");\n   }\n}\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/binders/BindSendMessageBatchRequestEntryWithDelaysToIndexedFormParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.binders;\n\nimport java.util.Map;\n\nimport org.jclouds.aws.binders.BindTableToIndexedFormParams;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.MapBinder;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableTable;\nimport com.google.common.collect.ImmutableTable.Builder;\nimport com.google.common.collect.Maps;\n\npublic class BindSendMessageBatchRequestEntryWithDelaysToIndexedFormParams extends BindTableToIndexedFormParams\n      implements MapBinder {\n\n   protected BindSendMessageBatchRequestEntryWithDelaysToIndexedFormParams() {\n      super(\"SendMessageBatchRequestEntry.%d.Id\", \"SendMessageBatchRequestEntry.%d.MessageBody\",\n            \"SendMessageBatchRequestEntry.%d.DelaySeconds\");\n   }\n\n   public Map<String, String> idMessageBody(Iterable<String> input) {\n      return Maps.uniqueIndex(input, new Function<String, String>() {\n         int index = 1;\n\n         @Override\n         public String apply(String input) {\n            return index++ + \"\";\n         }\n      });\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      Map<String, String> idMessageBody = (Map<String, String>) postParams.get(\"idMessageBody\");\n      if (idMessageBody == null) {\n         idMessageBody = idMessageBody((Iterable<String>) postParams.get(\"messageBodies\"));\n      }\n      int delaySeconds = (Integer) postParams.get(\"delaySeconds\");\n\n      Builder<Object, Object, Object> builder = ImmutableTable.builder();\n      for (Map.Entry<?, ?> entry : idMessageBody.entrySet())\n         builder.put(entry.getKey(), entry.getValue(), delaySeconds);\n      return bindToRequest(request, (Object) builder.build());\n   }\n}\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/config/SQSHttpApiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.config;\n\n\n\n\nimport org.jclouds.aws.config.FormSigningHttpApiModule;\nimport org.jclouds.aws.handlers.AWSServerErrorRetryHandler;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpRetryHandler;\nimport org.jclouds.http.annotation.ClientError;\nimport org.jclouds.http.annotation.Redirection;\nimport org.jclouds.http.annotation.ServerError;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.sqs.SQSApi;\nimport org.jclouds.sqs.handlers.ParseSQSErrorFromXmlContent;\nimport org.jclouds.sqs.handlers.SQSErrorRetryHandler;\n\n\n/**\n * Configures the SQS connection.\n */\n@ConfiguresHttpApi\npublic class SQSHttpApiModule extends FormSigningHttpApiModule<SQSApi> {\n\n   public SQSHttpApiModule() {\n      super(SQSApi.class);\n   }\n   \n   @Override\n   protected void bindErrorHandlers() {\n      bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(ParseSQSErrorFromXmlContent.class);\n      bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(ParseSQSErrorFromXmlContent.class);\n      bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(ParseSQSErrorFromXmlContent.class);\n   }\n\n   @Override\n   protected void bindRetryHandlers() {\n      bind(HttpRetryHandler.class).annotatedWith(ClientError.class).to(SQSErrorRetryHandler.class);\n      bind(HttpRetryHandler.class).annotatedWith(ServerError.class).to(AWSServerErrorRetryHandler.class);\n   }\n\n}\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/config/SQSProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.config;\n\n\n/**\n * Configuration properties and constants used in SQS connections.\n */\npublic final class SQSProperties {\n\n   /**\n    * Integer property.\n    * <p/>\n    * When creating a queue, you can encounter\n    * {@code AWS.SimpleQueueService.QueueDeletedRecently}, which is typically a\n    * resolvable error. default tries are 60,\n    */\n   public static final String CREATE_QUEUE_MAX_RETRIES = \"jclouds.sqs.create-queue.max-retries\";\n\n   /**\n    * Long property.\n    * <p/>\n    * When creating a queue, you can encounter\n    * {@code AWS.SimpleQueueService.QueueDeletedRecently}, which is typically a\n    * resolvable error. default interval between tries is 1000 milliseconds (1\n    * second).\n    */\n   public static final String CREATE_QUEUE_RETRY_INTERVAL = \"jclouds.sqs.create-queue.retry-interval\";\n\n   private SQSProperties() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/domain/Action.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.domain;\n\nimport com.google.common.base.CaseFormat;\n\n/**\n * \n * The action you want to allow for the specified principal.\n * \n * @see <a href=\n *      \"http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/acp-overview.html#PermissionTypes\"\n *      />\n */\npublic enum Action {\n   /**\n    * This permission type grants the following actions to a principal on a\n    * shared queue: receive messages, send messages, delete messages, change a\n    * message's visibility, get a queue's attributes.\n    */\n   ALL,\n   /**\n    * This grants permission to receive messages in the queue.\n    */\n   RECEIVE_MESSAGE,\n   /**\n    * This grants permission to send messages to the queue. SendMessageBatch\n    * inherits permissions associated with SendMessage.\n    */\n   SEND_MESSAGE,\n   /**\n    * This grants permission to delete messages from the queue.\n    * DeleteMessageBatch inherits permissions associated with DeleteMessage.\n    */\n   DELETE_MESSAGE,\n   /**\n    * This grants permission to extend or terminate the read lock timeout of a\n    * specified message. ChangeMessageVisibilityBatch inherits permissions\n    * associated with ChangeMessageVisibility. For more information about\n    * visibility timeout, see Visibility Timeout. For more information about\n    * this permission type, see the ChangeMessageVisibility operation.\n    */\n   CHANGE_MESSAGE_VISIBILITY,\n   /**\n    * This grants permission to receive all of the queue attributes except the\n    * policy, which can only be accessed by the queue's owner. For more\n    * information, see the GetQueueAttributes operation.\n    */\n   GET_QUEUE_ATTRIBUTES,\n   /**\n    * This grants permission to get the url of a queue by name.\n    */\n   GET_QUEUE_URL;\n\n   public String value() {\n      return this == ALL ? \"*\" : CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name());\n   }\n\n   @Override\n   public String toString() {\n      return value();\n   }\n}\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/domain/Attribute.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.domain;\n\n/**\n * \n * The action you want to allow for the specified principal.\n * \n * @see <a href=\n *      \"http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/acp-overview.html#PermissionTypes\"\n *      />\n */\npublic final class Attribute {\n\n   /**\n    * approximate number of visible messages in a queue.\n    */\n   public static final String APPROXIMATE_NUMBER_OF_MESSAGES = \"ApproximateNumberOfMessages\";\n   /**\n    * approximate number of messages that are not timed-out and not deleted.\n    */\n   public static final String APPROXIMATE_NUMBER_OF_MESSAGES_NOT_VISIBLE = \"ApproximateNumberOfMessagesNotVisible\";\n\n   /**\n    * approximate number of messages that are not visible because you have set a\n    * positive delay value on the queue\n    */\n   public static final String APPROXIMATE_NUMBER_OF_MESSAGES_DELAYED = \"ApproximateNumberOfMessagesDelayed\";\n\n   /**\n    * visibility timeout for the queue.\n    */\n   public static final String VISIBILITY_TIMEOUT = \"VisibilityTimeout\";\n\n   /**\n    * time when the queue was created (epoch time in seconds).\n    */\n   public static final String CREATED_TIMESTAMP = \"CreatedTimestamp\";\n\n   /**\n    * time when the queue was last changed (epoch time in seconds).\n    */\n   public static final String LAST_MODIFIED_TIMESTAMP = \"LastModifiedTimestamp\";\n\n   /**\n    * queue's policy.\n    */\n   public static final String POLICY = \"Policy\";\n\n   /**\n    * limit of how many bytes a message can contain before Amazon SQS rejects\n    * it.\n    */\n   public static final String MAXIMUM_MESSAGE_SIZE = \"MaximumMessageSize\";\n\n   /**\n    * number of seconds Amazon SQS retains a message.\n    */\n   public static final String MESSAGE_RETENTION_PERIOD = \"MessageRetentionPeriod\";\n\n   /**\n    * queue's Amazon resource name (ARN).\n    */\n   public static final String QUEUE_ARN = \"QueueArn\";\n\n   /**\n    * The time in seconds that the delivery of all messages in the queue will be\n    * delayed.\n    */\n   public static final String DELAY_SECONDS = \"DelaySeconds\";\n\n   private Attribute() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/domain/BatchError.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\n/**\n * \n * @see <a\n *      href=\"http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/APIReference/Query_QueryDeleteMessageBatch.html\"\n *      >doc</a>\n */\npublic class BatchError {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().fromErrorEntry(this);\n   }\n\n   public static class Builder {\n\n      private String id;\n      private boolean senderFault;\n      private String code;\n      private String message;\n\n      /**\n       * @see BatchError#getId()\n       */\n      public Builder id(String id) {\n         this.id = id;\n         return this;\n      }\n\n      /**\n       * @see BatchError#isSenderFault()\n       */\n      public Builder senderFault(boolean senderFault) {\n         this.senderFault = senderFault;\n         return this;\n      }\n\n      /**\n       * @see BatchError#getCode()\n       */\n      public Builder code(String code) {\n         this.code = code;\n         return this;\n      }\n\n      /**\n       * @see BatchError#getMessage()\n       */\n      public Builder message(String message) {\n         this.message = message;\n         return this;\n      }\n\n      public BatchError build() {\n         return new BatchError(id, senderFault, code, message);\n      }\n\n      public Builder fromErrorEntry(BatchError in) {\n         return id(in.getId()).senderFault(in.isSenderFault()).code(in.getCode()).message(in.getMessage());\n      }\n   }\n\n   private final String id;\n   private final boolean senderFault;\n   private final String code;\n   private final String message;\n\n   private BatchError(String id, boolean senderFault, String code, String message) {\n      this.id = checkNotNull(id, \"id\");\n      this.senderFault = senderFault;\n      this.code = checkNotNull(code, \"code of %s\", id);\n      this.message = checkNotNull(message, \"message of %s\", id);\n   }\n\n   /**\n    * The Id name that you assigned to the message.\n    */\n   public String getId() {\n      return id;\n   }\n\n   /**\n    * \n    */\n   public boolean isSenderFault() {\n      return senderFault;\n   }\n\n   /**\n    * A short string description of the error.\n    */\n   public String getCode() {\n      return code;\n   }\n\n   /**\n    * A description of the error.\n    */\n   public String getMessage() {\n      return message;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      BatchError that = BatchError.class.cast(obj);\n      return Objects.equal(this.id, that.id);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"id\", id).add(\"senderFault\", senderFault)\n            .add(\"message\", message).add(\"code\", code).toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/domain/BatchResult.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ForwardingMap;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Maps;\n\n/**\n * \n * @see <a\n *      href=\"http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/MessageLifecycle.html\"\n *      >doc</a>\n */\npublic class BatchResult<V> extends ForwardingMap<String, V> {\n\n   public static <V> Builder<V> builder() {\n      return new Builder<V>();\n   }\n\n   public Builder<V> toBuilder() {\n      return BatchResult.<V> builder().fromBatchResult(this);\n   }\n\n   public static class Builder<V> {\n\n      private ImmutableMap.Builder<String, V> results = ImmutableMap.<String, V> builder();\n      private ImmutableSet.Builder<BatchError> errors = ImmutableSet.<BatchError> builder();\n\n      /**\n       * @see BatchResult#getErrors()\n       */\n      public Builder<V> addError(BatchError error) {\n         this.errors.add(checkNotNull(error, \"error\"));\n         return this;\n      }\n\n      /**\n       * @see BatchResult#getErrors()\n       */\n      public Builder<V> errors(Iterable<BatchError> errors) {\n         this.errors = ImmutableSet.<BatchError> builder().addAll(checkNotNull(errors, \"errors\"));\n         return this;\n      }\n\n      /**\n       * @see BatchResult#get\n       */\n      public Builder<V> putAll(Map<String, V> results) {\n         this.results.putAll(checkNotNull(results, \"results\"));\n         return this;\n      }\n\n      /**\n       * @see BatchResult#get\n       */\n      public Builder<V> put(String name, V value) {\n         this.results.put(checkNotNull(name, \"name\"), checkNotNull(value, \"value\"));\n         return this;\n      }\n\n      public BatchResult<V> build() {\n         return new BatchResult<V>(results.build(), errors.build());\n      }\n\n      public Builder<V> fromBatchResult(BatchResult<V> in) {\n         return putAll(in).errors(in.getErrors().values());\n      }\n   }\n\n   private final Map<String, V> results;\n   private final Map<String, BatchError> errors;\n\n   private BatchResult(Map<String, V> results, Iterable<BatchError> errors) {\n      this.results = ImmutableMap.copyOf(checkNotNull(results, \"results\"));\n      this.errors = Maps.uniqueIndex(checkNotNull(errors, \"errors\"), new Function<BatchError, String>() {\n         @Override\n         public String apply(BatchError in) {\n            return in.getId();\n         }\n\n      });\n   }\n\n   @Override\n   protected Map<String, V> delegate() {\n      return results;\n   }\n\n   /**\n    * Errors indexed by requestor supplied id\n    */\n   public Map<String, BatchError> getErrors() {\n      return errors;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(results, errors);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      @SuppressWarnings(\"unchecked\")\n      BatchResult<V> that = BatchResult.class.cast(obj);\n      return Objects.equal(this.results, that.results) && Objects.equal(this.errors, that.errors);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"results\", results).add(\"errors\", errors).toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/domain/Message.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.hash.HashCode;\n\n/**\n * \n * @see <a\n *      href=\"http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/MessageLifecycle.html\"\n *      >doc</a>\n */\npublic class Message {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().fromMessage(this);\n   }\n\n   public static class Builder {\n\n      private String id;\n      private String body;\n      private String receiptHandle;\n      private HashCode md5;\n      private ImmutableMap.Builder<String, String> attributes = ImmutableMap.<String, String> builder();\n\n      /**\n       * @see Message#getId()\n       */\n      public Builder id(String id) {\n         this.id = id;\n         return this;\n      }\n\n      /**\n       * @see Message#getBody()\n       */\n      public Builder body(String body) {\n         this.body = body;\n         return this;\n      }\n\n      /**\n       * @see Message#getReceiptHandle()\n       */\n      public Builder receiptHandle(String receiptHandle) {\n         this.receiptHandle = receiptHandle;\n         return this;\n      }\n\n      /**\n       * @see Message#getMD5()\n       */\n      public Builder md5(HashCode md5) {\n         this.md5 = md5;\n         return this;\n      }\n\n      /**\n       * @see Message#getAttributes()\n       */\n      public Builder attributes(Map<String, String> attributes) {\n         this.attributes.putAll(checkNotNull(attributes, \"attributes\"));\n         return this;\n      }\n\n      /**\n       * @see Message#getAttributes()\n       */\n      public Builder addAttribute(String name, String value) {\n         this.attributes.put(checkNotNull(name, \"name\"), checkNotNull(value, \"value\"));\n         return this;\n      }\n\n      public Message build() {\n         return new Message(id, body, receiptHandle, md5, attributes.build());\n      }\n\n      public Builder fromMessage(Message in) {\n         return id(in.getId()).body(in.getBody()).receiptHandle(in.getReceiptHandle()).md5(in.getMD5())\n               .attributes(in.getAttributes());\n      }\n   }\n\n   private final String id;\n   private final String body;\n   private final String receiptHandle;\n   private final HashCode md5;\n   private final Map<String, String> attributes;\n\n   private Message(String id, String body, String receiptHandle, HashCode md5, Map<String, String> attributes) {\n      this.id = checkNotNull(id, \"id\");\n      this.body = checkNotNull(body, \"body of %s\", id);\n      this.receiptHandle = checkNotNull(receiptHandle, \"receiptHandle of %s\", id);\n      this.md5 = checkNotNull(md5, \"md5 of %s\", id);\n      this.attributes = ImmutableMap.copyOf(checkNotNull(attributes, \"attributes of %s\", id));\n   }\n\n   /**\n    * The message's SQS-assigned ID.\n    */\n   public String getId() {\n      return id;\n   }\n\n   /**\n    * The message's contents (not URL encoded)\n    */\n   public String getBody() {\n      return body;\n   }\n\n   /**\n    * A string associated with a specific instance of receiving the message.\n    */\n   public String getReceiptHandle() {\n      return receiptHandle;\n   }\n\n   /**\n    * An MD5 digest of the non-URL-encoded message body string\n    */\n   public HashCode getMD5() {\n      return md5;\n   }\n\n   /**\n    * Attributes of the queue\n    */\n   public Map<String, String> getAttributes() {\n      return attributes;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      Message that = Message.class.cast(obj);\n      return Objects.equal(this.id, that.id);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"id\", id).add(\"body\", body).add(\"md5\", md5)\n            .add(\"receiptHandle\", receiptHandle).add(\"attributes\", attributes).toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/domain/MessageIdAndMD5.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.hash.HashCode;\n\n/**\n * \n * @see <a\n *      href=\"http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/MessageLifecycle.html\"\n *      >doc</a>\n */\npublic class MessageIdAndMD5 {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().fromMessage(this);\n   }\n\n   public static class Builder {\n\n      private String id;\n      private HashCode md5;\n\n      /**\n       * @see MessageIdAndMD5#getId()\n       */\n      public Builder id(String id) {\n         this.id = id;\n         return this;\n      }\n\n      /**\n       * @see MessageIdAndMD5#getMD5()\n       */\n      public Builder md5(HashCode md5) {\n         this.md5 = md5;\n         return this;\n      }\n\n      public MessageIdAndMD5 build() {\n         return new MessageIdAndMD5(id, md5);\n      }\n\n      public Builder fromMessage(MessageIdAndMD5 in) {\n         return id(in.getId()).md5(in.getMD5());\n      }\n   }\n\n   private final String id;\n   private final HashCode md5;\n\n   private MessageIdAndMD5(String id, HashCode md5) {\n      this.id = checkNotNull(id, \"id\");\n      this.md5 = checkNotNull(md5, \"md5 of %s\", id);\n   }\n\n   /**\n    * The message's SQS-assigned ID.\n    */\n   public String getId() {\n      return id;\n   }\n\n   /**\n    * An MD5 digest of the non-URL-encoded message body string\n    */\n   public HashCode getMD5() {\n      return md5;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      MessageIdAndMD5 that = MessageIdAndMD5.class.cast(obj);\n      return Objects.equal(this.id, that.id);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"id\", id).add(\"md5\", md5).toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/domain/QueueAttributes.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Date;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.Optional;\n\n/**\n * \n * \n * @see <a href=\n *      \"http://docs.amazonwebservices.com/AWSSimpleQueueService/2011-10-01/APIReference/Query_QueryGetQueueAttributes.html\"\n *      />\n */\npublic class QueueAttributes {\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromQueueAttributes(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String queueArn;\n      protected long approximateNumberOfMessages;\n      protected long approximateNumberOfMessagesNotVisible;\n      protected long approximateNumberOfMessagesDelayed;\n      protected int visibilityTimeout;\n      protected Date createdTimestamp;\n      protected Date lastModifiedTimestamp;\n      protected Optional<String> rawPolicy = Optional.absent();\n      protected int maximumMessageSize;\n      protected int messageRetentionPeriod;\n      protected int delaySeconds;\n\n      /**\n       * @see QueueAttributes#getQueueArn()\n       */\n      public T queueArn(String queueArn) {\n         this.queueArn = queueArn;\n         return self();\n      }\n\n      /**\n       * @see QueueAttributes#getApproximateNumberOfMessages()\n       */\n      public T approximateNumberOfMessages(long approximateNumberOfMessages) {\n         this.approximateNumberOfMessages = approximateNumberOfMessages;\n         return self();\n      }\n\n      /**\n       * @see QueueAttributes#getApproximateNumberOfMessagesNotVisible()\n       */\n      public T approximateNumberOfMessagesNotVisible(long approximateNumberOfMessagesNotVisible) {\n         this.approximateNumberOfMessagesNotVisible = approximateNumberOfMessagesNotVisible;\n         return self();\n      }\n\n      /**\n       * @see QueueAttributes#getApproximateNumberOfMessagesDelayed()\n       */\n      public T approximateNumberOfMessagesDelayed(long approximateNumberOfMessagesDelayed) {\n         this.approximateNumberOfMessagesDelayed = approximateNumberOfMessagesDelayed;\n         return self();\n      }\n\n      /**\n       * @see QueueAttributes#getVisibilityTimeout()\n       */\n      public T visibilityTimeout(int visibilityTimeout) {\n         this.visibilityTimeout = visibilityTimeout;\n         return self();\n      }\n\n      /**\n       * @see QueueAttributes#getCreatedTimestamp()\n       */\n      public T createdTimestamp(Date createdTimestamp) {\n         this.createdTimestamp = createdTimestamp;\n         return self();\n      }\n\n      /**\n       * @see QueueAttributes#getLastModifiedTimestamp()\n       */\n      public T lastModifiedTimestamp(Date lastModifiedTimestamp) {\n         this.lastModifiedTimestamp = lastModifiedTimestamp;\n         return self();\n      }\n\n      /**\n       * @see QueueAttributes#getRawPolicy()\n       */\n      public T rawPolicy(String rawPolicy) {\n         this.rawPolicy = Optional.fromNullable(rawPolicy);\n         return self();\n      }\n\n      /**\n       * @see QueueAttributes#getMaximumMessageSize()\n       */\n      public T maximumMessageSize(int maximumMessageSize) {\n         this.maximumMessageSize = maximumMessageSize;\n         return self();\n      }\n\n      /**\n       * @see QueueAttributes#getMessageRetentionPeriod()\n       */\n      public T messageRetentionPeriod(int messageRetentionPeriod) {\n         this.messageRetentionPeriod = messageRetentionPeriod;\n         return self();\n      }\n\n      /**\n       * @see QueueAttributes#getDelaySeconds()\n       */\n      public T delaySeconds(int delaySeconds) {\n         this.delaySeconds = delaySeconds;\n         return self();\n      }\n\n      public QueueAttributes build() {\n         return new QueueAttributes(queueArn, approximateNumberOfMessages, approximateNumberOfMessagesNotVisible,\n               approximateNumberOfMessagesDelayed, visibilityTimeout, createdTimestamp, lastModifiedTimestamp,\n               rawPolicy, maximumMessageSize, messageRetentionPeriod, delaySeconds);\n      }\n\n      public T fromQueueAttributes(QueueAttributes in) {\n         return queueArn(in.queueArn).approximateNumberOfMessages(in.approximateNumberOfMessages)\n               .approximateNumberOfMessagesNotVisible(in.approximateNumberOfMessagesNotVisible)\n               .approximateNumberOfMessagesDelayed(in.approximateNumberOfMessagesDelayed)\n               .visibilityTimeout(in.visibilityTimeout).createdTimestamp(in.createdTimestamp)\n               .lastModifiedTimestamp(in.lastModifiedTimestamp).rawPolicy(in.rawPolicy.orNull())\n               .maximumMessageSize(in.maximumMessageSize).messageRetentionPeriod(in.messageRetentionPeriod)\n               .delaySeconds(in.delaySeconds);\n\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   protected final long approximateNumberOfMessages;\n   protected final long approximateNumberOfMessagesNotVisible;\n   protected final int visibilityTimeout;\n   protected final Date createdTimestamp;\n   protected final Date lastModifiedTimestamp;\n   protected final long approximateNumberOfMessagesDelayed;\n   protected final Optional<String> rawPolicy;\n   protected final int maximumMessageSize;\n   protected final int messageRetentionPeriod;\n   protected final String queueArn;\n   protected int delaySeconds;\n\n   protected QueueAttributes(String queueArn, long approximateNumberOfMessages,\n         long approximateNumberOfMessagesNotVisible, long approximateNumberOfMessagesDelayed, int visibilityTimeout,\n         Date createdTimestamp, Date lastModifiedTimestamp, Optional<String> rawPolicy, int maximumMessageSize,\n         int messageRetentionPeriod, int delaySeconds) {\n      this.queueArn = checkNotNull(queueArn, \"queueArn\");\n      this.approximateNumberOfMessages = approximateNumberOfMessages;\n      this.approximateNumberOfMessagesNotVisible = approximateNumberOfMessagesNotVisible;\n      this.approximateNumberOfMessagesDelayed = approximateNumberOfMessagesDelayed;\n      this.visibilityTimeout = visibilityTimeout;\n      this.createdTimestamp = checkNotNull(createdTimestamp, \"createdTimestamp of %s\", queueArn);\n      this.lastModifiedTimestamp = checkNotNull(lastModifiedTimestamp, \"lastModifiedTimestamp of %s\", queueArn);\n      this.rawPolicy = checkNotNull(rawPolicy, \"rawPolicy of %s\", queueArn);\n      this.maximumMessageSize = maximumMessageSize;\n      this.messageRetentionPeriod = messageRetentionPeriod;\n      this.delaySeconds = delaySeconds;\n   }\n\n   /**\n    * @see Attribute#QUEUE_ARN\n    */\n   public String getQueueArn() {\n      return queueArn;\n   }\n\n   /**\n    * @see Attribute#APPROXIMATE_NUMBER_OF_MESSAGES\n    */\n   public long getApproximateNumberOfMessages() {\n      return approximateNumberOfMessages;\n   }\n\n   /**\n    * @see Attribute#APPROXIMATE_NUMBER_OF_MESSAGES_NOT_VISIBLE\n    */\n   public long getApproximateNumberOfMessagesNotVisible() {\n      return approximateNumberOfMessagesNotVisible;\n   }\n\n   /**\n    * @see Attribute#APPROXIMATE_NUMBER_OF_MESSAGES_DELAYED\n    */\n   public long getApproximateNumberOfMessagesDelayed() {\n      return approximateNumberOfMessagesDelayed;\n   }\n\n   /**\n    * @see Attribute#VISIBILITY_TIMEOUT\n    */\n   public int getVisibilityTimeout() {\n      return visibilityTimeout;\n   }\n\n   /**\n    * @see Attribute#CREATED_TIMESTAMP\n    */\n   public Date getCreatedTimestamp() {\n      return createdTimestamp;\n   }\n\n   /**\n    * @see Attribute#LAST_MODIFIED_TIMESTAMP\n    */\n   public Date getLastModifiedTimestamp() {\n      return lastModifiedTimestamp;\n   }\n\n   /**\n    * Note this is in raw Json\n    * \n    * @see Attribute#POLICY\n    */\n   public Optional<String> getRawPolicy() {\n      return rawPolicy;\n   }\n\n   /**\n    * @see Attribute#MAXIMUM_MESSAGE_SIZE\n    */\n   public int getMaximumMessageSize() {\n      return maximumMessageSize;\n   }\n\n   /**\n    * @see Attribute#MESSAGE_RETENTION_PERIOD\n    */\n   public int getMessageRetentionPeriod() {\n      return messageRetentionPeriod;\n   }\n\n   /**\n    * @see Attribute#DELAY_SECONDS\n    */\n   public int getDelaySeconds() {\n      return delaySeconds;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(queueArn);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      QueueAttributes other = (QueueAttributes) obj;\n      return Objects.equal(this.queueArn, other.queueArn);\n\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"queueArn\", queueArn)\n            .add(\"approximateNumberOfMessages\", approximateNumberOfMessages)\n            .add(\"approximateNumberOfMessagesNotVisible\", approximateNumberOfMessagesNotVisible)\n            .add(\"approximateNumberOfMessagesDelayed\", approximateNumberOfMessagesDelayed)\n            .add(\"visibilityTimeout\", visibilityTimeout).add(\"createdTimestamp\", createdTimestamp)\n            .add(\"lastModifiedTimestamp\", lastModifiedTimestamp).add(\"rawPolicy\", rawPolicy.orNull())\n            .add(\"maximumMessageSize\", maximumMessageSize).add(\"messageRetentionPeriod\", messageRetentionPeriod)\n            .add(\"delaySeconds\", delaySeconds).toString();\n   }\n\n}\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/features/MessageApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.features;\n\nimport static org.jclouds.sqs.reference.SQSParameters.ACTION;\nimport static org.jclouds.sqs.reference.SQSParameters.VERSION;\n\nimport java.util.Map;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.FormParam;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\n\nimport org.jclouds.Constants;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.aws.filters.FormSigner;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.FormParams;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.VirtualHost;\nimport org.jclouds.rest.annotations.XMLResponseParser;\nimport org.jclouds.sqs.binders.BindChangeMessageVisibilityBatchRequestEntryToIndexedFormParams;\nimport org.jclouds.sqs.binders.BindDeleteMessageBatchRequestEntryToIndexedFormParams;\nimport org.jclouds.sqs.binders.BindSendMessageBatchRequestEntryToIndexedFormParams;\nimport org.jclouds.sqs.binders.BindSendMessageBatchRequestEntryWithDelaysToIndexedFormParams;\nimport org.jclouds.sqs.domain.BatchResult;\nimport org.jclouds.sqs.domain.Message;\nimport org.jclouds.sqs.domain.MessageIdAndMD5;\nimport org.jclouds.sqs.options.ReceiveMessageOptions;\nimport org.jclouds.sqs.options.SendMessageOptions;\nimport org.jclouds.sqs.xml.ChangeMessageVisibilityBatchResponseHandler;\nimport org.jclouds.sqs.xml.DeleteMessageBatchResponseHandler;\nimport org.jclouds.sqs.xml.MessageHandler;\nimport org.jclouds.sqs.xml.ReceiveMessageResponseHandler;\nimport org.jclouds.sqs.xml.RegexMessageIdAndMD5Handler;\nimport org.jclouds.sqs.xml.SendMessageBatchResponseHandler;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.Table;\n\n/**\n * Provides access to SQS via their REST API.\n * <p/>\n */\n@RequestFilters(FormSigner.class)\n@FormParams(keys = VERSION, values = \"{\" + Constants.PROPERTY_API_VERSION + \"}\")\n@VirtualHost\npublic interface MessageApi {\n\n   /**\n    * The DeleteMessage action deletes the specified message from the specified\n    * queue. You specify the message by using the message's receipt handle and\n    * not the message ID you received when you sent the message. Even if the\n    * message is locked by another reader due to the visibility timeout setting,\n    * it is still deleted from the queue. If you leave a message in the queue\n    * for more than 4 days, SQS automatically deletes it.\n    * \n    * <h4>Note</h4>\n    * \n    * The receipt handle is associated with a specific instance of receiving the\n    * message. If you receive a message more than once, the receipt handle you\n    * get each time you receive the message is different. When you request\n    * DeleteMessage, if you don't provide the most recently received receipt\n    * handle for the message, the request will still succeed, but the message\n    * might not be deleted.\n    * \n    * <h4>Important</h4>\n    * \n    * It is possible you will receive a message even after you have deleted it.\n    * This might happen on rare occasions if one of the servers storing a copy\n    * of the message is unavailable when you request to delete the message. The\n    * copy remains on the server and might be returned to you again on a\n    * subsequent receive request. You should create your system to be idempotent\n    * so that receiving a particular message more than once is not a problem.\n    * \n    * @param queue\n    *           the queue the message is in\n    * @param receiptHandle\n    *           The receipt handle associated with the message you want to\n    *           delete.\n    */\n   @Named(\"DeleteMessage\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DeleteMessage\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void delete(@FormParam(\"ReceiptHandle\") String receiptHandle);\n\n   /**\n    * Currently, you can send up to 10 {@link #delete} requests.\n    * \n    * <h4>Example usage</h4>\n    * \n    * <pre>\n    * BatchResult<String> results = api.delete(ImmutableMap.<String, String>builder()\n    *                                  .put(\"id1\", \"handle1\")\n    *                                  .put(\"id2\", \"handle2\")\n    *                                  .build());\n    * \n    * if (results.keySet().equals(ImmutableSet.of(\"id\", \"id2\"))\n    *    // all ok\n    * else\n    *   results.getErrors();\n    * </pre>\n    * \n    * @param idReceiptHandle\n    *           id for correlating the result to receipt handle\n    * @return result that contains success or errors of the operation\n    * @see #delete(String)\n    */\n   @Named(\"DeleteMessageBatch\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DeleteMessageBatch\")\n   @XMLResponseParser(DeleteMessageBatchResponseHandler.class)\n   BatchResult<String> delete(\n         @BinderParam(BindDeleteMessageBatchRequestEntryToIndexedFormParams.class) Map<String, String> idReceiptHandle);\n\n   /**\n    * Same as {@link #delete(Map)}, except that we generate numeric ids starting\n    * with {@code 1}\n    * \n    * @param receiptHandles\n    *           receipt handles to delete\n    * @see #delete(Map)\n    */\n   @Named(\"DeleteMessageBatch\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DeleteMessageBatch\")\n   @XMLResponseParser(DeleteMessageBatchResponseHandler.class)\n   BatchResult<String> delete(\n         @BinderParam(BindDeleteMessageBatchRequestEntryToIndexedFormParams.class) Iterable<String> receiptHandles);\n\n   /**\n    * The ChangeMessageVisibility action changes the visibility timeout of a\n    * specified message in a queue to a new value. The maximum allowed timeout\n    * value you can set the value to is 12 hours. This means you can't extend\n    * the timeout of a message in an existing queue to more than a total\n    * visibility timeout of 12 hours. (For more information visibility timeout,\n    * see Visibility Timeout in the Amazon SQS Developer Guide.)\n    * \n    * For example, let's say the timeout for the queue is 30 seconds, and you\n    * receive a message. Once you're 20 seconds into the timeout for that\n    * message (i.e., you have 10 seconds left), you extend it by 60 seconds by\n    * calling ChangeMessageVisibility with VisibilityTimeoutset to 60 seconds.\n    * You have then changed the remaining visibility timeout from 10 seconds to\n    * 60 seconds.\n    * \n    * <h4>Important</h4>\n    * \n    * If you attempt to set the VisibilityTimeout to an amount more than the\n    * maximum time left, Amazon SQS returns an error. It will not automatically\n    * recalculate and increase the timeout to the maximum time remaining.\n    * \n    * <h4>Important</h4>\n    * \n    * Unlike with a queue, when you change the visibility timeout for a specific\n    * message, that timeout value is applied immediately but is not saved in\n    * memory for that message. If you don't delete a message after it is\n    * received, the visibility timeout for the message the next time it is\n    * received reverts to the original timeout value, not the value you set with\n    * the ChangeMessageVisibility action.\n    * \n    * @param queue\n    *           the queue the message is in\n    * @param receiptHandle\n    *           The receipt handle associated with the message whose visibility\n    *           timeout you want to change. This parameter is returned by the\n    *           ReceiveMessage action.\n    * @param visibilityTimeout\n    *           The new value for the message's visibility timeout (in seconds)\n    *           from 0 to 43200 (maximum 12 hours)\n    */\n   @Named(\"ChangeMessageVisibility\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"ChangeMessageVisibility\")\n   void changeVisibility(@FormParam(\"ReceiptHandle\") String receiptHandle,\n         @FormParam(\"VisibilityTimeout\") int visibilityTimeout);\n\n   /**\n    * Currently, you can send up to 10 {@link #changeVisibility} requests.\n    * \n    * action. <h4>Example usage</h4>\n    * \n    * <pre>\n    * BatchResult<String> results = api.changeVisibility(ImmutableTable.<String, String, Integer>builder()\n    *                                  .put(\"id1\", \"handle1\", 45)\n    *                                  .put(\"id2\", \"handle2\", 10)\n    *                                  .build());\n    * \n    * if (results.keySet().equals(ImmutableSet.of(\"id\", \"id2\"))\n    *    // all ok\n    * else\n    *   results.getErrors();\n    * </pre>\n    * \n    * @param idReceiptHandleVisibilityTimeout\n    *           id for correlating the result, receipt handle, and visibility\n    *           timeout\n    * @return result that contains success or errors of the operation\n    * @see #changeVisibility(String, int)\n    */\n   @Named(\"ChangeMessageVisibilityBatch\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"ChangeMessageVisibilityBatch\")\n   @XMLResponseParser(ChangeMessageVisibilityBatchResponseHandler.class)\n   BatchResult<String> changeVisibility(\n         @BinderParam(BindChangeMessageVisibilityBatchRequestEntryToIndexedFormParams.class) Table<String, String, Integer> idReceiptHandleVisibilityTimeout);\n\n   /**\n    * Same as {@link #changeVisibility(Table)}, except that we generate numeric\n    * ids starting with {@code 1}\n    * \n    * @param receiptHandleVisibilityTimeout\n    *           receipt handle to visibility timeout\n    * @see #changeVisibility(Table)\n    */\n   @Named(\"ChangeMessageVisibilityBatch\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"ChangeMessageVisibilityBatch\")\n   @XMLResponseParser(ChangeMessageVisibilityBatchResponseHandler.class)\n   BatchResult<MessageIdAndMD5> changeVisibility(\n         @BinderParam(BindChangeMessageVisibilityBatchRequestEntryToIndexedFormParams.class) Map<String, Integer> receiptHandleVisibilityTimeout);\n\n   /**\n    * Currently, you can send up to 10 {@link #changeVisibility} requests.\n    * \n    * action. <h4>Example usage</h4>\n    * \n    * <pre>\n    * BatchResult<String> results = api.changeVisibility(ImmutableMap.<String, String>builder()\n    *                                  .put(\"id1\", \"handle1\")\n    *                                  .put(\"id2\", \"handle2\")\n    *                                  .build(), 45);\n    * \n    * if (results.keySet().equals(ImmutableSet.of(\"id\", \"id2\"))\n    *    // all ok\n    * else\n    *   results.getErrors();\n    * </pre>\n    * \n    * @param idReceiptHandle\n    *           id for correlating the result to receipt handle\n    * @param visibilityTimeout\n    *           The new value for the message's visibility timeout (in seconds).\n    * @return result that contains success or errors of the operation\n    * @see #changeVisibility(String, int)\n    */\n   @Named(\"ChangeMessageVisibilityBatch\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"ChangeMessageVisibilityBatch\")\n   @MapBinder(BindChangeMessageVisibilityBatchRequestEntryToIndexedFormParams.class)\n   @XMLResponseParser(ChangeMessageVisibilityBatchResponseHandler.class)\n   BatchResult<String> changeVisibility(\n         @PayloadParam(\"idReceiptHandle\") Map<String, String> idReceiptHandle,\n         @PayloadParam(\"visibilityTimeout\") int visibilityTimeout);\n\n   /**\n    * Same as {@link #changeVisibility(Map, int)}, except that we generate\n    * numeric ids starting with {@code 1}\n    * \n    * @param receiptHandles\n    *           receipt handles to change visibility\n    * @see #changeVisibility(Map, int)\n    */\n   @Named(\"ChangeMessageVisibilityBatch\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"ChangeMessageVisibilityBatch\")\n   @MapBinder(BindChangeMessageVisibilityBatchRequestEntryToIndexedFormParams.class)\n   @XMLResponseParser(ChangeMessageVisibilityBatchResponseHandler.class)\n   BatchResult<String> changeVisibility(\n         @PayloadParam(\"receiptHandles\") Iterable<String> receiptHandles,\n         @PayloadParam(\"visibilityTimeout\") int visibilityTimeout);\n\n   /**\n    * The SendMessage action delivers a message to the specified queue. The\n    * maximum allowed message size is 64 KB.\n    * \n    * <h4>Important</h4>\n    * \n    * The following list shows the characters (in Unicode) allowed in your\n    * message, according to the W3C XML specification (for more information, go\n    * to http://www.w3.org/TR/REC-xml/#charsets). If you send any characters not\n    * included in the list, your request will be rejected.\n    * \n    * \n    * {@code #x9 | #xA | #xD | [#x20 to #xD7FF] | [#xE000 to #xFFFD] | [#x10000 to #x10FFFF]}\n    * \n    * @param queue\n    *           queue you want to send to\n    * \n    * @param message\n    *           Type: String maximum 64 KB in size. For a list of allowed\n    *           characters, see the preceding important note.\n    * @return id of the message and md5 of the content sent\n    */\n   @Named(\"SendMessage\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"SendMessage\")\n   @ResponseParser(RegexMessageIdAndMD5Handler.class)\n   MessageIdAndMD5 send(@FormParam(\"MessageBody\") String message);\n\n   /**\n    * same as {@link #sendMessage(URI, String)} except you can control options\n    * such as delay seconds.\n    * \n    * @param options\n    *           options such as delay seconds\n    * @see #sendMessage(URI, String)\n    */\n   @Named(\"SendMessage\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"SendMessage\")\n   @ResponseParser(RegexMessageIdAndMD5Handler.class)\n   MessageIdAndMD5 send(@FormParam(\"MessageBody\") String message, SendMessageOptions options);\n\n   /**\n    * Same as {@link #send(Map)} except you can set a delay for each message in\n    * the request.\n    * \n    * <h4>Example usage</h4>\n    * \n    * <pre>\n    * BatchResult<? extends MessageIdAndMD5> results = api.sendWithDelays(ImmutableTable.<String, String, Integer>builder()\n    *                                  .put(\"id1\", \"test message one\", 1)\n    *                                  .put(\"id2\", \"test message two\", 10)\n    *                                  .build());\n    * \n    * if (results.keySet().equals(ImmutableSet.of(\"id\", \"id2\"))\n    *    // all ok\n    * else\n    *   results.getErrors();\n    * </pre>\n    * \n    * @param idMessageBodyDelaySeconds\n    *           id for correlating the result, message body, and delay seconds\n    * \n    * @return result that contains success or errors of the operation\n    * @see #send(String, SendMessageOptions)\n    */\n   @Named(\"SendMessageBatch\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"SendMessageBatch\")\n   @ResponseParser(RegexMessageIdAndMD5Handler.class)\n   @XMLResponseParser(SendMessageBatchResponseHandler.class)\n   BatchResult<? extends MessageIdAndMD5> sendWithDelays(\n         @BinderParam(BindSendMessageBatchRequestEntryWithDelaysToIndexedFormParams.class) Table<String, String, Integer> idMessageBodyDelaySeconds);\n\n   /**\n    * Same as {@link #sendWithDelays(Table)}, except that we generate numeric\n    * ids starting with {@code 1}\n    * \n    * @param messageBodyDelaySeconds\n    *           message body to the delay desired\n    * @see #sendWithDelays(Table)\n    */\n   @Named(\"SendMessageBatch\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"SendMessageBatch\")\n   @ResponseParser(RegexMessageIdAndMD5Handler.class)\n   @XMLResponseParser(SendMessageBatchResponseHandler.class)\n   BatchResult<? extends MessageIdAndMD5> sendWithDelays(\n         @BinderParam(BindSendMessageBatchRequestEntryWithDelaysToIndexedFormParams.class) Map<String, Integer> messageBodyDelaySeconds);\n\n   /**\n    * Same as {@link #send(Map)} except you set a delay for all messages in the\n    * request\n    * \n    * @param delaySeconds\n    *           The number of seconds to delay a specific message. Messages with\n    *           a positive DelaySeconds value become available for processing\n    *           after the delay time is finished.\n    * \n    * @see #send(String, SendMessageOptions)\n    */\n   @Named(\"SendMessageBatch\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"SendMessageBatch\")\n   @MapBinder(BindSendMessageBatchRequestEntryWithDelaysToIndexedFormParams.class)\n   @XMLResponseParser(SendMessageBatchResponseHandler.class)\n   BatchResult<? extends MessageIdAndMD5> sendWithDelay(\n         @PayloadParam(\"idMessageBody\") Map<String, String> idMessageBody,\n         @PayloadParam(\"delaySeconds\") int delaySeconds);\n\n   /**\n    * Same as {@link #sendWithDelay(Map, int)}, except that we generate numeric\n    * ids starting with {@code 1}\n    * \n    * @param messageBodies\n    *           message bodies to send\n    * @see #sendWithDelay(Map, int)\n    */\n   @Named(\"SendMessageBatch\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"SendMessageBatch\")\n   @MapBinder(BindSendMessageBatchRequestEntryWithDelaysToIndexedFormParams.class)\n   @XMLResponseParser(SendMessageBatchResponseHandler.class)\n   BatchResult<? extends MessageIdAndMD5> sendWithDelay(\n         @PayloadParam(\"messageBodies\") Iterable<String> messageBodies, @PayloadParam(\"delaySeconds\") int delaySeconds);\n\n   /**\n    * The SendMessageBatch action delivers up to ten messages to the specified\n    * queue. The maximum allowed individual message size is 64 KiB (65,536\n    * bytes).\n    * \n    * The maximum total payload size (i.e., the sum of all a batch's individual\n    * message lengths) is also 64 KiB (65,536 bytes).\n    * \n    * Currently, you can send up to 10 {@link #send} requests.\n    * \n    * action. <h4>Example usage</h4>\n    * \n    * <pre>\n    * BatchResult<? extends MessageIdAndMD5> results = api.send(ImmutableMap.<String, String>builder()\n    *                                  .put(\"id1\", \"test message one\")\n    *                                  .put(\"id2\", \"test message two\")\n    *                                  .build());\n    * \n    * if (results.keySet().equals(ImmutableSet.of(\"id\", \"id2\"))\n    *    // all ok\n    * else\n    *   results.getErrors();\n    * </pre>\n    * \n    * @param idMessageBody\n    *           id for correlating the result to message body\n    * \n    * @return result that contains success or errors of the operation\n    * @see #send(String)\n    */\n   @Named(\"SendMessageBatch\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"SendMessageBatch\")\n   @XMLResponseParser(SendMessageBatchResponseHandler.class)\n   BatchResult<? extends MessageIdAndMD5> send(\n         @BinderParam(BindSendMessageBatchRequestEntryToIndexedFormParams.class) Map<String, String> idMessageBody);\n\n   /**\n    * Same as {@link #send(Map)}, except that we generate numeric ids starting\n    * with {@code 1}\n    * \n    * @param messageBodies\n    *           message bodies to send\n    * @see #send(Map)\n    */\n   @Named(\"SendMessageBatch\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"SendMessageBatch\")\n   @XMLResponseParser(SendMessageBatchResponseHandler.class)\n   BatchResult<? extends MessageIdAndMD5> send(\n         @BinderParam(BindSendMessageBatchRequestEntryToIndexedFormParams.class) Iterable<String> messageBodies);\n\n   /**\n    * The ReceiveMessage action retrieves one or more messages from the\n    * specified queue. The ReceiveMessage action does not delete the message\n    * after it is retrieved. To delete a message, you must use the DeleteMessage\n    * action. For more information about message deletion in the message life\n    * cycle, see Message Lifecycle.\n    * \n    * <h4>Note</h4>\n    * \n    * Due to the distributed nature of the queue, a weighted random set of\n    * machines is sampled on a ReceiveMessage call. That means only the messages\n    * on the sampled machines are returned. If the number of messages in the\n    * queue is small (less than 1000), it is likely you will get fewer messages\n    * than you requested per ReceiveMessage call. If the number of messages in\n    * the queue is extremely small, you might not receive any messages in a\n    * particular ReceiveMessage response; in which case you should repeat the\n    * request.\n    * \n    * @param queue\n    *           from where you are receiving messages\n    * @return message including the receipt handle you can use to delete it\n    */\n   @Named(\"ReceiveMessage\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"ReceiveMessage\")\n   @XMLResponseParser(MessageHandler.class)\n   Message receive();\n\n   /**\n    * same as {@link #receive(URI)} except you can provide options like\n    * VisibilityTimeout parameter in your request, which will be applied to the\n    * messages that SQS returns in the response. If you do not include the\n    * parameter, the overall visibility timeout for the queue is used for the\n    * returned messages.\n    * \n    * @param options\n    *           options such as VisibilityTimeout\n    * @see #receive(URI)\n    */\n   @Named(\"ReceiveMessage\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"ReceiveMessage\")\n   @XMLResponseParser(MessageHandler.class)\n   Message receive(ReceiveMessageOptions options);\n\n   /**\n    * same as {@link #receive(URI)} except you can receive multiple messages.\n    * \n    * @param max\n    *           maximum messages to receive, current limit is 10\n    * @see #receive(URI)\n    */\n   @Named(\"ReceiveMessage\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"ReceiveMessage\")\n   @XMLResponseParser(ReceiveMessageResponseHandler.class)\n   FluentIterable<Message> receive(@FormParam(\"MaxNumberOfMessages\") int max);\n\n   /**\n    * same as {@link #receive(URI, int)} except you can provide options like\n    * VisibilityTimeout parameter in your request, which will be applied to the\n    * messages that SQS returns in the response. If you do not include the\n    * parameter, the overall visibility timeout for the queue is used for the\n    * returned messages.\n    * \n    * @param options\n    *           options such as VisibilityTimeout\n    * @see #receive(URI, int)\n    */\n   @Named(\"ReceiveMessage\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"ReceiveMessage\")\n   @XMLResponseParser(ReceiveMessageResponseHandler.class)\n   FluentIterable<Message> receive(@FormParam(\"MaxNumberOfMessages\") int max,\n         ReceiveMessageOptions options);\n\n}\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/features/Messages.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.features;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.sqs.domain.Message;\n\nimport com.google.common.base.Function;\n\n/**\n * Utilities for {@link Message}s\n */\npublic class Messages {\n   public static Function<Message, String> toReceiptHandle() {\n      return ToReceiptHandleFunction.INSTANCE;\n   }\n\n   // enum singleton pattern\n   private enum ToReceiptHandleFunction implements Function<Message, String> {\n      INSTANCE;\n\n      @Override\n      public String apply(Message o) {\n         return checkNotNull(o, \"message\").getReceiptHandle();\n      }\n\n      @Override\n      public String toString() {\n         return \"toReceiptHandle\";\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/features/PermissionApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.features;\n\nimport static org.jclouds.sqs.reference.SQSParameters.ACTION;\nimport static org.jclouds.sqs.reference.SQSParameters.VERSION;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.FormParam;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\n\nimport org.jclouds.Constants;\nimport org.jclouds.aws.filters.FormSigner;\nimport org.jclouds.rest.annotations.FormParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.VirtualHost;\nimport org.jclouds.sqs.domain.Action;\n\n/**\n * Provides access to SQS via their REST API.\n * <p/>\n */\n@RequestFilters(FormSigner.class)\n@FormParams(keys = VERSION, values = \"{\" + Constants.PROPERTY_API_VERSION + \"}\")\n@VirtualHost\npublic interface PermissionApi {\n\n   /**\n    * The AddPermission action adds a permission to a queue for a specific\n    * principal. This allows for sharing access to the queue.\n    * \n    * When you create a queue, you have full control access rights for the\n    * queue. Only you (as owner of the queue) can grant or deny permissions to\n    * the queue. For more information about these permissions, see Shared Queues\n    * in the Amazon SQS Developer Guide.\n    * \n    * Note\n    * \n    * AddPermission writes an SQS-generated policy. If you want to write your\n    * own policy, use SetQueueAttributes to upload your policy.\n    * \n    * @param queue\n    *           queue to change permissions on\n    * @param label\n    * \n    *           The unique identification of the permission you're setting.\n    *           example: AliceSendMessage\n    * \n    *           Constraints: Maximum 80 characters; alphanumeric characters,\n    *           hyphens (-), and underscores (_) are allowed.\n    * @param permission\n    *           The action you want to allow for the specified principal.\n    * @param accountId\n    *           The AWS account number of the principal who will be given\n    *           permission. The principal must have an AWS account, but does not\n    *           need to be signed up for Amazon SQS. For information about\n    *           locating the AWS account identification, see Your AWS\n    *           Identifiers in the Amazon SQS Developer Guide.\n    * \n    *           Constraints: Valid 12-digit AWS account number, without hyphens\n    * \n    */\n   @Named(\"AddPermission\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"AddPermission\")\n   void addPermissionToAccount(@FormParam(\"Label\") String label,\n         @FormParam(\"ActionName.1\") Action permission, @FormParam(\"AWSAccountId.1\") String accountId);\n\n   /**\n    * The RemovePermission action revokes any permissions in the queue policy\n    * that matches the Label parameter. Only the owner of the queue can remove\n    * permissions.\n    * \n    * @param queue\n    *           queue to change permissions on\n    * \n    * @param label\n    *           The identification of the permission you want to remove. This is\n    *           the label you added in AddPermission. example: AliceSendMessage\n    */\n   @Named(\"RemovePermission\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"RemovePermission\")\n   void remove(@FormParam(\"Label\") String label);\n\n}\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/features/QueueApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.features;\n\nimport static org.jclouds.sqs.reference.SQSParameters.ACTION;\nimport static org.jclouds.sqs.reference.SQSParameters.VERSION;\n\nimport java.net.URI;\nimport java.util.Map;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.FormParam;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\n\nimport org.jclouds.Constants;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.aws.filters.FormSigner;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.EndpointParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.FormParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.Transform;\nimport org.jclouds.rest.annotations.VirtualHost;\nimport org.jclouds.rest.annotations.XMLResponseParser;\nimport org.jclouds.sqs.binders.BindAttributeNamesToIndexedFormParams;\nimport org.jclouds.sqs.domain.QueueAttributes;\nimport org.jclouds.sqs.functions.MapToQueueAttributes;\nimport org.jclouds.sqs.options.CreateQueueOptions;\nimport org.jclouds.sqs.options.ListQueuesOptions;\nimport org.jclouds.sqs.xml.AttributesHandler;\nimport org.jclouds.sqs.xml.RegexListQueuesResponseHandler;\nimport org.jclouds.sqs.xml.RegexQueueHandler;\nimport org.jclouds.sqs.xml.ValueHandler;\n\nimport com.google.common.collect.FluentIterable;\n\n/**\n * Provides access to SQS via their REST API.\n * <p/>\n */\n@RequestFilters(FormSigner.class)\n@FormParams(keys = VERSION, values = \"{\" + Constants.PROPERTY_API_VERSION + \"}\")\n@VirtualHost\npublic interface QueueApi {\n\n   /**\n    * The ListQueues action returns a list of your queues. The maximum number of\n    * queues that can be returned is 1000. If you specify a value for the\n    * optional QueueNamePrefix parameter, only queues with a name beginning with\n    * the specified value are returned\n    * \n    * @param region\n    *           Queues are Region-specific.\n    * @param options\n    *           specify prefix or other options\n    * \n    * @see <a href=\n    *      \"http://docs.amazonwebservices.com/AWSSimpleQueueService/2011-10-01/APIReference/Query_QueryListQueues.html\"\n    *      />\n    */\n   @Named(\"ListQueues\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"ListQueues\")\n   @ResponseParser(RegexListQueuesResponseHandler.class)\n   FluentIterable<URI> list();\n\n   @Named(\"ListQueues\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"ListQueues\")\n   @ResponseParser(RegexListQueuesResponseHandler.class)\n   FluentIterable<URI> list(ListQueuesOptions options);\n\n   /**\n    * The GetQueueUrl action returns the Uniform Resource Locater (URL) of a\n    * queue. This action provides a simple way to retrieve the URL of an SQS\n    * queue.\n    * \n    * @param queueName\n    *           The name of an existing queue.\n    * @return uri of the queue or null if not found\n    */\n   @Named(\"GetQueueUrl\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"GetQueueUrl\")\n   @ResponseParser(RegexQueueHandler.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   URI get(@FormParam(\"QueueName\") String queueName);\n\n   /**\n    * like {@link #get(String)}, except specifying the owner of the queue.\n    * \n    * To access a queue that belongs to another AWS account, use the\n    * QueueOwnerAWSAccountId parameter to specify the account ID of the queue's\n    * owner. The queue's owner must grant you permission to access the queue.\n    * \n    * @param accountId\n    * @return The AWS account ID of the account that created the queue.\n    */\n   @Named(\"GetQueueUrl\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"GetQueueUrl\")\n   @ResponseParser(RegexQueueHandler.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   URI getInAccount(@FormParam(\"QueueName\") String queueName,\n         @FormParam(\"QueueOwnerAWSAccountId\") String accountId);\n\n   /**\n    * The CreateQueue action creates a new queue.\n    * \n    * When you request CreateQueue, you provide a name for the queue. To\n    * successfully create a new queue, you must provide a name that is unique\n    * within the scope of your own queues.\n    * \n    * <h4>Note</h4>\n    * \n    * This method will gracefully retry in case the queue name was recently taken.\n    * \n    * If you provide the name of an existing queue, along with the exact names\n    * and values of all the queue's attributes, CreateQueue returns the queue\n    * URL for the existing queue. If the queue name, attribute names, or\n    * attribute values do not match an existing queue, CreateQueue returns an\n    * error.\n    * \n    * <h4>Tip</h4>\n    * \n    * Use GetQueueUrl to get a queue's URL. GetQueueUrl requires only the\n    * QueueName parameter.\n    * \n    * @param region\n    *           Queues are Region-specific.\n    * @param queueName\n    *           The name to use for the queue created. Constraints: Maximum 80\n    *           characters; alphanumeric characters, hyphens (-), and\n    *           underscores (_) are allowed.\n    */\n   @Named(\"CreateQueue\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"CreateQueue\")\n   @ResponseParser(RegexQueueHandler.class)\n   URI create(@FormParam(\"QueueName\") String queueName);\n\n   /**\n    * same as {@link #create(String, String)} except you can\n    * control options such as delay seconds.\n    * \n    * @param options\n    *           options such as delay seconds\n    * @see #create(String, String)\n    */\n   @Named(\"CreateQueue\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"CreateQueue\")\n   @ResponseParser(RegexQueueHandler.class)\n   URI create(@FormParam(\"QueueName\") String queueName, CreateQueueOptions options);\n\n   /**\n    * The DeleteQueue action deletes the queue specified by the queue URL,\n    * regardless of whether the queue is empty. If the specified queue does not\n    * exist, SQS returns a successful response.\n    * \n    * <h4>Caution</h4>\n    * \n    * Use DeleteQueue with care; once you delete your queue, any messages in the\n    * queue are no longer available.\n    * \n    * When you delete a queue, the deletion process takes up to 60 seconds.\n    * Requests you send involving that queue during the 60 seconds might\n    * succeed. For example, a SendMessage request might succeed, but after the\n    * 60 seconds, the queue and that message you sent no longer exist. Also,\n    * when you delete a queue, you must wait at least 60 seconds before creating\n    * a queue with the same name.\n    * \n    * We reserve the right to delete queues that have had no activity for more\n    * than 30 days. For more information, see About SQS Queues in the Amazon SQS\n    * Developer Guide.\n    * \n    * @param queue\n    *           queue you want to delete\n    */\n   @Named(\"DeleteQueue\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DeleteQueue\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void delete(@EndpointParam URI queue);\n\n   /**\n    * returns all attributes of a queue.\n    * \n    * @param queue\n    *           queue to get the attributes of\n    */\n   @Named(\"GetQueueAttributes\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = { ACTION, \"AttributeName.1\" }, values = { \"GetQueueAttributes\", \"All\" })\n   @Transform(MapToQueueAttributes.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   @XMLResponseParser(AttributesHandler.class)\n   QueueAttributes getAttributes(@EndpointParam URI queue);\n\n   /**\n    * returns an attribute of a queue.\n    * \n    * @param queue\n    *           queue to get the attributes of\n    */\n   @Named(\"GetQueueAttributes\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"GetQueueAttributes\")\n   @XMLResponseParser(AttributesHandler.class)\n   Map<String, String> getAttributes(@EndpointParam URI queue,\n         @BinderParam(BindAttributeNamesToIndexedFormParams.class) Iterable<String> attributeNames);\n\n   /**\n    * returns an attribute of a queue.\n    * \n    * @param queue\n    *           queue to get the attributes of\n    */\n   @Named(\"GetQueueAttributes\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"GetQueueAttributes\")\n   @XMLResponseParser(ValueHandler.class)\n   String getAttribute(@EndpointParam URI queue, @FormParam(\"AttributeName.1\") String attributeName);\n\n   /**\n    * The SetQueueAttributes action sets one attribute of a queue per request.\n    * When you change a queue's attributes, the change can take up to 60 seconds\n    * to propagate throughout the SQS system.\n    * \n    * @param queue\n    *           queue to set the attribute on\n    * @param name\n    * \n    *           The name of the attribute you want to set.\n    * \n    *           VisibilityTimeout - The length of time (in seconds) that a\n    *           message received from a queue will be invisible to other\n    *           receiving components when they ask to receive messages. For more\n    *           information about VisibilityTimeout, see Visibility Timeout in\n    *           the Amazon SQS Developer Guide.\n    * \n    *           Policy - The formal description of the permissions for a\n    *           resource. For more information about Policy, see Basic Policy\n    *           Structure in the Amazon SQS Developer Guide.\n    * \n    *           MaximumMessageSize - The limit of how many bytes a message can\n    *           contain before Amazon SQS rejects it.\n    * \n    *           MessageRetentionPeriod - The number of seconds Amazon SQS\n    *           retains a message.\n    * \n    *           DelaySeconds - The time in seconds that the delivery of all\n    *           messages in the queue will be delayed.\n    * @param value\n    *           The value of the attribute you want to set. To delete a queue's\n    *           access control policy, set the policy to \"\".\n    * \n    *           Constraints: Constraints are specific for each value.\n    * \n    *           VisibilityTimeout - An integer from 0 to 43200 (12 hours). The\n    *           default for this attribute is 30 seconds.\n    * \n    *           Policy - A valid form-url-encoded policy. For more information\n    *           about policy structure, see Basic Policy Structure in the Amazon\n    *           SQS Developer Guide. For more information about\n    *           form-url-encoding, see\n    *           http://www.w3.org/MarkUp/html-spec/html-spec_8.html#SEC8.2.1.\n    * \n    *           MaximumMessageSize - An integer from 1024 bytes (1 KiB) up to\n    *           65536 bytes (64 KiB). The default for this attribute is 65536\n    *           (64 KiB).\n    * \n    *           MessageRetentionPeriod - Integer representing seconds, from 60\n    *           (1 minute) to 1209600 (14 days). The default for this attribute\n    *           is 345600 (4 days).\n    * \n    *           DelaySeconds - An integer from 0 to 900 (15 minutes). The\n    *           default for this attribute is 0.\n    */\n   @Named(\"SetQueueAttributes\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"SetQueueAttributes\")\n   void setAttribute(@EndpointParam URI queue, @FormParam(\"Attribute.Name\") String name,\n         @FormParam(\"Attribute.Value\") String value);\n\n}\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/functions/MapToQueueAttributes.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.functions;\n\nimport java.util.Date;\nimport java.util.Map;\n\nimport org.jclouds.sqs.domain.Attribute;\nimport org.jclouds.sqs.domain.QueueAttributes;\nimport org.jclouds.sqs.domain.QueueAttributes.Builder;\n\nimport com.google.common.base.Function;\n\n/**\n * Converts a Map to a typed QueueAttributes object\n */\npublic class MapToQueueAttributes implements Function<Map<String, String>, QueueAttributes> {\n\n   @Override\n   public QueueAttributes apply(Map<String, String> input) {\n      if (input == null)\n         return null;\n      Builder<?> builder = QueueAttributes.builder();\n      builder.queueArn(input.get(Attribute.QUEUE_ARN));\n      builder.approximateNumberOfMessages(Long.parseLong(input.get(Attribute.APPROXIMATE_NUMBER_OF_MESSAGES)));\n      builder.approximateNumberOfMessagesNotVisible(Long.parseLong(input\n            .get(Attribute.APPROXIMATE_NUMBER_OF_MESSAGES_NOT_VISIBLE)));\n      builder.approximateNumberOfMessagesDelayed(Long.parseLong(input\n            .get(Attribute.APPROXIMATE_NUMBER_OF_MESSAGES_DELAYED)));\n      builder.visibilityTimeout(Integer.parseInt(input.get(Attribute.VISIBILITY_TIMEOUT)));\n      builder.createdTimestamp(new Date(Long.parseLong(input.get(Attribute.CREATED_TIMESTAMP))));\n      builder.lastModifiedTimestamp(new Date(Long.parseLong(input.get(Attribute.LAST_MODIFIED_TIMESTAMP))));\n      builder.rawPolicy(input.get(Attribute.POLICY));\n      builder.maximumMessageSize(Integer.parseInt(input.get(Attribute.MAXIMUM_MESSAGE_SIZE)));\n      builder.messageRetentionPeriod(Integer.parseInt(input.get(Attribute.MESSAGE_RETENTION_PERIOD)));\n      builder.delaySeconds(Integer.parseInt(input.get(Attribute.DELAY_SECONDS)));\n      return builder.build();\n   }\n}\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/handlers/ParseSQSErrorFromXmlContent.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.handlers;\n\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.domain.AWSError;\nimport org.jclouds.aws.handlers.ParseAWSErrorFromXmlContent;\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rest.ResourceNotFoundException;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Singleton\npublic class ParseSQSErrorFromXmlContent extends ParseAWSErrorFromXmlContent {\n   protected Set<String> resourceNotFoundCodes = ImmutableSet.of(\"AWS.SimpleQueueService.NonExistentQueue\");\n   protected Set<String> illegalStateCodes = ImmutableSet.of(\"AWS.SimpleQueueService.QueueDeletedRecently\",\n         \"AWS.SimpleQueueService.QueueNameExists\");\n   protected Set<String> illegalArgumentCodes = ImmutableSet.of(\"InvalidAttributeName\", \"ReadCountOutOfRange\",\n         \"InvalidMessageContents\", \"MessageTooLong\");\n\n   @Inject\n   public ParseSQSErrorFromXmlContent(AWSUtils utils) {\n      super(utils);\n   }\n\n   @Override\n   protected Exception refineException(HttpCommand command, HttpResponse response, Exception exception, AWSError error,\n         String message) {\n      String errorCode = (error != null && error.getCode() != null) ? error.getCode() : null;\n      if (resourceNotFoundCodes.contains(errorCode))\n         exception = new ResourceNotFoundException(message, exception);\n      else if (illegalStateCodes.contains(errorCode))\n         exception = new IllegalStateException(message, exception);\n      else if (illegalArgumentCodes.contains(errorCode))\n         exception = new IllegalArgumentException(message, exception);\n      else\n         exception = super.refineException(command, response, exception, error, message);\n      return exception;\n   }\n}\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/handlers/SQSErrorRetryHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.handlers;\n\nimport static org.jclouds.sqs.config.SQSProperties.CREATE_QUEUE_MAX_RETRIES;\nimport static org.jclouds.sqs.config.SQSProperties.CREATE_QUEUE_RETRY_INTERVAL;\n\nimport java.util.Set;\nimport java.util.concurrent.TimeUnit;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.aws.domain.AWSError;\nimport org.jclouds.aws.handlers.AWSClientErrorRetryHandler;\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.annotation.ClientError;\nimport org.jclouds.http.handlers.BackoffLimitedRetryHandler;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.util.concurrent.Uninterruptibles;\nimport com.google.inject.Inject;\n\npublic class SQSErrorRetryHandler extends AWSClientErrorRetryHandler {\n\n   private final long retryInterval;\n   private final int maxTries;\n\n   @Inject\n   public SQSErrorRetryHandler(AWSUtils utils, BackoffLimitedRetryHandler backoffLimitedRetryHandler,\n         @ClientError Set<String> retryableCodes, @Named(CREATE_QUEUE_MAX_RETRIES) int maxTries,\n         @Named(CREATE_QUEUE_RETRY_INTERVAL) long retryInterval) {\n      super(utils, backoffLimitedRetryHandler, retryableCodes);\n      this.maxTries = maxTries;\n      this.retryInterval = retryInterval;\n   }\n\n   @VisibleForTesting\n   public boolean shouldRetryRequestOnError(HttpCommand command, HttpResponse response, AWSError error) {\n      if (\"AWS.SimpleQueueService.QueueDeletedRecently\".equals(error.getCode())) {\n         if (command.incrementFailureCount() - 1 < maxTries) {\n            Uninterruptibles.sleepUninterruptibly(retryInterval, TimeUnit.MILLISECONDS);\n            return true;\n         }\n         return false;\n      }\n      return super.shouldRetryRequestOnError(command, response, error);\n   }\n\n}\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/options/CreateQueueOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.options;\n\nimport java.util.Map;\nimport java.util.Map.Entry;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Multimap;\n\n/**\n * Options used to receive a message from a queue.\n *\n * @see <a\n *      href=\"http://docs.amazonwebservices.com/AWSSimpleQueueService/2011-10-01/APIReference/Query_QueryCreateQueue.html\"\n *      >docs</a>\n */\npublic class CreateQueueOptions extends BaseHttpRequestOptions implements Cloneable {\n\n   private ImmutableMap.Builder<String, String> attributes = ImmutableMap.<String, String> builder();\n\n   /**\n    * The duration (in seconds) that the received messages are hidden from\n    * subsequent retrieve requests after being retrieved by a CreateQueue\n    * request.\n    *\n    * @param visibilityTimeout\n    *           Constraints: 0 to 43200 (maximum 12 hours)\n    *\n    *           Default: The visibility timeout for the queue\n    */\n   public CreateQueueOptions visibilityTimeout(int visibilityTimeout) {\n      return attribute(\"VisibilityTimeout\", visibilityTimeout + \"\");\n   }\n\n   /**\n    */\n   public CreateQueueOptions attributes(Map<String, String> attributes) {\n      this.attributes = ImmutableMap.<String, String> builder().putAll(attributes);\n      return this;\n   }\n\n   /**\n    * @see #attributes\n    */\n   public CreateQueueOptions attribute(String name, String value) {\n      this.attributes.put(name, value);\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see CreateQueueOptions#visibilityTimeout\n       */\n      public static CreateQueueOptions visibilityTimeout(Integer visibilityTimeout) {\n         return new CreateQueueOptions().visibilityTimeout(visibilityTimeout);\n      }\n\n      /**\n       * @see CreateQueueOptions#attribute\n       */\n      public static CreateQueueOptions attribute(String name, String value) {\n         return new CreateQueueOptions().attribute(name, value);\n      }\n\n      /**\n       * @see CreateQueueOptions#attributes\n       */\n      public static CreateQueueOptions attributes(Map<String, String> attributes) {\n         return new CreateQueueOptions().attributes(attributes);\n      }\n   }\n\n   @Override\n   public Multimap<String, String> buildFormParameters() {\n      Multimap<String, String> params = super.buildFormParameters();\n      ImmutableMap<String, String> attributes = this.attributes.build();\n      if (!attributes.isEmpty()) {\n         int nameIndex = 1;\n         for (Entry<String, String> attribute : attributes.entrySet()) {\n            params.put(\"Attribute.\" + nameIndex + \".Name\", attribute.getKey());\n            params.put(\"Attribute.\" + nameIndex + \".Value\", attribute.getValue());\n            nameIndex++;\n         }\n      }\n      return params;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(attributes.build());\n   }\n\n   @Override\n   public CreateQueueOptions clone() {\n      return new CreateQueueOptions().attributes(attributes.build());\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      CreateQueueOptions other = CreateQueueOptions.class.cast(obj);\n      return Objects.equal(this.attributes.build(), other.attributes.build());\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String toString() {\n      ImmutableMap<String, String> attributes = this.attributes.build();\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"attributes\", !attributes.isEmpty() ? attributes : null)\n            .toString();\n   }\n}\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/options/ListQueuesOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\n/**\n * Contains options supported in the Form API for the ListQueues operation. <h2>\n * Usage</h2> The recommended way to instantiate a ListQueuesOptions object is to statically import\n * ListQueuesOptions.Builder.* and invoke a static creation method followed by an instance mutator\n * (if needed):\n * <p/>\n * <code>\n * import static org.jclouds.sqs.options.ListQueuesOptions.Builder.*\n * <p/>\n * SQSApi connection = // get connection\n * Set<Queue> queues = connection.listQueuesInRegion(queuePrefix(\"foo\"));\n * <code>\n * \n * @see <a\n *      href=\"http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/APIReference/Query_QueryListQueues.html\"\n *      />\n */\npublic class ListQueuesOptions extends BaseHttpRequestOptions {\n\n   /**\n    * String to use for filtering the list results. Only those queues whose name begins with the\n    * specified string are returned.\n    * \n    * @param prefix\n    *           Maximum 80 characters; alphanumeric characters, hyphens (-), and underscores (_) are\n    *           allowed.\n    */\n   public ListQueuesOptions queuePrefix(String prefix) {\n      formParameters.put(\"QueueNamePrefix\", prefix);\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see ListQueuesOptions#queuePrefix(String )\n       */\n      public static ListQueuesOptions queuePrefix(String prefix) {\n         ListQueuesOptions options = new ListQueuesOptions();\n         return options.queuePrefix(prefix);\n      }\n\n   }\n}\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/options/ReceiveMessageOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Multimap;\n\n/**\n * Options used to receive a message from a queue.\n *\n * @see <a\n *      href=\"http://docs.amazonwebservices.com/AWSSimpleQueueService/2011-10-01/APIReference/Query_QueryReceiveMessage.html\"\n *      >docs</a>\n */\npublic class ReceiveMessageOptions extends BaseHttpRequestOptions implements Cloneable {\n\n   private Integer visibilityTimeout;\n   private ImmutableSet.Builder<String> attributes = ImmutableSet.<String> builder();\n\n   /**\n    * The duration (in seconds) that the received messages are hidden from\n    * subsequent retrieve requests after being retrieved by a ReceiveMessage\n    * request.\n    *\n    * @param visibilityTimeout\n    *           Constraints: 0 to 43200 (maximum 12 hours)\n    *\n    *           Default: The visibility timeout for the queue\n    */\n   public ReceiveMessageOptions visibilityTimeout(Integer visibilityTimeout) {\n      this.visibilityTimeout = visibilityTimeout;\n      return this;\n   }\n\n   /**\n    * The attribute you want to get.\n    *\n    * All - returns all values.\n    *\n    * SenderId - returns the AWS account number (or the IP address, if anonymous\n    * access is allowed) of the sender.\n    *\n    * SentTimestamp - returns the time when the message was sent (epoch time in\n    * milliseconds).\n    *\n    * ApproximateReceiveCount - returns the number of times a message has been\n    * received but not deleted.\n    *\n    * ApproximateFirstReceiveTimestamp - returns the time when the message was\n    * first received (epoch time in milliseconds).\n    */\n   public ReceiveMessageOptions attributes(Iterable<String> attributes) {\n      this.attributes = ImmutableSet.<String> builder().addAll(attributes);\n      return this;\n   }\n\n   /**\n    * @see #attributes\n    */\n   public ReceiveMessageOptions attribute(String attribute) {\n      this.attributes.add(attribute);\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see ReceiveMessageOptions#visibilityTimeout\n       */\n      public static ReceiveMessageOptions visibilityTimeout(Integer visibilityTimeout) {\n         return new ReceiveMessageOptions().visibilityTimeout(visibilityTimeout);\n      }\n\n      /**\n       * @see ReceiveMessageOptions#attribute\n       */\n      public static ReceiveMessageOptions attribute(String attribute) {\n         return new ReceiveMessageOptions().attribute(attribute);\n      }\n\n      /**\n       * @see ReceiveMessageOptions#attributes\n       */\n      public static ReceiveMessageOptions attributes(Iterable<String> attributes) {\n         return new ReceiveMessageOptions().attributes(attributes);\n      }\n   }\n\n   @Override\n   public Multimap<String, String> buildFormParameters() {\n      Multimap<String, String> params = super.buildFormParameters();\n      if (visibilityTimeout != null)\n         params.put(\"VisibilityTimeout\", visibilityTimeout.toString());\n      ImmutableSet<String> attributes = this.attributes.build();\n      if (!attributes.isEmpty()) {\n         int nameIndex = 1;\n         for (String attribute : attributes) {\n            params.put(\"AttributeName.\" + nameIndex, attribute);\n            nameIndex++;\n         }\n      }\n      return params;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(visibilityTimeout, attributes.build());\n   }\n\n   @Override\n   public ReceiveMessageOptions clone() {\n      return new ReceiveMessageOptions().visibilityTimeout(visibilityTimeout).attributes(attributes.build());\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      ReceiveMessageOptions other = ReceiveMessageOptions.class.cast(obj);\n      return Objects.equal(this.visibilityTimeout, other.visibilityTimeout)\n            && Objects.equal(this.attributes.build(), other.attributes.build());\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String toString() {\n      ImmutableSet<String> attributes = this.attributes.build();\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"visibilityTimeout\", visibilityTimeout)\n            .add(\"attributes\", !attributes.isEmpty() ? attributes : null).toString();\n   }\n}\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/options/SendMessageOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.collect.Multimap;\n\n/**\n * Options used to send a message.\n * \n * @see <a\n *      href=\"http://docs.amazonwebservices.com/AWSSimpleQueueService/2011-10-01/APIReference/Query_QuerySendMessage.html\"\n *      >docs</a>\n */\npublic class SendMessageOptions extends BaseHttpRequestOptions implements Cloneable {\n\n   private Integer delaySeconds;\n\n   /**\n    * The number of seconds to delay a specific message. Messages with a\n    * positive DelaySeconds value become available for processing after the\n    * delay time is finished. If you don't specify a value, the default value\n    * for the queue applies.\n    * \n    * @param delaySeconds\n    *           from 0 to 900 (15 minutes). If this parameter is not used, the\n    *           default value for the queue applies.\n    */\n   public SendMessageOptions delaySeconds(Integer delaySeconds) {\n      this.delaySeconds = delaySeconds;\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see SendMessageOptions#delaySeconds\n       */\n      public static SendMessageOptions delaySeconds(Integer delaySeconds) {\n         return new SendMessageOptions().delaySeconds(delaySeconds);\n      }\n\n   }\n\n   @Override\n   public Multimap<String, String> buildFormParameters() {\n      Multimap<String, String> params = super.buildFormParameters();\n      if (delaySeconds != null)\n         params.put(\"DelaySeconds\", delaySeconds.toString());\n      return params;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(delaySeconds);\n   }\n\n   @Override\n   public SendMessageOptions clone() {\n      return new SendMessageOptions().delaySeconds(delaySeconds);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      SendMessageOptions other = SendMessageOptions.class.cast(obj);\n      return Objects.equal(this.delaySeconds, other.delaySeconds);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"delaySeconds\", delaySeconds).toString();\n   }\n}\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/package-info.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * This package contains an Amazon SQS api implemented by {@link org.jclouds.http.HttpCommandExecutorService} commands.\n *\n * @see <a href=\"http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/APIReference/index.html\"/>\n */\npackage org.jclouds.sqs;\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/reference/SQSParameters.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.reference;\n\n/**\n * Configuration properties and constants used in SQS connections.\n * \n * @see <a href=\"http://docs.amazonwebservices.com/AWSSimpleQueueService/2011-10-01/APIReference/Query_QueryParams.html\"\n *      />\n */\npublic final class SQSParameters {\n\n   /**\n    * The action to perform. For example: CreateQueue.\n    */\n   public static final String ACTION = \"Action\";\n\n   /**\n    * The API version to use, as specified in the WSDL. For example: 2011-10-01.\n    */\n   public static final String VERSION = \"Version\";\n\n   /**\n    * Your Access Key ID. For example: 0AS7253JW73RRM652K02. For more information, see Your AWS\n    * Identifiers in the Amazon SQS Developer Guide.\n    */\n   public static final String AWS_ACCESS_KEY_ID = \"AWSAccessKeyId\";\n\n   /**\n    * The date and time the request is signed, in the format YYYY-MM-DDThh:mm:ssZ, as specified in\n    * the ISO 8601 standard. Query requests must include either Timestamp or Expires, but not both.\n    * \n    */\n   public static final String TIMESTAMP = \"Timestamp\";\n\n   /**\n    * The date and time at which the signature included in the request expires, in the format\n    * YYYY-MM-DDThh:mm:ssZ, as specified in the ISO 8601 standard. Query requests must include\n    * either Timestamp or Expires, but not both.\n    */\n   public static final String EXPIRES = \"Expires\";\n   /**\n    * A request signature (for information, see Request Authentication in the Amazon SQS Developer\n    * Guide). For example: Qnpl4Qk/7tINHzfXCiT7VbBatDA=.\n    */\n   public static final String SIGNATURE = \"Signature\";\n   /**\n    *Required when you use signature version 2 with Query requests. For more information, see Query\n    * Request Authentication in the Amazon SQS Developer Guide.\n    */\n   public static final String SIGNATURE_METHOD = \"SignatureMethod\";\n   /**\n    * For more information, see Query Request Authentication in the Amazon SQS Developer Guide.\n    */\n   public static final String SIGNATURE_VERSION = \"SignatureVersion\";\n\n   private SQSParameters() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/reference/package-info.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * This package contains properties and reference data used in SQS.\n */\npackage org.jclouds.sqs.reference;\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/xml/AttributesHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.xml;\n\nimport static org.jclouds.util.SaxUtils.currentOrNull;\n\nimport java.util.Map;\n\nimport org.jclouds.http.functions.ParseSax;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMap.Builder;\n\n/**\n * @see <a href=\n *      \"http://docs.amazonwebservices.com/AWSSimpleQueueService/2011-10-01/APIReference/Query_QueryGetQueueAttributes.html\"\n *      />\n */\npublic class AttributesHandler extends ParseSax.HandlerForGeneratedRequestWithResult<Map<String, String>> {\n\n   private StringBuilder currentText = new StringBuilder();\n   private Builder<String, String> builder = ImmutableMap.<String, String> builder();\n   private String name;\n\n   @Override\n   public Map<String, String> getResult() {\n      try {\n         return builder.build();\n      } catch (NullPointerException e) {\n         return null;\n      } finally {\n         builder = ImmutableMap.<String, String> builder();\n      }\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) {\n      if (qName.equals(\"Name\")) {\n         this.name = currentOrNull(currentText);\n      } else if (qName.equals(\"Value\")) {\n         builder.put(this.name, currentOrNull(currentText));\n         this.name = null;\n      }\n      currentText.setLength(0);\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n\n}\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/xml/BatchErrorHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.xml;\n\nimport static org.jclouds.util.SaxUtils.currentOrNull;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.sqs.domain.BatchError;\n\n/**\n * @see <a href=\n *      \"http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/APIReference/Query_QueryDeleteMessageBatch.html\"\n *      />\n */\npublic class BatchErrorHandler extends ParseSax.HandlerForGeneratedRequestWithResult<BatchError> {\n\n   private StringBuilder currentText = new StringBuilder();\n   private BatchError.Builder builder = BatchError.builder();\n\n   @Override\n   public BatchError getResult() {\n      try {\n         return builder.build();\n      } catch (NullPointerException e) {\n         return null;\n      } finally {\n         builder = BatchError.builder();\n      }\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) {\n      if (qName.equals(\"Id\")) {\n         builder.id(currentOrNull(currentText));\n      } else if (qName.equals(\"SenderFault\")) {\n         builder.senderFault(Boolean.parseBoolean(currentOrNull(currentText)));\n      } else if (qName.equals(\"Code\")) {\n         builder.code(currentOrNull(currentText));\n      } else if (qName.equals(\"Message\")) {\n         builder.message(currentOrNull(currentText));\n      }\n      currentText.setLength(0);\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n\n}\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/xml/BatchResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.xml;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.http.functions.ParseSax.HandlerForGeneratedRequestWithResult;\nimport org.jclouds.sqs.domain.BatchError;\nimport org.jclouds.sqs.domain.BatchResult;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\n\n/**\n * @see <a\n *      href=\"http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/APIReference/Query_QueryDeleteMessageBatch.html\"\n *      >docs</a>\n */\npublic class BatchResponseHandler<V> extends ParseSax.HandlerForGeneratedRequestWithResult<BatchResult<V>> {\n\n   private final String resultElement;\n   private final ParseSax.HandlerForGeneratedRequestWithResult<Map.Entry<String, V>> resultHandler;\n   private final BatchErrorHandler errorHandler;\n\n   private ImmutableMap.Builder<String, V> results = ImmutableMap.<String, V> builder();\n   private Builder<BatchError> errors = ImmutableSet.<BatchError> builder();\n\n   private boolean inResult;\n   private boolean inError;\n\n   protected BatchResponseHandler(String resultElement, HandlerForGeneratedRequestWithResult<Map.Entry<String, V>> resultHandler,\n         BatchErrorHandler errorHandler) {\n      this.resultElement = checkNotNull(resultElement, \"resultElement\");\n      this.resultHandler = checkNotNull(resultHandler, \"resultHandler\");\n      this.errorHandler = checkNotNull(errorHandler, \"errorHandler\");\n   }\n\n   @Override\n   public BatchResult<V> getResult() {\n      return BatchResult.<V> builder().putAll(results.build()).errors(errors.build())\n            .build();\n   }\n\n   @Override\n   public void startElement(String url, String name, String qName, Attributes attributes) throws SAXException {\n      if (qName.equals(resultElement)) {\n         inResult = true;\n      } else if (qName.equals(\"BatchResultErrorEntry\")) {\n         inError = true;\n      }\n      if (inResult) {\n         resultHandler.startElement(url, name, qName, attributes);\n      } else if (inError) {\n         errorHandler.startElement(url, name, qName, attributes);\n      }\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) throws SAXException {\n      if (qName.equals(resultElement)) {\n         results.put(resultHandler.getResult());\n         inResult = false;\n      } else if (qName.equals(\"BatchResultErrorEntry\")) {\n         errors.add(errorHandler.getResult());\n         inError = false;\n      } else if (inResult) {\n         resultHandler.endElement(uri, name, qName);\n      } else if (inError) {\n         errorHandler.endElement(uri, name, qName);\n      }\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) throws SAXException {\n      if (inResult) {\n         resultHandler.characters(ch, start, length);\n      } else if (inError) {\n         errorHandler.characters(ch, start, length);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/xml/ChangeMessageVisibilityBatchResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.xml;\n\nimport jakarta.inject.Inject;\n\n/**\n * @see <a\n *      href=\"http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/APIReference/Query_QueryChangeMessageVisibilityBatch.html\"\n *      >docs</a>\n */\npublic class ChangeMessageVisibilityBatchResponseHandler extends BatchResponseHandler<String> {\n   @Inject\n   protected ChangeMessageVisibilityBatchResponseHandler(IdHandler resultHandler, BatchErrorHandler errorHandler) {\n      super(\"ChangeMessageVisibilityBatchResultEntry\", resultHandler, errorHandler);\n   }\n\n}\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/xml/DeleteMessageBatchResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.xml;\n\nimport jakarta.inject.Inject;\n\n/**\n * @see <a\n *      href=\"http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/APIReference/Query_QueryDeleteMessageBatch.html\"\n *      >docs</a>\n */\npublic class DeleteMessageBatchResponseHandler extends BatchResponseHandler<String> {\n\n   @Inject\n   protected DeleteMessageBatchResponseHandler(IdHandler resultHandler, BatchErrorHandler errorHandler) {\n      super(\"DeleteMessageBatchResultEntry\", resultHandler, errorHandler);\n   }\n\n}\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/xml/IdHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.xml;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\n\n/**\n * @see <a href=\n *      \"http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/APIReference/Query_QueryDeleteMessageBatch.html\"\n *      />\n */\npublic class IdHandler extends TextFromSingleElementHandler<Map.Entry<String, String>> {\n   @Inject\n   protected IdHandler(String elementName) {\n      super(\"Id\");\n   }\n\n   @Override\n   public Map.Entry<String, String> apply(String in) {\n      return Iterables.getOnlyElement(ImmutableMap.of(in, in).entrySet());\n   }\n\n}\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/xml/MessageHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.xml;\n\nimport static com.google.common.io.BaseEncoding.base16;\nimport static org.jclouds.util.SaxUtils.currentOrNull;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.sqs.domain.Message;\n\nimport com.google.common.hash.HashCode;\n\n/**\n * @see <a href=\n *      \"http://docs.amazonwebservices.com/AWSSimpleQueueService/2011-10-01/APIReference/Query_QueryReceiveMessage.html\"\n *      />\n */\npublic class MessageHandler extends ParseSax.HandlerForGeneratedRequestWithResult<Message> {\n\n   private StringBuilder currentText = new StringBuilder();\n   private Message.Builder builder = Message.builder();\n   private String name;\n\n   @Override\n   public Message getResult() {\n      try {\n         return builder.build();\n      } catch (NullPointerException e) {\n         return null;\n      } finally {\n         builder = Message.builder();\n      }\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) {\n      if (qName.equals(\"MessageId\")) {\n         builder.id(currentOrNull(currentText));\n      } else if (qName.equals(\"ReceiptHandle\")) {\n         builder.receiptHandle(currentOrNull(currentText));\n      } else if (qName.equals(\"MD5OfBody\")) {\n         builder.md5(HashCode.fromBytes(base16().lowerCase().decode(currentOrNull(currentText))));\n      } else if (qName.equals(\"Body\")) {\n         builder.body(currentOrNull(currentText));\n      } else if (qName.equals(\"Name\")) {\n         this.name = currentOrNull(currentText);\n      } else if (qName.equals(\"Value\")) {\n         builder.addAttribute(this.name, currentOrNull(currentText));\n         this.name = null;\n      }\n      currentText.setLength(0);\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n\n}\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/xml/ReceiveMessageResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.xml;\n\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.sqs.domain.Message;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableList.Builder;\nimport com.google.inject.Inject;\n\n/**\n * @see <a\n *      href=\"http://docs.amazonwebservices.com/AWSSimpleQueueService/2011-10-01/APIReference/Query_QueryReceiveMessage.html\"\n *      >docs</a>\n */\npublic class ReceiveMessageResponseHandler extends ParseSax.HandlerForGeneratedRequestWithResult<FluentIterable<Message>> {\n\n   private final MessageHandler messageHandler;\n\n   private Builder<Message> messages = ImmutableList.<Message> builder();\n\n   private boolean inMessages;\n\n   @Inject\n   public ReceiveMessageResponseHandler(MessageHandler messageHandler) {\n      this.messageHandler = messageHandler;\n   }\n\n   @Override\n   public FluentIterable<Message> getResult() {\n      return FluentIterable.from(messages.build());\n   }\n\n   @Override\n   public void startElement(String url, String name, String qName, Attributes attributes) throws SAXException {\n      if (equalsOrSuffix(qName, \"ReceiveMessageResult\")) {\n         inMessages = true;\n      }\n      if (inMessages) {\n         messageHandler.startElement(url, name, qName, attributes);\n      }\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) {\n      if (equalsOrSuffix(qName, \"ReceiveMessageResult\")) {\n         inMessages = false;\n      } else if (equalsOrSuffix(qName, \"Message\")) {\n         messages.add(messageHandler.getResult());\n      } else if (inMessages) {\n         messageHandler.endElement(uri, name, qName);\n      }\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      if (inMessages) {\n         messageHandler.characters(ch, start, length);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/xml/RegexListQueuesResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.xml;\n\nimport java.net.URI;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ReturnStringIf2xx;\nimport org.jclouds.sqs.xml.internal.BaseRegexQueueHandler;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.FluentIterable;\n\n/**\n * \n * @see <a href=\n *      \"http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/APIReference/Query_QueryListQueues.html\"\n *      />\n */\n@Singleton\npublic class RegexListQueuesResponseHandler extends BaseRegexQueueHandler implements Function<HttpResponse, FluentIterable<URI>> {\n   private final ReturnStringIf2xx returnStringIf200;\n\n   @Inject\n   RegexListQueuesResponseHandler(ReturnStringIf2xx returnStringIf200) {\n      this.returnStringIf200 = returnStringIf200;\n   }\n\n   @Override\n   public FluentIterable<URI> apply(HttpResponse response) {\n      return parse(returnStringIf200.apply(response));\n   }\n\n}\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/xml/RegexMessageIdAndMD5Handler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.xml;\n\nimport static com.google.common.io.BaseEncoding.base16;\n\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ReturnStringIf2xx;\nimport org.jclouds.sqs.domain.MessageIdAndMD5;\n\nimport com.google.common.base.Function;\nimport com.google.common.hash.HashCode;\nimport com.google.inject.Singleton;\n\n/**\n * \n * @see <a href=\"http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/APIReference/Query_QuerySendMessage.html\"\n *      />\n */\n@Singleton\npublic class RegexMessageIdAndMD5Handler implements Function<HttpResponse, MessageIdAndMD5> {\n   private static final Pattern pattern = Pattern.compile(\"<MessageId>([\\\\S&&[^<]]+)</MessageId>\\\\s*<MD5OfMessageBody>([\\\\S&&[^<]]+)</MD5OfMessageBody>\", Pattern.DOTALL);\n   private final ReturnStringIf2xx returnStringIf200;\n\n   @Inject\n   public RegexMessageIdAndMD5Handler(ReturnStringIf2xx returnStringIf200) {\n      this.returnStringIf200 = returnStringIf200;\n   }\n\n   @Override\n   public MessageIdAndMD5 apply(HttpResponse response) {\n      String content = returnStringIf200.apply(response);\n      if (content != null) {\n         Matcher matcher = pattern.matcher(content);\n         if (matcher.find()) {\n            return MessageIdAndMD5.builder()\n                                  .id(matcher.group(1))\n                                  .md5(HashCode.fromBytes(base16().lowerCase().decode(matcher.group(2))))\n                                  .build();\n         }\n      }\n      return null;\n   }\n\n}\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/xml/RegexQueueHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.xml;\n\nimport java.net.URI;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ReturnStringIf2xx;\nimport org.jclouds.sqs.xml.internal.BaseRegexQueueHandler;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.Iterables;\n\n/**\n * \n * @see <a href=\n *      \"http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/APIReference/Query_QueryListQueues.html\"\n *      />\n */\n@Singleton\npublic class RegexQueueHandler extends BaseRegexQueueHandler implements Function<HttpResponse, URI> {\n   private final ReturnStringIf2xx returnStringIf200;\n\n   @Inject\n   public RegexQueueHandler(ReturnStringIf2xx returnStringIf200) {\n      this.returnStringIf200 = returnStringIf200;\n   }\n\n   @Override\n   public URI apply(HttpResponse response) {\n      return Iterables.getOnlyElement(parse(returnStringIf200.apply(response)));\n   }\n}\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/xml/SendMessageBatchResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.xml;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.sqs.domain.MessageIdAndMD5;\n\n/**\n * @see <a\n *      href=\"http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/APIReference/Query_QuerySendMessageBatch.html\"\n *      >docs</a>\n */\npublic class SendMessageBatchResponseHandler extends BatchResponseHandler<MessageIdAndMD5> {\n\n   @Inject\n   protected SendMessageBatchResponseHandler(SendMessageBatchResultEntryHandler resultHandler,\n         BatchErrorHandler errorHandler) {\n      super(\"SendMessageBatchResultEntry\", resultHandler, errorHandler);\n   }\n\n}\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/xml/SendMessageBatchResultEntryHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.xml;\n\nimport static com.google.common.io.BaseEncoding.base16;\nimport static org.jclouds.util.SaxUtils.currentOrNull;\n\nimport java.util.Map;\nimport java.util.Map.Entry;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.sqs.domain.MessageIdAndMD5;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\nimport com.google.common.hash.HashCode;\n\n/**\n * @see <a href=\n *      \"http://docs.amazonwebservices.com/AWSSimpleQueueService/2011-10-01/APIReference/Query_QueryReceiveMessage.html\"\n *      />\n */\npublic class SendMessageBatchResultEntryHandler extends\n      ParseSax.HandlerForGeneratedRequestWithResult<Map.Entry<String, MessageIdAndMD5>> {\n\n   private StringBuilder currentText = new StringBuilder();\n   private MessageIdAndMD5.Builder builder = MessageIdAndMD5.builder();\n   private String id;\n\n   @Override\n   public Entry<String, MessageIdAndMD5> getResult() {\n      try {\n         return Iterables.getOnlyElement(ImmutableMap.of(id, builder.build()).entrySet());\n      } finally {\n         builder = MessageIdAndMD5.builder();\n      }\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) {\n      if (qName.equals(\"Id\")) {\n         this.id = currentOrNull(currentText);\n      } else if (qName.equals(\"MessageId\")) {\n         builder.id(currentOrNull(currentText));\n      } else if (qName.equals(\"MD5OfMessageBody\")) {\n         builder.md5(HashCode.fromBytes(base16().lowerCase().decode(currentOrNull(currentText))));\n      }\n      currentText.setLength(0);\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n\n}\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/xml/TextFromSingleElementHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.xml;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.util.SaxUtils.currentOrNull;\n\nimport org.jclouds.http.functions.ParseSax;\n\nimport com.google.common.base.Function;\n\n/**\n * looks for a single value in the xml\n */\npublic abstract class TextFromSingleElementHandler<V> extends ParseSax.HandlerForGeneratedRequestWithResult<V>\n      implements Function<String, V> {\n   private final String elementName;\n\n   protected TextFromSingleElementHandler(String elementName) {\n      this.elementName = checkNotNull(elementName, \"elementName\");\n   }\n\n   private StringBuilder currentText = new StringBuilder();\n   private String text;\n\n   @Override\n   public V getResult() {\n      return apply(text);\n   }\n\n   // this could be done with regex, if we had an unescaper\n   @Override\n   public void endElement(String uri, String name, String qName) {\n      if (qName.equals(elementName)) {\n         text = currentOrNull(currentText);\n      }\n      currentText.setLength(0);\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n\n}\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/xml/ValueHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.xml;\n\nimport jakarta.inject.Inject;\n\n/**\n * @see <a href=\n *      \"http://docs.amazonwebservices.com/AWSSimpleQueueService/2011-10-01/APIReference/Query_QueryGetQueueAttributes.html\"\n *      />\n */\npublic class ValueHandler extends TextFromSingleElementHandler<String> {\n   @Inject\n   protected ValueHandler(String elementName) {\n      super(\"Value\");\n   }\n\n   @Override\n   public String apply(String in) {\n      return in;\n   }\n\n}\n"
  },
  {
    "path": "apis/sqs/src/main/java/org/jclouds/sqs/xml/internal/BaseRegexQueueHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.xml.internal;\n\nimport java.net.URI;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport jakarta.inject.Singleton;\n\nimport com.google.common.base.Strings;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\n\n/**\n * \n * @see <a href=\n *      \"http://docs.amazonwebservices.com/AWSSimpleQueueService/latest/APIReference/Query_QueryListQueues.html\"\n *      />\n */\n@Singleton\npublic class BaseRegexQueueHandler {\n   protected final Pattern pattern = Pattern.compile(\"<QueueUrl>(https?://[\\\\S&&[^<]]+)</QueueUrl>\");\n\n   public FluentIterable<URI> parse(String in) {\n      Builder<URI> queues = ImmutableSet.<URI> builder();\n      Matcher matcher = pattern.matcher(in);\n      while (matcher.find()) {\n         String uriText = matcher.group(1);\n         if (!Strings.isNullOrEmpty(uriText))\n            queues.add(URI.create(uriText));\n      }\n      return FluentIterable.from(queues.build());\n   }\n\n}\n"
  },
  {
    "path": "apis/sqs/src/test/java/org/jclouds/sqs/SQSApiMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs;\n\nimport org.jclouds.View;\nimport org.jclouds.rest.internal.BaseHttpApiMetadataTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.reflect.TypeToken;\n\n@Test(groups = \"unit\", testName = \"SQSApiMetadataTest\")\npublic class SQSApiMetadataTest extends BaseHttpApiMetadataTest {\n\n   // no queue abstraction, yet\n   public SQSApiMetadataTest() {\n      super(new SQSApiMetadata(), ImmutableSet.<TypeToken<? extends View>> of());\n   }\n}\n"
  },
  {
    "path": "apis/sqs/src/test/java/org/jclouds/sqs/SQSTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\n\nimport org.easymock.EasyMock;\nimport org.jclouds.sqs.domain.Message;\nimport org.jclouds.sqs.features.MessageApi;\nimport org.jclouds.sqs.options.ReceiveMessageOptions;\nimport org.testng.Assert;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\n\n/**\n * Tests behavior of {@code SQS}.\n */\n@Test(testName = \"SQSTest\", singleThreaded = true)\npublic class SQSTest {\n\n   /**\n    * Tests {@link SQS#receiveAllAtRate} where a single response returns all\n    * results.\n    */\n   @Test\n   public void testSinglePageResult() throws Exception {\n      MessageApi messageClient = createMock(MessageApi.class);\n      ReceiveMessageOptions options = new ReceiveMessageOptions();\n      FluentIterable<Message> aMessage = FluentIterable.from(ImmutableSet.of(createMock(Message.class)));\n      FluentIterable<Message> noMessages = FluentIterable.from(ImmutableSet.<Message>of());\n\n      expect(messageClient.receive(1, options))\n            .andReturn(aMessage)\n            .once();\n      \n      expect(messageClient.receive(1, options))\n            .andReturn(noMessages)\n            .once();\n            \n      EasyMock.replay(messageClient);\n\n      Assert.assertEquals(1, Iterables.size(SQS.receiveAllAtRate(messageClient, 1, options)));\n   }\n   \n   /**\n    * Tests {@link SQS#receiveAllAtRate} where retrieving all results requires multiple requests.\n    */\n   @Test\n   public void testMultiPageResult() throws Exception {\n      MessageApi messageClient = createMock(MessageApi.class);\n      ReceiveMessageOptions options = new ReceiveMessageOptions();\n      FluentIterable<Message> aMessage = FluentIterable.from(ImmutableSet.of(createMock(Message.class)));\n      FluentIterable<Message> noMessages = FluentIterable.from(ImmutableSet.<Message>of());\n      \n      expect(messageClient.receive(1, options))\n            .andReturn(aMessage)\n            .times(2);\n      expect(messageClient.receive(1, options))\n            .andReturn(noMessages)\n            .once();\n\n      EasyMock.replay(messageClient);\n\n      Assert.assertEquals(2, Iterables.size(SQS.receiveAllAtRate(messageClient, 1, options)));\n   }\n}\n"
  },
  {
    "path": "apis/sqs/src/test/java/org/jclouds/sqs/features/BulkMessageApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.features;\n\nimport static org.jclouds.sqs.options.ReceiveMessageOptions.Builder.attribute;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\n\nimport java.net.URI;\nimport java.util.Map.Entry;\nimport java.util.Set;\n\nimport org.jclouds.sqs.SQS;\nimport org.jclouds.sqs.domain.BatchResult;\nimport org.jclouds.sqs.domain.Message;\nimport org.jclouds.sqs.domain.MessageIdAndMD5;\nimport org.jclouds.sqs.internal.BaseSQSApiLiveTest;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMap.Builder;\nimport com.google.common.collect.Iterables;\nimport com.google.common.hash.Hashing;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"BulkMessageApiLiveTest\")\npublic class BulkMessageApiLiveTest extends BaseSQSApiLiveTest {\n\n   private ImmutableMap<String, String> idPayload;\n\n   public BulkMessageApiLiveTest() {\n      prefix = prefix + \"-bulk\";\n\n      Builder<String, String> builder = ImmutableMap.<String, String> builder();\n      for (int i = 0; i < 10; i++) {\n         String message = \"hardyharhar\" + i;\n         builder.put(i + \"\", message);\n      }\n      idPayload = builder.build();\n   }\n\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   @Override\n   public void setup() {\n      super.setup();\n      recreateQueueInRegion(prefix, null);\n   }\n\n   public void testSendMessages() {\n      for (URI queue : queues) {\n         BatchResult<? extends MessageIdAndMD5> acks = api.getMessageApiForQueue(queue).send(idPayload);\n\n         assertEquals(acks.size(), idPayload.size(), \"error sending \" + acks);\n         assertEquals(acks.keySet(), idPayload.keySet());\n\n         for (Entry<String, ? extends MessageIdAndMD5> entry : acks.entrySet()) {\n            assertEquals(entry.getValue().getMD5(),\n                  Hashing.md5().hashString(idPayload.get(entry.getKey()), Charsets.UTF_8), \"bad md5 for: \" + entry);\n         }\n      }\n   }\n\n   private Iterable<String> receiptHandles;\n\n   @Test(dependsOnMethods = \"testSendMessages\")\n   public void testChangeMessageVisibility() {\n      for (URI queue : queues) {\n         MessageApi messageApi = api.getMessageApiForQueue(queue);\n         \n         Set<Message> messages = collectMessages(messageApi);\n\n         receiptHandles = Iterables.transform(messages, new Function<Message, String>() {\n            @Override\n            public String apply(Message in) {\n               return in.getReceiptHandle();\n            }\n         });\n\n         // hidden message, so we can't see it\n         assertNull(messageApi.receive());\n\n         // this should unhide it\n         BatchResult<String> acks = messageApi.changeVisibility(receiptHandles, 0);\n         assertEquals(acks.size(), messages.size(), \"error changing visibility \" + acks);\n\n         // so we can see it again\n         assertEquals(collectMessages(messageApi).size(), messages.size());\n      }\n   }\n\n   protected Set<Message> collectMessages(MessageApi api) {\n      return SQS.receiveAllAtRate(api, idPayload.size(), attribute(\"None\").visibilityTimeout(5)).toSet();\n   }\n\n   @Test(dependsOnMethods = \"testChangeMessageVisibility\")\n   public void testDeleteMessage() throws InterruptedException {\n      for (URI queue : queues) {\n         BatchResult<String> acks = api.getMessageApiForQueue(queue).delete(receiptHandles);\n         assertEquals(acks.size(), Iterables.size(receiptHandles), \"error deleting messages \" + acks);\n         assertNoMessages(queue);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/sqs/src/test/java/org/jclouds/sqs/features/MessageApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.features;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.sqs.SQSApi;\nimport org.jclouds.sqs.internal.BaseSQSApiExpectTest;\nimport org.jclouds.sqs.parse.ChangeMessageVisibilityBatchResponseTest;\nimport org.jclouds.sqs.parse.DeleteMessageBatchResponseTest;\nimport org.jclouds.sqs.parse.ReceiveMessageResponseTest;\nimport org.jclouds.sqs.parse.SendMessageBatchResponseTest;\nimport org.jclouds.sqs.parse.SendMessageResponseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableTable;\nimport com.google.common.collect.Iterables;\n\n@Test(groups = \"unit\", testName = \"MessageApiExpectTest\")\npublic class MessageApiExpectTest extends BaseSQSApiExpectTest {\n   \n   public HttpRequest sendMessage = HttpRequest.builder()\n         .method(\"POST\")\n         .endpoint(\"https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/\")\n         .addHeader(\"Host\", \"sqs.us-east-1.amazonaws.com\")\n         .addFormParam(\"Action\", \"SendMessage\")\n         .addFormParam(\"MessageBody\", \"hardyharhar\")\n         .addFormParam(\"Signature\", \"PVzszzgIcT1xt9+EzGzWB2Bt8zDadBc48HsgF89AoJE=\")\n         .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n         .addFormParam(\"SignatureVersion\", \"2\")\n         .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n         .addFormParam(\"Version\", \"2011-10-01\")\n         .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testSendMessageWhenResponseIs2xx() throws Exception {\n      \n      HttpResponse sendMessageResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResourceWithContentType(\"/send_message.xml\", \"text/xml\")).build();\n\n      SQSApi apiWhenExist = requestSendsResponse(sendMessage, sendMessageResponse);\n\n      assertEquals(apiWhenExist.getMessageApiForQueue(queue).send(\"hardyharhar\").toString(),\n            new SendMessageResponseTest().expected().toString());\n   }\n   \n   public HttpRequest sendMessageIterable = HttpRequest.builder()\n         .method(\"POST\")\n         .endpoint(\"https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/\")\n         .addHeader(\"Host\", \"sqs.us-east-1.amazonaws.com\")\n         .addFormParam(\"Action\", \"SendMessageBatch\")\n         .addFormParam(\"SendMessageBatchRequestEntry.1.Id\", \"1\")\n         .addFormParam(\"SendMessageBatchRequestEntry.1.MessageBody\", \"payload1\")\n         .addFormParam(\"SendMessageBatchRequestEntry.2.Id\", \"2\")\n         .addFormParam(\"SendMessageBatchRequestEntry.2.MessageBody\", \"payload2\")\n         .addFormParam(\"Signature\", \"2AYMDMLhoLncALJgBfHBGfOkaTB5ut3PeFRJeWffxdI=\")\n         .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n         .addFormParam(\"SignatureVersion\", \"2\")\n         .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n         .addFormParam(\"Version\", \"2011-10-01\")\n         .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testSendMessageIterableWhenResponseIs2xx() throws Exception {\n\n      HttpResponse sendMessageResponse = HttpResponse.builder()\n            .statusCode(200)\n            .payload(payloadFromResourceWithContentType(\"/send_message_batch.xml\", \"text/xml\")).build();\n\n      SQSApi apiWhenExist = requestSendsResponse(sendMessageIterable, sendMessageResponse);\n\n      assertEquals(apiWhenExist.getMessageApiForQueue(queue).send(ImmutableSet.of(\"payload1\", \"payload2\"))\n            .toString(), new SendMessageBatchResponseTest().expected().toString());\n   }\n\n   public HttpRequest sendMessageMap = HttpRequest.builder()\n         .method(\"POST\")\n         .endpoint(\"https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/\")\n         .addHeader(\"Host\", \"sqs.us-east-1.amazonaws.com\")\n         .addFormParam(\"Action\", \"SendMessageBatch\")\n         .addFormParam(\"SendMessageBatchRequestEntry.1.Id\", \"foo1\")\n         .addFormParam(\"SendMessageBatchRequestEntry.1.MessageBody\", \"payload1\")\n         .addFormParam(\"SendMessageBatchRequestEntry.2.Id\", \"foo2\")\n         .addFormParam(\"SendMessageBatchRequestEntry.2.MessageBody\", \"payload2\")\n         .addFormParam(\"Signature\", \"f9v8e/rPXTI3zhBYMhg7U8yCfvPqHjAV8bFjhGL6+Xc=\")\n         .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n         .addFormParam(\"SignatureVersion\", \"2\")\n         .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n         .addFormParam(\"Version\", \"2011-10-01\")\n         .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n   \n   public void testSendMessageMapWhenResponseIs2xx() throws Exception {\n\n      HttpResponse sendMessageResponse = HttpResponse.builder()\n            .statusCode(200)\n            .payload(payloadFromResourceWithContentType(\"/send_message_batch.xml\", \"text/xml\")).build();\n\n      SQSApi apiWhenExist = requestSendsResponse(sendMessageMap, sendMessageResponse);\n\n      assertEquals(\n            apiWhenExist.getMessageApiForQueue(queue)\n                  .send(ImmutableMap.of(\"foo1\", \"payload1\", \"foo2\", \"payload2\")).toString(),\n            new SendMessageBatchResponseTest().expected().toString());\n   }\n   \n   public HttpRequest sendMessageWithDelayMap = HttpRequest.builder()\n         .method(\"POST\")\n         .endpoint(\"https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/\")\n         .addHeader(\"Host\", \"sqs.us-east-1.amazonaws.com\")\n         .addFormParam(\"Action\", \"SendMessageBatch\")\n         .addFormParam(\"SendMessageBatchRequestEntry.1.DelaySeconds\", \"10\")\n         .addFormParam(\"SendMessageBatchRequestEntry.1.Id\", \"foo1\")\n         .addFormParam(\"SendMessageBatchRequestEntry.1.MessageBody\", \"payload1\")\n         .addFormParam(\"SendMessageBatchRequestEntry.2.DelaySeconds\", \"10\")\n         .addFormParam(\"SendMessageBatchRequestEntry.2.Id\", \"foo2\")\n         .addFormParam(\"SendMessageBatchRequestEntry.2.MessageBody\", \"payload2\")\n         .addFormParam(\"Signature\", \"COjjEaJ76EwziEFtkT2FuSRSbrCIu/hlJf1Zmu7cYoU=\")\n         .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n         .addFormParam(\"SignatureVersion\", \"2\")\n         .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n         .addFormParam(\"Version\", \"2011-10-01\")\n         .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testSendMessageWithDelayMapWhenResponseIs2xx() throws Exception {\n\n      HttpResponse sendMessageResponse = HttpResponse.builder()\n            .statusCode(200)\n            .payload(payloadFromResourceWithContentType(\"/send_message_batch.xml\", \"text/xml\")).build();\n\n      SQSApi apiWhenExist = requestSendsResponse(sendMessageWithDelayMap, sendMessageResponse);\n\n      assertEquals(apiWhenExist.getMessageApiForQueue(queue).sendWithDelay(ImmutableMap.<String, String>builder()\n            .put(\"foo1\", \"payload1\")\n            .put(\"foo2\", \"payload2\")\n            .build(), 10)\n            .toString(), new SendMessageBatchResponseTest().expected().toString());\n   }\n\n   public HttpRequest sendMessageWithDelayIterable = HttpRequest.builder()\n         .method(\"POST\")\n         .endpoint(\"https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/\")\n         .addHeader(\"Host\", \"sqs.us-east-1.amazonaws.com\")\n         .addFormParam(\"Action\", \"SendMessageBatch\")\n         .addFormParam(\"SendMessageBatchRequestEntry.1.DelaySeconds\", \"10\")\n         .addFormParam(\"SendMessageBatchRequestEntry.1.Id\", \"1\")\n         .addFormParam(\"SendMessageBatchRequestEntry.1.MessageBody\", \"payload1\")\n         .addFormParam(\"SendMessageBatchRequestEntry.2.DelaySeconds\", \"10\")\n         .addFormParam(\"SendMessageBatchRequestEntry.2.Id\", \"2\")\n         .addFormParam(\"SendMessageBatchRequestEntry.2.MessageBody\", \"payload2\")\n         .addFormParam(\"Signature\", \"8AVNvSVXPSnoXjJAc6h1rysMBBZPnSycbnmD2/qpdV8=\")\n         .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n         .addFormParam(\"SignatureVersion\", \"2\")\n         .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n         .addFormParam(\"Version\", \"2011-10-01\")\n         .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n   \n   public void testSendMessageWithDelayIterableWhenResponseIs2xx() throws Exception {\n\n      HttpResponse sendMessageResponse = HttpResponse.builder()\n            .statusCode(200)\n            .payload(payloadFromResourceWithContentType(\"/send_message_batch.xml\", \"text/xml\")).build();\n\n      SQSApi apiWhenExist = requestSendsResponse(sendMessageWithDelayIterable, sendMessageResponse);\n\n      assertEquals(\n            apiWhenExist.getMessageApiForQueue(queue).sendWithDelay(ImmutableSet.of(\"payload1\", \"payload2\"), 10)\n                  .toString(), new SendMessageBatchResponseTest().expected().toString());\n   }\n   public HttpRequest sendMessageWithDelaysTable = HttpRequest.builder()\n         .method(\"POST\")\n         .endpoint(\"https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/\")\n         .addHeader(\"Host\", \"sqs.us-east-1.amazonaws.com\")\n         .addFormParam(\"Action\", \"SendMessageBatch\")\n         .addFormParam(\"SendMessageBatchRequestEntry.1.DelaySeconds\", \"1\")\n         .addFormParam(\"SendMessageBatchRequestEntry.1.Id\", \"foo1\")\n         .addFormParam(\"SendMessageBatchRequestEntry.1.MessageBody\", \"payload1\")\n         .addFormParam(\"SendMessageBatchRequestEntry.2.DelaySeconds\", \"10\")\n         .addFormParam(\"SendMessageBatchRequestEntry.2.Id\", \"foo2\")\n         .addFormParam(\"SendMessageBatchRequestEntry.2.MessageBody\", \"payload2\")\n         .addFormParam(\"Signature\", \"M2X8Al+byyDM+9kdN28rMn1yJWl78hJ5i4GnaMZ1sYg=\")\n         .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n         .addFormParam(\"SignatureVersion\", \"2\")\n         .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n         .addFormParam(\"Version\", \"2011-10-01\")\n         .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testSendMessageWithDelaysTableWhenResponseIs2xx() throws Exception {\n\n      HttpResponse sendMessageResponse = HttpResponse.builder()\n            .statusCode(200)\n            .payload(payloadFromResourceWithContentType(\"/send_message_batch.xml\", \"text/xml\")).build();\n\n      SQSApi apiWhenExist = requestSendsResponse(sendMessageWithDelaysTable, sendMessageResponse);\n\n      assertEquals(apiWhenExist.getMessageApiForQueue(queue).sendWithDelays(ImmutableTable.<String, String, Integer>builder()\n            .put(\"foo1\", \"payload1\", 1)\n            .put(\"foo2\", \"payload2\", 10)\n            .build())\n            .toString(), new SendMessageBatchResponseTest().expected().toString());\n   }\n\n   public HttpRequest sendMessageWithDelaysMap = HttpRequest.builder()\n         .method(\"POST\")\n         .endpoint(\"https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/\")\n         .addHeader(\"Host\", \"sqs.us-east-1.amazonaws.com\")\n         .addFormParam(\"Action\", \"SendMessageBatch\")\n         .addFormParam(\"SendMessageBatchRequestEntry.1.DelaySeconds\", \"1\")\n         .addFormParam(\"SendMessageBatchRequestEntry.1.Id\", \"1\")\n         .addFormParam(\"SendMessageBatchRequestEntry.1.MessageBody\", \"payload1\")\n         .addFormParam(\"SendMessageBatchRequestEntry.2.DelaySeconds\", \"10\")\n         .addFormParam(\"SendMessageBatchRequestEntry.2.Id\", \"2\")\n         .addFormParam(\"SendMessageBatchRequestEntry.2.MessageBody\", \"payload2\")\n         .addFormParam(\"Signature\", \"nbA4UnKDAuQCiCcvQHH/1UjMMeo2s3d94A27Q3t9SlI=\")\n         .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n         .addFormParam(\"SignatureVersion\", \"2\")\n         .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n         .addFormParam(\"Version\", \"2011-10-01\")\n         .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n   \n   public void testSendMessageWithDelaysMapWhenResponseIs2xx() throws Exception {\n\n      HttpResponse sendMessageResponse = HttpResponse.builder()\n            .statusCode(200)\n            .payload(payloadFromResourceWithContentType(\"/send_message_batch.xml\", \"text/xml\")).build();\n\n      SQSApi apiWhenExist = requestSendsResponse(sendMessageWithDelaysMap, sendMessageResponse);\n\n      assertEquals(\n            apiWhenExist.getMessageApiForQueue(queue).sendWithDelays(ImmutableMap.of(\"payload1\", 1, \"payload2\", 10))\n                  .toString(), new SendMessageBatchResponseTest().expected().toString());\n   }\n   \n   public HttpRequest receiveMessage = HttpRequest.builder()\n         .method(\"POST\")\n         .endpoint(\"https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/\")\n         .addHeader(\"Host\", \"sqs.us-east-1.amazonaws.com\")\n         .addFormParam(\"Action\", \"ReceiveMessage\")\n         .addFormParam(\"Signature\", \"UURXsAjggoaz5P1h2EFswRd8Ji9euHmXhHvrAmIqM1E=\")\n         .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n         .addFormParam(\"SignatureVersion\", \"2\")\n         .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n         .addFormParam(\"Version\", \"2011-10-01\")\n         .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testReceiveMessageWhenResponseIs2xx() throws Exception {\n      \n      HttpResponse receiveMessageResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResourceWithContentType(\"/messages.xml\", \"text/xml\")).build();\n\n      SQSApi apiWhenExist = requestSendsResponse(receiveMessage, receiveMessageResponse);\n\n      assertEquals(apiWhenExist.getMessageApiForQueue(queue).receive().toString(),\n            Iterables.get(new ReceiveMessageResponseTest().expected(), 0).toString());\n   }\n   \n\n   public HttpRequest receiveMessages = HttpRequest.builder()\n         .method(\"POST\")\n         .endpoint(\"https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/\")\n         .addHeader(\"Host\", \"sqs.us-east-1.amazonaws.com\")\n         .addFormParam(\"Action\", \"ReceiveMessage\")\n         .addFormParam(\"MaxNumberOfMessages\", \"10\")\n         .addFormParam(\"Signature\", \"pZ9B4+TBvQA4n0joP4t8ue5x0xmKMd9prpVLVoT/7qU=\")\n         .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n         .addFormParam(\"SignatureVersion\", \"2\")\n         .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n         .addFormParam(\"Version\", \"2011-10-01\")\n         .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testReceiveMessagesWhenResponseIs2xx() throws Exception {\n      \n      HttpResponse receiveMessagesResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResourceWithContentType(\"/messages.xml\", \"text/xml\")).build();\n\n      SQSApi apiWhenExist = requestSendsResponse(receiveMessages, receiveMessagesResponse);\n\n      assertEquals(apiWhenExist.getMessageApiForQueue(queue).receive(10).toString(), new ReceiveMessageResponseTest()\n            .expected().toString());\n   }\n\n   public HttpRequest deleteMessage = HttpRequest.builder()\n         .method(\"POST\")\n         .endpoint(\"https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/\")\n         .addHeader(\"Host\", \"sqs.us-east-1.amazonaws.com\")\n         .addFormParam(\"Action\", \"DeleteMessage\")\n         .addFormParam(\"ReceiptHandle\", \"eXJYhj5rDr9cAe\")\n         .addFormParam(\"Signature\", \"9/kuCc2i78gMsmul+RsOPcdQ1OLUKrItqgGIRRBJb8M=\")\n         .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n         .addFormParam(\"SignatureVersion\", \"2\")\n         .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n         .addFormParam(\"Version\", \"2011-10-01\")\n         .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testDeleteMessageWhenResponseIs2xx() throws Exception {\n\n      HttpResponse deleteMessageResponse = HttpResponse.builder()\n            .statusCode(200)\n            .payload(\n                  payloadFromStringWithContentType(\n                        \"<DeleteMessageResponse><ResponseMetadata><RequestId>b5293cb5-d306-4a17-9048-b263635abe42</RequestId></ResponseMetadata></DeleteMessageResponse>\",\n                        \"text/xml\")).build();\n\n      SQSApi apiWhenExist = requestSendsResponse(deleteMessage, deleteMessageResponse);\n\n      apiWhenExist.getMessageApiForQueue(queue).delete(\"eXJYhj5rDr9cAe\");\n   }\n\n   public HttpRequest deleteMessageIterable = HttpRequest.builder()\n         .method(\"POST\")\n         .endpoint(\"https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/\")\n         .addHeader(\"Host\", \"sqs.us-east-1.amazonaws.com\")\n         .addFormParam(\"Action\", \"DeleteMessageBatch\")\n         .addFormParam(\"DeleteMessageBatchRequestEntry.1.Id\", \"1\")\n         .addFormParam(\"DeleteMessageBatchRequestEntry.1.ReceiptHandle\", \"eXJYhj5rDr9cAe\")\n         .addFormParam(\"DeleteMessageBatchRequestEntry.2.Id\", \"2\")\n         .addFormParam(\"DeleteMessageBatchRequestEntry.2.ReceiptHandle\", \"fffeeerrr\")\n         .addFormParam(\"Signature\", \"S4xIobjm3LOkJvibeI2X54nxKJw9r1a5zj/dvHlfDMY=\")\n         .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n         .addFormParam(\"SignatureVersion\", \"2\")\n         .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n         .addFormParam(\"Version\", \"2011-10-01\")\n         .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testDeleteMessageIterableWhenResponseIs2xx() throws Exception {\n\n      HttpResponse deleteMessageResponse = HttpResponse.builder()\n            .statusCode(200)\n            .payload(payloadFromResourceWithContentType(\"/delete_message_batch.xml\", \"text/xml\")).build();\n\n      SQSApi apiWhenExist = requestSendsResponse(deleteMessageIterable, deleteMessageResponse);\n\n      assertEquals(apiWhenExist.getMessageApiForQueue(queue).delete(ImmutableSet.of(\"eXJYhj5rDr9cAe\", \"fffeeerrr\"))\n            .toString(), new DeleteMessageBatchResponseTest().expected().toString());\n   }\n\n   public HttpRequest deleteMessageMap = HttpRequest.builder()\n         .method(\"POST\")\n         .endpoint(\"https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/\")\n         .addHeader(\"Host\", \"sqs.us-east-1.amazonaws.com\")\n         .addFormParam(\"Action\", \"DeleteMessageBatch\")\n         .addFormParam(\"DeleteMessageBatchRequestEntry.1.Id\", \"foo1\")\n         .addFormParam(\"DeleteMessageBatchRequestEntry.1.ReceiptHandle\", \"eXJYhj5rDr9cAe\")\n         .addFormParam(\"DeleteMessageBatchRequestEntry.2.Id\", \"foo2\")\n         .addFormParam(\"DeleteMessageBatchRequestEntry.2.ReceiptHandle\", \"fffeeerrr\")\n         .addFormParam(\"Signature\", \"kwHC3F3ZoJvfibhZWVTeIwFHUzoaVMR4OViyJbsmuV0=\")\n         .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n         .addFormParam(\"SignatureVersion\", \"2\")\n         .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n         .addFormParam(\"Version\", \"2011-10-01\")\n         .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testDeleteMessageMapWhenResponseIs2xx() throws Exception {\n\n      HttpResponse deleteMessageResponse = HttpResponse.builder()\n            .statusCode(200)\n            .payload(payloadFromResourceWithContentType(\"/delete_message_batch.xml\", \"text/xml\")).build();\n\n      SQSApi apiWhenExist = requestSendsResponse(deleteMessageMap, deleteMessageResponse);\n\n      assertEquals(\n            apiWhenExist.getMessageApiForQueue(queue)\n                  .delete(ImmutableMap.of(\"foo1\", \"eXJYhj5rDr9cAe\", \"foo2\", \"fffeeerrr\")).toString(),\n            new DeleteMessageBatchResponseTest().expected().toString());\n   }\n   \n   public HttpRequest changeMessageVisibility = HttpRequest.builder()\n         .method(\"POST\")\n         .endpoint(\"https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/\")\n         .addHeader(\"Host\", \"sqs.us-east-1.amazonaws.com\")\n         .addFormParam(\"Action\", \"ChangeMessageVisibility\")\n         .addFormParam(\"ReceiptHandle\", \"eXJYhj5rDr9cAe\")\n         .addFormParam(\"Signature\", \"gvmSHleGLkmszYU6aURCBImuec2k0O3pg3tAYhDvkNs=\")\n         .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n         .addFormParam(\"SignatureVersion\", \"2\")\n         .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n         .addFormParam(\"Version\", \"2011-10-01\")\n         .addFormParam(\"VisibilityTimeout\", \"10\")\n         .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testChangeMessageVisibilityWhenResponseIs2xx() throws Exception {\n\n      HttpResponse changeMessageVisibilityResponse = HttpResponse.builder()\n            .statusCode(200)\n            .payload(\n                  payloadFromStringWithContentType(\n                        \"<ChangeMessageVisibilityResponse><ResponseMetadata><RequestId>b5293cb5-d306-4a17-9048-b263635abe42</RequestId></ResponseMetadata></ChangeMessageVisibilityResponse>\",\n                        \"text/xml\")).build();\n\n      SQSApi apiWhenExist = requestSendsResponse(changeMessageVisibility, changeMessageVisibilityResponse);\n\n      apiWhenExist.getMessageApiForQueue(queue).changeVisibility(\"eXJYhj5rDr9cAe\", 10);\n   }\n\n   public HttpRequest changeMessageVisibilityTable = HttpRequest.builder()\n         .method(\"POST\")\n         .endpoint(\"https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/\")\n         .addHeader(\"Host\", \"sqs.us-east-1.amazonaws.com\")\n         .addFormParam(\"Action\", \"ChangeMessageVisibilityBatch\")\n         .addFormParam(\"ChangeMessageVisibilityBatchRequestEntry.1.Id\", \"foo1\")\n         .addFormParam(\"ChangeMessageVisibilityBatchRequestEntry.1.ReceiptHandle\", \"aaaaaaaaa\")\n         .addFormParam(\"ChangeMessageVisibilityBatchRequestEntry.1.VisibilityTimeout\", \"1\")\n         .addFormParam(\"ChangeMessageVisibilityBatchRequestEntry.2.Id\", \"foo2\")\n         .addFormParam(\"ChangeMessageVisibilityBatchRequestEntry.2.ReceiptHandle\", \"bbbbbbbbb\")\n         .addFormParam(\"ChangeMessageVisibilityBatchRequestEntry.2.VisibilityTimeout\", \"10\")\n         .addFormParam(\"Signature\", \"KjDusYiiC3hTdy3ZxLwBRHryrNoNaFb2AHJqUDu3mtQ=\")\n         .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n         .addFormParam(\"SignatureVersion\", \"2\")\n         .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n         .addFormParam(\"Version\", \"2011-10-01\")\n         .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testChangeMessageVisibilityTableWhenResponseIs2xx() throws Exception {\n\n      HttpResponse sendMessageResponse = HttpResponse.builder()\n            .statusCode(200)\n            .payload(payloadFromResourceWithContentType(\"/change_message_visibility_batch.xml\", \"text/xml\")).build();\n\n      SQSApi apiWhenExist = requestSendsResponse(changeMessageVisibilityTable, sendMessageResponse);\n\n      assertEquals(apiWhenExist.getMessageApiForQueue(queue).changeVisibility(ImmutableTable.<String, String, Integer>builder()\n            .put(\"foo1\", \"aaaaaaaaa\", 1)\n            .put(\"foo2\", \"bbbbbbbbb\", 10)\n            .build())\n            .toString(), new ChangeMessageVisibilityBatchResponseTest().expected().toString());\n   }\n\n   public HttpRequest changeMessageVisibilityMap = HttpRequest.builder()\n         .method(\"POST\")\n         .endpoint(\"https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/\")\n         .addHeader(\"Host\", \"sqs.us-east-1.amazonaws.com\")\n         .addFormParam(\"Action\", \"ChangeMessageVisibilityBatch\")\n         .addFormParam(\"ChangeMessageVisibilityBatchRequestEntry.1.Id\", \"1\")\n         .addFormParam(\"ChangeMessageVisibilityBatchRequestEntry.1.ReceiptHandle\", \"aaaaaaaaa\")\n         .addFormParam(\"ChangeMessageVisibilityBatchRequestEntry.1.VisibilityTimeout\", \"1\")\n         .addFormParam(\"ChangeMessageVisibilityBatchRequestEntry.2.Id\", \"2\")\n         .addFormParam(\"ChangeMessageVisibilityBatchRequestEntry.2.ReceiptHandle\", \"bbbbbbbbb\")\n         .addFormParam(\"ChangeMessageVisibilityBatchRequestEntry.2.VisibilityTimeout\", \"10\")\n         .addFormParam(\"Signature\", \"zj2cftkpHtiYb9iOjPR3AhcVhoobi0JvOy22PvQJtho=\")\n         .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n         .addFormParam(\"SignatureVersion\", \"2\")\n         .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n         .addFormParam(\"Version\", \"2011-10-01\")\n         .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n   \n   public void testChangeMessageVisibilityMapWhenResponseIs2xx() throws Exception {\n\n      HttpResponse sendMessageResponse = HttpResponse.builder()\n            .statusCode(200)\n            .payload(payloadFromResourceWithContentType(\"/change_message_visibility_batch.xml\", \"text/xml\")).build();\n\n      SQSApi apiWhenExist = requestSendsResponse(changeMessageVisibilityMap, sendMessageResponse);\n\n      assertEquals(\n            apiWhenExist.getMessageApiForQueue(queue).changeVisibility(ImmutableMap.of(\"aaaaaaaaa\", 1, \"bbbbbbbbb\", 10))\n                  .toString(), new ChangeMessageVisibilityBatchResponseTest().expected().toString());\n   }\n\n   public HttpRequest changeMessageVisibilityMapInt = HttpRequest.builder().method(\"POST\")\n                                                                           .endpoint(\"https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/\")\n                                                                           .addHeader(\"Host\", \"sqs.us-east-1.amazonaws.com\")\n                                                                           .addFormParam(\"Action\", \"ChangeMessageVisibilityBatch\")\n                                                                           .addFormParam(\"ChangeMessageVisibilityBatchRequestEntry.1.Id\", \"foo1\")\n                                                                           .addFormParam(\"ChangeMessageVisibilityBatchRequestEntry.1.ReceiptHandle\", \"aaaaaaaaa\")\n                                                                           .addFormParam(\"ChangeMessageVisibilityBatchRequestEntry.1.VisibilityTimeout\", \"10\")\n                                                                           .addFormParam(\"ChangeMessageVisibilityBatchRequestEntry.2.Id\", \"foo2\")\n                                                                           .addFormParam(\"ChangeMessageVisibilityBatchRequestEntry.2.ReceiptHandle\", \"bbbbbbbbb\")\n                                                                           .addFormParam(\"ChangeMessageVisibilityBatchRequestEntry.2.VisibilityTimeout\", \"10\")\n                                                                           .addFormParam(\"Signature\", \"y/gaaxoE5wrG2P7NIAyfDo7DTgRx2PLJUi9/zNnWQ6A=\")\n                                                                           .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n                                                                           .addFormParam(\"SignatureVersion\", \"2\")\n                                                                           .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n                                                                           .addFormParam(\"Version\", \"2011-10-01\")\n                                                                           .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testChangeMessageVisibilityMapIntWhenResponseIs2xx() throws Exception {\n\n      HttpResponse sendMessageResponse = HttpResponse.builder()\n            .statusCode(200)\n            .payload(payloadFromResourceWithContentType(\"/change_message_visibility_batch.xml\", \"text/xml\")).build();\n\n      SQSApi apiWhenExist = requestSendsResponse(changeMessageVisibilityMapInt, sendMessageResponse);\n\n      assertEquals(apiWhenExist.getMessageApiForQueue(queue).changeVisibility(ImmutableMap.<String, String>builder()\n            .put(\"foo1\", \"aaaaaaaaa\")\n            .put(\"foo2\", \"bbbbbbbbb\")\n            .build(), 10)\n            .toString(), new ChangeMessageVisibilityBatchResponseTest().expected().toString());\n   }\n\n   public HttpRequest changeMessageVisibilityIterableInt = HttpRequest.builder().method(\"POST\")\n                                                                      .endpoint(\"https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/\")\n                                                                      .addHeader(\"Host\", \"sqs.us-east-1.amazonaws.com\")\n                                                                      .addFormParam(\"Action\", \"ChangeMessageVisibilityBatch\")\n                                                                      .addFormParam(\"ChangeMessageVisibilityBatchRequestEntry.1.Id\", \"1\")\n                                                                      .addFormParam(\"ChangeMessageVisibilityBatchRequestEntry.1.ReceiptHandle\", \"aaaaaaaaa\")\n                                                                      .addFormParam(\"ChangeMessageVisibilityBatchRequestEntry.1.VisibilityTimeout\", \"10\")\n                                                                      .addFormParam(\"ChangeMessageVisibilityBatchRequestEntry.2.Id\", \"2\")\n                                                                      .addFormParam(\"ChangeMessageVisibilityBatchRequestEntry.2.ReceiptHandle\", \"bbbbbbbbb\")\n                                                                      .addFormParam(\"ChangeMessageVisibilityBatchRequestEntry.2.VisibilityTimeout\", \"10\")\n                                                                      .addFormParam(\"Signature\", \"f5aq7zdKFErM3+IdtDX5NOzPO7mqCRzPGj2wUUEWjgE=\")\n                                                                      .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n                                                                      .addFormParam(\"SignatureVersion\", \"2\")\n                                                                      .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n                                                                      .addFormParam(\"Version\", \"2011-10-01\")\n                                                                      .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n   \n   public void testChangeMessageVisibilityIterableIntWhenResponseIs2xx() throws Exception {\n\n      HttpResponse sendMessageResponse = HttpResponse.builder()\n            .statusCode(200)\n            .payload(payloadFromResourceWithContentType(\"/change_message_visibility_batch.xml\", \"text/xml\")).build();\n\n      SQSApi apiWhenExist = requestSendsResponse(changeMessageVisibilityIterableInt, sendMessageResponse);\n\n      assertEquals(\n            apiWhenExist.getMessageApiForQueue(queue).changeVisibility(ImmutableSet.of(\"aaaaaaaaa\", \"bbbbbbbbb\"), 10)\n                  .toString(), new ChangeMessageVisibilityBatchResponseTest().expected().toString());\n   }\n}\n"
  },
  {
    "path": "apis/sqs/src/test/java/org/jclouds/sqs/features/MessageApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.features;\n\nimport static org.jclouds.sqs.options.ReceiveMessageOptions.Builder.attribute;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\n\nimport java.net.URI;\n\nimport org.jclouds.sqs.internal.BaseSQSApiLiveTest;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.hash.HashCode;\nimport com.google.common.hash.Hashing;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"MessageApiLiveTest\")\npublic class MessageApiLiveTest extends BaseSQSApiLiveTest {\n\n   public MessageApiLiveTest() {\n      prefix = prefix + \"-message\";\n   }\n\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   @Override\n   public void setup() {\n      super.setup();\n      recreateQueueInRegion(prefix, null);\n   }\n\n   String message = \"hardyharhar\";\n   HashCode md5 = Hashing.md5().hashString(message, Charsets.UTF_8);\n\n   public void testSendMessage() {\n      for (URI queue : queues) {\n         assertEquals(api(queue).send(message).getMD5(), md5);\n      }\n   }\n\n   @Test(dependsOnMethods = \"testSendMessage\")\n   public void testReceiveMessageWithoutHidingMessage() {\n      for (URI queue : queues) {\n         assertEquals(api(queue).receive(attribute(\"All\").visibilityTimeout(0)).getMD5(), md5);\n      }\n   }\n\n   String receiptHandle;\n\n   @Test(dependsOnMethods = \"testReceiveMessageWithoutHidingMessage\")\n   public void testChangeMessageVisibility() {\n      for (URI queue : queues) {\n         MessageApi messageApi = api(queue);\n         // start hiding it at 5 seconds\n         receiptHandle = messageApi.receive(attribute(\"None\").visibilityTimeout(5)).getReceiptHandle();\n         // hidden message, so we can't see it\n         assertNull(messageApi.receive());\n         // this should unhide it\n         messageApi.changeVisibility(receiptHandle, 0);\n         // so we can see it again\n         assertEquals(messageApi.receive(attribute(\"All\").visibilityTimeout(0)).getMD5(), md5);\n      }\n   }\n\n   @Test(dependsOnMethods = \"testChangeMessageVisibility\")\n   public void testDeleteMessage() throws InterruptedException {\n      for (URI queue : queues) {\n         api(queue).delete(receiptHandle);\n         assertNoMessages(queue);\n      }\n   }\n\n   private MessageApi api(URI queue) {\n      return api.getMessageApiForQueue(queue);\n   }\n}\n"
  },
  {
    "path": "apis/sqs/src/test/java/org/jclouds/sqs/features/PermissionApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.features;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.sqs.SQSApi;\nimport org.jclouds.sqs.domain.Action;\nimport org.jclouds.sqs.internal.BaseSQSApiExpectTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"PermissionApiExpectTest\")\npublic class PermissionApiExpectTest extends BaseSQSApiExpectTest {\n   \n   public HttpRequest addPermission = HttpRequest.builder()\n         .method(\"POST\")\n         .endpoint(\"https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/\")\n         .addHeader(\"Host\", \"sqs.us-east-1.amazonaws.com\")\n         .addFormParam(\"Action\", \"AddPermission\")\n         .addFormParam(\"AWSAccountId.1\", \"125074342641\")\n         .addFormParam(\"ActionName.1\", \"ReceiveMessage\")\n         .addFormParam(\"Label\", \"testLabel\")\n         .addFormParam(\"Signature\", \"J9sV4q1rJ7dWYJDQp9JxsfEKNXQhpQBYIwBYi1IeXV0=\")\n         .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n         .addFormParam(\"SignatureVersion\", \"2\")\n         .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n         .addFormParam(\"Version\", \"2011-10-01\")\n         .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testAddPermissionWhenResponseIs2xx() throws Exception {\n\n      HttpResponse addPermissionResponse = HttpResponse.builder()\n            .statusCode(200)\n            .payload(\n                  payloadFromStringWithContentType(\n                        \"<AddPermissionsResponse><ResponseMetadata><RequestId>b5293cb5-d306-4a17-9048-b263635abe42</RequestId></ResponseMetadata></AddPermissionsResponse>\",\n                        \"text/xml\")).build();\n\n      SQSApi apiWhenExist = requestSendsResponse(addPermission, addPermissionResponse);\n\n      apiWhenExist.getPermissionApiForQueue(queue).addPermissionToAccount(\"testLabel\", Action.RECEIVE_MESSAGE, \"125074342641\");\n   }\n   \n   public HttpRequest removePermission = HttpRequest.builder()\n         .method(\"POST\")\n         .endpoint(\"https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/\")\n         .addHeader(\"Host\", \"sqs.us-east-1.amazonaws.com\")\n         .addFormParam(\"Action\", \"RemovePermission\")\n         .addFormParam(\"Label\", \"testLabel\")\n         .addFormParam(\"Signature\", \"VOA0L1uRVKQDQL1Klt0cYUajGoxN4Ur+7ISQ2I4RpRs=\")\n         .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n         .addFormParam(\"SignatureVersion\", \"2\")\n         .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n         .addFormParam(\"Version\", \"2011-10-01\")\n         .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testRemovePermissionWhenResponseIs2xx() throws Exception {\n\n      HttpResponse removePermissionResponse = HttpResponse.builder()\n            .statusCode(200)\n            .payload(\n                  payloadFromStringWithContentType(\n                        \"<RemovePermissionsResponse><ResponseMetadata><RequestId>b5293cb5-d306-4a17-9048-b263635abe42</RequestId></ResponseMetadata></RemovePermissionsResponse>\",\n                        \"text/xml\")).build();\n\n      SQSApi apiWhenExist = requestSendsResponse(removePermission, removePermissionResponse);\n\n      apiWhenExist.getPermissionApiForQueue(queue).remove(\"testLabel\");\n   }\n}\n"
  },
  {
    "path": "apis/sqs/src/test/java/org/jclouds/sqs/features/PermissionApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.features;\n\nimport static com.google.common.util.concurrent.MoreExecutors.newDirectExecutorService;\nimport static org.jclouds.providers.AnonymousProviderMetadata.forApiOnEndpoint;\nimport static org.jclouds.sqs.reference.SQSParameters.ACTION;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.Closeable;\nimport java.net.URI;\n\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.concurrent.config.ExecutorServiceModule;\nimport org.jclouds.rest.annotations.FormParams;\nimport org.jclouds.rest.annotations.XMLResponseParser;\nimport org.jclouds.sqs.domain.Action;\nimport org.jclouds.sqs.domain.QueueAttributes;\nimport org.jclouds.sqs.internal.BaseSQSApiLiveTest;\nimport org.jclouds.sqs.xml.ValueHandler;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"PermissionApiLiveTest\")\npublic class PermissionApiLiveTest extends BaseSQSApiLiveTest {\n\n   public PermissionApiLiveTest() {\n      prefix = prefix + \"-permission\";\n   }\n\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   @Override\n   public void setup() {\n      super.setup();\n      recreateQueueInRegion(prefix, null);\n   }\n\n   interface AnonymousAttributesApi extends Closeable {\n      @POST\n      @Path(\"/\")\n      @FormParams(keys = { ACTION, \"AttributeName.1\" }, values = { \"GetQueueAttributes\", \"QueueArn\" })\n      @XMLResponseParser(ValueHandler.class)\n      String getQueueArn();\n   }\n\n   public void testAddAnonymousPermission() throws InterruptedException {\n      for (URI queue : queues) {\n         QueueAttributes attributes = api.getQueueApi().getAttributes(queue);\n         assertNoPermissions(queue);\n\n         String accountToAuthorize = getOwner(queue);\n         api.getPermissionApiForQueue(queue).addPermissionToAccount(\"fubar\", Action.GET_QUEUE_ATTRIBUTES,\n               accountToAuthorize);\n\n         String policyForAuthorizationByAccount = assertPolicyPresent(queue);\n\n         String policyForAnonymous = policyForAuthorizationByAccount.replace(\"\\\"\" + accountToAuthorize + \"\\\"\", \"\\\"*\\\"\");\n         api.getQueueApi().setAttribute(queue, \"Policy\", policyForAnonymous);\n\n         assertEquals(getAnonymousAttributesApi(queue).getQueueArn(), attributes.getQueueArn());\n      }\n   }\n\n   @Test(dependsOnMethods = \"testAddAnonymousPermission\")\n   public void testRemovePermission() throws InterruptedException {\n      for (URI queue : queues) {\n         api.getPermissionApiForQueue(queue).remove(\"fubar\");\n         assertNoPermissions(queue);\n      }\n   }\n\n   private AnonymousAttributesApi getAnonymousAttributesApi(URI queue) {\n      return ContextBuilder.newBuilder(forApiOnEndpoint(AnonymousAttributesApi.class, queue.toASCIIString()))\n            .modules(ImmutableSet.<Module> of(new ExecutorServiceModule(newDirectExecutorService())))\n            .buildApi(AnonymousAttributesApi.class);\n   }\n\n}\n"
  },
  {
    "path": "apis/sqs/src/test/java/org/jclouds/sqs/features/QueueApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\n\nimport java.net.URI;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.sqs.SQSApi;\nimport org.jclouds.sqs.functions.MapToQueueAttributesTest;\nimport org.jclouds.sqs.internal.BaseSQSApiExpectTest;\nimport org.jclouds.sqs.parse.CreateQueueResponseTest;\nimport org.jclouds.sqs.parse.GetQueueAttributesResponseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\", testName = \"QueueApiExpectTest\")\npublic class QueueApiExpectTest extends BaseSQSApiExpectTest {\n   public HttpRequest getQueueUrl = HttpRequest.builder()\n         .method(\"POST\")\n         .endpoint(\"https://sqs.us-east-1.amazonaws.com/\")\n         .addHeader(\"Host\", \"sqs.us-east-1.amazonaws.com\")\n         .addFormParam(\"Action\", \"GetQueueUrl\")\n         .addFormParam(\"QueueName\", \"queueName\")\n         .addFormParam(\"Signature\", \"ZjHLpNl6NLqK+sqOyEFqEJMWGeOLuNBd3+0Z9RGPYWU=\")\n         .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n         .addFormParam(\"SignatureVersion\", \"2\")\n         .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n         .addFormParam(\"Version\", \"2011-10-01\")\n         .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testGetQueueUrlWhenResponseIs2xx() throws Exception {\n      \n      HttpResponse getQueueUrlResponse = HttpResponse.builder()\n            .statusCode(200)\n            .payload(payloadFromResourceWithContentType(\"/get_queue_url.xml\", \"text/xml\")).build();\n\n\n      SQSApi apiWhenExist = requestSendsResponse(getQueueUrl, getQueueUrlResponse);\n\n      assertEquals(apiWhenExist.getQueueApi().get(\"queueName\"), URI.create(\"http://sqs.us-east-1.amazonaws.com/123456789012/testQueue\"));\n   }\n   \n   public HttpRequest getQueueUrlByOwner = HttpRequest.builder()\n         .method(\"POST\")\n         .endpoint(\"https://sqs.us-east-1.amazonaws.com/\")\n         .addHeader(\"Host\", \"sqs.us-east-1.amazonaws.com\")\n         .addFormParam(\"Action\", \"GetQueueUrl\")\n         .addFormParam(\"QueueName\", \"queueName\")\n         .addFormParam(\"QueueOwnerAWSAccountId\", \"120908098979\")\n         .addFormParam(\"Signature\", \"O0E+3jh2vN6bKqmb4/XPTHUmPO1iat9o8YnIFH463g8=\")\n         .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n         .addFormParam(\"SignatureVersion\", \"2\")\n         .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n         .addFormParam(\"Version\", \"2011-10-01\")\n         .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testGetQueueUrlByOwnerWhenResponseIs2xx() throws Exception {\n      \n      HttpResponse getQueueUrlResponse = HttpResponse.builder()\n            .statusCode(200)\n            .payload(payloadFromResourceWithContentType(\"/get_queue_url.xml\", \"text/xml\")).build();\n\n\n      SQSApi apiWhenExist = requestSendsResponse(getQueueUrlByOwner, getQueueUrlResponse);\n\n      assertEquals(apiWhenExist.getQueueApi().getInAccount(\"queueName\", \"120908098979\"), URI.create(\"http://sqs.us-east-1.amazonaws.com/123456789012/testQueue\"));\n   }\n   \n   // when the queue doesn't exist, or you don't have access to it\n   public void testGetQueueUrlByOwnerWhenResponseIs400ReturnsNull() throws Exception {\n      \n      HttpResponse getQueueUrlResponse = HttpResponse.builder()\n            .statusCode(400)\n            .payload(\n                  payloadFromStringWithContentType(\n                        \"<ErrorResponse><Error><Type>Sender</Type><Code>AWS.SimpleQueueService.NonExistentQueue</Code><Message>The specified queue does not exist or you do not have access to it.</Message><Detail/></Error><RequestId>194a169f-4483-5bb1-8cb6-5e4ac865909a</RequestId></ErrorResponse>\",\n                        \"text/xml\")).build();\n\n      SQSApi apiWhenExist = requestSendsResponse(getQueueUrlByOwner, getQueueUrlResponse);\n\n      assertNull(apiWhenExist.getQueueApi().getInAccount(\"queueName\", \"120908098979\"));\n   }\n   \n   public HttpRequest createQueue = HttpRequest.builder()\n         .method(\"POST\")\n         .endpoint(\"https://sqs.us-east-1.amazonaws.com/\")\n         .addHeader(\"Host\", \"sqs.us-east-1.amazonaws.com\")\n         .addFormParam(\"Action\", \"CreateQueue\")\n         .addFormParam(\"QueueName\", \"queueName\")\n         .addFormParam(\"Signature\", \"I7tmwiCzJ9cvw79pmlz1rOILh2C2ZV6OpLk23JGx6AU=\")\n         .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n         .addFormParam(\"SignatureVersion\", \"2\")\n         .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n         .addFormParam(\"Version\", \"2011-10-01\")\n         .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testCreateQueueWhenResponseIs2xx() throws Exception {\n      \n      HttpResponse createQueueResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResourceWithContentType(\"/create_queue.xml\", \"text/xml\")).build();\n\n      SQSApi apiWhenExist = requestSendsResponse(createQueue, createQueueResponse);\n\n      assertEquals(apiWhenExist.getQueueApi().create(\"queueName\").toString(), new CreateQueueResponseTest().expected()\n            .toString());\n   }\n   \n   public HttpRequest getQueueAttribute = HttpRequest.builder()\n         .method(\"POST\")\n         .endpoint(\"https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/\")\n         .addHeader(\"Host\", \"sqs.us-east-1.amazonaws.com\")\n         .addFormParam(\"Action\", \"GetQueueAttributes\")\n         .addFormParam(\"AttributeName.1\", \"VisibilityTimeout\")\n         .addFormParam(\"Signature\", \"AfydayBBaIk4UGikHHY1CFNmOOAcTnogpFWydZyNass=\")\n         .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n         .addFormParam(\"SignatureVersion\", \"2\")\n         .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n         .addFormParam(\"Version\", \"2011-10-01\")\n         .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testGetQueueAttributeWhenResponseIs2xx() throws Exception {\n      \n      HttpResponse getQueueAttributeResponse = HttpResponse.builder()\n            .statusCode(200)\n            .payload(\n                  payloadFromStringWithContentType(\n                        \"<GetQueueAttributesResponse><GetQueueAttributesResult><Attribute><Name>VisibilityTimeout</Name><Value>30</Value></Attribute></GetQueueAttributesResult></GetQueueAttributesResponse>\",\n                        \"text/xml\")).build();\n\n      SQSApi apiWhenExist = requestSendsResponse(getQueueAttribute, getQueueAttributeResponse);\n\n      assertEquals(apiWhenExist.getQueueApi().getAttribute(queue, \"VisibilityTimeout\"), \"30\");\n   }\n   \n   public HttpRequest getQueueAttributes = HttpRequest.builder()\n         .method(\"POST\")\n         .endpoint(\"https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/\")\n         .addHeader(\"Host\", \"sqs.us-east-1.amazonaws.com\")\n         .addFormParam(\"Action\", \"GetQueueAttributes\")\n         .addFormParam(\"AttributeName.1\", \"All\")\n         .addFormParam(\"Signature\", \"welFLn0TV6JlH6s6s60XZTJeJfFXGiXN4qNPrBx7aHc=\")\n         .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n         .addFormParam(\"SignatureVersion\", \"2\")\n         .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n         .addFormParam(\"Version\", \"2011-10-01\")\n         .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testGetQueueAttributesWhenResponseIs2xx() throws Exception {\n      \n      HttpResponse getQueueAttributesResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResourceWithContentType(\"/attributes.xml\", \"text/xml\")).build();\n\n      SQSApi apiWhenExist = requestSendsResponse(getQueueAttributes, getQueueAttributesResponse);\n\n      assertEquals(apiWhenExist.getQueueApi().getAttributes(queue).toString(), new MapToQueueAttributesTest()\n            .expected().toString());\n   }\n   \n   public HttpRequest getQueueAttributesSubset = HttpRequest.builder()\n         .method(\"POST\")\n         .endpoint(\"https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/\")\n         .addHeader(\"Host\", \"sqs.us-east-1.amazonaws.com\")\n         .addFormParam(\"Action\", \"GetQueueAttributes\")\n         .addFormParam(\"AttributeName.1\", \"VisibilityTimeout\")\n         .addFormParam(\"AttributeName.2\", \"DelaySeconds\")\n         .addFormParam(\"Signature\", \"9KaiOOWWyFPTVMOnyHA3ZoXbPBPSD4AZ4q460UNMfDs=\")\n         .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n         .addFormParam(\"SignatureVersion\", \"2\")\n         .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n         .addFormParam(\"Version\", \"2011-10-01\")\n         .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testGetQueueAttributesSubsetWhenResponseIs2xx() throws Exception {\n      \n      HttpResponse getQueueAttributesSubsetResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResourceWithContentType(\"/attributes.xml\", \"text/xml\")).build();\n\n      SQSApi apiWhenExist = requestSendsResponse(getQueueAttributesSubset, getQueueAttributesSubsetResponse);\n\n      assertEquals(apiWhenExist.getQueueApi()\n            .getAttributes(queue, ImmutableSet.of(\"VisibilityTimeout\", \"DelaySeconds\")).toString(),\n            new GetQueueAttributesResponseTest().expected().toString());\n   }\n   \n   public HttpRequest setQueueAttribute = HttpRequest.builder()\n         .method(\"POST\")\n         .endpoint(\"https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/\")\n         .addHeader(\"Host\", \"sqs.us-east-1.amazonaws.com\")\n         .addFormParam(\"Action\", \"SetQueueAttributes\")\n         .addFormParam(\"Attribute.Name\", \"MaximumMessageSize\")\n         .addFormParam(\"Attribute.Value\", \"1\")\n         .addFormParam(\"Signature\", \"ktBkQ3c/rwGcBSec0fkckfo73xmcoTuub5fxudM1qh0=\")\n         .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n         .addFormParam(\"SignatureVersion\", \"2\")\n         .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n         .addFormParam(\"Version\", \"2011-10-01\")\n         .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testSetQueueAttributeWhenResponseIs2xx() throws Exception {\n\n      HttpResponse setQueueAttributeResponse = HttpResponse.builder()\n            .statusCode(200)\n            .payload(\n                  payloadFromStringWithContentType(\n                        \"<SetQueueAttributesResponse><ResponseMetadata><RequestId>b5293cb5-d306-4a17-9048-b263635abe42</RequestId></ResponseMetadata></SetQueueAttributesResponse>\",\n                        \"text/xml\")).build();\n\n      SQSApi apiWhenExist = requestSendsResponse(setQueueAttribute, setQueueAttributeResponse);\n\n      apiWhenExist.getQueueApi().setAttribute(queue, \"MaximumMessageSize\", \"1\");\n   }\n\n}\n"
  },
  {
    "path": "apis/sqs/src/test/java/org/jclouds/sqs/features/QueueApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.features;\n\nimport static com.google.common.collect.Iterables.getLast;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\n\nimport java.net.URI;\nimport java.util.Map;\nimport java.util.UUID;\n\nimport org.jclouds.sqs.internal.BaseSQSApiLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"QueueApiLiveTest\")\npublic class QueueApiLiveTest extends BaseSQSApiLiveTest {\n\n   public QueueApiLiveTest() {\n      prefix = prefix + \"-queue\";\n   }\n\n   @Test\n   public void testListQueues() throws InterruptedException {\n      listQueuesInRegion(null);\n   }\n\n   protected void listQueuesInRegion(String region) throws InterruptedException {\n      FluentIterable<URI> allResults = api.getQueueApiForRegion(region).list();\n      assertNotNull(allResults);\n      if (allResults.size() >= 1) {\n         URI queue = getLast(allResults);\n         assertQueueInList(region, queue);\n      }\n   }\n   \n   @Test\n   public void testGracefulNoQueue() throws InterruptedException {\n      assertNull(api.getQueueApi().get(UUID.randomUUID().toString()));\n   }\n   \n   @Test\n   public void testCanRecreateQueueGracefully() throws InterruptedException {\n      recreateQueueInRegion(prefix, null);\n      recreateQueueInRegion(prefix, null);\n   }\n\n   @Test(dependsOnMethods = \"testCanRecreateQueueGracefully\")\n   public void testCreateQueueWhenAlreadyExistsReturnsURI() {\n      for (URI queue : queues) {\n         assertEquals(api.getQueueApi().create(prefix), queue);\n      }\n   }\n   \n   @Test(dependsOnMethods = \"testCanRecreateQueueGracefully\")\n   public void testGet() {\n      for (URI queue : queues) {\n         assertEquals(api.getQueueApi().get(prefix), queue);\n      }\n   }\n\n   @Test(dependsOnMethods = \"testCanRecreateQueueGracefully\")\n   public void testGetInAccount() {\n      for (URI queue : queues) {\n         assertEquals(api.getQueueApi().getInAccount(prefix, getOwner(queue)), queue);\n      }\n   }\n   \n   @Test(dependsOnMethods = \"testCanRecreateQueueGracefully\")\n   public void testGetQueueAttributes() {\n      for (URI queue : queues) {\n         Map<String, String> attributes = api.getQueueApi().getAttributes(queue, ImmutableSet.of(\"All\"));\n         assertEquals(api.getQueueApi().getAttributes(queue, attributes.keySet()), attributes);\n      }\n   }\n\n   @Test(dependsOnMethods = \"testGetQueueAttributes\")\n   public void testSetQueueAttribute() {\n      for (URI queue : queues) {\n         api.getQueueApi().setAttribute(queue, \"MaximumMessageSize\", \"1024\");\n         assertEquals(api.getQueueApi().getAttributes(queue).getMaximumMessageSize(), 1024);\n      }\n   }\n}\n"
  },
  {
    "path": "apis/sqs/src/test/java/org/jclouds/sqs/functions/MapToQueueAttributesTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Date;\n\nimport org.jclouds.sqs.domain.QueueAttributes;\nimport org.jclouds.sqs.parse.GetQueueAttributesResponseTest;\nimport org.testng.annotations.Test;\n\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"MapToQueueAttributesTest\")\npublic class MapToQueueAttributesTest {\n\n   public void test() {\n      \n\n      QueueAttributes expected = expected();\n      \n      MapToQueueAttributes fn = new MapToQueueAttributes();\n\n      QueueAttributes result = fn.apply(new GetQueueAttributesResponseTest().expected());\n\n      assertEquals(result.toString(), expected.toString());\n\n   }\n\n   public QueueAttributes expected() {\n      return QueueAttributes.builder()\n                            .queueArn(\"arn:aws:sqs:us-east-1:993194456877:adrian-sqs1\")\n                            .approximateNumberOfMessages(0)\n                            .approximateNumberOfMessagesNotVisible(0)\n                            .approximateNumberOfMessagesDelayed(0)\n                            .createdTimestamp(new Date(1347566436L))\n                            .lastModifiedTimestamp(new Date(1347566436))\n                            .visibilityTimeout(30)\n                            .maximumMessageSize(65536)\n                            .messageRetentionPeriod(345600)\n                            .delaySeconds(0)\n                            .build();\n   }\n}\n"
  },
  {
    "path": "apis/sqs/src/test/java/org/jclouds/sqs/handlers/SQSErrorRetryHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.handlers;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.concurrent.TimeUnit;\n\nimport org.jclouds.aws.domain.AWSError;\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.handlers.BackoffLimitedRetryHandler;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Stopwatch;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code SQSErrorRetryHandler}\n */\n@Test(groups = \"unit\", testName = \"SQSErrorRetryHandlerTest\")\npublic class SQSErrorRetryHandlerTest {\n\n   String code = \"AWS.SimpleQueueService.QueueDeletedRecently\";\n   AWSError error;\n   HttpResponse response = HttpResponse.builder().statusCode(400)\n         .payload(String.format(\"<Error><Code>%s</Code></Error>\", code)).build();\n\n   public SQSErrorRetryHandlerTest() {\n      error = new AWSError();\n      error.setCode(code);\n   }\n   \n   public void testQueueDeletedRecentlyRetriesWhen59SleepsAndTries() {\n\n      SQSErrorRetryHandler retry = new SQSErrorRetryHandler(createMock(AWSUtils.class),\n            createMock(BackoffLimitedRetryHandler.class), ImmutableSet.<String> of(), 60, 100);\n\n      HttpCommand command = createHttpCommandForFailureCount(59);\n\n      Stopwatch watch = Stopwatch.createStarted();\n      assertTrue(retry.shouldRetryRequestOnError(command, response, error));\n      assertEquals(command.getFailureCount(), 60);\n      // allow for slightly inaccurate system timers\n      assertTrue(watch.stop().elapsed(TimeUnit.MILLISECONDS) >= 98);\n   }\n   \n\n   \n   public void testQueueDeletedRecentlyRetriesWhen60DoesntTry() {\n\n      SQSErrorRetryHandler retry = new SQSErrorRetryHandler(createMock(AWSUtils.class),\n            createMock(BackoffLimitedRetryHandler.class), ImmutableSet.<String> of(), 60, 100);\n\n      HttpCommand command = createHttpCommandForFailureCount(60);\n\n      Stopwatch watch = Stopwatch.createStarted();\n      assertFalse(retry.shouldRetryRequestOnError(command, response, error));\n      assertEquals(command.getFailureCount(), 61);\n      assertTrue(watch.stop().elapsed(TimeUnit.MILLISECONDS) < 100);\n   }\n   \n   HttpCommand createHttpCommandForFailureCount(final int failureCount) {\n      HttpCommand command = new HttpCommand(HttpRequest.builder().method(\"GET\").endpoint(\"http://localhost\").build());\n      while (command.getFailureCount() != failureCount)\n         command.incrementFailureCount();\n      return command;\n   }\n}\n"
  },
  {
    "path": "apis/sqs/src/test/java/org/jclouds/sqs/internal/BaseSQSApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.internal;\n\nimport org.jclouds.sqs.SQSApi;\n\npublic class BaseSQSApiExpectTest extends BaseSQSExpectTest<SQSApi> {\n\n}\n"
  },
  {
    "path": "apis/sqs/src/test/java/org/jclouds/sqs/internal/BaseSQSApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.internal;\n\nimport static com.google.common.collect.Iterables.get;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.Set;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport org.jclouds.apis.BaseApiLiveTest;\nimport org.jclouds.sqs.SQSApi;\nimport org.jclouds.sqs.domain.Message;\nimport org.jclouds.sqs.features.QueueApi;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.Sets;\nimport com.google.common.util.concurrent.Atomics;\nimport com.google.common.util.concurrent.Uninterruptibles;\n\n@Test(groups = \"live\")\npublic class BaseSQSApiLiveTest extends BaseApiLiveTest<SQSApi> {\n\n   protected String prefix = System.getProperty(\"user.name\") + \"-sqs\";\n\n   public BaseSQSApiLiveTest() {\n      provider = \"sqs\";\n   }\n\n   protected Set<URI> queues = Sets.newHashSet();\n\n   protected String getOwner(URI queue) {\n      return get(Splitter.on('/').split(queue.getPath()), 1);\n   }\n\n   protected String recreateQueueInRegion(String queueName, String region) {\n      QueueApi queueApi = api.getQueueApiForRegion(region);\n      URI result = queueApi.get(queueName);\n      if (result != null) {\n         queueApi.delete(result);\n      }\n      URI queue = queueApi.create(queueName);\n      assertQueueInList(region, queue);\n      queues.add(queue);\n      return queueName;\n   }\n\n   protected String assertPolicyPresent(final URI queue) {\n      final AtomicReference<String> policy = Atomics.newReference();\n      assertEventually(new Runnable() {\n         public void run() {\n            String policyForAuthorizationByAccount = api.getQueueApi().getAttribute(queue, \"Policy\");\n\n            assertNotNull(policyForAuthorizationByAccount);\n            policy.set(policyForAuthorizationByAccount);\n         }\n      });\n      return policy.get();\n   }\n\n   protected void assertNoPermissions(final URI queue) {\n      assertEventually(new Runnable() {\n         public void run() {\n            String policy = api.getQueueApi().getAttribute(queue, \"Policy\");\n            assertTrue(policy == null || policy.indexOf(\"\\\"Statement\\\":[]\") != -1, policy);\n         }\n      });\n   }\n\n   protected void assertNoMessages(final URI queue) {\n      assertEventually(new Runnable() {\n         public void run() {\n            Message message = api.getMessageApiForQueue(queue).receive();\n            assertNull(message, \"message: \" + message + \" left in queue \" + queue);\n         }\n      });\n   }\n\n   protected void assertQueueInList(final String region, URI queue) {\n      final URI finalQ = queue;\n      assertEventually(new Runnable() {\n         public void run() {\n            FluentIterable<URI> result = api.getQueueApiForRegion(region).list();\n            assertNotNull(result);\n            assert result.size() >= 1 : result;\n            assertTrue(result.contains(finalQ), finalQ + \" not in \" + result);\n         }\n      });\n   }\n\n   private static final int INCONSISTENCY_WINDOW = 10000;\n\n   /**\n    * Due to eventual consistency, container commands may not return correctly\n    * immediately. Hence, we will try up to the inconsistency window to see if\n    * the assertion completes.\n    */\n   protected static void assertEventually(Runnable assertion) {\n      long start = System.currentTimeMillis();\n      AssertionError error = null;\n      for (int i = 0; i < 30; i++) {\n         try {\n            assertion.run();\n            if (i > 0)\n               System.err.printf(\"%d attempts and %dms asserting %s%n\", i + 1, System.currentTimeMillis() - start,\n                     assertion.getClass().getSimpleName());\n            return;\n         } catch (AssertionError e) {\n            error = e;\n         }\n         Uninterruptibles.sleepUninterruptibly(INCONSISTENCY_WINDOW / 30, TimeUnit.MILLISECONDS);\n      }\n      if (error != null)\n         throw error;\n   }\n\n   @Override\n   @AfterClass(groups = \"live\")\n   protected void tearDown() {\n      for (URI queue : queues) {\n         api.getQueueApi().delete(queue);\n      }\n      super.tearDown();\n   }\n}\n"
  },
  {
    "path": "apis/sqs/src/test/java/org/jclouds/sqs/internal/BaseSQSExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.internal;\n\nimport java.net.URI;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.internal.BaseRestApiExpectTest;\nimport org.jclouds.sqs.config.SQSHttpApiModule;\n\nimport com.google.inject.Module;\n\npublic class BaseSQSExpectTest<T> extends BaseRestApiExpectTest<T> {\n   protected URI queue = URI.create(\"https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/\");\n\n   public BaseSQSExpectTest() {\n      provider = \"sqs\";\n   }\n\n   @ConfiguresHttpApi\n   private static final class TestSQSHttpApiModule extends SQSHttpApiModule {\n\n      @Override\n      protected String provideTimeStamp(final DateService dateService) {\n         return \"2009-11-08T15:54:08.897Z\";\n      }\n   }\n\n   @Override\n   protected Module createModule() {\n      return new TestSQSHttpApiModule();\n   }\n}\n"
  },
  {
    "path": "apis/sqs/src/test/java/org/jclouds/sqs/options/CreateQueueOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.options;\n\nimport static org.jclouds.sqs.options.CreateQueueOptions.Builder.attribute;\nimport static org.jclouds.sqs.options.CreateQueueOptions.Builder.visibilityTimeout;\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code CreateQueueOptions}\n */\n@Test(groups = \"unit\", testName = \"CreateQueueOptionsTest\")\npublic class CreateQueueOptionsTest {\n\n   public void testVisibilityTimeout() {\n      CreateQueueOptions options = new CreateQueueOptions().visibilityTimeout(2);\n      assertEquals(ImmutableSet.of(\"VisibilityTimeout\"), options.buildFormParameters().get(\"Attribute.1.Name\"));\n      assertEquals(ImmutableSet.of(\"2\"), options.buildFormParameters().get(\"Attribute.1.Value\"));\n   }\n\n   public void testVisibilityTimeoutStatic() {\n      CreateQueueOptions options = visibilityTimeout(2);\n      assertEquals(ImmutableSet.of(\"VisibilityTimeout\"), options.buildFormParameters().get(\"Attribute.1.Name\"));\n      assertEquals(ImmutableSet.of(\"2\"), options.buildFormParameters().get(\"Attribute.1.Value\"));\n   }\n\n   public void testAttribute() {\n      CreateQueueOptions options = new CreateQueueOptions().attribute(\"DelaySeconds\", \"1\");\n      assertEquals(ImmutableSet.of(\"DelaySeconds\"), options.buildFormParameters().get(\"Attribute.1.Name\"));\n      assertEquals(ImmutableSet.of(\"1\"), options.buildFormParameters().get(\"Attribute.1.Value\"));\n   }\n\n   public void testAttributeStatic() {\n      CreateQueueOptions options = attribute(\"DelaySeconds\", \"1\");\n      assertEquals(ImmutableSet.of(\"DelaySeconds\"), options.buildFormParameters().get(\"Attribute.1.Name\"));\n      assertEquals(ImmutableSet.of(\"1\"), options.buildFormParameters().get(\"Attribute.1.Value\"));\n   }\n\n}\n"
  },
  {
    "path": "apis/sqs/src/test/java/org/jclouds/sqs/options/ListQueuesOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.options;\n\nimport static org.jclouds.sqs.options.ListQueuesOptions.Builder.queuePrefix;\nimport static org.testng.Assert.assertEquals;\n\nimport com.google.common.collect.ImmutableList;\n\nimport org.jclouds.http.options.HttpRequestOptions;\nimport org.testng.annotations.Test;\n\n/**\n * Tests possible uses of ListQueuesOptions and ListQueuesOptions.Builder.*\n */\npublic class ListQueuesOptionsTest {\n\n   @Test\n   public void testAssignability() {\n      assert HttpRequestOptions.class.isAssignableFrom(ListQueuesOptions.class);\n      assert !String.class.isAssignableFrom(ListQueuesOptions.class);\n   }\n\n   @Test\n   public void testPrefix() {\n      ListQueuesOptions options = new ListQueuesOptions();\n      options.queuePrefix(\"test\");\n      assertEquals(options.buildFormParameters().get(\"QueueNamePrefix\"), ImmutableList.of(\"test\"));\n   }\n\n   @Test\n   public void testNullPrefix() {\n      ListQueuesOptions options = new ListQueuesOptions();\n      assertEquals(options.buildFormParameters().get(\"QueueNamePrefix\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testPrefixStatic() {\n      ListQueuesOptions options = queuePrefix(\"test\");\n      assertEquals(options.buildFormParameters().get(\"QueueNamePrefix\"), ImmutableList.of(\"test\"));\n   }\n\n   public void testNoPrefix() {\n      queuePrefix(null);\n   }\n}\n"
  },
  {
    "path": "apis/sqs/src/test/java/org/jclouds/sqs/options/ReceiveMessageOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.options;\n\nimport static org.jclouds.sqs.options.ReceiveMessageOptions.Builder.attribute;\nimport static org.jclouds.sqs.options.ReceiveMessageOptions.Builder.visibilityTimeout;\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code ReceiveMessageOptions}\n */\n@Test(groups = \"unit\", testName = \"ReceiveMessageOptionsTest\")\npublic class ReceiveMessageOptionsTest {\n\n   public void testVisibilityTimeout() {\n      ReceiveMessageOptions options = new ReceiveMessageOptions().visibilityTimeout(2);\n      assertEquals(ImmutableSet.of(\"2\"), options.buildFormParameters().get(\"VisibilityTimeout\"));\n   }\n\n   public void testVisibilityTimeoutStatic() {\n      ReceiveMessageOptions options = visibilityTimeout(2);\n      assertEquals(ImmutableSet.of(\"2\"), options.buildFormParameters().get(\"VisibilityTimeout\"));\n   }\n\n   public void testAttribute() {\n      ReceiveMessageOptions options = new ReceiveMessageOptions().attribute(\"All\");\n      assertEquals(ImmutableSet.of(\"All\"), options.buildFormParameters().get(\"AttributeName.1\"));\n   }\n\n   public void testAttributeStatic() {\n      ReceiveMessageOptions options = attribute(\"All\");\n      assertEquals(ImmutableSet.of(\"All\"), options.buildFormParameters().get(\"AttributeName.1\"));\n   }\n\n}\n"
  },
  {
    "path": "apis/sqs/src/test/java/org/jclouds/sqs/options/SendMessageOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.options;\n\nimport static org.jclouds.sqs.options.SendMessageOptions.Builder.delaySeconds;\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests possible uses of SendMessageOptions and SendMessageOptions.Builder.*\n */\npublic class SendMessageOptionsTest {\n\n   @Test\n   public void testDelaySeconds() {\n      SendMessageOptions options = new SendMessageOptions();\n      options.delaySeconds(3);\n      assertEquals(options.buildFormParameters().get(\"DelaySeconds\"), ImmutableSet.of(\"3\"));\n   }\n\n   @Test\n   public void testDelaySecondsStatic() {\n      SendMessageOptions options = delaySeconds(3);\n      assertEquals(options.buildFormParameters().get(\"DelaySeconds\"), ImmutableSet.of(\"3\"));\n   }\n\n   public void testNoDelaySeconds() {\n      delaySeconds(null);\n   }\n}\n"
  },
  {
    "path": "apis/sqs/src/test/java/org/jclouds/sqs/parse/ChangeMessageVisibilityBatchResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.parse;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.sqs.domain.BatchResult;\nimport org.jclouds.sqs.xml.ChangeMessageVisibilityBatchResponseHandler;\nimport org.testng.annotations.Test;\n\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"ChangeMessageVisibilityBatchResponseTest\")\npublic class ChangeMessageVisibilityBatchResponseTest extends BaseHandlerTest {\n\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/change_message_visibility_batch.xml\");\n\n      BatchResult<String> expected = expected();\n\n      ChangeMessageVisibilityBatchResponseHandler handler = injector.getInstance(ChangeMessageVisibilityBatchResponseHandler.class);\n      BatchResult<String> result = factory.create(handler).parse(is);\n\n      assertEquals(result.toString(), expected.toString());\n\n   }\n\n   public BatchResult<String> expected() {\n      return BatchResult.<String> builder()\n            .put(\"change_visibility_msg_2\", \"change_visibility_msg_2\")\n            .put(\"change_visibility_msg_3\", \"change_visibility_msg_3\")\n            .build();\n   }\n}\n"
  },
  {
    "path": "apis/sqs/src/test/java/org/jclouds/sqs/parse/CreateQueueResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.parse;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\nimport java.net.URI;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ReturnStringIf2xx;\nimport org.jclouds.sqs.xml.RegexQueueHandler;\nimport org.testng.annotations.Test;\n\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"CreateQueueResponseTest\")\npublic class CreateQueueResponseTest {\n\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/create_queue.xml\");\n\n      URI expected = expected();\n\n      RegexQueueHandler handler = new RegexQueueHandler(new ReturnStringIf2xx());\n      URI result = handler.apply(HttpResponse.builder().statusCode(200).payload(is).build());\n\n      assertEquals(result.toString(), expected.toString());\n\n   }\n\n   public URI expected() {\n      return URI.create(\"https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11\");\n   }\n}\n"
  },
  {
    "path": "apis/sqs/src/test/java/org/jclouds/sqs/parse/DeleteMessageBatchResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.parse;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.sqs.domain.BatchResult;\nimport org.jclouds.sqs.xml.DeleteMessageBatchResponseHandler;\nimport org.testng.annotations.Test;\n\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"DeleteMessageBatchResponseTest\")\npublic class DeleteMessageBatchResponseTest extends BaseHandlerTest {\n\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/delete_message_batch.xml\");\n\n      BatchResult<String> expected = expected();\n\n      DeleteMessageBatchResponseHandler handler = injector.getInstance(DeleteMessageBatchResponseHandler.class);\n      BatchResult<String> result = factory.create(handler).parse(is);\n\n      assertEquals(result.toString(), expected.toString());\n\n   }\n\n   public BatchResult<String> expected() {\n      return BatchResult.<String> builder()\n            .put(\"msg1\", \"msg1\")\n            .put(\"msg2\", \"msg2\")\n            .build();\n   }\n}\n"
  },
  {
    "path": "apis/sqs/src/test/java/org/jclouds/sqs/parse/GetQueueAttributesResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.parse;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\nimport java.util.Map;\n\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.sqs.xml.AttributesHandler;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\n\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"GetQueueAttributesResponseTest\")\npublic class GetQueueAttributesResponseTest extends BaseHandlerTest {\n\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/attributes.xml\");\n\n      Map<String, String> expected = expected();\n\n      AttributesHandler handler = injector.getInstance(AttributesHandler.class);\n      Map<String, String> result = factory.create(handler).parse(is);\n\n      assertEquals(result.toString(), expected.toString());\n\n   }\n\n   public Map<String, String> expected() {\n      return ImmutableMap.<String, String>builder()\n            .put(\"QueueArn\", \"arn:aws:sqs:us-east-1:993194456877:adrian-sqs1\")\n            .put(\"ApproximateNumberOfMessages\", \"0\")\n            .put(\"ApproximateNumberOfMessagesNotVisible\", \"0\")\n            .put(\"ApproximateNumberOfMessagesDelayed\", \"0\")\n            .put(\"CreatedTimestamp\", \"1347566436\")\n            .put(\"LastModifiedTimestamp\", \"1347566436\")\n            .put(\"VisibilityTimeout\", \"30\")\n            .put(\"MaximumMessageSize\", \"65536\")\n            .put(\"MessageRetentionPeriod\", \"345600\")\n            .put(\"DelaySeconds\", \"0\")\n            .build();\n   }\n}\n"
  },
  {
    "path": "apis/sqs/src/test/java/org/jclouds/sqs/parse/ReceiveMessageResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.parse;\n\nimport static com.google.common.io.BaseEncoding.base16;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.sqs.domain.Message;\nimport org.jclouds.sqs.xml.ReceiveMessageResponseHandler;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.hash.HashCode;\n\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"ReceiveMessageResponseTest\")\npublic class ReceiveMessageResponseTest extends BaseHandlerTest {\n\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/messages.xml\");\n\n      FluentIterable<Message> expected = expected();\n\n      ReceiveMessageResponseHandler handler = injector.getInstance(ReceiveMessageResponseHandler.class);\n      FluentIterable<Message> result = factory.create(handler).parse(is);\n\n      assertEquals(result.toString(), expected.toString());\n\n   }\n\n   public FluentIterable<Message> expected() {\n      return FluentIterable.from(ImmutableList.of(Message\n            .builder()\n            .id(\"5fea7756-0ea4-451a-a703-a558b933e274\")\n            .receiptHandle(\n                  \"+eXJYhj5rDr9cAe/9BuheT5fysi9BoqtEZSkO7IazVbNHg60eCCINxLqaSVv2pFHrWeWNpZwbleSkWRbCtZaQGgpOx/3cWJZiNSG1KKlJX4IOwISFvb3FwByMx4w0lnINeXzcw2VcKQXNrCatO9gdIiVPvJC3SCKatYM/7YTidtjqc8igrtYW2E2mHlCy3NXPCeXxP4tSvyEwIxpDAmMT7IF0mWvTHS6+JBUtFUsrmi61oIHlESNrD1OjdB1QQw+kdvJ6VbsntbJNNYKw+YqdqWNpZkiGQ8y1z9OdHsr1+4=\")\n            .md5(HashCode.fromBytes(base16().lowerCase().decode(\"fafb00f5732ab283681e124bf8747ed1\")))\n            .body(\"This is a test message\")\n            .addAttribute(\"SenderId\", \"195004372649\")\n            .addAttribute(\"SentTimestamp\", \"1238099229000\")\n            .addAttribute(\"ApproximateReceiveCount\", \"5\")\n            .addAttribute(\"ApproximateFirstReceiveTimestamp\", \"1250700979248\").build()));\n   }\n}\n"
  },
  {
    "path": "apis/sqs/src/test/java/org/jclouds/sqs/parse/SendMessageBatchResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.parse;\n\nimport static com.google.common.io.BaseEncoding.base16;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.sqs.domain.BatchResult;\nimport org.jclouds.sqs.domain.MessageIdAndMD5;\nimport org.jclouds.sqs.xml.SendMessageBatchResponseHandler;\nimport org.testng.annotations.Test;\n\nimport com.google.common.hash.HashCode;\n\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"SendMessageBatchResponseTest\")\npublic class SendMessageBatchResponseTest extends BaseHandlerTest {\n\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/send_message_batch.xml\");\n\n      BatchResult<MessageIdAndMD5> expected = expected();\n\n      SendMessageBatchResponseHandler handler = injector.getInstance(SendMessageBatchResponseHandler.class);\n      BatchResult<MessageIdAndMD5> result = factory.create(handler).parse(is);\n\n      assertEquals(result.toString(), expected.toString());\n\n   }\n\n   public BatchResult<MessageIdAndMD5> expected() {\n      return BatchResult\n            .<MessageIdAndMD5> builder()\n            .put(\"test_msg_001\",\n                  MessageIdAndMD5.builder().id(\"0a5231c7-8bff-4955-be2e-8dc7c50a25fa\")\n                        .md5(HashCode.fromBytes(base16().lowerCase().decode(\"0e024d309850c78cba5eabbeff7cae71\"))).build())\n            .put(\"test_msg_002\",\n                  MessageIdAndMD5.builder().id(\"15ee1ed3-87e7-40c1-bdaa-2e49968ea7e9\")\n                        .md5(HashCode.fromBytes(base16().lowerCase().decode(\"7fb8146a82f95e0af155278f406862c2\"))).build())\n            .build();\n   }\n}\n"
  },
  {
    "path": "apis/sqs/src/test/java/org/jclouds/sqs/parse/SendMessageResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sqs.parse;\n\nimport static com.google.common.io.BaseEncoding.base16;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ReturnStringIf2xx;\nimport org.jclouds.sqs.domain.MessageIdAndMD5;\nimport org.jclouds.sqs.xml.RegexMessageIdAndMD5Handler;\nimport org.testng.annotations.Test;\n\nimport com.google.common.hash.HashCode;\n\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"SendMessageResponseTest\")\npublic class SendMessageResponseTest {\n\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/send_message.xml\");\n\n      MessageIdAndMD5 expected = expected();\n\n      RegexMessageIdAndMD5Handler handler = new RegexMessageIdAndMD5Handler(new ReturnStringIf2xx());\n      MessageIdAndMD5 result = handler.apply(HttpResponse.builder().statusCode(200).payload(is).build());\n\n      assertEquals(result.toString(), expected.toString());\n\n   }\n\n   public MessageIdAndMD5 expected() {\n      return MessageIdAndMD5.builder().id(\"c332b2b0-b61f-42d3-8832-d03ebd89f68d\")\n            .md5(HashCode.fromBytes(base16().lowerCase().decode(\"e32aedf2b2b25355d04b1507055532e6\"))).build();\n   }\n}\n"
  },
  {
    "path": "apis/sqs/src/test/resources/attributes.xml",
    "content": "<?xml version=\"1.0\"?>\n<GetQueueAttributesResponse xmlns=\"http://queue.amazonaws.com/doc/2011-10-01/\">\n\t<GetQueueAttributesResult>\n\t\t<Attribute>\n\t\t\t<Name>QueueArn</Name>\n\t\t\t<Value>arn:aws:sqs:us-east-1:993194456877:adrian-sqs1</Value>\n\t\t</Attribute>\n\t\t<Attribute>\n\t\t\t<Name>ApproximateNumberOfMessages</Name>\n\t\t\t<Value>0</Value>\n\t\t</Attribute>\n\t\t<Attribute>\n\t\t\t<Name>ApproximateNumberOfMessagesNotVisible</Name>\n\t\t\t<Value>0</Value>\n\t\t</Attribute>\n\t\t<Attribute>\n\t\t\t<Name>ApproximateNumberOfMessagesDelayed</Name>\n\t\t\t<Value>0</Value>\n\t\t</Attribute>\n\t\t<Attribute>\n\t\t\t<Name>CreatedTimestamp</Name>\n\t\t\t<Value>1347566436</Value>\n\t\t</Attribute>\n\t\t<Attribute>\n\t\t\t<Name>LastModifiedTimestamp</Name>\n\t\t\t<Value>1347566436</Value>\n\t\t</Attribute>\n\t\t<Attribute>\n\t\t\t<Name>VisibilityTimeout</Name>\n\t\t\t<Value>30</Value>\n\t\t</Attribute>\n\t\t<Attribute>\n\t\t\t<Name>MaximumMessageSize</Name>\n\t\t\t<Value>65536</Value>\n\t\t</Attribute>\n\t\t<Attribute>\n\t\t\t<Name>MessageRetentionPeriod</Name>\n\t\t\t<Value>345600</Value>\n\t\t</Attribute>\n\t\t<Attribute>\n\t\t\t<Name>DelaySeconds</Name>\n\t\t\t<Value>0</Value>\n\t\t</Attribute>\n\t</GetQueueAttributesResult>\n\t<ResponseMetadata>\n\t\t<RequestId>35566a87-caa1-5841-b60b-224bf7068bf5</RequestId>\n\t</ResponseMetadata>\n</GetQueueAttributesResponse>"
  },
  {
    "path": "apis/sqs/src/test/resources/change_message_visibility_batch.xml",
    "content": "<ChangeMessageVisibilityBatchResponse>\n    <ChangeMessageVisibilityBatchResult>\n        <ChangeMessageVisibilityBatchResultEntry>\n            <Id>change_visibility_msg_2</Id>\n        </ChangeMessageVisibilityBatchResultEntry>\n        <ChangeMessageVisibilityBatchResultEntry>\n            <Id>change_visibility_msg_3</Id>\n        </ChangeMessageVisibilityBatchResultEntry>\n    </ChangeMessageVisibilityBatchResult>\n    <ResponseMetadata>\n        <RequestId>ca9668f7-ab1b-4f7a-8859-f15747ab17a7</RequestId>\n    </ResponseMetadata>\n</ChangeMessageVisibilityBatchResponse>"
  },
  {
    "path": "apis/sqs/src/test/resources/create_queue.xml",
    "content": "<?xml version=\"1.0\"?>\n<CreateQueueResponse xmlns=\"http://queue.amazonaws.com/doc/2011-10-01/\">\n\t<CreateQueueResult>\n\t\t<QueueUrl>https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11</QueueUrl>\n\t</CreateQueueResult>\n\t<ResponseMetadata>\n\t\t<RequestId>86f9002d-531a-5868-a452-48e4293ae0a4</RequestId>\n\t</ResponseMetadata>\n</CreateQueueResponse>"
  },
  {
    "path": "apis/sqs/src/test/resources/delete_message_batch.xml",
    "content": "<DeleteMessageBatchResponse>\n    <DeleteMessageBatchResult>\n        <DeleteMessageBatchResultEntry>\n            <Id>msg1</Id>\n        </DeleteMessageBatchResultEntry>\n        <DeleteMessageBatchResultEntry>\n            <Id>msg2</Id>\n        </DeleteMessageBatchResultEntry>\n    </DeleteMessageBatchResult>\n    <ResponseMetadata>\n        <RequestId>d6f86b7a-74d1-4439-b43f-196a1e29cd85</RequestId>\n    </ResponseMetadata>\n</DeleteMessageBatchResponse>"
  },
  {
    "path": "apis/sqs/src/test/resources/get_queue_url.xml",
    "content": "<GetQueueUrlResponse>\n    <GetQueueUrlResult>\n        <QueueUrl>http://sqs.us-east-1.amazonaws.com/123456789012/testQueue</QueueUrl>\n    </GetQueueUrlResult>\n    <ResponseMetadata>\n        <RequestId>470a6f13-2ed9-4181-ad8a-2fdea142988e</RequestId>\n    </ResponseMetadata>\n</GetQueueUrlResponse>"
  },
  {
    "path": "apis/sqs/src/test/resources/list_queues.xml",
    "content": "<?xml version=\"1.0\"?>\n<ListQueuesResponse xmlns=\"http://queue.amazonaws.com/doc/2011-10-01/\"><ListQueuesResult><QueueUrl>https://eu-west-1.queue.amazonaws.com/993194456877/adriancole-sqs1</QueueUrl><QueueUrl>https://eu-west-1.queue.amazonaws.com/993194456877/adriancole-sqs111</QueueUrl></ListQueuesResult><ResponseMetadata><RequestId>313c81c8-e345-4c75-ad57-ce4d9d5ff35a</RequestId></ResponseMetadata></ListQueuesResponse>"
  },
  {
    "path": "apis/sqs/src/test/resources/log4j.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE log4j:configuration SYSTEM \"log4j.dtd\">\n\n    <!--\n        For more configuration infromation and examples see the Apache\n        Log4j website: http://logging.apache.org/log4j/\n    -->\n<log4j:configuration xmlns:log4j=\"http://jakarta.apache.org/log4j/\"\n    debug=\"false\">\n\n    <!-- A time/date based rolling appender -->\n    <appender name=\"WIREFILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds-wire.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n\n    <!-- A time/date based rolling appender -->\n    <appender name=\"FILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n    <!-- A time/date based rolling appender -->\n\n    <!-- A time/date based rolling appender -->\n    <appender name=\"COMPUTEFILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds-compute.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n\n    <!-- A time/date based rolling appender -->\n    <appender name=\"SSHFILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds-ssh.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n\n    <appender name=\"ASYNCCOMPUTE\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"COMPUTEFILE\" />\n    </appender>\n\n    <appender name=\"ASYNCSSH\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"SSHFILE\" />\n    </appender>\n\n    <appender name=\"ASYNC\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"FILE\" />\n    </appender>\n\n    <appender name=\"ASYNCWIRE\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"WIREFILE\" />\n    </appender>\n    <!-- ================ -->\n    <!-- Limit categories -->\n    <!-- ================ -->\n\n    <category name=\"org.jclouds\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNC\" />\n    </category>\n\n    <category name=\"jclouds.headers\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNCWIRE\" />\n    </category>\n\n    <category name=\"jclouds.ssh\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNCSSH\" />\n    </category>\n    <category name=\"jclouds.wire\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNCWIRE\" />\n    </category>\n    <category name=\"jclouds.compute\">\n        <priority value=\"TRACE\" />\n        <appender-ref ref=\"ASYNCCOMPUTE\" />\n    </category>\n    <!-- ======================= -->\n    <!-- Setup the Root category -->\n    <!-- ======================= -->\n\n    <root>\n        <priority value=\"WARN\" />\n    </root>\n\n</log4j:configuration>\n"
  },
  {
    "path": "apis/sqs/src/test/resources/messages.xml",
    "content": "<ReceiveMessageResponse>\n  <ReceiveMessageResult>\n    <Message>\n      <MessageId>\n        5fea7756-0ea4-451a-a703-a558b933e274\n      </MessageId>\n      <ReceiptHandle>+eXJYhj5rDr9cAe/9BuheT5fysi9BoqtEZSkO7IazVbNHg60eCCINxLqaSVv2pFHrWeWNpZwbleSkWRbCtZaQGgpOx/3cWJZiNSG1KKlJX4IOwISFvb3FwByMx4w0lnINeXzcw2VcKQXNrCatO9gdIiVPvJC3SCKatYM/7YTidtjqc8igrtYW2E2mHlCy3NXPCeXxP4tSvyEwIxpDAmMT7IF0mWvTHS6+JBUtFUsrmi61oIHlESNrD1OjdB1QQw+kdvJ6VbsntbJNNYKw+YqdqWNpZkiGQ8y1z9OdHsr1+4=</ReceiptHandle>\n      <MD5OfBody>\n        fafb00f5732ab283681e124bf8747ed1\n      </MD5OfBody>\n      <Body>This is a test message</Body>\n      <Attribute>\n        <Name>SenderId</Name>\n        <Value>195004372649</Value>\n      </Attribute>\n      <Attribute>\n        <Name>SentTimestamp</Name>\n        <Value>1238099229000</Value>\n      </Attribute>\n      <Attribute>\n        <Name>ApproximateReceiveCount</Name>\n        <Value>5</Value>\n      </Attribute>\n      <Attribute>\n        <Name>ApproximateFirstReceiveTimestamp</Name>\n        <Value>1250700979248</Value>\n      </Attribute>\n    </Message>\n  </ReceiveMessageResult>\n  <ResponseMetadata>\n    <RequestId>\n      b6633655-283d-45b4-aee4-4e84e0ae6afa\n    </RequestId>\n  </ResponseMetadata>\n</ReceiveMessageResponse>"
  },
  {
    "path": "apis/sqs/src/test/resources/send_message.xml",
    "content": "<?xml version=\"1.0\"?>\n<SendMessageResponse xmlns=\"http://queue.amazonaws.com/doc/2011-10-01/\">\n\t<SendMessageResult>\n\t\t<MessageId>c332b2b0-b61f-42d3-8832-d03ebd89f68d</MessageId>\n\t\t<MD5OfMessageBody>e32aedf2b2b25355d04b1507055532e6</MD5OfMessageBody>\n\t</SendMessageResult>\n\t<ResponseMetadata>\n\t\t<RequestId>c6c18089-18ad-52f8-9d06-c840628cb2ea</RequestId>\n\t</ResponseMetadata>\n</SendMessageResponse>"
  },
  {
    "path": "apis/sqs/src/test/resources/send_message_batch.xml",
    "content": "<SendMessageBatchResponse>\n\t<SendMessageBatchResult>\n\t\t<SendMessageBatchResultEntry>\n\t\t\t<Id>test_msg_001</Id>\n\t\t\t<MessageId>0a5231c7-8bff-4955-be2e-8dc7c50a25fa</MessageId>\n\t\t\t<MD5OfMessageBody>0e024d309850c78cba5eabbeff7cae71</MD5OfMessageBody>\n\t\t</SendMessageBatchResultEntry>\n\t\t<SendMessageBatchResultEntry>\n\t\t\t<Id>test_msg_002</Id>\n\t\t\t<MessageId>15ee1ed3-87e7-40c1-bdaa-2e49968ea7e9</MessageId>\n\t\t\t<MD5OfMessageBody>7fb8146a82f95e0af155278f406862c2</MD5OfMessageBody>\n\t\t</SendMessageBatchResultEntry>\n\t</SendMessageBatchResult>\n\t<ResponseMetadata>\n\t\t<RequestId>ca1ad5d0-8271-408b-8d0f-1351bf547e74</RequestId>\n\t</ResponseMetadata>\n</SendMessageBatchResponse>"
  },
  {
    "path": "apis/sts/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.aws.*;version=\"${project.version}\";-noimport:=true, \\\n    org.jclouds.sts.*;version=\"${project.version}\";-noimport:=true"
  },
  {
    "path": "apis/sts/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.api</groupId>\n  <artifactId>sts</artifactId>\n  <name>jclouds sts api</name>\n  <description>jclouds components to access an implementation of Security Token Service (STS)</description>\n\n  <properties>\n    <test.sts.endpoint>https://sts.amazonaws.com</test.sts.endpoint>\n    <test.sts.api-version>2011-06-15</test.sts.api-version>\n    <test.sts.build-version />\n    <test.sts.identity>${test.aws.identity}</test.sts.identity>\n    <test.sts.credential>${test.aws.credential}</test.sts.credential>\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>jar</type>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-log4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.logging.log4j</groupId>\n      <artifactId>log4j-core</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.sts.endpoint>${test.sts.endpoint}</test.sts.endpoint>\n                    <test.sts.api-version>${test.sts.api-version}</test.sts.api-version>\n                    <test.sts.build-version>${test.sts.build-version}</test.sts.build-version>\n                    <test.sts.identity>${test.sts.identity}</test.sts.identity>\n                    <test.sts.credential>${test.sts.credential}</test.sts.credential>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n\n"
  },
  {
    "path": "apis/sts/src/main/java/org/jclouds/aws/AWSResponseException.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws;\n\nimport org.jclouds.aws.domain.AWSError;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.javax.annotation.Nullable;\n\n/**\n * Encapsulates an AWS Error from Amazon.\n * \n * @see <a href=\"http://docs.amazonwebservices.com/AmazonS3/2006-03-01/UsingRESTError.html\" />\n * @see AWSError\n * @see org.jclouds.aws.handlers.ParseAWSErrorFromXmlContent\n */\npublic class AWSResponseException extends HttpResponseException {\n\n   private transient AWSError error = new AWSError();\n\n   public AWSResponseException(HttpCommand command, HttpResponse response, AWSError error) {\n      super(String.format(\"request %s failed with code %s, error: %s\", command.getCurrentRequest().getRequestLine(), response\n               .getStatusCode(), error.toString()), command, response);\n      this.setError(error);\n\n   }\n\n   public AWSResponseException(HttpCommand command, HttpResponse response, AWSError error,\n            Throwable cause) {\n      super(String.format(\"request %1$s failed with error: %2$s\", command.getCurrentRequest().getRequestLine(), error\n               .toString()), command, response, cause);\n      this.setError(error);\n\n   }\n\n   public AWSResponseException(String message, HttpCommand command, HttpResponse response,\n            AWSError error) {\n      super(message, command, response);\n      this.setError(error);\n\n   }\n\n   public AWSResponseException(String message, HttpCommand command, HttpResponse response,\n            AWSError error, Throwable cause) {\n      super(message, command, response, cause);\n      this.setError(error);\n\n   }\n\n   public void setError(AWSError error) {\n      this.error = error;\n   }\n\n   @Nullable\n   public AWSError getError() {\n      return error;\n   }\n\n}\n"
  },
  {
    "path": "apis/sts/src/main/java/org/jclouds/aws/binders/BindMapToIndexedFormParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static java.lang.String.format;\n\nimport java.util.Map;\nimport java.util.Map.Entry;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Maps;\nimport com.google.common.collect.Multimap;\nimport com.google.common.collect.Multimaps;\n\npublic class BindMapToIndexedFormParams implements Binder {\n\n   private final String keyPattern;\n   private final String valuePattern;\n\n   protected BindMapToIndexedFormParams(String keyPattern, String valuePattern) {\n      this.keyPattern = keyPattern;\n      this.valuePattern = valuePattern;\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      if (checkNotNull(input, \"input\") instanceof Iterable)\n         input = Maps.uniqueIndex((Iterable<String>) input, new Function<String, String>() {\n            int index = 1;\n\n            @Override\n            public String apply(String input) {\n               return index++ + \"\";\n            }\n         });\n      checkArgument(checkNotNull(input, \"input\") instanceof Map, \"this binder is only valid for Map\");\n      Map<String, String> mapping = (Map<String, String>) input;\n\n      ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();\n      int amazonOneBasedIndex = 1; // according to docs, counters must start\n                                   // with 1\n      for (Entry<String, String> entry : mapping.entrySet()) {\n         // not null by contract\n         builder.put(format(keyPattern, amazonOneBasedIndex), entry.getKey());\n         builder.put(format(valuePattern, amazonOneBasedIndex), entry.getValue());\n         amazonOneBasedIndex++;\n      }\n      Multimap<String, String> forms = Multimaps.forMap(builder.build());\n      return forms.isEmpty() ? request : (R) request.toBuilder().replaceFormParams(forms).build();\n   }\n\n}\n"
  },
  {
    "path": "apis/sts/src/main/java/org/jclouds/aws/binders/BindTableToIndexedFormParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static java.lang.String.format;\n\nimport java.util.Map;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableTable;\nimport com.google.common.collect.ImmutableTable.Builder;\nimport com.google.common.collect.Multimap;\nimport com.google.common.collect.Multimaps;\nimport com.google.common.collect.Table;\nimport com.google.common.collect.Table.Cell;\n\npublic class BindTableToIndexedFormParams implements Binder {\n\n   private final String rowPattern;\n   private final String columnPattern;\n   private final String valuePattern;\n\n   protected BindTableToIndexedFormParams(String rowPattern, String columnPattern, String valuePattern) {\n      this.rowPattern = rowPattern;\n      this.columnPattern = columnPattern;\n      this.valuePattern = valuePattern;\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      if (checkNotNull(input, \"input\") instanceof Map) {\n         Builder<Object, Object, Object> builder = ImmutableTable.builder();\n         int index = 1;\n         for (Map.Entry<?, ?> entry : ((Map<?, ?>) input).entrySet())\n            builder.put(index++, entry.getKey(), entry.getValue());\n         input = builder.build();\n      }\n      checkArgument(checkNotNull(input, \"input\") instanceof Table, \"this binder is only valid for Table\");\n      Table<?, ?, ?> table = Table.class.cast(input);\n\n      ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();\n      int amazonOneBasedIndex = 1; // according to docs, counters must start\n                                   // with 1\n      for (Cell<?, ?, ?> cell : table.cellSet()) {\n         // not null by contract\n         builder.put(format(rowPattern, amazonOneBasedIndex), cell.getRowKey().toString());\n         builder.put(format(columnPattern, amazonOneBasedIndex), cell.getColumnKey().toString());\n         builder.put(format(valuePattern, amazonOneBasedIndex), cell.getValue().toString());\n\n         amazonOneBasedIndex++;\n      }\n      Multimap<String, String> forms = Multimaps.forMap(builder.build());\n      return forms.isEmpty() ? request : (R) request.toBuilder().replaceFormParams(forms).build();\n   }\n\n}\n"
  },
  {
    "path": "apis/sts/src/main/java/org/jclouds/aws/config/AWSHttpApiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.config;\n\n\nimport java.util.Set;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.handlers.AWSClientErrorRetryHandler;\nimport org.jclouds.aws.handlers.AWSServerErrorRetryHandler;\nimport org.jclouds.aws.handlers.ParseAWSErrorFromXmlContent;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpRetryHandler;\nimport org.jclouds.http.annotation.ClientError;\nimport org.jclouds.http.annotation.Redirection;\nimport org.jclouds.http.annotation.ServerError;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.config.HttpApiModule;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Provides;\n\n\n@ConfiguresHttpApi\npublic abstract class AWSHttpApiModule<A> extends HttpApiModule<A> {\n   protected AWSHttpApiModule() {\n\n   }\n\n   protected AWSHttpApiModule(Class<A> api) {\n      super(api);\n   }\n\n   @Provides\n   @ClientError\n   @Singleton\n   protected final Set<String> provideRetryableCodes() {\n      return ImmutableSet.of(\"RequestTimeout\", \"OperationAborted\", \"SignatureDoesNotMatch\");\n   }\n   \n   @Provides\n   @ServerError\n   @Singleton\n   protected final Set<String> provideRetryableServerCodes() {\n      return ImmutableSet.of(\"RequestLimitExceeded\", \"InternalError\");\n   }\n\n   @Override\n   protected void bindErrorHandlers() {\n      bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(ParseAWSErrorFromXmlContent.class);\n      bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(ParseAWSErrorFromXmlContent.class);\n      bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(ParseAWSErrorFromXmlContent.class);\n   }\n\n   @Override\n   protected void bindRetryHandlers() {\n      bind(HttpRetryHandler.class).annotatedWith(ClientError.class).to(AWSClientErrorRetryHandler.class);\n      bind(HttpRetryHandler.class).annotatedWith(ServerError.class).to(AWSServerErrorRetryHandler.class);\n   }\n\n}\n"
  },
  {
    "path": "apis/sts/src/main/java/org/jclouds/aws/config/FormSigningHttpApiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.config;\n\nimport java.util.Date;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.filters.FormSigner;\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.RequestSigner;\n\nimport com.google.inject.Provides;\n\n/**\n * Configures signature process and dependencies needed for AWS Query apis\n * (which we sent as POST requests, hence the name Form).\n */\n@ConfiguresHttpApi\npublic abstract class FormSigningHttpApiModule<A> extends AWSHttpApiModule<A> {\n   protected FormSigningHttpApiModule() {\n\n   }\n\n   protected FormSigningHttpApiModule(Class<A> api) {\n      super(api);\n   }\n\n   @Provides\n   @TimeStamp\n   protected final String guiceProvideTimeStamp(DateService dateService) {\n      return provideTimeStamp(dateService);\n   }\n\n   protected String provideTimeStamp(DateService dateService) {\n      return dateService.iso8601DateFormat(new Date(System.currentTimeMillis()));\n   }\n\n   @Provides\n   @Singleton\n   final RequestSigner provideRequestSigner(FormSigner in) {\n      if (in instanceof RequestSigner) {\n         return (RequestSigner) in;\n      }\n      return new RequestSigner() {\n         @Override public String createStringToSign(HttpRequest input) {\n            return null;\n         }\n\n         @Override public String sign(String toSign) {\n            return null;\n         }\n      };\n   }\n\n}\n"
  },
  {
    "path": "apis/sts/src/main/java/org/jclouds/aws/domain/AWSError.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.domain;\n\nimport java.util.Map;\n\nimport com.google.common.collect.Maps;\n\n/**\n * When an Amazon S3 request is in error, the client receives an error response.\n * \n * @see <a\n *      href=\"http://docs.amazonwebservices.com/AmazonS3/2006-03-01/index.html?ErrorResponse.html\"\n *      />\n */\npublic class AWSError {\n   private String code;\n   private String message;\n   private String requestId;\n   private String requestToken;\n   private Map<String, String> details = Maps.newHashMap();\n   private String stringSigned;\n   private String signature;\n\n   @Override\n   public String toString() {\n      final StringBuilder sb = new StringBuilder();\n      sb.append(\"AWSError\");\n      sb.append(\"{requestId='\").append(requestId).append('\\'');\n      sb.append(\", requestToken='\").append(requestToken).append('\\'');\n      if (code != null)\n         sb.append(\", code='\").append(code).append('\\'');\n      if (message != null)\n         sb.append(\", message='\").append(message).append('\\'');\n      if (stringSigned != null)\n         sb.append(\", stringSigned='\").append(stringSigned).append('\\'');\n      if (getSignature() != null)\n         sb.append(\", signature='\").append(getSignature()).append('\\'');\n      if (details.size() != 0)\n         sb.append(\", context='\").append(details.toString()).append('\\'');\n      sb.append('}');\n      return sb.toString();\n   }\n\n   public void setCode(String code) {\n      this.code = code;\n   }\n\n   /**\n    * The error code is a string that uniquely identifies an error condition. It is meant to be read\n    * and understood by programs that detect and handle errors by type\n    * \n    * @see <a href=\"http://docs.amazonwebservices.com/AmazonS3/2006-03-01/ErrorCode.html\" />\n    */\n   public String getCode() {\n      return code;\n   }\n\n   public void setMessage(String message) {\n      this.message = message;\n   }\n\n   /**\n    * The error message contains a generic description of the error condition in English.\n    * \n    * @see <a href=\"http://docs.amazonwebservices.com/AmazonS3/2006-03-01/ErrorMessage.html\" />\n    */\n   public String getMessage() {\n      return message;\n   }\n\n   public void setRequestId(String requestId) {\n      this.requestId = requestId;\n   }\n\n   /**\n    * * A unique ID assigned to each request by the system. In the unlikely event that you have\n    * problems with Amazon S3, Amazon can use this to help troubleshoot the problem.\n    * \n    */\n   public String getRequestId() {\n      return requestId;\n   }\n\n   public void setStringSigned(String stringSigned) {\n      this.stringSigned = stringSigned;\n   }\n\n   /**\n    * @return what jclouds signed before sending the request.\n    */\n   public String getStringSigned() {\n      return stringSigned;\n   }\n\n   public void setDetails(Map<String, String> context) {\n      this.details = context;\n   }\n\n   /**\n    * @return additional details surrounding the error.\n    */\n   public Map<String, String> getDetails() {\n      return details;\n   }\n\n   public void setRequestToken(String requestToken) {\n      this.requestToken = requestToken;\n   }\n\n   public String getRequestToken() {\n      return requestToken;\n   }\n\n   public void setSignature(String signature) {\n      this.signature = signature;\n   }\n\n   public String getSignature() {\n      return signature;\n   }\n}\n"
  },
  {
    "path": "apis/sts/src/main/java/org/jclouds/aws/domain/Region.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.domain;\n\nimport static org.jclouds.Constants.PROPERTY_ISO3166_CODES;\nimport static org.jclouds.location.reference.LocationConstants.ISO3166_CODES;\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_REGION;\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_REGIONS;\n\nimport java.util.Properties;\nimport java.util.Set;\n\nimport com.google.common.base.Joiner;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * \n * Regions used for all aws commands.\n * \n * @see <a\n *      href=\"http://docs.amazonwebservices.com/AmazonS3/latest/dev/index.html?LocationSelection.html\"\n *      />\n * @see <a\n *      href=\"https://docs.aws.amazon.com/general/latest/gr/rande.html\n *      />\n *\n */\npublic class Region {\n   /**\n    * EU (Ireland)\n    * <p/>\n    * <h3>S3</h3>\n    * <p/>\n    * In Amazon S3, the EU (Ireland) Region provides read-after-write consistency for PUTS of new\n    * objects in your Amazon S3 bucket and eventual consistency for overwrite PUTS and DELETES.\n    */\n   public static final String EU_WEST_1 = \"eu-west-1\";\n\n   /**\n    * EU (London)\n    */\n   public static final String EU_WEST_2 = \"eu-west-2\";\n   \n   /**\n    * EU (Paris)\n    */\n   public static final String EU_WEST_3 = \"eu-west-3\";\n\n   /**\n    * EU (Milan)\n    */\n   public static final String EU_SOUTH_1 = \"eu-south-1\";\n\n   /**\n    * EU (Spain)\n    */\n   public static final String EU_SOUTH_2 = \"eu-south-2\";\n\n   /**\n    * EU (Frankfurt)\n    */\n   public static final String EU_CENTRAL_1 = \"eu-central-1\";\n\n   /**\n    * EU (Zurich)\n    */\n   public static final String EU_CENTRAL_2 = \"eu-central-2\";\n\n   /**\n    * EU (Stockholm)\n    */\n   public static final String EU_NORTH_1 = \"eu-north-1\";\n\n   /**\n    * \n    * US Standard\n    * <p/>\n    * <h3>S3</h3>\n    * <p/>\n    * This is the default Region. All requests sent to s3.amazonaws.com go to this Region unless you\n    * specify a LocationConstraint on a bucket. The US Standard Region automatically places your\n    * data in either Amazon's east or west coast data centers depending on what will provide you\n    * with the lowest latency. To use this region, do not set the LocationConstraint bucket\n    * parameter. The US Standard Region provides eventual consistency for all requests.\n    */\n   public static final String US_STANDARD = \"us-standard\";\n\n   /**\n    * US-East-1 (N. Virginia)\n    */\n   public static final String US_EAST_1 = \"us-east-1\";\n\n   /**\n    * US-East-2 (Ohio)\n    */\n   public static final String US_EAST_2 = \"us-east-2\";\n\n   /**\n    * US-West (Northern California) <h3>S3</h3> Uses Amazon S3 servers in Northern California\n    * <p/>\n    * Optionally, use the endpoint s3-us-west-1.amazonaws.com on all requests to this bucket to\n    * reduce the latency you might experience after the first hour of creating a bucket in this\n    * Region.\n    * <p/>\n    * In Amazon S3, the US-West (Northern California) Region provides read-after-write consistency\n    * for PUTS of new objects in your Amazon S3 bucket and eventual consistency for overwrite PUTS\n    * and DELETES.\n    */\n   public static final String US_WEST_1 = \"us-west-1\";\n\n   /**\n    * US-West-2 (Oregon)\n    */\n   public static final String US_WEST_2 = \"us-west-2\";\n\n   /**\n    * CA-CENTRAL-1 (Canada)\n    */\n   public static final String CA_CENTRAL_1 = \"ca-central-1\";\n\n   /**\n    * SA-EAST-1 (Sao Paolo)\n    * \n    */\n   public static final String SA_EAST_1 = \"sa-east-1\";\n   \n   /**\n    * Asia Pacific (Sydney)\n    */\n   public static final String AP_SOUTHEAST_2 = \"ap-southeast-2\";\n   \n   /**\n    * Region in Singapore, launched April 28, 2010. This region improves latency for Asia-based\n    * users\n    */\n   public static final String AP_SOUTHEAST_1 = \"ap-southeast-1\";\n   \n   /**\n    * Region in Mumbai (India), launched June 27, 2016. This region improves latency for Asia-based\n    * users\n    */\n   public static final String AP_SOUTH_1 = \"ap-south-1\";\n\n   /**\n    * Region in Tokyo, launched March 2, 2011. This region improves latency for Asia-based users\n    */\n   public static final String AP_NORTHEAST_1 = \"ap-northeast-1\";\n\n   /**\n    * Region in Seoul, launched January 6, 2016. This region improves latency for Asia-based users\n    */\n   public static final String AP_NORTHEAST_2 = \"ap-northeast-2\";\n\n   /**\n    * Region in Beijing, launched early 2014. This region improves latency for China users\n    */\n    public static final String CN_NORTH_1 = \"cn-north-1\";\n\n   /**\n    * Region in Ningxia, launched  Dec 12, 2017. This region improves latency for China users\n    */\n   public static final String CN_NORTHWEST_1 = \"cn-northwest-1\";\n   \n   /**\n    * ME (Bahrain)\n    */\n   public static final String ME_SOUTH_1 = \"me-south-1\";\n   \n\n   public static final Set<String> DEFAULT_S3 = ImmutableSet.of(US_STANDARD, US_EAST_2, US_WEST_1, US_WEST_2,\n         CA_CENTRAL_1, SA_EAST_1,\n         EU_SOUTH_1, EU_SOUTH_2, EU_WEST_1, EU_WEST_2, EU_WEST_3, EU_CENTRAL_1, EU_CENTRAL_2, EU_NORTH_1,\n         AP_SOUTHEAST_1, AP_SOUTHEAST_2, AP_SOUTH_1, AP_NORTHEAST_1, AP_NORTHEAST_2,\n         CN_NORTH_1, CN_NORTHWEST_1, ME_SOUTH_1);\n\n   public static final Set<String> DEFAULT_REGIONS = ImmutableSet.of(US_EAST_1, US_EAST_2, US_WEST_1, US_WEST_2,\n         CA_CENTRAL_1, SA_EAST_1,\n         EU_SOUTH_1, EU_SOUTH_2, EU_WEST_1, EU_WEST_2, EU_WEST_3, EU_CENTRAL_1, EU_CENTRAL_2, EU_NORTH_1,\n         AP_SOUTHEAST_1, AP_SOUTHEAST_2, AP_SOUTH_1, AP_NORTHEAST_1, AP_NORTHEAST_2,\n         CN_NORTH_1, CN_NORTHWEST_1, ME_SOUTH_1);\n\n   public static Properties regionPropertiesS3() {\n\n      Properties properties = regionProperties();\n      properties.setProperty(PROPERTY_REGIONS, Joiner.on(',').join(DEFAULT_S3));\n      // note that due to US_STANDARD the codes include US instead of US-VA\n      properties.setProperty(PROPERTY_ISO3166_CODES, \"US,US-OH,US-CA,US-OR,CA,BR-SP,\"\n            + \"IE,GB-LND,FR-IDF,IT-MI,ES,DE-HE,CH-ZH,SE-AB,\"\n            + \"SG,AU-NSW,IN-MH,JP-13,KR-11,CN-BJ,CN-NX,BH\");\n      properties.setProperty(PROPERTY_REGION + \".\" + US_STANDARD + \".\" + ISO3166_CODES, \"US\");\n      return properties;\n   }\n\n   public static Properties regionProperties() {\n      Properties properties = new Properties();\n      properties.setProperty(PROPERTY_REGIONS, Joiner.on(',').join(DEFAULT_REGIONS));\n      properties.setProperty(PROPERTY_ISO3166_CODES, \"US-VA,US-OH,US-CA,US-OR,CA,BR-SP,\"\n            + \"IE,GB-LND,FR-IDF,IT-MI,ES,DE-HE,CH-ZH,SE-AB\"\n            + \"SG,AU-NSW,IN-MH,JP-13,KR-11,\"\n            + \"CN-BJ,CN-NX,BH\");\n      properties.setProperty(PROPERTY_REGION + \".\" + US_EAST_1 + \".\" + ISO3166_CODES, \"US-VA\");\n      properties.setProperty(PROPERTY_REGION + \".\" + US_EAST_2 + \".\" + ISO3166_CODES, \"US-OH\");\n      properties.setProperty(PROPERTY_REGION + \".\" + US_WEST_1 + \".\" + ISO3166_CODES, \"US-CA\");\n      properties.setProperty(PROPERTY_REGION + \".\" + US_WEST_2 + \".\" + ISO3166_CODES, \"US-OR\");\n      properties.setProperty(PROPERTY_REGION + \".\" + CA_CENTRAL_1 + \".\" + ISO3166_CODES, \"CA\");\n      properties.setProperty(PROPERTY_REGION + \".\" + SA_EAST_1 + \".\" + ISO3166_CODES, \"BR-SP\");\n\n      properties.setProperty(PROPERTY_REGION + \".\" + EU_WEST_1 + \".\" + ISO3166_CODES, \"IE\");\n      properties.setProperty(PROPERTY_REGION + \".\" + EU_WEST_2 + \".\" + ISO3166_CODES, \"GB-LND\");\n      properties.setProperty(PROPERTY_REGION + \".\" + EU_WEST_3 + \".\" + ISO3166_CODES, \"FR-IDF\");\n      properties.setProperty(PROPERTY_REGION + \".\" + EU_SOUTH_1 + \".\" + ISO3166_CODES, \"IT-MI\");\n      properties.setProperty(PROPERTY_REGION + \".\" + EU_SOUTH_2 + \".\" + ISO3166_CODES, \"ES\");\n      properties.setProperty(PROPERTY_REGION + \".\" + EU_CENTRAL_1 + \".\" + ISO3166_CODES, \"DE-HE\");\n      properties.setProperty(PROPERTY_REGION + \".\" + EU_CENTRAL_2 + \".\" + ISO3166_CODES, \"CH-ZH\");\n      properties.setProperty(PROPERTY_REGION + \".\" + EU_NORTH_1 + \".\" + ISO3166_CODES, \"SE-AB\");\n\n      properties.setProperty(PROPERTY_REGION + \".\" + AP_SOUTHEAST_1 + \".\" + ISO3166_CODES, \"SG\");\n      properties.setProperty(PROPERTY_REGION + \".\" + AP_SOUTHEAST_2 + \".\" + ISO3166_CODES, \"AU-NSW\");\n      properties.setProperty(PROPERTY_REGION + \".\" + AP_SOUTH_1 + \".\" + ISO3166_CODES, \"IN-MH\");\n      properties.setProperty(PROPERTY_REGION + \".\" + AP_NORTHEAST_1 + \".\" + ISO3166_CODES, \"JP-13\");\n      properties.setProperty(PROPERTY_REGION + \".\" + AP_NORTHEAST_2 + \".\" + ISO3166_CODES, \"KR-11\");\n\n      properties.setProperty(PROPERTY_REGION + \".\" + CN_NORTH_1 + \".\" + ISO3166_CODES, \"CN-BJ\");\n      properties.setProperty(PROPERTY_REGION + \".\" + CN_NORTHWEST_1 + \".\" + ISO3166_CODES, \"CN-NX\");\n      properties.setProperty(PROPERTY_REGION + \".\" + ME_SOUTH_1 + \".\" + ISO3166_CODES, \"BH\");\n      return properties;\n   }\n}\n"
  },
  {
    "path": "apis/sts/src/main/java/org/jclouds/aws/domain/SessionCredentials.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Date;\n\nimport org.jclouds.domain.Credentials;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.Optional;\n\n/**\n * AWS credentials for API authentication.\n * \n * @see <a href=\n *      \"http://docs.aws.amazon.com/STS/latest/APIReference/API_Credentials.html\"\n *      />\n */\npublic final class SessionCredentials extends Credentials {\n\n   private final String sessionToken;\n   private final Optional<Date> expiration;\n\n   private SessionCredentials(String accessKeyId, String secretAccessKey, String sessionToken, Optional<Date> expiration) {\n      super(checkNotNull(accessKeyId, \"accessKeyId\"), checkNotNull(secretAccessKey, \"secretAccessKey for %s\",\n            accessKeyId));\n      this.sessionToken = checkNotNull(sessionToken, \"sessionToken for %s\", accessKeyId);\n      this.expiration = checkNotNull(expiration, \"expiration for %s\", accessKeyId);\n   }\n\n   /**\n    * AccessKeyId ID that identifies the temporary credentials.\n    */\n   public String getAccessKeyId() {\n      return identity;\n   }\n\n   /**\n    * The Secret Access Key to sign requests.\n    */\n   public String getSecretAccessKey() {\n      return credential;\n   }\n\n   /**\n    * The security token that users must pass to the service API to use the\n    * temporary credentials.\n    */\n   public String getSessionToken() {\n      return sessionToken;\n   }\n\n   /**\n    * The date on which these credentials expire.\n    */\n   public Optional<Date> getExpiration() {\n      return expiration;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(identity, credential, sessionToken, expiration);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      SessionCredentials other = (SessionCredentials) obj;\n      return Objects.equal(this.identity, other.identity) && Objects.equal(this.credential, other.credential)\n            && Objects.equal(this.sessionToken, other.sessionToken) && Objects.equal(this.expiration, other.expiration);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"accessKeyId\", identity)\n            .add(\"sessionToken\", sessionToken).add(\"expiration\", expiration.orNull()).toString();\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().from(this);\n   }\n\n   public static final class Builder extends Credentials.Builder<SessionCredentials> {\n      private String accessKeyId;\n      private String secretAccessKey;\n      private String sessionToken;\n      private Optional<Date> expiration = Optional.absent();\n\n      @Override\n      public Builder identity(String identity) {\n         return accessKeyId(identity);\n      }\n\n      @Override\n      public Builder credential(String credential) {\n         return secretAccessKey(credential);\n      }\n\n      /**\n       * @see SessionCredentials#getAccessKeyId()\n       */\n      public Builder accessKeyId(String accessKeyId) {\n         this.accessKeyId = accessKeyId;\n         return this;\n      }\n\n      /**\n       * @see SessionCredentials#getSecretAccessKey()\n       */\n      public Builder secretAccessKey(String secretAccessKey) {\n         this.secretAccessKey = secretAccessKey;\n         return this;\n      }\n\n      /**\n       * @see SessionCredentials#getSessionToken()\n       */\n      public Builder sessionToken(String sessionToken) {\n         this.sessionToken = sessionToken;\n         return this;\n      }\n\n      /**\n       * @see SessionCredentials#getExpiration()\n       */\n      public Builder expiration(Date expiration) {\n         this.expiration = Optional.fromNullable(expiration);\n         return this;\n      }\n\n      public SessionCredentials build() {\n         return new SessionCredentials(accessKeyId, secretAccessKey, sessionToken, expiration);\n      }\n\n      public Builder from(SessionCredentials in) {\n         return this.accessKeyId(in.identity).secretAccessKey(in.credential).sessionToken(in.sessionToken)\n               .expiration(in.expiration.orNull());\n      }\n   }\n}\n"
  },
  {
    "path": "apis/sts/src/main/java/org/jclouds/aws/filters/FormSigner.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.filters;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.common.collect.Ordering.natural;\nimport static com.google.common.io.BaseEncoding.base64;\nimport static com.google.common.io.ByteStreams.readBytes;\nimport static org.jclouds.aws.filters.FormSignerUtils.getAnnotatedApiVersion;\nimport static org.jclouds.aws.reference.FormParameters.ACTION;\nimport static org.jclouds.aws.reference.FormParameters.AWS_ACCESS_KEY_ID;\nimport static org.jclouds.aws.reference.FormParameters.SECURITY_TOKEN;\nimport static org.jclouds.aws.reference.FormParameters.SIGNATURE;\nimport static org.jclouds.aws.reference.FormParameters.SIGNATURE_METHOD;\nimport static org.jclouds.aws.reference.FormParameters.SIGNATURE_VERSION;\nimport static org.jclouds.aws.reference.FormParameters.TIMESTAMP;\nimport static org.jclouds.aws.reference.FormParameters.VERSION;\nimport static org.jclouds.crypto.Macs.asByteProcessor;\nimport static org.jclouds.http.utils.Queries.encodeQueryLine;\nimport static org.jclouds.http.utils.Queries.queryParser;\nimport static org.jclouds.util.Strings2.toInputStream;\n\nimport java.util.Comparator;\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Provider;\n\nimport org.jclouds.Constants;\nimport org.jclouds.aws.domain.SessionCredentials;\nimport org.jclouds.crypto.Crypto;\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpRequestFilter;\nimport org.jclouds.http.HttpUtils;\nimport org.jclouds.http.internal.SignatureWire;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.rest.RequestSigner;\nimport org.jclouds.rest.annotations.ApiVersion;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Objects;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Multimap;\nimport com.google.common.collect.TreeMultimap;\nimport com.google.common.io.ByteProcessor;\nimport com.google.common.net.HttpHeaders;\nimport com.google.inject.ImplementedBy;\n\n@ImplementedBy(FormSigner.FormSignerV2.class)\npublic interface FormSigner extends HttpRequestFilter {\n\n   static final class FormSignerV2 implements FormSigner, RequestSigner {\n\n      public static final Set<String> mandatoryParametersForSignature = ImmutableSet\n            .of(ACTION, SIGNATURE_METHOD, SIGNATURE_VERSION, VERSION);\n\n      private final SignatureWire signatureWire;\n      private final String apiVersion;\n      private final Supplier<Credentials> creds;\n      private final Provider<String> dateService;\n      private final Crypto crypto;\n      private final HttpUtils utils;\n\n      @Resource @Named(Constants.LOGGER_SIGNATURE)\n      private Logger signatureLog = Logger.NULL;\n\n      @Inject FormSignerV2(SignatureWire signatureWire, @ApiVersion String apiVersion,\n            @org.jclouds.location.Provider Supplier<Credentials> creds, @TimeStamp Provider<String> dateService,\n            Crypto crypto, HttpUtils utils) {\n         this.signatureWire = signatureWire;\n         this.apiVersion = apiVersion;\n         this.creds = creds;\n         this.dateService = dateService;\n         this.crypto = crypto;\n         this.utils = utils;\n      }\n\n      public HttpRequest filter(HttpRequest request) throws HttpException {\n         checkNotNull(request.getFirstHeaderOrNull(HttpHeaders.HOST), \"request is not ready to sign; host not present\");\n         Multimap<String, String> decodedParams = queryParser().apply(request.getPayload().getRawContent().toString());\n         Optional<String> optAnnotatedVersion = getAnnotatedApiVersion(request);\n         String version;\n         if (optAnnotatedVersion.isPresent()) {\n            String annotatedVersion = optAnnotatedVersion.get();\n            version = annotatedVersion.compareTo(apiVersion) > 0 ? annotatedVersion : apiVersion;\n         } else {\n            version = apiVersion;\n         }\n         decodedParams.replaceValues(VERSION, ImmutableSet.of(version));\n         addSigningParams(decodedParams);\n         validateParams(decodedParams);\n         String stringToSign = createStringToSign(request, decodedParams);\n         String signature = sign(stringToSign);\n         addSignature(decodedParams, signature);\n         request = setPayload(request, decodedParams);\n         utils.logRequest(signatureLog, request, \"<<\");\n         return request;\n      }\n\n      HttpRequest setPayload(HttpRequest request, Multimap<String, String> decodedParams) {\n         String queryLine = buildQueryLine(decodedParams);\n         request.setPayload(queryLine);\n         request.getPayload().getContentMetadata().setContentType(\"application/x-www-form-urlencoded\");\n         return request;\n      }\n\n      private static final Comparator<String> actionFirstAccessKeyLast = new Comparator<String>() {\n         static final int LEFT_IS_GREATER = 1;\n         static final int RIGHT_IS_GREATER = -1;\n\n         @Override\n         public int compare(String left, String right) {\n            if (Objects.equal(left, right)) {\n               return 0;\n            }\n            if (\"Action\".equals(right) || \"AWSAccessKeyId\".equals(left)) {\n               return LEFT_IS_GREATER;\n            }\n            if (\"Action\".equals(left) || \"AWSAccessKeyId\".equals(right)) {\n               return RIGHT_IS_GREATER;\n            }\n            return natural().compare(left, right);\n         }\n      };\n\n      private static String buildQueryLine(Multimap<String, String> decodedParams) {\n         Multimap<String, String> sortedParams = TreeMultimap.create(actionFirstAccessKeyLast, natural());\n         sortedParams.putAll(decodedParams);\n         return encodeQueryLine(sortedParams);\n      }\n\n      @VisibleForTesting void validateParams(Multimap<String, String> params) {\n         for (String parameter : mandatoryParametersForSignature) {\n            checkState(params.containsKey(parameter), \"parameter \" + parameter + \" is required for signature\");\n         }\n      }\n\n      @VisibleForTesting void addSignature(Multimap<String, String> params, String signature) {\n         params.replaceValues(SIGNATURE, ImmutableList.of(signature));\n      }\n\n      @VisibleForTesting\n      public String sign(String toSign) {\n         String signature;\n         try {\n            ByteProcessor<byte[]> hmacSHA256 = asByteProcessor(\n                  crypto.hmacSHA256(creds.get().credential.getBytes(UTF_8)));\n            signature = base64().encode(readBytes(toInputStream(toSign), hmacSHA256));\n            if (signatureWire.enabled())\n               signatureWire.input(toInputStream(signature));\n         } catch (Exception e) {\n            throw new HttpException(\"error signing request\", e);\n         }\n         return signature;\n      }\n\n      @VisibleForTesting\n      public String createStringToSign(HttpRequest request, Multimap<String, String> decodedParams) {\n         utils.logRequest(signatureLog, request, \">>\");\n         StringBuilder stringToSign = new StringBuilder();\n         // StringToSign = HTTPVerb + \"\\n\" +\n         stringToSign.append(request.getMethod()).append(\"\\n\");\n         // ValueOfHostHeaderInLowercase + \"\\n\" +\n         stringToSign.append(request.getFirstHeaderOrNull(HttpHeaders.HOST).toLowerCase()).append(\"\\n\");\n         // HTTPRequestURI + \"\\n\" +\n         stringToSign.append(request.getEndpoint().getPath()).append(\"\\n\");\n         // CanonicalizedFormString <from the preceding step>\n         stringToSign.append(buildCanonicalizedString(decodedParams));\n         if (signatureWire.enabled())\n            signatureWire.output(stringToSign.toString());\n         return stringToSign.toString();\n      }\n\n      @VisibleForTesting String buildCanonicalizedString(Multimap<String, String> decodedParams) {\n         // note that aws wants to percent encode the canonicalized string without skipping '/' and '?'\n         return encodeQueryLine(TreeMultimap.create(decodedParams), ImmutableList.<Character>of());\n      }\n\n      @VisibleForTesting void addSigningParams(Multimap<String, String> params) {\n         params.removeAll(SIGNATURE);\n         params.removeAll(SECURITY_TOKEN);\n         Credentials current = creds.get();\n         if (current instanceof SessionCredentials) {\n            params.put(SECURITY_TOKEN, SessionCredentials.class.cast(current).getSessionToken());\n         }\n         params.replaceValues(SIGNATURE_METHOD, ImmutableList.of(\"HmacSHA256\"));\n         params.replaceValues(SIGNATURE_VERSION, ImmutableList.of(\"2\"));\n         params.replaceValues(TIMESTAMP, ImmutableList.of(dateService.get()));\n         params.replaceValues(AWS_ACCESS_KEY_ID, ImmutableList.of(creds.get().identity));\n      }\n\n      public String createStringToSign(HttpRequest input) {\n         return createStringToSign(input, queryParser().apply(input.getPayload().getRawContent().toString()));\n      }\n   }\n}\n"
  },
  {
    "path": "apis/sts/src/main/java/org/jclouds/aws/filters/FormSignerUtils.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.filters;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.reflect.Invocation;\nimport org.jclouds.rest.annotations.ApiVersionOverride;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\n\nimport com.google.common.base.Optional;\nimport com.google.common.reflect.Invokable;\n\n/**\n * Utilities for FormSigner implementations.\n */\npublic final class FormSignerUtils {\n\n   private FormSignerUtils() {}\n\n   /**\n    * Get the version from a @ApiVersionOverride() annotation on an API method or its owning class.\n    * @param request The API request for the method.\n    * @return An optional of the value of the annotation.\n    */\n   public static Optional<String> getAnnotatedApiVersion(HttpRequest request) {\n      if (request instanceof GeneratedHttpRequest) {\n         GeneratedHttpRequest generatedRequest = (GeneratedHttpRequest) request;\n         return getAnnotatedApiVersion(generatedRequest.getInvocation());\n      } else {\n         return Optional.absent();\n      }\n   }\n\n   private static Optional<String> getAnnotatedApiVersion(Invocation invocation) {\n      final Invokable<?, ?> invokable = invocation.getInvokable();\n      if (invokable.isAnnotationPresent(ApiVersionOverride.class)) {\n         return Optional.fromNullable(invokable.getAnnotation(ApiVersionOverride.class).value());\n      } else {\n         final Class<?> owner = invokable.getOwnerType().getRawType();\n         if (owner.isAnnotationPresent(ApiVersionOverride.class)) {\n            return Optional.fromNullable(owner.getAnnotation(ApiVersionOverride.class).value());\n         }\n      }\n      return Optional.absent();\n   }\n\n}\n"
  },
  {
    "path": "apis/sts/src/main/java/org/jclouds/aws/filters/FormSignerV4.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.filters;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.hash.Hashing.sha256;\nimport static com.google.common.io.BaseEncoding.base16;\nimport static com.google.common.net.HttpHeaders.AUTHORIZATION;\nimport static com.google.common.net.HttpHeaders.HOST;\nimport static org.jclouds.aws.filters.FormSignerUtils.getAnnotatedApiVersion;\nimport static org.jclouds.aws.reference.FormParameters.ACTION;\nimport static org.jclouds.aws.reference.FormParameters.VERSION;\nimport static org.jclouds.http.utils.Queries.queryParser;\n\nimport java.net.URI;\nimport java.security.GeneralSecurityException;\nimport java.util.List;\nimport java.util.Map;\n\nimport javax.crypto.Mac;\nimport javax.crypto.spec.SecretKeySpec;\nimport jakarta.inject.Inject;\n\nimport org.jclouds.aws.domain.SessionCredentials;\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.location.Provider;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.rest.annotations.ApiVersion;\n\nimport com.google.common.base.Joiner;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Splitter;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Multimap;\nimport com.google.inject.ImplementedBy;\n\npublic final class FormSignerV4 implements FormSigner {\n\n   // Specifying a default for how to parse the service and region in this way allows\n   // tests or other downstream services to not have to use guice overrides.\n   @ImplementedBy(ServiceAndRegion.AWSServiceAndRegion.class)\n   public interface ServiceAndRegion {\n      String service();\n      String region(String host);\n\n      static final class AWSServiceAndRegion implements ServiceAndRegion {\n         private final String service;\n\n         @Inject AWSServiceAndRegion(ProviderMetadata provider) {\n            this(provider.getEndpoint());\n         }\n\n         AWSServiceAndRegion(String endpoint) {\n            this.service = parseServiceAndRegion(URI.create(checkNotNull(endpoint, \"endpoint\")).getHost()).get(0);\n         }\n\n         @Override public String service() {\n            return service;\n         }\n\n         @Override public String region(String host) {\n            return parseServiceAndRegion(host).get(1);\n         }\n\n         /** This will only work for amazon deployments, and perhaps not all of them. */\n         private static List<String> parseServiceAndRegion(String host) {\n            return Splitter.on('.').splitToList(host);\n         }\n      }\n   }\n\n   private final String apiVersion;\n   private final Supplier<Credentials> creds;\n   private final jakarta.inject.Provider<String> iso8601Timestamp;\n   private final ServiceAndRegion serviceAndRegion;\n\n   @Inject FormSignerV4(@ApiVersion String apiVersion, @Provider Supplier<Credentials> creds,\n         @TimeStamp jakarta.inject.Provider<String> iso8601Timestamp, ServiceAndRegion serviceAndRegion) {\n      this.apiVersion = apiVersion;\n      this.creds = creds;\n      this.iso8601Timestamp = iso8601Timestamp;\n      this.serviceAndRegion = serviceAndRegion;\n   }\n\n   /**\n    * Adds the Authorization header to the request.\n    *\n    * Also if the method for the operation (or its class) is annotated with a version that is higher than the\n    * default (apiVersion), then the Version parameter of the request is set to be the value from the annotation.\n    *\n    * @param request The HTTP request for the API call.\n    * @return The request\n    * @throws HttpException\n    */\n   @Override\n   public HttpRequest filter(HttpRequest request) throws HttpException {\n      String host = request.getFirstHeaderOrNull(HOST);\n      checkArgument(host != null, \"request is not ready to sign; host not present\");\n      String form = request.getPayload().getRawContent().toString();\n      Multimap<String, String> decodedParams = queryParser().apply(form);\n      checkArgument(decodedParams.containsKey(ACTION), \"request is not ready to sign; Action not present %s\", form);\n\n      String timestamp = iso8601Timestamp.get();\n      String datestamp = timestamp.substring(0, 8);\n\n      String service = serviceAndRegion.service();\n      String region = serviceAndRegion.region(host);\n      String credentialScope = Joiner.on('/').join(datestamp, region, service, \"aws4_request\");\n\n      // content-type is not a required signing param. However, examples use this, so we include it to ease testing.\n      ImmutableMap.Builder<String, String> signedHeadersBuilder = ImmutableMap.<String, String> builder() //\n            .put(\"content-type\", request.getPayload().getContentMetadata().getContentType()) //\n            .put(\"host\", host) //\n            .put(\"x-amz-date\", timestamp);\n\n      HttpRequest.Builder<?> requestBuilder = request.toBuilder() //\n            .removeHeader(AUTHORIZATION) //\n            .replaceHeader(\"X-Amz-Date\", timestamp);\n\n      if (!decodedParams.containsKey(VERSION)) {\n         Optional<String> optAnnotatedVersion = getAnnotatedApiVersion(request);\n         if (optAnnotatedVersion.isPresent()) {\n            String annotatedVersion = optAnnotatedVersion.get();\n            // allow an explicit version annotation to _upgrade_ the version past apiVersion (but not downgrade)\n            String greater = annotatedVersion.compareTo(apiVersion) > 0 ? annotatedVersion : apiVersion;\n            requestBuilder.addFormParam(VERSION, greater);\n         } else {\n            requestBuilder.addFormParam(VERSION, apiVersion);\n         }\n      }\n\n      Credentials credentials = creds.get();\n\n      if (credentials instanceof SessionCredentials) {\n         String token = SessionCredentials.class.cast(credentials).getSessionToken();\n         requestBuilder.replaceHeader(\"X-Amz-Security-Token\", token);\n         signedHeadersBuilder.put(\"x-amz-security-token\", token);\n      }\n\n      ImmutableMap<String, String> signedHeaders = signedHeadersBuilder.build();\n\n      String stringToSign = createStringToSign(requestBuilder.build(), signedHeaders, credentialScope);\n      byte[] signatureKey = signatureKey(credentials.credential, datestamp, region, service);\n      String signature = base16().lowerCase().encode(hmacSHA256(stringToSign, signatureKey));\n\n      StringBuilder authorization = new StringBuilder(\"AWS4-HMAC-SHA256 \");\n      authorization.append(\"Credential=\").append(credentials.identity).append('/').append(credentialScope).append(\", \");\n      authorization.append(\"SignedHeaders=\").append(Joiner.on(';').join(signedHeaders.keySet())).append(\", \");\n      authorization.append(\"Signature=\").append(signature);\n\n      return requestBuilder.addHeader(AUTHORIZATION, authorization.toString()).build();\n   }\n\n   static byte[] signatureKey(String secretKey, String datestamp, String region, String service) {\n      byte[] kSecret = (\"AWS4\" + secretKey).getBytes(UTF_8);\n      byte[] kDate = hmacSHA256(datestamp, kSecret);\n      byte[] kRegion = hmacSHA256(region, kDate);\n      byte[] kService = hmacSHA256(service, kRegion);\n      byte[] kSigning = hmacSHA256(\"aws4_request\", kService);\n      return kSigning;\n   }\n\n   static byte[] hmacSHA256(String data, byte[] key) {\n      try {\n         String algorithm = \"HmacSHA256\";\n         Mac mac = Mac.getInstance(algorithm);\n         mac.init(new SecretKeySpec(key, algorithm));\n         return mac.doFinal(data.getBytes(UTF_8));\n      } catch (GeneralSecurityException e) {\n         throw new HttpException(e);\n      }\n   }\n\n   static String createStringToSign(HttpRequest request, Map<String, String> signedHeaders, String credentialScope) {\n      StringBuilder canonicalRequest = new StringBuilder();\n      // HTTPRequestMethod + '\\n' +\n      canonicalRequest.append(request.getMethod()).append(\"\\n\");\n      // CanonicalURI + '\\n' +\n      canonicalRequest.append(request.getEndpoint().getPath()).append(\"\\n\");\n      // CanonicalQueryString + '\\n' +\n      checkArgument(request.getEndpoint().getQuery() == null, \"Query parameters not yet supported %s\", request);\n      canonicalRequest.append(\"\\n\");\n      // CanonicalHeaders + '\\n' +\n      for (Map.Entry<String, String> entry : signedHeaders.entrySet()) {\n         canonicalRequest.append(entry.getKey()).append(':').append(entry.getValue()).append('\\n');\n      }\n      canonicalRequest.append(\"\\n\");\n\n      // SignedHeaders + '\\n' +\n      canonicalRequest.append(Joiner.on(';').join(signedHeaders.keySet())).append('\\n');\n\n      // HexEncode(Hash(Payload))\n      String payload = request.getPayload().getRawContent().toString();\n      canonicalRequest.append(base16().lowerCase().encode(sha256().hashString(payload, UTF_8).asBytes()));\n\n      StringBuilder toSign = new StringBuilder();\n      // Algorithm + '\\n' +\n      toSign.append(\"AWS4-HMAC-SHA256\").append('\\n');\n      // RequestDate + '\\n' +\n      toSign.append(signedHeaders.get(\"x-amz-date\")).append('\\n');\n      // CredentialScope + '\\n' +\n      toSign.append(credentialScope).append('\\n');\n      // HexEncode(Hash(CanonicalRequest))\n      toSign.append(base16().lowerCase().encode(sha256().hashString(canonicalRequest.toString(), UTF_8).asBytes()));\n\n      return toSign.toString();\n   }\n}\n"
  },
  {
    "path": "apis/sts/src/main/java/org/jclouds/aws/handlers/AWSClientErrorRetryHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.handlers;\n\nimport static org.jclouds.http.HttpUtils.closeClientButKeepContentStream;\n\nimport java.util.Set;\n\nimport org.jclouds.aws.domain.AWSError;\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpRetryHandler;\nimport org.jclouds.http.annotation.ClientError;\nimport org.jclouds.http.handlers.BackoffLimitedRetryHandler;\n\nimport com.google.inject.Inject;\n\n/**\n * Handles Retryable responses with error codes in the 4xx range\n */\npublic class AWSClientErrorRetryHandler implements HttpRetryHandler {\n\n   private final AWSUtils utils;\n   private final BackoffLimitedRetryHandler backoffLimitedRetryHandler;\n   private final Set<String> retryableCodes;\n\n   @Inject\n   public AWSClientErrorRetryHandler(AWSUtils utils, BackoffLimitedRetryHandler backoffLimitedRetryHandler,\n         @ClientError Set<String> retryableCodes) {\n      this.utils = utils;\n      this.backoffLimitedRetryHandler = backoffLimitedRetryHandler;\n      this.retryableCodes = retryableCodes;\n   }\n\n   @Override\n   public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) {\n      if (response.getStatusCode() == 400 || response.getStatusCode() == 403 || response.getStatusCode() == 409) {\n         // Content can be null in the case of HEAD requests\n         if (response.getPayload() != null) {\n            closeClientButKeepContentStream(response);\n            AWSError error = utils.parseAWSErrorFromContent(command.getCurrentRequest(), response);\n            if (error != null) {\n               return shouldRetryRequestOnError(command, response, error);\n            }\n         }\n      }\n      return false;\n   }\n\n   protected boolean shouldRetryRequestOnError(HttpCommand command, HttpResponse response, AWSError error) {\n      if (retryableCodes.contains(error.getCode()))\n         return backoffLimitedRetryHandler.shouldRetryRequest(command, response);\n      return false;\n   }\n\n}\n"
  },
  {
    "path": "apis/sts/src/main/java/org/jclouds/aws/handlers/AWSServerErrorRetryHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.handlers;\n\nimport static org.jclouds.http.HttpUtils.closeClientButKeepContentStream;\n\nimport java.util.Set;\n\nimport org.jclouds.aws.domain.AWSError;\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.annotation.ServerError;\nimport org.jclouds.http.handlers.BackoffLimitedRetryHandler;\n\nimport com.google.inject.Inject;\nimport com.google.inject.Singleton;\n\n/**\n * Handles Retryable responses with error codes in the 5xx range\n */\n@Singleton\npublic class AWSServerErrorRetryHandler extends BackoffLimitedRetryHandler {\n\n   private final AWSUtils utils;\n   private final Set<String> retryableServerCodes;\n\n   @Inject\n   public AWSServerErrorRetryHandler(AWSUtils utils,\n         @ServerError Set<String> retryableServerCodes) {\n      this.utils = utils;\n      this.retryableServerCodes = retryableServerCodes;\n   }\n\n   @Override\n   public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) {\n      switch (response.getStatusCode()) {\n      case 500:  // Internal Server Error\n      case 503:  // Service Unavailable\n         // Content can be null in the case of HEAD requests\n         if (response.getPayload() != null) {\n            closeClientButKeepContentStream(response);\n            AWSError error = utils.parseAWSErrorFromContent(command.getCurrentRequest(), response);\n            if (error != null) {\n               return shouldRetryRequestOnError(command, response, error);\n            }\n         }\n         break;\n      case 504:  // Gateway Timeout\n         return super.shouldRetryRequest(command, response);\n      }\n      return false;\n   }\n\n   protected boolean shouldRetryRequestOnError(HttpCommand command, HttpResponse response, AWSError error) {\n      if (retryableServerCodes.contains(error.getCode()))\n         return super.shouldRetryRequest(command, response);\n      return false;\n   }\n\n   public void imposeBackoffExponentialDelay(long period, int pow, int failureCount, int max, String commandDescription) {\n      imposeBackoffExponentialDelay(period, period * 100L, pow, failureCount, max, commandDescription);\n   }\n\n   \n}\n"
  },
  {
    "path": "apis/sts/src/main/java/org/jclouds/aws/handlers/ParseAWSErrorFromXmlContent.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.handlers;\n\nimport static org.jclouds.http.HttpUtils.closeClientButKeepContentStream;\nimport static org.jclouds.http.HttpUtils.releasePayload;\n\nimport java.io.IOException;\nimport java.nio.charset.StandardCharsets;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.AWSResponseException;\nimport org.jclouds.aws.domain.AWSError;\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.InsufficientResourcesException;\nimport org.jclouds.rest.ResourceAlreadyExistsException;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.jclouds.util.Strings2;\n\nimport com.google.common.annotations.VisibleForTesting;\n\n/**\n * This will parse and set an appropriate exception on the command object.\n * \n * @see AWSError\n */\n@Singleton\npublic class ParseAWSErrorFromXmlContent implements HttpErrorHandler {\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   @VisibleForTesting\n   final AWSUtils utils;\n\n   @Inject\n   public ParseAWSErrorFromXmlContent(AWSUtils utils) {\n      this.utils = utils;\n   }\n\n   public void handleError(HttpCommand command, HttpResponse response) {\n      Exception exception = new HttpResponseException(command, response);\n      try {\n         AWSError error = null;\n         // it is important to always read fully and close streams\n         byte[] data = closeClientButKeepContentStream(response);\n         String message = data != null ? new String(data, StandardCharsets.UTF_8) : null;\n         if (response.getPayload() != null) {\n            String contentType = response.getPayload().getContentMetadata().getContentType();\n            if (contentType != null && (contentType.indexOf(\"xml\") != -1 || contentType.indexOf(\"unknown\") != -1)) {\n               error = utils.parseAWSErrorFromContent(command.getCurrentRequest(), response);\n               if (error != null) {\n                  message = error.getMessage();\n                  exception = new AWSResponseException(command, response, error);\n               } else {\n                  exception = new HttpResponseException(command, response, message);\n               }\n            } else {\n               try {\n                  message = Strings2.toStringAndClose(response.getPayload().openStream());\n                  exception = new HttpResponseException(command, response, message);\n               } catch (IOException e) {\n               }\n            }\n         }\n         message = message != null ? message : String.format(\"%s -> %s\", command.getCurrentRequest().getRequestLine(),\n                  response.getStatusLine());\n         exception = refineException(command, response, exception, error, message);\n      } finally {\n         releasePayload(response);\n         command.setException(exception);\n      }\n   }\n\n   protected Exception refineException(HttpCommand command, HttpResponse response, Exception exception, AWSError error,\n            String message) {\n      String errorCode = (error != null && error.getCode() != null) ? error.getCode() : null;\n      switch (response.getStatusCode()) {\n         case 400:\n            if (\"UnsupportedOperation\".equals(errorCode))\n               exception = new UnsupportedOperationException(message, exception);\n            else if (\"AddressLimitExceeded\".equals(errorCode))\n               exception = new InsufficientResourcesException(message, exception);\n            else if (\"TooManyBuckets\".equals(errorCode))\n               exception = new InsufficientResourcesException(message, exception);\n            else if (errorCode != null && (errorCode.indexOf(\"NotFound\") != -1 || errorCode.endsWith(\".Unknown\")))\n               exception = new ResourceNotFoundException(message, exception);\n            else if (\"IncorrectState\".equals(errorCode)\n                     || (errorCode != null && (error.getCode().endsWith(\".Duplicate\") \n                              || error.getCode().endsWith(\".InUse\") || error.getCode().equals(\"DependencyViolation\")))\n                     || (message != null && (message.indexOf(\"already exists\") != -1 || message.indexOf(\"is in use\") != -1)))\n               exception = new IllegalStateException(message, exception);\n            else if (errorCode != null && errorCode.indexOf(\"AuthFailure\") != -1)\n               exception = new AuthorizationException(message, exception);\n            else if (message != null\n                     && (message.indexOf(\"Invalid id\") != -1 || message.indexOf(\"Failed to bind\") != -1))\n               exception = new IllegalArgumentException(message, exception);\n            break;\n         case 401:\n         case 403:\n            exception = new AuthorizationException(message, exception);\n            break;\n         case 404:\n            if (!command.getCurrentRequest().getMethod().equals(\"DELETE\")) {\n               exception = new ResourceNotFoundException(message, exception);\n            }\n            break;\n         case 409:\n            if (\"BucketAlreadyExists\".equals(errorCode)) {\n               exception = new ResourceAlreadyExistsException(exception);\n            } else {\n               exception = new IllegalStateException(message, exception);\n            }\n            break;\n      }\n      return exception;\n   }\n\n}\n"
  },
  {
    "path": "apis/sts/src/main/java/org/jclouds/aws/handlers/package-info.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * This package contains HttpResponseHandlers needed to operate the REST api.\n * @see <a href=\"http://docs.amazonwebservices.com/AmazonS3/latest/RESTAuthentication.html\" />\n */\npackage org.jclouds.aws.handlers;\n"
  },
  {
    "path": "apis/sts/src/main/java/org/jclouds/aws/reference/AWSConstants.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.reference;\n\n/**\n * Configuration properties and constants used in amazon connections.\n */\npublic final class AWSConstants {\n   public static final String PROPERTY_ZONECLIENT_ENDPOINT = \"jclouds.aws.zoneclient-endpoint\";\n   public static final String PROPERTY_AUTH_TAG = \"jclouds.aws.auth.tag\";\n   public static final String PROPERTY_HEADER_TAG = \"jclouds.aws.header.tag\";\n\n   private AWSConstants() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "apis/sts/src/main/java/org/jclouds/aws/reference/FormParameters.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.reference;\n\n/**\n * Configuration properties and constants used in EC2 connections.\n * \n * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/Query-Common-Parameters.html\"/>\n */\npublic final class FormParameters {\n\n   /**\n    * Indicates the action to perform. Example: RunInstances\n    */\n   public static final String ACTION = \"Action\";\n\n   /**\n    * The API version to use, as specified in the WSDL. Example: 2009-04-04\n    */\n   public static final String VERSION = \"Version\";\n\n   /**\n    * The Access Key ID for the request sender. This identifies the account which will be charged\n    * for usage of the service. The account with which the Access Key ID is associated must be\n    * signed up for Amazon EC2, or requests will not be accepted. AKIADQKE4SARGYLE\n    */\n   public static final String AWS_ACCESS_KEY_ID = \"AWSAccessKeyId\";\n\n   /**\n    * The date and time at which the request is signed, in the format YYYY-MM-DDThh:mm:ssZ. For more\n    * information, go to ISO 8601. Example: 2006-07-07T15:04:56Z\n    */\n   public static final String TIMESTAMP = \"Timestamp\";\n\n   /**\n    * The date and time at which the signature included in the request expires, in the format\n    * YYYY-MM-DDThh:mm:ssZ. Example: 2006-07-07T15:04:56Z\n    */\n   public static final String EXPIRES = \"Expires\";\n   /**\n    * The request signature. For more information, go to the Amazon Elastic Compute Cloud Developer\n    * Guide. Example: Qnpl4Qk/7tINHzfXCiT7VbBatDA=\n    */\n   public static final String SIGNATURE = \"Signature\";\n   /**\n    * Temporary access token.\n    */\n   public static final String SECURITY_TOKEN = \"SecurityToken\";\n   /**\n    * The hash algorithm you use to create the request signature. Valid values: HmacSHA256 |\n    * HmacSHA1. For more information, go to the Amazon Elastic Compute Cloud Developer Guide.\n    * Example: HmacSHA256\n    */\n   public static final String SIGNATURE_METHOD = \"SignatureMethod\";\n   /**\n    * The signature version you use to sign the request. Set this value to 2. For more information,\n    * go to the Amazon Elastic Compute Cloud Developer Guide. Example: 2\n    * \n    */\n   public static final String SIGNATURE_VERSION = \"SignatureVersion\";\n\n   private FormParameters() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "apis/sts/src/main/java/org/jclouds/aws/util/AWSUtils.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.util;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.aws.reference.AWSConstants.PROPERTY_HEADER_TAG;\nimport static org.jclouds.http.HttpUtils.closeClientButKeepContentStream;\n\nimport java.util.Collection;\nimport java.util.Map;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Provider;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.domain.AWSError;\nimport org.jclouds.aws.domain.Region;\nimport org.jclouds.aws.xml.ErrorHandler;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.http.functions.ParseSax.Factory;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.rest.RequestSigner;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableMultimap.Builder;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Multimap;\n\n/**\n * Needed to sign and verify requests and responses.\n */\n@Singleton\n@SuppressWarnings(\"unchecked\")\npublic class AWSUtils {\n   @Singleton\n   public static class GetRegionFromLocation implements Function<Location, String> {\n      public String apply(Location location) {\n         String region = location.getScope() == LocationScope.REGION ? location.getId() : location.getParent().getId();\n         return region;\n      }\n   }\n\n   private final RequestSigner signer;\n   private final ParseSax.Factory factory;\n   private final Provider<ErrorHandler> errorHandlerProvider;\n   private final String requestId;\n   private final String requestToken;\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   @Inject\n   AWSUtils(@Named(PROPERTY_HEADER_TAG) String headerTag, RequestSigner signer, Factory factory,\n         Provider<ErrorHandler> errorHandlerProvider) {\n      this.signer = signer;\n      this.factory = factory;\n      this.errorHandlerProvider = errorHandlerProvider;\n      this.requestId = String.format(\"x-%s-request-id\", headerTag);\n      this.requestToken = String.format(\"x-%s-id-2\", headerTag);\n   }\n\n   public AWSError parseAWSErrorFromContent(HttpRequest request, HttpResponse response) {\n      byte[] actualPayload = response.getPayload() != null ? closeClientButKeepContentStream(response) : null;\n      if (actualPayload == null || actualPayload.length == 0)\n         return null;\n      if (\"text/plain\".equals(response.getPayload().getContentMetadata().getContentType()))\n         return null;\n      try {\n         AWSError error = factory.create(errorHandlerProvider.get()).setContext(request).apply(response);\n         if (error.getRequestId() == null)\n            error.setRequestId(response.getFirstHeaderOrNull(requestId));\n         error.setRequestToken(response.getFirstHeaderOrNull(requestToken));\n         if (\"SignatureDoesNotMatch\".equals(error.getCode())) {\n            error.setStringSigned(signer.createStringToSign(request));\n            error.setSignature(signer.sign(error.getStringSigned()));\n         }\n         return error;\n      } catch (RuntimeException e) {\n         logger.warn(e, \"error parsing error\");\n         return null;\n      }\n   }\n\n   public static <R extends HttpRequest> R indexStringArrayToFormValuesWithStringFormat(R request, String format,\n         Object input) {\n      checkArgument(checkNotNull(input, \"input\") instanceof String[], \"this binder is only valid for String[] : \"\n            + input.getClass());\n      String[] values = (String[]) input;\n      Builder<String, String> builder = ImmutableMultimap.builder();\n      for (int i = 0; i < values.length; i++) {\n         builder.put(String.format(format, i + 1), checkNotNull(values[i], format.toLowerCase() + \"s[\" + i + \"]\"));\n      }\n      ImmutableMultimap<String, String> forms = builder.build();\n      return forms.size() == 0 ? request : (R) request.toBuilder().replaceFormParams(forms).build();\n   }\n\n   // TODO: make this more dynamic\n   public static boolean isRegion(String regionName) {\n      return Region.DEFAULT_REGIONS.contains(regionName);\n   }\n\n   public static <R extends HttpRequest> R indexIterableToFormValuesWithPrefix(R request, String prefix, Object input) {\n      checkArgument(checkNotNull(input, \"input\") instanceof Iterable<?>, \"this binder is only valid for Iterable<?>: \"\n            + input.getClass());\n      Iterable<?> values = (Iterable<?>) input;\n      Builder<String, String> builder = ImmutableMultimap.builder();\n      int i = 0;\n      for (Object o : values) {\n         builder.put(prefix + \".\" + (i++ + 1), checkNotNull(o.toString(), prefix.toLowerCase() + \"s[\" + i + \"]\"));\n      }\n      ImmutableMultimap<String, String> forms = builder.build();\n      return forms.isEmpty() ? request : (R) request.toBuilder().replaceFormParams(forms).build();\n   }\n\n   public static <R extends HttpRequest> R indexStringArrayToFormValuesWithPrefix(R request, String prefix, Object input) {\n      checkArgument(checkNotNull(input, \"input\") instanceof String[], \"this binder is only valid for String[] : \"\n            + input.getClass());\n      String[] values = (String[]) input;\n      Builder<String, String> builder = ImmutableMultimap.builder();\n      for (int i = 0; i < values.length; i++) {\n         builder.put(prefix + \".\" + (i + 1), checkNotNull(values[i], prefix.toLowerCase() + \"s[\" + i + \"]\"));\n      }\n      ImmutableMultimap<String, String> forms = builder.build();\n      return forms.isEmpty() ? request : (R) request.toBuilder().replaceFormParams(forms).build();\n   }\n\n   public static <R extends HttpRequest> R indexMapToFormValuesWithPrefix(R request, String prefix, String keySuffix, String valueSuffix, Object input) {\n      checkArgument(checkNotNull(input, \"input\") instanceof Map<?, ?>, \"this binder is only valid for Map<?,?>: \" + input.getClass());\n      Map<?, ?> map = (Map<?, ?>) input;\n      Builder<String, String> builder = ImmutableMultimap.builder();\n      int i = 1;\n      for (Map.Entry<?, ?> e : map.entrySet()) {\n         builder.put(prefix + \".\" + i + \".\" + keySuffix, checkNotNull(e.getKey().toString(), keySuffix.toLowerCase() + \"s[\" + i + \"]\"));\n         if (e.getValue() != null) {\n            builder.put(prefix + \".\" + i + \".\" + valueSuffix, e.getValue().toString());\n         }\n         i++;\n      }\n      ImmutableMultimap<String, String> forms = builder.build();\n      return forms.isEmpty() ? request : (R) request.toBuilder().replaceFormParams(forms).build();\n   }\n\n   public static <R extends HttpRequest> R indexMultimapToFormValuesWithPrefix(R request, String prefix, String keySuffix, String valueSuffix, Object input) {\n      checkArgument(checkNotNull(input, \"input\") instanceof Multimap<?, ?>, \"this binder is only valid for Multimap<?,?>: \" + input.getClass());\n      Multimap<Object, Object> map = (Multimap<Object, Object>) input;\n      Builder<String, String> builder = ImmutableMultimap.builder();\n      int i = 1;\n      for (Map.Entry<Object, Collection<Object>> entry : map.asMap().entrySet()) {\n         builder.put(prefix + \".\" + i + \".\" + keySuffix, checkNotNull(entry.getKey().toString(), keySuffix.toLowerCase() + \"s[\" + i + \"]\"));\n         int j = 1;\n         for (Object v : entry.getValue()) {\n            builder.put(prefix + \".\" + i + \".\" + valueSuffix + \".\" + j, v.toString());\n            j++;\n         }\n         i++;\n      }\n      ImmutableMultimap<String, String> forms = builder.build();\n      return forms.size() == 0 ? request : (R) request.toBuilder().replaceFormParams(forms).build();\n   }\n\n   public static <R extends HttpRequest> R indexMapOfIterableToFormValuesWithPrefix(R request, String prefix, String keySuffix, String valueSuffix, Object input) {\n      checkArgument(checkNotNull(input, \"input\") instanceof Map<?, ?>, \"this binder is only valid for Map<?,Iterable<?>>: \" + input.getClass());\n      Map<Object, Iterable<Object>> map = (Map<Object, Iterable<Object>>) input;\n      Builder<String, String> builder = ImmutableMultimap.builder();\n      int i = 1;\n      for (Map.Entry<Object, Iterable<Object>> entry : map.entrySet()) {\n         builder.put(prefix + \".\" + i + \".\" + keySuffix, checkNotNull(entry.getKey().toString(), keySuffix.toLowerCase() + \"s[\" + i + \"]\"));\n         Iterable<Object> iterable = entry.getValue();\n         if (!Iterables.isEmpty(iterable)) {\n            int j = 1;\n            for (Object v : iterable) {\n               builder.put(prefix + \".\" + i + \".\" + valueSuffix + \".\" + j, v.toString());\n               j++;\n            }\n         }\n         i++;\n      }\n      ImmutableMultimap<String, String> forms = builder.build();\n      return forms.size() == 0 ? request : (R) request.toBuilder().replaceFormParams(forms).build();\n   }\n\n   public static String getRegionFromLocationOrNull(Location location) {\n      return location.getScope() == LocationScope.ZONE ? location.getParent().getId() : location.getId();\n   }\n\n   // there may not be a region, and in this case we do-not encode it into the string\n   public static String[] parseHandle(String id) {\n      String[] parts = checkNotNull(id, \"id\").split(\"/\");\n      return (parts.length == 1) ? new String[] { null, id } : parts;\n   }\n\n   public static String findRegionInArgsOrNull(GeneratedHttpRequest gRequest) {\n      for (Object arg : gRequest.getInvocation().getArgs()) {\n         if (arg instanceof String) {\n            String regionName = (String) arg;\n            // TODO regions may not be amazon regions!\n            // take from a configured value\n            if (isRegion(regionName))\n               return regionName;\n         }\n      }\n      return null;\n   }\n}\n"
  },
  {
    "path": "apis/sts/src/main/java/org/jclouds/aws/xml/ErrorHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.xml;\n\nimport org.jclouds.aws.domain.AWSError;\nimport org.jclouds.http.functions.ParseSax;\n\n/**\n * Parses the error from the Amazon S3 REST API.\n * \n * @see <a\n *      href=\"http://docs.amazonwebservices.com/AmazonS3/2006-03-01/index.html?UsingRESTError.html\"\n *      />\n */\npublic class ErrorHandler extends ParseSax.HandlerWithResult<AWSError> {\n\n   private AWSError error = new AWSError();\n   private StringBuilder currentText = new StringBuilder();\n\n   public AWSError getResult() {\n      return error;\n   }\n\n   public void endElement(String uri, String name, String qName) {\n\n      if (qName.equals(\"Code\")) {\n         error.setCode(currentText.toString().trim());\n      } else if (qName.equals(\"Message\")) {\n         error.setMessage(currentText.toString().trim());\n      } else if (qName.equalsIgnoreCase(\"RequestId\")) {\n         error.setRequestId(currentText.toString().trim());\n      } else if (!qName.equals(\"Error\")) {\n         error.getDetails().put(qName, currentText.toString().trim());\n      }\n      currentText.setLength(0);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "apis/sts/src/main/java/org/jclouds/aws/xml/SessionCredentialsHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.xml;\n\nimport static org.jclouds.util.SaxUtils.currentOrNull;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.aws.domain.SessionCredentials;\nimport org.jclouds.date.DateService;\nimport org.jclouds.http.functions.ParseSax;\n\n/**\n * @see <a href=\n *      \"http://docs.aws.amazon.com/STS/latest/APIReference/API_Credentials.html\"\n *      />\n */\npublic class SessionCredentialsHandler extends ParseSax.HandlerForGeneratedRequestWithResult<SessionCredentials> {\n   private final DateService dateService;\n\n   @Inject\n   protected SessionCredentialsHandler(DateService dateService) {\n      this.dateService = dateService;\n   }\n\n   private StringBuilder currentText = new StringBuilder();\n   private SessionCredentials.Builder builder = SessionCredentials.builder();\n\n   @Override\n   public SessionCredentials getResult() {\n      try {\n         return builder.build();\n      } finally {\n         builder = SessionCredentials.builder();\n      }\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) {\n      if (qName.equals(\"AccessKeyId\")) {\n         builder.accessKeyId(currentOrNull(currentText));\n      } else if (qName.equals(\"SecretAccessKey\")) {\n         builder.secretAccessKey(currentOrNull(currentText));\n      } else if (qName.equals(\"SessionToken\")) {\n         builder.sessionToken(currentOrNull(currentText));\n      } else if (qName.equals(\"Expiration\")) {\n         try {\n            builder.expiration(dateService.iso8601SecondsDateParse(currentOrNull(currentText)));\n         } catch (IllegalArgumentException e) {\n            builder.expiration(dateService.iso8601DateParse(currentOrNull(currentText)));\n         }\n      }\n      currentText.setLength(0);\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "apis/sts/src/main/java/org/jclouds/sts/STSApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sts;\n\nimport java.io.Closeable;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.FormParam;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\n\nimport org.jclouds.aws.domain.SessionCredentials;\nimport org.jclouds.aws.filters.FormSigner;\nimport org.jclouds.aws.xml.SessionCredentialsHandler;\nimport org.jclouds.rest.annotations.FormParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.VirtualHost;\nimport org.jclouds.rest.annotations.XMLResponseParser;\nimport org.jclouds.sts.domain.UserAndSessionCredentials;\nimport org.jclouds.sts.options.AssumeRoleOptions;\nimport org.jclouds.sts.options.FederatedUserOptions;\nimport org.jclouds.sts.options.SessionCredentialsOptions;\nimport org.jclouds.sts.xml.UserAndSessionCredentialsHandler;\n\n/**\n * Provides access to Amazon STS via the Query API\n * <p/>\n * \n * @see <a href=\"http://docs.amazonwebservices.com/STS/latest/APIReference\" />\n */\n@RequestFilters(FormSigner.class)\n@VirtualHost\npublic interface STSApi extends Closeable {\n   /**\n    * Returns a set of temporary credentials for an AWS account or IAM user,\n    * with a default timeout\n    */\n   @Named(\"GetSessionToken\")\n   @POST\n   @Path(\"/\")\n   @XMLResponseParser(SessionCredentialsHandler.class)\n   @FormParams(keys = \"Action\", values = \"GetSessionToken\")\n   SessionCredentials createTemporaryCredentials();\n\n   /**\n    * like {@link #createTemporaryCredentials()}, except you can modify the\n    * timeout and other parameters.\n    */\n   @Named(\"GetSessionToken\")\n   @POST\n   @Path(\"/\")\n   @XMLResponseParser(SessionCredentialsHandler.class)\n   @FormParams(keys = \"Action\", values = \"GetSessionToken\")\n   SessionCredentials createTemporaryCredentials(SessionCredentialsOptions options);\n\n   /**\n    * Assumes a role for a specified session. Only IAM users can assume a role.\n    * \n    * @param sessionName\n    *           An identifier for the assumed role session, included as part of\n    *           {@link User#getId}.\n    * @param roleArn\n    *           The Amazon Resource Name (ARN) of the role that the caller is\n    *           assuming.\n    */\n   @Named(\"AssumeRole\")\n   @POST\n   @Path(\"/\")\n   @XMLResponseParser(UserAndSessionCredentialsHandler.class)\n   @FormParams(keys = \"Action\", values = \"AssumeRole\")\n   UserAndSessionCredentials assumeRole(@FormParam(\"RoleArn\") String roleArn,\n         @FormParam(\"RoleSessionName\") String sessionName);\n   \n   /**\n    * like {@link #assumeRole(String, String)}, except you can modify the\n    * timeout and other parameters.\n    */\n   @Named(\"AssumeRole\")\n   @POST\n   @Path(\"/\")\n   @XMLResponseParser(UserAndSessionCredentialsHandler.class)\n   @FormParams(keys = \"Action\", values = \"AssumeRole\")\n   UserAndSessionCredentials assumeRole(@FormParam(\"RoleArn\") String roleArn,\n         @FormParam(\"RoleSessionName\") String sessionName, AssumeRoleOptions options);\n   \n   /**\n    * Returns a set of temporary credentials for a federated user with the user\n    * name specified.\n    * \n    * @param userName\n    *           The name of the federated user, included as part of\n    *           {@link User#getId}.\n    */\n   @Named(\"GetFederationToken\")\n   @POST\n   @Path(\"/\")\n   @XMLResponseParser(UserAndSessionCredentialsHandler.class)\n   @FormParams(keys = \"Action\", values = \"GetFederationToken\")\n   UserAndSessionCredentials createFederatedUser(@FormParam(\"Name\") String userName);\n   \n   /**\n    * like {@link #createFederatedUser(String)}, except you can modify the\n    * timeout and other parameters.\n    */\n   @Named(\"GetFederationToken\")\n   @POST\n   @Path(\"/\")\n   @XMLResponseParser(UserAndSessionCredentialsHandler.class)\n   @FormParams(keys = \"Action\", values = \"GetFederationToken\")\n   UserAndSessionCredentials createFederatedUser(@FormParam(\"Name\") String userName, FederatedUserOptions options);\n}\n"
  },
  {
    "path": "apis/sts/src/main/java/org/jclouds/sts/STSApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sts;\n\nimport static org.jclouds.aws.reference.AWSConstants.PROPERTY_AUTH_TAG;\nimport static org.jclouds.aws.reference.AWSConstants.PROPERTY_HEADER_TAG;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.rest.internal.BaseHttpApiMetadata;\nimport org.jclouds.sts.config.STSHttpApiModule;\n\nimport com.google.auto.service.AutoService;\n\n/**\n * Implementation of {@link ApiMetadata} for Amazon's STS api.\n */\n@AutoService(ApiMetadata.class)\npublic class STSApiMetadata extends BaseHttpApiMetadata<STSApi> {\n\n   @Override\n   public Builder toBuilder() {\n      return new Builder().fromApiMetadata(this);\n   }\n\n   public STSApiMetadata() {\n      this(new Builder());\n   }\n\n   protected STSApiMetadata(Builder builder) {\n      super(Builder.class.cast(builder));\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = BaseHttpApiMetadata.defaultProperties();\n      properties.setProperty(PROPERTY_AUTH_TAG, \"AWS\");\n      properties.setProperty(PROPERTY_HEADER_TAG, \"amz\");\n      return properties;\n   }\n\n   public static class Builder extends BaseHttpApiMetadata.Builder<STSApi, Builder> {\n\n      protected Builder() {\n         id(\"sts\")\n         .name(\"Amazon STS Api\")\n         .identityName(\"Access Key ID\")\n         .credentialName(\"Secret Access Key\")\n         .version(\"2011-06-15\")\n         .documentation(URI.create(\"http://docs.amazonwebservices.com/STS/latest/APIReference/\"))\n         .defaultEndpoint(\"https://sts.amazonaws.com\")\n         .defaultProperties(STSApiMetadata.defaultProperties())\n         .defaultModule(STSHttpApiModule.class);\n      }\n\n      @Override\n      public STSApiMetadata build() {\n         return new STSApiMetadata(this);\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "apis/sts/src/main/java/org/jclouds/sts/config/STSHttpApiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sts.config;\n\nimport org.jclouds.aws.config.FormSigningHttpApiModule;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.sts.STSApi;\n\n/**\n * Configures the STS connection.\n */\n@ConfiguresHttpApi\npublic class STSHttpApiModule extends FormSigningHttpApiModule<STSApi> {\n\n}\n"
  },
  {
    "path": "apis/sts/src/main/java/org/jclouds/sts/domain/User.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sts.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\npublic final class User {\n   public static User fromIdAndArn(String id, String arn) {\n      return new User(id, arn);\n   }\n\n   private final String id;\n   private final String arn;\n\n   private User(String id, String arn) {\n      this.id = checkNotNull(id, \"id\");\n      this.arn = checkNotNull(arn, \"arn for %s\", id);\n   }\n\n   /**\n    * The id of the federated user or assumed role. ex.\n    * {@code ARO123EXAMPLE123:Bob}\n    */\n   public String getId() {\n      return id;\n   }\n\n   /**\n    * The arn of the federated user or assumed role.\n    * \n    * ex. {@code arn:aws:sts::123456789012:federated-user/Bob} or\n    * {@code arn:aws:sts::123456789012:assumed-role/demo/Bob}\n    */\n   public String getArn() {\n      return arn;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, arn);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      User other = (User) obj;\n      return Objects.equal(this.id, other.id) && Objects.equal(this.arn, other.arn);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).add(\"id\", id).add(\"arn\", arn).toString();\n   }\n}\n"
  },
  {
    "path": "apis/sts/src/main/java/org/jclouds/sts/domain/UserAndSessionCredentials.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sts.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.aws.domain.SessionCredentials;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\npublic final class UserAndSessionCredentials {\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().from(this);\n   }\n\n   public static final class Builder {\n      private User user;\n      private SessionCredentials credentials;\n      private int packedPolicySize;\n\n      /**\n       * @see UserAndSessionCredentials#getUser()\n       */\n      public Builder user(User user) {\n         this.user = user;\n         return this;\n      }\n\n      /**\n       * @see UserAndSessionCredentials#getCredentials()\n       */\n      public Builder credentials(SessionCredentials credentials) {\n         this.credentials = credentials;\n         return this;\n      }\n\n      /**\n       * @see UserAndSessionCredentials#getPackedPolicySize()\n       */\n      public Builder packedPolicySize(int packedPolicySize) {\n         this.packedPolicySize = packedPolicySize;\n         return this;\n      }\n\n      public UserAndSessionCredentials build() {\n         return new UserAndSessionCredentials(user, credentials, packedPolicySize);\n      }\n\n      public Builder from(UserAndSessionCredentials in) {\n         return this.user(in.user).credentials(in.credentials).packedPolicySize(in.packedPolicySize);\n      }\n   }\n\n   private final User user;\n   private final SessionCredentials credentials;\n   private final int packedPolicySize;\n\n   private UserAndSessionCredentials(User user, SessionCredentials credentials, int packedPolicySize) {\n      this.user = checkNotNull(user, \"user\");\n      this.credentials = checkNotNull(credentials, \"credentials for %s\", user);\n      this.packedPolicySize = packedPolicySize;\n   }\n\n   /**\n    * user correlating to {@link UserAndSessionCredentials#getCredentials()}\n    */\n   public User getUser() {\n      return user;\n   }\n\n   /**\n    * The temporary security credentials, which includes an Access Key ID, a\n    * Secret Access Key, and a security token.\n    */\n   public SessionCredentials getCredentials() {\n      return credentials;\n   }\n\n   /**\n    * A percentage value that indicates the size of the policy in packed form.\n    */\n   public int getPackedPolicySize() {\n      return packedPolicySize;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(user, credentials, packedPolicySize);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      UserAndSessionCredentials other = (UserAndSessionCredentials) obj;\n      return Objects.equal(this.user, other.user) && Objects.equal(this.credentials, other.credentials)\n            && Objects.equal(this.packedPolicySize, other.packedPolicySize);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).add(\"user\", user).add(\"credentials\", credentials)\n            .add(\"packedPolicySize\", packedPolicySize).toString();\n   }\n}\n"
  },
  {
    "path": "apis/sts/src/main/java/org/jclouds/sts/options/AssumeRoleOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sts.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.collect.Multimap;\n\n/**\n * @see <a href=\n *      \"http://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html\"\n *      />\n */\npublic class AssumeRoleOptions extends BaseHttpRequestOptions implements Cloneable {\n\n   // long as this is a more typical unit for duration, hence less casting\n   private Long durationSeconds;\n   private String policy;\n   private String externalId;\n\n   /**\n    * A unique identifier that is generated by a third party for each of their customers. \n    */\n   public AssumeRoleOptions externalId(String externalId) {\n      this.externalId = externalId;\n      return this;\n   }\n\n   /**\n    * The duration, in seconds, that the credentials should remain valid. 12\n    * hours is default. 15 minutes is current minimum.\n    */\n   public AssumeRoleOptions durationSeconds(long durationSeconds) {\n      this.durationSeconds = durationSeconds;\n      return this;\n   }\n\n   /**\n    * A supplemental policy that can be associated with the temporary security credentials. \n    */\n   public AssumeRoleOptions policy(String policy) {\n      this.policy = policy;\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see AssumeRoleOptions#externalId\n       */\n      public static AssumeRoleOptions externalId(String externalId) {\n         return new AssumeRoleOptions().externalId(externalId);\n      }\n\n      /**\n       * @see AssumeRoleOptions#durationSeconds\n       */\n      public static AssumeRoleOptions durationSeconds(long durationSeconds) {\n         return new AssumeRoleOptions().durationSeconds(durationSeconds);\n      }\n\n      /**\n       * @see AssumeRoleOptions#policy\n       */\n      public static AssumeRoleOptions policy(String policy) {\n         return new AssumeRoleOptions().policy(policy);\n      }\n   }\n\n   @Override\n   public Multimap<String, String> buildFormParameters() {\n      Multimap<String, String> params = super.buildFormParameters();\n      if (externalId != null)\n         params.put(\"ExternalId\", externalId.toString());\n      if (durationSeconds != null)\n         params.put(\"DurationSeconds\", durationSeconds.toString());\n      if (policy != null)\n         params.put(\"Policy\", policy);\n      return params;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(externalId, durationSeconds, policy);\n   }\n\n   @Override\n   public AssumeRoleOptions clone() {\n      return new AssumeRoleOptions().externalId(externalId).durationSeconds(durationSeconds)\n            .policy(policy);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      AssumeRoleOptions other = AssumeRoleOptions.class.cast(obj);\n      return Objects.equal(this.externalId, other.externalId)\n            && Objects.equal(this.durationSeconds, other.durationSeconds)\n            && Objects.equal(this.policy, other.policy);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"externalId\", externalId)\n            .add(\"durationSeconds\", durationSeconds).add(\"policy\", policy).toString();\n   }\n}\n"
  },
  {
    "path": "apis/sts/src/main/java/org/jclouds/sts/options/FederatedUserOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sts.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.collect.Multimap;\n\n/**\n * @see <a href=\n *      \"http://docs.aws.amazon.com/STS/latest/APIReference/API_GetFederationToken.html\"\n *      />\n */\npublic class FederatedUserOptions extends BaseHttpRequestOptions implements Cloneable {\n\n   // long as this is a more typical unit for duration, hence less casting\n   private Long durationSeconds;\n   private String policy;\n\n   /**\n    * The duration, in seconds, that the credentials should remain valid. 12\n    * hours is default. 15 minutes is current minimum.\n    */\n   public FederatedUserOptions durationSeconds(long durationSeconds) {\n      this.durationSeconds = durationSeconds;\n      return this;\n   }\n\n   /**\n    * A supplemental policy that can be associated with the temporary security\n    * credentials.\n    */\n   public FederatedUserOptions policy(String policy) {\n      this.policy = policy;\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see FederatedUserOptions#durationSeconds\n       */\n      public static FederatedUserOptions durationSeconds(long durationSeconds) {\n         return new FederatedUserOptions().durationSeconds(durationSeconds);\n      }\n\n      /**\n       * @see FederatedUserOptions#policy\n       */\n      public static FederatedUserOptions policy(String policy) {\n         return new FederatedUserOptions().policy(policy);\n      }\n   }\n\n   @Override\n   public Multimap<String, String> buildFormParameters() {\n      Multimap<String, String> params = super.buildFormParameters();\n      if (durationSeconds != null)\n         params.put(\"DurationSeconds\", durationSeconds.toString());\n      if (policy != null)\n         params.put(\"Policy\", policy);\n      return params;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(durationSeconds, policy);\n   }\n\n   @Override\n   public FederatedUserOptions clone() {\n      return new FederatedUserOptions().durationSeconds(durationSeconds).policy(policy);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      FederatedUserOptions other = FederatedUserOptions.class.cast(obj);\n      return Objects.equal(this.durationSeconds, other.durationSeconds) && Objects.equal(this.policy, other.policy);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"durationSeconds\", durationSeconds)\n            .add(\"policy\", policy).toString();\n   }\n}\n"
  },
  {
    "path": "apis/sts/src/main/java/org/jclouds/sts/options/SessionCredentialsOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sts.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.collect.Multimap;\n\n/**\n * Options used to get a session token.\n * \n * @see <a href=\n *      \"http://docs.aws.amazon.com/STS/latest/APIReference/API_GetSessionToken.html\"\n *      />\n */\npublic class SessionCredentialsOptions extends BaseHttpRequestOptions implements Cloneable {\n\n   // long as this is a more typical unit for duration, hence less casting\n   private Long durationSeconds;\n   private String tokenCode;\n   private String serialNumber;\n\n   /**\n    * The identification number of the MFA device for the user.\n    */\n   public SessionCredentialsOptions serialNumber(String serialNumber) {\n      this.serialNumber = serialNumber;\n      return this;\n   }\n\n   /**\n    * The duration, in seconds, that the credentials should remain valid. 12\n    * hours is default. 15 minutes is current minimum.\n    */\n   public SessionCredentialsOptions durationSeconds(long durationSeconds) {\n      this.durationSeconds = durationSeconds;\n      return this;\n   }\n\n   /**\n    * The value provided by the MFA device.\n    */\n   public SessionCredentialsOptions tokenCode(String tokenCode) {\n      this.tokenCode = tokenCode;\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see SessionCredentialsOptions#serialNumber\n       */\n      public static SessionCredentialsOptions serialNumber(String serialNumber) {\n         return new SessionCredentialsOptions().serialNumber(serialNumber);\n      }\n\n      /**\n       * @see SessionCredentialsOptions#durationSeconds\n       */\n      public static SessionCredentialsOptions durationSeconds(long durationSeconds) {\n         return new SessionCredentialsOptions().durationSeconds(durationSeconds);\n      }\n\n      /**\n       * @see SessionCredentialsOptions#tokenCode\n       */\n      public static SessionCredentialsOptions tokenCode(String tokenCode) {\n         return new SessionCredentialsOptions().tokenCode(tokenCode);\n      }\n   }\n\n   @Override\n   public Multimap<String, String> buildFormParameters() {\n      Multimap<String, String> params = super.buildFormParameters();\n      if (serialNumber != null)\n         params.put(\"SerialNumber\", serialNumber.toString());\n      if (durationSeconds != null)\n         params.put(\"DurationSeconds\", durationSeconds.toString());\n      if (tokenCode != null)\n         params.put(\"TokenCode\", tokenCode);\n      return params;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(serialNumber, durationSeconds, tokenCode);\n   }\n\n   @Override\n   public SessionCredentialsOptions clone() {\n      return new SessionCredentialsOptions().serialNumber(serialNumber).durationSeconds(durationSeconds)\n            .tokenCode(tokenCode);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      SessionCredentialsOptions other = SessionCredentialsOptions.class.cast(obj);\n      return Objects.equal(this.serialNumber, other.serialNumber)\n            && Objects.equal(this.durationSeconds, other.durationSeconds)\n            && Objects.equal(this.tokenCode, other.tokenCode);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"serialNumber\", serialNumber)\n            .add(\"durationSeconds\", durationSeconds).add(\"tokenCode\", tokenCode).toString();\n   }\n}\n"
  },
  {
    "path": "apis/sts/src/main/java/org/jclouds/sts/xml/UserAndSessionCredentialsHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sts.xml;\n\nimport static org.jclouds.util.SaxUtils.currentOrNull;\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport org.jclouds.aws.xml.SessionCredentialsHandler;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.sts.domain.User;\nimport org.jclouds.sts.domain.UserAndSessionCredentials;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\n\nimport com.google.inject.Inject;\n\npublic class UserAndSessionCredentialsHandler extends ParseSax.HandlerForGeneratedRequestWithResult<UserAndSessionCredentials> {\n\n   private final SessionCredentialsHandler credsHandler;\n\n   private StringBuilder currentText = new StringBuilder();\n   private UserAndSessionCredentials.Builder builder = UserAndSessionCredentials.builder();\n\n   @Inject\n   public UserAndSessionCredentialsHandler(SessionCredentialsHandler credsHandler) {\n      this.credsHandler = credsHandler;\n   }\n\n   @Override\n   public UserAndSessionCredentials getResult() {\n      try {\n         return builder.build();\n      } finally {\n         builder = UserAndSessionCredentials.builder();\n      }\n   }\n\n   private boolean inCreds;\n\n   private String arn;\n   private String id;\n\n   @Override\n   public void startElement(String url, String name, String qName, Attributes attributes) throws SAXException {\n      if (equalsOrSuffix(qName, \"Credentials\")) {\n         inCreds = true;\n      }\n      if (inCreds) {\n         credsHandler.startElement(url, name, qName, attributes);\n      }\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) {\n      if (inCreds) {\n         if (qName.equals(\"Credentials\")) {\n            inCreds = false;\n            builder.credentials(credsHandler.getResult());\n         } else {\n            credsHandler.endElement(uri, name, qName);\n         }\n      } else if (qName.equals(\"Arn\")) {\n         arn = currentOrNull(currentText);\n      } else if (qName.endsWith(\"Id\")) {// FederatedUserId or AssumedRoleId\n         id = currentOrNull(currentText);\n      } else if (qName.endsWith(\"User\")) {// FederatedUser or AssumedRoleUser\n         builder.user(User.fromIdAndArn(id, arn));\n         id = arn = null;\n      } else if (qName.equals(\"PackedPolicySize\")) {\n         builder.packedPolicySize(Integer.parseInt(currentOrNull(currentText)));\n      }\n      currentText.setLength(0);\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      if (inCreds) {\n         credsHandler.characters(ch, start, length);\n      } else {\n         currentText.append(ch, start, length);\n      }\n   }\n\n}\n"
  },
  {
    "path": "apis/sts/src/test/java/org/jclouds/aws/filters/FormSignerV2Test.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.filters;\n\nimport static jakarta.ws.rs.HttpMethod.GET;\nimport static org.jclouds.aws.reference.AWSConstants.PROPERTY_HEADER_TAG;\nimport static org.jclouds.providers.AnonymousProviderMetadata.forApiOnEndpoint;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.aws.filters.FormSigner.FormSignerV2;\nimport org.jclouds.aws.xml.SessionCredentialsHandlerTest;\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.IntegrationTestClient;\nimport org.jclouds.logging.config.NullLoggingModule;\nimport org.jclouds.rest.RequestSigner;\nimport org.jclouds.rest.internal.BaseRestApiTest.MockModule;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.net.HttpHeaders;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Injector;\nimport com.google.inject.Module;\nimport com.google.inject.name.Names;\n\n@Test(groups = \"unit\", singleThreaded = true, testName = \"FormSignerV2Test\")\npublic class FormSignerV2Test {\n   public static Injector injector(Credentials creds) {\n      return ContextBuilder\n            .newBuilder(forApiOnEndpoint(IntegrationTestClient.class, \"http://localhost\"))\n            .credentialsSupplier(Suppliers.<Credentials> ofInstance(creds)).apiVersion(\"apiVersion\")\n            .modules(ImmutableList.<Module> of(new MockModule(), new NullLoggingModule(), new AbstractModule() {\n               @Override\n               protected void configure() {\n                  bind(RequestSigner.class).to(FormSignerV2.class);\n                  bind(String.class).annotatedWith(Names.named(PROPERTY_HEADER_TAG)).toInstance(\"amz\");\n                  bind(String.class).annotatedWith(TimeStamp.class).toInstance(\"2009-11-08T15:54:08.897Z\");\n               }\n\n            })).buildInjector();\n   }\n\n   public static FormSignerV2 filter(Credentials creds) {\n      return injector(creds).getInstance(FormSignerV2.class);\n   }\n\n   public static FormSignerV2 staticCredentialsFilter = filter(new Credentials(\"identity\", \"credential\"));\n\n   HttpRequest request = HttpRequest.builder().method(GET)\n         .endpoint(\"http://localhost\")\n         .addHeader(HttpHeaders.HOST, \"localhost\")\n         .addFormParam(\"Action\", \"DescribeImages\")\n         .addFormParam(\"ImageId.1\", \"ami-2bb65342\").build();\n\n   @Test\n   void testAddsSecurityToken() {\n      HttpRequest filtered = filter(new SessionCredentialsHandlerTest().expected()).filter(request);\n      assertEquals(\n            filtered.getPayload().getRawContent(),\n            \"Action=DescribeImages&ImageId.1=ami-2bb65342&SecurityToken=AQoEXAMPLEH4aoAH0gNCAPyJxz4BlCFFxWNE1OPTgk5TthT&Signature=/8ReFVH1tvyNORsJb%2BSBieT9zvdqREQQr/olwmxC7VY%3D&SignatureMethod=HmacSHA256&SignatureVersion=2&Timestamp=2009-11-08T15%3A54%3A08.897Z&Version=apiVersion&AWSAccessKeyId=AKIAIOSFODNN7EXAMPLE\");\n   }\n\n   @Test\n   void testBuildCanonicalizedStringSetsVersion() {\n      HttpRequest filtered = staticCredentialsFilter.filter(request);\n      assertEquals(filtered.getPayload().getRawContent(),\n            \"Action=DescribeImages&ImageId.1=ami-2bb65342&Signature=ugnt4m2eHE7Ka/vXTr9EhKZq7bhxOfvW0y4pAEqF97w%3D&SignatureMethod=HmacSHA256&SignatureVersion=2&Timestamp=2009-11-08T15%3A54%3A08.897Z&Version=apiVersion&AWSAccessKeyId=identity\");\n   }\n\n   @Test\n   void testBuildCanonicalizedString() {\n      assertEquals(\n            staticCredentialsFilter.buildCanonicalizedString(new ImmutableMultimap.Builder<String, String>()\n                  .put(\"AWSAccessKeyId\", \"foo\").put(\"Action\", \"DescribeImages\").put(\"Expires\", \"2008-02-10T12:00:00Z\")\n                  .put(\"ImageId.1\", \"ami-2bb65342\").put(\"SignatureMethod\", \"HmacSHA256\").put(\"SignatureVersion\", \"2\")\n                  .put(\"Version\", \"2010-06-15\").build()),\n            \"AWSAccessKeyId=foo&Action=DescribeImages&Expires=2008-02-10T12%3A00%3A00Z&ImageId.1=ami-2bb65342&SignatureMethod=HmacSHA256&SignatureVersion=2&Version=2010-06-15\");\n   }\n}\n"
  },
  {
    "path": "apis/sts/src/test/java/org/jclouds/aws/filters/FormSignerV4LiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.filters;\n\nimport static java.util.concurrent.TimeUnit.MINUTES;\nimport static org.jclouds.sts.options.SessionCredentialsOptions.Builder.durationSeconds;\nimport static org.testng.Assert.assertEquals;\n\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\nimport java.util.TimeZone;\n\nimport jakarta.inject.Provider;\n\nimport org.jclouds.apis.BaseApiLiveTest;\nimport org.jclouds.aws.domain.SessionCredentials;\nimport org.jclouds.aws.filters.FormSignerV4.ServiceAndRegion;\nimport org.jclouds.aws.filters.FormSignerV4.ServiceAndRegion.AWSServiceAndRegion;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.ApiContext;\nimport org.jclouds.sts.STSApi;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"FormSignerV4LiveTest\")\npublic class FormSignerV4LiveTest extends BaseApiLiveTest<ApiContext<STSApi>> {\n\n   /** Example request, which hopefully the test user's account has access to! */\n   private final HttpRequest sampleRequest = HttpRequest.builder() //\n         .method(\"POST\") //\n         .endpoint(\"https://ec2.us-east-1.amazonaws.com/\") //\n         .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\") //\n         .addFormParam(\"Action\", \"DescribeRegions\") //\n         .addFormParam(\"Version\", \"2010-08-31\") //\n         .build();\n\n   /** Provides the expected iso8601 timestamp format for signature v4. */\n   private final Provider<String> timestamp = new Provider<String>() {\n      SimpleDateFormat iso8601 = new SimpleDateFormat(\"yyyyMMdd'T'HHmmss'Z'\");\n\n      @Override public String get() {\n         iso8601.setTimeZone(TimeZone.getTimeZone(\"GMT\"));\n         return iso8601.format(new Date());\n      }\n   };\n\n   /** Test how we parse the AWS service and region based on an endpoint. */\n   private final ServiceAndRegion serviceAndRegion = new AWSServiceAndRegion(sampleRequest.getEndpoint().toString());\n\n   public FormSignerV4LiveTest() {\n      provider = \"sts\";\n   }\n\n   public void signatureV4() {\n      Supplier<Credentials> accessAndSecretKey = Suppliers.ofInstance(new Credentials(identity, credential));\n\n      FormSignerV4 filter = new FormSignerV4(apiVersion, accessAndSecretKey, timestamp, serviceAndRegion);\n\n      HttpRequest request = filter.filter(sampleRequest);\n\n      assertEquals(api.utils().http().invoke(request).getStatusCode(), 200);\n   }\n\n   public void signatureV4_session() {\n      SessionCredentials creds = api.getApi().createTemporaryCredentials(durationSeconds(MINUTES.toSeconds(15)));\n      Supplier<Credentials> sessionToken = Suppliers.<Credentials>ofInstance(creds);\n\n      FormSignerV4 filter = new FormSignerV4(apiVersion, sessionToken, timestamp, serviceAndRegion);\n\n      HttpRequest request = filter.filter(sampleRequest);\n\n      assertEquals(api.utils().http().invoke(request).getStatusCode(), 200);\n   }\n}\n"
  },
  {
    "path": "apis/sts/src/test/java/org/jclouds/aws/filters/FormSignerV4Test.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.filters;\n\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.testng.Assert.assertEquals;\n\nimport jakarta.inject.Provider;\n\nimport org.jclouds.aws.domain.SessionCredentials;\nimport org.jclouds.aws.filters.FormSignerV4.ServiceAndRegion;\nimport org.jclouds.aws.xml.SessionCredentialsHandlerTest;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\n\n/**\n * Using samples from <a href=\"http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html\">Amazon\n * docs</a>\n */\n@Test\npublic class FormSignerV4Test {\n\n   String apiVersion = \"2010-05-08\";\n\n   Supplier<Credentials> accessAndSecretKey = Suppliers\n         .ofInstance(new Credentials(\"AKIAIOSFODNN7EXAMPLE\", \"wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY\"));\n\n   Provider<String> timestamp = new Provider<String>() {\n      @Override public String get() {\n         return \"20110909T233600Z\";\n      }\n   };\n\n   ServiceAndRegion serviceAndRegion = new ServiceAndRegion() {\n      @Override public String service() {\n         return \"iam\";\n      }\n\n      @Override public String region(String host) {\n         return \"us-east-1\";\n      }\n   };\n\n   public void signSampleRequest() {\n      HttpRequest request = HttpRequest.builder() //\n            .method(\"POST\") //\n            .endpoint(\"https://iam.amazonaws.com/\") //\n            .addHeader(\"Host\", \"iam.amazonaws.com\") //\n            .payload(\"Action=ListUsers&Version=2010-05-08\")\n            .build();\n\n      request.getPayload().getContentMetadata().setContentType(\"application/x-www-form-urlencoded; charset=utf-8\");\n\n      FormSignerV4 filter = new FormSignerV4(apiVersion, accessAndSecretKey, timestamp, serviceAndRegion);\n\n      HttpRequest filtered = filter.filter(request);\n\n      assertEquals(filtered.getFirstHeaderOrNull(\"X-Amz-Date\"), timestamp.get());\n\n      String sampleSignature = \"ced6826de92d2bdeed8f846f0bf508e8559e98e4b0199114b84c54174deb456c\";\n\n      assertThat(filtered.getFirstHeaderOrNull(\"Authorization\")).endsWith(\"Signature=\" + sampleSignature);\n   }\n\n   public void versionSampleRequest() {\n      HttpRequest request = HttpRequest.builder() //\n            .method(\"POST\") //\n            .endpoint(\"https://iam.amazonaws.com/\") //\n            .addHeader(\"Host\", \"iam.amazonaws.com\") //\n            .payload(\"Action=CoolVersionWordAction\")\n            .build();\n\n      request.getPayload().getContentMetadata().setContentType(\"application/x-www-form-urlencoded; charset=utf-8\");\n\n      FormSignerV4 filter = new FormSignerV4(apiVersion, accessAndSecretKey, timestamp, serviceAndRegion);\n\n      HttpRequest filtered = filter.filter(request);\n\n      assertEquals(filtered.getFirstHeaderOrNull(\"X-Amz-Date\"), timestamp.get());\n\n      assertThat(filtered.getPayload().getRawContent().toString().contains(\"&Version=2010-05-08\"));\n   }\n\n   public void sessionTokenRequest() {\n      HttpRequest request = HttpRequest.builder() //\n            .method(\"POST\") //\n            .endpoint(\"https://iam.amazonaws.com/\") //\n            .addHeader(\"Host\", \"iam.amazonaws.com\") //\n            .payload(\"Action=ListUsers&Version=2010-05-08\").build();\n\n      request.getPayload().getContentMetadata().setContentType(\"application/x-www-form-urlencoded; charset=utf-8\");\n\n      SessionCredentials sessionCredentials = new SessionCredentialsHandlerTest().expected();\n\n      FormSignerV4 filter = new FormSignerV4(apiVersion, Suppliers.<Credentials>ofInstance(sessionCredentials),\n            timestamp, serviceAndRegion);\n\n      HttpRequest filtered = filter.filter(request);\n\n      assertEquals(filtered.getFirstHeaderOrNull(\"X-Amz-Date\"), timestamp.get());\n      assertEquals(filtered.getFirstHeaderOrNull(\"X-Amz-Security-Token\"), sessionCredentials.getSessionToken());\n   }\n}\n"
  },
  {
    "path": "apis/sts/src/test/java/org/jclouds/aws/handlers/AWSClientErrorRetryHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.handlers;\nimport static jakarta.ws.rs.HttpMethod.PUT;\nimport static jakarta.ws.rs.core.Response.Status.CONFLICT;\nimport static jakarta.ws.rs.core.Response.Status.UNAUTHORIZED;\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\n\nimport org.jclouds.aws.domain.AWSError;\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.handlers.BackoffLimitedRetryHandler;\nimport org.jclouds.io.Payloads;\nimport org.testng.annotations.DataProvider;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code AWSClientErrorRetryHandler}\n */\n@Test(groups = \"unit\", testName = \"AWSClientErrorRetryHandlerTest\")\npublic class AWSClientErrorRetryHandlerTest {\n   @Test\n   public void test401DoesNotRetry() {\n\n      AWSUtils utils = createMock(AWSUtils.class);\n      BackoffLimitedRetryHandler backoffLimitedRetryHandler = createMock(BackoffLimitedRetryHandler.class);\n      HttpCommand command = createMock(HttpCommand.class);\n\n      replay(utils, backoffLimitedRetryHandler, command);\n\n      AWSClientErrorRetryHandler retry = new AWSClientErrorRetryHandler(utils, backoffLimitedRetryHandler,\n            ImmutableSet.<String> of());\n\n      assert !retry.shouldRetryRequest(command, HttpResponse.builder().statusCode(UNAUTHORIZED.getStatusCode()).build());\n\n      verify(utils, backoffLimitedRetryHandler, command);\n\n   }\n\n   @DataProvider(name = \"codes\")\n   public Object[][] createData() {\n      return new Object[][] { { \"RequestTimeout\" }, { \"OperationAborted\" }, { \"SignatureDoesNotMatch\" } };\n   }\n\n   @Test(dataProvider = \"codes\")\n   public void test409DoesBackoffAndRetryForCode(String code) {\n\n      AWSUtils utils = createMock(AWSUtils.class);\n      BackoffLimitedRetryHandler backoffLimitedRetryHandler = createMock(BackoffLimitedRetryHandler.class);\n      HttpCommand command = createMock(HttpCommand.class);\n\n      HttpRequest putBucket = HttpRequest.builder().method(PUT)\n            .endpoint(\"https://adriancole-blobstore113.s3.amazonaws.com/\").build();\n\n      HttpResponse operationAborted = HttpResponse.builder().statusCode(CONFLICT.getStatusCode())\n            .payload(Payloads.newStringPayload(String.format(\"<Error><Code>%s</Code></Error>\", code))).build();\n\n      expect(command.getCurrentRequest()).andReturn(putBucket);\n\n      AWSError error = new AWSError();\n      error.setCode(code);\n\n      expect(utils.parseAWSErrorFromContent(putBucket, operationAborted)).andReturn(error);\n\n      expect(backoffLimitedRetryHandler.shouldRetryRequest(command, operationAborted)).andReturn(Boolean.TRUE);\n\n      replay(utils, backoffLimitedRetryHandler, command);\n\n      AWSClientErrorRetryHandler retry = new AWSClientErrorRetryHandler(utils, backoffLimitedRetryHandler,\n            ImmutableSet.<String> of(\"RequestTimeout\", \"OperationAborted\", \"SignatureDoesNotMatch\"));\n\n      assert retry.shouldRetryRequest(command, operationAborted);\n\n      verify(utils, backoffLimitedRetryHandler, command);\n\n   }\n\n}\n"
  },
  {
    "path": "apis/sts/src/test/java/org/jclouds/aws/handlers/AWSServerErrorRetryHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.handlers;\nimport static jakarta.ws.rs.HttpMethod.PUT;\nimport static jakarta.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR;\nimport static jakarta.ws.rs.core.Response.Status.SERVICE_UNAVAILABLE;\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.concurrent.atomic.AtomicInteger;\n\nimport org.easymock.IAnswer;\n\nimport org.jclouds.aws.domain.AWSError;\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.io.Payloads;\nimport org.testng.annotations.DataProvider;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code AWSServerErrorRetryHandler}\n */\n@Test(groups = \"unit\", testName = \"AWSServerErrorRetryHandlerTest\")\npublic class AWSServerErrorRetryHandlerTest {\n   @Test\n   public void testUnknown500DoesNotRetry() {\n\n      AWSUtils utils = createMock(AWSUtils.class);\n      HttpCommand command = createMock(HttpCommand.class);\n\n      replay(utils, command);\n\n      AWSServerErrorRetryHandler retry = new AWSServerErrorRetryHandler(utils,\n            ImmutableSet.<String> of());\n\n      assertFalse(retry.shouldRetryRequest(command, HttpResponse.builder().statusCode(INTERNAL_SERVER_ERROR.getStatusCode()).build()));\n\n      verify(utils, command);\n\n   }\n\n   @DataProvider(name = \"codes\")\n   public Object[][] createData() {\n      return new Object[][] {\n              { SERVICE_UNAVAILABLE.getStatusCode(), \"RequestLimitExceeded\" },\n              { INTERNAL_SERVER_ERROR.getStatusCode(), \"InternalError\" }\n      };\n   }\n\n   @Test(dataProvider = \"codes\")\n   public void testDoesBackoffAndRetryForHttpStatusCodeAndErrorCode(int httpStatusCode, String errorCode) {\n\n      AWSUtils utils = createMock(AWSUtils.class);\n      HttpCommand command = createMock(HttpCommand.class);\n\n      HttpRequest putBucket = HttpRequest.builder().method(PUT)\n            .endpoint(\"https://adriancole-blobstore113.s3.amazonaws.com/\").build();\n\n      HttpResponse response = HttpResponse.builder().statusCode(httpStatusCode)\n            .payload(Payloads.newStringPayload(String.format(\"<Error><Code>%s</Code></Error>\", errorCode))).build();\n\n      expect(command.getCurrentRequest()).andReturn(putBucket);\n      final AtomicInteger counter = new AtomicInteger();\n      expect(command.incrementFailureCount()).andAnswer(new IAnswer<Integer>() {\n         @Override\n         public Integer answer() throws Throwable {\n            return counter.incrementAndGet();\n         }\n      }).anyTimes();\n      expect(command.isReplayable()).andReturn(true).anyTimes();\n      expect(command.getFailureCount()).andAnswer(new IAnswer<Integer>() {\n         @Override\n         public Integer answer() throws Throwable {\n            return counter.get();\n         }\n      }).anyTimes();\n\n      AWSError error = new AWSError();\n      error.setCode(errorCode);\n\n      expect(utils.parseAWSErrorFromContent(putBucket, response)).andReturn(error);\n\n      replay(utils, command);\n\n      AWSServerErrorRetryHandler retry = new AWSServerErrorRetryHandler(utils,\n            ImmutableSet.of(\"RequestLimitExceeded\", \"InternalError\"));\n\n      assert retry.shouldRetryRequest(command, response);\n\n      verify(utils, command);\n\n   }\n\n   @Test\n   public void test504DoesRetry() {\n      AWSUtils utils = createMock(AWSUtils.class);\n      HttpCommand command = createMock(HttpCommand.class);\n      expect(command.getFailureCount()).andReturn(1).anyTimes();\n      expect(command.incrementFailureCount()).andReturn(1);\n      expect(command.isReplayable()).andReturn(true);\n\n      replay(utils, command);\n\n      AWSServerErrorRetryHandler retry = new AWSServerErrorRetryHandler(utils,\n            ImmutableSet.<String> of());\n\n      assertTrue(retry.shouldRetryRequest(command, HttpResponse.builder().statusCode(504).build()));\n\n      verify(utils, command);\n   }\n}\n"
  },
  {
    "path": "apis/sts/src/test/java/org/jclouds/aws/handlers/ParseAWSErrorFromXmlContentTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.handlers;\nimport static jakarta.ws.rs.HttpMethod.GET;\nimport static jakarta.ws.rs.HttpMethod.POST;\nimport static jakarta.ws.rs.HttpMethod.PUT;\nimport static jakarta.ws.rs.core.MediaType.TEXT_PLAIN;\nimport static jakarta.ws.rs.core.Response.Status.BAD_REQUEST;\nimport static jakarta.ws.rs.core.Response.Status.CONFLICT;\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.reportMatcher;\nimport static org.easymock.EasyMock.verify;\nimport static org.jclouds.aws.reference.AWSConstants.PROPERTY_HEADER_TAG;\n\nimport java.net.URI;\n\nimport org.easymock.IArgumentMatcher;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.config.SaxParserModule;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.InsufficientResourcesException;\nimport org.jclouds.rest.RequestSigner;\nimport org.jclouds.rest.ResourceAlreadyExistsException;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.name.Names;\n\n@Test(groups = { \"unit\" })\npublic class ParseAWSErrorFromXmlContentTest {\n\n   @Test\n   public void test400WithNotFoundSetsResourceNotFoundException() {\n      assertCodeMakes(GET, URI.create(\"https://amazonaws.com/foo\"), BAD_REQUEST.getStatusCode(), \"\",\n               \"<Error><Code>Monster.NotFound</Code></Error>\", ResourceNotFoundException.class);\n   }\n   \n   @Test\n   public void test400WithCloudBridgeNotFoundSetsResourceNotFoundException() {\n      assertCodeMakes(POST, URI.create(\"https://api.greenqloud.com/\"), BAD_REQUEST.getStatusCode(), \"\",\n               \"<Error><Code>Client.InvalidInstanceID.NotFound</Code></Error>\", ResourceNotFoundException.class);\n   }\n   \n   @Test\n   public void test400WithInvalidIdIllegalArgumentException() {\n      assertCodeMakes(POST, URI.create(\"https://ec2.us-east-1.amazonaws.com\"), BAD_REQUEST.getStatusCode(), \"HTTP/1.1 400\", \"\",\n               \"Invalid id: \\\"asdaasdsa\\\" (expecting \\\"ami-...\\\")\", IllegalArgumentException.class);\n   }\n\n   @Test\n   public void test400WithLoadBalancerNotFoundSetsResourceNotFoundException() {\n      assertCodeMakes(GET, URI.create(\"https://amazonaws.com/foo\"), BAD_REQUEST.getStatusCode(), \"\",\n               \"<Error><Code>LoadBalancerNotFound</Code></Error>\", ResourceNotFoundException.class);\n   }\n   \n   @Test\n   public void test400WithSecurityGroupNotFoundForProjectSetsResourceNotFoundException() {\n      assertCodeMakes(GET, URI.create(\"https://amazonaws.com/foo\"), BAD_REQUEST.getStatusCode(), \"\",\n               \"<Error><Code>SecurityGroupNotFoundForProject</Code></Error>\", ResourceNotFoundException.class);\n   }\n\n   @Test\n   public void test400WithUnsupportedCodeMakesUnsupportedOperationException() {\n      assertCodeMakes(POST, URI.create(\"https://ec2.us-west-1.amazonaws.com/\"), BAD_REQUEST.getStatusCode(), \"\",\n               \"<Error><Code>UnsupportedOperation</Code></Error>\", UnsupportedOperationException.class);\n   }\n   \n   @Test\n   public void test400WithAddressLimitExceededCodeMakesInsufficientResourcesException() {\n      assertCodeMakes(\n               POST,\n               URI.create(\"https://ec2.us-east-1.amazonaws.com/\"),\n               BAD_REQUEST.getStatusCode(),\n               \"\",\n               \"<Response><Errors><Error><Code>AddressLimitExceeded</Code><Message>Too many addresses allocated</Message></Error></Errors><RequestID>c14f531a-cc35-4b48-8149-2655c7e6dc76</RequestID></Response>\",\n               InsufficientResourcesException.class);\n   }\n\n   @Test\n   public void test400WithTooManyBucketsCodeMakesInsufficientResourcesException() {\n      assertCodeMakes(\n               POST,\n               URI.create(\"https://ec2.us-east-1.amazonaws.com/\"),\n               BAD_REQUEST.getStatusCode(),\n               \"\",\n               \"<Response><Errors><Error><Code>TooManyBuckets</Code><Message>You have attempted to create more buckets than allowed</Message></Error></Errors><RequestID>c14f531a-cc35-4b48-8149-2655c7e6dc76</RequestID></Response>\",\n               InsufficientResourcesException.class);\n   }\n\n   @Test\n   public void test409WithBucketAlreadyExistsMakesResourceAlreadyExistsException() {\n      assertCodeMakes(\n               POST,\n               URI.create(\"https://ec2.us-east-1.amazonaws.com/\"),\n               CONFLICT.getStatusCode(),\n               \"\",\n               \"<Response><Errors><Error>\" +\n               \"<Code>BucketAlreadyExists</Code>\" +\n               \"<Message>The requested bucket name is not available.\" +\n               \" The bucket namespace is shared by all users of the system.\" +\n               \" Please select a different name and try again.</Message>\" +\n               \"</Error></Errors><RequestID>c14f531a-cc35-4b48-8149-2655c7e6dc76</RequestID></Response>\",\n               ResourceAlreadyExistsException.class);\n   }\n\n   @Test\n   public void test400WithInUseCodeSetsIllegalStateException() {\n      assertCodeMakes(GET, URI.create(\"https://amazonaws.com/foo\"), BAD_REQUEST.getStatusCode(), \"\",\n               \"<Error><Code>InvalidPlacementGroup.InUse</Code></Error>\", IllegalStateException.class);\n   }\n\n   @Test\n   public void test400WithUnknownSetsResourceNotFoundException() {\n      assertCodeMakes(GET, URI.create(\"https://amazonaws.com/foo\"), BAD_REQUEST.getStatusCode(), \"\",\n               \"<Error><Code>InvalidPlacementGroup.Unknown</Code></Error>\", ResourceNotFoundException.class);\n   }\n\n   @Test\n   public void test400WithIncorrectStateSetsIllegalStateException() {\n      assertCodeMakes(GET, URI.create(\"https://amazonaws.com/foo\"), BAD_REQUEST.getStatusCode(), \"\",\n               \"<Error><Code>IncorrectState</Code></Error>\", IllegalStateException.class);\n   }\n\n   @Test\n   public void test400WithInUseSetsIllegalStateException() {\n      assertCodeMakes(GET, URI.create(\"https://amazonaws.com/foo\"), BAD_REQUEST.getStatusCode(), \"\", TEXT_PLAIN,\n               \"The placement group 'jclouds#adriancoleec2cccluster#us-east-1' is in use and may not be deleted.\",\n               IllegalStateException.class);\n   }\n\n   @Test\n   public void test409SetsIllegalStateException() {\n      assertCodeMakes(\n               PUT,\n               URI.create(\"https://adriancole-blobstore011.s3.amazonaws.com/\"),\n               CONFLICT.getStatusCode(),\n               \"\",\n               \"<Error><Code>OperationAborted</Code><Message>A conflicting conditional operation is currently in progress against this resource. Please try again.</Message><RequestId>F716E81C3D814E59</RequestId><HostId>SDprHxWzG/YXzanVnV7VTz/wP+6fRt1dS+q00kH1rz248YOOSddkFiTXF04XtqNO</HostId></Error>\",\n               IllegalStateException.class);\n   }\n\n   @Test\n   public void test400WithInvalidGroupDuplicateIllegalStateException() {\n      assertCodeMakes(GET, URI.create(\"https://amazonaws.com/foo\"), BAD_REQUEST.getStatusCode(), BAD_REQUEST.getReasonPhrase(), \"application/unknown\",\n               \"<Error><Code>InvalidGroup.Duplicate</Code></Error>\", IllegalStateException.class);\n   }\n\n   @Test\n   public void test400WithInvalidKeyPairGroupDuplicateIllegalStateException() {\n      assertCodeMakes(GET, URI.create(\"https://amazonaws.com/foo\"), BAD_REQUEST.getStatusCode(), BAD_REQUEST.getReasonPhrase(), \"application/unknown\",\n               \"<Error><Code>InvalidKeyPair.Duplicate</Code></Error>\", IllegalStateException.class);\n   }\n\n   @Test\n   public void test400WithTextPlainIllegalArgumentException() {\n      assertCodeMakes(GET, URI.create(\"https://amazonaws.com/foo\"), BAD_REQUEST.getStatusCode(), BAD_REQUEST.getReasonPhrase(), TEXT_PLAIN,\n               \"Failure: 400 Bad Request\\nFailed to bind the following fields\\nMonitoring.Enabled = true\\n\\n\\n\",\n               IllegalArgumentException.class);\n   }\n\n   @Test\n   public void test400WithGroupAlreadyExistsEucalyptusIllegalStateException() {\n      assertCodeMakes(\n               GET,\n               URI.create(\"https://amazonaws.com/foo\"),\n               BAD_REQUEST.getStatusCode(),\n               \"\",\n               \"<?xml version=\\\"1.0\\\"?><Response><Errors><Error><Code>Groups</Code><Message>\\nError adding network group: group named jclouds#eucrun#Eucalyptus already exists\\nError adding network group: group named jclouds#eucrun#Eucalyptus already exists</Message></Error></Errors><RequestID>e0133975-3bc5-456d-9753-1d61b27e07e9</RequestID></Response>\",\n               IllegalStateException.class);\n   }\n\n   @Test\n   public void test400WithAuthFailureSetsAuthorizationException() {\n      assertCodeMakes(GET, URI.create(\"https://amazonaws.com/foo\"), BAD_REQUEST.getStatusCode(), \"\",\n               \"<Error><Code>AuthFailure</Code></Error>\", AuthorizationException.class);\n   }\n\n   @Test\n   public void test400WithCloudBridgeAuthFailureSetsAuthorizationException() {\n      assertCodeMakes(POST, URI.create(\"https://api.greenqloud.com/\"), BAD_REQUEST.getStatusCode(), \"\",\n               \"<Error><Code>Client.AuthFailure</Code></Error>\", AuthorizationException.class);\n   }\n\n   private void assertCodeMakes(String method, URI uri, int statusCode, String message, String content,\n            Class<? extends Exception> expected) {\n      assertCodeMakes(method, uri, statusCode, message, \"text/xml\", content, expected);\n   }\n\n   private void assertCodeMakes(String method, URI uri, int statusCode, String message, String contentType,\n            String content, Class<? extends Exception> expected) {\n\n      ParseAWSErrorFromXmlContent function = Guice.createInjector(new SaxParserModule(), new AbstractModule() {\n\n         @Override\n         protected void configure() {\n            bind(RequestSigner.class).toInstance(createMock(RequestSigner.class));\n            bindConstant().annotatedWith(Names.named(PROPERTY_HEADER_TAG)).to(\"amz\");\n         }\n\n      }).getInstance(ParseAWSErrorFromXmlContent.class);\n\n      HttpCommand command = createMock(HttpCommand.class);\n      HttpRequest request = HttpRequest.builder().method(method).endpoint(uri).build();\n      HttpResponse response = HttpResponse.builder().statusCode(statusCode).message(message).payload(content).build();\n      response.getPayload().getContentMetadata().setContentType(contentType);\n\n      expect(command.getCurrentRequest()).andReturn(request).atLeastOnce();\n      command.setException(classEq(expected));\n\n      replay(command);\n\n      function.handleError(command, response);\n\n      verify(command);\n   }\n\n   public static Exception classEq(final Class<? extends Exception> in) {\n      reportMatcher(new IArgumentMatcher() {\n\n         @Override\n         public void appendTo(StringBuffer buffer) {\n            buffer.append(\"classEq(\");\n            buffer.append(in);\n            buffer.append(\")\");\n         }\n\n         @Override\n         public boolean matches(Object arg) {\n            return arg.getClass() == in;\n         }\n\n      });\n      return null;\n   }\n\n}\n"
  },
  {
    "path": "apis/sts/src/test/java/org/jclouds/aws/util/AWSUtilsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.util;\nimport static jakarta.ws.rs.core.MediaType.TEXT_PLAIN;\nimport static jakarta.ws.rs.core.Response.Status.BAD_REQUEST;\nimport static jakarta.ws.rs.core.Response.Status.NOT_FOUND;\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\n\nimport java.io.IOException;\nimport java.io.InputStream;\n\nimport jakarta.inject.Provider;\n\nimport org.jclouds.aws.domain.AWSError;\nimport org.jclouds.aws.filters.FormSignerV2Test;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.io.payloads.StringPayload;\nimport org.jclouds.rest.RequestSigner;\nimport org.testng.annotations.AfterTest;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests parsing of S3 responses\n */\n@Test(singleThreaded = true, groups = \"unit\", testName = \"AWSUtilsTest\")\npublic class AWSUtilsTest {\n   AWSUtils utils = null;\n   private HttpCommand command;\n\n   @BeforeTest\n   protected void setUpInjector() throws IOException {\n\n      utils = FormSignerV2Test.injector(new Credentials(\"identity\", \"credential\")).getInstance(AWSUtils.class);\n\n      command = createMock(HttpCommand.class);\n      expect(command.getCurrentRequest()).andReturn(createMock(HttpRequest.class)).atLeastOnce();\n      replay(command);\n   }\n\n   @AfterTest\n   protected void tearDownInjector() {\n      utils = null;\n   }\n\n   HttpResponse response(InputStream content) {\n      HttpResponse response = HttpResponse.builder().statusCode(BAD_REQUEST.getStatusCode())\n                                          .message(\"boa\")\n                                          .payload(content)\n                                          .addHeader(\"x-amz-request-id\", \"requestid\")\n                                          .addHeader(\"x-amz-id-2\", \"requesttoken\").build();\n      response.getPayload().getContentMetadata().setContentType(\"text/xml\");\n      return response;\n   }\n   \n   /**\n    * HEAD requests don't have a payload\n    */\n   @Test\n   public void testNoExceptionWhenNoPayload() {\n      HttpResponse response = HttpResponse.builder().statusCode(BAD_REQUEST.getStatusCode()).build();\n      assertNull(utils.parseAWSErrorFromContent(command.getCurrentRequest(), response));\n   }\n   \n   /**\n    * clones or proxies can mess up the error message.\n    */\n   @Test\n   public void testNoExceptionParsingTextPlain() {\n      HttpResponse response = HttpResponse.builder().statusCode(BAD_REQUEST.getStatusCode()).payload(\"foo bar\").build();\n      response.getPayload().getContentMetadata().setContentType(TEXT_PLAIN);\n      assertNull(utils.parseAWSErrorFromContent(command.getCurrentRequest(), response));\n   }\n\n   /**\n    * Do not attempt to parse empty payload.\n    */\n   @Test\n   public void testNoExceptionEmptyPayload() {\n      RequestSigner requestSigner = createMock(RequestSigner.class);\n      ParseSax.Factory factory = createMock(ParseSax.Factory.class);\n      Provider provider = createMock(Provider.class);\n      // these all will throw UnexpectedInvocationEx if touched\n      replay(requestSigner, factory, provider);\n\n      AWSUtils riggedUtil = new AWSUtils(\n          \"ignore\",\n          requestSigner,\n          factory,\n          provider\n      );\n\n      HttpResponse response = HttpResponse.builder().statusCode(NOT_FOUND.getStatusCode()).payload(new StringPayload(\"\")).build();\n      response.getPayload().getContentMetadata().setContentType(\"application/unknown\");\n      assertNull(riggedUtil.parseAWSErrorFromContent(command.getCurrentRequest(), response));\n   }\n\n   @Test\n   public void testParseAWSErrorFromContentHttpCommandHttpResponseInputStream() {\n      AWSError error = utils.parseAWSErrorFromContent(command.getCurrentRequest(), response(getClass()\n            .getResourceAsStream(\"/error.xml\")));\n      assertEquals(error.getCode(), \"NoSuchKey\");\n      assertEquals(error.getMessage(), \"The resource you requested does not exist\");\n      assertEquals(error.getRequestToken(), \"requesttoken\");\n      assertEquals(error.getRequestId(), \"4442587FB7D0A2F9\");\n      assertEquals(error.getDetails().get(\"Resource\"), \"/mybucket/myfoto.jpg\");\n   }\n\n   @Test\n   public void testValidateBucketName() {\n      // TODO\n   }\n}\n"
  },
  {
    "path": "apis/sts/src/test/java/org/jclouds/aws/xml/ErrorHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.xml;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.aws.domain.AWSError;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code ErrorHandler}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"ErrorHandlerTest\")\npublic class ErrorHandlerTest extends BaseHandlerTest {\n   public static final String errorFromAmazonIfYouDontRemoveTransferEncodingHeader = \"<Error><Code>NotImplemented</Code><Message>A header you provided implies functionality that is not implemented</Message><Header>Transfer-Encoding</Header><RequestId>7C59925D75D15561</RequestId><HostId>fbskVU51OZJg2yZS/wNIxoE2PmCf0ZqFd0iH6Vrzw0uKG3KmokswBytL/Bfp/GWb</HostId></Error>\";\n\n   ParseSax<AWSError> createParser() {\n      ParseSax<AWSError> parser = factory.create(injector.getInstance(ErrorHandler.class));\n      return parser;\n   }\n\n   @Test\n   public void testErrorFromAmazonIfYouDontRemoveTransferEncodingHeader() throws HttpException {\n      ParseSax<AWSError> parser = createParser();\n      AWSError error = parser.parse(Strings2.toInputStream(errorFromAmazonIfYouDontRemoveTransferEncodingHeader));\n      assertEquals(error.getCode(), \"NotImplemented\");\n      assertEquals(error.getMessage(), \"A header you provided implies functionality that is not implemented\");\n      assertEquals(error.getDetails().get(\"Header\"), \"Transfer-Encoding\");\n      assertEquals(error.getDetails().get(\"HostId\"), \"fbskVU51OZJg2yZS/wNIxoE2PmCf0ZqFd0iH6Vrzw0uKG3KmokswBytL/Bfp/GWb\");\n   }\n\n   @Test\n   public void testErrorFromEucalyptusWhenGroupAlreadyExists() throws HttpException {\n      ParseSax<AWSError> parser = createParser();\n      AWSError error = parser\n               .parse(Strings2\n                        .toInputStream(\"<?xml version=\\\"1.0\\\"?><Response><Errors><Error><Code>Groups</Code><Message>\\nError adding network group: group named jclouds#eucrun#Eucalyptus already exists\\nError adding network group: group named jclouds#eucrun#Eucalyptus already exists</Message></Error></Errors><RequestID>e0133975-3bc5-456d-9753-1d61b27e07e9</RequestID></Response>\"));\n      assertEquals(error.getCode(), \"Groups\");\n      assertEquals(\n               error.getMessage(),\n               \"Error adding network group: group named jclouds#eucrun#Eucalyptus already exists\\nError adding network group: group named jclouds#eucrun#Eucalyptus already exists\");\n   }\n\n   public static final String badRequestWhenSourceIsDestBucketOnCopy400 = \"<Error><Code>InvalidRequest</Code><Message>The Source and Destination may not be the same when the MetadataDirective is Copy.</Message><RequestId>54C77CAF4D42474B</RequestId><HostId>SJecknEUUUx88/65VAKbCdKSOCkpuVTeu7ZG9in9x9NTNglGnoxdbALCfS4k/DUZ</HostId></Error>\";\n   public static final String noSuchSourceKeyOrBucketOnCopy404 = \"<Error><Code>NoSuchKey</Code><Message>The specified key does not exist.</Message><Key>null</Key><RequestId>9CCDF1DACA78B36F</RequestId><HostId>63cqk9YsTFBVfBfks840JVGsepPEdQM42mU+r7HN35sF4Nk5xAcWDEUPaQpK2eFU</HostId></Error>\";\n   public static final String noSuchDestinationBucketOnCopy404 = \"<Error><Code>NoSuchBucket</Code><Message>The specified bucketName does not exist</Message><BucketName>copydestination</BucketName><RequestId>4F0CF319C5535975</RequestId><HostId>hdZyHOm7VK+JI2UCdye3d6TVkKhRBIoWflldXVDTKbgipYlamy8HgPBzHrUAVQNJ</HostId></Error>\";\n   public static final String badSign403 = \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\"\n            + \"<Error><Code>SignatureDoesNotMatch</Code><Message>The operation signature we calculated does not match the signature you provided. Check your key and signing method.</Message><StringToSignBytes>47 45 54 0a 0a 0a 54 68 75 2c 20 31 39 20 4d 61 72 20 32 30 30 39 20 31 37 3a 34 38 3a 30 31 20 47 4d 54 0a 2f 61 64 72 69 61 6e 63 6f 6c 65 2e 73 33 2e 61 6d 61 7a 6f 6e 73 33 74 65 73 74 2e 66 69 6c 65 74 65 73 74 73 66 6f 72 61 64 72 69 61 6e 2f 66 69 6c 65</StringToSignBytes><RequestId>514AA22EB75A6E42</RequestId><HostId>H5nqnZkGjuKvB+seutvx5hnp1P+WAuC9c3Y7MdQCcYDr1TGwNX/mt+FHstK0pVld</HostId><SignatureProvided>Qm6Wss7e5e/eNXV50AxChH+xkLI=</SignatureProvided><StringToSign>GET\\n\"\n            + \"\\n\"\n            + \"\\n\"\n            + \"Thu, 19 Mar 2009 17:48:01 GMT\\n\"\n            + \"/adriancole.s3.amazons3test.filetestsforadrian/file</StringToSign><AWSAccessKeyId>0101100101001001</AWSAccessKeyId></Error>\";\n   public static final String amazonHadAnError500 = \"<Error><Code>InternalError</Code><Message>We encountered an internal error. Please try again.</Message><RequestId>EF6FA7A639CAFF15</RequestId><HostId>tBkX23mIeq2riHsNw2YShupMlZ9+iy3V/uN+lRhqCR4qHTE07ujFeyAUPTowvuH/</HostId></Error>\";\n\n}\n"
  },
  {
    "path": "apis/sts/src/test/java/org/jclouds/aws/xml/SessionCredentialsHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.xml;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.aws.domain.SessionCredentials;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.testng.annotations.Test;\n\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"SessionCredentialsHandlerTest\")\npublic class SessionCredentialsHandlerTest extends BaseHandlerTest {\n\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/credentials.xml\");\n\n      SessionCredentials expected = expected();\n\n      SessionCredentialsHandler handler = injector.getInstance(SessionCredentialsHandler.class);\n      SessionCredentials result = factory.create(handler).parse(is);\n\n      assertEquals(result, expected);\n      assertEquals(result.getAccessKeyId(), expected.getAccessKeyId());\n      assertEquals(result.getSecretAccessKey(), expected.getSecretAccessKey());\n      assertEquals(result.getSessionToken(), expected.getSessionToken());\n      assertEquals(result.getExpiration(), expected.getExpiration());\n   }\n\n   public SessionCredentials expected() {\n      return SessionCredentials.builder()\n            .accessKeyId(\"AKIAIOSFODNN7EXAMPLE\")\n            .secretAccessKey(\"wJalrXUtnFEMI/K7MDENG/bPxRfiCYzEXAMPLEKEY\")\n            .sessionToken(\"AQoEXAMPLEH4aoAH0gNCAPyJxz4BlCFFxWNE1OPTgk5TthT\")\n            .expiration(new SimpleDateFormatDateService().iso8601DateParse(\"2011-07-11T19:55:29.611Z\")).build();\n   }\n}\n"
  },
  {
    "path": "apis/sts/src/test/java/org/jclouds/sts/STSApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sts;\nimport static com.google.common.net.HttpHeaders.HOST;\nimport static jakarta.ws.rs.HttpMethod.POST;\nimport static jakarta.ws.rs.core.Response.Status.OK;\nimport static org.jclouds.sts.options.AssumeRoleOptions.Builder.externalId;\nimport static org.jclouds.sts.options.FederatedUserOptions.Builder.policy;\nimport static org.jclouds.sts.options.SessionCredentialsOptions.Builder.serialNumber;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.concurrent.TimeUnit;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.sts.internal.BaseSTSApiExpectTest;\nimport org.jclouds.sts.parse.AssumeRoleResponseTest;\nimport org.jclouds.sts.parse.GetFederationTokenResponseTest;\nimport org.jclouds.sts.parse.GetSessionTokenResponseTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"STSApiExpectTest\")\npublic class STSApiExpectTest extends BaseSTSApiExpectTest {\n\n   HttpRequest createTemporaryCredentials = HttpRequest.builder().method(POST)\n         .endpoint(\"https://sts.amazonaws.com/\")\n         .addHeader(HOST, \"sts.amazonaws.com\")\n         .addFormParam(\"Action\", \"GetSessionToken\")\n         .addFormParam(\"Signature\", \"ntC+PKAcmYTJ5Py5tjICG4KX5y00Pl2L0XJrLbSgLEs=\")\n         .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n         .addFormParam(\"SignatureVersion\", \"2\")\n         .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n         .addFormParam(\"Version\", \"2011-06-15\")\n         .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   HttpResponse createTemporaryCredentialsResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/session_token.xml\", \"text/xml\")).build();\n\n   public void testCreateTemporaryCredentialsWhenResponseIs2xx() {\n\n      STSApi apiWhenWithOptionsExist = requestSendsResponse(createTemporaryCredentials, createTemporaryCredentialsResponse);\n\n      assertEquals(\n            apiWhenWithOptionsExist.createTemporaryCredentials().toString(),\n            new GetSessionTokenResponseTest().expected().toString());\n   }\n\n   HttpRequest createTemporaryCredentialsWithOptions = HttpRequest.builder().method(POST)\n         .endpoint(\"https://sts.amazonaws.com/\")\n         .addHeader(HOST, \"sts.amazonaws.com\")\n         .addFormParam(\"Action\", \"GetSessionToken\")\n         .addFormParam(\"DurationSeconds\", \"900\")\n         .addFormParam(\"SerialNumber\", \"YourMFADeviceSerialNumber\")\n         .addFormParam(\"Signature\", \"e4HEkfKrw7EuLEQhe4/lK1l7ZmaynO3snsIMU/cdarI=\")\n         .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n         .addFormParam(\"SignatureVersion\", \"2\")\n         .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n         .addFormParam(\"TokenCode\", \"1234\")\n         .addFormParam(\"Version\", \"2011-06-15\")\n         .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testCreateTemporaryCredentialsWithOptionsWhenResponseIs2xx() {\n\n      STSApi apiWhenWithOptionsExist = requestSendsResponse(createTemporaryCredentialsWithOptions, createTemporaryCredentialsResponse);\n\n      assertEquals(\n            apiWhenWithOptionsExist.createTemporaryCredentials(\n                  serialNumber(\"YourMFADeviceSerialNumber\").tokenCode(\"1234\").durationSeconds(TimeUnit.MINUTES.toSeconds(15))).toString(),\n            new GetSessionTokenResponseTest().expected().toString());\n   }\n\n   HttpRequest assumeRole = HttpRequest.builder().method(POST)\n         .endpoint(\"https://sts.amazonaws.com/\")\n         .addHeader(HOST, \"sts.amazonaws.com\")\n         .addFormParam(\"Action\", \"AssumeRole\")\n         .addFormParam(\"RoleArn\", \"arn:aws:iam::123456789012:role/demo\")\n         .addFormParam(\"RoleSessionName\", \"Bob\")\n         .addFormParam(\"Signature\", \"0G1+6GX4cSU9Tjf2SyQ9oW5ivFri4BQPif/24FoRiWY=\")\n         .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n         .addFormParam(\"SignatureVersion\", \"2\")\n         .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n         .addFormParam(\"Version\", \"2011-06-15\")\n         .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   HttpResponse assumeRoleResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/assume_role.xml\", \"text/xml\")).build();\n\n   public void testAssumeRoleWhenResponseIs2xx() {\n\n      STSApi apiWhenWithOptionsExist = requestSendsResponse(assumeRole, assumeRoleResponse);\n\n      assertEquals(apiWhenWithOptionsExist.assumeRole(\"arn:aws:iam::123456789012:role/demo\", \"Bob\").toString(),\n            new AssumeRoleResponseTest().expected().toString());\n   }\n\n   String policy = \"{\\\"Statement\\\":[{\\\"Sid\\\":\\\"Stmt1\\\",\\\"Effect\\\":\\\"Allow\\\",\\\"Action\\\":\\\"s3:*\\\",\\\"Resource\\\":\\\"*\\\"}]}\";\n\n   HttpRequest assumeRoleWithOptions = HttpRequest.builder().method(POST)\n         .endpoint(\"https://sts.amazonaws.com/\")\n         .addHeader(HOST, \"sts.amazonaws.com\")\n         .addFormParam(\"Action\", \"AssumeRole\")\n         .addFormParam(\"DurationSeconds\", \"900\")\n         .addFormParam(\"ExternalId\", \"123ABC\")\n         .addFormParam(\"Policy\", policy)\n         .addFormParam(\"RoleArn\", \"arn:aws:iam::123456789012:role/demo\")\n         .addFormParam(\"RoleSessionName\", \"Bob\")\n         .addFormParam(\"Signature\", \"9qffV6zHRbTX8E9IYbEFeQPWrHEdSbwUfjJpg1SMaBo=\")\n         .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n         .addFormParam(\"SignatureVersion\", \"2\")\n         .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n         .addFormParam(\"Version\", \"2011-06-15\")\n         .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testAssumeRoleWithOptionsWhenResponseIs2xx() {\n\n      STSApi apiWhenWithOptionsExist = requestSendsResponse(assumeRoleWithOptions, assumeRoleResponse);\n\n      assertEquals(\n            apiWhenWithOptionsExist.assumeRole(\"arn:aws:iam::123456789012:role/demo\", \"Bob\",\n                  externalId(\"123ABC\").policy(policy).durationSeconds(TimeUnit.MINUTES.toSeconds(15))).toString(),\n            new AssumeRoleResponseTest().expected().toString());\n   }\n\n   HttpRequest createFederatedUser = HttpRequest.builder().method(POST)\n         .endpoint(\"https://sts.amazonaws.com/\")\n         .addHeader(HOST, \"sts.amazonaws.com\")\n         .addFormParam(\"Action\", \"GetFederationToken\")\n         .addFormParam(\"Name\", \"Bob\")\n         .addFormParam(\"Signature\", \"Z7AtGK4X9IAx/zMtLD7baNiyltNl+F+SHqjIGUidzOc=\")\n         .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n         .addFormParam(\"SignatureVersion\", \"2\")\n         .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n         .addFormParam(\"Version\", \"2011-06-15\")\n         .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   HttpResponse createFederatedUserResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/federation_token.xml\", \"text/xml\")).build();\n\n   public void testCreateFederatedUserWhenResponseIs2xx() {\n\n      STSApi apiWhenWithOptionsExist = requestSendsResponse(createFederatedUser, createFederatedUserResponse);\n\n      assertEquals(apiWhenWithOptionsExist.createFederatedUser(\"Bob\").toString(), new GetFederationTokenResponseTest()\n            .expected().toString());\n   }\n\n   HttpRequest createFederatedUserWithOptions = HttpRequest.builder().method(POST)\n         .endpoint(\"https://sts.amazonaws.com/\")\n         .addHeader(HOST, \"sts.amazonaws.com\")\n         .addFormParam(\"Action\", \"GetFederationToken\")\n         .addFormParam(\"DurationSeconds\", \"900\")\n         .addFormParam(\"Name\", \"Bob\")\n         .addFormParam(\"Policy\", policy)\n         .addFormParam(\"Signature\", \"+WGvCNtmb1UPmQHxXPMvcK6vH/TJ9r/wCuxdz03n/2w=\")\n         .addFormParam(\"SignatureMethod\", \"HmacSHA256\")\n         .addFormParam(\"SignatureVersion\", \"2\")\n         .addFormParam(\"Timestamp\", \"2009-11-08T15:54:08.897Z\")\n         .addFormParam(\"Version\", \"2011-06-15\")\n         .addFormParam(\"AWSAccessKeyId\", \"identity\").build();\n\n   public void testCreateFederatedUserWithOptionsWhenResponseIs2xx() {\n\n      STSApi apiWhenWithOptionsExist = requestSendsResponse(createFederatedUserWithOptions, createFederatedUserResponse);\n\n      assertEquals(\n            apiWhenWithOptionsExist.createFederatedUser(\"Bob\",\n                  policy(policy).durationSeconds(TimeUnit.MINUTES.toSeconds(15))).toString(),\n            new GetFederationTokenResponseTest().expected().toString());\n   }\n}\n"
  },
  {
    "path": "apis/sts/src/test/java/org/jclouds/sts/STSApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sts;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static java.util.concurrent.TimeUnit.MINUTES;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.aws.domain.SessionCredentials;\nimport org.jclouds.sts.domain.UserAndSessionCredentials;\nimport org.jclouds.sts.internal.BaseSTSApiLiveTest;\nimport org.jclouds.sts.options.AssumeRoleOptions;\nimport org.jclouds.sts.options.FederatedUserOptions;\nimport org.jclouds.sts.options.SessionCredentialsOptions;\nimport org.testng.SkipException;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"STSApiLiveTest\")\npublic class STSApiLiveTest extends BaseSTSApiLiveTest {\n\n   @Test\n   protected void testCreateTemporaryCredentials() {\n      SessionCredentials creds = api.createTemporaryCredentials(\n            new SessionCredentialsOptions().durationSeconds(MINUTES.toSeconds(15)));\n      checkTemporaryCredentials(creds);\n      // TODO: actually login to some service\n      //\n      //      context.close();\n      //      ProviderMetadata pm = createProviderMetadata();\n      //\n      //      context = (pm != null ? ContextBuilder.newBuilder(pm) : ContextBuilder.newBuilder(createApiMetadata()))\n      //            .credentialsSupplier(Supplier.<Credentials> of(creds)).modules(setupModules()).build();\n   }\n\n   @Test\n   protected void testCreateFederatedUser() {\n      UserAndSessionCredentials user = api.createFederatedUser(\"Bob\", new FederatedUserOptions().durationSeconds(MINUTES.toSeconds(15)));\n      checkTemporaryCredentials(user.getCredentials());\n      assertTrue(user.getUser().getId().contains(\"Bob\"), user + \" id incorrect\");\n      assertTrue(user.getUser().getArn().contains(\"Bob\"), user + \" arn incorrect\");\n      assertTrue(user.getPackedPolicySize() >= 0, user + \" policy size negative\");\n   }\n\n   @Test\n   protected void testAssumeRole() {\n      String arnToAssume = getTestArn();\n      UserAndSessionCredentials role = api.assumeRole(arnToAssume, \"session\",\n            new AssumeRoleOptions().durationSeconds(MINUTES.toSeconds(15)));\n      checkTemporaryCredentials(role.getCredentials());\n      assertTrue(role.getUser().getId().contains(\"session\"), role + \" id incorrect\");\n      assertTrue(role.getUser().getArn().contains(\"session\"), role + \" arn incorrect\");\n      assertTrue(role.getPackedPolicySize() >= 0, role + \" policy size negative\");\n   }\n\n   protected String getTestArn() {\n      throw new SkipException(\"TODO: need to query a valid arn to assume\");\n   }\n\n   private void checkTemporaryCredentials(SessionCredentials creds) {\n      checkNotNull(creds.getAccessKeyId(), \"AccessKeyId cannot be null for TemporaryCredentials.\");\n      checkNotNull(creds.getSecretAccessKey(), \"SecretAccessKey cannot be null for TemporaryCredentials.\");\n      checkNotNull(creds.getSessionToken(), \"SessionToken cannot be null for TemporaryCredentials.\");\n      checkNotNull(creds.getExpiration(), \"Expiration cannot be null for TemporaryCredentials.\");\n   }\n}\n"
  },
  {
    "path": "apis/sts/src/test/java/org/jclouds/sts/STSApiMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sts;\n\nimport org.jclouds.View;\nimport org.jclouds.rest.internal.BaseHttpApiMetadataTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.reflect.TypeToken;\n\n@Test(groups = \"unit\", testName = \"STSApiMetadataTest\")\npublic class STSApiMetadataTest extends BaseHttpApiMetadataTest {\n\n   // no token abstraction, yet\n   public STSApiMetadataTest() {\n      super(new STSApiMetadata(), ImmutableSet.<TypeToken<? extends View>> of());\n   }\n}\n"
  },
  {
    "path": "apis/sts/src/test/java/org/jclouds/sts/internal/BaseSTSApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sts.internal;\n\nimport org.jclouds.sts.STSApi;\n\npublic class BaseSTSApiExpectTest extends BaseSTSExpectTest<STSApi> {\n\n}\n"
  },
  {
    "path": "apis/sts/src/test/java/org/jclouds/sts/internal/BaseSTSApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sts.internal;\n\nimport org.jclouds.apis.BaseApiLiveTest;\nimport org.jclouds.sts.STSApi;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\")\npublic class BaseSTSApiLiveTest extends BaseApiLiveTest<STSApi> {\n   public BaseSTSApiLiveTest() {\n      provider = \"sts\";\n   }\n}\n"
  },
  {
    "path": "apis/sts/src/test/java/org/jclouds/sts/internal/BaseSTSExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sts.internal;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.sts.config.STSHttpApiModule;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.internal.BaseRestApiExpectTest;\n\nimport com.google.inject.Module;\n\npublic class BaseSTSExpectTest<T> extends BaseRestApiExpectTest<T> {\n\n   public BaseSTSExpectTest() {\n      provider = \"sts\";\n   }\n   \n   @ConfiguresHttpApi\n   private static final class TestSTSHttpApiModule extends STSHttpApiModule {\n\n      @Override\n      protected String provideTimeStamp(final DateService dateService) {\n         return \"2009-11-08T15:54:08.897Z\";\n      }\n   }\n\n   @Override\n   protected Module createModule() {\n      return new TestSTSHttpApiModule();\n   }\n}\n"
  },
  {
    "path": "apis/sts/src/test/java/org/jclouds/sts/options/AssumeRoleOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sts.options;\n\nimport static org.jclouds.sts.options.AssumeRoleOptions.Builder.externalId;\nimport static org.jclouds.sts.options.AssumeRoleOptions.Builder.durationSeconds;\nimport static org.jclouds.sts.options.AssumeRoleOptions.Builder.policy;\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\", testName = \"AssumeRoleOptionsTest\")\npublic class AssumeRoleOptionsTest {\n\n   public void testExternalId() {\n      AssumeRoleOptions options = new AssumeRoleOptions().externalId(\"123ABC\");\n      assertEquals(ImmutableSet.of(\"123ABC\"), options.buildFormParameters().get(\"ExternalId\"));\n   }\n\n   public void testExternalIdStatic() {\n      AssumeRoleOptions options = externalId(\"123ABC\");\n      assertEquals(ImmutableSet.of(\"123ABC\"), options.buildFormParameters().get(\"ExternalId\"));\n   }\n\n   public void testDurationSeconds() {\n      AssumeRoleOptions options = new AssumeRoleOptions().durationSeconds(3600);\n      assertEquals(ImmutableSet.of(\"3600\"), options.buildFormParameters().get(\"DurationSeconds\"));\n   }\n\n   public void testDurationSecondsStatic() {\n      AssumeRoleOptions options = durationSeconds(3600);\n      assertEquals(ImmutableSet.of(\"3600\"), options.buildFormParameters().get(\"DurationSeconds\"));\n   }\n\n   String policy = \"{\\\"Statement\\\":[{\\\"Sid\\\":\\\"Stmt1\\\",\\\"Effect\\\":\\\"Allow\\\",\\\"Action\\\":\\\"s3:*\\\",\\\"Resource\\\":\\\"*\\\"}]}\";\n\n   public void testPolicy() {\n      AssumeRoleOptions options = new AssumeRoleOptions().policy(policy);\n      assertEquals(ImmutableSet.of(policy), options.buildFormParameters().get(\"Policy\"));\n   }\n\n   public void testPolicyStatic() {\n      AssumeRoleOptions options = policy(policy);\n      assertEquals(ImmutableSet.of(policy), options.buildFormParameters().get(\"Policy\"));\n   }\n\n}\n"
  },
  {
    "path": "apis/sts/src/test/java/org/jclouds/sts/options/FederatedUserOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sts.options;\n\nimport static org.jclouds.sts.options.FederatedUserOptions.Builder.durationSeconds;\nimport static org.jclouds.sts.options.FederatedUserOptions.Builder.policy;\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\", testName = \"FederatedUserOptionsTest\")\npublic class FederatedUserOptionsTest {\n\n   public void testDurationSeconds() {\n      FederatedUserOptions options = new FederatedUserOptions().durationSeconds(3600);\n      assertEquals(ImmutableSet.of(\"3600\"), options.buildFormParameters().get(\"DurationSeconds\"));\n   }\n\n   public void testDurationSecondsStatic() {\n      FederatedUserOptions options = durationSeconds(3600);\n      assertEquals(ImmutableSet.of(\"3600\"), options.buildFormParameters().get(\"DurationSeconds\"));\n   }\n\n   String policy = \"{\\\"Statement\\\":[{\\\"Sid\\\":\\\"Stmt1\\\",\\\"Effect\\\":\\\"Allow\\\",\\\"Action\\\":\\\"s3:*\\\",\\\"Resource\\\":\\\"*\\\"}]}\";\n\n   public void testPolicy() {\n      FederatedUserOptions options = new FederatedUserOptions().policy(policy);\n      assertEquals(ImmutableSet.of(policy), options.buildFormParameters().get(\"Policy\"));\n   }\n\n   public void testPolicyStatic() {\n      FederatedUserOptions options = policy(policy);\n      assertEquals(ImmutableSet.of(policy), options.buildFormParameters().get(\"Policy\"));\n   }\n\n}\n"
  },
  {
    "path": "apis/sts/src/test/java/org/jclouds/sts/options/SessionCredentialsOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sts.options;\n\nimport static org.jclouds.sts.options.SessionCredentialsOptions.Builder.serialNumber;\nimport static org.jclouds.sts.options.SessionCredentialsOptions.Builder.durationSeconds;\nimport static org.jclouds.sts.options.SessionCredentialsOptions.Builder.tokenCode;\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\", testName = \"SessionCredentialsOptionsTest\")\npublic class SessionCredentialsOptionsTest {\n\n   public void testSerialNumber() {\n      SessionCredentialsOptions options = new SessionCredentialsOptions().serialNumber(\"YourMFADeviceSerialNumber\");\n      assertEquals(ImmutableSet.of(\"YourMFADeviceSerialNumber\"), options.buildFormParameters().get(\"SerialNumber\"));\n   }\n\n   public void testSerialNumberStatic() {\n      SessionCredentialsOptions options = serialNumber(\"YourMFADeviceSerialNumber\");\n      assertEquals(ImmutableSet.of(\"YourMFADeviceSerialNumber\"), options.buildFormParameters().get(\"SerialNumber\"));\n   }\n\n   public void testDurationSeconds() {\n      SessionCredentialsOptions options = new SessionCredentialsOptions().durationSeconds(3600);\n      assertEquals(ImmutableSet.of(\"3600\"), options.buildFormParameters().get(\"DurationSeconds\"));\n   }\n\n   public void testDurationSecondsStatic() {\n      SessionCredentialsOptions options = durationSeconds(3600);\n      assertEquals(ImmutableSet.of(\"3600\"), options.buildFormParameters().get(\"DurationSeconds\"));\n   }\n\n   public void testTokenCode() {\n      SessionCredentialsOptions options = new SessionCredentialsOptions().tokenCode(\"123456\");\n      assertEquals(ImmutableSet.of(\"123456\"), options.buildFormParameters().get(\"TokenCode\"));\n   }\n\n   public void testTokenCodeStatic() {\n      SessionCredentialsOptions options = tokenCode(\"123456\");\n      assertEquals(ImmutableSet.of(\"123456\"), options.buildFormParameters().get(\"TokenCode\"));\n   }\n\n}\n"
  },
  {
    "path": "apis/sts/src/test/java/org/jclouds/sts/parse/AssumeRoleResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sts.parse;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.sts.domain.UserAndSessionCredentials;\nimport org.jclouds.sts.domain.User;\nimport org.jclouds.sts.xml.UserAndSessionCredentialsHandler;\nimport org.testng.annotations.Test;\n\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"AssumeRoleResponseTest\")\npublic class AssumeRoleResponseTest extends BaseHandlerTest {\n\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/assume_role.xml\");\n\n      UserAndSessionCredentials expected = expected();\n\n      UserAndSessionCredentialsHandler handler = injector.getInstance(UserAndSessionCredentialsHandler.class);\n      UserAndSessionCredentials result = factory.create(handler).parse(is);\n\n      assertEquals(result, expected);\n      assertEquals(result.getUser(), expected.getUser());\n      assertEquals(result.getPackedPolicySize(), expected.getPackedPolicySize());\n   }\n\n   public UserAndSessionCredentials expected() {\n      return UserAndSessionCredentials.builder()\n                        .credentials(new GetSessionTokenResponseTest().expected())\n                        .user(User.fromIdAndArn(\"ARO123EXAMPLE123:Bob\", \"arn:aws:sts::123456789012:assumed-role/demo/Bob\"))\n                        .packedPolicySize(6).build();\n   }\n}\n"
  },
  {
    "path": "apis/sts/src/test/java/org/jclouds/sts/parse/GetFederationTokenResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sts.parse;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.sts.domain.UserAndSessionCredentials;\nimport org.jclouds.sts.domain.User;\nimport org.jclouds.sts.xml.UserAndSessionCredentialsHandler;\nimport org.testng.annotations.Test;\n\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"GetFederationTokenResponseTest\")\npublic class GetFederationTokenResponseTest extends BaseHandlerTest {\n\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/federation_token.xml\");\n\n      UserAndSessionCredentials expected = expected();\n\n      UserAndSessionCredentialsHandler handler = injector.getInstance(UserAndSessionCredentialsHandler.class);\n      UserAndSessionCredentials result = factory.create(handler).parse(is);\n\n      assertEquals(result, expected);\n      assertEquals(result.getUser(), expected.getUser());\n      assertEquals(result.getPackedPolicySize(), expected.getPackedPolicySize());\n   }\n\n   public UserAndSessionCredentials expected() {\n      return UserAndSessionCredentials.builder()\n                        .credentials(new GetSessionTokenResponseTest().expected())\n                        .user(User.fromIdAndArn(\"123456789012:Bob\", \"arn:aws:sts::123456789012:federated-user/Bob\"))\n                        .packedPolicySize(6).build();\n   }\n}\n"
  },
  {
    "path": "apis/sts/src/test/java/org/jclouds/sts/parse/GetSessionTokenResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sts.parse;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.aws.domain.SessionCredentials;\nimport org.jclouds.aws.xml.SessionCredentialsHandler;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.testng.annotations.Test;\n\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"GetSessionTokenResponseTest\")\npublic class GetSessionTokenResponseTest extends BaseHandlerTest {\n\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/session_token.xml\");\n\n      SessionCredentials expected = expected();\n\n      SessionCredentialsHandler handler = injector.getInstance(SessionCredentialsHandler.class);\n      SessionCredentials result = factory.create(handler).parse(is);\n\n      assertEquals(result, expected);\n      assertEquals(result.getAccessKeyId(), expected.getAccessKeyId());\n      assertEquals(result.getSecretAccessKey(), expected.getSecretAccessKey());\n      assertEquals(result.getSessionToken(), expected.getSessionToken());\n      assertEquals(result.getExpiration(), expected.getExpiration());\n   }\n\n   public SessionCredentials expected() {\n      return SessionCredentials.builder()\n            .accessKeyId(\"AKIAIOSFODNN7EXAMPLE\")\n            .secretAccessKey(\"wJalrXUtnFEMI/K7MDENG/bPxRfiCYzEXAMPLEKEY\")\n            .sessionToken(\"AQoEXAMPLEH4aoAH0gNCAPyJxz4BlCFFxWNE1OPTgk5TthT\")\n            .expiration(new SimpleDateFormatDateService().iso8601DateParse(\"2011-07-11T19:55:29.611Z\")).build();\n   }\n\n}\n"
  },
  {
    "path": "apis/sts/src/test/resources/assume_role.xml",
    "content": "<AssumeRoleResponse xmlns=\"https://sts.amazonaws.com/doc/2011-06-15/\">\n\t<AssumeRoleResult>\n\t\t<Credentials>\n\t\t\t<SessionToken>AQoEXAMPLEH4aoAH0gNCAPyJxz4BlCFFxWNE1OPTgk5TthT</SessionToken>\n\t\t\t<SecretAccessKey>wJalrXUtnFEMI/K7MDENG/bPxRfiCYzEXAMPLEKEY</SecretAccessKey>\n\t\t\t<Expiration>2011-07-11T19:55:29.611Z</Expiration>\n\t\t\t<AccessKeyId>AKIAIOSFODNN7EXAMPLE</AccessKeyId>\n\t\t</Credentials>\n\t\t<AssumedRoleUser>\n\t\t\t<Arn>arn:aws:sts::123456789012:assumed-role/demo/Bob</Arn>\n\t\t\t<AssumedRoleId>ARO123EXAMPLE123:Bob</AssumedRoleId>\n\t\t</AssumedRoleUser>\n\t\t<PackedPolicySize>6</PackedPolicySize>\n\t</AssumeRoleResult>\n\t<ResponseMetadata>\n\t\t<RequestId>c6104cbe-af31-11e0-8154-cbc7ccf896c7</RequestId>\n\t</ResponseMetadata>\n</AssumeRoleResponse>\n"
  },
  {
    "path": "apis/sts/src/test/resources/credentials.xml",
    "content": "<Credentials>\n\t<SessionToken>AQoEXAMPLEH4aoAH0gNCAPyJxz4BlCFFxWNE1OPTgk5TthT</SessionToken>\n\t<SecretAccessKey>wJalrXUtnFEMI/K7MDENG/bPxRfiCYzEXAMPLEKEY</SecretAccessKey>\n\t<Expiration>2011-07-11T19:55:29.611Z</Expiration>\n\t<AccessKeyId>AKIAIOSFODNN7EXAMPLE</AccessKeyId>\n</Credentials>"
  },
  {
    "path": "apis/sts/src/test/resources/error.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Error>\n  <Code>NoSuchKey</Code>\n  <Message>The resource you requested does not exist</Message>\n  <Resource>/mybucket/myfoto.jpg</Resource> \n  <RequestId>4442587FB7D0A2F9</RequestId>\n</Error>"
  },
  {
    "path": "apis/sts/src/test/resources/federation_token.xml",
    "content": "<GetFederationTokenResponse xmlns=\"https://sts.amazonaws.com/doc/2011-06-15/\">\n\t<GetFederationTokenResult>\n\t\t<Credentials>\n\t\t\t<SessionToken>AQoEXAMPLEH4aoAH0gNCAPyJxz4BlCFFxWNE1OPTgk5TthT</SessionToken>\n\t\t\t<SecretAccessKey>wJalrXUtnFEMI/K7MDENG/bPxRfiCYzEXAMPLEKEY</SecretAccessKey>\n\t\t\t<Expiration>2011-07-11T19:55:29.611Z</Expiration>\n\t\t\t<AccessKeyId>AKIAIOSFODNN7EXAMPLE</AccessKeyId>\n\t\t</Credentials>\n\t\t<FederatedUser>\n\t\t\t<Arn>arn:aws:sts::123456789012:federated-user/Bob</Arn>\n\t\t\t<FederatedUserId>123456789012:Bob</FederatedUserId>\n\t\t</FederatedUser>\n\t\t<PackedPolicySize>6</PackedPolicySize>\n\t</GetFederationTokenResult>\n\t<ResponseMetadata>\n\t\t<RequestId>c6104cbe-af31-11e0-8154-cbc7ccf896c7</RequestId>\n\t</ResponseMetadata>\n</GetFederationTokenResponse>"
  },
  {
    "path": "apis/sts/src/test/resources/log4j.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE log4j:configuration SYSTEM \"log4j.dtd\">\n\n    <!--\n        For more configuration infromation and examples see the Apache\n        Log4j website: http://logging.apache.org/log4j/\n    -->\n<log4j:configuration xmlns:log4j=\"http://jakarta.apache.org/log4j/\"\n    debug=\"false\">\n\n    <!-- A time/date based rolling appender -->\n    <appender name=\"WIREFILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds-wire.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n\n    <!-- A time/date based rolling appender -->\n    <appender name=\"FILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n    <!-- A time/date based rolling appender -->\n\n    <!-- A time/date based rolling appender -->\n    <appender name=\"COMPUTEFILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds-compute.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n\n    <!-- A time/date based rolling appender -->\n    <appender name=\"SSHFILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds-ssh.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n\n    <appender name=\"ASYNCCOMPUTE\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"COMPUTEFILE\" />\n    </appender>\n\n    <appender name=\"ASYNCSSH\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"SSHFILE\" />\n    </appender>\n\n    <appender name=\"ASYNC\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"FILE\" />\n    </appender>\n\n    <appender name=\"ASYNCWIRE\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"WIREFILE\" />\n    </appender>\n    <!-- ================ -->\n    <!-- Limit categories -->\n    <!-- ================ -->\n\n    <category name=\"org.jclouds\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNC\" />\n    </category>\n\n    <category name=\"jclouds.headers\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNCWIRE\" />\n    </category>\n\n    <category name=\"jclouds.ssh\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNCSSH\" />\n    </category>\n    <category name=\"jclouds.wire\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNCWIRE\" />\n    </category>\n    <category name=\"jclouds.compute\">\n        <priority value=\"TRACE\" />\n        <appender-ref ref=\"ASYNCCOMPUTE\" />\n    </category>\n    <!-- ======================= -->\n    <!-- Setup the Root category -->\n    <!-- ======================= -->\n\n    <root>\n        <priority value=\"WARN\" />\n    </root>\n\n</log4j:configuration>\n"
  },
  {
    "path": "apis/sts/src/test/resources/session_token.xml",
    "content": "<GetSessionTokenResponse xmlns=\"https://sts.amazonaws.com/doc/2011-06-15/\">\n\t<GetSessionTokenResult>\n\t\t<Credentials>\n\t\t\t<SessionToken>AQoEXAMPLEH4aoAH0gNCAPyJxz4BlCFFxWNE1OPTgk5TthT</SessionToken>\n\t\t\t<SecretAccessKey>wJalrXUtnFEMI/K7MDENG/bPxRfiCYzEXAMPLEKEY</SecretAccessKey>\n\t\t\t<Expiration>2011-07-11T19:55:29.611Z</Expiration>\n\t\t\t<AccessKeyId>AKIAIOSFODNN7EXAMPLE</AccessKeyId>\n\t\t</Credentials>\n\t</GetSessionTokenResult>\n\t<ResponseMetadata>\n\t\t<RequestId>58c5dbae-abef-11e0-8cfe-09039844ac7d</RequestId>\n\t</ResponseMetadata>\n</GetSessionTokenResponse>"
  },
  {
    "path": "blobstore/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.blobstore.*;version=\"${project.version}\";-noimport:=true"
  },
  {
    "path": "blobstore/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../project/pom.xml</relativePath>\n  </parent>\n  <artifactId>jclouds-blobstore</artifactId>\n  <name>jclouds blobstore core</name>\n  <description>jclouds components to access blobstore</description>\n\n  <scm>\n    <connection>scm:svn:http://jclouds.googlecode.com/svn/trunk/blobstore</connection>\n    <developerConnection>scm:svn:https://jclouds.googlecode.com/svn/trunk/blobstore</developerConnection>\n    <url>http://jclouds.googlecode.com/svn/trunk/blobstore</url>\n    <tag>HEAD</tag>\n  </scm>\n\n  <dependencies>\n    <dependency>\n      <groupId>${project.groupId}</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>jakarta.ws.rs</groupId>\n      <artifactId>jakarta.ws.rs-api</artifactId>\n    </dependency>\n    <dependency>\n      <groupId>${project.groupId}</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.value</groupId>\n      <artifactId>auto-value</artifactId>\n      <optional>true</optional>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <build>\n    <plugins>\n      <plugin>\n        <groupId>org.apache.maven.plugins</groupId>\n        <artifactId>maven-surefire-plugin</artifactId>\n        <executions>\n          <execution>\n            <id>integration</id>\n            <phase>integration-test</phase>\n            <goals>\n              <goal>test</goal>\n            </goals>\n            <configuration>\n              <excludes>\n                <exclude>**/*LiveTest.java</exclude>\n                <exclude>**/Base*Test.java</exclude>\n              </excludes>\n              <includes>\n                <include>**/*IntegrationTest.java</include>\n              </includes>\n              <systemPropertyVariables>\n                <jclouds.blobstore.httpstream.url>${jclouds.blobstore.httpstream.url}</jclouds.blobstore.httpstream.url>\n                <jclouds.blobstore.httpstream.md5>${jclouds.blobstore.httpstream.md5}</jclouds.blobstore.httpstream.md5>\n              </systemPropertyVariables>\n            </configuration>\n          </execution>\n        </executions>\n        <configuration>\n          <excludes>\n            <exclude>**/*IntegrationTest.java</exclude>\n            <exclude>**/*LiveTest.java</exclude>\n          </excludes>\n        </configuration>\n      </plugin>\n    </plugins>\n  </build>\n</project>\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/BlobRequestSigner.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore;\n\nimport com.google.common.annotations.Beta;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.internal.RequestSigningUnsupported;\nimport org.jclouds.blobstore.options.GetOptions;\nimport org.jclouds.http.HttpRequest;\n\nimport com.google.inject.ImplementedBy;\n\n/**\n * Generates signed requests for blobs. useful in other tools such as backup utilities.\n */\n@ImplementedBy(RequestSigningUnsupported.class)\npublic interface BlobRequestSigner {\n\n   /**\n    * gets a signed request, including headers as necessary, to access a blob from an external\n    * client.\n    * \n    * @param container\n    *           container where the blob resides\n    * @param directory\n    *           full path to the blob\n    * @throws UnsupportedOperationException\n    *            if not supported by the provider\n    */\n   HttpRequest signGetBlob(String container, String name);\n\n   /**\n    * gets a signed request, including headers as necessary, to allow access to a blob\n    * from an external client for a limited period of time\n    *\n    * @param timeInSeconds\n    *           validity time in seconds for the generated request\n    * @see #signGetBlob(String, String)\n    */\n   @Beta\n   HttpRequest signGetBlob(String container, String name, long timeInSeconds);\n\n   /**\n    * @param options\n    * @see #signGetBlob(String, String)\n    */\n   HttpRequest signGetBlob(String container, String name, GetOptions options);\n\n   /**\n    * gets a signed request, including headers as necessary, to upload a blob from an external\n    * client.\n    * \n    * <pre>\n    * Blob blob = context.getBlobStore.blobBuilder().name(&quot;name&quot;).forSigning().contentType(&quot;text/plain&quot;)\n    *          .contentLength(length).build();\n    * </pre>\n    * \n    * @param container\n    *           container where the blob resides\n    * @param blob\n    *           what to upload\n    * @throws UnsupportedOperationException\n    *            if not supported by the provider\n    * @see BlobBuilder#forSigning\n    */\n   HttpRequest signPutBlob(String container, Blob blob);\n\n   /**\n    * gets a signed request, including headers as necessary, to upload a blob from an\n    * external client for a limited period of time\n    *\n    * @param timeInSeconds\n    *           validity time in seconds for the generated request\n    * @see BlobBuilder#forSigning\n    * @see BlobRequestSigner#signPutBlob\n    */\n   @Beta\n   HttpRequest signPutBlob(String container, Blob blob, long timeInSeconds);\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/BlobStore.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore;\n\nimport java.io.File;\nimport java.io.InputStream;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.concurrent.ExecutorService;\n\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.BlobAccess;\nimport org.jclouds.blobstore.domain.BlobBuilder;\nimport org.jclouds.blobstore.domain.BlobMetadata;\nimport org.jclouds.blobstore.domain.ContainerAccess;\nimport org.jclouds.blobstore.domain.MultipartPart;\nimport org.jclouds.blobstore.domain.MultipartUpload;\nimport org.jclouds.blobstore.domain.PageSet;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.options.CopyOptions;\nimport org.jclouds.blobstore.options.CreateContainerOptions;\nimport org.jclouds.blobstore.options.GetOptions;\nimport org.jclouds.blobstore.options.ListContainerOptions;\nimport org.jclouds.blobstore.options.PutOptions;\nimport org.jclouds.domain.Location;\nimport org.jclouds.io.Payload;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.annotations.Beta;\n\n/**\n * Synchronous access to a BlobStore such as Amazon S3\n */\npublic interface BlobStore {\n   /**\n    * @return a reference to the context that created this BlobStore.\n    */\n   BlobStoreContext getContext();\n\n   /**\n    *\n    * @return builder for creating new {@link Blob}s\n    */\n   BlobBuilder blobBuilder(String name);\n\n   /**\n    * The get locations command returns all the valid locations for containers. A location has a\n    * scope, which is typically region or zone. A region is a general area, like eu-west, where a\n    * zone is similar to a datacenter. If a location has a parent, that implies it is within that\n    * location. For example a location can be a rack, whose parent is likely to be a zone.\n    */\n   Set<? extends Location> listAssignableLocations();\n\n   /**\n    * Lists all root-level resources available to the identity.\n    */\n   PageSet<? extends StorageMetadata> list();\n\n   /**\n    * determines if a service-level container exists\n    */\n   boolean containerExists(String container);\n\n   /**\n    * Creates a namespace for your blobs\n    * <p/>\n    *\n    * A container is a namespace for your objects. Depending on the service, the scope can be\n    * global, identity, or sub-identity scoped. For example, in Amazon S3, containers are called\n    * buckets, and they must be uniquely named such that no-one else in the world conflicts. In\n    * other blobstores, the naming convention of the container is less strict. All blobstores allow\n    * you to list your containers and also the contents within them. These contents can either be\n    * blobs, folders, or virtual paths.\n    *\n    * @param location\n    *           some blobstores allow you to specify a location, such as US-EAST, for where this\n    *           container will exist. null will choose a default location\n    * @param container\n    *           namespace. Typically constrained to lowercase alpha-numeric and hyphens.\n    * @return true if the container was created, false if it already existed.\n    */\n   boolean createContainerInLocation(@Nullable Location location, String container);\n\n   /**\n    *\n    * @param options\n    *           controls default access control\n    * @see #createContainerInLocation(Location,String)\n    */\n   boolean createContainerInLocation(@Nullable Location location, String container, CreateContainerOptions options);\n\n   @Beta\n   ContainerAccess getContainerAccess(String container);\n\n   @Beta\n   void setContainerAccess(String container, ContainerAccess access);\n\n   /**\n    * Lists all resources in a container non-recursive.\n    *\n    * @param container\n    *           what to list\n    * @return a list that may be incomplete, depending on whether PageSet#getNextMarker is set\n    */\n   PageSet<? extends StorageMetadata> list(String container);\n\n   /**\n    * Like {@link #list(String)} except you can control the size, recursion, and context of the list\n    * using {@link ListContainerOptions options}\n    *\n    * @param container\n    *           what to list\n    * @param options\n    *           size, recursion, and context of the list\n    * @return a list that may be incomplete, depending on whether PageSet#getNextMarker is set\n    */\n   PageSet<? extends StorageMetadata> list(String container, ListContainerOptions options);\n\n   /**\n    * This will delete the contents of a container at its root path without deleting the container\n    *\n    * @param container\n    *           what to clear\n    */\n   void clearContainer(String container);\n\n   /**\n    * Like {@link #clearContainer(String)} except you can use options to do things like recursive\n    * deletes, or clear at a different path than root.\n    *\n    * @param container\n    *           what to clear\n    * @param options\n    *           recursion and path to clear\n    */\n   void clearContainer(String container, ListContainerOptions options);\n\n   /**\n    * This will delete everything inside a container recursively.\n    *\n    * @param container\n    *           what to delete\n    * @param container name of the container to delete\n    */\n   void deleteContainer(String container);\n\n   /**\n    * Deletes a container if it is empty.\n    *\n    * @param container name of the container to delete\n    * @return true if the container was deleted or does not exist\n    */\n   boolean deleteContainerIfEmpty(String container);\n\n   /**\n    * Determines if a directory exists\n    *\n    * @param container\n    *           container where the directory resides\n    * @param directory\n    *           full path to the directory\n    * @deprecated use prefix and delimiter instead\n    */\n   @Deprecated\n   boolean directoryExists(String container, String directory);\n\n   /**\n    * Creates a folder or a directory marker depending on the service\n    *\n    * @param container\n    *           container to create the directory in\n    * @param directory\n    *           full path to the directory\n    * @deprecated use prefix and delimiter instead\n    */\n   @Deprecated\n   void createDirectory(String container, String directory);\n\n   /**\n    * Deletes a folder or a directory marker depending on the service\n    *\n    * @param container\n    *           container to delete the directory from\n    * @param directory\n    *           full path to the directory to delete\n    * @deprecated use prefix and delimiter instead\n    */\n   @Deprecated\n   void deleteDirectory(String containerName, String name);\n\n   /**\n    * Determines if a blob exists\n    *\n    * @param container\n    *           container where the blob resides\n    * @param directory\n    *           full path to the blob\n    */\n   boolean blobExists(String container, String name);\n\n   /**\n    * Adds a {@code Blob} representing the data at location {@code container/blob.metadata.name}\n    *\n    * @param container\n    *           container to place the blob.\n    * @param blob\n    *           fully qualified name relative to the container.\n    * @param options\n    *           byte range or condition options\n    * @return etag of the blob you uploaded, possibly null where etags are unsupported\n    * @throws ContainerNotFoundException\n    *            if the container doesn't exist\n    */\n   String putBlob(String container, Blob blob);\n\n   /**\n    * Adds a {@code Blob} representing the data at location {@code container/blob.metadata.name}\n    * options using multipart strategies.\n    *\n    * @param container\n    *           container to place the blob.\n    * @param blob\n    *           fully qualified name relative to the container.\n    * @param options\n    *           byte range options\n    * @return etag of the blob you uploaded, possibly null where etags are unsupported\n    * @throws ContainerNotFoundException\n    *            if the container doesn't exist\n    */\n   String putBlob(String container, Blob blob, PutOptions options);\n\n   /**\n    * Copy blob from one container to another.  Some providers implement this\n    * more efficiently than corresponding getBlob and putBlob operations.\n    *\n    * Note: options are currently ignored\n    *\n    * @return ETag of new blob\n    * @throws ContainerNotFoundException if either container does not exist\n    */\n   @Beta\n   String copyBlob(String fromContainer, String fromName, String toContainer, String toName,\n         CopyOptions options);\n\n   /**\n    * Retrieves the metadata of a {@code Blob} at location {@code container/name}\n    *\n    * @param container\n    *           container where this exists.\n    * @param name\n    *           fully qualified name relative to the container.\n    * @return null if name isn't present or the blob you intended to receive.\n    * @throws ContainerNotFoundException\n    *            if the container doesn't exist\n    */\n   @Nullable\n   BlobMetadata blobMetadata(String container, String name);\n\n   /**\n    * Retrieves a {@code Blob} representing the data at location {@code container/name}\n    *\n    * @param container\n    *           container where this exists.\n    * @param name\n    *           fully qualified name relative to the container.\n    * @return the blob you intended to receive or null, if it doesn't exist.\n    * @throws ContainerNotFoundException\n    *            if the container doesn't exist\n    */\n   @Nullable\n   Blob getBlob(String container, String name);\n\n   /**\n    * Retrieves a {@code Blob} representing the data at location {@code container/name}\n    *\n    * @param container\n    *           container where this exists.\n    * @param name\n    *           fully qualified name relative to the container.\n    * @param options\n    *           byte range or condition options\n    * @return the blob you intended to receive or null, if it doesn't exist.\n    * @throws ContainerNotFoundException\n    *            if the container doesn't exist\n    */\n   @Nullable\n   Blob getBlob(String container, String name, GetOptions options);\n\n   /**\n    * Deletes a {@code Blob} representing the data at location {@code container/name}\n    *\n    * @param container\n    *           container where this exists.\n    * @param name\n    *           fully qualified name relative to the container.\n    * @throws ContainerNotFoundException\n    *            if the container doesn't exist\n    */\n   void removeBlob(String container, String name);\n\n   /**\n    * Deletes multiple {@code Blob}s representing the data at location {@code container/name}\n    *\n    * @param container\n    *           container where this exists.\n    * @param names\n    *           fully qualified names relative to the container.\n    * @throws ContainerNotFoundException\n    *            if the container doesn't exist\n    */\n   void removeBlobs(String container, Iterable<String> names);\n\n   @Beta\n   BlobAccess getBlobAccess(String container, String name);\n\n   @Beta\n   void setBlobAccess(String container, String name, BlobAccess access);\n\n   /**\n    * @return a count of all blobs in the container, excluding directory markers\n    */\n   long countBlobs(String container);\n\n   /**\n    * @return a count of all blobs that are in a listing constrained by the options specified,\n    *         excluding directory markers\n    */\n   long countBlobs(String container, ListContainerOptions options);\n\n   @Beta\n   MultipartUpload initiateMultipartUpload(String container, BlobMetadata blob, PutOptions options);\n\n   @Beta\n   // TODO: take parts?\n   void abortMultipartUpload(MultipartUpload mpu);\n\n   @Beta\n   String completeMultipartUpload(MultipartUpload mpu, List<MultipartPart> parts);\n\n   @Beta\n   MultipartPart uploadMultipartPart(MultipartUpload mpu, int partNumber, Payload payload);\n\n   @Beta\n   List<MultipartPart> listMultipartUpload(MultipartUpload mpu);\n\n   @Beta\n   List<MultipartUpload> listMultipartUploads(String container);\n\n   @Beta\n   long getMinimumMultipartPartSize();\n\n   @Beta\n   long getMaximumMultipartPartSize();\n\n   @Beta\n   int getMaximumNumberOfParts();\n\n   @Beta\n   void downloadBlob(String container, String name, File destination);\n\n   @Beta\n   void downloadBlob(String container, String name, File destination, ExecutorService executor);\n\n   @Beta\n   InputStream streamBlob(String container, String name);\n\n   @Beta\n   InputStream streamBlob(String container, String name, ExecutorService executor);\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/BlobStoreContext.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore;\n\nimport java.io.Closeable;\n\nimport org.jclouds.View;\nimport org.jclouds.blobstore.attr.ConsistencyModel;\nimport org.jclouds.blobstore.internal.BlobStoreContextImpl;\nimport org.jclouds.rest.Utils;\n\nimport com.google.inject.ImplementedBy;\n\n/**\n * Represents a cloud that has key-value storage functionality. This object is scoped to a service\n * and an identity.\n */\n@ImplementedBy(BlobStoreContextImpl.class)\npublic interface BlobStoreContext extends Closeable, View {\n   /**\n    * \n    * Generates signed requests for blobs. useful in other tools such as backup utilities.\n    * \n    */\n   BlobRequestSigner getSigner();\n\n   /**\n    * @return a portable interface for the BlobStore.\n    */\n   BlobStore getBlobStore();\n\n   /**\n    * @return best guess at the consistency model used in this BlobStore.\n    */\n   ConsistencyModel getConsistencyModel();\n\n   Utils utils();\n\n   /**\n    * closes threads and resources related to this connection.\n    * \n    */\n   @Override\n   void close();\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/BlobStoreFallbacks.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Throwables.propagate;\nimport static org.jclouds.http.HttpUtils.contains404;\n\nimport org.jclouds.Fallback;\n\npublic final class BlobStoreFallbacks {\n   private BlobStoreFallbacks() {\n   }\n   \n   public static final class ThrowContainerNotFoundOn404 implements Fallback<Object> {\n      public Object createOrPropagate(Throwable t) throws Exception {\n         if (contains404(checkNotNull(t, \"throwable\")))\n            throw new ContainerNotFoundException(t);\n         throw propagate(t);\n      }\n   }\n\n   public static final class ThrowKeyNotFoundOn404 implements Fallback<Object> {\n      public Object createOrPropagate(Throwable t) throws Exception {\n         if (contains404(checkNotNull(t, \"throwable\")))\n            throw new KeyNotFoundException(t);\n         throw propagate(t);\n      }\n   }\n\n   public static final class FalseOnContainerNotFound implements Fallback<Boolean> {\n      public Boolean createOrPropagate(Throwable t) throws Exception {\n         if (checkNotNull(t, \"throwable\") instanceof ContainerNotFoundException) {\n            return false;\n         }\n         throw propagate(t);\n      }\n   }\n\n   public static final class FalseOnKeyNotFound implements Fallback<Boolean> {\n      public Boolean createOrPropagate(Throwable t) throws Exception {\n         if (checkNotNull(t, \"throwable\") instanceof KeyNotFoundException) {\n            return false;\n         }\n         throw propagate(t);\n      }\n   }\n\n   public static final class NullOnContainerNotFound implements Fallback<Object> {\n      public Object createOrPropagate(Throwable t) throws Exception {\n         if (checkNotNull(t, \"throwable\") instanceof ContainerNotFoundException) {\n            return null;\n         }\n         throw propagate(t);\n      }\n   }\n\n   public static final class NullOnKeyNotFound implements Fallback<Object> {\n      public Object createOrPropagate(Throwable t) throws Exception {\n         if (checkNotNull(t, \"throwable\") instanceof KeyNotFoundException) {\n            return null;\n         }\n         throw propagate(t);\n      }\n   }\n\n   public static final class NullOnKeyAlreadyExists implements Fallback<Object> {\n      public Object createOrPropagate(Throwable t) throws Exception {\n         if (checkNotNull(t, \"throwable\") instanceof KeyAlreadyExistsException) {\n            return null;\n         }\n         throw propagate(t);\n      }\n   }\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/BlobStores.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore;\n\nimport java.util.Iterator;\n\nimport org.jclouds.blobstore.domain.PageSet;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.options.ListAllOptions;\nimport org.jclouds.blobstore.options.ListContainerOptions;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.collect.AbstractIterator;\n\n/**\n * Utilities for using Blob Stores.\n * \n * @since 1.3\n */\npublic class BlobStores {\n\n   /**\n    * @see listAll(BlobStore, String, ListContainerOptions, ListAllOptions)\n    */\n   @Beta\n   public static Iterable<StorageMetadata> listAll(BlobStore blobStore, String container,\n            ListContainerOptions containerOptions) {\n      return listAll(blobStore, container, containerOptions, ListAllOptions.NONE);\n   }\n   \n   /**\n    * A variant of BlobStore.list(String, ListContainerOptions) that\n    * produces an Iterable over the entire set of results, not just one\n    * page, making multiple calls to BlobStore.list as needed.\n    * \n    * Note that if listAllOptions.isEager, then the first page will be fetched\n    * immediately and cached. Repeatedly iterating will not re-fetch (and thus\n    * will not refresh) the first page.\n    *  \n    * @throws ContainerNotFoundException If listAllOptions.isEager and container cannot be found\n    */\n   @Beta\n   public static Iterable<StorageMetadata> listAll(final BlobStore blobStore, final String container,\n            final ListContainerOptions containerOptions, final ListAllOptions listAllOptions) {\n      final boolean eager = listAllOptions.isEager();\n      final PageSet<? extends StorageMetadata> firstList;\n      final String firstMarker;\n\n      if (eager) {\n         firstList = blobStore.list(container, containerOptions);\n         firstMarker = firstList.getNextMarker();\n      } else {\n         firstList = null;\n         firstMarker = null;\n      }\n      \n      return new Iterable<StorageMetadata>() {\n         public Iterator<StorageMetadata> iterator() {\n            return new AbstractIterator<StorageMetadata>() {\n               private Iterator<? extends StorageMetadata> iterator;\n               private String marker;\n\n               public StorageMetadata computeNext() {\n                  while (true) {\n                     if (iterator == null) {\n                        PageSet<? extends StorageMetadata> list;\n                        if (eager && marker == null) {\n                           list = firstList;\n                           marker = firstMarker;\n                        } else {\n                           ListContainerOptions nextOptions = marker == null ? containerOptions : containerOptions.clone().afterMarker(marker);\n                           list = blobStore.list(container, nextOptions);\n                           marker = list.getNextMarker();\n                        }\n                        iterator = list.iterator();\n                     }\n                     if (iterator.hasNext()) {\n                        return iterator.next();\n                     }\n                     if (marker == null) {\n                        return endOfData();\n                     }\n                     iterator = null;\n                  }\n               }\n            };\n         }\n      };\n   }\n\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/ContainerNotFoundException.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore;\n\nimport org.jclouds.rest.ResourceNotFoundException;\n\n/**\n * Thrown when a container cannot be located.\n */\npublic class ContainerNotFoundException extends ResourceNotFoundException {\n\n   private String container;\n\n   public ContainerNotFoundException() {\n      super();\n   }\n\n   public ContainerNotFoundException(String container, String message) {\n      super(String.format(\"%s not found: %s\", container, message));\n      this.container = container;\n   }\n\n   public ContainerNotFoundException(Throwable from) {\n      super(from);\n   }\n\n   public String getContainer() {\n      return container;\n   }\n\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/KeyAlreadyExistsException.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore;\n\n/**\n * Thrown when a blob was attempted to be replaced while it already exists\n */\npublic class KeyAlreadyExistsException extends RuntimeException {\n\n   private String container;\n   private String key;\n\n   public KeyAlreadyExistsException() {\n      super();\n   }\n\n   public KeyAlreadyExistsException(String container, String key) {\n      super(String.format(\"%s already exists in container %s\", key, container));\n      this.container = container;\n      this.key = key;\n   }\n\n   public KeyAlreadyExistsException(Exception from) {\n      super(from);\n   }\n\n   public String getContainer() {\n      return container;\n   }\n\n   public String getKey() {\n      return key;\n   }\n\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/KeyNotFoundException.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore;\n\nimport org.jclouds.rest.ResourceNotFoundException;\n\n/**\n * Thrown when a blob cannot be located in the container.\n */\npublic class KeyNotFoundException extends ResourceNotFoundException {\n\n   private String container;\n   private String key;\n\n   public KeyNotFoundException() {\n      super();\n   }\n\n   public KeyNotFoundException(String container, String key, String message) {\n      super(String.format(\"%s not found in container %s: %s\", key, container, message));\n      this.container = container;\n      this.key = key;\n   }\n\n   public KeyNotFoundException(Throwable from) {\n      super(from);\n   }\n\n   public String getContainer() {\n      return container;\n   }\n\n   public String getKey() {\n      return key;\n   }\n\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/LocalBlobRequestSigner.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.net.URI;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.functions.BlobToHttpGetOptions;\nimport org.jclouds.blobstore.options.GetOptions;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.filters.BasicAuthentication;\nimport org.jclouds.io.ContentMetadataCodec;\nimport org.jclouds.location.Provider;\n\nimport com.google.common.base.Supplier;\n\n@Singleton\npublic class LocalBlobRequestSigner implements BlobRequestSigner {\n\n   private final BasicAuthentication basicAuth;\n   private final BlobToHttpGetOptions blob2HttpGetOptions;\n   private final Supplier<URI> endpoint;\n   private final ContentMetadataCodec contentMetadataCodec;\n\n   @Inject\n   public LocalBlobRequestSigner(BasicAuthentication basicAuth, BlobToHttpGetOptions blob2HttpGetOptions, @Provider Supplier<URI> endpoint,\n             ContentMetadataCodec contentMetadataCodec) {\n      this.basicAuth = checkNotNull(basicAuth, \"basicAuth\");\n      this.blob2HttpGetOptions = checkNotNull(blob2HttpGetOptions, \"blob2HttpGetOptions\");\n      this.endpoint = endpoint;\n      this.contentMetadataCodec = contentMetadataCodec;\n   }\n\n   @Override\n   public HttpRequest signGetBlob(String container, String name) {\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(String.format(\"%s/%s/%s\", endpoint.get(), container, name)).build();\n      return basicAuth.filter(request);\n   }\n\n   @Override\n   public HttpRequest signGetBlob(String container, String name, long timeInSeconds) {\n      throw new UnsupportedOperationException();\n   }\n\n   @Override\n   public HttpRequest signPutBlob(String container, Blob blob) {\n      HttpRequest request = HttpRequest.builder().method(\"PUT\").endpoint(\n               URI.create(String.format(\"%s/%s/%s\", endpoint.get(), container, blob.getMetadata().getName()))).payload(\n               blob.getPayload()).headers(\n               contentMetadataCodec.toHeaders(blob.getMetadata().getContentMetadata())).build();\n      return basicAuth.filter(request);\n   }\n\n   @Override\n   public HttpRequest signPutBlob(String container, Blob blob, long timeInSeconds) {\n      throw new UnsupportedOperationException();\n   }\n\n   @Override\n   public HttpRequest signGetBlob(String container, String name, GetOptions options) {\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\n               URI.create(String.format(\"%s/%s/%s\", endpoint.get(), container, name))).headers(\n               blob2HttpGetOptions.apply(options).buildRequestHeaders()).build();\n      return basicAuth.filter(request);\n   }\n\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/LocalStorageStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore;\n\nimport java.io.IOException;\nimport java.util.Collection;\n\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.BlobAccess;\nimport org.jclouds.blobstore.domain.ContainerAccess;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.options.CreateContainerOptions;\nimport org.jclouds.blobstore.options.ListContainerOptions;\nimport org.jclouds.domain.Location;\n\n/**\n * Strategy for local operations related to container and blob\n */\npublic interface LocalStorageStrategy {\n\n    /**\n     * Checks if a container exists\n     * @param container\n     * @return\n     */\n    boolean containerExists(String container);\n\n    /**\n     * Return an iterator that reports all the containers under base path\n     * @return\n     */\n    Collection<String> getAllContainerNames();\n\n    /**\n     * Creates a new container\n     *\n     * @param container\n     * @return\n     */\n    boolean createContainerInLocation(String container, Location location, CreateContainerOptions options);\n\n    ContainerAccess getContainerAccess(String container);\n\n    void setContainerAccess(String container, ContainerAccess access);\n\n    /**\n     * Deletes a container and all its content\n     * @param container\n     */\n    void deleteContainer(String container);\n\n    /**\n     * Empty the container of its content (files and subdirectories), but doesn't\n     * delete the container itself\n     * @param container\n     */\n    void clearContainer(String container);\n\n    /**\n     * Like {@link #clearContainer(String)} except you can use options to do things like recursive\n     * deletes, or clear at a different path than root.\n     *\n     * @param container\n     *           what to clear\n     * @param options\n     *           recursion and path to clear\n     */\n    void clearContainer(String container, ListContainerOptions options);\n\n    /** @return StorageMetadata associated with a container name, e.g., creation date and location, or null if container does not exist */\n    StorageMetadata getContainerMetadata(String container);\n\n    /**\n     * Return true if a blob named by key exists\n     * @param container\n     * @param key\n     * @return\n     */\n    boolean blobExists(String container, String key);\n\n    /**\n     * Returns all the blobs key inside a container\n     * @param container\n     * @return\n     * @throws IOException\n     */\n    Iterable<String> getBlobKeysInsideContainer(String container, String prefix, String delimiter) throws IOException;\n\n    /**\n     * Load the blob with the given key belonging to the container with the given\n     * name. There must exist a resource on the file system whose complete name\n     * is given concatenating the container name and the key\n     *\n     * @param container\n     *           it's the name of the container the blob belongs to\n     * @param key\n     *           it's the key of the blob\n     *\n     * @return the blob belonging to the given container with the given key\n     */\n    Blob getBlob(String containerName, String blobName);\n\n    @Deprecated\n    String putBlob(String containerName, Blob blob) throws IOException;\n\n    /**\n     * Write a {@link Blob} into a file\n     * @param container\n     * @param blob\n     * @param access\n     * @return etag of blob\n     * @throws IOException\n     */\n    String putBlob(String containerName, Blob blob, BlobAccess access) throws IOException;\n\n    /**\n     * Remove blob named by the given key\n     * @param container\n     * @param key\n     */\n    void removeBlob(String container, String key);\n\n    BlobAccess getBlobAccess(String container, String key);\n\n    void setBlobAccess(String container, String key, BlobAccess access);\n\n    /**\n     * @param containerName name of container\n     * @return Location of container or null\n     */\n    Location getLocation(String containerName);\n\n    /** @return path separator, either / or \\ */\n    String getSeparator();\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/TransientApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore;\n\nimport java.net.URI;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.apis.internal.BaseApiMetadata;\nimport org.jclouds.blobstore.config.TransientBlobStoreContextModule;\n\nimport com.google.auto.service.AutoService;\n\n/**\n * Implementation of {@link ApiMetadata} for jclouds in-memory (Transient) API\n */\n@AutoService(ApiMetadata.class)\npublic class TransientApiMetadata extends BaseApiMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return new Builder().fromApiMetadata(this);\n   }\n\n   public TransientApiMetadata() {\n      super(new Builder());\n   }\n\n   protected TransientApiMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static class Builder extends BaseApiMetadata.Builder<Builder> {\n\n      protected Builder() {\n         id(\"transient\")\n         .name(\"in-memory (Transient) API\")\n         .identityName(\"Unused\")\n         .defaultEndpoint(\"http://localhost\")\n         .defaultIdentity(System.getProperty(\"user.name\"))\n         .defaultCredential(\"bar\")\n         .version(\"1\")\n         .view(BlobStoreContext.class)\n         .defaultModule(TransientBlobStoreContextModule.class)\n         .documentation(URI.create(\"http://www.jclouds.org/documentation/userguide/blobstore-guide\"));\n      }\n\n      @Override\n      public TransientApiMetadata build() {\n         return new TransientApiMetadata(this);\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/TransientStorageStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.io.BaseEncoding.base16;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.Collection;\nimport java.util.Date;\nimport java.util.Map;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentMap;\nimport java.util.concurrent.ConcurrentSkipListMap;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.BlobAccess;\nimport org.jclouds.blobstore.domain.Blob.Factory;\nimport org.jclouds.blobstore.domain.ContainerAccess;\nimport org.jclouds.blobstore.domain.MutableStorageMetadata;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.domain.StorageType;\nimport org.jclouds.blobstore.domain.internal.MutableStorageMetadataImpl;\nimport org.jclouds.blobstore.options.CreateContainerOptions;\nimport org.jclouds.blobstore.options.ListContainerOptions;\nimport org.jclouds.blobstore.util.BlobStoreUtils;\nimport org.jclouds.date.DateService;\nimport org.jclouds.domain.Location;\nimport org.jclouds.http.HttpUtils;\nimport org.jclouds.io.ContentMetadataCodec;\nimport org.jclouds.io.MutableContentMetadata;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.util.Closeables2;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Multimaps;\nimport com.google.common.hash.HashCode;\nimport com.google.common.hash.Hashing;\nimport com.google.common.hash.HashingInputStream;\nimport com.google.common.io.ByteSource;\nimport com.google.common.io.ByteStreams;\nimport com.google.common.net.HttpHeaders;\n\npublic class TransientStorageStrategy implements LocalStorageStrategy {\n   private final ConcurrentMap<String, ConcurrentSkipListMap<String, Blob>> containerToBlobs = new ConcurrentHashMap<String, ConcurrentSkipListMap<String, Blob>>();\n   private final ConcurrentMap<String, ConcurrentMap<String, BlobAccess>> containerToBlobAccess = new ConcurrentHashMap<String, ConcurrentMap<String, BlobAccess>>();\n   private final ConcurrentMap<String, StorageMetadata> containerMetadata = new ConcurrentHashMap<String, StorageMetadata>();\n   private final ConcurrentMap<String, ContainerAccess> containerAccessMap = new ConcurrentHashMap<String, ContainerAccess>();\n   private final Supplier<Location> defaultLocation;\n   private final DateService dateService;\n   private final Factory blobFactory;\n   private final ContentMetadataCodec contentMetadataCodec;\n\n   @Inject\n   TransientStorageStrategy(Supplier<Location> defaultLocation, DateService dateService, Factory blobFactory,\n         ContentMetadataCodec contentMetadataCodec) {\n      this.defaultLocation = defaultLocation;\n      this.dateService = dateService;\n      this.blobFactory = blobFactory;\n      this.contentMetadataCodec = contentMetadataCodec;\n   }\n\n   @Override\n   public boolean containerExists(final String containerName) {\n      return containerToBlobs.containsKey(containerName);\n   }\n\n   @Override\n   public Collection<String> getAllContainerNames() {\n      return containerToBlobs.keySet();\n   }\n\n   @Override\n   public boolean createContainerInLocation(String containerName, Location location, CreateContainerOptions options) {\n      ConcurrentMap<String, Blob> origValue = containerToBlobs.putIfAbsent(\n            containerName, new ConcurrentSkipListMap<String, Blob>());\n      if (origValue != null) {\n         return false;\n      }\n      containerToBlobAccess.putIfAbsent(containerName, new ConcurrentHashMap<String, BlobAccess>());\n\n      MutableStorageMetadata metadata = new MutableStorageMetadataImpl();\n      metadata.setName(containerName);\n      metadata.setType(StorageType.CONTAINER);\n      metadata.setLocation(location);\n      metadata.setCreationDate(new Date());\n      containerMetadata.put(containerName, metadata);\n\n      containerAccessMap.put(containerName, options.isPublicRead()\n            ? ContainerAccess.PUBLIC_READ : ContainerAccess.PRIVATE);\n      return true;\n   }\n\n   @Override\n   public ContainerAccess getContainerAccess(String container) {\n      ContainerAccess access = containerAccessMap.get(container);\n      return access == null ? ContainerAccess.PRIVATE : access;\n   }\n\n   @Override\n   public void setContainerAccess(String container, ContainerAccess access) {\n      containerAccessMap.put(container, access);\n   }\n\n   @Override\n   public void deleteContainer(final String containerName) {\n      containerToBlobs.remove(containerName);\n      containerToBlobAccess.remove(containerName);\n   }\n\n   @Override\n   public void clearContainer(final String containerName) {\n      clearContainer(containerName, ListContainerOptions.Builder.recursive());\n   }\n\n   @Override\n   public void clearContainer(String containerName, ListContainerOptions options) {\n      // TODO implement options\n      containerToBlobs.get(containerName).clear();\n   }\n\n   @Override\n   public StorageMetadata getContainerMetadata(String container) {\n      return containerMetadata.get(container);\n   }\n\n   @Override\n   public boolean blobExists(final String containerName, final String blobName) {\n      Map<String, Blob> map = containerToBlobs.get(containerName);\n      return map != null && map.containsKey(blobName);\n   }\n\n   @Override\n   public Iterable<String> getBlobKeysInsideContainer(final String containerName, String prefix, String delimiter) {\n      ConcurrentSkipListMap<String, Blob> blobs = containerToBlobs.get(containerName);\n      if (prefix == null) {\n         return blobs.keySet();\n      }\n      String lastPrefix = prefix + (char) 65535;  // TODO: better sentinel?\n      return blobs.subMap(prefix, /*fromInclusive=*/ true, lastPrefix, /*toInclusive=*/ false).keySet();\n   }\n\n   @Override\n   public Blob getBlob(final String containerName, final String blobName) {\n      Map<String, Blob> map = containerToBlobs.get(containerName);\n      if (map == null) {\n         return null;\n      }\n      Blob blob = map.get(blobName);\n      if (blob == null) {\n         return null;\n      }\n\n      // Deep copy Blob to make sure ByteSourcePayload does not share Closer.\n      Payload payload = blob.getPayload();\n      MutableContentMetadata md = payload.getContentMetadata();\n      Blob newBlob = blobFactory.create(BlobStoreUtils.copy(blob.getMetadata()));\n      Payload newPayload = Payloads.newPayload(payload.getRawContent());\n      newBlob.setPayload(payload);\n      HttpUtils.copy(md, newPayload.getContentMetadata());\n      return newBlob;\n   }\n\n   @Override\n   public String putBlob(final String containerName, final Blob blob) throws IOException {\n      return putBlob(containerName, blob, BlobAccess.PRIVATE);\n   }\n\n   @Override\n   public String putBlob(final String containerName, final Blob blob, BlobAccess access) throws IOException {\n      byte[] payload;\n      HashCode actualHashCode;\n      HashingInputStream input = new HashingInputStream(Hashing.md5(), blob.getPayload().openStream());\n      try {\n         payload = ByteStreams.toByteArray(input);\n         long actualSize = payload.length;\n         Long expectedSize = blob.getMetadata().getContentMetadata().getContentLength();\n         if (expectedSize != null && actualSize != expectedSize) {\n            throw new IOException(\"Content-Length mismatch, actual: \" + actualSize +\n                  \" expected: \" + expectedSize);\n         }\n         actualHashCode = input.hash();\n         HashCode expectedHashCode = blob.getPayload().getContentMetadata().getContentMD5AsHashCode();\n         if (expectedHashCode != null && !actualHashCode.equals(expectedHashCode)) {\n            throw new IOException(\"MD5 hash code mismatch, actual: \" + actualHashCode +\n                  \" expected: \" + expectedHashCode);\n         }\n      } finally {\n         Closeables2.closeQuietly(input);\n      }\n\n      String eTag = null;\n      if (blob.getMetadata() != null) {\n         eTag = blob.getMetadata().getETag();\n      }\n      if (eTag == null) {\n         eTag = base16().lowerCase().encode(actualHashCode.asBytes());\n      }\n      Blob newBlob = createUpdatedCopyOfBlobInContainer(containerName, blob, payload, actualHashCode, eTag);\n      Map<String, Blob> map = containerToBlobs.get(containerName);\n      String blobName = newBlob.getMetadata().getName();\n      map.put(blobName, newBlob);\n      containerToBlobAccess.get(containerName).put(blobName, access);\n      return base16().lowerCase().encode(actualHashCode.asBytes());\n   }\n\n   @Override\n   public void removeBlob(final String containerName, final String blobName) {\n      Map<String, Blob> map = containerToBlobs.get(containerName);\n      if (map != null)\n         map.remove(blobName);\n   }\n\n   @Override\n   public BlobAccess getBlobAccess(String containerName, String blobName) {\n      Map<String, BlobAccess> map = containerToBlobAccess.get(containerName);\n      if (map == null) {\n         throw new ContainerNotFoundException(containerName, \"in getBlobAccess\");\n      }\n      BlobAccess access = map.get(blobName);\n      if (access == null) {\n         throw new KeyNotFoundException(containerName, blobName, \"in getBlobAccess\");\n      }\n      return access;\n   }\n\n   @Override\n   public void setBlobAccess(String containerName, String blobName, BlobAccess access) {\n      Map<String, BlobAccess> map = containerToBlobAccess.get(containerName);\n      if (map == null) {\n         throw new ContainerNotFoundException(containerName, \"in setBlobAccess\");\n      }\n      map.put(blobName, access);\n   }\n\n   @Override\n   public Location getLocation(final String containerName) {\n      return containerMetadata.get(containerName).getLocation();\n   }\n\n   @Override\n   public String getSeparator() {\n      return \"/\";\n   }\n\n   private Blob createUpdatedCopyOfBlobInContainer(String containerName, Blob in, byte[] input, HashCode contentMd5, String eTag) {\n      checkNotNull(containerName, \"containerName\");\n      checkNotNull(in, \"blob\");\n      checkNotNull(input, \"input\");\n      checkNotNull(contentMd5, \"contentMd5\");\n      checkNotNull(eTag, \"eTag\");\n      Payload payload = createPayload(input);\n      MutableContentMetadata oldMd = in.getPayload().getContentMetadata();\n      HttpUtils.copy(oldMd, payload.getContentMetadata());\n      payload.getContentMetadata().setContentMD5(contentMd5);\n      payload.getContentMetadata().setContentLength((long) input.length);\n      Blob blob = blobFactory.create(BlobStoreUtils.copy(in.getMetadata()));\n      blob.setPayload(payload);\n      blob.getMetadata().setContainer(containerName);\n      blob.getMetadata().setLastModified(new Date());\n      blob.getMetadata().setSize((long) input.length);\n      blob.getMetadata().setETag(eTag);\n      // Set HTTP headers to match metadata\n      blob.getAllHeaders().replaceValues(HttpHeaders.LAST_MODIFIED,\n               ImmutableList.of(dateService.rfc822DateFormat(blob.getMetadata().getLastModified())));\n      blob.getAllHeaders().replaceValues(HttpHeaders.ETAG, ImmutableList.of(eTag));\n      copyPayloadHeadersToBlob(payload, blob);\n      blob.getAllHeaders().putAll(Multimaps.forMap(blob.getMetadata().getUserMetadata()));\n      return blob;\n   }\n\n   private static final class RepeatingByteSource extends ByteSource {\n      private final byte ch;\n\n      RepeatingByteSource(byte ch) {\n         this.ch = ch;\n      }\n\n      @Override\n      public InputStream openStream() {\n         return new RepeatingInputStream(ch);\n      }\n   }\n\n   /** @return Payload of input, possibly optimized for sparse regions (ASCII NULs) */\n   private static Payload createPayload(byte[] input) {\n      for (int i = 0; i < input.length; ++i) {\n         if (input[i] != (byte) 0) {\n            return Payloads.newByteArrayPayload(input);\n         }\n      }\n\n      // all bytes are NUL\n      return Payloads.newByteSourcePayload(new RepeatingByteSource((byte) 0).slice(0, input.length));\n   }\n\n   private static final class RepeatingInputStream extends InputStream {\n      private final byte ch;\n\n      RepeatingInputStream(byte ch) {\n         this.ch = ch;\n      }\n\n      @Override\n      public int read() throws IOException {\n         return ch;\n      }\n\n      @Override\n      public int read(byte[] b, int off, int len) {\n         for (int i = 0; i < len; ++i) {\n            b[off + i] = ch;\n         }\n         return len;\n      }\n   }\n\n   private void copyPayloadHeadersToBlob(Payload payload, Blob blob) {\n      blob.getAllHeaders().putAll(contentMetadataCodec.toHeaders(payload.getContentMetadata()));\n   }\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/attr/BlobCapabilities.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.attr;\n\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.ElementType.TYPE;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\n@Target( { TYPE, METHOD })\n@Retention(RUNTIME)\npublic @interface BlobCapabilities {\n   BlobCapability [] value();\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/attr/BlobCapability.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.attr;\n\n/**\n * Represents the capabilities of a BlobStore\n */\npublic enum BlobCapability {\n\n   /**\n    * supports\n    */\n   CONDITIONAL_MATCH,\n   \n   /**\n    * receive pieces of a blob via Content-Range header\n    */\n   CONDITIONAL_DATE,\n   \n   /**\n    * receive pieces of a blob via Content-Range header\n    */\n   GET_RANGE,\n\n   /**\n    * replace pieces of a blob via Content-Range header\n    */\n   PUT_RANGE,\n\n   /**\n    * Enable \"chunked\"/\"streamed\" data, where the size needn't be known in advance.\n    */\n   CHUNKED_ENCODING,\n\n   /**\n    * blobs can have key-value pairs associated with them\n    */\n   METADATA,\n\n   /**\n    * blobs have an etag associated with them\n    */\n   ETAG,\n\n   /**\n    * blobs have a system generated ID associated with them\n    */\n   ID,\n\n   /**\n    * blobstore stores Content-MD5 header\n    */\n   MD5,\n\n   /**\n    * etag is the same value as the MD5 of the object\n    */\n   ETAG_EQUALS_MD5,\n\n   /**\n    * blobs will have last modified date associated with them\n    */\n   LAST_MODIFIED,\n\n   /**\n    * timestamps are precise in milliseconds (as opposed to seconds)\n    */\n   MILLISECOND_PRECISION,\n\n   /**\n    * blob size in bytes is exposed by service listing\n    */\n   SIZE,\n\n\n   /**\n    * possible to expose blobs to anonymous access\n    */\n   PUBLIC\n\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/attr/BlobScope.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.attr;\n\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.ElementType.TYPE;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\n@Target( { TYPE, METHOD })\n@Retention(RUNTIME)\npublic @interface BlobScope {\n   BlobScopes value();\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/attr/BlobScopes.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.attr;\n\n/**\n * Represents the ways a Blob is named.\n */\npublic enum BlobScopes {\n\n   /**\n    * Path to a blob is relative to the container\n    */\n   CONTAINER,\n   /**\n    * Path to a blob is relative to the container\n    */\n   FOLDER\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/attr/Charge.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.attr;\n\n/**\n * Represents the ways a BlobStore are charged.\n */\npublic enum Charge {\n\n   /**\n    * fees are incurred on basis of requests\n    */\n   REQUEST,\n   /**\n    * fees are incurred on basis of bytes stored\n    */\n   STORE,\n   /**\n    * fees are incurred on basis of bytes input into the system\n    */\n   IN,\n   /**\n    * fees are incurred on basis of bytes output from the system\n    */\n   OUT\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/attr/Charges.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.attr;\n\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.ElementType.TYPE;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\n@Target( { TYPE, METHOD })\n@Retention(RUNTIME)\npublic @interface Charges {\n   Charge value();\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/attr/ConsistencyModel.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.attr;\n\n/**\n * Represents the ways data can become consistent in distributed systems.\n */\npublic enum ConsistencyModel {\n\n   /**\n    * Eventually, all updates will propagate through the system. However, reads do not always return\n    * the latest write.\n    */\n   EVENTUAL,\n   /**\n    * Reads return the latest write.\n    */\n   STRICT\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/attr/ContainerCapabilities.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.attr;\n\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.ElementType.TYPE;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\n@Target( { TYPE, METHOD })\n@Retention(RUNTIME)\npublic @interface ContainerCapabilities {\n   ContainerCapability value();\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/attr/ContainerCapability.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.attr;\n\n/**\n * Represents the capabilities of a BlobStore\n */\npublic enum ContainerCapability {\n\n   /**\n    * deletion of a container is recursive\n    */\n   RECURSIVE_DELETE,\n\n   /**\n    * There's a container that exists at the root of the service\n    */\n   ROOTCONTAINER,\n\n   /**\n    * Containers (and subcontainers) are created implicitly\n    */\n   SKIP_CREATE_CONTAINER,\n\n   /**\n    * containers can have key-value pairs associated with them\n    */\n   METADATA,\n\n   /**\n    * containers have an etag associated with them\n    */\n   ETAG,\n\n   /**\n    * containers have a system generated ID associated with them\n    */\n   ID,\n\n   /**\n    * container will have last modified date associated with them\n    */\n   LAST_MODIFIED,\n\n\n   /**\n    * timestamps are precise in milliseconds (as opposed to seconds)\n    */\n   MILLISECOND_PRECISION,\n\n   /**\n    * container size in bytes is exposed by service listing\n    */\n   SIZE,\n\n\n   /**\n    * possible to expose a container to anonymous access\n    */\n   PUBLIC\n\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/attr/ContainerVisibilities.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.attr;\n\n/**\n * Represents the ways a container is scoped\n */\npublic enum ContainerVisibilities {\n\n   /**\n    * Container namespace is shared by the general public and therefore has highest likelihood of\n    * collision. Containers created in public namespace are not deletable by other identitys.\n    */\n   PUBLIC,\n   /**\n    * Container namespace is shared within an identity and therefore all containers are deletable by\n    * the identity.\n    */\n   ACCOUNT\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/attr/ContainerVisibility.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.attr;\n\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.ElementType.TYPE;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\n@Target( { TYPE, METHOD })\n@Retention(RUNTIME)\npublic @interface ContainerVisibility {\n   ContainerVisibilities value();\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/attr/FolderCapability.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.attr;\n\n/**\n * Represents the capabilities of a BlobStore\n */\npublic enum FolderCapability {\n\n   /**\n    * deletion of a container is recursive\n    */\n   RECURSIVE_DELETE,\n\n   /**\n    * There's a container that exists at the root of the service\n    */\n   ROOTCONTAINER,\n\n   /**\n    * Containers (and subcontainers) are created implicitly\n    */\n   SKIP_CREATE_CONTAINER,\n\n   /**\n    * containers can have key-value pairs associated with them\n    */\n   METADATA,\n\n   /**\n    * containers have an etag associated with them\n    */\n   ETAG,\n\n   /**\n    * containers have a system generated ID associated with them\n    */\n   ID,\n\n   /**\n    * container will have last modified date associated with them\n    */\n   LAST_MODIFIED,\n\n\n   /**\n    * timestamps are precise in milliseconds (as opposed to seconds)\n    */\n   MILLISECOND_PRECISION,\n\n   /**\n    * container size in bytes is exposed by service listing\n    */\n   SIZE,\n\n\n   /**\n    * possible to expose a container to anonymous access\n    */\n   PUBLIC\n\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/binders/BindBlobToMultipartForm.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.io.payloads.MultipartForm;\nimport org.jclouds.io.payloads.Part;\nimport org.jclouds.io.payloads.Part.PartOptions;\nimport org.jclouds.rest.Binder;\n\n@Singleton\npublic class BindBlobToMultipartForm implements Binder {\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkArgument(checkNotNull(input, \"input\") instanceof Blob, \"this binder is only valid for Blobs!\");\n      checkNotNull(request, \"request\");\n      Blob blob = Blob.class.cast(input);\n\n      Part part = Part.create(blob.getMetadata().getName(), blob.getPayload(),\n            new PartOptions().contentType(blob.getMetadata().getContentMetadata().getContentType()));\n\n      request.setPayload(new MultipartForm(part));\n      return request;\n   }\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/binders/BindMapToHeadersWithPrefix.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.blobstore.reference.BlobStoreConstants.PROPERTY_USER_METADATA_PREFIX;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\nimport org.jclouds.util.Maps2;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.Multimaps;\n\n@Singleton\npublic class BindMapToHeadersWithPrefix implements Binder {\n   private final Function<String, String> fn;\n\n   @Inject\n   public BindMapToHeadersWithPrefix(@Named(PROPERTY_USER_METADATA_PREFIX) final String metadataPrefix) {\n      checkNotNull(metadataPrefix, PROPERTY_USER_METADATA_PREFIX);\n      fn = new Function<String, String>() {\n\n         @Override\n         public String apply(String arg0) {\n            String inLowercase = arg0.toLowerCase();\n            return (inLowercase.startsWith(metadataPrefix)) ? inLowercase : metadataPrefix + inLowercase;\n         }\n\n         @Override\n         public String toString() {\n            return \"prefix: \" + metadataPrefix;\n         }\n\n      };\n\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkArgument(checkNotNull(input, \"input\") instanceof Map<?, ?>, \"this binder is only valid for Maps!\");\n      checkNotNull(request, \"request\");\n\n      Map<String, String> userMetadata = Maps2.transformKeys((Map<String, String>) input, fn);\n      return (R) request.toBuilder().replaceHeaders(Multimaps.forMap(userMetadata)).build();\n   }\n\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/binders/BindUserMetadataToHeadersWithPrefix.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\n@Singleton\npublic class BindUserMetadataToHeadersWithPrefix implements Binder {\n   private final BindMapToHeadersWithPrefix metadataPrefixer;\n\n   @Inject\n   public BindUserMetadataToHeadersWithPrefix(BindMapToHeadersWithPrefix metadataPrefixer) {\n      this.metadataPrefixer = checkNotNull(metadataPrefixer, \"metadataPrefixer\");\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkArgument(checkNotNull(input, \"input\") instanceof Blob, \"this binder is only valid for Blobs!\");\n      checkNotNull(request, \"request\");\n      return metadataPrefixer.bindToRequest(request, Blob.class.cast(input).getMetadata().getUserMetadata());\n   }\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/config/BlobStoreObjectModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.config;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Provider;\n\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.MutableBlobMetadata;\nimport org.jclouds.blobstore.domain.internal.BlobImpl;\n\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Provides;\nimport com.google.inject.Scopes;\n\n/**\n * Configures the domain object mappings needed for all Blob implementations\n */\npublic class BlobStoreObjectModule extends AbstractModule {\n\n   /**\n    * explicit factories are created here as it has been shown that Assisted Inject is extremely\n    * inefficient. http://code.google.com/p/google-guice/issues/detail?id=435\n    */\n   @Override\n   protected void configure() {\n      bind(Blob.Factory.class).to(BlobFactory.class).in(Scopes.SINGLETON);\n   }\n\n   private static class BlobFactory implements Blob.Factory {\n\n      @Inject\n      Provider<MutableBlobMetadata> metadataProvider;\n\n      public Blob create(MutableBlobMetadata metadata) {\n         return new BlobImpl(metadata != null ? metadata : metadataProvider.get());\n      }\n   }\n\n   @Provides\n   final Blob provideBlob(Blob.Factory factory) {\n      return factory.create(null);\n   }\n\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/config/LocalBlobStore.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.config;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.common.base.Throwables.getCausalChain;\nimport static com.google.common.base.Throwables.propagate;\nimport static com.google.common.collect.Iterables.size;\nimport static com.google.common.collect.Iterables.transform;\nimport static com.google.common.collect.Iterables.tryFind;\nimport static com.google.common.collect.Sets.filter;\nimport static com.google.common.collect.Sets.newTreeSet;\nimport static org.jclouds.blobstore.options.ListContainerOptions.Builder.recursive;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Date;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.SortedSet;\nimport java.util.UUID;\nimport java.util.concurrent.ExecutorService;\n\nimport jakarta.annotation.Resource;\nimport jakarta.ws.rs.core.Response.Status;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport com.google.common.hash.Hasher;\nimport com.google.common.hash.Hashing;\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.BlobStoreContext;\nimport org.jclouds.blobstore.ContainerNotFoundException;\nimport org.jclouds.blobstore.KeyNotFoundException;\nimport org.jclouds.blobstore.LocalStorageStrategy;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.BlobAccess;\nimport org.jclouds.blobstore.domain.BlobBuilder;\nimport org.jclouds.blobstore.domain.BlobBuilder.PayloadBlobBuilder;\nimport org.jclouds.blobstore.domain.BlobMetadata;\nimport org.jclouds.blobstore.domain.ContainerAccess;\nimport org.jclouds.blobstore.domain.MultipartPart;\nimport org.jclouds.blobstore.domain.MultipartUpload;\nimport org.jclouds.blobstore.domain.MutableBlobMetadata;\nimport org.jclouds.blobstore.domain.MutableStorageMetadata;\nimport org.jclouds.blobstore.domain.PageSet;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.domain.StorageType;\nimport org.jclouds.blobstore.domain.Tier;\nimport org.jclouds.blobstore.domain.internal.MutableStorageMetadataImpl;\nimport org.jclouds.blobstore.domain.internal.PageSetImpl;\nimport org.jclouds.blobstore.options.CopyOptions;\nimport org.jclouds.blobstore.options.CreateContainerOptions;\nimport org.jclouds.blobstore.options.GetOptions;\nimport org.jclouds.blobstore.options.ListContainerOptions;\nimport org.jclouds.blobstore.options.PutOptions;\nimport org.jclouds.blobstore.util.BlobStoreUtils;\nimport org.jclouds.blobstore.util.BlobUtils;\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.domain.Location;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.http.HttpUtils;\nimport org.jclouds.io.ByteStreams2;\nimport org.jclouds.io.ContentMetadata;\nimport org.jclouds.io.ContentMetadataCodec;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.payloads.InputStreamPayload;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.util.Closeables2;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Predicates;\nimport com.google.common.base.Strings;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Throwables;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Iterables;\nimport com.google.common.io.BaseEncoding;\nimport com.google.common.io.ByteSource;\nimport com.google.common.net.HttpHeaders;\n\n@Singleton\npublic final class LocalBlobStore implements BlobStore {\n   private static final String MULTIPART_PREFIX = \".mpus-\";\n\n   @Resource\n   private Logger logger = Logger.NULL;\n\n   private final BlobStoreContext context;\n   private final BlobUtils blobUtils;\n   private final Supplier<Set<? extends Location>> locations;\n   private final ContentMetadataCodec contentMetadataCodec;\n   private final Blob.Factory blobFactory;\n   private final LocalStorageStrategy storageStrategy;\n\n   @Inject\n   LocalBlobStore(BlobStoreContext context,\n         BlobUtils blobUtils,\n         @Memoized Supplier<Set<? extends Location>> locations,\n         ContentMetadataCodec contentMetadataCodec,\n         Blob.Factory blobFactory, LocalStorageStrategy storageStrategy) {\n      this.context = checkNotNull(context, \"context\");\n      this.blobUtils = checkNotNull(blobUtils, \"blobUtils\");\n      this.locations = checkNotNull(locations, \"locations\");\n      this.blobFactory = blobFactory;\n      this.contentMetadataCodec = contentMetadataCodec;\n      this.storageStrategy = storageStrategy;\n   }\n\n   @Override\n   public BlobStoreContext getContext() {\n      return context;\n   }\n\n   @Override\n   public BlobBuilder blobBuilder(String name) {\n      return blobUtils.blobBuilder().name(name);\n   }\n\n   /** This implementation invokes {@link #list(String, ListContainerOptions)} */\n   @Override\n   public PageSet<? extends StorageMetadata> list(String containerName) {\n      return this.list(containerName, ListContainerOptions.NONE);\n   }\n\n   /**\n    * This implementation invokes {@link #countBlobs} with the\n    * {@link ListContainerOptions#recursive} option.\n    */\n   @Override\n   public long countBlobs(String containerName) {\n      return countBlobs(containerName, recursive());\n   }\n\n   /**\n    * This implementation invokes {@link BlobUtils#countBlobs}\n    */\n   @Override\n   public long countBlobs(final String containerName, final ListContainerOptions options) {\n      return blobUtils.countBlobs(containerName, options);\n   }\n\n   /**\n    * This implementation invokes {@link #clearContainer} with the\n    * {@link ListContainerOptions#recursive} option.\n    */\n   @Override\n   public void clearContainer(String containerName) {\n      clearContainer(containerName, recursive());\n   }\n\n   @Override\n   public void clearContainer(String containerName, ListContainerOptions options) {\n      blobUtils.clearContainer(containerName, options);\n   }\n\n   @Override\n   public void deleteDirectory(final String containerName, final String directory) {\n      blobUtils.deleteDirectory(containerName, directory);\n   }\n\n   @Override\n   public boolean directoryExists(String containerName, String directory) {\n      return blobUtils.directoryExists(containerName, directory);\n   }\n\n   @Override\n   public void createDirectory(String containerName, String directory) {\n      if (!blobUtils.directoryExists(containerName, directory)) {\n         blobUtils.createDirectory(containerName, directory);\n      }\n   }\n\n   /**\n    * This implementation invokes {@link #getBlob(String,String, GetOptions)}\n    */\n   @Override\n   public Blob getBlob(String containerName, String key) {\n      return getBlob(containerName, key, GetOptions.NONE);\n   }\n\n   /**\n    * This implementation invokes {@link #deleteAndVerifyContainerGone}\n    */\n   @Override\n   public void deleteContainer(String containerName) {\n      deleteAndVerifyContainerGone(containerName);\n   }\n\n   @Override\n   public Set<? extends Location> listAssignableLocations() {\n      return locations.get();\n   }\n\n   /**\n    * default maxResults is 1000\n    */\n   @Override\n   public PageSet<? extends StorageMetadata> list(final String containerName, ListContainerOptions options) {\n      if (options.getDir() != null && options.getPrefix() != null) {\n         throw new IllegalArgumentException(\"Cannot set both prefix and directory\");\n      }\n\n      if ((options.getDir() != null || options.isRecursive()) && (options.getDelimiter() != null)) {\n         throw new IllegalArgumentException(\"Cannot set the delimiter if directory or recursive is set\");\n      }\n\n      // Check if the container exists\n      if (!storageStrategy.containerExists(containerName))\n         throw cnfe(containerName);\n\n      // Loading blobs from container\n      Iterable<String> blobBelongingToContainer = null;\n      try {\n         blobBelongingToContainer = storageStrategy.getBlobKeysInsideContainer(containerName, options.getPrefix(), options.getDelimiter());\n      } catch (IOException e) {\n         logger.error(e, \"An error occurred loading blobs contained into container %s\", containerName);\n         propagate(e);\n      }\n\n      SortedSet<StorageMetadata> contents = newTreeSet(FluentIterable.from(blobBelongingToContainer)\n            .transform(new Function<String, StorageMetadata>() {\n               @Override\n               public StorageMetadata apply(String key) {\n                  Blob oldBlob = loadBlob(containerName, key);\n                  if (oldBlob == null) {\n                     return null;\n                  }\n                  checkState(oldBlob.getMetadata() != null, \"blob \" + containerName + \"/\" + key + \" has no metadata\");\n                  MutableBlobMetadata md = BlobStoreUtils.copy(oldBlob.getMetadata());\n                  md.setSize(oldBlob.getMetadata().getSize());\n                  return md;\n               }\n            })\n            .filter(Predicates.<StorageMetadata>notNull()));\n\n      String marker = null;\n      if (options != null) {\n         if (options.getDir() != null && !options.getDir().isEmpty()) {\n            contents = filterDirectory(contents, options);\n         } else if (!Strings.isNullOrEmpty(options.getPrefix())) {\n            contents = filterPrefix(contents, options);\n         } else if (!options.isRecursive() || (options.getDelimiter() != null)) {\n            String delimiter = options.getDelimiter() == null ? storageStrategy.getSeparator() : options.getDelimiter();\n            contents = extractCommonPrefixes(contents, delimiter, null);\n         }\n\n         if (options.getMarker() != null) {\n            final String finalMarker = options.getMarker();\n            String delimiter = storageStrategy.getSeparator();\n            Optional<StorageMetadata> lastMarkerMetadata = tryFind(contents, new Predicate<StorageMetadata>() {\n               public boolean apply(StorageMetadata metadata) {\n                  return metadata.getName().compareTo(finalMarker) > 0;\n               }\n            });\n            if (lastMarkerMetadata.isPresent()) {\n               contents = contents.tailSet(lastMarkerMetadata.get());\n            } else {\n               // marker is after last key or container is empty\n               contents.clear();\n            }\n         }\n\n         int maxResults = options.getMaxResults() != null ? options.getMaxResults() : 1000;\n         if (!contents.isEmpty()) {\n            StorageMetadata lastElement = contents.last();\n            contents = newTreeSet(Iterables.limit(contents, maxResults));\n            if (maxResults != 0 && !contents.contains(lastElement)) {\n               // Partial listing\n               lastElement = contents.last();\n               marker = lastElement.getName();\n            }\n         }\n\n         // trim metadata, if the response isn't supposed to be detailed.\n         if (!options.isDetailed()) {\n            for (StorageMetadata md : contents) {\n               md.getUserMetadata().clear();\n            }\n         }\n      }\n\n      return new PageSetImpl<StorageMetadata>(contents, marker);\n   }\n\n   private SortedSet<StorageMetadata> filterDirectory(SortedSet<StorageMetadata> contents, ListContainerOptions\n           options) {\n      String prefix = options.getDir();\n      final String dirPrefix = prefix.endsWith(\"/\") ?\n              prefix :\n              prefix + \"/\";\n      contents = newTreeSet(filter(contents, new Predicate<StorageMetadata>() {\n         public boolean apply(StorageMetadata o) {\n            return o != null\n                    && o.getName().replace(File.separatorChar, '/').startsWith(dirPrefix)\n                    && !o.getName().replace(File.separatorChar, '/').equals(dirPrefix);\n         }\n      }));\n\n      if (!options.isRecursive()) {\n         return extractCommonPrefixes(contents, storageStrategy.getSeparator(), dirPrefix);\n      }\n\n      return contents;\n   }\n\n   private SortedSet<StorageMetadata> filterPrefix(SortedSet<StorageMetadata> contents, final ListContainerOptions\n                                                   options) {\n      contents = newTreeSet(filter(contents, new Predicate<StorageMetadata>() {\n         public boolean apply(StorageMetadata o) {\n            return o != null && o.getName().replace(File.separatorChar, '/').startsWith(options.getPrefix());\n         }\n      }));\n\n      if (options.getDelimiter() != null || !options.isRecursive()) {\n          String delimiter = options.getDelimiter() == null ? storageStrategy.getSeparator() : options.getDelimiter();\n          return extractCommonPrefixes(contents, delimiter, options.getPrefix());\n      }\n\n      return contents;\n   }\n\n   private SortedSet<StorageMetadata> extractCommonPrefixes(SortedSet<StorageMetadata> contents, String delimiter,\n                                                            String prefix) {\n      if (Strings.isNullOrEmpty(delimiter)) {\n         return contents;\n      }\n      SortedSet<String> commonPrefixes = newTreeSet(\n              transform(contents, new CommonPrefixes(prefix, delimiter)));\n      commonPrefixes.remove(CommonPrefixes.NO_PREFIX);\n\n      contents = newTreeSet(filter(contents, new DelimiterFilter(prefix, delimiter)));\n\n      for (String o : commonPrefixes) {\n         MutableStorageMetadata md = new MutableStorageMetadataImpl();\n         md.setType(StorageType.RELATIVE_PATH);\n\n         if (prefix != null) {\n            o = prefix + o;\n         }\n         md.setName(o + delimiter);\n         contents.add(md);\n      }\n      return contents;\n   }\n\n   private ContainerNotFoundException cnfe(final String name) {\n      return new ContainerNotFoundException(name, String.format(\n            \"container %s not in %s\", name,\n            storageStrategy.getAllContainerNames()));\n   }\n\n   @Override\n   public void removeBlob(String containerName, final String key) {\n      if (!storageStrategy.containerExists(containerName)) {\n         throw cnfe(containerName);\n      }\n      storageStrategy.removeBlob(containerName, key);\n   }\n\n   @Override\n   public void removeBlobs(String container, Iterable<String> names) {\n      for (String name : names) {\n         removeBlob(container, name);\n      }\n   }\n\n   @Override\n   public BlobAccess getBlobAccess(String container, String name) {\n      return storageStrategy.getBlobAccess(container, name);\n   }\n\n   @Override\n   public void setBlobAccess(String container, String name, BlobAccess access) {\n      storageStrategy.setBlobAccess(container, name, access);\n   }\n\n   @Override\n   public boolean deleteContainerIfEmpty(String containerName) {\n      boolean returnVal = true;\n      if (storageStrategy.containerExists(containerName)) {\n         try {\n            if (Iterables.isEmpty(storageStrategy.getBlobKeysInsideContainer(containerName, null, null)))\n               storageStrategy.deleteContainer(containerName);\n            else\n               returnVal = false;\n         } catch (IOException e) {\n            logger.error(e, \"An error occurred loading blobs contained into container %s\", containerName);\n            throw propagate(e);\n         }\n      }\n      return returnVal;\n   }\n\n   @Override\n   public boolean containerExists(String containerName) {\n      return storageStrategy.containerExists(containerName);\n   }\n\n   @Override\n   public PageSet<? extends StorageMetadata> list() {\n      ArrayList<String> containers = new ArrayList<String>(storageStrategy.getAllContainerNames());\n      Collections.sort(containers);\n\n      return new PageSetImpl<StorageMetadata>(FluentIterable\n            .from(containers)\n            .transform(new Function<String, StorageMetadata>() {\n               @Override\n               public StorageMetadata apply(String name) {\n                  return storageStrategy.getContainerMetadata(name);\n               }\n            })\n            .filter(Predicates.<StorageMetadata>notNull()),\n            null);\n   }\n\n   @Override\n   public boolean createContainerInLocation(Location location, String name) {\n      return storageStrategy.createContainerInLocation(name, location, CreateContainerOptions.NONE);\n   }\n\n   @Override\n   public ContainerAccess getContainerAccess(String container) {\n      return storageStrategy.getContainerAccess(container);\n   }\n\n   @Override\n   public void setContainerAccess(String container, ContainerAccess access) {\n      storageStrategy.setContainerAccess(container, access);\n   }\n\n   private Blob loadBlob(final String container, final String key) {\n      logger.debug(\"Opening blob in container: %s - %s\", container, key);\n      return storageStrategy.getBlob(container, key);\n   }\n\n   private static class DelimiterFilter implements Predicate<StorageMetadata> {\n      private final String prefix;\n      private final String delimiter;\n\n      public DelimiterFilter(String prefix, String delimiter) {\n         this.prefix = prefix;\n         this.delimiter = delimiter;\n      }\n\n      public boolean apply(StorageMetadata metadata) {\n         String name = metadata.getName();\n         if (prefix == null || prefix.isEmpty()) {\n            return name.indexOf(delimiter) == -1 || name.indexOf(delimiter) == name.length() - delimiter.length();\n         }\n         if (name.startsWith(prefix)) {\n            String unprefixedName = name.substring(prefix.length());\n            if (unprefixedName.equals(\"\")) {\n               // a blob that matches the prefix should also be returned\n               return true;\n            }\n            return unprefixedName.indexOf(delimiter) == -1 || unprefixedName.indexOf(delimiter) == unprefixedName.length() - delimiter.length();\n         }\n         return false;\n      }\n   }\n\n   private static class CommonPrefixes implements Function<StorageMetadata, String> {\n      private final String prefix;\n      private final String delimiter;\n      public static final String NO_PREFIX = \"NO_PREFIX\";\n\n      public CommonPrefixes(String prefix, String delimiter) {\n         this.prefix = prefix;\n         this.delimiter = delimiter;\n      }\n\n      public String apply(StorageMetadata metadata) {\n         String working = metadata.getName();\n         if (prefix != null) {\n            if (working.startsWith(prefix)) {\n               working = working.substring(prefix.length());\n            } else {\n               return NO_PREFIX;\n            }\n         }\n         if (working.indexOf(delimiter) >= 0) {\n            // not include the delimiter in the result\n            return working.substring(0, working.indexOf(delimiter));\n         } else {\n            return NO_PREFIX;\n         }\n      }\n   }\n\n   private static HttpResponseException returnResponseException(int code) {\n      HttpResponse response = HttpResponse.builder().statusCode(code).build();\n      return new HttpResponseException(new HttpCommand(HttpRequest.builder().method(\"GET\").endpoint(\"http://stub\")\n            .build()), response);\n   }\n\n   @Override\n   public String putBlob(String containerName, Blob blob) {\n      return putBlob(containerName, blob, PutOptions.NONE);\n   }\n\n   @Override\n   public String copyBlob(String fromContainer, String fromName, String toContainer, String toName,\n         CopyOptions options) {\n      Blob blob = getBlob(fromContainer, fromName);\n      if (blob == null) {\n         throw new KeyNotFoundException(fromContainer, fromName, \"while copying\");\n      }\n\n      String eTag = blob.getMetadata().getETag();\n      if (eTag != null) {\n         eTag = maybeQuoteETag(eTag);\n         if (options.ifMatch() != null && !maybeQuoteETag(options.ifMatch()).equals(eTag)) {\n            throw returnResponseException(412);\n         }\n         if (options.ifNoneMatch() != null && maybeQuoteETag(options.ifNoneMatch()).equals(eTag)) {\n            throw returnResponseException(412);\n         }\n      }\n\n      Date lastModified = blob.getMetadata().getLastModified();\n      if (lastModified != null) {\n         if (options.ifModifiedSince() != null && lastModified.compareTo(options.ifModifiedSince()) <= 0) {\n            throw returnResponseException(412);\n         }\n         if (options.ifUnmodifiedSince() != null && lastModified.compareTo(options.ifUnmodifiedSince()) >= 0) {\n            throw returnResponseException(412);\n         }\n      }\n\n      InputStream is = null;\n      try {\n         is = blob.getPayload().openStream();\n         ContentMetadata metadata = blob.getMetadata().getContentMetadata();\n         BlobBuilder.PayloadBlobBuilder builder = blobBuilder(toName)\n               .payload(is);\n         Long contentLength = metadata.getContentLength();\n         if (contentLength != null) {\n            builder.contentLength(contentLength);\n         }\n\n         ContentMetadata contentMetadata = options.contentMetadata();\n         if (contentMetadata != null) {\n            String cacheControl = contentMetadata.getCacheControl();\n            if (cacheControl != null) {\n               builder.cacheControl(cacheControl);\n            }\n            String contentDisposition = contentMetadata.getContentDisposition();\n            if (contentDisposition != null) {\n               builder.contentDisposition(contentDisposition);\n            }\n            String contentEncoding = contentMetadata.getContentEncoding();\n            if (contentEncoding != null) {\n               builder.contentEncoding(contentEncoding);\n            }\n            String contentLanguage = contentMetadata.getContentLanguage();\n            if (contentLanguage != null) {\n               builder.contentLanguage(contentLanguage);\n            }\n            String contentType = contentMetadata.getContentType();\n            if (contentType != null) {\n               builder.contentType(contentType);\n            }\n         } else {\n            builder.cacheControl(metadata.getCacheControl())\n                   .contentDisposition(metadata.getContentDisposition())\n                   .contentEncoding(metadata.getContentEncoding())\n                   .contentLanguage(metadata.getContentLanguage())\n                   .contentType(metadata.getContentType());\n         }\n\n         Map<String, String> userMetadata = options.userMetadata();\n         if (userMetadata != null) {\n            builder.userMetadata(userMetadata);\n         } else {\n            builder.userMetadata(blob.getMetadata().getUserMetadata());\n         }\n         return putBlob(toContainer, builder.build());\n      } catch (IOException ioe) {\n         throw Throwables.propagate(ioe);\n      } finally {\n         Closeables2.closeQuietly(is);\n      }\n   }\n\n   private void copyPayloadHeadersToBlob(Payload payload, Blob blob) {\n      blob.getAllHeaders().putAll(contentMetadataCodec.toHeaders(payload.getContentMetadata()));\n   }\n\n   @Override\n   public boolean blobExists(String containerName, String key) {\n      if (!storageStrategy.containerExists(containerName))\n         throw cnfe(containerName);\n      return storageStrategy.blobExists(containerName, key);\n   }\n\n   @Override\n   public Blob getBlob(String containerName, String key, GetOptions options) {\n      logger.debug(\"Retrieving blob with key %s from container %s\", key, containerName);\n      // If the container doesn't exist, an exception is thrown\n      if (!storageStrategy.containerExists(containerName)) {\n         logger.debug(\"Container %s does not exist\", containerName);\n         throw cnfe(containerName);\n      }\n\n      // If the blob doesn't exist, a null object is returned\n      Blob blob = loadBlob(containerName, key);\n      if (blob == null) {\n         logger.debug(\"Item %s does not exist in container %s\", key, containerName);\n         return null;\n      }\n\n      if (options != null) {\n         String eTag = blob.getMetadata().getETag();\n         if (eTag != null) {\n            eTag = maybeQuoteETag(eTag);\n            if (options.getIfMatch() != null) {\n               if (!eTag.equals(maybeQuoteETag(options.getIfMatch()))) {\n                  HttpResponse response = HttpResponse.builder().statusCode(Status.PRECONDITION_FAILED.getStatusCode()).addHeader(HttpHeaders.ETAG, eTag).build();\n                  throw new HttpResponseException(new HttpCommand(HttpRequest.builder().method(\"GET\").endpoint(\"http://stub\").build()), response);\n               }\n            }\n            if (options.getIfNoneMatch() != null) {\n               if (eTag.equals(maybeQuoteETag(options.getIfNoneMatch()))) {\n                  HttpResponse response = HttpResponse.builder().statusCode(Status.NOT_MODIFIED.getStatusCode()).addHeader(HttpHeaders.ETAG, eTag).build();\n                  throw new HttpResponseException(new HttpCommand(HttpRequest.builder().method(\"GET\").endpoint(\"http://stub\").build()), response);\n               }\n            }\n         }\n         if (options.getIfModifiedSince() != null) {\n            Date modifiedSince = options.getIfModifiedSince();\n            if (blob.getMetadata().getLastModified().before(modifiedSince)) {\n               HttpResponse.Builder response = HttpResponse.builder().statusCode(Status.NOT_MODIFIED.getStatusCode());\n               if (eTag != null) {\n                  response.addHeader(HttpHeaders.ETAG, eTag);\n               }\n               throw new HttpResponseException(String.format(\"%1$s is before %2$s\", blob\n                     .getMetadata().getLastModified(), modifiedSince), null, response.build());\n            }\n\n         }\n         if (options.getIfUnmodifiedSince() != null) {\n            Date unmodifiedSince = options.getIfUnmodifiedSince();\n            if (blob.getMetadata().getLastModified().after(unmodifiedSince)) {\n               HttpResponse.Builder response = HttpResponse.builder().statusCode(Status.PRECONDITION_FAILED.getStatusCode());\n               if (eTag != null) {\n                  response.addHeader(HttpHeaders.ETAG, eTag);\n               }\n               throw new HttpResponseException(String.format(\"%1$s is after %2$s\", blob\n                     .getMetadata().getLastModified(), unmodifiedSince), null, response.build());\n            }\n         }\n         blob = copyBlob(blob);\n\n         if (options.getRanges() != null && !options.getRanges().isEmpty()) {\n            long size = 0;\n            ImmutableList.Builder<ByteSource> streams = ImmutableList.builder();\n\n            // Try to convert payload to ByteSource, otherwise wrap it.\n            ByteSource byteSource;\n            Object object = blob.getPayload().getRawContent();\n            if (object instanceof ByteSource) {\n               byteSource = (ByteSource) object;\n            } else if (object instanceof byte[]) {\n               byteSource = ByteSource.wrap((byte[]) object);\n            } else {\n               // This should not happen.\n               try {\n                  byteSource = ByteSource.wrap(ByteStreams2.toByteArrayAndClose(blob.getPayload().openStream()));\n               } catch (IOException e) {\n                  throw new RuntimeException(e);\n               }\n            }\n\n            for (String s : options.getRanges()) {\n               // HTTP uses a closed interval while Java array indexing uses a\n               // half-open interval.\n               long offset = 0;\n               long last = blob.getPayload().getContentMetadata().getContentLength() - 1;\n               if (s.startsWith(\"-\")) {\n                  offset = last - Long.parseLong(s.substring(1)) + 1;\n                  if (offset < 0) {\n                     offset = 0;\n                  }\n               } else if (s.endsWith(\"-\")) {\n                  offset = Long.parseLong(s.substring(0, s.length() - 1));\n               } else if (s.contains(\"-\")) {\n                  String[] firstLast = s.split(\"\\\\-\");\n                  offset = Long.parseLong(firstLast[0]);\n                  last = Long.parseLong(firstLast[1]);\n               } else {\n                  throw new HttpResponseException(\"illegal range: \" + s, null, HttpResponse.builder().statusCode(416).build());\n               }\n\n               if (offset >= blob.getPayload().getContentMetadata().getContentLength()) {\n                  throw new HttpResponseException(\"illegal range: \" + s, null, HttpResponse.builder().statusCode(416).build());\n               }\n               if (last + 1 > blob.getPayload().getContentMetadata().getContentLength()) {\n                  last = blob.getPayload().getContentMetadata().getContentLength() - 1;\n               }\n               streams.add(byteSource.slice(offset, last - offset + 1));\n               size += last - offset + 1;\n               blob.getAllHeaders().put(HttpHeaders.CONTENT_RANGE,\n                     \"bytes \" + offset + \"-\" + last + \"/\" + blob.getPayload().getContentMetadata().getContentLength());\n            }\n            ContentMetadata cmd = blob.getPayload().getContentMetadata();\n            blob.setPayload(ByteSource.concat(streams.build()));\n            HttpUtils.copy(cmd, blob.getPayload().getContentMetadata());\n            blob.getPayload().getContentMetadata().setContentLength(size);\n            blob.getMetadata().setSize(size);\n         }\n      }\n      checkNotNull(blob.getPayload(), \"payload \" + blob);\n      // return InputStream to more closely follow real blobstore\n      Payload payload;\n      try {\n         InputStream is = blob.getPayload().openStream();\n         blob.resetPayload(/*release=*/ false);\n         payload = new InputStreamPayload(is);\n      } catch (IOException ioe) {\n         throw new RuntimeException(ioe);\n      }\n      payload.setContentMetadata(blob.getMetadata().getContentMetadata());\n      blob.setPayload(payload);\n      copyPayloadHeadersToBlob(blob.getPayload(), blob);\n      return blob;\n   }\n\n   @Override\n   public BlobMetadata blobMetadata(String containerName, String key) {\n      try {\n         Blob blob = getBlob(containerName, key);\n         return blob != null ? (BlobMetadata) BlobStoreUtils.copy(blob.getMetadata()) : null;\n      } catch (RuntimeException e) {\n         if (size(Iterables.filter(getCausalChain(e), KeyNotFoundException.class)) >= 1)\n            return null;\n         throw e;\n      }\n   }\n\n   private Blob copyBlob(Blob blob) {\n      Blob returnVal = blobFactory.create(BlobStoreUtils.copy(blob.getMetadata()));\n      returnVal.setPayload(blob.getPayload());\n      copyPayloadHeadersToBlob(blob.getPayload(), returnVal);\n      return returnVal;\n   }\n\n   private boolean deleteAndVerifyContainerGone(final String container) {\n      storageStrategy.deleteContainer(container);\n      return storageStrategy.containerExists(container);\n   }\n\n   @Override\n   public String putBlob(String containerName, Blob blob, PutOptions options) {\n      checkNotNull(containerName, \"containerName must be set\");\n      checkNotNull(blob, \"blob must be set\");\n      String blobKey = blob.getMetadata().getName();\n\n      logger.debug(\"Put blob with key [%s] to container [%s]\", blobKey, containerName);\n      if (!storageStrategy.containerExists(containerName)) {\n         throw cnfe(containerName);\n      }\n\n      try {\n         String eTag = storageStrategy.putBlob(containerName, blob, options.getBlobAccess());\n         return eTag;\n      } catch (IOException e) {\n         String message = e.getMessage();\n         if (message != null && message.startsWith(\"MD5 hash code mismatch\")) {\n            HttpResponseException exception = returnResponseException(400);\n            exception.initCause(e);\n            throw exception;\n         }\n         logger.error(e, \"An error occurred storing the new blob with name [%s] to container [%s].\", blobKey,\n               containerName);\n         throw propagate(e);\n      }\n   }\n\n   @Override\n   public boolean createContainerInLocation(Location location, String container, CreateContainerOptions options) {\n      return storageStrategy.createContainerInLocation(container, location, options);\n   }\n\n   @Override\n   public MultipartUpload initiateMultipartUpload(String container, BlobMetadata blobMetadata, PutOptions options) {\n      String uploadId = UUID.randomUUID().toString();\n      // create a stub blob\n      Blob blob = blobBuilder(MULTIPART_PREFIX + uploadId + \"-\" + blobMetadata.getName() + \"-stub\").payload(ByteSource.empty()).build();\n      putBlob(container, blob);\n      return MultipartUpload.create(container, blobMetadata.getName(), uploadId,\n            blobMetadata, options);\n   }\n\n   @Override\n   public void abortMultipartUpload(MultipartUpload mpu) {\n      List<MultipartPart> parts = listMultipartUpload(mpu);\n      for (MultipartPart part : parts) {\n         removeBlob(mpu.containerName(), MULTIPART_PREFIX + mpu.id() + \"-\" + mpu.blobName() + \"-\" + part.partNumber());\n      }\n      removeBlob(mpu.containerName(), MULTIPART_PREFIX + mpu.id() + \"-\" + mpu.blobName() + \"-stub\");\n   }\n\n   @Override\n   public String completeMultipartUpload(MultipartUpload mpu, List<MultipartPart> parts) {\n      ImmutableList.Builder<BlobMetadata> metas = ImmutableList.builder();\n      long contentLength = 0;\n      Hasher md5Hasher = Hashing.md5().newHasher();\n\n      for (MultipartPart part : parts) {\n         BlobMetadata meta = blobMetadata(mpu.containerName(), MULTIPART_PREFIX + mpu.id() + \"-\" + mpu.blobName() + \"-\" + part.partNumber());\n         contentLength += meta.getContentMetadata().getContentLength();\n         metas.add(meta);\n         if (meta.getETag() != null) {\n            md5Hasher.putBytes(BaseEncoding.base16().lowerCase().decode(meta.getETag()));\n         }\n      }\n      String mpuETag = new StringBuilder(\"\\\"\")\n         .append(md5Hasher.hash())\n         .append(\"-\")\n         .append(parts.size())\n         .append(\"\\\"\")\n         .toString();\n      PayloadBlobBuilder blobBuilder = blobBuilder(mpu.blobName())\n            .userMetadata(mpu.blobMetadata().getUserMetadata())\n            .payload(new MultiBlobInputStream(this, metas.build()))\n            .contentLength(contentLength)\n            .eTag(mpuETag);\n      String cacheControl = mpu.blobMetadata().getContentMetadata().getCacheControl();\n      if (cacheControl != null) {\n         blobBuilder.cacheControl(cacheControl);\n      }\n      String contentDisposition = mpu.blobMetadata().getContentMetadata().getContentDisposition();\n      if (contentDisposition != null) {\n         blobBuilder.contentDisposition(contentDisposition);\n      }\n      String contentEncoding = mpu.blobMetadata().getContentMetadata().getContentEncoding();\n      if (contentEncoding != null) {\n         blobBuilder.contentEncoding(contentEncoding);\n      }\n      String contentLanguage = mpu.blobMetadata().getContentMetadata().getContentLanguage();\n      if (contentLanguage != null) {\n         blobBuilder.contentLanguage(contentLanguage);\n      }\n      // intentionally not copying MD5\n      String contentType = mpu.blobMetadata().getContentMetadata().getContentType();\n      if (contentType != null) {\n         blobBuilder.contentType(contentType);\n      }\n      Date expires = mpu.blobMetadata().getContentMetadata().getExpires();\n      if (expires != null) {\n         blobBuilder.expires(expires);\n      }\n      Tier tier = mpu.blobMetadata().getTier();\n      if (tier != null) {\n          blobBuilder.tier(tier);\n      }\n\n      putBlob(mpu.containerName(), blobBuilder.build());\n\n      for (MultipartPart part : parts) {\n         removeBlob(mpu.containerName(), MULTIPART_PREFIX + mpu.id() + \"-\" + mpu.blobName() + \"-\" + part.partNumber());\n      }\n      removeBlob(mpu.containerName(), MULTIPART_PREFIX + mpu.id() + \"-\" + mpu.blobName() + \"-stub\");\n\n      setBlobAccess(mpu.containerName(), mpu.blobName(), mpu.putOptions().getBlobAccess());\n\n      return mpuETag;\n   }\n\n   @Override\n   public MultipartPart uploadMultipartPart(MultipartUpload mpu, int partNumber, Payload payload) {\n      String partName = MULTIPART_PREFIX + mpu.id() + \"-\" + mpu.blobName() + \"-\" + partNumber;\n      Blob blob = blobBuilder(partName)\n            .payload(payload)\n            .build();\n      String partETag = putBlob(mpu.containerName(), blob);\n      BlobMetadata metadata = blobMetadata(mpu.containerName(), partName);  // TODO: racy, how to get this from payload?\n      long partSize = metadata.getContentMetadata().getContentLength();\n      return MultipartPart.create(partNumber, partSize, partETag, metadata.getLastModified());\n   }\n\n   @Override\n   public List<MultipartPart> listMultipartUpload(MultipartUpload mpu) {\n      ImmutableList.Builder<MultipartPart> parts = ImmutableList.builder();\n      ListContainerOptions options =\n            new ListContainerOptions().prefix(MULTIPART_PREFIX + mpu.id() + \"-\" + mpu.blobName() + \"-\").recursive();\n      while (true) {\n         PageSet<? extends StorageMetadata> pageSet = list(mpu.containerName(), options);\n         for (StorageMetadata sm : pageSet) {\n            if (sm.getName().endsWith(\"-stub\")) {\n               continue;\n            }\n            int partNumber = Integer.parseInt(sm.getName().substring((MULTIPART_PREFIX + mpu.id() + \"-\" + mpu.blobName() + \"-\").length()));\n            long partSize = sm.getSize();\n            parts.add(MultipartPart.create(partNumber, partSize, sm.getETag(), sm.getLastModified()));\n         }\n         if (pageSet.isEmpty() || pageSet.getNextMarker() == null) {\n            break;\n         }\n         options.afterMarker(pageSet.getNextMarker());\n      }\n      return parts.build();\n   }\n\n   @Override\n   public List<MultipartUpload> listMultipartUploads(String container) {\n      ImmutableList.Builder<MultipartUpload> mpus = ImmutableList.builder();\n      ListContainerOptions options = new ListContainerOptions().prefix(MULTIPART_PREFIX).recursive();\n      int uuidLength = UUID.randomUUID().toString().length();\n      while (true) {\n         PageSet<? extends StorageMetadata> pageSet = list(container, options);\n         for (StorageMetadata sm : pageSet) {\n            if (!sm.getName().endsWith(\"-stub\")) {\n               continue;\n            }\n            String uploadId = sm.getName().substring(MULTIPART_PREFIX.length(), MULTIPART_PREFIX.length() + uuidLength);\n            String blobName = sm.getName().substring(MULTIPART_PREFIX.length() + uuidLength + 1);\n            int index = blobName.lastIndexOf('-');\n            blobName = blobName.substring(0, index);\n\n            mpus.add(MultipartUpload.create(container, blobName, uploadId, null, null));\n         }\n         if (pageSet.isEmpty() || pageSet.getNextMarker() == null) {\n            break;\n         }\n         options.afterMarker(pageSet.getNextMarker());\n      }\n\n      return mpus.build();\n   }\n\n   @Override\n   public long getMinimumMultipartPartSize() {\n      return 1;\n   }\n\n   @Override\n   public long getMaximumMultipartPartSize() {\n      return 5 * 1024 * 1024;\n   }\n\n   @Override\n   public int getMaximumNumberOfParts() {\n      return Integer.MAX_VALUE;\n   }\n\n   @Override\n   public void downloadBlob(String container, String name, File destination) {\n      throw new UnsupportedOperationException();\n   }\n\n   @Override\n   public void downloadBlob(String container, String name, File destination, ExecutorService executor) {\n      throw new UnsupportedOperationException();\n   }\n\n   @Override\n   public InputStream streamBlob(String container, String name) {\n      throw new UnsupportedOperationException();\n   }\n\n   @Override\n   public InputStream streamBlob(String container, String name, ExecutorService executor) {\n      throw new UnsupportedOperationException();\n   }\n\n   private static String maybeQuoteETag(String eTag) {\n      if (!eTag.startsWith(\"\\\"\") && !eTag.endsWith(\"\\\"\")) {\n         eTag = \"\\\"\" + eTag + \"\\\"\";\n      }\n      return eTag;\n   }\n\n   private static final class MultiBlobInputStream extends InputStream {\n      private final BlobStore blobStore;\n      private final Iterator<BlobMetadata> metas;\n      private InputStream current;\n\n      MultiBlobInputStream(BlobStore blobStore, List<BlobMetadata> metas) {\n         this.blobStore = blobStore;\n         this.metas = metas.iterator();\n      }\n\n      @Override\n      public int read() throws IOException {\n         while (true) {\n            if (current == null) {\n               if (!metas.hasNext()) {\n                  return -1;\n               }\n               BlobMetadata meta = metas.next();\n               current = blobStore.getBlob(meta.getContainer(), meta.getName()).getPayload().openStream();\n            }\n            int result = current.read();\n            if (result == -1) {\n               current.close();\n               current = null;\n               continue;\n            }\n            return result & 0x000000FF;\n         }\n      }\n\n      @Override\n      public int read(byte[] b, int off, int len) throws IOException {\n         while (true) {\n            if (current == null) {\n               if (!metas.hasNext()) {\n                  return -1;\n               }\n               BlobMetadata meta = metas.next();\n               current = blobStore.getBlob(meta.getContainer(), meta.getName()).getPayload().openStream();\n            }\n            int result = current.read(b, off, len);\n            if (result == -1) {\n               current.close();\n               current = null;\n               continue;\n            }\n            return result;\n         }\n      }\n\n      @Override\n      public void close() throws IOException {\n          if (current != null) {\n              current.close();\n              current = null;\n          }\n      }\n   }\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/config/TransientBlobStoreContextModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.config;\n\nimport org.jclouds.blobstore.BlobRequestSigner;\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.LocalBlobRequestSigner;\nimport org.jclouds.blobstore.LocalStorageStrategy;\nimport org.jclouds.blobstore.TransientStorageStrategy;\nimport org.jclouds.blobstore.attr.ConsistencyModel;\n\nimport com.google.inject.AbstractModule;\n\npublic class TransientBlobStoreContextModule extends AbstractModule {\n   @Override\n   protected void configure() {\n      install(new BlobStoreObjectModule());\n      bind(BlobStore.class).to(LocalBlobStore.class);\n      bind(ConsistencyModel.class).toInstance(ConsistencyModel.STRICT);\n      bind(LocalStorageStrategy.class).to(TransientStorageStrategy.class);\n      bind(BlobRequestSigner.class).to(LocalBlobRequestSigner.class);\n   }\n\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/domain/Blob.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.domain;\n\nimport org.jclouds.io.PayloadEnclosing;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.collect.Multimap;\n\n/**\n * Value type for an HTTP Blob service. Blobs are stored in containers and consist of a\n * {@link MutableBlobMetadata#getName name}, {@link Payload payload}, and\n * {@link MutableBlobMetadata metadata}.\n */\npublic interface Blob extends PayloadEnclosing, Comparable<Blob> {\n   /**\n    * Allows you to construct blobs without knowing the implementation type\n    */\n   public interface Factory {\n      /**\n       * Creates a blob, optionally setting its metadata to a known value. This is useful in making\n       * copies of blobs.\n       */\n      Blob create(@Nullable MutableBlobMetadata metadata);\n   }\n\n   /**\n    * @return System and User metadata relevant to this object.\n    */\n   MutableBlobMetadata getMetadata();\n\n   /**\n    * @return headers returned from the services\n    */\n   Multimap<String, String> getAllHeaders();\n\n   /**\n    * \n    * @see #getAllHeaders\n    */\n   void setAllHeaders(Multimap<String, String> allHeaders);\n\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/domain/BlobAccess.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.blobstore.domain;\n\nimport com.google.common.annotations.Beta;\n\n@Beta\npublic enum BlobAccess {\n   /** Only allow bucket owner to read and write objects. */\n   PRIVATE,\n   /** Allow all users to read object but only allow owner to write object. */\n   PUBLIC_READ;\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/domain/BlobBuilder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.domain;\n\nimport java.io.File;\nimport java.io.InputStream;\nimport java.util.Date;\nimport java.util.Map;\n\nimport org.jclouds.blobstore.domain.internal.BlobBuilderImpl;\nimport org.jclouds.io.Payload;\n\nimport com.google.common.hash.HashCode;\nimport com.google.common.io.ByteSource;\nimport com.google.common.net.MediaType;\nimport com.google.inject.ImplementedBy;\n\n/**\n * \n * In case the name was confusing, this indeed builds a Blob.\n */\n@ImplementedBy(BlobBuilderImpl.class)\npublic interface BlobBuilder {\n   /**\n    * @param name\n    *           The name of the {@link Blob}. Typically refers to an http path.\n    */\n   BlobBuilder name(String name);\n\n   /** @param tier The storage tier of the {@link Blob}. Typically STANDARD. */\n   BlobBuilder tier(Tier tier);\n\n   /**\n    * @param type\n    *           overrides default type of {@link StorageType#BLOB}\n    */\n   BlobBuilder type(StorageType type);\n\n   /**\n    * @param userMetadata\n    *           User defined metadata associated with this {@link Blob}.\n    * \n    */\n   BlobBuilder userMetadata(Map<String, String> userMetadata);\n\n   /**\n    * @param eTag\n    *           Entity Tag associated with the Blob. Typically, content MD5 hash.\n    */\n   BlobBuilder eTag(String eTag);\n\n   /**\n    * \n    * @param payload\n    *           payload you wish to construct the {@link Blob} with.\n    */\n   PayloadBlobBuilder payload(Payload payload);\n\n   /**\n    * \n    * @param payload\n    *           payload you wish to construct the {@link Blob} with.\n    */\n   PayloadBlobBuilder payload(InputStream payload);\n\n   /**\n    * If you are creating a blob only for signing, use this. {@see BlobRequestSigner}\n    */\n   PayloadBlobBuilder forSigning();\n\n   /**\n    * \n    * @param payload\n    *           payload you wish to construct the {@link Blob} with.\n    */\n   PayloadBlobBuilder payload(byte[] payload);\n\n   /**\n    * @param payload payload you wish to construct the {@link Blob} with.\n    */\n   PayloadBlobBuilder payload(ByteSource byteSource);\n\n   /**\n    * \n    * @param payload\n    *           payload you wish to construct the {@link Blob} with.\n    */\n   PayloadBlobBuilder payload(String payload);\n\n   /**\n    * \n    * @param payload\n    *           payload you wish to construct the {@link Blob} with.\n    */\n   PayloadBlobBuilder payload(File payload);\n\n   /**\n    * This makes a blob from the currently configured parameters.\n    * \n    * @return a new blob from the current parameters\n    */\n   Blob build();\n\n   public interface PayloadBlobBuilder extends BlobBuilder {\n\n      PayloadBlobBuilder cacheControl(String cacheControl);\n\n      PayloadBlobBuilder contentLength(long contentLength);\n\n      /** @deprecated use {@link #contentMD5(HashCode)} instead. */\n      @Deprecated\n      PayloadBlobBuilder contentMD5(byte[] md5);\n\n      PayloadBlobBuilder contentMD5(HashCode md5);\n\n      PayloadBlobBuilder contentType(MediaType contentType);\n\n      PayloadBlobBuilder contentType(String contentType);\n\n      PayloadBlobBuilder contentDisposition(String contentDisposition);\n\n      PayloadBlobBuilder contentLanguage(String contentLanguage);\n\n      PayloadBlobBuilder contentEncoding(String contentEncoding);\n\n      PayloadBlobBuilder expires(Date expires);\n\n      PayloadBlobBuilder eTag(String string);\n   }\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/domain/BlobMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.domain;\n\nimport java.net.URI;\n\nimport org.jclouds.blobstore.domain.internal.BlobMetadataImpl;\nimport org.jclouds.io.ContentMetadata;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.inject.ImplementedBy;\n\n/**\n * System and user Metadata for the {@link Blob}.\n */\n@ImplementedBy(BlobMetadataImpl.class)\npublic interface BlobMetadata extends StorageMetadata {\n   /**\n    * If the blob is publicly readable, what is the URI one can access it at.\n    * \n    * @return uri, or null, if not readable\n    */\n   @Nullable\n   URI getPublicUri();\n   \n   /**\n    * \n    * @return the container holding this blob\n    */\n   @Nullable\n   String getContainer();\n\n   ContentMetadata getContentMetadata();\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/domain/ContainerAccess.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.blobstore.domain;\n\nimport com.google.common.annotations.Beta;\n\n@Beta\npublic enum ContainerAccess {\n   /** Only allow bucket owner to read and write objects. */\n   PRIVATE,\n   /** Allow all users to read objects but only allow owner to write objects. */\n   PUBLIC_READ;\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/domain/MultipartPart.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.blobstore.domain;\n\nimport java.util.Date;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class MultipartPart {\n   public abstract int partNumber();\n   public abstract long partSize();\n   @Nullable public abstract String partETag();\n   @Nullable public abstract Date lastModified();\n\n   @Deprecated\n   public static MultipartPart create(int partNumber, long partSize, @Nullable String partETag) {\n      return MultipartPart.create(partNumber, partSize, partETag, null);\n   }\n\n   public static MultipartPart create(int partNumber, long partSize, @Nullable String partETag, @Nullable Date lastModified) {\n      return new AutoValue_MultipartPart(partNumber, partSize, partETag, lastModified);\n   }\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/domain/MultipartUpload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.blobstore.domain;\n\nimport org.jclouds.blobstore.options.PutOptions;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class MultipartUpload {\n   public abstract String containerName();\n   public abstract String blobName();\n   public abstract String id();\n   @Nullable public abstract BlobMetadata blobMetadata();\n   @Nullable public abstract PutOptions putOptions();\n\n   public static MultipartUpload create(String containerName, String blobName, String id, @Nullable BlobMetadata blobMetadata,\n         @Nullable PutOptions putOptions) {\n      return new AutoValue_MultipartUpload(containerName, blobName, id, blobMetadata, putOptions);\n   }\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/domain/MutableBlobMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.domain;\n\nimport java.net.URI;\n\nimport org.jclouds.blobstore.domain.internal.MutableBlobMetadataImpl;\nimport org.jclouds.io.MutableContentMetadata;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.inject.ImplementedBy;\n\n/**\n * System and user Metadata for the {@link Blob}.\n */\n@ImplementedBy(MutableBlobMetadataImpl.class)\npublic interface MutableBlobMetadata extends BlobMetadata, MutableStorageMetadata {\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   MutableContentMetadata getContentMetadata();\n\n   /**\n    * @see BlobMetadata#getContentMetadata\n    */\n   void setContentMetadata(MutableContentMetadata md);\n\n   /**\n    * @see BlobMetadata#getPublicUri\n    */\n   void setPublicUri(@Nullable URI publicUri);\n\n   /**\n    * @see BlobMetadata#getContainer\n    */\n   void setContainer(@Nullable String container);\n\n   void setTier(Tier tier);\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/domain/MutableStorageMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.domain;\n\nimport java.util.Date;\n\nimport org.jclouds.blobstore.domain.internal.MutableStorageMetadataImpl;\nimport org.jclouds.domain.MutableResourceMetadata;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.inject.ImplementedBy;\n\n/**\n * Used to construct new resources or modify existing ones.\n */\n@ImplementedBy(MutableStorageMetadataImpl.class)\npublic interface MutableStorageMetadata extends MutableResourceMetadata<StorageType>,\n         StorageMetadata {\n\n   /**\n    * @see #getETag\n    */\n   void setETag(String eTag);\n\n   /**\n    * @see #getCreationDate\n    */\n   void setCreationDate(@Nullable Date creationDate);\n\n   /**\n    * @see #getLastModified\n    */\n   void setLastModified(@Nullable Date lastModified);\n\n   /** @see #getSize */\n   void setSize(@Nullable Long size);\n\n   void setTier(Tier tier);\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/domain/PageSet.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.domain;\n\nimport java.util.Set;\n\npublic interface PageSet<T> extends Set<T> {\n\n   /**\n    * If there is a next marker, then the set is incomplete and you should issue another command to\n    * retrieve the rest, setting the option {@code marker} to this value.  Some providers like Azure\n    * have opaque markers so portable code should not rely on the actual values.\n    * \n    * @return next marker, or null if list is complete\n    */\n   String getNextMarker();\n\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/domain/StorageMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.domain;\n\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.Map;\n\nimport org.jclouds.blobstore.domain.internal.StorageMetadataImpl;\nimport org.jclouds.domain.ResourceMetadata;\n\nimport com.google.inject.ImplementedBy;\n\n/**\n * Identifies containers, files, etc.\n */\n@ImplementedBy(StorageMetadataImpl.class)\npublic interface StorageMetadata extends ResourceMetadata<StorageType> {\n\n   /**\n    * Whether this resource is a container, file, etc.\n    */\n   @Override\n   StorageType getType();\n\n   /**\n    * Unique identifier of this resource within its enclosing namespace. In some scenarios, this id\n    * is not user assignable. For files, this may be an system generated key, or the full path to\n    * the resource. ex. /path/to/file.txt\n    * \n    * @see org.jclouds.blobstore.attr.ContainerCapability#CONTAINER_METADATA\n    */\n   @Override\n   String getProviderId();\n\n   /**\n    * Name of this resource. Names are dictated by the user. For files, this may be the filename,\n    * ex. file.txt\n    * \n    */\n   @Override\n   String getName();\n\n   /**\n    * URI used to access this resource\n    */\n   @Override\n   URI getUri();\n\n   /**\n    * Any key-value pairs associated with the resource.\n    * \n    * @see org.jclouds.blobstore.attr.ContainerCapability#CONTAINER_METADATA\n    * @see org.jclouds.blobstore.attr.ContainerCapability#BLOB_METADATA\n    */\n   @Override\n   Map<String, String> getUserMetadata();\n\n   /**\n    * The eTag value stored in the Etag header returned by HTTP.\n    * \n    * @see org.jclouds.blobstore.attr.ContainerCapability#CONTAINER_ETAG\n    * @see org.jclouds.blobstore.attr.ContainerCapability#BLOB_ETAG\n    */\n   String getETag();\n\n   /**\n    * Creation date of the resource, possibly null.\n    */\n   Date getCreationDate();\n\n   /**\n    * Last modification time of the resource\n    * \n    * @see org.jclouds.blobstore.attr.ContainerCapability#CONTAINER_LAST_MODIFIED\n    * @see org.jclouds.blobstore.attr.ContainerCapability#BLOB_LAST_MODIFIED\n    * @see org.jclouds.blobstore.attr.ContainerCapability#MILLISECOND_PRECISION\n    */\n   Date getLastModified();\n\n   /** Size of the resource, possibly null. */\n   Long getSize();\n\n   Tier getTier();\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/domain/StorageType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.domain;\n\npublic enum StorageType {\n\n   /**\n    * A container\n    */\n   CONTAINER,\n   /**\n    * An object in the object store\n    */\n   BLOB,\n   /**\n    * Represents \"special\" blobs that have content-type set to\n    * application/directory.\n    */\n   FOLDER,\n   /**\n    * A partial path; used when the delimiter is set and represents all objects\n    * that start with the same name up to the delimiter character (e.g. foo-bar\n    * and foo-baz, with delimiter set to \"-\" will be returned as \"foo-\").\n    */\n   RELATIVE_PATH;\n\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/domain/Tier.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.domain;\n\n/**\n * Store data with different strategies, ranging from most performant to lowest\n * cost.  Tiering is best-effort and some providers will map lower tiers to\n * higher ones.\n */\npublic enum Tier {\n   /** Optimize for access speed. */\n   STANDARD,\n   /** @deprecated see COOL. */\n   @Deprecated INFREQUENT,\n   /** Slower access speed and reduced storage costs. */\n   COOL,\n   /** Even slower access speed and further reduced storage costs. */\n   COLD,\n   /**\n    * Optimize for storage cost.  Some providers may require a separate call to\n    * set the blob to STANDARD tier before access.\n    */\n   ARCHIVE;\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/domain/internal/BlobBuilderImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.domain.internal;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static org.jclouds.io.Payloads.newPayload;\n\nimport java.io.File;\nimport java.io.InputStream;\nimport java.util.Date;\nimport java.util.Map;\n\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.BlobBuilder;\nimport org.jclouds.blobstore.domain.StorageType;\nimport org.jclouds.blobstore.domain.Tier;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.payloads.PhantomPayload;\n\nimport com.google.common.collect.Maps;\nimport com.google.common.hash.HashCode;\nimport com.google.common.io.ByteSource;\nimport com.google.common.net.MediaType;\n\npublic class BlobBuilderImpl implements BlobBuilder {\n\n   private Payload payload;\n   private String name;\n   private Tier tier = Tier.STANDARD;\n   private Map<String, String> userMetadata = Maps.newLinkedHashMap();\n   private StorageType type = StorageType.BLOB;\n   private String eTag;\n\n   @Override\n   public BlobBuilder name(String name) {\n      checkNotNull(name, \"name\");\n      checkArgument(!name.isEmpty(), \"name\");\n      this.name = name;\n      return this;\n   }\n\n   @Override\n   public BlobBuilder tier(Tier tier) {\n      this.tier = checkNotNull(tier, \"tier\");\n      return this;\n   }\n\n   @Override\n   public BlobBuilder type(StorageType type) {\n      this.type = type;\n      return this;\n   }\n\n   @Override\n   public BlobBuilder eTag(String eTag) {\n      this.eTag = eTag;\n      return this;\n   }\n\n   @Override\n   public BlobBuilder userMetadata(Map<String, String> userMetadata) {\n      if (userMetadata != null)\n         this.userMetadata = Maps.newLinkedHashMap(userMetadata);\n      return this;\n   }\n\n   @Override\n   public PayloadBlobBuilder payload(Payload payload) {\n      this.payload = payload;\n      return new PayloadBlobBuilderImpl(this, payload);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public PayloadBlobBuilder payload(InputStream data) {\n      return payload(newPayload(checkNotNull(data, \"data\")));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public PayloadBlobBuilder payload(byte[] data) {\n      return payload(newPayload(checkNotNull(data, \"data\")));\n   }\n\n   @Override\n   public PayloadBlobBuilder payload(ByteSource data) {\n      return payload(newPayload(checkNotNull(data, \"data\")));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public PayloadBlobBuilder payload(String data) {\n      return payload(newPayload(checkNotNull(data, \"data\")));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public PayloadBlobBuilder payload(File data) {\n      return payload(newPayload(checkNotNull(data, \"data\")));\n   }\n\n   @Override\n   public Blob build() {\n      Blob blob = new BlobImpl(new MutableBlobMetadataImpl());\n      checkState(name != null, \"name\");\n      blob.getMetadata().setName(name);\n      if (payload != null)\n         blob.setPayload(payload);\n      blob.getMetadata().setUserMetadata(userMetadata);\n      blob.getMetadata().setType(type);\n      blob.getMetadata().setTier(tier);\n      blob.getMetadata().setETag(eTag);\n      return blob;\n   }\n\n   public static class PayloadBlobBuilderImpl implements PayloadBlobBuilder {\n      private final BlobBuilder builder;\n      private final Payload payload;\n\n      public PayloadBlobBuilderImpl(BlobBuilder builder, Payload payload) {\n         this.builder = checkNotNull(builder, \"builder\");\n         this.payload = checkNotNull(payload, \"payload\");\n      }\n\n      @Override\n      public BlobBuilder name(String name) {\n         return builder.name(name);\n      }\n\n      @Override\n      public BlobBuilder tier(Tier tier) {\n         return builder.tier(tier);\n      }\n\n      @Override\n      public BlobBuilder type(StorageType type) {\n         return builder.type(type);\n      }\n\n      @Override\n      public BlobBuilder userMetadata(Map<String, String> userMetadata) {\n         return builder.userMetadata(userMetadata);\n      }\n\n      @Override\n      public PayloadBlobBuilder payload(Payload payload) {\n         return builder.payload(payload);\n      }\n\n      @Override\n      public PayloadBlobBuilder payload(InputStream payload) {\n         return builder.payload(payload);\n      }\n\n      @Override\n      public PayloadBlobBuilder payload(byte[] payload) {\n         return builder.payload(payload);\n      }\n\n      @Override\n      public PayloadBlobBuilder payload(ByteSource payload) {\n         return builder.payload(payload);\n      }\n\n      @Override\n      public PayloadBlobBuilder payload(String payload) {\n         return builder.payload(payload);\n      }\n\n      @Override\n      public PayloadBlobBuilder payload(File payload) {\n         return builder.payload(payload);\n      }\n\n      @Override\n      public Blob build() {\n         return builder.build();\n      }\n\n      @Override\n      public PayloadBlobBuilder cacheControl(String cacheControl) {\n         payload.getContentMetadata().setCacheControl(cacheControl);\n         return this;\n      }\n\n      @Override\n      public PayloadBlobBuilder contentLength(long contentLength) {\n         checkArgument(contentLength >= 0, \"content length must be non-negative, was: %s\", contentLength);\n         payload.getContentMetadata().setContentLength(contentLength);\n         return this;\n      }\n\n      /** @deprecated use {@link #contentMD5(HashCode)} instead. */\n      @Deprecated\n      @Override\n      public PayloadBlobBuilder contentMD5(byte[] md5) {\n         return contentMD5(md5 == null ? null : HashCode.fromBytes(md5));\n      }\n\n      @Override\n      public PayloadBlobBuilder contentMD5(HashCode md5) {\n         payload.getContentMetadata().setContentMD5(md5);\n         return this;\n      }\n\n      @Override\n      public PayloadBlobBuilder contentType(MediaType contentType) {\n         return contentType(checkNotNull(contentType, \"contentType\").toString());\n      }\n\n      @Override\n      public PayloadBlobBuilder contentType(String contentType) {\n         payload.getContentMetadata().setContentType(contentType);\n         return this;\n      }\n\n      @Override\n      public PayloadBlobBuilder contentDisposition(String contentDisposition) {\n         payload.getContentMetadata().setContentDisposition(contentDisposition);\n         return this;\n      }\n\n      @Override\n      public PayloadBlobBuilder contentLanguage(String contentLanguage) {\n         payload.getContentMetadata().setContentLanguage(contentLanguage);\n         return this;\n\n      }\n\n      @Override\n      public PayloadBlobBuilder contentEncoding(String contentEncoding) {\n         payload.getContentMetadata().setContentEncoding(contentEncoding);\n         return this;\n      }\n\n      @Override\n      public PayloadBlobBuilder expires(Date expires) {\n         payload.getContentMetadata().setExpires(expires);\n         return this;\n      }\n\n      @Override\n      public PayloadBlobBuilder eTag(String eTag) {\n         this.builder.eTag(eTag);\n         return this;\n      }\n\n      @Override\n      public PayloadBlobBuilder forSigning() {\n         return builder.forSigning();\n      }\n\n   }\n\n   @Override\n   public PayloadBlobBuilder forSigning() {\n      return payload(new PhantomPayload());\n   }\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/domain/internal/BlobImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.domain.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.MutableBlobMetadata;\nimport org.jclouds.http.internal.PayloadEnclosingImpl;\nimport org.jclouds.io.Payload;\n\nimport com.google.common.collect.LinkedHashMultimap;\nimport com.google.common.collect.Multimap;\n\n/**\n * Value type for an HTTP Blob service. Blobs are stored in {@link StorageMetadata containers} and consist\n * of a {@link org.jclouds.blobstore.domain.Value#getInput() value}, a {@link Blob#getKey key and\n * \n * @link Blob.Metadata#getUserMetadata() metadata}\n */\npublic class BlobImpl extends PayloadEnclosingImpl implements Blob, Comparable<Blob> {\n\n   private final MutableBlobMetadata metadata;\n   private Multimap<String, String> allHeaders = LinkedHashMultimap.create();\n\n   @Inject\n   public BlobImpl(MutableBlobMetadata metadata) {\n      super();\n      this.metadata = metadata;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public MutableBlobMetadata getMetadata() {\n      return metadata;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Multimap<String, String> getAllHeaders() {\n      return allHeaders;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void setAllHeaders(Multimap<String, String> allHeaders) {\n      this.allHeaders = checkNotNull(allHeaders, \"allHeaders\");\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public int compareTo(Blob o) {\n      if (getMetadata().getName() == null)\n         return -1;\n      return (this == o) ? 0 : getMetadata().getName().compareTo(o.getMetadata().getName());\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = super.hashCode();\n      result = prime * result + ((metadata == null) ? 0 : metadata.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (!super.equals(obj))\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      BlobImpl other = (BlobImpl) obj;\n      if (metadata == null) {\n         if (other.metadata != null)\n            return false;\n      } else if (!metadata.equals(other.metadata))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"[metadata=\" + metadata + \"]\";\n   }\n\n   @Override\n   public void setPayload(Payload data) {\n      super.setPayload(data);\n      metadata.setContentMetadata(data.getContentMetadata());\n   }\n\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/domain/internal/BlobMetadataImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.domain.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.Map;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\nimport org.jclouds.blobstore.domain.BlobMetadata;\nimport org.jclouds.blobstore.domain.StorageType;\nimport org.jclouds.blobstore.domain.Tier;\nimport org.jclouds.domain.Location;\nimport org.jclouds.io.ContentMetadata;\nimport org.jclouds.javax.annotation.Nullable;\n\n/**\n * System and user Metadata for the {@link Blob}.\n */\npublic class BlobMetadataImpl extends StorageMetadataImpl implements BlobMetadata {\n\n   private final URI publicUri;\n   private final String container;\n   private final ContentMetadata contentMetadata;\n\n   public BlobMetadataImpl(String id, String name, @Nullable Location location, URI uri, String eTag,\n            @Nullable Date creationDate, @Nullable Date lastModified,\n            Map<String, String> userMetadata, @Nullable URI publicUri,\n            @Nullable String container, ContentMetadata contentMetadata, @Nullable Long size,\n            Tier tier) {\n      super(StorageType.BLOB, id, name, location, uri, eTag, creationDate, lastModified, userMetadata, size, tier);\n      this.publicUri = publicUri;\n      this.container = container;\n      this.contentMetadata = checkNotNull(contentMetadata, \"contentMetadata\");\n   }\n\n   @Deprecated\n   public BlobMetadataImpl(String id, String name, @Nullable Location location, URI uri, String eTag,\n            @Nullable Date creationDate, @Nullable Date lastModified,\n            Map<String, String> userMetadata, @Nullable URI publicUri,\n            @Nullable String container, ContentMetadata contentMetadata, @Nullable Long size) {\n      this(id, name, location, uri, eTag, creationDate, lastModified, userMetadata, publicUri, container, contentMetadata, size, Tier.STANDARD);\n   }\n\n   @Deprecated\n   public BlobMetadataImpl(String id, String name, @Nullable Location location, URI uri, String eTag,\n            @Nullable Date creationDate, @Nullable Date lastModified,\n            Map<String, String> userMetadata, @Nullable URI publicUri,\n            @Nullable String container, ContentMetadata contentMetadata) {\n      this(id, name, location, uri, eTag, creationDate, lastModified, userMetadata, publicUri, container, contentMetadata, null);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public URI getPublicUri() {\n      return publicUri;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getContainer() {\n      return container;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ContentMetadata getContentMetadata() {\n      return contentMetadata;\n   }\n\n   @Override\n   public boolean equals(Object object) {\n      if (object == this) {\n         return true;\n      }\n      if (!(object instanceof BlobMetadataImpl)) {\n         return false;\n      }\n      BlobMetadataImpl that = (BlobMetadataImpl) object;\n      return super.equals(that) &&\n            Objects.equal(publicUri, that.publicUri) &&\n            Objects.equal(container, that.container) &&\n            Objects.equal(contentMetadata, that.contentMetadata);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(super.hashCode(), publicUri, container, contentMetadata);\n   }\n\n   @Override\n   protected ToStringHelper string() {\n      return super.string()\n            .add(\"publicUri\", publicUri)\n            .add(\"container\", container)\n            .add(\"contentMetadata\", contentMetadata);\n   }\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/domain/internal/MutableBlobMetadataImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.domain.internal;\n\nimport java.net.URI;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\nimport org.jclouds.blobstore.domain.BlobMetadata;\nimport org.jclouds.blobstore.domain.MutableBlobMetadata;\nimport org.jclouds.blobstore.domain.StorageType;\nimport org.jclouds.blobstore.domain.Tier;\nimport org.jclouds.http.HttpUtils;\nimport org.jclouds.io.MutableContentMetadata;\nimport org.jclouds.io.payloads.BaseMutableContentMetadata;\n\n/**\n * System and user Metadata for the {@link Blob}.\n */\npublic class MutableBlobMetadataImpl extends MutableStorageMetadataImpl implements MutableBlobMetadata {\n\n   private MutableContentMetadata contentMetadata;\n   private URI publicUri;\n   private String container;\n   private Tier tier;\n\n   public MutableBlobMetadataImpl() {\n      this.setType(StorageType.BLOB);\n      this.contentMetadata = new BaseMutableContentMetadata();\n   }\n\n   public MutableBlobMetadataImpl(BlobMetadata from) {\n      super(from);\n      this.contentMetadata = new BaseMutableContentMetadata();\n      HttpUtils.copy(from.getContentMetadata(), this.contentMetadata);\n      this.publicUri = from.getPublicUri();\n      this.container = from.getContainer();\n      this.tier = from.getTier() == null ? Tier.STANDARD : from.getTier();\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public MutableContentMetadata getContentMetadata() {\n      return contentMetadata;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void setContentMetadata(MutableContentMetadata contentMetadata) {\n      this.contentMetadata = contentMetadata;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void setPublicUri(URI publicUri) {\n      this.publicUri = publicUri;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public URI getPublicUri() {\n      return publicUri;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getContainer() {\n      return container;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void setContainer(String container) {\n      this.container = container;\n   }\n\n   @Override\n   public Tier getTier() {\n      return tier;\n   }\n\n   @Override\n   public void setTier(Tier tier) {\n      this.tier = tier;\n   }\n\n   @Override\n   public boolean equals(Object object) {\n      if (object == this) {\n         return true;\n      }\n      if (!(object instanceof MutableBlobMetadataImpl)) {\n         return false;\n      }\n      MutableBlobMetadataImpl that = (MutableBlobMetadataImpl) object;\n      return super.equals(that) &&\n            Objects.equal(contentMetadata, that.contentMetadata) &&\n            Objects.equal(publicUri, that.publicUri) &&\n            Objects.equal(container, that.container) &&\n            Objects.equal(tier, that.tier);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(super.hashCode(), contentMetadata, publicUri, container);\n   }\n\n   @Override\n   protected ToStringHelper string() {\n      return super.string()\n            .add(\"publicUri\", publicUri)\n            .add(\"container\", container)\n            .add(\"contentMetadata\", contentMetadata)\n            .add(\"tier\", tier);\n   }\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/domain/internal/MutableStorageMetadataImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.domain.internal;\n\nimport java.util.Date;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\nimport org.jclouds.blobstore.domain.MutableStorageMetadata;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.domain.StorageType;\nimport org.jclouds.blobstore.domain.Tier;\nimport org.jclouds.domain.internal.MutableResourceMetadataImpl;\n\n/**\n * Used to construct new resources or modify existing ones.\n */\npublic class MutableStorageMetadataImpl extends MutableResourceMetadataImpl<StorageType> implements\n         MutableStorageMetadata {\n\n   private String eTag;\n   private Date creationDate;\n   private Date lastModified;\n   private Long size;\n   private Tier tier;\n\n   public MutableStorageMetadataImpl() {\n      super();\n   }\n\n   public MutableStorageMetadataImpl(StorageMetadata from) {\n      super(from);\n      this.eTag = from.getETag();\n      this.lastModified = from.getLastModified();\n      this.size = from.getSize();\n      this.tier = from.getTier();\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getETag() {\n      return eTag;\n   }\n\n   @Override\n   public Date getCreationDate() {\n      return creationDate;\n   }\n\n   @Override\n   public void setCreationDate(Date creationDate) {\n      this.creationDate = creationDate;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Date getLastModified() {\n      return lastModified;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void setLastModified(Date lastModified) {\n      this.lastModified = lastModified;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void setETag(String eTag) {\n      this.eTag = eTag;\n   }\n\n   @Override\n   public Long getSize() {\n      return size;\n   }\n\n   @Override\n   public void setSize(Long size) {\n      this.size = size;\n   }\n\n   @Override\n   public Tier getTier() {\n      return tier;\n   }\n\n   @Override\n   public void setTier(Tier tier) {\n      this.tier = tier;\n   }\n\n   @Override\n   public boolean equals(Object object) {\n      if (object == this) {\n         return true;\n      }\n      if (!(object instanceof MutableStorageMetadataImpl)) {\n         return false;\n      }\n      MutableStorageMetadataImpl that = (MutableStorageMetadataImpl) object;\n      return super.equals(that) &&\n            Objects.equal(eTag, that.eTag) &&\n            Objects.equal(creationDate, that.creationDate) &&\n            Objects.equal(lastModified, that.lastModified) &&\n            Objects.equal(size, that.size) &&\n            Objects.equal(tier, that.tier);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(super.hashCode(), eTag, creationDate, lastModified, size, tier);\n   }\n\n   @Override\n   protected ToStringHelper string() {\n      return super.string()\n            .add(\"eTag\", eTag)\n            .add(\"creationDate\", creationDate)\n            .add(\"lastModified\", lastModified)\n            .add(\"size\", size)\n            .add(\"tier\", tier);\n   }\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/domain/internal/PageSetImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.domain.internal;\n\nimport java.util.LinkedHashSet;\n\nimport org.jclouds.blobstore.domain.PageSet;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.collect.Iterables;\n\npublic class PageSetImpl<T> extends LinkedHashSet<T> implements PageSet<T> {\n\n   protected final String marker;\n\n   public PageSetImpl(Iterable<? extends T> contents, @Nullable String nextMarker) {\n      Iterables.addAll(this, contents);\n      this.marker = nextMarker;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getNextMarker() {\n      return marker;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = super.hashCode();\n      result = prime * result + ((marker == null) ? 0 : marker.hashCode());\n      return result;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (!super.equals(obj))\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      PageSetImpl<?> other = (PageSetImpl<?>) obj;\n      if (marker == null) {\n         if (other.marker != null)\n            return false;\n      } else if (!marker.equals(other.marker))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"marker: \" + marker + \" elements: \" + super.toString();\n   }\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/domain/internal/StorageMetadataImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.domain.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.Map;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.domain.StorageType;\nimport org.jclouds.blobstore.domain.Tier;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.internal.ResourceMetadataImpl;\nimport org.jclouds.javax.annotation.Nullable;\n\n/**\n * Idpayload of the object\n */\npublic class StorageMetadataImpl extends ResourceMetadataImpl<StorageType> implements StorageMetadata {\n\n   @Nullable\n   private final String eTag;\n   @Nullable\n   private final Date creationDate;\n   @Nullable\n   private final Date lastModified;\n   private final StorageType type;\n   @Nullable\n   private final Long size;\n   @Nullable\n   private final Tier tier;\n\n   public StorageMetadataImpl(StorageType type, @Nullable String id, @Nullable String name,\n         @Nullable Location location, @Nullable URI uri, @Nullable String eTag,\n         @Nullable Date creationDate, @Nullable Date lastModified,\n         Map<String, String> userMetadata, @Nullable Long size, Tier tier) {\n      super(id, name, location, uri, userMetadata);\n      this.eTag = eTag;\n      this.creationDate = creationDate;\n      this.lastModified = lastModified;\n      this.type = checkNotNull(type, \"type\");\n      this.size = size;\n      this.tier = tier;\n   }\n\n   /** @deprecated call StorageMetadataImpl(StorageType.class, String.class, String.class, Location.class, URI.class, String.class, Date.class, Date.class, Map.class, Long.class, Tier.class) */\n   @Deprecated\n   public StorageMetadataImpl(StorageType type, @Nullable String id, @Nullable String name,\n         @Nullable Location location, @Nullable URI uri, @Nullable String eTag,\n         @Nullable Date creationDate, @Nullable Date lastModified,\n         Map<String, String> userMetadata, @Nullable Long size) {\n      this(type, id, name, location, uri, eTag, creationDate, lastModified, userMetadata, size, null);\n   }\n\n   /** @deprecated call StorageMetadataImpl(StorageType.class, String.class, String.class, Location.class, URI.class, String.class, Date.class, Date.class, Map.class, Long.class) */\n   @Deprecated\n   public StorageMetadataImpl(StorageType type, @Nullable String id, @Nullable String name,\n         @Nullable Location location, @Nullable URI uri, @Nullable String eTag,\n         @Nullable Date creationDate, @Nullable Date lastModified,\n         Map<String, String> userMetadata) {\n      this(type, id, name, location, uri, eTag, creationDate, lastModified, userMetadata, null);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public StorageType getType() {\n      return type;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(super.hashCode(), eTag, creationDate,\n            lastModified, type, size, tier);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (!super.equals(obj))\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      StorageMetadataImpl other = (StorageMetadataImpl) obj;\n      if (!Objects.equal(eTag, other.eTag)) { return false; }\n      if (!Objects.equal(creationDate, other.creationDate)) { return false; }\n      if (!Objects.equal(lastModified, other.lastModified)) { return false; }\n      if (!Objects.equal(type, other.type)) { return false; }\n      if (!Objects.equal(size, other.size)) { return false; }\n      if (!Objects.equal(tier, other.tier)) { return false; }\n      return true;\n   }\n\n   @Override\n   protected ToStringHelper string() {\n      return super.string()\n            .add(\"eTag\", eTag)\n            .add(\"creationDate\", creationDate)\n            .add(\"lastModified\", lastModified)\n            .add(\"type\", type)\n            .add(\"size\", size)\n            .add(\"tier\", tier);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getETag() {\n      return eTag;\n   }\n\n   @Override\n   public Date getCreationDate() {\n      return creationDate;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Date getLastModified() {\n      return lastModified;\n   }\n\n   @Override\n   public Long getSize() {\n      return size;\n   }\n\n   @Override\n   public Tier getTier() {\n      return tier;\n   }\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/functions/BlobName.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.blobstore.domain.Blob;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic final class BlobName implements Function<Blob, String> {\n\n   public String apply(Blob input) {\n      return checkNotNull(checkNotNull(input, \"input\").getMetadata().getName(), \"blobName\");\n   }\n\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/functions/BlobToHttpGetOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.options.GetOptions;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class BlobToHttpGetOptions implements Function<org.jclouds.blobstore.options.GetOptions, GetOptions> {\n\n   @Override\n   public GetOptions apply(org.jclouds.blobstore.options.GetOptions from) {\n      checkNotNull(from, \"options\");\n      if (from == org.jclouds.blobstore.options.GetOptions.NONE)\n         return GetOptions.NONE;\n      GetOptions httpOptions = new GetOptions();\n      if (from.getIfMatch() != null) {\n         httpOptions.ifETagMatches(from.getIfMatch());\n      }\n      if (from.getIfModifiedSince() != null) {\n         httpOptions.ifModifiedSince(from.getIfModifiedSince());\n      }\n      if (from.getIfNoneMatch() != null) {\n         httpOptions.ifETagDoesntMatch(from.getIfNoneMatch());\n      }\n      if (from.getIfUnmodifiedSince() != null) {\n         httpOptions.ifUnmodifiedSince(from.getIfUnmodifiedSince());\n      }\n      for (String range : from.getRanges()) {\n         String[] firstLast = range.split(\"\\\\-\", 2);\n         if (!firstLast[0].isEmpty() && !firstLast[1].isEmpty())\n            httpOptions.range(Long.parseLong(firstLast[0]), Long.parseLong(firstLast[1]));\n         else if (firstLast[0].isEmpty() && !firstLast[1].isEmpty())\n            httpOptions.tail(Long.parseLong(firstLast[1]));\n         else\n            httpOptions.startAt(Long.parseLong(firstLast[0]));\n      }\n      return httpOptions;\n   }\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/functions/HttpGetOptionsListToGetOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Date;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.blobstore.options.GetOptions;\nimport org.jclouds.date.DateService;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class HttpGetOptionsListToGetOptions implements\n      Function<org.jclouds.http.options.GetOptions[], org.jclouds.blobstore.options.GetOptions> {\n   private final DateService dateService;\n\n   @Inject\n   HttpGetOptionsListToGetOptions(DateService dateService) {\n      this.dateService = checkNotNull(dateService, \"dateService\");\n   }\n\n   public GetOptions apply(org.jclouds.http.options.GetOptions[] from) {\n      checkNotNull(from, \"options\");\n\n      org.jclouds.blobstore.options.GetOptions to = new org.jclouds.blobstore.options.GetOptions();\n      if (from.length != 0) {\n         if (from[0].getIfMatch() != null) {\n            to.ifETagMatches(from[0].getIfMatch().replace(\"\\\"\", \"\"));\n         }\n         if (from[0].getIfModifiedSince() != null) {\n            Date time = dateService.rfc822DateParse(from[0].getIfModifiedSince());\n            to.ifModifiedSince(time);\n         }\n         if (from[0].getIfNoneMatch() != null) {\n            to.ifETagDoesntMatch(from[0].getIfNoneMatch().replace(\"\\\"\", \"\"));\n         }\n         if (from[0].getIfUnmodifiedSince() != null) {\n            Date time = dateService.rfc822DateParse(from[0].getIfUnmodifiedSince());\n            to.ifUnmodifiedSince(time);\n         }\n         for (String range : from[0].getRanges()) {\n            String[] firstLast = range.split(\"\\\\-\");\n            to.range(Long.parseLong(firstLast[0]), Long.parseLong(firstLast[1]));\n         }\n      }\n      return to;\n   }\n\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/functions/ParseBlobFromHeadersAndHttpContent.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.MutableBlobMetadata;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rest.InvocationContext;\n\nimport com.google.common.base.Function;\n\n/**\n * Parses response headers and creates a new Blob from them and the HTTP content.\n * \n * @see ParseSystemAndUserMetadataFromHeaders\n */\npublic class ParseBlobFromHeadersAndHttpContent implements Function<HttpResponse, Blob>,\n      InvocationContext<ParseBlobFromHeadersAndHttpContent> {\n   private final ParseSystemAndUserMetadataFromHeaders metadataParser;\n   private final Blob.Factory blobFactory;\n\n   @Inject\n   public ParseBlobFromHeadersAndHttpContent(ParseSystemAndUserMetadataFromHeaders metadataParser,\n         Blob.Factory blobFactory) {\n      this.metadataParser = checkNotNull(metadataParser, \"metadataParser\");\n      this.blobFactory = checkNotNull(blobFactory, \"blobFactory\");\n   }\n\n   public Blob apply(HttpResponse from) {\n      checkNotNull(from, \"request\");\n      MutableBlobMetadata metadata = metadataParser.apply(from);\n      Blob blob = blobFactory.create(metadata);\n      blob.getAllHeaders().putAll(from.getHeaders());\n      blob.setPayload(from.getPayload());\n      return blob;\n   }\n\n   @Override\n   public ParseBlobFromHeadersAndHttpContent setContext(HttpRequest request) {\n      metadataParser.setContext(request);\n      return this;\n   }\n\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/functions/ParseSystemAndUserMetadataFromHeaders.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.functions;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static org.jclouds.blobstore.reference.BlobStoreConstants.PROPERTY_USER_METADATA_PREFIX;\nimport static org.jclouds.blobstore.util.BlobStoreUtils.getNameFor;\n\nimport java.net.URI;\nimport java.util.Map.Entry;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Provider;\n\nimport org.jclouds.blobstore.domain.MutableBlobMetadata;\nimport org.jclouds.date.DateService;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpUtils;\nimport org.jclouds.rest.InvocationContext;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Function;\nimport com.google.common.net.HttpHeaders;\n\npublic class ParseSystemAndUserMetadataFromHeaders implements Function<HttpResponse, MutableBlobMetadata>,\n         InvocationContext<ParseSystemAndUserMetadataFromHeaders> {\n   private final String metadataPrefix;\n   private final DateService dateParser;\n   private final Provider<MutableBlobMetadata> metadataFactory;\n\n   private String name;\n   private URI endpoint;\n\n   @Inject\n   public ParseSystemAndUserMetadataFromHeaders(Provider<MutableBlobMetadata> metadataFactory, DateService dateParser,\n            @Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix) {\n      this.metadataFactory = checkNotNull(metadataFactory, \"metadataFactory\");\n      this.dateParser = checkNotNull(dateParser, \"dateParser\");\n      this.metadataPrefix = checkNotNull(metadataPrefix, \"metadataPrefix\").toLowerCase();\n   }\n\n   public MutableBlobMetadata apply(HttpResponse from) {\n      checkNotNull(from, \"request\");\n      checkState(name != null, \"name must be initialized by now\");\n\n      MutableBlobMetadata to = metadataFactory.get();\n      to.setName(name);\n      to.setUri(endpoint);\n      if (from.getPayload() != null)\n         HttpUtils.copy(from.getPayload().getContentMetadata(), to.getContentMetadata());\n      addETagTo(from, to);\n      parseLastModifiedOrThrowException(from, to);\n      addUserMetadataTo(from, to);\n      return to;\n   }\n\n   @VisibleForTesting\n   void addUserMetadataTo(HttpResponse from, MutableBlobMetadata metadata) {\n      for (Entry<String, String> header : from.getHeaders().entries()) {\n         if (header.getKey() != null && header.getKey().toLowerCase().startsWith(metadataPrefix))\n            metadata.getUserMetadata().put((header.getKey().substring(metadataPrefix.length())).toLowerCase(),\n                     header.getValue());\n      }\n   }\n\n   @VisibleForTesting\n   void parseLastModifiedOrThrowException(HttpResponse from, MutableBlobMetadata metadata) throws HttpException {\n      String lastModified = from.getFirstHeaderOrNull(HttpHeaders.LAST_MODIFIED);\n      if (lastModified == null) {\n         // scaleup-storage uses the wrong case for the last modified header\n         if ((lastModified = from.getFirstHeaderOrNull(\"Last-modified\")) == null)\n            throw new HttpException(HttpHeaders.LAST_MODIFIED + \" header not present in response: \" + from);\n      }\n\n      // Walrus\n      if (lastModified.startsWith(\"20\")) {\n         metadata.setLastModified(dateParser.iso8601DateParse(lastModified.replace(\"+0000\", \"Z\")));\n      } else {\n         metadata.setLastModified(dateParser.rfc822DateParse(lastModified));\n      }\n\n      if (metadata.getLastModified() == null)\n         throw new HttpException(\"could not parse: \" + HttpHeaders.LAST_MODIFIED + \": \" + lastModified);\n   }\n\n   protected void addETagTo(HttpResponse from, MutableBlobMetadata metadata) {\n      String eTag = from.getFirstHeaderOrNull(HttpHeaders.ETAG);\n      if (metadata.getETag() == null && eTag != null) {\n         metadata.setETag(eTag);\n      }\n   }\n\n   public ParseSystemAndUserMetadataFromHeaders setContext(HttpRequest request) {\n      this.endpoint = request.getEndpoint();\n      checkArgument(request instanceof GeneratedHttpRequest, \"note this handler requires a GeneratedHttpRequest\");\n      return setName(getNameFor(GeneratedHttpRequest.class.cast(request)));\n   }\n\n   public ParseSystemAndUserMetadataFromHeaders setName(String name) {\n      this.name = checkNotNull(name, \"name\");\n      return this;\n   }\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/functions/PrefixToResourceMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.blobstore.domain.MutableStorageMetadata;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.domain.StorageType;\nimport org.jclouds.blobstore.domain.internal.MutableStorageMetadataImpl;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class PrefixToResourceMetadata implements Function<String, StorageMetadata> {\n\n   public StorageMetadata apply(String from) {\n      checkNotNull(from, \"prefix\");\n      MutableStorageMetadata returnVal = new MutableStorageMetadataImpl();\n      returnVal.setType(StorageType.RELATIVE_PATH);\n      returnVal.setName(from);\n      return returnVal;\n   }\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/functions/ResourceMetadataToRelativePathResourceMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.domain.StorageType;\nimport org.jclouds.blobstore.domain.internal.StorageMetadataImpl;\nimport org.jclouds.blobstore.reference.BlobStoreConstants;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class ResourceMetadataToRelativePathResourceMetadata implements Function<StorageMetadata, StorageMetadata> {\n\n   public StorageMetadata apply(StorageMetadata md) {\n      checkNotNull(md, \"metadata\");\n      String name = checkNotNull(md.getName(), \"metadata.name\");\n      for (String suffix : BlobStoreConstants.DIRECTORY_SUFFIXES) {\n         if (name.endsWith(suffix))\n            name = name.substring(0, name.length() - suffix.length());\n      }\n      return new StorageMetadataImpl(StorageType.RELATIVE_PATH, md.getProviderId(), name, md.getLocation(),\n            md.getUri(), md.getETag(), md.getCreationDate(), md.getLastModified(), md.getUserMetadata());\n   }\n\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/internal/BaseBlobStore.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static org.jclouds.Constants.PROPERTY_USER_THREADS;\nimport static org.jclouds.blobstore.options.ListContainerOptions.Builder.recursive;\nimport static org.jclouds.util.Predicates2.retry;\n\nimport java.io.File;\nimport java.io.FilterInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.ExecutorService;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.BlobStoreContext;\nimport org.jclouds.blobstore.ContainerNotFoundException;\nimport org.jclouds.blobstore.KeyNotFoundException;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.BlobBuilder;\nimport org.jclouds.blobstore.domain.MultipartPart;\nimport org.jclouds.blobstore.domain.MultipartUpload;\nimport org.jclouds.blobstore.domain.PageSet;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.options.CopyOptions;\nimport org.jclouds.blobstore.options.ListContainerOptions;\nimport org.jclouds.blobstore.options.PutOptions;\nimport org.jclouds.blobstore.strategy.internal.MultipartUploadSlicingAlgorithm;\nimport org.jclouds.blobstore.util.BlobUtils;\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.domain.Location;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.io.ContentMetadata;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.io.PayloadSlicer;\nimport org.jclouds.util.Closeables2;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Throwables;\nimport com.google.common.util.concurrent.Futures;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.ListeningExecutorService;\n\npublic abstract class BaseBlobStore implements BlobStore {\n\n   protected final BlobStoreContext context;\n   protected final BlobUtils blobUtils;\n   protected final Supplier<Location> defaultLocation;\n   protected final Supplier<Set<? extends Location>> locations;\n   protected final PayloadSlicer slicer;\n\n   protected BaseBlobStore(BlobStoreContext context, BlobUtils blobUtils, Supplier<Location> defaultLocation,\n         @Memoized Supplier<Set<? extends Location>> locations, PayloadSlicer slicer) {\n      this.context = checkNotNull(context, \"context\");\n      this.blobUtils = checkNotNull(blobUtils, \"blobUtils\");\n      this.defaultLocation = checkNotNull(defaultLocation, \"defaultLocation\");\n      this.locations = checkNotNull(locations, \"locations\");\n      this.slicer = checkNotNull(slicer, \"slicer\");\n   }\n\n   @Override\n   public BlobStoreContext getContext() {\n      return context;\n   }\n\n   /**\n    * invokes {@link BlobUtilsImpl#blobBuilder }\n    */\n   @Override\n   public BlobBuilder blobBuilder(String name) {\n      return blobUtils.blobBuilder().name(name);\n   }\n\n   /**\n    * This implementation invokes\n    * {@link #list(String,org.jclouds.blobstore.options.ListContainerOptions)}\n    *\n    * @param container\n    *           container name\n    */\n   @Override\n   public PageSet<? extends StorageMetadata> list(String container) {\n      return this.list(container, org.jclouds.blobstore.options.ListContainerOptions.NONE);\n   }\n\n   /**\n    * This implementation invokes {@link BlobUtilsImpl#directoryExists}\n    *\n    * @param container\n    *           container name\n    * @param directory\n    *           virtual path\n    */\n   @Override\n   public boolean directoryExists(String containerName, String directory) {\n      return blobUtils.directoryExists(containerName, directory);\n   }\n\n   /**\n    * This implementation invokes {@link BlobUtilsImpl#createDirectory}\n    *\n    * @param container\n    *           container name\n    * @param directory\n    *           virtual path\n    */\n   @Override\n   public void createDirectory(String containerName, String directory) {\n      blobUtils.createDirectory(containerName, directory);\n   }\n\n   @Override\n   public void removeBlobs(String container, Iterable<String> names) {\n      for (String name : names) {\n         removeBlob(container, name);\n      }\n   }\n\n   /**\n    * This implementation invokes {@link #countBlobs} with the\n    * {@link ListContainerOptions#recursive} option.\n    *\n    * @param container\n    *           container name\n    */\n   @Override\n   public long countBlobs(String container) {\n      return countBlobs(container, recursive());\n   }\n\n   /**\n    * This implementation invokes {@link BlobUtilsImpl#countBlobs}\n    *\n    * @param container\n    *           container name\n    */\n   @Override\n   public long countBlobs(String containerName, ListContainerOptions options) {\n      return blobUtils.countBlobs(containerName, options);\n   }\n\n   /**\n    * This implementation invokes {@link #clearContainer} with the\n    * {@link ListContainerOptions#recursive} option.\n    *\n    * @param container\n    *           container name\n    */\n   @Override\n   public void clearContainer(String containerName) {\n      clearContainer(containerName, recursive());\n   }\n\n   /**\n    * This implementation invokes {@link BlobUtilsImpl#clearContainer}\n    *\n    * @param container\n    *           container name\n    */\n   @Override\n   public void clearContainer(String containerName, ListContainerOptions options) {\n      blobUtils.clearContainer(containerName, options);\n   }\n\n   /**\n    * This implementation invokes {@link BlobUtilsImpl#deleteDirectory}.\n    *\n    * @param container\n    *           container name\n    */\n   @Override\n   public void deleteDirectory(String containerName, String directory) {\n      blobUtils.deleteDirectory(containerName, directory);\n   }\n\n   /**\n    * This implementation invokes\n    * {@link #getBlob(String,String,org.jclouds.blobstore.options.GetOptions)}\n    *\n    * @param container\n    *           container name\n    * @param key\n    *           blob key\n    */\n   @Override\n   public Blob getBlob(String container, String key) {\n      return getBlob(container, key, org.jclouds.blobstore.options.GetOptions.NONE);\n   }\n\n   /**\n    * This implementation invokes {@link #deleteAndEnsurePathGone}\n    *\n    * @param container\n    *           bucket name\n    */\n   @Override\n   public void deleteContainer(String container) {\n      deletePathAndEnsureGone(container);\n   }\n\n   @Override\n   public boolean deleteContainerIfEmpty(String container) {\n      try {\n         return deleteAndVerifyContainerGone(container);\n      } catch (ContainerNotFoundException cnfe) {\n         return true;\n      }\n   }\n\n   protected void deletePathAndEnsureGone(String path) {\n      checkState(retry(new Predicate<String>() {\n         public boolean apply(String in) {\n            try {\n               clearContainer(in, recursive());\n               return deleteAndVerifyContainerGone(in);\n            } catch (ContainerNotFoundException e) {\n               return true;\n            }\n         }\n      }, 30000).apply(path), \"%s still exists after deleting!\", path);\n   }\n\n   @Override\n   public Set<? extends Location> listAssignableLocations() {\n      return locations.get();\n   }\n\n   /**\n    * Delete a container if it is empty.\n    *\n    * @param container what to delete\n    * @return whether container was deleted\n    */\n   protected abstract boolean deleteAndVerifyContainerGone(String container);\n\n   @Override\n   public String copyBlob(String fromContainer, String fromName, String toContainer, String toName,\n         CopyOptions options) {\n      Blob blob = getBlob(fromContainer, fromName);\n      if (blob == null) {\n         throw new KeyNotFoundException(fromContainer, fromName, \"while copying\");\n      }\n\n      String eTag = blob.getMetadata().getETag();\n      if (eTag != null) {\n         eTag = maybeQuoteETag(eTag);\n         if (options.ifMatch() != null && !maybeQuoteETag(options.ifMatch()).equals(eTag)) {\n            throw returnResponseException(412);\n         }\n         if (options.ifNoneMatch() != null && maybeQuoteETag(options.ifNoneMatch()).equals(eTag)) {\n            throw returnResponseException(412);\n         }\n      }\n\n      Date lastModified = blob.getMetadata().getLastModified();\n      if (lastModified != null) {\n         if (options.ifModifiedSince() != null && lastModified.compareTo(options.ifModifiedSince()) <= 0) {\n            throw returnResponseException(412);\n         }\n         if (options.ifUnmodifiedSince() != null && lastModified.compareTo(options.ifUnmodifiedSince()) >= 0) {\n            throw returnResponseException(412);\n         }\n      }\n\n      InputStream is = null;\n      try {\n         is = blob.getPayload().openStream();\n         BlobBuilder.PayloadBlobBuilder builder = blobBuilder(toName)\n               .payload(is);\n         Long contentLength = blob.getMetadata().getContentMetadata().getContentLength();\n         if (contentLength != null) {\n            builder.contentLength(contentLength);\n         }\n\n         ContentMetadata metadata;\n         if (options.contentMetadata() != null) {\n            metadata = options.contentMetadata();\n         } else {\n            metadata = blob.getMetadata().getContentMetadata();\n         }\n         builder.cacheControl(metadata.getCacheControl())\n               .contentDisposition(metadata.getContentDisposition())\n               .contentEncoding(metadata.getContentEncoding())\n               .contentLanguage(metadata.getContentLanguage())\n               .contentType(metadata.getContentType());\n\n         Map<String, String> userMetadata = options.userMetadata();\n         if (userMetadata != null) {\n            builder.userMetadata(userMetadata);\n         } else {\n            builder.userMetadata(blob.getMetadata().getUserMetadata());\n         }\n         return putBlob(toContainer, builder.build());\n      } catch (IOException ioe) {\n         throw Throwables.propagate(ioe);\n      } finally {\n         Closeables2.closeQuietly(is);\n      }\n   }\n\n   @com.google.inject.Inject\n   @Named(PROPERTY_USER_THREADS)\n   @VisibleForTesting\n   ListeningExecutorService userExecutor;\n\n   /**\n    * Upload using a user-provided executor, or the jclouds userExecutor\n    *\n    * @param container\n    * @param blob\n    * @param overrides\n    * @return the multipart blob etag\n    */\n   @Beta\n   protected String putMultipartBlob(String container, Blob blob, PutOptions overrides) {\n      if (overrides.getUseCustomExecutor()) {\n         return putMultipartBlob(container, blob, overrides, overrides.getCustomExecutor());\n      } else {\n         return putMultipartBlob(container, blob, overrides, userExecutor);\n      }\n   }\n\n   @Beta\n   protected String putMultipartBlob(String container, Blob blob, PutOptions overrides, ListeningExecutorService executor) {\n      ArrayList<ListenableFuture<MultipartPart>> parts = new ArrayList<ListenableFuture<MultipartPart>>();\n      MultipartUpload mpu = initiateMultipartUpload(container, blob.getMetadata(), overrides);\n      // Cannot slice InputStream Payload since slice and close mutate the\n      // underlying stream.  Also issue synchronous uploads to avoid buffering\n      // arbitrary amounts of data in-memory.\n      Payload payload = blob.getPayload();\n      boolean repeatable = blob.getPayload().isRepeatable();\n      if (!repeatable) {\n         payload = Payloads.newInputStreamPayload(new FilterInputStream((InputStream) payload.getRawContent()) {\n            @Override\n            public long skip(long offset) throws IOException {\n               // intentionally not implemented\n               return offset;\n            }\n\n            @Override\n            public void close() throws IOException {\n               // intentionally not implemented\n            }\n         });\n      }\n\n      try {\n         long contentLength = blob.getMetadata().getContentMetadata().getContentLength();\n         // TODO: inject MultipartUploadSlicingAlgorithm to override default part size\n         MultipartUploadSlicingAlgorithm algorithm = new MultipartUploadSlicingAlgorithm(\n               getMinimumMultipartPartSize(), getMaximumMultipartPartSize(), getMaximumNumberOfParts());\n         long partSize = algorithm.calculateChunkSize(contentLength);\n         int partNumber = 1;\n         while (partNumber <= algorithm.getParts()) {\n            Payload slice = slicer.slice(payload, algorithm.getCopied(), partSize);\n            BlobUploader b = new BlobUploader(mpu, partNumber++, slice);\n            parts.add(repeatable ? executor.submit(b) : Futures.immediateFuture(b.call()));\n            algorithm.addCopied(partSize);\n         }\n         if (algorithm.getRemaining() != 0) {\n            Payload slice = slicer.slice(payload, algorithm.getCopied(), algorithm.getRemaining());\n            BlobUploader b = new BlobUploader(mpu, partNumber, slice);\n            parts.add(repeatable ? executor.submit(b) : Futures.immediateFuture(b.call()));\n         }\n         return completeMultipartUpload(mpu, Futures.getUnchecked(Futures.allAsList(parts)));\n      } catch (RuntimeException re) {\n         abortMultipartUpload(mpu);\n         throw re;\n      }\n   }\n\n   private final class BlobUploader implements Callable<MultipartPart> {\n      private final MultipartUpload mpu;\n      private final int partNumber;\n      private final Payload payload;\n\n      BlobUploader(MultipartUpload mpu, int partNumber, Payload payload) {\n         this.mpu = mpu;\n         this.partNumber = partNumber;\n         this.payload = payload;\n      }\n\n      @Override\n      public MultipartPart call() {\n         return uploadMultipartPart(mpu, partNumber, payload);\n      }\n   }\n\n   private static HttpResponseException returnResponseException(int code) {\n      HttpResponse response = HttpResponse.builder().statusCode(code).build();\n      // TODO: bogus endpoint\n      return new HttpResponseException(new HttpCommand(HttpRequest.builder().method(\"GET\").endpoint(\"http://stub\")\n            .build()), response);\n   }\n\n   private static String maybeQuoteETag(String eTag) {\n      if (!eTag.startsWith(\"\\\"\") && !eTag.endsWith(\"\\\"\")) {\n         eTag = \"\\\"\" + eTag + \"\\\"\";\n      }\n      return eTag;\n   }\n\n   @Override\n   public void downloadBlob(String container, String name, File destination) {\n      throw new UnsupportedOperationException(\"Operation not supported yet\");\n   }\n\n   @Override\n   public void downloadBlob(String container, String name, File destination, ExecutorService executor) {\n      throw new UnsupportedOperationException(\"Operation not supported yet\");\n   }\n\n   @Override\n   public InputStream streamBlob(String container, String name) {\n      throw new UnsupportedOperationException(\"Operation not supported yet\");\n   }\n\n   @Override\n   public InputStream streamBlob(String container, String name, ExecutorService executor) {\n      throw new UnsupportedOperationException(\"Operation not supported yet\");\n   }\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/internal/BlobRuntimeException.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.internal;\n\npublic class BlobRuntimeException extends RuntimeException {\n\n   public BlobRuntimeException(String s) {\n      super(s);\n   }\n\n   public BlobRuntimeException(String s, Throwable throwable) {\n      super(s, throwable);\n   }\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/internal/BlobStoreContextImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Context;\nimport org.jclouds.blobstore.BlobRequestSigner;\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.BlobStoreContext;\nimport org.jclouds.blobstore.attr.ConsistencyModel;\nimport org.jclouds.internal.BaseView;\nimport org.jclouds.location.Provider;\nimport org.jclouds.rest.Utils;\nimport org.jclouds.util.Closeables2;\n\nimport com.google.common.reflect.TypeToken;\n\n@Singleton\npublic class BlobStoreContextImpl extends BaseView implements BlobStoreContext {\n   private final BlobStore blobStore;\n   private final ConsistencyModel consistencyModel;\n   private final Utils utils;\n   private final BlobRequestSigner blobRequestSigner;\n\n   @Inject\n   public BlobStoreContextImpl(@Provider Context backend, @Provider TypeToken<? extends Context> backendType,\n         Utils utils, ConsistencyModel consistencyModel, BlobStore blobStore, BlobRequestSigner blobRequestSigner) {\n      super(backend, backendType);\n      this.consistencyModel = checkNotNull(consistencyModel, \"consistencyModel\");\n      this.blobStore = checkNotNull(blobStore, \"blobStore\");\n      this.utils = checkNotNull(utils, \"utils\");\n      this.blobRequestSigner = checkNotNull(blobRequestSigner, \"blobRequestSigner\");\n   }\n\n   @Override\n   public ConsistencyModel getConsistencyModel() {\n      return consistencyModel;\n   }\n\n   @Override\n   public BlobStore getBlobStore() {\n      return blobStore;\n   }\n\n   @Override\n   public Utils utils() {\n      return utils;\n   }\n\n   @Override\n   public BlobRequestSigner getSigner() {\n      return blobRequestSigner;\n   }\n\n   @Override\n   public void close() {\n      Closeables2.closeQuietly(delegate());\n   }\n\n   public int hashCode() {\n      return delegate().hashCode();\n   }\n\n   @Override\n   public String toString() {\n      return delegate().toString();\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      return delegate().equals(obj);\n   }\n\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/internal/RequestSigningUnsupported.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.internal;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.blobstore.BlobRequestSigner;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.options.GetOptions;\nimport org.jclouds.http.HttpRequest;\n\n@Singleton\npublic class RequestSigningUnsupported implements BlobRequestSigner {\n\n   @Override\n   public HttpRequest signGetBlob(String container, String name) {\n      throw new UnsupportedOperationException();\n   }\n\n   @Override\n   public HttpRequest signGetBlob(String container, String name, long timeInSeconds) {\n      throw new UnsupportedOperationException();\n   }\n\n   @Override\n   public HttpRequest signGetBlob(String container, String name, GetOptions options) {\n      throw new UnsupportedOperationException();\n   }\n\n   @Override\n   public HttpRequest signPutBlob(String container, Blob blob) {\n      throw new UnsupportedOperationException();\n   }\n\n   @Override\n   public HttpRequest signPutBlob(String container, Blob blob, long timeInSeconds) {\n      throw new UnsupportedOperationException();\n   }\n\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/options/CopyOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.blobstore.options;\n\nimport java.util.Date;\nimport java.util.Map;\n\nimport org.jclouds.io.ContentMetadata;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.annotations.Beta;\nimport com.google.common.collect.ImmutableMap;\n\n@AutoValue\n@Beta\npublic abstract class CopyOptions {\n   public static final CopyOptions NONE = builder().build();\n\n   public static Builder builder() {\n      return new AutoValue_CopyOptions.Builder();\n   }\n\n   @Nullable\n   public abstract ContentMetadata contentMetadata();\n   @Nullable\n   public abstract Map<String, String> userMetadata();\n\n   @Nullable\n   public abstract Date ifModifiedSince();\n   @Nullable\n   public abstract Date ifUnmodifiedSince();\n   @Nullable\n   public abstract String ifMatch();\n   @Nullable\n   public abstract String ifNoneMatch();\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder contentMetadata(ContentMetadata contentMetadata);\n      public abstract Builder userMetadata(Map<String, String> userMetadata);\n\n      public abstract Builder ifModifiedSince(Date ifModifiedSince);\n      public abstract Builder ifUnmodifiedSince(Date ifUnmodifiedSince);\n      public abstract Builder ifMatch(String ifMatch);\n      public abstract Builder ifNoneMatch(String ifNoneMatch);\n\n      abstract Map<String, String> userMetadata();\n      abstract CopyOptions autoBuild();\n\n      public CopyOptions build() {\n         Map<String, String> userMetadata = userMetadata();\n         if (userMetadata != null) {\n            userMetadata(ImmutableMap.copyOf(userMetadata));\n         }\n         return autoBuild();\n      }\n   }\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/options/CreateContainerOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.options;\n\n/**\n * Contains options supported in the list container operation. <h2>\n * Usage</h2> The recommended way to instantiate a CreateOptions object is to statically import\n * CreateContainerOptions.* and invoke a static creation method followed by an instance mutator (if\n * needed):\n * <p/>\n * <code>\n * import static org.jclouds.blobstore.options.CreateContainerOptions.Builder.*\n * <p/>\n * BlobStore connection = // get connection\n * Future<CreateResponse<ResourceMetadata>> list = connection.list(\"container\",inDirectory(\"home/users\").maxResults(1000));\n * <code>\n */\npublic class CreateContainerOptions implements Cloneable {\n\n   public static final ImmutableCreateContainerOptions NONE = new ImmutableCreateContainerOptions(\n            new CreateContainerOptions());\n\n   private boolean publicRead;\n\n   public CreateContainerOptions() {\n   }\n\n   CreateContainerOptions(boolean publicRead) {\n      this.publicRead = publicRead;\n   }\n\n   public static class ImmutableCreateContainerOptions extends CreateContainerOptions {\n      private final CreateContainerOptions delegate;\n\n      public ImmutableCreateContainerOptions(CreateContainerOptions delegate) {\n         this.delegate = delegate;\n      }\n\n      @Override\n      public boolean isPublicRead() {\n         return delegate.isPublicRead();\n      }\n\n      @Override\n      public CreateContainerOptions publicRead() {\n         throw new UnsupportedOperationException();\n      }\n\n      @Override\n      public CreateContainerOptions clone() {\n         return delegate.clone();\n      }\n\n      @Override\n      public String toString() {\n         return delegate.toString();\n      }\n\n   }\n\n   public boolean isPublicRead() {\n      return publicRead;\n   }\n\n   /**\n    * return a listing of all objects inside the store, publicReadly.\n    */\n   public CreateContainerOptions publicRead() {\n      // checkArgument(path == null, \"path and publicRead combination currently not supported\");\n      this.publicRead = true;\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see CreateContainerOptions#publicRead()\n       */\n      public static CreateContainerOptions publicRead() {\n         CreateContainerOptions options = new CreateContainerOptions();\n         return options.publicRead();\n      }\n\n   }\n\n   @Override\n   public CreateContainerOptions clone() {\n      return new CreateContainerOptions(publicRead);\n   }\n\n   @Override\n   public String toString() {\n      return \"[publicRead=\" + publicRead + \"]\";\n   }\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/options/GetOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.options;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Date;\nimport java.util.List;\n\nimport com.google.common.collect.Lists;\n\n/**\n * Contains options supported for HTTP GET operations. <h2>\n * Usage</h2> The recommended way to instantiate a {@link GetOptions} object is to statically import\n * GetOptions.Builder.* and invoke a static creation method followed by an instance mutator (if\n * needed):\n * <p/>\n * <code>\n * import static org.jclouds.blobstore.options.GetOptions.Builder.*\n * \n * \n * // this will get the first megabyte of an blob, provided it wasn't modified since yesterday\n * blob = blobStore.getBlob(\"container, \"blobName\",range(0,1024).ifUnmodifiedSince(new Date().minusDays(1)));\n * <code>\n */\npublic class GetOptions {\n\n   public static final GetOptions NONE = new GetOptions();\n\n   private final List<String> ranges = Lists.newArrayList();\n   private Date ifModifiedSince;\n   private Date ifUnmodifiedSince;\n   private String ifMatch;\n   private String ifNoneMatch;\n\n   /**\n    * download the specified range of the object.\n    * @param start first offset included in the response\n    * @param end last offset included in the response (inclusive).\n    * @return itself to enable daisy-chaining of expressions\n    */\n   public GetOptions range(long start, long end) {\n      checkArgument(start >= 0, \"start must be >= 0\");\n      checkArgument(end >= 0, \"end must be >= 0\");\n      getRanges().add(String.format(\"%d-%d\", start, end));\n      return this;\n   }\n\n   /**\n    * download the specified range of the object.\n    */\n   public GetOptions startAt(long start) {\n      checkArgument(start >= 0, \"start must be >= 0\");\n      getRanges().add(String.format(\"%d-\", start));\n      return this;\n   }\n\n\n   /**\n    * download the specified range of the object starting from the end of the object.\n    */\n   public GetOptions tail(long length) {\n      checkArgument(length >= 0, \"length must be >= 0\");\n      getRanges().add(String.format(\"-%d\", length));\n      return this;\n   }\n\n   /**\n    * Only return the object if it has changed since this time.\n    * <p />\n    * Not compatible with {@link #ifETagMatches(String)} or {@link #ifUnmodifiedSince(Date)}\n    */\n   public GetOptions ifModifiedSince(Date ifModifiedSince) {\n      checkArgument(getIfMatch() == null, \"ifETagMatches() is not compatible with ifModifiedSince()\");\n      checkArgument(getIfUnmodifiedSince() == null, \"ifUnmodifiedSince() is not compatible with ifModifiedSince()\");\n      this.ifModifiedSince = checkNotNull(ifModifiedSince, \"ifModifiedSince\");\n      return this;\n   }\n\n   /**\n    * For use in the header If-Modified-Since\n    * <p />\n    * Return the object only if it has been modified since the specified time, otherwise return a\n    * 304 (not modified).\n    * \n    * @see GetOptions#ifModifiedSince(Date)\n    */\n   public Date getIfModifiedSince() {\n      return this.ifModifiedSince;\n   }\n\n   /**\n    * Only return the object if it hasn't changed since this time.\n    * <p />\n    * Not compatible with {@link #ifETagDoesntMatch(String)} or {@link #ifModifiedSince(Date)}\n    */\n   public GetOptions ifUnmodifiedSince(Date ifUnmodifiedSince) {\n      checkArgument(getIfNoneMatch() == null, \"ifETagDoesntMatch() is not compatible with ifUnmodifiedSince()\");\n      checkArgument(getIfModifiedSince() == null, \"ifModifiedSince() is not compatible with ifUnmodifiedSince()\");\n      this.ifUnmodifiedSince = checkNotNull(ifUnmodifiedSince, \"ifUnmodifiedSince\");\n      return this;\n   }\n\n   /**\n    * For use in the header If-Unmodified-Since\n    * <p />\n    * Return the object only if it has not been modified since the specified time, otherwise return\n    * a 412 (precondition failed).\n    * \n    * @see GetOptions#ifUnmodifiedSince(Date)\n    */\n   public Date getIfUnmodifiedSince() {\n      return this.ifUnmodifiedSince;\n   }\n\n   /**\n    * The object's eTag hash should match the parameter <code>eTag</code>.\n    * \n    * <p />\n    * Not compatible with {@link #ifETagDoesntMatch(String)} or {@link #ifModifiedSince(Date)}\n    * \n    * @param eTag\n    *           hash representing the payload\n    */\n   public GetOptions ifETagMatches(String eTag) {\n      checkArgument(getIfNoneMatch() == null, \"ifETagDoesntMatch() is not compatible with ifETagMatches()\");\n      checkArgument(getIfModifiedSince() == null, \"ifModifiedSince() is not compatible with ifETagMatches()\");\n      this.ifMatch = checkNotNull(eTag, \"eTag\");\n      return this;\n   }\n\n   /**\n    * For use in the request header: If-Match\n    * <p />\n    * Return the object only if its payload tag (ETag) is the same as the eTag specified, otherwise\n    * return a 412 (precondition failed).\n    * \n    * @see GetOptions#ifETagMatches(String)\n    */\n   public String getIfMatch() {\n      return this.ifMatch;\n   }\n\n   /**\n    * The object should not have a eTag hash corresponding with the parameter <code>eTag</code>.\n    * <p />\n    * Not compatible with {@link #ifETagMatches(String)} or {@link #ifUnmodifiedSince(Date)}\n    * \n    * @param eTag\n    *           hash representing the payload\n    */\n   public GetOptions ifETagDoesntMatch(String eTag) {\n      checkArgument(getIfMatch() == null, \"ifETagMatches() is not compatible with ifETagDoesntMatch()\");\n      checkArgument(getIfUnmodifiedSince() == null, \"ifUnmodifiedSince() is not compatible with ifETagDoesntMatch()\");\n      this.ifNoneMatch = checkNotNull(eTag, \"eTag\");\n      return this;\n   }\n\n   /**\n    * For use in the request header: If-None-Match\n    * <p />\n    * Return the object only if its payload tag (ETag) is different from the one specified,\n    * otherwise return a 304 (not modified).\n    * \n    * @see GetOptions#ifETagDoesntMatch(String)\n    */\n   public String getIfNoneMatch() {\n      return this.ifNoneMatch;\n   }\n\n   public List<String> getRanges() {\n      return ranges;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see GetOptions#range(long, long)\n       */\n      public static GetOptions range(long start, long end) {\n         GetOptions options = new GetOptions();\n         return options.range(start, end);\n      }\n\n      /**\n       * @see GetOptions#getIfModifiedSince()\n       */\n      public static GetOptions ifModifiedSince(Date ifModifiedSince) {\n         GetOptions options = new GetOptions();\n         return options.ifModifiedSince(ifModifiedSince);\n      }\n\n      /**\n       * @see GetOptions#ifUnmodifiedSince(Date)\n       */\n      public static GetOptions ifUnmodifiedSince(Date ifUnmodifiedSince) {\n         GetOptions options = new GetOptions();\n         return options.ifUnmodifiedSince(ifUnmodifiedSince);\n      }\n\n      /**\n       * @see GetOptions#ifETagMatches(String)\n       */\n      public static GetOptions ifETagMatches(String eTag) {\n         GetOptions options = new GetOptions();\n         return options.ifETagMatches(eTag);\n      }\n\n      /**\n       * @see GetOptions#ifETagDoesntMatch(String)\n       */\n      public static GetOptions ifETagDoesntMatch(String eTag) {\n         GetOptions options = new GetOptions();\n         return options.ifETagDoesntMatch(eTag);\n      }\n\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((ifMatch == null) ? 0 : ifMatch.hashCode());\n      result = prime * result + ((ifModifiedSince == null) ? 0 : ifModifiedSince.hashCode());\n      result = prime * result + ((ifNoneMatch == null) ? 0 : ifNoneMatch.hashCode());\n      result = prime * result + ((ifUnmodifiedSince == null) ? 0 : ifUnmodifiedSince.hashCode());\n      result = prime * result + ((ranges == null) ? 0 : ranges.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      GetOptions other = (GetOptions) obj;\n      if (ifMatch == null) {\n         if (other.ifMatch != null)\n            return false;\n      } else if (!ifMatch.equals(other.ifMatch))\n         return false;\n      if (ifModifiedSince == null) {\n         if (other.ifModifiedSince != null)\n            return false;\n      } else if (!ifModifiedSince.equals(other.ifModifiedSince))\n         return false;\n      if (ifNoneMatch == null) {\n         if (other.ifNoneMatch != null)\n            return false;\n      } else if (!ifNoneMatch.equals(other.ifNoneMatch))\n         return false;\n      if (ifUnmodifiedSince == null) {\n         if (other.ifUnmodifiedSince != null)\n            return false;\n      } else if (!ifUnmodifiedSince.equals(other.ifUnmodifiedSince))\n         return false;\n      if (ranges == null) {\n         if (other.ranges != null)\n            return false;\n      } else if (!ranges.equals(other.ranges))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"[ranges=\" + ranges + \", ifModifiedSince=\" + ifModifiedSince + \", ifUnmodifiedSince=\" + ifUnmodifiedSince\n               + \", ifMatch=\" + ifMatch + \", ifNoneMatch=\" + ifNoneMatch + \"]\";\n   }\n\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/options/ListAllOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.options;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Objects;\n\n/**\n * Contains options supported by BlobStores.listAll.\n *  \n * @see ListOptions for recommended usage patterns\n * \n * @since 1.3\n */\n@Beta\npublic class ListAllOptions implements Cloneable {\n\n   public static final ImmutableListAllOptions NONE = new ImmutableListAllOptions(new ListAllOptions());\n\n   private boolean eager = false;\n\n   public ListAllOptions() {\n   }\n\n   ListAllOptions(boolean eagerness) {\n      this.eager = eagerness;\n   }\n\n   public static class ImmutableListAllOptions extends ListAllOptions {\n      private final ListAllOptions delegate;\n\n      public ImmutableListAllOptions(ListAllOptions delegate) {\n         this.delegate = delegate;\n      }\n\n      @Override\n      public boolean isEager() {\n         return delegate.isEager();\n      }\n      \n      @Override\n      public ListAllOptions eager(boolean val) {\n         throw new UnsupportedOperationException();\n      }\n   }\n\n   public boolean isEager() {\n      return eager;\n   }\n\n   /**\n    * If eager, will connect to container immediately and fail-fast, rather than failing when \n    * first iterating over the list.\n    */\n   public ListAllOptions eager(boolean val) {\n      this.eager = val;\n      return this;\n   }\n\n   public static class Builder {\n      /**\n       * @see ListAllOptions#eager(boolean)\n       */\n      public static ListAllOptions eager(boolean eager) {\n         ListAllOptions options = new ListAllOptions();\n         return options.eager(eager);\n      }\n   }\n\n   @Override\n   public ListAllOptions clone() {\n      return new ListAllOptions(isEager());\n   }\n\n   @Override\n   public String toString() {\n      return \"[eager=\" + eager + \"]\";\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(eager);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      ListAllOptions other = (ListAllOptions) obj;\n      return eager == other.eager;\n   }\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/options/ListContainerOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.options;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.Objects;\n\n/**\n * Contains options supported in the list container operation. <h2>\n * Usage</h2> The recommended way to instantiate a ListOptions object is to statically import\n * ListContainerOptions.* and invoke a static creation method followed by an instance mutator (if\n * needed):\n * <p/>\n * <code>\n * import static org.jclouds.blobstore.options.ListContainerOptions.Builder.*\n * <p/>\n * BlobStore connection = // get connection\n * Future<ListResponse<ResourceMetadata>> list = connection.list(\"container\",prefix(\"home/users\").maxResults(1000));\n * <code>\n */\npublic class ListContainerOptions extends ListOptions implements Cloneable {\n\n   public static final ImmutableListContainerOptions NONE = new ImmutableListContainerOptions(\n            new ListContainerOptions());\n\n   private String delimiter;\n   private String dir;\n   private String prefix;\n   private boolean recursive;\n   private boolean detailed;\n\n   public ListContainerOptions() {\n   }\n\n   ListContainerOptions(Integer maxKeys, String marker, String dir, boolean recursive,\n            boolean detailed, String prefix, String delimiter) {\n      super(maxKeys, marker);\n      this.dir = dir;\n      this.recursive = recursive;\n      this.detailed = detailed;\n      this.prefix = prefix;\n      this.delimiter = delimiter;\n   }\n\n   public static class ImmutableListContainerOptions extends ListContainerOptions {\n      private final ListContainerOptions delegate;\n\n      @Override\n      public ListContainerOptions afterMarker(String marker) {\n         throw new UnsupportedOperationException();\n      }\n\n      public ImmutableListContainerOptions(ListContainerOptions delegate) {\n         this.delegate = delegate;\n      }\n\n      @Override\n      public String getDir() {\n         return delegate.getDir();\n      }\n\n      @Override\n      public ListContainerOptions inDirectory(String dir) {\n         throw new UnsupportedOperationException();\n      }\n\n      @Override\n      public boolean isDetailed() {\n         return delegate.isDetailed();\n      }\n\n      @Override\n      public boolean isRecursive() {\n         return delegate.isRecursive();\n      }\n\n      @Override\n      public ListContainerOptions maxResults(int maxKeys) {\n         throw new UnsupportedOperationException();\n      }\n\n      @Override\n      public ListContainerOptions recursive() {\n         throw new UnsupportedOperationException();\n\n      }\n\n      @Override\n      public String getMarker() {\n         return delegate.getMarker();\n      }\n\n      @Override\n      public Integer getMaxResults() {\n         return delegate.getMaxResults();\n      }\n\n      @Override\n      public String getPrefix() {\n         return delegate.getPrefix();\n      }\n\n      @Override\n      public ListContainerOptions prefix(String prefix) {\n         throw new UnsupportedOperationException();\n      }\n\n      @Override\n      public ListContainerOptions clone() {\n         return delegate.clone();\n      }\n\n      @Override\n      public ListContainerOptions delimiter(String delimiterString) {\n         throw new UnsupportedOperationException();\n      }\n\n      @Override\n      public String getDelimiter() {\n         return delegate.getDelimiter();\n      }\n\n      @Override\n      public String toString() {\n         return delegate.toString();\n      }\n\n   }\n\n   /**\n    * @deprecated superseded by ListContainerOptions.getPrefix and ListContainerOptions.getDelimiter.\n    */\n   @Deprecated\n   public String getDir() {\n      return dir;\n   }\n\n   public String getDelimiter() {\n      return delimiter;\n   }\n\n   public boolean isRecursive() {\n      return recursive;\n   }\n\n   public boolean isDetailed() {\n      return detailed;\n   }\n\n   public String getPrefix() {\n      return prefix;\n   }\n\n   /**\n    * This will list the contents of a virtual or real directory path.\n    *\n    * @deprecated superseded by ListContainerOptions.prefix and ListContainerOptions.delimiter.\n    */\n   @Deprecated\n   public ListContainerOptions inDirectory(String dir) {\n      checkNotNull(dir, \"dir\");\n      checkArgument(!dir.equals(\"/\"), \"dir must not be a slash\");\n      this.dir = dir;\n      return this;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ListContainerOptions afterMarker(String marker) {\n      return (ListContainerOptions) super.afterMarker(marker);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ListContainerOptions maxResults(int maxKeys) {\n      return (ListContainerOptions) super.maxResults(maxKeys);\n   }\n\n   /**\n    * return a listing of all objects inside the store, recursively.\n    */\n   public ListContainerOptions recursive() {\n      // checkArgument(path == null, \"path and recursive combination currently not supported\");\n      this.recursive = true;\n      return this;\n   }\n\n   /**\n    * populate each result with detailed such as metadata even if it incurs extra requests to the\n    * service.\n    */\n   public ListContainerOptions withDetails() {\n      this.detailed = true;\n      return this;\n   }\n\n   /**\n    * Only list keys that start with the supplied prefix\n    */\n   public ListContainerOptions prefix(String prefix) {\n      this.prefix = prefix;\n      return this;\n   }\n\n   /**\n    * specify the delimiter to be used when listing\n    *\n    */\n   public ListContainerOptions delimiter(String delimiterString) {\n      this.delimiter = delimiterString;\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see ListContainerOptions#inDirectory(String)\n       * @deprecated superseded by ListContainerOptions.prefix and ListContainerOptions.delimiter.\n       */\n      @Deprecated\n      public static ListContainerOptions inDirectory(String directory) {\n         ListContainerOptions options = new ListContainerOptions();\n         return options.inDirectory(directory);\n      }\n\n      /**\n       * @see ListContainerOptions#afterMarker(String)\n       */\n      public static ListContainerOptions afterMarker(String marker) {\n         ListContainerOptions options = new ListContainerOptions();\n         return options.afterMarker(marker);\n      }\n\n      /**\n       * @see ListContainerOptions#maxResults(int)\n       */\n      public static ListContainerOptions maxResults(int maxKeys) {\n         ListContainerOptions options = new ListContainerOptions();\n         return options.maxResults(maxKeys);\n      }\n\n      /**\n       * @see ListContainerOptions#recursive()\n       */\n      public static ListContainerOptions recursive() {\n         ListContainerOptions options = new ListContainerOptions();\n         return options.recursive();\n      }\n\n      /**\n       * @see ListContainerOptions#withDetails()\n       */\n      public static ListContainerOptions withDetails() {\n         ListContainerOptions options = new ListContainerOptions();\n         return options.withDetails();\n      }\n\n      /**\n       * @see ListContainerOptions#prefix(String)\n       */\n      public static ListContainerOptions prefix(String prefix) {\n         ListContainerOptions options = new ListContainerOptions();\n         return options.prefix(prefix);\n      }\n      /**\n        * @see ListContainerOptions#delimiter(String)\n        */\n      public static ListContainerOptions delimiter(String delimiterString) {\n         ListContainerOptions options = new ListContainerOptions();\n         return options.delimiter(delimiterString);\n      }\n   }\n\n   @Override\n   public ListContainerOptions clone() {\n      return new ListContainerOptions(getMaxResults(), getMarker(), dir, recursive, detailed, prefix, delimiter);\n   }\n\n   @Override\n   public String toString() {\n      return \"[dir=\" + dir + \", recursive=\" + recursive + \", detailed=\" + detailed\n               + \", prefix=\" + prefix + \", marker=\" + getMarker()\n               + \", delimiter=\" + delimiter\n               + \", maxResults=\" + getMaxResults() + \"]\";\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(detailed, recursive, dir, getMarker(), getMaxResults());\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      ListContainerOptions other = (ListContainerOptions) obj;\n      return (detailed == other.detailed) &&\n               recursive == other.recursive &&\n               Objects.equal(dir, other.dir) &&\n               Objects.equal(prefix, other.prefix) &&\n               Objects.equal(getMarker(), other.getMarker()) &&\n               Objects.equal(getMaxResults(), other.getMaxResults());\n   }\n\n\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/options/ListOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.options;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\n/**\n * Contains options supported in the list container operation. <h2>\n * Usage</h2> The recommended way to instantiate a ListOptions object is to statically import\n * ListOptions.* and invoke a static creation method followed by an instance mutator (if needed):\n * <p/>\n * <code>\n * import static org.jclouds.blobstore.options.ListOptions.Builder.*\n * <p/>\n * BlobStore connection = // get connection\n * Future<BoundedSortedSet<ResourceMetadata>> list = connection.list(maxResults(1000));\n * <code>\n */\npublic class ListOptions implements Cloneable {\n\n   public static class ImmutableListOptions extends ListOptions {\n      private final ListOptions delegate;\n\n      @Override\n      public ListContainerOptions afterMarker(String marker) {\n         throw new UnsupportedOperationException();\n      }\n\n      public ImmutableListOptions(ListOptions delegate) {\n         this.delegate = delegate;\n      }\n\n      @Override\n      public ListContainerOptions maxResults(int maxKeys) {\n         throw new UnsupportedOperationException();\n      }\n\n      @Override\n      public String getMarker() {\n         return delegate.getMarker();\n      }\n\n      @Override\n      public Integer getMaxResults() {\n         return delegate.getMaxResults();\n      }\n\n      @Override\n      public ListOptions clone() {\n         return delegate.clone();\n      }\n\n      @Override\n      public String toString() {\n         return delegate.toString();\n      }\n   }\n\n   public static final ImmutableListOptions NONE = new ImmutableListOptions(new ListOptions());\n\n   ListOptions(Integer maxKeys, String marker) {\n      this.maxKeys = maxKeys;\n      this.marker = marker;\n   }\n\n   public ListOptions() {\n   }\n\n   private Integer maxKeys;\n   private String marker;\n\n   public Integer getMaxResults() {\n      return maxKeys;\n   }\n\n   public String getMarker() {\n      return marker;\n   }\n\n   /**\n    * Place to continue a listing at. This must be the value returned from the last list object, as\n    * not all blobstores use lexicographic lists.\n    */\n   public ListOptions afterMarker(String marker) {\n      this.marker = checkNotNull(marker, \"marker\");\n      return this;\n   }\n\n   /**\n    * The maximum number of values you'd like to see in the response body. The server might return\n    * fewer than this many values, but will not return more.\n    */\n   public ListOptions maxResults(int maxKeys) {\n      checkArgument(maxKeys >= 0, \"maxKeys must be >= 0\");\n      this.maxKeys = maxKeys;\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see ListOptions#afterMarker(String)\n       */\n      public static ListOptions afterMarker(String marker) {\n         ListOptions options = new ListOptions();\n         return options.afterMarker(marker);\n      }\n\n      /**\n       * @see ListOptions#maxResults(int)\n       */\n      public static ListOptions maxResults(int maxKeys) {\n         ListOptions options = new ListOptions();\n         return options.maxResults(maxKeys);\n      }\n\n   }\n\n   @Override\n   protected ListOptions clone() {\n      return new ListOptions(maxKeys, marker);\n   }\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/options/PutOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.blobstore.domain.BlobAccess;\n\nimport com.google.common.base.Preconditions;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.common.util.concurrent.MoreExecutors;\n\n/**\n * Contains options supported in the put blob operation. <h2>\n * Usage</h2> The recommended way to instantiate a PutOptions object is to statically import\n * PutOptions.* and invoke a static creation method followed by an instance mutator (if needed):\n * <p/>\n * <code>\n * import static org.jclouds.blobstore.options.PutOptions.Builder.*\n * eTag = blobStore.putBlob(\"container\", blob, multipart());\n * <code>\n */\npublic class PutOptions implements Cloneable {\n\n   public static final ImmutablePutOptions NONE = new ImmutablePutOptions(new PutOptions());\n\n   private BlobAccess blobAccess = BlobAccess.PRIVATE;\n   private boolean multipart = false;\n   private boolean useCustomExecutor = false;\n\n   // TODO: This exposes ListeningExecutorService to the user, instead of a regular ExecutorService\n   private ListeningExecutorService customExecutor = MoreExecutors.newDirectExecutorService();\n\n   public PutOptions() {\n   }\n\n   public PutOptions(boolean multipart) {\n      this.multipart = multipart;\n   }\n\n   /**\n    * Used for clone\n    * @param multipart\n    * @param customExecutor\n    */\n   protected PutOptions(boolean multipart, boolean useCustomExecutor,  ListeningExecutorService customExecutor) {\n      Preconditions.checkNotNull(customExecutor);\n      this.multipart = multipart;\n      this.useCustomExecutor = useCustomExecutor;\n      this.customExecutor = customExecutor;\n   }\n\n   public PutOptions(ListeningExecutorService customExecutor) {\n      Preconditions.checkNotNull(customExecutor);\n      this.multipart = true;\n      this.useCustomExecutor = true;\n      this.customExecutor = customExecutor;\n   }\n\n   public static class ImmutablePutOptions extends PutOptions {\n      private final PutOptions delegate;\n\n      public ImmutablePutOptions(PutOptions delegate) {\n         this.delegate = delegate;\n      }\n\n      @Override\n      public ListeningExecutorService getCustomExecutor() {\n         return delegate.getCustomExecutor();\n      }\n\n      @Override\n      public PutOptions setCustomExecutor(ListeningExecutorService customExecutor) {\n         throw new UnsupportedOperationException();\n      }\n\n      @Override\n      public BlobAccess getBlobAccess() {\n         return delegate.getBlobAccess();\n      }\n\n      @Override\n      public PutOptions setBlobAccess(BlobAccess blobAccess) {\n         throw new UnsupportedOperationException();\n      }\n\n      @Override\n      public boolean isMultipart() {\n         return delegate.isMultipart();\n      }\n\n      @Override\n      public PutOptions multipart() {\n         throw new UnsupportedOperationException();\n      }\n\n      @Override\n      public PutOptions clone() {\n         return delegate.clone();\n      }\n\n      @Override\n      public String toString() {\n         return delegate.toString();\n      }\n\n   }\n\n   public BlobAccess getBlobAccess() {\n      return blobAccess;\n   }\n\n   public boolean getUseCustomExecutor() {\n      return useCustomExecutor;\n   }\n\n   public ListeningExecutorService getCustomExecutor() {\n      return customExecutor;\n   }\n\n   public PutOptions setCustomExecutor(ListeningExecutorService customExecutor) {\n      Preconditions.checkNotNull(customExecutor);\n      this.multipart = true;\n      this.useCustomExecutor = true;\n      this.customExecutor = customExecutor;\n      return this;\n   }\n\n   public PutOptions setBlobAccess(BlobAccess blobAccess) {\n      this.blobAccess = checkNotNull(blobAccess);\n      return this;\n   }\n\n   public boolean isMultipart() {\n      return multipart;\n   }\n\n   /**\n    * split large blobs into pieces, if supported by the provider.\n    *\n    * Equivalent to <code>multipart(true)</code>\n    */\n   public PutOptions multipart() {\n      return multipart(true);\n   }\n\n   /**\n    * whether to split large blobs into pieces, if supported by the provider\n    */\n   public PutOptions multipart(boolean val) {\n      this.multipart = val;\n      return this;\n   }\n\n   /**\n    * Whether to split large blobs into pieces, if supported by the provider, using a custom executor\n    *\n    * @param customExecutor User-provided ListeningExecutorService\n    */\n   public PutOptions multipart(ListeningExecutorService customExecutor) {\n      Preconditions.checkNotNull(customExecutor);\n      this.multipart = true;\n      this.useCustomExecutor = true;\n      this.customExecutor = customExecutor;\n      return this;\n   }\n\n   public static class Builder {\n\n      public static PutOptions fromPutOptions(PutOptions putOptions) {\n         return multipart(putOptions.multipart);\n      }\n\n      /**\n       * @see PutOptions#multipart()\n       */\n      public static PutOptions multipart() {\n         return multipart(true);\n      }\n\n      public static PutOptions multipart(boolean val) {\n         PutOptions options = new PutOptions();\n         return options.multipart(val);\n      }\n\n      public static PutOptions multipart(ListeningExecutorService customExecutor) {\n         PutOptions options = new PutOptions();\n         return options.multipart(customExecutor);\n      }\n   }\n\n   @Override\n   public PutOptions clone() {\n      return new PutOptions(multipart, useCustomExecutor, customExecutor);\n   }\n\n   @Override\n   public String toString() {\n      return \"[multipart=\" + multipart +\n            \", blobAccess=\" + blobAccess +\n            \", useCustomExecutor=\" + useCustomExecutor +\n            \", customExecutor=\" + customExecutor + \"]\";\n   }\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/reference/BlobStoreConstants.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.reference;\n\nimport java.util.Collection;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Configuration properties and constants used in BlobStore connections.\n */\npublic final class BlobStoreConstants {\n   /**\n    * <p/>\n    * To interoperate with other S3 tools, we also accept the following:\n    * <ul>\n    * <li>an object named '#{dirpath}_$folder$' or '#{dirpath}/' denoting a directory marker</li>\n    * <li>an object with content type set to 'application/directory' denoting a directory marker</li>\n    * <li>if there exists any objects with the prefix \"#{dirpath}/\", then the directory is said to\n    * exist</li>\n    * <li>if both a file with the name of a directory and a marker for that directory exists, then\n    * the *file masks the directory*, and the directory is never returned.</li>\n    * </ul>\n    */\n   public static final String DIRECTORY_SUFFIX_ROOT = \"/\";\n   public static final String DIRECTORY_SUFFIX_FOLDER = \"_$folder$\";\n   public static final Collection<String> DIRECTORY_SUFFIXES =\n         ImmutableList.of(DIRECTORY_SUFFIX_FOLDER, DIRECTORY_SUFFIX_ROOT, \"/\", \"\\\\\");\n\n   /**\n    * Key-value implementations of BlobStore, such as S3, do not have directories. We use an empty\n    * object '#{dirpath}_$folder$' with content type set to 'application/directory'.\n    */\n   public static final String PROPERTY_BLOBSTORE_DIRECTORY_SUFFIX = \"jclouds.blobstore.directorysuffix\";\n\n   /**\n    * Any header starting with this prefix is considered user metadata. It will be stored with the\n    * object and returned when you retrieve the object/\n    */\n   public static final String PROPERTY_USER_METADATA_PREFIX = \"jclouds.blobstore.metaprefix\";\n\n   public static final String BLOBSTORE_LOGGER = \"jclouds.blobstore\";\n   public static final String DIRECTORY_BLOB_SUFFIX = \"/\";\n\n   private BlobStoreConstants() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/reference/package-info.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * This package contains properties and reference data used in blob service.\n */\npackage org.jclouds.blobstore.reference;\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/strategy/ClearContainerStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.strategy;\n\nimport org.jclouds.blobstore.strategy.internal.DeleteAllKeysInList;\n\nimport com.google.inject.ImplementedBy;\n\n/**\n * Clears a container\n */\n@ImplementedBy(DeleteAllKeysInList.class)\npublic interface ClearContainerStrategy {\n\n   void execute(String containerName);\n\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/strategy/ClearListStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.strategy;\n\nimport org.jclouds.blobstore.options.ListContainerOptions;\nimport org.jclouds.blobstore.strategy.internal.DeleteAllKeysInList;\n\nimport com.google.inject.ImplementedBy;\n\n/**\n * Clears a container\n */\n@ImplementedBy(DeleteAllKeysInList.class)\npublic interface ClearListStrategy {\n\n   void execute(String containerName, ListContainerOptions options);\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/strategy/CountListStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.strategy;\n\nimport org.jclouds.blobstore.options.ListContainerOptions;\nimport org.jclouds.blobstore.strategy.internal.CountBlobTypeInList;\n\nimport com.google.inject.ImplementedBy;\n\n/**\n * Number of objects in a container\n */\n@ImplementedBy(CountBlobTypeInList.class)\npublic interface CountListStrategy {\n\n   long execute(String containerName, ListContainerOptions options);\n\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/strategy/DeleteDirectoryStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.strategy;\n\nimport org.jclouds.blobstore.strategy.internal.MarkersDeleteDirectoryStrategy;\n\nimport com.google.inject.ImplementedBy;\n\n/**\n * Deletes a directory.\n */\n@ImplementedBy(MarkersDeleteDirectoryStrategy.class)\npublic interface DeleteDirectoryStrategy {\n\n   void execute(String containerName, String directory);\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/strategy/GetBlobsInListStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.strategy;\n\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.options.ListContainerOptions;\nimport org.jclouds.blobstore.strategy.internal.GetAllBlobsInListAndRetryOnFailure;\n\nimport com.google.inject.ImplementedBy;\n\n/**\n * Retrieves all blobs in the blobstore by the most efficient means possible.\n */\n@ImplementedBy(GetAllBlobsInListAndRetryOnFailure.class)\npublic interface GetBlobsInListStrategy {\n\n   Iterable<Blob> execute(String containerName, ListContainerOptions options);\n\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/strategy/GetDirectoryStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.strategy;\n\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.strategy.internal.MarkersGetDirectoryStrategy;\n\nimport com.google.inject.ImplementedBy;\n\n/**\n * Gets a directory or throws KeyNotFoundException\n */\n@ImplementedBy(MarkersGetDirectoryStrategy.class)\npublic interface GetDirectoryStrategy {\n\n   StorageMetadata execute(String containerName, String directory);\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/strategy/ListBlobsInContainer.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.strategy;\n\nimport java.util.Set;\n\nimport org.jclouds.blobstore.domain.BlobMetadata;\nimport org.jclouds.blobstore.options.ListContainerOptions;\nimport org.jclouds.blobstore.strategy.internal.ListContainerAndRecurseThroughFolders;\n\nimport com.google.inject.ImplementedBy;\n\n/**\n * Lists the blobstore.\n */\n@ImplementedBy(ListContainerAndRecurseThroughFolders.class)\npublic interface ListBlobsInContainer {\n\n   Set<? extends BlobMetadata> execute(String containerName, ListContainerOptions options);\n\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/strategy/ListContainerStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.strategy;\n\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.options.ListContainerOptions;\nimport org.jclouds.blobstore.strategy.internal.ConcatenateContainerLists;\n\nimport com.google.inject.ImplementedBy;\n\n/**\n * Lists the blobstore.\n */\n@ImplementedBy(ConcatenateContainerLists.class)\npublic interface ListContainerStrategy {\n\n   Iterable<? extends StorageMetadata> execute(String containerName, ListContainerOptions options);\n\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/strategy/MkdirStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.strategy;\n\nimport org.jclouds.blobstore.strategy.internal.MarkerFileMkdirStrategy;\n\nimport com.google.inject.ImplementedBy;\n\n/**\n * Creates a directory\n */\n@ImplementedBy(MarkerFileMkdirStrategy.class)\npublic interface MkdirStrategy {\n\n   void execute(String containerName, String directory);\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/strategy/PutBlobsStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.strategy;\n\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.strategy.internal.PutBlobsStrategyImpl;\n\nimport com.google.inject.ImplementedBy;\n\n/**\n * puts all blobs into the blobstore by the most efficient means possible.\n */\n@ImplementedBy(PutBlobsStrategyImpl.class)\npublic interface PutBlobsStrategy {\n\n   void execute(String containerName, Iterable<? extends Blob> collection);\n\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/strategy/internal/ConcatenateContainerLists.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.strategy.internal;\n\nimport java.util.List;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.domain.PageSet;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.internal.BlobRuntimeException;\nimport org.jclouds.blobstore.options.ListContainerOptions;\nimport org.jclouds.blobstore.options.ListContainerOptions.ImmutableListContainerOptions;\nimport org.jclouds.blobstore.strategy.ListContainerStrategy;\n\nimport com.google.common.base.Throwables;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Lists;\nimport com.google.inject.Inject;\n\n/**\n * Retrieves all metadata in the blobstore by the most efficient means possible.\n */\n@Singleton\npublic class ConcatenateContainerLists implements ListContainerStrategy {\n\n   protected final BlobStore connection;\n\n   @Inject\n   public ConcatenateContainerLists(BlobStore connection) {\n      this.connection = connection;\n   }\n\n   @Override\n   public Iterable<? extends StorageMetadata> execute(String container, ListContainerOptions options) {\n      try {\n         boolean truncated = true;\n         List<PageSet<? extends StorageMetadata>> listings = Lists.newArrayList();\n         while (truncated) {\n            PageSet<? extends StorageMetadata> listing = connection.list(container, options);\n            truncated = listing.getNextMarker() != null;\n            if (truncated) {\n               options = options instanceof ImmutableListContainerOptions ? options.clone()\n                        .afterMarker(listing.getNextMarker()) : options.afterMarker(listing\n                        .getNextMarker());\n            }\n            listings.add(listing);\n         }\n         return Iterables.concat(listings);\n      } catch (Exception e) {\n         Throwables.propagateIfPossible(e, BlobRuntimeException.class);\n         throw new BlobRuntimeException(\"Error getting resource metadata in container: \"\n                  + container, e);\n      }\n   }\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/strategy/internal/CountBlobTypeInList.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.strategy.internal;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.blobstore.options.ListContainerOptions;\nimport org.jclouds.blobstore.strategy.CountListStrategy;\nimport org.jclouds.blobstore.strategy.ListBlobsInContainer;\n\nimport com.google.common.collect.Iterables;\n\n/**\n * counts all blobs in the blobstore at the prefix by the most efficient means possible.\n */\n@Singleton\npublic class CountBlobTypeInList implements CountListStrategy {\n   protected final ListBlobsInContainer getAllBlobMetadata;\n\n   @Inject\n   CountBlobTypeInList(ListBlobsInContainer getAllBlobMetadata) {\n      this.getAllBlobMetadata = getAllBlobMetadata;\n   }\n\n   public long execute(String container, ListContainerOptions options) {\n      return Iterables.size(getAllBlobMetadata.execute(container, options));\n   }\n\n   public long execute(String container) {\n      return execute(container, null);\n   }\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/strategy/internal/DeleteAllKeysInList.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.strategy.internal;\n\nimport static org.jclouds.blobstore.options.ListContainerOptions.Builder.recursive;\n\nimport java.util.HashSet;\nimport java.util.Collections;\nimport java.util.Set;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.Semaphore;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.TimeoutException;\nimport java.util.concurrent.atomic.AtomicBoolean;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Constants;\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.ContainerNotFoundException;\nimport org.jclouds.blobstore.domain.PageSet;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.internal.BlobRuntimeException;\nimport org.jclouds.blobstore.options.ListContainerOptions;\nimport org.jclouds.blobstore.reference.BlobStoreConstants;\nimport org.jclouds.blobstore.strategy.ClearContainerStrategy;\nimport org.jclouds.blobstore.strategy.ClearListStrategy;\nimport org.jclouds.http.handlers.BackoffLimitedRetryHandler;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.util.concurrent.FutureCallback;\nimport com.google.common.util.concurrent.Futures;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.common.util.concurrent.MoreExecutors;\nimport com.google.inject.Inject;\n\n/**\n * Deletes all keys in the container\n */\n@Singleton\npublic class DeleteAllKeysInList implements ClearListStrategy, ClearContainerStrategy {\n   @Resource\n   @Named(BlobStoreConstants.BLOBSTORE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   protected final BackoffLimitedRetryHandler retryHandler;\n\n   private final ListeningExecutorService executorService;\n\n   protected final BlobStore blobStore;\n\n   /** Maximum duration in milliseconds of a request. */\n   protected long maxTime = Long.MAX_VALUE;\n\n   /** Maximum times to retry an operation. */\n   protected int maxErrors = 3;\n\n   /** Maximum parallel deletes. */\n   private int maxParallelDeletes;\n\n   @Inject\n   DeleteAllKeysInList(@Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService executorService,\n         BlobStore blobStore, BackoffLimitedRetryHandler retryHandler,\n         @Named(Constants.PROPERTY_MAX_PARALLEL_DELETES) int maxParallelDeletes) {\n      this.executorService = executorService;\n      this.blobStore = blobStore;\n      this.retryHandler = retryHandler;\n      this.maxParallelDeletes = maxParallelDeletes;\n   }\n\n   @Inject(optional = true)\n   void setMaxTime(@Named(Constants.PROPERTY_REQUEST_TIMEOUT) long maxTime) {\n      this.maxTime = maxTime;\n   }\n\n   @Inject(optional = true)\n   void setMaxErrors(@Named(Constants.PROPERTY_MAX_RETRIES) int maxErrors) {\n      this.maxErrors = maxErrors;\n   }\n\n   public void execute(String containerName) {\n      execute(containerName, recursive());\n   }\n\n   private boolean parentIsFolder(final ListContainerOptions options,\n         final StorageMetadata md) {\n      return options.getDir() != null && md.getName().indexOf('/') == -1;\n   }\n\n   private void cancelOutstandingFutures(\n         final Set<ListenableFuture<Void>> outstandingFutures) {\n      for (ListenableFuture<Void> future : outstandingFutures) {\n         future.cancel(/*mayInterruptIfRunning=*/ true);\n      }\n   }\n\n   private String getMessage(final String containerName,\n         final ListContainerOptions options) {\n      return options.getDir() != null ? String.format(\"clearing path %s/%s\",\n            containerName, options.getDir()) : String.format(\n            \"clearing container %s\", containerName);\n   }\n\n   /**\n    * Get the object listing from a given container based on the options. For\n    * recursive listing of directories, identify a directory and call execute()\n    * with the appropriate options to get listing inside the directory.\n    *\n    * @param containerName\n    *           The container from which to get the object list.\n    * @param options\n    *           The options used for getting the listing.\n    * @returns A PageSet of StorageMetadata objects.\n    */\n   private PageSet<? extends StorageMetadata> getListing(\n         final String containerName,\n         final ListContainerOptions options,\n         final Semaphore semaphore,\n         final Set<ListenableFuture<Void>> outstandingFutures,\n         final AtomicBoolean deleteFailure) {\n      // fetch partial directory listing\n      PageSet<? extends StorageMetadata> listing = null;\n\n      // There's nothing much to do if the container doesn't exist.\n      // Note that if the container has just been created, trying to get the\n      // container listing might throw a ContainerNotFoundException because of\n      // eventual consistency.\n      try {\n         listing = blobStore.list(containerName, options);\n      } catch (ContainerNotFoundException ce) {\n         return listing;\n      }\n\n      // recurse on subdirectories\n      if (options.isRecursive()) {\n         for (StorageMetadata md : listing) {\n            String fullPath = parentIsFolder(options, md) ? options.getDir()\n                  + \"/\" + md.getName() : md.getName();\n            switch (md.getType()) {\n            case BLOB:\n               break;\n            case FOLDER:\n            case RELATIVE_PATH:\n               if (!fullPath.equals(options.getDir())) {\n                  executeOneIteration(containerName,\n                     options.clone().inDirectory(fullPath), semaphore,\n                     outstandingFutures, deleteFailure, /*blocking=*/ true);\n               }\n               break;\n            case CONTAINER:\n               throw new IllegalArgumentException(\n                  \"Container type not supported\");\n            }\n         }\n      }\n\n      return listing;\n   }\n\n   private ListenableFuture<Void> deleteDirectory(final ListContainerOptions options,\n         final String containerName, final String dirName) {\n      ListenableFuture<Void> blobDelFuture;\n\n      if (options.isRecursive()) {\n         blobDelFuture = executorService.submit(new Callable<Void>() {\n            @Override\n            public Void call() {\n               blobStore.deleteDirectory(containerName, dirName);\n               return null;\n            }\n         });\n      } else {\n         blobDelFuture = null;\n      }\n\n      return blobDelFuture;\n   }\n\n   /**\n    * Delete the blobs from a given PageSet. The PageSet may contain blobs or\n    * directories. If there are directories, they are expected to be empty.\n    *\n    * The logic of acquiring a semaphore, submitting a callable to the\n    * executorService and releasing the semaphore resides here.\n    *\n    * @param containerName\n    *           The container from which the objects are listed.\n    * @param options\n    *           The options used for getting the container listing.\n    * @param listing\n    *           The actual list of objects.\n    * @param semaphore\n    *           The semaphore used for making sure that only a certain number of\n    *           futures are outstanding.\n    * @param deleteFailure\n    *           This is set to true if any future used for deleting blobs\n    *           failed.\n    * @param outstandingFutures\n    *           The List of outstanding futures.\n    * @throws TimeoutException\n    *            If any blob deletion takes too long.\n    */\n   private void deleteBlobsAndEmptyDirs(final String containerName,\n         ListContainerOptions options,\n         PageSet<? extends StorageMetadata> listing, final Semaphore semaphore,\n         final AtomicBoolean deleteFailure,\n         final Set<ListenableFuture<Void>> outstandingFutures)\n         throws TimeoutException {\n      for (final StorageMetadata md : listing) {\n         final String fullPath = parentIsFolder(options, md) ? options.getDir()\n               + \"/\" + md.getName() : md.getName();\n\n         // Attempt to acquire a semaphore within the time limit. At least\n         // one outstanding future should complete within this period for the\n         // semaphore to be acquired.\n         try {\n            if (!semaphore.tryAcquire(maxTime, TimeUnit.MILLISECONDS)) {\n               throw new TimeoutException(\"Timeout waiting for semaphore\");\n            }\n         } catch (InterruptedException ie) {\n            logger.debug(\"Interrupted while deleting blobs\");\n            Thread.currentThread().interrupt();\n         }\n\n         final ListenableFuture<Void> blobDelFuture;\n         switch (md.getType()) {\n         case FOLDER:\n         case BLOB:\n            blobDelFuture = executorService.submit(new Callable<Void>() {\n               @Override\n               public Void call() {\n                  blobStore.removeBlob(containerName, fullPath);\n                  return null;\n               }\n            });\n            break;\n         case RELATIVE_PATH:\n            blobDelFuture = deleteDirectory(options, containerName,\n                  md.getName());\n            break;\n         case CONTAINER:\n            throw new IllegalArgumentException(\"Container type not supported\");\n         default:\n            blobDelFuture = null;\n         }\n\n         // If a future to delete a blob/directory actually got created above,\n         // keep a reference of that in the outstandingFutures list. This is\n         // useful in case of a timeout exception. All outstanding futures can\n         // then be cancelled.\n         if (blobDelFuture != null) {\n            outstandingFutures.add(blobDelFuture);\n\n            // Add a callback to release the semaphore. This is required for\n            // other threads waiting to acquire a semaphore above to make\n            // progress.\n            Futures.addCallback(blobDelFuture, new FutureCallback<Object>() {\n               @Override\n               public void onSuccess(final Object o) {\n                  outstandingFutures.remove(blobDelFuture);\n                  semaphore.release();\n               }\n\n               @Override\n               public void onFailure(final Throwable t) {\n                  // Make a note the fact that some blob/directory could not be\n                  // deleted successfully. This is used for retrying later.\n                  deleteFailure.set(true);\n                  outstandingFutures.remove(blobDelFuture);\n                  semaphore.release();\n               }\n            }, MoreExecutors.directExecutor());\n         } else {\n            // It is possible above to acquire a semaphore but not submit any\n            // task to the executorService. For e.g. if the listing contains\n            // an object of type 'FOLDER' and the ListContianerOptions are *not*\n            // recursive. In this case, there is no blobDelFuture and therefore\n            // no FutureCallback to release the semaphore. This semaphore is\n            // released here.\n            semaphore.release();\n         }\n      }\n   }\n\n   /**\n    * This method goes through all the blobs from a container and attempts to\n    * create futures for deleting them. If there is a TimeoutException when\n    * doing this, sets the deleteFailure flag to true and returns. If there are\n    * more retries left, this will get called again.\n    *\n    * @param containerName\n    *           The container from which to get the object list.\n    * @param listOptions\n    *           The options used for getting the listing.\n    * @param semaphore\n    *           The semaphore used for controlling number of outstanding\n    *           futures.\n    * @param outstandingFutures\n    *           A list of outstanding futures.\n    * @param deleteFailure\n    *           A flag used to track of whether there was a failure while\n    *           deleting any blob.\n    * @param blocking\n    *           when true, block until all outstanding operations have completed\n    * @return A PageSet of StorageMetadata objects.\n    */\n   @VisibleForTesting\n   void executeOneIteration(\n         final String containerName,\n         ListContainerOptions listOptions, final Semaphore semaphore,\n         final Set<ListenableFuture<Void>> outstandingFutures,\n         final AtomicBoolean deleteFailure, final boolean blocking) {\n      ListContainerOptions options = listOptions.clone();\n      String message = getMessage(containerName, listOptions);\n      if (options.isRecursive()) {\n         message += \" recursively\";\n      }\n      logger.debug(message);\n\n      PageSet<? extends StorageMetadata> listing = getListing(containerName,\n            options, semaphore, outstandingFutures, deleteFailure);\n      while (listing != null && !listing.isEmpty()) {\n         try {\n            // Remove blobs and now-empty subdirectories.\n            deleteBlobsAndEmptyDirs(containerName, options, listing, semaphore,\n                  deleteFailure, outstandingFutures);\n         } catch (TimeoutException te) {\n            logger.debug(\"TimeoutException while deleting blobs: {}\",\n                  te.getMessage());\n            cancelOutstandingFutures(outstandingFutures);\n            deleteFailure.set(true);\n         }\n\n         String marker = listing.getNextMarker();\n         if (marker != null) {\n            logger.debug(\"%s with marker %s\", message, marker);\n            options = options.afterMarker(marker);\n            listing = getListing(containerName, options, semaphore,\n                  outstandingFutures, deleteFailure);\n         } else {\n            break;\n         }\n      }\n\n      if (blocking) {\n         waitForCompletion(semaphore, outstandingFutures);\n      }\n   }\n\n   private void waitForCompletion(final Semaphore semaphore,\n         final Set<ListenableFuture<Void>> outstandingFutures) {\n      // Wait for all futures to complete by waiting to acquire all\n      // semaphores.\n      try {\n         semaphore.acquire(maxParallelDeletes);\n         semaphore.release(maxParallelDeletes);\n      } catch (InterruptedException e) {\n         logger.debug(\"Interrupted while waiting for blobs to be deleted\");\n         cancelOutstandingFutures(outstandingFutures);\n         Thread.currentThread().interrupt();\n      }\n   }\n\n   public void execute(final String containerName,\n         ListContainerOptions listOptions) {\n      final AtomicBoolean deleteFailure = new AtomicBoolean();\n      int retries = maxErrors;\n\n      /*\n       * A Semaphore is used to control the number of outstanding delete\n       * requests. One permit of the semaphore is acquired before submitting a\n       * request to the executorService to delete a blob. As requests complete,\n       * their FutureCallback will release the semaphore permit. That will allow\n       * the next delete request to proceed.\n       *\n       * If no Future completes in 'maxTime', i.e. a semaphore cannot be\n       * acquired in 'maxTime', a TimeoutException is thrown. Any outstanding\n       * futures at that time are cancelled.\n       */\n      final Semaphore semaphore = new Semaphore(maxParallelDeletes);\n      /*\n       * When a future is created, a reference for that is added to the\n       * outstandingFutures list. This reference is removed from the list in the\n       * FutureCallback since it no longer needs to be cancelled in the event of\n       * a timeout. Also, when the reference is removed from this list and when\n       * the executorService removes the reference that it has maintained, the\n       * future will be marked for GC since there should be no other references\n       * to it. This is important because this code can generate an unbounded\n       * number of futures.\n       */\n      final Set<ListenableFuture<Void>> outstandingFutures = Collections\n            .synchronizedSet(new HashSet<ListenableFuture<Void>>());\n      // TODO: Remove this retry loop.\n      while (retries > 0) {\n         deleteFailure.set(false);\n         executeOneIteration(containerName, listOptions, semaphore,\n               outstandingFutures, deleteFailure, /*blocking=*/ false);\n         waitForCompletion(semaphore, outstandingFutures);\n\n         // Try again if there was any failure while deleting blobs and the max\n         // retry count hasn't been reached.\n         if (deleteFailure.get() && --retries > 0) {\n            String message = getMessage(containerName, listOptions);\n            retryHandler.imposeBackoffExponentialDelay(maxErrors - retries,\n                  message);\n         } else {\n            break;\n         }\n      }\n\n      if (retries == 0) {\n         cancelOutstandingFutures(outstandingFutures);\n         throw new BlobRuntimeException(\"Exceeded maximum retry attempts\");\n      }\n   }\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/strategy/internal/FetchBlobMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.strategy.internal;\n\nimport static com.google.common.base.Preconditions.checkState;\nimport static org.jclouds.concurrent.FutureIterables.transformParallel;\n\nimport java.util.Collections;\nimport java.util.LinkedHashMap;\nimport java.util.Map;\nimport java.util.concurrent.Callable;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\n\nimport com.google.common.util.concurrent.Futures;\nimport org.jclouds.Constants;\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.domain.PageSet;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.domain.StorageType;\nimport org.jclouds.blobstore.domain.internal.PageSetImpl;\nimport org.jclouds.blobstore.reference.BlobStoreConstants;\nimport org.jclouds.http.handlers.BackoffLimitedRetryHandler;\nimport org.jclouds.javax.annotation.concurrent.NotThreadSafe;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.Lists;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.inject.Inject;\n\n/**\n * Retrieves all blobmetadata in the list as efficiently as possible\n */\n@NotThreadSafe\npublic class FetchBlobMetadata implements Function<PageSet<? extends StorageMetadata>, PageSet<? extends StorageMetadata>> {\n\n   protected final BackoffLimitedRetryHandler retryHandler;\n   protected final BlobStore blobstore;\n   protected final ListeningExecutorService userExecutor;\n   @Resource\n   @Named(BlobStoreConstants.BLOBSTORE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   private String container;\n   /**\n    * maximum duration of an blob Request\n    */\n   @Inject(optional = true)\n   @Named(Constants.PROPERTY_REQUEST_TIMEOUT)\n   protected Long maxTime;\n\n   @Inject\n   FetchBlobMetadata(@Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor, BlobStore blobstore,\n            BackoffLimitedRetryHandler retryHandler) {\n      this.userExecutor = userExecutor;\n      this.blobstore = blobstore;\n      this.retryHandler = retryHandler;\n   }\n\n   public FetchBlobMetadata setContainerName(String container) {\n      this.container = container;\n      return this;\n   }\n\n   public PageSet<? extends StorageMetadata> apply(PageSet<? extends StorageMetadata> in) {\n      checkState(container != null, \"container name should be initialized\");\n\n      if (in == null) {\n         return new PageSetImpl<>(Collections.<StorageMetadata>emptyList(), null);\n      }\n\n      Map<String, StorageMetadata> orderedMap = new LinkedHashMap<>(in.size());\n      for (StorageMetadata storageMetadata : in) {\n         orderedMap.put(storageMetadata.getName(), null);\n      }\n\n      Iterable<StorageMetadata> returnv = Lists.newArrayList(transformParallel(in,\n          new Function<StorageMetadata, ListenableFuture<? extends StorageMetadata>>() {\n\n         @Override\n         public ListenableFuture<StorageMetadata> apply(final StorageMetadata from) {\n            if (from.getType() != StorageType.BLOB) {\n               return Futures.immediateFuture(from);\n            }\n            return userExecutor.submit(new Callable<StorageMetadata>() {\n               @Override public StorageMetadata call() {\n                  return blobstore.blobMetadata(container, from.getName());\n               }\n            });\n         }\n\n      }, userExecutor, maxTime, logger, String.format(\"getting metadata from containerName: %s\", container)));\n\n      for (StorageMetadata storageMetadata : returnv) {\n         orderedMap.put(storageMetadata.getName(), storageMetadata);\n      }\n\n      return new PageSetImpl<>(orderedMap.values(), in.getNextMarker());\n   }\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/strategy/internal/GetAllBlobsInListAndRetryOnFailure.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.strategy.internal;\n\nimport static org.jclouds.concurrent.FutureIterables.transformParallel;\n\nimport java.util.concurrent.Callable;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Constants;\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.BlobMetadata;\nimport org.jclouds.blobstore.options.ListContainerOptions;\nimport org.jclouds.blobstore.reference.BlobStoreConstants;\nimport org.jclouds.blobstore.strategy.GetBlobsInListStrategy;\nimport org.jclouds.blobstore.strategy.ListBlobsInContainer;\nimport org.jclouds.http.handlers.BackoffLimitedRetryHandler;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Function;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.inject.Inject;\n\n/**\n * Retrieves all blobs in the blobstore under the current path, by the most efficient means\n * possible.\n */\n@Singleton\npublic class GetAllBlobsInListAndRetryOnFailure implements GetBlobsInListStrategy {\n\n   protected final ListBlobsInContainer getAllBlobMetadata;\n   protected final BackoffLimitedRetryHandler retryHandler;\n   protected final BlobStore blobstore;\n   protected final ListeningExecutorService userExecutor;\n   @Resource\n   @Named(BlobStoreConstants.BLOBSTORE_LOGGER)\n   protected Logger logger = Logger.NULL;\n   /**\n    * maximum duration of an blob Request\n    */\n   @Inject(optional = true)\n   @Named(Constants.PROPERTY_REQUEST_TIMEOUT)\n   protected Long maxTime;\n\n   @Inject\n   GetAllBlobsInListAndRetryOnFailure(@Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor,\n            ListBlobsInContainer getAllBlobMetadata, BlobStore blobstore, BackoffLimitedRetryHandler retryHandler) {\n      this.userExecutor = userExecutor;\n      this.blobstore = blobstore;\n      this.getAllBlobMetadata = getAllBlobMetadata;\n      this.retryHandler = retryHandler;\n   }\n\n   public Iterable<Blob> execute(final String container, ListContainerOptions options) {\n      Iterable<? extends BlobMetadata> list = getAllBlobMetadata.execute(container, options);\n      return transformParallel(list, new Function<BlobMetadata, ListenableFuture<? extends Blob>>() {\n\n         @Override\n         public ListenableFuture<Blob> apply(final BlobMetadata from) {\n            return userExecutor.submit(new Callable<Blob>() {\n               @Override public Blob call() throws Exception {\n                  return blobstore.getBlob(container, from.getName());\n               }\n            });\n         }\n\n      }, userExecutor, maxTime, logger, String.format(\"getting from containerName: %s\", container), retryHandler, 3);\n\n   }\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/strategy/internal/ListContainerAndRecurseThroughFolders.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.strategy.internal;\n\nimport static com.google.common.collect.Iterables.concat;\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.transform;\nimport static com.google.common.collect.Lists.newArrayList;\nimport static com.google.common.collect.Sets.newLinkedHashSet;\n\nimport java.util.List;\nimport java.util.Set;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.blobstore.domain.BlobMetadata;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.domain.StorageType;\nimport org.jclouds.blobstore.options.ListContainerOptions;\nimport org.jclouds.blobstore.strategy.ListBlobsInContainer;\nimport org.jclouds.blobstore.strategy.ListContainerStrategy;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.inject.Inject;\n\n/**\n * Retrieves all blobs in the blobstore by the most efficient means possible.\n */\n@Singleton\npublic class ListContainerAndRecurseThroughFolders implements ListBlobsInContainer {\n\n   protected final ListContainerStrategy lister;\n\n   @Inject\n   ListContainerAndRecurseThroughFolders(ListContainerStrategy lister) {\n      this.lister = lister;\n   }\n\n   @Override\n   public Set<? extends BlobMetadata> execute(final String containerName, final ListContainerOptions options) {\n      final List<Iterable<? extends BlobMetadata>> lists = newArrayList();\n      Iterable<? extends StorageMetadata> pwdList = lister.execute(containerName, options);\n      for (StorageMetadata md : filter(pwdList, new Predicate<StorageMetadata>() {\n         @Override\n         public boolean apply(StorageMetadata input) {\n            return (input.getType() == StorageType.FOLDER || input.getType() == StorageType.RELATIVE_PATH)\n                     && options.isRecursive();\n         }\n      })) {\n         String directory = (options.getDir() != null) ? options.getDir() + \"/\" + md.getName() : md.getName();\n         lists.add(execute(containerName, options.clone().inDirectory(directory)));\n      }\n      lists.add(transform(filter(pwdList, new Predicate<StorageMetadata>() {\n         @Override\n         public boolean apply(StorageMetadata input) {\n            return input.getType() == StorageType.BLOB;\n         }\n      }), new Function<StorageMetadata, BlobMetadata>() {\n         @Override\n         public BlobMetadata apply(StorageMetadata from) {\n            return (BlobMetadata) from;\n         }\n      }));\n      return newLinkedHashSet(concat(lists));\n   }\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/strategy/internal/MarkerFileMkdirStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.strategy.internal;\n\nimport static org.jclouds.io.Payloads.newByteArrayPayload;\n\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.domain.StorageType;\nimport org.jclouds.blobstore.reference.BlobStoreConstants;\nimport org.jclouds.blobstore.strategy.MkdirStrategy;\n\nimport com.google.inject.Inject;\n\n/**\n * Key-value implementations of BlobStore, such as S3, do not have directories. In following the\n * rackspace cloud files project, we use an empty object '#{dirpath}' with content type set to\n * 'application/directory'.\n */\n@Singleton\npublic class MarkerFileMkdirStrategy implements MkdirStrategy {\n\n   @Inject(optional = true)\n   @Named(BlobStoreConstants.PROPERTY_BLOBSTORE_DIRECTORY_SUFFIX)\n   protected String directorySuffix = \"\";\n   private final BlobStore blobStore;\n\n   @Inject\n   MarkerFileMkdirStrategy(BlobStore blobStore) {\n      this.blobStore = blobStore;\n   }\n\n   public void execute(String containerName, String directory) {\n      blobStore.putBlob(\n            containerName,\n            blobStore.blobBuilder(directory + directorySuffix).type(StorageType.FOLDER)\n                  .payload(newByteArrayPayload(new byte[] {})).contentType(\"application/directory\").build());\n   }\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/strategy/internal/MarkersDeleteDirectoryStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.strategy.internal;\n\nimport static com.google.common.base.Throwables.propagate;\nimport static org.jclouds.concurrent.FutureIterables.awaitCompletion;\n\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.TimeoutException;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Constants;\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.internal.BlobRuntimeException;\nimport org.jclouds.blobstore.reference.BlobStoreConstants;\nimport org.jclouds.blobstore.strategy.DeleteDirectoryStrategy;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.collect.Maps;\nimport com.google.common.collect.Sets;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.inject.Inject;\n\n/**\n * Key-value implementations of BlobStore, such as S3, do not have directories. In following the\n * rackspace cloud files project, we use an empty object '#{dirpath}' with content type set to\n * 'application/directory'.\n *\n * <p/>\n * To interoperate with other S3 tools, we accept the following ways to tell if the directory\n * exists:\n * <ul>\n * <li>an object named '#{dirpath}_$folder$' or '#{dirpath}/' denoting a directory marker</li>\n * <li>an object with content type set to 'application/directory' denoting a directory marker</li>\n * <li>if there exists any objects with the prefix \"#{dirpath}/\", then the directory is said to\n * exist</li>\n * <li>if both a file with the name of a directory and a marker for that directory exists, then the\n * *file masks the directory*, and the directory is never returned.</li>\n * </ul>\n *\n * @see MarkerFileMkdirStrategy\n */\n@Singleton\npublic class MarkersDeleteDirectoryStrategy implements DeleteDirectoryStrategy {\n\n   private final BlobStore blobstore;\n   private final ListeningExecutorService userExecutor;\n   @Resource\n   @Named(BlobStoreConstants.BLOBSTORE_LOGGER)\n   protected Logger logger = Logger.NULL;\n   /**\n    * maximum duration of an blob Request\n    */\n   @Inject(optional = true)\n   @Named(Constants.PROPERTY_REQUEST_TIMEOUT)\n   protected Long maxTime;\n\n   @Inject\n   MarkersDeleteDirectoryStrategy(@Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor,\n            BlobStore blobstore) {\n      this.userExecutor = userExecutor;\n      this.blobstore = blobstore;\n   }\n\n   public void execute(final String containerName, String directory) {\n      Set<String> names = Sets.newHashSet();\n      names.add(directory);\n      for (String suffix : BlobStoreConstants.DIRECTORY_SUFFIXES) {\n         names.add(directory + suffix);\n      }\n      Map<String, ListenableFuture<?>> responses = Maps.newHashMap();\n      for (final String name : names) {\n         responses.put(name, userExecutor.submit(new Callable<Void>() {\n            @Override public Void call() throws Exception {\n               blobstore.removeBlob(containerName, name);\n               return null;\n            }\n         }));\n      }\n      String message = String.format(\"deleting directory %s in containerName: %s\", directory,\n               containerName);\n      Map<String, Exception> exceptions;\n      try {\n         exceptions = awaitCompletion(responses, userExecutor, maxTime, logger, message);\n      } catch (TimeoutException te) {\n         throw propagate(te);\n      }\n      if (!exceptions.isEmpty())\n         throw new BlobRuntimeException(String.format(\"error %s: %s\", message, exceptions));\n      assert !blobstore.directoryExists(containerName, directory) : String.format(\n               \"still exists %s: %s\", message, exceptions);\n   }\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/strategy/internal/MarkersGetDirectoryStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.strategy.internal;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.domain.BlobMetadata;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.functions.ResourceMetadataToRelativePathResourceMetadata;\nimport org.jclouds.blobstore.reference.BlobStoreConstants;\nimport org.jclouds.blobstore.strategy.GetDirectoryStrategy;\n\nimport com.google.inject.Inject;\n\n/**\n * Key-value implementations of BlobStore, such as S3, do not have directories. In following the\n * rackspace cloud files project, we use an empty object '#{dirpath}' with content type set to\n * 'application/directory'.\n * \n * <p/>\n * To interoperate with other S3 tools, we accept the following ways to tell if the directory\n * exists:\n * <ul>\n * <li>an object named '#{dirpath}_$folder$' or '#{dirpath}/' denoting a directory marker</li>\n * <li>an object with content type set to 'application/directory' denoting a directory marker</li>\n * <li>if there exists any objects with the prefix \"#{dirpath}/\", then the directory is said to\n * exist</li>\n * <li>if both a file with the name of a directory and a marker for that directory exists, then the\n * *file masks the directory*, and the directory is never returned.</li>\n * </ul>\n * \n * @see MarkerFileMkdirStrategy\n */\n@Singleton\npublic class MarkersGetDirectoryStrategy implements GetDirectoryStrategy {\n\n   protected final ResourceMetadataToRelativePathResourceMetadata resource2Directory;\n   private final BlobStore connection;\n\n   @Inject\n   public MarkersGetDirectoryStrategy(BlobStore connection,\n            ResourceMetadataToRelativePathResourceMetadata resource2Directory) {\n      this.connection = connection;\n      this.resource2Directory = resource2Directory;\n   }\n\n   public StorageMetadata execute(String containerName, String directory) {\n      BlobMetadata md = connection.blobMetadata(containerName, directory);\n      if (md != null && md.getContentMetadata().getContentType().equals(\"application/directory\"))\n         return resource2Directory.apply(md);\n      for (String suffix : BlobStoreConstants.DIRECTORY_SUFFIXES) {\n         md = connection.blobMetadata(containerName, directory + suffix);\n         if (md != null)\n            return resource2Directory.apply(md);\n      }\n      return null;\n   }\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/strategy/internal/MultipartUploadSlicingAlgorithm.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.blobstore.strategy.internal;\n\nimport static com.google.common.base.Preconditions.checkArgument;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\n\nimport org.jclouds.blobstore.reference.BlobStoreConstants;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.inject.Inject;\n\npublic final class MultipartUploadSlicingAlgorithm {\n   private final long minimumPartSize;\n   private final long maximumPartSize;\n   private final int maximumNumberOfParts;\n\n   @Resource\n   @Named(BlobStoreConstants.BLOBSTORE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   @VisibleForTesting\n   public static final long DEFAULT_PART_SIZE = 33554432; // 32MB\n\n   @VisibleForTesting\n   static final int DEFAULT_MAGNITUDE_BASE = 100;\n\n   @Inject(optional = true)\n   @Named(\"jclouds.mpu.parts.size\")\n   @VisibleForTesting\n   long defaultPartSize = DEFAULT_PART_SIZE;\n\n   @Inject(optional = true)\n   @Named(\"jclouds.mpu.parts.magnitude\")\n   @VisibleForTesting\n   int magnitudeBase = DEFAULT_MAGNITUDE_BASE;\n\n   // calculated only once, but not from the constructor\n   private volatile int parts; // required number of parts with chunkSize\n   private volatile long chunkSize;\n   private volatile long remaining; // number of bytes remained for the last part\n\n   // sequentially updated values\n   private volatile int part;\n   private volatile long chunkOffset;\n   private volatile long copied;\n\n   public MultipartUploadSlicingAlgorithm(long minimumPartSize, long maximumPartSize, int maximumNumberOfParts) {\n      checkArgument(minimumPartSize > 0);\n      this.minimumPartSize = minimumPartSize;\n      checkArgument(maximumPartSize > 0);\n      this.maximumPartSize = maximumPartSize;\n      checkArgument(maximumNumberOfParts > 0);\n      this.maximumNumberOfParts = maximumNumberOfParts;\n   }\n\n   // TODO: This algorithm is needlessly complicated.\n   public long calculateChunkSize(long length) {\n      long unitPartSize = defaultPartSize; // first try with default part size\n      int parts = (int)(length / unitPartSize);\n      long partSize = unitPartSize;\n      int magnitude = parts / magnitudeBase;\n      if (magnitude > 0) {\n         partSize = magnitude * unitPartSize;\n         if (partSize > maximumPartSize) {\n            partSize = maximumPartSize;\n            unitPartSize = maximumPartSize;\n         }\n         parts = (int)(length / partSize);\n         if (parts * partSize < length) {\n            partSize = (magnitude + 1) * unitPartSize;\n            if (partSize > maximumPartSize) {\n               partSize = maximumPartSize;\n               unitPartSize = maximumPartSize;\n            }\n            parts = (int)(length / partSize);\n         }\n      }\n      if (partSize < minimumPartSize) {\n         partSize = minimumPartSize;\n         unitPartSize = minimumPartSize;\n         parts = (int)(length / unitPartSize);\n      }\n      if (partSize > maximumPartSize) {\n         partSize = maximumPartSize;\n         unitPartSize = maximumPartSize;\n         parts = (int)(length / unitPartSize);\n      }\n      if (parts > maximumNumberOfParts) {\n         partSize = length / maximumNumberOfParts;\n         unitPartSize = partSize;\n         parts = maximumNumberOfParts;\n      }\n      long remainder = length % unitPartSize;\n      if (remainder == 0 && parts > 0) {\n         parts -= 1;\n      }\n      if (remainder > 0 && parts == maximumNumberOfParts) {\n          parts -= 1;\n          partSize = length / parts;\n      }\n      this.chunkSize = partSize;\n      this.parts = parts;\n      this.remaining = length - partSize * parts;\n      logger.debug(\" %d bytes partitioned in %d parts of part size: %d, remaining: %d%s\", length, parts, chunkSize,\n            remaining, remaining > maximumPartSize ? \" overflow!\" : \"\");\n      return this.chunkSize;\n   }\n\n   public long getCopied() {\n      return copied;\n   }\n\n   public void setCopied(long copied) {\n      this.copied = copied;\n   }\n\n   public int getParts() {\n      return parts;\n   }\n\n   protected int getNextPart() {\n      return ++part;\n   }\n\n   public void addCopied(long copied) {\n      this.copied += copied;\n   }\n\n   protected long getNextChunkOffset() {\n      long next = chunkOffset;\n      chunkOffset += getChunkSize();\n      return next;\n   }\n\n   @VisibleForTesting\n   protected long getChunkSize() {\n      return chunkSize;\n   }\n\n   public long getRemaining() {\n      return remaining;\n   }\n\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/strategy/internal/PutBlobsStrategyImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.strategy.internal;\n\nimport static com.google.common.base.Throwables.propagate;\nimport static org.jclouds.concurrent.FutureIterables.awaitCompletion;\n\nimport java.util.Map;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.TimeoutException;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Constants;\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.internal.BlobRuntimeException;\nimport org.jclouds.blobstore.reference.BlobStoreConstants;\nimport org.jclouds.blobstore.strategy.PutBlobsStrategy;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.collect.Maps;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.inject.Inject;\n\n@Singleton\npublic class PutBlobsStrategyImpl implements PutBlobsStrategy {\n\n   private final BlobStore blobstore;\n   private final ListeningExecutorService userExecutor;\n   @Resource\n   @Named(BlobStoreConstants.BLOBSTORE_LOGGER)\n   protected Logger logger = Logger.NULL;\n   /**\n    * maximum duration of an blob Request\n    */\n   @Inject(optional = true)\n   @Named(Constants.PROPERTY_REQUEST_TIMEOUT)\n   protected Long maxTime;\n\n   @Inject\n   PutBlobsStrategyImpl(@Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor,\n            BlobStore blobstore) {\n      this.userExecutor = userExecutor;\n      this.blobstore = blobstore;\n   }\n\n   @Override\n   public void execute(final String containerName, Iterable<? extends Blob> blobs) {\n      Map<Blob, ListenableFuture<?>> responses = Maps.newLinkedHashMap();\n      for (final Blob blob : blobs) {\n         responses.put(blob, userExecutor.submit(new Callable<Object>() {\n            @Override public Object call() throws Exception {\n               return blobstore.putBlob(containerName, blob);\n            }\n         }));\n      }\n      Map<Blob, Exception> exceptions;\n      try {\n         exceptions = awaitCompletion(responses, userExecutor, maxTime, logger,\n                  String.format(\"putting into containerName: %s\", containerName));\n      } catch (TimeoutException te) {\n         throw propagate(te);\n      }\n      if (!exceptions.isEmpty())\n         throw new BlobRuntimeException(String.format(\"error putting into container %s: %s\",\n                  containerName, exceptions));\n   }\n\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/util/BlobStoreUtils.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.util;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.List;\nimport java.util.Map;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport org.jclouds.blobstore.domain.MutableBlobMetadata;\nimport org.jclouds.blobstore.domain.internal.MutableBlobMetadataImpl;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpRequestFilter;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\n\nimport com.google.common.collect.Maps;\n\npublic class BlobStoreUtils {\n   public static <T> HttpRequest cleanRequest(HttpRequest returnVal) {\n      checkNotNull(returnVal, \"http request\");\n      for (HttpRequestFilter filter : returnVal.getFilters())\n         returnVal = filter.filter(returnVal);\n      return HttpRequest.builder().method(returnVal.getMethod()).endpoint(returnVal.getEndpoint())\n               .headers(returnVal.getHeaders()).payload(returnVal.getPayload()).build();\n   }\n\n   public static String parseDirectoryFromPath(String path) {\n      return checkNotNull(path, \"path\").substring(0, path.lastIndexOf('/'));\n   }\n\n   private static Pattern keyFromContainer = Pattern.compile(\"/?[^/]+/(.*)\");\n\n   public static String getNameFor(GeneratedHttpRequest request) {\n      checkNotNull(request, \"request\");\n      List<Object> args = request.getInvocation().getArgs();\n      // assume first params are container and key\n      if (args.size() >= 2 && args.get(0) instanceof String\n            && args.get(1) instanceof String) {\n         return args.get(1).toString();\n      } else if (args.size() >= 1 && args.get(0) instanceof String) {\n         Matcher matcher = keyFromContainer.matcher(args.get(0).toString());\n         if (matcher.find())\n            return matcher.group(1);\n      }\n      String objectKey = request.getEndpoint().getPath();\n      if (objectKey.startsWith(\"/\")) {\n         // Trim initial slash from object key name.\n         objectKey = objectKey.substring(1);\n      }\n      return objectKey;\n   }\n   \n   public static MutableBlobMetadata copy(MutableBlobMetadata in) {\n      MutableBlobMetadata metadata = new MutableBlobMetadataImpl(in);\n      convertUserMetadataKeysToLowercase(metadata);\n      return metadata;\n   }\n\n   public static MutableBlobMetadata copy(MutableBlobMetadata in, String newKey) {\n      MutableBlobMetadata newMd = BlobStoreUtils.copy(in);\n      newMd.setName(newKey);\n      return newMd;\n   }\n\n   private static void convertUserMetadataKeysToLowercase(MutableBlobMetadata metadata) {\n      Map<String, String> lowerCaseUserMetadata = Maps.newHashMap();\n      for (Map.Entry<String, String> entry : metadata.getUserMetadata().entrySet()) {\n         lowerCaseUserMetadata.put(entry.getKey().toLowerCase(), entry.getValue());\n      }\n      metadata.setUserMetadata(lowerCaseUserMetadata);\n   }\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/util/BlobUtils.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.util;\n\nimport org.jclouds.blobstore.domain.BlobBuilder;\nimport org.jclouds.blobstore.options.ListContainerOptions;\nimport org.jclouds.blobstore.util.internal.BlobUtilsImpl;\n\nimport com.google.inject.ImplementedBy;\n\n@ImplementedBy(BlobUtilsImpl.class)\npublic interface BlobUtils {\n   BlobBuilder blobBuilder();\n\n   boolean directoryExists(String containerName, String directory);\n\n   void createDirectory(String containerName, String directory);\n\n   long countBlobs(String container, ListContainerOptions options);\n\n   void clearContainer(String container, ListContainerOptions options);\n\n   void deleteDirectory(String container, String directory);\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/util/ForwardingBlobStore.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.blobstore.util;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.io.File;\nimport java.io.InputStream;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.concurrent.ExecutorService;\n\nimport com.google.common.collect.ForwardingObject;\n\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.BlobStoreContext;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.BlobAccess;\nimport org.jclouds.blobstore.domain.BlobBuilder;\nimport org.jclouds.blobstore.domain.BlobMetadata;\nimport org.jclouds.blobstore.domain.ContainerAccess;\nimport org.jclouds.blobstore.domain.MultipartPart;\nimport org.jclouds.blobstore.domain.MultipartUpload;\nimport org.jclouds.blobstore.domain.PageSet;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.options.CopyOptions;\nimport org.jclouds.blobstore.options.CreateContainerOptions;\nimport org.jclouds.blobstore.options.GetOptions;\nimport org.jclouds.blobstore.options.ListContainerOptions;\nimport org.jclouds.blobstore.options.PutOptions;\nimport org.jclouds.domain.Location;\nimport org.jclouds.io.Payload;\n\npublic abstract class ForwardingBlobStore extends ForwardingObject\n      implements BlobStore {\n   private final BlobStore blobStore;\n\n   public ForwardingBlobStore(BlobStore blobStore) {\n      this.blobStore = checkNotNull(blobStore);\n   }\n\n   protected BlobStore delegate() {\n      return blobStore;\n   }\n\n   @Override\n   public BlobStoreContext getContext() {\n      return delegate().getContext();\n   }\n\n   @Override\n   public BlobBuilder blobBuilder(String name) {\n      return delegate().blobBuilder(name);\n   }\n\n   @Override\n   public Set<? extends Location> listAssignableLocations() {\n      return delegate().listAssignableLocations();\n   }\n\n   @Override\n   public PageSet<? extends StorageMetadata> list() {\n      return delegate().list();\n   }\n\n   @Override\n   public boolean containerExists(String container) {\n      return delegate().containerExists(container);\n   }\n\n   @Override\n   public boolean createContainerInLocation(Location location,\n         String container) {\n      return delegate().createContainerInLocation(location, container);\n   }\n\n   @Override\n   public boolean createContainerInLocation(Location location,\n         String container, CreateContainerOptions createContainerOptions) {\n      return delegate().createContainerInLocation(location, container,\n            createContainerOptions);\n   }\n\n   @Override\n   public ContainerAccess getContainerAccess(String container) {\n      return delegate().getContainerAccess(container);\n   }\n\n   @Override\n   public void setContainerAccess(String container, ContainerAccess\n         containerAccess) {\n      delegate().setContainerAccess(container, containerAccess);\n   }\n\n   @Override\n   public PageSet<? extends StorageMetadata> list(String container) {\n      return delegate().list(container);\n   }\n\n   @Override\n   public PageSet<? extends StorageMetadata> list(String container,\n         ListContainerOptions options) {\n      return delegate().list(container, options);\n   }\n\n   @Override\n   public void clearContainer(String container) {\n      delegate().clearContainer(container);\n   }\n\n   @Override\n   public void clearContainer(String container, ListContainerOptions options) {\n      delegate().clearContainer(container, options);\n   }\n\n   @Override\n   public void deleteContainer(String container) {\n      delegate().deleteContainer(container);\n   }\n\n   @Override\n   public boolean deleteContainerIfEmpty(String container) {\n      return delegate().deleteContainerIfEmpty(container);\n   }\n\n   @Override\n   public boolean directoryExists(String container, String directory) {\n      return delegate().directoryExists(container, directory);\n   }\n\n   @Override\n   public void createDirectory(String container, String directory) {\n      delegate().createDirectory(container, directory);\n   }\n\n   @Override\n   public void deleteDirectory(String container, String directory) {\n      delegate().deleteDirectory(container, directory);\n   }\n\n   @Override\n   public boolean blobExists(String container, String name) {\n      return delegate().blobExists(container, name);\n   }\n\n   @Override\n   public String putBlob(String containerName, Blob blob) {\n      return delegate().putBlob(containerName, blob);\n   }\n\n   @Override\n   public String putBlob(String containerName, Blob blob,\n         PutOptions putOptions) {\n      return delegate().putBlob(containerName, blob, putOptions);\n   }\n\n   @Override\n   public String copyBlob(String fromContainer, String fromName, String toContainer, String toName,\n         CopyOptions options) {\n      return delegate().copyBlob(fromContainer, fromName, toContainer, toName, options);\n   }\n\n   @Override\n   public BlobMetadata blobMetadata(String container, String name) {\n      return delegate().blobMetadata(container, name);\n   }\n\n   @Override\n   public Blob getBlob(String containerName, String blobName) {\n      return delegate().getBlob(containerName, blobName);\n   }\n\n   @Override\n   public Blob getBlob(String containerName, String blobName,\n         GetOptions getOptions) {\n      return delegate().getBlob(containerName, blobName, getOptions);\n   }\n\n   @Override\n   public void removeBlob(String container, String name) {\n      delegate().removeBlob(container, name);\n   }\n\n   @Override\n   public void removeBlobs(String container, Iterable<String> iterable) {\n      delegate().removeBlobs(container, iterable);\n   }\n\n   @Override\n   public BlobAccess getBlobAccess(String container, String name) {\n      return delegate().getBlobAccess(container, name);\n   }\n\n   @Override\n   public void setBlobAccess(String container, String name,\n         BlobAccess access) {\n      delegate().setBlobAccess(container, name, access);\n   }\n\n   @Override\n   public long countBlobs(String container) {\n      return delegate().countBlobs(container);\n   }\n\n   @Override\n   public long countBlobs(String container, ListContainerOptions options) {\n      return delegate().countBlobs(container, options);\n   }\n\n   @Override\n   public MultipartUpload initiateMultipartUpload(String container, BlobMetadata blobMetadata, PutOptions options) {\n      return delegate().initiateMultipartUpload(container, blobMetadata, options);\n   }\n\n   @Override\n   public void abortMultipartUpload(MultipartUpload mpu) {\n      delegate().abortMultipartUpload(mpu);\n   }\n\n   @Override\n   public String completeMultipartUpload(MultipartUpload mpu, List<MultipartPart> parts) {\n      return delegate().completeMultipartUpload(mpu, parts);\n   }\n\n   @Override\n   public MultipartPart uploadMultipartPart(MultipartUpload mpu, int partNumber, Payload payload) {\n      return delegate().uploadMultipartPart(mpu, partNumber, payload);\n   }\n\n   @Override\n   public List<MultipartPart> listMultipartUpload(MultipartUpload mpu) {\n      return delegate().listMultipartUpload(mpu);\n   }\n\n   @Override\n   public List<MultipartUpload> listMultipartUploads(String container) {\n      return delegate().listMultipartUploads(container);\n   }\n\n   @Override\n   public long getMinimumMultipartPartSize() {\n      return delegate().getMinimumMultipartPartSize();\n   }\n\n   @Override\n   public long getMaximumMultipartPartSize() {\n      return delegate().getMaximumMultipartPartSize();\n   }\n\n   @Override\n   public int getMaximumNumberOfParts() {\n      return delegate().getMaximumNumberOfParts();\n   }\n\n   @Override\n   public void downloadBlob(String container, String name, File destination) {\n      delegate().downloadBlob(container, name, destination);\n   }\n\n   @Override\n   public void downloadBlob(String container, String name, File destination, ExecutorService executor) {\n      delegate().downloadBlob(container, name, destination, executor);\n   }\n\n   @Override\n   public InputStream streamBlob(String container, String name) {\n      return delegate().streamBlob(container, name);\n   }\n\n   @Override\n   public InputStream streamBlob(String container, String name, ExecutorService executor) {\n      return delegate().streamBlob(container, name, executor);\n   }\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/util/ReadOnlyBlobStore.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.blobstore.util;\n\nimport java.io.File;\nimport java.io.InputStream;\nimport java.util.List;\nimport java.util.concurrent.ExecutorService;\n\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.BlobStoreContext;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.BlobAccess;\nimport org.jclouds.blobstore.domain.BlobBuilder;\nimport org.jclouds.blobstore.domain.BlobMetadata;\nimport org.jclouds.blobstore.domain.ContainerAccess;\nimport org.jclouds.blobstore.domain.MultipartPart;\nimport org.jclouds.blobstore.domain.MultipartUpload;\nimport org.jclouds.blobstore.options.CopyOptions;\nimport org.jclouds.blobstore.options.CreateContainerOptions;\nimport org.jclouds.blobstore.options.ListContainerOptions;\nimport org.jclouds.blobstore.options.PutOptions;\nimport org.jclouds.domain.Location;\nimport org.jclouds.io.Payload;\n\npublic final class ReadOnlyBlobStore extends ForwardingBlobStore {\n   public static BlobStore newReadOnlyBlobStore(BlobStore blobStore) {\n      return new ReadOnlyBlobStore(blobStore);\n   }\n\n   private ReadOnlyBlobStore(BlobStore blobStore) {\n      super(blobStore);\n   }\n\n   @Override\n   public BlobStoreContext getContext() {\n      return delegate().getContext();\n   }\n\n   @Override\n   public BlobBuilder blobBuilder(String name) {\n      return delegate().blobBuilder(name);\n   }\n\n   @Override\n   public boolean createContainerInLocation(Location location,\n         String container) {\n      throw new UnsupportedOperationException(\"Read-only BlobStore\");\n   }\n\n   @Override\n   public boolean createContainerInLocation(Location location,\n         String container, CreateContainerOptions createContainerOptions) {\n      throw new UnsupportedOperationException(\"Read-only BlobStore\");\n   }\n\n   @Override\n   public void setContainerAccess(String container, ContainerAccess\n         containerAccess) {\n      throw new UnsupportedOperationException(\"Read-only BlobStore\");\n   }\n\n   @Override\n   public void clearContainer(String container) {\n      throw new UnsupportedOperationException(\"Read-only BlobStore\");\n   }\n\n   @Override\n   public void clearContainer(String container, ListContainerOptions options) {\n      throw new UnsupportedOperationException(\"Read-only BlobStore\");\n   }\n\n   @Override\n   public void deleteContainer(String container) {\n      throw new UnsupportedOperationException(\"Read-only BlobStore\");\n   }\n\n   @Override\n   public boolean deleteContainerIfEmpty(String container) {\n      throw new UnsupportedOperationException(\"Read-only BlobStore\");\n   }\n\n   @Override\n   public void createDirectory(String container, String directory) {\n      throw new UnsupportedOperationException(\"Read-only BlobStore\");\n   }\n\n   @Override\n   public void deleteDirectory(String container, String directory) {\n      throw new UnsupportedOperationException(\"Read-only BlobStore\");\n   }\n\n   @Override\n   public String putBlob(String containerName, Blob blob) {\n      throw new UnsupportedOperationException(\"Read-only BlobStore\");\n   }\n\n   @Override\n   public String putBlob(String containerName, Blob blob,\n         PutOptions putOptions) {\n      throw new UnsupportedOperationException(\"Read-only BlobStore\");\n   }\n\n   @Override\n   public String copyBlob(String fromContainer, String fromName, String toContainer, String toName,\n         CopyOptions options) {\n      throw new UnsupportedOperationException(\"Read-only BlobStore\");\n   }\n\n   @Override\n   public void removeBlob(String container, String name) {\n      throw new UnsupportedOperationException(\"Read-only BlobStore\");\n   }\n\n   @Override\n   public void removeBlobs(String container, Iterable<String> iterable) {\n      throw new UnsupportedOperationException(\"Read-only BlobStore\");\n   }\n\n   @Override\n   public void setBlobAccess(String container, String name,\n         BlobAccess access) {\n      throw new UnsupportedOperationException(\"Read-only BlobStore\");\n   }\n\n   @Override\n   public MultipartUpload initiateMultipartUpload(String container, BlobMetadata blobMetadata, PutOptions options) {\n      throw new UnsupportedOperationException(\"Read-only BlobStore\");\n   }\n\n   @Override\n   public void abortMultipartUpload(MultipartUpload mpu) {\n      throw new UnsupportedOperationException(\"Read-only BlobStore\");\n   }\n\n   @Override\n   public String completeMultipartUpload(MultipartUpload mpu, List<MultipartPart> parts) {\n      throw new UnsupportedOperationException(\"Read-only BlobStore\");\n   }\n\n   @Override\n   public MultipartPart uploadMultipartPart(MultipartUpload mpu, int partNumber, Payload payload) {\n      throw new UnsupportedOperationException(\"Read-only BlobStore\");\n   }\n\n   @Override\n   public List<MultipartPart> listMultipartUpload(MultipartUpload mpu) {\n      throw new UnsupportedOperationException(\"Read-only BlobStore\");\n   }\n\n   // TODO: should ReadOnlyBlobStore allow listing parts and uploads?\n   @Override\n   public List<MultipartUpload> listMultipartUploads(String container) {\n      throw new UnsupportedOperationException(\"Read-only BlobStore\");\n   }\n\n   @Override\n   public void downloadBlob(String container, String name, File destination) {\n      throw new UnsupportedOperationException();\n   }\n\n   @Override\n   public void downloadBlob(String container, String name, File destination, ExecutorService executor) {\n      throw new UnsupportedOperationException();\n   }\n\n   @Override\n   public InputStream streamBlob(String container, String name) {\n      throw new UnsupportedOperationException();\n   }\n\n   @Override\n   public InputStream streamBlob(String container, String name, ExecutorService executor) {\n      throw new UnsupportedOperationException();\n   }\n}\n"
  },
  {
    "path": "blobstore/src/main/java/org/jclouds/blobstore/util/internal/BlobUtilsImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.util.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Provider;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.blobstore.domain.BlobBuilder;\nimport org.jclouds.blobstore.options.ListContainerOptions;\nimport org.jclouds.blobstore.strategy.ClearListStrategy;\nimport org.jclouds.blobstore.strategy.CountListStrategy;\nimport org.jclouds.blobstore.strategy.DeleteDirectoryStrategy;\nimport org.jclouds.blobstore.strategy.GetDirectoryStrategy;\nimport org.jclouds.blobstore.strategy.MkdirStrategy;\nimport org.jclouds.blobstore.util.BlobUtils;\n\n/**\n * Encryption, Hashing, and IO Utilities needed to sign and verify blobstore requests and responses.\n */\n@Singleton\npublic class BlobUtilsImpl implements BlobUtils {\n\n   protected final Provider<BlobBuilder> blobBuilders;\n   protected final ClearListStrategy clearContainerStrategy;\n   protected final GetDirectoryStrategy getDirectoryStrategy;\n   protected final MkdirStrategy mkdirStrategy;\n   protected final DeleteDirectoryStrategy rmDirStrategy;\n   protected final CountListStrategy countBlobsStrategy;\n\n   @Inject\n   protected BlobUtilsImpl(Provider<BlobBuilder> blobBuilders, ClearListStrategy clearContainerStrategy,\n         GetDirectoryStrategy getDirectoryStrategy, MkdirStrategy mkdirStrategy, CountListStrategy countBlobsStrategy,\n         DeleteDirectoryStrategy rmDirStrategy) {\n      this.blobBuilders = checkNotNull(blobBuilders, \"blobBuilders\");\n      this.clearContainerStrategy = checkNotNull(clearContainerStrategy, \"clearContainerStrategy\");\n      this.getDirectoryStrategy = checkNotNull(getDirectoryStrategy, \"getDirectoryStrategy\");\n      this.mkdirStrategy = checkNotNull(mkdirStrategy, \"mkdirStrategy\");\n      this.rmDirStrategy = checkNotNull(rmDirStrategy, \"rmDirStrategy\");\n      this.countBlobsStrategy = checkNotNull(countBlobsStrategy, \"countBlobsStrategy\");\n   }\n   \n   @Override\n   public BlobBuilder blobBuilder() {\n      return blobBuilders.get();\n   }\n\n   public boolean directoryExists(String containerName, String directory) {\n      return getDirectoryStrategy.execute(containerName, directory) != null;\n   }\n\n   public void createDirectory(String containerName, String directory) {\n      mkdirStrategy.execute(containerName, directory);\n   }\n\n   public long countBlobs(String container, ListContainerOptions options) {\n      return countBlobsStrategy.execute(container, options);\n   }\n\n   public void clearContainer(String container, ListContainerOptions options) {\n      clearContainerStrategy.execute(container, options);\n   }\n\n   public void deleteDirectory(String container, String directory) {\n      rmDirStrategy.execute(container, directory);\n   }\n\n}\n"
  },
  {
    "path": "blobstore/src/test/java/org/jclouds/blobstore/BlobStoreContextFactoryTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.net.URI;\nimport java.util.Iterator;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Splitter;\n\n/**\n * Tests parsing of a request\n */\n@Test(testName = \"blobstore.BlobStoreContextFactoryTest\")\npublic class BlobStoreContextFactoryTest {\n\n   public void test() throws IOException {\n      URI blobStore = URI.create(\"provider://identity:key@container/path\");\n      assertEquals(blobStore.getScheme(), \"provider\");\n      Iterator<String> identityKey = Splitter.on(\":\").split(\n               checkNotNull(blobStore.getUserInfo(), \"userInfo\")).iterator();\n      assertEquals(identityKey.next(), \"identity\");\n      assertEquals(identityKey.next(), \"key\");\n      assertEquals(blobStore.getHost(), \"container\");\n      assertEquals(blobStore.getPath(), \"/path\");\n   }\n\n   public void testNoPassword() throws IOException {\n      URI blobStore = URI.create(\"provider://identity@container/path\");\n      assertEquals(blobStore.getScheme(), \"provider\");\n      Iterator<String> identityKey = Splitter.on(\":\").split(\n               checkNotNull(blobStore.getUserInfo(), \"userInfo\")).iterator();\n      assertEquals(identityKey.next(), \"identity\");\n      assertEquals(blobStore.getHost(), \"container\");\n      assertEquals(blobStore.getPath(), \"/path\");\n   }\n\n}\n"
  },
  {
    "path": "blobstore/src/test/java/org/jclouds/blobstore/BlobStoresTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Set;\n\nimport org.easymock.EasyMock;\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.blobstore.domain.PageSet;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.domain.internal.PageSetImpl;\nimport org.jclouds.blobstore.options.ListAllOptions;\nimport org.jclouds.blobstore.options.ListContainerOptions;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Sets;\n\n@Test(singleThreaded = true, testName = \"BlobStoresTest\")\npublic class BlobStoresTest {\n\n   private final String containerName = \"mycontainer\";\n\n   @Test(expectedExceptions = { ContainerNotFoundException.class })\n   public void testListAllForUnknownContainerFromTransientBlobStoreEagerly() throws Exception {\n      ListContainerOptions containerOptions = ListContainerOptions.NONE;\n      ListAllOptions listAllOptions = ListAllOptions.Builder.eager(true);\n      BlobStoreContext context = blobStoreContext();\n      try {\n         BlobStore blobStore = context.getBlobStore();\n         BlobStores.listAll(blobStore, \"wrongcontainer\", containerOptions, listAllOptions);\n      } finally {\n         context.close();\n      }\n   }\n\n   /**\n    * Default listAll is not eager, so test that exception is thrown when first attempt to iterate.\n    */\n   @Test(expectedExceptions = { ContainerNotFoundException.class })\n   public void testListAllForUnknownContainerFromTransientBlobStore() throws Exception {\n      ListContainerOptions options = ListContainerOptions.NONE;\n      BlobStoreContext context = blobStoreContext();\n      try {\n         BlobStore blobStore = context.getBlobStore();\n         Iterable<StorageMetadata> iterable = BlobStores.listAll(blobStore, \"wrongcontainer\", options);\n         iterable.iterator().hasNext();\n      } finally {\n         context.close();\n      }\n   }\n\n   protected BlobStoreContext blobStoreContext() {\n      return ContextBuilder.newBuilder(\"transient\").build(BlobStoreContext.class);\n   }\n\n   @Test\n   public void testListAllFromTransientBlobStore() throws Exception {\n      runListAllFromTransientBlobStore(false);\n   }\n\n   @Test\n   public void testListAllFromTransientBlobStoreEagerly() throws Exception {\n      runListAllFromTransientBlobStore(true);\n   }\n\n   private void runListAllFromTransientBlobStore(boolean eager) throws Exception {\n      final int numTimesToIterate = 2;\n      final int NUM_BLOBS = 31;\n      ListContainerOptions containerOptions = ListContainerOptions.Builder.maxResults(10);\n      BlobStoreContext context = blobStoreContext();\n      BlobStore blobStore = null;\n      try {\n         blobStore = context.getBlobStore();\n         blobStore.createContainerInLocation(null, containerName);\n         Set<String> expectedNames = Sets.newHashSet();\n         for (int i = 0; i < NUM_BLOBS; i++) {\n            String blobName = \"myname\" + i;\n            blobStore.putBlob(containerName, blobStore.blobBuilder(blobName).payload(\"payload\" + i).build());\n            expectedNames.add(blobName);\n         }\n\n         ListAllOptions listAllOptions = ListAllOptions.Builder.eager(eager);\n         Iterable<StorageMetadata> iterable = BlobStores.listAll(blobStore, containerName, containerOptions,\n                  listAllOptions);\n\n         for (int i = 0; i < numTimesToIterate; i++) {\n            Iterable<String> iterableNames = Iterables.transform(iterable, new Function<StorageMetadata, String>() {\n               @Override\n               public String apply(StorageMetadata input) {\n                  return input.getName();\n               }\n            });\n\n            // Note that blob.getMetadata being put does not equal blob metadata being retrieved\n            // because uri is null in one and populated in the other.\n            // Therefore we just compare names to ensure the iterator worked.\n            assertEquals(ImmutableSet.copyOf(iterableNames), expectedNames);\n         }\n      } finally {\n         if (blobStore != null)\n            blobStore.deleteContainer(containerName);\n         context.close();\n      }\n   }\n\n   @Test\n   public void testListAllWhenOnePage() throws Exception {\n      BlobStore blobStore = createMock(BlobStore.class);\n      ListContainerOptions options = ListContainerOptions.NONE;\n      StorageMetadata v1 = createMock(StorageMetadata.class);\n      PageSet<StorageMetadata> pageSet = new PageSetImpl<StorageMetadata>(ImmutableList.of(v1), null);\n\n      EasyMock.<PageSet<? extends StorageMetadata>> expect(blobStore.list(containerName, options)).andReturn(pageSet)\n               .once();\n      EasyMock.replay(blobStore);\n\n      Iterable<StorageMetadata> iterable = BlobStores.listAll(blobStore, containerName, options);\n      assertEquals(ImmutableList.copyOf(iterable), ImmutableList.of(v1));\n   }\n\n   @Test\n   public void testListAllWhenTwoPages() throws Exception {\n      BlobStore blobStore = createMock(BlobStore.class);\n      ListContainerOptions options = ListContainerOptions.NONE;\n      ListContainerOptions options2 = ListContainerOptions.Builder.afterMarker(\"marker1\");\n      StorageMetadata v1 = createMock(StorageMetadata.class);\n      StorageMetadata v2 = createMock(StorageMetadata.class);\n      PageSet<StorageMetadata> pageSet = new PageSetImpl<StorageMetadata>(ImmutableList.of(v1), \"marker1\");\n      PageSet<StorageMetadata> pageSet2 = new PageSetImpl<StorageMetadata>(ImmutableList.of(v2), null);\n\n      EasyMock.<PageSet<? extends StorageMetadata>> expect(blobStore.list(containerName, options)).andReturn(pageSet)\n               .once();\n      EasyMock.<PageSet<? extends StorageMetadata>> expect(blobStore.list(containerName, options2)).andReturn(pageSet2)\n               .once();\n      EasyMock.replay(blobStore);\n\n      Iterable<StorageMetadata> iterable = BlobStores.listAll(blobStore, containerName, options);\n      assertEquals(ImmutableList.copyOf(iterable), ImmutableList.of(v1, v2));\n   }\n}\n"
  },
  {
    "path": "blobstore/src/test/java/org/jclouds/blobstore/TransientApiMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore;\n\nimport org.jclouds.blobstore.internal.BaseBlobStoreApiMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"TransientApiMetadataTest\")\npublic class TransientApiMetadataTest extends BaseBlobStoreApiMetadataTest {\n\n   public TransientApiMetadataTest() {\n      super(new TransientApiMetadata());\n   }\n}\n"
  },
  {
    "path": "blobstore/src/test/java/org/jclouds/blobstore/TransientBlobRequestSignerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\n\nimport jakarta.inject.Provider;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.blobstore.config.LocalBlobStore;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.BlobBuilder;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.internal.BaseRestAnnotationProcessingTest;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.hash.HashCode;\nimport com.google.common.hash.Hashing;\nimport com.google.common.io.ByteSource;\n\n/**\n * Tests behavior of {@code LocalBlobRequestSigner}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"TransientBlobRequestSignerTest\")\npublic class TransientBlobRequestSignerTest extends BaseRestAnnotationProcessingTest<LocalBlobStore> {\n\n   private BlobRequestSigner signer;\n   private Provider<BlobBuilder> blobFactory;\n   private final String endpoint = new TransientApiMetadata().getDefaultEndpoint().get();\n   private final String containerName = \"container\";\n   private final String blobName = \"blob\";\n   private final String fullUrl = String.format(\"%s/%s/%s\", endpoint, containerName, blobName);\n\n   public void testSignGetBlob() throws ArrayIndexOutOfBoundsException, SecurityException, IllegalArgumentException,\n            NoSuchMethodException, IOException {\n      HttpRequest request = signer.signGetBlob(containerName, blobName);\n\n      assertRequestLineEquals(request, \"GET \" + fullUrl + \" HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Authorization: Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertEquals(request.getFilters().size(), 0);\n   }\n\n   public void testSignPutBlob() throws ArrayIndexOutOfBoundsException, SecurityException, IllegalArgumentException,\n            NoSuchMethodException, IOException {\n      HashCode hashCode = HashCode.fromBytes(new byte[16]);\n      Blob blob = blobFactory.get().name(blobName).forSigning().contentLength(2L).contentMD5(hashCode)\n               .contentType(\"text/plain\").build();\n\n      assertEquals(blob.getPayload().getContentMetadata().getContentMD5AsHashCode(), hashCode);\n\n      HttpRequest request = signer.signPutBlob(containerName, blob);\n\n      assertRequestLineEquals(request, \"PUT \" + fullUrl + \" HTTP/1.1\");\n      assertNonPayloadHeadersEqual(\n               request,\n               \"Authorization: Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\\n\" +\n               \"Content-Length: 2\\n\" +\n               \"Content-MD5: AAAAAAAAAAAAAAAAAAAAAA==\\n\" +\n               \"Content-Type: text/plain\\n\");\n      assertContentHeadersEqual(request, \"text/plain\", null, null, null, 2L, hashCode.asBytes(), null);\n\n      assertEquals(request.getFilters().size(), 0);\n   }\n\n   public void testSignPutBlobWithGenerate() throws ArrayIndexOutOfBoundsException, SecurityException,\n            IllegalArgumentException, NoSuchMethodException, IOException {\n      ByteSource byteSource = ByteSource.wrap(\"foo\".getBytes(Charsets.UTF_8));\n      Blob blob = blobFactory.get().name(blobName)\n         .payload(byteSource)\n         .contentLength(byteSource.size())\n         .contentMD5(byteSource.hash(Hashing.md5()).asBytes())\n         .contentType(\"text/plain\").build();\n      byte[] md5 = { -84, -67, 24, -37, 76, -62, -8, 92, -19, -17, 101, 79, -52, -60, -92, -40 };\n      \n      assertEquals(blob.getPayload().getContentMetadata().getContentMD5(), md5);\n\n      HttpRequest request = signer.signPutBlob(containerName, blob);\n\n      assertRequestLineEquals(request, \"PUT \" + fullUrl + \" HTTP/1.1\");\n      assertNonPayloadHeadersEqual(\n               request,\n               \"Authorization: Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\\nContent-Length: 3\\nContent-MD5: rL0Y20zC+Fzt72VPzMSk2A==\\nContent-Type: text/plain\\n\");\n      assertContentHeadersEqual(request, \"text/plain\", null, null, null, 3L, md5, null);\n\n      assertEquals(request.getFilters().size(), 0);\n   }\n\n   @BeforeClass\n   protected void setupFactory() throws IOException {\n      super.setupFactory();\n      this.blobFactory = injector.getProvider(BlobBuilder.class);\n      this.signer = injector.getInstance(BlobRequestSigner.class);\n   }\n\n   @Override\n   protected void checkFilters(HttpRequest request) {\n   }\n\n   @Override\n   public ApiMetadata createApiMetadata() {\n      return new TransientApiMetadata();\n   }\n\n}\n"
  },
  {
    "path": "blobstore/src/test/java/org/jclouds/blobstore/binders/BindBlobToMultipartFormTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.binders;\n\nimport static org.jclouds.io.payloads.MultipartForm.BOUNDARY;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.File;\nimport java.io.IOException;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.Blob.Factory;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.Test;\n\n/**\n * Tests parsing of a request\n */\n@Test(testName = \"blobstore.BindBlobToMultipartFormTest\")\npublic class BindBlobToMultipartFormTest {\n   private static Factory blobProvider;\n   public static final String EXPECTS;\n   public static final Blob TEST_BLOB;\n\n   static {\n      blobProvider = ContextBuilder.newBuilder(\"transient\").buildInjector().getInstance(Blob.Factory.class);\n      StringBuilder builder = new StringBuilder(\"--\");\n      addData(BOUNDARY, \"hello\", builder);\n      builder.append(\"--\").append(BOUNDARY).append(\"--\").append(\"\\r\\n\");\n      EXPECTS = builder.toString();\n      TEST_BLOB = blobProvider.create(null);\n      TEST_BLOB.getMetadata().setName(\"hello\");\n      TEST_BLOB.setPayload(\"hello\");\n      TEST_BLOB.getMetadata().getContentMetadata().setContentType(MediaType.TEXT_PLAIN);\n   }\n\n   public void testSinglePart() throws IOException {\n\n      assertEquals(EXPECTS.length(), 113);\n\n      BindBlobToMultipartForm binder = new BindBlobToMultipartForm();\n\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://localhost:8001\").build();\n      binder.bindToRequest(request, TEST_BLOB);\n\n      assertEquals(Strings2.toStringAndClose(request.getPayload().openStream()), EXPECTS);\n      assertEquals(request.getPayload().getContentMetadata().getContentLength(), Long.valueOf(113));\n\n      assertEquals(request.getPayload().getContentMetadata().getContentType(), \"multipart/form-data; boundary=\"\n            + BOUNDARY);\n   }\n\n   private static void addData(String boundary, String data, StringBuilder builder) {\n      builder.append(boundary).append(\"\\r\\n\");\n      builder.append(\"Content-Disposition\").append(\": \").append(\"form-data; name=\\\"hello\\\"\").append(\"\\r\\n\");\n      builder.append(\"Content-Type\").append(\": \").append(\"text/plain\").append(\"\\r\\n\");\n      builder.append(\"\\r\\n\");\n      builder.append(data).append(\"\\r\\n\");\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testMustBeBlob() {\n      BindBlobToMultipartForm binder = new BindBlobToMultipartForm();\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      binder.bindToRequest(request, new File(\"foo\"));\n   }\n\n   @Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class })\n   public void testNullIsBad() {\n      BindBlobToMultipartForm binder = new BindBlobToMultipartForm();\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").build();\n      binder.bindToRequest(request, null);\n   }\n}\n"
  },
  {
    "path": "blobstore/src/test/java/org/jclouds/blobstore/binders/BindMapToHeadersWithPrefixTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.File;\n\nimport org.jclouds.http.HttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\n\n@Test(groups = \"unit\")\npublic class BindMapToHeadersWithPrefixTest {\n\n   @Test\n   public void testCorrect() throws SecurityException, NoSuchMethodException {\n\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").build();\n      BindMapToHeadersWithPrefix binder = new BindMapToHeadersWithPrefix(\"prefix:\");\n\n      assertEquals(\n            binder.bindToRequest(request, ImmutableMap.of(\"imageName\", \"foo\", \"serverId\", \"2\")),\n            HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\")\n                       .addHeader(\"prefix:imagename\", \"foo\")\n                       .addHeader(\"prefix:serverid\", \"2\").build());\n\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testMustBeMap() {\n      BindMapToHeadersWithPrefix binder = new BindMapToHeadersWithPrefix(\"prefix:\");\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      binder.bindToRequest(request, new File(\"foo\"));\n   }\n\n   @Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class })\n   public void testNullIsBad() {\n      BindMapToHeadersWithPrefix binder = new BindMapToHeadersWithPrefix(\"prefix:\");\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").build();\n      binder.bindToRequest(request, null);\n   }\n}\n"
  },
  {
    "path": "blobstore/src/test/java/org/jclouds/blobstore/binders/BindUserMetadataToHeadersWithPrefixTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.File;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.http.HttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\n\n@Test(groups = \"unit\")\npublic class BindUserMetadataToHeadersWithPrefixTest {\n\n   @Test\n   public void testCorrect() throws SecurityException, NoSuchMethodException {\n\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").build();\n      BindUserMetadataToHeadersWithPrefix binder = new BindUserMetadataToHeadersWithPrefix(\n            new BindMapToHeadersWithPrefix(\"prefix:\"));\n\n      Blob blob = ContextBuilder.newBuilder(\"transient\").buildInjector().getInstance(Blob.Factory.class).create(null);\n\n      blob.getMetadata().setUserMetadata(ImmutableMap.of(\"imageName\", \"foo\", \"serverId\", \"2\"));\n\n      assertEquals(\n            binder.bindToRequest(request, blob),\n            HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\")\n                       .addHeader(\"prefix:imagename\", \"foo\")\n                       .addHeader(\"prefix:serverid\", \"2\").build());   \n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testMustBeBlob() {\n      BindUserMetadataToHeadersWithPrefix binder = new BindUserMetadataToHeadersWithPrefix(\n            new BindMapToHeadersWithPrefix(\"prefix:\"));\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      binder.bindToRequest(request, new File(\"foo\"));\n   }\n\n   @Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class })\n   public void testNullIsBad() {\n      BindUserMetadataToHeadersWithPrefix binder = new BindUserMetadataToHeadersWithPrefix(\n            new BindMapToHeadersWithPrefix(\"prefix:\"));\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").build();\n      binder.bindToRequest(request, null);\n   }\n}\n"
  },
  {
    "path": "blobstore/src/test/java/org/jclouds/blobstore/functions/BlobNameTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.Blob.Factory;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class BlobNameTest {\n   BlobName fn = new BlobName();\n   \n   private static final Factory BLOB_FACTORY = ContextBuilder.newBuilder(\"transient\").buildInjector().getInstance(Blob.Factory.class);\n\n   @Test\n   public void testCorrect() throws SecurityException, NoSuchMethodException {\n\n      Blob blob = BLOB_FACTORY.create(null);\n      blob.getMetadata().setName(\"foo\");\n\n      assertEquals(fn.apply(blob), \"foo\");\n   }\n\n   @Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class })\n   public void testNullIsBad() {\n      fn.apply(null);\n   }\n}\n"
  },
  {
    "path": "blobstore/src/test/java/org/jclouds/blobstore/functions/BlobToHttpGetOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Date;\n\nimport org.jclouds.http.options.GetOptions;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class BlobToHttpGetOptionsTest {\n   BlobToHttpGetOptions fn = new BlobToHttpGetOptions();\n\n   @Test\n   public void testNoneReturnsNone()  {\n      assertEquals(fn.apply(org.jclouds.blobstore.options.GetOptions.NONE), GetOptions.NONE);\n   }\n\n   @Test\n   public void testIfUnmodifiedSince()  {\n\n      Date ifUnmodifiedSince = new Date(999999L);\n\n      org.jclouds.blobstore.options.GetOptions in = new org.jclouds.blobstore.options.GetOptions();\n      in.ifUnmodifiedSince(ifUnmodifiedSince);\n      GetOptions expected = new GetOptions();\n      expected.ifUnmodifiedSince(ifUnmodifiedSince);\n\n      assertEquals(fn.apply(in), expected);\n   }\n\n   @Test\n   public void testIfModifiedSince()  {\n\n      Date ifModifiedSince = new Date(999999L);\n\n      org.jclouds.blobstore.options.GetOptions in = new org.jclouds.blobstore.options.GetOptions();\n      in.ifModifiedSince(ifModifiedSince);\n      GetOptions expected = new GetOptions();\n      expected.ifModifiedSince(ifModifiedSince);\n\n      assertEquals(fn.apply(in), expected);\n   }\n\n   public void testIfUnmatch()  {\n\n      String ifUnmatch = \"foo\";\n\n      org.jclouds.blobstore.options.GetOptions in = new org.jclouds.blobstore.options.GetOptions();\n      in.ifETagDoesntMatch(ifUnmatch);\n      GetOptions expected = new GetOptions();\n      expected.ifETagDoesntMatch(ifUnmatch);\n\n      assertEquals(fn.apply(in), expected);\n   }\n\n   @Test\n   public void testIfMatch()  {\n\n      String ifMatch = \"foo\";\n\n      org.jclouds.blobstore.options.GetOptions in = new org.jclouds.blobstore.options.GetOptions();\n      in.ifETagMatches(ifMatch);\n      \n      GetOptions expected = new GetOptions();\n      expected.ifETagMatches(ifMatch);\n\n      assertEquals(fn.apply(in), expected);\n   }\n\n   @Test\n   public void testRanges() {\n      org.jclouds.blobstore.options.GetOptions in = new org.jclouds.blobstore.options.GetOptions();\n      in.range(0, 1024);\n      in.startAt(2048);\n      \n      GetOptions expected = new GetOptions();\n      expected.range(0, 1024);\n      expected.startAt(2048);\n\n      assertEquals(fn.apply(in), expected);\n\n   }\n\n   @Test\n   public void testRangesTail() {\n      org.jclouds.blobstore.options.GetOptions in = new org.jclouds.blobstore.options.GetOptions();\n      in.tail(1024);\n\n      GetOptions expected = new GetOptions();\n      expected.tail(1024);\n\n      assertEquals(fn.apply(in), expected);\n\n   }\n   @Test\n   public void testRangesStart() {\n      org.jclouds.blobstore.options.GetOptions in = new org.jclouds.blobstore.options.GetOptions();\n      in.startAt(1024);\n\n      GetOptions expected = new GetOptions();\n      expected.startAt(1024);\n\n      assertEquals(fn.apply(in), expected);\n\n   }\n   \n   @Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class })\n   public void testNullIsBad() {\n      fn.apply(null);\n   }\n}\n"
  },
  {
    "path": "blobstore/src/test/java/org/jclouds/blobstore/functions/ParseBlobFromHeadersAndHttpContentTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.functions;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.testng.Assert.assertEquals;\n\nimport jakarta.inject.Provider;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.blobstore.config.BlobStoreObjectModule;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.MutableBlobMetadata;\nimport org.jclouds.blobstore.domain.internal.MutableBlobMetadataImpl;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.inject.Guice;\n\npublic class ParseBlobFromHeadersAndHttpContentTest {\n\n   @BeforeTest\n   void setUp() {\n      blobProvider = Guice.createInjector(new BlobStoreObjectModule()).getInstance(Blob.Factory.class);\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testCall() throws HttpException {\n      ParseSystemAndUserMetadataFromHeaders metadataParser = createMock(ParseSystemAndUserMetadataFromHeaders.class);\n      ParseBlobFromHeadersAndHttpContent callable = new ParseBlobFromHeadersAndHttpContent(metadataParser, blobProvider);\n      HttpResponse response = HttpResponse.builder()\n                                          .statusCode(200).message(\"ok\")\n                                          .addHeader(\"Content-Range\", (String) null).build(); \n      callable.apply(response);\n   }\n\n   private Blob.Factory blobProvider;\n   private Provider<MutableBlobMetadata> blobMetadataProvider = new Provider<MutableBlobMetadata>() {\n\n      public MutableBlobMetadata get() {\n         return new MutableBlobMetadataImpl();\n      }\n\n   };\n\n   @Test\n   public void testParseContentLengthWhenContentRangeSet() throws HttpException {\n      ParseSystemAndUserMetadataFromHeaders metadataParser = createMock(ParseSystemAndUserMetadataFromHeaders.class);\n      ParseBlobFromHeadersAndHttpContent callable = new ParseBlobFromHeadersAndHttpContent(metadataParser, blobProvider);\n      HttpResponse response = HttpResponse.builder()\n                                          .statusCode(200).message(\"ok\")\n                                          .payload(\"\")\n                                          .addHeader(\"Content-Range\", \"0-10485759/20232760\").build(); \n\n      response.getPayload().getContentMetadata().setContentType(MediaType.APPLICATION_JSON);\n      response.getPayload().getContentMetadata().setContentLength(10485760L);\n\n      MutableBlobMetadata meta = blobMetadataProvider.get();\n      expect(metadataParser.apply(response)).andReturn(meta);\n      replay(metadataParser);\n\n      Blob object = callable.apply(response);\n      assertEquals(object.getPayload().getContentMetadata().getContentLength(), Long.valueOf(10485760));\n      assertEquals(object.getAllHeaders().get(\"Content-Range\"), ImmutableList.of(\"0-10485759/20232760\"));\n\n   }\n\n}\n"
  },
  {
    "path": "blobstore/src/test/java/org/jclouds/blobstore/functions/ParseSystemAndUserMetadataFromHeadersTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport jakarta.inject.Provider;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.blobstore.domain.BlobMetadata;\nimport org.jclouds.blobstore.domain.MutableBlobMetadata;\nimport org.jclouds.blobstore.domain.internal.MutableBlobMetadataImpl;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.net.HttpHeaders;\n\n@Test(singleThreaded = true)\npublic class ParseSystemAndUserMetadataFromHeadersTest {\n\n   private ParseSystemAndUserMetadataFromHeaders parser;\n   private Provider<MutableBlobMetadata> blobMetadataProvider = new Provider<MutableBlobMetadata>() {\n\n      public MutableBlobMetadata get() {\n         return new MutableBlobMetadataImpl();\n      }\n\n   };\n\n   @BeforeTest\n   void setUp() {\n      parser = new ParseSystemAndUserMetadataFromHeaders(blobMetadataProvider, new SimpleDateFormatDateService(),\n               \"prefix\");\n      parser.setName(\"key\");\n   }\n\n   @Test\n   public void testApplySetsName() {\n      HttpResponse from = HttpResponse.builder()\n                                      .statusCode(200).message(\"ok\")\n                                      .payload(\"\")\n                                      .addHeader(HttpHeaders.LAST_MODIFIED, \"Wed, 09 Sep 2009 19:50:23 GMT\").build(); \n      from.getPayload().getContentMetadata().setContentType(MediaType.APPLICATION_JSON);\n      from.getPayload().getContentMetadata().setContentLength(100L);\n      BlobMetadata metadata = parser.apply(from);\n      assertEquals(metadata.getName(), \"key\");\n   }\n\n   @Test\n   public void testNoContentOn204IsOk() {\n      HttpResponse from = HttpResponse.builder()\n               .statusCode(204).message(\"ok\")\n               .addHeader(HttpHeaders.LAST_MODIFIED, \"Wed, 09 Sep 2009 19:50:23 GMT\").build(); \n      parser.apply(from);\n   }\n\n   @Test\n   public void testSetLastModified() {\n      HttpResponse from = HttpResponse.builder()\n                                      .statusCode(200).message(\"ok\")\n                                      .payload(\"\")\n                                      .addHeader(HttpHeaders.LAST_MODIFIED, \"Wed, 09 Sep 2009 19:50:23 GMT\").build(); \n      MutableBlobMetadata metadata = blobMetadataProvider.get();\n      parser.parseLastModifiedOrThrowException(from, metadata);\n      assertEquals(metadata.getLastModified(), new SimpleDateFormatDateService()\n               .rfc822DateParse(\"Wed, 09 Sep 2009 19:50:23 GMT\"));\n   }\n\n\n   @Test\n   public void testSetLastModifiedIso8601() {\n      HttpResponse from = HttpResponse.builder()\n                                      .statusCode(200).message(\"ok\")\n                                      .payload(\"\")\n                                      .addHeader(HttpHeaders.LAST_MODIFIED, \"2011-01-28T17:35:08.000Z\").build(); \n      MutableBlobMetadata metadata = blobMetadataProvider.get();\n      parser.parseLastModifiedOrThrowException(from, metadata);\n      assertEquals(metadata.getLastModified(), new SimpleDateFormatDateService()\n               .iso8601DateParse(\"2011-01-28T17:35:08.000Z\"));\n   }\n\n   \n   @Test(expectedExceptions = HttpException.class)\n   public void testSetLastModifiedException() {\n      HttpResponse from = HttpResponse.builder()\n                                      .statusCode(200).message(\"ok\")\n                                      .payload(\"\").build(); \n      MutableBlobMetadata metadata = blobMetadataProvider.get();\n      parser.parseLastModifiedOrThrowException(from, metadata);\n   }\n\n   @Test\n   public void testAddETagTo() {\n      HttpResponse from = HttpResponse.builder()\n                                      .statusCode(200).message(\"ok\")\n                                      .payload(\"\")\n                                      .addHeader(HttpHeaders.ETAG, \"0xfeb\").build(); \n      MutableBlobMetadata metadata = blobMetadataProvider.get();\n      parser.addETagTo(from, metadata);\n      assertEquals(metadata.getETag(), \"0xfeb\");\n   }\n\n   @Test\n   public void testAddUserMetadataTo() {\n      HttpResponse from = HttpResponse.builder()\n                                      .statusCode(200).message(\"ok\")\n                                      .payload(\"\")\n                                      .addHeader(\"prefix\" + \"key\", \"value\").build();\n      MutableBlobMetadata metadata = blobMetadataProvider.get();\n      parser.addUserMetadataTo(from, metadata);\n      assertEquals(metadata.getUserMetadata().get(\"key\"), \"value\");\n   }\n}\n"
  },
  {
    "path": "blobstore/src/test/java/org/jclouds/blobstore/functions/PrefixToResourceMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.blobstore.domain.MutableStorageMetadata;\nimport org.jclouds.blobstore.domain.StorageType;\nimport org.jclouds.blobstore.domain.internal.MutableStorageMetadataImpl;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class PrefixToResourceMetadataTest {\n   PrefixToResourceMetadata fn = new PrefixToResourceMetadata();\n\n   @Test\n   public void testCorrect() throws SecurityException, NoSuchMethodException {\n      MutableStorageMetadata expected = new MutableStorageMetadataImpl();\n      expected.setType(StorageType.RELATIVE_PATH);\n      expected.setName(\"foo\");\n      assertEquals(fn.apply(\"foo\"), expected);\n   }\n\n   @Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class })\n   public void testNullIsBad() {\n      fn.apply(null);\n   }\n}\n"
  },
  {
    "path": "blobstore/src/test/java/org/jclouds/blobstore/functions/ResourceMetadataToRelativePathResourceMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport jakarta.inject.Provider;\n\nimport org.jclouds.blobstore.domain.MutableBlobMetadata;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.domain.StorageType;\nimport org.jclouds.blobstore.domain.internal.MutableBlobMetadataImpl;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class ResourceMetadataToRelativePathResourceMetadataTest {\n\n   private ResourceMetadataToRelativePathResourceMetadata parser = new ResourceMetadataToRelativePathResourceMetadata();\n\n   private Provider<MutableBlobMetadata> blobMetadataProvider = new Provider<MutableBlobMetadata>() {\n\n      public MutableBlobMetadata get() {\n         return new MutableBlobMetadataImpl();\n      }\n\n   };\n\n   @Test\n   public void test1() {\n      MutableBlobMetadata md = blobMetadataProvider.get();\n      md.setName(\"dir/\");\n      md.setId(\"dir/\");\n      StorageMetadata rd = parser.apply(md);\n      assertEquals(rd.getName(), \"dir\");\n      assertEquals(rd.getProviderId(), \"dir/\");\n      assertEquals(rd.getType(), StorageType.RELATIVE_PATH);\n   }\n\n   @Test\n   public void test2() {\n      MutableBlobMetadata md = blobMetadataProvider.get();\n      md.setName(\"dir_$folder$\");\n      md.setId(\"dir_$folder$\");\n      StorageMetadata rd = parser.apply(md);\n      assertEquals(rd.getName(), \"dir\");\n      assertEquals(rd.getProviderId(), \"dir_$folder$\");\n      assertEquals(rd.getType(), StorageType.RELATIVE_PATH);\n   }\n\n   @Test\n   public void testNoNameChange() {\n      MutableBlobMetadata md = blobMetadataProvider.get();\n      md.setName(\"dir\");\n      md.setId(\"dir\");\n      StorageMetadata rd = parser.apply(md);\n      assertEquals(rd.getName(), \"dir\");\n      assertEquals(rd.getProviderId(), \"dir\");\n      assertEquals(rd.getType(), StorageType.RELATIVE_PATH);\n   }\n}\n"
  },
  {
    "path": "blobstore/src/test/java/org/jclouds/blobstore/integration/TransientBlobIntegrationTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.integration;\n\nimport com.google.common.hash.Hasher;\nimport com.google.common.hash.Hashing;\nimport com.google.common.io.BaseEncoding;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.MultipartPart;\nimport org.jclouds.blobstore.integration.internal.BaseBlobIntegrationTest;\nimport org.testng.annotations.Test;\nimport org.testng.SkipException;\n\nimport java.util.List;\n\nimport static org.assertj.core.api.Assertions.assertThat;\n\n@Test(groups = { \"integration\" })\npublic class TransientBlobIntegrationTest extends BaseBlobIntegrationTest {\n   public TransientBlobIntegrationTest() {\n      provider = \"transient\";\n   }\n\n   @Override\n   @Test(groups = { \"integration\", \"live\" })\n   public void testSetBlobAccess() throws Exception {\n      throw new SkipException(\"transient does not support anonymous access\");\n   }\n\n   @Override\n   protected void checkMPUParts(Blob blob, List<MultipartPart> parts) {\n      assertThat(blob.getMetadata().getETag()).endsWith(String.format(\"-%d\\\"\", parts.size()));\n      Hasher eTagHasher = Hashing.md5().newHasher();\n      for (MultipartPart part : parts) {\n         eTagHasher.putBytes(BaseEncoding.base16().lowerCase().decode(part.partETag()));\n      }\n      String expectedETag = new StringBuilder(\"\\\"\")\n              .append(eTagHasher.hash())\n              .append(\"-\")\n              .append(parts.size())\n              .append(\"\\\"\")\n              .toString();\n      assertThat(blob.getMetadata().getETag()).isEqualTo(expectedETag);\n   }\n}\n"
  },
  {
    "path": "blobstore/src/test/java/org/jclouds/blobstore/integration/TransientContainerIntegrationTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.integration;\n\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static org.jclouds.blobstore.options.ListContainerOptions.Builder.maxResults;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.BlobMetadata;\nimport org.jclouds.blobstore.domain.PageSet;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.integration.internal.BaseContainerIntegrationTest;\nimport org.jclouds.domain.Location;\nimport org.testng.annotations.Test;\nimport org.testng.SkipException;\n\nimport com.google.common.collect.ImmutableMap;\n\n@Test(groups = { \"integration\", \"live\" })\npublic class TransientContainerIntegrationTest extends BaseContainerIntegrationTest {\n   public TransientContainerIntegrationTest() {\n      provider = \"transient\";\n   }\n   \n   @Test(groups = { \"integration\", \"live\" })\n   public void testNotWithDetails() throws InterruptedException {\n\n      String key = \"hello\";\n      // NOTE all metadata in jclouds comes out as lowercase, in an effort to normalize the\n      // providers.\n      Blob blob = view.getBlobStore().blobBuilder(\"hello\").userMetadata(ImmutableMap.of(\"Adrian\", \"powderpuff\"))\n            .payload(TEST_STRING).contentType(MediaType.TEXT_PLAIN).build();\n\n      String containerName = getContainerName();\n      try {\n         addBlobToContainer(containerName, blob);\n         validateContent(containerName, key);\n\n         PageSet<? extends StorageMetadata> container = view.getBlobStore().list(containerName, maxResults(1));\n\n         BlobMetadata metadata = (BlobMetadata) getOnlyElement(container);\n         // transient container should be lenient and not return metadata on undetailed listing.\n\n         assertEquals(metadata.getUserMetadata().size(), 0);\n\n      } finally {\n         returnContainer(containerName);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testDuplicateCreateContainer() {\n      BlobStore blobStore = view.getBlobStore();\n      Location location = null;\n      String container = \"container\";\n      boolean created;\n\n      created = blobStore.createContainerInLocation(location, container);\n      assertTrue(created);\n\n      created = blobStore.createContainerInLocation(location, container);\n      assertFalse(created);\n   }\n\n   @Override\n   @Test(groups = { \"integration\", \"live\" })\n   public void testSetContainerAccess() throws Exception {\n      throw new SkipException(\"transient does not support anonymous access\");\n   }\n}\n"
  },
  {
    "path": "blobstore/src/test/java/org/jclouds/blobstore/integration/TransientServiceIntegrationTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.integration;\n\nimport org.jclouds.blobstore.integration.internal.BaseServiceIntegrationTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = { \"integration\", \"live\" })\npublic class TransientServiceIntegrationTest extends BaseServiceIntegrationTest {\n   public TransientServiceIntegrationTest() {\n      provider = \"transient\";\n   }\n}\n"
  },
  {
    "path": "blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseBlobIntegrationTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.integration.internal;\n\nimport static org.assertj.core.api.Fail.failBecauseExceptionWasNotThrown;\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.hash.Hashing.md5;\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.jclouds.blobstore.options.GetOptions.Builder.ifETagDoesntMatch;\nimport static org.jclouds.blobstore.options.GetOptions.Builder.ifETagMatches;\nimport static org.jclouds.blobstore.options.GetOptions.Builder.ifModifiedSince;\nimport static org.jclouds.blobstore.options.GetOptions.Builder.ifUnmodifiedSince;\nimport static org.jclouds.blobstore.options.GetOptions.Builder.range;\nimport static org.jclouds.concurrent.FutureIterables.awaitCompletion;\nimport static org.jclouds.io.ByteStreams2.hashAndClose;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.fail;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.cert.CertificateException;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Random;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.TimeUnit;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.assertj.core.api.Fail;\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.ContainerNotFoundException;\nimport org.jclouds.blobstore.KeyNotFoundException;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.BlobAccess;\nimport org.jclouds.blobstore.domain.BlobBuilder.PayloadBlobBuilder;\nimport org.jclouds.blobstore.domain.BlobMetadata;\nimport org.jclouds.blobstore.domain.MultipartPart;\nimport org.jclouds.blobstore.domain.MultipartUpload;\nimport org.jclouds.blobstore.domain.PageSet;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.domain.StorageType;\nimport org.jclouds.blobstore.domain.Tier;\nimport org.jclouds.blobstore.options.CopyOptions;\nimport org.jclouds.blobstore.options.GetOptions;\nimport org.jclouds.blobstore.options.PutOptions;\nimport org.jclouds.blobstore.strategy.internal.MultipartUploadSlicingAlgorithm;\nimport org.jclouds.crypto.Crypto;\nimport org.jclouds.encryption.internal.JCECrypto;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.io.ByteStreams2;\nimport org.jclouds.io.ContentMetadataBuilder;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.io.payloads.ByteSourcePayload;\nimport org.jclouds.io.payloads.InputStreamPayload;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.util.Closeables2;\nimport org.jclouds.utils.TestUtils;\nimport org.testng.ITestContext;\nimport org.testng.SkipException;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.DataProvider;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Throwables;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Maps;\nimport com.google.common.hash.HashCode;\nimport com.google.common.hash.Hashing;\nimport com.google.common.io.ByteSource;\nimport com.google.common.io.ByteStreams;\nimport com.google.common.io.Files;\nimport com.google.common.net.HttpHeaders;\nimport com.google.common.util.concurrent.ListenableFuture;\n\npublic class BaseBlobIntegrationTest extends BaseBlobStoreIntegrationTest {\n   private static final ByteSource oneHundredOneConstitutions = TestUtils.randomByteSource().slice(0, 101 * 45118);\n\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   @Override\n   public void setUpResourcesOnThisThread(ITestContext testContext) throws Exception {\n      super.setUpResourcesOnThisThread(testContext);\n   }\n\n   public static ByteSource getTestDataSupplier() throws IOException {\n      return oneHundredOneConstitutions;\n   }\n\n   /**\n    * Attempt to capture the issue detailed in\n    * http://groups.google.com/group/jclouds/browse_thread/thread/4a7c8d58530b287f\n    */\n   @Test(groups = { \"integration\", \"live\" })\n   public void testPutBlobParallel() throws Exception {\n      final ByteSource expected = createTestInput(32 * 1024);\n\n      final String container = getContainerName();\n      try {\n         Map<Integer, ListenableFuture<?>> responses = Maps.newHashMap();\n         for (int i = 0; i < 3; i++) {\n            final String name = String.valueOf(i);\n            responses.put(i, this.exec.submit(new Callable<Void>() {\n\n               @Override\n               public Void call() throws Exception {\n                  Payload payload = Payloads.newByteSourcePayload(expected);\n                  payload.getContentMetadata().setContentType(\"image/png\");\n                  Blob blob = view.getBlobStore().blobBuilder(name).payload(payload).contentLength(expected.size()).build();\n                  view.getBlobStore().putBlob(container, blob);\n\n                  assertConsistencyAwareBlobExists(container, name);\n\n                  blob = view.getBlobStore().getBlob(container, name);\n                  byte[] actual = ByteStreams2.toByteArrayAndClose(blob.getPayload().openStream());\n                  assertThat(actual).isEqualTo(expected.read());\n\n                  view.getBlobStore().removeBlob(container, name);\n                  assertConsistencyAwareBlobDoesntExist(container, name);\n                  return null;\n               }\n\n            }));\n         }\n         Map<Integer, Exception> exceptions = awaitCompletion(responses, exec, 30000L, Logger.CONSOLE,\n                  \"putFileParallel\");\n         assert exceptions.size() == 0 : exceptions;\n\n      } finally {\n         returnContainer(container);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testFileGetParallel() throws Exception {\n      final ByteSource supplier = createTestInput(32 * 1024);\n      final String container = getContainerName();\n      try {\n         final String name = \"constitution.txt\";\n\n         uploadByteSource(container, name, supplier);\n         Map<Integer, ListenableFuture<?>> responses = Maps.newHashMap();\n         for (int i = 0; i < 10; i++) {\n            responses.put(i, this.exec.submit(new Callable<Void>() {\n               @Override public Void call() throws Exception {\n                  try {\n                     Blob blob = view.getBlobStore().getBlob(container, name);\n                     validateMetadata(blob.getMetadata(), container, name);\n                     assertEquals(hashAndClose(blob.getPayload().openStream(), md5()), supplier.hash(md5()));\n                  } catch (IOException e) {\n                     Throwables.propagate(e);\n                  }\n                  return null;\n               }\n            }));\n         }\n         Map<Integer, Exception> exceptions = awaitCompletion(responses, exec, 30000L, Logger.CONSOLE,\n                  \"get constitution\");\n         if (!exceptions.isEmpty()) {\n            throw exceptions.values().iterator().next();\n         }\n\n      } finally {\n         returnContainer(container);\n      }\n\n   }\n\n   private void uploadByteSource(String container, String name, ByteSource byteSource) throws IOException {\n      BlobStore blobStore = view.getBlobStore();\n      blobStore.putBlob(container, blobStore.blobBuilder(name)\n            .payload(new ByteSourcePayload(byteSource))\n            .contentType(\"text/plain\")\n            .contentMD5(byteSource.hash(md5()))\n            .contentLength(byteSource.size())\n            .build());\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testGetIfModifiedSince() throws InterruptedException {\n      String container = getContainerName();\n      try {\n         String name = \"apples\";\n\n         Date before = new Date(System.currentTimeMillis() - 1000);\n         // first create the blob\n         addObjectAndValidateContent(container, name);\n         // now, modify it\n         addObjectAndValidateContent(container, name);\n         Date after = new Date(System.currentTimeMillis() + 1000);\n\n         view.getBlobStore().getBlob(container, name, ifModifiedSince(before));\n         validateContent(container, name);\n\n         try {\n            view.getBlobStore().getBlob(container, name, ifModifiedSince(after));\n            validateContent(container, name);\n         } catch (HttpResponseException ex) {\n            assertEquals(ex.getResponse().getStatusCode(), 304);\n         }\n      } finally {\n         returnContainer(container);\n      }\n\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testOverwriteBlob() throws InterruptedException {\n      String container = getContainerName();\n      BlobStore blobStore = view.getBlobStore();\n      try {\n         String blobName = \"hello\";\n         Blob blob = blobStore.blobBuilder(blobName)\n               .payload(TEST_STRING)\n               .build();\n         blobStore.putBlob(container, blob);\n         Blob overwriteBlob = blobStore.blobBuilder(blobName)\n               .payload(\"overwrite content\")\n               .build();\n         blobStore.putBlob(container, overwriteBlob);\n      } finally {\n         returnContainer(container);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testCreateBlobWithExpiry() throws InterruptedException {\n      String container = getContainerName();\n      BlobStore blobStore = view.getBlobStore();\n      try {\n         final String blobName = \"hello\";\n         final Date expires = new Date((System.currentTimeMillis() / 1000) * 1000 + 60 * 1000);\n\n         blobStore.putBlob(container, blobStore.blobBuilder(blobName).payload(TEST_STRING).expires(expires).build());\n\n         assertConsistencyAwareBlobExpiryMetadata(container, blobName, expires);\n\n      } finally {\n         returnContainer(container);\n      }\n   }\n\n   private void putBlobWithMd5(Payload payload, long contentLength, HashCode contentMD5) throws InterruptedException, IOException {\n      String container = getContainerName();\n      BlobStore blobStore = view.getBlobStore();\n      try {\n         String blobName = \"putBlobWithMd5-\" + new Random().nextLong();\n         Blob blob = blobStore\n            .blobBuilder(blobName)\n            .payload(payload)\n            .contentLength(contentLength)\n            .contentMD5(contentMD5)\n            .build();\n         blobStore.putBlob(container, blob);\n      } finally {\n         returnContainer(container);\n      }\n   }\n\n   protected int getIncorrectContentMD5StatusCode() {\n      return 400;\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testPutCorrectContentMD5ByteSource() throws InterruptedException, IOException {\n      ByteSource payload = createTestInput(1024);\n      HashCode contentMD5 = md5().hashBytes(payload.read());\n      putBlobWithMd5(new ByteSourcePayload(payload), payload.size(), contentMD5);\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testPutIncorrectContentMD5ByteSource() throws InterruptedException, IOException {\n      ByteSource payload = createTestInput(1024);\n      HashCode contentMD5 = md5().hashBytes(new byte[0]);\n      try {\n         putBlobWithMd5(new ByteSourcePayload(payload), payload.size(), contentMD5);\n         fail();\n      } catch (HttpResponseException hre) {\n         if (hre.getResponse().getStatusCode() != getIncorrectContentMD5StatusCode()) {\n            throw hre;\n         }\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testPutCorrectContentMD5InputStream() throws InterruptedException, IOException {\n      ByteSource payload = createTestInput(1024);\n      HashCode contentMD5 = md5().hashBytes(payload.read());\n      putBlobWithMd5(new InputStreamPayload(payload.openStream()), payload.size(), contentMD5);\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testPutIncorrectContentMD5InputStream() throws InterruptedException, IOException {\n      ByteSource payload = createTestInput(1024);\n      HashCode contentMD5 = md5().hashBytes(new byte[0]);\n      try {\n         putBlobWithMd5(new InputStreamPayload(payload.openStream()), payload.size(), contentMD5);\n         fail();\n      } catch (HttpResponseException hre) {\n         if (hre.getResponse().getStatusCode() != getIncorrectContentMD5StatusCode()) {\n            throw hre;\n         }\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testGetIfUnmodifiedSince() throws InterruptedException {\n      String container = getContainerName();\n      try {\n\n         String name = \"apples\";\n\n         Date before = new Date(System.currentTimeMillis() - 10000);\n         addObjectAndValidateContent(container, name);\n         Date after = new Date(System.currentTimeMillis() + 10000);\n\n         awaitConsistency();\n         view.getBlobStore().getBlob(container, name, ifUnmodifiedSince(after));\n         validateContent(container, name);\n\n         try {\n            view.getBlobStore().getBlob(container, name, ifUnmodifiedSince(before));\n            validateContent(container, name);\n         } catch (HttpResponseException ex) {\n            assertEquals(ex.getResponse().getStatusCode(), 412);\n         }\n      } finally {\n         returnContainer(container);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testGetIfMatch() throws InterruptedException {\n      String container = getContainerName();\n      try {\n\n         String name = \"apples\";\n\n         String goodETag = addObjectAndValidateContent(container, name);\n\n         view.getBlobStore().getBlob(container, name, ifETagMatches(goodETag));\n         validateContent(container, name);\n\n         try {\n            view.getBlobStore().getBlob(container, name, ifETagMatches(\"powerfrisbee\"));\n            validateContent(container, name);\n         } catch (HttpResponseException ex) {\n            assertEquals(ex.getResponse().getStatusCode(), 412);\n         }\n      } finally {\n         returnContainer(container);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testGetIfNoneMatch() throws InterruptedException {\n      String container = getContainerName();\n      try {\n\n         String name = \"apples\";\n\n         String goodETag = addObjectAndValidateContent(container, name);\n\n         view.getBlobStore().getBlob(container, name, ifETagDoesntMatch(\"powerfrisbee\"));\n         validateContent(container, name);\n\n         try {\n            view.getBlobStore().getBlob(container, name, ifETagDoesntMatch(goodETag));\n         } catch (HttpResponseException ex) {\n            assertEquals(ex.getResponse().getStatusCode(), 304);\n         }\n      } finally {\n         returnContainer(container);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testGetRangeOutOfRange() throws InterruptedException, IOException {\n      String container = getContainerName();\n      try {\n         String name = \"apples\";\n\n         addObjectAndValidateContent(container, name);\n         try {\n            view.getBlobStore().getBlob(container, name, range(TEST_STRING.length(), TEST_STRING.length() + 1));\n            failBecauseExceptionWasNotThrown(HttpResponseException.class);\n         } catch (HttpResponseException e) {\n            assertThat(e.getResponse().getStatusCode()).isEqualTo(416);\n         }\n      } finally {\n         returnContainer(container);\n      }\n\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testGetRange() throws InterruptedException, IOException {\n      String container = getContainerName();\n      try {\n\n         String name = \"apples\";\n\n         addObjectAndValidateContent(container, name);\n         Blob blob1 = view.getBlobStore().getBlob(container, name, range(0, 5));\n         validateMetadata(blob1.getMetadata(), container, name);\n         assertEquals(getContentAsStringOrNullAndClose(blob1), TEST_STRING.substring(0, 6));\n         assertThat(blob1.getAllHeaders().get(HttpHeaders.CONTENT_RANGE)).containsExactly(\"bytes 0-5/46\");\n\n         Blob blob2 = view.getBlobStore().getBlob(container, name, range(6, TEST_STRING.length()));\n         validateMetadata(blob2.getMetadata(), container, name);\n         assertEquals(getContentAsStringOrNullAndClose(blob2), TEST_STRING.substring(6, TEST_STRING.length()));\n         assertThat(blob2.getAllHeaders().get(HttpHeaders.CONTENT_RANGE)).containsExactly(\"bytes 6-45/46\");\n\n         /* RFC 2616 14.35.1\n            \"If the entity is shorter than the specified suffix-length, the\n            entire entity-body is used.\" */\n         Blob blob3 = view.getBlobStore().getBlob(container, name, new GetOptions().tail(TEST_STRING.length() + 10));\n         validateMetadata(blob3.getMetadata(), container, name);\n         assertEquals(getContentAsStringOrNullAndClose(blob3), TEST_STRING);\n         // not all providers return Content-Range for non-partial responses\n      } finally {\n         returnContainer(container);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testGetTwoRanges() throws InterruptedException, IOException {\n      String container = getContainerName();\n      try {\n\n         String name = \"apples\";\n\n         addObjectAndValidateContent(container, name);\n         Blob blob = view.getBlobStore().getBlob(container, name, range(0, 5).range(6, TEST_STRING.length()));\n         validateMetadata(blob.getMetadata(), container, name);\n         assertEquals(getContentAsStringOrNullAndClose(blob), TEST_STRING);\n      } finally {\n         returnContainer(container);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testGetRangeMultipart() throws InterruptedException, IOException {\n      String container = getContainerName();\n      InputStream expect = null;\n      InputStream actual = null;\n      try {\n         String name = \"apples\";\n         long length = getMinimumMultipartBlobSize();\n         ByteSource byteSource = TestUtils.randomByteSource().slice(0, length);\n         Blob blob = view.getBlobStore().blobBuilder(name)\n                 .payload(byteSource)\n                 .contentLength(length)\n                 .build();\n         view.getBlobStore().putBlob(container, blob, new PutOptions().multipart(true));\n         blob = view.getBlobStore().getBlob(container, name, range(0, 5));\n         validateMetadata(blob.getMetadata(), container, name);\n         expect = byteSource.slice(0, 6).openStream();\n         actual = blob.getPayload().openStream();\n         assertThat(actual).hasContentEqualTo(expect);\n      } finally {\n         Closeables2.closeQuietly(expect);\n         Closeables2.closeQuietly(actual);\n         returnContainer(container);\n      }\n   }\n\n   private String addObjectAndValidateContent(String sourcecontainer, String sourceKey) throws InterruptedException {\n      String eTag = addBlobToContainer(sourcecontainer, sourceKey);\n      validateContent(sourcecontainer, sourceKey);\n      awaitConsistency();\n      return eTag;\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void deleteObjectNotFound() throws InterruptedException {\n      String container = getContainerName();\n      String name = \"test\";\n      try {\n         view.getBlobStore().removeBlob(container, name);\n      } finally {\n         returnContainer(container);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void blobNotFound() throws InterruptedException {\n      String container = getContainerName();\n      String name = \"test\";\n      try {\n         assert !view.getBlobStore().blobExists(container, name);\n      } finally {\n         returnContainer(container);\n      }\n   }\n\n   @DataProvider(name = \"delete\")\n   public Object[][] createData() {\n      if (System.getProperty(\"os.name\").toLowerCase().contains(\"windows\")) {\n         return new Object[][] { { \"normal\" }, { \"sp ace\" } };\n      } else {\n         return new Object[][] { { \"normal\" }, { \"sp ace\" }, { \"qu?stion\" }, { \"unic₪de\" }, { \"path/foo\" }, { \"colon:\" },\n               { \"asteri*k\" }, { \"quote\\\"\" }, { \"{great<r}\" }, { \"lesst>en\" }, { \"p|pe\" } };\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" }, dataProvider = \"delete\")\n   public void deleteObject(String name) throws InterruptedException {\n      String container = getContainerName();\n      try {\n         addBlobToContainer(container, name, name, MediaType.TEXT_PLAIN);\n         awaitConsistency();\n         view.getBlobStore().removeBlob(container, name);\n         awaitConsistency();\n         assertContainerEmptyDeleting(container, name);\n      } finally {\n         returnContainer(container);\n      }\n   }\n\n   private void assertContainerEmptyDeleting(String container, String name) {\n      Iterable<? extends StorageMetadata> listing = Iterables.filter(view.getBlobStore().list(container),\n               new Predicate<StorageMetadata>() {\n\n                  @Override\n                  public boolean apply(StorageMetadata input) {\n                     return input.getType() == StorageType.BLOB;\n                  }\n\n               });\n      assertEquals(Iterables.size(listing), 0, String.format(\n               \"deleting %s, we still have %s blobs left in container %s, using encoding %s\", name, Iterables\n                        .size(listing), container, LOCAL_ENCODING));\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void deleteObjectNoContainer() {\n      try {\n         view.getBlobStore().removeBlob(\"donb\", \"test\");\n      } catch (HttpResponseException e) {\n         assertEquals(e.getResponse().getStatusCode(), 404);\n      } catch (ContainerNotFoundException e) {\n      }\n\n   }\n\n   @Test(groups = { \"integration\", \"live\" }, dataProvider = \"delete\")\n   public void deleteMultipleObjects(String name) throws InterruptedException {\n      String name2 = name + \"2\";\n      String container = getContainerName();\n      try {\n         addBlobToContainer(container, name, name, MediaType.TEXT_PLAIN);\n         addBlobToContainer(container, name2, name2, MediaType.TEXT_PLAIN);\n         awaitConsistency();\n         view.getBlobStore().removeBlobs(container, ImmutableSet.of(name, name2));\n         awaitConsistency();\n         assertContainerEmptyDeleting(container, name);\n      } finally {\n         returnContainer(container);\n      }\n   }\n\n   @DataProvider(name = \"putTests\")\n   public Object[][] createData1() throws IOException {\n      File file = new File(\"pom.xml\");\n      String realObject = Files.toString(file, Charsets.UTF_8);\n\n      return new Object[][] { { \"file\", \"text/xml\", file, realObject },\n               { \"string\", \"text/xml\", realObject, realObject },\n               { \"bytes\", \"application/octet-stream\", realObject.getBytes(), realObject } };\n   }\n\n   @Test(groups = { \"integration\", \"live\" }, dataProvider = \"putTests\")\n   public void testPutObject(String name, String type, Object content, Object realObject) throws InterruptedException,\n            IOException {\n      PayloadBlobBuilder blobBuilder = view.getBlobStore().blobBuilder(name).payload(Payloads.newPayload(content))\n               .contentType(type);\n      addContentMetadata(blobBuilder);\n      Blob blob = blobBuilder.build();\n      String container = getContainerName();\n      try {\n         assertNotNull(view.getBlobStore().putBlob(container, blob));\n         awaitConsistency();\n\n         blob = view.getBlobStore().getBlob(container, blob.getMetadata().getName());\n         validateMetadata(blob.getMetadata(), container, name);\n         checkContentMetadata(blob);\n\n         String returnedString = getContentAsStringOrNullAndClose(blob);\n         assertEquals(returnedString, realObject);\n         PageSet<? extends StorageMetadata> set = view.getBlobStore().list(container);\n         assert set.size() == 1 : set;\n      } finally {\n         returnContainer(container);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testPutObjectStream() throws InterruptedException, IOException, ExecutionException {\n      PayloadBlobBuilder blobBuilder = view.getBlobStore().blobBuilder(\"streaming\").payload(\n               new ByteSourcePayload(ByteSource.wrap(\"foo\".getBytes())));\n      addContentMetadata(blobBuilder);\n\n      Blob blob = blobBuilder.build();\n\n      String container = getContainerName();\n      try {\n\n         assertNotNull(view.getBlobStore().putBlob(container, blob));\n         awaitConsistency();\n\n         blob = view.getBlobStore().getBlob(container, blob.getMetadata().getName());\n         String returnedString = getContentAsStringOrNullAndClose(blob);\n         assertEquals(returnedString, \"foo\");\n         validateMetadata(blob.getMetadata(), container, blob.getMetadata().getName());\n         checkContentMetadata(blob);\n         PageSet<? extends StorageMetadata> set = view.getBlobStore().list(container);\n         assert set.size() == 1 : set;\n      } finally {\n         returnContainer(container);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testPutByteSource() throws Exception {\n      long length = 42;\n      ByteSource byteSource = TestUtils.randomByteSource().slice(0, length);\n      Payload payload = new ByteSourcePayload(byteSource);\n      testPut(payload, null, payload, length, new PutOptions());\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testPutInputStream() throws Exception {\n      long length = 42;\n      ByteSource byteSource = TestUtils.randomByteSource().slice(0, length);\n      Payload payload = new InputStreamPayload(byteSource.openStream());\n      testPut(payload, null, new ByteSourcePayload(byteSource), length, new PutOptions());\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testPutZeroLengthByteSource() throws Exception {\n      long length = 0;\n      // do not use ByteSource.empty() since it is backed by a\n      // ByteArrayInputStream which supports reset\n      ByteSource byteSource = TestUtils.randomByteSource().slice(0, length);\n      Payload payload = new ByteSourcePayload(byteSource);\n      testPut(payload, null, payload, length, new PutOptions());\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testPutZeroLengthInputStream() throws Exception {\n      long length = 0;\n      // do not use ByteSource.empty() since it is backed by a\n      // ByteArrayInputStream which supports reset\n      ByteSource byteSource = TestUtils.randomByteSource().slice(0, length);\n      Payload payload = new InputStreamPayload(byteSource.openStream());\n      testPut(payload, null, payload, length, new PutOptions());\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testPutMultipartByteSource() throws Exception {\n      long length = Math.max(getMinimumMultipartBlobSize(), MultipartUploadSlicingAlgorithm.DEFAULT_PART_SIZE + 1);\n      BlobStore blobStore = view.getBlobStore();\n      MultipartUploadSlicingAlgorithm algorithm = new MultipartUploadSlicingAlgorithm(\n              blobStore.getMinimumMultipartPartSize(), blobStore.getMaximumMultipartPartSize(),\n              blobStore.getMaximumNumberOfParts());\n      // make sure that we are creating multiple parts\n      assertThat(algorithm.calculateChunkSize(length)).isLessThan(length);\n      ByteSource byteSource = TestUtils.randomByteSource().slice(0, length);\n      Payload payload = new ByteSourcePayload(byteSource);\n      HashCode hashCode = byteSource.hash(Hashing.md5());\n      testPut(payload, hashCode, payload, length, new PutOptions().multipart(true));\n   }\n\n   @Test(groups = { \"integration\", \"live\" }, enabled = false)\n   public void testPutMultipartByteSourceBig() throws Exception {\n      long length = 5L * 1024 * 1024 * 1024 + 1;\n      BlobStore blobStore = view.getBlobStore();\n      MultipartUploadSlicingAlgorithm algorithm = new MultipartUploadSlicingAlgorithm(\n              blobStore.getMinimumMultipartPartSize(), blobStore.getMaximumMultipartPartSize(),\n              blobStore.getMaximumNumberOfParts());\n      // make sure that we are creating multiple parts\n      assertThat(algorithm.calculateChunkSize(length)).isLessThan(length);\n      // TODO: this is inefficient due to skip recomputing entire stream\n      ByteSource byteSource = TestUtils.randomByteSource().slice(0, length);\n      Payload payload = new ByteSourcePayload(byteSource);\n      HashCode hashCode = byteSource.hash(Hashing.md5());\n      testPut(payload, hashCode, payload, length, new PutOptions().multipart(true));\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testPutMultipartInputStream() throws Exception {\n      long length = Math.max(getMinimumMultipartBlobSize(), MultipartUploadSlicingAlgorithm.DEFAULT_PART_SIZE + 1);\n      BlobStore blobStore = view.getBlobStore();\n      MultipartUploadSlicingAlgorithm algorithm = new MultipartUploadSlicingAlgorithm(\n              blobStore.getMinimumMultipartPartSize(), blobStore.getMaximumMultipartPartSize(),\n              blobStore.getMaximumNumberOfParts());\n      // make sure that we are creating multiple parts\n      assertThat(algorithm.calculateChunkSize(length)).isLessThan(length);\n      ByteSource byteSource = TestUtils.randomByteSource().slice(0, length);\n      Payload payload = new InputStreamPayload(byteSource.openStream());\n      testPut(payload, null, new ByteSourcePayload(byteSource), length, new PutOptions().multipart(true));\n   }\n\n   protected void allowPublicReadable(String containerName) {\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testSetBlobAccess() throws Exception {\n      BlobStore blobStore = view.getBlobStore();\n      String containerName = getContainerName();\n      String blobName = \"set-access-blob-name\";\n      try {\n         allowPublicReadable(containerName);\n         addBlobToContainer(containerName, blobName, blobName, MediaType.TEXT_PLAIN);\n\n         assertThat(blobStore.getBlobAccess(containerName, blobName)).isEqualTo(BlobAccess.PRIVATE);\n\n         blobStore.setBlobAccess(containerName, blobName, BlobAccess.PUBLIC_READ);\n         assertThat(blobStore.getBlobAccess(containerName, blobName)).isEqualTo(BlobAccess.PUBLIC_READ);\n\n         // test that blob is anonymously readable\n         HttpRequest request = view.getSigner().signGetBlob(containerName, blobName).toBuilder()\n                .replaceQueryParams(ImmutableMap.<String, String>of()).build();\n         HttpResponse response = view.utils().http().invoke(request);\n         assertThat(response.getStatusCode()).isEqualTo(200);\n\n         blobStore.setBlobAccess(containerName, blobName, BlobAccess.PRIVATE);\n         assertThat(blobStore.getBlobAccess(containerName, blobName)).isEqualTo(BlobAccess.PRIVATE);\n      } finally {\n         returnContainer(containerName);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testPutBlobAccess() throws Exception {\n      BlobStore blobStore = view.getBlobStore();\n      String containerName = getContainerName();\n      try {\n         String blobNamePrivate = \"put-access-blob-name-private\";\n         Blob blobPrivate = blobStore.blobBuilder(blobNamePrivate).payload(new byte[1]).build();\n         blobStore.putBlob(containerName, blobPrivate, new PutOptions().setBlobAccess(BlobAccess.PRIVATE));\n         assertThat(blobStore.getBlobAccess(containerName, blobNamePrivate)).isEqualTo(BlobAccess.PRIVATE);\n\n         String blobNamePublic = \"put-access-blob-name-public\";\n         Blob blobPublic = blobStore.blobBuilder(blobNamePublic).payload(new byte[1]).build();\n         blobStore.putBlob(containerName, blobPublic, new PutOptions().setBlobAccess(BlobAccess.PUBLIC_READ));\n         assertThat(blobStore.getBlobAccess(containerName, blobNamePublic)).isEqualTo(BlobAccess.PUBLIC_READ);\n      } finally {\n         returnContainer(containerName);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testPutBlobAccessMultipart() throws Exception {\n      BlobStore blobStore = view.getBlobStore();\n      String containerName = getContainerName();\n      allowPublicReadable(containerName);\n      ByteSource byteSource = TestUtils.randomByteSource().slice(0, getMinimumMultipartBlobSize());\n      Payload payload = Payloads.newByteSourcePayload(byteSource);\n      payload.getContentMetadata().setContentLength(byteSource.size());\n      try {\n         String blobNamePrivate = \"put-access-blob-name-private\";\n         Blob blobPrivate = blobStore.blobBuilder(blobNamePrivate).payload(payload).build();\n         blobStore.putBlob(containerName, blobPrivate, new PutOptions().setBlobAccess(BlobAccess.PRIVATE).multipart(true));\n         assertThat(blobStore.getBlobAccess(containerName, blobNamePrivate)).isEqualTo(BlobAccess.PRIVATE);\n\n         String blobNamePublic = \"put-access-blob-name-public\";\n         Blob blobPublic = blobStore.blobBuilder(blobNamePublic).payload(payload).build();\n         blobStore.putBlob(containerName, blobPublic, new PutOptions().setBlobAccess(BlobAccess.PUBLIC_READ).multipart(true));\n         assertThat(blobStore.getBlobAccess(containerName, blobNamePublic)).isEqualTo(BlobAccess.PUBLIC_READ);\n      } finally {\n         returnContainer(containerName);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testPutBlobTierStandard() throws Exception {\n      testPutBlobTierHelper(Tier.STANDARD, new PutOptions());\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testPutBlobTierInfrequent() throws Exception {\n      testPutBlobTierHelper(Tier.COOL, new PutOptions());\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testPutBlobTierArchive() throws Exception {\n      testPutBlobTierHelper(Tier.ARCHIVE, new PutOptions());\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testPutBlobTierStandardMultipart() throws Exception {\n      testPutBlobTierHelper(Tier.STANDARD, new PutOptions().multipart(true));\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testPutBlobTierInfrequentMultipart() throws Exception {\n      testPutBlobTierHelper(Tier.COOL, new PutOptions().multipart(true));\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testPutBlobTierArchiveMultipart() throws Exception {\n      testPutBlobTierHelper(Tier.ARCHIVE, new PutOptions().multipart(true));\n   }\n\n   protected void testPutBlobTierHelper(Tier tier, PutOptions options) throws Exception {\n      String blobName = \"put-blob-tier-\" + tier;\n      ByteSource payload = createTestInput(1024);\n      BlobStore blobStore = view.getBlobStore();\n      String containerName = getContainerName();\n      try {\n         Blob blob = blobStore.blobBuilder(blobName)\n            .payload(payload)\n            .contentLength(payload.size())\n            .tier(tier)\n            .build();\n         blobStore.putBlob(containerName, blob, options);\n         checkTier(blobStore.blobMetadata(containerName, blobName), tier);\n      } finally {\n         returnContainer(containerName);\n      }\n   }\n\n   protected void checkTier(BlobMetadata metadata, Tier expected) {\n      assertThat(metadata.getTier()).isEqualTo(expected);\n   }\n\n   protected void checkUserMetadata(Map<String, String> userMetadata1, Map<String, String> userMetadata2) {\n      assertThat(userMetadata1).isEqualTo(userMetadata2);\n   }\n\n   private void testPut(Payload payload, HashCode hashCode, Payload expectedPayload, long length, PutOptions options)\n         throws IOException, InterruptedException {\n      BlobStore blobStore = view.getBlobStore();\n      String blobName = \"multipart-upload\";\n      Map<String, String> userMetadata = ImmutableMap.of(\"key1\", \"value1\", \"key2\", \"value2\");\n      PayloadBlobBuilder blobBuilder = blobStore.blobBuilder(blobName)\n            .userMetadata(userMetadata)\n            .payload(payload)\n            .contentLength(length);\n      addContentMetadata(blobBuilder);\n      if (hashCode != null) {\n         blobBuilder.contentMD5(payload.getContentMetadata().getContentMD5AsHashCode());\n      }\n\n      String container = getContainerName();\n      try {\n         String etag = blobStore.putBlob(container, blobBuilder.build(), options);\n         assertThat(etag).isNotNull();\n\n         Blob blob = blobStore.getBlob(container, blobName);\n         assertThat(blob.getMetadata().getContentMetadata().getContentLength()).isEqualTo(length);\n\n         try (InputStream actual = blob.getPayload().openStream();\n              InputStream expected = expectedPayload.openStream()) {\n            while (length > 0) {\n               int bufferLength = (int) Math.min(1 << 20, length);\n               byte[] actualBuffer = new byte[bufferLength];\n               ByteStreams.readFully(actual, actualBuffer);\n               byte[] expectedBuffer = new byte[bufferLength];\n               ByteStreams.readFully(expected, expectedBuffer);\n               assertThat(actualBuffer).isEqualTo(expectedBuffer);\n               length -= bufferLength;\n            }\n         }\n         validateMetadata(blob.getMetadata(), container, blob.getMetadata().getName());\n         checkContentMetadata(blob);\n         checkUserMetadata(blob.getMetadata().getUserMetadata(), userMetadata);\n      } finally {\n         returnContainer(container);\n      }\n   }\n\n   protected long getMinimumMultipartBlobSize() {\n      throw new SkipException(\"multipart upload not supported\");\n   }\n\n   protected void checkContentMetadata(Blob blob) {\n      checkCacheControl(blob, \"max-age=3600\");\n      checkContentType(blob, \"text/csv\");\n      checkContentDisposition(blob, \"attachment; filename=photo.jpg\");\n      checkContentEncoding(blob, \"gzip\");\n      checkContentLanguage(blob, \"en\");\n   }\n\n   protected void addContentMetadata(PayloadBlobBuilder blobBuilder) {\n      blobBuilder.cacheControl(\"max-age=3600\");\n      blobBuilder.contentType(\"text/csv\");\n      blobBuilder.contentDisposition(\"attachment; filename=photo.jpg\");\n      blobBuilder.contentEncoding(\"gzip\");\n      blobBuilder.contentLanguage(\"en\");\n   }\n\n   protected void checkCacheControl(Blob blob, String cacheControl) {\n      assertThat(blob.getPayload().getContentMetadata().getCacheControl()).isEqualTo(cacheControl);\n      assertThat(blob.getMetadata().getContentMetadata().getCacheControl()).isEqualTo(cacheControl);\n   }\n\n   protected void checkContentType(Blob blob, String contentType) {\n      assert blob.getPayload().getContentMetadata().getContentType().startsWith(contentType) : blob.getPayload()\n               .getContentMetadata().getContentType();\n      assert blob.getMetadata().getContentMetadata().getContentType().startsWith(contentType) : blob.getMetadata()\n               .getContentMetadata().getContentType();\n   }\n\n   protected void checkContentDisposition(Blob blob, String contentDisposition) {\n      assert blob.getPayload().getContentMetadata().getContentDisposition().startsWith(contentDisposition) : blob\n               .getPayload().getContentMetadata().getContentDisposition();\n      assert blob.getMetadata().getContentMetadata().getContentDisposition().startsWith(contentDisposition) : blob\n               .getMetadata().getContentMetadata().getContentDisposition();\n\n   }\n\n   protected void checkContentEncoding(Blob blob, String contentEncoding) {\n      assert blob.getPayload().getContentMetadata().getContentEncoding().indexOf(contentEncoding) != -1 : blob\n               .getPayload().getContentMetadata().getContentEncoding();\n      assert blob.getMetadata().getContentMetadata().getContentEncoding().indexOf(contentEncoding) != -1 : blob\n               .getMetadata().getContentMetadata().getContentEncoding();\n   }\n\n   protected void checkContentLanguage(Blob blob, String contentLanguage) {\n      assert blob.getPayload().getContentMetadata().getContentLanguage().startsWith(contentLanguage) : blob\n               .getPayload().getContentMetadata().getContentLanguage();\n      assert blob.getMetadata().getContentMetadata().getContentLanguage().startsWith(contentLanguage) : blob\n               .getMetadata().getContentMetadata().getContentLanguage();\n   }\n\n   protected void checkMPUParts(Blob newBlob, List<MultipartPart> parts) {\n   }\n\n   protected static volatile Crypto crypto;\n   static {\n      try {\n         crypto = new JCECrypto();\n      } catch (NoSuchAlgorithmException e) {\n         Throwables.propagate(e);\n      } catch (CertificateException e) {\n         Throwables.propagate(e);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testMetadata() throws InterruptedException, IOException {\n      String name = \"hello\";\n      // NOTE all metadata in jclouds comes out as lowercase, in an effort to\n      // normalize the\n      // providers.\n      Blob blob = view.getBlobStore().blobBuilder(name).userMetadata(ImmutableMap.of(\"Adrian\", \"powderpuff\"))\n               .payload(TEST_STRING).contentType(MediaType.TEXT_PLAIN)\n               .contentMD5(md5().hashString(TEST_STRING, Charsets.UTF_8).asBytes())\n               .build();\n      String container = getContainerName();\n      try {\n         assertNull(view.getBlobStore().blobMetadata(container, \"powderpuff\"));\n\n         addBlobToContainer(container, blob);\n         Blob newObject = validateContent(container, name);\n\n         BlobMetadata metadata = newObject.getMetadata();\n\n         validateMetadata(metadata);\n         validateMetadata(metadata, container, name);\n         validateMetadata(view.getBlobStore().blobMetadata(container, name));\n\n         // write 2 items with the same name to ensure that provider doesn't\n         // accept dupes\n         blob.getMetadata().getUserMetadata().put(\"Adrian\", \"wonderpuff\");\n         blob.getMetadata().getUserMetadata().put(\"Adrian\", \"powderpuff\");\n\n         awaitConsistency();\n         addBlobToContainer(container, blob);\n         awaitConsistency();\n         validateMetadata(view.getBlobStore().blobMetadata(container, name));\n\n      } finally {\n         returnContainer(container);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testCopyBlobCopyMetadata() throws Exception {\n      BlobStore blobStore = view.getBlobStore();\n      String fromName = \"source\";\n      String toName = \"to\";\n      ByteSource payload = TestUtils.randomByteSource().slice(0, 1024);\n      Map<String, String> userMetadata = ImmutableMap.of(\"key1\", \"value1\", \"key2\", \"value2\");\n      PayloadBlobBuilder blobBuilder = blobStore\n            .blobBuilder(fromName)\n            .payload(payload)\n            .contentLength(payload.size());\n      addContentMetadata(blobBuilder);\n      blobBuilder.userMetadata(userMetadata);\n      Blob blob = blobBuilder.build();\n\n      String fromContainer = getContainerName();\n      String toContainer = getContainerName();\n      try {\n         blobStore.putBlob(fromContainer, blob);\n         blobStore.copyBlob(fromContainer, fromName, toContainer, toName, CopyOptions.NONE);\n         Blob toBlob = blobStore.getBlob(toContainer, toName);\n         InputStream is = null;\n         try {\n            is = toBlob.getPayload().openStream();\n            assertEquals(ByteStreams.toByteArray(is), payload.read());\n         } finally {\n            Closeables2.closeQuietly(is);\n         }\n         checkContentMetadata(toBlob);\n         checkUserMetadata(toBlob.getMetadata().getUserMetadata(), userMetadata);\n      } finally {\n         returnContainer(toContainer);\n         returnContainer(fromContainer);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testCopyBlobReplaceMetadata() throws Exception {\n      BlobStore blobStore = view.getBlobStore();\n      String fromName = \"source\";\n      String toName = \"to\";\n      ByteSource payload = TestUtils.randomByteSource().slice(0, 1024);\n      PayloadBlobBuilder blobBuilder = blobStore\n            .blobBuilder(fromName)\n            .userMetadata(ImmutableMap.of(\"key1\", \"value1\", \"key2\", \"value2\"))\n            .payload(payload)\n            .cacheControl(\"max-age=1800\")\n            .contentLength(payload.size())\n            .contentDisposition(\"attachment; filename=original.jpg\")\n            .contentEncoding(\"compress\")\n            .contentLanguage(\"fr\")\n            .contentType(\"audio/ogg\");\n      Blob blob = blobBuilder.build();\n\n      String fromContainer = getContainerName();\n      String toContainer = getContainerName();\n      try {\n         blobStore.putBlob(fromContainer, blob);\n         Map<String, String> userMetadata = ImmutableMap.of(\"key3\", \"value3\", \"key4\", \"value4\");\n         blobStore.copyBlob(fromContainer, fromName, toContainer, toName, CopyOptions.builder()\n               .contentMetadata(ContentMetadataBuilder.create()\n                     .cacheControl(\"max-age=3600\")\n                     .contentType(\"text/csv\")\n                     .contentDisposition(\"attachment; filename=photo.jpg\")\n                     .contentEncoding(\"gzip\")\n                     .contentLanguage(\"en\")\n                     .build())\n               .userMetadata(userMetadata)\n               .build());\n         Blob toBlob = blobStore.getBlob(toContainer, toName);\n         InputStream is = null;\n         try {\n            is = toBlob.getPayload().openStream();\n            assertEquals(ByteStreams.toByteArray(is), payload.read());\n         } finally {\n            Closeables2.closeQuietly(is);\n         }\n         checkContentMetadata(toBlob);\n         checkUserMetadata(toBlob.getMetadata().getUserMetadata(), userMetadata);\n      } finally {\n         returnContainer(toContainer);\n         returnContainer(fromContainer);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testCopyIfMatch() throws Exception {\n      BlobStore blobStore = view.getBlobStore();\n      String fromName = \"source\";\n      String toName = \"to\";\n      ByteSource payload = TestUtils.randomByteSource().slice(0, 1024);\n      Blob blob = blobStore\n            .blobBuilder(fromName)\n            .payload(payload)\n            .contentLength(payload.size())\n            .build();\n      String fromContainer = getContainerName();\n      String toContainer = getContainerName();\n      try {\n         String eTag = blobStore.putBlob(fromContainer, blob);\n         blobStore.copyBlob(fromContainer, fromName, toContainer, toName, CopyOptions.builder().ifMatch(eTag).build());\n         Blob toBlob = blobStore.getBlob(toContainer, toName);\n         InputStream is = null;\n         try {\n            is = toBlob.getPayload().openStream();\n            assertEquals(ByteStreams.toByteArray(is), payload.read());\n         } finally {\n            Closeables2.closeQuietly(is);\n         }\n      } finally {\n         returnContainer(toContainer);\n         returnContainer(fromContainer);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testCopyIfMatchNegative() throws Exception {\n      BlobStore blobStore = view.getBlobStore();\n      String fromName = \"source\";\n      String toName = \"to\";\n      ByteSource payload = TestUtils.randomByteSource().slice(0, 1024);\n      Blob blob = blobStore\n            .blobBuilder(fromName)\n            .payload(payload)\n            .contentLength(payload.size())\n            .build();\n      String fromContainer = getContainerName();\n      String toContainer = getContainerName();\n      try {\n         blobStore.putBlob(fromContainer, blob);\n         try {\n            blobStore.copyBlob(fromContainer, fromName, toContainer, toName, CopyOptions.builder().ifMatch(\"fake-etag\").build());\n            Fail.failBecauseExceptionWasNotThrown(HttpResponseException.class);\n         } catch (HttpResponseException hre) {\n            assertThat(hre.getResponse().getStatusCode()).isEqualTo(412);\n         }\n      } finally {\n         returnContainer(toContainer);\n         returnContainer(fromContainer);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testCopyIfNoneMatch() throws Exception {\n      BlobStore blobStore = view.getBlobStore();\n      String fromName = \"source\";\n      String toName = \"to\";\n      ByteSource payload = TestUtils.randomByteSource().slice(0, 1024);\n      Blob blob = blobStore\n            .blobBuilder(fromName)\n            .payload(payload)\n            .contentLength(payload.size())\n            .build();\n      String fromContainer = getContainerName();\n      String toContainer = getContainerName();\n      try {\n         blobStore.putBlob(fromContainer, blob);\n         blobStore.copyBlob(fromContainer, fromName, toContainer, toName, CopyOptions.builder().ifNoneMatch(\"fake-etag\").build());\n         Blob toBlob = blobStore.getBlob(toContainer, toName);\n         InputStream is = null;\n         try {\n            is = toBlob.getPayload().openStream();\n            assertEquals(ByteStreams.toByteArray(is), payload.read());\n         } finally {\n            Closeables2.closeQuietly(is);\n         }\n      } finally {\n         returnContainer(toContainer);\n         returnContainer(fromContainer);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testCopyIfNoneMatchNegative() throws Exception {\n      BlobStore blobStore = view.getBlobStore();\n      String fromName = \"source\";\n      String toName = \"to\";\n      ByteSource payload = TestUtils.randomByteSource().slice(0, 1024);\n      Blob blob = blobStore\n            .blobBuilder(fromName)\n            .payload(payload)\n            .contentLength(payload.size())\n            .build();\n      String fromContainer = getContainerName();\n      String toContainer = getContainerName();\n      try {\n         String eTag = blobStore.putBlob(fromContainer, blob);\n         try {\n            blobStore.copyBlob(fromContainer, fromName, toContainer, toName, CopyOptions.builder().ifNoneMatch(eTag).build());\n            Fail.failBecauseExceptionWasNotThrown(HttpResponseException.class);\n         } catch (HttpResponseException hre) {\n            assertThat(hre.getResponse().getStatusCode()).isEqualTo(412);\n         }\n      } finally {\n         returnContainer(toContainer);\n         returnContainer(fromContainer);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testCopyIfModifiedSince() throws Exception {\n      BlobStore blobStore = view.getBlobStore();\n      String fromName = \"source\";\n      String toName = \"to\";\n      ByteSource payload = TestUtils.randomByteSource().slice(0, 1024);\n      Blob blob = blobStore\n            .blobBuilder(fromName)\n            .payload(payload)\n            .contentLength(payload.size())\n            .build();\n      String fromContainer = getContainerName();\n      String toContainer = getContainerName();\n      try {\n         blobStore.putBlob(fromContainer, blob);\n         Date before = new Date(System.currentTimeMillis() - TimeUnit.HOURS.toMillis(1));\n         blobStore.copyBlob(fromContainer, fromName, toContainer, toName, CopyOptions.builder().ifModifiedSince(before).build());\n         Blob toBlob = blobStore.getBlob(toContainer, toName);\n         InputStream is = null;\n         try {\n            is = toBlob.getPayload().openStream();\n            assertEquals(ByteStreams.toByteArray(is), payload.read());\n         } finally {\n            Closeables2.closeQuietly(is);\n         }\n      } finally {\n         returnContainer(toContainer);\n         returnContainer(fromContainer);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testCopyIfModifiedSinceNegative() throws Exception {\n      BlobStore blobStore = view.getBlobStore();\n      String fromName = \"source\";\n      String toName = \"to\";\n      ByteSource payload = TestUtils.randomByteSource().slice(0, 1024);\n      Blob blob = blobStore\n            .blobBuilder(fromName)\n            .payload(payload)\n            .contentLength(payload.size())\n            .build();\n      String fromContainer = getContainerName();\n      String toContainer = getContainerName();\n      try {\n         blobStore.putBlob(fromContainer, blob);\n         // TODO: some problem with S3 and times in the future?\n         Date after = new Date(System.currentTimeMillis() + TimeUnit.HOURS.toMillis(1));\n         try {\n            blobStore.copyBlob(fromContainer, fromName, toContainer, toName, CopyOptions.builder().ifModifiedSince(after).build());\n            Fail.failBecauseExceptionWasNotThrown(HttpResponseException.class);\n         } catch (HttpResponseException hre) {\n            // most object stores return 412 but swift returns 304\n            assertThat(hre.getResponse().getStatusCode()).isIn(304, 412);\n         }\n      } finally {\n         returnContainer(toContainer);\n         returnContainer(fromContainer);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testCopyIfUnmodifiedSince() throws Exception {\n      BlobStore blobStore = view.getBlobStore();\n      String fromName = \"source\";\n      String toName = \"to\";\n      ByteSource payload = TestUtils.randomByteSource().slice(0, 1024);\n      Blob blob = blobStore\n            .blobBuilder(fromName)\n            .payload(payload)\n            .contentLength(payload.size())\n            .build();\n      String fromContainer = getContainerName();\n      String toContainer = getContainerName();\n      try {\n         blobStore.putBlob(fromContainer, blob);\n         Date after = new Date(System.currentTimeMillis() + TimeUnit.HOURS.toMillis(1));\n         blobStore.copyBlob(fromContainer, fromName, toContainer, toName, CopyOptions.builder().ifUnmodifiedSince(after).build());\n         Blob toBlob = blobStore.getBlob(toContainer, toName);\n         InputStream is = null;\n         try {\n            is = toBlob.getPayload().openStream();\n            assertEquals(ByteStreams.toByteArray(is), payload.read());\n         } finally {\n            Closeables2.closeQuietly(is);\n         }\n      } finally {\n         returnContainer(toContainer);\n         returnContainer(fromContainer);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testCopyIfUnmodifiedSinceNegative() throws Exception {\n      BlobStore blobStore = view.getBlobStore();\n      String fromName = \"source\";\n      String toName = \"to\";\n      ByteSource payload = TestUtils.randomByteSource().slice(0, 1024);\n      Blob blob = blobStore\n            .blobBuilder(fromName)\n            .payload(payload)\n            .contentLength(payload.size())\n            .build();\n      String fromContainer = getContainerName();\n      String toContainer = getContainerName();\n      try {\n         blobStore.putBlob(fromContainer, blob);\n         Date before = new Date(System.currentTimeMillis() - TimeUnit.HOURS.toMillis(1));\n         try {\n            blobStore.copyBlob(fromContainer, fromName, toContainer, toName, CopyOptions.builder().ifUnmodifiedSince(before).build());\n            Fail.failBecauseExceptionWasNotThrown(HttpResponseException.class);\n         } catch (HttpResponseException hre) {\n            assertThat(hre.getResponse().getStatusCode()).isEqualTo(412);\n         }\n      } finally {\n         returnContainer(toContainer);\n         returnContainer(fromContainer);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testMultipartUploadNoPartsAbort() throws Exception {\n      BlobStore blobStore = view.getBlobStore();\n      String container = getContainerName();\n      try {\n         String name = \"blob-name\";\n         Blob blob = blobStore.blobBuilder(name).build();\n         MultipartUpload mpu = blobStore.initiateMultipartUpload(container, blob.getMetadata(), new PutOptions());\n\n         List<MultipartPart> parts = blobStore.listMultipartUpload(mpu);\n         assertThat(parts).isEqualTo(ImmutableList.of());\n\n         blobStore.abortMultipartUpload(mpu);\n\n         assertThat(blobStore.list(container)).isEmpty();\n\n         blob = blobStore.getBlob(container, name);\n         assertThat(blob).isNull();\n      } finally {\n         returnContainer(container);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testMultipartUploadOnePartAbort() throws Exception {\n      BlobStore blobStore = view.getBlobStore();\n      String container = getContainerName();\n      try {\n         String name = \"blob-name\";\n         Blob blob = blobStore.blobBuilder(name).build();\n         MultipartUpload mpu = blobStore.initiateMultipartUpload(container, blob.getMetadata(), new PutOptions());\n\n         ByteSource byteSource = TestUtils.randomByteSource().slice(0, 1);\n         Payload payload = Payloads.newByteSourcePayload(byteSource);\n         payload.getContentMetadata().setContentLength(byteSource.size());\n         MultipartPart part = blobStore.uploadMultipartPart(mpu, 1, payload);\n\n         blobStore.abortMultipartUpload(mpu);\n\n         assertThat(blobStore.list(container)).isEmpty();\n\n         blob = blobStore.getBlob(container, name);\n         assertThat(blob).isNull();\n      } finally {\n         returnContainer(container);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testMultipartUploadSinglePart() throws Exception {\n      BlobStore blobStore = view.getBlobStore();\n      String container = getContainerName();\n      try {\n         String name = \"blob-name\";\n         PayloadBlobBuilder blobBuilder = blobStore.blobBuilder(name)\n               .userMetadata(ImmutableMap.of(\"key1\", \"value1\", \"key2\", \"value2\"))\n               // TODO: fake payload to add content metadata\n               .payload(new byte[0]);\n         addContentMetadata(blobBuilder);\n         Blob blob = blobBuilder.build();\n         MultipartUpload mpu = blobStore.initiateMultipartUpload(container, blob.getMetadata(), new PutOptions());\n\n         ByteSource byteSource = TestUtils.randomByteSource().slice(0, 1);\n         Payload payload = Payloads.newByteSourcePayload(byteSource);\n         payload.getContentMetadata().setContentLength(byteSource.size());\n         MultipartPart part = blobStore.uploadMultipartPart(mpu, 1, payload);\n\n         List<MultipartPart> parts = blobStore.listMultipartUpload(mpu);\n         assertThat(parts).hasSize(1);\n         assertThat(parts.get(0).partNumber()).isEqualTo(part.partNumber());\n         assertThat(parts.get(0).partSize()).isEqualTo(part.partSize());\n         assertThat(parts.get(0).partETag()).isEqualTo(part.partETag());\n         // not checking lastModified since B2, S3, and Swift do not return it from uploadMultipartPart\n\n         blobStore.completeMultipartUpload(mpu, ImmutableList.of(part));\n\n         Blob newBlob = blobStore.getBlob(container, name);\n         assertThat(newBlob).isNotNull();\n         assertThat(ByteStreams2.toByteArrayAndClose(newBlob.getPayload().openStream())).isEqualTo(byteSource.read());\n         checkContentMetadata(newBlob);\n         checkUserMetadata(newBlob.getMetadata().getUserMetadata(), blob.getMetadata().getUserMetadata());\n         checkMPUParts(newBlob, parts);\n      } finally {\n         returnContainer(container);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testMultipartUploadMultipleParts() throws Exception {\n      BlobStore blobStore = view.getBlobStore();\n      String container = getContainerName();\n      try {\n         String name = \"blob-name\";\n         PayloadBlobBuilder blobBuilder = blobStore.blobBuilder(name)\n               .userMetadata(ImmutableMap.of(\"key1\", \"value1\", \"key2\", \"value2\"))\n               // TODO: fake payload to add content metadata\n               .payload(new byte[0]);\n         addContentMetadata(blobBuilder);\n         Blob blob = blobBuilder.build();\n         MultipartUpload mpu = blobStore.initiateMultipartUpload(container, blob.getMetadata(), new PutOptions());\n\n         ByteSource byteSource = TestUtils.randomByteSource().slice(0, blobStore.getMinimumMultipartPartSize() + 1);\n         ByteSource byteSource1 = byteSource.slice(0, blobStore.getMinimumMultipartPartSize());\n         ByteSource byteSource2 = byteSource.slice(blobStore.getMinimumMultipartPartSize(), 1);\n         Payload payload1 = Payloads.newByteSourcePayload(byteSource1);\n         Payload payload2 = Payloads.newByteSourcePayload(byteSource2);\n         payload1.getContentMetadata().setContentLength(byteSource1.size());\n         payload2.getContentMetadata().setContentLength(byteSource2.size());\n         MultipartPart part1 = blobStore.uploadMultipartPart(mpu, 1, payload1);\n         MultipartPart part2 = blobStore.uploadMultipartPart(mpu, 2, payload2);\n\n         List<MultipartPart> parts = blobStore.listMultipartUpload(mpu);\n         assertThat(parts).hasSize(2);\n         assertThat(parts.get(0).partNumber()).isEqualTo(part1.partNumber());\n         assertThat(parts.get(0).partSize()).isEqualTo(part1.partSize());\n         assertThat(parts.get(0).partETag()).isEqualTo(part1.partETag());\n         assertThat(parts.get(1).partNumber()).isEqualTo(part2.partNumber());\n         assertThat(parts.get(1).partSize()).isEqualTo(part2.partSize());\n         assertThat(parts.get(1).partETag()).isEqualTo(part2.partETag());\n         // not checking lastModified since B2, S3, and Swift do not return it from uploadMultipartPart\n\n         blobStore.completeMultipartUpload(mpu, ImmutableList.of(part1, part2));\n\n         Blob newBlob = blobStore.getBlob(container, name);\n         assertThat(ByteStreams2.toByteArrayAndClose(newBlob.getPayload().openStream())).isEqualTo(byteSource.read());\n         checkContentMetadata(newBlob);\n         checkUserMetadata(newBlob.getMetadata().getUserMetadata(), blob.getMetadata().getUserMetadata());\n         checkMPUParts(newBlob, parts);\n      } finally {\n         returnContainer(container);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testListMultipartUploads() throws Exception {\n      BlobStore blobStore = view.getBlobStore();\n      String name = \"blob-name\";\n      PayloadBlobBuilder blobBuilder = blobStore.blobBuilder(name)\n            .userMetadata(ImmutableMap.of(\"key1\", \"value1\", \"key2\", \"value2\"))\n            // TODO: fake payload to add content metadata\n            .payload(new byte[0]);\n      addContentMetadata(blobBuilder);\n      Blob blob = blobBuilder.build();\n      MultipartUpload mpu = null;\n\n      String container = getContainerName();\n      try {\n         List<MultipartUpload> uploads = blobStore.listMultipartUploads(container);\n         assertThat(uploads).isEmpty();\n\n         mpu = blobStore.initiateMultipartUpload(container, blob.getMetadata(), new PutOptions());\n\n         // some providers like Azure cannot list an MPU until the first blob is uploaded\n         assertThat(uploads.size()).isBetween(0, 1);\n\n         // B2 requires at least two parts to call complete\n         ByteSource byteSource = TestUtils.randomByteSource().slice(0, blobStore.getMinimumMultipartPartSize() + 1);\n         ByteSource byteSource1 = byteSource.slice(0, blobStore.getMinimumMultipartPartSize());\n         ByteSource byteSource2 = byteSource.slice(blobStore.getMinimumMultipartPartSize(), 1);\n         Payload payload1 = Payloads.newByteSourcePayload(byteSource1);\n         Payload payload2 = Payloads.newByteSourcePayload(byteSource2);\n         payload1.getContentMetadata().setContentLength(byteSource1.size());\n         payload2.getContentMetadata().setContentLength(byteSource2.size());\n         MultipartPart part1 = blobStore.uploadMultipartPart(mpu, 1, payload1);\n         MultipartPart part2 = blobStore.uploadMultipartPart(mpu, 2, payload2);\n\n         uploads = blobStore.listMultipartUploads(container);\n         assertThat(uploads).hasSize(1);\n\n         blobStore.completeMultipartUpload(mpu, ImmutableList.of(part1, part2));\n         mpu = null;\n\n         uploads = blobStore.listMultipartUploads(container);\n         assertThat(uploads).isEmpty();\n\n         // cannot test abort since Azure does not have explicit support\n      } finally {\n         if (mpu != null) {\n            blobStore.abortMultipartUpload(mpu);\n         }\n         returnContainer(container);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" }, expectedExceptions = {KeyNotFoundException.class})\n   public void testCopy404BlobFail() throws Exception {\n      BlobStore blobStore = view.getBlobStore();\n      String container = getContainerName();\n      try {\n         blobStore.copyBlob(container, \"blob\", container, \"blob2\", CopyOptions.NONE);\n      } finally {\n         returnContainer(container);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" }, expectedExceptions = {KeyNotFoundException.class})\n   public void testCopy404BlobMetaFail() throws Exception {\n      BlobStore blobStore = view.getBlobStore();\n      String container = getContainerName();\n      try {\n         blobStore.copyBlob(container, \"blob\", container, \"blob2\",\n               CopyOptions.builder().userMetadata(ImmutableMap.of(\"x\", \"1\")).build());\n      } finally {\n         returnContainer(container);\n      }\n   }\n\n   protected void validateMetadata(BlobMetadata metadata) throws IOException {\n      assert metadata.getContentMetadata().getContentType().startsWith(\"text/plain\") : metadata.getContentMetadata()\n               .getContentType();\n      assertEquals(metadata.getContentMetadata().getContentLength(), Long.valueOf(TEST_STRING.length()));\n      assertEquals(metadata.getUserMetadata().get(\"adrian\"), \"powderpuff\");\n      checkMD5(metadata);\n   }\n\n   protected void checkMD5(BlobMetadata metadata) throws IOException {\n      assertEquals(metadata.getContentMetadata().getContentMD5(), md5().hashString(TEST_STRING, UTF_8).asBytes());\n   }\n\n   /** @return ByteSource containing a random length 0..length of random bytes. */\n   private static ByteSource createTestInput(int length) {\n      return TestUtils.randomByteSource().slice(0, new Random().nextInt(length));\n   }\n}\n"
  },
  {
    "path": "blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseBlobLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.integration.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.io.BaseEncoding.base16;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.Optional;\nimport org.testng.annotations.Parameters;\nimport org.testng.annotations.Test;\n\n/**\n * Tests integrated functionality of all PutObject commands.\n * <p/>\n * Each test uses a different container name, so it should be perfectly fine to run in parallel.\n */\n@Test(groups = { \"live\" })\npublic class BaseBlobLiveTest extends BaseBlobStoreIntegrationTest {\n\n   private static final String sysHttpStreamUrl = System.getProperty(\"jclouds.blobstore.httpstream.url\");\n   private static final String sysHttpStreamMD5 = System.getProperty(\"jclouds.blobstore.httpstream.md5\");\n\n   @Test\n   @Parameters( { \"jclouds.blobstore.httpstream.url\", \"jclouds.blobstore.httpstream.md5\" })\n   public void testCopyUrl(@Optional String httpStreamUrl, @Optional String httpStreamMD5) throws Exception {\n      httpStreamUrl = checkNotNull(httpStreamUrl != null ? httpStreamUrl : sysHttpStreamUrl, \"httpStreamUrl\");\n\n      httpStreamMD5 = checkNotNull(httpStreamMD5 != null ? httpStreamMD5 : sysHttpStreamMD5, \"httpStreamMd5\");\n\n      HttpResponse response = view.utils().http().invoke(HttpRequest.builder().method(\"GET\").endpoint(httpStreamUrl).build());\n      long length = response.getPayload().getContentMetadata().getContentLength();\n\n      String name = \"hello\";\n      byte[] md5 = base16().lowerCase().decode(httpStreamMD5);\n\n      Blob blob = view.getBlobStore().blobBuilder(name).payload(response.getPayload()).contentLength(length)\n               .contentMD5(md5).build();\n      String container = getContainerName();\n      try {\n         view.getBlobStore().putBlob(container, blob);\n         checkMD5(container, name, md5);\n      } finally {\n         returnContainer(container);\n      }\n   }\n\n   protected void checkMD5(String container, String name, byte[] md5) {\n      assertEquals(view.getBlobStore().blobMetadata(container, name).getContentMetadata().getContentMD5(), md5);\n   }\n\n}\n"
  },
  {
    "path": "blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseBlobSignerLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.integration.internal;\n\nimport static com.google.common.net.HttpHeaders.EXPECT;\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.jclouds.blobstore.options.GetOptions.Builder.range;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.fail;\n\nimport java.io.IOException;\nimport java.util.concurrent.TimeUnit;\n\nimport org.jclouds.blobstore.attr.ConsistencyModel;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.Test;\n\nimport com.google.common.util.concurrent.Uninterruptibles;\n\n/**\n * Tests integrated functionality of all signature commands.\n * <p/>\n * Each test uses a different container name, so it should be perfectly fine to run in parallel.\n */\n@Test(groups = {\"live\"})\npublic class BaseBlobSignerLiveTest extends BaseBlobStoreIntegrationTest {\n   protected int getSignedUrlTimeout() {\n      return 60;\n   }\n\n   @Test\n   public void testSignGetUrl() throws Exception {\n      String name = \"hello\";\n      String text = \"fooooooooooooooooooooooo\";\n\n      Blob blob = view.getBlobStore().blobBuilder(name).payload(text).contentType(\"text/plain\").build();\n      String container = getContainerName();\n      try {\n         view.getBlobStore().putBlob(container, blob);\n         assertConsistencyAwareContainerSize(container, 1);\n         HttpRequest request = view.getSigner().signGetBlob(container, name);\n         assertEquals(request.getFilters().size(), 0);\n         assertEquals(Strings2.toStringAndClose(view.utils().http().invoke(request).getPayload().openStream()), text);\n      } finally {\n         returnContainer(container);\n      }\n   }\n\n   @Test\n   public void testSignGetUrlOptions() throws Exception {\n      String name = \"hello\";\n      String text = \"fooooooooooooooooooooooo\";\n\n      Blob blob = view.getBlobStore().blobBuilder(name).payload(text).contentType(\"text/plain\").build();\n      String container = getContainerName();\n      try {\n         view.getBlobStore().putBlob(container, blob);\n         assertConsistencyAwareContainerSize(container, 1);\n         HttpRequest request = view.getSigner().signGetBlob(container, name, range(0, 1));\n         assertEquals(request.getFilters().size(), 0);\n         assertEquals(Strings2.toStringAndClose(view.utils().http().invoke(request).getPayload().openStream()), \"fo\");\n      } finally {\n         returnContainer(container);\n      }\n   }\n\n   @Test\n   public void testSignGetUrlWithTime() throws InterruptedException, IOException {\n      String name = \"hello\";\n      String text = \"fooooooooooooooooooooooo\";\n\n      Blob blob = view.getBlobStore().blobBuilder(name).payload(text).contentType(\"text/plain\").build();\n      String container = getContainerName();\n      try {\n         view.getBlobStore().putBlob(container, blob);\n         assertConsistencyAwareContainerSize(container, 1);\n         HttpRequest request = view.getSigner().signGetBlob(container, name, getSignedUrlTimeout());\n         assertEquals(request.getFilters().size(), 0);\n         assertEquals(Strings2.toStringAndClose(view.utils().http().invoke(request).getPayload().openStream()), text);\n      } finally {\n         returnContainer(container);\n      }\n   }\n\n   @Test(enabled = false)\n   public void testSignGetUrlWithTime(final long timeout) throws InterruptedException, IOException {\n      String name = \"hello\";\n      String text = \"fooooooooooooooooooooooo\";\n\n      Blob blob = view.getBlobStore().blobBuilder(name).payload(text).contentType(\"text/plain\").build();\n      String container = getContainerName();\n      try {\n         view.getBlobStore().putBlob(container, blob);\n         assertConsistencyAwareContainerSize(container, 1);\n         HttpRequest request = view.getSigner().signGetBlob(container, name, timeout);\n         assertEquals(request.getFilters().size(), 0);\n\n         try {\n            Strings2.toStringAndClose(view.utils().http().invoke(request).getPayload().openStream());\n            fail(\"Temporary URL did not expire as expected\");\n         } catch (AuthorizationException expected) {\n         }\n      } finally {\n         returnContainer(container);\n      }\n   }\n\n   @Test\n   public void testSignGetUrlWithTimeExpired() throws InterruptedException, IOException {\n       testSignGetUrlWithTime(-getSignedUrlTimeout());\n   }\n\n   @Test\n   public void testSignPutUrl() throws Exception {\n      String name = \"hello\";\n      String text = \"fooooooooooooooooooooooo\";\n\n      Blob blob = view.getBlobStore().blobBuilder(name).payload(text).contentType(\"image/png\").build();\n      String container = getContainerName();\n      try {\n         HttpRequest request = view.getSigner().signPutBlob(container, blob);\n         assertEquals(request.getFilters().size(), 0);\n         Strings2.toStringAndClose(view.utils().http().invoke(request).getPayload().openStream());\n\n         blob = view.getBlobStore().getBlob(container, name);\n         assertThat(blob.getMetadata().getContentMetadata().getContentType()).isEqualTo(\"image/png\");\n      } finally {\n         returnContainer(container);\n      }\n   }\n\n   @Test\n   public void testSignPutUrlWithTime() throws Exception {\n      String name = \"hello\";\n      String text = \"fooooooooooooooooooooooo\";\n\n      Blob blob = view.getBlobStore().blobBuilder(name).payload(text).contentType(\"text/plain\").build();\n      String container = getContainerName();\n      try {\n         HttpRequest request = view.getSigner().signPutBlob(container, blob, getSignedUrlTimeout());\n         assertEquals(request.getFilters().size(), 0);\n\n         // Strip Expect: 100-continue to make actual responses visible, since\n         // Java 7+ will throw a ProtocolException instead of setting the response code:\n         // http://www.docjar.com/html/api/sun/net/www/protocol/http/HttpURLConnection.java.html#1021\n         request = request.toBuilder().removeHeader(EXPECT).build();\n         Strings2.toStringAndClose(view.utils().http().invoke(request).getPayload().openStream());\n      } finally {\n         returnContainer(container);\n      }\n   }\n\n   @Test(enabled = false)\n   public void testSignPutUrlWithTime(final long timeout) throws InterruptedException, IOException {\n      String name = \"hello\";\n      String text = \"fooooooooooooooooooooooo\";\n\n      Blob blob = view.getBlobStore().blobBuilder(name).payload(text).contentType(\"text/plain\").build();\n      String container = getContainerName();\n      try {\n         HttpRequest request = view.getSigner().signPutBlob(container, blob, 0);\n         assertEquals(request.getFilters().size(), 0);\n\n         // Strip Expect: 100-continue to make actual responses visible, since\n         // Java 7+ will throw a ProtocolException instead of setting the response code:\n         // http://www.docjar.com/html/api/sun/net/www/protocol/http/HttpURLConnection.java.html#1021\n         request = request.toBuilder().removeHeader(EXPECT).build();\n\n         try {\n            Strings2.toStringAndClose(view.utils().http().invoke(request).getPayload().openStream());\n            fail(\"Temporary URL did not expire as expected\");\n         } catch (AuthorizationException expected) {\n         }\n      } finally {\n         returnContainer(container);\n      }\n   }\n\n   @Test\n   public void testSignPutUrlWithTimeExpired() throws Exception {\n       testSignPutUrlWithTime(-getSignedUrlTimeout());\n   }\n\n   protected void awaitConsistency() {\n      if (view.getConsistencyModel() == ConsistencyModel.EVENTUAL) {\n         Uninterruptibles.sleepUninterruptibly(AWAIT_CONSISTENCY_TIMEOUT_SECONDS, TimeUnit.SECONDS);\n      }\n   }\n}\n"
  },
  {
    "path": "blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseBlobStoreIntegrationTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.integration.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Throwables.propagateIfPossible;\nimport static org.jclouds.reflect.Reflection2.typeToken;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.util.Date;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.Set;\nimport java.util.concurrent.ArrayBlockingQueue;\nimport java.util.concurrent.BlockingQueue;\nimport java.util.concurrent.CancellationException;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicInteger;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport com.google.common.util.concurrent.Uninterruptibles;\nimport org.jclouds.apis.BaseViewLiveTest;\nimport org.jclouds.blobstore.BlobStoreContext;\nimport org.jclouds.blobstore.attr.ConsistencyModel;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.BlobMetadata;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.domain.StorageType;\nimport org.jclouds.domain.Location;\nimport org.jclouds.http.config.JavaUrlHttpCommandExecutorServiceModule;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.util.Strings2;\nimport org.testng.ITestContext;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.AfterSuite;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.BeforeSuite;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Throwables;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Sets;\nimport com.google.common.reflect.TypeToken;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.common.util.concurrent.MoreExecutors;\nimport com.google.inject.Module;\n\npublic class BaseBlobStoreIntegrationTest extends BaseViewLiveTest<BlobStoreContext> {\n\n   protected static final String LOCAL_ENCODING = System.getProperty(\"file.encoding\");\n   protected static final String XML_STRING_FORMAT = \"<apples><apple name=\\\"%s\\\"></apple> </apples>\";\n   protected static final String TEST_STRING = String.format(XML_STRING_FORMAT, \"apple\");\n\n   protected Map<String, String> fiveStrings = ImmutableMap.of(\"one\", String.format(XML_STRING_FORMAT, \"apple\"), \"two\",\n         String.format(XML_STRING_FORMAT, \"bear\"), \"three\", String.format(XML_STRING_FORMAT, \"candy\"), \"four\",\n         String.format(XML_STRING_FORMAT, \"dogma\"), \"five\", String.format(XML_STRING_FORMAT, \"emma\"));\n\n   protected Map<String, String> fiveStringsUnderPath = ImmutableMap.of(\"path/1\",\n         String.format(XML_STRING_FORMAT, \"apple\"), \"path/2\", String.format(XML_STRING_FORMAT, \"bear\"), \"path/3\",\n         String.format(XML_STRING_FORMAT, \"candy\"), \"path/4\", String.format(XML_STRING_FORMAT, \"dogma\"), \"path/5\",\n         String.format(XML_STRING_FORMAT, \"emma\"));\n\n   private static final Map<String, String> FILE_NESTED_STRINGS = ImmutableMap.of(\n           \"path/1/a\", String.format(XML_STRING_FORMAT, \"apple\"),\n           \"path/1/2/b\", String.format(XML_STRING_FORMAT, \"bear\"),\n           \"path/1/2/3/c\", String.format(XML_STRING_FORMAT, \"candy\"),\n           \"path/1/2/3/4/d\", String.format(XML_STRING_FORMAT, \"dog\"),\n           \"path/1/2/3/5/e\", String.format(XML_STRING_FORMAT, \"echo\")\n   );\n\n   public static long INCONSISTENCY_WINDOW = 10000;\n   protected static final AtomicInteger containerIndex = new AtomicInteger(0);\n\n   protected static volatile int containerCount = Integer.parseInt(System.getProperty(\"test.blobstore.container-count\",\n         \"10\"));\n   public static final String CONTAINER_PREFIX = (System.getProperty(\"user.name\") + \"-blobstore\").toLowerCase();\n   /**\n    * two test groups integration and live.\n    */\n   private static volatile BlockingQueue<String> containerNames = new ArrayBlockingQueue<String>(containerCount);\n\n   protected static final int AWAIT_CONSISTENCY_TIMEOUT_SECONDS = Integer.parseInt(System.getProperty(\n         \"test.blobstore.await-consistency-timeout-seconds\", \"10\"));\n\n   /**\n    * There are a lot of retries here mainly from experience running inside amazon EC2.\n    */\n   @BeforeSuite(groups = { \"integration\", \"live\" })\n   public void setUpResourcesForAllThreads(ITestContext testContext) throws Exception {\n      setupContext();\n      createContainersSharedByAllThreads(view, testContext);\n      view.close();\n      view = null;\n   }\n\n   @AfterSuite(groups = { \"integration\", \"live\" })\n   protected void destroyResources() throws Exception {\n      deleteEverything(view);\n\n      view.close();\n      view = null;\n   }\n\n   protected Iterable<Module> setupModules() {\n      return ImmutableSet.<Module> of(getLoggingModule(), createHttpModule());\n   }\n\n   protected ListeningExecutorService exec;\n\n   /**\n    * we are doing this at a class level, as the context.getBlobStore() object is going to be shared\n    * for all methods in the class. We don't want to do this for group, as some test classes may\n    * want to have a different implementation of context.getBlobStore(). For example, one class may\n    * want non-blocking i/o and another class google appengine.\n    */\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   public void setUpResourcesOnThisThread(ITestContext testContext) throws Exception {\n      exec = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());\n   }\n\n\n   @AfterClass(groups = { \"integration\", \"live\" })\n   @Override\n   protected void tearDownContext() {\n      if (exec != null) {\n         exec.shutdownNow();\n      }\n      view.close();\n   }\n\n   private static volatile boolean initialized = false;\n\n   protected void createContainersSharedByAllThreads(BlobStoreContext context, ITestContext testContext)\n         throws Exception {\n      while (!initialized) {\n         synchronized (BaseBlobStoreIntegrationTest.class) {\n            if (!initialized) {\n               deleteEverything(context);\n               for (; containerIndex.get() < containerCount; containerIndex.incrementAndGet()) {\n                  String containerName = CONTAINER_PREFIX + containerIndex;\n                  if (blackListContainers.contains(containerName)) {\n                     containerCount++;\n                  } else {\n                     try {\n                        createContainerAndEnsureEmpty(context, containerName, false);\n                        if (context.getBlobStore().containerExists(containerName))\n                           containerNames.put(containerName);\n                        else {\n                           deleteContainerOrWarnIfUnable(context, containerName);\n                           containerCount++;\n                        }\n                     } catch (Throwable e) {\n                        e.printStackTrace();\n                        // throw away the container and try again with the next\n                        // index\n                        deleteContainerOrWarnIfUnable(context, containerName);\n                        containerCount++;\n                     }\n                  }\n               }\n               awaitConsistency();\n               testContext.setAttribute(\"containerNames\", containerNames);\n               System.err.printf(\"*** containers to test: %s%n\", containerNames);\n               // careful not to keep too many files open\n               context.close();\n               initialized = true;\n            }\n         }\n      }\n   }\n\n   private static void deleteContainerOrWarnIfUnable(BlobStoreContext context, String containerName) {\n      try {\n         context.getBlobStore().deleteContainer(containerName);\n      } catch (Throwable ex) {\n         System.err.printf(\"unable to delete container %s, ignoring...%n\", containerName);\n         ex.printStackTrace();\n         blackListContainers.add(containerName);\n      }\n   }\n\n   private static final Set<String> blackListContainers = Sets.newHashSet();\n\n   /**\n    * Tries to delete all containers, runs up to two times\n    */\n   protected static void deleteEverything(final BlobStoreContext context) throws Exception {\n      try {\n         for (int i = 0; i < 2; i++) {\n            Iterable<? extends StorageMetadata> testContainers = Iterables.filter(context.getBlobStore().list(),\n                  new Predicate<StorageMetadata>() {\n                     public boolean apply(StorageMetadata input) {\n                        return (input.getType() == StorageType.CONTAINER || input.getType() == StorageType.FOLDER)\n                              && input.getName().startsWith(CONTAINER_PREFIX);\n                     }\n                  });\n            for (StorageMetadata container : testContainers) {\n               deleteContainerOrWarnIfUnable(context, container.getName());\n            }\n         } // try twice\n      } catch (CancellationException e) {\n         throw e;\n      }\n   }\n\n   /**\n    * two test groups integration and live.\n    */\n\n   public static boolean SANITY_CHECK_RETURNED_BUCKET_NAME = false;\n\n   /**\n    * Due to eventual consistency, container commands may not return correctly immediately. Hence,\n    * we will try up to the inconsistency window to see if the assertion completes.\n    */\n   protected static void assertConsistencyAware(BlobStoreContext context, Runnable assertion)\n         throws InterruptedException {\n      if (context.getConsistencyModel() == ConsistencyModel.STRICT) {\n         assertion.run();\n         return;\n      } else {\n\n         AssertionError error = null;\n         for (int i = 0; i < 30; i++) {\n            try {\n               assertion.run();\n               return;\n            } catch (AssertionError e) {\n               error = e;\n            }\n            Thread.sleep(INCONSISTENCY_WINDOW / 30);\n         }\n         if (error != null)\n            throw error;\n      }\n   }\n\n   protected void assertConsistencyAware(Runnable assertion) throws InterruptedException {\n      assertConsistencyAware(view, assertion);\n   }\n\n   protected void createContainerAndEnsureEmpty(BlobStoreContext context, final String containerName,\n         boolean ensureConsistent) throws InterruptedException {\n      context.getBlobStore().createContainerInLocation(null, containerName);\n      if (ensureConsistent) {\n         awaitConsistency();\n      }\n      context.getBlobStore().clearContainer(containerName);\n   }\n\n   protected void createContainerAndEnsureEmpty(String containerName) throws InterruptedException {\n      createContainerAndEnsureEmpty(view, containerName, true);\n   }\n\n   protected String addBlobToContainer(String sourceContainer, String key) {\n      return addBlobToContainer(sourceContainer, key, TEST_STRING, MediaType.TEXT_XML);\n   }\n\n   protected String addBlobToContainer(String sourceContainer, String key, String payload, String contentType) {\n      Blob sourceObject = view.getBlobStore().blobBuilder(key).payload(payload).contentType(contentType).build();\n      return addBlobToContainer(sourceContainer, sourceObject);\n   }\n\n   protected void add5BlobsUnderPathAnd5UnderRootToContainer(String sourceContainer) {\n      for (Entry<String, String> entry : Iterables.concat(fiveStrings.entrySet(), fiveStringsUnderPath.entrySet())) {\n         Blob sourceObject = view.getBlobStore().blobBuilder(entry.getKey()).payload(entry.getValue())\n               .contentType(\"text/xml\").build();\n         addBlobToContainer(sourceContainer, sourceObject);\n      }\n   }\n\n   protected void add5NestedBlobsToContainer(String sourceContainer) {\n      for (Entry<String, String> entry : FILE_NESTED_STRINGS.entrySet()) {\n         Blob sourceObject = view.getBlobStore().blobBuilder(entry.getKey()).payload(entry.getValue())\n                 .contentType(\"text/xml\").build();\n         addBlobToContainer(sourceContainer, sourceObject);\n      }\n   }\n\n   protected String addBlobToContainer(String sourceContainer, Blob object) {\n      return view.getBlobStore().putBlob(sourceContainer, object);\n   }\n\n   protected <T extends BlobMetadata> T validateMetadata(T md, String container, String name) {\n      assertEquals(md.getName(), name);\n      assertEquals(md.getContainer(), container);\n      assertEquals(md.getSize(), md.getContentMetadata().getContentLength());\n      return md;\n   }\n\n   protected Blob validateContent(String container, String name) throws InterruptedException {\n      assertConsistencyAwareContainerSize(container, 1);\n      Blob newObject = view.getBlobStore().getBlob(container, name);\n      assert newObject != null;\n      validateMetadata(newObject.getMetadata(), container, name);\n      try {\n         assertEquals(getContentAsStringOrNullAndClose(newObject), TEST_STRING);\n      } catch (IOException e) {\n         throw new RuntimeException(e);\n      }\n      return newObject;\n   }\n\n   protected void assertConsistencyAwareContainerSize(final String containerName, final int count)\n         throws InterruptedException {\n      assertConsistencyAware(new Runnable() {\n         public void run() {\n            try {\n               assert view.getBlobStore().countBlobs(containerName) == count : String.format(\n                     \"expected only %d values in %s: %s\", count, containerName, ImmutableSet.copyOf(Iterables\n                           .transform(view.getBlobStore().list(containerName),\n                                 new Function<StorageMetadata, String>() {\n\n                                    public String apply(StorageMetadata from) {\n                                       return from.getName();\n                                    }\n\n                                 })));\n            } catch (Exception e) {\n               Throwables.propagateIfPossible(e);\n            }\n         }\n      });\n   }\n\n   protected void assertConsistencyAwareBlobExists(final String containerName, final String name)\n         throws InterruptedException {\n      assertConsistencyAware(new Runnable() {\n         public void run() {\n            try {\n               assert view.getBlobStore().blobExists(containerName, name) : String.format(\n                     \"could not find %s in %s: %s\", name, containerName, ImmutableSet.copyOf(Iterables.transform(\n                           view.getBlobStore().list(containerName), new Function<StorageMetadata, String>() {\n\n                              public String apply(StorageMetadata from) {\n                                 return from.getName();\n                              }\n\n                           })));\n            } catch (Exception e) {\n               Throwables.propagateIfPossible(e);\n            }\n         }\n      });\n   }\n\n   protected void assertConsistencyAwareBlobDoesntExist(final String containerName, final String name)\n         throws InterruptedException {\n      assertConsistencyAware(new Runnable() {\n         public void run() {\n            try {\n               assert !view.getBlobStore().blobExists(containerName, name) : String.format(\"found %s in %s\", name,\n                     containerName);\n            } catch (Exception e) {\n               Throwables.propagateIfPossible(e);\n            }\n         }\n      });\n   }\n\n   protected void assertConsistencyAwareContainerExists(final String containerName) throws InterruptedException {\n      assertConsistencyAware(new Runnable() {\n         public void run() {\n            try {\n               assert view.getBlobStore().containerExists(containerName) : String.format(\"container %s doesn't exist\", containerName);\n            } catch (Exception e) {\n               Throwables.propagate(e);\n            }\n         }\n      });\n   }\n\n   protected void assertConsistencyAwareContainerInLocation(final String containerName, final Location loc)\n            throws InterruptedException {\n      assertConsistencyAware(new Runnable() {\n         public void run() {\n            try {\n               StorageMetadata container = Iterables.find(view.getBlobStore().list(), new Predicate<StorageMetadata>() {\n\n                  @Override\n                  public boolean apply(@Nullable StorageMetadata input) {\n                     return input.getName().equals(containerName);\n                  }\n\n               });\n               Location actualLoc = container.getLocation();\n\n               assert loc.equals(actualLoc) : String.format(\"blob %s, in location %s instead of %s\", containerName,\n                        actualLoc, loc);\n            } catch (Exception e) {\n               Throwables.propagate(e);\n            }\n         }\n      });\n   }\n\n   protected void assertConsistencyAwareBlobExpiryMetadata(final String containerName, final String blobName,\n            final Date expectedExpires) throws InterruptedException {\n      assertConsistencyAware(new Runnable() {\n         public void run() {\n            try {\n               Blob blob = view.getBlobStore().getBlob(containerName, blobName);\n               Date actualExpires = blob.getPayload().getContentMetadata().getExpires();\n               assert expectedExpires.equals(actualExpires) : \"expires=\" + actualExpires + \"; expected=\"\n                        + expectedExpires;\n            } catch (Exception e) {\n               Throwables.propagateIfPossible(e);\n            }\n         }\n      });\n   }\n\n   protected void assertConsistencyAwareBlobInLocation(final String containerName, final String blobName, final Location loc)\n            throws InterruptedException {\n      assertConsistencyAware(new Runnable() {\n         public void run() {\n            try {\n               Location actualLoc = view.getBlobStore().getBlob(containerName, blobName).getMetadata().getLocation();\n\n               assert loc.equals(actualLoc) : String.format(\n                     \"blob %s in %s, in location %s instead of %s\", blobName, containerName, actualLoc, loc);\n            } catch (Exception e) {\n               Throwables.propagate(e);\n            }\n         }\n      });\n   }\n\n   public String getContainerName() throws InterruptedException {\n      String containerName = containerNames.poll(30, TimeUnit.SECONDS);\n      assert containerName != null : \"unable to get a container for the test\";\n      createContainerAndEnsureEmpty(containerName);\n      return containerName;\n   }\n\n   /**\n    * requestor will create a container using the name returned from this. This method will take\n    * care not to exceed the maximum containers permitted by a provider by deleting an existing\n    * container first.\n    *\n    * @throws InterruptedException\n    */\n   public String getScratchContainerName() throws InterruptedException {\n      return allocateNewContainerName(getContainerName());\n   }\n\n   public void returnContainer(final String containerName) {\n      if (containerName != null) {\n         containerNames.add(containerName);\n         /*\n          * Ensure that any returned container name actually exists on the server. Return of a\n          * non-existent container introduces subtle testing bugs, where later unrelated tests will\n          * fail.\n          *\n          * NOTE: This sanity check should only be run for Stub-based Integration testing -- it will\n          * *substantially* slow down tests on a real server over a network.\n          */\n         if (SANITY_CHECK_RETURNED_BUCKET_NAME) {\n            if (!Iterables.any(view.getBlobStore().list(), new Predicate<StorageMetadata>() {\n               public boolean apply(StorageMetadata md) {\n                  return containerName.equals(md.getName());\n               }\n            })) {\n               throw new IllegalStateException(\"Test returned the name of a non-existent container: \" + containerName);\n            }\n         }\n      }\n   }\n\n   protected void assertNotExists(final String containerName) throws InterruptedException {\n      assertConsistencyAware(new Runnable() {\n         public void run() {\n            try {\n               assert !view.getBlobStore().containerExists(containerName) : \"container \" + containerName\n                     + \" still exists\";\n            } catch (Exception e) {\n               propagateIfPossible(e);\n            }\n         }\n      });\n   }\n\n   /**\n    * abandon old container name instead of waiting for the container to be created.\n    *\n    * @throws InterruptedException\n    */\n   public void destroyContainer(String scratchContainer) throws InterruptedException {\n      if (scratchContainer != null) {\n         recycleContainerAndAddToPool(scratchContainer);\n      }\n   }\n\n   protected void recycleContainerAndAddToPool(String scratchContainer) throws InterruptedException {\n      String newScratchContainer = recycleContainer(scratchContainer);\n      returnContainer(newScratchContainer);\n   }\n\n   protected String recycleContainer(final String container) throws InterruptedException {\n      String newScratchContainer = allocateNewContainerName(container);\n      createContainerAndEnsureEmpty(newScratchContainer);\n      return newScratchContainer;\n   }\n\n   private String allocateNewContainerName(final String container) {\n      exec.submit(new Runnable() {\n         public void run() {\n            deleteContainerOrWarnIfUnable(view, container);\n         }\n      });\n      String newScratchContainer = CONTAINER_PREFIX + containerIndex.incrementAndGet();\n      System.err.printf(\"*** allocated new container %s...%n\", newScratchContainer);\n      return newScratchContainer;\n   }\n\n   public static String getContentAsStringOrNullAndClose(Blob blob) throws IOException {\n      checkNotNull(blob, \"blob\");\n      checkNotNull(blob.getPayload(), \"blob.payload\");\n      return Strings2.toStringAndClose(blob.getPayload().openStream());\n   }\n   protected Module createHttpModule() {\n      return new JavaUrlHttpCommandExecutorServiceModule();\n   }\n\n   @Override\n   protected TypeToken<BlobStoreContext> viewType() {\n      return typeToken(BlobStoreContext.class);\n   }\n\n   protected void awaitConsistency() {\n      if (view.getConsistencyModel() == ConsistencyModel.EVENTUAL) {\n         Uninterruptibles.sleepUninterruptibly(AWAIT_CONSISTENCY_TIMEOUT_SECONDS, TimeUnit.SECONDS);\n      }\n   }\n}\n"
  },
  {
    "path": "blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseContainerIntegrationTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.integration.internal;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.base.Throwables.propagateIfPossible;\nimport static com.google.common.collect.Iterables.get;\nimport static com.google.common.hash.Hashing.md5;\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.jclouds.blobstore.options.ListContainerOptions.Builder.afterMarker;\nimport static org.jclouds.blobstore.options.ListContainerOptions.Builder.inDirectory;\nimport static org.jclouds.blobstore.options.ListContainerOptions.Builder.maxResults;\nimport static org.jclouds.utils.TestUtils.NO_INVOCATIONS;\nimport static org.jclouds.utils.TestUtils.SINGLE_NO_ARG_INVOCATION;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.Random;\nimport java.util.Set;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.TimeoutException;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.attr.ConsistencyModel;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.BlobMetadata;\nimport org.jclouds.blobstore.domain.ContainerAccess;\nimport org.jclouds.blobstore.domain.PageSet;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.options.ListContainerOptions;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.DataProvider;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.io.ByteSource;\nimport com.google.common.util.concurrent.Uninterruptibles;\n\npublic class BaseContainerIntegrationTest extends BaseBlobStoreIntegrationTest {\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void containerDoesntExist() {\n      Random random = new Random();\n      assert !view.getBlobStore().containerExists(\"forgetaboutit\" + random.nextInt(Integer.MAX_VALUE));\n      assert !view.getBlobStore().containerExists(\"cloudcachestorefunctionalintegrationtest-first\" +\n            random.nextInt(Integer.MAX_VALUE));\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   // TODO: the test name does not describe its behavior\n   public void testPutTwiceIsOkAndDoesntOverwrite() throws InterruptedException {\n      String containerName = getContainerName();\n      try {\n         view.getBlobStore().createContainerInLocation(null, containerName);\n\n         Blob blob = view.getBlobStore().blobBuilder(\"hello\").payload(TEST_STRING).build();\n         view.getBlobStore().putBlob(containerName, blob);\n\n         view.getBlobStore().createContainerInLocation(null, containerName);\n         awaitConsistency();\n         assertEquals(view.getBlobStore().countBlobs(containerName), 1);\n      } finally {\n         returnContainer(containerName);\n      }\n   }\n\n   @Test\n   public void testListMarkerAfterLastKey() throws Exception {\n      String key = \"hello\";\n      String containerName = getContainerName();\n      try {\n         addBlobToContainer(containerName,\n         // NOTE all metadata in jclouds comes out as lowercase, in an effort to\n         // normalize the providers.\n               view.getBlobStore().blobBuilder(key).userMetadata(ImmutableMap.of(\"Adrian\", \"powderpuff\"))\n                     .payload(TEST_STRING).contentType(MediaType.TEXT_PLAIN)\n                     .contentMD5(md5().hashString(TEST_STRING, UTF_8).asBytes())\n                     .build());\n         validateContent(containerName, key);\n         awaitConsistency();\n         PageSet<? extends StorageMetadata> container = view.getBlobStore().list(containerName, afterMarker(key));\n         assertThat(container).isEmpty();\n      } finally {\n         returnContainer(containerName);\n      }\n   }\n\n   @Test\n   public void testListContainerWithZeroMaxResults() throws Exception {\n      String key = \"hello\";\n      String containerName = getContainerName();\n      try {\n         addBlobToContainer(containerName,\n         // NOTE all metadata in jclouds comes out as lowercase, in an effort to\n         // normalize the providers.\n               view.getBlobStore().blobBuilder(key).userMetadata(ImmutableMap.of(\"Adrian\", \"powderpuff\"))\n                     .payload(TEST_STRING).contentType(MediaType.TEXT_PLAIN)\n                     .contentMD5(md5().hashString(TEST_STRING, UTF_8).asBytes())\n                     .build());\n         awaitConsistency();\n         validateContent(containerName, key);\n\n         PageSet<? extends StorageMetadata> container = view.getBlobStore().list(containerName, maxResults(0));\n         assertThat(container).isEmpty();\n      } finally {\n         returnContainer(containerName);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testWithDetails() throws InterruptedException, IOException {\n      String key = \"hello\";\n      String containerName = getContainerName();\n      try {\n         addBlobToContainer(containerName,\n         // NOTE all metadata in jclouds comes out as lowercase, in an effort to\n         // normalize the providers.\n               view.getBlobStore().blobBuilder(key).userMetadata(ImmutableMap.of(\"Adrian\", \"powderpuff\"))\n                     .payload(TEST_STRING).contentType(MediaType.TEXT_PLAIN)\n                     .contentMD5(md5().hashString(TEST_STRING, UTF_8).asBytes())\n                     .build());\n         awaitConsistency();\n         validateContent(containerName, key);\n\n         PageSet<? extends StorageMetadata> container = view.getBlobStore().list(containerName,\n               maxResults(1).withDetails());\n\n         BlobMetadata metadata = BlobMetadata.class.cast(get(container, 0));\n\n         assert metadata.getContentMetadata().getContentType().startsWith(\"text/plain\") : metadata.getContentMetadata()\n               .getContentType();\n         assertEquals(metadata.getContentMetadata().getContentLength(), Long.valueOf(TEST_STRING.length()));\n         assertEquals(metadata.getUserMetadata().get(\"adrian\"), \"powderpuff\");\n         checkMD5(metadata);\n      } finally {\n         returnContainer(containerName);\n      }\n   }\n\n   protected void checkMD5(BlobMetadata metadata) throws IOException {\n      assertEquals(metadata.getContentMetadata().getContentMD5(), md5().hashString(TEST_STRING, UTF_8).asBytes());\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testClearWhenContentsUnderPath() throws InterruptedException {\n      String containerName = getContainerName();\n      try {\n         add5BlobsUnderPathAnd5UnderRootToContainer(containerName);\n         view.getBlobStore().clearContainer(containerName);\n         assertConsistencyAwareContainerSize(containerName, 0);\n      } finally {\n         returnContainer(containerName);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testClearWithOptions() throws InterruptedException {\n      String containerName = getContainerName();\n      try {\n         ListContainerOptions options;\n\n         // Should wipe out all objects, as there are empty folders\n         // above\n         add5NestedBlobsToContainer(containerName);\n         options = new ListContainerOptions();\n         options.prefix(\"path/1/\");\n         options.recursive();\n         view.getBlobStore().clearContainer(containerName, options);\n         assertConsistencyAwareContainerSize(containerName, 0);\n\n         view.getBlobStore().clearContainer(containerName);\n         add5NestedBlobsToContainer(containerName);\n         options = new ListContainerOptions();\n         options.prefix(\"path/1/2/3\");\n         options.recursive();\n         view.getBlobStore().clearContainer(containerName, options);\n         assertConsistencyAwareBlobExists(containerName, \"path/1/a\");\n         assertConsistencyAwareBlobExists(containerName, \"path/1/2/b\");\n         assertConsistencyAwareBlobDoesntExist(containerName, \"path/1/2/3\");\n\n         view.getBlobStore().clearContainer(containerName);\n         add5NestedBlobsToContainer(containerName);\n         options = new ListContainerOptions();\n         options.prefix(\"path/1/2/3/4/\");\n         options.recursive();\n         view.getBlobStore().clearContainer(containerName, options);\n         assertConsistencyAwareBlobExists(containerName, \"path/1/a\");\n         assertConsistencyAwareBlobExists(containerName, \"path/1/2/b\");\n         assertConsistencyAwareBlobExists(containerName, \"path/1/2/3/5/e\");\n         assertConsistencyAwareBlobDoesntExist(containerName, \"path/1/2/3/4\");\n\n         // non-recursive, should not clear anything, as prefix does not match\n         view.getBlobStore().clearContainer(containerName);\n         add5NestedBlobsToContainer(containerName);\n         options = new ListContainerOptions();\n         options.prefix(\"path/1/2/3\");\n         view.getBlobStore().clearContainer(containerName, options);\n         assertConsistencyAwareBlobExists(containerName, \"path/1/a\");\n         assertConsistencyAwareBlobExists(containerName, \"path/1/2/b\");\n         assertConsistencyAwareBlobExists(containerName, \"path/1/2/3/c\");\n         assertConsistencyAwareBlobExists(containerName, \"path/1/2/3/5/e\");\n\n\n         // non-recursive, should only clear path/1/2/3/c\n         view.getBlobStore().clearContainer(containerName);\n         add5NestedBlobsToContainer(containerName);\n         options = new ListContainerOptions();\n         options.prefix(\"path/1/2/3/\");\n         view.getBlobStore().clearContainer(containerName, options);\n         assertConsistencyAwareBlobExists(containerName, \"path/1/a\");\n         assertConsistencyAwareBlobExists(containerName, \"path/1/2/b\");\n         assertConsistencyAwareBlobExists(containerName, \"path/1/2/3/4/d\");\n         assertConsistencyAwareBlobDoesntExist(containerName, \"path/1/2/3/c\");\n\n         // non-recursive, should only clear path/1/2/3/c\n         view.getBlobStore().clearContainer(containerName);\n         add5NestedBlobsToContainer(containerName);\n         options = new ListContainerOptions();\n         options.prefix(\"path/1/2/3/c\");\n         view.getBlobStore().clearContainer(containerName, options);\n         assertConsistencyAwareBlobExists(containerName, \"path/1/a\");\n         assertConsistencyAwareBlobExists(containerName, \"path/1/2/b\");\n         assertConsistencyAwareBlobExists(containerName, \"path/1/2/3/4/d\");\n         assertConsistencyAwareBlobDoesntExist(containerName, \"path/1/2/3/c\");\n      } finally {\n         returnContainer(containerName);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testListContainerMarker() throws InterruptedException {\n      String containerName = getContainerName();\n      try {\n         addAlphabetUnderRoot(containerName);\n\n         PageSet<? extends StorageMetadata> container = view.getBlobStore().list(containerName, maxResults(1));\n\n         assert container.getNextMarker() != null;\n         assertEquals(container.size(), 1);\n         String marker = container.getNextMarker();\n\n         container = view.getBlobStore().list(containerName, afterMarker(marker));\n         assertEquals(container.getNextMarker(), null);\n         assert container.size() == 25 : String.format(\"size should have been 25, but was %d: %s\", container.size(),\n               container);\n         assert container.getNextMarker() == null;\n      } finally {\n         returnContainer(containerName);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testListRootUsesDelimiter() throws InterruptedException {\n      String containerName = getContainerName();\n      try {\n         String prefix = \"rootdelimiter\";\n         addTenObjectsUnderPrefix(containerName, prefix);\n         add15UnderRoot(containerName);\n         awaitConsistency();\n         PageSet<? extends StorageMetadata> container = view.getBlobStore().list(containerName);\n         assert container.getNextMarker() == null;\n         assertEquals(container.size(), 16);\n      } finally {\n         returnContainer(containerName);\n      }\n\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testDirectory() throws InterruptedException {\n      String containerName = getContainerName();\n      try {\n         String directory = \"directory\";\n\n         assert !view.getBlobStore().directoryExists(containerName, directory);\n\n         view.getBlobStore().createDirectory(containerName, directory);\n\n         assert view.getBlobStore().directoryExists(containerName, directory);\n         PageSet<? extends StorageMetadata> container = view.getBlobStore().list(containerName);\n         // we should have only the directory under root\n         assert container.getNextMarker() == null;\n         assert container.size() == 1 : container;\n\n         container = view.getBlobStore().list(containerName, inDirectory(directory));\n\n         // we should have nothing in the directory\n         assert container.getNextMarker() == null;\n         assert container.size() == 0 : container;\n\n         addTenObjectsUnderPrefix(containerName, directory);\n\n         awaitConsistency();\n\n         container = view.getBlobStore().list(containerName);\n         // we should get back the subdir entry and the directory marker\n         assert container.getNextMarker() == null;\n         assertThat(container).hasSize(2);\n\n         container = view.getBlobStore().list(containerName, inDirectory(directory));\n         // we should have only the 10 items under the directory\n         assert container.getNextMarker() == null;\n         assert container.size() == 10 : container;\n\n         // try 2 level deep directory\n         assert !view.getBlobStore().directoryExists(containerName, directory + \"/\" + directory);\n         view.getBlobStore().createDirectory(containerName, directory + \"/\" + directory);\n\n         awaitConsistency();\n\n         assert view.getBlobStore().directoryExists(containerName, directory + \"/\" + directory);\n\n         view.getBlobStore().clearContainer(containerName, inDirectory(directory));\n         awaitConsistency();\n\n         assert view.getBlobStore().directoryExists(containerName, directory);\n         assertThat(view.getBlobStore().directoryExists(containerName, directory + \"/\" + directory)).isFalse();\n\n         // should have only the 2 level-deep directory above\n         container = view.getBlobStore().list(containerName, inDirectory(directory));\n         assert container.getNextMarker() == null;\n         assertThat(container).hasSize(0);\n\n         view.getBlobStore().createDirectory(containerName, directory + \"/\" + directory);\n\n         awaitConsistency();\n\n         container = view.getBlobStore().list(containerName, inDirectory(directory).recursive());\n         assert container.getNextMarker() == null;\n         assert container.size() == 1 : container;\n\n         view.getBlobStore().clearContainer(containerName, inDirectory(directory).recursive());\n\n         // should no longer have the 2 level-deep directory above\n         container = view.getBlobStore().list(containerName, inDirectory(directory));\n         assert container.getNextMarker() == null;\n         assert container.size() == 0 : container;\n\n         container = view.getBlobStore().list(containerName);\n         // should only have the directory\n         assert container.getNextMarker() == null;\n         assert container.size() == 1 : container;\n         view.getBlobStore().deleteDirectory(containerName, directory);\n\n         container = view.getBlobStore().list(containerName);\n         // now should be completely empty\n         assert container.getNextMarker() == null;\n         assert container.size() == 0 : container;\n      } finally {\n         returnContainer(containerName);\n      }\n\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testListContainerPrefix() throws InterruptedException {\n      String containerName = getContainerName();\n      try {\n         String prefix = \"containerprefix\";\n         addTenObjectsUnderPrefix(containerName, prefix);\n         add15UnderRoot(containerName);\n         awaitConsistency();\n         PageSet<? extends StorageMetadata> container = view.getBlobStore().list(\n               containerName, new ListContainerOptions().prefix(prefix + \"/\").delimiter(\"/\"));\n         assert container.getNextMarker() == null;\n         assertEquals(container.size(), 10);\n      } finally {\n         returnContainer(containerName);\n      }\n\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testListContainerMaxResults() throws InterruptedException {\n      String containerName = getContainerName();\n      try {\n         addAlphabetUnderRoot(containerName);\n\n         PageSet<? extends StorageMetadata> container;\n         ListContainerOptions options = maxResults(10);\n\n         container = view.getBlobStore().list(containerName, options);\n         assertThat(container).hasSize(10);\n         assertThat(container.getNextMarker()).isNotNull();\n\n         container = view.getBlobStore().list(containerName, options.afterMarker(container.getNextMarker()));\n         assertThat(container).hasSize(10);\n         assertThat(container.getNextMarker()).isNotNull();\n\n         container = view.getBlobStore().list(containerName, options.afterMarker(container.getNextMarker()));\n         assertThat(container).hasSize(6);\n         assertThat(container.getNextMarker()).isNull();\n      } finally {\n         returnContainer(containerName);\n      }\n   }\n\n   @Test(dataProvider = \"ignoreOnWindows\", groups = { \"integration\", \"live\" })\n   public void testDelimiter() throws Exception {\n      String containerName = getContainerName();\n      try {\n         for (String blobName : new String[] { \"asdf\", \"boo\" + File.separator + \"bar\", \"boo\" + File.separator\n               + \"baz\"  + File.separator + \"xyzzy\", \"cquux\" + File.separator + \"thud\", \"cquux\" + File.separator\n               + \"bla\" }) {\n            Blob blob = view.getBlobStore().blobBuilder(blobName).payload(TEST_STRING).build();\n            addBlobToContainer(containerName, blob);\n         }\n\n         // test root directory without marker\n         PageSet<? extends StorageMetadata> pageSet = view.getBlobStore().list(containerName);\n         assertThat(pageSet).hasSize(3);\n         assertThat(pageSet.getNextMarker()).isNull();\n\n         // list root directory with marker\n         ListContainerOptions options = new ListContainerOptions().maxResults(1);\n         pageSet = view.getBlobStore().list(containerName, options);\n         assertThat(pageSet).hasSize(1);\n         assertThat(pageSet.iterator().next().getName()).isEqualTo(\"asdf\");\n         assertThat(pageSet.getNextMarker()).isNotNull();\n\n         options.afterMarker(pageSet.getNextMarker());\n         pageSet = view.getBlobStore().list(containerName, options);\n         assertThat(pageSet).hasSize(1);\n         assertThat(pageSet.iterator().next().getName()).isEqualTo(\"boo/\");\n         assertThat(pageSet.getNextMarker()).isNotNull();\n\n         options.afterMarker(pageSet.getNextMarker());\n         pageSet = view.getBlobStore().list(containerName, options);\n         assertThat(pageSet).hasSize(1);\n         assertThat(pageSet.iterator().next().getName()).isEqualTo(\"cquux/\");\n         assertThat(pageSet.getNextMarker()).isNull();\n\n         // list child directory with marker\n         options = new ListContainerOptions().inDirectory(\"boo\").maxResults(1);\n         pageSet = view.getBlobStore().list(containerName, options);\n         assertThat(pageSet).hasSize(1);\n         assertThat(pageSet.iterator().next().getName()).isEqualTo(\"boo/bar\");\n         assertThat(pageSet.getNextMarker()).isNotNull();\n\n         options.afterMarker(pageSet.getNextMarker());\n         pageSet = view.getBlobStore().list(containerName, options);\n         assertThat(pageSet).hasSize(1);\n         assertThat(pageSet.iterator().next().getName()).isEqualTo(\"boo/baz/\");\n         assertThat(pageSet.getNextMarker()).isNull();\n\n         // list child directory without marker\n         options = new ListContainerOptions().inDirectory(\"boo\").maxResults(2);\n         pageSet = view.getBlobStore().list(containerName, options);\n         assertThat(pageSet).hasSize(2);\n         Iterator<? extends StorageMetadata> it = pageSet.iterator();\n         assertThat(it.next().getName()).isEqualTo(\"boo/bar\");\n         assertThat(it.next().getName()).isEqualTo(\"boo/baz/\");\n         assertThat(pageSet.getNextMarker()).isNull();\n      } finally {\n         returnContainer(containerName);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void containerExists() throws InterruptedException {\n      String containerName = getContainerName();\n      try {\n         assert view.getBlobStore().containerExists(containerName);\n      } finally {\n         returnContainer(containerName);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void deleteContainerWithContents() throws InterruptedException {\n      String containerName = getContainerName();\n      try {\n         addBlobToContainer(containerName, \"test\");\n         view.getBlobStore().deleteContainer(containerName);\n         awaitConsistency();\n         assertNotExists(containerName);\n      } finally {\n         recycleContainerAndAddToPool(containerName);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void deleteContainerWithoutContents() throws InterruptedException {\n      final String containerName = getContainerName();\n      try {\n         view.getBlobStore().deleteContainer(containerName);\n         awaitConsistency();\n         assertNotExists(containerName);\n      } finally {\n         // this container is now deleted, so we can't reuse it directly\n         recycleContainerAndAddToPool(containerName);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void deleteContainerIfEmptyWithContents() throws InterruptedException {\n      String containerName = getContainerName();\n      try {\n         addBlobToContainer(containerName, \"test\");\n         awaitConsistency();\n         assertFalse(view.getBlobStore().deleteContainerIfEmpty(containerName));\n         awaitConsistency();\n         assertTrue(view.getBlobStore().containerExists(containerName));\n      } finally {\n         recycleContainerAndAddToPool(containerName);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void deleteContainerIfEmptyWithoutContents() throws InterruptedException {\n      final String containerName = getContainerName();\n      try {\n         assertTrue(view.getBlobStore().deleteContainerIfEmpty(containerName));\n         awaitConsistency();\n         assertNotExists(containerName);\n         // verify that true is returned even if the container does not exist\n         assertTrue(view.getBlobStore().deleteContainerIfEmpty(containerName));\n      } finally {\n         // this container is now deleted, so we can't reuse it directly\n         recycleContainerAndAddToPool(containerName);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testListContainer() throws InterruptedException, ExecutionException, TimeoutException {\n      String containerName = getContainerName();\n      try {\n         add15UnderRoot(containerName);\n         awaitConsistency();\n         Set<? extends StorageMetadata> container = view.getBlobStore().list(containerName);\n         assertEquals(container.size(), 15);\n      } finally {\n         returnContainer(containerName);\n      }\n\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testListContainerGetBlobSize() throws Exception {\n      String containerName = getContainerName();\n      try {\n         ByteSource byteSource = ByteSource.wrap(new byte[42]);\n\n         for (int i = 0; i < 2; i++) {\n            view.getBlobStore().putBlob(containerName, view.getBlobStore()\n                  .blobBuilder(i + \"\")\n                  .payload(byteSource)\n                  .contentLength(byteSource.size())\n                  .build());\n         }\n\n         PageSet<? extends StorageMetadata> container = view.getBlobStore().list(containerName);\n\n         for (StorageMetadata metadata : container) {\n            assertEquals(metadata.getSize(), Long.valueOf(byteSource.size()));\n         }\n      } finally {\n         returnContainer(containerName);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testSetContainerAccess() throws Exception {\n      BlobStore blobStore = view.getBlobStore();\n      String containerName = getContainerName();\n      try {\n         assertThat(blobStore.getContainerAccess(containerName)).isEqualTo(ContainerAccess.PRIVATE);\n\n         blobStore.setContainerAccess(containerName, ContainerAccess.PUBLIC_READ);\n         assertThat(blobStore.getContainerAccess(containerName)).isEqualTo(ContainerAccess.PUBLIC_READ);\n\n         String blobName = \"blob\";\n         blobStore.putBlob(containerName, blobStore.blobBuilder(blobName).payload(\"\").build());\n\n         // test that blob is anonymously readable\n         HttpRequest request = view.getSigner().signGetBlob(containerName, blobName).toBuilder()\n                .replaceQueryParams(ImmutableMap.<String, String>of()).build();\n         HttpResponse response = view.utils().http().invoke(request);\n         assertThat(response.getStatusCode()).isEqualTo(200);\n\n         blobStore.setContainerAccess(containerName, ContainerAccess.PRIVATE);\n         assertThat(blobStore.getContainerAccess(containerName)).isEqualTo(ContainerAccess.PRIVATE);\n      } finally {\n         recycleContainerAndAddToPool(containerName);\n      }\n   }\n\n   @Test(groups = {\"integration\", \"live\"})\n   public void testContainerListWithPrefix() throws InterruptedException {\n      final String containerName = getContainerName();\n      BlobStore blobStore = view.getBlobStore();\n      String prefix = \"blob\";\n      try {\n         blobStore.putBlob(containerName, blobStore.blobBuilder(prefix).payload(\"\").build());\n         blobStore.putBlob(containerName, blobStore.blobBuilder(prefix + \"foo\").payload(\"\").build());\n         blobStore.putBlob(containerName, blobStore.blobBuilder(prefix + \"bar\").payload(\"\").build());\n         blobStore.putBlob(containerName, blobStore.blobBuilder(\"foo\").payload(\"\").build());\n         checkEqualNames(ImmutableSet.of(prefix, prefix + \"foo\", prefix + \"bar\"),\n               blobStore.list(containerName, ListContainerOptions.Builder.prefix(prefix)));\n      }\n      finally {\n         returnContainer(containerName);\n      }\n   }\n\n   @Test(groups = {\"integration\", \"live\"})\n   public void testContainerListWithDetails() throws InterruptedException {\n      final String containerName = getContainerName();\n      BlobStore blobStore = view.getBlobStore();\n      String prefix = \"testContainerListWithDetails/\";\n      try {\n         blobStore.putBlob(containerName, blobStore.blobBuilder(prefix + \"foo/bar\").payload(\"\").build());\n         blobStore.putBlob(containerName, blobStore.blobBuilder(prefix + \"car\").payload(\"\").build());\n         checkEqualNames(\n             ImmutableSet.of(prefix + \"foo/\", prefix + \"car\"),\n             blobStore.list(containerName, ListContainerOptions.Builder.prefix(prefix).delimiter(\"/\"))\n         );\n         checkEqualNames(\n             ImmutableSet.of(prefix + \"foo/\", prefix + \"car\"),\n             blobStore.list(containerName, ListContainerOptions.Builder.prefix(prefix).delimiter(\"/\").withDetails())\n         );\n      }\n      finally {\n         returnContainer(containerName);\n      }\n   }\n\n   @Test(groups = {\"integration\", \"live\"})\n   public void testDelimiterList() throws InterruptedException {\n      final String containerName = getContainerName();\n      BlobStore blobStore = view.getBlobStore();\n      String payload = \"foo\";\n      try {\n         blobStore.putBlob(containerName, blobStore.blobBuilder(\"test-foo-foo\").payload(payload).build());\n         blobStore.putBlob(containerName, blobStore.blobBuilder(\"test-bar-foo\").payload(payload).build());\n         blobStore.putBlob(containerName, blobStore.blobBuilder(\"foo\").payload(payload).build());\n         // NOTE: the test does not work if we use a file separator character (\"/\" or \"\\\"), as the file system blob\n         // store will create directories when putting such a blob. When listing results, these directories will also\n         // show up in the result set.\n         checkEqualNames(ImmutableSet.of(\"foo\", \"test-\"), blobStore.list(containerName,\n               ListContainerOptions.Builder.delimiter(\"-\")));\n         checkEqualNames(ImmutableSet.of(\"test-foo-foo\", \"test-bar-foo\", \"foo\"),\n               blobStore.list(containerName, ListContainerOptions.Builder.delimiter(\".\")));\n\n         blobStore.putBlob(containerName, blobStore.blobBuilder(\"bar\").payload(payload).build());\n         blobStore.putBlob(containerName, blobStore.blobBuilder(\"bazar\").payload(payload).build());\n         checkEqualNames(ImmutableSet.of(\"bar\", \"baza\"), blobStore.list(containerName,\n               ListContainerOptions.Builder.delimiter(\"a\").prefix(\"ba\")));\n      } finally {\n         returnContainer(containerName);\n      }\n   }\n\n   /** Test that listing with a marker prefix matches the first key with that prefix. */\n   @Test\n   public void testListMarkerPrefix() throws Exception {\n      BlobStore blobStore = view.getBlobStore();\n      final String container = getContainerName();\n      try {\n         blobStore.createContainerInLocation(null, container);\n         blobStore.putBlob(container, blobStore.blobBuilder(\"a/a\").payload(\"\").build());\n         blobStore.putBlob(container, blobStore.blobBuilder(\"b/b\").payload(\"\").build());\n         ListContainerOptions options = new ListContainerOptions().afterMarker(\"b/\").recursive();\n         PageSet<? extends StorageMetadata> res = blobStore.list(container, options);\n         assertThat(res).hasSize(1);\n         assertThat(res.iterator().next().getName()).isEqualTo(\"b/b\");\n      } finally {\n         returnContainer(container);\n      }\n   }\n\n   /** Test that listing with an empty string for prefix and delimiter returns all of the keys. */\n   @Test(groups = {\"integration\", \"live\"})\n   public void testListEmptyPrefixDelimiter() throws Exception {\n      final String container = getContainerName();\n      BlobStore blobStore = view.getBlobStore();\n      blobStore.createContainerInLocation(null, container);\n\n      try {\n         ImmutableList<String> blobs = ImmutableList.of(\"a\", \"b\", \"c\");\n         for (String blob : blobs) {\n            blobStore.putBlob(container, blobStore.blobBuilder(blob).payload(\"\").build());\n         }\n         ListContainerOptions options = ListContainerOptions.Builder.delimiter(\"\")\n                 .prefix(\"\").afterMarker(\"\");\n         PageSet<? extends StorageMetadata> rs = blobStore.list(container, options);\n         ImmutableList.Builder<String> builder = ImmutableList.builder();\n         for (StorageMetadata sm : rs) {\n            builder.add(sm.getName());\n         }\n         assertThat(builder.build()).containsExactlyElementsOf(blobs);\n      } finally {\n         returnContainer(container);\n      }\n   }\n\n   @DataProvider\n   public Object[][] getBlobsToEscape() {\n      ImmutableSet<String> testNames = ImmutableSet.of(\"%20\", \"%20 \", \" %20\", \" \", \"%\", \"%%\");\n      Object[][] result = new Object[1][1];\n      result[0][0] = testNames;\n      return result;\n   }\n\n   @Test(dataProvider = \"getBlobsToEscape\", groups = {\"integration\", \"live\"})\n   public void testBlobNameEscaping(Set<String> blobNames) throws InterruptedException {\n      final String containerName = getContainerName();\n      BlobStore blobStore = view.getBlobStore();\n      try {\n         for (String name : blobNames) {\n            Blob blob = blobStore.blobBuilder(name).payload(ByteSource.wrap(\"test\".getBytes())).contentLength(4)\n                  .build();\n            blobStore.putBlob(containerName, blob);\n         }\n         checkEqualNames(blobNames, blobStore.list(containerName));\n      } finally {\n         returnContainer(containerName);\n      }\n   }\n\n   private void checkEqualNames(Set<String> expectedSet, PageSet<? extends StorageMetadata> results) {\n      Set<String> names = new HashSet<String>();\n      for (StorageMetadata sm : results) {\n         names.add(sm.getName());\n      }\n\n      assertThat(names).containsOnlyElementsOf(expectedSet);\n   }\n\n   protected void addAlphabetUnderRoot(String containerName) throws InterruptedException {\n      for (char letter = 'a'; letter <= 'z'; letter++) {\n         view.getBlobStore().putBlob(containerName,\n               view.getBlobStore().blobBuilder(letter + \"\").payload(letter + \"content\").build());\n      }\n      assertContainerSize(containerName, 26);\n\n   }\n\n   protected void assertContainerSize(final String containerName, final int size) throws InterruptedException {\n      assertConsistencyAware(new Runnable() {\n         public void run() {\n            try {\n               assertEquals(view.getBlobStore().countBlobs(containerName), size);\n            } catch (Exception e) {\n               propagateIfPossible(e);\n            }\n         }\n      });\n   }\n\n   protected void add15UnderRoot(String containerName) throws InterruptedException {\n      for (int i = 0; i < 15; i++) {\n         view.getBlobStore().putBlob(containerName,\n               view.getBlobStore().blobBuilder(i + \"\").payload(i + \"content\").build());\n      }\n   }\n\n   protected void addTenObjectsUnderPrefix(String containerName, String prefix) throws InterruptedException {\n      for (int i = 0; i < 10; i++) {\n         view.getBlobStore().putBlob(containerName,\n               view.getBlobStore().blobBuilder(prefix + \"/\" + i).payload(i + \"content\").build());\n      }\n   }\n\n   protected void awaitConsistency() {\n      if (view.getConsistencyModel() == ConsistencyModel.EVENTUAL) {\n         Uninterruptibles.sleepUninterruptibly(AWAIT_CONSISTENCY_TIMEOUT_SECONDS, TimeUnit.SECONDS);\n      }\n   }\n\n   @DataProvider\n   public Object[][] ignoreOnWindows() {\n      return isWindowsOs() ? NO_INVOCATIONS\n            : SINGLE_NO_ARG_INVOCATION;\n   }\n\n   private static boolean isWindowsOs() {\n      return System.getProperty(\"os.name\", \"\").toLowerCase().contains(\"windows\");\n   }\n}\n"
  },
  {
    "path": "blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseContainerLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.integration.internal;\n\nimport static java.util.concurrent.TimeUnit.SECONDS;\n\nimport static org.jclouds.blobstore.options.CreateContainerOptions.Builder.publicRead;\nimport static org.jclouds.util.Predicates2.retry;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.net.MalformedURLException;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.logging.Logger;\n\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.domain.BlobMetadata;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.domain.Location;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.predicates.SocketOpen;\nimport org.jclouds.util.Strings2;\nimport org.testng.SkipException;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Predicates;\nimport com.google.common.base.Strings;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Lists;\nimport com.google.common.net.HostAndPort;\n\npublic class BaseContainerLiveTest extends BaseBlobStoreIntegrationTest {\n\n   private Location defaultLocation;\n\n   @Test(groups = \"live\")\n   public void testPublicAccess() throws InterruptedException, MalformedURLException, IOException {\n      final String containerName = getScratchContainerName();\n      try {\n         view.getBlobStore().createContainerInLocation(null, containerName, publicRead());\n         assertConsistencyAwareContainerExists(containerName);\n\n         defaultLocation = Iterables.find(view.getBlobStore().list(), new Predicate<StorageMetadata>() {\n\n            @Override\n            public boolean apply(@Nullable StorageMetadata input) {\n               return input.getName().equals(containerName);\n            }\n\n         }).getLocation();\n\n         view.getBlobStore().putBlob(containerName,\n                  view.getBlobStore().blobBuilder(\"hello\").payload(TEST_STRING).build());\n         assertConsistencyAwareContainerSize(containerName, 1);\n\n         BlobMetadata metadata = view.getBlobStore().blobMetadata(containerName, \"hello\");\n\n         assertNotNull(metadata.getPublicUri(), metadata.toString());\n\n         SocketOpen socketOpen = context.utils().injector().getInstance(SocketOpen.class);\n         Predicate<HostAndPort> socketTester = retry(socketOpen, 60, 5, SECONDS);\n         int port = metadata.getPublicUri().getPort();\n         HostAndPort hostAndPort = HostAndPort.fromParts(metadata.getPublicUri().getHost(), port != -1 ? port : 80);\n         assertTrue(socketTester.apply(hostAndPort), metadata.getPublicUri().toString());\n\n         assertEquals(Strings2.toStringAndClose(view.utils().http().get(metadata.getPublicUri())), TEST_STRING);\n\n      } finally {\n         // this container is now public, so we can't reuse it directly\n         recycleContainerAndAddToPool(containerName);\n      }\n   }\n\n   static Location findNonDefaultLocationOrSkip(BlobStore blobStore, Location defaultLocation) {\n      Iterable<? extends Location> iterable = Iterables.filter(blobStore.listAssignableLocations(),\n               Predicates.not(Predicates.equalTo(defaultLocation)));\n      List<? extends Location> locs = Lists.newArrayList(iterable);\n      if (locs.size() == 0)\n         throw new SkipException(\"No non-default location found in \" + locs);\n      // try to use a diverse location\n      Collections.shuffle(locs);\n      return locs.get(0);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testPublicAccess\")\n   public void testPublicAccessInNonDefaultLocation() throws InterruptedException, MalformedURLException, IOException {\n      Location nonDefault = findNonDefaultLocationOrSkip(view.getBlobStore(), defaultLocation);\n\n      String payload = \"my data\";\n      runCreateContainerInLocation(payload, nonDefault);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testPublicAccess\")\n   public void testPublicAccessInNonDefaultLocationWithBigBlob() throws InterruptedException, MalformedURLException,\n            IOException {\n      Location nonDefault = findNonDefaultLocationOrSkip(view.getBlobStore(), defaultLocation);\n      String payload = Strings.repeat(\"a\", 1024 * 1024); // 1MB\n      runCreateContainerInLocation(payload, nonDefault);\n   }\n\n   private void runCreateContainerInLocation(String payload, Location nonDefault) throws InterruptedException,\n            IOException {\n      String blobName = \"hello\";\n      BlobStore blobStore = view.getBlobStore();\n      final String containerName = getScratchContainerName();\n      try {\n         Logger.getAnonymousLogger().info(\n                  String.format(\"creating public container %s in location %s\", containerName, nonDefault.getId()));\n         blobStore.createContainerInLocation(nonDefault, containerName, publicRead());\n         assertConsistencyAwareContainerExists(containerName);\n         assertConsistencyAwareContainerInLocation(containerName, nonDefault);\n\n         blobStore.putBlob(containerName, blobStore.blobBuilder(blobName).payload(payload).build());\n\n         assertConsistencyAwareContainerSize(containerName, 1);\n\n         BlobMetadata metadata = view.getBlobStore().blobMetadata(containerName, blobName);\n         assertEquals(Strings2.toStringAndClose(view.utils().http().get(metadata.getPublicUri())), payload);\n\n         assertConsistencyAwareBlobInLocation(containerName, blobName, nonDefault);\n\n      } finally {\n         // this container is now public, so we can't reuse it directly\n         recycleContainerAndAddToPool(containerName);\n      }\n   }\n}\n"
  },
  {
    "path": "blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseServiceIntegrationTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.integration.internal;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\n\nimport org.jclouds.blobstore.domain.PageSet;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.domain.internal.MutableStorageMetadataImpl;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationScope;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\n\npublic class BaseServiceIntegrationTest extends BaseBlobStoreIntegrationTest {\n\n   @SuppressWarnings(\"CollectionIncompatibleType\")\n   @Test(groups = { \"integration\", \"live\" })\n   void containerDoesntExist() {\n      Set<? extends StorageMetadata> list = view.getBlobStore().list();\n      assert !list.contains(new MutableStorageMetadataImpl());\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testAllLocations() throws InterruptedException {\n      for (final Location location : view.getBlobStore().listAssignableLocations()) {\n         final String containerName = getScratchContainerName();\n         try {\n            System.err.printf(\" >> creating container in location %s%n\", location);\n            view.getBlobStore().createContainerInLocation(location, containerName);\n            System.err.printf(\" << call complete.. checking%n\");\n\n            assertConsistencyAware(new Runnable() {\n\n               @Override\n               public void run() {\n                  PageSet<? extends StorageMetadata> list = view.getBlobStore().list();\n                  assert Iterables.any(list, new Predicate<StorageMetadata>() {\n                     public boolean apply(StorageMetadata md) {\n                        return containerName.equals(md.getName()) && locationEquals(location, md.getLocation());\n                     }\n                  }) : String.format(\"container %s/%s not found in list %s\", location, containerName, list);\n                  assertTrue(view.getBlobStore().containerExists(containerName), containerName);\n               }\n\n            });\n         } finally {\n            recycleContainerAndAddToPool(containerName);\n         }\n      }\n   }\n\n   protected Set<String> getIso3166Codes() {\n      return ImmutableSet.<String> of();\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testGetAssignableLocations() throws Exception {\n      for (Location location : view.getBlobStore().listAssignableLocations()) {\n         System.err.printf(\"location %s%n\", location);\n         assert location.getId() != null : location;\n         assert location != location.getParent() : location;\n         assert location.getScope() != null : location;\n         switch (location.getScope()) {\n            case PROVIDER:\n               assertProvider(location);\n               break;\n            case REGION:\n               assertProvider(location.getParent());\n               assert location.getIso3166Codes().size() == 0\n                        || location.getParent().getIso3166Codes().containsAll(location.getIso3166Codes()) : location\n                        + \" ||\" + location.getParent();\n               break;\n            case ZONE:\n               Location provider = location.getParent().getParent();\n               // zone can be a direct descendant of provider\n               if (provider == null)\n                  provider = location.getParent();\n               assertProvider(provider);\n               assert location.getIso3166Codes().size() == 0\n                        || location.getParent().getIso3166Codes().containsAll(location.getIso3166Codes()) : location\n                        + \" ||\" + location.getParent();\n               break;\n            case HOST:\n               Location provider2 = location.getParent().getParent().getParent();\n               // zone can be a direct descendant of provider\n               if (provider2 == null)\n                  provider2 = location.getParent().getParent();\n               assertProvider(provider2);\n               break;\n         }\n      }\n   }\n\n   void assertProvider(Location provider) {\n      assertEquals(provider.getScope(), LocationScope.PROVIDER);\n      assertEquals(provider.getParent(), null);\n      assertEquals(provider.getIso3166Codes(), getIso3166Codes());\n   }\n\n   protected boolean locationEquals(Location location1, Location location2) {\n      return location1.equals(location2);\n   }\n}\n"
  },
  {
    "path": "blobstore/src/test/java/org/jclouds/blobstore/internal/BaseBlobSignerExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.internal;\n\nimport static org.jclouds.blobstore.options.GetOptions.Builder.range;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Date;\nimport java.util.Map;\nimport java.util.Properties;\n\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.options.GetOptions;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rest.internal.BaseRestApiExpectTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.hash.HashCode;\nimport com.google.inject.Module;\n\npublic abstract class BaseBlobSignerExpectTest extends BaseRestApiExpectTest<BlobStore> {\n\n   /**\n    * define the requests and responses needed to initialize the blobstore. For\n    * example, you may need to add in discovery requests needed (ex. KeyStone in\n    */\n   protected Map<HttpRequest, HttpResponse> init() {\n      return ImmutableMap.<HttpRequest, HttpResponse> of();\n   }\n\n   protected String container = \"container\";\n   protected String name = \"name\";\n   protected String text = \"fooooooooooooooooooooooo\";\n   protected GetOptions options = range(0, 1);\n\n   @Test\n   public void testSignGetBlob() {\n      BlobStore getBlob = requestsSendResponses(init());\n      assertEquals(getBlob.getContext().getSigner().signGetBlob(container, name), getBlob());\n   }\n\n   protected abstract HttpRequest getBlob();\n\n   @Test\n   public void testSignGetBlobWithTime() {\n      BlobStore getBlobWithTime = requestsSendResponses(init());\n      HttpRequest compare = getBlobWithTime();\n      assertEquals(getBlobWithTime.getContext().getSigner().signGetBlob(container, name, 3L /* seconds */),\n            compare);\n   }\n\n   protected abstract HttpRequest getBlobWithTime();\n\n   @Test\n   public void testSignGetBlobWithOptions() {\n      BlobStore getBlobWithOptions = requestsSendResponses(init());\n      assertEquals(getBlobWithOptions.getContext().getSigner().signGetBlob(container, name, options),\n            getBlobWithOptions());\n   }\n\n   protected abstract HttpRequest getBlobWithOptions();\n\n   @Test\n   public void testSignPutBlob() throws Exception {\n      HashCode hashCode = HashCode.fromBytes(new byte[16]);\n      BlobStore signPutBlob = requestsSendResponses(init());\n      Blob blob = signPutBlob.blobBuilder(\"name\").forSigning().contentLength(2L).contentMD5(hashCode)\n            .contentType(\"text/plain\").expires(new Date(1000)).build();\n      HttpRequest compare = putBlob();\n      compare.setPayload(blob.getPayload());\n      assertEquals(signPutBlob.getContext().getSigner().signPutBlob(container, blob), compare);\n   }\n\n   protected abstract HttpRequest putBlob();\n\n   @Test\n   public void testSignPutBlobWithTime() throws Exception {\n      BlobStore signPutBloblWithTime = requestsSendResponses(init());\n      Blob blob = signPutBloblWithTime.blobBuilder(name).payload(text).contentType(\"text/plain\").build();\n      HttpRequest compare = putBlobWithTime();\n      compare.setPayload(blob.getPayload());\n      assertEquals(signPutBloblWithTime.getContext().getSigner().signPutBlob(container, blob, 3L /* seconds */),\n            compare);\n   }\n\n   protected abstract HttpRequest putBlobWithTime();\n\n   protected abstract HttpRequest removeBlob();\n\n   @Override\n   public BlobStore createClient(Function<HttpRequest, HttpResponse> fn, Module module, Properties props) {\n      return createInjector(fn, module, props).getInstance(BlobStore.class);\n   }\n}\n"
  },
  {
    "path": "blobstore/src/test/java/org/jclouds/blobstore/internal/BaseBlobStoreApiMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.internal;\n\nimport static org.jclouds.reflect.Reflection2.typeToken;\n\nimport org.jclouds.View;\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.apis.internal.BaseApiMetadataTest;\nimport org.jclouds.blobstore.BlobStoreContext;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.reflect.TypeToken;\n\n@Test(groups = \"unit\")\npublic abstract class BaseBlobStoreApiMetadataTest extends BaseApiMetadataTest {\n\n   public BaseBlobStoreApiMetadataTest(ApiMetadata toTest) {\n      super(toTest, ImmutableSet.<TypeToken<? extends View>>of(typeToken(BlobStoreContext.class)));\n    }\n\n}\n"
  },
  {
    "path": "blobstore/src/test/java/org/jclouds/blobstore/options/GetOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.options;\n\nimport static org.jclouds.blobstore.options.GetOptions.Builder.ifETagDoesntMatch;\nimport static org.jclouds.blobstore.options.GetOptions.Builder.ifETagMatches;\nimport static org.jclouds.blobstore.options.GetOptions.Builder.ifModifiedSince;\nimport static org.jclouds.blobstore.options.GetOptions.Builder.ifUnmodifiedSince;\nimport static org.jclouds.blobstore.options.GetOptions.Builder.range;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\n\nimport java.util.Date;\n\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tests possible uses of GetOptions and GetOptions.Builder.*\n */\n@Test(groups = \"unit\")\npublic class GetOptionsTest {\n\n   private String etag;\n   private Date now;\n\n   @BeforeTest\n   void setUp() {\n      now = new Date();\n      etag = \"yrdy\";\n   }\n\n   @Test\n   public void testIfModifiedSince() {\n      GetOptions options = new GetOptions();\n      options.ifModifiedSince(now);\n      assertEquals(options.getIfModifiedSince(), now);\n   }\n\n   @Test\n   public void testNullIfModifiedSince() {\n      GetOptions options = new GetOptions();\n      assertNull(options.getIfModifiedSince());\n   }\n\n   @Test\n   public void testIfModifiedSinceStatic() {\n      GetOptions options = ifModifiedSince(now);\n      assertEquals(options.getIfModifiedSince(), now);\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testIfModifiedSinceNPE() {\n      ifModifiedSince(null);\n   }\n\n   @Test\n   public void testIfUnmodifiedSince() {\n      GetOptions options = new GetOptions();\n      options.ifUnmodifiedSince(now);\n      isNowExpected(options);\n   }\n\n   @Test\n   public void testNullIfUnmodifiedSince() {\n      GetOptions options = new GetOptions();\n      assertNull(options.getIfUnmodifiedSince());\n   }\n\n   @Test\n   public void testIfUnmodifiedSinceStatic() {\n      GetOptions options = ifUnmodifiedSince(now);\n      isNowExpected(options);\n   }\n\n   private void isNowExpected(GetOptions options) {\n      assertEquals(options.getIfUnmodifiedSince(), now);\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testIfUnmodifiedSinceNPE() {\n      ifUnmodifiedSince(null);\n   }\n\n   public void testModifiedSinceAndRange() {\n      GetOptions options = new GetOptions();\n      options.ifModifiedSince(now);\n      options.range(0, 1024);\n      assertEquals(options.getIfModifiedSince(), now);\n      bytes1to1024(options);\n   }\n\n   @Test\n   public void testRange() {\n      GetOptions options = new GetOptions();\n      options.range(0, 1024);\n      bytes1to1024(options);\n   }\n\n   private void bytes1to1024(GetOptions options) {\n      assertEquals(options.getRanges().get(0), \"0-1024\");\n   }\n\n   @Test\n   public void testRangeZeroToFive() {\n      GetOptions options = new GetOptions();\n      options.range(0, 5);\n      assertEquals(options.getRanges().get(0), \"0-5\");\n   }\n\n   @Test\n   public void testRangeZeroToFiveAnd10through100() {\n      GetOptions options = new GetOptions();\n      options.range(0, 5).range(10, 100);\n      assertEquals(options.getRanges(), ImmutableList.of(\"0-5\", \"10-100\"));\n   }\n\n\n   @Test\n   public void testRangeStartAt() {\n      GetOptions options = new GetOptions();\n      options.startAt(5);\n      assertEquals(options.getRanges(), ImmutableList.of(\"5-\"));\n   }\n\n   @Test\n   public void testRangeTail() {\n      GetOptions options = new GetOptions();\n      options.tail(5);\n      assertEquals(options.getRanges(), ImmutableList.of(\"-5\"));\n   }\n\n   @Test\n   public void testNoRange() {\n      GetOptions options = new GetOptions();\n      assertEquals(options.getRanges().size(), 0);\n   }\n\n   @Test\n   public void testRangeStatic() {\n      GetOptions options = range(0, 1024);\n      bytes1to1024(options);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testRangeNegative1() {\n      range(-1, 0);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testRangeNegative2() {\n      range(0, -1);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testRangeNegative() {\n      range(-1, -1);\n   }\n\n   @Test\n   public void testIfETagMatches() {\n      GetOptions options = new GetOptions();\n      options.ifETagMatches(etag);\n      assertEquals(etag, options.getIfMatch());\n   }\n\n   @Test\n   public void testNullIfETagMatches() {\n      GetOptions options = new GetOptions();\n      assertNull(options.getIfMatch());\n   }\n\n   @Test\n   public void testIfETagMatchesStatic() {\n      GetOptions options = ifETagMatches(etag);\n      assertEquals(etag, options.getIfMatch());\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testIfETagMatchesNPE() {\n      ifETagMatches(null);\n   }\n\n   @Test\n   public void testIfETagDoesntMatch() {\n      GetOptions options = new GetOptions();\n      options.ifETagDoesntMatch(etag);\n      assertEquals(etag, options.getIfNoneMatch());\n   }\n\n   @Test\n   public void testNullIfETagDoesntMatch() {\n      GetOptions options = new GetOptions();\n      assertNull(options.getIfNoneMatch());\n   }\n\n   @Test\n   public void testIfETagDoesntMatchStatic() {\n      GetOptions options = ifETagDoesntMatch(etag);\n      assertEquals(etag, options.getIfNoneMatch());\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testIfETagDoesntMatchNPE() {\n      ifETagDoesntMatch(null);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testIfUnmodifiedAfterModified() {\n      ifModifiedSince(now).ifUnmodifiedSince(now);\n\n   }\n\n   public void testIfUnmodifiedAfterETagMatches() {\n      ifETagMatches(etag).ifUnmodifiedSince(now);\n\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testIfUnmodifiedAfterETagDoesntMatch() {\n      ifETagDoesntMatch(etag).ifUnmodifiedSince(now);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testIfModifiedAfterUnmodified() {\n      ifUnmodifiedSince(now).ifModifiedSince(now);\n\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testIfModifiedAfterETagMatches() {\n      ifETagMatches(etag).ifModifiedSince(now);\n\n   }\n\n   public void testIfModifiedAfterETagDoesntMatch() {\n      ifETagDoesntMatch(etag).ifModifiedSince(now);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testETagMatchesAfterIfModified() {\n      ifModifiedSince(now).ifETagMatches(etag);\n\n   }\n\n   public void testETagMatchesAfterIfUnmodified() {\n      ifUnmodifiedSince(now).ifETagMatches(etag);\n\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testETagMatchesAfterETagDoesntMatch() {\n      ifETagDoesntMatch(etag).ifETagMatches(etag);\n   }\n\n   public void testETagDoesntMatchAfterIfModified() {\n      ifModifiedSince(now).ifETagDoesntMatch(etag);\n\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testETagDoesntMatchAfterIfUnmodified() {\n      ifUnmodifiedSince(now).ifETagDoesntMatch(etag);\n\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testETagDoesntMatchAfterETagMatches() {\n      ifETagMatches(etag).ifETagDoesntMatch(etag);\n   }\n\n}\n"
  },
  {
    "path": "blobstore/src/test/java/org/jclouds/blobstore/options/ListOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.options;\n\nimport static org.jclouds.blobstore.options.ListContainerOptions.Builder.afterMarker;\nimport static org.jclouds.blobstore.options.ListContainerOptions.Builder.inDirectory;\nimport static org.jclouds.blobstore.options.ListContainerOptions.Builder.maxResults;\nimport static org.jclouds.blobstore.options.ListContainerOptions.Builder.recursive;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport org.testng.annotations.Test;\n\n/**\n * Tests possible uses of ListOptions and ListOptions.Builder.*\n */\npublic class ListOptionsTest {\n   @Test\n   public void testRecursive() {\n      ListContainerOptions options = new ListContainerOptions();\n      options.recursive();\n      assertTrue(options.isRecursive());\n   }\n\n   @Test\n   public void testRecursiveStatic() {\n      ListContainerOptions options = recursive();\n      assertTrue(options.isRecursive());\n   }\n\n   @Test\n   public void testPath() {\n      ListContainerOptions options = new ListContainerOptions();\n      options.inDirectory(\"test\");\n      assertEquals(options.getDir(), \"test\");\n   }\n\n   @Test\n   public void testDelimiter() {\n      ListContainerOptions options = new ListContainerOptions();\n      options.delimiter(\"-\");\n      assertEquals(options.getDelimiter(), \"-\");\n   }\n\n   @Test\n   public void testPathStatic() {\n      ListContainerOptions options = inDirectory(\"test\");\n      assertEquals(options.getDir(), \"test\");\n   }\n\n   @Test\n   public void testTwoOptions() {\n      ListContainerOptions options = new ListContainerOptions();\n      options.inDirectory(\"test\").maxResults(1);\n      assertEquals(options.getDir(), \"test\");\n      assertEquals(options.getMaxResults(), Integer.valueOf(1));\n\n   }\n\n   @Test\n   public void testNullPath() {\n      ListContainerOptions options = new ListContainerOptions();\n      assertEquals(options.getDir(), null);\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testPathNPE() {\n      inDirectory(null);\n   }\n\n   @Test\n   public void testMarker() {\n      ListContainerOptions options = new ListContainerOptions();\n      options.afterMarker(\"test\");\n      assertEquals(options.getMarker(), \"test\");\n\n   }\n\n   @Test\n   public void testNullMarker() {\n      ListContainerOptions options = new ListContainerOptions();\n      assertEquals(options.getMarker(), null);\n   }\n\n   @Test\n   public void testMarkerStatic() {\n      ListContainerOptions options = afterMarker(\"test\");\n      assertEquals(options.getMarker(), \"test\");\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testMarkerNPE() {\n      afterMarker(null);\n   }\n\n   @Test\n   public void testMaxResults() {\n      ListContainerOptions options = new ListContainerOptions();\n      options.maxResults(1000);\n      assertEquals(options.getMaxResults(), Integer.valueOf(1000));\n   }\n\n   @Test\n   public void testNullMaxResults() {\n      ListContainerOptions options = new ListContainerOptions();\n      assertEquals(options.getMaxResults(), null);\n   }\n\n   @Test\n   public void testMaxResultsStatic() {\n      ListContainerOptions options = maxResults(1000);\n      assertEquals(options.getMaxResults(), Integer.valueOf(1000));\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testMaxResultsNegative() {\n      maxResults(-1);\n   }\n}\n"
  },
  {
    "path": "blobstore/src/test/java/org/jclouds/blobstore/strategy/internal/BiggerThanPageSizeTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.strategy.internal;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.BlobStoreContext;\nimport org.jclouds.blobstore.options.ListContainerOptions;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\n@Test\npublic class BiggerThanPageSizeTest {\n   private BlobStore blobstore;\n\n   @BeforeTest\n   void setupBlobStore() {\n      blobstore =  ContextBuilder.newBuilder(\"transient\").build(BlobStoreContext.class).getBlobStore();\n   }\n\n   public void test() throws IOException {\n      blobstore.createContainerInLocation(null, \"goodies\");\n      for (int i = 0; i < 1001; i++) {\n         blobstore.putBlob(\"goodies\", blobstore.blobBuilder(i + \"\").payload(i + \"\").build());\n      }\n      assertEquals(blobstore.countBlobs(\"goodies\"), 1001);\n      blobstore.clearContainer(\"goodies\");\n      assertEquals(blobstore.countBlobs(\"goodies\"), 0);\n   }\n\n   public void testStrategies() throws IOException {\n      blobstore.createContainerInLocation(null, \"poo\");\n      for (int i = 0; i < 1001; i++) {\n         blobstore.putBlob(\"poo\", blobstore.blobBuilder(i + \"\").payload(i + \"\").build());\n      }\n\n      ListContainerAndRecurseThroughFolders lister = new ListContainerAndRecurseThroughFolders(\n            new ConcatenateContainerLists(blobstore));\n      assertEquals(lister.execute(\"poo\", ListContainerOptions.NONE).size(), 1001);\n      blobstore.clearContainer(\"poo\");\n      assertEquals(lister.execute(\"poo\", ListContainerOptions.NONE).size(), 0);\n   }\n\n}\n"
  },
  {
    "path": "blobstore/src/test/java/org/jclouds/blobstore/strategy/internal/ConcatenateContainerListsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.strategy.internal;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.options.ListContainerOptions;\nimport org.jclouds.util.Closeables2;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Iterables;\nimport com.google.inject.Injector;\n\n@Test(testName = \"ConcatenateContainerListsTest\", singleThreaded = true)\npublic class ConcatenateContainerListsTest {\n   private BlobStore blobstore;\n   private ConcatenateContainerLists concatter;\n\n   @BeforeClass\n   void setupBlobStore() {\n      Injector injector = ContextBuilder.newBuilder(\"transient\").buildInjector();\n      blobstore = injector.getInstance(BlobStore.class);\n      concatter = injector.getInstance(ConcatenateContainerLists.class);\n   }\n\n   public void testLargerThanOnePageNoOptions() {\n      blobstore.createContainerInLocation(null, \"goodies\");\n      for (int i = 0; i < 1001; i++) {\n         blobstore.putBlob(\"goodies\", blobstore.blobBuilder(i + \"\").payload(i + \"\").build());\n      }\n      Iterable<? extends StorageMetadata> listing = concatter.execute(\"goodies\", new ListContainerOptions());\n      assertEquals(Iterables.size(listing), 1001);\n   }\n\n   public void testLargerThanOnePageInDirAndRecursive() {\n      blobstore.createContainerInLocation(null, \"foo\");\n      for (int i = 0; i < 1001; i++) {\n         blobstore.putBlob(\"foo\", blobstore.blobBuilder(i + \"\").payload(i + \"\").build());\n      }\n      for (int i = 0; i < 1001; i++) {\n         blobstore.putBlob(\"foo\", blobstore.blobBuilder(\"dir/\" + i + \"\").payload(i + \"\").build());\n      }\n      Iterable<? extends StorageMetadata> listing = concatter.execute(\"foo\", new ListContainerOptions());\n      assertEquals(Iterables.size(listing), 1002);\n      listing = concatter.execute(\"foo\", ListContainerOptions.Builder.inDirectory(\"dir\"));\n      assertEquals(Iterables.size(listing), 1001);\n      listing = concatter.execute(\"foo\", ListContainerOptions.Builder.recursive());\n      assertEquals(Iterables.size(listing), 2002);\n   }\n\n   @AfterClass\n   void close() {\n      if (blobstore != null)\n         Closeables2.closeQuietly(blobstore.getContext());\n   }\n}\n"
  },
  {
    "path": "blobstore/src/test/java/org/jclouds/blobstore/strategy/internal/DeleteAllKeysInListTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.strategy.internal;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.createMockBuilder;\nimport static org.easymock.EasyMock.createControl;\nimport static org.easymock.EasyMock.isA;\nimport static org.easymock.EasyMock.replay;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.Assert.fail;\n\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.Set;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.Executor;\nimport java.util.concurrent.Semaphore;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicBoolean;\n\nimport org.easymock.EasyMock;\nimport org.easymock.IMocksControl;\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.ContainerNotFoundException;\nimport org.jclouds.blobstore.options.ListContainerOptions;\nimport org.jclouds.util.Closeables2;\nimport org.jclouds.blobstore.domain.PageSet;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.internal.BlobRuntimeException;\nimport org.jclouds.http.handlers.BackoffLimitedRetryHandler;\nimport org.testng.annotations.AfterMethod;\nimport org.testng.annotations.BeforeMethod;\nimport org.testng.annotations.Test;\n\nimport com.google.common.util.concurrent.Futures;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.inject.Injector;\n\n@Test(testName = \"DeleteAllKeysInListTest\", singleThreaded = true)\npublic class DeleteAllKeysInListTest {\n   private BlobStore blobstore;\n   private DeleteAllKeysInList deleter;\n   private BackoffLimitedRetryHandler retryHandler;\n   private static final String containerName = \"container\";\n   private static final String directoryName = \"directory\";\n   private static final int maxParallelDeletes = 1024;\n\n   @BeforeMethod\n   void setupBlobStore() {\n      Injector injector = ContextBuilder.newBuilder(\"transient\")\n            .buildInjector();\n      blobstore = injector.getInstance(BlobStore.class);\n      deleter = injector.getInstance(DeleteAllKeysInList.class);\n      retryHandler = injector.getInstance(BackoffLimitedRetryHandler.class);\n      createDataSet();\n   }\n\n   @AfterMethod\n   void close() {\n      Closeables2.closeQuietly(blobstore.getContext());\n   }\n\n   public void testExecuteWithoutOptionsClearsRecursively() {\n      deleter.execute(containerName);\n      assertEquals(blobstore.countBlobs(containerName), 0);\n   }\n\n   public void testExecuteRecursive() {\n      deleter.execute(containerName, ListContainerOptions.Builder.recursive());\n      assertEquals(blobstore.countBlobs(containerName), 0);\n   }\n\n   public void testExecuteNonRecursive() {\n      deleter.execute(containerName, ListContainerOptions.NONE);\n      assertEquals(blobstore.countBlobs(containerName), 2222);\n   }\n\n   public void testExecuteInDirectory() {\n      deleter.execute(containerName, ListContainerOptions.Builder.inDirectory(directoryName));\n      assertEquals(blobstore.countBlobs(containerName), 1111);\n   }\n\n   public void testContainerNotFound() {\n      IMocksControl mockControl = createControl();\n      BlobStore blobStore = mockControl.createMock(BlobStore.class);\n      ListeningExecutorService executorService = mockControl\n            .createMock(ListeningExecutorService.class);\n      DeleteAllKeysInList testDeleter = createMockBuilder(\n            DeleteAllKeysInList.class).withConstructor(executorService,\n            blobStore, retryHandler, maxParallelDeletes).createMock();\n      EasyMock.<PageSet<? extends StorageMetadata>> expect(blobStore.list(\n                  isA(String.class), isA(ListContainerOptions.class)))\n            .andThrow(new ContainerNotFoundException()).once();\n      replay(blobStore);\n      testDeleter.execute(containerName,\n            ListContainerOptions.Builder.recursive());\n      // No blobs will be deleted since blobStore.list will throw a\n      // ContainerNotFoundException.\n      assertEquals(blobstore.countBlobs(containerName), 3333);\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   public void testDeleteAfterFutureFailure() {\n      IMocksControl mockControl = createControl();\n      ListeningExecutorService executorService = mockControl\n            .createMock(ListeningExecutorService.class);\n      DeleteAllKeysInList testDeleter = createMockBuilder(\n            DeleteAllKeysInList.class).withConstructor(executorService,\n            blobstore, retryHandler, maxParallelDeletes).createMock();\n      // Fail the first future that is created for deleting blobs.\n      EasyMock.<ListenableFuture<?>> expect(\n                  executorService.submit(isA(Callable.class)))\n            .andReturn(\n                  Futures.<Void> immediateFailedFuture(new RuntimeException()))\n            .once();\n      // There should be at least another 3333 calls to executorService.submit\n      // since there are 3333 blobs.\n      EasyMock.expectLastCall().andReturn(Futures.<Void> immediateFuture(null))\n            .times(3333, Integer.MAX_VALUE);\n      replay(executorService);\n      testDeleter.execute(containerName,\n            ListContainerOptions.Builder.recursive());\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   public void testExceptionThrownAfterMaxRetries() {\n      IMocksControl mockControl = createControl();\n      ListeningExecutorService executorService = mockControl\n            .createMock(ListeningExecutorService.class);\n      DeleteAllKeysInList testDeleter = createMockBuilder(\n            DeleteAllKeysInList.class).withConstructor(executorService,\n            blobstore, retryHandler, maxParallelDeletes).createMock();\n      // Fail the first future that is created for deleting blobs.\n      EasyMock.<ListenableFuture<?>> expect(\n                  executorService.submit(isA(Callable.class)))\n            .andReturn(\n                  Futures.<Void> immediateFailedFuture(new RuntimeException()))\n            .once();\n      EasyMock.expectLastCall().andReturn(Futures.<Void> immediateFuture(null))\n            .anyTimes();\n      replay(executorService);\n      testDeleter.setMaxErrors(1);\n\n      boolean blobRunTimeExceptionThrown = false;\n      try {\n      testDeleter.execute(containerName,\n            ListContainerOptions.Builder.recursive());\n      } catch (BlobRuntimeException be) {\n         blobRunTimeExceptionThrown = true;\n      }\n\n      assertTrue(blobRunTimeExceptionThrown, \"Expected a BlobRunTimeException\");\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   public void testFuturesCancelledOnFailure() {\n      IMocksControl mockControl = createControl();\n      ListeningExecutorService executorService = mockControl\n            .createMock(ListeningExecutorService.class);\n      DeleteAllKeysInList testDeleter = createMockBuilder(\n            DeleteAllKeysInList.class).withConstructor(executorService,\n            blobstore, retryHandler, maxParallelDeletes).createMock();\n      final AtomicBoolean deleteFailure = new AtomicBoolean();\n      final Semaphore semaphore = createMock(Semaphore.class);\n      final Set<ListenableFuture<Void>> outstandingFutures = Collections\n            .synchronizedSet(new HashSet<ListenableFuture<Void>>());\n      final ListenableFuture<Void> blobDelFuture = createMock(ListenableFuture.class);\n      try {\n\n         // Allow the first semaphore acquire to succeed.\n         EasyMock.expect(semaphore.tryAcquire(Long.MAX_VALUE,\n               TimeUnit.MILLISECONDS)).andReturn(true).once();\n         EasyMock.<ListenableFuture<?>> expect(\n                  executorService.submit(isA(Callable.class)))\n            .andReturn(blobDelFuture).once();\n\n         // Fail the second semaphore acquire.\n         EasyMock.expect(semaphore.tryAcquire(Long.MAX_VALUE,\n               TimeUnit.MILLISECONDS))\n               .andReturn(false).anyTimes();\n\n         blobDelFuture.addListener(isA(Runnable.class), isA(Executor.class));\n         EasyMock.expectLastCall();\n         EasyMock.expect(blobDelFuture.cancel(true)).andReturn(true)\n               .atLeastOnce();\n      } catch (InterruptedException e) {\n         fail();\n      }\n\n      replay(semaphore, executorService, blobDelFuture);\n      testDeleter.setMaxErrors(1);\n      testDeleter.executeOneIteration(containerName,\n            ListContainerOptions.Builder.recursive(), semaphore,\n            outstandingFutures, deleteFailure, /* blocking = */false);\n      assertEquals(outstandingFutures.size(), 1);\n      assertTrue(deleteFailure.get());\n   }\n\n   /**\n    * Create a container \"container\" with 1111 blobs named \"blob-%d\".  Create a\n    * subdirectory \"directory\" which contains 2222 more blobs named\n    * \"directory/blob-%d\".\n    */\n   private void createDataSet() {\n      String blobNameFmt = \"blob-%d\";\n      String directoryBlobNameFmt = \"%s/blob-%d\";\n\n      blobstore.createContainerInLocation(null, containerName);\n      for (int i = 0; i < 1111; i++) {\n         String blobName = String.format(blobNameFmt, i);\n         blobstore.putBlob(containerName, blobstore.blobBuilder(blobName).payload(blobName).build());\n      }\n      for (int i = 0; i < 2222; i++) {\n         String directoryBlobName = String.format(directoryBlobNameFmt, directoryName, i);\n         blobstore.putBlob(containerName, blobstore.blobBuilder(directoryBlobName).payload(directoryBlobName).build());\n      }\n      assertEquals(blobstore.countBlobs(containerName), 3333);\n   }\n}\n"
  },
  {
    "path": "blobstore/src/test/java/org/jclouds/blobstore/strategy/internal/DelimiterTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.strategy.internal;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.domain.StorageType;\nimport org.jclouds.blobstore.options.ListContainerOptions;\nimport org.jclouds.util.Closeables2;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Iterables;\nimport com.google.inject.Injector;\n\n@Test(testName = \"DelimiterTest\", singleThreaded = true)\npublic class DelimiterTest {\n   private BlobStore blobStore;\n\n   @BeforeClass\n   void setupBlobStore() {\n      Injector injector = ContextBuilder.newBuilder(\"transient\").buildInjector();\n      blobStore = injector.getInstance(BlobStore.class);\n   }\n\n   @AfterClass\n   void tearDownBlobStore() {\n      if (blobStore != null)\n         Closeables2.closeQuietly(blobStore.getContext());\n   }\n\n   public void testDelimiterList() {\n      String container = \"delimiter\";\n      String delimiter = \"--\";\n      blobStore.createContainerInLocation(null, container);\n      blobStore.putBlob(container, blobStore.blobBuilder(\"foo\").payload(\"\").build());\n      blobStore.putBlob(container, blobStore.blobBuilder(\"other\" + delimiter + \"bar\").payload(\"\").build());\n      Iterable<? extends StorageMetadata> results = blobStore.list(container,\n            ListContainerOptions.Builder.delimiter(delimiter));\n      assertEquals(Iterables.size(results), 2);\n      assertEquals(Iterables.get(results, 0).getType(), StorageType.BLOB);\n      assertEquals(Iterables.get(results, 0).getName(), \"foo\");\n      assertEquals(Iterables.get(results, 1).getType(), StorageType.RELATIVE_PATH);\n      assertEquals(Iterables.get(results, 1).getName(), \"other\" + delimiter);\n   }\n}\n"
  },
  {
    "path": "blobstore/src/test/java/org/jclouds/blobstore/strategy/internal/FetchBlobMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.strategy.internal;\n\nimport com.google.common.collect.Ordering;\nimport com.google.inject.Injector;\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.PageSet;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.options.ListContainerOptions;\nimport org.jclouds.util.Closeables2;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport java.util.Comparator;\n\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\n@Test(testName = \"FetchBlobMetadataTest\", singleThreaded = true)\npublic class FetchBlobMetadataTest {\n\n   private static final String CONTAINER_NAME = \"container\";\n\n   private BlobStore blobStore;\n   private FetchBlobMetadata fetchBlobMetadata;\n\n   @BeforeClass\n   public void setupBlobStore() {\n      Injector injector = ContextBuilder.newBuilder(\"transient\").buildInjector();\n      blobStore = injector.getInstance(BlobStore.class);\n      fetchBlobMetadata = injector.getInstance(FetchBlobMetadata.class);\n      fetchBlobMetadata.setContainerName(CONTAINER_NAME);\n   }\n\n   @AfterClass\n   public void closeBlobSore() {\n      if (blobStore != null) {\n         Closeables2.closeQuietly(blobStore.getContext());\n      }\n   }\n\n   @Test\n   public void testRetainsOriginalOrder() {\n      blobStore.createContainerInLocation(null, CONTAINER_NAME);\n      for (int blobIndex = 0; blobIndex < 20; blobIndex++) {\n         final Blob blob = blobStore.blobBuilder(\"prefix-\" + blobIndex).payload(\"\").build();\n         blobStore.putBlob(CONTAINER_NAME, blob);\n      }\n\n      final PageSet<? extends StorageMetadata> pageSet =\n              blobStore.list(CONTAINER_NAME, ListContainerOptions.Builder.withDetails());\n      final PageSet<? extends StorageMetadata> resultPageSet = fetchBlobMetadata.apply(pageSet);\n      assertNotNull(resultPageSet);\n\n      assertTrue(Ordering.from(new Comparator<StorageMetadata>() {\n         @Override\n         public int compare(StorageMetadata o1, StorageMetadata o2) {\n            return o1.getName().compareTo(o2.getName());\n         }\n      }).isOrdered(resultPageSet));\n   }\n}\n"
  },
  {
    "path": "blobstore/src/test/java/org/jclouds/blobstore/strategy/internal/ListContainerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.strategy.internal;\n\nimport static org.assertj.core.api.Assertions.assertThat;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.domain.PageSet;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.domain.StorageType;\nimport org.jclouds.blobstore.options.ListContainerOptions;\nimport org.jclouds.util.Closeables2;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Iterables;\nimport com.google.common.io.ByteSource;\nimport com.google.inject.Injector;\n\n@Test(testName = \"PrefixTest\", singleThreaded = true)\npublic class ListContainerTest {\n   private BlobStore blobStore;\n   private ConcatenateContainerLists concatter;\n\n   @BeforeClass\n   public void setupBlobStore() {\n      Injector injector = ContextBuilder.newBuilder(\"transient\").buildInjector();\n      blobStore = injector.getInstance(BlobStore.class);\n      concatter = injector.getInstance(ConcatenateContainerLists.class);\n   }\n\n   @AfterClass\n   public void closeBlobSore() {\n      if (blobStore != null) {\n         Closeables2.closeQuietly(blobStore.getContext());\n      }\n   }\n\n   public void testListBlobWithPrefixAndDelimiter() {\n      String containerName = \"test\";\n      String name = \"asdf/\";\n      blobStore.createContainerInLocation(null, containerName);\n      blobStore.putBlob(containerName, blobStore.blobBuilder(name).payload(\"\").build());\n      Iterable<? extends StorageMetadata> results = concatter.execute(containerName,\n            ListContainerOptions.Builder.prefix(name).delimiter(name));\n      assertThat(results).hasSize(1);\n   }\n\n   public void testListWithPrefix() {\n      String containerName = \"prefix\";\n      String prefix = \"foo\";\n      blobStore.createContainerInLocation(null, containerName);\n      blobStore.putBlob(containerName, blobStore.blobBuilder(prefix).payload(\"\").build());\n      blobStore.putBlob(containerName, blobStore.blobBuilder(prefix + \"bar\").payload(\"\").build());\n      blobStore.putBlob(containerName, blobStore.blobBuilder(prefix + \"baz\").payload(\"\").build());\n      blobStore.putBlob(containerName, blobStore.blobBuilder(\"bar\").payload(\"\").build());\n\n      Iterable<? extends StorageMetadata> results = concatter.execute(containerName,\n            ListContainerOptions.Builder.prefix(prefix)./* irrelevant */recursive());\n      assertThat(results).hasSize(3);\n      assertThat(Iterables.get(results, 0).getName()).isEqualTo(prefix);\n      assertThat(Iterables.get(results, 0).getType()).isEqualTo(StorageType.BLOB);\n      assertThat(Iterables.get(results, 1).getName()).isEqualTo(prefix + \"bar\");\n      assertThat(Iterables.get(results, 1).getType()).isEqualTo(StorageType.BLOB);\n      assertThat(Iterables.get(results, 2).getName()).isEqualTo(prefix + \"baz\");\n      assertThat(Iterables.get(results, 2).getType()).isEqualTo(StorageType.BLOB);\n   }\n\n   public void testListWithPrefixAndDelimiter() {\n      String containerName = \"prefixWithSeparator\";\n      String prefix = \"foo\";\n      blobStore.createContainerInLocation(null, containerName);\n      blobStore.putBlob(containerName, blobStore.blobBuilder(prefix + \"-object\").payload(\"\").build());\n      blobStore.putBlob(containerName, blobStore.blobBuilder(prefix + \"bar-object\").payload(\"\")\n            .build());\n      blobStore.putBlob(containerName, blobStore.blobBuilder(prefix + \"baz-object\").payload(\"\")\n            .build());\n      blobStore.putBlob(containerName, blobStore.blobBuilder(\"bar-object\").payload(\"\").build());\n\n      Iterable<? extends StorageMetadata> results = concatter.execute(containerName,\n            ListContainerOptions.Builder.prefix(prefix).delimiter(\"-\"));\n      assertThat(Iterables.size(results)).isEqualTo(3);\n      assertThat(Iterables.get(results, 0).getType()).isEqualTo(StorageType.RELATIVE_PATH);\n      assertThat(Iterables.get(results, 0).getName()).isEqualTo(prefix + \"-\");\n      assertThat(Iterables.get(results, 1).getName()).isEqualTo(prefix + \"bar-\");\n      assertThat(Iterables.get(results, 1).getType()).isEqualTo(StorageType.RELATIVE_PATH);\n      assertThat(Iterables.get(results, 2).getName()).isEqualTo(prefix + \"baz-\");\n      assertThat(Iterables.get(results, 2).getType()).isEqualTo(StorageType.RELATIVE_PATH);\n   }\n\n   public void testListRecursivePrefix() {\n      String containerName = \"testListRecursive\";\n      String prefix = \"foo\";\n      blobStore.createContainerInLocation(null, containerName);\n      blobStore.putBlob(containerName, blobStore.blobBuilder(prefix + \"/object\").payload(\"\").build());\n      blobStore.putBlob(containerName, blobStore.blobBuilder(prefix + \"bar/object\").payload(\"\")\n            .build());\n      blobStore.putBlob(containerName, blobStore.blobBuilder(prefix + \"baz/object\").payload(\"\")\n            .build());\n      blobStore.putBlob(containerName, blobStore.blobBuilder(\"bar/object\").payload(\"\").build());\n\n      Iterable<? extends StorageMetadata> results = concatter.execute(containerName,\n            ListContainerOptions.Builder.prefix(prefix).recursive());\n      assertThat(results).hasSize(3);\n      assertThat(Iterables.get(results, 0).getType()).isEqualTo(StorageType.BLOB);\n      assertThat(Iterables.get(results, 0).getName()).isEqualTo(prefix + \"/object\");\n      assertThat(Iterables.get(results, 1).getType()).isEqualTo(StorageType.BLOB);\n      assertThat(Iterables.get(results, 1).getName()).isEqualTo(prefix + \"bar/object\");\n      assertThat(Iterables.get(results, 2).getType()).isEqualTo(StorageType.BLOB);\n      assertThat(Iterables.get(results, 2).getName()).isEqualTo(prefix + \"baz/object\");\n   }\n\n   public void testListRecursivePrefixDelimiter() {\n      String containerName = \"testListRecursivePrefixDelimiter\";\n      String prefix = \"foo/\";\n      blobStore.createContainerInLocation(null, containerName);\n      blobStore.putBlob(containerName, blobStore.blobBuilder(prefix + \"object\").payload(\"\").build());\n      blobStore.putBlob(containerName, blobStore.blobBuilder(prefix + \"bar/object\").payload(\"\")\n            .build());\n      blobStore.putBlob(containerName, blobStore.blobBuilder(prefix + \"baz/object\").payload(\"\")\n            .build());\n      blobStore.putBlob(containerName, blobStore.blobBuilder(\"bar/object\").payload(\"\").build());\n\n      Iterable<? extends StorageMetadata> results = concatter.execute(containerName,\n            ListContainerOptions.Builder.prefix(prefix));\n      assertThat(results).hasSize(3);\n      assertThat(Iterables.get(results, 0).getType()).isEqualTo(StorageType.RELATIVE_PATH);\n      assertThat(Iterables.get(results, 0).getName()).isEqualTo(prefix + \"bar/\");\n      assertThat(Iterables.get(results, 1).getType()).isEqualTo(StorageType.RELATIVE_PATH);\n      assertThat(Iterables.get(results, 1).getName()).isEqualTo(prefix + \"baz/\");\n      assertThat(Iterables.get(results, 2).getType()).isEqualTo(StorageType.BLOB);\n      assertThat(Iterables.get(results, 2).getName()).isEqualTo(prefix + \"object\");\n   }\n\n   public void testListDirectory() {\n      String containerName = \"testListDir\";\n      String directory = \"dir\";\n      blobStore.createContainerInLocation(null, containerName);\n      blobStore.createDirectory(containerName, directory);\n      blobStore.putBlob(containerName, blobStore.blobBuilder(directory + \"/foo\").payload(\"\").build());\n      blobStore.putBlob(containerName, blobStore.blobBuilder(directory + \"/bar\").payload(\"\").build());\n      Iterable<? extends StorageMetadata> results = concatter.execute(containerName, ListContainerOptions.NONE);\n      assertThat(results).hasSize(2);\n      assertThat(Iterables.get(results, 0).getName()).isEqualTo(directory);\n      assertThat(Iterables.get(results, 0).getType()).isEqualTo(StorageType.FOLDER);\n      assertThat(Iterables.get(results, 1).getName()).isEqualTo(directory + '/');\n      assertThat(Iterables.get(results, 1).getType()).isEqualTo(StorageType.RELATIVE_PATH);\n   }\n\n   public void testListMarkers() {\n      String containerName = \"testListMarkers\";\n      blobStore.createContainerInLocation(null, containerName);\n      blobStore.putBlob(containerName, blobStore.blobBuilder(\"abc\").payload(\"\").build());\n      blobStore.putBlob(containerName, blobStore.blobBuilder(\"foo/bar\").payload(\"\").build());\n      blobStore.putBlob(containerName, blobStore.blobBuilder(\"foo/baz\").payload(\"\").build());\n      blobStore.putBlob(containerName, blobStore.blobBuilder(\"qux\").payload(\"\").build());\n\n      PageSet<? extends StorageMetadata> results = blobStore.list(\n              containerName, ListContainerOptions.Builder.maxResults(1));\n      assertThat(results.getNextMarker()).isEqualTo(\"abc\");\n      results = blobStore.list(containerName,\n              ListContainerOptions.Builder.maxResults(1).afterMarker(results.getNextMarker()));\n      assertThat(results.getNextMarker()).isEqualTo(\"foo/\");\n      results = blobStore.list(containerName,\n              ListContainerOptions.Builder.maxResults(1).afterMarker(results.getNextMarker()));\n      assertThat(results.getNextMarker()).isEqualTo(null);\n   }\n\n   public void testListBlobEndsWithDelimiter() {\n      String containerName = \"testListBlobEndsWithDelimiter\";\n      blobStore.createContainerInLocation(null, containerName);\n      blobStore.putBlob(containerName, blobStore.blobBuilder(\"foo/\").payload(ByteSource.empty()).build());\n      PageSet<? extends StorageMetadata> results = blobStore.list(containerName,\n            ListContainerOptions.Builder.prefix(\"foo/\"));\n      assertThat(results.size()).isEqualTo(1);\n      assertThat(Iterables.get(results, 0).getName()).isEqualTo(\"foo/\");\n      assertThat(Iterables.get(results, 0).getType()).isNotEqualTo(StorageType.RELATIVE_PATH);\n   }\n\n   public void testListBlobEndsWithDelimiterAndDelimiterFilter() {\n      String containerName = \"testListBlobEndsWithDelimiterAndDelimiterFilter\";\n      blobStore.createContainerInLocation(null, containerName);\n      blobStore.putBlob(containerName, blobStore.blobBuilder(\"foo/\").type(StorageType.FOLDER)\n         .payload(ByteSource.empty()).build());\n      blobStore.putBlob(containerName, blobStore.blobBuilder(\"bar/text\").type(StorageType.BLOB)\n         .payload(ByteSource.empty()).build());\n      PageSet<? extends StorageMetadata> results = blobStore.list(containerName,\n         ListContainerOptions.Builder.delimiter(\"/\"));\n      assertThat(results.size()).isEqualTo(2);\n      assertThat(Iterables.get(results, 0).getName()).isEqualTo(\"bar/\");\n      assertThat(Iterables.get(results, 0).getType()).isEqualTo(StorageType.RELATIVE_PATH);\n      assertThat(Iterables.get(results, 1).getName()).isEqualTo(\"foo/\");\n      assertThat(Iterables.get(results, 1).getType()).isEqualTo(StorageType.FOLDER);\n   }\n\n   public void testDirectoryListing() {\n      String containerName = \"testDirectoryListing\";\n      blobStore.createContainerInLocation(null, containerName);\n      blobStore.createDirectory(containerName, \"dir\");\n      blobStore.createDirectory(containerName, \"dir/dir\");\n\n      PageSet<? extends StorageMetadata> results = blobStore.list(containerName);\n      assertThat(results.size()).isEqualTo(2);\n      assertThat(Iterables.get(results, 0).getName()).isEqualTo(\"dir\");\n      assertThat(Iterables.get(results, 1).getName()).isEqualTo(\"dir/\");\n\n      results = blobStore.list(containerName, ListContainerOptions.Builder.inDirectory(\"dir\"));\n      assertThat(results.size()).isEqualTo(1);\n      assertThat(Iterables.get(results, 0).getName()).isEqualTo(\"dir/dir\");\n      assertThat(Iterables.get(results, 0).getType()).isEqualTo(StorageType.FOLDER);\n\n      blobStore.putBlob(containerName, blobStore.blobBuilder(\"dir/dir/blob\").payload(\"\").build());\n      results = blobStore.list(containerName, ListContainerOptions.Builder.inDirectory(\"dir\"));\n      assertThat(results.size()).isEqualTo(2);\n      assertThat(Iterables.get(results, 0).getName()).isEqualTo(\"dir/dir\");\n      assertThat(Iterables.get(results, 0).getType()).isEqualTo(StorageType.FOLDER);\n      assertThat(Iterables.get(results, 1).getName()).isEqualTo(\"dir/dir/\");\n      assertThat(Iterables.get(results, 1).getType()).isEqualTo(StorageType.RELATIVE_PATH);\n   }\n}\n"
  },
  {
    "path": "blobstore/src/test/java/org/jclouds/blobstore/strategy/internal/MpuPartitioningAlgorithmTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.strategy.internal;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code MultipartUploadSlicingAlgorithm} from the perspective of\n * partitioning algorithm\n */\n@Test(groups = \"unit\")\npublic final class MpuPartitioningAlgorithmTest {\n   private static final long MIN_PART_SIZE = 5L * 1024 * 1024;\n   private static final long MAX_PART_SIZE = 5L * 1024 * 1024 * 1024;\n   private static final int MAX_NUMBER_OF_PARTS = 10 * 1000;\n\n   /**\n    * Below 1 parts the MPU is not used.\n    * When we have more than {@code MultipartUploadSlicingAlgorithm.DEFAULT_PART_SIZE} bytes data,\n    * the MPU starts to become active.\n    */\n   @Test\n   public void testLowerLimitFromWhereMultipartBecomeActive() {\n      MultipartUploadSlicingAlgorithm strategy = new MultipartUploadSlicingAlgorithm(\n            MIN_PART_SIZE, MAX_PART_SIZE, MAX_NUMBER_OF_PARTS);\n\n      // exactly the MIN_PART_SIZE\n      long length = MIN_PART_SIZE;\n      long chunkSize = strategy.calculateChunkSize(length);\n      assertEquals(chunkSize, MultipartUploadSlicingAlgorithm.DEFAULT_PART_SIZE);\n      assertEquals(strategy.getParts(), 0);\n      assertEquals(strategy.getRemaining(), length);\n      assertEquals(chunkSize * strategy.getParts() + strategy.getRemaining(), length);\n\n      // below DEFAULT_PART_SIZE\n      length = MultipartUploadSlicingAlgorithm.DEFAULT_PART_SIZE;\n      chunkSize = strategy.calculateChunkSize(length);\n      assertEquals(chunkSize, MultipartUploadSlicingAlgorithm.DEFAULT_PART_SIZE);\n      assertEquals(strategy.getParts(), 0);\n      assertEquals(strategy.getRemaining(), length);\n      assertEquals(chunkSize * strategy.getParts() + strategy.getRemaining(), length);\n\n      // exactly the DEFAULT_PART_SIZE\n      length = MultipartUploadSlicingAlgorithm.DEFAULT_PART_SIZE + 1;\n      chunkSize = strategy.calculateChunkSize(length);\n      assertEquals(chunkSize, MultipartUploadSlicingAlgorithm.DEFAULT_PART_SIZE);\n      assertEquals(strategy.getParts(), 1);\n      assertEquals(strategy.getRemaining(), 1);\n      assertEquals(chunkSize * strategy.getParts() + strategy.getRemaining(), length);\n   }\n\n   /**\n    * Phase 1 of the algorithm.\n    * ChunkSize does not grow from a {@code MultipartUploadStrategy.DEFAULT_PART_SIZE}\n    * until we reach {@code MultipartUploadSlicingAlgorithm.MAGNITUDE_BASE} number of parts.\n    */\n   @Test\n   public void testWhenChunkSizeHasToStartGrowing() {\n      MultipartUploadSlicingAlgorithm strategy = new MultipartUploadSlicingAlgorithm(\n            MIN_PART_SIZE, MAX_PART_SIZE, MAX_NUMBER_OF_PARTS);\n      // upper limit while we still have exactly defaultPartSize chunkSize\n      long length = MultipartUploadSlicingAlgorithm.DEFAULT_PART_SIZE * MultipartUploadSlicingAlgorithm.DEFAULT_MAGNITUDE_BASE;\n      long chunkSize = strategy.calculateChunkSize(length);\n      assertEquals(chunkSize, MultipartUploadSlicingAlgorithm.DEFAULT_PART_SIZE);\n      assertEquals(strategy.getParts(), MultipartUploadSlicingAlgorithm.DEFAULT_MAGNITUDE_BASE - 1);\n      assertEquals(strategy.getRemaining(), MultipartUploadSlicingAlgorithm.DEFAULT_PART_SIZE);\n      assertEquals(chunkSize * strategy.getParts() + strategy.getRemaining(), length);\n\n      // then chunkSize is increasing\n      length += 1;\n      chunkSize = strategy.calculateChunkSize(length);\n      assertEquals(chunkSize, MultipartUploadSlicingAlgorithm.DEFAULT_PART_SIZE * 2);\n      assertEquals(strategy.getParts(), MultipartUploadSlicingAlgorithm.DEFAULT_MAGNITUDE_BASE / 2);\n      assertEquals(strategy.getRemaining(), 1);\n      assertEquals(chunkSize * strategy.getParts() + strategy.getRemaining(), length);\n   }\n\n   /**\n    * Phase 2 of the algorithm.\n    * The number of parts does not grow from {@code MultipartUploadSlicingAlgorithm.MAGNITUDE_BASE}\n    * until we reach the {@code MultipartUploadStrategy.MAX_PART_SIZE}.\n    */\n   @Test\n   public void testWhenPartsHasToStartGrowingFromMagnitudeBase() {\n      MultipartUploadSlicingAlgorithm strategy = new MultipartUploadSlicingAlgorithm(\n            MIN_PART_SIZE, MAX_PART_SIZE, MAX_NUMBER_OF_PARTS);\n      // upper limit while we still have exactly MAGNITUDE_BASE parts (together with the remaining)\n      long length = MAX_PART_SIZE * MultipartUploadSlicingAlgorithm.DEFAULT_MAGNITUDE_BASE;\n      long chunkSize = strategy.calculateChunkSize(length);\n      assertEquals(chunkSize, MAX_PART_SIZE);\n      assertEquals(strategy.getParts(), MultipartUploadSlicingAlgorithm.DEFAULT_MAGNITUDE_BASE - 1);\n      assertEquals(strategy.getRemaining(), MAX_PART_SIZE);\n      assertEquals(chunkSize * strategy.getParts() + strategy.getRemaining(), length);\n\n      // then the number of parts is increasing\n      length += 1;\n      chunkSize = strategy.calculateChunkSize(length);\n      assertEquals(chunkSize, MAX_PART_SIZE);\n      assertEquals(strategy.getParts(), MultipartUploadSlicingAlgorithm.DEFAULT_MAGNITUDE_BASE);\n      assertEquals(strategy.getRemaining(), 1);\n      assertEquals(chunkSize * strategy.getParts() + strategy.getRemaining(), length);\n   }\n\n   /**\n    * Phase 3 of the algorithm.\n    * The number of parts are increasing until {@code MAX_NUMBER_OF_PARTS}\n    * while its size does not exceeds the {@code MultipartUploadStrategy.MAX_PART_SIZE}.\n    */\n   @Test\n   public void testWhenPartsExceedsMaxNumberOfParts() {\n      MultipartUploadSlicingAlgorithm strategy = new MultipartUploadSlicingAlgorithm(\n            MIN_PART_SIZE, MAX_PART_SIZE, MAX_NUMBER_OF_PARTS);\n      // upper limit while we still have exactly MAX_NUMBER_OF_PARTS parts (together with the remaining)\n      long length = MAX_PART_SIZE * MAX_NUMBER_OF_PARTS;\n      long chunkSize = strategy.calculateChunkSize(length);\n      assertEquals(chunkSize, MAX_PART_SIZE);\n      assertEquals(strategy.getParts(), MAX_NUMBER_OF_PARTS - 1);\n      assertEquals(strategy.getRemaining(), MAX_PART_SIZE);\n      assertEquals(chunkSize * strategy.getParts() + strategy.getRemaining(), length);\n\n      // then the number of parts is increasing\n      length += 1;\n      chunkSize = strategy.calculateChunkSize(length);\n      assertEquals(chunkSize, 5369246044L);\n      assertEquals(strategy.getParts(), MAX_NUMBER_OF_PARTS - 1);\n      assertEquals(strategy.getRemaining(), 6045);\n      assertEquals(chunkSize * strategy.getParts() + strategy.getRemaining(), length);\n   }\n}\n"
  },
  {
    "path": "blobstore/src/test/java/org/jclouds/blobstore/util/BlobStoreUtilsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.blobstore.util;\n\nimport static org.assertj.core.api.Fail.failBecauseExceptionWasNotThrown;\nimport static org.jclouds.blobstore.util.BlobStoreUtils.getNameFor;\nimport static org.jclouds.reflect.Reflection2.method;\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport org.jclouds.reflect.Invocation;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Throwables;\nimport com.google.common.collect.ImmutableList;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.BlobStoreContext;\nimport org.jclouds.blobstore.domain.Blob;\n\n@Test(groups = \"unit\")\npublic class BlobStoreUtilsTest {\n\n   public void testGetKeyForAzureS3AndRackspace() {\n      GeneratedHttpRequest request = requestForEndpointAndArgs(\n            \"https://jclouds.blob.core.windows.net/adriancole-blobstore0/five\",\n            ImmutableList.<Object> of(\"adriancole-blobstore0\", \"five\"));\n      assertEquals(getNameFor(request), \"five\");\n   }\n\n   public void testGetKeyForAtmos() {\n      GeneratedHttpRequest request = requestForEndpointAndArgs(\n            \"https://storage4.clouddrive.com/v1/MossoCloudFS_dc1f419c-5059-4c87-a389-3f2e33a77b22/adriancole-blobstore0/four\",\n            ImmutableList.<Object> of(\"adriancole-blobstore0/four\"));\n      assertEquals(getNameFor(request), \"four\");\n   }\n\n   public void testReadOnlyBlobStore() {\n      BlobStoreContext context = ContextBuilder.newBuilder(\"transient\").build(BlobStoreContext.class);\n      try {\n         BlobStore rwBlobStore = context.getBlobStore();\n         BlobStore roBlobStore = ReadOnlyBlobStore.newReadOnlyBlobStore(rwBlobStore);\n         String containerName = \"name\";\n         rwBlobStore.createContainerInLocation(null, containerName);\n         Blob blob = rwBlobStore.blobBuilder(\"blob\")\n               .payload(new byte[0])\n               .build();\n         rwBlobStore.putBlob(containerName, blob);\n         try {\n            roBlobStore.putBlob(containerName, blob);\n            failBecauseExceptionWasNotThrown(UnsupportedOperationException.class);\n         } catch (UnsupportedOperationException uoe) {\n            // expected\n         }\n      } finally {\n         context.close();\n      }\n   }\n\n   GeneratedHttpRequest requestForEndpointAndArgs(String endpoint, List<Object> args) {\n      try {\n         Invocation invocation = Invocation.create(method(String.class, \"toString\"), args);\n         return GeneratedHttpRequest.builder().method(\"POST\").endpoint(URI.create(endpoint)).invocation(invocation)\n               .build();\n      } catch (SecurityException e) {\n         throw Throwables.propagate(e);\n      }\n   }\n}\n"
  },
  {
    "path": "common/googlecloud/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.googlecloud.*;version=\"${project.version}\";-noimport:=true"
  },
  {
    "path": "common/googlecloud/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n         xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n    <modelVersion>4.0.0</modelVersion>\n    <parent>\n        <groupId>org.apache.jclouds</groupId>\n        <artifactId>jclouds-project</artifactId>\n        <version>2.7.1-SNAPSHOT</version>\n        <relativePath>../../project/pom.xml</relativePath>\n    </parent>\n\n    <groupId>org.apache.jclouds.common</groupId>\n    <artifactId>googlecloud</artifactId>\n    <name>jclouds Google Cloud Core</name>\n    <description>jclouds components common to Google Cloud products</description>\n\n    <dependencies>\n        <dependency>\n            <groupId>org.apache.jclouds.api</groupId>\n            <artifactId>oauth</artifactId>\n            <version>${project.version}</version>\n            <type>jar</type>\n        </dependency>\n        <dependency>\n            <groupId>org.apache.jclouds.api</groupId>\n            <artifactId>oauth</artifactId>\n            <version>${project.version}</version>\n            <type>test-jar</type>\n            <scope>test</scope>\n        </dependency>\n        <dependency>\n            <groupId>com.google.auto.value</groupId>\n            <artifactId>auto-value</artifactId>\n            <scope>provided</scope>\n        </dependency>\n        <dependency>\n            <groupId>org.apache.jclouds</groupId>\n            <artifactId>jclouds-core</artifactId>\n            <version>${project.version}</version>\n            <type>test-jar</type>\n            <scope>test</scope>\n        </dependency>\n    </dependencies>\n</project>\n"
  },
  {
    "path": "common/googlecloud/src/main/java/org/jclouds/googlecloud/GoogleCredentialsFromJson.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloud;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.domain.Credentials;\n\nimport com.google.common.base.Supplier;\nimport com.google.gson.JsonObject;\nimport com.google.gson.JsonParser;\n\n/*\n * Provides an easy way to pass in credentials using the json-key format.\n * Just provide the path to the .json file and this extracts and sets identity\n *  and credentials from the json.\n */\npublic class GoogleCredentialsFromJson implements Supplier<Credentials>{\n\n   private final String jsonKeyString;\n\n   public GoogleCredentialsFromJson(String jsonString){\n      checkNotNull(jsonString, \"Google Credentials jsonString cannot be null\");\n      jsonKeyString = jsonString;\n   }\n\n   /**\n    * Function for parsing JSON Key String from file downloaded from GCP developers console.\n    *\n    * @param jsonString - a String in JSON format containing service account credentials\n    *  as provided from the Google Developers Console\n    * @return Credentials object with Credentials.identity and Credentials.credential correctly set.\n    */\n   private static Credentials parseJsonKeyString(String jsonString) {\n      // Parse JsonFile to extract Service Account and PrivateKey.\n      final JsonObject json = new JsonParser().parse(jsonString).getAsJsonObject();\n      String client_email = json.get(\"client_email\").toString().replace(\"\\\"\", \"\");\n      // When reading the file it reads in \\n in as\n      String private_key = json.get(\"private_key\").toString().replace(\"\\\"\", \"\").replace(\"\\\\n\", \"\\n\");\n\n      return new Credentials(client_email, // identity\n                             private_key); // credentials\n   }\n\n   @Override\n   public Credentials get() {\n      return parseJsonKeyString(jsonKeyString);\n   }\n}\n"
  },
  {
    "path": "common/googlecloud/src/main/java/org/jclouds/googlecloud/config/CurrentProject.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloud.config;\n\nimport static com.google.common.base.Preconditions.checkArgument;\n\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport jakarta.inject.Qualifier;\n\n/** Associated bindings with the current <a href=\"https://cloud.google.com/compute/docs/projects\">project</a>. */\n@Retention(value = RetentionPolicy.RUNTIME)\n@Target(value = {ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})\n@Qualifier\npublic @interface CurrentProject {\n\n   /** Utilities related to the email associated with the service account of a project. */\n   public static final class ClientEmail {\n      public static final String DESCRIPTION = \"\" //\n            + \"client_email which usually looks like project_id@developer.gserviceaccount.com or \" //\n            + \"project_id-extended_uid@developer.gserviceaccount.com or \" //\n            + \"account@project_id.company_domain.iam.gserviceaccount.com or \" //\n            + \"account@project_id.iam.gserviceaccount.com.\";\n      private static final Pattern PROJECT_NUMBER_PATTERN = Pattern.compile(\"^([0-9]+)[@-].*\");\n      private static final String IAM_ACCOUNT_SUFFIX = \".iam.gserviceaccount.com\";\n\n      /** Parses the project number from the client email or throws an {@linkplain IllegalArgumentException}. */\n      public static String toProjectNumber(String email) {\n         Matcher matcher = PROJECT_NUMBER_PATTERN.matcher(email);\n         boolean isIAM = email.endsWith(IAM_ACCOUNT_SUFFIX);\n         checkArgument(isIAM || matcher.find(), \"Client email %s is malformed. Should be %s\", email, DESCRIPTION);\n         return isIAM ? projectIdFromIAM(email) : matcher.group(1);\n      }\n\n      private static String projectIdFromIAM(String email) {\n         String project_id = email.substring(email.indexOf('@') + 1, email.indexOf(IAM_ACCOUNT_SUFFIX));\n         int dot = project_id.indexOf('.');\n         return dot > 0\n               // Convert project_id.company_domain into company_domain:project_id\n               ? String.format(\"%s:%s\", project_id.substring(dot + 1), project_id.substring(0, dot))\n               : project_id;\n      }\n   }\n}\n"
  },
  {
    "path": "common/googlecloud/src/main/java/org/jclouds/googlecloud/config/GoogleCloudProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloud.config;\n\nimport org.jclouds.oauth.v2.config.OAuthProperties;\n\n/** Configuration properties keys used in {@link org.jclouds.ContextBuilder#overrides(java.util.Properties)}. */\npublic final class GoogleCloudProperties {\n\n   /**\n    * How requests are authorized using OAuth. Defaults to {@link org.jclouds.oauth.v2.config.CredentialType#P12_PRIVATE_KEY_CREDENTIALS}.\n    *\n    * @see org.jclouds.oauth.v2.config.CredentialType\n    */\n   public static final String CREDENTIAL_TYPE = OAuthProperties.CREDENTIAL_TYPE;\n\n   /**\n    * Set this property to specify the <a href=\"https://cloud.google.com/compute/docs/projects\">project name</a> this\n    * context applies to.\n    * <p/> This is an alternative to looking up the project name at runtime.\n    */\n   public static final String PROJECT_NAME = \"jclouds.googlecloud.project-name\";\n\n   private GoogleCloudProperties() {\n   }\n}\n"
  },
  {
    "path": "common/googlecloud/src/main/java/org/jclouds/googlecloud/config/ListPageAdapterFactory.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloud.config;\n\nimport java.io.IOException;\nimport java.lang.reflect.ParameterizedType;\nimport java.lang.reflect.Type;\n\nimport org.jclouds.googlecloud.domain.ForwardingListPage;\nimport org.jclouds.googlecloud.domain.ListPage;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.gson.Gson;\nimport com.google.gson.TypeAdapter;\nimport com.google.gson.TypeAdapterFactory;\nimport com.google.gson.reflect.TypeToken;\nimport com.google.gson.stream.JsonReader;\nimport com.google.gson.stream.JsonToken;\nimport com.google.gson.stream.JsonWriter;\n\npublic final class ListPageAdapterFactory implements TypeAdapterFactory {\n   static final class ListPageAdapter extends TypeAdapter<ListPage<?>> {\n      private final TypeAdapter<?> itemAdapter;\n\n      ListPageAdapter(TypeAdapter<?> itemAdapter) {\n         this.itemAdapter = itemAdapter;\n         nullSafe();\n      }\n\n      public void write(JsonWriter out, ListPage<?> value) throws IOException {\n         throw new UnsupportedOperationException(\"We only read ListPages!\");\n      }\n\n      public ListPage<?> read(JsonReader in) throws IOException {\n         ImmutableList.Builder<Object> items = ImmutableList.builder();\n         String nextPageToken = null;\n         in.beginObject();\n         while (in.hasNext()) {\n            String name = in.nextName();\n            if (name.equals(\"items\")) {\n               if (in.peek() == JsonToken.BEGIN_ARRAY) {\n                  readItems(in, items);\n               } else { // aggregated\n                  readAggregate(in, items);\n               }\n            } else if (name.equals(\"nextPageToken\")) {\n               nextPageToken = in.nextString();\n            } else {\n               in.skipValue();\n            }\n         }\n         in.endObject();\n         return ForwardingListPage.create(items.build(), nextPageToken);\n      }\n\n      private void readItems(JsonReader in, ImmutableList.Builder<Object> items) throws IOException {\n         in.beginArray();\n         while (in.hasNext()) {\n            Object item = itemAdapter.read(in);\n            if (item != null) {\n               items.add(item);\n            }\n         }\n         in.endArray();\n      }\n\n      private void readAggregate(JsonReader in, ImmutableList.Builder<Object> items) throws IOException {\n         in.beginObject(); // enter zone name -> type -> items map\n         while (in.hasNext()) {\n            String scope = in.nextName(); // skip zone name\n            in.beginObject(); // enter zone map\n            while (in.hasNext()) {\n               String resourceTypeOrWarning = in.nextName();\n               if (!resourceTypeOrWarning.equals(\"warning\")) {\n                  readItems(in, items);\n               } else {\n                  in.skipValue();\n               }\n            }\n            in.endObject(); // end zone map\n         }\n         in.endObject(); // end item wrapper\n      }\n   }\n\n   @SuppressWarnings(\"unchecked\") public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> ownerType) {\n      Type type = ownerType.getType();\n      if (ownerType.getRawType() != ListPage.class || !(type instanceof ParameterizedType)) {\n         return null;\n      }\n      Type elementType = ((ParameterizedType) type).getActualTypeArguments()[0];\n      TypeAdapter<?> itemAdapter = gson.getAdapter(TypeToken.get(elementType));\n      return (TypeAdapter<T>) new ListPageAdapter(itemAdapter);\n   }\n}\n"
  },
  {
    "path": "common/googlecloud/src/main/java/org/jclouds/googlecloud/domain/ForwardingListPage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloud.domain;\n\nimport java.beans.ConstructorProperties;\nimport java.util.List;\n\nimport org.jclouds.googlecloud.internal.NullSafeCopies;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.collect.ForwardingList;\n\n/** An immutable list that includes a token, if there is another page available. */\npublic final class ForwardingListPage<T> extends ForwardingList<T> implements ListPage<T> {\n\n   private final List<T> items;\n   private final String nextPageToken;\n\n   @ConstructorProperties({ \"items\", \"nextPageToken\" }) ForwardingListPage(List<T> items, String nextPageToken) {\n      this.items = NullSafeCopies.copyOf(items);\n      this.nextPageToken = nextPageToken;\n   }\n\n   public static <T> ListPage<T> create(List<T> items, String nextPageToken) {\n      return new ForwardingListPage<T>(items, nextPageToken);\n   }\n\n   @Override @Nullable public String nextPageToken() {\n      return nextPageToken;\n   }\n\n   @Override protected List<T> delegate() {\n      return items;\n   }\n\n}\n\n"
  },
  {
    "path": "common/googlecloud/src/main/java/org/jclouds/googlecloud/domain/ListPage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloud.domain;\n\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\n\n/** An immutable list that includes a token, if there is another page available. */\npublic interface ListPage<T> extends List<T> {\n   /** Indicates more data is available. */\n   @Nullable String nextPageToken();\n}\n\n"
  },
  {
    "path": "common/googlecloud/src/main/java/org/jclouds/googlecloud/internal/AdvancingIterator.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloud.internal;\n\nimport org.jclouds.googlecloud.domain.ListPage;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.AbstractIterator;\n\nfinal class AdvancingIterator<T> extends AbstractIterator<ListPage<T>> {\n\n   private final Function<String, ListPage<T>> tokenToNext;\n   private ListPage<T> current;\n   private boolean unread = true;\n\n   AdvancingIterator(ListPage<T> initial, Function<String, ListPage<T>> tokenToNext) {\n      this.current = initial;\n      this.tokenToNext = tokenToNext;\n   }\n\n   @Override protected ListPage<T> computeNext() {\n      if (unread) {\n         try {\n            return current;\n         } finally {\n            unread = false;\n         }\n      } else if (current.nextPageToken() != null) {\n         return current = tokenToNext.apply(current.nextPageToken());\n      } else {\n         return endOfData();\n      }\n   }\n}\n"
  },
  {
    "path": "common/googlecloud/src/main/java/org/jclouds/googlecloud/internal/BaseArg0ToIteratorOfListPage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloud.internal;\n\nimport java.util.Iterator;\n\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecloud.options.ListOptions;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.InvocationContext;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\n\nimport com.google.common.base.Function;\n\npublic abstract class BaseArg0ToIteratorOfListPage<T, O extends ListOptions, I extends BaseArg0ToIteratorOfListPage<T, O, I>>\n      implements Function<ListPage<T>, Iterator<ListPage<T>>>, InvocationContext<I> {\n\n   private GeneratedHttpRequest request;\n\n   @Override public Iterator<ListPage<T>> apply(ListPage<T> input) {\n      if (input.nextPageToken() == null) {\n         return ListPages.singletonOrEmptyIterator(input);\n      }\n\n      String arg0 = (String) request.getInvocation().getArgs().get(0);\n      O options = ListPages.listOptions(request.getInvocation().getArgs());\n\n      return new AdvancingIterator<T>(input, fetchNextPage(arg0, options));\n   }\n\n   /**\n    * This is used when you need to close over the first argument of this api.\n    *\n    * <p/> For example, {@code arg0} will become \"myzone\", which you can use to ensure the next page goes to the\n    * same zone: <pre>{@code api.operations().listInZone(\"myzone\")}</pre>\n    */\n   protected abstract Function<String, ListPage<T>> fetchNextPage(String arg0, O options);\n\n   @SuppressWarnings(\"unchecked\")\n   @Override public I setContext(HttpRequest request) {\n      this.request = GeneratedHttpRequest.class.cast(request);\n      return (I) this;\n   }\n}\n"
  },
  {
    "path": "common/googlecloud/src/main/java/org/jclouds/googlecloud/internal/BaseCallerArg0ToIteratorOfListPage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloud.internal;\n\nimport java.util.Iterator;\n\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecloud.options.ListOptions;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.InvocationContext;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\n\nimport com.google.common.base.Function;\n\npublic abstract class BaseCallerArg0ToIteratorOfListPage<T, O extends ListOptions, I extends BaseCallerArg0ToIteratorOfListPage<T, O, I>>\n      implements Function<ListPage<T>, Iterator<ListPage<T>>>, InvocationContext<I> {\n\n   private GeneratedHttpRequest request;\n\n   @Override public Iterator<ListPage<T>> apply(ListPage<T> input) {\n      if (input.nextPageToken() == null) {\n         return ListPages.singletonOrEmptyIterator(input);\n      }\n\n      String arg0 = (String) request.getCaller().get().getArgs().get(0);\n      O options = ListPages.listOptions(request.getInvocation().getArgs());\n\n      return new AdvancingIterator<T>(input, fetchNextPage(arg0, options));\n   }\n\n   /**\n    * This is used when you need to close over the argument that created the api.\n    *\n    * <p/> For example, {@code callerArg0} will become \"myzone\", which you can use to ensure the next page goes to the\n    * same zone: <pre>{@code api.instancesInZone(\"myzone\").list()}</pre>\n    */\n   protected abstract Function<String, ListPage<T>> fetchNextPage(String callerArg0, O options);\n\n   @SuppressWarnings(\"unchecked\")\n   @Override public I setContext(HttpRequest request) {\n      this.request = GeneratedHttpRequest.class.cast(request);\n      return (I) this;\n   }\n}\n"
  },
  {
    "path": "common/googlecloud/src/main/java/org/jclouds/googlecloud/internal/BaseToIteratorOfListPage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloud.internal;\n\nimport java.util.Iterator;\n\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecloud.options.ListOptions;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.InvocationContext;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\n\nimport com.google.common.base.Function;\n\npublic abstract class BaseToIteratorOfListPage<T, O extends ListOptions, I extends BaseToIteratorOfListPage<T, O, I>>\n      implements Function<ListPage<T>, Iterator<ListPage<T>>>, InvocationContext<I> {\n\n   private GeneratedHttpRequest request;\n\n   @Override public Iterator<ListPage<T>> apply(ListPage<T> input) {\n      if (input.nextPageToken() == null) {\n         return ListPages.singletonOrEmptyIterator(input);\n      }\n      return new AdvancingIterator<T>(input,\n            fetchNextPage(ListPages.<O>listOptions(request.getInvocation().getArgs())));\n   }\n\n   protected abstract Function<String, ListPage<T>> fetchNextPage(O options);\n\n   @SuppressWarnings(\"unchecked\")\n   @Override public I setContext(HttpRequest request) {\n      this.request = GeneratedHttpRequest.class.cast(request);\n      return (I) this;\n   }\n}\n"
  },
  {
    "path": "common/googlecloud/src/main/java/org/jclouds/googlecloud/internal/ListPages.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloud.internal;\n\nimport static com.google.common.base.Predicates.instanceOf;\nimport static com.google.common.collect.Iterables.tryFind;\n\nimport java.util.Iterator;\nimport java.util.List;\n\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecloud.options.ListOptions;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.collect.AbstractIterator;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Iterators;\n\npublic final class ListPages {\n\n   public static <T> Iterable<T> concat(final Iterator<ListPage<T>> input) {\n      return new Iterable<T>() {\n         @Override public Iterator<T> iterator() {\n            return Iterators.concat(new AbstractIterator<Iterator<T>>() {\n               @Override protected Iterator<T> computeNext() {\n                  return input.hasNext() ? input.next().iterator() : endOfData();\n               }\n            });\n         }\n      };\n   }\n\n   /** Value of {@code <O>} is a final class in the cloud provider. Rather than playing with reflection, we trust it. */\n   @Nullable static <O extends ListOptions> O listOptions(List<Object> args) {\n      return (O) tryFind(args, instanceOf(ListOptions.class)).orNull();\n   }\n\n   static <T> Iterator<ListPage<T>> singletonOrEmptyIterator(ListPage<T> input) {\n      return input.isEmpty() ? ImmutableList.<ListPage<T>>of().iterator() : Iterators.singletonIterator(input);\n   }\n\n   private ListPages() {\n   }\n}\n"
  },
  {
    "path": "common/googlecloud/src/main/java/org/jclouds/googlecloud/internal/NullSafeCopies.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloud.internal;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\n\npublic final class NullSafeCopies {\n\n   public static <K, V> Map<K, V> copyOf(@Nullable Map<K, V> map) {\n      return map != null ? ImmutableMap.copyOf(map) : ImmutableMap.<K, V>of();\n   }\n\n   public static <E> List<E> copyOf(@Nullable List<E> list) {\n      return list != null ? ImmutableList.copyOf(list) : ImmutableList.<E>of();\n   }\n\n   private NullSafeCopies() {\n   }\n}\n"
  },
  {
    "path": "common/googlecloud/src/main/java/org/jclouds/googlecloud/options/ListOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloud.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\n/** Base controls for listing resources in google cloud products. */\npublic abstract class ListOptions extends BaseHttpRequestOptions {\n   /**  Sets Maximum count of results to be returned. Maximum value is product-specific. */\n   public ListOptions maxResults(Integer maxResults) {\n      this.queryParameters.put(\"maxResults\", checkNotNull(maxResults, \"maxResults\").toString());\n      return this;\n   }\n}\n"
  },
  {
    "path": "common/googlecloud/src/test/java/org/jclouds/googlecloud/config/ClientEmailTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloud.config;\n\nimport static org.jclouds.googlecloud.config.CurrentProject.ClientEmail.toProjectNumber;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.googlecloud.config.CurrentProject.ClientEmail;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ClientEmailTest\")\npublic class ClientEmailTest {\n\n   @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = \"Client email foo is malformed. Should be \"\n         + ClientEmail.DESCRIPTION)\n   public void testMalformedClientEmail() {\n      toProjectNumber(\"foo\");\n   }\n\n   public void testParseClientId() {\n      assertEquals(toProjectNumber(\"1234567890@developer.gserviceaccount.com\"), \"1234567890\");\n   }\n\n   public void testParseClientIdWithExtendedUid() {\n      assertEquals(toProjectNumber(\"1234567890-project_foo@developer.gserviceaccount.com\"), \"1234567890\");\n   }\n\n   public void testParseProjectIdFromIAMAccount() {\n      assertEquals(toProjectNumber(\"account@project_id.iam.gserviceaccount.com\"), \"project_id\");\n   }\n\n   public void testParseCompanyAndProjectIdFromIAMAccount() {\n      assertEquals(toProjectNumber(\"account@project_id.company.com.iam.gserviceaccount.com\"), \"company.com:project_id\");\n   }\n}\n"
  },
  {
    "path": "common/googlecloud/src/test/java/org/jclouds/googlecloud/internal/TestProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloud.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Throwables.propagate;\nimport static org.jclouds.googlecloud.config.GoogleCloudProperties.CREDENTIAL_TYPE;\nimport static org.jclouds.googlecloud.config.GoogleCloudProperties.PROJECT_NAME;\nimport static org.jclouds.oauth.v2.config.CredentialType.P12_PRIVATE_KEY_CREDENTIALS;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.nio.charset.Charset;\nimport java.util.Properties;\n\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.googlecloud.GoogleCredentialsFromJson;\nimport org.jclouds.oauth.v2.config.CredentialType;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.io.Files;\n\n/** Changes to this mandate changes to pom.xml and README.md */\npublic final class TestProperties {\n\n   public static Properties apply(String provider, Properties props) {\n      setIfTestSystemPropertyPresent(props, PROJECT_NAME);\n      setIfTestSystemPropertyPresent(props, CREDENTIAL_TYPE);\n      if (props.containsKey(CREDENTIAL_TYPE)\n            && CredentialType.fromValue(props.getProperty(CREDENTIAL_TYPE)) == P12_PRIVATE_KEY_CREDENTIALS) {\n         setCredential(props, provider + \".credential\");\n      }\n      return props;\n   }\n\n   // TODO: make BaseApiLiveTest.setIfTestSystemPropertyPresent static\n   private static String setIfTestSystemPropertyPresent(Properties overrides, String key) {\n      if (System.getProperties().containsKey(\"test.\" + key)) {\n         String val = System.getProperty(\"test.\" + key);\n         overrides.setProperty(key, val);\n         return val;\n      }\n      return null;\n   }\n\n   // TODO: move to jclouds-core\n   public static String setCredential(Properties overrides, String key) {\n      String val = null;\n      String credentialFromFile = null;\n      String testKey = \"test.\" + key;\n\n      if (System.getProperties().containsKey(testKey)) {\n         val = System.getProperty(testKey);\n      }\n      checkNotNull(val,\n            \"the property %s must be set (pem private key file path or private key as a string)\", testKey);\n\n      if (val.startsWith(\"-----BEGIN\")) {\n         return val;\n      }\n\n      try {\n         credentialFromFile = Files.toString(new File(val), Charsets.UTF_8);\n      } catch (IOException e) {\n         throw propagate(e);\n      }\n      overrides.setProperty(key, credentialFromFile);\n      return credentialFromFile;\n   }\n\n   /*\n    * Provides an easy way to pass in credentials using the json-key format.\n    * Just provide the path to the .json file as the system property test.google-cloud.json-key\n    * and this extracts and sets identity  and credentials from the json.\n    */\n   public static void setGoogleCredentialsFromJson(String provider) {\n      String key = \"test.google-cloud.json-key\";\n      if (System.getProperties().containsKey(key)) {\n         String val = System.getProperty(key);\n         try {\n            String fileContents = Files.toString(new File(val), Charset.defaultCharset());\n            Credentials creds = new GoogleCredentialsFromJson(fileContents).get();\n            System.setProperty(\"test.\" + provider + \".identity\", creds.identity);\n            System.setProperty(\"test.\" + provider + \".credential\", creds.credential);\n         } catch (IOException e) {\n            throw propagate(e);\n         }\n      }\n   }\n\n   private TestProperties() {\n   }\n}\n"
  },
  {
    "path": "common/openstack/README.txt",
    "content": "#\n# The jclouds provider for Rackspace (http://www.rackspace.com/).\n#\n# TODO: Implementation status.\n# TODO: Supported features.\n# See http://code.google.com/p/jclouds/wiki/QuickStartRackspace for example usage.\n"
  },
  {
    "path": "common/openstack/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.openstack.*;version=\"${project.version}\";-noimport:=true"
  },
  {
    "path": "common/openstack/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n\n  <groupId>org.apache.jclouds.common</groupId>\n  <artifactId>openstack-common</artifactId>\n  <name>jclouds OpenStack Components Core</name>\n  <description>jclouds Core components to access OpenStack apis</description>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n  </dependencies>\n\n</project>\n"
  },
  {
    "path": "common/openstack/src/main/java/org/jclouds/openstack/config/OpenStackAuthenticationModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.config;\n\nimport static com.google.common.base.Suppliers.memoizeWithExpiration;\nimport static org.jclouds.rest.config.BinderUtils.bindHttpApi;\n\nimport java.util.Date;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.TimeoutException;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpRetryHandler;\nimport org.jclouds.http.annotation.ClientError;\nimport org.jclouds.location.Provider;\nimport org.jclouds.openstack.domain.AuthenticationResponse;\nimport org.jclouds.openstack.functions.URIFromAuthenticationResponseForService;\nimport org.jclouds.openstack.handlers.RetryOnRenew;\nimport org.jclouds.openstack.internal.Authentication;\nimport org.jclouds.openstack.internal.OpenStackAuthClient;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Provides;\nimport com.google.inject.assistedinject.FactoryModuleBuilder;\n\n/**\n * Configures the Rackspace authentication service connection, including logging and http transport.\n */\npublic class OpenStackAuthenticationModule extends AbstractModule {\n\n   @Override\n   protected void configure() {\n      // OpenStackAuthClient is used directly for filters and retry handlers, so let's bind it explicitly\n      bindHttpApi(binder(), OpenStackAuthClient.class);\n      install(new FactoryModuleBuilder().build(URIFromAuthenticationResponseForService.Factory.class));\n      bind(HttpRetryHandler.class).annotatedWith(ClientError.class).to(RetryOnRenew.class);\n   }\n\n   @Provides\n   @Singleton\n   @Authentication\n   protected final Supplier<String> guiceProvideAuthenticationTokenCache(final Supplier<AuthenticationResponse> supplier)\n            throws InterruptedException, ExecutionException, TimeoutException {\n      return provideAuthenticationTokenCache(supplier);\n   }\n\n   /**\n    * borrowing concurrency code to ensure that caching takes place properly\n    */\n   protected Supplier<String> provideAuthenticationTokenCache(final Supplier<AuthenticationResponse> supplier)\n            throws InterruptedException, ExecutionException, TimeoutException {\n      return new Supplier<String>() {\n         @Override\n         public String get() {\n            return supplier.get().getAuthToken();\n         }\n      };\n   }\n\n   @Singleton\n   public static class GetAuthenticationResponse extends CacheLoader<Credentials, AuthenticationResponse> {\n      private final OpenStackAuthClient client;\n\n      @Inject\n      public GetAuthenticationResponse(final OpenStackAuthClient client) {\n         this.client = client;\n      }\n\n      @Override\n      public AuthenticationResponse load(Credentials input) {\n         return client.authenticate(input.identity, input.credential);\n      }\n\n      @Override\n      public String toString() {\n         return \"authenticate()\";\n      }\n\n   }\n\n   @Provides\n   @Singleton\n   public final LoadingCache<Credentials, AuthenticationResponse> provideAuthenticationResponseCache(\n         GetAuthenticationResponse getAuthenticationResponse) {\n      return CacheBuilder.newBuilder().expireAfterWrite(23, TimeUnit.HOURS).build(getAuthenticationResponse);\n   }\n\n   @Provides\n   @Singleton\n   protected final Supplier<AuthenticationResponse> provideAuthenticationResponseSupplier(\n         final LoadingCache<Credentials, AuthenticationResponse> cache, @Provider final Supplier<Credentials> creds) {\n      return new Supplier<AuthenticationResponse>() {\n         @Override\n         public AuthenticationResponse get() {\n            return cache.getUnchecked(creds.get());\n         }\n      };\n   }\n\n   @Provides\n   @Singleton\n   @TimeStamp\n   protected final Supplier<Date> guiceProvideCacheBusterDate() {\n      return provideCacheBusterDate();\n   }\n\n   protected Supplier<Date> provideCacheBusterDate() {\n      return memoizeWithExpiration(new Supplier<Date>() {\n         @Override\n         public Date get() {\n            return new Date();\n         }\n      }, 1, TimeUnit.SECONDS);\n   }\n\n}\n"
  },
  {
    "path": "common/openstack/src/main/java/org/jclouds/openstack/domain/AuthenticationResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.net.URI;\nimport java.util.Map;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ImmutableMap;\n\npublic class AuthenticationResponse {\n   private final String authToken;\n   private final Map<String, URI> services;\n\n   public AuthenticationResponse(String authToken, Map<String, URI> services) {\n      this.authToken = checkNotNull(authToken, \"authToken\");\n      this.services = ImmutableMap.copyOf(checkNotNull(services, \"services\"));\n   }\n\n   public Map<String, URI> getServices() {\n      return services;\n   }\n   \n   public String getAuthToken() {\n      return authToken;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(authToken, services);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (obj == null)\n         return false;\n      if (!(obj instanceof AuthenticationResponse)) {\n         return false;\n      }\n      AuthenticationResponse that = (AuthenticationResponse) obj;\n      return Objects.equal(this.authToken, that.authToken)\n         && Objects.equal(this.services, that.services);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).add(\"authToken\", authToken).add(\"services\", services).toString();\n   }\n\n}\n"
  },
  {
    "path": "common/openstack/src/main/java/org/jclouds/openstack/domain/Link.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.net.URI;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.Objects;\n\n/**\n * For convenience, resources contain links to themselves. This allows a client to easily obtain a\n * resource URIs rather than to construct them.\n * \n * @see <a href= \"http://docs.openstack.org/api/openstack-compute/1.1/content/LinksReferences.html\"\n *      />\n */\npublic class Link {\n   /**\n    * Relations associated with resources.\n    */\n   public static enum Relation {\n      /**\n       * a versioned link to the resource. These links should be used in cases where the link will\n       * be followed immediately.\n       */\n      SELF,\n      /**\n       * a permanent link to a resource that is appropriate for long term storage.\n       */\n      BOOKMARK,\n      /**\n       * \n       */\n      DESCRIBEDBY,\n      /**\n       * an alternate representation of the resource. For example, an OpenStack Compute image may\n       * have an alternate representation in the OpenStack Image service.\n       */\n      ALTERNATE,\n      /**\n       * the value returned by the OpenStack service was not recognized.\n       */\n      UNRECOGNIZED;\n\n      public String value() {\n         return name().toLowerCase();\n      }\n\n      public static Relation fromValue(String v) {\n         try {\n            return valueOf(v.toUpperCase());\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n\n   }\n\n   public static Link create(Relation relation, URI href) {\n      return new Link(relation, null, href);\n   }\n   \n   public static Link create(Relation relation, String type, URI href) {\n      return new Link(relation, type, href);\n   }\n   \n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().fromLink(this);\n   }\n\n   public static class Builder {\n      protected Relation relation;\n      protected String type;\n      protected URI href;\n\n      /**\n       * @see Link#getRelation()\n       */\n      public Builder relation(Relation relation) {\n         this.relation = checkNotNull(relation, \"relation\");\n         return this;\n      }\n\n      /**\n       * @see Link#getType()\n       */\n      public Builder type(String type) {\n         this.type = type;\n         return this;\n      }\n      \n      /**\n       * @see Link#getHref()\n       */\n      public Builder href(URI href) {\n         this.href = checkNotNull(href, \"href\");\n         return this;\n      }\n\n      public Link build() {\n         return new Link(relation, type, href);\n      }\n      \n      public Builder fromLink(Link from) {\n         return relation(from.getRelation()).type(from.getType()).href(from.getHref());\n      }\n   }\n  \n   @Named(\"rel\")\n   protected Relation relation;\n   protected String type;\n   protected URI href;\n\n   @ConstructorProperties({\"rel\", \"type\", \"href\"})\n   protected Link(Relation relation, @Nullable String type, URI href) {\n      this.relation = checkNotNull(relation, \"relation\");\n      this.type = type;\n      this.href = checkNotNull(href, \"href\");\n   }\n\n   /**\n    * There are three kinds of link relations associated with resources. A self link contains a\n    * versioned link to the resource. These links should be used in cases where the link will be\n    * followed immediately. A bookmark link provides a permanent link to a resource that is\n    * appropriate for long term storage. An alternate link can contain an alternate representation\n    * of the resource. For example, an OpenStack Compute image may have an alternate representation\n    * in the OpenStack Image service. Note that the type attribute here is used to provide a hint as\n    * to the type of representation to expect when following the link.\n    * \n    * @return the relation of the resource in the current OpenStack deployment\n    */\n   public Relation getRelation() {\n      return relation;\n   }\n   \n   /**\n    * @return the type of the resource or null if not specified\n    */\n   @Nullable\n   public String getType() {\n      return type;\n   }\n   \n   /**\n    * @return the href of the resource\n    */\n   public URI getHref() {\n      return href;\n   }\n\n   @Override\n   public boolean equals(Object object) {\n      if (this == object) {\n         return true;\n      }\n      if (object instanceof Link) {\n         final Link other = Link.class.cast(object);\n         return equal(relation, other.relation) && equal(type, other.type) && equal(href, other.href);\n      } else {\n         return false;\n      }\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(relation, type, href);\n   }\n\n   @Override\n   public String toString() {\n      return toStringHelper(\"\").add(\"relation\", relation).add(\"type\", type).add(\"href\", href).toString();\n   }\n\n}\n"
  },
  {
    "path": "common/openstack/src/main/java/org/jclouds/openstack/domain/Resource.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Collections;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Resource found in a paginated collection\n * \n * @see <a href=\n *      \"http://docs.openstack.org/api/openstack-compute/1.1/content/Paginated_Collections-d1e664.html\"\n *      />\n */\npublic class Resource implements Comparable<Resource> {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromResource(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>>  {\n      protected abstract T self();\n\n      private String id;\n      private String name;\n      private Set<Link> links = ImmutableSet.of();\n\n      /**\n       * @see Resource#getId()\n       */\n      public T id(String id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see Resource#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /**\n       * @see Resource#getLinks()\n       */\n      public T links(Link... links) {\n         return links(ImmutableSet.copyOf(checkNotNull(links, \"links\")));\n      }\n\n      /**\n       * @see Resource#getLinks()\n       */\n      public T links(Set<Link> links) {\n         this.links = links;\n         return self();\n      }\n\n      public Resource build() {\n         return new Resource(id, name, links);\n      }\n\n      public T fromResource(Resource in) {\n         return id(in.getId()).name(in.getName()).links(in.getLinks());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private String id;\n   private String name;\n   private Set<Link> links = ImmutableSet.of();\n\n   protected Resource(String id, @Nullable String name, @Nullable Set<Link> links) {\n      this.id = checkNotNull(id);\n      this.name = name;\n      this.links = links == null ? ImmutableSet.<Link>of() : ImmutableSet.copyOf(links);\n   }\n   \n   /**\n    * When providing an ID, it is assumed that the resource exists in the current OpenStack\n    * deployment\n    *\n    * @return the id of the resource in the current OpenStack deployment\n    */\n   public String getId() {\n      return id;\n   }\n\n   /**\n    * @return the name of the resource\n    */\n   @Nullable\n   public String getName() {\n      return name;\n   }\n\n   /**\n    * @return the links of the id address allocated to the new server\n    */\n   public Set<Link> getLinks() {\n      return Collections.unmodifiableSet(this.links);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, name, links);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Resource that = Resource.class.cast(obj);\n      return Objects.equal(this.getId(), that.getId())\n            && Objects.equal(this.name, that.name)\n            && Objects.equal(this.links, that.links);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(\"\")\n            .add(\"id\", getId())\n            .add(\"name\", name)\n            .add(\"links\", links);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n   @Override\n   public int compareTo(Resource that) {\n      if (that == null)\n         return 1;\n      if (this == that)\n         return 0;\n      return this.getId().compareTo(that.getId());\n   }\n\n}\n"
  },
  {
    "path": "common/openstack/src/main/java/org/jclouds/openstack/filters/AddTimestampQuery.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.filters;\n\nimport java.util.Date;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpRequestFilter;\n\nimport com.google.common.base.Supplier;\n\n/**\n * Adds a timestamp to the query line so that cache is invalidated.\n */\n@Singleton\npublic class AddTimestampQuery implements HttpRequestFilter {\n   private final Supplier<Date> dateProvider;\n\n   @Inject\n   public AddTimestampQuery(@TimeStamp Supplier<Date> dateProvider) {\n      this.dateProvider = dateProvider;\n   }\n\n   @Override\n   public HttpRequest filter(HttpRequest request) throws HttpException {\n      return request.toBuilder().replaceQueryParam(\"now\", dateProvider.get().getTime() + \"\").build();\n   }\n\n}\n"
  },
  {
    "path": "common/openstack/src/main/java/org/jclouds/openstack/filters/AuthenticateRequest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.filters;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpRequestFilter;\nimport org.jclouds.openstack.internal.Authentication;\nimport org.jclouds.openstack.reference.AuthHeaders;\n\nimport com.google.common.base.Supplier;\n\n/**\n * Signs the Rackspace request. This will update the Authentication Token before 24 hours is up.\n */\n@Singleton\npublic class AuthenticateRequest implements HttpRequestFilter {\n\n   private final Supplier<String> authTokenProvider;\n\n   @Inject\n   public AuthenticateRequest(@Authentication Supplier<String> authTokenProvider) {\n      this.authTokenProvider = authTokenProvider;\n   }\n\n   @Override\n   public HttpRequest filter(HttpRequest request) throws HttpException {\n      return request.toBuilder().replaceHeader(AuthHeaders.AUTH_TOKEN, authTokenProvider.get()).build();\n   }\n\n}\n"
  },
  {
    "path": "common/openstack/src/main/java/org/jclouds/openstack/functions/ParseAuthenticationResponseFromHeaders.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.http.HttpUtils.releasePayload;\nimport static org.jclouds.http.Uris.uriBuilder;\nimport static org.jclouds.openstack.reference.AuthHeaders.AUTH_TOKEN;\n\nimport java.net.URI;\nimport java.util.Map.Entry;\n\nimport jakarta.annotation.Resource;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.openstack.domain.AuthenticationResponse;\nimport org.jclouds.openstack.reference.AuthHeaders;\nimport org.jclouds.rest.InvocationContext;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMap.Builder;\n\n/**\n * This parses {@link AuthenticationResponse} from HTTP headers.\n */\npublic class ParseAuthenticationResponseFromHeaders implements Function<HttpResponse, AuthenticationResponse>,\n         InvocationContext<ParseAuthenticationResponseFromHeaders> {\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   private String hostToReplace;\n\n   /**\n    * parses the http response headers to create a new {@link AuthenticationResponse} object.\n    */\n   public AuthenticationResponse apply(HttpResponse from) {\n      releasePayload(from);\n\n      // HTTP headers are case insensitive (RFC 2616) so we must allow for that when looking an header names for the URL keyword\n      Builder<String, URI> builder = ImmutableMap.builder();\n      for (Entry<String, String> entry : from.getHeaders().entries()) {\n         String header = entry.getKey();\n         if (header.equalsIgnoreCase(AuthHeaders.STORAGE_URL)) {\n            builder.put(AuthHeaders.STORAGE_URL, getURI(entry.getValue()));\n         } else if (header.equalsIgnoreCase(AuthHeaders.SERVER_MANAGEMENT_URL)) {\n            builder.put(AuthHeaders.SERVER_MANAGEMENT_URL, getURI(entry.getValue()));\n         } else if (header.equalsIgnoreCase(AuthHeaders.CDN_MANAGEMENT_URL)) {\n            builder.put(AuthHeaders.CDN_MANAGEMENT_URL, getURI(entry.getValue()));\n         }\n      }\n      AuthenticationResponse response = new AuthenticationResponse(checkNotNull(from.getFirstHeaderOrNull(AUTH_TOKEN),\n               AUTH_TOKEN), builder.build());\n      logger.debug(\"will connect to: \", response);\n      return response;\n   }\n\n   // TODO: find the swift configuration or bug related to returning localhost\n   protected URI getURI(String headerValue) {\n      if (headerValue == null)\n         return null;\n      URI toReturn = URI.create(headerValue);\n      if (!\"127.0.0.1\".equals(toReturn.getHost()))\n         return toReturn;\n      return uriBuilder(toReturn).host(hostToReplace).build();\n   }\n\n   @Override\n   public ParseAuthenticationResponseFromHeaders setContext(HttpRequest request) {\n      String host = request.getEndpoint().getHost();\n      return setHostToReplace(host);\n   }\n\n   @VisibleForTesting\n   ParseAuthenticationResponseFromHeaders setHostToReplace(String hostToReplace) {\n      this.hostToReplace = hostToReplace;\n      return this;\n   }\n}\n"
  },
  {
    "path": "common/openstack/src/main/java/org/jclouds/openstack/functions/URIFromAuthenticationResponseForService.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.functions;\n\nimport java.net.URI;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.openstack.domain.AuthenticationResponse;\n\nimport com.google.common.base.Supplier;\nimport com.google.inject.assistedinject.Assisted;\n\npublic class URIFromAuthenticationResponseForService implements Supplier<URI> {\n   public interface Factory {\n      URIFromAuthenticationResponseForService create(String service);\n   }\n\n   private final Supplier<AuthenticationResponse> auth;\n   private final String service;\n\n   @Inject\n   public URIFromAuthenticationResponseForService(Supplier<AuthenticationResponse> auth, @Assisted String service) {\n      this.auth = auth;\n      this.service = service;\n   }\n\n   @Override\n   public URI get() {\n      return auth.get().getServices().get(service);\n   }\n\n   @Override\n   public String toString() {\n      return \"getURIForService(\" + service + \")\";\n   }\n}\n"
  },
  {
    "path": "common/openstack/src/main/java/org/jclouds/openstack/handlers/RetryOnRenew.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.handlers;\n\nimport java.util.concurrent.TimeUnit;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\n\nimport org.jclouds.Constants;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpRetryHandler;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.openstack.domain.AuthenticationResponse;\nimport org.jclouds.openstack.reference.AuthHeaders;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.cache.Cache;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.Multimap;\nimport com.google.common.util.concurrent.Uninterruptibles;\nimport com.google.inject.Inject;\nimport com.google.inject.Singleton;\n\n/**\n * This will parse and set an appropriate exception on the command object.\n */\n@Singleton\npublic class RetryOnRenew implements HttpRetryHandler {\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   @VisibleForTesting\n   @Inject(optional = true)\n   @Named(Constants.PROPERTY_MAX_RETRIES)\n   static int NUM_RETRIES = 5;\n\n   private final LoadingCache<Credentials, AuthenticationResponse> authenticationResponseCache;\n\n   /*\n    * The reason retries need to be tracked is that it is possible that a token\n    * can be expired at any time. The reason we track by request is that only\n    * some requests might return a 401 (such as temporary URLs). However\n    * consistent failures of the magnitude this code tracks should indicate a\n    * problem.\n    */\n   private static final Cache<HttpCommand, Integer> retryCountMap = CacheBuilder\n         .newBuilder().expireAfterWrite(5, TimeUnit.MINUTES).build();\n\n   @Inject\n   protected RetryOnRenew(LoadingCache<Credentials, AuthenticationResponse> authenticationResponseCache) {\n      this.authenticationResponseCache = authenticationResponseCache;\n   }\n\n   @Override\n   public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) {\n      boolean retry = false; // default\n      switch (response.getStatusCode()) {\n         case 401:\n            // Do not retry on 401 from authentication request\n            Multimap<String, String> headers = command.getCurrentRequest().getHeaders();\n            if (headers != null && headers.containsKey(AuthHeaders.AUTH_USER)\n                     && headers.containsKey(AuthHeaders.AUTH_KEY) && !headers.containsKey(AuthHeaders.AUTH_TOKEN)) {\n               retry = false;\n            } else {\n               // This is not an authentication request returning 401\n               // Check if we already had seen this request\n               Integer count = retryCountMap.getIfPresent(command);\n\n               if (count == null) {\n                  // First time this non-authentication request failed\n                  logger.debug(\"invalidating authentication token - first time for %s\", command);\n                  retryCountMap.put(command, 1);\n                  authenticationResponseCache.invalidateAll();\n                  retry = true;\n               } else {\n                  // This request has failed before\n                  if (count + 1 >= NUM_RETRIES) {\n                     logger.debug(\"too many 401s - giving up after: %s for %s\", count, command);\n                     retry = false;\n                  } else {\n                     // Retry just in case\n                     logger.debug(\"invalidating authentication token - retry %s for %s\", count, command);\n                     retryCountMap.put(command, count + 1);\n                     // Wait between retries\n                     authenticationResponseCache.invalidateAll();\n                     Uninterruptibles.sleepUninterruptibly(5, TimeUnit.SECONDS);\n                     retry = true;\n                  }\n               }\n            }\n         break;\n      }\n      return retry;\n   }\n\n}\n"
  },
  {
    "path": "common/openstack/src/main/java/org/jclouds/openstack/internal/Authentication.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.internal;\n\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\nimport jakarta.inject.Qualifier;\n\n/**\n * Represents a component related to Rackspace Cloud Files.\n * \n * @see <a href=\"http://www.rackspacecloud.com/cf-devguide-20090311.pdf\" />\n */\n@Retention(value = RetentionPolicy.RUNTIME)\n@Target(value = { ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })\n@Qualifier\npublic @interface Authentication {\n\n}\n"
  },
  {
    "path": "common/openstack/src/main/java/org/jclouds/openstack/internal/OpenStackAuthClient.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.internal;\nimport java.io.Closeable;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.HeaderParam;\nimport jakarta.ws.rs.Path;\n\nimport org.jclouds.Constants;\nimport org.jclouds.openstack.domain.AuthenticationResponse;\nimport org.jclouds.openstack.functions.ParseAuthenticationResponseFromHeaders;\nimport org.jclouds.openstack.reference.AuthHeaders;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.VirtualHost;\n\nimport com.google.inject.name.Named;\n\n/**\n * Provides access to OpenStack auth.\n */\n@Path(\"/v{\" + Constants.PROPERTY_API_VERSION + \"}\")\n@VirtualHost\npublic interface OpenStackAuthClient  extends Closeable {\n\n   @Named(\"authenticate\")\n   @GET\n   @Consumes\n   @ResponseParser(ParseAuthenticationResponseFromHeaders.class)\n   AuthenticationResponse authenticate(@HeaderParam(AuthHeaders.AUTH_USER) String user,\n         @HeaderParam(AuthHeaders.AUTH_KEY) String key);\n\n   @Named(\"authenticate\")\n   @GET\n   @Consumes\n   @ResponseParser(ParseAuthenticationResponseFromHeaders.class)\n   AuthenticationResponse authenticateStorage(@HeaderParam(AuthHeaders.STORAGE_USER) String user,\n         @HeaderParam(AuthHeaders.STORAGE_PASS) String key);\n}\n"
  },
  {
    "path": "common/openstack/src/main/java/org/jclouds/openstack/keystone/v1_1/AuthenticationClient.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v1_1;\n\nimport java.io.Closeable;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.openstack.keystone.v1_1.binders.BindCredentialsToJsonPayload;\nimport org.jclouds.openstack.keystone.v1_1.domain.Auth;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.SelectJson;\n\n/**\n * Provides access to the Keystone v1.1 Service API.\n */\n@Consumes(MediaType.APPLICATION_JSON)\n@Path(\"/v1.1\")\npublic interface AuthenticationClient extends Closeable {\n\n   /**\n    * Authenticate to generate a token.\n    *\n    * @return access with token\n    */\n   @POST\n   @SelectJson(\"auth\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Path(\"/auth\")\n   @MapBinder(BindCredentialsToJsonPayload.class)\n   Auth authenticate(@PayloadParam(\"username\") String username, @PayloadParam(\"key\") String key);\n}\n"
  },
  {
    "path": "common/openstack/src/main/java/org/jclouds/openstack/keystone/v1_1/binders/BindCredentialsToJsonPayload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v1_1.binders;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.json.Json;\nimport org.jclouds.rest.MapBinder;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport com.google.common.collect.ImmutableMap;\n\n@Singleton\npublic class BindCredentialsToJsonPayload extends BindToJsonPayload implements MapBinder {\n   @Inject\n   public BindCredentialsToJsonPayload(Json jsonBinder) {\n      super(jsonBinder);\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object toBind) {\n      throw new IllegalStateException(\"BindCredentialsToJsonPayload needs parameters\");\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      return super.bindToRequest(request, ImmutableMap.of(\"credentials\", postParams));\n   }\n\n}\n"
  },
  {
    "path": "common/openstack/src/main/java/org/jclouds/openstack/keystone/v1_1/config/AuthenticationServiceModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v1_1.config;\n\nimport static org.jclouds.rest.config.BinderUtils.bindHttpApi;\nimport static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL;\n\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.TimeoutException;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpRetryHandler;\nimport org.jclouds.http.annotation.ClientError;\nimport org.jclouds.location.Provider;\nimport org.jclouds.location.suppliers.ImplicitRegionIdSupplier;\nimport org.jclouds.location.suppliers.RegionIdToURISupplier;\nimport org.jclouds.openstack.internal.Authentication;\nimport org.jclouds.openstack.keystone.v1_1.AuthenticationClient;\nimport org.jclouds.openstack.keystone.v1_1.domain.Auth;\nimport org.jclouds.openstack.keystone.v1_1.handlers.RetryOnRenew;\nimport org.jclouds.openstack.keystone.v1_1.suppliers.RegionIdToURIFromAuthForServiceSupplier;\nimport org.jclouds.openstack.keystone.v1_1.suppliers.V1DefaultRegionIdSupplier;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.name.Named;\nimport com.google.inject.Provides;\nimport com.google.inject.assistedinject.FactoryModuleBuilder;\n\npublic class AuthenticationServiceModule extends AbstractModule {\n\n   @Override\n   protected void configure() {\n      // ServiceClient is used directly for filters and retry handlers, so let's bind it explicitly\n      bindHttpApi(binder(), AuthenticationClient.class);\n      install(new FactoryModuleBuilder().implement(RegionIdToURISupplier.class,\n               RegionIdToURIFromAuthForServiceSupplier.class).build(RegionIdToURISupplier.Factory.class));\n      install(new FactoryModuleBuilder().implement(ImplicitRegionIdSupplier.class, V1DefaultRegionIdSupplier.class)\n               .build(V1DefaultRegionIdSupplier.Factory.class));\n      bind(HttpRetryHandler.class).annotatedWith(ClientError.class).to(RetryOnRenew.class);\n   }\n\n   /**\n    * borrowing concurrency code to ensure that caching takes place properly\n    */\n   @Provides\n   @Singleton\n   @Authentication\n   protected final Supplier<String> provideAuthenticationTokenCache(final Supplier<Auth> supplier)\n            throws InterruptedException, ExecutionException, TimeoutException {\n      return new Supplier<String>() {\n         public String get() {\n            return supplier.get().getToken().getId();\n         }\n      };\n   }\n\n   @Singleton\n   public static class GetAuth extends CacheLoader<Credentials, Auth> {\n\n      private final AuthenticationClient client;\n\n      @Inject\n      public GetAuth(final AuthenticationClient client) {\n         this.client = client;\n      }\n\n      @Override\n      public Auth load(Credentials input) {\n         return client.authenticate(input.identity, input.credential);\n      }\n\n      @Override\n      public String toString() {\n         return \"authenticate()\";\n      }\n   }\n\n   @Provides\n   @Singleton\n   protected final LoadingCache<Credentials, Auth> provideAuthCache(GetAuth getAuth,\n         @Named(PROPERTY_SESSION_INTERVAL) long sessionInterval) {\n      return CacheBuilder.newBuilder().expireAfterWrite(sessionInterval, TimeUnit.SECONDS).build(getAuth);\n   }\n\n   @Provides\n   @Singleton\n   protected final Supplier<Auth> provideAuthSupplier(final LoadingCache<Credentials, Auth> cache,\n         @Provider final Supplier<Credentials> creds) {\n      return new Supplier<Auth>() {\n         @Override\n         public Auth get() {\n            return cache.getUnchecked(creds.get());\n         }\n      };\n   }\n}\n"
  },
  {
    "path": "common/openstack/src/main/java/org/jclouds/openstack/keystone/v1_1/domain/Auth.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v1_1.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.Multimap;\n\n/**\n * TODO\n * \n * @see <a href=\n *      \"http://docs.rackspace.com/loadbalancers/api/v1.0/clb-devguide/content/Endpoint_Access_Endpoints-d1e517.html\"\n *      />\n */\npublic class Auth implements Comparable<Auth> {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().fromAccess(this);\n   }\n\n   public static class Builder {\n      protected Token token;\n      protected Multimap<String, Endpoint> serviceCatalog = ImmutableMultimap.of();\n\n      /**\n       * @see Auth#getToken()\n       */\n      public Builder token(Token token) {\n         this.token = checkNotNull(token, \"token\");\n         return this;\n      }\n\n      /**\n       * @see Auth#getServiceCatalog()\n       */\n      public Builder serviceCatalog(Multimap<String, Endpoint> serviceCatalog) {\n         this.serviceCatalog = ImmutableMultimap.copyOf(checkNotNull(serviceCatalog, \"serviceCatalog\"));\n         return this;\n      }\n\n      public Auth build() {\n         return new Auth(token, serviceCatalog);\n      }\n\n      public Builder fromAccess(Auth from) {\n         return token(from.getToken()).serviceCatalog(from.getServiceCatalog());\n      }\n   }\n  \n   protected final Token token;\n   protected final Multimap<String, Endpoint> serviceCatalog;\n\n   public Auth(Token token, Multimap<String, Endpoint> serviceCatalog) {\n      this.token = checkNotNull(token, \"token\");\n      this.serviceCatalog = ImmutableMultimap.copyOf(checkNotNull(serviceCatalog, \"serviceCatalog\"));\n   }\n\n   /**\n    * TODO\n    */\n   public Token getToken() {\n      return token;\n   }\n\n   /**\n    * TODO\n    */\n   public Multimap<String, Endpoint> getServiceCatalog() {\n      return serviceCatalog;\n   }\n\n   @Override\n   public boolean equals(Object object) {\n      if (this == object) {\n         return true;\n      }\n      if (object instanceof Auth) {\n         final Auth other = Auth.class.cast(object);\n         return equal(token, other.token) && equal(serviceCatalog, other.serviceCatalog);\n      } else {\n         return false;\n      }\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(token, serviceCatalog);\n   }\n\n   @Override\n   public String toString() {\n      return toStringHelper(\"\").add(\"token\", token).add(\"serviceCatalog\", serviceCatalog).toString();\n   }\n\n   @Override\n   public int compareTo(Auth that) {\n      if (that == null)\n         return 1;\n      if (this == that)\n         return 0;\n      return this.token.compareTo(that.token);\n   }\n\n}\n"
  },
  {
    "path": "common/openstack/src/main/java/org/jclouds/openstack/keystone/v1_1/domain/Endpoint.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v1_1.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.net.URI;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.Objects;\n\n/**\n * An network-accessible address, usually described by URL, where a service may\n * be accessed. If using an extension for templates, you can create an endpoint\n * template, which represents the templates of all the consumable services that\n * are available across the regions.\n * \n * @see <a href=\n *      \"http://docs.rackspace.com/loadbalancers/api/v1.0/clb-devguv1Defaulte/content/Authentication-d1e699.html#Authenticate-d1e171\"\n *      />\n */\npublic class Endpoint implements Comparable<Endpoint> {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().fromEndpoint(this);\n   }\n\n   public static class Builder {\n\n      protected boolean v1Default;\n      protected String region;\n      protected URI publicURL;\n      protected URI internalURL;\n\n      /**\n       * @see Endpoint#isV1Default()\n       */\n      public Builder v1Default(boolean v1Default) {\n         this.v1Default = v1Default;\n         return this;\n      }\n\n      /**\n       * @see Endpoint#getRegion()\n       */\n      public Builder region(String region) {\n         this.region = checkNotNull(region, \"region\");\n         return this;\n      }\n\n      /**\n       * @see Endpoint#getPublicURL()\n       */\n      public Builder publicURL(URI publicURL) {\n         this.publicURL = checkNotNull(publicURL, \"publicURL\");\n         return this;\n      }\n\n      /**\n       * @see Endpoint#getTenantId()\n       */\n      public Builder internalURL(@Nullable URI internalURL) {\n         this.internalURL = internalURL;\n         return this;\n      }\n\n      public Endpoint build() {\n         return new Endpoint(v1Default, region, publicURL, internalURL);\n      }\n\n      public Builder fromEndpoint(Endpoint from) {\n         return v1Default(from.isV1Default()).region(from.getRegion()).publicURL(from.getPublicURL())\n               .internalURL(from.getInternalURL());\n      }\n   }\n\n   protected Endpoint() {\n      // we want serializers like Gson to work w/o using sun.misc.Unsafe,\n      // prohibited in GAE. This also implies fields are not final.\n      // see http://code.google.com/p/jclouds/issues/detail?id=925\n   }\n  \n   protected boolean v1Default;\n   protected String region;\n   protected URI publicURL;\n   protected URI internalURL;\n\n   protected Endpoint(boolean v1Default, @Nullable String region, @Nullable  URI publicURL, @Nullable URI internalURL) {\n      this.v1Default = v1Default;\n      this.region = region;\n      this.publicURL = publicURL;\n      this.internalURL = internalURL;\n   }\n\n   /**\n    * The v1Default attribute denotes that an endpoint is being returned in\n    * version 1.0 of the Cloud Authentication Service. The default value of\n    * v1Default is false; clients should assume the value is false when the\n    * attribute is missing. Auth 1.0 does not offer support for regional\n    * endpoints and therefore only returns one endpoint per service. Resources\n    * stored in endpoints where v1Default is false will not be seen by Auth 1.0\n    * clients.\n    * \n    * @return whether this endpoint is visible to v1.0 clients\n    */\n   public boolean isV1Default() {\n      return v1Default;\n   }\n\n   /**\n    * A service may expose endpoints in different regions. Regional endpoints\n    * allow clients to provision resources in a manner that provides high\n    * availability. <br/>\n    * <h3>Note</h3> Some services are not region-specific. These services supply\n    * a single non-regional endpoint and do not provide access to internal URLs.\n    * \n    * @return the region of the endpoint\n    */\n   @Nullable\n   public String getRegion() {\n      return region;\n   }\n\n   /**\n    * A public URL is accessible from anywhere. Access to a public URL usually incurs traffic\n    * charges.\n    * \n    * @return the public endpoint of the service\n    */\n   @Nullable\n   public URI getPublicURL() {\n      return publicURL;\n   }\n\n   /**\n    * Internal URLs are only accessible to services within the same region.\n    * Access to an internal URL is free of charge.\n    * \n    * @return the internal url of the endpoint\n    */\n   @Nullable\n   public URI getInternalURL() {\n      return internalURL;\n   }\n\n   @Override\n   public boolean equals(Object object) {\n      if (this == object) {\n         return true;\n      }\n      if (object instanceof Endpoint) {\n         final Endpoint other = Endpoint.class.cast(object);\n         return equal(v1Default, other.v1Default) && equal(region, other.region) && equal(publicURL, other.publicURL)\n               && equal(internalURL, other.internalURL);\n      } else {\n         return false;\n      }\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(v1Default, region, publicURL, internalURL);\n   }\n\n   @Override\n   public String toString() {\n      return toStringHelper(\"\").add(\"v1Default\", v1Default).add(\"region\", region).add(\"publicURL\", publicURL)\n            .add(\"internalURL\", internalURL).toString();\n   }\n\n   @Override\n   public int compareTo(Endpoint that) {\n      if (that == null)\n         return 1;\n      if (this == that)\n         return 0;\n      return this.publicURL.compareTo(that.publicURL);\n   }\n\n}\n"
  },
  {
    "path": "common/openstack/src/main/java/org/jclouds/openstack/keystone/v1_1/domain/Token.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v1_1.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Date;\n\nimport com.google.common.base.Objects;\n\n/**\n * \n * Tokens are valid for a finite duration. The expires attribute denotes the\n * time after which the token will automatically become invalid. A token may be\n * manually revoked before the time identified by the expires attribute; expires\n * predicts a token's maximum possible lifespan but does not guarantee that it\n * will reach that lifespan. Clients are encouraged to cache a token until it\n * expires.\n * \n * @see <a href=\n *      \"http://docs.rackspace.com/loadbalancers/api/v1.0/clb-devguide/content/Service_Access_Endpoints-d1e517.html\"\n *      />\n */\npublic class Token implements Comparable<Token> {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().fromToken(this);\n   }\n\n   public static class Builder {\n      protected String id;\n      protected Date expires;\n\n      /**\n       * @see Token#getId()\n       */\n      public Builder id(String id) {\n         this.id = checkNotNull(id, \"id\");\n         return this;\n      }\n\n      /**\n       * @see Token#getExpires()\n       */\n      public Builder expires(Date expires) {\n         this.expires = checkNotNull(expires, \"expires\");\n         return this;\n      }\n\n      public Token build() {\n         return new Token(id, expires);\n      }\n\n      public Builder fromToken(Token from) {\n         return id(from.getId()).expires(from.getExpires());\n      }\n   }\n\n   protected Token() {\n      // we want serializers like Gson to work w/o using sun.misc.Unsafe,\n      // prohibited in GAE. This also implies fields are not final.\n      // see http://code.google.com/p/jclouds/issues/detail?id=925\n   }\n  \n   protected String id;\n   protected Date expires;\n\n   public Token(String id, Date expires) {\n      this.id = checkNotNull(id, \"id\");\n      this.expires = checkNotNull(expires, \"expires\");\n   }\n\n   /**\n    * When providing an ID, it is assumed that the token exists in the current\n    * OpenStack deployment\n    * \n    * @return the id of the token in the current OpenStack deployment\n    */\n   public String getId() {\n      return id;\n   }\n\n   /**\n    * @return the expires of the token\n    */\n   public Date getExpires() {\n      return expires;\n   }\n\n   @Override\n   public boolean equals(Object object) {\n      if (this == object) {\n         return true;\n      }\n      if (object instanceof Token) {\n         final Token other = Token.class.cast(object);\n         return equal(id, other.id) && equal(expires, other.expires);\n      } else {\n         return false;\n      }\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, expires);\n   }\n\n   @Override\n   public String toString() {\n      return toStringHelper(\"\").add(\"id\", id).add(\"expires\", expires).toString();\n   }\n\n   @Override\n   public int compareTo(Token that) {\n      if (that == null)\n         return 1;\n      if (this == that)\n         return 0;\n      return this.id.compareTo(that.id);\n   }\n\n}\n"
  },
  {
    "path": "common/openstack/src/main/java/org/jclouds/openstack/keystone/v1_1/functions/EndpointToRegion.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v1_1.functions;\n\nimport org.jclouds.openstack.keystone.v1_1.domain.Endpoint;\n\nimport com.google.common.base.Function;\nimport com.google.inject.ImplementedBy;\n\n@ImplementedBy(RegionFirstPartOfDNSNameOrProvider.class)\npublic interface EndpointToRegion extends Function<Endpoint, String> {\n\n}\n"
  },
  {
    "path": "common/openstack/src/main/java/org/jclouds/openstack/keystone/v1_1/functions/EndpointToSupplierURI.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v1_1.functions;\n\nimport java.net.URI;\n\nimport org.jclouds.openstack.keystone.v1_1.domain.Endpoint;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.inject.ImplementedBy;\n\n@ImplementedBy(PublicURLOrInternalIfNull.class)\npublic interface EndpointToSupplierURI extends Function<Endpoint, Supplier<URI>> {\n}\n"
  },
  {
    "path": "common/openstack/src/main/java/org/jclouds/openstack/keystone/v1_1/functions/PublicURLOrInternalIfNull.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v1_1.functions;\n\nimport java.net.URI;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.openstack.keystone.v1_1.domain.Endpoint;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\n\n@Singleton\npublic class PublicURLOrInternalIfNull implements EndpointToSupplierURI {\n   // TODO: check accessibility and prioritize private first\n   @Override\n   public Supplier<URI> apply(Endpoint input) {\n      return Suppliers.ofInstance(input.getPublicURL() != null ? input.getPublicURL() : input.getInternalURL());\n   }\n\n   public String toString() {\n      return \"supplyPublicURL()\";\n   }\n}\n"
  },
  {
    "path": "common/openstack/src/main/java/org/jclouds/openstack/keystone/v1_1/functions/RegionFirstPartOfDNSNameOrProvider.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v1_1.functions;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.location.Provider;\nimport org.jclouds.openstack.keystone.v1_1.domain.Endpoint;\n\nimport com.google.common.net.InternetDomainName;\n\n@Singleton\npublic class RegionFirstPartOfDNSNameOrProvider implements EndpointToRegion {\n   private final String provider;\n\n   @Inject\n   RegionFirstPartOfDNSNameOrProvider(@Provider String provider) {\n      this.provider = provider;\n   }\n\n   @Override\n   public String apply(Endpoint input) {\n      if (input.getRegion() != null)\n         return input.getRegion();\n      String host = input.getPublicURL().getHost();\n      if (InternetDomainName.isValid(host)) {\n         InternetDomainName domain = InternetDomainName.from(host);\n         return domain.parts().get(0);\n      }\n      return provider;\n   }\n}\n"
  },
  {
    "path": "common/openstack/src/main/java/org/jclouds/openstack/keystone/v1_1/handlers/RetryOnRenew.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v1_1.handlers;\n\nimport java.util.concurrent.TimeUnit;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\n\nimport org.jclouds.Constants;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpRetryHandler;\nimport org.jclouds.http.handlers.BackoffLimitedRetryHandler;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.openstack.keystone.v1_1.domain.Auth;\nimport org.jclouds.openstack.reference.AuthHeaders;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.cache.Cache;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.Multimap;\nimport com.google.common.util.concurrent.Uninterruptibles;\nimport com.google.inject.Inject;\nimport com.google.inject.Singleton;\n\n/**\n * This will parse and set an appropriate exception on the command object.\n */\n@Singleton\npublic class RetryOnRenew implements HttpRetryHandler {\n   @VisibleForTesting\n   @Inject(optional = true)\n   @Named(Constants.PROPERTY_MAX_RETRIES)\n   static int NUM_RETRIES = 5;\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   private final LoadingCache<Credentials, Auth> authenticationResponseCache;\n\n   private final BackoffLimitedRetryHandler backoffHandler;\n\n   @Inject\n   protected RetryOnRenew(LoadingCache<Credentials, Auth> authenticationResponseCache,\n           BackoffLimitedRetryHandler backoffHandler) {\n      this.authenticationResponseCache = authenticationResponseCache;\n      this.backoffHandler = backoffHandler;\n   }\n\n   /*\n    * The reason retries need to be tracked is that it is possible that a token\n    * can be expired at any time. The reason we track by request is that only\n    * some requests might return a 401 (such as temporary URLs). However\n    * consistent failures of the magnitude this code tracks should indicate a\n    * problem.\n    */\n   private static final Cache<HttpCommand, Integer> retryCountMap = CacheBuilder\n         .newBuilder().expireAfterWrite(5, TimeUnit.MINUTES).build();\n\n   @Override\n   public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) {\n      boolean retry = false; // default\n      switch (response.getStatusCode()) {\n         case 401:\n            // Do not retry on 401 from authentication request\n            Multimap<String, String> headers = command.getCurrentRequest().getHeaders();\n            if (headers != null && headers.containsKey(AuthHeaders.AUTH_USER)\n                     && headers.containsKey(AuthHeaders.AUTH_KEY) && !headers.containsKey(AuthHeaders.AUTH_TOKEN)) {\n               retry = false;\n            } else {\n               // This is not an authentication request returning 401\n               // Check if we already had seen this request\n               Integer count = retryCountMap.getIfPresent(command);\n\n               if (count == null) {\n                  // First time this non-authentication request failed\n                  logger.debug(\"invalidating authentication token - first time for %s\", command);\n                  retryCountMap.put(command, 1);\n                  authenticationResponseCache.invalidateAll();\n                  retry = true;\n               } else {\n                  // This request has failed before\n                  if (count + 1 >= NUM_RETRIES) {\n                     logger.debug(\"too many 401s - giving up after: %s for %s\", count, command);\n                     retry = false;\n                  } else {\n                     // Retry just in case\n                     logger.debug(\"invalidating authentication token - retry %s for %s\", count, command);\n                     retryCountMap.put(command, count + 1);\n                     // Wait between retries\n                     authenticationResponseCache.invalidateAll();\n                     Uninterruptibles.sleepUninterruptibly(5, TimeUnit.SECONDS);\n                     retry = true;\n                  }\n               }\n            }\n            break;\n         case 408:\n            return backoffHandler.shouldRetryRequest(command, response);\n      }\n      return retry;\n   }\n\n}\n"
  },
  {
    "path": "common/openstack/src/main/java/org/jclouds/openstack/keystone/v1_1/suppliers/RegionIdToURIFromAuthForServiceSupplier.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v1_1.suppliers;\n\nimport java.net.URI;\nimport java.util.Collection;\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.location.suppliers.RegionIdToURISupplier;\nimport org.jclouds.openstack.keystone.v1_1.domain.Auth;\nimport org.jclouds.openstack.keystone.v1_1.domain.Endpoint;\nimport org.jclouds.openstack.keystone.v1_1.functions.EndpointToRegion;\nimport org.jclouds.openstack.keystone.v1_1.functions.EndpointToSupplierURI;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.Maps;\nimport com.google.inject.assistedinject.Assisted;\n\npublic class RegionIdToURIFromAuthForServiceSupplier implements RegionIdToURISupplier {\n\n   private final Supplier<Auth> auth;\n   private final EndpointToSupplierURI endpointToSupplierURI;\n   private final EndpointToRegion endpointToRegion;\n   private final String apiType;\n\n   @Inject\n   public RegionIdToURIFromAuthForServiceSupplier(Supplier<Auth> auth, EndpointToSupplierURI endpointToSupplierURI,\n            EndpointToRegion endpointToRegion, @Assisted(\"apiType\") String apiType,\n            @Nullable @Assisted(\"apiVersion\") String apiVersion) {\n      this.auth = auth;\n      this.endpointToSupplierURI = endpointToSupplierURI;\n      this.endpointToRegion = endpointToRegion;\n      this.apiType = apiType;\n   }\n\n   @Override\n   public Map<String, Supplier<URI>> get() {\n      Auth authResponse = auth.get();\n      Collection<Endpoint> endpointsForService = authResponse.getServiceCatalog().get(apiType);\n      Map<String, Endpoint> regionIdToEndpoint = Maps.uniqueIndex(endpointsForService, endpointToRegion);\n      return Maps.transformValues(regionIdToEndpoint, endpointToSupplierURI);\n   }\n\n   @Override\n   public String toString() {\n      return \"getPublicURLForService(\" + apiType + \")\";\n   }\n}\n"
  },
  {
    "path": "common/openstack/src/main/java/org/jclouds/openstack/keystone/v1_1/suppliers/V1DefaultRegionIdSupplier.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v1_1.suppliers;\n\nimport static com.google.common.collect.Iterables.tryFind;\n\nimport java.util.NoSuchElementException;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.location.suppliers.ImplicitRegionIdSupplier;\nimport org.jclouds.openstack.keystone.v1_1.domain.Auth;\nimport org.jclouds.openstack.keystone.v1_1.domain.Endpoint;\nimport org.jclouds.openstack.keystone.v1_1.functions.EndpointToRegion;\n\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.Iterables;\nimport com.google.inject.assistedinject.Assisted;\n\npublic class V1DefaultRegionIdSupplier implements ImplicitRegionIdSupplier {\n\n   public interface Factory {\n      /**\n       * \n       * @param apiType\n       *           type of the api, according to the provider. ex. {@code compute}\n       *           {@code object-store}\n       * @return region id\n       * @throws NoSuchElementException\n       *            if the {@code apiType} is not present in the catalog\n       */\n      ImplicitRegionIdSupplier createForApiType(@Assisted(\"apiType\") String apiType) throws NoSuchElementException;\n   }\n\n   private final Supplier<Auth> auth;\n   private final EndpointToRegion endpointToRegion;\n   private final String apiType;\n\n   @Inject\n   public V1DefaultRegionIdSupplier(Supplier<Auth> auth, EndpointToRegion endpointToRegion,\n            @Assisted(\"apiType\") String apiType) {\n      this.auth = auth;\n      this.endpointToRegion = endpointToRegion;\n      this.apiType = apiType;\n   }\n\n   /**\n    * returns {@link Endpoint#isV1Default()} or first endpoint for service\n    */\n   @Override\n   public String get() {\n      Auth authResponse = auth.get();\n      Iterable<Endpoint> endpointsForService = authResponse.getServiceCatalog().get(apiType);\n      Optional<Endpoint> defaultEndpoint = tryFind(endpointsForService, new Predicate<Endpoint>() {\n         @Override\n         public boolean apply(Endpoint in) {\n            return in.isV1Default();\n         }\n      });\n      return endpointToRegion.apply(defaultEndpoint.or(Iterables.get(endpointsForService, 0)));\n   }\n\n   @Override\n   public String toString() {\n      return \"defaultRegionIdFor(\" + apiType + \")\";\n   }\n}\n"
  },
  {
    "path": "common/openstack/src/main/java/org/jclouds/openstack/options/BaseListOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\n\nimport java.util.Date;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\n/**\n * Options used to control paginated results (aka list commands).\n * \n * @see <a href=\"http://docs.rackspacecloud.com/servers/api/cs-devguide-latest.pdf\" />\n */\npublic class BaseListOptions extends BaseHttpRequestOptions {\n   public static final BaseListOptions NONE = new BaseListOptions();\n\n   /**\n    * Only return objects changed since this time.\n    */\n   public BaseListOptions changesSince(Date ifModifiedSince) {\n      this.queryParameters.put(\"changes-since\", checkNotNull(ifModifiedSince, \"ifModifiedSince\")\n               .getTime()\n               / 1000 + \"\");\n      return this;\n   }\n\n   /**\n    * Indicates where to begin listing. The list will only include objects that occur after the\n    * offset. This is convenient for pagination: To get the next page of results use the last result\n    * number of the current page + current page offset as the offset.\n    */\n   public BaseListOptions startAt(long offset) {\n      checkState(offset >= 0, \"offset must be >= 0\");\n      queryParameters.put(\"offset\", String.valueOf(offset));\n      return this;\n   }\n\n   /**\n    * To reduce load on the service, list operations will return a maximum of 1,000 items at a time.\n    * To navigate the collection, the parameters limit and offset can be set in the URI\n    * (e.g.?limit=0&offset=0). If an offset is given beyond the end of a list an empty list will be\n    * returned.\n    * <p/>\n    * Note that list operations never return itemNotFound (404) faults.\n    */\n   public BaseListOptions maxResults(int limit) {\n      checkState(limit >= 0, \"limit must be >= 0\");\n      checkState(limit <= 10000, \"limit must be <= 10000\");\n      queryParameters.put(\"limit\", Integer.toString(limit));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see BaseListOptions#startAt(long)\n       */\n      public static BaseListOptions startAt(long prefix) {\n         BaseListOptions options = new BaseListOptions();\n         return options.startAt(prefix);\n      }\n\n      /**\n       * @see BaseListOptions#maxResults\n       */\n      public static BaseListOptions maxResults(int maxKeys) {\n         BaseListOptions options = new BaseListOptions();\n         return options.maxResults(maxKeys);\n      }\n\n      /**\n       * @see BaseListOptions#changesSince(Date)\n       */\n      public static BaseListOptions changesSince(Date since) {\n         BaseListOptions options = new BaseListOptions();\n         return options.changesSince(since);\n      }\n\n   }\n}\n"
  },
  {
    "path": "common/openstack/src/main/java/org/jclouds/openstack/predicates/LinkPredicates.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.net.URI;\n\nimport org.jclouds.openstack.domain.Link;\nimport org.jclouds.openstack.domain.Link.Relation;\n\nimport com.google.common.base.Predicate;\n\n/**\n * Predicates handy when working with Link Types\n */\n\npublic class LinkPredicates {\n   /**\n    * matches links of the given relation\n    * \n    * @param rel relation of the link\n    * @return predicate that will match links of the given rel\n    */\n   public static Predicate<Link> relationEquals(final Relation rel) {\n      checkNotNull(rel, \"rel must be defined\");\n\n      return new Predicate<Link>() {\n         @Override\n         public boolean apply(Link link) {\n            return rel.equals(link.getRelation());\n         }\n\n         @Override\n         public String toString() {\n            return \"relEquals(\" + rel + \")\";\n         }\n      };\n   }\n\n   /**\n    * matches links of the given href\n    * \n    * @param href\n    * @return predicate that will match links of the given href\n    */\n   public static Predicate<Link> hrefEquals(final URI href) {\n      checkNotNull(href, \"href must be defined\");\n\n      return new Predicate<Link>() {\n         @Override\n         public boolean apply(Link link) {\n            return href.equals(link.getHref());\n         }\n\n         @Override\n         public String toString() {\n            return \"hrefEquals(\" + href + \")\";\n         }\n      };\n   }\n\n   /**\n    * matches links of the given type\n    * \n    * @param type\n    *           ex. application/pdf\n    * @return predicate that will match links of the given type\n    */\n   public static Predicate<Link> typeEquals(final String type) {\n      checkNotNull(type, \"type must be defined\");\n\n      return new Predicate<Link>() {\n         @Override\n         public boolean apply(Link link) {\n            return type.equals(link.getType());\n         }\n\n         @Override\n         public String toString() {\n            return \"typeEquals(\" + type + \")\";\n         }\n      };\n   }\n}\n"
  },
  {
    "path": "common/openstack/src/main/java/org/jclouds/openstack/reference/AuthHeaders.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.reference;\n\n/**\n * Headers common to Rackspace apis.\n * \n * @see <a href=\"http://docs.rackspacecloud.com/servers/api/cs-devguide-latest.pdf\" />\n */\npublic final class AuthHeaders {\n\n   public static final String AUTH_USER = \"X-Auth-User\";\n   public static final String AUTH_KEY = \"X-Auth-Key\";\n   public static final String STORAGE_USER = \"X-Storage-User\";\n   public static final String STORAGE_PASS = \"X-Storage-Pass\";\n   public static final String AUTH_TOKEN = \"X-Auth-Token\";\n   public static final String URL_SUFFIX = \"-Url\";\n\n   public static final String CDN_MANAGEMENT_URL = \"X-CDN-Management\" + URL_SUFFIX;\n   public static final String SERVER_MANAGEMENT_URL = \"X-Server-Management\" + URL_SUFFIX;\n   public static final String STORAGE_URL = \"X-Storage\" + URL_SUFFIX;\n\n   private AuthHeaders() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "common/openstack/src/main/java/org/jclouds/openstack/reference/package-info.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * This package contains properties and reference data used in Rackspace.\n */\npackage org.jclouds.openstack.reference;\n"
  },
  {
    "path": "common/openstack/src/main/java/org/jclouds/openstack/services/Compute.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.services;\n\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\nimport jakarta.inject.Qualifier;\n\n/**\n * Compute (Nova)\n * \n * @see <a href=\"http://docs.openstack.org/api/openstack-typeentity-service/2.0/content/Identity-Service-Concepts-e1362.html\"\n *      />\n * @see ServiceType#COMPUTE\n */\n@Retention(value = RetentionPolicy.RUNTIME)\n@Target(value = { ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })\n@Qualifier\npublic @interface Compute {\n\n}\n"
  },
  {
    "path": "common/openstack/src/main/java/org/jclouds/openstack/services/Extension.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.services;\n\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\nimport jakarta.inject.Qualifier;\n\n/**\n * An extension of a {@link ServiceType service}. In order for us to understand\n * the context of the extension, we must consider the <a href=\n * \"http://docs.openstack.org/api/openstack-compute/2/content/Extensions-d1e1444.html\"\n * >extensions call</a>.\n * \n * <br/>\n * For our purposes, the minimal context of an extension is the type of the\n * service it extends ex. {@link ServiceType#COMPUTE}, and its namespace ex. <a\n * href\n * =\"http://docs.openstack.org/ext/keypairs/api/v1.1\">http://docs.openstack.org\n * /ext/keypairs/api/v1.1</a>.\n * \n * \n * @see ServiceType\n * @see <a href=\n *      \"http://docs.openstack.org/api/openstack-compute/2/content/Extensions-d1e1444.html\"\n *      />\n * @see <a href=\"http://nova.openstack.org/api_ext\" />\n * @see <a href=\"http://nova.openstack.org/api_ext/ext_keypairs.html\" />\n */\n@Retention(value = RetentionPolicy.RUNTIME)\n@Target(value = { ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })\n@Qualifier\npublic @interface Extension {\n\n   /**\n    * the service type this is an extension of.\n    * \n    * <h3>note</h3>\n    * \n    * This isn't necessarily one of the built-in {@link ServiceType services},\n    * it could be an extension of a custom service.\n    * \n    * @return the service type this is an extension of.\n    * \n    */\n   String of();\n\n   /**\n    * namespace ex. <a href\n    * =\"http://docs.openstack.org/ext/keypairs/api/v1.1\">http\n    * ://docs.openstack.org /ext/keypairs/api/v1.1</a>.\n    * \n    * @return the namespace of the extension\n    */\n   String namespace();\n\n}\n"
  },
  {
    "path": "common/openstack/src/main/java/org/jclouds/openstack/services/Image.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.services;\n\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\nimport jakarta.inject.Qualifier;\n\n/**\n * Image Service (Glance)\n * \n * @see <a href=\"http://docs.openstack.org/api/openstack-typeentity-service/2.0/content/Identity-Service-Concepts-e1362.html\"\n *      />\n * @see ServiceType#IMAGE\n */\n@Retention(value = RetentionPolicy.RUNTIME)\n@Target(value = { ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })\n@Qualifier\npublic @interface Image {\n\n}\n"
  },
  {
    "path": "common/openstack/src/main/java/org/jclouds/openstack/services/ObjectStore.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.services;\n\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\nimport jakarta.inject.Qualifier;\n\n/**\n * Object Storage (Swift)\n * \n * @see <a href=\"http://docs.openstack.org/api/openstack-typeentity-service/2.0/content/Identity-Service-Concepts-e1362.html\"\n *      />\n * @see ServiceType#OBJECT_STORE\n */\n@Retention(value = RetentionPolicy.RUNTIME)\n@Target(value = { ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })\n@Qualifier\npublic @interface ObjectStore {\n\n}\n"
  },
  {
    "path": "common/openstack/src/main/java/org/jclouds/openstack/services/ServiceType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.services;\n\n/**\n * An OpenStack service, such as Compute (Nova), Object Storage (Swift), or Image Service (Glance).\n * A service provides one or more endpoints through which users can access resources and perform\n * (presumably useful) operations.\n * \n * @see <a href=\"http://docs.openstack.org/api/openstack-typeentity-service/2.0/content/Identity-Service-Concepts-e1362.html\"\n *      />\n */\npublic class ServiceType {\n   /**\n    * Object Storage (Swift)\n    */\n   public static final String OBJECT_STORE = \"object-store\";\n   /**\n    * Compute (Nova)\n    */\n   public static final String COMPUTE = \"compute\";\n   /**\n    * Image Service (Glance)\n    */\n   public static final String IMAGE = \"image\";\n   /**\n    * Identity Service (Keystone)\n    */\n   public static final String IDENTITY = \"identity\";\n   /**\n    * Network Service (Quantum)\n    */\n   public static final String NETWORK = \"network\";\n\n   protected ServiceType() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "common/openstack/src/test/java/org/jclouds/openstack/filters/AddTimestampQueryTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.filters;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Date;\n\nimport org.jclouds.http.HttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\n\n\n@Test(groups = \"unit\")\npublic class AddTimestampQueryTest {\n\n   @Test\n   public void testApplySetsKey() {\n      final Date date = new Date();\n      Supplier<Date> dateSupplier = new Supplier<Date>() {\n\n         @Override\n         public Date get() {\n            return date;\n         }\n\n      };\n\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma/\").build();\n\n      AddTimestampQuery filter = new AddTimestampQuery(dateSupplier);\n\n      request = filter.filter(request);\n\n      assertEquals(request.getRequestLine(), String.format(\"GET http://momma/?now=%s HTTP/1.1\", date.getTime()));\n\n   }\n\n}\n"
  },
  {
    "path": "common/openstack/src/test/java/org/jclouds/openstack/functions/ParseAuthenticationResponseFromHeadersTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\n\nimport org.jclouds.Constants;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.domain.AuthenticationResponse;\nimport org.jclouds.openstack.reference.AuthHeaders;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport com.google.inject.name.Names;\n\n/**\n * Tests behavior of {@code ParseAuthenticationResponseFromHeaders}\n */\n@Test(groups = \"unit\", testName = \"ParseAuthenticationResponseFromHeadersTest\")\npublic class ParseAuthenticationResponseFromHeadersTest {\n\n   Injector i = Guice.createInjector(new AbstractModule() {\n\n      @Override\n      protected void configure() {\n         bindConstant().annotatedWith(Names.named(Constants.PROPERTY_API_VERSION)).to(\"1\");\n      }\n\n   });\n\n   public void testReplaceLocalhost() {\n      ParseAuthenticationResponseFromHeaders parser = i.getInstance(ParseAuthenticationResponseFromHeaders.class);\n      parser = parser.setHostToReplace(\"fooman\");\n\n      HttpResponse response = HttpResponse.builder().statusCode(204).message(\"No Content\")\n                                          .addHeader(\"X-Auth-Token\", \"token\")\n                                          .addHeader(\"X-Storage-Token\", \"token\")\n                                          .addHeader(\"X-Storage-Url\", \"http://127.0.0.1:8080/v1/token\")\n                                          .addHeader(\"X-CDN-Management-Url\", \"http://127.0.0.1:8080/cdn-mgmt\")\n                                          .addHeader(\"X-Server-Management-Url\", \"http://127.0.0.1:8080/srv-mgmt\")\n                                          .build();\n\n      AuthenticationResponse md = parser.apply(response);\n      assertEquals(md.getAuthToken(), \"token\");\n      assertEquals(md.getServices().get(AuthHeaders.STORAGE_URL), URI.create(\"http://fooman:8080/v1/token\"));\n      assertEquals(md.getServices().get(AuthHeaders.CDN_MANAGEMENT_URL), URI.create(\"http://fooman:8080/cdn-mgmt\"));\n      assertEquals(md.getServices().get(AuthHeaders.SERVER_MANAGEMENT_URL), URI.create(\"http://fooman:8080/srv-mgmt\"));\n   }\n\n   public void testHandleHeadersCaseInsensitively() {\n      ParseAuthenticationResponseFromHeaders parser = i.getInstance(ParseAuthenticationResponseFromHeaders.class);\n      parser = parser.setHostToReplace(\"fooman\");\n\n      HttpResponse response = HttpResponse.builder().statusCode(204).message(\"No Content\")\n              .addHeader(\"x-auth-token\", \"token\")\n              .addHeader(\"x-storage-token\", \"token\")\n              .addHeader(\"x-storage-url\", \"http://127.0.0.1:8080/v1/token\")\n              .addHeader(\"x-cdn-management-url\", \"http://127.0.0.1:8080/cdn-mgmt\")\n              .addHeader(\"x-server-management-url\", \"http://127.0.0.1:8080/srv-mgmt\")\n              .build();\n      AuthenticationResponse md = parser.apply(response);\n      assertEquals(md.getAuthToken(), \"token\");\n      assertEquals(md.getServices().get(AuthHeaders.STORAGE_URL), URI.create(\"http://fooman:8080/v1/token\"));\n      assertEquals(md.getServices().get(AuthHeaders.CDN_MANAGEMENT_URL), URI.create(\"http://fooman:8080/cdn-mgmt\"));\n      assertEquals(md.getServices().get(AuthHeaders.SERVER_MANAGEMENT_URL), URI.create(\"http://fooman:8080/srv-mgmt\"));\n   }\n}\n"
  },
  {
    "path": "common/openstack/src/test/java/org/jclouds/openstack/handlers/RetryOnRenewTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.handlers;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.expectLastCall;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.openstack.domain.AuthenticationResponse;\nimport org.testng.annotations.Test;\n\nimport com.google.common.cache.LoadingCache;\n\n/**\n * Tests behavior of {@code RetryOnRenew} handler\n */\n@Test(groups = \"unit\", testName = \"RetryOnRenewTest\")\npublic class RetryOnRenewTest {\n   @Test\n   public void test401ShouldRetry() {\n      HttpCommand command = createMock(HttpCommand.class);\n      HttpRequest request = createMock(HttpRequest.class);\n      HttpResponse response = createMock(HttpResponse.class);\n      @SuppressWarnings(\"unchecked\")\n      LoadingCache<Credentials, AuthenticationResponse> cache = createMock(LoadingCache.class);\n\n      expect(command.getCurrentRequest()).andReturn(request);\n\n      cache.invalidateAll();\n      expectLastCall();\n\n      expect(response.getPayload()).andReturn(Payloads.newStringPayload(\"\"))\n            .anyTimes();\n      expect(response.getStatusCode()).andReturn(401).atLeastOnce();\n\n      replay(command);\n      replay(response);\n      replay(cache);\n\n      RetryOnRenew retry = new RetryOnRenew(cache);\n\n      assertTrue(retry.shouldRetryRequest(command, response));\n\n      verify(command);\n      verify(response);\n      verify(cache);\n   }\n\n   /**\n    * We have three types of authentication failures: a) When the session\n    * (token) expires b) When you hit a URL you don't have access to (because of\n    * permissions) c) When you attempt to authenticate to the service (with bad\n    * credentials)\n    *\n    * In case c), which is detectable, we do not retry, as usually this means\n    * your credentials are broken. Case a) and b) cannot be distinguished easily\n    * at this point. Different providers will request token re-authentication in\n    * different ways (but usually preceded or by an authentication failure). To\n    * attempt to distinguish between case a) and b) this code tracks failures\n    * for specific calls. Multiple failures for the same call almost certainly\n    * indicates a permissions issue. A success results in a successful\n    * re-authentication.\n    */\n   @Test\n   public void test401ShouldRetry4Times() {\n      HttpCommand command = createMock(HttpCommand.class);\n      HttpRequest request = createMock(HttpRequest.class);\n      HttpResponse response = createMock(HttpResponse.class);\n\n      @SuppressWarnings(\"unchecked\")\n      LoadingCache<Credentials, AuthenticationResponse> cache = createMock(LoadingCache.class);\n\n      expect(command.getCurrentRequest()).andReturn(request).anyTimes();\n      expect(request.getHeaders()).andStubReturn(null);\n\n      cache.invalidateAll();\n      expectLastCall().anyTimes();\n\n      expect(response.getPayload()).andReturn(Payloads.newStringPayload(\"\"))\n            .anyTimes();\n      expect(response.getStatusCode()).andReturn(401).anyTimes();\n\n      replay(command, request, response, cache);\n\n      RetryOnRenew retry = new RetryOnRenew(cache);\n\n      for (int n = 0; n < RetryOnRenew.NUM_RETRIES - 1; n++) {\n         assertTrue(retry.shouldRetryRequest(command, response),\n               \"Expected retry to succeed\");\n      }\n\n      assertFalse(retry.shouldRetryRequest(command, response),\n            \"Expected retry to fail on attempt 5\");\n\n      verify(command, response, cache);\n   }\n}\n"
  },
  {
    "path": "common/openstack/src/test/java/org/jclouds/openstack/internal/OpenStackAuthClientTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.internal;\n\nimport static org.jclouds.providers.AnonymousProviderMetadata.forApiOnEndpoint;\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport java.io.IOException;\n\nimport org.jclouds.fallbacks.MapHttp4xxCodesToExceptions;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.IntegrationTestClient;\nimport org.jclouds.openstack.functions.ParseAuthenticationResponseFromHeaders;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.rest.internal.BaseRestAnnotationProcessingTest;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.reflect.Invokable;\n\n@Test(groups = \"unit\", testName = \"OpenStackAuthClientTest\")\npublic class OpenStackAuthClientTest extends BaseRestAnnotationProcessingTest<OpenStackAuthClient> {\n\n   public void testAuthenticate() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(OpenStackAuthClient.class, \"authenticate\", String.class, String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"foo\", \"bar\"));\n\n      assertRequestLineEquals(httpRequest, \"GET http://localhost:8080/v1 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: */*\\nHost: localhost:8080\\nX-Auth-Key: bar\\nX-Auth-User: foo\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseAuthenticationResponseFromHeaders.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n   }\n\n   public void testAuthenticateStorage() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(OpenStackAuthClient.class, \"authenticateStorage\", String.class, String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"foo\", \"bar\"));\n\n      assertRequestLineEquals(httpRequest, \"GET http://localhost:8080/v1 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"Accept: */*\\nHost: localhost:8080\\nX-Storage-Pass: bar\\nX-Storage-User: foo\\n\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseAuthenticationResponseFromHeaders.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);\n\n   }\n\n   @Override\n   public ProviderMetadata createProviderMetadata() {\n      return forApiOnEndpoint(IntegrationTestClient.class, \"http://localhost:8080\");\n   }\n\n   @Override\n   protected void checkFilters(HttpRequest request) {\n   }\n}\n"
  },
  {
    "path": "common/openstack/src/test/java/org/jclouds/openstack/internal/TestOpenStackAuthenticationModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.internal;\n\nimport java.net.URI;\nimport java.util.Date;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.openstack.config.OpenStackAuthenticationModule;\nimport org.jclouds.openstack.domain.AuthenticationResponse;\nimport org.jclouds.openstack.reference.AuthHeaders;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableMap;\n\npublic class TestOpenStackAuthenticationModule extends OpenStackAuthenticationModule {\n   @Override\n   protected void configure() {\n      super.configure();\n      bind(GetAuthenticationResponse.class).to(TestGetAuthenticationResponse.class);\n   }\n\n   @Singleton\n   public static class TestGetAuthenticationResponse extends GetAuthenticationResponse {\n\n      @Inject\n      protected TestGetAuthenticationResponse() {\n         super(null);\n      }\n\n      @Override\n      public AuthenticationResponse load(Credentials input) {\n         return new AuthenticationResponse(\"authToken\", ImmutableMap.<String, URI> of(\n                  AuthHeaders.SERVER_MANAGEMENT_URL, URI.create(\"http://endpoint/vapi-version\"),\n                  AuthHeaders.STORAGE_URL, URI.create(\"http://storage\")));\n      }\n\n   }\n\n   @Override\n   public Supplier<String> provideAuthenticationTokenCache(Supplier<AuthenticationResponse> supplier) {\n      return new Supplier<String>() {\n         public String get() {\n            return \"testtoken\";\n         }\n      };\n   }\n\n   @Override\n   public Supplier<Date> provideCacheBusterDate() {\n      return new Supplier<Date>() {\n         public Date get() {\n            return new Date();\n         }\n      };\n   }\n\n}\n"
  },
  {
    "path": "common/openstack/src/test/java/org/jclouds/openstack/keystone/v1_1/functions/PublicURLOrInternalIfNullTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v1_1.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\n\nimport org.jclouds.openstack.keystone.v1_1.domain.Endpoint;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"PublicURLOrInternalIfNullTest\")\npublic class PublicURLOrInternalIfNullTest {\n   private final PublicURLOrInternalIfNull fn = new PublicURLOrInternalIfNull();\n\n   public void testPublicURLNotNullReturnsPublicURL() {\n      assertEquals(fn.apply(\n               Endpoint.builder().region(\"LON\").publicURL(\n                        URI.create(\"https://cdn3.clouddrive.com/v1/MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953\"))\n                        .v1Default(true).build()).get(), URI\n               .create(\"https://cdn3.clouddrive.com/v1/MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953\"));\n   }\n\n   public void testPublicURLNullReturnsInternalURL() {\n      assertEquals(fn.apply(Endpoint.builder().internalURL(URI.create(\"https://192.168.1.1\")).v1Default(true).build())\n               .get(), URI.create(\"https://192.168.1.1\"));\n   }\n\n}\n"
  },
  {
    "path": "common/openstack/src/test/java/org/jclouds/openstack/keystone/v1_1/functions/RegionFirstPartOfDNSNameOrProviderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v1_1.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\n\nimport org.jclouds.openstack.keystone.v1_1.domain.Endpoint;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"RegionFirstPartOfDNSNameOrProviderTest\")\npublic class RegionFirstPartOfDNSNameOrProviderTest {\n   private final RegionFirstPartOfDNSNameOrProvider fn = new RegionFirstPartOfDNSNameOrProvider(\"keystone\");\n\n   public void testRegionNotNullReturnsRegion() {\n      assertEquals(fn.apply(Endpoint.builder().region(\"LON\").publicURL(\n               URI.create(\"https://cdn3.clouddrive.com/v1/MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953\"))\n               .v1Default(true).build()), \"LON\");\n   }\n\n   public void testRegionNullReturnsFirstPartOfHostWhenValid() {\n      assertEquals(fn.apply(Endpoint.builder().publicURL(\n               URI.create(\"https://cdn3.clouddrive.com/v1/MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953\"))\n               .v1Default(true).build()), \"cdn3\");\n   }\n\n   public void testRegionNullReturnsProvioderWhenHostNotValid() {\n      assertEquals(fn.apply(Endpoint.builder().publicURL(URI.create(\"https://1.1.1.4\")).v1Default(true).build()),\n               \"keystone\");\n   }\n\n}\n"
  },
  {
    "path": "common/openstack/src/test/java/org/jclouds/openstack/keystone/v1_1/handlers/RetryOnRenewTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v1_1.handlers;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.expectLastCall;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.handlers.BackoffLimitedRetryHandler;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.openstack.keystone.v1_1.domain.Auth;\nimport org.testng.annotations.Test;\n\nimport com.google.common.cache.LoadingCache;\n\n/**\n * Tests behavior of {@code RetryOnRenew} handler\n */\n@Test(groups = \"unit\", testName = \"RetryOnRenewTest\")\npublic class RetryOnRenewTest {\n   @Test\n   public void test401ShouldRetry() {\n      HttpCommand command = createMock(HttpCommand.class);\n      HttpRequest request = createMock(HttpRequest.class);\n      HttpResponse response = createMock(HttpResponse.class);\n      @SuppressWarnings(\"unchecked\")\n      LoadingCache<Credentials, Auth> cache = createMock(LoadingCache.class);\n      BackoffLimitedRetryHandler backoffHandler = createMock(BackoffLimitedRetryHandler.class);\n\n      expect(command.getCurrentRequest()).andReturn(request);\n\n      cache.invalidateAll();\n      expectLastCall();\n\n      expect(response.getPayload()).andReturn(Payloads.newStringPayload(\"token expired, please renew\")).anyTimes();\n      expect(response.getStatusCode()).andReturn(401).atLeastOnce();\n\n      replay(command);\n      replay(response);\n      replay(cache);\n      replay(backoffHandler);\n\n      RetryOnRenew retry = new RetryOnRenew(cache, backoffHandler);\n\n      assertTrue(retry.shouldRetryRequest(command, response));\n\n      verify(command);\n      verify(response);\n      verify(cache);\n      verify(backoffHandler);\n   }\n\n   @Test\n   public void test401ShouldRetry4Times() {\n      HttpCommand command = createMock(HttpCommand.class);\n      HttpRequest request = createMock(HttpRequest.class);\n      HttpResponse response = createMock(HttpResponse.class);\n\n      @SuppressWarnings(\"unchecked\")\n      LoadingCache<Credentials, Auth> cache = createMock(LoadingCache.class);\n      BackoffLimitedRetryHandler backoffHandler = createMock(BackoffLimitedRetryHandler.class);\n\n      expect(command.getCurrentRequest()).andReturn(request).anyTimes();\n      expect(request.getHeaders()).andStubReturn(null);\n\n      cache.invalidateAll();\n      expectLastCall().anyTimes();\n\n      expect(response.getPayload()).andReturn(Payloads.newStringPayload(\"\"))\n            .anyTimes();\n      expect(response.getStatusCode()).andReturn(401).anyTimes();\n\n      replay(command, request, response, cache);\n\n      RetryOnRenew retry = new RetryOnRenew(cache, backoffHandler);\n\n      for (int i = 0; i < RetryOnRenew.NUM_RETRIES - 1; ++i) {\n         assertTrue(retry.shouldRetryRequest(command, response),\n               \"Expected retry to succeed\");\n      }\n\n      assertFalse(retry.shouldRetryRequest(command, response),\n            \"Expected retry to fail on attempt \" + RetryOnRenew.NUM_RETRIES);\n\n      verify(command, response, cache);\n   }\n\n   @Test\n   public void test408ShouldRetry() {\n      HttpCommand command = createMock(HttpCommand.class);\n      HttpResponse response = createMock(HttpResponse.class);\n      @SuppressWarnings(\"unchecked\")\n      LoadingCache<Credentials, Auth> cache = createMock(LoadingCache.class);\n      BackoffLimitedRetryHandler backoffHandler = createMock(BackoffLimitedRetryHandler.class);\n\n      expect(backoffHandler.shouldRetryRequest(command, response)).andReturn(true).once();\n      expect(response.getStatusCode()).andReturn(408).once();\n\n      replay(command);\n      replay(response);\n      replay(cache);\n      replay(backoffHandler);\n\n      RetryOnRenew retry = new RetryOnRenew(cache, backoffHandler);\n\n      assertTrue(retry.shouldRetryRequest(command, response));\n\n      verify(command);\n      verify(response);\n      verify(cache);\n      verify(backoffHandler);\n   }\n\n   @Test\n   public void test404ShouldNotRetry() {\n      HttpCommand command = createMock(HttpCommand.class);\n      HttpRequest request = createMock(HttpRequest.class);\n      HttpResponse response = createMock(HttpResponse.class);\n      @SuppressWarnings(\"unchecked\")\n      LoadingCache<Credentials, Auth> cache = createMock(LoadingCache.class);\n      BackoffLimitedRetryHandler backoffHandler = createMock(BackoffLimitedRetryHandler.class);\n\n      expect(response.getStatusCode()).andReturn(404).once();\n\n      replay(command);\n      replay(response);\n      replay(cache);\n      replay(backoffHandler);\n\n      RetryOnRenew retry = new RetryOnRenew(cache, backoffHandler);\n\n      assertTrue(!retry.shouldRetryRequest(command, response));\n\n      verify(command);\n      verify(response);\n      verify(cache);\n      verify(backoffHandler);\n   }\n}\n"
  },
  {
    "path": "common/openstack/src/test/java/org/jclouds/openstack/keystone/v1_1/internal/BaseKeystoneRestClientExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v1_1.internal;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.keystone.v1_1.config.AuthenticationServiceModule;\nimport org.jclouds.rest.internal.BaseRestApiExpectTest;\n\nimport com.google.common.net.HttpHeaders;\n\n/**\n * Base class for writing KeyStone Rest Client Expect tests\n */\npublic class BaseKeystoneRestClientExpectTest<S> extends BaseRestApiExpectTest<S> {\n\n   protected String endpoint = \"http://localhost:5000\";\n\n   public BaseKeystoneRestClientExpectTest() {\n      identity = \"user@jclouds.org\";\n      credential = \"Password1234\";\n   }\n\n   protected HttpRequest initialAuth = HttpRequest.builder().method(\"POST\")\n         .endpoint(endpoint + \"/v1.1/auth\")\n         .addHeader(HttpHeaders.ACCEPT, \"application/json\")\n         .payload(\n               payloadFromStringWithContentType(\n                     \"{\\\"credentials\\\":{\\\"username\\\":\\\"user@jclouds.org\\\",\\\"key\\\":\\\"Password1234\\\"}}\",\n                     \"application/json\")).build();\n\n   protected String authToken = \"118fb907-0786-4799-88f0-9a5b7963d1ab\";\n\n   protected HttpResponse responseWithAuth = HttpResponse.builder().statusCode(200).message(\"HTTP/1.1 200\")\n         .payload(payloadFromResourceWithContentType(\"/auth1_1.json\", \"application/json\")).build();\n\n   /**\n    * in case you need to override anything\n    */\n   public static class TestKeystoneAuthenticationModule extends AuthenticationServiceModule {\n      @Override\n      protected void configure() {\n         super.configure();\n      }\n\n   }\n\n}\n"
  },
  {
    "path": "common/openstack/src/test/java/org/jclouds/openstack/keystone/v1_1/parse/ParseAuthTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v1_1.parse;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.openstack.keystone.v1_1.domain.Auth;\nimport org.jclouds.openstack.keystone.v1_1.domain.Endpoint;\nimport org.jclouds.openstack.keystone.v1_1.domain.Token;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMultimap;\n\n@Test(groups = \"unit\", testName = \"ParseAuthTest\")\npublic class ParseAuthTest extends BaseItemParserTest<Auth> {\n\n   @Override\n   public String resource() {\n      return \"/auth1_1.json\";\n   }\n\n   @Override\n   @SelectJson(\"auth\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Auth expected() {\n      return Auth\n            .builder()\n            .token(\n                  Token.builder()\n                        .expires(new SimpleDateFormatDateService().iso8601DateParse(\"2012-01-30T02:30:54.000-06:00\"))\n                        .id(\"118fb907-0786-4799-88f0-9a5b7963d1ab\").build())\n            .serviceCatalog(\n                  ImmutableMultimap.of(\n                        \"cloudFilesCDN\",\n                        Endpoint\n                              .builder()\n                              .region(\"LON\")\n                              .publicURL(\n                                    URI.create(\"https://cdn3.clouddrive.com/v1/MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953\"))\n                              .v1Default(true).build(),\n                        \"cloudFiles\",\n                        Endpoint\n                              .builder()\n                              .region(\"LON\")\n                              .publicURL(\n                                    URI.create(\"https://storage101.lon3.clouddrive.com/v1/MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953\"))\n                              .v1Default(true)\n                              .internalURL(\n                                    URI.create(\"https://snet-storage101.lon3.clouddrive.com/v1/MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953\"))\n                              .build(),\n                        \"cloudServers\",\n                        Endpoint.builder()\n                              .publicURL(URI.create(\"https://lon.servers.api.rackspacecloud.com/v1.0/10001786\"))\n                              .v1Default(true).build())).build();\n\n   }\n}\n"
  },
  {
    "path": "common/openstack/src/test/java/org/jclouds/openstack/keystone/v1_1/suppliers/RegionIdToURIFromAuthForServiceSupplierTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v1_1.suppliers;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.location.Provider;\nimport org.jclouds.location.suppliers.RegionIdToURISupplier;\nimport org.jclouds.openstack.keystone.v1_1.domain.Auth;\nimport org.jclouds.openstack.keystone.v1_1.parse.ParseAuthTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Maps;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Provides;\nimport com.google.inject.assistedinject.FactoryModuleBuilder;\n\n@Test(groups = \"unit\", testName = \"RegionIdToURIFromAuthForServiceSupplierTest\")\npublic class RegionIdToURIFromAuthForServiceSupplierTest {\n   private final RegionIdToURISupplier.Factory factory = Guice.createInjector(new AbstractModule() {\n\n      @Override\n      protected void configure() {\n         bindConstant().annotatedWith(Provider.class).to(\"keystone\");\n         install(new FactoryModuleBuilder().implement(RegionIdToURISupplier.class,\n                  RegionIdToURIFromAuthForServiceSupplier.class).build(RegionIdToURISupplier.Factory.class));\n      }\n\n      @Provides\n      @Singleton\n      public Supplier<Auth> provide() {\n         return Suppliers.ofInstance(new ParseAuthTest().expected());\n      }\n   }).getInstance(RegionIdToURISupplier.Factory.class);\n\n   public void testRegionMatches() {\n      assertEquals(Maps.transformValues(factory.createForApiTypeAndVersion(\"cloudFilesCDN\", \"1.0\").get(), Suppliers\n               .<URI> supplierFunction()), ImmutableMap.of(\"LON\", URI\n               .create(\"https://cdn3.clouddrive.com/v1/MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953\")));\n   }\n\n   public void testTakesFirstPartOfDNSWhenNoRegion() {\n      assertEquals(Maps.transformValues(factory.createForApiTypeAndVersion(\"cloudServers\", \"1.1\").get(), Suppliers\n               .<URI> supplierFunction()), ImmutableMap.of(\"lon\", URI\n               .create(\"https://lon.servers.api.rackspacecloud.com/v1.0/10001786\")));\n   }\n}\n"
  },
  {
    "path": "common/openstack/src/test/java/org/jclouds/openstack/keystone/v1_1/suppliers/V1DefaultRegionIdSupplierTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.keystone.v1_1.suppliers;\n\nimport static org.testng.Assert.assertEquals;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.location.Provider;\nimport org.jclouds.location.suppliers.ImplicitRegionIdSupplier;\nimport org.jclouds.openstack.keystone.v1_1.domain.Auth;\nimport org.jclouds.openstack.keystone.v1_1.parse.ParseAuthTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Provides;\nimport com.google.inject.assistedinject.FactoryModuleBuilder;\n\n@Test(groups = \"unit\", testName = \"V1DefaultRegionIdSupplierTest\")\npublic class V1DefaultRegionIdSupplierTest {\n   private final V1DefaultRegionIdSupplier.Factory factory = Guice.createInjector(new AbstractModule() {\n\n      @Override\n      protected void configure() {\n         bindConstant().annotatedWith(Provider.class).to(\"keystone\");\n         install(new FactoryModuleBuilder().implement(ImplicitRegionIdSupplier.class, V1DefaultRegionIdSupplier.class)\n                  .build(V1DefaultRegionIdSupplier.Factory.class));\n      }\n\n      @Provides\n      @Singleton\n      public Supplier<Auth> provide() {\n         return Suppliers.ofInstance(new ParseAuthTest().expected());\n      }\n   }).getInstance(V1DefaultRegionIdSupplier.Factory.class);\n\n   public void testRegionMatches() {\n      assertEquals(factory.createForApiType(\"cloudFilesCDN\").get(), \"LON\");\n   }\n\n   public void testTakesFirstPartOfDNSWhenNoRegion() {\n      assertEquals(factory.createForApiType(\"cloudServers\").get(), \"lon\");\n   }\n}\n"
  },
  {
    "path": "common/openstack/src/test/java/org/jclouds/openstack/options/BaseListOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.options;\n\nimport static org.jclouds.openstack.options.BaseListOptions.Builder.changesSince;\nimport static org.jclouds.openstack.options.BaseListOptions.Builder.maxResults;\nimport static org.jclouds.openstack.options.BaseListOptions.Builder.startAt;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Date;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tests behavior of {@code ListOptions}\n */\n@Test(groups = \"unit\")\npublic class BaseListOptionsTest {\n\n   public void testChangesSince() {\n      Date ifModifiedSince = new Date();\n      BaseListOptions options = new BaseListOptions().changesSince(ifModifiedSince);\n      assertEquals(ImmutableList.of(ifModifiedSince.getTime() / 1000 + \"\"), options\n               .buildQueryParameters().get(\"changes-since\"));\n   }\n\n   public void testStartAt() {\n      long offset = 1;\n      BaseListOptions options = new BaseListOptions().startAt(offset);\n      assertEquals(ImmutableList.of(\"1\"), options.buildQueryParameters().get(\"offset\"));\n   }\n\n   public void testMaxResults() {\n      int limit = 1;\n      BaseListOptions options = new BaseListOptions().maxResults(limit);\n      assertEquals(ImmutableList.of(\"1\"), options.buildQueryParameters().get(\"limit\"));\n   }\n\n   public void testChangesSinceStatic() {\n      Date ifModifiedSince = new Date();\n      BaseListOptions options = changesSince(ifModifiedSince);\n      assertEquals(ImmutableList.of(ifModifiedSince.getTime() / 1000 + \"\"), options\n               .buildQueryParameters().get(\"changes-since\"));\n   }\n\n   public void testStartAtStatic() {\n      long offset = 1;\n      BaseListOptions options = startAt(offset);\n      assertEquals(ImmutableList.of(\"1\"), options.buildQueryParameters().get(\"offset\"));\n   }\n\n   public void testMaxResultsStatic() {\n      int limit = 1;\n      BaseListOptions options = maxResults(limit);\n      assertEquals(ImmutableList.of(\"1\"), options.buildQueryParameters().get(\"limit\"));\n   }\n}\n"
  },
  {
    "path": "common/openstack/src/test/java/org/jclouds/openstack/predicates/LinkPredicatesTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openstack.predicates;\n\nimport static org.jclouds.openstack.predicates.LinkPredicates.hrefEquals;\nimport static org.jclouds.openstack.predicates.LinkPredicates.relationEquals;\nimport static org.jclouds.openstack.predicates.LinkPredicates.typeEquals;\n\nimport java.net.URI;\n\nimport org.jclouds.openstack.domain.Link;\nimport org.jclouds.openstack.domain.Link.Relation;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"LinkPredicatesTest\")\npublic class LinkPredicatesTest {\n   Link ref = Link.builder().type(\"application/pdf\").relation(Relation.DESCRIBEDBY).href(\n            URI.create(\"http://docs.openstack.org/ext/keypairs/api/v1.1\")).build();\n\n   @Test\n   public void testRelationEqualsWhenEqual() {\n      assert relationEquals(Relation.DESCRIBEDBY).apply(ref);\n   }\n\n   @Test\n   public void testRelationEqualsWhenNotEqual() {\n      assert !relationEquals(Relation.UNRECOGNIZED).apply(ref);\n   }\n\n   @Test\n   public void testTypeEqualsWhenEqual() {\n      assert typeEquals(\"application/pdf\").apply(ref);\n   }\n\n   @Test\n   public void testTypeEqualsWhenNotEqual() {\n      assert !typeEquals(\"foo\").apply(ref);\n   }\n\n   @Test\n   public void testHrefEqualsWhenEqual() {\n      assert hrefEquals(URI.create(\"http://docs.openstack.org/ext/keypairs/api/v1.1\")).apply(ref);\n   }\n\n   @Test\n   public void testHrefEqualsWhenNotEqual() {\n      assert !hrefEquals(URI.create(\"foo\")).apply(ref);\n   }\n}\n"
  },
  {
    "path": "common/openstack/src/test/resources/auth1_1.json",
    "content": "{\n    \"auth\": {\n        \"token\": {\n            \"id\": \"118fb907-0786-4799-88f0-9a5b7963d1ab\",\n            \"expires\": \"2012-01-30T02:30:54.000-06:00\"\n        },\n        \"serviceCatalog\": {\n            \"cloudFilesCDN\": [{\n                \"region\": \"LON\",\n                \"publicURL\": \"https:\\/\\/cdn3.clouddrive.com\\/v1\\/MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953\",\n                \"v1Default\": true\n            }],\n            \"cloudFiles\": [{\n                \"region\": \"LON\",\n                \"publicURL\": \"https:\\/\\/storage101.lon3.clouddrive.com\\/v1\\/MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953\",\n                \"v1Default\": true,\n                \"internalURL\": \"https:\\/\\/snet-storage101.lon3.clouddrive.com\\/v1\\/MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953\"\n            }],\n            \"cloudServers\": [{\n                \"publicURL\": \"https:\\/\\/lon.servers.api.rackspacecloud.com\\/v1.0\\/10001786\",\n                \"v1Default\": true\n            }]\n        }\n    }\n}"
  },
  {
    "path": "common/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <artifactId>jclouds-project</artifactId>\n    <groupId>org.apache.jclouds</groupId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.common</groupId>\n  <artifactId>jclouds-commons-project</artifactId>\n  <packaging>pom</packaging>\n  <name>jclouds commons project</name>\n  <modules>\n    <module>googlecloud</module>\n    <module>openstack</module>\n  </modules>\n</project>\n"
  },
  {
    "path": "compute/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.cim.*;version=\"${project.version}\";-noimport:=true, \\\n    org.jclouds.compute.*;version=\"${project.version}\";-noimport:=true, \\\n    org.jclouds.net.*;version=\"${project.version}\";-noimport:=true, \\\n    org.jclouds.ovf.*;version=\"${project.version}\";-noimport:=true, \\\n    org.jclouds.ssh.*;version=\"${project.version}\";-noimport:=true"
  },
  {
    "path": "compute/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../project/pom.xml</relativePath>\n  </parent>\n\n  <artifactId>jclouds-compute</artifactId>\n  <name>jclouds compute core</name>\n  <description>jclouds components to access compute providers</description>\n\n  <dependencies>\n    <dependency>\n      <groupId>${project.groupId}</groupId>\n      <artifactId>jclouds-scriptbuilder</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>${project.groupId}</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>${project.groupId}</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n</project>\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/cim/CIMPredicates.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cim;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Set;\n\nimport org.jclouds.cim.ResourceAllocationSettingData.ResourceType;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableSet;\n\npublic class CIMPredicates {\n\n   /**\n    * Return resource allocations of the specific type.\n    * \n    * @param type\n    *           type to match the items\n    * @return predicate\n    */\n   public static Predicate<ResourceAllocationSettingData> resourceTypeIn(final ResourceType... types) {\n      checkNotNull(types, \"resourceTypes\");\n      final Set<ResourceType> resourceTypes = ImmutableSet.copyOf(types);\n      return new Predicate<ResourceAllocationSettingData>() {\n         @Override\n         public boolean apply(ResourceAllocationSettingData in) {\n            return resourceTypes.contains(in.getResourceType());\n         }\n\n         @Override\n         public String toString() {\n            return \"resourceTypeIn(\" + resourceTypes + \")\";\n         }\n      };\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/cim/ManagedElement.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cim;\n\n\n/**\n * \n * ManagedElement is an abstract class that provides a common superclass (or top of the inheritance\n * tree) for the non-association classes in the CIM Schema.\n * \n * @see <a\n *      href=\"http://dmtf.org/sites/default/files/cim/cim_schema_v2280/cim_schema_2.28.0Final-Doc.zip\"\n *      />\n */\npublic abstract class ManagedElement extends SettingData {\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Builder toBuilder() {\n      return builder().fromManagedElement(this);\n   }\n\n   public static class Builder extends SettingData.Builder {\n      protected String caption;\n      protected String description;\n\n      /**\n       * @see ManagedSettingData#getCaption\n       */\n      public Builder caption(String caption) {\n         this.caption = caption;\n         return this;\n      }\n\n      /**\n       * @see ManagedSettingData#getDescription\n       */\n      public Builder description(String description) {\n         this.description = description;\n         return this;\n      }\n\n      public Builder fromManagedElement(ManagedElement in) {\n         return caption(in.getCaption()).description(in.getDescription()).fromSettingData(in);\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder fromSettingData(SettingData in) {\n         return Builder.class.cast(super.fromSettingData(in));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder elementName(String elementName) {\n         return Builder.class.cast(super.elementName(elementName));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder instanceID(String instanceID) {\n         return Builder.class.cast(super.instanceID(instanceID));\n      }\n\n   }\n\n   protected final String caption;\n   protected final String description;\n\n   public ManagedElement(String elementName, String instanceID, String caption, String description) {\n      super(elementName, instanceID);\n      this.caption = caption;\n      this.description = description;\n   }\n\n   /**\n    * The Caption property is a short textual description (one- line string) of the object.\n    */\n   public String getCaption() {\n      return caption;\n   }\n\n   /**\n    * The Description property provides a textual description of the object.\n    */\n   public String getDescription() {\n      return description;\n   }\n\n   @Override\n   public String toString() {\n      return String.format(\"[elementName=%s, instanceID=%s, caption=%s, description=%s]\", elementName, instanceID,\n               caption, description);\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/cim/OSType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cim;\n\nimport org.jclouds.compute.domain.OsFamily;\n\n/**\n * Operating system based on DMTF CIM model.\n * \n * @see <a\n *      href=\"http://dmtf.org/sites/default/files/cim/cim_schema_v2280/cim_schema_2.28.0Final-Doc.zip\"\n *      />\n */\npublic enum OSType {\n   /**\n    * Other\n    */\n   OTHER(1, \"Other\", OsFamily.UNRECOGNIZED, false),\n   /**\n    * MACOS\n    */\n   MACOS(2, \"MACOS\", OsFamily.DARWIN, false),\n   /**\n    * Solaris\n    */\n   SOLARIS(29, \"Solaris\", OsFamily.SOLARIS, false),\n   /**\n    * LINUX\n    */\n   LINUX(36, \"LINUX\", OsFamily.LINUX, false),\n   /**\n    * FreeBSD\n    */\n   FREEBSD(42, \"FreeBSD\", OsFamily.FREEBSD, false),\n   /**\n    * NetBSD\n    */\n   NETBSD(43, \"NetBSD\", OsFamily.NETBSD, false),\n   /**\n    * OpenBSD\n    */\n   OPENBSD(65, \"OpenBSD\", OsFamily.OPENBSD, false),\n   /**\n    * Not Applicable\n    */\n   NOT_APPLICABLE(66, \"Not Applicable\", OsFamily.UNRECOGNIZED, false),\n   /**\n    * Microsoft Windows Server 2003\n    */\n   WINDOWS_SERVER_2003(69, \"Microsoft Windows Server 2003\", OsFamily.WINDOWS, false),\n   /**\n    * Microsoft Windows Server 2003 64-Bit\n    */\n   WINDOWS_SERVER_2003_64(70, \"Microsoft Windows Server 2003 64-Bit\", OsFamily.WINDOWS, true),\n   /**\n    * Microsoft Windows Server 2008\n    */\n   WINDOWS_SERVER_2008(76, \"Microsoft Windows Server 2008\", OsFamily.WINDOWS, false),\n   /**\n    * Microsoft Windows Server 2008 64-Bit\n    */\n   WINDOWS_SERVER_2008_64(77, \"Microsoft Windows Server 2008 64-Bit\", OsFamily.WINDOWS, true),\n   /**\n    * FreeBSD 64-Bit\n    */\n   FREEBSD_64(78, \"FreeBSD 64-Bit\", OsFamily.FREEBSD, true),\n   /**\n    * RedHat Enterprise Linux\n    */\n   RHEL(79, \"RedHat Enterprise Linux\", OsFamily.RHEL, false),\n   /**\n    * RedHat Enterprise Linux 64-Bit\n    */\n   RHEL_64(80, \"RedHat Enterprise Linux 64-Bit\", OsFamily.RHEL, true),\n   /**\n    * Solaris 64-Bit\n    */\n   SOLARIS_64(81, \"Solaris 64-Bit\", OsFamily.SOLARIS, true),\n   /**\n    * SUSE\n    */\n   SUSE(82, \"SUSE\", OsFamily.SUSE, false),\n   /**\n    * SUSE 64-Bit\n    */\n   SUSE_64(83, \"SUSE 64-Bit\", OsFamily.SUSE, true),\n   /**\n    * SLES\n    */\n   SLES(84, \"SLES\", OsFamily.SUSE, false),\n   /**\n    * SLES 64-Bit\n    */\n   SLES_64(85, \"SLES 64-Bit\", OsFamily.SUSE, true),\n   /**\n    * Novell OES\n    */\n   NOVELL_OES(86, \"Novell OES\", OsFamily.SUSE, true),\n   /**\n    * Mandriva\n    */\n   MANDRIVA(89, \"Mandriva\", OsFamily.MANDRIVA, false),\n   /**\n    * Mandriva 64-Bit\n    */\n   MANDRIVA_64(90, \"Mandriva 64-Bit\", OsFamily.MANDRIVA, true),\n   /**\n    * TurboLinux\n    */\n   TURBOLINUX(91, \"TurboLinux\", OsFamily.TURBOLINUX, false),\n   /**\n    * TurboLinux 64-Bit\n    */\n   TURBOLINUX_64(92, \"TurboLinux 64-Bit\", OsFamily.TURBOLINUX, true),\n   /**\n    * Ubuntu\n    */\n   UBUNTU(93, \"Ubuntu\", OsFamily.UBUNTU, false),\n   /**\n    * Ubuntu 64-Bit\n    */\n   UBUNTU_64(94, \"Ubuntu 64-Bit\", OsFamily.UBUNTU, true),\n   /**\n    * Debian\n    */\n   DEBIAN(95, \"Debian\", OsFamily.DEBIAN, false),\n   /**\n    * Debian 64-Bit\n    */\n   DEBIAN_64(96, \"Debian 64-Bit\", OsFamily.DEBIAN, false),\n   /**\n    * Linux 2.4.x\n    */\n   LINUX_2_4(97, \"Linux 2.4.x\", OsFamily.LINUX, false),\n   /**\n    * Linux 2.4.x 64-Bi\n    */\n   LINUX_2_4_64(98, \"Linux 2.4.x 64-Bit\", OsFamily.LINUX, true),\n   /**\n    * Linux 2.6.x\n    */\n   LINUX_2_6(99, \"Linux 2.6.x\", OsFamily.LINUX, false),\n   /**\n    * Linux 2.6.x 64-Bit\n    */\n   LINUX_2_6_64(100, \"Linux 2.6.x 64-Bit\", OsFamily.LINUX, true),\n   /**\n    * Linux 64-Bit\n    */\n   LINUX_64(101, \"Linux 64-Bit\", OsFamily.LINUX, true),\n   /**\n    * Other 64-Bit\n    */\n   OTHER_64(102, \"Other 64-Bit\", OsFamily.UNRECOGNIZED, true),\n   /**\n    * Microsoft Windows Server 2008 R2\n    */\n   WINDOWS_SERVER_2008_R2(103, \"Microsoft Windows Server 2008 R2\", OsFamily.WINDOWS, true),\n   /**\n    * VMware ESXi\n    */\n   ESXI(104, \"VMware ESXi\", OsFamily.ESX, true),\n   /**\n    * Microsoft Windows 7\n    */\n   WINDOWS_7(105, \"Microsoft Windows 7\", OsFamily.WINDOWS, false),\n   /**\n    * CentOS 32-bit\n    */\n   CENTOS(106, \"CentOS 32-bit\", OsFamily.CENTOS, false),\n   /**\n    * CentOS 64-bit\n    */\n   CENTOS_64(107, \"CentOS 64-bit\", OsFamily.CENTOS, true),\n   /**\n    * Oracle Enterprise Linux 32-bit\n    */\n   ORACLE_ENTERPRISE_LINUX(108, \"Oracle Enterprise Linux 32-bit\", OsFamily.OEL, false),\n   /**\n    * Oracle Enterprise Linux 64-bit\n    */\n   ORACLE_ENTERPRISE_LINUX_64(109, \"Oracle Enterprise Linux 64-bit\", OsFamily.OEL, true),\n   /**\n    * eComStation 32-bitx\n    */\n   ECOMSTATION_32(109, \"eComStation 32-bitx\", OsFamily.UNRECOGNIZED, false), UNRECOGNIZED(Integer.MAX_VALUE,\n            \"UNRECOGNIZED\", null, true);\n   private final int code;\n\n   public int getCode() {\n      return code;\n   }\n\n   public String getValue() {\n      return value;\n   }\n\n   public OsFamily getFamily() {\n      return family;\n   }\n\n   public boolean is64Bit() {\n      return is64Bit;\n   }\n\n   private final String value;\n   private final OsFamily family;\n   private final boolean is64Bit;\n\n   OSType(int code, String value, OsFamily family, boolean is64Bit) {\n      this.code = code;\n      this.value = value;\n      this.family = family;\n      this.is64Bit = is64Bit;\n   }\n\n   public static OSType fromValue(int code) {\n      for (OSType type : values()) {\n         if (type.code == code)\n            return type;\n      }\n      return UNRECOGNIZED;\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/cim/ResourceAllocationSettingData.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cim;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Lists;\nimport com.google.common.collect.Maps;\n\n/**\n * \n * The ResourceAllocationSettingData class represents settings specifically\n * related to an allocated resource that are outside the scope of the CIM class\n * typically used to represent the resource itself. These settings include\n * information specific to the allocation that may not be visible to the\n * consumer of the resource itself. For example, a virtual processor may look\n * like a 2 ghz processor to the consumer (virtual computer system), however the\n * virtualization system may use time-slicing to schedule the the virtual\n * processor to only allow it to use 1 ghz.\n * \n * @see <a href=\n *      \"http://dmtf.org/sites/default/files/cim/cim_schema_v2280/cim_schema_2.28.0Final-Doc.zip\"\n *      />\n */\npublic class ResourceAllocationSettingData extends ManagedElement {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Builder toBuilder() {\n      return builder().fromResourceAllocationSettingData(this);\n   }\n\n   public static class Builder extends ManagedElement.Builder {\n\n      protected String address;\n      protected String addressOnParent;\n      protected String allocationUnits;\n      protected Boolean automaticAllocation;\n      protected Boolean automaticDeallocation;\n      protected ConsumerVisibility consumerVisibility;\n      protected Long limit;\n      protected MappingBehavior mappingBehavior;\n      protected String otherResourceType;\n      protected String parent;\n      protected String poolID;\n      protected Long reservation;\n      protected String resourceSubType;\n      protected ResourceType resourceType;\n      protected Long virtualQuantity;\n      protected String virtualQuantityUnits;\n      protected Integer weight;\n      protected List<String> connections = Lists.newArrayList();\n      protected List<String> hostResources = Lists.newArrayList();\n\n      /**\n       * @see ResourceAllocationSettingData#getAddress\n       */\n      public Builder address(String address) {\n         this.address = address;\n         return this;\n      }\n\n      /**\n       * @see ResourceAllocationSettingData#getAddressOnParent\n       */\n      public Builder addressOnParent(String addressOnParent) {\n         this.addressOnParent = addressOnParent;\n         return this;\n      }\n\n      /**\n       * @see ResourceAllocationSettingData#getAllocationUnits\n       */\n      public Builder allocationUnits(String allocationUnits) {\n         this.allocationUnits = allocationUnits;\n         return this;\n      }\n\n      /**\n       * @see ResourceAllocationSettingData#getAutomaticAllocation\n       */\n      public Builder automaticAllocation(Boolean automaticAllocation) {\n         this.automaticAllocation = automaticAllocation;\n         return this;\n      }\n\n      /**\n       * @see ResourceAllocationSettingData#getAutomaticDeallocation\n       */\n      public Builder automaticDeallocation(Boolean automaticDeallocation) {\n         this.automaticDeallocation = automaticDeallocation;\n         return this;\n      }\n\n      /**\n       * @see ResourceAllocationSettingData#getConsumerVisibility\n       */\n      public Builder consumerVisibility(ConsumerVisibility consumerVisibility) {\n         this.consumerVisibility = consumerVisibility;\n         return this;\n      }\n\n      /**\n       * @see ResourceAllocationSettingData#getLimit\n       */\n      public Builder limit(Long limit) {\n         this.limit = limit;\n         return this;\n      }\n\n      /**\n       * @see ResourceAllocationSettingData#getMappingBehavior\n       */\n      public Builder mappingBehavior(MappingBehavior mappingBehavior) {\n         this.mappingBehavior = mappingBehavior;\n         return this;\n      }\n\n      /**\n       * @see ResourceAllocationSettingData#getOtherResourceType\n       */\n      public Builder otherResourceType(String otherResourceType) {\n         this.otherResourceType = otherResourceType;\n         return this;\n      }\n\n      /**\n       * @see ResourceAllocationSettingData#getParent\n       */\n      public Builder parent(String parent) {\n         this.parent = parent;\n         return this;\n      }\n\n      /**\n       * @see ResourceAllocationSettingData#getPoolID\n       */\n      public Builder poolID(String poolID) {\n         this.poolID = poolID;\n         return this;\n      }\n\n      /**\n       * @see ResourceAllocationSettingData#getReservation\n       */\n      public Builder reservation(Long reservation) {\n         this.reservation = reservation;\n         return this;\n      }\n\n      /**\n       * @see ResourceAllocationSettingData#getResourceSubType\n       */\n      public Builder resourceSubType(String resourceSubType) {\n         this.resourceSubType = resourceSubType;\n         return this;\n      }\n\n      /**\n       * @see ResourceAllocationSettingData#getResourceType\n       */\n      public Builder resourceType(ResourceType resourceType) {\n         this.resourceType = resourceType;\n         return this;\n      }\n\n      /**\n       * @see ResourceAllocationSettingData#getVirtualQuantity\n       */\n      public Builder virtualQuantity(Long virtualQuantity) {\n         this.virtualQuantity = virtualQuantity;\n         return this;\n      }\n\n      /**\n       * @see ResourceAllocationSettingData#getVirtualQuantityUnits\n       */\n      public Builder virtualQuantityUnits(String virtualQuantityUnits) {\n         this.virtualQuantityUnits = virtualQuantityUnits;\n         return this;\n      }\n\n      /**\n       * @see ResourceAllocationSettingData#getWeight\n       */\n      public Builder weight(Integer weight) {\n         this.weight = weight;\n         return this;\n      }\n\n      /**\n       * @see ResourceAllocationSettingData#getConnection\n       */\n      public Builder connection(String connection) {\n         this.connections.add(checkNotNull(connection, \"connection\"));\n         return this;\n      }\n\n      /**\n       * @see ResourceAllocationSettingData#getHostResource\n       */\n      public Builder hostResource(String hostResource) {\n         this.hostResources.add(checkNotNull(hostResource, \"hostResource\"));\n         return this;\n      }\n\n      /**\n       * @see ResourceAllocationSettingData#getConnections\n       */\n      public Builder connections(List<String> connections) {\n         this.connections.addAll(checkNotNull(connections, \"connections\"));\n         return this;\n      }\n\n      /**\n       * @see ResourceAllocationSettingData#getHostResources\n       */\n      public Builder hostResources(List<String> hostResources) {\n         this.hostResources.addAll(checkNotNull(hostResources, \"hostResources\"));\n         return this;\n      }\n\n      public ResourceAllocationSettingData build() {\n         return new ResourceAllocationSettingData(elementName, instanceID, caption, description, address,\n               addressOnParent, allocationUnits, automaticAllocation, automaticDeallocation, consumerVisibility, limit,\n               mappingBehavior, otherResourceType, parent, poolID, reservation, resourceSubType, resourceType,\n               virtualQuantity, virtualQuantityUnits, weight, connections, hostResources);\n      }\n\n      public Builder fromResourceAllocationSettingData(ResourceAllocationSettingData in) {\n         return fromManagedElement(in).address(in.getAddress()).addressOnParent(in.getAddressOnParent())\n               .allocationUnits(in.getAllocationUnits()).automaticAllocation(in.isAutomaticAllocation())\n               .automaticDeallocation(in.isAutomaticDeallocation()).consumerVisibility(in.getConsumerVisibility())\n               .limit(in.getLimit()).mappingBehavior(in.getMappingBehavior())\n               .otherResourceType(in.getOtherResourceType()).parent(in.getParent()).poolID(in.getPoolID())\n               .reservation(in.getReservation()).resourceSubType(in.getResourceSubType())\n               .resourceType(in.getResourceType()).virtualQuantity(in.getVirtualQuantity())\n               .virtualQuantityUnits(in.getVirtualQuantityUnits()).weight(in.getWeight())\n               .connections(in.getConnections()).hostResources(in.getHostResources());\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder fromManagedElement(ManagedElement in) {\n         return Builder.class.cast(super.fromManagedElement(in));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder caption(String caption) {\n         return Builder.class.cast(super.caption(caption));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder description(String description) {\n         return Builder.class.cast(super.description(description));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder elementName(String elementName) {\n         return Builder.class.cast(super.elementName(elementName));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder instanceID(String instanceID) {\n         return Builder.class.cast(super.instanceID(instanceID));\n      }\n\n   }\n\n   /**\n    * The type of resource this allocation setting represents.\n    */\n   public static enum ResourceType {\n\n      OTHER(1), COMPUTER_SYSTEM(2), PROCESSOR(3), MEMORY(4), IDE_CONTROLLER(5), PARALLEL_SCSI_HBA(6), FC_HBA(7), ISCSI_HBA(\n            8), IB_HCA(9), ETHERNET_ADAPTER(10), OTHER_NETWORK_ADAPTER(11), IO_SLOT(12), IO_DEVICE(13), FLOPPY_DRIVE(14), CD_DRIVE(\n            15), DVD_DRIVE(16), DISK_DRIVE(17), TAPE_DRIVE(18), STORAGE_EXTENT(19), OTHER_STORAGE_DEVICE(20), SERIAL_PORT(\n            21), PARALLEL_PORT(22), USB_CONTROLLER(23), GRAPHICS_CONTROLLER(24), IEEE_1394_CONTROLLER(25), PARTITIONABLE_UNIT(\n            26), BASE_PARTITIONABLE_UNIT(27), POWER(28), COOLING_CAPACITY(29), ETHERNET_SWITCH_PORT(30), LOGICAL_DISK(\n            31), STORAGE_VOLUME(32), ETHERNET_CONNECTION(33), DMTF_RESERVED(Integer.valueOf(\"8000\", 16)), VENDOR_RESERVED(\n            Integer.valueOf(\"FFFF\", 16));\n\n      protected final int code;\n\n      ResourceType(int code) {\n         this.code = code;\n      }\n\n      public String value() {\n         return code + \"\";\n      }\n\n      protected static final Map<Integer, ResourceType> RESOURCE_TYPE_BY_ID = Maps.uniqueIndex(\n            ImmutableSet.copyOf(ResourceType.values()), new Function<ResourceType, Integer>() {\n\n               @Override\n               public Integer apply(ResourceType input) {\n                  return input.code;\n               }\n\n            });\n\n      public static ResourceType fromValue(String type) {\n         return RESOURCE_TYPE_BY_ID.get(Integer.valueOf(checkNotNull(type, \"type\")));\n      }\n   }\n\n   /**\n    * Describes the consumers visibility to the allocated resource.\n    */\n   public static enum ConsumerVisibility {\n      UNKNOWN(0),\n      /**\n       * indicates the underlying or host resource is utilized and passed\n       * through to the consumer, possibly using partitioning. At least one item\n       * shall be present in the HostResource property.\n       */\n      PASSED_THROUGH(2),\n      /**\n       * indicates the resource is virtualized and may not map directly to an\n       * underlying/host resource. Some implementations may support specific\n       * assignment for virtualized resources, in which case the host\n       * resource(s) are exposed using the HostResource property.\n       */\n      VIRTUALIZED(3),\n      /**\n       * indicates a representation of the resource does not exist within the\n       * context of the resource consumer.\n       */\n      NOT_REPRESENTED(4), DMTF_RESERVED(32767), VENDOR_RESERVED(65535);\n\n      protected final int code;\n\n      ConsumerVisibility(int code) {\n         this.code = code;\n      }\n\n      public String value() {\n         return code + \"\";\n      }\n\n      protected static final Map<Integer, ConsumerVisibility> MAPPING_BEHAVIOR_BY_ID = Maps.uniqueIndex(\n            ImmutableSet.copyOf(ConsumerVisibility.values()), new Function<ConsumerVisibility, Integer>() {\n\n               @Override\n               public Integer apply(ConsumerVisibility input) {\n                  return input.code;\n               }\n\n            });\n\n      public static ConsumerVisibility fromValue(String behavior) {\n         return MAPPING_BEHAVIOR_BY_ID.get(Integer.valueOf(checkNotNull(behavior, \"behavior\")));\n      }\n   }\n\n   /**\n    * Specifies how this resource maps to underlying resourcesIf the\n    * HostResource array contains any entries, this property reflects how the\n    * resource maps to those specific resources.\n    */\n   public static enum MappingBehavior {\n      UNKNOWN(0), NOT_SUPPORTED(2), DEDICATED(3), SOFT_AFFINITY(4), HARD_AFFINITY(5), DMTF_RESERVED(32767), VENDOR_RESERVED(\n            65535);\n\n      protected final int code;\n\n      MappingBehavior(int code) {\n         this.code = code;\n      }\n\n      public String value() {\n         return code + \"\";\n      }\n\n      protected static final Map<Integer, MappingBehavior> MAPPING_BEHAVIOR_BY_ID = Maps.uniqueIndex(\n            ImmutableSet.copyOf(MappingBehavior.values()), new Function<MappingBehavior, Integer>() {\n\n               @Override\n               public Integer apply(MappingBehavior input) {\n                  return input.code;\n               }\n\n            });\n\n      public static MappingBehavior fromValue(String behavior) {\n         return MAPPING_BEHAVIOR_BY_ID.get(Integer.valueOf(checkNotNull(behavior, \"behavior\")));\n      }\n   }\n\n   protected final String address;\n   protected final String addressOnParent;\n   protected final String allocationUnits;\n   protected final Boolean automaticAllocation;\n   protected final Boolean automaticDeallocation;\n   protected final ConsumerVisibility consumerVisibility;\n   protected final Long limit;\n   protected final MappingBehavior mappingBehavior;\n   protected final String otherResourceType;\n   protected final String parent;\n   protected final String poolID;\n   protected final Long reservation;\n   protected final String resourceSubType;\n   protected final ResourceType resourceType;\n   protected final Long virtualQuantity;\n   protected final String virtualQuantityUnits;\n   protected final Integer weight;\n   protected final List<String> connections;\n   protected final List<String> hostResources;\n\n   public ResourceAllocationSettingData(String elementName, String instanceID, String caption, String description,\n         String address, String addressOnParent, String allocationUnits, Boolean automaticAllocation,\n         Boolean automaticDeallocation, ConsumerVisibility consumerVisibility, Long limit,\n         MappingBehavior mappingBehavior, String otherResourceType, String parent, String poolID, Long reservation,\n         String resourceSubType, ResourceType resourceType, Long virtualQuantity, String virtualQuantityUnits,\n         Integer weight, List<String> connections, List<String> hostResources) {\n      super(elementName, instanceID, caption, description);\n      this.address = address;\n      this.addressOnParent = addressOnParent;\n      this.allocationUnits = allocationUnits;\n      this.automaticAllocation = automaticAllocation;\n      this.automaticDeallocation = automaticDeallocation;\n      this.consumerVisibility = consumerVisibility;\n      this.limit = limit;\n      this.mappingBehavior = mappingBehavior;\n      this.otherResourceType = otherResourceType;\n      this.parent = parent;\n      this.poolID = poolID;\n      this.reservation = reservation;\n      this.resourceSubType = resourceSubType;\n      this.resourceType = resourceType;\n      this.virtualQuantity = virtualQuantity;\n      this.virtualQuantityUnits = virtualQuantityUnits;\n      this.weight = weight;\n      this.connections = ImmutableList.copyOf(connections);\n      this.hostResources = ImmutableList.copyOf(hostResources);\n   }\n\n   /**\n    * The address of the resource. For example, the MAC address of a Ethernet\n    * port.\n    */\n   public String getAddress() {\n      return address;\n   }\n\n   /**\n    * Describes the address of this resource in the context of the Parent. The\n    * Parent/AddressOnParent properties are used to describe the controller\n    * relationship as well the ordering of devices on a controller.For example,\n    * if the parent is a PCI Controller, this property would specify the PCI\n    * slot of this child device.\n    */\n   public String getAddressOnParent() {\n      return addressOnParent;\n   }\n\n   /**\n    * This property specifies the units of allocation used by the Reservation\n    * and Limit properties. For example, when ResourceType=Processor,\n    * AllocationUnits may be set to hertz*10^6 or percent. When\n    * ResourceType=Memory, AllocationUnits may be set to bytes*10^3. It is\n    * expected that profiles constrain the units that apply in context of\n    * particular resource types. The value of this property shall be a legal\n    * value of the Programmatic Units qualifier as defined in Annex C.1 of\n    * DSP0004 V2.5 or later.\n    */\n   public String getAllocationUnits() {\n      return allocationUnits;\n   }\n\n   /**\n    * This property specifies if the resource will be automatically allocated.\n    * For example when set to true, when the consuming virtual computer system\n    * is powered on, this resource would be allocated. A value of false\n    * indicates the resource must be explicitly allocated. For example, the\n    * setting may represent removable media (cdrom, floppy, etc.) where at power\n    * on time, the media is not present. An explicit operation is required to\n    * allocate the resource.\n    */\n   public Boolean isAutomaticAllocation() {\n      return automaticAllocation;\n   }\n\n   /**\n    * This property specifies if the resource will be automatically\n    * de-allocated. For example, when set to true, when the consuming virtual\n    * computer system is powered off, this resource would be de-allocated. When\n    * set to false, the resource will remain allocated and must be explicitly\n    * de-allocated.\n    */\n   public Boolean isAutomaticDeallocation() {\n      return automaticDeallocation;\n   }\n\n   /**\n    * Describes the consumers visibility to the allocated resource.\n    */\n   public ConsumerVisibility getConsumerVisibility() {\n      return consumerVisibility;\n   }\n\n   /**\n    * This property specifies the upper bound, or maximum amount of resource\n    * that will be granted for this allocation. For example, a system which\n    * supports memory paging may support setting the Limit of a Memory\n    * allocation below that of the VirtualQuantity, thus forcing paging to occur\n    * for this allocation. The value of the Limit property is expressed in the\n    * unit specified by the value of the AllocationUnits property.\n    */\n   public Long getLimit() {\n      return limit;\n   }\n\n   /**\n    * Specifies how this resource maps to underlying resourcesIf the\n    * HostResource array contains any entries, this property reflects how the\n    * resource maps to those specific resources.\n    */\n   public MappingBehavior getMappingBehavior() {\n      return mappingBehavior;\n   }\n\n   /**\n    * A string that describes the resource type when a well defined value is not\n    * available and ResourceType has the value \"Other\".\n    */\n   public String getOtherResourceType() {\n      return otherResourceType;\n   }\n\n   /**\n    * The Parent of the resource. For example, a controller for the current\n    * allocation\n    */\n   public String getParent() {\n      return parent;\n   }\n\n   /**\n    * This property specifies which ResourcePool the resource is currently\n    * allocated from, or which ResourcePool the resource will be allocated from\n    * when the allocation occurs.\n    */\n   public String getPoolID() {\n      return poolID;\n   }\n\n   /**\n    * This property specifies the amount of resource guaranteed to be available\n    * for this allocation. On system which support over-commitment of resources,\n    * this value is typically used for admission control to prevent an an\n    * allocation from being accepted thus preventing starvation. The value of\n    * the Reservation property is expressed in the unit specified by the value\n    * of the AllocationUnits property.\n    */\n   public Long getReservation() {\n      return reservation;\n   }\n\n   /**\n    * A string describing an implementation specific sub-type for this resource.\n    * F\n    */\n   public String getResourceSubType() {\n      return resourceSubType;\n   }\n\n   /**\n    * The type of resource this allocation setting represents.\n    */\n   public ResourceType getResourceType() {\n      return resourceType;\n   }\n\n   /**\n    * This property specifies the quantity of resources presented to the\n    * consumer. For example, when ResourceType=Processor, this property would\n    * reflect the number of discrete Processors presented to the virtual\n    * computer system. When ResourceType=Memory, this property could reflect the\n    * number of MB reported to the virtual computer system. The value of the\n    * VirtualQuantity property should be expressed in units as defined by the\n    * value of the VirtualQuantityUnits property.\n    */\n   public Long getVirtualQuantity() {\n      return virtualQuantity;\n   }\n\n   /**\n    * This property specifies the units used by the VirtualQuantity property.\n    * For example - if ResourceType=Processor, the value of the\n    * VirtualQuantityUnits property may be set to \"count\", indicating that the\n    * value of the VirtualQuantity property is expressed as a count. - if\n    * ResourceType=Memory, the value of the VirtualQuantityUnits property may be\n    * set to \"bytes*10^3\", indicating that the value of the VirtualQuantity\n    * property is expressed in kilobyte. It is expected that profiles constrain\n    * the units that apply in context of particular resource types. The value of\n    * this property shall be a legal value of the Programmatic Units qualifier\n    * as defined in Annex C.1 of DSP0004 V2.5 or later.\n    */\n   public String getVirtualQuantityUnits() {\n      return virtualQuantityUnits;\n   }\n\n   /**\n    * This property specifies a relative priority for this allocation in\n    * relation to other allocations from the same ResourcePool. This property\n    * has no unit of measure, and is only relevant when compared to other\n    * allocations vying for the same host resources.\n    */\n   public Integer getWeight() {\n      return weight;\n   }\n\n   /**\n    * The thing to which this resource is connected. For example, a named\n    * network or switch port.\n    */\n   public List<String> getConnections() {\n      return connections;\n   }\n\n   /**\n    * This property exposes specific assignment of resources. Each non-null\n    * value of the HostResource property shall be formatted as a URI per RFC3986.\n    * If this resource is modeled then a value should be a WBEM URI (DSP0207).\n    * If the resource is not modeled then see the appropriate profile. Profiles\n    * may further constrain the type of URI. A NULL value or empty array\n    * requests the implementation decide the kind of host resource. If the\n    * virtual resource is mapped to more than one underlying resource, this\n    * property may be left NULL. If NULL, the DeviceAllocatedFromPool or\n    * ResourceAllocationFromPool associations may be used to determine the pool\n    * of host resources this virtual resource may use. If specific assignment is\n    * utilized, all underlying resources used by this virtual resource should be\n    * listed.The kind of dependency is specified by the ConsumerVisibility and\n    * the MappingBehavior properties. Typically the array contains one item,\n    * however multiple host resources may be specified. A client may set the\n    * value(s) to indicate that the requested virtual resource allocation be\n    * based on host resources that are identified by element values.\n    */\n   public List<String> getHostResources() {\n      return hostResources;\n   }\n\n   @Override\n   public String toString() {\n      return String\n            .format(\n                  \"[elementName=%s, instanceID=%s, caption=%s, description=%s, address=%s, addressOnParent=%s, allocationUnits=%s, automaticAllocation=%s, automaticDeallocation=%s, connections=%s, consumerVisibility=%s, hostResources=%s, limit=%s, mappingBehavior=%s, otherResourceType=%s, parent=%s, poolID=%s, reservation=%s, resourceSubType=%s, resourceType=%s, virtualQuantity=%s, virtualQuantityUnits=%s, weight=%s]\",\n                  elementName, instanceID, caption, description, address, addressOnParent, allocationUnits,\n                  automaticAllocation, automaticDeallocation, connections, consumerVisibility, hostResources, limit,\n                  mappingBehavior, otherResourceType, parent, poolID, reservation, resourceSubType, resourceType,\n                  virtualQuantity, virtualQuantityUnits, weight);\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = super.hashCode();\n      result = prime * result + ((address == null) ? 0 : address.hashCode());\n      result = prime * result + ((addressOnParent == null) ? 0 : addressOnParent.hashCode());\n      result = prime * result + ((resourceSubType == null) ? 0 : resourceSubType.hashCode());\n      result = prime * result + ((resourceType == null) ? 0 : resourceType.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (!super.equals(obj))\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      ResourceAllocationSettingData other = (ResourceAllocationSettingData) obj;\n      if (address == null) {\n         if (other.address != null)\n            return false;\n      } else if (!address.equals(other.address))\n         return false;\n      if (addressOnParent == null) {\n         if (other.addressOnParent != null)\n            return false;\n      } else if (!addressOnParent.equals(other.addressOnParent))\n         return false;\n      if (resourceSubType == null) {\n         if (other.resourceSubType != null)\n            return false;\n      } else if (!resourceSubType.equals(other.resourceSubType))\n         return false;\n      if (resourceType == null) {\n         if (other.resourceType != null)\n            return false;\n      } else if (!resourceType.equals(other.resourceType))\n         return false;\n      return true;\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/cim/SettingData.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cim;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\n/**\n * \n * The type of resource this allocation setting represents.\n * \n * @see <a\n *      href=\"http://dmtf.org/sites/default/files/cim/cim_schema_v2280/cim_schema_2.28.0Final-Doc.zip\"\n *      />\n */\npublic abstract class SettingData implements Comparable<SettingData> {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().fromSettingData(this);\n   }\n\n   public static class Builder {\n      protected String elementName;\n      protected String instanceID;\n\n      /**\n       * @see SettingData#getElementName\n       */\n      public Builder elementName(String elementName) {\n         this.elementName = checkNotNull(elementName, \"elementName\");\n         return this;\n      }\n\n      /**\n       * @see SettingData#getInstanceID\n       */\n      public Builder instanceID(String instanceID) {\n         this.instanceID = checkNotNull(instanceID, \"instanceID\");\n         return this;\n      }\n\n      public Builder fromSettingData(SettingData in) {\n         return elementName(in.getElementName()).instanceID(in.getInstanceID());\n      }\n   }\n\n   protected final String elementName;\n   protected final String instanceID;\n\n   public SettingData(String elementName, String instanceID) {\n      this.elementName = checkNotNull(elementName, \"elementName\");\n      this.instanceID = checkNotNull(instanceID, \"instanceID\");\n   }\n\n   /**\n    * The user-friendly name for this instance of SettingData. In addition, the user-friendly name\n    * can be used as an index property for a search or query. (Note: The name does not have to be\n    * unique within a namespace.)\n    */\n   public String getElementName() {\n      return elementName;\n   }\n\n   /**\n    * Within the scope of the instantiating Namespace, InstanceID opaquely and uniquely identifies\n    * an instance of this class.\n    */\n   public String getInstanceID() {\n      return instanceID;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((elementName == null) ? 0 : elementName.hashCode());\n      result = prime * result + ((instanceID == null) ? 0 : instanceID.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      SettingData other = (SettingData) obj;\n      if (elementName == null) {\n         if (other.elementName != null)\n            return false;\n      } else if (!elementName.equals(other.elementName))\n         return false;\n      if (instanceID == null) {\n         if (other.instanceID != null)\n            return false;\n      } else if (!instanceID.equals(other.instanceID))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return String.format(\"[elementName=%s, instanceID=%s]\", elementName, instanceID);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public int compareTo(SettingData o) {\n      if (instanceID == null)\n         return -1;\n      return (this == o) ? 0 : instanceID.compareTo(o.instanceID);\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/cim/VirtualSystemSettingData.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cim;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.Map;\nimport java.util.Set;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Maps;\nimport com.google.common.collect.Sets;\n\n/**\n * \n * CIM_VirtualSystemSettingData defines the virtual aspects of a virtual system through a set of\n * virtualization specific properties. CIM_VirtualSystemSettingData is also used as the top level\n * class of virtual system configurations. Virtual system configurations model configuration\n * information about virtual systems and their components. A virtual system configuration consists\n * of one top-level instance of class CIM_VirtualSystemSettingData that aggregates a number of\n * instances of class CIM_ResourceAllocationSettingData, using association CIM_ConcreteComponent.\n * Virtual system configurations may for example be used to reflect configurations of - virtual\n * systems that are defined at a virtualization platform, - virtual systems that are currently\n * active, - input requests to create new virtual systems, - input requests to modify existing\n * virtual systems, or - snapshots of virtual systems.\n * \n * @see <a\n *      href=\"http://dmtf.org/sites/default/files/cim/cim_schema_v2280/cim_schema_2.28.0Final-Doc.zip\"\n *      />\n */\npublic class VirtualSystemSettingData extends ManagedElement {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Builder toBuilder() {\n      return builder().fromVirtualSystemSettingData(this);\n   }\n\n   public static class Builder extends ManagedElement.Builder {\n      private AutomaticRecoveryAction automaticRecoveryAction;\n      private AutomaticShutdownAction automaticShutdownAction;\n      private AutomaticStartupAction automaticStartupAction;\n      private Long automaticStartupActionDelay;\n      private Integer automaticStartupActionSequenceNumber;\n      private URI configurationDataRoot;\n      private URI configurationFile;\n      private String configurationID;\n      private Date creationTime;\n      private URI logDataRoot;\n      private URI recoveryFile;\n      private URI snapshotDataRoot;\n      private URI suspendDataRoot;\n      private URI swapFileDataRoot;\n      private String virtualSystemIdentifier;\n      private Set<String> virtualSystemTypes = Sets.newLinkedHashSet();\n      private String notes;\n\n      public Builder automaticRecoveryAction(AutomaticRecoveryAction automaticRecoveryAction) {\n         this.automaticRecoveryAction = automaticRecoveryAction;\n         return this;\n      }\n\n      public Builder automaticShutdownAction(AutomaticShutdownAction automaticShutdownAction) {\n         this.automaticShutdownAction = automaticShutdownAction;\n         return this;\n      }\n\n      public Builder automaticStartupAction(AutomaticStartupAction automaticStartupAction) {\n         this.automaticStartupAction = automaticStartupAction;\n         return this;\n      }\n\n      public Builder automaticStartupActionDelay(Long automaticStartupActionDelay) {\n         this.automaticStartupActionDelay = automaticStartupActionDelay;\n         return this;\n      }\n\n      public Builder automaticStartupActionSequenceNumber(Integer automaticStartupActionSequenceNumber) {\n         this.automaticStartupActionSequenceNumber = automaticStartupActionSequenceNumber;\n         return this;\n      }\n\n      public Builder configurationDataRoot(URI configurationDataRoot) {\n         this.configurationDataRoot = configurationDataRoot;\n         return this;\n      }\n\n      public Builder configurationFile(URI configurationFile) {\n         this.configurationFile = configurationFile;\n         return this;\n      }\n\n      public Builder configurationID(String configurationID) {\n         this.configurationID = configurationID;\n         return this;\n      }\n\n      public Builder creationTime(Date creationTime) {\n         this.creationTime = creationTime;\n         return this;\n      }\n\n      public Builder logDataRoot(URI logDataRoot) {\n         this.logDataRoot = logDataRoot;\n         return this;\n      }\n\n      public Builder recoveryFile(URI recoveryFile) {\n         this.recoveryFile = recoveryFile;\n         return this;\n      }\n\n      public Builder snapshotDataRoot(URI snapshotDataRoot) {\n         this.snapshotDataRoot = snapshotDataRoot;\n         return this;\n      }\n\n      public Builder suspendDataRoot(URI suspendDataRoot) {\n         this.suspendDataRoot = suspendDataRoot;\n         return this;\n      }\n\n      public Builder swapFileDataRoot(URI swapFileDataRoot) {\n         this.swapFileDataRoot = swapFileDataRoot;\n         return this;\n      }\n\n      public Builder virtualSystemIdentifier(String virtualSystemIdentifier) {\n         this.virtualSystemIdentifier = virtualSystemIdentifier;\n         return this;\n      }\n\n      public Builder virtualSystemTypes(Iterable<String> virtualSystemTypes) {\n         this.virtualSystemTypes = ImmutableSet.copyOf(checkNotNull(virtualSystemTypes, \"virtualSystemTypes\"));\n         return this;\n      }\n\n      public Builder virtualSystemType(String virtualSystemType) {\n         this.virtualSystemTypes.add(checkNotNull(virtualSystemType, \"virtualSystemType\"));\n         return this;\n      }\n\n      public Builder notes(String notes) {\n         this.notes = notes;\n         return this;\n      }\n\n      public VirtualSystemSettingData build() {\n         return new VirtualSystemSettingData(elementName, instanceID, caption, description, automaticRecoveryAction,\n                  automaticShutdownAction, automaticStartupAction, automaticStartupActionDelay,\n                  automaticStartupActionSequenceNumber, configurationDataRoot, configurationFile, configurationID,\n                  creationTime, logDataRoot, recoveryFile, snapshotDataRoot, suspendDataRoot, swapFileDataRoot,\n                  virtualSystemIdentifier, virtualSystemTypes, notes);\n      }\n\n      public Builder fromVirtualSystemSettingData(VirtualSystemSettingData in) {\n         return fromManagedElement(in).automaticRecoveryAction(in.getAutomaticRecoveryAction())\n                  .automaticShutdownAction(in.getAutomaticShutdownAction()).automaticStartupAction(\n                           in.getAutomaticStartupAction()).automaticStartupActionDelay(\n                           in.getAutomaticStartupActionDelay()).automaticStartupActionSequenceNumber(\n                           in.getAutomaticStartupActionSequenceNumber()).configurationDataRoot(\n                           in.getConfigurationDataRoot()).configurationFile(in.getConfigurationFile()).configurationID(\n                           in.getConfigurationID()).creationTime(in.getCreationTime()).logDataRoot(in.getLogDataRoot())\n                  .recoveryFile(in.getRecoveryFile()).snapshotDataRoot(in.getSnapshotDataRoot()).suspendDataRoot(\n                           in.getSuspendDataRoot()).swapFileDataRoot(in.getSwapFileDataRoot()).virtualSystemIdentifier(\n                           in.getVirtualSystemIdentifier()).virtualSystemTypes(in.getVirtualSystemTypes()).notes(\n                           in.getNotes());\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder fromManagedElement(ManagedElement in) {\n         return Builder.class.cast(super.fromManagedElement(in));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder caption(String caption) {\n         return Builder.class.cast(super.caption(caption));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder description(String description) {\n         return Builder.class.cast(super.description(description));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder elementName(String elementName) {\n         return Builder.class.cast(super.elementName(elementName));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder instanceID(String instanceID) {\n         return Builder.class.cast(super.instanceID(instanceID));\n      }\n\n   }\n\n   /**\n    * Action to take for the virtual system when the software executed by the virtual system fails.\n    * Failures in this case means a failure that is detectable by the host platform, such as a\n    * non-interruptible wait state condition.\n    */\n   public static enum AutomaticRecoveryAction {\n\n      NONE(2),\n\n      RESTART(3),\n\n      REVERT_TO_SNAPSHOT(4);\n\n      protected final int code;\n\n      AutomaticRecoveryAction(int code) {\n         this.code = code;\n      }\n\n      public String value() {\n         return code + \"\";\n      }\n\n      protected static final Map<Integer, AutomaticRecoveryAction> AUTOMATIC_RECOVERY_ACTION_BY_ID = Maps.uniqueIndex(\n               ImmutableSet.copyOf(AutomaticRecoveryAction.values()), new Function<AutomaticRecoveryAction, Integer>() {\n\n                  @Override\n                  public Integer apply(AutomaticRecoveryAction input) {\n                     return input.code;\n                  }\n\n               });\n\n      public static AutomaticRecoveryAction fromValue(String automaticRecoveryAction) {\n         return AUTOMATIC_RECOVERY_ACTION_BY_ID.get(Integer.valueOf(checkNotNull(automaticRecoveryAction,\n                  \"automaticRecoveryAction\")));\n      }\n   }\n\n   /**\n    * Action to take for the virtual system when the host is shut down.\n    */\n   public static enum AutomaticShutdownAction {\n\n      TURN_OFF(2),\n\n      SAVE_STATE(3),\n\n      SHUTDOWN(4);\n\n      protected final int code;\n\n      AutomaticShutdownAction(int code) {\n         this.code = code;\n      }\n\n      public String value() {\n         return code + \"\";\n      }\n\n      protected static final Map<Integer, AutomaticShutdownAction> AUTOMATIC_SHUTDOWN_ACTION_BY_ID = Maps.uniqueIndex(\n               ImmutableSet.copyOf(AutomaticShutdownAction.values()), new Function<AutomaticShutdownAction, Integer>() {\n\n                  @Override\n                  public Integer apply(AutomaticShutdownAction input) {\n                     return input.code;\n                  }\n\n               });\n\n      public static AutomaticShutdownAction fromValue(String automaticShutdownAction) {\n         return AUTOMATIC_SHUTDOWN_ACTION_BY_ID.get(Integer.valueOf(checkNotNull(automaticShutdownAction,\n                  \"automaticShutdownAction\")));\n      }\n   }\n\n   /**\n    * Action to take for the virtual system when the host is started.\n    */\n   public static enum AutomaticStartupAction {\n\n      NONE(2),\n\n      RESTART_IF_PREVIOUSLY_ACTIVE(3),\n\n      ALWAYS_STARTUP(4);\n\n      protected final int code;\n\n      AutomaticStartupAction(int code) {\n         this.code = code;\n      }\n\n      public String value() {\n         return code + \"\";\n      }\n\n      protected static final Map<Integer, AutomaticStartupAction> AUTOMATIC_STARTUP_ACTION_BY_ID = Maps.uniqueIndex(\n               ImmutableSet.copyOf(AutomaticStartupAction.values()), new Function<AutomaticStartupAction, Integer>() {\n\n                  @Override\n                  public Integer apply(AutomaticStartupAction input) {\n                     return input.code;\n                  }\n\n               });\n\n      public static AutomaticStartupAction fromValue(String automaticStartupAction) {\n         return AUTOMATIC_STARTUP_ACTION_BY_ID.get(Integer.valueOf(checkNotNull(automaticStartupAction,\n                  \"automaticStartupAction\")));\n      }\n   }\n\n   private final AutomaticRecoveryAction automaticRecoveryAction;\n   private final AutomaticShutdownAction automaticShutdownAction;\n   private final AutomaticStartupAction automaticStartupAction;\n   private final Long automaticStartupActionDelay;\n   private final Integer automaticStartupActionSequenceNumber;\n   private final URI configurationDataRoot;\n   private final URI configurationFile;\n   private final String configurationID;\n   private final Date creationTime;\n   private final URI logDataRoot;\n   private final URI recoveryFile;\n   private final URI snapshotDataRoot;\n   private final URI suspendDataRoot;\n   private final URI swapFileDataRoot;\n   private final String virtualSystemIdentifier;\n   private final Set<String> virtualSystemTypes;\n   private final String notes;\n\n   public VirtualSystemSettingData(String elementName, String instanceID, String caption, String description,\n            AutomaticRecoveryAction automaticRecoveryAction, AutomaticShutdownAction automaticShutdownAction,\n            AutomaticStartupAction automaticStartupAction, Long automaticStartupActionDelay,\n            Integer automaticStartupActionSequenceNumber, URI configurationDataRoot, URI configurationFile,\n            String configurationID, Date creationTime, URI logDataRoot, URI recoveryFile, URI snapshotDataRoot,\n            URI suspendDataRoot, URI swapFileDataRoot, String virtualSystemIdentifier,\n            Iterable<String> virtualSystemTypes, String notes) {\n      super(elementName, instanceID, caption, description);\n      this.automaticRecoveryAction = automaticRecoveryAction;\n      this.automaticShutdownAction = automaticShutdownAction;\n      this.automaticStartupAction = automaticStartupAction;\n      this.automaticStartupActionDelay = automaticStartupActionDelay;\n      this.automaticStartupActionSequenceNumber = automaticStartupActionSequenceNumber;\n      this.configurationDataRoot = configurationDataRoot;\n      this.configurationFile = configurationFile;\n      this.configurationID = configurationID;\n      this.creationTime = creationTime;\n      this.logDataRoot = logDataRoot;\n      this.recoveryFile = recoveryFile;\n      this.snapshotDataRoot = snapshotDataRoot;\n      this.suspendDataRoot = suspendDataRoot;\n      this.swapFileDataRoot = swapFileDataRoot;\n      this.virtualSystemIdentifier = virtualSystemIdentifier;\n      this.virtualSystemTypes = ImmutableSet.copyOf(checkNotNull(virtualSystemTypes, \"virtualSystemTypes\"));\n      this.notes = notes;\n   }\n\n   /**\n    * Action to take for the virtual system when the software executed by the virtual system fails.\n    * Failures in this case means a failure that is detectable by the host platform, such as a\n    * non-interruptible wait state condition.\n    */\n   public AutomaticRecoveryAction getAutomaticRecoveryAction() {\n      return automaticRecoveryAction;\n   }\n\n   /**\n    * Action to take for the virtual system when the host is shut down.\n    */\n   public AutomaticShutdownAction getAutomaticShutdownAction() {\n      return automaticShutdownAction;\n   }\n\n   /**\n    * Action to take for the virtual system when the host is started.\n    */\n   public AutomaticStartupAction getAutomaticStartupAction() {\n      return automaticStartupAction;\n   }\n\n   /**\n    * Delay applicable to startup action. The value shall be in the interval variant of the datetime\n    * datatype.\n    */\n   public Long getAutomaticStartupActionDelay() {\n      return automaticStartupActionDelay;\n   }\n\n   /**\n    * Number indicating the relative sequence of virtual system activation when the host system is\n    * started. A lower number indicates earlier activation. If one or more configurations show the\n    * same value, the sequence is implementation dependent. A value of 0 indicates that the sequence\n    * is implementation dependent.\n    */\n   public Integer getAutomaticStartupActionSequenceNumber() {\n      return automaticStartupActionSequenceNumber;\n   }\n\n   /**\n    * Filepath of a directory where information about the virtual system configuration is\n    * stored.Format shall be URI based on RFC 2079.\n    */\n   public URI getConfigurationDataRoot() {\n      return configurationDataRoot;\n   }\n\n   /**\n    * Filepath of a file where information about the virtual system configuration is stored. A\n    * relative path appends to the value of the ConfigurationDataRoot property.Format shall be URI\n    * based on RFC 2079.\n    */\n   public URI getConfigurationFile() {\n      return configurationFile;\n   }\n\n   /**\n    * Unique id of the virtual system configuration. Note that the ConfigurationID is different from\n    * the InstanceID as it is assigned by the implementation to a virtual system or a virtual system\n    * configuration. It is not a key, and the same value may occur within more than one instance.\n    */\n   public String getConfigurationID() {\n      return configurationID;\n   }\n\n   /**\n    * Time when the virtual system configuration was created.\n    */\n   public Date getCreationTime() {\n      return creationTime;\n   }\n\n   /**\n    * Filepath of a directory where log information about the virtual system is stored. A relative\n    * path appends to the value of the ConfigurationDataRoot property.Format shall be URI based on\n    * RFC 2079.\n    */\n   public URI getLogDataRoot() {\n      return logDataRoot;\n   }\n\n   /**\n    * Filepath of a file where recovery related information of the virtual system is stored.Format\n    * shall be URI based on RFC 2079.\n    */\n   public URI getRecoveryFile() {\n      return recoveryFile;\n   }\n\n   /**\n    * Filepath of a directory where information about virtual system snapshots is stored. A relative\n    * path appends to the value of the ConfigurationDataRoot property.Format shall be URI based on\n    * RFC 2079.\n    */\n   public URI getSnapshotDataRoot() {\n      return snapshotDataRoot;\n   }\n\n   /**\n    * Filepath of a directory where suspend related information about the virtual system is stored.\n    * A relative path appends to the value of the ConfigurationDataRoot property.Format shall be URI\n    * based on RFC 2079.\n    */\n   public URI getSuspendDataRoot() {\n      return suspendDataRoot;\n   }\n\n   /**\n    * Filepath of a directory where swapfiles of the virtual system are stored. A relative path\n    * appends to the value of the ConfigurationDataRoot property.Format shall be URI based on RFC\n    * 2079.\n    */\n   public URI getSwapFileDataRoot() {\n      return swapFileDataRoot;\n   }\n\n   /**\n    * VirtualSystemIdentifier shall reflect a unique name for the system as it is used within the\n    * virtualization platform. Note that the VirtualSystemIdentifier is not the hostname assigned to\n    * the operating system instance running within the virtual system, nor is it an IP address or\n    * MAC address assigned to any of its network ports. On create requests VirtualSystemIdentifier\n    * may contain implementation specific rules (like simple patterns or regular expression) that\n    * may be interpreted by the implementation when assigning a VirtualSystemIdentifier.\n    */\n   public String getVirtualSystemIdentifier() {\n      return virtualSystemIdentifier;\n   }\n\n   /**\n    * VirtualSystemType shall reflect a particular type of virtual system.\n    */\n   public Set<String> getVirtualSystemTypes() {\n      return virtualSystemTypes;\n   }\n\n   /**\n    * End-user supplied notes that are related to the virtual system.\n    */\n   public String getNotes() {\n      return notes;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = super.hashCode();\n      result = prime * result + ((virtualSystemIdentifier == null) ? 0 : virtualSystemIdentifier.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (!super.equals(obj))\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      VirtualSystemSettingData other = (VirtualSystemSettingData) obj;\n      if (virtualSystemIdentifier == null) {\n         if (other.virtualSystemIdentifier != null)\n            return false;\n      } else if (!virtualSystemIdentifier.equals(other.virtualSystemIdentifier))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return String\n               .format(\n                        \"[elementName=%s, instanceID=%s, caption=%s, description=%s, automaticRecoveryAction=%s, automaticShutdownAction=%s, automaticStartupAction=%s, automaticStartupActionDelay=%s, automaticStartupActionSequenceNumber=%s, configurationDataRoot=%s, configurationFile=%s, configurationID=%s, creationTime=%s, logDataRoot=%s, notes=%s, recoveryFile=%s, snapshotDataRoot=%s, suspendDataRoot=%s, swapFileDataRoot=%s, virtualSystemIdentifier=%s, virtualSystemTypes=%s]\",\n                        elementName, instanceID, caption, description, automaticRecoveryAction,\n                        automaticShutdownAction, automaticStartupAction, automaticStartupActionDelay,\n                        automaticStartupActionSequenceNumber, configurationDataRoot, configurationFile,\n                        configurationID, creationTime, logDataRoot, notes, recoveryFile, snapshotDataRoot,\n                        suspendDataRoot, swapFileDataRoot, virtualSystemIdentifier, virtualSystemTypes);\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/cim/functions/HardwareBuilderFromResourceAllocations.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cim.functions;\n\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.find;\nimport static com.google.common.collect.Iterables.transform;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.cim.CIMPredicates;\nimport org.jclouds.cim.ResourceAllocationSettingData;\nimport org.jclouds.cim.ResourceAllocationSettingData.ResourceType;\nimport org.jclouds.compute.domain.HardwareBuilder;\nimport org.jclouds.compute.domain.Processor;\nimport org.jclouds.compute.domain.Volume;\nimport org.jclouds.compute.domain.internal.VolumeImpl;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class HardwareBuilderFromResourceAllocations implements\n         Function<Iterable<? extends ResourceAllocationSettingData>, HardwareBuilder> {\n   @Override\n   public HardwareBuilder apply(Iterable<? extends ResourceAllocationSettingData> from) {\n      HardwareBuilder builder = new HardwareBuilder();\n      builder.volumes(transform(filter(from, CIMPredicates.resourceTypeIn(ResourceType.DISK_DRIVE,\n               ResourceType.BASE_PARTITIONABLE_UNIT, ResourceType.PARTITIONABLE_UNIT)),\n               new Function<ResourceAllocationSettingData, Volume>() {\n\n                  @Override\n                  public Volume apply(ResourceAllocationSettingData from) {\n                     return HardwareBuilderFromResourceAllocations.this.apply(from);\n                  }\n\n               }));\n\n      builder.ram((int) find(from, CIMPredicates.resourceTypeIn(ResourceType.MEMORY)).getVirtualQuantity().longValue());\n\n      builder.processors(transform(filter(from, CIMPredicates.resourceTypeIn(ResourceType.PROCESSOR)),\n               new Function<ResourceAllocationSettingData, Processor>() {\n\n                  @Override\n                  public Processor apply(ResourceAllocationSettingData arg0) {\n                     return new Processor(arg0.getVirtualQuantity(), 1);\n                  }\n               }));\n      return builder;\n   }\n\n   public Volume apply(ResourceAllocationSettingData from) {\n      return new VolumeImpl(from.getAddressOnParent() + \"\", Volume.Type.LOCAL, from.getVirtualQuantity() == null ? null\n               : from.getVirtualQuantity() / (float) (1024 * 1024), null, \"0\".equals(from.getAddressOnParent())\n               || ResourceType.BASE_PARTITIONABLE_UNIT.equals(from.getResourceType()), true);\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/cim/xml/ResourceAllocationSettingDataHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cim.xml;\n\nimport static org.jclouds.util.SaxUtils.currentOrNull;\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport org.jclouds.cim.ResourceAllocationSettingData;\nimport org.jclouds.cim.ResourceAllocationSettingData.ConsumerVisibility;\nimport org.jclouds.cim.ResourceAllocationSettingData.MappingBehavior;\nimport org.jclouds.cim.ResourceAllocationSettingData.ResourceType;\nimport org.jclouds.http.functions.ParseSax;\nimport org.xml.sax.Attributes;\n\npublic class ResourceAllocationSettingDataHandler extends ParseSax.HandlerWithResult<ResourceAllocationSettingData> {\n   protected StringBuilder currentText = new StringBuilder();\n\n   protected ResourceAllocationSettingData.Builder builder = ResourceAllocationSettingData.builder();\n\n   public ResourceAllocationSettingData getResult() {\n      try {\n         return builder.build();\n      } finally {\n         builder = ResourceAllocationSettingData.builder();\n      }\n   }\n\n   @Override\n   public void startElement(String uri, String localName, String qName, Attributes attrs) {\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) {\n      String current = currentOrNull(currentText);\n      if (current != null) {\n         if (equalsOrSuffix(qName, \"ElementName\")) {\n            builder.elementName(current);\n         } else if (equalsOrSuffix(qName, \"InstanceID\")) {\n            builder.instanceID(current);\n         } else if (equalsOrSuffix(qName, \"Caption\")) {\n            builder.caption(current);\n         } else if (equalsOrSuffix(qName, \"Description\")) {\n            builder.description(current);\n         } else if (equalsOrSuffix(qName, \"Address\")) {\n            builder.address(current);\n         } else if (equalsOrSuffix(qName, \"AddressOnParent\")) {\n            builder.addressOnParent(current);\n         } else if (equalsOrSuffix(qName, \"AllocationUnits\")) {\n            builder.allocationUnits(current);\n         } else if (equalsOrSuffix(qName, \"AutomaticAllocation\")) {\n            builder.automaticAllocation(Boolean.valueOf(current));\n         } else if (equalsOrSuffix(qName, \"AutomaticDeallocation\")) {\n            builder.automaticDeallocation(Boolean.valueOf(current));\n         } else if (equalsOrSuffix(qName, \"ConsumerVisibility\")) {\n            builder.consumerVisibility(ConsumerVisibility.fromValue(current));\n         } else if (equalsOrSuffix(qName, \"Limit\")) {\n            builder.limit(Long.valueOf(current));\n         } else if (equalsOrSuffix(qName, \"MappingBehavior\")) {\n            builder.mappingBehavior(MappingBehavior.fromValue(current));\n         } else if (equalsOrSuffix(qName, \"OtherResourceType\")) {\n            builder.otherResourceType(current);\n         } else if (equalsOrSuffix(qName, \"Parent\")) {\n            builder.parent(current);\n         } else if (equalsOrSuffix(qName, \"PoolID\")) {\n            builder.poolID(current);\n         } else if (equalsOrSuffix(qName, \"Reservation\")) {\n            builder.reservation(Long.valueOf(current));\n         } else if (equalsOrSuffix(qName, \"ResourceSubType\")) {\n            builder.resourceSubType(current);\n         } else if (equalsOrSuffix(qName, \"ResourceType\")) {\n            builder.resourceType(ResourceType.fromValue(current));\n         } else if (equalsOrSuffix(qName, \"VirtualQuantity\")) {\n            builder.virtualQuantity(Long.valueOf(current));\n         } else if (equalsOrSuffix(qName, \"VirtualQuantityUnits\")) {\n            builder.virtualQuantityUnits(current);\n         } else if (equalsOrSuffix(qName, \"Weight\")) {\n            builder.weight(Integer.valueOf(current));\n         } else if (equalsOrSuffix(qName, \"Connection\")) {\n            builder.connection(current);\n         } else if (equalsOrSuffix(qName, \"HostResource\")) {\n            builder.hostResource(current);\n         }\n      }\n      currentText.setLength(0);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/cim/xml/VirtualSystemSettingDataHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.cim.xml;\n\nimport static org.jclouds.util.SaxUtils.currentOrNull;\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport java.net.URI;\n\nimport org.jclouds.cim.VirtualSystemSettingData;\nimport org.jclouds.cim.VirtualSystemSettingData.AutomaticRecoveryAction;\nimport org.jclouds.cim.VirtualSystemSettingData.AutomaticShutdownAction;\nimport org.jclouds.cim.VirtualSystemSettingData.AutomaticStartupAction;\nimport org.jclouds.http.functions.ParseSax;\nimport org.xml.sax.Attributes;\n\nimport com.google.common.base.Splitter;\n\npublic class VirtualSystemSettingDataHandler extends ParseSax.HandlerWithResult<VirtualSystemSettingData> {\n   protected StringBuilder currentText = new StringBuilder();\n\n   protected VirtualSystemSettingData.Builder builder = VirtualSystemSettingData.builder();\n\n   public VirtualSystemSettingData getResult() {\n      try {\n         return builder.build();\n      } finally {\n         builder = VirtualSystemSettingData.builder();\n      }\n   }\n\n   @Override\n   public void startElement(String uri, String localName, String qName, Attributes attrs) {\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) {\n      String current = currentOrNull(currentText);\n      if (current != null) {\n         if (equalsOrSuffix(qName, \"ElementName\")) {\n            builder.elementName(current);\n         } else if (equalsOrSuffix(qName, \"InstanceID\")) {\n            builder.instanceID(current);\n         } else if (equalsOrSuffix(qName, \"Caption\")) {\n            builder.caption(current);\n         } else if (equalsOrSuffix(qName, \"Description\")) {\n            builder.description(current);\n         } else if (equalsOrSuffix(qName, \"AutomaticRecoveryAction\")) {\n            builder.automaticRecoveryAction(AutomaticRecoveryAction.fromValue(current));\n         } else if (equalsOrSuffix(qName, \"AutomaticShutdownAction\")) {\n            builder.automaticShutdownAction(AutomaticShutdownAction.fromValue(current));\n         } else if (equalsOrSuffix(qName, \"AutomaticStartupAction\")) {\n            builder.automaticStartupAction(AutomaticStartupAction.fromValue(current));\n         } else if (equalsOrSuffix(qName, \"AutomaticStartupActionDelay\")) {\n            // TODO parse the format for intervals: ddddddddhhmmss.mmmmmm:000\n            builder.automaticStartupActionDelay(null);\n         } else if (equalsOrSuffix(qName, \"AutomaticStartupActionSequenceNumber\")) {\n            builder.automaticStartupActionSequenceNumber(Integer.valueOf(current));\n         } else if (equalsOrSuffix(qName, \"ConfigurationDataRoot\")) {\n            builder.configurationDataRoot(URI.create(current));\n         } else if (equalsOrSuffix(qName, \"ConfigurationFile\")) {\n            builder.configurationFile(URI.create(current));\n         } else if (equalsOrSuffix(qName, \"ConfigurationID\")) {\n            builder.configurationID(current);\n         } else if (equalsOrSuffix(qName, \"CreationTime\")) {\n            // TODO parse the format for timestamps: yyyymmddhhmmss.mmmmmmsutc\n            builder.creationTime(null);\n         } else if (equalsOrSuffix(qName, \"LogDataRoot\")) {\n            builder.logDataRoot(URI.create(current));\n         } else if (equalsOrSuffix(qName, \"RecoveryFile\")) {\n            builder.recoveryFile(URI.create(current));\n         } else if (equalsOrSuffix(qName, \"SuspendDataRoot\")) {\n            builder.suspendDataRoot(URI.create(current));\n         } else if (equalsOrSuffix(qName, \"SwapFileDataRoot\")) {\n            builder.swapFileDataRoot(URI.create(current));\n         } else if (equalsOrSuffix(qName, \"VirtualSystemIdentifier\")) {\n            builder.virtualSystemIdentifier(current);\n         } else if (equalsOrSuffix(qName, \"VirtualSystemType\")) {\n            builder.virtualSystemTypes(Splitter.on(',').trimResults().omitEmptyStrings().split(current));\n         } else if (equalsOrSuffix(qName, \"Notes\")) {\n            builder.notes(current);\n         }\n      }\n      currentText.setLength(0);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/ComputeService.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.ComputeMetadata;\nimport org.jclouds.compute.domain.ExecResponse;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.domain.TemplateBuilder;\nimport org.jclouds.compute.extensions.ImageExtension;\nimport org.jclouds.compute.extensions.SecurityGroupExtension;\nimport org.jclouds.compute.internal.BaseComputeService;\nimport org.jclouds.compute.options.RunScriptOptions;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.domain.Location;\nimport org.jclouds.scriptbuilder.domain.Statement;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.inject.ImplementedBy;\n\n/**\n * Provides portable access to launching compute instances.\n */\n@ImplementedBy(BaseComputeService.class)\npublic interface ComputeService {\n\n   /**\n    * @return a reference to the context that created this ComputeService.\n    */\n   ComputeServiceContext getContext();\n\n   /**\n    * Makes a new template builder for this service\n    */\n   TemplateBuilder templateBuilder();\n\n   /**\n    * Makes a new set of options for running nodes\n    */\n   TemplateOptions templateOptions();\n\n   /**\n    * The list hardware profiles command shows you the options including virtual cpu count, memory,\n    * and disks. cpu count is not a portable quantity across clouds, as they are measured\n    * differently. However, it is a good indicator of relative speed within a cloud. memory is\n    * measured in megabytes and disks in gigabytes.\n    * \n    * <h3>note</h3>\n    * \n    * This is a cached collection\n    */\n   Set<? extends Hardware> listHardwareProfiles();\n\n   /**\n    * Images define the operating system and metadata related to a node. In some clouds, Images are\n    * bound to a specific region, and their identifiers are different across these regions. For this\n    * reason, you should consider matching image requirements like operating system family with\n    * TemplateBuilder as opposed to choosing an image explicitly.\n    * \n    * <h3>note</h3>\n    * \n    * This is a cached collection\n    */\n   Set<? extends Image> listImages();\n   \n   /**\n    * Find an image by its id.\n    * \n    * <h3>note</h3>\n    * \n    * This is an uncached call to the backend service\n    */\n   Image getImage(String id);\n\n   /**\n    * @return all nodes available to the current user. If possible, the returned set will include\n    * {@link NodeMetadata} objects.\n    */\n   Set<? extends ComputeMetadata> listNodes();\n\n   /**\n    * @return all nodes with one of the provided ids available to the current user.\n    */\n   Set<? extends ComputeMetadata> listNodesByIds(Iterable<String> ids);\n\n   /**\n    * The list locations command returns all the valid locations for nodes. A location has a scope,\n    * which is typically region or zone. A region is a general area, like eu-west, where a zone is\n    * similar to a datacenter. If a location has a parent, that implies it is within that location.\n    * For example a location can be a rack, whose parent is likely to be a zone.\n    * \n    * <h3>note</h3>\n    * \n    * This is a cached collection\n    */\n   Set<? extends Location> listAssignableLocations();\n\n   /**\n    * \n    * The compute api treats nodes as a group based on the name you specify. Using this group, you\n    * can choose to operate one or many nodes as a logical unit without regard to the implementation\n    * details of the cloud.\n    * <p/>\n    * \n    * The set that is returned will include credentials you can use to ssh into the nodes. The \"key\"\n    * part of the credentials is either a password or a private key. You have to inspect the value\n    * to determine this.\n    * \n    * <pre>\n    * if (node.getCredentials().key.startsWith(\"-----BEGIN RSA PRIVATE KEY-----\"))\n    *    // it is a private key, not a password.\n    * </pre>\n    * \n    * <p/>\n    * Note. if all you want to do is execute a script at bootup, you should consider use of the\n    * runscript option.\n    * <p/>\n    * If resources such as security groups are needed, they will be reused or created for you.\n    * Inbound port 22 will always be opened up.\n    * \n    * <h3>Note</h3>\n    * \n    * While naming constraints on the group name vary per cloud, lower-case alphanumeric with\n    * hyphens and least characters practical is most compatible.\n    * \n    * @param group\n    *           - common identifier to group nodes by\n    * @param count\n    *           - how many to fire up.\n    * @param template\n    *           - how to configure the nodes\n    * @return all of the nodes the api was able to launch in a running state.\n    * \n    * @throws RunNodesException\n    *            when there's a problem applying options to nodes. Note that successful and failed\n    *            nodes are a part of this exception, so be sure to inspect this carefully.\n    */\n   Set<? extends NodeMetadata> createNodesInGroup(String group, int count, Template template) throws RunNodesException;\n\n   /**\n    * Like {@link ComputeService#createNodesInGroup(String,int,Template)}, except that the template\n    * is default, equivalent to {@code templateBuilder().any().options(templateOptions)}.\n    */\n   Set<? extends NodeMetadata> createNodesInGroup(String group, int count, TemplateOptions templateOptions)\n            throws RunNodesException;\n\n   /**\n    * Like {@link ComputeService#createNodesInGroup(String,int,TemplateOptions)}, except that the\n    * options are default, as specified in {@link ComputeService#templateOptions}.\n    */\n   Set<? extends NodeMetadata> createNodesInGroup(String group, int count) throws RunNodesException;\n\n   /**\n    * resume the node from {@link org.jclouds.compute.domain.NodeState#SUSPENDED suspended} state,\n    * given its id.\n    * \n    * <h4>note</h4>\n    * \n    * affected nodes may not resume with the same IP address(es)\n    */\n   void resumeNode(String id);\n\n   /**\n    * nodes matching the filter are treated as a logical set. Using the resume command, you can save\n    * time by resuming the nodes in parallel.\n    * \n    * <h4>note</h4>\n    * \n    * affected nodes may not resume with the same IP address(es)\n    * \n    * @return list of nodes resumed\n    *\n    * @throws UnsupportedOperationException\n    *            if the underlying provider doesn't support suspend/resume\n    * @throws NoSuchElementException\n    *            if no nodes matched the predicate specified\n    */\n   Set<? extends NodeMetadata> resumeNodesMatching(Predicate<? super NodeMetadata> filter);\n\n   /**\n    * suspend the node, given its id. This will result in\n    * {@link org.jclouds.compute.domain.NodeState#SUSPENDED suspended} state.\n    * \n    * <h4>note</h4>\n    * \n    * affected nodes may not resume with the same IP address(es)\n    * \n    * @throws UnsupportedOperationException\n    *            if the underlying provider doesn't support suspend/resume\n    */\n   void suspendNode(String id);\n\n   /**\n    * nodes matching the filter are treated as a logical set. Using the suspend command, you can\n    * save time by suspending the nodes in parallel.\n    * \n    * <h4>note</h4>\n    * \n    * affected nodes may not resume with the same IP address(es)\n    * \n    * @return list of nodes suspended\n    *\n    * @throws UnsupportedOperationException\n    *            if the underlying provider doesn't support suspend/resume\n    * @throws NoSuchElementException\n    *            if no nodes matched the predicate specified\n    */\n   Set<? extends NodeMetadata> suspendNodesMatching(Predicate<? super NodeMetadata> filter);\n\n   /**\n    * destroy the node, given its id. If it is the only node in a tag set, the dependent resources\n    * will also be destroyed.\n    */\n   void destroyNode(String id);\n\n   /**\n    * nodes matching the filter are treated as a logical set. Using the delete command, you can save\n    * time by removing the nodes in parallel. When the last node in a set is destroyed, any indirect\n    * resources it uses, such as keypairs, are also destroyed.\n    * \n    * @return list of nodes destroyed\n    */\n   Set<? extends NodeMetadata> destroyNodesMatching(Predicate<? super NodeMetadata> filter);\n\n   /**\n    * reboot the node, given its id.\n    */\n   void rebootNode(String id);\n\n   /**\n    * nodes matching the filter are treated as a logical set. Using this command, you can save time\n    * by rebooting the nodes in parallel.\n    * \n    * @return list of nodes rebooted\n    *\n    * @throws NoSuchElementException\n    *            if no nodes matched the predicate specified\n    */\n   Set<? extends NodeMetadata> rebootNodesMatching(Predicate<? super NodeMetadata> filter);\n\n   /**\n    * Find a node by its id.\n    */\n   NodeMetadata getNodeMetadata(String id);\n\n   /**\n    * get all nodes including details such as image and ip addresses even if it incurs extra\n    * requests to the service.\n    * \n    * @param filter\n    *           how to select the nodes you are interested in details on.\n    */\n   Set<? extends NodeMetadata> listNodesDetailsMatching(Predicate<? super NodeMetadata> filter);\n\n   /**\n    * \n    * @see ComputeService#runScriptOnNodesMatching(Predicate, Statement, RunScriptOptions)\n    */\n   Map<? extends NodeMetadata, ExecResponse> runScriptOnNodesMatching(Predicate<? super NodeMetadata> filter, String runScript)\n            throws RunScriptOnNodesException;\n\n   /**\n    * \n    * @see ComputeService#runScriptOnNodesMatching(Predicate, Statement, RunScriptOptions)\n    */\n   Map<? extends NodeMetadata, ExecResponse> runScriptOnNodesMatching(Predicate<? super NodeMetadata> filter,\n            Statement runScript) throws RunScriptOnNodesException;\n\n   /**\n    * \n    * @see ComputeService#runScriptOnNodesMatching(Predicate, Statement, RunScriptOptions)\n    */\n   Map<? extends NodeMetadata, ExecResponse> runScriptOnNodesMatching(Predicate<? super NodeMetadata> filter, String runScript,\n            RunScriptOptions options) throws RunScriptOnNodesException;\n\n   /**\n    * Run the script on all nodes with the specific predicate.\n    * \n    * @param filter\n    *           Predicate-based filter to define on which nodes the script is to be executed\n    * @param runScript\n    *           statement containing the script to run\n    * @param options\n    *           nullable options to how to run the script, whether to override credentials\n    * @return map with node identifiers and corresponding responses\n    * @throws NoSuchElementException\n    *            if no nodes matched the predicate specified\n    * @throws RunScriptOnNodesException\n    *            if anything goes wrong during script execution\n    * \n    * @see org.jclouds.compute.predicates.NodePredicates#runningInGroup(String)\n    * @see org.jclouds.scriptbuilder.domain.Statements\n    */\n   Map<? extends NodeMetadata, ExecResponse> runScriptOnNodesMatching(Predicate<? super NodeMetadata> filter,\n            Statement runScript, RunScriptOptions options) throws RunScriptOnNodesException;\n\n   /**\n    * Run the script on a specific node\n    * \n    * @param id\n    *           node the script is to be executed on\n    * @param runScript\n    *           statement containing the script to run\n    * @param options\n    *           nullable options to how to run the script, whether to override credentials\n    * @return map with node identifiers and corresponding responses\n    * @throws NoSuchElementException\n    *            if the node is not found\n    * @throws IllegalStateException\n    *            if the node is not in running state\n    * @throws ScriptStillRunningException\n    *            if the script was still running after {@link Timeouts#scriptComplete}\n    * \n    * @see org.jclouds.compute.predicates.NodePredicates#runningInGroup(String)\n    * @see org.jclouds.scriptbuilder.domain.Statements\n    */\n   ExecResponse runScriptOnNode(String id, Statement runScript, RunScriptOptions options);\n   \n   /**\n    * Run the script on a specific node in the background, typically as {@code nohup}\n    * \n    * @param id\n    *           node the script is to be executed on\n    * @param runScript\n    *           statement containing the script to run\n    * @param options\n    *           nullable options to how to run the script, whether to override credentials\n    * @return map with node identifiers and corresponding responses\n    * @throws NoSuchElementException\n    *            if the node is not found\n    * @throws IllegalStateException\n    *            if the node is not in running state\n    * \n    * @see org.jclouds.compute.predicates.NodePredicates#runningInGroup(String)\n    * @see org.jclouds.scriptbuilder.domain.Statements\n    */\n   @Beta\n   ListenableFuture<ExecResponse> submitScriptOnNode(String id, String runScript, RunScriptOptions options);\n\n   @Beta\n   ListenableFuture<ExecResponse> submitScriptOnNode(String id, Statement runScript, RunScriptOptions options);\n   \n   /**\n    * @see #runScriptOnNode(String, Statement, RunScriptOptions)\n    */\n   ExecResponse runScriptOnNode(String id, Statement runScript);\n\n   /**\n    * @see #runScriptOnNode(String, Statement, RunScriptOptions)\n    * @see org.jclouds.scriptbuilder.domain.Statements#exec\n    */\n   ExecResponse runScriptOnNode(String id, String runScript, RunScriptOptions options);\n\n   /**\n    * @see #runScriptOnNode(String, String, RunScriptOptions)\n    */\n   ExecResponse runScriptOnNode(String id, String runScript);\n   \n   /**\n    * Returns the {@link ImageExtension} for this provider if it implements it.\n    * \n    * @return an optional of the {@link ImageExtension} or {@link Optional#absent()} if not\n    *         implemented\n    */\n   @Beta\n   Optional<ImageExtension> getImageExtension();\n\n   /**\n    * Returns the {@link SecurityGroupExtension} for this provider if it implements it.\n    * \n    * @return an optional of the {@link SecurityGroupExtension} or {@link Optional#absent()} if not\n    *         implemented\n    */\n   @Beta\n   Optional<SecurityGroupExtension> getSecurityGroupExtension();\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/ComputeServiceAdapter.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.javax.annotation.Nullable;\n\n/**\n * A means of specifying the interface between the {@link ComputeService ComputeServices} and a\n * concrete compute cloud implementation, jclouds or otherwise.\n * \n * <h3>Important</h3>\n * \n * While implementations may cache results of calls to this interface, it is important to not cache\n * within this. Otherwise, status updates will not be visible immediately.\n */\npublic interface ComputeServiceAdapter<N, H, I, L> {\n\n   /**\n    * {@link ComputeService#createNodesInGroup(String, int, Template)} generates the parameters\n    * passed into this method such that each node in the set has a unique name.\n    * \n    * <h4>note</h4> It is intentional to return the library native node object, as generic type\n    * {@code N}. If you are not using library-native objects (such as libvirt {@code Domain}) use\n    * {@link JCloudsNativeComputeServiceAdapter} instead.\n    * \n    * <h4>note</h4> Your responsibility is to create a node with the underlying library and return\n    * after storing its credentials in the supplied map corresponding to\n    * {@link ComputeServiceContext#getCredentialStore credentialStore}\n    * \n    * @param group\n    *           used to aggregate nodes with identical configuration\n    * @param name\n    *           unique supplied name for the node, which has the group encoded into it.\n    * @param template\n    *           includes {@code imageId}, {@code locationId}, and {@code hardwareId} used to resume\n    *           the instance.\n    * @return library-native representation of a node. TODO: return typed exception on\n    *         createNodeFailure\n    * @see ComputeService#createNodesInGroup(String, int, Template)\n    */\n   NodeAndInitialCredentials<N> createNodeWithGroupEncodedIntoName(String group, String name, Template template);\n\n   public static class NodeAndInitialCredentials<N> {\n      private final N node;\n      private final String nodeId;\n      private final LoginCredentials credentials;\n\n      public NodeAndInitialCredentials(N node, String nodeId, @Nullable LoginCredentials credentials) {\n         this.node = checkNotNull(node, \"node\");\n         this.nodeId = checkNotNull(nodeId, \"nodeId\");\n         this.credentials = credentials;\n      }\n\n      /**\n       * \n       * @return cloud specific representation of the newly created node\n       */\n      public N getNode() {\n         return node;\n      }\n\n      /** @return Stringified version of the new node's id. */\n      public String getNodeId() {\n         return nodeId;\n      }\n\n      /**\n       * \n       * @return credentials given by the api for the node, or null if this information is not\n       *         available\n       */\n      @Nullable\n      public LoginCredentials getCredentials() {\n         return credentials;\n      }\n   }\n\n   /**\n    * Hardware profiles describe available cpu, memory, and disk configurations that can be used to\n    * run a node.\n    * <p/>\n    * To implement this method, return the library native hardware profiles available to the user.\n    * These will be used to launch nodes as a part of the template.\n    * \n    * @return a non-null iterable of available hardware profiles.\n    * @see ComputeService#listHardwareProfiles()\n    */\n   Iterable<H> listHardwareProfiles();\n\n   /**\n    * Images are the available configured operating systems that someone can run a node with.\n    * <p/>\n    * To implement this method, return the library native images available to the user. These will\n    * be used to launch nodes as a part of the template.\n    * \n    * @return a non-null iterable of available images.\n    * @see ComputeService#listImages()\n    */\n   Iterable<I> listImages();\n\n   /**\n    * get a specific image by id\n    * \n    * @param id\n    *           {@link Image#getId}, which is not necessarily {@link Image#getProviderId}\n    * @return image or null if not exists.\n    */\n   @Nullable\n   I getImage(String id);\n\n   Iterable<L> listLocations();\n\n   N getNode(String id);\n\n   // TODO consider making reboot/resume/suspend return the node they affected\n   void destroyNode(String id);\n\n   void rebootNode(String id);\n\n   void resumeNode(String id);\n\n   void suspendNode(String id);\n\n   Iterable<N> listNodes();\n\n   Iterable<N> listNodesByIds(Iterable<String> ids);\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/ComputeServiceContext.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute;\n\nimport java.io.Closeable;\n\nimport org.jclouds.View;\nimport org.jclouds.compute.internal.ComputeServiceContextImpl;\n\nimport com.google.inject.ImplementedBy;\n\n/**\n * Represents a cloud that has compute functionality.\n */\n@ImplementedBy(ComputeServiceContextImpl.class)\npublic interface ComputeServiceContext extends Closeable, View {\n\n   ComputeService getComputeService();\n\n   Utils utils();\n\n   @Override\n   void close();\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/JCloudsNativeComputeServiceAdapter.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute;\n\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.domain.Location;\n\n/**\n * A means of specifying the implementation of a service that uses jclouds\n * types.\n */\npublic interface JCloudsNativeComputeServiceAdapter extends\n      ComputeServiceAdapter<NodeMetadata, Hardware, Image, Location> {\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   NodeWithInitialCredentials createNodeWithGroupEncodedIntoName(String group, String name, Template template);\n\n   public static class NodeWithInitialCredentials extends ComputeServiceAdapter.NodeAndInitialCredentials<NodeMetadata> {\n\n      public NodeWithInitialCredentials(NodeMetadata node) {\n         super(node, node.getId(), node.getCredentials());\n      }\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   Iterable<NodeMetadata> listNodes();\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   Iterable<Image> listImages();\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   Iterable<Hardware> listHardwareProfiles();\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   Iterable<Location> listLocations();\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   NodeMetadata getNode(String id);\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   void destroyNode(String id);\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   void rebootNode(String id);\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/RunNodesException.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute;\n\nimport static org.jclouds.compute.util.ComputeServiceUtils.createExecutionErrorMessage;\nimport static org.jclouds.compute.util.ComputeServiceUtils.createNodeErrorMessage;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.Template;\n\npublic class RunNodesException extends Exception {\n\n   private final String group;\n   private final int count;\n   private final Template template;\n   private final Set<? extends NodeMetadata> successfulNodes;\n   private final Map<? extends NodeMetadata, ? extends Throwable> failedNodes;\n   private final Map<?, Exception> executionExceptions;\n\n   public RunNodesException(String group, int count, Template template,\n            Set<? extends NodeMetadata> successfulNodes, Map<?, Exception> executionExceptions,\n            Map<? extends NodeMetadata, ? extends Throwable> failedNodes) {\n      super(\n               String\n                        .format(\n                                 \"error running %d node%s group(%s) location(%s) image(%s) size(%s) options(%s)%n%s%n%s\",\n                                 count, count > 1 ? \"s\" : \"\", group, template.getLocation().getId(),\n                                 template.getImage().getProviderId(), template.getHardware()\n                                          .getProviderId(), template.getOptions(),\n                                 createExecutionErrorMessage(executionExceptions),\n                                 createNodeErrorMessage(failedNodes)));\n      this.group = group;\n      this.count = count;\n      this.template = template;\n      this.successfulNodes = successfulNodes;\n      this.failedNodes = failedNodes;\n      this.executionExceptions = executionExceptions;\n   }\n\n   /**\n    * \n    * @return Nodes that performed startup without error\n    */\n   public Set<? extends NodeMetadata> getSuccessfulNodes() {\n      return successfulNodes;\n   }\n\n   /**\n    * \n    * @return Nodes that performed startup without error, but incurred problems applying options\n    */\n   public Map<?, ? extends Throwable> getExecutionErrors() {\n      return executionExceptions;\n   }\n\n   /**\n    * \n    * @return Nodes that performed startup without error, but incurred problems applying options\n    */\n   public Map<? extends NodeMetadata, ? extends Throwable> getNodeErrors() {\n      return failedNodes;\n   }\n\n   public String getGroup() {\n      return group;\n   }\n\n   public int getCount() {\n      return count;\n   }\n\n   public Template getTemplate() {\n      return template;\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/RunScriptOnNodesException.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute;\n\nimport static org.jclouds.compute.util.ComputeServiceUtils.createExecutionErrorMessage;\nimport static org.jclouds.compute.util.ComputeServiceUtils.createNodeErrorMessage;\n\nimport java.util.Map;\n\nimport org.jclouds.compute.domain.ExecResponse;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.options.RunScriptOptions;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.scriptbuilder.domain.Statement;\n\npublic class RunScriptOnNodesException extends Exception {\n\n   private final Statement runScript;\n   private final RunScriptOptions options;\n   private final Map<NodeMetadata, ExecResponse> successfulNodes;\n   private final Map<? extends NodeMetadata, ? extends Throwable> failedNodes;\n   private final Map<?, Exception> executionExceptions;\n\n   public RunScriptOnNodesException(Statement runScript, @Nullable RunScriptOptions options,\n            Map<NodeMetadata, ExecResponse> successfulNodes, Map<?, Exception> executionExceptions,\n            Map<? extends NodeMetadata, ? extends Throwable> failedNodes) {\n      super(String.format(\"error runScript on filtered nodes options(%s)%n%s%n%s\", options,\n               createExecutionErrorMessage(executionExceptions), createNodeErrorMessage(failedNodes)));\n      this.runScript = runScript;\n      this.options = options;\n      this.successfulNodes = successfulNodes;\n      this.failedNodes = failedNodes;\n      this.executionExceptions = executionExceptions;\n   }\n\n   /**\n    * @return Nodes that performed ssh without error\n    */\n   public Map<NodeMetadata, ExecResponse> getSuccessfulNodes() {\n      return successfulNodes;\n   }\n\n   /**\n    * \n    * @return Nodes that performed startup without error, but incurred problems applying options\n    */\n   public Map<?, ? extends Throwable> getExecutionErrors() {\n      return executionExceptions;\n   }\n\n   /**\n    * \n    * @return Nodes that performed startup without error, but incurred problems applying options\n    */\n   public Map<? extends NodeMetadata, ? extends Throwable> getNodeErrors() {\n      return failedNodes;\n   }\n\n   public Statement getRunScript() {\n      return runScript;\n   }\n\n   public RunScriptOptions getOptions() {\n      return options;\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/Utils.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute;\n\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.internal.UtilsImpl;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.ssh.SshClient;\n\nimport com.google.common.base.Function;\nimport com.google.inject.ImplementedBy;\n\n@ImplementedBy(UtilsImpl.class)\npublic interface Utils extends org.jclouds.rest.Utils {\n   @Nullable\n   SshClient.Factory getSshClientFactory();\n\n   @Nullable\n   SshClient.Factory sshFactory();\n\n   /**\n    * @return function that gets an ssh client for a node that is available via ssh.\n    */\n   Function<NodeMetadata, SshClient> sshForNode();\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/callables/BlockUntilInitScriptStatusIsZeroThenReturnOutput.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.callables;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static java.util.concurrent.TimeUnit.MILLISECONDS;\nimport static org.jclouds.util.Predicates2.retry;\n\nimport java.util.concurrent.CancellationException;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.TimeoutException;\n\nimport jakarta.annotation.Resource;\n\nimport org.jclouds.Constants;\nimport org.jclouds.compute.domain.ExecResponse;\nimport org.jclouds.compute.events.StatementOnNodeCompletion;\nimport org.jclouds.compute.events.StatementOnNodeFailure;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Predicates;\nimport com.google.common.eventbus.EventBus;\nimport com.google.common.primitives.Ints;\nimport com.google.common.util.concurrent.AbstractFuture;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.inject.Inject;\nimport com.google.inject.assistedinject.Assisted;\nimport com.google.inject.name.Named;\n\n/**\n * A future that works in tandem with a task that was invoked by {@link InitScript}\n */\npublic class BlockUntilInitScriptStatusIsZeroThenReturnOutput extends AbstractFuture<ExecResponse> implements Runnable {\n\n   public interface Factory {\n      BlockUntilInitScriptStatusIsZeroThenReturnOutput create(SudoAwareInitManager commandRunner);\n   }\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   private final ListeningExecutorService userExecutor;\n   private final EventBus eventBus;\n   private final SudoAwareInitManager commandRunner;\n\n   public SudoAwareInitManager getCommandRunner() {\n      return commandRunner;\n   }\n\n   private Predicate<String> notRunningAnymore;\n\n   @Inject\n   public BlockUntilInitScriptStatusIsZeroThenReturnOutput(\n            @Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor, EventBus eventBus,\n            ComputeServiceConstants.InitStatusProperties properties, @Assisted SudoAwareInitManager commandRunner) {\n      this(userExecutor, eventBus, Predicates.<String> alwaysTrue(), commandRunner);\n      // this is mutable only until we can determine how to decouple \"this\" from here\n      notRunningAnymore = loopUntilTrueOrThrowCancellationException(new ExitStatusOfCommandGreaterThanZero(\n               commandRunner), properties.initStatusMaxPeriod, properties.initStatusInitialPeriod, this);\n   }\n\n   @VisibleForTesting\n   public BlockUntilInitScriptStatusIsZeroThenReturnOutput(ListeningExecutorService userExecutor, EventBus eventBus,\n            Predicate<String> notRunningAnymore, SudoAwareInitManager commandRunner) {\n      this.commandRunner = checkNotNull(commandRunner, \"commandRunner\");\n      this.userExecutor = checkNotNull(userExecutor, \"userExecutor\");\n      this.eventBus = checkNotNull(eventBus, \"eventBus\");\n      this.notRunningAnymore = checkNotNull(notRunningAnymore, \"notRunningAnymore\");\n   }\n\n   @VisibleForTesting\n   static class ExitStatusOfCommandGreaterThanZero implements Predicate<String> {\n      private final SudoAwareInitManager commandRunner;\n\n      ExitStatusOfCommandGreaterThanZero(SudoAwareInitManager commandRunner) {\n         this.commandRunner = commandRunner;\n      }\n\n      @Override\n      public boolean apply(String input) {\n         return commandRunner.runAction(input).getExitStatus() > 0;\n      }\n\n   }\n\n   /**\n    * make sure we stop the retry loop if someone cancelled the future, this keeps threads from\n    * being consumed on dead tasks\n    */\n   static Predicate<String> loopUntilTrueOrThrowCancellationException(Predicate<String> predicate, long period, long maxPeriod,\n         final AbstractFuture<ExecResponse> futureWhichMightBeCancelled) {\n      return retry(Predicates.<String> and(predicate, new Predicate<String>() {\n         public boolean apply(String in) {\n            if (futureWhichMightBeCancelled.isCancelled())\n               throw new CancellationException(futureWhichMightBeCancelled + \" is cancelled\");\n            return true;\n         }\n      }), period, maxPeriod, MILLISECONDS);\n   }\n\n   /**\n    * Submits a thread that will either set the result of the future or the exception that took\n    * place\n    */\n   public BlockUntilInitScriptStatusIsZeroThenReturnOutput init() {\n      userExecutor.submit(this);\n      return this;\n   }\n\n   @Override\n   public void run() {\n      try {\n         ExecResponse exec = null;\n         do {\n            notRunningAnymore.apply(\"status\");\n            String stdout = commandRunner.runAction(\"stdout\").getOutput();\n            String stderr = commandRunner.runAction(\"stderr\").getOutput();\n            Integer exitStatus = Ints.tryParse(commandRunner.runAction(\"exitstatus\").getOutput().trim());\n            exec = new ExecResponse(stdout, stderr, exitStatus == null ? Integer.valueOf(-1) : exitStatus);\n         } while (!isCancelled() && exec.getExitStatus() == -1);\n         logger.debug(\"<< complete(%s) status(%s)\", commandRunner.getStatement().getInstanceName(), exec\n                  .getExitStatus());\n         set(exec);\n      } catch (Exception e) {\n         setException(e);\n      }\n   }\n\n   @Override\n   protected boolean set(ExecResponse value) {\n      eventBus.post(new StatementOnNodeCompletion(getCommandRunner().getStatement(), getCommandRunner().getNode(),\n               value));\n      return super.set(value);\n   }\n\n   @Override\n   protected void interruptTask() {\n      logger.debug(\"<< cancelled(%s)\", commandRunner.getStatement().getInstanceName());\n      ExecResponse returnVal = commandRunner.refreshAndRunAction(\"stop\");\n      CancellationException e = new CancellationException(String.format(\n               \"cancelled %s on node: %s; stop command had exit status: %s\", getCommandRunner().getStatement()\n                        .getInstanceName(), getCommandRunner().getNode().getId(), returnVal));\n      eventBus.post(new StatementOnNodeFailure(getCommandRunner().getStatement(), getCommandRunner().getNode(), e));\n      super.interruptTask();\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).add(\"commandRunner\", commandRunner).toString();\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(commandRunner);\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (o == null)\n         return false;\n      if (!o.getClass().equals(getClass()))\n         return false;\n      BlockUntilInitScriptStatusIsZeroThenReturnOutput that = BlockUntilInitScriptStatusIsZeroThenReturnOutput.class\n               .cast(o);\n      return Objects.equal(this.commandRunner, that.commandRunner);\n   }\n\n   @Override\n   public ExecResponse get(long timeout, TimeUnit unit) throws InterruptedException, TimeoutException,\n            ExecutionException {\n      try {\n         return super.get(timeout, unit);\n      } catch (TimeoutException e) {\n         ScriptStillRunningException exception = new ScriptStillRunningException(timeout, unit, this);\n         exception.initCause(e);\n         throw exception;\n      }\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/callables/InitScriptConfigurationForTasks.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.callables;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.concurrent.atomic.AtomicInteger;\n\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport com.google.common.base.Supplier;\nimport com.google.inject.Inject;\n\n@Singleton\npublic class InitScriptConfigurationForTasks {\n   public static final String PROPERTY_INIT_SCRIPT_PATTERN = \"jclouds.compute.init-script-pattern\";\n\n   public static InitScriptConfigurationForTasks create() {\n      return new InitScriptConfigurationForTasks();\n   }\n\n   private String basedir = \"/tmp\";\n   private String initScriptPattern = basedir + \"/init-%s\";\n   private Supplier<String> suffixSupplier;\n\n   protected InitScriptConfigurationForTasks() {\n      appendCurrentTimeMillisToAnonymousTaskNames();\n   }\n\n   @Inject(optional = true)\n   public InitScriptConfigurationForTasks initScriptPattern(\n            @Named(PROPERTY_INIT_SCRIPT_PATTERN) String initScriptPattern) {\n      this.initScriptPattern = checkNotNull(initScriptPattern, \"initScriptPattern ex. /tmp/init-%s\");\n      checkArgument(this.initScriptPattern.startsWith(\"/\"), \"initScriptPattern must be a UNIX-style path starting at the root (/)\");\n\n      int lastSlash = initScriptPattern.lastIndexOf('/');\n      if (lastSlash == 0) {\n         // the only slash is at the beginning, so this is a filename but no subdirectories - e.g. \"/foo\"\n         this.basedir = \"/\";\n      } else {\n         // multiple path components - e.g. \"/foo/bar\"\n         this.basedir = initScriptPattern.substring(0, lastSlash);\n         // result: \"/foo/bar\" becomes \"/foo\"\n      }\n      return this;\n   }\n\n   public InitScriptConfigurationForTasks appendCurrentTimeMillisToAnonymousTaskNames() {\n      this.suffixSupplier = new Supplier<String>() {\n\n         @Override\n         public String get() {\n            return System.currentTimeMillis() + \"\";\n         }\n\n         @Override\n         public String toString() {\n            return \"currentTimeMillis()\";\n         }\n      };\n      return this;\n   }\n\n   public InitScriptConfigurationForTasks appendIncrementingNumberToAnonymousTaskNames() {\n      this.suffixSupplier = new Supplier<String>() {\n         private final AtomicInteger integer = new AtomicInteger();\n\n         @Override\n         public String get() {\n            return integer.getAndIncrement() + \"\";\n         }\n\n         @Override\n         public String toString() {\n            return \"incrementingNumber()\";\n         }\n      };\n      return this;\n   }\n\n   /**\n    * Directory where the init script is stored. the runtime directory of the process will be in\n    * this dir/taskName\n    */\n   public String getBasedir() {\n      return basedir;\n   }\n\n   /**\n    * \n    * @return the naming convention of init scripts. ex. {@code /tmp/init-%s}, noting logs are under\n    *         the basedir/%s where %s is the taskName\n    * @see InitScript#getHomeDir\n    * @see InitScript#getLogDir\n    */\n   public String getInitScriptPattern() {\n      return initScriptPattern;\n   }\n\n   /**\n    * @return suffix where the taskName isn't set. by default this is\n    *         {@link System#currentTimeMillis}\n    * @see #appendCurrentTimeMillisToAnonymousTaskNames\n    * @see #appendIncrementingNumberToAnonymousTaskNames\n    */\n   public Supplier<String> getAnonymousTaskSuffixSupplier() {\n      return suffixSupplier;\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/callables/RunScriptOnNode.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.callables;\n\nimport java.util.concurrent.Callable;\n\nimport org.jclouds.compute.domain.ExecResponse;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.options.RunScriptOptions;\nimport org.jclouds.scriptbuilder.domain.Statement;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.inject.ImplementedBy;\n\n/**\n * Separates out how one implements the ability to run a script on a node.\n */\n@Beta\npublic interface RunScriptOnNode extends Callable<ExecResponse> {\n\n   @ImplementedBy(org.jclouds.compute.config.BaseComputeServiceContextModule.RunScriptOnNodeFactoryImpl.class)\n   public interface Factory {\n\n      RunScriptOnNode create(NodeMetadata node, Statement script, RunScriptOptions options);\n\n      ListenableFuture<ExecResponse> submit(NodeMetadata node, Statement script, RunScriptOptions options);\n   }\n\n   /**\n    * Note that {@link #init} must be called first.\n    */\n   @Override\n   ExecResponse call();\n\n   /**\n    * @return statement that will be executed\n    */\n   Statement getStatement();\n\n   /**\n    * verifies that the command can execute on the node. For example, if this is ssh, it may attempt\n    * to find a reachable socket. If this is using an API, it may attempt to validate that\n    * connection.\n    */\n   RunScriptOnNode init();\n\n   /**\n    * the node this command is being executed on.\n    */\n   NodeMetadata getNode();\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/callables/RunScriptOnNodeAsInitScriptUsingSsh.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.callables;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\n\nimport org.jclouds.compute.domain.ExecResponse;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadataBuilder;\nimport org.jclouds.compute.events.InitScriptOnNodeSubmission;\nimport org.jclouds.compute.events.StatementOnNodeCompletion;\nimport org.jclouds.compute.events.StatementOnNodeFailure;\nimport org.jclouds.compute.options.RunScriptOptions;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.scriptbuilder.InitScript;\nimport org.jclouds.scriptbuilder.domain.AdminAccessVisitor;\nimport org.jclouds.scriptbuilder.domain.AppendFile;\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.jclouds.scriptbuilder.domain.Statement;\nimport org.jclouds.scriptbuilder.domain.Statements;\nimport org.jclouds.scriptbuilder.statements.login.AdminAccess;\nimport org.jclouds.ssh.SshClient;\nimport org.jclouds.ssh.SshException;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Splitter;\nimport com.google.common.base.Throwables;\nimport com.google.common.eventbus.EventBus;\nimport com.google.inject.assistedinject.Assisted;\nimport com.google.inject.assistedinject.AssistedInject;\n\npublic class RunScriptOnNodeAsInitScriptUsingSsh extends SudoAwareInitManager implements RunScriptOnNode {\n\n   protected final EventBus eventBus;\n\n   @AssistedInject\n   public RunScriptOnNodeAsInitScriptUsingSsh(Function<NodeMetadata, SshClient> sshFactory, EventBus eventBus,\n            InitScriptConfigurationForTasks initScriptConfiguration, @Assisted NodeMetadata node,\n            @Assisted Statement script, @Assisted RunScriptOptions options) {\n      super(sshFactory, options.shouldRunAsRoot(), checkNotNull(node, \"node\"),\n               initScriptConfiguration, checkNotNull(script, \"script\") instanceof InitScript ? InitScript.class.cast(script)\n                        : createInitScript(checkNotNull(initScriptConfiguration, \"initScriptConfiguration\"), options\n                                 .getTaskName(), script));\n      this.eventBus = checkNotNull(eventBus, \"eventBus\");\n   }\n\n   @Override\n   public RunScriptOnNodeAsInitScriptUsingSsh init() {\n      super.init();\n      return this;\n   }\n\n   @Override\n   public ExecResponse call() {\n      checkState(ssh != null, \"please call init() before invoking call\");\n      try {\n         ssh.connect();\n         ExecResponse returnVal = doCall();\n         eventBus.post(new StatementOnNodeCompletion(init, node, returnVal));\n         return returnVal;\n      } finally {\n         if (ssh != null)\n            ssh.disconnect();\n      }\n   }\n\n   public static InitScript createInitScript(InitScriptConfigurationForTasks config, String name, Statement script) {\n      if (name == null) {\n         name = \"jclouds-script-\" + config.getAnonymousTaskSuffixSupplier().get();\n      }\n      return InitScript.builder().name(name).home(config.getBasedir() + \"/\" + name).run(script).build();\n   }\n\n   protected void refreshSshIfNewAdminCredentialsConfigured(AdminAccess input) {\n      if (input.getAdminCredentials() != null && input.shouldGrantSudoToAdminUser()) {\n         ssh.disconnect();\n         logger.debug(\">> reconnecting as %s@%s\", input.getAdminCredentials().identity, ssh.getHostAddress());\n         ssh = sshFactory.apply(node = NodeMetadataBuilder.fromNodeMetadata(node)\n               .credentials(LoginCredentials.fromCredentials(input.getAdminCredentials())).build());\n         ssh.connect();\n         setupLinkToInitFile();\n      }\n   }\n\n   protected ExecResponse doCall() {\n      eventBus.post(new InitScriptOnNodeSubmission(init, node));\n      try {\n         try {\n            ssh.put(initFile, init.render(OsFamily.UNIX));\n         } catch (SshException e) {\n            // If there's a problem with the sftp configuration, we can try via\n            // ssh exec\n            if (logger.isTraceEnabled())\n               logger.warn(e, \"<< (%s) problem using sftp [%s], attempting via sshexec\", ssh.toString(), e.getMessage());\n            else\n               logger.warn(\"<< (%s) problem using sftp [%s], attempting via sshexec\", ssh.toString(), e.getMessage());\n            ssh.disconnect();\n            ssh.connect();\n            ssh.exec(\"rm \" + initFile);\n            ssh.exec(Statements.appendFile(initFile, Splitter.on('\\n').split(init.render(OsFamily.UNIX)),\n                  AppendFile.DELIMITER + \"_\" + init.getInstanceName()).render(OsFamily.UNIX));\n         }\n\n         ssh.exec(\"chmod 755 \" + initFile);\n         setupLinkToInitFile();\n\n         runAction(\"init\");\n         init.getInitStatement().accept(new AdminAccessVisitor() {\n\n            @Override\n            public void visit(AdminAccess input) {\n               refreshSshIfNewAdminCredentialsConfigured(input);\n            }\n\n         });\n         return runAction(\"start\");\n      } catch (Throwable e) {\n         eventBus.post(new StatementOnNodeFailure(init, node, e));\n         throw Throwables.propagate(e);\n      }\n   }\n\n   protected void setupLinkToInitFile() {\n      ssh.exec(String.format(\"ln -fs %s %s\", initFile, init.getInstanceName()));\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/callables/RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilComplete.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.callables;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.concurrent.TimeUnit;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.compute.domain.ExecResponse;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.events.StatementOnNodeFailure;\nimport org.jclouds.compute.options.RunScriptOptions;\nimport org.jclouds.compute.reference.ComputeServiceConstants.Timeouts;\nimport org.jclouds.scriptbuilder.domain.Statement;\nimport org.jclouds.ssh.SshClient;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Throwables;\nimport com.google.common.eventbus.EventBus;\nimport com.google.inject.assistedinject.Assisted;\n\npublic class RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilComplete extends RunScriptOnNodeAsInitScriptUsingSsh {\n   protected final Timeouts timeouts;\n   protected final BlockUntilInitScriptStatusIsZeroThenReturnOutput.Factory statusFactory;\n\n   @Inject\n   public RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilComplete(\n         BlockUntilInitScriptStatusIsZeroThenReturnOutput.Factory statusFactory, Timeouts timeouts,\n         Function<NodeMetadata, SshClient> sshFactory, EventBus eventBus,\n         InitScriptConfigurationForTasks initScriptConfiguration, @Assisted NodeMetadata node,\n         @Assisted Statement script, @Assisted RunScriptOptions options) {\n      super(sshFactory, eventBus, initScriptConfiguration, node, script, options);\n      this.statusFactory = checkNotNull(statusFactory, \"statusFactory\");\n      this.timeouts = checkNotNull(timeouts, \"timeouts\");\n   }\n\n   @Override\n   public ExecResponse doCall() {\n      try {\n         return future().get(timeouts.scriptComplete, TimeUnit.MILLISECONDS);\n      } catch (Throwable e) {\n         eventBus.post(new StatementOnNodeFailure(init, node, e));\n         throw Throwables.propagate(e);\n      }\n   }\n\n   public BlockUntilInitScriptStatusIsZeroThenReturnOutput future() {\n      ExecResponse returnVal = super.doCall();\n      if (returnVal.getExitStatus() != 0) {\n         IllegalStateException e = new IllegalStateException(String.format(\n               \"instance: %s on node: %s had non-zero exit status: %s\", init.getInstanceName(), getNode().getId(),\n               returnVal));\n         eventBus.post(new StatementOnNodeFailure(init, node, e));\n         throw e;\n      }\n      return statusFactory.create(this).init();\n   }\n\n   @Override\n   public RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilComplete init() {\n      return RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilComplete.class.cast(super.init());\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/callables/RunScriptOnNodeUsingSsh.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.callables;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\n\nimport org.jclouds.compute.domain.ExecResponse;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.events.StatementOnNodeCompletion;\nimport org.jclouds.compute.events.StatementOnNodeFailure;\nimport org.jclouds.compute.events.StatementOnNodeSubmission;\nimport org.jclouds.compute.options.RunScriptOptions;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.jclouds.scriptbuilder.domain.Statement;\nimport org.jclouds.ssh.SshClient;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Function;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Throwables;\nimport com.google.common.eventbus.EventBus;\nimport com.google.inject.assistedinject.Assisted;\nimport com.google.inject.assistedinject.AssistedInject;\n\npublic class RunScriptOnNodeUsingSsh implements RunScriptOnNode {\n   public static final String MARKER = \"RUN_SCRIPT_AS_ROOT_SSH\";\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   protected final Function<NodeMetadata, SshClient> sshFactory;\n   protected final EventBus eventBus;\n   protected final NodeMetadata node;\n   protected final Statement statement;\n   protected final boolean runAsRoot;\n\n   protected SshClient ssh;\n\n   @AssistedInject\n   public RunScriptOnNodeUsingSsh(Function<NodeMetadata, SshClient> sshFactory, EventBus eventBus,\n         @Assisted NodeMetadata node, @Assisted Statement statement, @Assisted RunScriptOptions options) {\n      this.sshFactory = checkNotNull(sshFactory, \"sshFactory\");\n      this.eventBus = checkNotNull(eventBus, \"eventBus\");\n      this.node = checkNotNull(node, \"node\");\n      this.statement = checkNotNull(statement, \"statement\");\n      this.runAsRoot = options.shouldRunAsRoot();\n   }\n\n   @Override\n   public ExecResponse call() {\n      checkState(ssh != null, \"please call init() before invoking call\");\n      try {\n         ssh.connect();\n         ExecResponse returnVal;\n         eventBus.post(new StatementOnNodeSubmission(statement, node));\n         String command = runAsRoot ? execAsRoot(statement.render(OsFamily.UNIX)) : execScriptAsDefaultUser(statement\n               .render(OsFamily.UNIX));\n         try {\n            returnVal = runCommand(command);\n         } catch (Throwable e) {\n            eventBus.post(new StatementOnNodeFailure(statement, node, e));\n            throw Throwables.propagate(e);\n         }\n         eventBus.post(new StatementOnNodeCompletion(statement, node, returnVal));\n         if (logger.isTraceEnabled())\n            logger.trace(\"<< %s[%s]\", statement, returnVal);\n         else\n            logger.debug(\"<< %s(%d)\", statement, returnVal.getExitStatus());\n         return returnVal;\n      } finally {\n         if (ssh != null)\n            ssh.disconnect();\n      }\n   }\n\n   @Override\n   public RunScriptOnNode init() {\n      ssh = sshFactory.apply(node);\n      return this;\n   }\n\n   protected ExecResponse runCommand(String command) {\n      ExecResponse returnVal;\n      logger.debug(\">> running [%s] as %s@%s\", command.replace(node.getCredentials().getOptionalPassword().isPresent() ? node\n            .getCredentials().getOptionalPassword().get() : \"XXXXX\", \"XXXXX\"), ssh.getUsername(), ssh.getHostAddress());\n      returnVal = ssh.exec(command);\n      return returnVal;\n   }\n\n   @VisibleForTesting\n   public String execAsRoot(String command) {\n      if (node.getCredentials().identity.equals(\"root\")) {\n      } else if (node.getCredentials().shouldAuthenticateSudo()) {\n         command = String.format(\"sudo -S sh <<'%s'\\n'%s'\\n%s%s\\n\", MARKER, node.getCredentials().getOptionalPassword\n               ().get(), command, MARKER);\n      } else {\n         command = String.format(\"sudo sh <<'%s'\\n%s%s\\n\", MARKER, command, MARKER);\n      }\n      return command;\n   }\n\n   protected String execScriptAsDefaultUser(String command) {\n      return command;\n   }\n\n   public NodeMetadata getNode() {\n      return node;\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).add(\"node\", node).add(\"name\", statement).add(\"runAsRoot\", runAsRoot)\n            .toString();\n   }\n\n   @Override\n   public Statement getStatement() {\n      return statement;\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/callables/ScriptStillRunningException.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.callables;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static java.lang.String.format;\n\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.TimeoutException;\n\nimport org.jclouds.compute.domain.ExecResponse;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.util.concurrent.ListenableFuture;\n\npublic class ScriptStillRunningException extends TimeoutException implements Supplier<ListenableFuture<ExecResponse>> {\n\n   private final ListenableFuture<ExecResponse> delegate;\n\n   public ScriptStillRunningException(long timeout, TimeUnit unit, ListenableFuture<ExecResponse> delegate) {\n      this(format(\"time up waiting %ds for %s to complete.\"\n               + \" call get() on this exception to get access to the task in progress\", TimeUnit.SECONDS.convert(\n               timeout, unit), delegate), delegate);\n   }\n\n   public ScriptStillRunningException(String message, ListenableFuture<ExecResponse> delegate) {\n      super(checkNotNull(message, \"message\"));\n      this.delegate = checkNotNull(delegate, \"delegate\");\n   }\n\n   @Override\n   public ListenableFuture<ExecResponse> get() {\n      return delegate;\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/callables/SudoAwareInitManager.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.callables;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\n\nimport org.jclouds.compute.domain.ExecResponse;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.scriptbuilder.InitScript;\nimport org.jclouds.ssh.SshClient;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Function;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Predicates;\nimport com.google.common.collect.ImmutableSet;\n\npublic class SudoAwareInitManager {\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger computeLogger = Logger.NULL;\n   protected Logger logger = Logger.NULL;\n   protected NodeMetadata node;\n   protected final String initFile;\n   protected final InitScript init;\n   protected final boolean runAsRoot;\n   protected final Function<NodeMetadata, SshClient> sshFactory;\n   protected SshClient ssh;\n\n   /**\n    * @return the absolute path to the file on disk relating to this task.\n    */\n   public String getInitFile() {\n      return initFile;\n   }\n   \n   public SudoAwareInitManager(Function<NodeMetadata, SshClient> sshFactory, boolean runAsRoot, NodeMetadata node,\n         InitScriptConfigurationForTasks initScriptConfiguration, InitScript init) {\n      this.sshFactory = checkNotNull(sshFactory, \"sshFactory\");\n      this.runAsRoot = runAsRoot;\n      this.node = checkNotNull(node, \"node\");\n      this.initFile = String.format(initScriptConfiguration.getInitScriptPattern(), init.getInstanceName());\n      this.init = checkNotNull(init, \"init\");\n   }\n\n   public SudoAwareInitManager init() {\n      ssh = sshFactory.apply(node);\n      return this;\n   }\n\n   public ExecResponse refreshAndRunAction(String action) {\n      checkState(ssh != null, \"please call init() before invoking call\");\n      try {\n         if (!ssh.isConnected()) {\n            ssh.connect();\n         }\n         return runAction(action);\n      } finally {\n         if (ssh != null)\n            ssh.disconnect();\n      }\n   }\n\n   public ExecResponse runAction(String action) {\n      ExecResponse returnVal;\n      String command = (runAsRoot && Predicates.in(ImmutableSet.of(\"start\", \"stop\", \"run\")).apply(action)) ? execScriptAsRoot(action)\n            : execScriptAsDefaultUser(action);\n      returnVal = runCommand(command);\n      if (ImmutableSet.of(\"status\", \"stdout\", \"stderr\").contains(action))\n         logger.trace(\"<< %s(%d)\", action, returnVal.getExitStatus());\n      else if (computeLogger.isTraceEnabled())\n         computeLogger.trace(\"<< %s[%s]\", action, returnVal);\n      else\n         computeLogger.debug(\"<< %s(%d)\", action, returnVal.getExitStatus());\n      return returnVal;\n   }\n\n   ExecResponse runCommand(String command) {\n      String statement = String.format(\"[%s] as %s@%s\", command.replace(\n            node.getCredentials().getOptionalPassword().isPresent() ? node.getCredentials().getOptionalPassword().get() : \"XXXXX\", \"XXXXX\"), ssh\n            .getUsername(), ssh.getHostAddress());\n      if (command.endsWith(\"status\") || command.endsWith(\"stdout\") || command.endsWith(\"stderr\"))\n         logger.trace(\">> running %s\", statement);\n      else \n         computeLogger.debug(\">> running \" + statement);\n      ExecResponse returnVal = ssh.exec(command);\n      if (!command.endsWith(\"status\"))\n         checkState(returnVal.getExitStatus() == 0, \"error running %s; returnVal !=0: %s\", statement, returnVal);\n      return returnVal;\n   }\n\n   @VisibleForTesting\n   String execScriptAsRoot(String action) {\n      String command;\n      if (node.getCredentials().identity.equals(\"root\")) {\n         command = initFile + \" \" + action;\n      } else if (node.getCredentials().shouldAuthenticateSudo()) {\n         command = String.format(\"echo '%s'|sudo -S %s %s\", node.getCredentials().getOptionalPassword().get(),\n               initFile, action);\n      } else {\n         command = \"sudo \" + initFile + \" \" + action;\n      }\n      return command;\n   }\n\n   protected String execScriptAsDefaultUser(String action) {\n      return initFile + \" \" + action;\n   }\n\n   public NodeMetadata getNode() {\n      return node;\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).add(\"node\", node.getId()).add(\"name\", init.getInstanceName())\n            .add(\"runAsRoot\", runAsRoot).toString();\n   }\n\n   public InitScript getStatement() {\n      return init;\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/config/AdminAccessConfiguration.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.config;\n\nimport static com.google.common.base.Charsets.UTF_8;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.security.SecureRandom;\nimport java.util.Map;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.config.AdminAccessConfiguration.Default;\nimport org.jclouds.compute.functions.Sha512Crypt;\nimport org.jclouds.scriptbuilder.statements.login.AdminAccess.Configuration;\nimport org.jclouds.ssh.SshKeys;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.io.Files;\nimport com.google.inject.ImplementedBy;\n\n@ImplementedBy(Default.class)\npublic interface AdminAccessConfiguration extends Configuration {\n   @Singleton\n   static class Default implements AdminAccessConfiguration {\n\n      private final Supplier<String> defaultAdminUsername = Suppliers.ofInstance(System.getProperty(\"user.name\"));\n      private final Supplier<Map<String, String>> defaultAdminSshKeys = new Supplier<Map<String, String>>() {\n         public Map<String, String> get() {\n            try {\n               return ImmutableMap.of(\"public\",\n                     Files.toString(new File(System.getProperty(\"user.home\") + \"/.ssh/id_rsa.pub\"), UTF_8), \"private\",\n                     Files.toString(new File(System.getProperty(\"user.home\") + \"/.ssh/id_rsa\"), UTF_8));\n            } catch (IOException e) {\n               return SshKeys.generate();\n            }\n         }\n      };\n\n      /**\n       * Cheap, lightweight, low-security password generator.\n       * \n       * @see <a href=\n       *      \"http://www.java-forums.org/java-lang/7355-how-create-lightweight-low-security-password-generator.html\" />\n       */\n      enum PasswordGenerator implements Supplier<String> {\n\n         INSTANCE;\n\n         /** Minimum length for a decent password */\n         public static final int MIN_LENGTH = 10;\n\n         /** The random number generator. */\n         protected static final SecureRandom r = new SecureRandom();\n\n         /*\n          * Set of characters that is valid. Must be printable, memorable, and \"won't break HTML\" (i.e., not ' <', '>',\n          * '&', '=', ...). or break shell commands (i.e., not ' <', '>', '$', '!', ...). I, L and O are good to leave\n          * out, as are numeric zero and one.\n          */\n         public static final char[] goodChar = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n', 'p', 'q',\n               'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'M', 'N',\n               'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9', '+', '-',\n               '@', };\n\n         @Override\n         public String get() {\n            StringBuilder sb = new StringBuilder();\n            for (int i = 0; i < MIN_LENGTH; i++) {\n               sb.append(goodChar[r.nextInt(goodChar.length)]);\n            }\n            return sb.toString();\n         }\n      }\n\n      private final Function<String, String> cryptFunction = Sha512Crypt.function();\n\n      @Override\n      public Supplier<String> defaultAdminUsername() {\n         return defaultAdminUsername;\n      }\n\n      @Override\n      public Supplier<Map<String, String>> defaultAdminSshKeys() {\n         return defaultAdminSshKeys;\n      }\n\n      @Override\n      public Supplier<String> passwordGenerator() {\n         return PasswordGenerator.INSTANCE;\n      }\n\n      @Override\n      public Function<String, String> cryptFunction() {\n         return cryptFunction;\n      }\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/config/BaseComputeServiceContextModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.config;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL;\nimport static org.jclouds.compute.config.ComputeServiceProperties.IMAGE_ID;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TEMPLATE;\nimport static org.jclouds.compute.domain.OsFamily.UBUNTU;\n\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.callables.BlockUntilInitScriptStatusIsZeroThenReturnOutput;\nimport org.jclouds.compute.callables.RunScriptOnNode;\nimport org.jclouds.compute.callables.RunScriptOnNodeAsInitScriptUsingSsh;\nimport org.jclouds.compute.callables.RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilComplete;\nimport org.jclouds.compute.callables.RunScriptOnNodeUsingSsh;\nimport org.jclouds.compute.domain.ComputeMetadata;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.domain.TemplateBuilder;\nimport org.jclouds.compute.extensions.ImageExtension;\nimport org.jclouds.compute.extensions.SecurityGroupExtension;\nimport org.jclouds.compute.extensions.internal.DelegatingImageExtension;\nimport org.jclouds.compute.functions.CreateSshClientOncePortIsListeningOnNode;\nimport org.jclouds.compute.functions.DefaultCredentialsFromImageOrOverridingCredentials;\nimport org.jclouds.compute.options.RunScriptOptions;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.compute.strategy.CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap;\nimport org.jclouds.compute.strategy.GetImageStrategy;\nimport org.jclouds.compute.strategy.InitializeRunScriptOnNodeOrPlaceInBadMap;\nimport org.jclouds.compute.suppliers.ImageCacheSupplier;\nimport org.jclouds.config.ValueOfConfigurationKeyOrNull;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.json.Json;\nimport org.jclouds.location.Provider;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.suppliers.MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier;\nimport org.jclouds.scriptbuilder.domain.Statement;\nimport org.jclouds.scriptbuilder.statements.login.AdminAccess;\nimport org.jclouds.ssh.SshClient;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Maps;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Binding;\nimport com.google.inject.Inject;\nimport com.google.inject.Injector;\nimport com.google.inject.Key;\nimport com.google.inject.Provides;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.assistedinject.FactoryModuleBuilder;\nimport com.google.inject.name.Names;\n\npublic abstract class BaseComputeServiceContextModule extends AbstractModule {\n\n   @Override\n   protected void configure() {\n      bind(AdminAccess.Configuration.class).to(AdminAccessConfiguration.class);\n      install(new ComputeServiceTimeoutsModule());\n      bind(new TypeLiteral<Function<NodeMetadata, SshClient>>() {\n      }).to(CreateSshClientOncePortIsListeningOnNode.class);\n      bind(LoginCredentials.class).annotatedWith(Names.named(\"image\")).toProvider(\n            GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNull.class);\n\n      bindCredentialsOverriderFunction();\n\n      install(new FactoryModuleBuilder()\n            .implement(RunScriptOnNodeUsingSsh.class, Names.named(\"direct\"), RunScriptOnNodeUsingSsh.class)\n            .implement(RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilComplete.class, Names.named(\"blocking\"),\n                  RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilComplete.class)\n            .implement(RunScriptOnNodeAsInitScriptUsingSsh.class, Names.named(\"nonblocking\"),\n                  RunScriptOnNodeAsInitScriptUsingSsh.class).build(RunScriptOnNodeFactoryImpl.Factory.class));\n\n      install(new PersistNodeCredentialsModule());\n\n      install(new FactoryModuleBuilder().implement(new TypeLiteral<Callable<Void>>() {\n      }, CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap.class)\n            .implement(new TypeLiteral<Function<AtomicReference<NodeMetadata>, Void>>() {\n            }, CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap.class)\n            .build(CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap.Factory.class));\n\n      install(new FactoryModuleBuilder().implement(new TypeLiteral<Callable<RunScriptOnNode>>() {\n      }, InitializeRunScriptOnNodeOrPlaceInBadMap.class).build(InitializeRunScriptOnNodeOrPlaceInBadMap.Factory.class));\n\n      install(new FactoryModuleBuilder().build(BlockUntilInitScriptStatusIsZeroThenReturnOutput.Factory.class));\n      \n      install(new FactoryModuleBuilder().build(DelegatingImageExtension.Factory.class));\n   }\n\n   protected void bindCredentialsOverriderFunction() {\n      bind(new TypeLiteral<Function<Template, LoginCredentials>>() {\n      }).to(DefaultCredentialsFromImageOrOverridingCredentials.class);\n   }\n\n   @Singleton\n   public static class RunScriptOnNodeFactoryImpl implements RunScriptOnNode.Factory {\n\n      interface Factory {\n\n         @Named(\"direct\")\n         RunScriptOnNodeUsingSsh exec(NodeMetadata node, Statement script, RunScriptOptions options);\n\n         @Named(\"blocking\")\n         RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilComplete backgroundAndBlockOnComplete(NodeMetadata node,\n               Statement script, RunScriptOptions options);\n\n         @Named(\"nonblocking\")\n         RunScriptOnNodeAsInitScriptUsingSsh background(NodeMetadata node, Statement script, RunScriptOptions options);\n      }\n\n      private final Factory factory;\n\n      @Inject\n      RunScriptOnNodeFactoryImpl(Factory factory) {\n         this.factory = checkNotNull(factory, \"factory\");\n      }\n\n      @Override\n      public RunScriptOnNode create(NodeMetadata node, Statement runScript, RunScriptOptions options) {\n         checkNotNull(node, \"node\");\n         checkNotNull(runScript, \"runScript\");\n         checkNotNull(options, \"options\");\n         return !options.shouldWrapInInitScript() ? factory.exec(node, runScript, options) : (options\n               .shouldBlockOnComplete() ? factory.backgroundAndBlockOnComplete(node, runScript, options) : factory\n               .background(node, runScript, options));\n      }\n\n      @Override\n      public BlockUntilInitScriptStatusIsZeroThenReturnOutput submit(NodeMetadata node, Statement script,\n            RunScriptOptions options) {\n         checkNotNull(node, \"node\");\n         checkNotNull(script, \"script\");\n         checkNotNull(options, \"options\");\n         options.shouldWrapInInitScript();\n         return factory.backgroundAndBlockOnComplete(node, script, options).init().future();\n      }\n   }\n\n   @Provides\n   @Singleton\n   public final Map<OsFamily, Map<String, String>> provideOsVersionMap(ComputeServiceConstants.ReferenceData data, Json json) {\n      return json.fromJson(data.osVersionMapJson, new TypeLiteral<Map<OsFamily, Map<String, String>>>() {\n      }.getType());\n   }\n\n   /**\n    * The default template if none is provided.\n    */\n   @Provides\n   @Named(\"DEFAULT\")\n   protected final TemplateBuilder provideTemplateOptionallyFromProperties(Injector injector, TemplateBuilder template,\n         @Provider String provider, ValueOfConfigurationKeyOrNull config) {\n      String templateString = config.apply(provider + \".template\");\n      if (templateString == null)\n         templateString = config.apply(TEMPLATE);\n      if (templateString != null) {\n         template.from(templateString);\n      } else {\n         template.osFamily(UBUNTU).osVersionMatches(\"1[012].[01][04]\").os64Bit(true);\n      }\n      String imageId = config.apply(provider + \".image-id\");\n      if (imageId == null)\n         imageId = config.apply(IMAGE_ID);\n      if (imageId != null)\n         template.imageId(imageId);\n      return template;\n   }\n\n   @Provides\n   @Singleton\n   protected final Map<OsFamily, LoginCredentials> provideOsFamilyToCredentials(Injector injector) {\n      return osFamilyToCredentials(injector);\n   }\n\n   protected Map<OsFamily, LoginCredentials> osFamilyToCredentials(Injector injector) {\n      return ImmutableMap.of(OsFamily.WINDOWS, LoginCredentials.builder().user(\"Administrator\").build());\n   }\n\n   /**\n    * The default options if none are provided.\n    */\n   @Provides\n   @Named(\"DEFAULT\")\n   protected final TemplateOptions guiceProvideTemplateOptions(Injector injector, TemplateOptions options) {\n      return provideTemplateOptions(injector, options);\n   }\n\n   protected TemplateOptions provideTemplateOptions(Injector injector, TemplateOptions options) {\n      return options;\n   }\n\n   @Provides\n   @Singleton\n   protected final Supplier<Map<String, ? extends Image>> provideImageMap(@Memoized Supplier<Set<? extends Image>> images) {\n      return Suppliers.compose(new Function<Set<? extends Image>, Map<String, ? extends Image>>() {\n\n         @Override\n         public Map<String, ? extends Image> apply(Set<? extends Image> from) {\n            return Maps.uniqueIndex(from, new Function<Image, String>() {\n\n               @Override\n               public String apply(Image from) {\n                  return from.getId();\n               }\n\n            });\n         }\n\n      }, images);\n   }\n\n   @Provides\n   @Singleton\n   @Memoized\n   protected final Supplier<Set<? extends Image>> supplyImageCache(\n         AtomicReference<AuthorizationException> authException, @Named(PROPERTY_SESSION_INTERVAL) long seconds,\n         final Supplier<Set<? extends Image>> imageSupplier, com.google.inject.Provider<GetImageStrategy> imageLoader, Injector injector) {\n      Supplier<Set<? extends Image>> parsingImageSupplier = shouldEagerlyParseImages(injector) ? imageSupplier\n            : supplyNonParsingImages(imageSupplier, injector);\n      return new ImageCacheSupplier(parsingImageSupplier, seconds, authException, imageLoader);\n   }\n\n   protected boolean shouldEagerlyParseImages(Injector injector) {\n      return true;\n   }\n\n   /**\n    * For overriding; default impl just returns the image supplier.\n    */\n   protected Supplier<Set<? extends Image>> supplyNonParsingImages(final Supplier<Set<? extends Image>> imageSupplier, Injector injector) {\n      return imageSupplier;\n   }\n\n   @Provides\n   @Singleton\n   protected final Supplier<Map<String, ? extends Hardware>> provideSizeMap(@Memoized Supplier<Set<? extends Hardware>> sizes) {\n      return Suppliers.compose(new Function<Set<? extends Hardware>, Map<String, ? extends Hardware>>() {\n\n         @Override\n         public Map<String, ? extends Hardware> apply(Set<? extends Hardware> from) {\n            return Maps.uniqueIndex(from, new Function<Hardware, String>() {\n\n               @Override\n               public String apply(Hardware from) {\n                  return from.getId();\n               }\n\n            });\n         }\n\n      }, sizes);\n   }\n\n   @Provides\n   @Singleton\n   @Memoized\n   protected final Supplier<Set<? extends Hardware>> supplySizeCache(AtomicReference<AuthorizationException> authException, @Named(PROPERTY_SESSION_INTERVAL) long seconds,\n         final Supplier<Set<? extends Hardware>> hardwareSupplier) {\n      return MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier.create(authException, hardwareSupplier,\n               seconds, TimeUnit.SECONDS);\n   }\n\n   @Provides\n   @Singleton\n   protected final Function<ComputeMetadata, String> indexer() {\n      return new Function<ComputeMetadata, String>() {\n         @Override\n         public String apply(ComputeMetadata from) {\n            return from.getProviderId();\n         }\n      };\n   }\n\n   @Provides\n   @Singleton\n   public final Optional<ImageExtension> guiceProvideImageExtension(Injector i) {\n      return provideImageExtension(i);\n   }\n\n   @Provides\n   @Singleton\n   protected final Optional<SecurityGroupExtension> guiceProvideSecurityGroupExtension(Injector i) {\n      return provideSecurityGroupExtension(i);\n   }\n\n   protected Optional<ImageExtension> provideImageExtension(Injector i) {\n      Binding<ImageExtension> binding = i.getExistingBinding(Key.get(ImageExtension.class));\n      return binding == null ? Optional.<ImageExtension> absent() : Optional.of(binding.getProvider().get());\n   }\n\n   protected Optional<SecurityGroupExtension> provideSecurityGroupExtension(Injector i) {\n      Binding<SecurityGroupExtension> binding = i.getExistingBinding(Key.get(SecurityGroupExtension.class));\n      return binding == null ? Optional.<SecurityGroupExtension> absent() : Optional.of(binding.getProvider().get());\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/config/BindComputeStrategiesByClass.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.config;\n\nimport org.jclouds.compute.strategy.CreateNodeWithGroupEncodedIntoName;\nimport org.jclouds.compute.strategy.CreateNodesInGroupThenAddToSet;\nimport org.jclouds.compute.strategy.DestroyNodeStrategy;\nimport org.jclouds.compute.strategy.GetImageStrategy;\nimport org.jclouds.compute.strategy.GetNodeMetadataStrategy;\nimport org.jclouds.compute.strategy.ListNodesStrategy;\nimport org.jclouds.compute.strategy.RebootNodeStrategy;\nimport org.jclouds.compute.strategy.ResumeNodeStrategy;\nimport org.jclouds.compute.strategy.SuspendNodeStrategy;\nimport org.jclouds.compute.strategy.impl.CreateNodesWithGroupEncodedIntoNameThenAddToSet;\n\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Scopes;\n\npublic abstract class BindComputeStrategiesByClass extends AbstractModule {\n   protected void configure() {\n      bindRunNodesAndAddToSetStrategy(defineRunNodesAndAddToSetStrategy());\n      bindAddNodeWithTagStrategy(defineAddNodeWithTagStrategy());\n      bindListNodesStrategy(defineListNodesStrategy());\n      bindGetNodeMetadataStrategy(defineGetNodeMetadataStrategy());\n      bindGetImageStrategy(defineGetImageStrategy());\n      bindRebootNodeStrategy(defineRebootNodeStrategy());\n      bindStartNodeStrategy(defineStartNodeStrategy());\n      bindStopNodeStrategy(defineStopNodeStrategy());\n      bindDestroyNodeStrategy(defineDestroyNodeStrategy());\n   }\n\n   protected void bindRunNodesAndAddToSetStrategy(Class<? extends CreateNodesInGroupThenAddToSet> clazz) {\n      bind(CreateNodesInGroupThenAddToSet.class).to(clazz).in(Scopes.SINGLETON);\n   }\n\n   /**\n    * needed, if {@link CreateNodesInGroupThenAddToSet} requires it\n    */\n   protected void bindAddNodeWithTagStrategy(Class<? extends CreateNodeWithGroupEncodedIntoName> clazz) {\n      bind(CreateNodeWithGroupEncodedIntoName.class).to(clazz).in(Scopes.SINGLETON);\n   }\n\n   protected void bindDestroyNodeStrategy(Class<? extends DestroyNodeStrategy> clazz) {\n      bind(DestroyNodeStrategy.class).to(clazz).in(Scopes.SINGLETON);\n   }\n\n   protected void bindRebootNodeStrategy(Class<? extends RebootNodeStrategy> clazz) {\n      bind(RebootNodeStrategy.class).to(clazz).in(Scopes.SINGLETON);\n   }\n\n   protected void bindStartNodeStrategy(Class<? extends ResumeNodeStrategy> clazz) {\n      bind(ResumeNodeStrategy.class).to(clazz).in(Scopes.SINGLETON);\n   }\n\n   protected void bindStopNodeStrategy(Class<? extends SuspendNodeStrategy> clazz) {\n      bind(SuspendNodeStrategy.class).to(clazz).in(Scopes.SINGLETON);\n   }\n\n   protected void bindGetNodeMetadataStrategy(Class<? extends GetNodeMetadataStrategy> clazz) {\n      bind(GetNodeMetadataStrategy.class).to(clazz).in(Scopes.SINGLETON);\n   }\n   \n   protected void bindGetImageStrategy(Class<? extends GetImageStrategy> clazz) {\n      bind(GetImageStrategy.class).to(clazz).in(Scopes.SINGLETON);\n   }\n   \n   protected void bindListNodesStrategy(Class<? extends ListNodesStrategy> clazz) {\n      bind(ListNodesStrategy.class).to(clazz).in(Scopes.SINGLETON);\n   }\n\n   protected Class<? extends CreateNodesInGroupThenAddToSet> defineRunNodesAndAddToSetStrategy() {\n      return CreateNodesWithGroupEncodedIntoNameThenAddToSet.class;\n   }\n\n   /**\n    * needed, if {@link CreateNodesInGroupThenAddToSet} requires it\n    */\n   protected abstract Class<? extends CreateNodeWithGroupEncodedIntoName> defineAddNodeWithTagStrategy();\n\n   protected abstract Class<? extends DestroyNodeStrategy> defineDestroyNodeStrategy();\n\n   protected abstract Class<? extends RebootNodeStrategy> defineRebootNodeStrategy();\n\n   protected abstract Class<? extends ResumeNodeStrategy> defineStartNodeStrategy();\n\n   protected abstract Class<? extends SuspendNodeStrategy> defineStopNodeStrategy();\n\n   protected abstract Class<? extends GetNodeMetadataStrategy> defineGetNodeMetadataStrategy();\n\n   protected abstract Class<? extends GetImageStrategy> defineGetImageStrategy();\n\n   protected abstract Class<? extends ListNodesStrategy> defineListNodesStrategy();\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/config/BindComputeSuppliersByClass.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.config;\n\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Image;\n\nimport com.google.common.base.Supplier;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Scopes;\nimport com.google.inject.TypeLiteral;\n\npublic abstract class BindComputeSuppliersByClass extends AbstractModule {\n\n   @Override\n   protected void configure() {\n      bindImageSupplier(defineImageSupplier());\n      bindHardwareSupplier(defineHardwareSupplier());\n   }\n\n   protected abstract Class<? extends Supplier<Set<? extends Image>>> defineImageSupplier();\n\n   protected abstract Class<? extends Supplier<Set<? extends Hardware>>> defineHardwareSupplier();\n\n   protected void bindImageSupplier(Class<? extends Supplier<Set<? extends Image>>> clazz) {\n      bind(new TypeLiteral<Supplier<Set<? extends Image>>>() {\n      }).to(clazz).in(Scopes.SINGLETON);\n   }\n   \n   protected void bindHardwareSupplier(Class<? extends Supplier<Set<? extends Hardware>>> clazz) {\n      bind(new TypeLiteral<Supplier<Set<? extends Hardware>>>() {\n      }).to(clazz).in(Scopes.SINGLETON);\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/config/ComputeServiceAdapterContextModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.config;\n\nimport static com.google.common.base.Functions.compose;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Predicates.notNull;\n\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.ComputeServiceAdapter;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.ImageBuilder;\nimport org.jclouds.compute.strategy.CreateNodeWithGroupEncodedIntoName;\nimport org.jclouds.compute.strategy.DestroyNodeStrategy;\nimport org.jclouds.compute.strategy.GetImageStrategy;\nimport org.jclouds.compute.strategy.GetNodeMetadataStrategy;\nimport org.jclouds.compute.strategy.ListNodesStrategy;\nimport org.jclouds.compute.strategy.PopulateDefaultLoginCredentialsForImageStrategy;\nimport org.jclouds.compute.strategy.RebootNodeStrategy;\nimport org.jclouds.compute.strategy.ResumeNodeStrategy;\nimport org.jclouds.compute.strategy.SuspendNodeStrategy;\nimport org.jclouds.compute.strategy.impl.AdaptingComputeServiceStrategies;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.location.suppliers.LocationsSupplier;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.FluentIterable;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Provides;\n\npublic class ComputeServiceAdapterContextModule<N, H, I, L> extends BaseComputeServiceContextModule {\n\n   /**\n    * install this, if you want to use your computeservice adapter to handle locations. Note that if you do this, you'll\n    * want to instantiate a subclass to prevent type erasure.\n    * \n    * ex.\n    * \n    * <pre>\n    * install(new LocationsFromComputeServiceAdapterModule&lt;NodeMetadata, Hardware, Image, Location&gt;() {\n    * });\n    * </pre>\n    * \n    * not\n    * \n    * <pre>\n    * install(new LocationsFromComputeServiceAdapterModule&lt;NodeMetadata, Hardware, Image, Location&gt;());\n    * </pre>\n    */\n   public static class LocationsFromComputeServiceAdapterModule<N, H, I, L> extends AbstractModule {\n\n      @Override\n      protected void configure() {\n      }\n\n      @Provides\n      @Singleton\n      protected final LocationsSupplier supplyLocationsFromComputeServiceAdapter(\n            final ComputeServiceAdapter<N, H, I, L> adapter, final Function<L, Location> transformer) {\n         return new LocationsSupplier() {\n            @Override\n            public Set<? extends Location> get() {\n               return transformGuardingNull(adapter.listLocations(), transformer);\n            }\n\n            public String toString() {\n               return toStringHelper(adapter).add(\"method\", \"listLocations\").toString();\n            }\n         };\n      }\n   }\n\n   @Provides\n   @Singleton\n   protected final Supplier<Set<? extends Hardware>> provideHardware(final ComputeServiceAdapter<N, H, I, L> adapter,\n         final Function<H, Hardware> transformer) {\n      return new Supplier<Set<? extends Hardware>>() {\n         @Override\n         public Set<? extends Hardware> get() {\n            return transformGuardingNull(adapter.listHardwareProfiles(), transformer);\n         }\n\n         public String toString() {\n            return toStringHelper(adapter).add(\"method\", \"listHardwareProfiles\").toString();\n         }\n      };\n   }\n\n   private static <F, T> Set<? extends T> transformGuardingNull(Iterable<F> from, Function<F, T> transformer) {\n      return FluentIterable.from(from).filter(notNull()).transform(transformer).filter(notNull()).toSet();\n   }\n\n   @Provides\n   @Singleton\n   protected final Supplier<Set<? extends Image>> provideImages(final ComputeServiceAdapter<N, H, I, L> adapter,\n         final Function<I, Image> transformer, final AddDefaultCredentialsToImage addDefaultCredentialsToImage) {\n      return new Supplier<Set<? extends Image>>() {\n         @Override\n         public Set<? extends Image> get() {\n            return transformGuardingNull(adapter.listImages(), compose(addDefaultCredentialsToImage, transformer));\n         }\n\n         public String toString() {\n            return toStringHelper(adapter).add(\"method\", \"listImages\").toString();\n         }\n      };\n   }\n\n   @Singleton\n   public static class AddDefaultCredentialsToImage implements Function<Image, Image> {\n      private final PopulateDefaultLoginCredentialsForImageStrategy credsForImage;\n\n      @Inject\n      public AddDefaultCredentialsToImage(PopulateDefaultLoginCredentialsForImageStrategy credsForImage) {\n         this.credsForImage = credsForImage;\n      }\n\n      @Override\n      public Image apply(Image arg0) {\n         if (arg0 == null)\n            return null;\n         LoginCredentials credentials = credsForImage.apply(arg0);\n         return credentials != null ? ImageBuilder.fromImage(arg0).defaultCredentials(credentials).build() : arg0;\n      }\n\n      @Override\n      public String toString() {\n         return toStringHelper(this).add(\"credsForImage\", credsForImage).toString();\n      }\n   }\n\n   @Provides\n   @Singleton\n   protected final CreateNodeWithGroupEncodedIntoName defineAddNodeWithTagStrategy(\n         AdaptingComputeServiceStrategies<N, H, I, L> in) {\n      return in;\n   }\n\n   @Provides\n   @Singleton\n   protected final DestroyNodeStrategy defineDestroyNodeStrategy(AdaptingComputeServiceStrategies<N, H, I, L> in) {\n      return in;\n   }\n\n   @Provides\n   @Singleton\n   protected final GetNodeMetadataStrategy defineGetNodeMetadataStrategy(AdaptingComputeServiceStrategies<N, H, I, L> in) {\n      return in;\n   }\n\n   @Provides\n   @Singleton\n   protected final GetImageStrategy defineGetImageStrategy(AdaptingComputeServiceStrategies<N, H, I, L> in) {\n      return in;\n   }\n\n   @Provides\n   @Singleton\n   protected final ListNodesStrategy defineListNodesStrategy(AdaptingComputeServiceStrategies<N, H, I, L> in) {\n      return in;\n   }\n\n   @Provides\n   @Singleton\n   protected final RebootNodeStrategy defineRebootNodeStrategy(AdaptingComputeServiceStrategies<N, H, I, L> in) {\n      return in;\n   }\n\n   @Provides\n   @Singleton\n   protected final ResumeNodeStrategy defineStartNodeStrategy(AdaptingComputeServiceStrategies<N, H, I, L> in) {\n      return in;\n   }\n\n   @Provides\n   @Singleton\n   protected final SuspendNodeStrategy defineStopNodeStrategy(AdaptingComputeServiceStrategies<N, H, I, L> in) {\n      return in;\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/config/ComputeServiceProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.config;\n\npublic final class ComputeServiceProperties {\n   public static final String RESOURCENAME_PREFIX = \"jclouds.compute.resourcename-prefix\";\n   public static final String RESOURCENAME_DELIMITER = \"jclouds.compute.resourcename-delimiter\";\n\n   public static final String TIMEOUT_NODE_RUNNING = \"jclouds.compute.timeout.node-running\";\n   public static final String TIMEOUT_NODE_SUSPENDED = \"jclouds.compute.timeout.node-suspended\";\n   public static final String TIMEOUT_NODE_TERMINATED = \"jclouds.compute.timeout.node-terminated\";\n\n   public static final String TIMEOUT_SCRIPT_COMPLETE = \"jclouds.compute.timeout.script-complete\";\n   public static final String TIMEOUT_PORT_OPEN = \"jclouds.compute.timeout.port-open\";\n\n   public static final String INIT_STATUS_INITIAL_PERIOD = \"jclouds.compute.init-status.initial-period\";\n   public static final String INIT_STATUS_MAX_PERIOD = \"jclouds.compute.init-status.max-period\";\n\n   /**\n    * Initial period between the ComputeService's node polls. Subsequent periods increase exponentially\n    * (based on the backoff factor) and become constant when the maximum period is reached.\n    * The unit is milliseconds.\n    */\n   public static final String POLL_INITIAL_PERIOD = \"jclouds.compute.poll-status.initial-period\";\n\n   /**\n    * Once the exponentially increasing period between ComputeService's node\n    * polls has reached this maximum period, it remains at this value.\n    * The unit is milliseconds.\n    */\n   public static final String POLL_MAX_PERIOD = \"jclouds.compute.poll-status.max-period\";\n\n   /**\n    * time in milliseconds to wait for an image to finish creating.\n    * \n    * Override {@link Timeouts#imageAvailable default} by setting this property using\n    * {@link ContextBuilder#overrides}\n    */\n   public static final String TIMEOUT_IMAGE_AVAILABLE = \"jclouds.compute.timeout.image-available\";\n   \n   /**\n    * time in milliseconds to wait for an image to delete.\n    * \n    * Override {@link Timeouts#imageDeleted default} by setting this property using\n    * {@link ContextBuilder#overrides}\n    */\n   public static final String TIMEOUT_IMAGE_DELETED = \"jclouds.compute.timeout.image-deleted\";\n\n   /**\n    * time in milliseconds to try to clean up incidental resources \n    * (e.g. security groups, key-pairs, etc).\n    * \n    * Override {@link Timeouts#cleanupIncidentalResources default} by setting this property using\n    * {@link ContextBuilder#overrides}\n    */\n   public static final String TIMEOUT_CLEANUP_INCIDENTAL_RESOURCES = \"jclouds.compute.timeout.cleanup-incidental-resources\";\n\n   /**\n    * overrides the default specified in the subclass of\n    * {@link BaseComputeServiceContextModule#provideTemplate}\n    * \n    * @see TemplateBuilderSpec\n    */\n   public static final String TEMPLATE = \"jclouds.template\";\n\n   /**\n    * overrides the image specified in the subclass of\n    * {@link BaseComputeServiceContextModule#provideTemplate}\n    */\n   public static final String IMAGE_ID = \"jclouds.image-id\";\n\n   /**\n    * username and, if colon delimited, password of the default user on the image that is or can\n    * become root\n    * <p/>\n    * ex. {@code ubuntu} ex. {@code toor:password}\n    */\n   public static final String IMAGE_LOGIN_USER = \"jclouds.image.login-user\";\n\n   /**\n    * true if gaining a sudo shell requires a password\n    */\n   public static final String IMAGE_AUTHENTICATE_SUDO = \"jclouds.image.authenticate-sudo\";\n\n   /**\n    * comma-separated nodes that we shouldn't attempt to list as they are dead in the provider for\n    * some reason.\n    */\n   public static final String BLACKLIST_NODES = \"jclouds.compute.blacklist-nodes\";\n\n   /**\n    * os to map of version input string to output string\n    * <p/>\n    * ex.\n    * \n    * <pre>\n    * {\"centos\":{\"5.4\":\"5.4\",\"5.5\":\"5.5\"},\"rhel\":{\"5.4\":\"5.4\",\"5.5\":\"5.5\"},\"ubuntu\":{\"karmic\":\"9.10\",\"lucid\":\"10.04\",\"maverick\":\"10.10\",\"natty\":\"11.04\"},\"windows\":{\"2008\":\"2008\",\"Server 2008\":\"2008\",\"2008 R2\":\"2008 R2\",\"Server 2008 R2\":\"2008 R2\",\"2008 SP2\":\"2008 SP2\",\"Server 2008 SP2\":\"2008 SP2\"}}\n    * </pre>\n    */\n   public static final String OS_VERSION_MAP_JSON = \"jclouds.compute.os-version-map-json\";\n\n   /**\n    * can be set to either PRIVATE, PUBLIC, ALL (default) controls what interfaces will be used when scanning for an open connection\n    */\n   public static final String SOCKET_FINDER_ALLOWED_INTERFACES = \"jclouds.compute.socket-finder-allowed-interfaces\";\n\n   private ComputeServiceProperties() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/config/ComputeServiceTimeoutsModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.config;\nimport static com.google.common.base.Predicates.not;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_IMAGE_AVAILABLE;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_IMAGE_DELETED;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_RUNNING;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_SUSPENDED;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_TERMINATED;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_SCRIPT_COMPLETE;\nimport static org.jclouds.util.Predicates2.retry;\n\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.functions.PollNodeRunning;\nimport org.jclouds.compute.predicates.AtomicImageAvailable;\nimport org.jclouds.compute.predicates.AtomicImageDeleted;\nimport org.jclouds.compute.predicates.AtomicNodeRunning;\nimport org.jclouds.compute.predicates.AtomicNodeSuspended;\nimport org.jclouds.compute.predicates.AtomicNodeTerminated;\nimport org.jclouds.compute.predicates.ScriptStatusReturnsZero;\nimport org.jclouds.compute.predicates.ScriptStatusReturnsZero.CommandUsingClient;\nimport org.jclouds.compute.reference.ComputeServiceConstants.PollPeriod;\nimport org.jclouds.compute.reference.ComputeServiceConstants.Timeouts;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Provides;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.name.Names;\n\npublic class ComputeServiceTimeoutsModule extends AbstractModule {\n\n   @Provides\n   @Singleton\n   @Named(TIMEOUT_NODE_RUNNING)\n   protected final Predicate<AtomicReference<NodeMetadata>> provideNodeRunning(AtomicNodeRunning statusRunning, Timeouts timeouts,\n           PollPeriod period) {\n      return nodeRunning(statusRunning, timeouts, period);\n   }\n\n   protected Predicate<AtomicReference<NodeMetadata>> nodeRunning(AtomicNodeRunning statusRunning, Timeouts timeouts,\n         PollPeriod period) {\n      return timeouts.nodeRunning == 0 ? statusRunning : RetryablePredicateGuardingNull.create(statusRunning,\n            timeouts.nodeRunning, period.pollInitialPeriod, period.pollMaxPeriod);\n   }\n\n   @Provides\n   @Singleton\n   @Named(TIMEOUT_NODE_TERMINATED)\n   protected final Predicate<AtomicReference<NodeMetadata>> provideServerTerminated(AtomicNodeTerminated statusTerminated,\n           Timeouts timeouts, PollPeriod period) {\n      return serverTerminated(statusTerminated, timeouts, period);\n   }\n\n   protected Predicate<AtomicReference<NodeMetadata>> serverTerminated(AtomicNodeTerminated statusTerminated,\n         Timeouts timeouts, PollPeriod period) {\n      return timeouts.nodeTerminated == 0 ? statusTerminated : retry(statusTerminated, timeouts.nodeTerminated,\n            period.pollInitialPeriod, period.pollMaxPeriod);\n   }\n\n   @Provides\n   @Singleton\n   @Named(TIMEOUT_NODE_SUSPENDED)\n   protected final Predicate<AtomicReference<NodeMetadata>> provideserverSuspended(AtomicNodeSuspended statusSuspended,\n           Timeouts timeouts, PollPeriod period) {\n      return serverSuspended(statusSuspended, timeouts, period);\n   }\n\n   protected Predicate<AtomicReference<NodeMetadata>> serverSuspended(AtomicNodeSuspended statusSuspended,\n         Timeouts timeouts, PollPeriod period) {\n      return timeouts.nodeSuspended == 0 ? statusSuspended : RetryablePredicateGuardingNull.create(statusSuspended,\n            timeouts.nodeSuspended, period.pollInitialPeriod, period.pollMaxPeriod);\n   }\n\n   @Provides\n   @Singleton\n   @Named(TIMEOUT_SCRIPT_COMPLETE)\n   protected final Predicate<CommandUsingClient> provideRunScriptRunning(ScriptStatusReturnsZero statusRunning, Timeouts timeouts) {\n      return runScriptRunning(statusRunning, timeouts);\n   }\n\n   protected Predicate<CommandUsingClient> runScriptRunning(ScriptStatusReturnsZero statusRunning, Timeouts timeouts) {\n      return timeouts.scriptComplete == 0 ? not(statusRunning) : retry(not(statusRunning), timeouts.scriptComplete);\n   }\n\n   @Provides\n   @Singleton\n   @Named(TIMEOUT_IMAGE_AVAILABLE)\n   protected final Predicate<AtomicReference<Image>> imageAvailable(AtomicImageAvailable statusAvailable, Timeouts timeouts,\n         PollPeriod period) {\n      return timeouts.imageAvailable == 0 ? statusAvailable : retry(statusAvailable, timeouts.imageAvailable,\n            period.pollInitialPeriod, period.pollMaxPeriod);\n   }\n\n   @Provides\n   @Singleton\n   @Named(TIMEOUT_IMAGE_DELETED)\n   protected final Predicate<AtomicReference<Image>> serverDeleted(AtomicImageDeleted statusDeleted, Timeouts timeouts,\n         PollPeriod period) {\n      return timeouts.imageDeleted == 0 ? statusDeleted : retry(statusDeleted, timeouts.imageDeleted,\n            period.pollInitialPeriod, period.pollMaxPeriod);\n   }\n\n   @Override\n   protected void configure() {\n      bind(new TypeLiteral<Function<AtomicReference<NodeMetadata>, AtomicReference<NodeMetadata>>>() {\n      }).annotatedWith(Names.named(TIMEOUT_NODE_RUNNING)).to(PollNodeRunning.class);\n   }\n\n   /**\n    * Avoids \"losing\" the ComputeMetadata if client returns null temporarily (issue #989).\n    * Ensures we always pass a non-null to the wrapped predicate, but will propagate the null to\n    * the caller qt the end.\n    * \n    */\n   private static class RetryablePredicateGuardingNull<T> implements Predicate<AtomicReference<T>> {\n      \n      private static <T> RetryablePredicateGuardingNull<T> create(Predicate<AtomicReference<T>> predicate, long maxWait, long period, long maxPeriod) {\n         return new RetryablePredicateGuardingNull<T>(predicate, maxWait, period, maxPeriod);\n      }\n      \n      private class AtomicRefAndOrig {\n         private final T orig;\n         private final AtomicReference<T> ref;\n         \n         AtomicRefAndOrig(T orig, AtomicReference<T> ref) {\n            this.orig = orig;\n            this.ref = ref;\n         }\n      }\n      \n      private final Predicate<AtomicRefAndOrig> retryablePredicate;\n      \n      private RetryablePredicateGuardingNull(final Predicate<AtomicReference<T>> predicate, long maxWait, long period, long maxPeriod) {\n         Predicate<AtomicRefAndOrig> nonNullThingPredicate = new Predicate<AtomicRefAndOrig>() {\n            @Override\n            public boolean apply(AtomicRefAndOrig input) {\n               AtomicReference<T> ref = (input.ref.get() != null) ? input.ref : new AtomicReference<T>(input.orig);\n               try {\n                  return predicate.apply(ref);\n               } finally {\n                  input.ref.set(ref.get());\n               }\n            }\n         };\n         retryablePredicate = retry(nonNullThingPredicate, maxWait, period, maxPeriod);\n      }\n\n      @Override\n      public boolean apply(AtomicReference<T> input) {\n         AtomicRefAndOrig refAndOrig = new AtomicRefAndOrig(input.get(), input);\n         return retryablePredicate.apply(refAndOrig);\n      }\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/config/CustomizationResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.config;\n\n/**\n * \n * Designates information related to customization of a resource.\n */\npublic interface CustomizationResponse {\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/config/GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNull.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.config;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.config.ValueOfConfigurationKeyOrNull;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.domain.LoginCredentials.Builder;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.location.Provider;\n\nimport com.google.inject.Inject;\n\n@Singleton\npublic class GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNull implements\n      jakarta.inject.Provider<LoginCredentials> {\n   private final ValueOfConfigurationKeyOrNull config;\n   private final String provider;\n   private final Map<String, Credentials> credentialStore;\n\n   @Inject\n   public GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNull(@Provider String provider,\n         ValueOfConfigurationKeyOrNull config, Map<String, Credentials> credentialStore) {\n      this.config = checkNotNull(config, \"config\");\n      this.provider = checkNotNull(provider, \"provider\");\n      this.credentialStore = checkNotNull(credentialStore, \"credentialStore\");\n   }\n\n   @Override\n   @Nullable\n   public LoginCredentials get() {\n      if (credentialStore.containsKey(\"image\")) {\n         return LoginCredentials.fromCredentials(credentialStore.get(\"image\"));\n      }\n      Builder builder = LoginCredentials.builder();\n\n      String loginUser = config.apply(provider + \".image.login-user\");\n      if (loginUser == null)\n         loginUser = config.apply(\"jclouds.image.login-user\");\n      if (loginUser != null) {\n         int pos = loginUser.indexOf(':');\n         if (pos != -1) {\n            builder.user(loginUser.substring(0, pos)).password(loginUser.substring(pos + 1));\n         } else\n            builder.user(loginUser);\n      }\n\n      String authenticateSudo = config.apply(provider + \".image.authenticate-sudo\");\n      if (authenticateSudo == null)\n         authenticateSudo = config.apply(\"jclouds.image.authenticate-sudo\");\n      if (authenticateSudo != null) {\n         builder.authenticateSudo(Boolean.valueOf(authenticateSudo));\n      }\n\n      LoginCredentials creds = builder.build();\n      if (creds != null)\n         credentialStore.put(\"image\", creds);\n      return creds;\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/config/JCloudsNativeComputeServiceAdapterContextModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.config;\n\n\nimport org.jclouds.compute.ComputeServiceAdapter;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.domain.Location;\nimport org.jclouds.functions.IdentityFunction;\n\nimport com.google.common.base.Function;\nimport com.google.inject.TypeLiteral;\n\npublic class JCloudsNativeComputeServiceAdapterContextModule extends\n         ComputeServiceAdapterContextModule<NodeMetadata, Hardware, Image, Location> {\n   protected final Class<? extends ComputeServiceAdapter<NodeMetadata, Hardware, Image, Location>> adapter;\n\n   public JCloudsNativeComputeServiceAdapterContextModule(\n            Class<? extends ComputeServiceAdapter<NodeMetadata, Hardware, Image, Location>> adapter) {\n      this.adapter = adapter;\n   }\n\n   /**\n    * This binds the converters to {@link IdentityFunction} as that ensure the same value is\n    * returned.\n    */\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   protected void configure() {\n      bind(new TypeLiteral<ComputeServiceAdapter<NodeMetadata, Hardware, Image, Location>>() {\n      }).to(adapter);\n      bind(new TypeLiteral<Function<NodeMetadata, NodeMetadata>>() {\n      }).to(Class.class.cast(IdentityFunction.class));\n      bind(new TypeLiteral<Function<Image, Image>>() {\n      }).to(Class.class.cast(IdentityFunction.class));\n      bind(new TypeLiteral<Function<Hardware, Hardware>>() {\n      }).to(Class.class.cast(IdentityFunction.class));\n      bind(new TypeLiteral<Function<Location, Location>>() {\n      }).to(Class.class.cast(IdentityFunction.class));\n      super.configure();\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/config/PersistNodeCredentialsModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.config;\n\nimport java.util.Map;\n\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadataBuilder;\nimport org.jclouds.compute.internal.PersistNodeCredentials;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.scriptbuilder.domain.Statement;\nimport org.jclouds.scriptbuilder.functions.CredentialsFromAdminAccess;\n\nimport com.google.common.base.Function;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Inject;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.assistedinject.Assisted;\nimport com.google.inject.assistedinject.FactoryModuleBuilder;\nimport com.google.inject.name.Names;\n\npublic class PersistNodeCredentialsModule extends AbstractModule {\n\n   static class RefreshCredentialsForNodeIfRanAdminAccess implements Function<NodeMetadata, NodeMetadata> {\n      protected final Map<String, Credentials> credentialStore;\n      protected final Statement statement;\n\n      @Inject\n      protected RefreshCredentialsForNodeIfRanAdminAccess(Map<String, Credentials> credentialStore,\n            @Nullable @Assisted Statement statement) {\n         this.credentialStore = credentialStore;\n         this.statement = statement;\n      }\n\n      @Override\n      public NodeMetadata apply(NodeMetadata input) {\n         if (statement == null)\n            return input;\n         Credentials credentials = CredentialsFromAdminAccess.INSTANCE.apply(statement);\n         if (credentials != null) {\n            LoginCredentials creds = LoginCredentials.fromCredentials(credentials);\n            input = NodeMetadataBuilder.fromNodeMetadata(input).credentials(creds).build();\n            credentialStore.put(\"node#\" + input.getId(), input.getCredentials());\n         }\n         return input;\n      }\n\n   }\n\n   static class RefreshCredentialsForNode extends RefreshCredentialsForNodeIfRanAdminAccess {\n\n      @Inject\n      public RefreshCredentialsForNode(Map<String, Credentials> credentialStore, @Assisted @Nullable Statement statement) {\n         super(credentialStore, statement);\n      }\n\n      @Override\n      public NodeMetadata apply(NodeMetadata input) {\n         input = super.apply(input);\n         if (input.getCredentials() != null)\n            credentialStore.put(\"node#\" + input.getId(), input.getCredentials());\n         return input;\n      }\n\n   }\n\n   @Override\n   protected void configure() {\n\n      install(new FactoryModuleBuilder().implement(new TypeLiteral<Function<NodeMetadata, NodeMetadata>>() {\n      }, Names.named(\"ifAdminAccess\"), RefreshCredentialsForNodeIfRanAdminAccess.class)\n            .implement(new TypeLiteral<Function<NodeMetadata, NodeMetadata>>() {\n            }, Names.named(\"always\"), RefreshCredentialsForNode.class).build(PersistNodeCredentials.class));\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/config/ResolvesImages.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.config;\n\nimport static java.lang.annotation.ElementType.TYPE;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\n/**\n * Marks that the module can augment an images of\n * a given cloud.\n *\n * Such a module binds a strategy to determine such things,\n * as:\n * <ul>\n * <li>default username</li>\n * <li>default password, specific to a cloud and image.</li>\n * </ul>\n */\n@Retention(RUNTIME)\n@Target(TYPE)\npublic @interface ResolvesImages {\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/domain/CIMOperatingSystem.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.domain;\n\nimport org.jclouds.cim.OSType;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.ovf.Envelope;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Operating system based on DMTF CIM model.\n * \n * @see <a href=\"http://dmtf.org/standards/cim/cim_schema_v2260\">DMTF CIM model</a>\n */\n@Beta\npublic class CIMOperatingSystem extends OperatingSystem {\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder extends OperatingSystem.Builder {\n      private OSType osType;\n\n      /**\n       * @see CIMOperatingSystem#getOsType\n       */\n      public Builder osType(@Nullable OSType osType) {\n         this.osType = osType;\n         return this;\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public CIMOperatingSystem build() {\n         return new CIMOperatingSystem(family, name, version, arch, description, is64Bit, osType);\n      }\n\n      public Builder fromCIMOperatingSystem(CIMOperatingSystem in) {\n         return fromOperatingSystem(in).osType(in.getOsType());\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n\n      @Override\n      public Builder arch(String arch) {\n         return Builder.class.cast(super.arch(arch));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder description(String description) {\n         return Builder.class.cast(super.description(description));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder family(OsFamily family) {\n         return Builder.class.cast(super.family(family));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder fromOperatingSystem(OperatingSystem in) {\n         return Builder.class.cast(super.fromOperatingSystem(in));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder is64Bit(boolean is64Bit) {\n         return Builder.class.cast(super.is64Bit(is64Bit));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder name(String name) {\n         return Builder.class.cast(super.name(name));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder version(String version) {\n         return Builder.class.cast(super.version(version));\n      }\n   }\n\n   public static CIMOperatingSystem toComputeOs(org.jclouds.ovf.OperatingSystemSection os) {\n      return new CIMOperatingSystem(OSType.fromValue(os.getId()), \"\", null, os.getDescription());\n   }\n\n   public static CIMOperatingSystem toComputeOs(Envelope ovf) {\n      return toComputeOs(ovf.getVirtualSystem().getOperatingSystemSection());\n   }\n\n   private OSType osType;\n\n   protected CIMOperatingSystem() {\n      super();\n   }\n\n   public CIMOperatingSystem(OSType osType, String version, String arch, String description) {\n      this(osType.getFamily(), osType.getValue(), version, arch, description, osType.is64Bit(), osType);\n   }\n\n   public CIMOperatingSystem(@Nullable OsFamily family, @Nullable String name, @Nullable String version,\n            @Nullable String arch, String description, boolean is64Bit, OSType osType) {\n      super(family, name, version, arch, description, is64Bit);\n      this.osType = osType;\n\n   }\n\n   /**\n    * CIM OSType of the image\n    */\n   public OSType getOsType() {\n      return osType;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = super.hashCode();\n      result = prime * result + ((osType == null) ? 0 : osType.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (!super.equals(obj))\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      CIMOperatingSystem other = (CIMOperatingSystem) obj;\n      if (osType == null) {\n         if (other.osType != null)\n            return false;\n      } else if (!osType.equals(other.osType))\n         return false;\n      return true;\n   }\n\n   @Override\n   protected ToStringHelper string() {\n      return super.string().add(\"osType\", osType);\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/domain/CloneImageTemplate.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.domain;\n\n/**\n * An {@link ImageTemplate} for the purpose of cloning an existing node.\n */\npublic interface CloneImageTemplate extends ImageTemplate {\n\n   String getSourceNodeId();\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/domain/ComputeMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.domain;\n\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.internal.ComputeMetadataImpl;\nimport org.jclouds.domain.ResourceMetadata;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.inject.ImplementedBy;\n\n/**\n */\n@ImplementedBy(ComputeMetadataImpl.class)\npublic interface ComputeMetadata extends ResourceMetadata<ComputeType> {\n   /**\n    * @return Type of the resource, ex node, image, size\n    */\n   @Override\n   ComputeType getType();\n\n   /**\n    * @return id of the server within the naming scope it was created. potentially generated by the\n    *         service.\n    */\n   @Override\n   String getProviderId();\n\n   /**\n    * @return user defined name of the server.\n    */\n   @Override\n   @Nullable\n   String getName();\n\n   /**\n    * \n    * A means to uniquely address this resource within a provider. For example, if the namespace of\n    * a node or image is region based, the id will likely include both the region and the\n    * provider-supplied id encoded to avoid collisions.\n    * \n    * @return unique id within your account on the provider\n    */\n   String getId();\n\n   /**\n    * @return tags describing this resource, if supported\n    */\n   Set<String> getTags();\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/domain/ComputeMetadataBuilder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.net.URI;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.internal.ComputeMetadataImpl;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.ResourceMetadataBuilder;\n\nimport com.google.common.collect.ImmutableSet;\n\npublic class ComputeMetadataBuilder extends ResourceMetadataBuilder<ComputeType> {\n   protected String id;\n   protected ComputeType type;\n   protected Set<String> tags = ImmutableSet.<String>of();\n\n   public ComputeMetadataBuilder(ComputeType type) {\n      this.type = checkNotNull(type, \"type\");\n   }\n\n   public ComputeMetadataBuilder id(String id) {\n      this.id = id;\n      return this;\n   }\n\n   public ComputeMetadataBuilder tags(Iterable<String> tags) {\n      this.tags  = ImmutableSet.<String> copyOf(checkNotNull(tags, \"tags\"));\n      return this;\n   }\n\n   /**\n    * set id and providerId to the same value;\n    */\n   public ComputeMetadataBuilder ids(String id) {\n      id(id).providerId(id);\n      return this;\n   }\n\n   @Override\n   public ComputeMetadataBuilder providerId(String providerId) {\n      return ComputeMetadataBuilder.class.cast(super.providerId(providerId));\n   }\n\n   @Override\n   public ComputeMetadataBuilder name(String name) {\n      return ComputeMetadataBuilder.class.cast(super.name(name));\n   }\n\n   @Override\n   public ComputeMetadataBuilder location(Location location) {\n      return ComputeMetadataBuilder.class.cast(super.location(location));\n   }\n\n   @Override\n   public ComputeMetadataBuilder uri(URI uri) {\n      return ComputeMetadataBuilder.class.cast(super.uri(uri));\n   }\n\n   @Override\n   public ComputeMetadataBuilder userMetadata(Map<String, String> userMetadata) {\n      return ComputeMetadataBuilder.class.cast(super.userMetadata(userMetadata));\n   }\n\n   public ComputeMetadata build() {\n      return new ComputeMetadataImpl(type, providerId, name, id, location, uri, userMetadata, tags);\n   }\n\n   public static ComputeMetadataBuilder fromComputeMetadata(ComputeMetadata in) {\n      return new ComputeMetadataBuilder(in.getType()).id(in.getId()).location(in.getLocation()).name(in.getName())\n            .uri(in.getUri()).userMetadata(in.getUserMetadata()).tags(in.getTags());\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/domain/ComputeMetadataIncludingStatus.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.domain;\n\nimport org.jclouds.javax.annotation.Nullable;\n\n/**\n */\npublic interface ComputeMetadataIncludingStatus<S extends Enum<S>> extends ComputeMetadata {\n\n   /**\n    * portable status of the resource\n    * \n    * @since 1.5\n    */\n   S getStatus();\n\n   /**\n    * status of the resource, as supplied literally from the backend api.\n    * \n    * @return status or null, if the backend api has no concept of status\n    * @since 1.5\n    */\n   @Nullable\n   String getBackendStatus();\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/domain/ComputeType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.domain;\n\npublic enum ComputeType {\n\n   NODE, IMAGE, HARDWARE, SECURITYGROUP;\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/domain/ExecChannel.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.io.Closeable;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\n\nimport org.jclouds.util.Closeables2;\n\nimport com.google.common.base.Supplier;\n\n/**\n * A current connection to an exec'd command.  Please ensure you call {@link ExecChannel#close}\n */\npublic class ExecChannel implements Closeable {\n\n   private final OutputStream input;\n   private final InputStream output;\n   private final InputStream error;\n   private final Supplier<Integer> exitStatus;\n   private final Closeable closer;\n\n   public ExecChannel(OutputStream input, InputStream output, InputStream error, Supplier<Integer> exitStatus,\n            Closeable closer) {\n      this.input = checkNotNull(input, \"input\");\n      this.output = checkNotNull(output, \"output\");\n      this.error = checkNotNull(error, \"error\");\n      this.exitStatus = checkNotNull(exitStatus, \"exitStatus\");\n      this.closer = checkNotNull(closer, \"closer\");\n   }\n\n   /**\n    * \n    * @return the command's {@code stdin} stream.\n    */\n   public OutputStream getInput() {\n      return input;\n   }\n\n   /**\n    * \n    * @return the command's {@code stderr} stream.\n    */\n   public InputStream getError() {\n      return error;\n   }\n\n   /**\n    * \n    * @return the command's {@code stdout} stream.\n    */\n   public InputStream getOutput() {\n      return output;\n   }\n\n   /**\n    * \n    * @return the exit status of the command if it was received, or {@code null} if this information\n    *         was not received.\n    */\n   public Supplier<Integer> getExitStatus() {\n      return exitStatus;\n   }\n\n   /**\n    * closes resources associated with this channel.\n    */\n   @Override\n   public void close() throws IOException {\n      Closeables2.closeQuietly(input);\n      Closeables2.closeQuietly(output);\n      Closeables2.closeQuietly(error);\n      closer.close();\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/domain/ExecResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.domain;\n\nimport org.jclouds.compute.config.CustomizationResponse;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\npublic class ExecResponse implements CustomizationResponse {\n\n   public static final int DEFAULT_EXIT_STATUS = -1;\n    \n   private final String output;\n   private final String error;\n   private final int exitStatus;\n\n   public ExecResponse(String output, String error, Integer exitStatus) {\n      this.output = output;\n      this.error = error;\n      this.exitStatus = exitStatus != null ? exitStatus : DEFAULT_EXIT_STATUS;\n   }\n\n   public String getError() {\n      return error;\n   }\n\n   public String getOutput() {\n      return output;\n   }\n\n   public int getExitStatus() {\n      return exitStatus;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(output, error, exitStatus);\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (o == null)\n         return false;\n      if (!o.getClass().equals(getClass()))\n         return false;\n      ExecResponse that = ExecResponse.class.cast(o);\n      return Objects.equal(this.output, that.output) && Objects.equal(this.error, that.error)\n            && Objects.equal(this.exitStatus, that.exitStatus);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(\"\").add(\"output\", output).add(\"error\", error).add(\"exitStatus\", exitStatus)\n            .toString();\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/domain/Hardware.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.domain;\n\nimport java.util.List;\n\nimport org.jclouds.compute.domain.internal.HardwareImpl;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.Predicate;\nimport com.google.inject.ImplementedBy;\n\n/**\n * Size of a node.\n */\n@ImplementedBy(HardwareImpl.class)\npublic interface Hardware extends ComputeMetadata {\n\n   /**\n    * Amount of virtual or physical processors provided\n    */\n   List<? extends Processor> getProcessors();\n\n   /**\n    * Amount of RAM provided in MB (256M, 1740)\n    */\n   int getRam();\n   \n   /**\n    * volumes associated with this.\n    */\n   List<? extends Volume> getVolumes();\n\n   /**\n    * Determines whether this size can run an image.\n    */\n   Predicate<Image> supportsImage();\n   \n   /**\n    * @return hypervisor type, if this is a virtual machine and the type is known\n    */\n   @Nullable\n   String getHypervisor();\n   \n   /**\n    * True if usage of the hardware profile is now discouraged.\n    */\n   boolean isDeprecated();\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/domain/HardwareBuilder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Predicates.not;\nimport static org.jclouds.compute.predicates.ImagePredicates.any;\n\nimport java.net.URI;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.compute.domain.internal.HardwareImpl;\nimport org.jclouds.compute.predicates.ImagePredicates;\nimport org.jclouds.domain.Location;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Lists;\n\npublic class HardwareBuilder extends ComputeMetadataBuilder {\n   protected List<Processor> processors = Lists.newArrayList();\n   protected int ram;\n   protected List<Volume> volumes = Lists.newArrayList();\n   protected Predicate<Image> supportsImage = any();\n   protected String hypervisor;\n   protected boolean deprecated = false;\n\n   public HardwareBuilder() {\n      super(ComputeType.HARDWARE);\n   }\n\n   public HardwareBuilder processor(Processor processor) {\n      this.processors.add(checkNotNull(processor, \"processor\"));\n      return this;\n   }\n\n   public HardwareBuilder processors(Iterable<Processor> processors) {\n      this.processors = ImmutableList.copyOf(checkNotNull(processors, \"processors\"));\n      return this;\n   }\n\n   public HardwareBuilder ram(int ram) {\n      this.ram = ram;\n      return this;\n   }\n\n   public HardwareBuilder volume(Volume volume) {\n      this.volumes.add(checkNotNull(volume, \"volume\"));\n      return this;\n   }\n\n   public HardwareBuilder volumes(Iterable<Volume> volumes) {\n      this.volumes = ImmutableList.copyOf(checkNotNull(volumes, \"volumes\"));\n      return this;\n   }\n\n   public HardwareBuilder supportsImage(Predicate<Image> supportsImage) {\n      this.supportsImage = checkNotNull(supportsImage, \"supportsImage\");\n      return this;\n   }\n\n   public HardwareBuilder hypervisor(String hypervisor) {\n      this.hypervisor = hypervisor;\n      return this;\n   }\n\n   public HardwareBuilder deprecated(boolean deprecated) {\n      this.deprecated = deprecated;\n      return this;\n   }\n   \n   public HardwareBuilder deprecated() {\n       return deprecated(true);\n   }\n   \n   public HardwareBuilder is64Bit(boolean is64Bit) {\n      supportsImage(is64Bit ? ImagePredicates.is64Bit() : not(ImagePredicates.is64Bit()));\n      return this;\n   }\n\n   @Override\n   public HardwareBuilder id(String id) {\n      return HardwareBuilder.class.cast(super.id(id));\n   }\n   \n   @Override\n   public HardwareBuilder tags(Iterable<String> tags) {\n      return HardwareBuilder.class.cast(super.tags(tags));\n   }\n\n   @Override\n   public HardwareBuilder ids(String id) {\n      return HardwareBuilder.class.cast(super.ids(id));\n   }\n\n   @Override\n   public HardwareBuilder providerId(String providerId) {\n      return HardwareBuilder.class.cast(super.providerId(providerId));\n   }\n\n   @Override\n   public HardwareBuilder name(String name) {\n      return HardwareBuilder.class.cast(super.name(name));\n   }\n\n   @Override\n   public HardwareBuilder location(Location location) {\n      return HardwareBuilder.class.cast(super.location(location));\n   }\n\n   @Override\n   public HardwareBuilder uri(URI uri) {\n      return HardwareBuilder.class.cast(super.uri(uri));\n   }\n\n   @Override\n   public HardwareBuilder userMetadata(Map<String, String> userMetadata) {\n      return HardwareBuilder.class.cast(super.userMetadata(userMetadata));\n   }\n\n   @Override\n   public Hardware build() {\n      return new HardwareImpl(providerId, name, id, location, uri, userMetadata, tags, processors, ram, volumes,\n               supportsImage, hypervisor, deprecated);\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   public static HardwareBuilder fromHardware(Hardware in) {\n      return new HardwareBuilder().id(in.getId()).providerId(in.getProviderId()).location(in.getLocation()).name(\n               in.getName()).uri(in.getUri()).userMetadata(in.getUserMetadata()).tags(in.getTags()).processors(\n               List.class.cast(in.getProcessors())).ram(in.getRam()).volumes(List.class.cast(in.getVolumes()))\n               .supportsImage(in.supportsImage()).hypervisor(in.getHypervisor());\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/domain/Image.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.domain;\n\nimport org.jclouds.compute.domain.internal.ImageImpl;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.annotations.Beta;\nimport com.google.inject.ImplementedBy;\n\n/**\n * Running Operating system\n */\n@ImplementedBy(ImageImpl.class)\npublic interface Image extends ComputeMetadataIncludingStatus<Image.Status> {\n\n   public static enum Status {\n      /**\n       * The image is in transition\n       */\n      PENDING,\n      /**\n       * The image is visible, and in the process of being deleted.\n       */\n      DELETED,\n      /**\n       * The image is available.\n       */\n      AVAILABLE,\n      /**\n       * There is an error on the image\n       */\n      ERROR,\n      /**\n       * The state of the image is unrecognized.\n       */\n      UNRECOGNIZED;\n\n   }\n   \n   /**\n    * The operating system installed on this image\n    */\n   @Beta\n   OperatingSystem getOperatingSystem();\n\n   /**\n    * Version of the image\n    */\n   String getVersion();\n\n   /**\n    * Description of the image.\n    */\n   @Nullable\n   String getDescription();\n\n   /**\n    * Default credentials for the current image\n    */\n   LoginCredentials getDefaultCredentials();\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/domain/ImageBuilder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.net.URI;\nimport java.util.Map;\n\nimport org.jclouds.compute.domain.Image.Status;\nimport org.jclouds.compute.domain.internal.ImageImpl;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.javax.annotation.Nullable;\n\npublic class ImageBuilder extends ComputeMetadataBuilder {\n   private OperatingSystem operatingSystem;\n   private Status status;\n   private String backendStatus;\n   private String version;\n   private String description;\n   private LoginCredentials defaultLoginCredentials;\n\n   public ImageBuilder() {\n      super(ComputeType.IMAGE);\n   }\n\n   public ImageBuilder operatingSystem(OperatingSystem operatingSystem) {\n      this.operatingSystem = checkNotNull(operatingSystem, \"operatingSystem\");\n      return this;\n   }\n   \n   public ImageBuilder status(Status status) {\n      this.status = checkNotNull(status, \"status\");\n      return this;\n   }\n   \n   public ImageBuilder backendStatus(@Nullable String backendStatus) {\n      this.backendStatus = backendStatus;\n      return this;\n   }\n   \n   public ImageBuilder version(@Nullable String version) {\n      this.version = version;\n      return this;\n   }\n\n   public ImageBuilder description(@Nullable String description) {\n      this.description = description;\n      return this;\n   }\n\n   public ImageBuilder defaultCredentials(@Nullable LoginCredentials defaultLoginCredentials) {\n      this.defaultLoginCredentials = defaultLoginCredentials;\n      return this;\n   }\n\n   @Override\n   public ImageBuilder id(String id) {\n      return ImageBuilder.class.cast(super.id(id));\n   }\n\n   public ImageBuilder tags(Iterable<String> tags) {\n      return ImageBuilder.class.cast(super.tags(tags));\n   }\n\n   @Override\n   public ImageBuilder ids(String id) {\n      return ImageBuilder.class.cast(super.ids(id));\n   }\n\n   @Override\n   public ImageBuilder providerId(String providerId) {\n      return ImageBuilder.class.cast(super.providerId(providerId));\n   }\n\n   @Override\n   public ImageBuilder name(String name) {\n      return ImageBuilder.class.cast(super.name(name));\n   }\n\n   @Override\n   public ImageBuilder location(Location location) {\n      return ImageBuilder.class.cast(super.location(location));\n   }\n\n   @Override\n   public ImageBuilder uri(URI uri) {\n      return ImageBuilder.class.cast(super.uri(uri));\n   }\n\n   @Override\n   public ImageBuilder userMetadata(Map<String, String> userMetadata) {\n      return ImageBuilder.class.cast(super.userMetadata(userMetadata));\n   }\n\n   @Override\n   public Image build() {\n      return new ImageImpl(providerId, name, id, location, uri, userMetadata, tags, operatingSystem, status,\n               backendStatus, description, version, defaultLoginCredentials);\n   }\n\n   public static ImageBuilder fromImage(Image image) {\n      return new ImageBuilder().providerId(image.getProviderId()).name(image.getName()).id(image.getId()).location(\n               image.getLocation()).uri(image.getUri()).userMetadata(image.getUserMetadata()).tags(image.getTags())\n               .version(image.getVersion()).description(image.getDescription()).operatingSystem(\n                        image.getOperatingSystem()).status(image.getStatus()).backendStatus(image.getBackendStatus())\n               .defaultCredentials(image.getDefaultCredentials());\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/domain/ImageTemplate.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.domain;\n\n/**\n * A template for building new {@link Image}s.\n */\npublic interface ImageTemplate {\n\n   /**\n    * @return the name of the new image\n    */\n   String getName();\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/domain/ImageTemplateBuilder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.domain;\n\nimport org.jclouds.compute.domain.internal.ImageTemplateImpl;\n\n/**\n * A builder for {@link ImageTemplate}s. Includes sub-builders to build specific\n * {@link ImageTemplate}s for different purposes, such as cloning, creating from iso, creating from\n * netboot.\n */\npublic abstract class ImageTemplateBuilder {\n\n   String name;\n\n   private ImageTemplateBuilder() {\n   }\n\n   public ImageTemplateBuilder name(String name) {\n      this.name = name;\n      return this;\n   }\n\n   public static class CloneImageTemplateBuilder extends ImageTemplateBuilder {\n\n      String nodeId;\n\n      @Override\n      public CloneImageTemplateBuilder name(String name) {\n         return CloneImageTemplateBuilder.class.cast(super.name(name));\n      }\n\n      public CloneImageTemplateBuilder nodeId(String nodeId) {\n         this.nodeId = nodeId;\n         return this;\n      }\n\n      public CloneImageTemplate build() {\n         return new ImageTemplateImpl.CloneImageTemplateImpl(name, nodeId);\n      }\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/domain/LoginType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.domain;\n\n\n/**\n * The login type of the server.\n * \n */\npublic enum LoginType {\n\n   RDP, SSH\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/domain/NodeMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.domain;\n\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.internal.NodeMetadataImpl;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.inject.ImplementedBy;\n\n@ImplementedBy(NodeMetadataImpl.class)\npublic interface NodeMetadata extends ComputeMetadataIncludingStatus<NodeMetadata.Status> {\n   \n   public static enum Status {\n      /**\n       * The node is in transition\n       */\n      PENDING,\n      /**\n       * The node is visible, and in the process of being deleted.\n       */\n      TERMINATED,\n      /**\n       * The node is deployed, but suspended or stopped.\n       */\n      SUSPENDED,\n      /**\n       * The node is available for requests\n       */\n      RUNNING,\n      /**\n       * There is an error on the node\n       */\n      ERROR,\n      /**\n       * The state of the node is unrecognized.\n       */\n      UNRECOGNIZED;\n\n   }\n   \n   /**\n    * <h4>note</h4> hostname is something that is set in the operating system image, so this value,\n    * if present, cannot be guaranteed on images not directly controlled by the cloud provider.\n    * \n    * @return hostname of the node, or null if unknown\n    * \n    */\n   @Nullable\n   String getHostname();\n\n   /**\n    * Tag used for all resources that belong to the same logical group. run, destroy commands are\n    * scoped to group.\n    * \n    * @return group for this node, or null, if not a part of a group\n    * \n    */\n   @Nullable\n   String getGroup();\n\n   /**\n    * \n    * The hardware this node is running, if possible to determine.\n    */\n   @Nullable\n   Hardware getHardware();\n\n   /**\n    * \n    * The id of the image this node was created from, if possible to correlate.\n    */\n   @Nullable\n   String getImageId();\n\n   /**\n    * \n    * The operating system this node is running, if possible to determine.\n    */\n   @Nullable\n   OperatingSystem getOperatingSystem();\n\n   /**\n    * @return the TCP port used for terminal connections. Generally, this is port 22 for ssh.\n    */\n   int getLoginPort();\n\n   /**\n    * If possible, these are returned upon all detail requests. However, it is often the case that\n    * credentials are only available when a node is initially created.\n    * \n    * @see ComputeServiceContext#credentialStore\n    */\n   @Nullable\n   LoginCredentials getCredentials();\n\n   /**\n    * All public IP addresses, potentially including shared ips.\n    */\n   Set<String> getPublicAddresses();\n\n   /**\n    * All private IP addresses.\n    */\n   Set<String> getPrivateAddresses();\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/domain/NodeMetadataBuilder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.net.URI;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.NodeMetadata.Status;\nimport org.jclouds.compute.domain.internal.NodeMetadataImpl;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Sets;\n\npublic class NodeMetadataBuilder extends ComputeMetadataBuilder {\n   private Status status;\n   private String backendStatus;\n   private Set<String> publicAddresses = Sets.newLinkedHashSet();\n   private Set<String> privateAddresses = Sets.newLinkedHashSet();\n   @Nullable\n   private LoginCredentials credentials;\n   @Nullable\n   private String group;\n   private int loginPort = 22;\n   @Nullable\n   private String imageId;\n   @Nullable\n   private Hardware hardware;\n   @Nullable\n   private OperatingSystem os;\n   @Nullable\n   private String hostname;\n\n   public NodeMetadataBuilder() {\n      super(ComputeType.NODE);\n   }\n\n   public NodeMetadataBuilder loginPort(int loginPort) {\n      this.loginPort = loginPort;\n      return this;\n   }\n  \n   public NodeMetadataBuilder status(Status status) {\n      this.status = checkNotNull(status, \"status\");\n      return this;\n   }\n   \n   public NodeMetadataBuilder backendStatus(@Nullable String backendStatus) {\n      this.backendStatus = backendStatus;\n      return this;\n   }\n\n   public NodeMetadataBuilder publicAddresses(Iterable<String> publicAddresses) {\n      this.publicAddresses = ImmutableSet.copyOf(checkNotNull(publicAddresses, \"publicAddresses\"));\n      return this;\n   }\n\n   public NodeMetadataBuilder privateAddresses(Iterable<String> privateAddresses) {\n      this.privateAddresses = ImmutableSet.copyOf(checkNotNull(privateAddresses, \"privateAddresses\"));\n      return this;\n   }\n\n   public NodeMetadataBuilder credentials(@Nullable LoginCredentials credentials) {\n      this.credentials = credentials;\n      return this;\n   }\n\n   public NodeMetadataBuilder group(@Nullable String group) {\n      this.group = group;\n      return this;\n   }\n\n   public NodeMetadataBuilder imageId(@Nullable String imageId) {\n      this.imageId = imageId;\n      return this;\n   }\n\n   public NodeMetadataBuilder hardware(@Nullable Hardware hardware) {\n      this.hardware = hardware;\n      return this;\n   }\n\n   public NodeMetadataBuilder operatingSystem(@Nullable OperatingSystem os) {\n      this.os = os;\n      return this;\n   }\n\n   public NodeMetadataBuilder hostname(String hostname) {\n      this.hostname = hostname;\n      return this;\n   }\n\n   @Override\n   public NodeMetadataBuilder id(String id) {\n      return NodeMetadataBuilder.class.cast(super.id(id));\n   }\n\n   @Override\n   public NodeMetadataBuilder tags(Iterable<String> tags) {\n      return NodeMetadataBuilder.class.cast(super.tags(tags));\n   }\n\n   @Override\n   public NodeMetadataBuilder ids(String id) {\n      return NodeMetadataBuilder.class.cast(super.ids(id));\n   }\n\n   @Override\n   public NodeMetadataBuilder providerId(String providerId) {\n      return NodeMetadataBuilder.class.cast(super.providerId(providerId));\n   }\n\n   @Override\n   public NodeMetadataBuilder name(String name) {\n      return NodeMetadataBuilder.class.cast(super.name(name));\n   }\n\n   @Override\n   public NodeMetadataBuilder location(Location location) {\n      return NodeMetadataBuilder.class.cast(super.location(location));\n   }\n\n   @Override\n   public NodeMetadataBuilder uri(URI uri) {\n      return NodeMetadataBuilder.class.cast(super.uri(uri));\n   }\n\n   @Override\n   public NodeMetadataBuilder userMetadata(Map<String, String> userMetadata) {\n      return NodeMetadataBuilder.class.cast(super.userMetadata(userMetadata));\n   }\n\n   @Override\n   public NodeMetadata build() {\n      return new NodeMetadataImpl(providerId, name, id, location, uri, userMetadata, tags, group, hardware, imageId,\n               os, status, backendStatus, loginPort, publicAddresses, privateAddresses, credentials, hostname);\n   }\n\n   public static NodeMetadataBuilder fromNodeMetadata(NodeMetadata node) {\n      return new NodeMetadataBuilder().providerId(node.getProviderId()).name(node.getName()).id(node.getId()).location(\n               node.getLocation()).uri(node.getUri()).userMetadata(node.getUserMetadata()).tags(node.getTags()).group(\n               node.getGroup()).hardware(node.getHardware()).imageId(node.getImageId()).operatingSystem(\n               node.getOperatingSystem()).status(node.getStatus()).backendStatus(node.getBackendStatus()).loginPort(\n               node.getLoginPort()).publicAddresses(node.getPublicAddresses()).privateAddresses(\n               node.getPrivateAddresses()).credentials(node.getCredentials()).hostname(node.getHostname());\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/domain/OperatingSystem.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Running Operating system\n */\n@Beta\npublic class OperatingSystem {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n      protected OsFamily family;\n      protected String name;\n      protected String arch;\n      protected String version;\n      protected String description;\n      protected boolean is64Bit;\n\n      public Builder family(@Nullable OsFamily family) {\n         this.family = family;\n         return this;\n      }\n\n      public Builder name(@Nullable String name) {\n         this.name = name;\n         return this;\n      }\n\n      public Builder arch(@Nullable String arch) {\n         this.arch = arch;\n         return this;\n      }\n\n      public Builder version(@Nullable String version) {\n         this.version = version;\n         return this;\n      }\n\n      public Builder description(String description) {\n         this.description = checkNotNull(description, \"description\");\n         return this;\n      }\n\n      public Builder is64Bit(boolean is64Bit) {\n         this.is64Bit = is64Bit;\n         return this;\n      }\n\n      public OperatingSystem build() {\n         return new OperatingSystem(family, name, version, arch, description, is64Bit);\n      }\n\n      public Builder fromOperatingSystem(OperatingSystem in) {\n         return family(in.getFamily()).name(in.getName()).version(in.getVersion()).arch(in.getArch()).description(\n                  in.getDescription()).is64Bit(in.is64Bit());\n      }\n   }\n\n   @Nullable\n   protected OsFamily family;\n   @Nullable\n   protected String name;\n   @Nullable\n   protected String arch;\n   @Nullable\n   protected String version;\n   protected String description;\n   protected boolean is64Bit;\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o)\n         return true;\n      if (o == null || getClass() != o.getClass())\n         return false;\n      OperatingSystem that = OperatingSystem.class.cast(o);\n      return equal(this.family, that.family) && equal(this.name, that.name) && equal(this.arch, that.arch)\n               && equal(this.version, that.version) && equal(this.description, that.description)\n               && equal(this.is64Bit, that.is64Bit);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(family, name, arch, version, description, is64Bit);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(\"\").omitNullValues().add(\"family\", family).add(\"name\", name).add(\"arch\", arch)\n               .add(\"version\", version).add(\"description\", description).add(\"is64Bit\", is64Bit);\n   }\n\n   // for serialization/deserialization\n   protected OperatingSystem() {\n\n   }\n\n   public OperatingSystem(@Nullable OsFamily family, @Nullable String name, @Nullable String version,\n            @Nullable String arch, String description, boolean is64Bit) {\n      this.family = family;\n      this.name = name;\n      this.arch = arch;\n      this.version = version;\n      this.description = checkNotNull(description, \"description\");\n      this.is64Bit = is64Bit;\n   }\n\n   /**\n    * Type of the operating system\n    * <p/>\n    * generally, this is used to compare the means by which you use an operating system. For\n    * example, to determine compatibility of a particular bootstrapping or package installation\n    * approach.\n    */\n   @Nullable\n   public OsFamily getFamily() {\n      return family;\n   }\n\n   /**\n    * name of the operating system; ex. {@code Red Hat Enterprise Linux}\n    * \n    * <h2>note</h2> While this looks similar to, and may in some cases be the same as the java\n    * system property {@code os.name} it isn't guaranteed to match a particular value. For example,\n    * this value could be derived from data parsed for a cloud api or the OVF CIM OSType enum value;\n    * \n    * @return operating system name or null if it couldn't be determined.\n    */\n   @Nullable\n   public String getName() {\n      return name;\n   }\n\n   /**\n    * architecture of the operating system; ex. {@code x86_64}\n    * <p/>\n    * generally, this is used to decide whether an operating system will run certain binaries, for\n    * example, a 64bit JDK.\n    * \n    * <h2>note</h2>\n    * While this looks similar to, and may in some cases be the same as the java system property\n    * {@code os.arch} it isn't guaranteed to match a particular value. For example, this value could\n    * be derived from data parsed for a cloud api or the OVF CIM OSType enum value;\n    * \n    * @return operating system architecture or null if it couldn't be determined.\n    */\n   @Nullable\n   public String getArch() {\n      return arch;\n   }\n\n   /**\n    * version of the operating system; ex. {@code 10.0.4}\n    * <p/>\n    * generally, this is used to compare versions of the same operating system name. It should be\n    * meaningful when sorted against, although this isn't necessary.\n    * <h2>note</h2>\n    * While this looks similar to, and may in some cases be the same as the java system property\n    * {@code os.version} it isn't guaranteed to match a particular value. For example, this value\n    * could be derived from data parsed for a cloud api or the OVF CIM OSType enum value;\n    * \n    * @return operating system version or null if it couldn't be determined.\n    */\n   @Nullable\n   public String getVersion() {\n      return version;\n   }\n\n   /**\n    * description of the operating system; ex. {@code CentOS 32-bit},{@code Other Linux (32-bit)}\n    * <p/>\n    * This is the only required field in the operating system object. In some implementations, it is\n    * this data that is used to parse the value of the {@link #name}, {@link #version}, and\n    * {@link #arch} fields.\n    * \n    * @return operating system description\n    */\n   public String getDescription() {\n      return description;\n   }\n\n   /**\n    * \n    * @return whether this operating system supports 64 bit computation.\n    */\n   public boolean is64Bit() {\n      return is64Bit;\n   }\n\n   public Builder toBuilder() {\n      return builder().fromOperatingSystem(this);\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/domain/OsFamily.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport static com.google.common.base.CaseFormat.LOWER_HYPHEN;\nimport static com.google.common.base.CaseFormat.UPPER_UNDERSCORE;\n\nimport java.util.Arrays;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.FluentIterable;\n\n/**\n * Running Operating system\n */\npublic enum OsFamily {\n   UNRECOGNIZED(false), AIX, ALPINE, ARCH, CENTOS, DARWIN, DEBIAN, ESX, FEDORA, FREEBSD, GENTOO, HPUX, LINUX(false), COREOS,\n   /**\n    * @see <a href=\"http://smartos.org\">SmartOS</a>\n    */\n   SMARTOS,\n   /**\n    * @see <a href=\"http://aws.amazon.com/amazon-linux-ami/\">amazon linux ami</a>\n    */\n   AMZN_LINUX, MANDRIVA, NETBSD,\n   /**\n    * \n    * Oracle Enterprise Linux\n    */\n   OEL, OPENBSD, RHEL,\n   /**\n    * Scientific Linux\n    */\n   SCIENTIFIC,\n   /**\n    * Google Compute Engine Linux\n    */\n   GCEL, SIGAR, SLACKWARE, SOLARIS, SUSE, TURBOLINUX, CLOUD_LINUX, UBUNTU, WINDOWS;\n\n   private final boolean prioritise;\n\n   OsFamily() {\n      this.prioritise = true;\n   }\n\n   OsFamily(boolean prioritise) {\n      this.prioritise = prioritise;\n   }\n\n   public String value() {\n      return UPPER_UNDERSCORE.to(LOWER_HYPHEN, name());\n   }\n\n   @Override\n   public String toString() {\n      return value();\n   }\n\n   public boolean shouldPrioritise() {\n      return prioritise;\n   }\n\n   public static OsFamily fromValue(String osFamily) {\n      try {\n         return valueOf(LOWER_HYPHEN.to(UPPER_UNDERSCORE, checkNotNull(osFamily, \"osFamily\")));\n      } catch (IllegalArgumentException e) {\n         return UNRECOGNIZED;\n      }\n   }\n\n   private static Predicate<OsFamily> predicateOnShouldPrioritise(final boolean prioritise) {\n      return new Predicate<OsFamily>() {\n         @Override\n         public boolean apply(OsFamily osFamily) {\n            return osFamily.shouldPrioritise() == prioritise;\n         }\n      };\n   }\n\n   public static OsFamily[] proritisedValues() {\n      return FluentIterable.from(Arrays.asList(values())).filter(predicateOnShouldPrioritise(true)).toArray(OsFamily.class);\n   }\n\n   public static OsFamily[] nonProritisedValues() {\n      return FluentIterable.from(Arrays.asList(values())).filter(predicateOnShouldPrioritise(false)).toArray(OsFamily.class);\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/domain/OsFamilyVersion64Bit.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.domain;\n\n\npublic class OsFamilyVersion64Bit {\n   public OsFamily family;\n   public String version;\n   public boolean is64Bit;\n\n   // for serialization\n   OsFamilyVersion64Bit() {\n\n   }\n\n   public OsFamilyVersion64Bit(OsFamily family, String version, boolean is64Bit) {\n      this.family = family;\n      this.version = version;\n      this.is64Bit = is64Bit;\n   }\n\n   @Override\n   public String toString() {\n      return \"[family=\" + family + \", version=\" + version + \", is64Bit=\" + is64Bit + \"]\";\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((family == null) ? 0 : family.hashCode());\n      result = prime * result + (is64Bit ? 1231 : 1237);\n      result = prime * result + ((version == null) ? 0 : version.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      OsFamilyVersion64Bit other = (OsFamilyVersion64Bit) obj;\n      if (family != other.family)\n         return false;\n      if (is64Bit != other.is64Bit)\n         return false;\n      if (version == null) {\n         if (other.version != null)\n            return false;\n      } else if (!version.equals(other.version))\n         return false;\n      return true;\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/domain/Processor.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.domain;\n\nimport static com.google.common.base.Objects.equal;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ComparisonChain;\n\n/**\n * Processor (or CPU) as a part of {@link Hardware} of a {@link NodeMetadata}\n */\npublic class Processor implements Comparable<Processor> {\n   private final double cores;\n   private final double speed;\n\n   public Processor(double cores, double speed) {\n      this.cores = cores;\n      this.speed = speed;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public int compareTo(Processor that) {\n      Processor thatProcessor = Processor.class.cast(that);\n      return ComparisonChain.start().compare(this.getCores(), thatProcessor.getCores())\n            .compare(this.getSpeed(), thatProcessor.getSpeed()).result();\n   }\n\n   /**\n    * Amount of virtual or physical cores provided\n    */\n   public double getCores() {\n      return cores;\n   }\n\n   /**\n    * Speed, not necessarily in ghz, but certainly relevant to other processors\n    * in the same provider.\n    */\n   public double getSpeed() {\n      return speed;\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o)\n         return true;\n      if (o == null || getClass() != o.getClass())\n         return false;\n      Processor that = Processor.class.cast(o);\n      return equal(this.cores, that.cores) && equal(this.speed, that.speed);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(cores, speed);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(\"\").omitNullValues().add(\"cores\", cores).add(\"speed\", speed);\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/domain/SecurityGroup.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.net.URI;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.internal.ComputeMetadataImpl;\nimport org.jclouds.domain.Location;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.net.domain.IpPermission;\n\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Describes a security group containing a set of @{link IpPermission}s\n */\npublic class SecurityGroup extends ComputeMetadataImpl {\n\n   private final Set<IpPermission> ipPermissions;\n   private final String ownerId;\n\n   public SecurityGroup(String providerId, String name, String id, @Nullable Location location, URI uri,\n                        Map<String, String> userMetadata, Set<String> tags,\n                        Iterable<IpPermission> ipPermissions,\n                        @Nullable String ownerId) {\n      super(ComputeType.SECURITYGROUP, providerId, name, id, location, uri, userMetadata, tags);\n      this.ipPermissions = ImmutableSet.copyOf(checkNotNull(ipPermissions, \"ipPermissions\"));\n      this.ownerId = ownerId;\n   }\n\n   /**\n    *\n    * @return The set of @{link IpPermission}s for this security group\n    */\n   public Set<IpPermission> getIpPermissions() {\n      return ipPermissions;\n   }\n\n   /**\n    *\n    * @return the owner ID. Can be null.\n    */\n   public String getOwnerId() {\n      return ownerId;\n   }\n\n   @Override\n   protected ToStringHelper string() {\n      ToStringHelper helper = computeToStringPrefix();\n      if (!ipPermissions.isEmpty())\n         helper.add(\"ipPermissions\", ipPermissions);\n      return addComputeToStringSuffix(helper);\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/domain/SecurityGroupBuilder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.net.URI;\nimport java.util.Map;\n\nimport org.jclouds.domain.Location;\nimport org.jclouds.net.domain.IpPermission;\n\nimport com.google.common.collect.ImmutableSet;\n\npublic class SecurityGroupBuilder extends ComputeMetadataBuilder {\n   private ImmutableSet.Builder<IpPermission> ipPermissions = ImmutableSet.<IpPermission> builder();\n   private String ownerId;\n   \n   public SecurityGroupBuilder() {\n      super(ComputeType.SECURITYGROUP);\n   }\n\n   public SecurityGroupBuilder ipPermissions() {\n      this.ipPermissions = ImmutableSet.<IpPermission> builder();\n      return this;\n   }\n\n   public SecurityGroupBuilder ipPermissions(Iterable<IpPermission> ipPermissions) {\n      this.ipPermissions.addAll(checkNotNull(ipPermissions, \"ipPermissions\"));\n      return this;\n   }\n\n   public SecurityGroupBuilder ipPermission(IpPermission ipPermission) {\n      this.ipPermissions.add(checkNotNull(ipPermission, \"ipPermission\"));\n      return this;\n   }\n\n   public SecurityGroupBuilder ownerId(String ownerId) {\n      this.ownerId = ownerId;\n      return this;\n   }\n\n   @Override\n   public SecurityGroupBuilder id(String id) {\n      return SecurityGroupBuilder.class.cast(super.id(id));\n   }\n\n   @Override\n   public SecurityGroupBuilder tags(Iterable<String> tags) {\n      return SecurityGroupBuilder.class.cast(super.tags(tags));\n   }\n\n   @Override\n   public SecurityGroupBuilder ids(String id) {\n      return SecurityGroupBuilder.class.cast(super.ids(id));\n   }\n\n   @Override\n   public SecurityGroupBuilder providerId(String providerId) {\n      return SecurityGroupBuilder.class.cast(super.providerId(providerId));\n   }\n\n   @Override\n   public SecurityGroupBuilder name(String name) {\n      return SecurityGroupBuilder.class.cast(super.name(name));\n   }\n\n   @Override\n   public SecurityGroupBuilder location(Location location) {\n      return SecurityGroupBuilder.class.cast(super.location(location));\n   }\n\n   @Override\n   public SecurityGroupBuilder uri(URI uri) {\n      return SecurityGroupBuilder.class.cast(super.uri(uri));\n   }\n\n   @Override\n   public SecurityGroupBuilder userMetadata(Map<String, String> userMetadata) {\n      return SecurityGroupBuilder.class.cast(super.userMetadata(userMetadata));\n   }\n\n   @Override\n   public SecurityGroup build() {\n      return new SecurityGroup(providerId, name, id, location, uri, userMetadata, tags,\n                               ipPermissions.build(), ownerId);\n   }\n\n   public static SecurityGroupBuilder fromSecurityGroup(SecurityGroup group) {\n      return new SecurityGroupBuilder().providerId(group.getProviderId())\n         .name(group.getName())\n         .id(group.getId())\n         .location(group.getLocation())\n         .uri(group.getUri())\n         .userMetadata(group.getUserMetadata())\n         .tags(group.getTags())\n         .ipPermissions(group.getIpPermissions())\n         .ownerId(group.getOwnerId());\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/domain/Template.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.domain;\n\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.domain.Location;\n\n/**\n * Configured operating system used to start nodes.\n */\npublic interface Template extends Cloneable {\n   /**\n    * Image that suits the requirements.\n    * \n    */\n   Image getImage();\n\n   /**\n    * Size that suits the requirements.\n    */\n   Hardware getHardware();\n\n   /**\n    * Location of the nodes.\n    */\n   Location getLocation();\n\n   /**\n    * options for launching this template, like run scripts or inbound ports\n    */\n   TemplateOptions getOptions();\n   \n   /**\n    * clone this template\n    * \n    * @see Object#clone\n    */\n   Template clone();\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/domain/TemplateBuilder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.domain;\n\n\nimport org.jclouds.compute.domain.internal.TemplateBuilderImpl;\nimport org.jclouds.compute.options.TemplateOptions;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.inject.ImplementedBy;\n\n/**\n * Creates a customized template based on requirements.\n */\n@ImplementedBy(TemplateBuilderImpl.class)\npublic interface TemplateBuilder {\n\n   /**\n    * prime this builder with parameters known to work on the current compute provider.\n    */\n   TemplateBuilder any();\n\n   /**\n    * Configure this template to require the minimum hardware of the parameter.\n    */\n   TemplateBuilder fromHardware(Hardware hardware);\n\n   /**\n    * Configure this template to fuzzy-match on the image parameter\n    */\n   TemplateBuilder fromImage(Image image);\n\n   /**\n    * Configure this template to match the resources of the template parameter.\n    */\n   TemplateBuilder fromTemplate(Template image);\n\n   /**\n    * Configure and return this template, updating it with the populated values of the given {@code spec}.\n    *\n    * @since 1.5\n    */\n   TemplateBuilder from(TemplateBuilderSpec spec);\n   \n   /**\n    * Configure and return this template, updating it with the populated values of the given {@code spec}.\n    * This is especially useful for command-line configuration of a {@code TemplateBuilder}.\n    *\n    * @param spec a String in the format specified by {@link TemplateBuilderSpec}\n    * @since 1.5\n    */\n   TemplateBuilder from(String spec);\n   \n   /**\n    * configure this template to the smallest hardware, based on cores, ram, then disk\n    */\n   TemplateBuilder smallest();\n\n   /**\n    * configure this template to the fastest hardware, based on cpu\n    */\n   TemplateBuilder fastest();\n\n   /**\n    * configure this template to the largest hardware, based on cores, ram, then disk\n    */\n   TemplateBuilder biggest();\n   \n   /**\n    * Configure this template to have an hypervisor that matches the regular expression\n    */\n   TemplateBuilder hypervisorMatches(String hypervisorRegex);\n\n   /**\n    * Configure this template to use a specific operating system image.\n    */\n   TemplateBuilder osFamily(OsFamily os);\n\n   /**\n    * Configure this template to start in a specific location\n    * \n    * @throws NoSuchElementException\n    *            if no location matches the id specified\n    */\n   TemplateBuilder locationId(String locationId);\n\n   /**\n    * Configure this template to require a specific imageId.\n    * <p/>\n    * Note that image Ids are often scoped to {@code location}\n    */\n   TemplateBuilder imageId(String imageId);\n\n   /**\n    * Configure this template to require a specific hardwareId.\n    */\n   TemplateBuilder hardwareId(String hardwareId);\n\n   /**\n    * Configure this template to have an operating system name that matches the regular expression\n    */\n   TemplateBuilder osNameMatches(String osNameRegex);\n\n   /**\n    * Configure this template to have an operating system description that matches the regular\n    * expression\n    */\n   TemplateBuilder osDescriptionMatches(String osDescriptionRegex);\n\n   /**\n    * Configure this template to have an os version that matches the regular expression\n    */\n   TemplateBuilder osVersionMatches(String osVersionRegex);\n\n   /**\n    * Configure this template to require a specific architecture. ex. virtualizationType or\n    * \n    */\n   TemplateBuilder osArchMatches(String architecture);\n\n   /**\n    * Configure this template to require a 64 bit operating system.\n    */\n   TemplateBuilder os64Bit(boolean is64bit);\n\n   /**\n    * Configure this template to have an image name that matches the regular expression\n    */\n   TemplateBuilder imageNameMatches(String imageNameRegex);\n\n   /**\n    * Configure this template to have an image version that matches the regular expression\n    */\n   TemplateBuilder imageVersionMatches(String imageVersionRegex);\n\n   /**\n    * Configure this template to have an image description that matches the regular expression\n    */\n   TemplateBuilder imageDescriptionMatches(String imageDescriptionRegex);\n\n   /**\n    * Configure this template to have an image that matches the supplied condition\n    * \n    * ex. \n    * \n    * <pre>\n    * builder.imageMatches(ImagePredicates.userMetadataContains(\"author\", \"sue\"));\n    * </pre>\n    */\n   TemplateBuilder imageMatches(Predicate<Image> condition);\n\n   /**\n    * Configure this template with a specific preference function which operates on\n    * images which match the other criteria.\n    * <p>\n    * If no function is supplied, jclouds will select one according to an internal strategy.\n    * This strategy may change from version to version.\n    */\n   TemplateBuilder imageChooser(Function<Iterable<? extends Image>, Image> imageChooser);\n\n   /**\n    * Configure this template to require the minimum cores below\n    */\n   TemplateBuilder minCores(double minCores);\n\n   /**\n    * Configure this template to require the minimum ram in megabytes below\n    */\n   TemplateBuilder minRam(int megabytes);\n\n   /**\n    * Configure this template with required minimum disk space in gigabytes\n    */\n   TemplateBuilder minDisk(double gigabytes);\n\n   /**\n    * Generate an immutable template from the current builder.\n    */\n   Template build();\n\n   /**\n    * Sets options on the template (i.e. items which adorn a created node rather than restricting selection of the node).\n    * Note that this method typically replaces any options previously specified in the builder.\n    * Normal usage is to build up all options and pass them to the builder with a single call to this method.\n    */\n   TemplateBuilder options(TemplateOptions options);\n   \n   /**\n    * Forces an image lookup against the provider to reload the image cache.\n    * <p>\n    * Use with caution. In some providers getting the list of images is an\n    * expensive operation, and the use of the image cache is recommended. If\n    * there is a need to minimize the amount of time the images are cached,\n    * consider configuring the cache expiration time by setting the\n    * {@link org.jclouds.Constants#PROPERTY_SESSION_INTERVAL} property.\n    * \n    * @since 2.0\n    */\n   @Beta\n   TemplateBuilder forceCacheReload();\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/domain/TemplateBuilderSpec.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkArgument;\n\nimport java.util.List;\n\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.domain.LoginCredentials.Builder;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Objects;\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * A specification of a {@link TemplateBuilder} configuration.\n * \n * <p>\n * {@code TemplateBuilderSpec} supports parsing configuration off of a string,\n * which makes it especially useful for command-line configuration of a\n * {@code TemplateBuilder}.\n * \n * <p>\n * The string syntax is a series of comma-separated keys or key-value pairs,\n * each corresponding to a {@code TemplateBuilder} method.\n * <ul>\n * <li>{@code hardwareId=[String]}: sets {@link TemplateBuilder#hardwareId}.\n * <li>{@code minCores=[double]}: sets {@link TemplateBuilder#minCores}.\n * <li>{@code minRam=[integer]}: sets {@link TemplateBuilder#minRam}.\n * <li>{@code hypervisorMatches=[String]}: sets\n * {@link TemplateBuilder#hypervisorMatches}.\n * <li>{@code imageId=[String]}: sets {@link TemplateBuilder#imageId}.\n * <li>{@code imageNameMatches=[String]}: sets\n * {@link TemplateBuilder#imageNameMatches}.\n * <li>{@code osFamily=[OsFamily]}: sets {@link TemplateBuilder#osFamily}.\n * <li>{@code osVersionMatches=[String]}: sets\n * {@link TemplateBuilder#osVersionMatches}.\n * <li>{@code os64Bit=[boolean]}: sets {@link TemplateBuilder#os64Bit}.\n * <li>{@code osArchMatches=[String]}: sets\n * {@link TemplateBuilder#osArchMatches}.\n * <li>{@code osDescriptionMatches=[String]}: sets\n * {@link TemplateBuilder#osDescriptionMatches}.\n * <li>{@code loginUser=[String]}: sets\n * {@link TemplateOptions#overrideLoginCredentials} parsing password, if colon\n * delimited.\n * <li>{@code authenticateSudo=[Boolean]}: sets\n * {@link TemplateOptions#overrideLoginCredentials}, but only if\n * {@code loginUser} is set.\n * <li>{@code locationId=[String]}: sets {@link TemplateBuilder#locationId}.\n * </ul>\n * \n * The set of supported keys will grow as {@code TemplateBuilder} evolves, but\n * existing keys will never be removed.\n * \n * <p>\n * Whitespace before and after commas and equal signs is ignored. Keys may not\n * be repeated.\n * \n * <p>\n * It is also illegal to use the following combination of keys\n * <ul>\n * <li>{@code hardwareId} and any of\n * <ul>\n * <li>{@code minCores}\n * <li>{@code minRam}\n * <li>{@code hypervisorMatches}\n * </ul>\n * <li>{@code imageId} and any of\n * <ul>\n * <li>{@code imageNameMatches}\n * <li>{@code osFamily}\n * <li>{@code osVersionMatches}\n * <li>{@code os64Bit}\n * <li>{@code osArchMatches}\n * <li>{@code osDescriptionMatches}\n * </ul>\n * </ul>\n * \n * <p>\n * {@code TemplateBuilderSpec} does not support configuring\n * {@code TemplateBuilder} methods with non-value parameters. These must be\n * configured in code.\n * \n * <p>\n * A new {@code TemplateBuilder} can be instantiated from a\n * {@code TemplateBuilderSpec} using\n * {@link TemplateBuilder#from(TemplateBuilderSpec)} or\n * {@link TemplateBuilder#from(String)}.\n * \n * <p>\n * Design inspired by {@link CacheBuilderSpec}\n * \n * @since 1.5\n */\n@Beta\npublic class TemplateBuilderSpec {\n\n   /** Parses a single value. */\n   protected interface ValueParser {\n      void parse(TemplateBuilderSpec spec, String key, @Nullable String value);\n   }\n\n   /** Splits each key-value pair. */\n   protected static final Splitter KEYS_SPLITTER = Splitter.on(',').trimResults();\n\n   /** Splits the key from the value. */\n   protected static final Splitter KEY_VALUE_SPLITTER = Splitter.on('=').trimResults();\n\n   /** Map of names to ValueParser. */\n   protected static final ImmutableMap<String, ValueParser> VALUE_PARSERS = ImmutableMap.<String, ValueParser> builder()\n         .put(\"hardwareId\", new HardwareIdParser())\n         .put(\"minCores\", new MinCoresParser())\n         .put(\"minRam\", new MinRamParser())\n         .put(\"minDisk\", new MinDiskParser())\n         .put(\"hypervisorMatches\", new HypervisorMatchesMatchesParser())\n         .put(\"imageId\", new ImageIdParser())\n         .put(\"imageNameMatches\", new ImageNameMatchesParser())\n         .put(\"osFamily\", new OsFamilyParser())\n         .put(\"osVersionMatches\", new OsVersionMatchesParser())\n         .put(\"os64Bit\", new Os64BitParser())\n         .put(\"osArchMatches\", new OsArchMatchesParser())\n         .put(\"osDescriptionMatches\", new OsDescriptionMatchesParser())\n         .put(\"loginUser\", new LoginUserParser())\n         .put(\"authenticateSudo\", new AuthenticateSudoParser())\n         .put(\"locationId\", new LocationIdParser())\n         .put(\"forceCacheReload\", new ForceCacheReloadParser())\n         .build();\n\n   @VisibleForTesting\n   String hardwareId;\n   @VisibleForTesting\n   Double minCores;\n   @VisibleForTesting\n   Integer minRam;\n   @VisibleForTesting\n   Double minDisk;\n   @VisibleForTesting\n   String hypervisorMatches;\n   @VisibleForTesting\n   String imageId;\n   @VisibleForTesting\n   String imageNameMatches;\n   @VisibleForTesting\n   OsFamily osFamily;\n   @VisibleForTesting\n   String osVersionMatches;\n   @VisibleForTesting\n   Boolean os64Bit;\n   @VisibleForTesting\n   String osArchMatches;\n   @VisibleForTesting\n   String osDescriptionMatches;\n   @VisibleForTesting\n   String loginUser;\n   @VisibleForTesting\n   Boolean authenticateSudo;\n   @VisibleForTesting\n   String locationId;\n   @VisibleForTesting\n   Boolean forceCacheReload;\n   \n   /** Specification; used for toParseableString(). */\n   // transient in case people using serializers don't want this to show up\n   protected transient String specification;\n   \n   protected TemplateBuilderSpec() {\n      // we want serializers like Gson to work w/o using sun.misc.Unsafe,\n      // prohibited in GAE. This also implies fields are not final.\n      // see http://code.google.com/p/jclouds/issues/detail?spec=925\n   }\n\n   protected TemplateBuilderSpec(String specification) {\n      this.specification = specification;\n   }\n\n   /**\n    * Creates a TemplateBuilderSpec from a string.\n    * \n    * @param templateBuilderSpecification\n    *           the string form\n    */\n   public static TemplateBuilderSpec parse(String templateBuilderSpecification) {\n      TemplateBuilderSpec spec = new TemplateBuilderSpec(templateBuilderSpecification);\n      if (!templateBuilderSpecification.isEmpty()) {\n         for (String keyValuePair : KEYS_SPLITTER.split(templateBuilderSpecification)) {\n            List<String> keyAndValue = ImmutableList.copyOf(KEY_VALUE_SPLITTER.split(keyValuePair));\n            checkArgument(!keyAndValue.isEmpty(), \"blank key-value pair\");\n            checkArgument(keyAndValue.size() <= 2, \"key-value pair %s with more than one equals sign\", keyValuePair);\n\n            // Find the ValueParser for the current key.\n            String key = keyAndValue.get(0);\n            ValueParser valueParser = VALUE_PARSERS.get(key);\n            checkArgument(valueParser != null, \"unknown key %s\", key);\n\n            String value = keyAndValue.size() == 1 ? null : keyAndValue.get(1);\n            valueParser.parse(spec, key, value);\n         }\n      }\n\n      return spec;\n   }\n\n   /**\n    * Returns a TemplateBuilder configured according to this instance's\n    * specification.\n    * @param templateOptions \n    */\n   public TemplateBuilder copyTo(TemplateBuilder builder, TemplateOptions templateOptions) {\n      if (hardwareId != null) {\n         builder.hardwareId(hardwareId);\n      }\n      if (minCores != null) {\n         builder.minCores(minCores);\n      }\n      if (minRam != null) {\n         builder.minRam(minRam);\n      }\n      if (minDisk != null) {\n         builder.minDisk(minDisk);\n      }\n      if (hypervisorMatches != null) {\n         builder.hypervisorMatches(hypervisorMatches);\n      }\n      if (imageId != null) {\n         builder.imageId(imageId);\n      }\n      if (imageNameMatches != null) {\n         builder.imageNameMatches(imageNameMatches);\n      }\n      if (osFamily != null) {\n         builder.osFamily(osFamily);\n      }\n      if (osVersionMatches != null) {\n         builder.osVersionMatches(osVersionMatches);\n      }\n      if (os64Bit != null) {\n         builder.os64Bit(os64Bit);\n      }\n      if (osArchMatches != null) {\n         builder.osArchMatches(osArchMatches);\n      }\n      if (osDescriptionMatches != null) {\n         builder.osDescriptionMatches(osDescriptionMatches);\n      }\n      if (loginUser != null) {\n         Builder loginBuilder = LoginCredentials.builder();\n\n         int pos = loginUser.indexOf(':');\n         if (pos != -1) {\n            loginBuilder.user(loginUser.substring(0, pos)).password(loginUser.substring(pos + 1));\n         } else\n            loginBuilder.user(loginUser);\n\n         if (authenticateSudo != null) {\n            loginBuilder.authenticateSudo(authenticateSudo);\n         }\n         LoginCredentials creds = loginBuilder.build();\n         templateOptions.overrideLoginCredentials(creds);\n      }\n      if (locationId != null) {\n         builder.locationId(locationId);\n      }\n      if (forceCacheReload != null && forceCacheReload) {\n         builder.forceCacheReload();\n      }\n      return builder;\n   }\n\n   /**\n    * Returns a string that can be used to parse an equivalent\n    * {@code TemplateBuilderSpec}. The order and form of this representation is\n    * not guaranteed, except that reparsing its output will produce a\n    * {@code TemplateBuilderSpec} equal to this instance.\n    */\n   public String toParsableString() {\n      return specification;\n   }\n\n   /**\n    * Returns a string representation for this TemplateBuilderSpec instance. The\n    * form of this representation is not guaranteed.\n    */\n   @Override\n   public String toString() {\n      return toStringHelper(this).addValue(toParsableString()).toString();\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(hardwareId, minCores, minRam, hypervisorMatches, imageId, imageNameMatches, osFamily,\n            osVersionMatches, os64Bit, osArchMatches, osDescriptionMatches, loginUser, authenticateSudo, locationId,\n            forceCacheReload);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) {\n         return true;\n      }\n      if (!(obj instanceof TemplateBuilderSpec)) {\n         return false;\n      }\n      TemplateBuilderSpec that = (TemplateBuilderSpec) obj;\n      return equal(hardwareId, that.hardwareId) && equal(minCores, that.minCores) && equal(minRam, that.minRam)\n            && equal(hypervisorMatches, that.hypervisorMatches) && equal(imageId, that.imageId)\n            && equal(imageNameMatches, that.imageNameMatches) && equal(osFamily, that.osFamily)\n            && equal(osVersionMatches, that.osVersionMatches) && equal(os64Bit, that.os64Bit)\n            && equal(osArchMatches, that.osArchMatches) && equal(osDescriptionMatches, that.osDescriptionMatches)\n            && equal(loginUser, that.loginUser) && equal(authenticateSudo, that.authenticateSudo)\n            && equal(locationId, that.locationId) && equal(forceCacheReload, that.forceCacheReload);\n   }\n   \n   /** Base class for parsing doubles. */\n   abstract static class DoubleParser implements ValueParser {\n      protected abstract void parseDouble(TemplateBuilderSpec spec, double value);\n\n      @Override\n      public void parse(TemplateBuilderSpec spec, String key, String value) {\n         checkArgument(value != null && !value.isEmpty(), \"value of key %s omitted\", key);\n         try {\n            parseDouble(spec, Double.parseDouble(value));\n         } catch (NumberFormatException e) {\n            throw new IllegalArgumentException(String.format(\"key %s value set to %s, must be double\", key, value), e);\n         }\n      }\n   }\n\n   /** Base class for parsing ints. */\n   abstract static class IntegerParser implements ValueParser {\n      protected abstract void parseInteger(TemplateBuilderSpec spec, int value);\n\n      @Override\n      public void parse(TemplateBuilderSpec spec, String key, String value) {\n         checkArgument(value != null && !value.isEmpty(), \"value of key %s omitted\", key);\n         try {\n            parseInteger(spec, Integer.parseInt(value));\n         } catch (NumberFormatException e) {\n            throw new IllegalArgumentException(String.format(\"key %s value set to %s, must be integer\", key, value), e);\n         }\n      }\n   }\n\n   /** Base class for parsing enums. */\n   abstract static class EnumParser<E extends Enum<E>> implements ValueParser {\n      private final Class<E> type;\n\n      protected EnumParser(Class<E> type) {\n         this.type = type;\n      }\n\n      protected abstract void parseEnum(TemplateBuilderSpec spec, E value);\n\n      @Override\n      public void parse(TemplateBuilderSpec spec, String key, String value) {\n         checkArgument(value != null && !value.isEmpty(), \"value of key %s omitted\", key);\n         try {\n            parseEnum(spec, Enum.valueOf(type, value));\n         } catch (IllegalArgumentException e) {\n            throw new IllegalArgumentException(String.format(\"key %s value set to %s, must be a name in enum %s\", key,\n                  value, type), e);\n         }\n      }\n   }\n\n   /** Base class for parsing strings. */\n   abstract static class StringParser implements ValueParser {\n      protected abstract void set(TemplateBuilderSpec spec, String value);\n\n      @Override\n      public void parse(TemplateBuilderSpec spec, String key, String value) {\n         checkArgument(value != null && !value.isEmpty(), \"value of key %s omitted\", key);\n         set(spec, value);\n      }\n   }\n   \n   /** Base class for parsing booleans. */\n   abstract static class BooleanParser implements ValueParser {\n      protected abstract void parseBoolean(TemplateBuilderSpec spec, boolean value);\n\n      @Override\n      public void parse(TemplateBuilderSpec spec, String key, String value) {\n         checkArgument(value != null && !value.isEmpty(), \"value of key %s omitted\", key);\n         try {\n            parseBoolean(spec, Boolean.parseBoolean(value));\n         } catch (NumberFormatException e) {\n            throw new IllegalArgumentException(String.format(\"key %s value set to %s, must be booleans\", key, value), e);\n         }\n      }\n   }\n\n   /** Parse hardwareId */\n   static class HardwareIdParser extends StringParser {\n      @Override\n      protected void set(TemplateBuilderSpec spec, String value) {\n         checkArgument(spec.hardwareId == null, \"hardware id was already set to \", spec.hardwareId);\n         checkArgument(spec.minCores == null, \"min cores was already set to \", spec.minCores);\n         checkArgument(spec.minRam == null, \"min ram was already set to \", spec.minRam);\n         checkArgument(spec.hypervisorMatches == null, \"hypervisor matches was already set to \", spec.hypervisorMatches);\n         spec.hardwareId = value;\n      }\n   }\n   \n   /** Parse minCores */\n   static class MinCoresParser extends DoubleParser {\n      @Override\n      protected void parseDouble(TemplateBuilderSpec spec, double value) {\n         checkArgument(spec.minCores == null, \"min cores was already set to \", spec.minCores);\n         checkArgument(spec.hardwareId == null, \"hardware id was already set to \", spec.hardwareId);\n         spec.minCores = value;\n      }\n   }\n\n   /** Parse minRam */\n   static class MinRamParser extends IntegerParser {\n      @Override\n      protected void parseInteger(TemplateBuilderSpec spec, int value) {\n         checkArgument(spec.minRam == null, \"min ram was already set to \", spec.minRam);\n         checkArgument(spec.hardwareId == null, \"hardware id was already set to \", spec.hardwareId);\n         spec.minRam = value;\n      }\n   }\n\n   /** Parse minDisk */\n   static class MinDiskParser extends DoubleParser {\n      @Override\n      protected void parseDouble(TemplateBuilderSpec spec, double value) {\n         checkArgument(spec.minDisk == null, \"min disk was already set to \", spec.minDisk);\n         checkArgument(spec.hardwareId == null, \"hardware id was already set to \", spec.hardwareId);\n         spec.minDisk = value;\n      }\n   }\n   \n   /** Parse hypervisorMatches */\n   static class HypervisorMatchesMatchesParser extends StringParser {\n      @Override\n      protected void set(TemplateBuilderSpec spec, String value) {\n         checkArgument(spec.hypervisorMatches == null, \"hypervisor matches was already set to \", spec.hypervisorMatches);\n         checkArgument(spec.hardwareId == null, \"hardware id was already set to \", spec.hardwareId);\n         spec.hypervisorMatches = value;\n      }\n   }\n\n   /** Parse imageId */\n   static class ImageIdParser extends StringParser {\n      @Override\n      protected void set(TemplateBuilderSpec spec, String value) {\n         checkArgument(spec.imageId == null, \"image id was already set to \", spec.imageId);\n         checkArgument(spec.imageNameMatches == null, \"image name matches was already set to \", spec.imageNameMatches);\n         checkArgument(spec.osFamily == null, \"operating system family was already set to \", spec.osFamily);\n         checkArgument(spec.osVersionMatches == null, \"os version matches was already set to \", spec.osVersionMatches);\n         checkArgument(spec.os64Bit == null, \"os 64 bit was already set to \", spec.os64Bit);\n         checkArgument(spec.osArchMatches == null, \"os arch matches was already set to \", spec.osArchMatches);\n         checkArgument(spec.osDescriptionMatches == null, \"os description matches was already set to \", spec.osDescriptionMatches);\n         spec.imageId = value;\n      }\n   }\n\n   /** Parse imageNameMatches */\n   static class ImageNameMatchesParser extends StringParser {\n      @Override\n      protected void set(TemplateBuilderSpec spec, String value) {\n         checkArgument(spec.imageNameMatches == null, \"image name matches was already set to \", spec.imageNameMatches);\n         checkArgument(spec.imageId == null, \"image id was already set to \", spec.imageId);\n         spec.imageNameMatches = value;\n      }\n   }\n   \n   /** Parse osFamily */\n   static class OsFamilyParser extends EnumParser<OsFamily> {\n\n      protected OsFamilyParser() {\n         super(OsFamily.class);\n      }\n\n      @Override\n      protected void parseEnum(TemplateBuilderSpec spec, OsFamily value) {\n         checkArgument(spec.osFamily == null, \"operating system family was already set to \", spec.osFamily);\n         checkArgument(spec.imageId == null, \"image id was already set to \", spec.imageId);\n         spec.osFamily = value;\n      }\n   }\n\n   /** Parse osVersionMatches */\n   static class OsVersionMatchesParser extends StringParser {\n      @Override\n      protected void set(TemplateBuilderSpec spec, String value) {\n         checkArgument(spec.osVersionMatches == null, \"os version matches was already set to \", spec.osVersionMatches);\n         checkArgument(spec.imageId == null, \"image id was already set to \", spec.imageId);\n         spec.osVersionMatches = value;\n      }\n   }\n   \n   /** Parse os64Bit */\n   static class Os64BitParser extends BooleanParser {\n      @Override\n      protected void parseBoolean(TemplateBuilderSpec spec, boolean value) {\n         checkArgument(spec.os64Bit == null, \"os 64 bit was already set to \", spec.os64Bit);\n         checkArgument(spec.imageId == null, \"image id was already set to \", spec.imageId);\n         spec.os64Bit = value;\n      }\n   }\n\n   /** Parse osArchMatches */\n   static class OsArchMatchesParser extends StringParser {\n      @Override\n      protected void set(TemplateBuilderSpec spec, String value) {\n         checkArgument(spec.osArchMatches == null, \"os arch matches was already set to \", spec.osArchMatches);\n         checkArgument(spec.imageId == null, \"image id was already set to \", spec.imageId);\n         spec.osArchMatches = value;\n      }\n   }\n\n   /** Parse osDescriptionMatches */\n   static class OsDescriptionMatchesParser extends StringParser {\n      @Override\n      protected void set(TemplateBuilderSpec spec, String value) {\n         checkArgument(spec.osDescriptionMatches == null, \"os description matches was already set to \", spec.osDescriptionMatches);\n         checkArgument(spec.imageId == null, \"image id was already set to \", spec.imageId);\n         spec.osDescriptionMatches = value;\n      }\n   }\n   \n   /** Parse loginUser */\n   static class LoginUserParser extends StringParser {\n      @Override\n      protected void set(TemplateBuilderSpec spec, String value) {\n         checkArgument(spec.loginUser == null, \"login user was already set to \", spec.loginUser);\n         spec.loginUser = value;\n      }\n   }\n   \n   /** Parse authenticateSudo */\n   static class AuthenticateSudoParser extends BooleanParser {\n      @Override\n      protected void parseBoolean(TemplateBuilderSpec spec, boolean value) {\n         checkArgument(spec.loginUser != null, \"login user must be set to use authenticateSudo\");\n         checkArgument(spec.authenticateSudo == null, \"authenticate sudo was already set to \", spec.authenticateSudo);\n         spec.authenticateSudo = value;\n      }\n   }\n\n   /** Parse locationId */\n   static class LocationIdParser extends StringParser {\n      @Override\n      protected void set(TemplateBuilderSpec spec, String value) {\n         checkArgument(spec.locationId == null, \"location id was already set to \", spec.locationId);\n         spec.locationId = value;\n      }\n   }\n   \n   /** Parse forceCacheReload */\n   static class ForceCacheReloadParser extends BooleanParser {\n      @Override\n      protected void parseBoolean(TemplateBuilderSpec spec, boolean value) {\n         checkArgument(spec.forceCacheReload == null, \"forceCacheReload was already set to \", spec.forceCacheReload);\n         spec.forceCacheReload = value;\n      }\n   }\n   \n   public String getHardwareId() {\n      return hardwareId;\n   }\n\n   public Double getMinCores() {\n      return minCores;\n   }\n\n   public Integer getMinRam() {\n      return minRam;\n   }\n\n   public String getHypervisorMatches() {\n      return hypervisorMatches;\n   }\n\n   public String getImageId() {\n      return imageId;\n   }\n\n   public String getImageNameMatches() {\n      return imageNameMatches;\n   }\n\n   public OsFamily getOsFamily() {\n      return osFamily;\n   }\n\n   public String getOsVersionMatches() {\n      return osVersionMatches;\n   }\n\n   public Boolean getOs64Bit() {\n      return os64Bit;\n   }\n\n   public String getOsArchMatches() {\n      return osArchMatches;\n   }\n\n   public String getOsDescriptionMatches() {\n      return osDescriptionMatches;\n   }\n\n   public String getLoginUser() {\n      return loginUser;\n   }\n\n   public Boolean getAuthenticateSudo() {\n      return authenticateSudo;\n   }\n\n   public String getLocationId() {\n      return locationId;\n   }\n\n   public String getSpecification() {\n      return specification;\n   }\n\n   public Boolean getForceCacheReload() {\n      return forceCacheReload;\n   }\n   \n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/domain/Volume.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.domain;\n\nimport org.jclouds.compute.domain.internal.VolumeImpl;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.inject.ImplementedBy;\n\n/**\n * Describes what appears as a disk to an {@link OperatingSystem}\n */\n@ImplementedBy(VolumeImpl.class)\npublic interface Volume {\n\n   /**\n    * Describes the cardinal type of a volume; used to determine scope and exclusivity.\n    */\n   public enum Type {\n      /**\n       * scoped to a node cannot be remounted onto another node.\n       */\n      LOCAL,\n\n      /**\n       * shared mount, non-exclusive by nature, although may happen to be exclusive.\n       */\n      NAS,\n      /**\n       * network storage; exclusive by nature, remountable onto other machines.\n       */\n      SAN;\n   }\n\n   /**\n    * Unique identifier. If set, can be used to reference the volume for reorganizing within\n    * {@link Hardware} or external commands such as backups.\n    * \n    */\n   @Nullable\n   String getId();\n\n   /**\n    * Describes the cardinal type of a volume; used to determine scope and exclusivity.\n    */\n   Type getType();\n\n   /**\n    * @return capacity in gigabytes, if available\n    * \n    */\n   @Nullable\n   Float getSize();\n\n   /**\n    * \n    * @return device this volume relates to on an operating system, if available\n    */\n   @Nullable\n   String getDevice();\n\n   /**\n    * \n    * @return true if this survives restarts\n    */\n   boolean isDurable();\n\n   /**\n    * \n    * @return true if this is the boot device\n    */\n   boolean isBootDevice();\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/domain/VolumeBuilder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.compute.domain.internal.VolumeImpl;\nimport org.jclouds.javax.annotation.Nullable;\n\npublic class VolumeBuilder {\n\n   private Volume.Type type;\n   @Nullable\n   private String id;\n   @Nullable\n   private Float size;\n   @Nullable\n   private String device;\n   private boolean bootDevice;\n   private boolean durable;\n\n   public VolumeBuilder type(Volume.Type type) {\n      this.type = checkNotNull(type, \"type\");\n      return this;\n   }\n\n   public VolumeBuilder id(String id) {\n      this.id = id;\n      return this;\n   }\n\n   public VolumeBuilder size(@Nullable Float size) {\n      this.size = size;\n      return this;\n   }\n\n   public VolumeBuilder device(@Nullable String device) {\n      this.device = device;\n      return this;\n   }\n\n   public VolumeBuilder bootDevice(boolean bootDevice) {\n      this.bootDevice = bootDevice;\n      return this;\n   }\n\n   public VolumeBuilder durable(boolean durable) {\n      this.durable = durable;\n      return this;\n   }\n\n   public Volume build() {\n      return new VolumeImpl(id, type, size, device, bootDevice, durable);\n   }\n\n   public static Volume fromVolume(Volume in) {\n      return new VolumeImpl(in.getId(), in.getType(), in.getSize(), in.getDevice(), in.isBootDevice(), in.isDurable());\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/domain/internal/ArbitraryCpuRamTemplateBuilderImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.domain.internal;\n\nimport com.google.common.base.Optional;\nimport com.google.common.base.Supplier;\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.HardwareBuilder;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.Processor;\nimport org.jclouds.compute.domain.TemplateBuilder;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.compute.util.AutomaticHardwareIdSpec;\nimport org.jclouds.domain.Location;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Provider;\nimport java.util.NoSuchElementException;\nimport java.util.Set;\n\nimport static org.jclouds.compute.util.AutomaticHardwareIdSpec.automaticHardwareIdSpecBuilder;\nimport static org.jclouds.compute.util.AutomaticHardwareIdSpec.isAutomaticId;\nimport static org.jclouds.compute.util.AutomaticHardwareIdSpec.parseId;\n\npublic class ArbitraryCpuRamTemplateBuilderImpl extends TemplateBuilderImpl {\n   @Inject\n   protected ArbitraryCpuRamTemplateBuilderImpl(@Memoized Supplier<Set<? extends Location>> locations,\n         @Memoized Supplier<Set<? extends Image>> images, @Memoized Supplier<Set<? extends Hardware>> hardwares,\n         Supplier<Location> defaultLocation, @Named(\"DEFAULT\") Provider<TemplateOptions> optionsProvider,\n         @Named(\"DEFAULT\") Provider<TemplateBuilder> defaultTemplateProvider) {\n      super(locations, images, hardwares, defaultLocation, optionsProvider, defaultTemplateProvider);\n   }\n\n   protected Hardware automaticHardware(double cores, int ram, Optional<Float> diskSize) {\n      HardwareBuilder builder = new HardwareBuilder();\n      if (diskSize.isPresent() && diskSize.get() > 0.0f) {\n            builder.volume(new VolumeImpl(diskSize.get(), true, true));\n      }\n      return builder\n            .id(automaticHardwareIdSpecBuilder(cores, ram, diskSize).toString())\n            .ram(ram)\n            .processor(new Processor(cores, 1.0))\n            .build();\n   }\n\n   protected Hardware findHardwareWithId(Set<? extends Hardware> hardwaresToSearch) {\n      try {\n         return super.findHardwareWithId(hardwaresToSearch);\n      } catch (NoSuchElementException ex) {\n         if (isAutomaticId(hardwareId)) {\n            AutomaticHardwareIdSpec spec = parseId(hardwareId);\n            return automaticHardware(spec.getCores(), spec.getRam(), spec.getDisk());\n         }\n         else {\n            throw ex;\n         }\n      }\n   }\n\n   protected Hardware resolveHardware(Set<? extends Hardware> hardwarel, final Iterable<? extends Image> images) {\n      try {\n         return super.resolveHardware(hardwarel, images);\n      }\n      catch (NoSuchElementException ex) {\n         if (minCores <= 0 || minRam == 0 || minDisk < 0) {\n            throw new IllegalArgumentException(\"No hardware profile matching the given criteria was found. If you\" +\n                    \" want to use exact values, please set the minCores, minRam and minDisk to positive values.\");\n         }\n         return automaticHardware(minCores, minRam, minDisk == 0 ? Optional.<Float>absent() : Optional.of((float)minDisk));\n      }\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/domain/internal/ComputeMetadataImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.domain.internal;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.ComparisonChain.start;\nimport static com.google.common.collect.Ordering.natural;\n\nimport java.net.URI;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.ComputeMetadata;\nimport org.jclouds.compute.domain.ComputeType;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.ResourceMetadata;\nimport org.jclouds.domain.internal.ResourceMetadataImpl;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableSet;\n\npublic class ComputeMetadataImpl extends ResourceMetadataImpl<ComputeType> implements ComputeMetadata {\n\n   private final String id;\n   private final ComputeType type;\n   protected final Set<String> tags;\n\n   public ComputeMetadataImpl(ComputeType type, String providerId, String name, String id, Location location, URI uri,\n            Map<String, String> userMetadata, Set<String> tags) {\n      super(providerId, name, location, uri, userMetadata);\n      this.id = checkNotNull(id, \"id\");\n      this.type = checkNotNull(type, \"type\");\n      this.tags = ImmutableSet.<String> copyOf(checkNotNull(tags, \"tags\"));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ComputeType getType() {\n      return type;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getId() {\n      return id;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Set<String> getTags() {\n      return tags;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public int compareTo(ResourceMetadata<ComputeType> that) {\n      if (that instanceof ComputeMetadata) {\n         ComputeMetadata thatMetadata = ComputeMetadata.class.cast(that);\n         return start()\n                 .compare(this.getId(), thatMetadata.getId())\n                 .compare(this.getType(), thatMetadata.getType())\n                 .compare(this.getName(), that.getName(), natural().nullsLast())\n                 .result();\n      } else {\n         return super.compareTo(that);\n      }\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o)\n         return true;\n      if (o == null || getClass() != o.getClass())\n         return false;\n      ComputeMetadataImpl that = ComputeMetadataImpl.class.cast(o);\n      return super.equals(that) && equal(this.id, that.id);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(super.hashCode(), id);\n   }\n\n   protected ToStringHelper computeToStringPrefix() {\n      return MoreObjects.toStringHelper(\"\").omitNullValues().add(\"id\", getId()).add(\"providerId\", getProviderId())\n               .add(\"uri\", getUri()).add(\"name\", getName()).add(\"uri\", getUri()).add(\"location\", getLocation());\n   }\n\n   protected ToStringHelper addComputeToStringSuffix(ToStringHelper helper) {\n      if (!getTags().isEmpty())\n         helper.add(\"tags\", getTags());\n      if (!getUserMetadata().isEmpty())\n         helper.add(\"userMetadata\", getUserMetadata());\n      return helper;\n   }\n\n   protected ToStringHelper string() {\n      return addComputeToStringSuffix(computeToStringPrefix());\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/domain/internal/HardwareImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.domain.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.compute.util.ComputeServiceUtils.getCores;\nimport static org.jclouds.compute.util.ComputeServiceUtils.getSpace;\n\nimport java.net.URI;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.ComputeType;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.Processor;\nimport org.jclouds.compute.domain.Volume;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.ResourceMetadata;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ComparisonChain;\nimport com.google.common.collect.ImmutableList;\n\npublic class HardwareImpl extends ComputeMetadataImpl implements Hardware {\n\n   private final List<? extends Processor> processors;\n   private final int ram;\n   private final List<? extends Volume> volumes;\n   private final Predicate<Image> supportsImage;\n   private final String hypervisor;\n   private final boolean deprecated;\n\n   public HardwareImpl(String providerId, String name, String id, @Nullable Location location, URI uri,\n         Map<String, String> userMetadata, Set<String> tags, Iterable<? extends Processor> processors, int ram,\n         Iterable<? extends Volume> volumes, Predicate<Image> supportsImage, @Nullable String hypervisor, boolean deprecated) {\n      super(ComputeType.HARDWARE, providerId, name, id, location, uri, userMetadata, tags);\n      this.processors = ImmutableList.copyOf(checkNotNull(processors, \"processors\"));\n      this.ram = ram;\n      this.volumes = ImmutableList.copyOf(checkNotNull(volumes, \"volumes\"));\n      this.supportsImage = supportsImage;\n      this.hypervisor = hypervisor;\n      this.deprecated = deprecated;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public List<? extends Processor> getProcessors() {\n      return processors;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public int getRam() {\n      return ram;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public List<? extends Volume> getVolumes() {\n      return volumes;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   @Nullable\n   public String getHypervisor() {\n      return hypervisor;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public boolean isDeprecated() {\n      return deprecated;\n   }\n   \n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public int compareTo(ResourceMetadata<ComputeType> that) {\n      if (that instanceof Hardware) {\n         Hardware thatHardware = Hardware.class.cast(that);\n         return ComparisonChain.start().compare(getCores(this), getCores(thatHardware)).compare(this.getRam(), thatHardware.getRam())\n               .compare(getSpace(this), getSpace(thatHardware)).result();\n      } else {\n         return super.compareTo(that);\n      }\n   }\n\n   @Override\n   protected ToStringHelper string() {\n      ToStringHelper helper = computeToStringPrefix();\n      helper.add(\"processors\", processors).add(\"ram\", ram);\n      if (!volumes.isEmpty())\n         helper.add(\"volumes\", volumes);\n      helper.add(\"hypervisor\", hypervisor);\n      helper.add(\"supportsImage\", supportsImage);\n      return addComputeToStringSuffix(helper);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Predicate<Image> supportsImage() {\n      return supportsImage;\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/domain/internal/ImageImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.domain.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.compute.util.ComputeServiceUtils.formatStatus;\n\nimport java.net.URI;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.ComputeType;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\npublic class ImageImpl extends ComputeMetadataImpl implements Image {\n\n   private final OperatingSystem operatingSystem;\n   private final Status status;\n   private final String backendStatus;\n   private final String version;\n   private final String description;\n   private final LoginCredentials defaultCredentials;\n\n   public ImageImpl(String providerId, String name, String id, Location location, URI uri,\n            Map<String, String> userMetadata, Set<String> tags, OperatingSystem operatingSystem, Image.Status status,\n            @Nullable String backendStatus, @Nullable String description, @Nullable String version,\n            @Nullable LoginCredentials defaultCredentials) {\n      super(ComputeType.IMAGE, providerId, name, id, location, uri, userMetadata, tags);\n      this.operatingSystem = checkNotNull(operatingSystem, \"operatingSystem\");\n      this.status = checkNotNull(status, \"status\");\n      this.backendStatus = backendStatus;\n      this.version = version;\n      this.description = description;\n      this.defaultCredentials = defaultCredentials;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public OperatingSystem getOperatingSystem() {\n      return operatingSystem;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Status getStatus() {\n      return status;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getBackendStatus() {\n      return backendStatus;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getVersion() {\n      return version;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getDescription() {\n      return description;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public LoginCredentials getDefaultCredentials() {\n      return defaultCredentials;\n   }\n\n   // equals and toString from super are sufficient to establish identity equivalence\n\n   protected ToStringHelper string() {\n      ToStringHelper helper = computeToStringPrefix();\n      helper.add(\"os\", getOperatingSystem()).add(\"description\", getDescription()).add(\"version\", getVersion())\n               .add(\"status\", formatStatus(this))\n               .add(\"loginUser\", defaultCredentials != null ? defaultCredentials.identity : null);\n      return addComputeToStringSuffix(helper);\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/domain/internal/ImageTemplateImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.domain.internal;\n\nimport org.jclouds.compute.domain.CloneImageTemplate;\nimport org.jclouds.compute.domain.ImageTemplate;\n\npublic abstract class ImageTemplateImpl implements ImageTemplate {\n\n   protected final String name;\n\n   public ImageTemplateImpl(String name) {\n      this.name = name;\n   }\n\n   @Override\n   public String getName() {\n      return this.name;\n   }\n\n   public static class CloneImageTemplateImpl extends ImageTemplateImpl implements CloneImageTemplate {\n\n      protected final String sourceNodeId;\n\n      public CloneImageTemplateImpl(String name, String sourceNodeId) {\n         super(name);\n         this.sourceNodeId = sourceNodeId;\n      }\n\n      @Override\n      public String getSourceNodeId() {\n         return this.sourceNodeId;\n      }\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/domain/internal/NodeMetadataImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.domain.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.compute.util.ComputeServiceUtils.formatStatus;\n\nimport java.net.URI;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.ComputeType;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableSet;\n\npublic class NodeMetadataImpl extends ComputeMetadataImpl implements NodeMetadata {\n\n   private final Status status;\n   private final String backendStatus;\n   private final int loginPort;\n   private final Set<String> publicAddresses;\n   private final Set<String> privateAddresses;\n   @Nullable\n   private final LoginCredentials credentials;\n   @Nullable\n   private final String group;\n   @Nullable\n   private final String imageId;\n   @Nullable\n   private final Hardware hardware;\n   @Nullable\n   private final OperatingSystem os;\n   @Nullable\n   private final String hostname;\n\n   public NodeMetadataImpl(String providerId, String name, String id, Location location, URI uri,\n            Map<String, String> userMetadata, Set<String> tags, @Nullable String group, @Nullable Hardware hardware,\n            @Nullable String imageId, @Nullable OperatingSystem os, Status status, @Nullable String backendStatus,\n            int loginPort, Iterable<String> publicAddresses, Iterable<String> privateAddresses,\n            @Nullable LoginCredentials credentials, String hostname) {\n      super(ComputeType.NODE, providerId, name, id, location, uri, userMetadata, tags);\n      this.group = group;\n      this.hardware = hardware;\n      this.imageId = imageId;\n      this.os = os;\n      this.status = checkNotNull(status, \"status\");\n      this.backendStatus = backendStatus;\n      this.loginPort = loginPort;\n      this.publicAddresses = ImmutableSet.copyOf(checkNotNull(publicAddresses, \"publicAddresses\"));\n      this.privateAddresses = ImmutableSet.copyOf(checkNotNull(privateAddresses, \"privateAddresses\"));\n      this.credentials = credentials;\n      this.hostname = hostname;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getGroup() {\n      return group;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Hardware getHardware() {\n      return hardware;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public LoginCredentials getCredentials() {\n      return credentials;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Set<String> getPublicAddresses() {\n      return publicAddresses;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Set<String> getPrivateAddresses() {\n      return privateAddresses;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Status getStatus() {\n      return status;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getBackendStatus() {\n      return backendStatus;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public int getLoginPort() {\n      return this.loginPort;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getImageId() {\n      return imageId;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public OperatingSystem getOperatingSystem() {\n      return os;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getHostname() {\n      return hostname;\n   }\n\n   // equals and toString from super are sufficient to establish identity equivalence\n\n   protected ToStringHelper string() {\n      ToStringHelper helper = computeToStringPrefix();\n      helper.add(\"group\", getGroup()).add(\"imageId\", getImageId()).add(\"os\", getOperatingSystem())\n               .add(\"status\", formatStatus(this)).add(\"loginPort\", getLoginPort()).add(\"hostname\", getHostname());\n      if (!getPrivateAddresses().isEmpty())\n         helper.add(\"privateAddresses\", getPrivateAddresses());\n      if (!getPublicAddresses().isEmpty())\n         helper.add(\"publicAddresses\", getPublicAddresses());\n      helper.add(\"hardware\", getHardware()).add(\"loginUser\", credentials != null ? credentials.identity : null);\n      return addComputeToStringSuffix(helper);\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/domain/internal/NullEqualToIsParentOrIsGrandparentOfCurrentLocation.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.domain.internal;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.common.base.Predicates.equalTo;\n\nimport org.jclouds.compute.domain.ComputeMetadata;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationScope;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Predicates;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\n\n/**\n * If the current location id is null, then we don't care where to launch a node.\n * \n * If the input location is null, then the data isn't location sensitive\n * \n * If the input location equals, is a parent or grandparent of the specified location, then we are ok.\n */\npublic class NullEqualToIsParentOrIsGrandparentOfCurrentLocation implements Predicate<ComputeMetadata> {\n   private final Supplier<Location> locationSupplier;\n\n   public NullEqualToIsParentOrIsGrandparentOfCurrentLocation(Supplier<Location> locationSupplier) {\n      this.locationSupplier = locationSupplier;\n   }\n\n   @Override\n   public boolean apply(ComputeMetadata input) {\n      Location current = locationSupplier.get();\n      if (current == null)\n         return true;\n      \n      if (input.getLocation() == null)\n         return true;\n      \n      Location parent = current.getParent();\n      checkArgument(\n            parent != null || current.getScope() == LocationScope.PROVIDER,\n            \"only locations of scope PROVIDER can have a null parent; arg: %s\",\n            current);\n      \n      checkState(\n            input.getLocation().getParent() != null || input.getLocation().getScope() == LocationScope.PROVIDER,\n            \"only locations of scope PROVIDER can have a null parent; input: %s\",\n            input.getLocation());\n\n      Builder<Predicate<Location>> predicates = ImmutableSet.builder();\n\n      predicates.add(equalTo(current));\n      \n      if (parent != null) {\n         predicates.add(equalTo(parent));\n         \n         Location grandparent = parent.getParent();\n         if (grandparent != null)\n            predicates.add(equalTo(grandparent));\n      }\n      \n      return Predicates.or(predicates.build()).apply(input.getLocation());\n\n   }\n\n   @Override\n   public String toString() {\n      // not calling .get() here, as it could accidentally cause eager api fetch\n      return \"nullEqualToIsParentOrIsGrandparentOfCurrentLocation()\";\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/domain/internal/TemplateBuilderImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.domain.internal;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Function;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Predicates;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ComparisonChain;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Ordering;\nimport com.google.common.primitives.Doubles;\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.domain.ComputeMetadata;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.domain.TemplateBuilder;\nimport org.jclouds.compute.domain.TemplateBuilderSpec;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.compute.predicates.ImagePredicates;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.compute.suppliers.ImageCacheSupplier;\nimport org.jclouds.domain.Location;\nimport org.jclouds.logging.Logger;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Provider;\nimport java.util.Comparator;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.NoSuchElementException;\nimport java.util.Set;\nimport java.util.regex.Pattern;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.find;\nimport static com.google.common.collect.Iterables.size;\nimport static com.google.common.collect.Iterables.transform;\nimport static com.google.common.collect.Iterables.tryFind;\nimport static com.google.common.collect.Lists.newArrayList;\nimport static java.lang.String.format;\nimport static org.jclouds.compute.util.ComputeServiceUtils.getCores;\nimport static org.jclouds.compute.util.ComputeServiceUtils.getCoresAndSpeed;\nimport static org.jclouds.compute.util.ComputeServiceUtils.getSpace;\n\npublic class TemplateBuilderImpl implements TemplateBuilder {\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   protected final ImageCacheSupplier images;\n   protected final Supplier<Set<? extends Hardware>> hardwares;\n   protected final Supplier<Set<? extends Location>> locations;\n   protected final Supplier<Location> defaultLocation;\n   protected final Provider<TemplateOptions> optionsProvider;\n   protected final Provider<TemplateBuilder> defaultTemplateProvider;\n\n   @VisibleForTesting\n   protected Location location;\n   @VisibleForTesting\n   protected String imageId;\n   @VisibleForTesting\n   protected String hardwareId;\n   @VisibleForTesting\n   protected String hypervisor;\n   @VisibleForTesting\n   protected String imageVersion;\n   @VisibleForTesting\n   protected OsFamily osFamily;\n   @VisibleForTesting\n   protected String osVersion;\n   @VisibleForTesting\n   protected Boolean os64Bit;\n   @VisibleForTesting\n   protected String osName;\n   @VisibleForTesting\n   protected String osDescription;\n   @VisibleForTesting\n   protected String osArch;\n   @VisibleForTesting\n   protected String imageName;\n   @VisibleForTesting\n   protected String imageDescription;\n   @VisibleForTesting\n   protected Predicate<Image> imagePredicate;\n   @VisibleForTesting\n   protected Function<Iterable<? extends Image>, Image> imageChooser;\n   @VisibleForTesting\n   protected double minCores;\n   @VisibleForTesting\n   protected int minRam;\n   @VisibleForTesting\n   protected double minDisk;\n   @VisibleForTesting\n   protected boolean biggest;\n   @VisibleForTesting\n   protected boolean fastest;\n   @VisibleForTesting\n   protected TemplateOptions options;\n   @VisibleForTesting\n   protected Boolean forceCacheReload;\n\n   @Inject\n   protected TemplateBuilderImpl(@Memoized Supplier<Set<? extends Location>> locations,\n         @Memoized Supplier<Set<? extends Image>> images, @Memoized Supplier<Set<? extends Hardware>> hardwares,\n         Supplier<Location> defaultLocation, @Named(\"DEFAULT\") Provider<TemplateOptions> optionsProvider,\n         @Named(\"DEFAULT\") Provider<TemplateBuilder> defaultTemplateProvider) {\n      this.locations = checkNotNull(locations, \"locations\");\n      checkArgument(images instanceof ImageCacheSupplier, \"an instance of the ImageCacheSupplier is needed\");\n      this.images = ImageCacheSupplier.class.cast(images);\n      this.hardwares = checkNotNull(hardwares, \"hardwares\");\n      this.defaultLocation = checkNotNull(defaultLocation, \"defaultLocation\");\n      this.optionsProvider = checkNotNull(optionsProvider, \"optionsProvider\");\n      this.defaultTemplateProvider = checkNotNull(defaultTemplateProvider, \"defaultTemplateProvider\");\n   }\n\n   static Predicate<Hardware> supportsImagesPredicate(final Iterable<? extends Image> images) {\n      return new Predicate<Hardware>() {\n         @Override\n         public boolean apply(final Hardware hardware) {\n            return Iterables.any(images, new Predicate<Image>() {\n\n               @Override\n               public boolean apply(Image input) {\n                  return hardware.supportsImage().apply(input);\n               }\n\n               @Override\n               public String toString() {\n                  return \"hardware(\" + hardware + \").supportsImage()\";\n               }\n\n            });\n\n         }\n\n      };\n   }\n\n   final Predicate<ComputeMetadata> locationPredicate = new NullEqualToIsParentOrIsGrandparentOfCurrentLocation(new Supplier<Location>() {\n\n      @Override\n      public Location get() {\n         return location;\n      }\n\n   });\n\n   private final Predicate<OperatingSystem> osFamilyPredicate = new Predicate<OperatingSystem>() {\n\n      @Override\n      public boolean apply(OperatingSystem input) {\n         boolean returnVal = true;\n         if (osFamily != null)\n            returnVal = osFamily.equals(input.getFamily());\n         return returnVal;\n      }\n\n      @Override\n      public String toString() {\n         return \"osFamily(\" + osFamily + \")\";\n      }\n   };\n\n   private final Predicate<OperatingSystem> osNamePredicate = new Predicate<OperatingSystem>() {\n      @Override\n      public boolean apply(OperatingSystem input) {\n         boolean returnVal = true;\n         if (osName != null) {\n            if (input.getName() == null)\n               returnVal = false;\n            else\n               returnVal = input.getName().contains(osName) || input.getName().matches(osName);\n         }\n         return returnVal;\n      }\n\n      @Override\n      public String toString() {\n         return \"osName(\" + osName + \")\";\n      }\n   };\n\n   private final Predicate<OperatingSystem> osDescriptionPredicate = new Predicate<OperatingSystem>() {\n      @Override\n      public boolean apply(OperatingSystem input) {\n         boolean returnVal = true;\n         if (osDescription != null) {\n            if (input.getDescription() == null)\n               returnVal = false;\n            else\n               returnVal = input.getDescription().contains(osDescription)\n                     || input.getDescription().matches(osDescription);\n         }\n         return returnVal;\n      }\n\n      @Override\n      public String toString() {\n         return \"osDescription(\" + osDescription + \")\";\n      }\n   };\n\n   private final Predicate<OperatingSystem> osVersionPredicate = new Predicate<OperatingSystem>() {\n      @Override\n      public boolean apply(OperatingSystem input) {\n         boolean returnVal = true;\n         if (osVersion != null) {\n            if (input.getVersion() == null)\n               returnVal = false;\n            else\n               returnVal = input.getVersion().contains(osVersion) || input.getVersion().matches(osVersion);\n         }\n         return returnVal;\n      }\n\n      @Override\n      public String toString() {\n         return \"osVersion(\" + osVersion + \")\";\n      }\n   };\n\n   private final Predicate<OperatingSystem> os64BitPredicate = new Predicate<OperatingSystem>() {\n      @Override\n      public boolean apply(OperatingSystem input) {\n         boolean returnVal = true;\n         if (os64Bit != null) {\n            if (os64Bit)\n               return input.is64Bit();\n            else\n               return !input.is64Bit();\n         }\n         return returnVal;\n      }\n\n      @Override\n      public String toString() {\n         return \"os64Bit(\" + os64Bit + \")\";\n      }\n   };\n\n   private final Predicate<OperatingSystem> osArchPredicate = new Predicate<OperatingSystem>() {\n      @Override\n      public boolean apply(OperatingSystem input) {\n         boolean returnVal = true;\n         if (osArch != null) {\n            if (input.getArch() == null)\n               returnVal = false;\n            else\n               returnVal = input.getArch().contains(osArch) || input.getArch().matches(osArch);\n         }\n         return returnVal;\n      }\n\n      @Override\n      public String toString() {\n         return \"osArch(\" + osArch + \")\";\n      }\n   };\n\n   private final Predicate<Image> imageVersionPredicate = new Predicate<Image>() {\n      @Override\n      public boolean apply(Image input) {\n         boolean returnVal = true;\n         if (imageVersion != null) {\n            if (input.getVersion() == null)\n               returnVal = false;\n            else\n               returnVal = input.getVersion().contains(imageVersion) || input.getVersion().matches(imageVersion);\n         }\n         return returnVal;\n      }\n\n      @Override\n      public String toString() {\n         return \"imageVersion(\" + imageVersion + \")\";\n      }\n   };\n\n   private final Predicate<Image> imageNamePredicate = new Predicate<Image>() {\n      @Override\n      public boolean apply(Image input) {\n         boolean returnVal = true;\n         if (imageName != null) {\n            if (input.getName() == null)\n               returnVal = false;\n            else\n               returnVal = input.getName().equals(imageName) || input.getName().contains(imageName)\n                        || input.getName().matches(imageName);\n         }\n         return returnVal;\n      }\n\n      @Override\n      public String toString() {\n         return \"imageName(\" + imageName + \")\";\n      }\n   };\n\n   private final Predicate<Image> imageDescriptionPredicate = new Predicate<Image>() {\n      @Override\n      public boolean apply(Image input) {\n         boolean returnVal = true;\n         if (imageDescription != null) {\n            if (input.getDescription() == null)\n               returnVal = false;\n            else\n               returnVal = input.getDescription().equals(imageDescription)\n                     || input.getDescription().contains(imageDescription)\n                     || input.getDescription().matches(imageDescription);\n         }\n         return returnVal;\n      }\n\n      @Override\n      public String toString() {\n         return \"imageDescription(\" + imageDescription + \")\";\n      }\n   };\n   private final Predicate<Hardware> hardwareIdPredicate = new Predicate<Hardware>() {\n      @Override\n      public boolean apply(Hardware input) {\n         boolean returnVal = true;\n         if (hardwareId != null) {\n            returnVal = hardwareId.equals(input.getId());\n            // match our input params so that the later predicates pass.\n            if (returnVal) {\n               fromHardware(input);\n            }\n         }\n         return returnVal;\n      }\n\n      @Override\n      public String toString() {\n         return \"hardwareId(\" + hardwareId + \")\";\n      }\n   };\n\n   private final Predicate<Hardware> hypervisorPredicate = new Predicate<Hardware>() {\n      @Override\n      public boolean apply(Hardware input) {\n         boolean returnVal = true;\n         if (hypervisor != null) {\n            if (input.getHypervisor() == null)\n               returnVal = false;\n            else\n               returnVal = input.getHypervisor().contains(hypervisor)\n                     || input.getHypervisor().matches(hypervisor);\n         }\n         return returnVal;\n      }\n\n      @Override\n      public String toString() {\n         return \"hypervisorMatches(\" + hypervisor + \")\";\n      }\n   };\n\n   private final Predicate<Hardware> hardwareCoresPredicate = new Predicate<Hardware>() {\n      @Override\n      public boolean apply(Hardware input) {\n         double cores = getCores(input);\n         return cores >= TemplateBuilderImpl.this.minCores;\n      }\n\n      @Override\n      public String toString() {\n         return \"minCores(\" + minCores + \")\";\n      }\n   };\n\n   private final Predicate<Hardware> hardwareDiskPredicate = new Predicate<Hardware>() {\n      @Override\n      public boolean apply(Hardware input) {\n         return getSpace(input) >= TemplateBuilderImpl.this.minDisk;\n      }\n\n      @Override\n      public String toString() {\n         return \"minDisk(\" + minDisk + \")\";\n      }\n   };\n\n   private final Predicate<Hardware> hardwareRamPredicate = new Predicate<Hardware>() {\n      @Override\n      public boolean apply(Hardware input) {\n         return input.getRam() >= TemplateBuilderImpl.this.minRam;\n      }\n\n      @Override\n      public String toString() {\n         return \"minRam(\" + minRam + \")\";\n      }\n   };\n\n   private Predicate<Hardware> buildHardwarePredicate() {\n      List<Predicate<Hardware>> predicates = newArrayList();\n      if (location != null)\n         predicates.add(new Predicate<Hardware>() {\n\n            @Override\n            public boolean apply(Hardware input) {\n               return locationPredicate.apply(input);\n            }\n\n            @Override\n            public String toString() {\n               return locationPredicate.toString();\n            }\n         });\n      if (hypervisor != null)\n         predicates.add(hypervisorPredicate);\n      predicates.add(hardwareCoresPredicate);\n      predicates.add(hardwareRamPredicate);\n      predicates.add(hardwareDiskPredicate);\n\n      // looks verbose, but explicit <Hardware> type needed for this to compile\n      // properly\n      Predicate<Hardware> hardwarePredicate = predicates.size() == 1 ? Iterables.<Predicate<Hardware>> get(predicates, 0)\n            : Predicates.<Hardware> and(predicates);\n      return hardwarePredicate;\n   }\n\n   static final Ordering<Hardware> DEFAULT_SIZE_ORDERING = new Ordering<Hardware>() {\n      public int compare(Hardware left, Hardware right) {\n         return ComparisonChain.start().compare(getCores(left), getCores(right)).compare(left.getRam(), right.getRam())\n               .compare(getSpace(left), getSpace(right)).result();\n      }\n   };\n   static final Ordering<Hardware> BY_CORES_ORDERING = new Ordering<Hardware>() {\n      public int compare(Hardware left, Hardware right) {\n         return Doubles.compare(getCoresAndSpeed(left), getCoresAndSpeed(right));\n      }\n   };\n   static final Ordering<Hardware> NOT_DEPRECATED_ORDERING = new Ordering<Hardware>() {\n      public int compare(Hardware left, Hardware right) {\n         // we take max so deprecated items come first\n         return ComparisonChain.start().compareTrueFirst(left.isDeprecated(), right.isDeprecated()).result();\n      }\n   };\n   static final Ordering<Image> DEFAULT_IMAGE_ORDERING = new Ordering<Image>() {\n      public int compare(Image left, Image right) {\n         /* This currently, and for some time, has *preferred* images whose fields are null,\n          * and prefers those which come last alphabetically.\n          * It seems preferable to take images whose fields are *not* null, ie nullsFirst;\n          * and to use something like the AlphaNum Algorithm then take the last\n          * (so \"Ubuntu 13.04\" would be preferred over \"Ubuntu 9.10\").\n          * However not changing it now as people may be surprised if the images they get back start changing.\n          */\n         return ComparisonChain.start()\n               .compare(left.getName(), right.getName(), Ordering.<String> natural().nullsLast())\n               .compare(left.getVersion(), right.getVersion(), Ordering.<String> natural().nullsLast())\n               .compare(left.getDescription(), right.getDescription(), Ordering.<String> natural().nullsLast())\n               .compare(left.getOperatingSystem().getName(), right.getOperatingSystem().getName(),\n                     Ordering.<String> natural().nullsLast())\n               .compare(left.getOperatingSystem().getVersion(), right.getOperatingSystem().getVersion(),\n                     Ordering.<String> natural().nullsLast())\n               .compare(left.getOperatingSystem().getDescription(), right.getOperatingSystem().getDescription(),\n                     Ordering.<String> natural().nullsLast())\n               .compare(left.getOperatingSystem().getArch(), right.getOperatingSystem().getArch(),\n                     Ordering.<String> natural().nullsLast()).result();\n      }\n   };\n\n   @VisibleForTesting\n   // non-static for logging\n   final Function<Iterable<? extends Image>, Image> imageChooserFromOrdering(final Ordering<Image> ordering) {\n      return new Function<Iterable<? extends Image>, Image>() {\n         @Override\n         public Image apply(Iterable<? extends Image> input) {\n            List<? extends Image> maxImages = multiMax(ordering, input);\n            if (logger.isTraceEnabled())\n               logger.trace(\"<<   best images(%s)\", transform(maxImages, imageToId));\n            return maxImages.get(maxImages.size() - 1);\n         }\n      };\n   }\n\n   @VisibleForTesting\n   Function<Iterable<? extends Image>, Image> defaultImageChooser() {\n       return imageChooserFromOrdering(DEFAULT_IMAGE_ORDERING);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public TemplateBuilder fromTemplate(Template template) {\n      location = template.getLocation();\n      fromHardware(template.getHardware());\n      fromImage(template.getImage());\n      options(template.getOptions());\n      return this;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public TemplateBuilder fromHardware(Hardware hardware) {\n      if (currentLocationWiderThan(hardware.getLocation()))\n         this.location = hardware.getLocation();\n      this.minCores = getCores(hardware);\n      this.minRam = hardware.getRam();\n      this.minDisk = getSpace(hardware);\n      this.hypervisor = hardware.getHypervisor();\n      return this;\n   }\n\n   private boolean currentLocationWiderThan(Location location) {\n      return this.location == null || (location != null && this.location.getScope().compareTo(location.getScope()) < 0);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public TemplateBuilder fromImage(Image image) {\n      if (currentLocationWiderThan(image.getLocation()))\n         this.location = image.getLocation();\n      if (image.getOperatingSystem().getFamily() != null)\n         this.osFamily = image.getOperatingSystem().getFamily();\n      if (image.getName() != null)\n         this.imageName = image.getName();\n      if (image.getDescription() != null)\n         this.imageDescription = String.format(\"^%s$\", Pattern.quote(image.getDescription()));\n      if (image.getOperatingSystem().getName() != null)\n         this.osName = image.getOperatingSystem().getName();\n      if (image.getOperatingSystem().getDescription() != null)\n         this.osDescription = image.getOperatingSystem().getDescription();\n      if (image.getVersion() != null)\n         this.imageVersion = String.format(\"^%s$\", Pattern.quote(image.getVersion()));\n      if (image.getOperatingSystem().getVersion() != null)\n         this.osVersion = image.getOperatingSystem().getVersion();\n      this.os64Bit = image.getOperatingSystem().is64Bit();\n      if (image.getOperatingSystem().getArch() != null)\n         this.osArch = image.getOperatingSystem().getArch();\n      return this;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public TemplateBuilder smallest() {\n      this.biggest = false;\n      return this;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public TemplateBuilder biggest() {\n      this.biggest = true;\n      return this;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public TemplateBuilder fastest() {\n      this.fastest = true;\n      return this;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public TemplateBuilder locationId(final String locationId) {\n      Set<? extends Location> locations = this.locations.get();\n      try {\n         this.location = find(locations, new Predicate<Location>() {\n\n            @Override\n            public boolean apply(Location input) {\n               return input.getId().equals(locationId);\n            }\n\n            @Override\n            public String toString() {\n               return \"locationId(\" + locationId + \")\";\n            }\n\n         });\n      } catch (NoSuchElementException e) {\n         throw new NoSuchElementException(format(\"location id %s not found in: %s\", locationId, locations));\n      }\n      return this;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public TemplateBuilder osFamily(OsFamily os) {\n      this.osFamily = os;\n      return this;\n   }\n\n   private static final Function<Image, String> imageToId = new Function<Image, String>() {\n\n      @Override\n      public String apply(Image arg0) {\n         return arg0.getId();\n      }\n\n   };\n\n\n   private static final Function<Hardware, String> hardwareToId = new Function<Hardware, String>() {\n\n      @Override\n      public String apply(Hardware arg0) {\n         return arg0.getId();\n      }\n\n   };\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Template build() {\n      if (nothingChangedExceptOptions()) {\n         TemplateBuilder defaultTemplate = defaultTemplateProvider.get();\n         if (options != null)\n            defaultTemplate.options(options);\n         return defaultTemplate.build();\n      }\n\n      if (options == null)\n         options = optionsProvider.get();\n      logger.debug(\">> searching params(%s)\", this);\n      Set<? extends Image> images = getImages();\n      checkState(!images.isEmpty(), \"no images present!\");\n      Set<? extends Hardware> hardwaresToSearch = hardwares.get();\n      checkState(!hardwaresToSearch.isEmpty(), \"no hardware profiles present!\");\n\n      Image image = null;\n      if (imageId != null) {\n         image = loadImageWithId(images);\n         if (currentLocationWiderThan(image.getLocation()))\n            this.location = image.getLocation();\n      }\n\n      Hardware hardware = null;\n      if (hardwareId != null) {\n         hardware = findHardwareWithId(hardwaresToSearch);\n         if (currentLocationWiderThan(hardware.getLocation()))\n            this.location = hardware.getLocation();\n      }\n\n      // if the user hasn't specified a location id, or an image or hardware\n      // with location, let's search scoped to the implicit one\n      if (location == null)\n         location = defaultLocation.get();\n\n      if (image == null) {\n         Iterable<? extends Image> supportedImages = findSupportedImages(images);\n         if (hardware == null)\n            hardware = resolveHardware(hardwaresToSearch, supportedImages);\n         image = resolveImage(hardware, supportedImages);\n      } else {\n         if (hardware == null)\n            hardware = resolveHardware(hardwaresToSearch, ImmutableSet.of(image));\n      }\n\n      logger.debug(\"<<   matched image(%s) hardware(%s) location(%s)\", image.getId(), hardware.getId(),\n            location.getId());\n      return new TemplateImpl(image, hardware, location, options);\n   }\n\n   private Iterable<? extends Image> findSupportedImages(Set<? extends Image> images) {\n      Predicate<Image> imagePredicate = buildImagePredicate();\n      Iterable<? extends Image> supportedImages = filter(images, imagePredicate);\n      if (size(supportedImages) == 0) {\n         throw throwNoSuchElementExceptionAfterLoggingImageIds(\n               format(\"no image matched predicate: %s\", imagePredicate), images);\n      }\n      return supportedImages;\n   }\n\n   private Image loadImageWithId(Iterable<? extends Image> images) {\n      Optional<? extends Image> image = tryFind(images, ImagePredicates.idEquals(imageId));\n      if (!image.isPresent()) {\n         image = this.images.get(imageId); // Load the image from the cache, and refresh if missing\n         if (!image.isPresent()) {\n            throw throwNoSuchElementExceptionAfterLoggingImageIds(format(\"imageId(%s) not found\", imageId), images);\n         }\n      }\n      fromImage(image.get());\n      return image.get();\n   }\n\n   protected Hardware findHardwareWithId(Set<? extends Hardware> hardwaresToSearch) {\n      Hardware hardware;\n      // TODO: switch to GetHardwareStrategy in version 1.5\n      hardware = tryFind(hardwaresToSearch, hardwareIdPredicate).orNull();\n      if (hardware == null)\n         throw throwNoSuchElementExceptionAfterLoggingHardwareIds(format(\"%s not found\", hardwareIdPredicate),\n               hardwaresToSearch);\n      return hardware;\n   }\n\n   protected NoSuchElementException throwNoSuchElementExceptionAfterLoggingImageIds(String message, Iterable<? extends Image> images) {\n      NoSuchElementException exception = new NoSuchElementException(message);\n      if (logger.isTraceEnabled())\n         logger.warn(exception, \"image ids that didn't match: %s\", transform(images, imageToId));\n      throw exception;\n   }\n\n   protected NoSuchElementException throwNoSuchElementExceptionAfterLoggingHardwareIds(String message, Iterable<? extends Hardware> hardwares) {\n      NoSuchElementException exception = new NoSuchElementException(message);\n      if (logger.isTraceEnabled())\n         logger.warn(exception, \"hardware ids that didn't match: %s\", transform(hardwares, hardwareToId));\n      throw exception;\n   }\n\n   protected Hardware resolveHardware(Set<? extends Hardware> hardwarel, final Iterable<? extends Image> images) {\n      Ordering<Hardware> hardwareOrdering = hardwareSorter();\n\n      Iterable<Predicate<Image>> supportsImagePredicates = Iterables.transform(hardwarel,\n               new Function<Hardware, Predicate<Image>>() {\n\n                  @Override\n                  public Predicate<Image> apply(Hardware input) {\n                     return input.supportsImage();\n                  }\n\n               });\n\n      Predicate<Image> supportsImagePredicate = Iterables.size(supportsImagePredicates) == 1 ? Iterables\n               .getOnlyElement(supportsImagePredicates) : Predicates.<Image>or(supportsImagePredicates);\n\n      if (!Iterables.any(images, supportsImagePredicate)) {\n         String message = format(\"no hardware profiles support images matching params: %s\", supportsImagePredicate);\n         throw throwNoSuchElementExceptionAfterLoggingHardwareIds(message, hardwarel);\n      }\n\n      Iterable<? extends Hardware> hardwareCompatibleWithOurImages = filter(hardwarel, supportsImagesPredicate(images));\n      Predicate<Hardware> hardwarePredicate = buildHardwarePredicate();\n      Hardware hardware;\n      try {\n         hardware = hardwareOrdering.max(filter(hardwareCompatibleWithOurImages, hardwarePredicate));\n      } catch (NoSuchElementException exception) {\n         String message = format(\"no hardware profiles match params: %s\", hardwarePredicate);\n         throw throwNoSuchElementExceptionAfterLoggingHardwareIds(message, hardwareCompatibleWithOurImages);\n      }\n      logger.trace(\"<<   matched hardware(%s)\", hardware.getId());\n      return hardware;\n   }\n\n   protected Function<Iterable<? extends Image>, Image> imageChooser() {\n      if (imageChooser != null) return imageChooser;\n      return defaultImageChooser();\n   }\n\n   protected Ordering<Hardware> hardwareSorter() {\n      Ordering<Hardware> hardwareOrdering = DEFAULT_SIZE_ORDERING;\n      if (!biggest)\n         hardwareOrdering = hardwareOrdering.reverse();\n      if (fastest)\n         hardwareOrdering = Ordering.compound(ImmutableList.of(BY_CORES_ORDERING, hardwareOrdering));\n      hardwareOrdering = Ordering.compound(ImmutableList.of(NOT_DEPRECATED_ORDERING, hardwareOrdering));\n      return hardwareOrdering;\n   }\n\n   /**\n    *\n    * @param hardware\n    * @param supportedImages\n    * @throws NoSuchElementException\n    *            if there's no image that matches the predicate\n    */\n   protected Image resolveImage(final Hardware hardware, Iterable<? extends Image> supportedImages) {\n      Predicate<Image> imagePredicate = new Predicate<Image>() {\n\n         @Override\n         public boolean apply(Image arg0) {\n            return hardware.supportsImage().apply(arg0);\n         }\n\n         @Override\n         public String toString() {\n            return \"hardware(\" + hardware + \").supportsImage()\";\n         }\n      };\n\n      try {\n         Iterable<? extends Image> matchingImages = filter(supportedImages, imagePredicate);\n         if (logger.isTraceEnabled())\n            logger.trace(\"<<   matched images(%s)\", transform(matchingImages, imageToId));\n         return imageChooser().apply(matchingImages);\n      } catch (NoSuchElementException exception) {\n         throw throwNoSuchElementExceptionAfterLoggingImageIds(format(\"no image matched params: %s\", toString()),\n               supportedImages);\n      }\n   }\n\n   /**\n    * Like Ordering, but handle the case where there are multiple valid maximums\n    */\n   @SuppressWarnings(\"unchecked\")\n   @VisibleForTesting\n   static <T, E extends T> List<E> multiMax(Comparator<T> ordering, Iterable<E> iterable) {\n      Iterator<E> iterator = iterable.iterator();\n      List<E> maxes = newArrayList(iterator.next());\n      E maxSoFar = maxes.get(0);\n      while (iterator.hasNext()) {\n         E current = iterator.next();\n         int comparison = ordering.compare(maxSoFar, current);\n         if (comparison == 0) {\n            maxes.add(current);\n         } else if (comparison < 0) {\n            maxes = newArrayList(current);\n            maxSoFar = current;\n         }\n      }\n      return maxes;\n   }\n   protected Set<? extends Image> getImages() {\n      return forceCacheReload != null && forceCacheReload ? images.rebuildCache() : images.get();\n   }\n\n   private Predicate<Image> buildImagePredicate() {\n      List<Predicate<Image>> predicates = newArrayList();\n      if (location != null)\n         predicates.add(new Predicate<Image>() {\n\n            @Override\n            public boolean apply(Image input) {\n               return locationPredicate.apply(input);\n            }\n\n            @Override\n            public String toString() {\n               return locationPredicate.toString();\n            }\n         });\n\n      final List<Predicate<OperatingSystem>> osPredicates = newArrayList();\n      if (osFamily != null)\n         osPredicates.add(osFamilyPredicate);\n      if (osName != null)\n         osPredicates.add(osNamePredicate);\n      if (osDescription != null)\n         osPredicates.add(osDescriptionPredicate);\n      if (osVersion != null)\n         osPredicates.add(osVersionPredicate);\n      if (os64Bit != null)\n         osPredicates.add(os64BitPredicate);\n      if (osArch != null)\n         osPredicates.add(osArchPredicate);\n      if (!osPredicates.isEmpty())\n         predicates.add(new Predicate<Image>() {\n\n            @Override\n            public boolean apply(Image input) {\n               return Predicates.and(osPredicates).apply(input.getOperatingSystem());\n            }\n\n            @Override\n            public String toString() {\n               return Predicates.and(osPredicates).toString();\n            }\n\n         });\n      if (imageVersion != null)\n         predicates.add(imageVersionPredicate);\n      if (imageName != null)\n         predicates.add(imageNamePredicate);\n      if (imageDescription != null)\n         predicates.add(imageDescriptionPredicate);\n      if (imagePredicate != null)\n         predicates.add(imagePredicate);\n\n      // looks verbose, but explicit <Image> type needed for this to compile\n      // properly\n      Predicate<Image> imagePredicate = predicates.size() == 1 ? Iterables.<Predicate<Image>> get(predicates, 0)\n            : Predicates.<Image> and(predicates);\n      return imagePredicate;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public TemplateBuilder imageId(String imageId) {\n      this.imageId = imageId;\n      this.imageName = null;\n      this.imageDescription = null;\n      this.imagePredicate = null;\n      this.imageVersion = null;\n      this.osFamily = null;\n      this.osName = null;\n      this.osDescription = null;\n      this.osVersion = null;\n      this.os64Bit = null;\n      this.osArch = null;\n      return this;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public TemplateBuilder imageNameMatches(String nameRegex) {\n      this.imageName = nameRegex;\n      return this;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public TemplateBuilder imageDescriptionMatches(String descriptionRegex) {\n      this.imageDescription = descriptionRegex;\n      return this;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public TemplateBuilder imageMatches(Predicate<Image> condition) {\n      this.imagePredicate = condition;\n      return this;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public TemplateBuilderImpl imageChooser(Function<Iterable<? extends Image>, Image> imageChooser) {\n      this.imageChooser = imageChooser;\n      return this;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public TemplateBuilder imageVersionMatches(String imageVersionRegex) {\n      this.imageVersion = imageVersionRegex;\n      return this;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public TemplateBuilder osVersionMatches(String osVersionRegex) {\n      this.osVersion = osVersionRegex;\n      return this;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public TemplateBuilder osArchMatches(String osArchitectureRegex) {\n      this.osArch = osArchitectureRegex;\n      return this;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public TemplateBuilder minCores(double minCores) {\n      this.minCores = minCores;\n      return this;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public TemplateBuilder minRam(int megabytes) {\n      this.minRam = megabytes;\n      return this;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public TemplateBuilder minDisk(double gigabytes) {\n      this.minDisk = gigabytes;\n      return this;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public TemplateBuilder osNameMatches(String osNameRegex) {\n      this.osName = osNameRegex;\n      return this;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public TemplateBuilder osDescriptionMatches(String osDescriptionRegex) {\n      this.osDescription = osDescriptionRegex;\n      return this;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public TemplateBuilder hardwareId(String hardwareId) {\n      this.hardwareId = hardwareId;\n      this.hypervisor = null;\n      return this;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public TemplateBuilder hypervisorMatches(String hypervisor) {\n      this.hypervisor = hypervisor;\n      return this;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public TemplateBuilder options(TemplateOptions options) {\n      this.options = optionsProvider.get();\n      checkNotNull(options, \"options\").copyTo(this.options);\n      return this;\n   }\n\n   @VisibleForTesting\n   boolean nothingChangedExceptOptions() {\n      return osFamily == null && location == null && imageId == null && hardwareId == null && hypervisor == null\n            && osName == null && imagePredicate == null && imageChooser == null && osDescription == null\n            && imageVersion == null && osVersion == null && osArch == null && os64Bit == null && imageName == null\n            && imageDescription == null && minCores == 0 && minRam == 0 && minDisk == 0 && !biggest && !fastest;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public TemplateBuilder any() {\n      return defaultTemplateProvider.get();\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   /**\n    * @since 1.5\n    */\n   protected ToStringHelper string() {\n      ToStringHelper toString = MoreObjects.toStringHelper(\"\").omitNullValues();\n      if (biggest)\n         toString.add(\"biggest\", biggest);\n      if (fastest)\n         toString.add(\"fastest\", fastest);\n      toString.add(\"imageName\", imageName);\n      toString.add(\"imageDescription\", imageDescription);\n      toString.add(\"imageId\", imageId);\n      toString.add(\"imagePredicate\", imagePredicate);\n      toString.add(\"imageChooser\", imageChooser);\n      toString.add(\"imageVersion\", imageVersion);\n      if (location != null)\n         toString.add(\"locationId\", location.getId());\n      if (minCores > 0) //TODO: make non-primitive\n         toString.add(\"minCores\", minCores);\n      if (minRam > 0) //TODO: make non-primitive\n         toString.add(\"minRam\", minRam);\n      if (minRam > 0) //TODO: make non-primitive\n         toString.add(\"minRam\", minRam);\n      if (minDisk > 0) //TODO: make non-primitive\n         toString.add(\"minDisk\", minDisk);\n      toString.add(\"osFamily\", osFamily);\n      toString.add(\"osName\", osName);\n      toString.add(\"osDescription\", osDescription);\n      toString.add(\"osVersion\", osVersion);\n      toString.add(\"osArch\", osArch);\n      toString.add(\"os64Bit\", os64Bit);\n      toString.add(\"hardwareId\", hardwareId);\n      toString.add(\"hypervisor\", hypervisor);\n      toString.add(\"forceCacheReload\", forceCacheReload);\n      return toString;\n   }\n\n   @Override\n   public TemplateBuilder os64Bit(boolean is64Bit) {\n      this.os64Bit = is64Bit;\n      return this;\n   }\n\n   @Override\n   public TemplateBuilder from(TemplateBuilderSpec spec) {\n      return spec.copyTo(this, options != null ? options : (options = optionsProvider.get()));\n   }\n\n   @Override\n   public TemplateBuilder from(String spec) {\n      return from(TemplateBuilderSpec.parse(spec));\n   }\n\n   @Override\n   public TemplateBuilder forceCacheReload() {\n      this.forceCacheReload = true;\n      return this;\n   }\n\n   \n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/domain/internal/TemplateImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.domain.internal;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.domain.Location;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\npublic class TemplateImpl implements Template {\n\n   private final Image image;\n   private final Hardware hardware;\n   private final Location location;\n   private final TemplateOptions options;\n\n   public TemplateImpl(Image image, Hardware hardware, Location location, TemplateOptions options) {\n      this.image = checkNotNull(image, \"image\");\n      this.hardware = checkNotNull(hardware, \"hardware\");\n      this.location = checkNotNull(location, \"location\");\n      this.options = checkNotNull(options, \"options\");\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Image getImage() {\n      return image;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Hardware getHardware() {\n      return hardware;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Location getLocation() {\n      return location;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public TemplateOptions getOptions() {\n      return options;\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o)\n         return true;\n      if (o == null || getClass() != o.getClass())\n         return false;\n      TemplateImpl that = TemplateImpl.class.cast(o);\n      return equal(this.image, that.image) && equal(this.hardware, that.hardware)\n               && equal(this.location, that.location) && equal(this.options, that.options);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(image, hardware, location, options);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   protected ToStringHelper string() {\n      ToStringHelper helper = MoreObjects.toStringHelper(\"\").omitNullValues().add(\"image\", image).add(\"hardware\", hardware)\n               .add(\"location\", location);\n      if (!options.equals(defaultOptions()))\n         helper.add(\"options\", options);\n      return helper;\n   }\n\n   protected TemplateOptions defaultOptions() {\n      return TemplateOptions.NONE;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Template clone() {\n      return new TemplateImpl(image, hardware, location, options.clone());\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/domain/internal/VolumeImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.domain.internal;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.compute.domain.Volume;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\npublic class VolumeImpl implements Volume {\n\n   @Nullable\n   private final String id;\n   private final Volume.Type type;\n   @Nullable\n   private final Float size;\n   @Nullable\n   private final String device;\n   private final boolean bootDevice;\n   private final boolean durable;\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o)\n         return true;\n      if (o == null || getClass() != o.getClass())\n         return false;\n      VolumeImpl that = VolumeImpl.class.cast(o);\n      return equal(this.id, that.id) && equal(this.getType(), that.getType()) && equal(this.size, that.size)\n               && equal(this.device, that.device) && equal(this.bootDevice, that.bootDevice)\n               && equal(this.durable, that.durable);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, size, device, bootDevice, durable);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(\"\").omitNullValues().add(\"id\", id).add(\"type\", getType()).add(\"size\", size)\n               .add(\"device\", device).add(\"bootDevice\", bootDevice).add(\"durable\", durable);\n   }\n\n   public VolumeImpl(@Nullable String id, Volume.Type type, @Nullable Float size, @Nullable String device,\n            boolean bootDevice, boolean durable) {\n      this.id = id;\n      this.type = checkNotNull(type, \"type\");\n      this.size = size;\n      this.device = device;\n      this.bootDevice = bootDevice;\n      this.durable = durable;\n   }\n\n   public VolumeImpl(@Nullable Float size, boolean bootDevice, boolean durable) {\n      this(null, Volume.Type.LOCAL, size, null, bootDevice, durable);\n   }\n\n   public VolumeImpl(@Nullable Float size, @Nullable String device, boolean bootDevice, boolean durable) {\n      this(null, Volume.Type.LOCAL, size, device, bootDevice, durable);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getId() {\n      return id;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Volume.Type getType() {\n      return type;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Float getSize() {\n      return size;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getDevice() {\n      return device;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public boolean isDurable() {\n      return durable;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public boolean isBootDevice() {\n      return bootDevice;\n   }\n\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/events/InitScriptOnNodeSubmission.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.events;\n\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.scriptbuilder.InitScript;\n\nimport com.google.common.annotations.Beta;\n\n/**\n * An init script was submitted to a node for execution.\n * <p/>\n * Note this does not guarantee that there was success, nor that the init script started.\n */\n@Beta\npublic class InitScriptOnNodeSubmission extends StatementOnNodeSubmission {\n\n   public InitScriptOnNodeSubmission(InitScript statement, NodeMetadata node) {\n      super(statement, node);\n   }\n   \n   public InitScript getStatement() {\n      return InitScript.class.cast(statement);\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/events/StatementOnNode.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.events;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.scriptbuilder.domain.Statement;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n\n */\n@Beta\npublic class StatementOnNode {\n   protected final Statement statement;\n   protected final NodeMetadata node;\n\n   public StatementOnNode(Statement statement, NodeMetadata node) {\n      this.statement = checkNotNull(statement, \"statement\");\n      this.node = checkNotNull(node, \"node\");\n   }\n\n   public Statement getStatement() {\n      return statement;\n   }\n\n   public NodeMetadata getNode() {\n      return node;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(statement, node);\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (o == null)\n         return false;\n      if (!o.getClass().equals(getClass()))\n         return false;\n      StatementOnNode that = StatementOnNode.class.cast(o);\n      return Objects.equal(this.statement, that.statement) && Objects.equal(this.node, that.node);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this).add(\"statement\", statement).add(\"node\", node.getId());\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/events/StatementOnNodeCompletion.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.events;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.compute.domain.ExecResponse;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.scriptbuilder.domain.Statement;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * A statement that completed execution on a node.\n */\n@Beta\npublic class StatementOnNodeCompletion extends StatementOnNode {\n\n   private final ExecResponse response;\n\n   public StatementOnNodeCompletion(Statement statement, NodeMetadata node, ExecResponse response) {\n      super(statement, node);\n      this.response = checkNotNull(response, \"response\");\n   }\n\n   public ExecResponse getResponse() {\n      return response;\n   }\n   \n   @Override\n   protected ToStringHelper string() {\n      return super.string().add(\"response\", response);\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/events/StatementOnNodeFailure.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.events;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.scriptbuilder.domain.Statement;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * A statement that failed execution on a node.\n */\n@Beta\npublic class StatementOnNodeFailure extends StatementOnNode {\n\n   private final Throwable cause;\n\n   public StatementOnNodeFailure(Statement statement, NodeMetadata node, Throwable cause) {\n      super(statement, node);\n      this.cause = checkNotNull(cause, \"cause\");\n   }\n\n   public Throwable getCause() {\n      return cause;\n   }\n   \n   @Override\n   protected ToStringHelper string() {\n      return super.string().add(\"cause\", cause.getMessage());\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/events/StatementOnNodeSubmission.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.events;\n\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.scriptbuilder.domain.Statement;\n\nimport com.google.common.annotations.Beta;\n\n/**\n * A statement was submitted to a node for execution.\n * <p/>\n * Note this does not guarantee that there was success, nor that the node\n * received the statement.\n */\n@Beta\npublic class StatementOnNodeSubmission extends StatementOnNode {\n\n   public StatementOnNodeSubmission(Statement statement, NodeMetadata node) {\n      super(statement, node);\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/extensions/ImageExtension.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.extensions;\n\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.ImageTemplate;\n\nimport com.google.common.util.concurrent.ListenableFuture;\n\n/**\n * An extension to compute service to allow for the manipulation of {@link Image}s. Implementation\n * is optional by providers.\n */\npublic interface ImageExtension {\n\n   /**\n    * Build an ImageTemplate from a running node, to use later to create a new {@link Image}.\n    * \n    * @param name\n    *           name to give the new image\n    * \n    * @param id\n    *           node to base the template on\n    * @return an image template that can be used to create a new image\n    */\n   ImageTemplate buildImageTemplateFromNode(String name, String id);\n\n   /**\n    * Transform the {@link ImageTemplate} on an {@link Image} that can be used to create nodes.\n    * \n    * @param template\n    *           template to base the new image on\n    * @return the image that was just built *after* it is registered on the provider\n    */\n   ListenableFuture<Image> createImage(ImageTemplate template);\n\n   /**\n    * Delete an {@link Image} on the provider.\n    * \n    * @param id\n    *           the id of the image to delete\n    * @return\n    */\n   boolean deleteImage(String id);\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/extensions/SecurityGroupExtension.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.extensions;\n\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.SecurityGroup;\nimport org.jclouds.domain.Location;\nimport org.jclouds.net.domain.IpPermission;\nimport org.jclouds.net.domain.IpProtocol;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.collect.Multimap;\n\n/**\n * An extension to compute service to allow for the manipulation of {@link SecurityGroup}s. Implementation\n * is optional by providers.\n */\npublic interface SecurityGroupExtension {\n\n   /**\n    * List security groups.\n    *\n    * @return The set of @{link SecurityGroup}s we have access to.\n    */\n   Set<SecurityGroup> listSecurityGroups();\n\n   /**\n    * List security groups in a given @{link Location}.\n    *\n    * @return The set of @{link SecurityGroup}s we have access to in the given location.\n    */\n   Set<SecurityGroup> listSecurityGroupsInLocation(Location location);\n   \n   /**\n    * List security groups for a given instance given the instance's ID.\n    *\n    * @return The set of @{link SecurityGroup}s for the given instance..\n    */\n   Set<SecurityGroup> listSecurityGroupsForNode(String id);\n\n   /**\n    * Get a security group by id.\n    *\n    * @return The @{link SecurityGroup}, if it exists.\n    */\n   SecurityGroup getSecurityGroupById(String id);\n\n   /**\n    * Create a new @{link SecurityGroup} from the parameters given.\n    *\n    * @param name\n    *           The name of the security group\n    * @param location\n    *           The @{link Location} of the security group\n    *\n    * @return The SecurityGroup that has been created.\n    */\n   SecurityGroup createSecurityGroup(String name, Location location);\n\n   /**\n    * Remove an existing @{link SecurityGroup}, and its permissions.\n    *\n    * @param id\n    *           The id of the SecurityGroup to delete.\n    *\n    * @return true if we were able to remove the group, false otherwise.\n    */\n   boolean removeSecurityGroup(String id);\n\n   /**\n    * Add a @{link IpPermission} to an existing @{link SecurityGroup}. Applies the permission to the\n    *   security group on the provider.\n    *\n    * @param rule\n    *           The IpPermission to add.\n    * @param group\n    *           The SecurityGroup to add the permission to.\n    *\n    * @return The SecurityGroup with the new permission added, after the permission has been applied on the provider.\n    */\n   SecurityGroup addIpPermission(IpPermission ipPermission, SecurityGroup group);\n\n   /**\n    * Remove a @{link IpPermission} from an existing @{link SecurityGroup}. Removes the permission from the\n    *   security group on the provider.\n    *\n    * @param rule\n    *           The IpPermission to remove.\n    * @param group\n    *           The SecurityGroup to remove the permission from.\n    *\n    * @return The SecurityGroup with the permission removed, after the permission has been removed on the provider.\n    */\n   SecurityGroup removeIpPermission(IpPermission ipPermission, SecurityGroup group);\n\n   /**\n    * Add a @{link IpPermission} to an existing @{link SecurityGroup}, based on the parameters given.\n    *   Applies the permission to the security group on the provider.\n    *\n    * @param protocol\n    *           The @{link IpProtocol} for the permission.\n    * @param startPort\n    *           The first port in the range to be opened, or -1 for ICMP.\n    * @param endPort\n    *           The last port in the range to be opened, or -1 for ICMP.\n    * @param tenantIdGroupNamePairs\n    *           source of traffic allowed is on basis of another group in a tenant, as opposed to by cidr\n    * @param ipRanges\n    *           An Iterable of Strings representing the IP range(s) the permission should allow.\n    * @param groupIds\n    *           An Iterable of @{link SecurityGroup} IDs this permission should allow.\n    * @param group\n    *           The SecurityGroup to add the permission to.\n    *\n    * @return The SecurityGroup with the new permission added, after the permission has been applied on the provider.\n    */\n   SecurityGroup addIpPermission(IpProtocol protocol, int startPort, int endPort,\n                                 Multimap<String, String> tenantIdGroupNamePairs,\n                                 Iterable<String> ipRanges,\n                                 Iterable<String> groupIds, SecurityGroup group);\n\n   /**\n    * Remove a @{link IpPermission} from an existing @{link SecurityGroup}, based on the parameters given.\n    *   Removes the permission from the security group on the provider.\n    *\n    * @param protocol\n    *           The @{link IpProtocol} for the permission.\n    * @param startPort\n    *           The first port in the range to be opened, or -1 for ICMP.\n    * @param endPort\n    *           The last port in the range to be opened, or -1 for ICMP.\n    * @param tenantIdGroupNamePairs\n    *           source of traffic allowed is on basis of another group in a tenant, as opposed to by cidr\n    * @param ipRanges\n    *           An Iterable of Strings representing the IP range(s) the permission should allow.\n    * @param groupIds\n    *           An Iterable of @{link SecurityGroup} IDs this permission should allow.\n    * @param group\n    *           The SecurityGroup to remove the permission from.\n    *\n    * @return The SecurityGroup with the permission removed, after the permission has been removed from the provider.\n    */\n   SecurityGroup removeIpPermission(IpProtocol protocol, int startPort, int endPort,\n                                    Multimap<String, String> tenantIdGroupNamePairs,\n                                    Iterable<String> ipRanges,\n                                    Iterable<String> groupIds, SecurityGroup group);\n\n   /**\n    * Returns true if this SecurityGroupExtension supports tenant ID + group name pairs.\n    */\n   boolean supportsTenantIdGroupNamePairs();\n\n   /**\n    * Returns true if this SecurityGroupExtension supports tenant ID + group ID pairs.\n    */\n   boolean supportsTenantIdGroupIdPairs();\n\n\n   /**\n    * Returns true if this SecurityGroupExtension supports group IDs.\n    */\n   boolean supportsGroupIds();\n\n   /**\n    * Returns true if this SecurityGroupExtension supports port ranges for group authorization.\n    */\n   boolean supportsPortRangesForGroups();\n   \n   /**\n    * Returns true if this SecurityGroupExtension supports exclusion CIDR groups.\n    */\n   @Beta\n   boolean supportsExclusionCidrBlocks();\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/extensions/internal/DelegatingImageExtension.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.extensions.internal;\n\nimport java.util.Map;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\n\nimport org.jclouds.compute.config.ComputeServiceAdapterContextModule.AddDefaultCredentialsToImage;\nimport org.jclouds.compute.domain.CloneImageTemplate;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.ImageBuilder;\nimport org.jclouds.compute.domain.ImageTemplate;\nimport org.jclouds.compute.extensions.ImageExtension;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.compute.suppliers.ImageCacheSupplier;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Function;\nimport com.google.common.util.concurrent.FutureCallback;\nimport com.google.common.util.concurrent.Futures;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.MoreExecutors;\nimport com.google.inject.assistedinject.Assisted;\n\n/**\n * Delegates to the provider specific {@link ImageExtension} and takes care of\n * propagating the changes made to the images to the image cache.\n */\n@Beta\npublic class DelegatingImageExtension implements ImageExtension {\n\n   public interface Factory {\n      DelegatingImageExtension create(ImageCacheSupplier imageCache, ImageExtension delegate);\n   }\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   private final ImageCacheSupplier imageCache;\n   private final ImageExtension delegate;\n   private final AddDefaultCredentialsToImage addDefaultCredentialsToImage;\n   private final Map<String, Credentials> credentialStore;\n\n   @Inject\n   DelegatingImageExtension(@Assisted ImageCacheSupplier imageCache, @Assisted ImageExtension delegate,\n         AddDefaultCredentialsToImage addDefaultCredentialsToImage, Map<String, Credentials> credentialStore) {\n      this.imageCache = imageCache;\n      this.delegate = delegate;\n      this.addDefaultCredentialsToImage = addDefaultCredentialsToImage;\n      this.credentialStore = credentialStore;\n   }\n\n   public ImageTemplate buildImageTemplateFromNode(String name, String id) {\n      return delegate.buildImageTemplateFromNode(name, id);\n   }\n\n   public ListenableFuture<Image> createImage(final ImageTemplate template) {\n      ListenableFuture<Image> future = delegate.createImage(template);\n\n      // Populate the default image credentials, if missing\n      future = Futures.transform(future, new Function<Image, Image>() {\n         @Override\n         public Image apply(Image input) {\n            if (input.getDefaultCredentials() != null) {\n               return input;\n            }\n\n            // If the image has been created by cloning a node, then try to\n            // populate the known node credentials as the default image\n            // credentials\n            if (template instanceof CloneImageTemplate) {\n               final CloneImageTemplate cloneImageTemplate = (CloneImageTemplate) template;\n\n               Credentials nodeCredentials = credentialStore.get(\"node#\" + cloneImageTemplate.getSourceNodeId());\n               if (nodeCredentials != null) {\n                  logger.info(\">> Adding node(%s) credentials to image(%s)...\", cloneImageTemplate.getSourceNodeId(),\n                        cloneImageTemplate.getName());\n                  return ImageBuilder.fromImage(input)\n                        .defaultCredentials(LoginCredentials.fromCredentials(nodeCredentials)).build();\n               }\n            }\n\n            // If no credentials are known for the node, populate the default\n            // credentials using the defined strategy\n            logger.info(\">> Adding default image credentials to image(%s)...\", template.getName());\n            return addDefaultCredentialsToImage.apply(input);\n         }\n      }, MoreExecutors.directExecutor());\n\n      Futures.addCallback(future, new FutureCallback<Image>() {\n         @Override\n         public void onSuccess(Image result) {\n            imageCache.registerImage(result);\n         }\n\n         @Override\n         public void onFailure(Throwable t) {\n\n         }\n      }, MoreExecutors.directExecutor());\n      return future;\n   }\n\n   public boolean deleteImage(String id) {\n      boolean success = delegate.deleteImage(id);\n      if (success) {\n         imageCache.removeImage(id);\n      }\n      return success;\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/functions/CreateSshClientOncePortIsListeningOnNode.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkState;\n\nimport java.util.concurrent.TimeUnit;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.compute.reference.ComputeServiceConstants.Timeouts;\nimport org.jclouds.compute.util.OpenSocketFinder;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.ssh.SshClient;\n\nimport com.google.common.base.Function;\nimport com.google.common.net.HostAndPort;\nimport com.google.inject.Inject;\n\n@Singleton\npublic class CreateSshClientOncePortIsListeningOnNode implements Function<NodeMetadata, SshClient> {\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   @Inject(optional = true)\n   SshClient.Factory sshFactory;\n\n   private final OpenSocketFinder openSocketFinder;\n\n   private final long timeoutMs;\n   \n   @Inject\n   public CreateSshClientOncePortIsListeningOnNode(OpenSocketFinder openSocketFinder, Timeouts timeouts) {\n      this.openSocketFinder = openSocketFinder;\n      this.timeoutMs = timeouts.portOpen;\n   }\n\n   @Override\n   public SshClient apply(NodeMetadata node) {\n      checkState(sshFactory != null, \"ssh requested, but no SshModule configured\");\n      checkNotNull(node.getCredentials(), \"no credentials found for node %s\", node.getId());\n      checkNotNull(node.getCredentials().identity, \"no login identity found for node %s\", node.getId());\n      checkArgument(node.getCredentials().credential != null || sshFactory.isAgentAvailable(), \"no credential or ssh agent found for %s on node %s\", node\n               .getCredentials().identity, node.getId());\n      HostAndPort socket = openSocketFinder.findOpenSocketOnNode(node, node.getLoginPort(), \n               timeoutMs, TimeUnit.MILLISECONDS);\n      return sshFactory.create(socket, node.getCredentials());\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/functions/DefaultCredentialsFromImageOrOverridingCredentials.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.functions;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.options.RunScriptOptions;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.domain.LoginCredentials.Builder;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class DefaultCredentialsFromImageOrOverridingCredentials implements Function<Template, LoginCredentials> {\n\n   @Override\n   public LoginCredentials apply(Template template) {\n      RunScriptOptions options = template.getOptions();\n      LoginCredentials defaultCreds = template.getImage().getDefaultCredentials();\n      return overrideDefaultCredentialsWithOptionsIfPresent(defaultCreds, options);\n   }\n\n   public static LoginCredentials overrideDefaultCredentialsWithOptionsIfPresent(\n         @Nullable LoginCredentials defaultCreds, RunScriptOptions options) {\n      Builder builder = LoginCredentials.builder(defaultCreds);\n      if (options.getLoginUser() != null)\n         builder.user(options.getLoginUser());\n      if (options.getLoginPassword() != null)\n         builder.password(options.getLoginPassword());\n      if (options.getLoginPrivateKey() != null)\n         builder.privateKey(options.getLoginPrivateKey());\n      if (options.shouldAuthenticateSudo() != null)\n         builder.authenticateSudo(true);\n      return builder.build();\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/functions/GroupNamingConvention.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.functions;\n\nimport org.jclouds.compute.internal.FormatSharedNamesAndAppendUniqueStringToThoseWhichRepeat;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Predicate;\nimport com.google.inject.ImplementedBy;\n\n/**\n * jclouds needs to understand the difference between resources it creates and\n * those supplied by the user. For example, if jclouds creates a security group,\n * it should be able to delete this as a part of cleanup without accidentally\n * deleting resources the user specified manually.\n * \n * <h3>uniqueness of a name</h3>\n * \n * The naming convention must apply to both to resources shared across all\n * members of a group, and those created for a subset of members.\n * \n * <ol>\n * <li>shared: something shared across all members of a group, and fully\n * retrievable via api. Ex. security group or network</li>\n * <li>unique: something that only applies to individuals or subsets of a group,\n * or isn't fully retrievable via api. Ex. node names or keypair names</li>\n * </ol>\n * \n * <h4>why repeat?</h4>\n * \n * Some resources we'd otherwise want to share across a group must be\n * redundantly created, if the user has no access to the complete object via api\n * or otherwise. For example, ssh key apis generally do not store the private\n * key data on the server. In order to ensure we can always log into a server\n * without configuration, we may generate a temporary key on-demand for each\n * call to {@link ComputeService#createNodesInGroup}\n * \n * \n * Typically, a security group or network is something shared across all members\n * of a group, so the name should be concise, yet unique.\n * \n * <h2>implementation</h2>\n * \n * Typically, a security group or network is something shared across all members\n * of a group, so the name should be concise, yet unique.\n * \n * <h4>character sets and delimiters</h4>\n * \n * Character sets in apis are often bound to dns names, perhaps also allowing\n * underscores. Since jclouds groups are allowed to be alphanumeric with hyphens\n * (hostname style), care must be taken to implement this in a way that allows\n * the delimiter to be also nested in the group name itself. In other words, we\n * need to be able to encode a group into a name even when they share the same\n * character set. Note that characters like {@code #} can sometimes break apis.\n * As such, you may end preferring always using a hyphen.\n * \n * <h4>shared resources</h4>\n * \n * A good name for a shared resources might include a prefix of jclouds, a\n * delimiter of {@code -} followed by the group name. The jclouds prefix\n * signifies this resource is safe to delete, and the hash clearly delineates\n * the encoding from what's in the group name.\n * \n * <h3>example</h3>\n * \n * given a jclouds group named {@code mycluster}, the naming convention for\n * shared resources would produce {@code jclouds-mycluster}\n * \n * <h4>unique resources</h4>\n * \n * A good name for a unique resource might be the same as the shared, with a\n * random hex string suffix. A few hex characters can give you 4096\n * combinations, giving a small degree of collision avoidance, yet without\n * making the resource name difficult.\n * \n * <h3>example</h3>\n * \n * given a jclouds group named {@code mycluster}, the naming convention for\n * unique resources could produce {@code jclouds-mycluster-f3e} the first time,\n * and {@code jclouds-mycluster-e64} the next.\n * \n * <h3>note</h3>\n * \n * It is typically safe to assume that an {@link IllegalStateException} is\n * thrown when attempting to create a named resource which already exists.\n * However, if you attempt to create a resource with a name generated by\n * {@link GroupNamingConvention}, and receive an {@link IllegalStateException},\n * it may have been for another reason besides name conflict.\n */\n@Beta\npublic interface GroupNamingConvention {\n\n   @ImplementedBy(FormatSharedNamesAndAppendUniqueStringToThoseWhichRepeat.Factory.class)\n   public interface Factory {\n\n      GroupNamingConvention create();\n\n      /**\n       * top-level resources do not need a prefix, yet still may need to follow\n       * a naming convention\n       */\n      GroupNamingConvention createWithoutPrefix();\n\n   }\n\n   /**\n    * encodes the {code group parameter} into a name that exists only once in\n    * the group.\n    * \n    */\n   String sharedNameForGroup(String group);\n\n   /**\n    * encodes the {code group parameter} into a name that exists more than once\n    * in the group.\n    * \n    * <h3>note</h3>\n    * \n    * Do not expect this name to be guaranteed unique, though a good\n    * implementation should guess a unique name in one or two tries.\n    */\n   String uniqueNameForGroup(String group);\n\n   /**\n    * retrieve the group associated with the encoded name\n    * \n    */\n   @Nullable\n   String groupInUniqueNameOrNull(String encoded);\n\n   /**\n    * retrieve the group associated with the encoded name\n    * \n    */\n   @Nullable\n   String groupInSharedNameOrNull(String encoded);\n\n   /**\n    * A predicate that identifies if an input has the given group encoded in it.\n    */\n   Predicate<String> containsGroup(String group);\n\n   /**\n    * A predicate that identifies if an input has any group encoded in it.\n    */\n   Predicate<String> containsAnyGroup();\n   \n   /**\n    * Extracts the group from a shared/unique name. Or returns null if not in correct format to contain a group.\n    */\n   String extractGroup(String encoded);\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/functions/InstallKeysAndRunScript.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.functions;\n\nimport static com.google.common.collect.Lists.newArrayList;\n\nimport java.util.List;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.scriptbuilder.InitScript;\nimport org.jclouds.scriptbuilder.domain.Statement;\nimport org.jclouds.scriptbuilder.domain.StatementList;\nimport org.jclouds.scriptbuilder.statements.ssh.AuthorizeRSAPublicKeys;\nimport org.jclouds.scriptbuilder.statements.ssh.InstallRSAPrivateKey;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Singleton\npublic class InstallKeysAndRunScript implements NodeAndTemplateOptionsToStatement {\n\n   @Override\n   public Statement apply(NodeMetadata node, TemplateOptions options) {\n      String user = options.getLoginUser();\n      if (user == null && node.getCredentials() != null) {\n         user = node.getCredentials().getUser();\n      }\n      List<Statement> bootstrap = newArrayList();\n      if (options.getPublicKey() != null)\n         bootstrap.add(new AuthorizeRSAPublicKeys(ImmutableSet.of(options.getPublicKey()), user));\n      if (options.getRunScript() != null)\n         bootstrap.add(options.getRunScript());\n      if (options.getPrivateKey() != null)\n         bootstrap.add(new InstallRSAPrivateKey(options.getPrivateKey()));\n      if (bootstrap.size() >= 1) {\n         if (options.getTaskName() == null && !(options.getRunScript() instanceof InitScript))\n            options.nameTask(\"bootstrap\");\n         return bootstrap.size() == 1 ? bootstrap.get(0) : new StatementList(bootstrap);\n      }\n      return null;\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/functions/NodeAndTemplateOptionsToStatement.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.functions;\n\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.scriptbuilder.domain.Statement;\n\nimport com.google.inject.ImplementedBy;\n\n/**\n * Returns the statement to be executed on the node.\n */\n@ImplementedBy(InstallKeysAndRunScript.class)\npublic interface NodeAndTemplateOptionsToStatement {\n\n   /**\n    * Returns the script that has to be executed in the given node.\n    * \n    * @return The script to be executed or <code>null</code> if no script needs\n    *         to be run.\n    */\n   @Nullable\n   Statement apply(NodeMetadata node, TemplateOptions options);\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/functions/NodeAndTemplateOptionsToStatementWithoutPublicKey.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.functions;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.scriptbuilder.InitScript;\nimport org.jclouds.scriptbuilder.domain.Statement;\nimport org.jclouds.scriptbuilder.domain.StatementList;\nimport org.jclouds.scriptbuilder.statements.ssh.InstallRSAPrivateKey;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Convert the node and template options into a statement, but ignoring the\n * public key.\n * <p>\n * Providers that can install the public key using their API should bind this\n * strategy to avoid an unnecessary SSH connection to manually upload it.\n */\n@Singleton\npublic class NodeAndTemplateOptionsToStatementWithoutPublicKey implements NodeAndTemplateOptionsToStatement {\n\n   @Override\n   public Statement apply(NodeMetadata node, TemplateOptions options) {\n      ImmutableList.Builder<Statement> builder = ImmutableList.builder();\n      if (options.getRunScript() != null) {\n         builder.add(options.getRunScript());\n      }\n      if (options.getPrivateKey() != null) {\n         builder.add(new InstallRSAPrivateKey(options.getPrivateKey()));\n      }\n\n      ImmutableList<Statement> bootstrap = builder.build();\n      if (!bootstrap.isEmpty()) {\n         if (options.getTaskName() == null && !(options.getRunScript() instanceof InitScript)) {\n            options.nameTask(\"bootstrap\");\n         }\n         return bootstrap.size() == 1 ? bootstrap.get(0) : new StatementList(bootstrap);\n      }\n\n      return null;\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/functions/PollNodeRunning.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Throwables.propagate;\nimport static java.lang.String.format;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_RUNNING;\nimport static org.jclouds.compute.util.ComputeServiceUtils.formatStatus;\n\nimport java.util.concurrent.atomic.AtomicReference;\nimport java.util.concurrent.TimeUnit;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\n\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadata.Status;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Stopwatch;\n\n/**\n * Polls until the node is running or throws {@link IllegalStateException} if\n * this cannot be achieved within the timeout.\n */\n@Named(TIMEOUT_NODE_RUNNING)\npublic class PollNodeRunning implements Function<AtomicReference<NodeMetadata>, AtomicReference<NodeMetadata>> {\n   private final Predicate<AtomicReference<NodeMetadata>> nodeRunning;\n\n   @Inject\n   public PollNodeRunning(@Named(TIMEOUT_NODE_RUNNING) Predicate<AtomicReference<NodeMetadata>> nodeRunning) {\n      this.nodeRunning = checkNotNull(nodeRunning, \"nodeRunning\");\n   }\n\n   /**\n    * @param node\n    *           will be updated with the node which is running\n    * @throws {@link IllegalStateException} if this cannot be achieved within\n    *         the timeout.\n    */\n   @Override\n   public AtomicReference<NodeMetadata> apply(AtomicReference<NodeMetadata> node) throws IllegalStateException {\n      String originalId = node.get().getId();\n      NodeMetadata originalNode = node.get();\n      try {\n         Stopwatch stopwatch = Stopwatch.createStarted();\n         if (!nodeRunning.apply(node)) {\n            long timeWaited = stopwatch.elapsed(TimeUnit.MILLISECONDS);\n            if (node.get() == null) {\n               node.set(originalNode);\n               throw new IllegalStateException(format(\"api response for node(%s) was null\", originalId));\n            } else {\n               throw new IllegalStateException(format(\n                     \"node(%s) didn't achieve the status running; aborting after %d seconds with final status: %s\",\n                     originalId, timeWaited / 1000, formatStatus(node.get())));\n            }\n         }\n      } catch (IllegalStateException e) {\n         if (node.get().getStatus() == Status.TERMINATED) {\n            throw new IllegalStateException(format(\"node(%s) terminated\", originalId));\n         } else {\n            throw propagate(e);\n         }\n      }\n      return node;\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/functions/Sha512Crypt.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/*\n   Sha512Crypt.java\n\n   Created: 18 December 2007\n   Last Changed By: $Author: broccol $\n   Version: $Revision: 7692 $\n   Last Mod Date: $Date: 2007-12-30 01:55:31 -0600 (Sun, 30 Dec 2007) $\n\n   Java Port By: James Ratcliff, falazar@arlut.utexas.edu\n\n   This class implements the new generation, scalable, SHA512-based\n   Unix 'crypt' algorithm developed by a group of engineers from Red\n   Hat, Sun, IBM, and HP for common use in the Unix and Linux\n   /etc/shadow files.\n\n   The Linux glibc library (starting at version 2.7) includes support\n   for validating passwords hashed using this algorithm.\n\n   The algorithm itself was released into the Public Domain by Ulrich\n   Drepper <drepper@redhat.com>.  A discussion of the rationale and\n   development of this algorithm is at\n\n   http://people.redhat.com/drepper/sha-crypt.html\n\n   and the specification and a sample C language implementation is at\n\n   http://people.redhat.com/drepper/SHA-crypt.txt\n\n   This Java Port is  \n\n     Copyright (c) 2008 The University of Texas at Austin.\n\n     All rights reserved.\n\n     Redistribution and use in source and binary form are permitted\n     provided that distributions retain this entire copyright notice\n     and comment. Neither the name of the University nor the names of\n     its contributors may be used to endorse or promote products\n     derived from this software without specific prior written\n     permission. THIS SOFTWARE IS PROVIDED \"AS IS\" AND WITHOUT ANY\n     EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE\n     IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n     PARTICULAR PURPOSE.\n\n */\n\npackage org.jclouds.compute.functions;\n\nimport java.security.MessageDigest;\nimport java.security.NoSuchAlgorithmException;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.Throwables;\n\n/**\n * This class defines a method,\n * {@link Sha512Crypt#Sha512_crypt(java.lang.String, java.lang.String, int)\n * Sha512_crypt()}, which takes a password and a salt string and generates a\n * Sha512 encrypted password entry.\n * \n * This class implements the new generation, scalable, SHA512-based Unix 'crypt'\n * algorithm developed by a group of engineers from Red Hat, Sun, IBM, and HP\n * for common use in the Unix and Linux /etc/shadow files.\n * \n * The Linux glibc library (starting at version 2.7) includes support for\n * validating passwords hashed using this algorithm.\n * \n * The algorithm itself was released into the Public Domain by Ulrich Drepper\n * &lt;drepper@redhat.com&gt;. A discussion of the rationale and development of\n * this algorithm is at\n * \n * http://people.redhat.com/drepper/sha-crypt.html\n * \n * and the specification and a sample C language implementation is at\n * \n * http://people.redhat.com/drepper/SHA-crypt.txt\n */\npublic class Sha512Crypt {\n   public static com.google.common.base.Function<String, String> function() {\n      return Function.INSTANCE;\n   }\n\n   private static enum Function implements com.google.common.base.Function<String, String> {\n      INSTANCE;\n\n      @Override\n      public String apply(String input) {\n         return Sha512Crypt.makeShadowLine(input, null);\n      }\n\n      @Override\n      public String toString() {\n         return \"sha512Crypt()\";\n      }\n   }\n\n   private static final String sha512_salt_prefix = \"$6$\";\n   private static final String sha512_rounds_prefix = \"rounds=\";\n   private static final int SALT_LEN_MAX = 16;\n   private static final int ROUNDS_DEFAULT = 5000;\n   private static final int ROUNDS_MIN = 1000;\n   private static final int ROUNDS_MAX = 999999999;\n   private static final String SALTCHARS = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890\";\n   private static final String itoa64 = \"./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\n   /**\n    * This method actually generates an Sha512 crypted password hash from a\n    * plaintext password and a salt.\n    * \n    * <p>\n    * The resulting string will be in the form\n    * '$6$&lt;rounds=n&gt;$&lt;salt&gt;$&lt;hashed mess&gt;\n    * </p>\n    * \n    * @param password\n    *           Plaintext password\n    * \n    * @param shadowPrefix\n    *           An encoded salt/rounds which will be consulted to determine the\n    *           salt and round count, if not null\n    * \n    * @return The Sha512 Unix Crypt hash text for the password\n    */\n   static String makeShadowLine(String password, @Nullable String shadowPrefix) {\n      MessageDigest ctx = sha512();\n      MessageDigest alt_ctx = sha512();\n\n      byte[] alt_result;\n      byte[] temp_result;\n      byte[] p_bytes = null;\n      byte[] s_bytes = null;\n      int cnt;\n      int cnt2;\n      int rounds = ROUNDS_DEFAULT; // Default number of rounds.\n      StringBuilder buffer;\n\n      /* -- */\n\n      if (shadowPrefix != null) {\n         if (shadowPrefix.startsWith(sha512_salt_prefix)) {\n            shadowPrefix = shadowPrefix.substring(sha512_salt_prefix.length());\n         }\n\n         if (shadowPrefix.startsWith(sha512_rounds_prefix)) {\n            String num = shadowPrefix.substring(sha512_rounds_prefix.length(), shadowPrefix.indexOf('$'));\n            int srounds = Integer.parseInt(num);\n            shadowPrefix = shadowPrefix.substring(shadowPrefix.indexOf('$') + 1);\n            rounds = Math.max(ROUNDS_MIN, Math.min(srounds, ROUNDS_MAX));\n         }\n\n         if (shadowPrefix.length() > SALT_LEN_MAX) {\n            shadowPrefix = shadowPrefix.substring(0, SALT_LEN_MAX);\n         }\n      } else {\n         java.util.Random randgen = new java.security.SecureRandom();\n         StringBuilder saltBuf = new StringBuilder();\n\n         while (saltBuf.length() < 16) {\n            int index = (int) (randgen.nextFloat() * SALTCHARS.length());\n            saltBuf.append(SALTCHARS, index, index + 1);\n         }\n\n         shadowPrefix = saltBuf.toString();\n      }\n\n      byte[] key = password.getBytes();\n      byte[] salts = shadowPrefix.getBytes();\n\n      ctx.reset();\n      ctx.update(key, 0, key.length);\n      ctx.update(salts, 0, salts.length);\n\n      alt_ctx.reset();\n      alt_ctx.update(key, 0, key.length);\n      alt_ctx.update(salts, 0, salts.length);\n      alt_ctx.update(key, 0, key.length);\n\n      alt_result = alt_ctx.digest();\n\n      for (cnt = key.length; cnt > 64; cnt -= 64) {\n         ctx.update(alt_result, 0, 64);\n      }\n\n      ctx.update(alt_result, 0, cnt);\n\n      for (cnt = key.length; cnt > 0; cnt >>= 1) {\n         if ((cnt & 1) != 0) {\n            ctx.update(alt_result, 0, 64);\n         } else {\n            ctx.update(key, 0, key.length);\n         }\n      }\n\n      alt_result = ctx.digest();\n\n      alt_ctx.reset();\n\n      for (cnt = 0; cnt < key.length; ++cnt) {\n         alt_ctx.update(key, 0, key.length);\n      }\n\n      temp_result = alt_ctx.digest();\n\n      p_bytes = new byte[key.length];\n\n      for (cnt2 = 0, cnt = p_bytes.length; cnt >= 64; cnt -= 64) {\n         System.arraycopy(temp_result, 0, p_bytes, cnt2, 64);\n         cnt2 += 64;\n      }\n\n      System.arraycopy(temp_result, 0, p_bytes, cnt2, cnt);\n\n      alt_ctx.reset();\n\n      for (cnt = 0; cnt < 16 + (alt_result[0] & 0xFF); ++cnt) {\n         alt_ctx.update(salts, 0, salts.length);\n      }\n\n      temp_result = alt_ctx.digest();\n\n      s_bytes = new byte[salts.length];\n\n      for (cnt2 = 0, cnt = s_bytes.length; cnt >= 64; cnt -= 64) {\n         System.arraycopy(temp_result, 0, s_bytes, cnt2, 64);\n         cnt2 += 64;\n      }\n\n      System.arraycopy(temp_result, 0, s_bytes, cnt2, cnt);\n\n      /*\n       * Repeatedly run the collected hash value through SHA512 to burn CPU\n       * cycles.\n       */\n\n      for (cnt = 0; cnt < rounds; ++cnt) {\n         ctx.reset();\n\n         if ((cnt & 1) != 0) {\n            ctx.update(p_bytes, 0, key.length);\n         } else {\n            ctx.update(alt_result, 0, 64);\n         }\n\n         if (cnt % 3 != 0) {\n            ctx.update(s_bytes, 0, salts.length);\n         }\n\n         if (cnt % 7 != 0) {\n            ctx.update(p_bytes, 0, key.length);\n         }\n\n         if ((cnt & 1) != 0) {\n            ctx.update(alt_result, 0, 64);\n         } else {\n            ctx.update(p_bytes, 0, key.length);\n         }\n\n         alt_result = ctx.digest();\n      }\n\n      buffer = new StringBuilder(sha512_salt_prefix);\n\n      if (rounds != 5000) {\n         buffer.append(sha512_rounds_prefix);\n         buffer.append(rounds);\n         buffer.append(\"$\");\n      }\n\n      buffer.append(shadowPrefix);\n      buffer.append(\"$\");\n\n      buffer.append(b64_from_24bit(alt_result[0], alt_result[21], alt_result[42], 4));\n      buffer.append(b64_from_24bit(alt_result[22], alt_result[43], alt_result[1], 4));\n      buffer.append(b64_from_24bit(alt_result[44], alt_result[2], alt_result[23], 4));\n      buffer.append(b64_from_24bit(alt_result[3], alt_result[24], alt_result[45], 4));\n      buffer.append(b64_from_24bit(alt_result[25], alt_result[46], alt_result[4], 4));\n      buffer.append(b64_from_24bit(alt_result[47], alt_result[5], alt_result[26], 4));\n      buffer.append(b64_from_24bit(alt_result[6], alt_result[27], alt_result[48], 4));\n      buffer.append(b64_from_24bit(alt_result[28], alt_result[49], alt_result[7], 4));\n      buffer.append(b64_from_24bit(alt_result[50], alt_result[8], alt_result[29], 4));\n      buffer.append(b64_from_24bit(alt_result[9], alt_result[30], alt_result[51], 4));\n      buffer.append(b64_from_24bit(alt_result[31], alt_result[52], alt_result[10], 4));\n      buffer.append(b64_from_24bit(alt_result[53], alt_result[11], alt_result[32], 4));\n      buffer.append(b64_from_24bit(alt_result[12], alt_result[33], alt_result[54], 4));\n      buffer.append(b64_from_24bit(alt_result[34], alt_result[55], alt_result[13], 4));\n      buffer.append(b64_from_24bit(alt_result[56], alt_result[14], alt_result[35], 4));\n      buffer.append(b64_from_24bit(alt_result[15], alt_result[36], alt_result[57], 4));\n      buffer.append(b64_from_24bit(alt_result[37], alt_result[58], alt_result[16], 4));\n      buffer.append(b64_from_24bit(alt_result[59], alt_result[17], alt_result[38], 4));\n      buffer.append(b64_from_24bit(alt_result[18], alt_result[39], alt_result[60], 4));\n      buffer.append(b64_from_24bit(alt_result[40], alt_result[61], alt_result[19], 4));\n      buffer.append(b64_from_24bit(alt_result[62], alt_result[20], alt_result[41], 4));\n      buffer.append(b64_from_24bit((byte) 0x00, (byte) 0x00, alt_result[63], 2));\n\n      /*\n       * Clear the buffer for the intermediate result so that people attaching\n       * to processes or reading core dumps cannot get any information.\n       */\n\n      ctx.reset();\n\n      return buffer.toString();\n   }\n\n   private static MessageDigest sha512() {\n      try {\n         return MessageDigest.getInstance(\"SHA-512\");\n      } catch (NoSuchAlgorithmException e) {\n         throw Throwables.propagate(e);\n      }\n   }\n\n   private static String b64_from_24bit(byte B2, byte B1, byte B0, int size) {\n      int v = ((((int) B2) & 0xFF) << 16) | ((((int) B1) & 0xFF) << 8) | ((int) B0 & 0xff);\n\n      StringBuilder result = new StringBuilder();\n\n      while (--size >= 0) {\n         result.append(itoa64.charAt(v & 0x3f));\n         v >>>= 6;\n      }\n\n      return result.toString();\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/internal/BaseComputeService.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.internal;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Predicates.and;\nimport static com.google.common.base.Predicates.not;\nimport static com.google.common.base.Predicates.notNull;\nimport static com.google.common.base.Throwables.propagate;\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Maps.newLinkedHashMap;\nimport static com.google.common.collect.Sets.newLinkedHashSet;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_RUNNING;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_SUSPENDED;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_TERMINATED;\nimport static org.jclouds.compute.predicates.NodePredicates.TERMINATED;\nimport static org.jclouds.compute.predicates.NodePredicates.all;\nimport static org.jclouds.compute.util.ComputeServiceUtils.formatStatus;\nimport static org.jclouds.concurrent.FutureIterables.awaitCompletion;\nimport static org.jclouds.concurrent.FutureIterables.transformParallel;\n\nimport java.util.Map;\nimport java.util.NoSuchElementException;\nimport java.util.Set;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.TimeoutException;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Provider;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Constants;\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.ComputeService;\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.compute.RunNodesException;\nimport org.jclouds.compute.RunScriptOnNodesException;\nimport org.jclouds.compute.callables.RunScriptOnNode;\nimport org.jclouds.compute.config.CustomizationResponse;\nimport org.jclouds.compute.domain.ComputeMetadata;\nimport org.jclouds.compute.domain.ExecResponse;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadata.Status;\nimport org.jclouds.compute.domain.NodeMetadataBuilder;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.domain.TemplateBuilder;\nimport org.jclouds.compute.extensions.ImageExtension;\nimport org.jclouds.compute.extensions.SecurityGroupExtension;\nimport org.jclouds.compute.extensions.internal.DelegatingImageExtension;\nimport org.jclouds.compute.options.RunScriptOptions;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.compute.strategy.CreateNodesInGroupThenAddToSet;\nimport org.jclouds.compute.strategy.DestroyNodeStrategy;\nimport org.jclouds.compute.strategy.GetImageStrategy;\nimport org.jclouds.compute.strategy.GetNodeMetadataStrategy;\nimport org.jclouds.compute.strategy.InitializeRunScriptOnNodeOrPlaceInBadMap;\nimport org.jclouds.compute.strategy.ListNodesStrategy;\nimport org.jclouds.compute.strategy.RebootNodeStrategy;\nimport org.jclouds.compute.strategy.ResumeNodeStrategy;\nimport org.jclouds.compute.strategy.RunScriptOnNodeAndAddToGoodMapOrPutExceptionIntoBadMap;\nimport org.jclouds.compute.strategy.SuspendNodeStrategy;\nimport org.jclouds.compute.suppliers.ImageCacheSupplier;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.domain.LoginCredentials.Builder;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.scriptbuilder.domain.Statement;\nimport org.jclouds.scriptbuilder.domain.Statements;\nimport org.jclouds.scriptbuilder.functions.InitAdminAccess;\nimport org.jclouds.util.Maps2;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.LinkedHashMultimap;\nimport com.google.common.collect.Multimap;\nimport com.google.common.util.concurrent.Atomics;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.ListeningExecutorService;\n\n@Singleton\npublic class BaseComputeService implements ComputeService {\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   protected final ComputeServiceContext context;\n   protected final Map<String, Credentials> credentialStore;\n\n   private final Supplier<Set<? extends Image>> images;\n   private final Supplier<Set<? extends Hardware>> hardwareProfiles;\n   private final Supplier<Set<? extends Location>> locations;\n   private final GetImageStrategy getImageStrategy;\n   private final ListNodesStrategy listNodesStrategy;\n   private final GetNodeMetadataStrategy getNodeMetadataStrategy;\n   private final CreateNodesInGroupThenAddToSet runNodesAndAddToSetStrategy;\n   private final RebootNodeStrategy rebootNodeStrategy;\n   private final DestroyNodeStrategy destroyNodeStrategy;\n   private final ResumeNodeStrategy resumeNodeStrategy;\n   private final SuspendNodeStrategy suspendNodeStrategy;\n   private final Provider<TemplateBuilder> templateBuilderProvider;\n   private final Provider<TemplateOptions> templateOptionsProvider;\n   private final Predicate<AtomicReference<NodeMetadata>> nodeRunning;\n   private final Predicate<AtomicReference<NodeMetadata>> nodeTerminated;\n   private final Predicate<AtomicReference<NodeMetadata>> nodeSuspended;\n   private final InitializeRunScriptOnNodeOrPlaceInBadMap.Factory initScriptRunnerFactory;\n   private final InitAdminAccess initAdminAccess;\n   private final PersistNodeCredentials persistNodeCredentials;\n   private final RunScriptOnNode.Factory runScriptOnNodeFactory;\n   private final ListeningExecutorService userExecutor;\n   private final Optional<ImageExtension> imageExtension;\n   private final Optional<SecurityGroupExtension> securityGroupExtension;\n\n   @Inject\n   protected BaseComputeService(ComputeServiceContext context, Map<String, Credentials> credentialStore,\n            @Memoized Supplier<Set<? extends Image>> images,\n            @Memoized Supplier<Set<? extends Hardware>> hardwareProfiles,\n            @Memoized Supplier<Set<? extends Location>> locations, ListNodesStrategy listNodesStrategy,\n            GetImageStrategy getImageStrategy, GetNodeMetadataStrategy getNodeMetadataStrategy,\n            CreateNodesInGroupThenAddToSet runNodesAndAddToSetStrategy, RebootNodeStrategy rebootNodeStrategy,\n            DestroyNodeStrategy destroyNodeStrategy, ResumeNodeStrategy resumeNodeStrategy,\n            SuspendNodeStrategy suspendNodeStrategy, Provider<TemplateBuilder> templateBuilderProvider,\n            @Named(\"DEFAULT\") Provider<TemplateOptions> templateOptionsProvider,\n            @Named(TIMEOUT_NODE_RUNNING) Predicate<AtomicReference<NodeMetadata>> nodeRunning,\n            @Named(TIMEOUT_NODE_TERMINATED) Predicate<AtomicReference<NodeMetadata>> nodeTerminated,\n            @Named(TIMEOUT_NODE_SUSPENDED) Predicate<AtomicReference<NodeMetadata>> nodeSuspended,\n            InitializeRunScriptOnNodeOrPlaceInBadMap.Factory initScriptRunnerFactory, InitAdminAccess initAdminAccess,\n            RunScriptOnNode.Factory runScriptOnNodeFactory, PersistNodeCredentials persistNodeCredentials,\n            @Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor,\n            Optional<ImageExtension> imageExtension, Optional<SecurityGroupExtension> securityGroupExtension,\n            DelegatingImageExtension.Factory delegatingImageExtension) {\n      this.context = checkNotNull(context, \"context\");\n      this.credentialStore = checkNotNull(credentialStore, \"credentialStore\");\n      this.images = checkNotNull(images, \"images\");\n      this.hardwareProfiles = checkNotNull(hardwareProfiles, \"hardwareProfiles\");\n      this.locations = checkNotNull(locations, \"locations\");\n      this.getNodeMetadataStrategy = checkNotNull(getNodeMetadataStrategy, \"getNodeMetadataStrategy\");\n      this.listNodesStrategy = checkNotNull(listNodesStrategy, \"listNodesStrategy\");\n      this.getImageStrategy = checkNotNull(getImageStrategy, \"getImageStrategy\");\n      this.runNodesAndAddToSetStrategy = checkNotNull(runNodesAndAddToSetStrategy, \"runNodesAndAddToSetStrategy\");\n      this.rebootNodeStrategy = checkNotNull(rebootNodeStrategy, \"rebootNodeStrategy\");\n      this.resumeNodeStrategy = checkNotNull(resumeNodeStrategy, \"resumeNodeStrategy\");\n      this.suspendNodeStrategy = checkNotNull(suspendNodeStrategy, \"suspendNodeStrategy\");\n      this.destroyNodeStrategy = checkNotNull(destroyNodeStrategy, \"destroyNodeStrategy\");\n      this.templateBuilderProvider = checkNotNull(templateBuilderProvider, \"templateBuilderProvider\");\n      this.templateOptionsProvider = checkNotNull(templateOptionsProvider, \"templateOptionsProvider\");\n      this.nodeRunning = checkNotNull(nodeRunning, \"nodeRunning\");\n      this.nodeTerminated = checkNotNull(nodeTerminated, \"nodeTerminated\");\n      this.nodeSuspended = checkNotNull(nodeSuspended, \"nodeSuspended\");\n      this.initScriptRunnerFactory = checkNotNull(initScriptRunnerFactory, \"initScriptRunnerFactory\");\n      this.initAdminAccess = checkNotNull(initAdminAccess, \"initAdminAccess\");\n      this.runScriptOnNodeFactory = checkNotNull(runScriptOnNodeFactory, \"runScriptOnNodeFactory\");\n      this.persistNodeCredentials = checkNotNull(persistNodeCredentials, \"persistNodeCredentials\");\n      this.userExecutor = checkNotNull(userExecutor, \"userExecutor\");\n      this.securityGroupExtension = checkNotNull(securityGroupExtension, \"securityGroupExtension\");\n      if (imageExtension.isPresent() && images instanceof ImageCacheSupplier) {\n         this.imageExtension = Optional.<ImageExtension> of(delegatingImageExtension.create(\n               ImageCacheSupplier.class.cast(images), imageExtension.get()));\n      } else {\n         this.imageExtension = checkNotNull(imageExtension, \"imageExtension\");\n      }\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ComputeServiceContext getContext() {\n      return context;\n   }\n\n   @Override\n   public Set<? extends NodeMetadata> createNodesInGroup(String group, int count, Template template)\n         throws RunNodesException {\n      checkNotNull(group, \"group cannot be null\");\n      checkNotNull(template.getLocation(), \"location\");\n      logger.debug(\">> running %d node%s group(%s) location(%s) image(%s) hardwareProfile(%s) options(%s)\", count,\n            count > 1 ? \"s\" : \"\", group, template.getLocation().getId(), template.getImage().getId(), template\n                  .getHardware().getId(), template.getOptions());\n      Set<NodeMetadata> goodNodes = newLinkedHashSet();\n      Map<NodeMetadata, Exception> badNodes = newLinkedHashMap();\n      Multimap<NodeMetadata, CustomizationResponse> customizationResponses = LinkedHashMultimap.create();\n\n      if (template.getOptions().getRunScript() != null)\n         initAdminAccess.visit(template.getOptions().getRunScript());\n\n      Map<?, ListenableFuture<Void>> responses = runNodesAndAddToSetStrategy.execute(group, count, template, goodNodes, badNodes,\n            customizationResponses);\n      Map<?, Exception> executionExceptions;\n      try {\n         executionExceptions = awaitCompletion(responses, userExecutor, null, logger, \"createNodesInGroup(\" + group + \")\");\n      } catch (TimeoutException te) {\n         throw propagate(te);\n      }\n      Function<NodeMetadata, NodeMetadata> fn = persistNodeCredentials.always(template.getOptions().getRunScript());\n      badNodes = Maps2.transformKeys(badNodes, fn);\n      goodNodes = ImmutableSet.copyOf(Iterables.transform(goodNodes, fn));\n      if (!executionExceptions.isEmpty() || !badNodes.isEmpty()) {\n         throw new RunNodesException(group, count, template, goodNodes, executionExceptions, badNodes);\n      }\n      return goodNodes;\n   }\n\n   @Override\n   public Set<? extends NodeMetadata> createNodesInGroup(String group, int count, TemplateOptions templateOptions)\n         throws RunNodesException {\n      return createNodesInGroup(group, count, templateBuilder().any().options(templateOptions).build());\n   }\n\n   @Override\n   public Set<? extends NodeMetadata> createNodesInGroup(String group, int count) throws RunNodesException {\n      return createNodesInGroup(group, count, templateOptions());\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void destroyNode(String id) {\n      NodeMetadata destroyedNodeOrNull = doDestroyNode(id);\n      if (destroyedNodeOrNull != null)\n         cleanUpIncidentalResourcesOfDeadNodes(ImmutableSet.of(destroyedNodeOrNull));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Set<? extends NodeMetadata> destroyNodesMatching(Predicate<? super NodeMetadata> filter) {\n      logger.debug(\">> destroying nodes matching(%s)\", filter);\n      Set<NodeMetadata> destroyNodes = ImmutableSet.copyOf(transformParallel(nodesMatchingFilterAndNotTerminated(filter),\n            new Function<NodeMetadata, ListenableFuture<? extends NodeMetadata>>() {\n\n               // TODO make an async interface instead of re-wrapping\n               @Override\n               public ListenableFuture<NodeMetadata> apply(final NodeMetadata from) {\n                  return userExecutor.submit(new Callable<NodeMetadata>() {\n                     public NodeMetadata call() throws Exception {\n                        doDestroyNode(from.getId());\n                        return from;\n                     }\n                     public String toString() {\n                        return \"destroyNode(\" + from.getId() + \")\";\n                     }\n                  });\n               }\n\n            }, userExecutor, null, logger, \"destroyNodesMatching(\" + filter + \")\"));\n      logger.debug(\"<< destroyed(%d)\", destroyNodes.size());\n\n      cleanUpIncidentalResourcesOfDeadNodes(destroyNodes);\n      return destroyNodes;\n   }\n\n   /**\n    *\n    * @param id\n    * @return node that was deleted or null if it wasn't found\n    */\n   @Nullable\n   protected NodeMetadata doDestroyNode(final String id) {\n      checkNotNull(id, \"id\");\n      logger.debug(\">> destroying node(%s)\", id);\n      NodeMetadata nodeMetadata = destroyNodeStrategy.destroyNode(id);\n      if (nodeMetadata == null) return null;\n      final AtomicReference<NodeMetadata> node = Atomics.newReference(nodeMetadata);\n      boolean successful = node.get() == null || nodeTerminated.apply(node);\n      if (successful)\n         credentialStore.remove(\"node#\" + id);\n      logger.debug(\"<< destroyed node(%s) success(%s)\", id, successful);\n      return nodeMetadata;\n   }\n\n   protected void cleanUpIncidentalResourcesOfDeadNodes(Set<? extends NodeMetadata> deadNodes) {\n      // no-op; to be overridden\n   }\n\n   Iterable<? extends NodeMetadata> nodesMatchingFilterAndNotTerminated(Predicate<? super NodeMetadata> filter) {\n      return filter(detailsOnAllNodes(), and(checkNotNull(filter, \"filter\"), not(TERMINATED)));\n   }\n\n   /**\n    * @throws NoSuchElementException\n    *            if none found\n    */\n   Iterable<? extends NodeMetadata> nodesMatchingFilterAndNotTerminatedExceptionIfNotFound(\n         Predicate<? super NodeMetadata> filter) {\n      Iterable<? extends NodeMetadata> nodes = nodesMatchingFilterAndNotTerminated(filter);\n      if (Iterables.isEmpty(nodes))\n         throw new NoSuchElementException(\"no nodes matched filter: \" + filter);\n      return nodes;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Set<? extends ComputeMetadata> listNodes() {\n      logger.trace(\">> listing nodes\");\n      Set<? extends ComputeMetadata> set = newLinkedHashSet(listNodesStrategy.listNodes());\n      logger.trace(\"<< list(%d)\", set.size());\n      return set;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Set<? extends NodeMetadata> listNodesByIds(Iterable<String> ids) {\n      checkNotNull(ids, \"ids\");\n      logger.trace(\">> listing node with ids(%s)\", ids);\n      Set<? extends NodeMetadata> set = ImmutableSet.copyOf(listNodesStrategy.listNodesByIds(ids));\n      logger.trace(\"<< list(%d)\", set.size());\n      return set;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Set<? extends NodeMetadata> listNodesDetailsMatching(Predicate<? super NodeMetadata> filter) {\n      checkNotNull(filter, \"filter\");\n      logger.trace(\">> listing node details matching(%s)\", filter);\n      Set<? extends NodeMetadata> set = newLinkedHashSet(listNodesStrategy.listDetailsOnNodesMatching(filter));\n      logger.trace(\"<< list(%d)\", set.size());\n      return set;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Set<? extends Hardware> listHardwareProfiles() {\n      return hardwareProfiles.get();\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Set<? extends Image> listImages() {\n      return images.get();\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Set<? extends Location> listAssignableLocations() {\n      return locations.get();\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public TemplateBuilder templateBuilder() {\n      return templateBuilderProvider.get();\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public NodeMetadata getNodeMetadata(String id) {\n      checkNotNull(id, \"id\");\n      return getNodeMetadataStrategy.getNode(id);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Image getImage(String id) {\n      checkNotNull(id, \"id\");\n      return getImageStrategy.getImage(id);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void rebootNode(String id) {\n      checkNotNull(id, \"id\");\n      logger.debug(\">> rebooting node(%s)\", id);\n      AtomicReference<NodeMetadata> node = Atomics.newReference(rebootNodeStrategy.rebootNode(id));\n      boolean successful = nodeRunning.apply(node);\n      logger.debug(\"<< rebooted node(%s) success(%s)\", id, successful);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Set<? extends NodeMetadata> rebootNodesMatching(Predicate<? super NodeMetadata> filter) {\n      logger.debug(\">> rebooting nodes matching(%s)\", filter);\n      Set<NodeMetadata> rebootNodes = ImmutableSet.copyOf(transformParallel(nodesMatchingFilterAndNotTerminated(filter),\n            new Function<NodeMetadata, ListenableFuture<? extends NodeMetadata>>() {\n\n               // TODO make an async interface instead of re-wrapping\n               @Override\n               public ListenableFuture<NodeMetadata> apply(final NodeMetadata from) {\n                  return userExecutor.submit(new Callable<NodeMetadata>() {\n                     public NodeMetadata call() throws Exception {\n                        rebootNode(from.getId());\n                        return from;\n                     }\n                     public String toString() {\n                        return \"rebootNode(\" + from.getId() + \")\";\n                     }\n                  });\n               }\n\n            }, userExecutor, null, logger, \"rebootNodesMatching(\" + filter + \")\"));\n      logger.debug(\"<< rebooted(%d)\", rebootNodes.size());\n\n      return rebootNodes;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void resumeNode(String id) {\n      checkNotNull(id, \"id\");\n      logger.debug(\">> resuming node(%s)\", id);\n      AtomicReference<NodeMetadata> node = Atomics.newReference(resumeNodeStrategy.resumeNode(id));\n      boolean successful = nodeRunning.apply(node);\n      logger.debug(\"<< resumed node(%s) success(%s)\", id, successful);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Set<? extends NodeMetadata> resumeNodesMatching(Predicate<? super NodeMetadata> filter) {\n      logger.debug(\">> resuming nodes matching(%s)\", filter);\n      Set<NodeMetadata> resumeNodes = ImmutableSet.copyOf(transformParallel(nodesMatchingFilterAndNotTerminated(filter),\n            new Function<NodeMetadata, ListenableFuture<? extends NodeMetadata>>() {\n\n               // TODO make an async interface instead of re-wrapping\n               @Override\n               public ListenableFuture<NodeMetadata> apply(final NodeMetadata from) {\n                  return userExecutor.submit(new Callable<NodeMetadata>() {\n                     public NodeMetadata call() throws Exception {\n                        resumeNode(from.getId());\n                        return from;\n                     }\n                     public String toString() {\n                        return \"resumeNode(\" + from.getId() + \")\";\n                     }\n                  });\n               }\n\n            }, userExecutor, null, logger, \"resumeNodesMatching(\" + filter + \")\"));\n      logger.debug(\"<< resumed(%d)\", resumeNodes.size());\n\n      return resumeNodes;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void suspendNode(String id) {\n      checkNotNull(id, \"id\");\n      logger.debug(\">> suspending node(%s)\", id);\n      AtomicReference<NodeMetadata> node = Atomics.newReference(suspendNodeStrategy.suspendNode(id));\n      boolean successful = nodeSuspended.apply(node);\n      logger.debug(\"<< suspended node(%s) success(%s)\", id, successful);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Set<? extends NodeMetadata> suspendNodesMatching(Predicate<? super NodeMetadata> filter) {\n      logger.debug(\">> suspending nodes matching(%s)\", filter);\n      Set<NodeMetadata> suspendNodes = ImmutableSet.copyOf(transformParallel(nodesMatchingFilterAndNotTerminated(filter),\n            new Function<NodeMetadata, ListenableFuture<? extends NodeMetadata>>() {\n\n               // TODO make an async interface instead of re-wrapping\n               @Override\n               public ListenableFuture<NodeMetadata> apply(final NodeMetadata from) {\n                  return userExecutor.submit(new Callable<NodeMetadata>() {\n                     public NodeMetadata call() throws Exception {\n                        suspendNode(from.getId());\n                        return from;\n                     }\n                     public String toString() {\n                        return \"suspendNode(\" + from.getId() + \")\";\n                     }\n                  });\n               }\n\n            }, userExecutor, null, logger, \"suspendNodesMatching(\" + filter + \")\"));\n      logger.debug(\"<< suspended(%d)\", suspendNodes.size());\n\n      return suspendNodes;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Map<NodeMetadata, ExecResponse> runScriptOnNodesMatching(Predicate<? super NodeMetadata> filter, String runScript)\n         throws RunScriptOnNodesException {\n      return runScriptOnNodesMatching(filter, Statements.literal(checkNotNull(runScript, \"runScript\")));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Map<NodeMetadata, ExecResponse> runScriptOnNodesMatching(Predicate<? super NodeMetadata> filter, Statement runScript)\n         throws RunScriptOnNodesException {\n      return runScriptOnNodesMatching(filter, runScript, RunScriptOptions.NONE);\n   }\n\n   @Override\n   public Map<? extends NodeMetadata, ExecResponse> runScriptOnNodesMatching(Predicate<? super NodeMetadata> filter,\n         String runScript, RunScriptOptions options) throws RunScriptOnNodesException {\n      return runScriptOnNodesMatching(filter, Statements.literal(checkNotNull(runScript, \"runScript\")), options);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Map<NodeMetadata, ExecResponse> runScriptOnNodesMatching(Predicate<? super NodeMetadata> filter, Statement runScript,\n         RunScriptOptions options) throws RunScriptOnNodesException {\n\n      checkNotNull(filter, \"filter\");\n      checkNotNull(runScript, \"runScript\");\n      checkNotNull(options, \"options\");\n\n      Map<NodeMetadata, ExecResponse> goodNodes = newLinkedHashMap();\n      Map<NodeMetadata, Exception> badNodes = newLinkedHashMap();\n      Map<NodeMetadata, ListenableFuture<ExecResponse>> responses = newLinkedHashMap();\n      Map<?, Exception> exceptions = ImmutableMap.<Object, Exception> of();\n\n      initAdminAccess.visit(runScript);\n\n      Iterable<? extends RunScriptOnNode> scriptRunners = transformNodesIntoInitializedScriptRunners(\n            nodesMatchingFilterAndNotTerminatedExceptionIfNotFound(filter), runScript, options, badNodes);\n      if (!Iterables.isEmpty(scriptRunners)) {\n         for (RunScriptOnNode runner : scriptRunners) {\n            responses.put(runner.getNode(), userExecutor.submit(new RunScriptOnNodeAndAddToGoodMapOrPutExceptionIntoBadMap(\n                  runner, goodNodes, badNodes)));\n         }\n         try {\n            exceptions = awaitCompletion(responses, userExecutor, null, logger, \"runScriptOnNodesMatching(\" + filter + \")\");\n         } catch (TimeoutException te) {\n            throw propagate(te);\n         }\n      }\n\n      Function<NodeMetadata, NodeMetadata> fn = persistNodeCredentials.ifAdminAccess(runScript);\n      badNodes = Maps2.transformKeys(badNodes, fn);\n      goodNodes = Maps2.transformKeys(goodNodes, fn);\n\n      if (!exceptions.isEmpty() || !badNodes.isEmpty()) {\n         throw new RunScriptOnNodesException(runScript, options, goodNodes, exceptions, badNodes);\n      }\n      return goodNodes;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ExecResponse runScriptOnNode(String id, String runScript) {\n      return runScriptOnNode(id, runScript, RunScriptOptions.NONE);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ExecResponse runScriptOnNode(String id, String runScript, RunScriptOptions options) {\n      return runScriptOnNode(id, Statements.literal(checkNotNull(runScript, \"runScript\")), options);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ExecResponse runScriptOnNode(String id, Statement runScript) {\n      return runScriptOnNode(id, runScript, RunScriptOptions.NONE);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ExecResponse runScriptOnNode(String id, Statement runScript, RunScriptOptions options) {\n      NodeMetadata node = this.getNodeMetadata(id);\n      if (node == null)\n         throw new NoSuchElementException(id);\n      if (node.getStatus() != Status.RUNNING)\n         throw new IllegalStateException(\"node \" + id\n               + \" needs to be running before executing a script on it. current state: \" + formatStatus(node));\n      initAdminAccess.visit(runScript);\n      node = updateNodeWithCredentialsIfPresent(node, options);\n      ExecResponse response = runScriptOnNodeFactory.create(node, runScript, options).init().call();\n      persistNodeCredentials.ifAdminAccess(runScript).apply(node);\n      return response;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ListenableFuture<ExecResponse> submitScriptOnNode(String id, String runScript, RunScriptOptions options) {\n      return submitScriptOnNode(id, Statements.literal(checkNotNull(runScript, \"runScript\")), options);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ListenableFuture<ExecResponse> submitScriptOnNode(String id, final Statement runScript,\n         RunScriptOptions options) {\n      NodeMetadata node = this.getNodeMetadata(id);\n      if (node == null)\n         throw new NoSuchElementException(id);\n      if (node.getStatus() != Status.RUNNING)\n         throw new IllegalStateException(\"node \" + id\n               + \" needs to be running before executing a script on it. current state: \" + formatStatus(node));\n      initAdminAccess.visit(runScript);\n      final NodeMetadata node1 = updateNodeWithCredentialsIfPresent(node, options);\n      ListenableFuture<ExecResponse> response = runScriptOnNodeFactory.submit(node1, runScript, options);\n      response.addListener(new Runnable() {\n         public void run() {\n            persistNodeCredentials.ifAdminAccess(runScript).apply(node1);\n         }\n      }, userExecutor);\n      return response;\n   }\n\n   private Iterable<RunScriptOnNode> transformNodesIntoInitializedScriptRunners(\n         Iterable<? extends NodeMetadata> nodes, Statement script, RunScriptOptions options,\n         Map<NodeMetadata, Exception> badNodes) {\n      return filter(transformParallel(nodes, new TransformNodesIntoInitializedScriptRunners(script, options, badNodes),\n            userExecutor, null, logger, \"initialize script runners\"), notNull());\n   }\n\n   private Set<? extends NodeMetadata> detailsOnAllNodes() {\n      return newLinkedHashSet(listNodesStrategy.listDetailsOnNodesMatching(all()));\n   }\n\n   @Override\n   public TemplateOptions templateOptions() {\n      return templateOptionsProvider.get();\n   }\n\n   protected NodeMetadata updateNodeWithCredentialsIfPresent(NodeMetadata node, RunScriptOptions options) {\n      checkNotNull(node, \"node\");\n      Builder builder = LoginCredentials.builder(node.getCredentials());\n      if (options.getLoginUser() != null)\n         builder.user(options.getLoginUser());\n      if (options.hasLoginPasswordOption()) {\n          if (options.hasLoginPassword()) {\n             builder.password(options.getLoginPassword());\n          } else {\n             builder.noPassword();\n          }\n      }\n      if (options.hasLoginPrivateKeyOption()) {\n          if (options.hasLoginPrivateKey()) {\n             builder.privateKey(options.getLoginPrivateKey());\n          } else {\n             builder.noPrivateKey();\n          }\n      }\n      if (options.shouldAuthenticateSudo() != null)\n         builder.authenticateSudo(true);\n      return NodeMetadataBuilder.fromNodeMetadata(node).credentials(builder.build()).build();\n   }\n\n   private final class TransformNodesIntoInitializedScriptRunners implements\n         Function<NodeMetadata, ListenableFuture<? extends RunScriptOnNode>> {\n      private final Map<NodeMetadata, Exception> badNodes;\n      private final Statement script;\n      private final RunScriptOptions options;\n\n      private TransformNodesIntoInitializedScriptRunners(Statement script, RunScriptOptions options,\n            Map<NodeMetadata, Exception> badNodes) {\n         this.badNodes = checkNotNull(badNodes, \"badNodes\");\n         this.script = checkNotNull(script, \"script\");\n         this.options = checkNotNull(options, \"options\");\n      }\n\n      @Override\n      public ListenableFuture<RunScriptOnNode> apply(NodeMetadata node) {\n         node = updateNodeWithCredentialsIfPresent(node, options);\n         return userExecutor.submit(initScriptRunnerFactory.create(node, script, options, badNodes));\n      }\n\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Optional<ImageExtension> getImageExtension() {\n      return imageExtension;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Optional<SecurityGroupExtension> getSecurityGroupExtension() {\n      return securityGroupExtension;\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/internal/ComputeServiceContextImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Context;\nimport org.jclouds.compute.ComputeService;\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.compute.Utils;\nimport org.jclouds.internal.BaseView;\nimport org.jclouds.location.Provider;\n\nimport com.google.common.reflect.TypeToken;\n\n@Singleton\npublic class ComputeServiceContextImpl extends BaseView implements ComputeServiceContext {\n   private final ComputeService computeService;\n   private final Utils utils;\n\n   @Inject\n   public ComputeServiceContextImpl(@Provider Context backend, @Provider TypeToken<? extends Context> backendType,\n            ComputeService computeService, Utils utils) {\n      super(backend, backendType);\n      this.computeService = checkNotNull(computeService, \"computeService\");\n      this.utils = checkNotNull(utils, \"utils\");\n   }\n   \n   @Override\n   public ComputeService getComputeService() {\n      return computeService;\n   }\n\n   @Override\n   public void close() {\n      delegate().close();\n   }\n\n   @Override\n   public Utils utils() {\n      return utils;\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/internal/FormatSharedNamesAndAppendUniqueStringToThoseWhichRepeat.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.compute.config.ComputeServiceProperties.RESOURCENAME_DELIMITER;\nimport static org.jclouds.compute.config.ComputeServiceProperties.RESOURCENAME_PREFIX;\n\nimport java.security.SecureRandom;\nimport java.util.NoSuchElementException;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.predicates.Validator;\nimport org.jclouds.predicates.validators.DnsNameValidator;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.inject.Inject;\n\n/**\n * Get a name using a random mechanism that still ties all nodes in a group\n * together.\n * \n * This implementation will pass the group and a hex formatted random number to\n * the configured naming convention.\n */\npublic class FormatSharedNamesAndAppendUniqueStringToThoseWhichRepeat implements GroupNamingConvention {\n\n   protected final String prefix;\n   protected final char delimiter;\n   protected final Supplier<String> suffixSupplier;\n   protected final String sharedFormat;\n   protected final String uniqueFormat;\n   protected final Pattern uniqueGroupPattern;\n   protected final Pattern sharedGroupPattern;\n   protected final Validator<String> groupValidator;\n\n   @Singleton\n   public static class Factory implements GroupNamingConvention.Factory {\n      @Inject(optional = true)\n      @Named(RESOURCENAME_PREFIX)\n      private String prefix = \"jclouds\";\n      @Inject(optional = true)\n      @Named(RESOURCENAME_DELIMITER)\n      private char delimiter = '-';\n      @Inject(optional = true)\n      private Supplier<String> suffixSupplier = new Supplier<String>() {\n         final SecureRandom random = new SecureRandom();\n\n         @Override\n         public String get() {\n            return Integer.toHexString(random.nextInt(4095));\n         }\n      };\n\n      @Inject(optional = true)\n      private Validator<String> groupValidator = new DnsNameValidator(3, 63);\n\n      // lazy init, so that @Inject stuff can work, and avoid calling the\n      // constructor\n      // each time, as it compiles new regexes\n      LoadingCache<String, GroupNamingConvention> cache = CacheBuilder.newBuilder().build(\n            new CacheLoader<String, GroupNamingConvention>() {\n\n               @Override\n               public GroupNamingConvention load(String key) throws Exception {\n                  return new FormatSharedNamesAndAppendUniqueStringToThoseWhichRepeat(key, delimiter, suffixSupplier, groupValidator);\n               }\n\n            });\n\n      @Override\n      public GroupNamingConvention create() {\n         return cache.getUnchecked(prefix);\n      }\n\n      @Override\n      public GroupNamingConvention createWithoutPrefix() {\n         return cache.getUnchecked(\"\");\n      }\n   }\n\n   public FormatSharedNamesAndAppendUniqueStringToThoseWhichRepeat(String prefix, char delimiter,\n         Supplier<String> suffixSupplier, Validator<String> groupValidator) {\n      this.prefix = checkNotNull(prefix, \"prefix\");\n      this.delimiter = delimiter;\n      this.suffixSupplier = checkNotNull(suffixSupplier, \"suffixSupplier\");\n      this.groupValidator = checkNotNull(groupValidator, \"groupValidator\");\n      this.sharedFormat = \"\".equals(prefix) ? \"%s\" : prefix + delimiter + \"%s\";\n      this.uniqueFormat = sharedFormat + delimiter + \"%s\";\n      this.uniqueGroupPattern = Pattern.compile(\"^\" + (\"\".equals(prefix) ? \"\" : (prefix + delimiter)) + \"(.+)\"\n            + delimiter + \"[^\" + delimiter + \"]+\");\n      this.sharedGroupPattern = Pattern.compile(\"^\" + (\"\".equals(prefix) ? \"\" : (prefix + delimiter)) + \"(.+)$\");\n   }\n\n   @Override\n   public String sharedNameForGroup(String group) {\n      return String.format(sharedFormat, checkGroup(group));\n   }\n\n   protected String checkGroup(String group) {\n      groupValidator.validate(checkNotNull(group, \"group\"));\n      return group;\n   }\n\n   @Override\n   public String uniqueNameForGroup(String group) {\n      return String.format(uniqueFormat, checkGroup(group), suffixSupplier.get());\n   }\n\n   @Override\n   public String groupInUniqueNameOrNull(String encoded) {\n      return firstGroupInPatternOrNull(uniqueGroupPattern, encoded);\n   }\n\n   protected String firstGroupInPatternOrNull(Pattern pattern, String encoded) {\n      Matcher matcher = pattern.matcher(checkNotNull(encoded, \"encoded\"));\n      if (!matcher.matches())\n         return null;\n      return matcher.group(1);\n   }\n\n   @Override\n   public String groupInSharedNameOrNull(String encoded) {\n      return firstGroupInPatternOrNull(sharedGroupPattern, encoded);\n   }\n\n   @Override\n   public Predicate<String> containsGroup(final String group) {\n      checkGroup(group);\n      return new Predicate<String>() {\n\n         @Override\n         public boolean apply(String input) {\n            try {\n               return group.equals(groupInUniqueNameOrNull(input)) || group.equals(groupInSharedNameOrNull(input));\n            } catch (NoSuchElementException e) {\n               return false;\n            }\n         }\n\n         @Override\n         public String toString() {\n            return \"containsGroup(\" + group + \")\";\n         }\n      };\n   }\n\n   @Override\n   public Predicate<String> containsAnyGroup() {\n      return new Predicate<String>() {\n\n         @Override\n         public boolean apply(String input) {\n            try {\n               return groupInUniqueNameOrNull(input) != null || groupInSharedNameOrNull(input) != null;\n            } catch (NoSuchElementException e) {\n               return false;\n            }\n         }\n\n         @Override\n         public String toString() {\n            return \"containsAnyGroup()\";\n         }\n      };\n   }\n\n   @Override\n   public String extractGroup(String encoded) {\n      String result = groupInUniqueNameOrNull(encoded);\n      if (result != null) return result;\n      \n      result = groupInSharedNameOrNull(encoded);\n      return result;\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/internal/PersistNodeCredentials.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.internal;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.scriptbuilder.domain.Statement;\n\nimport com.google.common.base.Function;\n\npublic interface PersistNodeCredentials {\n   @Named(\"ifAdminAccess\")\n   Function<NodeMetadata, NodeMetadata> ifAdminAccess(@Nullable Statement statement);\n\n   @Named(\"always\")\n   Function<NodeMetadata, NodeMetadata> always(@Nullable Statement statement);\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/internal/UtilsImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.internal;\n\nimport java.util.Map;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.Utils;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.crypto.Crypto;\nimport org.jclouds.date.DateService;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.json.Json;\nimport org.jclouds.logging.Logger.LoggerFactory;\nimport org.jclouds.rest.HttpClient;\nimport org.jclouds.ssh.SshClient;\nimport org.jclouds.ssh.SshClient.Factory;\nimport org.jclouds.xml.XMLParser;\n\nimport com.google.common.base.Function;\nimport com.google.common.eventbus.EventBus;\nimport com.google.inject.Inject;\nimport com.google.inject.Injector;\n\n@Singleton\npublic class UtilsImpl extends org.jclouds.rest.internal.UtilsImpl implements Utils {\n   @Inject(optional = true)\n   private Factory sshFactory;\n   private final Function<NodeMetadata, SshClient> sshForNode;\n\n   @Inject UtilsImpl(Injector injector, Json json, XMLParser xml, HttpClient simpleClient, Crypto encryption,\n         DateService date, EventBus eventBus, Map<String, Credentials> credentialStore, LoggerFactory loggerFactory,\n         Function<NodeMetadata, SshClient> sshForNode) {\n      super(injector, json, xml, simpleClient, encryption, date, eventBus, credentialStore, loggerFactory);\n      this.sshForNode = sshForNode;\n   }\n\n   @Override\n   public Factory getSshClientFactory() {\n      return sshFactory;\n   }\n\n   @Override\n   public Factory sshFactory() {\n      return sshFactory;\n   }\n\n   @Override\n   public Function<NodeMetadata, SshClient> sshForNode() {\n      return sshForNode;\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/options/RunScriptOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.options;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.Optional;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Enables additional options for running a script.\n */\npublic class RunScriptOptions {\n\n   /**\n    * Default options. The default settings are:\n    * <ul>\n    * <li>override the credentials with ones supplied in call to\n    * {@link org.jclouds.compute.ComputeService#runScriptOnNodesMatching}</li>\n    * <li>run the script as root (versus running with current privileges)</li>\n    * </ul>\n    */\n   public static final RunScriptOptions NONE = new ImmutableRunScriptOptions(new RunScriptOptions());\n\n   public void copyTo(RunScriptOptions to) {\n      if (this.getPort() != -1)\n         to.blockOnPort(this.getPort(), this.getSeconds());\n      if (this.getTaskName() != null)\n         to.nameTask(this.getTaskName());\n      to.runAsRoot(this.shouldRunAsRoot());\n      to.blockOnComplete(this.shouldBlockOnComplete());\n      to.wrapInInitScript(this.shouldWrapInInitScript());\n      if (this.hasLoginPasswordOption())\n         to.overrideLoginPassword(this.loginPassword);\n      if (this.hasLoginPrivateKeyOption())\n         to.overrideLoginPrivateKey(this.loginPrivateKey);\n      if (this.getLoginUser() != null)\n         to.overrideLoginUser(this.getLoginUser());\n      if (this.shouldAuthenticateSudo() != null) {\n         to.overrideAuthenticateSudo(this.shouldAuthenticateSudo());\n      }\n   }\n   \n   public static class ImmutableRunScriptOptions extends RunScriptOptions {\n      private final RunScriptOptions delegate;\n\n      public ImmutableRunScriptOptions(RunScriptOptions delegate) {\n         this.delegate = delegate;\n      }\n\n      @Override\n      public String toString() {\n         return delegate.toString();\n      }\n\n      @Override\n      public boolean shouldRunAsRoot() {\n         return delegate.shouldRunAsRoot();\n\n      }\n\n      @Override\n      public RunScriptOptions runAsRoot(boolean runAsRoot) {\n         throw new IllegalArgumentException(\"runAsRoot is immutable\");\n      }\n\n      @Override\n      public boolean shouldBlockOnComplete() {\n         return delegate.shouldBlockOnComplete();\n\n      }\n\n      @Override\n      public RunScriptOptions blockOnComplete(boolean blockOnComplete) {\n         throw new IllegalArgumentException(\"blockOnComplete is immutable\");\n      }\n\n      @Override\n      public RunScriptOptions overrideLoginCredentials(LoginCredentials overridingCredentials) {\n         throw new IllegalArgumentException(\"overridingCredentials is immutable\");\n      }\n\n      @Override\n      public RunScriptOptions overrideLoginPassword(String password) {\n         throw new IllegalArgumentException(\"password is immutable\");\n      }\n\n      @Override\n      public RunScriptOptions overrideLoginPrivateKey(String privateKey) {\n         throw new IllegalArgumentException(\"privateKey is immutable\");\n      }\n\n      @Override\n      public RunScriptOptions overrideAuthenticateSudo(boolean authenticateSudo) {\n         throw new IllegalArgumentException(\"authenticateSudo is immutable\");\n      }\n\n      @Override\n      public String getLoginUser() {\n         return delegate.getLoginUser();\n      }\n\n      @Override\n      public Boolean shouldAuthenticateSudo() {\n         return delegate.shouldAuthenticateSudo();\n      }\n\n      @Override\n      public String getLoginPassword() {\n         return delegate.getLoginPassword();\n      }\n\n      @Override\n      public String getLoginPrivateKey() {\n         return delegate.getLoginPrivateKey();\n      }\n\n      @Override\n      public boolean shouldWrapInInitScript() {\n         return delegate.shouldWrapInInitScript();\n      }\n\n      @Override\n      public RunScriptOptions overrideLoginUser(String loginUser) {\n         throw new IllegalArgumentException(\"loginUser is immutable\");\n      }\n      \n      @Override\n      public RunScriptOptions wrapInInitScript(boolean wrapInInitScript) {\n         throw new IllegalArgumentException(\"wrapInInitScript is immutable\");\n      }\n      \n      @Override\n      public String getTaskName() {\n         return delegate.getTaskName();\n      }\n\n      @Override\n      public RunScriptOptions nameTask(String name) {\n         throw new IllegalArgumentException(\"taskName is immutable\");\n      }\n\n      @Override\n      public RunScriptOptions blockOnPort(int port, int seconds) {\n         throw new IllegalArgumentException(\"port, seconds are immutable\");\n      }\n\n      @Override\n      public int getPort() {\n         return delegate.getPort();\n      }\n\n      @Override\n      public int getSeconds() {\n         return delegate.getSeconds();\n      }\n   }\n\n   protected int port = -1;\n   protected int seconds = -1;\n   protected String taskName;\n   protected boolean runAsRoot = true;\n   protected boolean blockOnComplete = true;\n   protected boolean wrapInInitScript = true;\n\n   protected String loginUser;\n   protected Boolean authenticateSudo;\n   protected Optional<String> loginPassword;\n   protected Optional<String> loginPrivateKey;\n\n   public RunScriptOptions overrideLoginCredentials(LoginCredentials overridingCredentials) {\n      checkNotNull(overridingCredentials, \"overridingCredentials\");\n      this.loginUser = overridingCredentials.getUser();\n      this.loginPassword = overridingCredentials.getOptionalPassword();\n      this.loginPrivateKey = overridingCredentials.getOptionalPrivateKey();\n      this.authenticateSudo = overridingCredentials.shouldAuthenticateSudo() ? true : null;\n      return this;\n   }\n  \n\n   public RunScriptOptions overrideLoginUser(String loginUser) {\n      checkNotNull(loginUser, \"loginUser\");\n      this.loginUser = loginUser;\n      return this;\n   }\n  \n   public RunScriptOptions overrideLoginPassword(String password) {\n      checkNotNull(password, \"password\");\n      this.loginPassword = Optional.of(password);\n      return this;\n   }\n\n   public RunScriptOptions overrideLoginPrivateKey(String privateKey) {\n      checkNotNull(privateKey, \"privateKey\");\n      this.loginPrivateKey = Optional.of(privateKey);\n      return this;\n   }\n\n   public RunScriptOptions overrideLoginPassword(Optional<String> password) {\n      checkNotNull(password, \"password\");\n      this.loginPassword = password;\n      return this;\n   }\n\n   public RunScriptOptions overrideLoginPrivateKey(Optional<String> privateKey) {\n      checkNotNull(privateKey, \"privateKey\");\n      this.loginPrivateKey = privateKey;\n      return this;\n   }\n\n   public RunScriptOptions overrideAuthenticateSudo(boolean authenticateSudo) {\n      this.authenticateSudo = authenticateSudo;\n      return this;\n   }\n\n   /**\n    * @return What to call the task relating to this script; default\n    *         {@code jclouds-script-timestamp} where timestamp is millis since\n    *         epoch\n    * \n    */\n   public RunScriptOptions nameTask(String name) {\n      this.taskName = name;\n      return this;\n   }\n\n   public RunScriptOptions runAsRoot(boolean runAsRoot) {\n      this.runAsRoot = runAsRoot;\n      return this;\n   }\n\n   /**\n    * default true\n    * <p/>\n    * \n    * @param wrapInInitScript\n    *           if the command is long-running, use this option to ensure it is\n    *           wrapInInitScripted properly. (ex. have jclouds wrap it an init\n    *           script, nohup, etc)\n    * @return\n    */\n   public RunScriptOptions wrapInInitScript(boolean wrapInInitScript) {\n      this.wrapInInitScript = wrapInInitScript;\n      return this;\n   }\n\n   /**\n    * As of version 1.1.0, we cannot kick off a script unless a node is in\n    * RUNNING state.\n    * \n    * @param blockOnComplete\n    *           (default true) false means kick off the script in the\n    *           background, but don't wait for it to finish. (as of version\n    *           1.1.0, implemented as nohup)\n    */\n   public RunScriptOptions blockOnComplete(boolean blockOnComplete) {\n      this.blockOnComplete = blockOnComplete;\n      return this;\n   }\n\n   /**\n    * When the node is started, wait until the following port is active\n    */\n   public RunScriptOptions blockOnPort(int port, int seconds) {\n      checkArgument(port > 0 && port < 65536, \"port must be a positive integer < 65535\");\n      checkArgument(seconds > 0, \"seconds must be a positive integer\");\n      this.port = port;\n      this.seconds = seconds;\n      return this;\n   }\n\n   public String getTaskName() {\n      return taskName;\n   }\n\n   public int getPort() {\n      return port;\n   }\n\n   public int getSeconds() {\n      return seconds;\n   }\n\n   /**\n    * \n    * @return the login user for\n    *         {@link org.jclouds.compute.ComputeService#runScriptOnNode}. By\n    *         default, null.\n    */\n   @Nullable\n   public String getLoginUser() {\n      return loginUser;\n   }\n\n   /**\n    * \n    * @return Whether the login user should authenticate sudo during\n    *         {@link org.jclouds.compute.ComputeService#runScriptOnNode}. By\n    *         default, null.\n    */\n   @Nullable\n   public Boolean shouldAuthenticateSudo() {\n      return authenticateSudo;\n   }\n\n   /**\n    * @return true if the login password has been configured\n    */\n   public boolean hasLoginPasswordOption() {\n      return loginPassword != null;\n   }\n\n   /**\n    * @return true if the login password is set\n    */\n   public boolean hasLoginPassword() {\n      return hasLoginPasswordOption() && loginPassword.isPresent();\n   }\n\n   /**\n    *\n    * @return the login password for\n    *         {@link org.jclouds.compute.ComputeService#runScriptOnNode}. By\n    *         default, null.\n    */\n   @Nullable\n   public String getLoginPassword() {\n      return hasLoginPassword() ? loginPassword.get() : null;\n   }\n\n   /**\n    * @return true if the login ssh key has been configured\n    */\n   public boolean hasLoginPrivateKeyOption() {\n      return loginPrivateKey != null;\n   }\n\n   /**\n    * @return true if the login ssh key is set\n    */\n   public boolean hasLoginPrivateKey() {\n      return hasLoginPrivateKeyOption() && loginPrivateKey.isPresent();\n   }\n\n   /**\n    * \n    * @return the login ssh key for\n    *         {@link org.jclouds.compute.ComputeService#runScriptOnNode}. By\n    *         default, null.\n    */\n   @Nullable\n   public String getLoginPrivateKey() {\n      return hasLoginPrivateKey() ? loginPrivateKey.get() : null;\n   }\n\n   /**\n    * Whether to run the script as root (or run with current privileges). By\n    * default, true.\n    * \n    * @return value\n    */\n   public boolean shouldRunAsRoot() {\n      return runAsRoot;\n   }\n\n   /**\n    * @see #blockOnComplete(boolean)\n    */\n   public boolean shouldBlockOnComplete() {\n      return blockOnComplete;\n   }\n\n   /**\n    * Whether to wait until the script has completed. By default, true.\n    * \n    * @return value\n    */\n   public boolean shouldWrapInInitScript() {\n      return wrapInInitScript;\n   }\n\n   public static class Builder {\n\n      public static RunScriptOptions nameTask(String name) {\n         RunScriptOptions options = new RunScriptOptions();\n         return options.nameTask(name);\n      }\n\n      public static RunScriptOptions overrideLoginUser(String user) {\n         RunScriptOptions options = new RunScriptOptions();\n         return options.overrideLoginUser(user);\n      }\n\n      public static RunScriptOptions overrideLoginPassword(String password) {\n         RunScriptOptions options = new RunScriptOptions();\n         return options.overrideLoginPassword(password);\n      }\n\n      public static RunScriptOptions overrideLoginPrivateKey(String privateKey) {\n         RunScriptOptions options = new RunScriptOptions();\n         return options.overrideLoginPrivateKey(privateKey);\n      }\n\n      public static RunScriptOptions overrideAuthenticateSudo(boolean authenticateSudo) {\n         RunScriptOptions options = new RunScriptOptions();\n         return options.overrideAuthenticateSudo(authenticateSudo);\n      }\n\n      public static RunScriptOptions overrideLoginCredentials(LoginCredentials credentials) {\n         RunScriptOptions options = new RunScriptOptions();\n         return options.overrideLoginCredentials(credentials);\n      }\n\n      public static RunScriptOptions runAsRoot(boolean value) {\n         RunScriptOptions options = new RunScriptOptions();\n         return options.runAsRoot(value);\n      }\n\n      /**\n       * @see RunScriptOptions#blockOnComplete(boolean)\n       */\n      public static RunScriptOptions blockOnComplete(boolean value) {\n         RunScriptOptions options = new RunScriptOptions();\n         return options.blockOnComplete(value);\n      }\n\n      public static RunScriptOptions wrapInInitScript(boolean value) {\n         RunScriptOptions options = new RunScriptOptions();\n         return options.wrapInInitScript(value);\n      }\n\n      public static RunScriptOptions blockOnPort(int port, int seconds) {\n         RunScriptOptions options = new RunScriptOptions();\n         return options.blockOnPort(port, seconds);\n      }\n\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o)\n         return true;\n      if (o == null || getClass() != o.getClass())\n         return false;\n      RunScriptOptions that = RunScriptOptions.class.cast(o);\n      return equal(this.loginUser, that.loginUser) && equal(this.loginPassword, that.loginPassword)\n            && equal(this.loginPrivateKey, that.loginPrivateKey) && equal(this.authenticateSudo, that.authenticateSudo)\n            && equal(this.port, that.port) && equal(this.seconds, that.seconds) && equal(this.taskName, that.taskName)\n            && equal(this.runAsRoot, that.runAsRoot) && equal(this.blockOnComplete, that.blockOnComplete)\n            && equal(this.wrapInInitScript, that.wrapInInitScript);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(loginUser, loginPassword, loginPrivateKey, authenticateSudo, port, seconds, taskName,\n            taskName, blockOnComplete, wrapInInitScript);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   protected ToStringHelper string() {\n      ToStringHelper toString = MoreObjects.toStringHelper(\"\").omitNullValues();\n      toString.add(\"loginUser\", loginUser);\n      if (loginPassword != null && loginPassword.isPresent())\n         toString.add(\"loginPasswordPresent\", true);\n      if (loginPrivateKey != null && loginPrivateKey.isPresent())\n         toString.add(\"loginPrivateKeyPresent\", true);\n      toString.add(\"authenticateSudo\", authenticateSudo);\n      if (port != -1 && seconds != -1) // TODO: not primitives\n         toString.add(\"blockOnPort:seconds\", port + \":\" + seconds);\n      toString.add(\"taskName\", taskName);\n      if (!runAsRoot)\n         toString.add(\"runAsRoot\", runAsRoot);\n      if (!blockOnComplete)\n         toString.add(\"blockOnComplete\", blockOnComplete);\n      if (!wrapInInitScript)\n         toString.add(\"wrapInInitScript\", wrapInInitScript);\n      return toString;\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/options/TemplateOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.options;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Arrays;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.scriptbuilder.domain.Statement;\nimport org.jclouds.scriptbuilder.domain.Statements;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Maps;\nimport com.google.common.primitives.Ints;\n\n/**\n * Contains options supported in the {@code ComputeService#createNodesInGroup}\n * operation. <h2>\n * Usage</h2> The recommended way to instantiate a TemplateOptions object is to\n * statically import TemplateOptions.* and invoke a static creation method\n * followed by any/all desired instance mutators.\n * <p/>\n * <code>\n * import static org.jclouds.compute.options.TemplateOptions.Builder.*;\n * <p/>\n * ComputeService client = // get connection\n * templateBuilder.options(inboundPorts(22, 80, 8080, 443));\n * Set<? extends NodeMetadata> set = client.createNodesInGroup(tag, 2, templateBuilder.build());\n * <code>\n * <p/>\n * Note that options can only be assigned to a builder once, so if assigning e.g. inboundPorts and tags,\n * that must be done in with mutators in a single call to options --\n * <code>templateBuilder.options(inboundPorts(22, 80, 8080, 443).tags(\"I love it!\"))</code>\n * -- not as repeated calls to <code>options</code>.\n */\npublic class TemplateOptions extends RunScriptOptions implements Cloneable {\n\n   @Override\n   public TemplateOptions clone() {\n      TemplateOptions options = new TemplateOptions();\n      copyTo(options);\n      return options;\n   }\n\n   public void copyTo(TemplateOptions to) {\n      super.copyTo(to);\n      if (!Arrays.equals(to.getInboundPorts(), this.getInboundPorts()))\n         to.inboundPorts(this.getInboundPorts());\n      if (this.getRunScript() != null)\n         to.runScript(this.getRunScript());\n      if (!this.getGroups().isEmpty())\n         to.securityGroups(this.getGroups());\n      if (this.getPrivateKey() != null)\n         to.installPrivateKey(this.getPrivateKey());\n      if (this.getPublicKey() != null)\n         to.authorizePublicKey(this.getPublicKey());\n      if (!this.getUserMetadata().isEmpty())\n         to.userMetadata(this.getUserMetadata());\n      if (!this.getTags().isEmpty())\n         to.tags(getTags());\n      if (!this.getNodeNames().isEmpty())\n         to.nodeNames(getNodeNames());\n      if (!this.shouldBlockUntilRunning())\n         to.blockUntilRunning(false);\n      if (!this.getNetworks().isEmpty())\n         to.networks(this.getNetworks());\n   }\n\n   public static class ImmutableTemplateOptions extends TemplateOptions {\n      private final TemplateOptions delegate;\n\n      @Override\n      public TemplateOptions clone() {\n         return delegate.clone();\n      }\n\n      @Override\n      public String getTaskName() {\n         return delegate.getTaskName();\n      }\n\n      @Override\n      public int getPort() {\n         return delegate.getPort();\n      }\n\n      @Override\n      public int getSeconds() {\n         return delegate.getSeconds();\n      }\n\n      @Override\n      public boolean shouldRunAsRoot() {\n         return delegate.shouldRunAsRoot();\n      }\n\n      @Override\n      public boolean shouldBlockOnComplete() {\n         return delegate.shouldBlockOnComplete();\n      }\n\n      @Override\n      public boolean shouldWrapInInitScript() {\n         return delegate.shouldWrapInInitScript();\n      }\n\n      @Override\n      public void copyTo(TemplateOptions to) {\n         delegate.copyTo(to);\n      }\n\n      public ImmutableTemplateOptions(TemplateOptions delegate) {\n         this.delegate = delegate;\n      }\n\n      @Override\n      public String toString() {\n         return delegate.toString();\n      }\n\n      /**\n       * unsupported as objects of this class are immutable\n       */\n      @Override\n      public TemplateOptions runScript(Statement script) {\n         throw new IllegalArgumentException(\"script is immutable\");\n      }\n\n      @Override\n      public TemplateOptions dontAuthorizePublicKey() {\n         throw new IllegalArgumentException(\"public key is immutable\");\n      }\n\n      @Override\n      public TemplateOptions blockOnPort(int port, int seconds) {\n         throw new IllegalArgumentException(\"ports are immutable\");\n      }\n\n      @Override\n      public TemplateOptions nameTask(String name) {\n         throw new IllegalArgumentException(\"task name is immutable\");\n      }\n\n      @Override\n      public TemplateOptions runAsRoot(boolean runAsRoot) {\n         throw new IllegalArgumentException(\"runAsRoot is immutable\");\n      }\n\n      @Override\n      public TemplateOptions wrapInInitScript(boolean wrapInInitScript) {\n         throw new IllegalArgumentException(\"wrapInInitScript is immutable\");\n      }\n\n      @Override\n      public TemplateOptions blockOnComplete(boolean blockOnComplete) {\n         throw new IllegalArgumentException(\"blockOnComplete is immutable\");\n      }\n\n      @Override\n      public TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials) {\n         throw new IllegalArgumentException(\"overridingCredentials is immutable\");\n      }\n\n      @Override\n      public TemplateOptions overrideLoginPassword(String password) {\n         throw new IllegalArgumentException(\"password is immutable\");\n      }\n\n      @Override\n      public TemplateOptions overrideLoginPrivateKey(String privateKey) {\n         throw new IllegalArgumentException(\"privateKey is immutable\");\n      }\n\n      @Override\n      public TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo) {\n         throw new IllegalArgumentException(\"authenticateSudo is immutable\");\n      }\n\n      @Override\n      public String getLoginUser() {\n         return delegate.getLoginUser();\n      }\n\n      @Override\n      public Boolean shouldAuthenticateSudo() {\n         return delegate.shouldAuthenticateSudo();\n      }\n\n      @Override\n      public String getLoginPassword() {\n         return delegate.getLoginPassword();\n      }\n\n      @Override\n      public String getLoginPrivateKey() {\n         return delegate.getLoginPrivateKey();\n      }\n\n      @Override\n      public TemplateOptions overrideLoginUser(String loginUser) {\n         throw new IllegalArgumentException(\"loginUser is immutable\");\n      }\n\n      @Override\n      public <T extends TemplateOptions> T as(Class<T> clazz) {\n         return delegate.as(clazz);\n      }\n\n      @Override\n      public TemplateOptions authorizePublicKey(String publicKey) {\n         throw new IllegalArgumentException(\"publicKey is immutable\");\n      }\n\n      /**\n       * unsupported as objects of this class are immutable\n       */\n      @Override\n      public TemplateOptions blockUntilRunning(boolean blockUntilRunning) {\n         throw new IllegalArgumentException(\"blockUntilRunning is immutable\");\n      }\n\n      @Override\n      public int[] getInboundPorts() {\n         return delegate.getInboundPorts();\n      }\n\n      @Override\n      public String getPrivateKey() {\n         return delegate.getPrivateKey();\n      }\n\n      @Override\n      public String getPublicKey() {\n         return delegate.getPublicKey();\n      }\n\n      @Override\n      public Statement getRunScript() {\n         return delegate.getRunScript();\n      }\n\n      @Override\n      public boolean shouldBlockUntilRunning() {\n         return delegate.shouldBlockUntilRunning();\n      }\n\n      @Override\n      public TemplateOptions inboundPorts(int... ports) {\n         throw new IllegalArgumentException(\"ports are immutable\");\n      }\n\n      @Override\n      public TemplateOptions installPrivateKey(String privateKey) {\n         throw new IllegalArgumentException(\"privateKey is immutable\");\n      }\n\n      @Override\n      public Set<String> getTags() {\n         return delegate.getTags();\n      }\n\n      @Override\n      public TemplateOptions tags(Iterable<String> tags) {\n         throw new IllegalArgumentException(\"tags are immutable\");\n      }\n\n      @Override\n       public Set<String> getNodeNames() {\n         return delegate.getNodeNames();\n      }\n\n      @Override\n      public TemplateOptions nodeNames(Iterable<String> nodeNames) {\n         throw new IllegalArgumentException(\"nodeNames are immutable\");\n      }\n\n      @Override\n      public Set<String> getGroups() {\n         return delegate.getGroups();\n      }\n\n      @Override\n      public TemplateOptions securityGroups(Iterable<String> securityGroups) {\n         throw new IllegalArgumentException(\"security groups are immutable\");\n      }\n\n      @Override\n      public TemplateOptions securityGroups(String... securityGroups) {\n         throw new IllegalArgumentException(\"security groups are immutable\");\n      }\n\n      @Override\n      public TemplateOptions networks(Iterable<String> networks) {\n         throw new IllegalArgumentException(\"networks are immutable\");\n      }\n\n      @Override\n      public TemplateOptions networks(String... networks) {\n         throw new IllegalArgumentException(\"networks are immutable\");\n      }\n\n      @Override\n      public TemplateOptions userMetadata(Map<String, String> userMetadata) {\n         throw new IllegalArgumentException(\"userMetadata is immutable\");\n      }\n\n      @Override\n      public TemplateOptions userMetadata(String key, String value) {\n         throw new IllegalArgumentException(\"userMetadata is immutable\");\n      }\n\n      @Override\n      public Map<String, String> getUserMetadata() {\n         return delegate.getUserMetadata();\n      }\n\n   }\n\n   private static final Set<Integer> DEFAULT_INBOUND_PORTS = ImmutableSet.of(22);\n\n   public static final TemplateOptions NONE = new ImmutableTemplateOptions(new TemplateOptions());\n\n   protected Set<Integer> inboundPorts = DEFAULT_INBOUND_PORTS;\n\n   protected Statement script;\n\n   protected Set<String> tags = ImmutableSet.of();\n\n   protected Set<String> securityGroups = ImmutableSet.of();\n\n   protected String privateKey;\n\n   protected String publicKey;\n\n   protected boolean blockUntilRunning = true;\n\n   protected Map<String, String> userMetadata = Maps.newLinkedHashMap();\n\n   protected Set<String> nodeNames = ImmutableSet.of();\n\n   protected Set<String> networks = ImmutableSet.of();\n\n   public boolean equals(Object o) {\n      if (this == o)\n         return true;\n      if (o == null || getClass() != o.getClass())\n         return false;\n      TemplateOptions that = TemplateOptions.class.cast(o);\n      return super.equals(that) && equal(this.inboundPorts, that.inboundPorts) && equal(this.script, that.script)\n              && equal(this.publicKey, that.publicKey) && equal(this.privateKey, that.privateKey)\n              && equal(this.blockUntilRunning, that.blockUntilRunning) && equal(this.tags, that.tags)\n              && equal(this.securityGroups, that.securityGroups) && equal(this.userMetadata, that.userMetadata)\n              && equal(this.nodeNames, that.nodeNames) && equal(this.networks, that.networks);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(super.hashCode(), inboundPorts, script, publicKey, privateKey, blockUntilRunning, tags,\n                              securityGroups, userMetadata, nodeNames, networks);\n   }\n\n   @Override\n   public ToStringHelper string() {\n      ToStringHelper toString = super.string();\n      if (!DEFAULT_INBOUND_PORTS.equals(inboundPorts))\n         toString.add(\"inboundPorts\", inboundPorts);\n      if (script != null)\n         toString.add(\"scriptPresent\", true);\n      if (publicKey != null)\n         toString.add(\"publicKeyPresent\", true);\n      if (privateKey != null)\n         toString.add(\"privateKeyPresent\", true);\n      if (!blockUntilRunning)\n         toString.add(\"blockUntilRunning\", blockUntilRunning);\n      if (!tags.isEmpty())\n         toString.add(\"tags\", tags);\n      if (!nodeNames.isEmpty())\n         toString.add(\"nodeNames\", nodeNames);\n      if (securityGroups.size() != 0)\n         toString.add(\"securityGroups\", securityGroups);\n      if (userMetadata.size() != 0)\n         toString.add(\"userMetadata\", userMetadata);\n      if (!networks.isEmpty())\n         toString.add(\"networks\", networks);\n      return toString;\n   }\n\n   public int[] getInboundPorts() {\n      return Ints.toArray(inboundPorts);\n   }\n\n   public Statement getRunScript() {\n      return script;\n   }\n\n   public Set<String> getTags() {\n      return tags;\n   }\n\n   public Set<String> getNodeNames() {\n      return nodeNames;\n   }\n\n   public Set<String> getGroups() {\n      return securityGroups;\n   }\n\n   public String getPrivateKey() {\n      return privateKey;\n   }\n\n   public String getPublicKey() {\n      return publicKey;\n   }\n\n   public Set<String> getNetworks() {\n      return networks;\n   }\n\n   /**\n    * @see TemplateOptions#blockUntilRunning(boolean)\n    */\n   public boolean shouldBlockUntilRunning() {\n      return blockUntilRunning;\n   }\n\n   public <T extends TemplateOptions> T as(Class<T> clazz) {\n      return clazz.cast(this);\n   }\n\n   /**\n    * This script will be executed as the root user upon system startup. This\n    * script gets a prologue, so no #!/bin/bash required, path set up, etc\n    *\n    */\n   public TemplateOptions runScript(String script) {\n      return runScript(Statements.exec(script));\n   }\n\n   /**\n    * This script will be executed as the root user upon system startup. This\n    * script gets a prologue, so no #!/bin/bash required, path set up, etc\n    *\n    */\n   public TemplateOptions runScript(Statement script) {\n      this.script = checkNotNull(script, \"script\");\n      return this;\n   }\n\n   /**\n    * replaces the rsa ssh key used at login.\n    */\n   public TemplateOptions installPrivateKey(String privateKey) {\n      checkArgument(checkNotNull(privateKey, \"privateKey\").startsWith(\"-----BEGIN RSA PRIVATE KEY-----\"),\n            \"key should start with -----BEGIN RSA PRIVATE KEY-----\");\n      this.privateKey = privateKey;\n      return this;\n   }\n\n   public TemplateOptions dontAuthorizePublicKey() {\n      this.publicKey = null;\n      return this;\n   }\n\n   /**\n    * authorize an rsa ssh key.\n    */\n   public TemplateOptions authorizePublicKey(String publicKey) {\n      checkArgument(checkNotNull(publicKey, \"publicKey\").startsWith(\"ssh-rsa\"), \"key should start with ssh-rsa\");\n      this.publicKey = publicKey;\n      return this;\n   }\n\n   /**\n    * assigns tags to the created nodes\n    */\n   public TemplateOptions tags(Iterable<String> tags) {\n      this.tags = ImmutableSet.copyOf(checkNotNull(tags, \"tags\"));\n      return this;\n   }\n\n   /**\n    * specifies names to be used for the created nodes.\n    *\n    * Note that this does not guarantee uniqueness - if there are already existing nodes with a name\n    * specified here, there will still be a new node created with the same name. Also, if more\n    * nodes are to be created than there are names, subsequent names will use the default naming strategy\n    * for that cloud.\n    */\n   public TemplateOptions nodeNames(Iterable<String> nodeNames) {\n      this.nodeNames = ImmutableSet.copyOf(checkNotNull(nodeNames, \"nodeNames\"));\n      return this;\n   }\n\n   /**\n    * assigns the created nodes to these security groups\n    */\n   public TemplateOptions securityGroups(Iterable<String> securityGroups) {\n      this.securityGroups = ImmutableSet.copyOf(checkNotNull(securityGroups, \"securityGroups\"));\n      return this;\n   }\n\n   /**\n    * @see TemplateOptions#securityGroups(Iterable<String>)\n    */\n   public TemplateOptions securityGroups(String... securityGroups) {\n      return securityGroups(ImmutableSet.copyOf(securityGroups));\n   }\n\n   /**\n    * Assigns the created nodes to these networks\n    */\n   public TemplateOptions networks(Iterable<String> networks) {\n      this.networks = ImmutableSet.copyOf(checkNotNull(networks, \"networks\"));\n      return this;\n   }\n\n   /**\n    * @see TemplateOptions#networks(Iterable)\n    */\n   public TemplateOptions networks(String... networks) {\n      return networks(ImmutableSet.copyOf(networks));\n   }\n\n   /**\n    * Opens the set of ports to public access.\n    */\n   public TemplateOptions inboundPorts(int... ports) {\n      for (int port : ports)\n         checkArgument(port > 0 && port < 65536, \"port must be a positive integer < 65535\");\n      this.inboundPorts = ImmutableSet.copyOf(Ints.asList(ports));\n      return this;\n   }\n\n   public static class Builder extends org.jclouds.compute.options.RunScriptOptions.Builder {\n\n      public static TemplateOptions nameTask(String name) {\n         TemplateOptions options = new TemplateOptions();\n         return options.nameTask(name);\n      }\n\n      public static TemplateOptions overrideLoginUser(String user) {\n         TemplateOptions options = new TemplateOptions();\n         return options.overrideLoginUser(user);\n      }\n\n      public static TemplateOptions overrideLoginPassword(String password) {\n         TemplateOptions options = new TemplateOptions();\n         return options.overrideLoginPassword(password);\n      }\n\n      public static TemplateOptions overrideLoginPrivateKey(String privateKey) {\n         TemplateOptions options = new TemplateOptions();\n         return options.overrideLoginPrivateKey(privateKey);\n      }\n\n      public static TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo) {\n         TemplateOptions options = new TemplateOptions();\n         return options.overrideAuthenticateSudo(authenticateSudo);\n      }\n\n      public static TemplateOptions overrideLoginCredentials(LoginCredentials credentials) {\n         TemplateOptions options = new TemplateOptions();\n         return options.overrideLoginCredentials(credentials);\n      }\n\n      public static TemplateOptions runAsRoot(boolean value) {\n         TemplateOptions options = new TemplateOptions();\n         return options.runAsRoot(value);\n      }\n\n      /**\n       * @see TemplateOptions#blockOnPort\n       */\n      public static TemplateOptions blockOnPort(int port, int seconds) {\n         TemplateOptions options = new TemplateOptions();\n         return options.blockOnPort(port, seconds);\n      }\n\n      /**\n       * @see TemplateOptions#inboundPorts\n       */\n      public static TemplateOptions inboundPorts(int... ports) {\n         TemplateOptions options = new TemplateOptions();\n         return options.inboundPorts(ports);\n      }\n\n      /**\n       * @see TemplateOptions#tags\n       */\n      public static TemplateOptions tags(Iterable<String> tags) {\n         TemplateOptions options = new TemplateOptions();\n         return options.tags(tags);\n      }\n\n      /**\n       * @see TemplateOptions#nodeNames\n       */\n      public static TemplateOptions nodeNames(Iterable<String> nodeNames) {\n         TemplateOptions options = new TemplateOptions();\n         return options.nodeNames(nodeNames);\n      }\n\n      /**\n       * @see TemplateOptions#securityGroups\n       */\n      public static TemplateOptions securityGroups(Iterable<String> securityGroups) {\n         TemplateOptions options = new TemplateOptions();\n         return options.securityGroups(securityGroups);\n      }\n\n      /**\n       * @see TemplateOptions#securityGroups\n       */\n      public static TemplateOptions securityGroups(String... securityGroups) {\n         TemplateOptions options = new TemplateOptions();\n         return options.securityGroups(securityGroups);\n      }\n\n      /**\n       * @see TemplateOptions#networks\n       */\n      public static TemplateOptions networks(Iterable<String> networks) {\n         TemplateOptions options = new TemplateOptions();\n         return options.networks(networks);\n      }\n\n      /**\n       * @see TemplateOptions#networks\n       */\n      public static TemplateOptions networks(String... networks) {\n         TemplateOptions options = new TemplateOptions();\n         return options.networks(networks);\n      }\n\n      /**\n       * @see TemplateOptions#blockUntilRunning(boolean)\n       */\n      public static TemplateOptions blockUntilRunning(boolean blockUntilRunning) {\n         TemplateOptions options = new TemplateOptions();\n         return options.blockUntilRunning(blockUntilRunning);\n      }\n\n      /**\n       * @see TemplateOptions#runScript(Statement)\n       */\n      public static TemplateOptions runScript(Statement script) {\n         TemplateOptions options = new TemplateOptions();\n         return options.runScript(script);\n      }\n\n      /**\n       * @see TemplateOptions#runScript(String)\n       */\n      public static TemplateOptions runScript(String script) {\n         TemplateOptions options = new TemplateOptions();\n         return options.runScript(script);\n      }\n\n      /**\n       * please use alternative that uses the {@link org.jclouds.io.Payload}\n       * object\n       *\n       * @see org.jclouds.io.Payloads\n       * @see #installPrivateKey(Payload)\n       */\n         public static TemplateOptions installPrivateKey(String rsaKey) {\n         TemplateOptions options = new TemplateOptions();\n         return options.installPrivateKey(rsaKey);\n      }\n\n      /**\n       * please use alternative that uses the {@link org.jclouds.io.Payload}\n       * object\n       *\n       * @see #authorizePublicKey(String)\n       */\n      public static TemplateOptions authorizePublicKey(String rsaKey) {\n         TemplateOptions options = new TemplateOptions();\n         return options.authorizePublicKey(rsaKey);\n      }\n\n      /**\n       * @see TemplateOptions#userMetadata(Map)\n       */\n      public static TemplateOptions userMetadata(Map<String, String> userMetadata) {\n         TemplateOptions options = new TemplateOptions();\n         return options.userMetadata(userMetadata);\n      }\n\n      /**\n       * @see TemplateOptions#userMetadata(String, String)\n       */\n      public static TemplateOptions userMetadata(String key, String value) {\n         TemplateOptions options = new TemplateOptions();\n         return options.userMetadata(key, value);\n      }\n\n      public static TemplateOptions blockOnComplete(boolean value) {\n         TemplateOptions options = new TemplateOptions();\n         return options.blockOnComplete(value);\n      }\n\n   }\n\n   /**\n    * <h4>Note</h4> As of version 1.1.0, this option is incompatible with\n    * {@link TemplateOptions#runScript(Statement)} and\n    * {@link RunScriptOptions#blockOnComplete(boolean)}, as all current\n    * implementations utilize ssh in order to execute scripts.\n    *\n    * @param blockUntilRunning\n    *           (default true) whether to block until the nodes in this template\n    *           are in {@link Status#RUNNING} state\n    */\n   public TemplateOptions blockUntilRunning(boolean blockUntilRunning) {\n      this.blockUntilRunning = blockUntilRunning;\n      if (!blockUntilRunning)\n         port = seconds = -1;\n      return this;\n   }\n\n   /**\n    *\n    * @param userMetadata\n    *           user-defined metadata to assign to this server\n    */\n   public TemplateOptions userMetadata(Map<String, String> userMetadata) {\n      this.userMetadata.putAll(checkNotNull(userMetadata, \"userMetadata\"));\n      return this;\n   }\n\n   /**\n    *\n    * @param key\n    *           key to place into the metadata map\n    * @param value\n    *           value to associate with that key\n    */\n   public TemplateOptions userMetadata(String key, String value) {\n      this.userMetadata.put(checkNotNull(key, \"key\"), checkNotNull(value, \"value\"));\n      return this;\n   }\n\n   /**\n    * @see #userMetadata(Map)\n    */\n   public Map<String, String> getUserMetadata() {\n      return userMetadata;\n   }\n\n   @Override\n   public TemplateOptions blockOnPort(int port, int seconds) {\n      return TemplateOptions.class.cast(super.blockOnPort(port, seconds));\n   }\n\n   @Override\n   public TemplateOptions nameTask(String name) {\n      return TemplateOptions.class.cast(super.nameTask(name));\n   }\n\n   @Override\n   public TemplateOptions runAsRoot(boolean runAsRoot) {\n      return TemplateOptions.class.cast(super.runAsRoot(runAsRoot));\n   }\n\n   @Override\n   public TemplateOptions wrapInInitScript(boolean wrapInInitScript) {\n      return TemplateOptions.class.cast(super.wrapInInitScript(wrapInInitScript));\n   }\n\n   @Override\n   public TemplateOptions blockOnComplete(boolean blockOnComplete) {\n      return TemplateOptions.class.cast(super.blockOnComplete(blockOnComplete));\n   }\n\n   @Override\n   public TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials) {\n      return TemplateOptions.class.cast(super.overrideLoginCredentials(overridingCredentials));\n   }\n\n   @Override\n   public TemplateOptions overrideLoginPassword(String password) {\n      return TemplateOptions.class.cast(super.overrideLoginPassword(password));\n   }\n\n   @Override\n   public TemplateOptions overrideLoginPrivateKey(String privateKey) {\n      return TemplateOptions.class.cast(super.overrideLoginPrivateKey(privateKey));\n   }\n\n   @Override\n   public TemplateOptions overrideLoginUser(String loginUser) {\n      return TemplateOptions.class.cast(super.overrideLoginUser(loginUser));\n   }\n\n   @Override\n   public TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo) {\n      return TemplateOptions.class.cast(super.overrideAuthenticateSudo(authenticateSudo));\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/predicates/AtomicImageAvailable.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.predicates;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.domain.Image.Status;\nimport org.jclouds.compute.predicates.internal.RefreshImageAndDoubleCheckOnFailUnlessStatusInvalid;\nimport org.jclouds.compute.strategy.GetImageStrategy;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * \n * Tests to see if a image is available.\n */\n@Singleton\npublic class AtomicImageAvailable extends RefreshImageAndDoubleCheckOnFailUnlessStatusInvalid {\n\n   @Inject\n   public AtomicImageAvailable(GetImageStrategy client) {\n      super(Status.AVAILABLE, ImmutableSet.of(Status.ERROR, Status.DELETED), client);\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/predicates/AtomicImageDeleted.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.Image.Status;\nimport org.jclouds.compute.predicates.internal.TrueIfNullOrDeletedRefreshAndDoubleCheckOnFalse;\nimport org.jclouds.compute.strategy.GetImageStrategy;\n\nimport com.google.inject.Inject;\n\npublic class AtomicImageDeleted extends TrueIfNullOrDeletedRefreshAndDoubleCheckOnFalse<Image.Status, Image> {\n\n   private final GetImageStrategy client;\n\n   @Inject\n   public AtomicImageDeleted(GetImageStrategy client) {\n      super(Status.DELETED);\n      this.client = checkNotNull(client, \"client\");\n   }\n   \n   @Override\n   protected Image refreshOrNull(Image resource) {\n      if (resource == null || resource.getId() == null)\n         return null;\n      return client.getImage(resource.getId());\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/predicates/AtomicNodeRunning.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.predicates;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.domain.NodeMetadata.Status;\nimport org.jclouds.compute.predicates.internal.RefreshNodeAndDoubleCheckOnFailUnlessStatusInvalid;\nimport org.jclouds.compute.strategy.GetNodeMetadataStrategy;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * \n * Tests to see if a node is running.\n */\n@Singleton\npublic class AtomicNodeRunning extends RefreshNodeAndDoubleCheckOnFailUnlessStatusInvalid {\n\n   @Inject\n   public AtomicNodeRunning(GetNodeMetadataStrategy client) {\n      super(Status.RUNNING, ImmutableSet.of(Status.ERROR, Status.TERMINATED), client);\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/predicates/AtomicNodeSuspended.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.predicates;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.domain.NodeMetadata.Status;\nimport org.jclouds.compute.predicates.internal.RefreshNodeAndDoubleCheckOnFailUnlessStatusInvalid;\nimport org.jclouds.compute.strategy.GetNodeMetadataStrategy;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * \n * Tests to see if a node is suspended.\n */\n@Singleton\npublic class AtomicNodeSuspended extends RefreshNodeAndDoubleCheckOnFailUnlessStatusInvalid {\n\n   @Inject\n   public AtomicNodeSuspended(GetNodeMetadataStrategy client) {\n      super(Status.SUSPENDED, ImmutableSet.of(Status.ERROR, Status.TERMINATED), client);\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/predicates/AtomicNodeTerminated.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadata.Status;\nimport org.jclouds.compute.predicates.internal.TrueIfNullOrDeletedRefreshAndDoubleCheckOnFalse;\nimport org.jclouds.compute.strategy.GetNodeMetadataStrategy;\n\nimport com.google.inject.Inject;\n\npublic class AtomicNodeTerminated extends TrueIfNullOrDeletedRefreshAndDoubleCheckOnFalse<NodeMetadata.Status, NodeMetadata> {\n\n   private final GetNodeMetadataStrategy client;\n\n   @Inject\n   public AtomicNodeTerminated(GetNodeMetadataStrategy client) {\n      super(Status.TERMINATED);\n      this.client = checkNotNull(client, \"client\");\n   }\n   \n   @Override\n   protected NodeMetadata refreshOrNull(NodeMetadata resource) {\n      if (resource == null || resource.getId() == null)\n         return null;\n      return client.getNode(resource.getId());\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/predicates/HardwarePredicates.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.compute.domain.Hardware;\n\nimport com.google.common.base.Predicate;\n\n/**\n * Container for hardware filters (predicates).\n * \n * This class has static methods that create customized predicates to use with\n * {@link org.jclouds.compute.ComputeService}.\n */\npublic class HardwarePredicates {\n\n   public static Predicate<Hardware> idEquals(final String id) {\n      checkNotNull(id, \"id must be defined\");\n      return new Predicate<Hardware>() {\n         @Override\n         public boolean apply(Hardware hardware) {\n            return id.equals(hardware.getId());\n         }\n\n         @Override\n         public String toString() {\n            return \"idEquals(\" + id + \")\";\n         }\n      };\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/predicates/ImagePredicates.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.Image;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Predicates;\nimport com.google.common.collect.Sets;\n\n/**\n * Container for image filters (predicates).\n * \n * This class has static methods that create customized predicates to use with\n * {@link org.jclouds.compute.ComputeService}.\n */\npublic class ImagePredicates {\n   private static final class Is64BitPredicate implements Predicate<Image> {\n      @Override\n      public boolean apply(Image image) {\n         return image.getOperatingSystem().is64Bit();\n      }\n\n      @Override\n      public String toString() {\n         return \"is64Bit()\";\n      }\n\n      @Override\n      public boolean equals(Object obj) {\n         return obj instanceof Is64BitPredicate;\n      }\n\n      @Override\n      public int hashCode() {\n         return 0;\n      }\n   }\n\n   /**\n    * evaluates true if the Image id is in the supplied set\n    * \n    * @param ids\n    *           ids of the images\n    * @return predicate\n    */\n   public static Predicate<Image> idIn(Iterable<String> ids) {\n      checkNotNull(ids, \"ids must be defined\");\n      final Set<String> search = Sets.newHashSet(ids);\n      return new Predicate<Image>() {\n         @Override\n         public boolean apply(Image image) {\n            return search.contains(image.getId());\n         }\n\n         @Override\n         public String toString() {\n            return \"idIn(\" + search + \")\";\n         }\n      };\n   }\n   \n   /**\n    * evaluates true if the Image metadata contains the following values\n    * \n    * @param key\n    *           key in Image#getUserMetadata\n    * @param value\n    *           value in Image#getUserMetadata\n     * @return predicate\n    */\n   public static Predicate<Image> userMetadataContains(final String key, final String value) {\n      checkNotNull(key, \"key must be defined\");\n      checkNotNull(value, \"value must be defined\");\n      return new Predicate<Image>() {\n         @Override\n         public boolean apply(Image image) {\n            return value.equals(image.getUserMetadata().get(key));\n         }\n\n         @Override\n         public String toString() {\n            return \"metadataContains(\" + key + \", \" + value + \")\";\n         }\n      };\n   }\n\n   /**\n    * evaluates true if the Image\n    * \n    * @param ids\n    *           ids of the images\n    * @return predicate\n    */\n   public static Predicate<Image> idEquals(final String id) {\n      checkNotNull(id, \"id must be defined\");\n      return new Predicate<Image>() {\n         @Override\n         public boolean apply(Image image) {\n            return id.equals(image.getId());\n         }\n\n         @Override\n         public String toString() {\n            return \"idEquals(\" + id + \")\";\n         }\n      };\n   }\n\n   /**\n    * return true if this is a 64bit image.\n    */\n   public static Predicate<Image> is64Bit() {\n      return new Is64BitPredicate();\n   }\n\n   /**\n    * return everything.\n    */\n   public static Predicate<Image> any() {\n      return Predicates.<Image> alwaysTrue();\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/predicates/NodePredicates.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Strings.emptyToNull;\n\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.ComputeMetadata;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadata.Status;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Predicates;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Container for node filters (predicates).\n * \n * This class has static methods that create customized predicates to use with\n * {@link org.jclouds.compute.ComputeService}.\n */\npublic class NodePredicates {\n\n   private static class ParentLocationId implements Predicate<ComputeMetadata> {\n      private final String id;\n\n      private ParentLocationId(String id) {\n         this.id = id;\n      }\n\n      @Override\n      public int hashCode() {\n         final int prime = 31;\n         int result = 1;\n         result = prime * result + ((id == null) ? 0 : id.hashCode());\n         return result;\n      }\n\n      @Override\n      public boolean equals(Object obj) {\n         if (this == obj)\n            return true;\n         if (obj == null)\n            return false;\n         if (getClass() != obj.getClass())\n            return false;\n         ParentLocationId other = (ParentLocationId) obj;\n         if (id == null) {\n            if (other.id != null)\n               return false;\n         } else if (!id.equals(other.id))\n            return false;\n         return true;\n      }\n\n      @Override\n      public boolean apply(ComputeMetadata nodeMetadata) {\n         if (nodeMetadata.getLocation().getParent() == null)\n            return false;\n         return id.equals(nodeMetadata.getLocation().getParent().getId());\n      }\n\n      @Override\n      public String toString() {\n         return \"ParentLocationId [id=\" + id + \"]\";\n      }\n   }\n\n   private static class LocationId implements Predicate<ComputeMetadata> {\n      @Override\n      public int hashCode() {\n         final int prime = 31;\n         int result = 1;\n         result = prime * result + ((id == null) ? 0 : id.hashCode());\n         return result;\n      }\n\n      @Override\n      public boolean equals(Object obj) {\n         if (this == obj)\n            return true;\n         if (obj == null)\n            return false;\n         if (getClass() != obj.getClass())\n            return false;\n         LocationId other = (LocationId) obj;\n         if (id == null) {\n            if (other.id != null)\n               return false;\n         } else if (!id.equals(other.id))\n            return false;\n         return true;\n      }\n\n      private final String id;\n\n      private LocationId(String id) {\n         this.id = id;\n      }\n\n      @Override\n      public boolean apply(ComputeMetadata nodeMetadata) {\n         return id.equals(nodeMetadata.getLocation().getId());\n      }\n\n      @Override\n      public String toString() {\n         return \"locationId(\" + id + \")\";\n      }\n   }\n\n   /**\n    * Return nodes in the specified location.\n    * \n    * @param id\n    *           id of the location\n    * @return predicate\n    */\n   public static Predicate<ComputeMetadata> locationId(final String id) {\n      checkNotNull(id, \"id must be defined\");\n      return new LocationId(id);\n   }\n\n   /**\n    * Return nodes in the specified parent location.\n    * \n    * @param id\n    *           id of the location\n    * @return predicate\n    */\n   public static Predicate<ComputeMetadata> parentLocationId(final String id) {\n      checkNotNull(id, \"id must be defined\");\n      return new ParentLocationId(id);\n   }\n\n   /**\n    * Return nodes with the specific ids Note: returns all nodes, regardless of the state.\n    * \n    * @param ids\n    *           ids of the resources\n    * @return predicate\n    */\n   public static <T extends ComputeMetadata> Predicate<T> withIds(String... ids) {\n      checkNotNull(ids, \"ids must be defined\");\n      final Set<String> search = ImmutableSet.copyOf(ids);\n      return new Predicate<T>() {\n         @Override\n         public boolean apply(T nodeMetadata) {\n            return search.contains(nodeMetadata.getId());\n         }\n\n         @Override\n         public String toString() {\n            return \"withIds(\" + search + \")\";\n         }\n      };\n   }\n\n   /**\n    * return everything.\n    */\n   public static Predicate<ComputeMetadata> all() {\n      return Predicates.<ComputeMetadata> alwaysTrue();\n   }\n\n   /**\n    * Return nodes in the specified group. Note: returns all nodes, regardless of the state.\n    * \n    * @param group\n    *           group to match the items\n    * @return predicate\n    */\n   public static Predicate<NodeMetadata> inGroup(final String group) {\n      checkNotNull(emptyToNull(group), \"group must be defined\");\n      return new Predicate<NodeMetadata>() {\n         @Override\n         public boolean apply(NodeMetadata nodeMetadata) {\n            return group.equals(nodeMetadata.getGroup());\n         }\n\n         @Override\n         public String toString() {\n            return \"inGroup(\" + group + \")\";\n         }\n      };\n   }\n   \n   /**\n    * Return nodes who have a value for {@link NodeMetadata#getGroup}\n    * \n    */\n   public static Predicate<NodeMetadata> hasGroup() {\n      return new Predicate<NodeMetadata>() {\n         @Override\n         public boolean apply(NodeMetadata nodeMetadata) {\n            return nodeMetadata != null && nodeMetadata.getGroup() != null;\n         }\n\n         @Override\n         public String toString() {\n            return \"hasGroup()\";\n         }\n      };\n   }\n   \n   /**\n    * Return nodes with specified group that are in the NODE_RUNNING state.\n    * \n    * @param group\n    *           group to match the items\n    * @return predicate\n    */\n   public static Predicate<NodeMetadata> runningInGroup(final String group) {\n      checkNotNull(emptyToNull(group), \"group must be defined\");\n      return new Predicate<NodeMetadata>() {\n         @Override\n         public boolean apply(NodeMetadata nodeMetadata) {\n            return group.equals(nodeMetadata.getGroup()) && nodeMetadata.getStatus() == Status.RUNNING;\n         }\n\n         @Override\n         public String toString() {\n            return \"runningInGroup(\" + group + \")\";\n         }\n      };\n   }\n\n   /**\n    * Match nodes with State == RUNNING\n    */\n   public static final Predicate<NodeMetadata> RUNNING = new Predicate<NodeMetadata>() {\n      @Override\n      public boolean apply(NodeMetadata nodeMetadata) {\n         return nodeMetadata.getStatus() == Status.RUNNING;\n      }\n\n      @Override\n      public String toString() {\n         return Status.RUNNING.toString();\n      }\n   };\n\n   /**\n    * Match nodes with State == NODE_TERMINATED\n    */\n   public static final Predicate<NodeMetadata> TERMINATED = new Predicate<NodeMetadata>() {\n      @Override\n      public boolean apply(NodeMetadata nodeMetadata) {\n         return nodeMetadata.getStatus() == Status.TERMINATED;\n      }\n\n      @Override\n      public String toString() {\n         return Status.TERMINATED.toString();\n      }\n   };\n\n   /**\n    * Match nodes with State == SUSPENDED\n    */\n   public static final Predicate<NodeMetadata> SUSPENDED = new Predicate<NodeMetadata>() {\n      @Override\n      public boolean apply(NodeMetadata nodeMetadata) {\n         return nodeMetadata.getStatus() == Status.SUSPENDED;\n      }\n\n      @Override\n      public String toString() {\n         return Status.SUSPENDED.toString();\n      }\n   };\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/predicates/OperatingSystemPredicates.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.predicates;\n\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.OperatingSystem;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Predicates;\nimport com.google.common.collect.Sets;\n\n/**\n * Container for operating system filters (predicates).\n * \n * This class has static methods that create customized predicates to use with\n * {@link org.jclouds.compute.ComputeService}.\n */\npublic class OperatingSystemPredicates {\n   /**\n    * evaluates true if the OperatingSystem is unix like\n    * \n    */\n   public static Predicate<OperatingSystem> isUnix() {\n      return new Predicate<OperatingSystem>() {\n         @Override\n         public boolean apply(OperatingSystem os) {\n            if (os.getFamily() != null) {\n               switch (os.getFamily()) {\n                  case WINDOWS:\n                     return false;\n               }\n            }\n            for (String toMatch : searchStrings(os))\n               if (toMatch != null && toMatch.toLowerCase().indexOf(\"windows\") != -1)\n                  return false;\n            return true;\n         }\n\n         @Override\n         public String toString() {\n            return \"isUnix()\";\n         }\n      };\n   }\n\n   /**\n    * evaluates true if the OperatingSystem supports the apt installer\n    * \n    */\n   public static Predicate<OperatingSystem> supportsApt() {\n      return new Predicate<OperatingSystem>() {\n         @Override\n         public boolean apply(OperatingSystem os) {\n            if (os.getFamily() != null) {\n               switch (os.getFamily()) {\n                  case DEBIAN:\n                  case UBUNTU:\n                     return true;\n               }\n            }\n            for (String toMatch : searchStrings(os))\n               if (toMatch != null && (toMatch.toLowerCase().indexOf(\"ubuntu\") != -1\n                        || toMatch.toLowerCase().indexOf(\"debian\") != -1))\n                  return true;\n            return false;\n         }\n\n         @Override\n         public String toString() {\n            return \"supportsApt()\";\n         }\n      };\n   }\n\n   /**\n    * evaluates true if the OperatingSystem supports the yum installer\n    * \n    */\n   public static Predicate<OperatingSystem> supportsYum() {\n      return new Predicate<OperatingSystem>() {\n         @Override\n         public boolean apply(OperatingSystem os) {\n            if (os.getFamily() != null) {\n               switch (os.getFamily()) {\n                  case CENTOS:\n                  case AMZN_LINUX:\n                  case FEDORA:\n                  case RHEL:\n                     return true;\n               }\n            }\n\n            for (String toMatch : searchStrings(os))\n               if (toMatch.toLowerCase().indexOf(\"centos\") != -1 || toMatch.toLowerCase().indexOf(\"rhel\") != -1\n                        || toMatch.toLowerCase().replace(\" \", \"\").indexOf(\"redhate\") != -1\n                        || toMatch.toLowerCase().indexOf(\"fedora\") != -1)\n                  return true;\n            return false;\n         }\n\n         @Override\n         public String toString() {\n            return \"supportsYum()\";\n         }\n      };\n   }\n\n   /**\n    * evaluates true if the OperatingSystem supports the zypper installer\n    * \n    */\n   public static Predicate<OperatingSystem> supportsZypper() {\n      return new Predicate<OperatingSystem>() {\n         @Override\n         public boolean apply(OperatingSystem os) {\n            if (os.getFamily() != null) {\n               switch (os.getFamily()) {\n                  case SUSE:\n                     return true;\n               }\n            }\n            for (String toMatch : searchStrings(os))\n               if (toMatch != null && toMatch.toLowerCase().indexOf(\"suse\") != -1)\n                  return true;\n            return false;\n         }\n\n         @Override\n         public String toString() {\n            return \"supportsZypper()\";\n         }\n      };\n   }\n\n   /**\n    * return everything.\n    */\n   public static Predicate<OperatingSystem> any() {\n      return Predicates.<OperatingSystem> alwaysTrue();\n   }\n\n   /**\n    * return true if this is a 64bit os.\n    */\n   public static Predicate<OperatingSystem> is64Bit() {\n      return new Predicate<OperatingSystem>() {\n         @Override\n         public boolean apply(OperatingSystem os) {\n            return os.is64Bit();\n         }\n\n         @Override\n         public String toString() {\n            return \"is64Bit()\";\n         }\n      };\n   }\n\n   static Iterable<String> searchStrings(OperatingSystem os) {\n      Set<String> search = Sets.newLinkedHashSet();\n      if (os.getName() != null)\n         search.add(os.getName());\n      if (os.getDescription() != null)\n         search.add(os.getDescription());\n      return search;\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/predicates/ScriptStatusReturnsZero.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.predicates;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.domain.ExecResponse;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.ssh.SshClient;\n\nimport com.google.common.base.Predicate;\n\n/**\n * \n * Tests to if the runscript is still running\n */\n@Singleton\npublic class ScriptStatusReturnsZero implements Predicate<ScriptStatusReturnsZero.CommandUsingClient> {\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   @Override\n   public boolean apply(CommandUsingClient commandUsingClient) {\n      logger.trace(\"looking for [%s] state on %s@%s\", commandUsingClient.command, commandUsingClient.client\n               .getUsername(), commandUsingClient.client.getHostAddress());\n      ExecResponse response = refresh(commandUsingClient);\n      while (response.getExitStatus() == -1)\n         response = refresh(commandUsingClient);\n      logger.trace(\"%s@%s: looking for exit code 0: currently: %s\", commandUsingClient.client.getUsername(),\n               commandUsingClient.client.getHostAddress(), response.getExitStatus());\n      return 0 == response.getExitStatus();\n   }\n\n   private ExecResponse refresh(CommandUsingClient commandUsingClient) {\n      return commandUsingClient.client.exec(commandUsingClient.command);\n   }\n\n   public static class CommandUsingClient {\n\n      public CommandUsingClient(String command, SshClient client) {\n         this.command = command;\n         this.client = client;\n      }\n\n      private final String command;\n      private final SshClient client;\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/predicates/internal/RefreshAndDoubleCheckOnFailUnlessStatusInvalid.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.predicates.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.compute.util.ComputeServiceUtils.formatStatus;\n\nimport java.util.Set;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport jakarta.annotation.Resource;\n\nimport org.jclouds.compute.domain.ComputeMetadataIncludingStatus;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * \n * Keep an atomic reference to a\n * resource, so as to eliminate a redundant {@link ComputeService#getNodeMetadata} call after the\n * predicate passes.\n */\npublic abstract class RefreshAndDoubleCheckOnFailUnlessStatusInvalid<S extends Enum<S>, C extends ComputeMetadataIncludingStatus<S>> implements Predicate<AtomicReference<C>> {\n\n   private final S intended;\n   private final Set<S> invalids;\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   public RefreshAndDoubleCheckOnFailUnlessStatusInvalid(S intended, Set<S> invalids) {\n      this.intended = checkNotNull(intended, \"intended\");\n      this.invalids = ImmutableSet.copyOf(checkNotNull(invalids, \"invalids\"));\n   }\n\n   public boolean apply(AtomicReference<C> atomicResource) {\n      C resource = atomicResource.get();\n      if (checkStatus(resource))\n         return true;\n      resource = refreshOrNull(resource);\n      atomicResource.set(resource);\n      return checkStatus(resource);\n   }\n\n   public boolean checkStatus(C resource) {\n      if (resource == null)\n         return false;\n      logger.trace(\"%s: looking for resource state %s: currently: %s\", resource.getId(), intended, formatStatus(resource));\n      if (invalids.contains(resource.getStatus()))\n         throw new IllegalStateException(\"resource \" + resource.getId() + \" in location \" + resource.getLocation()\n                  + \" is in invalid status \" + formatStatus(resource));\n      return resource.getStatus() == intended;\n   }\n\n   protected abstract C refreshOrNull(C resource);\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/predicates/internal/RefreshImageAndDoubleCheckOnFailUnlessStatusInvalid.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.predicates.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Set;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.Image.Status;\nimport org.jclouds.compute.strategy.GetImageStrategy;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Inject;\n\n/**\n * \n * The point of RefreshAndDoubleCheckOnFailUnlessStateInvalid is to keep an atomic reference to a\n * image, so as to eliminate a redundant {@link ComputeService#getImage} call after the\n * predicate passes.\n */\n@Singleton\npublic class RefreshImageAndDoubleCheckOnFailUnlessStatusInvalid extends RefreshAndDoubleCheckOnFailUnlessStatusInvalid<Image.Status, Image> {\n\n   private final GetImageStrategy client;\n\n   @Inject\n   public RefreshImageAndDoubleCheckOnFailUnlessStatusInvalid(Status intended, GetImageStrategy client) {\n      this(intended, ImmutableSet.of(Status.ERROR), client);\n   }\n\n   public RefreshImageAndDoubleCheckOnFailUnlessStatusInvalid(Status intended, Set<Status> invalids,\n            GetImageStrategy client) {\n      super(intended, invalids);\n      this.client = checkNotNull(client, \"client\");\n   }\n\n   @Override\n   protected Image refreshOrNull(Image resource) {\n      if (resource == null || resource.getId() == null)\n         return null;\n      return client.getImage(resource.getId());\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/predicates/internal/RefreshNodeAndDoubleCheckOnFailUnlessStatusInvalid.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.predicates.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Set;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadata.Status;\nimport org.jclouds.compute.strategy.GetNodeMetadataStrategy;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Inject;\n\n/**\n * \n * The point of RefreshAndDoubleCheckOnFailUnlessStateInvalid is to keep an atomic reference to a\n * node, so as to eliminate a redundant {@link ComputeService#getNodeMetadata} call after the\n * predicate passes.\n */\n@Singleton\npublic class RefreshNodeAndDoubleCheckOnFailUnlessStatusInvalid extends RefreshAndDoubleCheckOnFailUnlessStatusInvalid<NodeMetadata.Status, NodeMetadata> {\n\n   private final GetNodeMetadataStrategy client;\n\n   @Inject\n   public RefreshNodeAndDoubleCheckOnFailUnlessStatusInvalid(Status intended, GetNodeMetadataStrategy client) {\n      this(intended, ImmutableSet.of(Status.ERROR), client);\n   }\n\n   public RefreshNodeAndDoubleCheckOnFailUnlessStatusInvalid(Status intended, Set<Status> invalids,\n            GetNodeMetadataStrategy client) {\n      super(intended, invalids);\n      this.client = checkNotNull(client, \"client\");\n   }\n\n   @Override\n   protected NodeMetadata refreshOrNull(NodeMetadata resource) {\n      if (resource == null || resource.getId() == null)\n         return null;\n      return client.getNode(resource.getId());\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/predicates/internal/TrueIfNullOrDeletedRefreshAndDoubleCheckOnFalse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.predicates.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.compute.util.ComputeServiceUtils.formatStatus;\n\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport jakarta.annotation.Resource;\n\nimport org.jclouds.compute.domain.ComputeMetadataIncludingStatus;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Predicate;\n\npublic abstract class TrueIfNullOrDeletedRefreshAndDoubleCheckOnFalse<S extends Enum<S>, C extends ComputeMetadataIncludingStatus<S>>\n         implements Predicate<AtomicReference<C>> {\n   protected final S deletedStatus;\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   protected TrueIfNullOrDeletedRefreshAndDoubleCheckOnFalse(S deletedStatus) {\n      this.deletedStatus = checkNotNull(deletedStatus, \"deletedStatus\");\n   }\n\n   public boolean apply(AtomicReference<C> atomicResource) {\n      C resource = atomicResource.get();\n      if (checkStatus(resource))\n         return true;\n      resource = refreshOrNull(resource);\n      atomicResource.set(resource);\n      return checkStatus(resource);\n   }\n\n   public boolean checkStatus(C resource) {\n      if (resource == null)\n         return true;\n      logger.trace(\"%s: looking for resource status %s: currently: %s\", resource.getId(), deletedStatus, formatStatus(resource));\n      return resource.getStatus() == deletedStatus;\n   }\n\n   protected abstract C refreshOrNull(C resource);\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/reference/ComputeServiceConstants.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.reference;\nimport static org.jclouds.compute.config.ComputeServiceProperties.INIT_STATUS_INITIAL_PERIOD;\nimport static org.jclouds.compute.config.ComputeServiceProperties.INIT_STATUS_MAX_PERIOD;\nimport static org.jclouds.compute.config.ComputeServiceProperties.OS_VERSION_MAP_JSON;\nimport static org.jclouds.compute.config.ComputeServiceProperties.POLL_INITIAL_PERIOD;\nimport static org.jclouds.compute.config.ComputeServiceProperties.POLL_MAX_PERIOD;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_CLEANUP_INCIDENTAL_RESOURCES;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_IMAGE_AVAILABLE;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_IMAGE_DELETED;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_RUNNING;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_SUSPENDED;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_TERMINATED;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_PORT_OPEN;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_SCRIPT_COMPLETE;\n\nimport java.security.SecureRandom;\nimport java.util.concurrent.TimeUnit;\n\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.util.Predicates2;\n\nimport com.google.common.base.Supplier;\nimport com.google.inject.Inject;\n\npublic final class ComputeServiceConstants {\n\n   public static final String COMPUTE_LOGGER = \"jclouds.compute\";\n   public static final String LOCAL_PARTITION_GB_PATTERN = \"disk_drive/%s/gb\";\n   public static final String NODE_GROUP_KEY = \"jclouds-group\";\n\n   @Singleton\n   public static class NamingConvention {\n      @Inject(optional = true)\n      public Supplier<String> randomSuffix = new Supplier<String>() {\n         final SecureRandom random = new SecureRandom();\n\n         @Override\n         public String get() {\n            return random.nextInt(100) + \"\";\n         }\n      };\n   }\n\n   @Singleton\n   public static class InitStatusProperties {\n      @Inject(optional = true)\n      @Named(INIT_STATUS_INITIAL_PERIOD)\n      public long initStatusInitialPeriod = 500;\n\n      @Inject(optional = true)\n      @Named(INIT_STATUS_MAX_PERIOD)\n      public long initStatusMaxPeriod = 5000;\n   }\n\n   @Singleton\n   public static class PollPeriod {\n      @Inject(optional = true)\n      @Named(POLL_INITIAL_PERIOD)\n      public long pollInitialPeriod = Predicates2.DEFAULT_PERIOD;\n\n      @Inject(optional = true)\n      @Named(POLL_MAX_PERIOD)\n      public long pollMaxPeriod = Predicates2.DEFAULT_MAX_PERIOD;\n   }\n\n   @Singleton\n   public static class ReferenceData {\n      @Inject(optional = true)\n      @Named(OS_VERSION_MAP_JSON)\n      // TODO: switch this to read from resource, failing back to string\n      // constant on classpath problem\n      public String osVersionMapJson = \"{\\\"suse\\\":{\\\"\\\":\\\"\\\",\\\"11\\\":\\\"11\\\",\\\"11 SP1\\\":\\\"11 SP1\\\"}, \\\"debian\\\":{\\\"\\\":\\\"\\\",\\\"lenny\\\":\\\"5.0\\\",\\\"6\\\":\\\"6.0\\\",\\\"squeeze\\\":\\\"6.0\\\"},\\\"centos\\\":{\\\"\\\":\\\"\\\",\\\"5\\\":\\\"5.0\\\",\\\"5.2\\\":\\\"5.2\\\",\\\"5.3\\\":\\\"5.3\\\",\\\"5.4\\\":\\\"5.4\\\",\\\"5.5\\\":\\\"5.5\\\",\\\"5.6\\\":\\\"5.6\\\",\\\"5.7\\\":\\\"5.7\\\",\\\"6\\\":\\\"6.0\\\",\\\"6.0\\\":\\\"6.0\\\",\\\"6.2\\\":\\\"6.2\\\",\\\"6.3\\\":\\\"6.3\\\",\\\"6.4\\\":\\\"6.4\\\",\\\"6.5\\\":\\\"6.5\\\",\\\"6.6\\\":\\\"6.6\\\",\\\"6.7\\\":\\\"6.7\\\",\\\"6.8\\\":\\\"6.8\\\",\\\"7\\\":\\\"7.0\\\",\\\"7.0\\\":\\\"7.0\\\",\\\"7.1\\\":\\\"7.1\\\",\\\"7.2\\\":\\\"7.2\\\",\\\"7.3\\\":\\\"7.3\\\",\\\"7.4\\\":\\\"7.4\\\"},\\\"rhel\\\":{\\\"\\\":\\\"\\\",\\\"5\\\":\\\"5.0\\\",\\\"5.2\\\":\\\"5.2\\\",\\\"5.3\\\":\\\"5.3\\\",\\\"5.4\\\":\\\"5.4\\\",\\\"5.5\\\":\\\"5.5\\\",\\\"5.6\\\":\\\"5.6\\\",\\\"5.7\\\":\\\"5.7\\\",\\\"6\\\":\\\"6.0\\\",\\\"6.0\\\":\\\"6.0\\\",\\\"6.1\\\":\\\"6.1\\\",\\\"6.3\\\":\\\"6.3\\\",\\\"6.4\\\":\\\"6.4\\\",\\\"6.5\\\":\\\"6.5\\\",\\\"6.6\\\":\\\"6.6\\\",\\\"7\\\":\\\"7.0\\\",\\\"7.0\\\":\\\"7.0\\\",\\\"7.1\\\":\\\"7.1\\\",\\\"7.2\\\":\\\"7.2\\\",\\\"7.3\\\":\\\"7.3\\\",\\\"7.4\\\":\\\"7.4\\\"},\\\"solaris\\\":{\\\"\\\":\\\"\\\",\\\"10\\\":\\\"10\\\"},\\\"ubuntu\\\":{\\\"\\\":\\\"\\\",\\\"hardy\\\":\\\"8.04\\\",\\\"karmic\\\":\\\"9.10\\\",\\\"lucid\\\":\\\"10.04\\\",\\\"10.04.1\\\":\\\"10.04\\\",\\\"maverick\\\":\\\"10.10\\\",\\\"natty\\\":\\\"11.04\\\",\\\"oneiric\\\":\\\"11.10\\\",\\\"precise\\\":\\\"12.04\\\",\\\"quantal\\\":\\\"12.10\\\",\\\"raring\\\":\\\"13.04\\\",\\\"saucy\\\":\\\"13.10\\\",\\\"trusty\\\":\\\"14.04\\\",\\\"utopic\\\":\\\"14.10\\\",\\\"vivid\\\":\\\"15.04\\\",\\\"wily\\\":\\\"15.10\\\",\\\"xenial\\\":\\\"16.04\\\",\\\"yakkety\\\":\\\"16.10\\\",\\\"zesty\\\":\\\"17.04\\\"},\\\"windows\\\":{\\\"\\\":\\\"\\\",\\\"7\\\":\\\"7\\\",\\\"2003\\\":\\\"2003\\\",\\\"2003 Standard\\\":\\\"2003\\\",\\\"2003 R2\\\":\\\"2003 R2\\\",\\\"2008\\\":\\\"2008\\\",\\\"2008 Web\\\":\\\"2008\\\",\\\"2008 Server\\\":\\\"2008\\\",\\\"Server 2008\\\":\\\"2008\\\",\\\"2008 R1\\\":\\\"2008 R1\\\",\\\"2008 R2\\\":\\\"2008 R2\\\",\\\"Server 2008 R2\\\":\\\"2008 R2\\\",\\\"2008 Server R2\\\":\\\"2008 R2\\\",\\\"2008 SP2\\\":\\\"2008 SP2\\\",\\\"Server 2008 SP2\\\":\\\"2008 SP2\\\"}}\";\n   }\n\n   @Singleton\n   public static class Timeouts {\n      @Inject(optional = true)\n      @Named(TIMEOUT_NODE_TERMINATED)\n      public long nodeTerminated = 30 * 1000;\n\n      @Inject(optional = true)\n      @Named(TIMEOUT_NODE_RUNNING)\n      public long nodeRunning = 1200 * 1000;\n\n      @Inject(optional = true)\n      @Named(TIMEOUT_NODE_SUSPENDED)\n      public long nodeSuspended = 30 * 1000;\n\n      @Inject(optional = true)\n      @Named(TIMEOUT_SCRIPT_COMPLETE)\n      public long scriptComplete = 600 * 1000;\n\n      @Inject(optional = true)\n      @Named(TIMEOUT_PORT_OPEN)\n      public long portOpen = 600 * 1000;\n\n      /**\n       * current value of {@link ComputeServiceProperties#TIMEOUT_IMAGE_DELETED} defaults to 30\n       * seconds.\n       */\n      @Inject(optional = true)\n      @Named(TIMEOUT_IMAGE_DELETED)\n      public long imageDeleted = TimeUnit.SECONDS.toMillis(30);\n\n      /**\n       * current value of {@link ComputeServiceProperties#TIMEOUT_IMAGE_AVAILABLE} defaults to 45\n       * minutes.\n       */\n      @Inject(optional = true)\n      @Named(TIMEOUT_IMAGE_AVAILABLE)\n      public long imageAvailable = TimeUnit.MINUTES.toMillis(45);\n\n      /**\n       * current value of {@link ComputeServiceProperties#TIMEOUT_CLEANUP_INCIDENTAL_RESOURCES} defaults to 3\n       * seconds.\n       */\n      @Inject(optional = true)\n      @Named(TIMEOUT_CLEANUP_INCIDENTAL_RESOURCES)\n      public long cleanupIncidentalResources = TimeUnit.SECONDS.toMillis(3);\n   }\n\n   private ComputeServiceConstants() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/strategy/CreateNodeWithGroupEncodedIntoName.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.strategy;\n\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.Template;\n\n/**\n * Adds a node into an existing tag set, or creates one new.\n */\npublic interface CreateNodeWithGroupEncodedIntoName {\n\n   /**\n    * create a node given the name and template parameters such as imageid, hardwareid, and\n    * locationid.\n    * \n    * @param group\n    *           group name supplied by the user\n    * @param name\n    *           supplied by {@link CreateNodesInGroupThenAddToSet } and must have the tag encoded into\n    *           it.\n    * @param template\n    *           supplied by the user\n    * @return NodeMetadata from the new object, most likely in some pending state.\n    */\n   NodeMetadata createNodeWithGroupEncodedIntoName(String group, String name, Template template);\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/strategy/CreateNodesInGroupThenAddToSet.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.strategy;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.compute.config.CustomizationResponse;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.strategy.impl.CreateNodesWithGroupEncodedIntoNameThenAddToSet;\n\nimport com.google.common.collect.Multimap;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.inject.ImplementedBy;\n\n@ImplementedBy(CreateNodesWithGroupEncodedIntoNameThenAddToSet.class)\npublic interface CreateNodesInGroupThenAddToSet {\n\n   Map<?, ListenableFuture<Void>> execute(String group, int count, Template template, Set<NodeMetadata> goodNodes,\n            Map<NodeMetadata, Exception> badNodes, Multimap<NodeMetadata, CustomizationResponse> customizationResponses);\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/strategy/CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.strategy;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.common.base.Throwables.getRootCause;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_RUNNING;\n\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\n\nimport org.jclouds.compute.callables.RunScriptOnNode;\nimport org.jclouds.compute.config.CustomizationResponse;\nimport org.jclouds.compute.domain.ExecResponse;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.functions.NodeAndTemplateOptionsToStatement;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.compute.util.OpenSocketFinder;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.scriptbuilder.domain.Statement;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.Multimap;\nimport com.google.inject.assistedinject.Assisted;\nimport com.google.inject.assistedinject.AssistedInject;\n\npublic class CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap implements Callable<Void>,\n      Function<AtomicReference<NodeMetadata>, Void> {\n\n   public interface Factory {\n      Callable<Void> create(TemplateOptions options, AtomicReference<NodeMetadata> node, Set<NodeMetadata> goodNodes,\n            Map<NodeMetadata, Exception> badNodes, Multimap<NodeMetadata, CustomizationResponse> customizationResponses);\n\n      Function<AtomicReference<NodeMetadata>, Void> create(TemplateOptions options, Set<NodeMetadata> goodNodes,\n            Map<NodeMetadata, Exception> badNodes, Multimap<NodeMetadata, CustomizationResponse> customizationResponses);\n   }\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   private final Function<AtomicReference<NodeMetadata>, AtomicReference<NodeMetadata>> pollNodeRunning;\n   private final InitializeRunScriptOnNodeOrPlaceInBadMap.Factory initScriptRunnerFactory;\n   private final OpenSocketFinder openSocketFinder;\n\n   @Nullable\n   private final NodeAndTemplateOptionsToStatement nodeAndTemplateOptionsToStatement;\n   private final TemplateOptions options;\n   private AtomicReference<NodeMetadata> node;\n   private final Set<NodeMetadata> goodNodes;\n   private final Map<NodeMetadata, Exception> badNodes;\n   private final Multimap<NodeMetadata, CustomizationResponse> customizationResponses;\n\n   private transient boolean tainted;\n\n   @AssistedInject\n   public CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap(\n         @Named(TIMEOUT_NODE_RUNNING) Function<AtomicReference<NodeMetadata>, AtomicReference<NodeMetadata>> pollNodeRunning,\n         OpenSocketFinder openSocketFinder, NodeAndTemplateOptionsToStatement nodeAndTemplateOptionsToStatement,\n         InitializeRunScriptOnNodeOrPlaceInBadMap.Factory initScriptRunnerFactory, @Assisted TemplateOptions options,\n         @Assisted AtomicReference<NodeMetadata> node, @Assisted Set<NodeMetadata> goodNodes,\n         @Assisted Map<NodeMetadata, Exception> badNodes,\n         @Assisted Multimap<NodeMetadata, CustomizationResponse> customizationResponses) {\n      this.nodeAndTemplateOptionsToStatement = checkNotNull(nodeAndTemplateOptionsToStatement,\n            \"nodeAndTemplateOptionsToStatement\");\n      this.pollNodeRunning = checkNotNull(pollNodeRunning, \"pollNodeRunning\");\n      this.initScriptRunnerFactory = checkNotNull(initScriptRunnerFactory, \"initScriptRunnerFactory\");\n      this.openSocketFinder = checkNotNull(openSocketFinder, \"openSocketFinder\");\n      this.node = node;\n      this.options = checkNotNull(options, \"options\");\n      this.goodNodes = checkNotNull(goodNodes, \"goodNodes\");\n      this.badNodes = checkNotNull(badNodes, \"badNodes\");\n      this.customizationResponses = checkNotNull(customizationResponses, \"customizationResponses\");\n   }\n\n   @AssistedInject\n   public CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap(\n         @Named(TIMEOUT_NODE_RUNNING) Function<AtomicReference<NodeMetadata>, AtomicReference<NodeMetadata>> pollNodeRunning,\n         GetNodeMetadataStrategy getNode, OpenSocketFinder openSocketFinder,\n         NodeAndTemplateOptionsToStatement nodeAndTemplateOptionsToStatement,\n         InitializeRunScriptOnNodeOrPlaceInBadMap.Factory initScriptRunnerFactory, @Assisted TemplateOptions options,\n         @Assisted Set<NodeMetadata> goodNodes, @Assisted Map<NodeMetadata, Exception> badNodes,\n         @Assisted Multimap<NodeMetadata, CustomizationResponse> customizationResponses) {\n      this(pollNodeRunning, openSocketFinder, nodeAndTemplateOptionsToStatement, initScriptRunnerFactory, options,\n            new AtomicReference<NodeMetadata>(null), goodNodes, badNodes, customizationResponses);\n   }\n\n   @Override\n   public Void call() {\n      checkState(!tainted, \"this object is not designed to be reused: %s\", toString());\n      tainted = true;\n      String originalId = node.get().getId();\n      try {\n         if (options.shouldBlockUntilRunning()) {\n            pollNodeRunning.apply(node);\n            Statement statement = nodeAndTemplateOptionsToStatement.apply(node.get(), options);\n            if (statement != null) {\n               RunScriptOnNode runner = initScriptRunnerFactory.create(node.get(), statement, options, badNodes).call();\n               if (runner != null) {\n                  ExecResponse exec = runner.call();\n                  customizationResponses.put(node.get(), exec);\n               }\n            }\n            if (options.getPort() > 0) {\n               openSocketFinder.findOpenSocketOnNode(node.get(), options.getPort(), options.getSeconds(),\n                     TimeUnit.SECONDS);\n            }\n         }\n         logger.debug(\"<< customized node(%s)\", originalId);\n         goodNodes.add(node.get());\n      } catch (Exception e) {\n         logger.error(e, \"<< problem customizing node(%s): \", originalId, getRootCause(e).getMessage());\n         badNodes.put(node.get(), e);\n      }\n      return null;\n   }\n\n   @Override\n   public Void apply(AtomicReference<NodeMetadata> input) {\n      this.node = input;\n      call();\n      return null;\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/strategy/DestroyNodeStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.strategy;\n\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.javax.annotation.Nullable;\n\n/**\n * terminates the node\n */\npublic interface DestroyNodeStrategy {\n\n   /**\n    * \n    * @return null if the node wasn't found\n    */\n   @Nullable\n   NodeMetadata destroyNode(String id);\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/strategy/GetImageStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.strategy;\n\nimport org.jclouds.compute.domain.Image;\n\n/**\n * returns all details associated to the image below.\n */\npublic interface GetImageStrategy {\n\n   Image getImage(String id);\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/strategy/GetNodeMetadataStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.strategy;\n\nimport org.jclouds.compute.domain.NodeMetadata;\n\n/**\n * returns all details associated to the node below.\n */\npublic interface GetNodeMetadataStrategy {\n\n   NodeMetadata getNode(String id);\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/strategy/InitializeRunScriptOnNodeOrPlaceInBadMap.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.strategy;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\nimport java.util.concurrent.Callable;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.compute.callables.RunScriptOnNode;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.options.RunScriptOptions;\nimport org.jclouds.scriptbuilder.domain.Statement;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.inject.assistedinject.Assisted;\n\npublic class InitializeRunScriptOnNodeOrPlaceInBadMap implements Callable<RunScriptOnNode> {\n\n   public interface Factory {\n      Callable<RunScriptOnNode> create(NodeMetadata node, Statement script, RunScriptOptions options,\n               Map<NodeMetadata, Exception> badNodes);\n   }\n\n   private final RunScriptOnNode.Factory runScriptOnNodeFactory;\n   private final Statement script;\n   private final Map<NodeMetadata, Exception> badNodes;\n   private final NodeMetadata node;\n   private final RunScriptOptions options;\n\n   @Inject\n   InitializeRunScriptOnNodeOrPlaceInBadMap(RunScriptOnNode.Factory runScriptOnNodeFactory,\n            @Assisted NodeMetadata node, @Assisted Statement script, @Assisted RunScriptOptions options,\n            @Assisted Map<NodeMetadata, Exception> badNodes) {\n      this.runScriptOnNodeFactory = checkNotNull(runScriptOnNodeFactory, \"runScriptOnNodeFactory\");\n      this.script = checkNotNull(script, \"script\");\n      this.badNodes = checkNotNull(badNodes, \"badNodes\");\n      this.node = checkNotNull(node, \"node\");\n      this.options = checkNotNull(options, \"options\");\n   }\n\n   @Override\n   public RunScriptOnNode call() throws Exception {\n      try {\n         return runScriptOnNodeFactory.create(node, script, options).init();\n      } catch (Exception e) {\n         badNodes.put(node, e);\n         return null;\n      }\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).add(\"node\", node).add(\"options\", options).toString();\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/strategy/ListNodesStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.strategy;\n\nimport org.jclouds.compute.domain.ComputeMetadata;\nimport org.jclouds.compute.domain.NodeMetadata;\n\nimport com.google.common.base.Predicate;\n\npublic interface ListNodesStrategy {\n\n   Iterable<? extends ComputeMetadata> listNodes();\n\n   Iterable<? extends NodeMetadata> listDetailsOnNodesMatching(Predicate<? super NodeMetadata> filter);\n\n   Iterable<? extends NodeMetadata> listNodesByIds(Iterable<String> ids);\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/strategy/PopulateDefaultLoginCredentialsForImageStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.strategy;\n\nimport org.jclouds.compute.strategy.impl.ReturnCredentialsBoundToImage;\nimport org.jclouds.domain.LoginCredentials;\n\nimport com.google.common.base.Function;\nimport com.google.inject.ImplementedBy;\n\n@ImplementedBy(ReturnCredentialsBoundToImage.class)\npublic interface PopulateDefaultLoginCredentialsForImageStrategy extends Function<Object, LoginCredentials> {\n\n   /**\n    * Processes the cloud-specific resources to determine the login credentials.\n    * \n    * @param image\n    *           this is the cloud-specific representation of the image object.\n    * @return credentials parsed from the image if not null\n    */\n   LoginCredentials apply(Object image);\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/strategy/PrioritizeCredentialsFromTemplate.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.strategy;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.domain.LoginCredentials.Builder;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class PrioritizeCredentialsFromTemplate {\n   private final Function<Template, LoginCredentials> credentialsFromImageOrTemplateOptions;\n\n   @Inject\n   public PrioritizeCredentialsFromTemplate(Function<Template, LoginCredentials> credentialsFromImageOrTemplateOptions) {\n      this.credentialsFromImageOrTemplateOptions = checkNotNull(credentialsFromImageOrTemplateOptions,\n            \"credentialsFromImageOrTemplateOptions\");\n   }\n\n   public LoginCredentials apply(Template template, LoginCredentials fromNode) {\n      LoginCredentials creds = fromNode;\n      LoginCredentials credsFromParameters = credentialsFromImageOrTemplateOptions.apply(template);\n      if (credsFromParameters != null) {\n         Builder builder = LoginCredentials.builder(creds);\n         if (credsFromParameters.getUser() != null)\n            builder.user(credsFromParameters.getUser());\n         if (credsFromParameters.getOptionalPassword().isPresent())\n            builder.password(credsFromParameters.getOptionalPassword().get());\n         if (credsFromParameters.getOptionalPrivateKey().isPresent())\n            builder.privateKey(credsFromParameters.getOptionalPrivateKey().get());\n         if (credsFromParameters.shouldAuthenticateSudo())\n            builder.authenticateSudo(true);\n         creds = builder.build();\n      }\n      return creds;\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/strategy/RebootNodeStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.strategy;\n\nimport org.jclouds.compute.domain.NodeMetadata;\n\n/**\n * Reboots a node unless it is in the state NODE_TERMINATED.\n */\npublic interface RebootNodeStrategy {\n\n   NodeMetadata rebootNode(String id);\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/strategy/ResumeNodeStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.strategy;\n\nimport org.jclouds.compute.domain.NodeMetadata;\n\n/**\n * Resumes a node from the state {@link org.jclouds.compute.domain.NodeState#SUSPENDED suspended}\n */\npublic interface ResumeNodeStrategy {\n\n   NodeMetadata resumeNode(String id);\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/strategy/RunScriptOnNodeAndAddToGoodMapOrPutExceptionIntoBadMap.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.strategy;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.common.base.Throwables.getRootCause;\n\nimport java.util.Map;\nimport java.util.concurrent.Callable;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\n\nimport org.jclouds.compute.callables.RunScriptOnNode;\nimport org.jclouds.compute.domain.ExecResponse;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.inject.assistedinject.AssistedInject;\n\npublic class RunScriptOnNodeAndAddToGoodMapOrPutExceptionIntoBadMap implements Callable<ExecResponse> {\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n   private final RunScriptOnNode runScriptOnNode;\n   private final Map<NodeMetadata, Exception> badNodes;\n   private final Map<NodeMetadata, ExecResponse> goodNodes;\n\n   private transient boolean tainted;\n\n   @AssistedInject\n   public RunScriptOnNodeAndAddToGoodMapOrPutExceptionIntoBadMap(RunScriptOnNode runScriptOnNode,\n            Map<NodeMetadata, ExecResponse> goodNodes, Map<NodeMetadata, Exception> badNodes) {\n      this.runScriptOnNode = checkNotNull(runScriptOnNode, \"runScriptOnNode\");\n      this.badNodes = checkNotNull(badNodes, \"badNodes\");\n      this.goodNodes = checkNotNull(goodNodes, \"goodNodes\");\n   }\n\n   @Override\n   public ExecResponse call() {\n      checkState(runScriptOnNode != null, \"runScriptOnNode must be set\");\n      checkState(!tainted, \"this object is not designed to be reused: %s\", toString());\n      tainted = true;\n      try {\n         ExecResponse exec = runScriptOnNode.call();\n         logger.debug(\"<< options applied node(%s)\", runScriptOnNode.getNode().getId());\n         logger.trace(\"<< script output for node(%s): %s\", runScriptOnNode.getNode().getId(), exec);\n         goodNodes.put(runScriptOnNode.getNode(), exec);\n         return exec;\n      } catch (Exception e) {\n         logger.error(e, \"<< problem applying options to node(%s): \", runScriptOnNode.getNode().getId(),\n                  getRootCause(e).getMessage());\n         badNodes.put(runScriptOnNode.getNode(), e);\n      }\n      return null;\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).add(\"runScriptOnNode\", runScriptOnNode).add(\"goodNodes\", goodNodes).add(\n               \"badNodes\", badNodes).toString();\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/strategy/SuspendNodeStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.strategy;\n\nimport org.jclouds.compute.domain.NodeMetadata;\n\n/**\n * Reboots a node unless it is in the state {@link org.jclouds.compute.domain.NodeState#SUSPENDED suspended}\n */\npublic interface SuspendNodeStrategy {\n\n   NodeMetadata suspendNode(String id);\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/strategy/impl/AdaptingComputeServiceStrategies.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.strategy.impl;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.toArray;\nimport static com.google.common.collect.Iterables.transform;\nimport static org.jclouds.compute.predicates.NodePredicates.all;\nimport static org.jclouds.compute.predicates.NodePredicates.withIds;\nimport static org.jclouds.compute.util.ComputeServiceUtils.formatStatus;\n\nimport java.util.Map;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.ComputeServiceAdapter;\nimport org.jclouds.compute.ComputeServiceAdapter.NodeAndInitialCredentials;\nimport org.jclouds.compute.config.ComputeServiceAdapterContextModule.AddDefaultCredentialsToImage;\nimport org.jclouds.compute.domain.ComputeMetadata;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadataBuilder;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.domain.NodeMetadata.Status;\nimport org.jclouds.compute.predicates.NodePredicates;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.compute.strategy.CreateNodeWithGroupEncodedIntoName;\nimport org.jclouds.compute.strategy.DestroyNodeStrategy;\nimport org.jclouds.compute.strategy.GetImageStrategy;\nimport org.jclouds.compute.strategy.GetNodeMetadataStrategy;\nimport org.jclouds.compute.strategy.ListNodesStrategy;\nimport org.jclouds.compute.strategy.PrioritizeCredentialsFromTemplate;\nimport org.jclouds.compute.strategy.RebootNodeStrategy;\nimport org.jclouds.compute.strategy.ResumeNodeStrategy;\nimport org.jclouds.compute.strategy.SuspendNodeStrategy;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Functions;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.FluentIterable;\n\n@Singleton\npublic class AdaptingComputeServiceStrategies<N, H, I, L> implements CreateNodeWithGroupEncodedIntoName,\n         DestroyNodeStrategy, GetNodeMetadataStrategy, GetImageStrategy, ListNodesStrategy, RebootNodeStrategy,\n         ResumeNodeStrategy, SuspendNodeStrategy {\n   \n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   private final Map<String, Credentials> credentialStore;\n   private final PrioritizeCredentialsFromTemplate prioritizeCredentialsFromTemplate;\n   private final ComputeServiceAdapter<N, H, I, L> client;\n   private final Function<N, NodeMetadata> nodeMetadataAdapter;\n   private final Function<I, Image> imageAdapter;\n   private final AddDefaultCredentialsToImage addDefaultCredentialsToImage;\n\n   @Inject\n   public AdaptingComputeServiceStrategies(Map<String, Credentials> credentialStore,\n            PrioritizeCredentialsFromTemplate prioritizeCredentialsFromTemplate,\n            ComputeServiceAdapter<N, H, I, L> client, Function<N, NodeMetadata> nodeMetadataAdapter,\n            Function<I, Image> imageAdapter, AddDefaultCredentialsToImage addDefaultCredentialsToImage) {\n      this.credentialStore = checkNotNull(credentialStore, \"credentialStore\");\n      this.prioritizeCredentialsFromTemplate = checkNotNull(prioritizeCredentialsFromTemplate,\n               \"prioritizeCredentialsFromTemplate\");\n      this.client = checkNotNull(client, \"client\");\n      this.nodeMetadataAdapter = Functions.compose(addLoginCredentials, checkNotNull(nodeMetadataAdapter,\n               \"nodeMetadataAdapter\"));\n      this.imageAdapter = checkNotNull(imageAdapter, \"imageAdapter\");\n      this.addDefaultCredentialsToImage = checkNotNull(addDefaultCredentialsToImage, \"addDefaultCredentialsToImage\");\n   }\n\n   private final Function<NodeMetadata, NodeMetadata> addLoginCredentials = new Function<NodeMetadata, NodeMetadata>() {\n\n      @Override\n      public NodeMetadata apply(NodeMetadata arg0) {\n         return credentialStore.containsKey(\"node#\" + arg0.getId()) ? NodeMetadataBuilder.fromNodeMetadata(arg0)\n                  .credentials(LoginCredentials.fromCredentials(credentialStore.get(\"node#\" + arg0.getId()))).build()\n                  : arg0;\n      }\n\n      @Override\n      public String toString() {\n         return \"addLoginCredentialsFromCredentialStore()\";\n      }\n   };\n\n   @Override\n   public Iterable<? extends ComputeMetadata> listNodes() {\n      return listDetailsOnNodesMatching(NodePredicates.all());\n   }\n\n   @Override\n   public Iterable<? extends NodeMetadata> listNodesByIds(Iterable<String> ids) {\n      return FluentIterable.from(listDetailsOnNodesMatching(all())).filter(withIds(toArray(ids, String.class))).toSet();\n   }\n\n   @Override\n   public Iterable<? extends NodeMetadata> listDetailsOnNodesMatching(Predicate<? super NodeMetadata> filter) {\n      return filter(transform(client.listNodes(), nodeMetadataAdapter), filter);\n   }\n   \n   @Override\n   public Image getImage(String id) {\n      I image = client.getImage(checkNotNull(id, \"id\"));\n      if (image == null)\n         return null;\n      // The image supplier configured in the ComputeServiceAdapterContextModule also adds the default credentials to\n      // each image in the image list. When getting a single image, the behavior must be the same.\n      return addDefaultCredentialsToImage.apply(imageAdapter.apply(image));\n   }\n   \n   @Override\n   public NodeMetadata getNode(String id) {\n      N node = client.getNode(checkNotNull(id, \"id\"));\n      if (node == null)\n         return null;\n      return nodeMetadataAdapter.apply(node);\n   }\n\n   // TODO: make reboot/resume/suspend return the node they affected\n   @Override\n   public NodeMetadata rebootNode(String id) {\n      NodeMetadata node = getNode(checkNotNull(id, \"id\"));\n      checkStateAvailable(id, node);\n      client.rebootNode(id);\n      // invalidate state of node\n      return getNode(checkNotNull(id, \"id\"));\n   }\n\n   private void checkStateAvailable(String id, NodeMetadata node) {\n      checkState(node != null, \"node with id %s terminated or unavailable!\", id);\n      checkState(node.getStatus() != Status.TERMINATED,\n               \"node %s terminated or unavailable! current status: %s\", node, formatStatus(node));\n   }\n\n   @Override\n   public NodeMetadata resumeNode(String id) {\n      NodeMetadata node = getNode(checkNotNull(id, \"id\"));\n      checkStateAvailable(id, node);\n      client.resumeNode(id);\n      // invalidate state of node\n      return getNode(checkNotNull(id, \"id\"));\n   }\n\n   @Override\n   public NodeMetadata suspendNode(String id) {\n      NodeMetadata node = getNode(checkNotNull(id, \"id\"));\n      checkStateAvailable(id, node);\n      client.suspendNode(id);\n      // invalidate state of node\n      return getNode(checkNotNull(id, \"id\"));\n   }\n\n   @Override\n   public NodeMetadata destroyNode(String id) {\n      NodeMetadata node = getNode(checkNotNull(id, \"id\"));\n      if (node == null)\n         return node;\n      client.destroyNode(id);\n      return node;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public NodeMetadata createNodeWithGroupEncodedIntoName(String group, String name, Template template) {\n      checkNotNull(group, \"group (that which groups identical nodes together) must be specified\");\n      checkNotNull(name, \"name should have %s encoded into it\", group);\n      checkNotNull(template, \"template was null\");\n      checkNotNull(template.getOptions(), \"template options was null\");\n\n      NodeAndInitialCredentials<N> from = client.createNodeWithGroupEncodedIntoName(group, name, template);\n      LoginCredentials fromNode = from.getCredentials();\n      LoginCredentials creds = prioritizeCredentialsFromTemplate.apply(template, fromNode);\n      String credsKey = \"node#\" + from.getNodeId();\n      if (creds != null) {\n         credentialStore.put(credsKey, creds);\n      } else {\n         logger.trace(\"node(%s) creation did not return login credentials\", from.getNodeId());\n      }\n      NodeMetadata node = nodeMetadataAdapter.apply(from.getNode());\n      //TODO: test case that proves this\n      checkState(node.getId().equals(from.getNodeId()),\n               \"nodeAndInitialCredentials.getNodeId() returned %s, while parsed nodemetadata.getId() returned %s\", from\n                        .getNodeId(), node.getId());\n      if (creds != null) {\n         Credentials credsFromCache = credentialStore.get(credsKey);\n         //TODO: test case that proves this\n         checkState(node.getCredentials().equals(credsFromCache),\n                  \"credentialStore.get(%s): %s does not match node(%s).getCredentials(): %s\", credsKey, credsFromCache,\n                  node.getId(), node.getCredentials());\n      }\n      return node;\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/strategy/impl/CreateNodesWithGroupEncodedIntoNameThenAddToSet.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.strategy.impl;\n\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.any;\nimport static com.google.common.collect.Maps.newLinkedHashMap;\nimport static com.google.common.collect.Sets.newLinkedHashSet;\nimport static org.jclouds.compute.util.ComputeServiceUtils.formatStatus;\n\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport com.google.common.base.MoreObjects;\nimport org.jclouds.Constants;\nimport org.jclouds.compute.config.CustomizationResponse;\nimport org.jclouds.compute.domain.ComputeMetadata;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.compute.strategy.CreateNodeWithGroupEncodedIntoName;\nimport org.jclouds.compute.strategy.CreateNodesInGroupThenAddToSet;\nimport org.jclouds.compute.strategy.CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap;\nimport org.jclouds.compute.strategy.ListNodesStrategy;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Multimap;\nimport com.google.common.util.concurrent.Futures;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.ListeningExecutorService;\n\n/**\n * creates futures that correlate to\n */\n@Singleton\npublic class CreateNodesWithGroupEncodedIntoNameThenAddToSet implements CreateNodesInGroupThenAddToSet {\n\n   protected class AddNode implements Callable<AtomicReference<NodeMetadata>> {\n      private final String name;\n      private final String group;\n      private final Template template;\n\n      public AddNode(String name, String group, Template template) {\n         this.name = checkNotNull(name, \"name\");\n         this.group = checkNotNull(group, \"group\");\n         this.template = checkNotNull(template, \"template\");\n      }\n\n      @Override\n      public AtomicReference<NodeMetadata> call() throws Exception {\n         NodeMetadata node = null;\n         logger.debug(\">> adding node location(%s) name(%s) image(%s) hardware(%s)\", template.getLocation().getId(),\n               name, MoreObjects.firstNonNull(template.getImage().getProviderId(), template.getImage().getId()),\n               MoreObjects.firstNonNull(template.getHardware().getProviderId(), template.getHardware().getId()));\n         node = addNodeWithGroupStrategy.createNodeWithGroupEncodedIntoName(group, name, template);\n         logger.debug(\"<< %s node(%s)\", formatStatus(node), node.getId());\n         return new AtomicReference<NodeMetadata>(node);\n      }\n\n      public String toString() {\n         return toStringHelper(this).add(\"name\", name).add(\"group\", group).add(\"template\", template).toString();\n      }\n\n   }\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n   protected final CreateNodeWithGroupEncodedIntoName addNodeWithGroupStrategy;\n   protected final ListNodesStrategy listNodesStrategy;\n   protected final GroupNamingConvention.Factory namingConvention;\n   protected final ListeningExecutorService userExecutor;\n   protected final CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap.Factory customizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapFactory;\n\n   @Inject\n   protected CreateNodesWithGroupEncodedIntoNameThenAddToSet(\n            CreateNodeWithGroupEncodedIntoName addNodeWithGroupStrategy,\n            ListNodesStrategy listNodesStrategy,\n            GroupNamingConvention.Factory namingConvention,\n            @Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor,\n            CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap.Factory customizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapFactory) {\n      this.addNodeWithGroupStrategy = addNodeWithGroupStrategy;\n      this.listNodesStrategy = listNodesStrategy;\n      this.namingConvention = namingConvention;\n      this.userExecutor = userExecutor;\n      this.customizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapFactory = customizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapFactory;\n   }\n\n   /**\n    * This implementation gets a list of acceptable node names to encode the group into, then it\n    * simultaneously runs the nodes and applies options to them.\n    */\n   @Override\n   public Map<?, ListenableFuture<Void>> execute(String group, int count, Template template, Set<NodeMetadata> goodNodes,\n            Map<NodeMetadata, Exception> badNodes, Multimap<NodeMetadata, CustomizationResponse> customizationResponses) {\n      Map<String, ListenableFuture<Void>> responses = newLinkedHashMap();\n      for (String name : getNextNames(group, template, count)) {\n         responses.put(name, Futures.transform(createNodeInGroupWithNameAndTemplate(group, name, template),\n                  customizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapFactory.create(template.getOptions(), goodNodes,\n                           badNodes, customizationResponses), userExecutor));\n      }\n      return responses;\n   }\n\n   /**\n    * This calls logic necessary to create a node and convert it from its provider-specific object\n    * to the jclouds {@link NodeMetadata} object. This call directly precedes customization, such as\n    * executing scripts.\n    * \n    * </p> The outcome of this operation does not imply the node is {@link Status#RUNNING\n    * running}. If you want to insert logic after the node is created, yet before an attempt to\n    * customize the node, then append your behaviour to this method.\n    * \n    * ex. to attach an ip address post-creation\n    * \n    * <pre>\n    * &#064;Override\n    * protected ListenableFuture&lt;AtomicReference&lt;NodeMetadata&gt;&gt; createNodeInGroupWithNameAndTemplate(String group, String name,\n    *          Template template) {\n    * \n    *    ListenableFuture&lt;AtomicReference&lt;NodeMetadata&gt;&gt; future = super.addNodeIntoGroupWithNameAndTemplate(group, name, template);\n    *    return Futures.compose(future, new Function&lt;AtomicReference&lt;NodeMetadata&gt;, AtomicReference&lt;NodeMetadata&gt;&gt;() {\n    * \n    *       &#064;Override\n    *       public AtomicReference&lt;NodeMetadata&gt; apply(AtomicReference&lt;NodeMetadata&gt; input) {\n    *          NodeMetadata node = input.get();\n    *          // allocate and attach an ip\n    *          input.set(NodeMetadataBuilder.fromNodeMetadata(node).publicAddresses(ImmutableSet.of(ip.getIp())).build());\n    *          return input;\n    *       }\n    * \n    *    }, executor);\n    * }\n    * </pre>\n    * \n    * @param group group the node belongs to\n    * @param name generated name of the node\n    * @param template user-specified template\n    * @return node that is created, yet not necessarily in {@link Status#RUNNING}\n    */\n   protected ListenableFuture<AtomicReference<NodeMetadata>> createNodeInGroupWithNameAndTemplate(String group, String name,\n            Template template) {\n      return userExecutor.submit(new AddNode(name, group, template));\n   }\n\n   /**\n    * Find the next node names that can be used. If the nodeNames template option is not specified\n    * or is empty, these will be derived from the group and the template. We will pre-allocate a\n    * specified quantity, and attempt to verify that there is no name conflict with the current\n    * service. If the nodeNames option is specified, names from that will be used instead, without\n    * any check for name conflicts.\n    * If there are insufficient names in nodeNames, subsequent names will be generated in the\n    * default format.\n    * \n    * @param group\n    * @param count\n    * @param template\n    * @return\n    */\n   protected Set<String> getNextNames(final String group, final Template template, int count) {\n      Set<String> names = newLinkedHashSet();\n      Set<String> nodeNames = template.getOptions().getNodeNames();\n      if (nodeNames.size() >= count) {\n         return ImmutableSet.copyOf(Iterables.limit(nodeNames, count));\n      } else {\n         names.addAll(nodeNames);\n      }\n      Iterable<? extends ComputeMetadata> currentNodes = listNodesStrategy.listNodes();\n      int maxTries = 100;\n      int currentTries = 0;\n      while (names.size() < count && currentTries++ < maxTries) {\n         final String name = namingConvention.createWithoutPrefix().uniqueNameForGroup(group);\n         if (!any(currentNodes, new Predicate<ComputeMetadata>() {\n\n            @Override\n            public boolean apply(ComputeMetadata input) {\n               return name.equals(input.getName());\n            }\n\n         })) {\n            names.add(name);\n         }\n      }\n      return names;\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/strategy/impl/ReturnCredentialsBoundToImage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.strategy.impl;\n\nimport static com.google.common.base.Preconditions.checkState;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.strategy.PopulateDefaultLoginCredentialsForImageStrategy;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\n\n@Singleton\npublic class ReturnCredentialsBoundToImage implements PopulateDefaultLoginCredentialsForImageStrategy {\n\n   protected final LoginCredentials creds;\n   protected final Map<String, Credentials> credentialStore;\n   protected final Map<OsFamily, LoginCredentials> osFamilyToCredentials;\n\n   @Inject\n   public ReturnCredentialsBoundToImage(@Nullable @Named(\"image\") LoginCredentials creds,\n            Map<String, Credentials> credentialStore, Map<OsFamily, LoginCredentials> osFamilyToCredentials) {\n      this.creds = creds;\n      this.credentialStore = credentialStore;\n      this.osFamilyToCredentials = osFamilyToCredentials;\n   }\n\n   @Override\n   public LoginCredentials apply(Object resourceToAuthenticate) {\n      checkState(resourceToAuthenticate instanceof Image, \"this is only valid for images, not %s\",\n               resourceToAuthenticate.getClass().getSimpleName());\n      if (creds != null)\n         return creds;\n      Image image = Image.class.cast(resourceToAuthenticate);\n      if (credentialStore.containsKey(\"image#\" + image.getId()))\n         return LoginCredentials.fromCredentials(credentialStore.get(\"image#\" + image.getId()));\n      if (image.getOperatingSystem() != null && image.getOperatingSystem().getFamily() != null\n               && osFamilyToCredentials.containsKey(image.getOperatingSystem().getFamily())) {\n         return osFamilyToCredentials.get(image.getOperatingSystem().getFamily());\n      } else {\n         return LoginCredentials.builder().user(\"root\").build();\n      }\n   }\n   \n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).toString();\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/stub/StubApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.stub;\n\nimport java.net.URI;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.apis.internal.BaseApiMetadata;\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.compute.stub.config.StubComputeServiceContextModule;\n\nimport com.google.auto.service.AutoService;\n\n/**\n * Implementation of {@link ApiMetadata} for jclouds in-memory (Stub) API\n */\n@AutoService(ApiMetadata.class)\npublic class StubApiMetadata extends BaseApiMetadata {\n\n   @Override\n   public Builder toBuilder() {\n      return new Builder().fromApiMetadata(this);\n   }\n\n   public StubApiMetadata() {\n      super(new Builder());\n   }\n\n   protected StubApiMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static class Builder extends BaseApiMetadata.Builder<Builder> {\n\n      protected Builder() {\n         id(\"stub\")\n         .name(\"in-memory (Stub) API\")\n         .identityName(\"Unused\")\n         .defaultIdentity(\"stub\")\n         .defaultCredential(\"stub\")\n         .defaultEndpoint(\"stub\")\n         .documentation(URI.create(\"http://www.jclouds.org/documentation/userguide/compute\"))\n         .view(ComputeServiceContext.class)\n         .defaultModule(StubComputeServiceContextModule.class);\n      }\n\n      @Override\n      public StubApiMetadata build() {\n         return new StubApiMetadata(this);\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/stub/config/StubComputeServiceAdapter.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.stub.config;\n\nimport static com.google.common.base.Predicates.in;\nimport static com.google.common.collect.Iterables.find;\nimport static com.google.common.collect.Maps.filterKeys;\nimport static org.jclouds.compute.util.ComputeServiceUtils.formatStatus;\n\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentMap;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Provider;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Constants;\nimport org.jclouds.compute.JCloudsNativeComputeServiceAdapter;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.ImageBuilder;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadata.Status;\nimport org.jclouds.compute.domain.NodeMetadataBuilder;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.SecurityGroup;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.extensions.SecurityGroupExtension;\nimport org.jclouds.compute.predicates.ImagePredicates;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.location.suppliers.all.JustProvider;\nimport org.jclouds.rest.ResourceNotFoundException;\n\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Throwables;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableList.Builder;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Multimap;\nimport com.google.common.util.concurrent.ListeningExecutorService;\n\n@Singleton\npublic class StubComputeServiceAdapter implements JCloudsNativeComputeServiceAdapter {\n   private final Supplier<Location> location;\n   private final ConcurrentMap<String, NodeMetadata> nodes;\n   private final Multimap<String, SecurityGroup> groupsForNodes;\n   private final ListeningExecutorService executor;\n   private final Provider<Integer> idProvider;\n   private final String publicIpPrefix;\n   private final String privateIpPrefix;\n   private final String passwordPrefix;\n   private final Supplier<Set<? extends Location>> locationSupplier;\n   private final Map<OsFamily, Map<String, String>> osToVersionMap;\n   private final Optional<SecurityGroupExtension> securityGroupExtension;\n\n   @Inject\n   public StubComputeServiceAdapter(ConcurrentMap<String, NodeMetadata> nodes,\n            @Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService executor, Supplier<Location> location,\n            @Named(\"NODE_ID\") Provider<Integer> idProvider, @Named(\"PUBLIC_IP_PREFIX\") String publicIpPrefix,\n            @Named(\"PRIVATE_IP_PREFIX\") String privateIpPrefix, @Named(\"PASSWORD_PREFIX\") String passwordPrefix,\n            JustProvider locationSupplier, Map<OsFamily, Map<String, String>> osToVersionMap,\n            Multimap<String, SecurityGroup> groupsForNodes, Optional<SecurityGroupExtension> securityGroupExtension) {\n      this.nodes = nodes;\n      this.executor = executor;\n      this.location = location;\n      this.idProvider = idProvider;\n      this.publicIpPrefix = publicIpPrefix;\n      this.privateIpPrefix = privateIpPrefix;\n      this.passwordPrefix = passwordPrefix;\n      this.locationSupplier = locationSupplier;\n      this.osToVersionMap = osToVersionMap;\n      this.groupsForNodes = groupsForNodes;\n      this.securityGroupExtension = securityGroupExtension;\n   }\n\n   protected void setStateOnNode(Status status, NodeMetadata node) {\n      nodes.put(node.getId(), NodeMetadataBuilder.fromNodeMetadata(node).status(status).build());\n   }\n\n   protected void setStateOnNodeAfterDelay(final Status status, final NodeMetadata node, final long millis) {\n      if (millis == 0L)\n         setStateOnNode(status, node);\n      else\n         executor.execute(new Runnable() {\n\n            @Override\n            public void run() {\n               try {\n                  Thread.sleep(millis);\n               } catch (InterruptedException e) {\n                  Throwables.propagate(e);\n               }\n               setStateOnNode(status, node);\n            }\n\n         });\n   }\n   @Override\n   public NodeWithInitialCredentials createNodeWithGroupEncodedIntoName(String group, String name, Template template) {\n      NodeMetadataBuilder builder = new NodeMetadataBuilder();\n      String id = idProvider.get() + \"\";\n      builder.ids(id);\n      builder.name(name);\n      // using a predictable name so tests will pass\n      builder.hostname(group);\n      builder.tags(template.getOptions().getTags());\n      builder.userMetadata(template.getOptions().getUserMetadata());\n      builder.group(group);\n      builder.location(location.get());\n      builder.imageId(template.getImage().getId());\n      builder.operatingSystem(template.getImage().getOperatingSystem());\n      builder.status(Status.PENDING);\n      builder.publicAddresses(ImmutableSet.<String> of(publicIpPrefix + id));\n      builder.privateAddresses(ImmutableSet.<String> of(privateIpPrefix + id));\n      builder.credentials(LoginCredentials.builder().user(\"root\").password(passwordPrefix + id).build());\n      NodeMetadata node = builder.build();\n      nodes.put(node.getId(), node);\n\n      if (!template.getOptions().getGroups().isEmpty()) {\n         final String groupId = Iterables.getFirst(template.getOptions().getGroups(), \"0\");\n         Optional<SecurityGroup> secGroup = Iterables.tryFind(securityGroupExtension.get().listSecurityGroups(),\n                                                              new Predicate<SecurityGroup>() {\n                                                                 @Override\n                                                                 public boolean apply(SecurityGroup input) {\n                                                                    return input.getId().equals(groupId);\n                                                                 }\n                                                              });\n\n         if (secGroup.isPresent()) {\n            groupsForNodes.put(node.getId(), secGroup.get());\n         }\n      }\n\n      setStateOnNodeAfterDelay(Status.RUNNING, node, 100);\n      return new NodeWithInitialCredentials(node);\n   }\n\n   @Override\n   public Iterable<Hardware> listHardwareProfiles() {\n      return ImmutableSet.<Hardware> of(StubComputeServiceDependenciesModule.stub(\"small\", 1, 1740, 160),\n            StubComputeServiceDependenciesModule.stub(\"medium\", 4, 7680, 850),\n            StubComputeServiceDependenciesModule.stub(\"large\", 8, 15360, 1690));\n   }\n\n   @Override\n   public Iterable<Image> listImages() {\n      // initializing as a List, as ImmutableSet does not allow you to put\n      // duplicates\n      Builder<Image> images = ImmutableList.builder();\n      int id = 1;\n      for (boolean is64Bit : new boolean[] { true, false })\n         for (Entry<OsFamily, Map<String, String>> osVersions : this.osToVersionMap.entrySet()) {\n            for (String version : ImmutableSet.copyOf(osVersions.getValue().values())) {\n               String desc = String.format(\"stub %s %s\", osVersions.getKey(), is64Bit);\n               images.add(new ImageBuilder().ids(id++ + \"\").name(osVersions.getKey().name()).location(location.get())\n                     .operatingSystem(new OperatingSystem(osVersions.getKey(), desc, version, null, desc, is64Bit))\n                     .description(desc).status(Image.Status.AVAILABLE).build());\n            }\n         }\n      return images.build();\n   }\n\n   @Override\n   public Image getImage(String id) {\n      return find(listImages(), ImagePredicates.idEquals(id), null);\n   }\n\n   @Override\n   public Iterable<NodeMetadata> listNodes() {\n      return nodes.values();\n   }\n\n   @Override\n   public Iterable<NodeMetadata> listNodesByIds(Iterable<String> ids) {\n      return filterKeys(nodes, in(ImmutableSet.copyOf(ids))).values();\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public Iterable<Location> listLocations() {\n      return (Iterable<Location>) locationSupplier.get();\n   }\n\n   @Override\n   public NodeMetadata getNode(String id) {\n      return nodes.get(id);\n   }\n\n   @Override\n   public void destroyNode(final String id) {\n      NodeMetadata node = nodes.get(id);\n      if (node == null)\n         return;\n      setStateOnNodeAfterDelay(Status.PENDING, node, 0);\n      setStateOnNodeAfterDelay(Status.TERMINATED, node, 50);\n      groupsForNodes.removeAll(id);\n\n      executor.execute(new Runnable() {\n\n         @Override\n         public void run() {\n            try {\n               Thread.sleep(200);\n            } catch (InterruptedException e) {\n               Throwables.propagate(e);\n            } finally {\n               nodes.remove(id);\n            }\n         }\n\n      });\n   }\n\n   @Override\n   public void rebootNode(String id) {\n      NodeMetadata node = nodes.get(id);\n      if (node == null)\n         throw new ResourceNotFoundException(\"node not found: \" + id);\n      setStateOnNode(Status.PENDING, node);\n      setStateOnNodeAfterDelay(Status.RUNNING, node, 50);\n   }\n\n   @Override\n   public void resumeNode(String id) {\n      NodeMetadata node = nodes.get(id);\n      if (node == null)\n         throw new ResourceNotFoundException(\"node not found: \" + id);\n      if (node.getStatus() == Status.RUNNING)\n         return;\n      if (node.getStatus() != Status.SUSPENDED)\n         throw new IllegalStateException(\"to resume a node, it must be in suspended status, not: \" + formatStatus(node));\n      setStateOnNode(Status.PENDING, node);\n      setStateOnNodeAfterDelay(Status.RUNNING, node, 50);\n   }\n\n   @Override\n   public void suspendNode(String id) {\n      NodeMetadata node = nodes.get(id);\n      if (node == null)\n         throw new ResourceNotFoundException(\"node not found: \" + id);\n      if (node.getStatus() == Status.SUSPENDED)\n         return;\n      if (node.getStatus() != Status.RUNNING)\n         throw new IllegalStateException(\"to suspend a node, it must be in running status, not: \" + formatStatus(node));\n      setStateOnNode(Status.PENDING, node);\n      setStateOnNodeAfterDelay(Status.SUSPENDED, node, 50);\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/stub/config/StubComputeServiceContextModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.stub.config;\n\nimport org.jclouds.compute.config.JCloudsNativeComputeServiceAdapterContextModule;\nimport org.jclouds.concurrent.SingleThreaded;\n\n@SingleThreaded\npublic class StubComputeServiceContextModule extends JCloudsNativeComputeServiceAdapterContextModule {\n\n   public StubComputeServiceContextModule() {\n      super(StubComputeServiceAdapter.class);\n   }\n\n   @Override\n   protected void configure() {\n      install(new StubComputeServiceDependenciesModule());\n      super.configure();\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/stub/config/StubComputeServiceDependenciesModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.stub.config;\n\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentMap;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.atomic.AtomicInteger;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadata.Status;\nimport org.jclouds.compute.domain.Processor;\nimport org.jclouds.compute.domain.SecurityGroup;\nimport org.jclouds.compute.domain.Volume;\nimport org.jclouds.compute.domain.internal.VolumeImpl;\nimport org.jclouds.compute.extensions.SecurityGroupExtension;\nimport org.jclouds.compute.stub.extensions.StubSecurityGroupExtension;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.location.Provider;\nimport org.jclouds.predicates.SocketOpen;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.LinkedHashMultimap;\nimport com.google.common.collect.Multimap;\nimport com.google.common.net.HostAndPort;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Provides;\nimport com.google.inject.TypeLiteral;\n\npublic class StubComputeServiceDependenciesModule extends AbstractModule {\n\n   @Override\n   protected void configure() {\n      bind(new TypeLiteral<SecurityGroupExtension>() {\n      }).to(StubSecurityGroupExtension.class);\n\n   }\n\n   // STUB STUFF STATIC SO MULTIPLE CONTEXTS CAN SEE IT\n   protected static final LoadingCache<String, ConcurrentMap<String, NodeMetadata>> backing = CacheBuilder.newBuilder()\n            .build(new CacheLoader<String, ConcurrentMap<String, NodeMetadata>>() {\n\n               @Override\n               public ConcurrentMap<String, NodeMetadata> load(String arg0) throws Exception {\n                  return new ConcurrentHashMap<String, NodeMetadata>();\n               }\n\n            });\n\n   @Provides\n   @Singleton\n   protected final ConcurrentMap<String, NodeMetadata> provideNodesForIdentity(@Provider Supplier<Credentials> creds)\n            throws ExecutionException {\n      return backing.get(creds.get().identity);\n   }\n\n   protected static final LoadingCache<String, ConcurrentMap<String, SecurityGroup>> groupBacking = CacheBuilder.newBuilder()\n            .build(new CacheLoader<String, ConcurrentMap<String, SecurityGroup>>() {\n\n               @Override\n               public ConcurrentMap<String, SecurityGroup> load(String arg0) throws Exception {\n                  return new ConcurrentHashMap<String, SecurityGroup>();\n               }\n\n            });\n\n   @Provides\n   @Singleton\n   protected final ConcurrentMap<String, SecurityGroup> provideGroups(@Provider Supplier<Credentials> creds)\n            throws ExecutionException {\n      return groupBacking.get(creds.get().identity);\n   }\n\n   protected static final LoadingCache<String, Multimap<String, SecurityGroup>> groupsForNodeBacking = CacheBuilder.newBuilder()\n            .build(new CacheLoader<String, Multimap<String, SecurityGroup>>() {\n\n               @Override\n               public Multimap<String, SecurityGroup> load(String arg0) throws Exception {\n                  return LinkedHashMultimap.create();\n               }\n\n            });\n\n   @Provides\n   @Singleton\n   protected final Multimap<String, SecurityGroup> provideGroupsForNode(@Provider Supplier<Credentials> creds)\n            throws ExecutionException {\n      return groupsForNodeBacking.get(creds.get().identity);\n   }\n\n   protected static final LoadingCache<String, AtomicInteger> nodeIds = CacheBuilder.newBuilder().build(\n            new CacheLoader<String, AtomicInteger>() {\n\n               @Override\n               public AtomicInteger load(String arg0) throws Exception {\n                  return new AtomicInteger(0);\n               }\n\n            });\n\n   @Provides\n   @Named(\"NODE_ID\")\n   protected final Integer provideNodeIdForIdentity(@Provider Supplier<Credentials> creds) throws ExecutionException {\n      return nodeIds.get(creds.get().identity).incrementAndGet();\n   }\n\n   protected static final LoadingCache<String, AtomicInteger> groupIds = CacheBuilder.newBuilder().build(\n            new CacheLoader<String, AtomicInteger>() {\n\n               @Override\n               public AtomicInteger load(String arg0) throws Exception {\n                  return new AtomicInteger(0);\n               }\n\n            });\n\n   @Provides\n   @Named(\"GROUP_ID\")\n   protected final Integer provideGroupIdForIdentity(@Provider Supplier<Credentials> creds) throws ExecutionException {\n      return groupIds.get(creds.get().identity).incrementAndGet();\n   }\n\n   @Singleton\n   @Provides\n   @Named(\"PUBLIC_IP_PREFIX\")\n   final String publicIpPrefix() {\n      return \"144.175.1.\";\n   }\n\n   @Singleton\n   @Provides\n   @Named(\"PRIVATE_IP_PREFIX\")\n   final String privateIpPrefix() {\n      return \"10.1.1.\";\n   }\n\n   @Singleton\n   @Provides\n   @Named(\"PASSWORD_PREFIX\")\n   final String passwordPrefix() {\n      return \"password\";\n   }\n\n   @Singleton\n   @Provides\n   final SocketOpen socketOpen(StubSocketOpen in) {\n      return in;\n   }\n\n   @Singleton\n   public static class StubSocketOpen implements SocketOpen {\n      private final ConcurrentMap<String, NodeMetadata> nodes;\n      private final String publicIpPrefix;\n\n      @Inject\n      public StubSocketOpen(ConcurrentMap<String, NodeMetadata> nodes, @Named(\"PUBLIC_IP_PREFIX\") String publicIpPrefix) {\n         this.nodes = nodes;\n         this.publicIpPrefix = publicIpPrefix;\n      }\n\n      @Override\n      public boolean apply(HostAndPort input) {\n         if (input.getHost().indexOf(publicIpPrefix) == -1)\n            return false;\n         String id = input.getHost().replace(publicIpPrefix, \"\");\n         NodeMetadata node = nodes.get(id);\n         return node != null && node.getStatus() == Status.RUNNING;\n      }\n\n   }\n\n   static Hardware stub(String type, int cores, int ram, float disk) {\n      return new org.jclouds.compute.domain.HardwareBuilder().ids(type).name(type)\n            .processors(ImmutableList.of(new Processor(cores, 1.0))).ram(ram)\n            .volumes(ImmutableList.<Volume> of(new VolumeImpl(disk, true, false))).build();\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/stub/extensions/StubSecurityGroupExtension.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.stub.extensions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Predicates.equalTo;\nimport static com.google.common.base.Predicates.not;\nimport static com.google.common.collect.Iterables.filter;\n\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentMap;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Provider;\n\nimport org.jclouds.compute.domain.SecurityGroup;\nimport org.jclouds.compute.domain.SecurityGroupBuilder;\nimport org.jclouds.compute.extensions.SecurityGroupExtension;\nimport org.jclouds.domain.Location;\nimport org.jclouds.net.domain.IpPermission;\nimport org.jclouds.net.domain.IpProtocol;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Multimap;\n\n/**\n * An extension to compute service to allow for the manipulation of {@link SecurityGroup}s. Implementation\n * is optional by providers.\n */\npublic class StubSecurityGroupExtension implements SecurityGroupExtension {\n\n   private final Supplier<Location> location;\n   private final Provider<Integer> groupIdProvider;\n   private final ConcurrentMap<String, SecurityGroup> groups;\n   private final Multimap<String, SecurityGroup> groupsForNodes;\n\n   @Inject\n   public StubSecurityGroupExtension(ConcurrentMap<String, SecurityGroup> groups,\n                                     Supplier<Location> location,\n                                     @Named(\"GROUP_ID\") Provider<Integer> groupIdProvider,\n                                     Multimap<String, SecurityGroup> groupsForNodes) {\n      this.groups = groups;\n      this.location = location;\n      this.groupIdProvider = groupIdProvider;\n      this.groupsForNodes = groupsForNodes;\n   }\n\n   @Override\n   public Set<SecurityGroup> listSecurityGroups() {\n      return ImmutableSet.copyOf(groups.values());\n   }\n\n   @Override\n   public Set<SecurityGroup> listSecurityGroupsInLocation(final Location location) {\n      return ImmutableSet.copyOf(filter(groups.values(), new Predicate<SecurityGroup>() {\n               @Override\n               public boolean apply(SecurityGroup group) {\n                  return group.getLocation().equals(location);\n               }\n            }));\n   }\n\n   @Override\n   public Set<SecurityGroup> listSecurityGroupsForNode(String nodeId) {\n      return ImmutableSet.copyOf(groupsForNodes.get(nodeId));\n   }\n\n   @Override\n   public SecurityGroup getSecurityGroupById(String id) {\n      return groups.get(id);\n   }\n\n   @Override\n   public SecurityGroup createSecurityGroup(String name, Location location) {\n      SecurityGroupBuilder builder = new SecurityGroupBuilder();\n\n      String id = groupIdProvider.get() + \"\";\n      builder.ids(id);\n      builder.name(name);\n      builder.location(location);\n\n      SecurityGroup group = builder.build();\n\n      groups.put(group.getId(), group);\n\n      return group;\n   }\n\n   @Override\n   public boolean removeSecurityGroup(String id) {\n      if (groups.containsKey(id)) {\n         groups.remove(id);\n         return true;\n      }\n      return false;\n   }\n\n   @Override\n   public SecurityGroup addIpPermission(IpPermission ipPermission, SecurityGroup group) {\n      SecurityGroupBuilder builder = SecurityGroupBuilder.fromSecurityGroup(checkNotNull(group, \"group\"));\n\n      builder.ipPermission(checkNotNull(ipPermission, \"ipPermission\"));\n\n      SecurityGroup newGroup = builder.build();\n\n      if (groups.containsKey(newGroup.getId())) {\n         groups.remove(newGroup.getId());\n      }\n\n      groups.put(newGroup.getId(), newGroup);\n\n      return newGroup;\n   }\n\n   @Override\n   public SecurityGroup addIpPermission(IpProtocol protocol, int startPort, int endPort,\n                                 Multimap<String, String> tenantIdGroupNamePairs,\n                                 Iterable<String> ipRanges,\n                                 Iterable<String> groupIds, SecurityGroup group) {\n      IpPermission.Builder ipBuilder = IpPermission.builder();\n\n      ipBuilder.ipProtocol(protocol);\n      ipBuilder.fromPort(startPort);\n      ipBuilder.toPort(endPort);\n      if (!tenantIdGroupNamePairs.isEmpty()) {\n         ipBuilder.tenantIdGroupNamePairs(tenantIdGroupNamePairs);\n      }\n      if (!Iterables.isEmpty(ipRanges)) {\n         ipBuilder.cidrBlocks(ipRanges);\n      }\n      if (!Iterables.isEmpty(groupIds)) {\n         ipBuilder.groupIds(groupIds);\n      }\n\n      IpPermission perm = ipBuilder.build();\n\n      SecurityGroupBuilder builder = SecurityGroupBuilder.fromSecurityGroup(checkNotNull(group, \"group\"));\n\n      builder.ipPermission(perm);\n\n      SecurityGroup newGroup = builder.build();\n\n      if (groups.containsKey(newGroup.getId())) {\n         groups.remove(newGroup.getId());\n      }\n\n      groups.put(newGroup.getId(), newGroup);\n\n      return newGroup;\n   }\n\n   @Override\n   public SecurityGroup removeIpPermission(IpPermission ipPermission, SecurityGroup group) {\n      SecurityGroupBuilder builder = SecurityGroupBuilder.fromSecurityGroup(checkNotNull(group, \"group\"));\n\n      builder.ipPermissions();\n\n      builder.ipPermissions(filter(group.getIpPermissions(), not(equalTo(ipPermission))));\n\n      SecurityGroup newGroup = builder.build();\n\n      if (groups.containsKey(newGroup.getId())) {\n         groups.remove(newGroup.getId());\n      }\n\n      groups.put(newGroup.getId(), newGroup);\n\n      return newGroup;\n   }\n\n\n   @Override\n   public SecurityGroup removeIpPermission(IpProtocol protocol, int startPort, int endPort,\n                                    Multimap<String, String> tenantIdGroupNamePairs,\n                                    Iterable<String> ipRanges,\n                                    Iterable<String> groupIds, SecurityGroup group) {\n      IpPermission.Builder ipBuilder = IpPermission.builder();\n\n      ipBuilder.ipProtocol(protocol);\n      ipBuilder.fromPort(startPort);\n      ipBuilder.toPort(endPort);\n      if (!tenantIdGroupNamePairs.isEmpty()) {\n         ipBuilder.tenantIdGroupNamePairs(tenantIdGroupNamePairs);\n      }\n      if (!Iterables.isEmpty(ipRanges)) {\n         ipBuilder.cidrBlocks(ipRanges);\n      }\n      if (!Iterables.isEmpty(groupIds)) {\n         ipBuilder.groupIds(groupIds);\n      }\n\n      IpPermission perm = ipBuilder.build();\n\n      SecurityGroupBuilder builder = SecurityGroupBuilder.fromSecurityGroup(checkNotNull(group, \"group\"));\n\n      builder.ipPermissions();\n\n      builder.ipPermissions(filter(group.getIpPermissions(), not(equalTo(perm))));\n\n      SecurityGroup newGroup = builder.build();\n\n      if (groups.containsKey(newGroup.getId())) {\n         groups.remove(newGroup.getId());\n      }\n\n      groups.put(newGroup.getId(), newGroup);\n\n      return newGroup;\n   }\n\n   @Override\n   public boolean supportsTenantIdGroupNamePairs() {\n      return false;\n   }\n\n   @Override\n   public boolean supportsTenantIdGroupIdPairs() {\n      return false;\n   }\n\n   @Override\n   public boolean supportsGroupIds() {\n      return true;\n   }\n\n   @Override\n   public boolean supportsPortRangesForGroups() {\n      return true;\n   }\n\n   @Override\n   public boolean supportsExclusionCidrBlocks() {\n      return true;\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/suppliers/ImageCacheSupplier.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.suppliers;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Set;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\n\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.compute.strategy.GetImageStrategy;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.suppliers.MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier;\nimport org.jclouds.rest.suppliers.ValueLoadedCallback;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Maps;\nimport com.google.inject.Provider;\n\n/**\n * Memoized image supplier that allows new images to be registered at runtime.\n * <p>\n * The memoized <code>Supplier<Set<? extends Image>></code> is a static data\n * structure that can't be properly modified at runtime. This class is a wrapper\n * for the image supplier to provide a way to register new images as needed.\n * Once a new image is created by the\n * {@link org.jclouds.compute.extensions.ImageExtension}, or discovered by other\n * means (see https://issues.apache.org/jira/browse/JCLOUDS-570) this supplier\n * will allow the image to be appended to the cached list.\n */\n@Beta\npublic class ImageCacheSupplier implements Supplier<Set<? extends Image>>, ValueLoadedCallback<Set<? extends Image>> {\n\n   /**\n    * The image supplier that fetches the images from the provider.\n    */\n   private final Supplier<Set<? extends Image>> liveImageSupplier;\n   \n   /**\n    * The image supplier that loads the images and caches them for the duration\n    * of the session. Delegates to the {@link #liveImageSupplier}.\n    */\n   private final Supplier<Set<? extends Image>> memoizedImageSupplier;\n   \n   /**\n    * The actual image cache. It acts as a view over the memoized image supplier\n    * and allows to add and remove images at runtime.\n    */\n   private final LoadingCache<String, Image> imageCache;\n   \n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   public ImageCacheSupplier(Supplier<Set<? extends Image>> imageSupplier, long sessionIntervalSeconds,\n         AtomicReference<AuthorizationException> authException, final Provider<GetImageStrategy> imageLoader) {\n      liveImageSupplier = imageSupplier;\n      memoizedImageSupplier = MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier.create(authException,\n            imageSupplier, sessionIntervalSeconds, TimeUnit.SECONDS, this);\n      imageCache = CacheBuilder.newBuilder().expireAfterWrite(sessionIntervalSeconds, TimeUnit.SECONDS)\n            .build(new CacheLoader<String, Image>() {\n               @Override\n               public Image load(String key) throws Exception {\n                  return imageLoader.get().getImage(key);\n               }\n            });\n   }\n   \n   @Override\n   public Set<? extends Image> get() {\n      // Call the memoized supplier. The \"imageCache\" is subscribed to the\n      // reloads of the supplier once it expires. For this reason we ignore the\n      // value returned by the supplier: every time it is reloaded, the cache\n      // will be notified and re-populated with the fresh values. Any other call\n      // to the supplier that returns a cached value will be ignored and the\n      // values in the cache will be returned, as the cache properly handles\n      // individual image additions and deletions (introduced, for example, by\n      // the usage of the ImageExtension).\n      memoizedImageSupplier.get();\n      return ImmutableSet.copyOf(imageCache.asMap().values());\n   }\n\n   /**\n    * The cache is subscribed to value loading events generated by the\n    * {@link MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier}.\n    * <p>\n    * Every time the memoized supplier reloads a value, an event will be\n    * populated and this method will handle it. This makes it possible to\n    * refresh the cache with the last values everytime they are reloaded.\n    */\n   @Override\n   public void valueLoaded(Optional<Set<? extends Image>> value) {\n      if (value.isPresent()) {\n         reset(value.get());\n      }\n   }\n   \n   /**\n    * Resets the cache to the given set of images.\n    * <p>\n    * This method is called when the memoized image supplier is reloaded, or\n    * when the cache needs to be refreshed (for example when the TempalteBuilder\n    * is invoked forcing a fresh image lookup.\n    */\n   public void reset(Set<? extends Image> images) {\n      imageCache.invalidateAll();\n      imageCache.putAll(Maps.uniqueIndex(images, new Function<Image, String>() {\n         @Override\n         public String apply(Image input) {\n            return input.getId();\n         }\n      }));\n   }\n   \n   /**\n    * Calls the {@link #liveImageSupplier} to get the current images and\n    * rebuilds the cache with them.\n    */\n   public Set<? extends Image> rebuildCache() {\n      Set<? extends Image> images = liveImageSupplier.get();\n      reset(images);\n      return images;\n   }\n\n   /**\n    * Loads an image by id.\n    * <p>\n    * This methods returns the cached image, or performs a call to retrieve it\n    * if the image is still not cached.\n    */\n   public Optional<? extends Image> get(String id) {\n      try {\n         return Optional.fromNullable(imageCache.getUnchecked(id));\n      } catch (Exception ex) {\n         logger.error(ex, \"Unexpected error loading image %s\", id);\n         return Optional.absent();\n      }\n   }\n\n   /**\n    * Registers a new image in the image cache.\n    * <p>\n    * This method should be called to register new images into the image cache\n    * when some image that is known to exist in the provider is still not\n    * cached. For example, this can happen when an image is created after the\n    * image cache has been populated for the first time.\n    * <p>\n    * Note that this method does not check if the image is already cached, to\n    * avoid loading all images if the image cache is still not populated.\n    *\n    * @param image The image to be registered to the cache.\n    */\n   public void registerImage(Image image) {\n      checkNotNull(image, \"image\");\n      imageCache.put(image.getId(), image);\n   }\n\n   /**\n    * Removes an image from the image cache.\n    * <p>\n    * This method should be called to invalidate an already cached image, when\n    * some image known to not exist in the provider is still cached.\n    * \n    * @param imageId The id of the image to invalidate.\n    */\n   public void removeImage(String imageId) {\n      imageCache.invalidate(checkNotNull(imageId, \"imageId\"));\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/util/AutomaticHardwareIdSpec.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.util;\n\nimport com.google.common.base.Optional;\nimport com.google.common.base.Splitter;\n\nimport java.util.Map;\n\npublic class AutomaticHardwareIdSpec {\n\n   private double cores;\n   private int ram;\n   private Optional<Float> disk = Optional.absent();\n\n   public static boolean isAutomaticId(String id) {\n      return id.startsWith(\"automatic:\");\n   }\n\n   public static AutomaticHardwareIdSpec parseId(String hardwareId) {\n      AutomaticHardwareIdSpec spec = new AutomaticHardwareIdSpec();\n      String hardwareSpec = hardwareId.substring(10);\n      Map<String, String> specValues = Splitter.on(';')\n            .trimResults()\n            .omitEmptyStrings()\n            .withKeyValueSeparator('=')\n            .split(hardwareSpec);\n      if (!specValues.containsKey(\"ram\") || !specValues.containsKey(\"cores\")) {\n         throw new IllegalArgumentException(String.format(\"Omitted keys on hardwareId: %s. Please set number \" +\n               \"of cores and ram amount.\", hardwareId));\n      }\n      if (specValues.containsKey(\"disk\")) {\n         float disk = Float.parseFloat(specValues.get(\"disk\"));\n         if (disk > 0.0f) {\n            spec.disk = Optional.of(disk);\n         }\n         else {\n            throw new IllegalArgumentException(String.format(\"Invalid disk value: %s\", hardwareId));\n         }\n      }\n      spec.ram = Integer.parseInt(specValues.get(\"ram\"));\n      spec.cores = Double.parseDouble(specValues.get(\"cores\"));\n      return spec;\n   }\n\n   public static AutomaticHardwareIdSpec automaticHardwareIdSpecBuilder(double cores, int ram, Optional<Float> disk) {\n      AutomaticHardwareIdSpec spec = new AutomaticHardwareIdSpec();\n      if (cores <= 0 || ram == 0) {\n         throw new IllegalArgumentException(String.format(\"Omitted or wrong minCores and minRam. If you want to\" +\n               \" use exact values, please set the minCores and minRam values: cores=%s, ram=%s\", cores, ram));\n      }\n      if (disk.isPresent() && disk.get() <= 0.0f) {\n         throw new IllegalArgumentException(String.format(\"Invalid disk value: %.0f\", disk.get()));\n      }\n      spec.disk = disk;\n      spec.cores = cores;\n      spec.ram = ram;\n      return spec;\n   }\n\n   @Override\n   public String toString() {\n      if (disk.isPresent()) {\n         return String.format(\"automatic:cores=%s;ram=%s;disk=%.0f\", cores, ram, disk.get());\n      }\n      else {\n         return String.format(\"automatic:cores=%s;ram=%s\", cores, ram);\n      }\n   }\n\n   public double getCores() {\n      return cores;\n   }\n\n   public int getRam() {\n      return ram;\n   }\n\n   public Optional<Float> getDisk() {\n      return disk;\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/util/ComputeServiceUtils.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.util;\n\nimport static com.google.common.base.Predicates.equalTo;\nimport static com.google.common.base.Predicates.not;\nimport static com.google.common.base.Throwables.getStackTraceAsString;\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Maps.filterKeys;\nimport static com.google.common.collect.Maps.filterValues;\nimport static org.jclouds.scriptbuilder.domain.Statements.pipeHttpResponseToBash;\n\nimport java.net.URI;\nimport java.util.Formatter;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.NoSuchElementException;\nimport java.util.Set;\nimport java.util.regex.Pattern;\n\nimport org.jclouds.compute.domain.ComputeMetadata;\nimport org.jclouds.compute.domain.ComputeMetadataIncludingStatus;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadataBuilder;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.Processor;\nimport org.jclouds.compute.domain.Volume;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.scriptbuilder.domain.Statement;\nimport org.jclouds.scriptbuilder.domain.Statements;\n\nimport com.google.common.base.Joiner;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMap.Builder;\nimport com.google.common.collect.ImmutableSortedSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Maps;\nimport com.google.common.collect.Range;\nimport com.google.common.collect.RangeSet;\nimport com.google.common.collect.TreeRangeSet;\nimport com.google.common.primitives.Ints;\n\npublic class ComputeServiceUtils {\n\n   /**\n    * status as a string which optionally includes the backend status\n    */\n   public static String formatStatus(ComputeMetadataIncludingStatus<?> resource) {\n      if (resource.getBackendStatus() == null)\n         return resource.getStatus().toString();\n      return String.format(\"%s[%s]\", resource.getStatus(), resource.getBackendStatus());\n   }\n\n   public static final Pattern DELIMITED_BY_HYPHEN_ENDING_IN_HYPHEN_HEX = Pattern.compile(\"(.+)-[0-9a-f]+\");\n\n   /**\n    * build a shell script that invokes the contents of the http request in bash.\n    *\n    * @return a shell script that will invoke the http request\n    */\n   public static Statement execHttpResponse(HttpRequest request) {\n      return pipeHttpResponseToBash(request.getMethod(), request.getEndpoint(), request.getHeaders());\n   }\n\n   public static Statement execHttpResponse(URI location) {\n      return execHttpResponse(HttpRequest.builder().method(\"GET\").endpoint(location).build());\n   }\n\n   /**\n    * build a shell script that invokes the contents of the http request in bash.\n    *\n    * @return a shell script that will invoke the http request\n    */\n   public static Statement extractTargzIntoDirectory(HttpRequest targz, String directory) {\n      return Statements\n               .extractTargzIntoDirectory(targz.getMethod(), targz.getEndpoint(), targz.getHeaders(), directory);\n   }\n\n   public static Statement extractTargzIntoDirectory(URI targz, String directory) {\n      return extractTargzIntoDirectory(HttpRequest.builder().method(\"GET\").endpoint(targz).build(), directory);\n   }\n\n   /**\n    * build a shell script that invokes the contents of the http request in bash.\n    *\n    * @return a shell script that will invoke the http request\n    */\n   public static Statement extractZipIntoDirectory(HttpRequest zip, String directory) {\n      return Statements.extractZipIntoDirectory(zip.getMethod(), zip.getEndpoint(), zip.getHeaders(), directory);\n   }\n\n   public static Statement extractZipIntoDirectory(URI zip, String directory) {\n      return extractZipIntoDirectory(HttpRequest.builder().method(\"GET\").endpoint(zip).build(), directory);\n   }\n\n   public static double getCores(Hardware input) {\n      double cores = 0;\n      for (Processor processor : input.getProcessors())\n         cores += processor.getCores();\n      return cores;\n   }\n\n   public static double getCoresAndSpeed(Hardware input) {\n      double total = 0;\n      for (Processor processor : input.getProcessors())\n         total += processor.getCores() * processor.getSpeed();\n      return total;\n   }\n\n   public static double getSpace(Hardware input) {\n      double total = 0;\n      for (Volume volume : input.getVolumes()) {\n         Float size = volume.getSize();\n         if (size != null) {\n            total += size;\n         }\n      }\n      return total;\n   }\n\n   public static org.jclouds.compute.domain.OsFamily parseOsFamilyOrUnrecognized(String in) {\n      org.jclouds.compute.domain.OsFamily myOs = null;\n      for (org.jclouds.compute.domain.OsFamily os : org.jclouds.compute.domain.OsFamily.proritisedValues()) {\n         if (in.toLowerCase().replaceAll(\"\\\\s\", \"\").indexOf(os.toString()) != -1) {\n            myOs = os;\n         }\n      }\n      if (myOs != null) {\n         return myOs;\n      }\n      for (org.jclouds.compute.domain.OsFamily os : org.jclouds.compute.domain.OsFamily.nonProritisedValues()) {\n         if (in.toLowerCase().replaceAll(\"\\\\s\", \"\").indexOf(os.toString()) != -1) {\n            myOs = os;\n         }\n      }\n      return myOs != null ? myOs : OsFamily.UNRECOGNIZED;\n   }\n\n   public static String createExecutionErrorMessage(Map<?, Exception> executionExceptions) {\n      Formatter fmt = new Formatter().format(\"Execution failures:%n%n\");\n      int index = 1;\n      for (Entry<?, Exception> errorMessage : executionExceptions.entrySet()) {\n         fmt.format(\"%s) %s on %s:%n%s%n%n\", index++, errorMessage.getValue().getClass().getSimpleName(), errorMessage\n                  .getKey(), getStackTraceAsString(errorMessage.getValue()));\n      }\n      return fmt.format(\"%s error[s]\", executionExceptions.size()).toString();\n   }\n\n   public static String createNodeErrorMessage(Map<? extends NodeMetadata, ? extends Throwable> failedNodes) {\n      Formatter fmt = new Formatter().format(\"Node failures:%n%n\");\n      int index = 1;\n      for (Entry<? extends NodeMetadata, ? extends Throwable> errorMessage : failedNodes.entrySet()) {\n         fmt.format(\"%s) %s on node %s:%n%s%n%n\", index++, errorMessage.getValue().getClass().getSimpleName(),\n                  errorMessage.getKey().getId(), getStackTraceAsString(errorMessage.getValue()));\n      }\n      return fmt.format(\"%s error[s]\", failedNodes.size()).toString();\n   }\n\n   public static Iterable<? extends ComputeMetadata> filterByName(Iterable<? extends ComputeMetadata> nodes,\n            final String name) {\n      return filter(nodes, new Predicate<ComputeMetadata>() {\n         @Override\n         public boolean apply(ComputeMetadata input) {\n            return input.getName().equalsIgnoreCase(name);\n         }\n      });\n   }\n\n   /**\n    * For cloud apis that have a pattern of using empty strings as tags, return a map that contains\n    * that.\n    */\n   public static Map<String, String> metadataAndTagsAsValuesOfEmptyString(TemplateOptions options) {\n      Builder<String, String> builder = ImmutableMap.<String, String> builder();\n      builder.putAll(options.getUserMetadata());\n      for (String tag : options.getTags())\n         builder.put(tag, \"\");\n      return builder.build();\n   }\n\n   /**\n    * @see #metadataAndTagsAsValuesOfEmptyString\n    */\n   public static NodeMetadataBuilder addMetadataAndParseTagsFromValuesOfEmptyString(NodeMetadataBuilder builder,\n            Map<String, String> map) {\n      return builder.tags(filterValues(map, equalTo(\"\")).keySet()).userMetadata(filterValues(map, not(equalTo(\"\"))));\n   }\n\n   /**\n    * For cloud apis that need to namespace tags as the value of the key {@code jclouds.tags}\n    */\n   public static Map<String, String> metadataAndTagsAsCommaDelimitedValue(TemplateOptions options) {\n      Builder<String, String> builder = ImmutableMap.<String, String> builder();\n      builder.putAll(options.getUserMetadata());\n      if (!options.getTags().isEmpty())\n         builder.put(\"jclouds_tags\", Joiner.on(',').join(options.getTags()));\n      return builder.build();\n   }\n\n   /**\n    * @see #metadataAndTagsAsCommaDelimitedValue\n    */\n   public static NodeMetadataBuilder addMetadataAndParseTagsFromCommaDelimitedValue(NodeMetadataBuilder builder,\n            Map<String, String> map) {\n      String tagString = map.get(\"jclouds_tags\");\n      if (tagString != null)\n         builder.tags(Splitter.on(',').split(tagString));\n      builder.userMetadata(filterKeys(map, not(equalTo(\"jclouds_tags\"))));\n      return builder;\n   }\n\n   public static String parseVersionOrReturnEmptyString(org.jclouds.compute.domain.OsFamily family, String in,\n            Map<OsFamily, Map<String, String>> osVersionMap) {\n      if (osVersionMap.containsKey(family)) {\n         if (osVersionMap.get(family).containsKey(in))\n            return osVersionMap.get(family).get(in);\n         if (osVersionMap.get(family).containsValue(in))\n            return in;\n         ContainsSubstring contains = new ContainsSubstring(in.replace('-', '.'));\n         try {\n            String key = Iterables.find(osVersionMap.get(family).keySet(), contains);\n            return osVersionMap.get(family).get(key);\n         } catch (NoSuchElementException e) {\n            try {\n               return Iterables.find(osVersionMap.get(family).values(), contains);\n            } catch (NoSuchElementException e1) {\n            }\n         }\n      }\n      return \"\";\n   }\n\n   static final class ContainsSubstring implements Predicate<String> {\n      private final String in;\n\n      ContainsSubstring(String in) {\n         this.in = in;\n      }\n\n      @Override\n      public boolean apply(String input) {\n         if (\"\".equals(input))\n            return false;\n         return in.indexOf(input) != -1;\n      }\n\n      @Override\n      public String toString() {\n         return String.format(\"containsSubString(%s)\", in);\n      }\n   }\n\n   public static Map<Integer, Integer> getPortRangesFromList(int... ports) {\n      Set<Integer> sortedPorts = ImmutableSortedSet.copyOf(Ints.asList(ports));\n\n      RangeSet<Integer> ranges = TreeRangeSet.create();\n\n      for (Integer port : sortedPorts) {\n         ranges.add(Range.closedOpen(port, port + 1));\n      }\n\n      Map<Integer, Integer> portRanges = Maps.newHashMap();\n\n      for (Range<Integer> r : ranges.asRanges()) {\n         portRanges.put(r.lowerEndpoint(), r.upperEndpoint() - 1);\n      }\n\n      return portRanges;\n   }\n\n   public static String groupFromMapOrName(Map<String, String> metadataMap, String nodeName, GroupNamingConvention namingConvention) {\n      if (metadataMap.get(ComputeServiceConstants.NODE_GROUP_KEY) != null) {\n         return metadataMap.get(ComputeServiceConstants.NODE_GROUP_KEY);\n      } else {\n         return namingConvention.groupInUniqueNameOrNull(nodeName);\n      }\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/util/ComputeUtils.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.util;\n\nimport static com.google.common.collect.Maps.newLinkedHashMap;\n\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Constants;\nimport org.jclouds.compute.config.CustomizationResponse;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.compute.strategy.CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap;\n\nimport com.google.common.collect.Multimap;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.ListeningExecutorService;\n\n@Singleton\npublic class ComputeUtils {\n   private final CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap.Factory customizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapFactory;\n   private final ListeningExecutorService userExecutor;\n\n   @Inject\n   public ComputeUtils(\n            CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap.Factory customizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapFactory,\n            @Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor) {\n      this.customizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapFactory = customizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapFactory;\n      this.userExecutor = userExecutor;\n   }\n\n   public Map<?, ListenableFuture<Void>> customizeNodesAndAddToGoodMapOrPutExceptionIntoBadMap(TemplateOptions options,\n            Iterable<NodeMetadata> runningNodes, Set<NodeMetadata> goodNodes, Map<NodeMetadata, Exception> badNodes,\n            Multimap<NodeMetadata, CustomizationResponse> customizationResponses) {\n      Map<NodeMetadata, ListenableFuture<Void>> responses = newLinkedHashMap();\n      for (NodeMetadata node : runningNodes) {\n         responses.put(node, userExecutor.submit(customizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapFactory.create(\n                  options, new AtomicReference<NodeMetadata>(node), goodNodes, badNodes, customizationResponses)));\n      }\n      return responses;\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/util/ConcurrentOpenSocketFinder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.util;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.common.base.Predicates.or;\nimport static com.google.common.base.Throwables.propagate;\nimport static com.google.common.util.concurrent.Atomics.newReference;\nimport static com.google.common.util.concurrent.MoreExecutors.listeningDecorator;\nimport static java.lang.String.format;\nimport static org.jclouds.Constants.PROPERTY_USER_THREADS;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_RUNNING;\nimport static org.jclouds.compute.config.ComputeServiceProperties.SOCKET_FINDER_ALLOWED_INTERFACES;\nimport static org.jclouds.util.Predicates2.retry;\n\nimport java.util.NoSuchElementException;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\n\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.predicates.SocketOpen;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableList.Builder;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.net.HostAndPort;\nimport com.google.common.util.concurrent.Futures;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.inject.Inject;\n\npublic class ConcurrentOpenSocketFinder implements OpenSocketFinder {\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   private Logger logger = Logger.NULL;\n\n   private final SocketOpen socketTester;\n   private final Predicate<AtomicReference<NodeMetadata>> nodeRunning;\n   private final ListeningExecutorService userExecutor;\n\n   @Inject(optional = true)\n   @Named(SOCKET_FINDER_ALLOWED_INTERFACES)\n   private AllowedInterfaces allowedInterfaces = AllowedInterfaces.ALL;\n\n   @Inject\n   @VisibleForTesting\n   ConcurrentOpenSocketFinder(SocketOpen socketTester,\n         @Named(TIMEOUT_NODE_RUNNING) Predicate<AtomicReference<NodeMetadata>> nodeRunning,\n         @Named(PROPERTY_USER_THREADS) ListeningExecutorService userExecutor) {\n      this.socketTester = checkNotNull(socketTester, \"socketTester\");\n      this.nodeRunning = checkNotNull(nodeRunning, \"nodeRunning\");\n      this.userExecutor = listeningDecorator(checkNotNull(userExecutor, \"userExecutor\"));\n   }\n\n   @Override\n   public HostAndPort findOpenSocketOnNode(NodeMetadata node, final int port, long timeout, TimeUnit timeUnits) {\n      ImmutableSet<HostAndPort> sockets = checkNodeHasIps(node, allowedInterfaces).transform(new Function<String, HostAndPort>() {\n\n         @Override\n         public HostAndPort apply(String from) {\n            return HostAndPort.fromParts(from, port);\n         }\n      }).toSet();\n\n      // Specify a retry period of 1s, expressed in the same time units.\n      long period = timeUnits.convert(1, TimeUnit.SECONDS);\n\n      // For retrieving the socket found (if any)\n      AtomicReference<HostAndPort> result = newReference();\n\n      Predicate<Iterable<HostAndPort>> findOrBreak = or(updateRefOnSocketOpen(result), throwISEIfNoLongerRunning(node));\n\n      logger.debug(\">> blocking on sockets %s for %d %s\", sockets, timeout, timeUnits);\n      boolean passed = retryPredicate(findOrBreak, timeout, period,  timeUnits).apply(sockets);\n\n      if (passed) {\n         logger.debug(\"<< socket %s opened\", result);\n         assert result.get() != null;\n         return result.get();\n      } else {\n         logger.warn(\"<< sockets %s didn't open after %d %s\", sockets, timeout, timeUnits);\n         throw new NoSuchElementException(format(\"could not connect to any ip address port %d on node %s\", port, node));\n      }\n\n   }\n\n   @VisibleForTesting\n   protected <T> Predicate<T> retryPredicate(Predicate<T> findOrBreak, long timeout, long period, TimeUnit timeUnits) {\n      return retry(findOrBreak, timeout, period, timeUnits);\n   }\n\n   /**\n    * Checks if any any of the given HostAndPorts are reachable. It checks them\n    * all concurrently, and sets reference to a {@link HostAndPort} if found or\n    * returns false;\n    */\n   private Predicate<Iterable<HostAndPort>> updateRefOnSocketOpen(final AtomicReference<HostAndPort> reachableSocket) {\n      return new Predicate<Iterable<HostAndPort>>() {\n\n         @Override\n         public boolean apply(Iterable<HostAndPort> input) {\n\n            Builder<ListenableFuture<?>> futures = ImmutableList.builder();\n            for (final HostAndPort socket : input) {\n               futures.add(userExecutor.submit(new Runnable() {\n\n                  @Override\n                  public void run() {\n                     try {\n                        if (socketTester.apply(socket)) {\n                           // only set if the this socket was found first\n                           reachableSocket.compareAndSet(null, socket);\n                        }\n                     } catch (RuntimeException e) {\n                        logger.warn(e, \"Error checking reachability of ip:port %s\", socket);\n                     }\n                  }\n\n               }));\n            }\n            blockOn(futures.build());\n            return reachableSocket.get() != null;\n         }\n\n         @Override\n         public String toString() {\n            return \"setAndReturnTrueIfSocketFound()\";\n         }\n      };\n   }\n\n   /**\n    * Add this via\n    * {@code Predicates.or(condition, throwISEIfNoLongerRunning(node))} to\n    * short-circuit {@link RetryablePredicate} looping when the node is no\n    * longer running.\n    */\n   private <T> Predicate<T> throwISEIfNoLongerRunning(final NodeMetadata node) {\n      return new Predicate<T>() {\n\n         @Override\n         public boolean apply(T input) {\n            if (!nodeRunning.apply(newReference(node))) {\n               throw new IllegalStateException(node.getId() + \" is no longer running; aborting socket open loop\");\n            }\n            return false;\n         }\n\n         @Override\n         public String toString() {\n            return \"throwISEIfNoLongerRunning(\" + node.getId() + \")\";\n         }\n      };\n   }\n\n   @VisibleForTesting\n   static FluentIterable<String> checkNodeHasIps(NodeMetadata node, AllowedInterfaces allowedInterfaces) {\n      ImmutableSet.Builder<String> ipsBuilder = ImmutableSet.builder();\n      if (allowedInterfaces.scanPublic) {\n         ipsBuilder.addAll(node.getPublicAddresses());\n      }\n      if (allowedInterfaces.scanPrivate) {\n         ipsBuilder.addAll(node.getPrivateAddresses());\n      }\n      ImmutableSet<String> ips = ipsBuilder.build();\n      checkState(!ips.isEmpty(), \"node does not have IP addresses configured: %s\", node);\n      return FluentIterable.from(ips);\n   }\n\n   private static void blockOn(Iterable<ListenableFuture<?>> immutableList) {\n      try {\n         Futures.allAsList(immutableList).get();\n      } catch (InterruptedException e) {\n         Thread.currentThread().interrupt();\n         throw propagate(e);\n      } catch (ExecutionException e) {\n         throw propagate(e);\n      }\n   }\n\n   @VisibleForTesting\n   enum AllowedInterfaces {\n      ALL(true, true),\n      PUBLIC(true, false),\n      PRIVATE(false, true);\n\n      private final boolean scanPublic;\n      private final boolean scanPrivate;\n\n      private AllowedInterfaces(boolean scanPublic, boolean scanPrivate) {\n         this.scanPublic = scanPublic;\n         this.scanPrivate = scanPrivate;\n      }\n\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/compute/util/OpenSocketFinder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.util;\n\nimport java.util.concurrent.TimeUnit;\n\nimport org.jclouds.compute.domain.NodeMetadata;\n\nimport com.google.common.net.HostAndPort;\nimport com.google.inject.ImplementedBy;\n\n/**\n * For finding an open/reachable ip:port for a node.\n */\n@ImplementedBy(ConcurrentOpenSocketFinder.class)\npublic interface OpenSocketFinder {\n\n   /**\n    * \n    * @param node         The node (checking its public and private addresses)\n    * @param port         The port to try to connect to\n    * @param timeoutValue Max time to try to connect to the ip:port\n    * @param timeUnits\n    * \n    * @return The reachable ip:port\n    * @throws NoSuchElementException If no ports accessible within the given time\n    * @throws IllegalStateException  If the given node has no public or private addresses\n    */\n   HostAndPort findOpenSocketOnNode(final NodeMetadata node, final int port, long timeoutValue, TimeUnit timeUnits);\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/net/domain/IpPermission.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.net.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.transform;\nimport static org.jclouds.util.Strings2.isCidrFormat;\n\nimport java.util.Collection;\nimport java.util.Comparator;\nimport java.util.Iterator;\nimport java.util.Set;\n\nimport org.jclouds.net.util.IpPermissions;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Function;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.LinkedHashMultimap;\nimport com.google.common.collect.Multimap;\nimport com.google.common.collect.Sets;\n\n/**\n * Ingress access to a destination protocol on particular ports by source, which could be an ip\n * range (cidrblock), set of explicit security group ids in the current tenant, or security group\n * names in another tenant.\n *\n * @see IpPermissions\n */\n@Beta\npublic class IpPermission implements Comparable<IpPermission> {\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n      private IpProtocol ipProtocol;\n      private int fromPort;\n      private int toPort;\n      private Multimap<String, String> tenantIdGroupNamePairs = LinkedHashMultimap.create();\n      private Set<String> groupIds = Sets.newLinkedHashSet();\n      private Set<String> cidrBlocks = Sets.newLinkedHashSet();\n      private Set<String> exclusionCidrBlocks = Sets.newLinkedHashSet();\n\n      /**\n       * Creates a builder initialized from an existing permission.\n       * @param permission The existing permission.\n       * @return the builder.\n       */\n      public Builder fromPermission(IpPermission permission) {\n         this.ipProtocol = permission.ipProtocol;\n         this.fromPort = permission.fromPort;\n         this.toPort = permission.toPort;\n         this.tenantIdGroupNamePairs = LinkedHashMultimap.create();\n         tenantIdGroupNamePairs.putAll(permission.tenantIdGroupNamePairs);\n         this.groupIds = Sets.newLinkedHashSet();\n         this.groupIds.addAll(permission.groupIds);\n         this.cidrBlocks = Sets.newLinkedHashSet();\n         this.cidrBlocks.addAll(permission.cidrBlocks);\n         this.exclusionCidrBlocks = Sets.newLinkedHashSet();\n         this.exclusionCidrBlocks.addAll(permission.exclusionCidrBlocks);\n         return this;\n      }\n\n      /**\n       * @see IpPermission#getIpProtocol()\n       */\n      public Builder ipProtocol(IpProtocol ipProtocol) {\n         this.ipProtocol = ipProtocol;\n         return this;\n      }\n\n      /**\n       * @see IpPermission#getFromPort()\n       */\n      public Builder fromPort(int fromPort) {\n         this.fromPort = fromPort;\n         return this;\n      }\n\n      /**\n       * @see IpPermission#getToPort()\n       */\n      public Builder toPort(int toPort) {\n         this.toPort = toPort;\n         return this;\n      }\n\n      /**\n       * @see IpPermission#getTenantIdGroupNamePairs()\n       */\n      public Builder tenantIdGroupNamePair(String tenantId, String groupName) {\n         this.tenantIdGroupNamePairs.put(tenantId, groupName);\n         return this;\n      }\n\n      /**\n       * @see IpPermission#getTenantIdGroupNamePairs()\n       */\n      public Builder tenantIdGroupNamePairs(Multimap<String, String> tenantIdGroupNamePairs) {\n         this.tenantIdGroupNamePairs.putAll(tenantIdGroupNamePairs);\n         return this;\n      }\n\n      /**\n       * @see IpPermission#getCidrBlocks()\n       */\n      public Builder cidrBlock(String cidrBlock) {\n         checkArgument(isCidrFormat(cidrBlock), \"cidrBlock %s is not a valid CIDR\", cidrBlock);\n         this.cidrBlocks.add(cidrBlock);\n         return this;\n      }\n\n      /**\n       * @see IpPermission#getCidrBlocks()\n       */\n      public Builder cidrBlocks(Iterable<String> cidrBlocks) {\n         Iterables.addAll(this.cidrBlocks, transform(cidrBlocks, new Function<String, String>() {\n            @Override\n            public String apply(String input) {\n               checkArgument(isCidrFormat(input), \"input %s is not a valid CIDR\", input);\n               return input;\n            }\n         }));\n         return this;\n      }\n\n      /**\n       * @see IpPermission#getExclusionCidrBlocks()\n       */\n      @Beta\n      public Builder exclusionCidrBlock(String exclusionCidrBlock) {\n         checkArgument(isCidrFormat(exclusionCidrBlock), \"exclusionCidrBlock %s is not a valid CIDR\",\n            exclusionCidrBlock);\n         this.exclusionCidrBlocks.add(exclusionCidrBlock);\n         return this;\n      }\n\n      /**\n       * @see IpPermission#getExclusionCidrBlocks()\n       */\n      @Beta\n      public Builder exclusionCidrBlocks(Iterable<String> exclusionCidrBlocks) {\n         Iterables.addAll(this.exclusionCidrBlocks, transform(exclusionCidrBlocks, new Function<String, String>() {\n            @Override\n            public String apply(String input) {\n               checkArgument(isCidrFormat(input), \"input %s is not a valid CIDR\", input);\n               return input;\n            }\n         }));\n         return this;\n      }\n\n      /**\n       * @see IpPermission#getGroupIds()\n       */\n      public Builder groupId(String groupId) {\n         this.groupIds.add(groupId);\n         return this;\n      }\n\n      /**\n       * @see IpPermission#getGroupIds()\n       */\n      public Builder groupIds(Iterable<String> groupIds) {\n         Iterables.addAll(this.groupIds, groupIds);\n         return this;\n      }\n\n      public IpPermission build() {\n         return new IpPermission(ipProtocol, fromPort, toPort, tenantIdGroupNamePairs, groupIds, cidrBlocks,\n            exclusionCidrBlocks);\n      }\n   }\n\n   private final int fromPort;\n   private final int toPort;\n   private final Multimap<String, String> tenantIdGroupNamePairs;\n   private final Set<String> groupIds;\n   private final IpProtocol ipProtocol;\n   private final Set<String> cidrBlocks;\n   private final Set<String> exclusionCidrBlocks;\n\n   public IpPermission(IpProtocol ipProtocol, int fromPort, int toPort,\n                       Multimap<String, String> tenantIdGroupNamePairs, Iterable<String> groupIds, Iterable<String> cidrBlocks,\n                       Iterable<String> exclusionCidrBlocks) {\n      this.fromPort = fromPort;\n      this.toPort = toPort;\n      this.tenantIdGroupNamePairs = ImmutableMultimap.copyOf(checkNotNull(tenantIdGroupNamePairs,\n         \"tenantIdGroupNamePairs\"));\n      this.ipProtocol = checkNotNull(ipProtocol, \"ipProtocol\");\n      this.groupIds = ImmutableSet.copyOf(checkNotNull(groupIds, \"groupIds\"));\n      this.cidrBlocks = ImmutableSet.copyOf(checkNotNull(cidrBlocks, \"cidrBlocks\"));\n      this.exclusionCidrBlocks = ImmutableSet.copyOf(checkNotNull(exclusionCidrBlocks, \"exclusionCidrBlocks\"));\n   }\n\n\n   /**\n    * destination IP protocol\n    */\n   public IpProtocol getIpProtocol() {\n      return ipProtocol;\n   }\n\n   /**\n    * Start of destination port range for the TCP and UDP protocols, or an ICMP type number. An ICMP\n    * type number of -1 indicates a wildcard (i.e., any ICMP type number).\n    */\n   public int getFromPort() {\n      return fromPort;\n   }\n\n   /**\n    * End of destination port range for the TCP and UDP protocols, or an ICMP code. An ICMP code of\n    * -1 indicates a wildcard (i.e., any ICMP code).\n    */\n   public int getToPort() {\n      return toPort;\n   }\n\n   /**\n    * source of traffic allowed is on basis of another group in a tenant, as opposed to by cidr\n    */\n   public Multimap<String, String> getTenantIdGroupNamePairs() {\n      return tenantIdGroupNamePairs;\n   }\n\n   /**\n    * source of traffic allowed is on basis of another groupid in the same tenant\n    */\n   public Set<String> getGroupIds() {\n      return groupIds;\n   }\n\n   /**\n    * source of traffic is a cidrRange\n    */\n   public Set<String> getCidrBlocks() {\n      return cidrBlocks;\n   }\n\n   /**\n    * Traffic whose source matches any of these CIDR blocks will be blocked\n    */\n   @Beta\n   public Set<String> getExclusionCidrBlocks() {\n      return exclusionCidrBlocks;\n   }\n\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public int compareTo(IpPermission that) {\n      if (this == that) return 0;\n      final int proto = getIpProtocol().compareTo(that.getIpProtocol());\n      if (proto != 0) return proto;\n\n      final int fromP = Integer.valueOf(this.fromPort).compareTo(Integer.valueOf(that.fromPort));\n      if (fromP != 0) return fromP;\n\n      final int toP = Integer.valueOf(this.toPort).compareTo(Integer.valueOf(that.toPort));\n      if (toP != 0) return toP;\n\n      final int tenantGroups = new LinkedMultiMapComparator<String, String>()\n         .compare(this.tenantIdGroupNamePairs, that.tenantIdGroupNamePairs);\n      if (tenantGroups != 0) return tenantGroups;\n\n      final int groupIdComp = new CollectionComparator<String>()\n         .compare(this.groupIds, that.groupIds);\n      if (groupIdComp != 0) return groupIdComp;\n\n      final int cidrComp = new CollectionComparator<String>()\n         .compare(this.cidrBlocks, that.cidrBlocks);\n      if (cidrComp != 0) return cidrComp;\n\n      final int exclusionsComp = new CollectionComparator<String>()\n         .compare(this.exclusionCidrBlocks, that.exclusionCidrBlocks);\n      if (exclusionsComp != 0) return exclusionsComp;\n\n      return 0;\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o)\n         return true;\n      // allow subtypes\n      if (o == null || !(o instanceof IpPermission))\n         return false;\n      IpPermission that = IpPermission.class.cast(o);\n      return equal(this.ipProtocol, that.ipProtocol) && equal(this.fromPort, that.fromPort)\n         && equal(this.toPort, that.toPort) && equal(this.tenantIdGroupNamePairs, that.tenantIdGroupNamePairs)\n         && equal(this.groupIds, that.groupIds) && equal(this.cidrBlocks, that.cidrBlocks)\n         && equal(this.exclusionCidrBlocks, that.exclusionCidrBlocks);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(ipProtocol, fromPort, toPort, tenantIdGroupNamePairs, groupIds, cidrBlocks,\n         exclusionCidrBlocks);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(\"\").add(\"ipProtocol\", ipProtocol).add(\"fromPort\", fromPort)\n         .add(\"toPort\", toPort).add(\"tenantIdGroupNamePairs\", tenantIdGroupNamePairs).add(\"groupIds\", groupIds)\n         .add(\"cidrBlocks\", cidrBlocks).add(\"exclusionCidrBlocks\", exclusionCidrBlocks);\n   }\n\n\n   // A private tool for use in implementing a consistent compareTo relation.\n   private static class LinkedMultiMapComparator<K extends Comparable, V> implements Comparator<Multimap<K, V>> {\n\n      /**\n       * Compares {@link Multimap}s, in order of iterators.\n       * If two keys do not compare as zero, the key comparison result is used as the comparison result.\n       * For keys that are equal, the value collections are compared with {@link CollectionComparator}.\n       * If all entries compare as zero the map sizes determine the result.\n       *\n       * @param map1 The first map for comparison\n       * @param map2 The second map for comparison\n       * @return the comparison relation value\n       */\n      @Override\n      public int compare(Multimap<K, V> map1, Multimap<K, V> map2) {\n         final Iterator<K> leftIter = map1.keySet().iterator();\n         final Iterator<K> rightIter = map2.keySet().iterator();\n         while (leftIter.hasNext() && rightIter.hasNext()) {\n            K key1 = leftIter.next();\n            K key2 = rightIter.next();\n\n            int keyComp = key1.compareTo(key2);\n            if (keyComp != 0) return keyComp;\n\n            final int valuesComp = new CollectionComparator().compare(map1.get(key1), map2.get(key2));\n            if (valuesComp != 0) return valuesComp;\n         }\n         if (!leftIter.hasNext() && rightIter.hasNext()) {\n            return -1;\n         }\n         if (leftIter.hasNext() && !rightIter.hasNext()) {\n            return +1;\n         }\n         return 0;\n      }\n   }\n\n   // A private tool for use in implementing a consistent compareTo relation.\n   private static class CollectionComparator<T extends Comparable> implements Comparator<Collection<T>> {\n\n      /**\n       * Compares collections of comparable objects, in order of iterator.\n       * Iterates through the collections in step.\n       * If two entries do not compare as zero, the comparison result is the result of this method.\n       * If all entries compare as zero, then the collection sizes determine the result.\n       *\n       * @param o1 The first collection to compare.\n       * @param o2 The second collection to compare.\n       * @return The comparison relation value.\n       */\n      @Override\n      public int compare(Collection<T> o1, Collection<T> o2) {\n\n         final Iterator<T> leftIter = o1.iterator();\n         final Iterator<T> rightIter = o2.iterator();\n         while (leftIter.hasNext() && rightIter.hasNext()) {\n            int comp = leftIter.next().compareTo(rightIter.next());\n            if (comp != 0) return comp;\n         }\n         if (!leftIter.hasNext() && rightIter.hasNext()) {\n            return -1;\n         }\n         if (leftIter.hasNext() && !rightIter.hasNext()) {\n            return +1;\n         }\n         return 0;\n      }\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/net/domain/IpProtocol.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.net.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.annotations.Beta;\n\n@Beta\npublic enum IpProtocol {\n\n   TCP, UDP, ICMP, ALL, UNRECOGNIZED;\n\n   public String value() {\n      return this == ALL ? \"-1\" : name().toLowerCase();\n   }\n\n   @Override\n   public String toString() {\n      return value();\n   }\n\n   public static IpProtocol fromValue(String protocol) {\n      try {\n         if (protocol.equalsIgnoreCase(\"-1\"))\n            return ALL;\n         return valueOf(checkNotNull(protocol, \"protocol\").toUpperCase());\n      } catch (IllegalArgumentException e) {\n         return UNRECOGNIZED;\n      }\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/net/util/IpPermissions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.net.util;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.net.domain.IpPermission;\nimport org.jclouds.net.domain.IpProtocol;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Multimap;\n\n/**\n * \n * Shortcut to create ingress rules\n */\npublic class IpPermissions extends IpPermission {\n\n   protected IpPermissions(IpProtocol ipProtocol, int fromPort, int toPort,\n         Multimap<String, String> tenantIdGroupPairs, Iterable<String> groupIds, Iterable<String> cidrBlocks,\n         Iterable<String> exclusionCidrBlocks) {\n      super(ipProtocol, fromPort, toPort, tenantIdGroupPairs, groupIds, tenantIdGroupPairs.size() == 0 ? cidrBlocks\n            : ImmutableSet.<String> of(), tenantIdGroupPairs.size() == 0 ? exclusionCidrBlocks : ImmutableSet\n            .<String> of());\n   }\n\n   public static ICMPTypeSelection permitICMP() {\n      return new ICMPTypeSelection();\n   }\n\n   public static ToSourceSelection permitAnyProtocol() {\n      return new ToSourceSelection(IpProtocol.ALL, 1, 65535);\n   }\n\n   public static PortSelection permit(IpProtocol protocol) {\n      return new PortSelection(checkNotNull(protocol, \"protocol\"));\n   }\n\n   public static class ICMPTypeSelection extends ToSourceSelection {\n\n      ICMPTypeSelection() {\n         super(IpProtocol.ICMP, -1, -1);\n      }\n\n      /**\n       * @param type ex. 8 for ECHO (i.e. Ping)\n       * @see <a href=\"http://www.iana.org/assignments/icmp-parameters/icmp-parameters.xml\"> ICMP Types</a>\n       */\n      public AndCodeSelection type(int type) {\n         return new AndCodeSelection(type);\n      }\n   }\n\n   public static class AndCodeSelection extends ToSourceSelection {\n      AndCodeSelection(int type) {\n         super(IpProtocol.ICMP, type, -1);\n      }\n\n      public ToSourceSelection andCode(int code) {\n         return new ToSourceSelection(getIpProtocol(), getFromPort(), code);\n      }\n\n   }\n\n   public static class PortSelection extends ToSourceSelection {\n\n      PortSelection(IpProtocol ipProtocol) {\n         super(ipProtocol, ipProtocol == IpProtocol.ICMP ? -1 : 1, ipProtocol == IpProtocol.ICMP ? -1 : 65535);\n      }\n\n      public ToPortSelection fromPort(int port) {\n         return new ToPortSelection(getIpProtocol(), port);\n      }\n      \n      public ToSourceSelection port(int port) {\n         return new ToSourceSelection(getIpProtocol(), port, port);\n      }\n   }\n\n   public static class ToPortSelection extends ToSourceSelection {\n\n      ToPortSelection(IpProtocol ipProtocol, int fromPort) {\n         super(ipProtocol, fromPort, ipProtocol == IpProtocol.ICMP ? -1 : 65535);\n      }\n\n      public ToSourceSelection to(int port) {\n         return new ToSourceSelection(getIpProtocol(), getFromPort(), port);\n      }\n   }\n\n   public static class ToGroupSourceSelection extends IpPermissions {\n\n      protected ToGroupSourceSelection(IpProtocol ipProtocol, int fromPort, int toPort) {\n         super(ipProtocol, fromPort, toPort, ImmutableMultimap.<String, String> of(), ImmutableSet.<String> of(),\n               ImmutableSet.of(\"0.0.0.0/0\"), ImmutableSet.<String> of());\n      }\n\n      public IpPermissions originatingFromSecurityGroupId(String groupId) {\n         return originatingFromSecurityGroupIds(ImmutableSet.of(checkNotNull(groupId, \"groupId\")));\n      }\n\n      public IpPermissions originatingFromSecurityGroupIds(Iterable<String> groupIds) {\n         return new IpPermissions(getIpProtocol(), getFromPort(), getToPort(), getTenantIdGroupNamePairs(), groupIds,\n               ImmutableSet.<String> of(), ImmutableSet.<String> of());\n      }\n   }\n\n   public static class ToSourceSelection extends ToGroupSourceSelection {\n      ToSourceSelection(IpProtocol ipProtocol, int fromPort, int toPort) {\n         super(ipProtocol, fromPort, toPort);\n      }\n\n      public IpPermissions originatingFromCidrBlock(String cidrIp) {\n         return originatingFromCidrBlocks(ImmutableSet.of(checkNotNull(cidrIp, \"cidrIp\")));\n      }\n\n      public IpPermissions originatingFromCidrBlocks(Iterable<String> cidrIps) {\n         return new IpPermissions(getIpProtocol(), getFromPort(), getToPort(), ImmutableMultimap.<String, String> of(),\n               ImmutableSet.<String> of(), cidrIps, ImmutableSet.<String> of());\n      }\n\n      public IpPermissions exceptOriginatingFromCidrBlock(String excludedCidrIp) {\n         return exceptOriginatingFromCidrBlocks(ImmutableSet.of(checkNotNull(excludedCidrIp, \"excludedCidrIp\")));\n      }\n\n      public IpPermissions exceptOriginatingFromCidrBlocks(Iterable<String> excludedCidrIps) {\n         return new IpPermissions(getIpProtocol(), getFromPort(), getToPort(), ImmutableMultimap.<String, String> of(),\n               ImmutableSet.<String> of(), ImmutableSet.<String> of(), excludedCidrIps);\n      }\n\n      public IpPermissions originatingFromTenantAndSecurityGroup(String tenantId, String groupName) {\n         return toTenantsGroupsNamed(ImmutableMultimap.of(checkNotNull(tenantId, \"tenantId\"),\n               checkNotNull(groupName, \"groupName\")));\n      }\n\n      public IpPermissions toTenantsGroupsNamed(Multimap<String, String> tenantIdGroupNamePairs) {\n         return new IpPermissions(getIpProtocol(), getFromPort(), getToPort(), tenantIdGroupNamePairs, getGroupIds(),\n               ImmutableSet.<String> of(), ImmutableSet.<String> of());\n      }\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/ovf/Configuration.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ovf;\n\npublic class Configuration {\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n      protected String id;\n      protected String label;\n      protected String description;\n\n      /**\n       * @see Configuration#getId\n       */\n      public Builder id(String id) {\n         this.id = id;\n         return this;\n      }\n\n      /**\n       * @see Section#getLabel\n       */\n      public Builder label(String label) {\n         this.label = label;\n         return this;\n      }\n\n      /**\n       * @see Section#getDescription\n       */\n      public Builder description(String description) {\n         this.description = description;\n         return this;\n      }\n\n      public Configuration build() {\n         return new Configuration(id, label, description);\n      }\n\n      public Builder fromConfiguration(Configuration in) {\n         return id(in.getId()).description(in.getDescription()).label(in.getLabel());\n      }\n   }\n\n   private final String id;\n   private final String label;\n   private final String description;\n\n   public Configuration(String id, String label, String description) {\n      this.id = id;\n      this.label = label;\n      this.description = description;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((id == null) ? 0 : id.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      Configuration other = (Configuration) obj;\n      if (id == null) {\n         if (other.id != null)\n            return false;\n      } else if (!id.equals(other.id))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return String.format(\"[id=%s, label=%s, description=%s]\", id, label, description);\n   }\n\n   public String getId() {\n      return id;\n   }\n\n   public String getDescription() {\n      return description;\n   }\n\n   public String getLabel() {\n      return label;\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/ovf/DeploymentOptionSection.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ovf;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Set;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Sets;\n\n/**\n * The DeploymentOptionSection specifies a discrete set of intended resource configurations. The\n * author of an OVF package can include sizing metadata for different configurations. A consumer of\n * the OVF shall select a configuration, for example, by prompting the user. The selected\n * configuration is visible in the OVF environment, enabling guest software to adapt to the selected\n * configuration.\n */\npublic class DeploymentOptionSection extends Section<DeploymentOptionSection> {\n\n   @SuppressWarnings(\"unchecked\")\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Builder toBuilder() {\n      return builder().fromDeploymentOptionSection(this);\n   }\n\n   public static class Builder extends Section.Builder<DeploymentOptionSection> {\n      protected Set<Configuration> configurations = Sets.newLinkedHashSet();\n\n      /**\n       * @see DeploymentOptionSection#getConfigurations\n       */\n      public Builder configuration(Configuration configuration) {\n         this.configurations.add(checkNotNull(configuration, \"configuration\"));\n         return this;\n      }\n\n      /**\n       * @see DeploymentOptionSection#getConfigurations\n       */\n      public Builder configurations(Iterable<Configuration> configurations) {\n         this.configurations = ImmutableSet.<Configuration> copyOf(checkNotNull(configurations, \"configurations\"));\n         return this;\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public DeploymentOptionSection build() {\n         return new DeploymentOptionSection(info, configurations);\n      }\n\n      public Builder fromDeploymentOptionSection(DeploymentOptionSection in) {\n         return info(in.getInfo()).configurations(in.getConfigurations());\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder fromSection(Section<DeploymentOptionSection> in) {\n         return Builder.class.cast(super.fromSection(in));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder info(String info) {\n         return Builder.class.cast(super.info(info));\n      }\n\n   }\n\n   protected final Set<Configuration> configurations;\n\n   public DeploymentOptionSection(String info, Iterable<Configuration> configurations) {\n      super(info);\n      this.configurations = ImmutableSet.<Configuration> copyOf(checkNotNull(configurations, \"configurations\"));\n\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = super.hashCode();\n      result = prime * result + ((configurations == null) ? 0 : configurations.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (!super.equals(obj))\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      DeploymentOptionSection other = (DeploymentOptionSection) obj;\n      if (configurations == null) {\n         if (other.configurations != null)\n            return false;\n      } else if (!configurations.equals(other.configurations))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return String.format(\"[info=%s, configurations=%s]\", info, configurations);\n   }\n\n   public Set<Configuration> getConfigurations() {\n      return configurations;\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/ovf/Disk.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ovf;\n\nimport java.net.URI;\n\npublic class Disk implements Comparable<Disk> {\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n      private String id;\n      private Long capacity;\n      private String parentRef;\n      private String fileRef;\n      private URI format;\n      private Long populatedSize;\n      private String capacityAllocationUnits;\n\n      /**\n       * @see Disk#getId\n       */\n      public Builder id(String id) {\n         this.id = id;\n         return this;\n      }\n\n      /**\n       * @see Disk#getCapacity\n       */\n      public Builder capacity(Long capacity) {\n         this.capacity = capacity;\n         return this;\n      }\n\n      /**\n       * @see Disk#getParentRef\n       */\n      public Builder parentRef(String parentRef) {\n         this.parentRef = parentRef;\n         return this;\n      }\n\n      /**\n       * @see Disk#getFileRef\n       */\n      public Builder fileRef(String fileRef) {\n         this.fileRef = fileRef;\n         return this;\n      }\n\n      /**\n       * @see Disk#getFormat\n       */\n      public Builder format(URI format) {\n         this.format = format;\n         return this;\n      }\n\n      /**\n       * @see Disk#getPopulatedSize\n       */\n      public Builder populatedSize(Long populatedSize) {\n         this.populatedSize = populatedSize;\n         return this;\n      }\n\n      /**\n       * @see Disk#getCapacityAllocationUnits\n       */\n      public Builder capacityAllocationUnits(String capacityAllocationUnits) {\n         this.capacityAllocationUnits = capacityAllocationUnits;\n         return this;\n      }\n\n      public Disk build() {\n         return new Disk(id, capacity, parentRef, fileRef, format, populatedSize, capacityAllocationUnits);\n      }\n\n      public Builder fromDisk(Disk in) {\n         return id(in.getId()).capacity(in.getCapacity()).parentRef(in.getParentRef()).fileRef(in.getFileRef()).format(\n                  in.getFormat()).populatedSize(in.getPopulatedSize()).capacityAllocationUnits(\n                  in.getCapacityAllocationUnits());\n      }\n   }\n\n   private final String id;\n   private final Long capacity;\n   private final String parentRef;\n   private final String fileRef;\n   private final URI format;\n   private final Long populatedSize;\n   private final String capacityAllocationUnits;\n\n   public Disk(String id, Long capacity, String parentRef, String fileRef, URI format, Long populatedSize,\n            String capacityAllocationUnits) {\n      this.id = id;\n      this.capacity = capacity;\n      this.parentRef = parentRef;\n      this.fileRef = fileRef;\n      this.format = format;\n      this.populatedSize = populatedSize;\n      this.capacityAllocationUnits = capacityAllocationUnits;\n   }\n\n   /**\n    * Each virtual disk is represented by a Disk element that shall be given a identifier using the\n    * {@code id} attribute, the identifier shall be unique within the {@link DiskSection}.\n    */\n   public String getId() {\n      return id;\n   }\n\n   /**\n    * The capacity of a virtual disk shall be specified by the {@code capacity} attribute with an\n    * xs:long integer value. The default unit of allocation shall be bytes.\n    */\n   public Long getCapacity() {\n      return capacity;\n   }\n\n   /**\n    * OVF allows a disk image to be represented as a set of modified blocks in comparison to a\n    * parent image. The use of parent disks can often significantly reduce the size of an OVF\n    * package, if it contains multiple disks with similar content. For a Disk element, a parent disk\n    * may optionally be specified using the {@code parentRef} attribute, which shall contain a valid\n    * ovf:id reference to a different Disk element. If a disk block does not exist locally, lookup\n    * for that disk block then occurs in the parent disk. In {@link DiskSection}, parent Disk\n    * elements shall occur before child Disk elements that refer to them.\n    */\n   public String getParentRef() {\n      return parentRef;\n   }\n\n   /**\n    * The ovf:fileRef attribute denotes the virtual disk content by identifying an existing File\n    * element in the References element, the File element is identified by matching its {@code id}\n    * attribute value with the {@code fileRef} attribute value. Omitting the {@code fileRef}\n    * attribute shall indicate an empty disk. In this case, the disk shall be created and the entire\n    * disk content zeroed at installation time. The guest software will typically format empty disks\n    * in some file system format.\n    */\n   public String getFileRef() {\n      return fileRef;\n   }\n\n   /**\n    * The format URI of a non-empty virtual disk shall be specified by the {@code format} attribute.\n    */\n   public URI getFormat() {\n      return format;\n   }\n\n   /**\n    * For non-empty disks, the actual used size of the disk may optionally be specified using the\n    * {@code populatedSize} attribute. The unit of this attribute is always bytes. {@code\n    * populatedSize} is allowed to be an estimate of used disk size but shall not be larger than\n    * {@code capacity}.\n    */\n   public Long getPopulatedSize() {\n      return populatedSize;\n   }\n\n   /**\n    * The optional string attribute {@code ovf:capacityAllocationUnits} may be used to specify a\n    * particular unit of allocation. Values for {@code ovf:capacityAllocationUnits} shall match the\n    * format for programmatic units defined in DSP0004.\n    */\n   public String getCapacityAllocationUnits() {\n      return capacityAllocationUnits;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((id == null) ? 0 : id.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      Disk other = (Disk) obj;\n      if (id == null) {\n         if (other.id != null)\n            return false;\n      } else if (!id.equals(other.id))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return String\n               .format(\n                        \"[id=%s, capacity=%s, capacityAllocationUnits=%s, fileRef=%s, format=%s, parentRef=%s, populatedSize=%s]\",\n                        id, capacity, capacityAllocationUnits, fileRef, format, parentRef, populatedSize);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public int compareTo(Disk o) {\n      if (id == null)\n         return -1;\n      return (this == o) ? 0 : id.compareTo(o.id);\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/ovf/DiskSection.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ovf;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Set;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Sets;\n\n/**\n * A DiskSection describes meta-information about virtual disks in the OVF package. Virtual disks\n * and their metadata are described outside the virtual hardware to facilitate sharing between\n * virtual machines within an OVF package.\n */\npublic class DiskSection extends Section<DiskSection> {\n\n   @SuppressWarnings(\"unchecked\")\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Builder toBuilder() {\n      return new Builder().fromDiskSection(this);\n   }\n\n   public static class Builder extends Section.Builder<DiskSection> {\n      protected Set<Disk> disks = Sets.newLinkedHashSet();\n\n      /**\n       * @see DiskSection#getDisks\n       */\n      public Builder disk(Disk disk) {\n         this.disks.add(checkNotNull(disk, \"disk\"));\n         return this;\n      }\n\n      /**\n       * @see DiskSection#getDisks\n       */\n      public Builder disks(Iterable<Disk> disks) {\n         this.disks = ImmutableSet.<Disk> copyOf(checkNotNull(disks, \"disks\"));\n         return this;\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public DiskSection build() {\n         return new DiskSection(info, disks);\n      }\n\n      public Builder fromDiskSection(DiskSection in) {\n         return disks(in.getDisks()).info(in.getInfo());\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder fromSection(Section<DiskSection> in) {\n         return (Builder) super.fromSection(in);\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder info(String info) {\n         return (Builder) super.info(info);\n      }\n\n   }\n\n   private final Set<Disk> disks;\n\n   public DiskSection(String info, Iterable<Disk> disks) {\n      super(info);\n      this.disks = ImmutableSet.<Disk> copyOf(checkNotNull(disks, \"disks\"));\n   }\n\n   /**\n    * All disks referred to from Connection elements in all {@link VirtualHardwareSection} elements\n    * shall be defined in the DiskSection.\n    * \n    * @return\n    */\n   public Set<Disk> getDisks() {\n      return disks;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((info == null) ? 0 : info.hashCode());\n      result = prime * result + ((disks == null) ? 0 : disks.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      DiskSection other = (DiskSection) obj;\n      if (info == null) {\n         if (other.info != null)\n            return false;\n      } else if (!info.equals(other.info))\n         return false;\n      if (disks == null) {\n         if (other.disks != null)\n            return false;\n      } else if (!disks.equals(other.disks))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return String.format(\"[info=%s, disks=%s]\", info, disks);\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/ovf/Envelope.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ovf;\n\nimport org.jclouds.ovf.internal.BaseEnvelope;\n\nimport com.google.common.collect.Multimap;\n\npublic class Envelope extends BaseEnvelope<VirtualSystem, Envelope> {\n\n   @SuppressWarnings(\"unchecked\")\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Builder toBuilder() {\n      return new Builder().fromEnvelope(this);\n   }\n\n   public static class Builder extends BaseEnvelope.Builder<VirtualSystem, Envelope> {\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Envelope build() {\n         return new Envelope(diskSections, networkSections, additionalSections, virtualSystem);\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @SuppressWarnings(\"unchecked\")\n      @Override\n      public Builder additionalSection(String name, Section additionalSection) {\n         return Builder.class.cast(super.additionalSection(name, additionalSection));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @SuppressWarnings(\"unchecked\")\n      @Override\n      public Builder additionalSections(Multimap<String, Section> additionalSections) {\n         return Builder.class.cast(super.additionalSections(additionalSections));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder diskSection(DiskSection diskSection) {\n         return Builder.class.cast(super.diskSection(diskSection));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder diskSections(Iterable<? extends DiskSection> diskSections) {\n         return Builder.class.cast(super.diskSections(diskSections));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder fromEnvelope(BaseEnvelope<VirtualSystem, Envelope> in) {\n         return Builder.class.cast(super.fromEnvelope(in));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder networkSection(NetworkSection networkSection) {\n         return Builder.class.cast(super.networkSection(networkSection));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder networkSections(Iterable<? extends NetworkSection> networkSections) {\n         return Builder.class.cast(super.networkSections(networkSections));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder virtualSystem(VirtualSystem virtualSystem) {\n         return Builder.class.cast(super.virtualSystem(virtualSystem));\n      }\n\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   public Envelope(Iterable<? extends DiskSection> diskSections, Iterable<? extends NetworkSection> networkSections,\n            Multimap<String, Section> additionalSections, VirtualSystem virtualSystem) {\n      super(diskSections, networkSections, additionalSections, virtualSystem);\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/ovf/Network.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ovf;\n\n\npublic class Network {\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n      protected String name;\n      protected String description;\n\n      /**\n       * @see Network#getName\n       */\n      public Builder name(String name) {\n         this.name = name;\n         return this;\n      }\n\n      /**\n       * @see Section#getDescription\n       */\n      public Builder description(String description) {\n         this.description = description;\n         return this;\n      }\n\n      public Network build() {\n         return new Network(name, description);\n      }\n\n      public Builder fromNetwork(Network in) {\n         return name(in.getName()).description(in.getDescription());\n      }\n   }\n\n   private final String name;\n   private final String description;\n\n   public Network(String name, String description) {\n      this.name = name;\n      this.description = description;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((description == null) ? 0 : description.hashCode());\n      result = prime * result + ((name == null) ? 0 : name.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      Network other = (Network) obj;\n      if (description == null) {\n         if (other.description != null)\n            return false;\n      } else if (!description.equals(other.description))\n         return false;\n      if (name == null) {\n         if (other.name != null)\n            return false;\n      } else if (!name.equals(other.name))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"[name=\" + name + \", description=\" + description + \"]\";\n   }\n\n   public String getName() {\n      return name;\n   }\n\n   public String getDescription() {\n      return description;\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/ovf/NetworkSection.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ovf;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Set;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Sets;\n\n/**\n * The NetworkSection element shall list all logical networks used in the OVF package.\n */\npublic class NetworkSection extends Section<NetworkSection> {\n\n   @SuppressWarnings(\"unchecked\")\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Builder toBuilder() {\n      return builder().fromNetworkSection(this);\n   }\n\n   public static class Builder extends Section.Builder<NetworkSection> {\n      protected Set<Network> networks = Sets.newLinkedHashSet();\n\n      /**\n       * @see NetworkSection#getNetworks\n       */\n      public Builder network(Network network) {\n         this.networks.add(checkNotNull(network, \"network\"));\n         return this;\n      }\n\n      /**\n       * @see NetworkSection#getNetworks\n       */\n      public Builder networks(Iterable<Network> networks) {\n         this.networks = ImmutableSet.<Network> copyOf(checkNotNull(networks, \"networks\"));\n         return this;\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public NetworkSection build() {\n         return new NetworkSection(info, networks);\n      }\n\n      public Builder fromNetworkSection(NetworkSection in) {\n         return networks(in.getNetworks()).info(in.getInfo());\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder fromSection(Section<NetworkSection> in) {\n         return Builder.class.cast(super.fromSection(in));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder info(String info) {\n         return Builder.class.cast(super.info(info));\n      }\n\n   }\n\n   private final Set<Network> networks;\n\n   public NetworkSection(String info, Iterable<Network> networks) {\n      super(info);\n      this.networks = ImmutableSet.<Network> copyOf(checkNotNull(networks, \"networks\"));\n   }\n\n   /**\n    * All networks referred to from Connection elements in all {@link VirtualHardwareSection}\n    * elements shall be defined in the NetworkSection.\n    * \n    * @return\n    */\n   public Set<Network> getNetworks() {\n      return networks;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((info == null) ? 0 : info.hashCode());\n      result = prime * result + ((networks == null) ? 0 : networks.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      NetworkSection other = (NetworkSection) obj;\n      if (info == null) {\n         if (other.info != null)\n            return false;\n      } else if (!info.equals(other.info))\n         return false;\n      if (networks == null) {\n         if (other.networks != null)\n            return false;\n      } else if (!networks.equals(other.networks))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return String.format(\"[info=%s, networks=%s]\", info, networks);\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/ovf/OperatingSystemSection.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ovf;\n\nimport org.jclouds.javax.annotation.Nullable;\n\n/**\n * An OperatingSystemSection specifies the operating system installed on a virtual machine.\n */\npublic class OperatingSystemSection extends Section<OperatingSystemSection> {\n\n   @SuppressWarnings(\"unchecked\")\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Builder toBuilder() {\n      return builder().fromOperatingSystemSection(this);\n   }\n\n   public static class Builder extends Section.Builder<OperatingSystemSection> {\n      protected Integer id;\n      protected String description;\n\n      /**\n       * @see OperatingSystemSection#getID\n       */\n      public Builder id(Integer id) {\n         this.id = id;\n         return this;\n      }\n\n      /**\n       * @see OperatingSystemSection#getDescription\n       */\n      public Builder description(String description) {\n         this.description = description;\n         return this;\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public OperatingSystemSection build() {\n         return new OperatingSystemSection(id, info, description);\n      }\n\n      public Builder fromOperatingSystemSection(OperatingSystemSection in) {\n         return id(in.getId()).info(in.getInfo()).description(in.getDescription());\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder fromSection(Section<OperatingSystemSection> in) {\n         return Builder.class.cast(super.fromSection(in));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder info(String info) {\n         return Builder.class.cast(super.info(info));\n      }\n\n   }\n\n   protected final Integer id;\n   protected final String description;\n\n   public OperatingSystemSection(@Nullable Integer id, @Nullable String info, @Nullable String description) {\n      super(info);\n      this.id = id;\n      this.description = description;\n   }\n\n   /**\n    * \n    * @return ovf id\n    * @see OSType#getCode()\n    */\n   public Integer getId() {\n      return id;\n   }\n\n   /**\n    * \n    * @return description or null\n    */\n   public String getDescription() {\n      return description;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((description == null) ? 0 : description.hashCode());\n      result = prime * result + ((id == null) ? 0 : id.hashCode());\n      result = prime * result + ((info == null) ? 0 : info.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      OperatingSystemSection other = (OperatingSystemSection) obj;\n      if (description == null) {\n         if (other.description != null)\n            return false;\n      } else if (!description.equals(other.description))\n         return false;\n      if (id == null) {\n         if (other.id != null)\n            return false;\n      } else if (!id.equals(other.id))\n         return false;\n      if (info == null) {\n         if (other.info != null)\n            return false;\n      } else if (!info.equals(other.info))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return String.format(\"[info=%s, id=%s, description=%s]\", info, id, description);\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/ovf/ProductSection.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ovf;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Set;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Sets;\n\n/**\n * The ProductSection element specifies product-information for an appliance, such as product name,\n * version, and vendor.\n */\npublic class ProductSection extends Section<ProductSection> {\n\n   @SuppressWarnings(\"unchecked\")\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Builder toBuilder() {\n      return builder().fromDeploymentOptionSection(this);\n   }\n\n   public static class Builder extends Section.Builder<ProductSection> {\n      protected Set<Property> properties = Sets.newLinkedHashSet();\n\n      /**\n       * @see ProductSection#getPropertys\n       */\n      public Builder property(Property property) {\n         this.properties.add(checkNotNull(property, \"property\"));\n         return this;\n      }\n\n      /**\n       * @see ProductSection#getPropertys\n       */\n      public Builder properties(Iterable<Property> properties) {\n         this.properties = ImmutableSet.<Property> copyOf(checkNotNull(properties, \"properties\"));\n         return this;\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public ProductSection build() {\n         return new ProductSection(info, properties);\n      }\n\n      public Builder fromDeploymentOptionSection(ProductSection in) {\n         return info(in.getInfo()).properties(in.getProperties());\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder fromSection(Section<ProductSection> in) {\n         return Builder.class.cast(super.fromSection(in));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder info(String info) {\n         return Builder.class.cast(super.info(info));\n      }\n\n   }\n\n   protected final Set<Property> properties;\n\n   public ProductSection(String info, Iterable<Property> properties) {\n      super(info);\n      this.properties = ImmutableSet.<Property> copyOf(checkNotNull(properties, \"properties\"));\n\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = super.hashCode();\n      result = prime * result + ((properties == null) ? 0 : properties.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (!super.equals(obj))\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      ProductSection other = (ProductSection) obj;\n      if (properties == null) {\n         if (other.properties != null)\n            return false;\n      } else if (!properties.equals(other.properties))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return String.format(\"[info=%s, properties=%s]\", info, properties);\n   }\n\n   public Set<Property> getProperties() {\n      return properties;\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/ovf/Property.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ovf;\n\npublic class Property {\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n      protected String key;\n      protected String value;\n      protected String label;\n      protected String description;\n\n      /**\n       * @see Property#getKey\n       */\n      public Builder key(String key) {\n         this.key = key;\n         return this;\n      }\n\n      /**\n       * @see Property#getValue\n       */\n      public Builder value(String value) {\n         this.value = value;\n         return this;\n      }\n\n      /**\n       * @see Section#getLabel\n       */\n      public Builder label(String label) {\n         this.label = label;\n         return this;\n      }\n\n      /**\n       * @see Section#getDescription\n       */\n      public Builder description(String description) {\n         this.description = description;\n         return this;\n      }\n\n      public Property build() {\n         return new Property(key, value, label, description);\n      }\n\n      public Builder fromProperty(Property in) {\n         return key(in.getKey()).value(in.getValue()).description(in.getDescription()).label(in.getLabel());\n      }\n   }\n\n   private final String key;\n   private final String value;\n   private final String label;\n   private final String description;\n\n   public Property(String key, String value, String label, String description) {\n      this.key = key;\n      this.value = value;\n      this.label = label;\n      this.description = description;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((key == null) ? 0 : key.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      Property other = (Property) obj;\n      if (key == null) {\n         if (other.key != null)\n            return false;\n      } else if (!key.equals(other.key))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return String.format(\"[key=%s, value=%s, label=%s, description=%s]\", key, value, label, description);\n   }\n\n   public String getKey() {\n      return key;\n   }\n\n   public String getDescription() {\n      return description;\n   }\n\n   public String getLabel() {\n      return label;\n   }\n\n   public String getValue() {\n      return value;\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/ovf/Section.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ovf;\n\nimport org.jclouds.javax.annotation.Nullable;\n\n/**\n * Metadata about a virtual machine or grouping of them\n */\npublic class Section<T extends Section<T>> {\n\n   public static <T extends Section<T>> Builder<T> builder() {\n      return new Builder<T>();\n   }\n\n   public Builder<T> toBuilder() {\n      return new Builder<T>().fromSection(this);\n   }\n\n   public static class Builder<T extends Section<T>> {\n      protected String info;\n\n      /**\n       * @see Section#getInfo\n       */\n      public Builder<T> info(String info) {\n         this.info = info;\n         return this;\n      }\n\n      public Section<T> build() {\n         return new Section<T>(info);\n      }\n\n      public Builder<T> fromSection(Section<T> in) {\n         return info(in.getInfo());\n      }\n   }\n\n   protected final String info;\n\n   public Section(@Nullable String info) {\n      this.info = info;\n   }\n\n   /**\n    * \n    * @return ovf info\n    */\n   public String getInfo() {\n      return info;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((info == null) ? 0 : info.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      Section<?> other = (Section<?>) obj;\n      if (info == null) {\n         if (other.info != null)\n            return false;\n      } else if (!info.equals(other.info))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"[info=\" + getInfo() + \"]\";\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/ovf/VirtualHardwareSection.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ovf;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Set;\n\nimport org.jclouds.cim.ResourceAllocationSettingData;\nimport org.jclouds.cim.VirtualSystemSettingData;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Sets;\n\n/**\n * The virtual hardware required by a virtual machine is specified in VirtualHardwareSection.\n * <p/>\n * This specification supports abstract or incomplete hardware descriptions in which only the major\n * devices are described. The hypervisor is allowed to create additional virtual hardware\n * controllers and devices, as long as the required devices listed in the descriptor are realized.\n */\npublic class VirtualHardwareSection extends Section<VirtualHardwareSection> {\n\n   @SuppressWarnings(\"unchecked\")\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Builder toBuilder() {\n      return builder().fromVirtualHardwareSection(this);\n   }\n\n   public static class Builder extends Section.Builder<VirtualHardwareSection> {\n      protected VirtualSystemSettingData virtualSystem;\n      protected Set<String> transports = Sets.newLinkedHashSet();\n      protected Set<ResourceAllocationSettingData> items = Sets.newLinkedHashSet();\n\n      /**\n       * @see VirtualHardwareSection#getSystem\n       */\n      public Builder system(VirtualSystemSettingData virtualSystem) {\n         this.virtualSystem = virtualSystem;\n         return this;\n      }\n\n      /**\n       * @see VirtualHardwareSection#getTransports\n       */\n      public Builder transport(String transport) {\n         this.transports.add(checkNotNull(transport, \"transport\"));\n         return this;\n      }\n\n      /**\n       * @see VirtualHardwareSection#getTransports\n       */\n      public Builder transports(Iterable<String> transports) {\n         this.transports = ImmutableSet.<String> copyOf(checkNotNull(transports, \"transports\"));\n         return this;\n      }\n\n      /**\n       * @see VirtualHardwareSection#getItems\n       */\n      public Builder item(ResourceAllocationSettingData item) {\n         this.items.add(checkNotNull(item, \"item\"));\n         return this;\n      }\n\n      /**\n       * @see VirtualHardwareSection#getItems\n       */\n      public Builder items(Iterable<? extends ResourceAllocationSettingData> items) {\n         this.items = ImmutableSet.<ResourceAllocationSettingData> copyOf(checkNotNull(\n                  items, \"items\"));\n         return this;\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public VirtualHardwareSection build() {\n         return new VirtualHardwareSection(info, transports, virtualSystem, items);\n      }\n\n      public Builder fromVirtualHardwareSection(VirtualHardwareSection in) {\n         return fromSection(in).items(in.getItems()).transports(in.getTransports()).system(\n                  in.getSystem()).info(in.getInfo());\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder fromSection(Section<VirtualHardwareSection> in) {\n         return Builder.class.cast(super.fromSection(in));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder info(String info) {\n         return Builder.class.cast(super.info(info));\n      }\n\n   }\n\n   protected final VirtualSystemSettingData virtualSystem;\n   protected final Set<String> transports;\n   protected final Set<ResourceAllocationSettingData> items;\n\n   public VirtualHardwareSection(String info, Iterable<String> transports, VirtualSystemSettingData virtualSystem,\n            Iterable<? extends ResourceAllocationSettingData> items) {\n      super(info);\n      this.virtualSystem = virtualSystem;\n      this.transports = ImmutableSet.<String> copyOf(checkNotNull(transports, \"transports\"));\n      this.items = ImmutableSet.<ResourceAllocationSettingData> copyOf(checkNotNull(items,\n               \"items\"));\n   }\n\n   /**\n    * transport types define methods by which the environment document is communicated from the\n    * deployment platform to the guest software.\n    * <p/>\n    * To enable interoperability, this specification defines an \"iso\" transport type which all\n    * implementations that support CD-ROM devices are required to support. The iso transport\n    * communicates the environment 1346 document by making a dynamically generated ISO image\n    * available to the guest software. To support the iso transport type, prior to booting a virtual\n    * machine, an implementation shall make an ISO 9660 read-only disk image available as backing\n    * for a disconnected CD-ROM. If the iso transport is selected for a VirtualHardwareSection, at\n    * least one disconnected CD-ROM device shall be present in this section.\n    * <p/>\n    * Support for the \"iso\" transport type is not a requirement for virtual hardware architectures\n    * or guest 1351 operating systems which do not have CD-ROM device support.\n    * \n    * @return\n    */\n   public Set<String> getTransports() {\n      return transports;\n   }\n\n   public VirtualSystemSettingData getSystem() {\n      return virtualSystem;\n   }\n\n   public Set<? extends ResourceAllocationSettingData> getItems() {\n      return items;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = super.hashCode();\n      result = prime * result + ((items == null) ? 0 : items.hashCode());\n      result = prime * result + ((transports == null) ? 0 : transports.hashCode());\n      result = prime * result + ((virtualSystem == null) ? 0 : virtualSystem.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (!super.equals(obj))\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      VirtualHardwareSection other = (VirtualHardwareSection) obj;\n      if (items == null) {\n         if (other.items != null)\n            return false;\n      } else if (!items.equals(other.items))\n         return false;\n      if (transports == null) {\n         if (other.transports != null)\n            return false;\n      } else if (!transports.equals(other.transports))\n         return false;\n      if (virtualSystem == null) {\n         if (other.virtualSystem != null)\n            return false;\n      } else if (!virtualSystem.equals(other.virtualSystem))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return String.format(\"[info=%s, items=%s, transports=%s, virtualSystem=%s]\", info,\n               items, transports, virtualSystem);\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/ovf/VirtualSystem.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ovf;\n\nimport org.jclouds.ovf.internal.BaseVirtualSystem;\n\nimport com.google.common.collect.Multimap;\n\npublic class VirtualSystem extends BaseVirtualSystem<VirtualSystem> {\n\n   public static class Builder extends BaseVirtualSystem.Builder<VirtualSystem> {\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public VirtualSystem build() {\n         return new VirtualSystem(id, info, name, operatingSystem, virtualHardwareSections, productSections,\n                  additionalSections);\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @SuppressWarnings(\"unchecked\")\n      @Override\n      public Builder additionalSection(String name, Section additionalSection) {\n         return Builder.class.cast(super.additionalSection(name, additionalSection));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @SuppressWarnings(\"unchecked\")\n      @Override\n      public Builder additionalSections(Multimap<String, Section> additionalSections) {\n         return Builder.class.cast(super.additionalSections(additionalSections));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder fromSection(Section<VirtualSystem> in) {\n         return Builder.class.cast(super.fromSection(in));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder fromVirtualSystem(BaseVirtualSystem<VirtualSystem> in) {\n         return Builder.class.cast(super.fromVirtualSystem(in));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder virtualHardwareSection(VirtualHardwareSection virtualHardwareSection) {\n         return Builder.class.cast(super.virtualHardwareSection(virtualHardwareSection));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder virtualHardwareSections(Iterable<? extends VirtualHardwareSection> virtualHardwareSections) {\n         return Builder.class.cast(super.virtualHardwareSections(virtualHardwareSections));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder id(String id) {\n         return Builder.class.cast(super.id(id));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder info(String info) {\n         return Builder.class.cast(super.info(info));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder name(String name) {\n         return Builder.class.cast(super.name(name));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder operatingSystemSection(OperatingSystemSection operatingSystem) {\n         return Builder.class.cast(super.operatingSystemSection(operatingSystem));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder productSection(ProductSection productSection) {\n         return Builder.class.cast(super.productSection(productSection));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder productSections(Iterable<? extends ProductSection> productSections) {\n         return Builder.class.cast(super.productSections(productSections));\n      }\n\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   public VirtualSystem(String id, String info, String name, OperatingSystemSection operatingSystem,\n            Iterable<? extends VirtualHardwareSection> virtualHardwareSections,\n            Iterable<? extends ProductSection> productSections, Multimap<String, Section> additionalSections) {\n      super(id, info, name, operatingSystem, virtualHardwareSections, productSections, additionalSections);\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/ovf/internal/BaseEnvelope.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ovf.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Set;\n\nimport org.jclouds.ovf.DiskSection;\nimport org.jclouds.ovf.NetworkSection;\nimport org.jclouds.ovf.Section;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.LinkedHashMultimap;\nimport com.google.common.collect.Multimap;\nimport com.google.common.collect.Sets;\n\npublic class BaseEnvelope<V extends BaseVirtualSystem<V>, E extends BaseEnvelope<V, E>> {\n\n   public static <V extends BaseVirtualSystem<V>, E extends BaseEnvelope<V, E>> Builder<V, E> builder() {\n      return new Builder<V, E>();\n   }\n\n   public Builder<V, E> toBuilder() {\n      return new Builder<V, E>().fromEnvelope(this);\n   }\n\n   public static class Builder<V extends BaseVirtualSystem<V>, E extends BaseEnvelope<V, E>> {\n      protected Set<DiskSection> diskSections = Sets.newLinkedHashSet();\n      protected Set<NetworkSection> networkSections = Sets.newLinkedHashSet();\n      @SuppressWarnings(\"unchecked\")\n      protected Multimap<String, Section> additionalSections = LinkedHashMultimap.create();\n      protected V virtualSystem;\n\n      /**\n       * @see BaseEnvelope#getDiskSections\n       */\n      public Builder<V, E> diskSection(DiskSection diskSection) {\n         this.diskSections.add(checkNotNull(diskSection, \"diskSection\"));\n         return this;\n      }\n\n      /**\n       * @see BaseEnvelope#getDiskSections\n       */\n      public Builder<V, E> diskSections(Iterable<? extends DiskSection> diskSections) {\n         this.diskSections = ImmutableSet.<DiskSection> copyOf(checkNotNull(diskSections, \"diskSections\"));\n         return this;\n      }\n\n      /**\n       * @see BaseEnvelope#getNetworkSections\n       */\n      public Builder<V, E> networkSection(NetworkSection networkSection) {\n         this.networkSections.add(checkNotNull(networkSection, \"networkSection\"));\n         return this;\n      }\n\n      /**\n       * @see BaseEnvelope#getNetworkSections\n       */\n      public Builder<V, E> networkSections(Iterable<? extends NetworkSection> networkSections) {\n         this.networkSections = ImmutableSet.<NetworkSection> copyOf(checkNotNull(networkSections, \"networkSections\"));\n         return this;\n      }\n\n      /**\n       * @see BaseEnvelope#getAdditionalSections\n       */\n      @SuppressWarnings(\"unchecked\")\n      public Builder<V, E> additionalSection(String name, Section additionalSection) {\n         this.additionalSections.put(checkNotNull(name, \"name\"), checkNotNull(additionalSection, \"additionalSection\"));\n         return this;\n      }\n\n      /**\n       * @see BaseEnvelope#getAdditionalSections\n       */\n      @SuppressWarnings(\"unchecked\")\n      public Builder<V, E> additionalSections(Multimap<String, Section> additionalSections) {\n         this.additionalSections = ImmutableMultimap.<String, Section> copyOf(checkNotNull(additionalSections,\n                  \"additionalSections\"));\n         return this;\n      }\n\n      /**\n       * @see BaseEnvelope#getVirtualSystem\n       */\n      public Builder<V, E> virtualSystem(V virtualSystem) {\n         this.virtualSystem = virtualSystem;\n         return this;\n      }\n\n      @SuppressWarnings(\"unchecked\")\n      public E build() {\n         return (E) new BaseEnvelope<V, E>(diskSections, networkSections, additionalSections, virtualSystem);\n      }\n\n      public Builder<V, E> fromEnvelope(BaseEnvelope<V, E> in) {\n         return virtualSystem(in.getVirtualSystem()).diskSections(in.getDiskSections())\n                  .networkSections(networkSections).additionalSections(in.getAdditionalSections());\n      }\n\n   }\n\n   private final Set<? extends DiskSection> diskSections;\n   private final Set<? extends NetworkSection> networkSections;\n   @SuppressWarnings(\"unchecked\")\n   private final Multimap<String, Section> additionalSections;\n   private final V virtualSystem;\n\n   @SuppressWarnings(\"unchecked\")\n   public BaseEnvelope(Iterable<? extends DiskSection> diskSections, Iterable<? extends NetworkSection> networkSections,\n            Multimap<String, Section> additionalSections, V virtualSystem) {\n      this.diskSections = ImmutableSet.copyOf(checkNotNull(diskSections, \"diskSections\"));\n      this.networkSections = ImmutableSet.copyOf(checkNotNull(networkSections, \"networkSections\"));\n      this.additionalSections = ImmutableMultimap.copyOf(checkNotNull(additionalSections, \"additionalSections\"));\n      this.virtualSystem = checkNotNull(virtualSystem, \"virtualSystem\");\n   }\n\n   public V getVirtualSystem() {\n      return virtualSystem;\n   }\n\n   public Set<? extends DiskSection> getDiskSections() {\n      return diskSections;\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   public Multimap<String, Section> getAdditionalSections() {\n      return additionalSections;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((additionalSections == null) ? 0 : additionalSections.hashCode());\n      result = prime * result + ((diskSections == null) ? 0 : diskSections.hashCode());\n      result = prime * result + ((networkSections == null) ? 0 : networkSections.hashCode());\n      result = prime * result + ((virtualSystem == null) ? 0 : virtualSystem.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      BaseEnvelope<?, ?> other = (BaseEnvelope<?, ?>) obj;\n      if (additionalSections == null) {\n         if (other.additionalSections != null)\n            return false;\n      } else if (!additionalSections.equals(other.additionalSections))\n         return false;\n      if (diskSections == null) {\n         if (other.diskSections != null)\n            return false;\n      } else if (!diskSections.equals(other.diskSections))\n         return false;\n      if (networkSections == null) {\n         if (other.networkSections != null)\n            return false;\n      } else if (!networkSections.equals(other.networkSections))\n         return false;\n      if (virtualSystem == null) {\n         if (other.virtualSystem != null)\n            return false;\n      } else if (!virtualSystem.equals(other.virtualSystem))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return String.format(\"[diskSections=%s, networkSections=%s, additionalSections=%s, virtualSystem=%s]\",\n               diskSections, networkSections, additionalSections, virtualSystem);\n   }\n\n   public Set<? extends NetworkSection> getNetworkSections() {\n      return networkSections;\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/ovf/internal/BaseVirtualSystem.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ovf.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Set;\n\nimport org.jclouds.ovf.OperatingSystemSection;\nimport org.jclouds.ovf.ProductSection;\nimport org.jclouds.ovf.Section;\nimport org.jclouds.ovf.VirtualHardwareSection;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.LinkedHashMultimap;\nimport com.google.common.collect.Multimap;\nimport com.google.common.collect.Sets;\n\npublic class BaseVirtualSystem<T extends BaseVirtualSystem<T>> extends Section<T> {\n\n   @SuppressWarnings(\"unchecked\")\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Builder<T> toBuilder() {\n      return new Builder<T>().fromVirtualSystem(this);\n   }\n\n   public static class Builder<T extends BaseVirtualSystem<T>> extends Section.Builder<T> {\n      protected String id;\n      protected String name;\n      protected OperatingSystemSection operatingSystem;\n      protected Set<VirtualHardwareSection> virtualHardwareSections = Sets.newLinkedHashSet();\n      protected Set<ProductSection> productSections = Sets.newLinkedHashSet();\n      @SuppressWarnings(\"unchecked\")\n      protected Multimap<String, Section> additionalSections = LinkedHashMultimap.create();\n\n      /**\n       * @see BaseVirtualSystem#getName\n       */\n      public Builder<T> name(String name) {\n         this.name = name;\n         return this;\n      }\n\n      /**\n       * @see BaseVirtualSystem#getId\n       */\n      public Builder<T> id(String id) {\n         this.id = id;\n         return this;\n      }\n\n      /**\n       * @see BaseVirtualSystem#getOperatingSystemSection\n       */\n      public Builder<T> operatingSystemSection(OperatingSystemSection operatingSystem) {\n         this.operatingSystem = operatingSystem;\n         return this;\n      }\n\n      /**\n       * @see BaseVirtualSystem#getVirtualHardwareSections\n       */\n      public Builder<T> virtualHardwareSection(VirtualHardwareSection virtualHardwareSection) {\n         this.virtualHardwareSections.add(checkNotNull(virtualHardwareSection, \"virtualHardwareSection\"));\n         return this;\n      }\n\n      /**\n       * @see BaseVirtualSystem#getVirtualHardwareSections\n       */\n      public Builder<T> virtualHardwareSections(Iterable<? extends VirtualHardwareSection> virtualHardwareSections) {\n         this.virtualHardwareSections = ImmutableSet.<VirtualHardwareSection> copyOf(checkNotNull(virtualHardwareSections,\n                  \"virtualHardwareSections\"));\n         return this;\n      }\n\n      /**\n       * @see BaseVirtualSystem#getProductSections\n       */\n      public Builder<T> productSection(ProductSection productSection) {\n         this.productSections.add(checkNotNull(productSection, \"productSection\"));\n         return this;\n      }\n\n      /**\n       * @see BaseVirtualSystem#getProductSections\n       */\n      public Builder<T> productSections(Iterable<? extends ProductSection> productSections) {\n         this.productSections = ImmutableSet.<ProductSection> copyOf(checkNotNull(productSections, \"productSections\"));\n         return this;\n      }\n\n      /**\n       * @see BaseVirtualSystem#getAdditionalSections\n       */\n      @SuppressWarnings(\"unchecked\")\n      public Builder<T> additionalSection(String name, Section additionalSection) {\n         this.additionalSections.put(checkNotNull(name, \"name\"), checkNotNull(additionalSection, \"additionalSection\"));\n         return this;\n      }\n\n      /**\n       * @see BaseVirtualSystem#getAdditionalSections\n       */\n      @SuppressWarnings(\"unchecked\")\n      public Builder<T> additionalSections(Multimap<String, Section> additionalSections) {\n         this.additionalSections = ImmutableMultimap.<String, Section> copyOf(checkNotNull(additionalSections,\n                  \"additionalSections\"));\n         return this;\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public BaseVirtualSystem<T> build() {\n         return new BaseVirtualSystem<T>(id, info, name, operatingSystem, virtualHardwareSections, productSections,\n                  additionalSections);\n      }\n\n      public Builder<T> fromVirtualSystem(BaseVirtualSystem<T> in) {\n         return fromSection(in).id(in.getId()).name(in.getName())\n                  .operatingSystemSection(in.getOperatingSystemSection()).virtualHardwareSections(\n                           in.getVirtualHardwareSections()).productSections(in.getProductSections())\n                  .additionalSections(in.getAdditionalSections());\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder<T> fromSection(Section<T> in) {\n         return (Builder<T>) super.fromSection(in);\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder<T> info(String info) {\n         return (Builder<T>) super.info(info);\n      }\n\n   }\n\n   protected final String id;\n   protected final String name;\n   protected final OperatingSystemSection operatingSystem;\n   protected final Set<? extends VirtualHardwareSection> virtualHardwareSections;\n   protected final Set<? extends ProductSection> productSections;\n   @SuppressWarnings(\"unchecked\")\n   protected final Multimap<String, Section> additionalSections;\n\n   @SuppressWarnings(\"unchecked\")\n   public BaseVirtualSystem(String id, String info, String name, OperatingSystemSection operatingSystem,\n            Iterable<? extends VirtualHardwareSection> virtualHardwareSections,\n            Iterable<? extends ProductSection> productSections, Multimap<String, Section> additionalSections) {\n      super(info);\n      this.id = id;\n      this.name = name;\n      this.operatingSystem = checkNotNull(operatingSystem, \"operatingSystem\");\n      this.virtualHardwareSections = ImmutableSet.copyOf(checkNotNull(virtualHardwareSections, \"virtualHardwareSections\"));\n      this.productSections = ImmutableSet.copyOf(checkNotNull(productSections, \"productSections\"));\n      this.additionalSections = ImmutableMultimap.copyOf(checkNotNull(additionalSections, \"additionalSections\"));\n   }\n\n   public String getId() {\n      return id;\n   }\n\n   public String getName() {\n      return name;\n   }\n\n   public OperatingSystemSection getOperatingSystemSection() {\n      return operatingSystem;\n   }\n\n   /**\n    * Each VirtualSystem element may contain one or more VirtualHardwareSection elements, each of\n    * which describes the virtual virtualHardwareSections required by the virtual system.\n    */\n   public Set<? extends VirtualHardwareSection> getVirtualHardwareSections() {\n      return virtualHardwareSections;\n   }\n\n   /**\n    * Specifies product-information for a package, such as product name and version, along with a\n    * set of properties that can be configured\n    */\n   public Set<? extends ProductSection> getProductSections() {\n      return productSections;\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   public Multimap<String, Section> getAdditionalSections() {\n      return additionalSections;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((id == null) ? 0 : id.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      BaseVirtualSystem<?> other = (BaseVirtualSystem<?>) obj;\n      if (id == null) {\n         if (other.id != null)\n            return false;\n      } else if (!id.equals(other.id))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return String\n               .format(\n                        \"[id=%s, name=%s, info=%s, operatingSystem=%s, virtualHardwareSections=%s,  productSections=%s, additionalSections=%s]\",\n                        id, name, info, operatingSystem, virtualHardwareSections, productSections, additionalSections);\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/ovf/xml/DeploymentOptionSectionHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ovf.xml;\n\nimport static org.jclouds.util.SaxUtils.currentOrNull;\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Provider;\n\nimport org.jclouds.ovf.Configuration;\nimport org.jclouds.ovf.DeploymentOptionSection;\nimport org.jclouds.util.SaxUtils;\nimport org.xml.sax.Attributes;\n\npublic class DeploymentOptionSectionHandler extends\n         SectionHandler<DeploymentOptionSection, DeploymentOptionSection.Builder> {\n   protected Configuration.Builder configBuilder = Configuration.builder();\n\n   @Inject\n   public DeploymentOptionSectionHandler(Provider<DeploymentOptionSection.Builder> builderProvider) {\n      super(builderProvider);\n   }\n\n   public void startElement(String uri, String localName, String qName, Attributes attrs) {\n      Map<String, String> attributes = SaxUtils.cleanseAttributes(attrs);\n      if (equalsOrSuffix(qName, \"Configuration\")) {\n         configBuilder.id(attributes.get(\"id\"));\n         // TODO default;\n      }\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) {\n      if (equalsOrSuffix(qName, \"Info\")) {\n         builder.info(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"Label\")) {\n         configBuilder.label(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"Description\")) {\n         configBuilder.description(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"Configuration\")) {\n         try {\n            builder.configuration(configBuilder.build());\n         } finally {\n            configBuilder = Configuration.builder();\n         }\n      }\n      super.endElement(uri, localName, qName);\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/ovf/xml/DiskSectionHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ovf.xml;\n\nimport static org.jclouds.util.SaxUtils.currentOrNull;\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport java.net.URI;\nimport java.util.Map;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Provider;\n\nimport org.jclouds.logging.Logger;\nimport org.jclouds.ovf.Disk;\nimport org.jclouds.ovf.DiskSection;\nimport org.jclouds.util.SaxUtils;\nimport org.xml.sax.Attributes;\n\npublic class DiskSectionHandler extends SectionHandler<DiskSection, DiskSection.Builder> {\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n   protected Disk.Builder diskBuilder = Disk.builder();\n\n   @Inject\n   public DiskSectionHandler(Provider<DiskSection.Builder> builderProvider) {\n      super(builderProvider);\n   }\n\n   public void startElement(String uri, String localName, String qName, Attributes attrs) {\n      Map<String, String> attributes = SaxUtils.cleanseAttributes(attrs);\n      if (equalsOrSuffix(qName, \"Disk\")) {\n         diskBuilder.id(attributes.get(\"diskId\"));\n         diskBuilder.capacity(attemptToParse(attributes.get(\"capacity\"), \"capacity\", attributes.get(\"diskId\")));\n         diskBuilder.parentRef(attributes.get(\"parentRef\"));\n         diskBuilder.fileRef(attributes.get(\"fileRef\"));\n         if (attributes.containsKey(\"format\"))\n            diskBuilder.format(URI.create(attributes.get(\"format\")));\n         diskBuilder.populatedSize(attemptToParse(attributes.get(\"populatedSize\"), \"populatedSize\", attributes\n                  .get(\"diskId\")));\n         diskBuilder.capacityAllocationUnits(attributes.get(\"capacityAllocationUnits\"));\n      }\n   }\n\n   private Long attemptToParse(String toParse, String key, String diskId) {\n      Long val = null;\n      if (toParse != null) {\n         try {\n            val = Long.valueOf(toParse);\n         } catch (NumberFormatException e) {\n            logger.warn(\"%s for disk %s not a number [%s]\", key, diskId, toParse);\n         }\n      }\n      return val;\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) {\n      if (equalsOrSuffix(qName, \"Info\")) {\n         builder.info(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"Disk\")) {\n         try {\n            builder.disk(diskBuilder.build());\n         } finally {\n            diskBuilder = Disk.builder();\n         }\n      }\n      super.endElement(uri, localName, qName);\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/ovf/xml/EnvelopeHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ovf.xml;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Provider;\n\nimport org.jclouds.ovf.Envelope;\nimport org.jclouds.ovf.VirtualSystem;\nimport org.jclouds.ovf.Envelope.Builder;\nimport org.jclouds.ovf.xml.internal.BaseEnvelopeHandler;\n\npublic class EnvelopeHandler extends\n         BaseEnvelopeHandler<VirtualSystem, VirtualSystem.Builder, VirtualSystemHandler, Envelope, Envelope.Builder> {\n\n   @Inject\n   public EnvelopeHandler(DiskSectionHandler diskHandler, NetworkSectionHandler networkHandler,\n            VirtualSystemHandler virtualSystemHandler, Provider<Builder> envelopeBuilderProvider) {\n      super(diskHandler, networkHandler, virtualSystemHandler, envelopeBuilderProvider);\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/ovf/xml/NetworkSectionHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ovf.xml;\n\nimport static org.jclouds.util.SaxUtils.currentOrNull;\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Provider;\n\nimport org.jclouds.ovf.Network;\nimport org.jclouds.ovf.NetworkSection;\nimport org.jclouds.util.SaxUtils;\nimport org.xml.sax.Attributes;\n\npublic class NetworkSectionHandler extends SectionHandler<NetworkSection, NetworkSection.Builder> {\n   protected Network.Builder networkBuilder = Network.builder();\n\n   @Inject\n   public NetworkSectionHandler(Provider<NetworkSection.Builder> builderProvider) {\n      super(builderProvider);\n   }\n\n   public void startElement(String uri, String localName, String qName, Attributes attrs) {\n      Map<String, String> attributes = SaxUtils.cleanseAttributes(attrs);\n      if (equalsOrSuffix(qName, \"Network\")) {\n         networkBuilder.name(attributes.get(\"name\"));\n      }\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) {\n      if (equalsOrSuffix(qName, \"Info\")) {\n         builder.info(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"Description\")) {\n         networkBuilder.description(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"Network\")) {\n         try {\n            builder.network(networkBuilder.build());\n         } finally {\n            networkBuilder = Network.builder();\n         }\n      }\n      super.endElement(uri, localName, qName);\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/ovf/xml/OperatingSystemSectionHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ovf.xml;\n\nimport static org.jclouds.util.SaxUtils.cleanseAttributes;\nimport static org.jclouds.util.SaxUtils.currentOrNull;\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Provider;\n\nimport org.jclouds.ovf.OperatingSystemSection;\nimport org.xml.sax.Attributes;\n\npublic class OperatingSystemSectionHandler extends\n         SectionHandler<OperatingSystemSection, OperatingSystemSection.Builder> {\n   @Inject\n   public OperatingSystemSectionHandler(Provider<OperatingSystemSection.Builder> builderProvider) {\n      super(builderProvider);\n   }\n\n   @Override\n   public void startElement(String uri, String localName, String qName, Attributes attrs) {\n      Map<String, String> attributes = cleanseAttributes(attrs);\n      if (equalsOrSuffix(qName, \"OperatingSystemSection\")) {\n         if (attributes.containsKey(\"id\"))\n            builder.id(Integer.parseInt(attributes.get(\"id\")));\n      }\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) {\n      if (equalsOrSuffix(qName, \"Info\")) {\n         builder.info(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"Description\")) {\n         builder.description(currentOrNull(currentText));\n      }\n      super.endElement(uri, localName, qName);\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/ovf/xml/ProductSectionHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ovf.xml;\n\nimport static org.jclouds.util.SaxUtils.currentOrNull;\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Provider;\n\nimport org.jclouds.ovf.ProductSection;\nimport org.jclouds.ovf.Property;\nimport org.jclouds.util.SaxUtils;\nimport org.xml.sax.Attributes;\n\npublic class ProductSectionHandler extends SectionHandler<ProductSection, ProductSection.Builder> {\n   protected Property.Builder configBuilder = Property.builder();\n\n   @Inject\n   public ProductSectionHandler(Provider<ProductSection.Builder> builderProvider) {\n      super(builderProvider);\n   }\n\n   public void startElement(String uri, String localName, String qName, Attributes attrs) {\n      Map<String, String> attributes = SaxUtils.cleanseAttributes(attrs);\n      if (equalsOrSuffix(qName, \"Property\")) {\n         configBuilder.key(attributes.get(\"key\"));\n         configBuilder.value(attributes.get(\"value\"));\n      }\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) {\n      if (equalsOrSuffix(qName, \"Info\")) {\n         builder.info(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"Label\")) {\n         configBuilder.label(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"Description\")) {\n         configBuilder.description(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"Property\")) {\n         try {\n            builder.property(configBuilder.build());\n         } finally {\n            configBuilder = Property.builder();\n         }\n      }\n      super.endElement(uri, localName, qName);\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/ovf/xml/SectionHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ovf.xml;\n\nimport static org.jclouds.util.SaxUtils.currentOrNull;\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport jakarta.inject.Provider;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.ovf.Section;\nimport org.jclouds.ovf.Section.Builder;\n\npublic class SectionHandler<T extends Section<T>, B extends Section.Builder<T>> extends ParseSax.HandlerWithResult<T> {\n   @SuppressWarnings(\"unchecked\")\n   public static SectionHandler create() {\n      return new SectionHandler(new Provider<Section.Builder>() {\n\n         @Override\n         public Builder get() {\n            return new Section.Builder();\n         }\n\n      });\n   }\n\n   protected final Provider<? extends Section.Builder<T>> builderProvider;\n   protected StringBuilder currentText = new StringBuilder();\n   protected B builder;\n\n   public SectionHandler(Provider<B> builderProvider) {\n      this.builderProvider = builderProvider;\n      this.builder = builderProvider.get();\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   public T getResult() {\n      try {\n         return (T) builder.build();\n      } finally {\n         builder = (B) builderProvider.get();\n      }\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) {\n      if (equalsOrSuffix(qName, \"Info\")) {\n         builder.info(currentOrNull(currentText));\n      }\n      currentText.setLength(0);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/ovf/xml/VirtualHardwareSectionHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ovf.xml;\n\nimport static org.jclouds.util.SaxUtils.cleanseAttributes;\nimport static org.jclouds.util.SaxUtils.currentOrNull;\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Provider;\n\nimport org.jclouds.cim.xml.ResourceAllocationSettingDataHandler;\nimport org.jclouds.cim.xml.VirtualSystemSettingDataHandler;\nimport org.jclouds.ovf.VirtualHardwareSection;\nimport org.xml.sax.Attributes;\n\nimport com.google.common.base.Splitter;\n\npublic class VirtualHardwareSectionHandler extends\n         SectionHandler<VirtualHardwareSection, VirtualHardwareSection.Builder> {\n\n   private final VirtualSystemSettingDataHandler systemHandler;\n   private final ResourceAllocationSettingDataHandler allocationHandler;\n\n   @Inject\n   public VirtualHardwareSectionHandler(Provider<VirtualHardwareSection.Builder> builderProvider,\n            VirtualSystemSettingDataHandler systemHandler, ResourceAllocationSettingDataHandler allocationHandler) {\n      super(builderProvider);\n      this.systemHandler = systemHandler;\n      this.allocationHandler = allocationHandler;\n   }\n\n   private boolean inItem;\n   private boolean inSystem;\n\n   public void startElement(String uri, String localName, String qName, Attributes attrs) {\n      Map<String, String> attributes = cleanseAttributes(attrs);\n      if (equalsOrSuffix(qName, \"VirtualHardwareSection\")) {\n         if (attributes.containsKey(\"transport\"))\n            builder.transports(Splitter.on(' ').split(attributes.get(\"transport\")));\n      } else if (equalsOrSuffix(qName, \"System\")) {\n         inSystem = true;\n      } else if (!inSystem && equalsOrSuffix(qName, \"Item\")) {\n         inItem = true;\n      }\n      if (inSystem) {\n         systemHandler.startElement(uri, localName, qName, attrs);\n      } else if (inItem) {\n         allocationHandler.startElement(uri, localName, qName, attrs);\n      }\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) {\n      if (equalsOrSuffix(qName, \"System\")) {\n         inSystem = false;\n         builder.system(systemHandler.getResult());\n      } else if (equalsOrSuffix(qName, \"Item\")) {\n         inItem = false;\n         builder.item(allocationHandler.getResult());\n      }\n      if (inSystem) {\n         systemHandler.endElement(uri, localName, qName);\n      } else if (inItem) {\n         allocationHandler.endElement(uri, localName, qName);\n      } else {\n         if (equalsOrSuffix(qName, \"Info\"))\n            builder.info(currentOrNull(currentText));\n         super.endElement(uri, localName, qName);\n      }\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      if (inSystem) {\n         systemHandler.characters(ch, start, length);\n      } else if (inItem) {\n         allocationHandler.characters(ch, start, length);\n      } else {\n         super.characters(ch, start, length);\n      }\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/ovf/xml/VirtualSystemHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ovf.xml;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Provider;\n\nimport org.jclouds.ovf.VirtualSystem;\nimport org.jclouds.ovf.xml.internal.BaseVirtualSystemHandler;\n\npublic class VirtualSystemHandler extends BaseVirtualSystemHandler<VirtualSystem, VirtualSystem.Builder> {\n\n   @Inject\n   public VirtualSystemHandler(Provider<VirtualSystem.Builder> builderProvider,\n            OperatingSystemSectionHandler osHandler, VirtualHardwareSectionHandler hardwareHandler,\n            ProductSectionHandler productHandler) {\n      super(builderProvider, osHandler, hardwareHandler, productHandler);\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/ovf/xml/internal/BaseEnvelopeHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ovf.xml.internal;\n\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport java.util.Map;\n\nimport jakarta.inject.Named;\nimport jakarta.inject.Provider;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.ovf.internal.BaseEnvelope;\nimport org.jclouds.ovf.internal.BaseVirtualSystem;\nimport org.jclouds.ovf.xml.DiskSectionHandler;\nimport org.jclouds.ovf.xml.NetworkSectionHandler;\nimport org.jclouds.ovf.xml.SectionHandler;\nimport org.jclouds.util.SaxUtils;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.inject.Inject;\n\npublic class BaseEnvelopeHandler<V extends BaseVirtualSystem<V>, B extends BaseVirtualSystem.Builder<V>, H extends BaseVirtualSystemHandler<V, B>, E extends BaseEnvelope<V, E>, T extends BaseEnvelope.Builder<V, E>>\n         extends ParseSax.HandlerWithResult<E> {\n\n   public E getResult() {\n      try {\n         return builder.build();\n      } finally {\n         builder = envelopeBuilderProvider.get();\n      }\n   }\n\n   protected final H virtualSystemHandler;\n   protected final DiskSectionHandler diskHandler;\n   protected final NetworkSectionHandler networkHandler;\n   protected final Provider<T> envelopeBuilderProvider;\n   protected T builder;\n\n   @Inject\n   public BaseEnvelopeHandler(DiskSectionHandler diskHandler, NetworkSectionHandler networkHandler,\n            H virtualSystemHandler, Provider<T> envelopeBuilderProvider) {\n      this.virtualSystemHandler = virtualSystemHandler;\n      this.diskHandler = diskHandler;\n      this.networkHandler = networkHandler;\n      this.envelopeBuilderProvider = envelopeBuilderProvider;\n      this.builder = envelopeBuilderProvider.get();\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   protected SectionHandler defaultSectionHandler = SectionHandler.create();\n\n   @SuppressWarnings(\"unchecked\")\n   @Inject(optional = true)\n   @Named(\"Envelope\")\n   Map<String, Provider<? extends SectionHandler>> extensionHandlers = ImmutableMap\n            .<String, Provider<? extends SectionHandler>> of();\n\n   @SuppressWarnings(\"unchecked\")\n   protected SectionHandler extensionHandler;\n\n   protected boolean inDisk;\n   protected boolean inNetwork;\n   protected boolean inVirtualSystem;\n   protected boolean inSection;\n   protected boolean inExtensionSection;\n\n   protected int depth = 0;\n\n   public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException {\n      Map<String, String> attributes = SaxUtils.cleanseAttributes(attrs);\n      depth++;\n      if (depth == 2) {\n         if (equalsOrSuffix(qName, \"DiskSection\")) {\n            inDisk = true;\n         } else if (equalsOrSuffix(qName, \"NetworkSection\")) {\n            inNetwork = true;\n         } else if (equalsOrSuffix(qName, \"VirtualSystem\")) {\n            inVirtualSystem = true;\n         } else if (extensionHandlers.containsKey(qName) || (attributes.containsKey(\"type\")\n                  && extensionHandlers.containsKey(attributes.get(\"type\")))) {\n            inExtensionSection = true;\n            extensionHandler = extensionHandlers.get(qName).get();\n         } else if (qName.endsWith(\"Section\")) {\n            inSection = true;\n         }\n      }\n\n      if (inDisk) {\n         diskHandler.startElement(uri, localName, qName, attrs);\n      } else if (inNetwork) {\n         networkHandler.startElement(uri, localName, qName, attrs);\n      } else if (inVirtualSystem) {\n         virtualSystemHandler.startElement(uri, localName, qName, attrs);\n      } else if (inExtensionSection) {\n         extensionHandler.startElement(uri, localName, qName, attrs);\n      } else if (inSection) {\n         defaultSectionHandler.startElement(uri, localName, qName, attrs);\n      }\n\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) {\n      depth--;\n      if (depth == 1) {\n         if (equalsOrSuffix(qName, \"DiskSection\")) {\n            inDisk = false;\n            builder.diskSection(diskHandler.getResult());\n         } else if (equalsOrSuffix(qName, \"NetworkSection\")) {\n            inNetwork = false;\n            builder.networkSection(networkHandler.getResult());\n         } else if (equalsOrSuffix(qName, \"VirtualSystemCollection\")) {\n            // http://code.google.com/p/jclouds/issues/detail?id=811\n            throw new IllegalArgumentException(\"this handler cannot currently create envelopes with multiple virtual systems\");\n         } else if (equalsOrSuffix(qName, \"VirtualSystem\")) {\n            inVirtualSystem = false;\n            builder.virtualSystem(virtualSystemHandler.getResult());\n         } else if (extensionHandlers.containsKey(qName)) {\n            builder.additionalSection(qName, extensionHandler.getResult());\n            inExtensionSection = false;\n         } else if (qName.endsWith(\"Section\")) {\n            builder.additionalSection(qName, defaultSectionHandler.getResult());\n            inSection = false;\n         }\n      }\n\n      if (inDisk) {\n         diskHandler.endElement(uri, localName, qName);\n      } else if (inNetwork) {\n         networkHandler.endElement(uri, localName, qName);\n      } else if (inVirtualSystem) {\n         virtualSystemHandler.endElement(uri, localName, qName);\n      } else if (inExtensionSection) {\n         extensionHandler.endElement(uri, localName, qName);\n      } else if (inSection) {\n         defaultSectionHandler.endElement(uri, localName, qName);\n      }\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      if (inDisk) {\n         diskHandler.characters(ch, start, length);\n      } else if (inNetwork) {\n         networkHandler.characters(ch, start, length);\n      } else if (inVirtualSystem) {\n         virtualSystemHandler.characters(ch, start, length);\n      } else if (inExtensionSection) {\n         extensionHandler.characters(ch, start, length);\n      } else if (inSection) {\n         defaultSectionHandler.characters(ch, start, length);\n      }\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/ovf/xml/internal/BaseVirtualSystemHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ovf.xml.internal;\n\nimport static org.jclouds.util.SaxUtils.cleanseAttributes;\nimport static org.jclouds.util.SaxUtils.currentOrNull;\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport java.util.Map;\n\nimport jakarta.inject.Named;\nimport jakarta.inject.Provider;\n\nimport org.jclouds.ovf.Section;\nimport org.jclouds.ovf.internal.BaseVirtualSystem;\nimport org.jclouds.ovf.xml.OperatingSystemSectionHandler;\nimport org.jclouds.ovf.xml.ProductSectionHandler;\nimport org.jclouds.ovf.xml.SectionHandler;\nimport org.jclouds.ovf.xml.VirtualHardwareSectionHandler;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.inject.Inject;\n\npublic class BaseVirtualSystemHandler<T extends BaseVirtualSystem<T>, B extends BaseVirtualSystem.Builder<T>> extends\n         SectionHandler<T, B> {\n\n   private final OperatingSystemSectionHandler osHandler;\n   private final VirtualHardwareSectionHandler hardwareHandler;\n   private final ProductSectionHandler productHandler;\n\n   @Inject\n   public BaseVirtualSystemHandler(Provider<B> builderProvider, OperatingSystemSectionHandler osHandler,\n            VirtualHardwareSectionHandler hardwareHandler, ProductSectionHandler productHandler) {\n      super(builderProvider);\n      this.osHandler = osHandler;\n      this.hardwareHandler = hardwareHandler;\n      this.productHandler = productHandler;\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   protected SectionHandler defaultSectionHandler = SectionHandler.create();\n\n   @SuppressWarnings(\"unchecked\")\n   protected Map<String, Provider<? extends SectionHandler>> extensionHandlers = ImmutableMap\n            .<String, Provider<? extends SectionHandler>> of();\n\n   @SuppressWarnings(\"unchecked\")\n   @Inject(optional = true)\n   protected void setExtensionHandlers(\n            @Named(\"VirtualSystem\") Map<String, Provider<? extends SectionHandler>> extensionHandlers) {\n      this.extensionHandlers = ImmutableMap.<String, Provider<? extends SectionHandler>> builder().putAll(\n               this.extensionHandlers).putAll(extensionHandlers).build();\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   protected SectionHandler extensionHandler;\n\n   private boolean inHardware;\n   private boolean inOs;\n   private boolean inProduct;\n   private boolean inSection;\n   private boolean inExtensionSection;\n   private int depth;\n\n   public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException {\n      Map<String, String> attributes = cleanseAttributes(attrs);\n      depth++;\n      if (depth == 2) {\n         if (equalsOrSuffix(qName, \"VirtualHardwareSection\")) {\n            inHardware = true;\n         } else if (equalsOrSuffix(qName, \"OperatingSystemSection\")) {\n            inOs = true;\n         } else if (equalsOrSuffix(qName, \"ProductSection\")) {\n            inProduct = true;\n         } else if (extensionHandlers.containsKey(qName)) {\n            inExtensionSection = true;\n            extensionHandler = extensionHandlers.get(qName).get();\n         } else if (attributes.containsKey(\"type\") && extensionHandlers.containsKey(attributes.get(\"type\"))) {\n            inExtensionSection = true;\n            extensionHandler = extensionHandlers.get(attributes.get(\"type\")).get();\n         } else if (qName.endsWith(\"Section\")) {\n            inSection = true;\n         }\n      }\n      if (inHardware) {\n         hardwareHandler.startElement(uri, localName, qName, attrs);\n      } else if (inOs) {\n         osHandler.startElement(uri, localName, qName, attrs);\n      } else if (inProduct) {\n         productHandler.startElement(uri, localName, qName, attrs);\n      } else if (inExtensionSection) {\n         extensionHandler.startElement(uri, localName, qName, attrs);\n      } else if (inSection) {\n         defaultSectionHandler.startElement(uri, localName, qName, attrs);\n      } else if (equalsOrSuffix(qName, \"VirtualSystem\")) {\n         builder.id(attributes.get(\"id\"));\n      }\n\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) {\n      depth--;\n      if (depth == 1) {\n         if (equalsOrSuffix(qName, \"VirtualHardwareSection\")) {\n            inHardware = false;\n            builder.virtualHardwareSection(hardwareHandler.getResult());\n         } else if (equalsOrSuffix(qName, \"OperatingSystemSection\")) {\n            inOs = false;\n            builder.operatingSystemSection(osHandler.getResult());\n         } else if (equalsOrSuffix(qName, \"ProductSection\")) {\n            inProduct = false;\n            builder.productSection(productHandler.getResult());\n         } else if (extensionHandlers.containsKey(qName)) {\n            addAdditionalSection(qName, extensionHandler.getResult());\n            inSection = false;\n            inExtensionSection = false;\n         } else if (qName.endsWith(\"Section\")) {\n            addAdditionalSection(qName, inExtensionSection ? extensionHandler.getResult() : defaultSectionHandler\n                     .getResult());\n            inSection = false;\n            inExtensionSection = false;\n         }\n      }\n\n      if (inHardware) {\n         hardwareHandler.endElement(uri, localName, qName);\n      } else if (inOs) {\n         osHandler.endElement(uri, localName, qName);\n      } else if (inProduct) {\n         productHandler.endElement(uri, localName, qName);\n      } else if (inExtensionSection) {\n         extensionHandler.endElement(uri, localName, qName);\n      } else if (inSection) {\n         defaultSectionHandler.endElement(uri, localName, qName);\n      } else {\n         if (equalsOrSuffix(qName, \"Info\")) {\n            builder.info(currentOrNull(currentText));\n         } else if (equalsOrSuffix(qName, \"Name\")) {\n            builder.name(currentOrNull(currentText));\n         }\n         super.endElement(uri, localName, qName);\n      }\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   protected void addAdditionalSection(String qName, Section additionalSection) {\n      builder.additionalSection(qName, additionalSection);\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      if (inHardware) {\n         hardwareHandler.characters(ch, start, length);\n      } else if (inOs) {\n         osHandler.characters(ch, start, length);\n      } else if (inProduct) {\n         productHandler.characters(ch, start, length);\n      } else if (inExtensionSection) {\n         extensionHandler.characters(ch, start, length);\n      } else if (inSection) {\n         defaultSectionHandler.characters(ch, start, length);\n      } else {\n         super.characters(ch, start, length);\n      }\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/ssh/SshClient.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ssh;\n\nimport org.jclouds.compute.domain.ExecChannel;\nimport org.jclouds.compute.domain.ExecResponse;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.io.Payload;\n\nimport com.google.common.net.HostAndPort;\n\npublic interface SshClient {\n\n   interface Factory {\n      SshClient create(HostAndPort socket, LoginCredentials credentials);\n      boolean isAgentAvailable();\n   }\n\n   String getUsername();\n\n   String getHostAddress();\n\n   void put(String path, Payload contents);\n\n   Payload get(String path);\n\n   /**\n    * Execute a process and block until it is complete\n    * \n    * @param command\n    *           command line to invoke\n    * @return output of the command\n    */\n   ExecResponse exec(String command);\n\n   /**\n    * Execute a process and allow the user to interact with it.\n    * \n    * @param command\n    *           command line to invoke\n    * @return reference to the running process\n    * @since 1.5.0\n    */\n   ExecChannel execChannel(String command);\n\n   void connect();\n\n   void disconnect();\n\n   boolean isConnected();\n\n   void put(String path, String contents);\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/ssh/SshException.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ssh;\n\npublic class SshException extends RuntimeException {\n\n   public SshException() {\n      super();\n   }\n\n   public SshException(String arg0, Throwable arg1) {\n      super(arg0, arg1);\n   }\n\n   public SshException(String arg0) {\n      super(arg0);\n   }\n\n   public SshException(Throwable arg0) {\n      super(arg0);\n   }\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/ssh/SshKeyPairGenerator.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ssh;\n\nimport java.util.Map;\n\nimport org.jclouds.ssh.internal.RsaSshKeyPairGenerator;\n\nimport com.google.common.base.Supplier;\nimport com.google.inject.ImplementedBy;\n\n/**\n * Creates a unique keypair without a passphrase. The resulting map has the following keys\n * <ul>\n * <li>public</li>\n * <li>private</li>\n * </ul>\n */\n@ImplementedBy(RsaSshKeyPairGenerator.class)\npublic interface SshKeyPairGenerator extends Supplier<Map<String, String>> {\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/ssh/SshKeys.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ssh;\n\nimport static com.google.common.base.Joiner.on;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Splitter.fixedLength;\nimport static com.google.common.base.Throwables.propagate;\nimport static com.google.common.collect.Iterables.get;\nimport static com.google.common.collect.Iterables.size;\nimport static com.google.common.io.BaseEncoding.base16;\nimport static com.google.common.io.BaseEncoding.base64;\nimport static org.jclouds.crypto.Pems.pem;\nimport static org.jclouds.crypto.Pems.privateKeySpec;\nimport static org.jclouds.util.Strings2.toStringAndClose;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.math.BigInteger;\nimport java.security.KeyFactory;\nimport java.security.KeyPair;\nimport java.security.KeyPairGenerator;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.SecureRandom;\nimport java.security.interfaces.RSAPrivateKey;\nimport java.security.interfaces.RSAPublicKey;\nimport java.security.spec.InvalidKeySpecException;\nimport java.security.spec.KeySpec;\nimport java.security.spec.RSAPrivateCrtKeySpec;\nimport java.security.spec.RSAPublicKeySpec;\nimport java.util.Map;\n\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Charsets;\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMap.Builder;\nimport com.google.common.hash.HashCode;\nimport com.google.common.hash.Hashing;\nimport com.google.common.io.ByteSource;\nimport com.google.common.io.ByteStreams;\n\n/**\n * Utilities for ssh key pairs\n * \n * @see <a href=\n *      \"http://stackoverflow.com/questions/3706177/how-to-generate-ssh-compatible-id-rsa-pub-from-java\"\n *      />\n */\n@Beta\npublic class SshKeys {\n\n   /**\n    * Executes {@link Pems#publicKeySpecFromOpenSSH(ByteSource)} on the string which was OpenSSH\n    * Base64 Encoded {@code id_rsa.pub}\n    * \n    * @param idRsaPub\n    *           formatted {@code ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAB...}\n    * @see Pems#publicKeySpecFromOpenSSH(ByteSource)\n    */\n   public static RSAPublicKeySpec publicKeySpecFromOpenSSH(String idRsaPub) {\n      try {\n         return publicKeySpecFromOpenSSH(ByteSource.wrap(\n            idRsaPub.getBytes(Charsets.UTF_8)));\n      } catch (IOException e) {\n         throw propagate(e);\n      }\n   }\n\n   /**\n    * Returns {@link RSAPublicKeySpec} which was OpenSSH Base64 Encoded {@code id_rsa.pub}\n    * \n    * @param supplier\n    *           the input stream factory, formatted {@code ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAB...}\n    * \n    * @return the {@link RSAPublicKeySpec} which was OpenSSH Base64 Encoded {@code id_rsa.pub}\n    * @throws IOException\n    *            if an I/O error occurs\n    */\n   public static RSAPublicKeySpec publicKeySpecFromOpenSSH(ByteSource supplier)\n            throws IOException {\n      InputStream stream = supplier.openStream();\n      Iterable<String> parts = Splitter.on(' ').split(toStringAndClose(stream).trim());\n      checkArgument(size(parts) >= 2 && \"ssh-rsa\".equals(get(parts, 0)),\n               \"bad format, should be: ssh-rsa AAAAB3...\");\n      stream = new ByteArrayInputStream(base64().decode(get(parts, 1)));\n      String marker = new String(readLengthFirst(stream));\n      checkArgument(\"ssh-rsa\".equals(marker), \"looking for marker ssh-rsa but got %s\", marker);\n      BigInteger publicExponent = new BigInteger(readLengthFirst(stream));\n      BigInteger modulus = new BigInteger(readLengthFirst(stream));\n      return new RSAPublicKeySpec(modulus, publicExponent);\n   }\n\n   // http://www.ietf.org/rfc/rfc4253.txt\n   private static byte[] readLengthFirst(InputStream in) throws IOException {\n      int byte1 = in.read();\n      int byte2 = in.read();\n      int byte3 = in.read();\n      int byte4 = in.read();\n      int length = (byte1 << 24) + (byte2 << 16) + (byte3 << 8) + (byte4 << 0);\n      byte[] val = new byte[length];\n      ByteStreams.readFully(in, val);\n      return val;\n   }\n\n   /**\n    * \n    * @param generator\n    *           to generate RSA key pairs\n    * @param rand\n    *           for initializing {@code generator}\n    * @return new 2048 bit keyPair\n    * @see Crypto#rsaKeyPairGenerator()\n    */\n   public static KeyPair generateRsaKeyPair(KeyPairGenerator generator, SecureRandom rand) {\n      generator.initialize(2048, rand);\n      return generator.genKeyPair();\n   }\n\n   /**\n    * return a \"public\" -> rsa public key, \"private\" -> its corresponding private key\n    */\n   public static Map<String, String> generate() {\n      try {\n         return generate(KeyPairGenerator.getInstance(\"RSA\"), new SecureRandom());\n      } catch (NoSuchAlgorithmException e) {\n         throw propagate(e);\n      }\n   }\n\n   public static Map<String, String> generate(KeyPairGenerator generator, SecureRandom rand) {\n      KeyPair pair = generateRsaKeyPair(generator, rand);\n      Builder<String, String> builder = ImmutableMap.builder();\n      builder.put(\"public\", encodeAsOpenSSH(RSAPublicKey.class.cast(pair.getPublic())));\n      builder.put(\"private\", pem(RSAPrivateKey.class.cast(pair.getPrivate())));\n      return builder.build();\n   }\n\n   public static String encodeAsOpenSSH(RSAPublicKey key) {\n      byte[] keyBlob = keyBlob(key.getPublicExponent(), key.getModulus());\n      return \"ssh-rsa \" + base64().encode(keyBlob);\n   }\n\n   /**\n    * @param privateKeyPEM\n    *           RSA private key in PEM format\n    * @param publicKeyOpenSSH\n    *           RSA public key in OpenSSH format\n    * @return true if the keypairs match\n    */\n   public static boolean privateKeyMatchesPublicKey(String privateKeyPEM, String publicKeyOpenSSH) {\n      KeySpec privateKeySpec = privateKeySpec(privateKeyPEM);\n      checkArgument(privateKeySpec instanceof RSAPrivateCrtKeySpec,\n               \"incorrect format expected RSAPrivateCrtKeySpec was %s\", privateKeySpec);\n      return privateKeyMatchesPublicKey(RSAPrivateCrtKeySpec.class.cast(privateKeySpec),\n               publicKeySpecFromOpenSSH(publicKeyOpenSSH));\n   }\n\n   /**\n    * @return true if the keypairs match\n    */\n   public static boolean privateKeyMatchesPublicKey(RSAPrivateCrtKeySpec privateKey, RSAPublicKeySpec publicKey) {\n      return privateKey.getPublicExponent().equals(publicKey.getPublicExponent())\n               && privateKey.getModulus().equals(publicKey.getModulus());\n   }\n\n   /**\n    * @return true if the keypair has the same fingerprint as supplied\n    */\n   public static boolean privateKeyHasFingerprint(RSAPrivateCrtKeySpec privateKey, String fingerprint) {\n      return fingerprint(privateKey.getPublicExponent(), privateKey.getModulus()).equals(fingerprint);\n   }\n\n   /**\n    * @param privateKeyPEM\n    *           RSA private key in PEM format\n    * @param fingerprint\n    *           ex. {@code 2b:a9:62:95:5b:8b:1d:61:e0:92:f7:03:10:e9:db:d9}\n    * @return true if the keypair has the same fingerprint as supplied\n    */\n   public static boolean privateKeyHasFingerprint(String privateKeyPEM, String fingerprint) {\n      KeySpec privateKeySpec = privateKeySpec(privateKeyPEM);\n      checkArgument(privateKeySpec instanceof RSAPrivateCrtKeySpec,\n               \"incorrect format expected RSAPrivateCrtKeySpec was %s\", privateKeySpec);\n      return privateKeyHasFingerprint(RSAPrivateCrtKeySpec.class.cast(privateKeySpec), fingerprint);\n   }\n\n   /**\n    * @param privateKeyPEM\n    *           RSA private key in PEM format\n    * @return fingerprint ex. {@code 2b:a9:62:95:5b:8b:1d:61:e0:92:f7:03:10:e9:db:d9}\n    */\n   public static String fingerprintPrivateKey(String privateKeyPEM) {\n      KeySpec privateKeySpec = privateKeySpec(privateKeyPEM);\n      checkArgument(privateKeySpec instanceof RSAPrivateCrtKeySpec,\n               \"incorrect format expected RSAPrivateCrtKeySpec was %s\", privateKeySpec);\n      RSAPrivateCrtKeySpec certKeySpec = RSAPrivateCrtKeySpec.class.cast(privateKeySpec);\n      return fingerprint(certKeySpec.getPublicExponent(), certKeySpec.getModulus());\n   }\n\n   /**\n    * @param publicKeyOpenSSH\n    *           RSA public key in OpenSSH format\n    * @return fingerprint ex. {@code 2b:a9:62:95:5b:8b:1d:61:e0:92:f7:03:10:e9:db:d9}\n    */\n   public static String fingerprintPublicKey(String publicKeyOpenSSH) {\n      RSAPublicKeySpec publicKeySpec = publicKeySpecFromOpenSSH(publicKeyOpenSSH);\n      return fingerprint(publicKeySpec.getPublicExponent(), publicKeySpec.getModulus());\n   }\n\n   /**\n    * @return true if the keypair has the same SHA1 fingerprint as supplied\n    */\n   public static boolean privateKeyHasSha1(RSAPrivateCrtKeySpec privateKey, String fingerprint) {\n      return sha1(privateKey).equals(fingerprint);\n   }\n\n   /**\n    * @param privateKeyPEM\n    *           RSA private key in PEM format\n    * @param sha1HexColonDelimited\n    *           ex. {@code 2b:a9:62:95:5b:8b:1d:61:e0:92:f7:03:10:e9:db:d9}\n    * @return true if the keypair has the same fingerprint as supplied\n    */\n   public static boolean privateKeyHasSha1(String privateKeyPEM, String sha1HexColonDelimited) {\n      KeySpec privateKeySpec = privateKeySpec(privateKeyPEM);\n      checkArgument(privateKeySpec instanceof RSAPrivateCrtKeySpec,\n               \"incorrect format expected RSAPrivateCrtKeySpec was %s\", privateKeySpec);\n      return privateKeyHasSha1(RSAPrivateCrtKeySpec.class.cast(privateKeySpec), sha1HexColonDelimited);\n   }\n\n   /**\n    * @param privateKeyPEM\n    *           RSA private key in PEM format\n    * @return sha1HexColonDelimited ex. {@code 2b:a9:62:95:5b:8b:1d:61:e0:92:f7:03:10:e9:db:d9}\n    */\n   public static String sha1PrivateKey(String privateKeyPEM) {\n      KeySpec privateKeySpec = privateKeySpec(privateKeyPEM);\n      checkArgument(privateKeySpec instanceof RSAPrivateCrtKeySpec,\n               \"incorrect format expected RSAPrivateCrtKeySpec was %s\", privateKeySpec);\n      RSAPrivateCrtKeySpec certKeySpec = RSAPrivateCrtKeySpec.class.cast(privateKeySpec);\n      return sha1(certKeySpec);\n   }\n\n   /**\n    * Create a SHA-1 digest of the DER encoded private key.\n    * \n    * @param publicExponent\n    * @param modulus\n    * \n    * @return hex sha1HexColonDelimited ex. {@code 2b:a9:62:95:5b:8b:1d:61:e0:92:f7:03:10:e9:db:d9}\n    */\n   public static String sha1(RSAPrivateCrtKeySpec privateKey) {\n      try {\n         byte[] encodedKey = KeyFactory.getInstance(\"RSA\").generatePrivate(privateKey).getEncoded();\n         return hexColonDelimited(Hashing.sha1().hashBytes(encodedKey));\n      } catch (InvalidKeySpecException e) {\n         throw propagate(e);\n      } catch (NoSuchAlgorithmException e) {\n         throw propagate(e);\n      }\n   }\n\n   /**\n    * @return true if the keypair has the same fingerprint as supplied\n    */\n   public static boolean publicKeyHasFingerprint(RSAPublicKeySpec publicKey, String fingerprint) {\n      return fingerprint(publicKey.getPublicExponent(), publicKey.getModulus()).equals(fingerprint);\n   }\n\n   /**\n    * @param publicKeyOpenSSH\n    *           RSA public key in OpenSSH format\n    * @param fingerprint\n    *           ex. {@code 2b:a9:62:95:5b:8b:1d:61:e0:92:f7:03:10:e9:db:d9}\n    * @return true if the keypair has the same fingerprint as supplied\n    */\n   public static boolean publicKeyHasFingerprint(String publicKeyOpenSSH, String fingerprint) {\n      return publicKeyHasFingerprint(publicKeySpecFromOpenSSH(publicKeyOpenSSH), fingerprint);\n   }\n\n   /**\n    * Create a fingerprint per the following <a\n    * href=\"http://tools.ietf.org/html/draft-friedl-secsh-fingerprint-00\" >spec</a>\n    * \n    * @param publicExponent\n    * @param modulus\n    * \n    * @return hex fingerprint ex. {@code 2b:a9:62:95:5b:8b:1d:61:e0:92:f7:03:10:e9:db:d9}\n    */\n   public static String fingerprint(BigInteger publicExponent, BigInteger modulus) {\n      byte[] keyBlob = keyBlob(publicExponent, modulus);\n      return hexColonDelimited(Hashing.md5().hashBytes(keyBlob));\n   }\n\n   private static String hexColonDelimited(HashCode hc) {\n      return on(':').join(fixedLength(2).split(base16().lowerCase().encode(hc.asBytes())));\n   }\n\n   private static byte[] keyBlob(BigInteger publicExponent, BigInteger modulus) {\n      try {\n         ByteArrayOutputStream out = new ByteArrayOutputStream();\n         writeLengthFirst(\"ssh-rsa\".getBytes(), out);\n         writeLengthFirst(publicExponent.toByteArray(), out);\n         writeLengthFirst(modulus.toByteArray(), out);\n         return out.toByteArray();\n      } catch (IOException e) {\n         throw propagate(e);\n      }\n   }\n\n   // http://www.ietf.org/rfc/rfc4253.txt\n   private static void writeLengthFirst(byte[] array, ByteArrayOutputStream out) throws IOException {\n      out.write((array.length >>> 24) & 0xFF);\n      out.write((array.length >>> 16) & 0xFF);\n      out.write((array.length >>> 8) & 0xFF);\n      out.write((array.length >>> 0) & 0xFF);\n      if (array.length == 1 && array[0] == (byte) 0x00)\n         out.write(new byte[0]);\n      else\n         out.write(array);\n   }\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/ssh/config/ConfiguresSshClient.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ssh.config;\n\nimport static java.lang.annotation.ElementType.TYPE;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\n/**\n * designates the module configures an Ssh Client.\n */\n@Retention(RUNTIME)\n@Target(TYPE)\npublic @interface ConfiguresSshClient {\n\n}\n"
  },
  {
    "path": "compute/src/main/java/org/jclouds/ssh/internal/RsaSshKeyPairGenerator.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ssh.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.security.SecureRandom;\nimport java.util.Map;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.crypto.Crypto;\nimport org.jclouds.ssh.SshKeyPairGenerator;\nimport org.jclouds.ssh.SshKeys;\n\nimport com.google.inject.Inject;\n\n@Singleton\npublic class RsaSshKeyPairGenerator implements SshKeyPairGenerator {\n   private final Crypto crypto;\n   private final SecureRandom secureRandom;\n\n   @Inject\n   private RsaSshKeyPairGenerator(Crypto crypto, SecureRandom secureRandom) {\n      this.crypto = checkNotNull(crypto, \"crypto\");\n      this.secureRandom = checkNotNull(secureRandom, \"secureRandom\");\n   }\n\n   @Override\n   public Map<String, String> get() {\n      return SshKeys.generate(crypto.rsaKeyPairGenerator(), secureRandom);\n   }\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/ComputeTestUtils.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Strings.emptyToNull;\nimport static com.google.common.collect.Iterables.get;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.lang.reflect.UndeclaredThrowableException;\nimport java.net.URI;\nimport java.util.Map;\nimport java.util.concurrent.TimeoutException;\n\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.rest.HttpClient;\nimport org.jclouds.ssh.SshKeys;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.base.Throwables;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.io.Files;\n\n/**\n * utilities helpful in testing compute providers\n */\npublic class ComputeTestUtils {\n\n   public static Map<String, String> setupKeyPair()  {\n      String secretKeyFile;\n      try {\n         secretKeyFile = checkNotNull(System.getProperty(\"test.ssh.keyfile\"), \"test.ssh.keyfile\");\n      } catch (NullPointerException e) {\n         secretKeyFile = System.getProperty(\"user.home\") + \"/.ssh/id_rsa\";\n      }\n      try {\n         checkSecretKeyFile(secretKeyFile);\n      }\n      catch (IllegalStateException e) {\n         return SshKeys.generate();\n      }\n      try {\n         String secret = Files.toString(new File(secretKeyFile), Charsets.UTF_8);\n         assert secret.startsWith(\"-----BEGIN RSA PRIVATE KEY-----\") : \"invalid key:\\n\" + secret;\n         return ImmutableMap.<String, String> of(\"private\", secret, \"public\", Files.toString(new File(secretKeyFile\n                  + \".pub\"), Charsets.UTF_8));\n      } catch (IOException e) {\n        throw Throwables.propagate(e);\n      }\n   }\n\n   public static void checkSecretKeyFile(String secretKeyFile) {\n      checkNotNull(emptyToNull(secretKeyFile), \"System property: [test.ssh.keyfile] set to an empty string\");\n      if (!new File(secretKeyFile).exists()) {\n         throw new IllegalStateException(\"secretKeyFile not found at: \" + secretKeyFile);\n      }\n   }\n\n   public static void checkHttpGet(HttpClient client, NodeMetadata node, int port) {\n      for (int i = 0; i < 5; i++)\n         try {\n            assert client.get(URI.create(String.format(\"http://%s:%d\", get(node.getPublicAddresses(), 0), port))) != null;\n            break;\n         } catch (UndeclaredThrowableException e) {\n            assertEquals(e.getCause().getClass(), TimeoutException.class);\n            try {\n               Thread.sleep(1000);\n            } catch (InterruptedException e1) {\n            }\n         }\n   }\n\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/JettyStatements.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute;\n\nimport static org.jclouds.scriptbuilder.domain.Statements.exec;\nimport static org.jclouds.scriptbuilder.domain.Statements.extractTargzAndFlattenIntoDirectory;\nimport static org.jclouds.scriptbuilder.domain.Statements.literal;\n\nimport java.net.URI;\n\nimport org.jclouds.scriptbuilder.domain.Statement;\nimport org.jclouds.scriptbuilder.domain.StatementList;\nimport org.jclouds.scriptbuilder.statements.java.InstallJDK;\nimport org.jclouds.scriptbuilder.statements.login.AdminAccess;\n\npublic class JettyStatements {\n\n   public static final URI JETTY_URL = URI.create(System.getProperty(\"test.jetty-url\",\n         \"http://archive.eclipse.org/jetty/8.1.8.v20121106/dist/jetty-distribution-8.1.8.v20121106.tar.gz\"));\n\n   public static final String JETTY_HOME = \"/usr/local/jetty\";\n   \n   public static final int port = 8080;\n\n   public static Statement version() {\n      return exec(String.format(\"head -1 %s/VERSION.txt | cut -f1 -d ' '\", JETTY_HOME));\n   }\n\n   public static Statement install() {\n      return new StatementList(\n            AdminAccess.builder().adminUsername(\"web\").build(),\n            InstallJDK.fromOpenJDK(),\n            authorizePortInIpTables(),\n            extractTargzAndFlattenIntoDirectory(JETTY_URL, JETTY_HOME),\n            exec(\"chown -R web \" + JETTY_HOME));\n   }\n\n   private static Statement authorizePortInIpTables() {\n      return new StatementList(\n            exec(\"iptables -I INPUT 1 -p tcp --dport \" + port + \" -j ACCEPT\"),\n            exec(\"iptables-save\"));\n   }\n   \n   public static Statement start() {\n      return new StatementList(\n            literal(String.format(\"JETTY_PORT=%d nohup %s/bin/jetty.sh start > start.log 2>&1 < /dev/null &\", port, JETTY_HOME)),\n            literal(\"test $? && sleep 1\")); // in case it is slow starting the proc\n   }\n   \n   public static Statement stop() {\n      return literal(JETTY_HOME + \"/bin/jetty.sh stop\");\n   }\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/StubComputeServiceIntegrationTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute;\nimport static java.util.concurrent.TimeUnit.MILLISECONDS;\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.eq;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.reportMatcher;\nimport static org.jclouds.util.Predicates2.retry;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.TimeUnit;\n\nimport org.easymock.IArgumentMatcher;\nimport org.jclouds.compute.config.AdminAccessConfiguration;\nimport org.jclouds.compute.domain.ExecResponse;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.internal.BaseComputeServiceLiveTest;\nimport org.jclouds.compute.util.OpenSocketFinder;\nimport org.jclouds.crypto.Pems;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.io.Payload;\nimport org.jclouds.predicates.SocketOpen;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.ssh.SshClient;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.base.Throwables;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.net.HostAndPort;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Module;\n\n@Test(groups = \"live\", testName = \"StubComputeServiceIntegrationTest\")\npublic class StubComputeServiceIntegrationTest extends BaseComputeServiceLiveTest {\n\n   private static final ExecResponse EXEC_GOOD = new ExecResponse(\"\", \"\", 0);\n   private static final ExecResponse EXEC_BAD = new ExecResponse(\"\", \"\", 1);\n   private static final ExecResponse EXEC_RC_GOOD = new ExecResponse(\"0\", \"\", 0);\n\n   public StubComputeServiceIntegrationTest() {\n      provider = \"stub\";\n   }\n\n   @Override\n   public void testCorrectAuthException() throws Exception {\n   }\n\n   protected void buildSocketTester() {\n      SocketOpen socketOpen = createMock(SocketOpen.class);\n\n      expect(socketOpen.apply(HostAndPort.fromParts(\"144.175.1.1\", 22))).andReturn(true).times(5);\n\n      replay(socketOpen);\n\n      socketTester = retry(socketOpen, 1, 1, MILLISECONDS);\n      \n      openSocketFinder = new OpenSocketFinder() {\n\n         @Override\n         public HostAndPort findOpenSocketOnNode(NodeMetadata node, int port, long timeoutValue, TimeUnit timeUnits) {\n            return HostAndPort.fromParts(\"144.175.1.1\", 8080);\n         }\n         \n      };\n   }\n\n   @Override\n   protected void checkHttpGet(NodeMetadata node) {\n\n   }\n\n   @Override\n   protected Module getSshModule() {\n      return new AbstractModule() {\n         @Override\n         protected void configure() {\n            bind(AdminAccessConfiguration.class).toInstance(new AdminAccessConfiguration() {\n               public Supplier<String> defaultAdminUsername() {\n                  return Suppliers.ofInstance(\"defaultAdminUsername\");\n               }\n\n               public Supplier<Map<String, String>> defaultAdminSshKeys() {\n                  return Suppliers.<Map<String, String>> ofInstance(ImmutableMap.of(\"public\", \"publicKey\", \"private\",\n                        Pems.PRIVATE_PKCS1_MARKER));\n               }\n               \n               public Function<String, String> cryptFunction() {\n                  return new Function<String, String>() {\n                     public String apply(String input) {\n                        return String.format(\"crypt(%s)\", input);\n                     }\n                  };\n               }\n               \n               public Supplier<String> passwordGenerator() {\n                  return Suppliers.ofInstance(\"randompassword\");\n               }\n            });\n            SshClient.Factory factory = createMock(SshClient.Factory.class);\n            SshClient client1 = createMock(SshClient.class);\n            SshClient client1New = createMock(SshClient.class);\n            SshClient client2 = createMock(SshClient.class);\n            SshClient client2New = createMock(SshClient.class);\n            SshClient client2Foo = createMock(SshClient.class);\n            SshClient client3 = createMock(SshClient.class);\n            SshClient client4 = createMock(SshClient.class);\n            SshClient client5 = createMock(SshClient.class);\n            SshClient client6 = createMock(SshClient.class);\n            SshClient client7 = createMock(SshClient.class);\n\n            expect(\n                  factory.create(HostAndPort.fromParts(\"144.175.1.1\", 22),\n                        LoginCredentials.builder().user(\"root\").password(\"password1\").build())).andReturn(client1);\n            expect(\n                  factory.create(HostAndPort.fromParts(\"144.175.1.1\", 22),\n                        LoginCredentials.builder().user(\"web\").privateKey(Pems.PRIVATE_PKCS1_MARKER).build())).andReturn(client1New)\n                  .times(10);\n            runScriptAndService(client1, client1New);\n\n            expect(\n                  factory.create(HostAndPort.fromParts(\"144.175.1.2\", 22),\n                        LoginCredentials.builder().user(\"root\").password(\"password2\").build())).andReturn(client2)\n                  .times(4);\n            expect(\n                  factory.create(HostAndPort.fromParts(\"144.175.1.2\", 22),\n                        LoginCredentials.builder().user(\"root\").password(\"password2\").build())).andReturn(client2New);\n            expect(\n                  factory.create(HostAndPort.fromParts(\"144.175.1.2\", 22),\n                        LoginCredentials.builder().user(\"foo\").privateKey(Pems.PRIVATE_PKCS1_MARKER).build())).andReturn(client2Foo);\n            expect(\n                  factory.create(HostAndPort.fromParts(\"144.175.1.2\", 22),\n                        LoginCredentials.builder().user(\"root\").password(\"romeo\").build())).andThrow(\n                  new AuthorizationException(\"Auth fail\", null));\n\n            // run script without backgrounding (via predicate)\n            client2.connect();\n            expect(client2.exec(\"hostname -s\\n\")).andReturn(new ExecResponse(\"stub-r\\n\", \"\", 0));\n            client2.disconnect();\n\n            // run script without backgrounding (via id)\n            client2.connect();\n            expect(client2.exec(\"hostname -s\\n\")).andReturn(new ExecResponse(\"stub-r\\n\", \"\", 0));\n            client2.disconnect();\n\n            client2.connect();\n            try {\n               runScript(client2, \"runScriptWithCreds\",\n                        Strings2.toStringAndClose(StubComputeServiceIntegrationTest.class\n                                 .getResourceAsStream(\"/runscript.sh\")), 2);\n            } catch (IOException e) {\n               Throwables.propagate(e);\n            }\n            client2.disconnect();\n\n            client2New.connect();\n            try {\n               runScript(client2New, \"adminUpdate\", Strings2.toStringAndClose(StubComputeServiceIntegrationTest.class\n                        .getResourceAsStream(\"/runscript_adminUpdate.sh\")), 2);\n            } catch (IOException e) {\n               Throwables.propagate(e);\n            }\n            client2New.disconnect();\n\n            // check id\n            client2Foo.connect();\n            expect(client2Foo.getUsername()).andReturn(\"foo\").atLeastOnce();\n            expect(client2Foo.getHostAddress()).andReturn(\"foo\").atLeastOnce();\n            expect(client2Foo.exec(\"echo $USER\\n\")).andReturn(new ExecResponse(\"foo\\n\", \"\", 0));\n            client2Foo.disconnect();\n\n            expect(\n                  factory.create(HostAndPort.fromParts(\"144.175.1.3\", 22),\n                        LoginCredentials.builder().user(\"root\").password(\"password3\").build())).andReturn(client3)\n                  .times(2);\n            expect(\n                  factory.create(HostAndPort.fromParts(\"144.175.1.4\", 22),\n                        LoginCredentials.builder().user(\"root\").password(\"password4\").build())).andReturn(client4)\n                  .times(2);\n            expect(\n                  factory.create(HostAndPort.fromParts(\"144.175.1.5\", 22),\n                        LoginCredentials.builder().user(\"root\").password(\"password5\").build())).andReturn(client5)\n                  .times(2);\n            expect(\n                  factory.create(HostAndPort.fromParts(\"144.175.1.6\", 22),\n                        LoginCredentials.builder().user(\"root\").password(\"password6\").build())).andReturn(client6)\n                  .times(2);\n            expect(\n                  factory.create(HostAndPort.fromParts(\"144.175.1.7\", 22),\n                        LoginCredentials.builder().user(\"root\").password(\"password7\").build())).andReturn(client7)\n                  .times(2);\n\n            runScriptAndInstallSsh(client3, \"bootstrap\", 3);\n            runScriptAndInstallSsh(client4, \"bootstrap\", 4);\n            runScriptAndInstallSsh(client5, \"bootstrap\", 5);\n            runScriptAndInstallSsh(client6, \"bootstrap\", 6);\n            runScriptAndInstallSsh(client7, \"bootstrap\", 7);\n\n            expect(\n                  factory.create(eq(HostAndPort.fromParts(\"144.175.1.1\", 22)),\n                        eq(LoginCredentials.builder().user(\"defaultAdminUsername\").privateKey(Pems.PRIVATE_PKCS1_MARKER).build())))\n                  .andReturn(client1);\n            expect(\n                  factory.create(eq(HostAndPort.fromParts(\"144.175.1.2\", 22)),\n                        eq(LoginCredentials.builder().user(\"defaultAdminUsername\").privateKey(Pems.PRIVATE_PKCS1_MARKER).build())))\n                  .andReturn(client2);\n            expect(\n                  factory.create(eq(HostAndPort.fromParts(\"144.175.1.3\", 22)),\n                        eq(LoginCredentials.builder().user(\"defaultAdminUsername\").privateKey(Pems.PRIVATE_PKCS1_MARKER).build())))\n                  .andReturn(client3);\n            expect(\n                  factory.create(eq(HostAndPort.fromParts(\"144.175.1.4\", 22)),\n                        eq(LoginCredentials.builder().user(\"defaultAdminUsername\").privateKey(Pems.PRIVATE_PKCS1_MARKER).build())))\n                  .andReturn(client4);\n            expect(\n                  factory.create(eq(HostAndPort.fromParts(\"144.175.1.5\", 22)),\n                        eq(LoginCredentials.builder().user(\"defaultAdminUsername\").privateKey(Pems.PRIVATE_PKCS1_MARKER).build())))\n                  .andReturn(client5);\n            expect(\n                  factory.create(eq(HostAndPort.fromParts(\"144.175.1.6\", 22)),\n                        eq(LoginCredentials.builder().user(\"defaultAdminUsername\").privateKey(Pems.PRIVATE_PKCS1_MARKER).build())))\n                  .andReturn(client6);\n            expect(\n                  factory.create(eq(HostAndPort.fromParts(\"144.175.1.7\", 22)),\n                        eq(LoginCredentials.builder().user(\"defaultAdminUsername\").privateKey(Pems.PRIVATE_PKCS1_MARKER).build())))\n                  .andReturn(client7);\n\n            helloAndJava(client2);\n            helloAndJava(client3);\n            helloAndJava(client4);\n            helloAndJava(client5);\n            helloAndJava(client6);\n            helloAndJava(client7);\n\n            replay(factory);\n            replay(client1);\n            replay(client1New);\n            replay(client2);\n            replay(client2New);\n            replay(client2Foo);\n            replay(client3);\n            replay(client4);\n            replay(client5);\n            replay(client6);\n            replay(client7);\n\n            bind(SshClient.Factory.class).toInstance(factory);\n         }\n\n         private void runScriptAndService(SshClient client, SshClient clientNew) {\n            client.connect();\n\n            try {\n               String scriptName = \"configure-jetty\";\n               client.put(\"/tmp/init-\" + scriptName, Strings2.toStringAndClose(StubComputeServiceIntegrationTest.class\n                        .getResourceAsStream(\"/initscript_with_jetty.sh\")));\n               expect(client.exec(\"chmod 755 /tmp/init-\" + scriptName)).andReturn(EXEC_GOOD);\n               expect(client.exec(\"ln -fs /tmp/init-\" + scriptName + \" \" + scriptName)).andReturn(EXEC_GOOD);\n               expect(client.getUsername()).andReturn(\"root\").atLeastOnce();\n               expect(client.getHostAddress()).andReturn(\"localhost\").atLeastOnce();\n               expect(client.exec(\"/tmp/init-\" + scriptName + \" init\")).andReturn(EXEC_GOOD);\n               expect(client.exec(\"/tmp/init-\" + scriptName + \" start\")).andReturn(EXEC_GOOD);\n               expect(client.exec(\"/tmp/init-\" + scriptName + \" status\")).andReturn(EXEC_GOOD);\n               // next status says the script is done, since not found.\n               expect(client.exec(\"/tmp/init-\" + scriptName + \" status\")).andReturn(EXEC_BAD);\n               expect(client.exec(\"/tmp/init-\" + scriptName + \" stdout\")).andReturn(EXEC_GOOD);\n               expect(client.exec(\"/tmp/init-\" + scriptName + \" stderr\")).andReturn(EXEC_GOOD);\n               expect(client.exec(\"/tmp/init-\" + scriptName + \" exitstatus\")).andReturn(EXEC_RC_GOOD);\n\n               // note we have to reconnect here, as we updated the login user.\n               client.disconnect();\n\n               clientNew.connect();               \n               expect(clientNew.getUsername()).andReturn(\"web\").atLeastOnce();\n               expect(clientNew.getHostAddress()).andReturn(\"localhost\").atLeastOnce();\n               expect(clientNew.exec(\"head -1 /usr/local/jetty/VERSION.txt | cut -f1 -d ' '\\n\")).andReturn(EXEC_GOOD);\n               clientNew.disconnect();\n                              \n               clientNew.connect();\n               expect(clientNew.exec(\"java -fullversion\\n\")).andReturn(EXEC_GOOD);\n               clientNew.disconnect();\n\n               String startJetty = new StringBuilder()\n                  .append(\"JETTY_PORT=8080 nohup /usr/local/jetty/bin/jetty.sh start > start.log 2>&1 < /dev/null &\").append('\\n')\n                  .append(\"test $? && sleep 1\").append('\\n').toString();\n\n               clientNew.connect();\n               expect(clientNew.exec(startJetty)).andReturn(EXEC_GOOD);\n               clientNew.disconnect();\n\n               clientNew.connect();\n               expect(clientNew.exec(\"/usr/local/jetty/bin/jetty.sh stop\\n\")).andReturn(EXEC_GOOD);\n               clientNew.disconnect();\n\n               clientNew.connect();\n               expect(clientNew.exec(startJetty)).andReturn(EXEC_GOOD);\n               clientNew.disconnect();\n\n            } catch (IOException e) {\n               Throwables.propagate(e);\n            }\n            clientNew.disconnect();\n\n         }\n\n         private void runScriptAndInstallSsh(SshClient client, String scriptName, int nodeId) {\n            client.connect();\n\n            try {\n               runScript(client, scriptName, Strings2.toStringAndClose(StubComputeServiceIntegrationTest.class\n                        .getResourceAsStream(\"/initscript_with_java.sh\")), nodeId);\n            } catch (IOException e) {\n               Throwables.propagate(e);\n            }\n\n            client.disconnect();\n\n         }\n\n         private void runScript(SshClient client, String scriptName, String script, int nodeId) {\n            client.put(\"/tmp/init-\" + scriptName, script);\n            expect(client.exec(\"chmod 755 /tmp/init-\" + scriptName)).andReturn(EXEC_GOOD);\n            expect(client.exec(\"ln -fs /tmp/init-\" + scriptName + \" \" + scriptName)).andReturn(EXEC_GOOD);\n            expect(client.getUsername()).andReturn(\"root\").atLeastOnce();\n            expect(client.getHostAddress()).andReturn(nodeId + \"\").atLeastOnce();\n            expect(client.exec(\"/tmp/init-\" + scriptName + \" init\")).andReturn(EXEC_GOOD);\n            expect(client.exec(\"/tmp/init-\" + scriptName + \" start\")).andReturn(EXEC_GOOD);\n            expect(client.exec(\"/tmp/init-\" + scriptName + \" status\")).andReturn(EXEC_GOOD);\n            // next status says the script is done, since not found.\n            expect(client.exec(\"/tmp/init-\" + scriptName + \" status\")).andReturn(EXEC_BAD);\n            expect(client.exec(\"/tmp/init-\" + scriptName + \" stdout\")).andReturn(EXEC_GOOD);\n            expect(client.exec(\"/tmp/init-\" + scriptName + \" stderr\")).andReturn(EXEC_GOOD);\n            expect(client.exec(\"/tmp/init-\" + scriptName + \" exitstatus\")).andReturn(EXEC_RC_GOOD);\n         }\n\n         private void helloAndJava(SshClient client) {\n            client.connect();\n\n            expect(client.exec(\"echo hello\")).andReturn(new ExecResponse(\"hello\", \"\", 0));\n            expect(client.exec(\"java -version\")).andReturn(new ExecResponse(\"\", \"OpenJDK\", 0));\n\n            client.disconnect();\n         }\n\n      };\n   }\n\n   protected void assertNodeZero(Set<? extends NodeMetadata> metadataSet) {\n      // TODO: this fails so we override it.\n   }\n\n   public static Payload payloadEq(String value) {\n      reportMatcher(new PayloadEquals(value));\n      return null;\n   }\n\n   private static class PayloadEquals implements IArgumentMatcher {\n\n      private final Object expected;\n\n      public PayloadEquals(Object expected) {\n         this.expected = expected;\n      }\n\n      public boolean matches(Object actual) {\n         if (this.expected == null) {\n            return actual == null;\n         }\n         try {\n            String real = Strings2.toStringAndClose(((Payload) actual).openStream());\n            assertEquals(real, expected);\n            return true;\n         } catch (IOException e) {\n            Throwables.propagate(e);\n            return false;\n         }\n      }\n\n      public void appendTo(StringBuffer buffer) {\n         appendQuoting(buffer);\n         buffer.append(expected);\n         appendQuoting(buffer);\n      }\n\n      private void appendQuoting(StringBuffer buffer) {\n         if (expected instanceof String) {\n            buffer.append(\"\\\"\");\n         } else if (expected instanceof Character) {\n            buffer.append(\"'\");\n         }\n      }\n\n      @Override\n      public boolean equals(Object o) {\n         if (o == null || !this.getClass().equals(o.getClass()))\n            return false;\n         PayloadEquals other = (PayloadEquals) o;\n         return (this.expected == null && other.expected == null) ||\n                (this.expected != null && this.expected.equals(other.expected));\n      }\n\n      @Override\n      public int hashCode() {\n         throw new UnsupportedOperationException(\"hashCode() is not supported\");\n      }\n\n   }\n\n   @Override\n   protected void setupKeyPairForTest() {\n      keyPair = ImmutableMap.<String, String> of(\"public\", \"ssh-rsa\", \"private\", \"-----BEGIN RSA PRIVATE KEY-----\");\n   }\n\n   // TODO: I have absolutely no idea why I have to redeclare all this cruft. If\n   // I don't, then we\n   // get all sorts of not allowed to depend on errors.\n   @Override\n   public void testImagesCache() throws Exception {\n      super.testImagesCache();\n   }\n\n   @Override\n   public void testCompareSizes() throws Exception {\n      super.testCompareSizes();\n   }\n\n   @Test(enabled = true, dependsOnMethods = { \"testImagesCache\" })\n   public void testAScriptExecutionAfterBootWithBasicTemplate() throws Exception {\n      super.testAScriptExecutionAfterBootWithBasicTemplate();\n   }\n\n   @Test(enabled = false)\n   @Override\n   public void testWeCanCancelTasks() throws Exception {\n      // not sure how to do multithreading in a mock so that tests can work\n   }\n\n   @Test(enabled = true, dependsOnMethods = { \"testCompareSizes\" })\n   public void testCreateAndRunAService() throws Exception {\n      super.testCreateAndRunAService();\n   }\n\n   @Test(enabled = true, dependsOnMethods = \"testTemplateMatch\")\n   public void testConcurrentUseOfComputeServiceToCreateNodes() throws Exception {\n      super.testConcurrentUseOfComputeServiceToCreateNodes();\n   }\n\n   @Test(enabled = true, dependsOnMethods = \"testConcurrentUseOfComputeServiceToCreateNodes\")\n   public void testCreateTwoNodesWithRunScript() throws Exception {\n      super.testCreateTwoNodesWithRunScript();\n   }\n\n   @Test(enabled = true, dependsOnMethods = \"testCreateTwoNodesWithRunScript\")\n   public void testCreateAnotherNodeWithANewContextToEnsureSharedMemIsntRequired() throws Exception {\n      super.testCreateAnotherNodeWithANewContextToEnsureSharedMemIsntRequired();\n   }\n\n   @Test(enabled = true, dependsOnMethods = \"testCreateAnotherNodeWithANewContextToEnsureSharedMemIsntRequired\")\n   public void testCreateTwoNodesWithOneSpecifiedName() throws Exception {\n      super.testCreateTwoNodesWithOneSpecifiedName();\n   }\n\n\n   @Test(enabled = true, dependsOnMethods = \"testCreateAnotherNodeWithANewContextToEnsureSharedMemIsntRequired\")\n   public void testCredentialsCache() throws Exception {\n      super.testCredentialsCache();\n   }\n\n   @Test(enabled = true, dependsOnMethods = \"testCreateAnotherNodeWithANewContextToEnsureSharedMemIsntRequired\")\n   public void testGet() throws Exception {\n      super.testGet();\n   }\n\n   @Test(enabled = true, dependsOnMethods = \"testGet\")\n   public void testOptionToNotBlock() throws Exception {\n      super.testOptionToNotBlock();\n   }\n\n   @Test(enabled = true, dependsOnMethods = \"testGet\")\n   public void testReboot() throws Exception {\n      super.testReboot();\n   }\n\n   @Test(enabled = true, dependsOnMethods = \"testReboot\")\n   public void testSuspendResume() throws Exception {\n      super.testSuspendResume();\n   }\n\n   @Test(enabled = true, dependsOnMethods = { \"testImagesCache\" })\n   public void testTemplateMatch() throws Exception {\n      super.testTemplateMatch();\n   }\n\n   @Test(enabled = true, dependsOnMethods = \"testSuspendResume\")\n   public void testGetNodesWithDetails() throws Exception {\n      super.testGetNodesWithDetails();\n   }\n\n   @Test(enabled = true, dependsOnMethods = \"testSuspendResume\")\n   public void testListNodes() throws Exception {\n      super.testListNodes();\n   }\n\n   @Test(enabled = true, dependsOnMethods = \"testSuspendResume\")\n   public void testListNodesByIds() throws Exception {\n      super.testListNodesByIds();\n   }\n\n   @Test(enabled = true, dependsOnMethods = { \"testListNodes\", \"testGetNodesWithDetails\", \"testListNodesByIds\" })\n   public void testDestroyNodes() {\n      super.testDestroyNodes();\n   }\n\n   @Override\n   protected void waitGracePeriodForDestroyedNodes() {\n      // Do not wait\n   }\n\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/StubTemplateBuilderIntegrationTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute;\n\nimport java.util.Set;\n\nimport org.jclouds.compute.internal.BaseTemplateBuilderLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = { \"integration\", \"live\" })\npublic class StubTemplateBuilderIntegrationTest extends BaseTemplateBuilderLiveTest {\n\n   public StubTemplateBuilderIntegrationTest() {\n      provider = \"stub\";\n   }\n\n   @Override\n   protected Set<String> getIso3166Codes() {\n      return ImmutableSet.of();\n   }\n\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/callables/BlockUntilInitScriptStatusIsZeroThenReturnOutputTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.callables;\nimport static org.easymock.EasyMock.createMockBuilder;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.jclouds.compute.callables.BlockUntilInitScriptStatusIsZeroThenReturnOutput.loopUntilTrueOrThrowCancellationException;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.fail;\n\nimport java.util.concurrent.CancellationException;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.atomic.AtomicBoolean;\n\nimport org.jclouds.compute.callables.BlockUntilInitScriptStatusIsZeroThenReturnOutput.ExitStatusOfCommandGreaterThanZero;\nimport org.jclouds.compute.domain.ExecResponse;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadataBuilder;\nimport org.jclouds.scriptbuilder.InitScript;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Predicates;\nimport com.google.common.eventbus.EventBus;\nimport com.google.common.util.concurrent.AbstractFuture;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.common.util.concurrent.MoreExecutors;\n\n@Test(groups = \"unit\", singleThreaded = true, testName = \"BlockUntilInitScriptStatusIsZeroThenReturnOutputTest\")\npublic class BlockUntilInitScriptStatusIsZeroThenReturnOutputTest {\n\n   public void testloopUntilTrueOrThrowCancellationExceptionReturnsWhenPredicateIsTrue() {\n      AbstractFuture<ExecResponse> future = new AbstractFuture<ExecResponse>() {\n\n         @Override\n         public boolean isCancelled() {\n            return false;\n         }\n\n      };\n\n      Predicate<String> pred = loopUntilTrueOrThrowCancellationException(Predicates\n               .<String> alwaysTrue(), 1, 1, future);\n      assertEquals(pred.apply(\"foo\"), true);\n\n   }\n\n   public void testloopUntilTrueOrThrowCancellationExceptionReturnsWhenPredicateIsTrueSecondTimeWhileNotCancelled() {\n      AbstractFuture<ExecResponse> future = new AbstractFuture<ExecResponse>() {\n\n         @Override\n         public boolean isCancelled() {\n            return false;\n         }\n\n      };\n\n      Predicate<String> predicate = new Predicate<String>() {\n         AtomicBoolean bool = new AtomicBoolean();\n\n         @Override\n         public boolean apply(String input) {\n            return bool.getAndSet(true);\n         }\n\n      };\n\n      Predicate<String> pred = loopUntilTrueOrThrowCancellationException(predicate, 1, 1, future);\n      assertEquals(pred.apply(\"foo\"), true);\n\n   }\n\n   // need to break the loop when cancelled.\n   public void testloopUntilTrueOrThrowCancellationExceptionSkipsAndReturnsFalseOnCancelled() {\n      AbstractFuture<ExecResponse> future = new AbstractFuture<ExecResponse>() {\n\n         @Override\n         public boolean isCancelled() {\n            return true;\n         }\n\n      };\n      Predicate<String> pred = loopUntilTrueOrThrowCancellationException(Predicates.<String> alwaysFalse(), 1, 1,\n            future);\n      assertEquals(pred.apply(\"foo\"), false);\n\n   }\n\n   public void testExitStatusOfCommandGreaterThanZeroTrueWhen1() {\n\n      SudoAwareInitManager commandRunner = createMockBuilder(SudoAwareInitManager.class).addMockedMethod(\"runAction\")\n               .createStrictMock();\n      expect(commandRunner.runAction(\"status\")).andReturn(new ExecResponse(\"\", \"\", 1));\n      replay(commandRunner);\n\n      Predicate<String> pred = new ExitStatusOfCommandGreaterThanZero(commandRunner);\n      assertEquals(pred.apply(\"status\"), true);\n\n      verify(commandRunner);\n\n   }\n\n   public void testExitStatusOfCommandGreaterThanZeroFalseWhen0() {\n\n      SudoAwareInitManager commandRunner = createMockBuilder(SudoAwareInitManager.class).addMockedMethod(\"runAction\")\n               .createStrictMock();\n      expect(commandRunner.runAction(\"status\")).andReturn(new ExecResponse(\"\", \"\", 0));\n      replay(commandRunner);\n\n      Predicate<String> pred = new ExitStatusOfCommandGreaterThanZero(commandRunner);\n      assertEquals(pred.apply(\"status\"), false);\n\n      verify(commandRunner);\n\n   }\n\n   EventBus eventBus = new EventBus();\n\n   public void testExitStatusZeroReturnsExecResponse() throws InterruptedException, ExecutionException {\n      ListeningExecutorService userExecutor = MoreExecutors.newDirectExecutorService();\n      Predicate<String> notRunningAnymore = Predicates.alwaysTrue();\n      SudoAwareInitManager commandRunner = createMockBuilder(SudoAwareInitManager.class).addMockedMethod(\"runAction\")\n               .addMockedMethod(\"getStatement\").addMockedMethod(\"getNode\").addMockedMethod(\"toString\")\n               .createStrictMock();\n      InitScript initScript = createMockBuilder(InitScript.class).addMockedMethod(\"getInstanceName\").createStrictMock();\n\n      expect(commandRunner.runAction(\"stdout\")).andReturn(new ExecResponse(\"stdout\", \"\", 0));\n      expect(commandRunner.runAction(\"stderr\")).andReturn(new ExecResponse(\"stderr\", \"\", 0));\n      expect(commandRunner.runAction(\"exitstatus\")).andReturn(new ExecResponse(\"444\\n\", \"\", 0));\n\n      toStringAndEventBusExpectations(commandRunner, initScript);\n\n      replay(commandRunner, initScript);\n\n      BlockUntilInitScriptStatusIsZeroThenReturnOutput future = new BlockUntilInitScriptStatusIsZeroThenReturnOutput(\n               userExecutor, eventBus, notRunningAnymore, commandRunner);\n\n      future.run();\n\n      assertEquals(future.get(), new ExecResponse(\"stdout\", \"stderr\", 444));\n\n      verify(commandRunner, initScript);\n\n   }\n\n   public void testFirstExitStatusOneButSecondExitStatusZeroReturnsExecResponse() throws InterruptedException,\n            ExecutionException {\n      ListeningExecutorService userExecutor = MoreExecutors.newDirectExecutorService();\n      Predicate<String> notRunningAnymore = Predicates.alwaysTrue();\n\n      SudoAwareInitManager commandRunner = createMockBuilder(SudoAwareInitManager.class).addMockedMethod(\"runAction\")\n               .addMockedMethod(\"getStatement\").addMockedMethod(\"getNode\").addMockedMethod(\"toString\")\n               .createStrictMock();\n      InitScript initScript = createMockBuilder(InitScript.class).addMockedMethod(\"getInstanceName\").createStrictMock();\n\n      // exit status is 1 means we are still running!\n      expect(commandRunner.runAction(\"stdout\")).andReturn(new ExecResponse(\"\", \"\", 0));\n      expect(commandRunner.runAction(\"stderr\")).andReturn(new ExecResponse(\"\", \"\", 0));\n      expect(commandRunner.runAction(\"exitstatus\")).andReturn(new ExecResponse(\"\", \"\", 1));\n\n      // second time around, it did stop\n      expect(commandRunner.runAction(\"stdout\")).andReturn(new ExecResponse(\"stdout\", \"\", 0));\n      expect(commandRunner.runAction(\"stderr\")).andReturn(new ExecResponse(\"stderr\", \"\", 0));\n      expect(commandRunner.runAction(\"exitstatus\")).andReturn(new ExecResponse(\"444\\n\", \"\", 0));\n\n      toStringAndEventBusExpectations(commandRunner, initScript);\n\n      replay(commandRunner, initScript);\n\n      BlockUntilInitScriptStatusIsZeroThenReturnOutput future = new BlockUntilInitScriptStatusIsZeroThenReturnOutput(\n               userExecutor, eventBus, notRunningAnymore, commandRunner);\n\n      future.run();\n\n      assertEquals(future.get(), new ExecResponse(\"stdout\", \"stderr\", 444));\n\n      verify(commandRunner, initScript);\n\n   }\n\n   public void testCancelInterruptStopsCommand() throws InterruptedException, ExecutionException {\n      ListeningExecutorService userExecutor = MoreExecutors.newDirectExecutorService();\n      Predicate<String> notRunningAnymore = Predicates.alwaysTrue();\n      SudoAwareInitManager commandRunner = createMockBuilder(SudoAwareInitManager.class).addMockedMethod(\n               \"refreshAndRunAction\").addMockedMethod(\"runAction\").addMockedMethod(\"getStatement\").addMockedMethod(\n               \"getNode\").addMockedMethod(\"toString\").createStrictMock();\n      InitScript initScript = createMockBuilder(InitScript.class).addMockedMethod(\"getInstanceName\").createStrictMock();\n\n      // log what we are stopping\n      expect(commandRunner.getStatement()).andReturn(initScript);\n      expect(initScript.getInstanceName()).andReturn(\"init-script\");\n\n      // stop\n      expect(commandRunner.refreshAndRunAction(\"stop\")).andReturn(new ExecResponse(\"stdout\", \"\", 0));\n\n      // create cancellation exception\n      expect(commandRunner.getStatement()).andReturn(initScript);\n      expect(initScript.getInstanceName()).andReturn(\"init-script\");\n      expect(commandRunner.getNode()).andReturn(\n               new NodeMetadataBuilder().ids(\"id\").status(NodeMetadata.Status.RUNNING).build()).atLeastOnce();\n\n      // StatementOnNodeFailure event\n      expect(commandRunner.getStatement()).andReturn(initScript);\n      expect(commandRunner.getNode()).andReturn(\n               new NodeMetadataBuilder().ids(\"id\").status(NodeMetadata.Status.RUNNING).build()).atLeastOnce();\n\n      replay(commandRunner, initScript);\n\n      BlockUntilInitScriptStatusIsZeroThenReturnOutput future = new BlockUntilInitScriptStatusIsZeroThenReturnOutput(\n               userExecutor, eventBus, notRunningAnymore, commandRunner);\n\n      future.cancel(true);\n\n      try {\n         future.get();\n         fail();\n      } catch (CancellationException e) {\n\n      }\n\n      verify(commandRunner, initScript);\n\n   }\n\n   public void testCancelDontInterruptLeavesCommandRunningAndReturnsLastStatus() throws InterruptedException,\n            ExecutionException {\n      ListeningExecutorService userExecutor = MoreExecutors.newDirectExecutorService();\n      Predicate<String> notRunningAnymore = Predicates.alwaysTrue();\n      SudoAwareInitManager commandRunner = createMockBuilder(SudoAwareInitManager.class).addMockedMethod(\"runAction\")\n               .addMockedMethod(\"getStatement\").addMockedMethod(\"getNode\").addMockedMethod(\"toString\")\n               .createStrictMock();\n      InitScript initScript = createMockBuilder(InitScript.class).addMockedMethod(\"getInstanceName\").createStrictMock();\n\n      expect(commandRunner.runAction(\"stdout\")).andReturn(new ExecResponse(\"stillrunning\", \"\", 0));\n      expect(commandRunner.runAction(\"stderr\")).andReturn(new ExecResponse(\"\", \"\", 0));\n      expect(commandRunner.runAction(\"exitstatus\")).andReturn(new ExecResponse(\"\", \"\", 1));\n\n      toStringAndEventBusExpectations(commandRunner, initScript);\n\n      replay(commandRunner, initScript);\n\n      BlockUntilInitScriptStatusIsZeroThenReturnOutput future = new BlockUntilInitScriptStatusIsZeroThenReturnOutput(\n               userExecutor, eventBus, notRunningAnymore, commandRunner);\n\n      future.cancel(false);\n\n      // note if this didn't cancel properly, the loop would never end!\n      future.run();\n\n      try {\n         future.get();\n         fail();\n      } catch (CancellationException e) {\n\n      }\n      verify(commandRunner, initScript);\n\n   }\n\n   private void toStringAndEventBusExpectations(SudoAwareInitManager commandRunner, InitScript initScript) {\n      toStringExpectations(commandRunner, initScript);\n      expect(commandRunner.getStatement()).andReturn(initScript);\n      expect(commandRunner.getNode()).andReturn(\n               new NodeMetadataBuilder().ids(\"id\").status(NodeMetadata.Status.RUNNING).build());\n   }\n\n   private void toStringExpectations(SudoAwareInitManager commandRunner, InitScript initScript) {\n      expect(commandRunner.getStatement()).andReturn(initScript);\n      expect(initScript.getInstanceName()).andReturn(\"init-script\");\n   }\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/callables/InitScriptConfigurationForTasksTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.callables;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.name.Names;\n\n@Test(groups = \"unit\", singleThreaded = true, testName = \"InitScriptConfigurationForTasksTest\")\npublic class InitScriptConfigurationForTasksTest {\n\n   public void testDefaults() {\n      InitScriptConfigurationForTasks config = InitScriptConfigurationForTasks.create();\n      assertEquals(config.getAnonymousTaskSuffixSupplier().toString(), \"currentTimeMillis()\");\n      assertEquals(config.getBasedir(), \"/tmp\");\n      assertEquals(config.getInitScriptPattern(), \"/tmp/init-%s\");\n   }\n\n   public void testPatternUpdatesBasedir() {\n      InitScriptConfigurationForTasks config = InitScriptConfigurationForTasks.create();\n      config.initScriptPattern(\"/var/foo-init-%s\");\n      assertEquals(config.getBasedir(), \"/var\");\n      assertEquals(config.getInitScriptPattern(), \"/var/foo-init-%s\");\n   }\n\n   public void testPatternUpdatesBasedirGuice() {\n      InitScriptConfigurationForTasks config = Guice.createInjector(new AbstractModule() {\n\n         @Override\n         protected void configure() {\n            bindConstant().annotatedWith(Names.named(InitScriptConfigurationForTasks.PROPERTY_INIT_SCRIPT_PATTERN)).to(\n                     \"/var/foo-init-%s\");\n         }\n\n      }).getInstance(InitScriptConfigurationForTasks.class);\n      config.initScriptPattern(\"/var/foo-init-%s\");\n      assertEquals(config.getBasedir(), \"/var\");\n      assertEquals(config.getInitScriptPattern(), \"/var/foo-init-%s\");\n   }\n\n   public void testCurrentTimeSupplier() throws InterruptedException {\n      InitScriptConfigurationForTasks config = InitScriptConfigurationForTasks.create();\n      long time1 = Long.parseLong(config.getAnonymousTaskSuffixSupplier().get());\n      assert time1 <= System.currentTimeMillis();\n      Thread.sleep(10);\n      long time2 = Long.parseLong(config.getAnonymousTaskSuffixSupplier().get());\n      assert time2 <= System.currentTimeMillis();\n      assert time2 > time1;\n   }\n\n   public void testIncrementingTimeSupplier() throws InterruptedException {\n      InitScriptConfigurationForTasks config = InitScriptConfigurationForTasks.create()\n               .appendIncrementingNumberToAnonymousTaskNames();\n      assertEquals(config.getAnonymousTaskSuffixSupplier().get(), \"0\");\n      assertEquals(config.getAnonymousTaskSuffixSupplier().get(), \"1\");\n   }\n\n   @Test\n   public void testInitScriptPattern() throws Exception {\n      InitScriptConfigurationForTasks config = InitScriptConfigurationForTasks.create();\n      config.initScriptPattern(\"/var/tmp/jclouds-%s\");\n      assertEquals(config.getBasedir(), \"/var/tmp\");\n      assertEquals(config.getInitScriptPattern(), \"/var/tmp/jclouds-%s\");\n   }\n\n   @Test\n   public void testInitScriptPatternAtRoot() throws Exception {\n      InitScriptConfigurationForTasks config = InitScriptConfigurationForTasks.create();\n      config.initScriptPattern(\"/jclouds-%s\");\n      assertEquals(config.getBasedir(), \"/\");\n      assertEquals(config.getInitScriptPattern(), \"/jclouds-%s\");\n   }\n   \n   @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = \"initScriptPattern must be a UNIX-style path starting at the root \\\\(/\\\\)\")\n   public void testInitScriptPatternIsUnixLike() {\n      InitScriptConfigurationForTasks config = InitScriptConfigurationForTasks.create();\n      config.initScriptPattern(\"jclouds-%s/foo\");\n   }\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/callables/RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilCompleteTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.callables;\n\nimport static com.google.common.util.concurrent.MoreExecutors.newDirectExecutorService;\nimport static com.google.inject.name.Names.named;\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.jclouds.Constants.PROPERTY_USER_THREADS;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_SCRIPT_COMPLETE;\nimport static org.jclouds.scriptbuilder.domain.Statements.exec;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.compute.domain.ExecResponse;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadata.Status;\nimport org.jclouds.compute.domain.NodeMetadataBuilder;\nimport org.jclouds.compute.options.RunScriptOptions;\nimport org.jclouds.compute.reference.ComputeServiceConstants.Timeouts;\nimport org.jclouds.concurrent.config.ExecutorServiceModule;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.scriptbuilder.InitScript;\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.jclouds.scriptbuilder.domain.Statement;\nimport org.jclouds.ssh.SshClient;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Functions;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.eventbus.EventBus;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport com.google.inject.assistedinject.FactoryModuleBuilder;\n\n@Test(groups = \"unit\", singleThreaded = true, testName = \"RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilCompleteTest\")\npublic class RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilCompleteTest {\n   Injector injector = Guice.createInjector(new ExecutorServiceModule(newDirectExecutorService()),\n         new AbstractModule() {\n            protected void configure() {\n               bindConstant().annotatedWith(named(PROPERTY_USER_THREADS)).to(1);\n               bindConstant().annotatedWith(named(TIMEOUT_SCRIPT_COMPLETE)).to(100);\n               install(new FactoryModuleBuilder().build(BlockUntilInitScriptStatusIsZeroThenReturnOutput.Factory.class));\n            }\n         });\n   EventBus eventBus = new EventBus();\n   BlockUntilInitScriptStatusIsZeroThenReturnOutput.Factory statusFactory = injector\n         .getInstance(BlockUntilInitScriptStatusIsZeroThenReturnOutput.Factory.class);\n\n   // fail faster than normal\n   Timeouts timeouts = injector.getInstance(Timeouts.class);\n\n   @Test(expectedExceptions = IllegalStateException.class)\n   public void testWithoutInitThrowsIllegalStateException() {\n      Statement command = exec(\"doFoo\");\n      NodeMetadata node = new NodeMetadataBuilder().ids(\"id\").status(Status.RUNNING).credentials(\n            LoginCredentials.builder().user(\"tester\").password(\"testpassword!\").build()).build();\n\n      SshClient sshClient = createMock(SshClient.class);\n\n      replay(sshClient);\n\n      RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilComplete testMe = new RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilComplete(\n               statusFactory, timeouts, Functions.forMap(ImmutableMap.of(node, sshClient)),\n               eventBus, InitScriptConfigurationForTasks.create().appendIncrementingNumberToAnonymousTaskNames(), node, command,\n               new RunScriptOptions());\n\n      testMe.call();\n   }\n\n   public void testDefault() {\n      Statement command = exec(\"doFoo\");\n      NodeMetadata node = new NodeMetadataBuilder().ids(\"id\").status(Status.RUNNING)\n            .credentials(LoginCredentials.builder().user(\"tester\").password(\"testpassword!\").build()).build();\n\n      SshClient sshClient = createMock(SshClient.class);\n\n      InitScript init = InitScript.builder().name(\"jclouds-script-0\").home(\"/tmp/jclouds-script-0\").run(command)\n            .build();\n\n      sshClient.connect();\n      sshClient.put(\"/tmp/init-jclouds-script-0\", init.render(OsFamily.UNIX));\n      expect(sshClient.getUsername()).andReturn(\"tester\").atLeastOnce();\n      expect(sshClient.getHostAddress()).andReturn(\"somewhere.example.com\").atLeastOnce();\n\n      // setup script as default user\n      expect(sshClient.exec(\"chmod 755 /tmp/init-jclouds-script-0\")).andReturn(new ExecResponse(\"\", \"\", 0));\n      expect(sshClient.exec(\"ln -fs /tmp/init-jclouds-script-0 jclouds-script-0\")).andReturn(\n               new ExecResponse(\"\", \"\", 0));\n      expect(sshClient.exec(\"/tmp/init-jclouds-script-0 init\")).andReturn(new ExecResponse(\"\", \"\", 0));\n\n      // start script as root via sudo, note that since there's no adminPassword we do a straight\n      // sudo\n      expect(sshClient.exec(\"sudo /tmp/init-jclouds-script-0 start\")).andReturn(new ExecResponse(\"\", \"\", 0));\n\n      // signal the command completed\n      expect(sshClient.exec(\"/tmp/init-jclouds-script-0 status\")).andReturn(new ExecResponse(\"\", \"\", 1)).times(1);\n      expect(sshClient.exec(\"/tmp/init-jclouds-script-0 stdout\")).andReturn(new ExecResponse(\"out\", \"\", 0));\n      expect(sshClient.exec(\"/tmp/init-jclouds-script-0 stderr\")).andReturn(new ExecResponse(\"err\", \"\", 0));\n      expect(sshClient.exec(\"/tmp/init-jclouds-script-0 exitstatus\")).andReturn(new ExecResponse(\"0\", \"\", 0));\n\n      sshClient.disconnect();\n      replay(sshClient);\n\n      RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilComplete testMe = new RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilComplete(\n               statusFactory, timeouts, Functions.forMap(ImmutableMap.of(node, sshClient)),\n               eventBus, InitScriptConfigurationForTasks.create().appendIncrementingNumberToAnonymousTaskNames(), node, command,\n               new RunScriptOptions());\n\n      assertEquals(testMe.getInitFile(), \"/tmp/init-jclouds-script-0\");\n      assertEquals(testMe.getNode(), node);\n      assertEquals(testMe.getStatement(), init);\n\n      testMe.init();\n      \n      assertEquals(testMe.call(), new ExecResponse(\"out\", \"err\", 0));\n\n      verify(sshClient);\n   }\n\n   public void testWithSudoPassword() {\n      Statement command = exec(\"doFoo\");\n      NodeMetadata node = new NodeMetadataBuilder().ids(\"id\").status(Status.RUNNING).credentials(\n            LoginCredentials.builder().user(\"tester\").password(\"testpassword!\").authenticateSudo(true).build()).build();\n\n      SshClient sshClient = createMock(SshClient.class);\n\n      InitScript init = InitScript.builder().name(\"jclouds-script-0\").home(\"/tmp/jclouds-script-0\").run(command)\n            .build();\n\n      sshClient.connect();\n      sshClient.put(\"/tmp/init-jclouds-script-0\", init.render(OsFamily.UNIX));\n      expect(sshClient.getUsername()).andReturn(\"tester\").atLeastOnce();\n      expect(sshClient.getHostAddress()).andReturn(\"somewhere.example.com\").atLeastOnce();\n\n      // setup script as default user\n      expect(sshClient.exec(\"chmod 755 /tmp/init-jclouds-script-0\")).andReturn(new ExecResponse(\"\", \"\", 0));\n      expect(sshClient.exec(\"ln -fs /tmp/init-jclouds-script-0 jclouds-script-0\")).andReturn(\n               new ExecResponse(\"\", \"\", 0));\n      expect(sshClient.exec(\"/tmp/init-jclouds-script-0 init\")).andReturn(new ExecResponse(\"\", \"\", 0));\n\n      // since there's an adminPassword we must pass this in\n      expect(sshClient.exec(\"echo 'testpassword!'|sudo -S /tmp/init-jclouds-script-0 start\")).andReturn(new ExecResponse(\"\", \"\", 0));\n\n      // signal the command completed\n      expect(sshClient.exec(\"/tmp/init-jclouds-script-0 status\")).andReturn(new ExecResponse(\"\", \"\", 1));\n      expect(sshClient.exec(\"/tmp/init-jclouds-script-0 stdout\")).andReturn(new ExecResponse(\"out\", \"\", 0));\n      expect(sshClient.exec(\"/tmp/init-jclouds-script-0 stderr\")).andReturn(new ExecResponse(\"err\", \"\", 0));\n      expect(sshClient.exec(\"/tmp/init-jclouds-script-0 exitstatus\")).andReturn(new ExecResponse(\"0\", \"\", 0));\n\n      sshClient.disconnect();\n      replay(sshClient);\n\n      RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilComplete testMe = new RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilComplete(\n               statusFactory, timeouts, Functions.forMap(ImmutableMap.of(node, sshClient)),\n               eventBus, InitScriptConfigurationForTasks.create().appendIncrementingNumberToAnonymousTaskNames(), node, command,\n               new RunScriptOptions());\n\n      assertEquals(testMe.getInitFile(), \"/tmp/init-jclouds-script-0\");\n      assertEquals(testMe.getNode(), node);\n      assertEquals(testMe.getStatement(), init);\n\n      testMe.init();\n      \n      assertEquals(testMe.call(), new ExecResponse(\"out\", \"err\", 0));\n      \n      verify(sshClient);\n   }\n\n   /**\n    * in a couple versions of ubuntu on aws-ec2, status returneds no pid (ex. empty stdout w/exit code 1) transiently. sadly, we need to doublecheck status before assuming it has failed.\n    * \n    */\n   public void testDoublecheckStatusInCaseTransientlyWrong() {\n      Statement command = exec(\"doFoo\");\n      NodeMetadata node = new NodeMetadataBuilder().ids(\"id\").status(Status.RUNNING).credentials(\n            LoginCredentials.builder().user(\"tester\").password(\"testpassword!\").authenticateSudo(true).build()).build();\n\n      SshClient sshClient = createMock(SshClient.class);\n\n      InitScript init = InitScript.builder().name(\"jclouds-script-0\").home(\"/tmp/jclouds-script-0\").run(command)\n            .build();\n\n      sshClient.connect();\n      sshClient.put(\"/tmp/init-jclouds-script-0\", init.render(OsFamily.UNIX));\n      expect(sshClient.getUsername()).andReturn(\"tester\").atLeastOnce();\n      expect(sshClient.getHostAddress()).andReturn(\"somewhere.example.com\").atLeastOnce();\n\n      // setup script as default user\n      expect(sshClient.exec(\"chmod 755 /tmp/init-jclouds-script-0\")).andReturn(new ExecResponse(\"\", \"\", 0));\n      expect(sshClient.exec(\"ln -fs /tmp/init-jclouds-script-0 jclouds-script-0\")).andReturn(\n               new ExecResponse(\"\", \"\", 0));\n      expect(sshClient.exec(\"/tmp/init-jclouds-script-0 init\")).andReturn(new ExecResponse(\"\", \"\", 0));\n\n      // since there's an adminPassword we must pass this in\n      expect(sshClient.exec(\"echo 'testpassword!'|sudo -S /tmp/init-jclouds-script-0 start\")).andReturn(new ExecResponse(\"\", \"\", 0));\n\n      // signal the command completed\n      expect(sshClient.exec(\"/tmp/init-jclouds-script-0 status\")).andReturn(new ExecResponse(\"8001\", \"\", 0));\n      expect(sshClient.exec(\"/tmp/init-jclouds-script-0 status\")).andReturn(new ExecResponse(\"\", \"\", 1));\n      expect(sshClient.exec(\"/tmp/init-jclouds-script-0 stdout\")).andReturn(new ExecResponse(\"out\", \"\", 0));\n      expect(sshClient.exec(\"/tmp/init-jclouds-script-0 stderr\")).andReturn(new ExecResponse(\"err\", \"\", 0));\n      expect(sshClient.exec(\"/tmp/init-jclouds-script-0 exitstatus\")).andReturn(new ExecResponse(\"0\", \"\", 0));\n\n      sshClient.disconnect();\n      replay(sshClient);\n\n      RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilComplete testMe = new RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilComplete(\n               statusFactory, timeouts, Functions.forMap(ImmutableMap.of(node, sshClient)),\n               eventBus, InitScriptConfigurationForTasks.create().appendIncrementingNumberToAnonymousTaskNames(), node, command,\n               new RunScriptOptions());\n\n      assertEquals(testMe.getInitFile(), \"/tmp/init-jclouds-script-0\");\n      assertEquals(testMe.getNode(), node);\n      assertEquals(testMe.getStatement(), init);\n\n      testMe.init();\n      \n      assertEquals(testMe.call(), new ExecResponse(\"out\", \"err\", 0));\n      \n      verify(sshClient);\n   }\n   \n   public void testNotRoot() {\n      Statement command = exec(\"doFoo\");\n      NodeMetadata node = new NodeMetadataBuilder().ids(\"id\").status(Status.RUNNING).credentials(\n            LoginCredentials.builder().user(\"tester\").password(\"testpassword!\").authenticateSudo(true).build()).build();\n\n      SshClient sshClient = createMock(SshClient.class);\n\n      InitScript init = InitScript.builder().name(\"jclouds-script-0\").home(\"/tmp/jclouds-script-0\").run(command)\n            .build();\n\n      sshClient.connect();\n      sshClient.put(\"/tmp/init-jclouds-script-0\", init.render(OsFamily.UNIX));\n      expect(sshClient.getUsername()).andReturn(\"tester\").atLeastOnce();\n      expect(sshClient.getHostAddress()).andReturn(\"somewhere.example.com\").atLeastOnce();\n\n      // setup script as default user\n      expect(sshClient.exec(\"chmod 755 /tmp/init-jclouds-script-0\")).andReturn(new ExecResponse(\"\", \"\", 0));\n      expect(sshClient.exec(\"ln -fs /tmp/init-jclouds-script-0 jclouds-script-0\")).andReturn(\n               new ExecResponse(\"\", \"\", 0));\n      expect(sshClient.exec(\"/tmp/init-jclouds-script-0 init\")).andReturn(new ExecResponse(\"\", \"\", 0));\n\n      // kick off as current user\n      expect(sshClient.exec(\"/tmp/init-jclouds-script-0 start\")).andReturn(new ExecResponse(\"\", \"\", 0));\n\n      // signal the command completed\n      expect(sshClient.exec(\"/tmp/init-jclouds-script-0 status\")).andReturn(new ExecResponse(\"\", \"\", 1));\n      expect(sshClient.exec(\"/tmp/init-jclouds-script-0 stdout\")).andReturn(new ExecResponse(\"out\", \"\", 0));\n      expect(sshClient.exec(\"/tmp/init-jclouds-script-0 stderr\")).andReturn(new ExecResponse(\"err\", \"\", 0));\n      expect(sshClient.exec(\"/tmp/init-jclouds-script-0 exitstatus\")).andReturn(new ExecResponse(\"0\", \"\", 0));\n\n      sshClient.disconnect();\n      replay(sshClient);\n\n      RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilComplete testMe = new RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilComplete(\n               statusFactory, timeouts, Functions.forMap(ImmutableMap.of(node, sshClient)),\n               eventBus, InitScriptConfigurationForTasks.create().appendIncrementingNumberToAnonymousTaskNames(), node, command,\n               new RunScriptOptions().runAsRoot(false));\n\n      assertEquals(testMe.getInitFile(), \"/tmp/init-jclouds-script-0\");\n      assertEquals(testMe.getNode(), node);\n      assertEquals(testMe.getStatement(), init);\n\n      testMe.init();\n      \n      assertEquals(testMe.call(), new ExecResponse(\"out\", \"err\", 0));\n\n      verify(sshClient);\n   }\n   \n   public void testBadReturnCode() {\n      Statement command = exec(\"doFoo\");\n      NodeMetadata node = new NodeMetadataBuilder().ids(\"badreturncode\").status(Status.RUNNING).credentials(\n            LoginCredentials.builder().user(\"tester\").password(\"testpassword!\").authenticateSudo(true).build()).build();\n      \n      SshClient sshClient = createMock(SshClient.class);\n\n      InitScript init = InitScript.builder().name(\"jclouds-script-0\").home(\"/tmp/jclouds-script-0\").run(command)\n            .build();\n\n      sshClient.connect();\n      sshClient.put(\"/tmp/init-jclouds-script-0\", init.render(OsFamily.UNIX));\n      expect(sshClient.getUsername()).andReturn(\"tester\").atLeastOnce();\n      expect(sshClient.getHostAddress()).andReturn(\"somewhere.example.com\").atLeastOnce();\n\n      // setup script as default user\n      expect(sshClient.exec(\"chmod 755 /tmp/init-jclouds-script-0\")).andReturn(new ExecResponse(\"\", \"\", 0));\n      expect(sshClient.exec(\"ln -fs /tmp/init-jclouds-script-0 jclouds-script-0\")).andReturn(\n               new ExecResponse(\"\", \"\", 0));\n      expect(sshClient.exec(\"/tmp/init-jclouds-script-0 init\")).andReturn(new ExecResponse(\"\", \"\", 0));\n\n      // kick off as current user\n      expect(sshClient.exec(\"/tmp/init-jclouds-script-0 start\")).andReturn(new ExecResponse(\"\", \"\", 0));\n\n      // signal the command completed\n      expect(sshClient.exec(\"/tmp/init-jclouds-script-0 status\")).andReturn(new ExecResponse(\"\", \"\", 1));\n      expect(sshClient.exec(\"/tmp/init-jclouds-script-0 stdout\")).andReturn(new ExecResponse(\"out\", \"\", 0));\n      expect(sshClient.exec(\"/tmp/init-jclouds-script-0 stderr\")).andReturn(new ExecResponse(\"err\", \"\", 0));\n      expect(sshClient.exec(\"/tmp/init-jclouds-script-0 exitstatus\")).andReturn(new ExecResponse(\"1\", \"\", 0));\n\n      sshClient.disconnect();\n      replay(sshClient);\n\n      RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilComplete testMe = new RunScriptOnNodeAsInitScriptUsingSshAndBlockUntilComplete(\n               statusFactory, timeouts, Functions.forMap(ImmutableMap.of(node, sshClient)),\n               eventBus, InitScriptConfigurationForTasks.create().appendIncrementingNumberToAnonymousTaskNames(), node, command,\n               new RunScriptOptions().runAsRoot(false));\n\n      assertEquals(testMe.getInitFile(), \"/tmp/init-jclouds-script-0\");\n      assertEquals(testMe.getNode(), node);\n      assertEquals(testMe.getStatement(), init);\n\n      testMe.init();\n      \n      assertEquals(testMe.call(), new ExecResponse(\"out\", \"err\", 1));\n\n      verify(sshClient);\n   }\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/callables/RunScriptOnNodeAsInitScriptUsingSshTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.callables;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.jclouds.scriptbuilder.domain.Statements.exec;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.compute.domain.ExecResponse;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadataBuilder;\nimport org.jclouds.compute.domain.NodeMetadata.Status;\nimport org.jclouds.compute.options.RunScriptOptions;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.scriptbuilder.InitScript;\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.jclouds.scriptbuilder.domain.Statement;\nimport org.jclouds.ssh.SshClient;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Functions;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.eventbus.EventBus;\n\n@Test(groups = \"unit\", singleThreaded = true, testName = \"RunScriptOnNodeAsInitScriptUsingSshTest\")\npublic class RunScriptOnNodeAsInitScriptUsingSshTest {\n   EventBus eventBus = new EventBus();\n\n   @Test(expectedExceptions = IllegalStateException.class)\n   public void testWithoutInitThrowsIllegalStateException() {\n      Statement command = exec(\"doFoo\");\n      NodeMetadata node = new NodeMetadataBuilder().ids(\"id\").status(Status.RUNNING).credentials(\n               LoginCredentials.builder().user(\"tester\").password(\"notalot\").build()).build();\n\n      SshClient sshClient = createMock(SshClient.class);\n\n      replay(sshClient);\n\n      RunScriptOnNodeAsInitScriptUsingSsh testMe = new RunScriptOnNodeAsInitScriptUsingSsh(Functions\n               .forMap(ImmutableMap.of(node, sshClient)), eventBus, InitScriptConfigurationForTasks.create()\n               .appendIncrementingNumberToAnonymousTaskNames(), node, command, new RunScriptOptions());\n\n      testMe.call();\n   }\n\n   public void testDefault() {\n      Statement command = exec(\"doFoo\");\n      NodeMetadata node = new NodeMetadataBuilder().ids(\"id\").status(Status.RUNNING).credentials(\n            LoginCredentials.builder().user(\"tester\").password(\"notalot\").build()).build();\n\n      SshClient sshClient = createMock(SshClient.class);\n\n      InitScript init = InitScript.builder().name(\"jclouds-script-0\").home(\"/tmp/jclouds-script-0\").run(command)\n            .build();\n\n      sshClient.connect();\n      sshClient.put(\"/tmp/init-jclouds-script-0\", init.render(OsFamily.UNIX));\n      expect(sshClient.getUsername()).andReturn(\"tester\").atLeastOnce();\n      expect(sshClient.getHostAddress()).andReturn(\"somewhere.example.com\").atLeastOnce();\n      \n      // setup script as default user\n      expect(sshClient.exec(\"chmod 755 /tmp/init-jclouds-script-0\")).andReturn(new ExecResponse(\"\", \"\", 0));\n      expect(sshClient.exec(\"ln -fs /tmp/init-jclouds-script-0 jclouds-script-0\")).andReturn(new ExecResponse(\"\", \"\", 0));\n      expect(sshClient.exec(\"/tmp/init-jclouds-script-0 init\")).andReturn(new ExecResponse(\"\", \"\", 0));\n      \n      // start script as root via sudo, note that since there's no adminPassword we do a straight sudo\n      expect(sshClient.exec(\"sudo /tmp/init-jclouds-script-0 start\")).andReturn(new ExecResponse(\"\", \"\", 0));\n\n      \n      sshClient.disconnect();\n      replay(sshClient);\n\n      RunScriptOnNodeAsInitScriptUsingSsh testMe = new RunScriptOnNodeAsInitScriptUsingSsh(Functions\n               .forMap(ImmutableMap.of(node, sshClient)), eventBus, InitScriptConfigurationForTasks.create()\n               .appendIncrementingNumberToAnonymousTaskNames(), node, command, new RunScriptOptions());\n\n      assertEquals(testMe.getInitFile(), \"/tmp/init-jclouds-script-0\");\n      assertEquals(testMe.getNode(), node);\n      assertEquals(testMe.getStatement(), init);\n\n      testMe.init();\n      testMe.call();\n      verify(sshClient);\n   }\n\n\n   public void testWithSudoPassword() {\n      Statement command = exec(\"doFoo\");\n      NodeMetadata node = new NodeMetadataBuilder().ids(\"id\").status(Status.RUNNING).credentials(\n            LoginCredentials.builder().user(\"tester\").password(\"notalot\").authenticateSudo(true).build()).build();\n\n      SshClient sshClient = createMock(SshClient.class);\n\n      InitScript init = InitScript.builder().name(\"jclouds-script-0\").home(\"/tmp/jclouds-script-0\").run(command)\n            .build();\n\n      sshClient.connect();\n      sshClient.put(\"/tmp/init-jclouds-script-0\", init.render(OsFamily.UNIX));\n      expect(sshClient.getUsername()).andReturn(\"tester\").atLeastOnce();\n      expect(sshClient.getHostAddress()).andReturn(\"somewhere.example.com\").atLeastOnce();\n      \n      // setup script as default user\n      expect(sshClient.exec(\"chmod 755 /tmp/init-jclouds-script-0\")).andReturn(new ExecResponse(\"\", \"\", 0));\n      expect(sshClient.exec(\"ln -fs /tmp/init-jclouds-script-0 jclouds-script-0\")).andReturn(new ExecResponse(\"\", \"\", 0));\n      expect(sshClient.exec(\"/tmp/init-jclouds-script-0 init\")).andReturn(new ExecResponse(\"\", \"\", 0));\n      \n      // since there's an adminPassword we must pass this in\n      expect(sshClient.exec(\"echo 'notalot'|sudo -S /tmp/init-jclouds-script-0 start\")).andReturn(new ExecResponse(\"\", \"\", 0));\n\n      \n      sshClient.disconnect();\n      replay(sshClient);\n\n      RunScriptOnNodeAsInitScriptUsingSsh testMe = new RunScriptOnNodeAsInitScriptUsingSsh(Functions\n               .forMap(ImmutableMap.of(node, sshClient)), eventBus, InitScriptConfigurationForTasks.create()\n               .appendIncrementingNumberToAnonymousTaskNames(), node, command, new RunScriptOptions());\n\n      assertEquals(testMe.getInitFile(), \"/tmp/init-jclouds-script-0\");\n      assertEquals(testMe.getNode(), node);\n      assertEquals(testMe.getStatement(), init);\n\n      testMe.init();\n      testMe.call();\n      verify(sshClient);\n   }\n\n\n\n   public void testNotRoot() {\n      Statement command = exec(\"doFoo\");\n      NodeMetadata node = new NodeMetadataBuilder().ids(\"id\").status(Status.RUNNING).credentials(\n            LoginCredentials.builder().user(\"tester\").password(\"notalot\").authenticateSudo(true).build()).build();\n\n      SshClient sshClient = createMock(SshClient.class);\n\n      InitScript init = InitScript.builder().name(\"jclouds-script-0\").home(\"/tmp/jclouds-script-0\").run(command)\n            .build();\n\n      sshClient.connect();\n      sshClient.put(\"/tmp/init-jclouds-script-0\", init.render(OsFamily.UNIX));\n      expect(sshClient.getUsername()).andReturn(\"tester\").atLeastOnce();\n      expect(sshClient.getHostAddress()).andReturn(\"somewhere.example.com\").atLeastOnce();\n      \n      // setup script as default user\n      expect(sshClient.exec(\"chmod 755 /tmp/init-jclouds-script-0\")).andReturn(new ExecResponse(\"\", \"\", 0));\n      expect(sshClient.exec(\"ln -fs /tmp/init-jclouds-script-0 jclouds-script-0\")).andReturn(new ExecResponse(\"\", \"\", 0));\n      expect(sshClient.exec(\"/tmp/init-jclouds-script-0 init\")).andReturn(new ExecResponse(\"\", \"\", 0));\n      \n      // kick off as current user\n      expect(sshClient.exec(\"/tmp/init-jclouds-script-0 start\")).andReturn(new ExecResponse(\"\", \"\", 0));\n      \n      sshClient.disconnect();\n      replay(sshClient);\n\n      RunScriptOnNodeAsInitScriptUsingSsh testMe = new RunScriptOnNodeAsInitScriptUsingSsh(Functions\n               .forMap(ImmutableMap.of(node, sshClient)), eventBus, InitScriptConfigurationForTasks.create()\n               .appendIncrementingNumberToAnonymousTaskNames(), node, command, new RunScriptOptions().runAsRoot(false));\n\n      assertEquals(testMe.getInitFile(), \"/tmp/init-jclouds-script-0\");\n      assertEquals(testMe.getNode(), node);\n      assertEquals(testMe.getStatement(), init);\n\n      testMe.init();\n      testMe.call();\n      verify(sshClient);\n   }\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/callables/RunScriptOnNodeUsingSshTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.callables;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.jclouds.compute.options.RunScriptOptions.Builder.wrapInInitScript;\nimport static org.jclouds.scriptbuilder.domain.Statements.exec;\n\nimport org.jclouds.compute.domain.ExecResponse;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.scriptbuilder.statements.login.UserAdd;\nimport org.jclouds.ssh.SshClient;\nimport org.testng.annotations.BeforeMethod;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.eventbus.EventBus;\n\n@Test(groups = { \"unit\" }, singleThreaded = true)\npublic class RunScriptOnNodeUsingSshTest {\n   EventBus eventBus = new EventBus();\n\n   private SshClient sshClient;\n   private NodeMetadata node;\n   private Function<NodeMetadata, SshClient> sshFactory;\n\n   private static String testPassword = \"wit h(char%special\";\n\n   @BeforeMethod(groups = { \"unit\" })\n   public void init() {\n      sshClient = createMock(SshClient.class);\n      sshFactory = new Function<NodeMetadata, SshClient>() {\n         @Override\n         public SshClient apply(@Nullable NodeMetadata nodeMetadata) {\n            return sshClient;\n         }\n      };\n      node = createMock(NodeMetadata.class);\n      expect(node.getCredentials()).andReturn(LoginCredentials.builder().user(\"tester\").password(testPassword).build())\n            .atLeastOnce();\n      replay(node);\n   }\n\n   public void simpleTest() {\n      RunScriptOnNodeUsingSsh testMe = new RunScriptOnNodeUsingSsh(sshFactory, eventBus, node, exec(\"echo $USER\\necho $USER\"),\n            wrapInInitScript(false).runAsRoot(false));\n\n      testMe.init();\n\n      sshClient.connect();\n      expect(sshClient.getUsername()).andReturn(\"tester\");\n      expect(sshClient.getHostAddress()).andReturn(\"somewhere.example.com\");\n      expect(sshClient.exec(\"echo $USER\\n\" + \"echo $USER\\n\")).andReturn(new ExecResponse(\"tester\\ntester\\n\", null, 0));\n      sshClient.disconnect();\n      replay(sshClient);\n\n      testMe.call();\n   }\n\n   public void simpleRootTest() {\n      RunScriptOnNodeUsingSsh testMe = new RunScriptOnNodeUsingSsh(sshFactory, eventBus, node, exec(\"echo $USER\\necho $USER\"),\n            wrapInInitScript(false).runAsRoot(true));\n\n      testMe.init();\n\n      sshClient.connect();\n      expect(sshClient.getUsername()).andReturn(\"tester\");\n      expect(sshClient.getHostAddress()).andReturn(\"somewhere.example.com\");\n      expect(\n            sshClient.exec(\"sudo sh <<'RUN_SCRIPT_AS_ROOT_SSH'\\n\" + \"echo $USER\\n\" + \"echo $USER\\n\"\n                  + \"RUN_SCRIPT_AS_ROOT_SSH\\n\")).andReturn(new ExecResponse(\"root\\nroot\\n\", null, 0));\n      sshClient.disconnect();\n      replay(sshClient);\n\n      testMe.call();\n   }\n\n   public void simpleRootTestWithSudoPassword() {\n      node = createMock(NodeMetadata.class);\n      expect(node.getCredentials())\n            .andReturn(LoginCredentials.builder().user(\"tester\").password(testPassword).authenticateSudo(true).build())\n            .atLeastOnce();\n      replay(node);\n      RunScriptOnNodeUsingSsh testMe = new RunScriptOnNodeUsingSsh(sshFactory, eventBus, node, exec(\"echo $USER\\necho $USER\"),\n            wrapInInitScript(false).runAsRoot(true));\n      testMe.init();\n\n      sshClient.connect();\n      expect(sshClient.getUsername()).andReturn(\"tester\");\n      expect(sshClient.getHostAddress()).andReturn(\"somewhere.example.com\");\n      expect(sshClient.exec(\"sudo -S sh <<'RUN_SCRIPT_AS_ROOT_SSH'\\n\" + \"'\" + testPassword + \"'\\n\" + \"echo $USER\\n\"\n                  + \"echo $USER\\n\" + \"RUN_SCRIPT_AS_ROOT_SSH\\n\")).andReturn(new ExecResponse(\"root\\nroot\\n\", null, 0));\n      sshClient.disconnect();\n      replay(sshClient);\n\n      testMe.call();\n   }\n\n   public void testUserAddAsRoot() {\n      RunScriptOnNodeUsingSsh testMe = new RunScriptOnNodeUsingSsh(sshFactory, eventBus, node, UserAdd.builder()\n            .login(\"testuser\").build(), wrapInInitScript(false).runAsRoot(true).overrideLoginPassword(testPassword));\n\n      testMe.init();\n\n      sshClient.connect();\n      expect(sshClient.getUsername()).andReturn(\"tester\");\n      expect(sshClient.getHostAddress()).andReturn(\"somewhere.example.com\");\n      expect(\n            sshClient.exec(\"sudo sh <<'RUN_SCRIPT_AS_ROOT_SSH'\\n\"\n                  + \"mkdir -p /home/users\\n\"\n                  + \"chmod 0755 /home/users\\n\"\n                  + \"useradd -c testuser -s /bin/bash -m  -d /home/users/testuser testuser\\n\"\n                  + \"chown -R testuser /home/users/testuser\\n\" + \"RUN_SCRIPT_AS_ROOT_SSH\\n\")).andReturn(\n            new ExecResponse(\"done\", null, 0));\n      sshClient.disconnect();\n      replay(sshClient);\n\n      testMe.call();\n   }\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/callables/ScriptStillRunningExceptionTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.callables;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.concurrent.TimeUnit;\n\nimport org.jclouds.compute.domain.ExecResponse;\nimport org.testng.annotations.Test;\n\nimport com.google.common.util.concurrent.AbstractFuture;\nimport com.google.common.util.concurrent.ListenableFuture;\n\n@Test(groups = \"unit\", singleThreaded = true, testName = \"ScriptStillRunningExceptionTest\")\npublic class ScriptStillRunningExceptionTest {\n\n   public void simpleMessage() {\n      ListenableFuture<ExecResponse> future = new AbstractFuture<ExecResponse>() {\n         @Override\n         public String toString() {\n            return \"task for foo\";\n         }\n\n      };\n\n      ScriptStillRunningException testMe = new ScriptStillRunningException(1000, TimeUnit.MILLISECONDS, future);\n      assertEquals(testMe.getMessage(),\n               \"time up waiting 1s for task for foo to complete. call get() on this exception to get access to the task in progress\");\n\n   }\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/config/ComputeServicePropertiesTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.config;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Properties;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.compute.reference.ComputeServiceConstants.InitStatusProperties;\nimport org.jclouds.compute.reference.ComputeServiceConstants.PollPeriod;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ComputeServicePropertiesTest\")\npublic class ComputeServicePropertiesTest {\n   public void testDefaultInitStatusProperties() {\n      InitStatusProperties props = ContextBuilder.newBuilder(\"stub\").buildInjector()\n            .getInstance(InitStatusProperties.class);\n      assertEquals(props.initStatusInitialPeriod, 500);\n      assertEquals(props.initStatusMaxPeriod, 5000);\n   }\n\n   public void testOverrideInitStatusProperties() {\n      Properties overrides = new Properties();\n      overrides.setProperty(ComputeServiceProperties.INIT_STATUS_INITIAL_PERIOD, \"501\");\n      overrides.setProperty(ComputeServiceProperties.INIT_STATUS_MAX_PERIOD, \"5001\");\n      \n      InitStatusProperties props = ContextBuilder.newBuilder(\"stub\").overrides(overrides).buildInjector()\n            .getInstance(InitStatusProperties.class);\n      \n      assertEquals(props.initStatusInitialPeriod, 501);\n      assertEquals(props.initStatusMaxPeriod, 5001);\n   }\n\n   public void testDefaultPollPeriod() {\n\t   PollPeriod props = ContextBuilder.newBuilder(\"stub\").buildInjector()\n            .getInstance(PollPeriod.class);\n      assertEquals(props.pollInitialPeriod, 50);\n      assertEquals(props.pollMaxPeriod, 1000);\n   }\n\n   public void testOverridePollPeriod() {\n      Properties overrides = new Properties();\n      overrides.setProperty(ComputeServiceProperties.POLL_INITIAL_PERIOD, \"501\");\n      overrides.setProperty(ComputeServiceProperties.POLL_MAX_PERIOD, \"5001\");\n      \n      PollPeriod props = ContextBuilder.newBuilder(\"stub\").overrides(overrides).buildInjector()\n            .getInstance(PollPeriod.class);\n      \n      assertEquals(props.pollInitialPeriod, 501);\n      assertEquals(props.pollMaxPeriod, 5001);\n   }\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/config/GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNullTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.config;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Map;\n\nimport org.jclouds.config.ValueOfConfigurationKeyOrNull;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.domain.LoginCredentials;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNullTest\")\npublic class GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNullTest {\n\n   public void testWhenCredentialsNotPresentReturnsNull() {\n      @SuppressWarnings(\"unchecked\")\n      Map<String, Credentials> credstore = createMock(Map.class);\n      Credentials expected = null;\n\n      ValueOfConfigurationKeyOrNull config = createMock(ValueOfConfigurationKeyOrNull.class);\n\n      expect(credstore.containsKey(\"image\")).andReturn(false);\n      expect(config.apply(\"provider.image.login-user\")).andReturn(null);\n      expect(config.apply(\"jclouds.image.login-user\")).andReturn(null);\n      expect(config.apply(\"provider.image.authenticate-sudo\")).andReturn(null);\n      expect(config.apply(\"jclouds.image.authenticate-sudo\")).andReturn(null);\n\n      replay(config);\n      replay(credstore);\n\n      GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNull fn = new GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNull(\n            \"provider\", config, credstore);\n      assertEquals(fn.get(), expected);\n\n      verify(config);\n      verify(credstore);\n\n   }\n\n   public void testWhenCredentialsNotPresentAndProviderPropertyHasUser() {\n      @SuppressWarnings(\"unchecked\")\n      Map<String, Credentials> credstore = createMock(Map.class);\n      Credentials expected = new Credentials(\"ubuntu\", null);\n\n      ValueOfConfigurationKeyOrNull config = createMock(ValueOfConfigurationKeyOrNull.class);\n\n      expect(credstore.containsKey(\"image\")).andReturn(false);\n      expect(config.apply(\"provider.image.login-user\")).andReturn(\"ubuntu\");\n      expect(config.apply(\"provider.image.authenticate-sudo\")).andReturn(null);\n      expect(config.apply(\"jclouds.image.authenticate-sudo\")).andReturn(null);\n      expect(credstore.put(\"image\", expected)).andReturn(null);\n\n      replay(config);\n      replay(credstore);\n\n      GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNull fn = new GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNull(\n            \"provider\", config, credstore);\n      assertEquals(fn.get(), expected);\n\n      verify(config);\n      verify(credstore);\n\n   }\n\n   public void testWhenCredentialsNotPresentAndJcloudsPropertyHasUser() {\n      @SuppressWarnings(\"unchecked\")\n      Map<String, Credentials> credstore = createMock(Map.class);\n      Credentials expected = new Credentials(\"ubuntu\", null);\n\n      ValueOfConfigurationKeyOrNull config = createMock(ValueOfConfigurationKeyOrNull.class);\n\n      expect(credstore.containsKey(\"image\")).andReturn(false);\n      expect(config.apply(\"provider.image.login-user\")).andReturn(null);\n      expect(config.apply(\"jclouds.image.login-user\")).andReturn(\"ubuntu\");\n      expect(config.apply(\"provider.image.authenticate-sudo\")).andReturn(null);\n      expect(config.apply(\"jclouds.image.authenticate-sudo\")).andReturn(null);\n      expect(credstore.put(\"image\", expected)).andReturn(null);\n\n      replay(config);\n      replay(credstore);\n\n      GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNull fn = new GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNull(\n            \"provider\", config, credstore);\n      assertEquals(fn.get(), expected);\n\n      verify(config);\n      verify(credstore);\n\n   }\n\n   public void testWhenCredentialsAlreadyPresentReturnsSame() {\n      @SuppressWarnings(\"unchecked\")\n      Map<String, Credentials> credstore = createMock(Map.class);\n      Credentials expected = new Credentials(\"root\", null);\n\n      ValueOfConfigurationKeyOrNull config = createMock(ValueOfConfigurationKeyOrNull.class);\n\n      expect(credstore.containsKey(\"image\")).andReturn(true);\n      expect(credstore.get(\"image\")).andReturn(expected);\n\n      replay(config);\n      replay(credstore);\n\n      GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNull fn = new GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNull(\n            \"provider\", config, credstore);\n      assertEquals(fn.get(), expected);\n\n      verify(config);\n      verify(credstore);\n\n   }\n\n   public void testWhenCredentialsNotPresentAndProviderPropertyHasUserAndPassword() {\n      @SuppressWarnings(\"unchecked\")\n      Map<String, Credentials> credstore = createMock(Map.class);\n      Credentials expected = new Credentials(\"ubuntu\", \"password\");\n\n      ValueOfConfigurationKeyOrNull config = createMock(ValueOfConfigurationKeyOrNull.class);\n\n      expect(credstore.containsKey(\"image\")).andReturn(false);\n      expect(config.apply(\"provider.image.login-user\")).andReturn(\"ubuntu:password\");\n      expect(config.apply(\"provider.image.authenticate-sudo\")).andReturn(null);\n      expect(config.apply(\"jclouds.image.authenticate-sudo\")).andReturn(null);\n      expect(credstore.put(\"image\", expected)).andReturn(null);\n\n      replay(config);\n      replay(credstore);\n\n      GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNull fn = new GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNull(\n            \"provider\", config, credstore);\n      assertEquals(fn.get(), expected);\n\n      verify(config);\n      verify(credstore);\n\n   }\n\n   public void testWhenCredentialsNotPresentAndJcloudsPropertyHasUserAndPassword() {\n      @SuppressWarnings(\"unchecked\")\n      Map<String, Credentials> credstore = createMock(Map.class);\n      Credentials expected = new Credentials(\"ubuntu\", \"password\");\n\n      ValueOfConfigurationKeyOrNull config = createMock(ValueOfConfigurationKeyOrNull.class);\n\n      expect(credstore.containsKey(\"image\")).andReturn(false);\n      expect(config.apply(\"provider.image.login-user\")).andReturn(null);\n      expect(config.apply(\"jclouds.image.login-user\")).andReturn(\"ubuntu:password\");\n      expect(config.apply(\"provider.image.authenticate-sudo\")).andReturn(null);\n      expect(config.apply(\"jclouds.image.authenticate-sudo\")).andReturn(null);\n      expect(credstore.put(\"image\", expected)).andReturn(null);\n\n      replay(config);\n      replay(credstore);\n\n      GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNull fn = new GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNull(\n            \"provider\", config, credstore);\n      assertEquals(fn.get(), expected);\n\n      verify(config);\n      verify(credstore);\n\n   }\n\n   public void testWhenCredentialsNotPresentAndJcloudsPropertyHasUserAndPasswordAndSudo() {\n      @SuppressWarnings(\"unchecked\")\n      Map<String, Credentials> credstore = createMock(Map.class);\n      LoginCredentials expected = LoginCredentials.builder().user(\"ubuntu\").password(\"password\").authenticateSudo(true)\n            .build();\n\n      ValueOfConfigurationKeyOrNull config = createMock(ValueOfConfigurationKeyOrNull.class);\n\n      expect(credstore.containsKey(\"image\")).andReturn(false);\n      expect(config.apply(\"provider.image.login-user\")).andReturn(null);\n      expect(config.apply(\"jclouds.image.login-user\")).andReturn(\"ubuntu:password\");\n      expect(config.apply(\"provider.image.authenticate-sudo\")).andReturn(null);\n      expect(config.apply(\"jclouds.image.authenticate-sudo\")).andReturn(\"true\");\n      expect(credstore.put(\"image\", expected)).andReturn(null);\n\n      replay(config);\n      replay(credstore);\n\n      GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNull fn = new GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNull(\n            \"provider\", config, credstore);\n      assertEquals(fn.get(), expected);\n\n      verify(config);\n      verify(credstore);\n\n   }\n\n   public void testWhenCredentialsNotPresentAndProviderPropertyHasUserAndPasswordAndSudo() {\n      @SuppressWarnings(\"unchecked\")\n      Map<String, Credentials> credstore = createMock(Map.class);\n      LoginCredentials expected = LoginCredentials.builder().user(\"ubuntu\").password(\"password\").authenticateSudo(true)\n            .build();\n\n      ValueOfConfigurationKeyOrNull config = createMock(ValueOfConfigurationKeyOrNull.class);\n\n      expect(credstore.containsKey(\"image\")).andReturn(false);\n      expect(config.apply(\"provider.image.login-user\")).andReturn(\"ubuntu:password\");\n      expect(config.apply(\"provider.image.authenticate-sudo\")).andReturn(\"true\");\n      expect(credstore.put(\"image\", expected)).andReturn(null);\n\n      replay(config);\n      replay(credstore);\n\n      GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNull fn = new GetLoginForProviderFromPropertiesAndStoreCredentialsOrReturnNull(\n            \"provider\", config, credstore);\n      assertEquals(fn.get(), expected);\n\n      verify(config);\n      verify(credstore);\n\n   }\n\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/config/PersistNodeCredentialsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.config;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Map;\n\nimport org.jclouds.compute.config.PersistNodeCredentialsModule.RefreshCredentialsForNode;\nimport org.jclouds.compute.config.PersistNodeCredentialsModule.RefreshCredentialsForNodeIfRanAdminAccess;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadataBuilder;\nimport org.jclouds.compute.domain.NodeMetadata.Status;\nimport org.jclouds.compute.internal.PersistNodeCredentials;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.scriptbuilder.statements.login.AdminAccess;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.TypeLiteral;\n\n@Test(groups = \"unit\")\npublic class PersistNodeCredentialsTest {\n\n   public void testReturnsCorrectFunction() {\n      PersistNodeCredentials persistNodeCredentials = Guice.createInjector(new PersistNodeCredentialsModule(),\n            new AbstractModule() {\n\n               @Override\n               protected void configure() {\n                  bind(new TypeLiteral<Map<String, Credentials>>() {\n                  }).toInstance(ImmutableMap.<String, Credentials> of());\n               }\n\n            }).getInstance(PersistNodeCredentials.class);\n      assertEquals(persistNodeCredentials.always(null).getClass(),\n            PersistNodeCredentialsModule.RefreshCredentialsForNode.class);\n      assertEquals(persistNodeCredentials.ifAdminAccess(null).getClass(),\n            PersistNodeCredentialsModule.RefreshCredentialsForNodeIfRanAdminAccess.class);\n   }\n\n   public void testRefreshCredentialsForNodeIfRanAdminAccessWhenStatementIsNullSameCredentialsAndNoCaching() {\n      @SuppressWarnings(\"unchecked\")\n      Map<String, Credentials> credstore = createMock(Map.class);\n\n      replay(credstore);\n\n      NodeMetadata node = new NodeMetadataBuilder().ids(\"id\").status(Status.RUNNING).build();\n      RefreshCredentialsForNodeIfRanAdminAccess fn = new PersistNodeCredentialsModule.RefreshCredentialsForNodeIfRanAdminAccess(\n            credstore, null);\n      assertEquals(node, fn.apply(node));\n\n      verify(credstore);\n\n   }\n\n   public void testRefreshCredentialsForNodeWhenStatementIsNullSameCredentialsAndDoesCache() {\n      @SuppressWarnings(\"unchecked\")\n      Map<String, Credentials> credstore = createMock(Map.class);\n      LoginCredentials credentials = createMock(LoginCredentials.class);\n\n      expect(credstore.put(\"node#id\", credentials)).andReturn(null);\n\n      replay(credstore);\n\n      NodeMetadata node = new NodeMetadataBuilder().ids(\"id\").status(Status.RUNNING).credentials(credentials).build();\n      RefreshCredentialsForNode fn = new PersistNodeCredentialsModule.RefreshCredentialsForNode(credstore, null);\n      assertEquals(node, fn.apply(node));\n\n      verify(credstore);\n\n   }\n\n   public void testRefreshCredentialsForNodeIfRanAdminAccessWhenStatementIsAdminAccessNewCredentialsAndDoesCache() {\n      @SuppressWarnings(\"unchecked\")\n      Map<String, Credentials> credstore = createMock(Map.class);\n\n      AdminAccess statement = createMock(AdminAccess.class);\n      LoginCredentials credentials = LoginCredentials.builder().user(\"foo\").build();\n\n      expect(statement.getAdminCredentials()).andReturn(credentials).atLeastOnce();\n      expect(credstore.put(\"node#id\", credentials)).andReturn(null);\n\n      replay(statement);\n      replay(credstore);\n\n      NodeMetadata node = new NodeMetadataBuilder().ids(\"id\").status(Status.RUNNING).build();\n      RefreshCredentialsForNodeIfRanAdminAccess fn = new PersistNodeCredentialsModule.RefreshCredentialsForNodeIfRanAdminAccess(\n            credstore, statement);\n      assertEquals(fn.apply(node).getCredentials(), credentials);\n\n      verify(statement);\n      verify(credstore);\n\n   }\n\n   public void testRefreshCredentialsForNodeWhenStatementIsAdminAccessNewCredentialsAndDoesCache() {\n      @SuppressWarnings(\"unchecked\")\n      Map<String, Credentials> credstore = createMock(Map.class);\n\n      AdminAccess statement = createMock(AdminAccess.class);\n      LoginCredentials credentials = LoginCredentials.builder().user(\"foo\").build();\n      expect(statement.getAdminCredentials()).andReturn(credentials).atLeastOnce();\n      expect(credstore.put(\"node#id\", credentials)).andReturn(null);\n      expect(credstore.put(\"node#id\", credentials)).andReturn(null); // TODO\n                                                                     // optimize\n                                                                     // this\n\n      replay(statement);\n      replay(credstore);\n\n      NodeMetadata node = new NodeMetadataBuilder().ids(\"id\").status(Status.RUNNING).build();\n      RefreshCredentialsForNode fn = new PersistNodeCredentialsModule.RefreshCredentialsForNode(credstore, statement);\n      assertEquals(fn.apply(node).getCredentials(), credentials);\n\n      verify(statement);\n      verify(credstore);\n\n   }\n\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/domain/ImageBuilderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.domain;\n\nimport static org.testng.Assert.assertNull;\n\nimport org.jclouds.compute.domain.Image.Status;\nimport org.testng.annotations.Test;\n\n/**\n * Unit tests for org.jclouds.compute.domain.ImageBuilder\n */\n@Test(testName = \"ImageBuilderTest\")\npublic class ImageBuilderTest {\n    \n    /**\n     * Ensures that an explicitly set null Image description results in no errors.\n     */\n    public void testNullDescription() {\n        Image img = new ImageBuilder().id(\"test-id\")\n                .description(null)\n                .status(Status.AVAILABLE)\n                .operatingSystem(new OperatingSystem(OsFamily.CLOUD_LINUX, null, null, null, \"os-description\", true))\n                .build();\n        assertNull(img.getDescription());\n    }\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/domain/TemplateBuilderSpecTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.domain;\n\nimport static org.jclouds.compute.domain.TemplateBuilderSpec.parse;\nimport static org.jclouds.compute.options.TemplateOptions.Builder.overrideLoginCredentials;\nimport static org.jclouds.compute.options.TemplateOptions.Builder.overrideLoginUser;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotEquals;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.fail;\n\nimport java.lang.reflect.Field;\n\nimport jakarta.inject.Provider;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.domain.LoginCredentials;\nimport org.testng.annotations.Test;\n\nimport com.google.gson.Gson;\n\n/**\n * \n * <p/>\n * inspired by guava {@code CacheBuilderSpecTest}\n */\n@Test(testName = \"TemplateBuilderSpecTest\")\npublic class TemplateBuilderSpecTest {\n   Provider<TemplateBuilder> templateBuilders = ContextBuilder.newBuilder(\"stub\").buildInjector()\n         .getProvider(TemplateBuilder.class);\n\n   public void testParse_empty() {\n      TemplateBuilderSpec spec = parse(\"\");\n      assertNull(spec.hardwareId);\n      assertNull(spec.minCores);\n      assertNull(spec.minRam);\n      assertNull(spec.minDisk);\n      assertNull(spec.hypervisorMatches);\n      assertNull(spec.imageId);\n      assertNull(spec.imageNameMatches);\n      assertNull(spec.osFamily);\n      assertNull(spec.osVersionMatches);\n      assertNull(spec.os64Bit);\n      assertNull(spec.osArchMatches);\n      assertNull(spec.osDescriptionMatches);\n      assertNull(spec.loginUser);\n      assertNull(spec.authenticateSudo);\n      assertNull(spec.locationId);\n      assertNull(spec.forceCacheReload);\n      assertTemplateBuilderEquivalence(templateBuilders.get(), templateBuilders.get().from(spec));\n   }\n\n   public void testParse_hardwareId() {\n      TemplateBuilderSpec spec = parse(\"hardwareId=m1.small\");\n      assertEquals(spec.hardwareId, \"m1.small\");\n      assertNull(spec.minCores);\n      assertNull(spec.minRam);\n      assertNull(spec.minDisk);\n      assertNull(spec.hypervisorMatches);\n      assertNull(spec.imageId);\n      assertNull(spec.imageNameMatches);\n      assertNull(spec.osFamily);\n      assertNull(spec.osVersionMatches);\n      assertNull(spec.os64Bit);\n      assertNull(spec.osArchMatches);\n      assertNull(spec.osDescriptionMatches);\n      assertNull(spec.loginUser);\n      assertNull(spec.authenticateSudo);\n      assertNull(spec.locationId);\n      assertNull(spec.forceCacheReload);\n      assertTemplateBuilderEquivalence(templateBuilders.get().hardwareId(\"m1.small\"),\n            templateBuilders.get().from(spec));\n   }\n\n   public void testParse_hardwareIdRepeated() {\n      try {\n         parse(\"hardwareId=m1.small, hardwareId=t1.micro\");\n         fail(\"Expected exception\");\n      } catch (IllegalArgumentException expected) {\n         // expected\n      }\n   }\n\n   public void testParse_hardwareIdNotCompatibleWithHardwareValues() {\n      try {\n         parse(\"hardwareId=m1.small,minCores=1\");\n         fail(\"Expected exception\");\n      } catch (IllegalArgumentException expected) {\n         // expected\n      }\n      try {\n         parse(\"hardwareId=m1.small,minRam=512\");\n         fail(\"Expected exception\");\n      } catch (IllegalArgumentException expected) {\n         // expected\n      }\n      try {\n         parse(\"hardwareId=m1.small,hypervisorMatches=OpenVZ\");\n         fail(\"Expected exception\");\n      } catch (IllegalArgumentException expected) {\n         // expected\n      }\n   }\n   \n   public void testParse_minCores() {\n      TemplateBuilderSpec spec = parse(\"minCores=32\");\n      assertNull(spec.hardwareId);\n      assertEquals(32, spec.minCores.intValue());\n      assertNull(spec.minRam);\n      assertNull(spec.minDisk);\n      assertNull(spec.hypervisorMatches);\n      assertNull(spec.imageId);\n      assertNull(spec.imageNameMatches);\n      assertNull(spec.osFamily);\n      assertNull(spec.osVersionMatches);\n      assertNull(spec.os64Bit);\n      assertNull(spec.osArchMatches);\n      assertNull(spec.osDescriptionMatches);\n      assertNull(spec.loginUser);\n      assertNull(spec.authenticateSudo);\n      assertNull(spec.locationId);\n      assertNull(spec.forceCacheReload);\n      assertTemplateBuilderEquivalence(templateBuilders.get().minCores(32), templateBuilders.get().from(spec));\n   }\n\n   public void testParse_minCoresRepeated() {\n      try {\n         parse(\"minCores=10, minCores=20\");\n         fail(\"Expected exception\");\n      } catch (IllegalArgumentException expected) {\n         // expected\n      }\n   }\n   \n   public void testParse_minRam() {\n      TemplateBuilderSpec spec = parse(\"minRam=10\");\n      assertNull(spec.hardwareId);\n      assertNull(spec.minCores);\n      assertEquals(spec.minRam.intValue(), 10);\n      assertNull(spec.hypervisorMatches);\n      assertNull(spec.imageId);\n      assertNull(spec.imageNameMatches);\n      assertNull(spec.osFamily);\n      assertNull(spec.osVersionMatches);\n      assertNull(spec.os64Bit);\n      assertNull(spec.osArchMatches);\n      assertNull(spec.osDescriptionMatches);\n      assertNull(spec.loginUser);\n      assertNull(spec.authenticateSudo);\n      assertNull(spec.locationId);\n      assertNull(spec.forceCacheReload);\n      assertTemplateBuilderEquivalence(templateBuilders.get().minRam(10), templateBuilders.get().from(spec));\n   }\n\n   public void testParse_minDisk() {\n      TemplateBuilderSpec spec = parse(\"minDisk=10\");\n      assertNull(spec.hardwareId);\n      assertNull(spec.minCores);\n      assertNull(spec.minRam);\n      assertEquals(spec.minDisk.doubleValue(), 10.0);\n      assertNull(spec.hypervisorMatches);\n      assertNull(spec.imageId);\n      assertNull(spec.imageNameMatches);\n      assertNull(spec.osFamily);\n      assertNull(spec.osVersionMatches);\n      assertNull(spec.os64Bit);\n      assertNull(spec.osArchMatches);\n      assertNull(spec.osDescriptionMatches);\n      assertNull(spec.loginUser);\n      assertNull(spec.authenticateSudo);\n      assertNull(spec.locationId);\n      assertNull(spec.forceCacheReload);\n      assertTemplateBuilderEquivalence(templateBuilders.get().minRam(10), templateBuilders.get().from(spec));\n   }\n\n   public void testParse_minDiskIsNotEqual() {\n      TemplateBuilderSpec spec1 = parse(\"minDisk=10\");\n      TemplateBuilderSpec spec2 = parse(\"minDisk=20\");\n      assertTemplateBuilderEquivalence(templateBuilders.get().minDisk(10), templateBuilders.get().from(spec1));\n      assertTemplateBuilderEquivalence(templateBuilders.get().minDisk(20), templateBuilders.get().from(spec2));\n      assertNotEquals(spec1.minDisk, spec2.minDisk);\n   }\n\n   public void testParse_minRamRepeated() {\n      try {\n         parse(\"minRam=10, minRam=20\");\n         fail(\"Expected exception\");\n      } catch (IllegalArgumentException expected) {\n         // expected\n      }\n   }\n\n   public void testParse_hypervisorMatches() {\n      TemplateBuilderSpec spec = parse(\"hypervisorMatches=OpenVZ\");\n      assertNull(spec.hardwareId);\n      assertNull(spec.minCores);\n      assertNull(spec.minRam);\n      assertNull(spec.minDisk);\n      assertEquals(spec.hypervisorMatches, \"OpenVZ\");\n      assertNull(spec.imageId);\n      assertNull(spec.imageNameMatches);\n      assertNull(spec.osVersionMatches);\n      assertNull(spec.os64Bit);\n      assertNull(spec.osArchMatches);\n      assertNull(spec.osDescriptionMatches);\n      assertNull(spec.loginUser);\n      assertNull(spec.authenticateSudo);\n      assertNull(spec.locationId);\n      assertNull(spec.forceCacheReload);\n      assertTemplateBuilderEquivalence(templateBuilders.get().hypervisorMatches(\"OpenVZ\"),\n            templateBuilders.get().from(spec));\n   }\n\n   public void testParse_hypervisorMatchesRepeated() {\n      try {\n         parse(\"hypervisorMatches=VSphere, hypervisorMatches=OpenVZ\");\n         fail(\"Expected exception\");\n      } catch (IllegalArgumentException expected) {\n         // expected\n      }\n   }\n   \n   public void testParse_imageId() {\n      TemplateBuilderSpec spec = parse(\"imageId=us-east-1/ami-fffffff\");\n      assertNull(spec.hardwareId);\n      assertNull(spec.minCores);\n      assertNull(spec.minRam);\n      assertNull(spec.minDisk);\n      assertNull(spec.hypervisorMatches);\n      assertEquals(spec.imageId, \"us-east-1/ami-fffffff\");\n      assertNull(spec.imageNameMatches);\n      assertNull(spec.osFamily);\n      assertNull(spec.osVersionMatches);\n      assertNull(spec.os64Bit);\n      assertNull(spec.osArchMatches);\n      assertNull(spec.osDescriptionMatches);\n      assertNull(spec.loginUser);\n      assertNull(spec.authenticateSudo);\n      assertNull(spec.locationId);\n      assertNull(spec.forceCacheReload);\n      assertTemplateBuilderEquivalence(templateBuilders.get().imageId(\"us-east-1/ami-fffffff\"),\n            templateBuilders.get().from(spec));\n   }\n   \n   public void testParse_imageIdRepeated() {\n      try {\n         parse(\"imageId=us-east-1/ami-fffffff, imageId=ami-eeeeeee\");\n         fail(\"Expected exception\");\n      } catch (IllegalArgumentException expected) {\n         // expected\n      }\n   }\n\n   public void testParse_imageIdNotCompatibleWithImageValues() {\n      try {\n         parse(\"imageId=us-east-1/ami-fffffff,imageNameMatches=foo\");\n         fail(\"Expected exception\");\n      } catch (IllegalArgumentException expected) {\n         // expected\n      }\n      try {\n         parse(\"imageId=us-east-1/ami-fffffff,osFamily=UBUNTU\");\n         fail(\"Expected exception\");\n      } catch (IllegalArgumentException expected) {\n         // expected\n      }\n      try {\n         parse(\"imageId=us-east-1/ami-fffffff,osVersionMatches=10.04\");\n         fail(\"Expected exception\");\n      } catch (IllegalArgumentException expected) {\n         // expected\n      }\n      try {\n         parse(\"imageId=us-east-1/ami-fffffff,os64Bit=true\");\n         fail(\"Expected exception\");\n      } catch (IllegalArgumentException expected) {\n         // expected\n      }\n      try {\n         parse(\"imageId=us-east-1/ami-fffffff,osArchMatches=x86\");\n         fail(\"Expected exception\");\n      } catch (IllegalArgumentException expected) {\n         // expected\n      }\n      try {\n         parse(\"imageId=us-east-1/ami-fffffff,osDescriptionMatches=^((?!MGC).)*$\");\n         fail(\"Expected exception\");\n      } catch (IllegalArgumentException expected) {\n         // expected\n      }\n   }\n\n\n   public void testParse_imageNameMatches() {\n      TemplateBuilderSpec spec = parse(\"imageNameMatches=.*w/ None.*\");\n      assertNull(spec.hardwareId);\n      assertNull(spec.minCores);\n      assertNull(spec.minRam);\n      assertNull(spec.minDisk);\n      assertNull(spec.hypervisorMatches);\n      assertNull(spec.imageId);\n      assertEquals(spec.imageNameMatches, \".*w/ None.*\");\n      assertNull(spec.osVersionMatches);\n      assertNull(spec.os64Bit);\n      assertNull(spec.osArchMatches);\n      assertNull(spec.osDescriptionMatches);\n      assertNull(spec.loginUser);\n      assertNull(spec.authenticateSudo);\n      assertNull(spec.locationId);\n      assertNull(spec.forceCacheReload);\n      assertTemplateBuilderEquivalence(templateBuilders.get().imageNameMatches(\".*w/ None.*\"),\n            templateBuilders.get().from(spec));\n   }\n\n   public void testParse_imageNameMatchesRepeated() {\n      try {\n         parse(\"imageNameMatches=hello, imageNameMatches=.*w/ None.*\");\n         fail(\"Expected exception\");\n      } catch (IllegalArgumentException expected) {\n         // expected\n      }\n   }\n\n   public void testParse_osFamily() {\n      TemplateBuilderSpec spec = parse(\"osFamily=UBUNTU\");\n      assertNull(spec.hardwareId);\n      assertNull(spec.minCores);\n      assertNull(spec.minRam);\n      assertNull(spec.minDisk);\n      assertNull(spec.hypervisorMatches);\n      assertNull(spec.imageId);\n      assertNull(spec.imageNameMatches);\n      assertEquals(spec.osFamily, OsFamily.UBUNTU);\n      assertNull(spec.osVersionMatches);\n      assertNull(spec.os64Bit);\n      assertNull(spec.osArchMatches);\n      assertNull(spec.osDescriptionMatches);\n      assertNull(spec.loginUser);\n      assertNull(spec.authenticateSudo);\n      assertNull(spec.locationId);\n      assertNull(spec.forceCacheReload);\n      assertTemplateBuilderEquivalence(templateBuilders.get().osFamily(OsFamily.UBUNTU),\n            templateBuilders.get().from(spec));\n   }\n\n   public void testParse_osFamilyRepeated() {\n      try {\n         parse(\"osFamily=UBUNTU, osFamily=LINUX\");\n         fail(\"Expected exception\");\n      } catch (IllegalArgumentException expected) {\n         // expected\n      }\n   }\n\n   public void testParse_osVersionMatches() {\n      TemplateBuilderSpec spec = parse(\"osVersionMatches=.*[Aa]utomated SSH Access.*\");\n      assertNull(spec.hardwareId);\n      assertNull(spec.minCores);\n      assertNull(spec.minRam);\n      assertNull(spec.minDisk);\n      assertNull(spec.hypervisorMatches);\n      assertNull(spec.imageId);\n      assertNull(spec.imageNameMatches);\n      assertEquals(spec.osVersionMatches, \".*[Aa]utomated SSH Access.*\");\n      assertNull(spec.os64Bit);\n      assertNull(spec.osArchMatches);\n      assertNull(spec.osDescriptionMatches);\n      assertNull(spec.loginUser);\n      assertNull(spec.authenticateSudo);\n      assertNull(spec.locationId);\n      assertNull(spec.forceCacheReload);\n      assertTemplateBuilderEquivalence(templateBuilders.get().osVersionMatches(\".*[Aa]utomated SSH Access.*\"),\n            templateBuilders.get().from(spec));\n   }\n\n   public void testParse_osVersionMatchesRepeated() {\n      try {\n         parse(\"osVersionMatches=11.04, osVersionMatches=.*[Aa]utomated SSH Access.*\");\n         fail(\"Expected exception\");\n      } catch (IllegalArgumentException expected) {\n         // expected\n      }\n   }\n\n   public void testParse_os64Bit() {\n      TemplateBuilderSpec spec = parse(\"os64Bit=true\");\n      assertNull(spec.hardwareId);\n      assertNull(spec.minCores);\n      assertNull(spec.minRam);\n      assertNull(spec.minDisk);\n      assertNull(spec.hypervisorMatches);\n      assertNull(spec.imageId);\n      assertNull(spec.imageNameMatches);\n      assertNull(spec.osVersionMatches);\n      assertEquals(spec.os64Bit.booleanValue(), true);\n      assertNull(spec.osArchMatches);\n      assertNull(spec.osDescriptionMatches);\n      assertNull(spec.loginUser);\n      assertNull(spec.authenticateSudo);\n      assertNull(spec.locationId);\n      assertNull(spec.forceCacheReload);\n      assertTemplateBuilderEquivalence(templateBuilders.get().os64Bit(true),\n            templateBuilders.get().from(spec));\n   }\n\n   public void testParse_os64BitRepeated() {\n      try {\n         parse(\"os64Bit=false, os64Bit=true\");\n         fail(\"Expected exception\");\n      } catch (IllegalArgumentException expected) {\n         // expected\n      }\n   }\n\n   public void testParse_osArchMatches() {\n      TemplateBuilderSpec spec = parse(\"osArchMatches=x86\");\n      assertNull(spec.hardwareId);\n      assertNull(spec.minCores);\n      assertNull(spec.minRam);\n      assertNull(spec.minDisk);\n      assertNull(spec.hypervisorMatches);\n      assertNull(spec.imageId);\n      assertNull(spec.imageNameMatches);\n      assertNull(spec.osVersionMatches);\n      assertNull(spec.os64Bit);\n      assertEquals(spec.osArchMatches, \"x86\");\n      assertNull(spec.osDescriptionMatches);\n      assertNull(spec.loginUser);\n      assertNull(spec.authenticateSudo);\n      assertNull(spec.locationId);\n      assertNull(spec.forceCacheReload);\n      assertTemplateBuilderEquivalence(templateBuilders.get().osArchMatches(\"x86\"),\n            templateBuilders.get().from(spec));\n   }\n\n   public void testParse_osArchMatchesRepeated() {\n      try {\n         parse(\"osArchMatches=x86, osArchMatches=foo\");\n         fail(\"Expected exception\");\n      } catch (IllegalArgumentException expected) {\n         // expected\n      }\n   }\n   \n   public void testParse_osDescriptionMatches() {\n      TemplateBuilderSpec spec = parse(\"osDescriptionMatches=^((?!MGC).)*$\");\n      assertNull(spec.hardwareId);\n      assertNull(spec.minCores);\n      assertNull(spec.minRam);\n      assertNull(spec.minDisk);\n      assertNull(spec.hypervisorMatches);\n      assertNull(spec.imageId);\n      assertNull(spec.imageNameMatches);\n      assertNull(spec.osVersionMatches);\n      assertNull(spec.os64Bit);\n      assertNull(spec.osArchMatches);\n      assertEquals(spec.osDescriptionMatches, \"^((?!MGC).)*$\");\n      assertNull(spec.loginUser);\n      assertNull(spec.authenticateSudo);\n      assertNull(spec.locationId);\n      assertNull(spec.forceCacheReload);\n      assertTemplateBuilderEquivalence(templateBuilders.get().osDescriptionMatches(\"^((?!MGC).)*$\"),\n            templateBuilders.get().from(spec));\n   }\n\n   public void testParse_osDescriptionMatchesRepeated() {\n      try {\n         parse(\"osDescriptionMatches=^((?!MGC).)*$, osDescriptionMatches=.*[Aa]utomated SSH Access.*\");\n         fail(\"Expected exception\");\n      } catch (IllegalArgumentException expected) {\n         // expected\n      }\n   }\n\n   public void testParse_loginUser() {\n      TemplateBuilderSpec spec = parse(\"loginUser=ubuntu\");\n      assertNull(spec.hardwareId);\n      assertNull(spec.minCores);\n      assertNull(spec.minRam);\n      assertNull(spec.minDisk);\n      assertNull(spec.hypervisorMatches);\n      assertNull(spec.imageId);\n      assertNull(spec.imageNameMatches);\n      assertNull(spec.osFamily);\n      assertNull(spec.osVersionMatches);\n      assertNull(spec.os64Bit);\n      assertNull(spec.osArchMatches);\n      assertNull(spec.osDescriptionMatches);\n      assertEquals(spec.loginUser, \"ubuntu\");\n      assertNull(spec.authenticateSudo);\n      assertNull(spec.locationId);\n      assertNull(spec.forceCacheReload);\n      assertTemplateBuilderEquivalence(\n            templateBuilders.get().options(overrideLoginUser(\"ubuntu\")), templateBuilders\n                  .get().from(spec));\n   }\n\n   public void testParse_loginUserRepeated() {\n      try {\n         parse(\"loginUser=aws-user,loginUser=ubuntu\");\n         fail(\"Expected exception\");\n      } catch (IllegalArgumentException expected) {\n         // expected\n      }\n   }\n\n   public void testParse_loginUserWithPassword() {\n      TemplateBuilderSpec spec = parse(\"loginUser=root:toor\");\n      assertNull(spec.hardwareId);\n      assertNull(spec.minCores);\n      assertNull(spec.minRam);\n      assertNull(spec.minDisk);\n      assertNull(spec.hypervisorMatches);\n      assertNull(spec.imageId);\n      assertNull(spec.imageNameMatches);\n      assertNull(spec.osFamily);\n      assertNull(spec.osVersionMatches);\n      assertNull(spec.os64Bit);\n      assertNull(spec.osArchMatches);\n      assertNull(spec.osDescriptionMatches);\n      assertEquals(spec.loginUser, \"root:toor\");\n      assertNull(spec.authenticateSudo);\n      assertNull(spec.locationId);\n      assertNull(spec.forceCacheReload);\n      assertTemplateBuilderEquivalence(\n            templateBuilders.get().options(\n                  overrideLoginCredentials(LoginCredentials.builder().user(\"root\").password(\"toor\").build())),\n            templateBuilders.get().from(spec));\n   }\n   \n   public void testParse_authenticateSudoWithoutLoginUser() {\n      try {\n         parse(\"authenticateSudo=true\");\n         fail(\"Expected exception\");\n      } catch (IllegalArgumentException expected) {\n         // expected\n      }\n   }\n\n   public void testParse_authenticateSudo() {\n      TemplateBuilderSpec spec = parse(\"loginUser=root:toor,authenticateSudo=true\");\n      assertNull(spec.hardwareId);\n      assertNull(spec.minCores);\n      assertNull(spec.minRam);\n      assertNull(spec.minDisk);\n      assertNull(spec.imageId);\n      assertNull(spec.imageNameMatches);\n      assertNull(spec.hypervisorMatches);\n      assertNull(spec.osFamily);\n      assertNull(spec.osVersionMatches);\n      assertNull(spec.os64Bit);\n      assertNull(spec.osArchMatches);\n      assertNull(spec.osDescriptionMatches);\n      assertEquals(spec.loginUser, \"root:toor\");\n      assertEquals(spec.authenticateSudo.booleanValue(), true);\n      assertNull(spec.locationId);\n      assertNull(spec.forceCacheReload);\n      assertTemplateBuilderEquivalence(\n            templateBuilders.get().options(\n                  overrideLoginCredentials(LoginCredentials.builder().user(\"root\").password(\"toor\")\n                        .authenticateSudo(true).build())), templateBuilders.get().from(spec));\n   }\n   \n   public void testParse_authenticateSudoRepeated() {\n      try {\n         parse(\"loginUser=root:toor,authenticateSudo=true,authenticateSudo=false\");\n         fail(\"Expected exception\");\n      } catch (IllegalArgumentException expected) {\n         // expected\n      }\n   }\n   \n   public void testParse_forceCacheReload() {\n      TemplateBuilderSpec spec = parse(\"forceCacheReload=true\");\n      assertNull(spec.hardwareId);\n      assertNull(spec.minCores);\n      assertNull(spec.minRam);\n      assertNull(spec.minDisk);\n      assertNull(spec.imageId);\n      assertNull(spec.imageNameMatches);\n      assertNull(spec.hypervisorMatches);\n      assertNull(spec.osFamily);\n      assertNull(spec.osVersionMatches);\n      assertNull(spec.os64Bit);\n      assertNull(spec.osArchMatches);\n      assertNull(spec.osDescriptionMatches);\n      assertNull(spec.loginUser);\n      assertNull(spec.authenticateSudo);\n      assertNull(spec.locationId);\n      assertEquals(spec.forceCacheReload.booleanValue(), true);\n      assertTemplateBuilderEquivalence(templateBuilders.get().forceCacheReload(), templateBuilders.get().from(spec));\n   }\n\n   public void testParse_forceCacheReloadRepeated() {\n      try {\n         parse(\"forceCacheReload=true,forceCacheReload=false\");\n         fail(\"Expected exception\");\n      } catch (IllegalArgumentException expected) {\n         // expected\n      }\n   }\n\n   public void testParse_locationId() {\n      TemplateBuilderSpec spec = parse(\"locationId=stub\");\n      assertNull(spec.hardwareId);\n      assertNull(spec.minCores);\n      assertNull(spec.minRam);\n      assertNull(spec.minDisk);\n      assertNull(spec.hypervisorMatches);\n      assertNull(spec.imageId);\n      assertNull(spec.imageNameMatches);\n      assertNull(spec.osFamily);\n      assertNull(spec.osVersionMatches);\n      assertNull(spec.os64Bit);\n      assertNull(spec.osArchMatches);\n      assertNull(spec.osDescriptionMatches);\n      assertNull(spec.loginUser);\n      assertNull(spec.authenticateSudo);\n      assertEquals(spec.locationId, \"stub\");\n      assertNull(spec.forceCacheReload);\n      assertTemplateBuilderEquivalence(templateBuilders.get().locationId(\"stub\"),\n            templateBuilders.get().from(spec));\n   }\n   \n   public void testParse_locationIdRepeated() {\n      try {\n         parse(\"locationId=stub, locationId=stub\");\n         fail(\"Expected exception\");\n      } catch (IllegalArgumentException expected) {\n         // expected\n      }\n   }\n   \n   public void testParse_multipleKeys() {\n      TemplateBuilderSpec spec = parse(\"osFamily=UBUNTU,osVersionMatches=1[012].[01][04],imageNameMatches=.*w/ None.*\");\n      assertNull(spec.hardwareId);\n      assertNull(spec.minCores);\n      assertNull(spec.minRam);\n      assertNull(spec.minDisk);\n      assertNull(spec.hypervisorMatches);\n      assertNull(spec.imageId);\n      assertEquals(spec.imageNameMatches, \".*w/ None.*\");\n      assertEquals(spec.osFamily, OsFamily.UBUNTU);\n      assertEquals(spec.osVersionMatches, \"1[012].[01][04]\");\n      assertNull(spec.os64Bit);\n      assertNull(spec.osArchMatches);\n      assertNull(spec.osDescriptionMatches);\n      assertNull(spec.loginUser);\n      assertNull(spec.authenticateSudo);\n      assertNull(spec.locationId);\n      assertNull(spec.forceCacheReload);\n      TemplateBuilder expected = templateBuilders.get().osVersionMatches(\"1[012].[01][04]\").imageNameMatches(\".*w/ None.*\").osFamily(OsFamily.UBUNTU);\n      assertTemplateBuilderEquivalence(expected, templateBuilders.get().from(spec));\n   }\n\n   public void testParse_whitespaceAllowed() {\n      TemplateBuilderSpec spec = parse(\" minRam=10,\\nosFamily=UBUNTU\");\n      assertNull(spec.hardwareId);\n      assertNull(spec.minCores);\n      assertEquals(spec.minRam.intValue(), 10);\n      assertNull(spec.minDisk);\n      assertNull(spec.hypervisorMatches);\n      assertNull(spec.imageId);\n      assertNull(spec.imageNameMatches);\n      assertEquals(spec.osFamily, OsFamily.UBUNTU);\n      assertNull(spec.osVersionMatches);\n      assertNull(spec.os64Bit);\n      assertNull(spec.osArchMatches);\n      assertNull(spec.osDescriptionMatches);\n      assertNull(spec.loginUser);\n      assertNull(spec.authenticateSudo);\n      assertNull(spec.locationId);\n      assertNull(spec.forceCacheReload);\n      TemplateBuilder expected = templateBuilders.get().minRam(10).osFamily(OsFamily.UBUNTU);\n      assertTemplateBuilderEquivalence(expected, templateBuilders.get().from(spec));\n   }\n\n   public void testNiceJson() {\n      TemplateBuilderSpec spec = parse(\"osFamily=UBUNTU,osVersionMatches=1[012].[01][04],imageNameMatches=.*w/ None.*\");\n      assertEquals(new Gson().toJson(spec), \"{\\\"imageNameMatches\\\":\\\".*w/ None.*\\\",\\\"osFamily\\\":\\\"UBUNTU\\\",\\\"osVersionMatches\\\":\\\"1[012].[01][04]\\\"}\");\n      assertEquals(new Gson().fromJson(new Gson().toJson(spec), TemplateBuilderSpec.class), spec);\n   }\n   \n   public void testParse_unknownKey() {\n      try {\n         parse(\"foo=17\");\n         fail(\"Expected exception\");\n      } catch (IllegalArgumentException expected) {\n         // expected\n      }\n   }\n\n   public void testTemplateBuilderFrom_string() {\n      TemplateBuilder fromString = templateBuilders.get().from(\"minRam=10,osFamily=UBUNTU\");\n      TemplateBuilder expected = templateBuilders.get().minCores(30).minRam(10).osFamily(OsFamily.UBUNTU);\n      assertTemplateBuilderEquivalence(expected, fromString);\n   }\n\n   private void assertTemplateBuilderEquivalence(TemplateBuilder a, TemplateBuilder b) {\n      // Labs hack: dig into the TemplateBuilder instances, verifying all fields\n      // are equal.\n      for (Field f : TemplateBuilder.class.getFields()) {\n         f.setAccessible(true);\n         try {\n            assertEquals(f.get(a), f.get(b), \"Field \" + f.getName() + \" not equal\");\n         } catch (IllegalArgumentException e) {\n            throw new AssertionError(e.getMessage());\n         } catch (IllegalAccessException e) {\n            throw new AssertionError(e.getMessage());\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/domain/VolumeBuilderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.domain;\n\nimport static org.testng.Assert.assertNull;\n\nimport org.jclouds.compute.domain.Volume.Type;\nimport org.testng.annotations.Test;\n\n/**\n * Unit tests for org.jclouds.compute.domain.VolumeBuilder\n */\n@Test(testName = \"VolumeBuilderTest\", groups = \"unit\")\npublic class VolumeBuilderTest {\n\n    /**\n     * Ensures that an explicitly set null id results in no errors.\n     */\n    public void testNullDescription() {\n        Volume vol = new VolumeBuilder().id(null)\n                .type(Type.LOCAL)\n                .size(10.0f)\n                .device(\"/dev/sda1\")\n                .bootDevice(true)\n                .durable(false)\n                .build();\n        assertNull(vol.getId());\n    }\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/domain/internal/ArbitraryCpuRamTemplateBuilderImplTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.domain.internal;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.util.concurrent.Atomics;\nimport com.google.inject.Provider;\nimport com.google.inject.util.Providers;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.HardwareBuilder;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.ImageBuilder;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.Processor;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.domain.TemplateBuilder;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.compute.strategy.GetImageStrategy;\nimport org.jclouds.compute.suppliers.ImageCacheSupplier;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.rest.AuthorizationException;\nimport org.testng.annotations.Test;\n\nimport java.net.URI;\nimport java.util.Set;\n\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.easymock.EasyMock.anyObject;\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\n\n@Test(groups = \"unit\", singleThreaded = true, testName = \"ArbitraryCpuRamTemplateBuilderImplTest\")\npublic class ArbitraryCpuRamTemplateBuilderImplTest {\n   private Location provider = new LocationBuilder()\n         .scope(LocationScope.PROVIDER)\n         .id(\"generic-provider\")\n         .description(\"generic-provider\")\n         .build();\n\n   private Location region = new LocationBuilder()\n         .scope(LocationScope.REGION)\n         .id(\"us-east-1\")\n         .description(\"us-east-1\")\n         .parent(provider)\n         .build();\n\n   private OperatingSystem os = OperatingSystem.builder()\n         .name(\"osName\")\n         .version(\"osVersion\")\n         .description(\"osDescription\")\n         .arch(\"X86_32\")\n         .build();\n\n   private Image image = new ImageBuilder()\n         .id(\"imageId\")\n         .providerId(\"imageId\")\n         .name(\"imageName\")\n         .description(\"imageDescription\")\n         .version(\"imageVersion\")\n         .operatingSystem(os)\n         .status(Image.Status.AVAILABLE)\n         .location(null)\n         .build();\n\n   private Hardware hardware = new HardwareBuilder()\n         .ram(2048)\n         .processor(new Processor(2, 1))\n         .id(\"hardwareId\")\n         .name(\"hardwareName\")\n         .location(region)\n         .uri(URI.create(\"uri\"))\n         .build();\n\n   private final String errorMessage = \"No hardware profile matching the given criteria was found. If you want to use\" +\n           \" exact values, please set the minCores, minRam and minDisk to positive values.\";\n\n   @Test\n   public void testAutoGeneratedHardwareFromId(){\n      Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n            .of(region));\n      Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.of(image));\n      Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet\n            .<Hardware> of(hardware));\n      Provider<TemplateOptions> optionsProvider = createMock(Provider.class);\n      Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);\n      TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class);\n      GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class);\n\n      expect(optionsProvider.get()).andReturn(new TemplateOptions());\n      expect(getImageStrategy.getImage(anyObject(String.class))).andReturn(null);\n      replay(defaultTemplate, optionsProvider, templateBuilderProvider, getImageStrategy);\n\n      TemplateBuilderImpl templateBuilder = new ArbitraryCpuRamTemplateBuilderImpl(locations,\n            new ImageCacheSupplier(images, 60,\n                  Atomics.<AuthorizationException>newReference(), Providers.of(getImageStrategy)), hardwares,\n                  Suppliers.ofInstance(region),\n                  optionsProvider, templateBuilderProvider);\n\n      Hardware hardware = templateBuilder.hardwareId(\"automatic:cores=2;ram=256\").build().getHardware();\n      assertThat(hardware.getRam()).isEqualTo(256);\n      assertThat(hardware.getProcessors()).extracting(\"cores\").containsExactly(2.0);\n      assertThat(hardware.getId()).isEqualTo(\"automatic:cores=2.0;ram=256\");\n\n      Hardware hardware2 = templateBuilder.hardwareId(\"automatic:cores=2;ram=256;disk=100\").build().getHardware();\n      assertThat(hardware2.getRam()).isEqualTo(256);\n      assertThat(hardware2.getProcessors()).extracting(\"cores\").containsExactly(2.0);\n      assertThat(hardware2.getId()).isEqualTo(\"automatic:cores=2.0;ram=256;disk=100\");\n      assertThat(hardware2.getVolumes().get(0).getSize()).isEqualTo(100);\n   }\n\n   @Test\n   public void testAutoGeneratedHardwareWithMinCoresAndMinRam(){\n      Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet.of(region));\n      Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.of(image));\n      Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet\n            .<Hardware> of(hardware));\n      Provider<TemplateOptions> optionsProvider = createMock(Provider.class);\n      Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);\n      TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class);\n      GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class);\n\n      expect(optionsProvider.get()).andReturn(new TemplateOptions());\n      expect(getImageStrategy.getImage(anyObject(String.class))).andReturn(null);\n      replay(defaultTemplate, optionsProvider, templateBuilderProvider, getImageStrategy);\n      TemplateBuilderImpl templateBuilder = new ArbitraryCpuRamTemplateBuilderImpl(locations,\n            new ImageCacheSupplier(images, 60,\n                  Atomics.<AuthorizationException>newReference(), Providers.of(getImageStrategy)), hardwares,\n                  Suppliers.ofInstance(region), optionsProvider, templateBuilderProvider);\n      templateBuilder.minRam(1024);\n      templateBuilder.minCores(4);\n      Template template = templateBuilder.build();\n      Hardware hardware = template.getHardware();\n      assertThat(hardware.getRam()).isEqualTo(1024);\n      assertThat(hardware.getProcessors()).extracting(\"cores\").containsExactly(4.0);\n      assertThat(hardware.getId()).isEqualTo(\"automatic:cores=4.0;ram=1024\");\n   }\n\n   @Test\n   public void testAutoGeneratedHardwareWithMinCoresMinRamAndMinDisk() {\n      Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>>ofInstance(ImmutableSet.of(region));\n      Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>>ofInstance(ImmutableSet.of(image));\n      Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>>ofInstance(ImmutableSet\n            .<Hardware>of(hardware));\n      Provider<TemplateOptions> optionsProvider = createMock(Provider.class);\n      Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);\n      TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class);\n      GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class);\n\n      expect(optionsProvider.get()).andReturn(new TemplateOptions());\n      expect(getImageStrategy.getImage(anyObject(String.class))).andReturn(null);\n      replay(defaultTemplate, optionsProvider, templateBuilderProvider, getImageStrategy);\n      TemplateBuilderImpl templateBuilder = new ArbitraryCpuRamTemplateBuilderImpl(locations,\n            new ImageCacheSupplier(images, 60,\n                  Atomics.<AuthorizationException>newReference(), Providers.of(getImageStrategy)), hardwares,\n                  Suppliers.ofInstance(region), optionsProvider, templateBuilderProvider);\n      templateBuilder.minCores(2);\n      templateBuilder.minRam(2048);\n      templateBuilder.minDisk(100);\n      Template template = templateBuilder.build();\n      Hardware hardware = template.getHardware();\n      assertThat(hardware.getRam()).isEqualTo(2048);\n      assertThat(hardware.getProcessors()).extracting(\"cores\").containsExactly(2.0);\n      assertThat(hardware.getId()).isEqualTo(\"automatic:cores=2.0;ram=2048;disk=100\");\n      assertThat(hardware.getVolumes().get(0).getSize()).isEqualTo(100);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class,\n         expectedExceptionsMessageRegExp = errorMessage)\n   public void testAutoGeneratedHardwareWithMinCoresMinRamAndInvalidMinDisk() {\n      Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>>ofInstance(ImmutableSet.of(region));\n      Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>>ofInstance(ImmutableSet.of(image));\n      Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>>ofInstance(ImmutableSet\n            .<Hardware>of(hardware));\n      Provider<TemplateOptions> optionsProvider = createMock(Provider.class);\n      Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);\n      TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class);\n      GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class);\n\n      expect(optionsProvider.get()).andReturn(new TemplateOptions());\n      expect(getImageStrategy.getImage(anyObject(String.class))).andReturn(null);\n      replay(defaultTemplate, optionsProvider, templateBuilderProvider, getImageStrategy);\n      TemplateBuilderImpl templateBuilder = new ArbitraryCpuRamTemplateBuilderImpl(locations,\n            new ImageCacheSupplier(images, 60,\n               Atomics.<AuthorizationException>newReference(), Providers.of(getImageStrategy)), hardwares,\n               Suppliers.ofInstance(region), optionsProvider, templateBuilderProvider);\n      templateBuilder.minCores(2);\n      templateBuilder.minRam(4096);\n      templateBuilder.minDisk(-100f);\n      Template template = templateBuilder.build();\n      Hardware hardware = template.getHardware();\n      assertThat(hardware.getId()).isEqualTo(\"automatic:cores=2.0;ram=4096;disk=-100\");\n   }\n\n   @Test\n   public void testExistingHardwareProfileMatchHardwareProfileWithMinCoresMinRam() {\n      Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n            .of(region));\n      Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.of(image));\n      Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet\n            .<Hardware> of(hardware));\n      Provider<TemplateOptions> optionsProvider = createMock(Provider.class);\n      Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);\n      TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class);\n      GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class);\n\n      expect(optionsProvider.get()).andReturn(new TemplateOptions());\n      expect(getImageStrategy.getImage(anyObject(String.class))).andReturn(null);\n      replay(defaultTemplate, optionsProvider, templateBuilderProvider, getImageStrategy);\n      TemplateBuilderImpl templateBuilder = new ArbitraryCpuRamTemplateBuilderImpl(locations,\n            new ImageCacheSupplier(images, 60,\n                  Atomics.<AuthorizationException>newReference(), Providers.of(getImageStrategy)), hardwares,\n                  Suppliers.ofInstance(region), optionsProvider, templateBuilderProvider);\n      templateBuilder.minCores(2);\n      templateBuilder.minRam(1024);\n      Template template = templateBuilder.build();\n      Hardware hardware = template.getHardware();\n      assertThat(hardware.getRam()).isEqualTo(2048);\n      assertThat(hardware.getProcessors()).extracting(\"cores\").containsExactly(2.0);\n      assertThat(hardware.getId()).isEqualTo(\"hardwareId\");\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class,\n         expectedExceptionsMessageRegExp = errorMessage)\n   public void testOnlyRam() {\n      Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet.of(region));\n      Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.of(image));\n      Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet\n            .<Hardware> of(hardware));\n      Provider<TemplateOptions> optionsProvider = createMock(Provider.class);\n      Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);\n      TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class);\n      GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class);\n\n      expect(optionsProvider.get()).andReturn(new TemplateOptions());\n      expect(getImageStrategy.getImage(anyObject(String.class))).andReturn(null);\n      replay(defaultTemplate, optionsProvider, templateBuilderProvider, getImageStrategy);\n      TemplateBuilderImpl templateBuilder = new ArbitraryCpuRamTemplateBuilderImpl(locations,\n            new ImageCacheSupplier(images, 60,\n                  Atomics.<AuthorizationException>newReference(), Providers.of(getImageStrategy)), hardwares,\n                  Suppliers.ofInstance(region), optionsProvider, templateBuilderProvider);\n      templateBuilder.minRam(4096);\n      templateBuilder.build();\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class,\n         expectedExceptionsMessageRegExp = errorMessage)\n   public void testOnlyCores() {\n      Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n            .of(region));\n      Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.of(image));\n      Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet\n            .<Hardware> of(hardware));\n      Provider<TemplateOptions> optionsProvider = createMock(Provider.class);\n      Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);\n      TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class);\n      GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class);\n\n      expect(optionsProvider.get()).andReturn(new TemplateOptions());\n      expect(getImageStrategy.getImage(anyObject(String.class))).andReturn(null);\n      replay(defaultTemplate, optionsProvider, templateBuilderProvider, getImageStrategy);\n      TemplateBuilderImpl templateBuilder = new ArbitraryCpuRamTemplateBuilderImpl(locations,\n            new ImageCacheSupplier(images, 60,\n                  Atomics.<AuthorizationException>newReference(), Providers.of(getImageStrategy)), hardwares,\n                  Suppliers.ofInstance(region), optionsProvider, templateBuilderProvider);\n      templateBuilder.minCores(4);\n      templateBuilder.build();\n   }\n\n   @Test\n   public void testOnlyRamMatchHardwareProfile() {\n      Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet.of(region));\n      Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.of(image));\n      Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet\n            .<Hardware> of(hardware));\n      Provider<TemplateOptions> optionsProvider = createMock(Provider.class);\n      Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);\n      TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class);\n      GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class);\n\n      expect(optionsProvider.get()).andReturn(new TemplateOptions());\n      expect(getImageStrategy.getImage(anyObject(String.class))).andReturn(null);\n      replay(defaultTemplate, optionsProvider, templateBuilderProvider, getImageStrategy);\n      TemplateBuilderImpl templateBuilder = new ArbitraryCpuRamTemplateBuilderImpl(locations,\n            new ImageCacheSupplier(images, 60,\n                  Atomics.<AuthorizationException>newReference(), Providers.of(getImageStrategy)), hardwares,\n                  Suppliers.ofInstance(region), optionsProvider, templateBuilderProvider);\n      templateBuilder.minRam(1024);\n      templateBuilder.build();\n      assertThat(hardware.getRam()).isEqualTo(2048);\n      assertThat(hardware.getProcessors()).extracting(\"cores\").containsExactly(2.0);\n      assertThat(hardware.getId()).isEqualTo(\"hardwareId\");\n   }\n\n   @Test\n   public void testOnlyCoresMatchHardwareProfile() {\n      Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n            .of(region));\n      Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.of(image));\n      Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet\n            .<Hardware> of(hardware));\n      Provider<TemplateOptions> optionsProvider = createMock(Provider.class);\n      Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);\n      TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class);\n      GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class);\n\n      expect(optionsProvider.get()).andReturn(new TemplateOptions());\n      expect(getImageStrategy.getImage(anyObject(String.class))).andReturn(null);\n      replay(defaultTemplate, optionsProvider, templateBuilderProvider, getImageStrategy);\n      TemplateBuilderImpl templateBuilder = new ArbitraryCpuRamTemplateBuilderImpl(locations,\n            new ImageCacheSupplier(images, 60,\n                  Atomics.<AuthorizationException>newReference(), Providers.of(getImageStrategy)), hardwares,\n            Suppliers.ofInstance(region), optionsProvider, templateBuilderProvider);\n      templateBuilder.minCores(1);\n      templateBuilder.build();\n      assertThat(hardware.getRam()).isEqualTo(2048);\n      assertThat(hardware.getProcessors()).extracting(\"cores\").containsExactly(2.0);\n      assertThat(hardware.getId()).isEqualTo(\"hardwareId\");\n   }\n\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/domain/internal/NullEqualToIsParentOrIsGrandparentOfCurrentLocationTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.domain.internal;\n\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.HardwareBuilder;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Suppliers;\n\n@Test(testName = \"NullEqualToIsParentOrIsGrandparentOfCurrentLocationTest\")\npublic class NullEqualToIsParentOrIsGrandparentOfCurrentLocationTest {\n   Location provider = new LocationBuilder().scope(LocationScope.PROVIDER).id(\"aws-ec2\").description(\"aws-ec2\").build();\n\n   Location region = new LocationBuilder().scope(LocationScope.REGION).id(\"us-east-1\").description(\"us-east-1\")\n         .parent(provider).build();\n\n   Location zone = new LocationBuilder().scope(LocationScope.ZONE).id(\"us-east-1a\").description(\"us-east-1a\")\n         .parent(region).build();\n\n   Location host = new LocationBuilder().scope(LocationScope.HOST).id(\"xxxxx\").description(\"xxxx\").parent(zone).build();\n\n   Location otherRegion = new LocationBuilder().scope(LocationScope.REGION).id(\"us-west-1\").description(\"us-west-1\")\n         .parent(provider).build();\n\n   Location otherZone = new LocationBuilder().scope(LocationScope.ZONE).id(\"us-west-1a\").description(\"us-west-1a\")\n         .parent(otherRegion).build();\n\n   Location orphanedRegion = new LocationBuilder().scope(LocationScope.REGION).id(\"us-east-1\").description(\"us-east-1\")\n         .build();\n   \n   Location orphanedZone = new LocationBuilder().scope(LocationScope.ZONE).id(\"us-east-1a\")\n         .description(\"us-east-1a\").build();\n   /**\n    * If the current location id is null, then we don't care where to launch a\n    */\n   public void testReturnTrueWhenIDontSpecifyALocation() {\n      NullEqualToIsParentOrIsGrandparentOfCurrentLocation predicate = new NullEqualToIsParentOrIsGrandparentOfCurrentLocation(Suppliers.<Location> ofInstance(null));\n      Hardware md = new HardwareBuilder().id(\"foo\").location(region).build();\n      assertTrue(predicate.apply(md));\n   }\n\n   /**\n    * If the input location is null, then the data isn't location sensitive\n    */\n   public void testReturnTrueWhenISpecifyALocationAndInputLocationIsNull() {\n      NullEqualToIsParentOrIsGrandparentOfCurrentLocation predicate = new NullEqualToIsParentOrIsGrandparentOfCurrentLocation(Suppliers.ofInstance(region));\n      Hardware md = new HardwareBuilder().id(\"foo\").location(null).build();\n      assertTrue(predicate.apply(md));\n   }\n\n   /**\n    * If the input location is null, then the data isn't location sensitive\n    */\n   public void testReturnTrueWhenIDontSpecifyALocationAndInputLocationIsNull() {\n      NullEqualToIsParentOrIsGrandparentOfCurrentLocation predicate = new NullEqualToIsParentOrIsGrandparentOfCurrentLocation(Suppliers.<Location> ofInstance(null));\n      Hardware md = new HardwareBuilder().id(\"foo\").location(null).build();\n      assertTrue(predicate.apply(md));\n   }\n\n   @Test\n   public void testReturnTrueWhenISpecifyARegionAndInputLocationIsProvider() {\n      NullEqualToIsParentOrIsGrandparentOfCurrentLocation predicate = new NullEqualToIsParentOrIsGrandparentOfCurrentLocation(Suppliers.ofInstance(region));\n      Hardware md = new HardwareBuilder().id(\"foo\").location(provider).build();\n      assertTrue(predicate.apply(md));\n   }\n\n   /**\n    * When locations are equal\n    */\n   @Test\n   public void testReturnFalseWhenISpecifyALocationWhichTheSameScopeByNotEqualToInputLocationAndParentsAreNull() {\n      NullEqualToIsParentOrIsGrandparentOfCurrentLocation predicate = new NullEqualToIsParentOrIsGrandparentOfCurrentLocation(Suppliers.ofInstance(region));\n      Hardware md = new HardwareBuilder().id(\"foo\").location(otherRegion).build();\n      assertFalse(predicate.apply(md));\n   }\n\n   /**\n    * If the input location is null, then the data isn't location sensitive\n    */\n   public void testReturnFalseWhenISpecifyALocationWhichTheSameScopeByNotEqualToInputLocationAndParentsAreNotNull() {\n      NullEqualToIsParentOrIsGrandparentOfCurrentLocation predicate = new NullEqualToIsParentOrIsGrandparentOfCurrentLocation(Suppliers.ofInstance(zone));\n      Hardware md = new HardwareBuilder().id(\"foo\").location(otherZone).build();\n      assertFalse(predicate.apply(md));\n   }\n\n   /**\n    * If the input location is a parent of the specified location, then we are\n    * ok.\n    */\n   public void testReturnTrueWhenISpecifyALocationWhichIsAChildOfInput() {\n      NullEqualToIsParentOrIsGrandparentOfCurrentLocation predicate = new NullEqualToIsParentOrIsGrandparentOfCurrentLocation(Suppliers.ofInstance(zone));\n      Hardware md = new HardwareBuilder().id(\"foo\").location(region).build();\n      assertTrue(predicate.apply(md));\n   }\n\n   /**\n    * If the input location is a parent of the specified location, then we are\n    * ok.\n    */\n   public void testReturnFalseWhenISpecifyALocationWhichIsNotAChildOfInput() {\n      NullEqualToIsParentOrIsGrandparentOfCurrentLocation predicate = new NullEqualToIsParentOrIsGrandparentOfCurrentLocation(Suppliers.ofInstance(zone));\n      Hardware md = new HardwareBuilder().id(\"foo\").location(otherRegion).build();\n      assertFalse(predicate.apply(md));\n   }\n\n   /**\n    * If the input location is a grandparent of the specified location, then we\n    * are ok.\n    */\n   public void testReturnTrueWhenISpecifyALocationWhichIsAGrandChildOfInput() {\n      NullEqualToIsParentOrIsGrandparentOfCurrentLocation predicate = new NullEqualToIsParentOrIsGrandparentOfCurrentLocation(Suppliers.ofInstance(host));\n\n      Hardware md = new HardwareBuilder().id(\"foo\").location(host).build();\n      assertTrue(predicate.apply(md));\n   }\n\n   /**\n    * If the input location is a grandparent of the specified location, then we\n    * are ok.\n    */\n   public void testReturnFalseWhenISpecifyALocationWhichIsNotAGrandChildOfInput() {\n      NullEqualToIsParentOrIsGrandparentOfCurrentLocation predicate = new NullEqualToIsParentOrIsGrandparentOfCurrentLocation(Suppliers.ofInstance(host));\n      Hardware md = new HardwareBuilder().id(\"foo\").location(otherRegion).build();\n      assertFalse(predicate.apply(md));\n   }\n\n   /**\n    * Only the PROVIDER scope should have a null parent, It is an illegal state if a ZONE or REGION are orphaned\n    * \n    */\n   @Test(expectedExceptions = IllegalStateException.class)\n   public void testThrowIllegalStateExceptionWhenInputIsAnOrphanedRegion() {\n      NullEqualToIsParentOrIsGrandparentOfCurrentLocation predicate = new NullEqualToIsParentOrIsGrandparentOfCurrentLocation(Suppliers.ofInstance(region));\n      Hardware md = new HardwareBuilder().id(\"foo\").location(orphanedRegion).build();\n      predicate.apply(md);\n   }\n   \n   /**\n    * Only the PROVIDER scope should have a null parent, It is an illegal state if a ZONE or REGION are orphaned\n    * \n    */\n   @Test(expectedExceptions = IllegalStateException.class)\n   public void testThrowIllegalStateExceptionWhenInputIsAnOrphanedZone() {\n      NullEqualToIsParentOrIsGrandparentOfCurrentLocation predicate = new NullEqualToIsParentOrIsGrandparentOfCurrentLocation(Suppliers.ofInstance(region));\n      Hardware md = new HardwareBuilder().id(\"foo\").location(orphanedZone).build();\n      predicate.apply(md);\n   }\n\n   /**\n    * Only the PROVIDER scope should have a null parent, It is an illegal state if a ZONE or REGION are orphaned\n    * \n    */\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testThrowIllegalArgumentExceptionWhenWhenISpecifyAnOrphanedRegion() {\n      NullEqualToIsParentOrIsGrandparentOfCurrentLocation predicate = new NullEqualToIsParentOrIsGrandparentOfCurrentLocation(Suppliers.ofInstance(orphanedRegion));\n      Hardware md = new HardwareBuilder().id(\"foo\").location(region).build();\n      predicate.apply(md);\n   }\n   \n   /**\n    * Only the PROVIDER scope should have a null parent, It is an illegal state if a ZONE or REGION are orphaned\n    * \n    */\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testThrowIllegalArgumentExceptionWhenWhenISpecifyAnOrphanedZone() {\n      NullEqualToIsParentOrIsGrandparentOfCurrentLocation predicate = new NullEqualToIsParentOrIsGrandparentOfCurrentLocation(Suppliers.ofInstance(orphanedZone));\n      Hardware md = new HardwareBuilder().id(\"foo\").location(region).build();\n      predicate.apply(md);\n   }\n\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/domain/internal/TemplateBuilderImplTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.domain.internal;\n\nimport static org.easymock.EasyMock.anyObject;\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.Assert.fail;\n\nimport java.util.Arrays;\nimport java.util.NoSuchElementException;\nimport java.util.Set;\n\nimport jakarta.inject.Provider;\n\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.HardwareBuilder;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.Image.Status;\nimport org.jclouds.compute.domain.ImageBuilder;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.Processor;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.domain.TemplateBuilder;\nimport org.jclouds.compute.domain.Volume;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.compute.predicates.ImagePredicates;\nimport org.jclouds.compute.strategy.GetImageStrategy;\nimport org.jclouds.compute.suppliers.ImageCacheSupplier;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.rest.AuthorizationException;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Functions;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ComparisonChain;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Ordering;\nimport com.google.common.util.concurrent.Atomics;\nimport com.google.inject.util.Providers;\n\n@Test(groups = \"unit\", singleThreaded = true, testName = \"TemplateBuilderImplTest\")\npublic class TemplateBuilderImplTest {\n\n   public void testMultiMax() {\n      Iterable<String> values = ImmutableList.of(\"1\", \"2\", \"2\", \"3\", \"3\");\n      assertEquals(TemplateBuilderImpl.multiMax(Ordering.natural(), values), ImmutableList.of(\"3\", \"3\"));\n   }\n\n   public void testMultiMax1() {\n      Iterable<String> values = ImmutableList.of(\"1\", \"2\", \"2\", \"3\");\n      assertEquals(TemplateBuilderImpl.multiMax(Ordering.natural(), values), ImmutableList.of(\"3\"));\n   }\n   \n   public void testMultiMax2() {\n      // check with max buried in the middle\n      Iterable<String> values = ImmutableList.of(\"1\", \"3\", \"2\", \"2\");\n      assertEquals(TemplateBuilderImpl.multiMax(Ordering.natural(), values), ImmutableList.of(\"3\"));\n   }\n\n   public void testMultiMaxNull() {\n      // we rely on checking nulls in some Orderings, so assert it also does what we expect\n      // (unfortunately can't use ImmutableList here as that doesn't allow nulls)\n      Iterable<String> values = Arrays.asList(\"1\", \"3\", null, \"2\", \"2\");\n      assertEquals(TemplateBuilderImpl.multiMax(Ordering.natural().nullsLast(), values), Arrays.asList((Object)null));\n   }\n\n   public void testMultiMaxNulls() {\n      Iterable<String> values = Arrays.asList(\"1\", \"3\", null, \"2\", \"2\", null);\n      assertEquals(TemplateBuilderImpl.multiMax(Ordering.natural().nullsLast(), values), Arrays.asList((Object)null, null));\n   }\n\n   protected Location provider = new LocationBuilder().scope(LocationScope.PROVIDER).id(\"aws-ec2\").description(\"aws-ec2\").build();\n\n   protected Location region = new LocationBuilder().scope(LocationScope.REGION).id(\"us-east-1\")\n            .description(\"us-east-1\").parent(provider).build();\n\n   protected Location region2 = new LocationBuilder().scope(LocationScope.REGION).id(\"us-east-2\")\n            .description(\"us-east-2\").parent(provider).build();\n\n   protected OperatingSystem os = OperatingSystem.builder().name(\"osName\").version(\"osVersion\")\n            .description(\"osDescription\").arch(\"X86_32\").build();\n\n   protected String getProviderFormatId(String uniqueLabel) {\n       return uniqueLabel;\n   }\n   \n   protected Image image = new ImageBuilder().id(getProviderFormatId(\"imageId\")).providerId(\"imageId\").name(\"imageName\")\n            .description(\"imageDescription\").version(\"imageVersion\").operatingSystem(os).status(Image.Status.AVAILABLE)\n            .location(region).build();\n\n   protected Image image64bit = ImageBuilder.fromImage(image).id(getProviderFormatId(\"image64bId\")).providerId(\"image64bId\")\n            .operatingSystem(os.toBuilder().arch(\"X86_64\").build()).build();\n\n   protected Image imageArchNull = ImageBuilder.fromImage(image).id(getProviderFormatId(\"imageArchNullId\")).providerId(\"imageArchNullId\")\n            .operatingSystem(os.toBuilder().arch(null).build()).build();\n\n   protected Image imageNameAlt = ImageBuilder.fromImage(image).id(getProviderFormatId(\"imageNameAltId\")).providerId(\"imageNameAltId\")\n            .name(\"alternateImageName\").build();\n\n   @SuppressWarnings(\"unchecked\")\n   public void testLocationPredicateWhenComputeMetadataIsNotLocationBound() {\n\n      Hardware hardware = new HardwareBuilder().id(\"hardwareId\").build();\n\n      Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n               .<Location> of(region));\n      Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of(image));\n      Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet\n               .<Hardware> of(hardware));\n      Provider<TemplateOptions> optionsProvider = createMock(Provider.class);\n      Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);\n      TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class);\n      GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class);\n\n      replay(defaultTemplate, optionsProvider, templateBuilderProvider, getImageStrategy);\n\n      TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, hardwares, region,\n               optionsProvider, templateBuilderProvider, getImageStrategy);\n      assert template.locationPredicate.apply(hardware);\n\n      verify(defaultTemplate, optionsProvider, templateBuilderProvider, getImageStrategy);\n   }\n   \n   /**\n    * Resolves images using a default TemplateBuilder, optionally applying a customizer to that\n    * TemplateBuilder where the customizer may e.g. apply an imageChooser\n    */\n   @SuppressWarnings(\"unchecked\")\n   protected void doTestResolveImagesWithTemplateBuilderCustomizer(\n         Supplier<Set<? extends Image>> inputImages,\n         Function<TemplateBuilderImpl, TemplateBuilderImpl> templateBuilderPerTestCustomizer,\n         Image expectedBest) {\n\n      Hardware hardware = new HardwareBuilder().id(\"hardwareId\").build();\n\n      Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n               .<Location> of(region));\n      Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet\n               .<Hardware> of(hardware));\n      Provider<TemplateOptions> optionsProvider = createMock(Provider.class);\n      Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);\n      TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class);\n      GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class);\n\n      replay(defaultTemplate, optionsProvider, templateBuilderProvider, getImageStrategy);\n\n      TemplateBuilderImpl template = createTemplateBuilder(null, locations, inputImages, hardwares, region,\n               optionsProvider, templateBuilderProvider, getImageStrategy);\n      template = templateBuilderPerTestCustomizer.apply(template);\n\n      assertEquals(template.resolveImage(hardware, inputImages.get()), expectedBest);\n\n      verify(defaultTemplate, optionsProvider, templateBuilderProvider, getImageStrategy);\n   }\n\n   protected void doTestResolveImages(Supplier<Set<? extends Image>> inputImages, Image expectedBest) {\n       doTestResolveImagesWithTemplateBuilderCustomizer(\n             inputImages,\n             Functions.<TemplateBuilderImpl>identity(),\n             expectedBest);\n   }\n\n   public void testResolveImagesSimple() {\n      doTestResolveImages(\n            Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of(image, image64bit)),\n            image64bit);\n   }\n\n   public void testResolveImagesPrefersNull() {\n      // preferring null has been the default behaviour; not sure if this is ideal\n      // (would make more sense to prefer nonNull) but don't change behaviour by default\n      doTestResolveImages(\n            Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of(image, imageArchNull, image64bit)),\n            imageArchNull);\n   }\n\n   public void testResolveImagesCustomSorterPreferringNonNull() {\n      // preferring null has been the default behaviour;\n      // see comments in TemplateBuilderImpl.DEFAULT_IMAGE_ORDERING\n\n      final Ordering<Image> sorterPreferringNonNullArch = new Ordering<Image>() {\n         @Override\n         public int compare(Image left, Image right) {\n            return ComparisonChain.start()\n                   .compare(left.getOperatingSystem().getArch(), right.getOperatingSystem().getArch(),\n                       Ordering.<String> natural().nullsFirst())\n                   .compare(left, right, TemplateBuilderImpl.DEFAULT_IMAGE_ORDERING)\n                   .result();\n         }\n      };\n      assertTrue(TemplateBuilderImpl.DEFAULT_IMAGE_ORDERING.compare(image64bit, imageArchNull) < 0, \"wrong default image ordering\");\n      assertTrue(sorterPreferringNonNullArch.compare(image64bit, imageArchNull) > 0, \"wrong custom image ordering\");\n\n      Function<TemplateBuilderImpl, TemplateBuilderImpl> tbCustomiser = new Function<TemplateBuilderImpl, TemplateBuilderImpl>() {\n         @Override\n         public TemplateBuilderImpl apply(TemplateBuilderImpl input) {\n            return input.imageChooser(input.imageChooserFromOrdering(sorterPreferringNonNullArch));\n         }\n      };\n\n      doTestResolveImagesWithTemplateBuilderCustomizer(\n            Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of(image, imageArchNull, image64bit)),\n            tbCustomiser, image64bit);\n   }\n\n   public void testResolveImagesPrefersImageBecauseNameIsLastAlphabetically() {\n      // preferring that which comes later alphabetically is the default behaviour;\n      // see comments in TemplateBuilderImpl.DEFAULT_IMAGE_ORDERING\n      doTestResolveImages(\n            Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of(imageNameAlt, image)),\n            image);\n   }\n\n   public void testResolveImagesCustomSorterPreferringAltImage() {\n      Function<TemplateBuilderImpl, TemplateBuilderImpl> tbSortWithAlternate = new Function<TemplateBuilderImpl, TemplateBuilderImpl>() {\n         @Override\n         public TemplateBuilderImpl apply(TemplateBuilderImpl input) {\n            return input.imageChooser(input.imageChooserFromOrdering(new Ordering<Image>() {\n               private int score(Image img) {\n                  if (img.getName().contains(\"alternate\")) return 10;\n                  return 0;\n               }\n               @Override\n               public int compare(Image left, Image right) {\n                  return score(left) - score(right);\n               }\n            }));\n         }\n      };\n      doTestResolveImagesWithTemplateBuilderCustomizer(\n            Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of(imageNameAlt, image, imageArchNull, image64bit)),\n            tbSortWithAlternate, imageNameAlt);\n   }\n\n   public void testResolveImagesCustomChooserPreferringAltImage() {\n      Function<TemplateBuilderImpl, TemplateBuilderImpl> tbChooseAlternate = new Function<TemplateBuilderImpl, TemplateBuilderImpl>() {\n         @Override\n         public TemplateBuilderImpl apply(TemplateBuilderImpl input) {\n            return input.imageChooser(new Function<Iterable<? extends Image>, Image>() {\n               @Override\n               public Image apply(Iterable<? extends Image> input) {\n                  return Iterables.find(input, new Predicate<Image>() {\n                     @Override\n                     public boolean apply(Image input) {\n                        return input.getName() != null && input.getName().contains(\"alternate\");\n                     }\n                  });\n               }\n            });\n         }\n      };\n      doTestResolveImagesWithTemplateBuilderCustomizer(\n            Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of(imageNameAlt, image, imageArchNull, image64bit)),\n            tbChooseAlternate, imageNameAlt);\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Test\n   public void testArchWins() {\n\n      Hardware hardware = new HardwareBuilder().id(\"hardwareId\").build();\n\n      Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n               .<Location> of(region));\n      Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of(\n               image, image64bit));\n      Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet\n               .<Hardware> of(hardware));\n      Provider<TemplateOptions> optionsProvider = createMock(Provider.class);\n      Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);\n      TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class);\n      GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class);\n\n      expect(optionsProvider.get()).andReturn(new TemplateOptions());\n\n      replay(defaultTemplate, optionsProvider, templateBuilderProvider, getImageStrategy);\n\n      TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, hardwares, region,\n               optionsProvider, templateBuilderProvider, getImageStrategy);\n\n      assertEquals(template.smallest().osArchMatches(\"X86_32\").build().getImage(), image);\n\n      verify(defaultTemplate, optionsProvider, templateBuilderProvider, getImageStrategy);\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Test\n   public void testHardwareWithImageIdPredicateOnlyAcceptsImage() {\n\n      Hardware hardware = new HardwareBuilder().id(\"hardwareId\").supportsImage(ImagePredicates.idEquals(getProviderFormatId(\"imageId\")))\n               .build();\n\n      Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n               .<Location> of(region));\n      Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet\n               .<Image> of(image));\n      Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet\n               .<Hardware> of(hardware));\n      Provider<TemplateOptions> optionsProvider = createMock(Provider.class);\n      Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);\n      TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class);\n      GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class);\n\n      expect(optionsProvider.get()).andReturn(new TemplateOptions());\n\n      replay(defaultTemplate, optionsProvider, templateBuilderProvider, getImageStrategy);\n\n      TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, hardwares, region,\n               optionsProvider, templateBuilderProvider, getImageStrategy);\n\n      template.imageId(getProviderFormatId(\"imageId\")).build();\n\n      verify(defaultTemplate, optionsProvider, templateBuilderProvider, getImageStrategy);\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Test\n   public void testHardwareWithImageIdPredicateOnlyAcceptsImageWhenLocationNull() {\n\n      Hardware hardware = new HardwareBuilder().id(\"hardwareId\").supportsImage(ImagePredicates.idEquals(getProviderFormatId(\"imageId\")))\n               .build();\n\n      Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n               .<Location> of(region));\n      Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet\n               .<Image> of(image));\n      Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet\n               .<Hardware> of(hardware));\n      Provider<TemplateOptions> optionsProvider = createMock(Provider.class);\n      Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);\n      TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class);\n      GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class);\n\n      expect(optionsProvider.get()).andReturn(new TemplateOptions());\n\n      replay(defaultTemplate, optionsProvider, templateBuilderProvider, getImageStrategy);\n\n      TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, hardwares, region,\n               optionsProvider, templateBuilderProvider, getImageStrategy);\n\n      template.imageId(getProviderFormatId(\"imageId\")).build();\n\n      verify(defaultTemplate, optionsProvider, templateBuilderProvider, getImageStrategy);\n\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Test\n   public void testHardwareWithImageIdPredicateOnlyDoesntImage() {\n\n      Hardware hardware = new HardwareBuilder().id(\"hardwareId\").supportsImage(ImagePredicates.idEquals(\"differentImageId\"))\n               .build();\n\n      Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n               .<Location> of(region));\n      Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet\n               .<Image> of(image));\n      Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet\n               .<Hardware> of(hardware));\n      Provider<TemplateOptions> optionsProvider = createMock(Provider.class);\n      Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);\n      TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class);\n      GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class);\n\n      expect(optionsProvider.get()).andReturn(new TemplateOptions());\n      \n      replay(defaultTemplate, optionsProvider, templateBuilderProvider, getImageStrategy);\n      \n      TemplateBuilderImpl template = createTemplateBuilder(image, locations, images, hardwares, region,\n               optionsProvider, templateBuilderProvider, getImageStrategy);\n      try {\n         template.imageId(getProviderFormatId(\"imageId\")).build();\n         fail(\"Expected NoSuchElementException\");\n      } catch (NoSuchElementException e) {\n         // make sure message is succinct\n         assertEquals(e.getMessage(), \"no hardware profiles support images matching params: idEquals(differentImageId)\");\n         verify(defaultTemplate, optionsProvider, templateBuilderProvider, getImageStrategy);\n      }\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Test\n   public void testOptionsUsesDefaultTemplateBuilder() {\n      TemplateOptions options = provideTemplateOptions();\n      TemplateOptions from = provideTemplateOptions();\n\n      Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n               .<Location> of());\n      Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of());\n      Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet\n               .<Hardware> of());\n      Location defaultLocation = createMock(Location.class);\n      Provider<TemplateOptions> optionsProvider = createMock(Provider.class);\n      Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);\n      TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class);\n      GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class);\n\n      expect(templateBuilderProvider.get()).andReturn(defaultTemplate);\n      expect(defaultTemplate.options(from)).andReturn(defaultTemplate);\n      expect(defaultTemplate.build()).andReturn(null);\n      expect(optionsProvider.get()).andReturn(from).atLeastOnce();\n\n      replay(defaultTemplate, defaultLocation, optionsProvider, templateBuilderProvider, getImageStrategy);\n\n      TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, hardwares, defaultLocation,\n               optionsProvider, templateBuilderProvider, getImageStrategy);\n\n      template.options(options).build();\n\n      verify(defaultTemplate, defaultLocation, optionsProvider, templateBuilderProvider, getImageStrategy);\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Test\n   public void testNothingUsesDefaultTemplateBuilder() {\n\n      Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n               .<Location> of());\n      Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of());\n      Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet\n               .<Hardware> of());\n\n      Location defaultLocation = createMock(Location.class);\n      Provider<TemplateOptions> optionsProvider = createMock(Provider.class);\n      Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);\n      TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class);\n      GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class);\n\n      expect(templateBuilderProvider.get()).andReturn(defaultTemplate);\n      expect(defaultTemplate.build()).andReturn(null);\n\n      replay(defaultTemplate, defaultLocation, optionsProvider, templateBuilderProvider, getImageStrategy);\n\n      TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, hardwares, defaultLocation,\n               optionsProvider, templateBuilderProvider, getImageStrategy);\n\n      template.build();\n\n      verify(defaultTemplate, defaultLocation, optionsProvider, templateBuilderProvider, getImageStrategy);\n   }\n\n   protected TemplateBuilderImpl createTemplateBuilder(Image knownImage, Supplier<Set<? extends Location>> locations,\n            Supplier<Set<? extends Image>> images, Supplier<Set<? extends Hardware>> hardwares,\n            Location defaultLocation, Provider<TemplateOptions> optionsProvider,\n            Provider<TemplateBuilder> templateBuilderProvider, GetImageStrategy getImageStrategy) {\n      TemplateBuilderImpl template = new TemplateBuilderImpl(locations, new ImageCacheSupplier(images, 60,\n            Atomics.<AuthorizationException> newReference(), Providers.of(getImageStrategy)), hardwares,\n            Suppliers.ofInstance(defaultLocation),\n            optionsProvider, templateBuilderProvider);\n      return template;\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Test\n   public void testSuppliedImageLocationWiderThanDefault() {\n      TemplateOptions from = provideTemplateOptions();\n\n      Hardware hardware = new HardwareBuilder().id(\"hardwareId\").supportsImage(ImagePredicates.idEquals(image.getId())).build();\n\n      Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n               .<Location> of(provider, region));\n      Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet\n               .<Image> of(image));\n      Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet\n               .<Hardware> of(hardware));\n\n      Provider<TemplateOptions> optionsProvider = createMock(Provider.class);\n      Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);\n      TemplateOptions defaultOptions = createMock(TemplateOptions.class);\n      GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class);\n      expect(optionsProvider.get()).andReturn(from).atLeastOnce();\n\n      replay(defaultOptions, optionsProvider, templateBuilderProvider, getImageStrategy);\n\n      TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, hardwares, region,\n               optionsProvider, templateBuilderProvider, getImageStrategy);\n\n      assertEquals(template.imageId(image.getId()).locationId(provider.getId()).build().getLocation(), region);\n\n      verify(defaultOptions, optionsProvider, templateBuilderProvider, getImageStrategy);\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Test\n   public void testSuppliedLocationWithNoOptions() {\n      Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n               .<Location> of(region));\n      Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of());\n      Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet\n               .<Hardware> of());\n      Provider<TemplateOptions> optionsProvider = createMock(Provider.class);\n      Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);\n      TemplateOptions defaultOptions = createMock(TemplateOptions.class);\n      GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class);\n\n      replay(defaultOptions, optionsProvider, templateBuilderProvider, getImageStrategy);\n\n      TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, hardwares, region,\n               optionsProvider, templateBuilderProvider, getImageStrategy);\n\n      try {\n         template.imageId(\"foo\").locationId(\"location\").build();\n         fail(\"Expected NoSuchElementException\");\n      } catch (NoSuchElementException e) {\n\n      }\n\n      verify(defaultOptions, optionsProvider, templateBuilderProvider, getImageStrategy);\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Test\n   public void testSuppliedLocationAndOptions() {\n      TemplateOptions from = provideTemplateOptions();\n\n      Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n               .<Location> of(region));\n      Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of());\n      Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet\n               .<Hardware> of());\n      Provider<TemplateOptions> optionsProvider = createMock(Provider.class);\n      Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);\n      GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class);\n\n      expect(optionsProvider.get()).andReturn(from).atLeastOnce();\n\n      replay(optionsProvider, templateBuilderProvider, getImageStrategy);\n\n      TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, hardwares, region,\n               optionsProvider, templateBuilderProvider, getImageStrategy);\n\n      try {\n         template.imageId(\"foo\").options(provideTemplateOptions()).locationId(\"location\").build();\n         fail(\"Expected NoSuchElementException\");\n      } catch (NoSuchElementException e) {\n\n      }\n\n      verify(optionsProvider, templateBuilderProvider, getImageStrategy);\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   public void testImagesMustBePresentWhenQuerying() {\n      Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n               .<Location> of(region));\n      Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of());\n      Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet\n               .<Hardware> of(createMock(Hardware.class)));\n      Provider<TemplateOptions> optionsProvider = createMock(Provider.class);\n      Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);\n      TemplateOptions defaultOptions = createMock(TemplateOptions.class);\n      GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class);\n\n      expect(optionsProvider.get()).andReturn(defaultOptions);\n\n      replay(defaultOptions, optionsProvider, templateBuilderProvider, getImageStrategy);\n\n      TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, hardwares, region,\n               optionsProvider, templateBuilderProvider, getImageStrategy);\n\n      try {\n         template.os64Bit(true).build();\n         fail(\"Expected IllegalStateException\");\n      } catch (IllegalStateException e) {\n         assertEquals(e.getMessage(), \"no images present!\");\n      }\n\n      verify(defaultOptions, optionsProvider, templateBuilderProvider, getImageStrategy);\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   public void testHardwareProfilesMustBePresentWhenQuerying() {\n      Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n               .<Location> of(region));\n      Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of(image));\n      Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet\n               .<Hardware> of());\n      Provider<TemplateOptions> optionsProvider = createMock(Provider.class);\n      Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);\n      TemplateOptions defaultOptions = createMock(TemplateOptions.class);\n      GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class);\n\n      expect(optionsProvider.get()).andReturn(defaultOptions);\n\n      replay(defaultOptions, optionsProvider, templateBuilderProvider, getImageStrategy);\n\n      TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, hardwares, region,\n               optionsProvider, templateBuilderProvider, getImageStrategy);\n\n      try {\n         template.os64Bit(true).build();\n         fail(\"Expected IllegalStateException\");\n      } catch (IllegalStateException e) {\n         assertEquals(e.getMessage(), \"no hardware profiles present!\");\n      }\n\n      verify(defaultOptions, optionsProvider, templateBuilderProvider, getImageStrategy);\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Test\n   public void testDefaultLocationWithNoOptionsNoSuchElement() {\n      Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n               .<Location> of(region));\n      Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of(image));\n      Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet\n               .<Hardware> of(createMock(Hardware.class)));\n      Provider<TemplateOptions> optionsProvider = createMock(Provider.class);\n      Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);\n      TemplateOptions defaultOptions = createMock(TemplateOptions.class);\n      GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class);\n\n      expect(optionsProvider.get()).andReturn(defaultOptions);\n      expect(getImageStrategy.getImage(anyObject(String.class))).andReturn(null);\n\n      replay(defaultOptions, optionsProvider, templateBuilderProvider, getImageStrategy);\n\n      TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, hardwares, region,\n               optionsProvider, templateBuilderProvider, getImageStrategy);\n\n      try {\n         template.imageId(\"region/imageId2\").build();\n         fail(\"Expected NoSuchElementException\");\n      } catch (NoSuchElementException e) {\n         // make sure big data is not in the exception message\n         assertEquals(e.getMessage(), \"imageId(region/imageId2) not found\");\n      }\n\n      verify(defaultOptions, optionsProvider, templateBuilderProvider);\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Test\n   public void testDefaultLocationWithUnmatchedPredicateExceptionMessageAndLocationNotCalled() {\n      Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n               .<Location> of(region));\n      Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of(image));\n      Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet\n               .<Hardware> of(createMock(Hardware.class)));\n      Provider<TemplateOptions> optionsProvider = createMock(Provider.class);\n      Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);\n      TemplateOptions defaultOptions = createMock(TemplateOptions.class);\n      GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class);\n\n      expect(optionsProvider.get()).andReturn(defaultOptions);\n\n      replay(defaultOptions, optionsProvider, templateBuilderProvider, getImageStrategy);\n\n      TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, hardwares, region,\n               optionsProvider, templateBuilderProvider, getImageStrategy);\n\n      try {\n         template.imageDescriptionMatches(\"notDescription\").build();\n         fail(\"Expected NoSuchElementException\");\n      } catch (NoSuchElementException e) {\n         // make sure big data is not in the exception message\n         assertTrue(e.getMessage().length() < 1024);\n      }\n\n      verify(defaultOptions, optionsProvider, templateBuilderProvider, getImageStrategy);\n   }\n\n   protected TemplateOptions provideTemplateOptions() {\n      return new TemplateOptions();\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Test\n   public void testDefaultLocationWithOptions() {\n      Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n               .<Location> of());\n      Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of(image));\n      Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet\n               .<Hardware> of(createMock(Hardware.class)));\n      Location defaultLocation = createMock(Location.class);\n      Provider<TemplateOptions> optionsProvider = createMock(Provider.class);\n      TemplateOptions from = provideTemplateOptions();\n      Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);\n      GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class);\n\n      expect(optionsProvider.get()).andReturn(from);\n      expect(getImageStrategy.getImage(anyObject(String.class))).andReturn(null);\n\n      replay(defaultLocation, optionsProvider, templateBuilderProvider, getImageStrategy);\n\n      TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, hardwares, defaultLocation,\n               optionsProvider, templateBuilderProvider, getImageStrategy);\n\n      try {\n         template.imageId(\"region/ami\").options(provideTemplateOptions()).build();\n         fail(\"Expected NoSuchElementException\");\n      } catch (NoSuchElementException e) {\n\n      }\n\n      verify(defaultLocation, optionsProvider, templateBuilderProvider);\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Test\n   public void testImageIdNullsEverythingElse() {\n      Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n               .<Location> of());\n      Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of());\n      Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet\n               .<Hardware> of());\n      Location defaultLocation = createMock(Location.class);\n      Provider<TemplateOptions> optionsProvider = createMock(Provider.class);\n      Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);\n      GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class);\n\n      replay(defaultLocation, optionsProvider, templateBuilderProvider, getImageStrategy);\n\n      TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, hardwares, defaultLocation,\n               optionsProvider, templateBuilderProvider, getImageStrategy);\n\n      template.imageDescriptionMatches(\"imageDescriptionMatches\");\n      template.imageNameMatches(\"imageNameMatches\");\n      template.imageVersionMatches(\"imageVersionMatches\");\n      template.osDescriptionMatches(\"osDescriptionMatches\");\n      template.osFamily(OsFamily.CENTOS);\n      template.osArchMatches(\"osArchMatches\");\n\n      assertEquals(template.osArch, \"osArchMatches\");\n      assertEquals(template.imageDescription, \"imageDescriptionMatches\");\n      assertEquals(template.imageName, \"imageNameMatches\");\n      assertEquals(template.imageVersion, \"imageVersionMatches\");\n      assertEquals(template.osDescription, \"osDescriptionMatches\");\n      assertEquals(template.osFamily, OsFamily.CENTOS);\n      assertEquals(template.imageId, null);\n\n      template.imageId(\"myid\");\n      assertEquals(template.osArch, null);\n      assertEquals(template.imageDescription, null);\n      assertEquals(template.imageName, null);\n      assertEquals(template.imageVersion, null);\n      assertEquals(template.osDescription, null);\n      assertEquals(template.osFamily, null);\n      assertEquals(template.imageId, \"myid\");\n\n      verify(defaultLocation, optionsProvider, templateBuilderProvider, getImageStrategy);\n   }\n\n   @Test\n   public void testFindImageWithIdDefaultToGetImageStrategy() {\n      final Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n            .<Location> of(region));\n      final Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet\n            .<Image> of(\n                  new ImageBuilder()\n                        .ids(\"Ubuntu 11.04 x64\")\n                        .name(\"Ubuntu 11.04 x64\")\n                        .description(\"Ubuntu 11.04 x64\")\n                        .location(region)\n                        .status(Status.AVAILABLE)\n                        .operatingSystem(\n                              OperatingSystem.builder().name(\"Ubuntu 11.04 x64\").description(\"Ubuntu 11.04 x64\")\n                                    .is64Bit(true).version(\"11.04\").family(OsFamily.UBUNTU).build()).build(),\n                  new ImageBuilder()\n                        .ids(\"Ubuntu 11.04 64-bit\")\n                        .name(\"Ubuntu 11.04 64-bit\")\n                        .description(\"Ubuntu 11.04 64-bit\")\n                        .location(region)\n                        .status(Status.AVAILABLE)\n                        .operatingSystem(\n                              OperatingSystem.builder().name(\"Ubuntu 11.04 64-bit\").description(\"Ubuntu 11.04 64-bit\")\n                                    .is64Bit(true).version(\"11.04\").family(OsFamily.UBUNTU).build()).build()));\n\n      final Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet\n            .<Hardware> of(\n                  new HardwareBuilder()\n                        .ids(String.format(\"datacenter(%s)platform(%s)cpuCores(%d)memorySizeMB(%d)diskSizeGB(%d)\",\n                              \"Falkenberg\", \"Xen\", 1, 512, 5)).ram(512)\n                        .processors(ImmutableList.of(new Processor(1, 1.0)))\n                        .volumes(ImmutableList.<Volume> of(new VolumeImpl((float) 5, true, true))).hypervisor(\"Xen\")\n                        .location(region)\n                        .supportsImage(ImagePredicates.idEquals(image.getId())).build()));\n\n      final Provider<TemplateOptions> optionsProvider = new Provider<TemplateOptions>() {\n         @Override\n         public TemplateOptions get() {\n            return new TemplateOptions();\n         }\n      };\n\n      final GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class);\n\n      expect(getImageStrategy.getImage(image.getId())).andReturn(image);\n      replay(getImageStrategy);\n\n      Provider<TemplateBuilder> templateBuilderProvider = new Provider<TemplateBuilder>() {\n         @Override\n         public TemplateBuilder get() {\n            return createTemplateBuilder(null, locations, images, hardwares, region, optionsProvider, this, getImageStrategy);\n         }\n      };\n\n      // Note that the image provided is not in the image list, but it is the one returned by the GetImagestrategy\n      TemplateBuilder templateBuilder = templateBuilderProvider.get().imageId(image.getId());\n      Template template = templateBuilder.build();\n\n      assertEquals(template.getImage().getId(), image.getId());\n      verify(getImageStrategy);\n   }\n   \n   @Test\n   public void testFindImageWithIdDefaultToGetImageStrategyAndPopulatesTheCache() {\n      final Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n            .<Location> of(region));\n      final Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet\n            .<Image> of(\n                  new ImageBuilder()\n                        .ids(\"Ubuntu 11.04 x64\")\n                        .name(\"Ubuntu 11.04 x64\")\n                        .description(\"Ubuntu 11.04 x64\")\n                        .location(region)\n                        .status(Status.AVAILABLE)\n                        .operatingSystem(\n                              OperatingSystem.builder().name(\"Ubuntu 11.04 x64\").description(\"Ubuntu 11.04 x64\")\n                                    .is64Bit(true).version(\"11.04\").family(OsFamily.UBUNTU).build()).build(),\n                  new ImageBuilder()\n                        .ids(\"Ubuntu 11.04 64-bit\")\n                        .name(\"Ubuntu 11.04 64-bit\")\n                        .description(\"Ubuntu 11.04 64-bit\")\n                        .location(region)\n                        .status(Status.AVAILABLE)\n                        .operatingSystem(\n                              OperatingSystem.builder().name(\"Ubuntu 11.04 64-bit\").description(\"Ubuntu 11.04 64-bit\")\n                                    .is64Bit(true).version(\"11.04\").family(OsFamily.UBUNTU).build()).build()));\n\n      final Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet\n            .<Hardware> of(\n                  new HardwareBuilder()\n                        .ids(String.format(\"datacenter(%s)platform(%s)cpuCores(%d)memorySizeMB(%d)diskSizeGB(%d)\",\n                              \"Falkenberg\", \"Xen\", 1, 512, 5)).ram(512)\n                        .processors(ImmutableList.of(new Processor(1, 1.0)))\n                        .volumes(ImmutableList.<Volume> of(new VolumeImpl((float) 5, true, true))).hypervisor(\"Xen\")\n                        .location(region)\n                        .supportsImage(ImagePredicates.idEquals(image.getId())).build()));\n\n      final Provider<TemplateOptions> optionsProvider = new Provider<TemplateOptions>() {\n         @Override\n         public TemplateOptions get() {\n            return new TemplateOptions();\n         }\n      };\n\n      final GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class);\n\n      expect(getImageStrategy.getImage(image.getId())).andReturn(image);\n      replay(getImageStrategy);\n\n      Provider<TemplateBuilder> templateBuilderProvider = new Provider<TemplateBuilder>() {\n         @Override\n         public TemplateBuilder get() {\n            return createTemplateBuilder(null, locations, images, hardwares, region, optionsProvider, this, getImageStrategy);\n         }\n      };\n\n      TemplateBuilder templateBuilder = templateBuilderProvider.get();\n\n      try {\n         // First call searching for the image properties will fail, as the image is not in the cache\n         templateBuilder.osNameMatches(image.getOperatingSystem().getName()).build();\n         fail(\"Image should not exist in the cache\");\n      } catch (Exception ex) {\n         // Expected path\n      }\n\n      // A second call using the imageId will fallback to the GetImageStrategy and populate the image in the cache.\n      assertNotNull(templateBuilder.imageId(image.getId()).build());\n\n      // The third call will succeed, as the previous one should have populated the image in the cache.\n      templateBuilder.imageId(null); // Clear all criteria\n      Template template = templateBuilder.osNameMatches(image.getOperatingSystem().getName()).build();\n      assertEquals(template.getImage().getId(), image.getId());\n\n      // Verify this is called only once, as the third call will already find the image in the cache\n      verify(getImageStrategy);\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Test\n   public void testHardwareIdNullsHypervisor() {\n      Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n               .<Location> of());\n      Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of());\n      Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet\n               .<Hardware> of());\n      Location defaultLocation = createMock(Location.class);\n      Provider<TemplateOptions> optionsProvider = createMock(Provider.class);\n      Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);\n      GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class);\n\n      replay(defaultLocation, optionsProvider, templateBuilderProvider, getImageStrategy);\n\n      TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, hardwares, defaultLocation,\n               optionsProvider, templateBuilderProvider, getImageStrategy);\n\n\n      template.hypervisorMatches(\"OpenVZ\");\n\n      assertEquals(template.hardwareId, null);\n      assertEquals(template.hypervisor, \"OpenVZ\");\n\n      template.hardwareId(\"myid\");\n      assertEquals(template.hardwareId, \"myid\");\n      assertEquals(template.hypervisor, null);\n\n\n      verify(defaultLocation, optionsProvider, templateBuilderProvider, getImageStrategy);\n   }\n\n   @Test\n   public void testMatchesHardwareWithIdPredicate() {\n      final Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n            .<Location> of(region));\n      String imageId = getProviderFormatId(\"Ubuntu 11.04 x64\");\n      final Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet\n            .<Image> of(\n                  new ImageBuilder()\n                        .ids(imageId)\n                        .name(\"Ubuntu 11.04 x64\")\n                        .description(\"Ubuntu 11.04 x64\")\n                        .location(region)\n                        .status(Status.AVAILABLE)\n                        .operatingSystem(\n                              OperatingSystem.builder().name(\"Ubuntu 11.04 x64\").description(\"Ubuntu 11.04 x64\")\n                                    .is64Bit(true).version(\"11.04\").family(OsFamily.UBUNTU).build()).build(),\n                  new ImageBuilder()\n                        .ids(getProviderFormatId(\"Ubuntu 11.04 64-bit\"))\n                        .name(\"Ubuntu 11.04 64-bit\")\n                        .description(\"Ubuntu 11.04 64-bit\")\n                        .location(region)\n                        .status(Status.AVAILABLE)\n                        .operatingSystem(\n                              OperatingSystem.builder().name(\"Ubuntu 11.04 64-bit\").description(\"Ubuntu 11.04 64-bit\")\n                                    .is64Bit(true).version(\"11.04\").family(OsFamily.UBUNTU).build()).build()));\n\n      final Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet\n            .<Hardware> of(\n                  new HardwareBuilder()\n                        .ids(String.format(\"datacenter(%s)platform(%s)cpuCores(%d)memorySizeMB(%d)diskSizeGB(%d)\",\n                              \"Falkenberg\", \"Xen\", 1, 512, 5)).ram(512)\n                        .processors(ImmutableList.of(new Processor(1, 1.0)))\n                        .volumes(ImmutableList.<Volume> of(new VolumeImpl((float) 5, true, true))).hypervisor(\"Xen\")\n                        .location(region)\n                        .supportsImage(ImagePredicates.idIn(ImmutableSet.of(imageId))).build(),\n                  new HardwareBuilder()\n                        .ids(String.format(\"datacenter(%s)platform(%s)cpuCores(%d)memorySizeMB(%d)diskSizeGB(%d)\",\n                              \"Falkenberg\", \"OpenVZ\", 1, 512, 5)).ram(512)\n                        .processors(ImmutableList.of(new Processor(1, 1.0)))\n                        .volumes(ImmutableList.<Volume> of(new VolumeImpl((float) 5, true, true))).hypervisor(\"OpenVZ\")\n                        .location(region)\n                        .supportsImage(ImagePredicates.idIn(ImmutableSet.of(imageId))).build()));\n\n      final Provider<TemplateOptions> optionsProvider = new Provider<TemplateOptions>() {\n\n         @Override\n         public TemplateOptions get() {\n            return new TemplateOptions();\n         }\n\n      };\n\n      final GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class);\n\n      Provider<TemplateBuilder> templateBuilderProvider = new Provider<TemplateBuilder>() {\n\n         @Override\n         public TemplateBuilder get() {\n            return createTemplateBuilder(null, locations, images, hardwares, region, optionsProvider, this, getImageStrategy);\n         }\n\n      };\n\n      TemplateBuilder templateBuilder = templateBuilderProvider.get().minRam(512).osFamily(OsFamily.UBUNTU)\n            .hypervisorMatches(\"OpenVZ\").osVersionMatches(\"1[10].[10][04]\").os64Bit(true);\n\n      assertEquals(templateBuilder.toString(), \"{minRam=512, minRam=512, osFamily=ubuntu, osVersion=1[10].[10][04], os64Bit=true, hypervisor=OpenVZ}\");\n\n      Template template = templateBuilder.build();\n      assertEquals(template.getHardware().getHypervisor(), \"OpenVZ\");\n      assertEquals(template.getImage().getId(), imageId);\n   }\n   \n   @Test\n   public void testMatchesHardwarePrefersNonDeprecated() {\n      final Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n            .<Location> of(region));\n      String imageId = getProviderFormatId(\"Ubuntu 11.04 x64\");\n      final Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet\n            .<Image> of(\n                  new ImageBuilder()\n                        .ids(imageId)\n                        .name(\"Ubuntu 11.04 x64\")\n                        .description(\"Ubuntu 11.04 x64\")\n                        .location(region)\n                        .status(Status.AVAILABLE)\n                        .operatingSystem(\n                              OperatingSystem.builder().name(\"Ubuntu 11.04 x64\").description(\"Ubuntu 11.04 x64\")\n                                    .is64Bit(true).version(\"11.04\").family(OsFamily.UBUNTU).build()).build()));\n\n      final Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet\n            .<Hardware> of(\n                  new HardwareBuilder()\n                        .ids(String.format(\"hardware-deprecated\")).ram(512)\n                        .processors(ImmutableList.of(new Processor(1, 1.0)))\n                        .volumes(ImmutableList.<Volume> of(new VolumeImpl((float) 5, true, true))).hypervisor(\"Xen\")\n                        .location(region)\n                        .deprecated()\n                        .supportsImage(ImagePredicates.idIn(ImmutableSet.of(imageId))).build(),\n                    new HardwareBuilder()\n                        .ids(String.format(\"hardware-good\")).ram(512)\n                        .processors(ImmutableList.of(new Processor(1, 1.0)))\n                        .volumes(ImmutableList.<Volume> of(new VolumeImpl((float) 5, true, true))).hypervisor(\"Xen\")\n                        .location(region)\n                        .supportsImage(ImagePredicates.idIn(ImmutableSet.of(imageId))).build()));\n\n      final Provider<TemplateOptions> optionsProvider = new Provider<TemplateOptions>() {\n\n         @Override\n         public TemplateOptions get() {\n            return new TemplateOptions();\n         }\n\n      };\n\n      final GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class);\n\n      Provider<TemplateBuilder> templateBuilderProvider = new Provider<TemplateBuilder>() {\n\n         @Override\n         public TemplateBuilder get() {\n            return createTemplateBuilder(null, locations, images, hardwares, region, optionsProvider, this, getImageStrategy);\n         }\n\n      };\n\n      TemplateBuilder templateBuilder = templateBuilderProvider.get().minRam(512).osFamily(OsFamily.UBUNTU);\n\n      Template template = templateBuilder.build();\n      assertEquals(template.getHardware().getId(), \"hardware-good\");\n      assertEquals(template.getImage().getId(), imageId);\n   }\n   \n   @Test\n   public void testImageLocationNonDefault() {\n      final Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n            .<Location> of(region));\n      final Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet\n            .<Image> of(\n                  new ImageBuilder()\n                        .id(\"us-east-2/ami-ffff\")\n                        .providerId(\"ami-ffff\")\n                        .name(\"Ubuntu 11.04 x64\")\n                        .description(\"Ubuntu 11.04 x64\")\n                        .location(region2)\n                        .status(Status.AVAILABLE)\n                        .operatingSystem(\n                              OperatingSystem.builder().name(\"Ubuntu 11.04 x64\").description(\"Ubuntu 11.04 x64\")\n                                    .is64Bit(true).version(\"11.04\").family(OsFamily.UBUNTU).build()).build()));\n\n      final Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet\n            .<Hardware> of(\n                  new HardwareBuilder()\n                        .ids(\"m1.small\").ram(512)\n                        .processors(ImmutableList.of(new Processor(1, 1.0)))\n                        .volumes(ImmutableList.<Volume> of(new VolumeImpl((float) 5, true, true))).build()));\n\n      final Provider<TemplateOptions> optionsProvider = new Provider<TemplateOptions>() {\n\n         @Override\n         public TemplateOptions get() {\n            return new TemplateOptions();\n         }\n\n      };\n\n      final GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class);\n\n      Provider<TemplateBuilder> templateBuilderProvider = new Provider<TemplateBuilder>() {\n\n         @Override\n         public TemplateBuilder get() {\n            return createTemplateBuilder(null, locations, images, hardwares, region, optionsProvider, this, getImageStrategy);\n         }\n\n      };\n\n      TemplateBuilder templateBuilder = templateBuilderProvider.get().hardwareId(\"m1.small\").imageId(\"us-east-2/ami-ffff\");\n\n      assertEquals(templateBuilder.toString(), \"{imageId=us-east-2/ami-ffff, hardwareId=m1.small}\");\n\n      Template template = templateBuilder.build();\n      assertEquals(template.getLocation().getId(), \"us-east-2\");\n   }\n\n   @Test\n   public void testFromSpecWithLoginUser() {\n      final Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n            .<Location> of(region));\n      final Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet\n            .<Image> of(\n                  new ImageBuilder()\n                        .id(\"us-east-2/ami-ffff\")\n                        .providerId(\"ami-ffff\")\n                        .name(\"Ubuntu 11.04 x64\")\n                        .description(\"Ubuntu 11.04 x64\")\n                        .location(region2)\n                        .status(Status.AVAILABLE)\n                        .operatingSystem(\n                              OperatingSystem.builder().name(\"Ubuntu 11.04 x64\").description(\"Ubuntu 11.04 x64\")\n                                    .is64Bit(true).version(\"11.04\").family(OsFamily.UBUNTU).build()).build()));\n\n      final Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet\n            .<Hardware> of(\n                  new HardwareBuilder()\n                        .ids(\"m1.small\").ram(512)\n                        .processors(ImmutableList.of(new Processor(1, 1.0)))\n                        .volumes(ImmutableList.<Volume> of(new VolumeImpl((float) 5, true, true))).build()));\n\n      final Provider<TemplateOptions> optionsProvider = new Provider<TemplateOptions>() {\n\n         @Override\n         public TemplateOptions get() {\n            return new TemplateOptions();\n         }\n\n      };\n\n      final GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class);\n\n      Provider<TemplateBuilder> templateBuilderProvider = new Provider<TemplateBuilder>() {\n\n         @Override\n         public TemplateBuilder get() {\n            return createTemplateBuilder(null, locations, images, hardwares, region, optionsProvider, this, getImageStrategy);\n         }\n\n      };\n\n      TemplateBuilder templateBuilder = templateBuilderProvider.get().from(\"hardwareId=m1.small,imageId=us-east-2/ami-ffff,loginUser=user:Password01,authenticateSudo=true\");\n\n      assertEquals(templateBuilder.toString(), \"{imageId=us-east-2/ami-ffff, hardwareId=m1.small}\");\n\n      Template template = templateBuilder.build();\n      assertEquals(template.getLocation().getId(), \"us-east-2\");\n      assertEquals(template.getOptions().getLoginUser(), \"user\");\n      assertEquals(template.getOptions().getLoginPassword(), \"Password01\");\n      assertEquals(template.getOptions().getLoginPrivateKey(), null);\n      assertEquals(template.getOptions().shouldAuthenticateSudo(), Boolean.TRUE);\n   }\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/extensions/internal/BaseImageExtensionLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.extensions.internal;\n\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static org.jclouds.compute.predicates.NodePredicates.inGroup;\nimport static org.jclouds.util.Predicates2.retry;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.NoSuchElementException;\nimport java.util.concurrent.ExecutionException;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\n\nimport org.jclouds.compute.ComputeService;\nimport org.jclouds.compute.RunNodesException;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.ImageTemplate;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.domain.TemplateBuilder;\nimport org.jclouds.compute.extensions.ImageExtension;\nimport org.jclouds.compute.internal.BaseComputeServiceContextLiveTest;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.ssh.SshClient;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Iterables;\n\n\n/**\n * Base test for {@link ImageExtension} implementations.\n */\npublic abstract class BaseImageExtensionLiveTest extends BaseComputeServiceContextLiveTest {\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   protected final String imageGroup = \"test-create-image\";\n\n   protected String imageId;\n\n   /**\n    * Returns the template for the base node, override to test different templates.\n    * \n    * @return\n    */\n   public TemplateBuilder getNodeTemplate() {\n      TemplateBuilder templateBuilder = view.getComputeService().templateBuilder();\n      if (templateBuilderSpec != null) {\n          templateBuilder = templateBuilder.from(templateBuilderSpec);\n      }\n      return templateBuilder;\n   }\n\n   /**\n    * Returns the maximum amount of time (in seconds) to wait for a node spawned from the new image\n    * to become available, override to increase this time.\n    * \n    * @return\n    */\n   public long getSpawnNodeMaxWait() {\n      return 600L;\n   }\n\n   /**\n    * Lists the images found in the {@link ComputeService}, subclasses may override to constrain\n    * search.\n    * \n    * @return\n    */\n   protected Iterable<? extends Image> listImages() {\n      return view.getComputeService().listImages();\n   }\n\n   @Test(groups = { \"integration\", \"live\" }, singleThreaded = true)\n   public void testCreateImage() throws RunNodesException, InterruptedException, ExecutionException {\n      ComputeService computeService = view.getComputeService();\n      Optional<ImageExtension> imageExtension = computeService.getImageExtension();\n      assertTrue(imageExtension.isPresent(), \"image extension was not present\");\n\n      Template template = getNodeTemplate().build();\n      NodeMetadata node = Iterables.getOnlyElement(computeService.createNodesInGroup(imageGroup, 1, template));\n      checkReachable(node);\n      \n      prepareNodeBeforeCreatingImage(node);\n\n      logger.info(\"Creating image from node %s, started with template: %s\", node, template);\n      ImageTemplate newImageTemplate = imageExtension.get().buildImageTemplateFromNode(imageGroup,\n              node.getId());\n      Image image = imageExtension.get().createImage(newImageTemplate).get();\n      logger.info(\"Image created: %s\", image);\n\n      assertEquals(imageGroup, image.getName());\n\n      imageId = image.getId();\n      computeService.destroyNode(node.getId());\n\n      Optional<? extends Image> optImage = getImage();\n      assertTrue(optImage.isPresent());\n   }\n   \n   /**\n    * Subclasses can override this to prepare the node before creating an image (run cleanup scripts, etc)\n    */\n   protected void prepareNodeBeforeCreatingImage(NodeMetadata node) {\n      \n   }\n\n   @Test(groups = { \"integration\", \"live\" }, singleThreaded = true, dependsOnMethods = \"testCreateImage\")\n   public void testImageIsCachedAfterBeingCreated() {\n      Optional<Image> imageInCache = findImageWithNameInCache(imageGroup);\n      assertTrue(imageInCache.isPresent());\n      assertEquals(imageInCache.get().getId(), imageId);\n   }\n\n   @Test(groups = { \"integration\", \"live\" }, singleThreaded = true, dependsOnMethods = \"testCreateImage\")\n   public void testSpawnNodeFromImage() throws RunNodesException {\n      ComputeService computeService = view.getComputeService();\n      Optional<? extends Image> optImage = getImage();\n      assertTrue(optImage.isPresent());\n\n      NodeMetadata node = Iterables.getOnlyElement(computeService.createNodesInGroup(imageGroup, 1, getNodeTemplate()\n               // fromImage does not use the arg image's id (but we do need to set location)\n               .imageId(optImage.get().getId()).fromImage(optImage.get()).build()));\n\n      checkReachable(node);\n      view.getComputeService().destroyNode(node.getId());\n   }\n\n   @Test(groups = { \"integration\", \"live\" }, singleThreaded = true, dependsOnMethods = { \"testCreateImage\",\n            \"testSpawnNodeFromImage\", \"testImageIsCachedAfterBeingCreated\" })\n   public void testDeleteImage() {\n      ComputeService computeService = view.getComputeService();\n\n      Optional<ImageExtension> imageExtension = computeService.getImageExtension();\n      assertTrue(imageExtension.isPresent(), \"image extension was not present\");\n\n      Optional<? extends Image> optImage = getImage();\n      assertTrue(optImage.isPresent());\n\n      Image image = optImage.get();\n      assertTrue(imageExtension.get().deleteImage(image.getId()));\n   }\n   \n   @Test(groups = { \"integration\", \"live\" }, singleThreaded = true, dependsOnMethods = \"testDeleteImage\")\n   public void testImageIsRemovedFromCacheAfterDeletion() {\n      Optional<Image> imageInCache = findImageWithNameInCache(imageGroup);\n      assertFalse(imageInCache.isPresent());\n      assertFalse(getImage().isPresent());\n   }\n\n   private Optional<? extends Image> getImage() {\n      return Optional.fromNullable(view.getComputeService().getImage(imageId));\n   }\n\n   private void checkReachable(NodeMetadata node) {\n      SshClient client = view.utils().sshForNode().apply(node);\n      assertTrue(retry(new Predicate<SshClient>() {\n         @Override\n         public boolean apply(SshClient input) {\n            input.connect();\n            if (input.exec(\"id\").getExitStatus() == 0) {\n               return true;\n            }\n            return false;\n         }\n      }, getSpawnNodeMaxWait(), 1L, SECONDS).apply(client));\n   }\n\n   protected Optional<Image> findImageWithNameInCache(String name) {\n      try {\n         Template template = view.getComputeService().templateBuilder().imageNameMatches(name).build();\n         return Optional.of(template.getImage());\n      } catch (NoSuchElementException ex) {\n         return Optional.absent();\n      }\n   }\n\n   @AfterClass(groups = { \"integration\", \"live\" })\n   @Override\n   protected void tearDownContext() {\n      try {\n         view.getComputeService().destroyNodesMatching(inGroup(imageGroup));\n\n         Optional<? extends Image> image = getImage();\n\n         if (image.isPresent() && image.get().getStatus() != Image.Status.DELETED) {\n            Optional<ImageExtension> imageExtension = view.getComputeService().getImageExtension();\n            if (imageExtension.isPresent()) {\n               imageExtension.get().deleteImage(image.get().getId());\n            }\n         }\n      } catch (Exception e) {\n         // Any exception is most likely due to nodes/images not existing, which is the desired result\n         // anyway, so discarding the exception.\n      }\n\n      super.tearDownContext();\n   }\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/extensions/internal/BaseSecurityGroupExtensionLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.extensions.internal;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\nimport java.util.concurrent.ExecutionException;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\n\nimport org.jclouds.compute.ComputeService;\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.compute.RunNodesException;\nimport org.jclouds.compute.domain.SecurityGroup;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.extensions.SecurityGroupExtension;\nimport org.jclouds.compute.internal.BaseComputeServiceContextLiveTest;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.domain.Location;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.net.domain.IpPermission;\nimport org.jclouds.net.domain.IpProtocol;\nimport org.testng.SkipException;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.LinkedHashMultimap;\nimport com.google.common.collect.Multimap;\nimport com.google.common.collect.Sets;\n\n\n/**\n * Base test for {@link SecurityGroupExtension} implementations.\n */\npublic abstract class BaseSecurityGroupExtensionLiveTest extends BaseComputeServiceContextLiveTest {\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   protected final String secGroupName = \"test-create-security-group\";\n   protected final String secGroupNameToDelete = \"test-create-security-group-to-delete\";\n   protected final String nodeGroup = \"test-create-node-with-group\";\n\n   protected String groupId;\n\n   protected boolean securityGroupsSupported = true;\n\n   /**\n    * Returns the template for the base node, override to test different templates.\n    *\n    * @return\n    */\n   public Template getNodeTemplate() {\n      return view.getComputeService().templateBuilder().build();\n   }\n\n   protected void skipIfSecurityGroupsNotSupported() {\n      if (!securityGroupsSupported) {\n         throw new SkipException(\"Test cannot run without security groups available.\");\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" }, singleThreaded = true)\n   public void testCreateSecurityGroup() throws RunNodesException, InterruptedException, ExecutionException {\n      skipIfSecurityGroupsNotSupported();\n\n      ComputeService computeService = view.getComputeService();\n\n      Location location = getNodeTemplate().getLocation();\n      \n      Optional<SecurityGroupExtension> securityGroupExtension = computeService.getSecurityGroupExtension();\n\n      assertTrue(securityGroupExtension.isPresent(), \"security extension was not present\");\n\n      SecurityGroup group = securityGroupExtension.get().createSecurityGroup(secGroupName, location);\n\n      logger.info(\"Group created: %s\", group);\n\n      assertTrue(group.getName().contains(secGroupName));\n\n      groupId = group.getId();\n   }\n\n   @Test(groups = { \"integration\", \"live\" }, singleThreaded = true, dependsOnMethods = \"testCreateSecurityGroup\")\n   public void testGetSecurityGroupById() throws RunNodesException, InterruptedException, ExecutionException {\n      skipIfSecurityGroupsNotSupported();\n\n      ComputeService computeService = view.getComputeService();\n\n      Location location = getNodeTemplate().getLocation();\n      \n      Optional<SecurityGroupExtension> securityGroupExtension = computeService.getSecurityGroupExtension();\n\n      assertTrue(securityGroupExtension.isPresent(), \"security extension was not present\");\n\n      SecurityGroup group = securityGroupExtension.get().getSecurityGroupById(groupId);\n\n      logger.info(\"Group found: %s\", group);\n\n      assertTrue(group.getName().contains(secGroupName));\n   }\n\n   @Test(groups = { \"integration\", \"live\" }, singleThreaded = true, dependsOnMethods = \"testGetSecurityGroupById\")\n   public void testAddIpPermission() {\n      skipIfSecurityGroupsNotSupported();\n\n      ComputeService computeService = view.getComputeService();\n\n      Optional<SecurityGroupExtension> securityGroupExtension = computeService.getSecurityGroupExtension();\n      assertTrue(securityGroupExtension.isPresent(), \"security group extension was not present\");\n\n      Optional<SecurityGroup> optGroup = getGroup(securityGroupExtension.get());\n\n      assertTrue(optGroup.isPresent());\n\n      SecurityGroup group = optGroup.get();\n\n      IpPermission portRangeIpPermission = createPortRangePermission();\n      IpPermission singlePortIpPermission = createSinglePortPermission();\n\n      Set<IpPermission> expectedPermissions = ImmutableSet.of(portRangeIpPermission, singlePortIpPermission);\n\n      SecurityGroup onePermissionAdded = securityGroupExtension.get().addIpPermission(portRangeIpPermission, group);\n      SecurityGroup twoPermissionsAdded = securityGroupExtension.get().addIpPermission(singlePortIpPermission,\n            onePermissionAdded);\n\n      assertEquals(twoPermissionsAdded.getIpPermissions(), expectedPermissions);\n   }\n\n   @Test(groups = { \"integration\", \"live\" }, singleThreaded = true, dependsOnMethods = \"testAddIpPermission\")\n   public void testRemoveIpPermission() {\n      skipIfSecurityGroupsNotSupported();\n\n      ComputeService computeService = view.getComputeService();\n\n      Optional<SecurityGroupExtension> securityGroupExtension = computeService.getSecurityGroupExtension();\n      assertTrue(securityGroupExtension.isPresent(), \"security group extension was not present\");\n\n      Optional<SecurityGroup> optGroup = getGroup(securityGroupExtension.get());\n\n      assertTrue(optGroup.isPresent());\n\n      SecurityGroup group = optGroup.get();\n\n      IpPermission portRangeIpPermission = createPortRangePermission();\n      IpPermission singlePortIpPermission = createSinglePortPermission();\n\n      SecurityGroup newGroup = securityGroupExtension.get().removeIpPermission(portRangeIpPermission, group);\n      SecurityGroup emptyGroup = securityGroupExtension.get().removeIpPermission(singlePortIpPermission, newGroup);\n\n      assertEquals(Iterables.size(emptyGroup.getIpPermissions()), 0, \"Group should have no permissions, but has \"\n            + Iterables.size(emptyGroup.getIpPermissions()));\n   }\n\n   @Test(groups = { \"integration\", \"live\" }, singleThreaded = true, dependsOnMethods = \"testRemoveIpPermission\")\n   public void testAddIpPermissionsFromSpec() {\n      skipIfSecurityGroupsNotSupported();\n\n      ComputeService computeService = view.getComputeService();\n\n      Optional<SecurityGroupExtension> securityGroupExtension = computeService.getSecurityGroupExtension();\n      assertTrue(securityGroupExtension.isPresent(), \"security group extension was not present\");\n\n      Optional<SecurityGroup> optGroup = getGroup(securityGroupExtension.get());\n\n      assertTrue(optGroup.isPresent());\n\n      SecurityGroup group = optGroup.get();\n\n      IpPermission.Builder builder = IpPermission.builder();\n\n      builder.ipProtocol(IpProtocol.TCP);\n      builder.fromPort(50);\n      builder.toPort(60);\n      builder.cidrBlock(\"0.0.0.0/0\");\n\n      IpPermission perm = builder.build();\n\n      SecurityGroup newGroup = securityGroupExtension.get().addIpPermission(IpProtocol.TCP,\n                                                                            50,\n                                                                            60,\n                                                                            emptyMultimap(),\n                                                                            ImmutableSet.of(\"0.0.0.0/0\"),\n                                                                            emptyStringSet(),\n                                                                            group);\n\n      assertTrue(newGroup.getIpPermissions().contains(perm)); \n\n      if (securityGroupExtension.get().supportsGroupIds()) {\n         IpPermission.Builder secondBuilder = IpPermission.builder();\n         \n         int fromPort;\n         int toPort;\n\n         if (securityGroupExtension.get().supportsPortRangesForGroups()) {\n            fromPort = 70;\n            toPort = 80;\n         } else {\n            fromPort = 1;\n            toPort = 65535;\n         }\n         secondBuilder.ipProtocol(IpProtocol.TCP);\n         secondBuilder.fromPort(fromPort);\n         secondBuilder.toPort(toPort);\n         secondBuilder.groupId(group.getId());\n         \n         IpPermission secondPerm = secondBuilder.build();\n         \n         SecurityGroup secondNewGroup = securityGroupExtension.get().addIpPermission(IpProtocol.TCP,\n                                                                                     fromPort,\n                                                                                     toPort,\n                                                                                     emptyMultimap(),\n                                                                                     emptyStringSet(),\n                                                                                     ImmutableSet.of(group.getId()),\n                                                                                     newGroup);\n\n         assertTrue(secondNewGroup.getIpPermissions().contains(secondPerm), \"permissions for second group should contain \"\n                 + secondPerm + \" but do not: \" + secondNewGroup.getIpPermissions());\n      }\n\n      if (securityGroupExtension.get().supportsTenantIdGroupNamePairs()\n              || securityGroupExtension.get().supportsTenantIdGroupIdPairs()) {\n         IpPermission.Builder thirdBuilder = IpPermission.builder();\n\n         int fromPort;\n         int toPort;\n\n         if (securityGroupExtension.get().supportsPortRangesForGroups()) {\n            fromPort = 90;\n            toPort = 100;\n         } else {\n            fromPort = 1;\n            toPort = 65535;\n         }\n         thirdBuilder.ipProtocol(IpProtocol.TCP);\n         thirdBuilder.fromPort(fromPort);\n         thirdBuilder.toPort(toPort);\n         if (securityGroupExtension.get().supportsTenantIdGroupIdPairs()) {\n            thirdBuilder.tenantIdGroupNamePair(group.getOwnerId(), group.getProviderId());\n         } else if (securityGroupExtension.get().supportsTenantIdGroupNamePairs()) {\n            thirdBuilder.tenantIdGroupNamePair(group.getOwnerId(), group.getName());\n         }\n\n         IpPermission thirdPerm = thirdBuilder.build();\n\n         SecurityGroup thirdNewGroup = securityGroupExtension.get().addIpPermission(IpProtocol.TCP,\n                                                                                    fromPort,\n                                                                                    toPort,\n                                                                                    thirdPerm.getTenantIdGroupNamePairs(),\n                                                                                    emptyStringSet(),\n                                                                                    emptyStringSet(),\n                                                                                    newGroup);\n\n         assertTrue(thirdNewGroup.getIpPermissions().contains(thirdPerm));\n      }\n   }\n\n   /*\n   @Test(groups = { \"integration\", \"live\" }, singleThreaded = true, dependsOnMethods = \"testAddIpPermissionsFromSpec\")\n   public void testCreateNodeWithSecurityGroup() throws RunNodesException, InterruptedException, ExecutionException {\n      skipIfSecurityGroupsNotSupported();\n\n      ComputeService computeService = view.getComputeService();\n\n      Optional<SecurityGroupExtension> securityGroupExtension = computeService.getSecurityGroupExtension();\n\n      assertTrue(securityGroupExtension.isPresent(), \"security group extension was not present\");\n\n      Template template = view.getComputeService().templateBuilder()\n         .options(TemplateOptions.Builder.securityGroups(groupId))\n         .build();\n      \n      NodeMetadata node = Iterables.getOnlyElement(computeService.createNodesInGroup(nodeGroup, 1, template));\n\n      Set<SecurityGroup> groups = securityGroupExtension.get().listSecurityGroupsForNode(node.getId());\n\n      assertTrue(groups.size() > 0, \"node has no groups\");\n      \n      Optional<SecurityGroup> secGroup = Iterables.tryFind(securityGroupExtension.get().listSecurityGroupsForNode(node.getId()),\n                                                           new Predicate<SecurityGroup>() {\n                                                              @Override\n                                                              public boolean apply(SecurityGroup input) {\n                                                                 return input.getId().equals(groupId);\n                                                              }\n                                                           });\n\n      assertTrue(secGroup.isPresent());\n\n      computeService.destroyNodesMatching(inGroup(node.getGroup()));\n\n      \n   }\n*/\n\n   @Test(groups = { \"integration\", \"live\" }, singleThreaded = true, dependsOnMethods = \"testAddIpPermissionsFromSpec\")\n   public void testAddIpPermissionWithCidrExclusionGroup() {\n      skipIfSecurityGroupsNotSupported();\n\n      ComputeService computeService = view.getComputeService();\n\n      Optional<SecurityGroupExtension> securityGroupExtension = computeService.getSecurityGroupExtension();\n      assertTrue(securityGroupExtension.isPresent(), \"security group extension was not present\");\n      if (!securityGroupExtension.get().supportsExclusionCidrBlocks()) {\n         throw new SkipException(\"Test cannot run without CIDR exclusion groups available.\");\n      }\n\n      Optional<SecurityGroup> optGroup = getGroup(securityGroupExtension.get());\n      assertTrue(optGroup.isPresent());\n      SecurityGroup group = optGroup.get();\n\n      IpPermission cidrExclusionPermission = createCidrExclusionPermission();\n      Set<IpPermission> expectedPermissions = ImmutableSet.of(cidrExclusionPermission);\n\n      SecurityGroup securityGroupWithExclusion = securityGroupExtension.get().addIpPermission(cidrExclusionPermission, group);\n\n      assertTrue(securityGroupWithExclusion.getIpPermissions().containsAll(expectedPermissions));\n   }\n\n   @Test(groups = { \"integration\", \"live\" }, singleThreaded = true, dependsOnMethods = \"testAddIpPermissionWithCidrExclusionGroup\")\n   public void testRemoveIpPermissionWithCidrExclusionGroup() {\n      skipIfSecurityGroupsNotSupported();\n\n      ComputeService computeService = view.getComputeService();\n\n      Optional<SecurityGroupExtension> securityGroupExtension = computeService.getSecurityGroupExtension();\n      assertTrue(securityGroupExtension.isPresent(), \"security group extension was not present\");\n      if (!securityGroupExtension.get().supportsExclusionCidrBlocks()) {\n         throw new SkipException(\"Test cannot run without CIDR exclusion groups available.\");\n      }\n\n      Optional<SecurityGroup> optGroup = getGroup(securityGroupExtension.get());\n      assertTrue(optGroup.isPresent());\n      SecurityGroup group = optGroup.get();\n\n      IpPermission cidrExclusionPermission = createCidrExclusionPermission();\n\n      SecurityGroup emptyGroup = securityGroupExtension.get().removeIpPermission(cidrExclusionPermission, group);\n\n      assertFalse(emptyGroup.getIpPermissions().contains(cidrExclusionPermission));\n   }\n\n   // testDeleteSecurityGroup currently disabled until I can find a way to get it to delete the security group while a terminated\n   // instance is still floating around in EC2. - abayer, 6/14/13\n   @Test(groups = { \"integration\", \"live\" }, singleThreaded = true, dependsOnMethods = \"testRemoveIpPermissionWithCidrExclusionGroup\", alwaysRun = true)\n   public void testDeleteSecurityGroup() {\n      skipIfSecurityGroupsNotSupported();\n\n      ComputeService computeService = view.getComputeService();\n\n      Optional<SecurityGroupExtension> securityGroupExtension = computeService.getSecurityGroupExtension();\n      assertTrue(securityGroupExtension.isPresent(), \"security group extension was not present\");\n\n      Optional<SecurityGroup> optGroup = getGroup(securityGroupExtension.get());\n\n      assertTrue(optGroup.isPresent());\n\n      SecurityGroup group = optGroup.get();\n      assertTrue(securityGroupExtension.get().removeSecurityGroup(group.getId()));\n   }\n\n   @Test(groups = {\"integration\", \"live\"}, singleThreaded = true)\n   public void testSecurityGroupCacheInvalidated() throws Exception {\n      ComputeService computeService = view.getComputeService();\n      Optional<SecurityGroupExtension> securityGroupExtension = computeService.getSecurityGroupExtension();\n      assertTrue(securityGroupExtension.isPresent(), \"security extension was not present\");\n      final SecurityGroupExtension security = securityGroupExtension.get();\n      final SecurityGroup seedGroup = security.createSecurityGroup(secGroupNameToDelete, getNodeTemplate().getLocation());\n      boolean deleted = security.removeSecurityGroup(seedGroup.getId());\n      assertTrue(deleted, \"just created security group failed deletion\");\n      final SecurityGroup recreatedGroup = security.createSecurityGroup(secGroupNameToDelete, getNodeTemplate().getLocation());\n\n      // Makes sure the security group exists and is re-created and is not just returned from cache\n      security.addIpPermission(IpPermission.builder()\n                      .fromPort(1000)\n                      .toPort(1000)\n                      .cidrBlock(\"1.1.1.1/32\")\n                      .ipProtocol(IpProtocol.TCP)\n                      .build(),\n              recreatedGroup);\n      boolean deleted2 = security.removeSecurityGroup(recreatedGroup.getId());\n      assertTrue(deleted2, \"just created security group failed deletion\");\n   }\n\n   @Test(groups = {\"integration\", \"live\"}, singleThreaded = true)\n   public void testSecurityGroupCacheInvalidatedWhenDeletedExternally() throws Exception {\n      String testSecurityGroupName = secGroupNameToDelete + \"-externally\";\n      ComputeService computeService = view.getComputeService();\n      Optional<SecurityGroupExtension> securityGroupExtension = computeService.getSecurityGroupExtension();\n      assertTrue(securityGroupExtension.isPresent(), \"security extension was not present\");\n      final SecurityGroupExtension security = securityGroupExtension.get();\n      final SecurityGroup seedGroup = security.createSecurityGroup(testSecurityGroupName, getNodeTemplate().getLocation());\n\n      deleteSecurityGroupFromAnotherView(seedGroup);\n\n      boolean deleted = security.removeSecurityGroup(seedGroup.getId());\n      assertFalse(deleted, \"SG deleted externally so should've failed deletion\");\n      final SecurityGroup recreatedGroup = security.createSecurityGroup(testSecurityGroupName, getNodeTemplate().getLocation());\n\n      // Makes sure the security group exists and is re-created and is not just returned from cache\n      security.addIpPermission(IpPermission.builder()\n                      .fromPort(1000)\n                      .toPort(1000)\n                      .cidrBlock(\"1.1.1.1/32\")\n                      .ipProtocol(IpProtocol.TCP)\n                      .build(),\n              recreatedGroup);\n      boolean deleted2 = security.removeSecurityGroup(recreatedGroup.getId());\n      assertTrue(deleted2, \"just created security group failed deletion\");\n   }\n\n   private void deleteSecurityGroupFromAnotherView(SecurityGroup seedGroup) {\n      ComputeServiceContext localView = createView(setupProperties(), setupModules());\n      try {\n         ComputeService localComputeService = localView.getComputeService();\n         Optional<SecurityGroupExtension> securityGroupExtension = localComputeService.getSecurityGroupExtension();\n         assertTrue(securityGroupExtension.isPresent(), \"security extension was not present\");\n         final SecurityGroupExtension security = securityGroupExtension.get();\n\n         boolean deleted = security.removeSecurityGroup(seedGroup.getId());\n         assertTrue(deleted, \"just created security group failed deletion\");\n      } finally {\n         localView.close();\n      }\n   }\n\n   private Multimap<String, String> emptyMultimap() {\n      return LinkedHashMultimap.create();\n   }\n\n   private Set<String> emptyStringSet() {\n      return Sets.newLinkedHashSet();\n   }\n   \n   private Optional<SecurityGroup> getGroup(SecurityGroupExtension ext) {\n      return Iterables.tryFind(ext.listSecurityGroups(), new Predicate<SecurityGroup>() {\n         @Override\n         public boolean apply(SecurityGroup input) {\n            return input.getId().equals(groupId);\n         }\n      });\n   }\n\n   private IpPermission createPortRangePermission() {\n      IpPermission.Builder builder = IpPermission.builder();\n\n      builder.ipProtocol(IpProtocol.TCP);\n      builder.fromPort(10);\n      builder.toPort(20);\n      builder.cidrBlock(\"0.0.0.0/0\");\n\n      return builder.build();\n   }\n\n   private IpPermission createCidrExclusionPermission() {\n      IpPermission.Builder builder = IpPermission.builder();\n\n      builder.ipProtocol(IpProtocol.TCP);\n      builder.fromPort(10);\n      builder.toPort(20);\n      builder.exclusionCidrBlock(\"10.0.0.0/8\");\n\n      return builder.build();\n   }\n\n   private IpPermission createSinglePortPermission() {\n      IpPermission.Builder builder = IpPermission.builder();\n\n      builder.ipProtocol(IpProtocol.UDP);\n      builder.fromPort(41);\n      builder.toPort(41);\n      builder.cidrBlock(\"1.1.1.1/32\");\n\n      return builder.build();\n   }\n\n   private void cleanup() {\n      if (securityGroupsSupported) {\n         ComputeService computeService = view.getComputeService();\n\n         Optional<SecurityGroupExtension> securityGroupExtension = computeService.getSecurityGroupExtension();\n\n         if (securityGroupExtension.isPresent()) {\n            Optional<SecurityGroup> group = getGroup(securityGroupExtension.get());\n\n            if (group.isPresent()) {\n               securityGroupExtension.get().removeSecurityGroup(group.get().getId());\n            }\n         }\n      }\n   }\n\n\n   @AfterClass(groups = { \"integration\", \"live\" })\n   @Override\n   protected void tearDownContext() {\n      try {\n         cleanup();\n      } catch (Exception e) {\n\n      }\n      super.tearDownContext();\n   }\n\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/extensions/internal/DelegatingImageExtensionTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.extensions.internal;\n\nimport static com.google.common.util.concurrent.Futures.immediateFuture;\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.expectLastCall;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Collections;\nimport java.util.Map;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.Future;\n\nimport org.jclouds.compute.config.ComputeServiceAdapterContextModule.AddDefaultCredentialsToImage;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.Image.Status;\nimport org.jclouds.compute.domain.ImageBuilder;\nimport org.jclouds.compute.domain.ImageTemplate;\nimport org.jclouds.compute.domain.ImageTemplateBuilder.CloneImageTemplateBuilder;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.internal.ImageTemplateImpl;\nimport org.jclouds.compute.extensions.ImageExtension;\nimport org.jclouds.compute.suppliers.ImageCacheSupplier;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.domain.LoginCredentials;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.util.concurrent.Futures;\n\n@Test(groups = \"unit\", testName = \"DelegatingImageExtensionTest\")\npublic class DelegatingImageExtensionTest {\n\n   @Test\n   public void createImageRegistersInCacheAndAddsCredentials()  {\n      ImageCacheSupplier imageCache = createMock(ImageCacheSupplier.class);\n      ImageExtension delegate = createMock(ImageExtension.class);\n      AddDefaultCredentialsToImage credsToImage = createMock(AddDefaultCredentialsToImage.class);\n\n      ImageTemplate template = new ImageTemplateImpl(\"test\") {\n      };\n      Image result = new ImageBuilder().id(\"test\")\n            .operatingSystem(OperatingSystem.builder().description(\"test\").build()).status(Status.AVAILABLE).build();\n\n      LoginCredentials credentials = LoginCredentials.builder().user(\"jclouds\").password(\"pass\").build();\n      Image withCredentials = ImageBuilder.fromImage(result).defaultCredentials(credentials).build();\n\n      expect(delegate.createImage(template)).andReturn(immediateFuture(result));\n      expect(credsToImage.apply(result)).andReturn(withCredentials);\n      imageCache.registerImage(withCredentials);\n      expectLastCall();\n      replay(delegate, imageCache, credsToImage);\n\n      new DelegatingImageExtension(imageCache, delegate, credsToImage, null).createImage(template);\n\n      verify(delegate, imageCache, credsToImage);\n   }\n\n   @Test\n   public void createImageDoesNotRegisterInCacheWhenFailed() {\n      ImageCacheSupplier imageCache = createMock(ImageCacheSupplier.class);\n      ImageExtension delegate = createMock(ImageExtension.class);\n      AddDefaultCredentialsToImage credsToImage = createMock(AddDefaultCredentialsToImage.class);\n\n      ImageTemplate template = new ImageTemplateImpl(\"test\") {\n      };\n\n      expect(delegate.createImage(template)).andReturn(Futures.<Image> immediateFailedFuture(new RuntimeException()));\n      replay(delegate, imageCache, credsToImage);\n\n      new DelegatingImageExtension(imageCache, delegate, credsToImage, null).createImage(template);\n\n      verify(delegate, imageCache, credsToImage);\n   }\n\n   @Test\n   public void createImageDoesNotRegisterInCacheWhenCancelled() {\n      ImageCacheSupplier imageCache = createMock(ImageCacheSupplier.class);\n      ImageExtension delegate = createMock(ImageExtension.class);\n      AddDefaultCredentialsToImage credsToImage = createMock(AddDefaultCredentialsToImage.class);\n\n      ImageTemplate template = new ImageTemplateImpl(\"test\") {\n      };\n\n      expect(delegate.createImage(template)).andReturn(Futures.<Image> immediateCancelledFuture());\n      replay(delegate, imageCache, credsToImage);\n\n      new DelegatingImageExtension(imageCache, delegate, credsToImage, null).createImage(template);\n\n      verify(delegate, imageCache, credsToImage);\n   }\n\n   @Test\n   public void deleteUnregistersImageFromCache() {\n      ImageCacheSupplier imageCache = createMock(ImageCacheSupplier.class);\n      ImageExtension delegate = createMock(ImageExtension.class);\n\n      expect(delegate.deleteImage(\"test\")).andReturn(true);\n      imageCache.removeImage(\"test\");\n      expectLastCall();\n      replay(delegate, imageCache);\n\n      new DelegatingImageExtension(imageCache, delegate, null, null).deleteImage(\"test\");\n\n      verify(delegate, imageCache);\n   }\n\n   @Test\n   public void deleteDoesNotUnregisterImageFromCacheWhenFailed() {\n      ImageCacheSupplier imageCache = createMock(ImageCacheSupplier.class);\n      ImageExtension delegate = createMock(ImageExtension.class);\n\n      expect(delegate.deleteImage(\"test\")).andReturn(false);\n      replay(delegate, imageCache);\n\n      new DelegatingImageExtension(imageCache, delegate, null, null).deleteImage(\"test\");\n\n      verify(delegate, imageCache);\n   }\n\n   @Test\n   public void createByCloningDoesNothingIfImageHasCredentials() throws InterruptedException, ExecutionException {\n      LoginCredentials credentials = LoginCredentials.builder().user(\"jclouds\").password(\"pass\").build();\n\n      ImageCacheSupplier imageCache = createMock(ImageCacheSupplier.class);\n      ImageExtension delegate = createMock(ImageExtension.class);\n      AddDefaultCredentialsToImage credsToImage = createMock(AddDefaultCredentialsToImage.class);\n\n      ImageTemplate template = new CloneImageTemplateBuilder().name(\"test\").nodeId(\"node1\").build();\n      Image result = new ImageBuilder().id(\"test\")\n            .operatingSystem(OperatingSystem.builder().description(\"test\").build()).status(Status.AVAILABLE)\n            .defaultCredentials(credentials).build();\n\n      expect(delegate.createImage(template)).andReturn(immediateFuture(result));\n      replay(delegate, credsToImage);\n\n      Future<Image> image = new DelegatingImageExtension(imageCache, delegate, credsToImage, null)\n            .createImage(template);\n\n      // Verify that the exact same instance is returned unmodified\n      assertTrue(image.get() == result);\n\n      verify(delegate, credsToImage);\n   }\n\n   @Test\n   public void createByCloningAddsNodeCredentials() throws InterruptedException, ExecutionException {\n      Credentials credentials = LoginCredentials.builder().user(\"jclouds\").password(\"pass\").build();\n\n      ImageCacheSupplier imageCache = createMock(ImageCacheSupplier.class);\n      ImageExtension delegate = createMock(ImageExtension.class);\n      AddDefaultCredentialsToImage credsToImage = createMock(AddDefaultCredentialsToImage.class);\n      Map<String, Credentials> credentialStore = ImmutableMap.of(\"node#node1\", credentials);\n\n      ImageTemplate template = new CloneImageTemplateBuilder().name(\"test\").nodeId(\"node1\").build();\n      Image result = new ImageBuilder().id(\"test\")\n            .operatingSystem(OperatingSystem.builder().description(\"test\").build()).status(Status.AVAILABLE).build();\n\n      expect(delegate.createImage(template)).andReturn(immediateFuture(result));\n      replay(delegate, credsToImage);\n\n      Future<Image> image = new DelegatingImageExtension(imageCache, delegate, credsToImage, credentialStore)\n            .createImage(template);\n\n      assertEquals(image.get().getDefaultCredentials(), credentials);\n\n      verify(delegate, credsToImage);\n   }\n\n   @Test\n   public void createByCloningAddsDefaultImageCredentials() throws InterruptedException, ExecutionException {\n      LoginCredentials credentials = LoginCredentials.builder().user(\"jclouds\").password(\"pass\").build();\n\n      ImageCacheSupplier imageCache = createMock(ImageCacheSupplier.class);\n      ImageExtension delegate = createMock(ImageExtension.class);\n      AddDefaultCredentialsToImage credsToImage = createMock(AddDefaultCredentialsToImage.class);\n      Map<String, Credentials> credentialStore = Collections.emptyMap();\n\n      ImageTemplate template = new CloneImageTemplateBuilder().name(\"test\").nodeId(\"node1\").build();\n      Image result = new ImageBuilder().id(\"test\")\n            .operatingSystem(OperatingSystem.builder().description(\"test\").build()).status(Status.AVAILABLE).build();\n\n      expect(delegate.createImage(template)).andReturn(immediateFuture(result));\n      expect(credsToImage.apply(result)).andReturn(\n            ImageBuilder.fromImage(result).defaultCredentials(credentials).build());\n      replay(delegate, credsToImage);\n\n      Future<Image> image = new DelegatingImageExtension(imageCache, delegate, credsToImage, credentialStore)\n            .createImage(template);\n\n      assertEquals(image.get().getDefaultCredentials(), credentials);\n\n      verify(delegate, credsToImage);\n   }\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/functions/DefaultCredentialsFromImageOrOverridingCredentialsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.functions;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.domain.LoginCredentials;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"DefaultLoginCredentialsFromImageOrOverridingLoginCredentialsTest\")\npublic class DefaultCredentialsFromImageOrOverridingCredentialsTest {\n   private static final DefaultCredentialsFromImageOrOverridingCredentials fn = new DefaultCredentialsFromImageOrOverridingCredentials();\n\n   public void testWhenLoginCredentialsNotPresentInImageOrTemplateOptionsReturnNull() {\n      LoginCredentials expected = null;\n\n      Image image = createMock(Image.class);\n      Template template = createMock(Template.class);\n\n      expect(template.getImage()).andReturn(image);\n      expect(image.getDefaultCredentials()).andReturn(null);\n      expect(template.getOptions()).andReturn(new TemplateOptions());\n\n      replay(template, image);\n\n      assertEquals(fn.apply(template), expected);\n\n      verify(template, image);\n   }\n\n   LoginCredentials expected = LoginCredentials.builder().user(\"ubuntu\").password(\"password\").build();\n\n   public void testWhenLoginCredentialsNotPresentInImageReturnsOneInTemplateOptions() {\n      Image image = createMock(Image.class);\n      Template template = createMock(Template.class);\n\n      expect(template.getImage()).andReturn(image);\n      expect(image.getDefaultCredentials()).andReturn(null);\n      expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginCredentials(expected));\n\n      replay(template, image);\n\n      assertEquals(fn.apply(template), expected);\n\n      verify(template, image);\n   }\n\n   public void testWhenLoginCredentialsNotPresentInTemplateOptionsReturnsOneInImage() {\n      Image image = createMock(Image.class);\n      Template template = createMock(Template.class);\n\n      expect(template.getImage()).andReturn(image);\n      expect(image.getDefaultCredentials()).andReturn(expected);\n      expect(template.getOptions()).andReturn(new TemplateOptions());\n\n      replay(template, image);\n\n      assertEquals(fn.apply(template), expected);\n\n      verify(template, image);\n   }\n\n   public void testWhenLoginCredentialsPresentInImageOverridesIdentityFromLoginCredentialsInTemplateOptions() {\n      Image image = createMock(Image.class);\n      Template template = createMock(Template.class);\n\n      expect(template.getImage()).andReturn(image);\n      expect(image.getDefaultCredentials()).andReturn(LoginCredentials.builder().user(\"user\").password(\"password\").build());\n      expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginUser(\"ubuntu\"));\n\n      replay(template, image);\n\n      assertEquals(fn.apply(template), expected);\n      \n      verify(template, image);\n   }\n\n   public void testWhenLoginCredentialsPresentInImageOverridesCredentialFromLoginCredentialsInTemplateOptions() {\n      Image image = createMock(Image.class);\n      Template template = createMock(Template.class);\n\n      expect(template.getImage()).andReturn(image);\n      expect(image.getDefaultCredentials()).andReturn(LoginCredentials.builder().user(\"ubuntu\").password(\"password2\").build());\n      expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginPassword(\"password\"));\n\n      replay(template, image);\n\n      assertEquals(fn.apply(template), expected);\n\n      verify(template, image);\n   }\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/functions/NodeAndTemplateOptionsToStatementWithoutPublicKeyTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.functions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Map;\n\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.jclouds.scriptbuilder.domain.Statement;\nimport org.jclouds.scriptbuilder.domain.StatementList;\nimport org.jclouds.scriptbuilder.statements.ssh.InstallRSAPrivateKey;\nimport org.jclouds.ssh.SshKeys;\nimport org.testng.annotations.Test;\n\n/**\n * Unit tests for the {@link NodeAndTemplateOptionsToStatementWithoutPublicKey} class.\n */\n@Test(groups = \"unit\", testName = \"NodeAndTemplateOptionsToStatementWithoutPublicKeyTest\")\npublic class NodeAndTemplateOptionsToStatementWithoutPublicKeyTest {\n\n   @Test\n   public void testPublicKeyDoesNotGenerateAuthorizePublicKeyStatementIfOnlyPublicKeyOptionsConfigured() {\n      Map<String, String> keys = SshKeys.generate();\n      TemplateOptions options = TemplateOptions.Builder.authorizePublicKey(keys.get(\"public\"));\n      NodeAndTemplateOptionsToStatementWithoutPublicKey function = new NodeAndTemplateOptionsToStatementWithoutPublicKey();\n      assertNull(function.apply(null, options));\n   }\n\n   @Test\n   public void testPublicAndRunScriptKeyDoesNotGenerateAuthorizePublicKeyStatementIfRunScriptPresent() {\n      Map<String, String> keys = SshKeys.generate();\n      TemplateOptions options = TemplateOptions.Builder.authorizePublicKey(keys.get(\"public\")).runScript(\"uptime\");\n\n      NodeAndTemplateOptionsToStatementWithoutPublicKey function = new NodeAndTemplateOptionsToStatementWithoutPublicKey();\n      Statement statement = function.apply(null, options);\n\n      assertEquals(statement.render(OsFamily.UNIX), \"uptime\\n\");\n   }\n\n   @Test\n   public void testPublicAndPrivateKeyAndRunScriptDoesNotGenerateAuthorizePublicKeyStatementIfOtherOptionsPresent() {\n      Map<String, String> keys = SshKeys.generate();\n      TemplateOptions options = TemplateOptions.Builder.authorizePublicKey(keys.get(\"public\"))\n            .installPrivateKey(keys.get(\"private\")).runScript(\"uptime\");\n\n      NodeAndTemplateOptionsToStatementWithoutPublicKey function = new NodeAndTemplateOptionsToStatementWithoutPublicKey();\n      Statement statement = function.apply(null, options);\n\n      assertTrue(statement instanceof StatementList);\n      StatementList statements = (StatementList) statement;\n\n      assertEquals(statements.size(), 2);\n      assertEquals(statements.get(0).render(OsFamily.UNIX), \"uptime\\n\");\n      assertTrue(statements.get(1) instanceof InstallRSAPrivateKey);\n   }\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/functions/PollNodeRunningTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.functions;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport org.easymock.EasyMock;\nimport org.easymock.IAnswer;\nimport org.jclouds.compute.config.ComputeServiceTimeoutsModule;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadata.Status;\nimport org.jclouds.compute.domain.NodeMetadataBuilder;\nimport org.jclouds.compute.predicates.AtomicNodeRunning;\nimport org.jclouds.compute.reference.ComputeServiceConstants.PollPeriod;\nimport org.jclouds.compute.reference.ComputeServiceConstants.Timeouts;\nimport org.jclouds.compute.strategy.GetNodeMetadataStrategy;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.util.concurrent.Atomics;\n\n@Test\npublic class PollNodeRunningTest {\n\n   @Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = \"node\\\\(id\\\\) didn't achieve the status running; aborting after 0 seconds with final status: PENDING\")\n   public void testIllegalStateExceptionWhenNodeStillPending() {\n      final NodeMetadata pendingNode = new NodeMetadataBuilder().ids(\"id\").status(Status.PENDING).build();\n\n      // node always stays pending\n      Predicate<AtomicReference<NodeMetadata>> nodeRunning = new Predicate<AtomicReference<NodeMetadata>>() {\n\n         @Override\n         public boolean apply(AtomicReference<NodeMetadata> input) {\n            assertEquals(input.get(), pendingNode);\n            return false;\n         }\n\n      };\n\n      AtomicReference<NodeMetadata> atomicNode = Atomics.newReference(pendingNode);\n      try {\n         new PollNodeRunning(nodeRunning).apply(atomicNode);\n      } finally {\n         assertEquals(atomicNode.get(), pendingNode);\n      }\n   }\n\n   @Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = \"node\\\\(id\\\\) terminated\")\n   public void testIllegalStateExceptionWhenNodeDied() {\n      final NodeMetadata pendingNode = new NodeMetadataBuilder().ids(\"id\").status(Status.PENDING).build();\n      final NodeMetadata deadNode = new NodeMetadataBuilder().ids(\"id\").status(Status.TERMINATED).build();\n\n      Predicate<AtomicReference<NodeMetadata>> nodeRunning = new Predicate<AtomicReference<NodeMetadata>>() {\n\n         @Override\n         public boolean apply(AtomicReference<NodeMetadata> input) {\n            assertEquals(input.get(), pendingNode);\n            input.set(deadNode);\n            return false;\n         }\n\n      };\n\n      AtomicReference<NodeMetadata> atomicNode = Atomics.newReference(pendingNode);\n      try {\n         new PollNodeRunning(nodeRunning).apply(atomicNode);\n      } finally {\n         assertEquals(atomicNode.get(), deadNode);\n      }\n   }\n\n   @Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = \"api response for node\\\\(id\\\\) was null\")\n   public void testIllegalStateExceptionAndNodeResetWhenRefSetToNull() {\n      final NodeMetadata pendingNode = new NodeMetadataBuilder().ids(\"id\").status(Status.PENDING).build();\n\n      Predicate<AtomicReference<NodeMetadata>> nodeRunning = new Predicate<AtomicReference<NodeMetadata>>() {\n\n         @Override\n         public boolean apply(AtomicReference<NodeMetadata> input) {\n            assertEquals(input.get(), pendingNode);\n            input.set(null);\n            return false;\n         }\n\n      };\n\n      AtomicReference<NodeMetadata> atomicNode = Atomics.newReference(pendingNode);\n      try {\n         new PollNodeRunning(nodeRunning).apply(atomicNode);\n      } finally {\n         assertEquals(atomicNode.get(), pendingNode);\n      }\n   }\n\n   public void testRecoversWhenTemporarilyNodeNotFound() {\n      String nodeId = \"myid\";\n      Timeouts timeouts = new Timeouts();\n\n      PollPeriod period = new PollPeriod();\n\n      final NodeMetadata pendingNode = new NodeMetadataBuilder().ids(nodeId).status(Status.PENDING).build();\n      final NodeMetadata runningNode = new NodeMetadataBuilder().ids(nodeId).status(Status.RUNNING).build();\n      GetNodeMetadataStrategy nodeClient = createMock(GetNodeMetadataStrategy.class);\n      AtomicNodeRunning nodeRunning = new AtomicNodeRunning(nodeClient);\n      Predicate<AtomicReference<NodeMetadata>> retryableNodeRunning = new ComputeServiceTimeoutsModule() {\n         public Predicate<AtomicReference<NodeMetadata>> nodeRunning(AtomicNodeRunning statusRunning,\n               Timeouts timeouts, PollPeriod period) {\n            return super.nodeRunning(statusRunning, timeouts, period);\n         }\n      }.nodeRunning(nodeRunning, timeouts, period);\n      AtomicReference<NodeMetadata> atomicNode = Atomics.newReference(pendingNode);\n\n      // Simulate transient error: first call returns null; subsequent calls\n      // return the running node\n      EasyMock.expect(nodeClient.getNode(nodeId)).andAnswer(new IAnswer<NodeMetadata>() {\n         private int count = 0;\n\n         @Override\n         public NodeMetadata answer() throws Throwable {\n            count++;\n            if (count <= 1) {\n               return null;\n            } else {\n               return runningNode;\n            }\n         }\n      }).anyTimes();\n\n      // replay mocks\n      replay(nodeClient);\n\n      // run\n      new PollNodeRunning(retryableNodeRunning).apply(atomicNode);\n\n      assertEquals(atomicNode.get().getStatus(), Status.RUNNING);\n\n      // verify mocks\n      verify(nodeClient);\n   }\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/functions/Sha512CryptTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.DataProvider;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class Sha512CryptTest {\n\n   public static final Object[][] TEST_DATA = {\n            { \"Hello world!\", \"$6$saltstring\",\n                     \"$6$saltstring$svn8UoSVapNtMuq1ukKS4tPQd8iKwSMHWjl/O817G3uBnIFNjnQJuesI68u4OTLiBFdcbYEdFCoEOfaS35inz1\" },\n            {\n                     \"Hello world!\",\n                     \"$6$rounds=10000$saltstringsaltstring\",\n                     \"$6$rounds=10000$saltstringsaltst$OW1/O6BYHV6BcXZu8QVeXbDWra3Oeqh0sbHbbMCVNSnCM/UrjmM0Dp8vOuZeHBy/YTBmSK6H9qs/y3RnOaw5v.\" },\n            { \"This is just a test\", \"$6$rounds=5000$toolongsaltstring\",\n                     \"$6$toolongsaltstrin$lQ8jolhgVRVhY4b5pZKaysCLi0QBxGoNeKQzQ3glMhwllF7oGDZxUhx1yxdYcz/e1JSbq3y6JMxxl8audkUEm0\" },\n            {\n                     \"a very much longer text to encrypt.  This one even stretches over morethan one line.\",\n                     \"$6$rounds=1400$anotherlongsaltstring\",\n                     \"$6$rounds=1400$anotherlongsalts$POfYwTEok97VWcjxIiSOjiykti.o/pQs.wPvMxQ6Fm7I6IoYN3CmLs66x9t0oSwbtEW7o7UmJEiDwGqd8p4ur1\" },\n\n            {\n                     \"a short string\",\n                     \"$6$rounds=123456$asaltof16chars..\",\n                     \"$6$rounds=123456$asaltof16chars..$BtCwjqMJGx5hrJhZywWvt0RLE8uZ4oPwcelCjmw2kSYu.Ec6ycULevoBK25fs2xXgMNrCzIMVcgEJAstJeonj1\" },\n            { \"the minimum number is still observed\", \"$6$rounds=10$roundstoolow\",\n                     \"$6$rounds=1000$roundstoolow$kUMsbe306n21p9R.FRkW3IGn.S9NPN0x50YhH1xhLsPuWGsUSklZt58jaTfF4ZEQpyUNGc0dqbpBYYBaHHrsX.\" } };\n\n   @DataProvider(name = \"data\")\n   public Object[][] createData1() {\n      return TEST_DATA;\n   }\n\n   /**\n    * Validate our implementation using test data from Ulrich Drepper's C implementation.\n    */\n   @Test(dataProvider = \"data\")\n   public void testMakeCryptedPasswordHash(String password, String salt, String expected) {\n      assertEquals(Sha512Crypt.makeShadowLine(password, salt), expected);\n   }\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/internal/BaseComputeServiceApiMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.internal;\n\nimport static org.jclouds.reflect.Reflection2.typeToken;\n\nimport org.jclouds.View;\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.apis.internal.BaseApiMetadataTest;\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.reflect.TypeToken;\n\n@Test(groups = \"unit\")\npublic abstract class BaseComputeServiceApiMetadataTest extends BaseApiMetadataTest {\n\n   public BaseComputeServiceApiMetadataTest(ApiMetadata toTest) {\n     super(toTest, ImmutableSet.<TypeToken<? extends View>>of(typeToken(ComputeServiceContext.class)));\n   }\n\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/internal/BaseComputeServiceContextLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.internal;\n\nimport static org.jclouds.reflect.Reflection2.typeToken;\n\nimport org.jclouds.compute.ComputeServiceContext;\n\nimport com.google.common.reflect.TypeToken;\n\npublic abstract class BaseComputeServiceContextLiveTest extends BaseGenericComputeServiceContextLiveTest<ComputeServiceContext> {\n\n   @Override\n   protected TypeToken<ComputeServiceContext> viewType() {\n      return typeToken(ComputeServiceContext.class);\n   }\n   \n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/internal/BaseComputeServiceLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Predicates.in;\nimport static com.google.common.base.Predicates.not;\nimport static com.google.common.collect.ImmutableSet.copyOf;\nimport static com.google.common.collect.Iterables.concat;\nimport static com.google.common.collect.Iterables.get;\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static com.google.common.collect.Iterables.transform;\nimport static com.google.common.collect.Maps.newLinkedHashMap;\nimport static com.google.common.collect.Maps.uniqueIndex;\nimport static com.google.common.collect.Sets.filter;\nimport static com.google.common.collect.Sets.newTreeSet;\nimport static java.lang.String.format;\nimport static java.lang.System.currentTimeMillis;\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static java.util.logging.Logger.getAnonymousLogger;\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.jclouds.Constants.PROPERTY_USER_THREADS;\nimport static org.jclouds.compute.options.RunScriptOptions.Builder.nameTask;\nimport static org.jclouds.compute.options.RunScriptOptions.Builder.wrapInInitScript;\nimport static org.jclouds.compute.options.TemplateOptions.Builder.overrideLoginCredentials;\nimport static org.jclouds.compute.options.TemplateOptions.Builder.runAsRoot;\nimport static org.jclouds.compute.predicates.NodePredicates.TERMINATED;\nimport static org.jclouds.compute.predicates.NodePredicates.all;\nimport static org.jclouds.compute.predicates.NodePredicates.inGroup;\nimport static org.jclouds.compute.predicates.NodePredicates.runningInGroup;\nimport static org.jclouds.compute.util.ComputeServiceUtils.getCores;\nimport static org.jclouds.util.Predicates2.retry;\nimport static org.jclouds.utils.TestUtils.NO_INVOCATIONS;\nimport static org.jclouds.utils.TestUtils.SINGLE_NO_ARG_INVOCATION;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.Assert.fail;\n\nimport java.io.IOException;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.NoSuchElementException;\nimport java.util.Properties;\nimport java.util.Set;\nimport java.util.SortedSet;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.CancellationException;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.TimeoutException;\n\nimport org.jclouds.compute.ComputeService;\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.compute.ComputeTestUtils;\nimport org.jclouds.compute.JettyStatements;\nimport org.jclouds.compute.RunNodesException;\nimport org.jclouds.compute.RunScriptOnNodesException;\nimport org.jclouds.compute.domain.ComputeMetadata;\nimport org.jclouds.compute.domain.ComputeType;\nimport org.jclouds.compute.domain.ExecResponse;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadata.Status;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.domain.TemplateBuilder;\nimport org.jclouds.compute.domain.internal.ArbitraryCpuRamTemplateBuilderImpl;\nimport org.jclouds.compute.util.OpenSocketFinder;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.predicates.SocketOpen;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.scriptbuilder.domain.Statement;\nimport org.jclouds.scriptbuilder.domain.Statements;\nimport org.jclouds.scriptbuilder.statements.java.InstallJDK;\nimport org.jclouds.scriptbuilder.statements.login.AdminAccess;\nimport org.jclouds.ssh.SshClient;\nimport org.jclouds.ssh.SshException;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.DataProvider;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Predicates;\nimport com.google.common.base.Stopwatch;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSortedSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Lists;\nimport com.google.common.collect.Maps;\nimport com.google.common.net.HostAndPort;\nimport com.google.common.util.concurrent.Futures;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.common.util.concurrent.Uninterruptibles;\nimport com.google.inject.Key;\nimport com.google.inject.Module;\nimport com.google.inject.name.Names;\n\n@Test(groups = { \"integration\", \"live\" }, singleThreaded = true)\npublic abstract class BaseComputeServiceLiveTest extends BaseComputeServiceContextLiveTest {\n\n   protected String group;\n\n   protected Predicate<HostAndPort> socketTester;\n   protected OpenSocketFinder openSocketFinder;\n   protected SortedSet<? extends NodeMetadata> nodes;\n   protected ComputeService client;\n\n   protected Template template;\n   protected Map<String, String> keyPair;\n\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   @Override\n   public void setupContext() {\n      setServiceDefaults();\n      if (group == null)\n         group = checkNotNull(provider, \"provider\");\n      // groups need to work with hyphens in them, so let's make sure there is\n      // one!\n      if (group.indexOf('-') == -1)\n         group = group + \"-\";\n      setupKeyPairForTest();\n      super.setupContext();\n   }\n\n   public void setServiceDefaults() {\n\n   }\n\n   protected void setupKeyPairForTest() {\n      keyPair = ComputeTestUtils.setupKeyPair();\n   }\n\n\n   protected void buildSocketTester() {\n      SocketOpen socketOpen = view.utils().injector().getInstance(SocketOpen.class);\n      socketTester = retry(socketOpen, 60, 1, SECONDS);\n      // wait a maximum of 60 seconds for port 8080 to open.\n      openSocketFinder = context.utils().injector().getInstance(OpenSocketFinder.class);\n   }\n\n   @Override\n   protected void initializeContext() {\n      super.initializeContext();\n      client = view.getComputeService();\n      buildSocketTester();\n   }\n\n   @Test(enabled = true, expectedExceptions = AuthorizationException.class)\n   public void testCorrectAuthException() throws Exception {\n      ComputeServiceContext context = null;\n      try {\n         Properties overrides = setupProperties();\n         overrides.setProperty(provider + \".identity\", \"MOM:MA\");\n         overrides.setProperty(provider + \".credential\", \"MIA\");\n         context = newBuilder()\n               .modules(ImmutableSet.of(getLoggingModule(), credentialStoreModule))\n               .overrides(overrides).build(ComputeServiceContext.class);\n         context.getComputeService().listNodes();\n      } catch (AuthorizationException e) {\n         throw e;\n      } catch (RuntimeException e) {\n         e.printStackTrace();\n         throw e;\n      } finally {\n         if (context != null)\n            context.close();\n      }\n   }\n\n   @Test(enabled = true)\n   public void testImagesCache() throws Exception {\n      client.listImages();\n      long time = currentTimeMillis();\n      client.listImages();\n      long duration = currentTimeMillis() - time;\n      assert duration < 1000 : format(\"%dms to get images\", duration);\n   }\n\n   @Test(enabled = true, expectedExceptions = NoSuchElementException.class)\n   public void testCorrectExceptionRunningNodesNotFound() throws Exception {\n      client.runScriptOnNodesMatching(runningInGroup(\"zebras-are-awesome\"), InstallJDK.fromOpenJDK());\n   }\n\n   public void testImageById() {\n      Template defaultTemplate = view.getComputeService().templateBuilder().build();\n      assertEquals(view.getComputeService().getImage(defaultTemplate.getImage().getId()), defaultTemplate.getImage());\n   }\n\n   // since surefire and eclipse don't otherwise guarantee the order, we are\n   // starting this one alphabetically before create2nodes..\n   @Test(enabled = true, dependsOnMethods = { \"testCompareSizes\" })\n   public void testAScriptExecutionAfterBootWithBasicTemplate() throws Exception {\n      String group = this.group + \"r\";\n      try {\n         client.destroyNodesMatching(inGroup(group));\n      } catch (Exception e) {\n\n      }\n      template = buildTemplate(templateBuilder());\n      template.getOptions().blockOnPort(22, 120);\n      try {\n         Set<? extends NodeMetadata> nodes = client.createNodesInGroup(group, 1, template);\n         NodeMetadata node = get(nodes, 0);\n         LoginCredentials good = node.getCredentials();\n         assert good.identity != null : nodes;\n\n         for (Entry<? extends NodeMetadata, ExecResponse> response : client.runScriptOnNodesMatching(\n               runningInGroup(group), \"hostname -s\",\n               wrapInInitScript(false).runAsRoot(false).overrideLoginCredentials(good)).entrySet()) {\n            checkResponseEqualsHostname(response.getValue(), response.getKey());\n         }\n\n         // test single-node execution\n         ExecResponse response = client.runScriptOnNode(node.getId(), \"hostname -s\",\n               wrapInInitScript(false).runAsRoot(false));\n         checkResponseEqualsHostname(response, node);\n         OperatingSystem os = node.getOperatingSystem();\n\n         // test bad password\n         tryBadPassword(group, good);\n\n         runScriptWithCreds(group, os, good);\n\n         checkNodes(nodes, group, \"runScriptWithCreds\");\n\n         // test adding AdminAccess later changes the default boot user, in this\n         // case to foo, with home dir /over/ridden/foo\n         ListenableFuture<ExecResponse> future = client.submitScriptOnNode(node.getId(), AdminAccess.builder()\n               .adminUsername(\"foo\").adminHome(\"/over/ridden/foo\").build(), nameTask(\"adminUpdate\"));\n\n         response = future.get(3, TimeUnit.MINUTES);\n         assert response.getExitStatus() == 0 : node.getId() + \": \" + response;\n\n         node = client.getNodeMetadata(node.getId());\n         // test that the node updated to the correct admin user!\n         assertEquals(node.getCredentials().identity, \"foo\");\n         assert node.getCredentials().credential != null : nodes;\n\n         response = client.runScriptOnNode(node.getId(), \"echo $USER\", wrapInInitScript(false).runAsRoot(false));\n         assert response.getOutput().trim().equals(\"foo\") : node.getId() + \": \" + response;\n\n      } finally {\n         client.destroyNodesMatching(inGroup(group));\n      }\n   }\n\n   @Test\n   public void testWeCanCancelTasks() throws Exception {\n      String group = this.group + \"w\";\n      try {\n         client.destroyNodesMatching(inGroup(group));\n      } catch (Exception e) {\n\n      }\n      template = buildTemplate(templateBuilder());\n      try {\n         Set<? extends NodeMetadata> nodes = client.createNodesInGroup(group, 1, template);\n         NodeMetadata node = getOnlyElement(nodes);\n         weCanCancelTasks(node);\n      } finally {\n         client.destroyNodesMatching(inGroup(group));\n      }\n   }\n\n   @Test(enabled = false)\n   protected void tryBadPassword(String group, Credentials good) throws AssertionError {\n      try {\n         Map<? extends NodeMetadata, ExecResponse> responses = client.runScriptOnNodesMatching(\n               runningInGroup(group),\n               \"echo I put a bad password\",\n               wrapInInitScript(false).runAsRoot(false).overrideLoginCredentials(\n                     LoginCredentials.builder().user(good.identity).noPrivateKey().password(\"romeo\").build()));\n         assert responses.size() == 0 : \"shouldn't pass with a bad password\\n\" + responses;\n      } catch (AssertionError e) {\n         throw e;\n      } catch (RunScriptOnNodesException e) {\n         assert Iterables.any(e.getNodeErrors().values(), Predicates.instanceOf(AuthorizationException.class)) : e\n               + \" not authexception!\";\n      }\n   }\n\n   @Test(enabled = false)\n   protected void weCanCancelTasks(NodeMetadata node) throws InterruptedException, ExecutionException {\n      ListenableFuture<ExecResponse> future = client.submitScriptOnNode(node.getId(), \"sleep 300\",\n            nameTask(\"sleeper\").runAsRoot(false));\n      ExecResponse response = null;\n      try {\n         response = future.get(1, TimeUnit.MILLISECONDS);\n         fail(node.getId() + \": \" + response);\n      } catch (TimeoutException e) {\n         assert !future.isDone();\n         response = client.runScriptOnNode(node.getId(), \"/tmp/init-sleeper status\",\n               wrapInInitScript(false).runAsRoot(false));\n         assert !response.getOutput().trim().equals(\"\") : node.getId() + \": \" + response;\n         future.cancel(true);\n         response = client.runScriptOnNode(node.getId(), \"/tmp/init-sleeper status\",\n               wrapInInitScript(false).runAsRoot(false));\n         assert response.getOutput().trim().equals(\"\") : node.getId() + \": \" + response;\n         try {\n            future.get();\n            fail(future.toString());\n         } catch (CancellationException e1) {\n\n         }\n      }\n   }\n\n   protected void checkResponseEqualsHostname(ExecResponse execResponse, NodeMetadata node1) {\n      assert execResponse.getOutput().trim().equals(node1.getHostname()) : node1 + \": \" + execResponse;\n   }\n\n   @Test(enabled = true, dependsOnMethods = { \"testImagesCache\" })\n   public void testTemplateMatch() throws Exception {\n      template = buildTemplate(templateBuilder());\n      Template toMatch = client.templateBuilder().imageId(template.getImage().getId()).build();\n      assertEquals(toMatch.getImage(), template.getImage());\n   }\n\n   protected void checkHttpGet(NodeMetadata node) {\n      ComputeTestUtils.checkHttpGet(view.utils().http(), node, 8080);\n   }\n\n   @Test(enabled = true, dependsOnMethods = \"testCreateTwoNodesWithOneSpecifiedName\")\n   public void testCreateTwoNodesWithRunScript() throws Exception {\n      try {\n         client.destroyNodesMatching(inGroup(group));\n      } catch (NoSuchElementException e) {\n\n      }\n      refreshTemplate();\n      try {\n         nodes = newTreeSet(client.createNodesInGroup(group, 2, template));\n      } catch (RunNodesException e) {\n         nodes = newTreeSet(concat(e.getSuccessfulNodes(), e.getNodeErrors().keySet()));\n         throw e;\n      }\n\n      assertEquals(nodes.size(), 2, \"expected two nodes but was \" + nodes);\n      checkNodes(nodes, group, \"bootstrap\");\n      NodeMetadata node1 = nodes.first();\n      NodeMetadata node2 = nodes.last();\n      // credentials aren't always the same\n      // assertEquals(node1.getCredentials(), node2.getCredentials());\n\n      assertLocationSameOrChild(checkNotNull(node1.getLocation(), \"location of %s\", node1), template.getLocation());\n      assertLocationSameOrChild(checkNotNull(node2.getLocation(), \"location of %s\", node2), template.getLocation());\n      checkImageIdMatchesTemplate(node1);\n      checkImageIdMatchesTemplate(node2);\n      checkOsMatchesTemplate(node1);\n      checkOsMatchesTemplate(node2);\n   }\n\n   @Test(enabled = true, dependsOnMethods = \"testDestroyNodes\", alwaysRun = true)\n   public void testCreateTwoNodesWithOneSpecifiedName() throws Exception {\n      template = buildTemplate(templateBuilder());\n      template.getOptions().nodeNames(ImmutableSet.of(\"first-node\"));\n      try {\n         this.nodes = newTreeSet(client.createNodesInGroup(group, 2, template));\n      } catch (RunNodesException e) {\n         this.nodes = newTreeSet(concat(e.getSuccessfulNodes(), e.getNodeErrors().keySet()));\n         throw e;\n      }\n\n      assertEquals(this.nodes.size(), 2, \"expected two nodes but was \" + nodes);\n      NodeMetadata node1 = Iterables.getFirst(this.nodes, null);\n      NodeMetadata node2 = Iterables.getLast(this.nodes, null);\n      // credentials aren't always the same\n      // assertEquals(node1.getCredentials(), node2.getCredentials());\n\n      assertTrue(node1.getName().equals(\"first-node\") || node2.getName().equals(\"first-node\"),\n              \"one node should be named 'first-node'\");\n      assertFalse(node1.getName().equals(\"first-node\") && node2.getName().equals(\"first-node\"),\n              \"one node should be named something other than 'first-node\");\n   }\n\n   protected Template refreshTemplate() {\n      return template = addRunScriptToTemplate(buildTemplate(templateBuilder()));\n   }\n\n   protected Template addRunScriptToTemplate(Template template) {\n      template.getOptions().runScript(Statements.newStatementList(AdminAccess.standard(), InstallJDK.fromOpenJDK()));\n      return template;\n   }\n\n   protected void checkImageIdMatchesTemplate(NodeMetadata node) {\n      if (node.getImageId() != null)\n         assertEquals(node.getImageId(), template.getImage().getId());\n   }\n\n   protected void checkOsMatchesTemplate(NodeMetadata node) {\n      if (node.getOperatingSystem() != null)\n         assert node.getOperatingSystem().getFamily().equals(template.getImage().getOperatingSystem().getFamily()) : String\n               .format(\"expecting family %s but got %s\", template.getImage().getOperatingSystem().getFamily(),\n                     node.getOperatingSystem());\n   }\n\n   void assertLocationSameOrChild(Location test, Location expected) {\n      if (!test.equals(expected)) {\n         assertEquals(test.getParent().getId(), expected.getId());\n      } else {\n         assertEquals(test, expected);\n      }\n   }\n\n   @Test(enabled = true, dependsOnMethods = \"testCreateTwoNodesWithRunScript\", alwaysRun = true)\n   public void testCreateAnotherNodeWithANewContextToEnsureSharedMemIsntRequired() throws Exception {\n      if (this.nodes == null || this.nodes.isEmpty()) {\n         template = buildTemplate(templateBuilder());\n         try {\n            nodes = newTreeSet(client.createNodesInGroup(group, 1, template));\n         } catch (RunNodesException e) {\n            nodes = newTreeSet(concat(e.getSuccessfulNodes(), e.getNodeErrors().keySet()));\n            throw e;\n         }\n      }\n\n      initializeContext();\n\n      Location existingLocation = Iterables.get(this.nodes, 0).getLocation();\n      boolean existingLocationIsAssignable = Iterables.any(client.listAssignableLocations(),\n            Predicates.equalTo(existingLocation));\n\n      if (existingLocationIsAssignable) {\n         getAnonymousLogger().info(\"creating another node based on existing nodes' location: \" + existingLocation);\n         template = buildTemplate(templateBuilder());\n         template = addRunScriptToTemplate(client.templateBuilder().fromTemplate(template)\n               .locationId(existingLocation.getId()).build());\n      } else {\n         refreshTemplate();\n         getAnonymousLogger().info(\n               format(\"%s is not assignable; using template's location %s as  \", existingLocation,\n                     template.getLocation()));\n      }\n\n      Set<? extends NodeMetadata> nodes = client.createNodesInGroup(group, 1, template);\n      assertEquals(nodes.size(), 1);\n      checkNodes(nodes, group, \"bootstrap\");\n      NodeMetadata node = Iterables.getOnlyElement(nodes);\n      if (existingLocationIsAssignable)\n         assertEquals(node.getLocation(), existingLocation);\n      else\n         this.assertLocationSameOrChild(checkNotNull(node.getLocation(), \"location of %s\", node), template.getLocation());\n      checkOsMatchesTemplate(node);\n      this.nodes = newTreeSet(concat(this.nodes, nodes));\n   }\n\n   @Test(enabled = true, dependsOnMethods = \"testCompareSizes\")\n   public void testConcurrentUseOfComputeServiceToCreateNodes() throws Exception {\n      final long timeoutMs = 20 * 60 * 1000;\n      List<String> groups = Lists.newArrayList();\n      List<ListenableFuture<NodeMetadata>> futures = Lists.newArrayList();\n      ListeningExecutorService userExecutor = context.utils().injector()\n            .getInstance(Key.get(ListeningExecutorService.class, Names.named(PROPERTY_USER_THREADS)));\n\n      try {\n         for (int i = 0; i < 2; i++) {\n            final int groupNum = i;\n            final String group = \"twin\" + groupNum;\n            groups.add(group);\n            template = buildTemplate(templateBuilder());\n            template.getOptions().inboundPorts(22, 8080).blockOnPort(22, 300 + groupNum);\n            ListenableFuture<NodeMetadata> future = userExecutor.submit(new Callable<NodeMetadata>() {\n               public NodeMetadata call() throws Exception {\n                  NodeMetadata node = getOnlyElement(client.createNodesInGroup(group, 1, template));\n                  getAnonymousLogger().info(\"Started node \" + node.getId());\n                  return node;\n               }\n            });\n            futures.add(future);\n         }\n\n         ListenableFuture<List<NodeMetadata>> compoundFuture = Futures.allAsList(futures);\n         compoundFuture.get(timeoutMs, TimeUnit.MILLISECONDS);\n\n      } finally {\n         for (String group : groups) {\n            client.destroyNodesMatching(inGroup(group));\n         }\n      }\n   }\n\n   @Test(enabled = true, dependsOnMethods = \"testCreateAnotherNodeWithANewContextToEnsureSharedMemIsntRequired\")\n   public void testCredentialsCache() throws Exception {\n      initializeContext();\n      for (NodeMetadata node : nodes)\n         assert view.utils().credentialStore().get(\"node#\" + node.getId()) != null : \"credentials for \" + node.getId();\n   }\n\n   protected Map<? extends NodeMetadata, ExecResponse> runScriptWithCreds(final String group, OperatingSystem os,\n         LoginCredentials creds) throws RunScriptOnNodesException {\n      return client.runScriptOnNodesMatching(runningInGroup(group), InstallJDK.fromOpenJDK(),\n            overrideLoginCredentials(creds).nameTask(\"runScriptWithCreds\"));\n   }\n\n   protected void checkNodes(Iterable<? extends NodeMetadata> nodes, String group, String taskName) throws IOException {\n      for (NodeMetadata node : nodes) {\n         assertNotNull(node.getProviderId());\n         assertNotNull(node.getGroup());\n         assertEquals(node.getGroup(), group);\n         assertEquals(node.getStatus(), Status.RUNNING);\n         Credentials fromStore = view.utils().credentialStore().get(\"node#\" + node.getId());\n         assertEquals(fromStore, node.getCredentials());\n         assert node.getPublicAddresses().size() >= 1 || node.getPrivateAddresses().size() >= 1 : \"no ips in\" + node;\n         assertNotNull(node.getCredentials());\n         if (node.getCredentials().identity != null) {\n            assertNotNull(node.getCredentials().identity);\n            sshPing(node, taskName);\n         }\n      }\n   }\n\n   protected TemplateBuilder templateBuilder() {\n      TemplateBuilder templateBuilder = client.templateBuilder();\n      if (templateBuilderSpec != null) {\n         templateBuilder = templateBuilder.from(templateBuilderSpec);\n      }\n      return templateBuilder;\n   }\n\n   protected Template buildTemplate(TemplateBuilder templateBuilder) {\n      return templateBuilder.build();\n   }\n\n   @Test(enabled = true)\n   public void testGet() throws Exception {\n      template = buildTemplate(templateBuilder());\n      try {\n         nodes = newTreeSet(client.createNodesInGroup(group, 1, template));\n      } catch (RunNodesException e) {\n         nodes = newTreeSet(concat(e.getSuccessfulNodes(), e.getNodeErrors().keySet()));\n         throw e;\n      }\n\n      Map<String, ? extends NodeMetadata> uniqueMap = uniqueIndex(\n            filter(client.listNodesDetailsMatching(all()), Predicates.and(inGroup(group), not(TERMINATED))),\n            new Function<NodeMetadata, String>() {\n\n               @Override\n               public String apply(NodeMetadata from) {\n                  return from.getId();\n               }\n\n            });\n      Map<String, ? extends NodeMetadata> metadataMap = newLinkedHashMap(uniqueMap);\n      for (NodeMetadata node : nodes) {\n         assertNotNull(metadataMap.remove(node.getId()));\n         NodeMetadata metadata = client.getNodeMetadata(node.getId());\n         assertEquals(metadata.getProviderId(), node.getProviderId());\n         assertEquals(metadata.getGroup(), node.getGroup());\n         assertLocationSameOrChild(checkNotNull(metadata.getLocation(), \"location of %s\", metadata), template.getLocation());\n         checkImageIdMatchesTemplate(metadata);\n         checkOsMatchesTemplate(metadata);\n         assert metadata.getStatus() == Status.RUNNING : metadata;\n         // due to DHCP the addresses can actually change in-between runs.\n         assertEquals(metadata.getPrivateAddresses().size(), node.getPrivateAddresses().size(), format(\n               \"[%s] didn't match: [%s]\", metadata.getPrivateAddresses(), node.getPrivateAddresses().size()));\n         assertEquals(metadata.getPublicAddresses().size(), node.getPublicAddresses().size(), format(\n               \"[%s] didn't match: [%s]\", metadata.getPublicAddresses(), node.getPublicAddresses().size()));\n      }\n   }\n\n   @Test(enabled = true, dependsOnMethods = \"testGet\")\n   public void testReboot() throws Exception {\n      Set<? extends NodeMetadata> rebootNodes = client.rebootNodesMatching(inGroup(group));\n      for (ComputeMetadata node : rebootNodes) {\n         assertNotNull(node);\n         assert node.getProviderId() != null : node;\n         assert node.getLocation() != null : node;\n      }\n\n      // validation\n      testGet();\n   }\n\n   @Test(enabled = true, dependsOnMethods = \"testReboot\")\n   public void testSuspendResume() throws Exception {\n\n      Set<? extends NodeMetadata> suspendedNodes = client.suspendNodesMatching(inGroup(group));\n      for (ComputeMetadata node : suspendedNodes) {\n         assertNotNull(node);\n         assert node.getProviderId() != null : node;\n         assert node.getLocation() != null : node;\n      }\n\n      Set<? extends NodeMetadata> stoppedNodes = refreshNodes();\n\n      assert Iterables.all(stoppedNodes, new Predicate<NodeMetadata>() {\n\n         @Override\n         public boolean apply(NodeMetadata input) {\n            boolean returnVal = input.getStatus() == Status.SUSPENDED;\n            if (!returnVal)\n               getAnonymousLogger().warning(format(\"node %s in state %s%n\", input.getId(), input.getStatus()));\n            return returnVal;\n         }\n\n      }) : stoppedNodes;\n\n      Set<? extends NodeMetadata> resumedNodes = client.resumeNodesMatching(inGroup(group));\n      for (ComputeMetadata node : resumedNodes) {\n         assertNotNull(node);\n         assert node.getProviderId() != null : node;\n         assert node.getLocation() != null : node;\n      }\n\n      testGet();\n   }\n\n   @Test(enabled = true, dependsOnMethods = \"testSuspendResume\")\n   public void testListNodes() throws Exception {\n      for (ComputeMetadata node : client.listNodes()) {\n         assert node.getProviderId() != null : node;\n         assert node.getLocation() != null : node;\n         assertEquals(node.getType(), ComputeType.NODE);\n      }\n   }\n\n   @Test(enabled = true, dependsOnMethods = \"testSuspendResume\")\n   public void testListNodesByIds() throws Exception {\n      Set<String> nodeIds = copyOf(transform(nodes,\n         new Function<NodeMetadata, String>() {\n\n            @Override\n            public String apply(NodeMetadata from) {\n               return from.getId();\n            }\n\n         }));\n\n      SortedSet<? extends ComputeMetadata> listedNodes = ImmutableSortedSet.copyOf(client.listNodesByIds(nodeIds));\n      // newTreeSet is here because elementsEqual cares about ordering.\n      assertTrue(Iterables.elementsEqual(nodes, listedNodes),\n              \"nodes and listNodesByIds should be identical: was \" + listedNodes + \" but should be \" + nodes);\n   }\n\n   @Test(enabled = true, dependsOnMethods = \"testSuspendResume\")\n   public void testGetNodesWithDetails() throws Exception {\n      for (NodeMetadata node : client.listNodesDetailsMatching(all())) {\n         assert node.getProviderId() != null : node;\n         assert node.getLocation() != null : node;\n         assertEquals(node.getType(), ComputeType.NODE);\n         NodeMetadata nodeMetadata = node;\n         assert nodeMetadata.getProviderId() != null : nodeMetadata;\n         // nullable\n         // assert nodeMetadata.getImage() != null : node;\n         // user specified name is not always supported\n         // assert nodeMetadata.getName() != null : nodeMetadata;\n         if (nodeMetadata.getStatus() == Status.RUNNING) {\n            assert nodeMetadata.getPublicAddresses() != null : nodeMetadata;\n            assert !nodeMetadata.getPublicAddresses().isEmpty() || !nodeMetadata.getPrivateAddresses().isEmpty() : nodeMetadata;\n            assertNotNull(nodeMetadata.getPrivateAddresses());\n         }\n      }\n   }\n\n   @Test(enabled = true, alwaysRun = true, dependsOnMethods = { \"testListNodes\", \"testGetNodesWithDetails\", \"testListNodesByIds\" })\n   public void testDestroyNodes() {\n      int toDestroy = refreshNodes().size();\n      Set<? extends NodeMetadata> destroyed = client.destroyNodesMatching(inGroup(group));\n      assertEquals(toDestroy, destroyed.size());\n      waitGracePeriodForDestroyedNodes();\n      for (NodeMetadata node : filter(client.listNodesDetailsMatching(all()), inGroup(group))) {\n         assert node.getStatus() == Status.TERMINATED : node;\n         assert view.utils().credentialStore().get(\"node#\" + node.getId()) == null : \"credential should have been null for \"\n               + \"node#\" + node.getId();\n      }\n   }\n\n   protected void waitGracePeriodForDestroyedNodes() {\n      Uninterruptibles.sleepUninterruptibly(100, TimeUnit.SECONDS);\n   }\n\n   private Set<? extends NodeMetadata> refreshNodes() {\n      return filter(client.listNodesDetailsMatching(all()), Predicates.and(inGroup(group), not(TERMINATED)));\n   }\n\n   static class ServiceStats {\n      long backgroundProcessMilliseconds;\n      long socketOpenMilliseconds;\n\n      @Override\n      public String toString() {\n         return format(\"[backgroundProcessMilliseconds=%s, socketOpenMilliseconds=%s]\",\n               backgroundProcessMilliseconds, socketOpenMilliseconds);\n      }\n   }\n\n   protected ServiceStats trackAvailabilityOfProcessOnNode(Statement process, String processName, NodeMetadata node) {\n      ServiceStats stats = new ServiceStats();\n      Stopwatch watch = Stopwatch.createStarted();\n      ExecResponse exec = client.runScriptOnNode(node.getId(), process, runAsRoot(false).wrapInInitScript(false));\n      stats.backgroundProcessMilliseconds = watch.elapsed(TimeUnit.MILLISECONDS);\n      watch.reset().start();\n\n      HostAndPort socket = null;\n      try {\n         socket = openSocketFinder.findOpenSocketOnNode(node, 8080, 600, TimeUnit.SECONDS);\n      } catch (NoSuchElementException e) {\n         throw new NoSuchElementException(format(\"%s%n%s%s\", e.getMessage(), exec.getOutput(), exec.getError()));\n      }\n\n      stats.socketOpenMilliseconds = watch.elapsed(TimeUnit.MILLISECONDS);\n\n      getAnonymousLogger().info(format(\"<< %s on node(%s)[%s] %s\", processName, node.getId(), socket, stats));\n      return stats;\n   }\n\n   @Test(enabled = true)\n   public void testCreateAndRunAService() throws Exception {\n\n      String group = this.group + \"s\";\n      try {\n         client.destroyNodesMatching(inGroup(group));\n      } catch (Exception e) {\n\n      }\n\n      try {\n         createAndRunAServiceInGroup(group);\n      } finally {\n         client.destroyNodesMatching(inGroup(group));\n      }\n\n   }\n\n   protected void createAndRunAServiceInGroup(String group) throws RunNodesException {\n      // note that some cloud providers do not support mixed case tag names\n      ImmutableMap<String, String> userMetadata = ImmutableMap.<String, String> of(\"test\", group);\n\n      ImmutableSet<String> tags = ImmutableSet.of(group);\n      Stopwatch watch = Stopwatch.createStarted();\n\n      template = buildTemplate(templateBuilder());\n      template.getOptions().inboundPorts(22, 8080).blockOnPort(22, 300).userMetadata(userMetadata).tags(tags);\n\n      NodeMetadata node = getOnlyElement(client.createNodesInGroup(group, 1, template));\n      long createSeconds = watch.elapsed(TimeUnit.SECONDS);\n\n      final String nodeId = node.getId();\n\n      checkUserMetadataContains(node, userMetadata);\n      checkTagsInNodeEquals(node, tags);\n\n      getAnonymousLogger().info(\n            format(\"<< available node(%s) os(%s) in %ss\", node.getId(), node.getOperatingSystem(), createSeconds));\n\n      watch.reset().start();\n\n      client.runScriptOnNode(nodeId, JettyStatements.install(), nameTask(\"configure-jetty\"));\n\n      long configureSeconds = watch.elapsed(TimeUnit.SECONDS);\n\n      getAnonymousLogger().info(\n            format(\n                  \"<< configured node(%s) with %s and jetty %s in %ss\",\n                  nodeId,\n                  exec(nodeId, \"java -fullversion\"),\n                  exec(nodeId, JettyStatements.version()), configureSeconds));\n\n      trackAvailabilityOfProcessOnNode(JettyStatements.start(), \"start jetty\", node);\n\n      client.runScriptOnNode(nodeId, JettyStatements.stop(), runAsRoot(false).wrapInInitScript(false));\n\n      trackAvailabilityOfProcessOnNode(JettyStatements.start(), \"start jetty\", node);\n   }\n\n   protected String exec(final String nodeId, String command) {\n      return exec(nodeId, Statements.exec(command));\n   }\n\n   protected String exec(final String nodeId, Statement command) {\n      return client.runScriptOnNode(nodeId, command, runAsRoot(false).wrapInInitScript(false)).getOutput().trim();\n   }\n\n   protected void checkUserMetadataContains(NodeMetadata node, ImmutableMap<String, String> userMetadata) {\n      Map<String, String> missing = Maps.difference(node.getUserMetadata(), userMetadata).entriesOnlyOnRight();\n      assert missing.isEmpty() : format(\"node userMetadata did not contain %s %s\", missing, node);\n   }\n\n   protected void checkTagsInNodeEquals(NodeMetadata node, ImmutableSet<String> tags) {\n      assert node.getTags().equals(tags) : format(\"node tags did not match %s %s\", tags, node);\n   }\n\n   public void testListImages() throws Exception {\n      for (Image image : client.listImages()) {\n         assert image.getProviderId() != null : image;\n         // image.getLocationId() can be null, if it is a location-free image\n         assertEquals(image.getType(), ComputeType.IMAGE);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testGetAssignableLocations() throws Exception {\n      for (Location location : client.listAssignableLocations()) {\n         getAnonymousLogger().warning(\"location \" + location);\n         assert location.getId() != null : location;\n         assert location != location.getParent() : location;\n         assert location.getScope() != null : location;\n         switch (location.getScope()) {\n         case PROVIDER:\n            assertProvider(location);\n            break;\n         case REGION:\n            assertProvider(location.getParent());\n            break;\n         case ZONE:\n            Location provider = location.getParent().getParent();\n            // zone can be a direct descendant of provider\n            if (provider == null)\n               provider = location.getParent();\n            assertProvider(provider);\n            break;\n         case HOST:\n            Location provider2 = location.getParent().getParent().getParent();\n            // zone can be a direct descendant of provider\n            if (provider2 == null)\n               provider2 = location.getParent().getParent();\n            assertProvider(provider2);\n            break;\n         default:\n            break;\n         }\n      }\n   }\n\n   protected int nonBlockDurationSeconds = 30;\n\n   public void testOptionToNotBlock() throws Exception {\n      String group = this.group + \"block\";\n      try {\n         client.destroyNodesMatching(inGroup(group));\n      } catch (Exception e) {\n\n      }\n      // no inbound ports\n      template = buildTemplate(templateBuilder());\n      template.getOptions().blockUntilRunning(false).inboundPorts();\n      try {\n         long time = currentTimeMillis();\n         Set<? extends NodeMetadata> nodes = client.createNodesInGroup(group, 1, template);\n         NodeMetadata node = getOnlyElement(nodes);\n         assert node.getStatus() != Status.RUNNING : node;\n         long duration = (currentTimeMillis() - time) / 1000;\n         assert duration < nonBlockDurationSeconds : format(\"duration(%d) longer than expected(%d) seconds! \",\n               duration, nonBlockDurationSeconds);\n      } finally {\n         client.destroyNodesMatching(inGroup(group));\n      }\n   }\n\n   private void assertProvider(Location provider) {\n      assertEquals(provider.getScope(), LocationScope.PROVIDER);\n      assertEquals(provider.getParent(), null);\n   }\n\n   public void testListSizes() throws Exception {\n      for (Hardware hardware : client.listHardwareProfiles()) {\n         assert hardware.getProviderId() != null : hardware;\n         assert getCores(hardware) > 0 : hardware;\n         assert hardware.getRam() > 0 : hardware;\n         assertEquals(hardware.getType(), ComputeType.HARDWARE);\n         checkVolumes(hardware);\n      }\n   }\n\n   protected void checkVolumes(Hardware hardware) {\n      assert hardware.getVolumes().size() > 0 : hardware;\n   }\n\n   @Test(enabled = true)\n   public void testCompareSizes() throws Exception {\n      // Allow to override the comparison but keeping testng dependencies happy\n      doCompareSizes();\n   }\n\n   protected void doCompareSizes() throws Exception {\n      Hardware defaultSize = client.templateBuilder().build().getHardware();\n\n      Hardware smallest = client.templateBuilder().smallest().build().getHardware();\n      Hardware fastest = client.templateBuilder().fastest().build().getHardware();\n      Hardware biggest = client.templateBuilder().biggest().build().getHardware();\n\n      getAnonymousLogger().info(\"smallest \" + smallest);\n      getAnonymousLogger().info(\"fastest \" + fastest);\n      getAnonymousLogger().info(\"biggest \" + biggest);\n\n      assertEquals(defaultSize, smallest);\n\n      assert getCores(smallest) <= getCores(fastest) : format(\"%s ! <= %s\", smallest, fastest);\n      assert getCores(biggest) <= getCores(fastest) : format(\"%s ! <= %s\", biggest, fastest);\n\n      assert biggest.getRam() >= fastest.getRam() : format(\"%s ! >= %s\", biggest, fastest);\n      assert biggest.getRam() >= smallest.getRam() : format(\"%s ! >= %s\", biggest, smallest);\n\n      assert getCores(fastest) >= getCores(biggest) : format(\"%s ! >= %s\", fastest, biggest);\n      assert getCores(fastest) >= getCores(smallest) : format(\"%s ! >= %s\", fastest, smallest);\n   }\n\n   private void sshPing(NodeMetadata node, String taskName) throws IOException {\n      for (int i = 0; i < 5; i++) {// retry loop TODO replace with predicate.\n         try {\n            doCheckJavaIsInstalledViaSsh(node, taskName);\n            return;\n         } catch (SshException e) {\n            try {\n               Thread.sleep(10 * 1000);\n            } catch (InterruptedException e1) {\n            }\n            continue;\n         }\n      }\n   }\n\n   protected void doCheckJavaIsInstalledViaSsh(NodeMetadata node, String taskName) throws IOException {\n      SshClient ssh = view.utils().sshForNode().apply(node);\n      try {\n         ssh.connect();\n         ExecResponse hello = ssh.exec(\"echo hello\");\n         assertEquals(hello.getOutput().trim(), \"hello\");\n         ExecResponse exec = ssh.exec(\"java -version\");\n         assert exec.getError().indexOf(\"OpenJDK\") != -1 || exec.getOutput().indexOf(\"OpenJDK\") != -1 : exec\n               + \"\\n\"\n               + ssh.exec(\"cat /tmp/\" + taskName + \"/\" + taskName + \".sh /tmp/\" + taskName + \"/stdout.log /tmp/\"\n                     + taskName + \"/stderr.log\");\n      } finally {\n         if (ssh != null)\n            ssh.disconnect();\n      }\n   }\n\n   @DataProvider\n   public Object[][] onlyIfAutomaticHardwareSupported() {\n      return  client.templateBuilder() instanceof ArbitraryCpuRamTemplateBuilderImpl ?\n            SINGLE_NO_ARG_INVOCATION : NO_INVOCATIONS;\n   }\n\n   @Test(dataProvider = \"onlyIfAutomaticHardwareSupported\", groups = {\"integration\", \"live\"})\n   public void testCreateNodeWithCustomHardware() throws Exception {\n      Template template = buildTemplate(templateBuilder()\n            .hardwareId(\"automatic:cores=2;ram=4096\"));\n      try {\n         NodeMetadata node = getOnlyElement(client.createNodesInGroup(group + \"custom\", 1, template));\n         assertThat(node.getHardware().getRam()).isEqualTo(4096);\n         assertThat(node.getHardware().getProcessors().get(0).getCores()).isEqualTo(2);\n      }\n      finally {\n         client.destroyNodesMatching(inGroup(group + \"custom\"));\n      }\n   }\n\n   @AfterClass(groups = { \"integration\", \"live\" })\n   @Override\n   protected void tearDownContext() {\n      try {\n         if (nodes != null) {\n            // Destroy all nodes in the group but also make sure to destroy other created nodes that might not be in it.\n            // The \"testCreateTwoNodesWithOneSpecifiedName\" creates nodes with an explicit name that puts them outside the group,\n            // so the list of nodes should also be taken into account when destroying the nodes.\n            client.destroyNodesMatching(Predicates.<NodeMetadata> or(inGroup(group), (Predicate<NodeMetadata>) in(nodes)));\n         }\n      } catch (Exception e) {\n\n      }\n      super.tearDownContext();\n   }\n\n   @Override\n   protected Module getSshModule() {\n      throw new IllegalStateException(\"ssh is required for this test!\");\n   }\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/internal/BaseGenericComputeServiceContextLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.internal;\n\nimport java.util.Properties;\nimport java.util.concurrent.ConcurrentHashMap;\n\nimport org.jclouds.apis.BaseViewLiveTest;\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.compute.domain.TemplateBuilderSpec;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.domain.LoginCredentials.Builder;\nimport org.jclouds.rest.config.CredentialStoreModule;\n\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.io.ByteSource;\nimport com.google.inject.Module;\nimport com.google.inject.util.Modules;\n\npublic abstract class BaseGenericComputeServiceContextLiveTest<W extends ComputeServiceContext> extends BaseViewLiveTest<W> {\n\n   protected TemplateBuilderSpec templateBuilderSpec;\n   protected LoginCredentials loginCredentials = LoginCredentials.builder().user(\"root\").build();\n\n   // isolate tests from eachother, as default credentialStore is static\n   protected Module credentialStoreModule = new CredentialStoreModule(\n         new ConcurrentHashMap<String, ByteSource>());\n   \n   @Override\n   protected Properties setupProperties() {\n      Properties overrides = super.setupProperties();\n      String spec = setIfTestSystemPropertyPresent(overrides, provider + \".template\");\n      if (spec != null) {\n         templateBuilderSpec = TemplateBuilderSpec.parse(spec);\n         if (templateBuilderSpec.getLoginUser() != null) {\n            Iterable<String> userPass = Splitter.on(':').split(templateBuilderSpec.getLoginUser());\n            Builder loginCredentialsBuilder = LoginCredentials.builder();\n            loginCredentialsBuilder.user(Iterables.get(userPass, 0));\n            if (Iterables.size(userPass) == 2)\n               loginCredentialsBuilder.password(Iterables.get(userPass, 1));\n            if (templateBuilderSpec.getAuthenticateSudo() != null)\n               loginCredentialsBuilder.authenticateSudo(templateBuilderSpec.getAuthenticateSudo());\n            loginCredentials = loginCredentialsBuilder.build();\n         }\n      }\n      return overrides;\n   }\n\n   @Override\n   protected Iterable<Module> setupModules() {\n      return ImmutableSet.<Module> of(getLoggingModule(), credentialStoreModule, getSshModule());\n   }\n   \n   protected Module getSshModule() {\n      return Modules.EMPTY_MODULE;\n   }\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/internal/BaseTemplateBuilderLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.internal;\n\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.jclouds.compute.util.ComputeServiceUtils.getCores;\nimport static org.jclouds.utils.TestUtils.NO_INVOCATIONS;\nimport static org.jclouds.utils.TestUtils.SINGLE_NO_ARG_INVOCATION;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.util.Properties;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentHashMap;\n\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.domain.internal.ArbitraryCpuRamTemplateBuilderImpl;\nimport org.jclouds.compute.util.AutomaticHardwareIdSpec;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.rest.config.CredentialStoreModule;\nimport org.testng.SkipException;\nimport org.testng.annotations.DataProvider;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.io.ByteSource;\nimport com.google.inject.Module;\n\n@Test(groups = \"integration,live\")\npublic abstract class BaseTemplateBuilderLiveTest extends BaseComputeServiceContextLiveTest {\n\n   public void testCompareSizes() throws Exception {\n      Hardware defaultSize = view.getComputeService().templateBuilder().build().getHardware();\n\n      Hardware smallest = view.getComputeService().templateBuilder().smallest().build().getHardware();\n      Hardware fastest = view.getComputeService().templateBuilder().fastest().build().getHardware();\n      Hardware biggest = view.getComputeService().templateBuilder().biggest().build().getHardware();\n\n      assertEquals(defaultSize, smallest);\n\n      assert getCores(smallest) <= getCores(fastest) : String.format(\"%s ! <= %s\", smallest, fastest);\n      assert getCores(biggest) <= getCores(fastest) : String.format(\"%s ! <= %s\", biggest, fastest);\n\n      assert biggest.getRam() >= fastest.getRam() : String.format(\"%s ! >= %s\", biggest, fastest);\n      assert biggest.getRam() >= smallest.getRam() : String.format(\"%s ! >= %s\", biggest, smallest);\n\n      assert getCores(fastest) >= getCores(biggest) : String.format(\"%s ! >= %s\", fastest, biggest);\n      assert getCores(fastest) >= getCores(smallest) : String.format(\"%s ! >= %s\", fastest, smallest);\n   }\n\n   public void testFromTemplate() {\n      Template defaultTemplate = view.getComputeService().templateBuilder().build();\n      assertEquals(view.getComputeService().templateBuilder().fromTemplate(defaultTemplate).build().toString(),\n            defaultTemplate.toString());\n   }\n\n   @Test\n   public void testTemplateBuilderCanUseImageId() throws Exception {\n      Template defaultTemplate = view.getComputeService().templateBuilder().build();\n      view.close();\n      setupContext();\n\n      Template template = view.getComputeService().templateBuilder().imageId(defaultTemplate.getImage().getId())\n            .locationId(defaultTemplate.getLocation().getId()).build();\n      assertEquals(template.getImage(), defaultTemplate.getImage());\n   }\n\n   @Test\n   public void testDefaultTemplateBuilder() throws IOException {\n      Template defaultTemplate = view.getComputeService().templateBuilder().build();\n      assertTrue(defaultTemplate.getImage().getOperatingSystem().getVersion().matches(\"\\\\d+\\\\.\\\\d+\"),\n            \"Version mismatch, expected dd.dd, found: \" + defaultTemplate.getImage().getOperatingSystem().getVersion());\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true);\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.UBUNTU);\n      assertEquals(getCores(defaultTemplate.getHardware()), 1.0d);\n   }\n\n   protected abstract Set<String> getIso3166Codes();\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testGetAssignableLocations() throws Exception {\n      assertProvider(view.unwrap());\n      for (Location location : view.getComputeService().listAssignableLocations()) {\n         assert location.getId() != null : location;\n         assert location != location.getParent() : location;\n         assert location.getScope() != null : location;\n         switch (location.getScope()) {\n         case PROVIDER:\n            assertProvider(location);\n            break;\n         case REGION:\n            assertProvider(location.getParent());\n            assert location.getIso3166Codes().size() == 0\n                  || location.getParent().getIso3166Codes().containsAll(location.getIso3166Codes()) : location + \" ||\"\n                  + location.getParent();\n            break;\n         case ZONE:\n            Location provider = location.getParent().getParent();\n            // zone can be a direct descendant of provider\n            if (provider == null)\n               provider = location.getParent();\n            assertProvider(provider);\n            assert location.getIso3166Codes().size() == 0\n                  || location.getParent().getIso3166Codes().containsAll(location.getIso3166Codes()) : location + \" ||\"\n                  + location.getParent();\n            break;\n         case SYSTEM:\n            Location systemParent = location.getParent();\n            // loop up to root, which must be the provider\n            while (systemParent.getParent() != null) {\n                systemParent = systemParent.getParent();\n            }\n            assertProvider(systemParent);\n            break;\n         case NETWORK:\n             Location networkParent = location.getParent();\n             // loop up to root, which must be the provider\n             while (networkParent.getParent() != null) {\n                 networkParent = networkParent.getParent();\n             }\n             assertProvider(networkParent);\n             break;\n         case HOST:\n            Location provider2 = location.getParent().getParent().getParent();\n            // zone can be a direct descendant of provider\n            if (provider2 == null)\n               provider2 = location.getParent().getParent();\n            assertProvider(provider2);\n            break;\n         }\n      }\n   }\n\n   @Test\n   public void testTemplateBuilderWithImageIdSpecified() throws IOException {\n      Template defaultTemplate = view.getComputeService().templateBuilder().build();\n\n      ComputeServiceContext context = null;\n      try {\n         Properties overrides = setupProperties();\n         overrides.setProperty(\"jclouds.image-id\", defaultTemplate.getImage().getId());\n\n         context = createView(overrides, setupModules());\n\n         assertEqualsTemplate(context.getComputeService().templateBuilder().build(), defaultTemplate);\n      } finally {\n         if (context != null)\n            context.close();\n      }\n\n      context = null;\n      try {\n         Properties overrides = setupProperties();\n         overrides.setProperty(provider + \".image-id\", defaultTemplate.getImage().getId());\n\n         context = createView(overrides, setupModules());\n\n         assertEqualsTemplate(context.getComputeService().templateBuilder().build(), defaultTemplate);\n      } finally {\n         if (context != null)\n            context.close();\n      }\n   }\n\n   @Test\n   public void testTemplateBuilderWithLoginUserSpecified() throws IOException {\n      tryOverrideUsingPropertyKey(\"jclouds\");\n      tryOverrideUsingPropertyKey(provider);\n   }\n\n   protected void tryOverrideUsingPropertyKey(String propertyKey) {\n      // isolate tests from eachother, as default credentialStore is static\n      Module credentialStoreModule = new CredentialStoreModule(\n            new ConcurrentHashMap<String, ByteSource>());\n\n      ComputeServiceContext context = null;\n      try {\n         Properties overrides = setupProperties();\n         String login = templateBuilderSpec != null && templateBuilderSpec.getLoginUser() != null ? templateBuilderSpec\n               .getLoginUser() : \"foo:bar\";\n         overrides.setProperty(propertyKey + \".image.login-user\", login);\n         boolean auth = templateBuilderSpec != null && templateBuilderSpec.getAuthenticateSudo() != null ? templateBuilderSpec\n               .getAuthenticateSudo() : true;\n         overrides.setProperty(propertyKey + \".image.authenticate-sudo\", auth + \"\");\n\n         context = createView(overrides, ImmutableSet.<Module>of(credentialStoreModule));\n\n         Iterable<String> userPass = Splitter.on(':').split(login);\n         String user = Iterables.get(userPass, 0);\n         String pass = Iterables.size(userPass) > 1 ? Iterables.get(userPass, 1) : null;\n         assertEquals(context.getComputeService().templateBuilder().build().getImage().getDefaultCredentials(),\n               LoginCredentials.builder().user(user).password(pass).authenticateSudo(auth).build());\n      } finally {\n         if (context != null) {\n            context.close();\n         }\n      }\n   }\n\n   void assertProvider(Location provider) {\n      assertEquals(provider.getScope(), LocationScope.PROVIDER);\n      assertEquals(provider.getParent(), null);\n      assertEquals(provider.getIso3166Codes(), getIso3166Codes());\n   }\n\n   static void assertEqualsTemplate(Template actual, Template expected){\n      assertEquals(actual.getImage(), expected.getImage());\n      assertEquals(actual.getHardware(), expected.getHardware());\n      assertEquals(actual.getOptions(), expected.getOptions());\n      assertTrue(actual.getLocation().getScope().compareTo(expected.getLocation().getScope()) <= 0);\n   }\n\n   @DataProvider\n   public Object[][] onlyIfAutomaticHardwareSupported() {\n      return  view.getComputeService().templateBuilder() instanceof ArbitraryCpuRamTemplateBuilderImpl ?\n            SINGLE_NO_ARG_INVOCATION : NO_INVOCATIONS;\n   }\n\n   @Test(dataProvider = \"onlyIfAutomaticHardwareSupported\", groups = {\"integration\", \"live\"})\n   public void testAutoGeneratedHardwareFromId() {\n      Template template = view.getComputeService().templateBuilder()\n            .hardwareId(\"automatic:cores=2;ram=1024\").build();\n      assertThat(template.getHardware().getId()).isEqualTo(\"automatic:cores=2.0;ram=1024\");\n      assertThat(template.getHardware().getRam()).isEqualTo(1024);\n      assertThat(template.getHardware().getProcessors().get(0).getCores()).isEqualTo(2);\n   }\n\n   @Test(dataProvider = \"onlyIfAutomaticHardwareSupported\", groups = {\"integration\", \"live\"})\n   public void testAutoGeneratedHardwareMatchHardwareProfile() {\n      if (!view.getComputeService().listHardwareProfiles().isEmpty()) {\n         Template template = view.getComputeService().templateBuilder()\n               .minRam(2048).minCores(2).build();\n         assertThat(AutomaticHardwareIdSpec.isAutomaticId(template.getHardware().getId())).isFalse();\n         assertThat(template.getHardware().getRam()).isGreaterThanOrEqualTo(2048);\n         assertThat(template.getHardware().getProcessors().get(0).getCores()).isGreaterThanOrEqualTo(2);\n      }\n      else {\n         throw new SkipException(\"Hardware profile list is empty, this provider can not match any hardware profile\" +\n               \"to the specified minRam and minCores.\");\n      }\n   }\n\n   @Test(dataProvider = \"onlyIfAutomaticHardwareSupported\", groups = {\"integration\", \"live\"})\n   public void testAutoGeneratedHardwareWithMinCoresAndMinRam() {\n      if (view.getComputeService().listHardwareProfiles().isEmpty()) {\n         Template template = view.getComputeService().templateBuilder()\n               .minRam(2048).minCores(2).build();\n         assertThat(AutomaticHardwareIdSpec.isAutomaticId(template.getHardware().getId())).isTrue();\n         assertThat(template.getHardware().getRam()).isEqualTo(2048);\n         assertThat(template.getHardware().getProcessors().get(0).getCores()).isEqualTo(2);\n      }\n      else {\n         throw new SkipException(\"Hardware profile list not empty.\");\n      }\n   }\n\n   @Test(dataProvider = \"onlyIfAutomaticHardwareSupported\", groups = {\"integration\", \"live\"})\n   public void testAutoGeneratedHardwareWithOnlyMinCoresMatchHardwareProfile() {\n      if (!view.getComputeService().listHardwareProfiles().isEmpty()) {\n         Template template = view.getComputeService().templateBuilder().minCores(4).build();\n         assertThat(AutomaticHardwareIdSpec.isAutomaticId(template.getHardware().getId())).isFalse();\n         assertThat(template.getHardware().getProcessors().get(0).getCores()).isGreaterThanOrEqualTo(4);\n      }\n      else {\n         throw new SkipException(\"Hardware profile list is empty, this provider can not match any hardware profile\" +\n               \"to the specified minRam and minCores.\");\n      }\n   }\n\n   @Test(dataProvider = \"onlyIfAutomaticHardwareSupported\", groups = {\"integration\", \"live\"})\n   public void testAutoGeneratedHardwareWithOnlyMinRamMatchHardwareProfile() {\n      if (!view.getComputeService().listHardwareProfiles().isEmpty()) {\n         Template template = view.getComputeService().templateBuilder().minRam(4096).build();\n         assertThat(AutomaticHardwareIdSpec.isAutomaticId(template.getHardware().getId())).isFalse();\n         assertThat(template.getHardware().getRam()).isGreaterThanOrEqualTo(4096);\n      }\n      else {\n         throw new SkipException(\"Hardware profile list is empty, this provider can not match any hardware profile\" +\n               \"to the specified minRam and minCores.\");\n      }\n   }\n\n   @Test(dataProvider = \"onlyIfAutomaticHardwareSupported\", groups = {\"integration\", \"live\"},\n         expectedExceptions = IllegalArgumentException.class,\n         expectedExceptionsMessageRegExp = \"No hardware profile matching the given criteria was found. \" +\n         \"If you want to use exact values, please set the minCores and minRam values\")\n   public void testAutoGeneratedHardwareWithOnlyMinRamNotMatchHardwareProfile() {\n      if (view.getComputeService().listHardwareProfiles().isEmpty()) {\n         view.getComputeService().templateBuilder().minRam(4096).build();\n      }\n      else {\n         throw new SkipException(\"Hardware profile list not empty.\");\n      }\n   }\n\n   @Test(dataProvider = \"onlyIfAutomaticHardwareSupported\", groups = {\"integration\", \"live\"},\n         expectedExceptions = IllegalArgumentException.class,\n         expectedExceptionsMessageRegExp = \"No hardware profile matching the given criteria was found. \" +\n               \"If you want to use exact values, please set the minCores and minRam values\")\n   public void testAutoGeneratedHardwareWithOnlyMinCoresNotMatchHardwareProfile() {\n      if (view.getComputeService().listHardwareProfiles().isEmpty()) {\n         view.getComputeService().templateBuilder().minCores(4).build();\n      }\n      else {\n         throw new SkipException(\"Hardware profile list not empty.\");\n      }\n   }\n\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/internal/FormatSharedNamesAndAppendUniqueStringToThoseWhichRepeatTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.internal;\n\nimport static org.jclouds.compute.config.ComputeServiceProperties.RESOURCENAME_DELIMITER;\nimport static org.jclouds.compute.config.ComputeServiceProperties.RESOURCENAME_PREFIX;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.predicates.Validator;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.name.Names;\n\n@Test(testName = \"FormatSharedNamesAndAppendUniqueStringToThoseWhichRepeatTest\")\npublic class FormatSharedNamesAndAppendUniqueStringToThoseWhichRepeatTest {\n   Validator<String> okValidator = new Validator<String>() {\n\n      @Override\n      public void validate(String t) throws IllegalArgumentException {\n\n      }\n\n   };\n\n   public void testSharedName() {\n      FormatSharedNamesAndAppendUniqueStringToThoseWhichRepeat fn = new FormatSharedNamesAndAppendUniqueStringToThoseWhichRepeat(\n            \"jclouds\", '_', Suppliers.ofInstance(\"123\"), okValidator);\n\n      assertEquals(fn.sharedNameForGroup(\"cluster\"), \"jclouds_cluster\");\n      assertEquals(fn.groupInSharedNameOrNull(\"jclouds_cluster\"), \"cluster\");\n      assertEquals(fn.groupInUniqueNameOrNull(\"jclouds_cluster\"), null);\n      assertTrue(fn.containsGroup(\"cluster\").apply(\"jclouds_cluster\"));\n   }\n\n   public void testOkToHaveDelimiterInGroupOnUniqueName() {\n      FormatSharedNamesAndAppendUniqueStringToThoseWhichRepeat fn = new FormatSharedNamesAndAppendUniqueStringToThoseWhichRepeat(\n            \"jclouds\", '_', Suppliers.ofInstance(\"123\"), okValidator);\n\n      assertEquals(fn.sharedNameForGroup(\"cluster_\"), \"jclouds_cluster_\");\n      assertEquals(fn.groupInSharedNameOrNull(\"jclouds_cluster_\"), \"cluster_\");\n      assertEquals(fn.groupInUniqueNameOrNull(\"jclouds_cluster_\"), null);\n      assertTrue(fn.containsGroup(\"cluster_\").apply(\"jclouds_cluster_\"));\n   }\n\n   public void testSharedNameWithHyphenInGroup() {\n      FormatSharedNamesAndAppendUniqueStringToThoseWhichRepeat fn = new FormatSharedNamesAndAppendUniqueStringToThoseWhichRepeat(\n            \"jclouds\", '_', Suppliers.ofInstance(\"123\"), okValidator);\n\n      assertEquals(fn.sharedNameForGroup(\"cluster-\"), \"jclouds_cluster-\");\n      assertEquals(fn.groupInSharedNameOrNull(\"jclouds_cluster-\"), \"cluster-\");\n      assertEquals(fn.groupInUniqueNameOrNull(\"jclouds_cluster-\"), null);\n      assertTrue(fn.containsGroup(\"cluster-\").apply(\"jclouds_cluster-\"));\n   }\n\n   public void testNextName() {\n      FormatSharedNamesAndAppendUniqueStringToThoseWhichRepeat fn = new FormatSharedNamesAndAppendUniqueStringToThoseWhichRepeat(\n            \"jclouds\", '_', Suppliers.ofInstance(\"123\"), okValidator);\n\n      assertEquals(fn.uniqueNameForGroup(\"cluster\"), \"jclouds_cluster_123\");\n      // note accidental treatment of a unique node as a shared one can lead to \n      // incorrect group names, as long as we permit delimiter to be in group name\n      assertEquals(fn.groupInSharedNameOrNull(\"jclouds_cluster_123\"), \"cluster_123\");\n      assertEquals(fn.groupInUniqueNameOrNull(\"jclouds_cluster_123\"), \"cluster\");\n      assertTrue(fn.containsGroup(\"cluster\").apply(\"jclouds_cluster_123\"));\n   }\n\n   public void testCannotFindSharedNameWhenDelimiterWrong() {\n      FormatSharedNamesAndAppendUniqueStringToThoseWhichRepeat fn = new FormatSharedNamesAndAppendUniqueStringToThoseWhichRepeat(\n            \"jclouds\", '_', Suppliers.ofInstance(\"123\"), okValidator);\n      assertEquals(fn.groupInSharedNameOrNull(\"jclouds#cluster\"), null);\n      assertEquals(fn.groupInUniqueNameOrNull(\"jclouds#cluster\"), null);\n      assertFalse(fn.containsGroup(\"cluster\").apply(\"jclouds#cluster\"));\n   }\n\n   public void testCannotFindNextNameWhenDelimiterWrong() {\n      FormatSharedNamesAndAppendUniqueStringToThoseWhichRepeat fn = new FormatSharedNamesAndAppendUniqueStringToThoseWhichRepeat(\n            \"jclouds\", '_', Suppliers.ofInstance(\"123\"), okValidator);\n      assertEquals(fn.groupInSharedNameOrNull(\"jclouds#cluster#123\"), null);\n      assertEquals(fn.groupInUniqueNameOrNull(\"jclouds#cluster#123\"), null);\n      assertFalse(fn.containsGroup(\"cluster\").apply(\"jclouds#cluster#123\"));\n   }\n\n   public void testPropertyChangesDelimiter() {\n      GroupNamingConvention fn = Guice.createInjector(new AbstractModule() {\n\n         @Override\n         protected void configure() {\n            bindConstant().annotatedWith(Names.named(RESOURCENAME_DELIMITER)).to('#');\n         }\n      }).getInstance(GroupNamingConvention.Factory.class).create();\n\n      assertEquals(fn.sharedNameForGroup(\"cluster\"), \"jclouds#cluster\");\n      assertEquals(fn.groupInSharedNameOrNull(\"jclouds#cluster\"), \"cluster\");\n      assertEquals(fn.groupInUniqueNameOrNull(\"jclouds#cluster\"), null);\n      assertTrue(fn.containsGroup(\"cluster\").apply(\"jclouds#cluster\"));\n   }\n\n   public void testPropertyChangesPrefix() {\n      GroupNamingConvention fn = Guice.createInjector(new AbstractModule() {\n\n         @Override\n         protected void configure() {\n            bindConstant().annotatedWith(Names.named(RESOURCENAME_PREFIX)).to(\"kclouds\");\n         }\n      }).getInstance(GroupNamingConvention.Factory.class).create();\n\n      assertEquals(fn.sharedNameForGroup(\"cluster\"), \"kclouds-cluster\");\n      assertEquals(fn.groupInSharedNameOrNull(\"kclouds-cluster\"), \"cluster\");\n      assertEquals(fn.groupInUniqueNameOrNull(\"kclouds-cluster\"), null);\n      assertTrue(fn.containsGroup(\"cluster\").apply(\"kclouds-cluster\"));\n\n   }\n\n   public void testCanChangeSuffixSupplier() {\n      GroupNamingConvention fn = Guice.createInjector(new AbstractModule() {\n\n         @Override\n         protected void configure() {\n            bind(new TypeLiteral<Supplier<String>>() {\n            }).toInstance(Suppliers.ofInstance(\"foo\"));\n         }\n      }).getInstance(GroupNamingConvention.Factory.class).create();\n\n      assertEquals(fn.uniqueNameForGroup(\"cluster\"), \"jclouds-cluster-foo\");\n      // note accidental treatment of a unique node as a shared one can lead to \n      // incorrect group names, as long as we permit delimiter to be in group name\n      assertEquals(fn.groupInSharedNameOrNull(\"jclouds-cluster-foo\"), \"cluster-foo\");\n      assertEquals(fn.groupInUniqueNameOrNull(\"jclouds-cluster-foo\"), \"cluster\");\n      assertTrue(fn.containsGroup(\"cluster\").apply(\"jclouds-cluster-foo\"));\n\n   }\n\n   // ///\n\n   public void testSharedNameNoPrefix() {\n      FormatSharedNamesAndAppendUniqueStringToThoseWhichRepeat fn = new FormatSharedNamesAndAppendUniqueStringToThoseWhichRepeat(\n            \"\", '_', Suppliers.ofInstance(\"123\"), okValidator);\n\n      assertEquals(fn.sharedNameForGroup(\"cluster\"), \"cluster\");\n      assertEquals(fn.groupInSharedNameOrNull(\"cluster\"), \"cluster\");\n      assertEquals(fn.groupInUniqueNameOrNull(\"cluster\"), null);\n      assertTrue(fn.containsGroup(\"cluster\").apply(\"cluster\"));\n   }\n\n   public void testNextNameNoPrefix() {\n      FormatSharedNamesAndAppendUniqueStringToThoseWhichRepeat fn = new FormatSharedNamesAndAppendUniqueStringToThoseWhichRepeat(\n            \"\", '_', Suppliers.ofInstance(\"123\"), okValidator);\n\n      assertEquals(fn.uniqueNameForGroup(\"cluster\"), \"cluster_123\");\n      assertEquals(fn.groupInSharedNameOrNull(\"cluster_123\"), \"cluster_123\");\n      assertEquals(fn.groupInUniqueNameOrNull(\"cluster_123\"), \"cluster\");\n      assertTrue(fn.containsGroup(\"cluster\").apply(\"cluster_123\"));\n   }\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/options/TemplateOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.options;\n\nimport com.google.common.collect.ImmutableSet;\nimport org.testng.annotations.Test;\n\nimport java.io.IOException;\nimport java.util.Set;\n\nimport static org.jclouds.compute.options.TemplateOptions.Builder.authorizePublicKey;\nimport static org.jclouds.compute.options.TemplateOptions.Builder.blockOnPort;\nimport static org.jclouds.compute.options.TemplateOptions.Builder.blockUntilRunning;\nimport static org.jclouds.compute.options.TemplateOptions.Builder.inboundPorts;\nimport static org.jclouds.compute.options.TemplateOptions.Builder.installPrivateKey;\nimport static org.jclouds.compute.options.TemplateOptions.Builder.networks;\nimport static org.jclouds.compute.options.TemplateOptions.Builder.nodeNames;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\n/**\n * Tests possible uses of TemplateOptions and TemplateOptions.Builder.*\n */\npublic class TemplateOptionsTest {\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testinstallPrivateKeyBadFormat() {\n      TemplateOptions options = new TemplateOptions();\n      options.installPrivateKey(\"whompy\");\n   }\n\n   @Test\n   public void testinstallPrivateKey() throws IOException {\n      TemplateOptions options = new TemplateOptions();\n      options.installPrivateKey(\"-----BEGIN RSA PRIVATE KEY-----\");\n      assertEquals(options.toString(), \"{privateKeyPresent=true}\");\n      assertEquals(options.getPrivateKey(), \"-----BEGIN RSA PRIVATE KEY-----\");\n   }\n\n   @Test\n   public void testNullinstallPrivateKey() {\n      TemplateOptions options = new TemplateOptions();\n      assertEquals(options.getPrivateKey(), null);\n   }\n\n   @Test\n   public void testinstallPrivateKeyStatic() throws IOException {\n      TemplateOptions options = installPrivateKey(\"-----BEGIN RSA PRIVATE KEY-----\");\n      assertEquals(options.getPrivateKey(), \"-----BEGIN RSA PRIVATE KEY-----\");\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testinstallPrivateKeyNPE() {\n      installPrivateKey((String) null);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testauthorizePublicKeyBadFormat() {\n      TemplateOptions options = new TemplateOptions();\n      options.authorizePublicKey(\"whompy\");\n   }\n\n   @Test\n   public void testauthorizePublicKey() throws IOException {\n      TemplateOptions options = new TemplateOptions();\n      options.authorizePublicKey(\"ssh-rsa\");\n      assertEquals(options.toString(), \"{publicKeyPresent=true}\");\n      assertEquals(options.getPublicKey(), \"ssh-rsa\");\n   }\n\n   @Test\n   public void testNullauthorizePublicKey() {\n      TemplateOptions options = new TemplateOptions();\n      assertEquals(options.getPublicKey(), null);\n   }\n\n   @Test\n   public void testauthorizePublicKeyStatic() throws IOException {\n      TemplateOptions options = authorizePublicKey(\"ssh-rsa\");\n      assertEquals(options.getPublicKey(), \"ssh-rsa\");\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testauthorizePublicKeyNPE() {\n      authorizePublicKey((String) null);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testblockOnPortBadFormat() {\n      TemplateOptions options = new TemplateOptions();\n      options.blockOnPort(-1, -1);\n   }\n\n   @Test\n   public void testblockOnPort() {\n      TemplateOptions options = new TemplateOptions();\n      options.blockOnPort(22, 30);\n      assertEquals(options.toString(), \"{blockOnPort:seconds=22:30}\");\n      assertEquals(options.getPort(), 22);\n      assertEquals(options.getSeconds(), 30);\n\n   }\n\n   @Test\n   public void testNullblockOnPort() {\n      TemplateOptions options = new TemplateOptions();\n      assertEquals(options.getPort(), -1);\n      assertEquals(options.getSeconds(), -1);\n   }\n\n   @Test\n   public void testblockOnPortStatic() {\n      TemplateOptions options = blockOnPort(22, 30);\n      assertEquals(options.getPort(), 22);\n      assertEquals(options.getSeconds(), 30);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testinboundPortsBadFormat() {\n      TemplateOptions options = new TemplateOptions();\n      options.inboundPorts(-1, -1);\n   }\n\n   @Test\n   public void testinboundPorts() {\n      TemplateOptions options = new TemplateOptions();\n      options.inboundPorts(22, 30);\n      assertEquals(options.getInboundPorts()[0], 22);\n      assertEquals(options.getInboundPorts()[1], 30);\n\n   }\n\n   @Test\n   public void testDefaultOpen22() {\n      TemplateOptions options = new TemplateOptions();\n      assertEquals(options.getInboundPorts()[0], 22);\n   }\n\n   @Test\n   public void testinboundPortsStatic() {\n      TemplateOptions options = inboundPorts(22, 30);\n      assertEquals(options.toString(), \"{inboundPorts=[22, 30]}\");\n      assertEquals(options.getInboundPorts()[0], 22);\n      assertEquals(options.getInboundPorts()[1], 30);\n   }\n\n   @Test\n   public void testblockUntilRunningDefault() {\n      TemplateOptions options = new TemplateOptions();\n      assertEquals(options.toString(), \"{}\");\n      assertEquals(options.shouldBlockUntilRunning(), true);\n   }\n\n   @Test\n   public void testblockUntilRunning() {\n      TemplateOptions options = new TemplateOptions();\n      options.blockUntilRunning(false);\n      assertEquals(options.toString(), \"{blockUntilRunning=false}\");\n      assertEquals(options.shouldBlockUntilRunning(), false);\n   }\n\n   @Test\n   public void testBlockUntilRunningUnsetsBlockOnPort() {\n      TemplateOptions options = new TemplateOptions();\n      options.blockOnPort(22, 30);\n      options.blockUntilRunning(false);\n      assertEquals(options.shouldBlockUntilRunning(), false);\n      assertEquals(options.getPort(), -1);\n      assertEquals(options.getSeconds(), -1);\n   }\n\n   @Test\n   public void testblockUntilRunningStatic() {\n      TemplateOptions options = blockUntilRunning(false);\n      assertEquals(options.shouldBlockUntilRunning(), false);\n   }\n\n   @Test\n   public void testNodeNames() {\n      Set<String> nodeNames = ImmutableSet.of(\"first-node\", \"second-node\");\n      TemplateOptions options = nodeNames(nodeNames);\n      assertTrue(options.getNodeNames().containsAll(nodeNames));\n   }\n\n   @Test\n   public void testNetworks() {\n      Set<String> networks = ImmutableSet.of(\"first-network\", \"second-network\");\n      TemplateOptions options = networks(networks);\n      assertTrue(options.getNetworks().containsAll(networks));\n   }\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/predicates/AtomicNodePredicatesTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.predicates;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\n\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport com.google.common.util.concurrent.Atomics;\n\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadataBuilder;\nimport org.jclouds.compute.domain.NodeMetadata.Status;\nimport org.jclouds.compute.strategy.GetNodeMetadataStrategy;\nimport org.jclouds.domain.LoginCredentials;\nimport org.testng.Assert;\nimport org.testng.annotations.BeforeMethod;\nimport org.testng.annotations.Test;\n\n/**\n * Tests possible uses of NodePredicates\n */\n@Test(singleThreaded = true, testName = \"AtomicNodePredicatesTest\")\npublic class AtomicNodePredicatesTest {\n\n   private NodeMetadata node;\n   private GetNodeMetadataStrategy computeService;\n\n   @Test\n   public void testNoUpdatesAtomicReferenceOnPass() {\n      NodeMetadata running = new NodeMetadataBuilder().id(\"myid\").status(Status.RUNNING).build();\n      GetNodeMetadataStrategy computeService = createMock(GetNodeMetadataStrategy.class);\n\n      replay(computeService);\n\n      AtomicNodeRunning nodeRunning = new AtomicNodeRunning(computeService);\n      AtomicReference<NodeMetadata> reference = Atomics.newReference(running);\n      Assert.assertTrue(nodeRunning.apply(reference));\n      Assert.assertEquals(reference.get(), running);\n\n      verify(computeService);\n\n   }\n\n   @Test\n   public void testRefreshUpdatesAtomicReferenceOnRecheckPending() {\n      NodeMetadata pending = new NodeMetadataBuilder().id(\"myid\").status(Status.PENDING).build();\n      GetNodeMetadataStrategy computeService = createMock(GetNodeMetadataStrategy.class);\n\n      expect(computeService.getNode(\"myid\")).andReturn(pending);\n\n      replay(computeService);\n\n      AtomicNodeRunning nodeRunning = new AtomicNodeRunning(computeService);\n      AtomicReference<NodeMetadata> reference = Atomics.newReference(pending);\n      Assert.assertFalse(nodeRunning.apply(reference));\n      Assert.assertEquals(reference.get(), pending);\n\n      verify(computeService);\n\n   }\n\n   @Test\n   public void testRefreshUpdatesAtomicReferenceOnRecheckPendingAcceptsNewCredentials() {\n      LoginCredentials creds = LoginCredentials.builder().user(\"user\").password(\"password\").build();\n      NodeMetadata newNode = new NodeMetadataBuilder().id(\"myid\").status(Status.UNRECOGNIZED).credentials(creds).build();\n\n      LoginCredentials creds2 = LoginCredentials.builder().user(\"user\").password(\"password2\").build();\n\n      NodeMetadata pending = new NodeMetadataBuilder().id(\"myid\").status(Status.PENDING).credentials(creds2).build();\n      \n      GetNodeMetadataStrategy computeService = createMock(GetNodeMetadataStrategy.class);\n\n      expect(computeService.getNode(\"myid\")).andReturn(pending);\n\n      replay(computeService);\n\n      AtomicNodeRunning nodeRunning = new AtomicNodeRunning(computeService);\n      AtomicReference<NodeMetadata> reference = Atomics.newReference(newNode);\n      Assert.assertFalse(nodeRunning.apply(reference));\n      Assert.assertEquals(reference.get(), pending);\n\n      verify(computeService);\n   }\n   \n   @Test\n   public void testRefreshUpdatesAtomicReferenceOnRecheckRunning() {\n      NodeMetadata running = new NodeMetadataBuilder().id(\"myid\").status(Status.RUNNING).build();\n      NodeMetadata pending = new NodeMetadataBuilder().id(\"myid\").status(Status.PENDING).build();\n      GetNodeMetadataStrategy computeService = createMock(GetNodeMetadataStrategy.class);\n\n      expect(computeService.getNode(\"myid\")).andReturn(running);\n\n      replay(computeService);\n\n      AtomicNodeRunning nodeRunning = new AtomicNodeRunning(computeService);\n      AtomicReference<NodeMetadata> reference = Atomics.newReference(pending);\n      Assert.assertTrue(nodeRunning.apply(reference));\n      Assert.assertEquals(reference.get(), running);\n\n      verify(computeService);\n\n   }\n\n   @BeforeMethod\n   public void setUp() throws Exception {\n      node = createMock(NodeMetadata.class);\n      computeService = createMock(GetNodeMetadataStrategy.class);\n\n      expect(node.getId()).andReturn(\"myid\").anyTimes();\n      expect(computeService.getNode(\"myid\")).andReturn(node).anyTimes();\n      expect(node.getLocation()).andReturn(null).anyTimes();\n   }\n\n   @Test\n   public void testNodeRunningReturnsTrueWhenRunning() {\n      expect(node.getStatus()).andReturn(Status.RUNNING).atLeastOnce();\n      expect(node.getBackendStatus()).andReturn(null).atLeastOnce();\n      replay(node, computeService);\n\n      AtomicNodeRunning nodeRunning = new AtomicNodeRunning(computeService);\n      AtomicReference<NodeMetadata> reference = Atomics.newReference(node);\n      Assert.assertTrue(nodeRunning.apply(reference));\n      Assert.assertEquals(reference.get(), node);\n   }\n   \n   @Test\n   public void testNodeSuspendedReturnsTrueWhenSuspended() {\n      expect(node.getStatus()).andReturn(Status.SUSPENDED).atLeastOnce();\n      expect(node.getBackendStatus()).andReturn(null).atLeastOnce();\n      replay(node, computeService);\n\n      AtomicNodeSuspended nodeSuspended = new AtomicNodeSuspended(computeService);\n      AtomicReference<NodeMetadata> reference = Atomics.newReference(node);\n      Assert.assertTrue(nodeSuspended.apply(reference));\n      Assert.assertEquals(reference.get(), node);\n   }\n\n   @Test(expectedExceptions = IllegalStateException.class)\n   public void testNodeRunningFailsOnTerminated() {\n      expect(node.getStatus()).andReturn(Status.TERMINATED).atLeastOnce();\n      expect(node.getBackendStatus()).andReturn(null).atLeastOnce();\n      replay(node, computeService);\n\n      AtomicNodeRunning nodeRunning = new AtomicNodeRunning(computeService);\n      AtomicReference<NodeMetadata> reference = Atomics.newReference(node);\n      nodeRunning.apply(reference);\n      Assert.assertEquals(reference.get(), node);\n   }\n\n   @Test(expectedExceptions = IllegalStateException.class)\n   public void testNodeRunningFailsOnError() {\n      expect(node.getStatus()).andReturn(Status.ERROR).atLeastOnce();\n      expect(node.getBackendStatus()).andReturn(null).atLeastOnce();\n      replay(node, computeService);\n\n      AtomicNodeRunning nodeRunning = new AtomicNodeRunning(computeService);\n      AtomicReference<NodeMetadata> reference = Atomics.newReference(node);\n      nodeRunning.apply(reference);\n      Assert.assertEquals(reference.get(), node);\n   }\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/predicates/HardwarePredicatesTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.predicates;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.compute.ComputeService;\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.compute.domain.Hardware;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Iterables;\n\n@Test\npublic class HardwarePredicatesTest {\n   ComputeService computeService = ContextBuilder.newBuilder(\"stub\").build(ComputeServiceContext.class).getComputeService();\n\n   public void testHardwareId() {\n      Hardware first = Iterables.get(computeService.listHardwareProfiles(), 0);\n      assert HardwarePredicates.idEquals(first.getId()).apply(first);\n      Hardware second = Iterables.get(computeService.listHardwareProfiles(), 1);\n      assert !HardwarePredicates.idEquals(first.getId()).apply(second);\n   }\n\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/predicates/ImagePredicatesTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.predicates;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.compute.ComputeService;\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.ImageBuilder;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\n\n@Test\npublic class ImagePredicatesTest {\n   ComputeService computeService = ContextBuilder.newBuilder(\"stub\").build(ComputeServiceContext.class).getComputeService();\n\n   public void testImageId() {\n      Image first = Iterables.get(computeService.listImages(), 0);\n      assert ImagePredicates.idEquals(first.getId()).apply(first);\n      Image second = Iterables.get(computeService.listImages(), 1);\n      assert !ImagePredicates.idEquals(first.getId()).apply(second);\n   }\n\n   public void testUserMetadataContains() {\n      Image first = Iterables.get(computeService.listImages(), 0);\n      first = ImageBuilder.fromImage(first).userMetadata(ImmutableMap.of(\"foo\", \"bar\")).build();\n      assert ImagePredicates.userMetadataContains(\"foo\", \"bar\").apply(first);\n      Image second = Iterables.get(computeService.listImages(), 1);\n      second = ImageBuilder.fromImage(second).userMetadata(ImmutableMap.of(\"foo\", \"baz\")).build();\n      assert !ImagePredicates.userMetadataContains(\"foo\", \"bar\").apply(second);\n   }\n\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/predicates/OperatingSystemPredicatesTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.predicates;\n\nimport static org.jclouds.compute.predicates.OperatingSystemPredicates.supportsApt;\nimport static org.jclouds.compute.predicates.OperatingSystemPredicates.supportsYum;\nimport static org.jclouds.compute.predicates.OperatingSystemPredicates.supportsZypper;\n\nimport org.jclouds.cim.OSType;\nimport org.jclouds.compute.domain.CIMOperatingSystem;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.testng.annotations.Test;\n\n/**\n * Tests possible uses of OperatingSystemPredicates\n */\n@Test\npublic class OperatingSystemPredicatesTest {\n\n   public void testCIMCENTOSDoesntSupportApt() {\n      assert !supportsApt().apply(new CIMOperatingSystem(OSType.CENTOS, \"\", null, \"description\"));\n      assert !supportsApt().apply(new CIMOperatingSystem(OSType.CENTOS_64, \"\", null, \"description\"));\n   }\n\n   public void testCIMRHELDoesntSupportApt() {\n      assert !supportsApt().apply(new CIMOperatingSystem(OSType.RHEL, \"\", null, \"description\"));\n      assert !supportsApt().apply(new CIMOperatingSystem(OSType.RHEL_64, \"\", null, \"description\"));\n   }\n\n   public void testCIMDEBIANSupportsApt() {\n      assert supportsApt().apply(new CIMOperatingSystem(OSType.DEBIAN, \"\", null, \"description\"));\n      assert supportsApt().apply(new CIMOperatingSystem(OSType.DEBIAN_64, \"\", null, \"description\"));\n   }\n\n   public void testCIMUBUNTUSupportsApt() {\n      assert supportsApt().apply(new CIMOperatingSystem(OSType.UBUNTU, \"\", null, \"description\"));\n      assert supportsApt().apply(new CIMOperatingSystem(OSType.UBUNTU_64, \"\", null, \"description\"));\n   }\n\n   public void testUbuntuNameSupportsApt() {\n      assert supportsApt().apply(new OperatingSystem(null, \"Ubuntu\", \"\", null, \"description\", false));\n   }\n\n   public void testCIMCENTOSSupportsYum() {\n      assert supportsYum().apply(new CIMOperatingSystem(OSType.CENTOS, \"\", null, \"description\"));\n      assert supportsYum().apply(new CIMOperatingSystem(OSType.CENTOS_64, \"\", null, \"description\"));\n   }\n\n   public void testCIMRHELSupportsYum() {\n      assert supportsYum().apply(new CIMOperatingSystem(OSType.RHEL, \"\", null, \"description\"));\n      assert supportsYum().apply(new CIMOperatingSystem(OSType.RHEL_64, \"\", null, \"description\"));\n   }\n\n   public void testCIMDEBIANDoesntSupportYum() {\n      assert !supportsYum().apply(new CIMOperatingSystem(OSType.DEBIAN, \"\", null, \"description\"));\n      assert !supportsYum().apply(new CIMOperatingSystem(OSType.DEBIAN_64, \"\", null, \"description\"));\n   }\n\n   public void testCIMUBUNTUDoesntSupportYum() {\n      assert !supportsYum().apply(new CIMOperatingSystem(OSType.UBUNTU, \"\", null, \"description\"));\n      assert !supportsYum().apply(new CIMOperatingSystem(OSType.UBUNTU_64, \"\", null, \"description\"));\n   }\n\n   public void testSuseTypeSupportsZypper() {\n      assert supportsZypper().apply(new OperatingSystem(OsFamily.SUSE, null, \"\", null, \"description\", false));\n   }\n\n   public void testSuseDescriptionSupportsZypper() {\n      assert supportsZypper().apply(new OperatingSystem(null, \"\", null, null, \"Suse\", false));\n   }\n\n   public void testSuseNameSupportsZypper() {\n      assert supportsZypper().apply(new OperatingSystem(null, \"Suse\", \"\", null, \"description\", false));\n   }\n\n   public void testCentosTypeSupportsYum() {\n      assert supportsYum().apply(new OperatingSystem(OsFamily.CENTOS, null, \"\", null, \"description\", false));\n   }\n\n   public void testAmzTypeSupportsYum() {\n      assert supportsYum().apply(new OperatingSystem(OsFamily.AMZN_LINUX, null, \"\", null, \"description\", false));\n   }\n\n   public void testRhelTypeSupportsYum() {\n      assert supportsYum().apply(new OperatingSystem(OsFamily.RHEL, null, \"\", null, \"description\", false));\n   }\n\n   public void testFedoraTypeSupportsYum() {\n      assert supportsYum().apply(new OperatingSystem(OsFamily.FEDORA, null, \"\", null, \"description\", false));\n   }\n\n   public void testCentosNameSupportsYum() {\n      assert supportsYum().apply(new OperatingSystem(null, \"Centos\", \"\", null, \"description\", false));\n   }\n\n   public void testRhelNameSupportsYum() {\n      assert supportsYum().apply(new OperatingSystem(null, \"RHEL\", \"\", null, \"description\", false));\n   }\n\n   public void testFedoraNameSupportsYum() {\n      assert supportsYum().apply(new OperatingSystem(null, \"Fedora\", \"\", null, \"description\", false));\n   }\n\n   public void testRedHatEnterpriseLinuxNameSupportsYum() {\n      assert supportsYum().apply(new OperatingSystem(null, \"Red Hat Enterprise Linux\", \"\", null, \"description\", false));\n   }\n\n   public void testCentosDescriptionSupportsYum() {\n      assert supportsYum().apply(new OperatingSystem(null, \"\", null, null, \"Centos\", false));\n   }\n\n   public void testRhelDescriptionSupportsYum() {\n      assert supportsYum().apply(new OperatingSystem(null, \"\", null, null, \"RHEL\", false));\n   }\n\n   public void testFedoraDescriptionSupportsYum() {\n      assert supportsYum().apply(new OperatingSystem(null, \"\", null, null, \"Fedora\", false));\n   }\n\n   public void testRedHatEnterpriseLinuxDescriptionSupportsYum() {\n      assert supportsYum().apply(new OperatingSystem(null, \"\", null, null, \"Red Hat Enterprise Linux\", false));\n   }\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/predicates/SocketOpenPredicates.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.predicates;\n\nimport org.jclouds.predicates.SocketOpen;\n\nimport com.google.common.net.HostAndPort;\n\n\n/**\n * For use in unit tests.\n */\npublic class SocketOpenPredicates {\n\n    public static final SocketOpen alwaysSucceed = new SocketOpen() {\n        @Override public boolean apply(HostAndPort socket) { return true; }\n    };\n\n    public static final SocketOpen alwaysFail = new SocketOpen() {\n        @Override public boolean apply(HostAndPort socket) { return false; }\n    };\n\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/strategy/CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.strategy;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Map;\nimport java.util.NoSuchElementException;\nimport java.util.Set;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport org.jclouds.compute.config.CustomizationResponse;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadata.Status;\nimport org.jclouds.compute.domain.NodeMetadataBuilder;\nimport org.jclouds.compute.functions.InstallKeysAndRunScript;\nimport org.jclouds.compute.functions.NodeAndTemplateOptionsToStatement;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.compute.util.OpenSocketFinder;\nimport org.jclouds.scriptbuilder.domain.Statement;\nimport org.testng.Assert;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.LinkedHashMultimap;\nimport com.google.common.collect.Maps;\nimport com.google.common.collect.Multimap;\nimport com.google.common.collect.Sets;\nimport com.google.common.util.concurrent.Atomics;\n\n@Test(groups = \"unit\", testName = \"CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapTest\")\npublic class CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapTest {\n\n   public void testBreakOnIllegalStateExceptionDuringPollNode() {\n      InitializeRunScriptOnNodeOrPlaceInBadMap.Factory initScriptRunnerFactory = createMock(InitializeRunScriptOnNodeOrPlaceInBadMap.Factory.class);\n      OpenSocketFinder openSocketFinder = createMock(OpenSocketFinder.class);\n      NodeAndTemplateOptionsToStatement nodeAndTemplateOptionsToStatement = new InstallKeysAndRunScript();\n      @SuppressWarnings(\"unused\")\n      Statement statement = null;\n      TemplateOptions options = new TemplateOptions();\n      Set<NodeMetadata> goodNodes = Sets.newLinkedHashSet();\n      Map<NodeMetadata, Exception> badNodes = Maps.newLinkedHashMap();\n      Multimap<NodeMetadata, CustomizationResponse> customizationResponses = LinkedHashMultimap.create();\n\n      final NodeMetadata pendingNode = new NodeMetadataBuilder().ids(\"id\").status(Status.PENDING).build();\n\n      // node always stays pending\n      Function<AtomicReference<NodeMetadata>, AtomicReference<NodeMetadata>> pollNodeRunning = new Function<AtomicReference<NodeMetadata>, AtomicReference<NodeMetadata>>() {\n\n         @Override\n         public AtomicReference<NodeMetadata> apply(AtomicReference<NodeMetadata> node) {\n            Assert.assertEquals(node.get(), pendingNode);\n            throw new IllegalStateException(\"bad state!\");\n         }\n\n      };\n\n      // replay mocks\n      replay(initScriptRunnerFactory, openSocketFinder);\n      // run\n      AtomicReference<NodeMetadata> atomicNode = Atomics.newReference(pendingNode);\n      new CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap(pollNodeRunning, openSocketFinder,\n            nodeAndTemplateOptionsToStatement, initScriptRunnerFactory, options, atomicNode, goodNodes, badNodes,\n            customizationResponses).apply(atomicNode);\n\n      assertEquals(goodNodes.size(), 0);\n      assertEquals(badNodes.keySet(), ImmutableSet.of(pendingNode));\n      assertEquals(badNodes.get(pendingNode).getMessage(), \"bad state!\");\n      assertEquals(customizationResponses.size(), 0);\n\n      // verify mocks\n      verify(initScriptRunnerFactory, openSocketFinder);\n   }\n\n   public void testBreakGraceWhenNodeSocketFailsToOpen() {\n      int portTimeoutSecs = 2;\n      InitializeRunScriptOnNodeOrPlaceInBadMap.Factory initScriptRunnerFactory = createMock(InitializeRunScriptOnNodeOrPlaceInBadMap.Factory.class);\n      OpenSocketFinder openSocketFinder = createMock(OpenSocketFinder.class);\n      NodeAndTemplateOptionsToStatement nodeAndTemplateOptionsToStatement = new InstallKeysAndRunScript();\n      TemplateOptions options = new TemplateOptions().blockOnPort(22, portTimeoutSecs);\n      Set<NodeMetadata> goodNodes = Sets.newLinkedHashSet();\n      Map<NodeMetadata, Exception> badNodes = Maps.newLinkedHashMap();\n      Multimap<NodeMetadata, CustomizationResponse> customizationResponses = LinkedHashMultimap.create();\n\n      final NodeMetadata pendingNode = new NodeMetadataBuilder().ids(\"id\").status(Status.PENDING).build();\n      final NodeMetadata runningNode = new NodeMetadataBuilder().ids(\"id\").status(Status.RUNNING).build();\n\n      expect(openSocketFinder.findOpenSocketOnNode(runningNode, 22, portTimeoutSecs, TimeUnit.SECONDS)).andThrow(\n            new NoSuchElementException(\"could not connect to any ip address port\")).once();\n\n      Function<AtomicReference<NodeMetadata>, AtomicReference<NodeMetadata>> pollNodeRunning = new Function<AtomicReference<NodeMetadata>, AtomicReference<NodeMetadata>>() {\n\n         @Override\n         public AtomicReference<NodeMetadata> apply(AtomicReference<NodeMetadata> node) {\n            Assert.assertEquals(node.get(), pendingNode);\n            node.set(runningNode);\n            return node;\n         }\n\n      };\n\n      // replay mocks\n      replay(initScriptRunnerFactory, openSocketFinder);\n\n      // run\n      AtomicReference<NodeMetadata> atomicNode = Atomics.newReference(pendingNode);\n      new CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap(pollNodeRunning, openSocketFinder,\n            nodeAndTemplateOptionsToStatement, initScriptRunnerFactory, options, atomicNode, goodNodes, badNodes,\n            customizationResponses).apply(atomicNode);\n\n      assertEquals(goodNodes.size(), 0);\n      assertEquals(badNodes.keySet(), ImmutableSet.of(pendingNode));\n      badNodes.get(pendingNode).printStackTrace();\n      assertEquals(badNodes.get(pendingNode).getMessage(), \"could not connect to any ip address port\");\n      assertEquals(customizationResponses.size(), 0);\n\n      // verify mocks\n      verify(initScriptRunnerFactory, openSocketFinder);\n   }\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/strategy/PrioritizeCredentialsFromTemplateTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.strategy;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.functions.DefaultCredentialsFromImageOrOverridingCredentials;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.domain.LoginCredentials;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"PrioritizeCredentialsFromTemplateTest\")\npublic class PrioritizeCredentialsFromTemplateTest {\n   private static final PrioritizeCredentialsFromTemplate fn = new PrioritizeCredentialsFromTemplate(\n         new DefaultCredentialsFromImageOrOverridingCredentials());\n\n   public void testWhenCredentialsNotPresentInImageTemplateOptionsOrParameterReturnNull() {\n      Credentials expected = null;\n\n      Image image = createMock(Image.class);\n      Template template = createMock(Template.class);\n\n      expect(template.getImage()).andReturn(image);\n      expect(image.getDefaultCredentials()).andReturn(null);\n      expect(template.getOptions()).andReturn(new TemplateOptions());\n\n      replay(template, image);\n\n      assertEquals(fn.apply(template, null), expected);\n\n      verify(template);\n      verify(image);\n   }\n   \n   public void testWhenCredentialsNotPresentInImageTemplateOptionsReturnsFromParameter() {\n      LoginCredentials expected = LoginCredentials.builder().user(\"foo\").password(\"bar\").build();\n\n      Image image = createMock(Image.class);\n      Template template = createMock(Template.class);\n\n      expect(template.getImage()).andReturn(image);\n      expect(image.getDefaultCredentials()).andReturn(null);\n      expect(template.getOptions()).andReturn(new TemplateOptions());\n\n      replay(template, image);\n\n      assertEquals(fn.apply(template, expected), expected);\n\n      verify(template);\n      verify(image);\n   }\n   \n   public void testWhenCredentialsNotPresentInImageReturnsOneInTemplateOptionsAndNotParameter() {\n      LoginCredentials expected = LoginCredentials.builder().user(\"ubuntu\").password(\"password\").build();\n\n      Image image = createMock(Image.class);\n      Template template = createMock(Template.class);\n\n      expect(template.getImage()).andReturn(image);\n      expect(image.getDefaultCredentials()).andReturn(null);\n      expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginCredentials(expected));\n\n      replay(template, image);\n\n      assertEquals(fn.apply(template, LoginCredentials.builder().user(\"foo\").password(\"bar\").build()), expected);\n\n      verify(template);\n      verify(image);\n   }\n   \n   public void testWhenCredentialsNotPresentInImageReturnsCredentialFromTemplateOptionsAndUserFromParameter() {\n      Credentials expected = new Credentials(\"ubuntu\", \"password\");\n\n      Image image = createMock(Image.class);\n      Template template = createMock(Template.class);\n\n      expect(template.getImage()).andReturn(image);\n      expect(image.getDefaultCredentials()).andReturn(null);\n      expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginUser(\"ubuntu\"));\n\n      replay(template, image);\n\n      assertEquals(fn.apply(template, LoginCredentials.builder().user(\"foo\").password(\"password\").build()), expected);\n\n      verify(template);\n      verify(image);\n   }\n   \n   public void testWhenCredentialsNotPresentInTemplateOptionsReturnsOneInImageAndNotParameter() {\n      LoginCredentials expected = LoginCredentials.builder().user(\"ubuntu\").password(\"password\").build();\n\n      Image image = createMock(Image.class);\n      Template template = createMock(Template.class);\n\n      expect(template.getImage()).andReturn(image);\n      expect(image.getDefaultCredentials()).andReturn(expected);\n      expect(template.getOptions()).andReturn(new TemplateOptions());\n\n      replay(template, image);\n\n      assertEquals(fn.apply(template, LoginCredentials.builder().user(\"foo\").password(\"bar\").build()), expected);\n\n      verify(template);\n      verify(image);\n   }\n   \n   public void testWhenCredentialsPresentInImageOverridesIdentityFromCredentialsInTemplateOptionsAndNotParameter() {\n      Credentials expected = new Credentials(\"ubuntu\", \"password\");\n\n      Image image = createMock(Image.class);\n      Template template = createMock(Template.class);\n\n      expect(template.getImage()).andReturn(image);\n      expect(image.getDefaultCredentials()).andReturn(LoginCredentials.builder().user(\"ubuntu\").password(\"password\").build());\n      expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginUser(\"ubuntu\"));\n\n      replay(template, image);\n\n      assertEquals(fn.apply(template, LoginCredentials.builder().user(\"foo\").password(\"bar\").build()), expected);\n\n      verify(template, image);\n   }\n   \n   public void testWhenCredentialsPresentInImageOverridesCredentialFromCredentialsInTemplateOptionsAndNotParameter() {\n      LoginCredentials expected = LoginCredentials.builder().user(\"ubuntu\").password(\"password\").build();\n\n      Image image = createMock(Image.class);\n      Template template = createMock(Template.class);\n\n      expect(template.getImage()).andReturn(image);\n      expect(image.getDefaultCredentials()).andReturn(LoginCredentials.builder().user(\"ubuntu\").password(\"password2\").build());\n      expect(template.getOptions()).andReturn(TemplateOptions.Builder.overrideLoginPassword(\"password\"));\n\n      replay(template, image);\n\n      assertEquals(fn.apply(template, LoginCredentials.builder().user(\"foo\").password(\"bar\").build()), expected);\n\n      verify(template);\n      verify(image);\n   }\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/strategy/impl/ReturnCredentialsBoundToImageTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.strategy.impl;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.domain.LoginCredentials;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\n\n@Test(groups = \"unit\", testName = \"ReturnCredentialsBoundToImageTest\")\npublic class ReturnCredentialsBoundToImageTest {\n   LoginCredentials creds = LoginCredentials.builder().user(\"ubuntu\").password(\"foo\").build();\n\n   public void testDefaultIsToReturnConfiguredCredential() {\n      Image image = createMock(Image.class);\n      replay(image);\n\n      assertEquals(new ReturnCredentialsBoundToImage(creds, ImmutableMap.<String, Credentials> of(), ImmutableMap\n               .<OsFamily, LoginCredentials> of()).apply(image), creds);\n\n      verify(image);\n\n   }\n\n   public void testDefaultIsToReturnConfiguredCredentialInStore() {\n      Image image = createMock(Image.class);\n      expect(image.getId()).andReturn(\"1\").times(2);\n      replay(image);\n\n      assertEquals(new ReturnCredentialsBoundToImage(null, ImmutableMap.<String, Credentials> of(\"image#1\", creds),\n               ImmutableMap.<OsFamily, LoginCredentials> of()).apply(image), creds);\n\n      verify(image);\n\n   }\n\n   public void testReturnLoginCredentialAssociatedToOsFamily() {\n      Image image = createMock(Image.class);\n      expect(image.getId()).andReturn(\"1\");\n      expect(image.getOperatingSystem()).andReturn(\n               OperatingSystem.builder().family(OsFamily.WINDOWS).description(\"foo\").build()).atLeastOnce();\n      replay(image);\n\n      Credentials creds = new Credentials(\"Administrator\", null);\n      assertEquals(new ReturnCredentialsBoundToImage(null, ImmutableMap.<String, Credentials> of(), ImmutableMap.of(\n               OsFamily.WINDOWS, LoginCredentials.builder().user(\"Administrator\").build())).apply(image), creds);\n\n      verify(image);\n\n   }\n\n   public void testReturnRootWhenNotOnWindows() {\n      Image image = createMock(Image.class);\n      expect(image.getId()).andReturn(\"1\");\n      expect(image.getOperatingSystem()).andReturn(\n               OperatingSystem.builder().family(OsFamily.LINUX).description(\"foo\").build()).atLeastOnce();\n      replay(image);\n\n      Credentials creds = new Credentials(\"root\", null);\n      assertEquals(new ReturnCredentialsBoundToImage(null, ImmutableMap.<String, Credentials> of(), ImmutableMap\n               .<OsFamily, LoginCredentials> of()).apply(image), creds);\n\n      verify(image);\n\n   }\n\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/stub/StubApiMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.stub;\n\nimport org.jclouds.compute.internal.BaseComputeServiceApiMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"StubApiMetadataTest\")\npublic class StubApiMetadataTest extends BaseComputeServiceApiMetadataTest {\n\n   public StubApiMetadataTest() {\n      super(new StubApiMetadata());\n   }\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/stub/extensions/StubSecurityGroupExtensionIntegrationTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.stub.extensions;\n\nimport java.util.Properties;\n\nimport org.jclouds.compute.extensions.internal.BaseSecurityGroupExtensionLiveTest;\nimport org.testng.annotations.Test;\n\n\n/**\n * Base test for {@link SecurityGroupExtension} implementations.\n */\n@Test(groups = { \"integration\", \"live\" }, singleThreaded = true, testName = \"StubSecurityGroupExtensionIntegrationTest\")\npublic class StubSecurityGroupExtensionIntegrationTest extends BaseSecurityGroupExtensionLiveTest {\n\n   public StubSecurityGroupExtensionIntegrationTest() {\n      provider = \"stub\";\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties overrides = super.setupProperties();\n      // This is a hack to make sure we get a different set of node IDs, nodes, groups, etc from StubComputeServiceIntegrationTest.\n      overrides.setProperty(provider + \".identity\", \"sec-stub\");\n\n      return overrides;\n   }\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/suppliers/ImageCacheSupplierTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.suppliers;\n\nimport static com.google.common.collect.Iterables.any;\nimport static org.jclouds.compute.predicates.ImagePredicates.idEquals;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\nimport java.util.concurrent.TimeUnit;\n\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.ImageBuilder;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.strategy.GetImageStrategy;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.rest.AuthorizationException;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.util.concurrent.Atomics;\nimport com.google.common.util.concurrent.Uninterruptibles;\nimport com.google.inject.util.Providers;\n\n/**\n * Unit tests for the {@link ImageCacheSupplier} class.\n */\n@Test(groups = \"unit\", testName = \"ImageCacheSupplierTest\")\npublic class ImageCacheSupplierTest {\n\n   private Location location = new LocationBuilder().scope(LocationScope.PROVIDER).id(\"location\")\n         .description(\"location\").build();\n\n   private OperatingSystem os = OperatingSystem.builder().name(\"osName\").version(\"osVersion\")\n         .description(\"osDescription\").arch(\"X86_32\").build();\n\n   private Image image = new ImageBuilder().id(\"imageId\").providerId(\"imageId\").name(\"imageName\")\n         .description(\"imageDescription\").version(\"imageVersion\").operatingSystem(os).status(Image.Status.AVAILABLE)\n         .location(location).build();\n\n   private Set<? extends Image> images = ImmutableSet.of(image);\n\n   private GetImageStrategy getImageStrategy = new GetImageStrategy() {\n      @Override\n      public Image getImage(String id) {\n         return new ImageBuilder().id(id).providerId(id).name(\"imageName-\" + id).description(\"imageDescription\")\n               .version(\"imageVersion\").operatingSystem(os).status(Image.Status.AVAILABLE).location(location).build();\n      }\n   };\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testRegisterNullImageIsNotAllowed() {\n      ImageCacheSupplier imageCache = new ImageCacheSupplier(Suppliers.<Set<? extends Image>> ofInstance(images), 60,\n            Atomics.<AuthorizationException> newReference(), Providers.of(getImageStrategy));\n      imageCache.registerImage(null);\n   }\n\n   @Test\n   public void testRegisterImageIgnoresDuplicates() {\n      ImageCacheSupplier imageCache = new ImageCacheSupplier(Suppliers.<Set<? extends Image>> ofInstance(images), 60,\n            Atomics.<AuthorizationException> newReference(), Providers.of(getImageStrategy));\n      assertEquals(imageCache.get().size(), 1);\n\n      imageCache.registerImage(image);\n\n      assertEquals(imageCache.get().size(), 1);\n   }\n\n   @Test\n   public void testRegisterNewImage() {\n      ImageCacheSupplier imageCache = new ImageCacheSupplier(Suppliers.<Set<? extends Image>> ofInstance(images), 60,\n            Atomics.<AuthorizationException> newReference(), Providers.of(getImageStrategy));\n      assertEquals(imageCache.get().size(), 1);\n\n      imageCache.registerImage(ImageBuilder.fromImage(image).id(\"newimage\").build());\n\n      assertEquals(imageCache.get().size(), 2);\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testRemoveNullImageIsNotAllowed() {\n      ImageCacheSupplier imageCache = new ImageCacheSupplier(Suppliers.<Set<? extends Image>> ofInstance(images), 60,\n            Atomics.<AuthorizationException> newReference(), Providers.of(getImageStrategy));\n      imageCache.removeImage(null);\n   }\n\n   @Test\n   public void testRemoveImage() {\n      ImageCacheSupplier imageCache = new ImageCacheSupplier(Suppliers.<Set<? extends Image>> ofInstance(images), 60,\n            Atomics.<AuthorizationException> newReference(), Providers.of(getImageStrategy));\n      assertEquals(imageCache.get().size(), 1);\n\n      imageCache.removeImage(image.getId());\n\n      assertEquals(imageCache.get().size(), 0);\n   }\n\n   @Test\n   public void testLoadImage() {\n      ImageCacheSupplier imageCache = new ImageCacheSupplier(Suppliers.<Set<? extends Image>> ofInstance(images), 60,\n            Atomics.<AuthorizationException> newReference(), Providers.of(getImageStrategy));\n      assertEquals(imageCache.get().size(), 1);\n\n      Optional<? extends Image> image = imageCache.get(\"foo\");\n\n      assertTrue(image.isPresent());\n      assertEquals(image.get().getName(), \"imageName-foo\");\n      assertEquals(imageCache.get().size(), 2);\n   }\n\n   @Test\n   public void testSupplierExpirationReloadsTheCache() {\n      ImageCacheSupplier imageCache = new ImageCacheSupplier(Suppliers.<Set<? extends Image>> ofInstance(images), 3,\n            Atomics.<AuthorizationException> newReference(), Providers.of(getImageStrategy));\n      assertEquals(imageCache.get().size(), 1);\n\n      Optional<? extends Image> image = imageCache.get(\"foo\");\n\n      // Load an image into the cache\n      assertTrue(image.isPresent());\n      assertEquals(image.get().getName(), \"imageName-foo\");\n      assertEquals(imageCache.get().size(), 2);\n\n      // Once the supplier expires, reloading it will load the initial values\n      // (it is a hardcoded supplier), so the just loaded image should be gone\n      Uninterruptibles.sleepUninterruptibly(4, TimeUnit.SECONDS);\n      assertEquals(imageCache.get().size(), 1);\n      assertFalse(any(imageCache.get(), idEquals(\"foo\")));\n   }\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/util/AutomaticHardwareIdSpecTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.util;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\n\nimport static org.assertj.core.api.Assertions.assertThat;\n\n@Test(groups = \"unit\", testName = \"AutomaticHardwareIdSpecTest\")\npublic class AutomaticHardwareIdSpecTest {\n   @Test\n   public void isAutomaticIdTest() {\n      assertThat(AutomaticHardwareIdSpec.isAutomaticId(\"automatic:cores=2;ram=256\")).isTrue();\n   }\n\n   @Test\n   public void isNotAutomaticId() {\n      assertThat(AutomaticHardwareIdSpec.isAutomaticId(\"Hi, I'm a non automatic id.\")).isFalse();\n   }\n\n   @Test\n   public void parseAutomaticIdTest() {\n      AutomaticHardwareIdSpec parser = AutomaticHardwareIdSpec.parseId(\"automatic:cores=2;ram=256\");\n      assertThat(parser.getRam()).isEqualTo(256);\n      assertThat(parser.getCores()).isEqualTo(2);\n      AutomaticHardwareIdSpec parser2 = AutomaticHardwareIdSpec.parseId(\"automatic:cores=2;ram=4096;disk=100\");\n      assertThat(parser2.getRam()).isEqualTo(4096);\n      assertThat(parser2.getCores()).isEqualTo(2);\n      assertThat(parser2.getDisk().get()).isEqualTo(100);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void parseAutomaticIdMissingValuesTest() {\n      AutomaticHardwareIdSpec.parseId(\"automatic:cores=2\");\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class,\n         expectedExceptionsMessageRegExp = \"Invalid disk value: automatic:cores=2;ram=4096;disk=-100\")\n   public void parseAutomaticIdInvalidDiskTest() {\n      AutomaticHardwareIdSpec.parseId(\"automatic:cores=2;ram=4096;disk=-100\");\n   }\n\n   @Test\n   public void generateAutomaticIdTest() {\n      AutomaticHardwareIdSpec spec = AutomaticHardwareIdSpec.parseId(\"automatic:cores=2;ram=1024\");\n      assertThat(spec.toString()).isEqualTo(\"automatic:cores=2.0;ram=1024\");\n      AutomaticHardwareIdSpec spec2 = AutomaticHardwareIdSpec.parseId(\"automatic:cores=2;ram=4096;disk=100\");\n      assertThat(spec2.toString()).isEqualTo(\"automatic:cores=2.0;ram=4096;disk=100\");\n   }\n\n   @Test\n   public void automaticHardwareIdSpecBuilderTest() {\n      AutomaticHardwareIdSpec spec = AutomaticHardwareIdSpec.automaticHardwareIdSpecBuilder(2.0, 2048, Optional.<Float>absent());\n      assertThat(spec.getCores()).isEqualTo(2.0);\n      assertThat(spec.getRam()).isEqualTo(2048);\n      assertThat(spec.toString()).isEqualTo(\"automatic:cores=2.0;ram=2048\");\n      AutomaticHardwareIdSpec spec2 = AutomaticHardwareIdSpec.automaticHardwareIdSpecBuilder(4.0, 4096, Optional.of(10.0f));\n      assertThat(spec2.getCores()).isEqualTo(4.0);\n      assertThat(spec2.getRam()).isEqualTo(4096);\n      assertThat(spec2.getDisk().get()).isEqualTo(10);\n      assertThat(spec2.toString()).isEqualTo(\"automatic:cores=4.0;ram=4096;disk=10\");\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class,\n         expectedExceptionsMessageRegExp = \"Omitted or wrong minCores and minRam. If you want to\" +\n               \" use exact values, please set the minCores and minRam values: cores=2.0, ram=0\")\n   public void automaticHardwareIdSpecBuilderWrongSpecsTest() {\n      AutomaticHardwareIdSpec.automaticHardwareIdSpecBuilder(2.0, 0, Optional.<Float>absent());\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class,\n           expectedExceptionsMessageRegExp = \"Invalid disk value: -10\")\n   public void automaticHardwareIdSpecBuilderWrongDiskTest() {\n      AutomaticHardwareIdSpec.automaticHardwareIdSpecBuilder(2.0, 2048, Optional.of(-10.0f));\n   }\n\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/util/ComputeServiceUtilsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.util;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.jclouds.compute.util.ComputeServiceUtils.formatStatus;\nimport static org.jclouds.compute.util.ComputeServiceUtils.metadataAndTagsAsCommaDelimitedValue;\nimport static org.jclouds.compute.util.ComputeServiceUtils.metadataAndTagsAsValuesOfEmptyString;\nimport static org.jclouds.compute.util.ComputeServiceUtils.parseVersionOrReturnEmptyString;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Map;\n\nimport org.jclouds.compute.config.BaseComputeServiceContextModule;\nimport org.jclouds.compute.domain.ComputeMetadataIncludingStatus;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.json.Json;\nimport org.jclouds.json.config.GsonModule;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Maps;\nimport com.google.inject.Guice;\n\n/**\n * Test the compute utils.\n */\n@Test(groups = \"unit\", testName = \"ComputeServiceUtilsTest\")\npublic class ComputeServiceUtilsTest {\n   \n   @SuppressWarnings(\"unchecked\")\n   @Test\n   public void testFormatStatusWithBackendStatus() {\n      ComputeMetadataIncludingStatus<Image.Status> resource = createMock(ComputeMetadataIncludingStatus.class);\n      expect(resource.getStatus()).andReturn(Image.Status.PENDING);\n      expect(resource.getBackendStatus()).andReturn(\"queued\").anyTimes();\n      replay(resource);\n      assertEquals(formatStatus(resource), \"PENDING[queued]\");\n      verify(resource);\n   }\n   \n   @SuppressWarnings(\"unchecked\")\n   @Test\n   public void testFormatStatusWithoutBackendStatus() {\n      ComputeMetadataIncludingStatus<Image.Status> resource = createMock(ComputeMetadataIncludingStatus.class);\n      expect(resource.getStatus()).andReturn(Image.Status.PENDING);\n      expect(resource.getBackendStatus()).andReturn(null).anyTimes();\n      replay(resource);\n      assertEquals(formatStatus(resource), \"PENDING\");\n      verify(resource);\n   }\n   \n   Map<OsFamily, Map<String, String>> map = new BaseComputeServiceContextModule() {\n   }.provideOsVersionMap(new ComputeServiceConstants.ReferenceData(), Guice.createInjector(new GsonModule())\n         .getInstance(Json.class));\n\n   @Test\n   public void testMetadataAndTagsAsValuesOfEmptyString() {\n      TemplateOptions options = TemplateOptions.Builder.tags(ImmutableSet.of(\"tag\")).userMetadata(ImmutableMap.<String, String>of(\"foo\", \"bar\"));\n      assertEquals(metadataAndTagsAsValuesOfEmptyString(options), ImmutableMap.<String, String>of(\"foo\", \"bar\", \"tag\", \"\"));\n   }\n   \n   @Test\n   public void testMetadataAndTagsAsCommaDelimitedValue() {\n      TemplateOptions options = TemplateOptions.Builder.tags(ImmutableSet.of(\"tag\")).userMetadata(ImmutableMap.<String, String>of(\"foo\", \"bar\"));\n      assertEquals(metadataAndTagsAsCommaDelimitedValue(options), ImmutableMap.<String, String>of(\"foo\", \"bar\", \"jclouds_tags\", \"tag\"));\n   }\n\n   @Test\n   public void testMetadataAndTagsAsValuesOfEmptyStringNoTags() {\n      TemplateOptions options = TemplateOptions.Builder.userMetadata(ImmutableMap.<String, String>of(\"foo\", \"bar\"));\n      assertEquals(metadataAndTagsAsValuesOfEmptyString(options), ImmutableMap.<String, String>of(\"foo\", \"bar\"));\n   }\n   \n   @Test\n   public void testMetadataAndTagsAsCommaDelimitedValueNoTags() {\n      TemplateOptions options = TemplateOptions.Builder.userMetadata(ImmutableMap.<String, String>of(\"foo\", \"bar\"));\n      assertEquals(metadataAndTagsAsCommaDelimitedValue(options), ImmutableMap.<String, String>of(\"foo\", \"bar\"));\n   }\n   \n   @Test\n   public void testParseVersionOrReturnEmptyStringUbuntu1004() {\n      assertEquals(parseVersionOrReturnEmptyString(OsFamily.UBUNTU, \"Ubuntu 10.04\", map), \"10.04\");\n   }\n\n   @Test\n   public void testParseVersionOrReturnEmptyStringUbuntu1104() {\n      assertEquals(parseVersionOrReturnEmptyString(OsFamily.UBUNTU, \"ubuntu 11.04 server (i386)\", map), \"11.04\");\n   }\n\n   @Test\n   public void testExecHttpResponse() {\n      HttpRequest request = HttpRequest.builder()\n                                       .method(\"GET\")\n                                       .endpoint(\"https://adriancolehappy.s3.amazonaws.com/java/install\")\n                                       .addHeader(\"Host\", \"adriancolehappy.s3.amazonaws.com\")\n                                       .addHeader(\"Date\", \"Sun, 12 Sep 2010 08:25:19 GMT\")\n                                       .addHeader(\"Authorization\", \"AWS 0ASHDJAS82:JASHFDA=\").build();\n\n      assertEquals(\n            ComputeServiceUtils.execHttpResponse(request).render(org.jclouds.scriptbuilder.domain.OsFamily.UNIX),\n            \"curl -q -s -S -L --connect-timeout 10 --max-time 600 --retry 20 -X GET -H \\\"Host: adriancolehappy.s3.amazonaws.com\\\" -H \\\"Date: Sun, 12 Sep 2010 08:25:19 GMT\\\" -H \\\"Authorization: AWS 0ASHDJAS82:JASHFDA=\\\" https://adriancolehappy.s3.amazonaws.com/java/install |(bash)\\n\");\n\n   }\n\n   @Test\n   public void testTarxzpHttpResponse() {\n      HttpRequest request = HttpRequest.builder()\n                                       .method(\"GET\")\n                                       .endpoint(\"https://adriancolehappy.s3.amazonaws.com/java/install\")\n                                       .addHeader(\"Host\", \"adriancolehappy.s3.amazonaws.com\")\n                                       .addHeader(\"Date\", \"Sun, 12 Sep 2010 08:25:19 GMT\")\n                                       .addHeader(\"Authorization\", \"AWS 0ASHDJAS82:JASHFDA=\").build();\n            \n      assertEquals(\n            ComputeServiceUtils.extractTargzIntoDirectory(request, \"/stage/\").render(\n                  org.jclouds.scriptbuilder.domain.OsFamily.UNIX),\n            \"curl -q -s -S -L --connect-timeout 10 --max-time 600 --retry 20 -X GET -H \\\"Host: adriancolehappy.s3.amazonaws.com\\\" -H \\\"Date: Sun, 12 Sep 2010 08:25:19 GMT\\\" -H \\\"Authorization: AWS 0ASHDJAS82:JASHFDA=\\\" https://adriancolehappy.s3.amazonaws.com/java/install |(mkdir -p /stage/ &&cd /stage/ &&tar -xpzf -)\\n\");\n   }\n\n   @Test\n   public void testGetPortRangesFromList() {\n      Map<Integer, Integer> portRanges = Maps.newHashMap();\n      portRanges.put(5, 7);\n      portRanges.put(10, 11);\n      portRanges.put(20, 20);\n      assertEquals(portRanges, ComputeServiceUtils.getPortRangesFromList(5, 6, 7, 10, 11, 20));\n   }\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/compute/util/ConcurrentOpenSocketFinderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.compute.util;\n\nimport static com.google.common.base.Predicates.alwaysFalse;\nimport static com.google.common.base.Predicates.alwaysTrue;\nimport static com.google.common.base.Throwables.propagate;\nimport static com.google.common.util.concurrent.MoreExecutors.listeningDecorator;\nimport static com.google.common.util.concurrent.Uninterruptibles.sleepUninterruptibly;\nimport static java.util.concurrent.Executors.newCachedThreadPool;\nimport static java.util.concurrent.TimeUnit.MILLISECONDS;\nimport static org.jclouds.compute.domain.NodeMetadata.Status.RUNNING;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.fail;\n\nimport java.util.Map;\nimport java.util.NoSuchElementException;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadataBuilder;\nimport org.jclouds.compute.util.ConcurrentOpenSocketFinder.AllowedInterfaces;\nimport org.jclouds.predicates.SocketOpen;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Stopwatch;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.net.HostAndPort;\nimport com.google.common.util.concurrent.ListeningExecutorService;\n\n@Test(singleThreaded = true)\npublic class ConcurrentOpenSocketFinderTest {\n\n   /**\n    * prevente test failures on slow build slaves\n    */\n   private static final long SLOW_GRACE = 700;\n   private static final long EARLY_GRACE = 10;\n\n   private static final String PUBLIC_IP = \"1.2.3.4\";\n   private static final String PRIVATE_IP = \"1.2.3.5\";\n\n   private final NodeMetadata node = new NodeMetadataBuilder().id(\"myid\")\n                                                              .status(RUNNING)\n                                                              .publicAddresses(ImmutableSet.of(PUBLIC_IP))\n                                                              .privateAddresses(ImmutableSet.of(PRIVATE_IP)).build();\n\n   private final SocketOpen socketAlwaysClosed = new SocketOpen() {\n      @Override\n      public boolean apply(HostAndPort input) {\n         return false;\n      }\n   };\n   private final SocketOpen socketAlwaysOpen = new SocketOpen() {\n      @Override\n      public boolean apply(HostAndPort input) {\n         return true;\n      }\n   };\n   private final Predicate<AtomicReference<NodeMetadata>> nodeRunning = alwaysTrue();\n   private final Predicate<AtomicReference<NodeMetadata>> nodeNotRunning = alwaysFalse();\n\n   private ListeningExecutorService userExecutor;\n\n   @BeforeClass\n   public void setUp() {\n      userExecutor = listeningDecorator(newCachedThreadPool());\n   }\n\n   @AfterClass(alwaysRun = true)\n   public void tearDown() {\n      if (userExecutor != null)\n         userExecutor.shutdownNow();\n   }\n\n   @Test\n   public void testRespectsTimeout() throws Exception {\n      final long timeoutMs = 1000;\n\n      OpenSocketFinder finder = new ConcurrentOpenSocketFinder(socketAlwaysClosed, nodeRunning, userExecutor);\n\n      Stopwatch stopwatch = Stopwatch.createUnstarted();\n      stopwatch.start();\n      try {\n         finder.findOpenSocketOnNode(node, 22, timeoutMs, MILLISECONDS);\n         fail();\n      } catch (NoSuchElementException success) {\n         // expected\n      }\n      long timetaken = stopwatch.elapsed(MILLISECONDS);\n\n      assertTrue(timetaken >= timeoutMs - EARLY_GRACE && timetaken <= timeoutMs + SLOW_GRACE, \"timetaken=\" + timetaken);\n\n   }\n\n   @Test\n   public void testReturnsReachable() throws Exception {\n      SocketOpen secondSocketOpen = new SocketOpen() {\n         @Override\n         public boolean apply(HostAndPort input) {\n            return HostAndPort.fromParts(PRIVATE_IP, 22).equals(input);\n         }\n      };\n\n      OpenSocketFinder finder = new ConcurrentOpenSocketFinder(secondSocketOpen, nodeRunning, userExecutor);\n\n      HostAndPort result = finder.findOpenSocketOnNode(node, 22, 2000, MILLISECONDS);\n      assertEquals(result, HostAndPort.fromParts(PRIVATE_IP, 22));\n\n   }\n\n   @Test\n   public void testChecksSocketsConcurrently() throws Exception {\n      ControllableSocketOpen socketTester = new ControllableSocketOpen(ImmutableMap.of(\n            HostAndPort.fromParts(PUBLIC_IP, 22), new SlowCallable<Boolean>(true, 1500),\n            HostAndPort.fromParts(PRIVATE_IP, 22), new SlowCallable<Boolean>(true, 1000)));\n\n      OpenSocketFinder finder = new ConcurrentOpenSocketFinder(socketTester, nodeRunning, userExecutor);\n\n      HostAndPort result = finder.findOpenSocketOnNode(node, 22, 2000, MILLISECONDS);\n      assertEquals(result, HostAndPort.fromParts(PRIVATE_IP, 22));\n   }\n\n   @Test\n   public void testAbortsWhenNodeNotRunning() throws Exception {\n\n      OpenSocketFinder finder = new ConcurrentOpenSocketFinder(socketAlwaysClosed, nodeNotRunning, userExecutor) {\n         @Override\n         protected <T> Predicate<T> retryPredicate(final Predicate<T> findOrBreak, long timeout, long period,\n               TimeUnit timeUnits) {\n            return new Predicate<T>() {\n               @Override\n               public boolean apply(T input) {\n                  try {\n                     findOrBreak.apply(input);\n                     fail(\"should have thrown IllegalStateException\");\n                  } catch (IllegalStateException e) {\n                  }\n                  return false;\n               }\n            };\n         }\n      };\n\n      try {\n         finder.findOpenSocketOnNode(node, 22, 2000, MILLISECONDS);\n         fail();\n      } catch (NoSuchElementException e) {\n         // success\n         // Note: don't get the \"no longer running\" message, because\n         // logged+swallowed by RetryablePredicate\n      }\n   }\n\n\n   @Test\n   public void testSocketFinderAllowedInterfacesAll() throws Exception {\n      FluentIterable<String> ips = ConcurrentOpenSocketFinder.checkNodeHasIps(node, AllowedInterfaces.ALL);\n      assertTrue(ips.contains(PUBLIC_IP));\n      assertTrue(ips.contains(PRIVATE_IP));\n   }\n\n   @Test\n   public void testSocketFinderAllowedInterfacesPrivate() throws Exception {\n      FluentIterable<String> ips = ConcurrentOpenSocketFinder.checkNodeHasIps(node, AllowedInterfaces.PRIVATE);\n      assertFalse(ips.contains(PUBLIC_IP));\n      assertTrue(ips.contains(PRIVATE_IP));\n   }\n\n   @Test\n   public void testSocketFinderAllowedInterfacesPublic() throws Exception {\n      FluentIterable<String> ips = ConcurrentOpenSocketFinder.checkNodeHasIps(node, AllowedInterfaces.PUBLIC);\n      assertTrue(ips.contains(PUBLIC_IP));\n      assertFalse(ips.contains(PRIVATE_IP));\n   }\n\n   private static class SlowCallable<T> implements Callable<T> {\n      private final T result;\n      private final long delay;\n\n      SlowCallable(T result, long delay) {\n         this.result = result;\n         this.delay = delay;\n      }\n\n      @Override\n      public T call() throws Exception {\n         sleepUninterruptibly(delay, MILLISECONDS);\n         return result;\n      }\n   };\n\n   private static class ControllableSocketOpen implements SocketOpen {\n      private final Map<HostAndPort, ? extends Callable<Boolean>> answers;\n\n      ControllableSocketOpen(Map<HostAndPort, ? extends Callable<Boolean>> answers) {\n         this.answers = answers;\n      }\n\n      @Override\n      public boolean apply(HostAndPort input) {\n         try {\n            return answers.get(input).call();\n         } catch (Exception e) {\n            throw propagate(e);\n         }\n      }\n   };\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/net/domain/IpPermissionTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.net.domain;\n\nimport static org.jclouds.net.domain.IpPermission.builder;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.List;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\npublic class IpPermissionTest {\n\n   @Test\n   public void testCompareProtocol() {\n      final IpPermission tcp = builder().ipProtocol(IpProtocol.TCP).build();\n      final IpPermission tcp2 = builder().ipProtocol(IpProtocol.TCP).build();\n      assertEqualAndComparable(tcp, tcp2);\n\n      final IpPermission udp = builder().ipProtocol(IpProtocol.UDP).build();\n      assertOrder(tcp, udp);\n\n      final IpPermission t10 = builder().fromPermission(tcp).fromPort(10).build();\n      final IpPermission t20 = builder().fromPermission(tcp).fromPort(20).build();\n      final IpPermission u10 = builder().fromPermission(udp).fromPort(10).build();\n\n      final IpPermission t0to10 = builder().fromPermission(tcp).toPort(10).build();\n      final IpPermission t0to20 = builder().fromPermission(tcp).toPort(20).build();\n\n      assertTotalOrder(ImmutableList.of(tcp, t0to10, t0to20, t10, t20, udp, u10));\n   }\n\n   @Test\n   public void testCompareTenantIdGroupNamePairs() {\n      final IpPermission tcp = builder().ipProtocol(IpProtocol.TCP).build();\n\n      final IpPermission g1 = builder().fromPermission(tcp)\n         .tenantIdGroupNamePair(\"tenant1\", \"group1\").build();\n\n      final IpPermission g2 = builder().fromPermission(tcp)\n         .tenantIdGroupNamePair(\"tenant1\", \"group2\").build();\n\n      final IpPermission g12 = builder().fromPermission(tcp)\n         .tenantIdGroupNamePair(\"tenant1\", \"group1\")\n         .tenantIdGroupNamePair(\"tenant1\", \"group2\").build();\n\n      final IpPermission g21 = builder().fromPermission(tcp)\n         .tenantIdGroupNamePair(\"tenant1\", \"group2\")\n         .tenantIdGroupNamePair(\"tenant1\", \"group1\").build();\n\n      final IpPermission t2g1 = builder().fromPermission(tcp)\n         .tenantIdGroupNamePair(\"tenant2\", \"group1\").build();\n\n      assertTotalOrder(ImmutableList.of(tcp, g1, g12, g2, g21, t2g1));\n\n      final IpPermission g12b = builder().fromPermission(tcp)\n         .tenantIdGroupNamePair(\"tenant1\", \"group1\")\n         .tenantIdGroupNamePair(\"tenant1\", \"group2\").build();\n\n      assertEqualAndComparable(g12, g12b);\n   }\n\n   @Test\n   public void testCompareGroupIds() {\n      final IpPermission tcp = builder().ipProtocol(IpProtocol.TCP).build();\n\n      final IpPermission aa = builder().fromPermission(tcp)\n         .groupId(\"a\").build();\n\n      final IpPermission a = builder().fromPermission(tcp)\n         .groupId(\"a\").build();\n\n      final IpPermission ab = builder().fromPermission(tcp)\n         .groupId(\"a\")\n         .groupId(\"b\").build();\n\n      final IpPermission ba = builder().fromPermission(tcp)\n         .groupId(\"b\")\n         .groupId(\"a\").build();\n\n      assertTotalOrder(ImmutableList.of(tcp, a, ab, ba));\n      assertEqualAndComparable(a, aa);\n   }\n\n   @Test\n   public void testCompareCidrBlocks() {\n      final IpPermission tcp = builder().ipProtocol(IpProtocol.TCP).build();\n\n      final IpPermission everything = builder().fromPermission(tcp)\n         .cidrBlock(\"0.0.0.0/0\").build();\n      final IpPermission universal = builder().fromPermission(tcp)\n         .cidrBlock(\"0.0.0.0/0\").build();\n      assertEqualAndComparable(everything, universal);\n\n      final IpPermission localhost = builder().fromPermission(tcp)\n         .cidrBlock(\"127.0.0.1/32\").build();\n\n      final IpPermission tenTwentyOne = builder().fromPermission(tcp)\n         .cidrBlock(\"10.0.0.21/32\").build();\n\n      final IpPermission tenTwoHundred = builder().fromPermission(tcp)\n         .cidrBlock(\"10.0.0.200/32\").build();\n\n      // comparison is alphabetic, not by numeric equivalent\n      assertOrder(tenTwoHundred, tenTwentyOne);\n\n      assertTotalOrder(ImmutableList.of(tcp, everything, tenTwoHundred, tenTwentyOne, localhost));\n   }\n\n   @Test\n   public void testCompareExclusionCidrBlocks() {\n      final IpPermission tcp = builder().ipProtocol(IpProtocol.TCP).build();\n\n      final IpPermission everything = builder().fromPermission(tcp)\n         .exclusionCidrBlock(\"0.0.0.0/0\").build();\n      final IpPermission universal = builder().fromPermission(tcp)\n         .exclusionCidrBlock(\"0.0.0.0/0\").build();\n      assertEqualAndComparable(everything, universal);\n\n      final IpPermission localhost = builder().fromPermission(tcp)\n         .exclusionCidrBlock(\"127.0.0.1/32\").build();\n      final IpPermission stillLocal = builder().fromPermission(tcp)\n         .exclusionCidrBlock(\"127.0.0.1/32\").build();\n      assertEqualAndComparable(localhost, stillLocal);\n\n      final IpPermission tenTwentyOne = builder().fromPermission(tcp)\n         .exclusionCidrBlock(\"10.0.0.21/32\").build();\n\n      final IpPermission tenTwoHundred = builder().fromPermission(tcp)\n         .exclusionCidrBlock(\"10.0.0.200/32\").build();\n\n      // comparison is alphabetic, not by numeric equivalent\n      assertOrder(tenTwoHundred, tenTwentyOne);\n\n      assertTotalOrder(ImmutableList.of(tcp, everything, tenTwoHundred, tenTwentyOne, localhost));\n   }\n\n\n   @Test\n   public void testPairwise() {\n\n      final IpPermission tcp = builder().ipProtocol(IpProtocol.TCP).build();\n      final IpPermission udp = builder().ipProtocol(IpProtocol.UDP).build();\n\n      final IpPermission f10 = builder().fromPermission(tcp).fromPort(10).build();\n      final IpPermission f20 = builder().fromPermission(tcp).fromPort(20).build();\n      final IpPermission u10 = builder().fromPermission(udp).fromPort(10).build();\n\n      final IpPermission t20 = builder().fromPermission(f10).toPort(20).build();\n      final IpPermission t30 = builder().fromPermission(f10).toPort(30).build();\n\n      final IpPermission t2g1 = builder().fromPermission(t20)\n         .tenantIdGroupNamePair(\"tenant1\", \"group1\")\n      .build();\n\n      final IpPermission t2g2 = builder().fromPermission(t20)\n         .tenantIdGroupNamePair(\"tenant1\", \"group2\")\n      .build();\n\n      final IpPermission gidA = builder().fromPermission(t2g1)\n         .groupId(\"groupA\")\n      .build();\n\n      final IpPermission gidB = builder().fromPermission(t2g1)\n         .groupId(\"groupB\")\n      .build();\n\n      final IpPermission cidr10 = builder().fromPermission(gidA)\n         .cidrBlock(\"10.10.10.10/32\")\n      .build();\n\n      final IpPermission cidr20 = builder().fromPermission(gidA)\n         .cidrBlock(\"10.10.10.20/32\")\n      .build();\n\n      final IpPermission ex10 = builder().fromPermission(cidr10)\n         .exclusionCidrBlock(\"172.16.10.10/32\")\n      .build();\n\n      final IpPermission ex20 = builder().fromPermission(cidr10)\n         .exclusionCidrBlock(\"172.16.10.20/32\")\n      .build();\n\n      assertTotalOrder(ImmutableList.of(\n         tcp,\n            f10,\n               t20,\n                  t2g1,\n                     gidA,\n                        cidr10,\n                           ex10,\n                           ex20,\n                        cidr20,\n                     gidB,\n                  t2g2,\n               t30,\n            f20,\n         udp,\n            u10\n      ));\n   }\n\n\n   public static void assertEqualAndComparable(IpPermission first, IpPermission second) {\n      assertEquals(first, second, first + \" does not equal \" + second);\n      assertTrue(first.compareTo(second) == 0, first + \" does not compare zero to \" + second);\n   }\n\n   @SuppressWarnings(\"SelfComparison\")\n   private static void assertOrder(IpPermission smaller, IpPermission bigger) {\n      assertTrue(smaller.compareTo(bigger) < 0, smaller + \" does not compare less than \" + bigger);\n      assertTrue(bigger.compareTo(smaller) > 0, bigger + \" does not compare greater than \" + smaller);\n      assertTrue(smaller.compareTo(smaller) == 0, smaller + \" does not compare zero to itself\");\n      assertTrue(bigger.compareTo(bigger) == 0, bigger + \" does not compare zero to itself\");\n   }\n\n   private static void assertTotalOrder(List<IpPermission> permissions) {\n      if (permissions.size() < 2) return;\n      IpPermission head = permissions.get(0);\n      List<IpPermission> tail = permissions.subList(1, permissions.size());\n      for (IpPermission perm : tail) {\n         assertOrder(head, perm);\n      }\n      assertTotalOrder(tail);\n   }\n\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/net/util/IpPermissionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.net.util;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.net.domain.IpPermission;\nimport org.jclouds.net.domain.IpProtocol;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests possible uses of IpPermissions\n */\n@Test(testName = \"IpPermissionsTest\")\npublic class IpPermissionsTest {\n   public void testAllProtocol() {\n      IpPermissions authorization = IpPermissions.permitAnyProtocol();\n      assertEquals(authorization, IpPermission.builder().ipProtocol(IpProtocol.ALL).fromPort(1).toPort(65535)\n               .cidrBlock(\"0.0.0.0/0\").build());\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testAllProtocolInvalidCidr() {\n      IpPermissions authorization = IpPermissions.permitAnyProtocol();\n      assertEquals(authorization, IpPermission.builder().ipProtocol(IpProtocol.ALL).fromPort(1).toPort(65535)\n               .cidrBlock(\"a.0.0.0/0\").build());\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testAllProtocolInvalidExclusionCidr() {\n      IpPermissions authorization = IpPermissions.permitAnyProtocol();\n      assertEquals(authorization, IpPermission.builder().ipProtocol(IpProtocol.ALL).fromPort(1).toPort(65535)\n               .exclusionCidrBlock(\"a.0.0.0/0\").build());\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testAllProtocolInvalidCidrMultiple() {\n      IpPermissions authorization = IpPermissions.permitAnyProtocol();\n      assertEquals(authorization, IpPermission.builder().ipProtocol(IpProtocol.ALL).fromPort(1).toPort(65535)\n                   .cidrBlocks(ImmutableSet.of(\"a.0.0.0/0\", \"0.0.0.0/0\")).build());\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testAllProtocolInvalidExclusionCidrMultiple() {\n      IpPermissions authorization = IpPermissions.permitAnyProtocol();\n      assertEquals(authorization, IpPermission.builder().ipProtocol(IpProtocol.ALL).fromPort(1).toPort(65535)\n                   .exclusionCidrBlocks(ImmutableSet.of(\"a.0.0.0/0\", \"0.0.0.0/0\")).build());\n   }\n\n   public void testAllProtocolCidrBound() {\n      IpPermissions authorization = IpPermissions.permit(IpProtocol.ALL).originatingFromCidrBlock(\"1.1.1.1/32\");\n      assertEquals(authorization, IpPermission.builder().ipProtocol(IpProtocol.ALL).fromPort(1).toPort(65535)\n               .cidrBlock(\"1.1.1.1/32\").build());\n   }\n\n   public void testAllProtocolExclusionCidrBound() {\n      IpPermissions authorization = IpPermissions.permit(IpProtocol.ALL).exceptOriginatingFromCidrBlock(\"1.1.1.1/32\");\n      assertEquals(authorization, IpPermission.builder().ipProtocol(IpProtocol.ALL).fromPort(1).toPort(65535)\n               .exclusionCidrBlock(\"1.1.1.1/32\").build());\n   }\n\n   public void testJustProtocolAndCidr() {\n      IpPermissions authorization = IpPermissions.permit(IpProtocol.TCP).originatingFromCidrBlock(\"1.1.1.1/32\");\n      assertEquals(authorization, IpPermission.builder().ipProtocol(IpProtocol.TCP).fromPort(1).toPort(65535)\n               .cidrBlock(\"1.1.1.1/32\").build());\n   }\n\n   public void testJustProtocolAndExcludedCidr() {\n      IpPermissions authorization = IpPermissions.permit(IpProtocol.TCP).exceptOriginatingFromCidrBlock(\"1.1.1.1/32\");\n      assertEquals(authorization, IpPermission.builder().ipProtocol(IpProtocol.TCP).fromPort(1).toPort(65535)\n               .exclusionCidrBlock(\"1.1.1.1/32\").build());\n   }\n\n   public void testAnyProtocol() {\n      IpPermissions authorization = IpPermissions.permitAnyProtocol().originatingFromCidrBlock(\"1.1.1.1/32\");\n      assertEquals(authorization, IpPermission.builder().ipProtocol(IpProtocol.ALL).fromPort(1).toPort(65535)\n               .cidrBlock(\"1.1.1.1/32\").build());\n   }\n\n   public void testAnyProtocolWithExcludedCidr() {\n      IpPermissions authorization = IpPermissions.permitAnyProtocol().exceptOriginatingFromCidrBlock(\"1.1.1.1/32\");\n      assertEquals(authorization, IpPermission.builder().ipProtocol(IpProtocol.ALL).fromPort(1).toPort(65535)\n               .exclusionCidrBlock(\"1.1.1.1/32\").build());\n   }\n\n   public void testMultipleCidrs() {\n      IpPermissions authorization = IpPermissions.permit(IpProtocol.TCP).originatingFromCidrBlocks(\n               ImmutableSet.of(\"1.1.1.1/32\", \"1.1.1.2/32\"));\n      assertEquals(authorization, IpPermission.builder().ipProtocol(IpProtocol.TCP).fromPort(1).toPort(65535)\n               .cidrBlocks(ImmutableSet.of(\"1.1.1.1/32\", \"1.1.1.2/32\")).build());\n   }\n\n   public void testMultipleCidrsExclusions() {\n      IpPermissions authorization = IpPermissions.permit(IpProtocol.TCP).exceptOriginatingFromCidrBlocks(\n               ImmutableSet.of(\"1.1.1.1/32\", \"1.1.1.2/32\"));\n      assertEquals(authorization, IpPermission.builder().ipProtocol(IpProtocol.TCP).fromPort(1).toPort(65535)\n               .exclusionCidrBlocks(ImmutableSet.of(\"1.1.1.1/32\", \"1.1.1.2/32\")).build());\n   }\n\n   public void testProtocolFromAndToPortAndGroupIds() {\n      IpPermissions authorization = IpPermissions.permit(IpProtocol.UDP).fromPort(11).to(53)\n               .originatingFromSecurityGroupId(\"groupId\");\n      assertEquals(authorization, IpPermission.builder().ipProtocol(IpProtocol.UDP).fromPort(11).toPort(53)\n               .groupId(\"groupId\").build());\n   }\n\n   public void testProtocolICMPAny() {\n      IpPermissions authorization = IpPermissions.permitICMP().originatingFromSecurityGroupId(\"groupId\");\n      assertEquals(authorization, IpPermission.builder().ipProtocol(IpProtocol.ICMP).fromPort(-1).toPort(-1)\n               .groupId(\"groupId\").build());\n   }\n\n   public void testProtocolICMPTypeAnyCode() {\n      IpPermissions authorization = IpPermissions.permitICMP().type(8).originatingFromSecurityGroupId(\"groupId\");\n      assertEquals(authorization, IpPermission.builder().ipProtocol(IpProtocol.ICMP).fromPort(8).toPort(-1)\n               .groupId(\"groupId\").build());\n   }\n\n   public void testProtocolICMPTypeCode() {\n      IpPermissions authorization = IpPermissions.permitICMP().type(8).andCode(0).originatingFromSecurityGroupId(\n               \"groupId\");\n      assertEquals(authorization, IpPermission.builder().ipProtocol(IpProtocol.ICMP).fromPort(8).toPort(0).groupId(\n               \"groupId\").build());\n   }\n\n   public void testProtocolFromAndToPortAndUserGroups() {\n      IpPermissions authorization = IpPermissions.permit(IpProtocol.ICMP).fromPort(8).to(0)\n               .originatingFromTenantAndSecurityGroup(\"tenantId\", \"groupName\");\n\n      assertEquals(authorization, IpPermission.builder().ipProtocol(IpProtocol.ICMP).fromPort(8).toPort(0)\n               .tenantIdGroupNamePair(\"tenantId\", \"groupName\").build());\n   }\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/ovf/xml/DiskSectionHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ovf.xml;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\nimport java.net.URI;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.http.functions.ParseSax.Factory;\nimport org.jclouds.http.functions.config.SaxParserModule;\nimport org.jclouds.ovf.Disk;\nimport org.jclouds.ovf.DiskSection;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n/**\n * Tests behavior of {@code DiskSectionHandler}\n */\n@Test(groups = \"unit\")\npublic class DiskSectionHandlerTest {\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/disksection.xml\");\n      Injector injector = Guice.createInjector(new SaxParserModule());\n      Factory factory = injector.getInstance(ParseSax.Factory.class);\n      DiskSection result = factory.create(injector.getInstance(DiskSectionHandler.class)).parse(is);\n      assertEquals(result.toString(), DiskSection.builder().info(\"Describes the set of virtual disks\").disk(\n               Disk.builder().id(\"vmdisk1\")\n\n               .fileRef(\"file1\").capacity(8589934592L).populatedSize(3549324972L).format(\n                        URI.create(\"http://www.vmware.com/interfaces/specifications/vmdk.html#sparse\")).build()).disk(\n               Disk.builder().id(\"vmdisk2\").capacity(536870912L).build()).disk(\n               Disk.builder().id(\"vmdisk3\").capacityAllocationUnits(\"byte * 2^30\").build())\n\n      .build().toString()\n\n      );\n   }\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/ovf/xml/NetworkSectionHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ovf.xml;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.http.functions.ParseSax.Factory;\nimport org.jclouds.http.functions.config.SaxParserModule;\nimport org.jclouds.ovf.Network;\nimport org.jclouds.ovf.NetworkSection;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n/**\n * Tests behavior of {@code NetworkSectionHandler}\n */\n@Test(groups = \"unit\")\npublic class NetworkSectionHandlerTest {\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/networksection.xml\");\n      Injector injector = Guice.createInjector(new SaxParserModule());\n      Factory factory = injector.getInstance(ParseSax.Factory.class);\n      NetworkSection result = factory.create(injector.getInstance(NetworkSectionHandler.class)).parse(is);\n      assertEquals(result.toString(), NetworkSection.builder().info(\"List of logical networks used in the package\")\n               .network(\n                        Network.builder().name(\"red\").description(\"The network the Red service is available on\")\n                                 .build()).network(\n                        Network.builder().name(\"blue\").description(\"The network the Blue service is available on\")\n                                 .build())\n               .build().toString()\n\n      );\n   }\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/ovf/xml/OperatingSystemSectionHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ovf.xml;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.http.functions.ParseSax.Factory;\nimport org.jclouds.http.functions.config.SaxParserModule;\nimport org.jclouds.ovf.OperatingSystemSection;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n/**\n * Tests behavior of {@code OperatingSystemSectionHandler}\n */\n@Test(groups = \"unit\")\npublic class OperatingSystemSectionHandlerTest {\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/operatingsystemsection.xml\");\n      Injector injector = Guice.createInjector(new SaxParserModule());\n      Factory factory = injector.getInstance(ParseSax.Factory.class);\n      OperatingSystemSection result = factory.create(injector.getInstance(OperatingSystemSectionHandler.class)).parse(\n               is);\n      assertEquals(result.toString(), OperatingSystemSection.builder().info(\"Specifies the operating system installed\")\n               .description(\"Microsoft Windows Server 2008\").id(76).build().toString()\n\n      );\n   }\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/ovf/xml/ProductSectionHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ovf.xml;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.http.functions.ParseSax.Factory;\nimport org.jclouds.http.functions.config.SaxParserModule;\nimport org.jclouds.ovf.ProductSection;\nimport org.jclouds.ovf.Property;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n/**\n * Tests behavior of {@code ProductSectionHandler}\n */\n@Test(groups = \"unit\")\npublic class ProductSectionHandlerTest {\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/productsection.xml\");\n      Injector injector = Guice.createInjector(new SaxParserModule());\n      Factory factory = injector.getInstance(ParseSax.Factory.class);\n      ProductSection result = factory.create(injector.getInstance(ProductSectionHandler.class)).parse(is);\n      assertEquals(result.toString(), ProductSection.builder().info(\"vCenter Information\").property(\n               Property.builder().value(\"false\").key(\"vmwareToolsEnabled\").label(\"VMWare Tools Enabled status\")\n                        .description(\"VMWare Tools Enabled status\").build()).property(\n\n               Property.builder().value(\"10.12.46.171\").key(\"vmwareESXHost\").label(\"VMWare ESXHost Ipaddress\")\n                        .description(\"VMWare ESXHost Ipaddress\").build()).property(\n\n               Property.builder().value(\"cussl01s01c01alun088bal,cussl01s01c01alun089bal\").key(\"datastores\").label(\n                        \"Datastore Name\").description(\"Datastore Name\").build()).property(\n               Property.builder().value(\"[Totalcapacity=1335915184128,UsedCapacity=549755813888]\").key(\n                        \"cussl01s01c01alun088bal\").label(\"Datastore Capacity\").description(\n                        \"Datastore cussl01s01c01alun088bal Total Capacity, Used Capacity in comma separated\").build())\n               .property(\n\n                        Property.builder().value(\"[Totalcapacity=1335915184129,UsedCapacity=549755813889]\").key(\n                                 \"cussl01s01c01alun089bal\").label(\"Datastore Capacity\").description(\n                                 \"Datastore cussl01s01c01alun089bal Total Capacity, Used Capacity in comma separated\")\n                                 .build()).property(\n\n                        Property.builder().value(\"[name=3282176-1949-bal-tier01,ip=0.0.0.0,mac=00:50:56:8c:3f:3c]\")\n                                 .key(\"customerPortprofile\").label(\"customerPortprofile\").description(\n                                          \"customerPortprofile\").build()).property(\n\n                        Property.builder().value(\"[name=vm-server-mgmt,ip=0.0.0.0,mac=00:50:56:8c:39:75]\").key(\n                                 \"savvisPortprofile\").label(\"savvisPortprofile\").description(\"savvisPortprofile\")\n                                 .build()).build().toString()\n\n      );\n   }\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/ssh/SshKeysTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ssh;\n\nimport static org.jclouds.ssh.SshKeys.fingerprint;\nimport static org.jclouds.ssh.SshKeys.generate;\nimport static org.jclouds.ssh.SshKeys.privateKeyHasFingerprint;\nimport static org.jclouds.ssh.SshKeys.privateKeyHasSha1;\nimport static org.jclouds.ssh.SshKeys.privateKeyMatchesPublicKey;\nimport static org.jclouds.ssh.SshKeys.publicKeySpecFromOpenSSH;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.security.KeyFactory;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.interfaces.RSAPublicKey;\nimport java.security.spec.InvalidKeySpecException;\nimport java.security.spec.RSAPrivateCrtKeySpec;\nimport java.security.spec.RSAPublicKeySpec;\nimport java.util.Map;\n\nimport com.google.common.io.Resources;\n\nimport org.jclouds.crypto.Pems;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", singleThreaded = true, testName = \"SshKeysTest\")\npublic class SshKeysTest {\n\n   String expectedFingerprint = \"2b:a9:62:95:5b:8b:1d:61:e0:92:f7:03:10:e9:db:d9\";\n   String expectedSha1 = \"c8:01:34:c0:3c:8c:91:ac:e1:da:cf:72:15:d7:f2:e5:99:5b:28:d4\";\n\n   @Test\n   public void testCanReadRsaAndCompareFingerprintOnPublicRSAKey() throws IOException {\n      String pubKey = Strings2.toStringAndClose(getClass().getResourceAsStream(\"/test.pub\"));\n      RSAPublicKeySpec key = SshKeys.publicKeySpecFromOpenSSH(pubKey);\n      String fingerPrint = fingerprint(key.getPublicExponent(), key.getModulus());\n      assertEquals(fingerPrint, expectedFingerprint);\n   }\n\n   @Test\n   public void testCanReadRsaAndCompareFingerprintOnPrivateRSAKey() throws IOException {\n      String privKey = Strings2.toStringAndClose(getClass().getResourceAsStream(\"/test\"));\n      RSAPrivateCrtKeySpec key = (RSAPrivateCrtKeySpec) Pems.privateKeySpec(privKey);\n      String fingerPrint = fingerprint(key.getPublicExponent(), key.getModulus());\n      assertEquals(fingerPrint, expectedFingerprint);\n   }\n\n   @Test\n   public void testPrivateKeyMatchesFingerprintTyped() throws IOException {\n      String privKey = Strings2.toStringAndClose(getClass().getResourceAsStream(\"/test\"));\n      RSAPrivateCrtKeySpec privateKey = (RSAPrivateCrtKeySpec) Pems.privateKeySpec(privKey);\n      assert privateKeyHasFingerprint(privateKey, expectedFingerprint);\n   }\n\n   @Test\n   public void testPrivateKeyMatchesFingerprintString() throws IOException {\n      String privKey = Strings2.toStringAndClose(getClass().getResourceAsStream(\"/test\"));\n      assert privateKeyHasFingerprint(privKey, expectedFingerprint);\n   }\n\n   @Test\n   public void testPrivateKeyMatchesSha1Typed() throws IOException {\n      String privKey = Strings2.toStringAndClose(getClass().getResourceAsStream(\"/test\"));\n      RSAPrivateCrtKeySpec privateKey = (RSAPrivateCrtKeySpec) Pems.privateKeySpec(privKey);\n      assert privateKeyHasSha1(privateKey, expectedSha1);\n   }\n\n   @Test\n   public void testPrivateKeyMatchesSha1String() throws IOException {\n      String privKey = Strings2.toStringAndClose(getClass().getResourceAsStream(\"/test\"));\n      assert privateKeyHasSha1(privKey, expectedSha1);\n   }\n\n   @Test\n   public void testPrivateKeyMatchesPublicKeyTyped() throws IOException {\n      String privKey = Strings2.toStringAndClose(getClass().getResourceAsStream(\"/test\"));\n      RSAPrivateCrtKeySpec privateKey = (RSAPrivateCrtKeySpec) Pems.privateKeySpec(privKey);\n      String pubKey = Strings2.toStringAndClose(getClass().getResourceAsStream(\"/test.pub\"));\n      RSAPublicKeySpec publicKey = publicKeySpecFromOpenSSH(pubKey);\n      assert privateKeyMatchesPublicKey(privateKey, publicKey);\n   }\n\n   @Test\n   public void testPrivateKeyMatchesPublicKeyString() throws IOException {\n      String privKey = Strings2.toStringAndClose(getClass().getResourceAsStream(\"/test\"));\n      String pubKey = Strings2.toStringAndClose(getClass().getResourceAsStream(\"/test.pub\"));\n      assert privateKeyMatchesPublicKey(privKey, pubKey);\n   }\n\n   @Test\n   public void testCanGenerate() {\n      Map<String, String> map = generate();\n      assert map.get(\"public\").startsWith(\"ssh-rsa \") : map;\n      assert map.get(\"private\").startsWith(\"-----BEGIN RSA PRIVATE KEY-----\") : map;\n      assert privateKeyMatchesPublicKey(map.get(\"private\"), map.get(\"public\")) : map;\n\n   }\n\n   @Test\n   public void testEncodeAsOpenSSH() throws IOException, InvalidKeySpecException, NoSuchAlgorithmException {\n      String encoded = SshKeys.encodeAsOpenSSH((RSAPublicKey) KeyFactory.getInstance(\"RSA\").generatePublic(\n               SshKeys.publicKeySpecFromOpenSSH(Resources.asByteSource(Resources.getResource(getClass(), \"/test.pub\")))));\n      assertEquals(encoded, Strings2.toStringAndClose(getClass().getResourceAsStream(\"/test.pub\")).trim());\n   }\n\n}\n"
  },
  {
    "path": "compute/src/test/java/org/jclouds/ssh/config/RsaSshKeyPairGeneratorTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ssh.config;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.jclouds.crypto.PemsTest.PRIVATE_KEY;\nimport static org.jclouds.crypto.PemsTest.PUBLIC_KEY;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.security.KeyFactory;\nimport java.security.KeyPair;\nimport java.security.KeyPairGenerator;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.PrivateKey;\nimport java.security.PublicKey;\nimport java.security.SecureRandom;\nimport java.security.interfaces.RSAPublicKey;\nimport java.security.spec.InvalidKeySpecException;\n\nimport org.jclouds.crypto.Crypto;\nimport org.jclouds.crypto.Pems;\nimport org.jclouds.ssh.SshKeys;\nimport org.jclouds.ssh.internal.RsaSshKeyPairGenerator;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.io.ByteSource;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\n\n@Test(groups = \"unit\", testName = \"RsaSshKeyPairGeneratorTest\")\npublic class RsaSshKeyPairGeneratorTest {\n   private static final String lineSeparator = System.getProperty(\"line.separator\");\n\n   private KeyPair keyPair;\n   private String openSshKey;\n\n   @BeforeClass\n   public void setup() throws InvalidKeySpecException, NoSuchAlgorithmException, IOException {\n      KeyFactory keyfactory = KeyFactory.getInstance(\"RSA\");\n      PrivateKey privateKey = keyfactory.generatePrivate(Pems.privateKeySpec(ByteSource.wrap(PRIVATE_KEY.getBytes(Charsets.UTF_8))));\n\n      PublicKey publicKey = keyfactory.generatePublic(Pems.publicKeySpec(ByteSource.wrap(PUBLIC_KEY.getBytes(Charsets.UTF_8))));\n\n      keyPair = new KeyPair(publicKey, privateKey);\n      openSshKey = SshKeys.encodeAsOpenSSH(RSAPublicKey.class.cast(publicKey));\n   }\n\n   @Test\n   public void testApply() {\n      final Crypto crypto = createMock(Crypto.class);\n      KeyPairGenerator rsaKeyPairGenerator = createMock(KeyPairGenerator.class);\n      final SecureRandom secureRandom = createMock(SecureRandom.class);\n\n      expect(crypto.rsaKeyPairGenerator()).andReturn(rsaKeyPairGenerator);\n      rsaKeyPairGenerator.initialize(2048, secureRandom);\n      expect(rsaKeyPairGenerator.genKeyPair()).andReturn(keyPair);\n\n      replay(crypto, rsaKeyPairGenerator, secureRandom);\n\n      RsaSshKeyPairGenerator supplier = Guice.createInjector(new AbstractModule() {\n         protected void configure() {\n            bind(Crypto.class).toInstance(crypto);\n            bind(SecureRandom.class).toInstance(secureRandom);\n         }\n      }).getInstance(RsaSshKeyPairGenerator.class);\n\n      assertEquals(supplier.get(),\n               ImmutableMap.of(\"public\", openSshKey, \"private\", PRIVATE_KEY.replaceAll(\"\\n\", lineSeparator)));\n\n      verify(crypto, rsaKeyPairGenerator, secureRandom);\n   }\n\n}\n"
  },
  {
    "path": "compute/src/test/resources/.gitattributes",
    "content": "*.sh -crlf\n"
  },
  {
    "path": "compute/src/test/resources/disksection.xml",
    "content": "<DiskSection>\n    <Info>Describes the set of virtual disks</Info>\n    <Disk ovf:diskId=\"vmdisk1\" ovf:fileRef=\"file1\" ovf:capacity=\"8589934592\"\n        ovf:populatedSize=\"3549324972\"\n        ovf:format=\"http://www.vmware.com/interfaces/specifications/vmdk.html#sparse\">\n    </Disk>\n    <Disk ovf:diskId=\"vmdisk2\" ovf:capacity=\"536870912\" />\n    <Disk ovf:diskId=\"vmdisk3\" ovf:capacity=\"${disk.size}\"\n        ovf:capacityAllocationUnits=\"byte * 2^30\" />\n</DiskSection>"
  },
  {
    "path": "compute/src/test/resources/initscript_with_java.sh",
    "content": "#!/bin/bash\nset +u\nshopt -s xpg_echo\nshopt -s expand_aliases\nunset PATH JAVA_HOME LD_LIBRARY_PATH\nfunction abort {\n   echo \"aborting: $@\" 1>&2\n   exit 1\n}\nfunction default {\n   export INSTANCE_NAME=\"bootstrap\"\nexport INSTANCE_HOME=\"/tmp/bootstrap\"\nexport LOG_DIR=\"$INSTANCE_HOME\"\n   return $?\n}\nfunction bootstrap {\n      return $?\n}\nfunction findPid {\n   unset FOUND_PID;\n   [ $# -eq 1 ] || {\n      abort \"findPid requires a parameter of pattern to match\"\n      return 1\n   }\n   local PATTERN=\"$1\"; shift\n   local _FOUND=`ps auxwww|grep \"$PATTERN\"|grep -v \" $0\"|grep -v grep|grep -v $$|awk '{print $2}'`\n   [ -n \"$_FOUND\" ] && {\n      export FOUND_PID=$_FOUND\n      return 0\n   } || {\n      return 1\n   }\n}\nfunction forget {\n   unset FOUND_PID;\n   [ $# -eq 3 ] || {\n      abort \"forget requires parameters INSTANCE_NAME SCRIPT LOG_DIR\"\n      return 1\n   }\n   local INSTANCE_NAME=\"$1\"; shift\n   local SCRIPT=\"$1\"; shift\n   local LOG_DIR=\"$1\"; shift\n   mkdir -p $LOG_DIR\n   findPid $INSTANCE_NAME\n   [ -n \"$FOUND_PID\" -a -f $LOG_DIR/stdout.log ] && {\n      echo $INSTANCE_NAME already running pid $FOUND_PID\n      return 1;\n   } || {\n      nohup $SCRIPT >$LOG_DIR/stdout.log 2>$LOG_DIR/stderr.log &\n      RETURN=$?\n      # this is generally followed by findPid, so we shouldn't exit \n      # immediately as the proc may not have registered in ps, yet\n      test $RETURN && sleep 1\n      return $RETURN;\n   }\n}\nexport PATH=/usr/ucb/bin:/bin:/sbin:/usr/bin:/usr/sbin\ncase $1 in\ninit)\n   default || exit 1\n   bootstrap || exit 1\n   mkdir -p $INSTANCE_HOME\n   \n   # create runscript header\n   cat > $INSTANCE_HOME/bootstrap.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\t#!/bin/bash\n\tset +u\n\tshopt -s xpg_echo\n\tshopt -s expand_aliases\n\t\n\tPROMPT_COMMAND='echo -ne \\\"\\033]0;bootstrap\\007\\\"'\n\texport PATH=/usr/ucb/bin:/bin:/sbin:/usr/bin:/usr/sbin\n\n\texport INSTANCE_NAME='bootstrap'\nEND_OF_JCLOUDS_SCRIPT\n   cat >> $INSTANCE_HOME/bootstrap.sh <<-END_OF_JCLOUDS_SCRIPT\n\texport INSTANCE_NAME='$INSTANCE_NAME'\n\texport INSTANCE_HOME='$INSTANCE_HOME'\n\texport LOG_DIR='$LOG_DIR'\nEND_OF_JCLOUDS_SCRIPT\n   cat >> $INSTANCE_HOME/bootstrap.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\tfunction abort {\n   echo \"aborting: $@\" 1>&2\n   exit 1\n}\nalias apt-get-update=\"apt-get update -qq\"\nalias apt-get-install=\"apt-get install -f -y -qq --force-yes\"\nalias yum-install=\"yum --quiet --nogpgcheck -y install\"\n\nfunction ensure_cmd_or_install_package_apt(){\n  local cmd=$1\n  shift\n  local pkg=$*\n  \n  hash $cmd 2>/dev/null || ( apt-get-update && apt-get-install $pkg )\n}\n\nfunction ensure_cmd_or_install_package_yum(){\n  local cmd=$1\n  shift\n  local pkg=$*\n  hash $cmd 2>/dev/null || yum-install $pkg\n}\n\nfunction ensure_netutils_apt() {\n  ensure_cmd_or_install_package_apt nslookup dnsutils\n  ensure_cmd_or_install_package_apt curl curl\n}\n\nfunction ensure_netutils_yum() {\n  ensure_cmd_or_install_package_yum nslookup bind-utils\n  ensure_cmd_or_install_package_yum curl curl\n}\n\n# most network services require that the hostname is in\n# the /etc/hosts file, or they won't operate\nfunction ensure_hostname_in_hosts() {\n  [ -n \"$SSH_CONNECTION\" ] && {\n    local ipaddr=`echo $SSH_CONNECTION | awk '{print $3}'`\n  } || {\n    local ipaddr=`hostname -i`\n  }\n  # NOTE: we blindly trust existing hostname settings in /etc/hosts\n  egrep -q `hostname -s` /etc/hosts || echo \"$ipaddr `hostname -f` `hostname -s`\" >> /etc/hosts\n}\n\n# download locations for many services are at public dns\nfunction ensure_can_resolve_public_dns() {\n  nslookup yahoo.com | grep yahoo.com > /dev/null || echo nameserver 208.67.222.222 >> /etc/resolv.conf\n}\n\nfunction setupPublicCurl() {\n  ensure_hostname_in_hosts\n  if which dpkg &> /dev/null; then\n    ensure_netutils_apt\n  elif which rpm &> /dev/null; then\n    ensure_netutils_yum\n  else\n    abort \"we only support apt-get and yum right now... please contribute!\"\n    return 1\n  fi\n  ensure_can_resolve_public_dns\n  return 0  \n}\n# adds JAVA_HOME and into PATH in global and user-specific profiles\nfunction setupJavaHomeInProfile() {\n  PROFILES=(/etc/bashrc $HOME/.bashrc /etc/skel/.bashrc)\n  test -n \"$SUDO_USER\" &&\n    PROFILES=(${PROFILES[*]} `getent passwd $SUDO_USER| cut -f6 -d:`/.bashrc)\n  for PROFILE in ${PROFILES[*]}; do\n    cat >> $PROFILE <<-'END_OF_JCLOUDS_FILE'\n\texport JAVA_HOME=/usr/local/jdk\n\texport PATH=$JAVA_HOME/bin:$PATH\nEND_OF_JCLOUDS_FILE\n  done\n}\n\n# resets JAVA_HOME to what an openjdk installer created\nfunction findOpenJDK() {\n  local oldJavaHome=$JAVA_HOME\n  unset JAVA_HOME\n  for CANDIDATE in $oldJavaHome `ls -d /usr/lib/jvm/java-*-openjdk* 2>&-`; do\n    if [ -n \"$CANDIDATE\" -a -x \"$CANDIDATE/bin/java\" ]; then\n      export JAVA_HOME=$CANDIDATE\n      break\n    fi\n  done\n}\n\n# assures JDK installed and JAVA_HOME to a link at /usr/local/jdk\nfunction installOpenJDK() {\n  if [ \"$JAVA_HOME\" == \"/usr/local/jdk\" ]; then\n    echo skipping as JAVA_HOME is already set to /usr/local/jdk\n    return 0\n  fi\n  if [ -n \"$JAVA_HOME\" -a -x \"$JAVA_HOME/bin/java\" ]; then\n    echo reusing JAVA_HOME $JAVA_HOME\n  else\n    if which dpkg &> /dev/null; then\n      apt-get-update && \\\n          PACKAGE=$(apt-cache search --names-only '^openjdk-.-jdk$' | sort -r | cut -d' ' -f1 | head -1) && \\\n          [ ! -z \"$PACKAGE\" ] && \\\n          {  apt-get-install $PACKAGE-headless || apt-get-install $PACKAGE; }\n    elif which rpm &> /dev/null; then\n      PACKAGE=$(repoquery --qf='%{name}' --pkgnarrow=available 'java-*-openjdk-devel' | sort -r | head -1) && \\\n        [ ! -z \"$PACKAGE\" ] && \\\n        yum-install $PACKAGE\n    else\n      abort \"we only support apt-get and yum right now... please contribute\"\n    fi\n    findOpenJDK\n    if [ -n \"$JAVA_HOME\" ]; then\n      echo installed JAVA_HOME $JAVA_HOME\n    else\n      abort \"JDK installation failed\"\n    fi\n  fi\n  rm -rf /usr/local/jdk\n  ln -Fs $JAVA_HOME /usr/local/jdk\n  /usr/local/jdk/bin/java -version || abort \"cannot run java\"\n  setupJavaHomeInProfile\n}\n\nEND_OF_JCLOUDS_SCRIPT\n   \n   # add desired commands from the user\n   cat >> $INSTANCE_HOME/bootstrap.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\tcd $INSTANCE_HOME\n\trm -f $INSTANCE_HOME/rc\n\ttrap 'echo $?>$INSTANCE_HOME/rc' 0 1 2 3 15\n\tcat > /etc/sudoers <<-'END_OF_JCLOUDS_FILE'\n\t\tDefaults    env_reset\n\t\tDefaults    secure_path=\"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\"\n\t\troot ALL = (ALL) ALL\n\t\t%wheel ALL = (ALL) NOPASSWD:ALL\n\tEND_OF_JCLOUDS_FILE\n\tchmod 0440 /etc/sudoers\n\tmkdir -p /home/users\n\tchmod 0755 /home/users\n\tgetent group wheel || groupadd -f wheel\n\tuseradd -c 'defaultAdminUsername' -s /bin/bash -g wheel -m  -d /home/users/defaultAdminUsername -p 'crypt(randompassword)' defaultAdminUsername\n\tmkdir -p /home/users/defaultAdminUsername/.ssh\n\tcat >> /home/users/defaultAdminUsername/.ssh/authorized_keys <<-'END_OF_JCLOUDS_FILE'\n\t\tpublicKey\n\tEND_OF_JCLOUDS_FILE\n\tchmod 600 /home/users/defaultAdminUsername/.ssh/authorized_keys\n\tchown -R defaultAdminUsername /home/users/defaultAdminUsername/.ssh\n\tchown -R defaultAdminUsername /home/users/defaultAdminUsername\n\texec 3<> /etc/ssh/sshd_config && awk -v TEXT=\"PasswordAuthentication no\n\tPermitRootLogin no\n\t\" 'BEGIN {print TEXT}{print}' /etc/ssh/sshd_config >&3\n\thash service 2>&- && service ssh reload 2>&- || service sshd reload 2>&- || /etc/init.d/ssh* reload\n\tawk -v user=^${SUDO_USER:=${USER}}: -v password='crypt(randompassword)' 'BEGIN { FS=OFS=\":\" } $0 ~ user { $2 = password } 1' /etc/shadow >/etc/shadow.${SUDO_USER:=${USER}}\n\ttest -f /etc/shadow.${SUDO_USER:=${USER}} && mv /etc/shadow.${SUDO_USER:=${USER}} /etc/shadow\n\tsetupPublicCurl || return 1\n\tinstallOpenJDK || return 1\n\t\nEND_OF_JCLOUDS_SCRIPT\n   \n   # add runscript footer\n   cat >> $INSTANCE_HOME/bootstrap.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\texit $?\n\t\nEND_OF_JCLOUDS_SCRIPT\n   \n   chmod u+x $INSTANCE_HOME/bootstrap.sh\n   ;;\nstatus)\n   default || exit 1\n   findPid $INSTANCE_NAME || exit 1\n   echo $FOUND_PID\n   ;;\nstop)\n   default || exit 1\n   findPid $INSTANCE_NAME || exit 1\n   [ -n \"$FOUND_PID\" ]  && {\n      echo stopping $FOUND_PID\n      kill -9 $FOUND_PID\n   }\n   ;;\nstart)\n   default || exit 1\n   forget $INSTANCE_NAME $INSTANCE_HOME/$INSTANCE_NAME.sh $LOG_DIR || exit 1\n   ;;\nstdout)\n   default || exit 1\n   cat $LOG_DIR/stdout.log\n   ;;\nstderr)\n   default || exit 1\n   cat $LOG_DIR/stderr.log\n   ;;\nexitstatus)\n   default || exit 1\n   [ -f $LOG_DIR/rc ] && cat $LOG_DIR/rc;;\ntail)\n   default || exit 1\n   tail $LOG_DIR/stdout.log\n   ;;\ntailerr)\n   default || exit 1\n   tail $LOG_DIR/stderr.log\n   ;;\nrun)\n   default || exit 1\n   $INSTANCE_HOME/$INSTANCE_NAME.sh\n   ;;\nesac\nexit $?\n"
  },
  {
    "path": "compute/src/test/resources/initscript_with_jetty.sh",
    "content": "#!/bin/bash\nset +u\nshopt -s xpg_echo\nshopt -s expand_aliases\nunset PATH JAVA_HOME LD_LIBRARY_PATH\nfunction abort {\n   echo \"aborting: $@\" 1>&2\n   exit 1\n}\nfunction default {\n   export INSTANCE_NAME=\"configure-jetty\"\nexport INSTANCE_HOME=\"/tmp/configure-jetty\"\nexport LOG_DIR=\"$INSTANCE_HOME\"\n   return $?\n}\nfunction configure-jetty {\n      return $?\n}\nfunction findPid {\n   unset FOUND_PID;\n   [ $# -eq 1 ] || {\n      abort \"findPid requires a parameter of pattern to match\"\n      return 1\n   }\n   local PATTERN=\"$1\"; shift\n   local _FOUND=`ps auxwww|grep \"$PATTERN\"|grep -v \" $0\"|grep -v grep|grep -v $$|awk '{print $2}'`\n   [ -n \"$_FOUND\" ] && {\n      export FOUND_PID=$_FOUND\n      return 0\n   } || {\n      return 1\n   }\n}\nfunction forget {\n   unset FOUND_PID;\n   [ $# -eq 3 ] || {\n      abort \"forget requires parameters INSTANCE_NAME SCRIPT LOG_DIR\"\n      return 1\n   }\n   local INSTANCE_NAME=\"$1\"; shift\n   local SCRIPT=\"$1\"; shift\n   local LOG_DIR=\"$1\"; shift\n   mkdir -p $LOG_DIR\n   findPid $INSTANCE_NAME\n   [ -n \"$FOUND_PID\" -a -f $LOG_DIR/stdout.log ] && {\n      echo $INSTANCE_NAME already running pid $FOUND_PID\n      return 1;\n   } || {\n      nohup $SCRIPT >$LOG_DIR/stdout.log 2>$LOG_DIR/stderr.log &\n      RETURN=$?\n      # this is generally followed by findPid, so we shouldn't exit \n      # immediately as the proc may not have registered in ps, yet\n      test $RETURN && sleep 1\n      return $RETURN;\n   }\n}\nexport PATH=/usr/ucb/bin:/bin:/sbin:/usr/bin:/usr/sbin\ncase $1 in\ninit)\n   default || exit 1\n   configure-jetty || exit 1\n   mkdir -p $INSTANCE_HOME\n   \n   # create runscript header\n   cat > $INSTANCE_HOME/configure-jetty.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\t#!/bin/bash\n\tset +u\n\tshopt -s xpg_echo\n\tshopt -s expand_aliases\n\t\n\tPROMPT_COMMAND='echo -ne \\\"\\033]0;configure-jetty\\007\\\"'\n\texport PATH=/usr/ucb/bin:/bin:/sbin:/usr/bin:/usr/sbin\n\n\texport INSTANCE_NAME='configure-jetty'\nEND_OF_JCLOUDS_SCRIPT\n   cat >> $INSTANCE_HOME/configure-jetty.sh <<-END_OF_JCLOUDS_SCRIPT\n\texport INSTANCE_NAME='$INSTANCE_NAME'\n\texport INSTANCE_HOME='$INSTANCE_HOME'\n\texport LOG_DIR='$LOG_DIR'\nEND_OF_JCLOUDS_SCRIPT\n   cat >> $INSTANCE_HOME/configure-jetty.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\tfunction abort {\n   echo \"aborting: $@\" 1>&2\n   exit 1\n}\nalias apt-get-update=\"apt-get update -qq\"\nalias apt-get-install=\"apt-get install -f -y -qq --force-yes\"\nalias yum-install=\"yum --quiet --nogpgcheck -y install\"\n\nfunction ensure_cmd_or_install_package_apt(){\n  local cmd=$1\n  shift\n  local pkg=$*\n  \n  hash $cmd 2>/dev/null || ( apt-get-update && apt-get-install $pkg )\n}\n\nfunction ensure_cmd_or_install_package_yum(){\n  local cmd=$1\n  shift\n  local pkg=$*\n  hash $cmd 2>/dev/null || yum-install $pkg\n}\n\nfunction ensure_netutils_apt() {\n  ensure_cmd_or_install_package_apt nslookup dnsutils\n  ensure_cmd_or_install_package_apt curl curl\n}\n\nfunction ensure_netutils_yum() {\n  ensure_cmd_or_install_package_yum nslookup bind-utils\n  ensure_cmd_or_install_package_yum curl curl\n}\n\n# most network services require that the hostname is in\n# the /etc/hosts file, or they won't operate\nfunction ensure_hostname_in_hosts() {\n  [ -n \"$SSH_CONNECTION\" ] && {\n    local ipaddr=`echo $SSH_CONNECTION | awk '{print $3}'`\n  } || {\n    local ipaddr=`hostname -i`\n  }\n  # NOTE: we blindly trust existing hostname settings in /etc/hosts\n  egrep -q `hostname -s` /etc/hosts || echo \"$ipaddr `hostname -f` `hostname -s`\" >> /etc/hosts\n}\n\n# download locations for many services are at public dns\nfunction ensure_can_resolve_public_dns() {\n  nslookup yahoo.com | grep yahoo.com > /dev/null || echo nameserver 208.67.222.222 >> /etc/resolv.conf\n}\n\nfunction setupPublicCurl() {\n  ensure_hostname_in_hosts\n  if which dpkg &> /dev/null; then\n    ensure_netutils_apt\n  elif which rpm &> /dev/null; then\n    ensure_netutils_yum\n  else\n    abort \"we only support apt-get and yum right now... please contribute!\"\n    return 1\n  fi\n  ensure_can_resolve_public_dns\n  return 0  \n}\n# adds JAVA_HOME and into PATH in global and user-specific profiles\nfunction setupJavaHomeInProfile() {\n  PROFILES=(/etc/bashrc $HOME/.bashrc /etc/skel/.bashrc)\n  test -n \"$SUDO_USER\" &&\n    PROFILES=(${PROFILES[*]} `getent passwd $SUDO_USER| cut -f6 -d:`/.bashrc)\n  for PROFILE in ${PROFILES[*]}; do\n    cat >> $PROFILE <<-'END_OF_JCLOUDS_FILE'\n\texport JAVA_HOME=/usr/local/jdk\n\texport PATH=$JAVA_HOME/bin:$PATH\nEND_OF_JCLOUDS_FILE\n  done\n}\n\n# resets JAVA_HOME to what an openjdk installer created\nfunction findOpenJDK() {\n  local oldJavaHome=$JAVA_HOME\n  unset JAVA_HOME\n  for CANDIDATE in $oldJavaHome `ls -d /usr/lib/jvm/java-*-openjdk* 2>&-`; do\n    if [ -n \"$CANDIDATE\" -a -x \"$CANDIDATE/bin/java\" ]; then\n      export JAVA_HOME=$CANDIDATE\n      break\n    fi\n  done\n}\n\n# assures JDK installed and JAVA_HOME to a link at /usr/local/jdk\nfunction installOpenJDK() {\n  if [ \"$JAVA_HOME\" == \"/usr/local/jdk\" ]; then\n    echo skipping as JAVA_HOME is already set to /usr/local/jdk\n    return 0\n  fi\n  if [ -n \"$JAVA_HOME\" -a -x \"$JAVA_HOME/bin/java\" ]; then\n    echo reusing JAVA_HOME $JAVA_HOME\n  else\n    if which dpkg &> /dev/null; then\n      apt-get-update && \\\n          PACKAGE=$(apt-cache search --names-only '^openjdk-.-jdk$' | sort -r | cut -d' ' -f1 | head -1) && \\\n          [ ! -z \"$PACKAGE\" ] && \\\n          {  apt-get-install $PACKAGE-headless || apt-get-install $PACKAGE; }\n    elif which rpm &> /dev/null; then\n      PACKAGE=$(repoquery --qf='%{name}' --pkgnarrow=available 'java-*-openjdk-devel' | sort -r | head -1) && \\\n        [ ! -z \"$PACKAGE\" ] && \\\n        yum-install $PACKAGE\n    else\n      abort \"we only support apt-get and yum right now... please contribute\"\n    fi\n    findOpenJDK\n    if [ -n \"$JAVA_HOME\" ]; then\n      echo installed JAVA_HOME $JAVA_HOME\n    else\n      abort \"JDK installation failed\"\n    fi\n  fi\n  rm -rf /usr/local/jdk\n  ln -Fs $JAVA_HOME /usr/local/jdk\n  /usr/local/jdk/bin/java -version || abort \"cannot run java\"\n  setupJavaHomeInProfile\n}\n\nEND_OF_JCLOUDS_SCRIPT\n   \n   # add desired commands from the user\n   cat >> $INSTANCE_HOME/configure-jetty.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\tcd $INSTANCE_HOME\n\trm -f $INSTANCE_HOME/rc\n\ttrap 'echo $?>$INSTANCE_HOME/rc' 0 1 2 3 15\n\tcat > /etc/sudoers <<-'END_OF_JCLOUDS_FILE'\n\t\tDefaults    env_reset\n\t\tDefaults    secure_path=\"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\"\n\t\troot ALL = (ALL) ALL\n\t\t%wheel ALL = (ALL) NOPASSWD:ALL\n\tEND_OF_JCLOUDS_FILE\n\tchmod 0440 /etc/sudoers\n\tmkdir -p /home/users\n\tchmod 0755 /home/users\n\tgetent group wheel || groupadd -f wheel\n\tuseradd -c 'web' -s /bin/bash -g wheel -m  -d /home/users/web -p 'crypt(randompassword)' web\n\tmkdir -p /home/users/web/.ssh\n\tcat >> /home/users/web/.ssh/authorized_keys <<-'END_OF_JCLOUDS_FILE'\n\t\tpublicKey\n\tEND_OF_JCLOUDS_FILE\n\tchmod 600 /home/users/web/.ssh/authorized_keys\n\tchown -R web /home/users/web/.ssh\n\tchown -R web /home/users/web\n\texec 3<> /etc/ssh/sshd_config && awk -v TEXT=\"PasswordAuthentication no\n\tPermitRootLogin no\n\t\" 'BEGIN {print TEXT}{print}' /etc/ssh/sshd_config >&3\n\thash service 2>&- && service ssh reload 2>&- || service sshd reload 2>&- || /etc/init.d/ssh* reload\n\tawk -v user=^${SUDO_USER:=${USER}}: -v password='crypt(randompassword)' 'BEGIN { FS=OFS=\":\" } $0 ~ user { $2 = password } 1' /etc/shadow >/etc/shadow.${SUDO_USER:=${USER}}\n\ttest -f /etc/shadow.${SUDO_USER:=${USER}} && mv /etc/shadow.${SUDO_USER:=${USER}} /etc/shadow\n\tsetupPublicCurl || return 1\n\tinstallOpenJDK || return 1\n\tiptables -I INPUT 1 -p tcp --dport 8080 -j ACCEPT\n\tiptables-save\n\texport TAR_TEMP=\"$(mktemp -d)\"\n\tcurl -q -s -S -L --connect-timeout 10 --max-time 600 --retry 20 -X GET  http://archive.eclipse.org/jetty/8.1.8.v20121106/dist/jetty-distribution-8.1.8.v20121106.tar.gz |(mkdir -p \"${TAR_TEMP}\" &&cd \"${TAR_TEMP}\" &&tar -xpzf -)\n\tmkdir -p /usr/local/jetty\n\tmv \"${TAR_TEMP}\"/*/* /usr/local/jetty\n\trm -rf \"${TAR_TEMP}\"\n\tchown -R web /usr/local/jetty\n\t\nEND_OF_JCLOUDS_SCRIPT\n   \n   # add runscript footer\n   cat >> $INSTANCE_HOME/configure-jetty.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\texit $?\n\t\nEND_OF_JCLOUDS_SCRIPT\n   \n   chmod u+x $INSTANCE_HOME/configure-jetty.sh\n   ;;\nstatus)\n   default || exit 1\n   findPid $INSTANCE_NAME || exit 1\n   echo $FOUND_PID\n   ;;\nstop)\n   default || exit 1\n   findPid $INSTANCE_NAME || exit 1\n   [ -n \"$FOUND_PID\" ]  && {\n      echo stopping $FOUND_PID\n      kill -9 $FOUND_PID\n   }\n   ;;\nstart)\n   default || exit 1\n   forget $INSTANCE_NAME $INSTANCE_HOME/$INSTANCE_NAME.sh $LOG_DIR || exit 1\n   ;;\nstdout)\n   default || exit 1\n   cat $LOG_DIR/stdout.log\n   ;;\nstderr)\n   default || exit 1\n   cat $LOG_DIR/stderr.log\n   ;;\nexitstatus)\n   default || exit 1\n   [ -f $LOG_DIR/rc ] && cat $LOG_DIR/rc;;\ntail)\n   default || exit 1\n   tail $LOG_DIR/stdout.log\n   ;;\ntailerr)\n   default || exit 1\n   tail $LOG_DIR/stderr.log\n   ;;\nrun)\n   default || exit 1\n   $INSTANCE_HOME/$INSTANCE_NAME.sh\n   ;;\nesac\nexit $?\n"
  },
  {
    "path": "compute/src/test/resources/log4j.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE log4j:configuration SYSTEM \"log4j.dtd\">\n\n    <!--\n        For more configuration infromation and examples see the Apache\n        Log4j website: http://logging.apache.org/log4j/\n    -->\n<log4j:configuration xmlns:log4j=\"http://jakarta.apache.org/log4j/\"\n    debug=\"false\">\n    \n    <!-- A time/date based rolling appender -->\n    <appender name=\"FILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n    <!-- A time/date based rolling appender -->\n    <appender name=\"COMPUTEFILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds-compute.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n\n    <!-- A time/date based rolling appender -->\n    <appender name=\"SSHFILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds-ssh.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n\n    <appender name=\"ASYNCCOMPUTE\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"COMPUTEFILE\" />\n    </appender>\n\n    <appender name=\"ASYNCSSH\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"SSHFILE\" />\n    </appender>\n\n    <appender name=\"ASYNC\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"FILE\" />\n    </appender>\n    \n    <!-- ================ -->\n    <!-- Limit categories -->\n    <!-- ================ -->\n\n    <category name=\"org.jclouds\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNC\" />\n    </category>\n\n    <category name=\"jclouds.ssh\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNCSSH\" />\n    </category>\n    \n    <category name=\"jclouds.compute\">\n        <priority value=\"TRACE\" />\n        <appender-ref ref=\"ASYNCCOMPUTE\" />\n    </category>\n    <!-- ======================= -->\n    <!-- Setup the Root category -->\n    <!-- ======================= -->\n\n    <root>\n        <priority value=\"WARN\" />\n    </root>\n\n</log4j:configuration>\n"
  },
  {
    "path": "compute/src/test/resources/logback.xml",
    "content": "<?xml version=\"1.0\"?>\n<configuration scan=\"false\">\n    <appender name=\"FILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <appender name=\"WIREFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds-wire.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <appender name=\"COMPUTEFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds-compute.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n    \n    <appender name=\"SSHFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds-ssh.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <root>\n        <level value=\"warn\" />\n    </root>\n\n    <logger name=\"org.jclouds\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"FILE\" />\n    </logger>\n\n    <logger name=\"jclouds.wire\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n\n    <logger name=\"jclouds.headers\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n\n    <logger name=\"jclouds.compute\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"COMPUTEFILE\" />\n    </logger>\n    \n    <logger name=\"jclouds.ssh\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"SSHFILE\" />\n    </logger>\n\n</configuration>\n"
  },
  {
    "path": "compute/src/test/resources/networksection.xml",
    "content": "<NetworkSection>\n    <Info>List of logical networks used in the package</Info>\n    <Network ovf:name=\"red\">\n        <Description>The network the Red service is available on\n        </Description>\n    </Network>\n    <Network ovf:name=\"blue\">\n        <Description>The network the Blue service is available on\n        </Description>\n    </Network>\n</NetworkSection>"
  },
  {
    "path": "compute/src/test/resources/operatingsystemsection.xml",
    "content": "<OperatingSystemSection ovf:id=\"76\">\n    <Info>Specifies the operating system installed</Info>\n    <Description>Microsoft Windows Server 2008</Description>\n</OperatingSystemSection>"
  },
  {
    "path": "compute/src/test/resources/productsection.xml",
    "content": "    <ovf:ProductSection>\n        <ovf:Info>vCenter Information</ovf:Info>\n        <ovf:Property ovf:value=\"false\" ovf:type=\"String\" ovf:key=\"vmwareToolsEnabled\">\n            <ovf:Label>VMWare Tools Enabled status</ovf:Label>\n            <ovf:Description>VMWare Tools Enabled status</ovf:Description>\n        </ovf:Property>\n        <ovf:Property ovf:value=\"10.12.46.171\" ovf:type=\"String\" ovf:key=\"vmwareESXHost\">\n            <ovf:Label>VMWare ESXHost Ipaddress</ovf:Label>\n            <ovf:Description>VMWare ESXHost Ipaddress</ovf:Description>\n        </ovf:Property>\n        <ovf:Property ovf:value=\"cussl01s01c01alun088bal,cussl01s01c01alun089bal\" ovf:type=\"String\" ovf:key=\"datastores\">\n            <ovf:Label>Datastore Name</ovf:Label>\n            <ovf:Description>Datastore Name</ovf:Description>\n        </ovf:Property>\n        <!-- **** capacity unit : bytes *** -->\n        <ovf:Property ovf:value=\"[Totalcapacity=1335915184128,UsedCapacity=549755813888]\" ovf:type=\"String\"\n                      ovf:key=\"cussl01s01c01alun088bal\">\n            <ovf:Label>Datastore Capacity</ovf:Label>\n            <ovf:Description>Datastore cussl01s01c01alun088bal Total Capacity, Used Capacity in comma separated\n            </ovf:Description>\n        </ovf:Property>\n        <ovf:Property ovf:value=\"[Totalcapacity=1335915184129,UsedCapacity=549755813889]\" ovf:type=\"String\"\n                      ovf:key=\"cussl01s01c01alun089bal\">\n            <ovf:Label>Datastore Capacity</ovf:Label>\n            <ovf:Description>Datastore cussl01s01c01alun089bal Total Capacity, Used Capacity in comma separated\n            </ovf:Description>\n        </ovf:Property>\n        <ovf:Property ovf:value=\"[name=3282176-1949-bal-tier01,ip=0.0.0.0,mac=00:50:56:8c:3f:3c]\" ovf:type=\"String\"\n                      ovf:key=\"customerPortprofile\">\n            <ovf:Label>customerPortprofile</ovf:Label>\n            <ovf:Description>customerPortprofile</ovf:Description>\n        </ovf:Property>\n        <ovf:Property ovf:value=\"[name=vm-server-mgmt,ip=0.0.0.0,mac=00:50:56:8c:39:75]\" ovf:type=\"String\"\n                      ovf:key=\"savvisPortprofile\">\n            <ovf:Label>savvisPortprofile</ovf:Label>\n            <ovf:Description>savvisPortprofile</ovf:Description>\n        </ovf:Property>\n    </ovf:ProductSection>"
  },
  {
    "path": "compute/src/test/resources/resourceallocation.xml",
    "content": " <ovf:Item>\n            <rasd:Address xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:nil=\"true\"/>\n            <rasd:AddressOnParent xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:nil=\"true\"/>\n            <rasd:AllocationUnits>Gigabytes</rasd:AllocationUnits>\n            <rasd:AutomaticAllocation xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:nil=\"true\"/>\n            <rasd:AutomaticDeallocation xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:nil=\"true\"/>\n            <rasd:Caption>1234568</rasd:Caption>\n            <rasd:ChangeableType xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:nil=\"true\"/>\n            <rasd:ConfigurationName xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:nil=\"true\"/>\n            <rasd:ConsumerVisibility xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:nil=\"true\"/>\n            <rasd:Description>Hard Disk</rasd:Description>\n            <rasd:ElementName>D:\\</rasd:ElementName>\n            <rasd:Generation xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:nil=\"true\"/>\n            <rasd:HostResource>data</rasd:HostResource>\n            <rasd:InstanceID>6</rasd:InstanceID>\n            <rasd:Limit xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:nil=\"true\"/>\n            <rasd:MappingBehavior xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:nil=\"true\"/>\n            <rasd:OtherResourceType xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:nil=\"true\"/>\n            <rasd:Parent xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:nil=\"true\"/>\n            <rasd:PoolID xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:nil=\"true\"/>\n            <rasd:Reservation xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:nil=\"true\"/>\n            <rasd:ResourceSubType xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:nil=\"true\"/>\n            <rasd:ResourceType>26</rasd:ResourceType>\n            <rasd:VirtualQuantity>50</rasd:VirtualQuantity>\n            <rasd:Weight xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:nil=\"true\"/>\n        </ovf:Item>"
  },
  {
    "path": "compute/src/test/resources/runscript.sh",
    "content": "#!/bin/bash\nset +u\nshopt -s xpg_echo\nshopt -s expand_aliases\nunset PATH JAVA_HOME LD_LIBRARY_PATH\nfunction abort {\n   echo \"aborting: $@\" 1>&2\n   exit 1\n}\nfunction default {\n   export INSTANCE_NAME=\"runScriptWithCreds\"\nexport INSTANCE_HOME=\"/tmp/runScriptWithCreds\"\nexport LOG_DIR=\"$INSTANCE_HOME\"\n   return $?\n}\nfunction runScriptWithCreds {\n      return $?\n}\nfunction findPid {\n   unset FOUND_PID;\n   [ $# -eq 1 ] || {\n      abort \"findPid requires a parameter of pattern to match\"\n      return 1\n   }\n   local PATTERN=\"$1\"; shift\n   local _FOUND=`ps auxwww|grep \"$PATTERN\"|grep -v \" $0\"|grep -v grep|grep -v $$|awk '{print $2}'`\n   [ -n \"$_FOUND\" ] && {\n      export FOUND_PID=$_FOUND\n      return 0\n   } || {\n      return 1\n   }\n}\nfunction forget {\n   unset FOUND_PID;\n   [ $# -eq 3 ] || {\n      abort \"forget requires parameters INSTANCE_NAME SCRIPT LOG_DIR\"\n      return 1\n   }\n   local INSTANCE_NAME=\"$1\"; shift\n   local SCRIPT=\"$1\"; shift\n   local LOG_DIR=\"$1\"; shift\n   mkdir -p $LOG_DIR\n   findPid $INSTANCE_NAME\n   [ -n \"$FOUND_PID\" -a -f $LOG_DIR/stdout.log ] && {\n      echo $INSTANCE_NAME already running pid $FOUND_PID\n      return 1;\n   } || {\n      nohup $SCRIPT >$LOG_DIR/stdout.log 2>$LOG_DIR/stderr.log &\n      RETURN=$?\n      # this is generally followed by findPid, so we shouldn't exit \n      # immediately as the proc may not have registered in ps, yet\n      test $RETURN && sleep 1\n      return $RETURN;\n   }\n}\nexport PATH=/usr/ucb/bin:/bin:/sbin:/usr/bin:/usr/sbin\ncase $1 in\ninit)\n   default || exit 1\n   runScriptWithCreds || exit 1\n   mkdir -p $INSTANCE_HOME\n   \n   # create runscript header\n   cat > $INSTANCE_HOME/runScriptWithCreds.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\t#!/bin/bash\n\tset +u\n\tshopt -s xpg_echo\n\tshopt -s expand_aliases\n\t\n\tPROMPT_COMMAND='echo -ne \\\"\\033]0;runScriptWithCreds\\007\\\"'\n\texport PATH=/usr/ucb/bin:/bin:/sbin:/usr/bin:/usr/sbin\n\n\texport INSTANCE_NAME='runScriptWithCreds'\nEND_OF_JCLOUDS_SCRIPT\n   cat >> $INSTANCE_HOME/runScriptWithCreds.sh <<-END_OF_JCLOUDS_SCRIPT\n\texport INSTANCE_NAME='$INSTANCE_NAME'\n\texport INSTANCE_HOME='$INSTANCE_HOME'\n\texport LOG_DIR='$LOG_DIR'\nEND_OF_JCLOUDS_SCRIPT\n   cat >> $INSTANCE_HOME/runScriptWithCreds.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\tfunction abort {\n   echo \"aborting: $@\" 1>&2\n   exit 1\n}\nalias apt-get-update=\"apt-get update -qq\"\nalias apt-get-install=\"apt-get install -f -y -qq --force-yes\"\nalias yum-install=\"yum --quiet --nogpgcheck -y install\"\n\nfunction ensure_cmd_or_install_package_apt(){\n  local cmd=$1\n  shift\n  local pkg=$*\n  \n  hash $cmd 2>/dev/null || ( apt-get-update && apt-get-install $pkg )\n}\n\nfunction ensure_cmd_or_install_package_yum(){\n  local cmd=$1\n  shift\n  local pkg=$*\n  hash $cmd 2>/dev/null || yum-install $pkg\n}\n\nfunction ensure_netutils_apt() {\n  ensure_cmd_or_install_package_apt nslookup dnsutils\n  ensure_cmd_or_install_package_apt curl curl\n}\n\nfunction ensure_netutils_yum() {\n  ensure_cmd_or_install_package_yum nslookup bind-utils\n  ensure_cmd_or_install_package_yum curl curl\n}\n\n# most network services require that the hostname is in\n# the /etc/hosts file, or they won't operate\nfunction ensure_hostname_in_hosts() {\n  [ -n \"$SSH_CONNECTION\" ] && {\n    local ipaddr=`echo $SSH_CONNECTION | awk '{print $3}'`\n  } || {\n    local ipaddr=`hostname -i`\n  }\n  # NOTE: we blindly trust existing hostname settings in /etc/hosts\n  egrep -q `hostname -s` /etc/hosts || echo \"$ipaddr `hostname -f` `hostname -s`\" >> /etc/hosts\n}\n\n# download locations for many services are at public dns\nfunction ensure_can_resolve_public_dns() {\n  nslookup yahoo.com | grep yahoo.com > /dev/null || echo nameserver 208.67.222.222 >> /etc/resolv.conf\n}\n\nfunction setupPublicCurl() {\n  ensure_hostname_in_hosts\n  if which dpkg &> /dev/null; then\n    ensure_netutils_apt\n  elif which rpm &> /dev/null; then\n    ensure_netutils_yum\n  else\n    abort \"we only support apt-get and yum right now... please contribute!\"\n    return 1\n  fi\n  ensure_can_resolve_public_dns\n  return 0  \n}\n# adds JAVA_HOME and into PATH in global and user-specific profiles\nfunction setupJavaHomeInProfile() {\n  PROFILES=(/etc/bashrc $HOME/.bashrc /etc/skel/.bashrc)\n  test -n \"$SUDO_USER\" &&\n    PROFILES=(${PROFILES[*]} `getent passwd $SUDO_USER| cut -f6 -d:`/.bashrc)\n  for PROFILE in ${PROFILES[*]}; do\n    cat >> $PROFILE <<-'END_OF_JCLOUDS_FILE'\n\texport JAVA_HOME=/usr/local/jdk\n\texport PATH=$JAVA_HOME/bin:$PATH\nEND_OF_JCLOUDS_FILE\n  done\n}\n\n# resets JAVA_HOME to what an openjdk installer created\nfunction findOpenJDK() {\n  local oldJavaHome=$JAVA_HOME\n  unset JAVA_HOME\n  for CANDIDATE in $oldJavaHome `ls -d /usr/lib/jvm/java-*-openjdk* 2>&-`; do\n    if [ -n \"$CANDIDATE\" -a -x \"$CANDIDATE/bin/java\" ]; then\n      export JAVA_HOME=$CANDIDATE\n      break\n    fi\n  done\n}\n\n# assures JDK installed and JAVA_HOME to a link at /usr/local/jdk\nfunction installOpenJDK() {\n  if [ \"$JAVA_HOME\" == \"/usr/local/jdk\" ]; then\n    echo skipping as JAVA_HOME is already set to /usr/local/jdk\n    return 0\n  fi\n  if [ -n \"$JAVA_HOME\" -a -x \"$JAVA_HOME/bin/java\" ]; then\n    echo reusing JAVA_HOME $JAVA_HOME\n  else\n    if which dpkg &> /dev/null; then\n      apt-get-update && \\\n          PACKAGE=$(apt-cache search --names-only '^openjdk-.-jdk$' | sort -r | cut -d' ' -f1 | head -1) && \\\n          [ ! -z \"$PACKAGE\" ] && \\\n          {  apt-get-install $PACKAGE-headless || apt-get-install $PACKAGE; }\n    elif which rpm &> /dev/null; then\n      PACKAGE=$(repoquery --qf='%{name}' --pkgnarrow=available 'java-*-openjdk-devel' | sort -r | head -1) && \\\n        [ ! -z \"$PACKAGE\" ] && \\\n        yum-install $PACKAGE\n    else\n      abort \"we only support apt-get and yum right now... please contribute\"\n    fi\n    findOpenJDK\n    if [ -n \"$JAVA_HOME\" ]; then\n      echo installed JAVA_HOME $JAVA_HOME\n    else\n      abort \"JDK installation failed\"\n    fi\n  fi\n  rm -rf /usr/local/jdk\n  ln -Fs $JAVA_HOME /usr/local/jdk\n  /usr/local/jdk/bin/java -version || abort \"cannot run java\"\n  setupJavaHomeInProfile\n}\n\nEND_OF_JCLOUDS_SCRIPT\n   \n   # add desired commands from the user\n   cat >> $INSTANCE_HOME/runScriptWithCreds.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\tcd $INSTANCE_HOME\n\trm -f $INSTANCE_HOME/rc\n\ttrap 'echo $?>$INSTANCE_HOME/rc' 0 1 2 3 15\n\tsetupPublicCurl || exit 1\n\tinstallOpenJDK || exit 1\n\t\nEND_OF_JCLOUDS_SCRIPT\n   \n   # add runscript footer\n   cat >> $INSTANCE_HOME/runScriptWithCreds.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\texit $?\n\t\nEND_OF_JCLOUDS_SCRIPT\n   \n   chmod u+x $INSTANCE_HOME/runScriptWithCreds.sh\n   ;;\nstatus)\n   default || exit 1\n   findPid $INSTANCE_NAME || exit 1\n   echo $FOUND_PID\n   ;;\nstop)\n   default || exit 1\n   findPid $INSTANCE_NAME || exit 1\n   [ -n \"$FOUND_PID\" ]  && {\n      echo stopping $FOUND_PID\n      kill -9 $FOUND_PID\n   }\n   ;;\nstart)\n   default || exit 1\n   forget $INSTANCE_NAME $INSTANCE_HOME/$INSTANCE_NAME.sh $LOG_DIR || exit 1\n   ;;\nstdout)\n   default || exit 1\n   cat $LOG_DIR/stdout.log\n   ;;\nstderr)\n   default || exit 1\n   cat $LOG_DIR/stderr.log\n   ;;\nexitstatus)\n   default || exit 1\n   [ -f $LOG_DIR/rc ] && cat $LOG_DIR/rc;;\ntail)\n   default || exit 1\n   tail $LOG_DIR/stdout.log\n   ;;\ntailerr)\n   default || exit 1\n   tail $LOG_DIR/stderr.log\n   ;;\nrun)\n   default || exit 1\n   $INSTANCE_HOME/$INSTANCE_NAME.sh\n   ;;\nesac\nexit $?\n"
  },
  {
    "path": "compute/src/test/resources/runscript_adminUpdate.sh",
    "content": "#!/bin/bash\nset +u\nshopt -s xpg_echo\nshopt -s expand_aliases\nunset PATH JAVA_HOME LD_LIBRARY_PATH\nfunction abort {\n   echo \"aborting: $@\" 1>&2\n   exit 1\n}\nfunction default {\n   export INSTANCE_NAME=\"adminUpdate\"\nexport INSTANCE_HOME=\"/tmp/adminUpdate\"\nexport LOG_DIR=\"$INSTANCE_HOME\"\n   return $?\n}\nfunction adminUpdate {\n      return $?\n}\nfunction findPid {\n   unset FOUND_PID;\n   [ $# -eq 1 ] || {\n      abort \"findPid requires a parameter of pattern to match\"\n      return 1\n   }\n   local PATTERN=\"$1\"; shift\n   local _FOUND=`ps auxwww|grep \"$PATTERN\"|grep -v \" $0\"|grep -v grep|grep -v $$|awk '{print $2}'`\n   [ -n \"$_FOUND\" ] && {\n      export FOUND_PID=$_FOUND\n      return 0\n   } || {\n      return 1\n   }\n}\nfunction forget {\n   unset FOUND_PID;\n   [ $# -eq 3 ] || {\n      abort \"forget requires parameters INSTANCE_NAME SCRIPT LOG_DIR\"\n      return 1\n   }\n   local INSTANCE_NAME=\"$1\"; shift\n   local SCRIPT=\"$1\"; shift\n   local LOG_DIR=\"$1\"; shift\n   mkdir -p $LOG_DIR\n   findPid $INSTANCE_NAME\n   [ -n \"$FOUND_PID\" -a -f $LOG_DIR/stdout.log ] && {\n      echo $INSTANCE_NAME already running pid $FOUND_PID\n      return 1;\n   } || {\n      nohup $SCRIPT >$LOG_DIR/stdout.log 2>$LOG_DIR/stderr.log &\n      RETURN=$?\n      # this is generally followed by findPid, so we shouldn't exit \n      # immediately as the proc may not have registered in ps, yet\n      test $RETURN && sleep 1\n      return $RETURN;\n   }\n}\nexport PATH=/usr/ucb/bin:/bin:/sbin:/usr/bin:/usr/sbin\ncase $1 in\ninit)\n   default || exit 1\n   adminUpdate || exit 1\n   mkdir -p $INSTANCE_HOME\n   \n   # create runscript header\n   cat > $INSTANCE_HOME/adminUpdate.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\t#!/bin/bash\n\tset +u\n\tshopt -s xpg_echo\n\tshopt -s expand_aliases\n\t\n\tPROMPT_COMMAND='echo -ne \\\"\\033]0;adminUpdate\\007\\\"'\n\texport PATH=/usr/ucb/bin:/bin:/sbin:/usr/bin:/usr/sbin\n\n\texport INSTANCE_NAME='adminUpdate'\nEND_OF_JCLOUDS_SCRIPT\n   cat >> $INSTANCE_HOME/adminUpdate.sh <<-END_OF_JCLOUDS_SCRIPT\n\texport INSTANCE_NAME='$INSTANCE_NAME'\n\texport INSTANCE_HOME='$INSTANCE_HOME'\n\texport LOG_DIR='$LOG_DIR'\nEND_OF_JCLOUDS_SCRIPT\n   \n   # add desired commands from the user\n   cat >> $INSTANCE_HOME/adminUpdate.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\tcd $INSTANCE_HOME\n\trm -f $INSTANCE_HOME/rc\n\ttrap 'echo $?>$INSTANCE_HOME/rc' 0 1 2 3 15\n\tcat > /etc/sudoers <<-'END_OF_JCLOUDS_FILE'\n\t\tDefaults    env_reset\n\t\tDefaults    secure_path=\"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\"\n\t\troot ALL = (ALL) ALL\n\t\t%wheel ALL = (ALL) NOPASSWD:ALL\n\tEND_OF_JCLOUDS_FILE\n\tchmod 0440 /etc/sudoers\n\tmkdir -p /over/ridden\n\tchmod 0755 /over/ridden\n\tgetent group wheel || groupadd -f wheel\n\tuseradd -c 'foo' -s /bin/bash -g wheel -m  -d /over/ridden/foo -p 'crypt(randompassword)' foo\n\tmkdir -p /over/ridden/foo/.ssh\n\tcat >> /over/ridden/foo/.ssh/authorized_keys <<-'END_OF_JCLOUDS_FILE'\n\t\tpublicKey\n\tEND_OF_JCLOUDS_FILE\n\tchmod 600 /over/ridden/foo/.ssh/authorized_keys\n\tchown -R foo /over/ridden/foo/.ssh\n\tchown -R foo /over/ridden/foo\n\texec 3<> /etc/ssh/sshd_config && awk -v TEXT=\"PasswordAuthentication no\n\tPermitRootLogin no\n\t\" 'BEGIN {print TEXT}{print}' /etc/ssh/sshd_config >&3\n\thash service 2>&- && service ssh reload 2>&- || service sshd reload 2>&- || /etc/init.d/ssh* reload\n\tawk -v user=^${SUDO_USER:=${USER}}: -v password='crypt(randompassword)' 'BEGIN { FS=OFS=\":\" } $0 ~ user { $2 = password } 1' /etc/shadow >/etc/shadow.${SUDO_USER:=${USER}}\n\ttest -f /etc/shadow.${SUDO_USER:=${USER}} && mv /etc/shadow.${SUDO_USER:=${USER}} /etc/shadow\n\t\nEND_OF_JCLOUDS_SCRIPT\n   \n   # add runscript footer\n   cat >> $INSTANCE_HOME/adminUpdate.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\texit $?\n\t\nEND_OF_JCLOUDS_SCRIPT\n   \n   chmod u+x $INSTANCE_HOME/adminUpdate.sh\n   ;;\nstatus)\n   default || exit 1\n   findPid $INSTANCE_NAME || exit 1\n   echo $FOUND_PID\n   ;;\nstop)\n   default || exit 1\n   findPid $INSTANCE_NAME || exit 1\n   [ -n \"$FOUND_PID\" ]  && {\n      echo stopping $FOUND_PID\n      kill -9 $FOUND_PID\n   }\n   ;;\nstart)\n   default || exit 1\n   forget $INSTANCE_NAME $INSTANCE_HOME/$INSTANCE_NAME.sh $LOG_DIR || exit 1\n   ;;\nstdout)\n   default || exit 1\n   cat $LOG_DIR/stdout.log\n   ;;\nstderr)\n   default || exit 1\n   cat $LOG_DIR/stderr.log\n   ;;\nexitstatus)\n   default || exit 1\n   [ -f $LOG_DIR/rc ] && cat $LOG_DIR/rc;;\ntail)\n   default || exit 1\n   tail $LOG_DIR/stdout.log\n   ;;\ntailerr)\n   default || exit 1\n   tail $LOG_DIR/stderr.log\n   ;;\nrun)\n   default || exit 1\n   $INSTANCE_HOME/$INSTANCE_NAME.sh\n   ;;\nesac\nexit $?\n"
  },
  {
    "path": "core/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.*;version=${project.version};-noimport:=true\n\nBundle-Activator: org.jclouds.osgi.Activator\n\n-includeresource: \\\n    lib/gson-${gson.version}.jar=gson-${gson.version}.jar;lib:=true\n\n-exportcontents: \\\n    com.google.gson, \\\n    com.google.gson.annotations, \\\n    com.google.gson.reflect, \\\n    com.google.gson.stream, \\\n    com.google.gson.internal;version=${gson.version}, \\\n    com.google.gson.internal.bind;version=${gson.version}, \\\n    com.google.gson.internal.bind.util;version=${gson.version}, \\\n    com.google.gson.internal.reflect;version=${gson.version}\n"
  },
  {
    "path": "core/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <artifactId>jclouds-project</artifactId>\n    <groupId>org.apache.jclouds</groupId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../project/pom.xml</relativePath>\n  </parent>\n  <artifactId>jclouds-core</artifactId>\n  <name>jclouds Components Core</name>\n  <description>Core components to access jclouds services</description>\n\n  <scm>\n    <connection>scm:svn:http://jclouds.googlecode.com/svn/trunk</connection>\n    <developerConnection>scm:svn:https://jclouds.googlecode.com/svn/trunk</developerConnection>\n    <url>http://jclouds.googlecode.com/svn/trunk</url>\n    <tag>HEAD</tag>\n  </scm>\n\n  <dependencies>\n    <dependency>\n      <groupId>com.google.code.gson</groupId>\n      <artifactId>gson</artifactId>\n    </dependency>\n    <dependency>\n      <groupId>com.google.guava</groupId>\n      <artifactId>guava</artifactId>\n    </dependency>\n    <dependency>\n      <groupId>com.google.inject</groupId>\n      <artifactId>guice</artifactId>\n    </dependency>\n    <dependency>\n      <groupId>com.google.inject.extensions</groupId>\n      <artifactId>guice-assistedinject</artifactId>\n    </dependency>\n    <dependency>\n      <groupId>jakarta.ws.rs</groupId>\n      <artifactId>jakarta.ws.rs-api</artifactId>\n    </dependency>\n    <dependency>\n      <groupId>jakarta.annotation</groupId>\n      <artifactId>jakarta.annotation-api</artifactId>\n    </dependency>\n    <dependency>\n      <groupId>jakarta.inject</groupId>\n      <artifactId>jakarta.inject-api</artifactId>\n    </dependency>\n    <dependency>\n      <groupId>jakarta.xml.bind</groupId>\n      <artifactId>jakarta.xml.bind-api</artifactId>\n    </dependency>\n    <dependency>\n      <groupId>org.glassfish.jaxb</groupId>\n      <artifactId>jaxb-runtime</artifactId>\n    </dependency>\n    <dependency>\n      <groupId>org.osgi</groupId>\n      <artifactId>org.osgi.core</artifactId>\n      <scope>provided</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.osgi</groupId>\n      <artifactId>osgi.cmpn</artifactId>\n      <scope>provided</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n    <dependency>\n      <groupId>org.gaul</groupId>\n      <artifactId>modernizer-maven-annotations</artifactId>\n      <optional>true</optional>\n    </dependency>\n    <dependency>\n      <groupId>org.eclipse.jetty</groupId>\n      <artifactId>jetty-security</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.squareup.okhttp3</groupId>\n      <artifactId>mockwebserver</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.squareup.okhttp3</groupId>\n      <artifactId>okhttp-tls</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.value</groupId>\n      <artifactId>auto-value</artifactId>\n      <scope>test</scope>\n    </dependency>\n  </dependencies>\n\n  <build>\n    <plugins>\n      <plugin>\n        <groupId>org.apache.maven.plugins</groupId>\n        <artifactId>maven-jar-plugin</artifactId>\n        <executions>\n          <execution>\n            <goals>\n              <goal>test-jar</goal>\n            </goals>\n          </execution>\n        </executions>\n        <configuration>\n          <!--\n              These files are excluded to avoid corrupting the classpath with ProviderMetadata implementation\n              classes that should only be available when running the core tests.\n          -->\n          <excludes>\n            <exclude>META-INF/services/</exclude>\n            <exclude>org/jclouds/providers/ProvidersTest.class</exclude>\n          </excludes>\n        </configuration>\n      </plugin>\n    </plugins>\n  </build>\n</project>\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/Constants.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds;\n\n\nimport org.jclouds.location.reference.LocationConstants;\n\n/**\n * Constants used in jclouds services.\n */\npublic final class Constants {\n   /**\n    * Integer property. default (0)\n    * <p/>\n    * Amount of threads servicing the user requests and transformations\n    */\n   public static final String PROPERTY_USER_THREADS = \"jclouds.user-threads\";\n\n   /**\n    * Integer property. default (20)\n    * <p/>\n    * Amount of threads servicing the I/O of http connections.\n    *\n    * @deprecated No longer used. Will be removed in jclouds v2\n    */\n   @Deprecated\n   public static final String PROPERTY_IO_WORKER_THREADS = \"jclouds.io-worker-threads\";\n\n   /**\n    * Integer property. default (10)\n    * <p/>\n    * Amount of threads servicing scheduled tasks.\n    */\n   public static final String PROPERTY_SCHEDULER_THREADS = \"jclouds.scheduler-threads\";\n\n   /**\n    * Integer property. default (20)\n    * <p/>\n    * Limits the amount of connections per context.\n    */\n   public static final String PROPERTY_MAX_CONNECTIONS_PER_CONTEXT = \"jclouds.max-connections-per-context\";\n\n   /**\n    * Integer property. default (0)\n    * <p/>\n    * Limits the amount of connections per host. 0 means indirectly limited by\n    * {@link #PROPERTY_MAX_CONNECTIONS_PER_CONTEXT}.\n    */\n   public static final String PROPERTY_MAX_CONNECTIONS_PER_HOST = \"jclouds.max-connections-per-host\";\n\n   /**\n    * Integer property. default (2)\n    * <p/>\n    * Maximum amount of http session failures before a pool is disabled.\n    */\n   public static final String PROPERTY_MAX_SESSION_FAILURES = \"jclouds.max-session-failures\";\n   /**\n    * Integer property. default (75)\n    * <p/>\n    * Maximum amount of times to re_use an http connection. Services like Amazon S3 throw errors if\n    * connections are reused too many times.\n    */\n   public static final String PROPERTY_MAX_CONNECTION_REUSE = \"jclouds.max-connection-reuse\";\n\n   /**\n    * int property. default (60000)\n    * <p/>\n    * How many milliseconds to wait before a socket connection times out. 0 means infinity.\n    */\n   public static final String PROPERTY_SO_TIMEOUT = \"jclouds.so-timeout\";\n\n   /**\n    * Long property. default (60000)\n    * <p/>\n    * How many milliseconds to wait before a connection times out. 0 means infinity.\n    */\n   public static final String PROPERTY_CONNECTION_TIMEOUT = \"jclouds.connection-timeout\";\n\n   /**\n    * Long property. default (60)\n    * <p/>\n    * How many seconds to wait before creating a new session\n    */\n   public static final String PROPERTY_SESSION_INTERVAL = \"jclouds.session-interval\";\n\n   /**\n    * Boolean property.\n    * <p/>\n    * Whether or not to attempt to use the proxy setup from the underlying operating system.\n    * Defaults to false.\n    * Only considered if {@link #PROPERTY_PROXY_ENABLE_JVM_PROXY} is false\n    * and {@link #PROPERTY_PROXY_HOST} is not supplied.\n    * Due to how Java's <code>java.net.useSystemProxies</code> is handled,\n    * this may have limited effectiveness.\n    * @deprecated in 2.0.0, replaced by {@link #PROPERTY_PROXY_ENABLE_JVM_PROXY} does what this intended but better\n    */\n   @Deprecated\n   // deprecated because:  the impl attempts to set the corresponding JVM system property\n   // but that is documented to have no effect if set after system startup;\n   // see e.g. https://docs.oracle.com/javase/7/docs/api/java/net/doc-files/net-properties.html\n   public static final String PROPERTY_PROXY_SYSTEM = \"jclouds.use-system-proxy\";\n\n   /**\n    * Boolean property.\n    * <p/>\n    * Whether or not jclouds is permitted to use the default proxy detected by the JVM\n    * and configured there using the usual Java settings:\n    * <ul>\n    * <li> <code>java.net.useSystemProxies</code>\n    * <li> <code>java.net.httpProxyHost</code>\n    * <li> <code>java.net.httpProxyPort</code>\n    * </ul>\n    * <p/>\n    * Defaults to true so that the Java standard way of setting proxies can be used.\n    * However if {@link #PROPERTY_PROXY_HOST} is set that will always take priority\n    * when jclouds looks for a proxy.\n    * If this property is explicitly set <code>false</code>,\n    * then jclouds will not use a proxy irrespective of the <code>java.net.*</code> settings,\n    * unless {@link #PROPERTY_PROXY_HOST} is set or {@link #PROPERTY_PROXY_SYSTEM} is true.\n    */\n   public static final String PROPERTY_PROXY_ENABLE_JVM_PROXY = \"jclouds.enable-jvm-proxy\";\n\n   /**\n    * String property.\n    * <p/>\n    *Explicitly sets the host name of a proxy server.\n    */\n   public static final String PROPERTY_PROXY_HOST = \"jclouds.proxy-host\";\n\n   /**\n    * Integer property. default is 80 when {@link #PROPERTY_PROXY_TYPE} is\n    * {@code HTTP}, and 1080 when {@link #PROPERTY_PROXY_TYPE} is {@code SOCKS}.\n    * <p/>\n    * Explicitly sets the port number of a proxy server.\n    */\n   public static final String PROPERTY_PROXY_PORT = \"jclouds.proxy-port\";\n\n   /**\n    * String property. default {@code HTTP}, valid options: {@code HTTP}, {@code SOCKS}.\n    * <p/>\n    * Explicitly sets the type of a proxy server.\n    * \n    * @see Proxy.Type\n    */\n   public static final String PROPERTY_PROXY_TYPE = \"jclouds.proxy-type\";\n   \n   /**\n    * String property.\n    * <p/>\n    * Explicitly sets the user name credential for proxy authentication.\n    * This only applies when {@link #PROPERTY_PROXY_HOST} is supplied.\n    */\n   public static final String PROPERTY_PROXY_USER = \"jclouds.proxy-user\";\n   \n   /**\n    * String property.\n    * <p/>\n    * Explicitly sets the password credential for proxy authentication.\n    * This only applies when {@link #PROPERTY_PROXY_HOST} is supplied.\n    */\n   public static final String PROPERTY_PROXY_PASSWORD = \"jclouds.proxy-password\";\n\n   /**\n    * Boolean property. Default true.\n    * <p/>\n    * If a proxy server is configured, it will be used for all types of schemes.\n    * Set to false to not use a proxy server for sockets (such as ssh access).\n    */\n   public static final String PROPERTY_PROXY_FOR_SOCKETS = \"jclouds.proxy-for-sockets\";\n\n   /**\n    * Integer property.\n    * <p/>\n    * Commands are retried, if the problem on the server side was a resolvable conflict. However,\n    * the maximum tries of a single command is bounded.\n    */\n   public static final String PROPERTY_MAX_RETRIES = \"jclouds.max-retries\";\n   /**\n    * Long property.\n    * <p/>\n    * Commands are retried, if the problem on the server side was a resolvable conflict. However,\n    * the maximum tries of a single command is bounded. If {@link #PROPERTY_MAX_RETRIES} is greater\n    * than zero, this property is used to determine the start delay. The delay is based on exponential\n    * backoff algorithm. Default value for this property is 50 milliseconds.\n    */\n   public static final String PROPERTY_RETRY_DELAY_START = \"jclouds.retries-delay-start\";\n   /**\n    * Integer property.\n    * <p/>\n    * Commands are limited to only a certain amount of redirects.\n    */\n   public static final String PROPERTY_MAX_REDIRECTS = \"jclouds.max-redirects\";\n   /**\n    * Long property.\n    * <p/>\n    * Maximum duration in milliseconds a single request can take before throwing an exception.\n    */\n   public static final String PROPERTY_REQUEST_TIMEOUT = \"jclouds.request-timeout\";\n   /**\n    * Boolean property.\n    * <p/>\n    * allow mismatch between hostname and ssl certificate. Set to true in DNS_based services like\n    * Amazon S3.\n    */\n   public static final String PROPERTY_RELAX_HOSTNAME = \"jclouds.relax-hostname\";\n   /**\n    * Boolean property.\n    * <p/>\n    * trust self-signed certs\n    */\n   public static final String PROPERTY_TRUST_ALL_CERTS = \"jclouds.trust-all-certs\";\n   /**\n    * Boolean property.\n    * <p/>\n    * true to allow logging of sensitive information like passwords in the wire log\n    * default value is false\n    */\n   public static final String PROPERTY_LOGGER_WIRE_LOG_SENSITIVE_INFO = \"jclouds.wire.log.sensitive\";\n   /**\n    * Name of the logger that records all http headers from the client and the server.\n    */\n   public static final String LOGGER_HTTP_HEADERS = \"jclouds.headers\";\n   /**\n    * Name of the logger that records the content sent to and from the server.\n    */\n   public static final String LOGGER_HTTP_WIRE = \"jclouds.wire\";\n   /**\n    * Name of the logger that records the steps of the request signing process of the HTTP_service.\n    */\n   public static final String LOGGER_SIGNATURE = \"jclouds.signature\";\n\n   /**\n    * String property.\n    * <p/>\n    * Explicitly identifies a provider of an api\n    */\n   public static final String PROPERTY_PROVIDER = \"jclouds.provider\";\n\n   /**\n    * String property.\n    * <p/>\n    * Explicitly identifies the name of a product that a provider may run\n    */\n   public static final String PROPERTY_API = \"jclouds.api\";\n\n   /**\n    * String property. default empty string\n    * <p/>\n    * Explicitly identifies the version of an api.\n    */\n   public static final String PROPERTY_API_VERSION = \"jclouds.api-version\";\n\n   /**\n    * String property.\n    * <p/>\n    * Explicitly identifies the build that the server jclouds connects to is running.\n    * \n    * For example, for virtualbox, the api version may be {@code 4.1.8} while the build version is\n    * {@code 4.1.8r75467}.\n    */\n   public static final String PROPERTY_BUILD_VERSION = \"jclouds.build-version\";\n   \n   /**\n    * String property.\n    * <p/>\n    * Explicitly identifies the most top-level endpoint to a service provider. This helps\n    * differentiate two providers of the same api, or a different environments providing the same\n    * api.\n    */\n   public static final String PROPERTY_ENDPOINT = \"jclouds.endpoint\";\n\n   /**\n    * String property.\n    * <p/>\n    * Explicitly sets the login identity into a provider\n    */\n   public static final String PROPERTY_IDENTITY = \"jclouds.identity\";\n\n   /**\n    * String property. default(\"\")\n    * <p/>\n    * comma-delimited iso 3166 codes; ex. US-CA,US\n    * \n    * @see Location#getIso3166Codes\n    */\n   public static final String PROPERTY_ISO3166_CODES = \"jclouds.\" + LocationConstants.ISO3166_CODES;\n\n   /**\n    * String property.\n    * <p/>\n    * Explicitly sets the secret, which when combined with the identity, will create an\n    * authenticated subject or session\n    */\n   public static final String PROPERTY_CREDENTIAL = \"jclouds.credential\";\n\n   /**\n    * Long properties\n    * <p/>\n    * Overrides timeouts on sync interfaces. Timeout value is in ms.\n    * Here's an example of an override for a single method:\n    * <p/>\n    * <code>\n    * #10 seconds <br/>\n    * jclouds.timeouts.S3Client.bucketExists=10000\n    * </code>\n    * <p/>\n    * Or for all methods:\n    * <p/>\n    * <code>\n    * jclouds.timeouts.GridServerClient = 350000\n    * </code>\n    */\n   public static final String PROPERTY_TIMEOUTS_PREFIX = \"jclouds.timeouts.\";\n\n   /**\n    * Integer property. Default (32768).\n    * <p/>\n    * Buffer size for socket write (currently honored only by the default\n    * Java URL HTTP client, JavaUrlHttpCommandExcecutorService).\n    */\n   public static final String PROPERTY_OUTPUT_SOCKET_BUFFER_SIZE = \"jclouds.output-socket-buffer-size\";\n\n   /**\n    * Boolean property. Default (true).\n    * <p/>\n    * Configures the response parsers to pretty print the payload when possible. \n    */\n   public static final String PROPERTY_PRETTY_PRINT_PAYLOADS = \"jclouds.payloads.pretty-print\";\n\n   /**\n    * When true, strip the Expect: 100-continue header. Useful when interacting with\n    * providers that don't properly support Expect headers. Defaults to false.\n    */\n   public static final String PROPERTY_STRIP_EXPECT_HEADER = \"jclouds.strip-expect-header\";\n\n   /**\n    * String property.\n    * <p/>\n    * This will override the user agent header in http request.\n    */\n   public static final String PROPERTY_USER_AGENT = \"jclouds.user-agent\";\n\n   /**\n    * When true, add the Connection: close header. Useful when interacting with\n    * providers that don't properly support persistent connections. Defaults to false.\n    */\n   public static final String PROPERTY_CONNECTION_CLOSE_HEADER = \"jclouds.connection-close-header\";\n\n   /**\n    * The maximum number of blob deletes happening in parallel at any point in time.\n    */\n   public static final String PROPERTY_MAX_PARALLEL_DELETES = \"jclouds.max-parallel-deletes\";\n\n   /** Comma-separated list of methods considered idempotent for purposes of retries.  By default jclouds uses DELETE,GET,HEAD,OPTIONS,PUT. */\n   public static final String PROPERTY_IDEMPOTENT_METHODS = \"jclouds.idempotent-methods\";\n   \n   /**\n    * Maximum amount of time (in milliseconds) a request will wait until retrying if\n    * the rate limit is exhausted.\n    * <p>\n    * Default value: 2 minutes.\n    */\n   public static final String PROPERTY_MAX_RATE_LIMIT_WAIT = \"jclouds.max-ratelimit-wait\";\n   \n   /**\n    * Boolean property.\n    * <p/>\n    * When true, the proxy server type is HTTPS i.e HTTP and SSL\n    * \n    */\n   public static final String PROPERTY_PROXY_ENABLE_SSL_PROXY = \"jclouds.enable-ssl-proxy\";\n\n   private Constants() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/Context.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds;\n\nimport java.io.Closeable;\n\nimport org.jclouds.domain.Location;\nimport org.jclouds.internal.ContextImpl;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.rest.Utils;\n\nimport com.google.inject.ImplementedBy;\n\n/**\n * Represents an authenticated context to the cloud.\n * \n * <h2>Note</h2> Please issue {@link #close()} when you are finished with this context in order to\n * release resources.\n */\n@ImplementedBy(ContextImpl.class)\npublic interface Context extends Location, Closeable {\n\n  /**\n   * Identifies the Context. This is a unique name optionally specified by the user and safe to index on.\n   * The purpose of this property is to provide means to distinct between multiple contexts, without having to check\n   * multiple properties or have explicit knowledge of how the context was created.\n   * @return\n   */\n   String getName();\n\n   /**\n    * @return the providerMetadata used to create this context\n    * @see ContextBuilder#newBuilder(org.jclouds.providers.ProviderMetadata)\n    */\n   ProviderMetadata getProviderMetadata();\n\n   /**\n    * @return the current login user, access key, email, or whatever the 'identity' field was building the context.\n    * @see ApiMetadata#getDefaultIdentity\n    */\n   String getIdentity();\n\n   Utils utils();\n\n   /**\n    * Closes all connections, including executor service\n    */\n   @Override\n   void close();\n\n   /**\n    * @return true if context open\n    */\n   boolean isOpen();\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/ContextBuilder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds;\n\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Predicates.containsPattern;\nimport static com.google.common.base.Predicates.instanceOf;\nimport static com.google.common.base.Predicates.not;\nimport static com.google.common.base.Predicates.notNull;\nimport static com.google.common.base.Throwables.propagate;\nimport static com.google.common.collect.Iterables.addAll;\nimport static com.google.common.collect.Iterables.any;\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.find;\nimport static com.google.common.collect.Iterables.transform;\nimport static com.google.common.collect.Lists.newArrayList;\nimport static com.google.common.collect.Lists.newArrayListWithCapacity;\nimport static com.google.common.collect.Maps.filterKeys;\nimport static com.google.common.util.concurrent.MoreExecutors.newDirectExecutorService;\nimport static org.jclouds.Constants.PROPERTY_API;\nimport static org.jclouds.Constants.PROPERTY_API_VERSION;\nimport static org.jclouds.Constants.PROPERTY_BUILD_VERSION;\nimport static org.jclouds.Constants.PROPERTY_CREDENTIAL;\nimport static org.jclouds.Constants.PROPERTY_ENDPOINT;\nimport static org.jclouds.Constants.PROPERTY_IDENTITY;\nimport static org.jclouds.Constants.PROPERTY_ISO3166_CODES;\nimport static org.jclouds.Constants.PROPERTY_PROVIDER;\nimport static org.jclouds.reflect.Reflection2.typeToken;\nimport static org.jclouds.rest.config.BinderUtils.bindHttpApi;\nimport static org.jclouds.util.Throwables2.propagateAuthorizationOrOriginalException;\n\nimport java.io.Closeable;\nimport java.lang.reflect.InvocationTargetException;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.apis.Apis;\nimport org.jclouds.concurrent.SingleThreaded;\nimport org.jclouds.concurrent.config.ConfiguresExecutorService;\nimport org.jclouds.concurrent.config.ExecutorServiceModule;\nimport org.jclouds.config.BindApiContextWithWildcardExtendsExplicitAndRawType;\nimport org.jclouds.config.BindNameToContext;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.events.config.ConfiguresEventBus;\nimport org.jclouds.events.config.EventBusModule;\nimport org.jclouds.functions.ExpandProperties;\nimport org.jclouds.http.config.ConfiguresHttpCommandExecutorService;\nimport org.jclouds.http.config.JavaUrlHttpCommandExecutorServiceModule;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.lifecycle.config.LifeCycleModule;\nimport org.jclouds.logging.config.LoggingModule;\nimport org.jclouds.logging.jdk.config.JDKLoggingModule;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.Providers;\nimport org.jclouds.providers.config.BindProviderMetadataContextAndCredentials;\nimport org.jclouds.providers.internal.UpdateProviderMetadataFromProperties;\nimport org.jclouds.reflect.Invocation;\nimport org.jclouds.rest.ApiContext;\nimport org.jclouds.rest.ConfiguresCredentialStore;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.HttpApiMetadata;\nimport org.jclouds.rest.HttpClient;\nimport org.jclouds.rest.config.CredentialStoreModule;\nimport org.jclouds.rest.config.HttpApiModule;\nimport org.jclouds.rest.config.RestModule;\nimport org.jclouds.rest.internal.InvokeHttpMethod;\nimport org.jclouds.util.TypeTokenUtils;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Function;\nimport com.google.common.base.Joiner;\nimport com.google.common.base.Objects;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Splitter;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableMultimap.Builder;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.reflect.TypeToken;\nimport com.google.common.util.concurrent.ExecutionList;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport com.google.inject.Key;\nimport com.google.inject.Module;\nimport com.google.inject.Stage;\nimport com.google.inject.TypeLiteral;\n\n/**\n * Creates {@link Context} or {@link Injector} configured to an api and\n * endpoint. Alternatively, this can be used to make a portable {@link View} of\n * that api.\n * \n * <br/>\n * ex. to build a {@code Api} on a particular endpoint using the typed\n * interface\n * \n * <pre>\n * api = ContextBuilder.newBuilder(new NovaApiMetadata())\n *                     .endpoint(\"http://10.10.10.10:5000/v2.0\")\n *                     .credentials(user, pass)\n *                     .buildApi(NovaApi.class);\n * </pre>\n * \n * <br/>\n * ex. to build a {@link View} of a particular backend context, looked up by\n * key.\n * \n * <pre>\n * context = ContextBuilder.newBuilder(\"aws-s3\")\n *                         .credentials(apikey, secret)\n *                         .buildView(BlobStoreContext.class);\n * </pre>\n * \n * <h4>Assumptions</h4>\n * \n * Threadsafe objects will be bound as singletons to the Injector or Context\n * provided.\n * <p/>\n * If no <code>Module</code>s are specified, the default\n * {@link JDKLoggingModule logging} and\n * {@link JavaUrlHttpCommandExecutorServiceModule http transports} will be\n * installed.\n * \n * @see Context\n * @see View\n * @see ApiMetadata\n * @see ProviderMetadata\n */\npublic class ContextBuilder {\n\n   private static final Stage GUICE_STAGE = Stage.PRODUCTION;\n\n   /**\n    * looks up a provider or api with the given id\n    * \n    * @param providerOrApi\n    *           id of the provider or api\n    * @return means to build a context to that provider\n    * @throws NoSuchElementException\n    *            if the id was not configured.\n    */\n   public static ContextBuilder newBuilder(String providerOrApi) throws NoSuchElementException {\n      try {\n         try {\n            return ContextBuilder.newBuilder(Providers.withId(providerOrApi));\n         } catch (NoSuchElementException e) {\n            return ContextBuilder.newBuilder(Apis.withId(providerOrApi));\n         }\n      } catch (NoSuchElementException e) {\n         Builder<String, String> builder = ImmutableMultimap.<String, String> builder();\n         builder.putAll(\"providers\", transform(Providers.all(), Providers.idFunction()));\n         builder.putAll(\"apis\", transform(Apis.all(), Apis.idFunction()));\n         throw new NoSuchElementException(String.format(\"key [%s] not in the list of providers or apis: %s\",\n                  providerOrApi, builder.build()));\n      }\n   }\n\n   public static ContextBuilder newBuilder(ApiMetadata apiMetadata) {\n      try {\n         return new ContextBuilder(apiMetadata);\n      } catch (Exception e) {\n         return propagateAuthorizationOrOriginalException(e);\n      }\n   }\n\n   public static ContextBuilder newBuilder(ProviderMetadata providerMetadata) {\n      try {\n         return new ContextBuilder(providerMetadata);\n      } catch (Exception e) {\n         return propagateAuthorizationOrOriginalException(e);\n      }\n   }\n\n   protected Optional<String> name = Optional.absent();\n   protected Optional<ProviderMetadata> providerMetadata = Optional.absent();\n   protected final String providerId;\n   protected Optional<String> endpoint = Optional.absent();\n   protected Optional<String> identity = Optional.absent();\n   protected Optional<Supplier<Credentials>> credentialsSupplierOption = Optional.absent();\n   @Nullable\n   protected String credential;\n   protected ApiMetadata apiMetadata;\n   protected String apiVersion;\n   protected String buildVersion;\n   protected Optional<Properties> overrides = Optional.absent();\n   protected List<Module> modules = newArrayListWithCapacity(3);\n\n   @Override\n   public String toString() {\n      return toStringHelper(\"\").add(\"providerMetadata\", providerMetadata).add(\"apiMetadata\", apiMetadata).toString();\n   }\n\n   protected ContextBuilder(ProviderMetadata providerMetadata) {\n      this(providerMetadata, checkNotNull(providerMetadata, \"providerMetadata\").getApiMetadata());\n   }\n\n   protected ContextBuilder(@Nullable ProviderMetadata providerMetadata, ApiMetadata apiMetadata) {\n      this.apiMetadata = checkNotNull(apiMetadata, \"apiMetadata\");\n      if (providerMetadata != null) {\n         this.providerMetadata = Optional.of(providerMetadata);\n         this.endpoint = Optional.of(providerMetadata.getEndpoint());\n         this.providerId = providerMetadata.getId();\n      } else {\n         this.endpoint = apiMetadata.getDefaultEndpoint();\n         this.providerId = apiMetadata.getId();\n      }\n      this.identity = apiMetadata.getDefaultIdentity();\n      this.credential = apiMetadata.getDefaultCredential().orNull();\n      this.apiVersion = apiMetadata.getVersion();\n      this.buildVersion = apiMetadata.getBuildVersion().or(\"\");\n   }\n\n   public ContextBuilder(ApiMetadata apiMetadata) {\n      this(null, apiMetadata);\n   }\n\n   public ContextBuilder name(String name) {\n     this.name = Optional.of(checkNotNull(name, \"name\"));\n     return this;\n   }\n\n   /**\n    * returns the current login credentials. jclouds will not cache this value. Use this when you need to change\n    * credentials at runtime.\n    */\n   public ContextBuilder credentialsSupplier(Supplier<Credentials> credentialsSupplier) {\n      this.credentialsSupplierOption = Optional.of(checkNotNull(credentialsSupplier, \"credentialsSupplier\"));\n      return this;\n   }\n   \n   /**\n    * constant value of the cloud identity and credential.\n    * \n    * @param credential (optional depending on {@link ApiMetadata#getCredentialName()}\n    */\n   public ContextBuilder credentials(String identity, @Nullable String credential) {\n      this.identity = Optional.of(checkNotNull(identity, \"identity\"));\n      this.credential = credential;\n      return this;\n   }\n\n   public ContextBuilder endpoint(String endpoint) {\n      this.endpoint = Optional.of(checkNotNull(endpoint, \"endpoint\"));\n      return this;\n   }\n\n   public ContextBuilder apiVersion(String apiVersion) {\n      this.apiVersion = checkNotNull(apiVersion, \"apiVersion\");\n      return this;\n   }\n\n   public ContextBuilder buildVersion(String buildVersion) {\n      this.buildVersion = checkNotNull(buildVersion, \"buildVersion\");\n      return this;\n   }\n\n   public ContextBuilder modules(Iterable<? extends Module> modules) {\n      addAll(this.modules, checkNotNull(modules, \"modules\"));\n      return this;\n   }\n\n   public ContextBuilder overrides(Properties overrides) {\n      this.overrides = Optional.of(checkNotNull(overrides, \"overrides\"));\n      return this;\n   }\n\n   public static String searchPropertiesForProviderScopedProperty(Properties mutable, String prov, String key) throws NoSuchElementException {\n      try {\n         return find(newArrayList(mutable.getProperty(prov + \".\" + key), mutable.getProperty(\"jclouds.\" + key)),\n                  notNull());\n      } catch (NoSuchElementException e) {\n         throw new NoSuchElementException(String.format(\"property %s.%s not present in properties: %s\", prov, key, mutable.keySet()));\n      } finally {\n         mutable.remove(prov + \".\" + key);\n         mutable.remove(\"jclouds.\" + key);\n      }\n   }\n\n   public Injector buildInjector() {\n\n      Properties unexpanded = currentStateToUnexpandedProperties();\n\n      Set<String> keysToResolve = ImmutableSet.of(PROPERTY_IDENTITY, PROPERTY_CREDENTIAL, PROPERTY_ENDPOINT,\n            PROPERTY_API, PROPERTY_API_VERSION, PROPERTY_BUILD_VERSION);\n\n      Set<String> optionalKeys;\n      if (credentialsSupplierOption.isPresent()) {\n         optionalKeys = ImmutableSet.of(PROPERTY_IDENTITY, PROPERTY_CREDENTIAL);\n      } else if (!apiMetadata.getCredentialName().isPresent()) {\n         optionalKeys = ImmutableSet.of(PROPERTY_CREDENTIAL);\n      } else {\n         optionalKeys = ImmutableSet.of();\n      }\n\n      Properties resolved = resolveProperties(unexpanded, providerId, keysToResolve, optionalKeys);\n\n      Properties expanded = new ExpandProperties().apply(resolved);\n\n      Supplier<Credentials> credentialsSupplier = buildCredentialsSupplier(expanded);\n\n      ProviderMetadata providerMetadata = new UpdateProviderMetadataFromProperties(apiMetadata, this.providerMetadata)\n            .apply(expanded);\n\n      // We use either the specified name (optional) or a hash of provider/api, endpoint, api version & identity. Hash\n      // is used to be something readable.\n      return buildInjector(name.or(String.valueOf(Objects.hashCode(providerMetadata.getId(),\n            providerMetadata.getEndpoint(), providerMetadata.getApiMetadata().getVersion(), credentialsSupplier))),\n            providerMetadata, credentialsSupplier, modules);\n   }\n\n   protected Supplier<Credentials> buildCredentialsSupplier(Properties expanded) {\n      Credentials creds = new Credentials(getAndRemove(expanded, PROPERTY_IDENTITY), getAndRemove(expanded,\n            PROPERTY_CREDENTIAL));\n\n      Supplier<Credentials> credentialsSupplier;\n      if (credentialsSupplierOption.isPresent()) {\n         credentialsSupplier = credentialsSupplierOption.get();\n      } else {\n         credentialsSupplier = Suppliers.ofInstance(creds);\n      }\n      return credentialsSupplier;\n   }\n\n   private static String getAndRemove(Properties expanded, String key) {\n      try {\n         return expanded.getProperty(key);\n      } finally {\n         expanded.remove(key);\n      }\n   }\n   \n   private Properties currentStateToUnexpandedProperties() {\n      Properties defaults = new Properties();\n      putAllAsString(apiMetadata.getDefaultProperties(), defaults);\n      defaults.setProperty(PROPERTY_PROVIDER, providerId);\n      if (providerMetadata.isPresent()) {\n         putAllAsString(providerMetadata.get().getDefaultProperties(), defaults);\n         defaults.setProperty(PROPERTY_ISO3166_CODES, Joiner.on(',').join(providerMetadata.get().getIso3166Codes()));\n      }\n      if (endpoint.isPresent())\n         defaults.setProperty(PROPERTY_ENDPOINT, endpoint.get());\n      defaults.setProperty(PROPERTY_API, apiMetadata.getName());\n      defaults.setProperty(PROPERTY_API_VERSION, apiVersion);\n      defaults.setProperty(PROPERTY_BUILD_VERSION, buildVersion);\n      if (credentialsSupplierOption.isPresent()) {\n         Credentials credentials = credentialsSupplierOption.get().get();\n         defaults.setProperty(PROPERTY_IDENTITY, credentials.identity);\n         defaults.setProperty(PROPERTY_CREDENTIAL, credentials.credential);\n      } else {\n         if (identity.isPresent())\n            defaults.setProperty(PROPERTY_IDENTITY, identity.get());\n         if (credential != null)\n            defaults.setProperty(PROPERTY_CREDENTIAL, credential);\n      }\n      if (overrides.isPresent())\n         putAllAsString(overrides.get(), defaults);\n      putAllAsString(propertiesPrefixedWithJcloudsApiOrProviderId(getSystemProperties(), apiMetadata.getId(), providerId), defaults);\n      return defaults;\n   }\n\n   private static void putAllAsString(Map<?, ?> source, Properties target) {\n      for (Map.Entry<?, ?> entry : source.entrySet()) {\n         target.setProperty(entry.getKey().toString(), entry.getValue().toString());\n      }\n   }\n\n   @VisibleForTesting\n   protected Properties getSystemProperties() {\n      return System.getProperties();\n   }\n\n   public static Injector buildInjector(String name, ProviderMetadata providerMetadata, Supplier<Credentials> creds, List<Module> inputModules) {\n      List<Module> modules = newArrayList();\n      modules.addAll(inputModules);\n      boolean apiModuleSpecifiedByUser = apiModulePresent(inputModules);\n      Iterable<Module> defaultModules = ifSpecifiedByUserDontIncludeDefaultApiModule(\n               providerMetadata.getApiMetadata(), apiModuleSpecifiedByUser);\n      addAll(modules, defaultModules);\n      addClientModuleIfNotPresent(providerMetadata.getApiMetadata(), modules);\n      addRestContextBinding(providerMetadata.getApiMetadata(), modules);\n      addLoggingModuleIfNotPresent(modules);\n      addHttpModuleIfNeededAndNotPresent(modules);\n      addExecutorServiceIfNotPresent(modules);\n      addEventBusIfNotPresent(modules);\n      addCredentialStoreIfNotPresent(modules);\n      modules.add(new LifeCycleModule());\n      modules.add(new BindProviderMetadataContextAndCredentials(providerMetadata, creds));\n      modules.add(new BindNameToContext(name));\n      Injector returnVal = Guice.createInjector(GUICE_STAGE, modules);\n      returnVal.getInstance(ExecutionList.class).execute();\n      return returnVal;\n   }\n\n   static Properties resolveProperties(Properties mutable, String providerId, Set<String> keys, Set<String> optionalKeys) throws NoSuchElementException {\n      for (String key : keys) {\n         String scopedProperty = Iterables.get(Splitter.on('.').split(key), 1);\n         try {\n            mutable.setProperty(key, searchPropertiesForProviderScopedProperty(mutable, providerId, scopedProperty));\n         } catch (NoSuchElementException e) {\n            if (!optionalKeys.contains(key))\n               throw e;\n         }\n      }\n      return mutable;\n   }\n\n   static void addRestContextBinding(ApiMetadata apiMetadata, List<Module> modules) {\n      if (apiMetadata instanceof HttpApiMetadata) {\n         try {\n            modules\n                  .add(new BindApiContextWithWildcardExtendsExplicitAndRawType(HttpApiMetadata.class.cast(apiMetadata)));\n         } catch (IllegalArgumentException ignored) {\n\n         }\n      }\n   }\n\n   static Iterable<Module> ifSpecifiedByUserDontIncludeDefaultApiModule(ApiMetadata apiMetadata,\n            boolean restModuleSpecifiedByUser) {\n      Iterable<Module> defaultModules = transform(apiMetadata.getDefaultModules(),\n               new Function<Class<? extends Module>, Module>() {\n\n                  @Override\n                  public Module apply(Class<? extends Module> arg0) {\n                     try {\n                        return arg0.getConstructor().newInstance();\n                     } catch (InstantiationException e) {\n                        throw propagate(e);\n                     } catch (IllegalAccessException e) {\n                        throw propagate(e);\n                     } catch (InvocationTargetException e) {\n                        throw propagate(e);\n                     } catch (NoSuchMethodException e) {\n                        throw propagate(e);\n                     }\n                  }\n\n               });\n      if (restModuleSpecifiedByUser)\n         defaultModules = filter(defaultModules, not(configuresApi));\n      return defaultModules;\n   }\n\n   @SuppressWarnings( { \"unchecked\" })\n   static Map<String, Object> propertiesPrefixedWithJcloudsApiOrProviderId(Properties properties, String apiId,\n            String providerId) {\n      return filterKeys(Map.class.cast(properties), containsPattern(\"^(jclouds|\" + providerId + \"|\" + apiId + \").*\"));\n   }\n\n   @VisibleForTesting\n   static void addLoggingModuleIfNotPresent(List<Module> modules) {\n      if (!any(modules, instanceOf(LoggingModule.class)))\n         modules.add(new JDKLoggingModule());\n   }\n\n   @VisibleForTesting\n   static void addHttpModuleIfNeededAndNotPresent(List<Module> modules) {\n      if (nothingConfiguresAnHttpService(modules))\n         modules.add(new JavaUrlHttpCommandExecutorServiceModule());\n   }\n\n   static boolean nothingConfiguresAnHttpService(List<Module> modules) {\n      return !any(modules, new Predicate<Module>() {\n         public boolean apply(Module input) {\n            return input.getClass().isAnnotationPresent(ConfiguresHttpCommandExecutorService.class);\n         }\n\n      });\n   }\n\n   @VisibleForTesting\n   static void addClientModuleIfNotPresent(ApiMetadata apiMetadata, List<Module> modules) {\n      if (!apiModulePresent(modules)) {\n         addClientModule(apiMetadata, modules);\n      }\n   }\n   private static boolean apiModulePresent(List<Module> modules) {\n      return any(modules, configuresApi);\n   }\n\n   private static Predicate<Module> configuresApi = new Predicate<Module>() {\n      public boolean apply(Module input) {\n         return input.getClass().isAnnotationPresent(ConfiguresHttpApi.class);\n      }\n\n   };\n\n   @SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n   static void addClientModule(ApiMetadata apiMetadata, List<Module> modules) {\n      // TODO: move this up\n      if (apiMetadata instanceof HttpApiMetadata) {\n         HttpApiMetadata api = HttpApiMetadata.class.cast(apiMetadata);\n         modules.add(new HttpApiModule(api.getApi()));\n      } else {\n         modules.add(new RestModule());\n         // Minimally bind HttpClient so that Utils works.\n         modules.add(new AbstractModule() {\n            @Override public void configure() {\n               bind(new TypeLiteral<Function<Invocation, Object>>() {\n               }).to(InvokeHttpMethod.class);\n               bindHttpApi(binder(), HttpClient.class);\n            }\n         });\n      }\n   }\n\n   @VisibleForTesting\n   static void addEventBusIfNotPresent(List<Module> modules) {\n      if (!any(modules, new Predicate<Module>() {\n         public boolean apply(Module input) {\n            return input.getClass().isAnnotationPresent(ConfiguresEventBus.class);\n         }\n      }\n\n      )) {\n         modules.add(new EventBusModule());\n      }\n   }\n\n   @VisibleForTesting\n   static void addExecutorServiceIfNotPresent(List<Module> modules) {\n      if (!any(modules, new Predicate<Module>() {\n         public boolean apply(Module input) {\n            return input.getClass().isAnnotationPresent(ConfiguresExecutorService.class);\n         }\n      }\n\n      )) {\n         if (any(modules, new Predicate<Module>() {\n            public boolean apply(Module input) {\n               return input.getClass().isAnnotationPresent(SingleThreaded.class);\n            }\n         })) {\n            modules.add(new ExecutorServiceModule(newDirectExecutorService()));\n         } else {\n            modules.add(new ExecutorServiceModule());\n         }\n      }\n   }\n\n   @VisibleForTesting\n   static void addCredentialStoreIfNotPresent(List<Module> modules) {\n      if (!any(modules, new Predicate<Module>() {\n         public boolean apply(Module input) {\n            return input.getClass().isAnnotationPresent(ConfiguresCredentialStore.class);\n         }\n      }\n\n      )) {\n         modules.add(new CredentialStoreModule());\n      }\n\n   }\n\n   /**\n    * Builds the base context for this api. Note that this may be of type {@link Closer}, if nothing\n    * else was configured via {@link ApiMetadata#getContext()}. Typically, the type returned is\n    * {@link ApiContext}\n    * \n    * @see ApiMetadata#getContext()\n    * @see #build(TypeToken)\n    */\n   @SuppressWarnings(\"unchecked\")\n   public <C extends Context> C build() {\n      return (C) build(apiMetadata.getContext());\n   }\n\n   /**\n    * @see #buildView(Class)\n    */\n   public <V extends View> V build(Class<V> viewType) {\n     return buildView(checkNotNull(viewType, \"viewType\"));\n   }\n\n   /**\n    * @see #buildView(TypeToken)\n    */\n   public <V extends View> V buildView(Class<V> viewType) {\n     return buildView(typeToken(viewType));\n   }\n   \n   /**\n    * this will build any {@link ApiMetadata#getViews() view} supported by the ApiMetadata.\n    * \n    * ex. {@code builder.build(BlobStoreContext.class) } will work, if {@code TypeToken<BlobStore>}\n    * is a configured {@link ApiMetadata#getViews() view} of this api.\n    * \n    */\n   @SuppressWarnings(\"unchecked\")\n   public <V extends View> V buildView(TypeToken<V> viewType) {\n      TypeToken<V> returnType;\n      try {\n         returnType = (TypeToken<V>) Apis.findView(apiMetadata, checkNotNull(viewType, \"viewType\"));\n      } catch (NoSuchElementException e) {\n         throw new IllegalArgumentException(String.format(\n                  \"api %s not wrappable as %s; context: %s, views: %s\", apiMetadata,\n                  viewType, apiMetadata.getContext(), apiMetadata.getViews()));\n      }\n      return (V) buildInjector().getInstance(Key.get(TypeLiteral.get(returnType.getType())));\n   }\n\n   /**\n    * this will build the {@link ApiMetadata#getContext() context} supported by the current ApiMetadata.\n    */\n   @SuppressWarnings(\"unchecked\")\n   public <C extends Context> C build(TypeToken<C> contextType) {\n      TypeToken<C> returnType = null;\n      if (TypeTokenUtils.isSupertypeOf(contextType, apiMetadata.getContext()))\n         returnType = (TypeToken<C>) apiMetadata.getContext();\n      else\n         throw new IllegalArgumentException(String.format(\"api %s not assignable from %s; context: %s\", apiMetadata,\n                  contextType, apiMetadata.getContext()));\n      return (C) buildInjector().getInstance(Key.get(TypeLiteral.get(returnType.getType())));\n   }\n\n   /**\n    * This will return the top-level interface for the api or provider.\n    * \n    * Ex. \n    * <pre>\n    * api = ContextBuilder.newBuilder(\"openstack-nova\")\n    *                     ... \n    *                     .buildApi(NovaApi.class);\n    *</pre>\n    */\n   public <A extends Closeable> A buildApi(Class<A> api) {\n      return buildApi(typeToken(api));\n   }\n\n   /**\n    * like {@link #buildApi(Class)} but permits a type-token for convenience.\n    */\n   @SuppressWarnings(\"unchecked\")\n   public <A extends Closeable> A buildApi(TypeToken<A> apiType) {\n      return (A) buildInjector().getInstance(Key.get(TypeLiteral.get(apiType.getType())));\n   }\n\n   public ApiMetadata getApiMetadata() {\n      return apiMetadata;\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/Fallback.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds;\n\nimport com.google.common.annotations.Beta;\n\n/**\n * Provides a backup value to replace an earlier exception.\n * \n * @param <V>\n *           the result type of the backup value\n * \n * @since 1.6\n */\n@Beta\npublic interface Fallback<V> {\n   /**\n    * The exception is provided so that the {@code Fallback} implementation can\n    * conditionally determine whether to propagate the exception or to attempt\n    * to recover.\n    * \n    * @param t\n    *           the exception that made the call fail.\n    */\n   V createOrPropagate(Throwable t) throws Exception;\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/Fallbacks.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Predicates.equalTo;\nimport static com.google.common.base.Predicates.in;\nimport static com.google.common.base.Throwables.propagate;\nimport static com.google.common.primitives.Ints.asList;\nimport static org.jclouds.http.HttpUtils.contains404;\nimport static org.jclouds.http.HttpUtils.returnValueOnCodeOrNull;\nimport static org.jclouds.util.Throwables2.getFirstThrowableOfType;\n\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.IterableWithMarkers;\nimport org.jclouds.collect.PagedIterable;\nimport org.jclouds.collect.PagedIterables;\nimport org.jclouds.rest.ResourceNotFoundException;\n\nimport com.google.common.base.Optional;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\n\npublic final class Fallbacks {\n   private Fallbacks() {\n   }\n\n   public static final class NullOnNotFoundOr404 implements Fallback<Object> {\n      public Object createOrPropagate(Throwable t) throws Exception {\n         return valOnNotFoundOr404(null, checkNotNull(t, \"throwable\"));\n      }\n   }\n\n   public static final class VoidOnNotFoundOr404 implements Fallback<Void> {\n      public Void createOrPropagate(Throwable t) throws Exception {\n         return valOnNotFoundOr404(null, checkNotNull(t, \"throwable\"));\n      }\n   }\n\n   public static final class TrueOnNotFoundOr404 implements Fallback<Boolean> {\n      public Boolean createOrPropagate(Throwable t) throws Exception {\n         return valOnNotFoundOr404(true, checkNotNull(t, \"throwable\"));\n      }\n   }\n\n   public static final class FalseOnNotFoundOr404 implements Fallback<Boolean> {\n      public Boolean createOrPropagate(Throwable t) throws Exception {\n         return valOnNotFoundOr404(false, checkNotNull(t, \"throwable\"));\n      }\n   }\n\n   public static final class FalseOnNotFoundOr422 implements Fallback<Boolean> {\n      public Boolean createOrPropagate(Throwable t) throws Exception {\n         if (containsResourceNotFoundException(checkNotNull(t, \"throwable\"))\n               || returnValueOnCodeOrNull(t, true, equalTo(422)) != null)\n            return false;\n         throw propagate(t);\n      }\n   }\n\n   /**\n    */\n   public static final class AbsentOn403Or404Or500 implements Fallback<Optional<Object>> {\n      public Optional<Object> createOrPropagate(Throwable t) throws Exception {\n         Boolean returnVal = returnValueOnCodeOrNull(checkNotNull(t, \"throwable\"), true, in(asList(403, 404, 500)));\n         if (returnVal != null)\n            return Optional.absent();\n         throw propagate(t);\n      }\n   }\n\n   public static final class EmptyFluentIterableOnNotFoundOr404 implements Fallback<FluentIterable<Object>> {\n      public FluentIterable<Object> createOrPropagate(Throwable t) throws Exception {\n         return valOnNotFoundOr404(FluentIterable.from(ImmutableSet.of()), checkNotNull(t, \"throwable\"));\n      }\n   }\n\n   public static final class EmptyIterableWithMarkerOnNotFoundOr404 implements Fallback<IterableWithMarker<Object>> {\n      public IterableWithMarker<Object> createOrPropagate(Throwable t) throws Exception {\n         return valOnNotFoundOr404(IterableWithMarkers.from(ImmutableSet.of()), checkNotNull(t, \"throwable\"));\n      }\n   }\n\n   public static final class EmptyPagedIterableOnNotFoundOr404 implements Fallback<PagedIterable<Object>> {\n      public PagedIterable<Object> createOrPropagate(Throwable t) throws Exception {\n         return valOnNotFoundOr404(PagedIterables.of(IterableWithMarkers.from(ImmutableSet.of())),\n               checkNotNull(t, \"throwable\"));\n      }\n   }\n\n   public static final class EmptyListOnNotFoundOr404 implements Fallback<ImmutableList<Object>> { // NO_UCD\n      public ImmutableList<Object> createOrPropagate(Throwable t) throws Exception {\n         return valOnNotFoundOr404(ImmutableList.of(), checkNotNull(t, \"throwable\"));\n      }\n   }\n\n   public static final class EmptySetOnNotFoundOr404 implements Fallback<ImmutableSet<Object>> {\n      public ImmutableSet<Object> createOrPropagate(Throwable t) throws Exception {\n         return valOnNotFoundOr404(ImmutableSet.of(), checkNotNull(t, \"throwable\"));\n      }\n   }\n\n   public static final class EmptyMapOnNotFoundOr404 implements Fallback<ImmutableMap<Object, Object>> {\n      public ImmutableMap<Object, Object> createOrPropagate(Throwable t) throws Exception {\n         return valOnNotFoundOr404(ImmutableMap.of(), checkNotNull(t, \"throwable\"));\n      }\n   }\n\n   public static final class EmptyMultimapOnNotFoundOr404 implements Fallback<ImmutableMultimap<Object, Object>> { // NO_UCD\n      public ImmutableMultimap<Object, Object> createOrPropagate(Throwable t) throws Exception {\n         return valOnNotFoundOr404(ImmutableMultimap.of(), checkNotNull(t, \"throwable\"));\n      }\n   }\n\n   public static <T> T valOnNotFoundOr404(T val, Throwable t) {\n      if (containsResourceNotFoundException(checkNotNull(t, \"throwable\")) || contains404(t))\n         return val;\n      throw propagate(t);\n   }\n\n   private static boolean containsResourceNotFoundException(Throwable from) {\n      return getFirstThrowableOfType(from, ResourceNotFoundException.class) != null;\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/JcloudsVersion.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static java.lang.String.format;\nimport static org.jclouds.util.Closeables2.closeQuietly;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.Properties;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.annotations.VisibleForTesting;\n\npublic class JcloudsVersion {\n    @VisibleForTesting\n    static final String VERSION_RESOURCE_FILE = \"META-INF/maven/org.apache.jclouds/jclouds-core/pom.properties\";\n    private static final String VERSION_PROPERTY_NAME = \"version\";\n\n    /*\n     * x.y.z or x.y.z-alpha.n or x.y.z-beta.n or x.y.z-rc.n or x.y.z-SNAPSHOT -\n     * see http://semver.org.\n     */\n    private static final Pattern SEMANTIC_VERSION_PATTERN =\n        Pattern.compile(\"(\\\\d+)\\\\.(\\\\d+)\\\\.(\\\\d+)(?:-(alpha|beta|rc)\\\\.(\\\\d+)|-SNAPSHOT)?\");\n    private static final String ALPHA_VERSION_IDENTIFIER = \"alpha\";\n    private static final String BETA_VERSION_IDENTIFIER = \"beta\";\n\n    private static final JcloudsVersion INSTANCE = new JcloudsVersion();\n\n    public final int majorVersion;\n    public final int minorVersion;\n    public final int patchVersion;\n    public final boolean alpha;\n    public final boolean beta;\n\n    /**\n     * Non-null iff {@link #alpha} is {@code true}\n     */\n    @Nullable public final Integer alphaVersion;\n\n    /**\n     * Non-null iff {@link #beta} is {@code true}\n     */\n    @Nullable public final Integer betaVersion;\n\n    public final boolean releaseCandidate;\n\n    /**\n     * Non-null iff {@link #releaseCandidate} is {@code true}\n     */\n    @Nullable public final Integer releaseCandidateVersion;\n    public final boolean snapshot;\n    private final String version;\n\n    @VisibleForTesting\n    JcloudsVersion() {\n        this(JcloudsVersion.class.getClassLoader());\n    }\n\n    @VisibleForTesting\n    JcloudsVersion(ClassLoader resourceLoader) {\n        this(readVersionPropertyFromClasspath(resourceLoader));\n    }\n\n    private static String readVersionPropertyFromClasspath(ClassLoader resourceLoader) {\n        Properties versionProperties = new Properties();\n        InputStream is = checkNotNull(resourceLoader.getResourceAsStream(VERSION_RESOURCE_FILE), VERSION_RESOURCE_FILE);\n        try {\n            versionProperties.load(is);\n        } catch (IOException exception) {\n            throw new IllegalStateException(format(\"Unable to load version resource file '%s'\", VERSION_RESOURCE_FILE), exception);\n        } finally {\n            closeQuietly(is);\n        }\n        return checkNotNull(versionProperties.getProperty(VERSION_PROPERTY_NAME), VERSION_PROPERTY_NAME);\n    }\n\n    @VisibleForTesting\n    JcloudsVersion(String version) {\n        Matcher versionMatcher = SEMANTIC_VERSION_PATTERN.matcher(version);\n        checkArgument(versionMatcher.matches(), \"Version '%s' did not match expected pattern '%s'\", \n                version, SEMANTIC_VERSION_PATTERN);\n        this.version = version;\n        // a match will produce three or five matching groups (alpha/beta/release candidate identifier and version optional)\n        majorVersion = Integer.parseInt(versionMatcher.group(1));\n        minorVersion = Integer.parseInt(versionMatcher.group(2));\n        patchVersion = Integer.parseInt(versionMatcher.group(3));\n\n        String alphaOrBetaOrReleaseCandidateVersionIfPresent = versionMatcher.group(4);\n        if (alphaOrBetaOrReleaseCandidateVersionIfPresent != null) {\n            Integer alphaOrBetaOrReleaseCandidateVersion = Integer.valueOf(versionMatcher.group(5));\n            if (alphaOrBetaOrReleaseCandidateVersionIfPresent.equals(ALPHA_VERSION_IDENTIFIER)) {\n                alpha = true;\n                alphaVersion = alphaOrBetaOrReleaseCandidateVersion;\n                beta = false;\n                betaVersion = null;\n                releaseCandidate = false;\n                releaseCandidateVersion = null;\n            } else if (alphaOrBetaOrReleaseCandidateVersionIfPresent.equals(BETA_VERSION_IDENTIFIER)) {\n                alpha = false;\n                alphaVersion = null;\n                beta = true;\n                betaVersion = alphaOrBetaOrReleaseCandidateVersion;\n                releaseCandidate = false;\n                releaseCandidateVersion = null;\n            } else {\n                alpha = false;\n                alphaVersion = null;\n                beta = false;\n                betaVersion = null;\n                releaseCandidate = true;\n                releaseCandidateVersion = alphaOrBetaOrReleaseCandidateVersion;\n            }\n        } else {\n            alpha = false;\n            alphaVersion = null;\n            beta = false;\n            betaVersion = null;\n            releaseCandidate = false;\n            releaseCandidateVersion = null;\n        }\n\n        // endsWith(\"T\") would be cheaper but we only do this once...\n        snapshot = version.endsWith(\"-SNAPSHOT\");\n    }\n\n    @Override\n    public String toString() {\n        return version;\n    }\n\n    public static JcloudsVersion get() {\n        return INSTANCE;\n    }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/View.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds;\n\nimport java.io.Closeable;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.reflect.TypeToken;\n\n/**\n * {@link View} allows access to the provider-specific, or library-driven api\n * behind an abstraction. One backend context can support multiple views.\n * <p/>\n * For example, the {@code CloudStackContext} can be backend by both\n * {@code ComputeServiceContext} and {@code LoadBalancerServiceContext}, as the\n * api covers these features.\n */\n@Beta\npublic interface View {\n\n   /**\n    * \n    * @return type of the context powering the current one.\n    */\n   TypeToken<?> getBackendType();\n\n   /**\n    * Return an object of the specified type to allow access to the backend\n    * context. If the backend context is not assignable from the supplied type,\n    * an {@link IllegalArgumentException} is thrown.\n    * \n    * ex.\n    * <pre>\n    * ApiContext<NovaApi> backendApi = computeContext.unwrap(new TypeToken<ApiContext<NovaApi>>(){});\n    * </pre>\n    * @param type\n    *           the type of the context to be returned. The backend context must\n    *           be assignable from this type.\n    * @return an instance of the specified type\n    * @throws IllegalArgumentException\n    *            if the backend context is not assignable from the specified\n    *            class.\n    * @see #getBackendType()\n    */\n   <C extends Context> C unwrap(TypeToken<C> type) throws IllegalArgumentException;\n\n   /**\n    * shortcut for {@code unwrap(getWrappedType())}\n    * \n    * @throws ClassCastException\n    *            if the user supplied {@code C} param is not assignableFrom\n    *            {@link #getBackendType()}\n    */\n   <C extends Context> C unwrap() throws ClassCastException;\n\n   /**\n    * Unwraps the underlying api from this view.\n    *\n    * @param apiClass The class of the api to unwrap.\n    * @return The unwrapped api.\n    *\n    * @since 1.7\n    */\n   <A extends Closeable> A unwrapApi(Class<A> apiClass);\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/annotations/Name.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.annotations;\n\nimport jakarta.inject.Qualifier;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\nimport static java.lang.annotation.ElementType.ANNOTATION_TYPE;\nimport static java.lang.annotation.ElementType.FIELD;\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.ElementType.PARAMETER;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\n/**\n * Designates that this Resource qualifies an object to a context name.\n */\n@Target( { ANNOTATION_TYPE, FIELD, METHOD, PARAMETER })\n@Retention(RUNTIME)\n@Qualifier\npublic @interface Name {\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/apis/ApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.apis;\n\nimport java.net.URI;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport org.jclouds.Context;\nimport org.jclouds.View;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Optional;\nimport com.google.common.reflect.TypeToken;\nimport com.google.inject.Module;\n\n/**\n * The ApiMetadata interface allows jclouds to provide a plugin framework for\n * gathering cloud api metadata.\n * \n * @since 1.5\n */\n@Beta\npublic interface ApiMetadata {\n\n   public interface Builder<B extends Builder<B>> {\n      /**\n       * @see ApiMetadata#getId()\n       */\n      B id(String id);\n\n      /**\n       * @see ApiMetadata#getName()\n       */\n      B name(String name);\n\n      /**\n       * @see ApiMetadata#getContext()\n       */\n      B context(TypeToken<? extends Context> context);\n\n      /**\n       * @see ApiMetadata#getViews()\n       */\n      B view(Class<? extends View> view);\n      \n      /**\n       * @see ApiMetadata#getViews()\n       */\n      B view(TypeToken<? extends View> view);\n\n      /**\n       * @see ApiMetadata#getViews()\n       */\n      B views(Set<TypeToken<? extends View>> views);\n\n      /**\n       * @see ApiMetadata#getEndpointName()\n       */\n      B endpointName(String endpointName);\n\n      /**\n       * @see ApiMetadata#getIdentityName()\n       */\n      B identityName(String identityName);\n\n      /**\n       * @see ApiMetadata#getCredentialName()\n       */\n      B credentialName(@Nullable String credentialName);\n\n      /**\n       * @see ApiMetadata#getVersion()\n       */\n      B version(String version);\n\n      /**\n       * @see ApiMetadata#getBuildVersion()\n       */\n      B buildVersion(@Nullable String buildVersion);\n\n      /**\n       * @see ApiMetadata#getDefaultEndpoint()\n       */\n      B defaultEndpoint(@Nullable String defaultEndpoint);\n\n      /**\n       * @see ApiMetadata#getDefaultIdentity()\n       */\n      B defaultIdentity(@Nullable String defaultIdentity);\n\n      /**\n       * @see ApiMetadata#getDefaultCredential()\n       */\n      B defaultCredential(@Nullable String defaultCredential);\n\n      /**\n       * @see ApiMetadata#getDefaultProperties()\n       */\n      B defaultProperties(Properties defaultProperties);\n      \n      /**\n       * @see ApiMetadata#getDefaultModules()\n       */\n      B defaultModule(Class<? extends Module> defaultModule);\n\n      /**\n       * @see ApiMetadata#getDefaultModules()\n       */\n      B defaultModules(Set<Class<? extends Module>> defaultModules);\n      \n      /**\n       * @see ApiMetadata#getDocumentation()\n       */\n      B documentation(URI documentation);\n\n      ApiMetadata build();\n\n      B fromApiMetadata(ApiMetadata from);\n      \n   }\n\n   /**\n    * @see Builder\n    */\n   Builder<?> toBuilder();\n\n   /**\n    * \n    * @return the api's unique identifier (ex. ec2, openstack-nova)\n    */\n   String getId();\n\n   /**\n    * \n    * @return the name (display name) of the api (ex. EC2 Base API)\n    */\n   String getName();\n\n   /**\n    * \n    * The {@code endpointName} helps the user supply the correct data when\n    * prompted.\n    * <p/>\n    * For example, on OpenStack APIs, this could be: {@code Keystone url} <br/>\n    * For file-based apis, this could be: {@code Path of byon.yaml}\n    * <p/>\n    * Default: {@code \"https endpoint\"}\n    * <p/>\n    * \n    * @return the name (display name) of an endpoint to this api (ex. Keystone\n    *         url).\n    */\n   String getEndpointName();\n   \n   /**\n    * \n    * @return the name (display name) of an identity on this api (ex. user,\n    *         email, account, apikey, tenantId:username)\n    */\n   String getIdentityName();\n\n   /**\n    * Note: if the api doesn't need a credential, this will return absent.\n    * \n    * @return the name (display name) of a credential on this api, if it is\n    *         required (ex. password, secret, rsaKey)\n    */\n   Optional<String> getCredentialName();\n\n   /**\n    * Explicitly identifies the version of an api.\n    */\n   String getVersion();\n\n   /**\n    * Explicitly identifies the build that the server jclouds connects to is\n    * running.\n    * \n    * For example, for virtualbox, the api version may be {@code 4.1.8} while\n    * the build version is {@code 4.1.8r75467}.\n    */\n   Optional<String> getBuildVersion();\n\n   /**\n    * Explicitly identifies the most top-level endpoint to a service provider.\n    * This helps differentiate two providers of the same api, or a different\n    * environments providing the same api.\n    * \n    * <h3>note</h3>\n    * \n    * The type of endpoint is {@code String} as we permit endpoints that require\n    * variable expansion.\n    * \n    * ex.\n    * \n    * <pre>\n    * https://${jclouds.identity}.blob.core.windows.net\n    * </pre>\n    * \n    * @return the api's default endpoint, if known.\n    */\n   Optional<String> getDefaultEndpoint();\n\n   /**\n    * Explicitly identifies the login identity into a provider\n    * \n    * @return the login identity into a provider, if known.\n    */\n   Optional<String> getDefaultIdentity();\n\n   /**\n    * Explicitly sets the secret, which when combined with the identity, will\n    * create an authenticated subject or session\n    * \n    * @return the api's default credential, if known.\n    * @see #getDefaultIdentity\n    * @see #getCredentialName\n    */\n   Optional<String> getDefaultCredential();\n\n   /**\n    * Configuration Properties used when creating connections to this api\n    * \n    * @return properties used to create connections to this api\n    */\n   Properties getDefaultProperties();\n\n   /**\n    * Modules that configure dependency injection for this context\n    * \n    * @return modules that configure dependency injection for this context\n    */\n   Set<Class<? extends Module>> getDefaultModules();\n   \n   /**\n    * \n    * @return the url for the API documentation related to this service\n    */\n   URI getDocumentation();\n\n   /**\n    * @return the primary context of this api, for example {@code ApiContext<EC2Api>}\n    */\n   TypeToken<? extends Context> getContext();\n   \n   /**\n    * @return types of contexts this can be transformed into, for example {@code BlobStoreContext}\n    */\n   Set<TypeToken<? extends View>> getViews();\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/apis/ApiPredicates.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.apis;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Strings.emptyToNull;\n\nimport org.jclouds.View;\nimport org.jclouds.util.TypeTokenUtils;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Predicates;\nimport com.google.common.reflect.TypeToken;\n\n/**\n * Container for api filters (predicates).\n */\npublic class ApiPredicates {\n\n   /**\n    * Returns all apis available to jclouds regardless of type.\n    * \n    * @return all available apis\n    */\n   public static Predicate<ApiMetadata> all() {\n      return Predicates.<ApiMetadata> alwaysTrue();\n   }\n\n   /**\n    * Returns all apis with the given id.\n    * \n    * @param id\n    *           the id of the api to return\n    * \n    * @return the apis with the given id\n    */\n   public static Predicate<ApiMetadata> id(final String id) {\n      checkNotNull(emptyToNull(id), \"id must be defined\");\n      return new Predicate<ApiMetadata>() {\n         /**\n          * {@inheritDoc}\n          */\n         @Override\n         public boolean apply(ApiMetadata apiMetadata) {\n            return apiMetadata.getId().equals(id);\n         }\n\n         /**\n          * {@inheritDoc}\n          */\n         @Override\n         public String toString() {\n            return \"id(\" + id + \")\";\n         }\n      };\n   }\n\n   /**\n    * Returns all apis who's contexts are assignable from the parameter\n    * \n    * @param type\n    *           the type of the context to search for\n    * \n    * @return the apis with contexts assignable from given type\n    */\n   public static Predicate<ApiMetadata> contextAssignableFrom(final TypeToken<?> type) {\n      checkNotNull(type, \"context must be defined\");\n      return new Predicate<ApiMetadata>() {\n         /**\n          * {@inheritDoc}\n          */\n         @Override\n         public boolean apply(ApiMetadata apiMetadata) {\n            return TypeTokenUtils.isSupertypeOf(type, apiMetadata.getContext());\n         }\n\n         /**\n          * {@inheritDoc}\n          */\n         @Override\n         public String toString() {\n            return \"contextAssignableFrom(\" + type + \")\";\n         }\n      };\n   }\n\n   /**\n    * Returns all apis who's contexts are transformable to the parameter\n    * \n    * @param type\n    *           the type of the context to search for\n    * \n    * @return the apis with contexts transformable to the given type\n    */\n   public static Predicate<ApiMetadata> viewableAs(final TypeToken<?> type) {\n      checkNotNull(type, \"context must be defined\");\n      return new Predicate<ApiMetadata>() {\n         /**\n          * {@inheritDoc}\n          */\n         @Override\n         public boolean apply(ApiMetadata apiMetadata) {\n            for (TypeToken<? extends View> to : apiMetadata.getViews())\n               if (TypeTokenUtils.isSupertypeOf(type, to))\n                  return true;\n            return false;\n         }\n\n         /**\n          * {@inheritDoc}\n          */\n         @Override\n         public String toString() {\n            return \"viewableAs(\" + type + \")\";\n         }\n      };\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/apis/Apis.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.apis;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.find;\nimport static org.jclouds.reflect.Reflection2.typeToken;\n\nimport java.util.NoSuchElementException;\nimport java.util.ServiceLoader;\n\nimport org.jclouds.View;\nimport org.jclouds.osgi.ApiRegistry;\nimport org.jclouds.util.TypeTokenUtils;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.reflect.TypeToken;\n\n/**\n * The Apis class provides static methods for accessing apis.\n */\npublic class Apis {\n\n   private static enum IdFunction implements Function<ApiMetadata, String> {\n      INSTANCE;\n\n      @Override\n      public String apply(ApiMetadata input) {\n         return input.getId();\n      }\n\n   }\n\n   public static Function<ApiMetadata, String> idFunction() {\n      return IdFunction.INSTANCE;\n   }\n\n   /**\n    * Returns the apis located on the classpath via {@link java.util.ServiceLoader}.\n    * \n    * @return all available apis loaded from classpath via ServiceLoader\n    */\n   private static Iterable<ApiMetadata> fromServiceLoader() {\n      return ServiceLoader.load(ApiMetadata.class);\n   }\n\n   /**\n    * Returns all available apis.\n    * \n    * @return all available apis\n    */\n   public static Iterable<ApiMetadata> all() {\n      return ImmutableSet.<ApiMetadata>builder()\n                         .addAll(fromServiceLoader())\n                         .addAll(ApiRegistry.fromRegistry()).build();\n   }\n\n   /**\n    * Returns the first api with the provided id\n    * \n    * @param id\n    *           the id of the api to return\n    * \n    * @return the api with the given id\n    * \n    * @throws NoSuchElementException\n    *            whenever there are no apis with the provided id\n    */\n   public static ApiMetadata withId(String id) throws NoSuchElementException {\n      return find(all(), ApiPredicates.id(id));\n   }\n   \n   /**\n    * Returns all apis who's contexts are assignable from the parameter\n    * \n    * @param type\n    *           the type of the context to search for\n    * \n    * @return the apis with contexts assignable from given type\n    */\n   public static Iterable<ApiMetadata> contextAssignableFrom(TypeToken<?> type) {\n      return filter(all(), ApiPredicates.contextAssignableFrom(type));\n   }\n   \n   /**\n    * Returns all apis who's contexts are assignable from the parameter\n    * \n    * @param type\n    *           the type of the context to search for\n    * \n    * @return the apis with contexts assignable from given type\n    */\n   public static Iterable<ApiMetadata> viewableAs(TypeToken<? extends View> type) {\n      return filter(all(), ApiPredicates.viewableAs(type));\n   }\n   \n   public static Iterable<ApiMetadata> viewableAs(Class<? extends View> type) {\n      return filter(all(), ApiPredicates.viewableAs(typeToken(type)));\n   }\n\n   /**\n    * Returns the type of context\n    * \n    * @param type\n    *           the type of the context to search for\n    * \n    * @return the apis with contexts transformable to the given type\n    */\n   public static TypeToken<?> findView(final ApiMetadata apiMetadata, final TypeToken<?> view)\n            throws NoSuchElementException {\n      checkNotNull(apiMetadata, \"apiMetadata must be defined\");\n      checkNotNull(view, \"context must be defined\");\n      return Iterables.find(apiMetadata.getViews(), new Predicate<TypeToken<?>>() {\n\n         @Override\n         public boolean apply(TypeToken<?> input) {\n            return TypeTokenUtils.isSupertypeOf(view, input);\n         }\n\n      });\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/apis/internal/BaseApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.apis.internal;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.Constants.PROPERTY_CONNECTION_CLOSE_HEADER;\nimport static org.jclouds.Constants.PROPERTY_CONNECTION_TIMEOUT;\nimport static org.jclouds.Constants.PROPERTY_IDEMPOTENT_METHODS;\nimport static org.jclouds.Constants.PROPERTY_ISO3166_CODES;\nimport static org.jclouds.Constants.PROPERTY_MAX_CONNECTIONS_PER_CONTEXT;\nimport static org.jclouds.Constants.PROPERTY_MAX_CONNECTIONS_PER_HOST;\nimport static org.jclouds.Constants.PROPERTY_MAX_CONNECTION_REUSE;\nimport static org.jclouds.Constants.PROPERTY_MAX_PARALLEL_DELETES;\nimport static org.jclouds.Constants.PROPERTY_MAX_SESSION_FAILURES;\nimport static org.jclouds.Constants.PROPERTY_OUTPUT_SOCKET_BUFFER_SIZE;\nimport static org.jclouds.Constants.PROPERTY_PRETTY_PRINT_PAYLOADS;\nimport static org.jclouds.Constants.PROPERTY_SCHEDULER_THREADS;\nimport static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL;\nimport static org.jclouds.Constants.PROPERTY_SO_TIMEOUT;\nimport static org.jclouds.Constants.PROPERTY_STRIP_EXPECT_HEADER;\nimport static org.jclouds.Constants.PROPERTY_USER_THREADS;\nimport static org.jclouds.Constants.PROPERTY_USER_AGENT;\nimport static org.jclouds.reflect.Reflection2.typeToken;\n\nimport java.net.URI;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport org.jclouds.Context;\nimport org.jclouds.JcloudsVersion;\nimport org.jclouds.View;\nimport org.jclouds.apis.ApiMetadata;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.reflect.TypeToken;\nimport com.google.inject.Module;\n/**\n * The BaseApiMetadata class is an abstraction of {@link ApiMetadata} to be extended by those\n * implementing ApiMetadata.\n * \n * (Note: This class must be abstract to allow {@link java.util.ServiceLoader} to work properly.\n */\npublic abstract class BaseApiMetadata implements ApiMetadata {\n\n   public static Properties defaultProperties() {\n      Properties props = new Properties();\n      // TODO: move this to ApiMetadata\n      final int numUserThreads = 50;\n\n      props.setProperty(PROPERTY_ISO3166_CODES, \"\");\n      props.setProperty(PROPERTY_MAX_CONNECTIONS_PER_CONTEXT, 20 + \"\");\n      props.setProperty(PROPERTY_MAX_CONNECTIONS_PER_HOST, 0 + \"\");\n      props.setProperty(PROPERTY_SO_TIMEOUT, 60000 + \"\");\n      props.setProperty(PROPERTY_CONNECTION_TIMEOUT, 60000 + \"\");\n      // Successfully tested 50 user threads with BlobStore.clearContainer.\n      props.setProperty(PROPERTY_USER_THREADS, numUserThreads + \"\");\n      props.setProperty(PROPERTY_SCHEDULER_THREADS, 10 + \"\");\n      props.setProperty(PROPERTY_MAX_CONNECTION_REUSE, 75 + \"\");\n      props.setProperty(PROPERTY_MAX_SESSION_FAILURES, 2 + \"\");\n      props.setProperty(PROPERTY_SESSION_INTERVAL, 60 + \"\");\n      props.setProperty(PROPERTY_PRETTY_PRINT_PAYLOADS, \"true\");\n      props.setProperty(PROPERTY_STRIP_EXPECT_HEADER, \"false\");\n      props.setProperty(PROPERTY_USER_AGENT,\n\t\t\tString.format(\"jclouds/%s java/%s\",\n                                       JcloudsVersion.get(),\n                                       System.getProperty(\"java.version\")));\n      props.setProperty(PROPERTY_CONNECTION_CLOSE_HEADER, \"false\");\n\n      // By default, we allow maximum parallel deletes to be equal to the number\n      // of user threads since one thread is used to delete on blob.\n      props.setProperty(PROPERTY_MAX_PARALLEL_DELETES, numUserThreads + \"\");\n\n      props.setProperty(PROPERTY_IDEMPOTENT_METHODS, \"DELETE,GET,HEAD,OPTIONS,PUT\");\n      props.setProperty(PROPERTY_OUTPUT_SOCKET_BUFFER_SIZE, 32768 + \"\");\n      return props;\n   }\n\n   public abstract static class Builder<T extends Builder<T>> implements ApiMetadata.Builder<T> {\n      protected abstract T self();\n\n      private String id;\n      private String name;\n      private Set<TypeToken<? extends View>> views = ImmutableSet.of();\n      private String endpointName = \"https endpoint\";\n      private String identityName;\n      private Optional<String> credentialName = Optional.absent();\n      private String version = \"\";\n      private Optional<String> buildVersion = Optional.of(\"\");\n      private Optional<String> defaultEndpoint = Optional.absent();\n      private Optional<String> defaultIdentity = Optional.absent();\n      private Optional<String> defaultCredential = Optional.absent();\n      private Properties defaultProperties = BaseApiMetadata.defaultProperties();\n      private URI documentation;\n      private TypeToken<? extends Context> context = typeToken(Context.class);\n      private Set<Class<? extends Module>> defaultModules = ImmutableSet.of();\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public T id(String id) {\n         this.id = checkNotNull(id, \"id\");\n         return self();\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public T name(String name) {\n         this.name = checkNotNull(name, \"name\");\n         return self();\n      }\n      \n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public T view(Class<? extends View> view) {\n         return view(typeToken(checkNotNull(view, \"view\")));\n      }\n      \n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public T view(TypeToken<? extends View> view) {\n         return views(ImmutableSet.<TypeToken<? extends View>>of(checkNotNull(view, \"view\")));\n      }\n      \n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public T views(Set<TypeToken<? extends View>> views) {\n         this.views = ImmutableSet.copyOf(checkNotNull(views, \"views\"));\n         return self();\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public T endpointName(String endpointName) {\n         this.endpointName = checkNotNull(endpointName, \"endpointName\");\n         return self();\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public T identityName(String identityName) {\n         this.identityName = checkNotNull(identityName, \"identityName\");\n         return self();\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public T credentialName(String credentialName) {\n         this.credentialName = Optional.fromNullable(credentialName);\n         return self();\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public T version(String version) {\n         this.version = checkNotNull(version, \"version\");\n         return self();\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public T buildVersion(String buildVersion) {\n         this.buildVersion = Optional.fromNullable(buildVersion);\n         return self();\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public T defaultEndpoint(String defaultEndpoint) {\n         this.defaultEndpoint = Optional.fromNullable(defaultEndpoint);\n         return self();\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public T defaultIdentity(String defaultIdentity) {\n         this.defaultIdentity = Optional.fromNullable(defaultIdentity);\n         return self();\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public T defaultCredential(String defaultCredential) {\n         this.defaultCredential = Optional.fromNullable(defaultCredential);\n         return self();\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public T defaultProperties(Properties defaultProperties) {\n         this.defaultProperties = checkNotNull(defaultProperties, \"defaultProperties\");\n         return self();\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public T documentation(URI documentation) {\n         this.documentation = checkNotNull(documentation, \"documentation\");\n         return self();\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public T context(TypeToken<? extends Context> context) {\n         this.context = checkNotNull(context, \"context\");\n         return self();\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public T defaultModule(Class<? extends Module> defaultModule) {\n         return defaultModules(ImmutableSet.<Class<? extends Module>>of(checkNotNull(defaultModule, \"defaultModule\")));\n      }\n      \n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public T defaultModules(Set<Class<? extends Module>> defaultModules) {\n         this.defaultModules = ImmutableSet.copyOf(checkNotNull(defaultModules, \"defaultModules\"));\n         return self();\n      }\n\n      public T fromApiMetadata(ApiMetadata in) {\n         return id(in.getId()).views(in.getViews()).name(in.getName()).endpointName(in.getEndpointName()).identityName(\n                  in.getIdentityName()).credentialName(in.getCredentialName().orNull()).version(in.getVersion())\n                  .buildVersion(in.getBuildVersion().orNull()).defaultEndpoint(in.getDefaultEndpoint().orNull())\n                  .defaultIdentity(in.getDefaultIdentity().orNull()).defaultCredential(\n                           in.getDefaultCredential().orNull()).defaultProperties(in.getDefaultProperties())\n                  .documentation(in.getDocumentation()).context(in.getContext()).defaultModules(in.getDefaultModules());\n      }\n   }\n\n   private final String id;\n   private final String name;\n   private final Set<TypeToken<? extends View>> views;\n   private final String endpointName;\n   private final String identityName;\n   private final Optional<String> credentialName;\n   private final String version;\n   private final Optional<String> buildVersion;\n   private final Optional<String> defaultEndpoint;\n   private final Optional<String> defaultIdentity;\n   private final Optional<String> defaultCredential;\n   private final Properties defaultProperties;\n   private final URI documentation;\n   private final TypeToken<? extends Context> context;\n   private final Set<Class<? extends Module>> defaultModules;\n\n   protected BaseApiMetadata(Builder<?> builder) {\n      this(builder.id, builder.name, builder.views, builder.endpointName, builder.identityName, builder.credentialName,\n               builder.version, builder.buildVersion, builder.defaultEndpoint, builder.defaultIdentity,\n               builder.defaultCredential, builder.defaultProperties, builder.documentation, builder.context,\n               builder.defaultModules);\n   }\n\n   protected BaseApiMetadata(String id, String name, Set<TypeToken<? extends View>> views, String endpointName, String identityName, // NO_UCD (use private)\n            Optional<String> credentialName, String version, Optional<String> buildVersion,\n            Optional<String> defaultEndpoint, Optional<String> defaultIdentity, Optional<String> defaultCredential,\n            Properties defaultProperties, URI documentation, TypeToken<? extends Context> context,\n            Set<Class<? extends Module>> defaultModules) {\n      this.id = checkNotNull(id, \"id\");\n      this.name = checkNotNull(name, \"name\");\n      this.views = ImmutableSet.copyOf(checkNotNull(views, \"views\"));\n      this.endpointName = checkNotNull(endpointName, \"endpointName\");\n      this.identityName = checkNotNull(identityName, \"identityName\");\n      this.credentialName = checkNotNull(credentialName, \"credentialName\");\n      this.version = checkNotNull(version, \"version\");\n      this.buildVersion = checkNotNull(buildVersion, \"buildVersion\");\n      this.defaultEndpoint = checkNotNull(defaultEndpoint, \"defaultEndpoint\");\n      this.defaultIdentity = checkNotNull(defaultIdentity, \"defaultIdentity\");\n      this.defaultCredential = checkNotNull(defaultCredential, \"defaultCredential\");\n      this.defaultProperties = checkNotNull(defaultProperties, \"defaultProperties\");\n      this.documentation = checkNotNull(documentation, \"documentation\");\n      this.context = checkNotNull(context, \"context\");\n      this.defaultModules = ImmutableSet.copyOf(checkNotNull(defaultModules, \"defaultModules\"));\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o)\n         return true;\n      // subclass equivalence is ok, since we don't know the classloader\n      // we'll get things from\n      if (o == null || !(o instanceof ApiMetadata))\n         return false;\n      ApiMetadata that = ApiMetadata.class.cast(o);\n      return equal(this.getId(), that.getId()) && equal(this.getName(), that.getName())\n               && equal(this.getViews(), that.getViews());\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(getId(), getName(), getViews());\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(\"\").add(\"id\", getId()).add(\"name\", getName()).add(\"views\", getViews()).add(\n               \"endpointName\", getEndpointName()).add(\"identityName\", getIdentityName()).add(\"credentialName\",\n               getCredentialName()).add(\"documentation\", getDocumentation());\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getId() {\n      return id;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getName() {\n      return name;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Set<TypeToken<? extends View>> getViews() {\n      return views;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getEndpointName() {\n      return endpointName;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getIdentityName() {\n      return identityName;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Optional<String> getCredentialName() {\n      return credentialName;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getVersion() {\n      return version;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Optional<String> getBuildVersion() {\n      return buildVersion;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Optional<String> getDefaultEndpoint() {\n      return defaultEndpoint;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Optional<String> getDefaultIdentity() {\n      return defaultIdentity;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Optional<String> getDefaultCredential() {\n      return defaultCredential;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Properties getDefaultProperties() {\n      return defaultProperties;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public URI getDocumentation() {\n      return documentation;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public TypeToken<? extends Context> getContext() {\n      return context;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Set<Class<? extends Module>> getDefaultModules() {\n      return defaultModules;\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/collect/AbstractMapEntry.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.collect;\n\nimport java.util.Map.Entry;\n\nimport com.google.common.base.Objects;\n\n\nabstract class AbstractMapEntry<K, V> implements Entry<K, V> {\n\n   @Override\n   public V setValue(V value) { // NO_UCD\n      throw new UnsupportedOperationException();\n   }\n\n   @Override\n   public boolean equals(Object object) {\n      if (object instanceof Entry) {\n         Entry<?, ?> that = (Entry<?, ?>) object;\n         return Objects.equal(this.getKey(), that.getKey()) && Objects.equal(this.getValue(), that.getValue());\n      }\n      return false;\n   }\n\n   @Override\n   public int hashCode() {\n      K k = getKey();\n      V v = getValue();\n      return ((k == null) ? 0 : k.hashCode()) ^ ((v == null) ? 0 : v.hashCode());\n   }\n\n   @Override\n   public String toString() {\n      return getKey() + \"=\" + getValue();\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/collect/AdvanceUntilEmptyIterable.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.collect;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Iterator;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.AbstractIterator;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.Iterators;\nimport com.google.common.collect.UnmodifiableIterator;\n\n/**\n * continues to supply iterables until the last was empty\n *\n * @param <E>\n */\n@Beta\npublic class AdvanceUntilEmptyIterable<E> extends FluentIterable<FluentIterable<E>> {\n\n   public static <E> AdvanceUntilEmptyIterable<E> create(Supplier<FluentIterable<E>> nextIterable) {\n      return new AdvanceUntilEmptyIterable<E>(nextIterable);\n   }\n\n   private final AdvanceUntilEmptyIterator<E> iterator;\n\n   protected AdvanceUntilEmptyIterable(Supplier<FluentIterable<E>> nextIterable) {\n      this.iterator = new AdvanceUntilEmptyIterator<E>(checkNotNull(nextIterable, \"next iterable\"));\n   }\n\n   @Override\n   public Iterator<FluentIterable<E>> iterator() {\n      return iterator;\n   }\n\n   private static class AdvanceUntilEmptyIterator<E> extends AbstractIterator<FluentIterable<E>> {\n\n      private final Supplier<FluentIterable<E>> nextIterable;\n      private transient FluentIterable<E> current;\n      private transient boolean unread = true;\n\n      private AdvanceUntilEmptyIterator(Supplier<FluentIterable<E>> nextIterable) {\n         this.nextIterable = checkNotNull(nextIterable, \"next iterable\");\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      protected FluentIterable<E> computeNext() {\n         if (unread)\n            try {\n               return current = nextIterable.get();\n            } finally {\n               unread = false;\n            }\n         else if (!current.isEmpty())\n            return current = nextIterable.get();\n         else\n            return endOfData();\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public int hashCode() {\n         return Objects.hashCode(current, unread);\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public boolean equals(Object obj) {\n         if (this == obj)\n            return true;\n         if (obj == null || getClass() != obj.getClass())\n            return false;\n         AdvanceUntilEmptyIterator<?> other = AdvanceUntilEmptyIterator.class.cast(obj);\n         return Objects.equal(this.current, other.current) && Objects.equal(this.unread, other.unread);\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public String toString() {\n         return MoreObjects.toStringHelper(\"\").omitNullValues().add(\"current\", current).add(\"unread\", unread).toString();\n      }\n   }\n\n   /**\n    * Combines all the pages into a single unmodifiable iterable. ex.\n    *\n    * <pre>\n    * FluentIterable<StorageMetadata> blobs = blobstore.list(...).concat();\n    * for (StorageMetadata blob : blobs) {\n    *     process(blob);\n    * }\n    * </pre>\n    *\n    * @see Iterators#concat\n    */\n   public FluentIterable<E> concat() {\n      final Iterator<FluentIterable<E>> iterator = iterator();\n      final UnmodifiableIterator<Iterator<E>> unmodifiable = new UnmodifiableIterator<Iterator<E>>() {\n         @Override\n         public boolean hasNext() {\n            return iterator.hasNext();\n         }\n\n         @Override\n         public Iterator<E> next() {\n            return iterator.next().iterator();\n         }\n      };\n      return new FluentIterable<E>() {\n         @Override\n         public Iterator<E> iterator() {\n            return Iterators.concat(unmodifiable);\n         }\n      };\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/collect/IterableWithMarker.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.collect;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.FluentIterable;\n\n/**\n * An {@code Iterable} that can be continued\n */\n@Beta\npublic abstract class IterableWithMarker<T> extends FluentIterable<T> {\n\n   /**\n    * If there is a next marker, then the set is incomplete and you should issue another command to\n    * retrieve the rest, setting the option {@code marker} to this value \n    * \n    * @return next marker, or absent if list is complete\n    */\n   public abstract Optional<Object> nextMarker();\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/collect/IterableWithMarkers.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.collect;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Iterator;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Utilities for using {@link IterableWithMarker}s.\n */\n@Beta\npublic class IterableWithMarkers {\n   \n   @SuppressWarnings(\"rawtypes\")\n   public static final IterableWithMarker EMPTY = from(ImmutableSet.of());\n\n   /**\n    * Returns a paginated iterable containing the given elements and null marker.\n    * \n    * \n    * @throws NullPointerException\n    *            if {@code elements} are null\n    */\n   public static <T> IterableWithMarker<T> from(Iterable<T> elements) {\n      return from(elements, null);\n   }\n\n   /**\n    * Returns a paginated iterable containing the given elements and marker.\n    * \n    * \n    * @throws NullPointerException\n    *            if {@code elements} are null\n    */\n   public static <T> IterableWithMarker<T> from(final Iterable<T> elements, @Nullable final Object marker) {\n      return new ForwardingIterableWithMarker<T>() {\n\n         @Override\n         protected IterableWithMarker<T> delegate() {\n            return new ForwardedIterableWithMarker<T>(elements, marker);\n         }\n\n      };\n   }\n\n   private static final class ForwardedIterableWithMarker<T> extends IterableWithMarker<T> {\n      private final Iterable<T> elements;\n      private final Optional<Object> marker;\n\n      private ForwardedIterableWithMarker(Iterable<T> elements, @Nullable Object marker) {\n         this.elements = checkNotNull(elements, \"elements\");\n         this.marker = Optional.fromNullable(marker);\n      }\n\n      @Override\n      public Iterator<T> iterator() {\n         return elements.iterator();\n      }\n\n      @Override\n      public Optional<Object> nextMarker() {\n         return marker;\n      }\n   }\n\n   private abstract static class ForwardingIterableWithMarker<T> extends IterableWithMarker<T> {\n\n      protected abstract IterableWithMarker<T> delegate();\n\n      @Override\n      public Iterator<T> iterator() {\n         return delegate().iterator();\n      }\n\n      @Override\n      public Optional<Object> nextMarker() {\n         return delegate().nextMarker();\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/collect/Memoized.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.collect;\n\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.ElementType.PARAMETER;\nimport static java.lang.annotation.ElementType.TYPE;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\nimport jakarta.inject.Qualifier;\n\n/**\n * Designates that this object is going to return cached results\n */\n@Target( { TYPE, METHOD, PARAMETER })\n@Retention(RUNTIME)\n@Qualifier\npublic @interface Memoized {\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/collect/PagedIterable.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.collect;\n\nimport java.util.Iterator;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.Iterators;\nimport com.google.common.collect.UnmodifiableIterator;\n\n/**\n * Extends {@link FluentIterable} allowing you to lazily advance through\n * sequence of pages in a result set. Typically used in APIs that return only a\n * certain number of records at a time.\n * </p>\n * Simplest usage is to employ the {@link #concat} convenience function, and iterate.\n * </p>\n * <pre>\n * FluentIterable<? extends Image> images = imageApi.listInDetail().concat();\n *\n * for (Image image: images) {\n *    System.out.println(image);\n * }\n * </pre>\n * </p> \n * Another usage is to employ the {@link #concat} convenience function, and one\n * of the methods from {@link FluentIterable}.\n * </p>\n * <pre>\n *    Optional<? extends Image> image = imageApi.listInDetail().concat().firstMatch(isInterestingImage());\n *    System.out.println(image.orNull());\n * ...\n * private static Predicate<Image> isInterestingImage() {\n *    return new Predicate<Image>() {\n *       {@literal @}Override\n *       public boolean apply(Image image) {\n *          return image.getName().startsWith(\"Arch\");\n *       }\n *    };\n * }\n * </pre>\n */\n@Beta\npublic abstract class PagedIterable<E> extends FluentIterable<IterableWithMarker<E>> {\n\n   /**\n    * Combines all the pages into a single unmodifiable iterable. ex.\n    * \n    * <pre>\n    * FluentIterable<StorageMetadata> blobs = blobstore.list(...).concat();\n    * for (StorageMetadata blob : blobs) {\n    *     process(blob);\n    * }\n    * </pre>\n    * \n    * @see Iterators#concat\n    */\n   public FluentIterable<E> concat() {\n      final Iterator<IterableWithMarker<E>> iterator = iterator();\n      final UnmodifiableIterator<Iterator<E>> unmodifiable = new UnmodifiableIterator<Iterator<E>>() {\n         @Override\n         public boolean hasNext() {\n            return iterator.hasNext();\n         }\n\n         @Override\n         public Iterator<E> next() {\n            return iterator.next().iterator();\n         }\n      };\n      return new FluentIterable<E>() {\n         @Override\n         public Iterator<E> iterator() {\n            return Iterators.concat(unmodifiable);\n         }\n      };\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/collect/PagedIterables.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.collect;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Iterator;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Function;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.collect.AbstractIterator;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Utilities for using {@link PagedIterable}s.\n */\n@Beta\npublic class PagedIterables {\n   /**\n    * @param only\n    *           the only page of data\n    * \n    * @return iterable with only the one page\n    */\n   public static <T> PagedIterable<T> onlyPage(final IterableWithMarker<T> only) {\n      return new PagedIterable<T>() {\n         public Iterator<IterableWithMarker<T>> iterator() {\n            return ImmutableSet.of(only).iterator();\n         }\n      };\n   }\n\n   /**\n    * @see #onlyPage(IterableWithMarker)\n    */\n   @Deprecated\n   public static <T> PagedIterable<T> of(IterableWithMarker<T> only) {\n      return onlyPage(only);\n   }\n\n   /**\n    * \n    * \n    * @param initial\n    *           the initial set current data\n    * @param markerToNext\n    *           produces the next set based on the marker\n    * \n    * @return iterable current data which continues if the user iterates beyond\n    *         the first page\n    */\n   public static <T> PagedIterable<T> advance(final IterableWithMarker<T> initial,\n         final Function<Object, IterableWithMarker<T>> markerToNext) {\n      return new PagedIterable<T>() {\n         public Iterator<IterableWithMarker<T>> iterator() {\n            return advancingIterator(initial, markerToNext);\n         }\n      };\n   }\n\n   private static class AdvancingIterator<T> extends AbstractIterator<IterableWithMarker<T>> {\n\n      private final Function<Object, IterableWithMarker<T>> markerToNext;\n      private transient IterableWithMarker<T> current;\n      private transient boolean unread = true;\n\n      private AdvancingIterator(IterableWithMarker<T> initial, Function<Object, IterableWithMarker<T>> markerToNext) {\n         this.current = checkNotNull(initial, \"initial iterable\");\n         this.markerToNext = checkNotNull(markerToNext, \"marker to next iterable\");\n      }\n\n      @Override\n      protected IterableWithMarker<T> computeNext() {\n         if (unread)\n            try {\n               return current;\n            } finally {\n               unread = false;\n            }\n         else if (current.nextMarker().isPresent())\n            return current = markerToNext.apply(current.nextMarker().get());\n         else\n            return endOfData();\n      }\n\n      @Override\n      public int hashCode() {\n         return Objects.hashCode(current, unread);\n      }\n\n      @Override\n      public boolean equals(Object obj) {\n         if (this == obj)\n            return true;\n         if (obj == null || getClass() != obj.getClass())\n            return false;\n         AdvancingIterator<?> other = AdvancingIterator.class.cast(obj);\n         return Objects.equal(this.current, other.current) && Objects.equal(this.unread, other.unread);\n      }\n\n      @Override\n      public String toString() {\n         return MoreObjects.toStringHelper(\"\").add(\"current\", current).add(\"unread\", unread).toString();\n      }\n   }\n\n   /**\n    * \n    * @param initial\n    *           the initial set current data\n    * @param markerToNext\n    *           produces the next set based on the marker\n    * \n    * @return iterable current data which continues if the user iterates beyond\n    *         the first page\n    */\n   private static <T> Iterator<IterableWithMarker<T>> advancingIterator(IterableWithMarker<T> initial,\n         Function<Object, IterableWithMarker<T>> markerToNext) {\n      if (!initial.nextMarker().isPresent()) {\n         return ImmutableSet.of(initial).iterator();\n      }\n      return new AdvancingIterator<T>(initial, markerToNext);\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/collect/TransformingMap.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.collect;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.AbstractMap;\nimport java.util.AbstractSet;\nimport java.util.Iterator;\nimport java.util.Map;\nimport java.util.Set;\n\nimport com.google.common.base.Function;\n\n/**\n * A map that transforms values on the way in and out. Inspired by the guava method\n * {@code Maps.transformValues}.\n */\npublic class TransformingMap<K, V1, V2> extends AbstractMap<K, V2> {\n   private final Map<K, V1> fromMap;\n   private final Function<? super V1, V2> getFunction;\n   private final Function<? super V2, V1> putFunction;\n\n   public TransformingMap(Map<K, V1> fromMap, Function<? super V1, V2> getFunction, Function<? super V2, V1> putFunction) {\n      this.fromMap = checkNotNull(fromMap);\n      this.getFunction = checkNotNull(getFunction);\n      this.putFunction = checkNotNull(putFunction);\n   }\n\n   @Override\n   public int size() {\n      return fromMap.size();\n   }\n\n   @Override\n   public V2 put(K key, V2 value) {\n      V2 old = get(key);\n      fromMap.put(key, value != null ? putFunction.apply(value) : null);\n      return old;\n   }\n\n   @Override\n   public boolean containsKey(Object key) {\n      return fromMap.containsKey(key);\n   }\n\n   @Override\n   public V2 get(Object key) {\n      V1 value = fromMap.get(key);\n      return (value != null || fromMap.containsKey(key)) ? getFunction.apply(value) : null;\n   }\n\n   @Override\n   public V2 remove(Object key) {\n      return fromMap.containsKey(key) ? getFunction.apply(fromMap.remove(key)) : null;\n   }\n\n   @Override\n   public void clear() {\n      fromMap.clear();\n   }\n\n   @Override\n   public Set<Entry<K, V2>> entrySet() {\n      return new EntrySet();\n\n   }\n\n   private class EntrySet extends AbstractSet<Entry<K, V2>> {\n      @Override\n      public int size() {\n         return TransformingMap.this.size();\n      }\n\n      @Override\n      public Iterator<Entry<K, V2>> iterator() {\n         final Iterator<Entry<K, V1>> mapIterator = fromMap.entrySet().iterator();\n\n         return new Iterator<Entry<K, V2>>() {\n            public boolean hasNext() {\n               return mapIterator.hasNext();\n            }\n\n            public Entry<K, V2> next() {\n               final Entry<K, V1> entry = mapIterator.next();\n               return new AbstractMapEntry<K, V2>() {\n                  @Override\n                  public K getKey() {\n                     return entry.getKey();\n                  }\n\n                  @Override\n                  public V2 getValue() {\n                     return getFunction.apply(entry.getValue());\n                  }\n               };\n            }\n\n            public void remove() {\n               mapIterator.remove();\n            }\n         };\n      }\n\n      @Override\n      public void clear() {\n         fromMap.clear();\n      }\n\n      @Override\n      public boolean contains(Object o) {\n         if (!(o instanceof Entry)) {\n            return false;\n         }\n         Entry<?, ?> entry = (Entry<?, ?>) o;\n         Object entryKey = entry.getKey();\n         Object entryValue = entry.getValue();\n         V2 mapValue = TransformingMap.this.get(entryKey);\n         if (mapValue != null) {\n            return mapValue.equals(entryValue);\n         }\n         return entryValue == null && containsKey(entryKey);\n      }\n\n      @Override\n      public boolean remove(Object o) {\n         if (contains(o)) {\n            Entry<?, ?> entry = (Entry<?, ?>) o;\n            Object key = entry.getKey();\n            fromMap.remove(key);\n            return true;\n         }\n         return false;\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/collect/internal/Arg0ToPagedIterable.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.collect.internal;\n\nimport java.util.List;\n\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\n\n/**\n * Used to propagate {@code arg0} during an advance in a {@link PagedIterable}. For example, in the call\n * {@code api.getUserApi().listPathPrefix(\"/users\")}, the arg0 is the value {@code \"/users\"}.\n */\n@Beta\npublic abstract class Arg0ToPagedIterable<T, I extends Arg0ToPagedIterable<T, I>> extends ArgsToPagedIterable<T, I> {\n\n   @Override\n   protected Function<Object, IterableWithMarker<T>> markerToNextForArgs(List<Object> args) {\n      Optional<Object> arg0 = Optional.fromNullable(!args.isEmpty() ? args.get(0) : null);\n      return markerToNextForArg0(arg0);\n   }\n\n   /**\n    * @param arg0\n    *           present when there was an arg0\n    */\n   protected abstract Function<Object, IterableWithMarker<T>> markerToNextForArg0(Optional<Object> arg0);\n\n   /**\n    * Used to propagate caller {@code arg0} to a callee during an advance in a {@link PagedIterable}. For example, in\n    * the call {@code api.getUserApi(region).list()}, the caller arg0 is the value of {@code region}, and the callee\n    * is {@code UserApi.list()}\n    *\n    */\n   public abstract static class FromCaller<T, I extends FromCaller<T, I>> extends Arg0ToPagedIterable<T, I> {\n      @Override\n      protected List<Object> getArgs(GeneratedHttpRequest request) {\n         return request.getCaller().get().getArgs();\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/collect/internal/ArgsToPagedIterable.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.collect.internal;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static org.jclouds.collect.PagedIterables.advance;\nimport static org.jclouds.collect.PagedIterables.onlyPage;\n\nimport java.util.List;\n\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.PagedIterable;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.InvocationContext;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Function;\n\n/**\n * Used to propagate the invoked method arguments during an advance in a\n * {@link PagedIterable}.\n * <p>\n * In order to fetch the next page in the result set, subclasses may need to\n * have the context of the initial request. This class propagates the arguments\n * used in the original request, so they can be used to fetch the next page in\n * the result set.\n */\n@Beta\npublic abstract class ArgsToPagedIterable<T, I extends ArgsToPagedIterable<T, I>> implements\n      Function<IterableWithMarker<T>, PagedIterable<T>>, InvocationContext<I> {\n\n   protected GeneratedHttpRequest request;\n\n   @Override\n   public PagedIterable<T> apply(IterableWithMarker<T> input) {\n      return input.nextMarker().isPresent() ? advance(input, markerToNextForArgs(getArgs(request))) : onlyPage(input);\n   }\n\n   protected List<Object> getArgs(GeneratedHttpRequest request) {\n      return request.getInvocation().getArgs();\n   }\n\n   protected abstract Function<Object, IterableWithMarker<T>> markerToNextForArgs(List<Object> args);\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public I setContext(HttpRequest request) {\n      checkArgument(request instanceof GeneratedHttpRequest,\n            \"ArgsToPagedIterable only supports a GeneratedHttpRequest\");\n      this.request = GeneratedHttpRequest.class.cast(request);\n      return (I) this;\n   }\n\n   /**\n    * Sometimes the arguments in the invoked method do not provide enough\n    * information to fetch the next page of the result set. This, for example,\n    * is common in APIs dealing with several endpoints.\n    * <p>\n    * This class provides a way to propagate the arguments passed to the caller\n    * of the method, so they can be used to fetch the next page of the result\n    * set. For example, in the call {@code api.getUserApi(region).list()},\n    * the caller arg0 is the value of {@code region}, and the callee is\n    * {@code UserApi.list()}\n    *\n    * @see ParseImages function in openstack-glance for a usage example.\n    */\n   public abstract static class FromCaller<T, I extends FromCaller<T, I>> extends ArgsToPagedIterable<T, I> {\n      @Override\n      protected List<Object> getArgs(GeneratedHttpRequest request) {\n         return request.getCaller().get().getArgs();\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/collect/internal/CallerArg0ToPagedIterable.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.collect.internal;\n\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.PagedIterable;\nimport org.jclouds.collect.PagedIterables;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.InvocationContext;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\n\n/**\n * @deprecated Arg0ToPagedIterable.FromCaller\n */\n@Beta\n@Deprecated\npublic abstract class CallerArg0ToPagedIterable<T, I extends CallerArg0ToPagedIterable<T, I>> implements\n      Function<IterableWithMarker<T>, PagedIterable<T>>, InvocationContext<I> {\n\n   private GeneratedHttpRequest request;\n\n   @Override\n   public PagedIterable<T> apply(IterableWithMarker<T> input) {\n      if (input.nextMarker() == null)\n         return PagedIterables.of(input);\n\n      Optional<String> arg0Option = Optional.absent();\n      if (!request.getCaller().get().getArgs().isEmpty()) {\n         Object arg0 = request.getCaller().get().getArgs().get(0);\n         if (arg0 != null)\n            arg0Option = Optional.of(arg0.toString());\n      }\n      final String arg0 = arg0Option.orNull();\n      return PagedIterables.advance(input, markerToNextForCallingArg0(arg0));\n   }\n\n   protected abstract Function<Object, IterableWithMarker<T>> markerToNextForCallingArg0(String arg0);\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public I setContext(HttpRequest request) {\n      this.request = GeneratedHttpRequest.class.cast(request);\n      return (I) this;\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/concurrent/DynamicExecutors.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.concurrent;\n\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.ThreadFactory;\nimport java.util.concurrent.ThreadPoolExecutor;\nimport java.util.concurrent.TimeUnit;\n\n/**\n * Factory and utility methods for handling {@link DynamicThreadPoolExecutor}.\n */\npublic class DynamicExecutors {\n\n   /**\n    * Creates a thread pool, same as in {@link #newScalingThreadPool(int, int, long)}, using the provided ThreadFactory\n    * to create new threads when needed.\n    * \n    * @param min\n    *           the number of threads to keep in the pool, even if they are idle.\n    * @param max\n    *           the maximum number of threads to allow in the pool.\n    * @param keepAliveTime\n    *           when the number of threads is greater than the min, this is the maximum time that excess idle threads\n    *           will wait for new tasks before terminating (in milliseconds).\n    * @param threadFactory\n    *           the factory to use when creating new threads.\n    * @return the newly created thread pool\n    */\n   public static ExecutorService newScalingThreadPool(int min, int max, long keepAliveTime, ThreadFactory threadFactory) {\n      DynamicThreadPoolExecutor.DynamicQueue<Runnable> queue = new DynamicThreadPoolExecutor.DynamicQueue<Runnable>();\n      ThreadPoolExecutor executor = new DynamicThreadPoolExecutor(min, max, keepAliveTime,\n               TimeUnit.MILLISECONDS, queue, threadFactory);\n      executor.setRejectedExecutionHandler(new DynamicThreadPoolExecutor.ForceQueuePolicy());\n      queue.setThreadPoolExecutor(executor);\n      return executor;\n   }\n\n   /**\n    * Cannot instantiate.\n    */\n   private DynamicExecutors() {\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/concurrent/DynamicThreadPoolExecutor.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.concurrent;\n\nimport java.util.concurrent.BlockingQueue;\nimport java.util.concurrent.LinkedBlockingQueue;\nimport java.util.concurrent.RejectedExecutionException;\nimport java.util.concurrent.RejectedExecutionHandler;\nimport java.util.concurrent.ThreadFactory;\nimport java.util.concurrent.ThreadPoolExecutor;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicInteger;\n\n/**\n * An {@link ExecutorService} that executes each submitted task using one of possibly several pooled threads, normally\n * configured using {@link DynamicExecutors} factory methods.\n */\nclass DynamicThreadPoolExecutor extends ThreadPoolExecutor {\n   /**\n    * number of threads that are actively executing tasks\n    */\n   private final AtomicInteger activeCount = new AtomicInteger();\n\n   DynamicThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,\n         BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) {\n      super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);\n   }\n\n   @Override\n   public int getActiveCount() {\n      return activeCount.get();\n   }\n\n   @Override\n   protected void beforeExecute(Thread t, Runnable r) {\n      activeCount.incrementAndGet();\n   }\n\n   @Override\n   protected void afterExecute(Runnable r, Throwable t) {\n      activeCount.decrementAndGet();\n   }\n\n   /**\n    * Much like a {@link SynchronousQueue} which acts as a rendezvous channel. It is well suited for handoff designs, in\n    * which a tasks is only queued if there is an available thread to pick it up.\n    * <p/>\n    * This queue is correlated with a thread-pool, and allows insertions to the queue only if there is a free thread\n    * that can poll this task. Otherwise, the task is rejected and the decision is left up to one of the\n    * {@link RejectedExecutionHandler} policies:\n    * <ol>\n    * <li> {@link ForceQueuePolicy} - forces the queue to accept the rejected task.</li>\n    * <li> {@link TimedBlockingPolicy} - waits for a given time for the task to be executed.</li>\n    * </ol>\n    * \n    */\n   static class DynamicQueue<E> extends LinkedBlockingQueue<E> {\n      private static final long serialVersionUID = 1L;\n\n      /**\n       * The executor this Queue belongs to\n       */\n      private transient ThreadPoolExecutor executor;\n\n      /**\n       * Creates a <tt>DynamicQueue</tt> with a capacity of {@link Integer#MAX_VALUE}.\n       */\n      public DynamicQueue() {\n         super();\n      }\n\n      /**\n       * Creates a <tt>DynamicQueue</tt> with the given (fixed) capacity.\n       * \n       * @param capacity\n       *           the capacity of this queue.\n       */\n      DynamicQueue(int capacity) {\n         super(capacity);\n      }\n\n      /**\n       * Sets the executor this queue belongs to.\n       */\n      public void setThreadPoolExecutor(ThreadPoolExecutor executor) {\n         this.executor = executor;\n      }\n\n      /**\n       * Inserts the specified element at the tail of this queue if there is at least one available thread to run the\n       * current task. If all pool threads are actively busy, it rejects the offer.\n       * \n       * @param o\n       *           the element to add.\n       * @return <tt>true</tt> if it was possible to add the element to this queue, else <tt>false</tt>\n       * @see ThreadPoolExecutor#execute(Runnable)\n       */\n      @Override\n      public boolean offer(E o) {\n         int allWorkingThreads = executor.getActiveCount() + super.size();\n         return allWorkingThreads < executor.getPoolSize() && super.offer(o);\n      }\n   }\n\n   /**\n    * A handler for rejected tasks that adds the specified element to this queue, waiting if necessary for space to\n    * become available.\n    */\n   static class ForceQueuePolicy implements RejectedExecutionHandler {\n      public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {\n         if (executor.isShutdown()) {\n            throw new RejectedExecutionException(\"Rejected execution of task [\" + r.getClass()\n                  + \"] since the executor is shutdown.\");\n         }\n         try {\n            executor.getQueue().put(r);\n         } catch (InterruptedException e) {\n            // should never happen since we never wait\n            throw new RejectedExecutionException(e);\n         }\n      }\n   }\n\n   /**\n    * A handler for rejected tasks that inserts the specified element into this queue, waiting if necessary up to the\n    * specified wait time for space to become available.\n    */\n   static class TimedBlockingPolicy implements RejectedExecutionHandler {\n      private final long waitTime;\n\n      /**\n       * @param waitTime\n       *           wait time in milliseconds for space to become available.\n       */\n      TimedBlockingPolicy(long waitTime) {\n         this.waitTime = waitTime;\n      }\n\n      public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {\n         if (executor.isShutdown()) {\n            throw new RejectedExecutionException(\"Rejected execution of task [\" + r.getClass()\n                  + \"] since the executor is shutdown.\");\n         }\n         try {\n            boolean successful = executor.getQueue().offer(r, waitTime, TimeUnit.MILLISECONDS);\n            if (!successful)\n               throw new RejectedExecutionException(\"Rejected execution after waiting \" + waitTime + \" ms for task [\"\n                     + r.getClass() + \"] to be executed.\");\n         } catch (InterruptedException e) {\n            throw new RejectedExecutionException(e);\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/concurrent/FutureIterables.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.concurrent;\n\nimport static com.google.common.base.Throwables.propagate;\nimport static com.google.common.collect.Iterables.any;\nimport static com.google.common.collect.Iterables.transform;\nimport static com.google.common.collect.Maps.newConcurrentMap;\nimport static com.google.common.collect.Maps.newHashMap;\nimport static org.jclouds.util.Throwables2.containsThrowable;\nimport static org.jclouds.util.Throwables2.propagateAuthorizationOrOriginalException;\n\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.concurrent.ConcurrentMap;\nimport java.util.concurrent.CountDownLatch;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.TimeoutException;\nimport java.util.concurrent.atomic.AtomicInteger;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.Constants;\nimport org.jclouds.http.handlers.BackoffLimitedRetryHandler;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.rest.AuthorizationException;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Function;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.inject.Inject;\n\n/**\n * functions related to or replacing those in {@link com.google.common.collect.Iterables} dealing with Futures\n */\n@Beta\npublic class FutureIterables {\n\n   @Inject(optional = true)\n   @Named(Constants.PROPERTY_MAX_RETRIES)\n   private static int maxRetries = 5;\n\n   @Inject(optional = true)\n   @Named(Constants.PROPERTY_RETRY_DELAY_START)\n   private static long delayStart = 50L;\n\n   @Inject(optional = true)\n   private static BackoffLimitedRetryHandler retryHandler = BackoffLimitedRetryHandler.INSTANCE;\n\n   public static <F, T> Iterable<T> transformParallel(final Iterable<F> fromIterable,\n         final Function<? super F, ListenableFuture<? extends T>> function, ListeningExecutorService exec, @Nullable Long maxTime, Logger logger,\n               String logPrefix) {\n      return transformParallel(fromIterable, function, exec, maxTime, logger, logPrefix, retryHandler, maxRetries);\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   public static <F, T> Iterable<T> transformParallel(Iterable<F> fromIterable,\n         Function<? super F, ListenableFuture<? extends T>> function, ListeningExecutorService exec, @Nullable Long maxTime, Logger logger,\n               String logPrefix, BackoffLimitedRetryHandler retryHandler, int maxRetries) {\n      Map<F, Exception> exceptions = newHashMap();\n      Map<F, ListenableFuture<? extends T>> responses = newHashMap();\n      for (int i = 0; i < maxRetries; i++) {\n\n         for (F from : fromIterable) {\n            ListenableFuture<? extends T> to = function.apply(from);\n            responses.put(from, to);\n         }\n         try {\n            exceptions = awaitCompletion(responses, exec, maxTime, logger, logPrefix);\n         } catch (TimeoutException te) {\n            throw propagate(te);\n         }\n         if (!exceptions.isEmpty() && !any(exceptions.values(), containsThrowable(AuthorizationException.class))) {\n            fromIterable = exceptions.keySet();\n            retryHandler.imposeBackoffExponentialDelay(delayStart, 2, i + 1, maxRetries,\n                  String.format(\"error %s: %s: %s\", logPrefix, fromIterable, exceptions));\n         } else {\n            break;\n         }\n      }\n      //make sure we propagate any authorization exception so that we don't lock out accounts\n      if (!exceptions.isEmpty())\n         return propagateAuthorizationOrOriginalException(new TransformParallelException(Map.class.cast(responses),\n               exceptions, logPrefix));\n\n      return unwrap(responses.values());\n   }\n\n   public static <F> Map<F, Exception> awaitCompletion(Map<F, ? extends ListenableFuture<?>> responses,\n         ListeningExecutorService exec, @Nullable Long maxTime, final Logger logger, final String logPrefix)\n         throws TimeoutException {\n      final ConcurrentMap<F, Exception> errorMap = newConcurrentMap();\n      if (responses.isEmpty())\n         return errorMap;\n      final int total = responses.size();\n      final CountDownLatch doneSignal = new CountDownLatch(total);\n      final AtomicInteger complete = new AtomicInteger(0);\n      final AtomicInteger errors = new AtomicInteger(0);\n      final long start = System.currentTimeMillis();\n      for (final Entry<F, ? extends ListenableFuture<?>> future : responses.entrySet()) {\n         future.getValue().addListener(new Runnable() {\n\n            @Override\n            public void run() {\n               try {\n                  future.getValue().get();\n                  complete.incrementAndGet();\n               } catch (Exception e) {\n                  errors.incrementAndGet();\n                  logException(logger, logPrefix, total, complete.get(), errors.get(), start, e);\n                  errorMap.put(future.getKey(), e);\n               } finally {\n\t               doneSignal.countDown();\n               }\n            }\n\n            @Override\n            public String toString() {\n               return \"callGetOnFuture(\" + future.getKey() + \",\" + future.getValue() + \")\";\n            }\n         }, exec);\n      }\n      try {\n         if (maxTime != null) {\n            if (!doneSignal.await(maxTime, TimeUnit.MILLISECONDS)) {\n               String message = message(logPrefix, total, complete.get(), errors.get(), start);\n               TimeoutException te = new TimeoutException(message);\n               logger.error(te, message);\n               throw te;\n            }\n         } else {\n            doneSignal.await();\n         }\n         if (errors.get() > 0) {\n            String message = message(logPrefix, total, complete.get(), errors.get(), start);\n            RuntimeException exception = new RuntimeException(message);\n            logger.error(exception, message);\n         }\n         if (logger.isTraceEnabled()) {\n            String message = message(logPrefix, total, complete.get(), errors.get(), start);\n            logger.trace(message);\n         }\n      } catch (InterruptedException ie) {\n         String message = message(logPrefix, total, complete.get(), errors.get(), start);\n         logger.error(ie, message);\n         throw propagate(ie);\n      }\n      return errorMap;\n   }\n\n   private static <T> Iterable<T> unwrap(Iterable<ListenableFuture<? extends T>> values) {\n      return transform(values, new Function<ListenableFuture<? extends T>, T>() {\n         @Override\n         public T apply(ListenableFuture<? extends T> from) {\n            try {\n               return from.get();\n            } catch (InterruptedException e) {\n               propagate(e);\n            } catch (ExecutionException e) {\n               propagate(e);\n            }\n            return null;\n         }\n\n         @Override\n         public String toString() {\n            return \"callGetOnFuture()\";\n         }\n      });\n   }\n\n   private static void logException(Logger logger, String logPrefix, int total, int complete, int errors, long start,\n         Exception e) {\n      String message = message(logPrefix, total, complete, errors, start);\n      logger.error(e, message);\n   }\n\n   private static String message(String prefix, int size, int complete, int errors, long start) {\n      return String.format(\"%s, completed: %d/%d, errors: %d, rate: %dms/op\", prefix, complete, size, errors,\n            (long) ((System.currentTimeMillis() - start) / ((double) size)));\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/concurrent/SingleThreaded.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.concurrent;\n\nimport static java.lang.annotation.ElementType.TYPE;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\n/**\n * designates that the object must not exist in an environment that spawns threads.\n */\n@Retention(RUNTIME)\n@Target(TYPE)\npublic @interface SingleThreaded {\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/concurrent/TransformParallelException.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.concurrent;\n\nimport java.util.Map;\nimport java.util.concurrent.Future;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\n\n/**\n * A failure occurred while concurrently operating on an Iterable\n */\n@SuppressWarnings(\"serial\")\npublic final class TransformParallelException extends RuntimeException {\n\n   private final Map<?, Future<?>> success;\n   private final Map<?, Exception> exceptions;\n\n   public TransformParallelException(Map<?, Future<?>> success, Map<?, Exception> exceptions, String messagePrefix) {\n      super(String.format(\"error %s: %s\", messagePrefix, exceptions));\n      this.success = ImmutableMap.copyOf(success);\n      this.exceptions = ImmutableMap.copyOf(exceptions);\n      initCause(Iterables.get(exceptions.values(), 0));\n   }\n\n   /**\n    * @return Elements that performed the transform without error\n    */\n   public Map<?, Future<?>> getSuccessfulToValue() {\n      return success;\n   }\n\n   /**\n    * @return Elements that failed during the transform\n    */\n   public Map<?, Exception> getFromToException() {\n      return exceptions;\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/concurrent/config/ConfiguresExecutorService.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.concurrent.config;\n\nimport static java.lang.annotation.ElementType.TYPE;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\n/**\n * designates the the module configures a {@link HttpCommandExecutorService}\n */\n@Retention(RUNTIME)\n@Target(TYPE)\npublic @interface ConfiguresExecutorService {\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/concurrent/config/ExecutorServiceModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.concurrent.config;\n\nimport static com.google.common.util.concurrent.MoreExecutors.listeningDecorator;\nimport static org.jclouds.Constants.PROPERTY_USER_THREADS;\nimport static org.jclouds.concurrent.DynamicExecutors.newScalingThreadPool;\n\nimport java.io.Closeable;\nimport java.io.IOException;\nimport java.util.List;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.ThreadFactory;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.lifecycle.Closer;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.common.util.concurrent.SimpleTimeLimiter;\nimport com.google.common.util.concurrent.ThreadFactoryBuilder;\nimport com.google.common.util.concurrent.TimeLimiter;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Provides;\n\n/**\n * Configures {@link ListeningExecutorService}.\n *\n * Note that this uses threads.\n *\n * <p>\n * This extends the underlying Future to expose a description (the task's toString) and the submission context (stack\n * trace). The submission stack trace is appended to relevant stack traces on exceptions that are returned, so the user\n * can see the logical chain of execution (in the executor, and where it was passed to the executor).\n */\n@ConfiguresExecutorService\npublic class ExecutorServiceModule extends AbstractModule {\n\n   static final class ShutdownExecutorOnClose implements Closeable {\n      @Resource\n      private Logger logger = Logger.NULL;\n\n      private final ListeningExecutorService service;\n\n      private ShutdownExecutorOnClose(ListeningExecutorService service) {\n         this.service = service;\n      }\n\n      @Override\n      public void close() throws IOException {\n         List<Runnable> runnables = service.shutdownNow();\n         if (!runnables.isEmpty())\n            logger.warn(\"when shutting down executor %s, runnables outstanding: %s\", service, runnables);\n      }\n   }\n\n   final ListeningExecutorService userExecutorFromConstructor;\n\n   public ExecutorServiceModule() {\n      this.userExecutorFromConstructor = null;\n   }\n\n   /**\n    * @deprecated {@code ioExecutor} is no longer used. This constructor will be removed in jclouds v2.\n    * Use {@link #ExecutorServiceModule(ExecutorService)} instead.\n    */\n   @Deprecated\n   public ExecutorServiceModule(@Named(PROPERTY_USER_THREADS) ExecutorService userExecutor,\n         ExecutorService ioExecutor) {\n      this(userExecutor);\n   }\n\n   /**\n    * @deprecated {@code ioExecutor} is no longer used. This constructor will be removed in jclouds v2.\n    * Use {@link #ExecutorServiceModule(ListeningExecutorService)} instead.\n    */\n   @Deprecated\n   public ExecutorServiceModule(@Named(PROPERTY_USER_THREADS) ListeningExecutorService userExecutor,\n         ListeningExecutorService ioExecutor) {\n      this(userExecutor);\n   }\n\n   public ExecutorServiceModule(@Named(PROPERTY_USER_THREADS) ExecutorService userExecutor) {\n      this(listeningDecorator(userExecutor));\n   }\n\n   public ExecutorServiceModule(@Named(PROPERTY_USER_THREADS) ListeningExecutorService userExecutor) {\n      this.userExecutorFromConstructor = WithSubmissionTrace.wrap(userExecutor);\n   }\n\n   @Override\n   protected void configure() { // NO_UCD\n   }\n\n   @Provides\n   @Singleton\n   final TimeLimiter timeLimiter(@Named(PROPERTY_USER_THREADS) ListeningExecutorService userExecutor) {\n      return SimpleTimeLimiter.create(userExecutor);\n   }\n\n   @Provides\n   @Singleton\n   @Named(PROPERTY_USER_THREADS)\n   final ListeningExecutorService provideListeningUserExecutorService(@Named(PROPERTY_USER_THREADS) int count, Closer closer) { // NO_UCD\n      if (userExecutorFromConstructor != null)\n         return userExecutorFromConstructor;\n      return shutdownOnClose(WithSubmissionTrace.wrap(newThreadPoolNamed(\"user thread %d\", count)), closer);\n   }\n\n   @Provides\n   @Singleton\n   @Named(PROPERTY_USER_THREADS)\n   final ExecutorService provideUserExecutorService(@Named(PROPERTY_USER_THREADS) ListeningExecutorService in) { // NO_UCD\n      return in;\n   }\n\n   static <T extends ListeningExecutorService> T shutdownOnClose(final T service, Closer closer) {\n      closer.addToClose(new ShutdownExecutorOnClose(service));\n      return service;\n   }\n\n   private ListeningExecutorService newCachedThreadPoolNamed(String name) {\n      return listeningDecorator(Executors.newCachedThreadPool(namedThreadFactory(name)));\n   }\n\n   private ListeningExecutorService newThreadPoolNamed(String name, int maxCount) {\n      return maxCount == 0 ? newCachedThreadPoolNamed(name) : newScalingThreadPoolNamed(name, maxCount);\n   }\n\n   private ListeningExecutorService newScalingThreadPoolNamed(String name, int maxCount) {\n      return listeningDecorator(newScalingThreadPool(1, maxCount, 60L * 1000, namedThreadFactory(name)));\n   }\n\n   private ThreadFactory namedThreadFactory(String name) {\n      return new ThreadFactoryBuilder().setNameFormat(name).setThreadFactory(Executors.defaultThreadFactory()).build();\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/concurrent/config/ScheduledExecutorServiceModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.concurrent.config;\n\nimport static com.google.common.util.concurrent.MoreExecutors.listeningDecorator;\nimport static java.util.concurrent.Executors.defaultThreadFactory;\nimport static java.util.concurrent.Executors.newScheduledThreadPool;\nimport static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;\nimport static org.jclouds.Constants.PROPERTY_SCHEDULER_THREADS;\nimport static org.jclouds.concurrent.config.ExecutorServiceModule.shutdownOnClose;\n\nimport java.util.concurrent.ScheduledExecutorService;\nimport java.util.concurrent.ThreadFactory;\n\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.lifecycle.Closer;\n\nimport com.google.common.util.concurrent.ListeningScheduledExecutorService;\nimport com.google.common.util.concurrent.ThreadFactoryBuilder;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Provides;\n\n/**\n * Provides an {@link ScheduledExecutorService} to run periodical tasks such as virtual machine monitoring, etc.\n * <p>\n * This module is not registered by default in the context because some providers do not allow to spawn threads.\n * \n * \n * @see ExecutorServiceModule\n */\npublic class ScheduledExecutorServiceModule extends AbstractModule {\n   @Provides\n   @Singleton\n   @Named(PROPERTY_SCHEDULER_THREADS)\n   final ListeningScheduledExecutorService provideListeningScheduledExecutorService(\n         @Named(PROPERTY_SCHEDULER_THREADS) int count, Closer closer) {\n      return shutdownOnClose(WithSubmissionTrace.wrap(newScheduledThreadPoolNamed(\"scheduler thread %d\", count)),\n            closer);\n   }\n\n   @Provides\n   @Singleton\n   @Named(PROPERTY_SCHEDULER_THREADS)\n   final ScheduledExecutorService provideScheduledExecutor(\n         @Named(PROPERTY_SCHEDULER_THREADS) ListeningScheduledExecutorService in) {\n      return in;\n   }\n\n   private static ListeningScheduledExecutorService newScheduledThreadPoolNamed(String name, int maxCount) {\n      ThreadFactory factory = new ThreadFactoryBuilder().setNameFormat(name).setThreadFactory(defaultThreadFactory())\n            .build();\n      return listeningDecorator(maxCount == 0 ? newSingleThreadScheduledExecutor(factory) : newScheduledThreadPool(\n            maxCount, factory));\n   }\n\n   @Override\n   protected void configure() { // NO_UCD\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/concurrent/config/WithSubmissionTrace.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.concurrent.config;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.toArray;\nimport static com.google.common.collect.ObjectArrays.concat;\n\nimport java.util.Arrays;\nimport java.util.Set;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.Delayed;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.Executor;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.TimeoutException;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.util.concurrent.ForwardingFuture;\nimport com.google.common.util.concurrent.ForwardingListenableFuture;\nimport com.google.common.util.concurrent.ForwardingListeningExecutorService;\n\npublic class WithSubmissionTrace {\n\n   private WithSubmissionTrace() {\n   }\n\n   public static ListeningExecutorService wrap(com.google.common.util.concurrent.ListeningExecutorService delegate) {\n      return new ListeningExecutorService(delegate);\n   }\n\n   private static class ListeningExecutorService extends ForwardingListeningExecutorService {\n\n      private final com.google.common.util.concurrent.ListeningExecutorService delegate;\n\n      private ListeningExecutorService(com.google.common.util.concurrent.ListeningExecutorService delegate) {\n         this.delegate = checkNotNull(delegate, \"delegate\");\n      }\n\n      @Override\n      protected com.google.common.util.concurrent.ListeningExecutorService delegate() {\n         return delegate;\n      }\n\n      @Override\n      public <T> com.google.common.util.concurrent.ListenableFuture<T> submit(Callable<T> task) {\n         return new ListenableFuture<T>(delegate().submit(task));\n      }\n\n      @SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n      @Override\n      public com.google.common.util.concurrent.ListenableFuture<?> submit(Runnable task) {\n         return new ListenableFuture(delegate().submit(task));\n      }\n\n      @Override\n      public <T> com.google.common.util.concurrent.ListenableFuture<T> submit(Runnable task, T result) {\n         return new ListenableFuture<T>(delegate().submit(task, result));\n      }\n   }\n\n   private static class ListenableFuture<T> extends ForwardingListenableFuture<T> {\n      private final com.google.common.util.concurrent.ListenableFuture<T> delegate;\n      private final StackTraceElement[] submissionTrace;\n\n      ListenableFuture(com.google.common.util.concurrent.ListenableFuture<T> delegate) {\n         this.delegate = checkNotNull(delegate, \"delegate\");\n         this.submissionTrace = getStackTraceHere();\n      }\n\n      @Override\n      protected com.google.common.util.concurrent.ListenableFuture<T> delegate() {\n         return delegate;\n      }\n\n      @Override\n      public T get() throws InterruptedException, ExecutionException {\n         try {\n            return delegate().get();\n         } catch (ExecutionException e) {\n            throw addSubmissionTrace(submissionTrace, e);\n         }\n      }\n\n      @Override\n      public T get(long arg0, TimeUnit arg1) throws InterruptedException, ExecutionException, TimeoutException {\n         try {\n            return delegate().get(arg0, arg1);\n         } catch (ExecutionException e) {\n            throw addSubmissionTrace(submissionTrace, e);\n         }\n      }\n   }\n\n   private static final Set<String> stackTracesToTrim = ImmutableSet.of(WithSubmissionTrace.class.getName(),\n         ListeningExecutorService.class.getName(), ListenableFuture.class.getName(),\n         ListeningScheduledExecutorService.class.getName(), ScheduledFuture.class.getName(),\n         ListenableScheduledFuture.class.getName());\n\n   /** returns the stack trace at the caller */\n   private static StackTraceElement[] getStackTraceHere() {\n      StackTraceElement[] trace = Thread.currentThread().getStackTrace();\n      return filterTrace(trace);\n   }\n\n   private static StackTraceElement[] filterTrace(StackTraceElement[] trace) {\n      return toArray(filter(Arrays.asList(trace), new Predicate<StackTraceElement>() {\n         public boolean apply(StackTraceElement input) {\n            String className = input.getClassName();\n            return !stackTracesToTrim.contains(className);\n         }\n      }), StackTraceElement.class);\n   }\n\n   private static ExecutionException addSubmissionTrace(StackTraceElement[] submissionTrace, ExecutionException e) {\n      if (e.getCause() == null) {\n         return filterTrace(e);\n      }\n      Throwable cause = e.getCause();\n      StackTraceElement[] combined = filterTrace(concat(cause.getStackTrace(), submissionTrace, StackTraceElement.class));\n      cause.setStackTrace(combined);\n      return filterTrace(e);\n   }\n\n   private static ExecutionException filterTrace(ExecutionException e) {\n      StackTraceElement[] withoutHere = filterTrace(e.getStackTrace());\n      e.setStackTrace(withoutHere);\n      return e;\n   }\n\n   public static ListeningScheduledExecutorService wrap(\n         com.google.common.util.concurrent.ListeningScheduledExecutorService delegate) {\n      return new ListeningScheduledExecutorService(delegate);\n   }\n\n   private static class ListeningScheduledExecutorService extends ListeningExecutorService implements\n         com.google.common.util.concurrent.ListeningScheduledExecutorService {\n\n      private ListeningScheduledExecutorService(\n            com.google.common.util.concurrent.ListeningScheduledExecutorService delegate) {\n         super(delegate);\n      }\n\n      @Override\n      protected com.google.common.util.concurrent.ListeningScheduledExecutorService delegate() {\n         return com.google.common.util.concurrent.ListeningScheduledExecutorService.class.cast(super.delegate());\n      }\n\n      @Override\n      public <T> ListenableFuture<T> submit(Callable<T> task) {\n         return new ListenableFuture<T>(delegate().submit(task));\n      }\n\n      @SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n      @Override\n      public ListenableFuture<?> submit(Runnable task) {\n         return new ListenableFuture(delegate().submit(task));\n      }\n\n      @Override\n      public <T> ListenableFuture<T> submit(Runnable task, T result) {\n         return new ListenableFuture<T>(delegate().submit(task, result));\n      }\n\n      @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n      @Override\n      public ListenableScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {\n         return new ListenableScheduledFuture(delegate().schedule(command, delay, unit));\n      }\n\n      @Override\n      public <V> ListenableScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {\n         return new ListenableScheduledFuture(delegate().schedule(callable, delay, unit));\n      }\n\n      @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n      @Override\n      public ListenableScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {\n         return new ListenableScheduledFuture(delegate().scheduleAtFixedRate(command, initialDelay, period, unit));\n      }\n\n      @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n      @Override\n      public ListenableScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {\n         return new ListenableScheduledFuture(delegate().scheduleWithFixedDelay(command, initialDelay, delay, unit));\n      }\n\n   }\n\n   private static class ScheduledFuture<T> extends ForwardingFuture<T> implements\n         java.util.concurrent.ScheduledFuture<T> {\n\n      private final java.util.concurrent.ScheduledFuture<T> delegate;\n      private final StackTraceElement[] submissionTrace;\n\n      private ScheduledFuture(java.util.concurrent.ScheduledFuture<T> delegate) {\n         this.delegate = checkNotNull(delegate, \"delegate\");\n         this.submissionTrace = getStackTraceHere();\n      }\n\n      @Override\n      protected java.util.concurrent.ScheduledFuture<T> delegate() {\n         return delegate;\n      }\n\n      @Override\n      public long getDelay(TimeUnit arg0) {\n         return delegate().getDelay(arg0);\n      }\n\n      @Override\n      public int compareTo(Delayed arg0) {\n         return delegate().compareTo(arg0);\n      }\n\n      @Override\n      public T get() throws InterruptedException, ExecutionException {\n         try {\n            return delegate().get();\n         } catch (ExecutionException e) {\n            throw addSubmissionTrace(submissionTrace, e);\n         }\n      }\n\n      @Override\n      public T get(long arg0, TimeUnit arg1) throws InterruptedException, ExecutionException, TimeoutException {\n         try {\n            return delegate().get(arg0, arg1);\n         } catch (ExecutionException e) {\n            throw addSubmissionTrace(submissionTrace, e);\n         }\n      }\n   }\n\n   private static class ListenableScheduledFuture<T> extends ScheduledFuture<T>\n         implements com.google.common.util.concurrent.ListenableScheduledFuture<T> {\n      private ListenableScheduledFuture(com.google.common.util.concurrent.ListenableScheduledFuture<T> delegate) {\n         super(delegate);\n      }\n\n      @Override\n      public void addListener(Runnable listener, Executor executor) {\n         ((com.google.common.util.concurrent.ListenableScheduledFuture<T>) delegate()).addListener(listener, executor);\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/config/BindApiContextWithWildcardExtendsExplicitAndRawType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.config;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.reflect.Reflection2.typeToken;\n\nimport org.jclouds.rest.ApiContext;\nimport org.jclouds.rest.HttpApiMetadata;\nimport org.jclouds.rest.internal.ApiContextImpl;\nimport org.jclouds.rest.internal.BaseHttpApiMetadata;\n\nimport com.google.common.reflect.TypeToken;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.util.Types;\n\n/**\n * Allows you to lookup the {@link HttpApiMetadata#getContext()} as\n * {@link ApiContext}, {@code ApiContext<Api>}, and {@code ApiContext<?>}.\n */\npublic class BindApiContextWithWildcardExtendsExplicitAndRawType extends AbstractModule {\n   private final HttpApiMetadata<?> httpApiMetadata;\n\n   public BindApiContextWithWildcardExtendsExplicitAndRawType(HttpApiMetadata<?> httpApiMetadata)\n         throws IllegalArgumentException {\n      this.httpApiMetadata = checkNotNull(httpApiMetadata, \"httpApiMetadata\");\n      checkArgument(httpApiMetadata.getContext().getRawType().equals(ApiContext.class),\n            \"this does not work as %s raw type is not ApiContext\", httpApiMetadata.getContext());\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   protected void configure() {\n      TypeToken<?> concreteType = BaseHttpApiMetadata.contextToken(typeToken(httpApiMetadata.getApi()));\n      // bind explicit type\n      bind(TypeLiteral.get(concreteType.getType())).to(\n            TypeLiteral.class.cast(TypeLiteral.get(Types.newParameterizedType(ApiContextImpl.class,\n                  httpApiMetadata.getApi()))));\n      // bind potentially wildcard type\n      if (!concreteType.equals(httpApiMetadata.getContext())) {\n         bind(TypeLiteral.get(httpApiMetadata.getContext().getType())).to(\n               TypeLiteral.class.cast(TypeLiteral.get(Types.newParameterizedType(ApiContextImpl.class,\n                     httpApiMetadata.getApi()))));\n      }\n      // bind w/o types\n      bind(TypeLiteral.get(ApiContext.class)).to(\n            TypeLiteral.class.cast(TypeLiteral.get(Types.newParameterizedType(ApiContextImpl.class,\n                  httpApiMetadata.getApi()))));\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/config/BindNameToContext.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.config;\n\nimport com.google.inject.AbstractModule;\nimport org.jclouds.annotations.Name;\n\n/**\n * Binds name to Context.\n */\npublic class BindNameToContext extends AbstractModule {\n\n   private final String name;\n\n   public BindNameToContext(String name) {\n      this.name = name;\n   }\n\n   @Override\n   protected void configure() {\n      bind(String.class).annotatedWith(Name.class).toInstance(name);\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/config/ContextLinking.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.config;\n\nimport org.jclouds.Context;\nimport org.jclouds.View;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Module;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.name.Names;\n\n/**\n * Utility methods to allow {@link Context} and {@link View} linking between\n * contexts.\n * <p>\n * By using this module users can configure a context to be able to inject other\n * contexts or views by their provider id.\n */\npublic class ContextLinking {\n\n   static final TypeLiteral<Supplier<Context>> CONTEXT_SUPPLIER = new TypeLiteral<Supplier<Context>>() {\n   };\n\n   static final TypeLiteral<Supplier<View>> VIEW_SUPPLIER = new TypeLiteral<Supplier<View>>() {\n   };\n\n   public static Module linkView(final String id, final Supplier<View> view) {\n      return new AbstractModule() {\n         @Override\n         protected void configure() {\n            bind(VIEW_SUPPLIER).annotatedWith(Names.named(id)).toInstance(view);\n            bind(CONTEXT_SUPPLIER).annotatedWith(Names.named(id)).toInstance(Suppliers.compose(ViewToContext, view));\n         }\n      };\n   }\n\n   public static Module linkContext(final String id, final Supplier<Context> context) {\n      return new AbstractModule() {\n         @Override\n         protected void configure() {\n            bind(CONTEXT_SUPPLIER).annotatedWith(Names.named(id)).toInstance(context);\n         }\n      };\n   }\n\n   public static Module linkView(View view) {\n      return linkView(view.unwrap().getId(), Suppliers.ofInstance(view));\n   }\n\n   public static Module linkContext(Context context) {\n      return linkContext(context.getId(), Suppliers.ofInstance(context));\n   }\n\n   private static final Function<View, Context> ViewToContext = new Function<View, Context>() {\n      @Override\n      public Context apply(View input) {\n         return input.unwrap();\n      }\n   };\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/config/ValueOfConfigurationKeyOrNull.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.config;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.inject.name.Names.named;\n\nimport jakarta.inject.Inject;\n\nimport com.google.common.base.Function;\nimport com.google.inject.ConfigurationException;\nimport com.google.inject.Injector;\nimport com.google.inject.Key;\n\npublic class ValueOfConfigurationKeyOrNull implements Function<String, String> {\n   private final Injector injector;\n\n   @Inject\n   private ValueOfConfigurationKeyOrNull(Injector injector) {\n      this.injector = checkNotNull(injector, \"injector\");\n   }\n\n   @Override\n   public String apply(String configurationKey) {\n      checkNotNull(configurationKey, \"configurationKey\");\n      try {\n         return injector.getInstance(Key.get(String.class, named(configurationKey)));\n      } catch (ConfigurationException e) {\n         return null;\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/crypto/ASN1Codec.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.crypto;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Predicates.notNull;\nimport static com.google.common.base.Throwables.propagate;\nimport static com.google.common.collect.Iterators.filter;\nimport static com.google.common.io.ByteStreams.limit;\nimport static com.google.common.io.ByteStreams.toByteArray;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.math.BigInteger;\nimport java.security.interfaces.RSAPrivateCrtKey;\nimport java.security.spec.RSAPrivateCrtKeySpec;\nimport java.security.spec.RSAPublicKeySpec;\nimport java.util.Iterator;\nimport java.util.List;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableList.Builder;\nimport com.google.common.primitives.Bytes;\n\n/**\n * \n * This codec is based on code from {@code bouncycastle.org}. It simplifies extraction of RSA keys from {@code ASN.1}\n * encoding. This only parses the {@code BigInteger} elements needed to generate {@link KeySpec}\n */\n@Beta\nfinal class ASN1Codec {\n\n   private ASN1Codec() {\n   };\n\n   @SuppressWarnings(\"unchecked\")\n   static RSAPublicKeySpec decodeRSAPublicKey(byte[] bytes) {\n      List<Object> seq = createASN1Sequence(bytes);\n      checkArgument(seq.size() == 2, \"expected 2 components of ASN1Sequence: %s\", seq);\n      if (seq.get(1) instanceof List) {\n         seq = List.class.cast(seq.get(1));\n      }\n      return new RSAPublicKeySpec(bigIntAt(seq, 0), bigIntAt(seq, 1));\n   }\n\n   static RSAPrivateCrtKeySpec decodeRSAPrivateKey(byte[] bytes) {\n      List<Object> seq = createASN1Sequence(bytes);\n      checkArgument(seq.size() >= 9, \"not enough elements (%s) for a private key\", seq.size(), seq);\n      int version = bigIntAt(seq, 0).intValue();\n      checkArgument(version == 0 || version == 1, \"wrong version %s for RSA private key\", version);\n      return new RSAPrivateCrtKeySpec(bigIntAt(seq, 1), bigIntAt(seq, 2), bigIntAt(seq, 3), bigIntAt(seq, 4), bigIntAt(\n            seq, 5), bigIntAt(seq, 6), bigIntAt(seq, 7), bigIntAt(seq, 8));\n   }\n\n   private static BigInteger bigIntAt(List<Object> seq, int index) {\n      return BigInteger.class.cast(seq.get(index));\n   }\n\n   private static final int TAG = 0x02;\n   private static final int CONSTRUCTED = 0x20;\n   private static final int INTEGER = 0x02;\n   private static final int BIT_STRING = 0x03;\n   private static final int SEQUENCE = 0x10;\n\n   @SuppressWarnings(\"unchecked\")\n   private static List<Object> createASN1Sequence(byte[] input) {\n      Object out = create(new ByteArrayInputStream(input), input.length).get();\n      checkArgument(out instanceof List, \"expected List not %s\", out);\n      return List.class.cast(out);\n   }\n\n   /**\n    * skips most {@code ASN.1} tags as we are only interested in the integers. As such, this either creates a\n    * {@code BigInteger}, a list of them, or a nested list.\n    */\n   private static Optional<Object> buildObject(int tag, int tagNo, InputStream in, int limit) {\n      boolean isConstructed = (tag & CONSTRUCTED) != 0;\n      InputStream limited = limit(in, limit);\n      if (isConstructed && tagNo == SEQUENCE) {\n         return Optional.<Object> of(buildEncodableList(limited, limit));\n      }\n      byte[] bytes = toArray(limited);\n      switch (tagNo) {\n      case BIT_STRING:\n         return Optional.<Object> of(nestedASN1Sequence(bytes));\n      case INTEGER:\n         return Optional.<Object> of(new BigInteger(bytes));\n      }\n      return Optional.absent();\n   }\n\n   private static List<Object> nestedASN1Sequence(byte[] bytes) {\n      checkArgument(bytes.length >= 1, \"truncated BIT_STRING detected\");\n      byte[] data = new byte[bytes.length - 1];\n      System.arraycopy(bytes, 1, data, 0, bytes.length - 1);\n      return createASN1Sequence(data);\n   }\n\n   private static List<Object> buildEncodableList(final InputStream in, final int limit) {\n      return ImmutableList.copyOf(filter(new Iterator<Object>() {\n\n         boolean hasNext = true;\n\n         public boolean hasNext() {\n            return hasNext;\n         }\n\n         public Object next() {\n            int tag = read(in);\n            if (tag == -1) {\n               hasNext = false;\n               return null;\n            }\n            checkArgument(tag != 0, \"invalid tag %s\", tag);\n            int tagNo = tag & 0x1f;\n            int length = readLength(in, limit);\n            checkArgument(length >= 0, \"indefinite length not supported\");\n            return buildObject(tag, tagNo, in, length).orNull();\n         }\n\n         public void remove() {\n         }\n\n      }, notNull()));\n   }\n\n   private static Optional<Object> create(InputStream in, int limit) {\n      int tag = read(in);\n      if (tag == -1)\n         return Optional.absent();\n      checkArgument(tag != 0, \"invalid tag %s\", tag);\n      int tagNo = tag & 0x1f;\n      int length = readLength(in, limit);\n      checkArgument(length >= 0, \"indefinite length not supported\");\n      return buildObject(tag, tagNo, in, length);\n   }\n\n   private static int readLength(InputStream s, int limit) {\n      int length = read(s);\n      checkArgument(length >= 0, \"EOF found when length expected\");\n      checkArgument(length != 0x80, \"indefinite-length encoding not supported\");\n      if (length > 127) {\n         int size = length & 0x7f;\n         checkArgument(size <= 4, \"DER length more than 4 bytes: %s\", size);\n         length = 0;\n         for (int i = 0; i < size; i++) {\n            int next = read(s);\n            checkArgument(next >= 0, \"EOF found reading length\");\n            length = (length << 8) + next;\n         }\n         checkArgument(length >= 0, \"corrupted stream - negative length %s found\", length);\n         checkArgument(length < limit, \"corrupted stream - length %s out of bounds %s\", length, limit);\n      }\n      return length;\n   }\n\n   private static int read(InputStream s) {\n      try {\n         return s.read();\n      } catch (IOException e) {\n         throw propagate(e);  // impossible as we are only using a byte array\n      }\n   }\n\n   private static byte[] toArray(InputStream limited) {\n      try {\n         return toByteArray(limited);\n      } catch (IOException e) {\n         throw propagate(e); // impossible as we are only using a byte array\n      }\n   }\n\n   static byte[] encode(RSAPrivateCrtKey key) {\n      List<BigInteger> seq = ImmutableList.<BigInteger> builder()\n                                          .add(BigInteger.valueOf(0)) // version\n                                          .add(key.getModulus())\n                                          .add(key.getPublicExponent())\n                                          .add(key.getPrivateExponent())\n                                          .add(key.getPrimeP())\n                                          .add(key.getPrimeQ())\n                                          .add(key.getPrimeExponentP())\n                                          .add(key.getPrimeExponentQ())\n                                          .add(key.getCrtCoefficient()).build();\n      int length = 0;\n      for (BigInteger part : seq) {\n         byte[] bytes = part.toByteArray();\n         length += 1 + calculateBodyLength(bytes.length) + bytes.length;\n      }\n\n      Builder<Byte> output = ImmutableList.<Byte> builder();\n      output.add((byte) (SEQUENCE | CONSTRUCTED));\n      writeLength(output, length);\n      for (BigInteger part : seq) {\n         byte[] bytes = part.toByteArray();\n         output.add((byte) TAG);\n         writeLength(output, bytes.length);\n         output.addAll(Bytes.asList(bytes));\n      }\n      return Bytes.toArray(output.build());\n   }\n\n   private static void writeLength(Builder<Byte> output, int length) {\n      if (length > 127) {\n         int size = 1;\n         int val = length;\n         while ((val >>>= 8) != 0) {\n            size++;\n         }\n         output.add((byte) (size | 0x80));\n         for (int i = (size - 1) * 8; i >= 0; i -= 8) {\n            output.add((byte) (length >> i));\n         }\n      } else {\n         output.add((byte) length);\n      }\n   }\n\n   private static int calculateBodyLength(int length) {\n      int count = 1;\n      if (length > 127) {\n         int size = 1;\n         int val = length;\n         while ((val >>>= 8) != 0) {\n            size++;\n         }\n         for (int i = (size - 1) * 8; i >= 0; i -= 8) {\n            count++;\n         }\n      }\n      return count;\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/crypto/Crypto.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.crypto;\n\nimport java.security.InvalidKeyException;\nimport java.security.KeyFactory;\nimport java.security.KeyPairGenerator;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.cert.CertificateFactory;\n\nimport javax.crypto.Cipher;\nimport javax.crypto.Mac;\nimport javax.crypto.NoSuchPaddingException;\n\nimport org.jclouds.encryption.internal.JCECrypto;\n\nimport com.google.inject.ImplementedBy;\n\n/**\n * Allows you to access cryptographic objects and factories without adding a provider to the JCE runtime.\n */\n@ImplementedBy(JCECrypto.class)\npublic interface Crypto {\n   KeyPairGenerator rsaKeyPairGenerator();\n\n   KeyFactory rsaKeyFactory();\n\n   CertificateFactory certFactory();\n\n   Mac hmac(String algorithm, byte[] key) throws NoSuchAlgorithmException, InvalidKeyException;\n\n   Mac hmacSHA256(byte[] key) throws InvalidKeyException;\n\n   Mac hmacSHA1(byte[] key) throws InvalidKeyException;\n\n   Cipher cipher(String algorithm) throws NoSuchAlgorithmException, NoSuchPaddingException;\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/crypto/Macs.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.crypto;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport javax.crypto.Mac;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.io.ByteProcessor;\n\n/**\n * functions for {@link Mac}\n */\n@Beta\npublic class Macs {\n\n   /**\n    * Computes and returns the MAC value for a supplied input stream.\n    * \n    * @param mac\n    *           the mac object\n    * @return the result of {@link Mac#doFinal()} on {@link ByteProcessor#getResult()}\n    */\n   public static ByteProcessor<byte[]> asByteProcessor(final Mac mac) {\n      checkNotNull(mac, \"mac\");\n      return new ByteProcessor<byte[]>() {\n         public boolean processBytes(byte[] buf, int off, int len) {\n            mac.update(buf, off, len);\n            return true;\n         }\n\n         public byte[] getResult() {\n            return mac.doFinal();\n         }\n      };\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/crypto/Pems.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.crypto;\n\nimport static com.google.common.base.Charsets.US_ASCII;\nimport static com.google.common.base.Joiner.on;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.common.base.Splitter.fixedLength;\nimport static com.google.common.base.Throwables.propagate;\nimport static com.google.common.base.Throwables.propagateIfInstanceOf;\nimport static com.google.common.io.BaseEncoding.base64;\nimport static org.jclouds.crypto.ASN1Codec.decodeRSAPrivateKey;\nimport static org.jclouds.crypto.ASN1Codec.decodeRSAPublicKey;\nimport static org.jclouds.crypto.ASN1Codec.encode;\nimport static org.jclouds.util.Closeables2.closeQuietly;\n\nimport java.io.BufferedReader;\nimport java.io.ByteArrayInputStream;\nimport java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.StringReader;\nimport java.nio.charset.StandardCharsets;\nimport java.security.PrivateKey;\nimport java.security.PublicKey;\nimport java.security.cert.CertificateEncodingException;\nimport java.security.cert.CertificateException;\nimport java.security.cert.CertificateFactory;\nimport java.security.cert.X509Certificate;\nimport java.security.interfaces.RSAPrivateCrtKey;\nimport java.security.interfaces.RSAPublicKey;\nimport java.security.spec.KeySpec;\nimport java.security.spec.PKCS8EncodedKeySpec;\nimport java.security.spec.X509EncodedKeySpec;\nimport java.util.Map;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Charsets;\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.io.ByteProcessor;\nimport com.google.common.io.ByteSource;\n\n/**\n * Reads and writes PEM encoded Strings and Streams\n */\n@Beta\npublic class Pems {\n   public static final String PRIVATE_PKCS1_MARKER = \"-----BEGIN RSA PRIVATE KEY-----\";\n   public static final String PRIVATE_PKCS8_MARKER = \"-----BEGIN PRIVATE KEY-----\";\n   public static final String CERTIFICATE_X509_MARKER = \"-----BEGIN CERTIFICATE-----\";\n   public static final String PUBLIC_X509_MARKER = \"-----BEGIN PUBLIC KEY-----\";\n   public static final String PUBLIC_PKCS1_MARKER = \"-----BEGIN RSA PUBLIC KEY-----\";\n   public static final String PROC_TYPE_ENCRYPTED = \"Proc-Type: 4,ENCRYPTED\";\n\n   private static class PemProcessor<T> implements ByteProcessor<T> {\n      private interface ResultParser<T> {\n         T parseResult(byte[] bytes) throws IOException;\n      }\n\n      private final ByteArrayOutputStream out = new ByteArrayOutputStream();\n      private final Map<String, ResultParser<T>> parsers;\n\n      private PemProcessor(Map<String, ResultParser<T>> parsers) {\n         this.parsers = checkNotNull(parsers, \"parsers\");\n      }\n\n      @Override\n      public boolean processBytes(byte[] buf, int off, int len) {\n         out.write(buf, off, len);\n         return true;\n      }\n\n      @Override\n      public T getResult() {\n         Pem pem = PemReader.INSTANCE.apply(new String(out.toByteArray(), US_ASCII));\n         String beginMarker = \"-----BEGIN \" + pem.type + \"-----\";\n         checkState(parsers.containsKey(beginMarker), \"Invalid PEM: no parsers for marker %s in %s\", beginMarker,\n               parsers.keySet());\n         try {\n            return parsers.get(beginMarker).parseResult(pem.content);\n         } catch (IOException e) {\n            throw new IllegalStateException(\"Invalid PEM : \" + pem, e);\n         }\n      }\n   }\n\n   /**\n    * Parsed PEM format\n    * \n    * <pre>\n    *  -----BEGIN RSA PRIVATE KEY-----\n    *  Proc-Type: 4,ENCRYPTED\n    *  DEK-Info: DES-EDE3-CBC,3F17F5316E2BAC89\n    * \n    *  ...base64 encoded data...\n    *  -----END RSA PRIVATE KEY-----\n    * \n    * </pre>\n    * \n    */\n   private static enum PemReader implements Function<CharSequence, Pem> {\n      INSTANCE;\n      private static final String BEGIN = \"-----BEGIN \";\n      private static final String END = \"-----END \";\n\n      @Override\n      public Pem apply(CharSequence chars) {\n         checkNotNull(chars, \"chars\");\n         BufferedReader reader = null;\n         try {\n           reader  =  new BufferedReader(new StringReader(chars.toString()));\n            Optional<String> begin = skipUntilBegin(reader);\n            checkArgument(begin.isPresent(), \"chars %s doesn't contain % line\", chars, BEGIN);\n            String line = begin.get().substring(BEGIN.length());\n            String type = line.substring(0, line.indexOf('-'));\n            StringBuilder encoded = new StringBuilder();\n\n            boolean reachedEnd = false;\n            while ((line = reader.readLine()) != null) {\n               if (line.indexOf(':') >= 0) { // skip headers\n                  continue;\n               }\n               if (line.indexOf(END + type) != -1) {\n                  reachedEnd = true;\n                  break;\n               }\n               encoded.append(line.trim());\n            }\n\n            checkArgument(reachedEnd, \"chars %s doesn't contain % line\", chars, END);\n            return new Pem(type, base64().decode(encoded.toString()));\n         } catch (IOException e) {\n            throw new IllegalStateException(String.format(\"io exception reading %s\", chars), e);\n         } finally {\n            closeQuietly(reader);\n         }\n\n      }\n\n      private static Optional<String> skipUntilBegin(BufferedReader reader) throws IOException {\n         String line = reader.readLine();\n         while (line != null && !line.startsWith(BEGIN)) {\n            line = reader.readLine();\n         }\n         return Optional.fromNullable(line);\n      }\n   }\n\n   private static final class Pem {\n\n      private final String type;\n      private final byte[] content;\n\n      private Pem(String type, byte[] content) {\n         this.type = checkNotNull(type, \"type\");\n         this.content = checkNotNull(content, \"content\");\n      }\n\n      @Override\n      public String toString() {\n         return type + \" \" + new String(content, StandardCharsets.UTF_8);\n      }\n   }\n\n   /**\n    * Returns the object of generic type {@code T} that is pem encoded in the supplier.\n    * \n    * @param supplier\n    *           the input stream factory\n    * @param marker\n    *           header that begins the PEM block\n    * @param processor\n    *           how to parser the object from a byte array\n    * @return the object of generic type {@code T} which was PEM encoded in the stream\n    * @throws IOException\n    *            if an I/O error occurs\n    */\n   public static <T> T fromPem(ByteSource supplier, PemProcessor<T> processor)\n         throws IOException {\n      try {\n         return supplier.read(processor);\n      } catch (RuntimeException e) {\n         propagateIfInstanceOf(e.getCause(), IOException.class);\n         propagateIfInstanceOf(e, IOException.class);\n         throw e;\n      }\n   }\n\n   /**\n    * Returns the {@link RSAPrivateKeySpec} that is pem encoded in the supplier.\n    * \n    * @param supplier\n    *           the input stream factory\n    * \n    * @return the {@link RSAPrivateKeySpec} which was PEM encoded in the stream\n    * @throws IOException\n    *            if an I/O error occurs\n    */\n   public static KeySpec privateKeySpec(ByteSource supplier) throws IOException {\n      return fromPem(\n            supplier,\n            new PemProcessor<KeySpec>(ImmutableMap.<String, PemProcessor.ResultParser<KeySpec>> of(\n                  PRIVATE_PKCS1_MARKER, DecodeRSAPrivateCrtKeySpec.INSTANCE, PRIVATE_PKCS8_MARKER,\n                  new PemProcessor.ResultParser<KeySpec>() {\n                     @Override\n                     public KeySpec parseResult(byte[] bytes) throws IOException {\n                        return new PKCS8EncodedKeySpec(bytes);\n                     }\n\n                  })));\n   }\n\n   /**\n    * Decode PKCS#1 encoded private key into RSAPrivateCrtKeySpec.\n    * \n    * @param keyBytes\n    *           Encoded PKCS#1 rsa key.\n    */\n   private static enum DecodeRSAPrivateCrtKeySpec implements PemProcessor.ResultParser<KeySpec> {\n      INSTANCE;\n\n      @Override\n      public KeySpec parseResult(byte[] bytes) throws IOException {\n         return decodeRSAPrivateKey(bytes);\n      }\n   }\n\n   /**\n    * Executes {@link Pems#privateKeySpec(ByteSource)} on the string which contains an encoded private key in PEM\n    * format.\n    * \n    * @param pem\n    *           private key in pem encoded format.\n    * @see Pems#privateKeySpec(ByteSource)\n    */\n   public static KeySpec privateKeySpec(String pem) {\n      try {\n         return privateKeySpec(ByteSource.wrap(\n            pem.getBytes(Charsets.UTF_8)));\n      } catch (IOException e) {\n         throw propagate(e);\n      }\n   }\n\n   /**\n    * Returns the {@link KeySpec} that is pem encoded in the supplier.\n    * \n    * @param supplier\n    *           the input stream factory\n    * \n    * @return the {@link KeySpec} which was PEM encoded in the stream\n    * @throws IOException\n    *            if an I/O error occurs\n    */\n   public static KeySpec publicKeySpec(ByteSource supplier) throws IOException {\n      return fromPem(\n            supplier,\n            new PemProcessor<KeySpec>(ImmutableMap.<String, PemProcessor.ResultParser<KeySpec>> of(PUBLIC_PKCS1_MARKER,\n                  DecodeRSAPublicKeySpec.INSTANCE, PUBLIC_X509_MARKER, new PemProcessor.ResultParser<KeySpec>() {\n\n                     @Override\n                     public X509EncodedKeySpec parseResult(byte[] bytes) throws IOException {\n                        return new X509EncodedKeySpec(bytes);\n                     }\n\n                  })));\n   }\n\n   /**\n    * Decode PKCS#1 encoded public key into RSAPublicKeySpec.\n    * <p>\n    * Keys here can be in two different formats. They can have the algorithm encoded, or they can have only the modulus\n    * and the public exponent.\n    * <p>\n    * The latter is not a valid PEM encoded file, but it is a valid DER encoded RSA key, so this method should also\n    * support it.\n    * \n    * @param keyBytes\n    *           Encoded PKCS#1 rsa key.\n    */\n   private static enum DecodeRSAPublicKeySpec implements PemProcessor.ResultParser<KeySpec> {\n      INSTANCE;\n      @Override\n      public KeySpec parseResult(byte[] bytes) throws IOException {\n         return decodeRSAPublicKey(bytes);\n      }\n   }\n\n   /**\n    * Executes {@link Pems#publicKeySpec(ByteSource)} on the string which contains an encoded public key in PEM\n    * format.\n    * \n    * @param pem\n    *           public key in pem encoded format.\n    * @see Pems#publicKeySpec(ByteSource)\n    */\n   public static KeySpec publicKeySpec(String pem) throws IOException {\n      return publicKeySpec(ByteSource.wrap(\n         pem.getBytes(Charsets.UTF_8)));\n   }\n\n   /**\n    * Returns the {@link X509EncodedKeySpec} that is pem encoded in the supplier.\n    * \n    * @param supplier\n    *           the input stream factory\n    * @param certFactory\n    *           or null to use default\n    * \n    * @return the {@link X509EncodedKeySpec} which was PEM encoded in the stream\n    * @throws IOException\n    *            if an I/O error occurs\n    * @throws CertificateException\n    */\n   public static X509Certificate x509Certificate(ByteSource supplier,\n         @Nullable CertificateFactory certFactory) throws IOException, CertificateException {\n      final CertificateFactory certs = certFactory != null ? certFactory : CertificateFactory.getInstance(\"X.509\");\n      try {\n         return fromPem(\n               supplier,\n               new PemProcessor<X509Certificate>(ImmutableMap.<String, PemProcessor.ResultParser<X509Certificate>> of(\n                     CERTIFICATE_X509_MARKER, new PemProcessor.ResultParser<X509Certificate>() {\n\n                        @Override\n                        public X509Certificate parseResult(byte[] bytes) throws IOException {\n                           try {\n                              return (X509Certificate) certs.generateCertificate(new ByteArrayInputStream(bytes));\n                           } catch (CertificateException e) {\n                              throw new RuntimeException(e);\n                           }\n                        }\n\n                     })));\n      } catch (RuntimeException e) {\n         propagateIfInstanceOf(e.getCause(), CertificateException.class);\n         throw e;\n      }\n   }\n\n   /**\n    * Executes {@link Pems#x509Certificate(ByteSource, CertificateFactory)} on the string which contains an X.509\n    * certificate in PEM format.\n    * \n    * @param pem\n    *           certificate in pem encoded format.\n    * @see Pems#x509Certificate(ByteSource, CertificateFactory)\n    */\n   public static X509Certificate x509Certificate(String pem) throws IOException, CertificateException {\n      return x509Certificate(ByteSource.wrap(\n         pem.getBytes(Charsets.UTF_8)), null);\n   }\n\n   /**\n    * encodes the {@link X509Certificate} to PEM format.\n    * \n    * @param cert\n    *           what to encode\n    * @return the PEM encoded certificate\n    * @throws IOException\n    * @throws CertificateEncodingException\n    */\n   public static String pem(X509Certificate cert) throws CertificateEncodingException {\n      String marker = CERTIFICATE_X509_MARKER;\n      return pem(cert.getEncoded(), marker);\n   }\n\n   /**\n    * encodes the {@link PublicKey} to PEM format.\n    */\n   public static String pem(PublicKey key) {\n      String marker = key instanceof RSAPublicKey ? PUBLIC_PKCS1_MARKER : PUBLIC_X509_MARKER;\n      return pem(key.getEncoded(), marker);\n   }\n\n   /**\n    * encodes the {@link PrivateKey} to PEM format.\n    */\n   public static String pem(PrivateKey key) {\n      String marker = key instanceof RSAPrivateCrtKey ? PRIVATE_PKCS1_MARKER : PRIVATE_PKCS8_MARKER;\n      return pem(key instanceof RSAPrivateCrtKey ? encode(RSAPrivateCrtKey.class.cast(key)) : key.getEncoded(), marker);\n   }\n\n   private static String pem(byte[] encoded, String marker) {\n      String ls = System.getProperty(\"line.separator\");\n      StringBuilder builder = new StringBuilder();\n      builder.append(marker).append(ls);\n      builder.append(on(ls).join(fixedLength(64).split(base64().encode(encoded)))).append(ls);\n      builder.append(marker.replace(\"BEGIN\", \"END\")).append(ls);\n      return builder.toString();\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/date/DateCodec.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.date;\n\nimport java.util.Date;\n\n/**\n * converting from Date->String and vice versa.\n * \n * @see DateCodecFactory\n */\npublic interface DateCodec {\n\n   /**\n    * @param toParse\n    *           text to parse\n    * @return parsed date\n    * @throws IllegalArgumentException\n    *            if the input is invalid\n    */\n   Date toDate(String date) throws IllegalArgumentException;\n\n   String toString(Date date);\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/date/DateCodecFactory.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.date;\n\nimport org.jclouds.date.internal.DateServiceDateCodecFactory;\n\nimport com.google.inject.ImplementedBy;\n\n/**\n * Codecs for converting from Date->String and vice versa.\n * \n * @see DateCodec\n */\n@ImplementedBy(DateServiceDateCodecFactory.class)\npublic interface DateCodecFactory {\n\n   DateCodec rfc822();\n\n   DateCodec rfc1123();\n\n   DateCodec iso8601();\n\n   DateCodec iso8601Seconds();\n\n   DateCodec asctime();\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/date/DateService.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.date;\n\nimport java.util.Date;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\n\nimport com.google.inject.ImplementedBy;\n\n/**\n * Parses and formats the ISO8601, C, and RFC822 date formats found in XML responses and HTTP\n * response headers.\n */\n@ImplementedBy(SimpleDateFormatDateService.class)\npublic interface DateService {\n\n   String cDateFormat(Date date);\n\n   String cDateFormat();\n\n   /**\n    * @param toParse text to parse\n    * @return parsed date\n    * @throws IllegalArgumentException if the input is invalid\n    */\n   Date cDateParse(String toParse) throws IllegalArgumentException;\n\n   String rfc822DateFormat(Date date);\n\n   String rfc822DateFormat();\n   \n   /**\n    * @param toParse text to parse\n    * @return parsed date\n    * @throws IllegalArgumentException if the input is invalid\n    */\n   Date rfc822DateParse(String toParse) throws IllegalArgumentException;\n   \n   String iso8601SecondsDateFormat(Date dateTime);\n\n   String iso8601SecondsDateFormat();\n\n   String iso8601DateFormat(Date date);\n\n   String iso8601DateFormat();\n   \n   /**\n    * @param toParse text to parse\n    * @return parsed date\n    * @throws IllegalArgumentException if the input is invalid\n    */\n   Date iso8601DateParse(String toParse) throws IllegalArgumentException;\n\n   /**\n    * @param toParse text to parse\n    * @return parsed date\n    * @throws IllegalArgumentException if the input is invalid\n    */\n   Date iso8601SecondsDateParse(String toParse) throws IllegalArgumentException;\n\n   /**\n    * Parse a given date in either of two iso8601 formats:\n    * \"yyyy-MM-dd'T'HH:mm:ssZ\" or \"yyyy-MM-dd'T'HH:mm:ss.SSSZ\". The latter one\n    * has the timezone designator, e.g. 2014-07-23T20:53:17+0000. At least one\n    * S3 compatible blobstore uses both these formats when returning\n    * container/object metadata.\n    *\n    * @param toParse\n    *           The string to parse.\n    * @return the Date object of the parsed string.\n    * @throws IllegalArgumentException\n    */\n   Date iso8601DateOrSecondsDateParse(String toParse)\n         throws IllegalArgumentException;\n\n   String rfc1123DateFormat(Date date);\n\n   String rfc1123DateFormat();\n\n   /**\n    * @param toParse text to parse\n    * @return parsed date\n    * @throws IllegalArgumentException if the input is invalid\n    */\n   Date rfc1123DateParse(String toParse) throws IllegalArgumentException;\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/date/TimeStamp.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.date;\n\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\nimport jakarta.inject.Qualifier;\n\n/**\n * Related to a TimeStamp\n */\n@Retention(value = RetentionPolicy.RUNTIME)\n@Target(value = { ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })\n@Qualifier\npublic @interface TimeStamp {\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/date/internal/DateServiceDateCodecFactory.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.date.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Date;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.date.DateCodec;\nimport org.jclouds.date.DateCodecFactory;\nimport org.jclouds.date.DateService;\n\nimport com.google.inject.Inject;\n\n@Singleton\npublic class DateServiceDateCodecFactory implements DateCodecFactory {\n\n   private final DateCodec rfc822Codec;\n   private final DateCodec rfc1123Codec;\n   private final DateCodec iso8601Codec;\n   private final DateCodec iso8601SecondsCodec;\n   private final DateCodec asctime;\n\n   @Inject\n   public DateServiceDateCodecFactory(DateService dateService) {\n      checkNotNull(dateService, \"dateService\");\n      this.rfc822Codec = new DateServiceRfc822Codec(dateService);\n      this.rfc1123Codec = new DateServiceRfc1123Codec(dateService);\n      this.iso8601Codec = new DateServiceIso8601Codec(dateService);\n      this.iso8601SecondsCodec = new DateServiceIso8601SecondsCodec(dateService);\n      this.asctime = new DateServiceAsctimeCodec(dateService);\n   }\n\n   @Singleton\n   public static class DateServiceRfc822Codec implements DateCodec {\n\n      protected final DateService dateService;\n\n      @Inject\n      public DateServiceRfc822Codec(final DateService dateService) {\n         this.dateService = checkNotNull(dateService, \"dateService\");\n      }\n\n      @Override\n      public Date toDate(String date) throws IllegalArgumentException {\n         return dateService.rfc822DateParse(date);\n      }\n\n      @Override\n      public String toString(Date date) {\n         return dateService.rfc822DateFormat(date);\n      }\n\n      @Override\n      public String toString() {\n         return \"rfc822()\";\n      }\n\n   }\n\n   @Singleton\n   public static class DateServiceRfc1123Codec implements DateCodec {\n\n      protected final DateService dateService;\n\n      @Inject\n      public DateServiceRfc1123Codec(final DateService dateService) {\n         this.dateService = checkNotNull(dateService, \"dateService\");\n      }\n\n      @Override\n      public Date toDate(String date) throws IllegalArgumentException {\n         return dateService.rfc1123DateParse(date);\n      }\n\n      @Override\n      public String toString(Date date) {\n         return dateService.rfc1123DateFormat(date);\n      }\n\n      @Override\n      public String toString() {\n         return \"rfc1123()\";\n      }\n\n   }\n   \n   @Singleton\n   public static class DateServiceIso8601Codec implements DateCodec {\n\n      protected final DateService dateService;\n\n      @Inject\n      public DateServiceIso8601Codec(DateService dateService) {\n         this.dateService = checkNotNull(dateService, \"dateService\");\n      }\n\n      @Override\n      public Date toDate(String date) throws IllegalArgumentException {\n         return dateService.iso8601DateParse(date);\n      }\n\n      @Override\n      public String toString(Date date) {\n         return dateService.iso8601DateFormat(date);\n      }\n\n      @Override\n      public String toString() {\n         return \"iso8601()\";\n      }\n\n   }\n   \n   @Singleton\n   public static class DateServiceIso8601SecondsCodec implements DateCodec {\n\n      protected final DateService dateService;\n\n      @Inject\n      public DateServiceIso8601SecondsCodec(DateService dateService) {\n         this.dateService = checkNotNull(dateService, \"dateService\");\n      }\n\n      @Override\n      public Date toDate(String date) throws IllegalArgumentException {\n         return dateService.iso8601SecondsDateParse(date);\n      }\n\n      @Override\n      public String toString(Date date) {\n         return dateService.iso8601SecondsDateFormat(date);\n      }\n\n      @Override\n      public String toString() {\n         return \"iso8601Seconds()\";\n      }\n\n   }\n\n   @Singleton\n   public static class DateServiceAsctimeCodec implements DateCodec {\n\n      protected final DateService dateService;\n\n      @Inject\n      public DateServiceAsctimeCodec(DateService dateService) {\n         this.dateService = checkNotNull(dateService, \"dateService\");\n      }\n\n      @Override\n      public Date toDate(String date) throws IllegalArgumentException {\n         return dateService.cDateParse(date);\n      }\n\n      @Override\n      public String toString(Date date) {\n         return dateService.cDateFormat(date);\n      }\n\n      @Override\n      public String toString() {\n         return \"asctime()\";\n      }\n\n   }\n\n   @Override\n   public DateCodec rfc822() {\n      return rfc822Codec;\n   }\n\n   @Override\n   public DateCodec rfc1123() {\n      return rfc1123Codec;\n   }\n\n   @Override\n   public DateCodec iso8601() {\n      return iso8601Codec;\n   }\n\n   @Override\n   public DateCodec iso8601Seconds() {\n      return iso8601SecondsCodec;\n   }\n\n   @Override\n   public DateCodec asctime() {\n      return asctime;\n   }\n   \n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/date/internal/DateUtils.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.date.internal;\n\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class DateUtils {\n\n   private static final String TZ_REGEX = \"([+-][0-9][0-9](:?[0-9][0-9])?|Z)\";\n   private static final Pattern MILLIS_PATTERN = Pattern.compile(\"(.*\\\\.[0-9][0-9][0-9])[0-9]*\" + TZ_REGEX + \"?\");\n   // This regexp will match all TZ forms that are valid is ISO 8601\n   private static final Pattern TZ_PATTERN = Pattern.compile(\"(.*)\" + TZ_REGEX + \"$\");\n\n   public static String trimToMillis(String toParse) {\n       Matcher matcher = MILLIS_PATTERN.matcher(toParse);\n       if (matcher.find()) {\n          toParse = matcher.group(1);\n          if (matcher.group(2) != null)\n             toParse += matcher.group(2);\n       }\n      return toParse;\n   }\n\n   private static final Pattern SECOND_PATTERN = Pattern.compile(\".*[0-2][0-9]:00\");\n\n   public static String trimTZ(String toParse) {\n      Matcher matcher = TZ_PATTERN.matcher(toParse);\n      if (matcher.find()) {\n         toParse = matcher.group(1);\n      }\n      // TODO explain why this check is here\n      if (toParse.length() == 25 && SECOND_PATTERN.matcher(toParse).matches())\n         toParse = toParse.substring(0, toParse.length() - 6);\n      return toParse;\n   }\n\n   public static String findTZ(String toParse) {\n      Matcher matcher = TZ_PATTERN.matcher(toParse);\n      if (matcher.find()) {\n         // Remove ':' from the TZ string, as SimpleDateFormat can't handle it\n         String tz = matcher.group(2).replace(\":\", \"\");\n         // Append '00; if we only have a two digit TZ, as SimpleDateFormat\n         if (tz.length() == 2) tz += \"00\";\n         // Replace Z with +0000\n         if (tz.equals(\"Z\")) return \"+0000\";\n         return tz;\n      } else {\n         // Return +0000 if no time zone\n         return \"+0000\";\n      }\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/date/internal/SimpleDateFormatDateService.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.date.internal;\nimport static org.jclouds.date.internal.DateUtils.findTZ;\nimport static org.jclouds.date.internal.DateUtils.trimTZ;\nimport static org.jclouds.date.internal.DateUtils.trimToMillis;\n\nimport java.text.ParseException;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\nimport java.util.Locale;\nimport java.util.SimpleTimeZone;\n\nimport org.jclouds.date.DateService;\n\n/**\n * \n * uses {@link SimpleDateFormat} internally.\n */\npublic class SimpleDateFormatDateService implements DateService {\n\n   /*\n    * Use default Java Date/SimpleDateFormat classes for date manipulation, but be *very* careful to\n    * guard against the lack of thread safety.\n    */\n   // @GuardedBy(\"this\")\n   private static final SimpleDateFormat iso8601SecondsSimpleDateFormat = new SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ssZ\", Locale.US);\n\n   // @GuardedBy(\"this\")\n   private static final SimpleDateFormat iso8601SimpleDateFormat = new SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ss.SSSZ\", Locale.US);\n\n   // @GuardedBy(\"this\")\n   private static final SimpleDateFormat rfc822SimpleDateFormat = new SimpleDateFormat(\"EEE, dd MMM yyyy HH:mm:ss 'GMT'\", Locale.US);\n\n   // See http://stackoverflow.com/questions/10584647/simpledateformat-parse-is-one-hour-out-using-rfc-1123-gmt-in-summer\n   // for why not using \"zzz\"\n   // @GuardedBy(\"this\")\n   private static final SimpleDateFormat rfc1123SimpleDateFormat = new SimpleDateFormat(\"EEE, dd MMM yyyy HH:mm:ss Z\", Locale.US);\n\n   // @GuardedBy(\"this\")\n   private static final SimpleDateFormat cSimpleDateFormat = new SimpleDateFormat(\"EEE MMM dd HH:mm:ss Z yyyy\", Locale.US);\n\n   static {\n      iso8601SimpleDateFormat.setTimeZone(new SimpleTimeZone(0, \"GMT\"));\n      iso8601SecondsSimpleDateFormat.setTimeZone(new SimpleTimeZone(0, \"GMT\"));\n      rfc822SimpleDateFormat.setTimeZone(new SimpleTimeZone(0, \"GMT\"));\n      cSimpleDateFormat.setTimeZone(new SimpleTimeZone(0, \"GMT\"));\n   }\n\n   @Override\n   public final String cDateFormat(Date date) {\n      synchronized (cSimpleDateFormat) {\n         return cSimpleDateFormat.format(date);\n      }\n   }\n\n   @Override\n   public final String cDateFormat() {\n      return cDateFormat(new Date());\n   }\n\n   @Override\n   public final Date cDateParse(String toParse) {\n      synchronized (cSimpleDateFormat) {\n         try {\n            return cSimpleDateFormat.parse(toParse);\n         } catch (ParseException pe) {\n            throw new IllegalArgumentException(\"Error parsing data at \" + pe.getErrorOffset(), pe);\n         }\n      }\n   }\n\n   @Override\n   public final String rfc822DateFormat(Date date) {\n      synchronized (rfc822SimpleDateFormat) {\n         return rfc822SimpleDateFormat.format(date);\n      }\n   }\n\n   @Override\n   public final String rfc822DateFormat() {\n      return rfc822DateFormat(new Date());\n   }\n\n   @Override\n   public final Date rfc822DateParse(String toParse) {\n      synchronized (rfc822SimpleDateFormat) {\n         try {\n            return rfc822SimpleDateFormat.parse(toParse);\n         } catch (ParseException pe) {\n            throw new IllegalArgumentException(\"Error parsing data at \" + pe.getErrorOffset(), pe);\n         }\n      }\n   }\n\n   @Override\n   public final String iso8601SecondsDateFormat() {\n      return iso8601SecondsDateFormat(new Date());\n   }\n\n   @Override\n   public final String iso8601DateFormat(Date date) {\n      synchronized (iso8601SimpleDateFormat) {\n         String parsed = iso8601SimpleDateFormat.format(date);\n         String tz = findTZ(parsed);\n         if (tz.equals(\"+0000\")) {\n            parsed = trimTZ(parsed) + \"Z\";\n         }\n         return parsed;\n      }\n   }\n\n   @Override\n   public final String iso8601DateFormat() {\n      return iso8601DateFormat(new Date());\n   }\n\n   @Override\n   public final Date iso8601DateParse(String toParse) {\n      if (toParse.length() < 10)\n         throw new IllegalArgumentException(\"incorrect date format \" + toParse);\n      String tz = findTZ(toParse);\n      toParse = trimToMillis(toParse);\n      toParse = trimTZ(toParse);\n      toParse += tz;\n      if (toParse.charAt(10) == ' ')\n         toParse = new StringBuilder(toParse).replace(10, 11, \"T\").toString();\n      synchronized (iso8601SimpleDateFormat) {\n         try {\n            return iso8601SimpleDateFormat.parse(toParse);\n         } catch (ParseException pe) {\n            throw new IllegalArgumentException(\"Error parsing data at \" + pe.getErrorOffset(), pe);\n         }\n      }\n   }\n\n   @Override\n   public final Date iso8601SecondsDateParse(String toParse)\n         throws IllegalArgumentException {\n      if (toParse.length() < 10)\n         throw new IllegalArgumentException(\"incorrect date format \" + toParse);\n      String tz = findTZ(toParse);\n      toParse = trimToMillis(toParse);\n      toParse = trimTZ(toParse);\n      toParse += tz;\n      if (toParse.charAt(10) == ' ')\n         toParse = new StringBuilder(toParse).replace(10, 11, \"T\").toString();\n      synchronized (iso8601SecondsSimpleDateFormat) {\n         try {\n            return iso8601SecondsSimpleDateFormat.parse(toParse);\n         } catch (ParseException pe) {\n            throw new IllegalArgumentException(\"Error parsing data at \" + pe.getErrorOffset(), pe);\n         }\n      }\n   }\n\n   @Override\n   @SuppressWarnings(\"UnusedException\")\n   public Date iso8601DateOrSecondsDateParse(String toParse)\n         throws IllegalArgumentException {\n      try {\n         return iso8601DateParse(toParse);\n      } catch (IllegalArgumentException orig) {\n         try {\n            return iso8601SecondsDateParse(toParse);\n         } catch (IllegalArgumentException ignored) {\n            throw orig;\n         }\n      }\n   }\n\n   @Override\n   public String iso8601SecondsDateFormat(Date date) {\n      synchronized (iso8601SecondsSimpleDateFormat) {\n         String parsed = iso8601SecondsSimpleDateFormat.format(date);\n         String tz = findTZ(parsed);\n         if (tz.equals(\"+0000\")) {\n            parsed = trimTZ(parsed) + \"Z\";\n         }\n         return parsed;\n      }\n   }\n\n   @Override\n   public final String rfc1123DateFormat(Date date) {\n      synchronized (rfc1123SimpleDateFormat) {\n         return rfc1123SimpleDateFormat.format(date);\n      }\n   }\n\n   @Override\n   public final String rfc1123DateFormat() {\n      return rfc1123DateFormat(new Date());\n   }\n\n   @Override\n   public final Date rfc1123DateParse(String toParse) throws IllegalArgumentException {\n      synchronized (rfc1123SimpleDateFormat) {\n         try {\n            return rfc1123SimpleDateFormat.parse(toParse);\n         } catch (ParseException pe) {\n            throw new IllegalArgumentException(\"Error parsing data at \" + pe.getErrorOffset(), pe);\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/domain/Credentials.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.domain;\n\nimport com.google.common.base.Objects;\n\npublic class Credentials {\n   public static class Builder<T extends Credentials> {\n      protected String identity;\n      protected String credential;\n\n      public Builder<T> identity(String identity) {\n         this.identity = identity;\n         return this;\n      }\n\n      public Builder<T> credential(String credential) {\n         this.credential = credential;\n         return this;\n      }\n\n      @SuppressWarnings(\"unchecked\")\n      public T build() {\n         return (T) new Credentials(identity, credential);\n      }\n   }\n\n   public final String identity;\n   public final String credential;\n\n   public Credentials(String identity, String credential) {\n      this.identity = identity;\n      this.credential = credential;\n   }\n\n   public Builder<? extends Credentials> toBuilder() {\n      return new Builder<Credentials>().identity(identity).credential(credential);\n   }\n\n   @Override\n   public String toString() {\n      return \"[identity=\" + identity + \", credential=\" + credential + \"]\";\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(identity, credential);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (!(obj instanceof Credentials))\n         return false;\n      Credentials other = (Credentials) obj;\n      if (!Objects.equal(identity, other.identity))\n         return false;\n      if (!Objects.equal(credential, other.credential))\n         return false;\n      return true;\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/domain/JsonBall.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.regex.Pattern;\n\n/**\n * \n * As String is final, using a different marker to imply this is a json object\n * \n * @see <a href=\"http://code.google.com/p/google-gson/issues/detail?id=326\"/>\n */\npublic class JsonBall implements Comparable<String>, CharSequence {\n   \n   public static final Pattern JSON_STRING_PATTERN = Pattern.compile(\"^[^\\\"\\\\{\\\\[].*[^\\\\{\\\\[\\\"]$\");\n   public static final Pattern JSON_NUMBER_PATTERN = Pattern.compile(\"^[0-9]*\\\\.?[0-9]*$\");\n   public static final Pattern JSON_BOOLEAN_PATTERN = Pattern.compile(\"^(true|false)$\");\n   \n   private final String value;\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      JsonBall other = (JsonBall) obj;\n      if (value == null) {\n         if (other.value != null)\n            return false;\n      } else if (!value.equals(other.value))\n         return false;\n      return true;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((value == null) ? 0 : value.hashCode());\n      return result;\n   }\n\n   @Override\n   public String toString() {\n      return value;\n   }\n\n   public JsonBall(double value) {\n      this.value = value + \"\";\n   }\n\n   public JsonBall(int value) {\n      this.value = value + \"\";\n   }\n\n   public JsonBall(long value) {\n      this.value = value + \"\";\n   }\n   \n   public JsonBall(boolean value) {\n      this.value = value + \"\";\n   }\n\n   public JsonBall(String value) {\n      this.value = quoteStringIfNotNumberOrBoolean(checkNotNull(value, \"value\"));\n   }\n\n   private static String quoteStringIfNotNumberOrBoolean(String in) {\n      if (JSON_STRING_PATTERN.matcher(in).find() && !JSON_NUMBER_PATTERN.matcher(in).find()\n            && !JSON_BOOLEAN_PATTERN.matcher(in).find()) {\n         return \"\\\"\" + in + \"\\\"\";\n      }\n      return in;\n   }\n\n   @Override\n   public char charAt(int index) {\n      return value.charAt(index);\n   }\n\n   @Override\n   public int length() {\n      return value.length();\n   }\n\n   @Override\n   public CharSequence subSequence(int start, int end) {\n      return value.subSequence(start, end);\n   }\n\n   @Override\n   public int compareTo(String o) {\n      return value.compareTo(o);\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/domain/Location.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.domain;\n\nimport java.util.Map;\nimport java.util.Set;\n\n/**\n * Description of where a resource is running. Note this can be physical or virtual.\n */\npublic interface Location {\n\n   /**\n    * Scope of the location, ex. region, zone, host\n    * \n    */\n   LocationScope getScope();\n\n   /**\n    * Unique ID provided by the provider (us-standard, miami, etc)\n    * \n    */\n   String getId();\n\n   /**\n    * Description of the location\n    */\n   String getDescription();\n\n   /**\n    * The parent, or null, if top-level\n    */\n   Location getParent();\n\n   /**\n    * @return immutable set of metadata relating to this location\n    */\n   Map<String, Object> getMetadata();\n\n   /**\n    * @return if known, the IS0 3166 or 3166-2 divisions where this service may run. ex. a set of\n    *         strings like \"US\" or \"US-CA\"; otherwise returns an empty list.\n    * @see <a\n    *      href=\"http://www.iso.org/iso/country_codes/background_on_iso_3166/what_is_iso_3166.htm\">3166</a>\n    */\n   Set<String> getIso3166Codes();\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/domain/LocationBuilder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.domain.internal.LocationImpl;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\n\npublic final class LocationBuilder {\n   private LocationScope scope;\n   private String id;\n   private String description;\n   private Location parent;\n   private Set<String> iso3166Codes = ImmutableSet.of();\n   private Map<String, Object> metadata = ImmutableMap.of();\n\n   public LocationBuilder scope(LocationScope scope) {\n      this.scope = scope;\n      return this;\n   }\n\n   public LocationBuilder id(String id) {\n      this.id = id;\n      return this;\n   }\n\n   public LocationBuilder description(String description) {\n      this.description = description;\n      return this;\n   }\n\n   public LocationBuilder parent(Location parent) {\n      this.parent = parent;\n      return this;\n   }\n\n   public LocationBuilder iso3166Codes(Iterable<String> iso3166Codes) {\n      this.iso3166Codes = ImmutableSet.copyOf(checkNotNull(iso3166Codes, \"iso3166Codes\"));\n      return this;\n   }\n\n   public LocationBuilder metadata(Map<String, Object> metadata) {\n      this.metadata = ImmutableMap.copyOf(checkNotNull(metadata, \"metadata\"));\n      return this;\n   }\n\n   public Location build() {\n      return new LocationImpl(scope, id, description, parent, iso3166Codes, metadata);\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/domain/LocationScope.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.domain;\n\n/**\n * The scope of the location\n * \n */\npublic enum LocationScope {\n\n    PROVIDER,\n    REGION,\n    ZONE,\n    /**\n     * @see <a href=\"http://dmtf.org/standards/cloud\">cimi system docs</a>\n     */\n    SYSTEM,\n    /**\n     * E.g. the DMZ segment, secure segment. \n     */\n    NETWORK,\n    HOST;\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/domain/LoginCredentials.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.crypto.Pems.PRIVATE_PKCS1_MARKER;\nimport static org.jclouds.crypto.Pems.PRIVATE_PKCS8_MARKER;\n\nimport org.jclouds.crypto.Pems;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.Optional;\n\npublic class LoginCredentials extends Credentials {\n\n   private static boolean isPrivateKeyCredential(String credential) {\n      return credential != null\n            && (credential.startsWith(PRIVATE_PKCS1_MARKER) || credential.startsWith(PRIVATE_PKCS8_MARKER));\n   }\n\n   public static LoginCredentials fromCredentials(Credentials creds) {\n      if (creds == null)\n         return null;\n      if (creds instanceof LoginCredentials)\n         return LoginCredentials.class.cast(creds);\n      return builder(creds).build();\n   }\n\n   public static Builder builder(Credentials creds) {\n      if (creds == null)\n         return builder();\n      if (creds instanceof LoginCredentials)\n         return LoginCredentials.class.cast(creds).toBuilder();\n      else\n         return builder().identity(creds.identity).credential(creds.credential);\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n   \n   public static class Builder extends Credentials.Builder<LoginCredentials> {\n      private boolean authenticateSudo;\n      private Optional<String> password = Optional.absent();\n      private Optional<String> privateKey = Optional.absent();\n\n      public Builder identity(String identity) {\n         return Builder.class.cast(super.identity(identity));\n      }\n\n      public Builder user(String user) {\n         return identity(user);\n      }\n\n      public Builder password(String password) {\n         this.password = Optional.fromNullable(password);\n         return this;\n      }\n\n      public Builder noPassword() {\n         this.password = Optional.absent();\n         return this;\n      }\n\n      public Builder privateKey(String privateKey) {\n         this.privateKey = Optional.fromNullable(privateKey);\n         return this;\n      }\n\n      public Builder noPrivateKey() {\n         this.privateKey = Optional.absent();\n         return this;\n      }\n\n      public Builder credential(String credential) {\n         if (isPrivateKeyCredential(credential))\n            return noPassword().privateKey(credential);\n         else if (credential != null)\n            return password(credential).noPrivateKey();\n         return this;\n      }\n\n      public Builder authenticateSudo(boolean authenticateSudo) {\n         this.authenticateSudo = authenticateSudo;\n         return this;\n      }\n\n      public LoginCredentials build() {\n         if (identity == null && !password.isPresent() && !privateKey.isPresent() && !authenticateSudo)\n            return null;\n         return new LoginCredentials(identity, password, privateKey, authenticateSudo);\n      }\n   }\n\n   private final boolean authenticateSudo;\n   private final Optional<String> password;\n   private final Optional<String> privateKey;\n\n   private LoginCredentials(String username, Optional<String> password, Optional<String> privateKey, boolean authenticateSudo) {\n      super(username, privateKey.isPresent() && isPrivateKeyCredential(privateKey.get())\n                    ? privateKey.get()\n                    : password.orNull());\n      this.authenticateSudo = authenticateSudo;\n      this.password = checkNotNull(password, \"password\");\n      this.privateKey = checkNotNull(privateKey, \"privateKey\");\n   }\n\n   /**\n    * @return the login user\n    */\n   public String getUser() {\n      return identity;\n   }\n\n   /**\n    * @return the password of the login user or null\n    * \n    * @deprecated since 1.8; instead use {@link #getOptionalPassword()}\n    */\n   @Nullable\n   @Deprecated\n   public String getPassword() {\n      return password.orNull();\n   }\n\n   /**\n    * @return the optional password of the user (Optional.absent if none supplied).\n    */\n   public Optional<String> getOptionalPassword() {\n      return password;\n   }\n\n   /**\n    * @return the private ssh key of the user or null\n    * \n    * @deprecated since 1.8; instead use {@link #getOptionalPrivateKey()}\n    */\n   @Nullable\n   @Deprecated\n   public String getPrivateKey() {\n      return privateKey.orNull();\n   }\n\n   /**\n    * @return true if there is a private key attached that is not encrypted\n    */\n   public boolean hasUnencryptedPrivateKey() {\n      return getOptionalPrivateKey().isPresent()\n         && !getOptionalPrivateKey().get().isEmpty()\n         && !getOptionalPrivateKey().get().contains(Pems.PROC_TYPE_ENCRYPTED);\n   }\n\n   /**\n    * @return the optional private ssh key of the user (Optional.absent if none supplied).\n    */\n   public Optional<String> getOptionalPrivateKey() {\n      return privateKey;\n   }\n\n   /**\n    * secures access to root requires a password. This password is required to\n    * access either the console or run sudo as root.\n    * <p/>\n    * ex. {@code echo 'password' |sudo -S command}\n    * \n    * @return if a password is required to access the root user\n    */\n   public boolean shouldAuthenticateSudo() {\n      return authenticateSudo;\n   }\n\n   @Override\n   public Builder toBuilder() {\n      Builder builder = new Builder().user(identity).authenticateSudo(authenticateSudo);\n      if (password != null) {\n         if (password.isPresent()) {\n            builder = builder.password(password.get());\n         } else {\n            builder = builder.noPassword();\n         }\n      }\n      if (privateKey != null) {\n         if (privateKey.isPresent()) {\n            builder = builder.privateKey(privateKey.get());\n         } else {\n            builder = builder.noPrivateKey();\n         }\n      }\n      return builder;\n   }\n\n   @Override\n   public String toString() {\n      return \"[user=\" + getUser() + \", passwordPresent=\" + password.isPresent() + \", privateKeyPresent=\"\n            + privateKey.isPresent() + \", shouldAuthenticateSudo=\" + authenticateSudo + \"]\";\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/domain/MutableResourceMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.domain;\n\nimport java.net.URI;\nimport java.util.Map;\n\nimport org.jclouds.domain.internal.MutableResourceMetadataImpl;\n\nimport com.google.inject.ImplementedBy;\n\n/**\n * Used to construct new resources or modify existing ones.\n */\n@ImplementedBy(MutableResourceMetadataImpl.class)\npublic interface MutableResourceMetadata<T extends Enum<T>> extends ResourceMetadata<T> {\n   /**\n    * @see #getType\n    */\n   void setType(T type);\n\n   /**\n    * @see #getId\n    */\n   void setId(String id);\n\n   /**\n    * @see #getName\n    */\n   void setName(String name);\n\n   /**\n    * @see #getLocation\n    */\n   void setLocation(Location location);\n\n   /**\n    * @see #getUri\n    */\n   void setUri(URI url);\n\n   /**\n    * @see #getUserMetadata\n    */\n   void setUserMetadata(Map<String, String> userMetadata);\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/domain/ResourceMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.domain;\n\nimport java.net.URI;\nimport java.util.Map;\n\nimport org.jclouds.domain.internal.ResourceMetadataImpl;\n\nimport com.google.inject.ImplementedBy;\n\n/**\n * Identifies containers, files, etc.\n */\n@ImplementedBy(ResourceMetadataImpl.class)\npublic interface ResourceMetadata<T extends Enum<T>> extends Comparable<ResourceMetadata<T>> {\n\n   /**\n    * Whether this resource is a container, file, node, queue, etc.\n    */\n   T getType();\n\n   /**\n    * Unique identifier of this resource within its enclosing namespace. In some scenarios, this id\n    * is not user assignable. For files, this may be an system generated key, or the full path to\n    * the resource. ex. /path/to/file.txt\n    * \n    */\n   String getProviderId();\n\n   /**\n    * Name of this resource. Names are dictated by the user. For files, this may be the filename,\n    * ex. file.txt\n    * \n    */\n   String getName();\n\n   /**\n    * Physical location of the resource, or null if n/a\n    * \n    * ex. us-west-1\n    * \n    */\n   Location getLocation();\n\n   /**\n    * URI used to access this resource\n    */\n   URI getUri();\n\n   /**\n    * Any key-value pairs associated with the resource.\n    */\n   Map<String, String> getUserMetadata();\n\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/domain/ResourceMetadataBuilder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.net.URI;\nimport java.util.Map;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Maps;\n\npublic abstract class ResourceMetadataBuilder<T extends Enum<T>> {\n   protected String providerId;\n   protected String name;\n   protected Location location;\n   protected URI uri;\n   protected Map<String, String> userMetadata = Maps.newLinkedHashMap();\n\n   public ResourceMetadataBuilder<T> providerId(String providerId) {\n      this.providerId = providerId;\n      return this;\n   }\n\n   public ResourceMetadataBuilder<T> name(String name) {\n      this.name = name;\n      return this;\n   }\n\n   public ResourceMetadataBuilder<T> location(Location location) {\n      this.location = location;\n      return this;\n   }\n\n   public ResourceMetadataBuilder<T> uri(URI uri) {\n      this.uri = uri;\n      return this;\n   }\n\n   public ResourceMetadataBuilder<T> userMetadata(Map<String, String> userMetadata) {\n      this.userMetadata = ImmutableMap.copyOf(checkNotNull(userMetadata, \"userMetadata\"));\n      return this;\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/domain/internal/LocationImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.domain.internal;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\n\npublic class LocationImpl implements Location {\n\n   private final LocationScope scope;\n   private final String id;\n   private final String description;\n   private final Location parent;\n   private final Set<String> iso3166Codes;\n   private final Map<String, Object> metadata;\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o)\n         return true;\n      if (o == null || getClass() != o.getClass())\n         return false;\n      LocationImpl that = LocationImpl.class.cast(o);\n      return equal(this.scope, that.scope) && equal(this.id, that.id) && equal(this.parent, that.parent);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(scope, id, parent);\n   }\n\n   @Override\n   public String toString() {\n      ToStringHelper helper = MoreObjects.toStringHelper(\"\").omitNullValues().add(\"scope\", scope).add(\"id\", id)\n            .add(\"description\", description);\n      if (parent != null)\n         helper.add(\"parent\", parent.getId());\n      if (!iso3166Codes.isEmpty())\n         helper.add(\"iso3166Codes\", iso3166Codes);\n      if (!metadata.isEmpty())\n         helper.add(\"metadata\", metadata);\n      return helper.toString();\n   }\n\n   public LocationImpl(LocationScope scope, String id, String description, @Nullable Location parent,\n            Iterable<String> iso3166Codes, Map<String, Object> metadata) {\n      this.scope = checkNotNull(scope, \"scope\");\n      this.id = checkNotNull(id, \"id\");\n      this.description = checkNotNull(description, \"description\");\n      this.metadata = ImmutableMap.copyOf(checkNotNull(metadata, \"metadata\"));\n      this.iso3166Codes = ImmutableSet.copyOf(checkNotNull(iso3166Codes, \"iso3166Codes\"));\n      this.parent = parent;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public LocationScope getScope() {\n      return scope;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getId() {\n      return id;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getDescription() {\n      return description;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Location getParent() {\n      return parent;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Set<String> getIso3166Codes() {\n      return iso3166Codes;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Map<String, Object> getMetadata() {\n      return metadata;\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/domain/internal/MutableResourceMetadataImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.domain.internal;\n\nimport java.net.URI;\nimport java.util.Map;\n\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.MutableResourceMetadata;\nimport org.jclouds.domain.ResourceMetadata;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.Maps;\n\n/**\n * Used to construct new resources or modify existing ones.\n */\npublic class MutableResourceMetadataImpl<T extends Enum<T>> implements MutableResourceMetadata<T> {\n\n   private T type;\n   private String id;\n   private String name;\n   private Location location;\n   private URI uri;\n   private Map<String, String> userMetadata;\n\n   public MutableResourceMetadataImpl() {\n      userMetadata = Maps.newLinkedHashMap();\n   }\n\n   public MutableResourceMetadataImpl(ResourceMetadata<T> from) {\n      this.type = from.getType();\n      this.id = from.getProviderId();\n      this.name = from.getName();\n      this.location = from.getLocation();\n      this.uri = from.getUri();\n      this.userMetadata = from.getUserMetadata();\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public int compareTo(ResourceMetadata<T> o) {\n      if (getName() == null)\n         return -1;\n      return (this == o) ? 0 : getName().compareTo(o.getName());\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public T getType() {\n      return type;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getName() {\n      return name;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getProviderId() {\n      return id;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public URI getUri() {\n      return uri;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Map<String, String> getUserMetadata() {\n      return userMetadata;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void setName(String name) {\n      this.name = name;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void setType(T type) {\n      this.type = type;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void setUserMetadata(Map<String, String> userMetadata) {\n      this.userMetadata = userMetadata;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void setId(String id) {\n      this.id = id;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void setUri(URI uri) {\n      this.uri = uri;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void setLocation(Location location) {\n      this.location = location;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Location getLocation() {\n      return location;\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(\"\").omitNullValues()\n            .add(\"id\", id)\n            .add(\"location\", location)\n            .add(\"name\", name)\n            .add(\"type\", getType())\n            .add(\"uri\", uri)\n            .add(\"userMetadata\", userMetadata);\n   }\n\n   @Override\n   public int hashCode() {\n      // intentionally not hashing userMetadata\n      return Objects.hashCode(id, location, name, type, uri);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (!(obj instanceof MutableResourceMetadata<?>))\n         return false;\n      MutableResourceMetadata<?> other = (MutableResourceMetadata<?>) obj;\n      return Objects.equal(id, other.getProviderId())\n            && Objects.equal(location, other.getLocation())\n            && Objects.equal(name, other.getName())\n            && Objects.equal(type, other.getType())\n            && Objects.equal(uri, other.getUri());\n            // intentionally not comparing userMetadata\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/domain/internal/ResourceMetadataImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.domain.internal;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.ComparisonChain.start;\nimport static com.google.common.collect.Ordering.natural;\n\nimport java.net.URI;\nimport java.util.Map;\n\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.ResourceMetadata;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.Maps;\n\n/**\n * Idpayload of the object\n */\npublic abstract class ResourceMetadataImpl<T extends Enum<T>> implements ResourceMetadata<T> {\n\n   @Nullable\n   private final String providerId;\n   @Nullable\n   private final String name;\n   @Nullable\n   private final Location location;\n   @Nullable\n   private final URI uri;\n   private final Map<String, String> userMetadata = Maps.newLinkedHashMap();\n\n   public ResourceMetadataImpl(@Nullable String providerId, @Nullable String name, @Nullable Location location,\n         @Nullable URI uri, Map<String, String> userMetadata) {\n      this.providerId = providerId;\n      this.name = name;\n      this.location = location;\n      this.uri = uri;\n      this.userMetadata.putAll(checkNotNull(userMetadata, \"userMetadata\"));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public int compareTo(ResourceMetadata<T> that) {\n      return start()\n            .compare(this.getName(), that.getName(), natural().nullsLast())\n            .result();\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getProviderId() {\n      return providerId;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getName() {\n      return name;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Location getLocation() {\n      return location;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public URI getUri() {\n      return uri;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Map<String, String> getUserMetadata() {\n      return userMetadata;\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o)\n         return true;\n      if (o == null || getClass() != o.getClass())\n         return false;\n      ResourceMetadataImpl<?> that = ResourceMetadataImpl.class.cast(o);\n      return equal(this.getType(), that.getType()) && equal(this.providerId, that.providerId)\n               && equal(this.name, that.name) && equal(this.location, that.location) && equal(this.uri, that.uri);\n               // intentionally not comparing userMetadata\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(getType(), providerId, name, location, uri);\n      // intentionally not hashing userMetadata\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(\"\").omitNullValues().add(\"type\", getType()).add(\"providerId\", providerId)\n               .add(\"name\", name).add(\"location\", location).add(\"uri\", uri).add(\"userMetadata\", userMetadata);\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/encryption/internal/JCECrypto.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.encryption.internal;\n\nimport java.security.InvalidKeyException;\nimport java.security.KeyFactory;\nimport java.security.KeyPairGenerator;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.Provider;\nimport java.security.cert.CertificateException;\nimport java.security.cert.CertificateFactory;\n\nimport javax.crypto.Cipher;\nimport javax.crypto.Mac;\nimport javax.crypto.NoSuchPaddingException;\nimport javax.crypto.spec.SecretKeySpec;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.crypto.Crypto;\nimport org.jclouds.javax.annotation.Nullable;\n\n@Singleton\npublic class JCECrypto implements Crypto {\n\n   private final KeyPairGenerator rsaKeyPairGenerator;\n   private final KeyFactory rsaKeyFactory;\n   private final CertificateFactory certFactory;\n   private final Provider provider;\n\n   @Inject\n   public JCECrypto() throws NoSuchAlgorithmException, CertificateException {\n      this(null);\n   }\n\n   public JCECrypto(@Nullable Provider provider) throws NoSuchAlgorithmException, CertificateException {\n      this.rsaKeyPairGenerator = provider == null ? KeyPairGenerator.getInstance(\"RSA\") : KeyPairGenerator.getInstance(\n            \"RSA\", provider);\n      this.rsaKeyFactory = provider == null ? KeyFactory.getInstance(\"RSA\") : KeyFactory.getInstance(\"RSA\", provider);\n      this.certFactory = provider == null ? CertificateFactory.getInstance(\"X.509\") : CertificateFactory.getInstance(\n            \"X.509\", provider);\n      this.provider = provider;\n   }\n\n   @Override\n   public Mac hmac(String algorithm, byte[] key) throws NoSuchAlgorithmException, InvalidKeyException {\n      Mac mac = null;\n      if (provider != null) {\n          try {\n          mac = Mac.getInstance(algorithm, provider);\n          } catch (Exception e) {\n              //Provider does not function.\n              //Do nothing and let it fallback to the default way.\n          }\n      }\n      if (mac == null) {\n         mac = Mac.getInstance(algorithm);\n      }\n      SecretKeySpec signingKey = new SecretKeySpec(key, algorithm);\n      mac.init(signingKey);\n      return mac;\n\n   }\n\n   @Override\n   public Cipher cipher(String algorithm) throws NoSuchAlgorithmException, NoSuchPaddingException {\n      return provider == null ? Cipher.getInstance(algorithm) : Cipher.getInstance(algorithm, provider);\n   }\n\n   private static final String HmacSHA256 = \"HmacSHA256\";\n   private static final String HmacSHA1 = \"HmacSHA1\";\n\n   @Override\n   public Mac hmacSHA1(byte[] key) throws InvalidKeyException {\n      try {\n         return hmac(HmacSHA1, key);\n      } catch (NoSuchAlgorithmException e) {\n         throw new IllegalStateException(\"HmacSHA1 must be supported\", e);\n      }\n   }\n\n   @Override\n   public Mac hmacSHA256(byte[] key) throws InvalidKeyException {\n      try {\n         return hmac(HmacSHA256, key);\n      } catch (NoSuchAlgorithmException e) {\n         throw new IllegalStateException(\"HmacSHA256 must be supported\", e);\n      }\n   }\n\n   @Override\n   public CertificateFactory certFactory() {\n      return certFactory;\n   }\n\n   @Override\n   public KeyFactory rsaKeyFactory() {\n      return rsaKeyFactory;\n   }\n\n   @Override\n   public KeyPairGenerator rsaKeyPairGenerator() {\n      return rsaKeyPairGenerator;\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/events/config/ConfiguresEventBus.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.events.config;\n\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\n/**\n * Designates the module configures an {@link EventBus}.\n */\n@Retention(RetentionPolicy.RUNTIME)\n@Target(ElementType.TYPE)\npublic @interface ConfiguresEventBus {\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/events/config/EventBusModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.events.config;\n\nimport static com.google.inject.Scopes.SINGLETON;\nimport static org.jclouds.Constants.PROPERTY_USER_THREADS;\n\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.events.config.annotations.AsyncBus;\nimport org.jclouds.events.handlers.DeadEventLoggingHandler;\n\nimport com.google.common.eventbus.AsyncEventBus;\nimport com.google.common.eventbus.EventBus;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Provides;\n\n/**\n * Configures the {@link EventBus} to be used in the platform.\n * <p>\n * This class will provide an {@link AsyncEventBus} to be used to provide a basic pub/sub system for asynchronous\n * operations.\n * \n * \n * @see ExecutorServiceModule\n * @see AsyncEventBus\n * @see EventBus\n * @see AsyncBus\n */\n@ConfiguresEventBus\npublic class EventBusModule extends AbstractModule {\n   /**\n    * Provides an {@link AsyncEventBus} that will use the configured executor service to dispatch events to subscribers.\n    */\n   @Provides\n   @Singleton\n   final AsyncEventBus provideAsyncEventBus(@Named(PROPERTY_USER_THREADS) ListeningExecutorService userExecutor,\n         DeadEventLoggingHandler deadEventsHandler) {// NO_UCD\n      AsyncEventBus asyncBus = new AsyncEventBus(\"jclouds-async-event-bus\", userExecutor);\n      asyncBus.register(deadEventsHandler);\n      return asyncBus;\n   }\n\n   /**\n    * Provides asynchronous {@link EventBus}.\n    */\n   @Provides\n   @Singleton\n   final EventBus provideSyncEventBus(DeadEventLoggingHandler deadEventsHandler) { // NO_UCD\n      EventBus syncBus = new EventBus(\"jclouds-sync-event-bus\");\n      syncBus.register(deadEventsHandler);\n      return syncBus;\n   }\n\n   /**\n    * Configures the {@link EventBus} to be singleton and enables the {@link AsyncBus} annotation.\n    */\n   @Override\n   protected void configure() {\n      bind(EventBus.class).annotatedWith(AsyncBus.class).to(AsyncEventBus.class).in(SINGLETON);\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/events/config/annotations/AsyncBus.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.events.config.annotations;\n\nimport static java.lang.annotation.ElementType.ANNOTATION_TYPE;\nimport static java.lang.annotation.ElementType.FIELD;\nimport static java.lang.annotation.ElementType.PARAMETER;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\nimport jakarta.inject.Qualifier;\n\n/**\n * Used to configure {@link EventBus} injection, providing a flexible way to inject the\n * {@link AsyncEventBus}.\n * \n * \n * @see EventBusModule\n */\n@Target({ANNOTATION_TYPE, FIELD, PARAMETER})\n@Retention(RUNTIME)\n@Qualifier\npublic @interface AsyncBus {\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/events/handlers/DeadEventLoggingHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.events.handlers;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.eventbus.DeadEvent;\nimport com.google.common.eventbus.Subscribe;\n\n/**\n * Default handler for dead events.\n * <p>\n * It simply logs all dead events to allow debugging and troubleshooting.\n */\n@Singleton\npublic class DeadEventLoggingHandler {\n   @Resource\n   private Logger logger = Logger.NULL;\n\n   @Subscribe\n   public void handleDeadEvent(DeadEvent deadEvent) { // NO_UCD\n      logger.trace(\"detected dead event %s\", deadEvent.getEvent());\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/fallbacks/HeaderToRetryAfterException.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.fallbacks;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Throwables.propagate;\nimport static java.util.concurrent.TimeUnit.MILLISECONDS;\nimport static java.util.concurrent.TimeUnit.NANOSECONDS;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.date.DateCodec;\nimport org.jclouds.date.DateCodecFactory;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.rest.RetryAfterException;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Ticker;\nimport com.google.common.net.HttpHeaders;\n\n/**\n * propagates as {@link RetryAfterException} if a Throwable is an\n * {@link HttpResponseException} with a {@link HttpResponse set} and a valid\n * {@link HttpHeaders#RETRY_AFTER} header set.\n * \n * @see <a href=\"https://tools.ietf.org/html/rfc2616#section-14.37\">Retry-After\n *      format</a>\n */\n@Beta\npublic final class HeaderToRetryAfterException implements PropagateIfRetryAfter {\n\n   private final Ticker ticker;\n   private final DateCodec dateCodec;\n\n   /**\n    * \n    * @param ticker\n    *           how to read current time\n    * @param dateCodec\n    *           how to parse the {@link HttpHeaders#RETRY_AFTER} header, if it\n    *           is a Date.\n    * @return\n    */\n   public static HeaderToRetryAfterException create(Ticker ticker, DateCodec dateCodec) {\n      return new HeaderToRetryAfterException(ticker, dateCodec);\n   }\n\n   /**\n    * uses {@link Ticker#systemTicker()} and {@link DateCodecFactory#rfc822()}\n    */\n   @Inject\n   private HeaderToRetryAfterException(DateCodecFactory factory) {\n      this(Ticker.systemTicker(), factory.rfc822());\n   }\n\n   private HeaderToRetryAfterException(Ticker ticker, DateCodec dateCodec) {\n      this.ticker = checkNotNull(ticker, \"ticker\");\n      this.dateCodec = checkNotNull(dateCodec, \"dateCodec\");\n   }\n\n   @Override public Object createOrPropagate(Throwable t) throws Exception {\n      if (!(t instanceof HttpResponseException))\n         throw propagate(t);\n      HttpResponse response = HttpResponseException.class.cast(t).getResponse();\n      if (response == null) {\n         return null;\n      }\n\n      // https://tools.ietf.org/html/rfc2616#section-14.37\n      String retryAfter = response.getFirstHeaderOrNull(HttpHeaders.RETRY_AFTER);\n      if (retryAfter != null) {\n         Optional<RetryAfterException> retryException = tryCreateRetryAfterException(t, retryAfter);\n         if (retryException.isPresent())\n            throw retryException.get();\n      }\n\n      return null;\n   }\n\n   /**\n    * returns a {@link RetryAfterException} if parameter {@code retryAfter}\n    * corresponds to known formats.\n    * \n    * @see <a\n    *      href=\"https://tools.ietf.org/html/rfc2616#section-14.37\">Retry-After\n    *      format</a>\n    */\n   public Optional<RetryAfterException> tryCreateRetryAfterException(Throwable in, String retryAfter) {\n      checkNotNull(in, \"throwable\");\n      checkNotNull(retryAfter, \"retryAfter\");\n\n      if (retryAfter.matches(\"^[0-9]+$\"))\n         return Optional.of(new RetryAfterException(in, Integer.parseInt(retryAfter)));\n      try {\n         long retryTimeMillis = dateCodec.toDate(retryAfter).getTime();\n         long currentTimeMillis = NANOSECONDS.toMillis(ticker.read());\n         return Optional.of(new RetryAfterException(in, (int) MILLISECONDS.toSeconds(retryTimeMillis\n               - currentTimeMillis)));\n      } catch (IllegalArgumentException e) {\n         // ignored\n      }\n      return Optional.absent();\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/fallbacks/MapHttp4xxCodesToExceptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.fallbacks;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Throwables.propagate;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Fallback;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.ResourceNotFoundException;\n\n@Singleton\npublic final class MapHttp4xxCodesToExceptions implements Fallback<Object> {\n\n   private final PropagateIfRetryAfter propagateIfRetryAfter;\n\n   @Inject\n   MapHttp4xxCodesToExceptions(PropagateIfRetryAfter propagateIfRetryAfter) { // NO_UCD\n      this.propagateIfRetryAfter = checkNotNull(propagateIfRetryAfter, \"propagateIfRetryAfter\");\n   }\n   @Override\n   public Object createOrPropagate(Throwable t) throws Exception {\n      propagateIfRetryAfter.createOrPropagate(t); // if we pass here, we aren't a retry-after exception\n      if (t instanceof HttpResponseException) {\n         HttpResponseException responseException = HttpResponseException.class.cast(t);\n         if (responseException.getResponse() != null)\n            switch (responseException.getResponse().getStatusCode()) {\n            case 401:\n               throw new AuthorizationException(responseException);\n            case 403:\n               throw new AuthorizationException(responseException);\n            case 404:\n               throw new ResourceNotFoundException(responseException);\n            case 409:\n               throw new IllegalStateException(responseException);\n            }\n      }\n      throw propagate(t);\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/fallbacks/PropagateIfRetryAfter.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.fallbacks;\n\nimport org.jclouds.Fallback;\n\nimport com.google.inject.ImplementedBy;\n\n/**\n * propagates as {@link org.jclouds.rest.RetryAfterException} if a Throwable contains information such as a retry\n * offset.\n */\n@ImplementedBy(HeaderToRetryAfterException.class)\npublic interface PropagateIfRetryAfter extends Fallback<Object> {\n   /**\n    * if input is not of type {@link org.jclouds.http.HttpResponseException}, this method propagates. Otherwise,\n    * {@code null}, if didn't coerce to {@link org.jclouds.rest.RetryAfterException}\n    */\n   @Override Object createOrPropagate(Throwable t) throws Exception;\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/functions/ExpandProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Maps;\n\nimport org.gaul.modernizer_maven_annotations.SuppressModernizer;\n\n/**\n * Resolves the values of the properties so they can be inferred from other\n * properties.\n */\npublic class ExpandProperties implements Function<Properties, Properties> {\n\n   // Matches variables in a string such as ${foo.bar}\n   private static final Pattern VAR = Pattern.compile(\"\\\\$\\\\{[^\\\\}]+\\\\}\");\n\n   @Override\n   public Properties apply(final Properties properties) {\n      checkNotNull(properties, \"properties cannot be null\");\n\n      // Only expand the properties that are Strings\n      Map<String, String> stringProperties = Maps.toMap(properties.stringPropertyNames(),\n            new Function<String, String>() {\n               @Override\n               public String apply(String input) {\n                  return properties.getProperty(input);\n               }\n            });\n\n      boolean pendingReplacements = true;\n      Map<String, String> propertiesToResolve = new HashMap<String, String>(stringProperties);\n\n      while (pendingReplacements) {\n         Map<String, String> leafs = leafs(propertiesToResolve);\n         if (leafs.isEmpty()) {\n            break;\n         }\n         pendingReplacements = resolveProperties(propertiesToResolve, leafs);\n      }\n\n      // Replace the values with the resolved ones\n      Properties resolved = new Properties();\n      resolved.putAll(properties);\n      for (Map.Entry<String, String> entry : propertiesToResolve.entrySet()) {\n         resolved.setProperty(entry.getKey(), entry.getValue());\n      }\n\n      return resolved;\n   }\n\n   private Map<String, String> leafs(Map<String, String> input) {\n      return Maps.filterValues(input, new Predicate<String>() {\n         @Override\n         public boolean apply(String input) {\n            Matcher m = VAR.matcher(input);\n            return !m.find();\n         }\n      });\n   }\n\n   @SuppressModernizer  // for Matcher.appendReplacement(StringBuffer, String)\n   private boolean resolveProperties(Map<String, String> properties, Map<String, String> variables) {\n      boolean anyReplacementDone = false;\n      for (Map.Entry<String, String> entry : properties.entrySet()) {\n         String key = entry.getKey();\n         StringBuffer sb = new StringBuffer();\n         Matcher m = VAR.matcher(entry.getValue());\n         while (m.find()) {\n            String match = m.group();\n            // Remove the ${} from the matched variable\n            String var = match.substring(2, match.length() - 1);\n            // Avoid recursive properties. Only get he value if the variable\n            // is different than the current key\n            Optional<String> value = var.equals(key) ? Optional.<String> absent() : Optional.fromNullable(variables\n                  .get(var));\n            // Replace by the value or leave the original value\n            m.appendReplacement(sb, value.or(\"\\\\\" + match));\n            if (value.isPresent()) {\n               anyReplacementDone = true;\n            }\n         }\n         m.appendTail(sb);\n         properties.put(key, sb.toString());\n      }\n      return anyReplacementDone;\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/functions/IdentityFunction.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.functions;\n\nimport jakarta.inject.Singleton;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic enum IdentityFunction implements Function<Object, Object> {\n   INSTANCE;\n\n   public Object apply(Object o) {\n      return o;\n   }\n\n   @Override\n   public String toString() {\n      return \"identity\";\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/functions/JoinOnComma.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.functions;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.lang.reflect.Array;\n\nimport jakarta.inject.Singleton;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Joiner;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableList.Builder;\nimport com.google.common.collect.Iterables;\n\n@Singleton\npublic class JoinOnComma implements Function<Object, String> {\n\n   public String apply(Object o) {\n      checkNotNull(o, \"input cannot be null\");\n      if (o.getClass().isArray()) {\n         Builder<Object> builder = ImmutableList.builder();\n         for (int i = 0; i < Array.getLength(o); i++)\n            builder.add(Array.get(o, i));\n         o = builder.build();\n      }\n      checkArgument(o instanceof Iterable<?>, \"you must pass an iterable or array\");\n      Iterable<?> toJoin = (Iterable<?>) o;\n      checkArgument(!Iterables.isEmpty(toJoin), \"you must pass an iterable or array with elements\");\n      return Joiner.on(',').join(toJoin);\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/functions/OnlyElementOrNull.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.functions;\n\nimport jakarta.inject.Singleton;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.Iterables;\n\n@Singleton\npublic class OnlyElementOrNull<T> implements Function<Iterable<T>, T> {\n\n   @Override\n   public T apply(Iterable<T> arg0) {\n      if (arg0 == null || Iterables.isEmpty(arg0))\n         return null;\n      return Iterables.getOnlyElement(arg0);\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/functions/ToLowerCase.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Singleton;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class ToLowerCase implements Function<String, String> {\n\n\t@Override\n\tpublic String apply(String input) {\n\t\tcheckNotNull(input, \"input cannot be null\");\n\t\treturn input.toLowerCase();\n\t}\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/HttpCommand.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\n\nimport com.google.common.base.Objects;\n\n/**\n * Command whose endpoint is an http service.\n */\n//TODO: get rid of all the mock tests so that this can be made final\npublic class HttpCommand {\n\n   private volatile HttpRequest request;\n   private volatile int failureCount;\n   private volatile int redirectCount;\n   private volatile Exception exception;\n\n   public HttpCommand(HttpRequest request) {\n      this.request = checkNotNull(request, \"request\");\n      this.failureCount = 0;\n      this.redirectCount = 0;\n   }\n\n   /**\n    * This displays the current number of error retries for this command.\n    * \n    * @see org.jclouds.Constants.PROPERTY_MAX_RETRIES\n    */\n   public int getFailureCount() {\n      return failureCount;\n   }\n\n   /**\n    * increment the current failure count.\n    * \n    * @see #getFailureCount\n    */\n   public int incrementFailureCount() {\n      return ++failureCount;\n   }\n\n   /**\n    * Used to prevent a command from being re-executed, or having its response parsed.\n    */\n   public void setException(Exception exception) {\n      this.exception = exception;\n   }\n\n   /**\n    * @see #setException\n    */\n   public Exception getException() {\n      return exception;\n   }\n\n   /**\n    * increments the current number of redirect attempts for this command.\n    * \n    * @see #getRedirectCount\n    */\n   public int incrementRedirectCount() {\n      return ++redirectCount;\n   }\n\n   /**\n    * This displays the current number of redirect attempts for this command.\n    * \n    * @see org.jclouds.Constants.PROPERTY_MAX_REDIRECTS\n    */\n   public int getRedirectCount() {\n      return redirectCount;\n   }\n\n   /**\n    * Commands need to be replayed, if redirected or on a retryable error. Typically, this implies\n    * the payload carried is not a streaming type.\n    */\n   public boolean isReplayable() {\n      return (request.getPayload() == null) ? true : request.getPayload().isRepeatable();\n   }\n\n   /**\n    * The request associated with this command.\n    */\n   public HttpRequest getCurrentRequest() {\n      return request;\n   }\n\n   /**\n    * The request associated with this command.\n    */\n   public void setCurrentRequest(HttpRequest request) {\n      this.request = request;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(request);\n   }\n\n   @Override\n   public boolean equals(Object that) {\n      if (that == null)\n         return false;\n      if (!(that instanceof HttpCommand))\n         return false;\n      return Objects.equal(this.request, HttpCommand.class.cast(that).getCurrentRequest());\n   }\n\n   @Override\n   public String toString() {\n      if (request instanceof GeneratedHttpRequest) {\n         GeneratedHttpRequest gRequest = GeneratedHttpRequest.class.cast(request);\n         return String.format(\"[method=%s, request=%s]\", gRequest.getInvocation(), gRequest.getRequestLine());\n      }\n      return \"[request=\" + request.getRequestLine() + \"]\";\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/HttpCommandExecutorService.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http;\n\n/**\n * Capable of invoking http commands.\n */\npublic interface HttpCommandExecutorService {\n\n   /**\n    * Returns a {@code HttpResponse} from the server which responded to the\n    * {@code command}.\n    */\n   HttpResponse invoke(HttpCommand command);\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/HttpErrorHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http;\n\n/**\n * Responsible for setting an exception on the command relevant to the unrecoverable error in the\n * HttpResponse.\n */\npublic interface HttpErrorHandler {\n   HttpErrorHandler NOOP = new HttpErrorHandler() {\n      public void handleError(HttpCommand command, HttpResponse response) {\n         if (response.getPayload() != null)\n            response.getPayload().release();\n      }\n\n      public String toString() {\n         return \"NOOP\";\n      }\n   };\n\n   void handleError(HttpCommand command, HttpResponse response);\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/HttpException.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http;\n\n/**\n * // TODO: Adrian: Document this!\n */\npublic class HttpException extends RuntimeException {\n\n   private static final long serialVersionUID = 1L;\n\n   public HttpException(String s) {\n      super(s);\n   }\n\n   public HttpException(String s, Throwable throwable) {\n      super(s, throwable);\n   }\n\n   public HttpException(Throwable throwable) {\n      super(throwable);\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/HttpMessage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.io.File;\nimport java.io.InputStream;\nimport java.util.Collection;\n\nimport org.jclouds.functions.ToLowerCase;\nimport org.jclouds.http.internal.PayloadEnclosingImpl;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.util.Multimaps2;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.Multimap;\nimport com.google.common.io.ByteSource;\n\n/**\n * Represents a request that can be executed within {@link HttpCommandExecutorService}\n */\npublic class HttpMessage extends PayloadEnclosingImpl {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromHttpMessage(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>>  {\n      protected abstract T self();\n\n      protected ImmutableMultimap.Builder<String, String> headers = ImmutableMultimap.<String, String>builder();\n      protected Payload payload;\n\n      /**\n       * @see HttpMessage#getPayload()\n       */\n      public T payload(Payload payload) {\n         this.payload = payload;\n         return self();\n      }\n\n      /**\n       * @see HttpMessage#getPayload()\n       */\n      public T payload(byte [] payload) {\n         this.payload = Payloads.newByteArrayPayload(checkNotNull(payload, \"payload\"));\n         return self();\n      }\n\n      /**\n       * @see HttpMessage#getPayload()\n       */\n      public T payload(ByteSource payload) {\n         this.payload = Payloads.newByteSourcePayload(checkNotNull(payload, \"payload\"));\n         return self();\n      }\n\n      /**\n       * @see HttpMessage#getPayload()\n       */\n      public T payload(File payload) {\n         this.payload = Payloads.newFilePayload(checkNotNull(payload, \"payload\"));\n         return self();\n      }\n\n      /**\n       * @see HttpMessage#getPayload()\n       */\n      public T payload(InputStream payload) {\n         this.payload = Payloads.newInputStreamPayload(checkNotNull(payload, \"payload\"));\n         return self();\n      }\n\n      /**\n       * @see HttpMessage#getPayload()\n       */\n      public T payload(String payload) {\n         this.payload = Payloads.newStringPayload(checkNotNull(payload, \"payload\"));\n         return self();\n      }\n\n      /**\n       * replaces all headers with the the supplied multimap.\n       *\n       * @see HttpMessage#getHeaders()\n       */\n      public T headers(Multimap<String, String> headers) {\n         this.headers = ImmutableMultimap.<String, String> builder();\n         this.headers.putAll(checkNotNull(headers, \"headers\"));\n         return self();\n      }\n\n      /**\n       * replace all headers that have the same keys as the input multimap\n       *\n       * @see HttpMessage#getHeaders()\n       */\n      public T replaceHeaders(Multimap<String, String> headers) {\n         checkNotNull(headers, \"headers\");\n         Multimap<String, String> oldHeaders = this.headers.build();\n         this.headers = ImmutableMultimap.<String, String> builder();\n         this.headers.putAll(Multimaps2.replaceEntries(oldHeaders, headers));\n         return self();\n      }\n\n      /**\n       * replace all headers that have the same keys as the input multimap\n       *\n       * @see HttpMessage#getHeaders()\n       */\n      public T removeHeader(String name) {\n         checkNotNull(name, \"name\");\n         Multimap<String, String> oldHeaders = this.headers.build();\n         this.headers = ImmutableMultimap.<String, String> builder();\n         this.headers.putAll(Multimaps2.withoutKey(oldHeaders, name));\n         return self();\n      }\n\n      /**\n       * Note that if there's an existing header of the same name, this will only add the new value,\n       * not replace it.\n       *\n       * @see HttpMessage#getHeaders()\n       */\n      public T addHeader(String name, String ... values) {\n         this.headers.putAll(checkNotNull(name, \"name\"), checkNotNull(values, \"values of %s\", name));\n         return self();\n      }\n\n      /**\n       * Replace header.\n       *\n       * @see HttpMessage#getHeaders()\n       */\n      public T replaceHeader(String name, String ... values) {\n         checkNotNull(name, \"name\");\n         checkNotNull(values, \"values of %s\", name);\n         return replaceHeaders(ImmutableMultimap.<String, String> builder().putAll(name, values).build());\n      }\n\n      public HttpMessage build() {\n         return new HttpMessage(headers.build(), payload);\n      }\n\n      public T fromHttpMessage(HttpMessage in) {\n         return this\n               .headers(in.getHeaders())\n               .payload(in.getPayload());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   protected final Multimap<String, String> headers;\n\n   protected HttpMessage(Multimap<String, String> headers, @Nullable Payload payload) {\n      super(payload);\n      this.headers = ImmutableMultimap.copyOf(checkNotNull(headers, \"headers\"));\n   }\n\n   public Multimap<String, String> getHeaders() {\n      return headers;\n   }\n\n   /**\n    * try to get the value, then try as lowercase.\n    */\n   public String getFirstHeaderOrNull(String string) {\n      Collection<String> values = headers.get(string);\n      if (values.isEmpty()) {\n         Multimap<String, String> lowerCaseHeaders = Multimaps2.transformKeys(getHeaders(), new ToLowerCase());\n         values = lowerCaseHeaders.get(string.toLowerCase());\n      }\n      return (values.size() >= 1) ? values.iterator().next() : null;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(headers, payload);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      // testing equals by value, not by type\n      if (!(obj instanceof HttpMessage)) return false;\n      HttpMessage that = HttpMessage.class.cast(obj);\n      return Objects.equal(this.headers, that.headers)\n            && Objects.equal(this.payload, that.payload);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(\"\").omitNullValues()\n                    .add(\"headers\", headers)\n                    .add(\"payload\", payload);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/HttpRequest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.http.Uris.uriBuilder;\nimport static org.jclouds.http.utils.Queries.queryParser;\nimport static org.jclouds.io.Payloads.newUrlEncodedFormPayload;\n\nimport java.net.URI;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.io.Payload;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.LinkedHashMultimap;\nimport com.google.common.collect.Multimap;\nimport com.google.common.collect.Multimaps;\n\n/**\n * Represents a request that can be executed within {@link HttpCommandExecutorService}\n */\npublic class HttpRequest extends HttpMessage {\n\n   public static final Set<String> NON_PAYLOAD_METHODS = ImmutableSet\n         .of(\"OPTIONS\", \"GET\", \"HEAD\", \"DELETE\", \"TRACE\", \"CONNECT\");\n\n   public static Builder<?> builder() { \n      return new ConcreteBuilder();\n   }\n   \n   public Builder<?> toBuilder() { \n      return new ConcreteBuilder().fromHttpRequest(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> extends HttpMessage.Builder<T>  {\n      protected String method;\n      protected URI endpoint;\n      protected ImmutableList.Builder<HttpRequestFilter> filters = ImmutableList.<HttpRequestFilter>builder();\n   \n      /** \n       * @see HttpRequest#getMethod()\n       */\n      public T method(String method) {\n         this.method = checkNotNull(method, \"method\");\n         return self();\n      }\n\n      /** \n       * @see HttpRequest#getEndpoint()\n       */\n      public T endpoint(URI endpoint) {\n         this.endpoint = checkNotNull(endpoint, \"endpoint\");\n         return self();\n      }\n\n      /** \n       * @see HttpRequest#getEndpoint()\n       */\n      public T endpoint(String endpoint) {\n         return endpoint(URI.create(checkNotNull(endpoint, \"endpoint\")));\n      }\n      \n      /**\n       * @see HttpRequest#getEndpoint()\n       */\n      public T addQueryParam(String name, Iterable<String> values) {\n         endpoint = uriBuilder(endpoint).addQuery(name, values).build();\n         return self();\n      }\n      \n      /**\n       * @see HttpRequest#getEndpoint()\n       */\n      public T addQueryParam(String name, String... values) {\n         endpoint = uriBuilder(endpoint).addQuery(name, values).build();\n         return self();\n      }\n\n      /**\n       * @see HttpRequest#getEndpoint()\n       */\n      public T addQueryParams(Multimap<String, String> parameters) {\n         endpoint = uriBuilder(endpoint).addQuery(parameters).build();\n         return self();\n      }\n      \n      /**\n       * @see HttpRequest#getEndpoint()\n       */\n      public T replaceQueryParam(String name, Iterable<String> values) {\n         endpoint = uriBuilder(endpoint).replaceQuery(name, values).build();\n         return self();\n      }\n      \n      /**\n       * @see HttpRequest#getEndpoint()\n       */\n      public T replaceQueryParam(String name, String... values) {\n         endpoint = uriBuilder(endpoint).replaceQuery(name, values).build();\n         return self();\n      }\n      \n      /**\n       * @see HttpRequest#getEndpoint()\n       */\n      public T replaceQueryParams(Map<String, String> parameters) {\n         return replaceQueryParams(Multimaps.forMap(parameters));\n      }\n      \n      /**\n       * @see HttpRequest#getEndpoint()\n       */\n      public T replaceQueryParams(Multimap<String, String> parameters) {\n         endpoint = uriBuilder(endpoint).replaceQuery(parameters).build();\n         return self();\n      }\n\n      /**\n       * @see HttpRequest#getEndpoint()\n       */\n      public T replacePath(String path) {\n         checkNotNull(endpoint, \"endpoint\");\n         checkNotNull(path, \"path\");\n         endpoint = uriBuilder(endpoint).path(path).build();\n         return self();\n      }\n      \n      /**\n       * @see #addFormParams\n       */\n      public T addFormParam(String name, String... values) {\n         return addFormParams(ImmutableMultimap.<String, String> builder()\n                  .putAll(checkNotNull(name, \"name\"), checkNotNull(values, \"values of %s\", name)).build());\n      }\n\n      /**\n       * Replaces the current payload with one that is a urlencoded payload including the following\n       * parameters and any formerly set.\n       * \n       * @see HttpRequest#getPayload()\n       */\n      public T addFormParams(Multimap<String, String> parameters) {\n         checkNotNull(endpoint, \"endpoint\");\n         Multimap<String, String> map = payload != null ? queryParser().apply(payload.getRawContent().toString())\n               : LinkedHashMultimap.<String, String> create();\n         map.putAll(parameters);\n         payload = newUrlEncodedFormPayload(map);\n         return self();\n      }\n\n      /**\n       * @see #replaceFormParams\n       */\n      public T replaceFormParam(String name, String... values) {\n         return replaceFormParams(ImmutableMultimap.<String, String> builder()\n                  .putAll(checkNotNull(name, \"name\"), checkNotNull(values, \"values of %s\", name)).build());\n      }\n\n      /**\n       * Replaces the current payload with one that is a urlencoded payload including the following\n       * parameters and any formerly set.\n       * \n       * @see HttpRequest#getPayload()\n       */\n      public T replaceFormParams(Multimap<String, String> parameters) {\n         checkNotNull(endpoint, \"endpoint\");\n         Multimap<String, String> map = payload != null ? queryParser().apply(payload.getRawContent().toString())\n               : LinkedHashMultimap.<String, String> create();\n         for (Map.Entry<String, Collection<String>> entry : parameters.asMap().entrySet()) {\n            map.replaceValues(entry.getKey(), entry.getValue());\n         }\n         payload = newUrlEncodedFormPayload(map);\n         return self();\n      }\n\n      /** \n       * @see HttpRequest#getFilters()\n       */\n      public T filters(Iterable<HttpRequestFilter> filters) {\n         this.filters = ImmutableList.<HttpRequestFilter>builder();\n         this.filters.addAll(checkNotNull(filters, \"filters\"));\n         return self();\n      }\n\n      /** \n       * @see HttpRequest#getFilters()\n       */\n      public T filter(HttpRequestFilter filter) {\n         this.filters.add(checkNotNull(filter, \"filter\"));\n         return self();\n      }\n\n      public HttpRequest build() {\n         return new HttpRequest(method, endpoint, headers.build(), payload, filters.build());\n      }\n      \n      public T fromHttpRequest(HttpRequest in) {\n         return super.fromHttpMessage(in)\n                     .method(in.getMethod())\n                     .endpoint(in.getEndpoint())\n                     .filters(in.getFilters());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n   \n   private final String method;\n   private final URI endpoint;\n   private final List<HttpRequestFilter> filters;\n\n   protected HttpRequest(String method, URI endpoint, Multimap<String, String> headers, @Nullable Payload payload,\n         Iterable<HttpRequestFilter> filters) {\n      super(headers, payload);\n      this.method = checkNotNull(method, \"method\");\n      this.endpoint = checkNotNull(endpoint, \"endpoint\");\n      checkArgument(endpoint.getHost() != null, \"endpoint.getHost() is null for %s\", endpoint);\n      this.filters = ImmutableList.<HttpRequestFilter> copyOf(checkNotNull(filters, \"filters\"));\n   }\n\n   public String getRequestLine() {\n      return String.format(\"%s %s HTTP/1.1\", getMethod(), getEndpoint().toASCIIString());\n   }\n\n   /**\n    * We cannot return an enum, as per specification custom methods are allowed. Enums are not\n    * extensible.\n    * \n    * @see <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.1\" >rfc2616</a>\n    */\n   public String getMethod() {\n      return method;\n   }\n\n   public URI getEndpoint() {\n      return endpoint;\n   }\n\n   public List<HttpRequestFilter> getFilters() {\n      return filters;\n   }\n   \n   @Override\n   public int hashCode() {\n      return Objects.hashCode(method, endpoint, super.hashCode());\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      // testing equals by value, not by type\n      if (!(obj instanceof HttpRequest)) return false;\n      HttpRequest that = HttpRequest.class.cast(obj);\n      return super.equals(that) && Objects.equal(this.method, that.method)\n               && Objects.equal(this.endpoint, that.endpoint);\n   }\n   \n   @Override\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(\"\").omitNullValues()\n                    .add(\"method\", method)\n                    .add(\"endpoint\", endpoint)\n                    .add(\"headers\", headers)\n                    .add(\"payload\", payload);\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/HttpRequestFilter.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http;\n\n/**\n * // TODO: Adrian: Document this!\n * \n * NOTE: {@link #filter} must be idempotent in a sense that multiple calls to it with the same\n * request yield in the same output. Example: this is required for request retrial (\n * {@link org.jclouds.http.internal.BaseHttpCommandExecutorService}, so that signatures can be\n * updated.\n */\npublic interface HttpRequestFilter {\n   // note this is not generic typed, as http implementations do not care\n   // about subclasses.\n   HttpRequest filter(HttpRequest request) throws HttpException;\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/HttpResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http;\n\nimport org.jclouds.io.Payload;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.Multimap;\n\n/**\n * Represents a response produced from {@link HttpCommandExecutorService}\n */\npublic class HttpResponse extends HttpMessage {\n\n   public static Builder<?> builder() { \n      return new ConcreteBuilder();\n   }\n   \n   public Builder<?> toBuilder() { \n      return new ConcreteBuilder().fromHttpResponse(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> extends HttpMessage.Builder<T>  {\n      protected int statusCode;\n      protected String message;\n\n      /** \n       * @see HttpResponse#getStatusCode()\n       */\n      public T statusCode(int statusCode) {\n         this.statusCode = statusCode;\n         return self();\n      }\n\n      /** \n       * @see HttpResponse#getMessage()\n       */\n      public T message(@Nullable String message) {\n         this.message = message;\n         return self();\n      }\n\n      public HttpResponse build() {\n         return new HttpResponse(statusCode, message, headers.build(), payload);\n      }\n      \n      public T fromHttpResponse(HttpResponse in) {\n         return super.fromHttpMessage(in)\n                     .statusCode(in.getStatusCode())\n                     .message(in.getMessage());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n   \n   private final int statusCode;\n   private final String message;\n\n   protected HttpResponse(int statusCode, @Nullable String message, Multimap<String, String> headers, @Nullable Payload payload) {\n      super(headers, payload);\n      this.statusCode = statusCode;\n      this.message = message;\n   }\n\n   public int getStatusCode() {\n      return statusCode;\n   }\n\n   @Nullable\n   public String getMessage() {\n      return message;\n   }\n   \n   public String getStatusLine() {\n      return String.format(\"HTTP/1.1 %d %s\", getStatusCode(), getMessage());\n   }\n   \n   @Override\n   public int hashCode() {\n      return Objects.hashCode(statusCode, message, super.hashCode());\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      // testing equals by value, not by type\n      if (!(obj instanceof HttpResponse)) return false;\n      HttpResponse that = HttpResponse.class.cast(obj);\n      return super.equals(that) \n               && Objects.equal(this.statusCode, that.statusCode)\n               && Objects.equal(this.message, that.message);\n   }\n   \n   @Override\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(\"\").omitNullValues()\n                    .add(\"statusCode\", statusCode)\n                    .add(\"message\", message)\n                    .add(\"headers\", headers)\n                    .add(\"payload\", payload);\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/HttpResponseException.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http;\n\nimport org.jclouds.Constants;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.payloads.StringPayload;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.util.Strings2;\n\nimport java.io.IOException;\n\n/**\n * Represents an error obtained from an HttpResponse.\n */\npublic class HttpResponseException extends RuntimeException {\n\n   private static final long serialVersionUID = 1L;\n\n   protected final transient HttpCommand command;\n   protected final transient HttpResponse response;\n   private String content;\n\n   public HttpResponseException(String message, HttpCommand command, @Nullable HttpResponse response, Throwable cause) {\n      super(message, cause);\n      this.command = command;\n      this.response = response;\n   }\n\n   public HttpResponseException(String message, HttpCommand command, @Nullable HttpResponse response,\n         String content, Throwable cause) {\n      super(message, cause);\n      this.command = command;\n      this.response = response;\n      this.content = content;\n   }\n\n   public HttpResponseException(HttpCommand command, HttpResponse response, Throwable cause) {\n      this(String.format(\"command: %1$s failed with response: %2$s\", command.getCurrentRequest().getRequestLine(),\n            response.getStatusLine()), command, response, cause);\n   }\n\n   public HttpResponseException(HttpCommand command, HttpResponse response, String content, Throwable cause) {\n      this(String.format(\"command: %1$s failed with response: %2$s; content: [%3$s]\", command.getCurrentRequest()\n            .getRequestLine(), response.getStatusLine(), content), command, response, content, cause);\n   }\n\n   public HttpResponseException(String message, HttpCommand command, @Nullable HttpResponse response) {\n      super(message);\n      this.command = command;\n      this.response = response;\n   }\n\n   public HttpResponseException(String message, HttpCommand command, @Nullable HttpResponse response, String content) {\n      super(message);\n      this.command = command;\n      this.response = response;\n      this.content = content;\n   }\n\n   public HttpResponseException(HttpCommand command, HttpResponse response) {\n      this(command, response, false);\n   }\n   public HttpResponseException(HttpCommand command, HttpResponse response, boolean logSensitiveInformation) {\n      this(String.format(\"request: %s %sfailed with response: %s\", command.getCurrentRequest().getRequestLine(),\n            requestPayloadIfStringOrFormIfNotReturnEmptyString(command.getCurrentRequest(), logSensitiveInformation),\n            response.getStatusLine()), command, response);\n   }\n\n   static String requestPayloadIfStringOrFormIfNotReturnEmptyString(HttpRequest request) {\n      return requestPayloadIfStringOrFormIfNotReturnEmptyString(request, false);\n   }\n\n   static String requestPayloadIfStringOrFormIfNotReturnEmptyString(HttpRequest request, boolean logSensitiveInformation) {\n      Payload payload = request.getPayload();\n      if (payload != null\n            && (\"application/x-www-form-urlencoded\".equals(payload.getContentMetadata().getContentType()) || payload instanceof StringPayload)\n            && payload.getContentMetadata().getContentLength() != null\n            && payload.getContentMetadata().getContentLength() < 1024) {\n         try {\n            String logStatement;\n            if (payload.isSensitive() && !logSensitiveInformation) {\n               logStatement = \"Sensitive data in payload, use \" + Constants.PROPERTY_LOGGER_WIRE_LOG_SENSITIVE_INFO + \" override to enable logging this data.\";\n            } else if (payload instanceof StringPayload) {\n               logStatement = payload.getRawContent().toString();\n            } else {\n               logStatement = Strings2.toStringAndClose(payload.openStream());\n            }\n            return String.format(\" [%s] \", logStatement);\n         } catch (IOException e) {\n         }\n      }\n      return \"\";\n   }\n\n   public HttpResponseException(HttpCommand command, HttpResponse response, String content) {\n      this(String.format(\"command: %s failed with response: %s; content: [%s]\", command.getCurrentRequest()\n            .getRequestLine(), response.getStatusLine(), content), command, response, content);\n   }\n\n   @Nullable\n   public HttpCommand getCommand() {\n      return command;\n   }\n\n   @Nullable\n   public HttpResponse getResponse() {\n      return response;\n   }\n\n   public void setContent(String content) {\n      this.content = content;\n   }\n\n   public String getContent() {\n      return content;\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/HttpRetryHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http;\n\n/**\n * Indicate whether a request should be retried after a server error response (HTTP status code >=\n * 500) based on the request's replayable status and the number of attempts already performed.\n */\npublic interface HttpRetryHandler {\n   HttpRetryHandler ALWAYS_RETRY = new HttpRetryHandler() {\n      public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) {\n         return true;\n      }\n\n      @Override\n      public String toString() {\n         return \"ALWAYS_RETRY\";\n      }\n   };\n\n   HttpRetryHandler NEVER_RETRY = new HttpRetryHandler() {\n      public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) {\n         return false;\n      }\n\n      @Override\n      public String toString() {\n         return \"NEVER_RETRY\";\n      }\n   };\n\n   /**\n    * Return true if the command should be retried. This method should only be invoked when the\n    * response has failed with a HTTP 5xx error indicating a server-side error.\n    */\n   boolean shouldRetryRequest(HttpCommand command, HttpResponse response);\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/HttpUtils.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Predicates.and;\nimport static com.google.common.base.Predicates.equalTo;\nimport static com.google.common.base.Predicates.in;\nimport static com.google.common.base.Predicates.not;\nimport static com.google.common.base.Predicates.notNull;\nimport static com.google.common.base.Throwables.getCausalChain;\nimport static com.google.common.base.Throwables.propagate;\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.get;\nimport static com.google.common.collect.Iterables.size;\nimport static com.google.common.collect.Multimaps.filterKeys;\nimport static com.google.common.io.BaseEncoding.base64;\nimport static com.google.common.io.ByteStreams.toByteArray;\nimport static com.google.common.net.HttpHeaders.CACHE_CONTROL;\nimport static com.google.common.net.HttpHeaders.CONTENT_DISPOSITION;\nimport static com.google.common.net.HttpHeaders.CONTENT_ENCODING;\nimport static com.google.common.net.HttpHeaders.CONTENT_LANGUAGE;\nimport static com.google.common.net.HttpHeaders.CONTENT_LENGTH;\nimport static com.google.common.net.HttpHeaders.CONTENT_MD5;\nimport static com.google.common.net.HttpHeaders.CONTENT_TYPE;\nimport static com.google.common.net.HttpHeaders.EXPIRES;\nimport static org.jclouds.util.Closeables2.closeQuietly;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.lang.annotation.Annotation;\nimport java.util.Collection;\nimport java.util.Map.Entry;\n\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\nimport jakarta.ws.rs.HttpMethod;\n\nimport org.jclouds.Constants;\nimport org.jclouds.io.ContentMetadata;\nimport org.jclouds.io.MutableContentMetadata;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.PayloadEnclosing;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.logging.internal.Wire;\n\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Multimap;\nimport com.google.common.collect.ImmutableSet.Builder;\nimport com.google.common.reflect.Invokable;\nimport com.google.inject.Inject;\n\n@Singleton\npublic class HttpUtils {\n\n   @Inject(optional = true)\n   @Named(Constants.PROPERTY_RELAX_HOSTNAME)\n   private boolean relaxHostname = false;\n\n   private final int globalMaxConnections;\n   private final int globalMaxConnectionsPerHost;\n   private final int connectionTimeout;\n   private final int soTimeout;\n   \n   @Inject(optional = true)\n   @Named(Constants.PROPERTY_TRUST_ALL_CERTS)\n   private boolean trustAllCerts;\n\n   @Inject\n   public HttpUtils(@Named(Constants.PROPERTY_CONNECTION_TIMEOUT) int connectionTimeout,\n         @Named(Constants.PROPERTY_SO_TIMEOUT) int soTimeout,\n         @Named(Constants.PROPERTY_MAX_CONNECTIONS_PER_CONTEXT) int globalMaxConnections,\n         @Named(Constants.PROPERTY_MAX_CONNECTIONS_PER_HOST) int globalMaxConnectionsPerHost) {\n      this.soTimeout = soTimeout;\n      this.connectionTimeout = connectionTimeout;\n      this.globalMaxConnections = globalMaxConnections;\n      this.globalMaxConnectionsPerHost = globalMaxConnectionsPerHost;\n   }\n\n   public int getSocketOpenTimeout() {\n      return soTimeout;\n   }\n\n   public int getConnectionTimeout() {\n      return connectionTimeout;\n   }\n\n   public boolean relaxHostname() {\n      return relaxHostname;\n   }\n\n   public boolean trustAllCerts() {\n      return trustAllCerts;\n   }\n\n   public int getMaxConnections() {\n      return globalMaxConnections;\n   }\n\n   public int getMaxConnectionsPerHost() {\n      return globalMaxConnectionsPerHost;\n   }\n\n   public static byte[] toByteArrayOrNull(PayloadEnclosing response) {\n      if (response.getPayload() != null) {\n         InputStream input = null;\n         try {\n            input = response.getPayload().openStream();\n            return toByteArray(input);\n         } catch (IOException e) {\n            propagate(e);\n         } finally {\n            closeQuietly(input);\n         }\n      }\n      return null;\n   }\n\n   public static Optional<String> tryFindHttpMethod(Invokable<?, ?> method) {\n      Builder<String> methodsBuilder = ImmutableSet.builder();\n      for (Annotation annotation : method.getAnnotations()) {\n         HttpMethod http = annotation.annotationType().getAnnotation(HttpMethod.class);\n         if (http != null)\n            methodsBuilder.add(http.value());\n      }\n      Collection<String> methods = methodsBuilder.build();\n      switch (methods.size()) {\n      case 0:\n         return Optional.absent();\n      case 1:\n         return Optional.of(get(methods, 0));\n      default:\n         throw new IllegalStateException(\"You must specify at most one HttpMethod annotation on: \" + method);\n      }\n   }\n   \n   /**\n    * Content stream may need to be read. However, we should always close the http stream.\n    * \n    * @throws IOException\n    */\n   public static byte[] closeClientButKeepContentStream(PayloadEnclosing response) {\n      byte[] returnVal = toByteArrayOrNull(response);\n      if (returnVal != null && !response.getPayload().isRepeatable()) {\n         Payload newPayload = Payloads.newByteArrayPayload(returnVal);\n         MutableContentMetadata fromMd = response.getPayload().getContentMetadata();\n         MutableContentMetadata toMd = newPayload.getContentMetadata();\n         copy(fromMd, toMd);\n         response.setPayload(newPayload);\n      }\n      return returnVal;\n   }\n\n   public static void copy(ContentMetadata fromMd, MutableContentMetadata toMd) {\n      toMd.setCacheControl(fromMd.getCacheControl());\n      toMd.setContentLength(fromMd.getContentLength());\n      toMd.setContentMD5(fromMd.getContentMD5());\n      toMd.setContentType(fromMd.getContentType());\n      toMd.setContentDisposition(fromMd.getContentDisposition());\n      toMd.setContentEncoding(fromMd.getContentEncoding());\n      toMd.setContentLanguage(fromMd.getContentLanguage());\n      toMd.setExpires(fromMd.getExpires());\n   }\n\n   public void logRequest(Logger logger, HttpRequest request, String prefix) {\n      if (logger.isDebugEnabled()) {\n         logger.debug(\"%s %s\", prefix, request.getRequestLine().toString());\n         logMessage(logger, request, prefix);\n      }\n   }\n\n   private void logMessage(Logger logger, HttpMessage message, String prefix) {\n      for (Entry<String, String> header : message.getHeaders().entries()) {\n         if (header.getKey() != null)\n            logger.debug(\"%s %s: %s\", prefix, header.getKey(), header.getValue());\n      }\n      if (message.getPayload() != null) {\n         if (message.getPayload().getContentMetadata().getCacheControl() != null)\n            logger.debug(\"%s %s: %s\", prefix, CACHE_CONTROL, message.getPayload().getContentMetadata().getCacheControl());\n         if (message.getPayload().getContentMetadata().getContentType() != null)\n            logger.debug(\"%s %s: %s\", prefix, CONTENT_TYPE, message.getPayload().getContentMetadata().getContentType());\n         if (message.getPayload().getContentMetadata().getContentLength() != null)\n            logger.debug(\"%s %s: %s\", prefix, CONTENT_LENGTH, message.getPayload().getContentMetadata()\n                  .getContentLength());\n         byte[] md5 = message.getPayload().getContentMetadata().getContentMD5();\n         if (md5 != null)\n            logger.debug(\"%s %s: %s\", prefix, CONTENT_MD5, base64().encode(md5));\n         if (message.getPayload().getContentMetadata().getContentDisposition() != null)\n            logger.debug(\"%s %s: %s\", prefix, CONTENT_DISPOSITION, message.getPayload().getContentMetadata()\n                  .getContentDisposition());\n         if (message.getPayload().getContentMetadata().getContentEncoding() != null)\n            logger.debug(\"%s %s: %s\", prefix, CONTENT_ENCODING, message.getPayload().getContentMetadata()\n                  .getContentEncoding());\n         if (message.getPayload().getContentMetadata().getContentLanguage() != null)\n            logger.debug(\"%s %s: %s\", prefix, CONTENT_LANGUAGE, message.getPayload().getContentMetadata()\n                  .getContentLanguage());\n         if (message.getPayload().getContentMetadata().getExpires() != null)\n            logger.debug(\"%s %s: %s\", prefix, EXPIRES, message.getPayload().getContentMetadata().getExpires());\n      }\n   }\n\n   public void logResponse(Logger logger, HttpResponse response, String prefix) {\n      if (logger.isDebugEnabled()) {\n         logger.debug(\"%s %s\", prefix, response.getStatusLine().toString());\n         logMessage(logger, response, prefix);\n      }\n   }\n\n   public void checkRequestHasRequiredProperties(HttpRequest message) {\n      checkArgument(\n            message.getPayload() == null || message.getFirstHeaderOrNull(CACHE_CONTROL) == null,\n            \"configuration error please use request.getPayload().getContentMetadata().setCacheControl(value) as opposed to adding a cache control header: %s\",\n                  message);\n      checkArgument(\n            message.getPayload() == null || message.getFirstHeaderOrNull(CONTENT_TYPE) == null,\n            \"configuration error please use request.getPayload().getContentMetadata().setContentType(value) as opposed to adding a content type header: %s\",\n                  message);\n      checkArgument(\n            message.getPayload() == null || message.getFirstHeaderOrNull(CONTENT_LENGTH) == null,\n            \"configuration error please use request.getPayload().getContentMetadata().setContentLength(value) as opposed to adding a content length header: %s\",\n                  message);\n      checkArgument(\n            message.getPayload() == null || message.getPayload().getContentMetadata().getContentLength() != null\n                  || \"chunked\".equalsIgnoreCase(message.getFirstHeaderOrNull(\"Transfer-Encoding\")),\n            \"either chunked encoding must be set on the http request or contentlength set on the payload: %s\", message);\n      checkArgument(\n            message.getPayload() == null || message.getFirstHeaderOrNull(\"Content-MD5\") == null,\n            \"configuration error please use request.getPayload().getContentMetadata().setContentMD5(value) as opposed to adding a content md5 header: %s\",\n                  message);\n      checkArgument(\n            message.getPayload() == null || message.getFirstHeaderOrNull(\"Content-Disposition\") == null,\n            \"configuration error please use request.getPayload().getContentMetadata().setContentDisposition(value) as opposed to adding a content disposition header: %s\",\n                  message);\n      checkArgument(\n            message.getPayload() == null || message.getFirstHeaderOrNull(CONTENT_ENCODING) == null,\n            \"configuration error please use request.getPayload().getContentMetadata().setContentEncoding(value) as opposed to adding a content encoding header: %s\",\n                  message);\n      checkArgument(\n            message.getPayload() == null || message.getFirstHeaderOrNull(CONTENT_LANGUAGE) == null,\n            \"configuration error please use request.getPayload().getContentMetadata().setContentLanguage(value) as opposed to adding a content language header: %s\",\n                  message);\n      checkArgument(\n            message.getPayload() == null || message.getFirstHeaderOrNull(EXPIRES) == null,\n            \"configuration error please use request.getPayload().getContentMetadata().setExpires(value) as opposed to adding an expires header: %s\",\n                  message);\n   }\n\n   public static void releasePayload(HttpMessage from) {\n      if (from.getPayload() != null)\n         from.getPayload().release();\n   }\n\n   public static String nullToEmpty(byte[] md5) {\n      return md5 != null ? base64().encode(md5) : \"\";\n   }\n\n   public static String nullOrZeroToEmpty(Long contentLength) {\n      return contentLength != null && contentLength > 0 ? contentLength.toString() : \"\";\n   }\n\n   public static String nullToEmpty(Collection<String> collection) {\n      return (collection == null || collection.isEmpty()) ? \"\" : collection.iterator().next();\n   }\n\n   public static Long attemptToParseSizeAndRangeFromHeaders(HttpMessage from) throws HttpException {\n      String contentRange = from.getFirstHeaderOrNull(\"Content-Range\");\n      if (contentRange == null && from.getPayload() != null) {\n         return from.getPayload().getContentMetadata().getContentLength();\n      } else if (contentRange != null) {\n         return Long.parseLong(contentRange.substring(contentRange.lastIndexOf('/') + 1));\n      }\n      return null;\n   }\n\n   public static void checkRequestHasContentLengthOrChunkedEncoding(HttpMessage request, String message) {\n      boolean chunked = \"chunked\".equals(request.getFirstHeaderOrNull(\"Transfer-Encoding\"));\n      checkArgument(request.getPayload() == null || chunked\n            || request.getPayload().getContentMetadata().getContentLength() != null, message);\n   }\n\n   public static void wirePayloadIfEnabled(Wire wire, HttpMessage request) {\n      if (request.getPayload() != null && wire.enabled()) {\n         wire.output(request);\n         checkRequestHasContentLengthOrChunkedEncoding(request,\n               \"After wiring, the request has neither chunked encoding nor content length: \" + request);\n      }\n   }\n\n   public static <T> T returnValueOnCodeOrNull(Throwable from, T value, Predicate<Integer> codePredicate) {\n      Iterable<HttpResponseException> throwables = filter(getCausalChain(from), HttpResponseException.class);\n      if (size(throwables) >= 1 && get(throwables, 0).getResponse() != null\n            && codePredicate.apply(get(throwables, 0).getResponse().getStatusCode())) {\n         return value;\n      }\n      return null;\n   }\n\n   public static Multimap<String, String> filterOutContentHeaders(Multimap<String, String> headers) {\n      // http message usually comes in as a null key header, let's filter it out.\n      return ImmutableMultimap.copyOf(filterKeys(headers, and(notNull(), not(in(ContentMetadata.HTTP_HEADERS)))));\n   }\n\n   public static boolean contains404(Throwable t) {\n      return returnValueOnCodeOrNull(t, true, equalTo(404)) != null;\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/IOExceptionRetryHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http;\n\nimport java.io.IOException;\n\nimport org.jclouds.http.handlers.BackoffLimitedRetryHandler;\n\nimport com.google.inject.ImplementedBy;\n\n@ImplementedBy(BackoffLimitedRetryHandler.class)\npublic interface IOExceptionRetryHandler {\n\n   IOExceptionRetryHandler ALWAYS_RETRY = new IOExceptionRetryHandler() {\n      public boolean shouldRetryRequest(HttpCommand command, IOException response) {\n         return true;\n      }\n\n      @Override\n      public String toString() {\n         return \"ALWAYS_RETRY\";\n      }\n   };\n\n   IOExceptionRetryHandler NEVER_RETRY = new IOExceptionRetryHandler() {\n      public boolean shouldRetryRequest(HttpCommand command, IOException response) {\n         return false;\n      }\n\n      @Override\n      public String toString() {\n         return \"NEVER_RETRY\";\n      }\n   };\n\n   boolean shouldRetryRequest(HttpCommand command, IOException error);\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/UriTemplates.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\n\nimport com.google.common.collect.Lists;\n\npublic class UriTemplates {\n\n   /**\n    * \n    * @param template\n    *           URI template that can be in level 1 <a href=\"http://tools.ietf.org/html/rfc6570\">RFC6570</a> form.\n    * \n    * @param variables\n    *           to the URI template\n    * @return expanded template, leaving any unresolved parameters literal\n    */\n   public static String expand(String template, Map<String, ?> variables) {\n      if (checkNotNull(template, \"template\").length() < 3)\n         return template.toString(); // skip expansion if there's no valid variables set. ex. {a} is the first valid\n      checkNotNull(variables, \"variables for %s\", template);\n\n      // if no variables provided - return template as is\n      if (variables.isEmpty()) {\n         return template;\n      }\n\n      boolean inVar = false;\n      StringBuilder var = new StringBuilder();\n      StringBuilder builder = new StringBuilder();\n      for (char c : Lists.charactersOf(template)) {\n         switch (c) {\n         case '{':\n            if (inVar) {\n                builder.append('{');\n                builder.append(var);\n                var.setLength(0);\n            }\n            inVar = true;\n            break;\n         case '}':\n            String key = var.toString();\n            Object value = variables.get(var.toString());\n            if (inVar) {\n               if (value != null)\n                  builder.append(value);\n               else\n                  builder.append('{').append(key).append('}');\n            } else {\n               builder.append('}');\n            }\n            var.setLength(0);\n            inVar = false;\n            break;\n         default:\n            if (inVar)\n               var.append(c);\n            else\n               builder.append(c);\n         }\n      }\n\n      // if variables provided but, curve bracket is not closed - append remaining to the result\n      if (inVar) {\n         builder.append('{').append(var);\n      }\n\n      return builder.toString();\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/Uris.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Strings.emptyToNull;\nimport static com.google.common.collect.Multimaps.forMap;\nimport static org.jclouds.http.utils.Queries.buildQueryLine;\nimport static org.jclouds.http.utils.Queries.queryParser;\nimport static org.jclouds.util.Strings2.urlDecode;\nimport static org.jclouds.util.Strings2.urlEncode;\n\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.util.Arrays;\nimport java.util.Map;\n\nimport org.jclouds.http.utils.QueryValue;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.LinkedHashMultimap;\nimport com.google.common.collect.Lists;\nimport com.google.common.collect.Multimap;\nimport com.google.common.collect.Multimaps;\n\n/**\n * Functions on {@code String}s and {@link URI}s. Strings can be level 1 <a\n * href=\"http://tools.ietf.org/html/rfc6570\">RFC6570</a> form.\n *\n * ex.\n *\n * <pre>\n *  https://api.github.com/repos/{user}\n * </pre>\n *\n * <h4>Reminder</h4>\n *\n * Unresolved <a href=\"http://tools.ietf.org/html/rfc6570\">RFC6570</a> templates are not supported by\n * {@link URI#create(String)} and result in an {@link IllegalArgumentException}.\n *\n * <h4>Limitations</h4>\n *\n * In order to reduce complexity not needed in jclouds, this doesn't support {@link URI#getUserInfo()},\n * {@link URI#getFragment()}, or {@code matrix} params. Matrix params can be achieved via adding {@code ;} refs in the\n * http path directly. Moreover, since jclouds only uses level 1 templates, this doesn't support the additional forms\n * noted in the RFC.\n *\n * @since 1.6\n */\n@Beta\npublic final class Uris {\n\n   /**\n    * @param template\n    *           URI string that can be in level 1 <a href=\"http://tools.ietf.org/html/rfc6570\">RFC6570</a> form.\n    */\n   public static UriBuilder uriBuilder(CharSequence template) {\n      return new UriBuilder(template);\n   }\n\n   /**\n    * @param in\n    *           uri\n    */\n   public static UriBuilder uriBuilder(URI uri) {\n      return new UriBuilder(uri);\n   }\n\n   /**\n    * Mutable URI builder that can be in level 1 <a href=\"http://tools.ietf.org/html/rfc6570\">RFC6570</a> template form.\n    *\n    * ex.\n    *\n    * <pre>\n    *  https://api.github.com/repos/{user}\n    * </pre>\n    *\n    */\n   public static final class UriBuilder {\n      private static final TransformObjectToQueryValue QUERY_VALUE_TRANSFORMER = new TransformObjectToQueryValue();\n\n      // colon for urns, semicolon & equals for matrix params\n      private Iterable<Character> skipPathEncoding = Lists.charactersOf(\"/:;=\");\n      private String scheme;\n      private String host;\n      private Integer port;\n      private String path;\n      private Multimap<String, Object> query = LinkedHashMultimap.create();\n\n      /**\n       * override default of {@code / : ; =}\n       * @param scheme\n       *           scheme to set or replace\n       */\n      public UriBuilder skipPathEncoding(Iterable<Character> skipPathEncoding) {\n         this.skipPathEncoding = ImmutableSet.copyOf(checkNotNull(skipPathEncoding, \"skipPathEncoding\"));\n         return this;\n      }\n\n      /**\n       * @param scheme\n       *           scheme to set or replace\n       */\n      public UriBuilder scheme(String scheme) {\n         this.scheme = checkNotNull(scheme, \"scheme\");\n         return this;\n      }\n\n      /**\n       * @param host\n       *           host to set or replace\n       * @return replaced value\n       */\n      public UriBuilder host(String host) {\n         this.host = checkNotNull(host, \"host\");\n         return this;\n      }\n\n      public UriBuilder path(@Nullable String path) {\n         path = emptyToNull(path);\n         if (path == null)\n            this.path = null;\n         else\n            this.path = prefixIfNeeded(urlDecode(path));\n         return this;\n      }\n\n      public UriBuilder appendPath(String path) {\n         if (this.path == null) {\n            path(path);\n         } else {\n            path(slash(this.path, path));\n         }\n         return this;\n      }\n\n      public UriBuilder query(@Nullable String queryLine) {\n         if (query == null)\n            return clearQuery();\n         return query(queryParser().apply(queryLine));\n      }\n\n      public UriBuilder clearQuery() {\n         query.clear();\n         return this;\n      }\n\n      public UriBuilder query(Multimap<String, ?> parameters) {\n         Multimap<String, QueryValue> queryValueMultimap = Multimaps.transformValues(\n               checkNotNull(parameters, \"parameters\"), QUERY_VALUE_TRANSFORMER);\n         query.clear();\n         query.putAll(queryValueMultimap);\n         return this;\n      }\n\n      public UriBuilder addQuery(String name, Iterable<?> values) {\n         query.putAll(checkNotNull(name, \"name\"), Iterables.transform(checkNotNull(values, \"values of %s\", name),\n               QUERY_VALUE_TRANSFORMER));\n         return this;\n      }\n\n      public UriBuilder addQuery(String name, String... values) {\n         return addQuery(name, Arrays.asList(checkNotNull(values, \"values of %s\", name)));\n      }\n\n      public UriBuilder addQuery(Multimap<String, ?> parameters) {\n         Multimap<String, QueryValue> queryValueMultimap = Multimaps.transformValues(\n               checkNotNull(parameters, \"parameters\"), QUERY_VALUE_TRANSFORMER);\n         query.putAll(queryValueMultimap);\n         return this;\n      }\n\n      public UriBuilder replaceQuery(String name, Iterable<?> values) {\n         Iterable<QueryValue> queryValues = Iterables.transform(checkNotNull(values, \"values of %s\", name),\n               QUERY_VALUE_TRANSFORMER);\n         query.replaceValues(checkNotNull(name, \"name\"), queryValues);\n         return this;\n      }\n\n      public UriBuilder replaceQuery(String name, String... values) {\n         return replaceQuery(name, Arrays.asList(checkNotNull(values, \"values of %s\", name)));\n      }\n\n      public UriBuilder replaceQuery(Map<String, ?> parameters) {\n         return replaceQuery(forMap(parameters));\n      }\n\n      public UriBuilder replaceQuery(Multimap<String, ?> parameters) {\n         for (String key : checkNotNull(parameters, \"parameters\").keySet())\n            replaceQuery(key, parameters.get(key));\n         return this;\n      }\n\n      /**\n       * <a href=\"http://tools.ietf.org/html/rfc6570\">RFC6570</a> templates have variables defined in curly braces.\n       * Curly brace characters are unparsable via {@link URI#create} and result in an {@link IllegalArgumentException}.\n       *\n       * This implementation temporarily replaces curly braces with double parenthesis so that it can reuse\n       * {@link URI#create}.\n       *\n       * @param uri\n       *           template which may have template parameters inside\n       */\n      private UriBuilder(CharSequence uri) {\n         this(URI.create(escapeSpecialChars(checkNotNull(uri, \"uri\"))));\n      }\n\n      private static String escapeSpecialChars(CharSequence uri) {\n         // skip encoding if there's no valid variables set. ex. {a} is the left valid\n         if (uri.length() < 3)\n            return uri.toString();\n\n         // duplicates memory even if there are no special characters, however only requires a single scan.\n         StringBuilder builder = new StringBuilder();\n         for (char c : Lists.charactersOf(uri)) {\n            switch (c) {\n            case '{':\n               builder.append(\"((\");\n               break;\n            case '}':\n               builder.append(\"))\");\n               break;\n            default:\n               builder.append(c);\n            }\n         }\n         return builder.toString();\n      }\n\n      private static String unescapeSpecialChars(CharSequence uri) {\n         if (uri.length() < 5) // skip encoding if there's no valid variables set. ex. ((a)) is the left valid\n            return uri.toString();\n\n         char last = uri.charAt(0);  // duplicates even if there are no special characters, but only requires 1 scan\n         StringBuilder builder = new StringBuilder();\n         for (char c : Lists.charactersOf(uri)) {\n            switch (c) {\n            case '(':\n               if (last == '(') {\n                  builder.setCharAt(builder.length() - 1, '{');\n               } else {\n                  builder.append('(');\n               }\n               break;\n            case ')':\n               if (last == ')') {\n                  builder.setCharAt(builder.length() - 1, '}');\n               } else {\n                  builder.append(')');\n               }\n               break;\n            default:\n               builder.append(c);\n            }\n            last = c;\n         }\n         return builder.toString();\n      }\n\n      private UriBuilder(URI uri) {\n         checkNotNull(uri, \"uri\");\n         this.scheme = uri.getScheme();\n         this.host = uri.getHost();\n         this.port = uri.getPort() == -1 ? null : uri.getPort();\n         if (uri.getRawPath() != null)\n            // path decodes the string, so we need to get at the raw (encoded) string\n            path(unescapeSpecialChars(uri.getRawPath()));\n         if (uri.getRawQuery() != null)\n            // The query parser decodes the strings that are passed to it; we should pass raw (encoded) queries\n            query(queryParser().apply(unescapeSpecialChars(uri.getRawQuery())));\n      }\n\n      public URI build() {\n         return build(ImmutableMap.<String, Object> of());\n      }\n\n      public URI build(Map<String, ?> variables, boolean encodePath) {\n         try {\n            return new URI(expand(variables, encodePath));\n         } catch (URISyntaxException e) {\n            throw new IllegalArgumentException(e);\n         }\n      }\n\n      /**\n       * @throws IllegalArgumentException\n       *            if there's a problem parsing the URI\n       */\n      public URI build(Map<String, ?> variables) {\n         try {\n            return new URI(expand(variables, true));\n         } catch (URISyntaxException e) {\n            throw new IllegalArgumentException(e);\n         }\n      }\n\n      private String expand(Map<String, ?> variables, boolean encodePath) {\n         StringBuilder b = new StringBuilder();\n         if (scheme != null)\n            b.append(scheme).append(\"://\");\n         if (host != null)\n            b.append(UriTemplates.expand(host, variables));\n         if (port != null)\n            b.append(':').append(port);\n         if (path != null) {\n            if (encodePath) {\n               b.append(urlEncode(UriTemplates.expand(path, variables), skipPathEncoding));\n            } else {\n               b.append(UriTemplates.expand(path, variables));\n            }\n         }\n         if (!query.isEmpty()) {\n            b.append('?').append(buildQueryLine(query));\n         }\n         return b.toString();\n      }\n\n      /**\n       * returns template expression without url encoding\n       */\n      @Override\n      public String toString() {\n         StringBuilder b = new StringBuilder();\n         if (scheme != null)\n            b.append(scheme).append(\"://\");\n         if (host != null)\n            b.append(host);\n         if (port != null)\n            b.append(':').append(port);\n         if (path != null)\n            b.append(path);\n         if (!query.isEmpty())\n            b.append('?').append(buildQueryLine(query));\n         return b.toString();\n      }\n   }\n\n   private static String slash(CharSequence left, CharSequence right) {\n      return delimit(left, right, '/');\n   }\n\n   private static String delimit(CharSequence left, CharSequence right, char token) {\n      if (left.length() == 0)\n         return right.toString();\n      if (right.length() == 0)\n         return left.toString();\n      StringBuilder builder = new StringBuilder(left);\n      if (lastChar(left) == token) {\n         if (firstChar(right) == token) // left/ + /right\n            return builder.append(right.subSequence(1, right.length())).toString();\n         return builder.append(right).toString(); // left/ + right\n      } else if (firstChar(right) == token) {\n         return builder.append(right).toString(); // left + /right\n      } // left + / + right\n      return new StringBuilder(left).append(token).append(right).toString();\n   }\n\n   public static boolean lastCharIsToken(CharSequence left, char token) {\n      return lastChar(left) == token;\n   }\n\n   public static char lastChar(CharSequence in) {\n      return in.charAt(in.length() - 1);\n   }\n\n   public static char firstChar(CharSequence in) {\n      return in.charAt(0);\n   }\n\n   public static boolean isToken(CharSequence right, char token) {\n      return right.length() == 1 && right.charAt(0) == token;\n   }\n\n   private static String prefixIfNeeded(String in) {\n      if (in != null && in.charAt(0) != '/')\n         return new StringBuilder().append('/').append(in).toString();\n      return in;\n   }\n\n   private static class TransformObjectToQueryValue implements Function<Object, QueryValue> {\n      @Override\n      public QueryValue apply(Object o) {\n         if (o == null) {\n            return null;\n         }\n         if (o instanceof QueryValue) {\n            return (QueryValue) o;\n         }\n         return new QueryValue(o.toString(), false);\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/annotation/ClientError.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.annotation;\n\nimport static java.lang.annotation.ElementType.FIELD;\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.ElementType.PARAMETER;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\nimport jakarta.inject.Qualifier;\n\n/**\n * Implies that the object can address {@link org.jclouds.http.HttpResponse}s\n * that contain status code 4xx.\n */\n@Qualifier\n@Target( { FIELD, PARAMETER, METHOD })\n@Retention(RUNTIME)\npublic @interface ClientError {\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/annotation/Redirection.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.annotation;\n\nimport static java.lang.annotation.ElementType.FIELD;\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.ElementType.PARAMETER;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\nimport jakarta.inject.Qualifier;\n\n/**\n * Implies that the object can address {@link org.jclouds.http.HttpResponse}s that contain status\n * code 3xx.\n */\n@Qualifier\n@Target( { FIELD, PARAMETER, METHOD })\n@Retention(RUNTIME)\npublic @interface Redirection {\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/annotation/ServerError.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.annotation;\n\nimport static java.lang.annotation.ElementType.FIELD;\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.ElementType.PARAMETER;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\nimport jakarta.inject.Qualifier;\n\n/**\n * Implies that the object can address {@link org.jclouds.http.HttpResponse}s that contain status\n * code 5xx.\n */\n@Qualifier\n@Target( { FIELD, PARAMETER, METHOD })\n@Retention(RUNTIME)\npublic @interface ServerError {\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/config/ConfiguresHttpCommandExecutorService.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.config;\n\nimport static java.lang.annotation.ElementType.TYPE;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\n/**\n * designates the the module configures a {@link HttpCommandExecutorService}\n */\n@Retention(RUNTIME)\n@Target(TYPE)\npublic @interface ConfiguresHttpCommandExecutorService {\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/config/JavaUrlHttpCommandExecutorServiceModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.config;\n\nimport org.jclouds.http.HttpCommandExecutorService;\nimport org.jclouds.http.internal.JavaUrlHttpCommandExecutorService;\n\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Scopes;\n\n/**\n * Configures {@link JavaUrlHttpCommandExecutorService}.\n * \n * Note that this uses threads\n */\n@ConfiguresHttpCommandExecutorService\npublic class JavaUrlHttpCommandExecutorServiceModule extends AbstractModule {\n\n   @Override\n   protected void configure() {\n      install(new SSLModule());\n      bind(HttpCommandExecutorService.class).to(JavaUrlHttpCommandExecutorService.class).in(Scopes.SINGLETON);\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/config/SSLModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.config;\n\nimport java.security.SecureRandom;\nimport java.security.cert.X509Certificate;\nimport java.util.Map;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\nimport javax.net.ssl.HostnameVerifier;\nimport javax.net.ssl.SSLContext;\nimport javax.net.ssl.SSLSession;\nimport javax.net.ssl.TrustManager;\nimport javax.net.ssl.X509TrustManager;\n\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.collect.MapMaker;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Throwables;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.name.Names;\n\npublic class SSLModule extends AbstractModule {\n\n   @Override\n   protected void configure() {\n      bind(HostnameVerifier.class).annotatedWith(Names.named(\"untrusted\")).to(LogToMapHostnameVerifier.class);\n      bind(new TypeLiteral<Supplier<SSLContext>>() {\n      }).annotatedWith(Names.named(\"untrusted\")).to(new TypeLiteral<UntrustedSSLContextSupplier>() {\n      });\n      bind(X509TrustManager.class).annotatedWith(Names.named(\"untrusted\")).to(TrustAllCerts.class);\n   }\n\n   /**\n    * \n    * Used to get more information about HTTPS hostname wrong errors.\n    * \n    */\n   @Singleton\n   public static class LogToMapHostnameVerifier implements HostnameVerifier {\n      @Resource\n      private Logger logger = Logger.NULL;\n      private final Map<String, String> sslMap = new MapMaker().makeMap();\n\n      public boolean verify(String hostname, SSLSession session) {\n         String peerHost = session.getPeerHost();\n         if (!hostname.equals(peerHost)) {\n             String oldPeerHost = sslMap.get(hostname);\n             if (oldPeerHost == null || !oldPeerHost.equals(peerHost)) {\n                 logger.warn(\"hostname was %s while session was %s\", hostname, peerHost);\n                 sslMap.put(hostname, peerHost);\n             }\n         }\n         return true;\n      }\n   }\n\n   @Singleton\n   public static class UntrustedSSLContextSupplier implements Supplier<SSLContext> {\n      private final SSLContext sslContext;\n\n      @Inject\n      UntrustedSSLContextSupplier(TrustAllCerts trustAllCerts) {\n         try {\n            SSLContext sslContext = SSLContext.getInstance(\"TLS\");\n            sslContext.init(null, new TrustManager[] { trustAllCerts }, new SecureRandom());\n            this.sslContext = sslContext;\n         } catch (Exception e) {\n            throw Throwables.propagate(e);\n         }\n      }\n\n      @Override\n      public SSLContext get() {\n         return sslContext;\n      }\n   }\n\n   /**\n    * \n    * Used to trust all certs\n    * \n    */\n   @Singleton\n   public static class TrustAllCerts implements X509TrustManager {\n      public X509Certificate[] getAcceptedIssuers() {\n         return new X509Certificate[0];\n      }\n\n      public void checkClientTrusted(X509Certificate[] certs, String authType) {\n         return;\n      }\n\n      public void checkServerTrusted(X509Certificate[] certs, String authType) {\n         return;\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/filters/BasicAuthentication.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.filters;\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.io.BaseEncoding.base64;\nimport static com.google.common.net.HttpHeaders.AUTHORIZATION;\nimport static java.lang.String.format;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpRequestFilter;\nimport org.jclouds.location.Provider;\n\nimport com.google.common.base.Supplier;\n\n/**\n * Uses Basic Authentication to sign the request.\n * \n * @see <a href= \"http://en.wikipedia.org/wiki/Basic_access_authentication\" />\n */\n@Singleton\npublic class BasicAuthentication implements HttpRequestFilter {\n\n   private final Supplier<Credentials> creds;\n\n   @Inject\n   public BasicAuthentication(@Provider Supplier<Credentials> creds) {\n      this.creds = checkNotNull(creds, \"creds\");\n   }\n\n   public static String basic(String user, String password) {\n      return new StringBuilder(\"Basic \").append(\n            base64().encode(\n                  format(\"%s:%s\", checkNotNull(user, \"user\"), checkNotNull(password, \"password\")).getBytes(UTF_8)))\n            .toString();\n   }\n\n   @Override\n   public HttpRequest filter(HttpRequest request) throws HttpException {\n      Credentials currentCreds = checkNotNull(creds.get(), \"credential supplier returned null\");\n      return request.toBuilder().replaceHeader(AUTHORIZATION, basic(currentCreds.identity, currentCreds.credential))\n            .build();\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/filters/ConnectionCloseHeader.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.http.filters;\n\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpRequestFilter;\n\nimport com.google.common.net.HttpHeaders;\nimport com.google.inject.Singleton;\n\n@Singleton\npublic class ConnectionCloseHeader implements HttpRequestFilter {\n   @Override\n   public HttpRequest filter(HttpRequest request) throws HttpException {\n      return request.toBuilder().addHeader(HttpHeaders.CONNECTION, \"close\").build();\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/filters/StripExpectHeader.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.http.filters;\n\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpRequestFilter;\n\nimport com.google.common.net.HttpHeaders;\nimport com.google.inject.Singleton;\n\n@Singleton\npublic class StripExpectHeader implements HttpRequestFilter {\n   @Override\n   public HttpRequest filter(HttpRequest request) throws HttpException {\n      return request.toBuilder().removeHeader(HttpHeaders.EXPECT).build();\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/functions/ParseETagHeader.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.functions;\n\nimport static com.google.common.net.HttpHeaders.ETAG;\nimport static org.jclouds.http.HttpUtils.releasePayload;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpResponse;\n\nimport com.google.common.base.Function;\n\n/**\n * Parses an MD5 checksum from the header {@link com.google.common.net.HttpHeaders.HttpHeaders#ETAG}.\n */\n@Singleton\npublic class ParseETagHeader implements Function<HttpResponse, String> {\n\n   public String apply(HttpResponse from) {\n      releasePayload(from);\n      String eTag = from.getFirstHeaderOrNull(ETAG);\n      if (eTag == null) {\n         // TODO: Cloud Files sends incorrectly cased ETag header... Remove this when fixed.\n         eTag = from.getFirstHeaderOrNull(\"Etag\");\n      }\n      if (eTag != null) {\n         return eTag;\n      }\n      throw new HttpException(\"did not receive ETag\");\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/functions/ParseFirstJsonValueNamed.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport jakarta.annotation.Resource;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.json.internal.GsonWrapper;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.util.Closeables2;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.util.concurrent.Atomics;\nimport com.google.gson.stream.JsonReader;\nimport com.google.gson.stream.JsonToken;\nimport com.google.inject.TypeLiteral;\n\npublic class ParseFirstJsonValueNamed<T> implements Function<HttpResponse, T> {\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   private final GsonWrapper json;\n   private final TypeLiteral<T> type;\n   private final ImmutableSet<String> nameChoices;\n\n   /**\n    * @param nameChoices\n    *           tried in order, first match wins\n    */\n   public ParseFirstJsonValueNamed(GsonWrapper json, TypeLiteral<T> type, String... nameChoices) {\n      this.json = checkNotNull(json, \"json\");\n      this.type = checkNotNull(type, \"type\");\n      this.nameChoices = ImmutableSet.copyOf(checkNotNull(nameChoices, \"nameChoices\"));\n   }\n\n   @Override\n   public T apply(HttpResponse arg0) {\n      if (arg0.getPayload() == null)\n         return nothing();\n      JsonReader reader = null;\n      try {\n         reader = new JsonReader(new InputStreamReader(arg0.getPayload().getInput()));\n         // in case keys are not in quotes\n         reader.setLenient(true);\n         AtomicReference<String> name = Atomics.newReference();\n         JsonToken token = reader.peek();\n         for (; token != JsonToken.END_DOCUMENT && nnn(reader, token, name); token = skipAndPeek(token, reader)) {\n         }\n         if (name.get() == null) {\n            logger.trace(\"did not object named %s in json from response %s\", nameChoices, arg0);\n            return nothing();\n         } else if (nameChoices.contains(name.get())) {\n            return json.delegate().<T> fromJson(reader, type.getType());\n         } else {\n            return nothing();\n         }\n      } catch (IOException e) {\n         throw new RuntimeException(String.format(\n               \"error reading from stream, parsing object named %s from http response %s\", nameChoices, arg0), e);\n      } finally {\n         Closeables2.closeQuietly(reader);\n         arg0.getPayload().release();\n      }\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   private T nothing() {\n      if (type.getRawType().isAssignableFrom(Set.class))\n         return (T) ImmutableSet.of();\n      else if (type.getRawType().isAssignableFrom(List.class))\n         return (T) ImmutableList.of();\n      else if (type.getRawType().isAssignableFrom(Map.class))\n         return (T) ImmutableMap.of();\n      return null;\n   }\n\n   private boolean nnn(JsonReader reader, JsonToken token, AtomicReference<String> name) throws IOException {\n      if (token == JsonToken.NAME) {\n         String name2 = reader.nextName();\n         if (nameChoices.contains(name2)) {\n            name.set(name2);\n            return false;\n         }\n      }\n      return true;\n\n   }\n\n   private JsonToken skipAndPeek(JsonToken token, JsonReader reader) throws IOException {\n      switch (token) {\n      case BEGIN_ARRAY:\n         reader.beginArray();\n         break;\n      case END_ARRAY:\n         reader.endArray();\n         break;\n      case BEGIN_OBJECT:\n         reader.beginObject();\n         break;\n      case END_OBJECT:\n         reader.endObject();\n         break;\n      case NAME:\n         // NOTE that we have already advanced on NAME in the eval block;\n         break;\n      case STRING:\n         reader.nextString();\n         break;\n      case NUMBER:\n         reader.nextString();\n         break;\n      case BOOLEAN:\n         reader.nextBoolean();\n         break;\n      case NULL:\n         reader.nextNull();\n         break;\n      case END_DOCUMENT:\n         break;\n      }\n      return reader.peek();\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/functions/ParseJson.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.functions;\n\nimport static org.jclouds.http.HttpUtils.releasePayload;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.lang.reflect.Type;\nimport java.nio.charset.StandardCharsets;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.json.Json;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Function;\nimport com.google.inject.TypeLiteral;\n\n/**\n * This object will parse the body of an HttpResponse and return the result of\n * type <T> back to the caller.\n */\n@Singleton\npublic class ParseJson<T> implements Function<HttpResponse, T> {\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n   protected final Json json;\n   protected final TypeLiteral<T> type;\n\n   @Inject\n   public ParseJson(Json json, TypeLiteral<T> type) {\n      this.json = json;\n      this.type = type;\n   }\n\n   /**\n    * parses the http response body to create a new {@code <T>}.\n    */\n   public T apply(HttpResponse from) {\n      try {\n         InputStream gson = from.getPayload().openStream();\n         return apply(gson);\n      } catch (Exception e) {\n         StringBuilder message = new StringBuilder();\n         message.append(\"Error parsing input: \");\n         message.append(e.getMessage());\n         logger.error(e, message.toString());\n         throw new HttpResponseException(message.toString() + \"\\n\" + from, null, from, e);\n      } finally {\n         releasePayload(from);\n      }\n\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   public T apply(InputStream stream) throws IOException {\n      return (T) apply(stream, type.getType());\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   public <V> V apply(InputStream stream, Type type) throws IOException {\n      try {\n         return (V) json.fromJson(stream, StandardCharsets.UTF_8, type);\n      } finally {\n         if (stream != null)\n            stream.close();\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/functions/ParseSax.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.functions;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.http.HttpUtils.closeClientButKeepContentStream;\nimport static org.jclouds.util.Closeables2.closeQuietly;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.StringReader;\nimport java.nio.charset.StandardCharsets;\n\nimport jakarta.annotation.Resource;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.rest.InvocationContext;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.xml.sax.InputSource;\nimport org.xml.sax.SAXException;\nimport org.xml.sax.SAXParseException;\nimport org.xml.sax.XMLReader;\nimport org.xml.sax.helpers.DefaultHandler;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Throwables;\nimport org.jclouds.util.Closeables2;\n\n/**\n * This object will parse the body of an HttpResponse and return the result of type <T> back to the\n * caller.\n */\npublic class ParseSax<T> implements Function<HttpResponse, T>, InvocationContext<ParseSax<T>> {\n\n   @Resource\n   private Logger logger = Logger.NULL;\n\n   private final XMLReader parser;\n   private final HandlerWithResult<T> handler;\n   private HttpRequest request;\n\n   public interface Factory {\n      <T> ParseSax<T> create(HandlerWithResult<T> handler);\n   }\n\n   public ParseSax(XMLReader parser, HandlerWithResult<T> handler) {\n      this.parser = checkNotNull(parser, \"parser\");\n      this.handler = checkNotNull(handler, \"handler\");\n   }\n\n   public T apply(HttpResponse from) {\n      try {\n         checkNotNull(from, \"http response\");\n         checkNotNull(from.getPayload(), \"payload in \" + from);\n      } catch (NullPointerException e) {\n         return addDetailsAndPropagate(from, e);\n      }\n      InputStream is = null;\n      try {\n         // debug is more normally set, so trace is more appropriate for\n         // something heavy like this\n         if (from.getStatusCode() >= 300 || logger.isTraceEnabled())\n            return convertStreamToStringAndParse(from);\n         is = from.getPayload().getInput();\n         return parse(new InputSource(is));\n      } catch (RuntimeException e) {\n         return addDetailsAndPropagate(from, e);\n      } finally {\n         Closeables2.closeQuietly(is);\n         from.getPayload().release();\n      }\n   }\n\n   private T convertStreamToStringAndParse(HttpResponse response) {\n      String from = null;\n      try {\n         byte[] fromBytes = closeClientButKeepContentStream(response);\n         from = new String(fromBytes, StandardCharsets.UTF_8);\n         validateXml(from);\n         // Use InputStream to skip over byte order mark.\n         return doParse(new InputSource(new ByteArrayInputStream(fromBytes)));\n      } catch (Exception e) {\n         return addDetailsAndPropagate(response, e, from);\n      }\n   }\n\n   public T parse(String from) {\n      try {\n         validateXml(from);\n         return doParse(new InputSource(new StringReader(from)));\n      } catch (Exception e) {\n         return addDetailsAndPropagate(null, e, from);\n      }\n   }\n\n   private void validateXml(String from) {\n      checkNotNull(from, \"xml string\");\n      checkArgument(from.indexOf('<') >= 0, \"not an xml document [%s] \", from);\n   }\n\n   public T parse(InputStream from) {\n      try {\n         return parse(new InputSource(from));\n      } finally {\n         closeQuietly(from);\n      }\n   }\n\n   public T parse(InputSource from) {\n      try {\n         return doParse(from);\n      } catch (Exception e) {\n         return addDetailsAndPropagate(null, e);\n      }\n   }\n\n   protected T doParse(InputSource from) throws IOException, SAXException {\n      checkNotNull(from, \"xml inputsource\");\n      from.setEncoding(StandardCharsets.UTF_8.name());\n      parser.setContentHandler(getHandler());\n      // This method should accept documents with a BOM (Byte-order mark)\n      parser.parse(from);\n      return getHandler().getResult();\n   }\n\n   public T addDetailsAndPropagate(HttpResponse response, Exception e) {\n      return addDetailsAndPropagate(response, e, null);\n   }\n\n   public T addDetailsAndPropagate(HttpResponse response, Exception e, @Nullable String text) {\n      StringBuilder message = new StringBuilder();\n      if (request != null) {\n         message.append(\"request: \").append(request.getRequestLine());\n      }\n      if (response != null) {\n         if (message.length() != 0)\n            message.append(\"; \");\n         message.append(\"response: \").append(response.getStatusLine());\n      }\n      if (e instanceof SAXParseException) {\n         SAXParseException parseException = (SAXParseException) e;\n         String systemId = parseException.getSystemId();\n         if (systemId == null) {\n            systemId = \"\";\n         }\n         if (message.length() != 0)\n            message.append(\"; \");\n         message.append(String.format(\"error at %d:%d in document %s\", parseException.getColumnNumber(), parseException\n                  .getLineNumber(), systemId));\n      }\n      if (text != null)\n         message.append(\"; source:\\n\").append(text);\n      if (message.length() != 0) {\n         message.append(\"; cause: \").append(e.toString());\n         throw new RuntimeException(message.toString(), e);\n      } else {\n         throw Throwables.propagate(e);\n      }\n\n   }\n\n   public HandlerWithResult<T> getHandler() {\n      return handler;\n   }\n\n   /**\n    * Handler that produces a useable domain object accessible after parsing completes.\n    * \n    */\n   public abstract static class HandlerWithResult<T> extends DefaultHandler implements\n            InvocationContext<HandlerWithResult<T>> {\n      private HttpRequest request;\n\n      protected HttpRequest getRequest() {\n         return request;\n      }\n\n      public abstract T getResult();\n\n      @Override\n      public HandlerWithResult<T> setContext(HttpRequest request) {\n         this.request = request;\n         return this;\n      }\n   }\n\n   public abstract static class HandlerForGeneratedRequestWithResult<T> extends HandlerWithResult<T> {\n\n      @Override\n      public HandlerForGeneratedRequestWithResult<T> setContext(HttpRequest request) {\n         checkArgument(checkNotNull(request, \"request\") instanceof GeneratedHttpRequest, \"note this handler requires a GeneratedHttpRequest\");\n         super.setContext(request);\n         return this;\n      }\n      \n      @Override\n      protected GeneratedHttpRequest getRequest() {\n         return (GeneratedHttpRequest) super.getRequest();\n      }\n   }\n\n   @Override\n   public ParseSax<T> setContext(HttpRequest request) {\n      handler.setContext(request);\n      this.request = request;\n      return this;\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/functions/ParseURIFromListOrLocationHeaderIf20x.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.functions;\n\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.common.net.HttpHeaders.CONTENT_TYPE;\nimport static com.google.common.net.HttpHeaders.LOCATION;\nimport static org.jclouds.http.HttpUtils.releasePayload;\n\nimport java.io.IOException;\nimport java.net.URI;\n\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.http.Uris;\nimport org.jclouds.rest.InvocationContext;\nimport org.jclouds.util.Strings2;\n\nimport com.google.common.base.Function;\n\n/**\n * parses a single URI from a list\n */\npublic class ParseURIFromListOrLocationHeaderIf20x implements Function<HttpResponse, URI>,\n      InvocationContext<ParseURIFromListOrLocationHeaderIf20x> {\n\n   protected HttpRequest request;\n\n   public URI apply(HttpResponse from) {\n      if (from.getStatusCode() > 206)\n         throw new HttpException(String.format(\"Unhandled status code  - %1$s\", from));\n      if (\"text/uri-list\".equals(from.getFirstHeaderOrNull(CONTENT_TYPE))) {\n         try {\n            if (from.getPayload().getInput() == null)\n               throw new HttpResponseException(\"no content\", null, from);\n            String toParse = Strings2.toStringAndClose(from.getPayload().getInput());\n            return URI.create(toParse.trim());\n         } catch (IOException e) {\n            throw new HttpResponseException(\"couldn't parse uri from content\", null, from, e);\n         } finally {\n            releasePayload(from);\n         }\n      } else {\n         releasePayload(from);\n         String location = from.getFirstHeaderOrNull(LOCATION);\n         if (location == null)\n            location = from.getFirstHeaderOrNull(\"location\");\n         if (location != null) {\n            URI locationUri = URI.create(location);\n            if (locationUri.getHost() != null)\n               return locationUri;\n            checkState(request != null, \"request should have been initialized\");\n            if (!location.startsWith(\"/\"))\n               location = \"/\" + location;\n            locationUri = URI.create(location);\n            return Uris.uriBuilder(request.getEndpoint()).path(locationUri.getPath()).query(locationUri.getQuery()).build();\n         } else {\n            return null;\n         }\n\n      }\n   }\n\n   @Override\n   public ParseURIFromListOrLocationHeaderIf20x setContext(HttpRequest request) {\n      this.request = request;\n      return this;\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/functions/ParseXMLWithJAXB.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.functions;\n\nimport static org.jclouds.http.HttpUtils.releasePayload;\n\nimport java.io.IOException;\nimport java.io.InputStream;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.util.Strings2;\nimport org.jclouds.xml.XMLParser;\n\nimport com.google.common.base.Function;\nimport com.google.inject.TypeLiteral;\n\n/**\n * This object will parse the body of an HttpResponse and return the result of\n * type <T> back to the caller.\n * <p>\n * {@link JAXBContext} works with {@link Class} objects instead of {@link Type}.\n * This could be a limitation if we are trying to parse typed collections of\n * objects. However, when using JAXB we expect to have well formed XML documents\n * with one single root element, so the objects to parse should not be\n * collections but objects that wrap collections of elements, and that should\n * work fine.\n */\n@Singleton\npublic class ParseXMLWithJAXB<T> implements Function<HttpResponse, T> {\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   protected XMLParser xml;\n\n   protected final TypeLiteral<T> type;\n\n   @Inject\n   public ParseXMLWithJAXB(final XMLParser xml, final TypeLiteral<T> type) {\n      this.xml = xml;\n      this.type = type;\n   }\n\n   @Override\n   public T apply(final HttpResponse from) {\n      InputStream xml = from.getPayload().getInput();\n      try {\n         return apply(xml);\n      } catch (Exception e) {\n         StringBuilder message = new StringBuilder();\n         message.append(\"Error parsing input\");\n         logger.error(e, message.toString());\n         throw new HttpResponseException(message.toString() + \"\\n\" + from, null, from, e);\n      } finally {\n         releasePayload(from);\n      }\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   public T apply(final InputStream stream) throws IOException {\n      return (T) apply(stream, type.getRawType());\n   }\n\n   public <V> V apply(final InputStream stream, final Class<V> type) throws IOException {\n      try {\n         String str = Strings2.toStringAndClose(stream);\n         return xml.fromXML(str, type);\n      } finally {\n         if (stream != null) {\n            stream.close();\n         }\n      }\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/functions/ReleasePayloadAndReturn.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.functions;\n\nimport static org.jclouds.http.HttpUtils.releasePayload;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class ReleasePayloadAndReturn implements Function<HttpResponse, Void> {\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   public Void apply(HttpResponse from) {\n      releasePayload(from);\n      return null;\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/functions/ReturnInputStream.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.functions;\n\nimport java.io.InputStream;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpResponse;\n\nimport com.google.common.base.Function;\n\n/**\n * Simply returns the InputStream of the response\n */\n@Singleton\npublic class ReturnInputStream implements Function<HttpResponse, InputStream> {\n\n   public InputStream apply(HttpResponse from) {\n      return from.getPayload() != null ? from.getPayload().getInput() : null;\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/functions/ReturnStringIf2xx.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.functions;\n\nimport static org.jclouds.http.HttpUtils.releasePayload;\n\nimport java.io.IOException;\nimport java.io.InputStream;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.util.Strings2;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class ReturnStringIf2xx implements Function<HttpResponse, String> {\n\n   public String apply(HttpResponse from) {\n      if (from.getPayload() == null)\n         return null;\n      try {\n         if (from.getStatusCode() >= 200) {\n            InputStream payload = from.getPayload().getInput();\n            String toReturn = null;\n            try {\n               toReturn = Strings2.toStringAndClose(payload);\n            } catch (IOException e) {\n               throw new HttpException(String.format(\n                        \"Couldn't receive response %1$s, payload: %2$s \", from, toReturn), e);\n            }\n            return toReturn;\n         } else {\n            throw new HttpException(String.format(\"Unhandled status code  - %1$s\", from));\n         }\n      } finally {\n         releasePayload(from);\n      }\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/functions/ReturnTrueIf201.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.functions;\n\nimport static org.jclouds.http.HttpUtils.releasePayload;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpResponse;\n\nimport com.google.common.base.Function;\n\n/**\n * Parses the status code of an HTTPResponse and returns True if it is 201.\n * False otherwise.\n */\n@Singleton\npublic class ReturnTrueIf201 implements Function<HttpResponse, Boolean> {\n   @Override\n   public Boolean apply(HttpResponse from) {\n      releasePayload(from);\n      return from.getStatusCode() == 201;\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/functions/ReturnTrueIf2xx.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.functions;\n\nimport static org.jclouds.http.HttpUtils.releasePayload;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpResponse;\n\nimport com.google.common.base.Function;\n\n/**\n * Simply returns true when the http response code is in the range 200-299.\n */\n@Singleton\npublic class ReturnTrueIf2xx implements Function<HttpResponse, Boolean> {\n\n   public Boolean apply(HttpResponse from) {\n      releasePayload(from);\n      int code = from.getStatusCode();\n      if (code >= 300 || code < 200) {\n         throw new IllegalStateException(\"incorrect code for this operation: \" + from);\n      }\n      return true;\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/functions/UnwrapOnlyJsonValue.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.functions;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpResponse;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.Iterables;\n\n@Singleton\npublic class UnwrapOnlyJsonValue<T> implements Function<HttpResponse, T> {\n\n   private final ParseJson<Map<String, T>> json;\n\n   @Inject\n   UnwrapOnlyJsonValue(ParseJson<Map<String, T>> json) {\n      this.json = json;\n   }\n\n   @Override\n   public T apply(HttpResponse arg0) {\n      Map<String, T> map = json.apply(arg0);\n      return Iterables.getOnlyElement(map.values());\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/functions/UnwrapOnlyJsonValueInSet.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.functions;\n\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpResponse;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.Iterables;\n\n@Singleton\npublic class UnwrapOnlyJsonValueInSet<T> implements Function<HttpResponse, T> {\n\n   private final UnwrapOnlyJsonValue<Set<T>> json;\n\n   @Inject\n   UnwrapOnlyJsonValueInSet(UnwrapOnlyJsonValue<Set<T>> json) {\n      this.json = json;\n   }\n\n   @Override\n   public T apply(HttpResponse arg0) {\n      Set<T> set = json.apply(arg0);\n      if (set == null || set.isEmpty())\n         return null;\n      return Iterables.getOnlyElement(set);\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/functions/config/SaxParserModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.functions.config;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\nimport javax.xml.parsers.SAXParser;\nimport javax.xml.parsers.SAXParserFactory;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.http.functions.ParseSax.HandlerWithResult;\nimport org.xml.sax.XMLReader;\n\nimport com.google.common.base.Throwables;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Injector;\nimport com.google.inject.Provides;\nimport com.google.inject.Scopes;\n\n/**\n * Contains logic for parsing objects from Strings.\n */\npublic class SaxParserModule extends AbstractModule {\n\n   protected void configure() {\n      bind(ParseSax.Factory.class).to(Factory.class).in(Scopes.SINGLETON);\n   }\n\n   static class Factory implements ParseSax.Factory {\n      private final SAXParserFactory factory;\n      private final Injector i;\n\n      @Inject\n      Factory(SAXParserFactory factory, Injector i) {\n         this.factory = factory;\n         this.i = i;\n      }\n\n      public <T> ParseSax<T> create(HandlerWithResult<T> handler) {\n         SAXParser saxParser;\n         try {\n            saxParser = factory.newSAXParser();\n            XMLReader parser = saxParser.getXMLReader();\n            // TODO: switch to @AssistedInject\n            ParseSax<T> returnVal = new ParseSax<T>(parser, handler);\n            i.injectMembers(returnVal);\n            return returnVal;\n         } catch (Exception e) {\n            throw Throwables.propagate(e);\n         }\n\n      }\n   }\n\n   @Provides\n   @Singleton\n   final SAXParserFactory provideSAXParserFactory() {\n      SAXParserFactory factory = SAXParserFactory.newInstance();\n      factory.setNamespaceAware(false);\n      factory.setValidating(false);\n      return factory;\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/handlers/BackoffLimitedRetryHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.handlers;\n\nimport static java.lang.Math.max;\n\nimport java.io.IOException;\nimport java.util.Random;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Constants;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpRetryHandler;\nimport org.jclouds.http.IOExceptionRetryHandler;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Throwables;\nimport com.google.inject.Inject;\n\n/**\n * Allow replayable request to be retried a limited number of times, and impose an exponential\n * back-off delay before returning.\n * <p>\n * The back-off delay grows rapidly according to the formula\n * <code>50 * (<i>{@link TransformingHttpCommand#getFailureCount()}</i> ^ 2)</code>. For example:\n * <table>\n * <tr>\n * <th>Number of Attempts</th>\n * <th>Delay in milliseconds</th>\n * </tr>\n * <tr>\n * <td>1</td>\n * <td>50</td>\n * </tr>\n * <tr>\n * <td>2</td>\n * <td>200</td>\n * </tr>\n * <tr>\n * <td>3</td>\n * <td>450</td>\n * </tr>\n * <tr>\n * <td>4</td>\n * <td>800</td>\n * </tr>\n * <tr>\n * <td>5</td>\n * <td>1250</td>\n * </tr>\n * </table>\n * <p>\n * This implementation has two side-effects. It increments the command's failure count with\n * {@link TransformingHttpCommand#incrementFailureCount()}, because this failure count value is used\n * to determine how many times the command has already been tried. It also closes the response's\n * content input stream to ensure connections are cleaned up.\n */\n@Singleton\npublic class BackoffLimitedRetryHandler implements HttpRetryHandler, IOExceptionRetryHandler {\n\n   public static final BackoffLimitedRetryHandler INSTANCE = new BackoffLimitedRetryHandler();\n\n   @Inject(optional = true)\n   @Named(Constants.PROPERTY_MAX_RETRIES)\n   private int retryCountLimit = 5;\n\n   @Inject(optional = true)\n   @Named(Constants.PROPERTY_RETRY_DELAY_START)\n   private long delayStart = 50L;\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   public boolean shouldRetryRequest(HttpCommand command, IOException error) {\n      return ifReplayableBackoffAndReturnTrue(command);\n   }\n\n   public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) {\n      return ifReplayableBackoffAndReturnTrue(command);\n   }\n\n   private boolean ifReplayableBackoffAndReturnTrue(HttpCommand command) {\n      command.incrementFailureCount();\n\n      if (!command.isReplayable()) {\n         logger.error(\"Cannot retry after server error, command is not replayable: %1$s\", command);\n         return false;\n      } else if (command.getFailureCount() > retryCountLimit) {\n         logger.error(\"Cannot retry after server error, command has exceeded retry limit %1$d: %2$s\", retryCountLimit,\n                  command);\n         return false;\n      } else {\n         imposeBackoffExponentialDelay(command.getFailureCount(), \"server error: \" + command.toString());\n         return true;\n      }\n   }\n\n   public void imposeBackoffExponentialDelay(int failureCount, String commandDescription) {\n      imposeBackoffExponentialDelay(delayStart, 2, failureCount, retryCountLimit, commandDescription);\n   }\n\n   public void imposeBackoffExponentialDelay(long period, int pow, int failureCount, int max, String commandDescription) {\n      imposeBackoffExponentialDelay(period, period * 10L, pow, failureCount, max, commandDescription);\n   }\n\n   public void imposeBackoffExponentialDelay(long period, long maxPeriod, int pow, int failureCount, int max,\n            String commandDescription) {\n      if (period == 0) {\n         // Essentially disables the exponential backoff\n         logger.debug(\"Retry %d/%d: delaying for %d ms: %s\", failureCount, max, 0, commandDescription);\n         return;\n      }\n      long delayMs = (long) (period * Math.pow(failureCount, pow));\n      // Add random delay to avoid thundering herd problem when multiple\n      // simultaneous failed requests retry after sleeping for the same delay.\n      // Throws an exception for a value of 0\n      delayMs += new Random().nextInt((int) (max(delayMs / 10, 1) ));\n      delayMs = delayMs > maxPeriod ? maxPeriod : delayMs;\n      logger.debug(\"Retry %d/%d: delaying for %d ms: %s\", failureCount, max, delayMs, commandDescription);\n      try {\n         Thread.sleep(delayMs);\n      } catch (InterruptedException e) {\n         Throwables.propagate(e);\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/handlers/CloseContentAndSetExceptionErrorHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.handlers;\n\nimport static org.jclouds.http.HttpUtils.releasePayload;\n\nimport java.io.IOException;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.util.Strings2;\n\n@Singleton\npublic class CloseContentAndSetExceptionErrorHandler implements HttpErrorHandler {\n\n   public void handleError(HttpCommand command, HttpResponse from) {\n      String content;\n      try {\n         content = from.getPayload() != null ? Strings2.toStringAndClose(from.getPayload().openStream()) : null;\n         command.setException(new HttpResponseException(command, from, content));\n      } catch (IOException e) {\n         command.setException(new HttpResponseException(command, from));\n      } finally {\n         releasePayload(from);\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/handlers/DelegatingErrorHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.handlers;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.annotation.ClientError;\nimport org.jclouds.http.annotation.Redirection;\nimport org.jclouds.http.annotation.ServerError;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.inject.Inject;\n\n/**\n * Delegates to {@link HttpErrorHandler HttpErrorHandlers} who are annotated according to the\n * response codes they relate to.\n */\n@Singleton\npublic class DelegatingErrorHandler implements HttpErrorHandler {\n\n   @VisibleForTesting\n   @Inject(optional = true)\n   @Redirection\n   HttpErrorHandler redirectionHandler;\n\n   @VisibleForTesting\n   @Inject(optional = true)\n   @ClientError\n   HttpErrorHandler clientErrorHandler;\n\n   @VisibleForTesting\n   @Inject(optional = true)\n   @ServerError\n   HttpErrorHandler serverErrorHandler;\n\n   @Inject\n   DelegatingErrorHandler() {\n      this.redirectionHandler = new CloseContentAndSetExceptionErrorHandler();\n      this.clientErrorHandler = redirectionHandler;\n      this.serverErrorHandler = redirectionHandler;\n   }\n\n   public void handleError(HttpCommand command, HttpResponse response) {\n      int statusCode = response.getStatusCode();\n      if (statusCode >= 300 && statusCode < 400) {\n         getRedirectionHandler().handleError(command, response);\n      } else if (statusCode >= 400 && statusCode < 500) {\n         getClientErrorHandler().handleError(command, response);\n      } else if (statusCode >= 500) {\n         getServerErrorHandler().handleError(command, response);\n      }\n   }\n\n   public HttpErrorHandler getRedirectionHandler() {\n      return redirectionHandler;\n   }\n\n   public HttpErrorHandler getClientErrorHandler() {\n      return clientErrorHandler;\n   }\n\n   public HttpErrorHandler getServerErrorHandler() {\n      return serverErrorHandler;\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/handlers/DelegatingRetryHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.handlers;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpRetryHandler;\nimport org.jclouds.http.annotation.ClientError;\nimport org.jclouds.http.annotation.Redirection;\nimport org.jclouds.http.annotation.ServerError;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.inject.Inject;\n\n/**\n * Delegates to {@link HttpRetryHandler HttpRetryHandlers} who are annotated according to the\n * response codes they relate to.\n */\n@Singleton\npublic class DelegatingRetryHandler implements HttpRetryHandler {\n\n   @VisibleForTesting\n   @Inject(optional = true)\n   @Redirection\n   HttpRetryHandler redirectionRetryHandler;\n\n   @VisibleForTesting\n   @Inject(optional = true)\n   @ClientError\n   HttpRetryHandler clientErrorRetryHandler;\n\n   @VisibleForTesting\n   @Inject(optional = true)\n   @ServerError\n   HttpRetryHandler serverErrorRetryHandler;\n\n   @Inject\n   public DelegatingRetryHandler(BackoffLimitedRetryHandler backOff,\n            RedirectionRetryHandler redirectionRetryHandler) {\n      this.serverErrorRetryHandler = backOff;\n      this.redirectionRetryHandler = redirectionRetryHandler;\n      this.clientErrorRetryHandler = HttpRetryHandler.NEVER_RETRY;\n   }\n\n   public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) {\n      int statusCode = response.getStatusCode();\n      boolean retryRequest = false;\n      if (statusCode >= 300 && statusCode < 400) {\n         retryRequest = redirectionRetryHandler.shouldRetryRequest(command, response);\n      } else if (statusCode >= 400 && statusCode < 500) {\n         retryRequest = clientErrorRetryHandler.shouldRetryRequest(command, response);\n      } else if (statusCode >= 500) {\n         retryRequest = serverErrorRetryHandler.shouldRetryRequest(command, response);\n      }\n      return retryRequest;\n   }\n\n   public HttpRetryHandler getRedirectionRetryHandler() {\n      return redirectionRetryHandler;\n   }\n\n   public HttpRetryHandler getClientErrorRetryHandler() {\n      return clientErrorRetryHandler;\n   }\n\n   public HttpRetryHandler getServerErrorRetryHandler() {\n      return serverErrorRetryHandler;\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/handlers/RateLimitRetryHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.handlers;\n\nimport static org.jclouds.Constants.PROPERTY_MAX_RATE_LIMIT_WAIT;\nimport static org.jclouds.Constants.PROPERTY_MAX_RETRIES;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\n\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpRetryHandler;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Optional;\nimport com.google.inject.Inject;\n\n/**\n * Retry handler that takes into account the provider rate limit and delays the\n * requests until they are known to succeed.\n */\n@Beta\npublic abstract class RateLimitRetryHandler implements HttpRetryHandler {\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   @Inject(optional = true)\n   @Named(PROPERTY_MAX_RETRIES)\n   private int retryCountLimit = 5;\n\n   @Inject(optional = true)\n   @Named(PROPERTY_MAX_RATE_LIMIT_WAIT)\n   private int maxRateLimitWait = 2 * 60 * 1000;\n\n   /**\n    * Returns the response status that will be considered a rate limit error.\n    * <p>\n    * Providers can override this to customize which responses are retried.\n    */\n   protected int rateLimitErrorStatus() {\n      return 429;\n   }\n\n   /**\n    * Compute the number of milliseconds that must pass until a request can be\n    * performed.\n    * \n    * @param command The command being executed.\n    * @param response The rate-limit error response.\n    * @return The number of milliseconds to wait for an available request, if taht information is available.\n    */\n   protected abstract Optional<Long> millisToNextAvailableRequest(final HttpCommand command, final HttpResponse response);\n\n   @Override\n   public boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response) {\n      command.incrementFailureCount();\n\n      // Do not retry client errors that are not rate limit errors\n      if (response.getStatusCode() != rateLimitErrorStatus()) {\n         return false;\n      } else if (!command.isReplayable()) {\n         logger.error(\"Cannot retry after rate limit error, command is not replayable: %1$s\", command);\n         return false;\n      } else if (command.getFailureCount() > retryCountLimit) {\n         logger.error(\"Cannot retry after rate limit error, command has exceeded retry limit %1$d: %2$s\",\n               retryCountLimit, command);\n         return false;\n      } else {\n         return delayRequestUntilAllowed(command, response);\n      }\n   }\n\n   protected boolean delayRequestUntilAllowed(final HttpCommand command, final HttpResponse response) {\n      Optional<Long> millisToNextAvailableRequest = millisToNextAvailableRequest(command, response);\n      if (!millisToNextAvailableRequest.isPresent()) {\n         logger.error(\"Cannot retry after rate limit error, no retry information provided in the response\");\n         return false;\n      }\n\n      long waitPeriod = millisToNextAvailableRequest.get();\n      if (waitPeriod > 0L) {\n         if (waitPeriod > maxRateLimitWait) {\n            logger.error(\"Max wait for rate limited requests is %sms but need to wait %sms, aborting\",\n                  maxRateLimitWait, waitPeriod);\n            return false;\n         }\n\n         try {\n            logger.debug(\"Waiting %sms before retrying, as defined by the rate limit\", waitPeriod);\n            // Do not use Uninterrumpibles or similar, to let the jclouds\n            // tiemout configuration interrupt this thread\n            Thread.sleep(waitPeriod);\n         } catch (InterruptedException ex) {\n            // If the request is being executed and has a timeout configured,\n            // the thread may be interrupted when the timeout is reached.\n            logger.error(\"Request execution was interrupted, aborting\");\n            Thread.currentThread().interrupt();\n            return false;\n         }\n      }\n\n      return true;\n   }\n\n   public int getRetryCountLimit() {\n      return retryCountLimit;\n   }\n\n   public int getMaxRateLimitWait() {\n      return maxRateLimitWait;\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/handlers/RedirectionRetryHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.handlers;\n\nimport static com.google.common.net.HttpHeaders.HOST;\nimport static com.google.common.net.HttpHeaders.LOCATION;\nimport static org.jclouds.http.HttpUtils.closeClientButKeepContentStream;\nimport static org.jclouds.http.Uris.uriBuilder;\n\nimport java.net.URI;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Constants;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpRetryHandler;\nimport org.jclouds.logging.Logger;\n\nimport com.google.inject.Inject;\n\n/**\n * Handles Retryable responses with error codes in the 3xx range, backing off\n * when redirecting to itself.\n */\n@Singleton\npublic class RedirectionRetryHandler implements HttpRetryHandler {\n   @Inject(optional = true)\n   @Named(Constants.PROPERTY_MAX_REDIRECTS)\n   protected int retryCountLimit = 5;\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   protected final BackoffLimitedRetryHandler backoffHandler;\n\n   @Inject\n   protected RedirectionRetryHandler(BackoffLimitedRetryHandler backoffHandler) {\n      this.backoffHandler = backoffHandler;\n   }\n\n   public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) {\n      closeClientButKeepContentStream(response);\n      if (!command.isReplayable()) {\n         logger.error(\"Cannot retry after redirect, command is not replayable: %s\", command);\n         return false;\n      }\n      if (command.incrementRedirectCount() > retryCountLimit) {\n         logger.error(\"Cannot retry after redirect, command exceeded retry limit %d: %s\", retryCountLimit, command);\n         return false;\n      }\n      String location = response.getFirstHeaderOrNull(LOCATION);\n      if (location == null) {\n         logger.error(\"Cannot retry after redirect, no host header: %s\", command);\n         return false;\n      }\n      HttpRequest current = command.getCurrentRequest();\n      URI redirect = URI.create(location);\n      if (!redirect.isAbsolute()) {\n         if (redirect.getPath() == null) {\n            logger.error(\"Cannot retry after redirect, no path in location header %s\", command);\n            return false;\n         }\n         redirect = uriBuilder(current.getEndpoint()).path(redirect.getPath()).query(redirect.getQuery()).build();\n      }\n      if (redirect.equals(current.getEndpoint())) {\n         backoffHandler.imposeBackoffExponentialDelay(command.getRedirectCount(), \"redirect: \" + command.toString());\n      } else if (current.getFirstHeaderOrNull(HOST) != null && redirect.getHost() != null) {\n         String host = redirect.getPort() > 0 ? redirect.getHost() + \":\" + redirect.getPort() : redirect.getHost();\n         command.setCurrentRequest(current.toBuilder().replaceHeader(HOST, host).endpoint(redirect).build());\n      } else {\n         command.setCurrentRequest(current.toBuilder().endpoint(redirect).build());\n      }\n      return true;\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/internal/BaseHttpCommandExecutorService.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Throwables.propagate;\nimport static org.jclouds.Constants.PROPERTY_IDEMPOTENT_METHODS;\nimport static org.jclouds.http.HttpUtils.checkRequestHasContentLengthOrChunkedEncoding;\nimport static org.jclouds.http.HttpUtils.releasePayload;\nimport static org.jclouds.http.HttpUtils.wirePayloadIfEnabled;\nimport static org.jclouds.util.Throwables2.getFirstThrowableOfType;\n\nimport java.io.IOException;\nimport java.net.ProtocolException;\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\n\nimport org.jclouds.Constants;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpCommandExecutorService;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpRequestFilter;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.http.HttpUtils;\nimport org.jclouds.http.IOExceptionRetryHandler;\nimport org.jclouds.http.handlers.DelegatingErrorHandler;\nimport org.jclouds.http.handlers.DelegatingRetryHandler;\nimport org.jclouds.io.ContentMetadataCodec;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.collect.ImmutableSet;\n\npublic abstract class BaseHttpCommandExecutorService<Q> implements HttpCommandExecutorService {\n   protected final HttpUtils utils;\n   protected final ContentMetadataCodec contentMetadataCodec;\n\n   protected final DelegatingRetryHandler retryHandler;\n   protected final IOExceptionRetryHandler ioRetryHandler;\n   protected final DelegatingErrorHandler errorHandler;\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n   @Resource\n   @Named(Constants.LOGGER_HTTP_HEADERS)\n   protected Logger headerLog = Logger.NULL;\n\n   protected final HttpWire wire;\n\n   private final Set<String> idempotentMethods;\n\n   protected BaseHttpCommandExecutorService(HttpUtils utils, ContentMetadataCodec contentMetadataCodec,\n         DelegatingRetryHandler retryHandler, IOExceptionRetryHandler ioRetryHandler,\n         DelegatingErrorHandler errorHandler, HttpWire wire,\n         @Named(PROPERTY_IDEMPOTENT_METHODS) String idempotentMethods) {\n      this.utils = checkNotNull(utils, \"utils\");\n      this.contentMetadataCodec = checkNotNull(contentMetadataCodec, \"contentMetadataCodec\");\n      this.retryHandler = checkNotNull(retryHandler, \"retryHandler\");\n      this.ioRetryHandler = checkNotNull(ioRetryHandler, \"ioRetryHandler\");\n      this.errorHandler = checkNotNull(errorHandler, \"errorHandler\");\n      this.wire = checkNotNull(wire, \"wire\");\n      this.idempotentMethods = ImmutableSet.copyOf(idempotentMethods.split(\",\"));\n   }\n\n   @Override\n   public HttpResponse invoke(HttpCommand command) {\n      HttpResponse response = null;\n      for (;;) {\n         HttpRequest request = command.getCurrentRequest();\n         Q nativeRequest = null;\n         try {\n            for (HttpRequestFilter filter : request.getFilters()) {\n               request = filter.filter(request);\n            }\n            checkRequestHasContentLengthOrChunkedEncoding(request,\n                  \"After filtering, the request has neither chunked encoding nor content length: \" + request);\n            logger.debug(\"Sending request %s: %s\", request.hashCode(), request.getRequestLine());\n            wirePayloadIfEnabled(wire, request);\n            utils.logRequest(headerLog, request, \">>\");\n            nativeRequest = convert(request);\n            response = invoke(nativeRequest);\n\n            logger.debug(\"Receiving response %s: %s\", request.hashCode(), response.getStatusLine());\n            utils.logResponse(headerLog, response, \"<<\");\n            if (response.getPayload() != null && wire.enabled())\n               wire.input(response);\n            nativeRequest = null; // response took ownership of streams\n            int statusCode = response.getStatusCode();\n            if (statusCode >= 300) {\n               if (shouldContinue(command, response))\n                  continue;\n               else\n                  break;\n            } else {\n               break;\n            }\n         } catch (Exception e) {\n            IOException ioe = getFirstThrowableOfType(e, IOException.class);\n            if (ioe != null && shouldContinue(command, ioe)) {\n               continue;\n            }\n            command.setException(new HttpResponseException(e.getMessage() + \" connecting to \"\n                  + command.getCurrentRequest().getRequestLine(), command, null, e));\n            break;\n\n         } finally {\n            cleanup(nativeRequest);\n         }\n      }\n      if (command.getException() != null)\n         throw propagate(command.getException());\n      return response;\n   }\n\n   @VisibleForTesting\n   boolean shouldContinue(HttpCommand command, HttpResponse response) {\n      boolean shouldContinue = false;\n      if (retryHandler.shouldRetryRequest(command, response)) {\n         shouldContinue = true;\n      } else {\n         errorHandler.handleError(command, response);\n      }\n      // At this point we are going to send a new request or we have just handled the error, so\n      // we should make sure that any open stream is closed.\n      releasePayload(response);\n      return shouldContinue;\n   }\n\n   boolean shouldContinue(HttpCommand command, IOException response) {\n      // Even though Java does not want to handle it this way,\n      // treat a Protocol Exception on PUT with 100-Continue as a case of Unauthorized (and attempt to retry)\n      if (command.getCurrentRequest().getMethod().equals(\"PUT\")\n            && command.getCurrentRequest().getHeaders().containsEntry(\"Expect\", \"100-continue\")\n            && response instanceof ProtocolException\n            && response.getMessage().equals(\"Server rejected operation\")\n            ) {\n         logger.debug(\"Caught a protocol exception on a 100-continue PUT request. Attempting to retry.\");\n         return isIdempotent(command) && retryHandler.shouldRetryRequest(command, HttpResponse.builder().statusCode(401).message(\"Unauthorized\").build());\n      }\n      return isIdempotent(command) && ioRetryHandler.shouldRetryRequest(command, response);\n   }\n\n   private boolean isIdempotent(HttpCommand command) {\n      String method = command.getCurrentRequest().getMethod();\n      if (!idempotentMethods.contains(method)) {\n         logger.error(\"Command not considered safe to retry because request method is %1$s: %2$s\", method, command);\n         return false;\n      } else {\n         return true;\n      }\n   }\n\n   protected abstract Q convert(HttpRequest request) throws IOException, InterruptedException;\n\n   protected abstract HttpResponse invoke(Q nativeRequest) throws IOException, InterruptedException;\n\n   protected abstract void cleanup(Q nativeRequest);\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/internal/HttpWire.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.internal;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.inject.Inject;\nimport org.jclouds.Constants;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.logging.internal.Wire;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\n\npublic class HttpWire extends Wire {\n\n   @Resource\n   @Named(Constants.LOGGER_HTTP_WIRE)\n   Logger wireLog = Logger.NULL;\n\n   @VisibleForTesting\n   @Inject(optional = true)\n   @Named(Constants.PROPERTY_LOGGER_WIRE_LOG_SENSITIVE_INFO)\n   boolean logSensitiveInformation = false;\n\n   public Logger getWireLog() {\n      return wireLog;\n   }\n\n   @Override\n   protected boolean isLogSensitiveInformation() {\n      return logSensitiveInformation;\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/internal/JavaUrlHttpCommandExecutorService.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Throwables.propagate;\nimport static com.google.common.net.HttpHeaders.CONTENT_LENGTH;\nimport static com.google.common.net.HttpHeaders.HOST;\nimport static com.google.common.net.HttpHeaders.USER_AGENT;\nimport static org.jclouds.Constants.PROPERTY_IDEMPOTENT_METHODS;\nimport static org.jclouds.Constants.PROPERTY_OUTPUT_SOCKET_BUFFER_SIZE;\nimport static org.jclouds.Constants.PROPERTY_USER_AGENT;\nimport static org.jclouds.http.HttpUtils.filterOutContentHeaders;\nimport static org.jclouds.io.Payloads.newInputStreamPayload;\nimport static org.jclouds.util.Closeables2.closeQuietly;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.lang.reflect.Field;\nimport java.net.HttpURLConnection;\nimport java.net.ProtocolException;\nimport java.net.Proxy;\nimport java.net.URI;\nimport java.net.URL;\nimport java.util.List;\nimport java.util.Map;\n\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\nimport javax.net.ssl.HostnameVerifier;\nimport javax.net.ssl.HttpsURLConnection;\nimport javax.net.ssl.SSLContext;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpUtils;\nimport org.jclouds.http.IOExceptionRetryHandler;\nimport org.jclouds.http.handlers.DelegatingErrorHandler;\nimport org.jclouds.http.handlers.DelegatingRetryHandler;\nimport org.jclouds.io.ByteStreams2;\nimport org.jclouds.io.ContentMetadataCodec;\nimport org.jclouds.io.MutableContentMetadata;\nimport org.jclouds.io.Payload;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableMultimap.Builder;\nimport com.google.common.io.CountingOutputStream;\nimport com.google.inject.Inject;\n\n@Singleton\npublic class JavaUrlHttpCommandExecutorService extends BaseHttpCommandExecutorService<HttpURLConnection> {\n   protected final Supplier<SSLContext> untrustedSSLContextProvider;\n   protected final Function<URI, Proxy> proxyForURI;\n   protected final HostnameVerifier verifier;\n   @Inject(optional = true)\n   protected Supplier<SSLContext> sslContextSupplier;\n   protected final int outputSocketBufferSize;\n   protected final String userAgent;\n\n   @Inject\n   public JavaUrlHttpCommandExecutorService(HttpUtils utils, ContentMetadataCodec contentMetadataCodec,\n         DelegatingRetryHandler retryHandler, IOExceptionRetryHandler ioRetryHandler,\n         DelegatingErrorHandler errorHandler, HttpWire wire, @Named(\"untrusted\") HostnameVerifier verifier,\n         @Named(\"untrusted\") Supplier<SSLContext> untrustedSSLContextProvider, Function<URI, Proxy> proxyForURI,\n         @Named(PROPERTY_IDEMPOTENT_METHODS) String idempotentMethods,\n         @Named(PROPERTY_OUTPUT_SOCKET_BUFFER_SIZE) int outputSocketBufferSize,\n         @Named(PROPERTY_USER_AGENT) String userAgent) {\n      super(utils, contentMetadataCodec, retryHandler, ioRetryHandler, errorHandler, wire, idempotentMethods);\n      if (utils.getMaxConnections() > 0) {\n         System.setProperty(\"http.maxConnections\", String.valueOf(checkNotNull(utils, \"utils\").getMaxConnections()));\n      }\n      this.untrustedSSLContextProvider = checkNotNull(untrustedSSLContextProvider, \"untrustedSSLContextProvider\");\n      this.verifier = checkNotNull(verifier, \"verifier\");\n      this.proxyForURI = checkNotNull(proxyForURI, \"proxyForURI\");\n      this.userAgent = userAgent;\n      this.outputSocketBufferSize = outputSocketBufferSize;\n   }\n\n   @Override\n   protected HttpResponse invoke(HttpURLConnection connection) throws IOException, InterruptedException {\n      HttpResponse.Builder<?> builder = HttpResponse.builder();\n      InputStream in = null;\n      try {\n         in = connection.getInputStream();\n      } catch (IOException e) {\n         in = connection.getErrorStream();\n      } catch (RuntimeException e) {\n         closeQuietly(in);\n         throw e;\n      }\n\n      int responseCode = connection.getResponseCode();\n      if (responseCode == 204) {\n         closeQuietly(in);\n         in = null;\n      }\n      builder.statusCode(responseCode);\n      builder.message(connection.getResponseMessage());\n\n      Builder<String, String> headerBuilder = ImmutableMultimap.builder();\n      for (Map.Entry<String, List<String>> entry : connection.getHeaderFields().entrySet()) {\n         String header = entry.getKey();\n         // HTTP message comes back as a header without a key\n         if (header != null)\n            headerBuilder.putAll(header, entry.getValue());\n      }\n      ImmutableMultimap<String, String> headers = headerBuilder.build();\n      if (in != null) {\n         Payload payload = newInputStreamPayload(in);\n         contentMetadataCodec.fromHeaders(payload.getContentMetadata(), headers);\n         builder.payload(payload);\n      }\n      builder.headers(filterOutContentHeaders(headers));\n      return builder.build();\n   }\n\n   @Override\n   protected HttpURLConnection convert(HttpRequest request) throws IOException, InterruptedException {\n      boolean chunked = \"chunked\".equals(request.getFirstHeaderOrNull(\"Transfer-Encoding\"));\n\n      HttpURLConnection connection = initConnection(request);\n      connection.setConnectTimeout(utils.getConnectionTimeout());\n      connection.setReadTimeout(utils.getSocketOpenTimeout());\n      connection.setAllowUserInteraction(false);\n      // do not follow redirects since https redirects don't work properly\n      // ex. Caused by: java.io.IOException: HTTPS hostname wrong: should be\n      // <adriancole.s3int0.s3-external-3.amazonaws.com>\n      connection.setInstanceFollowRedirects(false);\n\n      setRequestMethodBypassingJREMethodLimitation(connection, request.getMethod());\n      configureRequestHeaders(connection, request);\n\n      String host = request.getEndpoint().getHost();\n      if (request.getEndpoint().getPort() != -1) {\n         host += \":\" + request.getEndpoint().getPort();\n      }\n      connection.setRequestProperty(HOST, host);\n      if (connection.getRequestProperty(USER_AGENT) == null) {\n         connection.setRequestProperty(USER_AGENT, userAgent);\n      }\n      Payload payload = request.getPayload();\n      if (payload != null) {\n         MutableContentMetadata md = payload.getContentMetadata();\n         for (Map.Entry<String, String> entry : contentMetadataCodec.toHeaders(md).entries()) {\n            connection.setRequestProperty(entry.getKey(), entry.getValue());\n         }\n         if (chunked) {\n            connection.setChunkedStreamingMode(8196);\n            writePayloadToConnection(payload, \"streaming\", connection);\n         } else {\n            Long length = checkNotNull(md.getContentLength(), \"payload.getContentLength\");\n            if (length > 0) {\n               connection.setRequestProperty(CONTENT_LENGTH, length.toString());\n               if (length <= Integer.MAX_VALUE) {\n                  connection.setFixedLengthStreamingMode(length.intValue());\n               } else {\n                  setFixedLengthStreamingMode(connection, length);\n               }\n               writePayloadToConnection(payload, length, connection);\n            } else {\n               writeNothing(connection);\n            }\n         }\n      } else {\n         writeNothing(connection);\n      }\n      return connection;\n   }\n\n   /** Uses {@link HttpURLConnection#setFixedLengthStreamingMode(long)} if possible or throws if not. */\n   private static void setFixedLengthStreamingMode(HttpURLConnection connection, long length) {\n      try { // Not caching method as invocation is literally sending > 2GB, which means reflection isn't a limiter!\n         HttpURLConnection.class.getMethod(\"setFixedLengthStreamingMode\", long.class).invoke(connection, length);\n      } catch (Exception e) {\n         throw new IllegalArgumentException(\"Cannot transfer 2 GB or larger chunks due to JDK 1.6 limitations.\" +\n               \" Use chunked encoding or multi-part upload, if possible, or use a different http driver.\" +\n               \" For more information: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6755625\");\n      }\n   }\n\n   /**\n    * Creates and initializes the connection.\n    */\n   protected HttpURLConnection initConnection(HttpRequest request) throws IOException {\n      URL url = request.getEndpoint().toURL();\n      HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxyForURI.apply(request.getEndpoint()));\n      if (connection instanceof HttpsURLConnection) {\n         HttpsURLConnection sslCon = (HttpsURLConnection) connection;\n         if (utils.relaxHostname())\n            sslCon.setHostnameVerifier(verifier);\n         if (sslContextSupplier != null) {\n             // used for providers which e.g. use certs for authentication (like FGCP)\n             // Provider provides SSLContext impl (which inits context with key manager)\n             sslCon.setSSLSocketFactory(sslContextSupplier.get().getSocketFactory());\n         } else if (utils.trustAllCerts()) {\n             sslCon.setSSLSocketFactory(untrustedSSLContextProvider.get().getSocketFactory());\n         }\n      }\n      return connection;\n   }\n\n   /**\n    * Configure the HTTP request headers in the connection.\n    */\n   protected void configureRequestHeaders(HttpURLConnection connection, HttpRequest request) {\n      for (Map.Entry<String, String> entry : request.getHeaders().entries()) {\n         connection.setRequestProperty(entry.getKey(), entry.getValue());\n      }\n   }\n\n   /**\n    * Workaround for a bug in <code>HttpURLConnection.setRequestMethod(String)</code>\n    * The implementation of Sun Microsystems is throwing a <code>ProtocolException</code>\n    * when the method is other than the HTTP/1.1 default methods. So\n    * to use PATCH and others, we must apply this workaround.\n    *\n    * See issue http://java.net/jira/browse/JERSEY-639\n    */\n   private void setRequestMethodBypassingJREMethodLimitation(final HttpURLConnection httpURLConnection, final String method) {\n      try {\n         httpURLConnection.setRequestMethod(method);\n         // If the JRE does not support the given method, set it using reflection\n      } catch (final ProtocolException pe) {\n         Class<?> connectionClass = httpURLConnection.getClass();\n         Field delegateField = null;\n         try {\n            // SSL connections may have the HttpURLConnection wrapped inside\n            delegateField = connectionClass.getDeclaredField(\"delegate\");\n            // TODO: Fails on modern Java versions:\n            // Unable to make field private final sun.net.www.protocol.https.DelegateHttpsURLConnection sun.net.www.protocol.https.HttpsURLConnectionImpl.delegate accessible: module java.base does not \"opens sun.net.www.protocol.https\" to unnamed module @1ed4004b connecting to PATCH\n            delegateField.setAccessible(true);\n            HttpURLConnection delegateConnection = (HttpURLConnection) delegateField.get(httpURLConnection);\n            setRequestMethodBypassingJREMethodLimitation(delegateConnection, method);\n         } catch (NoSuchFieldException e) {\n            // Ignore for now, keep going\n         } catch (IllegalArgumentException e) {\n            logger.error(e, \"could not set request method: \", method);\n            propagate(e);\n         } catch (IllegalAccessException e) {\n            logger.error(e, \"could not set request method: \", method);\n            propagate(e);\n         }\n         try {\n            Field methodField = null;\n            while (connectionClass != null) {\n               try {\n                  methodField = connectionClass.getDeclaredField(\"method\");\n               } catch (NoSuchFieldException e) {\n                  connectionClass = connectionClass.getSuperclass();\n                  continue;\n               }\n               methodField.setAccessible(true);\n               methodField.set(httpURLConnection, method);\n               break;\n            }\n         } catch (final Exception e) {\n            logger.error(e, \"could not set request method: \", method);\n            propagate(e);\n         }\n      }\n   }\n\n   protected void writeNothing(HttpURLConnection connection) {\n      if (!HttpRequest.NON_PAYLOAD_METHODS.contains(connection.getRequestMethod())) {\n         connection.setRequestProperty(CONTENT_LENGTH, \"0\");\n         // HttpUrlConnection strips Content-Length: 0 without setDoOutput(true)\n         String method = connection.getRequestMethod();\n         if (\"POST\".equals(method) || \"PUT\".equals(method)) {\n            connection.setFixedLengthStreamingMode(0);\n            connection.setDoOutput(true);\n         }\n      }\n   }\n\n   /**\n    * @param payload\n    *           payload to write\n    * @param lengthDesc\n    *           what to use in error log when an IOException occurs\n    * @param connection\n    *           connection to write to\n    */\n   void writePayloadToConnection(Payload payload, Object lengthDesc, HttpURLConnection connection) throws IOException {\n      connection.setDoOutput(true);\n      CountingOutputStream out = new CountingOutputStream(connection.getOutputStream());\n      InputStream is = payload.openStream();\n      try {\n         ByteStreams2.copy(is, out, outputSocketBufferSize);\n      } catch (IOException e) {\n         logger.error(e, \"error after writing %d/%s bytes to %s\", out.getCount(), lengthDesc, connection.getURL());\n         throw e;\n      } finally {\n         closeQuietly(is);\n      }\n   }\n\n   @Override\n   protected void cleanup(HttpURLConnection connection) {\n      if (connection != null)\n         connection.disconnect();\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/internal/PayloadEnclosingImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.io.Payloads.newPayload;\n\nimport java.io.File;\nimport java.io.InputStream;\n\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.PayloadEnclosing;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.io.ByteSource;\n\npublic class PayloadEnclosingImpl implements PayloadEnclosing {\n   protected Payload payload;\n\n   public PayloadEnclosingImpl() {\n      this(null);\n   }\n\n   public PayloadEnclosingImpl(@Nullable Payload payload) {\n      this.payload = payload;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Payload getPayload() {\n      return payload;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void setPayload(Payload data) {\n      if (this.payload != null)\n         payload.release();\n      this.payload = checkNotNull(data, \"data\");\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void setPayload(InputStream data) {\n      setPayload(newPayload(checkNotNull(data, \"data\")));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void setPayload(byte[] data) {\n      setPayload(newPayload(checkNotNull(data, \"data\")));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void setPayload(String data) {\n      setPayload(newPayload(checkNotNull(data, \"data\")));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void setPayload(File data) {\n      setPayload(newPayload(checkNotNull(data, \"data\")));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void setPayload(ByteSource data) {\n      setPayload(newPayload(checkNotNull(data, \"data\")));\n   }\n\n   @Override\n   public void resetPayload(boolean release) {\n      if (release && payload != null) {\n         payload.release();\n      }\n      payload = null;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((payload == null) ? 0 : payload.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      PayloadEnclosingImpl other = (PayloadEnclosingImpl) obj;\n      if (payload == null) {\n         if (other.payload != null)\n            return false;\n      } else if (!payload.equals(other.payload))\n         return false;\n      return true;\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/internal/SignatureWire.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.internal;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\n\nimport org.jclouds.Constants;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.logging.internal.Wire;\n\npublic class SignatureWire extends Wire {\n\n   @Resource\n   @Named(Constants.LOGGER_SIGNATURE)\n   Logger signatureLog = Logger.NULL;\n\n   public Logger getWireLog() {\n      return signatureLog;\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/options/BaseHttpRequestOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.options;\n\nimport java.util.Collection;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.collect.LinkedHashMultimap;\nimport com.google.common.collect.Multimap;\n\n/**\n * \n * @see HttpRequestOptions\n */\npublic class BaseHttpRequestOptions implements HttpRequestOptions {\n\n   protected final Multimap<String, String> formParameters = LinkedHashMultimap.create();\n   protected final Multimap<String, String> queryParameters = LinkedHashMultimap.create();\n   protected final Multimap<String, String> headers = LinkedHashMultimap.create();\n   protected String payload;\n   protected String pathSuffix;\n\n   public String buildStringPayload() {\n      return payload;\n   }\n\n   protected String getFirstQueryOrNull(String string) {\n      Collection<String> values = queryParameters.get(string);\n      return (values != null && values.size() >= 1) ? values.iterator().next() : null;\n   }\n\n   protected String getFirstFormOrNull(String string) {\n      Collection<String> values = formParameters.get(string);\n      return (values != null && values.size() >= 1) ? values.iterator().next() : null;\n   }\n\n   protected String getFirstHeaderOrNull(String string) {\n      Collection<String> values = headers.get(string);\n      return (values != null && values.size() >= 1) ? values.iterator().next() : null;\n   }\n\n   protected void replaceHeader(String key, String value) {\n      headers.removeAll(key);\n      headers.put(key, value);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Multimap<String, String> buildRequestHeaders() {\n      return headers;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Multimap<String, String> buildQueryParameters() {\n      return queryParameters;\n   }\n\n   public String buildPathSuffix() {\n      return pathSuffix;\n   }\n\n   public Multimap<String, String> buildFormParameters() {\n      return formParameters;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((formParameters == null) ? 0 : formParameters.hashCode());\n      result = prime * result + ((headers == null) ? 0 : headers.hashCode());\n      result = prime * result + ((pathSuffix == null) ? 0 : pathSuffix.hashCode());\n      result = prime * result + ((payload == null) ? 0 : payload.hashCode());\n      result = prime * result + ((queryParameters == null) ? 0 : queryParameters.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      BaseHttpRequestOptions other = (BaseHttpRequestOptions) obj;\n      if (formParameters == null) {\n         if (other.formParameters != null)\n            return false;\n      } else if (!formParameters.equals(other.formParameters))\n         return false;\n      if (headers == null) {\n         if (other.headers != null)\n            return false;\n      } else if (!headers.equals(other.headers))\n         return false;\n      if (pathSuffix == null) {\n         if (other.pathSuffix != null)\n            return false;\n      } else if (!pathSuffix.equals(other.pathSuffix))\n         return false;\n      if (payload == null) {\n         if (other.payload != null)\n            return false;\n      } else if (!payload.equals(other.payload))\n         return false;\n      if (queryParameters == null) {\n         if (other.queryParameters != null)\n            return false;\n      } else if (!queryParameters.equals(other.queryParameters))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"formParameters\", formParameters)\n            .add(\"headers\", headers).add(\"pathSuffix\", pathSuffix).add(\"payload\", payload)\n            .add(\"queryParameters\", queryParameters).toString();\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/options/GetOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.options;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.net.HttpHeaders.IF_MATCH;\nimport static com.google.common.net.HttpHeaders.IF_MODIFIED_SINCE;\nimport static com.google.common.net.HttpHeaders.IF_NONE_MATCH;\nimport static com.google.common.net.HttpHeaders.IF_UNMODIFIED_SINCE;\nimport static com.google.common.net.HttpHeaders.RANGE;\n\nimport java.util.Date;\nimport java.util.List;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\n\nimport com.google.common.base.Joiner;\nimport com.google.common.collect.Lists;\nimport com.google.common.collect.Multimap;\n\n/**\n * Contains options supported for HTTP GET operations. <h2>\n * Usage</h2> The recommended way to instantiate a GetObjectOptions object is to statically import\n * GetObjectOptions.Builder.* and invoke a static creation method followed by an instance mutator\n * (if needed):\n * <p/>\n * <code>\n * import static org.jclouds.http.options.GetOptions.Builder.*\n *\n *\n * // this will get the first megabyte of an object.\n * blob = client.get(\"objectName\",range(0,1024));\n * <code>\n */\npublic class GetOptions extends BaseHttpRequestOptions {\n   private static final DateService dateService = new SimpleDateFormatDateService();\n   public static final GetOptions NONE = new GetOptions();\n   private final List<String> ranges = Lists.newArrayList();\n\n   @Override\n   public Multimap<String, String> buildRequestHeaders() {\n      Multimap<String, String> headers = super.buildRequestHeaders();\n      String range = getRange();\n      if (range != null)\n         headers.put(RANGE, this.getRange());\n      return headers;\n   }\n\n   /**\n    * download the specified range of the object.\n    */\n   public GetOptions range(long start, long end) {\n      checkArgument(start >= 0, \"start must be >= 0\");\n      checkArgument(end >= 0, \"end must be >= 0\");\n      ranges.add(String.format(\"%d-%d\", start, end));\n      return this;\n   }\n\n   /**\n    * download the object offset at <code>start</code>\n    */\n   public GetOptions startAt(long start) {\n      checkArgument(start >= 0, \"start must be >= 0\");\n      ranges.add(String.format(\"%d-\", start));\n      return this;\n   }\n\n   /**\n    * download the last <code>count</code> bytes of the object\n    */\n   public GetOptions tail(long count) {\n      checkArgument(count > 0, \"count must be > 0\");\n      ranges.add(String.format(\"-%d\", count));\n      return this;\n   }\n\n   /**\n    * For use in the header Range\n    * <p />\n    *\n    * @see GetOptions#range(long, long)\n    */\n   public String getRange() {\n      return (!ranges.isEmpty()) ? String.format(\"bytes=%s\", Joiner.on(\",\").join(ranges)) : null;\n   }\n\n   /**\n    * Only return the object if it has changed since this time.\n    * <p />\n    * Not compatible with {@link #ifETagMatches(String)} or {@link #ifUnmodifiedSince(Date)}\n    */\n   public GetOptions ifModifiedSince(Date ifModifiedSince) {\n      checkArgument(getIfMatch() == null, \"ifETagMatches() is not compatible with ifModifiedSince()\");\n      checkArgument(getIfUnmodifiedSince() == null, \"ifUnmodifiedSince() is not compatible with ifModifiedSince()\");\n      this.headers.put(IF_MODIFIED_SINCE,\n            dateService.rfc822DateFormat(checkNotNull(ifModifiedSince, \"ifModifiedSince\")));\n      return this;\n   }\n\n   /**\n    * For use in the header If-Modified-Since\n    * <p />\n    * Return the object only if it has been modified since the specified time, otherwise return a\n    * 304 (not modified).\n    *\n    * @see #ifModifiedSince(Date)\n    */\n   public String getIfModifiedSince() {\n      return this.getFirstHeaderOrNull(IF_MODIFIED_SINCE);\n   }\n\n   /**\n    * Only return the object if it hasn't changed since this time.\n    * <p />\n    * Not compatible with {@link #ifETagDoesntMatch(String)} or {@link #ifModifiedSince(Date)}\n    */\n   public GetOptions ifUnmodifiedSince(Date ifUnmodifiedSince) {\n      checkArgument(getIfNoneMatch() == null, \"ifETagDoesntMatch() is not compatible with ifUnmodifiedSince()\");\n      checkArgument(getIfModifiedSince() == null, \"ifModifiedSince() is not compatible with ifUnmodifiedSince()\");\n      this.headers.put(IF_UNMODIFIED_SINCE,\n            dateService.rfc822DateFormat(checkNotNull(ifUnmodifiedSince, \"ifUnmodifiedSince\")));\n      return this;\n   }\n\n   /**\n    * For use in the header If-Unmodified-Since\n    * <p />\n    * Return the object only if it has not been modified since the specified time, otherwise return\n    * a 412 (precondition failed).\n    *\n    * @see #ifUnmodifiedSince(Date)\n    */\n   public String getIfUnmodifiedSince() {\n      return this.getFirstHeaderOrNull(IF_UNMODIFIED_SINCE);\n   }\n\n   /**\n    * The object's eTag hash should match the parameter <code>eTag</code>.\n    *\n    * <p />\n    * Not compatible with {@link #ifETagDoesntMatch(byte[])} or {@link #ifModifiedSince(Date)}\n    *\n    * @param eTag\n    *           hash representing the payload\n    */\n   public GetOptions ifETagMatches(String eTag) {\n      checkArgument(getIfNoneMatch() == null, \"ifETagDoesntMatch() is not compatible with ifETagMatches()\");\n      checkArgument(getIfModifiedSince() == null, \"ifModifiedSince() is not compatible with ifETagMatches()\");\n      this.headers.put(IF_MATCH, maybeQuoteETag(checkNotNull(eTag, \"eTag\")));\n      return this;\n   }\n\n   /**\n    * For use in the request header: If-Match\n    * <p />\n    * Return the object only if its payload tag (ETag) is the same as the eTag specified, otherwise\n    * return a 412 (precondition failed).\n    *\n    * @see #ifETagMatches(String)\n    */\n   public String getIfMatch() {\n      return this.getFirstHeaderOrNull(IF_MATCH);\n   }\n\n   /**\n    * The object should not have a eTag hash corresponding with the parameter <code>eTag</code>.\n    * <p />\n    * Not compatible with {@link #ifETagMatches(String)} or {@link #ifUnmodifiedSince(Date)}\n    *\n    * @param eTag\n    *           hash representing the payload\n    */\n   public GetOptions ifETagDoesntMatch(String eTag) {\n      checkArgument(getIfMatch() == null, \"ifETagMatches() is not compatible with ifETagDoesntMatch()\");\n      checkArgument(getIfUnmodifiedSince() == null, \"ifUnmodifiedSince() is not compatible with ifETagDoesntMatch()\");\n      this.headers.put(IF_NONE_MATCH, maybeQuoteETag(checkNotNull(eTag, \"ifETagDoesntMatch\")));\n      return this;\n   }\n\n   /**\n    * For use in the request header: If-None-Match\n    * <p />\n    * Return the object only if its payload tag (ETag) is different from the one specified,\n    * otherwise return a 304 (not modified).\n    *\n    * @see #ifETagDoesntMatch(String)\n    */\n   public String getIfNoneMatch() {\n      return this.getFirstHeaderOrNull(IF_NONE_MATCH);\n   }\n\n   public List<String> getRanges() {\n      return ranges;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see GetOptions#range(long, long)\n       */\n      public static GetOptions range(long start, long end) {\n         GetOptions options = new GetOptions();\n         return options.range(start, end);\n      }\n\n      /**\n       * @see GetOptions#startAt(long)\n       */\n      public static GetOptions startAt(long start) {\n         GetOptions options = new GetOptions();\n         return options.startAt(start);\n      }\n\n      /**\n       * @see GetOptions#tail(long)\n       */\n      public static GetOptions tail(long count) {\n         GetOptions options = new GetOptions();\n         return options.tail(count);\n      }\n\n      /**\n       * @see GetOptions#getIfModifiedSince()\n       */\n      public static GetOptions ifModifiedSince(Date ifModifiedSince) {\n         GetOptions options = new GetOptions();\n         return options.ifModifiedSince(ifModifiedSince);\n      }\n\n      /**\n       * @see GetOptions#ifUnmodifiedSince(Date)\n       */\n      public static GetOptions ifUnmodifiedSince(Date ifUnmodifiedSince) {\n         GetOptions options = new GetOptions();\n         return options.ifUnmodifiedSince(ifUnmodifiedSince);\n      }\n\n      /**\n       * @see GetOptions#ifETagMatches(String)\n       */\n      public static GetOptions ifETagMatches(String eTag) {\n         GetOptions options = new GetOptions();\n         return options.ifETagMatches(eTag);\n      }\n\n      /**\n       * @see GetOptions#ifETagDoesntMatch(String)\n       */\n      public static GetOptions ifETagDoesntMatch(String eTag) {\n         GetOptions options = new GetOptions();\n         return options.ifETagDoesntMatch(eTag);\n      }\n\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = super.hashCode();\n      result = prime * result + ((ranges == null) ? 0 : ranges.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (!super.equals(obj))\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      GetOptions other = (GetOptions) obj;\n      if (ranges == null) {\n         if (other.ranges != null)\n            return false;\n      } else if (!ranges.equals(other.ranges))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"[formParameters=\" + formParameters + \", queryParameters=\" + queryParameters + \", headers=\" + headers\n            + \", payload=\" + payload + \", pathSuffix=\" + pathSuffix + \", ranges=\" + ranges + \"]\";\n   }\n\n   private static String maybeQuoteETag(String eTag) {\n      if (!eTag.startsWith(\"\\\"\") && !eTag.endsWith(\"\\\"\")) {\n         eTag = \"\\\"\" + eTag + \"\\\"\";\n      }\n      return eTag;\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/options/HttpRequestOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.options;\n\nimport com.google.common.collect.Multimap;\n\n/**\n * Builds options that override or append to HttpRequests.\n */\npublic interface HttpRequestOptions {\n\n   /**\n    * Builds headers representing options.\n    * \n    * @return multimap that may contain headers.\n    */\n   Multimap<String, String> buildRequestHeaders();\n\n   /**\n    * Builds query parameters representing options.\n    * \n    * @return map that may contain query parameters.\n    */\n   Multimap<String, String> buildQueryParameters();\n\n   /**\n    * Builds form parameters representing options.\n    * \n    * @return map that may contain query parameters.\n    */\n   Multimap<String, String> buildFormParameters();\n\n   String buildStringPayload();\n\n   String buildPathSuffix();\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/utils/Queries.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.utils;\n\nimport static org.jclouds.util.Strings2.urlDecode;\nimport static org.jclouds.util.Strings2.urlEncode;\n\nimport java.util.Map.Entry;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.LinkedListMultimap;\nimport com.google.common.collect.Multimap;\n\npublic class Queries {\n\n   private static final Function<String, Multimap<String, String>> parseQueryToDecodedMap = new Function<String, Multimap<String, String>>() {\n      @Override\n      public Multimap<String, String> apply(String in) {\n         // some query values are null, which aren't permitted by Immutable*\n         Multimap<String, String> map = LinkedListMultimap.create();\n         if (in == null) {\n         } else if (in.indexOf('&') == -1) {\n            if (in.indexOf('=') != -1)\n               parseKeyValueFromStringToDecodedMap(in, map);\n            else\n               map.put(in, null);\n         } else {\n            for (String part : Splitter.on('&').split(in)) {\n               parseKeyValueFromStringToDecodedMap(part, map);\n            }\n         }\n         return map;\n      }\n   };\n\n   public static Function<String, Multimap<String, String>> queryParser() {\n      return parseQueryToDecodedMap;\n   }\n\n   private static void parseKeyValueFromStringToDecodedMap(String stringToParse, Multimap<String, String> map) {\n      // note that '=' can be a valid part of the value\n      int indexOfFirstEquals = stringToParse.indexOf('=');\n      String key = indexOfFirstEquals == -1 ? stringToParse : stringToParse.substring(0, indexOfFirstEquals);\n      String value = indexOfFirstEquals == -1 ? null : stringToParse.substring(indexOfFirstEquals + 1);\n      map.put(urlDecode(key), urlDecode(value));\n   }\n\n   /**\n    * percent encodes the query parameters, excep {@code /} and {@code ,} characters.\n    * \n    * @param queryParams\n    * @return percent encoded line or null if no queryParams present\n    */\n   public static String encodeQueryLine(Multimap<String, ?> queryParams) {\n      if (queryParams.isEmpty())\n         return null;\n      return buildQueryLine(queryParams, new EncodeAndAppendParam());\n   }\n   \n   /**\n    * percent encodes the query parameters according except characters specified in the {@code skips} argument.\n    * \n    * @param queryParams\n    * @return percent encoded line or null if no queryParams present\n    */\n   public static String encodeQueryLine(Multimap<String, ?> queryParams, Iterable<Character> skips) {\n      if (queryParams.isEmpty())\n         return null;\n      return buildQueryLine(queryParams, new EncodeAndAppendParam(skips));\n   }\n\n   public static String buildQueryLine(Multimap<String, ?> queryParams) {\n      if (queryParams.isEmpty())\n         return null;\n      return buildQueryLine(queryParams, new AppendParam());\n   }\n\n   private static String buildQueryLine(Multimap<String, ?> queryParams, AppendParam appendParam) {\n      StringBuilder queryBuilder = appendParam.b;\n      for (Entry<String, ?> pair : queryParams.entries()) {\n         queryBuilder.append('&');\n         appendParam.appendKey(pair.getKey());\n         if (pair.getValue() != null)\n            queryBuilder.append('=');\n         if (pair.getValue() != null && !pair.getValue().equals(\"\")) {\n            appendParam.appendValue(pair.getValue());\n         }\n      }\n      queryBuilder.deleteCharAt(0);\n      return queryBuilder.toString();\n   }\n\n   private static class AppendParam {\n      final StringBuilder b;\n\n      private AppendParam() {\n         this.b = new StringBuilder();\n      }\n\n      private void appendKey(String key) {\n         append(key);\n      }\n\n      private void appendValue(Object val) {\n         append(val);\n      }\n\n      void append(Object in) {\n         b.append(in.toString());\n      }\n   }\n\n   private static class EncodeAndAppendParam extends AppendParam {\n      private Iterable<Character> skips;\n\n      private EncodeAndAppendParam() {\n         this(ImmutableList.of('/', ','));\n      }\n\n      private EncodeAndAppendParam(Iterable<Character> skips) {\n         this.skips = skips;\n      }\n\n      @Override\n      void append(Object in) {\n         super.append(urlEncode(in.toString(), skips));\n      }\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/http/utils/QueryValue.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.utils;\n\nimport org.jclouds.util.Strings2;\n\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ImmutableList;\n\npublic class QueryValue implements Comparable {\n   private final boolean encoded;\n   private final Object value;\n   private final Iterable<Character> skipChars;\n\n   public QueryValue(Object value, boolean encoded) {\n      this.value = value;\n      this.encoded = encoded;\n      this.skipChars = ImmutableList.of('/', ',');\n   }\n\n   @Override\n   public String toString() {\n      if (!encoded) {\n         return Strings2.urlEncode(value.toString(), skipChars);\n      }\n      return value.toString();\n   }\n\n   @Override\n   public boolean equals(Object other) {\n      if (other instanceof QueryValue) {\n         // Compare the resulting string, as opposed to whether the string is encoded or not\n         return this.toString().equals(other.toString());\n      } else {\n         return false;\n      }\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(this.toString());\n   }\n\n   @Override\n   public int compareTo(Object o) {\n      return this.toString().compareTo(o.toString());\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/internal/BaseView.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.internal;\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.io.Closeable;\n\nimport org.jclouds.Context;\nimport org.jclouds.View;\nimport org.jclouds.location.Provider;\nimport org.jclouds.rest.ApiContext;\nimport org.jclouds.util.TypeTokenUtils;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ForwardingObject;\nimport com.google.common.reflect.TypeParameter;\nimport com.google.common.reflect.TypeToken;\n\npublic abstract class BaseView extends ForwardingObject implements View {\n\n   private final Context backend;\n   private final TypeToken<? extends Context> backendType;\n\n   protected BaseView(@Provider Context backend, @Provider TypeToken<? extends Context> backendType) {\n      this.backend = checkNotNull(backend, \"backend\");\n      this.backendType = checkNotNull(backendType, \"backendType\");\n   }\n   \n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <C extends Context> C unwrap(TypeToken<C> type) {\n      checkArgument(TypeTokenUtils.isSupertypeOf(checkNotNull(type, \"type\"), backendType), \"%s is not a supertype of backend type %s\", type, backendType);\n      return (C) backend;\n   }\n   \n   @Override\n   public TypeToken<? extends Context> getBackendType() {\n      return backendType;\n   }\n   \n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <C extends Context> C unwrap() throws ClassCastException {\n      return (C) unwrap(getBackendType());\n   }\n   \n   @Override\n   public <A extends Closeable> A unwrapApi(Class<A> apiClass) {\n      checkArgument(ApiContext.class.isAssignableFrom(backendType.getRawType()),\n            \"backend type: %s should be an ApiContext\", backendType);\n      TypeToken<ApiContext<? extends A>> contextToken = new TypeToken<ApiContext<? extends A>>(delegate().getClass()) {\n         private static final long serialVersionUID = 1L;\n      }.where(new TypeParameter<A>() {\n      }, TypeToken.of(apiClass));\n      return unwrap(contextToken).getApi();\n   }\n\n   @Override\n   protected Context delegate() {\n      return backend;\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o)\n         return true;\n      if (o == null || getClass() != o.getClass())\n         return false;\n      BaseView that = BaseView.class.cast(o);\n      return equal(this.delegate(), that.delegate()) && equal(this.getBackendType(), that.getBackendType());\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(delegate(), getBackendType());\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(\"\").add(\"backend\", delegate()).add(\"backendType\", getBackendType());\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/internal/ContextImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.internal;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport static org.jclouds.lifecycle.Closer.State.AVAILABLE;\nimport static org.jclouds.util.Closeables2.closeQuietly;\n\nimport java.net.URI;\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.Context;\nimport org.jclouds.annotations.Name;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.lifecycle.Closer;\nimport org.jclouds.location.Provider;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.rest.Utils;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.inject.Singleton;\n\n@Singleton\npublic class ContextImpl implements Context {\n\n   private final ProviderMetadata providerMetadata;\n   private final Supplier<Credentials> creds;\n   private final Utils utils;\n   private final Closer closer;\n   private final String name;\n\n   @Inject\n   protected ContextImpl(@Name String name, ProviderMetadata providerMetadata, @Provider Supplier<Credentials> creds,\n         Utils utils, Closer closer) {\n      this.providerMetadata = checkNotNull(providerMetadata, \"providerMetadata\");\n      this.creds = checkNotNull(creds, \"creds\");\n      this.utils = checkNotNull(utils, \"utils\");\n      this.closer = checkNotNull(closer, \"closer\");\n      this.name = checkNotNull(name, \"name\");\n    }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void close() {\n      closeQuietly(closer);\n   }\n\n   @Override\n   public boolean isOpen() {\n      return closer.getState() == AVAILABLE;\n   }\n\n    /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ProviderMetadata getProviderMetadata() {\n      return providerMetadata;\n   }\n\n  /**\n   * {@inheritDoc}\n   */\n  @Override\n  public String getName() {\n    return name;\n  }\n\n  /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getIdentity() {\n      return creds.get().identity;\n   }\n\n   @Override\n   public Utils utils() {\n      return utils;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(providerMetadata, creds);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      ContextImpl that = ContextImpl.class.cast(obj);\n      return equal(this.providerMetadata, that.providerMetadata) && equal(this.creds, that.creds);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String toString() {\n      return toStringHelper(\"\").add(\"providerMetadata\", providerMetadata).add(\"identity\", getIdentity()).toString();\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getDescription() {\n      return providerMetadata.getName();\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getId() {\n      return providerMetadata.getId();\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Set<String> getIso3166Codes() {\n      return providerMetadata.getIso3166Codes();\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Map<String, Object> getMetadata() {\n      return ImmutableMap.<String, Object> of(\"endpoint\", URI.create(providerMetadata.getEndpoint()), \"apiVersion\",\n               providerMetadata.getApiMetadata().getVersion(), \"buildVersion\", providerMetadata.getApiMetadata()\n                        .getBuildVersion().or(\"\"), \"identity\", getIdentity());\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Location getParent() {\n      return null;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public LocationScope getScope() {\n      return LocationScope.PROVIDER;\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/internal/FilterStringsBoundToInjectorByName.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.lang.annotation.Annotation;\nimport java.util.List;\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Maps;\nimport com.google.inject.Binding;\nimport com.google.inject.Injector;\nimport com.google.inject.TypeLiteral;\n\n/**\n * finds all the named string bindings who's name annotation matches the filter.\n * for convenience, the bindings are returned as a map.\n */\n@Singleton\npublic class FilterStringsBoundToInjectorByName implements Function<Predicate<String>, Map<String, String>> {\n\n   private final Injector injector;\n\n   @Inject\n   public FilterStringsBoundToInjectorByName(Injector injector) {\n      this.injector = checkNotNull(injector, \"injector\");\n   }\n\n   @Override\n   public Map<String, String> apply(Predicate<String> filter) {\n      List<Binding<String>> stringBindings = injector.findBindingsByType(TypeLiteral.get(String.class));\n      Iterable<Binding<String>> annotatedWithName = Iterables.filter(stringBindings, new Predicate<Binding<String>>() {\n\n         @Override\n         public boolean apply(Binding<String> input) {\n            Annotation annotation = input.getKey().getAnnotation();\n            if (annotation == null)\n               return false;\n            return (annotation instanceof jakarta.inject.Named) || (annotation instanceof com.google.inject.name.Named);\n         }\n\n      });\n\n      Map<String, Binding<String>> bindingsByName = Maps.uniqueIndex(annotatedWithName,\n            new Function<Binding<String>, String>() {\n\n               @Override\n               public String apply(Binding<String> input) {\n                  Annotation annotation = input.getKey().getAnnotation();\n                  return (annotation instanceof jakarta.inject.Named) ? jakarta.inject.Named.class.cast(annotation)\n                        .value() : com.google.inject.name.Named.class.cast(annotation).value();\n               }\n\n            });\n\n      Map<String, Binding<String>> filteredBindingsByName = Maps.filterKeys(bindingsByName, filter);\n\n      Map<String, String> stringBoundByName = Maps.transformValues(filteredBindingsByName,\n            new Function<Binding<String>, String>() {\n\n               @Override\n               public String apply(Binding<String> input) {\n                  return input.getProvider().get();\n               }\n            });\n      return stringBoundByName;\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/io/ByteSources.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.io;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.collect.Iterables;\nimport com.google.common.io.ByteSource;\n\n/**\n * functions related to or replacing those in {@link ByteSource}\n */\n@Beta\npublic class ByteSources {\n\n   /** Create an infinite-length ByteSource which repeats its input. */\n   public static ByteSource repeatingArrayByteSource(final byte[] input) {\n      return ByteSource.concat(Iterables.cycle(ByteSource.wrap(input)));\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/io/ByteStreams2.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.io;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.util.Closeables2.closeQuietly;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.hash.HashCode;\nimport com.google.common.hash.HashFunction;\nimport com.google.common.hash.HashingInputStream;\nimport com.google.common.io.ByteStreams;\n\n@Beta\npublic class ByteStreams2 {\n   private static final int INPUT_STREAM_READ_END_OF_STREAM_INDICATOR = -1;\n\n   public static HashCode hashAndClose(InputStream input, HashFunction hashFunction) throws IOException {\n      checkNotNull(input, \"input\");\n      checkNotNull(hashFunction, \"hashFunction\");\n      try {\n         HashingInputStream his = new HashingInputStream(hashFunction, input);\n         ByteStreams.copy(his, ByteStreams.nullOutputStream());\n         return his.hash();\n      } finally {\n         closeQuietly(input);\n      }\n   }\n\n   public static byte[] toByteArrayAndClose(InputStream input) throws IOException {\n      checkNotNull(input, \"input\");\n      try {\n         return ByteStreams.toByteArray(input);\n      } finally {\n         closeQuietly(input);\n      }\n   }\n\n   public static long copy(InputStream from, OutputStream to, int bufferSize) throws IOException {\n      checkNotNull(from, \"from\");\n      checkNotNull(to, \"to\");\n      checkArgument(bufferSize >= 1, \"bufferSize must be >= 1\");\n\n      byte[] buf = new byte[bufferSize];\n      long total = 0L;\n\n      while (true) {\n         int len = from.read(buf);\n         if (len == INPUT_STREAM_READ_END_OF_STREAM_INDICATOR) {\n            return total;\n         }\n\n         to.write(buf, 0, len);\n         total += (long)len;\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/io/ContentMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.io;\nimport static com.google.common.net.HttpHeaders.CACHE_CONTROL;\nimport static com.google.common.net.HttpHeaders.CONTENT_DISPOSITION;\nimport static com.google.common.net.HttpHeaders.CONTENT_ENCODING;\nimport static com.google.common.net.HttpHeaders.CONTENT_LANGUAGE;\nimport static com.google.common.net.HttpHeaders.CONTENT_LENGTH;\nimport static com.google.common.net.HttpHeaders.CONTENT_MD5;\nimport static com.google.common.net.HttpHeaders.CONTENT_TYPE;\nimport static com.google.common.net.HttpHeaders.EXPIRES;\n\nimport java.util.Date;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.hash.HashCode;\nimport com.google.common.collect.ImmutableSet;\n\npublic interface ContentMetadata {\n   Set<String> HTTP_HEADERS = ImmutableSet.of(\n         CACHE_CONTROL,\n         CONTENT_LENGTH,\n         CONTENT_MD5,\n         CONTENT_TYPE,\n         CONTENT_DISPOSITION,\n         CONTENT_ENCODING,\n         CONTENT_LANGUAGE,\n         EXPIRES);\n\n   // See http://stackoverflow.com/questions/10584647/simpledateformat-parse-is-one-hour-out-using-rfc-1123-gmt-in-summer\n   // for why not using \"zzz\"\n   String RFC1123_DATE_PATTERN = \"EEE, dd MMM yyyyy HH:mm:ss Z\";\n   \n   @Nullable\n   String getCacheControl();\n\n   /**\n    * Returns the total size of the payload, or the chunk that's available.\n    * <p/>\n    * Chunking is only used when {@link org.jclouds.http.GetOptions} is called with options like\n    * tail, range, or startAt.\n    * \n    * @return the length in bytes that can be be obtained from {@link #getInput()}\n    * @see com.google.common.net.HttpHeaders#CONTENT_LENGTH\n    * @see org.jclouds.http.options.GetOptions\n    */\n   @Nullable\n   Long getContentLength();\n\n   /**\n    * Specifies presentational information for the object.\n    * \n    * @see <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html?sec19.5.1.\"/>\n    */\n   @Nullable\n   String getContentDisposition();\n\n   /**\n    * Specifies what content encodings have been applied to the object and thus what decoding\n    * mechanisms must be applied in order to obtain the media-type referenced by the Content-Type\n    * header field.\n    * \n    * @see <a href= \"http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html?sec14.11\" />\n    */\n   @Nullable\n   String getContentEncoding();\n\n   /**\n    * \n    * A standard MIME type describing the format of the contents. If none is provided, the default\n    * is binary/octet-stream.\n    * \n    * @see <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17\"/>\n    */\n   @Nullable\n   String getContentType();\n\n   /** @deprecated use {@link #getContentMD5AsHashCode()} instead. */\n   @Deprecated\n   @Nullable\n   byte[] getContentMD5();\n\n   @Nullable\n   HashCode getContentMD5AsHashCode();\n\n   /**\n    * Get Content Language of the payload\n    * <p/>\n    * Not all providers may support it\n    */\n   @Nullable\n   String getContentLanguage();\n\n   /**\n    * Gives the date/time after which the response is considered stale.\n    * \n    * @throws IllegalStateException If the Expires header is non-null, and not a valid RFC 1123 date\n    * \n    * @see <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.21\"/>\n    */\n   @Nullable\n   Date getExpires();\n\n  ContentMetadataBuilder toBuilder();\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/io/ContentMetadataBuilder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.io;\n\nimport java.util.Date;\n\nimport org.jclouds.io.payloads.BaseImmutableContentMetadata;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.Preconditions;\nimport com.google.common.hash.HashCode;\n\npublic class ContentMetadataBuilder {\n\n   public static ContentMetadataBuilder create() {\n      return new ContentMetadataBuilder();\n   }\n\n   protected String cacheControl;\n   protected String contentType = \"application/unknown\";\n   protected Long contentLength;\n   protected HashCode contentMD5;\n   protected String contentDisposition;\n   protected String contentLanguage;\n   protected String contentEncoding;\n   protected Date expires;\n\n   public ContentMetadataBuilder cacheControl(@Nullable String cacheControl) {\n      this.cacheControl = cacheControl;\n      return this;\n   }\n\n   public ContentMetadataBuilder contentLength(@Nullable Long contentLength) {\n      this.contentLength = contentLength;\n      return this;\n   }\n\n   /** @deprecated use {@link #contentMD5(HashCode)} instead. */\n   @Deprecated\n   public ContentMetadataBuilder contentMD5(@Nullable byte[] contentMD5) {\n      return contentMD5(contentMD5 == null ? null : HashCode.fromBytes(contentMD5));\n   }\n\n   public ContentMetadataBuilder contentMD5(@Nullable HashCode contentMD5) {\n      if (contentMD5 != null) {\n         Preconditions.checkArgument(contentMD5.bits() == 128, \"MD5 hash must have 128 bits, was: %s\", contentMD5.bits());\n      }\n      this.contentMD5 = contentMD5;\n      return this;\n   }\n\n   public ContentMetadataBuilder contentType(@Nullable String contentType) {\n      this.contentType = contentType;\n      return this;\n   }\n\n   public ContentMetadataBuilder contentDisposition(@Nullable String contentDisposition) {\n      this.contentDisposition = contentDisposition;\n      return this;\n\n   }\n\n   public ContentMetadataBuilder contentLanguage(@Nullable String contentLanguage) {\n      this.contentLanguage = contentLanguage;\n      return this;\n   }\n\n   public ContentMetadataBuilder contentEncoding(@Nullable String contentEncoding) {\n      this.contentEncoding = contentEncoding;\n      return this;\n   }\n\n   public ContentMetadataBuilder expires(@Nullable Date expires) {\n      this.expires = expires;\n      return this;\n   }\n\n   public ContentMetadata build() {\n      return new BaseImmutableContentMetadata(cacheControl, contentType, contentLength,\n               contentMD5 == null ? null : contentMD5.asBytes(), contentDisposition,\n               contentLanguage, contentEncoding, expires);\n   }\n\n   public static ContentMetadataBuilder fromContentMetadata(ContentMetadata in) {\n      return new ContentMetadataBuilder()\n               .cacheControl(in.getCacheControl()).contentType(in.getContentType()).contentLength(in.getContentLength())\n               .contentMD5(in.getContentMD5()).contentDisposition(in.getContentDisposition()).contentLanguage(\n                        in.getContentLanguage()).contentEncoding(in.getContentEncoding()).expires(in.getExpires());\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(contentDisposition, contentEncoding, contentLanguage, contentLength, \n               contentMD5, contentType, expires);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      ContentMetadataBuilder other = (ContentMetadataBuilder) obj;\n      return Objects.equal(cacheControl, other.cacheControl) &&\n             Objects.equal(contentDisposition, other.contentDisposition) &&\n             Objects.equal(contentEncoding, other.contentEncoding) &&\n             Objects.equal(contentLanguage, other.contentLanguage) &&\n             Objects.equal(contentLength, other.contentLength) &&\n             Objects.equal(contentMD5, other.contentMD5) &&\n             Objects.equal(contentType, other.contentType) &&\n             Objects.equal(expires, other.expires);\n   }\n\n   @Override\n   public String toString() {\n      return \"[cacheControl=\" + cacheControl\n               + \", contentDisposition=\" + contentDisposition + \", contentEncoding=\" + contentEncoding\n               + \", contentLanguage=\" + contentLanguage + \", contentLength=\" + contentLength + \", contentMD5=\"\n               + contentMD5 + \", contentType=\" + contentType + \", expires=\" + expires + \"]\";\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/io/ContentMetadataCodec.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.io;\n\nimport static com.google.common.collect.Iterables.any;\nimport static com.google.common.io.BaseEncoding.base64;\nimport static com.google.common.net.HttpHeaders.CACHE_CONTROL;\nimport static com.google.common.net.HttpHeaders.CONTENT_DISPOSITION;\nimport static com.google.common.net.HttpHeaders.CONTENT_ENCODING;\nimport static com.google.common.net.HttpHeaders.CONTENT_LANGUAGE;\nimport static com.google.common.net.HttpHeaders.CONTENT_LENGTH;\nimport static com.google.common.net.HttpHeaders.CONTENT_MD5;\nimport static com.google.common.net.HttpHeaders.CONTENT_TYPE;\nimport static com.google.common.net.HttpHeaders.EXPIRES;\n\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Map.Entry;\n\nimport jakarta.annotation.Resource;\n\nimport org.jclouds.date.DateCodec;\nimport org.jclouds.date.DateCodecFactory;\nimport org.jclouds.io.ContentMetadataCodec.DefaultContentMetadataCodec;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableMultimap.Builder;\nimport com.google.common.collect.Multimap;\nimport com.google.inject.ImplementedBy;\nimport com.google.inject.Inject;\n\n@ImplementedBy(DefaultContentMetadataCodec.class)\npublic interface ContentMetadataCodec {\n\n   /**\n    * Generates standard HTTP headers for the give metadata.\n    */\n   Multimap<String, String> toHeaders(ContentMetadata md);\n\n   /**\n    * Sets properties related to the http headers listed in {@link ContentMetadata#HTTP_HEADERS}\n    */\n   void fromHeaders(MutableContentMetadata contentMetadata, Multimap<String, String> headers);\n\n   /**\n    * Parses the 'Expires' header.\n    * If invalid, returns a date in the past (in accordance with HTTP 1.1 client spec).\n    */\n   Date parseExpires(String expires);\n\n   /**\n    * Default implementation, in accordance with HTTP 1.1 spec.\n    * \n    */\n   public static class DefaultContentMetadataCodec implements ContentMetadataCodec {\n      \n      @Resource\n      protected Logger logger = Logger.NULL;\n\n      private final DateCodec httpExpiresDateCodec;\n      private final List<DateCodec> httpExpiresDateDecoders;\n\n      @Inject\n      public DefaultContentMetadataCodec(DateCodecFactory dateCodecs) {\n         httpExpiresDateCodec = dateCodecs.rfc1123();\n         httpExpiresDateDecoders = ImmutableList.of(dateCodecs.rfc1123(), dateCodecs.asctime());\n      }\n\n      protected DateCodec getExpiresDateCodec() {\n         return httpExpiresDateCodec;\n      }\n\n      protected List<DateCodec> getExpiresDateDecoders() {\n         return httpExpiresDateDecoders;\n      }\n\n      @Override\n      public Multimap<String, String> toHeaders(ContentMetadata md) {\n         Builder<String, String> builder = ImmutableMultimap.builder();\n         if (md.getCacheControl() != null)\n            builder.put(CACHE_CONTROL, md.getCacheControl());\n         if (md.getContentType() != null)\n            builder.put(CONTENT_TYPE, md.getContentType());\n         if (md.getContentDisposition() != null)\n            builder.put(CONTENT_DISPOSITION, md.getContentDisposition());\n         if (md.getContentEncoding() != null)\n            builder.put(CONTENT_ENCODING, md.getContentEncoding());\n         if (md.getContentLanguage() != null)\n            builder.put(CONTENT_LANGUAGE, md.getContentLanguage());\n         if (md.getContentLength() != null)\n            builder.put(CONTENT_LENGTH, md.getContentLength() + \"\");\n         if (md.getContentMD5() != null)\n            builder.put(CONTENT_MD5, base64().encode(md.getContentMD5()));\n         if (md.getExpires() != null)\n            builder.put(EXPIRES, getExpiresDateCodec().toString(md.getExpires()));\n         return builder.build();\n      }\n      \n      @Override\n      public void fromHeaders(MutableContentMetadata contentMetadata, Multimap<String, String> headers) {\n         boolean chunked = any(headers.entries(), new Predicate<Entry<String, String>>() {\n            @Override\n            public boolean apply(Entry<String, String> input) {\n               return \"Transfer-Encoding\".equalsIgnoreCase(input.getKey()) && \"chunked\".equalsIgnoreCase(input.getValue());\n            }\n         });\n         for (Entry<String, String> header : headers.entries()) {\n            if (CACHE_CONTROL.equalsIgnoreCase(header.getKey())) {\n               contentMetadata.setCacheControl(header.getValue());\n            } else if (!chunked && CONTENT_LENGTH.equalsIgnoreCase(header.getKey())) {\n               contentMetadata.setContentLength(Long.valueOf(header.getValue()));\n            } else if (CONTENT_MD5.equalsIgnoreCase(header.getKey())) {\n               contentMetadata.setContentMD5(base64().decode(header.getValue()));\n            } else if (CONTENT_TYPE.equalsIgnoreCase(header.getKey())) {\n               contentMetadata.setContentType(header.getValue());\n            } else if (CONTENT_DISPOSITION.equalsIgnoreCase(header.getKey())) {\n               contentMetadata.setContentDisposition(header.getValue());\n            } else if (CONTENT_ENCODING.equalsIgnoreCase(header.getKey())) {\n               contentMetadata.setContentEncoding(header.getValue());\n            } else if (CONTENT_LANGUAGE.equalsIgnoreCase(header.getKey())) {\n               contentMetadata.setContentLanguage(header.getValue());\n            } else if (EXPIRES.equalsIgnoreCase(header.getKey())) {\n               contentMetadata.setExpires(parseExpires(header.getValue()));\n            }\n         }\n      }\n      \n      /**\n       * Parses the date from the given Expires header.\n       * <p>\n       * According to the RFC, dates should always come in RFC-1123 format.\n       * However, clients should also support older and deprecated formats for\n       * compatibility, so this method will try to parse an RFC-1123 date, and\n       * fallback to the ANSI C format.\n       * \n       * @see https://tools.ietf.org/html/rfc2616#section-3.3\n       */\n      public Date parseExpires(String expires) {\n         if (expires == null)\n            return null;\n\n         for (DateCodec decoder : getExpiresDateDecoders()) {\n            try {\n               return decoder.toDate(expires);\n            } catch (IllegalArgumentException ex) {\n               logger.trace(\"Expires header (%s) is not in the expected %s format\", expires, decoder);\n               // Continue trying the other decoders\n            }\n         }\n\n         logger.debug(\"Invalid Expires header (%s); should be in RFC-1123 format; treating as already expired\", expires);\n         return new Date(0);\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/io/MutableContentMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.io;\n\nimport java.util.Date;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.hash.HashCode;\n\npublic interface MutableContentMetadata extends ContentMetadata {\n\n   void setCacheControl(@Nullable String cacheControl);\n\n   void setContentLength(@Nullable Long contentLength);\n\n   /** @deprecated use {@link #setContentMD5(HashCode)} instead. */\n   @Deprecated\n   void setContentMD5(@Nullable byte[] md5);\n\n   void setContentMD5(@Nullable HashCode md5);\n\n   void setContentType(@Nullable String contentType);\n\n   /**\n    * Set Content Disposition of the payload\n    * <p/>\n    * Not all providers may support it\n    * \n    * @param contentDisposition\n    */\n   void setContentDisposition(@Nullable String contentDisposition);\n\n   /**\n    * Set Content Language of the payload\n    * <p/>\n    * Not all providers may support it\n    * \n    * @param contentLanguage\n    */\n   void setContentLanguage(@Nullable String contentLanguage);\n\n   /**\n    * Set Content Encoding of the payload\n    * <p/>\n    * Not all providers may support it\n    * \n    * @param contentEncoding\n    */\n   void setContentEncoding(@Nullable String contentEncoding);\n\n   void setExpires(@Nullable Date expires);\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/io/Payload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.io;\n\nimport java.io.Closeable;\nimport java.io.IOException;\nimport java.io.InputStream;\n\npublic interface Payload extends Closeable {\n\n   /**\n    * Creates a new InputStream object of the payload.\n    */\n   InputStream openStream() throws IOException;\n\n   /**\n    * Creates a new InputStream object of the payload.\n    *\n    * @deprecated see {@link Payload#openStream()}.\n    */\n   @Deprecated\n   InputStream getInput();\n\n   /**\n    * Payload in its original form.\n    */\n   Object getRawContent();\n\n   /**\n    * Tells if the payload is capable of producing its data more than once.\n    */\n   boolean isRepeatable();\n\n   /**\n    * release resources used by this entity. This should be called when data is discarded.\n    */\n   void release();\n\n   MutableContentMetadata getContentMetadata();\n\n   void setContentMetadata(MutableContentMetadata in);\n\n   /**\n    * Sets whether the payload contains sensitive information. This is used when trying to decide whether to print out the\n    * payload information or not in logs\n    */\n   void setSensitive(boolean isSensitive);\n\n   /**\n    * Returns whether the payload contains sensitive information. This is used when trying to decide whether to print out the\n    * payload information or not in logs\n    */\n   boolean isSensitive();\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/io/PayloadEnclosing.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.io;\n\nimport java.io.File;\nimport java.io.InputStream;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.io.ByteSource;\n\npublic interface PayloadEnclosing {\n\n   /**\n    * Sets payload for the request or the content from the response. If size isn't set, this will\n    * attempt to discover it.\n    * \n    * @param data\n    *           typically InputStream for downloads, or File, byte[], String, InputStream,\n    *           of ByteSource for uploads.\n    */\n   void setPayload(Payload data);\n\n   void setPayload(File data);\n\n   void setPayload(byte[] data);\n\n   void setPayload(InputStream data);\n\n   void setPayload(String data);\n\n   void setPayload(ByteSource data);\n\n   @Nullable\n   Payload getPayload();\n\n   void resetPayload(boolean release);\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/io/PayloadSlicer.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.io;\n\nimport org.jclouds.io.internal.BasePayloadSlicer;\n\nimport com.google.inject.ImplementedBy;\n\n\n@ImplementedBy(BasePayloadSlicer.class)\npublic interface PayloadSlicer {\n   /**\n    * Returns a {@link Payload} that returns input streams from the an underlying payload, where\n    * each stream starts at the given offset and is limited to the specified number of bytes.\n    * \n    * @param input\n    *           the payload from which to get the raw streams\n    * @param offset\n    *           the offset in bytes into the underlying stream where the returned streams will start\n    * @param length\n    *           the maximum length of the returned streams\n    * @throws IllegalArgumentException\n    *            if offset or length are negative\n    */\n   Payload slice(Payload input, long offset, long length);\n\n   /**\n    * Returns an {@link Iterable} of {@link Payload} instances that are no larger than\n    * <code>size</code> bytes in length.\n    *\n    * @param input\n    *           the {@link Payload} to be sliced\n    * @param size\n    *           the maximum size of each slice\n    * @return an {@link Iterable} of {@link Payload} instances\n    */\n   Iterable<Payload> slice(Payload input, long size);\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/io/Payloads.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.io;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.io.File;\nimport java.io.InputStream;\n\nimport org.jclouds.io.payloads.ByteArrayPayload;\nimport org.jclouds.io.payloads.ByteSourcePayload;\nimport org.jclouds.io.payloads.FilePayload;\nimport org.jclouds.io.payloads.InputStreamPayload;\nimport org.jclouds.io.payloads.StringPayload;\nimport org.jclouds.io.payloads.UrlEncodedFormPayload;\n\nimport com.google.common.collect.Multimap;\nimport com.google.common.io.ByteSource;\n\npublic class Payloads {\n   private Payloads() {\n   }\n\n   public static Payload newPayload(Object data) {\n      checkNotNull(data, \"data\");\n      if (data instanceof Payload) {\n         return (Payload) data;\n      } else if (data instanceof InputStream) {\n         return newInputStreamPayload((InputStream) data);\n      } else if (data instanceof byte[]) {\n         return newByteArrayPayload((byte[]) data);\n      } else if (data instanceof ByteSource) {\n         return newByteSourcePayload((ByteSource) data);\n      } else if (data instanceof String) {\n         return newStringPayload((String) data);\n      } else if (data instanceof File) {\n         return newFilePayload((File) data);\n      } else {\n         throw new UnsupportedOperationException(\"unsupported payload type: \" + data.getClass());\n      }\n   }\n\n   public static InputStreamPayload newInputStreamPayload(InputStream data) {\n      return new InputStreamPayload(checkNotNull(data, \"data\"));\n   }\n\n   public static ByteArrayPayload newByteArrayPayload(byte[] data) {\n      return new ByteArrayPayload(checkNotNull(data, \"data\"));\n   }\n\n   public static ByteSourcePayload newByteSourcePayload(ByteSource data) {\n      return new ByteSourcePayload(checkNotNull(data, \"data\"));\n   }\n\n   public static StringPayload newStringPayload(String data) {\n      return new StringPayload(checkNotNull(data, \"data\"));\n   }\n\n   public static FilePayload newFilePayload(File data) {\n      return new FilePayload(checkNotNull(data, \"data\"));\n   }\n\n   public static UrlEncodedFormPayload newUrlEncodedFormPayload(Multimap<String, String> formParams) {\n      return new UrlEncodedFormPayload(formParams);\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/io/internal/BasePayloadSlicer.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.io.internal;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.Arrays;\nimport java.util.Iterator;\nimport java.util.NoSuchElementException;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.io.ContentMetadata;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.io.PayloadSlicer;\nimport org.jclouds.io.payloads.BaseMutableContentMetadata;\nimport org.jclouds.io.payloads.ByteSourcePayload;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.base.Throwables;\nimport com.google.common.hash.HashCode;\nimport com.google.common.io.ByteSource;\nimport com.google.common.io.ByteStreams;\nimport com.google.common.io.Files;\n\n@Singleton\npublic class BasePayloadSlicer implements PayloadSlicer {\n\n   private static final class InputStreamPayloadIterable implements Iterable<Payload> {\n      private final InputStream input;\n      private final ContentMetadata metaData;\n\n      InputStreamPayloadIterable(InputStream input, ContentMetadata metaData) {\n         this.input = checkNotNull(input, \"input\");\n         this.metaData = checkNotNull(metaData, \"metaData\");\n      }\n\n      @Override\n      public Iterator<Payload> iterator() {\n         return new InputStreamPayloadIterator(input, metaData);\n      }\n   }\n\n   private static final class InputStreamPayloadIterator implements Iterator<Payload> {\n      private final InputStream input;\n      private final ContentMetadata metaData;\n      private Payload nextPayload;\n      private final int readLen;\n\n      InputStreamPayloadIterator(InputStream input, ContentMetadata metaData) {\n         this.input = checkNotNull(input, \"input\");\n         this.metaData = checkNotNull(metaData, \"metaData\");\n         this.readLen = checkNotNull(this.metaData.getContentLength(), \"content-length\").intValue();\n\n         this.nextPayload = getNextPayload();\n      }\n\n      @Override\n      public boolean hasNext() {\n         return nextPayload != null;\n      }\n\n      @Override\n      public Payload next() {\n         Payload payload;\n\n         if (!hasNext())\n            throw new NoSuchElementException();\n\n         payload = nextPayload;\n         nextPayload = getNextPayload();\n\n         return payload;\n      }\n\n      @Override\n      public void remove() {\n         throw new UnsupportedOperationException(\"Payload iterator does not support removal\");\n      }\n\n      private Payload getNextPayload() {\n         byte[] content = new byte[readLen];\n         int offset = 0;\n\n         try {\n            while (true) {\n               int read = input.read(content, offset, readLen - offset);\n               if (read <= 0) {\n                  if (offset == 0) {\n                     return null;\n                  } else {\n                     break;\n                  }\n               }\n               offset += read;\n            }\n         } catch (IOException e) {\n            throw Throwables.propagate(e);\n         }\n\n         return createPayload((content.length == offset) ? content : Arrays.copyOf(content, offset));\n      }\n\n      private Payload createPayload(byte[] content) {\n         Payload payload = null;\n\n         if (content.length > 0) {\n            payload = Payloads.newByteArrayPayload(content);\n            ContentMetadata cm = metaData.toBuilder().contentLength((long)content.length).contentMD5((HashCode) null).build();\n            payload.setContentMetadata(BaseMutableContentMetadata.fromContentMetadata(cm));\n         }\n\n         return payload;\n      }\n\n   }\n\n   private static final class ByteSourcePayloadIterable implements Iterable<Payload> {\n      private final ByteSource input;\n      private final ContentMetadata metaData;\n\n      ByteSourcePayloadIterable(ByteSource input, ContentMetadata metaData) {\n         this.input = checkNotNull(input, \"input\");\n         this.metaData = checkNotNull(metaData, \"metaData\");\n      }\n\n      @Override\n      public Iterator<Payload> iterator() {\n         return new ByteSourcePayloadIterator(input, metaData);\n      }\n   }\n\n   private static final class ByteSourcePayloadIterator implements Iterator<Payload> {\n      private final ByteSource input;\n      private final ContentMetadata metaData;\n      private Payload nextPayload;\n      private long offset = 0;\n      private final long readLen;\n\n      ByteSourcePayloadIterator(ByteSource input, ContentMetadata metaData) {\n         this.input = checkNotNull(input, \"input\");\n         this.metaData = checkNotNull(metaData, \"metaData\");\n         this.readLen = checkNotNull(this.metaData.getContentLength(), \"content-length\").longValue();\n         this.nextPayload = getNextPayload();\n      }\n\n      @Override\n      public boolean hasNext() {\n         return nextPayload != null;\n      }\n\n      @Override\n      public Payload next() {\n         if (!hasNext()) {\n            throw new NoSuchElementException();\n         }\n\n         Payload payload = nextPayload;\n         nextPayload = getNextPayload();\n\n         return payload;\n      }\n\n      @Override\n      public void remove() {\n         throw new UnsupportedOperationException(\"Payload iterator does not support removal\");\n      }\n\n      private Payload getNextPayload() {\n         ByteSource byteSource;\n         long byteSourceSize;\n         try {\n            if (offset >= input.size()) {\n               return null;\n            }\n            byteSource = input.slice(offset, readLen);\n            byteSourceSize = byteSource.size();\n         } catch (IOException e) {\n            throw Throwables.propagate(e);\n         }\n\n         Payload nextPayload = new ByteSourcePayload(byteSource);\n         ContentMetadata cm = metaData.toBuilder()\n               .contentLength(byteSourceSize)\n               .contentMD5((HashCode) null)\n               .build();\n         nextPayload.setContentMetadata(BaseMutableContentMetadata.fromContentMetadata(cm));\n         offset += byteSourceSize;\n         return nextPayload;\n      }\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Payload slice(Payload input, long offset, long length) {\n      checkNotNull(input);\n      checkArgument(offset >= 0, \"offset is negative\");\n      checkArgument(length >= 0, \"length is negative\");\n      Payload returnVal;\n      if (input.getRawContent() instanceof File) {\n         returnVal = doSlice((File) input.getRawContent(), offset, length);\n      } else if (input.getRawContent() instanceof String) {\n         returnVal = doSlice((String) input.getRawContent(), offset, length);\n      } else if (input.getRawContent() instanceof byte[]) {\n         returnVal = doSlice((byte[]) input.getRawContent(), offset, length);\n      } else if (input.getRawContent() instanceof InputStream) {\n         returnVal = doSlice((InputStream) input.getRawContent(), offset, length);\n      } else if (input.getRawContent() instanceof ByteSource) {\n         returnVal = doSlice((ByteSource) input.getRawContent(), offset, length);\n      } else {\n         returnVal = doSlice(input, offset, length);\n      }\n      return copyMetadataAndSetLength(input, returnVal, length);\n   }\n\n   protected Payload doSlice(Payload content, long offset, long length) {\n      return doSlice(content.getInput(), offset, length);\n   }\n\n   protected Payload doSlice(String content, long offset, long length) {\n      return doSlice(content.getBytes(), offset, length);\n   }\n\n   protected Payload doSlice(File content, long offset, long length) {\n      return doSlice(Files.asByteSource(content), offset, length);\n   }\n\n   protected Payload doSlice(InputStream content, long offset, long length) {\n      try {\n         ByteStreams.skipFully(content, offset);\n      } catch (IOException ioe) {\n         throw Throwables.propagate(ioe);\n      }\n      return Payloads.newInputStreamPayload(ByteStreams.limit(content, length));\n   }\n\n   protected Payload doSlice(ByteSource content, long offset, long length) {\n      return Payloads.newByteSourcePayload(content.slice(offset, length));\n   }\n\n   protected Payload doSlice(byte[] content, long offset, long length) {\n      checkArgument(offset <= Integer.MAX_VALUE, \"offset is too big for an array\");\n      checkArgument(length <= Integer.MAX_VALUE, \"length is too big for an array\");\n      // TODO(adriancole): Make ByteArrayPayload carry offset, length as opposed to wrapping here.\n      return Payloads.newByteSourcePayload(ByteSource.wrap(content).slice(offset, length));\n   }\n\n   protected Payload copyMetadataAndSetLength(Payload input, Payload returnVal, long length) {\n      returnVal.setContentMetadata(BaseMutableContentMetadata.fromContentMetadata(input.getContentMetadata()\n            .toBuilder().contentLength(length).contentMD5((HashCode) null).build()));\n      return returnVal;\n   }\n\n   @Override\n   public Iterable<Payload> slice(Payload input, long size) {\n      checkNotNull(input, \"input\");\n      checkArgument(size >= 0, \"size must be non-negative but was: %s\", size);\n\n      ContentMetadata meta = BaseMutableContentMetadata.fromContentMetadata(input.getContentMetadata())\n                                                       .toBuilder()\n                                                       .contentLength(size)\n                                                       .contentMD5((HashCode) null)\n                                                       .build();\n      Object rawContent = input.getRawContent();\n      if (rawContent instanceof File) {\n         return doSlice((File) rawContent, meta);\n      } else if (rawContent instanceof String) {\n         return doSlice((String) rawContent, meta);\n      } else if (rawContent instanceof byte[]) {\n         return doSlice((byte[]) rawContent, meta);\n      } else if (rawContent instanceof InputStream) {\n         return doSlice((InputStream) rawContent, meta);\n      } else if (rawContent instanceof ByteSource) {\n         return doSlice((ByteSource) rawContent, meta);\n      } else {\n         return doSlice(input, meta);\n      }\n\n   }\n\n   protected Iterable<Payload> doSlice(Payload input, ContentMetadata meta) {\n      return doSlice(input.getInput(), meta);\n   }\n\n   protected Iterable<Payload> doSlice(String rawContent, ContentMetadata meta) {\n      return doSlice(ByteSource.wrap(rawContent.getBytes(Charsets.UTF_8)), meta);\n   }\n\n   protected Iterable<Payload> doSlice(byte[] rawContent, ContentMetadata meta) {\n      return doSlice(ByteSource.wrap(rawContent), meta);\n   }\n\n   protected Iterable<Payload> doSlice(File rawContent, ContentMetadata meta) {\n      return doSlice(Files.asByteSource(rawContent), meta);\n   }\n\n   protected Iterable<Payload> doSlice(InputStream rawContent, ContentMetadata meta) {\n      return new InputStreamPayloadIterable(rawContent, meta);\n   }\n\n   protected Iterable<Payload> doSlice(ByteSource rawContent, ContentMetadata meta) {\n      return new ByteSourcePayloadIterable(rawContent, meta);\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/io/payloads/BaseCipherPayload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.io.payloads;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.io.IOException;\nimport java.security.Key;\n\nimport javax.crypto.Cipher;\nimport javax.crypto.CipherInputStream;\n\nimport org.jclouds.crypto.Crypto;\nimport org.jclouds.io.Payload;\n\npublic abstract class BaseCipherPayload extends DelegatingPayload {\n\n   private final Key key;\n\n   protected final Crypto crypto;\n\n   public BaseCipherPayload(Crypto crypto, Payload delegate, Key key) {\n      super(delegate);\n      this.crypto = checkNotNull(crypto, \"crypto\");\n      this.key = checkNotNull(key, \"key\");\n   }\n\n   public abstract Cipher initializeCipher(Key key);\n\n   @Override\n   public CipherInputStream openStream() throws IOException {\n      return new CipherInputStream(super.openStream(), initializeCipher(key));\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/io/payloads/BaseImmutableContentMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.io.payloads;\n\nimport java.util.Date;\n\nimport org.jclouds.io.ContentMetadata;\nimport org.jclouds.io.ContentMetadataBuilder;\n\nimport com.google.common.base.Objects;\nimport com.google.common.hash.HashCode;\n\npublic class BaseImmutableContentMetadata implements ContentMetadata {\n\n   protected String cacheControl;\n   protected String contentType;\n   protected Long contentLength;\n   protected HashCode contentMD5;\n   protected String contentDisposition;\n   protected String contentLanguage;\n   protected String contentEncoding;\n   protected Date expires;\n\n   @Deprecated\n   public BaseImmutableContentMetadata(String contentType, Long contentLength, byte[] contentMD5,\n            String contentDisposition, String contentLanguage, String contentEncoding, Date expires) {\n      this(null, contentType, contentLength, contentMD5, contentDisposition, contentLanguage, contentEncoding, expires);\n   }\n\n   public BaseImmutableContentMetadata(String cacheControl, String contentType, Long contentLength, byte[] contentMD5,\n            String contentDisposition, String contentLanguage, String contentEncoding, Date expires) {\n      this.cacheControl = cacheControl;\n      this.contentType = contentType;\n      this.contentLength = contentLength;\n      this.contentMD5 = contentMD5 == null ? null : HashCode.fromBytes(contentMD5);\n      this.contentDisposition = contentDisposition;\n      this.contentLanguage = contentLanguage;\n      this.contentEncoding = contentEncoding;\n      this.expires = expires;\n   }\n\n   @Override\n   public String getCacheControl() {\n      return cacheControl;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Long getContentLength() {\n      return contentLength;\n   }\n\n   /** @deprecated use {@link #getContentMD5AsHashCode()} instead. */\n   @Deprecated\n   @Override\n   public byte[] getContentMD5() {\n      HashCode hashCode = getContentMD5AsHashCode();\n      return hashCode == null ? null : hashCode.asBytes();\n   }\n\n   @Override\n   public HashCode getContentMD5AsHashCode() {\n      return contentMD5;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getContentType() {\n      return contentType;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getContentDisposition() {\n      return this.contentDisposition;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getContentLanguage() {\n      return this.contentLanguage;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getContentEncoding() {\n      return this.contentEncoding;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Date getExpires() {\n      return expires;\n   }\n\n   @Override\n   public String toString() {\n      return \"[cacheControl=\" + cacheControl\n               + \"contentType=\" + contentType + \", contentLength=\" + contentLength + \", contentDisposition=\"\n               + contentDisposition + \", contentEncoding=\" + contentEncoding + \", contentLanguage=\" + contentLanguage\n               + \", contentMD5=\" + contentMD5 + \", expires = \" + expires + \"]\";\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(contentDisposition, contentEncoding, contentLanguage, contentLength, \n               contentMD5, contentType, expires);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      BaseImmutableContentMetadata other = (BaseImmutableContentMetadata) obj;\n      if (!Objects.equal(cacheControl, other.cacheControl)) {\n         return false;\n      }\n      if (contentDisposition == null) {\n         if (other.contentDisposition != null)\n            return false;\n      } else if (!contentDisposition.equals(other.contentDisposition))\n         return false;\n      if (contentEncoding == null) {\n         if (other.contentEncoding != null)\n            return false;\n      } else if (!contentEncoding.equals(other.contentEncoding))\n         return false;\n      if (contentLanguage == null) {\n         if (other.contentLanguage != null)\n            return false;\n      } else if (!contentLanguage.equals(other.contentLanguage))\n         return false;\n      if (contentLength == null) {\n         if (other.contentLength != null)\n            return false;\n      } else if (!contentLength.equals(other.contentLength))\n         return false;\n      if (!Objects.equal(contentMD5, other.contentMD5))\n         return false;\n      if (contentType == null) {\n         if (other.contentType != null)\n            return false;\n      } else if (!contentType.equals(other.contentType))\n         return false;\n      if (!Objects.equal(expires, other.expires)) {\n         return false;\n      }\n      return true;\n   }\n\n   @Override\n   public ContentMetadataBuilder toBuilder() {\n      return ContentMetadataBuilder.fromContentMetadata(this);\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/io/payloads/BaseMutableContentMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.io.payloads;\n\nimport java.util.Date;\n\nimport org.jclouds.io.ContentMetadata;\nimport org.jclouds.io.ContentMetadataBuilder;\nimport org.jclouds.io.MutableContentMetadata;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.hash.HashCode;\n\npublic class BaseMutableContentMetadata extends ContentMetadataBuilder implements MutableContentMetadata {\n\n   @Override\n   public String getCacheControl() {\n      return cacheControl;\n   }\n\n   @Override\n   public void setCacheControl(@Nullable String cacheControl) {\n      cacheControl(cacheControl);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Long getContentLength() {\n      return contentLength;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void setContentLength(@Nullable Long contentLength) {\n      contentLength(contentLength);\n   }\n\n   /** @deprecated use {@link #getContentMD5AsHashCode()} instead. */\n   @Deprecated\n   @Override\n   public byte[] getContentMD5() {\n      HashCode hashCode = getContentMD5AsHashCode();\n      return hashCode == null ? null : hashCode.asBytes();\n   }\n\n   @Override\n   public HashCode getContentMD5AsHashCode() {\n      return contentMD5;\n   }\n\n   /** @deprecated use {@link #setContentMD5(HashCode)} instead. */\n   @Deprecated\n   @Override\n   public void setContentMD5(byte[] md5) {\n      setContentMD5(md5 == null ? null : HashCode.fromBytes(md5));\n   }\n\n   @Override\n   public void setContentMD5(HashCode md5) {\n      contentMD5(md5);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getContentType() {\n      return contentType;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void setContentType(@Nullable String contentType) {\n      contentType(contentType);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void setContentDisposition(@Nullable String contentDisposition) {\n      contentDisposition(contentDisposition);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getContentDisposition() {\n      return this.contentDisposition;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void setContentLanguage(@Nullable String contentLanguage) {\n      contentLanguage(contentLanguage);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getContentLanguage() {\n      return this.contentLanguage;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void setContentEncoding(@Nullable String contentEncoding) {\n      contentEncoding(contentEncoding);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getContentEncoding() {\n      return this.contentEncoding;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void setExpires(@Nullable Date expires) {\n      expires(expires);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Date getExpires() {\n      return expires;\n   }\n\n   @Override\n   public BaseMutableContentMetadata toBuilder() {\n      return BaseMutableContentMetadata.fromContentMetadata(this);\n   }\n\n   public static BaseMutableContentMetadata fromContentMetadata(ContentMetadata in) {\n      return (BaseMutableContentMetadata) new BaseMutableContentMetadata()\n               .cacheControl(in.getCacheControl())\n               .contentDisposition(in.getContentDisposition())\n               .contentEncoding(in.getContentEncoding())\n               .contentLanguage(in.getContentLanguage())\n               .contentLength(in.getContentLength())\n               .contentMD5(in.getContentMD5())\n               .contentType(in.getContentType())\n               .expires(in.getExpires());\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/io/payloads/BasePayload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.io.payloads;\n\nimport com.google.common.base.Throwables;\nimport org.jclouds.io.MutableContentMetadata;\nimport org.jclouds.io.Payload;\n\nimport java.io.IOException;\nimport java.io.InputStream;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\npublic abstract class BasePayload<V> implements Payload {\n   protected final V content;\n   protected transient volatile boolean written;\n   protected MutableContentMetadata contentMetadata;\n   private boolean isSensitive;\n\n   protected BasePayload(V content) {\n      this(content, new BaseMutableContentMetadata());\n   }\n\n   protected BasePayload(V content, MutableContentMetadata contentMetadata) {\n      this.content = checkNotNull(content, \"content\");\n      this.contentMetadata = checkNotNull(contentMetadata, \"contentMetadata\");\n   }\n\n   @Override\n   public InputStream getInput() {\n      try {\n         return openStream();\n      } catch (IOException ioe) {\n         throw Throwables.propagate(ioe);\n      }\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public V getRawContent() {\n      return content;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((content == null) ? 0 : content.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (!(obj instanceof Payload))\n         return false;\n      Payload other = (Payload) obj;\n      if (content == null) {\n         if (other.getRawContent() != null)\n            return false;\n      } else if (!content.equals(other.getRawContent()))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"[content=\" + (content != null) + \", contentMetadata=\" + contentMetadata + \", written=\" + written + \", isSensitive=\" + isSensitive + \"]\";\n   }\n\n   /**\n    * By default we are repeatable.\n    */\n   @Override\n   public boolean isRepeatable() {\n      return true;\n   }\n\n   /**\n    * By default there are no resources to release.\n    */\n   @Override\n   public void release() {\n   }\n\n   /**\n    * Delegates to release()\n    */\n   @Override\n   public void close() {\n      release();\n   }\n\n   /**\n    * \n    * {@inheritDoc}\n    */\n   @Override\n   public MutableContentMetadata getContentMetadata() {\n      return contentMetadata;\n   }\n\n   /**\n    * \n    * {@inheritDoc}\n    */\n   @Override\n   public void setContentMetadata(MutableContentMetadata in) {\n      this.contentMetadata = in;\n   }\n\n   @Override\n   public void setSensitive(boolean isSensitive) {\n      this.isSensitive = isSensitive;\n   }\n\n   @Override\n   public boolean isSensitive() {\n      return this.isSensitive;\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/io/payloads/ByteArrayPayload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.io.payloads;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.InputStream;\n\npublic class ByteArrayPayload extends BasePayload<byte[]> {\n   public ByteArrayPayload(byte[] content) {\n      this(content, null);\n   }\n\n   public ByteArrayPayload(byte[] content, byte[] md5) {\n      super(content);\n      getContentMetadata().setContentLength(Long.valueOf(checkNotNull(content, \"content\").length));\n      getContentMetadata().setContentMD5(md5);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public InputStream openStream() {\n      return new ByteArrayInputStream(content);\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/io/payloads/ByteSourcePayload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.io.payloads;\n\nimport static org.jclouds.util.Closeables2.closeQuietly;\n\nimport java.io.IOException;\nimport java.io.InputStream;\n\nimport com.google.common.io.ByteSource;\nimport com.google.common.io.Closer;\n\n/**\n * A repeatable, ByteSource-backed Payload.\n */\npublic class ByteSourcePayload extends BasePayload<ByteSource> {\n   private final Closer closer = Closer.create();\n\n   public ByteSourcePayload(ByteSource content) {\n      super(content);\n   }\n\n   @Override\n   public InputStream openStream() throws IOException {\n      return closer.register(content.openStream());\n   }\n\n   @Override\n   public boolean isRepeatable() {\n      return true;\n   }\n\n   /**\n    * if we created the stream, then it is already consumed on close.\n    */\n   @Override\n   public void release() {\n      closeQuietly(closer);\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/io/payloads/DelegatingPayload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.io.payloads;\n\nimport com.google.common.base.Throwables;\nimport org.jclouds.io.MutableContentMetadata;\nimport org.jclouds.io.Payload;\n\nimport java.io.IOException;\nimport java.io.InputStream;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\npublic class DelegatingPayload implements Payload {\n\n   private final Payload delegate;\n   private boolean isSensitive;\n\n   public DelegatingPayload(Payload delegate) {\n      this.delegate = checkNotNull(delegate, \"delegate\");\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public InputStream openStream() throws IOException {\n      return delegate.openStream();\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public InputStream getInput() {\n      try {\n         return openStream();\n      } catch (IOException ioe) {\n         throw Throwables.propagate(ioe);\n      }\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Object getRawContent() {\n      return delegate.getInput();\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public boolean isRepeatable() {\n      return delegate.isRepeatable();\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public int hashCode() {\n      return delegate.hashCode();\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public boolean equals(Object obj) {\n      return delegate.equals(obj);\n\n   }\n\n   public Payload getDelegate() {\n      return delegate;\n   }\n\n   @Override\n   public void release() {\n      delegate.release();\n   }\n\n   @Override\n   public void close() throws IOException {\n      delegate.close();\n   }\n\n   @Override\n   public MutableContentMetadata getContentMetadata() {\n      return delegate.getContentMetadata();\n   }\n\n   @Override\n   public void setContentMetadata(MutableContentMetadata in) {\n       delegate.setContentMetadata(in);\n   }\n\n   @Override\n   public void setSensitive(boolean isSensitive) {\n      this.isSensitive = isSensitive;\n   }\n\n   @Override\n   public boolean isSensitive() {\n      return this.isSensitive;\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/io/payloads/FilePayload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.io.payloads;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.InputStream;\nimport java.io.IOException;\n\n\npublic class FilePayload extends BasePayload<File> {\n\n   public FilePayload(File content) {\n      super(content);\n      getContentMetadata().setContentLength(content.length());\n      checkNotNull(content, \"content\");\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public InputStream openStream() throws IOException {\n      return new FileInputStream(content);\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/io/payloads/InputStreamPayload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.io.payloads;\n\nimport static org.jclouds.util.Closeables2.closeQuietly;\n\nimport java.io.InputStream;\n\npublic class InputStreamPayload extends BasePayload<InputStream> {\n\n   public InputStreamPayload(InputStream content) {\n      super(content);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public InputStream openStream() {\n      return content;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public boolean isRepeatable() {\n      return false;\n   }\n\n   /**\n    * if we created the stream, then it is already consumed on close.\n    */\n   @Override\n   public void release() {\n      closeQuietly(content);\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/io/payloads/MultipartForm.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.io.payloads;\n\nimport static com.google.common.collect.Lists.newArrayList;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.SequenceInputStream;\nimport java.util.Collections;\nimport java.util.Map.Entry;\n\nimport com.google.common.collect.ImmutableList;\n\npublic class MultipartForm extends BasePayload<Iterable<? extends Part>> {\n   public static final String BOUNDARY = \"--JCLOUDS--\";\n   private static final String rn = \"\\r\\n\";\n   private static final String dd = \"--\";\n\n   private final String boundary;\n   private final Iterable<? extends Part> content;\n   private final boolean isRepeatable;\n\n   @SuppressWarnings(\"unchecked\")\n   public MultipartForm(String boundary, Iterable<? extends Part> content) {\n      super(content);\n      this.boundary = boundary;\n      this.content = content;\n\n      getContentMetadata().setContentType(\"multipart/form-data; boundary=\" + boundary);\n      String boundaryrn = boundary + rn;\n      boolean isRepeatable = true;\n      long contentLength = 0;\n      for (Part part : content) {\n         if (!part.isRepeatable())\n            isRepeatable = false;\n         contentLength += part.getContentMetadata().getContentLength()\n            + createHeaders(boundaryrn, part).getBytes().length\n            + createRn().length();\n      }\n      contentLength += createFooter(boundary).length();\n      getContentMetadata().setContentLength(contentLength);\n      this.isRepeatable = isRepeatable;\n   }\n\n   public MultipartForm(String boundary, Part... parts) {\n      this(boundary, newArrayList(parts));\n   }\n\n   public MultipartForm(Part... parts) {\n      this(BOUNDARY, parts);\n   }\n\n   private String createRn() {\n      return rn;\n   }\n\n   private String createHeaders(String boundaryrn, Part part) {\n      StringBuilder builder = new StringBuilder(dd).append(boundaryrn);\n      for (Entry<String, String> entry : part.getHeaders().entries()) {\n         String header = String.format(\"%s: %s%s\", entry.getKey(), entry.getValue(), rn);\n         builder.append(header);\n      }\n      builder.append(rn);\n      return builder.toString();\n   }\n\n   private static String createFooter(String boundary) {\n      return dd + boundary + dd + rn;\n   }\n\n   @Override\n   public InputStream openStream() throws IOException {\n      String boundaryrn = boundary + rn;\n      ImmutableList.Builder<InputStream> builder = ImmutableList.builder();\n      for (Part part : content) {\n         builder.add(new ByteArrayInputStream(createHeaders(boundaryrn, part).getBytes()))\n            .add(part.openStream())\n            .add(new ByteArrayInputStream(createRn().getBytes()));\n      }\n      builder.add(new ByteArrayInputStream(createFooter(boundary).getBytes()));\n      return new SequenceInputStream(Collections.enumeration(builder.build()));\n   }\n\n   @Override\n   public boolean isRepeatable() {\n      return isRepeatable;\n   }\n\n   @Override\n   public void release() {\n      for (Part part : content)\n         part.release();\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/io/payloads/Part.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.io.payloads;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.Multimap;\nimport com.google.common.net.HttpHeaders;\n\npublic class Part extends DelegatingPayload {\n   final String name;\n   final Multimap<String, String> headers;\n\n   private static class PartMap extends ImmutableMultimap.Builder<String, String> {\n\n      static Part.PartMap create(String name) {\n         Part.PartMap map = new PartMap();\n         map.put(\"Content-Disposition\", String.format(\"form-data; name=\\\"%s\\\"\", checkNotNull(name,\n                  \"name\")));\n         return map;\n      }\n\n      static Part.PartMap create(String name, String filename) {\n         Part.PartMap map = new PartMap();\n         map.put(\"Content-Disposition\", String.format(\"form-data; name=\\\"%s\\\"; filename=\\\"%s\\\"\",\n                  checkNotNull(name, \"name\"), checkNotNull(filename, \"filename\")));\n         return map;\n      }\n\n      Part.PartMap contentType(@Nullable String type) {\n         if (type != null)\n            put(HttpHeaders.CONTENT_TYPE, checkNotNull(type, \"type\"));\n         return this;\n      }\n\n      public static Part.PartMap create(String name, Payload delegate, Part.PartOptions options) {\n         String filename = options != null ? options.getFilename() : null;\n         if (delegate instanceof FilePayload)\n            filename = FilePayload.class.cast(delegate).getRawContent().getName();\n         Part.PartMap returnVal;\n         returnVal = (filename != null) ? create(name, filename) : create(name);\n         if (options != null)\n            returnVal.contentType(options.getContentType());\n         return returnVal;\n\n      }\n   }\n\n   private Part(String name, Part.PartMap map, Payload delegate) {\n      super(delegate);\n      this.name = name;\n      this.headers = checkNotNull(map, \"headers\").build();\n   }\n\n   public static class PartOptions {\n      private String contentType;\n      private String filename;\n\n      public Part.PartOptions contentType(String contentType) {\n         this.contentType = checkNotNull(contentType, \"contentType\");\n         return this;\n      }\n\n      public Part.PartOptions filename(String filename) {\n         this.filename = checkNotNull(filename, \"filename\");\n         return this;\n      }\n\n      public static class Builder {\n         public static Part.PartOptions contentType(String contentType) {\n            return new PartOptions().contentType(contentType);\n         }\n\n         public static Part.PartOptions filename(String filename) {\n            return new PartOptions().filename(filename);\n         }\n      }\n\n      public String getContentType() {\n         return contentType;\n      }\n\n      public String getFilename() {\n         return filename;\n      }\n   }\n\n   public static Part create(String name, String value) {\n      return new Part(name, PartMap.create(name), Payloads.newStringPayload(value));\n   }\n\n   public static Part create(String name, Payload delegate, Part.PartOptions options) {\n      return new Part(name, PartMap.create(name, delegate, options), delegate);\n   }\n\n   public Multimap<String, String> getHeaders() {\n      return headers;\n   }\n\n   public String getName() {\n      return name;\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/io/payloads/PhantomPayload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.io.payloads;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.io.InputStream;\n\nimport org.jclouds.io.ContentMetadata;\nimport org.jclouds.io.MutableContentMetadata;\n\npublic class PhantomPayload extends BasePayload<Object> {\n\n   public PhantomPayload() {\n      super(Object.class);\n   }\n\n   public PhantomPayload(ContentMetadata contentMetadata) {\n      this(BaseMutableContentMetadata.fromContentMetadata(checkNotNull(contentMetadata, \"contentMetadata\")));\n   }\n\n   public PhantomPayload(MutableContentMetadata contentMetadata) {\n      super(Object.class, checkNotNull(contentMetadata, \"contentMetadata\"));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public InputStream openStream() {\n      throw new UnsupportedOperationException();\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/io/payloads/RSADecryptingPayload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.io.payloads;\n\nimport java.security.InvalidKeyException;\nimport java.security.Key;\nimport java.security.NoSuchAlgorithmException;\n\nimport javax.crypto.Cipher;\nimport javax.crypto.NoSuchPaddingException;\n\nimport org.jclouds.crypto.Crypto;\nimport org.jclouds.io.Payload;\n\nimport com.google.common.base.Throwables;\n\npublic class RSADecryptingPayload extends BaseCipherPayload {\n\n   public RSADecryptingPayload(Crypto crypto, Payload delegate, Key key) {\n      super(crypto, delegate, key);\n   }\n\n   @Override\n   public Cipher initializeCipher(Key key) {\n      Cipher cipher = null;\n      try {\n         cipher = crypto.cipher(\"RSA\");\n         cipher.init(Cipher.DECRYPT_MODE, key);\n      } catch (NoSuchAlgorithmException e) {\n         Throwables.propagate(e);\n      } catch (NoSuchPaddingException e) {\n         Throwables.propagate(e);\n      } catch (InvalidKeyException e) {\n         Throwables.propagate(e);\n      }\n      return cipher;\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/io/payloads/RSAEncryptingPayload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.io.payloads;\n\nimport java.security.InvalidKeyException;\nimport java.security.Key;\nimport java.security.NoSuchAlgorithmException;\n\nimport javax.crypto.Cipher;\nimport javax.crypto.NoSuchPaddingException;\n\nimport org.jclouds.crypto.Crypto;\nimport org.jclouds.io.Payload;\n\nimport com.google.common.base.Throwables;\n\npublic class RSAEncryptingPayload extends BaseCipherPayload {\n\n   public RSAEncryptingPayload(Crypto crypto, Payload delegate, Key key) {\n      super(crypto, delegate, key);\n   }\n\n   @Override\n   public Cipher initializeCipher(Key key) {\n      Cipher cipher = null;\n      try {\n         cipher = crypto.cipher(\"RSA\");\n         cipher.init(Cipher.ENCRYPT_MODE, key);\n      } catch (NoSuchAlgorithmException e) {\n         Throwables.propagate(e);\n      } catch (NoSuchPaddingException e) {\n         Throwables.propagate(e);\n      } catch (InvalidKeyException e) {\n         Throwables.propagate(e);\n      }\n      return cipher;\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/io/payloads/StringPayload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.io.payloads;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.InputStream;\n\nimport com.google.common.base.Charsets;\n\n/**\n * This implementation converts the String to a byte array using UTF-8 encoding. If you wish to use\n * a different encoding, please use {@link ByteArrayPayload}.\n * \n */\npublic class StringPayload extends BasePayload<String> {\n\n   private final byte[] bytes;\n\n   // it is possible to discover length by walking the string and updating current length based on\n   // character code. However, this is process intense, and assumes an encoding type of UTF-8\n   public StringPayload(String content) {\n      super(content);\n      this.bytes = content.getBytes(Charsets.UTF_8);\n      getContentMetadata().setContentLength(Long.valueOf(bytes.length));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public InputStream openStream() {\n      return new ByteArrayInputStream(bytes);\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/io/payloads/UrlEncodedFormPayload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.io.payloads;\nimport static com.google.common.net.MediaType.FORM_DATA;\nimport static org.jclouds.http.utils.Queries.encodeQueryLine;\nimport static org.jclouds.util.Strings2.toInputStream;\n\nimport java.io.InputStream;\n\nimport com.google.common.collect.Multimap;\n\npublic class UrlEncodedFormPayload extends BasePayload<String> {\n   public UrlEncodedFormPayload(Multimap<String, String> formParams) {\n      super(encodeQueryLine(formParams));\n      getContentMetadata().setContentLength((long) content.length());\n      getContentMetadata().setContentType(FORM_DATA.toString());\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public InputStream openStream() {\n      return toInputStream(content);\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/javax/annotation/Nullable.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.javax.annotation;\n\n@java.lang.annotation.Documented\n@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)\npublic @interface Nullable {\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/javax/annotation/concurrent/NotThreadSafe.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.javax.annotation.concurrent;\n\n@java.lang.annotation.Documented\n@java.lang.annotation.Target({java.lang.annotation.ElementType.TYPE})\n@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.CLASS)\npublic @interface NotThreadSafe {\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/json/Json.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.json;\n\nimport java.io.InputStream;\nimport java.lang.reflect.Type;\nimport java.nio.charset.Charset;\n\npublic interface Json {\n   /**\n    * Serialize the object into json. If the object is a generic type, use\n    * {@link #toJson(Object, Type)}\n    */\n   String toJson(Object src);\n\n   /**\n    * Serialize the generic object into json. If the object is not a generic, use\n    * {@link #toJson(Object, Type)}\n    */\n   String toJson(Object src, Type type);\n\n   /**\n    * Deserialize the generic object from json. If the object is not a generic type, use\n    * {@link #fromJson(Object, Class)}\n    */\n   <T> T fromJson(String json, Type type);\n\n   /**\n    * Deserialize the object from json. If the object is a generic type, use\n    * {@link #fromJson(Object, Type)}\n    */\n   <T> T fromJson(String json, Class<T> classOfT);\n   \n   /**\n    * Deserialize the generic object from json. If the object is not a generic type, use\n    * {@link #fromJson(Object, Class)}\n    */\n   <T> T fromJson(InputStream json, Charset charset, Type type);\n\n   /**\n    * Deserialize the object from json. If the object is a generic type, use\n    * {@link #fromJson(Object, Type)}\n    */\n   <T> T fromJson(InputStream json, Charset charset, Class<T> classOfT);\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/json/SerializedNames.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.json;\n\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\nimport com.google.common.annotations.Beta;\n\n/**\n * This annotation identifies the canonical factory method on an {@code AutoValue} type used for json.\n * It also dictates the serialized naming convention of the fields. This is required as there's currently\n * no way to add annotations to the fields generated by {@code AutoValue}.\n *\n * <p/>Example:\n * <pre>{@code @AutoValue class Resource {\n *   abstract String id();\n *   @Nullable abstract Map<String, String> metadata();\n *\n *   @SerializedNames({ \"Id\", \"Metadata\" }) // Note case format is controlled here!\n *   static Resource create(String id, Map<String, String> metadata) {\n *     return new AutoValue_Resource(id, metadata);\n *   }\n * }}</pre>\n */\n@Beta @Target(METHOD) @Retention(RUNTIME)\npublic @interface SerializedNames {\n\n   /**\n    * Ordered values that dictate the naming convention for serialization.\n    *\n    * <h3>Note</h3>\n    * The order of these names must exactly match the factory method parameters and also match the order of the\n    * auto-value constructor parameters.\n    */\n   String[] value();\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/json/config/GsonModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.json.config;\n\nimport static com.google.common.io.BaseEncoding.base16;\n\nimport java.beans.ConstructorProperties;\nimport java.io.File;\nimport java.io.IOException;\nimport java.lang.reflect.Type;\nimport java.util.Date;\nimport java.util.Enumeration;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport jakarta.inject.Provider;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.domain.JsonBall;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.json.Json;\nimport org.jclouds.json.SerializedNames;\nimport com.google.gson.ReflectionAccessFilter;\nimport com.google.gson.internal.ConstructorConstructor;\nimport com.google.gson.internal.Excluder;\nimport com.google.gson.internal.JsonReaderInternalAccess;\nimport org.jclouds.json.internal.DeserializationConstructorAndReflectiveTypeAdapterFactory;\nimport org.jclouds.json.internal.EnumTypeAdapterThatReturnsFromValue;\nimport org.jclouds.json.internal.GsonWrapper;\nimport org.jclouds.json.internal.NamingStrategies.AnnotationConstructorNamingStrategy;\nimport org.jclouds.json.internal.NamingStrategies.AnnotationOrNameFieldNamingStrategy;\nimport org.jclouds.json.internal.NamingStrategies.ExtractNamed;\nimport org.jclouds.json.internal.NamingStrategies.ExtractSerializedName;\nimport org.jclouds.json.internal.NullFilteringTypeAdapterFactories.CollectionTypeAdapterFactory;\nimport org.jclouds.json.internal.NullFilteringTypeAdapterFactories.FluentIterableTypeAdapterFactory;\nimport org.jclouds.json.internal.NullFilteringTypeAdapterFactories.ImmutableListTypeAdapterFactory;\nimport org.jclouds.json.internal.NullFilteringTypeAdapterFactories.ImmutableMapTypeAdapterFactory;\nimport org.jclouds.json.internal.NullFilteringTypeAdapterFactories.ImmutableSetTypeAdapterFactory;\nimport org.jclouds.json.internal.NullFilteringTypeAdapterFactories.IterableTypeAdapterFactory;\nimport org.jclouds.json.internal.NullFilteringTypeAdapterFactories.ListTypeAdapterFactory;\nimport org.jclouds.json.internal.NullFilteringTypeAdapterFactories.MapTypeAdapterFactory;\nimport org.jclouds.json.internal.NullFilteringTypeAdapterFactories.MultimapTypeAdapterFactory;\nimport org.jclouds.json.internal.NullFilteringTypeAdapterFactories.SetTypeAdapterFactory;\nimport org.jclouds.json.internal.NullHackJsonLiteralAdapter;\nimport org.jclouds.json.internal.OptionalTypeAdapterFactory;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMap.Builder;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Maps;\nimport com.google.common.collect.Sets;\nimport com.google.common.primitives.Bytes;\nimport com.google.gson.ExclusionStrategy;\nimport com.google.gson.FieldAttributes;\nimport com.google.gson.FieldNamingStrategy;\nimport com.google.gson.Gson;\nimport com.google.gson.GsonBuilder;\nimport com.google.gson.InstanceCreator;\nimport com.google.gson.TypeAdapter;\nimport com.google.gson.TypeAdapterFactory;\nimport com.google.gson.reflect.TypeToken;\nimport com.google.gson.stream.JsonReader;\nimport com.google.gson.stream.JsonToken;\nimport com.google.gson.stream.JsonWriter;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.ImplementedBy;\nimport com.google.inject.Inject;\nimport com.google.inject.Provides;\n\npublic class GsonModule extends AbstractModule {\n\n   @SuppressWarnings(\"rawtypes\")\n   @Provides\n   @Singleton\n   final Gson provideGson(TypeAdapter<JsonBall> jsonAdapter, DateAdapter adapter, ByteListAdapter byteListAdapter,\n         ByteArrayAdapter byteArrayAdapter, PropertiesAdapter propertiesAdapter, JsonAdapterBindings bindings,\n         CredentialsAdapterFactory credentialsAdapterFactory, OptionalTypeAdapterFactory optional,\n         SetTypeAdapterFactory set, ImmutableSetTypeAdapterFactory immutableSet, MapTypeAdapterFactory map,\n         MultimapTypeAdapterFactory multimap, IterableTypeAdapterFactory iterable,\n         CollectionTypeAdapterFactory collection, ListTypeAdapterFactory list,\n         ImmutableListTypeAdapterFactory immutableList, FluentIterableTypeAdapterFactory fluentIterable,\n         ImmutableMapTypeAdapterFactory immutableMap, DefaultExclusionStrategy exclusionStrategy) {\n\n      FieldNamingStrategy serializationPolicy = new AnnotationOrNameFieldNamingStrategy(ImmutableSet.of(\n            new ExtractSerializedName(), new ExtractNamed()));\n\n      GsonBuilder builder = new GsonBuilder().setFieldNamingStrategy(serializationPolicy)\n                                             .setExclusionStrategies(exclusionStrategy);\n\n      // simple (type adapters)\n      builder.registerTypeAdapter(Properties.class, propertiesAdapter.nullSafe());\n      builder.registerTypeAdapter(Date.class, adapter.nullSafe());\n      builder.registerTypeAdapter(byte[].class, byteArrayAdapter.nullSafe());\n      builder.registerTypeAdapter(JsonBall.class, jsonAdapter.nullSafe());\n      builder.registerTypeAdapter(File.class, new FileTypeAdapter());\n\n      builder.registerTypeAdapterFactory(credentialsAdapterFactory);\n      builder.registerTypeAdapterFactory(optional);\n      builder.registerTypeAdapterFactory(iterable);\n      builder.registerTypeAdapterFactory(collection);\n      builder.registerTypeAdapterFactory(list);\n      builder.registerTypeAdapter(new TypeToken<List<Byte>>() {\n      }.getType(), byteListAdapter.nullSafe());\n      builder.registerTypeAdapterFactory(immutableList);\n      builder.registerTypeAdapterFactory(set);\n      builder.registerTypeAdapterFactory(immutableSet);\n      builder.registerTypeAdapterFactory(map);\n      builder.registerTypeAdapterFactory(multimap);\n      builder.registerTypeAdapterFactory(fluentIterable);\n      builder.registerTypeAdapterFactory(immutableMap);\n\n      AnnotationConstructorNamingStrategy deserializationPolicy = new AnnotationConstructorNamingStrategy(\n            ImmutableSet.of(ConstructorProperties.class, SerializedNames.class, Inject.class),\n            ImmutableSet.of(new ExtractNamed()));\n\n      builder.registerTypeAdapterFactory(new DeserializationConstructorAndReflectiveTypeAdapterFactory(\n            new ConstructorConstructor(ImmutableMap.<Type, InstanceCreator<?>>of(), /*useJdkUnsafe=*/ false, ImmutableList.<ReflectionAccessFilter>of()), serializationPolicy,\n            Excluder.DEFAULT, deserializationPolicy));\n\n      // complicated (serializers/deserializers as they need context to operate)\n      builder.registerTypeHierarchyAdapter(Enum.class, new EnumTypeAdapterThatReturnsFromValue());\n\n      for (Map.Entry<Type, Object> binding : bindings.getBindings().entrySet()) {\n         builder.registerTypeAdapter(binding.getKey(), binding.getValue());\n      }\n\n      for (TypeAdapterFactory factory : bindings.getFactories()) {\n         builder.registerTypeAdapterFactory(factory);\n      }\n\n      return builder.create();\n   }\n\n   @ImplementedBy(NoExclusions.class)\n   public interface DefaultExclusionStrategy extends ExclusionStrategy {\n   }\n\n   public static class NoExclusions implements DefaultExclusionStrategy {\n      public boolean shouldSkipField(FieldAttributes f) {\n         return false;\n      }\n\n      public boolean shouldSkipClass(Class<?> clazz) {\n         return false;\n      }\n   }\n\n   @ImplementedBy(CDateAdapter.class)\n   public abstract static class DateAdapter extends TypeAdapter<Date> {\n\n   }\n\n   @Provides\n   @Singleton\n   protected final TypeAdapter<JsonBall> provideJsonBallAdapter(NullHackJsonBallAdapter in) {\n      return in;\n   }\n\n   public static class NullHackJsonBallAdapter extends NullHackJsonLiteralAdapter<JsonBall> {\n\n      @Override\n      protected JsonBall createJsonLiteralFromRawJson(String json) {\n         return new JsonBall(json);\n      }\n\n   }\n\n   @ImplementedBy(HexByteListAdapter.class)\n   public abstract static class ByteListAdapter extends TypeAdapter<List<Byte>> {\n\n   }\n\n   @ImplementedBy(HexByteArrayAdapter.class)\n   public abstract static class ByteArrayAdapter extends TypeAdapter<byte[]> {\n\n   }\n\n   @Singleton\n   public static class HexByteListAdapter extends ByteListAdapter {\n\n      @Override\n      public void write(JsonWriter writer, List<Byte> value) throws IOException {\n         writer.value(base16().lowerCase().encode(Bytes.toArray(value)));\n      }\n\n      @Override\n      public List<Byte> read(JsonReader reader) throws IOException {\n         return Bytes.asList(base16().lowerCase().decode(reader.nextString()));\n      }\n\n   }\n\n   @Singleton\n   public static class HexByteArrayAdapter extends ByteArrayAdapter {\n\n      @Override\n      public void write(JsonWriter writer, byte[] value) throws IOException {\n         writer.value(base16().lowerCase().encode(value));\n      }\n\n      @Override\n      public byte[] read(JsonReader reader) throws IOException {\n         return base16().lowerCase().decode(reader.nextString());\n      }\n   }\n\n   @Singleton\n   public static class Iso8601DateAdapter extends DateAdapter {\n      private final DateService dateService;\n\n      @Inject\n      public Iso8601DateAdapter(DateService dateService) {\n         this.dateService = dateService;\n      }\n\n      public void write(JsonWriter writer, Date value) throws IOException {\n         writer.value(dateService.iso8601DateFormat(value));\n      }\n\n      public Date read(JsonReader reader) throws IOException {\n         return parseDate(reader.nextString());\n      }\n\n      protected Date parseDate(String toParse) {\n         try {\n            return dateService.iso8601DateParse(toParse);\n         } catch (RuntimeException e) {\n            return dateService.iso8601SecondsDateParse(toParse);\n         }\n      }\n\n   }\n\n   @Singleton\n   public static class PropertiesAdapter extends TypeAdapter<Properties> {\n      private final Provider<Gson> gson;\n      private final TypeToken<Map<String, String>> mapType = new TypeToken<Map<String, String>>() {\n      };\n\n      @Inject\n      public PropertiesAdapter(Provider<Gson> gson) {\n         this.gson = gson;\n      }\n\n      @Override\n      public void write(JsonWriter out, Properties value) throws IOException {\n         Builder<String, String> srcMap = ImmutableMap.builder();\n         for (Enumeration<?> propNames = value.propertyNames(); propNames.hasMoreElements();) {\n            String propName = (String) propNames.nextElement();\n            srcMap.put(propName, value.getProperty(propName));\n         }\n         gson.get().getAdapter(mapType).write(out, srcMap.build());\n      }\n\n      @Override\n      public Properties read(JsonReader in) throws IOException {\n         Properties props = new Properties();\n         in.beginObject();\n         while (in.hasNext()) {\n            JsonReaderInternalAccess.INSTANCE.promoteNameToValue(in);\n            props.setProperty(in.nextString(), in.nextString());\n         }\n         in.endObject();\n         return props;\n      }\n\n   }\n\n   @Singleton\n   public static class CDateAdapter extends DateAdapter {\n      private final DateService dateService;\n\n      @Inject\n      public CDateAdapter(DateService dateService) {\n         this.dateService = dateService;\n      }\n\n      public void write(JsonWriter writer, Date value) throws IOException {\n         writer.value(dateService.cDateFormat(value));\n      }\n\n      public Date read(JsonReader reader) throws IOException {\n         return dateService.cDateParse(reader.nextString());\n      }\n\n   }\n\n   @Singleton\n   public static class LongDateAdapter extends DateAdapter {\n\n      public void write(JsonWriter writer, Date value) throws IOException {\n         writer.value(value.getTime());\n      }\n\n      public Date read(JsonReader reader) throws IOException {\n         long toParse = reader.nextLong();\n         if (toParse == -1)\n            return null;\n         return new Date(toParse);\n      }\n   }\n\n   private static class FileTypeAdapter extends TypeAdapter<File> {\n      @Override\n      public void write(JsonWriter out, File file) throws IOException {\n         if (file == null) {\n            out.nullValue();\n         } else {\n            out.value(file.getPath());\n         }\n      }\n\n      @Override\n      public File read(JsonReader in) throws IOException {\n         if (in.peek() == JsonToken.NULL) {\n            in.nextNull();\n            return null;\n         } else {\n            return new File(in.nextString());\n         }\n      }\n   }\n\n   /** Special cases serialization for {@linkplain LoginCredentials} and normalizes all others. */\n   public static class CredentialsAdapterFactory extends TypeAdapter<Credentials> implements TypeAdapterFactory {\n\n      @Override public void write(JsonWriter out, Credentials credentials) throws IOException {\n         out.beginObject();\n         if (credentials instanceof LoginCredentials) {\n            LoginCredentials login = (LoginCredentials) credentials;\n            out.name(\"user\");\n            out.value(login.getUser());\n            out.name(\"password\");\n            out.value(login.getOptionalPassword().orNull());\n            out.name(\"privateKey\");\n            out.value(login.getOptionalPrivateKey().orNull());\n            if (login.shouldAuthenticateSudo()) {\n               out.name(\"authenticateSudo\");\n               out.value(login.shouldAuthenticateSudo());\n            }\n         } else {\n            out.name(\"identity\");\n            out.value(credentials.identity);\n            out.name(\"credential\");\n            out.value(credentials.credential);\n         }\n         out.endObject();\n      }\n\n      @Override public Credentials read(JsonReader in) throws IOException {\n         LoginCredentials.Builder builder = LoginCredentials.builder();\n         String identity = null;\n         String credential = null;\n         in.beginObject();\n         while (in.hasNext()) {\n            String name = in.nextName();\n            if (name.equals(\"identity\")) {\n               identity = in.nextString();\n            } else if (name.equals(\"credential\")) {\n               credential = in.nextString();\n            } else if (name.equals(\"user\")) {\n               builder.user(in.nextString());\n            } else if (name.equals(\"password\")) {\n               builder.password(in.nextString());\n            } else if (name.equals(\"privateKey\")) {\n               builder.privateKey(in.nextString());\n            } else if (name.equals(\"authenticateSudo\")) {\n               builder.authenticateSudo(in.nextBoolean());\n            } else {\n               in.skipValue();\n            }\n         }\n         in.endObject();\n         LoginCredentials result = builder.build();\n         return result != null ? result : new Credentials(identity, credential);\n      }\n\n      @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {\n         if (!(Credentials.class.isAssignableFrom(typeToken.getRawType()))) {\n            return null;\n         }\n         return (TypeAdapter<T>) this;\n      }\n   }\n\n   @Singleton\n   public static class JsonAdapterBindings {\n      private final Map<Type, Object> bindings = Maps.newHashMap();\n      private final Set<TypeAdapterFactory> factories = Sets.newHashSet();\n\n      @com.google.inject.Inject(optional = true)\n      public void setBindings(Map<Type, Object> bindings) {\n         this.bindings.putAll(bindings);\n      }\n\n      @com.google.inject.Inject(optional = true)\n      public void setFactories(Set<TypeAdapterFactory> factories) {\n         this.factories.addAll(factories);\n      }\n\n      public Map<Type, Object> getBindings() {\n         return bindings;\n      }\n\n      public Set<TypeAdapterFactory> getFactories() {\n         return factories;\n      }\n   }\n\n   @Override\n   protected void configure() {\n      bind(Json.class).to(GsonWrapper.class);\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/json/internal/DeserializationConstructorAndReflectiveTypeAdapterFactory.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.json.internal;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.reflect.Reflection2.typeToken;\n\nimport java.io.IOException;\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Modifier;\nimport java.util.List;\nimport java.util.Map;\n\nimport com.google.gson.ReflectionAccessFilter;\nimport com.google.gson.internal.bind.JsonAdapterAnnotationTypeAdapterFactory;\nimport com.google.gson.internal.ConstructorConstructor;\nimport com.google.gson.internal.Excluder;\nimport com.google.gson.internal.bind.ReflectiveTypeAdapterFactory;\nimport org.jclouds.json.internal.NamingStrategies.AnnotationConstructorNamingStrategy;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMap.Builder;\nimport com.google.common.reflect.Invokable;\nimport com.google.common.reflect.Parameter;\nimport com.google.gson.FieldNamingStrategy;\nimport com.google.gson.Gson;\nimport com.google.gson.JsonSyntaxException;\nimport com.google.gson.TypeAdapter;\nimport com.google.gson.TypeAdapterFactory;\nimport com.google.gson.reflect.TypeToken;\nimport com.google.gson.stream.JsonReader;\nimport com.google.gson.stream.JsonToken;\nimport com.google.gson.stream.JsonWriter;\n\n/**\n * Creates type adapters for types handled in the following ways:\n * <p/>\n * <ul>\n * <li>Deserialization</li>\n * If there's an annotation designating a parameterized constructor, invoke that for fields correlating to named\n * parameter annotations. Otherwise, use {@link ConstructorConstructor}, and set fields via reflection.\n * <p/>\n * Notes: primitive constructor params are set to the Java defaults (0 or false) if not present; and the empty object\n * ({}) is treated as a null if the constructor for the object throws an NPE.\n * <li>Serialization</li> Serialize based on reflective access to fields, delegating to ReflectiveTypeAdaptor.\n * </ul>\n * <h3>Example: Using javax inject to select a constructor and corresponding named parameters</h3>\n * <p/>\n * \n * <pre>\n * \n * import NamingStrategies.*;\n * \n * serializationStrategy = new AnnotationOrNameFieldNamingStrategy(\n *    new ExtractSerializedName(), new ExtractNamed());\n * \n * deserializationStrategy = new AnnotationConstructorNamingStrategy(\n *    ImmutableSet.of(jakarta.inject.Inject.class),\n *    ImmutableSet.of(new ExtractNamed()));\n *    \n * factory = new DeserializationConstructorAndReflectiveTypeAdapterFactory(new ConstructorConstructor(),\n *      serializationStrategy, Excluder.DEFAULT, deserializationStrategy);\n * \n * gson = new GsonBuilder(serializationStrategy).registerTypeAdapterFactory(factory).create();\n * \n * </pre>\n * <p/>\n * The above would work fine on the following class, which has no gson-specific annotations:\n * <p/>\n * \n * <pre>\n * private static class ImmutableAndVerifiedInCtor {\n *    final int foo;\n *    &#064;Named(&quot;_bar&quot;)\n *    final int bar;\n * \n *    &#064;Inject\n *    ImmutableAndVerifiedInCtor(@Named(&quot;foo&quot;) int foo, @Named(&quot;_bar&quot;) int bar) {\n *       if (foo &lt; 0)\n *          throw new IllegalArgumentException(&quot;negative!&quot;);\n *       this.foo = foo;\n *       this.bar = bar;\n *    }\n * }\n * </pre>\n * <p/>\n * <br/>\n */\npublic final class DeserializationConstructorAndReflectiveTypeAdapterFactory implements TypeAdapterFactory {\n   private final AnnotationConstructorNamingStrategy constructorFieldNamingPolicy;\n   private final ReflectiveTypeAdapterFactory delegateFactory;\n\n   /**\n    * @see ReflectiveTypeAdapterFactory\n    */\n   public DeserializationConstructorAndReflectiveTypeAdapterFactory(ConstructorConstructor constructorConstructor,\n         FieldNamingStrategy serializationFieldNamingPolicy, Excluder excluder,\n         AnnotationConstructorNamingStrategy deserializationFieldNamingPolicy) {\n      this.constructorFieldNamingPolicy = checkNotNull(deserializationFieldNamingPolicy,\n            \"deserializationFieldNamingPolicy\");\n      this.delegateFactory = new ReflectiveTypeAdapterFactory(constructorConstructor, checkNotNull(\n            serializationFieldNamingPolicy, \"fieldNamingPolicy\"), checkNotNull(excluder, \"excluder\"),\n              new JsonAdapterAnnotationTypeAdapterFactory(constructorConstructor), ImmutableList.<ReflectionAccessFilter>of());\n   }\n\n   public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {\n      com.google.common.reflect.TypeToken<T> token = typeToken(type.getType());\n      Invokable<T, T> deserializationTarget = constructorFieldNamingPolicy.getDeserializer(token);\n\n      if (deserializationTarget == null) {\n         return null; // allow GSON to choose the correct Adapter (can't simply return delegateFactory.create())\n      }\n      // @AutoValue is SOURCE retention, which means it cannot be looked up at runtime.\n      // Assume abstract types built by static methods are AutoValue.\n      if (Modifier.isAbstract(type.getRawType().getModifiers()) && deserializationTarget.isStatic()) {\n         // Lookup the generated AutoValue class, whose fields must be read for serialization.\n         String packageName = type.getRawType().getPackage().getName();\n         String autoClassName = type.getRawType().getName().replace('$', '_')\n               .replace(packageName + \".\", packageName + \".AutoValue_\");\n         try {\n            type = (TypeToken<T>) TypeToken.get(type.getRawType().getClassLoader().loadClass(autoClassName));\n         } catch (ClassNotFoundException ignored) {\n         }\n      }\n      return new DeserializeIntoParameterizedConstructor<T>(delegateFactory.create(gson, type), deserializationTarget,\n            getParameterReaders(gson, deserializationTarget));\n   }\n\n   private static final class DeserializeIntoParameterizedConstructor<T> extends TypeAdapter<T> {\n      private final TypeAdapter<T> serializer;\n      private final Invokable<T, T> parameterizedCtor;\n      private final Map<String, ParameterReader<?>> parameterReaders;\n\n      private DeserializeIntoParameterizedConstructor(TypeAdapter<T> serializer, Invokable<T, T> deserializationCtor,\n            Map<String, ParameterReader<?>> parameterReaders) {\n         this.serializer = serializer;\n         this.parameterizedCtor = deserializationCtor;\n         this.parameterReaders = parameterReaders;\n      }\n\n      @Override\n      public T read(JsonReader in) throws IOException {\n         if (in.peek() == JsonToken.NULL) {\n            in.nextNull();\n            return null;\n         }\n\n         List<Parameter> params = parameterizedCtor.getParameters();\n         Object[] values = new Object[params.size()];\n         boolean empty = true;\n\n         // Set all primitive constructor params to defaults\n         for (Parameter param : params) {\n            if (param.getType().getRawType() == boolean.class) {\n               values[param.hashCode()] = Boolean.FALSE;\n            } else if (param.getType().getRawType().isPrimitive()) {\n               values[param.hashCode()] = 0;\n            }\n         }\n\n         try {\n            in.beginObject();\n            while (in.hasNext()) {\n               empty = false;\n               String name = in.nextName();\n               ParameterReader<?> parameter = parameterReaders.get(name);\n               if (parameter == null || in.peek() == JsonToken.NULL) {\n                  in.skipValue();\n               } else {\n                  Object value = parameter.read(in);\n                  if (value != null)\n                     values[parameter.position] = value;\n               }\n            }\n         } catch (IllegalStateException e) {\n            throw new JsonSyntaxException(e);\n         }\n\n         for (Parameter param : params) {\n            if (param.getType().getRawType().isPrimitive()) {\n               checkArgument(values[param.hashCode()] != null,\n                  \"Primitive param[%s] in constructor %s cannot be absent!\", param.hashCode(), parameterizedCtor);\n            } else if (param.getType().getRawType() == Optional.class && values[param.hashCode()] == null) {\n               values[param.hashCode()] = Optional.absent();\n            }\n         }\n         in.endObject();\n\n         try {\n            return newInstance(values);\n         } catch (NullPointerException ex) {\n            // If {} was found and constructor threw NPE, we treat the field as null\n            if (empty && values.length > 0) {\n               return null;\n            }\n            throw ex;\n         }\n      }\n\n      /**\n       * pass to delegate\n       */\n      @Override\n      public void write(JsonWriter out, T value) throws IOException {\n         serializer.write(out, value);\n      }\n\n      private T newInstance(Object[] ctorParams) throws AssertionError {\n         try {\n            return parameterizedCtor.invoke(null, ctorParams);\n         } catch (IllegalAccessException e) {\n            throw new AssertionError(e);\n         } catch (InvocationTargetException e) {\n            if (e.getCause() instanceof RuntimeException)\n               throw RuntimeException.class.cast(e.getCause());\n            throw new AssertionError(e);\n         }\n      }\n\n      @Override\n      public int hashCode() {\n         return Objects.hashCode(serializer, parameterizedCtor, parameterReaders);\n      }\n\n      @Override\n      public boolean equals(Object obj) {\n         if (this == obj)\n            return true;\n         if (obj == null || getClass() != obj.getClass())\n            return false;\n         DeserializeIntoParameterizedConstructor<?> that = DeserializeIntoParameterizedConstructor.class.cast(obj);\n         return Objects.equal(this.serializer, that.serializer)\n               && Objects.equal(this.parameterizedCtor, that.parameterizedCtor)\n               && Objects.equal(this.parameterReaders, that.parameterReaders);\n      }\n\n      @Override\n      public String toString() {\n         return MoreObjects.toStringHelper(this).add(\"parameterizedCtor\", parameterizedCtor)\n               .add(\"parameterReaders\", parameterReaders).add(\"serializer\", serializer).toString();\n      }\n\n   }\n\n   // logic borrowed from ReflectiveTypeAdapterFactory\n   static class ParameterReader<T> {\n      final String name;\n      final int position;\n      final TypeAdapter<T> typeAdapter;\n\n      ParameterReader(int position, String name, TypeAdapter<T> typeAdapter) {\n         this.name = name;\n         this.position = position;\n         this.typeAdapter = typeAdapter;\n      }\n\n      public Object read(JsonReader reader) throws IOException {\n         return typeAdapter.read(reader);\n      }\n\n      @Override\n      public boolean equals(Object obj) {\n         if (obj instanceof ParameterReader) {\n            ParameterReader<?> that = ParameterReader.class.cast(obj);\n            return position == that.position && name.equals(that.name);\n         }\n         return false;\n      }\n\n      @Override\n      public int hashCode() {\n         return Objects.hashCode(position, name);\n      }\n\n      @Override\n      public String toString() {\n         return typeAdapter + \" arg\" + position;\n      }\n   }\n\n   private <T> Map<String, ParameterReader<?>> getParameterReaders(Gson context, Invokable<T, T> deserializationCtor) {\n      Builder<String, ParameterReader<?>> result = ImmutableMap.builder();\n      for (Parameter param : deserializationCtor.getParameters()) {\n         TypeAdapter<?> adapter = context.getAdapter(TypeToken.get(param.getType().getType()));\n         String parameterName = constructorFieldNamingPolicy.translateName(deserializationCtor, param.hashCode());\n         checkArgument(parameterName != null, deserializationCtor + \" parameter \" + 0 + \" failed to be named by \"\n               + constructorFieldNamingPolicy);\n         @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n         ParameterReader<?> parameterReader = new ParameterReader(param.hashCode(), parameterName, adapter);\n         result.put(parameterReader.name, parameterReader);\n      }\n      return result.build();\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/json/internal/EnumTypeAdapterThatReturnsFromValue.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.json.internal;\n\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport java.lang.reflect.Type;\n\nimport com.google.common.reflect.Invokable;\nimport com.google.gson.JsonDeserializationContext;\nimport com.google.gson.JsonDeserializer;\nimport com.google.gson.JsonElement;\nimport com.google.gson.JsonParseException;\nimport com.google.gson.JsonPrimitive;\nimport com.google.gson.JsonSerializationContext;\nimport com.google.gson.JsonSerializer;\n\n@SuppressWarnings(\"unchecked\")\npublic class EnumTypeAdapterThatReturnsFromValue<T extends Enum<T>> implements JsonSerializer<T>, JsonDeserializer<T> {\n   public JsonElement serialize(T src, Type typeOfSrc, JsonSerializationContext context) {\n      return new JsonPrimitive(src.toString());\n   }\n\n   @SuppressWarnings(\"cast\")\n   public T deserialize(JsonElement json, Type classOfT, JsonDeserializationContext context) throws JsonParseException {\n      try {\n         return (T) Enum.valueOf((Class<T>) classOfT, json.getAsString());\n      } catch (IllegalArgumentException e) {\n         try {\n            Invokable<?, Object> converter = method((Class<?>) classOfT, \"fromValue\", String.class);\n            return (T) converter.invoke(null, json.getAsString());\n         } catch (Exception e1) {\n            throw e;\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/json/internal/GsonWrapper.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.json.internal;\n\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.lang.reflect.Type;\nimport java.nio.charset.Charset;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.json.Json;\n\nimport com.google.common.collect.ForwardingObject;\nimport com.google.gson.Gson;\n\n@Singleton\npublic class GsonWrapper extends ForwardingObject implements Json  {\n\n   private final Gson gson;\n\n   @Inject\n   public GsonWrapper(Gson gson) {\n      this.gson = gson;\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <T> T fromJson(String json, Type type) {\n      return (T) gson.fromJson(json, type);\n   }\n\n   @Override\n   public <T> T fromJson(String json, Class<T> classOfT) {\n      return gson.fromJson(json, classOfT);\n   }\n   \n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <T> T fromJson(InputStream json, Charset charset, Type type) {\n      return (T) gson.fromJson(new InputStreamReader(json, charset), type);\n   }\n\n   @Override\n   public <T> T fromJson(InputStream json, Charset charset, Class<T> classOfT) {\n      return gson.fromJson(new InputStreamReader(json, charset), classOfT);\n   }\n\n   @Override\n   public String toJson(Object src) {\n      return gson.toJson(src);\n   }\n\n   @Override\n   public String toJson(Object src, Type type) {\n      return gson.toJson(src, type);\n   }\n\n   @Override\n   public Gson delegate() {\n      return gson;\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/json/internal/NamingStrategies.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.json.internal;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Predicates.in;\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.get;\nimport static com.google.common.collect.Iterables.size;\nimport static com.google.common.collect.Iterables.transform;\nimport static com.google.common.collect.Iterables.tryFind;\nimport static org.jclouds.reflect.Reflection2.constructors;\n\nimport java.beans.ConstructorProperties;\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Modifier;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.Map;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Function;\nimport com.google.common.base.Joiner;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.Maps;\nimport com.google.common.reflect.Invokable;\nimport com.google.common.reflect.Parameter;\nimport com.google.common.reflect.TypeToken;\nimport com.google.gson.FieldNamingStrategy;\nimport com.google.gson.annotations.SerializedName;\n\n/**\n * NamingStrategies used for JSON deserialization using GSON\n */\npublic class NamingStrategies {\n   /**\n    * Specifies how to extract the name from an annotation for use in determining the serialized name.\n    * \n    * @see com.google.gson.annotations.SerializedName\n    * @see ExtractSerializedName\n    */\n   public abstract static class NameExtractor<A extends Annotation> implements Function<Annotation, String>,\n         Supplier<Predicate<Annotation>> {\n      protected final Class<A> annotationType;\n      protected final Predicate<Annotation> predicate;\n\n      protected NameExtractor(final Class<A> annotationType) {\n         this.annotationType = checkNotNull(annotationType, \"annotationType\");\n         this.predicate = new Predicate<Annotation>() {\n            public boolean apply(Annotation input) {\n               return input.getClass().equals(annotationType);\n            }\n         };\n      }\n\n      @SuppressWarnings(\"unchecked\")\n      public Class<Annotation> annotationType() {\n         return (Class<Annotation>) annotationType;\n      }\n\n      @Override\n      public String apply(Annotation in) {\n         return extractName(annotationType.cast(in));\n      }\n\n      protected abstract String extractName(A cast);\n\n      @Override\n      public Predicate<Annotation> get() {\n         return predicate;\n      }\n\n      @Override\n      public String toString() {\n         return \"nameExtractor(\" + annotationType.getSimpleName() + \")\";\n      }\n\n      @Override\n      public int hashCode() {\n         return annotationType.hashCode();\n      }\n\n      @Override\n      public boolean equals(Object obj) {\n         if (this == obj)\n            return true;\n         if (obj == null || getClass() != obj.getClass())\n            return false;\n         return annotationType.equals(NameExtractor.class.cast(obj).annotationType);\n      }\n   }\n\n   public static class ExtractSerializedName extends NameExtractor<SerializedName> {\n      public ExtractSerializedName() {\n         super(SerializedName.class);\n      }\n\n      public String extractName(SerializedName in) {\n         return checkNotNull(in, \"input annotation\").value();\n      }\n   }\n\n   public static class ExtractNamed extends NameExtractor<Named> {\n      public ExtractNamed() {\n         super(Named.class);\n      }\n\n      @Override\n      public String extractName(Named in) {\n         return checkNotNull(in, \"input annotation\").value();\n      }\n   }\n\n   public abstract static class AnnotationBasedNamingStrategy {\n      protected final Map<Class<? extends Annotation>, ? extends NameExtractor<?>> annotationToNameExtractor;\n      protected final String forToString;\n\n      public AnnotationBasedNamingStrategy(Iterable<? extends NameExtractor<?>> extractors) {\n         checkNotNull(extractors, \"means to extract names by annotations\");\n\n         this.annotationToNameExtractor = Maps.uniqueIndex(extractors,\n               new Function<NameExtractor<?>, Class<? extends Annotation>>() {\n                  @Override\n                  public Class<? extends Annotation> apply(NameExtractor<?> input) {\n                     return input.annotationType();\n                  }\n               });\n         this.forToString = Joiner.on(\",\").join(transform(extractors, new Function<NameExtractor<?>, String>() {\n            @Override\n            public String apply(NameExtractor<?> input) {\n               return input.annotationType().getName();\n            }\n         }));\n      }\n\n      @Override\n      public String toString() {\n         return \"AnnotationBasedNamingStrategy requiring one of \" + forToString;\n      }\n   }\n\n   /**\n    * Definition of field naming policy for annotation-based field\n    */\n   public static class AnnotationFieldNamingStrategy extends AnnotationBasedNamingStrategy implements\n         FieldNamingStrategy {\n\n      public AnnotationFieldNamingStrategy(Iterable<? extends NameExtractor<?>> extractors) {\n         super(extractors);\n         checkArgument(extractors.iterator().hasNext(), \"you must supply at least one name extractor, for example: \"\n               + ExtractSerializedName.class.getSimpleName());\n      }\n\n      @Override\n      public String translateName(Field f) {\n         // Determining if AutoValue is tough, since annotations are SOURCE retention.\n         if (Modifier.isAbstract(f.getDeclaringClass().getSuperclass().getModifiers())) { // AutoValue means abstract.\n            for (Invokable<?, ?> target : constructors(TypeToken.of(f.getDeclaringClass().getSuperclass()))) {\n               SerializedNames names = target.getAnnotation(SerializedNames.class);\n               if (names != null && target.isStatic()) { // == factory method\n                  // Fields and constructor params are written by AutoValue in same order as methods are declared.\n                  // By contract, SerializedNames factory methods must declare its names in the same order.\n                  List<Field> declaredFields = Arrays.asList(f.getDeclaringClass().getDeclaredFields());\n                  // Instrumentation libraries, such as JaCoCo might introduce synthetic fields to the class.\n                  // We should ignore them\n                  Iterable<Field> fields = filter(declaredFields, new Predicate<Field>() {\n                     @Override\n                     public boolean apply(Field input) {\n                        return !input.isSynthetic();\n                     }\n                  });\n                  int numFields = size(fields);\n                  if (numFields != names.value().length) {\n                     String message = \"Incorrect number of names on %s. Class [%s]. Annotation config: [%s]. Fields in object; [%s]\";\n                     String types = Joiner.on(\",\").join(transform(fields, new Function<Field, String>() {\n                        @Override\n                        public String apply(Field input) {\n                           return input.getType().getName();\n                        }\n                     }));\n                     throw new IllegalStateException(String.format(message, names, f.getDeclaringClass().getName(),\n                           Joiner.on(\",\").join(names.value()), types));\n                  }\n                  for (int i = 0; i < numFields; i++) {\n                     if (get(fields, i).equals(f)) {\n                        return names.value()[i];\n                     }\n                  }\n                  // The input field was not a declared field. Accidentally placed on something not AutoValue?\n                  throw new IllegalStateException(\"Inconsistent state. Ensure type is AutoValue on \" + target);\n               }\n            }\n         }\n         for (Annotation annotation : f.getAnnotations()) {\n            if (annotationToNameExtractor.containsKey(annotation.annotationType())) {\n               return annotationToNameExtractor.get(annotation.annotationType()).apply(annotation);\n            }\n         }\n         return null;\n      }\n   }\n\n   public static class AnnotationOrNameFieldNamingStrategy extends AnnotationFieldNamingStrategy implements\n         FieldNamingStrategy {\n\n      public AnnotationOrNameFieldNamingStrategy(Iterable<? extends NameExtractor<?>> extractors) {\n         super(extractors);\n      }\n\n      @Override\n      public String translateName(Field f) {\n         String result = super.translateName(f);\n         return result == null ? f.getName() : result;\n      }\n   }\n\n   /**\n    * Determines field naming from constructor annotations\n    */\n   public static final class AnnotationConstructorNamingStrategy extends AnnotationBasedNamingStrategy {\n      private final Predicate<Invokable<?, ?>> hasMarker;\n      private final Collection<? extends Class<? extends Annotation>> markers;\n\n      public AnnotationConstructorNamingStrategy(Collection<? extends Class<? extends Annotation>> markers,\n            Iterable<? extends NameExtractor<?>> extractors) {\n         super(extractors);\n         this.markers = checkNotNull(markers,\n               \"you must supply at least one annotation to mark deserialization constructors\");\n         this.hasMarker = hasAnnotationIn(markers);\n      }\n\n      private static Predicate<Invokable<?, ?>> hasAnnotationIn(\n            final Collection<? extends Class<? extends Annotation>> markers) {\n         return new Predicate<Invokable<?, ?>>() {\n            public boolean apply(Invokable<?, ?> input) {\n               return FluentIterable.from(Arrays.asList(input.getAnnotations()))\n                     .transform(new Function<Annotation, Class<? extends Annotation>>() {\n                        public Class<? extends Annotation> apply(Annotation input) {\n                           return input.annotationType();\n                        }\n                     }).anyMatch((Predicate<Class<? extends Annotation>>) in(markers));\n            }\n         };\n      }\n\n      @VisibleForTesting\n      <T> Invokable<T, T> getDeserializer(TypeToken<T> token) {\n         return tryFind(constructors(token), hasMarker).orNull();\n      }\n\n      @SuppressWarnings(\"CollectionIncompatibleType\")\n      @VisibleForTesting\n      <T> String translateName(Invokable<T, T> c, int index) {\n         String name = null;\n\n         if ((markers.contains(ConstructorProperties.class) && c.getAnnotation(ConstructorProperties.class) != null)\n               || (markers.contains(SerializedNames.class) && c.getAnnotation(SerializedNames.class) != null)) {\n\n            String[] names = c.getAnnotation(SerializedNames.class) != null\n                  ? c.getAnnotation(SerializedNames.class).value()\n                  : c.getAnnotation(ConstructorProperties.class).value();\n\n            if (names.length != c.getParameters().size()) {\n               String message = \"Incorrect count of names on annotation of %s. Class: [%s]. Annotation config: [%s]. Parameters; [%s]\";\n               String types = Joiner.on(\",\").join(transform(c.getParameters(), new Function<Parameter, String>() {\n                  @Override\n                  public String apply(Parameter input) {\n                     return input.getClass().getName();\n                  }\n               }));\n               throw new IllegalArgumentException(String.format(message, c, c.getDeclaringClass().getName(),\n                     Joiner.on(\",\").join(names), types));\n            }\n\n            if (names != null && names.length > index) {\n               name = names[index];\n            }\n\n         } else {\n            for (Annotation annotation : c.getParameters().get(index).getAnnotations()) {\n               if (annotationToNameExtractor.containsKey(annotation.annotationType())) {\n                  name = annotationToNameExtractor.get(annotation.annotationType()).apply(annotation);\n                  break;\n               }\n            }\n         }\n         return name;\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/json/internal/NullFilteringTypeAdapterFactories.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.json.internal;\n\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Objects.equal;\n\nimport java.io.IOException;\nimport java.lang.reflect.ParameterizedType;\nimport java.lang.reflect.Type;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.Set;\n\nimport com.google.gson.internal.JsonReaderInternalAccess;\n\nimport com.google.common.base.Objects;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableCollection;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Multimap;\nimport com.google.gson.Gson;\nimport com.google.gson.TypeAdapter;\nimport com.google.gson.TypeAdapterFactory;\nimport com.google.gson.reflect.TypeToken;\nimport com.google.gson.stream.JsonReader;\nimport com.google.gson.stream.JsonToken;\nimport com.google.gson.stream.JsonWriter;\n\n/**\n * Eliminates null values when deserializing Collections, Maps, and Multimaps\n * <p/>\n * Treats [null] as the empty set; [A, null] as [A]; etc.\n */\npublic class NullFilteringTypeAdapterFactories {\n   private NullFilteringTypeAdapterFactories() {\n   }\n\n   static <T> TypeToken<?> resolve(TypeToken<T> ownerType, Type param) {\n      return TypeToken.get(com.google.gson.internal.$Gson$Types.resolve(ownerType.getType(), ownerType.getRawType(),\n            param));\n   }\n\n   public static final class IterableTypeAdapter<E> extends TypeAdapter<Iterable<E>> {\n\n      private final TypeAdapter<E> elementAdapter;\n\n      public IterableTypeAdapter(TypeAdapter<E> elementAdapter) {\n         this.elementAdapter = elementAdapter;\n         nullSafe();\n      }\n\n      public void write(JsonWriter out, Iterable<E> value) throws IOException {\n         if (value == null) {\n            out.nullValue();\n            return;\n         }\n         out.beginArray();\n         for (E element : value)\n            elementAdapter.write(out, element);\n         out.endArray();\n      }\n\n      public Iterable<E> read(JsonReader in) throws IOException {\n         return readAndBuild(in, ImmutableList.<E> builder());\n      }\n\n      @SuppressWarnings(\"unchecked\")\n      protected <C extends Iterable<E>, B extends ImmutableCollection.Builder<E>> C readAndBuild(JsonReader in,\n            B builder) throws IOException {\n         if (in.peek() == JsonToken.NULL) {\n            in.nextNull();\n            return null;\n         }\n         in.beginArray();\n         while (in.hasNext()) {\n            E element = elementAdapter.read(in);\n            if (element != null)\n               builder.add(element);\n         }\n         in.endArray();\n         return (C) builder.build();\n      }\n\n      @Override\n      public int hashCode() {\n         return elementAdapter.hashCode();\n      }\n\n      @Override\n      public boolean equals(Object obj) {\n         if (this == obj)\n            return true;\n         if (obj == null || getClass() != obj.getClass())\n            return false;\n         IterableTypeAdapter<?> that = IterableTypeAdapter.class.cast(obj);\n         return equal(this.elementAdapter, that.elementAdapter);\n      }\n\n      @Override\n      public String toString() {\n         return toStringHelper(this).add(\"elementAdapter\", elementAdapter).toString();\n      }\n   }\n\n   public static class ImmutableListTypeAdapterFactory implements TypeAdapterFactory {\n\n      protected final Class<?> declaring;\n\n      public ImmutableListTypeAdapterFactory() {\n         this(ImmutableList.class);\n      }\n\n      protected ImmutableListTypeAdapterFactory(Class<?> declaring) {\n         this.declaring = declaring;\n      }\n\n      @SuppressWarnings(\"unchecked\")\n      public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> ownerType) {\n         Type type = ownerType.getType();\n         if (ownerType.getRawType() != declaring || !(type instanceof ParameterizedType))\n            return null;\n         Type elementType = ((ParameterizedType) type).getActualTypeArguments()[0];\n         TypeAdapter<?> elementAdapter = gson.getAdapter(TypeToken.get(elementType));\n         return (TypeAdapter<T>) newAdapter(elementAdapter);\n      }\n\n      @SuppressWarnings(\"unchecked\")\n      protected <E, I> TypeAdapter<I> newAdapter(TypeAdapter<E> elementAdapter) {\n         return (TypeAdapter<I>) new IterableTypeAdapter<E>(elementAdapter);\n      }\n\n   }\n\n   public static class IterableTypeAdapterFactory extends ImmutableListTypeAdapterFactory {\n      public IterableTypeAdapterFactory() {\n         super(Iterable.class);\n      }\n   }\n\n   public static class CollectionTypeAdapterFactory extends ImmutableListTypeAdapterFactory {\n      public CollectionTypeAdapterFactory() {\n         super(Collection.class);\n      }\n   }\n\n   public static class ListTypeAdapterFactory extends ImmutableListTypeAdapterFactory {\n      public ListTypeAdapterFactory() {\n         super(List.class);\n      }\n   }\n\n   public static final class SetTypeAdapter<E> extends TypeAdapter<Set<E>> {\n\n      private final IterableTypeAdapter<E> delegate;\n\n      public SetTypeAdapter(TypeAdapter<E> elementAdapter) {\n         this.delegate = new IterableTypeAdapter<E>(elementAdapter);\n         nullSafe();\n      }\n\n      public void write(JsonWriter out, Set<E> value) throws IOException {\n         this.delegate.write(out, value);\n      }\n\n      public Set<E> read(JsonReader in) throws IOException {\n         return delegate.readAndBuild(in, ImmutableSet.<E> builder());\n      }\n\n      @Override\n      public int hashCode() {\n         return delegate.hashCode();\n      }\n\n      @Override\n      public boolean equals(Object obj) {\n         if (this == obj)\n            return true;\n         if (obj == null || getClass() != obj.getClass())\n            return false;\n         SetTypeAdapter<?> that = SetTypeAdapter.class.cast(obj);\n         return equal(this.delegate, that.delegate);\n      }\n\n      @Override\n      public String toString() {\n         return toStringHelper(this).add(\"elementAdapter\", delegate.elementAdapter).toString();\n      }\n   }\n\n   public static class ImmutableSetTypeAdapterFactory extends ImmutableListTypeAdapterFactory {\n      public ImmutableSetTypeAdapterFactory() {\n         this(ImmutableSet.class);\n      }\n\n      protected ImmutableSetTypeAdapterFactory(Class<?> declaring) {\n         super(declaring);\n      }\n\n      @SuppressWarnings(\"unchecked\")\n      protected <E, I> TypeAdapter<I> newAdapter(TypeAdapter<E> elementAdapter) {\n         return (TypeAdapter<I>) new SetTypeAdapter<E>(elementAdapter);\n      }\n   }\n\n   public static class SetTypeAdapterFactory extends ImmutableSetTypeAdapterFactory {\n      public SetTypeAdapterFactory() {\n         super(Set.class);\n      }\n   }\n\n   private static final class FluentIterableTypeAdapter<E> extends TypeAdapter<FluentIterable<E>> {\n\n      private final IterableTypeAdapter<E> delegate;\n\n      public FluentIterableTypeAdapter(TypeAdapter<E> elementAdapter) {\n         this.delegate = new IterableTypeAdapter<E>(elementAdapter);\n         nullSafe();\n      }\n\n      public void write(JsonWriter out, FluentIterable<E> value) throws IOException {\n         this.delegate.write(out, value.toList());\n      }\n\n      public FluentIterable<E> read(JsonReader in) throws IOException {\n         return FluentIterable.from(delegate.read(in));\n      }\n\n      @Override\n      public int hashCode() {\n         return delegate.hashCode();\n      }\n\n      @Override\n      public boolean equals(Object obj) {\n         if (this == obj)\n            return true;\n         if (obj == null || getClass() != obj.getClass())\n            return false;\n         FluentIterableTypeAdapter<?> that = FluentIterableTypeAdapter.class.cast(obj);\n         return equal(this.delegate, that.delegate);\n      }\n\n      @Override\n      public String toString() {\n         return toStringHelper(this).add(\"elementAdapter\", delegate.elementAdapter).toString();\n      }\n   }\n\n   public static class FluentIterableTypeAdapterFactory extends ImmutableListTypeAdapterFactory {\n      public FluentIterableTypeAdapterFactory() {\n         super(FluentIterable.class);\n      }\n\n      @SuppressWarnings(\"unchecked\")\n      protected <E, I> TypeAdapter<I> newAdapter(TypeAdapter<E> elementAdapter) {\n         return (TypeAdapter<I>) new FluentIterableTypeAdapter<E>(elementAdapter);\n      }\n   }\n\n   public static class ImmutableMapTypeAdapterFactory extends MapTypeAdapterFactory {\n\n      public ImmutableMapTypeAdapterFactory() {\n         super(ImmutableMap.class);\n      }\n   }\n\n   public static class MapTypeAdapter<K, V> extends TypeAdapter<Map<K, V>> {\n\n      protected final TypeAdapter<K> keyAdapter;\n      protected final TypeAdapter<V> valueAdapter;\n\n      protected MapTypeAdapter(TypeAdapter<K> keyAdapter, TypeAdapter<V> valueAdapter) {\n         this.keyAdapter = keyAdapter;\n         this.valueAdapter = valueAdapter;\n         nullSafe();\n      }\n\n      public void write(JsonWriter out, Map<K, V> value) throws IOException {\n         if (value == null) {\n            out.nullValue();\n            return;\n         }\n         out.beginObject();\n         for (Map.Entry<K, V> element : value.entrySet()) {\n            out.name(String.valueOf(element.getKey()));\n            valueAdapter.write(out, element.getValue());\n         }\n         out.endObject();\n      }\n\n      public Map<K, V> read(JsonReader in) throws IOException {\n         if (in.peek() == JsonToken.NULL) {\n            in.nextNull();\n            return null;\n         }\n         ImmutableMap.Builder<K, V> result = ImmutableMap.builder();\n         in.beginObject();\n         while (in.hasNext()) {\n            JsonReaderInternalAccess.INSTANCE.promoteNameToValue(in);\n            K name = keyAdapter.read(in);\n            V value = valueAdapter.read(in);\n            if (value != null)\n               result.put(name, value);\n         }\n         in.endObject();\n         return result.build();\n      }\n\n      @Override\n      public int hashCode() {\n         return Objects.hashCode(keyAdapter, valueAdapter);\n      }\n\n      @Override\n      public boolean equals(Object obj) {\n         if (this == obj)\n            return true;\n         if (obj == null || getClass() != obj.getClass())\n            return false;\n         MapTypeAdapter<?, ?> that = MapTypeAdapter.class.cast(obj);\n         return equal(this.keyAdapter, that.keyAdapter) && equal(this.valueAdapter, that.valueAdapter);\n      }\n\n      @Override\n      public String toString() {\n         return toStringHelper(this).add(\"keyAdapter\", keyAdapter).add(\"valueAdapter\", valueAdapter).toString();\n      }\n   }\n\n   public static class MapTypeAdapterFactory implements TypeAdapterFactory {\n\n      protected final Class<?> declaring;\n\n      public MapTypeAdapterFactory() {\n         this(Map.class);\n      }\n\n      protected MapTypeAdapterFactory(Class<?> declaring) {\n         this.declaring = declaring;\n      }\n\n      public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> ownerType) {\n         Type type = ownerType.getType();\n         if (ownerType.getRawType() != declaring || !(type instanceof ParameterizedType))\n            return null;\n         Type keyType = ((ParameterizedType) type).getActualTypeArguments()[0];\n         Type valueType = ((ParameterizedType) type).getActualTypeArguments()[1];\n         TypeAdapter<?> keyAdapter = gson.getAdapter(TypeToken.get(keyType));\n         TypeAdapter<?> valueAdapter = gson.getAdapter(TypeToken.get(valueType));\n         return newAdapter(keyAdapter, valueAdapter);\n      }\n\n      @SuppressWarnings(\"unchecked\")\n      protected <K, V, T> TypeAdapter<T> newAdapter(TypeAdapter<K> keyAdapter, TypeAdapter<V> valueAdapter) {\n         return (TypeAdapter<T>) new MapTypeAdapter<K, V>(keyAdapter, valueAdapter);\n      }\n   }\n\n   private static final class MultimapTypeAdapter<K, V> extends TypeAdapter<Multimap<K, V>> {\n\n      private final MapTypeAdapter<K, Iterable<V>> delegate;\n\n      public MultimapTypeAdapter(TypeAdapter<K> keyAdapter, TypeAdapter<V> valueAdapter) {\n         this.delegate = new MapTypeAdapter<K, Iterable<V>>(keyAdapter,\n               new IterableTypeAdapter<V>(valueAdapter));\n         nullSafe();\n      }\n\n      @SuppressWarnings(\"unchecked\")\n      public void write(JsonWriter out, Multimap<K, V> value) throws IOException {\n         this.delegate.write(out, Map.class.cast(value.asMap()));\n      }\n\n      public Multimap<K, V> read(JsonReader in) throws IOException {\n         ImmutableMultimap.Builder<K, V> builder = ImmutableMultimap.<K, V> builder();\n         for (Entry<K, Iterable<V>> entry : delegate.read(in).entrySet())\n            builder.putAll(entry.getKey(), entry.getValue());\n         return builder.build();\n      }\n\n      @Override\n      public int hashCode() {\n         return delegate.hashCode();\n      }\n\n      @Override\n      public boolean equals(Object obj) {\n         if (this == obj)\n            return true;\n         if (obj == null || getClass() != obj.getClass())\n            return false;\n         MultimapTypeAdapter<?, ?> that = MultimapTypeAdapter.class.cast(obj);\n         return equal(this.delegate, that.delegate);\n      }\n\n      @Override\n      public String toString() {\n         return toStringHelper(this).add(\"keyAdapter\", delegate.keyAdapter)\n               .add(\"valueAdapter\", delegate.valueAdapter).toString();\n      }\n   }\n\n   public static class MultimapTypeAdapterFactory extends MapTypeAdapterFactory {\n\n      public MultimapTypeAdapterFactory() {\n         super(Multimap.class);\n      }\n\n      @SuppressWarnings(\"unchecked\")\n      @Override\n      protected <K, V, T> TypeAdapter<T> newAdapter(TypeAdapter<K> keyAdapter, TypeAdapter<V> valueAdapter) {\n         return (TypeAdapter<T>) new MultimapTypeAdapter<K, V>(keyAdapter, valueAdapter);\n      }\n\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/json/internal/NullHackJsonLiteralAdapter.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.json.internal;\n\nimport java.io.IOException;\nimport java.io.Writer;\nimport java.lang.reflect.Field;\n\nimport com.google.gson.internal.bind.TypeAdapters;\n\nimport com.google.common.base.Throwables;\nimport com.google.gson.TypeAdapter;\nimport com.google.gson.stream.JsonReader;\nimport com.google.gson.stream.JsonWriter;\n\n/**\n * writes or reads the literal json directly\n * \n * @see <a href=\"http://code.google.com/p/google-gson/issues/detail?id=326\" />\n */\npublic abstract class NullHackJsonLiteralAdapter<L> extends TypeAdapter<L> {\n\n   @Override\n   public L read(JsonReader reader) throws IOException {\n      return createJsonLiteralFromRawJson(TypeAdapters.JSON_ELEMENT.read(reader).toString());\n   }\n\n\n   /**\n    * User supplied type that holds json literally. Ex. number as {@code 8}, boolean as {@code true}\n    * , string as {@code \"value\"}, object as {@code , list {@code []}.\n    */\n   protected abstract L createJsonLiteralFromRawJson(String json);\n\n   // the writer inside JsonWriter is not accessible currently\n   private static final Field outField;\n   static {\n      try {\n         outField = JsonWriter.class.getDeclaredField(\"out\");\n      } catch (SecurityException e) {\n         throw Throwables.propagate(e);\n      } catch (NoSuchFieldException e) {\n         throw Throwables.propagate(e);\n      }\n      outField.setAccessible(true);\n   }\n\n   @Override\n   public void write(JsonWriter jsonWriter, L value) throws IOException {\n\n      Writer writer = getWriter(jsonWriter);\n      boolean serializeNulls = jsonWriter.getSerializeNulls();\n      try {\n         // we are using an implementation hack which depends on replacing null with the raw json\n         // supplied as a parameter. In this case, we must ensure we indeed serialize nulls.\n         NullReplacingWriter nullReplacingWriter = new NullReplacingWriter(writer, toString(value));\n         setWriter(jsonWriter, nullReplacingWriter);\n         jsonWriter.setSerializeNulls(true);\n         jsonWriter.nullValue();\n      } finally {\n         setWriter(jsonWriter, writer);\n         jsonWriter.setSerializeNulls(serializeNulls);\n      }\n\n   }\n\n   protected String toString(L value) {\n      return value.toString();\n   }\n\n   protected Writer getWriter(JsonWriter arg0) {\n      try {\n         return Writer.class.cast(outField.get(arg0));\n      } catch (IllegalAccessException e) {\n         throw Throwables.propagate(e);\n      }\n   }\n\n   private void setWriter(JsonWriter arg0, Writer arg1) {\n      try {\n         outField.set(arg0, arg1);\n      } catch (IllegalAccessException e) {\n         throw Throwables.propagate(e);\n      }\n   }\n\n   public static final class NullReplacingWriter extends Writer {\n      private final Writer delegate;\n      private final String nullReplacement;\n\n      public NullReplacingWriter(Writer delegate, String nullReplacement) {\n         this.delegate = delegate;\n         this.nullReplacement = nullReplacement;\n      }\n\n      @Override\n      public void write(char[] buffer, int offset, int count) throws IOException {\n         delegate.write(buffer, offset, count);\n      }\n\n      @Override\n      public void write(String s) throws IOException {\n         if (nullReplacement != null && s.equals(\"null\")) {\n            s = nullReplacement;\n         }\n         super.write(s);\n      }\n\n      @Override\n      public void flush() throws IOException {\n         delegate.flush();\n      }\n\n      @Override\n      public void close() throws IOException {\n         delegate.close();\n      }\n\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/json/internal/OptionalTypeAdapterFactory.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.json.internal;\n\nimport java.io.IOException;\nimport java.lang.reflect.ParameterizedType;\nimport java.lang.reflect.Type;\n\nimport com.google.common.base.Optional;\nimport com.google.gson.Gson;\nimport com.google.gson.TypeAdapter;\nimport com.google.gson.TypeAdapterFactory;\nimport com.google.gson.reflect.TypeToken;\nimport com.google.gson.stream.JsonReader;\nimport com.google.gson.stream.JsonToken;\nimport com.google.gson.stream.JsonWriter;\n\n/**\n * Writes and reads Optional values as JSON\n */\npublic class OptionalTypeAdapterFactory implements TypeAdapterFactory {\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {\n      Type type = typeToken.getType();\n      if (typeToken.getRawType() != Optional.class || !(type instanceof ParameterizedType)) {\n         return null;\n      }\n\n      Type elementType = ((ParameterizedType) type).getActualTypeArguments()[0];\n      TypeAdapter<?> elementAdapter = gson.getAdapter(TypeToken.get(elementType));\n      return (TypeAdapter<T>) newOptionalAdapter(elementAdapter);\n   }\n\n   protected <E> TypeAdapter<Optional<E>> newOptionalAdapter(\n         final TypeAdapter<E> elementAdapter) {\n      return new TypeAdapter<Optional<E>>() {\n         public void write(JsonWriter out, Optional<E> value) throws IOException {\n            if (!value.isPresent()) {\n               out.nullValue();\n               return;\n            }\n            elementAdapter.write(out, value.get());\n         }\n\n         public Optional<E> read(JsonReader in) throws IOException {\n            Optional<E> result = Optional.absent();\n            if (in.peek() == JsonToken.NULL) {\n               in.nextNull();\n            } else {\n               E element = elementAdapter.read(in);\n               if (element != null) {\n                  result = Optional.of(element);\n               }\n            }\n            return result;\n         }\n      };\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/lifecycle/BaseLifeCycle.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.lifecycle;\n\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport jakarta.annotation.PostConstruct;\nimport jakarta.annotation.PreDestroy;\nimport jakarta.annotation.Resource;\n\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.collect.Lists;\nimport com.google.common.util.concurrent.Atomics;\nimport com.google.common.util.concurrent.ListeningExecutorService;\n\n/**\n * // TODO: Adrian: Document this!\n */\npublic abstract class BaseLifeCycle implements Runnable, LifeCycle {\n   @Resource\n   protected Logger logger = Logger.NULL;\n   \n   protected final ListeningExecutorService userExecutor;\n   protected final List<LifeCycle> dependencies;\n   protected final Object statusLock;\n   protected volatile Status status;\n   protected AtomicReference<Exception> exception = Atomics.newReference();\n\n   public BaseLifeCycle(ListeningExecutorService userExecutor, LifeCycle... dependencies) {\n      this.userExecutor = userExecutor;\n      this.dependencies = Lists.newArrayList();\n      this.dependencies.addAll(Arrays.asList(dependencies));\n      this.statusLock = new Object();\n      this.status = Status.INACTIVE;\n   }\n\n   public void addDependency(LifeCycle lifeCycle) {\n      dependencies.add(lifeCycle);\n   }\n\n   public Status getStatus() {\n      return status;\n   }\n\n   public void run() {\n      try {\n         while (shouldDoWork()) {\n            doWork();\n         }\n      } catch (Exception e) {\n         logger.error(e, \"Exception doing work\");\n         exception.set(e);\n      }\n      this.status = Status.SHUTTING_DOWN;\n      doShutdown();\n      this.status = Status.SHUT_DOWN;\n      logger.info(\"Shutdown %s\", this);\n   }\n\n   protected abstract void doWork() throws Exception;\n\n   protected abstract void doShutdown();\n\n   /**\n    * @return false if any dependencies are inactive, or we are inactive, or we have a global\n    *         exception.\n    */\n   protected boolean shouldDoWork() {\n      try {\n         exceptionIfDependenciesNotActive();\n      } catch (IllegalStateException e) {\n         return false;\n      }\n      return status.equals(Status.ACTIVE) && exception.get() == null;\n   }\n\n   @PostConstruct\n   public void start() {\n      logger.info(\"Starting %s\", this);\n      synchronized (this.statusLock) {\n         if (this.status.compareTo(Status.SHUTDOWN_REQUEST) >= 0) {\n            doShutdown();\n            this.status = Status.SHUT_DOWN;\n            this.statusLock.notifyAll();\n            return;\n         }\n         if (this.status.compareTo(Status.ACTIVE) == 0) {\n            this.statusLock.notifyAll();\n            return;\n         }\n\n         if (this.status.compareTo(Status.INACTIVE) != 0) {\n            throw new IllegalStateException(\"Illegal state: \" + this.status);\n         }\n\n         exceptionIfDependenciesNotActive();\n\n         this.status = Status.ACTIVE;\n      }\n      userExecutor.execute(this);\n   }\n\n   protected void exceptionIfDependenciesNotActive() {\n      for (LifeCycle dependency : dependencies) {\n         if (dependency.getStatus().compareTo(Status.ACTIVE) != 0) {\n            throw new IllegalStateException(String.format(\"Illegal state: %s for component: %s\",\n                     dependency.getStatus(), dependency));\n         }\n      }\n   }\n\n   protected Exception getExceptionFromDependenciesOrNull() {\n      for (LifeCycle dependency : dependencies) {\n         if (dependency.getException() != null) {\n            return dependency.getException();\n         }\n      }\n      return null;\n   }\n\n   public Exception getException() {\n      return this.exception.get();\n   }\n\n   protected void awaitShutdown(long timeout) throws InterruptedException {\n      awaitStatus(Status.SHUT_DOWN, timeout);\n   }\n\n   protected void awaitStatus(Status intended, long timeout) throws InterruptedException {\n      synchronized (this.statusLock) {\n         long deadline = System.currentTimeMillis() + timeout;\n         long remaining = timeout;\n         while (this.status != intended) {\n            this.statusLock.wait(remaining);\n            if (timeout > 0) {\n               remaining = deadline - System.currentTimeMillis();\n               if (remaining <= 0) {\n                  break;\n               }\n            }\n         }\n      }\n   }\n\n   @PreDestroy\n   public void shutdown() {\n      shutdown(2000);\n   }\n\n   public void shutdown(long waitMs) {\n      synchronized (this.statusLock) {\n         if (this.status.compareTo(Status.ACTIVE) > 0) {\n            return;\n         }\n         this.status = Status.SHUTDOWN_REQUEST;\n         try {\n            awaitShutdown(waitMs);\n         } catch (InterruptedException ignore) {\n         }\n      }\n   }\n\n   protected void exceptionIfNotActive() {\n      if (!status.equals(Status.ACTIVE))\n         throw new IllegalStateException(String.format(\"not active: %s\", this));\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/lifecycle/Closer.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.lifecycle;\n\nimport java.io.Closeable;\nimport java.io.IOException;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport jakarta.inject.Singleton;\n\nimport com.google.common.collect.Lists;\nimport com.google.common.util.concurrent.Atomics;\n\nimport static org.jclouds.lifecycle.Closer.State.AVAILABLE;\nimport static org.jclouds.lifecycle.Closer.State.DONE;\nimport static org.jclouds.lifecycle.Closer.State.PROCESSING;\n\n/**\n * This will close objects in the reverse order that they were added.\n */\n@Singleton\npublic class Closer implements Closeable {\n   // guice is single threaded. no need to lock this\n   List<Closeable> methodsToClose = Lists.<Closeable> newArrayList();\n\n   public enum State {\n      AVAILABLE,\n      PROCESSING,\n      DONE\n   }\n\n   private final AtomicReference<State> state;\n\n   public Closer() {\n      this.state = Atomics.newReference(AVAILABLE);\n   }\n\n   public void addToClose(Closeable toClose) {\n      methodsToClose.add(toClose);\n   }\n\n   public void close() throws IOException {\n      if (state.compareAndSet(AVAILABLE, PROCESSING)) {\n         Collections.reverse(methodsToClose);\n         for (Closeable toClose : methodsToClose) {\n            toClose.close();\n         }\n         state.set(DONE);\n      }\n   }\n\n   public State getState() {\n      return state.get();\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/lifecycle/LifeCycle.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.lifecycle;\n\nimport jakarta.annotation.PostConstruct;\nimport jakarta.annotation.PreDestroy;\n\n/**\n * // TODO: Adrian: Document this!\n */\npublic interface LifeCycle {\n\n    /**\n     * @return the current state of the component;\n     */\n    Status getStatus();\n\n    /**\n     * @return Exception or null, if there are no fatal Exceptions encountered in the lifecycle of this component.\n     */\n    Exception getException();\n\n    /**\n     * Asynchronously starts the component\n     */\n    @PostConstruct\n    void start();\n\n    /**\n     * Requests shutdown of the component.\n     */\n    @PreDestroy\n    void shutdown();\n\n    /**\n     * Requests shutdown, but will only wait @link waitms milliseconds\n     *\n     * @param waitMs maximum time to wait in milliseconds\n     */\n    void shutdown(long waitMs);\n\n    /**\n     * States that are possible for a component.\n     */\n    public static enum Status {\n\n        /**\n         * The component is inactive / has not been started\n         */\n        INACTIVE,\n\n        /**\n         * The component is active / processing I/O events.\n         */\n        ACTIVE,\n\n        /**\n         * Shutdown of the component has been requested.\n         */\n        SHUTDOWN_REQUEST,\n\n        /**\n         * The component is shutting down.\n         */\n        SHUTTING_DOWN,\n\n        /**\n         * The component has shut down.\n         */\n        SHUT_DOWN;\n    }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/lifecycle/config/LifeCycleModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.lifecycle.config;\n\nimport static com.google.common.base.Throwables.propagate;\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.util.concurrent.MoreExecutors.newDirectExecutorService;\nimport static com.google.inject.matcher.Matchers.any;\nimport static org.jclouds.Constants.PROPERTY_SCHEDULER_THREADS;\nimport static org.jclouds.Constants.PROPERTY_USER_THREADS;\nimport static org.jclouds.reflect.Reflection2.methods;\n\nimport java.io.Closeable;\nimport java.io.IOException;\nimport java.lang.reflect.InvocationTargetException;\nimport java.util.Collection;\nimport java.util.concurrent.ScheduledExecutorService;\n\nimport jakarta.annotation.PostConstruct;\nimport jakarta.annotation.PreDestroy;\nimport jakarta.inject.Named;\n\nimport org.jclouds.lifecycle.Closer;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.reflect.Invokable;\nimport com.google.common.util.concurrent.ExecutionList;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Inject;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.spi.InjectionListener;\nimport com.google.inject.spi.TypeEncounter;\nimport com.google.inject.spi.TypeListener;\n\n/**\n * This associates java lifecycle annotations with guice hooks. For example, we invoke {@link PostConstruct} after\n * injection, and Associate {@link PreDestroy} with a global {@link Closer} object.\n * \n * <h3>Important</h3> Make sure you create your injector with {@link Stage#PRODUCTION} and execute the bound\n * {@link ExecutionList} prior to using any other objects.\n * \n * <p/>\n * Ex.\n * \n * <pre>\n * \n * </pre>\n */\npublic class LifeCycleModule extends AbstractModule {\n\n   protected void configure() {\n\n      Closeable executorCloser = new Closeable() {\n         @Inject\n         @Named(PROPERTY_USER_THREADS)\n         ListeningExecutorService userExecutor;\n         // ScheduledExecutor is defined in an optional module\n         @Inject(optional = true)\n         @Named(PROPERTY_SCHEDULER_THREADS)\n         ScheduledExecutorService scheduledExecutor;\n\n         public void close() throws IOException {\n            assert userExecutor != null;\n            userExecutor.shutdownNow();\n            // ScheduledExecutor is defined in an optional module\n            if (scheduledExecutor != null)\n               scheduledExecutor.shutdownNow();\n         }\n      };\n\n      binder().requestInjection(executorCloser);\n      Closer closer = new Closer();\n      closer.addToClose(executorCloser);\n      bind(Closer.class).toInstance(closer);\n\n      ExecutionList list = new ExecutionList();\n      bindPostInjectionInvoke(closer, list);\n      bind(ExecutionList.class).toInstance(list);\n   }\n\n   private static final Predicate<Invokable<?, ?>> isPreDestroy = new Predicate<Invokable<?, ?>>() {\n      public boolean apply(Invokable<?, ?> in) {\n         return in.isAnnotationPresent(PreDestroy.class);\n      }\n   };\n\n   private static final Predicate<Invokable<?, ?>> isPostConstruct = new Predicate<Invokable<?, ?>>() {\n      public boolean apply(Invokable<?, ?> in) {\n         return in.isAnnotationPresent(PostConstruct.class);\n      }\n   };\n\n   protected void bindPostInjectionInvoke(final Closer closer, final ExecutionList list) {\n      bindListener(any(), new TypeListener() {\n         public <I> void hear(TypeLiteral<I> injectableType, TypeEncounter<I> encounter) {\n            Collection<? extends Invokable<? super I, Object>> methods = methods(injectableType.getRawType());\n            for (final Invokable<? super I, Object> method : filter(methods, isPostConstruct)) {\n               encounter.register(new InjectionListener<I>() {\n                  public void afterInjection(final I injectee) {\n                     list.add(new Runnable() {\n                        public void run() {\n                           invokeOnInjectee(method, injectee);\n                        }\n\n                     }, newDirectExecutorService());\n                  }\n               });\n            }\n            for (final Invokable<? super I, Object> method : filter(methods, isPreDestroy)) {\n               encounter.register(new InjectionListener<I>() {\n                  public void afterInjection(final I injectee) {\n                     closer.addToClose(new Closeable() {\n                        public void close() throws IOException {\n                           invokeOnInjectee(method, injectee);\n                        }\n                     });\n                  }\n               });\n            }\n         }\n\n      });\n   }\n\n   private static <I> void invokeOnInjectee(Invokable<? super I, Object> method, I injectee) {\n      try {\n         method.invoke(injectee);\n      } catch (InvocationTargetException ie) {\n         throw propagate(ie.getTargetException());\n      } catch (IllegalAccessException e) {\n         throw propagate(e);\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/Iso3166.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location;\n\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\nimport jakarta.inject.Qualifier;\n\n/**\n * Related to a Iso3166 code\n */\n@Retention(value = RetentionPolicy.RUNTIME)\n@Target(value = { ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })\n@Qualifier\npublic @interface Iso3166 {\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/Provider.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location;\n\nimport static java.lang.annotation.ElementType.ANNOTATION_TYPE;\nimport static java.lang.annotation.ElementType.FIELD;\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.ElementType.PARAMETER;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\nimport jakarta.inject.Qualifier;\n\n/**\n * Designates that this Resource qualifies an object to a provider of a rest service.\n */\n@Target( { ANNOTATION_TYPE, FIELD, METHOD, PARAMETER })\n@Retention(RUNTIME)\n@Qualifier\npublic @interface Provider {\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/Region.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location;\n\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\nimport jakarta.inject.Qualifier;\n\n/**\n * Related to a Region-scoped resource.\n */\n@Retention(value = RetentionPolicy.RUNTIME)\n@Target(value = { ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })\n@Qualifier\npublic @interface Region {\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/Zone.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location;\n\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\nimport jakarta.inject.Qualifier;\n\n/**\n * Related to a Zone-scoped resource.\n */\n@Retention(value = RetentionPolicy.RUNTIME)\n@Target(value = { ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })\n@Qualifier\npublic @interface Zone {\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/config/LocationModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.config;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL;\n\nimport java.net.URI;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.domain.Location;\nimport org.jclouds.location.Iso3166;\nimport org.jclouds.location.Provider;\nimport org.jclouds.location.Region;\nimport org.jclouds.location.Zone;\nimport org.jclouds.location.predicates.RegionIdFilter;\nimport org.jclouds.location.predicates.ZoneIdFilter;\nimport org.jclouds.location.suppliers.ImplicitLocationSupplier;\nimport org.jclouds.location.suppliers.ImplicitRegionIdSupplier;\nimport org.jclouds.location.suppliers.LocationIdToIso3166CodesSupplier;\nimport org.jclouds.location.suppliers.LocationsSupplier;\nimport org.jclouds.location.suppliers.ProviderURISupplier;\nimport org.jclouds.location.suppliers.RegionIdToURISupplier;\nimport org.jclouds.location.suppliers.RegionIdToZoneIdsSupplier;\nimport org.jclouds.location.suppliers.RegionIdsSupplier;\nimport org.jclouds.location.suppliers.ZoneIdToURISupplier;\nimport org.jclouds.location.suppliers.ZoneIdsSupplier;\nimport org.jclouds.reflect.InvocationSuccess;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.functions.ImplicitOptionalConverter;\nimport org.jclouds.rest.suppliers.MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.Sets;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Provides;\nimport com.google.inject.TypeLiteral;\n\n/**\n * All of these are memoized as locations do not change often at runtime. Note that we take care to\n * propagate authorization exceptions. this is so that we do not lock out the account.\n */\npublic class LocationModule extends AbstractModule {\n\n   @Override\n   protected void configure() {\n      bind(new TypeLiteral<Function<InvocationSuccess, Optional<Object>>>(){}).to(ImplicitOptionalConverter.class);\n   }\n\n   @Provides\n   @Singleton\n   @Iso3166\n   protected final Supplier<Map<String, Supplier<Set<String>>>> isoCodesSupplier(\n            AtomicReference<AuthorizationException> authException, @Named(PROPERTY_SESSION_INTERVAL) long seconds,\n            LocationIdToIso3166CodesSupplier uncached) {\n      return MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier.create(authException, uncached, seconds,\n               TimeUnit.SECONDS);\n   }\n\n   @Provides\n   @Singleton\n   @Provider\n   protected final Supplier<URI> provideProvider(AtomicReference<AuthorizationException> authException,\n            @Named(PROPERTY_SESSION_INTERVAL) long seconds, ProviderURISupplier uncached) {\n      return MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier.create(authException, uncached, seconds,\n               TimeUnit.SECONDS);\n   }\n\n   @Provides\n   @Singleton\n   protected final Supplier<Location> implicitLocationSupplier(AtomicReference<AuthorizationException> authException,\n            @Named(PROPERTY_SESSION_INTERVAL) long seconds, ImplicitLocationSupplier uncached) {\n      return MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier.create(authException, uncached, seconds,\n               TimeUnit.SECONDS);\n   }\n\n   @Provides\n   @Singleton\n   // TODO: we should eventually get rid of memoized as an annotation, as it is confusing\n   @Memoized\n   protected final Supplier<Set<? extends Location>> memoizedLocationsSupplier(\n            AtomicReference<AuthorizationException> authException, @Named(PROPERTY_SESSION_INTERVAL) long seconds,\n            LocationsSupplier uncached) {\n      return MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier.create(authException, uncached, seconds,\n               TimeUnit.SECONDS);\n   }\n\n   @Provides\n   @Singleton\n   @Region\n   protected final Supplier<Set<String>> regionIdsSupplier(AtomicReference<AuthorizationException> authException,\n            @Named(PROPERTY_SESSION_INTERVAL) long seconds, RegionIdFilter filter, RegionIdsSupplier uncached) {\n      return MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier.create(authException,\n               Suppliers.compose(new FilterStrings(filter), uncached), seconds, TimeUnit.SECONDS);\n   }\n   \n   @Provides\n   @Singleton\n   @Zone\n   protected final Supplier<Set<String>> zoneIdsSupplier(\n            AtomicReference<AuthorizationException> authException, @Named(PROPERTY_SESSION_INTERVAL) long seconds,\n            ZoneIdFilter filter, ZoneIdsSupplier uncached) {\n      return MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier.create(authException,\n               Suppliers.compose(new FilterStrings(filter), uncached), seconds, TimeUnit.SECONDS);\n   }\n\n   static class FilterStrings implements Function<Set<String>, Set<String>> {\n      public final Predicate<String> filter;\n\n      public FilterStrings(Predicate<String> filter) {\n         this.filter = checkNotNull(filter, \"filter\");\n      }\n\n\n      @Override\n      public Set<String> apply(Set<String> input) {\n         return Sets.filter(input, filter);\n      }\n\n      @Override\n      public String toString() {\n         return \"filterStrings(\" + filter + \")\";\n      }\n\n   }\n   \n   @Provides\n   @Singleton\n   @Region\n   protected final Supplier<Map<String, Supplier<URI>>> regionIdToURISupplier(\n            AtomicReference<AuthorizationException> authException, @Named(PROPERTY_SESSION_INTERVAL) long seconds,\n            RegionIdToURISupplier uncached) {\n      return MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier.create(authException, uncached, seconds,\n               TimeUnit.SECONDS);\n   }\n\n   @Provides\n   @Singleton\n   @Region\n   protected final Supplier<String> implicitRegionIdSupplier(AtomicReference<AuthorizationException> authException,\n            @Named(PROPERTY_SESSION_INTERVAL) long seconds, ImplicitRegionIdSupplier uncached) {\n      return MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier.create(authException, uncached, seconds,\n               TimeUnit.SECONDS);\n   }\n\n\n   @Provides\n   @Singleton\n   @Zone\n   protected final Supplier<Map<String, Supplier<Set<String>>>> regionIdToZoneIdsSupplier(\n            AtomicReference<AuthorizationException> authException, @Named(PROPERTY_SESSION_INTERVAL) long seconds,\n            RegionIdToZoneIdsSupplier uncached) {\n      return MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier.create(authException, uncached, seconds,\n               TimeUnit.SECONDS);\n   }\n\n   @Provides\n   @Singleton\n   @Zone\n   protected final Supplier<Map<String, Supplier<URI>>> zoneIdToURISupplier(\n            AtomicReference<AuthorizationException> authException, @Named(PROPERTY_SESSION_INTERVAL) long seconds,\n            ZoneIdToURISupplier uncached) {\n      return MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier.create(authException, uncached, seconds,\n               TimeUnit.SECONDS);\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/functions/RegionToEndpoint.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.functions;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkState;\n\nimport java.net.URI;\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.location.Region;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\n\npublic final class RegionToEndpoint implements Function<Object, URI> {\n\n   private final Supplier<Map<String, Supplier<URI>>> regionToEndpoints;\n\n   @Inject\n   RegionToEndpoint(@Region Supplier<Map<String, Supplier<URI>>> regionToEndpoints) {\n      this.regionToEndpoints = regionToEndpoints;\n   }\n\n   @Override\n   public URI apply(Object from) {\n      Map<String, Supplier<URI>> regionToEndpoint = regionToEndpoints.get();\n      checkState(!regionToEndpoint.isEmpty(), \"no region name to endpoint mappings configured!\");\n      checkArgument(regionToEndpoint.containsKey(from),\n               \"requested location %s, which is not a configured region: %s\", from, regionToEndpoint);\n      return regionToEndpoint.get(from).get();\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/functions/RegionToEndpointOrProviderIfNull.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.functions;\n\nimport static com.google.common.base.Preconditions.checkArgument;\n\nimport java.net.URI;\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.location.Provider;\nimport org.jclouds.location.Region;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\n\n/**\n * Return a uri corresponding to the name of the region (passed argument).\n * Otherwise, return the default location.\n */\npublic final class RegionToEndpointOrProviderIfNull implements Function<Object, URI> {\n   private final Supplier<URI> defaultUri;\n   private final String defaultProvider;\n   private final Supplier<Map<String, Supplier<URI>>> regionToEndpointSupplier;\n\n   @Inject\n   RegionToEndpointOrProviderIfNull(@Provider String defaultProvider, @Provider Supplier<URI> defaultUri,\n         @Region Supplier<Map<String, Supplier<URI>>> regionToEndpointSupplier) {\n      this.defaultProvider = defaultProvider;\n      this.defaultUri = defaultUri;\n      this.regionToEndpointSupplier = regionToEndpointSupplier;\n   }\n\n   @Override\n   public URI apply(@Nullable Object from) {\n      if (from == null)\n         return defaultUri.get();\n      Map<String, Supplier<URI>> regionToEndpoint = regionToEndpointSupplier.get();\n      if (from.equals(defaultProvider)) {\n         if (regionToEndpoint.containsKey(from))\n            return regionToEndpoint.get(from).get();\n         return defaultUri.get();\n      }\n      checkArgument(regionToEndpoint.containsKey(from),\n            \"requested location %s, which is not in the configured locations: %s\", from, regionToEndpoint);\n      return regionToEndpoint.get(from).get();\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/functions/ToIdAndScope.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.functions;\n\nimport org.jclouds.domain.Location;\n\nimport com.google.common.base.Function;\n\npublic enum ToIdAndScope implements Function<Location, String> {\n   INSTANCE;\n   @Override\n   public String apply(Location input) {\n      return input.getId() + \":\" + input.getScope();\n   }\n\n   @Override\n   public String toString() {\n      return \"toIdAndScope()\";\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/functions/ZoneToEndpoint.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.functions;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkState;\n\nimport java.net.URI;\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.location.Zone;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\n\npublic final class ZoneToEndpoint implements Function<Object, URI> {\n\n   private final Supplier<Map<String, Supplier<URI>>> zoneToEndpoints;\n\n   @Inject\n   ZoneToEndpoint(@Zone Supplier<Map<String, Supplier<URI>>> zoneToEndpoints) {\n      this.zoneToEndpoints = zoneToEndpoints;\n   }\n\n   @Override\n   public URI apply(Object from) {\n      Map<String, Supplier<URI>> zoneToEndpoint = zoneToEndpoints.get();\n      checkState(!zoneToEndpoint.isEmpty(), \"no zone name to endpoint mappings configured!\");\n      checkArgument(zoneToEndpoint.containsKey(from),\n               \"requested location %s, which is not a configured zone: %s\", from, zoneToEndpoint);\n      return zoneToEndpoint.get(from).get();\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/predicates/LocationPredicates.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationScope;\n\nimport com.google.common.base.Predicate;\n\npublic class LocationPredicates {\n\n   public static Predicate<Location> isProvider() {\n      return IsProvider.INSTANCE;\n   }\n\n   @Singleton\n   static enum IsProvider implements Predicate<Location> {\n      INSTANCE;\n      @Override\n      public boolean apply(Location input) {\n         return input.getScope() == LocationScope.PROVIDER;\n      }\n\n      @Override\n      public String toString() {\n         return \"isProvider()\";\n      }\n   }\n\n   public static Predicate<Location> isZone() {\n      return IsZone.INSTANCE;\n   }\n\n   @Singleton\n   static enum IsZone implements Predicate<Location> {\n      INSTANCE;\n      @Override\n      public boolean apply(Location input) {\n         return input.getScope() == LocationScope.ZONE;\n      }\n\n      @Override\n      public String toString() {\n         return \"isZone()\";\n      }\n   }\n\n   public static Predicate<Location> isRegion() {\n      return IsRegion.INSTANCE;\n   }\n\n   static enum IsRegion implements Predicate<Location> {\n      INSTANCE;\n      @Override\n      public boolean apply(Location input) {\n         return input.getScope() == LocationScope.REGION;\n      }\n\n      @Override\n      public String toString() {\n         return \"isRegion()\";\n      }\n   }\n\n   public static Predicate<Location> isSystem() {\n       return IsSystem.INSTANCE;\n    }\n\n    static enum IsSystem implements Predicate<Location> {\n       INSTANCE;\n       @Override\n       public boolean apply(Location input) {\n          return input.getScope() == LocationScope.SYSTEM;\n       }\n\n       @Override\n       public String toString() {\n          return \"isSystem()\";\n       }\n    }\n\n    public static Predicate<Location> isNetwork() {\n        return IsNetwork.INSTANCE;\n     }\n\n     static enum IsNetwork implements Predicate<Location> {\n        INSTANCE;\n        @Override\n        public boolean apply(Location input) {\n           return input.getScope() == LocationScope.NETWORK;\n        }\n\n        @Override\n        public String toString() {\n           return \"isNetwork()\";\n        }\n     }\n\n   public static Predicate<Location> idEquals(String id) {\n      return new IdEquals(id);\n   }\n\n   static class IdEquals implements Predicate<Location> {\n\n      private final String id;\n\n      IdEquals(String id) {\n         this.id = checkNotNull(id, \"id\");\n      }\n\n      @Override\n      public boolean apply(Location input) {\n\n         return input.getId().equals(id);\n      }\n\n      @Override\n      public String toString() {\n         return \"idEquals(\" + id + \")\";\n      }\n   }\n   \n   public static Predicate<Location> isZoneOrRegionWhereRegionIdEquals(String region) {\n      return new IsZoneOrRegionWhereRegionIdEquals(region);\n   }\n\n   static class IsZoneOrRegionWhereRegionIdEquals implements Predicate<Location> {\n\n      private final String region;\n\n      IsZoneOrRegionWhereRegionIdEquals(String region) {\n         this.region = checkNotNull(region, \"region\");\n      }\n\n      @Override\n      public boolean apply(Location input) {\n         switch (input.getScope()) {\n         case ZONE:\n            return input.getParent().getId().equals(region);\n         case REGION:\n            return input.getId().equals(region);\n         default:\n            return false;\n         }\n      }\n\n      @Override\n      public String toString() {\n         return \"isRegionAndIdEqualsOrIsZoneParentIdEquals(\" + region + \")\";\n      }\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/predicates/RegionIdFilter.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.predicates;\n\nimport org.jclouds.location.predicates.fromconfig.AnyOrConfiguredRegionId;\n\nimport com.google.common.base.Predicate;\nimport com.google.inject.ImplementedBy;\n\n/**\n * Means to constrain regions returned to abstraction calls. Particularly useful\n * to whitelist certain regions.\n */\n@ImplementedBy(AnyOrConfiguredRegionId.class)\npublic interface RegionIdFilter extends Predicate<String> {\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/predicates/ZoneIdFilter.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.predicates;\n\nimport org.jclouds.location.predicates.fromconfig.AnyOrConfiguredZoneId;\n\nimport com.google.common.base.Predicate;\nimport com.google.inject.ImplementedBy;\n\n/**\n * Means to constrain zones returned to abstraction calls. Particularly useful\n * to whitelist certain zones.\n */\n@ImplementedBy(AnyOrConfiguredZoneId.class)\npublic interface ZoneIdFilter extends Predicate<String> {\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/predicates/fromconfig/AnyOrConfiguredRegionId.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.predicates.fromconfig;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.location.predicates.RegionIdFilter;\nimport org.jclouds.location.suppliers.fromconfig.RegionIdsFromConfiguration;\n\n/**\n *\n * If there are regions configured in {@link RegionIdsFromConfiguration}, return\n * true if that set contains the input param. If there aren't, return true.\n */\n@Singleton\npublic class AnyOrConfiguredRegionId implements RegionIdFilter {\n\n   private RegionIdsFromConfiguration idsInConfigSupplier;\n\n   @Inject\n   protected AnyOrConfiguredRegionId(RegionIdsFromConfiguration idsInConfigSupplier) {\n      this.idsInConfigSupplier = checkNotNull(idsInConfigSupplier, \"idsInConfigSupplier\");\n   }\n\n   @Override\n   public boolean apply(String input) {\n      Set<String> idsInConfig = idsInConfigSupplier.get();\n      if (idsInConfig.isEmpty())\n         return true;\n      return idsInConfig.contains(input);\n   }\n\n   @Override\n   public String toString() {\n      return \"anyOrConfiguredRegionId(\" + idsInConfigSupplier + \")\";\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/predicates/fromconfig/AnyOrConfiguredZoneId.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.predicates.fromconfig;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.location.predicates.ZoneIdFilter;\nimport org.jclouds.location.suppliers.fromconfig.ZoneIdsFromConfiguration;\n\n/**\n *\n * If there are zones configured in {@link ZoneIdsFromConfiguration}, return\n * true if that set contains the input param. If there aren't, return true.\n */\n@Singleton\npublic class AnyOrConfiguredZoneId implements ZoneIdFilter {\n\n   private ZoneIdsFromConfiguration idsInConfigSupplier;\n\n   @Inject\n   protected AnyOrConfiguredZoneId(ZoneIdsFromConfiguration idsInConfigSupplier) {\n      this.idsInConfigSupplier = checkNotNull(idsInConfigSupplier, \"idsInConfigSupplier\");\n   }\n\n   @Override\n   public boolean apply(String input) {\n      Set<String> idsInConfig = idsInConfigSupplier.get();\n      if (idsInConfig.isEmpty())\n         return true;\n      return idsInConfig.contains(input);\n   }\n\n   @Override\n   public String toString() {\n      return \"anyOrConfiguredZoneId(\" + idsInConfigSupplier + \")\";\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/reference/LocationConstants.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.reference;\n\npublic final class LocationConstants {\n   public static final String ENDPOINT = \"endpoint\";\n   public static final String ISO3166_CODES = \"iso3166-codes\";\n   public static final String PROPERTY_REGIONS = \"jclouds.regions\";\n   public static final String PROPERTY_REGION = \"jclouds.region\";\n   public static final String PROPERTY_ZONES = \"jclouds.zones\";\n   public static final String PROPERTY_ZONE = \"jclouds.zone\";\n\n   private LocationConstants() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/suppliers/ImplicitLocationSupplier.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.suppliers;\n\nimport org.jclouds.domain.Location;\nimport org.jclouds.location.suppliers.implicit.OnlyLocationOrFirstRegionOptionallyMatchingRegionId;\n\nimport com.google.common.base.Supplier;\nimport com.google.inject.ImplementedBy;\n\n@ImplementedBy(OnlyLocationOrFirstRegionOptionallyMatchingRegionId.class)\npublic interface ImplicitLocationSupplier extends Supplier<Location> {\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/suppliers/ImplicitRegionIdSupplier.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.suppliers;\n\nimport org.jclouds.location.suppliers.implicit.GetRegionIdMatchingProviderURIOrNull;\n\nimport com.google.common.base.Supplier;\nimport com.google.inject.ImplementedBy;\n\n@ImplementedBy(GetRegionIdMatchingProviderURIOrNull.class)\npublic interface ImplicitRegionIdSupplier extends Supplier<String> {\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/suppliers/LocationIdToIso3166CodesSupplier.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.suppliers;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.location.suppliers.fromconfig.LocationIdToIso3166CodesFromConfiguration;\n\nimport com.google.common.base.Supplier;\nimport com.google.inject.ImplementedBy;\n\n/**\n * \n\n */\n@ImplementedBy(LocationIdToIso3166CodesFromConfiguration.class)\npublic interface LocationIdToIso3166CodesSupplier extends Supplier<Map<String, Supplier<Set<String>>>> {\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/suppliers/LocationsSupplier.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.suppliers;\n\nimport java.util.Set;\n\nimport org.jclouds.domain.Location;\nimport org.jclouds.location.suppliers.all.ZoneToRegionToProviderOrJustProvider;\n\nimport com.google.common.base.Supplier;\nimport com.google.inject.ImplementedBy;\n\n@ImplementedBy(ZoneToRegionToProviderOrJustProvider.class)\npublic interface LocationsSupplier extends Supplier<Set<? extends Location>> {\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/suppliers/ProviderURISupplier.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.suppliers;\n\nimport java.net.URI;\n\nimport org.jclouds.location.suppliers.fromconfig.ProviderURIFromProviderMetadata;\n\nimport com.google.common.base.Supplier;\nimport com.google.inject.ImplementedBy;\n\n@ImplementedBy(ProviderURIFromProviderMetadata.class)\npublic interface ProviderURISupplier extends Supplier<URI> {\n   \n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/suppliers/RegionIdToURISupplier.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.suppliers;\n\nimport java.net.URI;\nimport java.util.Map;\nimport java.util.NoSuchElementException;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.location.suppliers.fromconfig.RegionIdToURIFromConfigurationOrDefaultToProvider;\n\nimport com.google.common.base.Supplier;\nimport com.google.inject.ImplementedBy;\nimport com.google.inject.assistedinject.Assisted;\n\n@ImplementedBy(RegionIdToURIFromConfigurationOrDefaultToProvider.class)\npublic interface RegionIdToURISupplier extends Supplier<Map<String, Supplier<URI>>> {\n   interface Factory {\n      /**\n       * \n       * @param apiType\n       *           type of the api, according to the provider. ex. {@code compute} {@code\n       *           object-store}\n       * @param apiVersion\n       *           version of the api, or null if not available\n       * @return regions mapped to default uri\n       * @throws NoSuchElementException if the {@code apiType} is not present in the catalog\n       */\n      RegionIdToURISupplier createForApiTypeAndVersion(@Assisted(\"apiType\") String apiType,\n               @Nullable @Assisted(\"apiVersion\") String apiVersion) throws NoSuchElementException;\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/suppliers/RegionIdToZoneIdsSupplier.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.suppliers;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.location.suppliers.fromconfig.RegionIdToZoneIdsFromConfiguration;\n\nimport com.google.common.base.Supplier;\nimport com.google.inject.ImplementedBy;\n\n/**\n\n */\n@ImplementedBy(RegionIdToZoneIdsFromConfiguration.class)\npublic interface RegionIdToZoneIdsSupplier extends Supplier<Map<String, Supplier<Set<String>>>> {\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/suppliers/RegionIdsSupplier.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.suppliers;\n\nimport java.util.Set;\n\nimport org.jclouds.location.suppliers.fromconfig.RegionIdsFromConfiguration;\n\nimport com.google.common.base.Supplier;\nimport com.google.inject.ImplementedBy;\n\n/**\n\n */\n@ImplementedBy(RegionIdsFromConfiguration.class)\npublic interface RegionIdsSupplier extends Supplier<Set<String>> {\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/suppliers/ZoneIdToURISupplier.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.suppliers;\n\nimport java.net.URI;\nimport java.util.Map;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.location.suppliers.fromconfig.ZoneIdToURIFromConfigurationOrDefaultToProvider;\n\nimport com.google.common.base.Supplier;\nimport com.google.inject.ImplementedBy;\nimport com.google.inject.assistedinject.Assisted;\n\n@ImplementedBy(ZoneIdToURIFromConfigurationOrDefaultToProvider.class)\npublic interface ZoneIdToURISupplier extends Supplier<Map<String, Supplier<URI>>> {\n   interface Factory {\n      /**\n       * \n       * @param apiType\n       *           type of the api, according to the provider. ex. {@code compute} {@code\n       *           object-store}\n       * @param apiVersion\n       *           version of the api, or null if not present\n       * @return regions mapped to default uri\n       */\n      ZoneIdToURISupplier createForApiTypeAndVersion(@Assisted(\"apiType\") String apiType,\n               @Nullable @Assisted(\"apiVersion\") String apiVersion);\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/suppliers/ZoneIdsSupplier.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.suppliers;\n\nimport java.util.Set;\n\nimport org.jclouds.location.suppliers.fromconfig.ZoneIdsFromConfiguration;\n\nimport com.google.common.base.Supplier;\nimport com.google.inject.ImplementedBy;\n\n@ImplementedBy(ZoneIdsFromConfiguration.class)\npublic interface ZoneIdsSupplier extends Supplier<Set<String>> {\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/suppliers/all/JustProvider.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.suppliers.all;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.net.URI;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.location.Iso3166;\nimport org.jclouds.location.Provider;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableSet;\n\n@Singleton\npublic class JustProvider implements Supplier<Set<? extends Location>> {\n   private final String providerName;\n   private final Supplier<URI> endpointSupplier;\n   private final Set<String> isoCodesSupplier;\n\n   @Inject\n   public JustProvider(@Provider String providerName, @Provider Supplier<URI> endpointSupplier, @Iso3166 Set<String> isoCodesSupplier) {\n      this.providerName = checkNotNull(providerName, \"providerName\");\n      this.endpointSupplier = checkNotNull(endpointSupplier, \"endpoint\");\n      this.isoCodesSupplier = checkNotNull(isoCodesSupplier, \"isoCodes\");\n   }\n\n   @Override\n   public Set<? extends Location> get() {\n      return ImmutableSet.of(new LocationBuilder().scope(LocationScope.PROVIDER).id(providerName)\n            .description(endpointSupplier.get().toASCIIString()).iso3166Codes(isoCodesSupplier).build());\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/suppliers/all/RegionToProvider.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.suppliers.all;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.location.Iso3166;\nimport org.jclouds.location.Region;\nimport org.jclouds.location.suppliers.LocationsSupplier;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\nimport com.google.common.collect.Iterables;\n\n@Singleton\npublic class RegionToProvider implements LocationsSupplier {\n   private final JustProvider justProvider;\n   private final Supplier<Set<String>> regionsSupplier;\n   private final Supplier<Map<String, Supplier<Set<String>>>> isoCodesByIdSupplier;\n\n   @Inject\n   public RegionToProvider(JustProvider justProvider, @Region Supplier<Set<String>> regionsSupplier,\n            @Iso3166 Supplier<Map<String, Supplier<Set<String>>>> isoCodesByIdSupplier) {\n      this.justProvider = checkNotNull(justProvider, \"justProvider\");\n      this.regionsSupplier = checkNotNull(regionsSupplier, \"regionsSupplier\");\n      this.isoCodesByIdSupplier = checkNotNull(isoCodesByIdSupplier, \"isoCodesByIdSupplier\");\n   }\n\n   @Override\n   public Set<? extends Location> get() {\n      Builder<Location> locations = ImmutableSet.builder();\n      Location provider = Iterables.getOnlyElement(justProvider.get());\n      Set<String> regions = regionsSupplier.get();\n      checkState(!regions.isEmpty(), \"no regions found for provider %s, using supplier %s\", provider, regionsSupplier);\n      Map<String, Supplier<Set<String>>> isoCodesById = isoCodesByIdSupplier.get();\n      for (String region : regions) {\n         LocationBuilder builder = new LocationBuilder().scope(LocationScope.REGION).id(region).description(region)\n                  .parent(provider);\n         if (isoCodesById.containsKey(region))\n            builder.iso3166Codes(isoCodesById.get(region).get());\n         locations.add(builder.build());\n      }\n      return locations.build();\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/suppliers/all/RegionToProviderOrJustProvider.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.suppliers.all;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.location.Iso3166;\nimport org.jclouds.location.Region;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\nimport com.google.common.collect.Iterables;\n\n@Singleton\npublic class RegionToProviderOrJustProvider implements Supplier<Set<? extends Location>> {\n   private final JustProvider justProvider;\n   private final Supplier<Set<String>> regionsSupplier;\n   private final Supplier<Map<String, Supplier<Set<String>>>> isoCodesByIdSupplier;\n\n   @Inject\n   public RegionToProviderOrJustProvider(JustProvider justProvider, @Region Supplier<Set<String>> regionsSupplier,\n            @Iso3166 Supplier<Map<String, Supplier<Set<String>>>> isoCodesByIdSupplier) {\n      this.justProvider = checkNotNull(justProvider, \"justProvider\");\n      this.regionsSupplier = checkNotNull(regionsSupplier, \"regionsSupplier\");\n      this.isoCodesByIdSupplier = checkNotNull(isoCodesByIdSupplier, \"isoCodesByIdSupplier\");\n   }\n\n   @Override\n   public Set<? extends Location> get() {\n      Builder<Location> locations = ImmutableSet.builder();\n      Location provider = Iterables.getOnlyElement(justProvider.get());\n      Set<String> regions = regionsSupplier.get();\n      Map<String, Supplier<Set<String>>> isoCodesById = isoCodesByIdSupplier.get();\n      if (regions.isEmpty())\n         return locations.add(provider).build();\n      else\n         for (String region : regions) {\n            LocationBuilder builder = new LocationBuilder().scope(LocationScope.REGION).id(region).description(region)\n                     .parent(provider);\n            if (isoCodesById.containsKey(region))\n               builder.iso3166Codes(isoCodesById.get(region).get());\n            locations.add(builder.build());\n         }\n      return locations.build();\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/suppliers/all/ZoneToProvider.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.suppliers.all;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.location.Iso3166;\nimport org.jclouds.location.Zone;\nimport org.jclouds.location.suppliers.LocationsSupplier;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\nimport com.google.common.collect.Iterables;\n\n@Singleton\npublic class ZoneToProvider implements LocationsSupplier {\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   private final JustProvider justProvider;\n   private final Supplier<Set<String>> zoneIdsSupplier;\n   private final Supplier<Map<String, Supplier<Set<String>>>> isoCodesByIdSupplier;\n\n   @Inject\n   ZoneToProvider(JustProvider justProvider, @Zone Supplier<Set<String>> zoneIdsSupplier,\n            @Iso3166 Supplier<Map<String, Supplier<Set<String>>>> isoCodesByIdSupplier) {\n      this.justProvider = checkNotNull(justProvider, \"justProvider\");\n      this.zoneIdsSupplier = checkNotNull(zoneIdsSupplier, \"zoneIdsSupplier\");\n      this.isoCodesByIdSupplier = checkNotNull(isoCodesByIdSupplier, \"isoCodesByIdSupplier\");\n   }\n\n   @Override\n   public Set<? extends Location> get() {\n      Location provider = Iterables.getOnlyElement(justProvider.get());\n      Set<String> zoneIds = zoneIdsSupplier.get();\n      checkState(!zoneIds.isEmpty(), \"no zones found for provider %s, using supplier %s\", provider, zoneIdsSupplier);\n      Map<String, Supplier<Set<String>>> isoCodesById = isoCodesByIdSupplier.get();\n\n      Builder<Location> locations = ImmutableSet.builder();\n      for (String zoneId : zoneIds) {\n         LocationBuilder builder = new LocationBuilder().scope(LocationScope.ZONE).id(zoneId).description(zoneId)\n                  .parent(provider);\n         if (isoCodesById.containsKey(zoneId))\n            builder.iso3166Codes(isoCodesById.get(zoneId).get());\n         locations.add(builder.build());\n      }\n      return locations.build();\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/suppliers/all/ZoneToRegionToProviderOrJustProvider.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.suppliers.all;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.location.Iso3166;\nimport org.jclouds.location.Zone;\nimport org.jclouds.location.predicates.LocationPredicates;\nimport org.jclouds.location.suppliers.LocationsSupplier;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Maps;\nimport com.google.common.collect.Sets;\nimport com.google.common.collect.Sets.SetView;\n\n@Singleton\npublic class ZoneToRegionToProviderOrJustProvider implements LocationsSupplier {\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   private final RegionToProviderOrJustProvider regionToProviderOrJustProvider;\n   private final Supplier<Set<String>> zoneIdsSupplier;\n   private final Supplier<Map<String, Supplier<Set<String>>>> isoCodesByIdSupplier;\n   private final Supplier<Map<String, Supplier<Set<String>>>> regionIdToZoneIdsSupplier;\n\n   @Inject\n   ZoneToRegionToProviderOrJustProvider(RegionToProviderOrJustProvider regionToProviderOrJustProvider,\n            @Zone Supplier<Set<String>> zoneIdsSupplier,\n            @Iso3166 Supplier<Map<String, Supplier<Set<String>>>> isoCodesByIdSupplier,\n            @Zone Supplier<Map<String, Supplier<Set<String>>>> regionIdToZoneIdsSupplier) {\n      this.regionToProviderOrJustProvider = checkNotNull(regionToProviderOrJustProvider,\n               \"regionToProviderOrJustProvider\");\n      this.zoneIdsSupplier = checkNotNull(zoneIdsSupplier, \"zoneIdsSupplier\");\n      this.regionIdToZoneIdsSupplier = checkNotNull(regionIdToZoneIdsSupplier, \"regionIdToZoneIdsSupplier\");\n      this.isoCodesByIdSupplier = checkNotNull(isoCodesByIdSupplier, \"isoCodesByIdSupplier\");\n   }\n\n   @Override\n   public Set<? extends Location> get() {\n      Set<? extends Location> regionsOrJustProvider = regionToProviderOrJustProvider.get();\n      Set<String> zoneIds = zoneIdsSupplier.get();\n      if (zoneIds.isEmpty())\n         return regionsOrJustProvider;\n      Map<String, Location> zoneIdToParent = setParentOfZoneToRegionOrProvider(zoneIds, regionsOrJustProvider);\n      Map<String, Supplier<Set<String>>> isoCodesById = isoCodesByIdSupplier.get();\n\n      Builder<Location> locations = ImmutableSet.builder();\n      if (!Iterables.all(regionsOrJustProvider, LocationPredicates.isProvider()))\n         locations.addAll(regionsOrJustProvider);\n      for (Map.Entry<String, Location> entry : zoneIdToParent.entrySet()) {\n         String zoneId = entry.getKey();\n         Location parent = entry.getValue();\n         LocationBuilder builder = new LocationBuilder().scope(LocationScope.ZONE).id(zoneId).description(zoneId)\n                  .parent(parent);\n         if (isoCodesById.containsKey(zoneId))\n            builder.iso3166Codes(isoCodesById.get(zoneId).get());\n         // be cautious.. only inherit iso codes if the parent is a region\n         // regions may be added dynamically, and we prefer to inherit an\n         // empty set of codes from a region, then a provider, whose code\n         // are likely hard-coded.\n         else if (parent.getScope() == LocationScope.REGION)\n            builder.iso3166Codes(parent.getIso3166Codes());\n         locations.add(builder.build());\n      }\n      return locations.build();\n   }\n\n   private Map<String, Location> setParentOfZoneToRegionOrProvider(Set<String> zoneIds,\n            Set<? extends Location> locations) {\n      // mutable, so that we can query current state when adding. safe as its temporary\n      Map<String, Location> zoneIdToParent = Maps.newLinkedHashMap();\n\n      Location provider = Iterables.find(locations, LocationPredicates.isProvider(), null);\n      if (locations.size() == 1 && provider != null) {\n         for (String zone : zoneIds)\n            zoneIdToParent.put(zone, provider);\n      } else {\n         // note that we only call regionIdToZoneIdsSupplier if there are region locations present\n         // they cannot be, if the above is true\n         Map<String, Supplier<Set<String>>> regionIdToZoneIds = regionIdToZoneIdsSupplier.get();\n         for (Location region : Iterables.filter(locations, LocationPredicates.isRegion())) {\n            provider = region.getParent();\n            if (regionIdToZoneIds.containsKey(region.getId())) {\n               for (String zoneId : regionIdToZoneIds.get(region.getId()).get())\n                  // Just consider the zones provided by the zone supplier (zones can be filtered)\n                  if (zoneIds.contains(zoneId)) {\n                     zoneIdToParent.put(zoneId, region);\n                  }\n            } else {\n               logger.debug(\"no zones configured for region: %s\", region);\n            }\n         }\n      }\n\n      SetView<String> orphans = Sets.difference(zoneIds, zoneIdToParent.keySet());\n      if (!orphans.isEmpty()) {\n         // any unmatched zones should have their parents set to the provider\n         checkState(\n                  provider != null,\n                  \"cannot configure zones %s as we need a parent, and the only available location [%s] is not a provider\",\n                  zoneIds, locations);\n         for (String orphanedZoneId : orphans)\n            zoneIdToParent.put(orphanedZoneId, provider);\n      }\n\n      checkState(zoneIdToParent.keySet().containsAll(zoneIds), \"orphaned zones: %s \", Sets.difference(zoneIds,\n               zoneIdToParent.keySet()));\n      return zoneIdToParent;\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/suppliers/derived/RegionIdsFromRegionIdToURIKeySet.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.suppliers.derived;\n\nimport static com.google.common.base.Throwables.propagate;\n\nimport java.lang.reflect.UndeclaredThrowableException;\nimport java.net.URI;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.location.Region;\nimport org.jclouds.location.suppliers.RegionIdsSupplier;\n\nimport com.google.common.base.Supplier;\nimport com.google.inject.Inject;\n\n/** As opposed to via properties, lets look up regions via api, as they are more likely to change. */\npublic final class RegionIdsFromRegionIdToURIKeySet implements RegionIdsSupplier {\n\n   private final Supplier<Map<String, Supplier<URI>>> regionIdToURIs;\n\n   @Inject\n   RegionIdsFromRegionIdToURIKeySet(@Region Supplier<Map<String, Supplier<URI>>> regionIdToURIs) {\n      this.regionIdToURIs = regionIdToURIs;\n   }\n\n   @Override\n   public Set<String> get() {\n      try {\n         return regionIdToURIs.get().keySet();\n      } catch (UndeclaredThrowableException e) {\n         throw propagate(e.getCause());\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/suppliers/derived/ZoneIdToURIFromJoinOnRegionIdToURI.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.suppliers.derived;\n\nimport static com.google.common.base.Preconditions.checkState;\n\nimport java.net.URI;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.location.Region;\nimport org.jclouds.location.Zone;\nimport org.jclouds.location.suppliers.ZoneIdToURISupplier;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMap.Builder;\n\npublic final class ZoneIdToURIFromJoinOnRegionIdToURI implements ZoneIdToURISupplier {\n\n   private final Supplier<Map<String, Supplier<URI>>> regionIdToURIs;\n   private final Supplier<Map<String, Supplier<Set<String>>>> regionIdToZoneIds;\n\n   @Inject\n   ZoneIdToURIFromJoinOnRegionIdToURI(@Region Supplier<Map<String, Supplier<URI>>> regionIdToURIs,\n         @Zone Supplier<Map<String, Supplier<Set<String>>>> regionIdToZoneIds) {\n      this.regionIdToURIs = regionIdToURIs;\n      this.regionIdToZoneIds = regionIdToZoneIds;\n   }\n\n   @Override\n   public Map<String, Supplier<URI>> get() {\n      Map<String, Supplier<Set<String>>> regionIdToZoneIds = this.regionIdToZoneIds.get();\n      Builder<String, Supplier<URI>> builder = ImmutableMap.builder();\n      for (Entry<String, Supplier<URI>> regionToURI : regionIdToURIs.get().entrySet()) {\n         Supplier<Set<String>> zoneIds = regionIdToZoneIds.get(regionToURI.getKey());\n         checkState(zoneIds != null, \"region %s is not in the configured region to zone mappings: %s\",\n               regionToURI.getKey(), regionIdToZoneIds);\n         for (String zone : zoneIds.get()) {\n            builder.put(zone, regionToURI.getValue());\n         }\n      }\n      return builder.build();\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/suppliers/derived/ZoneIdsFromRegionIdToZoneIdsValues.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.suppliers.derived;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.location.Zone;\nimport org.jclouds.location.suppliers.ZoneIdsSupplier;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableSet;\n\n/** As opposed to via properties, lets look up zones via api, as they are more likely to change. */\npublic final class ZoneIdsFromRegionIdToZoneIdsValues implements ZoneIdsSupplier {\n\n   private final Supplier<Map<String, Supplier<Set<String>>>> regionIdToZoneIds;\n\n   @Inject\n   ZoneIdsFromRegionIdToZoneIdsValues(@Zone Supplier<Map<String, Supplier<Set<String>>>> regionIdToZoneIds) {\n      this.regionIdToZoneIds = regionIdToZoneIds;\n   }\n\n   @Override\n   public Set<String> get() {\n      ImmutableSet.Builder<String> result = ImmutableSet.builder();\n      for (Supplier<Set<String>> zone : regionIdToZoneIds.get().values()) {\n         result.addAll(zone.get());\n      }\n      return result.build();\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/suppliers/derived/ZoneIdsFromZoneIdToURIKeySet.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.suppliers.derived;\n\nimport java.net.URI;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.location.Zone;\nimport org.jclouds.location.suppliers.ZoneIdsSupplier;\n\nimport com.google.common.base.Supplier;\nimport com.google.inject.Inject;\n\n/** As opposed to via properties, lets look up zones via api, as they are more likely to change. */\npublic final class ZoneIdsFromZoneIdToURIKeySet implements ZoneIdsSupplier {\n\n   private final Supplier<Map<String, Supplier<URI>>> zoneIdToURIs;\n\n   @Inject\n   ZoneIdsFromZoneIdToURIKeySet(@Zone Supplier<Map<String, Supplier<URI>>> zoneIdToURIs) {\n      this.zoneIdToURIs = zoneIdToURIs;\n   }\n\n   @Override\n   public Set<String> get() {\n      return zoneIdToURIs.get().keySet();\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/suppliers/fromconfig/LocationIdToIso3166CodesFromConfiguration.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.suppliers.fromconfig;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.location.reference.LocationConstants.ISO3166_CODES;\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_REGION;\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_ZONE;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.location.Iso3166;\nimport org.jclouds.location.suppliers.LocationIdToIso3166CodesSupplier;\nimport org.jclouds.util.Predicates2;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Predicates;\nimport com.google.common.base.Splitter;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMap.Builder;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * \n * looks for properties bound to the naming conventions jclouds.region. {@code regionId}\n * .iso3166-codes and jclouds.zone.{@code zoneId}.iso3166-codes\n */\n@Singleton\npublic class LocationIdToIso3166CodesFromConfiguration implements LocationIdToIso3166CodesSupplier {\n\n   private final Function<Predicate<String>, Map<String, String>> filterStringsBoundByName;\n\n   @Inject\n   public LocationIdToIso3166CodesFromConfiguration(\n            Function<Predicate<String>, Map<String, String>> filterStringsBoundByName) {\n      this.filterStringsBoundByName = checkNotNull(filterStringsBoundByName, \"filterStringsBoundByName\");\n   }\n\n   @Singleton\n   @Iso3166\n   @Override\n   public Map<String, Supplier<Set<String>>> get() {\n      Map<String, String> stringsBoundWithRegionOrZonePrefix = filterStringsBoundByName.apply(Predicates.<String>or(\n             Predicates2.startsWith(PROPERTY_REGION),\n             Predicates2.startsWith(PROPERTY_ZONE)));\n      Builder<String, Supplier<Set<String>>> codes = ImmutableMap.builder();\n      for (String key : ImmutableSet.of(PROPERTY_REGION, PROPERTY_ZONE)) {\n         String regionOrZoneString = stringsBoundWithRegionOrZonePrefix.get(key + \"s\");\n         if (regionOrZoneString == null)\n            continue;\n         for (String region : Splitter.on(',').split(regionOrZoneString)) {\n            String isoCodes = stringsBoundWithRegionOrZonePrefix.get(key + \".\" + region + \".\" + ISO3166_CODES);\n            if (isoCodes != null)\n               codes.put(region, Suppliers.<Set<String>> ofInstance(ImmutableSet.copyOf(Splitter.on(',')\n                        .split(isoCodes))));\n         }\n      }\n      return codes.build();\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/suppliers/fromconfig/LocationIdToURIFromConfigurationOrDefaultToProvider.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.suppliers.fromconfig;\n\nimport static org.jclouds.location.reference.LocationConstants.ENDPOINT;\n\nimport java.net.URI;\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\n\nimport org.jclouds.config.ValueOfConfigurationKeyOrNull;\nimport org.jclouds.location.Provider;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMap.Builder;\nimport com.google.inject.assistedinject.Assisted;\n\npublic class LocationIdToURIFromConfigurationOrDefaultToProvider implements Supplier<Map<String, Supplier<URI>>> {\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   protected final ValueOfConfigurationKeyOrNull config;\n   protected final Supplier<Set<String>> locationIds;\n   protected final Supplier<URI> providerURI;\n   protected final String configPrefix;\n   \n   @Inject\n   public LocationIdToURIFromConfigurationOrDefaultToProvider(ValueOfConfigurationKeyOrNull config, @Provider Supplier<URI> providerURI, @Assisted Supplier<Set<String>> locationIds,\n            @Assisted String configPrefix) {\n      this.config = config;\n      this.locationIds = locationIds;\n      this.providerURI = providerURI;\n      this.configPrefix = configPrefix;\n   }\n\n   @Override\n   public Map<String, Supplier<URI>> get() {\n      Builder<String, Supplier<URI>> locations = ImmutableMap.builder();\n      for (String location : locationIds.get()) {\n         String configKey = configPrefix + \".\" + location + \".\" + ENDPOINT;\n         String locationUri = config.apply(configKey);\n         if (locationUri == null) {\n            logger.debug(\"config key %s not present, defaulting to %s\", configKey, providerURI);\n            locations.put(location, providerURI);\n         } else {\n            locations.put(location, Suppliers.ofInstance(URI.create(locationUri)));\n   \n         }\n      }\n      return locations.build();\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/suppliers/fromconfig/ProviderURIFromProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.suppliers.fromconfig;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.location.suppliers.ProviderURISupplier;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.rest.suppliers.URIFromStringSupplier;\n\n@Singleton\npublic class ProviderURIFromProviderMetadata extends URIFromStringSupplier implements\n         ProviderURISupplier {\n   @Inject\n   protected ProviderURIFromProviderMetadata(ProviderMetadata in) {\n      super(in.getEndpoint());\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/suppliers/fromconfig/RegionIdToURIFromConfigurationOrDefaultToProvider.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.suppliers.fromconfig;\n\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_REGION;\n\nimport java.net.URI;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.config.ValueOfConfigurationKeyOrNull;\nimport org.jclouds.location.Provider;\nimport org.jclouds.location.Region;\nimport org.jclouds.location.suppliers.RegionIdToURISupplier;\n\nimport com.google.common.base.Supplier;\n\n/**\n * \n * looks for properties bound to the naming convention jclouds.region.{@code regionId}.endpoint\n */\n@Singleton\npublic class RegionIdToURIFromConfigurationOrDefaultToProvider extends LocationIdToURIFromConfigurationOrDefaultToProvider implements RegionIdToURISupplier {\n\n   @Inject\n   protected RegionIdToURIFromConfigurationOrDefaultToProvider(ValueOfConfigurationKeyOrNull config, @Provider Supplier<URI> providerURI,\n            @Region Supplier<Set<String>> regionIds) {\n      super(config, providerURI, regionIds, PROPERTY_REGION);\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/suppliers/fromconfig/RegionIdToZoneIdsFromConfiguration.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.suppliers.fromconfig;\n\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_REGION;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.config.ValueOfConfigurationKeyOrNull;\nimport org.jclouds.location.Provider;\nimport org.jclouds.location.Region;\nimport org.jclouds.location.Zone;\nimport org.jclouds.location.suppliers.RegionIdToZoneIdsSupplier;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Splitter;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMap.Builder;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n *\n * looks for properties bound to the naming convention jclouds.location.region.{@code regionId}\n * .zones\n */\n@Singleton\npublic class RegionIdToZoneIdsFromConfiguration implements RegionIdToZoneIdsSupplier {\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   private final ValueOfConfigurationKeyOrNull config;\n   private final String provider;\n   private final Supplier<Set<String>> regionsSupplier;\n\n   @Inject\n   protected RegionIdToZoneIdsFromConfiguration(ValueOfConfigurationKeyOrNull config, @Provider String provider,\n            @Region Supplier<Set<String>> regionsSupplier) {\n      this.config = config;\n      this.provider = provider;\n      this.regionsSupplier = regionsSupplier;\n   }\n\n   @Singleton\n   @Zone\n   @Override\n   public Map<String, Supplier<Set<String>>> get() {\n      Set<String> regions = regionsSupplier.get();\n      if (regions.isEmpty()) {\n         logger.debug(\"no regions configured for provider %s\", provider);\n         return ImmutableMap.of();\n      }\n      Builder<String, Supplier<Set<String>>> regionToZones = ImmutableMap.builder();\n      for (String region : regions) {\n         String configKey = PROPERTY_REGION + \".\" + region + \".zones\";\n         String zones = config.apply(configKey);\n         if (zones == null)\n            logger.debug(\"config key %s not present\", configKey);\n         else\n            regionToZones.put(region, Suppliers.<Set<String>> ofInstance(ImmutableSet.copyOf(Splitter.on(',').split(\n                     zones))));\n      }\n      return regionToZones.build();\n\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/suppliers/fromconfig/RegionIdsFromConfiguration.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.suppliers.fromconfig;\n\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_REGIONS;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.config.ValueOfConfigurationKeyOrNull;\nimport org.jclouds.location.Provider;\nimport org.jclouds.location.suppliers.RegionIdsSupplier;\n\n\n/**\n * \n * looks for properties bound to the naming convention jclouds.regions\n */\n@Singleton\npublic class RegionIdsFromConfiguration extends SplitConfigurationKey implements RegionIdsSupplier {\n\n   @Inject\n   protected RegionIdsFromConfiguration(ValueOfConfigurationKeyOrNull config, @Provider String provider) {\n      super(config, provider, PROPERTY_REGIONS);\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/suppliers/fromconfig/SplitConfigurationKey.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.suppliers.fromconfig;\n\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.config.ValueOfConfigurationKeyOrNull;\nimport org.jclouds.location.Provider;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Splitter;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.assistedinject.Assisted;\n\n@Singleton\npublic class SplitConfigurationKey implements Supplier<Set<String>> {\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   protected final ValueOfConfigurationKeyOrNull config;\n   protected final String provider;\n   protected final String configKey;\n\n   public SplitConfigurationKey(ValueOfConfigurationKeyOrNull config, @Provider String provider,\n            @Assisted String configKey) {\n      this.config = config;\n      this.provider = provider;\n      this.configKey = configKey;\n   }\n\n   @Override\n   public Set<String> get() {\n      String regionString = config.apply(configKey);\n      if (regionString == null) {\n         logger.debug(\"no %s configured for provider %s\", configKey, provider);\n         return ImmutableSet.of();\n      } else {\n         return ImmutableSet.copyOf(Splitter.on(',').split(regionString));\n      }\n   }\n\n   @Override\n   public String toString() {\n      return \"splitConfigurationKey(\" + configKey + \")\";\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/suppliers/fromconfig/ZoneIdToURIFromConfigurationOrDefaultToProvider.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.suppliers.fromconfig;\n\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_ZONE;\n\nimport java.net.URI;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.config.ValueOfConfigurationKeyOrNull;\nimport org.jclouds.location.Provider;\nimport org.jclouds.location.Zone;\nimport org.jclouds.location.suppliers.ZoneIdToURISupplier;\n\nimport com.google.common.base.Supplier;\n\n/**\n * \n * looks for properties bound to the naming convention jclouds.zone.{@code zoneId}.endpoint\n */\n@Singleton\npublic class ZoneIdToURIFromConfigurationOrDefaultToProvider extends LocationIdToURIFromConfigurationOrDefaultToProvider implements ZoneIdToURISupplier {\n\n   @Inject\n   protected ZoneIdToURIFromConfigurationOrDefaultToProvider(ValueOfConfigurationKeyOrNull config, @Provider Supplier<URI> providerURI,\n            @Zone Supplier<Set<String>> zoneIds) {\n      super(config, providerURI, zoneIds, PROPERTY_ZONE);\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/suppliers/fromconfig/ZoneIdsFromConfiguration.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.suppliers.fromconfig;\n\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_ZONES;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.config.ValueOfConfigurationKeyOrNull;\nimport org.jclouds.location.Provider;\nimport org.jclouds.location.suppliers.ZoneIdsSupplier;\n\n\n/**\n * \n * looks for properties bound to the naming convention jclouds.zones\n */\n@Singleton\npublic class ZoneIdsFromConfiguration extends SplitConfigurationKey implements ZoneIdsSupplier {\n\n   @Inject\n   protected ZoneIdsFromConfiguration(ValueOfConfigurationKeyOrNull config, @Provider String provider) {\n      super(config, provider, PROPERTY_ZONES);\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/suppliers/implicit/FirstNetwork.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.suppliers.implicit;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.find;\nimport static com.google.common.collect.Iterables.transform;\nimport static org.jclouds.location.predicates.LocationPredicates.isNetwork;\n\nimport java.util.NoSuchElementException;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.domain.Location;\nimport org.jclouds.location.functions.ToIdAndScope;\nimport org.jclouds.location.suppliers.ImplicitLocationSupplier;\n\nimport com.google.common.base.Supplier;\n\n@Singleton\npublic class FirstNetwork implements ImplicitLocationSupplier {\n\n    private final Supplier<Set<? extends Location>> locationsSupplier;\n\n    @Inject\n    FirstNetwork(@Memoized Supplier<Set<? extends Location>> locationsSupplier) {\n        this.locationsSupplier = checkNotNull(locationsSupplier,\n                \"locationsSupplierSupplier\");\n    }\n\n    @Override\n    public Location get() {\n        Set<? extends Location> locations = locationsSupplier.get();\n        try {\n            return find(locations, isNetwork());\n        } catch (NoSuchElementException e) {\n            throw new NoSuchElementException(\n                    \"none of the locations are scope NETWORK: \"\n                            + transform(locations, ToIdAndScope.INSTANCE));\n        }\n    }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/suppliers/implicit/FirstRegion.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.suppliers.implicit;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.find;\nimport static com.google.common.collect.Iterables.transform;\nimport static org.jclouds.location.predicates.LocationPredicates.isRegion;\n\nimport java.util.NoSuchElementException;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.domain.Location;\nimport org.jclouds.location.functions.ToIdAndScope;\nimport org.jclouds.location.suppliers.ImplicitLocationSupplier;\n\nimport com.google.common.base.Supplier;\n\n@Singleton\npublic class FirstRegion implements ImplicitLocationSupplier {\n\n   private final Supplier<Set<? extends Location>> locationsSupplier;\n\n   @Inject\n   FirstRegion(@Memoized Supplier<Set<? extends Location>> locationsSupplier) {\n      this.locationsSupplier = checkNotNull(locationsSupplier, \"locationsSupplierSupplier\");\n   }\n\n   @Override\n   public Location get() {\n      Set<? extends Location> locations = locationsSupplier.get();\n      try {\n         return find(locations, isRegion());\n      } catch (NoSuchElementException e) {\n         throw new NoSuchElementException(\"none to of the locations are scope REGION: \"\n               + transform(locations, ToIdAndScope.INSTANCE));\n      }\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/suppliers/implicit/FirstZone.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.suppliers.implicit;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.find;\nimport static com.google.common.collect.Iterables.transform;\nimport static org.jclouds.location.predicates.LocationPredicates.isZone;\n\nimport java.util.NoSuchElementException;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.domain.Location;\nimport org.jclouds.location.functions.ToIdAndScope;\nimport org.jclouds.location.suppliers.ImplicitLocationSupplier;\n\nimport com.google.common.base.Supplier;\n\n@Singleton\npublic class FirstZone implements ImplicitLocationSupplier {\n\n   private final Supplier<Set<? extends Location>> locationsSupplier;\n\n   @Inject\n   FirstZone(@Memoized Supplier<Set<? extends Location>> locationsSupplier) {\n      this.locationsSupplier = checkNotNull(locationsSupplier, \"locationsSupplierSupplier\");\n   }\n\n   @Override\n   public Location get() {\n      Set<? extends Location> locations = locationsSupplier.get();\n      try {\n         return find(locations, isZone());\n      } catch (NoSuchElementException e) {\n         throw new NoSuchElementException(\"none to of the locations are scope ZONE: \"\n               + transform(locations, ToIdAndScope.INSTANCE));\n      }\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/suppliers/implicit/GetRegionIdMatchingProviderURIOrNull.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.suppliers.implicit;\n\nimport java.net.URI;\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.location.Provider;\nimport org.jclouds.location.Region;\nimport org.jclouds.location.suppliers.ImplicitRegionIdSupplier;\nimport org.jclouds.suppliers.SupplyKeyMatchingValueOrNull;\n\nimport com.google.common.base.Supplier;\n\n@Singleton\npublic class GetRegionIdMatchingProviderURIOrNull extends SupplyKeyMatchingValueOrNull<String, URI> implements\n         ImplicitRegionIdSupplier {\n\n   @Inject\n   public GetRegionIdMatchingProviderURIOrNull(@Region Supplier<Map<String, Supplier<URI>>> supplier,\n            @Provider Supplier<URI> providerUri) {\n      super(supplier, providerUri);\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/suppliers/implicit/OnlyLocationOrFirstRegionOptionallyMatchingRegionId.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.suppliers.implicit;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static com.google.common.collect.Iterables.transform;\nimport static org.jclouds.location.predicates.LocationPredicates.isRegion;\nimport static org.jclouds.location.predicates.LocationPredicates.isZone;\nimport static org.jclouds.location.predicates.LocationPredicates.isZoneOrRegionWhereRegionIdEquals;\n\nimport java.util.NoSuchElementException;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.location.Region;\nimport org.jclouds.location.functions.ToIdAndScope;\nimport org.jclouds.location.suppliers.ImplicitLocationSupplier;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Predicates;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.Iterables;\n\n@Singleton\npublic class OnlyLocationOrFirstRegionOptionallyMatchingRegionId implements ImplicitLocationSupplier {\n   private final Supplier<String>  regionSupplier;\n   private final Supplier<Set<? extends Location>> locationsSupplier;\n\n   @Inject\n   OnlyLocationOrFirstRegionOptionallyMatchingRegionId(@Region Supplier<String> regionSupplier,\n            @Memoized Supplier<Set<? extends Location>> locationsSupplier) {\n      this.regionSupplier = checkNotNull(regionSupplier, \"regionSupplier\");\n      this.locationsSupplier = checkNotNull(locationsSupplier, \"locationsSupplier\");\n   }\n\n   @Override\n   @Singleton\n   public Location get() {\n      String region = regionSupplier.get();\n      Predicate<Location> locationPredicate = region == null ? Predicates.<Location>or(isZone(), isRegion())\n               : isZoneOrRegionWhereRegionIdEquals(region);\n      Set<? extends Location> locations = locationsSupplier.get();\n      if (locationsSupplier.get().size() == 1)\n         return getOnlyElement(locationsSupplier.get());\n      try {\n         Location toReturn = Iterables.find(locations, locationPredicate);\n         return toReturn.getScope() == LocationScope.REGION ? toReturn : toReturn.getParent();\n      } catch (NoSuchElementException e) {\n         throw new NoSuchElementException(String.format(\"couldn't find region matching %s in %s\", locationPredicate,\n               transform(locations, ToIdAndScope.INSTANCE)));\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/location/suppliers/implicit/OnlyLocationOrFirstZone.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.suppliers.implicit;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.find;\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static com.google.common.collect.Iterables.transform;\nimport static org.jclouds.location.predicates.LocationPredicates.isZone;\n\nimport java.util.NoSuchElementException;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.domain.Location;\nimport org.jclouds.location.functions.ToIdAndScope;\nimport org.jclouds.location.suppliers.ImplicitLocationSupplier;\n\nimport com.google.common.base.Supplier;\n\n@Singleton\npublic class OnlyLocationOrFirstZone implements ImplicitLocationSupplier {\n\n   private final Supplier<Set<? extends Location>> locationsSupplier;\n\n   @Inject\n   OnlyLocationOrFirstZone(@Memoized Supplier<Set<? extends Location>> locationsSupplier) {\n      this.locationsSupplier = checkNotNull(locationsSupplier, \"locationsSupplierSupplier\");\n   }\n\n   @Override\n   public Location get() {\n      Set<? extends Location> locations = locationsSupplier.get();\n      if (locations.size() == 1)\n         return getOnlyElement(locations);\n      try {\n         return find(locations, isZone());\n      } catch (NoSuchElementException e) {\n         throw new NoSuchElementException(\"none to of the locations are scope ZONE: \"\n               + transform(locations, ToIdAndScope.INSTANCE));\n      }\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/logging/BaseLogger.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.logging;\n\n/**\n * Base implementation that constructs formatted log strings.\n */\npublic abstract class BaseLogger implements Logger {\n\n   protected abstract void logError(String message, Throwable e);\n\n   protected abstract void logError(String message);\n\n   protected abstract void logWarn(String message, Throwable e);\n\n   protected abstract void logWarn(String message);\n\n   protected abstract void logInfo(String message);\n\n   protected abstract void logDebug(String message);\n\n   protected abstract void logTrace(String message);\n\n   public void trace(String message, Object... args) {\n      if (isTraceEnabled())\n         logTrace(formatIfArgs(message, args));\n   }\n\n   private String formatIfArgs(String message, Object... args) {\n      return args.length == 0 ? message : String.format(message, args);\n   }\n\n   public void debug(String message, Object... args) {\n      if (isDebugEnabled())\n         logDebug(formatIfArgs(message, args));\n   }\n\n   public void info(String message, Object... args) {\n      if (isInfoEnabled())\n         logInfo(formatIfArgs(message, args));\n   }\n\n   public void warn(String message, Object... args) {\n      if (isWarnEnabled())\n         logWarn(formatIfArgs(message, args));\n   }\n\n   public void warn(Throwable e, String message, Object... args) {\n      if (isWarnEnabled())\n         logWarn(formatIfArgs(message, args), e);\n   }\n\n   public void error(String message, Object... args) {\n      if (isErrorEnabled())\n         logError(formatIfArgs(message, args));\n   }\n\n   public void error(Throwable e, String message, Object... args) {\n      if (isErrorEnabled())\n         logError(formatIfArgs(message, args), e);\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/logging/ConsoleLogger.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.logging;\n\nimport com.google.common.base.Throwables;\n\n/**\n * <tt>Logger</tt> that logs to the console\n * <p />\n * Useful to get baseline performance unaffected by logging.\n */\npublic class ConsoleLogger implements Logger {\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void debug(String message, Object... args) {\n\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void error(String message, Object... args) {\n      System.err.printf(String.format(\"ERROR: %s%n\", message), args);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void error(Throwable throwable, String message, Object... args) {\n      System.err.printf(String.format(\"ERROR: %s%n%s\", message, Throwables\n               .getStackTraceAsString(throwable)), args);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getCategory() {\n      return null;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void info(String message, Object... args) {\n      System.err.printf(String.format(\"INFO: %s%n\", message), args);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public boolean isDebugEnabled() {\n      return false;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public boolean isErrorEnabled() {\n\n      return true;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public boolean isInfoEnabled() {\n\n      return true;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public boolean isTraceEnabled() {\n\n      return false;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public boolean isWarnEnabled() {\n\n      return true;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void trace(String message, Object... args) {\n\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void warn(String message, Object... args) {\n      System.err.printf(String.format(\"WARN: %s%n\", message), args);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void warn(Throwable throwable, String message, Object... args) {\n      System.err.printf(String.format(\"WARN: %s%n%s\", message, Throwables\n               .getStackTraceAsString(throwable)), args);\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/logging/Logger.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.logging;\n\n/**\n * JClouds log abstraction layer.\n * <p/>\n * Implementations of logging are optional and injected if they are configured.\n * <p/>\n * <code> @Resource Logger logger = Logger.NULL;</code> The above will get you a null-safe instance\n * of <tt>Logger</tt>. If configured, this logger will be swapped with a real Logger implementation\n * with category set to the current class name. This is done post-object construction, so do not\n * attempt to use these loggers in your constructor.\n * <p/>\n * If you wish to initialize loggers like these yourself, do not use the @Resource annotation.\n * <p/>\n * This implementation first checks to see if the level is enabled before issuing the log command.\n * In other words, don't do the following\n * <code>if (logger.isTraceEnabled()) logger.trace(\"message\");.\n * <p/>\n */\npublic interface Logger {\n\n   /**\n    * Assign to member to avoid NPE when no logging module is configured.\n    */\n   Logger NULL = new NullLogger();\n\n   /**\n    * Assign to member to avoid NPE when no logging module is configured.\n    */\n   Logger CONSOLE = new ConsoleLogger();\n\n   String getCategory();\n\n   void trace(String message, Object... args);\n\n   boolean isTraceEnabled();\n\n   void debug(String message, Object... args);\n\n   boolean isDebugEnabled();\n\n   void info(String message, Object... args);\n\n   boolean isInfoEnabled();\n\n   void warn(String message, Object... args);\n\n   void warn(Throwable throwable, String message, Object... args);\n\n   boolean isWarnEnabled();\n\n   void error(String message, Object... args);\n\n   void error(Throwable throwable, String message, Object... args);\n\n   boolean isErrorEnabled();\n\n   /**\n    * Produces instances of {@link Logger} relevant to the specified category\n    * \n    * \n    */\n   public interface LoggerFactory {\n      Logger getLogger(String category);\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/logging/LoggingModules.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.logging;\n\nimport static com.google.common.collect.Iterables.find;\n\nimport java.util.NoSuchElementException;\nimport java.util.ServiceLoader;\n\nimport org.jclouds.logging.config.LoggingModule;\nimport org.jclouds.logging.jdk.config.JDKLoggingModule;\n\nimport com.google.common.base.Predicates;\n\n/**\n * The LoggingModules class provides static methods for accessing\n * loggingModules.\n */\npublic class LoggingModules {\n\n   /**\n    * Returns the {@link LoggingModule}s located on the classpath via\n    * {@link java.util.ServiceLoader}.\n    * \n    */\n   private static Iterable<LoggingModule> fromServiceLoader() {\n      return ServiceLoader.load(LoggingModule.class);\n   }\n\n   /**\n    * all available {@link LoggingModule}s\n    */\n   public static Iterable<LoggingModule> all() {\n      return fromServiceLoader();\n   }\n\n   /**\n    * the first available {@link LoggingModule}s from\n    * {@link java.util.ServiceLoader} or {@link JDKLoggingModule}\n    */\n   public static LoggingModule firstOrJDKLoggingModule() {\n      try {\n         return find(ServiceLoader.load(LoggingModule.class),\n               Predicates.not(Predicates.instanceOf(JDKLoggingModule.class)));\n      } catch (NoSuchElementException e) {\n         return new JDKLoggingModule();\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/logging/NullLogger.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.logging;\n\nimport com.google.common.base.Throwables;\n\n/**\n * <tt>Logger</tt> that doesn't do anything.\n * <p />\n * Useful to get baseline performance unaffected by logging.\n */\npublic class NullLogger implements Logger {\n\n   public void debug(String message, Object... args) {\n\n   }\n\n   public void error(String message, Object... args) {\n      System.err.printf(message + \"%n\", args);\n   }\n\n   public void error(Throwable throwable, String message, Object... args) {\n      System.err.printf(message, args);\n      System.err.printf(\"%n%s\", Throwables.getStackTraceAsString(throwable));\n   }\n\n   public String getCategory() {\n\n      return null;\n   }\n\n   public void info(String message, Object... args) {\n\n   }\n\n   public boolean isDebugEnabled() {\n\n      return false;\n   }\n\n   public boolean isErrorEnabled() {\n\n      return true;\n   }\n\n   public boolean isInfoEnabled() {\n\n      return false;\n   }\n\n   public boolean isTraceEnabled() {\n\n      return false;\n   }\n\n   public boolean isWarnEnabled() {\n\n      return false;\n   }\n\n   public void trace(String message, Object... args) {\n\n   }\n\n   public void warn(String message, Object... args) {\n\n   }\n\n   public void warn(Throwable throwable, String message, Object... args) {\n\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/logging/config/BindLoggersAnnotatedWithResource.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.logging.config;\n\nimport static com.google.common.collect.Sets.filter;\n\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.Field;\nimport java.util.Arrays;\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\n\nimport org.jclouds.logging.Logger;\nimport org.jclouds.logging.Logger.LoggerFactory;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Sets;\nimport com.google.inject.ProvisionException;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.spi.InjectionListener;\nimport com.google.inject.spi.TypeEncounter;\nimport com.google.inject.spi.TypeListener;\n\n/**\n * TypeListener that will bind {@link org.jclouds.logging.Logger} to members annotated with\n * {@link jakarta.annotation.Resource}\n * <p/>\n * This class is a TypeListener so that it can create a logger whose category is\n * the same as the name of the injected instance's class.\n * <p/>\n * Note that this occurs post-object construction through\n * {@link com.google.inject.Binder#bindListener}.\n * <p/>\n * Here's an example usage:\n * <pre>\n *     class A {\n *         @Resource private Logger logger = Logger.NULL;\n *     }\n * <p/>\n *     Injector i = Guice.createInjector(new AbstractModule() {\n *         @Override protected void configure() {\n *             bindListener(any(), new\n *                 BindLoggersAnnotatedWithResource( new\n *                     JDKLogger.JDKLoggerFactory()));\n *         }\n *     });\n * <p/>\n *     A = i.getInstance(A.class);\n *     // A will now have a logger associated with it\n * </pre>\n */\npublic class BindLoggersAnnotatedWithResource implements TypeListener {\n\n    static class AssignLoggerToField<I> implements InjectionListener<I> {\n        private final Logger logger;\n        private final Field field;\n\n        AssignLoggerToField(Logger logger, Field field) {\n            this.logger = logger;\n            this.field = field;\n        }\n\n        public void afterInjection(I injectee) {\n            try {\n                field.setAccessible(true);\n                field.set(injectee, logger);\n            } catch (IllegalAccessException e) {\n                throw new ProvisionException(e.getMessage(), e);\n            }\n        }\n    }\n\n    static class LoggerFieldsAnnotatedWithResource implements\n            Predicate<Field> {\n        public boolean apply(Field from) {\n            Annotation inject = from.getAnnotation(Resource.class);\n            return inject != null && from.getType().isAssignableFrom(Logger.class);\n        }\n    }\n\n    private final LoggerFactory loggerFactory;\n\n    @Inject\n    public BindLoggersAnnotatedWithResource(LoggerFactory loggerFactory) {\n        this.loggerFactory = loggerFactory;\n    }\n\n    public <I> void hear(TypeLiteral<I> injectableType,\n                         TypeEncounter<I> encounter) {\n\n        Class<? super I> type = injectableType.getRawType();\n        Set<Field> loggerFields = getLoggerFieldsAnnotatedWithResource(type);\n        if (loggerFields.isEmpty())\n            return;\n\n        Logger logger = loggerFactory.getLogger(type.getName());\n\n        for (Field field : loggerFields) {\n           if (field.isAnnotationPresent(Named.class)) {\n              Named name = field.getAnnotation(Named.class);\n              encounter.register(new AssignLoggerToField<I>(loggerFactory.getLogger(name.value()), field));\n           } else {\n              encounter.register(new AssignLoggerToField<I>(logger, field));\n           }\n        }\n    }\n\n    @VisibleForTesting\n    Set<Field> getLoggerFieldsAnnotatedWithResource(Class<?> declaredType) {\n        Set<Field> fields = Sets.newHashSet();\n        Class<?> type = declaredType;\n        while (type != null) {\n            fields.addAll(Arrays.asList(type.getDeclaredFields()));\n            type = type.getSuperclass();\n        }\n        return filter(fields, new LoggerFieldsAnnotatedWithResource());\n    }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/logging/config/ConsoleLoggingModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.logging.config;\n\nimport org.jclouds.logging.Logger;\n\n/**\n * Configures logging of type {@link ConsoleLogger}\n */\npublic class ConsoleLoggingModule extends LoggingModule {\n\n   public Logger.LoggerFactory createLoggerFactory() {\n      return new Logger.LoggerFactory() {\n         public Logger getLogger(String category) {\n            return Logger.CONSOLE;\n         }\n      };\n   }\n\n   /**\n    * note that we override, as if we are not logging, there's no use in the overhead of listening\n    * for loggers\n    */\n   @Override\n   protected void configure() {\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/logging/config/LoggingModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.logging.config;\n\nimport static com.google.inject.matcher.Matchers.any;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.logging.Logger;\n\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Provides;\n\n/**\n * Creates a post-injection listener that binds Loggers named the same as the enclosing class.\n */\npublic abstract class LoggingModule extends AbstractModule {\n\n   @Override\n   protected void configure() {\n      bindListener(any(), new BindLoggersAnnotatedWithResource(createLoggerFactory()));\n   }\n\n   @Provides\n   @Singleton\n   public final Logger.LoggerFactory provideLoggerFactory() {\n      return createLoggerFactory();\n   }\n\n   public abstract Logger.LoggerFactory createLoggerFactory();\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/logging/config/NullLoggingModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.logging.config;\n\nimport org.jclouds.logging.Logger;\n\n/**\n * Configures logging of type {@link NullLogger}\n */\npublic class NullLoggingModule extends LoggingModule {\n\n   public Logger.LoggerFactory createLoggerFactory() {\n      return new Logger.LoggerFactory() {\n         public Logger getLogger(String category) {\n            return Logger.NULL;\n         }\n      };\n   }\n\n   /**\n    * note that we override, as if we are not logging, there's no use in the overhead of listening\n    * for loggers\n    */\n   @Override\n   protected void configure() {\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/logging/internal/Wire.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.logging.internal;\n\nimport com.google.common.io.ByteStreams;\nimport com.google.common.io.FileBackedOutputStream;\nimport org.jclouds.Constants;\nimport org.jclouds.io.MutableContentMetadata;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.PayloadEnclosing;\nimport org.jclouds.logging.Logger;\n\nimport jakarta.annotation.Resource;\nimport java.io.ByteArrayInputStream;\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileNotFoundException;\nimport java.io.FilterInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.io.Payloads.newPayload;\nimport static org.jclouds.util.Closeables2.closeQuietly;\n\n/**\n * Logs data to the wire LOG, similar to {@code org.apache.HttpWire.impl.conn.Wire}\n */\npublic abstract class Wire {\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   protected abstract Logger getWireLog();\n\n   protected boolean isLogSensitiveInformation() {\n      return false;\n   }\n\n   private void wire(String header, InputStream instream) {\n      StringBuilder buffer = new StringBuilder();\n      int ch;\n      try {\n         while ((ch = instream.read()) != -1) {\n            if (ch == 13) {\n               buffer.append(\"[\\\\r]\");\n            } else if (ch == 10) {\n               buffer.append(\"[\\\\n]\\\"\");\n               buffer.insert(0, \"\\\"\");\n               buffer.insert(0, header);\n               getWireLog().debug(buffer.toString());\n               buffer.setLength(0);\n            } else if ((ch < 32) || (ch > 127)) {\n               buffer.append(\"[0x\");\n               buffer.append(Integer.toHexString(ch));\n               buffer.append(\"]\");\n            } else {\n               buffer.append((char) ch);\n            }\n         }\n         if (buffer.length() > 0) {\n            buffer.append('\\\"');\n            buffer.insert(0, '\\\"');\n            buffer.insert(0, header);\n            getWireLog().debug(buffer.toString());\n         }\n      } catch (IOException e) {\n         logger.error(e, \"Error tapping line\");\n      }\n   }\n\n   public boolean enabled() {\n      return getWireLog().isDebugEnabled();\n   }\n\n   public InputStream copy(final String header, InputStream instream) {\n      int limit = 256 * 1024;\n      final FileBackedOutputStream out = new FileBackedOutputStream(limit);\n      try {\n         long bytesRead = ByteStreams.copy(instream, out);\n         if (bytesRead >= limit)\n            logger.debug(\"over limit %d/%d: wrote temp file\", bytesRead, limit);\n         InputStream is = out.asByteSource().openStream();\n         try {\n            wire(header, is);\n         } finally {\n            is.close();\n         }\n         // we must call FileBackedOutputStream.reset to remove temporary file\n         return new FilterInputStream(out.asByteSource().openStream()) {\n            @Override\n            public void close() throws IOException {\n               super.close();\n               out.reset();\n            }\n         };\n      } catch (IOException e) {\n         throw new RuntimeException(\"Error tapping line\", e);\n      } finally {\n         closeQuietly(out);\n         closeQuietly(instream);\n      }\n   }\n\n   public InputStream input(InputStream instream) {\n      return copy(\"<< \", checkNotNull(instream, \"input\"));\n   }\n\n   public void input(PayloadEnclosing request) {\n      Payload oldContent = request.getPayload();\n      Payload wiredPayload;\n      if (!oldContent.isSensitive() || isLogSensitiveInformation()) {\n         wiredPayload = newPayload(input(oldContent.getInput()));\n      } else {\n         wiredPayload = newPayload(oldContent.getInput());\n      }\n      wiredPayload.setSensitive(oldContent.isSensitive());\n      copyPayloadMetadata(oldContent, wiredPayload);\n      request.setPayload(wiredPayload);\n   }\n\n   public void output(PayloadEnclosing request) {\n      Payload oldContent = request.getPayload();\n      Payload wiredPayload;\n      if (!oldContent.isSensitive() || isLogSensitiveInformation()) {\n         try {\n            wiredPayload = newPayload(output(oldContent.getRawContent()));\n         } catch (UnsupportedOperationException e) {\n            wiredPayload = newPayload(output(oldContent.getInput()));\n         }\n      } else {\n         try {\n            wiredPayload = newPayload(oldContent.getRawContent());\n         } catch (UnsupportedOperationException e) {\n            wiredPayload = newPayload(oldContent.getInput());\n         }\n         output(\"Sensitive data in payload, use \" + Constants.PROPERTY_LOGGER_WIRE_LOG_SENSITIVE_INFO + \" override to enable logging this data.\");\n      }\n      wiredPayload.setSensitive(oldContent.isSensitive());\n      copyPayloadMetadata(oldContent, wiredPayload);\n      request.setPayload(wiredPayload);\n   }\n\n   private void copyPayloadMetadata(Payload oldContent, Payload wiredPayload) {\n      MutableContentMetadata oldMd = oldContent.getContentMetadata();\n      MutableContentMetadata wiredMd = wiredPayload.getContentMetadata();\n      if (oldMd.getContentLength() != null)\n         wiredMd.setContentLength(oldMd.getContentLength());\n      wiredMd.setCacheControl(oldMd.getCacheControl());\n      wiredMd.setContentType(oldMd.getContentType());\n      wiredMd.setContentMD5(oldMd.getContentMD5());\n      wiredMd.setContentDisposition(oldMd.getContentDisposition());\n      wiredMd.setContentEncoding(oldMd.getContentEncoding());\n      wiredMd.setContentLanguage(oldMd.getContentLanguage());\n      wiredMd.setExpires(oldMd.getExpires());\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   public <T> T output(T data) {\n      checkNotNull(data, \"data\");\n      if (data instanceof InputStream) {\n         return (T) copy(\">> \", (InputStream) data);\n      } else if (data instanceof byte[]) {\n         output((byte[]) data);\n         return data;\n      } else if (data instanceof String) {\n         output((String) data);\n         return data;\n      } else if (data instanceof File) {\n         output((File) data);\n         return data;\n      }\n      throw new UnsupportedOperationException(\"Content not supported \" + data.getClass());\n   }\n\n   private void output(final File out) {\n      checkNotNull(out, \"output\");\n      InputStream in = null;\n      try {\n         in = new FileInputStream(out);\n         wire(\">> \", in);\n      } catch (FileNotFoundException e) {\n         logger.error(e, \"Error tapping file: %s\", out);\n      } finally {\n         closeQuietly(in);\n      }\n   }\n\n   private void output(byte[] b) {\n      wire(\">> \", new ByteArrayInputStream(checkNotNull(b, \"output\")));\n   }\n\n   private void output(final String s) {\n      output(checkNotNull(s, \"output\").getBytes());\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/logging/jdk/JDKLogger.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.logging.jdk;\n\nimport java.util.logging.Level;\n\nimport org.jclouds.logging.BaseLogger;\nimport org.jclouds.logging.Logger;\n\n/**\n * {@link java.util.logging.Logger} implementation of {@link Logger}.\n */\npublic class JDKLogger extends BaseLogger {\n   private final java.util.logging.Logger logger;\n\n   public static class JDKLoggerFactory implements LoggerFactory {\n      public Logger getLogger(String category) {\n         return new JDKLogger(java.util.logging.Logger.getLogger(category));\n      }\n   }\n\n   public JDKLogger(java.util.logging.Logger logger) {\n      this.logger = logger;\n   }\n\n   @Override\n   protected void logTrace(String message) {\n      logger.finest(message);\n   }\n\n   public boolean isTraceEnabled() {\n      return logger.isLoggable(Level.FINEST);\n   }\n\n   @Override\n   protected void logDebug(String message) {\n      logger.fine(message);\n   }\n\n   public boolean isDebugEnabled() {\n      return logger.isLoggable(Level.FINE);\n   }\n\n   @Override\n   protected void logInfo(String message) {\n      logger.info(message);\n   }\n\n   public boolean isInfoEnabled() {\n      return logger.isLoggable(Level.INFO);\n   }\n\n   @Override\n   protected void logWarn(String message) {\n      logger.warning(message);\n   }\n\n   @Override\n   protected void logWarn(String message, Throwable e) {\n      logger.log(Level.WARNING, message, e);\n   }\n\n   public boolean isWarnEnabled() {\n      return logger.isLoggable(Level.WARNING);\n   }\n\n   @Override\n   protected void logError(String message) {\n      logger.severe(message);\n   }\n\n   @Override\n   protected void logError(String message, Throwable e) {\n      logger.log(Level.SEVERE, message, e);\n   }\n\n   public boolean isErrorEnabled() {\n      return logger.isLoggable(Level.SEVERE);\n   }\n\n   public String getCategory() {\n      return logger.getName();\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/logging/jdk/config/JDKLoggingModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.logging.jdk.config;\n\nimport org.jclouds.logging.Logger;\nimport org.jclouds.logging.config.LoggingModule;\nimport org.jclouds.logging.jdk.JDKLogger;\n\nimport com.google.auto.service.AutoService;\n\n/**\n * Configures logging of type {@link JDKLogger}\n */\n@AutoService(LoggingModule.class)\npublic class JDKLoggingModule extends LoggingModule {\n   @Override\n   public Logger.LoggerFactory createLoggerFactory() {\n       return new JDKLogger.JDKLoggerFactory();\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/osgi/Activator.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.osgi;\n\nimport org.osgi.framework.BundleActivator;\nimport org.osgi.framework.BundleContext;\nimport org.osgi.framework.ServiceReference;\nimport org.osgi.util.tracker.ServiceTracker;\n\npublic class Activator implements BundleActivator {\n\n   private ServiceTracker providerListenerTracker = null;\n   private ServiceTracker apiListenerTracker = null;\n   private MetadataBundleListener bundleListener = new MetadataBundleListener();\n\n   /**\n    * Called when this bundle is started so the Framework can perform the bundle-specific activities necessary to start\n    * this bundle. This method can be used to register services or to allocate any resources that this bundle needs.\n    * <p/>\n    * <p/>\n    * This method must complete and return to its caller in a timely manner.\n    * \n    * @param context\n    *           The execution context of the bundle being started.\n    * @throws Exception\n    *            If this method throws an exception, this bundle is marked as stopped and the Framework will remove this\n    *            bundle's listeners, unregister all services registered by this bundle, and release all services used by\n    *            this bundle.\n    */\n   @Override\n   public void start(BundleContext context) throws Exception {\n      bundleListener.start(context);\n      providerListenerTracker = new ServiceTracker(context, ProviderListener.class.getName(), null) {\n         @Override\n         public Object addingService(ServiceReference reference) {\n            Object obj = super.addingService(reference);\n            if (ProviderListener.class.isAssignableFrom(obj.getClass())) {\n               bundleListener.addProviderListener((ProviderListener) obj);\n            }\n            return obj;\n         }\n\n         @Override\n         public void removedService(ServiceReference reference, Object service) {\n            if (ProviderListener.class.isAssignableFrom(service.getClass())) {\n               bundleListener.removeProviderListener((ProviderListener) service);\n            }\n            super.removedService(reference, service);\n         }\n      };\n\n      apiListenerTracker = new ServiceTracker(context, ApiListener.class.getName(), null) {\n         @Override\n         public Object addingService(ServiceReference reference) {\n            Object obj = super.addingService(reference);\n            if (ApiListener.class.isAssignableFrom(obj.getClass())) {\n               bundleListener.addApiListenerListener((ApiListener) obj);\n            }\n            return obj;\n         }\n\n         @Override\n         public void removedService(ServiceReference reference, Object service) {\n            if (ApiListener.class.isAssignableFrom(service.getClass())) {\n               bundleListener.removeApiListenerListener((ApiListener) service);\n            }\n            super.removedService(reference, service);\n         }\n      };\n\n      providerListenerTracker.open();\n      apiListenerTracker.open();\n   }\n\n   /**\n    * Called when this bundle is stopped so the Framework can perform the bundle-specific activities necessary to stop\n    * the bundle. In general, this method should undo the work that the <code>BundleActivator.start</code> method\n    * started. There should be no active threads that were started by this bundle when this bundle returns. A stopped\n    * bundle must not call any Framework objects.\n    * <p/>\n    * <p/>\n    * This method must complete and return to its caller in a timely manner.\n    * \n    * @param context\n    *           The execution context of the bundle being stopped.\n    * @throws Exception\n    *            If this method throws an exception, the bundle is still marked as stopped, and the Framework will\n    *            remove the bundle's listeners, unregister all services registered by the bundle, and release all\n    *            services used by the bundle.\n    */\n   @Override\n   public void stop(BundleContext context) throws Exception {\n      bundleListener.stop(context);\n      ProviderRegistry.clear();\n      ApiRegistry.clear();\n      if (apiListenerTracker != null) {\n         apiListenerTracker.close();\n      }\n      if (providerListenerTracker != null) {\n         providerListenerTracker.close();\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/osgi/ApiListener.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.osgi;\n\nimport org.jclouds.apis.ApiMetadata;\n\n/**\n * A listener interface for {@link org.jclouds.apis.ApiMetadata}. In OSGi a api can be added or removed dynamically.\n * OSGi services using this interface will receive a notification whenever this happens.\n */\npublic interface ApiListener {\n\n   /**\n    * Method to be called when an api gets added.\n    * \n    * @param api\n    *           The api that was added.\n    * @param <A>\n    *           The {@link org.jclouds.apis.ApiMetadata}.\n    */\n   <A extends ApiMetadata> void added(A api);\n\n   /**\n    * Method to be called when an api gets removed.\n    * \n    * @param api\n    *           The api that was added.\n    * @param <A>\n    *           The {@link ApiMetadata}.\n    */\n   <A extends ApiMetadata> void removed(A api);\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/osgi/ApiRegistry.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.osgi;\n\nimport java.util.Set;\n\nimport org.jclouds.apis.ApiMetadata;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.collect.Sets;\n\n/**\n * A registry for holding {@link org.jclouds.apis.ApiMetadata}.\n */\n@Beta\npublic class ApiRegistry {\n\n   private static final Set<ApiMetadata> apis = Sets.newHashSet();\n\n   public static void registerApi(ApiMetadata api) {\n      apis.add(api);\n   }\n\n   public static void unRegisterApi(ApiMetadata api) {\n      apis.remove(api);\n   }\n\n   public static Iterable<ApiMetadata> fromRegistry() {\n      return apis;\n   }\n\n   public static void clear() {\n      apis.clear();\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/osgi/Bundles.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.osgi;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Predicates.notNull;\nimport static org.jclouds.util.Strings2.toStringAndClose;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.lang.reflect.InvocationTargetException;\nimport java.net.URL;\n\nimport org.osgi.framework.Bundle;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Utility functions helpful in working with {@link Bundle bundles}.\n */\npublic final class Bundles {\n   private Bundles() {\n   }\n\n   /**\n    * instantiates the supplied classnames using the bundle classloader, and casts to the supplied type. Any errors are\n    * silently ignored.\n    *\n    * @return instances that could be instantiated without error.\n    */\n   public static <T> ImmutableSet<T> instantiateAvailableClasses(Bundle bundle, Iterable<String> classNames,\n         Class<T> type) {\n      checkNotNull(bundle, \"bundle\");\n      checkNotNull(classNames, \"classNames\");\n      checkNotNull(type, \"type\");\n      return FluentIterable.from(classNames)\n                           .transform(loadClassIfAssignableFrom(bundle, type))\n                           .filter(notNull())\n                           .transform(instantiateIfPossible(type))\n                           .filter(notNull())\n                           .toSet();\n   }\n\n   /**\n    * A function that loads classes from the bundle, or returns null if the class isn't found or assignable by the input\n    * parameter\n    *\n    * @param bundle\n    *           where to find classes\n    * @param clazz\n    *           type classes must be assignable from\n    */\n   private static Function<String, Class<?>> loadClassIfAssignableFrom(final Bundle bundle, final Class<?> clazz) {\n      checkNotNull(bundle, \"bundle\");\n      checkNotNull(clazz, \"clazz\");\n      return new Function<String, Class<?>>() {\n         @Override\n         public Class<?> apply(String in) {\n            checkNotNull(in, \"classname\");\n            try {\n               Class<?> thing = bundle.loadClass(in);\n               // Classes loaded by other class loaders are not assignable.\n               if (clazz.isAssignableFrom(thing))\n                  return thing.asSubclass(clazz);\n            } catch (ClassNotFoundException e) {\n            }\n            return null;\n         }\n      };\n   }\n\n   /**\n    * A function that instantiates classes or returns null, if it encounters any problems.\n    *\n    * @param clazz\n    *           superclass to cast as\n    */\n   private static <T> Function<Class<?>, T> instantiateIfPossible(final Class<T> clazz) {\n      return new Function<Class<?>, T>() {\n         @Override\n         public T apply(Class<?> in) {\n            checkNotNull(in, \"input class\");\n            try {\n               return clazz.cast(in.getConstructor().newInstance());\n            } catch (InstantiationException e) {\n            } catch (IllegalAccessException e) {\n            } catch (InvocationTargetException e) {\n            } catch (NoSuchMethodException e) {\n            }\n            return null;\n         }\n      };\n   }\n\n   /**\n    * Reads the resource from a {@link Bundle}.\n    *\n    * @param resourcePath\n    *           The path to the resource.\n    * @param bundle\n    *           The bundle to read from.\n    * @return strings delimited by newline in the stream or empty set, on any exception.\n    */\n   public static ImmutableSet<String> stringsForResourceInBundle(String resourcePath, Bundle bundle) {\n      checkNotNull(resourcePath, \"resourcePath\");\n      checkNotNull(bundle, \"bundle\");\n\n      URL resource = bundle.getEntry(resourcePath);\n      if (resource == null)\n         return ImmutableSet.of();\n      try {\n         return ImmutableSet.copyOf(splitOrEmptyAndClose(resource.openStream()));\n      } catch (IOException e) {\n      } catch (RuntimeException ex) {\n      }\n      return ImmutableSet.of();\n   }\n\n   private static Iterable<String> splitOrEmptyAndClose(InputStream in) throws IOException {\n      return Splitter.onPattern(\"\\r?\\n\").omitEmptyStrings().split(toStringAndClose(in));\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/osgi/MetadataBundleListener.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.osgi;\n\nimport static org.jclouds.osgi.Bundles.instantiateAvailableClasses;\nimport static org.jclouds.osgi.Bundles.stringsForResourceInBundle;\nimport static org.osgi.framework.BundleEvent.STARTED;\nimport static org.osgi.framework.BundleEvent.STOPPED;\nimport static org.osgi.framework.BundleEvent.STOPPING;\n\nimport java.util.List;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.osgi.framework.Bundle;\nimport org.osgi.framework.BundleContext;\nimport org.osgi.framework.BundleEvent;\nimport org.osgi.framework.BundleListener;\n\nimport com.google.common.collect.ArrayListMultimap;\nimport com.google.common.collect.Lists;\nimport com.google.common.collect.Multimap;\n\n/**\n * A {@link BundleListener} that listens for {@link BundleEvent} and searches for\n * {@link org.jclouds.providers.ProviderMetadata} and {@link org.jclouds.apis.ApiMetadata} in newly installed Bundles.\n * This is used as a workaround for OSGi environments where the ServiceLoader cannot cross bundle boundaries.\n */\npublic class MetadataBundleListener implements BundleListener {\n\n   private final Multimap<Long, ProviderMetadata> providerMetadataMap = ArrayListMultimap.create();\n   private final Multimap<Long, ApiMetadata> apiMetadataMap = ArrayListMultimap.create();\n\n   private final List<ProviderListener> providerListeners = Lists.newArrayList();\n   private final List<ApiListener> apiListeners = Lists.newArrayList();\n\n   /**\n    * Starts the listener. Checks the bundles that are already active and registers {@link ProviderMetadata} and\n    * {@link ApiMetadata} found. Registers the itself as a {@link BundleListener}.\n    * \n    * @param bundleContext\n    */\n   public synchronized void start(BundleContext bundleContext) {\n      bundleContext.addBundleListener(this);\n      for (Bundle bundle : bundleContext.getBundles()) {\n         if (bundle.getState() == Bundle.ACTIVE) {\n            addBundle(bundle);\n         }\n      }\n      bundleContext.addBundleListener(this);\n   }\n\n   /**\n    * Stops the listener. Removes itself from the {@link BundleListener}s. Clears metadata maps and listeners lists.\n    * \n    * @param bundleContext\n    */\n   public void stop(BundleContext bundleContext) {\n      bundleContext.removeBundleListener(this);\n      providerMetadataMap.clear();\n      apiMetadataMap.clear();\n      apiListeners.clear();\n      providerListeners.clear();\n   }\n\n   @Override\n   public synchronized void bundleChanged(BundleEvent event) {\n      switch (event.getType()) {\n      case STARTED:\n         addBundle(event.getBundle());\n         break;\n      case STOPPING:\n      case STOPPED:\n         removeBundle(event.getBundle());\n         break;\n      }\n   }\n\n   /**\n    * Searches for {@link ProviderMetadata} and {@link ApiMetadata} inside the {@link Bundle}. If metadata are found\n    * they are registered in the {@link ProviderRegistry} and {@link ApiRegistry}. Also the {@link ProviderListener} and\n    * {@link ApiListener} are notified.\n    * \n    * @param bundle\n    */\n   private synchronized void addBundle(Bundle bundle) {\n      for (ProviderMetadata providerMetadata : listProviderMetadata(bundle)) {\n         if (providerMetadata != null) {\n            ProviderRegistry.registerProvider(providerMetadata);\n            providerMetadataMap.put(bundle.getBundleId(), providerMetadata);\n            for (ProviderListener listener : providerListeners) {\n               listener.added(providerMetadata);\n            }\n         }\n      }\n\n      for (ApiMetadata apiMetadata : listApiMetadata(bundle)) {\n         if (apiMetadata != null) {\n            ApiRegistry.registerApi(apiMetadata);\n            apiMetadataMap.put(bundle.getBundleId(), apiMetadata);\n            for (ApiListener listener : apiListeners) {\n               listener.added(apiMetadata);\n            }\n         }\n      }\n   }\n\n   /**\n    * Searches for {@link ProviderMetadata} and {@link ApiMetadata} registered under the {@link Bundle} id. If metadata\n    * are found they are removed the {@link ProviderRegistry} and {@link ApiRegistry}. Also the {@link ProviderListener}\n    * and {@link ApiListener} are notified.\n    * \n    * @param bundle\n    */\n   private synchronized void removeBundle(Bundle bundle) {\n      for (ProviderMetadata providerMetadata : providerMetadataMap.removeAll(bundle.getBundleId())) {\n         ProviderRegistry.unregisterProvider(providerMetadata);\n         for (ProviderListener listener : providerListeners) {\n            listener.removed(providerMetadata);\n         }\n      }\n      for (ApiMetadata apiMetadata : apiMetadataMap.removeAll(bundle.getBundleId())) {\n         ApiRegistry.unRegisterApi(apiMetadata);\n         for (ApiListener listener : apiListeners) {\n            listener.removed(apiMetadata);\n         }\n      }\n   }\n\n   /**\n    * Creates an instance of {@link ProviderMetadata} from the {@link Bundle}.\n    * \n    * @param bundle\n    * @return\n    */\n   public Iterable<ProviderMetadata> listProviderMetadata(Bundle bundle) {\n      Iterable<String> classNames = stringsForResourceInBundle(\n            \"/META-INF/services/org.jclouds.providers.ProviderMetadata\", bundle);\n      return instantiateAvailableClasses(bundle, classNames, ProviderMetadata.class);\n   }\n\n   /**\n    * Creates an instance of {@link ApiMetadata} from the {@link Bundle}.\n    * \n    * @param bundle\n    * @return\n    */\n   public Iterable<ApiMetadata> listApiMetadata(Bundle bundle) {\n      Iterable<String> classNames = stringsForResourceInBundle(\"/META-INF/services/org.jclouds.apis.ApiMetadata\", bundle);\n      return instantiateAvailableClasses(bundle, classNames, ApiMetadata.class);\n   }\n\n   /**\n    * Adds a {@link ProviderListener} and notifies it of existing {@link ProviderMetadata}.\n    * \n    * @param listener\n    *           The listener.\n    */\n   public synchronized void addProviderListener(ProviderListener listener) {\n      providerListeners.add(listener);\n      for (ProviderMetadata metadata : providerMetadataMap.values()) {\n         listener.added(metadata);\n      }\n   }\n\n   /**\n    * Removes the {@link ProviderListener}\n    * \n    * @param listener\n    *           The listener\n    */\n   public synchronized void removeProviderListener(ProviderListener listener) {\n      providerListeners.remove(listener);\n   }\n\n   /**\n    * Adds a {@link ApiListener} and notifies it of existing {@link ApiMetadata}.\n    * \n    * @param listener\n    */\n   public synchronized void addApiListenerListener(ApiListener listener) {\n      apiListeners.add(listener);\n      for (ApiMetadata metadata : apiMetadataMap.values()) {\n         listener.added(metadata);\n      }\n   }\n\n   /**\n    * Removes the {@link ApiListener}\n    * \n    * @param listener\n    */\n   public synchronized void removeApiListenerListener(ApiListener listener) {\n      apiListeners.remove(listener);\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/osgi/ProviderListener.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.osgi;\n\nimport org.jclouds.providers.ProviderMetadata;\n\n/**\n * A listener interface for {@link ProviderMetadata}. In OSGi a provider can be added or removed dynamically. OSGi\n * services using this interface will receive a notification whenever this happens.\n */\npublic interface ProviderListener {\n\n   /**\n    * Method to be called when a Provider gets added.\n    * \n    * @param provider\n    *           The provider that was added.\n    * @param <P>\n    *           The {@link ProviderMetadata}.\n    */\n   <P extends ProviderMetadata> void added(P provider);\n\n   /**\n    * Method to be called when a Provider gets removed.\n    * \n    * @param provider\n    *           The provider that was added.\n    * @param <P>\n    *           The {@link ProviderMetadata}.\n    */\n   <P extends ProviderMetadata> void removed(P provider);\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/osgi/ProviderRegistry.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.osgi;\n\nimport java.util.Set;\n\nimport org.jclouds.providers.ProviderMetadata;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.collect.Sets;\n\n/**\n * A registry for holding {@link org.jclouds.providers.ProviderMetadata}.\n */\n@Beta\npublic class ProviderRegistry {\n\n   private static final Set<ProviderMetadata> providers = Sets.newHashSet();\n\n   public static void registerProvider(ProviderMetadata provider) {\n      providers.add(provider);\n   }\n\n   public static void unregisterProvider(ProviderMetadata provider) {\n      providers.remove(provider);\n   }\n\n   public static Iterable<ProviderMetadata> fromRegistry() {\n      return providers;\n   }\n\n   public static void clear() {\n      providers.clear();\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/predicates/InetSocketAddressConnect.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.net.Proxy;\nimport java.net.Socket;\nimport java.net.URI;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Function;\nimport com.google.common.net.HostAndPort;\nimport com.google.inject.Inject;\n\n/**\n * \n * Tests to see if a socket is open.\n */\n@Singleton\npublic class InetSocketAddressConnect implements SocketOpen {\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   @Inject(optional = true)\n   @Named(\"org.jclouds.socket_timeout\")\n   private int timeout = 2000;\n\n   private final Function<URI, Proxy> proxyForURI;\n\n   @VisibleForTesting\n   @Inject\n   InetSocketAddressConnect(Function<URI, Proxy> proxyForURI) {\n      this.proxyForURI = checkNotNull(proxyForURI, \"proxyForURI\");\n   }\n   \n   @Override\n   public boolean apply(HostAndPort socketA) {\n      InetSocketAddress socketAddress = new InetSocketAddress(socketA.getHost(), socketA\n               .getPort());\n      Socket socket = null;\n      try {\n         logger.trace(\"testing socket %s\", socketAddress);\n         socket = new Socket(\n               proxyForURI.apply(URI.create(\"socket://\" + socketA.getHost() + \":\" + socketA.getPort())));\n         socket.setReuseAddress(false);\n         socket.setSoLinger(false, 1);\n         socket.setSoTimeout(timeout);\n         socket.connect(socketAddress, timeout);\n      } catch (IOException e) {\n         return false;\n      } finally {\n         if (socket != null) {\n            try {\n               socket.close();\n            } catch (IOException ioe) {\n               // no work to do\n            }\n         }\n      }\n      return true;\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/predicates/SocketOpen.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.predicates;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.net.HostAndPort;\nimport com.google.inject.ImplementedBy;\n\n/**\n * \n * Tests to see if a socket is open.\n */\n@ImplementedBy(InetSocketAddressConnect.class)\npublic interface SocketOpen extends Predicate<HostAndPort> {\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/predicates/SocketOpenUnsupported.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.predicates;\n\nimport jakarta.inject.Singleton;\n\nimport com.google.common.net.HostAndPort;\n\n@Singleton\npublic class SocketOpenUnsupported implements SocketOpen {\n\n   @Override\n   public boolean apply(HostAndPort socketA) {\n      throw new UnsupportedOperationException(\"socket testing not configured\");\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/predicates/Validator.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.predicates;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.Predicate;\n\n/**\n * Abstract class that creates a bridge between {@link com.google.common.base.Predicate}\n * and {@link org.jclouds.rest.annotations.ParamValidators}s.\n *\n * @param <T> Type of object to be validated. For generic\n * validation (where object's class is determined in {@link #validate(Object)},\n * use {@link Object}.\n *\n * @see com.google.common.base.Predicate\n */\npublic abstract class Validator<T> implements Predicate<T> {\n\n    @Override\n    public boolean apply(@Nullable T t) {\n        validate(t);\n        return true; // by contract, if no exception thrown\n    }\n\n    // TODO: add @Override after upgrading to Java 8\n    public boolean test(@Nullable T t) {\n        return apply(t);\n    }\n\n    /**\n     * Validates the parameter\n     * @param t parameter to be validated\n     * @throws IllegalArgumentException if validation failed\n     */\n    public abstract void validate(@Nullable T t) throws IllegalArgumentException;\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/predicates/validators/AllLowerCaseValidator.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.predicates.validators;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.predicates.Validator;\n\n/**\n * Validates that the string parameter doesn't have any uppercase letters.\n * \n * @see org.jclouds.rest.InputParamValidator\n * @see org.jclouds.predicates.Validator\n */\npublic class AllLowerCaseValidator extends Validator<String> {\n\n   public void validate(@Nullable String s) {\n      if (!(s == null || s.toLowerCase().equals(s))) {\n         throw new IllegalArgumentException(String.format(\n                  \"Object '%s' doesn't match the lower case\", s));\n      }\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/predicates/validators/DnsNameValidator.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.predicates.validators;\n\nimport static com.google.common.base.CharMatcher.inRange;\nimport static com.google.common.base.CharMatcher.is;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\n\nimport org.jclouds.predicates.Validator;\n\nimport com.google.common.base.CharMatcher;\nimport com.google.inject.Singleton;\n\n/**\n * Validates name for dns-style names\n * \n * @see org.jclouds.rest.InputParamValidator\n * @see org.jclouds.predicates.Validator\n */\n@Singleton\npublic class DnsNameValidator extends Validator<String> {\n   private int min;\n   private int max;\n\n   @Inject\n   public DnsNameValidator(@Named(\"jclouds.dns_name_length_min\") int min,\n            @Named(\"jclouds.dns_name_length_max\") int max) {\n      this.min = min;\n      this.max = max;\n   }\n\n   public void validate(String name) {\n      if (name == null || name.isEmpty() || name.length() < min || name.length() > max)\n         throw exception(name, \"Can't be null or empty. Length must be \" + min + \" to \" + max\n                  + \" symbols.\");\n      if (!Character.isLetterOrDigit(name.charAt(0)))\n         throw exception(name, \"Should start with letter/number\");\n      if (!name.toLowerCase().equals(name))\n         throw exception(name, \"Should be only lowercase\");\n\n      /*\n       * The name must be a valid DNS name. From wikipedia: \"The characters allowed in a label are a\n       * subset of the ASCII character set, a and includes the characters a through z, A through Z,\n       * digits 0 through 9\". From Azure: Every Dash (-) Must Be Immediately Preceded and Followed\n       * by a Letter or Number.\n       */\n      CharMatcher range = getAcceptableRange();\n      if (!range.matchesAllOf(name))\n         throw exception(name, \"Should have lowercase ASCII letters, \" + \"numbers, or dashes\");\n   }\n\n   protected CharMatcher getAcceptableRange() {\n      return inRange('a', 'z').or(inRange('0', '9').or(is('-')));\n   }\n\n   protected IllegalArgumentException exception(String vAppName, String reason) {\n      return new IllegalArgumentException(String.format(\n               \"Object '%s' doesn't match dns naming constraints. \" + \"Reason: %s.\", vAppName,\n               reason));\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/providers/AnonymousProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.providers;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\nimport org.jclouds.rest.AnonymousHttpApiMetadata;\n\n/**\n * Useful in creating arbitrary clients.\n */\npublic class AnonymousProviderMetadata extends BaseProviderMetadata {\n\n   public static <A> ProviderMetadata forApiOnEndpoint(Class<A> api, String endpoint) {\n      return forApiWithEndpoint(AnonymousHttpApiMetadata.forApi(api), endpoint);\n   }\n\n   public static ProviderMetadata forApiWithEndpoint(ApiMetadata md, String endpoint) {\n      checkNotNull(md, \"api\");\n      checkNotNull(endpoint, \"endpoint (%s)\", md.getEndpointName());\n      return new AnonymousProviderMetadata(md, endpoint);\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return (Builder) new Builder(getApiMetadata(), getEndpoint()).fromProviderMetadata(this);\n   }\n\n   public AnonymousProviderMetadata(ApiMetadata apiMetadata, String endpoint) {\n      super(new Builder(apiMetadata, endpoint));\n   }\n\n   public AnonymousProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static class Builder extends BaseProviderMetadata.Builder {\n\n      public Builder(ApiMetadata apiMetadata, String endpoint) {\n         id(checkNotNull(apiMetadata, \"apiMetadata\").getId())\n         .name(apiMetadata.getName())\n         .apiMetadata(apiMetadata)\n         .endpoint(endpoint);\n      }\n\n      @Override\n      public AnonymousProviderMetadata build() {\n         return new AnonymousProviderMetadata(this);\n      }\n\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/providers/ProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.providers;\n\nimport java.net.URI;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.Optional;\n\n/**\n * The ProviderMetadata interface allows jclouds to provide a plugin framework\n * for gathering cloud provider metadata.\n */\npublic interface ProviderMetadata {\n  \n   /**\n    * \n    * @since 1.5\n    */\n   public interface Builder {\n      /**\n       * @see ProviderMetadata#getId()\n       */\n      Builder id(String id);\n\n      /**\n       * @see ProviderMetadata#getName()\n       */\n      Builder name(String name);\n\n      /**\n       * @see ProviderMetadata#getApiMetadata()\n       */\n      Builder apiMetadata(ApiMetadata api);\n\n      /**\n       * @see ProviderMetadata#getEndpoint()\n       */\n      Builder endpoint(String endpoint);\n\n      /**\n       * @see ProviderMetadata#getDefaultProperties()\n       */\n      Builder defaultProperties(Properties defaultProperties);\n\n      /**\n       * @see ProviderMetadata#getConsole()\n       */\n      Builder console(@Nullable URI console);\n\n      /**\n       * @see ProviderMetadata#getHomepage()\n       */\n      Builder homepage(@Nullable URI homepage);\n\n      /**\n       * @see ProviderMetadata#getLinkedServices()\n       */\n      Builder linkedServices(Iterable<String> linkedServices);\n\n      /**\n       * @see ProviderMetadata#getLinkedServices()\n       */\n      Builder linkedServices(String... linkedServices);\n\n      /**\n       * @see ProviderMetadata#getLinkedServices()\n       */\n      Builder linkedService(String linkedService);\n\n      /**\n       * @see ProviderMetadata#getIso3166Code()\n       */\n      Builder iso3166Codes(Iterable<String> iso3166Codes);\n\n      /**\n       * @see ProviderMetadata#getIso3166Code()\n       */\n      Builder iso3166Codes(String... iso3166Codes);\n\n      /**\n       * @see ProviderMetadata#getIso3166Code()\n       */\n      Builder iso3166Code(String iso3166Code);\n\n      ProviderMetadata build();\n\n      Builder fromProviderMetadata(ProviderMetadata in);\n\n   }\n\n   /**\n    * @see Builder\n    * @since 1.5\n    */\n   Builder toBuilder();\n\n   /**\n    * \n    * @return the provider's unique identifier (ex. aws-ec2, rackspace-cloudservers-us)\n    */\n   String getId();\n\n   /**\n    * \n    * @return the name (display name) of the provider (ex. GoGrid)\n    */\n   String getName();\n\n   /**\n    * \n    * @return the provider's api\n    * @since 1.5\n    */\n   ApiMetadata getApiMetadata();\n\n   /**\n    * @see ApiMetadata#getEndpoint\n    * @return the url for the provider's api\n    */\n   String getEndpoint();\n\n   /**\n    * Configuration Properties used when creating connections to this provider.\n    * For example, location information, or default networking configuration.\n    * \n    * @return properties used to create connections to this provider\n    * @see ApiMetadata#getDefaultProperties\n    */\n   Properties getDefaultProperties();\n\n   /**\n    * \n    * @return the url for the provider's console, or absent if one doesn't exist\n    */\n   Optional<URI> getConsole();\n\n   /**\n    * \n    * @return the url for the provider's homepage, or absent if unknown\n    */\n   Optional<URI> getHomepage();\n\n   /**\n    * \n    * @return ids of all known {@link ProviderMetadata providers} which have the\n    *         same account as this.\n    */\n   Set<String> getLinkedServices();\n\n   /**\n    * iso 3166 codes; ex. US-CA,US\n    * \n    * @return all known region/location ISO 3166 codes\n    */\n   Set<String> getIso3166Codes();\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/providers/ProviderPredicates.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.providers;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Strings.emptyToNull;\n\nimport org.jclouds.Context;\nimport org.jclouds.View;\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.apis.ApiPredicates;\nimport org.jclouds.util.TypeTokenUtils;\n\nimport com.google.common.base.Preconditions;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Predicates;\nimport com.google.common.reflect.TypeToken;\n\n/**\n * Container for provider filters (predicates).\n */\npublic class ProviderPredicates {\n\n   public static class ContextAssignableFrom implements Predicate<ProviderMetadata> {\n      private final TypeToken<? extends Context> type;\n\n      public ContextAssignableFrom(TypeToken<? extends Context> type) {\n         Preconditions.checkNotNull(type, \"context must be defined\");\n         this.type = type;\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public boolean apply(ProviderMetadata providerMetadata) {\n         return ApiPredicates.contextAssignableFrom(type).apply(providerMetadata.getApiMetadata());\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public String toString() {\n         return \"contextAssignableFrom(\" + type + \")\";\n      }\n   }\n   \n   public static class TransformableTo implements Predicate<ProviderMetadata> {\n      private final TypeToken<? extends View> type;\n\n      public TransformableTo(TypeToken<? extends View> type) {\n         Preconditions.checkNotNull(type, \"context must be defined\");\n         this.type = type;\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public boolean apply(ProviderMetadata providerMetadata) {\n         return ApiPredicates.viewableAs(type).apply(providerMetadata.getApiMetadata());\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public String toString() {\n         return \"viewableAs(\" + type + \")\";\n      }\n   }\n\n   /**\n    * Returns all providers available to jclouds regardless of type.\n    * \n    * @return all available providers\n    */\n   public static Predicate<ProviderMetadata> all() {\n      return Predicates.<ProviderMetadata> alwaysTrue();\n   }\n\n   /**\n    * Returns all providers with the given id.\n    * \n    * @param id\n    *           the id of the provider to return\n    * \n    * @return the providers with the given id\n    */\n   public static Predicate<ProviderMetadata> id(final String id) {\n      checkNotNull(emptyToNull(id), \"id must be defined\");\n      return new Predicate<ProviderMetadata>() {\n         /**\n          * {@inheritDoc}\n          */\n         @Override\n         public boolean apply(ProviderMetadata providerMetadata) {\n            return providerMetadata.getId().equals(id);\n         }\n\n         /**\n          * {@inheritDoc}\n          */\n         @Override\n         public String toString() {\n            return \"id(\" + id + \")\";\n         }\n      };\n   }\n\n   /**\n    * Returns the providers that are bound to the same location as the given ISO\n    * 3166 code.\n    * \n    * @param isoCode\n    *           the ISO 3166 code to filter providers by\n    * \n    * @return the providers with the given ISO 3166 code\n    */\n   public static Predicate<ProviderMetadata> boundedByIso3166Code(final String iso3166Code) {\n      Preconditions.checkNotNull(iso3166Code, \"iso3166Code must not be null\");\n\n      return new Predicate<ProviderMetadata>() {\n         /**\n          * {@inheritDoc}\n          */\n         @Override\n         public boolean apply(ProviderMetadata providerMetadata) {\n            return providerContainsIso3166Code(providerMetadata, iso3166Code);\n         }\n\n         /**\n          * {@inheritDoc}\n          */\n         @Override\n         public String toString() {\n            return \"boundedByIso3166Code(\" + iso3166Code + \")\";\n         }\n      };\n   }\n\n   /**\n    * Return all providers that have at least one ISO 3166 code in common with\n    * the given provider metadata.\n    * \n    * @param refProviderMetadata\n    *           the provider metadata to use to filter providers by\n    * \n    * @return the providers that have at least one ISO 3166 code in common\n    */\n   public static Predicate<ProviderMetadata> intersectingIso3166Code(\n         final ProviderMetadata refProviderMetadata) {\n      Preconditions.checkNotNull(refProviderMetadata, \"refProviderMetadata must not be null\");\n\n      return new Predicate<ProviderMetadata>() {\n         /**\n          * {@inheritDoc}\n          */\n         @Override\n         public boolean apply(ProviderMetadata providerMetadata) {\n            for (String refIso3166Code : refProviderMetadata.getIso3166Codes()) {\n               // Return only if the potential provider contains the same ISO\n               // 3166 code and the provider and\n               // reference provider are not the same.\n               if (providerContainsIso3166Code(providerMetadata, refIso3166Code)\n                     && !refProviderMetadata.equals(providerMetadata)) {\n                  return true;\n               }\n            }\n            return false;\n         }\n\n         /**\n          * {@inheritDoc}\n          */\n         @Override\n         public String toString() {\n            return \"intersectingIso3166Code(\" + refProviderMetadata + \")\";\n         }\n      };\n   }\n\n   /**\n    * Returns whether or not the provided provider contains the ISO 3166 code\n    * provider or is within the same \"global\" region, like \"US\" would contain\n    * \"US-*\".\n    * \n    * @param providerMetadata\n    *           the provider metadata to search\n    * @param iso3166Code\n    *           the ISO 3166 code to search the provider metadata for\n    * \n    * @return the result\n    */\n   private static boolean providerContainsIso3166Code(ProviderMetadata providerMetadata, String iso3166Code) {\n      for (String availCode : providerMetadata.getIso3166Codes()) {\n         if (iso3166Code.indexOf('-') == -1) {\n            if (availCode.startsWith(iso3166Code + \"-\")) {\n               return true;\n            }\n         } else if (availCode.equals(iso3166Code)) {\n            return true;\n         }\n      }\n\n      return false;\n   }\n\n   /**\n    * Returns all providers with an apimetadata assignable from the given api.\n    * \n    * @param apiClass\n    *           the api of the provider to return\n    * \n    * @return the providers with an apimetadata assignable from the given api.\n    */\n   public static  Predicate<ProviderMetadata> apiMetadataAssignableFrom(\n         final TypeToken<? extends ApiMetadata> apiClass) {\n      Preconditions.checkNotNull(apiClass, \"api must be defined\");\n      return new Predicate<ProviderMetadata>() {\n         /**\n          * {@inheritDoc}\n          */\n         @Override\n         public boolean apply(ProviderMetadata providerMetadata) {\n            return TypeTokenUtils.isSupertypeOf(apiClass, providerMetadata.getApiMetadata().getClass());\n         }\n\n         /**\n          * {@inheritDoc}\n          */\n         @Override\n         public String toString() {\n            return \"apiAssignableFrom(\" + apiClass + \")\";\n         }\n      };\n   }\n\n   /**\n    * Returns all providers with an context assignable from the given type.\n    * \n    * @param type\n    *           the context of the provider to return\n    * \n    * @return the providers with an context assignable from the given type.\n    */\n   public static Predicate<ProviderMetadata> contextAssignableFrom(final TypeToken<? extends Context> type) {\n      return new ContextAssignableFrom(type);\n   }\n\n   /**\n    * Returns all providers with an context transformable to the given type.\n    * \n    * @param type\n    *           the context you wish to achieve ex. {@code BlobStoreContext}\n    * \n    * @return the providers with an context transformable to from the given type.\n    */\n   public static Predicate<ProviderMetadata> viewableAs(final TypeToken<? extends View> type) {\n      return new TransformableTo(type);\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/providers/Providers.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.providers;\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.find;\nimport static org.jclouds.reflect.Reflection2.typeToken;\n\nimport java.util.NoSuchElementException;\nimport java.util.ServiceLoader;\n\nimport org.jclouds.Context;\nimport org.jclouds.View;\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.osgi.ProviderRegistry;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Preconditions;\nimport com.google.common.base.Predicates;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.reflect.TypeToken;\n\n/**\n * The Providers class provides static methods for accessing providers.\n */\npublic class Providers {\n\n   public static enum IdFunction implements Function<ProviderMetadata, String> {\n      INSTANCE;\n\n      @Override\n      public String apply(ProviderMetadata input) {\n         return input.getId();\n      }\n\n   }\n\n   public static Function<ProviderMetadata, String> idFunction() {\n      return IdFunction.INSTANCE;\n   }\n\n   public static class ApiMetadataFunction implements Function<ProviderMetadata, ApiMetadata> {\n      @Override\n      public ApiMetadata apply(ProviderMetadata input) {\n         return input.getApiMetadata();\n      }\n\n   }\n\n   public static Function<ProviderMetadata, ApiMetadata> apiMetadataFunction() {\n      return new ApiMetadataFunction();\n   }\n\n   /**\n    * Returns the providers located on the classpath via {@link java.util.ServiceLoader}.\n    * \n    * @return all available providers loaded from classpath via ServiceLoader\n    */\n   public static Iterable<ProviderMetadata> fromServiceLoader() {\n      return ServiceLoader.load(ProviderMetadata.class);\n   }\n\n   /**\n    * Returns all available providers.\n    * \n    * @return all available providers\n    */\n   public static Iterable<ProviderMetadata> all() {\n     return ImmutableSet.<ProviderMetadata>builder()\n                        .addAll(fromServiceLoader())\n                        .addAll(ProviderRegistry.fromRegistry()).build();\n   }\n\n   /**\n    * Returns the first provider with the provided id\n    * \n    * @param id\n    *           the id of the provider to return\n    * \n    * @return the provider with the given id\n    * \n    * @throws NoSuchElementException\n    *            whenever there are no providers with the provided id\n    */\n   public static ProviderMetadata withId(String id) throws NoSuchElementException {\n      return find(all(), ProviderPredicates.id(id));\n   }\n\n   /**\n    * Returns the providers that are of the provided viewableAs.\n    * \n    * @param viewableAs\n    *           the viewableAs to providers to return\n    * \n    * @return the providers of the provided viewableAs\n    */\n   public static Iterable<ProviderMetadata> viewableAs(TypeToken<? extends View> viewableAs) {\n      return filter(all(), ProviderPredicates.viewableAs(viewableAs));\n   }\n\n   public static Iterable<ProviderMetadata> viewableAs(Class<? extends View> viewableAs) {\n      return filter(all(), ProviderPredicates.viewableAs(typeToken(viewableAs)));\n   }\n\n   /**\n    * Returns the providers that are of the provided api.\n    * \n    * @param api\n    *           the api to providers to return\n    * \n    * @return the providers of the provided api\n    */\n   public static Iterable<ProviderMetadata> apiMetadataAssignableFrom(TypeToken<? extends ApiMetadata> api) {\n      Preconditions.checkNotNull(api, \"api must be defined\");\n      return filter(all(), ProviderPredicates.apiMetadataAssignableFrom(api));\n   }\n\n   /**\n    * Returns the providers that are of the provided context.\n    * \n    * @param context\n    *           the context to providers to return\n    * \n    * @return the providers of the provided context\n    */\n   public static <C extends Context> Iterable<ProviderMetadata> contextAssignableFrom(\n            TypeToken<? extends Context> context) {\n      Preconditions.checkNotNull(context, \"context must be defined\");\n      return filter(all(), new ProviderPredicates.ContextAssignableFrom(context));\n   }\n\n   /**\n    * Returns the providers that are bound to the same location as the given ISO 3166 code\n    * regardless of viewableAs.\n    * \n    * @param isoCode\n    *           the ISO 3166 code to filter providers by\n    * \n    * @return the providers bound by the given ISO 3166 code\n    */\n   public static Iterable<ProviderMetadata> boundedByIso3166Code(String iso3166Code) {\n      return filter(all(), ProviderPredicates.boundedByIso3166Code(iso3166Code));\n   }\n\n   /**\n    * Returns the providers that are bound to the same location as the given ISO 3166 code and of\n    * the given viewableAs.\n    * \n    * @param iso3166Code\n    *           the ISO 3166 code to filter providers by\n    * @param viewableAs\n    *           the viewableAs to filter providers by\n    * \n    * @return the providers bound by the given ISO 3166 code and of the proper viewableAs\n    */\n   public static Iterable<ProviderMetadata> boundedByIso3166Code(String iso3166Code,\n            TypeToken<? extends View> viewableAs) {\n      return filter(all(), Predicates.and(ProviderPredicates.boundedByIso3166Code(iso3166Code), ProviderPredicates\n               .viewableAs(viewableAs)));\n   }\n\n   public static Iterable<ProviderMetadata> boundedByIso3166Code(String iso3166Code,\n            Class<? extends View> viewableAs) {\n      return boundedByIso3166Code(iso3166Code, typeToken(viewableAs));\n   }\n\n   /**\n    * Returns the providers that have at least one common ISO 3166 code in common regardless of\n    * viewableAs.\n    * \n    * @param providerMetadata\n    *           the provider metadata to use to filter providers by\n    * \n    * @return the providers that share at least one common ISO 3166 code\n    */\n   public static Iterable<ProviderMetadata> collocatedWith(ProviderMetadata providerMetadata) {\n      return filter(all(), ProviderPredicates.intersectingIso3166Code(providerMetadata));\n   }\n\n   /**\n    * Returns the providers that have at least one common ISO 3166 code and are of the given\n    * viewableAs.\n    * \n    * @param providerMetadata\n    *           the provider metadata to use to filter providers by\n    * @param viewableAs\n    *           the viewableAs to filter providers by\n    * \n    * @return the providers that share at least one common ISO 3166 code and of the given\n    *         viewableAs\n    */\n   public static Iterable<ProviderMetadata> collocatedWith(ProviderMetadata providerMetadata,\n            TypeToken<? extends View> viewableAs) {\n      return filter(all(), Predicates.and(ProviderPredicates.intersectingIso3166Code(providerMetadata),\n               ProviderPredicates.viewableAs(viewableAs)));\n   }\n\n   public static Iterable<ProviderMetadata> collocatedWith(ProviderMetadata providerMetadata,\n            Class<? extends View> viewableAs) {\n      return collocatedWith(providerMetadata, typeToken(viewableAs));\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/providers/config/BindProviderMetadataContextAndCredentials.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.providers.config;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Properties;\nimport java.util.Set;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Context;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.location.Iso3166;\nimport org.jclouds.location.Provider;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.rest.annotations.Api;\nimport org.jclouds.rest.annotations.ApiVersion;\nimport org.jclouds.rest.annotations.BuildVersion;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.reflect.TypeToken;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Injector;\nimport com.google.inject.Key;\nimport com.google.inject.Provides;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.name.Names;\n\n/**\n * Binds data inside {@link ProviderMetadata} to types with scopes qualified with annotations in the\n * {@code org.jclouds.location} and {@code org.jclouds.rest.annotations} packages. It also binds the\n * properties specified in {@link ProviderMetadata#getDefaultProperties()} {@link ProviderMetadata}\n * explicitly. Finally, it bind the context type so that it can be looked up later.\n */\npublic class BindProviderMetadataContextAndCredentials extends AbstractModule {\n\n   private final ProviderMetadata providerMetadata;\n   private final Supplier<Credentials> creds;\n\n   public BindProviderMetadataContextAndCredentials(ProviderMetadata providerMetadata, Supplier<Credentials> creds) {\n      this.providerMetadata = checkNotNull(providerMetadata, \"providerMetadata\");\n      this.creds = checkNotNull(creds, \"creds\");\n   }\n\n   @Override\n   protected void configure() {\n      bind(ProviderMetadata.class).toInstance(providerMetadata);\n      Properties toBind = new Properties();\n      toBind.putAll(providerMetadata.getApiMetadata().getDefaultProperties());\n      toBind.putAll(providerMetadata.getDefaultProperties());\n      Names.bindProperties(binder(), toBind);\n      bind(new TypeLiteral<Supplier<Credentials>>(){}).annotatedWith(Provider.class).toInstance(creds);\n      bindConstant().annotatedWith(Provider.class).to(providerMetadata.getId());\n      bind(new TypeLiteral<Set<String>>() {\n      }).annotatedWith(Iso3166.class).toInstance(providerMetadata.getIso3166Codes());\n      bindConstant().annotatedWith(Api.class).to(providerMetadata.getApiMetadata().getId());\n      bindConstant().annotatedWith(ApiVersion.class).to(providerMetadata.getApiMetadata().getVersion());\n      // nullable\n      bind(String.class).annotatedWith(BuildVersion.class).toProvider(\n               com.google.inject.util.Providers.of(providerMetadata.getApiMetadata().getBuildVersion().orNull()));\n      bind(new TypeLiteral<TypeToken<? extends Context>>() {\n      }).annotatedWith(Provider.class).toInstance(providerMetadata.getApiMetadata().getContext());\n   }\n\n   @Provides\n   @Provider\n   @Singleton\n   protected Context backend(Injector i, @Provider TypeToken<? extends Context> backendType) {\n      return Context.class.cast(i.getInstance(Key.get(TypeLiteral.get(backendType.getType()))));\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/providers/internal/BaseProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.providers.internal;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.addAll;\nimport static com.google.common.collect.Sets.newLinkedHashSet;\n\nimport java.net.URI;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.providers.ProviderMetadata;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.Optional;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * The BaseProviderMetadata class is an abstraction of {@link ProviderMetadata} to be extended by\n * those implementing ProviderMetadata.\n * \n * (Note: This class must be abstract to allow {@link java.util.ServiceLoader} to work properly.\n */\npublic abstract class BaseProviderMetadata implements ProviderMetadata {\n\n   @Override\n   public ProviderMetadata.Builder toBuilder() {\n      return new BaseProviderMetadata.Builder().fromProviderMetadata(this);\n   }\n\n   public static class Builder implements ProviderMetadata.Builder {\n      protected String id;\n      protected String name;\n      protected ApiMetadata api;\n      protected String endpoint;\n      protected Properties defaultProperties = new Properties();\n      protected URI console;\n      protected URI homepage;\n      protected Set<String> linkedServices = newLinkedHashSet();\n      protected Set<String> iso3166Codes = newLinkedHashSet();\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder id(String id) {\n         this.id = checkNotNull(id, \"id\");\n         return linkedService(id);\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder name(String name) {\n         this.name = checkNotNull(name, \"name\");\n         return this;\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder apiMetadata(ApiMetadata api) {\n         this.api = checkNotNull(api, \"api\");\n         if (this.endpoint == null)\n            this.endpoint = api.getDefaultEndpoint().orNull();\n         return this;\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder endpoint(String endpoint) {\n         this.endpoint = checkNotNull(endpoint, \"endpoint\");\n         return this;\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder defaultProperties(Properties defaultProperties) {\n         this.defaultProperties = checkNotNull(defaultProperties, \"defaultProperties\");\n         return this;\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder console(@Nullable URI console) {\n         this.console = console;\n         return this;\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder homepage(URI homepage) {\n         this.homepage = homepage;\n         return this;\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder linkedServices(Iterable<String> linkedServices) {\n         addAll(this.linkedServices, checkNotNull(linkedServices, \"linkedServices\"));\n         return this;\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder linkedServices(String... linkedServices) {\n         return linkedServices(ImmutableSet.copyOf(checkNotNull(linkedServices, \"linkedServices\")));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder linkedService(String linkedService) {\n         this.linkedServices.add(checkNotNull(linkedService, \"linkedService\"));\n         return this;\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder iso3166Codes(Iterable<String> iso3166Codes) {\n         addAll(this.iso3166Codes, checkNotNull(iso3166Codes, \"iso3166Codes\"));\n         return this;\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder iso3166Codes(String... iso3166Codes) {\n         return iso3166Codes(ImmutableSet.copyOf(checkNotNull(iso3166Codes, \"iso3166Codes\")));\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder iso3166Code(String iso3166Code) {\n         this.iso3166Codes.add(checkNotNull(iso3166Code, \"iso3166Code\"));\n         return this;\n      }\n\n      /**\n       * {@inheritDoc}\n       */\n      @Override\n      public Builder fromProviderMetadata(ProviderMetadata in) {\n         return id(in.getId()).name(in.getName()).apiMetadata(in.getApiMetadata()).endpoint(in.getEndpoint())\n                  .defaultProperties(in.getDefaultProperties()).console(in.getConsole().orNull()).homepage(\n                           in.getHomepage().orNull()).linkedServices(in.getLinkedServices()).iso3166Codes(\n                           in.getIso3166Codes());\n      }\n\n      @Override\n      public ProviderMetadata build() {\n         return new BaseProviderMetadata(this) {\n         };\n      }\n   }\n\n   protected final String id;\n   protected final String name;\n   protected final ApiMetadata api;\n   protected final String endpoint;\n   protected final Properties defaultProperties;\n   protected final Optional<URI> homepage;\n   protected final Optional<URI> console;\n   protected final Set<String> linkedServices;\n   protected final Set<String> iso3166Codes;\n\n   public BaseProviderMetadata(Builder builder) {\n      this(builder.id, builder.name, builder.api, builder.endpoint, builder.defaultProperties, Optional\n               .fromNullable(builder.homepage), Optional.fromNullable(builder.console), builder.linkedServices,\n               builder.iso3166Codes);\n   }\n\n   public BaseProviderMetadata(String id, String name, ApiMetadata api, String endpoint, Properties defaultProperties,\n            Optional<URI> homepage, Optional<URI> console, Set<String> linkedServices, Set<String> iso3166Codes) {\n      this.id = checkNotNull(id, \"id\");\n      this.name = checkNotNull(name, \"name\");\n      this.api = checkNotNull(api, \"api\");\n      this.endpoint = checkNotNull(endpoint, \"endpoint\");\n      this.console = checkNotNull(console, \"console\");\n      this.defaultProperties = checkNotNull(defaultProperties, \"defaultProperties\");\n      this.homepage = checkNotNull(homepage, \"homepage\");\n      this.linkedServices = ImmutableSet.copyOf(linkedServices);\n      this.iso3166Codes = ImmutableSet.copyOf(iso3166Codes);\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o)\n         return true;\n      // subclass equivalence is ok, since we don't know the classloader\n      // we'll get things from\n      if (o == null || !(o instanceof ProviderMetadata))\n         return false;\n      ProviderMetadata that = ProviderMetadata.class.cast(o);\n      return equal(this.getId(), that.getId()) && equal(this.getName(), that.getName())\n               && equal(this.getApiMetadata(), that.getApiMetadata()) && equal(this.getEndpoint(), that.getEndpoint());\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(getId(), getName(), getApiMetadata(), getEndpoint());\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   public ToStringHelper string() {\n      return MoreObjects.toStringHelper(\"\").add(\"id\", getId()).add(\"name\", getName()).add(\"api\", getApiMetadata()).add(\n               \"endpoint\", getEndpoint()).add(\"console\", getConsole()).add(\"homepage\", getHomepage()).add(\n               \"linkedServices\", getLinkedServices()).add(\"iso3166Codes\", getIso3166Codes());\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getId() {\n      return id;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getName() {\n      return name;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ApiMetadata getApiMetadata() {\n      return api;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getEndpoint() {\n      return endpoint;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Optional<URI> getConsole() {\n      return console;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Properties getDefaultProperties() {\n      return defaultProperties;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Optional<URI> getHomepage() {\n      return homepage;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Set<String> getLinkedServices() {\n      return linkedServices;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Set<String> getIso3166Codes() {\n      return iso3166Codes;\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/providers/internal/UpdateProviderMetadataFromProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.providers.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.Constants.PROPERTY_API;\nimport static org.jclouds.Constants.PROPERTY_API_VERSION;\nimport static org.jclouds.Constants.PROPERTY_BUILD_VERSION;\nimport static org.jclouds.Constants.PROPERTY_ENDPOINT;\nimport static org.jclouds.Constants.PROPERTY_ISO3166_CODES;\nimport static org.jclouds.Constants.PROPERTY_PROVIDER;\n\nimport java.util.Properties;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.providers.AnonymousProviderMetadata;\nimport org.jclouds.providers.ProviderMetadata;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Joiner;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Splitter;\n\n/**\n * Updates {@link ProviderMetadata} carrying over the input {@code Properties}, filtering out those which are typed fields in {@link ProviderMetadata} or {@link ApiMetadata}\n */\npublic class UpdateProviderMetadataFromProperties implements Function<Properties, ProviderMetadata> {\n   private final ApiMetadata apiMetadata;\n   private final Optional<ProviderMetadata> providerMetadata;\n\n   public UpdateProviderMetadataFromProperties(ProviderMetadata providerMetadata) {\n      this(checkNotNull(providerMetadata, \"providerMetadata\").getApiMetadata(), Optional.of(providerMetadata));\n   }\n\n   public UpdateProviderMetadataFromProperties(ApiMetadata apiMetadata) {\n      this(checkNotNull(apiMetadata, \"apiMetadata\"), Optional.<ProviderMetadata> absent());\n   }\n\n   public UpdateProviderMetadataFromProperties(ApiMetadata apiMetadata, Optional<ProviderMetadata> providerMetadata) {\n      this.apiMetadata = checkNotNull(apiMetadata, \"apiMetadata\");\n      this.providerMetadata = checkNotNull(providerMetadata, \"providerMetadata\");\n   }\n\n   @Override\n   public ProviderMetadata apply(Properties input) {\n      Properties mutable = new Properties();\n      mutable.putAll(input);\n      ApiMetadata apiMetadata = this.apiMetadata.toBuilder()\n                                    .name(getAndRemove(mutable, PROPERTY_API, this.apiMetadata.getName()))\n                                    .version(getAndRemove(mutable, PROPERTY_API_VERSION, this.apiMetadata.getVersion()))\n                                    .buildVersion(getAndRemove(mutable, PROPERTY_BUILD_VERSION, this.apiMetadata.getBuildVersion().orNull())).build();\n\n      String endpoint = getAndRemove(mutable, PROPERTY_ENDPOINT, providerMetadata.isPresent() ? providerMetadata.get()\n               .getEndpoint() : null);\n      \n      String providerId = getAndRemove(mutable, PROPERTY_PROVIDER, providerMetadata.isPresent() ? providerMetadata.get()\n               .getId() : apiMetadata.getId());\n      \n      String isoCodes = getAndRemove(mutable, PROPERTY_ISO3166_CODES, providerMetadata.isPresent() ? Joiner.on(',').join(providerMetadata.get()\n               .getIso3166Codes()) : \"\");\n      \n      ProviderMetadata providerMetadata = this.providerMetadata\n               .or(AnonymousProviderMetadata.forApiWithEndpoint(apiMetadata, checkNotNull(endpoint, PROPERTY_ENDPOINT)))\n               .toBuilder()\n               .apiMetadata(apiMetadata)\n               .id(providerId)\n               .iso3166Codes(Splitter.on(',').omitEmptyStrings().split(isoCodes))\n               .endpoint(endpoint).defaultProperties(mutable).build();\n\n      return providerMetadata;\n   }\n\n   private static String getAndRemove(Properties expanded, String key, String defaultVal) {\n      try {\n         return expanded.getProperty(key, defaultVal);\n      } finally {\n         expanded.remove(key);\n      }\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/proxy/ProxyConfig.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.proxy;\n\nimport java.net.Proxy.Type;\n\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.proxy.internal.GuiceProxyConfig;\n\nimport com.google.common.base.Optional;\nimport com.google.common.net.HostAndPort;\nimport com.google.inject.ImplementedBy;\n\n/**\n * parameters needed to configure {@link java.net.Proxy}. Check presence of\n * {@link #getProxyHost()} to decide if proxy support should even be attempted.\n */\n@ImplementedBy(GuiceProxyConfig.class)\npublic interface ProxyConfig {\n\n   /**\n    * @deprecated\n    * @see org.jclouds.Constants#PROPERTY_PROXY_SYSTEM\n    */\n   @Deprecated\n   boolean useSystem();\n\n   /**\n    * @see org.jclouds.Constants#PROPERTY_PROXY_FROM_JVM\n    */\n   boolean isJvmProxyEnabled();\n\n   /**\n    * @see org.jclouds.Constants#PROPERTY_PROXY_TYPE\n    */\n   Type getType();\n\n   /**\n    * Returns the host and port of the proxy configured here, if there is one\n    *\n    * @see org.jclouds.Constants#PROPERTY_PROXY_HOST\n    * @see org.jclouds.Constants#PROPERTY_PROXY_PORT\n    */\n   Optional<HostAndPort> getProxy();\n\n   /**\n    * @see org.jclouds.Constants#PROPERTY_PROXY_USER\n    * @see org.jclouds.Constants#PROPERTY_PROXY_PASSWORD\n    */\n   Optional<Credentials> getCredentials();\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/proxy/ProxyForURI.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.proxy;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.getLast;\nimport static org.jclouds.Constants.PROPERTY_PROXY_FOR_SOCKETS;\n\nimport java.net.Authenticator;\nimport java.net.InetSocketAddress;\nimport java.net.PasswordAuthentication;\nimport java.net.Proxy;\nimport java.net.ProxySelector;\nimport java.net.SocketAddress;\nimport java.net.URI;\n\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.domain.Credentials;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.inject.Inject;\n\n@Singleton\npublic class ProxyForURI implements Function<URI, Proxy> {\n   private final ProxyConfig config;\n\n   @Inject(optional = true)\n   @Named(PROPERTY_PROXY_FOR_SOCKETS)\n   private boolean useProxyForSockets = true;\n\n   @VisibleForTesting\n   @Inject\n   ProxyForURI(ProxyConfig config) {\n      this.config = checkNotNull(config, \"config\");\n   }\n\n   /**\n    * @param endpoint\n    *           <ul>\n    *           <li>http URI for http connections</li>\n    *           <li>https URI for https connections</li>\n    *           <li>ftp URI for ftp connections</li>\n    *           <li>socket://host:port for tcp client sockets connections</li>\n    *           </ul>\n    */\n   @Override\n   public Proxy apply(URI endpoint) {\n      if (!useProxyForSockets && \"socket\".equals(endpoint.getScheme())) {\n         return Proxy.NO_PROXY;\n      }\n      if (config.getProxy().isPresent()) {\n         SocketAddress addr = new InetSocketAddress(config.getProxy().get().getHost(), config.getProxy().get()\n            .getPort());\n         Proxy proxy = new Proxy(config.getType(), addr);\n\n         final Optional<Credentials> creds = config.getCredentials();\n         if (creds.isPresent()) {\n            Authenticator authenticator = new Authenticator() {\n               public PasswordAuthentication getPasswordAuthentication() {\n                  return new PasswordAuthentication(creds.get().identity, creds.get().credential.toCharArray());\n               }\n            };\n            Authenticator.setDefault(authenticator);\n         }\n         return proxy;\n      }\n      if (config.isJvmProxyEnabled()) {\n         return getDefaultProxy(endpoint);\n      }\n      if (config.useSystem()) {\n         // see notes on the Constant which initialized the above for deprecation;\n         // in short the following applied after startup is documented to have no effect.\n         System.setProperty(\"java.net.useSystemProxies\", \"true\");\n         return getDefaultProxy(endpoint);\n      }\n      return Proxy.NO_PROXY;\n   }\n\n   private Proxy getDefaultProxy(URI endpoint) {\n      Iterable<Proxy> proxies = ProxySelector.getDefault().select(endpoint);\n      return getLast(proxies);\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/proxy/internal/GuiceProxyConfig.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.proxy.internal;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static org.jclouds.Constants.PROPERTY_PROXY_ENABLE_JVM_PROXY;\nimport static org.jclouds.Constants.PROPERTY_PROXY_HOST;\nimport static org.jclouds.Constants.PROPERTY_PROXY_PASSWORD;\nimport static org.jclouds.Constants.PROPERTY_PROXY_PORT;\nimport static org.jclouds.Constants.PROPERTY_PROXY_SYSTEM;\nimport static org.jclouds.Constants.PROPERTY_PROXY_TYPE;\nimport static org.jclouds.Constants.PROPERTY_PROXY_USER;\nimport static org.jclouds.Constants.PROPERTY_PROXY_ENABLE_SSL_PROXY;\n\nimport java.net.Proxy;\nimport java.net.Proxy.Type;\n\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.proxy.ProxyConfig;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Strings;\nimport com.google.common.net.HostAndPort;\nimport com.google.inject.Inject;\n\n/**\n * Configuration derived from Guice properties.\n */\n@Singleton\npublic class GuiceProxyConfig implements ProxyConfig {\n\n   @SuppressWarnings(\"deprecation\")\n   @Inject(optional = true)\n   @Named(PROPERTY_PROXY_SYSTEM)\n   @Deprecated\n   private boolean systemProxies = Boolean.parseBoolean(System.getProperty(\"java.net.useSystemProxies\", \"false\"));\n   @Inject(optional = true)\n   @Named(PROPERTY_PROXY_ENABLE_JVM_PROXY)\n   private boolean jvmProxyEnabled = true;\n   @Inject(optional = true)\n   @Named(PROPERTY_PROXY_HOST)\n   private String host;\n   @Inject(optional = true)\n   @Named(PROPERTY_PROXY_PORT)\n   private Integer port;\n   @Inject(optional = true)\n   @Named(PROPERTY_PROXY_USER)\n   private String user;\n   @Inject(optional = true)\n   @Named(PROPERTY_PROXY_PASSWORD)\n   private String password;\n   @Inject(optional = true)\n   @Named(PROPERTY_PROXY_TYPE)\n   private Proxy.Type type = Proxy.Type.HTTP;\n   @Inject(optional = true)\n   @Named(PROPERTY_PROXY_ENABLE_SSL_PROXY)\n   private Boolean sslProxyEnabled = false;\n\n   @Override\n   public Optional<HostAndPort> getProxy() {\n      if (Strings.isNullOrEmpty(host))\n         return Optional.absent();\n      Integer port = this.port;\n      if (port == null) {\n         switch (type) {\n         case HTTP:\n            port = 80;\n            break;\n         case SOCKS:\n            port = 1080;\n            break;\n         default:\n            throw new IllegalArgumentException(type + \" not supported\");\n         }\n      }\n      return Optional.of(HostAndPort.fromParts(host, port));\n   }\n\n   @Override\n   public Optional<Credentials> getCredentials() {\n      if (user == null)\n         return Optional.absent();\n      return Optional.of(new Credentials(user, checkNotEmpty(password, \"set property %s for user %s\",\n            PROPERTY_PROXY_PASSWORD, user)));\n   }\n\n   private static String checkNotEmpty(String nullableString, String message, Object... args) {\n      checkArgument(Strings.emptyToNull(nullableString) != null, message, args);\n      return nullableString;\n   }\n\n   @Override\n   public Type getType() {\n      return type;\n   }\n\n   @Override\n   public boolean useSystem() {\n      return systemProxies;\n   }\n\n   @Override\n   public boolean isJvmProxyEnabled() {\n      return jvmProxyEnabled;\n   }\n   \n   public boolean isSslProxyEnabled() {\n      return sslProxyEnabled;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"systemProxies\", systemProxies ? \"true\" : null)\n            .add(\"jvmProxyEnabled\", jvmProxyEnabled ? \"true\" : \"false\")\n            .add(\"proxyHostPort\", getProxy().orNull()).add(\"user\", user).add(\"type\", host != null ? type : null).toString();\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/reflect/FunctionalReflection.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.reflect;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Predicates.notNull;\nimport static com.google.common.base.Throwables.propagate;\nimport static com.google.common.collect.Iterables.all;\nimport static org.jclouds.reflect.Reflection2.method;\nimport static org.jclouds.reflect.Reflection2.typeToken;\nimport static org.jclouds.util.Throwables2.propagateIfPossible;\n\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Proxy;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Function;\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.reflect.Invokable;\nimport com.google.common.reflect.TypeToken;\n\n/**\n * Static utilities relating to functional Java reflection.\n * \n * @since 1.6\n */\n@Beta\npublic final class FunctionalReflection {\n   /**\n    * Returns a proxy instance that implements {@code enclosingType} by dispatching method invocations to\n    * {@code invocationFunction}. The class loader of {@code enclosingType} will be used to define the proxy class.\n    * <p>\n    * Usage example:\n    * \n    * <pre>\n    * httpAdapter = new Function&lt;Invocation, Result&gt;() {\n    *    public Result apply(Invocation in) {\n    *       try {\n    *          HttpRequest request = parseRequest(in);\n    *          HttpResponse response = invoke(request);\n    *          return Result.success(parseJson(response));\n    *       } catch (Exception e) {\n    *          return Result.failure(e);\n    *       }\n    *    }\n    * };\n    * \n    * client = FunctionalReflection.newProxy(Client.class, httpAdapter);\n    * </pre>\n    * \n    * @param invocationFunction\n    *           returns a result or a top-level exception, or result\n    * @throws IllegalArgumentException\n    *            if {@code enclosingType} does not specify the type of a Java interface\n    * @see com.google.common.reflect.AbstractInvocationHandler#invoke(Object, Method, Object[])\n    * @see com.google.common.reflect.Reflection#newProxy(Class, java.lang.reflect.InvocationHandler)\n    */\n   public static <T> T newProxy(TypeToken<T> enclosingType, Function<Invocation, Object> invocationFunction) {\n      checkNotNull(enclosingType, \"enclosingType\");\n      checkNotNull(invocationFunction, \"invocationFunction\");\n      return newProxy(enclosingType.getRawType(), new FunctionalInvocationHandler<T>(enclosingType, invocationFunction));\n   }\n\n   public static <T> T newProxy(Class<T> enclosingType, Function<Invocation, Object> invocationFunction) {\n      checkNotNull(invocationFunction, \"invocationFunction\");\n      return newProxy(enclosingType, new FunctionalInvocationHandler<T>(typeToken(enclosingType), invocationFunction));\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   private static <T> T newProxy(Class<? super T> enclosingType, FunctionalInvocationHandler<T> invocationHandler) {\n      checkNotNull(enclosingType, \"enclosingType\");\n      checkArgument(enclosingType.isInterface(), \"%s is not an interface\", enclosingType);\n      return (T) Proxy.newProxyInstance(enclosingType.getClassLoader(), new Class<?>[] { enclosingType },\n            invocationHandler);\n   }\n\n   private static final class FunctionalInvocationHandler<T> extends\n         com.google.common.reflect.AbstractInvocationHandler {\n      private final TypeToken<T> enclosingType;\n      private final Function<Invocation, Object> invocationFunction;\n\n      private FunctionalInvocationHandler(TypeToken<T> enclosingType, Function<Invocation, Object> invocationFunction) {\n         this.enclosingType = enclosingType;\n         this.invocationFunction = invocationFunction;\n      }\n\n      @Override\n      protected Object handleInvocation(Object proxy, Method invoked, Object[] argv) throws Throwable {\n         List<Object> args = Arrays.asList(argv);\n         if (all(args, notNull()))\n            args = ImmutableList.copyOf(args);\n         else\n            args = Collections.unmodifiableList(args);\n         Invokable<T, Object> invokable = method(enclosingType, invoked);\n         Invocation invocation = Invocation.create(invokable, args);\n         try {\n            return invocationFunction.apply(invocation);\n         } catch (RuntimeException e) {\n            propagateIfPossible(e, invocation.getInvokable().getExceptionTypes());\n            throw propagate(e);\n         }\n      }\n\n      @Override\n      public boolean equals(Object o) {\n         if (this == o)\n            return true;\n         if (o == null || getClass() != o.getClass())\n            return false;\n         FunctionalInvocationHandler<?> that = FunctionalInvocationHandler.class.cast(o);\n         return equal(this.enclosingType, that.enclosingType)\n               && equal(this.invocationFunction, that.invocationFunction);\n      }\n\n      @Override\n      public int hashCode() {\n         return Objects.hashCode(enclosingType, invocationFunction);\n      }\n\n      @Override\n      public String toString() {\n         return invocationFunction.toString();\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/reflect/Invocation.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.reflect;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.List;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.reflect.Invokable;\n\n/**\n * Context needed to call {@link com.google.common.reflect.Invokable#invoke(Object, Object...)}\n */\n@Beta\npublic final class Invocation {\n\n   /**\n    * @param args\n    *           as these represent parameters, can contain nulls\n    */\n   public static Invocation create(Invokable<?, ?> invokable, List<Object> args) {\n      return new Invocation(invokable, args);\n   }\n\n   /**\n    * invocation without arguments.\n    *\n    * @throws IllegalArgumentException\n    *            if in invokable requires arguments\n    */\n   public static Invocation create(Invokable<?, ?> invokable) {\n      checkArgument(\n            invokable.getParameters().isEmpty() || (invokable.getParameters().size() == 1 && invokable.isVarArgs()),\n            \"please specify arguments to %s\", invokable);\n      return create(invokable, ImmutableList.of());\n   }\n\n   private final Invokable<?, ?> invokable;\n   private final List<Object> args;\n\n   private Invocation(Invokable<?, ?> invokable, List<Object> args) {\n      this.invokable = checkNotNull(invokable, \"invokable\");\n      this.args = checkNotNull(args, \"args\");\n   }\n\n   /**\n    * what we can invoke\n    */\n   public Invokable<?, ?> getInvokable() {\n      return invokable;\n   }\n\n   /**\n    * arguments applied to {@link #getInvokable()} during {@link Invokable#invoke(Object, Object...)}\n    *\n    * @param args\n    *           as these represent parameters, can contain nulls\n    */\n   public List<Object> getArgs() {\n      return args;\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o)\n         return true;\n      if (o == null || getClass() != o.getClass())\n         return false;\n      Invocation that = Invocation.class.cast(o);\n      return equal(this.invokable, that.invokable) && equal(this.args, that.args);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(invokable, args);\n   }\n\n   @Override\n   public String toString() {\n      return String.format(\"%s%s\", invokable, args);\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/reflect/InvocationSuccess.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.reflect;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.base.Optional;\n\n/**\n * Holds the context of a successful call to {@link com.google.common.reflect.Invokable#invoke(Object, Object...)}\n */\n@Beta\npublic final class InvocationSuccess {\n   public static InvocationSuccess create(Invocation invocation, @Nullable Object result) {\n      return new InvocationSuccess(invocation, Optional.fromNullable(result));\n   }\n\n   private final Invocation invocation;\n   private final Optional<Object> result;\n\n   private InvocationSuccess(Invocation invocation, Optional<Object> result) {\n      this.invocation = checkNotNull(invocation, \"invocation\");\n      this.result = checkNotNull(result, \"result\");\n   }\n\n   /**\n    * what was invocation\n    */\n   public Invocation getInvocation() {\n      return invocation;\n   }\n\n   public Optional<Object> getResult() {\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o)\n         return true;\n      if (o == null || getClass() != o.getClass())\n         return false;\n      InvocationSuccess that = InvocationSuccess.class.cast(o);\n      return equal(this.invocation, that.invocation) && equal(this.result.orNull(), that.result.orNull());\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(invocation, result.orNull());\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(\"\").omitNullValues().add(\"invocation\", invocation).add(\"result\", result.orNull());\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/reflect/Reflection2.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.reflect;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Throwables.propagate;\nimport static com.google.common.collect.Iterables.tryFind;\n\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Modifier;\nimport java.lang.reflect.Type;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.concurrent.ExecutionException;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Function;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Lists;\nimport com.google.common.reflect.Invokable;\nimport com.google.common.reflect.Parameter;\nimport com.google.common.reflect.TypeToken;\nimport com.google.common.util.concurrent.UncheckedExecutionException;\n\n/**\n * Utilities that allow access to {@link Invokable}s with {@link Invokable#getOwnerType() owner types}.\n *\n * @since 1.6\n */\n@Beta\npublic class Reflection2 {\n\n   /**\n    * gets a {@link TypeToken} for the given type.\n    */\n   @SuppressWarnings(\"unchecked\")\n   public static <T> TypeToken<T> typeToken(Type in) {\n      return (TypeToken<T>) get(typeTokenForType, checkNotNull(in, \"class\"));\n   }\n\n   /**\n    * gets a {@link TypeToken} for the given class.\n    */\n   @SuppressWarnings(\"unchecked\")\n   public static <T> TypeToken<T> typeToken(Class<T> in) {\n      return (TypeToken<T>) get(typeTokenForClass, checkNotNull(in, \"class\"));\n   }\n\n   /**\n    * returns an {@link Invokable} object that reflects a constructor present in the {@link TypeToken} type.\n    *\n    * @param ownerType\n    *           corresponds to {@link Invokable#getOwnerType()}\n    * @param parameterTypes\n    *           corresponds to {@link Constructor#getParameterTypes()}\n    *\n    * @throws IllegalArgumentException\n    *            if the constructor doesn't exist or a security exception occurred\n    */\n   @SuppressWarnings(\"unchecked\")\n   public static <T> Invokable<T, T> constructor(Class<T> ownerType, Class<?>... parameterTypes) {\n      return (Invokable<T, T>) get(constructorForParams, new TypeTokenAndParameterTypes(typeToken(ownerType),\n            parameterTypes));\n   }\n\n   /**\n    * return all constructors or static factory methods present in the class as {@link Invokable}s.\n    *\n    * @param ownerType\n    *           corresponds to {@link Invokable#getOwnerType()}\n    */\n   @SuppressWarnings(\"unchecked\")\n   public static <T> Collection<Invokable<T, T>> constructors(TypeToken<T> ownerType) {\n      return Collection.class.cast(get(constructorsForTypeToken, ownerType));\n   }\n\n   /**\n    * returns an {@link Invokable} object that links the {@code method} to its owner.\n    *\n    * @param ownerType\n    *           corresponds to {@link Invokable#getOwnerType()}\n    * @param method\n    *           present in {@code ownerType}\n    */\n   @SuppressWarnings(\"unchecked\")\n   public static <T, R> Invokable<T, R> method(TypeToken<T> ownerType, Method method) {\n      return (Invokable<T, R>) method(ownerType.getRawType(), method.getName(), method.getParameterTypes());\n   }\n\n   /**\n    * returns an {@link Invokable} object that reflects a method present in the {@link TypeToken} type.\n    * If there are multiple methods of the same name and parameter list, returns the method in the nearest\n    * ancestor with the most specific return type (see {@link Class#getDeclaredMethod}).\n    *\n    * @param ownerType\n    *           corresponds to {@link Invokable#getOwnerType()}\n    * @param name\n    *           name of the method to be returned\n    * @param parameterTypes\n    *           corresponds to {@link Method#getParameterTypes()}\n    *\n    * @throws IllegalArgumentException\n    *            if the method doesn't exist or a security exception occurred\n    */\n   @SuppressWarnings(\"unchecked\")\n   public static <T, R> Invokable<T, R> method(Class<T> ownerType, String name, Class<?>... parameterTypes) {\n      return (Invokable<T, R>) get(methodForParams, new TypeTokenNameAndParameterTypes(typeToken(ownerType), name,\n            parameterTypes));\n   }\n\n   /**\n    * return all methods present in the class as {@link Invokable}s.\n    *\n    * @param ownerType\n    *           corresponds to {@link Invokable#getOwnerType()}\n    */\n   @SuppressWarnings(\"unchecked\")\n   public static <T> Collection<Invokable<T, Object>> methods(Class<T> ownerType) {\n      return Collection.class.cast(get(methodsForTypeToken, typeToken(ownerType)));\n   }\n\n   /**\n    * This gets all declared constructors or factory methods on abstract types, not just public ones, and makes them\n    * accessible.\n    */\n   private static LoadingCache<TypeToken<?>, Set<Invokable<?, ?>>> constructorsForTypeToken = CacheBuilder\n         .newBuilder().build(new CacheLoader<TypeToken<?>, Set<Invokable<?, ?>>>() {\n            public Set<Invokable<?, ?>> load(TypeToken<?> key) {\n               ImmutableSet.Builder<Invokable<?, ?>> builder = ImmutableSet.<Invokable<?, ?>> builder();\n               Class<?> raw = key.getRawType();\n               for (Constructor<?> ctor : raw.getDeclaredConstructors()) {\n                  // TODO replace isAccessible() with canAccess() when using Java >= 9\n                  if (!ctor.isAccessible() && !coreJavaClass(raw)) {\n                     // In JDK 11 up to 14, the only uses for `java.beans.ConstructorProperties` annotation\n                     // are in the `java.awt`, `java.beans` and `javax.swing` packages.\n                     // Since these constructors are public, there is no need to call `setAccessible()`\n                     ctor.setAccessible(true);\n                  }\n                  builder.add(key.constructor(ctor));\n               }\n               // Look for factory methods, if this is an abstract type.\n               if (Modifier.isAbstract(raw.getModifiers())) {\n                  for (Invokable<?, Object> method : methods(raw)){\n                     if (method.isStatic() && method.getReturnType().equals(key)) {\n                        // TODO replace isAccessible() with canAccess() when using Java >= 9\n                        if (!method.isAccessible() && !coreJavaClass(raw)) {\n                           method.setAccessible(true);\n                        }\n                        builder.add(method);\n                     }\n                  }\n               }\n               return builder.build();\n            }\n         });\n\n   protected static List<Class<?>> toClasses(ImmutableList<Parameter> params) {\n      return Lists.transform(params, new Function<Parameter, Class<?>>() {\n         public Class<?> apply(Parameter input) {\n            return input.getType().getRawType();\n         }\n      });\n   }\n\n   private static LoadingCache<Type, TypeToken<?>> typeTokenForType = CacheBuilder.newBuilder().build(\n         new CacheLoader<Type, TypeToken<?>>() {\n            public TypeToken<?> load(Type key) {\n               return TypeToken.of(key);\n            }\n         });\n\n   private static LoadingCache<Class<?>, TypeToken<?>> typeTokenForClass = CacheBuilder.newBuilder().build(\n         new CacheLoader<Class<?>, TypeToken<?>>() {\n            public TypeToken<?> load(Class<?> key) {\n               return TypeToken.of(key);\n            }\n         });\n\n   private static LoadingCache<TypeTokenAndParameterTypes, Invokable<?, ?>> constructorForParams = CacheBuilder\n         .newBuilder().build(new CacheLoader<TypeTokenAndParameterTypes, Invokable<?, ?>>() {\n            public Invokable<?, ?> load(final TypeTokenAndParameterTypes key) {\n               Set<Invokable<?, ?>> constructors = get(constructorsForTypeToken, key.type);\n               Optional<Invokable<?, ?>> constructor = tryFind(constructors, new Predicate<Invokable<?, ?>>() {\n                  public boolean apply(Invokable<?, ?> input) {\n                     return Objects.equal(toClasses(input.getParameters()), key.parameterTypes);\n                  }\n               });\n               if (constructor.isPresent())\n                  return constructor.get();\n               throw new IllegalArgumentException(\"no such constructor \" + key.toString() + \"in: \" + constructors);\n            }\n         });\n\n   private static final LoadingCache<Invokable<?, ?>, ImmutableList<Parameter>> invokableParamsCache =\n      CacheBuilder.newBuilder().maximumSize(100).build(new CacheLoader<Invokable<?, ?>, ImmutableList<Parameter>>() {\n            @Override\n            public ImmutableList<Parameter> load(Invokable<?, ?> invokable) {\n               return invokable.getParameters();\n            }\n         });\n\n   /**\n    * Returns the {@link Parameter}s associated with the given {@link Invokable}. This function is backed by a cache.\n    *\n    * @param invokable\n    *           The {@link Invokable} we want to get Parameters from\n    */\n   public static List<Parameter> getInvokableParameters(final Invokable<?, ?> invokable) {\n      return invokableParamsCache.getUnchecked(invokable);\n   }\n\n   private static class TypeTokenAndParameterTypes {\n\n      protected TypeToken<?> type;\n      protected List<Class<?>> parameterTypes;\n\n      public TypeTokenAndParameterTypes(TypeToken<?> type, Class<?>... parameterTypes) {\n         this.type = checkNotNull(type, \"type\");\n         this.parameterTypes = Arrays.asList(checkNotNull(parameterTypes, \"parameterTypes\"));\n      }\n\n      public int hashCode() {\n         return Objects.hashCode(type, parameterTypes);\n      }\n\n      public boolean equals(Object obj) {\n         if (this == obj)\n            return true;\n         if (obj == null || getClass() != obj.getClass())\n            return false;\n         TypeTokenAndParameterTypes that = TypeTokenAndParameterTypes.class.cast(obj);\n         return Objects.equal(this.type, that.type) && Objects.equal(this.parameterTypes, that.parameterTypes);\n      }\n\n      public String toString() {\n         return MoreObjects.toStringHelper(\"\").add(\"type\", type).add(\"parameterTypes\", parameterTypes).toString();\n      }\n   }\n\n   private static LoadingCache<TypeTokenNameAndParameterTypes, Invokable<?, ?>> methodForParams = CacheBuilder\n         .newBuilder().build(new CacheLoader<TypeTokenNameAndParameterTypes, Invokable<?, ?>>() {\n            public Invokable<?, ?> load(final TypeTokenNameAndParameterTypes key) {\n               Set<Invokable<?, ?>> methods = get(methodsForTypeToken, key.type);\n               /*\n                * There may be multiple instances, even on the most immediate ancestor,\n                * of a method with the required name and parameter set. This will occur\n                * if the method overrides one declared in a parent class with a less specific\n                * return type. These bridge methods inserted by the compiler will be marked\n                * as \"synthetic\".\n                */\n               Optional<Invokable<?, ?>> method = tryFind(methods, new Predicate<Invokable<?, ?>>() {\n                  public boolean apply(Invokable<?, ?> input) {\n                     // Invokable doesn't expose Method#isBridge\n                     return !input.isSynthetic() && Objects.equal(input.getName(), key.name)\n                           && Objects.equal(toClasses(input.getParameters()), key.parameterTypes);\n                  }\n               });\n               checkArgument(method.isPresent(), \"no such method %s in: %s\", key.toString(), methods);\n               return method.get();\n            }\n         });\n\n   private static class TypeTokenNameAndParameterTypes extends TypeTokenAndParameterTypes {\n\n      private String name;\n\n      public TypeTokenNameAndParameterTypes(TypeToken<?> type, String name, Class<?>... parameterTypes) {\n         super(type, parameterTypes);\n         this.name = checkNotNull(name, \"name\");\n      }\n\n      public int hashCode() {\n         return Objects.hashCode(super.hashCode(), name);\n      }\n\n      public boolean equals(Object obj) {\n         if (super.equals(obj)) {\n            TypeTokenNameAndParameterTypes that = TypeTokenNameAndParameterTypes.class.cast(obj);\n            return name.equals(that.name);\n         }\n         return false;\n      }\n\n      public String toString() {\n         return MoreObjects.toStringHelper(\"\").add(\"type\", type).add(\"name\", name).add(\"parameterTypes\", parameterTypes)\n               .toString();\n      }\n   }\n\n   /**\n    * this gets all declared methods, not just public ones. makes them accessible. Does not include Object methods.\n    * Invokables for a type are ordered so all invokables on a subtype are always listed before invokables on a\n    * supertype (see {@link TypeToken#getTypes()}).\n    */\n   private static LoadingCache<TypeToken<?>, Set<Invokable<?, ?>>> methodsForTypeToken = CacheBuilder\n         .newBuilder().build(new CacheLoader<TypeToken<?>, Set<Invokable<?, ?>>>() {\n            public Set<Invokable<?, ?>> load(TypeToken<?> key) {\n               ImmutableSet.Builder<Invokable<?, ?>> builder = ImmutableSet.<Invokable<?, ?>> builder();\n               for (TypeToken<?> token : key.getTypes()) {\n                  Class<?> raw = token.getRawType();\n                  if (raw == Object.class)\n                     continue;\n                  for (Method method : raw.getDeclaredMethods()) {\n                     builder.add(key.method(method));\n                  }\n               }\n               return builder.build();\n            }\n         });\n\n   private static boolean coreJavaClass(Class<?> clazz) {\n      // treat null packages (e.g. for proxy objects) as \"non-core\"\n      Package clazzPackage = clazz.getPackage();\n      if (clazzPackage == null) {\n         return false;\n      }\n      String packageName = clazzPackage.getName();\n      return packageName.startsWith(\"com.sun.\") || packageName.startsWith(\"java.\")\n              || packageName.startsWith(\"javax.\") || packageName.startsWith(\"sun.\");\n   }\n\n   /**\n    * ensures that exceptions are not doubly-wrapped\n    */\n   private static <K, V> V get(LoadingCache<K, V> cache, K key) {\n      try {\n         return cache.get(key);\n      } catch (UncheckedExecutionException e) {\n         throw propagate(e.getCause());\n      } catch (ExecutionException e) {\n         throw propagate(e.getCause());\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/reflect/Types2.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.reflect;\n\nimport static com.google.common.base.Preconditions.checkState;\n\nimport java.lang.reflect.TypeVariable;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.reflect.TypeToken;\n\n/**\n * @since 1.7\n */\n@Beta\npublic class Types2 {\n\n   /**\n    * Helpful when you are capturing the type inside a constructor.\n    * \n    * @throws IllegalStateException\n    *            if the type is an instanceof {@link TypeVariable}\n    */\n   public static <T> TypeToken<T> checkBound(TypeToken<T> type) throws IllegalStateException {\n      checkState(!(type.getType() instanceof TypeVariable<?>),\n            \"unbound type variable: %s, use ctor that explicitly assigns this\", type);\n      return type;\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/AnonymousHttpApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest;\n\nimport java.net.URI;\n\nimport org.jclouds.rest.internal.BaseHttpApiMetadata;\n\nimport com.google.common.annotations.Beta;\n\n/**\n * Useful in creating arbitrary http apis.\n */\n@Beta\npublic class AnonymousHttpApiMetadata<A> extends BaseHttpApiMetadata<A> {\n\n   public static <A> AnonymousHttpApiMetadata<A> forApi(Class<A> httpApi) {\n      return new Builder<A>(httpApi).build();\n   }\n\n   @Override\n   public Builder<A> toBuilder() {\n      return new Builder<A>(getApi()).fromApiMetadata(this);\n   }\n\n   private AnonymousHttpApiMetadata(Builder<A> builder) {\n      super(builder);\n   }\n\n   private static final class Builder<A> extends BaseHttpApiMetadata.Builder<A, Builder<A>> {\n\n      private Builder(Class<A> api) {\n         super(api);\n         id(api.getSimpleName())\n         .identityName(\"unused\")\n         .defaultIdentity(\"foo\")\n         .version(\"1\")\n         .documentation(URI.create(\"http://jclouds.org/documentation\"));\n      }\n\n      @Override\n      public AnonymousHttpApiMetadata<A> build() {\n         return new AnonymousHttpApiMetadata<A>(this);\n      }\n\n      @Override\n      protected Builder<A> self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/ApiContext.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest;\n\nimport org.jclouds.Context;\nimport org.jclouds.rest.internal.ApiContextImpl;\n\nimport com.google.inject.ImplementedBy;\n\n/**\n * Represents an authenticated context to the cloud.\n * \n * <h2>Note</h2> Please issue {@link #close()} when you are finished with this context in order to\n * release resources.\n */\n@ImplementedBy(ApiContextImpl.class)\npublic interface ApiContext<A> extends Context {\n\n\n   /**\n    * low-level api to the cloud. Threadsafe implementations will return a singleton.\n    * \n    * @return a connection to the cloud where all methods block\n    */\n   A getApi();\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/AuthorizationException.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest;\n\n\n/**\n * Thrown when there is an authorization error.\n */\npublic class AuthorizationException extends RuntimeException {\n\n   private static final long serialVersionUID = 1L;\n\n   public AuthorizationException() {\n      super();\n   }\n\n   public AuthorizationException(String message, Throwable cause) {\n      super(message, cause);\n   }\n\n   public AuthorizationException(Throwable cause) {\n      super(cause);\n   }\n\n   public AuthorizationException(String message) {\n      super(message);\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/Binder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest;\n\nimport org.jclouds.http.HttpRequest;\n\n/**\n * Adds an payload to a request.\n */\npublic interface Binder {\n   <R extends HttpRequest> R bindToRequest(R request, Object input);\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/ConfiguresCredentialStore.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest;\n\nimport static java.lang.annotation.ElementType.TYPE;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\nimport com.google.common.annotations.Beta;\n\n/**\n * designates the module configures a {@code Map<String, ? extends Credentials>}\n */\n@Beta\n@Retention(RUNTIME)\n@Target(TYPE)\npublic @interface ConfiguresCredentialStore {\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/ConfiguresHttpApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest;\n\nimport static java.lang.annotation.ElementType.TYPE;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\n/**\n * designates the module configures a top-level api which is annotated with http methods.\n */\n@Retention(RUNTIME)\n@Target(TYPE)\npublic @interface ConfiguresHttpApi {\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/HttpApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest;\n\nimport org.jclouds.apis.ApiMetadata;\n\nimport com.google.common.annotations.Beta;\n\n/**\n * \n * @since 1.6\n * @see ConfiguresHttpApi\n */\n@Beta\npublic interface HttpApiMetadata<A> extends ApiMetadata {\n\n   public interface Builder<A, T extends Builder<A, T>> extends ApiMetadata.Builder<T> {\n\n      /**\n       * @see ApiMetadata#getApi()\n       */\n      T api(Class<A> api);\n   }\n\n   /**\n    * \n    * @return the type of the java api which has http annotations on its methods.\n    */\n   Class<A> getApi();\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/HttpClient.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest;\n\nimport java.io.Closeable;\nimport java.io.InputStream;\nimport java.net.URI;\n\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.HEAD;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\n\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseETagHeader;\nimport org.jclouds.io.Payload;\nimport org.jclouds.rest.annotations.EndpointParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.ResponseParser;\n\n/**\n * Simple client\n */\npublic interface HttpClient extends Closeable {\n   /**\n    * @return eTag\n    */\n   @PUT\n   @ResponseParser(ParseETagHeader.class)\n   String put(@EndpointParam URI location, Payload payload);\n\n   /**\n    * @return eTag\n    */\n   @POST\n   @ResponseParser(ParseETagHeader.class)\n   String post(@EndpointParam URI location, Payload payload);\n\n   /**\n    * @see HttpClient#exists\n    */\n   @HEAD\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean exists(@EndpointParam URI location);\n\n   /**\n    * @return null if the resource didn't exist.\n    */\n   @GET\n   @Fallback(NullOnNotFoundOr404.class)\n   InputStream get(@EndpointParam URI location);\n\n   /**\n    * \n    * @param request\n    * @return response, but make sure you consume its content.\n    */\n   HttpResponse invoke(HttpRequest request);\n\n   /**\n    * @return false if the resource didn't exist.\n    */\n   @DELETE\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean delete(@EndpointParam URI location);\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/InputParamValidator.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.List;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.predicates.Validator;\nimport org.jclouds.reflect.Invocation;\nimport org.jclouds.rest.annotations.ParamValidators;\n\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Lists;\nimport com.google.common.reflect.Parameter;\nimport com.google.inject.Injector;\n\n/**\n * Validates method parameters.\n * \n * Checks the {@link ParamValidators} annotation for validators. There can be method-level validators that apply to all\n * parameters, and parameter-level validators. When validation on at least one parameter doesn't pass, throws\n * {@link IllegalStateException}.\n */\npublic class InputParamValidator {\n\n   private final Injector injector;\n\n   @Inject\n   public InputParamValidator(Injector injector) {\n      this.injector = injector;\n   }\n\n   public InputParamValidator() {\n      injector = null;\n   }\n\n   /**\n    * Validates that method parameters are correct, according to {@link ParamValidators}.\n    * \n    * @param method\n    *           method with optionally set {@link ParamValidators}\n    * @param args\n    *           method arguments with optionally set {@link ParamValidators}\n    * @see ParamValidators\n    * @see Validator\n    * \n    * @throws IllegalStateException\n    *            if validation failed\n    */\n   public void validateMethodParametersOrThrow(Invocation invocation, List<Parameter> parameters) {\n      try {\n         performMethodValidation(checkNotNull(invocation, \"invocation\"));\n         performParameterValidation(invocation, checkNotNull(parameters, \"parameters\"));\n      } catch (IllegalArgumentException e) {\n         throw new IllegalArgumentException(String.format(\"Validation on '%s' didn't pass:%n Reason: %s.\", parameters,\n               e.getMessage()), e);\n      }\n   }\n\n   /**\n    * Returns if all the method parameters passed all of the method-level validators or throws an\n    * {@link IllegalArgumentException}.\n    * \n    * @param method\n    *           method with optionally set {@link ParamValidators}. This can not be null.\n    * @param args\n    *           method's parameters\n    */\n   private void performMethodValidation(Invocation invocation) {\n      ParamValidators paramValidatorsAnnotation = invocation.getInvokable().getAnnotation(ParamValidators.class);\n      if (paramValidatorsAnnotation == null)\n         return; // by contract\n\n      List<Validator<?>> methodValidators = getValidatorsFromAnnotation(paramValidatorsAnnotation);\n\n      runPredicatesAgainstArgs(methodValidators, invocation.getArgs());\n   }\n\n   /**\n    * Returns if all the method parameters passed all of their corresponding validators or throws an\n    * {@link IllegalArgumentException}.\n    * \n    * @param parameters\n    *           annotations for method's arguments\n    * @param args\n    *           arguments that correspond to the array of annotations\n    */\n   private void performParameterValidation(Invocation invocation, List<Parameter> parameters) {\n      for (Parameter param : parameters) {\n         ParamValidators annotation = param.getAnnotation(ParamValidators.class);\n         if (annotation == null)\n            continue;\n         List<Validator<?>> parameterValidators = getValidatorsFromAnnotation(annotation);\n         // TODO position guava issue 1243\n         runPredicatesAgainstArg(parameterValidators, invocation.getArgs().get(param.hashCode()));\n      }\n   }\n\n   private List<Validator<?>> getValidatorsFromAnnotation(ParamValidators paramValidatorsAnnotation) {\n      List<Validator<?>> validators = Lists.newArrayList();\n      for (Class<? extends Validator<?>> validator : paramValidatorsAnnotation.value()) {\n         validators.add(checkNotNull(injector.getInstance(validator)));\n      }\n      return validators;\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   private void runPredicatesAgainstArg(List<Validator<?>> predicates, Object arg) {\n      for (@SuppressWarnings(\"rawtypes\")\n      Validator validator : predicates) {\n         validator.apply(arg);\n      }\n   }\n\n   @SuppressWarnings({\"CheckReturnValue\", \"unchecked\"})\n   private void runPredicatesAgainstArgs(List<Validator<?>> predicates, List<Object> args) {\n      for (@SuppressWarnings(\"rawtypes\")\n      Validator validator : predicates) {\n         Iterables.all(args, validator);\n      }\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/InsufficientResourcesException.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest;\n\n/**\n * Thrown when there is a quota or otherwise limit preventing the operation from occurring.\n */\npublic class InsufficientResourcesException extends RuntimeException {\n\n   private static final long serialVersionUID = 1L;\n\n   public InsufficientResourcesException() {\n      super();\n   }\n\n   public InsufficientResourcesException(String arg0) {\n      super(arg0);\n   }\n\n   public InsufficientResourcesException(String arg0, Throwable arg1) {\n      super(arg0, arg1);\n   }\n\n   public InsufficientResourcesException(Throwable arg0) {\n      super(arg0);\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/InvocationContext.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest;\n\nimport org.jclouds.http.HttpRequest;\n\n/**\n * Passes generated Http request into this object;\n * \n * @see PathParam\n */\npublic interface InvocationContext<I extends InvocationContext<I>> {\n   I setContext(HttpRequest request);\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/MapBinder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest;\n\nimport java.util.Map;\n\nimport org.jclouds.http.HttpRequest;\n\n/**\n * Builds the payload of a Post request.\n */\npublic interface MapBinder extends Binder {\n\n   /**\n    * creates and binds the POST payload to the request using parameters specified.\n    * \n    * @see org.jclouds.rest.annotations.PayloadParam\n    */\n   <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams);\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/RateLimitExceededException.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest;\n\n/**\n * Thrown when a request fails because the rate limit has been exceeded.\n */\npublic class RateLimitExceededException extends RuntimeException {\n\n   private static final long serialVersionUID = 1L;\n\n   public RateLimitExceededException() {\n      super();\n   }\n\n   public RateLimitExceededException(String message, Throwable cause) {\n      super(message, cause);\n   }\n\n   public RateLimitExceededException(String message) {\n      super(message);\n   }\n\n   public RateLimitExceededException(Throwable cause) {\n      super(cause);\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/RequestSigner.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest;\n\nimport org.jclouds.http.HttpRequest;\n\n/**\n * @deprecated This is an internal interface historically used to debug signature logic. It currently is a broken\n * abstraction as AWS Signature v4 requires multiple parameters to sign a request.\n */\n@Deprecated\npublic interface RequestSigner {\n\n   String createStringToSign(HttpRequest input);\n\n   String sign(String toSign);\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/ResourceAlreadyExistsException.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.rest;\n\n/**\n * Thrown when creating a resource that already exists.\n */\npublic class ResourceAlreadyExistsException extends RuntimeException {\n   public ResourceAlreadyExistsException() {\n      this(null, null);\n   }\n\n   public ResourceAlreadyExistsException(String message) {\n      this(message, null);\n   }\n\n   public ResourceAlreadyExistsException(Throwable cause) {\n      this(null, cause);\n   }\n\n   public ResourceAlreadyExistsException(String message, Throwable cause) {\n      super(message, cause);\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/ResourceNotFoundException.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest;\n\n/**\n * Thrown when a resource cannot be located.\n */\npublic class ResourceNotFoundException extends RuntimeException {\n\n   private static final long serialVersionUID = 1L;\n\n   public ResourceNotFoundException() {\n\t\tsuper();\n\t}\n\n\tpublic ResourceNotFoundException(String arg0, Throwable arg1) {\n\t\tsuper(arg0, arg1);\n\t}\n\n\tpublic ResourceNotFoundException(String arg0) {\n\t\tsuper(arg0);\n\t}\n\n\tpublic ResourceNotFoundException(Throwable arg0) {\n\t\tsuper(arg0);\n\t}\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/RetryAfterException.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest;\n\n/**\n * This exception is raised when an http endpoint returns with a response\n * telling the caller to make the same request after a certain period of time.\n * \n * Typically, this is returned with a {@code 503} status code, as specified in\n * the {@link HttpHeaders#RETRY_AFTER} header.\n */\npublic class RetryAfterException extends RuntimeException {\n\n   private static final long serialVersionUID = 1L;\n\n   /**\n    * Delta in seconds\n    */\n   private final int seconds;\n\n   /**\n    * Construct an exception instance to happen at a time in the future\n    * \n    * @param message\n    *           message\n    * @param seconds\n    *           retry after delta. Negative values are converted to zero\n    */\n   public RetryAfterException(String message, int seconds) {\n      super(message);\n      this.seconds = Math.max(seconds, 0);\n   }\n\n   /**\n    * Construct an exception instance to happen at a time in the future\n    * \n    * @param cause\n    *           cause\n    * @param seconds\n    *           retry after delta. Negative values are converted to zero\n    */\n   public RetryAfterException(Throwable cause, int seconds) {\n      super(defaultMessage(seconds = Math.max(seconds, 0)), cause);\n      this.seconds = seconds;\n   }\n   \n   private static String defaultMessage(int seconds) {\n      switch (seconds) {\n      case 0:\n         return \"retry now\";\n      case 1:\n         return \"retry in 1 second\";\n      default:\n         return String.format(\"retry in %d seconds\", seconds);\n      }\n   }\n\n   /**\n    * Construct an exception instance to happen at a time in the future\n    * \n    * @param message\n    *           message\n    * @param cause\n    *           cause\n    * @param seconds\n    *           retry after delta. Negative values are converted to zero\n    */\n   public RetryAfterException(String message, Throwable cause, int seconds) {\n      super(message, cause);\n      this.seconds = Math.max(seconds, 0);\n   }\n\n   /**\n    * Get the value of the retry time\n    * \n    * @return the retry time, in seconds. This is always zero or positive.\n    */\n   public int getSeconds() {\n      return seconds;\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/Utils.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest;\n\nimport java.util.Map;\n\nimport org.jclouds.crypto.Crypto;\nimport org.jclouds.date.DateService;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.json.Json;\nimport org.jclouds.logging.Logger.LoggerFactory;\nimport org.jclouds.rest.internal.UtilsImpl;\nimport org.jclouds.xml.XMLParser;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.eventbus.EventBus;\nimport com.google.inject.ImplementedBy;\nimport com.google.inject.Injector;\n\n@ImplementedBy(UtilsImpl.class)\npublic interface Utils {\n\n   /**\n    * retrieves a list of credentials for resources created within this context, keyed on {@code id}\n    * of the resource with a namespace prefix (ex. {@code node#}. We are testing this approach for\n    * resources such as compute nodes, where you could access this externally.\n    * <p/>\n    * <h4>accessing credentials for a node</h4>\n    * <p/>\n    * the key is in the form {@code node#id}.\n    * <ul>\n    * <li>if the node id is {@code 8}, then the key will be {@code node#8}</li>\n    * <li>if the node id is {@code us-east-1/i-asdfdas}, then the key will be {@code\n    * node#us-east-1/i-asdfdas}</li>\n    * <li>if the node id is {@code http://cloud/instances/1}, then the key will be {@code\n    * node#http://cloud/instances/1}</li>\n    * </ul>\n    */\n   @Beta\n   Map<String, Credentials> credentialStore();\n\n   Json json();\n\n   HttpClient http();\n\n   Crypto crypto();\n\n   DateService date();\n\n   EventBus eventBus();\n\n   LoggerFactory loggerFactory();\n\n   @Beta\n   Injector injector();\n\n   XMLParser xml();\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/annotations/Api.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.annotations;\n\nimport static java.lang.annotation.ElementType.ANNOTATION_TYPE;\nimport static java.lang.annotation.ElementType.FIELD;\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.ElementType.PARAMETER;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\nimport jakarta.inject.Qualifier;\n\n/**\n * Designates that this Resource qualifies an object to an api.\n */\n@Target( { ANNOTATION_TYPE, FIELD, METHOD, PARAMETER })\n@Retention(RUNTIME)\n@Qualifier\npublic @interface Api {\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/annotations/ApiVersion.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.annotations;\n\nimport static java.lang.annotation.ElementType.ANNOTATION_TYPE;\nimport static java.lang.annotation.ElementType.FIELD;\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.ElementType.PARAMETER;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\nimport jakarta.inject.Qualifier;\n\n/**\n * Designates that this Resource qualifies an object to an api version.\n * \n * @see Constants#PROPERTY_API_VERSION\n */\n@Target( { ANNOTATION_TYPE, FIELD, METHOD, PARAMETER })\n@Retention(RUNTIME)\n@Qualifier\npublic @interface ApiVersion {\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/annotations/ApiVersionOverride.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.annotations;\n\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\nimport jakarta.inject.Qualifier;\n\n\n/**\n * @Deprecated The intention is to use @SinceApiVersion for this purpose, but that would affect\n * a number of APIs, and we would want to have good test coverage before merging that change\n * (in {@link FormSignerUtils#getAnnotatedApiVersion}). However, there is some issue with certain tests at\n * present that means we cannot successfully test all APIs that make use of @SinceApiVersion in order\n * to assure ourselves that FormSignerUtils will not introduce some problem. See\n * <a href=\"https://github.com/jclouds/jclouds/pull/1102#issuecomment-302682049\">\n *    comments on github</a> for details\n * This annotation is introduced as a temporary measure in order to decouple the functionality of\n * {@link FormSignerUtils#getAnnotatedApiVersion} from @SinceApiVersion and the tests in question.\n * It can be removed and replaced by @SinceApiVersion when those tests are fixed.\n *\n * Designates that a method overrides the {@link ApiVersion} on the class with a specific value.\n *\n * @see ApiVersion\n */\n@Deprecated\n@Target({ METHOD })\n@Retention(RUNTIME)\n@Qualifier\npublic @interface ApiVersionOverride {\n\n   /**\n    * Value to override the default {@link ApiVersion}.\n    *\n    */\n   String value();\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/annotations/BinderParam.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.annotations;\n\nimport static java.lang.annotation.ElementType.PARAMETER;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\nimport org.jclouds.rest.Binder;\n\n/**\n * Designates that this parameter will modify the request, possibly including adding an payload to\n * it.\n */\n@Target(PARAMETER)\n@Retention(RUNTIME)\npublic @interface BinderParam {\n\n   /**\n    * how to persist this payload.\n    */\n   Class<? extends Binder> value();\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/annotations/BuildVersion.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.annotations;\n\nimport static java.lang.annotation.ElementType.ANNOTATION_TYPE;\nimport static java.lang.annotation.ElementType.FIELD;\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.ElementType.PARAMETER;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\nimport jakarta.inject.Qualifier;\n\n/**\n * Designates that this Resource qualifies an object to an build version.\n * \n * @see Constants#PROPERTY_BUILD_VERSION\n */\n@Target( { ANNOTATION_TYPE, FIELD, METHOD,  PARAMETER })\n@Retention(RUNTIME)\n@Qualifier\npublic @interface BuildVersion {\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/annotations/Delegate.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.annotations;\n\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\n/**\n * Designates that this method returns a rest client\n */\n@Target(METHOD)\n@Retention(RUNTIME)\npublic @interface Delegate {\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/annotations/Endpoint.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.annotations;\n\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.ElementType.TYPE;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Annotation;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\n/**\n * Designates that this Resource expects virtual host style requests\n */\n@Target( { TYPE, METHOD })\n@Retention(RUNTIME)\npublic @interface Endpoint {\n   Class<? extends Annotation> value();\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/annotations/EndpointParam.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.annotations;\n\nimport static java.lang.annotation.ElementType.PARAMETER;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\nimport java.net.URI;\n\nimport jakarta.inject.Singleton;\n\nimport com.google.common.base.Function;\n\n/**\n * Extracts the endpoint of a parameter from an object.\n * \n * @see PathParam\n */\n@Target(PARAMETER)\n@Retention(RUNTIME)\npublic @interface EndpointParam {\n   @Singleton\n   public static class ReturnSame implements Function<Object, URI> {\n\n      @Override\n      public URI apply(Object from) {\n         // TODO check arg;\n         return (URI) from;\n      }\n\n   }\n\n   Class<? extends Function<Object, URI>> parser() default ReturnSame.class;\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/annotations/Fallback.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.annotations;\n\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\n/**\n * Annotates the appropriate {@link org.jclouds.Fallback} which propagates\n * the exception or returns a valid fallback value.\n * \n * @since 1.6\n */\n@Target(METHOD)\n@Retention(RUNTIME)\npublic @interface Fallback {\n   Class<? extends org.jclouds.Fallback<?>> value();\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/annotations/FormParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.annotations;\n\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.ElementType.TYPE;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\n/**\n * Designates that a url encoded form will be added to the request.\n * \n * @see FormParam\n */\n@Target( { TYPE, METHOD })\n@Retention(RUNTIME)\npublic @interface FormParams {\n\n   String NULL = \"FORM_NULL\";\n\n   String[] keys();\n\n   String[] values() default NULL;\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/annotations/Headers.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.annotations;\n\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.ElementType.TYPE;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\n/**\n * Designates that a header will be added to the request. This header will contain the specified\n * {@code value}, expanding any variables annotated with {@code PathParam}.\n * \n * @see PathParam\n */\n@Target( { TYPE, METHOD })\n@Retention(RUNTIME)\npublic @interface Headers {\n\n   /**\n    * @see HttpHeaders\n    */\n   String[] keys();\n\n/**\n    * can be defined literally, or with enclosed variables (ex. <code>{variable}</code>)\n    * <p/>\n    * The inputs to these variables are taken from method parameters annotated with {@code\n    * @PathParam}.\n    * \n    * @see javax.ws.rs.PathParam\n    * \n    */\n   String[] values();\n\n   /**\n    * Indicates whether a header should be URL encoded. Optional for backwards compatibility.\n    * The default behavior is that the header is not URL encoded.\n    */\n   boolean[] urlEncode() default {};\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/annotations/JAXBResponseParser.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.annotations;\n\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\nimport javax.lang.model.type.NullType;\n\n\n/**\n * Shows the transformer type used to parse XML with the\n * {@link ParseXMLWithJAXB} parser in a HttpResponse.\n */\n@Target(METHOD)\n@Retention(RUNTIME)\npublic @interface JAXBResponseParser {\n\n   /**\n    * If present, this is the class that will be used to unmarshal the XML\n    * document. If omitted, the return type of the annotated method will be\n    * used.\n    */\n   Class<?> value() default NullType.class;\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/annotations/MapBinder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.annotations;\n\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\n/**\n * Designates that this parameter will hold the payload for a PUT or POST command.\n */\n@Target(METHOD)\n@Retention(RUNTIME)\npublic @interface MapBinder {\n\n   /**\n    * How to bind {@link PayloadParam} values, if there is no {@link MapBinder} in the method\n    * definition\n    */\n   Class<? extends org.jclouds.rest.MapBinder> value();\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/annotations/OnlyElement.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.annotations;\n\nimport static java.lang.annotation.ElementType.ANNOTATION_TYPE;\nimport static java.lang.annotation.ElementType.FIELD;\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.ElementType.PARAMETER;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\nimport jakarta.inject.Qualifier;\n\n/**\n * Extracts the only element of a collection or null\n * \n * @see SelectJson\n */\n@Target( { ANNOTATION_TYPE, METHOD, FIELD, PARAMETER })\n@Retention(RUNTIME)\n@Qualifier\npublic @interface OnlyElement {\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/annotations/OverrideRequestFilters.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.annotations;\n\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\n/**\n * Do not accept filters that were passed from the type.\n */\n@Target( { METHOD })\n@Retention(RUNTIME)\npublic @interface OverrideRequestFilters {\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/annotations/PATCH.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.annotations;\n\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\nimport jakarta.ws.rs.HttpMethod;\n\n/**\n * Implements the PATCH HTTP request type\n */\n@Target({ ElementType.METHOD })\n@Retention(RetentionPolicy.RUNTIME)\n@HttpMethod(\"PATCH\")\npublic @interface PATCH {\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/annotations/ParamParser.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.annotations;\n\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.ElementType.PARAMETER;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\nimport com.google.common.base.Function;\n\n/**\n * Extracts the value of a parameter from an object. If placed on a method, the function will be\n * presented with a Object [] from the method args used to derive the value;\n * \n * @see PathParam\n */\n@Target( { METHOD, PARAMETER })\n@Retention(RUNTIME)\npublic @interface ParamParser {\n   Class<? extends Function<Object, String>> value();\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/annotations/ParamValidators.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.annotations;\n\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.ElementType.PARAMETER;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\nimport org.jclouds.predicates.Validator;\n\n/**\n * Marks the validation for method/parameter value(s).\n * \n * @see org.jclouds.rest.internal.RestAnnotationProcessor\n * @see com.google.common.base.Predicate\n */\n@Target( { METHOD, PARAMETER })\n@Retention(RUNTIME)\npublic @interface ParamValidators {\n   Class<? extends Validator<?>>[] value();\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/annotations/PartParam.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.annotations;\n\nimport static java.lang.annotation.ElementType.PARAMETER;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\n/**\n * Designates that this parameter will be bound to a multipart form.\n */\n@Target(PARAMETER)\n@Retention(RUNTIME)\npublic @interface PartParam {\n   // hacks as nulls are not allowed as default values\n   String NO_FILENAME = \"---NO_FILENAME---\";\n   String NO_CONTENT_TYPE = \"---NO_CONTENT_TYPE---\";\n\n   String name();\n\n   String contentType() default NO_CONTENT_TYPE;\n   \n   String filename() default NO_FILENAME;\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/annotations/Payload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.annotations;\n\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\n/**\n * Designates that this parameter will hold the payload for a PUT or POST command.\n */\n@Target(METHOD)\n@Retention(RUNTIME)\npublic @interface Payload {\n\n   /**\n    * Note that if you'd like curly braces literally in the payload, urlencode them first.\n    * \n    * @see Path#value()\n    * @see PayloadParam\n    */\n   String value();\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/annotations/PayloadParam.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.annotations;\n\nimport static java.lang.annotation.ElementType.PARAMETER;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\n/**\n * Designates that this parameter will hold the payload for a PUT or POST command.\n */\n@Target(PARAMETER)\n@Retention(RUNTIME)\npublic @interface PayloadParam {\n\n   /**\n    * The key used in a map passed to the {@link MapBinder} or {@link Payload} associated with the\n    * request.\n    */\n   String value();\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/annotations/PayloadParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.annotations;\n\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.ElementType.TYPE;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\n/**\n * Designates that default parameters will be added a map that builds the request entity.\n * \n * @see QueryParam\n * @see Payload\n * @see MapBinder\n */\n@Target( { TYPE, METHOD })\n@Retention(RUNTIME)\npublic @interface PayloadParams {\n\n   String NULL = \"MAP_PAYLOAD_NULL\";\n\n   String[] keys();\n\n   String[] values() default NULL;\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/annotations/QueryParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.annotations;\n\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.ElementType.TYPE;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\n/**\n * Designates that a query will be added to the request.\n * \n * @see QueryParam\n */\n@Target( { TYPE, METHOD })\n@Retention(RUNTIME)\npublic @interface QueryParams {\n\n   String NULL = \"QUERY_NULL\";\n\n   String [] keys();\n\n   String [] values() default NULL;\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/annotations/RequestFilters.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.annotations;\n\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.ElementType.TYPE;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\nimport org.jclouds.http.HttpRequestFilter;\n\n/**\n * Filters that should be applied to the request\n */\n@Target( { TYPE, METHOD })\n@Retention(RUNTIME)\npublic @interface RequestFilters {\n   Class<? extends HttpRequestFilter>[] value();\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/annotations/ResponseParser.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.annotations;\n\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\nimport org.jclouds.http.HttpResponse;\n\nimport com.google.common.base.Function;\n\n/**\n * Shows the transformer type used to parse the HttpResponse\n */\n@Target(METHOD)\n@Retention(RUNTIME)\npublic @interface ResponseParser {\n   Class<? extends Function<HttpResponse, ?>> value();\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/annotations/SelectJson.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.annotations;\n\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\n/**\n * Selects a name in a json structure as opposed to parsing from root.\n * \n * ex. for \"foo\" { \"foo\" :\"bar\" } becomes \"bar\"\n */\n@Target(METHOD)\n@Retention(RUNTIME)\npublic @interface SelectJson {\n\n   /**\n    * Each of the keys are tried in order. This helps in the case the server renamed a field in json.\n    */\n   String[] value();\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/annotations/SinceApiVersion.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.annotations;\n\nimport static java.lang.annotation.ElementType.FIELD;\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.ElementType.PARAMETER;\nimport static java.lang.annotation.ElementType.TYPE;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\nimport jakarta.inject.Qualifier;\n\n\n/**\n * Designates that this resource only exists since a particular\n * {@link ApiVersion}.\n * \n * For example, in EC2, the tag api only exists at or after version\n * {@code 2010-08-31}\n * \n * @see ApiVersion\n */\n@Target({ TYPE, METHOD, FIELD, PARAMETER })\n@Retention(RUNTIME)\n@Qualifier\npublic @interface SinceApiVersion {\n\n   /**\n    * less than or equal to the String bound to {@link ApiVersion}, typically\n    * bound as either {@link Constants#PROPERTY_API_VERSION} property or\n    * {@link ContextBuilder#apiVersion}\n    * \n    */\n   String value();\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/annotations/SkipEncoding.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.annotations;\n\nimport static java.lang.annotation.ElementType.TYPE;\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\n/**\n * Designates we should not encode the following parameters\n */\n@Target({ TYPE, METHOD })\n@Retention(RUNTIME)\npublic @interface SkipEncoding {\n   char[] value();\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/annotations/Transform.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.annotations;\n\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\nimport com.google.common.base.Function;\n\n/**\n * Shows the transformer type used to parse the first result of the HttpResponse\n */\n@Target(METHOD)\n@Retention(RUNTIME)\npublic @interface Transform {\n   Class<? extends Function<?, ?>> value();\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/annotations/Unwrap.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.annotations;\n\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\n/**\n * Unwraps the only value in a nested json response\n * \n * ex. { \"foo\" :\"bar\" } becomes \"bar\"\n */\n@Target(METHOD)\n@Retention(RUNTIME)\npublic @interface Unwrap {\n\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/annotations/VirtualHost.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.annotations;\n\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.ElementType.TYPE;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\n/**\n * Designates that this Resource expects virtual host style requests\n */\n@Target( { TYPE, METHOD })\n@Retention(RUNTIME)\npublic @interface VirtualHost {\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/annotations/WrapWith.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.annotations;\n\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.ElementType.PARAMETER;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\n/**\n * Wraps the payload in json nested one level deep, relating to the value parameter.\n * \n * ex. \"bar\" becomes { \"foo\" :\"bar\" }\n */\n@Target( { METHOD, PARAMETER })\n@Retention(RUNTIME)\npublic @interface WrapWith {\n\n   /**\n    * what to wrap the value in\n    */\n   String value();\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/annotations/XMLResponseParser.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.annotations;\n\nimport static java.lang.annotation.ElementType.METHOD;\nimport static java.lang.annotation.RetentionPolicy.RUNTIME;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.Target;\n\nimport org.jclouds.http.functions.ParseSax;\n\n/**\n * Shows the transformer type used to parse XML in a HttpResponse\n */\n@Target(METHOD)\n@Retention(RUNTIME)\npublic @interface XMLResponseParser {\n   Class<? extends ParseSax.HandlerWithResult<?>> value();\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/binders/BindAsHostPrefix.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.net.InternetDomainName.from;\nimport static com.google.common.net.InternetDomainName.isValid;\nimport static org.jclouds.http.Uris.uriBuilder;\n\nimport java.net.URI;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\nimport com.google.common.net.InternetDomainName;\n\n@Singleton\npublic class BindAsHostPrefix implements Binder {\n\n   @Override\n   @SuppressWarnings(\"unchecked\")\n   public <R extends HttpRequest> R bindToRequest(R request, Object payload) {\n      checkNotNull(payload, \"hostprefix\");\n      checkArgument(isValid(request.getEndpoint().getHost()), \"this is only valid for hostnames: \" + request);\n      InternetDomainName name = from(request.getEndpoint().getHost()).child(payload.toString());\n      URI newEndpoint = uriBuilder(request.getEndpoint()).host(name.toString()).build();\n      return (R) request.toBuilder().endpoint(newEndpoint).replacePath(request.getEndpoint().getRawPath()).build();\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/binders/BindException.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.binders;\n\nimport org.jclouds.http.HttpRequest;\n\n/**\n * Exception thrown during the binding process.\n */\npublic class BindException extends RuntimeException {\n\n   private static final long serialVersionUID = 1L;\n\n   private HttpRequest request;\n\n   public BindException(final HttpRequest request) {\n      super();\n      this.request = request;\n   }\n\n   public BindException(final HttpRequest request, final String message) {\n      super(message);\n      this.request = request;\n   }\n\n   public BindException(final HttpRequest request, final Throwable cause) {\n      super(cause.getMessage(), cause);\n      this.request = request;\n   }\n\n   public BindException(final HttpRequest request, final String message, final Throwable cause) {\n      super(message, cause);\n      this.request = request;\n   }\n\n   @Override\n   public String getMessage() {\n      String msg = \"Could not bind object to request\" + request + \": \";\n      return msg + super.getMessage();\n   }\n\n   public HttpRequest getRequest() {\n      return request;\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/binders/BindMapToStringPayload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.http.UriTemplates.expand;\nimport static org.jclouds.util.Strings2.urlDecode;\n\nimport java.util.Map;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.MapBinder;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\n\nimport com.google.common.reflect.Invokable;\n\n@Singleton\npublic class BindMapToStringPayload implements MapBinder {\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      checkNotNull(postParams, \"postParams\");\n      GeneratedHttpRequest r = GeneratedHttpRequest.class.cast(checkNotNull(request, \"request\"));\n      Invokable<?, ?> invoked = r.getInvocation().getInvokable();\n      checkArgument(invoked.isAnnotationPresent(Payload.class),\n            \"method %s must have @Payload annotation to use this binder\", invoked);\n      String payload = invoked.getAnnotation(Payload.class).value();\n      if (!postParams.isEmpty()) {\n         payload = urlDecode(expand(payload, postParams));\n      }\n      return (R) request.toBuilder().payload(payload).build();\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object payload) {\n      throw new IllegalArgumentException(\"this is a map binder\");\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/binders/BindToJsonPayload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.binders;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.json.Json;\nimport org.jclouds.rest.MapBinder;\n\n/**\n * Binds the object to the request as a json object.\n */\npublic class BindToJsonPayload implements MapBinder {\n\n   protected final Json jsonBinder;\n\n   @Inject\n   public BindToJsonPayload(Json jsonBinder) {\n      this.jsonBinder = checkNotNull(jsonBinder, \"jsonBinder\");\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      return bindToRequest(request, (Object) postParams);\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object payload) {\n      String json = jsonBinder.toJson(checkNotNull(payload, \"payload\"));\n      request.setPayload(json);\n      request.getPayload().getContentMetadata().setContentType(\"application/json\");\n      return request;\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/binders/BindToJsonPayloadWrappedWith.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.binders;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.MapBinder;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.inject.assistedinject.Assisted;\n\n/**\n * Sometimes, cloud apis wrap requests inside an envelope. This addresses this.\n */\npublic class BindToJsonPayloadWrappedWith implements MapBinder {\n\n   public interface Factory {\n      BindToJsonPayloadWrappedWith create(String envelope);\n   }\n\n   private final BindToJsonPayload jsonBinder;\n   private final String envelope;\n\n   @Inject\n   BindToJsonPayloadWrappedWith(BindToJsonPayload jsonBinder, @Assisted String envelope) {\n      this.jsonBinder = checkNotNull(jsonBinder, \"jsonBinder\");\n      this.envelope = checkNotNull(envelope, \"envelope\");\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object payload) {\n      return jsonBinder.bindToRequest(request, (Object) ImmutableMap.of(envelope, checkNotNull(payload, \"payload\")));\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      return this.bindToRequest(request, (Object) postParams);\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/binders/BindToStringPayload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.binders;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\n/**\n * Adds an payload to a request.\n */\n@Singleton\npublic class BindToStringPayload implements Binder {\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object payload) {\n      request.setPayload(payload.toString());\n      return request;\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/binders/BindToXMLPayload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.binders;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.io.IOException;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.io.MutableContentMetadata;\nimport org.jclouds.rest.Binder;\nimport org.jclouds.xml.XMLParser;\n\nimport com.google.common.base.Strings;\n\n/**\n * Binds the request parameters to an XML formatted payload.\n */\n@Singleton\npublic class BindToXMLPayload implements Binder {\n   protected final XMLParser xmlParser;\n\n   @Inject\n   public BindToXMLPayload(final XMLParser xmlParser) {\n      this.xmlParser = checkNotNull(xmlParser, \"xmlParser\");\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(final R request, final Object input) {\n      try {\n         String xml = xmlParser.toXML(checkNotNull(input, \"input\"));\n         request.setPayload(xml);\n         MutableContentMetadata metadata = request.getPayload().getContentMetadata();\n         if (contentTypeMustBeAdded(metadata)) {\n            metadata.setContentType(\"application/xml\");\n         }\n         return request;\n      } catch (IOException ex) {\n         throw new BindException(request, ex);\n      }\n   }\n\n   private static boolean contentTypeMustBeAdded(final MutableContentMetadata metadata) {\n      return Strings.isNullOrEmpty(metadata.getContentType())\n            || metadata.getContentType().equals(\"application/unknown\");\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/config/AnnotatedHttpApiProvider.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.config;\n\nimport java.lang.reflect.Proxy;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.reflect.Invocation;\nimport org.jclouds.rest.internal.DelegatesToInvocationFunction;\n\nimport com.google.common.base.Function;\nimport com.google.inject.Provider;\n\n@Singleton\npublic class AnnotatedHttpApiProvider<A> implements Provider<A> {\n   private final Class<A> annotatedApiType;\n   private final DelegatesToInvocationFunction<A, Function<Invocation, Object>> httpInvoker;\n\n   @Inject\n   private AnnotatedHttpApiProvider(DelegatesToInvocationFunction<A, Function<Invocation, Object>> httpInvoker,\n         Class<A> annotatedApiType) {\n      this.httpInvoker = httpInvoker;\n      this.annotatedApiType = annotatedApiType;\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public A get() {\n      return (A) Proxy.newProxyInstance(annotatedApiType.getClassLoader(), new Class<?>[] { annotatedApiType }, httpInvoker);\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/config/BinderUtils.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.config;\n\nimport com.google.common.reflect.TypeParameter;\nimport com.google.common.reflect.TypeToken;\nimport com.google.inject.Binder;\nimport com.google.inject.TypeLiteral;\n\npublic class BinderUtils {\n\n   /**\n    * adds an explicit binding for {@code async} by parsing its annotations.\n    * \n    * @param <S>\n    *           sync interface that blocks\n    * @param <A>\n    *           api type with http annotations\n    * @param binder\n    *           guice binder\n    * @param api\n    *           type with http annotations\n    */\n   public static <S, A> void bindHttpApi(Binder binder, Class<A> api) {\n      bindClass(binder, api);\n      bindAnnotatedHttpApiProvider(binder, api);\n   }\n   \n   @SuppressWarnings({ \"unchecked\", \"serial\" })\n   private static <T> void bindAnnotatedHttpApiProvider(Binder binder, Class<T> annotated) {\n      TypeToken<AnnotatedHttpApiProvider<T>> token = new TypeToken<AnnotatedHttpApiProvider<T>>() {\n      }.where(new TypeParameter<T>() {\n      }, annotated);\n      binder.bind(annotated).toProvider(TypeLiteral.class.cast(TypeLiteral.get(token.getType())));\n   }\n\n   @SuppressWarnings({ \"unchecked\", \"serial\" })\n   private static <K> void bindClass(Binder binder, Class<K> sync) {\n      binder.bind(TypeLiteral.class.cast(TypeLiteral.get(new TypeToken<Class<K>>() {\n      }.where(new TypeParameter<K>() {\n      }, sync).getType()))).toInstance(sync);\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/config/CredentialStoreModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.config;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\nimport java.util.concurrent.ConcurrentHashMap;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.collect.TransformingMap;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.json.Json;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.rest.ConfiguresCredentialStore;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Charsets;\nimport com.google.common.base.Function;\nimport com.google.common.io.ByteSource;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Provides;\nimport com.google.inject.TypeLiteral;\n\n@Beta\n@ConfiguresCredentialStore\npublic class CredentialStoreModule extends AbstractModule {\n   private final Map<String, ByteSource> backing;\n\n   public CredentialStoreModule(Map<String, ByteSource> backing) {\n      this.backing = backing;\n   }\n\n   public CredentialStoreModule() {\n      this(new ConcurrentHashMap<String, ByteSource>());\n   }\n\n   @Override\n   protected void configure() {\n      bind(new TypeLiteral<Function<Credentials, ByteSource>>() {\n      }).to(CredentialsToJsonByteSource.class);\n      bind(new TypeLiteral<Function<ByteSource, Credentials>>() {\n      }).to(CredentialsFromJsonByteSource.class);\n      bind(new TypeLiteral<Map<String, ByteSource>>() {\n      }).toInstance(backing);\n   }\n\n   public static class CredentialsToJsonByteSource implements Function<Credentials, ByteSource> {\n      private final Json json;\n\n      @Inject CredentialsToJsonByteSource(Json json) {\n         this.json = json;\n      }\n\n      @Override public ByteSource apply(Credentials from) {\n         checkNotNull(from, \"inputCredentials\");\n         return ByteSource.wrap(json.toJson(from).getBytes(Charsets.UTF_8));\n      }\n   }\n\n   public static class CredentialsFromJsonByteSource implements Function<ByteSource, Credentials> {\n      @Resource\n      protected Logger logger = Logger.NULL;\n\n      private final Json json;\n\n      @Inject CredentialsFromJsonByteSource(Json json) {\n         this.json = json;\n      }\n\n      @Override public Credentials apply(ByteSource from) {\n         try {\n            String creds = (checkNotNull(from)).asCharSource(Charsets.UTF_8).read();\n            return json.fromJson(creds, Credentials.class);\n         } catch (Exception e) {\n            logger.warn(e, \"ignoring problem retrieving credentials\");\n            return null;\n         }\n      }\n   }\n\n   @Provides\n   @Singleton\n   protected final Map<String, Credentials> provideCredentialStore(Map<String, ByteSource> backing,\n         Function<Credentials, ByteSource> credentialsSerializer,\n         Function<ByteSource, Credentials> credentialsDeserializer) {\n      return new TransformingMap<String, ByteSource, Credentials>(backing, credentialsDeserializer,\n            credentialsSerializer);\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/config/HttpApiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.config;\n\nimport static org.jclouds.reflect.Types2.checkBound;\nimport static org.jclouds.rest.config.BinderUtils.bindHttpApi;\n\nimport org.jclouds.reflect.Invocation;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.HttpClient;\nimport org.jclouds.rest.internal.InvokeHttpMethod;\n\nimport com.google.common.base.Function;\nimport com.google.common.reflect.TypeToken;\nimport com.google.inject.TypeLiteral;\n\n@ConfiguresHttpApi\npublic class HttpApiModule<A> extends RestModule {\n   protected final Class<A> api;\n\n   /**\n    * Note that this ctor requires that you instantiate w/resolved generic\n    * params. For example, via a subclass of a bound type, or natural\n    * instantiation w/resolved type params.\n    */\n   @SuppressWarnings(\"unchecked\")\n   protected HttpApiModule() {\n      this.api = Class.class.cast(checkBound(new TypeToken<A>(getClass()) {\n         private static final long serialVersionUID = 1L;\n      }).getRawType());\n   }\n\n   public HttpApiModule(Class<A> api) {\n     this.api = api;\n   }\n\n   @Override\n   protected void configure() {\n      super.configure();\n      bind(new TypeLiteral<Function<Invocation, Object>>() {\n      }).to(InvokeHttpMethod.class);\n      bindHttpApi(binder(), api);\n      bindHttpApi(binder(), HttpClient.class);\n      bindErrorHandlers();\n      bindRetryHandlers();\n   }\n\n   /**\n    * overrides this to change the default retry handlers for the http engine\n    * \n    * ex.\n    * \n    * <pre>\n    * bind(HttpRetryHandler.class).annotatedWith(Redirection.class).to(AWSRedirectionRetryHandler.class);\n    * bind(HttpRetryHandler.class).annotatedWith(ClientError.class).to(AWSClientErrorRetryHandler.class);\n    * </pre>\n    * \n    */\n   protected void bindRetryHandlers() {\n   }\n\n   /**\n    * overrides this to change the default error handlers for the http engine\n    * \n    * ex.\n    * \n    * <pre>\n    * bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(ParseAWSErrorFromXmlContent.class);\n    * bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(ParseAWSErrorFromXmlContent.class);\n    * bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(ParseAWSErrorFromXmlContent.class);\n    * </pre>\n    * \n    * \n    */\n   protected void bindErrorHandlers() {\n\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/config/InvocationConfig.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.config;\n\nimport org.jclouds.Fallback;\nimport org.jclouds.reflect.Invocation;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Optional;\nimport com.google.inject.ImplementedBy;\n\n/**\n * Provides the ability to decouple timeouts and fallbacks from what's built-in.\n */\n@Beta\n@ImplementedBy(ReadAnnotationsAndProperties.class)\npublic interface InvocationConfig {\n\n   /**\n    * If this is present, Sync method calls will block up to the specified nanos\n    * and throw an {@linkplain UncheckedTimeoutException}. If this is not\n    * present, Sync method calls will be invoked directly, typically through\n    * {@linkplain HttpCommandExecutorService#invoke}.\n    */\n   Optional<Long> getTimeoutNanos(Invocation in);\n\n   /**\n    * command named used in logging and configuration keys.\n    */\n   String getCommandName(Invocation invocation);\n\n   /**\n    * fallback used for commands when exceptions are encountered.\n    */\n   Fallback<?> getFallback(Invocation invocation);\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/config/ReadAnnotationsAndProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.config;\n\nimport static com.google.common.base.Optional.fromNullable;\nimport static com.google.common.collect.Maps.transformValues;\nimport static java.util.concurrent.TimeUnit.MILLISECONDS;\nimport static org.jclouds.Constants.PROPERTY_TIMEOUTS_PREFIX;\nimport static org.jclouds.util.Maps2.transformKeys;\nimport static org.jclouds.util.Predicates2.startsWith;\n\nimport java.util.Map;\nimport java.util.regex.Pattern;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.reflect.Invocation;\nimport org.jclouds.rest.annotations.Fallback;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.reflect.Invokable;\nimport com.google.inject.Injector;\n\n@Beta\n@Singleton\npublic class ReadAnnotationsAndProperties implements InvocationConfig {\n   private final Injector injector;\n   private final org.jclouds.Fallback<Object> defaultFallback;\n   private final Map<String, Long> timeouts;\n\n   @Inject\n   ReadAnnotationsAndProperties(Injector injector,\n         Function<Predicate<String>, Map<String, String>> filterStringsBoundByName,\n         org.jclouds.Fallback<Object> defaultFallback) {\n      this.injector = injector;\n      this.defaultFallback = defaultFallback;\n      this.timeouts = timeouts(filterStringsBoundByName);\n   }\n\n   @Override\n   public Optional<Long> getTimeoutNanos(Invocation in) {\n      String commandName = getCommandName(in);\n      Optional<Long> defaultMillis = fromNullable(timeouts.get(\"default\"));\n      Optional<Long> timeoutMillis = fromNullable(timeouts.get(commandName));\n      Invokable<?, ?> invoked = in.getInvokable();\n      if (invoked.isAnnotationPresent(Named.class)) {\n         timeoutMillis = timeoutMillis.or(defaultMillis);\n      } else {\n         // TODO: remove old logic once Named annotations are on all methods\n         String className = invoked.getOwnerType().getRawType().getSimpleName();\n         timeoutMillis = timeoutMillis.or(fromNullable(timeouts.get(className))).or(defaultMillis);\n      }\n      if (timeoutMillis.isPresent())\n         return Optional.of(MILLISECONDS.toNanos(timeoutMillis.get()));\n      return Optional.absent();\n   }\n\n   @Override\n   public String getCommandName(Invocation invocation) {\n      Invokable<?, ?> invoked = invocation.getInvokable();\n      if (invoked.isAnnotationPresent(Named.class)) {\n         return invoked.getAnnotation(Named.class).value();\n      } else {\n         // TODO: remove old logic once Named annotations are on all methods\n         String className = invoked.getOwnerType().getRawType().getSimpleName();\n         return className + \".\" + invoked.getName();\n      }\n   }\n\n   @Override\n   public org.jclouds.Fallback<?> getFallback(Invocation invocation) {\n      Fallback fallback = invocation.getInvokable().getAnnotation(Fallback.class);\n      if (fallback != null) {\n         return injector.getInstance(fallback.value());\n      }\n      return defaultFallback;\n   }\n\n   /**\n    * override timeout by values configured in properties(in ms)\n    */\n   static Map<String, Long> timeouts(Function<Predicate<String>, Map<String, String>> filterStringsBoundByName) {\n      Map<String, String> stringBoundWithTimeoutPrefix = filterStringsBoundByName\n            .apply(startsWith(PROPERTY_TIMEOUTS_PREFIX));\n      Map<String, Long> longsByName = transformValues(stringBoundWithTimeoutPrefix, new Function<String, Long>() {\n         public Long apply(String input) {\n            return Long.valueOf(String.valueOf(input));\n         }\n      });\n      return transformKeys(longsByName, new Function<String, String>() {\n         public String apply(String input) {\n            return input.replaceFirst(Pattern.quote(PROPERTY_TIMEOUTS_PREFIX), \"\");\n         }\n      });\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/config/RestModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.config;\n\nimport static com.google.common.util.concurrent.Atomics.newReference;\n\nimport java.net.Proxy;\nimport java.net.URI;\nimport java.util.Map;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport org.jclouds.fallbacks.MapHttp4xxCodesToExceptions;\nimport org.jclouds.functions.IdentityFunction;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.config.SaxParserModule;\nimport org.jclouds.internal.FilterStringsBoundToInjectorByName;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.location.config.LocationModule;\nimport org.jclouds.proxy.ProxyForURI;\nimport org.jclouds.reflect.Invocation;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.binders.BindToJsonPayloadWrappedWith;\nimport org.jclouds.rest.internal.RestAnnotationProcessor;\nimport org.jclouds.rest.internal.TransformerForRequest;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.assistedinject.FactoryModuleBuilder;\n\npublic class RestModule extends AbstractModule {\n   protected final AtomicReference<AuthorizationException> authException = newReference();\n\n   protected void installLocations() {\n      install(new LocationModule());\n   }\n\n   @Override\n   protected void configure() {\n      install(new SaxParserModule());\n      install(new GsonModule());\n      install(new SetCaller.Module());\n      install(new FactoryModuleBuilder().build(BindToJsonPayloadWrappedWith.Factory.class));\n      bind(new TypeLiteral<Function<HttpRequest, Function<HttpResponse, ?>>>() {\n      }).to(TransformerForRequest.class);\n      bind(new TypeLiteral<org.jclouds.Fallback<Object>>() {\n      }).to(MapHttp4xxCodesToExceptions.class);\n      bind(new TypeLiteral<Function<Invocation, HttpRequest>>() {\n      }).to(RestAnnotationProcessor.class);\n      bind(IdentityFunction.class).toInstance(IdentityFunction.INSTANCE);\n      // this will help short circuit scenarios that can otherwise lock out users\n      bind(new TypeLiteral<AtomicReference<AuthorizationException>>() {\n      }).toInstance(authException);\n      bind(new TypeLiteral<Function<Predicate<String>, Map<String, String>>>() {\n      }).to(FilterStringsBoundToInjectorByName.class);\n      bind(new TypeLiteral<Function<URI, Proxy>>() {\n      }).to(ProxyForURI.class);\n      installLocations();\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/config/SetCaller.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.config;\n\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.inject.name.Names.named;\n\nimport org.jclouds.reflect.Invocation;\n\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Key;\nimport com.google.inject.Provider;\n\n/**\n * Allows the provider to supply a value set in a threadlocal.\n */\npublic class SetCaller {\n\n   private final ThreadLocal<Invocation> caller = new ThreadLocal<Invocation>();\n\n   public void enter(Invocation caller) {\n      checkState(this.caller.get() == null, \"A scoping block is already in progress\");\n      this.caller.set(caller);\n   }\n\n   public void exit() {\n      checkState(caller.get() != null, \"No scoping block in progress\");\n      caller.remove();\n   }\n\n   public static class Module extends AbstractModule {\n      public void configure() {\n         SetCaller delegateScope = new SetCaller();\n         bind(CALLER_INVOCATION).toProvider(delegateScope.new CallerInvocationProvider());\n         bind(SetCaller.class).toInstance(delegateScope);\n      }\n   }\n\n   private static final Key<Invocation> CALLER_INVOCATION = Key.get(Invocation.class, named(\"caller\"));\n\n   class CallerInvocationProvider implements Provider<Invocation> {\n      @Override\n      public Invocation get() {\n         return caller.get();\n      }\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/functions/AlwaysPresentImplicitOptionalConverter.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.functions;\n\nimport org.jclouds.reflect.InvocationSuccess;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Optional;\n\n@Beta\npublic class AlwaysPresentImplicitOptionalConverter implements ImplicitOptionalConverter {\n\n   @Override\n   public Optional<Object> apply(InvocationSuccess input) {\n      return input.getResult();\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/functions/ImplicitOptionalConverter.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.functions;\n\nimport org.jclouds.reflect.InvocationSuccess;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.inject.ImplementedBy;\n\n/**\n * When a client marked @Delegate is optional, the implementation of this is\n * responsible for creating the optional object.\n * \n * For example.\n * \n * <pre>\n * interface MyCloud {\n *    &#064;Delegate\n *    Optional&lt;KeyPairClient&gt; getKeyPairExtensionForRegion(String region);\n * }\n * </pre>\n * \n * The input object of type {@link InvocationSuccess} will include the\n * following.\n * <ol>\n * <li>the class declaring the method that returns optional:\n * {@link InvocationSuccess#getClazz}; in the example above,\n * {@code MyCloud}</li>\n * <li>the method returning the optional:\n * {@link InvocationSuccess#getMethod}; in the example above,\n * {@code getKeyPairExtensionForRegion}</li>\n * <li>the args passed to that method at runtime:\n * {@link InvocationSuccess#getArgs}; for example {@code North}</li>\n * <li>the rest client to be enclosed in the optional, should you choose to\n * return it: {@link InvocationSuccess#getReturnVal}; in the example\n * above, an implementation of {@code KeyPairClient}</li>\n * </ol>\n * \n * Using this context, your implementation of {@link ImplicitOptionalConverter}\n * can perform whatever you need, when deciding if the the returnVal is present\n * and available. Here are some ideas:\n * <ul>\n * <li>call a smoke test command</li>\n * <li>look at the annotations on the class and compare those against a\n * configuration switch enabling the extension</li>\n * <li>inspect the health of the client, perhaps looking for error status</li>\n * <li>call another api which can validate the feature can be presented</li>\n * </ul>\n * \n * The {@link PresentWhenApiVersionLexicographicallyAtOrAfterSinceApiVersion\n * default implementation} returns present if no {@link SinceApiVersion}\n * annotation is assigned, or the value is less than or equal to the current\n * {@link ApiVersion}. To override this, add the following in your subclass\n * override of {@link RestClientModule#configure} method:\n * \n * <pre>\n * bind(ImplicitOptionalConverter.class).to(MyCustomOptionalConverter.class);\n * </pre>\n */\n@Beta\n@ImplementedBy(PresentWhenApiVersionLexicographicallyAtOrAfterSinceApiVersion.class)\npublic interface ImplicitOptionalConverter extends Function<InvocationSuccess, Optional<Object>> {\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/functions/PresentWhenApiVersionLexicographicallyAtOrAfterSinceApiVersion.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.util.Optionals2.unwrapIfOptional;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.reflect.InvocationSuccess;\nimport org.jclouds.rest.annotations.ApiVersion;\nimport org.jclouds.rest.annotations.SinceApiVersion;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Optional;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\n\n@Beta\n@Singleton\npublic class PresentWhenApiVersionLexicographicallyAtOrAfterSinceApiVersion implements ImplicitOptionalConverter {\n\n   @VisibleForTesting\n   static final class Loader extends CacheLoader<InvocationSuccess, Optional<Object>> {\n      private final String apiVersion;\n\n      @Inject\n      Loader(@ApiVersion String apiVersion) {\n         this.apiVersion = checkNotNull(apiVersion, \"apiVersion\");\n      }\n\n      @Override\n      public Optional<Object> load(InvocationSuccess input) {\n         Class<?> target = unwrapIfOptional(input.getInvocation().getInvokable().getReturnType());\n         Optional<SinceApiVersion> sinceApiVersion = Optional.fromNullable(target.getAnnotation(SinceApiVersion.class));\n         if (sinceApiVersion.isPresent()) {\n            String since = sinceApiVersion.get().value();\n            if (since.compareTo(apiVersion) <= 0)\n               return input.getResult();\n            return Optional.absent();\n         } else {\n            // No SinceApiVersion annotation, so return present\n            return input.getResult();\n         }\n      }\n   }\n\n   private final LoadingCache<InvocationSuccess, Optional<Object>> lookupCache;\n\n   @Inject\n   protected PresentWhenApiVersionLexicographicallyAtOrAfterSinceApiVersion(@ApiVersion String apiVersion) {\n      // no need to read class annotations for every request\n      this.lookupCache = CacheBuilder.newBuilder().build(new Loader(apiVersion));\n   }\n\n   @Override\n   public Optional<Object> apply(InvocationSuccess input) {\n      return lookupCache.getUnchecked(input);\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/internal/ApiContextImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.annotations.Name;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.internal.ContextImpl;\nimport org.jclouds.lifecycle.Closer;\nimport org.jclouds.location.Provider;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.rest.ApiContext;\nimport org.jclouds.rest.Utils;\n\nimport com.google.common.base.Supplier;\nimport com.google.inject.Injector;\nimport com.google.inject.Key;\nimport com.google.inject.Singleton;\nimport com.google.inject.TypeLiteral;\n\n/**\n*/\n@Singleton\npublic class ApiContextImpl<A> extends ContextImpl implements ApiContext<A> {\n\n   private final A api;\n\n   @Inject\n   protected ApiContextImpl(@Name String name, ProviderMetadata providerMetadata,\n         @Provider Supplier<Credentials> creds, Utils utils, Closer closer, Injector injector, TypeLiteral<A> api) {\n      super(name, providerMetadata, creds, utils, closer);\n      checkNotNull(injector, \"injector\");\n      this.api = injector.getInstance(Key.get(checkNotNull(api, \"api\")));\n   }\n\n   @Override\n   public A getApi() {\n      return api;\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/internal/BaseHttpApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.reflect.Reflection2.typeToken;\nimport static org.jclouds.reflect.Types2.checkBound;\n\nimport java.util.Properties;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.apis.internal.BaseApiMetadata;\nimport org.jclouds.rest.ApiContext;\nimport org.jclouds.rest.HttpApiMetadata;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.reflect.TypeParameter;\nimport com.google.common.reflect.TypeToken;\n\n/**\n * Useful in creating http apis.\n */\n@Beta\npublic abstract class BaseHttpApiMetadata<A> extends BaseApiMetadata implements HttpApiMetadata<A> {\n\n   protected final Class<A> api;\n\n   protected BaseHttpApiMetadata(Builder<A, ?> builder) {\n      super(builder);\n      this.api = checkNotNull(builder.api, \"api\");\n   }\n\n   public static Properties defaultProperties() {\n      Properties props = BaseApiMetadata.defaultProperties();\n      return props;\n   }\n\n   public static <S, A> TypeToken<ApiContext<A>> contextToken(TypeToken<A> apiToken) {\n      return new TypeToken<ApiContext<A>>() {\n         private static final long serialVersionUID = 1L;\n      }.where(new TypeParameter<A>() {\n      }, apiToken);\n   }\n\n   public abstract static class Builder<A, T extends Builder<A, T>> extends BaseApiMetadata.Builder<T> implements\n         HttpApiMetadata.Builder<A, T> {\n      protected Class<A> api;\n\n      /**\n       * Note that this ctor requires that you instantiate w/resolved generic\n       * params. For example, via a subclass of a bound type, or natural\n       * instantiation w/resolved type params.\n       */\n      @SuppressWarnings(\"unchecked\")\n      protected Builder() {\n         this.api = Class.class.cast(checkBound(new TypeToken<A>(getClass()) {\n            private static final long serialVersionUID = 1L;\n         }).getRawType());\n         init();\n      }\n\n      protected Builder(Class<A> api) {\n         this.api = checkNotNull(api, \"api\");\n         init();\n      }\n\n      private void init() {\n         api(api)\n         .name(api.getSimpleName())\n         .context(contextToken(typeToken(api)))\n         .defaultProperties(BaseHttpApiMetadata.defaultProperties());\n      }\n\n      @Override\n      public T api(Class<A> api) {\n         this.api = checkNotNull(api, \"api\");\n         return self();\n      }\n\n      @SuppressWarnings(\"unchecked\")\n      @Override\n      public T fromApiMetadata(ApiMetadata in) {\n         if (in instanceof HttpApiMetadata) {\n            HttpApiMetadata<?> http = HttpApiMetadata.class.cast(in);\n            api(Class.class.cast(http.getApi()));\n         }\n         super.fromApiMetadata(in);\n         return self();\n      }\n\n   }\n\n   @Override\n   public Class<A> getApi() {\n      return api;\n   }\n\n   @Override\n   protected ToStringHelper string() {\n      return super.string().add(\"api\", getApi());\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/internal/DelegatesToInvocationFunction.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.internal;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Predicates.notNull;\nimport static com.google.common.base.Throwables.propagate;\nimport static com.google.common.collect.Iterables.all;\nimport static com.google.common.collect.Iterables.find;\nimport static com.google.inject.util.Types.newParameterizedType;\nimport static org.jclouds.reflect.Reflection2.method;\nimport static org.jclouds.reflect.Reflection2.typeToken;\nimport static org.jclouds.util.Optionals2.isReturnTypeOptional;\nimport static org.jclouds.util.Optionals2.unwrapIfOptional;\nimport static org.jclouds.util.Throwables2.getFirstThrowableOfType;\nimport static org.jclouds.util.Throwables2.propagateIfPossible;\n\nimport java.io.Closeable;\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.InvocationHandler;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Proxy;\nimport java.lang.reflect.Type;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Qualifier;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.lifecycle.Closer;\nimport org.jclouds.reflect.FunctionalReflection;\nimport org.jclouds.reflect.Invocation;\nimport org.jclouds.reflect.InvocationSuccess;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.annotations.Delegate;\nimport org.jclouds.rest.config.SetCaller;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Function;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.reflect.Invokable;\nimport com.google.common.reflect.TypeToken;\nimport com.google.inject.Binding;\nimport com.google.inject.ConfigurationException;\nimport com.google.inject.Injector;\nimport com.google.inject.Key;\nimport com.google.inject.Provides;\nimport com.google.inject.ProvisionException;\nimport com.google.inject.util.Types;\n\n/**\n * @param <S>\n *           The enclosing type of the interface that a dynamic proxy like this implements\n * @param <F>\n *           The function that implements this dynamic proxy\n */\n@Beta\npublic class DelegatesToInvocationFunction<S, F extends Function<Invocation, Object>> implements\n      InvocationHandler {\n\n   private static final Object[] NO_ARGS = {};\n\n   /**\n    * {@inheritDoc}\n    * \n    * <p>\n    * <ul>\n    * <li>{@code proxy.hashCode()} delegates to {@link AbstractInvocationHandler#hashCode}\n    * <li>{@code proxy.toString()} delegates to {@link AbstractInvocationHandler#toString}\n    * <li>{@code proxy.equals(argument)} returns true if:\n    * <ul>\n    * <li>{@code proxy} and {@code argument} are of the same type\n    * <li>and {@link AbstractInvocationHandler#equals} returns true for the {@link InvocationHandler} of\n    * {@code argument}\n    * </ul>\n    * <li>other method calls are dispatched to {@link #handleInvocation}.\n    * </ul>\n    * \n    * @throws Throwable\n    */\n   @Override\n   public final Object invoke(Object proxy, Method invoked, @Nullable Object[] argv) throws Throwable {\n      if (argv == null) {\n         argv = NO_ARGS;\n      }\n      if (argv.length == 0 && invoked.getName().equals(\"hashCode\")) {\n         return hashCode();\n      }\n      if (argv.length == 1 && invoked.getName().equals(\"equals\") && invoked.getParameterTypes()[0] == Object.class) {\n         Object arg = argv[0];\n         return proxy.getClass().isInstance(arg) && equals(Proxy.getInvocationHandler(arg));\n      }\n      if (argv.length == 0 && invoked.getName().equals(\"toString\")) {\n         return toString();\n      }\n      List<Object> args = Arrays.asList(argv);\n      if (all(args, notNull()))\n         args = ImmutableList.copyOf(args);\n      else\n         args = Collections.unmodifiableList(args);\n      Invokable<?, Object> invokable = method(ownerType, invoked);\n      Invocation invocation = Invocation.create(invokable, args);\n      try {\n         return handle(invocation);\n      } catch (Throwable e) {\n         propagateIfPossible(e, invocation.getInvokable().getExceptionTypes());\n         throw e;\n      }\n   }\n\n   private static final Invokable<?, ?> CLOSE;\n\n   static {\n      try {\n         CLOSE = Invokable.from(Closeable.class.getMethod(\"close\"));\n      } catch (SecurityException e) {\n         throw propagate(e);\n      } catch (NoSuchMethodException e) {\n         throw propagate(e);\n      }\n   }\n\n   protected Object handle(Invocation invocation) {\n      Invokable<?, ?> invokable = invocation.getInvokable();\n      if (isCloseMethod(invokable)) {\n         try {\n            injector.getInstance(Closer.class).close();\n            return null;\n         } catch (Throwable e) {\n            throw propagate(e);\n         }\n      } else if (invokable.isAnnotationPresent(Provides.class)) {\n         return lookupValueFromGuice(invokable);\n      } else if (invokable.isAnnotationPresent(Delegate.class)) {\n         return propagateContextToDelegate(invocation);\n      } else {\n         return methodInvoker.apply(invocation);\n      }\n   }\n\n   private static boolean isCloseMethod(Invokable<?, ?> invokable) {\n      /*\n       * Tests equality according to the Javadoc for java.lang.reflect.Method:\n       *\n       * Two Methods are the same if they were declared by the same class\n       * and have the same name and formal parameter types and return type.\n       *\n       * Invokable now uses the *owning* class (not the declaring class) in\n       * its equals check.\n       */\n      return CLOSE.getDeclaringClass().equals(invokable.getDeclaringClass())\n              && CLOSE.getName().equals(invokable.getName())\n              && CLOSE.getParameters().equals(invokable.getParameters())\n              && CLOSE.getReturnType().equals(invokable.getReturnType());\n   }\n\n   protected final Injector injector;\n   protected final TypeToken<S> ownerType;\n   protected final SetCaller setCaller;\n   protected final Function<InvocationSuccess, Optional<Object>> optionalConverter;\n   protected final F methodInvoker;\n\n   @Inject\n   DelegatesToInvocationFunction(Injector injector, SetCaller setCaller, \n         Class<S> ownerType, Function<InvocationSuccess, Optional<Object>> optionalConverter, F methodInvoker) {\n      this.injector = checkNotNull(injector, \"injector\");\n      this.ownerType = typeToken(checkNotNull(ownerType, \"ownerType\"));\n      this.setCaller = checkNotNull(setCaller, \"setCaller\");\n      this.optionalConverter = checkNotNull(optionalConverter, \"optionalConverter\");\n      this.methodInvoker = checkNotNull(methodInvoker, \"methodInvoker\");\n   }\n\n   private Object propagateContextToDelegate(Invocation caller) {\n      Class<?> returnType = unwrapIfOptional(caller.getInvokable().getReturnType());\n      Function<Invocation, Object> delegate;\n      setCaller.enter(caller);\n      try {\n         @SuppressWarnings(\"unchecked\")\n         Key<Function<Invocation, Object>> delegateType = (Key<Function<Invocation, Object>>) methodInvokerFor(returnType);\n         delegate = injector.getInstance(delegateType);\n      } finally {\n         setCaller.exit();\n      }\n      Object result = FunctionalReflection.newProxy(returnType, delegate);\n      if (isReturnTypeOptional(caller.getInvokable())) {\n         result = optionalConverter.apply(InvocationSuccess.create(caller, result));\n      }\n      return result;\n   }\n\n   /**\n    * attempts to guess the generic type params for the delegate's invocation function based on the supplied type\n    */\n   protected Key<?> methodInvokerFor(Class<?> returnType) {\n      switch (methodInvoker.getClass().getTypeParameters().length) {\n      case 0:\n         return Key.get(methodInvoker.getClass());\n      case 1:\n         return Key.get(Types.newParameterizedType(methodInvoker.getClass(), returnType));\n      }\n      throw new IllegalArgumentException(returnType + \" has too many type parameters\");\n   }\n\n   static final Predicate<Annotation> isQualifierPresent = new Predicate<Annotation>() {\n      public boolean apply(Annotation input) {\n         return input.annotationType().isAnnotationPresent(Qualifier.class);\n      }\n   };\n\n   private Object lookupValueFromGuice(Invokable<?, ?> invoked) {\n      try {\n         Type genericReturnType = invoked.getReturnType().getType();\n         try {\n            Annotation qualifier = find(ImmutableList.copyOf(invoked.getAnnotations()), isQualifierPresent);\n            return getInstanceOfTypeWithQualifier(genericReturnType, qualifier);\n         } catch (ProvisionException e) {\n            throw propagate(e.getCause());\n         } catch (RuntimeException e) {\n            return instanceOfTypeOrPropagate(genericReturnType, e);\n         }\n      } catch (ProvisionException e) {\n         AuthorizationException aex = getFirstThrowableOfType(e, AuthorizationException.class);\n         if (aex != null)\n            throw aex;\n         throw e;\n      }\n   }\n\n   Object instanceOfTypeOrPropagate(Type genericReturnType, RuntimeException e) {\n      try {\n         // look for an existing binding\n         Binding<?> binding = injector.getExistingBinding(Key.get(genericReturnType));\n         if (binding != null)\n            return binding.getProvider().get();\n\n         // then, try looking via supplier\n         binding = injector.getExistingBinding(Key.get(newParameterizedType(Supplier.class, genericReturnType)));\n         if (binding != null)\n            return Supplier.class.cast(binding.getProvider().get()).get();\n\n         // else try to create an instance\n         return injector.getInstance(Key.get(genericReturnType));\n      } catch (ConfigurationException ce) {\n         throw e;\n      }\n   }\n\n   Object getInstanceOfTypeWithQualifier(Type genericReturnType, Annotation qualifier) {\n      // look for an existing binding\n      Binding<?> binding = injector.getExistingBinding(Key.get(genericReturnType, qualifier));\n      if (binding != null)\n         return binding.getProvider().get();\n\n      // then, try looking via supplier\n      binding = injector\n            .getExistingBinding(Key.get(newParameterizedType(Supplier.class, genericReturnType), qualifier));\n      if (binding != null)\n         return Supplier.class.cast(binding.getProvider().get()).get();\n\n      // else try to create an instance\n      return injector.getInstance(Key.get(genericReturnType, qualifier));\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(\"\").omitNullValues().add(\"ownerType\", ownerType.getRawType().getSimpleName())\n            .add(\"methodInvoker\", methodInvoker).toString();\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/internal/GeneratedHttpRequest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.net.URI;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpRequestFilter;\nimport org.jclouds.io.Payload;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.reflect.Invocation;\n\nimport com.google.common.base.Optional;\nimport com.google.common.collect.Multimap;\n\npublic final class GeneratedHttpRequest extends HttpRequest {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return new Builder().fromGeneratedHttpRequest(this);\n   }\n\n   public static final class Builder extends HttpRequest.Builder<Builder> {\n      private Invocation invocation;\n      private Optional<Invocation> caller = Optional.absent();\n\n      /**\n       * @see GeneratedHttpRequest#getInvocation()\n       */\n      public Builder invocation(Invocation invocation) {\n         this.invocation = checkNotNull(invocation, \"invocation\");\n         return this;\n      }\n\n      /**\n       * @see GeneratedHttpRequest#getCaller()\n       */\n      public Builder caller(@Nullable Invocation caller) {\n         this.caller = Optional.fromNullable(caller);\n         return this;\n      }\n\n      public GeneratedHttpRequest build() {\n         return new GeneratedHttpRequest(method, endpoint, headers.build(), payload, filters.build(), invocation,\n               caller);\n      }\n\n      public Builder fromGeneratedHttpRequest(GeneratedHttpRequest in) {\n         return super.fromHttpRequest(in).invocation(in.invocation).caller(in.getCaller().orNull());\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n   }\n\n   private final Invocation invocation;\n   private final Optional<Invocation> caller;\n\n   protected GeneratedHttpRequest(String method, URI endpoint, Multimap<String, String> headers,\n         @Nullable Payload payload, Iterable<HttpRequestFilter> filters, Invocation invocation,\n         Optional<Invocation> caller) {\n      super(method, endpoint, headers, payload, filters);\n      this.invocation = checkNotNull(invocation, \"invocation\");\n      this.caller = checkNotNull(caller, \"caller\");\n   }\n\n   /**\n    * what was interpreted to create this request\n    */\n   public Invocation getInvocation() {\n      return invocation;\n   }\n\n   public Optional<Invocation> getCaller() {\n      return caller;\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/internal/GetAcceptHeaders.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.internal;\n\nimport java.util.Set;\n\nimport jakarta.ws.rs.Consumes;\n\nimport org.jclouds.reflect.Invocation;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableSet;\n\nclass GetAcceptHeaders implements Function<Invocation, Set<String>> {\n\n   @Override\n   public Set<String> apply(Invocation invocation) {\n      Optional<Consumes> accept = Optional.fromNullable(invocation.getInvokable().getAnnotation(Consumes.class)).or(\n            Optional.fromNullable(invocation.getInvokable().getOwnerType().getRawType().getAnnotation(Consumes.class)));\n      return (accept.isPresent()) ? ImmutableSet.copyOf(accept.get().value()) : ImmutableSet.<String> of();\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/internal/InvokeHttpMethod.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.internal;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Throwables.propagate;\nimport static java.util.concurrent.TimeUnit.NANOSECONDS;\n\nimport java.util.concurrent.Callable;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\n\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpCommandExecutorService;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.reflect.Invocation;\nimport org.jclouds.rest.InvocationContext;\nimport org.jclouds.rest.config.InvocationConfig;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Function;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.Optional;\nimport com.google.common.util.concurrent.TimeLimiter;\n\npublic class InvokeHttpMethod implements Function<Invocation, Object> {\n\n   @Resource\n   private Logger logger = Logger.NULL;\n\n   private final Function<Invocation, HttpRequest> annotationProcessor;\n   private final HttpCommandExecutorService http;\n   private final TimeLimiter timeLimiter;\n   private final Function<HttpRequest, Function<HttpResponse, ?>> transformerForRequest;\n   private final InvocationConfig config;\n\n   @Inject\n   @VisibleForTesting\n   InvokeHttpMethod(Function<Invocation, HttpRequest> annotationProcessor,\n         HttpCommandExecutorService http, Function<HttpRequest, Function<HttpResponse, ?>> transformerForRequest,\n         TimeLimiter timeLimiter, InvocationConfig config) {\n      this.annotationProcessor = annotationProcessor;\n      this.http = http;\n      this.timeLimiter = timeLimiter;\n      this.transformerForRequest = transformerForRequest;\n      this.config = config;\n   }\n\n   @Override\n   public Object apply(Invocation in) {\n      Optional<Long> timeoutNanos = config.getTimeoutNanos(in);\n      if (timeoutNanos.isPresent()) {\n         return invokeWithTimeout(in, timeoutNanos.get());\n      }\n      return invoke(in);\n   }\n\n   /**\n    * invokes the {@linkplain HttpCommand} associated with {@code invocation},\n    * {@link #getTransformer(String, HttpCommand) parses its response}, and\n    * applies a {@link #getFallback(String, Invocation, HttpCommand) fallback}\n    * if a {@code Throwable} is encountered.\n    */\n   public Object invoke(Invocation invocation) {\n      String commandName = config.getCommandName(invocation);\n      HttpCommand command = toCommand(commandName, invocation);\n      Function<HttpResponse, ?> transformer = getTransformer(commandName, command);\n      org.jclouds.Fallback<?> fallback = getFallback(commandName, invocation, command);\n\n      logger.debug(\">> invoking %s\", commandName);\n      try {\n         return transformer.apply(http.invoke(command));\n      } catch (Throwable t) {\n         try {\n            return fallback.createOrPropagate(t);\n         } catch (Exception e) {\n            throw propagate(e);\n         }\n      }\n   }\n\n   /**\n    * calls {@link #invoke(Invocation)}, timing out after the specified time\n    * limit. If the target method call finished before the limit is reached, the\n    * return value or exception is propagated to the caller exactly as-is. If,\n    * on the other hand, the time limit is reached, we attempt to abort the call\n    * to the target, and throw an {@link UncheckedTimeoutException} to the\n    * caller.\n    * \n    * @param invocation\n    *           the Invocation to invoke via {@link #invoke(Invocation)}\n    * @param limitNanos\n    *           with timeoutUnit, the maximum length of time to wait in\n    *           nanoseconds\n    * @throws InterruptedException\n    *            if our thread is interrupted during execution\n    * @throws UncheckedTimeoutException\n    *            if the time limit is reached\n    * @see TimeLimiter#callWithTimeout(Callable, long, TimeUnit)\n    */\n   public Object invokeWithTimeout(final Invocation invocation, final long limitNanos) {\n      String commandName = config.getCommandName(invocation);\n      HttpCommand command = toCommand(commandName, invocation);\n      org.jclouds.Fallback<?> fallback = getFallback(commandName, invocation, command);\n\n      logger.debug(\">> blocking on %s for %s\", invocation, limitNanos);\n      try {\n         return timeLimiter\n               .callWithTimeout(new InvokeAndTransform(commandName, command), limitNanos, NANOSECONDS);\n      } catch (Throwable t) {\n         try {\n            return fallback.createOrPropagate(t);\n         } catch (Exception e) {\n            throw propagate(e);\n         }\n      }\n   }\n\n   private org.jclouds.Fallback<?> getFallback(String commandName, Invocation invocation, HttpCommand command) {\n      HttpRequest request = command.getCurrentRequest();\n      org.jclouds.Fallback<?> fallback = config.getFallback(invocation);\n      if (fallback instanceof InvocationContext)\n         InvocationContext.class.cast(fallback).setContext(request);\n      logger.trace(\"<< exceptions from %s are parsed by %s\", commandName, fallback.getClass().getSimpleName());\n      return fallback;\n   }\n\n   @VisibleForTesting\n   final class InvokeAndTransform implements Callable<Object> {\n      private final String commandName;\n      private final HttpCommand command;\n      private final Function<HttpResponse, ?> transformer;\n\n      InvokeAndTransform(String commandName, HttpCommand command) {\n         this.commandName = commandName;\n         this.command = command;\n         this.transformer = getTransformer(commandName, command);\n      }\n\n      @Override\n      public Object call() throws Exception {\n         return transformer.apply(http.invoke(command));\n      }\n\n      @Override\n      public int hashCode() {\n         return Objects.hashCode(commandName, command, transformer);\n      }\n\n      @Override\n      public boolean equals(Object obj) {\n         if (this == obj)\n            return true;\n         if (obj == null || getClass() != obj.getClass())\n            return false;\n         InvokeAndTransform that = InvokeAndTransform.class.cast(obj);\n         return equal(this.commandName, that.commandName) && equal(this.command, that.command)\n               && equal(this.transformer, that.transformer);\n      }\n\n      @Override\n      public String toString() {\n         return toStringHelper(this).add(\"commandName\", commandName).add(\"command\", command)\n               .add(\"transformer\", transformer).toString();\n      }\n   }\n\n   private HttpCommand toCommand(String commandName, Invocation invocation) {\n      logger.trace(\">> converting %s\", commandName);\n      HttpRequest request = annotationProcessor.apply(invocation);\n      logger.trace(\"<< converted %s to %s\", commandName, request.getRequestLine());\n      return new HttpCommand(request);\n   }\n\n   private Function<HttpResponse, ?> getTransformer(String commandName, HttpCommand command) {\n      HttpRequest request = command.getCurrentRequest();\n      Function<HttpResponse, ?> transformer = transformerForRequest.apply(request);\n      logger.trace(\"<< response from %s is parsed by %s\", commandName, transformer.getClass().getSimpleName());\n      return transformer;\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o)\n         return true;\n      if (o == null || getClass() != o.getClass())\n         return false;\n      InvokeHttpMethod that = InvokeHttpMethod.class.cast(o);\n      return equal(this.annotationProcessor, that.annotationProcessor);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(annotationProcessor);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(\"\").omitNullValues().add(\"annotationParser\", annotationProcessor).toString();\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/internal/RestAnnotationProcessor.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.internal;\n\nimport static com.google.common.base.Functions.toStringFunction;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.common.base.Predicates.instanceOf;\nimport static com.google.common.collect.Collections2.filter;\nimport static com.google.common.collect.Iterables.concat;\nimport static com.google.common.collect.Iterables.get;\nimport static com.google.common.collect.Iterables.transform;\nimport static com.google.common.collect.Iterables.tryFind;\nimport static com.google.common.collect.Lists.newArrayList;\nimport static com.google.common.collect.Lists.newLinkedList;\nimport static com.google.common.collect.Multimaps.transformValues;\nimport static com.google.common.net.HttpHeaders.ACCEPT;\nimport static com.google.common.net.HttpHeaders.CONTENT_TYPE;\nimport static com.google.common.net.HttpHeaders.HOST;\nimport static java.lang.String.format;\nimport static java.util.Arrays.asList;\nimport static org.jclouds.http.HttpUtils.filterOutContentHeaders;\nimport static org.jclouds.http.HttpUtils.tryFindHttpMethod;\nimport static org.jclouds.http.Uris.uriBuilder;\nimport static org.jclouds.io.Payloads.newPayload;\nimport static org.jclouds.reflect.Reflection2.getInvokableParameters;\nimport static org.jclouds.util.Strings2.replaceTokens;\nimport static org.jclouds.util.Strings2.urlEncode;\n\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.Array;\nimport java.net.URI;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.NoSuchElementException;\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Encoded;\nimport jakarta.ws.rs.FormParam;\nimport jakarta.ws.rs.HeaderParam;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.QueryParam;\n\nimport org.jclouds.Constants;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpRequestFilter;\nimport org.jclouds.http.HttpUtils;\nimport org.jclouds.http.Uris.UriBuilder;\nimport org.jclouds.http.filters.ConnectionCloseHeader;\nimport org.jclouds.http.filters.StripExpectHeader;\nimport org.jclouds.http.options.HttpRequestOptions;\nimport org.jclouds.http.utils.QueryValue;\nimport org.jclouds.io.ContentMetadataCodec;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.PayloadEnclosing;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.io.payloads.MultipartForm;\nimport org.jclouds.io.payloads.Part;\nimport org.jclouds.io.payloads.Part.PartOptions;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.location.Provider;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.reflect.Invocation;\nimport org.jclouds.rest.Binder;\nimport org.jclouds.rest.InputParamValidator;\nimport org.jclouds.rest.annotations.ApiVersion;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.BuildVersion;\nimport org.jclouds.rest.annotations.Endpoint;\nimport org.jclouds.rest.annotations.EndpointParam;\nimport org.jclouds.rest.annotations.FormParams;\nimport org.jclouds.rest.annotations.Headers;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.OverrideRequestFilters;\nimport org.jclouds.rest.annotations.ParamParser;\nimport org.jclouds.rest.annotations.PartParam;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.PayloadParams;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SkipEncoding;\nimport org.jclouds.rest.annotations.VirtualHost;\nimport org.jclouds.rest.annotations.WrapWith;\nimport org.jclouds.rest.binders.BindMapToStringPayload;\nimport org.jclouds.rest.binders.BindToJsonPayloadWrappedWith;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Function;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\nimport com.google.common.collect.LinkedHashMultimap;\nimport com.google.common.collect.LinkedListMultimap;\nimport com.google.common.collect.Maps;\nimport com.google.common.collect.Multimap;\nimport com.google.common.primitives.Chars;\nimport com.google.common.reflect.Invokable;\nimport com.google.common.reflect.Parameter;\nimport com.google.inject.Inject;\nimport com.google.inject.Injector;\nimport com.google.inject.Key;\nimport com.google.inject.TypeLiteral;\n\npublic class RestAnnotationProcessor implements Function<Invocation, HttpRequest> {\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   private static final Function<? super Entry<String, Object>, ? extends Part> ENTRY_TO_PART = new Function<Entry<String, Object>, Part>() {\n      @Override\n      public Part apply(Entry<String, Object> from) {\n         return Part.create(from.getKey(), from.getValue().toString());\n      }\n   };\n\n   private final Injector injector;\n   private final HttpUtils utils;\n   private final ContentMetadataCodec contentMetadataCodec;\n   private final Supplier<Credentials> credentials;\n   private final String apiVersion;\n   private final String buildVersion;\n   private final InputParamValidator inputParamValidator;\n   private final GetAcceptHeaders getAcceptHeaders;\n   private final Invocation caller;\n   private final boolean stripExpectHeader;\n   private final boolean connectionCloseHeader;\n\n   @Inject\n   private RestAnnotationProcessor(Injector injector,\n         @Provider Supplier<Credentials> credentials, @ApiVersion String apiVersion, @BuildVersion String buildVersion,\n         HttpUtils utils, ContentMetadataCodec contentMetadataCodec, InputParamValidator inputParamValidator,\n         GetAcceptHeaders getAcceptHeaders, @Nullable @Named(\"caller\") Invocation caller,\n         @Named(Constants.PROPERTY_STRIP_EXPECT_HEADER) boolean stripExpectHeader,\n         @Named(Constants.PROPERTY_CONNECTION_CLOSE_HEADER) boolean connectionCloseHeader) {\n      this.injector = injector;\n      this.utils = utils;\n      this.contentMetadataCodec = contentMetadataCodec;\n      this.credentials = credentials;\n      this.apiVersion = apiVersion;\n      this.buildVersion = buildVersion;\n      this.inputParamValidator = inputParamValidator;\n      this.getAcceptHeaders = getAcceptHeaders;\n      this.caller = caller;\n      this.stripExpectHeader = stripExpectHeader;\n      this.connectionCloseHeader = connectionCloseHeader;\n   }\n\n   /**\n    * Note this is dangerous as it cannot pass the inheriting class! Using this\n    * when subclassing interfaces may result in lost data.\n    */\n   @Deprecated\n   public GeneratedHttpRequest createRequest(Invokable<?, ?> invokable, List<Object> args) {\n      return apply(Invocation.create(invokable, args));\n   }\n\n   @Override\n   public GeneratedHttpRequest apply(Invocation invocation) {\n      checkNotNull(invocation, \"invocation\");\n      inputParamValidator.validateMethodParametersOrThrow(invocation, getInvokableParameters(invocation.getInvokable()));\n\n      Optional<URI> endpoint = Optional.absent();\n      HttpRequest r = findOrNull(invocation.getArgs(), HttpRequest.class);\n      if (r != null) {\n         endpoint = Optional.fromNullable(r.getEndpoint());\n         if (endpoint.isPresent())\n            logger.trace(\"using endpoint %s from invocation.getArgs() for %s\", endpoint, invocation);\n      } else {\n         // If there is no explicit HttpRequest parameter, try to find the endpoint. When using\n         // delegate apis, the endpoint defined in the callee takes precedence\n         endpoint = getEndpointFor(invocation);\n         if (!endpoint.isPresent()) {\n            if (caller != null) {\n               endpoint = getEndpointFor(caller);\n               if (endpoint.isPresent())\n                  logger.trace(\"using endpoint %s from caller %s for %s\", endpoint, caller, invocation);\n               else\n                  endpoint = findEndpoint(invocation);\n            } else {\n               endpoint = findEndpoint(invocation);\n            }\n         }\n      }\n\n      if (!endpoint.isPresent())\n         throw new NoSuchElementException(format(\"no endpoint found for %s\", invocation));\n      GeneratedHttpRequest.Builder requestBuilder = GeneratedHttpRequest.builder().invocation(invocation)\n            .caller(caller);\n      String requestMethod = null;\n      if (r != null) {\n         requestMethod = r.getMethod();\n         requestBuilder.fromHttpRequest(r);\n      } else {\n         requestMethod = tryFindHttpMethod(invocation.getInvokable()).get();\n         requestBuilder.method(requestMethod);\n      }\n\n      requestBuilder.filters(getFiltersIfAnnotated(invocation));\n      if (stripExpectHeader) {\n         requestBuilder.filter(new StripExpectHeader());\n      }\n      if (connectionCloseHeader) {\n         requestBuilder.filter(new ConnectionCloseHeader());\n      }\n\n      Multimap<String, Object> tokenValues = LinkedHashMultimap.create();\n\n      tokenValues.put(Constants.PROPERTY_IDENTITY, credentials.get().identity);\n      tokenValues.put(Constants.PROPERTY_API_VERSION, apiVersion);\n      tokenValues.put(Constants.PROPERTY_BUILD_VERSION, buildVersion);\n      // URI template in rfc6570 form\n      UriBuilder uriBuilder = uriBuilder(endpoint.get().toString());\n\n      overridePathEncoding(uriBuilder, invocation);\n\n      boolean encodeFullPath = !isEncodedUsed(invocation);\n      if (caller != null)\n         tokenValues.putAll(addPathAndGetTokens(caller, uriBuilder, encodeFullPath));\n      tokenValues.putAll(addPathAndGetTokens(invocation, uriBuilder, encodeFullPath));\n      Multimap<String, Object> formParams;\n      if (caller != null) {\n         formParams = addFormParams(tokenValues, caller);\n         formParams.putAll(addFormParams(tokenValues, invocation));\n      } else {\n         formParams = addFormParams(tokenValues, invocation);\n      }\n\n      Multimap<String, Object> queryParams = addQueryParams(tokenValues, invocation);\n\n      Multimap<String, String> headers;\n      if (caller != null) {\n         headers = buildHeaders(tokenValues, caller);\n         headers.putAll(buildHeaders(tokenValues, invocation));\n      } else {\n         headers = buildHeaders(tokenValues, invocation);\n      }\n\n      if (r != null)\n         headers.putAll(r.getHeaders());\n\n      if (shouldAddHostHeader(invocation)) {\n         StringBuilder hostHeader = new StringBuilder(endpoint.get().getHost());\n         if (endpoint.get().getPort() != -1)\n            hostHeader.append(\":\").append(endpoint.get().getPort());\n         headers.put(HOST, hostHeader.toString());\n      }\n\n      Payload payload = null;\n      for (HttpRequestOptions options : findOptionsIn(invocation)) {\n         injector.injectMembers(options);  // TODO test case\n         for (Entry<String, String> header : options.buildRequestHeaders().entries()) {\n            headers.put(header.getKey(), replaceTokens(header.getValue(), tokenValues));\n         }\n         for (Entry<String, String> query : options.buildQueryParameters().entries()) {\n            queryParams.put(urlEncode(query.getKey(), '/', ','),\n                  new QueryValue(replaceTokens(query.getValue(), tokenValues), false));\n         }\n         for (Entry<String, String> form : options.buildFormParameters().entries()) {\n            formParams.put(form.getKey(), replaceTokens(form.getValue(), tokenValues));\n         }\n\n         String pathSuffix = options.buildPathSuffix();\n         if (pathSuffix != null) {\n            uriBuilder.appendPath(pathSuffix);\n         }\n         String stringPayload = options.buildStringPayload();\n         if (stringPayload != null)\n            payload = Payloads.newStringPayload(stringPayload);\n      }\n\n      if (!queryParams.isEmpty()) {\n         uriBuilder.query(queryParams);\n      }\n\n      requestBuilder.headers(filterOutContentHeaders(headers));\n\n      // Query parameter encoding is handled in the annotation processor\n      requestBuilder.endpoint(uriBuilder.build(convertUnsafe(tokenValues), /*encodePath=*/encodeFullPath));\n\n      if (payload == null) {\n         PayloadEnclosing payloadEnclosing = findOrNull(invocation.getArgs(), PayloadEnclosing.class);\n         payload = (payloadEnclosing != null) ? payloadEnclosing.getPayload() : findOrNull(invocation.getArgs(),\n               Payload.class);\n      }\n\n      List<? extends Part> parts = getParts(invocation, ImmutableMultimap.<String, Object> builder()\n            .putAll(tokenValues).putAll(formParams).build());\n\n      if (!parts.isEmpty()) {\n         if (!formParams.isEmpty()) {\n            parts = newLinkedList(concat(transform(formParams.entries(), ENTRY_TO_PART), parts));\n         }\n         payload = new MultipartForm(MultipartForm.BOUNDARY, parts);\n      } else if (!formParams.isEmpty()) {\n         payload = Payloads.newUrlEncodedFormPayload(transformValues(formParams, NullableToStringFunction.INSTANCE));\n      } else if (headers.containsKey(CONTENT_TYPE) && !HttpRequest.NON_PAYLOAD_METHODS.contains(requestMethod)) {\n         if (payload == null)\n            payload = Payloads.newByteArrayPayload(new byte[] {});\n         payload.getContentMetadata().setContentType(get(headers.get(CONTENT_TYPE), 0));\n      }\n      if (payload != null) {\n         requestBuilder.payload(payload);\n      }\n      GeneratedHttpRequest request = requestBuilder.build();\n\n      org.jclouds.rest.MapBinder mapBinder = getMapPayloadBinderOrNull(invocation);\n      if (mapBinder != null) {\n         Map<String, Object> mapParams;\n         if (caller != null) {\n            mapParams = buildPayloadParams(caller);\n            mapParams.putAll(buildPayloadParams(invocation));\n         } else {\n            mapParams = buildPayloadParams(invocation);\n         }\n         if (invocation.getInvokable().isAnnotationPresent(PayloadParams.class)) {\n            PayloadParams params = invocation.getInvokable().getAnnotation(PayloadParams.class);\n            addMapPayload(mapParams, params, headers, tokenValues);\n         }\n         request = mapBinder.bindToRequest(request, mapParams);\n      } else {\n         request = decorateRequest(request);\n      }\n\n      if (request.getPayload() != null) {\n         contentMetadataCodec.fromHeaders(request.getPayload().getContentMetadata(), headers);\n      }\n\n      request = stripExpectHeaderIfContentZero(request);\n\n      utils.checkRequestHasRequiredProperties(request);\n      return request;\n   }\n\n   private static <T> T findOrNull(Iterable<Object> args, Class<T> clazz) {\n      return clazz.cast(tryFind(args, instanceOf(clazz)).orNull());\n   }\n\n   private static <K, V> Map<K, V> convertUnsafe(Multimap<K, V> in) {\n      LinkedHashMap<K, V> out = Maps.newLinkedHashMap();\n      for (Entry<K, V> entry : in.entries()) {\n         out.put(entry.getKey(), entry.getValue());\n      }\n      return ImmutableMap.copyOf(out);\n   }\n\n   private void overridePathEncoding(UriBuilder uriBuilder, Invocation invocation) {\n      if (invocation.getInvokable().getOwnerType().getRawType().isAnnotationPresent(SkipEncoding.class)) {\n         uriBuilder.skipPathEncoding(Chars.asList(invocation.getInvokable().getOwnerType().getRawType()\n               .getAnnotation(SkipEncoding.class).value()));\n      }\n      if (invocation.getInvokable().isAnnotationPresent(SkipEncoding.class)) {\n         uriBuilder.skipPathEncoding(Chars.asList(invocation.getInvokable().getAnnotation(SkipEncoding.class).value()));\n      }\n   }\n\n   // different than guava as accepts null\n   private static enum NullableToStringFunction implements Function<Object, String> {\n      INSTANCE;\n      @Override\n      public String apply(Object o) {\n         if (o == null)\n            return null;\n         return o.toString();\n      }\n   }\n\n   protected Optional<URI> findEndpoint(Invocation invocation) {\n      Optional<URI> endpoint = getEndpointFor(invocation);\n      if (endpoint.isPresent())\n         logger.trace(\"using endpoint %s for %s\", endpoint, invocation);\n      if (!endpoint.isPresent()) {\n         logger.trace(\"looking up default endpoint for %s\", invocation);\n         endpoint = Optional.fromNullable(injector.getInstance(\n               Key.get(uriSupplierLiteral, org.jclouds.location.Provider.class)).get());\n         if (endpoint.isPresent())\n            logger.trace(\"using default endpoint %s for %s\", endpoint, invocation);\n      }\n      return endpoint;\n   }\n\n   private Multimap<String, Object> addPathAndGetTokens(Invocation invocation, UriBuilder uriBuilder,\n                                                        boolean encodeFullPath) {\n      if (invocation.getInvokable().getOwnerType().getRawType().isAnnotationPresent(Path.class))\n         uriBuilder.appendPath(invocation.getInvokable().getOwnerType().getRawType().getAnnotation(Path.class).value());\n      if (invocation.getInvokable().isAnnotationPresent(Path.class))\n         uriBuilder.appendPath(invocation.getInvokable().getAnnotation(Path.class).value());\n      return getPathParamKeyValues(invocation, encodeFullPath);\n   }\n\n   private Multimap<String, Object> addFormParams(Multimap<String, ?> tokenValues, Invocation invocation) {\n      Multimap<String, Object> formMap = LinkedListMultimap.create();\n      if (invocation.getInvokable().getOwnerType().getRawType().isAnnotationPresent(FormParams.class)) {\n         FormParams form = invocation.getInvokable().getOwnerType().getRawType().getAnnotation(FormParams.class);\n         addForm(formMap, form, tokenValues);\n      }\n\n      if (invocation.getInvokable().isAnnotationPresent(FormParams.class)) {\n         FormParams form = invocation.getInvokable().getAnnotation(FormParams.class);\n         addForm(formMap, form, tokenValues);\n      }\n\n      for (Entry<String, Object> form : getFormParamKeyValues(invocation).entries()) {\n         formMap.put(form.getKey(), replaceTokens(form.getValue().toString(), tokenValues));\n      }\n      return formMap;\n   }\n\n   private Multimap<String, Object> addQueryParams(Multimap<String, ?> tokenValues, Invocation invocation) {\n      Multimap<String, Object> queryMap = LinkedListMultimap.create();\n      if (invocation.getInvokable().getOwnerType().getRawType().isAnnotationPresent(QueryParams.class)) {\n         QueryParams query = invocation.getInvokable().getOwnerType().getRawType().getAnnotation(QueryParams.class);\n         addQuery(queryMap, query, tokenValues);\n      }\n\n      if (invocation.getInvokable().isAnnotationPresent(QueryParams.class)) {\n         QueryParams query = invocation.getInvokable().getAnnotation(QueryParams.class);\n         addQuery(queryMap, query, tokenValues);\n      }\n\n      for (Entry<String, Object> query : getQueryParamKeyValues(invocation, tokenValues).entries()) {\n         queryMap.put(query.getKey(), query.getValue());\n      }\n      return queryMap;\n   }\n\n   private void addForm(Multimap<String, Object> formParams, FormParams form, Multimap<String, ?> tokenValues) {\n      for (int i = 0; i < form.keys().length; i++) {\n         if (form.values()[i].equals(FormParams.NULL)) {\n            formParams.removeAll(form.keys()[i]);\n            formParams.put(form.keys()[i], null);\n         } else {\n            formParams.put(form.keys()[i], replaceTokens(form.values()[i], tokenValues));\n         }\n      }\n   }\n\n   private void addQuery(Multimap<String, Object> queryParams, QueryParams query, Multimap<String, ?> tokenValues) {\n      for (int i = 0; i < query.keys().length; i++) {\n         String key = urlEncode(query.keys()[i], '/', ',');\n         if (query.values()[i].equals(QueryParams.NULL)) {\n            queryParams.removeAll(key);\n            queryParams.put(key, null);\n         } else {\n            queryParams.put(key, new QueryValue(replaceTokens(query.values()[i], tokenValues), false));\n         }\n      }\n   }\n\n   private void addMapPayload(Map<String, Object> postParams, PayloadParams mapDefaults,\n         Multimap<String, String> headers, Multimap<String, Object> tokenValues) {\n      for (int i = 0; i < mapDefaults.keys().length; i++) {\n         if (mapDefaults.values()[i].equals(PayloadParams.NULL)) {\n            postParams.put(mapDefaults.keys()[i], null);\n         } else {\n            postParams.put(mapDefaults.keys()[i], replaceTokens(replaceTokens(mapDefaults.values()[i], headers), tokenValues));\n         }\n      }\n   }\n\n   private List<HttpRequestFilter> getFiltersIfAnnotated(Invocation invocation) {\n      List<HttpRequestFilter> filters = newArrayList();\n      if (invocation.getInvokable().getOwnerType().getRawType().isAnnotationPresent(RequestFilters.class)) {\n         for (Class<? extends HttpRequestFilter> clazz : invocation.getInvokable().getOwnerType().getRawType()\n               .getAnnotation(RequestFilters.class).value()) {\n            HttpRequestFilter instance = injector.getInstance(clazz);\n            filters.add(instance);\n            logger.trace(\"adding filter %s from annotation on %s\", instance, invocation.getInvokable().getOwnerType()\n                  .getRawType().getName());\n         }\n      }\n      if (invocation.getInvokable().isAnnotationPresent(RequestFilters.class)) {\n         if (invocation.getInvokable().isAnnotationPresent(OverrideRequestFilters.class))\n            filters.clear();\n         for (Class<? extends HttpRequestFilter> clazz : invocation.getInvokable().getAnnotation(RequestFilters.class)\n               .value()) {\n            HttpRequestFilter instance = injector.getInstance(clazz);\n            filters.add(instance);\n            logger.trace(\"adding filter %s from annotation on %s\", instance, invocation.getInvokable().getName());\n         }\n      }\n      return filters;\n   }\n\n   @VisibleForTesting\n   static URI getEndpointInParametersOrNull(Invocation invocation, Injector injector) {\n      Collection<Parameter> endpointParams = parametersWithAnnotation(invocation.getInvokable(), EndpointParam.class);\n      if (endpointParams.isEmpty())\n         return null;\n      checkState(endpointParams.size() == 1, \"invocation.getInvoked() %s has too many EndpointParam annotations\",\n            invocation.getInvokable());\n      Parameter endpointParam = get(endpointParams, 0);\n      Function<Object, URI> parser = injector.getInstance(endpointParam.getAnnotation(EndpointParam.class).parser());\n      int position = endpointParam.hashCode();  // guava issue 1243\n      try {\n         URI returnVal = parser.apply(invocation.getArgs().get(position));\n         checkArgument(returnVal != null,\n               \"endpoint for [%s] not configured for %s\", position, invocation.getInvokable());\n         return returnVal;\n      } catch (NullPointerException e) {\n         throw new IllegalArgumentException(format(\"argument at index %d on invocation.getInvoked() %s was null\",\n               position, invocation.getInvokable()), e);\n      }\n   }\n\n   private static Collection<Parameter> parametersWithAnnotation(Invokable<?, ?> invokable,\n         final Class<? extends Annotation> annotationType) {\n      return filter(getInvokableParameters(invokable), new Predicate<Parameter>() {\n         public boolean apply(Parameter in) {\n            return in.isAnnotationPresent(annotationType);\n         }\n      });\n   }\n\n   private static final TypeLiteral<Supplier<URI>> uriSupplierLiteral = new TypeLiteral<Supplier<URI>>() {\n   };\n\n   protected Optional<URI> getEndpointFor(Invocation invocation) {\n      URI endpoint = getEndpointInParametersOrNull(invocation, injector);\n      if (endpoint == null) {\n         Endpoint annotation;\n         if (invocation.getInvokable().isAnnotationPresent(Endpoint.class)) {\n            annotation = invocation.getInvokable().getAnnotation(Endpoint.class);\n         } else if (invocation.getInvokable().getOwnerType().getRawType().isAnnotationPresent(Endpoint.class)) {\n            annotation = invocation.getInvokable().getOwnerType().getRawType().getAnnotation(Endpoint.class);\n         } else {\n            logger.trace(\"no annotations on class or invocation.getInvoked(): %s\", invocation.getInvokable());\n            return Optional.absent();\n         }\n         endpoint = injector.getInstance(Key.get(uriSupplierLiteral, annotation.value())).get();\n      }\n      URI provider = injector.getInstance(Key.get(uriSupplierLiteral, org.jclouds.location.Provider.class)).get();\n      return Optional.fromNullable(addHostIfMissing(endpoint, provider));\n   }\n\n   @VisibleForTesting\n   static URI addHostIfMissing(URI original, URI withHost) {\n      checkNotNull(withHost, \"URI withHost cannot be null\");\n      checkArgument(withHost.getHost() != null, \"URI withHost must have host:\" + withHost);\n      if (original == null)\n         return null;\n      if (original.getHost() != null)\n         return original;\n      String host = withHost.toString();\n      URI baseURI = host.endsWith(\"/\") ? withHost : URI.create(host + \"/\");\n      return baseURI.resolve(original);\n   }\n\n   private org.jclouds.rest.MapBinder getMapPayloadBinderOrNull(Invocation invocation) {\n      if (invocation.getArgs() != null) {\n         for (Object arg : invocation.getArgs()) {\n            if (arg instanceof Object[]) {\n               Object[] postBinders = (Object[]) arg;\n               if (postBinders.length == 0) {\n               } else if (postBinders.length == 1) {\n                  if (postBinders[0] instanceof org.jclouds.rest.MapBinder) {\n                     org.jclouds.rest.MapBinder binder = (org.jclouds.rest.MapBinder) postBinders[0];\n                     injector.injectMembers(binder);\n                     return binder;\n                  }\n               } else {\n                  if (postBinders[0] instanceof org.jclouds.rest.MapBinder) {\n                     throw new IllegalArgumentException(\n                           \"we currently do not support multiple varinvocation.getArgs() postBinders in: \"\n                                 + invocation.getInvokable().getName());\n                  }\n               }\n            } else if (arg instanceof org.jclouds.rest.MapBinder) {\n               org.jclouds.rest.MapBinder binder = (org.jclouds.rest.MapBinder) arg;\n               injector.injectMembers(binder);\n               return binder;\n            }\n         }\n      }\n      if (invocation.getInvokable().isAnnotationPresent(MapBinder.class)) {\n         return injector.getInstance(invocation.getInvokable().getAnnotation(MapBinder.class).value());\n      } else if (invocation.getInvokable().isAnnotationPresent(org.jclouds.rest.annotations.Payload.class)) {\n         return injector.getInstance(BindMapToStringPayload.class);\n      } else if (invocation.getInvokable().isAnnotationPresent(WrapWith.class)) {\n         return injector.getInstance(BindToJsonPayloadWrappedWith.Factory.class).create(\n               invocation.getInvokable().getAnnotation(WrapWith.class).value());\n      }\n      return null;\n   }\n\n   private boolean shouldAddHostHeader(Invocation invocation) {\n      return invocation.getInvokable().getOwnerType().getRawType().isAnnotationPresent(VirtualHost.class) || invocation\n            .getInvokable().isAnnotationPresent(VirtualHost.class);\n   }\n\n   private GeneratedHttpRequest decorateRequest(GeneratedHttpRequest request) throws NegativeArraySizeException {\n      Invocation invocation = request.getInvocation();\n      List<Object> args = request.getInvocation().getArgs();\n      Set<Parameter> binderOrWrapWith = ImmutableSet.copyOf(concat(\n            parametersWithAnnotation(invocation.getInvokable(), BinderParam.class),\n            parametersWithAnnotation(invocation.getInvokable(), WrapWith.class)));\n      OUTER: for (Parameter entry : binderOrWrapWith) {\n         int position = entry.hashCode();\n         boolean shouldBreak = false;\n         Binder binder;\n         if (entry.isAnnotationPresent(BinderParam.class))\n            binder = injector.getInstance(entry.getAnnotation(BinderParam.class).value());\n         else\n            binder = injector.getInstance(BindToJsonPayloadWrappedWith.Factory.class).create(\n                  entry.getAnnotation(WrapWith.class).value());\n         Object arg = args.size() >= position + 1 ? args.get(position) : null;\n         if (args.size() >= position + 1 && arg != null) {\n            Class<?> parameterType = entry.getType().getRawType();\n            Class<? extends Object> argType = arg.getClass();\n            if (!argType.isArray() && parameterType.isArray()) {// TODO: &&\n                                                                // invocation.getInvokable().isVarArgs())\n                                                                // {\n               int arrayLength = args.size() - getInvokableParameters(invocation.getInvokable()).size() + 1;\n               if (arrayLength == 0)\n                  break OUTER;\n               arg = (Object[]) Array.newInstance(arg.getClass(), arrayLength);\n               System.arraycopy(args.toArray(), position, arg, 0, arrayLength);\n               shouldBreak = true;\n            } else if (argType.isArray() && parameterType.isArray()) {// TODO:\n                                                                      // &&\n                                                                      // invocation.getInvokable().isVarArgs())\n                                                                      // {\n            } else {\n               if (arg.getClass().isArray()) {\n                  Object[] payloadArray = (Object[]) arg;\n                  arg = payloadArray.length > 0 ? payloadArray[0] : null;\n               }\n            }\n            if (arg != null) {\n               request = binder.bindToRequest(request, arg);\n            }\n            if (shouldBreak)\n               break OUTER;\n         } else {\n            if (position + 1 == getInvokableParameters(invocation.getInvokable()).size() && entry.getType().isArray())// TODO:\n                                                                                                              // &&\n                                                                                                              // invocation.getInvokable().isVarArgs())\n               continue OUTER;\n\n            if (entry.isAnnotationPresent(Nullable.class)) {\n               continue OUTER;\n            }\n            checkNotNull(arg, invocation.getInvokable().getName() + \" parameter \" + (position + 1));\n         }\n      }\n      return request;\n   }\n\n   private static final LoadingCache<Invokable<?, ?>, Set<Integer>> invokableToIndexesOfOptions = CacheBuilder\n         .newBuilder().build(new CacheLoader<Invokable<?, ?>, Set<Integer>>() {\n            @Override\n            public Set<Integer> load(Invokable<?, ?> invokable) {\n               Builder<Integer> toReturn = ImmutableSet.builder();\n               for (Parameter param : getInvokableParameters(invokable)) {\n                  Class<?> type = param.getType().getRawType();\n                  if (HttpRequestOptions.class.isAssignableFrom(type)\n                        || HttpRequestOptions[].class.isAssignableFrom(type))\n                     toReturn.add(param.hashCode());\n               }\n               return toReturn.build();\n            }\n         });\n\n   private Set<HttpRequestOptions> findOptionsIn(Invocation invocation) {\n      ImmutableSet.Builder<HttpRequestOptions> result = ImmutableSet.builder();\n      for (int index : invokableToIndexesOfOptions.getUnchecked(invocation.getInvokable())) {\n         if (invocation.getArgs().size() >= index + 1) {// accommodate\n                                                        // varinvocation.getArgs()\n            if (invocation.getArgs().get(index) instanceof Object[]) {\n               for (Object option : (Object[]) invocation.getArgs().get(index)) {\n                  if (option instanceof HttpRequestOptions) {\n                     result.add((HttpRequestOptions) option);\n                  }\n               }\n            } else {\n               for (; index < invocation.getArgs().size(); index++) {\n                  if (invocation.getArgs().get(index) instanceof HttpRequestOptions) {\n                     result.add((HttpRequestOptions) invocation.getArgs().get(index));\n                  }\n               }\n            }\n         }\n      }\n      return result.build();\n   }\n\n   private Multimap<String, String> buildHeaders(Multimap<String, ?> tokenValues, Invocation invocation) {\n      Multimap<String, String> headers = LinkedHashMultimap.create();\n      addHeaderIfAnnotationPresentOnMethod(headers, invocation, tokenValues);\n      for (Parameter headerParam : parametersWithAnnotation(invocation.getInvokable(), HeaderParam.class)) {\n         Annotation key = headerParam.getAnnotation(HeaderParam.class);\n         String value = invocation.getArgs().get(headerParam.hashCode()).toString();\n         value = replaceTokens(value, tokenValues);\n         headers.put(((HeaderParam) key).value(), value);\n      }\n      addProducesIfPresentOnTypeOrMethod(headers, invocation);\n      addConsumesIfPresentOnTypeOrMethod(headers, invocation);\n      return headers;\n   }\n\n   private void addConsumesIfPresentOnTypeOrMethod(Multimap<String, String> headers, Invocation invocation) {\n      Set<String> accept = getAcceptHeaders.apply(invocation);\n      if (!accept.isEmpty())\n         headers.replaceValues(ACCEPT, accept);\n   }\n\n   private void addProducesIfPresentOnTypeOrMethod(Multimap<String, String> headers, Invocation invocation) {\n      if (invocation.getInvokable().getOwnerType().getRawType().isAnnotationPresent(Produces.class)) {\n         Produces header = invocation.getInvokable().getOwnerType().getRawType().getAnnotation(Produces.class);\n         headers.replaceValues(CONTENT_TYPE, asList(header.value()));\n      }\n      if (invocation.getInvokable().isAnnotationPresent(Produces.class)) {\n         Produces header = invocation.getInvokable().getAnnotation(Produces.class);\n         headers.replaceValues(CONTENT_TYPE, asList(header.value()));\n      }\n   }\n\n   private void addHeaderIfAnnotationPresentOnMethod(Multimap<String, String> headers, Invocation invocation,\n         Multimap<String, ?> tokenValues) {\n      if (invocation.getInvokable().getOwnerType().getRawType().isAnnotationPresent(Headers.class)) {\n         Headers header = invocation.getInvokable().getOwnerType().getRawType().getAnnotation(Headers.class);\n         addHeader(headers, header, tokenValues);\n      }\n      if (invocation.getInvokable().isAnnotationPresent(Headers.class)) {\n         Headers header = invocation.getInvokable().getAnnotation(Headers.class);\n         addHeader(headers, header, tokenValues);\n      }\n   }\n\n   private static void addHeader(Multimap<String, String> headers, Headers header, Multimap<String, ?> tokenValues) {\n      for (int i = 0; i < header.keys().length; i++) {\n         String value = header.values()[i];\n         value = replaceTokens(value, tokenValues);\n         // urlEncode may have less entries than keys e.g. default value of {}\n         if (i < header.urlEncode().length && header.urlEncode()[i])\n            value = urlEncode(value, '/');\n         headers.put(header.keys()[i], value);\n      }\n   }\n\n   private static List<Part> getParts(Invocation invocation, Multimap<String, ?> tokenValues) {\n      ImmutableList.Builder<Part> parts = ImmutableList.<Part> builder();\n      for (Parameter param : parametersWithAnnotation(invocation.getInvokable(), PartParam.class)) {\n         PartParam partParam = param.getAnnotation(PartParam.class);\n         PartOptions options = new PartOptions();\n         if (!PartParam.NO_CONTENT_TYPE.equals(partParam.contentType()))\n            options.contentType(partParam.contentType());\n         if (!PartParam.NO_FILENAME.equals(partParam.filename()))\n            options.filename(replaceTokens(partParam.filename(), tokenValues));\n         Object arg = invocation.getArgs().get(param.hashCode());\n         checkNotNull(arg, partParam.name());\n         Part part = Part.create(partParam.name(), newPayload(arg), options);\n         parts.add(part);\n      }\n      return parts.build();\n   }\n\n   private static GeneratedHttpRequest stripExpectHeaderIfContentZero(GeneratedHttpRequest request) {\n      boolean isBodyEmpty = true;\n      if (request.getPayload() != null) {\n         Long length = request.getPayload().getContentMetadata().getContentLength();\n         isBodyEmpty = length != null && length == 0;\n      }\n      if (isBodyEmpty) {\n         request = request.toBuilder().removeHeader(\"Expect\").build();\n      }\n      return request;\n   }\n\n   private boolean isEncodedUsed(Invocation invocation) {\n      return !parametersWithAnnotation(invocation.getInvokable(), Encoded.class).isEmpty();\n   }\n\n   private Multimap<String, Object> getPathParamKeyValues(Invocation invocation, boolean encodeFullPath) {\n      Multimap<String, Object> pathParamValues = LinkedHashMultimap.create();\n      for (Parameter param : parametersWithAnnotation(invocation.getInvokable(), PathParam.class)) {\n         PathParam pathParam = param.getAnnotation(PathParam.class);\n         String paramKey = pathParam.value();\n         Optional<?> paramValue = getParamValue(invocation, param.getAnnotation(ParamParser.class), param.hashCode(),\n               paramKey);\n         if (paramValue.isPresent()) {\n            if (!encodeFullPath && !param.isAnnotationPresent(Encoded.class)) {\n               pathParamValues.put(paramKey, urlEncode(paramValue.get().toString()));\n            } else {\n               pathParamValues.put(paramKey, paramValue.get().toString());\n            }\n         }\n      }\n      return pathParamValues;\n   }\n\n   private Optional<?> getParamValue(Invocation invocation, @Nullable ParamParser extractor, int argIndex,\n         String paramKey) {\n      Object arg = invocation.getArgs().get(argIndex);\n      if (extractor != null && checkPresentOrNullable(invocation, paramKey, argIndex, arg)) {\n         // ParamParsers can deal with nullable parameters\n         arg = injector.getInstance(extractor.value()).apply(arg);\n      }\n      checkPresentOrNullable(invocation, paramKey, argIndex, arg);\n      return Optional.fromNullable(arg);\n   }\n\n   private boolean checkPresentOrNullable(Invocation invocation, String paramKey, int argIndex, Object arg) {\n      if (arg == null && !getInvokableParameters(invocation.getInvokable()).get(argIndex).isAnnotationPresent(Nullable.class))\n         throw new NullPointerException(format(\"param{%s} for invocation %s.%s\", paramKey, invocation.getInvokable()\n               .getOwnerType().getRawType().getSimpleName(), invocation.getInvokable().getName()));\n      return true;\n   }\n\n   private Multimap<String, Object> getFormParamKeyValues(Invocation invocation) {\n      Multimap<String, Object> formParamValues = LinkedHashMultimap.create();\n      for (Parameter param : parametersWithAnnotation(invocation.getInvokable(), FormParam.class)) {\n         FormParam formParam = param.getAnnotation(FormParam.class);\n         String paramKey = formParam.value();\n         Optional<?> paramValue = getParamValue(invocation, param.getAnnotation(ParamParser.class), param.hashCode(),\n               paramKey);\n         if (paramValue.isPresent())\n            formParamValues.put(paramKey, paramValue.get().toString());\n      }\n      return formParamValues;\n   }\n\n   private Multimap<String, Object> getQueryParamKeyValues(Invocation invocation, Multimap<String, ?> tokenValues) {\n      Multimap<String, Object> queryParamValues = LinkedHashMultimap.create();\n      for (Parameter param : parametersWithAnnotation(invocation.getInvokable(), QueryParam.class)) {\n         QueryParam queryParam = param.getAnnotation(QueryParam.class);\n         String paramKey = urlEncode(queryParam.value(), '/', ',');\n         Optional<?> paramValue = getParamValue(invocation, param.getAnnotation(ParamParser.class), param.hashCode(),\n               paramKey);\n         boolean encoded = param.isAnnotationPresent(Encoded.class);\n         if (paramValue.isPresent())\n            if (paramValue.get() instanceof Iterable) {\n               @SuppressWarnings(\"unchecked\")\n               Iterable<String> iterableStrings = transform(Iterable.class.cast(paramValue.get()), toStringFunction());\n               List<QueryValue> values = new ArrayList<QueryValue>();\n               for (String stringValue : iterableStrings) {\n                  values.add(new QueryValue(replaceTokens(stringValue, tokenValues), encoded));\n               }\n               queryParamValues.putAll(paramKey, values);\n            } else {\n               String value = paramValue.get().toString();\n               queryParamValues.put(paramKey, new QueryValue(replaceTokens(value, tokenValues), encoded));\n            }\n      }\n      return queryParamValues;\n   }\n\n   private Map<String, Object> buildPayloadParams(Invocation invocation) {\n      Map<String, Object> payloadParamValues = Maps.newLinkedHashMap();\n      for (Parameter param : parametersWithAnnotation(invocation.getInvokable(), PayloadParam.class)) {\n         PayloadParam payloadParam = param.getAnnotation(PayloadParam.class);\n         String paramKey = payloadParam.value();\n         Optional<?> paramValue = getParamValue(invocation, param.getAnnotation(ParamParser.class), param.hashCode(),\n               paramKey);\n         if (paramValue.isPresent())\n            payloadParamValues.put(paramKey, paramValue.get());\n      }\n      return payloadParamValues;\n   }\n\n   @Override\n   public String toString() {\n      String callerString = caller != null ? String.format(\"%s.%s%s\", caller.getInvokable().getOwnerType().getRawType().getSimpleName(),\n            caller.getInvokable().getName(), caller.getArgs()) : null;\n      return MoreObjects.toStringHelper(\"\").omitNullValues().add(\"caller\", callerString).toString();\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/internal/TransformerForRequest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.internal;\n\nimport static com.google.inject.util.Types.newParameterizedType;\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_XML;\n\nimport java.io.InputStream;\nimport java.lang.reflect.ParameterizedType;\nimport java.lang.reflect.Type;\nimport java.net.URI;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport javax.lang.model.type.NullType;\n\nimport org.jclouds.functions.IdentityFunction;\nimport org.jclouds.functions.OnlyElementOrNull;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseFirstJsonValueNamed;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.http.functions.ParseSax.Factory;\nimport org.jclouds.http.functions.ParseSax.HandlerWithResult;\nimport org.jclouds.http.functions.ParseURIFromListOrLocationHeaderIf20x;\nimport org.jclouds.http.functions.ParseXMLWithJAXB;\nimport org.jclouds.http.functions.ReleasePayloadAndReturn;\nimport org.jclouds.http.functions.ReturnInputStream;\nimport org.jclouds.http.functions.ReturnStringIf2xx;\nimport org.jclouds.http.functions.ReturnTrueIf2xx;\nimport org.jclouds.http.functions.UnwrapOnlyJsonValue;\nimport org.jclouds.json.internal.GsonWrapper;\nimport org.jclouds.reflect.Invocation;\nimport org.jclouds.rest.InvocationContext;\nimport org.jclouds.rest.annotations.JAXBResponseParser;\nimport org.jclouds.rest.annotations.OnlyElement;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.Transform;\nimport org.jclouds.rest.annotations.Unwrap;\nimport org.jclouds.rest.annotations.XMLResponseParser;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Function;\nimport com.google.common.base.Functions;\nimport com.google.common.base.Optional;\nimport com.google.common.reflect.Invokable;\nimport com.google.common.reflect.TypeToken;\nimport com.google.inject.Injector;\nimport com.google.inject.Key;\nimport com.google.inject.TypeLiteral;\n\npublic class TransformerForRequest implements Function<HttpRequest, Function<HttpResponse, ?>> {\n   private final ParseSax.Factory parserFactory;\n   private final Injector injector;\n   private final GetAcceptHeaders getAcceptHeaders;\n\n   @Inject TransformerForRequest(Injector injector, Factory parserFactory, GetAcceptHeaders getAcceptHeaders) {\n      this.injector = injector;\n      this.parserFactory = parserFactory;\n      this.getAcceptHeaders = getAcceptHeaders;\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public Function<HttpResponse, ?> apply(HttpRequest in) {\n      GeneratedHttpRequest request = GeneratedHttpRequest.class.cast(in);\n      Function<HttpResponse, ?> transformer;\n      Class<? extends HandlerWithResult<?>> handler = getSaxResponseParserClassOrNull(request.getInvocation()\n            .getInvokable());\n      if (handler != null) {\n         HandlerWithResult<?> h = injector.getInstance(handler);\n         transformer = parserFactory.create(h);\n      } else {\n         transformer = getTransformerForMethod(request.getInvocation(), injector);\n      }\n      if (transformer instanceof InvocationContext<?>) {\n         InvocationContext.class.cast(transformer).setContext(request);\n      }\n      if (request.getInvocation().getInvokable().isAnnotationPresent(Transform.class)) {\n         Function<?, ?> wrappingTransformer = injector.getInstance(request.getInvocation().getInvokable()\n               .getAnnotation(Transform.class).value());\n         if (wrappingTransformer instanceof InvocationContext<?>) {\n            ((InvocationContext<?>) wrappingTransformer).setContext(request);\n         }\n         transformer = Functions.compose(Function.class.cast(wrappingTransformer), transformer);\n      }\n      return transformer;\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @VisibleForTesting\n   Key<? extends Function<HttpResponse, ?>> getParserOrThrowException(Invocation invocation) {\n      Invokable<?, ?> invoked = invocation.getInvokable();\n      Set<String> acceptHeaders = getAcceptHeaders.apply(invocation);\n      ResponseParser annotation = invoked.getAnnotation(ResponseParser.class);\n      Class<?> rawReturnType = invoked.getReturnType().getRawType();\n      if (annotation == null) {\n         if (rawReturnType.equals(void.class)) {\n            return Key.get(ReleasePayloadAndReturn.class);\n         } else if (rawReturnType.equals(boolean.class) || rawReturnType.equals(Boolean.class)) {\n            return Key.get(ReturnTrueIf2xx.class);\n         } else if (rawReturnType.equals(InputStream.class)) {\n            return Key.get(ReturnInputStream.class);\n         } else if (rawReturnType.equals(HttpResponse.class)) {\n            return Key.get(Class.class.cast(IdentityFunction.class));\n         } else if (acceptHeaders.contains(APPLICATION_JSON)) {\n            return getJsonParserKeyForMethod(invoked);\n         } else if (acceptHeaders.contains(APPLICATION_XML) || invoked.isAnnotationPresent(JAXBResponseParser.class)) {\n            return getJAXBParserKeyForMethod(invoked);\n         } else if (rawReturnType.equals(String.class)) {\n            return Key.get(ReturnStringIf2xx.class);\n         } else if (rawReturnType.equals(URI.class)) {\n            return Key.get(ParseURIFromListOrLocationHeaderIf20x.class);\n         } else {\n            throw new IllegalStateException(\"You must specify a ResponseParser annotation on: \" + invoked.toString());\n         }\n      }\n      return Key.get(annotation.value());\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   private static Key<? extends Function<HttpResponse, ?>> getJAXBParserKeyForMethod(Invokable<?, ?> invoked) {\n      Optional<Type> configuredReturnVal = Optional.absent();\n      if (invoked.isAnnotationPresent(JAXBResponseParser.class)) {\n         Type configuredClass = invoked.getAnnotation(JAXBResponseParser.class).value();\n         configuredReturnVal = configuredClass.equals(NullType.class)\n               ? Optional.<Type>absent()\n               : Optional.<Type>of(configuredClass);\n      }\n      Type returnVal = configuredReturnVal.or(getReturnTypeFor(invoked.getReturnType()));\n      Type parserType = newParameterizedType(ParseXMLWithJAXB.class, returnVal);\n      return (Key<? extends Function<HttpResponse, ?>>) Key.get(parserType);\n   }\n\n   @SuppressWarnings({ \"unchecked\" })\n   private static Key<? extends Function<HttpResponse, ?>> getJsonParserKeyForMethod(Invokable<?, ?> invoked) {\n      ParameterizedType parserType;\n      if (invoked.isAnnotationPresent(Unwrap.class)) {\n         parserType = newParameterizedType(UnwrapOnlyJsonValue.class, getReturnTypeFor(invoked.getReturnType()));\n      } else if (invoked.isAnnotationPresent(Transform.class)) {\n         // At this point, there's no user-configured response parser. Make a default one from Transform's input.\n         TypeToken<? extends Function> fn = TypeToken.of(invoked.getAnnotation(Transform.class).value());\n         Type fnInput = ((ParameterizedType) fn.getSupertype(Function.class).getType()).getActualTypeArguments()[0];\n         parserType = newParameterizedType(ParseJson.class, fnInput);\n      } else {\n         parserType = newParameterizedType(ParseJson.class, getReturnTypeFor(invoked.getReturnType()));\n      }\n      return (Key<? extends Function<HttpResponse, ?>>) Key.get(parserType);\n   }\n\n   static Type getReturnTypeFor(TypeToken<?> typeToken) {\n      Type returnVal = typeToken.getType();\n      if (typeToken.getRawType().getTypeParameters().length == 0) {\n         returnVal = typeToken.getRawType();\n      }\n      return returnVal;\n   }\n\n   // TODO: refactor this out of here\n   @VisibleForTesting\n   @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n   public Function<HttpResponse, ?> getTransformerForMethod(Invocation invocation, Injector injector) {\n      Invokable<?, ?> invoked = invocation.getInvokable();\n      Function<HttpResponse, ?> transformer;\n      if (invoked.isAnnotationPresent(SelectJson.class)) {\n         Type returnVal = getReturnTypeFor(invoked.getReturnType());\n         if (invoked.isAnnotationPresent(OnlyElement.class))\n            returnVal = newParameterizedType(Set.class, returnVal);\n         transformer = new ParseFirstJsonValueNamed(injector.getInstance(GsonWrapper.class),\n               TypeLiteral.get(returnVal), invoked.getAnnotation(SelectJson.class).value());\n         if (invoked.isAnnotationPresent(OnlyElement.class))\n            transformer = Functions.compose(new OnlyElementOrNull(), transformer);\n      } else {\n         transformer = injector.getInstance(getParserOrThrowException(invocation));\n      }\n      return transformer;\n   }\n\n   static Class<? extends HandlerWithResult<?>> getSaxResponseParserClassOrNull(Invokable<?, ?> invoked) {\n      XMLResponseParser annotation = invoked.getAnnotation(XMLResponseParser.class);\n      if (annotation != null) {\n         return annotation.value();\n      }\n      return null;\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/internal/UtilsImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.internal;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.crypto.Crypto;\nimport org.jclouds.date.DateService;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.json.Json;\nimport org.jclouds.logging.Logger.LoggerFactory;\nimport org.jclouds.rest.HttpClient;\nimport org.jclouds.rest.Utils;\nimport org.jclouds.xml.XMLParser;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.eventbus.EventBus;\nimport com.google.inject.Injector;\nimport com.google.inject.Singleton;\n\n@Singleton\npublic class UtilsImpl implements Utils {\n\n   private final Json json;\n   private final HttpClient simpleClient;\n   private final Crypto encryption;\n   private final DateService date;\n   private final EventBus eventBus;\n   private final Map<String, Credentials> credentialStore;\n   private final LoggerFactory loggerFactory;\n   private Injector injector;\n   private XMLParser xml;\n\n   @Inject\n   protected UtilsImpl(Injector injector, Json json, XMLParser xml, HttpClient simpleClient, Crypto encryption,\n         DateService date, EventBus eventBus, Map<String, Credentials> credentialStore, LoggerFactory loggerFactory) {\n      this.injector = injector;\n      this.json = json;\n      this.simpleClient = simpleClient;\n      this.encryption = encryption;\n      this.date = date;\n      this.eventBus = eventBus;\n      this.credentialStore = credentialStore;\n      this.loggerFactory = loggerFactory;\n      this.xml = xml;\n   }\n\n   @Override\n   public DateService date() {\n      return date;\n   }\n\n   @Override\n   public Crypto crypto() {\n      return encryption;\n   }\n\n   @Override\n   public HttpClient http() {\n      return simpleClient;\n   }\n\n   @Override\n   public EventBus eventBus() {\n      return eventBus;\n   }\n\n   @Override\n   public LoggerFactory loggerFactory() {\n      return loggerFactory;\n   }\n\n   @Override\n   public Json json() {\n      return json;\n   }\n\n   @Override\n   @Beta\n   public Injector injector() {\n      return injector;\n   }\n\n   @Override\n   public XMLParser xml() {\n      return xml;\n   }\n\n   @Override\n   public Map<String, Credentials> credentialStore() {\n      return credentialStore;\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/suppliers/MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.suppliers;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Throwables.propagate;\nimport static org.jclouds.util.Throwables2.getFirstThrowableOfType;\n\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport org.jclouds.rest.AuthorizationException;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ForwardingObject;\nimport com.google.common.util.concurrent.UncheckedExecutionException;\n\n/**\n * This will retry the supplier if it encounters a timeout exception, but not if it encounters an\n * AuthorizationException.\n * <p/>\n * A shared exception reference is used so that anyone who encounters an authorizationexception will be short-circuited.\n * This prevents accounts from being locked out.\n * \n * <h3>details</h3>\n * http://code.google.com/p/google-guice/issues/detail?id=483 guice doesn't remember when singleton providers throw\n * exceptions. in this case, if the supplier fails with an authorization exception, it is called again for each provider\n * method that depends on it. To short-circuit this, we remember the last exception trusting that guice is\n * single-threaded.\n * \n * Note this implementation is folded into the same class, vs being decorated as stacktraces are exceptionally long and\n * difficult to grok otherwise. We use {@link LoadingCache} to deal with concurrency issues related to the supplier.\n */\npublic class MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier<T> extends ForwardingObject implements\n      Supplier<T> {\n   \n   static class SetAndThrowAuthorizationExceptionSupplierBackedLoader<V> extends CacheLoader<String, Optional<V>> {\n\n      private final Supplier<V> delegate;\n      private final AtomicReference<AuthorizationException> authException;\n      private final ValueLoadedCallback<V> valueLoadedCallback;\n\n      public SetAndThrowAuthorizationExceptionSupplierBackedLoader(Supplier<V> delegate,\n            AtomicReference<AuthorizationException> authException, ValueLoadedCallback<V> valueLoadedCallback) {\n         this.delegate = checkNotNull(delegate, \"delegate\");\n         this.authException = checkNotNull(authException, \"authException\");\n         this.valueLoadedCallback = checkNotNull(valueLoadedCallback, \"valueLoadedCallback\");\n      }\n\n      @Override\n      public Optional<V> load(String key) {\n         if (authException.get() != null)\n            throw authException.get();\n         try {\n            Optional<V> value = Optional.fromNullable(delegate.get());\n            valueLoadedCallback.valueLoaded(value);\n            return value;\n         } catch (Exception e) {\n            AuthorizationException aex = getFirstThrowableOfType(e, AuthorizationException.class);\n            if (aex != null) {\n               authException.set(aex);\n               throw aex;\n            }\n            throw propagate(e);\n         }\n      }\n\n      @Override\n      public String toString() {\n         return MoreObjects.toStringHelper(this).add(\"delegate\", delegate).toString();\n      }\n   }\n   \n   public static class ValueLoadedEvent<V> {\n      private final Object eventKey;\n      private final Optional<V> value;\n\n      public ValueLoadedEvent(Object eventKey, Optional<V> value) {\n         this.eventKey = checkNotNull(eventKey, \"eventKey\");\n         this.value = checkNotNull(value, \"value\");\n      }\n\n      public Object getEventKey() {\n         return eventKey;\n      }\n\n      public Optional<V> getValue() {\n         return value;\n      }\n   }\n\n   private final Supplier<T> delegate;\n   private final long duration;\n   private final TimeUnit unit;\n   private final LoadingCache<String, Optional<T>> cache;\n\n   public static <T> MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier<T> create(\n         AtomicReference<AuthorizationException> authException, Supplier<T> delegate, long duration, TimeUnit unit) {\n      return new MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier<T>(authException, delegate, duration,\n            unit, new ValueLoadedCallback.NoOpCallback<T>());\n   }\n   \n   /**\n    * Creates a memoized supplier that calls the given callback each time values are loaded.\n    */\n   public static <T> MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier<T> create(\n         AtomicReference<AuthorizationException> authException, Supplier<T> delegate, long duration, TimeUnit unit,\n         ValueLoadedCallback<T> valueLoadedCallback) {\n      return new MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier<T>(authException, delegate, duration,\n            unit, valueLoadedCallback);\n   }\n   \n   MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier(AtomicReference<AuthorizationException> authException,\n         Supplier<T> delegate, long duration, TimeUnit unit, ValueLoadedCallback<T> valueLoadedCallback) {\n      this.delegate = delegate;\n      this.duration = duration;\n      this.unit = unit;\n      this.cache = CacheBuilder.newBuilder().expireAfterWrite(duration, unit)\n            .build(new SetAndThrowAuthorizationExceptionSupplierBackedLoader<T>(delegate, authException, valueLoadedCallback));\n   }\n\n   @Override\n   protected Supplier<T> delegate() {\n      return delegate;\n   }\n\n   @Override\n   public T get() {\n      try {\n         return cache.get(\"FOO\").orNull();\n      } catch (UncheckedExecutionException e) {\n         throw propagate(e.getCause());\n      } catch (ExecutionException e) {\n         throw propagate(e.getCause());\n      }\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).add(\"delegate\", delegate).add(\"duration\", duration).add(\"unit\", unit)\n            .toString();\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/suppliers/SetAndThrowAuthorizationExceptionSupplier.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.suppliers;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Throwables.propagate;\nimport static org.jclouds.util.Throwables2.getFirstThrowableOfType;\n\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport org.jclouds.rest.AuthorizationException;\n\nimport com.google.common.base.Supplier;\n\npublic class SetAndThrowAuthorizationExceptionSupplier<T> implements Supplier<T> {\n   private final Supplier<T> delegate;\n   private final AtomicReference<AuthorizationException> authException;\n\n   public SetAndThrowAuthorizationExceptionSupplier(Supplier<T> delegate,\n         AtomicReference<AuthorizationException> authException) {\n      this.delegate = checkNotNull(delegate, \"delegate\");\n      this.authException = checkNotNull(authException, \"authException\");\n   }\n\n   public T get() {\n      if (authException.get() != null)\n         throw authException.get();\n      try {\n         return delegate.get();\n      } catch (AuthorizationException e) {\n         authException.set(e);\n         throw e;\n      } catch (Exception e) {\n         AuthorizationException aex = getFirstThrowableOfType(e, AuthorizationException.class);\n         if (aex != null) {\n            authException.set(aex);\n            throw aex;\n         }\n         throw propagate(e);\n      }\n   }\n\n   @Override\n   public String toString() {\n      return \"RetryOnTimeOutButNotOnAuthorizationExceptionSupplier(\" + delegate + \")\";\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/suppliers/URIFromStringSupplier.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.suppliers;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.net.URI;\n\nimport jakarta.inject.Inject;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.base.Supplier;\n\npublic class URIFromStringSupplier implements Supplier<URI> {\n\n   private final URI endpoint;\n\n   @Inject\n   protected URIFromStringSupplier(String uri) {\n      this.endpoint = URI.create(checkNotNull(uri, \"uri\"));\n   }\n\n   @Override\n   public URI get() {\n      return endpoint;\n   }\n\n   @Override\n   public boolean equals(Object object) {\n      if (this == object) {\n         return true;\n      }\n      if (object instanceof URIFromStringSupplier) {\n         final URIFromStringSupplier other = URIFromStringSupplier.class.cast(object);\n         return equal(endpoint, other.endpoint);\n      } else {\n         return false;\n      }\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(endpoint);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   protected ToStringHelper string() {\n      return toStringHelper(\"\").add(\"endpoint\", endpoint);\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/rest/suppliers/ValueLoadedCallback.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.suppliers;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Optional;\n\n/**\n * Callback that gets called every time the supplier loads new values.\n */\n@Beta\npublic interface ValueLoadedCallback<V> {\n   \n   void valueLoaded(Optional<V> value);\n\n   /** The default implementation does nothing */\n   public static class NoOpCallback<V> implements ValueLoadedCallback<V> {\n      @Override\n      public void valueLoaded(Optional<V> value) {\n         // Do nothing\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/suppliers/SupplyKeyMatchingValueOrNull.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.suppliers;\n\nimport java.util.Collection;\nimport java.util.Map;\n\nimport jakarta.annotation.Resource;\n\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Maps;\nimport com.google.common.collect.Multimap;\nimport com.google.common.collect.Multimaps;\n\n/**\n * Allows you to lazy discover a key by value. This is useful for example in service discovery,\n * where you need to see what the \"current\" service name is based on a map of service names to\n * endpoints. <h3>note</h3> take care to memoize this using {@link Suppliers#memoize(Supplier)}\n */\npublic class SupplyKeyMatchingValueOrNull<K, V> implements Supplier<K> {\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   private final Supplier<Map<K, Supplier<V>>> supplier;\n   private final Supplier<V> valueSupplier;\n\n   public SupplyKeyMatchingValueOrNull(Supplier<Map<K, Supplier<V>>> supplier, Supplier<V> valueSupplier) {\n      this.valueSupplier = valueSupplier;\n      this.supplier = supplier;\n   }\n\n   @Override\n   public K get() {\n      V uri = valueSupplier.get();\n      // eagerly get all the values, so we can see which is default\n      final Map<K, V> map = Maps.transformValues(supplier.get(), Suppliers.<V> supplierFunction());\n\n      // There can be keys with the same value so we need a multimap here\n      Multimap<V, K> inverted = Multimaps.index(map.keySet(), new Function<K, V>() {\n         @Override public V apply(K input) {\n            return map.get(input);\n         }\n      });\n\n      Collection<K> keys = inverted.get(uri);\n      K key = null;\n\n      if (keys == null || keys.isEmpty()) {\n         if (!map.isEmpty()) {\n            key = Iterables.get(map.keySet(), 0);\n            logger.warn(\"failed to find key for value %s in %s; choosing first: %s\", uri, map, key);\n         }\n      } else {\n         key = Iterables.get(keys, 0);\n         if (keys.size() > 1) {\n            logger.debug(\"found %s keys for value %s. choosing first: %s\", keys.size(), uri, key);\n         }\n      }\n\n      return key;\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/util/Closeables2.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.util;\n\nimport java.io.Closeable;\nimport java.io.IOException;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.annotations.Beta;\n\n/**\n * Alternative to {@link com.google.common.io.Closeables}, which allows jclouds\n * to avoid guava incompatibility on said class.\n */\n@Beta\npublic final class Closeables2 {\n\n   /** Closes the closable, swallowing any {@linkplain IOException}. */\n   public static void closeQuietly(@Nullable Closeable closeable) {\n      if (closeable == null) {\n         return;\n      }\n      try {\n         closeable.close();\n      } catch (IOException ignored) {\n      }\n   }\n\n   private Closeables2() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/util/InetAddresses2.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.util;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Singleton;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.Iterables;\nimport com.google.common.net.InetAddresses;\n\npublic class InetAddresses2 {\n   @Singleton\n   public static enum IsPrivateIPAddress implements Predicate<String> {\n      INSTANCE;\n\n      public boolean apply(String in) {\n         if (InetAddresses.isInetAddress(checkNotNull(in, \"input address\"))) {\n            // 24-bit Block (/8 prefix, 1/A) 10.0.0.0 10.255.255.255 16777216\n            if (in.indexOf(\"10.\") == 0)\n               return true;\n            // 20-bit Block (/12 prefix, 16/B) 172.16.0.0 172.31.255.255 1048576\n            if (in.indexOf(\"172.\") == 0) {\n               int second = Integer.parseInt(Iterables.get(Splitter.on('.').split(in), 1));\n               if (second >= 16 && second <= 31)\n                  return true;\n            }\n            // 16-bit Block (/16 prefix, 256/C) 192.168.0.0 192.168.255.255 65536\n            if (in.indexOf(\"192.168.\") == 0)\n               return true;\n         }\n         return false;\n      }\n\n      @Override\n      public String toString() {\n         return \"isPrivateIPAddress()\";\n      }\n\n   }\n\n   /**\n    * @return true if the input is an ip4 address and in one of the 3 reserved private blocks.\n    */\n   public static boolean isPrivateIPAddress(String in) {\n      return IsPrivateIPAddress.INSTANCE.apply(in);\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/util/Maps2.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.util;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\nimport java.util.Map.Entry;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMap.Builder;\n\n/**\n * General utilities used in jclouds code for {@link Map Maps}.\n */\npublic class Maps2 {\n\n   /**\n    * change the keys but keep the values in-tact.\n    * \n    * @param <K1>\n    *           input key type\n    * @param <K2>\n    *           output key type\n    * @param <V>\n    *           value type\n    * @param in\n    *           input map to transform\n    * @param fn\n    *           how to transform the values\n    * @return immutableMap with the new keys.\n    */\n   public static <K1, K2, V> Map<K2, V> transformKeys(Map<K1, V> in, Function<K1, K2> fn) {\n      checkNotNull(in, \"input map\");\n      checkNotNull(fn, \"function\");\n      Builder<K2, V> returnVal = ImmutableMap.builder();\n      for (Entry<K1, V> entry : in.entrySet())\n         returnVal.put(fn.apply(entry.getKey()), entry.getValue());\n      return returnVal.build();\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/util/Multimaps2.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.util;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map.Entry;\nimport java.util.Set;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicates;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableMultimap.Builder;\nimport com.google.common.collect.Multimap;\nimport com.google.common.collect.Multimaps;\n\npublic class Multimaps2 {\n\n   public static <K, V> Multimap<K, V> replaceValue(Multimap<K, V> fromMultimap, final K key, final V value) {\n      checkNotNull(fromMultimap, \"input multimap\");\n      checkNotNull(key, \"key\");\n      checkNotNull(value, \"value\");\n      return ImmutableMultimap.<K, V>builder()\n                              .putAll(withoutKey(fromMultimap, key))\n                              .put(key, value).build();\n   }\n   \n   public static <K, V> Multimap<K, V> replaceEntries(Multimap<K, V> fromMultimap, Multimap<K, V> updates) {\n      checkNotNull(fromMultimap, \"input multimap\");\n      checkNotNull(updates, \"updates\");\n      return ImmutableMultimap.<K, V>builder()\n                              .putAll(withoutKeys(fromMultimap, updates.keySet()))\n                              .putAll(updates).build();\n   }\n   \n   public static <K, V> Multimap<K, V> withoutKey(Multimap<K, V> fromMultimap, K key) {\n      return Multimaps.<K, V> filterKeys(fromMultimap, Predicates.not(Predicates.equalTo(key)));\n   }\n   \n   public static <K, V> Multimap<K, V> withoutKeys(Multimap<K, V> fromMultimap, Set<K> keys) {\n      return Multimaps.<K, V> filterKeys(fromMultimap, Predicates.not(Predicates.in(keys)));\n   }\n   \n   /**\n    * change the keys but keep the values in-tact.\n    * \n    * @param <K1>\n    *           input key type\n    * @param <K2>\n    *           output key type\n    * @param <V>\n    *           value type\n    * @param in\n    *           input map to transform\n    * @param fn\n    *           how to transform the values\n    * @return immutableMap with the new keys.\n    */\n   public static <K1, K2, V> Multimap<K2, V> transformKeys(Multimap<K1, V> in, Function<K1, K2> fn) {\n      checkNotNull(in, \"input map\");\n      checkNotNull(fn, \"function\");\n      Builder<K2, V> returnVal = ImmutableMultimap.builder();\n      for (Entry<K1, V> entry : in.entries())\n         returnVal.put(fn.apply(entry.getKey()), entry.getValue());\n      return returnVal.build();\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/util/Optionals2.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.util;\n\nimport java.lang.reflect.ParameterizedType;\nimport java.lang.reflect.Type;\nimport java.lang.reflect.WildcardType;\n\nimport com.google.common.base.Optional;\nimport com.google.common.reflect.Invokable;\nimport com.google.common.reflect.TypeToken;\n\npublic class Optionals2 {\n   public static Class<?> unwrapIfOptional(TypeToken<?> type) {\n      if (type.getRawType().isAssignableFrom(Optional.class)) {\n         ParameterizedType futureType = ParameterizedType.class.cast(type.getType());\n         // TODO: error checking in case this is a type, not a class.\n         Type t = futureType.getActualTypeArguments()[0];\n         if (t instanceof WildcardType) {\n            t = ((WildcardType) t).getUpperBounds()[0];\n         }\n         return Class.class.cast(t);\n      }\n      return type.getRawType();\n   }\n\n   public static boolean isReturnTypeOptional(Invokable<?, ?> method) {\n      return method.getReturnType().getRawType().isAssignableFrom(Optional.class);\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/util/PasswordGenerator.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.util;\n\nimport static com.google.common.base.Preconditions.checkArgument;\n\nimport java.security.SecureRandom;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Random;\n\nimport com.google.common.base.Joiner;\nimport com.google.common.base.Strings;\nimport com.google.common.primitives.Chars;\n\n/**\n * Generates random passwords.\n * <p>\n * This class allows to configure the password requirements for:\n * <ul>\n * <li>Number of upper case and lower case letters</li>\n * <li>Inclusion of numbers</li>\n * <li>Inclusion of special characters</li>\n * </ul>\n * By default, it will include at least three lower case letters, three upper\n * case, three numbers and three special characters, and a maximum of five from\n * each set.\n * <p>\n * It also allows to configure forbidden characters to accommodate the password\n * requirements for the different clouds.\n * <p>\n * Example usage:\n * <pre>\n * String password = new PasswordGenerator()\n *    .lower().count(3)  // Exactly three lower case characters\n *    .upper().count(2)  // Exactly 2 upper case characters \n *    .numbers().min(5).exclude(\"012345\".toCharArray()) // At least five numbers, from 6 to 9.\n *    .symbols().min(6).max(10) // Between 6 and 10 special characters\n *    .generate();\n * </pre>\n *\n */\npublic class PasswordGenerator {\n\n   private static final Random RANDOM = new SecureRandom();\n\n   private final Config lower = new Config(\"abcdefghijklmnopqrstuvwxyz\").min(3).max(5);\n   private final Config upper = new Config(\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\").min(3).max(5);\n   private final Config numbers = new Config(\"1234567890\").min(3).max(5);\n   // Use a small set of symbols that does not break shell commands\n   private final Config symbols = new Config(\"~@#%*()-_=+:,.?\").min(3).max(5);\n\n   /**\n    * Returns the lower case configuration. Allows to configure the presence of lower case characters.\n    */\n   public Config lower() {\n      return lower;\n   }\n\n   /**\n    * Returns the upper case configuration. Allows to configure the presence of upper case characters.\n    */\n   public Config upper() {\n      return upper;\n   }\n\n   /**\n    * Returns the numbers configuration. Allows to configure the presence of numeric characters.\n    */\n   public Config numbers() {\n      return numbers;\n   }\n\n   /**\n    * Returns the special character configuration. Allows to configure the presence of special characters.\n    */\n   public Config symbols() {\n      return symbols;\n   }\n\n   /**\n    * Generates a random password using the configured spec.\n    */\n   public String generate() {\n      StringBuilder sb = new StringBuilder();\n      sb.append(lower.fragment());\n      sb.append(upper.fragment());\n      sb.append(numbers.fragment());\n      sb.append(symbols.fragment());\n      return shuffleAndJoin(sb.toString().toCharArray());\n   }\n\n   private static String shuffleAndJoin(char[] chars) {\n      List<Character> result = Chars.asList(chars);\n      Collections.shuffle(result);\n      return Joiner.on(\"\").join(result);\n   }\n\n   public class Config {\n      private final String characters;\n      private char[] exclusions;\n      private int minLength;\n      private int maxLength;\n\n      private Config(String characters) {\n         checkArgument(!Strings.isNullOrEmpty(characters), \"charactets must be a non-empty string\");\n         this.characters = characters;\n      }\n\n      public Config exclude(char[] exclusions) {\n         this.exclusions = exclusions;\n         return this;\n      }\n\n      public Config min(int num) {\n         this.minLength = num;\n         return this;\n      }\n\n      public Config max(int num) {\n         this.maxLength = num;\n         return this;\n      }\n\n      public Config count(int num) {\n         min(num);\n         max(num);\n         return this;\n      }\n\n      private String fragment() {\n         int length = minLength + RANDOM.nextInt((maxLength - minLength) + 1);\n         return new Generator(characters, length, exclusions).generate();\n      }\n\n      // Delegate to enclosing class for better fluent generators\n\n      public Config lower() {\n         return PasswordGenerator.this.lower();\n      }\n\n      public Config upper() {\n         return PasswordGenerator.this.upper();\n      }\n\n      public Config numbers() {\n         return PasswordGenerator.this.numbers();\n      }\n\n      public Config symbols() {\n         return PasswordGenerator.this.symbols();\n      }\n\n      public String generate() {\n         return PasswordGenerator.this.generate();\n      }\n   }\n\n   private static class Generator {\n      private final char[] characters;\n      private final int count;\n\n      private Generator(String characters, int count, char[] exclusions) {\n         checkArgument(!Strings.isNullOrEmpty(characters), \"charactets must be a non-empty string\");\n         this.count = count;\n         if (exclusions == null || exclusions.length == 0) {\n            this.characters = characters.toCharArray();\n         } else {\n            this.characters = characters.replaceAll(\"[\" + new String(exclusions) + \"]\", \"\").toCharArray();\n         }\n      }\n\n      public String generate() {\n         char[] selected = new char[count];\n         for (int i = 0; i < count; i++) {\n            selected[i] = characters[RANDOM.nextInt(characters.length)];\n         }\n         return shuffleAndJoin(selected);\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/util/Patterns.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.util;\n\nimport java.util.regex.Pattern;\n\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\n\npublic class Patterns {\n\n   public static final Pattern NEWLINE_PATTERN = Pattern.compile(\"\\r?\\n\");\n\n   public static final LoadingCache<String, Pattern> TOKEN_TO_PATTERN = CacheBuilder.newBuilder()\n         .<String, Pattern> build(new CacheLoader<String, Pattern>() {\n            @Override\n            public Pattern load(String tokenValue) {\n               return Pattern.compile(\"\\\\{\" + tokenValue + \"\\\\}\");\n            }\n         });\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/util/Predicates2.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.util;\n\nimport static java.util.concurrent.TimeUnit.MILLISECONDS;\nimport static org.jclouds.util.Throwables2.getFirstThrowableOfType;\n\nimport java.util.Date;\nimport java.util.concurrent.CancellationException;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.TimeoutException;\n\nimport jakarta.annotation.Resource;\n\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Predicate;\n\npublic class Predicates2 {\n   /** Returns a predicate that evaluates to true if the String being tested starts with a prefix. */\n   public static Predicate<String> startsWith(final String prefix) {\n      return new Predicate<String>() {\n         @Override\n         public boolean apply(final String input) {\n             return input.startsWith(prefix);\n         }\n\n         @Override\n         public String toString() {\n            return \"startsWith(\" + prefix + \")\";\n         }\n      };\n   }\n\n   /**\n    * Retries a predicate until it is met, a timeout occurs, or an exception occurs.\n    */\n   public static <T> Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod,\n         TimeUnit unit) {\n      return new RetryablePredicate<T>(findOrBreak, timeout, period, maxPeriod, unit);\n   }\n\n   /**\n    * like {@link #retry(Predicate, long, long, long, TimeUnit)} where {@code maxPeriod} is 10x {@code period}\n    */\n   public static <T> Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, TimeUnit unit) {\n      return retry(findOrBreak, timeout, period, period * 10L, unit);\n   }\n\n   /**\n    * like {@link #retry(Predicate, long, long, long, TimeUnit)} where {@code unit} is in milliseconds\n    */\n   public static <T> Predicate<T> retry(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod) {\n      return retry(findOrBreak, timeout, period, maxPeriod, MILLISECONDS);\n   }\n\n   /**\n    * @see org.jclouds.compute.config.ComputeServiceProperties#POLL_INITIAL_PERIOD\n    */\n   public static final long DEFAULT_PERIOD = 50L;\n   /**\n    * @see org.jclouds.compute.config.ComputeServiceProperties#POLL_MAX_PERIOD\n    */\n   public static final long DEFAULT_MAX_PERIOD = 1000L;\n\n   /**\n    * like {@link #retry(Predicate, long, long, long, TimeUnit)} where {@code unit} is in milliseconds, {@code period}\n    * is 50ms, and {@code maxPeriod} 1s.\n    */\n   public static <T> Predicate<T> retry(Predicate<T> findOrBreak, long timeout) {\n      return retry(findOrBreak, timeout, DEFAULT_PERIOD, DEFAULT_MAX_PERIOD, MILLISECONDS);\n   }\n\n   private static class RetryablePredicate<T> implements Predicate<T> {\n      private final long timeout;\n      private final long period;\n      private final long maxPeriod;\n      private final Predicate<T> findOrBreak;\n\n      @Resource\n      protected Logger logger = Logger.NULL;\n\n      protected RetryablePredicate(Predicate<T> findOrBreak, long timeout, long period, long maxPeriod, TimeUnit unit) {\n         this.findOrBreak = findOrBreak;\n         this.timeout = unit.toMillis(timeout);\n         this.period = unit.toMillis(period);\n         this.maxPeriod = unit.toMillis(maxPeriod);\n      }\n      \n      @Override\n      public boolean apply(T input) {\n         // Ensure that try one last time at the end (e.g. if timeout is 30 secs and last sleep\n         // takes us up to the 30 secs mark, then test again rather than returning immediately \n         // after the sleep!).\n         // Always try at least once, even if timeout is 0 or negative.\n         // A timeout of 0 means 0 millis.\n         try {\n            long i = 1L;\n            long now = System.currentTimeMillis();\n            long end = now + timeout;\n            while (now < end) {\n               if (findOrBreak.apply(input)) {\n                  return true;\n               }\n               long sleepTime = nextMaxInterval(i++, end);\n               if (sleepTime > 0) Thread.sleep(sleepTime);\n               now = System.currentTimeMillis();\n            }\n\n            return findOrBreak.apply(input);\n\n         } catch (InterruptedException e) {\n            logger.warn(e, \"predicate %s on %s interrupted, returning false\", input, findOrBreak);\n            Thread.currentThread().interrupt();\n            return false;\n         } catch (RuntimeException e) {\n            if (getFirstThrowableOfType(e, ExecutionException.class) != null) {\n               logger.warn(e, \"predicate %s on %s errored [%s], returning false\", input, findOrBreak, e.getMessage());\n               return false;\n            } else if (getFirstThrowableOfType(e, IllegalStateException.class) != null) {\n               logger.warn(e, \"predicate %s on %s illegal state [%s], returning false\", input, findOrBreak, e.getMessage());\n               return false;\n            } else if (getFirstThrowableOfType(e, CancellationException.class) != null) {\n               logger.warn(e, \"predicate %s on %s cancelled [%s], returning false\", input, findOrBreak, e.getMessage());\n               return false;\n            } else if (getFirstThrowableOfType(e, TimeoutException.class) != null) {\n               logger.warn(e, \"predicate %s on %s timed out [%s], returning false\", input, findOrBreak, e.getMessage());\n               return false;\n            } else\n               throw e;\n         }\n      }\n\n      /**\n       * @deprecated since 1.9.0; use {@link #nextMaxInterval(long, long)}\n       */\n      @Deprecated\n      protected long nextMaxInterval(long attempt, Date end) {\n         return nextMaxInterval(attempt, end.getTime());\n      }\n\n      /**\n       * Calculates the time interval to a retry attempt.<p>\n       * The interval increases exponentially with each attempt, at a rate of nextInterval *= 1.5\n       * (where 1.5 is the backoff factor), to the maximum interval or specified timeout.\n       * \n       * @param attempt number of this attempt (starting at 1 for the first retry)\n       * @param endTime timeout\n       * @return time in milliseconds from now until the next attempt, or if negative, time lapsed\n       * since the specified timeout\n       */\n      protected long nextMaxInterval(long attempt, long endTime) {\n         long interval = (long) (period * Math.pow(1.5, attempt - 1));\n         interval = interval > maxPeriod ? maxPeriod : interval;\n         long max = endTime - System.currentTimeMillis();\n         return (interval > max) ? max : interval;\n      }\n\n      /**\n       * @deprecated since 1.9.0; use {@link #nextMaxInterval(long, long)}\n       */\n      @Deprecated\n      protected boolean before(Date end) {\n         return new Date().compareTo(end) < 0;\n      }\n\n      /**\n       * @deprecated since 1.9.0; use {@link #nextMaxInterval(long, long)}\n       */\n      @Deprecated\n      protected boolean atOrAfter(Date end) {\n         return new Date().compareTo(end) >= 0;\n      }\n   }   \n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/util/SaxUtils.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.util;\n\nimport java.util.Map;\n\nimport org.xml.sax.Attributes;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMap.Builder;\n\npublic class SaxUtils {\n\n   public static boolean equalsOrSuffix(String val, String expected) {\n      return expected.equals(val) || val.endsWith(\":\" + expected);\n   }\n\n   public static Map<String, String> cleanseAttributes(Attributes in) {\n      Builder<String, String> attrs = ImmutableMap.builder();\n      for (int i = 0; i < in.getLength(); i++) {\n         String name = in.getQName(i);\n         if (name.indexOf(':') != -1)\n            name = name.substring(name.indexOf(':') + 1);\n         attrs.put(name, in.getValue(i));\n      }\n      return attrs.build();\n   }\n\n   public static String currentOrNull(StringBuilder currentText) {\n      String returnVal = currentText.toString().trim();\n      return returnVal.equals(\"\") ? null : returnVal;\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/util/Strings2.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.util;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.util.Closeables2.closeQuietly;\nimport static org.jclouds.util.Patterns.TOKEN_TO_PATTERN;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.io.UnsupportedEncodingException;\nimport java.net.URLDecoder;\nimport java.net.URLEncoder;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.concurrent.ExecutionException;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.Multimap;\nimport com.google.common.io.CharStreams;\nimport com.google.common.net.InetAddresses;\nimport com.google.common.primitives.Chars;\n\npublic class Strings2 {\n\n   /**\n    * Web browsers do not always handle '+' characters well, use the well-supported '%20' instead.\n    */\n   public static String urlEncode(String in, char... skipEncode) {\n      return urlEncode(in, Chars.asList(skipEncode));\n   }\n\n   public static String urlEncode(String in, Iterable<Character> skipEncode) {\n      try {\n         String returnVal = URLEncoder.encode(in, \"UTF-8\");\n         returnVal = returnVal.replace(\"+\", \"%20\");\n         returnVal = returnVal.replace(\"*\", \"%2A\");\n         for (char c : skipEncode) {\n            returnVal = returnVal.replace(CHAR_TO_ENCODED.get(c), c + \"\");\n         }\n         return returnVal;\n      } catch (UnsupportedEncodingException e) {\n         throw new IllegalStateException(\"Bad encoding on input: \" + in, e);\n      } catch (ExecutionException e) {\n         throw new IllegalStateException(\"error creating pattern: \" + in, e);\n      }\n   }\n\n   private static final LoadingCache<Character, String> CHAR_TO_ENCODED = CacheBuilder.newBuilder()\n         .<Character, String> build(new CacheLoader<Character, String>() {\n            @Override\n            public String load(Character plain) throws ExecutionException {\n               try {\n                  return URLEncoder.encode(plain + \"\", \"UTF-8\");\n               } catch (UnsupportedEncodingException e) {\n                  throw new ExecutionException(\"Bad encoding on input: \" + plain, e);\n               }\n            }\n         });\n\n   private static final String IP_ADDRESS = \"(\\\\d{1,3})\\\\.(\\\\d{1,3})\\\\.(\\\\d{1,3})\\\\.(\\\\d{1,3})\";\n   private static final String SLASH_FORMAT = IP_ADDRESS + \"/(\\\\d{1,3})\";\n   private static final Pattern CIDR_PATTERN = Pattern.compile(SLASH_FORMAT);\n\n   public static boolean isCidrFormat(String in) {\n      return CIDR_PATTERN.matcher(in).matches() || isIPv6CIDR(in);\n   }\n\n   public static boolean isIPv6CIDR(String in) {\n      // ensure IPv6 notation (as opposed to parsing for IPv4)\n      if ( !in.contains(\":\"))\n         return false;\n      String[] parts = in.split(\"/\");\n      if ( parts.length != 2 ) {\n         if (parts.length == 1)\n            return InetAddresses.isInetAddress(in);\n         else\n            return false;\n      }\n      // no leading zero\n      if ( parts[1].length() > 1 && parts[1].startsWith(\"0\"))\n         return false;\n      int mask;\n      try {\n         mask = Integer.parseInt(parts[1]);\n      } catch (NumberFormatException e) {\n         return false;\n      }\n      if (mask < 0 || mask > 128) return false;\n      return InetAddresses.isInetAddress(parts[0]);\n   }\n\n   /**\n    * url decodes the input param, if set.\n    *\n    * @param in\n    *           nullable\n    * @return null if input was null\n    * @throws IllegalStateException\n    *            if encoding isn't {@code UTF-8}\n    */\n   public static String urlDecode(@Nullable String in) {\n      if (in == null)\n         return null;\n      String input = in.toString();\n      try {\n         return URLDecoder.decode(input, \"UTF-8\");\n      } catch (UnsupportedEncodingException e) {\n         throw new IllegalStateException(\"Bad encoding on input: \" + in, e);\n      }\n   }\n\n   public static String toStringAndClose(InputStream input) throws IOException {\n      checkNotNull(input, \"input\");\n      try {\n         return CharStreams.toString(new InputStreamReader(input, Charsets.UTF_8));\n      } finally {\n         closeQuietly(input);\n      }\n   }\n\n   public static InputStream toInputStream(String in) {\n      return new ByteArrayInputStream(in.getBytes(Charsets.UTF_8));\n   }\n\n   /**\n    * replaces tokens that are expressed as <code>{token}</code>\n    *\n    * <p/>\n    * ex. if input is \"hello {where}\"<br/>\n    * and replacements is \"where\" -> \"world\" <br/>\n    * then replaceTokens returns \"hello world\"\n    *\n    * @param input\n    *           source to replace\n    * @param replacements\n    *           token/value pairs\n    */\n   public static String replaceTokens(String input, Map<String, String> replacements) {\n      Matcher matcher = TOKEN_PATTERN.matcher(input);\n      StringBuilder builder = new StringBuilder();\n      int i = 0;\n      while (matcher.find()) {\n         String replacement = replacements.get(matcher.group(1));\n         builder.append(input, i, matcher.start());\n         if (replacement == null)\n            builder.append(matcher.group(0));\n         else\n            builder.append(replacement);\n         i = matcher.end();\n      }\n      builder.append(input, i, input.length());\n      return builder.toString();\n   }\n\n   private static final Pattern TOKEN_PATTERN = Pattern.compile(\"\\\\{(.+?)\\\\}\");\n\n   public static String replaceTokens(String input, Multimap<String, ?> tokenValues) {\n      for (Entry<String, ?> tokenValue : tokenValues.entries()) {\n         Pattern pattern = TOKEN_TO_PATTERN.getUnchecked(tokenValue.getKey());\n         input = pattern.matcher(input).replaceAll(tokenValue.getValue().toString().replace(\"\\\\\", \"\\\\\\\\\").replace(\"$\", \"\\\\$\"));\n      }\n      return input;\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/util/Suppliers2.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.util;\n\nimport java.util.Map;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Function;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.base.Throwables;\nimport com.google.common.collect.Iterables;\n\npublic class Suppliers2 {\n\n   public static <K, V> Supplier<V> getLastValueInMap(final Supplier<Map<K, Supplier<V>>> input) {\n      return new Supplier<V>() {\n         @Override\n         public V get() {\n            Supplier<V> last = Iterables.getLast(input.get().values());\n            return last != null ? last.get() : null;\n         }\n\n         @Override\n         public String toString() {\n            return \"getLastValueInMap()\";\n         }\n      };\n   }\n\n   public static <K, V> Supplier<V> getValueInMapOrNull(final Supplier<Map<K, Supplier<V>>> input, final K keyValue) {\n      return new Supplier<V>() {\n         @Override\n         public V get() {\n            Map<K, Supplier<V>> map = input.get();\n            return map.containsKey(keyValue) ? map.get(keyValue).get() : null;\n         }\n\n         @Override\n         public String toString() {\n            return String.format(\"getValueInMapOrNull('%1$s')\", keyValue);\n         }\n      };\n   }\n\n   public static <X> Function<X, Supplier<X>> ofInstanceFunction() {\n      return new Function<X, Supplier<X>>() {\n\n         @Override\n         public Supplier<X> apply(X arg0) {\n            return Suppliers.ofInstance(arg0);\n         }\n\n         @Override\n         public String toString() {\n            return \"Suppliers.ofInstance()\";\n         }\n      };\n   }\n\n   /**\n    * returns the value of the first supplier, or the value of the fallback, if the unlessNull is\n    * null.\n    */\n   @Beta\n   public static <T> Supplier<T> or(final Supplier<T> unlessNull, final Supplier<T> fallback) {\n      return new Supplier<T>() {\n\n         @Override\n         public T get() {\n            T val = unlessNull.get();\n            if (val != null)\n               return val;\n            return fallback.get();\n         }\n\n         @Override\n         public String toString() {\n            return MoreObjects.toStringHelper(this).add(\"unlessNull\", unlessNull).add(\"fallback\", fallback).toString();\n         }\n      };\n   }\n\n   /**\n    * if a throwable of certain type is encountered on getting the first value, use the fallback.\n    */\n   @Beta\n   public static <T, X extends Throwable> Supplier<T> onThrowable(final Supplier<T> unlessThrowable,\n            final Class<X> throwable, final Supplier<T> fallback) {\n      return new Supplier<T>() {\n\n         @Override\n         public T get() {\n            try {\n               return unlessThrowable.get();\n            } catch (Throwable t) {\n               if (Throwables2.getFirstThrowableOfType(t, throwable) != null)\n                  return fallback.get();\n               throw Throwables.propagate(t);\n            }\n         }\n\n         @Override\n         public String toString() {\n            return MoreObjects.toStringHelper(this).add(\"unlessThrowable\", unlessThrowable)\n                     .add(\"throwable\", throwable.getSimpleName()).add(\"fallback\", fallback).toString();\n         }\n      };\n   }\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/util/Throwables2.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.util;\n\nimport static com.google.common.base.Predicates.instanceOf;\nimport static com.google.common.base.Throwables.getCausalChain;\nimport static com.google.common.base.Throwables.propagate;\nimport static com.google.common.collect.Iterables.find;\n\nimport java.util.ConcurrentModificationException;\nimport java.util.NoSuchElementException;\n\nimport org.jclouds.concurrent.TransformParallelException;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.InsufficientResourcesException;\nimport org.jclouds.rest.RateLimitExceededException;\nimport org.jclouds.rest.ResourceAlreadyExistsException;\nimport org.jclouds.rest.ResourceNotFoundException;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.reflect.TypeToken;\nimport com.google.inject.CreationException;\nimport com.google.inject.ProvisionException;\nimport com.google.inject.spi.Message;\n\n/**\n * General utilities used in jclouds code.\n */\npublic class Throwables2 {\n\n   public static <T extends Throwable> Predicate<Throwable> containsThrowable(final Class<T> throwableType) {\n      return new Predicate<Throwable>() {\n\n         @Override\n         public boolean apply(Throwable input) {\n            return getFirstThrowableOfType(input, throwableType) != null;\n         }\n\n         public String toString() {\n            return \"containsThrowable()\";\n         }\n      };\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   public static <T extends Throwable> T getFirstThrowableOfType(Throwable from, Class<T> clazz) {\n      if (from instanceof ProvisionException)\n         return getFirstThrowableOfType(ProvisionException.class.cast(from), clazz);\n      else if (from instanceof TransformParallelException)\n         return getFirstThrowableOfType(TransformParallelException.class.cast(from), clazz);\n      else if (from instanceof CreationException)\n         return getFirstThrowableOfType(CreationException.class.cast(from), clazz);\n      try {\n         return (T) find(getCausalChain(from), instanceOf(clazz));\n      } catch (NoSuchElementException e) {\n         return null;\n      }\n   }\n\n   @VisibleForTesting\n   static <T extends Throwable> T getFirstThrowableOfType(TransformParallelException e, Class<T> clazz) {\n      for (Exception exception : e.getFromToException().values()) {\n         T cause = getFirstThrowableOfType(exception, clazz);\n         if (cause != null)\n            return cause;\n      }\n      return null;\n   }\n\n   @VisibleForTesting\n   static <T extends Throwable> T getFirstThrowableOfType(ProvisionException e, Class<T> clazz) {\n      for (Message message : e.getErrorMessages()) {\n         if (message.getCause() != null) {\n            T cause = getFirstThrowableOfType(message.getCause(), clazz);\n            if (cause instanceof ProvisionException)\n               return getFirstThrowableOfType(ProvisionException.class.cast(cause), clazz);\n            else if (cause instanceof TransformParallelException)\n               return getFirstThrowableOfType(TransformParallelException.class.cast(cause), clazz);\n            else if (cause instanceof CreationException)\n               return getFirstThrowableOfType(CreationException.class.cast(cause), clazz);\n            return cause;\n         }\n      }\n      return null;\n   }\n\n   @VisibleForTesting\n   static <T extends Throwable> T getFirstThrowableOfType(CreationException e, Class<T> clazz) {\n      for (Message message : e.getErrorMessages()) {\n         if (message.getCause() != null) {\n            T cause = getFirstThrowableOfType(message.getCause(), clazz);\n            if (cause instanceof ProvisionException)\n               return getFirstThrowableOfType(ProvisionException.class.cast(cause), clazz);\n            else if (cause instanceof TransformParallelException)\n               return getFirstThrowableOfType(TransformParallelException.class.cast(cause), clazz);\n            else if (cause instanceof CreationException)\n               return getFirstThrowableOfType(CreationException.class.cast(cause), clazz);\n            return cause;\n         }\n      }\n      return null;\n   }\n\n   public static <T> T propagateAuthorizationOrOriginalException(Exception e) {\n      AuthorizationException aex = getFirstThrowableOfType(e, AuthorizationException.class);\n      if (aex != null)\n         throw aex;\n      throw propagate(e);\n   }\n\n   // Note that ordering matters to propagateIfPossible.\n   private static final ImmutableList<Class<? extends Throwable>> PROPAGATABLE_EXCEPTION_TYPES = ImmutableList.of(\n         IllegalStateException.class,\n         AssertionError.class,\n         UnsupportedOperationException.class,\n         IllegalArgumentException.class,\n         AuthorizationException.class,\n         ResourceAlreadyExistsException.class,\n         ResourceNotFoundException.class,\n         InsufficientResourcesException.class,\n         RateLimitExceededException.class,\n         ConcurrentModificationException.class,\n         HttpResponseException.class);\n\n   // Note this needs to be kept up-to-date with all top-level exceptions jclouds works against\n   public static void propagateIfPossible(Throwable exception, Iterable<TypeToken<? extends Throwable>> throwables)\n         throws Throwable {\n      for (TypeToken<? extends Throwable> type : throwables) {\n         Throwable throwable = Throwables2.getFirstThrowableOfType(exception, (Class<Throwable>) type.getRawType());\n         if (throwable != null) {\n            throw throwable;\n         }\n      }\n      for (Class<? extends Throwable> propagatableExceptionType : PROPAGATABLE_EXCEPTION_TYPES) {\n         Throwable throwable = Throwables2.getFirstThrowableOfType(exception, propagatableExceptionType);\n         if (throwable != null) {\n            throw throwable;\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/util/TypeTokenUtils.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.util;\n\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Type;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Throwables;\nimport com.google.common.reflect.TypeToken;\n\n@Beta\npublic final class TypeTokenUtils {\n   private static final Method IS_SUPERTYPE_OF_TYPE;\n   private static final Method IS_SUPERTYPE_OF_TYPETOKEN;\n   static {\n      Method isSuperTypeOfType;\n      Method isSuperTypeOfTypeToken;\n      try {\n         // Guava 19 and later method\n         isSuperTypeOfType = TypeToken.class.getDeclaredMethod(\"isSupertypeOf\", Type.class);\n         isSuperTypeOfTypeToken = TypeToken.class.getDeclaredMethod(\"isSupertypeOf\", TypeToken.class);\n      } catch (NoSuchMethodException nsme) {\n         try {\n            // Guava 18 and earlier method\n            isSuperTypeOfType = TypeToken.class.getDeclaredMethod(\"isAssignableFrom\", Type.class);\n            isSuperTypeOfTypeToken = TypeToken.class.getDeclaredMethod(\"isAssignableFrom\", TypeToken.class);\n         } catch (NoSuchMethodException nsme2) {\n            throw Throwables.propagate(nsme2);\n         }\n      }\n      IS_SUPERTYPE_OF_TYPE = isSuperTypeOfType;\n      IS_SUPERTYPE_OF_TYPETOKEN = isSuperTypeOfTypeToken;\n   }\n\n   private TypeTokenUtils() {\n      throw new AssertionError(\"intentionally not implemented\");\n   }\n\n   public static <C> boolean isSupertypeOf(TypeToken<C> token, Type type) {\n      try {\n         return (Boolean) IS_SUPERTYPE_OF_TYPE.invoke(token, type);\n      } catch (IllegalAccessException iae) {\n         throw Throwables.propagate(iae);\n      } catch (InvocationTargetException ite) {\n         throw Throwables.propagate(ite);\n      }\n   }\n\n   public static <C, D> boolean isSupertypeOf(TypeToken<C> token, TypeToken<D> token2) {\n      try {\n         return (Boolean) IS_SUPERTYPE_OF_TYPETOKEN.invoke(token, token2);\n      } catch (IllegalAccessException iae) {\n         throw Throwables.propagate(iae);\n      } catch (InvocationTargetException ite) {\n         throw Throwables.propagate(ite);\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/xml/XMLParser.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.xml;\n\nimport java.io.IOException;\n\nimport org.jclouds.xml.internal.JAXBParser;\n\nimport com.google.inject.ImplementedBy;\n\n/**\n * Parses XML documents.\n */\n@ImplementedBy(JAXBParser.class)\npublic interface XMLParser {\n   /** The default xml header. */\n   String DEFAULT_XML_HEADER = \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\" standalone=\\\"yes\\\"?>\";\n\n   /**\n    * Serialize the object into xml.\n    */\n   String toXML(Object src) throws IOException;\n\n   /**\n    * Serialize the object into xml, as the declared type.\n    */\n   <T> String toXML(Object src, Class<T> type) throws IOException;\n\n   /**\n    * Deserialize the object from xml.\n    */\n   <T> T fromXML(String xml, Class<T> type) throws IOException;\n\n}\n"
  },
  {
    "path": "core/src/main/java/org/jclouds/xml/internal/JAXBParser.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.xml.internal;\n\nimport java.io.IOException;\nimport java.io.StringReader;\nimport java.io.StringWriter;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\nimport jakarta.xml.bind.JAXBContext;\nimport jakarta.xml.bind.JAXBException;\nimport jakarta.xml.bind.Marshaller;\nimport jakarta.xml.bind.Unmarshaller;\n\nimport org.jclouds.Constants;\nimport org.jclouds.xml.XMLParser;\n\nimport com.google.inject.name.Named;\n\n/**\n * Parses XML documents using JAXB.\n * \n * @see ParseXMLWithJAXB\n */\n@Singleton\npublic class JAXBParser implements XMLParser {\n\n   /** Boolean indicating if the output must be pretty printed. */\n   private Boolean prettyPrint;\n\n   @Inject\n   public JAXBParser(@Named(Constants.PROPERTY_PRETTY_PRINT_PAYLOADS) String prettyPrint) {\n      super();\n      this.prettyPrint = Boolean.valueOf(prettyPrint);\n   }\n\n   @Override\n   public String toXML(final Object src) throws IOException {\n      return toXML(src, src.getClass());\n   }\n\n   @Override\n   public <T> String toXML(final Object src, final Class<T> type) throws IOException {\n      try {\n         JAXBContext context = JAXBContext.newInstance(type);\n         Marshaller marshaller = context.createMarshaller();\n         marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, prettyPrint);\n         StringWriter writer = new StringWriter();\n         marshaller.marshal(src, writer);\n         return writer.toString();\n      } catch (JAXBException ex) {\n         throw new IOException(\"Could not marshall object\", ex);\n      }\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <T> T fromXML(String xml, final Class<T> type) throws IOException {\n      // ignore byte order mark\n      if (xml.charAt(0) == 0xFEFF) {\n         xml = xml.substring(1);\n      }\n      try {\n         StringReader reader = new StringReader(xml);\n         JAXBContext context = JAXBContext.newInstance(type);\n         Unmarshaller unmarshaller = context.createUnmarshaller();\n         return (T) unmarshaller.unmarshal(reader);\n      } catch (Exception ex) {\n         throw new IOException(\"Could not unmarshal document into type: \" + type.getSimpleName() + \"\\n\" + xml, ex);\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/ContextBuilderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds;\n\nimport static com.google.common.base.Suppliers.ofInstance;\nimport static org.jclouds.providers.AnonymousProviderMetadata.forApiOnEndpoint;\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport org.jclouds.concurrent.config.ExecutorServiceModule;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.events.config.EventBusModule;\nimport org.jclouds.http.IntegrationTestClient;\nimport org.jclouds.http.config.ConfiguresHttpCommandExecutorService;\nimport org.jclouds.http.config.JavaUrlHttpCommandExecutorServiceModule;\nimport org.jclouds.location.Provider;\nimport org.jclouds.logging.config.LoggingModule;\nimport org.jclouds.logging.config.NullLoggingModule;\nimport org.jclouds.logging.jdk.config.JDKLoggingModule;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.rest.annotations.ApiVersion;\nimport org.jclouds.rest.config.CredentialStoreModule;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Lists;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Key;\nimport com.google.inject.Module;\nimport com.google.inject.TypeLiteral;\n\n/**\n * Tests behavior of modules configured in ContextBuilder\n */\n@Test(groups = \"unit\", testName = \"ContextBuilderTest\")\npublic class ContextBuilderTest {\n\n   @ConfiguresHttpCommandExecutorService\n   static class HttpModule extends AbstractModule {\n      protected void configure() {\n      }\n   }\n\n   private ContextBuilder testContextBuilder() {\n      return ContextBuilder.newBuilder(forApiOnEndpoint(IntegrationTestClient.class, \"http://localhost\"));\n   }\n\n   @Test\n   public void testVariablesReplaceOnEndpoint() {\n      ContextBuilder withVariablesToReplace = testContextBuilder().endpoint(\"http://${jclouds.identity}.service.com\")\n               .credentials(\"foo\", \"bar\");\n      URI endpoint = withVariablesToReplace.buildInjector().getInstance(\n               Key.get(new TypeLiteral<Supplier<URI>>(){}, Provider.class)).get();\n      assertEquals(endpoint, URI.create(\"http://foo.service.com\"));\n   }\n\n   @Test\n   public void testContextName() {\n     ContextBuilder withNoName = testContextBuilder().endpoint(\"http://${jclouds.identity}.service.com\").name(\"mytest\")\n              .credentials(\"foo\", \"bar\");\n     Context context = withNoName.build();\n     assertEquals(context.getName(), \"mytest\");\n   }\n\n   @Test\n   public void testProviderMetadataBoundWithCorrectEndpoint() {\n      ContextBuilder withVariablesToReplace = testContextBuilder().endpoint(\"http://${jclouds.identity}.service.com\")\n               .credentials(\"foo\", \"bar\");\n      String endpoint = withVariablesToReplace.buildInjector().getInstance(ProviderMetadata.class).getEndpoint();\n      assertEquals(endpoint, \"http://foo.service.com\");\n   }\n\n   @Test\n   public void testProviderMetadataWithEmptyIsoCodePropertyHasEmptySet() {\n      Properties overrides = new Properties();\n      overrides.setProperty(Constants.PROPERTY_ISO3166_CODES, \"\");\n      ContextBuilder withVariablesToReplace = testContextBuilder().overrides(overrides).credentials(\"foo\", \"bar\");\n      Set<String> codes = withVariablesToReplace.buildInjector().getInstance(ProviderMetadata.class).getIso3166Codes();\n      assertEquals(codes, ImmutableSet.<String> of());\n   }\n\n   @Test\n   public void testProviderMetadataWithCredentialsSetViaProperty() {\n      Properties overrides = new Properties();\n      overrides.setProperty(Constants.PROPERTY_IDENTITY, \"foo\");\n      overrides.setProperty(Constants.PROPERTY_CREDENTIAL, \"BAR\");\n      ContextBuilder withCredsInProps = testContextBuilder().overrides(overrides);\n      Credentials creds = withCredsInProps.buildInjector()\n            .getInstance(Key.get(new TypeLiteral<Supplier<Credentials>>() {\n            }, Provider.class)).get();\n      assertEquals(creds, new Credentials(\"foo\", \"BAR\"));\n   }\n\n   @Test\n   public void testProviderMetadataWithCredentialsSetSupplier() {\n      ContextBuilder withCredsSupplier = testContextBuilder().credentialsSupplier(\n            ofInstance(new Credentials(\"foo\", \"BAR\")));\n      Credentials creds = withCredsSupplier.buildInjector()\n            .getInstance(Key.get(new TypeLiteral<Supplier<Credentials>>() {\n            }, Provider.class)).get();\n      assertEquals(creds, new Credentials(\"foo\", \"BAR\"));\n   }\n   \n   @Test\n   public void testProviderMetadataWithVersionSetViaProperty() {\n      Properties overrides = new Properties();\n      overrides.setProperty(Constants.PROPERTY_API_VERSION, \"1.1\");\n      ContextBuilder withVersionInProps = testContextBuilder().overrides(overrides);\n      String version = withVersionInProps.buildInjector().getInstance(Key.get(String.class, ApiVersion.class));\n      assertEquals(version, \"1.1\");\n   }\n\n   @Test\n   public void testAllPropertiesAreStrings() {\n      Properties overrides = new Properties();\n      overrides.setProperty(\"foo\", \"bar\");\n      overrides.put(\"one\", 1);\n      overrides.put(\"two\", 2.0f);\n      overrides.put(\"true\", true);\n      overrides.put(\"object\", new Object() {\n         @Override\n         public String toString() {\n            return \"object\";\n         }\n      });\n      Context withObjectsInProps = testContextBuilder().overrides(overrides).build();\n      Properties resolved = withObjectsInProps.getProviderMetadata().getDefaultProperties();\n      assertEquals(resolved.getProperty(\"foo\"), \"bar\");\n      assertEquals(resolved.getProperty(\"one\"), \"1\");\n      assertEquals(resolved.getProperty(\"true\"), \"true\");\n      assertEquals(resolved.getProperty(\"object\"), \"object\");\n   }\n\n   @Test\n   public void testAddHttpModuleIfNotPresent() {\n      List<Module> modules = Lists.newArrayList();\n      HttpModule module = new HttpModule();\n      modules.add(module);\n      ContextBuilder.addHttpModuleIfNeededAndNotPresent(modules);\n      assertEquals(modules.size(), 1);\n      assertEquals(modules.remove(0), module);\n   }\n\n   @Test\n   public void testAddLoggingModuleIfNotPresent() {\n      List<Module> modules = Lists.newArrayList();\n      LoggingModule module = new NullLoggingModule();\n      modules.add(module);\n      ContextBuilder.addLoggingModuleIfNotPresent(modules);\n      assertEquals(modules.size(), 1);\n      assertEquals(modules.remove(0), module);\n   }\n   \n   @Test\n   public void testAddEventBusModuleIfNotPresent() {\n      List<Module> modules = Lists.newArrayList();\n      EventBusModule module = new EventBusModule();\n      modules.add(module);\n      ContextBuilder.addEventBusIfNotPresent(modules);\n      assertEquals(modules.size(), 1);\n      assertEquals(modules.remove(0), module);\n   }\n\n   @Test\n   public void testAddExecutorServiceModuleIfNotPresent() {\n      List<Module> modules = Lists.newArrayList();\n      ExecutorServiceModule module = new ExecutorServiceModule();\n      modules.add(module);\n      ContextBuilder.addExecutorServiceIfNotPresent(modules);\n      assertEquals(modules.size(), 1);\n      assertEquals(modules.remove(0), module);\n   }\n\n   @Test\n   public void testAddCredentialStoreModuleIfNotPresent() {\n      List<Module> modules = Lists.newArrayList();\n      CredentialStoreModule module = new CredentialStoreModule();\n      modules.add(module);\n      ContextBuilder.addCredentialStoreIfNotPresent(modules);\n      assertEquals(modules.size(), 1);\n      assertEquals(modules.remove(0), module);\n   }\n\n   @Test\n   public void testAddNone() {\n      List<Module> modules = Lists.newArrayList();\n      LoggingModule loggingModule = new NullLoggingModule();\n      modules.add(loggingModule);\n      HttpModule httpModule = new HttpModule();\n      modules.add(httpModule);\n      ContextBuilder.addHttpModuleIfNeededAndNotPresent(modules);\n      ContextBuilder.addLoggingModuleIfNotPresent(modules);\n      assertEquals(modules.size(), 2);\n      assertEquals(modules.remove(0), loggingModule);\n      assertEquals(modules.remove(0), httpModule);\n   }\n\n   @Test\n   public void testAddBothWhenDefault() {\n      List<Module> modules = Lists.newArrayList();\n      ContextBuilder.addHttpModuleIfNeededAndNotPresent(modules);\n      ContextBuilder.addLoggingModuleIfNotPresent(modules);\n      assertEquals(modules.size(), 2);\n      assert modules.remove(0) instanceof JavaUrlHttpCommandExecutorServiceModule;\n      assert modules.remove(0) instanceof JDKLoggingModule;\n   }\n\n   @Test\n   public void testAddBothWhenLive() {\n      List<Module> modules = Lists.newArrayList();\n      ContextBuilder.addHttpModuleIfNeededAndNotPresent(modules);\n      ContextBuilder.addLoggingModuleIfNotPresent(modules);\n      assertEquals(modules.size(), 2);\n      assert modules.remove(0) instanceof JavaUrlHttpCommandExecutorServiceModule;\n      assert modules.remove(0) instanceof JDKLoggingModule;\n   }\n\n   public void testBuilder() {\n\n      Module module1 = new AbstractModule() {\n         protected void configure() {\n         }\n      };\n      Module module2 = new AbstractModule() {\n         protected void configure() {\n         }\n      };\n      ContextBuilder builder = testContextBuilder();\n      builder.modules(Arrays.asList(module1, module2));\n\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/JcloudsVersionTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds;\n\nimport static org.jclouds.JcloudsVersion.VERSION_RESOURCE_FILE;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.InputStream;\nimport java.util.List;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Iterables;\n\n@Test(singleThreaded = true)\npublic class JcloudsVersionTest {\n\n    @Test(expectedExceptions = { NullPointerException.class })\n    public void testFailsIfResourceFileMissing() {\n        new JcloudsVersion(new ResourceHidingClassLoader(JcloudsVersion.class.getClassLoader(), \n                VERSION_RESOURCE_FILE));\n    }\n\n    @Test(expectedExceptions = { IllegalArgumentException.class })\n    public void testFailsIfInvalidVersion() {\n        new JcloudsVersion(\"${project.version}\");\n    }\n\n    @Test(expectedExceptions = { IllegalArgumentException.class })\n    public void testFailsIfNonSemverReleaseCandidate() {\n        // no longer supported after the 1.3.0 RC cycle\n        new JcloudsVersion(\"1.2.3-rc-4\");\n    }\n\n    @Test(expectedExceptions = { IllegalArgumentException.class })\n    public void testFailsIfIncubating() {\n        // no longer supported after graduation from the Apache Incubator\n        new JcloudsVersion(\"1.2.3-incubating\");\n    }\n\n    @Test(expectedExceptions = { IllegalArgumentException.class })\n    public void testFailsIfAlphaSnapshot() {\n        new JcloudsVersion(\"1.2.3-alpha.5-SNAPSHOT\");\n    }\n\n    @Test(expectedExceptions = { IllegalArgumentException.class })\n    public void testFailsIfBetaSnapshot() {\n        new JcloudsVersion(\"1.2.3-beta.5-SNAPSHOT\");\n    }\n\n    @Test(expectedExceptions = { IllegalArgumentException.class })\n    public void testFailsIfReleaseCandidateSnapshot() {\n        new JcloudsVersion(\"1.2.3-rc.4-SNAPSHOT\");\n    }\n\n    @Test(expectedExceptions = { IllegalArgumentException.class })\n    public void testFailsIfIncubatingSnapshot() {\n        new JcloudsVersion(\"1.2.3-incubating-SNAPSHOT\");\n    }\n\n    @Test(expectedExceptions = { IllegalArgumentException.class })\n    public void testFailsIfNumberedIncubating() {\n        new JcloudsVersion(\"1.2.3-incubating.1\");\n    }\n\n    @Test\n    public void testExtractsVersionFromResourceFile() {\n        JcloudsVersion version = new JcloudsVersion();\n        assertEquals(\"0.0.0-SNAPSHOT\", version.toString());\n    }\n\n    @Test\n    public void testExtractsMajorMinorPatchVersions() {\n        JcloudsVersion version = new JcloudsVersion(\"1.2.3\");\n        assertEquals(1, version.majorVersion);\n        assertEquals(2, version.minorVersion);\n        assertEquals(3, version.patchVersion);\n    }\n\n    @Test\n    public void testSupportsNonSnapshot() {\n        JcloudsVersion version = new JcloudsVersion(\"1.2.3\");\n        assertFalse(version.snapshot, \"Expected non-snapshot\");\n    }\n\n    @Test\n    public void testRecognisesSnapshot() {\n        JcloudsVersion version = new JcloudsVersion(\"1.2.3-SNAPSHOT\");\n        assertTrue(version.snapshot, \"Expected snapshot\");\n    }\n\n    @Test\n    public void testSupportsReleaseVersion() {\n        JcloudsVersion version = new JcloudsVersion(\"1.2.3\");\n        assertFalse(version.alpha, \"Expected non-alpha\");\n        assertFalse(version.beta, \"Expected non-beta\");\n        assertFalse(version.releaseCandidate, \"Expected non-release candidate\");\n        assertNull(version.alphaVersion);\n        assertNull(version.betaVersion);\n        assertNull(version.releaseCandidateVersion);\n    }\n\n    @Test\n    public void testRecognisesAlpha() {\n        JcloudsVersion version = new JcloudsVersion(\"1.2.3-alpha.5\");\n        assertTrue(version.alpha, \"Expected alpha\");\n    }\n\n    @Test\n    public void testExtractsAlphaVersion() {\n        JcloudsVersion version = new JcloudsVersion(\"1.2.3-alpha.5\");\n        assertEquals(Integer.valueOf(5), version.alphaVersion);\n    }\n\n    @Test\n    public void testRecognisesBeta() {\n        JcloudsVersion version = new JcloudsVersion(\"1.2.3-beta.5\");\n        assertTrue(version.beta, \"Expected beta\");\n    }\n\n    @Test\n    public void testExtractsBetaVersion() {\n        JcloudsVersion version = new JcloudsVersion(\"1.2.3-beta.5\");\n        assertEquals(Integer.valueOf(5), version.betaVersion);\n    }\n\n    @Test\n    public void testRecognisesReleaseCandidate() {\n        JcloudsVersion version = new JcloudsVersion(\"1.2.3-rc.4\");\n        assertTrue(version.releaseCandidate, \"Expected release candidate\");\n    }\n\n    @Test\n    public void testExtractsReleaseCandidateVersion() {\n        JcloudsVersion version = new JcloudsVersion(\"1.2.3-rc.4\");\n        assertEquals(Integer.valueOf(4), version.releaseCandidateVersion);\n    }\n\n    private static class ResourceHidingClassLoader extends ClassLoader {\n        private final ClassLoader delegate;\n        private final List<String> resourcesToHide;\n\n        private ResourceHidingClassLoader(ClassLoader delegate, String... resourcesToHide) {\n            this.delegate = delegate;\n            this.resourcesToHide = ImmutableList.copyOf(resourcesToHide);\n        }\n\n        @Override\n        public InputStream getResourceAsStream(String name) {\n            return Iterables.contains(resourcesToHide, name)\n                    ? null\n                    : delegate.getResourceAsStream(name);\n        }\n    }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/PerformanceTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds;\n\nimport static java.util.concurrent.Executors.defaultThreadFactory;\n\nimport java.util.List;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.CompletionService;\nimport java.util.concurrent.CountDownLatch;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.ExecutorCompletionService;\nimport java.util.concurrent.ExecutorService;\n\nimport org.jclouds.concurrent.DynamicExecutors;\nimport org.testng.annotations.AfterTest;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"performance\")\npublic abstract class PerformanceTest {\n   protected static int LOOP_COUNT = 1000;\n   protected static int THREAD_COUNT = 100;\n   protected ExecutorService exec;\n\n   @BeforeTest\n   public void setupExecutorService() {\n      exec = DynamicExecutors.newScalingThreadPool(1, THREAD_COUNT, 1000, defaultThreadFactory());\n   }\n\n   @AfterTest\n   public void teardownExecutorService() {\n      exec.shutdownNow();\n      exec = null;\n   }\n\n   /**\n    * Executes a list of Runnable tasks in {@link #THREAD_COUNT} simultaneous threads, and outputs\n    * the timing results.\n    * <p>\n    * This method is careful to time only the actual task execution time, not the overhead of\n    * creating and queuing the tasks. We also use CountDownLatches to ensure that all tasks start at\n    * the same time, so concurrency is fully tested without ramp-up or ramp-down times.\n    * <p>\n    * This code is heavily based on Listing 5.11 in \"Java Concurrency in Practice\" by Brian Goetz et\n    * al, Addison-Wesley Professional.\n    * \n    * @see {@link DateService} for example usage.\n    * \n    * @param performanceTestName\n    * @param tasks\n    * @throws InterruptedException\n    * @throws ExecutionException\n    * @throws Throwable\n    */\n   protected void executeMultiThreadedPerformanceTest(String performanceTestName,\n            List<Runnable> tasks) throws InterruptedException, ExecutionException, Throwable {\n      CompletionService<Throwable> completer = new ExecutorCompletionService<Throwable>(exec);\n      final CountDownLatch startGate = new CountDownLatch(1);\n      final CountDownLatch endGate = new CountDownLatch(THREAD_COUNT);\n\n      for (int i = 0; i < THREAD_COUNT; i++) {\n         final Runnable task = tasks.get(i % tasks.size());\n         // Wrap task so we can count down endGate.\n         completer.submit(new Callable<Throwable>() {\n            public Throwable call() {\n               try {\n                  startGate.await(); // Wait to start simultaneously\n                  task.run();\n                  return null;\n               } catch (Throwable t) {\n                  return t;\n               } finally {\n                  endGate.countDown(); // Notify that I've finished\n               }\n            }\n         });\n      }\n\n      // Only time the execution time for all tasks, not start/stop times.\n      long startTime = System.nanoTime();\n      startGate.countDown(); // Trigger start of all tasks\n      endGate.await();\n      long endTime = System.nanoTime() - startTime;\n\n      // Check for assertion failures\n      Throwable t;\n      for (int i = 0; i < THREAD_COUNT; i++) {\n         t = completer.take().get();\n         if (t != null) {\n            throw t;\n         }\n      }\n      if (performanceTestName != null) {\n         System.out.printf(\"TIMING: Multi-threaded %s took %.3fms for %d threads\\n\",\n                  performanceTestName, (double) endTime / 1000000, THREAD_COUNT);\n      }\n   }\n\n   protected void executeMultiThreadedCorrectnessTest(List<Runnable> tasks)\n            throws InterruptedException, ExecutionException, Throwable {\n      executeMultiThreadedPerformanceTest(null, tasks);\n   }\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/apis/ApisTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.apis;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.fail;\n\nimport java.util.NoSuchElementException;\n\nimport org.testng.annotations.Test;\n\n/**\n * The ApisTest tests the org.jclouds.apis.Apis class.\n */\n@Test(groups = \"unit\", testName = \"ApisTest\")\npublic class ApisTest {\n\n   private final JcloudsTestBlobStoreApiMetadata testBlobstoreApi = new JcloudsTestBlobStoreApiMetadata();\n   private final JcloudsTestComputeApiMetadata testComputeApi = new JcloudsTestComputeApiMetadata();\n   private final JcloudsTestYetAnotherComputeApiMetadata testYetAnotherComputeApi = new JcloudsTestYetAnotherComputeApiMetadata();\n\n   @Test\n   public void testWithId() {\n\n      ApiMetadata apiMetadata;\n      try {\n         apiMetadata = Apis.withId(\"fake-id\");\n         fail(\"Looking for a api with an id that doesn't exist should \" + \"throw an exception.\");\n      } catch (NoSuchElementException nsee) {\n         // expected\n      }\n\n      apiMetadata = Apis.withId(testBlobstoreApi.getId());\n\n      assertEquals(testBlobstoreApi, apiMetadata);\n   }\n\n   @Test\n   public void testTransformableTo() {\n      Iterable<ApiMetadata> apisMetadata = Apis.viewableAs(Storage.class);\n\n      for (ApiMetadata apiMetadata : apisMetadata) {\n         assertEquals(testBlobstoreApi, apiMetadata);\n      }\n\n      apisMetadata = Apis.viewableAs(Compute.class);\n\n      for (ApiMetadata apiMetadata : apisMetadata) {\n         if (apiMetadata.getName().equals(testComputeApi.getName())) {\n            assertEquals(testComputeApi, apiMetadata);\n         } else {\n            assertEquals(testYetAnotherComputeApi, apiMetadata);\n         }\n      }\n\n      apisMetadata = Apis.viewableAs(Balancer.class);\n\n      assertEquals(false, apisMetadata.iterator().hasNext());\n   }\n\n   @Test\n   public void testAll() {\n      Iterable<ApiMetadata> apisMetadata = Apis.all();\n\n      for (ApiMetadata apiMetadata : apisMetadata) {\n         if (apiMetadata.getName().equals(testBlobstoreApi.getName())) {\n            assertEquals(testBlobstoreApi, apiMetadata);\n         } else if (apiMetadata.getName().equals(testComputeApi.getName())) {\n            assertEquals(testComputeApi, apiMetadata);\n         } else {\n            assertEquals(testYetAnotherComputeApi, apiMetadata);\n         }\n      }\n   }\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/apis/Balancer.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.apis;\n\nimport org.jclouds.Context;\nimport org.jclouds.internal.BaseView;\nimport org.jclouds.location.Provider;\n\nimport com.google.common.reflect.TypeToken;\nimport com.google.inject.Inject;\n\n/**\n * For tests\n */\npublic class Balancer extends BaseView {\n\n   @Inject\n   public Balancer(@Provider Context ctx, @Provider TypeToken<? extends Context> inputType)  {\n      super(ctx, inputType);\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/apis/BaseApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.apis;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.Constants.PROPERTY_RELAX_HOSTNAME;\nimport static org.jclouds.Constants.PROPERTY_TRUST_ALL_CERTS;\nimport static org.jclouds.util.Closeables2.closeQuietly;\n\nimport java.io.Closeable;\nimport java.util.NoSuchElementException;\nimport java.util.Properties;\nimport java.util.Set;\nimport java.util.logging.Logger;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.logging.LoggingModules;\nimport org.jclouds.logging.config.LoggingModule;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.Providers;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\n\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Sets;\nimport com.google.common.reflect.TypeToken;\nimport com.google.inject.Module;\n\npublic abstract class BaseApiLiveTest<A extends Closeable> {\n   protected String prefix = System.getProperty(\"user.name\");\n   protected String provider;\n\n   protected volatile A api;\n\n   protected String identity;\n   protected String credential;\n   protected String endpoint;\n   protected String apiVersion;\n\n   protected Properties setupProperties() {\n      Properties overrides = new Properties();\n      overrides.setProperty(PROPERTY_TRUST_ALL_CERTS, \"true\");\n      overrides.setProperty(PROPERTY_RELAX_HOSTNAME, \"true\");\n      identity = setIfTestSystemPropertyPresent(overrides,  provider + \".identity\");\n      credential = setIfTestSystemPropertyPresent(overrides,  provider + \".credential\");\n      endpoint = setIfTestSystemPropertyPresent(overrides,  provider + \".endpoint\");\n      apiVersion = setIfTestSystemPropertyPresent(overrides,  provider + \".api-version\");\n      setIfTestSystemPropertyPresent(overrides,  provider + \".build-version\");\n      return overrides;\n   }\n\n   protected String setIfTestSystemPropertyPresent(Properties overrides, String key) {\n      if (System.getProperties().containsKey(\"test.\" + key)) {\n         String val = System.getProperty(\"test.\" + key);\n         overrides.setProperty(key, val);\n         return val;\n      }\n      return null;\n   }\n\n   protected String setIfTestSystemPropertyPresent(Properties overrides, String key, String defaultValue) {\n      String val = setIfTestSystemPropertyPresent(overrides, key);\n\n      if (val == null) {\n         val = defaultValue;\n         overrides.setProperty(key, val);\n      }\n\n      return val;\n   }\n\n   /**\n    * This helps live testing against specific regions only.\n    * @param regions A list of regions, usually from getConfiguredRegions()\n    * @return a set of regions in the given set that are also contained in the set specified by the test.live.regions system property\n    */\n   protected Set<String> filterRegions(Set<String> regions) {\n      String regionsToList = System.getProperty(\"test.live.regions\");\n      if (regionsToList == null) {\n         return regions; // no filter applied\n      }\n      Set<String> regionFilter = Sets.newHashSet(Splitter.on(',').split(regionsToList));\n      return Sets.intersection(regions, regionFilter);\n   }\n\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   public void setup() {\n      initialize();\n   }\n\n   protected void initialize() {\n      closeQuietly(api);\n      api = create(setupProperties(), setupModules());\n   }\n\n   protected Iterable<Module> setupModules() {\n      return ImmutableSet.<Module> of(getLoggingModule());\n   }\n\n   protected LoggingModule getLoggingModule() {\n      return LoggingModules.firstOrJDKLoggingModule();\n   }\n\n   /**\n    * @see org.jclouds.providers.Providers#withId\n    */\n   protected ProviderMetadata createProviderMetadata() {\n      try {\n         return Providers.withId(provider);\n      } catch (NoSuchElementException e) {\n         return null;\n      }\n   }\n\n   /**\n    * @see org.jclouds.apis.Apis#withId\n    */\n   protected ApiMetadata createApiMetadata() {\n      try {\n         return Apis.withId(provider);\n      } catch (NoSuchElementException e) {\n         return null;\n      }\n   }\n\n   @SuppressWarnings(\"serial\")\n   protected A create(Properties props, Iterable<Module> modules) {\n      return newBuilder().modules(modules).overrides(props).buildApi(new TypeToken<A>(getClass()) {\n      });\n   }\n\n   protected ContextBuilder newBuilder() {\n      if (provider != null)\n         try {\n            return ContextBuilder.newBuilder(provider);\n         } catch (NoSuchElementException e) {\n            Logger.getAnonymousLogger()\n                  .warning(\"provider [\"\n                        + provider\n                        + \"] is not setup as META-INF/services/org.jclouds.apis.ApiMetadata or META-INF/services/org.jclouds.providers.ProviderMetadata\");\n         }\n\n      ProviderMetadata pm = createProviderMetadata();\n\n      ContextBuilder builder = pm != null ? ContextBuilder.newBuilder(pm) : ContextBuilder\n            .newBuilder(ApiMetadata.class.cast(checkNotNull(createApiMetadata(),\n                  \"either createApiMetadata or createProviderMetadata must be overridden\")));\n      return builder;\n   }\n\n   @AfterClass(groups = { \"integration\", \"live\" })\n   protected void tearDown() {\n      closeQuietly(api);\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/apis/BaseContextLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.apis;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.NoSuchElementException;\nimport java.util.Properties;\nimport java.util.logging.Logger;\n\nimport org.jclouds.Constants;\nimport org.jclouds.Context;\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.logging.LoggingModules;\nimport org.jclouds.logging.config.LoggingModule;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.Providers;\nimport org.jclouds.util.Closeables2;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.reflect.TypeToken;\nimport com.google.inject.Module;\n\npublic abstract class BaseContextLiveTest<C extends Context> {\n   protected String prefix = System.getProperty(\"user.name\");\n   protected String provider;\n\n   protected volatile C context;\n\n   protected String identity;\n   protected String credential;\n   protected String endpoint;\n   protected String apiVersion;\n\n   protected Properties setupProperties() {\n      Properties overrides = new Properties();\n      overrides.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, \"true\");\n      overrides.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, \"true\");\n      identity = setIfTestSystemPropertyPresent(overrides,  provider + \".identity\");\n      credential = setIfTestSystemPropertyPresent(overrides,  provider + \".credential\");\n      endpoint = setIfTestSystemPropertyPresent(overrides,  provider + \".endpoint\");\n      apiVersion = setIfTestSystemPropertyPresent(overrides,  provider + \".api-version\");\n      setIfTestSystemPropertyPresent(overrides,  provider + \".build-version\");\n      return overrides;\n   }\n\n   protected String setIfTestSystemPropertyPresent(Properties overrides, String key) {\n      if (System.getProperties().containsKey(\"test.\" + key)) {\n         String val = System.getProperty(\"test.\" + key);\n         overrides.setProperty(key, val);\n         return val;\n      }\n      return null;\n   }\n\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   public void setupContext() {\n      initializeContext();\n   }\n\n   protected void initializeContext() {\n      Closeables2.closeQuietly(context);\n      context = createContext(setupProperties(), setupModules());\n   }\n\n   protected Iterable<Module> setupModules() {\n      return ImmutableSet.<Module> of(getLoggingModule());\n   }\n\n   protected LoggingModule getLoggingModule() {\n      return LoggingModules.firstOrJDKLoggingModule();\n   }\n\n   /**\n    * @see org.jclouds.providers.Providers#withId\n    */\n   protected ProviderMetadata createProviderMetadata() {\n      try {\n         return Providers.withId(provider);\n      } catch (NoSuchElementException e) {\n         return null;\n      }\n   }\n   \n   /**\n    * @see org.jclouds.apis.Apis#withId\n    */\n   protected ApiMetadata createApiMetadata() {\n      try {\n         return Apis.withId(provider);\n      } catch (NoSuchElementException e) {\n         return null;\n      }\n   }\n   \n   protected abstract TypeToken<C> contextType();\n   \n   protected C createContext(Properties props, Iterable<Module> modules) {\n      return newBuilder().modules(modules).overrides(props).build(contextType());\n   }\n\n   protected ContextBuilder newBuilder() {\n      if (provider != null)\n         try {\n            return ContextBuilder.newBuilder(provider);\n         } catch (NoSuchElementException e) {\n            Logger.getAnonymousLogger()\n                  .warning(\"provider [\"\n                        + provider\n                        + \"] is not setup as META-INF/services/org.jclouds.apis.ApiMetadata or META-INF/services/org.jclouds.providers.ProviderMetadata\");\n         }\n\n      ProviderMetadata pm = createProviderMetadata();\n\n      ContextBuilder builder = pm != null ? ContextBuilder.newBuilder(pm) : ContextBuilder\n            .newBuilder(ApiMetadata.class.cast(checkNotNull(createApiMetadata(),\n                  \"either createApiMetadata or createProviderMetadata must be overridden\")));\n      return builder;\n   }\n   \n   @AfterClass(groups = { \"integration\", \"live\" })\n   protected void tearDownContext() {\n      Closeables2.closeQuietly(context);\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/apis/BaseViewLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.apis;\n\nimport static org.jclouds.reflect.Reflection2.typeToken;\n\nimport java.util.Properties;\n\nimport org.jclouds.Context;\nimport org.jclouds.View;\nimport org.jclouds.util.Closeables2;\n\nimport com.google.common.reflect.TypeToken;\nimport com.google.inject.Module;\n\npublic abstract class BaseViewLiveTest<V extends View> extends BaseContextLiveTest<Context> {\n\n   protected volatile V view;\n\n   @Override\n   protected void initializeContext() {\n      Closeables2.closeQuietly(context);\n      view = createView(setupProperties(), setupModules());\n      context = view.unwrap();\n   }\n\n   protected abstract TypeToken<V> viewType();\n   \n   @Override\n   protected TypeToken<Context> contextType() {\n     return typeToken(Context.class);\n   }\n   \n   protected V createView(Properties props, Iterable<Module> modules) {\n      return newBuilder().modules(modules).overrides(props).buildView(viewType());\n   }\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/apis/Compute.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.apis;\n\nimport com.google.inject.Inject;\nimport org.jclouds.Context;\nimport org.jclouds.internal.BaseView;\nimport org.jclouds.location.Provider;\n\nimport com.google.common.reflect.TypeToken;\n\n/**\n * For tests\n */\npublic class Compute extends BaseView {\n\n   @Inject\n   public Compute(@Provider Context ctx, @Provider TypeToken<? extends Context> inputType)  {\n      super(ctx, inputType);\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/apis/JcloudsTestBlobStoreApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.apis;\n\nimport java.net.URI;\n\nimport org.jclouds.http.IntegrationTestClient;\nimport org.jclouds.rest.internal.BaseHttpApiMetadata;\n\nimport com.google.auto.service.AutoService;\n\n/**\n * Implementation of {@link ApiMetadata} for testing.\n */\n@AutoService(ApiMetadata.class)\npublic class JcloudsTestBlobStoreApiMetadata extends BaseHttpApiMetadata<IntegrationTestClient> {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return Builder.class.cast(builder().fromApiMetadata(this));\n   }\n\n   public JcloudsTestBlobStoreApiMetadata() {\n      super(builder());\n   }\n\n   protected JcloudsTestBlobStoreApiMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static class Builder extends BaseHttpApiMetadata.Builder<IntegrationTestClient, Builder> {\n\n      protected Builder() {\n         super(IntegrationTestClient.class);\n         id(\"test-blobstore-api\")\n         .view(Storage.class)\n         .name(\"Test Blobstore Api\")\n         .identityName(\"user\")\n         .credentialName(\"password\")\n         .documentation(URI.create(\"http://jclouds.org/documentation\"));\n      }\n\n      @Override\n      public JcloudsTestBlobStoreApiMetadata build() {\n         return new JcloudsTestBlobStoreApiMetadata(this);\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/apis/JcloudsTestComputeApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.apis;\n\nimport java.net.URI;\n\nimport org.jclouds.http.IntegrationTestClient;\nimport org.jclouds.rest.internal.BaseHttpApiMetadata;\n\nimport com.google.auto.service.AutoService;\n\n/**\n * Implementation of {@link ApiMetadata} for testing.\n */\n@AutoService(ApiMetadata.class)\npublic class JcloudsTestComputeApiMetadata extends BaseHttpApiMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return Builder.class.cast(builder().fromApiMetadata(this));\n   }\n\n   public JcloudsTestComputeApiMetadata() {\n      super(builder());\n   }\n\n   protected JcloudsTestComputeApiMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static class Builder extends BaseHttpApiMetadata.Builder<IntegrationTestClient, Builder> {\n\n      protected Builder() {\n         super(IntegrationTestClient.class);\n         id(\"test-compute-api\")\n         .view(Compute.class)\n         .name(\"Test Compute Api\")\n         .identityName(\"user\")\n         .credentialName(\"password\")\n         .documentation(URI.create(\"http://jclouds.org/documentation\"));\n      }\n\n      @Override\n      public JcloudsTestComputeApiMetadata build() {\n         return new JcloudsTestComputeApiMetadata(this);\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/apis/JcloudsTestYetAnotherComputeApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.apis;\n\nimport java.net.URI;\n\nimport org.jclouds.http.IntegrationTestClient;\nimport org.jclouds.rest.internal.BaseHttpApiMetadata;\n\nimport com.google.auto.service.AutoService;\n\n/**\n * Implementation of {@link ApiMetadata} for testing.\n */\n@AutoService(ApiMetadata.class)\npublic class JcloudsTestYetAnotherComputeApiMetadata extends BaseHttpApiMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return Builder.class.cast(builder().fromApiMetadata(this));\n   }\n\n   public JcloudsTestYetAnotherComputeApiMetadata() {\n      super(builder());\n   }\n\n   protected JcloudsTestYetAnotherComputeApiMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static class Builder extends BaseHttpApiMetadata.Builder<IntegrationTestClient, Builder>  {\n\n      protected Builder() {\n         super(IntegrationTestClient.class);\n         id(\"test-yet-another-compute-api\")\n         .view(Compute.class)\n         .name(\"Test Yet Another Compute Api\")\n         .identityName(\"user\")\n         .credentialName(\"password\")\n         .documentation(URI.create(\"http://jclouds.org/documentation\"));\n      }\n\n      @Override\n      public JcloudsTestYetAnotherComputeApiMetadata build() {\n         return new JcloudsTestYetAnotherComputeApiMetadata(this);\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/apis/Storage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.apis;\n\nimport org.jclouds.Context;\nimport org.jclouds.internal.BaseView;\nimport org.jclouds.location.Provider;\n\nimport com.google.common.reflect.TypeToken;\nimport com.google.inject.Inject;\n\n/**\n * For tests\n */\npublic class Storage extends BaseView {\n\n   @Inject\n   public Storage(@Provider Context ctx, @Provider TypeToken<? extends Context> inputType)  {\n      super(ctx, inputType);\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/apis/internal/BaseApiMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.apis.internal;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Set;\n\nimport org.jclouds.View;\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.apis.Apis;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.reflect.TypeToken;\n\n@Test(groups = \"unit\")\npublic abstract class BaseApiMetadataTest {\n\n   protected final ApiMetadata toTest;\n   protected final Set<TypeToken<? extends View>> views;\n\n   public BaseApiMetadataTest(ApiMetadata toTest, Set<TypeToken<? extends View>> views) {\n      this.toTest = toTest;\n      this.views = views;\n   }\n\n   @Test\n   public void testWithId() {\n      ApiMetadata apiMetadata = Apis.withId(toTest.getId());\n\n      assertEquals(toTest, apiMetadata);\n   }\n\n   // it is ok to have multiple services in the same classpath (ex. ec2 vs elb)\n   @Test\n   public void testTransformableToContains() {\n      for (TypeToken<? extends View> view : views) {\n         ImmutableSet<ApiMetadata> ofType = ImmutableSet.copyOf(Apis.viewableAs(view));\n         assert ofType.contains(toTest) : String.format(\"%s not found in %s for %s\", toTest, ofType,\n                  view);\n      }\n   }\n\n   @Test\n   public void testAllContains() {\n      ImmutableSet<ApiMetadata> all = ImmutableSet.copyOf(Apis.all());\n      assert all.contains(toTest) : String.format(\"%s not found in %s\", toTest, all);\n   }\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/collect/AdvanceUntilEmptyIterableTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.collect;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\n\nimport org.easymock.EasyMock;\nimport org.testng.Assert;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code AdvanceUntilEmptyIterable}.\n */\n@Test(testName = \"AdvanceUntilEmptyIterableTest\")\npublic class AdvanceUntilEmptyIterableTest {\n\n   @SuppressWarnings(\"unchecked\")\n   @Test\n   public void testSinglePageResultReturnsSame() {\n\n      FluentIterable<String> initial = FluentIterable.from(ImmutableSet.of(\"foo\", \"bar\"));\n      Supplier<FluentIterable<String>> nextIterable = createMock(Supplier.class);\n      expect(nextIterable.get()).andReturn(initial);\n\n      EasyMock.replay(nextIterable);\n\n      AdvanceUntilEmptyIterable<String> iterable = new AdvanceUntilEmptyIterable<String>(nextIterable);\n\n      Assert.assertSame(iterable.get(0), initial);\n\n      EasyMock.verify(nextIterable);\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Test\n   public void testConcatStopsWhenEmpty() {\n\n      Supplier<FluentIterable<String>> nextIterable = createMock(Supplier.class);\n\n      expect(nextIterable.get()).andReturn(FluentIterable.from(ImmutableSet.of(\"foo\", \"bar\")));\n      expect(nextIterable.get()).andReturn(FluentIterable.from(ImmutableSet.of(\"boo\", \"baz\")));\n\n      expect(nextIterable.get()).andReturn(FluentIterable.from(ImmutableSet.of(\"ham\", \"cheeze\")));\n      expect(nextIterable.get()).andReturn(FluentIterable.from(ImmutableSet.<String>of()));\n\n      EasyMock.replay(nextIterable);\n\n      AdvanceUntilEmptyIterable<String> iterable = new AdvanceUntilEmptyIterable<String>(nextIterable);\n\n      Assert.assertEquals(iterable.concat().toSet(),\n            ImmutableSet.of(\"foo\", \"bar\", \"boo\", \"baz\", \"ham\", \"cheeze\"));\n\n      EasyMock.verify(nextIterable);\n\n   }\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/collect/IterableWithMarkersTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.collect;\n\nimport org.testng.Assert;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code IterableWithMarkers}.\n */\n@Test(testName = \"IterableWithMarkersTest\")\npublic class IterableWithMarkersTest {\n\n   @Test\n   public void testElementsEqual() {\n\n      IterableWithMarker<String> initial = IterableWithMarkers.from(ImmutableSet.of(\"foo\", \"bar\"));\n      Assert.assertEquals(initial.toSet(), ImmutableSet.of(\"foo\", \"bar\"));\n      Assert.assertEquals(initial.nextMarker(), Optional.absent());\n   }\n\n   @Test\n   public void testMarkerEqual() {\n\n      IterableWithMarker<String> initial = IterableWithMarkers.from(ImmutableSet.of(\"foo\", \"bar\"), \"MARKER\");\n      Assert.assertEquals(initial.toSet(), ImmutableSet.of(\"foo\", \"bar\"));\n      Assert.assertEquals(initial.nextMarker(), Optional.of(\"MARKER\"));\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/collect/PagedIterablesTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.collect;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\n\nimport org.easymock.EasyMock;\nimport org.testng.Assert;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code IterableWithMarkers}.\n */\n@Test(testName = \"PagedIterablesTest\")\npublic class PagedIterablesTest {\n\n   @SuppressWarnings(\"unchecked\")\n   @Test\n   public void testSinglePageResultReturnsSame() {\n\n      IterableWithMarker<String> initial = IterableWithMarkers.from(ImmutableSet.of(\"foo\", \"bar\"));\n      Function<Object, IterableWithMarker<String>> markerToNext = createMock(Function.class);\n\n      EasyMock.replay(markerToNext);\n\n      PagedIterable<String> iterable = PagedIterables.advance(initial, markerToNext);\n\n      Assert.assertSame(iterable.get(0), initial);\n\n      EasyMock.verify(markerToNext);\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Test\n   public void testConcatPage3Pages() {\n\n      IterableWithMarker<String> initial = IterableWithMarkers.from(ImmutableSet.of(\"foo\", \"bar\"), \"MARKER1\");\n      Function<Object, IterableWithMarker<String>> markerToNext = createMock(Function.class);\n\n      expect(markerToNext.apply(\"MARKER1\")).andReturn(\n               IterableWithMarkers.from(ImmutableSet.of(\"boo\", \"baz\"), \"MARKER2\"));\n\n      expect(markerToNext.apply(\"MARKER2\")).andReturn(IterableWithMarkers.from(ImmutableSet.of(\"ham\", \"cheeze\"), null));\n\n      EasyMock.replay(markerToNext);\n\n      PagedIterable<String> iterable = PagedIterables.advance(initial, markerToNext);\n\n      Assert.assertEquals(iterable.concat().toSet(),\n               ImmutableSet.of(\"foo\", \"bar\", \"boo\", \"baz\", \"ham\", \"cheeze\"));\n\n      EasyMock.verify(markerToNext);\n\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/collect/internal/Arg0ToPagedIterableTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.collect.internal;\n\nimport static com.google.common.base.Throwables.propagate;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.fail;\n\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.IterableWithMarkers;\nimport org.jclouds.reflect.Invocation;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Functions;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.reflect.Invokable;\n\n@Test(testName = \"Arg0ToPagedIterableTest\")\npublic class Arg0ToPagedIterableTest {\n\n   private abstract static class TestArg0 extends Arg0ToPagedIterable<String, TestArg0> {\n      private TestArg0(GeneratedHttpRequest in) {\n         this.setContext(in);\n      }\n   }\n\n   @Test\n   public void testWhenNextMarkerAbsentDoesntAdvance() {\n      GeneratedHttpRequest request = args(ImmutableList.of());\n\n      TestArg0 converter = new TestArg0(request) {\n\n         @Override\n         protected Function<Object, IterableWithMarker<String>> markerToNextForArg0(Optional<Object> arg0) {\n            fail(\"The Iterable should not advance\");\n            return null;\n         }\n\n      };\n\n      assertEquals(converter.apply(IterableWithMarkers.from(ImmutableSet.of(\"foo\", \"bar\"))).concat().toSet(),\n            ImmutableSet.of(\"foo\", \"bar\"));\n   }\n\n   @Test\n   public void testWhenNextMarkerPresentButNoArgsMarkerToNextForArg0ParamIsAbsent() {\n      GeneratedHttpRequest request = args(ImmutableList.of());\n      final IterableWithMarker<String> next = IterableWithMarkers.from(ImmutableSet.of(\"baz\"));\n\n      TestArg0 converter = new TestArg0(request) {\n\n         @Override\n         protected Function<Object, IterableWithMarker<String>> markerToNextForArg0(Optional<Object> arg0) {\n            assertEquals(arg0, Optional.absent());\n            return Functions.constant(next);\n         }\n\n      };\n\n      assertEquals(converter.apply(IterableWithMarkers.from(ImmutableSet.of(\"foo\", \"bar\"), \"marker\")).concat().toSet(),\n            ImmutableSet.of(\"foo\", \"bar\", \"baz\"));\n   }\n\n   @Test\n   public void testWhenNextMarkerPresentWithArgsMarkerToNextForArg0ParamIsPresent() {\n      GeneratedHttpRequest request = args(ImmutableList.<Object> of(\"path\"));\n      final IterableWithMarker<String> next = IterableWithMarkers.from(ImmutableSet.of(\"baz\"));\n\n      TestArg0 converter = new TestArg0(request) {\n\n         @Override\n         protected Function<Object, IterableWithMarker<String>> markerToNextForArg0(Optional<Object> arg0) {\n            assertEquals(arg0, Optional.of(\"path\"));\n            return Functions.constant(next);\n         }\n\n      };\n\n      assertEquals(converter.apply(IterableWithMarkers.from(ImmutableSet.of(\"foo\", \"bar\"), \"marker\")).concat().toSet(),\n            ImmutableSet.of(\"foo\", \"bar\", \"baz\"));\n   }\n\n   private GeneratedHttpRequest args(ImmutableList<Object> args) {\n      try {\n         return GeneratedHttpRequest.builder().method(\"GET\").endpoint(\"http://localhost\")\n               .invocation(Invocation.create(Invokable.from(String.class.getMethod(\"toString\")), args)).build();\n      } catch (Exception e) {\n         throw propagate(e);\n      }\n   }\n\n   private abstract static class TestCallerArg0 extends Arg0ToPagedIterable.FromCaller<String, TestCallerArg0> {\n      private TestCallerArg0(GeneratedHttpRequest in) {\n         this.setContext(in);\n      }\n   }\n\n   @Test\n   public void testFromCallerWhenNextMarkerPresentButNoArgsMarkerToNextForArg0ParamIsAbsent() {\n      GeneratedHttpRequest request = callerArgs(ImmutableList.of());\n      final IterableWithMarker<String> next = IterableWithMarkers.from(ImmutableSet.of(\"baz\"));\n\n      TestCallerArg0 converter = new TestCallerArg0(request) {\n\n         @Override\n         protected Function<Object, IterableWithMarker<String>> markerToNextForArg0(Optional<Object> arg0) {\n            assertEquals(arg0, Optional.absent());\n            return Functions.constant(next);\n         }\n\n      };\n\n      assertEquals(converter.apply(IterableWithMarkers.from(ImmutableSet.of(\"foo\", \"bar\"), \"marker\")).concat().toSet(),\n            ImmutableSet.of(\"foo\", \"bar\", \"baz\"));\n   }\n\n   @Test\n   public void testFromCallerWhenNextMarkerPresentWithArgsMarkerToNextForArg0ParamIsPresent() {\n      GeneratedHttpRequest request = callerArgs(ImmutableList.<Object> of(\"path\"));\n      final IterableWithMarker<String> next = IterableWithMarkers.from(ImmutableSet.of(\"baz\"));\n\n      TestCallerArg0 converter = new TestCallerArg0(request) {\n\n         @Override\n         protected Function<Object, IterableWithMarker<String>> markerToNextForArg0(Optional<Object> arg0) {\n            assertEquals(arg0, Optional.of(\"path\"));\n            return Functions.constant(next);\n         }\n\n      };\n\n      assertEquals(converter.apply(IterableWithMarkers.from(ImmutableSet.of(\"foo\", \"bar\"), \"marker\")).concat().toSet(),\n            ImmutableSet.of(\"foo\", \"bar\", \"baz\"));\n   }\n\n   private GeneratedHttpRequest callerArgs(ImmutableList<Object> args) {\n      try {\n         return GeneratedHttpRequest.builder().method(\"GET\").endpoint(\"http://localhost\")\n               .invocation(Invocation.create(Invokable.from(String.class.getMethod(\"toString\"))))\n               .caller(Invocation.create(Invokable.from(String.class.getMethod(\"toString\")), args)).build();\n      } catch (Exception e) {\n         throw propagate(e);\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/collect/internal/ArgsToPagedIterableTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.collect.internal;\n\nimport static com.google.common.base.Throwables.propagate;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.Assert.fail;\n\nimport java.util.List;\n\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.IterableWithMarkers;\nimport org.jclouds.reflect.Invocation;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Functions;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.reflect.Invokable;\n\n@Test(testName = \"ArgsToPagedIterableTest\")\npublic class ArgsToPagedIterableTest {\n\n   private abstract static class TestArgs extends ArgsToPagedIterable<String, TestArgs> {\n      private TestArgs(GeneratedHttpRequest in) {\n         this.setContext(in);\n      }\n   }\n\n   @Test\n   public void testWhenNextMarkerAbsentDoesntAdvance() {\n      GeneratedHttpRequest request = args(ImmutableList.of());\n\n      TestArgs converter = new TestArgs(request) {\n\n         @Override\n         protected Function<Object, IterableWithMarker<String>> markerToNextForArgs(List<Object> args) {\n            fail(\"The Iterable should not advance\");\n            return null;\n         }\n\n      };\n\n      assertEquals(converter.apply(IterableWithMarkers.from(ImmutableSet.of(\"foo\", \"bar\"))).concat().toSet(),\n            ImmutableSet.of(\"foo\", \"bar\"));\n   }\n\n   @Test\n   public void testWhenNextMarkerPresentButNoArgsMarkerToNextForArgsParamIsAbsent() {\n      GeneratedHttpRequest request = args(ImmutableList.of());\n      final IterableWithMarker<String> next = IterableWithMarkers.from(ImmutableSet.of(\"baz\"));\n\n      TestArgs converter = new TestArgs(request) {\n\n         @Override\n         protected Function<Object, IterableWithMarker<String>> markerToNextForArgs(List<Object> args) {\n            assertTrue(args.isEmpty());\n            return Functions.constant(next);\n         }\n\n      };\n\n      assertEquals(converter.apply(IterableWithMarkers.from(ImmutableSet.of(\"foo\", \"bar\"), \"marker\")).concat().toSet(),\n            ImmutableSet.of(\"foo\", \"bar\", \"baz\"));\n   }\n\n   @Test\n   public void testWhenNextMarkerPresentWithArgsMarkerToNextForArgsParamIsPresent() {\n      GeneratedHttpRequest request = args(ImmutableList.<Object> of(\"path\"));\n      final IterableWithMarker<String> next = IterableWithMarkers.from(ImmutableSet.of(\"baz\"));\n\n      TestArgs converter = new TestArgs(request) {\n\n         @Override\n         protected Function<Object, IterableWithMarker<String>> markerToNextForArgs(List<Object> args) {\n            assertEquals(args.get(0), \"path\");\n            return Functions.constant(next);\n         }\n\n      };\n\n      assertEquals(converter.apply(IterableWithMarkers.from(ImmutableSet.of(\"foo\", \"bar\"), \"marker\")).concat().toSet(),\n            ImmutableSet.of(\"foo\", \"bar\", \"baz\"));\n   }\n\n   private GeneratedHttpRequest args(ImmutableList<Object> args) {\n      try {\n         return GeneratedHttpRequest.builder().method(\"GET\").endpoint(\"http://localhost\")\n               .invocation(Invocation.create(Invokable.from(String.class.getMethod(\"toString\")), args)).build();\n      } catch (Exception e) {\n         throw propagate(e);\n      }\n   }\n\n   private abstract static class TestCallerArgs extends ArgsToPagedIterable.FromCaller<String, TestCallerArgs> {\n      private TestCallerArgs(GeneratedHttpRequest in) {\n         this.setContext(in);\n      }\n   }\n\n   @Test\n   public void testFromCallerWhenNextMarkerPresentButNoArgsMarkerToNextForArgsParamIsAbsent() {\n      GeneratedHttpRequest request = callerArgs(ImmutableList.of());\n      final IterableWithMarker<String> next = IterableWithMarkers.from(ImmutableSet.of(\"baz\"));\n\n      TestCallerArgs converter = new TestCallerArgs(request) {\n\n         @Override\n         protected Function<Object, IterableWithMarker<String>> markerToNextForArgs(List<Object> args) {\n            assertTrue(args.isEmpty());\n            return Functions.constant(next);\n         }\n\n      };\n\n      assertEquals(converter.apply(IterableWithMarkers.from(ImmutableSet.of(\"foo\", \"bar\"), \"marker\")).concat().toSet(),\n            ImmutableSet.of(\"foo\", \"bar\", \"baz\"));\n   }\n\n   @Test\n   public void testFromCallerWhenNextMarkerPresentWithArgsMarkerToNextForArgsParamIsPresent() {\n      GeneratedHttpRequest request = callerArgs(ImmutableList.<Object> of(\"path\"));\n      final IterableWithMarker<String> next = IterableWithMarkers.from(ImmutableSet.of(\"baz\"));\n\n      TestCallerArgs converter = new TestCallerArgs(request) {\n\n         @Override\n         protected Function<Object, IterableWithMarker<String>> markerToNextForArgs(List<Object> args) {\n            assertEquals(args.get(0), \"path\");\n            return Functions.constant(next);\n         }\n\n      };\n\n      assertEquals(converter.apply(IterableWithMarkers.from(ImmutableSet.of(\"foo\", \"bar\"), \"marker\")).concat().toSet(),\n            ImmutableSet.of(\"foo\", \"bar\", \"baz\"));\n   }\n\n   private GeneratedHttpRequest callerArgs(ImmutableList<Object> args) {\n      try {\n         return GeneratedHttpRequest.builder().method(\"GET\").endpoint(\"http://localhost\")\n               .invocation(Invocation.create(Invokable.from(String.class.getMethod(\"toString\"))))\n               .caller(Invocation.create(Invokable.from(String.class.getMethod(\"toString\")), args)).build();\n      } catch (Exception e) {\n         throw propagate(e);\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/concurrent/DynamicThreadPoolExecutorTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.concurrent;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.Future;\nimport java.util.concurrent.RejectedExecutionException;\nimport java.util.concurrent.RejectedExecutionHandler;\nimport java.util.concurrent.ThreadFactory;\nimport java.util.concurrent.ThreadPoolExecutor;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.TimeoutException;\nimport java.util.concurrent.atomic.AtomicInteger;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.util.concurrent.ThreadFactoryBuilder;\nimport com.google.common.util.concurrent.Uninterruptibles;\n\npublic class DynamicThreadPoolExecutorTest {\n\n   @Test\n   public void testTasksAreEnqueuedIfQueueFull() throws InterruptedException, ExecutionException, TimeoutException {\n      DynamicThreadPoolExecutor executor = newExecutor(new DynamicThreadPoolExecutor.ForceQueuePolicy());\n      try {\n         List<Task> tasks = ImmutableList.of(new Task(2), new Task(2), new Task(2), new Task(2));\n         List<Future<?>> futures = new ArrayList<Future<?>>();\n         for (Task task : tasks) {\n            futures.add(executor.submit(task));\n         }\n\n         for (Future<?> future : futures) {\n            future.get(5, TimeUnit.SECONDS);\n         }\n      } finally {\n         executor.shutdownNow();\n      }\n   }\n\n   @Test(expectedExceptions = RejectedExecutionException.class)\n   public void testTasksAreRejectedIfQueueFull() throws InterruptedException, ExecutionException, TimeoutException {\n      DynamicThreadPoolExecutor executor = newExecutor(new ThreadPoolExecutor.AbortPolicy());\n      try {\n         for (int i = 0; i < executor.getMaximumPoolSize() + 4; i++) {\n            executor.submit(new Task(2));\n         }\n      } finally {\n         executor.shutdownNow();\n      }\n   }\n\n   @Test\n   public void testTasksWaitForSpaceIfQueueFull() throws InterruptedException, ExecutionException, TimeoutException {\n      DynamicThreadPoolExecutor executor = newExecutor(new DynamicThreadPoolExecutor.TimedBlockingPolicy(5000));\n      try {\n         List<Task> tasks = ImmutableList.of(new Task(2), new Task(2), new Task(2), new Task(2));\n         List<Future<?>> futures = new ArrayList<Future<?>>();\n         for (Task task : tasks) {\n            futures.add(executor.submit(task));\n         }\n\n         for (Future<?> future : futures) {\n            future.get(5, TimeUnit.SECONDS);\n         }\n      } finally {\n         executor.shutdownNow();\n      }\n   }\n\n   @Test(expectedExceptions = RejectedExecutionException.class)\n   public void testTasksAreRejectedIfExecutorIsShutdownAndPolicyIsForce() throws InterruptedException,\n         ExecutionException, TimeoutException {\n      DynamicThreadPoolExecutor executor = newExecutor(new DynamicThreadPoolExecutor.ForceQueuePolicy());\n      try {\n         executor.submit(new Task(2));\n         executor.shutdown();\n         executor.submit(new Task(2));\n      } finally {\n         executor.shutdownNow();\n      }\n   }\n\n   @Test(expectedExceptions = RejectedExecutionException.class)\n   public void testTasksAreRejectedIfExecutorIsShutdownAndPolicyIsWait() throws InterruptedException,\n         ExecutionException, TimeoutException {\n      DynamicThreadPoolExecutor executor = newExecutor(new DynamicThreadPoolExecutor.TimedBlockingPolicy(5000));\n      try {\n         executor.submit(new Task(2));\n         executor.shutdown();\n         executor.submit(new Task(2));\n      } finally {\n         executor.shutdownNow();\n      }\n   }\n\n   private static class Task implements Runnable {\n      private final AtomicInteger executions;\n\n      public Task(int executions) {\n         this.executions = new AtomicInteger(executions);\n      }\n\n      @Override\n      public void run() {\n         while (executions.decrementAndGet() >= 0) {\n            Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);\n         }\n      }\n   }\n\n   public DynamicThreadPoolExecutor newExecutor(RejectedExecutionHandler rejectionPolicy) {\n      DynamicThreadPoolExecutor.DynamicQueue<Runnable> queue = new DynamicThreadPoolExecutor.DynamicQueue<Runnable>();\n      DynamicThreadPoolExecutor executor = new DynamicThreadPoolExecutor(1, 1, 60000, TimeUnit.MILLISECONDS, queue,\n            namedThreadFactory(\"dyn-pool-test\"));\n      executor.setRejectedExecutionHandler(rejectionPolicy);\n      queue.setThreadPoolExecutor(executor);\n      return executor;\n   }\n\n   private ThreadFactory namedThreadFactory(String name) {\n      return new ThreadFactoryBuilder().setNameFormat(name).setThreadFactory(Executors.defaultThreadFactory()).build();\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/concurrent/FutureIterablesTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.concurrent;\n\nimport static com.google.common.collect.Maps.newHashMap;\nimport static com.google.common.util.concurrent.Futures.immediateFailedFuture;\nimport static com.google.common.util.concurrent.MoreExecutors.newDirectExecutorService;\nimport static org.jclouds.concurrent.FutureIterables.transformParallel;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.fail;\n\nimport java.util.Map;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.TimeoutException;\nimport java.util.concurrent.atomic.AtomicInteger;\n\nimport org.jclouds.logging.Logger;\nimport org.jclouds.rest.AuthorizationException;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.common.util.concurrent.MoreExecutors;\n\n/**\n * Tests behavior of FutureIterables\n */\n@Test(groups = \"unit\", singleThreaded = true, testName = \"FutureIterablesTest\")\npublic class FutureIterablesTest {\n\n   public void testAuthorizationExceptionPropagatesAndOnlyTriesOncePerElement() {\n      final AtomicInteger counter = new AtomicInteger();\n\n      try {\n         transformParallel(ImmutableSet.of(\"hello\", \"goodbye\"), new Function<String, ListenableFuture<? extends String>>() {\n            public ListenableFuture<String> apply(String input) {\n               counter.incrementAndGet();\n               return immediateFailedFuture(new AuthorizationException());\n            }\n         }, newDirectExecutorService(), null, Logger.NULL, \"\");\n         fail(\"Expected AuthorizationException\");\n      } catch (AuthorizationException e) {\n         assertEquals(counter.get(), 2);\n      }\n\n   }\n\n   public void testNormalExceptionPropagatesAsTransformParallelExceptionAndTries5XPerElement() {\n      final AtomicInteger counter = new AtomicInteger();\n\n      try {\n         transformParallel(ImmutableSet.of(\"hello\", \"goodbye\"), new Function<String, ListenableFuture<? extends String>>() {\n            public ListenableFuture<String> apply(String input) {\n               counter.incrementAndGet();\n               return immediateFailedFuture(new RuntimeException());\n            }\n         }, newDirectExecutorService(), null, Logger.CONSOLE, \"\");\n         fail(\"Expected TransformParallelException\");\n      } catch (TransformParallelException e) {\n         assertEquals(e.getFromToException().size(), 2);\n         assertEquals(counter.get(), 10);\n      }\n\n   }\n\n   public void testAwaitCompletionTimeout() throws Exception {\n      final long timeoutMs = 1000;\n      ListeningExecutorService userExecutor = MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor());\n      Map<Void, ListenableFuture<?>> responses = newHashMap();\n      try {\n         responses.put(null, userExecutor.submit(new Runnable() {\n            @Override\n            public void run() {\n               try {\n                  Thread.sleep(2 * timeoutMs);\n               } catch (InterruptedException ie) {\n                  // triggered during shutdown\n               }\n            }\n         }));\n         Map<Void, Exception> errors = FutureIterables.awaitCompletion(responses, userExecutor, timeoutMs, Logger.NULL,\n         /* prefix= */\"\");\n         if (!errors.isEmpty()) {\n            throw errors.values().iterator().next();\n         }\n         fail(\"Did not throw TimeoutException\");\n      } catch (TimeoutException te) {\n         // expected\n      } finally {\n         userExecutor.shutdownNow();\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/concurrent/config/ExecutorServiceModuleTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.concurrent.config;\n\nimport static com.google.common.base.Throwables.getStackTraceAsString;\nimport static com.google.inject.name.Names.named;\nimport static java.lang.String.format;\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.jclouds.Constants.PROPERTY_USER_THREADS;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotEquals;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.util.concurrent.ExecutionException;\n\nimport org.jclouds.lifecycle.Closer;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport com.google.inject.Key;\n\n@Test\npublic class ExecutorServiceModuleTest {\n   private static final String LINE_SEPARATOR = System.getProperty(\"line.separator\");\n\n   private Injector injector;\n\n   @BeforeClass\n   private void setupExecutorModule() {\n      ExecutorServiceModule module = new ExecutorServiceModule() {\n         @Override\n         protected void configure() {\n            bindConstant().annotatedWith(named(PROPERTY_USER_THREADS)).to(1);\n            super.configure();\n         }\n      };\n\n      injector = Guice.createInjector(module);\n      assertNull(module.userExecutorFromConstructor);\n   }\n\n   @AfterClass\n   private void close() throws IOException {\n      ListeningExecutorService user = injector.getInstance(Key.get(ListeningExecutorService.class,\n            named(PROPERTY_USER_THREADS)));\n      injector.getInstance(Closer.class).close();\n      assertTrue(user.isShutdown());\n   }\n\n   @Test\n   public void testShutdownOnClose() throws IOException {\n      Injector i = Guice.createInjector();\n\n      Closer closer = i.getInstance(Closer.class);\n      ListeningExecutorService executor = createMock(ListeningExecutorService.class);\n      ExecutorServiceModule.shutdownOnClose(executor, closer);\n\n      expect(executor.shutdownNow()).andReturn(ImmutableList.<Runnable> of()).atLeastOnce();\n\n      replay(executor);\n      closer.close();\n\n      verify(executor);\n   }\n\n   @Test(timeOut = 5000)\n   public void testExceptionInSubmitRunnableIncludesSubmissionTrace() throws Exception {\n      ListeningExecutorService exec = injector.getInstance(Key.get(ListeningExecutorService.class,\n            named(PROPERTY_USER_THREADS)));\n      String submission = null;\n      try {\n         // this is sensitive to formatting as we are looking for the stack traces to match. if you wrap the below\n         // line again, you'll need to change incrementInitialElement to 3 line numbers instead of 2.\n         submission = getStackTraceAsString(incrementInitialElement(new RuntimeException(), 2)).replaceFirst(format(\".*%s\", LINE_SEPARATOR),\n               \"\");\n         exec.submit(runnableThrowsRTE()).get();\n      } catch (ExecutionException e) {\n         assertTraceHasSubmission(getStackTraceAsString(e), submission);\n         assertTraceHasSubmission(getStackTraceAsString(e.getCause()), submission);\n      }\n   }\n\n   static void assertTraceHasSubmission(String trace, String expected) {\n      assertEquals(trace.indexOf(WithSubmissionTrace.class.getName()), -1, trace);\n      assertNotEquals(trace.indexOf(expected), -1, trace + \" \" + expected);\n   }\n\n   static <E extends Exception> E incrementInitialElement(E ex, int lines) {\n      StackTraceElement[] trace = ex.getStackTrace();\n      StackTraceElement initialElement = trace[0];\n      trace[0] = new StackTraceElement(initialElement.getClassName(), initialElement.getMethodName(),\n            initialElement.getFileName(), initialElement.getLineNumber() + lines);\n      ex.setStackTrace(trace);\n      return ex;\n   }\n\n   static Runnable runnableThrowsRTE() {\n      return new Runnable() {\n         public void run() {\n            throw new RuntimeException();\n         }\n      };\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/concurrent/config/ScheduledExecutorServiceModuleTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.concurrent.config;\nimport static com.google.common.base.Throwables.getStackTraceAsString;\nimport static com.google.inject.name.Names.named;\nimport static java.lang.String.format;\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.jclouds.Constants.PROPERTY_SCHEDULER_THREADS;\nimport static org.jclouds.concurrent.config.ExecutorServiceModuleTest.assertTraceHasSubmission;\nimport static org.jclouds.concurrent.config.ExecutorServiceModuleTest.incrementInitialElement;\nimport static org.jclouds.concurrent.config.ExecutorServiceModuleTest.runnableThrowsRTE;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.TimeUnit;\n\nimport org.jclouds.lifecycle.Closer;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.util.concurrent.ListeningScheduledExecutorService;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport com.google.inject.Key;\n\n@Test\npublic class ScheduledExecutorServiceModuleTest {\n   private static final String LINE_SEPARATOR = System.getProperty(\"line.separator\");\n\n   private Injector injector;\n\n   @BeforeClass\n   private void setupExecutorModule() {\n      ScheduledExecutorServiceModule module = new ScheduledExecutorServiceModule() {\n         @Override\n         protected void configure() {\n            bindConstant().annotatedWith(named(PROPERTY_SCHEDULER_THREADS)).to(1);\n            super.configure();\n         }\n      };\n\n      injector = Guice.createInjector(module);\n   }\n\n   @AfterClass\n   private void close() throws IOException {\n      ListeningScheduledExecutorService sched = injector.getInstance(Key.get(ListeningScheduledExecutorService.class,\n            named(PROPERTY_SCHEDULER_THREADS)));\n      injector.getInstance(Closer.class).close();\n      assertTrue(sched.isShutdown());\n   }\n\n   @Test\n   public void testShutdownOnClose() throws IOException {\n      Injector i = Guice.createInjector();\n\n      Closer closer = i.getInstance(Closer.class);\n      ListeningScheduledExecutorService executor = createMock(ListeningScheduledExecutorService.class);\n      ExecutorServiceModule.shutdownOnClose(executor, closer);\n\n      expect(executor.shutdownNow()).andReturn(ImmutableList.<Runnable> of()).atLeastOnce();\n\n      replay(executor);\n      closer.close();\n\n      verify(executor);\n   }\n\n   @Test(timeOut = 5000)\n   public void testExceptionInSubmitRunnableIncludesSubmissionTrace() throws Exception {\n      ListeningScheduledExecutorService sched = injector.getInstance(Key.get(ListeningScheduledExecutorService.class,\n            named(PROPERTY_SCHEDULER_THREADS)));\n      String submission = null;\n      try {\n         // this is sensitive to formatting as we are looking for the stack traces to match. if you wrap the below\n         // line again, you'll need to change incrementInitialElement to 3 line numbers instead of 2.\n         submission = getStackTraceAsString(incrementInitialElement(new RuntimeException(), 2))\n               .replaceFirst(format(\".*%s\", LINE_SEPARATOR), \"\");\n         sched.submit(runnableThrowsRTE()).get();\n      } catch (ExecutionException e) {\n         assertTraceHasSubmission(getStackTraceAsString(e), submission);\n         assertTraceHasSubmission(getStackTraceAsString(e.getCause()), submission);\n      }\n   }\n   \n   @Test(timeOut = 5000)\n   public void testExceptionInScheduleWithFixedDelayRunnableIncludesSubmissionTrace() throws Exception {\n      ListeningScheduledExecutorService sched = injector.getInstance(Key.get(ListeningScheduledExecutorService.class,\n            named(PROPERTY_SCHEDULER_THREADS)));\n      String submission = null;\n      try {\n         // this is sensitive to formatting as we are looking for the stack traces to match. if you wrap the below\n         // line again, you'll need to change incrementInitialElement to 3 line numbers instead of 2.\n         submission = getStackTraceAsString(incrementInitialElement(new RuntimeException(), 2))\n               .replaceFirst(format(\".*%s\", LINE_SEPARATOR), \"\");\n         sched.scheduleWithFixedDelay(runnableThrowsRTE(), 0, 1, TimeUnit.MICROSECONDS).get();\n      } catch (ExecutionException e) {\n         assertTraceHasSubmission(getStackTraceAsString(e), submission);\n         assertTraceHasSubmission(getStackTraceAsString(e.getCause()), submission);\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/config/ContextLinkingTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.config;\n\nimport static org.jclouds.config.ContextLinking.CONTEXT_SUPPLIER;\nimport static org.jclouds.config.ContextLinking.VIEW_SUPPLIER;\nimport static org.jclouds.config.ContextLinking.linkContext;\nimport static org.jclouds.config.ContextLinking.linkView;\nimport static org.jclouds.providers.AnonymousProviderMetadata.forApiOnEndpoint;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.io.Closeable;\n\nimport org.jclouds.Context;\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.http.IntegrationTestClient;\nimport org.jclouds.internal.BaseView;\nimport org.testng.annotations.Test;\n\nimport com.google.common.reflect.TypeToken;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport com.google.inject.Key;\nimport com.google.inject.name.Names;\n\n@Test(groups = \"unit\", testName = \"ContextLinkingTest\")\npublic class ContextLinkingTest {\n\n   @Test\n   public void testLinkedViewBindsViewAndContextSuppliers() {\n      Injector injector = Guice.createInjector(linkView(new DummyView(contextFor(IntegrationTestClient.class))));\n\n      assertNotNull(injector.getExistingBinding(Key.get(CONTEXT_SUPPLIER, Names.named(\"IntegrationTestClient\"))));\n      assertNotNull(injector.getExistingBinding(Key.get(VIEW_SUPPLIER, Names.named(\"IntegrationTestClient\"))));\n   }\n\n   @Test\n   public void testLinkedContextBindsContextSupplier() {\n      Injector injector = Guice.createInjector(linkContext(contextFor(IntegrationTestClient.class)));\n\n      assertNotNull(injector.getExistingBinding(Key.get(CONTEXT_SUPPLIER, Names.named(\"IntegrationTestClient\"))));\n   }\n\n   private static class DummyView extends BaseView {\n      protected DummyView(Context context) {\n         super(context, new TypeToken<Context>() {\n            private static final long serialVersionUID = 1L;\n         });\n      }\n   }\n\n   private static Context contextFor(Class<? extends Closeable> apiClass) {\n      return ContextBuilder.newBuilder(forApiOnEndpoint(apiClass, \"http://localhost\")).build();\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/config/ValueOfConfigurationKeyOrNullTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.config;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.name.Names;\n\n/**\n * Tests behavior of ValueOfConfigurationKeyOrNull\n */\n@Test(groups = \"unit\")\npublic class ValueOfConfigurationKeyOrNullTest {\n\n   @Test\n   public void testNotThere() {\n      assertEquals(Guice.createInjector().getInstance(ValueOfConfigurationKeyOrNull.class).apply(\"foo\"), null);\n   }\n\n   @Test\n   public void testThere() {\n      assertEquals(Guice.createInjector(new AbstractModule() {\n\n         @Override\n         protected void configure() {\n            bindConstant().annotatedWith(Names.named(\"foo\")).to(\"bar\");\n         }\n\n      }).getInstance(ValueOfConfigurationKeyOrNull.class).apply(\"foo\"), \"bar\");\n   }\n   \n   @Test\n   public void testEmptyIsThere() {\n      assertEquals(Guice.createInjector(new AbstractModule() {\n\n         @Override\n         protected void configure() {\n            bindConstant().annotatedWith(Names.named(\"foo\")).to(\"\");\n         }\n\n      }).getInstance(ValueOfConfigurationKeyOrNull.class).apply(\"foo\"), \"\");\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/crypto/PemsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.crypto;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.security.KeyFactory;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.cert.CertificateException;\nimport java.security.cert.CertificateFactory;\nimport java.security.interfaces.RSAPrivateCrtKey;\nimport java.security.spec.InvalidKeySpecException;\nimport java.security.spec.KeySpec;\nimport java.security.spec.RSAPublicKeySpec;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.io.ByteSource;\n\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", singleThreaded = true)\npublic class PemsTest {\n\n   public static final String PRIVATE_KEY = \"-----BEGIN RSA PRIVATE KEY-----\\nMIIEpQIBAAKCAQEAyb2ZJJqGm0KKR+8nfQJNsSd+F9tXNMV7CfOcW6jsqs8EZgiV\\nR09hD1IYOj4YqM0qJONlgyg4xRWewdSG7QTPj1lJpVAida9sXy2+kzyagZA1Am0O\\nZcbqb5hoeIDgcX+eDa79s0u0DomjcfO9EKhvHLBz+zM+3QqPRkPV8nYTbfs+HjVz\\nzOU6D1B0XR3+IPZZl2AnWs2d0qhnStHcDUvnRVQ0P482YwN9VgceOZtpPz0DCKEJ\\n5Tx5STub8k0/zt/VAMHQafLSuQMLd2s4ZLuOZptN//uAsTmxireqd37z+8ZTdBbJ\\n8LEpJ+iCXuSfm5aUh7iw6oxvToY2AL53+jK2UQIDAQABAoIBAQDA88B3i/xWn0vX\\nBVxFamCYoecuNjGwXXkSyZew616A+EOCu47bh4aTurdFbYL0YFaAtaWvzlaN2eHg\\nDb+HDuTefE29+WkcGk6SshPmiz5T0XOCAICWw6wSVDkHmGwS4jZvbAFm7W8nwGk9\\nYhxgxFiRngswJZFopOLoF5WXs2td8guIYNslMpo7tu50iFnBHwKO2ZsPAk8t9nnS\\nxlDavKruymEmqHCr3+dtio5eaenJcp3fjoXBQOKUk3ipII29XRB8NqeCVV/7Kxwq\\nckqOBEbRwBclckyIbD+RiAgKvOelORjEiE9R42vuqvxRA6k9kd9o7utlX0AUtpEn\\n3gZc6LepAoGBAP9ael5Y75+sK2JJUNOOhO8ae45cdsilp2yI0X+UBaSuQs2+dyPp\\nkpEHAxd4pmmSvn/8c9TlEZhr+qYbABXVPlDncxpIuw2Ajbk7s/S4XaSKsRqpXL57\\nzj/QOqLkRk8+OVV9q6lMeQNqLtEj1u6JPviX70Ro+FQtRttNOYbfdP/fAoGBAMpA\\nXjR5woV5sUb+REg9vEuYo8RSyOarxqKFCIXVUNsLOx+22+AK4+CQpbueWN7jotrl\\nYD6uT6svWi3AAC7kiY0UI/fjVPRCUi8tVoQUE0TaU5VLITaYOB+W/bBaDE4M9560\\n1NuDWO90baA5dfU44iuzva02rGJXK9+nS3o8nk/PAoGBALOL6djnDe4mwAaG6Jco\\ncd4xr8jkyPzCRZuyBCSBbwphIUXLc7hDprPky064ncJD1UDmwIdkXd/fpMkg2QmA\\n/CUk6LEFjMisqHojOaCL9gQZJPhLN5QUN2x1PJWGjs1vQh8Tkx0iUUCOa8bQPXNR\\n+34OTsW6TUna4CSZAycLfhffAoGBAIggVsefBCvuQkF0NeUhmDCRZfhnd8y55RHR\\n1HCvqKIlpv+rhcX/zmyBLuteopYyRJRsOiE2FW00i8+rIPRu4Z3Q5nybx7w3PzV9\\noHN5R5baE9OyI4KpZWztpYYitZF67NcnAvVULHHOvVJQGnKYfLHJYmrJF7GA1ojM\\nAuMdFbjFAoGAPxUhxwFy8gaqBahKUEZn4F81HFP5ihGhkT4QL6AFPO2e+JhIGjuR\\n27+85hcFqQ+HHVtFsm81b/a+R7P4UuCRgc8eCjxQMoJ1Xl4n7VbjPbHMnIN0Ryvd\\nO4ZpWDWYnCO021JTOUUOJ4J/y0416Bvkw0z59y7sNX7wDBBHHbK/XCc=\\n-----END RSA PRIVATE KEY-----\\n\";\n\n   public static final String INVALID_PRIVATE_KEY = \"-----BEGIN FOO PRIVATE KEY-----\\nMIIEpQIBAAKCAQEAyb2ZJJqGm0KKR+8nfQJNsSd+F9tXNMV7CfOcW6jsqs8EZgiV\\nR09hD1IYOj4YqM0qJONlgyg4xRWewdSG7QTPj1lJpVAida9sXy2+kzyagZA1Am0O\\nZcbqb5hoeIDgcX+eDa79s0u0DomjcfO9EKhvHLBz+zM+3QqPRkPV8nYTbfs+HjVz\\nzOU6D1B0XR3+IPZZl2AnWs2d0qhnStHcDUvnRVQ0P482YwN9VgceOZtpPz0DCKEJ\\n5Tx5STub8k0/zt/VAMHQafLSuQMLd2s4ZLuOZptN//uAsTmxireqd37z+8ZTdBbJ\\n8LEpJ+iCXuSfm5aUh7iw6oxvToY2AL53+jK2UQIDAQABAoIBAQDA88B3i/xWn0vX\\nBVxFamCYoecuNjGwXXkSyZew616A+EOCu47bh4aTurdFbYL0YFaAtaWvzlaN2eHg\\nDb+HDuTefE29+WkcGk6SshPmiz5T0XOCAICWw6wSVDkHmGwS4jZvbAFm7W8nwGk9\\nYhxgxFiRngswJZFopOLoF5WXs2td8guIYNslMpo7tu50iFnBHwKO2ZsPAk8t9nnS\\nxlDavKruymEmqHCr3+dtio5eaenJcp3fjoXBQOKUk3ipII29XRB8NqeCVV/7Kxwq\\nckqOBEbRwBclckyIbD+RiAgKvOelORjEiE9R42vuqvxRA6k9kd9o7utlX0AUtpEn\\n3gZc6LepAoGBAP9ael5Y75+sK2JJUNOOhO8ae45cdsilp2yI0X+UBaSuQs2+dyPp\\nkpEHAxd4pmmSvn/8c9TlEZhr+qYbABXVPlDncxpIuw2Ajbk7s/S4XaSKsRqpXL57\\nzj/QOqLkRk8+OVV9q6lMeQNqLtEj1u6JPviX70Ro+FQtRttNOYbfdP/fAoGBAMpA\\nXjR5woV5sUb+REg9vEuYo8RSyOarxqKFCIXVUNsLOx+22+AK4+CQpbueWN7jotrl\\nYD6uT6svWi3AAC7kiY0UI/fjVPRCUi8tVoQUE0TaU5VLITaYOB+W/bBaDE4M9560\\n1NuDWO90baA5dfU44iuzva02rGJXK9+nS3o8nk/PAoGBALOL6djnDe4mwAaG6Jco\\ncd4xr8jkyPzCRZuyBCSBbwphIUXLc7hDprPky064ncJD1UDmwIdkXd/fpMkg2QmA\\n/CUk6LEFjMisqHojOaCL9gQZJPhLN5QUN2x1PJWGjs1vQh8Tkx0iUUCOa8bQPXNR\\n+34OTsW6TUna4CSZAycLfhffAoGBAIggVsefBCvuQkF0NeUhmDCRZfhnd8y55RHR\\n1HCvqKIlpv+rhcX/zmyBLuteopYyRJRsOiE2FW00i8+rIPRu4Z3Q5nybx7w3PzV9\\noHN5R5baE9OyI4KpZWztpYYitZF67NcnAvVULHHOvVJQGnKYfLHJYmrJF7GA1ojM\\nAuMdFbjFAoGAPxUhxwFy8gaqBahKUEZn4F81HFP5ihGhkT4QL6AFPO2e+JhIGjuR\\n27+85hcFqQ+HHVtFsm81b/a+R7P4UuCRgc8eCjxQMoJ1Xl4n7VbjPbHMnIN0Ryvd\\nO4ZpWDWYnCO021JTOUUOJ4J/y0416Bvkw0z59y7sNX7wDBBHHbK/XCc=\\n-----END FOO PRIVATE KEY-----\\n\";\n\n   public static final String PUBLIC_KEY = \"-----BEGIN PUBLIC KEY-----\\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyb2ZJJqGm0KKR+8nfQJN\\nsSd+F9tXNMV7CfOcW6jsqs8EZgiVR09hD1IYOj4YqM0qJONlgyg4xRWewdSG7QTP\\nj1lJpVAida9sXy2+kzyagZA1Am0OZcbqb5hoeIDgcX+eDa79s0u0DomjcfO9EKhv\\nHLBz+zM+3QqPRkPV8nYTbfs+HjVzzOU6D1B0XR3+IPZZl2AnWs2d0qhnStHcDUvn\\nRVQ0P482YwN9VgceOZtpPz0DCKEJ5Tx5STub8k0/zt/VAMHQafLSuQMLd2s4ZLuO\\nZptN//uAsTmxireqd37z+8ZTdBbJ8LEpJ+iCXuSfm5aUh7iw6oxvToY2AL53+jK2\\nUQIDAQAB\\n-----END PUBLIC KEY-----\\n\";\n\n   public static final String INVALID_PUBLIC_KEY = \"-----BEGIN FOO PUBLIC KEY-----\\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyb2ZJJqGm0KKR+8nfQJN\\nsSd+F9tXNMV7CfOcW6jsqs8EZgiVR09hD1IYOj4YqM0qJONlgyg4xRWewdSG7QTP\\nj1lJpVAida9sXy2+kzyagZA1Am0OZcbqb5hoeIDgcX+eDa79s0u0DomjcfO9EKhv\\nHLBz+zM+3QqPRkPV8nYTbfs+HjVzzOU6D1B0XR3+IPZZl2AnWs2d0qhnStHcDUvn\\nRVQ0P482YwN9VgceOZtpPz0DCKEJ5Tx5STub8k0/zt/VAMHQafLSuQMLd2s4ZLuO\\nZptN//uAsTmxireqd37z+8ZTdBbJ8LEpJ+iCXuSfm5aUh7iw6oxvToY2AL53+jK2\\nUQIDAQAB\\n-----END FOO PUBLIC KEY-----\\n\";\n\n   private static final String PUBLIC_KEY_PKCS1 = \"-----BEGIN RSA PUBLIC KEY-----\\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAp0ytgXbPzqJwOOixn7bT\\na6VAiNvVIOn+yDPoWbyEfc0li93BHIwv01KW/mn55IXnSbMw86rdxisvwPHFfb7U\\nRuKuTzME6yrphBiancmNjushZZeBWb8jqJhnFIKbaaOqew0LZSyG9ycYODB/HDK/\\npWTV4Bd1OtLHBNFrnIf+r3HOjJsa4rmKWXgSQIQO7be/iRHysApV9tfVH8lo1ETn\\nA08JTrQwDgo9St9YNbydb5V0CiLiQsOaIbY09buUK9lXthh/rrRVbGbSwQM6OYdX\\nIEZTN2BFvQ0p5pH8AiTwFqb0ICO46a0SjfGcXNjC/QfHljAPY3T5xyIOODM8afHC\\nnwIDAQAB\\n-----END RSA PUBLIC KEY-----\\n\";\n\n   private static final String PUBLIC_KEY_PKCS1_RAW = \"-----BEGIN RSA PUBLIC KEY-----\\nMIIBCgKCAQEAp0ytgXbPzqJwOOixn7bTa6VAiNvVIOn+yDPoWbyEfc0li93BHIwv\\n01KW/mn55IXnSbMw86rdxisvwPHFfb7URuKuTzME6yrphBiancmNjushZZeBWb8j\\nqJhnFIKbaaOqew0LZSyG9ycYODB/HDK/pWTV4Bd1OtLHBNFrnIf+r3HOjJsa4rmK\\nWXgSQIQO7be/iRHysApV9tfVH8lo1ETnA08JTrQwDgo9St9YNbydb5V0CiLiQsOa\\nIbY09buUK9lXthh/rrRVbGbSwQM6OYdXIEZTN2BFvQ0p5pH8AiTwFqb0ICO46a0S\\njfGcXNjC/QfHljAPY3T5xyIOODM8afHCnwIDAQAB\\n-----END RSA PUBLIC KEY-----\\n\";\n\n   private static final String CERTIFICATE = \"-----BEGIN CERTIFICATE-----\\nMIIClzCCAgCgAwIBAgIBATANBgkqhkiG9w0BAQUFADCBnjELMAkGA1UEBhMCVVMx\\nEzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxFjAUBgNVBAoM\\nDU9wc2NvZGUsIEluYy4xHDAaBgNVBAsME0NlcnRpZmljYXRlIFNlcnZpY2UxMjAw\\nBgNVBAMMKW9wc2NvZGUuY29tL2VtYWlsQWRkcmVzcz1hdXRoQG9wc2NvZGUuY29t\\nMB4XDTEwMDczMDIwNDEzMFoXDTIwMDcyNzIwNDEzMFowADCCASIwDQYJKoZIhvcN\\nAQEBBQADggEPADCCAQoCggEBAMm9mSSahptCikfvJ30CTbEnfhfbVzTFewnznFuo\\n7KrPBGYIlUdPYQ9SGDo+GKjNKiTjZYMoOMUVnsHUhu0Ez49ZSaVQInWvbF8tvpM8\\nmoGQNQJtDmXG6m+YaHiA4HF/ng2u/bNLtA6Jo3HzvRCobxywc/szPt0Kj0ZD1fJ2\\nE237Ph41c8zlOg9QdF0d/iD2WZdgJ1rNndKoZ0rR3A1L50VUND+PNmMDfVYHHjmb\\naT89AwihCeU8eUk7m/JNP87f1QDB0Gny0rkDC3drOGS7jmabTf/7gLE5sYq3qnd+\\n8/vGU3QWyfCxKSfogl7kn5uWlIe4sOqMb06GNgC+d/oytlECAwEAATANBgkqhkiG\\n9w0BAQUFAAOBgQBftzSZxstWw60GqRTDNN/F2GnrdtnKBoXzHww3r6jtGEylYq20\\n5KfKpEx+sPX0gyZuYJiXC2CkEjImAluWKcdN9ZF6VD541sheAjbiaU7q7ZsztTxF\\nWUH2tCvHeDXYKPKek3QzL7bYpUhLnCN/XxEv6ibeMDwtI7f5qpk2Aspzcw==\\n-----END CERTIFICATE-----\\n\";\n\n   private static final String ls = System.getProperty(\"line.separator\");\n\n   @Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = \"^Invalid PEM: no parsers for marker -----BEGIN FOO PRIVATE KEY----- .*\")\n   public void testPrivateKeySpecFromPemWithInvalidMarker() throws IOException {\n      Pems.privateKeySpec(ByteSource.wrap(INVALID_PRIVATE_KEY.getBytes(Charsets.UTF_8)));\n   }\n\n   @Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = \"^Invalid PEM: no parsers for marker -----BEGIN FOO PUBLIC KEY----- .*\")\n   public void testPublicKeySpecFromPemWithInvalidMarker() throws IOException {\n      Pems.publicKeySpec(ByteSource.wrap(INVALID_PUBLIC_KEY.getBytes(Charsets.UTF_8)));\n   }\n\n   @Test\n   public void testPrivateKeySpecFromPem() throws IOException {\n      Pems.privateKeySpec(ByteSource.wrap(PRIVATE_KEY.getBytes(Charsets.UTF_8)));\n   }\n\n   @Test\n   public void testPublicKeySpecFromPem() throws IOException {\n      Pems.publicKeySpec(ByteSource.wrap(PUBLIC_KEY.getBytes(Charsets.UTF_8)));\n   }\n\n   @Test\n   public void testX509CertificateFromPemDefault() throws IOException, CertificateException {\n      Pems.x509Certificate(ByteSource.wrap(CERTIFICATE.getBytes(Charsets.UTF_8)), null);\n   }\n\n   @Test\n   public void testX509CertificateFromPemSuppliedCertFactory() throws IOException, CertificateException {\n      Pems.x509Certificate(ByteSource.wrap(CERTIFICATE.getBytes(Charsets.UTF_8)), CertificateFactory.getInstance(\"X.509\"));\n   }\n\n   @Test\n   public void testPrivateKeySpecPem() throws IOException, InvalidKeySpecException, NoSuchAlgorithmException {\n      RSAPrivateCrtKey key = (RSAPrivateCrtKey) KeyFactory.getInstance(\"RSA\").generatePrivate(\n            Pems.privateKeySpec(ByteSource.wrap(PRIVATE_KEY.getBytes(Charsets.UTF_8))));\n      String encoded = Pems.pem(key);\n      assertEquals(encoded, PRIVATE_KEY.replaceAll(\"\\n\", ls));\n   }\n\n   @Test\n   public void testRSAPublicKeySpecPem() throws IOException, InvalidKeySpecException, NoSuchAlgorithmException {\n      String encoded = Pems.pem(KeyFactory.getInstance(\"RSA\").generatePublic(\n            Pems.publicKeySpec(PUBLIC_KEY)));\n      assertEquals(encoded, PUBLIC_KEY.replaceAll(\"PUBLIC\", \"RSA PUBLIC\").replaceAll(\"\\n\", ls));\n   }\n\n   @Test\n   public void testRSAPKCS1PublicKeySpecPem() throws IOException, InvalidKeySpecException, NoSuchAlgorithmException {\n      String encoded = Pems.pem(KeyFactory.getInstance(\"RSA\").generatePublic(\n            Pems.publicKeySpec(PUBLIC_KEY_PKCS1)));\n      assertEquals(encoded, PUBLIC_KEY_PKCS1.replaceAll(\"\\n\", ls));\n   }\n\n   @Test\n   public void testRSAPKCS1RawPublicKeySpecPem() throws IOException, InvalidKeySpecException, NoSuchAlgorithmException {\n      KeySpec spec = Pems.publicKeySpec(PUBLIC_KEY_PKCS1_RAW);\n      String encoded = Pems.pem(KeyFactory.getInstance(\"RSA\").generatePublic(spec));\n      KeySpec generatedSpec = Pems.publicKeySpec(encoded);\n\n      assertTrue(spec instanceof RSAPublicKeySpec);\n      assertTrue(generatedSpec instanceof RSAPublicKeySpec);\n\n      // The encoded is different because the generatePublic method adds the\n      // algorithm to the key.\n      assertNotEquals(encoded, PUBLIC_KEY_PKCS1_RAW.replaceAll(\"\\n\", ls).trim());\n      // Verify that the modulus and public exponent of the encoded key are the\n      // same than the ones in the original key\n      assertEquals(RSAPublicKeySpec.class.cast(spec).getModulus(), RSAPublicKeySpec.class.cast(generatedSpec)\n            .getModulus());\n      assertEquals(RSAPublicKeySpec.class.cast(spec).getPublicExponent(), RSAPublicKeySpec.class.cast(generatedSpec)\n            .getPublicExponent());\n   }\n\n   @Test\n   public void testX509CertificatePem() throws IOException, CertificateException {\n      String encoded = Pems.pem(Pems.x509Certificate(ByteSource.wrap(CERTIFICATE.getBytes(Charsets.UTF_8)),\n            CertificateFactory.getInstance(\"X.509\")));\n      assertEquals(encoded, CERTIFICATE.replaceAll(\"\\n\", ls));\n   }\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/date/DateServiceTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.date;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Date;\nimport java.util.List;\n\nimport org.jclouds.PerformanceTest;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Lists;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n/* \n * TODO: Scrap any non-DateService references (eg Joda & Amazon) if/when\n * we confirm that the DateService is fast enough.\n */\n\n/**\n * Compares performance of date operations\n */\n// NOTE:without testName, this will fail w/NPE during surefire\n@Test(groups = \"performance\", singleThreaded = true, timeOut = 2 * 60 * 1000, testName = \"DateServiceTest\")\npublic class DateServiceTest extends PerformanceTest {\n   protected DateService dateService;\n\n   @BeforeTest\n   protected void createDateService() {\n      Injector i = Guice.createInjector();\n      dateService = i.getInstance(DateService.class);\n   }\n\n   protected TestData[] testData;\n\n   protected static class TestData {\n      public final String iso8601DateString;\n      public final String iso8601DateStringTz;\n\n      public final String iso8601SecondsDateString;\n      public final String rfc822DateString;\n      public final String cDateString;\n\n      public final Date date;\n\n      TestData(String iso8601, String iso8601DateStringTz, String iso8601Seconds, String rfc822, String cDateString,\n            Date dateTime) {\n         this.iso8601DateString = iso8601;\n         this.iso8601DateStringTz = iso8601DateStringTz;\n         this.iso8601SecondsDateString = iso8601Seconds;\n         this.rfc822DateString = rfc822;\n         this.cDateString = cDateString;\n         this.date = dateTime;\n      }\n   }\n\n   public DateServiceTest() {\n      // Constant time test values, each TestData item must contain matching\n      // times!\n      testData = new TestData[] {\n            new TestData(\"2009-03-12T02:00:07.000Z\", \"2009-03-12T06:00:07+0400\", \"2009-03-12T02:00:07Z\",\n                  \"Thu, 12 Mar 2009 02:00:07 GMT\", \"Thu Mar 12 02:00:07 +0000 2009\", new Date(1236823207000L)),\n            new TestData(\"2009-03-12T02:00:07.000Z\", \"2009-03-12T06:00:07+0400\", \"2009-03-12T02:00:07Z\",\n                  \"Thu, 12 Mar 2009 02:00:07 GMT\", \"Thu Mar 12 02:00:07 +0000 2009\", new Date(1236823207000L)),\n            new TestData(\"2009-03-14T04:00:07.000Z\", \"2009-03-14T08:00:07+0400\", \"2009-03-14T04:00:07Z\",\n                  \"Sat, 14 Mar 2009 04:00:07 GMT\", \"Thu Mar 14 04:00:07 +0000 2009\", new Date(1237003207000L)),\n            new TestData(\"2009-03-16T06:00:07.000Z\", \"2009-03-16T10:00:07+0400\", \"2009-03-16T06:00:07Z\",\n                  \"Mon, 16 Mar 2009 06:00:07 GMT\", \"Thu Mar 16 06:00:07 +0000 2009\", new Date(1237183207000L)),\n            new TestData(\"2009-03-18T08:00:07.000Z\", \"2009-03-18T12:00:07+0400\", \"2009-03-18T08:00:07Z\",\n                  \"Wed, 18 Mar 2009 08:00:07 GMT\", \"Thu Mar 18 08:00:07 +0000 2009\", new Date(1237363207000L)),\n            new TestData(\"2009-03-20T10:00:07.000Z\", \"2009-03-20T14:00:07+0400\", \"2009-03-20T10:00:07Z\",\n                  \"Fri, 20 Mar 2009 10:00:07 GMT\", \"Thu Mar 20 10:00:07 +0000 2009\", new Date(1237543207000L)) };\n   }\n\n   @Test\n   public void testIso8601DateParse() {\n      Date dsDate = dateService.iso8601DateParse(testData[0].iso8601DateString);\n      assertEquals(dsDate, testData[0].date);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testIso8601DateParseIllegal() {\n      dateService.iso8601DateParse(\"-1\");\n   }\n   \n   @Test\n   public void testIso8601DateParseTz() {\n      Date dsDate = dateService.iso8601SecondsDateParse(testData[0].iso8601DateStringTz);\n      assertEquals(dsDate, testData[0].date);\n   }\n\n   @Test\n   public void testIso8601DateOrSecondsDateParse() {\n      Date dsDate = dateService\n            .iso8601DateOrSecondsDateParse(testData[0].iso8601DateString);\n      assertEquals(dsDate, testData[0].date);\n\n      Date dsSecondsDate = dateService\n            .iso8601DateOrSecondsDateParse(testData[0].iso8601SecondsDateString);\n      assertEquals(dsSecondsDate, testData[0].date);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testIso8601DateOrSecondsDateParseIllegal() {\n      dateService.iso8601DateOrSecondsDateParse(\"-1\");\n   }\n\n   @Test\n   public void testIso8601SecondsDateParse() {\n      Date dsDate = dateService.iso8601SecondsDateParse(testData[0].iso8601SecondsDateString);\n      assertEquals(dsDate, testData[0].date);\n   }\n   \n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testIso8601SecondsDateParseIllegal() {\n      dateService.iso8601SecondsDateParse(\"-1\");\n   }\n\n   @Test\n   public void testCDateParse() {\n      Date dsDate = dateService.cDateParse(testData[0].cDateString);\n      assertEquals(dsDate, testData[0].date);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testCDateParseIllegal() {\n      dateService.cDateParse(\"foo\");\n   }\n   \n   @Test\n   public void testRfc822DateParse() {\n      Date dsDate = dateService.rfc822DateParse(testData[0].rfc822DateString);\n      assertEquals(dsDate, testData[0].date);\n   }\n   \n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testRfc822DateParseIllegal() {\n      dateService.rfc822DateParse(\"foo\");\n   }\n\n   @Test\n   public void testIso8601DateFormat() {\n      String dsString = dateService.iso8601DateFormat(testData[0].date);\n      assertEquals(dsString, testData[0].iso8601DateString);\n   }\n\n   @Test\n   public void testIso8601SecondsDateFormat() {\n      String dsString = dateService.iso8601SecondsDateFormat(testData[0].date);\n      assertEquals(dsString, testData[0].iso8601SecondsDateString);\n   }\n\n   @Test\n   public void testCDateFormat() {\n      String dsString = dateService.cDateFormat(testData[0].date);\n      assertEquals(dsString, testData[0].cDateString);\n   }\n\n   @Test\n   public void testRfc822DateFormat() {\n      String dsString = dateService.rfc822DateFormat(testData[0].date);\n      assertEquals(dsString, testData[0].rfc822DateString);\n   }\n\n   @Test\n   void testIso8601DateFormatResponseTime() {\n      for (int i = 0; i < LOOP_COUNT; i++)\n         dateService.iso8601DateFormat();\n   }\n\n   @Test\n   void testUTCIsGMT() {\n      assertEquals(dateService.iso8601SecondsDateParse(\"2012-11-26T17:32:31UTC+0000\").getTime(), dateService.iso8601SecondsDateParse(\"2012-11-26T17:32:31UTC+0000\").getTime());\n   }\n   \n   @Test\n   void testTz() {\n      assertEquals(dateService.iso8601SecondsDateParse(\"2011-05-26T02:14:13-04:00\").getTime(), 1306390453000L);\n   }\n   \n   @Test\n   void testTzNoT() {\n      assertEquals(dateService.iso8601DateParse(\"2011-05-25 16:12:21.656+0000\").getTime(), 1306339941656L);\n   }\n\n   @Test\n   void testRfc822DateFormatResponseTime() {\n      for (int i = 0; i < LOOP_COUNT; i++)\n         dateService.rfc822DateFormat();\n   }\n\n   @Test\n   void testCDateFormatResponseTime() {\n      for (int i = 0; i < LOOP_COUNT; i++)\n         dateService.cDateFormat();\n   }\n\n   @Test\n   void testFormatIso8601DateCorrectnessInParallel() throws Throwable {\n      List<Runnable> tasks = Lists.newArrayListWithCapacity(testData.length);\n      for (final TestData myData : testData) {\n         tasks.add(new Runnable() {\n            public void run() {\n               String dsString = dateService.iso8601DateFormat(myData.date);\n               assertEquals(dsString, myData.iso8601DateString);\n            }\n         });\n      }\n      executeMultiThreadedCorrectnessTest(tasks);\n   }\n\n   @Test\n   void testFormatIso8601DatePerformanceInParallel() throws Throwable {\n      List<Runnable> tasks = Lists.newArrayListWithCapacity(testData.length);\n      for (final TestData myData : testData) {\n         tasks.add(new Runnable() {\n            public void run() {\n               dateService.iso8601DateFormat(myData.date);\n            }\n         });\n      }\n      executeMultiThreadedPerformanceTest(\"testFormatIso8601DatePerformanceInParallel\", tasks);\n   }\n\n   @Test\n   void testParseIso8601DateSerialResponseTime() {\n      for (int i = 0; i < LOOP_COUNT; i++)\n         dateService.iso8601DateParse(testData[0].iso8601DateString);\n   }\n\n   @Test\n   void testParseIso8601DateCorrectnessInParallel() throws Throwable {\n      List<Runnable> tasks = Lists.newArrayListWithCapacity(testData.length);\n      for (final TestData myData : testData) {\n         tasks.add(new Runnable() {\n            public void run() {\n               Date dsDate = dateService.iso8601DateParse(myData.iso8601DateString);\n               assertEquals(dsDate, myData.date);\n            }\n         });\n      }\n      executeMultiThreadedCorrectnessTest(tasks);\n   }\n\n   @Test\n   void testParseIso8601DatePerformanceInParallel() throws Throwable {\n      List<Runnable> tasks = Lists.newArrayListWithCapacity(testData.length);\n      for (final TestData myData : testData) {\n         tasks.add(new Runnable() {\n            public void run() {\n               dateService.iso8601DateParse(myData.iso8601DateString);\n            }\n         });\n      }\n      executeMultiThreadedPerformanceTest(\"testParseIso8601DatePerformanceInParallel\", tasks);\n   }\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/date/internal/DateServiceDateCodecFactoryTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.date.internal;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.fail;\n\nimport java.util.Date;\n\nimport org.jclouds.date.DateCodec;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\n@Test(testName = \"DateServiceDateCodecFactoryTest\")\npublic class DateServiceDateCodecFactoryTest {\n\n   private DateServiceDateCodecFactory simpleDateCodecFactory;\n   private DateCodec rfc822Codec;\n   private DateCodec rfc1123Codec;\n   private DateCodec iso8601Codec;\n   private DateCodec iso8601SecondsCodec;\n   private DateCodec asctimeCodec;\n\n   @BeforeTest\n   public void setUp() {\n      simpleDateCodecFactory = new DateServiceDateCodecFactory(new SimpleDateFormatDateService());\n      rfc822Codec = simpleDateCodecFactory.rfc822();\n      rfc1123Codec = simpleDateCodecFactory.rfc1123();\n      iso8601Codec = simpleDateCodecFactory.iso8601();\n      iso8601SecondsCodec = simpleDateCodecFactory.iso8601Seconds();\n      asctimeCodec = simpleDateCodecFactory.asctime();\n   }\n   \n   @Test\n   public void testCodecForRfc822() {\n      Date date = new Date(1000);\n      assertEquals(rfc822Codec.toDate(rfc822Codec.toString(date)), date);\n\n      assertEquals(rfc822Codec.toDate(\"Thu, 01 Dec 1994 16:00:00 GMT\"), new Date(786297600000L));\n   }\n\n   @Test\n   public void testCodecForRfc822ThrowsParseExceptionWhenMalformed() {\n      try {\n         rfc822Codec.toDate(\"wrong\");\n         fail();\n      } catch (IllegalArgumentException e) {\n      }\n   }\n\n   @Test\n   public void testCodecForRfc1123() {\n      Date date = new Date(1000);\n      assertEquals(rfc1123Codec.toDate(rfc1123Codec.toString(date)), date);\n\n      assertEquals(rfc1123Codec.toDate(\"Thu, 01 Dec 1994 16:00:00 GMT\"), new Date(786297600000L));\n   }\n\n   @Test\n   public void testCodecForRfc1123ThrowsParseExceptionWhenMalformed() {\n      try {\n         rfc1123Codec.toDate(\"wrong\");\n         fail();\n      } catch (IllegalArgumentException e) {\n      }\n   }\n\n   @Test\n   public void testCodecForIso8601() {\n      Date date = new Date(1000);\n      assertEquals(iso8601Codec.toDate(iso8601Codec.toString(date)), date);\n\n      assertEquals(iso8601Codec.toDate(\"1994-12-01T16:00:00.000Z\"), new Date(786297600000L));\n   }\n\n   @Test\n   public void testCodecForIso8601ThrowsParseExceptionWhenMalformed() {\n      try {\n         iso8601Codec.toDate(\"-\");\n         fail();\n      } catch (IllegalArgumentException e) {\n      }\n   }\n   \n   @Test\n   public void testCodecForIso8601Seconds() {\n      Date date = new Date(1000);\n      assertEquals(iso8601SecondsCodec.toDate(iso8601SecondsCodec.toString(date)), date);\n\n      assertEquals(iso8601SecondsCodec.toDate(\"2012-11-14T21:51:28UTC\").getTime(), 1352929888000L);\n   }\n\n   @Test\n   public void testCodecForIso8601SecondsThrowsParseExceptionWhenMalformed() {\n      try {\n         iso8601SecondsCodec.toDate(\"-\");\n         fail();\n      } catch (IllegalArgumentException e) {\n      }\n   }\n   \n   @Test\n   public void testCodecForAsctime() {\n      Date date = new Date(1000);\n      assertEquals(asctimeCodec.toDate(asctimeCodec.toString(date)), date);\n\n      assertEquals(asctimeCodec.toDate(\"Thu Dec 01 16:00:00 GMT 1994\"), new Date(786297600000L));\n   }\n\n   @Test\n   public void testCodecForAsctimeThrowsParseExceptionWhenMalformed() {\n      try {\n         asctimeCodec.toDate(\"-\");\n         fail();\n      } catch (IllegalArgumentException e) {\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/date/internal/DateUtilsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.date.internal;\n\nimport static org.testng.AssertJUnit.assertEquals;\n\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"DateUtilsTest\")\npublic class DateUtilsTest {\n\n   @Test\n   public void testTrimsToMillisWithTimezone() {\n      assertEquals(\"NO_MILLISZ\", DateUtils.trimToMillis(\"NO_MILLISZ\"));\n      assertEquals(\"NO_MILLIS.1Z\", DateUtils.trimToMillis(\"NO_MILLIS.1Z\"));\n      assertEquals(\"NO_MILLIS.12Z\", DateUtils.trimToMillis(\"NO_MILLIS.12Z\"));\n      assertEquals(\"NO_MILLIS.123Z\", DateUtils.trimToMillis(\"NO_MILLIS.123Z\"));\n      assertEquals(\"NO_MILLIS.123Z\", DateUtils.trimToMillis(\"NO_MILLIS.1234Z\"));\n      assertEquals(\"NO_MILLIS.123Z\", DateUtils.trimToMillis(\"NO_MILLIS.12345Z\"));\n      assertEquals(\"NO_MILLIS.123Z\", DateUtils.trimToMillis(\"NO_MILLIS.123456Z\"));\n      assertEquals(\"NO_MILLIS.123Z\", DateUtils.trimToMillis(\"NO_MILLIS.1234567Z\"));\n      assertEquals(\"NO_MILLIS.123Z\", DateUtils.trimToMillis(\"NO_MILLIS.12345689Z\"));\n      assertEquals(\"NO_MILLIS.123Z\", DateUtils.trimToMillis(\"NO_MILLIS.12345690123345678Z\"));\n   }\n\n   @Test\n   public void testTrimsToMillisNoTimezone() {\n      assertEquals(\"NO_MILLIS\", DateUtils.trimToMillis(\"NO_MILLIS\"));\n      assertEquals(\"NO_MILLIS.1\", DateUtils.trimToMillis(\"NO_MILLIS.1\"));\n      assertEquals(\"NO_MILLIS.12\", DateUtils.trimToMillis(\"NO_MILLIS.12\"));\n      assertEquals(\"NO_MILLIS.123\", DateUtils.trimToMillis(\"NO_MILLIS.123\"));\n      assertEquals(\"NO_MILLIS.123\", DateUtils.trimToMillis(\"NO_MILLIS.1234\"));\n      assertEquals(\"NO_MILLIS.123\", DateUtils.trimToMillis(\"NO_MILLIS.12345\"));\n      assertEquals(\"NO_MILLIS.123\", DateUtils.trimToMillis(\"NO_MILLIS.123456\"));\n      assertEquals(\"NO_MILLIS.123\", DateUtils.trimToMillis(\"NO_MILLIS.1234567\"));\n      assertEquals(\"NO_MILLIS.123\", DateUtils.trimToMillis(\"NO_MILLIS.12345689\"));\n      assertEquals(\"NO_MILLIS.123\", DateUtils.trimToMillis(\"NO_MILLIS.12345690123345678\"));\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/date/internal/SimpleDateFormatDateServiceTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.date.internal;\n\nimport static org.testng.AssertJUnit.assertEquals;\n\nimport java.util.Date;\n\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"SimpleDateFormatDateServiceTest\")\npublic class SimpleDateFormatDateServiceTest {\n   // TODO: this test has to work when a machine is not in GMT timezone\n   @Test(enabled = false)\n   public void testCorrectHandlingOfMillis() {\n      Date date = new SimpleDateFormatDateService().iso8601DateParse(\"2011-11-07T11:19:13.38225Z\");\n      assertEquals(\"Mon Nov 07 11:19:13 GMT 2011\", date.toString());\n   }\n\n   // TODO: this test has to work when a machine is not in GMT timezone\n   @Test(enabled = false)\n   public void testCorrectHandlingOfMillisWithNoTimezone() {\n      Date date = new SimpleDateFormatDateService().iso8601DateParse(\"2009-02-03T05:26:32.612278\");\n      assertEquals(\"Tue Feb 03 05:26:32 GMT 2009\", date.toString());\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/domain/CredentialsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.domain;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class CredentialsTest {\n\n   public void testSubClassEquals() {\n      Credentials creds = new Credentials(\"user\", \"pass\");\n      assertEquals(creds, new Credentials(\"user\", \"pass\") {\n      });\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/domain/JsonBallTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.domain;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.util.Map;\nimport java.util.regex.Matcher;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\nimport org.jclouds.json.config.GsonModule;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport com.google.inject.Key;\nimport com.google.inject.TypeLiteral;\n\n@Test(groups = \"unit\")\npublic class JsonBallTest {\n\n   public void testJSON_STRING_PATTERN1() {\n      Matcher matcher = JsonBall.JSON_STRING_PATTERN.matcher(\"hello\");\n      assert matcher.find();\n   }\n\n   public void testJSON_STRING_PATTERN2() {\n      Matcher matcher = JsonBall.JSON_STRING_PATTERN.matcher(\"hello world!\");\n      assert matcher.find();\n   }\n\n   public void testJSON_STRING_PATTERN3() {\n      Matcher matcher = JsonBall.JSON_STRING_PATTERN.matcher(\"\\\"hello world!\\\"\");\n      assert !matcher.find();\n   }\n\n   public void testJSON_STRING_PATTERN4() {\n      Matcher matcher = JsonBall.JSON_STRING_PATTERN.matcher(\"[hello world!]\");\n      assert !matcher.find();\n   }\n\n   public void testJSON_STRING_PATTERN5() {\n      Matcher matcher = JsonBall.JSON_STRING_PATTERN.matcher(\"{hello world!}\");\n      assert !matcher.find();\n   }\n\n   public void testJSON_NUMBER_PATTERN1() {\n      Matcher matcher = JsonBall.JSON_NUMBER_PATTERN.matcher(\"1\");\n      assert matcher.find();\n   }\n\n   public void testJSON_NUMBER_PATTERN2() {\n      Matcher matcher = JsonBall.JSON_NUMBER_PATTERN.matcher(\"1.1\");\n      assert matcher.find();\n   }\n\n   public void testJSON_NUMBER_PATTERN3() {\n      Matcher matcher = JsonBall.JSON_NUMBER_PATTERN.matcher(\"\\\"1.1\\\"\");\n      assert !matcher.find();\n   }\n\n   public void testJSON_NUMBER_PATTERN4() {\n      Matcher matcher = JsonBall.JSON_NUMBER_PATTERN.matcher(\"\\\"1\\\"\");\n      assert !matcher.find();\n   }\n\n   private ParseJson<Map<String, JsonBall>> handler;\n   private Json mapper;\n\n   @BeforeTest\n   protected void setUpInjector() throws IOException {\n      Injector injector = Guice.createInjector(new GsonModule());\n      handler = injector.getInstance(Key.get(new TypeLiteral<ParseJson<Map<String, JsonBall>>>() {\n      }));\n      mapper = injector.getInstance(Json.class);\n\n   }\n\n   public void testObject() {\n      String json = \"{\\\"tomcat6\\\":{\\\"ssl_port\\\":8433}}\";\n\n      Map<String, JsonBall> map = ImmutableMap.<String, JsonBall> of(\"tomcat6\", new JsonBall(\"{\\\"ssl_port\\\":8433}\"));\n\n      assertEquals(handler.apply(HttpResponse.builder().statusCode(200).message(\"ok\").payload(json).build()), map);\n      assertEquals(mapper.toJson(map), json);\n\n   }\n\n   public void testList() {\n      String json = \"{\\\"list\\\":[8431,8433]}\";\n\n      Map<String, JsonBall> map = ImmutableMap.<String, JsonBall> of(\"list\", new JsonBall(\"[8431,8433]\"));\n\n      assertEquals(handler.apply(HttpResponse.builder().statusCode(200).message(\"ok\").payload(json).build()), map);\n      assertEquals(mapper.toJson(map), json);\n\n   }\n\n   public void testString() {\n      String json = \"{\\\"name\\\":\\\"fooy\\\"}\";\n\n      Map<String, JsonBall> map = ImmutableMap.<String, JsonBall> of(\"name\", new JsonBall(\"fooy\"));\n\n      assertEquals(handler.apply(HttpResponse.builder().statusCode(200).message(\"ok\").payload(json).build()), map);\n      assertEquals(mapper.toJson(map), json);\n\n   }\n\n   public void testNumber() {\n      String json = \"{\\\"number\\\":1.0}\";\n\n      Map<String, JsonBall> map = ImmutableMap.<String, JsonBall> of(\"number\", new JsonBall(1.0));\n\n      assertEquals(handler.apply(HttpResponse.builder().statusCode(200).message(\"ok\").payload(json).build()), map);\n      assertEquals(mapper.toJson(map), json);\n\n   }\n\n\n   public void testBoolean() {\n      String json = \"{\\\"boolean\\\":false}\";\n\n      Map<String, JsonBall> map = ImmutableMap.<String, JsonBall> of(\"boolean\", new JsonBall(false));\n\n      assertEquals(handler.apply(HttpResponse.builder().statusCode(200).message(\"ok\").payload(json).build()), map);\n      assertEquals(mapper.toJson(map), json);\n\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/domain/JsonObjectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.domain;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.util.Map;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\nimport org.jclouds.json.config.GsonModule;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport com.google.inject.Key;\nimport com.google.inject.TypeLiteral;\n\n@Test(groups = \"unit\")\npublic class JsonObjectTest {\n   private ParseJson<Map<String, Object>> handler;\n   private Json mapper;\n\n   @BeforeTest\n   protected void setUpInjector() throws IOException {\n      Injector injector = Guice.createInjector(new GsonModule());\n      handler = injector.getInstance(Key.get(new TypeLiteral<ParseJson<Map<String, Object>>>() {\n      }));\n      mapper = injector.getInstance(Json.class);\n\n   }\n\n   public void testHash() {\n      String json = \"{\\\"tomcat6\\\":{\\\"ssl_port\\\":8433}}\";\n\n      // gson deserialized numbers to double, so integers end up changed to fractions\n      assertEquals(handler.apply(HttpResponse.builder().statusCode(200).message(\"ok\").payload(json).build()),\n            ImmutableMap.<String, Object> of(\"tomcat6\", ImmutableMap.of(\"ssl_port\", 8433d)));\n\n      assertEquals(mapper.toJson(ImmutableMap.<String, Object> of(\"tomcat6\", ImmutableMap.of(\"ssl_port\", 8433))), json);\n\n   }\n\n   public void testList() {\n      String json = \"{\\\"list\\\":[8431,8433]}\";\n\n      // gson deserialized numbers to double, so integers end up changed to fractions\n      assertEquals(handler.apply(HttpResponse.builder().statusCode(200).message(\"ok\").payload(json).build()),\n            ImmutableMap.<String, Object> of(\"list\", ImmutableList.of(8431d, 8433d)));\n      \n      assertEquals(mapper.toJson(ImmutableMap.<String, Object> of(\"list\", ImmutableList.of(8431, 8433))), json);\n\n   }\n\n   public void testString() {\n      String json = \"{\\\"name\\\":\\\"fooy\\\"}\";\n\n      Map<String, Object> map = ImmutableMap.<String, Object> of(\"name\", \"fooy\");\n\n      assertEquals(handler.apply(HttpResponse.builder().statusCode(200).message(\"ok\").payload(json).build()), map);\n      assertEquals(mapper.toJson(map), json);\n\n   }\n\n   public void testNumber() {\n      String json = \"{\\\"number\\\":1.0}\";\n\n      Map<String, Object> map = ImmutableMap.<String, Object> of(\"number\", 1d);\n\n      assertEquals(handler.apply(HttpResponse.builder().statusCode(200).message(\"ok\").payload(json).build()), map);\n      assertEquals(mapper.toJson(map), json);\n\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/domain/LoginCredentialsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.domain;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\n\n@Test(groups = \"unit\", testName = \"LoginCredentialsTest\")\npublic class LoginCredentialsTest {\n\n   public void testPasswordSetsPrivateKeyToAbsentWhenUnset() {\n      LoginCredentials toTest = LoginCredentials.builder().user(\"user\").password(\"password\").build();\n      assertEquals(toTest.getOptionalPassword(), Optional.of(\"password\"));\n      assertEquals(toTest.getOptionalPrivateKey(), Optional.absent());\n   }\n\n   public void testPasswordLeavesPrivateKeyAloneWhenSet() {\n      LoginCredentials toTest = LoginCredentials.builder().user(\"user\").privateKey(\"key\").password(\"password\").build();\n      assertEquals(toTest.getOptionalPassword(), Optional.of(\"password\"));\n      assertEquals(toTest.getOptionalPrivateKey(), Optional.of(\"key\"));\n   }\n\n   public void testPrivateKeySetsPasswordToAbsentWhenUnset() {\n      LoginCredentials toTest = LoginCredentials.builder().user(\"user\").privateKey(\"key\").build();\n      assertEquals(toTest.getOptionalPassword(), Optional.absent());\n      assertEquals(toTest.getOptionalPrivateKey(), Optional.of(\"key\"));\n   }\n\n   public void testPrivateKeyLeavesPasswordAloneWhenSet() {\n      LoginCredentials toTest = LoginCredentials.builder().user(\"user\").password(\"password\").privateKey(\"key\").build();\n      assertEquals(toTest.getOptionalPassword(), Optional.of(\"password\"));\n      assertEquals(toTest.getOptionalPrivateKey(), Optional.of(\"key\"));\n   }\n   \n   \n   public void testToStringWhenNullPasswordAndKey() {\n      LoginCredentials toTest = LoginCredentials.builder().user(\"myuser\").build();\n      assertNotNull(toTest.toString());\n   }\n   \n   public void testToString() {\n      LoginCredentials toTest = LoginCredentials.builder().user(\"myuser\").password(\"password\").privateKey(\"key\").build();\n      assertNotNull(toTest.toString());\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/events/config/EventBusModuleTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.events.config;\n\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertSame;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.Constants;\nimport org.jclouds.concurrent.config.ExecutorServiceModule;\nimport org.jclouds.events.config.annotations.AsyncBus;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.eventbus.AsyncEventBus;\nimport com.google.common.eventbus.EventBus;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport com.google.inject.Key;\nimport com.google.inject.name.Names;\n\n/**\n * Unit tests for the {@link EventBusModule} class.\n */\n@Test(groups = \"unit\", testName = \"EventBusModuleTest\")\npublic class EventBusModuleTest {\n    private Injector injector;\n    \n    @BeforeClass\n    public void setup() {\n        ExecutorServiceModule userExecutorModule = new ExecutorServiceModule() {\n            @Override\n            protected void configure() {\n               bindConstant().annotatedWith(Names.named(Constants.PROPERTY_USER_THREADS)).to(1);\n               super.configure();\n            }\n         };\n         EventBusModule eventBusModule = new EventBusModule();\n         injector = Guice.createInjector(userExecutorModule, eventBusModule);\n    }\n    \n    public void testAsyncExecutorIsProvided() {\n        assertNotNull(injector.getInstance(AsyncEventBus.class));\n    }\n\n    public void testAsyncAnnotatedEventBusIsBound() {\n        Key<EventBus> eventBusKey = Key.get(EventBus.class, AsyncBus.class);\n        EventBus eventBus = injector.getInstance(eventBusKey);\n\n        assertNotNull(eventBus);\n        assertTrue(eventBus instanceof AsyncEventBus);\n    }\n\n    public void testEventBusIsSingleton() {\n        EventBus eventBus1 = injector.getInstance(EventBus.class);\n        EventBus eventBus2 = injector.getInstance(EventBus.class);\n\n        assertSame(eventBus1, eventBus2);\n    }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/fallbacks/HeaderToRetryAfterExceptionTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.fallbacks;\nimport static java.util.concurrent.TimeUnit.MILLISECONDS;\n\nimport org.jclouds.date.DateCodec;\nimport org.jclouds.date.internal.DateServiceDateCodecFactory.DateServiceRfc822Codec;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.rest.RetryAfterException;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Ticker;\nimport com.google.common.net.HttpHeaders;\n\n@Test(groups = \"unit\")\npublic class HeaderToRetryAfterExceptionTest {\n\n   @Test(expectedExceptions = RuntimeException.class)\n   public void testArbitraryExceptionDoesntConvert() throws Exception {\n      fn.createOrPropagate(new RuntimeException());\n   }\n   \n   public void testHttpResponseExceptionWithoutResponseDoesntPropagate() throws Exception {\n      fn.createOrPropagate(new HttpResponseException(\"message\", command, null));\n   }\n\n   public void testHttpResponseExceptionWithoutRetryAfterHeaderDoesntPropagate() throws Exception {\n      fn.createOrPropagate(new HttpResponseException(command, HttpResponse.builder().statusCode(500).build()));\n   }\n\n   public void testHttpResponseExceptionWithMalformedRetryAfterHeaderDoesntConvert() throws Exception {\n      fn.createOrPropagate(new HttpResponseException(command,\n            HttpResponse.builder().statusCode(503).addHeader(HttpHeaders.RETRY_AFTER, \"Fri, 31 Dec 1999 23:59:59 ZBW\")\n                  .build()));\n   }\n   \n   @Test(expectedExceptions = RetryAfterException.class, expectedExceptionsMessageRegExp = \"retry now\")\n   public void testHttpResponseExceptionWithRetryAfterDate() throws Exception {\n      fn.createOrPropagate(new HttpResponseException(command,\n            HttpResponse.builder().statusCode(503).addHeader(HttpHeaders.RETRY_AFTER, \"Fri, 31 Dec 1999 23:59:59 GMT\")\n                  .build()));\n   }\n   \n   @Test(expectedExceptions = RetryAfterException.class, expectedExceptionsMessageRegExp = \"retry in 700 seconds\")\n   public void testHttpResponseExceptionWithRetryAfterOffset() throws Exception {\n      fn.createOrPropagate(new HttpResponseException(command,\n            HttpResponse.builder().statusCode(503).addHeader(HttpHeaders.RETRY_AFTER, \"700\").build()));\n   }\n   \n   @Test(expectedExceptions = RetryAfterException.class, expectedExceptionsMessageRegExp = \"retry in 86400 seconds\")\n   public void testHttpResponseExceptionWithRetryAfterPastIsZero() throws Exception {\n      fn.createOrPropagate(new HttpResponseException(command,\n            HttpResponse.builder().statusCode(503).addHeader(HttpHeaders.RETRY_AFTER, \"Sun, 2 Jan 2000 00:00:00 GMT\")\n                  .build()));\n   }\n\n   public static HttpCommand command = new HttpCommand(HttpRequest.builder().method(\"GET\").endpoint(\"http://stub\").build());\n\n   static DateCodec rfc822 = new DateServiceRfc822Codec(new SimpleDateFormatDateService());\n   \n   static Ticker y2k = new Ticker() {\n\n      @Override\n      public long read() {\n         return MILLISECONDS.toNanos(rfc822.toDate(\"Sat, 1 Jan 2000 00:00:00 GMT\").getTime());\n      }\n      \n   };\n   \n   public static HeaderToRetryAfterException fn = HeaderToRetryAfterException.create(y2k, rfc822);\n\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/fallbacks/MapHttp4xxCodesToExceptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.fallbacks;\n\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.jclouds.rest.RetryAfterException;\nimport org.testng.annotations.Test;\n\nimport com.google.common.net.HttpHeaders;\n\n@Test(groups = { \"unit\" })\npublic class MapHttp4xxCodesToExceptionsTest {\n\n   @Test(expectedExceptions = AuthorizationException.class)\n   public void test401ToAuthorizationException() throws Exception {\n      fn.createOrPropagate(new HttpResponseException(command, HttpResponse.builder().statusCode(401).build()));\n   }\n\n   @Test(expectedExceptions = AuthorizationException.class)\n   public void test403ToAuthorizationException() throws Exception {\n      fn.createOrPropagate(new HttpResponseException(command, HttpResponse.builder().statusCode(403).build()));\n   }\n   \n   @Test(expectedExceptions = ResourceNotFoundException.class)\n   public void test404ToResourceNotFoundException() throws Exception {\n      fn.createOrPropagate(new HttpResponseException(command, HttpResponse.builder().statusCode(404).build()));\n   }\n\n   @Test(expectedExceptions = IllegalStateException.class)\n   public void test409ToIllegalStateException() throws Exception {\n      fn.createOrPropagate(new HttpResponseException(command, HttpResponse.builder().statusCode(409).build()));\n   }\n   \n   @Test(expectedExceptions = RetryAfterException.class, expectedExceptionsMessageRegExp = \"retry now\")\n   public void testHttpResponseExceptionWithRetryAfterDate() throws Exception {\n      fn.createOrPropagate(new HttpResponseException(command,\n            HttpResponse.builder()\n                        .statusCode(503)\n                        .addHeader(HttpHeaders.RETRY_AFTER, \"Fri, 31 Dec 1999 23:59:59 GMT\").build()));\n   }\n   \n   @Test(expectedExceptions = RetryAfterException.class, expectedExceptionsMessageRegExp = \"retry in 700 seconds\")\n   public void testHttpResponseExceptionWithRetryAfterOffset() throws Exception {\n      fn.createOrPropagate(new HttpResponseException(command,\n            HttpResponse.builder()\n                        .statusCode(503)\n                        .addHeader(HttpHeaders.RETRY_AFTER, \"700\").build()));\n   }\n   \n   @Test(expectedExceptions = RetryAfterException.class, expectedExceptionsMessageRegExp = \"retry in 86400 seconds\")\n   public void testHttpResponseExceptionWithRetryAfterPastIsZero() throws Exception {\n      fn.createOrPropagate(new HttpResponseException(command,\n            HttpResponse.builder()\n                        .statusCode(503)\n                        .addHeader(HttpHeaders.RETRY_AFTER, \"Sun, 2 Jan 2000 00:00:00 GMT\").build()));\n   }\n   \n   MapHttp4xxCodesToExceptions fn = new MapHttp4xxCodesToExceptions(HeaderToRetryAfterExceptionTest.fn);\n   \n   HttpCommand command = HeaderToRetryAfterExceptionTest.command;\n   \n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/functions/CacheLearningTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.functions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.fail;\n\nimport java.util.concurrent.ExecutionException;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.util.concurrent.UncheckedExecutionException;\n\n@Test(groups = \"unit\", singleThreaded = true, testName = \"CacheLearningTest\")\npublic class CacheLearningTest {\n   @Test\n   public void howTo() throws ExecutionException {\n      LoadingCache<String, String> cache = CacheBuilder.newBuilder().build(new CacheLoader<String, String>() {\n\n         @Override\n         public String load(String key) throws Exception {\n            if (key.equals(\"runtimeexception\"))\n               throw new RuntimeException(\"runtimeexception\");\n            if (key.equals(\"exception\"))\n               throw new Exception(\"exception\");\n            return key.equals(\"foo\") ? null : key;\n         }\n\n         @Override\n         public String toString() {\n            return \"testLoader\";\n         }\n\n      });\n      try {\n         cache.get(\"foo\");\n         fail(\"expected exception on miss\");\n      } catch (CacheLoader.InvalidCacheLoadException e) {\n         assertEquals(e.getMessage(), \"CacheLoader returned null for key foo.\");\n      }\n      \n      try {\n         cache.getUnchecked(\"foo\");\n         fail(\"expected exception on miss\");\n      } catch (CacheLoader.InvalidCacheLoadException e) {\n         assertEquals(e.getMessage(), \"CacheLoader returned null for key foo.\");\n      }\n      \n      assertEquals(cache.asMap().keySet().size(), 0);\n      assertEquals(cache.asMap().size(), 0);\n\n      // check insert behind\n      cache.asMap().put(\"foo\", \"bar\");\n      assertEquals(cache.get(\"foo\"), \"bar\");\n\n      assertEquals(cache.asMap().keySet().size(), 1);\n      assertEquals(cache.asMap().size(), 1);\n      \n      // check delete behind invalidates\n      cache.asMap().remove(\"foo\");\n      assertEquals(cache.asMap().keySet().size(), 0);\n      assertEquals(cache.asMap().size(), 0);\n      \n      try {\n         cache.get(\"exception\");\n         fail(\"expected checked exception in loader to rethrow as ExecutionException\");\n      } catch (ExecutionException e) {\n         assertEquals(e.getMessage(), \"java.lang.Exception: exception\");\n      }\n\n      try {\n         cache.get(\"runtimeexception\");\n         fail(\"expected unchecked exception in loader to rethrow as UncheckedExecutionException\");\n      } catch (UncheckedExecutionException e) {\n         assertEquals(e.getMessage(), \"java.lang.RuntimeException: runtimeexception\");\n      }\n\n      try {\n         cache.getUnchecked(\"exception\");\n         fail(\"expected checked exception in loader to rethrow as UncheckedExecutionException, when getUnchecked called\");\n      } catch (UncheckedExecutionException e) {\n         assertEquals(e.getMessage(), \"java.lang.Exception: exception\");\n      }\n\n      assertEquals(cache.get(\"bar\"), \"bar\");\n      assertEquals(cache.get(\"baz\"), \"baz\");\n      assertEquals(cache.asMap().size(), 2);\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/functions/ExpandPropertiesTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Properties;\n\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ExpandPropertiesTest\")\npublic class ExpandPropertiesTest {\n\n   @Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = \"properties cannot be null\")\n   public void testPropertiesMandatory() {\n      new ExpandProperties().apply(null);\n   }\n\n   @Test\n   public void testResolveProperties() {\n      Properties props = new Properties();\n      props.put(\"number\", 1);\n      props.put(\"two\", \"2\");\n      props.put(\"greeting\", \"hello\");\n      props.put(\"simple\", \"simple: ${greeting}\");\n      props.put(\"nested\", \"nested: ${simple}\");\n      props.put(\"mixed\", \"mixed: ${nested} and ${simple}\");\n      props.put(\"unexisting\", \"${foobar} substitution\");\n      props.put(\"recursive\", \"variable5 ${recursive} recursive ${unexisting}\");\n      props.put(\"characters{{$$\", \"characters\");\n      props.put(\"ugly\", \"substitute: ${characters{{$$}\");\n\n      Properties resolved = new ExpandProperties().apply(props);\n\n      assertEquals(resolved.size(), props.size());\n      assertEquals(resolved.get(\"number\"), 1);\n      assertEquals(resolved.get(\"two\"), \"2\");\n      assertEquals(resolved.get(\"greeting\"), \"hello\");\n      assertEquals(resolved.get(\"simple\"), \"simple: hello\");\n      assertEquals(resolved.get(\"nested\"), \"nested: simple: hello\");\n      assertEquals(resolved.get(\"mixed\"), \"mixed: nested: simple: hello and simple: hello\");\n      assertEquals(resolved.get(\"unexisting\"), \"${foobar} substitution\");\n      assertEquals(resolved.get(\"recursive\"), \"variable5 ${recursive} recursive ${unexisting}\");\n      assertEquals(resolved.get(\"ugly\"), \"substitute: characters\");\n   }\n\n   @Test\n   public void testNoLeafs() {\n      Properties props = new Properties();\n      props.put(\"one\", \"${two}\");\n      props.put(\"two\", \"${one}\");\n\n      Properties resolved = new ExpandProperties().apply(props);\n\n      assertEquals(resolved.size(), props.size());\n      assertEquals(resolved.get(\"one\"), \"${two}\");\n      assertEquals(resolved.get(\"two\"), \"${one}\");\n   }\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/functions/JoinOnCommaTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", singleThreaded = true)\npublic class JoinOnCommaTest {\n   @Test\n   public void testIterableLong() {\n      String list = new JoinOnComma().apply(ImmutableList.of(1L, 2L));\n      assertEquals(list, \"1,2\");\n   }\n\n   @Test\n   public void testLongArray() {\n      String list = new JoinOnComma().apply(new long[] { 1L, 2L });\n      assertEquals(list, \"1,2\");\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testEmptyArrayIllegalArgumentException() {\n      new JoinOnComma().apply(new long[] {});\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testEmptyIterableIllegalArgumentException() {\n      new JoinOnComma().apply(ImmutableList.of());\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testNullPointer() {\n      new JoinOnComma().apply(null);\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/http/BackoffLimitedRetryJavaTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http;\n\nimport static org.jclouds.Constants.PROPERTY_MAX_RETRIES;\nimport static org.jclouds.util.Closeables2.closeQuietly;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.fail;\n\nimport java.util.Properties;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\n\nimport org.jclouds.http.config.JavaUrlHttpCommandExecutorServiceModule;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Module;\n\n\n/**\n * Tests the retry behavior of the default {@link RetryHandler} implementation\n * {@link BackoffLimitedRetryHandler} to ensure that retries up to the default\n * limit succeed.\n */\n@Test(groups = \"integration\")\npublic class BackoffLimitedRetryJavaTest extends BaseMockWebServerTest {\n\n   private final int maxRetries = 5;\n\n   @Override\n   protected void addOverrideProperties(Properties props) {\n      props.setProperty(PROPERTY_MAX_RETRIES, \"\" + maxRetries);\n   }\n\n   @Override\n   protected Module createConnectionModule() {\n      return new JavaUrlHttpCommandExecutorServiceModule();\n   }\n\n   protected IntegrationTestClient client(String url) {\n      return api(IntegrationTestClient.class, url);\n   }\n\n   @Test\n   public void testNoRetriesSuccessful() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse());\n      IntegrationTestClient client = client(server.url(\"/\").toString());\n      try {\n         client.download(\"\");\n         assertEquals(server.getRequestCount(), 1);\n      } finally {\n         closeQuietly(client);\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testSingleRetrySuccessful() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(500), new MockResponse());\n      IntegrationTestClient client = client(server.url(\"/\").toString());\n      try {\n         client.download(\"\");\n         assertEquals(server.getRequestCount(), 2);\n      } finally {\n         closeQuietly(client);\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testMaximumRetriesSuccessful() throws Exception {\n      MockWebServer server = mockWebServer();\n      for (int i = 0; i < maxRetries - 1; i++) {\n         server.enqueue(new MockResponse().setResponseCode(500));\n      }\n      server.enqueue(new MockResponse());\n\n      IntegrationTestClient client = client(server.url(\"/\").toString());\n      try {\n         client.download(\"\");\n         assertEquals(server.getRequestCount(), maxRetries);\n      } finally {\n         closeQuietly(client);\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testMaximumRetriesExceeded() throws Exception {\n      MockWebServer server = mockWebServer();\n      for (int i = 0; i <= maxRetries; i++) {\n         server.enqueue(new MockResponse().setResponseCode(500));\n      }\n\n      IntegrationTestClient client = client(server.url(\"/\").toString());\n      try {\n\n         client.download(\"\");\n         fail(\"Request should not succeed within \" + maxRetries + \" requests\");\n      } catch (HttpResponseException ex) {\n         assertEquals(ex.getResponse().getStatusCode(), 500);\n         assertEquals(server.getRequestCount(), maxRetries + 1);\n      } finally {\n         closeQuietly(client);\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testInterleavedSuccessesAndFailures() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse(), new MockResponse());\n      for (int i = 0; i <= maxRetries; i++) {\n         server.enqueue(new MockResponse().setResponseCode(500));\n      }\n\n      IntegrationTestClient client = client(server.url(\"/\").toString());\n      try {\n         client.download(\"\");\n         client.download(\"\");\n\n         try {\n            client.download(\"\");\n            fail(\"Request should not succeed within \" + maxRetries + \" requests\");\n         } catch (HttpResponseException ex) {\n            assertEquals(ex.getResponse().getStatusCode(), 500);\n            assertEquals(server.getRequestCount(), maxRetries + 3);\n         }\n      } finally {\n         closeQuietly(client);\n         server.shutdown();\n      }\n   }\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/http/BaseHttpCommandExecutorServiceIntegrationTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http;\n\nimport static com.google.common.hash.Hashing.md5;\nimport static com.google.common.io.BaseEncoding.base64;\nimport static com.google.common.io.Files.asByteSource;\nimport static org.jclouds.http.options.GetOptions.Builder.tail;\nimport static org.jclouds.io.Payloads.newByteSourcePayload;\nimport static org.jclouds.util.Closeables2.closeQuietly;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.Assert.fail;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.net.URLDecoder;\nimport java.util.Random;\nimport java.util.concurrent.TimeUnit;\n\nimport okhttp3.mockwebserver.Dispatcher;\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\nimport okhttp3.mockwebserver.RecordedRequest;\n\nimport okio.Buffer;\n\nimport org.jclouds.io.ByteStreams2;\nimport org.jclouds.io.Payload;\nimport org.jclouds.util.Strings2;\nimport org.jclouds.utils.TestUtils;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.DataProvider;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Throwables;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Multimap;\nimport com.google.common.io.ByteSource;\nimport com.google.common.io.Files;\n\n\n/**\n * Tests for functionality all {@link HttpCommandExecutorService} http executor\n * services must express. These tests will operate against an in-memory http\n * engine, so as to ensure end-to-end functionality works.\n */\n@Test(groups = \"integration\")\npublic abstract class BaseHttpCommandExecutorServiceIntegrationTest extends BaseMockWebServerTest {\n\n   private static final String XML = \"<foo><bar>whoppers</bar></foo>\";\n   private static final String XML2 = \"<foo><bar>chubbs</bar></foo>\";\n   private static final ByteSource oneHundredOneConstitutions = TestUtils.randomByteSource().slice(0, 101 * 45118);\n\n   @BeforeClass(groups = \"integration\")\n   public void setup() throws IOException {\n   }\n\n   protected IntegrationTestClient client(String url) {\n      return api(IntegrationTestClient.class, url);\n   }\n\n   @Test\n   public void testRequestFilter() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(\"test\"));\n      IntegrationTestClient client = client(server.url(\"/\").toString());\n      try {\n         String result = client.downloadFilter(\"\", \"filterme\");\n\n         RecordedRequest request = server.takeRequest();\n         assertEquals(request.getHeader(\"filterme\"), \"filterme\");\n         assertEquals(request.getHeader(\"test\"), \"test\");\n         assertEquals(result, \"test\");\n      } finally {\n         closeQuietly(client);\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testGetStringWithHeader() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(\"test\"));\n      IntegrationTestClient client = client(server.url(\"/\").toString());\n      try {\n         String result = client.download(\"\", \"test\");\n\n         RecordedRequest request = server.takeRequest();\n         assertEquals(request.getHeader(\"test\"), \"test\");\n         assertEquals(result, \"test\");\n      } finally {\n         closeQuietly(client);\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testGetString() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(XML));\n      IntegrationTestClient client = client(server.url(\"/\").toString());\n      try {\n         assertEquals(client.download(\"\"), XML);\n      } finally {\n         closeQuietly(client);\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testGetStringIsRetriedOnFailure() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(500), new MockResponse().setBody(XML));\n      IntegrationTestClient client = client(server.url(\"/\").toString());\n      try {\n         String result = client.download(\"\");\n         assertEquals(server.getRequestCount(), 2);\n         assertEquals(result, XML);\n      } finally {\n         closeQuietly(client);\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testGetStringViaRequest() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(XML));\n      IntegrationTestClient client = client(server.url(\"/\").toString());\n      try {\n         HttpResponse getStringResponse = client.invoke(HttpRequest.builder().method(\"GET\")\n               .endpoint(server.url(\"/objects\").toString()).build());\n         assertEquals(Strings2.toStringAndClose(getStringResponse.getPayload().openStream()).trim(), XML);\n      } finally {\n         closeQuietly(client);\n         server.shutdown();\n      }\n   }\n\n   @DataProvider(name = \"gets\")\n   public Object[][] createData() {\n      return new Object[][] { { \"object\" }, { \"/path\" }, { \"sp ace\" }, { \"unic₪de\" }, { \"qu?stion\" } };\n   }\n\n   @Test(dataProvider = \"gets\")\n   public void testGetStringSynch(String uri) throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(XML));\n      IntegrationTestClient client = client(server.url(\"/\").toString());\n      try {\n         String result = client.synch(uri);\n         RecordedRequest request = server.takeRequest();\n         assertTrue(URLDecoder.decode(request.getPath(), \"UTF-8\").endsWith(uri));\n         assertEquals(result, XML);\n      } finally {\n         closeQuietly(client);\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testGetException() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(404));\n      IntegrationTestClient client = client(server.url(\"/\").toString());\n      try {\n         String result = client.downloadException(\"\", tail(1));\n         assertEquals(result, \"foo\");\n      } finally {\n         closeQuietly(client);\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testGetSynchException() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(404));\n      IntegrationTestClient client = client(server.url(\"/\").toString());\n      try {\n         String result = client.synchException(\"\", \"\");\n         assertEquals(result, \"foo\");\n      } finally {\n         closeQuietly(client);\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testGetStringRedirect() throws Exception {\n      MockWebServer redirectTarget = mockWebServer(new MockResponse().setBody(XML2));\n      redirectTarget.useHttps(sslSocketFactory(), false);\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(302).setHeader(\"Location\",\n            redirectTarget.url(\"/\").toString()));\n      IntegrationTestClient client = client(server.url(\"/\").toString());\n      try {\n         String result = client.download(\"redirect\");\n         assertEquals(result, XML2);\n         assertEquals(server.getRequestCount(), 1);\n         assertEquals(redirectTarget.getRequestCount(), 1);\n      } finally {\n         closeQuietly(client);\n         redirectTarget.shutdown();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testGetBigFile() throws Exception {\n      String constitutionsMd5 = base64().encode(oneHundredOneConstitutions.hash(md5()).asBytes());\n      MockResponse response = new MockResponse().addHeader(\"Content-MD5\", constitutionsMd5)\n            .addHeader(\"Content-type\", \"text/plain\")\n            .setBody(new Buffer().readFrom(oneHundredOneConstitutions.openStream(), oneHundredOneConstitutions.size()));\n\n      MockWebServer server = mockWebServer(response, response);\n      InputStream input = server.url(\"/101constitutions\").url().openStream();\n\n      try {\n         assertValidMd5(input, constitutionsMd5);\n      } catch (RuntimeException e) {\n      } finally {\n         closeQuietly(input);\n      }\n   }\n\n   private void assertValidMd5(final InputStream input, String md5) throws IOException {\n      assertEquals(base64().encode(ByteStreams2.hashAndClose(input, md5()).asBytes()), md5);\n   }\n\n   private static class MD5CheckDispatcher extends Dispatcher {\n\n      @Override\n      public MockResponse dispatch(RecordedRequest request) throws InterruptedException {\n         try {\n            MockResponse response = new MockResponse();\n            String expectedMd5 = request.getHeader(\"Content-MD5\");\n            ByteSource body = ByteSource.wrap(request.getBody().readByteArray());\n            String realMd5FromRequest = base64().encode(body.hash(md5()).asBytes());\n            boolean matched = expectedMd5.equals(realMd5FromRequest);\n            if (matched) {\n               response.addHeader(\"x-Content-MD5\", realMd5FromRequest);\n            } else {\n               response.setResponseCode(500);\n            }\n            return response;\n         } catch (IOException ex) {\n            throw Throwables.propagate(ex);\n         }\n      }\n\n   }\n\n   @Test\n   public void testUploadBigFile() throws Exception {\n      MockWebServer server = mockWebServer(new MD5CheckDispatcher());\n      IntegrationTestClient client = client(server.url(\"/\").toString());\n\n      File f = null;\n      Payload payload = null;\n\n      try {\n         f = java.nio.file.Files.createTempFile(\"jclouds\", \"tmp\").toFile();\n         long length = (new Random().nextInt(32) + 1) * 1024L * 1024L;\n         TestUtils.randomByteSource().slice(0, length).copyTo(Files.asByteSink(f));\n\n         ByteSource byteSource = asByteSource(f);\n         payload = newByteSourcePayload(byteSource);\n         byte[] digest = byteSource.hash(md5()).asBytes();\n         String strDigest = base64().encode(digest);\n\n         payload.getContentMetadata().setContentMD5(digest);\n         payload.getContentMetadata().setContentLength(f.length());\n         Multimap<String, String> headers = client.postPayloadAndReturnHeaders(\"\", payload);\n         RecordedRequest request = server.takeRequest();\n         assertEquals(request.getHeader(\"Content-MD5\"), strDigest);\n         assertEquals(headers.get(\"x-Content-MD5\"), ImmutableList.of(strDigest));\n      } finally {\n         if (payload != null) {\n            payload.release();\n         }\n         if (f != null && f.exists()) {\n            f.delete();\n         }\n         closeQuietly(client);\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testPost() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(\"fooPOST\"));\n      IntegrationTestClient client = client(server.url(\"/\").toString());\n      try {\n         String result = client.post(\"\", \"foo\");\n         // Verify that the body is properly populated\n         RecordedRequest request = server.takeRequest();\n         assertEquals(request.getBody().readUtf8(), \"foo\");\n         assertEquals(result, \"fooPOST\");\n      } finally {\n         closeQuietly(client);\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testZeroLengthPost() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse());\n      IntegrationTestClient client = client(server.url(\"/\").toString());\n      try {\n         client.postNothing(\"\");\n         assertEquals(server.getRequestCount(), 1);\n         RecordedRequest request = server.takeRequest();\n         assertEquals(request.getBody().readUtf8(), \"\");\n      } finally {\n         closeQuietly(client);\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testPostIsRetriedOnFailure() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(500),\n            new MockResponse().setBody(\"fooPOST\"));\n      IntegrationTestClient client = client(server.url(\"/\").toString());\n      try {\n         String result = client.post(\"\", \"foo\");\n         assertEquals(server.getRequestCount(), 2);\n         assertEquals(result, \"fooPOST\");\n         // Verify that the body was properly sent in the two requests\n         RecordedRequest request = server.takeRequest();\n         assertEquals(request.getBody().readUtf8(), \"foo\");\n         request = server.takeRequest();\n         assertEquals(request.getBody().readUtf8(), \"foo\");\n      } finally {\n         closeQuietly(client);\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testPostRedirect() throws Exception {\n      MockWebServer redirectTarget = mockWebServer(new MockResponse().setBody(\"fooPOSTREDIRECT\"));\n      redirectTarget.useHttps(sslSocketFactory(), false);\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(302).setHeader(\"Location\",\n            redirectTarget.url(\"/\").toString()));\n      IntegrationTestClient client = client(server.url(\"/\").toString());\n      try {\n         String result = client.post(\"redirect\", \"foo\");\n         assertEquals(result, \"fooPOSTREDIRECT\");\n         assertEquals(server.getRequestCount(), 1);\n         assertEquals(redirectTarget.getRequestCount(), 1);\n         // Verify that the body was populated after the redirect\n         RecordedRequest request = server.takeRequest();\n         assertEquals(request.getBody().readUtf8(), \"foo\");\n         request = redirectTarget.takeRequest();\n         assertEquals(request.getBody().readUtf8(), \"foo\");\n      } finally {\n         closeQuietly(client);\n         redirectTarget.shutdown();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testPostAsInputStream() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(\"fooPOST\"));\n      IntegrationTestClient client = client(server.url(\"/\").toString());\n      try {\n         String result = client.postAsInputStream(\"\", \"foo\");\n         // Verify that the body is properly populated\n         RecordedRequest request = server.takeRequest();\n         assertEquals(request.getBody().readUtf8(), \"foo\");\n         assertEquals(result, \"fooPOST\");\n      } finally {\n         closeQuietly(client);\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testPostAsInputStreamDoesNotRetryOnFailure() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(500), new MockResponse());\n      IntegrationTestClient client = client(server.url(\"/\").toString());\n      try {\n         client.postAsInputStream(\"\", \"foo\");\n         fail(\"Request should have thrown an exception after a server error\");\n      } catch (Exception expected) {\n         assertEquals(server.getRequestCount(), 1);\n      } finally {\n         closeQuietly(client);\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testPostBinder() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(\"fooPOSTJSON\"));\n      IntegrationTestClient client = client(server.url(\"/\").toString());\n      try {\n         String result = client.postJson(\"\", \"foo\");\n         // Verify that the body is properly populated\n         RecordedRequest request = server.takeRequest();\n         assertEquals(request.getBody().readUtf8(), \"{\\\"key\\\":\\\"foo\\\"}\");\n         assertEquals(result, \"fooPOSTJSON\");\n      } finally {\n         closeQuietly(client);\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testPostContentDisposition() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().addHeader(\"x-Content-Disposition\",\n            \"attachment; filename=photo.jpg\"));\n      IntegrationTestClient client = client(server.url(\"/\").toString());\n      Payload payload = null;\n      try {\n         ByteSource body = ByteSource.wrap(\"foo\".getBytes());\n         payload = newByteSourcePayload(body);\n         payload.getContentMetadata().setContentDisposition(\"attachment; filename=photo.jpg\");\n         payload.getContentMetadata().setContentLength(body.size());\n         Multimap<String, String> headers = client.postPayloadAndReturnHeaders(\"\", payload);\n         RecordedRequest request = server.takeRequest();\n         assertEquals(request.getHeader(\"Content-Disposition\"), \"attachment; filename=photo.jpg\");\n         assertEquals(headers.get(\"x-Content-Disposition\"), ImmutableList.of(\"attachment; filename=photo.jpg\"));\n      } finally {\n         if (payload != null) {\n            payload.release();\n         }\n         closeQuietly(client);\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testPostContentEncoding() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().addHeader(\"x-Content-Encoding\", \"gzip\"));\n      IntegrationTestClient client = client(server.url(\"/\").toString());\n      Payload payload = null;\n      try {\n         ByteSource body = ByteSource.wrap(\"foo\".getBytes());\n         payload = newByteSourcePayload(body);\n         payload.getContentMetadata().setContentEncoding(\"gzip\");\n         payload.getContentMetadata().setContentLength(body.size());\n         Multimap<String, String> headers = client.postPayloadAndReturnHeaders(\"\", payload);\n         RecordedRequest request = server.takeRequest();\n         assertEquals(request.getHeader(\"Content-Encoding\"), \"gzip\");\n         assertEquals(headers.get(\"x-Content-Encoding\"), ImmutableList.of(\"gzip\"));\n      } finally {\n         if (payload != null) {\n            payload.release();\n         }\n         closeQuietly(client);\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testPostContentLanguage() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().addHeader(\"x-Content-Language\", \"mi, en\"));\n      IntegrationTestClient client = client(server.url(\"/\").toString());\n      Payload payload = null;\n      try {\n         ByteSource body = ByteSource.wrap(\"foo\".getBytes());\n         payload = newByteSourcePayload(body);\n         payload.getContentMetadata().setContentLanguage(\"mi, en\");\n         payload.getContentMetadata().setContentLength(body.size());\n         Multimap<String, String> headers = client.postPayloadAndReturnHeaders(\"\", payload);\n         RecordedRequest request = server.takeRequest();\n         assertEquals(request.getHeader(\"Content-Language\"), \"mi, en\");\n         assertEquals(headers.get(\"x-Content-Language\"), ImmutableList.of(\"mi, en\"));\n      } finally {\n         if (payload != null) {\n            payload.release();\n         }\n         closeQuietly(client);\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testPut() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(\"fooPUT\"));\n      IntegrationTestClient client = client(server.url(\"/\").toString());\n      try {\n         String result = client.upload(\"\", \"foo\");\n         // Verify that the body is properly populated\n         RecordedRequest request = server.takeRequest();\n         assertEquals(request.getBody().readUtf8(), \"foo\");\n         assertEquals(result, \"fooPUT\");\n      } finally {\n         closeQuietly(client);\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testPutRedirect() throws Exception {\n      MockWebServer redirectTarget = mockWebServer(new MockResponse().setBody(\"fooPUTREDIRECT\"));\n      redirectTarget.useHttps(sslSocketFactory(), false);\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(302).setHeader(\"Location\",\n            redirectTarget.url(\"/\").toString()));\n      IntegrationTestClient client = client(server.url(\"/\").toString());\n      try {\n         String result = client.upload(\"redirect\", \"foo\");\n         assertEquals(result, \"fooPUTREDIRECT\");\n         assertEquals(server.getRequestCount(), 1);\n         assertEquals(redirectTarget.getRequestCount(), 1);\n         // Verify that the body was populated after the redirect\n         RecordedRequest request = server.takeRequest();\n         assertEquals(request.getBody().readUtf8(), \"foo\");\n         request = redirectTarget.takeRequest();\n         assertEquals(request.getBody().readUtf8(), \"foo\");\n      } finally {\n         closeQuietly(client);\n         redirectTarget.shutdown();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testZeroLengthPut() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse());\n      IntegrationTestClient client = client(server.url(\"/\").toString());\n      try {\n         client.putNothing(\"\");\n         assertEquals(server.getRequestCount(), 1);\n         RecordedRequest request = server.takeRequest();\n         assertEquals(request.getBody().readUtf8(), \"\");\n      } finally {\n         closeQuietly(client);\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testPutIsRetriedOnFailure() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(500),\n            new MockResponse().setBody(\"fooPUT\"));\n      IntegrationTestClient client = client(server.url(\"/\").toString());\n      try {\n         String result = client.upload(\"\", \"foo\");\n         assertEquals(server.getRequestCount(), 2);\n         assertEquals(result, \"fooPUT\");\n         // Verify that the body was properly sent in the two requests\n         RecordedRequest request = server.takeRequest();\n         assertEquals(request.getBody().readUtf8(), \"foo\");\n         request = server.takeRequest();\n         assertEquals(request.getBody().readUtf8(), \"foo\");\n      } finally {\n         closeQuietly(client);\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testHead() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse());\n      IntegrationTestClient client = client(server.url(\"/\").toString());\n      try {\n         assertTrue(client.exists(\"\"));\n      } finally {\n         closeQuietly(client);\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testHeadIsRetriedOnServerError() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(500), new MockResponse());\n      IntegrationTestClient client = client(server.url(\"/\").toString());\n      try {\n         assertTrue(client.exists(\"\"));\n         assertEquals(server.getRequestCount(), 2);\n      } finally {\n         closeQuietly(client);\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testHeadFailure() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(404));\n      IntegrationTestClient client = client(server.url(\"/\").toString());\n      try {\n         assertFalse(client.exists(\"\"));\n      } finally {\n         closeQuietly(client);\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testGetAndParseSax() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(XML));\n      IntegrationTestClient client = client(server.url(\"/\").toString());\n      try {\n         String result = client.downloadAndParse(\"\");\n         assertEquals(result, \"whoppers\");\n      } finally {\n         closeQuietly(client);\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testInterruptThrottledGet() throws Exception {\n      long timeoutMillis = 10 * 1000;\n      MockWebServer server = mockWebServer(new MockResponse().setBody(XML).throttleBody(XML.length() / 2, timeoutMillis, TimeUnit.MILLISECONDS));\n      IntegrationTestClient client = client(server.url(\"/\").toString());\n      try {\n         HttpResponse response = client.invoke(HttpRequest.builder()\n            .method(\"GET\")\n            .endpoint(server.url(\"/\").uri())\n            .build());\n         InputStream is = response.getPayload().openStream();\n         long now = System.currentTimeMillis();\n         is.close();\n         long diff = System.currentTimeMillis() - now;\n         assertTrue(diff < timeoutMillis / 2, \"expected \" + diff + \" to be less than \" + (timeoutMillis / 2));\n      } finally {\n         closeQuietly(client);\n         try {\n            server.shutdown();\n         } catch (IOException ex) {\n            // MockWebServer 2.1.0 introduces an active wait for its executor termination.\n            // That active wait is a hardcoded value and throws an IOE if the executor has not\n            // terminated in that timeout. It is safe to ignore this exception (related to how\n            // throttling works internally in MWS), as the functionality has been properly verified.\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/http/BaseHttpErrorHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.reportMatcher;\nimport static org.easymock.EasyMock.verify;\n\nimport java.net.URI;\n\nimport org.easymock.IArgumentMatcher;\nimport org.jclouds.http.functions.config.SaxParserModule;\n\nimport com.google.inject.Guice;\n\npublic abstract class BaseHttpErrorHandlerTest {\n\n   public static Exception classEq(final Class<? extends Exception> in) {\n      reportMatcher(new IArgumentMatcher() {\n\n         @Override\n         public void appendTo(StringBuffer buffer) {\n            buffer.append(\"classEq(\");\n            buffer.append(in);\n            buffer.append(\")\");\n         }\n\n         @Override\n         public boolean matches(Object arg) {\n            return arg.getClass() == in;\n         }\n\n      });\n      return null;\n   }\n\n   protected abstract Class<? extends HttpErrorHandler> getHandlerClass();\n\n   protected void assertCodeMakes(String method, URI uri, int statusCode, String message, String content,\n            Class<? extends Exception> expected) {\n      assertCodeMakes(method, uri, statusCode, message, null, content, expected);\n   }\n\n   protected void assertCodeMakes(String method, URI uri, int statusCode, String message, String contentType,\n            String content, Class<? extends Exception> expected) {\n\n      HttpErrorHandler function = Guice.createInjector(new SaxParserModule()).getInstance(getHandlerClass());\n\n      HttpCommand command = createMock(HttpCommand.class);\n      HttpRequest request = HttpRequest.builder().method(method).endpoint(uri).build();\n      HttpResponse response = HttpResponse.builder().statusCode(statusCode).message(message).payload(content).build();\n      if (contentType != null)\n         response.getPayload().getContentMetadata().setContentType(contentType);\n\n      expect(command.getCurrentRequest()).andReturn(request).atLeastOnce();\n      command.setException(classEq(expected));\n\n      replay(command);\n\n      function.handleError(command, response);\n\n      verify(command);\n   }\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/http/BaseMockWebServerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http;\n\nimport static org.jclouds.Constants.PROPERTY_RELAX_HOSTNAME;\nimport static org.jclouds.Constants.PROPERTY_TRUST_ALL_CERTS;\n\nimport java.io.Closeable;\nimport java.io.IOException;\nimport java.net.InetAddress;\nimport java.net.UnknownHostException;\nimport java.util.Properties;\n\nimport javax.net.ssl.SSLSocketFactory;\n\nimport okhttp3.mockwebserver.Dispatcher;\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\nimport okhttp3.tls.HandshakeCertificates;\nimport okhttp3.tls.HeldCertificate;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.providers.AnonymousProviderMetadata;\nimport org.testng.annotations.BeforeClass;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n\n/**\n * Base class for integration tests that use {@link MockWebServer} to verify the\n * behavior of the HTTP workflows.\n */\npublic abstract class BaseMockWebServerTest {\n\n   protected HandshakeCertificates serverCertificates;\n\n   @BeforeClass(groups = \"integration\")\n   protected void setupSSL() {\n      try {\n         String localhost = InetAddress.getLocalHost().getHostName();\n         HeldCertificate localhostCertificate = new HeldCertificate.Builder()\n             .addSubjectAlternativeName(localhost)\n             .build();\n\n         serverCertificates = new HandshakeCertificates.Builder()\n             .heldCertificate(localhostCertificate)\n             .build();\n      } catch (UnknownHostException ex) {\n         throw new RuntimeException(ex);\n      }\n   }\n\n   /**\n    * Creates a {@link MockWebServer} that uses the\n    * {@link GlobalChecksRequestDispatcher}.\n    */\n   protected static MockWebServer mockWebServer(MockResponse... responses) throws IOException {\n      MockWebServer server = new MockWebServer();\n      server.start();\n      for (MockResponse response : responses) {\n         server.enqueue(response);\n      }\n      return server;\n   }\n\n   /**\n    * Creates a {@link MockWebServer} that uses the given {@link Dispatcher}.\n    */\n   protected static MockWebServer mockWebServer(Dispatcher dispatcher) throws IOException {\n      MockWebServer server = new MockWebServer();\n      server.start();\n      server.setDispatcher(dispatcher);\n      return server;\n   }\n\n   /**\n    * Creates a test api for the given class and URL.\n    */\n   protected <T extends Closeable> T api(Class<T> apiClass, String url) {\n      return api(apiClass, url, createConnectionModule());\n   }\n\n   /**\n    * Creates a test api for the given class, URI and Module.\n    */\n   protected <T extends Closeable> T api(Class<T> apiClass, String url, Module... connectionModules) {\n      Properties properties = new Properties();\n      properties.setProperty(PROPERTY_TRUST_ALL_CERTS, \"true\");\n      properties.setProperty(PROPERTY_RELAX_HOSTNAME, \"true\");\n      addOverrideProperties(properties);\n      return ContextBuilder.newBuilder(AnonymousProviderMetadata.forApiOnEndpoint(apiClass, url))\n            .modules(ImmutableSet.copyOf(connectionModules)).overrides(properties).buildApi(apiClass);\n   }\n\n   protected SSLSocketFactory sslSocketFactory() {\n      return serverCertificates.sslSocketFactory();\n   }\n\n   /**\n    * Add the connection properties used to configure the tests.\n    */\n   protected abstract void addOverrideProperties(Properties props);\n\n   /**\n    * Return the connection module that provides the HTTP driver to use in the\n    * tests.\n    * <p>\n    * Unless a concrete HTTP is required, subclasses may want to use the\n    * {@link org.jclouds.http.config.JavaUrlHttpCommandExecutorServiceModule}.\n    */\n   protected abstract Module createConnectionModule();\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/http/HttpMessageTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMultimap;\n\n@Test(testName = \"HttpMessageTest\")\npublic class HttpMessageTest {\n\n   public void testEndpoint() {\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://foo\").build();\n\n      assertEquals(request.toBuilder()\n                          .endpoint(\"http://bar\").build(), \n              HttpRequest.builder()\n                         .method(\"GET\")\n                         .endpoint(\"http://bar\").build());\n   }\n\n   public void testReplaceHeader() {\n      HttpRequest request = HttpRequest.builder()\n                                       .method(\"GET\")\n                                       .endpoint(\"http://foo\")\n                                       .addHeader(\"foo\", \"bar\").build();\n\n      assertEquals(request.toBuilder().replaceHeader(\"foo\", \"baz\").build(), \n               HttpRequest.builder()\n                          .method(\"GET\")\n                          .endpoint(\"http://foo\")\n                          .addHeader(\"foo\", \"baz\").build());\n   }\n\n   public void testRemoveHeader() {\n      HttpRequest request = HttpRequest.builder()\n                                       .method(\"GET\")\n                                       .endpoint(\"http://foo\")\n                                       .addHeader(\"foo\", \"bar\").build();\n\n      assertEquals(request.toBuilder().removeHeader(\"foo\").build(),\n               HttpRequest.builder().method(\"GET\").endpoint(\"http://foo\").build());\n   }\n\n   public void testReplaceHeaders() {\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://foo\")\n                                       .addHeader(\"foo\", \"bar\")\n                                       .addHeader(\"rabbit\", \"tree\").build();\n\n      assertEquals(\n               request.toBuilder()\n                      .replaceHeaders(ImmutableMultimap.of(\"foo\", \"bar\", \"rabbit\", \"robot\", \"robert\", \"baz\")).build().getHeaders(),\n               ImmutableMultimap.of(\"foo\", \"bar\", \"rabbit\", \"robot\", \"robert\", \"baz\"));\n   }\n\n   public void testPutHeadersAddsAnotherValue() {\n      HttpRequest request = HttpRequest.builder()\n                                       .method(\"GET\").endpoint(\"http://foo\")\n                                       .addHeader(\"foo\", \"bar\").build();\n\n      assertEquals(request.toBuilder()\n                          .addHeader(\"foo\", \"baz\").build().getHeaders(), \n                   ImmutableMultimap.<String, String> builder()\n                                    .putAll(\"foo\", \"bar\", \"baz\").build());\n   }\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/http/HttpRequestTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http;\n\nimport static com.google.common.net.MediaType.FORM_DATA;\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\n\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMultimap;\n\n/**\n * Tests parsing of a request\n */\n@Test(testName = \"http.HttpRequestTest\")\npublic class HttpRequestTest {\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testConstructorHostNull() throws Exception {\n      URI uri = URI.create(\"http://adriancole.compute1138eu.s3-external-3.amazonaws.com:-1\");\n      assert uri.getHost() == null : \"test requires something to produce a uri with a null hostname\";\n      HttpRequest.builder().method(\"GET\").endpoint(uri).build();\n   }\n\n   public void testReplaceQueryParams() throws Exception {\n      URI uri = URI.create(\"http://goo.com:443?header=value1\");\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(uri).build();\n\n      assertEquals(request.toBuilder().replaceQueryParam(\"header\", \"foo\").build(), HttpRequest.builder().method(\"GET\")\n               .endpoint(\"http://goo.com:443?header=foo\").build());\n   }\n\n   // it is easy to accidentally encode twice. make sure this always works!\n   public void testEncodesOnlyOnce() throws Exception {\n      URI uri = URI.create(\"http://goo.com:443?header=value1\");\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(uri).build();\n\n      assertEquals(request.toBuilder().replaceQueryParam(\"header\", \"hello?\").build(),\n            HttpRequest.builder().method(\"GET\").endpoint(\"http://goo.com:443?header=hello%3F\").build());\n   }\n\n   public void testAddFormParamAddsAnotherValue() {\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://foo\")\n               .payload(\"foo=bar\").build();\n      Payload payload = Payloads.newStringPayload(\"foo=bar&foo=baz\");\n      payload.getContentMetadata().setContentType(FORM_DATA.toString());\n      assertEquals(request.toBuilder().addFormParams(ImmutableMultimap.of(\"foo\", \"baz\")).build(), HttpRequest\n               .builder().method(\"GET\").endpoint(\"http://foo\").payload(payload).build());\n   }\n\n   // note that + ends up encoded as %2B (plus) and %2F converts back into slash\n   public void testAddBase64AndUrlEncodedQueryParams() {\n      String base64Chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\";\n      URI uri = URI.create(\"http://goo.com:443?header1=\" + Strings2.urlEncode(base64Chars));\n      HttpRequest request = HttpRequest.builder()\n            .method(\"GET\")\n            .endpoint(uri)\n            .addQueryParam(\"header2\", base64Chars)\n            .build();\n\n      assertEquals(\n            request.getRequestLine(),\n            \"GET http://goo.com:443?header1=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789%2B/%3D&header2=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789%2B/%3D HTTP/1.1\");\n   }\n\n   // base64 symbols with newline separator should be url encoded in query param\n   public void testAddBase64EncodedQueryParamWithNewlines() {\n      String base64Chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\\nabcdefghijklmnopqrstuvwxyz\\n0123456789+/=\";\n      URI uri = URI.create(\"http://goo.com:443?header1=value1\");\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(uri)\n            .addQueryParam(\"header2\", base64Chars).build();\n\n      assertEquals(\n            request.getRequestLine(),\n            \"GET http://goo.com:443?header1=value1&header2=ABCDEFGHIJKLMNOPQRSTUVWXYZ%0Aabcdefghijklmnopqrstuvwxyz%0A0123456789%2B/%3D HTTP/1.1\");\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/http/IntegrationTestClient.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http;\n\nimport java.io.Closeable;\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\nimport jakarta.inject.Singleton;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.HEAD;\nimport jakarta.ws.rs.HeaderParam;\nimport jakarta.ws.rs.HttpMethod;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\n\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.http.options.HttpRequestOptions;\nimport org.jclouds.io.Payload;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.XMLResponseParser;\nimport org.jclouds.rest.binders.BindToJsonPayload;\nimport org.jclouds.rest.binders.BindToStringPayload;\nimport org.jclouds.util.Strings2;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.Multimap;\nimport com.google.inject.Provides;\n\n/**\n * Sample test for the behaviour of our Integration Test jetty server.\n */\npublic interface IntegrationTestClient extends Closeable {\n   @Target({ ElementType.METHOD })\n   @Retention(RetentionPolicy.RUNTIME)\n   @HttpMethod(\"ROWDY\")\n   public @interface ROWDY {\n   }\n\n   @ROWDY\n   @Path(\"/objects/{id}\")\n   String rowdy(@PathParam(\"id\") String path);\n\n   @HEAD\n   @Path(\"/objects/{id}\")\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean exists(@PathParam(\"id\") String path);\n\n   @GET\n   @Path(\"/objects/{id}\")\n   String download(@PathParam(\"id\") String id);\n\n   HttpResponse invoke(HttpRequest request);\n   \n   @GET\n   @Path(\"/{path}\")\n   String synch(@PathParam(\"path\") String id);\n\n   @GET\n   @Path(\"/objects/{id}\")\n   @Fallback(FooOnException.class)\n   String downloadException(@PathParam(\"id\") String id, HttpRequestOptions options);\n\n   static class FooOnException implements org.jclouds.Fallback<String> {\n      public String createOrPropagate(Throwable t) throws Exception {\n         return \"foo\";\n      }\n   }\n\n   @GET\n   @Path(\"/objects/{id}\")\n   @Fallback(FooOnException.class)\n   String synchException(@PathParam(\"id\") String id, @HeaderParam(\"Range\") String header);\n\n   @PUT\n   @Path(\"/objects/{id}\")\n   String upload(@PathParam(\"id\") String id, @BinderParam(BindToStringPayload.class) String toPut);\n\n   @POST\n   @Path(\"/objects/{id}\")\n   String post(@PathParam(\"id\") String id, @BinderParam(BindToStringPayload.class) String toPut);\n\n   @POST\n   @Path(\"/objects/{id}\")\n   String postAsInputStream(@PathParam(\"id\") String id,\n         @BinderParam(BindToInputStreamPayload.class) String toPut);\n\n   static class BindToInputStreamPayload extends BindToStringPayload {\n      @Override\n      public <R extends HttpRequest> R bindToRequest(R request, Object payload) {\n         request.setPayload(Strings2.toInputStream(payload.toString()));\n         request.getPayload().getContentMetadata().setContentLength((long) payload.toString().getBytes().length);\n         return request;\n      }\n   }\n\n   @Singleton\n   static class ResponsePayload implements Function<HttpResponse, Multimap<String, String>> {\n\n      public Multimap<String, String> apply(HttpResponse from) {\n         return from.getHeaders();\n      }\n\n   }\n\n   @POST\n   @Path(\"/objects/{id}\")\n   @ResponseParser(ResponsePayload.class)\n   Multimap<String, String> postPayloadAndReturnHeaders(@PathParam(\"id\") String id, Payload payload);\n\n   @POST\n   @Path(\"/objects/{id}\")\n   @MapBinder(BindToJsonPayload.class)\n   String postJson(@PathParam(\"id\") String id, @PayloadParam(\"key\") String toPut);\n\n   @GET\n   @Path(\"/objects/{id}\")\n   @RequestFilters(Filter.class)\n   String downloadFilter(@PathParam(\"id\") String id, @HeaderParam(\"filterme\") String header);\n\n   static class Filter implements HttpRequestFilter {\n      public HttpRequest filter(HttpRequest request) throws HttpException {\n         if (request.getHeaders().containsKey(\"filterme\")) {\n            request = request.toBuilder().replaceHeader(\"test\", \"test\").build();\n         }\n         return request;\n      }\n   }\n\n   @GET\n   @Path(\"/objects/{id}\")\n   String download(@PathParam(\"id\") String id, @HeaderParam(\"test\") String header);\n\n   @GET\n   @Path(\"/objects/{id}\")\n   @XMLResponseParser(BarHandler.class)\n   String downloadAndParse(@PathParam(\"id\") String id);\n\n   public static class BarHandler extends ParseSax.HandlerWithResult<String> {\n\n      private String bar = null;\n      private StringBuilder currentText = new StringBuilder();\n\n      @Override\n      public void endElement(String uri, String name, String qName) {\n         if (qName.equals(\"bar\")) {\n            bar = currentText.toString();\n         }\n         currentText.setLength(0);\n      }\n\n      @Override\n      public void characters(char[] ch, int start, int length) {\n         currentText.append(ch, start, length);\n\n      }\n\n      @Override\n      public String getResult() {\n         return bar;\n      }\n\n   }\n\n   @PUT\n   @Path(\"/objects/{id}\")\n   void putNothing(@PathParam(\"id\") String id);\n   \n   @POST\n   @Path(\"/objects/{id}\")\n   void postNothing(@PathParam(\"id\") String id);\n\n   @Provides\n   StringBuilder newStringBuilder();\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/http/IntegrationTestClientExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http;\n\nimport static com.google.common.base.Throwables.propagate;\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\nimport java.util.concurrent.atomic.AtomicInteger;\n\nimport javax.net.ssl.SSLException;\n\nimport org.jclouds.providers.JcloudsTestBlobStoreProviderMetadata;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.rest.internal.BaseRestApiExpectTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\n\n/**\n * \n * Allows us to test a client via its side effects.\n */\n@Test(groups = \"unit\", testName = \"IntegrationTestClientExpectTest\")\n// only needed as IntegrationTestClient is not registered in rest.properties\npublic class IntegrationTestClientExpectTest extends BaseRestApiExpectTest<IntegrationTestClient> {\n   \n   public void testRetryOnSSLExceptionClose() {\n      // keeps track of request count\n      final AtomicInteger counter = new AtomicInteger(0);\n\n      IntegrationTestClient client = createClient(new Function<HttpRequest, HttpResponse>() {\n         @Override\n         public HttpResponse apply(HttpRequest input) {\n            // on first request, throw an SSL close_notify exception\n            if (counter.getAndIncrement() == 0)\n               throw propagate(new SSLException(\"Received close_notify during handshake\"));\n            \n            // on other requests, just validate and return 200\n            assertEquals(renderRequest(input), renderRequest(HttpRequest.builder().method(\"HEAD\").endpoint(\n                     URI.create(\"http://mock/objects/rabbit\")).build()));\n            return HttpResponse.builder().statusCode(200).build();\n         }\n      });\n\n      // try three times, first should fail quietly due to retry logic\n      for (int i = 0; i < 3; i++)\n         assertEquals(client.exists(\"rabbit\"), true);\n\n      // should be an extra request relating to the retry\n      assertEquals(counter.get(), 4);\n\n   }\n   \n   public void testWhenResponseIs2xxExistsReturnsTrue() {\n\n      IntegrationTestClient client = requestSendsResponse(HttpRequest.builder().method(\"HEAD\").endpoint(\n               URI.create(\"http://mock/objects/rabbit\")).build(), HttpResponse.builder().statusCode(200).build());\n\n      assertEquals(client.exists(\"rabbit\"), true);\n\n   }\n\n   public void testWhenResponseIs404ExistsReturnsFalse() {\n\n      IntegrationTestClient client = requestSendsResponse(HttpRequest.builder().method(\"HEAD\").endpoint(\n               URI.create(\"http://mock/objects/rabbit\")).build(), HttpResponse.builder().statusCode(404).build());\n\n      assertEquals(client.exists(\"rabbit\"), false);\n\n   }\n\n   @Override\n   public ProviderMetadata createProviderMetadata() {\n      return new JcloudsTestBlobStoreProviderMetadata();\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/http/JavaUrlHttpCommandExecutorServiceIntegrationTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http;\n\nimport static com.google.common.net.HttpHeaders.CONTENT_LENGTH;\nimport static org.jclouds.Constants.PROPERTY_MAX_CONNECTIONS_PER_CONTEXT;\nimport static org.jclouds.Constants.PROPERTY_MAX_CONNECTIONS_PER_HOST;\nimport static org.jclouds.Constants.PROPERTY_USER_THREADS;\nimport static org.jclouds.util.Closeables2.closeQuietly;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.fail;\n\nimport java.util.Properties;\n\nimport okhttp3.mockwebserver.Dispatcher;\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\nimport okhttp3.mockwebserver.RecordedRequest;\n\nimport org.jclouds.http.config.JavaUrlHttpCommandExecutorServiceModule;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.payloads.StringPayload;\nimport org.jclouds.rest.HttpClient;\nimport org.jclouds.utils.TestUtils;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Module;\n\n\n@Test(groups = \"integration\")\npublic class JavaUrlHttpCommandExecutorServiceIntegrationTest extends BaseHttpCommandExecutorServiceIntegrationTest {\n\n   protected Module createConnectionModule() {\n      return new JavaUrlHttpCommandExecutorServiceModule();\n   }\n\n   protected void addOverrideProperties(Properties props) {\n      props.setProperty(PROPERTY_MAX_CONNECTIONS_PER_CONTEXT, 50 + \"\");\n      props.setProperty(PROPERTY_MAX_CONNECTIONS_PER_HOST, 0 + \"\");\n      props.setProperty(PROPERTY_USER_THREADS, 5 + \"\");\n   }\n\n   @Test public void longContentLengthSupported() throws Exception {\n      long reallyLongContent = TestUtils.isJava6() ? Integer.MAX_VALUE : Long.MAX_VALUE;\n\n      // Setup a mock server that doesn't attempt to read the request payload.\n      MockWebServer server = new MockWebServer();\n      server.setDispatcher(new Dispatcher() {\n         @Override public MockResponse dispatch(RecordedRequest recordedRequest) {\n            return new MockResponse();\n         }\n      });\n      server.start();\n\n      HttpClient client =  api(HttpClient.class, server.url(\"/\").toString());\n\n      // Make a fake payload that has no data, but says there's a lot!\n      Payload fakePayload = new StringPayload(\"\");\n      fakePayload.getContentMetadata().setContentLength(reallyLongContent);\n\n      try {\n         try {\n            client.post(server.url(\"/\").uri(), fakePayload);\n            fail(\"Should have errored since we didn't sent that much data!\");\n         } catch (HttpResponseException expected) {\n         }\n         assertEquals(server.takeRequest().getHeader(CONTENT_LENGTH), String.valueOf(reallyLongContent));\n      } finally {\n         closeQuietly(client);\n         server.shutdown();\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/http/TransformingHttpCommandImplTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http;\n\nimport org.testng.annotations.Test;\n\npublic class TransformingHttpCommandImplTest {\n\n   @Test\n   public void testTransformingHttpCommandImpl() {\n      // TODO\n   }\n\n   @Test\n   public void testExecute() {\n      // TODO\n   }\n\n   @Test\n   public void testGetFailureCount() {\n      // TODO\n   }\n\n   @Test\n   public void testIncrementFailureCount() {\n      // TODO\n   }\n\n   @Test\n   public void testSetCurrentEndpoint() {\n      // TODO\n   }\n\n   @Test\n   public void testGetCurrentEndpoint() {\n      // TODO\n   }\n\n   @Test\n   public void testSetException() {\n      // TODO\n   }\n\n   @Test\n   public void testGetException() {\n      // TODO\n   }\n\n   @Test\n   public void testIncrementRedirectCount() {\n      // TODO\n   }\n\n   @Test\n   public void testGetRedirectCount() {\n      // TODO\n   }\n\n   @Test\n   public void testIsReplayable() {\n      // TODO\n   }\n\n   @Test\n   public void testBuildRequest() {\n      // TODO\n   }\n\n   @Test\n   public void testSetCurrentMethod() {\n      // TODO\n   }\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/http/UriTemplatesTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http;\n\nimport static org.jclouds.http.UriTemplates.expand;\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.DataProvider;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\n\n@Test\npublic class UriTemplatesTest {\n\n   @DataProvider(name = \"strings\")\n   public Object[][] createData() {\n      return new Object[][] { { \"apples\" }, { \"sp ace\" }, { \"unic₪de\" }, { \"qu?stion\" } };\n   }\n\n   @Test(dataProvider = \"strings\")\n   public void testExpandNotUrlEncoded(String val) {\n      assertEquals(expand(\"/repos/{user}\", ImmutableMap.of(\"user\", val)), \"/repos/\" + val);\n   }\n\n   public void testMultipleParams() {\n      assertEquals(expand(\"/repos/{user}/{repo}\", ImmutableMap.of(\"user\", \"unic₪de\", \"repo\", \"foo\")),\n            \"/repos/unic₪de/foo\");\n   }\n\n   // jclouds params often include hyphens\n   public void testParamKeyHyphen() {\n      assertEquals(expand(\"/{user-dir}\", ImmutableMap.of(\"user-dir\", \"foo\")), \"/foo\");\n   }\n\n   // sometimes the user intends to have a curly brace in the url\n   public void testMissingParamProceeds() {\n      assertEquals(expand(\"/{user-dir}\", ImmutableMap.of(\"user_dir\", \"foo\")), \"/{user-dir}\");\n   }\n\n   public void testJson() {\n      assertEquals(expand(\"{\\\"key\\\":\\\"{variable}\\\"}\", ImmutableMap.of(\"variable\", \"value\")), \"{\\\"key\\\":\\\"value\\\"}\");\n   }\n\n   public void testExpandWithOpenedCurveBracket() {\n      assertEquals(expand(\"/repos/folder with { brackets in a key\", ImmutableMap.of()),\n              \"/repos/folder with { brackets in a key\");\n      assertEquals(expand(\"/repos/folder with {foo\", ImmutableMap.of(\"foo\", \"var\")),\n              \"/repos/folder with {foo\");\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/http/UrisTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http;\n\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.jclouds.http.Uris.uriBuilder;\nimport static org.jclouds.util.Strings2.urlEncode;\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\n\nimport org.testng.annotations.DataProvider;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\n\n@Test\npublic class UrisTest {\n\n   private static final ImmutableMap<String, String> templateParams = ImmutableMap.of(\"user\", \"bob\");\n\n   public void testScheme() {\n      assertEquals(uriBuilder(\"https://foo.com:8080\").scheme(\"http\").toString(), \"http://foo.com:8080\");\n      assertEquals(uriBuilder(\"https://foo.com:8080\").scheme(\"http\").build().toString(), \"http://foo.com:8080\");\n      assertEquals(uriBuilder(\"https://api.github.com/repos/user?foo=bar&kung=fu\").scheme(\"http\").toString(),\n            \"http://api.github.com/repos/user?foo=bar&kung=fu\");\n      assertEquals(uriBuilder(\"https://api.github.com/repos/user?foo=bar&kung=fu\").scheme(\"http\").build().toString(),\n            \"http://api.github.com/repos/user?foo=bar&kung=fu\");\n      assertEquals(uriBuilder(\"https://api.github.com/repos/{user}\").scheme(\"http\").toString(),\n            \"http://api.github.com/repos/{user}\");\n      assertEquals(uriBuilder(\"https://api.github.com/repos/{user}\").scheme(\"http\").build(templateParams)\n            .toASCIIString(), \"http://api.github.com/repos/bob\");\n\n   }\n\n   public void testHost() {\n      assertEquals(uriBuilder(\"https://foo.com:8080\").host(\"robots\").toString(), \"https://robots:8080\");\n      assertEquals(uriBuilder(\"https://foo.com:8080\").host(\"robots\").build().toString(), \"https://robots:8080\");\n      assertEquals(uriBuilder(\"https://api.github.com/repos/user?foo=bar&kung=fu\").host(\"robots\").toString(),\n            \"https://robots/repos/user?foo=bar&kung=fu\");\n      assertEquals(uriBuilder(\"https://api.github.com/repos/user?foo=bar&kung=fu\").host(\"robots\").build().toString(),\n            \"https://robots/repos/user?foo=bar&kung=fu\");\n      assertEquals(uriBuilder(\"https://api.github.com/repos/{user}\").host(\"robots\").toString(),\n            \"https://robots/repos/{user}\");\n      assertEquals(uriBuilder(\"https://api.github.com/repos/{user}\").host(\"robots\").build(templateParams)\n            .toASCIIString(), \"https://robots/repos/bob\");\n   }\n\n   @DataProvider(name = \"strings\")\n   public Object[][] createData() {\n      return new Object[][] { { \"normal\" }, { \"sp ace\" }, { \"qu?stion\" }, { \"unic₪de\" }, { \"path/foo\" }, { \"colon:\" },\n            { \"asteri*k\" }, { \"quote\\\"\" }, { \"great<r\" }, { \"lesst>en\" }, { \"p|pe\" } };\n   }\n\n   @Test(dataProvider = \"strings\")\n   public void testQuery(String val) {\n      assertThat(uriBuilder(\"https://foo.com:8080\").addQuery(\"moo\", val).build().getQuery())\n            .isEqualTo(\"moo=\" + val);\n      assertThat(uriBuilder(\"https://foo.com:8080\").addQuery(\"moo\", val).build().getRawQuery())\n            .isEqualTo(\"moo=\" + urlEncode(val, '/', ','));\n      assertThat(uriBuilder(\"https://api.github.com/repos/user?foo=bar&kung=fu\").addQuery(\"moo\", val).build()\n            .getQuery())\n            .isEqualTo(\"foo=bar&kung=fu&moo=\" + val);\n      assertThat(uriBuilder(\"https://api.github.com/repos/user?foo=bar&kung=fu\").addQuery(\"moo\", val).build()\n            .getRawQuery())\n            .isEqualTo(\"foo=bar&kung=fu&moo=\" + urlEncode(val, '/', ','));\n      assertThat(uriBuilder(\"https://api.github.com/repos/{user}\").addQuery(\"moo\", val).build().getQuery())\n            .isEqualTo(\"moo=\" + val);\n      assertThat(uriBuilder(\"https://api.github.com/repos/{user}\").addQuery(\"moo\", val).toString())\n            .isEqualTo(\"https://api.github.com/repos/{user}?moo=\" + urlEncode(val, '/', ','));\n      assertThat(uriBuilder(\"https://api.github.com/repos/{user}\").addQuery(\"moo\", val).build(templateParams)\n            .getRawQuery())\n            .isEqualTo(\"moo=\" + urlEncode(val, '/', ','));\n      assertThat(uriBuilder(\"https://api.github.com/repos/{user}\").addQuery(\"moo\", val).build(templateParams)\n            .getPath())\n            .isEqualTo(\"/repos/bob\");\n   }\n\n   @Test(dataProvider = \"strings\")\n   public void testPath(String path) {\n      assertEquals(uriBuilder(\"https://foo.com:8080\").path(path).toString(), \"https://foo.com:8080/\" + path);\n      assertEquals(uriBuilder(\"https://foo.com:8080\").path(path).build().toString(), \"https://foo.com:8080/\"\n            + urlEncode(path, '/', ':', ';', '='));\n      assertEquals(uriBuilder(\"https://api.github.com/repos/user?foo=bar&kung=fu\").path(path).toString(),\n            \"https://api.github.com/\" + path + \"?foo=bar&kung=fu\");\n      assertEquals(uriBuilder(\"https://api.github.com/repos/user?foo=bar&kung=fu\").path(path).build().toString(),\n            \"https://api.github.com/\" + urlEncode(path, '/', ':', ';', '=') + \"?foo=bar&kung=fu\");\n      assertEquals(uriBuilder(\"https://api.github.com/repos/{user}\").path(path).toString(), \"https://api.github.com/\"\n            + path);\n      assertEquals(uriBuilder(\"https://api.github.com/repos/{user}\").path(path).build(templateParams).toASCIIString(),\n            \"https://api.github.com/\" + urlEncode(path, '/', ':', ';', '='));\n   }\n\n   @Test(dataProvider = \"strings\")\n   public void testAppendPath(String path) {\n      assertEquals(uriBuilder(\"https://foo.com:8080\").appendPath(path).toString(), \"https://foo.com:8080/\" + path);\n      assertEquals(uriBuilder(\"https://foo.com:8080\").appendPath(path).build().toString(), \"https://foo.com:8080/\"\n            + urlEncode(path, '/', ':', ';', '='));\n      assertEquals(uriBuilder(\"https://api.github.com/repos/user?foo=bar&kung=fu\").appendPath(path).toString(),\n            \"https://api.github.com/repos/user/\" + path + \"?foo=bar&kung=fu\");\n      assertEquals(uriBuilder(\"https://api.github.com/repos/user?foo=bar&kung=fu\").appendPath(path).build().toString(),\n            \"https://api.github.com/repos/user/\" + urlEncode(path, '/', ':', ';', '=') + \"?foo=bar&kung=fu\");\n      assertEquals(uriBuilder(\"https://api.github.com/repos/{user}\").appendPath(path).toString(),\n            \"https://api.github.com/repos/{user}/\" + path);\n      assertEquals(uriBuilder(\"https://api.github.com/repos/{user}\").appendPath(path).build(templateParams)\n            .toASCIIString(), \"https://api.github.com/repos/bob/\" + urlEncode(path, '/', ':', ';', '='));\n   }\n\n   @Test\n   public void testNoDoubleSlashInPath() {\n      assertEquals(uriBuilder(\"https://cloud/api/\").appendPath(\"/\").build().toASCIIString(), \"https://cloud/api/\");\n   }\n\n   @Test\n   public void testWhenMatrixOnPath() {\n      assertEquals(\n            uriBuilder(\"https://api.rimuhosting.com/r\").appendPath(\"orders;include_inactive=N\").build(templateParams)\n                  .toASCIIString(), \"https://api.rimuhosting.com/r/orders;include_inactive=N\");\n   }\n\n   @Test(dataProvider = \"strings\")\n   public void testReplaceQueryIsEncoded(String key) {\n      assertThat(uriBuilder(\"/redirect\").addQuery(\"foo\", key).build().getQuery()).isEqualTo(\"foo=\" + key);\n      assertThat(uriBuilder(\"/redirect\").addQuery(\"foo\", key).build().getRawQuery())\n            .isEqualTo(\"foo=\" + urlEncode(key, '/', ','));\n   }\n\n   public void testAddQuery() {\n      assertEquals(uriBuilder(\"http://localhost:8080/client/api\").addQuery(\"response\", \"json\").toString(),\n            \"http://localhost:8080/client/api?response=json\");\n\n      assertEquals(\n            uriBuilder(URI.create(\"http://localhost:8080/client/api\")).addQuery(\"response\", \"json\")\n                  .addQuery(\"command\", \"queryAsyncJobResult\").build().toString(),\n            \"http://localhost:8080/client/api?response=json&command=queryAsyncJobResult\");\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/http/config/SSLModuleTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.config;\n\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport org.testng.annotations.Test;\n\nimport static org.testng.Assert.assertSame;\n\n@Test(testName = \"http.config.SSLModuleTest\")\npublic class SSLModuleTest {\n\n    @Test\n    public void sameUntrustedSslContext() {\n        Injector injector = Guice.createInjector(new SSLModule());\n        SSLModule.UntrustedSSLContextSupplier untrustedSSLContextSupplier = injector.getInstance(SSLModule.UntrustedSSLContextSupplier.class);\n        assertSame(untrustedSSLContextSupplier.get(), untrustedSSLContextSupplier.get());\n    }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/http/filters/BasicAuthenticationTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.filters;\n\nimport static com.google.common.base.Suppliers.ofInstance;\nimport static com.google.common.collect.Queues.newArrayDeque;\nimport static com.google.common.net.HttpHeaders.AUTHORIZATION;\nimport static java.util.Arrays.asList;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Deque;\n\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\n\n@Test(groups = \"unit\")\npublic class BasicAuthenticationTest {\n   private static final Credentials credential1 = new Credentials(\"Aladdin\", \"open sesame\");\n   private static final Credentials credential2 = new Credentials(\"Little\", \"Mermaid\");\n\n   public void testAuth() {\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://localhost\").build();\n      request = new BasicAuthentication(ofInstance(credential1)).filter(request);\n      assertEquals(request.getFirstHeaderOrNull(AUTHORIZATION), \"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==\");\n      request = new BasicAuthentication(ofInstance(credential2)).filter(request);\n      assertEquals(request.getFirstHeaderOrNull(AUTHORIZATION), \"Basic TGl0dGxlOk1lcm1haWQ=\");\n   }\n\n   public void testAuthWithRuntimePasswordChange() {\n      Supplier<Credentials> credentialRotation = new Supplier<Credentials>() {\n         Deque<Credentials> rotation = newArrayDeque(asList(credential1, credential2));\n\n         public Credentials get() {\n            return rotation.poll();\n         }\n      };\n      BasicAuthentication filter = new BasicAuthentication(credentialRotation);\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://localhost\").build();\n      request = filter.filter(request);\n      assertEquals(request.getFirstHeaderOrNull(AUTHORIZATION), \"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==\");\n      request = filter.filter(request);\n      assertEquals(request.getFirstHeaderOrNull(AUTHORIZATION), \"Basic TGl0dGxlOk1lcm1haWQ=\");\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/http/filters/ConnectionCloseHeaderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.http.filters;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.http.HttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.net.HttpHeaders;\n\n@Test(groups = \"unit\")\npublic class ConnectionCloseHeaderTest {\n   public void testConnectionHeaderIsAdded() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      request = new ConnectionCloseHeader().filter(request);\n\n      assertTrue(request.getHeaders().containsKey(HttpHeaders.CONNECTION));\n      assertEquals(request.getHeaders().get(HttpHeaders.CONNECTION).size(), 1);\n      assertEquals(request.getHeaders().get(HttpHeaders.CONNECTION).iterator().next(), \"close\");\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/http/filters/StripExpectHeaderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.http.filters;\n\nimport static org.testng.Assert.assertFalse;\n\nimport org.jclouds.http.HttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.net.HttpHeaders;\n\n@Test(groups = \"unit\")\npublic class StripExpectHeaderTest {\n   public void testExpectHeaderIsStripped() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").addHeader(HttpHeaders.EXPECT, \"100-Continue\")\n         .endpoint(\"http://localhost\").build();\n      request = new StripExpectHeader().filter(request);\n      assertFalse(request.getHeaders().containsKey(HttpHeaders.EXPECT));\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/http/functions/BaseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.functions;\n\nimport static com.google.common.base.Throwables.propagate;\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport java.util.List;\n\nimport org.jclouds.http.functions.config.SaxParserModule;\nimport org.jclouds.reflect.Invocation;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.AfterTest;\nimport org.testng.annotations.BeforeTest;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\npublic class BaseHandlerTest {\n\n   protected Injector injector = null;\n   protected ParseSax.Factory factory;\n   protected GeneratedHttpRequest request;\n   private Invocation toString;\n\n   @BeforeTest\n   protected void setUpInjector() {\n      injector = Guice.createInjector(new SaxParserModule());\n      factory = injector.getInstance(ParseSax.Factory.class);\n      assert factory != null;\n   }\n\n   @BeforeTest\n   protected void setUpRequest() {\n      try {\n         toString = Invocation.create(method(String.class, \"toString\"), ImmutableList.of());\n      } catch (SecurityException e) {\n         throw propagate(e);\n      }\n      request = GeneratedHttpRequest.builder().method(\"POST\").endpoint(\"http://localhost/key\").invocation(toString)\n            .build();\n   }\n\n   @AfterTest\n   protected void tearDownInjector() {\n      factory = null;\n      injector = null;\n   }\n\n   protected GeneratedHttpRequest requestForArgs(List<Object> args) {\n      return GeneratedHttpRequest.builder().method(\"POST\").endpoint(\"http://localhost/key\")\n            .invocation(Invocation.create(toString.getInvokable(), args)).build();\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/http/functions/ParseFirstJsonValueNamedTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.json.internal.GsonWrapper;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\nimport com.google.inject.TypeLiteral;\n\n@Test(testName = \"ParseFirstJsonValueNamedTest\")\npublic class ParseFirstJsonValueNamedTest {\n\n   GsonWrapper json = Guice.createInjector(new GsonModule()).getInstance(GsonWrapper.class);\n\n   static class Event {\n      private String name;\n      private String source;\n\n      private Event(String name, String source) {\n         this.name = name;\n         this.source = source;\n      }\n\n      @Override\n      public String toString() {\n         return String.format(\"(name=%s, source=%s)\", name, source);\n      }\n   }\n\n   public void testParseNestedElements() throws IOException {\n      String nested = \"{ \\\"count\\\":1 ,\\\"event\\\" : [  {name:'GREETINGS',source:'guest'} ] }\";\n      HttpResponse response = HttpResponse.builder().statusCode(200).message(\"goodie\")\n            .payload(Payloads.newPayload(nested)).build();\n\n      List<Event> val = new ParseFirstJsonValueNamed<List<Event>>(json, new TypeLiteral<List<Event>>() {\n      }, \"event\").apply(response);\n      assertEquals(val.toString(), \"[(name=GREETINGS, source=guest)]\");\n   }\n   \n   /**\n    * scenario: server renames field from event to _event\n    */\n   public void testParseRenamedField() throws IOException {\n      String nested = \"{ \\\"count\\\":1 ,\\\"_event\\\" : [  {name:'GREETINGS',source:'guest'} ] }\";\n      HttpResponse response = HttpResponse.builder().statusCode(200).message(\"goodie\")\n            .payload(Payloads.newPayload(nested)).build();\n\n      List<Event> val = new ParseFirstJsonValueNamed<List<Event>>(json, new TypeLiteral<List<Event>>() {\n      }, \"event\", \"_event\").apply(response);\n      assertEquals(val.toString(), \"[(name=GREETINGS, source=guest)]\");\n   }\n\n   public void testParseNestedElementsWhenNotFoundIsEmpty() throws IOException {\n      String nested = \"{ \\\"count\\\":1 ,\\\"evant\\\" : [  {name:'GREETINGS',source:'guest'} ] }\";\n      HttpResponse response = HttpResponse.builder().statusCode(200).message(\"goodie\")\n            .payload(Payloads.newPayload(nested)).build();\n\n      List<Event> val = new ParseFirstJsonValueNamed<List<Event>>(json, new TypeLiteral<List<Event>>() {\n      }, \"event\").apply(response);\n      assertEquals(val.toString(), \"[]\");\n   }\n\n   public void testParseNestedElementsButNothing() throws IOException {\n      String nested = \"{ \\\"count\\\":1 ,\\\"event\\\" : [  ] }\";\n      HttpResponse response = HttpResponse.builder().statusCode(200).message(\"goodie\")\n            .payload(Payloads.newPayload(nested)).build();\n\n      List<Event> val = new ParseFirstJsonValueNamed<List<Event>>(json, new TypeLiteral<List<Event>>() {\n      }, \"event\").apply(response);\n      assertEquals(val.toString(), \"[]\");\n   }\n\n   public void testParseNestedFurtherElements() throws IOException {\n      String nestedFurther = \"{ \\\"listaccountsresponse\\\" : { \\\"count\\\":1 ,\\\"event\\\" : [  {name:'GREETINGS',source:'guest'} ] } }\";\n      HttpResponse response = HttpResponse.builder().statusCode(200).message(\"goodie\")\n            .payload(Payloads.newPayload(nestedFurther)).build();\n\n      List<Event> val = new ParseFirstJsonValueNamed<List<Event>>(json, new TypeLiteral<List<Event>>() {\n      }, \"event\").apply(response);\n      assertEquals(val.toString(), \"[(name=GREETINGS, source=guest)]\");\n   }\n\n   public void testParseNestedFurtherElementsButNothing() throws IOException {\n      String nestedFurther = \"{ \\\"listaccountsresponse\\\" : { \\\"count\\\":1 ,\\\"event\\\" : [ ] } }\";\n      HttpResponse response = HttpResponse.builder().statusCode(200).message(\"goodie\")\n            .payload(Payloads.newPayload(nestedFurther)).build();\n\n      List<Event> val = new ParseFirstJsonValueNamed<List<Event>>(json, new TypeLiteral<List<Event>>() {\n      }, \"event\").apply(response);\n      assertEquals(val.toString(), \"[]\");\n   }\n\n   public void testParseNoPayloadEmptyList() throws IOException {\n      HttpResponse response = HttpResponse.builder().statusCode(200).message(\"goodie\").build();\n\n      List<Event> val = new ParseFirstJsonValueNamed<List<Event>>(json, new TypeLiteral<List<Event>>() {\n      }, \"event\").apply(response);\n      assertEquals(val, ImmutableList.<Event> of());\n   }\n\n   public void testParseNoPayloadEmptyMap() throws IOException {\n      HttpResponse response = HttpResponse.builder().statusCode(200).message(\"goodie\").build();\n\n      Map<String, String> val = new ParseFirstJsonValueNamed<Map<String, String>>(json,\n            new TypeLiteral<Map<String, String>>() {\n            }, \"event\").apply(response);\n      assertEquals(val, ImmutableMap.<String, String> of());\n   }\n\n   public void testParseNoPayloadEmptySet() throws IOException {\n      HttpResponse response = HttpResponse.builder().statusCode(200).message(\"goodie\").build();\n\n      Set<Event> val = new ParseFirstJsonValueNamed<Set<Event>>(json, new TypeLiteral<Set<Event>>() {\n      }, \"event\").apply(response);\n      assertEquals(val, ImmutableSet.<Event> of());\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/http/functions/ParseSaxTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.functions;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.utils.TestUtils;\nimport org.testng.annotations.Test;\nimport org.xml.sax.Locator;\nimport org.xml.sax.SAXParseException;\n\n/**\n * Tests behavior of {@code ParseSax}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"ParseSaxTest\")\npublic class ParseSaxTest extends BaseHandlerTest {\n   public static class TestHandler extends ParseSax.HandlerWithResult<String> {\n      @Override\n      public String getResult() {\n         return \"\";\n      }\n   }\n\n   ParseSax<String> createParser() {\n      return factory.create(injector.getInstance(TestHandler.class));\n   }\n   \n   @Test\n   public void testAddDetailsAndPropagateOkWhenRequestWithNoDataAndRuntimeExceptionThrowsOriginalException() {\n\n      ParseSax<String> parser = createParser();\n      Exception input = new RuntimeException(\"foo\");\n\n      try {\n         parser.addDetailsAndPropagate(null, input);\n      } catch (RuntimeException e) {\n         assertEquals(e, input);\n      }\n   }\n\n   @Test\n   public void testAddDetailsAndPropagateOkWhenRequestWithNoDataAndExceptionPropagates() {\n\n      ParseSax<String> parser = createParser();\n      Exception input = new Exception(\"foo\");\n\n      try {\n         parser.addDetailsAndPropagate(null, input);\n      } catch (RuntimeException e) {\n         assertEquals(e.getMessage(), \"java.lang.Exception: foo\");\n         assertEquals(e.getCause(), input);\n      }\n   }\n\n   @Test\n   public void testAddDetailsAndPropagateOkWhenRequestIsNotNullAndResponseIsNull() {\n\n      ParseSax<String> parser = createParser();\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://foohost\").build(); \n      Exception input = new Exception(\"foo\");\n\n      try {\n         parser.setContext(request);\n         parser.addDetailsAndPropagate(null, input);\n      } catch (RuntimeException e) {\n         assertEquals(e.getMessage(), \"request: GET http://foohost HTTP/1.1; cause: java.lang.Exception: foo\");\n         assertEquals(e.getCause(), input);\n      }\n   }\n   \n   @Test\n   public void testAddDetailsAndPropagateOkWithValidRequestResponse() {\n\n      ParseSax<String> parser = createParser();\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://foohost\").build();\n      HttpResponse response = HttpResponse.builder().statusCode(304).message(\"Not Modified\").build();\n      Exception input = new Exception(\"foo\");\n\n      try {\n         parser.setContext(request);\n         parser.addDetailsAndPropagate(response, input);\n      } catch (RuntimeException e) {\n         assertEquals(e.getMessage(), \"request: GET http://foohost HTTP/1.1; response: HTTP/1.1 304 Not Modified; cause: java.lang.Exception: foo\");\n         assertEquals(e.getCause(), input);\n      }\n   }\n\n   @Test\n   public void testAddDetailsAndPropagateOkWithValidRequestResponseWithSAXParseException() {\n\n      ParseSax<String> parser = createParser();\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://foohost\").build();\n      HttpResponse response = HttpResponse.builder().statusCode(304).message(\"Not Modified\").build();\n      Locator locator = createMock(Locator.class);\n      expect(locator.getColumnNumber()).andReturn(1);\n      expect(locator.getLineNumber()).andReturn(1);\n      expect(locator.getPublicId()).andReturn(\"publicId\");\n      expect(locator.getSystemId()).andReturn(\"systemId\");\n      replay(locator);\n      Exception input = new SAXParseException(\"foo\", locator);\n      verify(locator);\n\n      try {\n         parser.setContext(request);\n         parser.addDetailsAndPropagate(response, input);\n      } catch (RuntimeException e) {\n         assertEquals(e.getMessage(), TestUtils.isJava6()\n               ? \"request: GET http://foohost HTTP/1.1; response: HTTP/1.1 304 Not Modified; error at 1:1 in document systemId; cause: org.xml.sax.SAXParseException: foo\"\n               : \"request: GET http://foohost HTTP/1.1; response: HTTP/1.1 304 Not Modified; error at 1:1 in document systemId; cause: org.xml.sax.SAXParseExceptionpublicId: publicId; systemId: systemId; lineNumber: 1; columnNumber: 1; foo\");\n         assertEquals(e.getCause(), input);\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/http/functions/ParseURIFromListOrLocationHeaderIf20xTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.functions;\n\nimport static com.google.common.net.HttpHeaders.CONTENT_TYPE;\nimport static com.google.common.net.HttpHeaders.LOCATION;\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.jclouds.util.Strings2.toInputStream;\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.io.Payload;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\n\n@Test(groups = { \"unit\" })\npublic class ParseURIFromListOrLocationHeaderIf20xTest {\n\n   @Test\n   public void testExceptionWhenNoContentOn200() {\n      Function<HttpResponse, URI> function = new ParseURIFromListOrLocationHeaderIf20x();\n      HttpResponse response = createMock(HttpResponse.class);\n      Payload payload = createMock(Payload.class);\n\n      expect(response.getStatusCode()).andReturn(200).atLeastOnce();\n      expect(response.getFirstHeaderOrNull(CONTENT_TYPE)).andReturn(\"text/uri-list\");\n      expect(response.getPayload()).andReturn(payload).atLeastOnce();\n      expect(payload.getInput()).andReturn(null);\n      payload.release();\n\n      replay(payload);\n      replay(response);\n      try {\n         function.apply(response);\n      } catch (Exception e) {\n         assert e.getMessage().equals(\"no content\");\n      }\n      verify(payload);\n      verify(response);\n   }\n\n   @Test\n   public void testExceptionWhenIOExceptionOn200() {\n      Function<HttpResponse, URI> function = new ParseURIFromListOrLocationHeaderIf20x();\n      HttpResponse response = createMock(HttpResponse.class);\n      Payload payload = createMock(Payload.class);\n\n      expect(response.getStatusCode()).andReturn(200).atLeastOnce();\n      expect(response.getFirstHeaderOrNull(CONTENT_TYPE)).andReturn(\"text/uri-list\");\n      RuntimeException exception = new RuntimeException(\"bad\");\n      expect(response.getPayload()).andReturn(payload).atLeastOnce();\n      expect(payload.getInput()).andThrow(exception);\n      payload.release();\n\n      replay(payload);\n      replay(response);\n      try {\n         function.apply(response);\n      } catch (Exception e) {\n         assert e.equals(exception);\n      }\n      verify(payload);\n      verify(response);\n   }\n\n   @Test\n   public void testResponseOk() {\n      Function<HttpResponse, URI> function = new ParseURIFromListOrLocationHeaderIf20x();\n      HttpResponse response = createMock(HttpResponse.class);\n      Payload payload = createMock(Payload.class);\n\n      expect(response.getStatusCode()).andReturn(200).atLeastOnce();\n      expect(response.getFirstHeaderOrNull(CONTENT_TYPE)).andReturn(\"text/uri-list\");\n      expect(response.getPayload()).andReturn(payload).atLeastOnce();\n      expect(payload.getInput()).andReturn(toInputStream(\"http://locahost\")).atLeastOnce();\n      payload.release();\n\n      replay(payload);\n      replay(response);\n      assertEquals(function.apply(response), URI.create(\"http://locahost\"));\n\n      verify(payload);\n      verify(response);\n   }\n\n   @Test\n   public void testResponseLocationOk() {\n      Function<HttpResponse, URI> function = new ParseURIFromListOrLocationHeaderIf20x();\n      HttpResponse response = createMock(HttpResponse.class);\n      Payload payload = createMock(Payload.class);\n\n      expect(response.getStatusCode()).andReturn(200).atLeastOnce();\n      expect(response.getFirstHeaderOrNull(CONTENT_TYPE)).andReturn(\"text/plain\");\n      expect(response.getFirstHeaderOrNull(LOCATION)).andReturn(\"http://locahost\");\n      expect(response.getPayload()).andReturn(payload).atLeastOnce();\n      payload.release();\n\n      replay(payload);\n      replay(response);\n      assertEquals(function.apply(response), URI.create(\"http://locahost\"));\n      verify(response);\n      verify(payload);\n\n   }\n\n   @Test\n   public void testResponseLowercaseLocationOk() {\n      Function<HttpResponse, URI> function = new ParseURIFromListOrLocationHeaderIf20x();\n      HttpResponse response = createMock(HttpResponse.class);\n      Payload payload = createMock(Payload.class);\n\n      expect(response.getStatusCode()).andReturn(200).atLeastOnce();\n      expect(response.getFirstHeaderOrNull(CONTENT_TYPE)).andReturn(\"text/plain\");\n      expect(response.getFirstHeaderOrNull(LOCATION)).andReturn(null);\n      expect(response.getFirstHeaderOrNull(\"location\")).andReturn(\"http://locahost\");\n      expect(response.getPayload()).andReturn(payload).atLeastOnce();\n      payload.release();\n\n      replay(payload);\n      replay(response);\n      assertEquals(function.apply(response), URI.create(\"http://locahost\"));\n      verify(response);\n      verify(payload);\n\n   }\n\n   @Test\n   public void testResponsePathLocationOk() {\n      ParseURIFromListOrLocationHeaderIf20x function = new ParseURIFromListOrLocationHeaderIf20x();\n      HttpResponse response = createMock(HttpResponse.class);\n      Payload payload = createMock(Payload.class);\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://new/fd\").build();\n      \n      function.setContext(request);\n      expect(response.getStatusCode()).andReturn(200).atLeastOnce();\n      expect(response.getFirstHeaderOrNull(CONTENT_TYPE)).andReturn(\"text/plain\");\n      expect(response.getFirstHeaderOrNull(LOCATION)).andReturn(\"path\");\n      expect(response.getPayload()).andReturn(payload).atLeastOnce();\n      payload.release();\n\n      replay(payload);\n      replay(response);\n      assertEquals(function.apply(response), URI.create(\"http://new/path\"));\n      verify(response);\n      verify(payload);\n\n   }\n\n   @Test\n   public void testResponsePathPortLocationOk() {\n      ParseURIFromListOrLocationHeaderIf20x function = new ParseURIFromListOrLocationHeaderIf20x();\n      HttpResponse response = createMock(HttpResponse.class);\n      Payload payload = createMock(Payload.class);\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://new:8080/fd\").build();\n\n      function.setContext(request);\n      expect(response.getStatusCode()).andReturn(200).atLeastOnce();\n      expect(response.getFirstHeaderOrNull(CONTENT_TYPE)).andReturn(\"text/plain\");\n      expect(response.getFirstHeaderOrNull(LOCATION)).andReturn(\"path\");\n      expect(response.getPayload()).andReturn(payload).atLeastOnce();\n      payload.release();\n\n      replay(payload);\n      replay(response);\n      assertEquals(function.apply(response), URI.create(\"http://new:8080/path\"));\n      verify(response);\n      verify(payload);\n\n   }\n\n   @Test\n   public void testResponsePathSchemeLocationOk() {\n      ParseURIFromListOrLocationHeaderIf20x function = new ParseURIFromListOrLocationHeaderIf20x();\n      HttpResponse response = createMock(HttpResponse.class);\n      Payload payload = createMock(Payload.class);\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"https://new/fd\").build();\n\n      function.setContext(request);\n      expect(response.getStatusCode()).andReturn(200).atLeastOnce();\n      expect(response.getFirstHeaderOrNull(CONTENT_TYPE)).andReturn(\"text/plain\");\n      expect(response.getFirstHeaderOrNull(LOCATION)).andReturn(\"path\");\n      expect(response.getPayload()).andReturn(payload).atLeastOnce();\n      payload.release();\n\n      replay(payload);\n      replay(response);\n      assertEquals(function.apply(response), URI.create(\"https://new/path\"));\n      verify(response);\n      verify(payload);\n\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/http/functions/ReturnStringIf200Test.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.functions;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.TimeoutException;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.io.Payload;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\n\n@Test(groups = { \"unit\" })\npublic class ReturnStringIf200Test {\n\n   @Test\n   public void testNullWhenNoContentOn200() throws ExecutionException, InterruptedException,\n            TimeoutException, IOException {\n      Function<HttpResponse, String> function = new ReturnStringIf2xx();\n      HttpResponse response = createMock(HttpResponse.class);\n      Payload payload = createMock(Payload.class);\n\n      expect(response.getPayload()).andReturn(null);\n\n      replay(payload);\n      replay(response);\n      assert function.apply(response) == null;\n\n      verify(payload);\n      verify(response);\n   }\n\n   @Test\n   public void testExceptionWhenIOExceptionOn200() throws ExecutionException, InterruptedException,\n            TimeoutException, IOException {\n      Function<HttpResponse, String> function = new ReturnStringIf2xx();\n      HttpResponse response = createMock(HttpResponse.class);\n      Payload payload = createMock(Payload.class);\n\n      expect(response.getStatusCode()).andReturn(200).atLeastOnce();\n      RuntimeException exception = new RuntimeException(\"bad\");\n      expect(response.getPayload()).andReturn(payload).atLeastOnce();\n      expect(payload.getInput()).andThrow(exception);\n      payload.release();\n\n      replay(payload);\n      replay(response);\n      try {\n         function.apply(response);\n      } catch (Exception e) {\n         assert e.equals(exception);\n      }\n      verify(payload);\n      verify(response);\n   }\n\n   @Test\n   public void testResponseOk() throws Exception {\n      Function<HttpResponse, String> function = new ReturnStringIf2xx();\n      HttpResponse response = createMock(HttpResponse.class);\n      Payload payload = createMock(Payload.class);\n\n      expect(response.getStatusCode()).andReturn(200).atLeastOnce();\n      expect(response.getPayload()).andReturn(payload).atLeastOnce();\n      expect(payload.getInput()).andReturn(Strings2.toInputStream(\"hello\"));\n      payload.release();\n\n      replay(payload);\n      replay(response);\n\n      assertEquals(function.apply(response), \"hello\");\n\n      verify(payload);\n      verify(response);\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/http/functions/UnwrapFirstValueNamedTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.json.internal.GsonWrapper;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\nimport com.google.inject.TypeLiteral;\n\n@Test\npublic class UnwrapFirstValueNamedTest {\n\n   GsonWrapper json = Guice.createInjector(new GsonModule()).getInstance(GsonWrapper.class);\n\n   static class Event {\n      private String name;\n      private String source;\n\n      private Event(String name, String source) {\n         this.name = name;\n         this.source = source;\n      }\n\n      @Override\n      public String toString() {\n         return String.format(\"(name=%s, source=%s)\", name, source);\n      }\n   }\n\n   public void testParseNestedElements() throws IOException {\n      String nested = \"{ \\\"count\\\":1 ,\\\"event\\\" : [  {name:'GREETINGS',source:'guest'} ] }\";\n      HttpResponse response = HttpResponse.builder().statusCode(200).message(\"goodie\")\n            .payload(Payloads.newPayload(nested)).build();\n\n      List<Event> val = new ParseFirstJsonValueNamed<List<Event>>(json, new TypeLiteral<List<Event>>() {\n      }, \"event\").apply(response);\n      assertEquals(val.toString(), \"[(name=GREETINGS, source=guest)]\");\n   }\n\n   public void testParseNestedElementsButNothing() throws IOException {\n      String nested = \"{ \\\"count\\\":1 ,\\\"event\\\" : [  ] }\";\n      HttpResponse response = HttpResponse.builder().statusCode(200).message(\"goodie\")\n            .payload(Payloads.newPayload(nested)).build();\n\n      List<Event> val = new ParseFirstJsonValueNamed<List<Event>>(json, new TypeLiteral<List<Event>>() {\n      }, \"event\").apply(response);\n      assertEquals(val.toString(), \"[]\");\n   }\n\n   public void testParseNestedFurtherElements() throws IOException {\n      String nestedFurther = \"{ \\\"listaccountsresponse\\\" : { \\\"count\\\":1 ,\\\"event\\\" : [  {name:'GREETINGS',source:'guest'} ] } }\";\n      HttpResponse response = HttpResponse.builder().statusCode(200).message(\"goodie\")\n            .payload(Payloads.newPayload(nestedFurther)).build();\n\n      List<Event> val = new ParseFirstJsonValueNamed<List<Event>>(json, new TypeLiteral<List<Event>>() {\n      }, \"event\").apply(response);\n      assertEquals(val.toString(), \"[(name=GREETINGS, source=guest)]\");\n   }\n\n   public void testParseNestedFurtherElementsButNothing() throws IOException {\n      String nestedFurther = \"{ \\\"listaccountsresponse\\\" : { \\\"count\\\":1 ,\\\"event\\\" : [ ] } }\";\n      HttpResponse response = HttpResponse.builder().statusCode(200).message(\"goodie\")\n            .payload(Payloads.newPayload(nestedFurther)).build();\n\n      List<Event> val = new ParseFirstJsonValueNamed<List<Event>>(json, new TypeLiteral<List<Event>>() {\n      }, \"event\").apply(response);\n      assertEquals(val.toString(), \"[]\");\n   }\n\n   public void testParseNoPayloadEmptyList() throws IOException {\n      HttpResponse response = HttpResponse.builder().statusCode(200).message(\"goodie\").build();\n\n      List<Event> val = new ParseFirstJsonValueNamed<List<Event>>(json, new TypeLiteral<List<Event>>() {\n      }, \"event\").apply(response);\n      assertEquals(val, ImmutableList.<Event> of());\n   }\n\n   public void testParseNoPayloadEmptyMap() throws IOException {\n      HttpResponse response = HttpResponse.builder().statusCode(200).message(\"goodie\").build();\n\n      Map<String, String> val = new ParseFirstJsonValueNamed<Map<String, String>>(json,\n            new TypeLiteral<Map<String, String>>() {\n            }, \"event\").apply(response);\n      assertEquals(val, ImmutableMap.<String, String> of());\n   }\n\n   public void testParseNoPayloadEmptySet() throws IOException {\n      HttpResponse response = HttpResponse.builder().statusCode(200).message(\"goodie\").build();\n\n      Set<Event> val = new ParseFirstJsonValueNamed<Set<Event>>(json, new TypeLiteral<Set<Event>>() {\n      }, \"event\").apply(response);\n      assertEquals(val, ImmutableSet.<Event> of());\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/http/handlers/BackoffLimitedRetryHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.handlers;\n\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.jclouds.reflect.Reflection2.method;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.fail;\n\nimport java.io.IOException;\nimport java.io.InputStream;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.IntegrationTestClient;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.providers.AnonymousProviderMetadata;\nimport org.jclouds.reflect.Invocation;\nimport org.jclouds.rest.internal.RestAnnotationProcessor;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.reflect.Invokable;\n\n@Test(groups = \"unit\", testName = \"BackoffLimitedRetryHandlerTest\")\npublic class BackoffLimitedRetryHandlerTest {\n\n   BackoffLimitedRetryHandler handler = new BackoffLimitedRetryHandler();\n\n   @Test\n   void testExponentialBackoffDelayDefaultMaxInterval500() throws InterruptedException {\n      long period = 500;\n      long acceptableDelay = period - 1;\n\n      long startTime = System.nanoTime();\n      handler.imposeBackoffExponentialDelay(period, 2, 1, 5, \"TEST FAILURE: 1\");\n      long elapsedTime = (System.nanoTime() - startTime) / 1000000;\n      assertThat(elapsedTime).isBetween(period, period + acceptableDelay);\n\n      startTime = System.nanoTime();\n      handler.imposeBackoffExponentialDelay(period, 2, 2, 5, \"TEST FAILURE: 2\");\n      elapsedTime = (System.nanoTime() - startTime) / 1000000;\n      assertThat(elapsedTime).isBetween(period * 4, period * 9);\n\n      startTime = System.nanoTime();\n      handler.imposeBackoffExponentialDelay(period, 2, 3, 5, \"TEST FAILURE: 3\");\n      elapsedTime = (System.nanoTime() - startTime) / 1000000;\n      assertThat(elapsedTime).isBetween(period * 9, period * 10);\n\n      startTime = System.nanoTime();\n      handler.imposeBackoffExponentialDelay(period, 2, 4, 5, \"TEST FAILURE: 4\");\n      elapsedTime = (System.nanoTime() - startTime) / 1000000;\n      assertThat(elapsedTime).isBetween(period * 10, period * 11);\n\n      startTime = System.nanoTime();\n      handler.imposeBackoffExponentialDelay(period, 2, 5, 5, \"TEST FAILURE: 5\");\n      elapsedTime = (System.nanoTime() - startTime) / 1000000;\n      assertThat(elapsedTime).isBetween(period * 10, period * 11);\n\n   }\n\n   // TODO: disabled since this often fails due to race conditions\n   @Test(enabled = false)\n   void testExponentialBackoffDelaySmallInterval5() throws InterruptedException {\n      long period = 5;\n      long acceptableDelay = period - 1;\n\n      long startTime = System.nanoTime();\n      handler.imposeBackoffExponentialDelay(period, 2, 1, 5, \"TEST FAILURE: 1\");\n      long elapsedTime = (System.nanoTime() - startTime) / 1000000;\n      assertThat(elapsedTime).isBetween(period, period + acceptableDelay);\n   }\n\n   // TODO: disabled since this often fails due to race conditions\n   @Test(enabled = false)\n   void testExponentialBackoffDelaySmallInterval1() throws InterruptedException {\n      long period = 1;\n      long acceptableDelay = 5;\n\n      long startTime = System.nanoTime();\n      handler.imposeBackoffExponentialDelay(period, 2, 1, 5, \"TEST FAILURE: 1\");\n      long elapsedTime = (System.nanoTime() - startTime) / 1000000;\n      assertThat(elapsedTime).isBetween(period, period + acceptableDelay);\n   }\n\n   @Test\n   void testExponentialBackoffDelaySmallInterval0() throws InterruptedException {\n      long period = 0;\n      long acceptableDelay = 5;\n\n      long startTime = System.nanoTime();\n      handler.imposeBackoffExponentialDelay(period, 2, 1, 5, \"TEST FAILURE: 1\");\n      long elapsedTime = (System.nanoTime() - startTime) / 1000000;\n      assertThat(elapsedTime).isBetween(period, period + acceptableDelay);\n   }\n\n   @Test\n   void testInputStreamIsNotClosed() throws SecurityException, NoSuchMethodException, IOException {\n      HttpCommand command = createCommand();\n      HttpResponse response = HttpResponse.builder().statusCode(500).build();\n\n      InputStream inputStream = new InputStream() {\n         int count = 2;\n\n         @Override\n         public void close() {\n            fail(\"The retry handler should not close the response stream\");\n         }\n\n         @Override\n         public int read() throws IOException {\n            return count < 0 ? -1 : --count;\n         }\n\n         @Override\n         public int available() throws IOException {\n            return count < 0 ? 0 : count;\n         }\n      };\n\n      response.setPayload(Payloads.newInputStreamPayload(inputStream));\n      response.getPayload().getContentMetadata().setContentLength(1L);\n      assertEquals(response.getPayload().openStream().available(), 2);\n      assertEquals(response.getPayload().openStream().read(), 1);\n\n      handler.shouldRetryRequest(command, response);\n\n      assertEquals(response.getPayload().openStream().available(), 1);\n      assertEquals(response.getPayload().openStream().read(), 0);\n   }\n\n   private final Function<Invocation, HttpRequest> processor = ContextBuilder\n         .newBuilder(AnonymousProviderMetadata.forApiOnEndpoint(IntegrationTestClient.class, \"http://localhost\"))\n         .buildInjector().getInstance(RestAnnotationProcessor.class);\n\n\n   private HttpCommand createCommand() throws SecurityException, NoSuchMethodException {\n      Invokable<IntegrationTestClient, String> method = method(IntegrationTestClient.class, \"download\", String.class);\n\n      return new HttpCommand(processor.apply(Invocation.create(method, ImmutableList.<Object> of(\"1\"))));\n   }\n\n   @Test\n   void testIncrementsFailureCount() throws InterruptedException, IOException, SecurityException, NoSuchMethodException {\n      HttpCommand command = createCommand();\n      HttpResponse response = HttpResponse.builder().statusCode(400).build();\n\n      handler.shouldRetryRequest(command, response);\n      assertEquals(command.getFailureCount(), 1);\n\n      handler.shouldRetryRequest(command, response);\n      assertEquals(command.getFailureCount(), 2);\n\n      handler.shouldRetryRequest(command, response);\n      assertEquals(command.getFailureCount(), 3);\n   }\n\n   @Test\n   void testDisallowsExcessiveRetries() throws InterruptedException, IOException, SecurityException,\n            NoSuchMethodException {\n      HttpCommand command = createCommand();\n      HttpResponse response = HttpResponse.builder().statusCode(400).build();\n\n      assertEquals(handler.shouldRetryRequest(command, response), true); // Failure 1\n\n      assertEquals(handler.shouldRetryRequest(command, response), true); // Failure 2\n\n      assertEquals(handler.shouldRetryRequest(command, response), true); // Failure 3\n\n      assertEquals(handler.shouldRetryRequest(command, response), true); // Failure 4\n\n      assertEquals(handler.shouldRetryRequest(command, response), true); // Failure 5\n\n      assertEquals(handler.shouldRetryRequest(command, response), false); // Failure 6\n   }\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/http/handlers/BaseHttpErrorHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.handlers;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.reportMatcher;\nimport static org.easymock.EasyMock.verify;\n\nimport java.net.URI;\n\nimport org.easymock.IArgumentMatcher;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Guice;\n\n@Test(groups = { \"unit\" })\npublic abstract class BaseHttpErrorHandlerTest<T extends HttpErrorHandler> {\n   protected abstract Class<T> getClassToTest();\n\n   protected void assertCodeMakes(String method, URI uri, int statusCode, String message, String content,\n            Class<? extends Exception> expected, String exceptionMessage) {\n      assertCodeMakes(method, uri, statusCode, message, \"text/xml\", content, expected, exceptionMessage);\n   }\n\n   private void assertCodeMakes(String method, URI uri, int statusCode, String message, String contentType,\n            String content, Class<? extends Exception> expected, String exceptionMessage) {\n\n      T function = Guice.createInjector().getInstance(getClassToTest());\n\n      HttpCommand command = createMock(HttpCommand.class);\n      HttpRequest request = HttpRequest.builder().method(method).endpoint(uri).build();\n      HttpResponse response = HttpResponse.builder()\n                                          .statusCode(statusCode)\n                                          .message(message)\n                                          .payload(content).build();\n      response.getPayload().getContentMetadata().setContentType(contentType);\n\n      expect(command.getCurrentRequest()).andReturn(request).atLeastOnce();\n      command.setException(exceptionEq(expected, exceptionMessage));\n\n      replay(command);\n\n      function.handleError(command, response);\n\n      verify(command);\n   }\n\n   public static Exception exceptionEq(final Class<? extends Exception> in, final String exceptionMessage) {\n      reportMatcher(new IArgumentMatcher() {\n\n         @Override\n         public void appendTo(StringBuffer buffer) {\n            buffer.append(\"exceptionEq(\");\n            buffer.append(in);\n            buffer.append(\",\");\n            buffer.append(exceptionMessage);\n            buffer.append(\")\");\n         }\n\n         @Override\n         public boolean matches(Object arg) {\n            return arg.getClass() == in && exceptionMessage.equals(Exception.class.cast(arg).getMessage());\n         }\n\n      });\n      return null;\n   }\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/http/handlers/DelegatingErrorHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.handlers;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.annotation.ClientError;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\n\n@Test(groups = \"unit\")\npublic class DelegatingErrorHandlerTest {\n\n   public void testDefaultInjection() {\n      DelegatingErrorHandler handler = Guice.createInjector().getInstance(\n               DelegatingErrorHandler.class);\n      assertEquals(handler.getClientErrorHandler().getClass(),\n               CloseContentAndSetExceptionErrorHandler.class);\n      assertEquals(handler.getServerErrorHandler().getClass(),\n               CloseContentAndSetExceptionErrorHandler.class);\n      assertEquals(handler.getRedirectionHandler().getClass(),\n               CloseContentAndSetExceptionErrorHandler.class);\n   }\n\n   public void testClientHandlerInjection() {\n      DelegatingErrorHandler handler = Guice.createInjector(new AbstractModule() {\n\n         @Override\n         protected void configure() {\n            bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(\n                     DelegatingErrorHandler.class);\n         }\n\n      }).getInstance(DelegatingErrorHandler.class);\n      assertEquals(handler.getClientErrorHandler().getClass(), DelegatingErrorHandler.class);\n      assertEquals(handler.getServerErrorHandler().getClass(),\n               CloseContentAndSetExceptionErrorHandler.class);\n      assertEquals(handler.getRedirectionHandler().getClass(),\n               CloseContentAndSetExceptionErrorHandler.class);\n   }\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/http/handlers/RateLimitRetryHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.handlers;\n\nimport static com.google.common.net.HttpHeaders.RETRY_AFTER;\nimport static org.jclouds.http.HttpUtils.releasePayload;\nimport static org.jclouds.io.Payloads.newInputStreamPayload;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.ByteArrayInputStream;\nimport java.util.concurrent.TimeUnit;\n\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.io.Payload;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.util.concurrent.Uninterruptibles;\n\n@Test(groups = \"unit\", testName = \"RateLimitRetryHandlerTest\")\npublic class RateLimitRetryHandlerTest {\n\n   // Configure a safe timeout of one minute to abort the tests in case they get\n   // stuck\n   private static final long TEST_SAFE_TIMEOUT = 60000;\n\n   private final RateLimitRetryHandler rateLimitRetryHandler = new RateLimitRetryHandler() {\n      @Override\n      protected Optional<Long> millisToNextAvailableRequest(HttpCommand command, HttpResponse response) {\n         String secondsToNextAvailableRequest = response.getFirstHeaderOrNull(RETRY_AFTER);\n         return secondsToNextAvailableRequest != null ? Optional.of(Long.valueOf(secondsToNextAvailableRequest) * 1000)\n               : Optional.<Long> absent();\n      }\n   };\n\n   @Test(timeOut = TEST_SAFE_TIMEOUT)\n   public void testDoNotRetryIfNoRateLimit() {\n      HttpCommand command = new HttpCommand(HttpRequest.builder().method(\"GET\").endpoint(\"http://localhost\").build());\n      HttpResponse response = HttpResponse.builder().statusCode(450).build();\n\n      assertFalse(rateLimitRetryHandler.shouldRetryRequest(command, response));\n   }\n\n   @Test(timeOut = TEST_SAFE_TIMEOUT)\n   public void testDoNotRetryIfNotReplayable() {\n      // InputStream payloads are not replayable\n      Payload payload = newInputStreamPayload(new ByteArrayInputStream(new byte[0]));\n      HttpCommand command = new HttpCommand(HttpRequest.builder().method(\"GET\").endpoint(\"http://localhost\")\n            .payload(payload).build());\n      HttpResponse response = HttpResponse.builder().statusCode(429).build();\n\n      try {\n         assertFalse(rateLimitRetryHandler.shouldRetryRequest(command, response));\n      } finally {\n         releasePayload(command.getCurrentRequest());\n      }\n   }\n\n   @Test(timeOut = TEST_SAFE_TIMEOUT)\n   public void testDoNotRetryIfNoRateLimitInfo() {\n      HttpCommand command = new HttpCommand(HttpRequest.builder().method(\"GET\").endpoint(\"http://localhost\").build());\n      HttpResponse response = HttpResponse.builder().statusCode(429).build();\n\n      assertFalse(rateLimitRetryHandler.shouldRetryRequest(command, response));\n   }\n\n   @Test(timeOut = TEST_SAFE_TIMEOUT)\n   public void testDoNotRetryIfTooMuchWait() {\n      HttpCommand command = new HttpCommand(HttpRequest.builder().method(\"GET\").endpoint(\"http://localhost\").build());\n      HttpResponse response = HttpResponse.builder().statusCode(429).addHeader(RETRY_AFTER, \"400\").build();\n\n      assertFalse(rateLimitRetryHandler.shouldRetryRequest(command, response));\n   }\n\n   @Test(timeOut = TEST_SAFE_TIMEOUT)\n   public void testRequestIsDelayed() {\n      HttpCommand command = new HttpCommand(HttpRequest.builder().method(\"GET\").endpoint(\"http://localhost\").build());\n      HttpResponse response = HttpResponse.builder().statusCode(429).addHeader(RETRY_AFTER, \"5\").build();\n\n      long start = System.currentTimeMillis();\n\n      assertTrue(rateLimitRetryHandler.shouldRetryRequest(command, response));\n      // Should have blocked the amount of time configured in the header. Use a\n      // smaller value to compensate the time it takes to reach the code that\n      // computes the amount of time to wait.\n      assertTrue(System.currentTimeMillis() - start > 2500);\n   }\n\n   @Test(timeOut = TEST_SAFE_TIMEOUT)\n   public void testDoNotRetryIfRequestIsAborted() throws Exception {\n      final HttpCommand command = new HttpCommand(HttpRequest.builder().method(\"GET\").endpoint(\"http://localhost\")\n            .build());\n      final HttpResponse response = HttpResponse.builder().statusCode(429).addHeader(RETRY_AFTER, \"10\").build();\n\n      final Thread requestThread = Thread.currentThread();\n      Thread killer = new Thread() {\n         @Override\n         public void run() {\n            Uninterruptibles.sleepUninterruptibly(2, TimeUnit.SECONDS);\n            requestThread.interrupt();\n         }\n      };\n\n      // Start the killer thread that will abort the rate limit wait\n      killer.start();\n      assertFalse(rateLimitRetryHandler.shouldRetryRequest(command, response));\n   }\n\n   @Test(timeOut = TEST_SAFE_TIMEOUT)\n   public void testIncrementsFailureCount() {\n      HttpCommand command = new HttpCommand(HttpRequest.builder().method(\"GET\").endpoint(\"http://localhost\").build());\n      HttpResponse response = HttpResponse.builder().statusCode(429).build();\n\n      rateLimitRetryHandler.shouldRetryRequest(command, response);\n      assertEquals(command.getFailureCount(), 1);\n\n      rateLimitRetryHandler.shouldRetryRequest(command, response);\n      assertEquals(command.getFailureCount(), 2);\n\n      rateLimitRetryHandler.shouldRetryRequest(command, response);\n      assertEquals(command.getFailureCount(), 3);\n   }\n\n   @Test(timeOut = TEST_SAFE_TIMEOUT)\n   public void testDisallowExcessiveRetries() {\n      HttpCommand command = new HttpCommand(HttpRequest.builder().method(\"GET\").endpoint(\"http://localhost\").build());\n      HttpResponse response = HttpResponse.builder().statusCode(429).addHeader(RETRY_AFTER, \"0\").build();\n\n      for (int i = 0; i < 5; i++) {\n         assertTrue(rateLimitRetryHandler.shouldRetryRequest(command, response));\n      }\n      assertFalse(rateLimitRetryHandler.shouldRetryRequest(command, response));\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/http/handlers/RedirectionRetryHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.handlers;\n\nimport static com.google.common.net.HttpHeaders.HOST;\nimport static com.google.common.net.HttpHeaders.LOCATION;\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.jclouds.providers.AnonymousProviderMetadata.forApiOnEndpoint;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.IntegrationTestClient;\nimport org.jclouds.rest.internal.BaseRestApiTest.MockModule;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Injector;\nimport com.google.inject.Module;\n\n/**\n * Tests behavior of {@code RedirectionRetryHandler}\n */\n@Test(groups = \"unit\")\npublic class RedirectionRetryHandlerTest {\n   Injector injector = ContextBuilder.newBuilder(forApiOnEndpoint(IntegrationTestClient.class, \"http://localhost\"))\n         .modules(ImmutableSet.<Module>of(new MockModule())).buildInjector();\n\n   @Test\n   public void test302DoesNotRetry() {\n\n      HttpCommand command = createMock(HttpCommand.class);\n      HttpResponse response = HttpResponse.builder()\n                                          .statusCode(302)\n                                          .message(\"HTTP/1.1 302 Found\").build();\n\n      expect(command.isReplayable()).andReturn(true);\n      expect(command.incrementRedirectCount()).andReturn(0);\n\n      replay(command);\n\n      RedirectionRetryHandler retry = injector.getInstance(RedirectionRetryHandler.class);\n\n      assert !retry.shouldRetryRequest(command, response);\n\n      verify(command);\n\n   }\n\n   @Test\n   public void test302DoesNotRetryAfterLimit() {\n\n      HttpCommand command = createMock(HttpCommand.class);\n      HttpResponse response = HttpResponse.builder()\n                                          .statusCode(302)\n                                          .message(\"HTTP/1.1 302 Found\")\n                                          .addHeader(LOCATION, \"/api/v0.8b-ext2.5/Error.aspx?aspxerrorpath=/api/v0.8b-ext2.5/org.svc/1906645\").build(); \n\n      expect(command.isReplayable()).andReturn(true);\n      expect(command.incrementRedirectCount()).andReturn(6);\n\n      replay(command);\n\n      RedirectionRetryHandler retry = injector.getInstance(RedirectionRetryHandler.class);\n\n      assert !retry.shouldRetryRequest(command, response);\n\n      verify(command);\n\n   }\n\n   @Test\n   public void test302WithPathOnlyHeader() {\n\n      verifyRedirectRoutes(\n               HttpRequest.builder()\n                          .method(\"GET\")\n                          .endpoint(\"https://services.enterprisecloud.terremark.com/api/v0.8b-ext2.5/org/1906645\").build(),\n               HttpResponse.builder()\n                           .statusCode(302)\n                           .message(\"HTTP/1.1 302 Found\")\n                           .addHeader(LOCATION, \"/api/v0.8b-ext2.5/Error.aspx?aspxerrorpath=/api/v0.8b-ext2.5/org.svc/1906645\").build(),\n               HttpRequest.builder()\n                          .method(\"GET\")\n                          .endpoint(\"https://services.enterprisecloud.terremark.com/api/v0.8b-ext2.5/Error.aspx?aspxerrorpath=/api/v0.8b-ext2.5/org.svc/1906645\").build());\n   }\n\n   @Test\n   public void test302ToHttps() {\n\n      verifyRedirectRoutes(\n               HttpRequest.builder()\n                          .method(\"GET\")\n                          .endpoint(\"http://services.enterprisecloud.terremark.com/api/v0.8b-ext2.5/org/1906645\").build(),\n               HttpResponse.builder()\n                           .statusCode(302)\n                           .message(\"HTTP/1.1 302 Found\")\n                           .addHeader(LOCATION, \"https://services.enterprisecloud.terremark.com/api/v0.8b-ext2.5/org/1906645\").build(),\n               HttpRequest.builder()\n                          .method(\"GET\")\n                          .endpoint(\"https://services.enterprisecloud.terremark.com/api/v0.8b-ext2.5/org/1906645\").build());\n   }\n\n   @Test\n   public void test302ToDifferentPort() {\n      verifyRedirectRoutes(\n               HttpRequest.builder()\n                          .method(\"GET\")\n                          .endpoint(\"http://services.enterprisecloud.terremark.com/api/v0.8b-ext2.5/org/1906645\").build(),\n               HttpResponse.builder()\n                           .statusCode(302)\n                           .message(\"HTTP/1.1 302 Found\")\n                           .addHeader(LOCATION, \"http://services.enterprisecloud.terremark.com:3030/api/v0.8b-ext2.5/org/1906645\").build(),\n               HttpRequest.builder()\n                          .method(\"GET\")\n                          .endpoint(\"http://services.enterprisecloud.terremark.com:3030/api/v0.8b-ext2.5/org/1906645\").build());\n   }\n\n   @Test\n   public void test302WithHeader() {\n      verifyRedirectRoutes(\n               HttpRequest.builder()\n                          .method(\"GET\")\n                          .endpoint(\"https://services.enterprisecloud.terremark.com/api/v0.8b-ext2.5/org/1906645\").build(),\n               HttpResponse.builder()\n                           .statusCode(302)\n                           .message(\"HTTP/1.1 302 Found\")\n                           .addHeader(LOCATION, \"https://services1.enterprisecloud.terremark.com/api/v0.8b-ext2.5/org/1906645\").build(),\n               HttpRequest.builder()\n                          .method(\"GET\")\n                          .endpoint(\"https://services1.enterprisecloud.terremark.com/api/v0.8b-ext2.5/org/1906645\").build());\n   }\n\n   @Test\n   public void test302WithHeaderReplacesHostHeader() {\n      verifyRedirectRoutes(\n               HttpRequest.builder()\n                          .method(\"GET\")\n                          .endpoint(\"https://services.enterprisecloud.terremark.com/api/v0.8b-ext2.5/org/1906645\")\n                          .addHeader(HOST, \"services.enterprisecloud.terremark.com\").build(),\n               HttpResponse.builder()\n                           .statusCode(302)\n                           .message(\"HTTP/1.1 302 Found\")\n                           .addHeader(LOCATION, \"https://services1.enterprisecloud.terremark.com/api/v0.8b-ext2.5/org/1906645\").build(),\n               HttpRequest.builder()\n                          .method(\"GET\")\n                          .endpoint(\"https://services1.enterprisecloud.terremark.com/api/v0.8b-ext2.5/org/1906645\")\n                          .addHeader(HOST, \"services1.enterprisecloud.terremark.com\").build());\n   }\n\n   protected void verifyRedirectRoutes(HttpRequest request, HttpResponse response, HttpRequest expected) {\n      HttpCommand command = createMock(HttpCommand.class);\n\n      expect(command.isReplayable()).andReturn(true);\n      expect(command.incrementRedirectCount()).andReturn(0);\n      expect(command.getCurrentRequest()).andReturn(request);\n      command.setCurrentRequest(expected);\n\n      replay(command);\n\n      RedirectionRetryHandler retry = injector.getInstance(RedirectionRetryHandler.class);\n\n      assert retry.shouldRetryRequest(command, response);\n      verify(command);\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/http/internal/BaseHttpCommandExecutorServiceTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.internal;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.expectLastCall;\nimport static org.easymock.EasyMock.getCurrentArguments;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.jclouds.Constants.PROPERTY_IDEMPOTENT_METHODS;\nimport static org.jclouds.http.HttpUtils.closeClientButKeepContentStream;\nimport static org.jclouds.http.HttpUtils.releasePayload;\nimport static org.jclouds.io.Payloads.newInputStreamPayload;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.Assert.fail;\n\nimport java.io.IOException;\nimport java.io.InputStream;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\n\nimport org.easymock.EasyMock;\nimport org.easymock.IAnswer;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpRequestFilter;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpUtils;\nimport org.jclouds.http.IOExceptionRetryHandler;\nimport org.jclouds.http.handlers.DelegatingErrorHandler;\nimport org.jclouds.http.handlers.DelegatingRetryHandler;\nimport org.jclouds.io.ContentMetadataCodec;\nimport org.jclouds.rest.internal.BaseHttpApiMetadata;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport com.google.inject.name.Names;\n\n@Test(groups = \"unit\", testName = \"BaseHttpCommandExecutorServiceTest\")\npublic class BaseHttpCommandExecutorServiceTest {\n\n   public void testStreamIsClosedWhenRetrying() throws IOException {\n      MockInputStream in = new MockInputStream(2); // Input stream that produces 2 bytes\n      HttpResponse response = HttpResponse.builder().payload(newInputStreamPayload(in)).build();\n      response.getPayload().getContentMetadata().setContentLength(1L);\n      HttpCommand command = mockHttpCommand();\n\n      DelegatingRetryHandler retryHandler = EasyMock.createMock(DelegatingRetryHandler.class);\n      DelegatingErrorHandler errorHandler = EasyMock.createMock(DelegatingErrorHandler.class);\n\n      expect(retryHandler.shouldRetryRequest(command, response)).andReturn(true);\n      replay(retryHandler, errorHandler);\n\n      // Verify the stream is open. This consumes one byte.\n      assertEquals(response.getPayload().openStream().available(), 2);\n      assertEquals(response.getPayload().openStream().read(), 1);\n\n      BaseHttpCommandExecutorService<?> service = mockHttpCommandExecutorService(retryHandler, errorHandler);\n      assertTrue(service.shouldContinue(command, response));\n\n      verify(retryHandler, errorHandler);\n\n      // Verify that the response stream is closed and consumed\n      assertFalse(in.isOpen);\n      assertTrue(response.getPayload().openStream() == in); // The service shouldn't have changed it\n      assertEquals(response.getPayload().openStream().available(), 0);\n      assertEquals(response.getPayload().openStream().read(), -1);\n   }\n\n   public void testStreamIsClosedWhenNotRetrying() throws IOException {\n      MockInputStream in = new MockInputStream(2); // Input stream that produces 2 bytes\n      HttpResponse response = HttpResponse.builder().payload(newInputStreamPayload(in)).build();\n      response.getPayload().getContentMetadata().setContentLength(1L);\n      HttpCommand command = mockHttpCommand();\n\n      DelegatingRetryHandler retryHandler = EasyMock.createMock(DelegatingRetryHandler.class);\n      DelegatingErrorHandler errorHandler = EasyMock.createMock(DelegatingErrorHandler.class);\n\n      errorHandler.handleError(command, response);\n      expectLastCall();\n      expect(retryHandler.shouldRetryRequest(command, response)).andReturn(false);\n      replay(retryHandler, errorHandler);\n\n      // Verify the stream is open. This consumes one byte.\n      assertEquals(response.getPayload().openStream().available(), 2);\n      assertEquals(response.getPayload().openStream().read(), 1);\n\n      BaseHttpCommandExecutorService<?> service = mockHttpCommandExecutorService(retryHandler, errorHandler);\n      assertFalse(service.shouldContinue(command, response));\n\n      verify(retryHandler, errorHandler);\n\n      // Verify that the response stream is closed\n      assertFalse(in.isOpen);\n      assertTrue(response.getPayload().openStream() == in);\n      assertEquals(response.getPayload().openStream().available(), 0);\n      assertEquals(response.getPayload().openStream().read(), -1);\n   }\n\n   public void testStreamIsClosedAndBufferedInTheErrorHandlerWhenNotRetrying() throws IOException {\n      MockInputStream in = new MockInputStream(2); // Input stream that produces 2 bytes\n      HttpResponse response = HttpResponse.builder().payload(newInputStreamPayload(in)).build();\n      response.getPayload().getContentMetadata().setContentLength(1L);\n      HttpCommand command = mockHttpCommand();\n\n      DelegatingRetryHandler retryHandler = EasyMock.createMock(DelegatingRetryHandler.class);\n      DelegatingErrorHandler errorHandler = EasyMock.createMock(DelegatingErrorHandler.class);\n\n      errorHandler.handleError(command, response);\n      expectLastCall().andAnswer(new IAnswer<Void>() {\n         @Override\n         public Void answer() throws Throwable {\n            // This error handler will close the original stream and buffer it into memory\n            HttpResponse response = (HttpResponse) getCurrentArguments()[1];\n            closeClientButKeepContentStream(response);\n            return null;\n         }\n      });\n\n      expect(retryHandler.shouldRetryRequest(command, response)).andReturn(false);\n      replay(retryHandler, errorHandler);\n\n      // Verify the stream is open. This consumes one byte.\n      assertEquals(response.getPayload().openStream().available(), 2);\n      assertEquals(response.getPayload().openStream().read(), 1);\n\n      BaseHttpCommandExecutorService<?> service = mockHttpCommandExecutorService(retryHandler, errorHandler);\n      assertFalse(service.shouldContinue(command, response));\n\n      verify(retryHandler, errorHandler);\n\n      // Verify that the original response stream is closed and consumed\n      assertFalse(in.isOpen);\n      assertEquals(in.available(), 0);\n      assertEquals(in.read(), -1);\n\n      // Verify that the buffered stream is now repeatable and we can read the bytes that still have not\n      // been consumed from the original stream\n      assertTrue(response.getPayload().isRepeatable());\n      assertEquals(response.getPayload().openStream().available(), 1);\n      assertEquals(response.getPayload().openStream().read(), 0);\n   }\n\n   public void testCloseStreamCanBeCalledMoreThanOnce() throws IOException {\n      MockInputStream in = new MockInputStream(2); // Input stream that produces 2 bytes\n      HttpResponse response = HttpResponse.builder().payload(newInputStreamPayload(in)).build();\n      response.getPayload().getContentMetadata().setContentLength(1L);\n      HttpCommand command = mockHttpCommand();\n\n      DelegatingRetryHandler retryHandler = EasyMock.createMock(DelegatingRetryHandler.class);\n      DelegatingErrorHandler errorHandler = EasyMock.createMock(DelegatingErrorHandler.class);\n\n      errorHandler.handleError(command, response);\n      expectLastCall().andAnswer(new IAnswer<Void>() {\n         @Override\n         public Void answer() throws Throwable {\n            // This error handler will close the original stream\n            HttpResponse response = (HttpResponse) getCurrentArguments()[1];\n            releasePayload(response);\n            return null;\n         }\n      });\n\n      expect(retryHandler.shouldRetryRequest(command, response)).andReturn(false);\n      replay(retryHandler, errorHandler);\n\n      // Verify the stream is open. This consumes one byte.\n      assertEquals(response.getPayload().openStream().available(), 2);\n      assertEquals(response.getPayload().openStream().read(), 1);\n\n      BaseHttpCommandExecutorService<?> service = mockHttpCommandExecutorService(retryHandler, errorHandler);\n      assertFalse(service.shouldContinue(command, response));\n\n      verify(retryHandler, errorHandler);\n\n      // Verify that the response stream is closed and consumed\n      assertFalse(in.isOpen);\n      assertEquals(in.closeCount, 2); // The stream has been closed twice, but the IOException should not propagated\n      assertTrue(response.getPayload().openStream() == in); // The service shouldn't have changed it\n      assertEquals(response.getPayload().openStream().available(), 0);\n      assertEquals(response.getPayload().openStream().read(), -1);\n   }\n\n   public void testDoNotRetryPostOnException() throws IOException {\n      helperRetryOnlyIdempotent(\"POST\");\n   }\n\n   public void testRetryGetOnException() throws IOException {\n      helperRetryOnlyIdempotent(\"GET\");\n   }\n\n   private void helperRetryOnlyIdempotent(String method) throws IOException {\n      final IOException error = new IOException(\"test exception\");\n      HttpRequestFilter throwingFilter = new HttpRequestFilter() {\n         @Override\n         public HttpRequest filter(HttpRequest request) throws HttpException {\n            throw new HttpException(error);\n         }\n      };\n      HttpCommand command = new HttpCommand(HttpRequest.builder().endpoint(\"http://localhost\").method(method).filter(throwingFilter).build());\n\n      IOExceptionRetryHandler ioRetryHandler = EasyMock.createMock(IOExceptionRetryHandler.class);\n\n      if (\"GET\".equals(method)) {\n         expect(ioRetryHandler.shouldRetryRequest(command, error)).andReturn(true);\n         expect(ioRetryHandler.shouldRetryRequest(command, error)).andReturn(false);\n      }\n      replay(ioRetryHandler);\n\n      BaseHttpCommandExecutorService<?> service = mockHttpCommandExecutorService(ioRetryHandler);\n      try {\n         service.invoke(command);\n         fail(\"Expected to fail due to throwing filter\");\n      } catch (Exception e) {}\n\n      verify(ioRetryHandler);\n   }\n\n   private HttpCommand mockHttpCommand() {\n      return new HttpCommand(HttpRequest.builder().endpoint(\"http://localhost\").method(\"mock\").build());\n   }\n   \n   private BaseHttpCommandExecutorService<?> mockHttpCommandExecutorService(final DelegatingRetryHandler retryHandler,\n         final DelegatingErrorHandler errorHandler) {\n      Injector injector = Guice.createInjector(new AbstractModule() {\n         @Override\n         protected void configure() {\n            Names.bindProperties(binder(), BaseHttpApiMetadata.defaultProperties());\n            bind(DelegatingRetryHandler.class).toInstance(retryHandler);\n            bind(DelegatingErrorHandler.class).toInstance(errorHandler);\n            bind(BaseHttpCommandExecutorService.class).to(MockHttpCommandExecutorService.class);\n         }\n      });\n\n      return injector.getInstance(BaseHttpCommandExecutorService.class);\n   }\n\n   private BaseHttpCommandExecutorService<?> mockHttpCommandExecutorService(final IOExceptionRetryHandler ioRetryHandler) {\n      Injector injector = Guice.createInjector(new AbstractModule() {\n         @Override\n         protected void configure() {\n            Names.bindProperties(binder(), BaseHttpApiMetadata.defaultProperties());\n            bind(IOExceptionRetryHandler.class).toInstance(ioRetryHandler);\n            bind(BaseHttpCommandExecutorService.class).to(MockHttpCommandExecutorService.class);\n         }\n      });\n\n      return injector.getInstance(BaseHttpCommandExecutorService.class);\n   }\n\n   private static class MockInputStream extends InputStream {\n      boolean isOpen = true;\n      int count;\n      int closeCount = 0;\n\n      public MockInputStream(int count) {\n         this.count = count;\n      }\n\n      @Override\n      public void close() throws IOException {\n         this.closeCount++;\n         if (!this.isOpen) {\n            throw new IOException(\"The stream is already closed\");\n         }\n         this.isOpen = false;\n      }\n\n      @Override\n      public int read() throws IOException {\n         if (this.isOpen)\n            return (count > 0) ? --count : -1;\n         else\n            return -1;\n      }\n\n      @Override\n      public int available() throws IOException {\n         if (this.isOpen)\n            return count;\n         else\n            return 0;\n      }\n\n   }\n\n   private static class MockHttpCommandExecutorService extends BaseHttpCommandExecutorService<Object> {\n\n      @Inject\n      MockHttpCommandExecutorService(HttpUtils utils, ContentMetadataCodec contentMetadataCodec,\n            DelegatingRetryHandler retryHandler, IOExceptionRetryHandler ioRetryHandler,\n            DelegatingErrorHandler errorHandler, HttpWire wire,\n            @Named(PROPERTY_IDEMPOTENT_METHODS) String idempotentMethods) {\n         super(utils, contentMetadataCodec, retryHandler, ioRetryHandler, errorHandler, wire, idempotentMethods);\n      }\n\n      @Override\n      protected Object convert(HttpRequest request) throws IOException, InterruptedException {\n         return null;\n      }\n\n      @Override\n      protected HttpResponse invoke(Object nativeRequest) throws IOException, InterruptedException {\n         return null;\n      }\n\n      @Override\n      protected void cleanup(Object nativeRequest) {\n\n      }\n\n   }\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/http/internal/TrackingJavaUrlHttpCommandExecutorService.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.internal;\n\nimport static org.jclouds.Constants.PROPERTY_IDEMPOTENT_METHODS;\nimport static org.jclouds.Constants.PROPERTY_OUTPUT_SOCKET_BUFFER_SIZE;\nimport static org.jclouds.Constants.PROPERTY_USER_AGENT;\n\nimport java.net.Proxy;\nimport java.net.URI;\nimport java.util.Collection;\nimport java.util.List;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\nimport javax.net.ssl.HostnameVerifier;\nimport javax.net.ssl.SSLContext;\n\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpUtils;\nimport org.jclouds.http.IOExceptionRetryHandler;\nimport org.jclouds.http.handlers.DelegatingErrorHandler;\nimport org.jclouds.http.handlers.DelegatingRetryHandler;\nimport org.jclouds.io.ContentMetadataCodec;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.Iterables;\nimport com.google.common.reflect.Invokable;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Module;\nimport com.google.inject.TypeLiteral;\n\n/**\n * Records all http commands submitted, storing them in the given List<HttpCommand>.\n */\n@Singleton\npublic class TrackingJavaUrlHttpCommandExecutorService extends JavaUrlHttpCommandExecutorService {\n\n   private final List<HttpCommand> commandsInvoked;\n\n   /**\n    * Creates a guice module, which will bind in TrackingJavaUrlHttpCommandExecutorService and also bind\n    * the given list so that it is used by the tracker.\n    */\n   public static Module newTrackingModule(final List<HttpCommand> commandsInvoked) {\n      return new AbstractModule() {\n\n         @Override\n         protected void configure() {\n            bind(JavaUrlHttpCommandExecutorService.class).to(\n                     TrackingJavaUrlHttpCommandExecutorService.class);\n            bind(new TypeLiteral<List<HttpCommand>>() {\n            }).toInstance(commandsInvoked);\n         }\n      };\n   }\n   \n   public static Invokable<?, ?> getInvokerOfRequestAtIndex(final Collection<HttpCommand> commandsInvoked, int index) {\n      return getInvokerOfRequest(Iterables.get(commandsInvoked, index));\n   }\n\n   public static Invokable<?, ?> getInvokerOfRequest(HttpCommand commandInvoked) {\n      return GeneratedHttpRequest.class.cast(commandInvoked.getCurrentRequest()).getInvocation().getInvokable();\n   }\n\n   public static List<Object> getArgsForRequestAtIndex(final Collection<HttpCommand> commandsInvoked, int index) {\n      return GeneratedHttpRequest.class.cast(Iterables.get(commandsInvoked, index).getCurrentRequest()).getInvocation()\n            .getArgs();\n   }\n\n   @Inject\n   public TrackingJavaUrlHttpCommandExecutorService(HttpUtils utils, ContentMetadataCodec contentMetadataCodec,\n            DelegatingRetryHandler retryHandler, IOExceptionRetryHandler ioRetryHandler,\n            DelegatingErrorHandler errorHandler, HttpWire wire, @Named(\"untrusted\") HostnameVerifier verifier,\n            @Named(\"untrusted\") Supplier<SSLContext> untrustedSSLContextProvider, Function<URI, Proxy> proxyForURI,\n            List<HttpCommand> commandsInvoked,\n            @Named(PROPERTY_IDEMPOTENT_METHODS) String idempotentMethods,\n            @Named(PROPERTY_OUTPUT_SOCKET_BUFFER_SIZE) int outputSocketBufferSize,\n            @Named(PROPERTY_USER_AGENT) String userAgent)\n            throws SecurityException, NoSuchFieldException {\n      super(utils, contentMetadataCodec, retryHandler, ioRetryHandler, errorHandler, wire, verifier,\n            untrustedSSLContextProvider, proxyForURI, idempotentMethods, outputSocketBufferSize, userAgent);\n      this.commandsInvoked = commandsInvoked;\n   }\n\n   @Override\n   public HttpResponse invoke(HttpCommand command) {\n      commandsInvoked.add(command);\n      return super.invoke(command);\n   }\n   \n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/http/internal/WireLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.hash.Hashing.md5;\nimport static com.google.common.io.BaseEncoding.base16;\nimport static java.util.concurrent.Executors.newCachedThreadPool;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\nimport java.net.URL;\nimport java.net.URLConnection;\nimport java.net.UnknownHostException;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.Future;\nimport java.util.concurrent.TimeUnit;\n\nimport com.google.common.io.ByteStreams;\n\nimport org.jclouds.io.ByteStreams2;\nimport org.jclouds.logging.Logger;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true)\npublic class WireLiveTest {\n\n   private static final String sysHttpStreamUrl = System.getProperty(\"jclouds.wire.httpstream.url\");\n   private static final String sysHttpStreamMd5 = System.getProperty(\"jclouds.wire.httpstream.md5\");\n\n   private static class ConnectionTester implements Callable<Void> {\n      private final InputStream fromServer;\n\n      private ConnectionTester(InputStream fromServer) {\n         this.fromServer = fromServer;\n      }\n\n      public Void call() throws Exception {\n         HttpWire wire = setUp();\n         InputStream in = wire.input(fromServer);\n         byte[] compare = md5().hashBytes(ByteStreams.toByteArray(in)).asBytes();\n         Thread.sleep(100);\n         assertEquals(base16().lowerCase().encode(compare), checkNotNull(sysHttpStreamMd5, \"sysHttpStreamMd5\"));\n         assertEquals(((BufferLogger) wire.getWireLog()).buff.toString().getBytes().length, 3331484);\n         return null;\n      }\n   }\n\n   static class BufferLogger implements Logger {\n      StringBuilder buff = new StringBuilder();\n\n      public void debug(String message, Object... args) {\n         buff.append(message);\n      }\n\n      public void error(String message, Object... args) {\n      }\n\n      public void error(Throwable throwable, String message, Object... args) {\n      }\n\n      public String getCategory() {\n         return null;\n      }\n\n      public void info(String message, Object... args) {\n      }\n\n      public boolean isDebugEnabled() {\n         return true;\n      }\n\n      public boolean isErrorEnabled() {\n         return false;\n      }\n\n      public boolean isInfoEnabled() {\n         return false;\n      }\n\n      public boolean isTraceEnabled() {\n         return false;\n      }\n\n      public boolean isWarnEnabled() {\n         return false;\n      }\n\n      public void trace(String message, Object... args) {\n      }\n\n      public void warn(String message, Object... args) {\n      }\n\n      public void warn(Throwable throwable, String message, Object... args) {\n      }\n\n   }\n\n   public static HttpWire setUp() throws Exception {\n      BufferLogger bufferLogger = new BufferLogger();\n      HttpWire wire = new HttpWire();\n      wire.wireLog = bufferLogger;\n      return wire;\n   }\n\n   public HttpWire setUpSynch() throws Exception {\n      BufferLogger bufferLogger = new BufferLogger();\n      HttpWire wire = new HttpWire();\n      wire.wireLog = bufferLogger;\n      return wire;\n   }\n\n   @Test(groups = \"live\")\n   public void testRemoteInputStream() throws Exception {\n      try {\n         URL url = new URL(checkNotNull(sysHttpStreamUrl, \"sysHttpStreamUrl\"));\n         URLConnection connection = url.openConnection();\n         HttpWire wire = setUp();\n         InputStream in = wire.input(connection.getInputStream());\n         byte[] compare = ByteStreams2.hashAndClose(in, md5()).asBytes();\n         Thread.sleep(100);\n         assertEquals(base16().lowerCase().encode(compare), checkNotNull(sysHttpStreamMd5, \"sysHttpStreamMd5\"));\n         assertEquals(((BufferLogger) wire.getWireLog()).buff.toString().getBytes().length, 3331484);\n      } catch (UnknownHostException e) {\n         // probably in offline mode\n      }\n   }\n\n   @Test(groups = \"live\", enabled = false)\n   public void testCopyRemoteInputStream() throws Exception {\n      URL url = new URL(checkNotNull(sysHttpStreamUrl, \"sysHttpStreamUrl\"));\n      URLConnection connection = url.openConnection();\n      Callable<Void> callable = new ConnectionTester(connection.getInputStream());\n      Future<Void> result = newCachedThreadPool().submit(callable);\n      result.get(30, TimeUnit.SECONDS);\n   }\n\n   @Test(groups = \"live\")\n   public void testRemoteInputStreamSynch() throws Exception {\n      try {\n         URL url = new URL(checkNotNull(sysHttpStreamUrl, \"sysHttpStreamUrl\"));\n         URLConnection connection = url.openConnection();\n         HttpWire wire = setUpSynch();\n         InputStream in = wire.input(connection.getInputStream());\n         byte[] compare = ByteStreams2.hashAndClose(in, md5()).asBytes();\n         Thread.sleep(100);\n         assertEquals(base16().lowerCase().encode(compare), checkNotNull(sysHttpStreamMd5, \"sysHttpStreamMd5\"));\n         assertEquals(((BufferLogger) wire.getWireLog()).buff.toString().getBytes().length, 3331484);\n      } catch (UnknownHostException e) {\n         // probably in offline mode\n      }\n   }\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/http/internal/WireTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.internal;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.io.PayloadEnclosing;\nimport org.jclouds.io.payloads.StringPayload;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.Test;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.InputStream;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotEquals;\n\n@Test(groups = \"unit\", singleThreaded = true)\npublic class WireTest {\n\n   static class BufferLogger implements Logger {\n      StringBuilder buff = new StringBuilder();\n\n      public void debug(String message, Object... args) {\n         buff.append(message);\n      }\n\n      public void error(String message, Object... args) {\n      }\n\n      public void error(Throwable throwable, String message, Object... args) {\n      }\n\n      public String getCategory() {\n         return null;\n      }\n\n      public void info(String message, Object... args) {\n      }\n\n      public boolean isDebugEnabled() {\n         return true;\n      }\n\n      public boolean isErrorEnabled() {\n         return false;\n      }\n\n      public boolean isInfoEnabled() {\n         return false;\n      }\n\n      public boolean isTraceEnabled() {\n         return false;\n      }\n\n      public boolean isWarnEnabled() {\n         return false;\n      }\n\n      public void trace(String message, Object... args) {\n      }\n\n      public void warn(String message, Object... args) {\n      }\n\n      public void warn(Throwable throwable, String message, Object... args) {\n      }\n\n   }\n\n   public HttpWire setUp() throws Exception {\n      BufferLogger bufferLogger = new BufferLogger();\n      HttpWire wire = new HttpWire();\n      wire.wireLog = bufferLogger;\n      return wire;\n   }\n\n   public HttpWire setUpSynch() throws Exception {\n      BufferLogger bufferLogger = new BufferLogger();\n      HttpWire wire = new HttpWire();\n      wire.wireLog = bufferLogger;\n      return wire;\n   }\n\n   public void testInputInputStream() throws Exception {\n      HttpWire wire = setUp();\n      InputStream in = wire.input(new ByteArrayInputStream(\"foo\".getBytes()));\n      String compare = Strings2.toStringAndClose(in);\n      Thread.sleep(100);\n      assertEquals(compare, \"foo\");\n      assertEquals(((BufferLogger) wire.getWireLog()).buff.toString(), \"<< \\\"foo\\\"\");\n   }\n\n   public void testInputInputStreamSynch() throws Exception {\n      HttpWire wire = setUpSynch();\n      InputStream in = wire.input(new ByteArrayInputStream(\"foo\".getBytes()));\n      String compare = Strings2.toStringAndClose(in);\n      assertEquals(compare, \"foo\");\n      assertEquals(((BufferLogger) wire.getWireLog()).buff.toString(), \"<< \\\"foo\\\"\");\n   }\n\n   public void testOutputInputStream() throws Exception {\n      HttpWire wire = setUp();\n      InputStream in = wire.output(new ByteArrayInputStream(\"foo\".getBytes()));\n      String compare = Strings2.toStringAndClose(in);\n      Thread.sleep(100);\n      assertEquals(compare, \"foo\");\n      assertEquals(((BufferLogger) wire.getWireLog()).buff.toString(), \">> \\\"foo\\\"\");\n   }\n\n   public void testOutputBytes() throws Exception {\n      HttpWire wire = setUp();\n      wire.output(\"foo\".getBytes());\n      assertEquals(((BufferLogger) wire.getWireLog()).buff.toString(), \">> \\\"foo\\\"\");\n   }\n\n   public void testOutputString() throws Exception {\n      HttpWire wire = setUp();\n      wire.output(\"foo\");\n      assertEquals(((BufferLogger) wire.getWireLog()).buff.toString(), \">> \\\"foo\\\"\");\n   }\n\n   @Test\n   public void testInputPayload() throws Exception {\n      HttpWire wire = setUp();\n      StringPayload payload = new StringPayload(\"foo\");\n      PayloadEnclosing request = HttpRequest.builder().method(\"foo\").endpoint(\"http://foo\").payload(payload).build();\n      wire.input(request);\n      BufferLogger wireLog = (BufferLogger) wire.getWireLog();\n      assertEquals(wireLog.buff.toString(), \"<< \\\"foo\\\"\", \"Expected payload to be printed in logs\");\n      wireLog.buff.setLength(0);\n\n      payload.setSensitive(true);\n      request = HttpRequest.builder().method(\"foo\").endpoint(\"http://foo\").payload(payload).build();\n      wire.input(request);\n      assertNotEquals(wireLog.buff.toString(), \"<< \\\"foo\\\"\", \"Expected payload to NOT be printed in logs\");\n      wireLog.buff.setLength(0);\n\n      wire.logSensitiveInformation = true;\n      request = HttpRequest.builder().method(\"foo\").endpoint(\"http://foo\").payload(payload).build();\n      wire.input(request);\n      assertEquals(wireLog.buff.toString(), \"<< \\\"foo\\\"\", \"Expected payload to be printed in logs\");\n   }\n\n   @Test\n   public void testOutputPayload() throws Exception {\n      HttpWire wire = setUp();\n      StringPayload payload = new StringPayload(\"foo\");\n      PayloadEnclosing request = HttpRequest.builder().method(\"foo\").endpoint(\"http://foo\").payload(payload).build();\n      wire.output(request);\n      BufferLogger wireLog = (BufferLogger) wire.getWireLog();\n      assertEquals(wireLog.buff.toString(), \">> \\\"foo\\\"\", \"Expected payload to be printed in logs\");\n      wireLog.buff.setLength(0);\n\n      payload.setSensitive(true);\n      request = HttpRequest.builder().method(\"foo\").endpoint(\"http://foo\").payload(payload).build();\n      wire.output(request);\n      assertNotEquals(wireLog.buff.toString(), \">> \\\"foo\\\"\", \"Expected payload to NOT be printed in logs\");\n      wireLog.buff.setLength(0);\n\n      wire.logSensitiveInformation = true;\n      request = HttpRequest.builder().method(\"foo\").endpoint(\"http://foo\").payload(payload).build();\n      wire.output(request);\n      assertEquals(wireLog.buff.toString(), \">> \\\"foo\\\"\", \"Expected payload to be printed in logs\");\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/http/options/GetOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.options;\n\nimport static org.jclouds.http.options.GetOptions.Builder.ifETagDoesntMatch;\nimport static org.jclouds.http.options.GetOptions.Builder.ifETagMatches;\nimport static org.jclouds.http.options.GetOptions.Builder.ifModifiedSince;\nimport static org.jclouds.http.options.GetOptions.Builder.ifUnmodifiedSince;\nimport static org.jclouds.http.options.GetOptions.Builder.range;\nimport static org.jclouds.http.options.GetOptions.Builder.startAt;\nimport static org.jclouds.http.options.GetOptions.Builder.tail;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\n\nimport java.util.Date;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests possible uses of GetOptions and GetOptions.Builder.*\n */\n@Test(groups = \"unit\")\npublic class GetOptionsTest {\n\n   private String etag;\n   private Date now;\n   private String nowExpected;\n\n   @BeforeTest\n   void setUp() {\n      now = new Date();\n      nowExpected = new SimpleDateFormatDateService().rfc822DateFormat(now);\n      etag = \"yrdy\";\n   }\n\n   @Test\n   public void testIfModifiedSince() {\n      GetOptions options = new GetOptions();\n      options.ifModifiedSince(now);\n      assertEquals(options.getIfModifiedSince(), nowExpected);\n   }\n\n   @Test\n   public void testNullIfModifiedSince() {\n      GetOptions options = new GetOptions();\n      assertNull(options.getIfModifiedSince());\n   }\n\n   @Test\n   public void testIfModifiedSinceStatic() {\n      GetOptions options = ifModifiedSince(now);\n      assertEquals(options.getIfModifiedSince(), nowExpected);\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testIfModifiedSinceNPE() {\n      ifModifiedSince(null);\n   }\n\n   @Test\n   public void testIfUnmodifiedSince() {\n      GetOptions options = new GetOptions();\n      options.ifUnmodifiedSince(now);\n      isNowExpected(options);\n   }\n\n   @Test\n   public void testNullIfUnmodifiedSince() {\n      GetOptions options = new GetOptions();\n      assertNull(options.getIfUnmodifiedSince());\n   }\n\n   @Test\n   public void testIfUnmodifiedSinceStatic() {\n      GetOptions options = ifUnmodifiedSince(now);\n      isNowExpected(options);\n   }\n\n   private void isNowExpected(GetOptions options) {\n      assertEquals(options.getIfUnmodifiedSince(), nowExpected);\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testIfUnmodifiedSinceNPE() {\n      ifUnmodifiedSince(null);\n   }\n\n   public void testModifiedSinceAndRange() {\n      GetOptions options = new GetOptions();\n      options.ifModifiedSince(now);\n      options.range(0, 1024);\n      assertEquals(options.getIfModifiedSince(), nowExpected);\n      bytes1to1024(options);\n   }\n\n   @Test\n   public void testRange() {\n      GetOptions options = new GetOptions();\n      options.range(0, 1024);\n      bytes1to1024(options);\n   }\n\n   private void bytes1to1024(GetOptions options) {\n      assertEquals(options.getRange(), \"bytes=0-1024\");\n   }\n\n   @Test\n   public void testRangeZeroToFive() {\n      GetOptions options = new GetOptions();\n      options.range(0, 5);\n      assertEquals(options.getRange(), \"bytes=0-5\");\n   }\n\n   @Test\n   public void testTail() {\n      GetOptions options = new GetOptions();\n      options.tail(100);\n      assertEquals(options.getRange(), \"bytes=-100\");\n   }\n\n   @Test\n   public void testTailStatic() {\n      GetOptions options = tail(100);\n      assertEquals(options.getRange(), \"bytes=-100\");\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testTailFail() {\n      GetOptions options = new GetOptions();\n      options.tail(0);\n   }\n\n   @Test\n   public void testStartAt() {\n      GetOptions options = new GetOptions();\n      options.startAt(100);\n      assertEquals(options.getRange(), \"bytes=100-\");\n   }\n\n   @Test\n   public void testStartAtStatic() {\n      GetOptions options = startAt(100);\n      assertEquals(options.getRange(), \"bytes=100-\");\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testStartAtFail() {\n      GetOptions options = new GetOptions();\n      options.startAt(-1);\n   }\n\n   @Test\n   public void testRangeZeroToFiveAnd10through100() {\n      GetOptions options = new GetOptions();\n      options.range(0, 5).range(10, 100);\n      assertEquals(options.getRange(), \"bytes=0-5,10-100\");\n   }\n\n   @Test\n   public void testNullRange() {\n      GetOptions options = new GetOptions();\n      assertNull(options.getRange());\n   }\n\n   @Test\n   public void testRangeStatic() {\n      GetOptions options = range(0, 1024);\n      bytes1to1024(options);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testRangeNegative1() {\n      range(-1, 0);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testRangeNegative2() {\n      range(0, -1);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testRangeNegative() {\n      range(-1, -1);\n   }\n\n   @Test\n   public void testIfETagMatches() {\n      GetOptions options = new GetOptions();\n      options.ifETagMatches(etag);\n      matchesHex(options.getIfMatch());\n   }\n\n   @Test\n   public void testNullIfETagMatches() {\n      GetOptions options = new GetOptions();\n      assertNull(options.getIfMatch());\n   }\n\n   @Test\n   public void testIfETagMatchesStatic() {\n      GetOptions options = ifETagMatches(etag);\n      matchesHex(options.getIfMatch());\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testIfETagMatchesNPE() {\n      ifETagMatches(null);\n   }\n\n   @Test\n   public void testIfETagDoesntMatch() {\n      GetOptions options = new GetOptions();\n      options.ifETagDoesntMatch(etag);\n      matchesHex(options.getIfNoneMatch());\n   }\n\n   @Test\n   public void testNullIfETagDoesntMatch() {\n      GetOptions options = new GetOptions();\n      assertNull(options.getIfNoneMatch());\n   }\n\n   @Test\n   public void testIfETagDoesntMatchStatic() {\n      GetOptions options = ifETagDoesntMatch(etag);\n      matchesHex(options.getIfNoneMatch());\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testIfETagDoesntMatchNPE() {\n      ifETagDoesntMatch(null);\n   }\n\n   private void matchesHex(String match) {\n      String expected = \"\\\"\" + etag + \"\\\"\";\n      assertEquals(match, expected);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testIfUnmodifiedAfterModified() {\n      ifModifiedSince(now).ifUnmodifiedSince(now);\n\n   }\n\n   public void testIfUnmodifiedAfterETagMatches() {\n      ifETagMatches(etag).ifUnmodifiedSince(now);\n\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testIfUnmodifiedAfterETagDoesntMatch() {\n      ifETagDoesntMatch(etag).ifUnmodifiedSince(now);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testIfModifiedAfterUnmodified() {\n      ifUnmodifiedSince(now).ifModifiedSince(now);\n\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testIfModifiedAfterETagMatches() {\n      ifETagMatches(etag).ifModifiedSince(now);\n\n   }\n\n   public void testIfModifiedAfterETagDoesntMatch() {\n      ifETagDoesntMatch(etag).ifModifiedSince(now);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testETagMatchesAfterIfModified() {\n      ifModifiedSince(now).ifETagMatches(etag);\n\n   }\n\n   public void testETagMatchesAfterIfUnmodified() {\n      ifUnmodifiedSince(now).ifETagMatches(etag);\n\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testETagMatchesAfterETagDoesntMatch() {\n      ifETagDoesntMatch(etag).ifETagMatches(etag);\n   }\n\n   public void testETagDoesntMatchAfterIfModified() {\n      ifModifiedSince(now).ifETagDoesntMatch(etag);\n\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testETagDoesntMatchAfterIfUnmodified() {\n      ifUnmodifiedSince(now).ifETagDoesntMatch(etag);\n\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testETagDoesntMatchAfterETagMatches() {\n      ifETagMatches(etag).ifETagDoesntMatch(etag);\n   }\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/http/utils/QueriesTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.utils;\n\nimport static org.jclouds.http.utils.Queries.queryParser;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Set;\n\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.LinkedListMultimap;\nimport com.google.common.collect.Multimap;\n\n@Test(groups = \"unit\", testName = \"QueriesTest\")\npublic class QueriesTest {\n\n   public void testParseBase64InForm() {\n      Multimap<String, String> expects = LinkedListMultimap.create();\n      expects.put(\"Version\", \"2010-06-15\");\n      expects.put(\"Action\", \"ModifyInstanceAttribute\");\n      expects.put(\"Attribute\", \"userData\");\n      expects.put(\"Value\", \"dGVzdA==\");\n      expects.put(\"InstanceId\", \"1\");\n      assertEquals(\n            queryParser()\n                  .apply(\n                        \"Version=2010-06-15&Action=ModifyInstanceAttribute&Attribute=userData&Value=dGVzdA%3D%3D&InstanceId=1\"),\n            expects);\n   }\n\n   @Test\n   public void testParseQueryToMapSingleParam() {\n      Multimap<String, String> parsedMap = queryParser().apply(\"v=1.3\");\n      assert parsedMap.keySet().size() == 1 : \"Expected 1 key, found: \" + parsedMap.keySet().size();\n      assert parsedMap.keySet().contains(\"v\") : \"Expected v to be a part of the keys\";\n      String valueForV = Iterables.getOnlyElement(parsedMap.get(\"v\"));\n      assert valueForV.equals(\"1.3\") : \"Expected the value for 'v' to be '1.3', found: \" + valueForV;\n   }\n\n   @Test\n   public void testParseQueryToMapMultiParam() {\n      Multimap<String, String> parsedMap = queryParser().apply(\"v=1.3&sig=123\");\n      assert parsedMap.keySet().size() == 2 : \"Expected 2 keys, found: \" + parsedMap.keySet().size();\n      assert parsedMap.keySet().contains(\"v\") : \"Expected v to be a part of the keys\";\n      assert parsedMap.keySet().contains(\"sig\") : \"Expected sig to be a part of the keys\";\n      String valueForV = Iterables.getOnlyElement(parsedMap.get(\"v\"));\n      assert valueForV.equals(\"1.3\") : \"Expected the value for 'v' to be '1.3', found: \" + valueForV;\n      String valueForSig = Iterables.getOnlyElement(parsedMap.get(\"sig\"));\n      assert valueForSig.equals(\"123\") : \"Expected the value for 'v' to be '123', found: \" + valueForSig;\n   }\n\n   @Test\n   public void testParseQueryEncodedWithDefaultJavaEncoder() {\n      String key = \"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCc903twxU2zcQnIJdXv61RwZNZW94uId9qz08fgsBJsCOnHNIC4+L9k\" +\n         \"DOA2IHV9cUfEDBm1Be5TbpadWwSbS/05E+FARH2/MCO932UgcKUq5PGymS0249fLCBPci5zoLiG5vIym+1ij1hL/nHvkK99NIwe7io+Lmp\" +\n         \"9OcF3PTsm3Rgh5T09cRHGX9horp0VoAVa9vKJx6C1/IEHVnG8p0YPPa1lmemvx5kNBEiyoNQNYa34EiFkcJfP6rqNgvY8h/j4nE9SXoUCC\" +\n         \"/g6frhMFMOL0tzYqvz0Lczqm1Oh4RnSn3O9X4R934p28qqAobe337hmlLUdb6H5zuf+NwCh0HdZ\";\n\n      Set<String> expected = ImmutableSet.of(key);\n\n      Multimap<String, String> parsedMap = queryParser().apply(\"a=1&b=1+2&publickey=\" + Strings2.urlEncode(key));\n      assertEquals(parsedMap.get(\"publickey\"), expected);\n\n      parsedMap = queryParser().apply(\"publickey=\" + Strings2.urlEncode(key));\n      assertEquals(parsedMap.get(\"publickey\"), expected);\n   }\n\n   @Test\n   public void testParseQueryWithKeysThatRequireDecoding() {\n      Multimap<String, String> parsedMap = queryParser().apply(\"network%5B0%5D.id=23&network%5B0%5D.address=192.168.0.1\");\n\n      assertEquals(parsedMap.get(\"network[0].id\"), ImmutableSet.of(\"23\"));\n      assertEquals(parsedMap.get(\"network[0].address\"), ImmutableSet.of(\"192.168.0.1\"));\n   }\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/internal/BaseViewTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.internal;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.jclouds.reflect.Reflection2.typeToken;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotEquals;\nimport static org.testng.Assert.fail;\n\nimport java.io.Closeable;\nimport java.io.IOException;\n\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.lifecycle.Closer;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.rest.ApiContext;\nimport org.jclouds.rest.Utils;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.reflect.TypeToken;\n\n/** \n */\n@Test(groups = \"unit\", testName = \"BaseViewTest\")\npublic class BaseViewTest {\n\n   static Supplier<Credentials> creds = Suppliers.ofInstance(new Credentials(\"identity\", null));\n\n   private static class Water extends ContextImpl {\n\n      protected Water() {\n         super(\"water\", createMock(ProviderMetadata.class), creds, createMock(Utils.class), createMock(Closer.class));\n      }\n\n      public void close() {\n      }\n   }\n\n   private static class PeanutButter extends ContextImpl {\n\n      protected PeanutButter() {\n         super(\"peanutbutter\", createMock(ProviderMetadata.class), creds, createMock(Utils.class), createMock(Closer.class));\n      }\n\n      public void close() {\n      }\n   }\n   \n   private static class Wine extends BaseView {\n\n      protected Wine() {\n         super(new Water(), typeToken(Water.class));\n      }\n   }\n\n   private static class DummyApi implements Closeable {\n\n      @Override\n      public void close() throws IOException {\n\n      }\n   }\n\n   public static class DummyView extends BaseView {\n\n      protected DummyView(ApiContext<DummyApi> context) {\n         super(context, new TypeToken<ApiContext<DummyApi>>() {\n            private static final long serialVersionUID = 1L;\n         });\n      }\n   }\n\n   public void testWaterTurnedIntoWine() {\n      Wine wine = new Wine();\n      assertEquals(wine.getBackendType(), typeToken(Water.class));\n      assertEquals(wine.unwrap(typeToken(Water.class)).getClass(), Water.class);\n      assertEquals(wine.unwrap().getClass(), Water.class);\n   }\n\n   public void testPeanutButterDidntTurnIntoWine() {\n      Wine wine = new Wine();\n      assertNotEquals(wine.getBackendType(), typeToken(PeanutButter.class));\n      try {\n         wine.unwrap(typeToken(PeanutButter.class));\n         fail();\n      } catch (IllegalArgumentException e) {\n         assertEquals(e.getMessage(), \"org.jclouds.internal.BaseViewTest$PeanutButter is not a supertype of backend type org.jclouds.internal.BaseViewTest$Water\");\n      }\n   }\n\n   public void testCannotUnwrapIfNotApiContext() {\n      Wine wine = new Wine();\n      try {\n         wine.unwrapApi(DummyApi.class);\n         fail();\n      } catch (IllegalArgumentException e) {\n         assertEquals(e.getMessage(), \"backend type: org.jclouds.internal.BaseViewTest$Water should be an ApiContext\");\n      }\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   public void testUnwrapApi() {\n      DummyApi beer = new DummyApi();\n      ApiContext<DummyApi> beerContext = createMock(ApiContext.class);\n      expect(beerContext.getApi()).andReturn(beer);\n      replay(beerContext);\n\n      DummyView bar = new DummyView(beerContext);\n      DummyApi result = bar.unwrapApi(DummyApi.class);\n\n      assertEquals(result, beer);\n      verify(beerContext);\n   }\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/internal/FilterStringsBoundToInjectorByNameTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.internal;\n\nimport static org.testng.Assert.assertEquals;\n\nimport jakarta.inject.Named;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicates;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Provides;\nimport com.google.inject.name.Names;\n\n@Test(testName = \"FilterStringsBoundToInjectorByNameTest\")\npublic class FilterStringsBoundToInjectorByNameTest {\n\n   public void testEmptyWhenNoStringsBound() {\n      FilterStringsBoundToInjectorByName fn = Guice.createInjector().getInstance(FilterStringsBoundToInjectorByName.class);\n      assertEquals(fn.apply(Predicates.<String> alwaysTrue()), ImmutableMap.<String, String> of());\n   }\n\n   public void testEmptyWhenNotStringsBound() {\n      FilterStringsBoundToInjectorByName fn = Guice.createInjector(new AbstractModule() {\n\n         @Override\n         protected void configure() {\n            bindConstant().annotatedWith(Names.named(\"foo\")).to(1L);\n         }\n\n      }).getInstance(FilterStringsBoundToInjectorByName.class);\n\n      assertEquals(fn.apply(Predicates.<String> alwaysTrue()), ImmutableMap.<String, String> of());\n   }\n\n   public void testReturnsGuiceNamedString() {\n      FilterStringsBoundToInjectorByName fn = Guice.createInjector(new AbstractModule() {\n\n         @Override\n         protected void configure() {\n            bindConstant().annotatedWith(Names.named(\"foo\")).to(\"bar\");\n         }\n\n      }).getInstance(FilterStringsBoundToInjectorByName.class);\n\n      assertEquals(fn.apply(Predicates.<String> alwaysTrue()), ImmutableMap.<String, String> of(\"foo\", \"bar\"));\n   }\n\n   public void testReturnsJavaNamedString() {\n      FilterStringsBoundToInjectorByName fn = Guice.createInjector(new AbstractModule() {\n         @Named(\"foo\")\n         @Provides\n         String provideFoo() {\n            return \"bar\";\n         }\n\n         @Override\n         protected void configure() {\n         }\n\n      }).getInstance(FilterStringsBoundToInjectorByName.class);\n\n      assertEquals(fn.apply(Predicates.<String> alwaysTrue()), ImmutableMap.<String, String> of(\"foo\", \"bar\"));\n   }\n\n   public void testFilterWorks() {\n      FilterStringsBoundToInjectorByName fn = Guice.createInjector(new AbstractModule() {\n\n         @Override\n         protected void configure() {\n            bindConstant().annotatedWith(Names.named(\"foo\")).to(\"bar\");\n            bindConstant().annotatedWith(Names.named(\"bing\")).to(\"bong\");\n         }\n\n      }).getInstance(FilterStringsBoundToInjectorByName.class);\n\n      assertEquals(fn.apply(Predicates.<String> equalTo(\"bing\")), ImmutableMap.<String, String> of(\"bing\", \"bong\"));\n   }\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/io/DefaultContentMetadataCodecTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.io;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Date;\n\nimport org.jclouds.date.internal.DateServiceDateCodecFactory;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.io.ContentMetadataCodec.DefaultContentMetadataCodec;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"DefaultContentMetadataCodecTest\")\npublic class DefaultContentMetadataCodecTest {\n\n   private final DateServiceDateCodecFactory codecfactory = new DateServiceDateCodecFactory(\n         new SimpleDateFormatDateService());\n\n   public void testCanParseRFC1123Dates() {\n      DefaultContentMetadataCodec codec = new DefaultContentMetadataCodec(codecfactory);\n      Date parsed = codec.parseExpires(\"Thu, 01 Dec 1994 16:00:00 GMT\");\n      assertEquals(parsed, new Date(786297600000L));\n   }\n\n   public void testCanParseAsctimeDates() {\n      DefaultContentMetadataCodec codec = new DefaultContentMetadataCodec(codecfactory);\n      Date parsed = codec.parseExpires(\"Thu Dec 01 16:00:00 GMT 1994\");\n      assertEquals(parsed, new Date(786297600000L));\n   }\n\n   public void testFallbackToExpiredDate() {\n      DefaultContentMetadataCodec codec = new DefaultContentMetadataCodec(codecfactory);\n      Date parsed = codec.parseExpires(\"1994-12-01T16:00:00.000Z\");\n      assertEquals(parsed, new Date(0));\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/io/internal/BasePayloadSlicerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.io.internal;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.IOException;\nimport java.util.Iterator;\n\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.PayloadSlicer;\nimport org.jclouds.io.payloads.ByteSourcePayload;\nimport org.jclouds.io.payloads.InputStreamPayload;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.io.ByteSource;\n\n@Test\npublic class BasePayloadSlicerTest {\n\n   @Test\n   public void testIterableSliceExpectedSingle() throws IOException {\n      PayloadSlicer slicer = new BasePayloadSlicer();\n      String contents = \"aaaaaaaaaabbbbbbbbbbccccc\";\n      Payload payload = new InputStreamPayload(new ByteArrayInputStream(contents.getBytes(Charsets.US_ASCII)));\n\n      Iterator<Payload> iter = slicer.slice(payload, 25).iterator();\n\n      assertTrue(iter.hasNext(), \"Not enough results\");\n      assertEquals(Strings2.toStringAndClose(iter.next().openStream()), contents);\n      assertFalse(iter.hasNext());\n\n   }\n\n   @Test\n   public void testIterableSliceExpectedMulti() throws IOException {\n      PayloadSlicer slicer = new BasePayloadSlicer();\n      Payload payload = new InputStreamPayload(new ByteArrayInputStream(\"aaaaaaaaaabbbbbbbbbbccccc\".getBytes(Charsets.US_ASCII)));\n\n      Iterator<Payload> iter = slicer.slice(payload, 10).iterator();\n\n      assertTrue(iter.hasNext(), \"Not enough results\");\n      assertEquals(Strings2.toStringAndClose(iter.next().getInput()), \"aaaaaaaaaa\");\n      assertTrue(iter.hasNext(), \"Not enough results\");\n      assertEquals(Strings2.toStringAndClose(iter.next().getInput()), \"bbbbbbbbbb\");\n      assertTrue(iter.hasNext(), \"Not enough results\");\n      assertEquals(Strings2.toStringAndClose(iter.next().getInput()), \"ccccc\");\n      assertFalse(iter.hasNext());\n\n   }\n\n   @Test\n   public void testIterableSliceWithRepeatingByteSourceSmallerPartSize() throws IOException {\n      PayloadSlicer slicer = new BasePayloadSlicer();\n      ByteSource byteSource = ByteSource.wrap(\"aaaaaaaaaabbbbbbbbbbccccc\".getBytes(Charsets.UTF_8)); /* 25 chars */\n      Payload payload = new ByteSourcePayload(byteSource);\n\n      Iterator<Payload> iter = slicer.slice(payload, 10).iterator();\n      Payload part;\n\n      assertTrue(iter.hasNext(), \"Not enough results\");\n      part = iter.next();\n      assertEquals(Strings2.toStringAndClose(part.getInput()), \"aaaaaaaaaa\");\n      assertEquals(part.getContentMetadata().getContentLength(), Long.valueOf(10));\n\n      assertTrue(iter.hasNext(), \"Not enough results\");\n      part = iter.next();\n      assertEquals(Strings2.toStringAndClose(part.getInput()), \"bbbbbbbbbb\");\n      assertEquals(part.getContentMetadata().getContentLength(), Long.valueOf(10));\n\n      assertTrue(iter.hasNext(), \"Not enough results\");\n      part = iter.next();\n      assertEquals(Strings2.toStringAndClose(part.getInput()), \"ccccc\");\n      assertEquals(part.getContentMetadata().getContentLength(), Long.valueOf(5));\n\n      assertFalse(iter.hasNext());\n   }\n\n   @Test\n   public void testIterableSliceWithRepeatingByteSourceLargerPartSize() throws IOException {\n      PayloadSlicer slicer = new BasePayloadSlicer();\n      ByteSource byteSource = ByteSource.wrap(\"aaaaaaaaaabbbbbbbbbbccccc\".getBytes(Charsets.UTF_8)); /* 25 chars */\n      Payload payload = new ByteSourcePayload(byteSource);\n\n      Iterator<Payload> iter = slicer.slice(payload, 50).iterator();\n      Payload part;\n\n      assertTrue(iter.hasNext(), \"Not enough results\");\n      part = iter.next();\n      assertEquals(Strings2.toStringAndClose(part.getInput()), \"aaaaaaaaaabbbbbbbbbbccccc\");\n      assertEquals(part.getContentMetadata().getContentLength(), Long.valueOf(25));\n\n      assertFalse(iter.hasNext());\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/io/payloads/MultipartFormTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.io.payloads;\n\nimport static com.google.common.net.MediaType.PLAIN_TEXT_UTF_8;\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\n\nimport org.jclouds.io.Payloads;\nimport org.jclouds.io.payloads.Part.PartOptions;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.Test;\n\n/**\n * Tests parsing of a request\n */\n@Test(testName = \"http.MultipartFormTest\")\npublic class MultipartFormTest {\n   String boundary = \"------------------------------c88555ffd14e\";\n\n   public void testSinglePart() throws IOException {\n\n      StringBuilder builder = new StringBuilder();\n      addData(boundary, \"file\", \"hello\", builder);\n      builder.append(\"--\").append(boundary).append(\"--\").append(\"\\r\\n\");\n      String expects = builder.toString();\n      assertEquals(expects.length(), 199);\n\n      MultipartForm multipartForm = new MultipartForm(boundary, newPart(\"file\", \"hello\"));\n\n      assertEquals(Strings2.toStringAndClose(multipartForm.openStream()), expects);\n      assertEquals(multipartForm.getContentMetadata().getContentLength(), Long.valueOf(199));\n   }\n\n   public void testLengthIsCorrectPerUTF8() throws IOException {\n\n      StringBuilder builder = new StringBuilder();\n      addData(boundary, \"unic₪de\", \"hello\", builder);\n      builder.append(\"--\").append(boundary).append(\"--\").append(\"\\r\\n\");\n      String expects = builder.toString();\n      assertEquals(expects.getBytes().length, 204);\n\n      MultipartForm multipartForm = new MultipartForm(boundary, newPart(\"unic₪de\", \"hello\"));\n\n      assertEquals(Strings2.toStringAndClose(multipartForm.openStream()), expects);\n      assertEquals(multipartForm.getContentMetadata().getContentLength(), Long.valueOf(204));\n   }\n\n   public static class MockFilePayload extends FilePayload {\n\n      private final StringPayload realPayload;\n\n      public MockFilePayload(String content) {\n         super(createMockFile(content));\n         this.realPayload = Payloads.newStringPayload(content);\n      }\n\n      private static File createMockFile(String content) {\n         File file = createMock(File.class);\n         expect(file.length()).andReturn((long) content.length());\n         expect(file.exists()).andReturn(true);\n         expect(file.getName()).andReturn(\"testfile.txt\");\n         replay(file);\n         return file;\n      }\n\n      @Override\n      public InputStream openStream() throws IOException {\n         return realPayload.openStream();\n      }\n\n      @Override\n      public boolean isRepeatable() {\n         return realPayload.isRepeatable();\n      }\n   }\n\n   private Part newPart(String name, String data) {\n      return Part.create(name, new MockFilePayload(data),\n            new PartOptions().contentType(PLAIN_TEXT_UTF_8.withoutParameters().toString()));\n   }\n\n   private void addData(String boundary, String name, String data, StringBuilder builder) {\n      builder.append(\"--\").append(boundary).append(\"\\r\\n\");\n      builder.append(\"Content-Disposition\").append(\": \").append(\"form-data; name=\\\"\").append(name).append(\"\\\"; filename=\\\"testfile.txt\\\"\")\n               .append(\"\\r\\n\");\n      builder.append(\"Content-Type\").append(\": \").append(\"text/plain\").append(\"\\r\\n\");\n      builder.append(\"\\r\\n\");\n      builder.append(data).append(\"\\r\\n\");\n   }\n\n   public void testMultipleParts() throws IOException {\n\n      StringBuilder builder = new StringBuilder();\n      addData(boundary, \"file\", \"hello\", builder);\n      addData(boundary, \"file\", \"goodbye\", builder);\n\n      builder.append(\"--\").append(boundary).append(\"--\").append(\"\\r\\n\");\n      String expects = builder.toString();\n\n      assertEquals(expects.length(), 352);\n\n      MultipartForm multipartForm = new MultipartForm(boundary, newPart(\"file\", \"hello\"), newPart(\"file\", \"goodbye\"));\n\n      assertEquals(Strings2.toStringAndClose(multipartForm.openStream()), expects);\n\n      // test repeatable\n      assert multipartForm.isRepeatable();\n      assertEquals(Strings2.toStringAndClose(multipartForm.openStream()), expects);\n      assertEquals(multipartForm.getContentMetadata().getContentLength(), Long.valueOf(352));\n   }\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/io/payloads/StringPayloadTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.io.payloads;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.io.Payload;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Charsets;\n\n@Test\npublic class StringPayloadTest {\n   public void testLengthIsCorrectPerUTF8() {\n      Payload stringPayload = new StringPayload(\"unic₪de\");\n      assertEquals(stringPayload.getContentMetadata().getContentLength(), Long.valueOf(\n            \"unic₪de\".getBytes(Charsets.UTF_8).length));\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/json/BaseItemParserTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.json;\n\n\npublic abstract class BaseItemParserTest<T> extends BaseParserTest<T, T> {\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/json/BaseIterableWithMarkerParserTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.json;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.collect.IterableWithMarker;\n\nimport com.google.common.collect.ImmutableSortedSet;\n\npublic abstract class BaseIterableWithMarkerParserTest<T> extends BaseParserTest<IterableWithMarker<T>, T> {\n\n   public void compare(IterableWithMarker<T> expects, IterableWithMarker<T> response) {\n      assertEquals(ImmutableSortedSet.copyOf(response).toString(), ImmutableSortedSet.copyOf(expects).toString());\n   }\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/json/BaseParserTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.json;\n\nimport static org.jclouds.reflect.Reflection2.method;\nimport static org.testng.Assert.assertEquals;\n\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\nimport jakarta.inject.Qualifier;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.config.SaxParserModule;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.reflect.Invocation;\nimport org.jclouds.rest.internal.TransformerForRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Throwables;\nimport com.google.common.collect.ImmutableList;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\npublic abstract class BaseParserTest<T, G> {\n\n   @Retention(value = RetentionPolicy.RUNTIME)\n   @Target(value = { ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })\n   @Qualifier\n   public @interface Nested {\n\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   protected Function<HttpResponse, T> parser(Injector i) {\n      try {\n         return (Function<HttpResponse, T>) i\n               .createChildInjector(new SaxParserModule())\n               .getInstance(TransformerForRequest.class)\n               .getTransformerForMethod(Invocation.create(method(getClass(), \"expected\"), ImmutableList.of()), i);\n      } catch (Exception e) {\n         throw Throwables.propagate(e);\n      }\n   }\n\n   @Test\n   public void test() {\n      T expects = expected();\n      Function<HttpResponse, T> parser = parser(injector());\n      T response = parser.apply(HttpResponse.builder().statusCode(200).message(\"ok\").payload(payload()).build());\n      compare(expects, response);\n   }\n\n   protected Payload payload() {\n      return Payloads.newInputStreamPayload(getClass().getResourceAsStream(resource()));\n   }\n\n   public void compare(T expects, T response) {\n      assertEquals(response.toString(), expects.toString());\n   }\n\n   protected Injector injector() {\n      return Guice.createInjector(new GsonModule() {\n         protected void configure() {\n            bind(DateAdapter.class).to(Iso8601DateAdapter.class);\n            super.configure();\n         }\n      });\n\n   }\n\n   protected String resource() {\n      throw new IllegalStateException(\"please define resource such as \\\"/testaddresses.json\\\"\");\n   }\n\n   public abstract T expected();\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/json/BaseSetParserTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.json;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Set;\n\nimport com.google.common.collect.ImmutableSortedSet;\n\npublic abstract class BaseSetParserTest<T> extends BaseParserTest<Set<T>, T> {\n\n   public void compare(Set<T> expects, Set<T> response) {\n      assertEquals(ImmutableSortedSet.copyOf(response).toString(), ImmutableSortedSet.copyOf(expects).toString());\n   }\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/json/GsonExperimentsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.json;\n\nimport static com.google.common.base.Objects.equal;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.io.StringReader;\nimport java.lang.reflect.ParameterizedType;\nimport java.lang.reflect.Type;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.Lists;\nimport com.google.common.util.concurrent.Atomics;\nimport com.google.gson.Gson;\nimport com.google.gson.GsonBuilder;\nimport com.google.gson.JsonArray;\nimport com.google.gson.JsonParser;\nimport com.google.gson.TypeAdapter;\nimport com.google.gson.TypeAdapterFactory;\nimport com.google.gson.reflect.TypeToken;\nimport com.google.gson.stream.JsonReader;\nimport com.google.gson.stream.JsonToken;\nimport com.google.gson.stream.JsonWriter;\nimport com.google.inject.TypeLiteral;\n\n@Test\npublic class GsonExperimentsTest {\n   public static final String json = \"['hello',5,{name:'GREETINGS',source:'guest'}]\";\n\n   static class Event {\n      private String name;\n      private String source;\n\n      private Event(String name, String source) {\n         this.name = name;\n         this.source = source;\n      }\n\n      @Override\n      public String toString() {\n         return String.format(\"(name=%s, source=%s)\", name, source);\n      }\n   }\n\n   private Gson gson;\n   private String json2;\n\n   @BeforeTest\n   void setupSource() {\n      gson = new Gson();\n      Collection<Object> collection = Lists.newArrayList();\n      collection.add(\"hello\");\n      collection.add(5);\n      collection.add(new Event(\"GREETINGS\", \"guest\"));\n      json2 = gson.toJson(collection);\n      assertEquals(json2, \"[\\\"hello\\\",5,{\\\"name\\\":\\\"GREETINGS\\\",\\\"source\\\":\\\"guest\\\"}]\");\n   }\n\n   public class OptionalTypeAdapterFactory implements TypeAdapterFactory {\n      @SuppressWarnings(\"unchecked\")\n      public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {\n         Type type = typeToken.getType();\n         if (typeToken.getRawType() != Optional.class || !(type instanceof ParameterizedType)) {\n            return null;\n         }\n\n         Type elementType = ((ParameterizedType) type).getActualTypeArguments()[0];\n         TypeAdapter<?> elementAdapter = gson.getAdapter(TypeToken.get(elementType));\n         return (TypeAdapter<T>) newOptionalAdapter(elementAdapter);\n      }\n\n      private <E> TypeAdapter<Optional<E>> newOptionalAdapter(final TypeAdapter<E> elementAdapter) {\n         return new TypeAdapter<Optional<E>>() {\n            public void write(JsonWriter out, Optional<E> value) throws IOException {\n               if (value == null || !value.isPresent()) {\n                  out.nullValue();\n                  return;\n               }\n               elementAdapter.write(out, value.get());\n            }\n\n            public Optional<E> read(JsonReader in) throws IOException {\n               if (in.peek() == JsonToken.NULL) {\n                  in.nextNull();\n                  return Optional.absent();\n               }\n               return Optional.of(elementAdapter.read(in));\n            }\n         };\n      }\n   }\n\n   static class OptionalType {\n      Optional<String> present = Optional.of(\"hello\");\n      Optional<String> notPresent = Optional.absent();\n\n      @Override\n      public boolean equals(Object object) {\n         if (this == object) {\n            return true;\n         }\n         if (object instanceof OptionalType) {\n            final OptionalType other = OptionalType.class.cast(object);\n            return equal(present, other.present) && equal(notPresent, other.notPresent);\n         } else {\n            return false;\n         }\n      }\n\n      @Override\n      public int hashCode() {\n         return Objects.hashCode(present, notPresent);\n      }\n   }\n\n   public void testPersistOptional() {\n      Gson gson = new GsonBuilder().registerTypeAdapterFactory(new OptionalTypeAdapterFactory()).create();\n      String json = gson.toJson(new OptionalType());\n      assertEquals(json, \"{\\\"present\\\":\\\"hello\\\"}\");\n      assertEquals(gson.fromJson(json, OptionalType.class), new OptionalType());\n   }\n\n   // inspired by\n   // http://code.google.com/p/google-gson/source/browse/trunk/extras/src/main/java/com/google/gson/extras/examples/rawcollections/RawCollectionsExample.java\n   public void testRawCollectionsWithParser() {\n      JsonParser parser = new JsonParser();\n      JsonArray array = parser.parse(json).getAsJsonArray();\n      String message = gson.fromJson(array.get(0), String.class);\n      int number = gson.fromJson(array.get(1), int.class);\n      Event event = gson.fromJson(array.get(2), Event.class);\n      assertEquals(message, \"hello\");\n      assertEquals(number, 5);\n      assertEquals(event.toString(), new Event(\"GREETINGS\", \"guest\").toString());\n   }\n\n   private final String nested = \"{ \\\"count\\\":1 ,\\\"event\\\" : [  {name:'GREETINGS',source:'guest'} ] }\";\n   private final String nestedFurther = \"{ \\\"listaccountsresponse\\\" : { \\\"count\\\":1 ,\\\"event\\\" : [  {name:'GREETINGS',source:'guest'} ] } }\";\n\n   // inspired by http://sites.google.com/site/gson/streaming\n   public void testParseNestedElements() throws IOException {\n      JsonReader reader = new JsonReader(new StringReader(nested));\n      List<Event> val = parseThingFromReaderOrNull(\"event\", reader, new TypeLiteral<List<Event>>() {\n      }.getType());\n      assertEquals(val.toString(), \"[(name=GREETINGS, source=guest)]\");\n   }\n\n   public void testParseNestedFurtherElements() throws IOException {\n      JsonReader reader = new JsonReader(new StringReader(nestedFurther));\n      List<Event> val = parseThingFromReaderOrNull(\"event\", reader, new TypeLiteral<List<Event>>() {\n      }.getType());\n      assertEquals(val.toString(), \"[(name=GREETINGS, source=guest)]\");\n   }\n\n   protected <T> T parseThingFromReaderOrNull(String toFind, JsonReader reader, Type type) throws IOException {\n      AtomicReference<String> name = Atomics.newReference();\n      JsonToken token = reader.peek();\n      for (; token != JsonToken.END_DOCUMENT && nnn(toFind, reader, token, name); token = skipAndPeek(token, reader)) {\n      }\n      T val = gson.<T> fromJson(reader, type);\n      reader.close();\n      return val;\n   }\n\n   protected boolean nnn(String toFind, JsonReader reader, JsonToken token, AtomicReference<String> name)\n         throws IOException {\n      if (token == JsonToken.NAME) {\n         String name2 = reader.nextName();\n         if (toFind.equals(name2)) {\n            name.set(name2);\n            return false;\n         }\n      }\n      return true;\n\n   }\n\n   public JsonToken skipAndPeek(JsonToken token, JsonReader reader) throws IOException {\n      switch (token) {\n      case BEGIN_ARRAY:\n         reader.beginArray();\n         break;\n      case END_ARRAY:\n         reader.endArray();\n         break;\n      case BEGIN_OBJECT:\n         reader.beginObject();\n         break;\n      case END_OBJECT:\n         reader.endObject();\n         break;\n      case NAME:\n         // NOTE that we have already advanced on NAME in the eval block;\n         break;\n      case STRING:\n         reader.nextString();\n         break;\n      case NUMBER:\n         reader.nextString();\n         break;\n      case BOOLEAN:\n         reader.nextBoolean();\n         break;\n      case NULL:\n         reader.nextNull();\n         break;\n      case END_DOCUMENT:\n         break;\n      }\n      return reader.peek();\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/json/JsonTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.json;\n\nimport static com.google.common.io.BaseEncoding.base16;\nimport static com.google.common.primitives.Bytes.asList;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.IOException;\nimport java.nio.charset.Charset;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.json.config.GsonModule.DefaultExclusionStrategy;\nimport org.testng.annotations.Test;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.gson.FieldAttributes;\nimport com.google.gson.Gson;\nimport com.google.gson.TypeAdapter;\nimport com.google.gson.TypeAdapterFactory;\nimport com.google.gson.reflect.TypeToken;\nimport com.google.gson.stream.JsonReader;\nimport com.google.gson.stream.JsonWriter;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Provides;\nimport com.google.inject.TypeLiteral;\n\n@Test\npublic class JsonTest {\n   private Json json = Guice.createInjector(new GsonModule()).getInstance(Json.class);\n\n   private static class ObjectNoDefaultConstructor {\n      private final String stringValue;\n      private final int intValue;\n\n      public ObjectNoDefaultConstructor(String stringValue, int intValue) {\n         this.stringValue = stringValue;\n         this.intValue = intValue;\n      }\n\n      @Override\n      public int hashCode() {\n         final int prime = 31;\n         int result = 1;\n         result = prime * result + intValue;\n         result = prime * result + ((stringValue == null) ? 0 : stringValue.hashCode());\n         return result;\n      }\n\n      @Override\n      public boolean equals(Object obj) {\n         if (this == obj)\n            return true;\n         if (obj == null)\n            return false;\n         if (getClass() != obj.getClass())\n            return false;\n         ObjectNoDefaultConstructor other = (ObjectNoDefaultConstructor) obj;\n         if (intValue != other.intValue)\n            return false;\n         if (stringValue == null) {\n            if (other.stringValue != null)\n               return false;\n         } else if (!stringValue.equals(other.stringValue))\n            return false;\n         return true;\n      }\n   }\n\n   public void testObjectNoDefaultConstructor() {\n      ObjectNoDefaultConstructor obj = new ObjectNoDefaultConstructor(\"foo\", 1);\n      assertEquals(json.toJson(obj), \"{\\\"stringValue\\\":\\\"foo\\\",\\\"intValue\\\":1}\");\n      ObjectNoDefaultConstructor obj2 = json.fromJson(json.toJson(obj), ObjectNoDefaultConstructor.class);\n      assertEquals(obj2, obj);\n      assertEquals(json.toJson(obj2), json.toJson(obj));\n   }\n\n   static class ExcludeStringValue implements DefaultExclusionStrategy {\n      public boolean shouldSkipClass(Class<?> clazz) {\n        return false;\n      }\n\n      public boolean shouldSkipField(FieldAttributes f) {\n        return f.getName().equals(\"stringValue\");\n      }\n   }\n\n   public void testExcluder() {\n      Json excluder = Guice.createInjector(new GsonModule(), new AbstractModule() {\n         protected void configure() {\n            bind(DefaultExclusionStrategy.class).to(ExcludeStringValue.class);\n         }\n      }).getInstance(Json.class);\n      ObjectNoDefaultConstructor obj = new ObjectNoDefaultConstructor(\"foo\", 1);\n      assertEquals(excluder.toJson(obj), \"{\\\"intValue\\\":1}\");\n   }\n\n   private static class EnumInside {\n      private static enum Test {\n         FOO, BAR;\n      }\n\n      private Test enumValue;\n   }\n\n   private static class ByteList {\n      List<Byte> checksum;\n   }\n\n   public void testByteList() {\n      ByteList bl = new ByteList();\n      bl.checksum = asList(base16().lowerCase().decode(\"1dda05ed139664f1f89b9dec482b77c0\"));\n      assertEquals(json.toJson(bl), \"{\\\"checksum\\\":\\\"1dda05ed139664f1f89b9dec482b77c0\\\"}\");\n      assertEquals(json.fromJson(json.toJson(bl), ByteList.class).checksum, bl.checksum);\n   }\n\n   public void testPropertiesSerializesDefaults() {\n      Properties props = new Properties();\n      props.put(\"string\", \"string\");\n      props.put(\"number\", \"1\");\n      props.put(\"boolean\", \"true\");\n      assertEquals(json.toJson(props), \"{\\\"string\\\":\\\"string\\\",\\\"boolean\\\":\\\"true\\\",\\\"number\\\":\\\"1\\\"}\");\n      Properties props3 = new Properties(props);\n      assertEquals(json.toJson(props3), \"{\\\"string\\\":\\\"string\\\",\\\"boolean\\\":\\\"true\\\",\\\"number\\\":\\\"1\\\"}\");\n      Properties props2 = json.fromJson(json.toJson(props), Properties.class);\n      assertEquals(props2, props);\n      assertEquals(json.toJson(props2), json.toJson(props));\n   }\n\n   public void testMapStringObjectWithAllValidValuesOneDeep() {\n      Map<String, Object> map = ImmutableMap.<String, Object>builder()\n         .put(\"string\", \"string\")\n         .put(\"map\", ImmutableMap.of(\"key\", \"value\"))\n         .put(\"list\", ImmutableList.of(\"key\", \"value\"))\n         .put(\"boolean\", true)\n         .put(\"number\", 1.0)\n         .build();\n      assertEquals(json.toJson(map),\n               \"{\\\"string\\\":\\\"string\\\",\\\"map\\\":{\\\"key\\\":\\\"value\\\"},\\\"list\\\":[\\\"key\\\",\\\"value\\\"],\\\"boolean\\\":true,\\\"number\\\":1.0}\");\n      Map<String, Object> map2 = json.fromJson(json.toJson(map), new TypeLiteral<Map<String, Object>>() {\n      }.getType());\n      assertEquals(map2, map);\n      assertEquals(json.toJson(map2), json.toJson(map));\n   }\n\n   public void testMapStringObjectWithNumericalKeysConvertToStrings() {\n      Map<String, Object> map = ImmutableMap.<String, Object> of(\"map\", ImmutableMap.of(1, \"value\"));\n      assertEquals(json.toJson(map), \"{\\\"map\\\":{\\\"1\\\":\\\"value\\\"}}\");\n      Map<String, Object> map2 = json.fromJson(json.toJson(map), new TypeLiteral<Map<String, Object>>() {\n      }.getType());\n      // note conversion.. ensures valid\n      assertEquals(map2, ImmutableMap.<String, Object> of(\"map\", ImmutableMap.of(\"1\", \"value\")));\n      assertEquals(json.toJson(map2), json.toJson(map));\n   }\n\n   public void testMapStringObjectWithBooleanKeysConvertToStrings() {\n      Map<String, Object> map = ImmutableMap.<String, Object> of(\"map\", ImmutableMap.of(true, \"value\"));\n      assertEquals(json.toJson(map), \"{\\\"map\\\":{\\\"true\\\":\\\"value\\\"}}\");\n      Map<String, Object> map2 = json.fromJson(json.toJson(map), new TypeLiteral<Map<String, Object>>() {\n      }.getType());\n      // note conversion.. ensures valid\n      assertEquals(map2, ImmutableMap.<String, Object> of(\"map\", ImmutableMap.of(\"true\", \"value\")));\n      assertEquals(json.toJson(map2), json.toJson(map));\n   }\n\n   public void testDeserializeEnum() {\n      assertEquals(json.fromJson(\"{enumValue : \\\"FOO\\\"}\", EnumInside.class).enumValue, EnumInside.Test.FOO);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testDeserializeEnumWhenBadValue() {\n      assertEquals(json.fromJson(\"{enumValue : \\\"s\\\"}\", EnumInside.class).enumValue, EnumInside.Test.FOO);\n   }\n\n   private static class EnumInsideWithParser {\n      public static enum Test {\n         FOO, BAR, UNRECOGNIZED;\n\n         @SuppressWarnings(\"unused\")\n         public static Test fromValue(String state) {\n            try {\n               return valueOf(state);\n            } catch (IllegalArgumentException e) {\n               return UNRECOGNIZED;\n            }\n         }\n      }\n\n      private Test enumValue;\n   }\n\n   public void testDeserializeEnumWithParser() {\n      assertEquals(json.fromJson(\"{enumValue : \\\"FOO\\\"}\", EnumInsideWithParser.class).enumValue,\n               EnumInsideWithParser.Test.FOO);\n   }\n\n   public void testDeserializeEnumWithParserAndBadValue() {\n      assertEquals(json.fromJson(\"{enumValue : \\\"sd\\\"}\", EnumInsideWithParser.class).enumValue,\n               EnumInsideWithParser.Test.UNRECOGNIZED);\n   }\n\n   @AutoValue\n   abstract static class SerializedNamesType {\n      abstract String id();\n\n      @Nullable abstract Map<String, String> volumes();\n\n      @SerializedNames({ \"Id\", \"Volumes\" })\n      private static SerializedNamesType create(String id, Map<String, String> volumes) {\n         return new AutoValue_JsonTest_SerializedNamesType(id, volumes);\n      }\n   }\n\n   public void autoValueSerializedNames() {\n      Json json = Guice.createInjector(new GsonModule()).getInstance(Json.class);\n\n      SerializedNamesType resource = SerializedNamesType.create(\"1234\", Collections.<String, String>emptyMap());\n      String spinalJson = \"{\\\"Id\\\":\\\"1234\\\",\\\"Volumes\\\":{}}\";\n\n      assertEquals(json.toJson(resource), spinalJson);\n      assertEquals(json.fromJson(spinalJson, SerializedNamesType.class), resource);\n   }\n\n   public void autoValueWithBuilder() {\n      Json json = Guice.createInjector(new GsonModule()).getInstance(Json.class);\n\n      SerializedNamesWithBuilder resource = SerializedNamesWithBuilder.builder().id(\"1234\").number(2).build();\n      String spinalJson = \"{\\\"custom_id_name\\\":\\\"1234\\\",\\\"number\\\":2}\";\n\n      assertEquals(json.toJson(resource), spinalJson);\n      assertEquals(json.fromJson(spinalJson, SerializedNamesWithBuilder.class), resource);\n   }\n\n   public void autoValueWithBuilderNested() {\n      Json json = Guice.createInjector(new GsonModule()).getInstance(Json.class);\n\n      SerializedNamesNestedWithBuilder resource = SerializedNamesNestedWithBuilder.builder().id(\"1234\")\n            .snwb(ImmutableList.of(SerializedNamesWithBuilder.builder().id(\"5678\").number(1).build())).build();\n\n      String spinalJson = \"{\\\"nested_id_name\\\":\\\"1234\\\",\\\"serialized_name_with_builder\\\":[{\\\"custom_id_name\\\":\\\"5678\\\",\\\"number\\\":1}]}\";\n\n      assertEquals(json.toJson(resource), spinalJson);\n      assertEquals(json.fromJson(spinalJson, SerializedNamesNestedWithBuilder.class), resource);\n   }\n\n   public void autoValueWithBuilderMissingNested() {\n      Json json = Guice.createInjector(new GsonModule()).getInstance(Json.class);\n\n      SerializedNamesNestedWithBuilder resource = SerializedNamesNestedWithBuilder.builder().id(\"1234\")\n            .snwb(ImmutableList.<SerializedNamesWithBuilder>of()).build();\n\n      String spinalJson = \"{\\\"nested_id_name\\\":\\\"1234\\\",\\\"serialized_name_with_builder\\\":[]}\";\n\n      assertEquals(json.toJson(resource), spinalJson);\n      assertEquals(json.fromJson(spinalJson, SerializedNamesNestedWithBuilder.class), resource);\n   }\n\n   @AutoValue\n   abstract static class SerializedNamesNestedWithBuilder {\n      public abstract String getId();\n      @Nullable\n      public abstract List<SerializedNamesWithBuilder> getSnwb();\n\n      public static Builder builder() {\n         return new AutoValue_JsonTest_SerializedNamesNestedWithBuilder.Builder();\n      }\n      public abstract Builder toBuilder();\n\n      @AutoValue.Builder\n      public interface Builder {\n         Builder id(String id);\n         Builder snwb(List<SerializedNamesWithBuilder> snwb);\n         SerializedNamesNestedWithBuilder build();\n      }\n\n      @SerializedNames({\"nested_id_name\", \"serialized_name_with_builder\"})\n      private static SerializedNamesNestedWithBuilder create(String id, List<SerializedNamesWithBuilder> snwb) {\n         return builder().id(id).snwb(snwb).build();\n      }\n   }\n\n   @AutoValue\n   abstract static class SerializedNamesWithBuilder {\n      public abstract String getId();\n      public abstract int getNumber();\n\n      public static Builder builder() {\n         return new AutoValue_JsonTest_SerializedNamesWithBuilder.Builder();\n      }\n      public abstract Builder toBuilder();\n\n      @AutoValue.Builder\n      public interface Builder {\n         Builder id(String id);\n         Builder number(int number);\n         SerializedNamesWithBuilder build();\n      }\n\n      @SerializedNames({\"custom_id_name\", \"number\"})\n      private static SerializedNamesWithBuilder create(String id, int number) {\n         return builder().id(id).number(number).build();\n      }\n   }\n\n   @AutoValue\n   abstract static class SerializedNamesTooFewType {\n      abstract String id();\n\n      @Nullable abstract Map<String, String> volumes();\n\n      @SerializedNames(\"Id\") // TODO: check things like this with error-prone, not runtime!\n      private static SerializedNamesTooFewType create(String id, Map<String, String> volumes) {\n         return new AutoValue_JsonTest_SerializedNamesTooFewType(id, volumes);\n      }\n   }\n\n   /** Common problem. Someone adds a parameter, but forgets to add it to the names list. */\n   @Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = \"Incorrect number .*\")\n   public void autoValueSerializedNames_tooFew() {\n      Json json = Guice.createInjector(new GsonModule()).getInstance(Json.class);\n      json.toJson(SerializedNamesTooFewType.create(\"1234\", null));\n   }\n\n   public void autoValueSerializedNames_nullValueInJson() {\n      Json json = Guice.createInjector(new GsonModule()).getInstance(Json.class);\n\n      assertEquals(json.fromJson(\"{\\\"Id\\\":\\\"1234\\\",\\\"Volumes\\\":null}\", SerializedNamesType.class),\n            SerializedNamesType.create(\"1234\", null));\n   }\n\n   public void nonUtf8InputStream() {\n      Json json = Guice.createInjector(new GsonModule()).getInstance(Json.class);\n      String jsonValue = \"{\\\"stringValue\\\":\\\"1234\\\",\\\"intValue\\\":1234}\";\n      Charset ebcdicCharset = Charset.forName(\"IBM-1047\");\n      ByteArrayInputStream inputStream = new ByteArrayInputStream(jsonValue.getBytes(ebcdicCharset));\n      assertEquals(json.fromJson(inputStream, ebcdicCharset, ObjectNoDefaultConstructor.class),\n              new ObjectNoDefaultConstructor(\"1234\", 1234));\n   }\n\n   @AutoValue\n   abstract static class NestedSerializedNamesType {\n      abstract SerializedNamesType item();\n      abstract List<SerializedNamesType> items();\n\n      @SerializedNames({ \"Item\", \"Items\" })\n      private static NestedSerializedNamesType create(SerializedNamesType item, List<SerializedNamesType> items) {\n         return new AutoValue_JsonTest_NestedSerializedNamesType(item, items);\n      }\n   }\n\n   private final NestedSerializedNamesType nested = NestedSerializedNamesType\n         .create(SerializedNamesType.create(\"1234\", Collections.<String, String>emptyMap()),\n               Arrays.asList(SerializedNamesType.create(\"5678\", ImmutableMap.of(\"Foo\", \"Bar\"))));\n\n   public void autoValueSerializedNames_nestedType() {\n      Json json = Guice.createInjector(new GsonModule()).getInstance(Json.class);\n\n      String spinalJson = \"{\\\"Item\\\":{\\\"Id\\\":\\\"1234\\\",\\\"Volumes\\\":{}},\\\"Items\\\":[{\\\"Id\\\":\\\"5678\\\",\\\"Volumes\\\":{\\\"Foo\\\":\\\"Bar\\\"}}]}\";\n\n      assertEquals(json.toJson(nested), spinalJson);\n      assertEquals(json.fromJson(spinalJson, NestedSerializedNamesType.class), nested);\n   }\n\n   public void autoValueSerializedNames_overriddenTypeAdapterFactory() {\n      Json json = Guice.createInjector(new GsonModule(), new AbstractModule() {\n         @Override protected void configure() {\n         }\n\n         @Provides public Set<TypeAdapterFactory> typeAdapterFactories() {\n            return ImmutableSet.<TypeAdapterFactory>of(new NestedSerializedNamesTypeAdapterFactory());\n         }\n      }).getInstance(Json.class);\n\n      assertEquals(json.toJson(nested), \"{\\\"id\\\":\\\"1234\\\",\\\"count\\\":1}\");\n      assertEquals(json.fromJson(\"{\\\"id\\\":\\\"1234\\\",\\\"count\\\":1}\", NestedSerializedNamesType.class), nested);\n   }\n\n   private class NestedSerializedNamesTypeAdapterFactory extends TypeAdapter<NestedSerializedNamesType>\n         implements TypeAdapterFactory {\n\n      @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {\n         if (!(NestedSerializedNamesType.class.isAssignableFrom(typeToken.getRawType()))) {\n            return null;\n         }\n         return (TypeAdapter<T>) this;\n      }\n\n      @Override public void write(JsonWriter out, NestedSerializedNamesType value) throws IOException {\n         out.beginObject();\n         out.name(\"id\").value(value.item().id());\n         out.name(\"count\").value(value.items().size());\n         out.endObject();\n      }\n\n      @Override public NestedSerializedNamesType read(JsonReader in) throws IOException {\n         in.beginObject();\n         in.nextName();\n         in.nextString();\n         in.nextName();\n         in.nextInt();\n         in.endObject();\n         return nested;\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/json/internal/DeserializationConstructorAndReflectiveTypeAdapterFactoryTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.json.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotSame;\nimport static org.testng.Assert.assertNull;\n\nimport java.beans.ConstructorProperties;\nimport java.io.IOException;\nimport java.lang.reflect.Type;\nimport java.util.List;\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\n\nimport org.jclouds.json.SerializedNames;\nimport com.google.gson.ReflectionAccessFilter;\nimport com.google.gson.internal.ConstructorConstructor;\nimport com.google.gson.internal.Excluder;\nimport org.jclouds.json.internal.NamingStrategies.AnnotationConstructorNamingStrategy;\nimport org.jclouds.json.internal.NamingStrategies.AnnotationOrNameFieldNamingStrategy;\nimport org.jclouds.json.internal.NamingStrategies.ExtractNamed;\nimport org.jclouds.json.internal.NamingStrategies.ExtractSerializedName;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Lists;\nimport com.google.common.collect.Maps;\nimport com.google.gson.FieldNamingStrategy;\nimport com.google.gson.Gson;\nimport com.google.gson.GsonBuilder;\nimport com.google.gson.InstanceCreator;\nimport com.google.gson.TypeAdapter;\nimport com.google.gson.reflect.TypeToken;\n\n@Test(testName = \"DeserializationConstructorTypeAdapterFactoryTest\")\n@SuppressWarnings(\"unused\")\npublic final class DeserializationConstructorAndReflectiveTypeAdapterFactoryTest {\n\n   Gson gson = new Gson();\n\n   DeserializationConstructorAndReflectiveTypeAdapterFactory parameterizedCtorFactory = parameterizedCtorFactory();\n\n   static DeserializationConstructorAndReflectiveTypeAdapterFactory parameterizedCtorFactory() {\n      FieldNamingStrategy serializationPolicy = new AnnotationOrNameFieldNamingStrategy(ImmutableSet.of(\n            new ExtractSerializedName(), new ExtractNamed()));\n      AnnotationConstructorNamingStrategy deserializationPolicy = new AnnotationConstructorNamingStrategy(\n            ImmutableSet.of(ConstructorProperties.class, SerializedNames.class, Inject.class),\n            ImmutableSet.of(new ExtractNamed()));\n\n      return new DeserializationConstructorAndReflectiveTypeAdapterFactory(\n            new ConstructorConstructor(ImmutableMap.<Type, InstanceCreator<?>>of(), /*useJdkUnsafe=*/ false, ImmutableList.<ReflectionAccessFilter>of()),\n            serializationPolicy, Excluder.DEFAULT, deserializationPolicy);\n   }\n\n   public void testNullWhenPrimitive() {\n      assertNull(parameterizedCtorFactory.create(gson, TypeToken.get(int.class)));\n   }\n\n   private static class DefaultConstructor {\n      int foo;\n      int bar;\n\n      private DefaultConstructor() {\n      }\n   }\n\n   public void testRejectsIfNoConstuctorMarked() throws IOException {\n      TypeAdapter<DefaultConstructor> adapter = parameterizedCtorFactory.create(gson,\n            TypeToken.get(DefaultConstructor.class));\n      assertNull(adapter);\n   }\n\n   private static class WithDeserializationConstructorButWithoutSerializedName {\n      final int foo;\n\n      @Inject\n      WithDeserializationConstructorButWithoutSerializedName(int foo) {\n         this.foo = foo;\n      }\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = \".* parameter 0 failed to be named by AnnotationBasedNamingStrategy requiring one of jakarta.inject.Named\")\n   public void testSerializedNameRequiredOnAllParameters() {\n      parameterizedCtorFactory\n            .create(gson, TypeToken.get(WithDeserializationConstructorButWithoutSerializedName.class));\n   }\n\n   private static class DuplicateSerializedNames {\n      final int foo;\n      final int bar;\n\n      @Inject\n      DuplicateSerializedNames(@Named(\"foo\") int foo, @Named(\"foo\") int bar) {\n         this.foo = foo;\n         this.bar = bar;\n      }\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class,\n         expectedExceptionsMessageRegExp = \"Multiple entries with same key: foo.*\")\n   public void testNoDuplicateSerializedNamesRequiredOnAllParameters() {\n      parameterizedCtorFactory.create(gson, TypeToken.get(DuplicateSerializedNames.class));\n   }\n\n   private static class ValidatedConstructor {\n      final int foo;\n      final int bar;\n\n      @Inject\n      ValidatedConstructor(@Named(\"foo\") Optional<Integer> foo, @Named(\"bar\") int bar) {\n         if (!foo.isPresent())\n            throw new IllegalArgumentException(\"absent!\");\n         this.foo = foo.get();\n         this.bar = bar;\n      }\n\n      @Override\n      public boolean equals(Object obj) {\n         ValidatedConstructor other = ValidatedConstructor.class.cast(obj);\n         return other != null && Objects.equal(foo, other.foo) && Objects.equal(bar, other.bar);\n      }\n\n      @Override\n      public int hashCode() {\n         return Objects.hashCode(foo, bar);\n      }\n   }\n\n    @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = \"absent!\")\n    public void testValidatedConstructor() throws IOException {\n        Gson gson = new GsonBuilder().registerTypeAdapterFactory(parameterizedCtorFactory)\n                .registerTypeAdapterFactory(new OptionalTypeAdapterFactory()).create();\n\n        assertEquals(new ValidatedConstructor(Optional.of(0), 1),\n                gson.fromJson(\"{\\\"foo\\\":0,\\\"bar\\\":1}\", ValidatedConstructor.class));\n        gson.fromJson(\"{\\\"bar\\\":1}\", ValidatedConstructor.class);\n    }\n\n   private abstract static class ValueTypeWithFactory {\n      abstract List<String> foo();\n      abstract Map<String, String> bar();\n\n      @SerializedNames({ \"foo\", \"bar\" })\n      static ValueTypeWithFactory create(List<String> foo, Map<String, String> bar) {\n         return new GenericParamsCopiedIn(foo, bar);\n      }\n   }\n\n   private static class GenericParamsCopiedIn extends ValueTypeWithFactory {\n      final List<String> foo;\n      final Map<String, String> bar;\n\n      @Inject GenericParamsCopiedIn(@Named(\"foo\") List<String> foo, @Named(\"bar\") Map<String, String> bar) {\n         this.foo = Lists.newArrayList(foo);\n         this.bar = Maps.newHashMap(bar);\n      }\n\n      @Override List<String> foo() {\n         return foo;\n      }\n\n      @Override Map<String, String> bar() {\n         return bar;\n      }\n   }\n\n   public void testBuilderOnAbstractValueType() throws IOException {\n      TypeAdapter<ValueTypeWithFactory> adapter = parameterizedCtorFactory.create(gson,\n            TypeToken.get(ValueTypeWithFactory.class));\n      List<String> inputFoo = Lists.newArrayList();\n      inputFoo.add(\"one\");\n      Map<String, String> inputBar = Maps.newHashMap();\n      inputBar.put(\"2\", \"two\");\n\n      ValueTypeWithFactory toTest = adapter.fromJson(\"{ \\\"foo\\\":[\\\"one\\\"], \\\"bar\\\":{ \\\"2\\\":\\\"two\\\"}}\");\n      assertEquals(inputFoo, toTest.foo());\n      assertNotSame(inputFoo, toTest.foo());\n      assertEquals(inputBar, toTest.bar());\n   }\n\n   private abstract static class ValueTypeWithFactoryMissingSerializedNames {\n      @SerializedNames({ \"foo\" })\n      static ValueTypeWithFactoryMissingSerializedNames create(List<String> foo, Map<String, String> bar) {\n         return null;\n      }\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class,\n         expectedExceptionsMessageRegExp = \"Incorrect count of names on annotation of .*\")\n   public void testSerializedNamesMustHaveCorrectCountOfNames() {\n      parameterizedCtorFactory.create(gson, TypeToken.get(ValueTypeWithFactoryMissingSerializedNames.class));\n   }\n\n   public void testGenericParamsCopiedIn() throws IOException {\n      TypeAdapter<GenericParamsCopiedIn> adapter = parameterizedCtorFactory.create(gson,\n            TypeToken.get(GenericParamsCopiedIn.class));\n      List<String> inputFoo = Lists.newArrayList();\n      inputFoo.add(\"one\");\n      Map<String, String> inputBar = Maps.newHashMap();\n      inputBar.put(\"2\", \"two\");\n\n      GenericParamsCopiedIn toTest = adapter.fromJson(\"{ \\\"foo\\\":[\\\"one\\\"], \\\"bar\\\":{ \\\"2\\\":\\\"two\\\"}}\");\n      assertEquals(inputFoo, toTest.foo);\n      assertNotSame(inputFoo, toTest.foo);\n      assertEquals(inputBar, toTest.bar);\n   }\n\n   private static class RenamedFields {\n      final int foo;\n      @Named(\"_bar\")\n      final int bar;\n\n      @ConstructorProperties({ \"foo\", \"_bar\" })\n      RenamedFields(int foo, int bar) {\n         if (foo < 0)\n            throw new IllegalArgumentException(\"negative!\");\n         this.foo = foo;\n         this.bar = bar;\n      }\n      \n      @Override\n      public boolean equals(Object obj) {\n         RenamedFields other = RenamedFields.class.cast(obj);\n         return other != null && Objects.equal(foo, other.foo) && Objects.equal(bar, other.bar);\n      }\n\n      @Override\n      public int hashCode() {\n         return Objects.hashCode(foo, bar);\n      }\n   }\n\n   public void testCanOverrideDefault() throws IOException {\n      Gson gson = new GsonBuilder().registerTypeAdapterFactory(parameterizedCtorFactory).create();\n\n      assertEquals(new RenamedFields(0, 1), gson.fromJson(\"{\\\"foo\\\":0,\\\"_bar\\\":1}\", RenamedFields.class));\n      assertEquals(gson.toJson(new RenamedFields(0, 1)), \"{\\\"foo\\\":0,\\\"_bar\\\":1}\");\n   }\n\n   public void testRenamedFields() throws IOException {\n      TypeAdapter<RenamedFields> adapter = parameterizedCtorFactory.create(gson, TypeToken.get(RenamedFields.class));\n      assertEquals(new RenamedFields(0, 1), adapter.fromJson(\"{\\\"foo\\\":0,\\\"_bar\\\":1}\"));\n      assertEquals(adapter.toJson(new RenamedFields(0, 1)), \"{\\\"foo\\\":0,\\\"_bar\\\":1}\");\n   }\n\n   private static class ComposedObjects {\n      final ValidatedConstructor x;\n      final ValidatedConstructor y;\n\n      @ConstructorProperties({ \"x\", \"y\" })\n      ComposedObjects(ValidatedConstructor x, ValidatedConstructor y) {\n         this.x = checkNotNull(x);\n         this.y = checkNotNull(y);\n      }\n\n      @Override\n      public boolean equals(Object obj) {\n         ComposedObjects other = ComposedObjects.class.cast(obj);\n         return other != null && Objects.equal(x, other.x) && Objects.equal(y, other.y);\n      }\n\n      @Override\n      public int hashCode() {\n         return Objects.hashCode(x, y);\n      }\n   }\n\n   public void checkSimpleComposedObject() throws IOException {\n      ValidatedConstructor x = new ValidatedConstructor(Optional.of(0), 1);\n      ValidatedConstructor y = new ValidatedConstructor(Optional.of(1), 2);\n      TypeAdapter<ComposedObjects> adapter = parameterizedCtorFactory\n            .create(gson, TypeToken.get(ComposedObjects.class));\n      assertEquals(new ComposedObjects(x, y),\n            adapter.fromJson(\"{\\\"x\\\":{\\\"foo\\\":0,\\\"bar\\\":1},\\\"y\\\":{\\\"foo\\\":1,\\\"bar\\\":2}}\"));\n   }\n\n   public void testEmptyObjectIsNull() throws IOException {\n      TypeAdapter<ComposedObjects> adapter = parameterizedCtorFactory\n            .create(gson, TypeToken.get(ComposedObjects.class));\n      assertNull(adapter.fromJson(\"{}\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testPartialObjectStillThrows() throws IOException {\n      TypeAdapter<ComposedObjects> adapter = parameterizedCtorFactory\n            .create(gson, TypeToken.get(ComposedObjects.class));\n      assertNull(adapter.fromJson(\"{\\\"x\\\":{\\\"foo\\\":0,\\\"bar\\\":1}}\"));\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/json/internal/NamingStrategiesTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.json.internal;\n\nimport static org.jclouds.reflect.Reflection2.typeToken;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.fail;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\n\nimport org.jclouds.json.internal.NamingStrategies.AnnotationConstructorNamingStrategy;\nimport org.jclouds.json.internal.NamingStrategies.AnnotationFieldNamingStrategy;\nimport org.jclouds.json.internal.NamingStrategies.AnnotationOrNameFieldNamingStrategy;\nimport org.jclouds.json.internal.NamingStrategies.ExtractNamed;\nimport org.jclouds.json.internal.NamingStrategies.ExtractSerializedName;\nimport org.jclouds.json.internal.NamingStrategies.NameExtractor;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.reflect.Invokable;\nimport com.google.gson.FieldNamingStrategy;\nimport com.google.gson.annotations.SerializedName;\n\n@Test(testName = \"NamingStrategiesTest\")\npublic final class NamingStrategiesTest {\n\n   private static class SimpleTest {\n      @SerializedName(\"aardvark\")\n      private String a;\n      @SuppressWarnings(\"unused\")\n      private String b;\n      @Named(\"cat\")\n      private String c;\n      @Named(\"dog\")\n      private String d;\n      \n      @ConstructorProperties({\"aardvark\", \"bat\", \"coyote\", \"dog\"})\n      private SimpleTest(String aa, String bb, String cc, String dd) {\n      }\n      \n      @Inject\n      private SimpleTest(@Named(\"aa\") String aa, @Named(\"bb\") String bb, @Named(\"cc\") String cc, @Named(\"dd\") String dd, boolean nothing) {         \n      }\n   }\n\n   public void testExtractSerializedName() throws Exception {\n      NameExtractor<SerializedName> extractor = new ExtractSerializedName();\n      assertEquals(extractor.extractName(SimpleTest.class.getDeclaredField(\"a\").getAnnotation(SerializedName.class)),\n            \"aardvark\");\n      try {\n         extractor.extractName(SimpleTest.class.getDeclaredField(\"b\").getAnnotation(SerializedName.class));\n         fail();\n      } catch (NullPointerException e) {\n      }\n      try {\n         extractor.extractName(SimpleTest.class.getDeclaredField(\"c\").getAnnotation(SerializedName.class));\n         fail();\n      } catch (NullPointerException e) {\n      }\n      try {\n         extractor.extractName(SimpleTest.class.getDeclaredField(\"d\").getAnnotation(SerializedName.class));\n         fail();\n      } catch (NullPointerException e) {\n      }\n   }\n\n   public void testExtractNamed() throws Exception {\n      NameExtractor<Named> extractor = new ExtractNamed();\n      try {\n         extractor.extractName(SimpleTest.class.getDeclaredField(\"a\").getAnnotation(Named.class));\n      } catch (NullPointerException e) {\n      }\n      try {\n         extractor.extractName(SimpleTest.class.getDeclaredField(\"b\").getAnnotation(Named.class));\n         fail();\n      } catch (NullPointerException e) {\n      }\n      assertEquals(extractor.extractName(SimpleTest.class.getDeclaredField(\"c\").getAnnotation(Named.class)),\n            \"cat\");\n      assertEquals(extractor.extractName(SimpleTest.class.getDeclaredField(\"d\").getAnnotation(Named.class)),\n            \"dog\");\n   }\n   \n   public void testAnnotationFieldNamingStrategy() throws Exception {\n      FieldNamingStrategy strategy = new AnnotationFieldNamingStrategy(ImmutableSet.of(new ExtractNamed()));\n\n      assertEquals(strategy.translateName(SimpleTest.class.getDeclaredField(\"a\")), null);\n      assertEquals(strategy.translateName(SimpleTest.class.getDeclaredField(\"b\")), null);\n      assertEquals(strategy.translateName(SimpleTest.class.getDeclaredField(\"c\")), \"cat\");\n      assertEquals(strategy.translateName(SimpleTest.class.getDeclaredField(\"d\")), \"dog\");\n   }\n\n   public void testAnnotationOrNameFieldNamingStrategy() throws Exception {\n      FieldNamingStrategy strategy = new AnnotationOrNameFieldNamingStrategy(ImmutableSet.of(new ExtractNamed()));\n\n      assertEquals(strategy.translateName(SimpleTest.class.getDeclaredField(\"a\")), \"a\");\n      assertEquals(strategy.translateName(SimpleTest.class.getDeclaredField(\"b\")), \"b\");\n      assertEquals(strategy.translateName(SimpleTest.class.getDeclaredField(\"c\")), \"cat\");\n      assertEquals(strategy.translateName(SimpleTest.class.getDeclaredField(\"d\")), \"dog\");\n   }\n\n   public void testAnnotationConstructorFieldNamingStrategyCPAndNamed() throws Exception {\n      AnnotationConstructorNamingStrategy strategy = new AnnotationConstructorNamingStrategy(\n            ImmutableSet.of(ConstructorProperties.class), ImmutableSet.of(new ExtractNamed()));\n\n      Invokable<SimpleTest, SimpleTest> constructor = strategy.getDeserializer(typeToken(SimpleTest.class));\n      assertNotNull(constructor);\n      assertEquals(constructor.getParameters().size(), 4);\n\n      assertEquals(strategy.translateName(constructor, 0), \"aardvark\");\n      assertEquals(strategy.translateName(constructor, 1), \"bat\");\n      assertEquals(strategy.translateName(constructor, 2), \"coyote\");\n   }\n\n   public void testAnnotationConstructorFieldNamingStrategyCP() throws Exception {\n      AnnotationConstructorNamingStrategy strategy = new AnnotationConstructorNamingStrategy(\n            ImmutableSet.of(ConstructorProperties.class), ImmutableSet.<NameExtractor<?>>of());\n\n      Invokable<SimpleTest, SimpleTest> constructor = strategy.getDeserializer(typeToken(SimpleTest.class));\n      assertNotNull(constructor);\n      assertEquals(constructor.getParameters().size(), 4);\n\n      assertEquals(strategy.translateName(constructor, 0), \"aardvark\");\n      assertEquals(strategy.translateName(constructor, 1), \"bat\");\n      assertEquals(strategy.translateName(constructor, 2), \"coyote\");\n      assertEquals(strategy.translateName(constructor, 3), \"dog\");\n   }\n   \n   public void testAnnotationConstructorFieldNamingStrategyInject() throws Exception {\n      AnnotationConstructorNamingStrategy strategy = new AnnotationConstructorNamingStrategy(\n            ImmutableSet.of(Inject.class), ImmutableSet.of(new ExtractNamed()));\n\n      Invokable<SimpleTest, SimpleTest> constructor = strategy.getDeserializer(typeToken(SimpleTest.class));\n      assertNotNull(constructor);\n      assertEquals(constructor.getParameters().size(), 5);\n\n      assertEquals(strategy.translateName(constructor, 0), \"aa\");\n      assertEquals(strategy.translateName(constructor, 1), \"bb\");\n      assertEquals(strategy.translateName(constructor, 2), \"cc\");\n      assertEquals(strategy.translateName(constructor, 3), \"dd\");\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/json/internal/NullFilteringTypeAdapterFactoriesTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.json.internal;\n\nimport com.google.common.base.Objects;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Multimap;\nimport com.google.common.reflect.TypeToken;\nimport com.google.gson.Gson;\nimport com.google.gson.GsonBuilder;\nimport org.jclouds.json.internal.NullFilteringTypeAdapterFactories.CollectionTypeAdapterFactory;\nimport org.jclouds.json.internal.NullFilteringTypeAdapterFactories.FluentIterableTypeAdapterFactory;\nimport org.jclouds.json.internal.NullFilteringTypeAdapterFactories.ImmutableListTypeAdapterFactory;\nimport org.jclouds.json.internal.NullFilteringTypeAdapterFactories.ImmutableSetTypeAdapterFactory;\nimport org.jclouds.json.internal.NullFilteringTypeAdapterFactories.IterableTypeAdapterFactory;\nimport org.jclouds.json.internal.NullFilteringTypeAdapterFactories.ListTypeAdapterFactory;\nimport org.jclouds.json.internal.NullFilteringTypeAdapterFactories.MapTypeAdapterFactory;\nimport org.jclouds.json.internal.NullFilteringTypeAdapterFactories.MultimapTypeAdapterFactory;\nimport org.jclouds.json.internal.NullFilteringTypeAdapterFactories.SetTypeAdapterFactory;\nimport org.jclouds.json.internal.NullFilteringTypeAdapterFactories.ImmutableMapTypeAdapterFactory;\nimport org.testng.annotations.Test;\n\nimport java.lang.reflect.Type;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport static com.google.common.base.Objects.equal;\nimport static org.testng.Assert.assertEquals;\n\n@Test(testName = \"NullFilteringTypeAdapterFactoriesTest\")\npublic class NullFilteringTypeAdapterFactoriesTest {\n   private static class Resource {\n      private final String id;\n      private final String name;\n\n      private Resource(String id, String name) {\n         this.id = id;\n         this.name = name;\n      }\n\n      @Override\n      public int hashCode() {\n         return Objects.hashCode(id, name);\n      }\n\n      @Override\n      public boolean equals(Object obj) {\n         if (this == obj)\n            return true;\n         if (obj == null || getClass() != obj.getClass())\n            return false;\n         Resource that = Resource.class.cast(obj);\n         return equal(this.id, that.id) && equal(this.name, that.name);\n      }\n   }\n\n   private Gson fluentIterable = new GsonBuilder().registerTypeAdapterFactory(new FluentIterableTypeAdapterFactory())\n         .create();\n   private Type fluentIterableType = new TypeToken<FluentIterable<String>>() {\n      private static final long serialVersionUID = 1L;\n   }.getType();\n   private Type fluentIterableResourceType = new TypeToken<FluentIterable<Resource>>() {\n      private static final long serialVersionUID = 1L;\n   }.getType();\n\n   public void testFluentIterable() {\n      FluentIterable<String> noNulls = fluentIterable.fromJson(\"[\\\"value\\\",\\\"a test string!\\\"]\", fluentIterableType);\n      assertEquals(noNulls.toList(), ImmutableList.of(\"value\", \"a test string!\"));\n      FluentIterable<String> withNull = fluentIterable.fromJson(\"[null,\\\"a test string!\\\"]\", fluentIterableType);\n      assertEquals(withNull.toList(), ImmutableList.of(\"a test string!\"));\n      FluentIterable<String> withDupes = fluentIterable.fromJson(\"[\\\"value\\\",\\\"value\\\"]\", fluentIterableType);\n      assertEquals(withDupes.toList(), ImmutableList.of(\"value\", \"value\"));\n      FluentIterable<Resource> resources = fluentIterable.fromJson(\n            \"[{\\\"id\\\":\\\"i-foo\\\",\\\"name\\\":\\\"foo\\\"},{\\\"id\\\":\\\"i-bar\\\",\\\"name\\\":\\\"bar\\\"}]\", fluentIterableResourceType);\n      assertEquals(resources.toList(), ImmutableList.of(new Resource(\"i-foo\", \"foo\"), new Resource(\"i-bar\", \"bar\")));\n   }\n\n   private Gson collection = new GsonBuilder().registerTypeAdapterFactory(new CollectionTypeAdapterFactory()).create();\n   private Type collectionType = new TypeToken<Collection<String>>() {\n      private static final long serialVersionUID = 1L;\n   }.getType();\n   private Type collectionResourceType = new TypeToken<Collection<Resource>>() {\n      private static final long serialVersionUID = 1L;\n   }.getType();\n\n   public void testCollection() {\n      Collection<String> noNulls = collection.fromJson(\"[\\\"value\\\",\\\"a test string!\\\"]\", collectionType);\n      assertEquals(noNulls, ImmutableList.of(\"value\", \"a test string!\"));\n      Collection<String> withNull = collection.fromJson(\"[null,\\\"a test string!\\\"]\", collectionType);\n      assertEquals(withNull, ImmutableList.of(\"a test string!\"));\n      Collection<String> withDupes = collection.fromJson(\"[\\\"value\\\",\\\"value\\\"]\", collectionType);\n      assertEquals(withDupes, ImmutableList.of(\"value\", \"value\"));\n      Collection<Resource> resources = collection.fromJson(\n            \"[{\\\"id\\\":\\\"i-foo\\\",\\\"name\\\":\\\"foo\\\"},{\\\"id\\\":\\\"i-bar\\\",\\\"name\\\":\\\"bar\\\"}]\", collectionResourceType);\n      assertEquals(resources, ImmutableList.of(new Resource(\"i-foo\", \"foo\"), new Resource(\"i-bar\", \"bar\")));\n   }\n\n   private Gson iterable = new GsonBuilder().registerTypeAdapterFactory(new IterableTypeAdapterFactory()).create();\n   private Type iterableType = new TypeToken<Iterable<String>>() {\n      private static final long serialVersionUID = 1L;\n   }.getType();\n   private Type iterableResourceType = new TypeToken<Iterable<Resource>>() {\n      private static final long serialVersionUID = 1L;\n   }.getType();\n\n   public void testIterable() {\n      Iterable<String> noNulls = iterable.fromJson(\"[\\\"value\\\",\\\"a test string!\\\"]\", iterableType);\n      assertEquals(noNulls, ImmutableList.of(\"value\", \"a test string!\"));\n      Iterable<String> withNull = iterable.fromJson(\"[null,\\\"a test string!\\\"]\", iterableType);\n      assertEquals(withNull, ImmutableList.of(\"a test string!\"));\n      Iterable<String> withDupes = iterable.fromJson(\"[\\\"value\\\",\\\"value\\\"]\", iterableType);\n      assertEquals(withDupes, ImmutableList.of(\"value\", \"value\"));\n      Iterable<Resource> resources = iterable.fromJson(\n            \"[{\\\"id\\\":\\\"i-foo\\\",\\\"name\\\":\\\"foo\\\"},{\\\"id\\\":\\\"i-bar\\\",\\\"name\\\":\\\"bar\\\"}]\", iterableResourceType);\n      assertEquals(resources, ImmutableList.of(new Resource(\"i-foo\", \"foo\"), new Resource(\"i-bar\", \"bar\")));\n   }\n\n   private Type iterableWildcardExtendsResourceType = new TypeToken<Iterable<? extends Resource>>() {\n      private static final long serialVersionUID = 1L;\n   }.getType();\n\n   public void testWildcardExtends() {\n      Iterable<? extends Resource> wildcardExtendsResources = iterable.fromJson(\n            \"[{\\\"id\\\":\\\"i-foo\\\",\\\"name\\\":\\\"foo\\\"},{\\\"id\\\":\\\"i-bar\\\",\\\"name\\\":\\\"bar\\\"}]\",\n            iterableWildcardExtendsResourceType);\n      assertEquals(wildcardExtendsResources,\n            ImmutableList.of(new Resource(\"i-foo\", \"foo\"), new Resource(\"i-bar\", \"bar\")));\n   }\n\n   private Gson list = new GsonBuilder().registerTypeAdapterFactory(new ListTypeAdapterFactory()).create();\n   private Type listType = new TypeToken<List<String>>() {\n      private static final long serialVersionUID = 1L;\n   }.getType();\n   private Type listResourceType = new TypeToken<List<Resource>>() {\n      private static final long serialVersionUID = 1L;\n   }.getType();\n\n   public void testList() {\n      Iterable<String> noNulls = list.fromJson(\"[\\\"value\\\",\\\"a test string!\\\"]\", listType);\n      assertEquals(noNulls, ImmutableList.of(\"value\", \"a test string!\"));\n      Iterable<String> withNull = list.fromJson(\"[null,\\\"a test string!\\\"]\", listType);\n      assertEquals(withNull, ImmutableList.of(\"a test string!\"));\n      Iterable<String> withDupes = list.fromJson(\"[\\\"value\\\",\\\"value\\\"]\", listType);\n      assertEquals(withDupes, ImmutableList.of(\"value\", \"value\"));\n      Iterable<Resource> resources = list.fromJson(\n            \"[{\\\"id\\\":\\\"i-foo\\\",\\\"name\\\":\\\"foo\\\"},{\\\"id\\\":\\\"i-bar\\\",\\\"name\\\":\\\"bar\\\"}]\", listResourceType);\n      assertEquals(resources, ImmutableList.of(new Resource(\"i-foo\", \"foo\"), new Resource(\"i-bar\", \"bar\")));\n   }\n\n   private Gson immutableList = new GsonBuilder().registerTypeAdapterFactory(new ImmutableListTypeAdapterFactory()).create();\n   private Type immutableListType = new TypeToken<ImmutableList<String>>() {\n      private static final long serialVersionUID = 1L;\n   }.getType();\n   private Type immutableListResourceType = new TypeToken<ImmutableList<Resource>>() {\n      private static final long serialVersionUID = 1L;\n   }.getType();\n\n   public void testImmutableList() {\n      Iterable<String> noNulls = immutableList.fromJson(\"[\\\"value\\\",\\\"a test string!\\\"]\", immutableListType);\n      assertEquals(noNulls, ImmutableList.of(\"value\", \"a test string!\"));\n      Iterable<String> withNull = immutableList.fromJson(\"[null,\\\"a test string!\\\"]\", immutableListType);\n      assertEquals(withNull, ImmutableList.of(\"a test string!\"));\n      Iterable<String> withDupes = immutableList.fromJson(\"[\\\"value\\\",\\\"value\\\"]\", immutableListType);\n      assertEquals(withDupes, ImmutableList.of(\"value\", \"value\"));\n      Iterable<Resource> resources = immutableList.fromJson(\n            \"[{\\\"id\\\":\\\"i-foo\\\",\\\"name\\\":\\\"foo\\\"},{\\\"id\\\":\\\"i-bar\\\",\\\"name\\\":\\\"bar\\\"}]\", immutableListResourceType);\n      assertEquals(resources, ImmutableList.of(new Resource(\"i-foo\", \"foo\"), new Resource(\"i-bar\", \"bar\")));\n   }\n\n   private Gson set = new GsonBuilder().registerTypeAdapterFactory(new SetTypeAdapterFactory()).create();\n   private Type setType = new TypeToken<Set<String>>() {\n      private static final long serialVersionUID = 1L;\n   }.getType();\n   private Type setResourceType = new TypeToken<Set<Resource>>() {\n      private static final long serialVersionUID = 1L;\n   }.getType();\n\n   public void testSet() {\n      Set<String> noNulls = set.fromJson(\"[\\\"value\\\",\\\"a test string!\\\"]\", setType);\n      assertEquals(noNulls, ImmutableSet.of(\"value\", \"a test string!\"));\n      Set<String> withNull = set.fromJson(\"[null,\\\"a test string!\\\"]\", setType);\n      assertEquals(withNull, ImmutableSet.of(\"a test string!\"));\n      Set<String> withDupes = set.fromJson(\"[\\\"value\\\",\\\"value\\\"]\", setType);\n      assertEquals(withDupes, ImmutableSet.of(\"value\"));\n      Set<Resource> resources = set.fromJson(\n            \"[{\\\"id\\\":\\\"i-foo\\\",\\\"name\\\":\\\"foo\\\"},{\\\"id\\\":\\\"i-bar\\\",\\\"name\\\":\\\"bar\\\"}]\", setResourceType);\n      assertEquals(resources, ImmutableSet.of(new Resource(\"i-foo\", \"foo\"), new Resource(\"i-bar\", \"bar\")));\n   }\n\n   private Gson immutableSet = new GsonBuilder().registerTypeAdapterFactory(new ImmutableSetTypeAdapterFactory()).create();\n   private Type immutableSetType = new TypeToken<ImmutableSet<String>>() {\n      private static final long serialVersionUID = 1L;\n   }.getType();\n   private Type immutableSetResourceType = new TypeToken<ImmutableSet<Resource>>() {\n      private static final long serialVersionUID = 1L;\n   }.getType();\n\n   public void testImmutableSet() {\n      Iterable<String> noNulls = immutableSet.fromJson(\"[\\\"value\\\",\\\"a test string!\\\"]\", immutableSetType);\n      assertEquals(noNulls, ImmutableSet.of(\"value\", \"a test string!\"));\n      Iterable<String> withNull = immutableSet.fromJson(\"[null,\\\"a test string!\\\"]\", immutableSetType);\n      assertEquals(withNull, ImmutableSet.of(\"a test string!\"));\n      Iterable<String> withDupes = immutableSet.fromJson(\"[\\\"value\\\",\\\"value\\\"]\", immutableSetType);\n      assertEquals(withDupes, ImmutableSet.of(\"value\", \"value\"));\n      Iterable<Resource> resources = immutableSet.fromJson(\n            \"[{\\\"id\\\":\\\"i-foo\\\",\\\"name\\\":\\\"foo\\\"},{\\\"id\\\":\\\"i-bar\\\",\\\"name\\\":\\\"bar\\\"}]\", immutableSetResourceType);\n      assertEquals(resources, ImmutableSet.of(new Resource(\"i-foo\", \"foo\"), new Resource(\"i-bar\", \"bar\")));\n   }\n\n   private Gson immutableMap = new GsonBuilder().registerTypeAdapterFactory(new ImmutableMapTypeAdapterFactory()).create();\n   private Type immutableMapType = new TypeToken<ImmutableMap<String, String>>() {\n      private static final long serialVersionUID = 1L;\n   }.getType();\n   private Type immutableMapResourceType = new TypeToken<ImmutableMap<String, Resource>>() {\n      private static final long serialVersionUID = 1L;\n   }.getType();\n\n   public void testImmutableMap() {\n      ImmutableMap<String, String> noNulls = immutableMap.fromJson(\"{\\\"value\\\":\\\"a test string!\\\"}\", immutableMapType);\n      assertEquals(noNulls, ImmutableMap.of(\"value\", \"a test string!\"));\n      ImmutableMap<String, String> withNull = immutableMap.fromJson(\"{\\\"key\\\":null}\", immutableMapType);\n      assertEquals(withNull, ImmutableMap.of());\n      ImmutableMap<String, String> withEmpty = map.fromJson(\"{\\\"value\\\":\\\"\\\"}\", mapType);\n      assertEquals(withEmpty, ImmutableMap.of(\"value\", \"\"));\n      ImmutableMap<String, Resource> resources = immutableMap.fromJson(\n            \"{\\\"key1\\\":{\\\"id\\\":\\\"i-foo\\\",\\\"name\\\":\\\"foo\\\"},\\\"key2\\\":{\\\"id\\\":\\\"i-bar\\\",\\\"name\\\":\\\"bar\\\"}}\", immutableMapResourceType);\n      assertEquals(resources, ImmutableMap.of(\"key1\", new Resource(\"i-foo\", \"foo\"), \"key2\",  new Resource(\"i-bar\", \"bar\")));\n   }\n\n   private Gson map = new GsonBuilder().registerTypeAdapterFactory(new MapTypeAdapterFactory()).create();\n   private Type mapType = new TypeToken<Map<String, String>>() {\n      private static final long serialVersionUID = 1L;\n   }.getType();\n   private Type mapResourceType = new TypeToken<Map<String, Resource>>() {\n      private static final long serialVersionUID = 1L;\n   }.getType();\n\n   public void testMap() {\n      Map<String, String> noNulls = map.fromJson(\"{\\\"value\\\":\\\"a test string!\\\"}\", mapType);\n      assertEquals(noNulls, ImmutableMap.of(\"value\", \"a test string!\"));\n      Map<String, String> withNull = map.fromJson(\"{\\\"value\\\":null}\", mapType);\n      assertEquals(withNull, ImmutableMap.of());\n      Map<String, String> withEmpty = map.fromJson(\"{\\\"value\\\":\\\"\\\"}\", mapType);\n      assertEquals(withEmpty, ImmutableMap.of(\"value\", \"\"));\n      Map<String, Resource> resources = map.fromJson(\n            \"{\\\"i-foo\\\":{\\\"id\\\":\\\"i-foo\\\",\\\"name\\\":\\\"foo\\\"},\\\"i-bar\\\":{\\\"id\\\":\\\"i-bar\\\",\\\"name\\\":\\\"bar\\\"}}\",\n            mapResourceType);\n      assertEquals(resources,\n            ImmutableMap.of(\"i-foo\", new Resource(\"i-foo\", \"foo\"), \"i-bar\", new Resource(\"i-bar\", \"bar\")));\n   }\n\n   private Gson multimap = new GsonBuilder().registerTypeAdapterFactory(new MultimapTypeAdapterFactory()).create();\n   private Type multimapType = new TypeToken<Multimap<String, String>>() {\n      private static final long serialVersionUID = 1L;\n   }.getType();\n   private Type multimapResourceType = new TypeToken<Multimap<String, Resource>>() {\n      private static final long serialVersionUID = 1L;\n   }.getType();\n\n   public void testMultimap() {\n      Multimap<String, String> noNulls = multimap.fromJson(\"{\\\"value\\\":[\\\"a test string!\\\"]}\", multimapType);\n      assertEquals(noNulls, ImmutableMultimap.of(\"value\", \"a test string!\"));\n      Multimap<String, String> withNull = multimap.fromJson(\"{\\\"value\\\":[null]}\", multimapType);\n      assertEquals(withNull, ImmutableMultimap.of());\n      Multimap<String, String> withEmpty = multimap.fromJson(\"{\\\"value\\\":[\\\"\\\"]}\", multimapType);\n      assertEquals(withEmpty, ImmutableMultimap.of(\"value\", \"\"));\n      Multimap<String, String> withDupes = multimap.fromJson(\"{\\\"key\\\":[\\\"value\\\",\\\"value\\\"]}\", multimapType);\n      assertEquals(withDupes.get(\"key\"), ImmutableList.of(\"value\", \"value\"));\n      Multimap<String, Resource> resources = multimap.fromJson(\n            \"{\\\"i-foo\\\":[{\\\"id\\\":\\\"i-foo\\\",\\\"name\\\":\\\"foo\\\"}],\\\"i-bar\\\":[{\\\"id\\\":\\\"i-bar\\\",\\\"name\\\":\\\"bar\\\"}]}\",\n            multimapResourceType);\n      assertEquals(resources,\n            ImmutableMultimap.of(\"i-foo\", new Resource(\"i-foo\", \"foo\"), \"i-bar\", new Resource(\"i-bar\", \"bar\")));\n      Multimap<String, Resource> resourceDupes = multimap.fromJson(\n            \"{\\\"i-foo\\\":[{\\\"id\\\":\\\"i-foo\\\",\\\"name\\\":\\\"foo\\\"},{\\\"id\\\":\\\"i-bar\\\",\\\"name\\\":\\\"bar\\\"}]}\",\n            multimapResourceType);\n      assertEquals(resourceDupes.get(\"i-foo\"),\n            ImmutableList.of(new Resource(\"i-foo\", \"foo\"), new Resource(\"i-bar\", \"bar\")));\n   }\n\n   private Gson listInMap = new GsonBuilder().registerTypeAdapterFactory(new MapTypeAdapterFactory())\n         .registerTypeAdapterFactory(new ListTypeAdapterFactory()).create();\n   private Type listInMapType = new TypeToken<Map<String, List<Map<String, String>>>>() {\n      private static final long serialVersionUID = 1L;\n   }.getType();\n\n   public void testListInMap() {\n      Map<String, List<Map<String, String>>> notNull = listInMap\n            .fromJson(\"{\\\"value\\\":[{\\\"x\\\":\\\"y\\\",\\\"a\\\":\\\"b\\\"},{\\\"u\\\":\\\"v\\\"}]}\", listInMapType);\n      assertEquals(notNull,\n            ImmutableMap.of(\"value\", ImmutableList.of(ImmutableMap.of(\"x\", \"y\", \"a\", \"b\"), ImmutableMap.of(\"u\", \"v\"))));\n      Map<String, List<Map<String, String>>> innerMapValueNull = listInMap\n            .fromJson(\"{\\\"value\\\":[{\\\"x\\\":\\\"y\\\",\\\"a\\\":null},{\\\"u\\\":\\\"v\\\"}]}\", listInMapType);\n      assertEquals(innerMapValueNull,\n            ImmutableMap.of(\"value\", ImmutableList.of(ImmutableMap.of(\"x\", \"y\"), ImmutableMap.of(\"u\", \"v\"))));\n      Map<String, List<Map<String, String>>> withNullInList = listInMap.fromJson(\"{\\\"value\\\":[null]}\", listInMapType);\n      assertEquals(withNullInList, ImmutableMap.of(\"value\", ImmutableList.of()));\n      Map<String, List<Map<String, String>>> withNullAsList = listInMap.fromJson(\"{\\\"parent\\\":null}\", listInMapType);\n      assertEquals(withNullAsList, ImmutableMap.of());\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/json/internal/NullHackJsonLiteralAdapterTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.json.internal;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.domain.JsonBall.JSON_BOOLEAN_PATTERN;\nimport static org.jclouds.domain.JsonBall.JSON_NUMBER_PATTERN;\nimport static org.jclouds.domain.JsonBall.JSON_STRING_PATTERN;\nimport static org.testng.Assert.assertEquals;\n\nimport java.lang.reflect.Type;\nimport java.util.Map;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.gson.Gson;\nimport com.google.gson.GsonBuilder;\nimport com.google.gson.reflect.TypeToken;\n\n/**\n * Shows how we currently allow users to specify json literal types.\n * \n * @see <a href=\"http://code.google.com/p/google-gson/issues/detail?id=326\"/>\n */\n@Test(testName = \"NullHackJsonLiteralAdapterTest\")\npublic class NullHackJsonLiteralAdapterTest {\n\n   /**\n    * User supplied type that holds json literally. Ex. number as {@code 8}, boolean as {@code true}\n    * , string as {@code \"value\"}, object as {@code , list {@code []}.\n    */\n   static class RawJson implements CharSequence {\n\n      private final String value;\n\n      public RawJson(double value) {\n         this.value = value + \"\";\n      }\n\n      public RawJson(boolean value) {\n         this.value = value + \"\";\n      }\n\n      public RawJson(String value) {\n         this.value = quoteStringIfNotNumberOrBoolean(checkNotNull(value, \"value\"));\n      }\n\n      @Override\n      public int hashCode() {\n         return Objects.hashCode(value);\n      }\n\n      @Override\n      public boolean equals(Object that) {\n         if (that == null)\n            return false;\n         return Objects.equal(this.toString(), that.toString());\n      }\n\n      @Override\n      public String toString() {\n         return value;\n      }\n\n      static String quoteStringIfNotNumberOrBoolean(String in) {\n         if (JSON_STRING_PATTERN.matcher(in).find() && !JSON_NUMBER_PATTERN.matcher(in).find()\n               && !JSON_BOOLEAN_PATTERN.matcher(in).find()) {\n            return \"\\\"\" + in + \"\\\"\";\n         }\n         return in;\n      }\n\n      @Override\n      public char charAt(int index) {\n         return value.charAt(index);\n      }\n\n      @Override\n      public int length() {\n         return value.length();\n      }\n\n      @Override\n      public CharSequence subSequence(int start, int end) {\n         return value.subSequence(start, end);\n      }\n\n   }\n\n   /**\n    * writes or reads the literal directly\n    */\n   public static class RawJsonAdapter extends NullHackJsonLiteralAdapter<RawJson> {\n\n      @Override\n      protected RawJson createJsonLiteralFromRawJson(String json) {\n         return new RawJson(json);\n      }\n  }\n\n   // register the type adapter so that gson can serialize/deserialize to it\n   private Gson gsonAdapter = new GsonBuilder().registerTypeAdapter(RawJson.class, new RawJsonAdapter()).create();\n\n   Type type = new TypeToken<Map<String, RawJson>>() {\n   }.getType();\n\n   public void testObject() {\n      String json = \"{\\\"tomcat6\\\":{\\\"ssl_port\\\":8433}}\";\n\n      Map<String, RawJson> map = ImmutableMap.<String, RawJson> of(\"tomcat6\", new RawJson(\"{\\\"ssl_port\\\":8433}\"));\n\n      assertEquals(gsonAdapter.toJson(map), json);\n      assertEquals(gsonAdapter.fromJson(json, type), map);\n   }\n\n   public void testList() {\n      String json = \"{\\\"list\\\":[8431,8433]}\";\n\n      Map<String, RawJson> map = ImmutableMap.<String, RawJson> of(\"list\", new RawJson(\"[8431,8433]\"));\n\n      assertEquals(gsonAdapter.toJson(map), json);\n      assertEquals(gsonAdapter.fromJson(json, type), map);\n   }\n\n   public void testString() {\n      String json = \"{\\\"name\\\":\\\"fooy\\\"}\";\n\n      Map<String, RawJson> map = ImmutableMap.<String, RawJson> of(\"name\", new RawJson(\"fooy\"));\n\n      assertEquals(gsonAdapter.toJson(map), json);\n      assertEquals(gsonAdapter.fromJson(json, type), map);\n   }\n\n   public void testNumber() {\n      String json = \"{\\\"number\\\":1.0}\";\n\n      Map<String, RawJson> map = ImmutableMap.<String, RawJson> of(\"number\", new RawJson(1.0));\n\n      assertEquals(gsonAdapter.toJson(map), json);\n      assertEquals(gsonAdapter.fromJson(json, type), map);\n   }\n\n   public void testBoolean() {\n      String json = \"{\\\"boolean\\\":false}\";\n\n      Map<String, RawJson> map = ImmutableMap.<String, RawJson> of(\"boolean\", new RawJson(false));\n\n      assertEquals(gsonAdapter.toJson(map), json);\n      assertEquals(gsonAdapter.fromJson(json, type), map);\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/json/internal/OptionalTypeAdapterFactoryTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.json.internal;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.Optional;\nimport com.google.gson.Gson;\nimport com.google.gson.GsonBuilder;\n\n/**\n * Tests to verify and illustrate the behavior of the OptionalTypeAdaptorFactory.\n */\n@Test(testName = \"OptionalTypeAdapterFactoryTest\")\npublic class OptionalTypeAdapterFactoryTest {\n\n   /**\n    * Simple type with an Optional field\n    */\n   static class SimpleBean {\n      private final Optional<String> value;\n      private final String someOtherValue;\n\n      public SimpleBean(Optional<String> value, String someOtherValue) {\n         this.value = value;\n         this.someOtherValue = someOtherValue;\n      }\n\n      // Required to ensure GSON doesn't initialize our Optional to null!\n      @SuppressWarnings(\"unused\")\n      private SimpleBean() {\n         this.value = Optional.absent();\n         this.someOtherValue = null;\n      }\n\n      public Optional<String> getValue() {\n         return value;\n      }\n\n      public String getSomeOtherValue() {\n         return someOtherValue;\n      }\n\n      @Override\n      public boolean equals(Object other) {\n         SimpleBean that = SimpleBean.class.cast(other);\n         return Objects.equal(value, that.value) && Objects.equal(someOtherValue, that.someOtherValue);\n      }\n\n      @Override\n      public int hashCode() {\n         return Objects.hashCode(value, someOtherValue);\n      }\n   }\n\n   // register the type adapter so that gson can serialize/deserialize to it\n   private Gson gsonAdapter = new GsonBuilder().registerTypeAdapterFactory(new OptionalTypeAdapterFactory()).create();\n\n   public void testValuePresent() {\n      String json = \"{\\\"value\\\":\\\"a test string!\\\"}\";\n      SimpleBean expected = new SimpleBean(Optional.of(\"a test string!\"), null);\n\n      SimpleBean actual = gsonAdapter.fromJson(json, SimpleBean.class);\n      \n      assertTrue(actual.value.isPresent());\n      assertEquals(actual.getValue().get(), \"a test string!\");\n      assertNull(actual.getSomeOtherValue());\n      \n      assertEquals(actual, expected);\n      assertEquals(gsonAdapter.toJson(actual), json);\n  }\n\n   public void testValueAbsent() {\n      String json = \"{\\\"someOtherValue\\\":\\\"testvalue\\\"}\";\n      SimpleBean expected = new SimpleBean(Optional.<String>absent(), \"testvalue\");\n\n      SimpleBean actual = gsonAdapter.fromJson(json, SimpleBean.class);\n\n      assertFalse(actual.value.isPresent());\n      assertEquals(actual.getSomeOtherValue(), \"testvalue\");\n\n      assertEquals(actual, expected);\n      assertEquals(gsonAdapter.toJson(actual), json);\n   }\n\n   public void testValueNull() {\n      String json = \"{\\\"value\\\":null}\";\n      SimpleBean expected = new SimpleBean(Optional.<String>absent(), null);\n\n      SimpleBean actual = gsonAdapter.fromJson(json, SimpleBean.class);\n\n      assertFalse(actual.value.isPresent());\n      assertNull(actual.getSomeOtherValue());\n\n      assertEquals(actual, expected);\n      // Note: the field is omitted from serialized form!\n      assertEquals(gsonAdapter.toJson(actual), \"{}\");\n   }\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/lifecycle/config/LifeCycleModuleTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.lifecycle.config;\n\nimport static com.google.inject.name.Names.named;\nimport static org.jclouds.Constants.PROPERTY_USER_THREADS;\n\nimport java.io.Closeable;\nimport java.io.IOException;\nimport java.util.concurrent.CountDownLatch;\n\nimport jakarta.annotation.PostConstruct;\n\nimport static org.easymock.EasyMock.createStrictMock;\nimport static org.easymock.EasyMock.expectLastCall;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport org.jclouds.concurrent.config.ExecutorServiceModule;\nimport org.jclouds.lifecycle.Closer;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Throwables;\nimport com.google.common.util.concurrent.ExecutionList;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport com.google.inject.Key;\n\n@Test\npublic class LifeCycleModuleTest {\n\n   @Test\n   void testBindsExecutor() {\n      Injector i = createInjector();\n      assert i.getInstance(Key.get(ListeningExecutorService.class, named(PROPERTY_USER_THREADS))) != null;\n   }\n\n   private Injector createInjector() {\n      Injector i = Guice.createInjector(new AbstractModule() {\n         protected void configure() {\n            bindConstant().annotatedWith(named(PROPERTY_USER_THREADS)).to(1);\n         }\n      }, new LifeCycleModule(), new ExecutorServiceModule());\n      // TODO: currently have to manually invoke the execution list, as otherwise it may occur\n      // before everything is wired up\n      i.getInstance(ExecutionList.class).execute();\n      return i;\n   }\n\n   @Test\n   void testBindsCloser() {\n      Injector i = createInjector();\n      assert i.getInstance(Closer.class) != null;\n      assert i.getInstance(Closer.class).getState() == Closer.State.AVAILABLE;\n   }\n\n   @Test\n   void testCloserClosesExecutor() throws IOException {\n      Injector i = createInjector();\n      ListeningExecutorService executor = i.getInstance(Key.get(ListeningExecutorService.class,\n            named(PROPERTY_USER_THREADS)));\n      assert !executor.isShutdown();\n      Closer closer = i.getInstance(Closer.class);\n      assert closer.getState() == Closer.State.AVAILABLE;\n      closer.close();\n      assert executor.isShutdown();\n      assert closer.getState() == Closer.State.DONE;\n   }\n\n   @Test\n   void testCloserPreDestroyOrder() throws IOException {\n      Injector i = createInjector();\n      ListeningExecutorService userExecutor = i.getInstance(Key.get(ListeningExecutorService.class,\n            named(PROPERTY_USER_THREADS)));\n      assert !userExecutor.isShutdown();\n      Closer closer = i.getInstance(Closer.class);\n      assert closer.getState() == Closer.State.AVAILABLE;\n      closer.close();\n      assert userExecutor.isShutdown();\n      assert closer.getState() == Closer.State.DONE;\n   }\n\n   public static class PostConstructable {\n      boolean isStarted;\n\n      @PostConstruct\n      public void start() {\n         isStarted = true;\n      }\n   }\n\n   @Test\n   void testPostConstruct() {\n      Injector i = createInjector().createChildInjector(new AbstractModule() {\n         protected void configure() {\n            bind(PostConstructable.class);\n         }\n      });\n      PostConstructable postConstructable = i.getInstance(PostConstructable.class);\n      assert postConstructable.isStarted;\n   }\n\n   @Test\n   void testCloserClosingState() throws InterruptedException {\n      Injector i = createInjector();\n      final Closer closer = i.getInstance(Closer.class);\n\n      final CountDownLatch closeDone = new CountDownLatch(1);\n      final CountDownLatch closeStart = new CountDownLatch(1);\n\n      closer.addToClose(new Closeable() {\n         @Override\n         public void close() throws IOException {\n             try {\n                 closeStart.countDown();\n                 assert closer.getState() == Closer.State.PROCESSING;\n                 closeDone.await();\n             } catch (InterruptedException e) {\n                 throw Throwables.propagate(e);\n             }\n         }\n      });\n\n      Thread thread = new Thread(new Runnable() {\n         @Override\n         public void run() {\n            try {\n               closer.close();\n            } catch (IOException e) {\n               throw Throwables.propagate(e);\n            }\n         }\n      });\n\n      thread.start();\n\n      closeStart.await();\n\n      assert closer.getState() == Closer.State.PROCESSING;\n\n      closeDone.countDown();\n\n      thread.join();\n\n      assert closer.getState() == Closer.State.DONE;\n   }\n\n   @Test\n   void testCloserCallOneClose() throws IOException, InterruptedException {\n      Injector i = createInjector();\n      final Closer closer = i.getInstance(Closer.class);\n\n      Closeable closeable = createStrictMock(Closeable.class);\n\n      closeable.close();\n\n      expectLastCall();\n\n      replay(closeable);\n\n      closer.addToClose(closeable);\n\n      Runnable closeContext = new Runnable() {\n         @Override\n         public void run() {\n            try {\n               closer.close();\n            } catch (IOException e) {\n               throw Throwables.propagate(e);\n            }\n         }\n      };\n\n      Thread thread1 = new Thread(closeContext);\n      Thread thread2 = new Thread(closeContext);\n\n      thread1.start();\n      thread2.start();\n\n      thread1.join();\n      thread2.join();\n\n      verify(closeable);\n\n      assert closer.getState() == Closer.State.DONE;\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/location/config/ProvideIso3166CodesByLocationIdViaPropertiesTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.config;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.location.suppliers.LocationIdToIso3166CodesSupplier;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Maps;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Provides;\n\n@Test(testName = \"ProvideIso3166CodesByLocationIdViaPropertiesTest\")\npublic class ProvideIso3166CodesByLocationIdViaPropertiesTest {\n\n   public void testEmptyWhenNoLocationsBound() {\n      LocationIdToIso3166CodesSupplier fn = createWithValue(ImmutableMap.<String, String> of());\n\n      assertEquals(fn.get(), ImmutableMap.<String, Set<String>> of());\n   }\n\n   public void testEmptyWhenRegionsAndZonesBoundButNoIsoCodes() {\n\n      LocationIdToIso3166CodesSupplier fn = createWithValue(ImmutableMap.<String, String> of(\n            \"jclouds.regions\", \"us-east\", \"jclouds.zones\", \"us-easta\"));\n\n      assertEquals(fn.get(), ImmutableMap.<String, Set<String>> of());\n   }\n\n   public void testIsoCodesWhenRegionsAndZonesBoundWithIsoCodes() {\n\n      LocationIdToIso3166CodesSupplier fn = createWithValue(ImmutableMap.<String, String> of(\n            \"jclouds.regions\", \"us-east\", \"jclouds.region.us-east.iso3166-codes\", \"US\", \"jclouds.zones\", \"us-easta\",\n            \"jclouds.zone.us-easta.iso3166-codes\", \"US-CA\"));\n\n      assertEquals(Maps.transformValues(fn.get(), Suppliers.<Set<String>> supplierFunction()), ImmutableMap\n               .<String, Set<String>> of(\"us-east\", ImmutableSet.of(\"US\"), \"us-easta\", ImmutableSet.of(\"US-CA\")));\n   }\n\n   private LocationIdToIso3166CodesSupplier createWithValue(final ImmutableMap<String, String> value) {\n      LocationIdToIso3166CodesSupplier fn = Guice.createInjector(new AbstractModule() {\n         @Provides\n         Function<Predicate<String>, Map<String, String>> provide() {\n            return new Function<Predicate<String>, Map<String, String>>() {\n\n               @Override\n               public Map<String, String> apply(Predicate<String> input) {\n                  return Maps.filterKeys(value, input);\n               };\n            };\n         }\n\n         @Override\n         protected void configure() {\n         }\n\n      }).getInstance(LocationIdToIso3166CodesSupplier.class);\n      return fn;\n   }\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/location/functions/RegionToEndpointOrProviderIfNullTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.File;\nimport java.net.URI;\nimport java.util.Map;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Tests behavior of {@code RegionToEndpointOrProviderIfNull}\n */\n@Test(groups = \"unit\", testName = \"RegionToEndpointOrProviderIfNullTest\")\npublic class RegionToEndpointOrProviderIfNullTest {\n\n   @Test\n   public void testWhenRegionNameIsSameAsProviderName() throws SecurityException, NoSuchMethodException {\n      RegionToEndpointOrProviderIfNull fn = new RegionToEndpointOrProviderIfNull(\"leader\", Suppliers.ofInstance(URI\n               .create(\"http://leader\")), Suppliers.<Map<String, Supplier<URI>>>ofInstance(ImmutableMap.of(\"leader\", Suppliers.ofInstance(URI.create(\"http://leaderregion\")))));\n      assertEquals(fn.apply(\"leader\"), URI.create(\"http://leaderregion\"));\n   }\n   \n   @Test\n   public void testWhenFindsRegion() throws SecurityException, NoSuchMethodException {\n      RegionToEndpointOrProviderIfNull fn = new RegionToEndpointOrProviderIfNull(\"leader\", Suppliers.ofInstance(URI\n               .create(\"http://leader\")), Suppliers.<Map<String, Supplier<URI>>>ofInstance(ImmutableMap.of(\"1\", Suppliers.ofInstance(URI.create(\"http://1\")))));\n      assertEquals(fn.apply(\"1\"), URI.create(\"http://1\"));\n   }\n\n   public void testNullReturnsProvider() {\n      RegionToEndpointOrProviderIfNull fn = new RegionToEndpointOrProviderIfNull(\"leader\", Suppliers.ofInstance(URI\n               .create(\"http://leader\")), Suppliers.<Map<String, Supplier<URI>>>ofInstance(ImmutableMap.of(\"1\", Suppliers.ofInstance(URI.create(\"http://1\")))));\n      assertEquals(fn.apply(\"leader\"), URI.create(\"http://leader\"));\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testMustBeString() {\n      RegionToEndpointOrProviderIfNull fn = new RegionToEndpointOrProviderIfNull(\"leader\", Suppliers.ofInstance(URI\n               .create(\"http://leader\")), Suppliers.<Map<String, Supplier<URI>>>ofInstance(ImmutableMap.of(\"1\", Suppliers.ofInstance(URI.create(\"http://1\")))));\n      fn.apply(new File(\"foo\"));\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testMustBeInRegionMapIfSpecified() {\n      RegionToEndpointOrProviderIfNull fn = new RegionToEndpointOrProviderIfNull(\"leader\", Suppliers.ofInstance(URI\n               .create(\"http://leader\")), Suppliers.<Map<String, Supplier<URI>>>ofInstance(ImmutableMap.of(\"1\", Suppliers.ofInstance(URI.create(\"http://1\")))));\n      fn.apply(\"2\");\n   }\n\n   public void testOkIfNoRegionMappings() {\n      new RegionToEndpointOrProviderIfNull(\"leader\", Suppliers.ofInstance(URI.create(\"http://leader\")), Suppliers\n               .<Map<String, Supplier<URI>>> ofInstance(ImmutableMap.<String, Supplier<URI>> of()));\n   }\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/location/functions/RegionToEndpointTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\nimport java.util.Map;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Tests behavior of {@code RegionToEndpoint}\n */\n@Test(groups = \"unit\", testName = \"RegionToEndpointTest\")\npublic class RegionToEndpointTest {\n\n   @Test\n   public void testCorrect() {\n      RegionToEndpoint fn = new RegionToEndpoint(Suppliers.<Map<String, Supplier<URI>>> ofInstance(ImmutableMap.of(\"1\",\n               Suppliers.ofInstance(URI.create(\"http://1\")))));\n      assertEquals(fn.apply(\"1\"), URI.create(\"http://1\"));\n   }\n\n   @Test(expectedExceptions = IllegalStateException.class)\n   public void testMustHaveEndpoints() {\n      RegionToEndpoint fn = new RegionToEndpoint(Suppliers.<Map<String, Supplier<URI>>> ofInstance(ImmutableMap\n               .<String, Supplier<URI>> of()));\n      fn.apply(\"1\");\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/location/functions/ZoneToEndpointTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.File;\nimport java.net.URI;\nimport java.util.Map;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Tests behavior of {@code ZoneToEndpoint}\n */\n@Test(groups = \"unit\", testName = \"ZoneToEndpointTest\")\npublic class ZoneToEndpointTest {\n\n   @Test\n   public void testCorrect() {\n      ZoneToEndpoint fn = new ZoneToEndpoint(Suppliers.<Map<String, Supplier<URI>>> ofInstance(ImmutableMap.of(\"1\",\n               Suppliers.ofInstance(URI.create(\"http://1\")))));\n      assertEquals(fn.apply(\"1\"), URI.create(\"http://1\"));\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testMustBeString() {\n      ZoneToEndpoint fn = new ZoneToEndpoint(Suppliers.<Map<String, Supplier<URI>>> ofInstance(ImmutableMap.of(\"1\",\n               Suppliers.ofInstance(URI.create(\"http://1\")))));\n      fn.apply(new File(\"foo\"));\n   }\n\n   @Test(expectedExceptions = IllegalStateException.class)\n   public void testMustHaveEndpoints() {\n      ZoneToEndpoint fn = new ZoneToEndpoint(Suppliers.<Map<String, Supplier<URI>>> ofInstance(ImmutableMap\n               .<String, Supplier<URI>> of()));\n      fn.apply(\"1\");\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testNullIsIllegal() {\n      ZoneToEndpoint fn = new ZoneToEndpoint(Suppliers.<Map<String, Supplier<URI>>> ofInstance(ImmutableMap.of(\"1\",\n               Suppliers.ofInstance(URI.create(\"http://1\")))));\n      fn.apply(null);\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/location/predicates/fromconfig/AnyOrConfiguredRegionIdTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.predicates.fromconfig;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Set;\n\nimport org.jclouds.location.Provider;\nimport org.jclouds.location.predicates.RegionIdFilter;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Sets;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.name.Names;\n\n/**\n * Tests behavior of {@code AnyOrConfiguredRegionId}\n */\n@Test(groups = \"unit\", testName = \"AnyOrConfiguredRegionIdTest\")\npublic class AnyOrConfiguredRegionIdTest {\n\n   @Test\n   public void testWithoutConfigAllIdsMatch() {\n      Set<String> regionIds = ImmutableSet.of(\"us-east-1\", \"eu-west-1\");\n     \n      RegionIdFilter filter = Guice.createInjector(new AbstractModule() {\n\n         @Override\n         protected void configure() {\n            bindConstant().annotatedWith(Provider.class).to(\"aws-ec2\");\n         }\n         \n      }).getInstance(AnyOrConfiguredRegionId.class);\n      assertEquals(Sets.filter(regionIds, filter), ImmutableSet.of(\"us-east-1\", \"eu-west-1\"));\n   }\n   \n   @Test\n   public void testWithConfigOnlyMatchingIds() {\n      Set<String> regionIds = ImmutableSet.of(\"us-east-1\", \"eu-west-1\");\n     \n      RegionIdFilter filter = Guice.createInjector(new AbstractModule() {\n\n         @Override\n         protected void configure() {\n            bindConstant().annotatedWith(Provider.class).to(\"aws-ec2\");\n            bindConstant().annotatedWith(Names.named(\"jclouds.regions\")).to(\"us-east-1,unknown-1\");\n         }\n         \n      }).getInstance(AnyOrConfiguredRegionId.class);\n      \n      assertEquals(Sets.filter(regionIds, filter), ImmutableSet.of(\"us-east-1\"));\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/location/predicates/fromconfig/AnyOrConfiguredZoneIdTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.predicates.fromconfig;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Set;\n\nimport org.jclouds.location.Provider;\nimport org.jclouds.location.predicates.ZoneIdFilter;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Sets;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.name.Names;\n\n/**\n * Tests behavior of {@code AnyOrConfiguredZoneId}\n */\n@Test(groups = \"unit\", testName = \"AnyOrConfiguredZoneIdTest\")\npublic class AnyOrConfiguredZoneIdTest {\n\n   @Test\n   public void testWithoutConfigAllIdsMatch() {\n      Set<String> zoneIds = ImmutableSet.of(\"us-east-1a\", \"us-east-1b\");\n     \n      ZoneIdFilter filter = Guice.createInjector(new AbstractModule() {\n\n         @Override\n         protected void configure() {\n            bindConstant().annotatedWith(Provider.class).to(\"aws-ec2\");\n         }\n         \n      }).getInstance(AnyOrConfiguredZoneId.class);\n      assertEquals(Sets.filter(zoneIds, filter), ImmutableSet.of(\"us-east-1a\", \"us-east-1b\"));\n   }\n   \n   @Test\n   public void testWithConfigOnlyMatchingIds() {\n      Set<String> zoneIds = ImmutableSet.of(\"us-east-1a\", \"us-east-1b\");\n     \n      ZoneIdFilter filter = Guice.createInjector(new AbstractModule() {\n\n         @Override\n         protected void configure() {\n            bindConstant().annotatedWith(Provider.class).to(\"aws-ec2\");\n            bindConstant().annotatedWith(Names.named(\"jclouds.zones\")).to(\"us-east-1a,us-east-1d\");\n         }\n         \n      }).getInstance(AnyOrConfiguredZoneId.class);\n      \n      assertEquals(Sets.filter(zoneIds, filter), ImmutableSet.of(\"us-east-1a\"));\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/location/suppliers/all/JustProviderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.suppliers.all;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\n\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code JustProvider}\n */\n@Test(groups = \"unit\", testName = \"JustProviderTest\")\npublic class JustProviderTest {\n\n   @Test\n   public void test() throws SecurityException, NoSuchMethodException {\n      JustProvider fn = new JustProvider(\"servo\", Suppliers.ofInstance(URI.create(\"http://servo\")), ImmutableSet.of(\"US\"));\n      assertEquals(\n            fn.get(),\n            ImmutableSet.of(new LocationBuilder().scope(LocationScope.PROVIDER).id(\"servo\").description(\"http://servo\")\n                  .iso3166Codes(ImmutableSet.of(\"US\")).build()));\n   }\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/location/suppliers/all/RegionToProviderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.suppliers.all;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\", testName = \"RegionToProviderTest\")\npublic class RegionToProviderTest {\n   Location provider = new LocationBuilder().scope(LocationScope.PROVIDER).id(\"servo\").description(\"http://servo\")\n            .iso3166Codes(ImmutableSet.of(\"US\")).build();\n   JustProvider justProvider = new JustProvider(\"servo\", Suppliers.ofInstance(URI.create(\"http://servo\")), ImmutableSet.of(\"US\"));\n\n   @Test\n   public void test() {\n      Supplier<Set<String>> regionIdsSupplier = Suppliers.<Set<String>>ofInstance(ImmutableSet.of(\"region1\", \"region2\"));\n      Supplier<Map<String, Supplier<Set<String>>>> locationToIsoCodes = Suppliers.<Map<String, Supplier<Set<String>>>>ofInstance(\n               ImmutableMap.of(\n                        \"servo\", Suppliers.<Set<String>>ofInstance(ImmutableSet.of(\"US\")),\n                        \"region1\", Suppliers.<Set<String>>ofInstance(ImmutableSet.of(\"US-CA\")),\n                        \"region2\", Suppliers.<Set<String>>ofInstance(ImmutableSet.of(\"US-VA\"))\n                        ));\n      RegionToProvider fn = new RegionToProvider(justProvider, regionIdsSupplier, locationToIsoCodes);\n      \n      assertEquals(fn.get(), ImmutableSet.of(\n               new LocationBuilder().scope(LocationScope.REGION).id(\"region1\").description(\"region1\").iso3166Codes(ImmutableSet.of(\"US-CA\")).parent(provider).build(),\n               new LocationBuilder().scope(LocationScope.REGION).id(\"region2\").description(\"region2\").iso3166Codes(ImmutableSet.of(\"US-VA\")).parent(provider).build()\n               ));\n   }\n   \n   @Test(expectedExceptions = IllegalStateException.class)\n   public void testWhenNoRegions() {\n      Supplier<Set<String>> regionIdsSupplier = Suppliers.<Set<String>>ofInstance(ImmutableSet.<String>of());\n      Supplier<Map<String, Supplier<Set<String>>>> locationToIsoCodes = Suppliers.<Map<String, Supplier<Set<String>>>>ofInstance(\n               ImmutableMap.<String, Supplier<Set<String>>>of());\n      RegionToProvider fn = new RegionToProvider(justProvider, regionIdsSupplier, locationToIsoCodes);\n      fn.get();\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/location/suppliers/all/ZoneToProviderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.suppliers.all;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\", testName = \"ZoneToProviderTest\")\npublic class ZoneToProviderTest {\n   Location provider = new LocationBuilder().scope(LocationScope.PROVIDER).id(\"servo\").description(\"http://servo\")\n            .iso3166Codes(ImmutableSet.of(\"US\")).build();\n   JustProvider justProvider = new JustProvider(\"servo\", Suppliers.ofInstance(URI.create(\"http://servo\")), ImmutableSet.of(\"US\"));\n\n   @Test\n   public void test() {\n      Supplier<Set<String>> zoneIdsSupplier = Suppliers.<Set<String>>ofInstance(ImmutableSet.of(\"zone1\", \"zone2\"));\n      Supplier<Map<String, Supplier<Set<String>>>> locationToIsoCodes = Suppliers.<Map<String, Supplier<Set<String>>>>ofInstance(\n               ImmutableMap.of(\n                        \"servo\", Suppliers.<Set<String>>ofInstance(ImmutableSet.of(\"US\")),\n                        \"zone1\", Suppliers.<Set<String>>ofInstance(ImmutableSet.of(\"US-CA\")),\n                        \"zone2\", Suppliers.<Set<String>>ofInstance(ImmutableSet.of(\"US-VA\"))\n                        ));\n      ZoneToProvider fn = new ZoneToProvider(justProvider, zoneIdsSupplier, locationToIsoCodes);\n      \n      assertEquals(fn.get(), ImmutableSet.of(\n               new LocationBuilder().scope(LocationScope.ZONE).id(\"zone1\").description(\"zone1\").iso3166Codes(ImmutableSet.of(\"US-CA\")).parent(provider).build(),\n               new LocationBuilder().scope(LocationScope.ZONE).id(\"zone2\").description(\"zone2\").iso3166Codes(ImmutableSet.of(\"US-VA\")).parent(provider).build()\n               ));\n   }\n   \n   @Test(expectedExceptions = IllegalStateException.class)\n   public void testWhenNoZones() {\n      Supplier<Set<String>> zoneIdsSupplier = Suppliers.<Set<String>>ofInstance(ImmutableSet.<String>of());\n      Supplier<Map<String, Supplier<Set<String>>>> locationToIsoCodes = Suppliers.<Map<String, Supplier<Set<String>>>>ofInstance(\n               ImmutableMap.<String, Supplier<Set<String>>>of());\n      ZoneToProvider fn = new ZoneToProvider(justProvider, zoneIdsSupplier, locationToIsoCodes);\n      fn.get();\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/location/suppliers/all/ZoneToRegionToProviderOrJustProviderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.suppliers.all;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\", testName = \"ZoneToRegionToProviderOrJustProviderTest\")\npublic class ZoneToRegionToProviderOrJustProviderTest {\n   Location provider = new LocationBuilder().scope(LocationScope.PROVIDER).id(\"provider\").description(\"provider\")\n            .iso3166Codes(ImmutableSet.of(\"US\")).build();\n   JustProvider justProvider = new JustProvider(\"provider\", Suppliers.ofInstance(URI.create(\"http://localhost\")), ImmutableSet.of(\"US\"));\n   \n   Supplier<Map<String, Supplier<Set<String>>>> regionToZones = Suppliers.<Map<String, Supplier<Set<String>>>>ofInstance(\n         ImmutableMap.of(\n               \"region1\", Suppliers.<Set<String>>ofInstance(ImmutableSet.of(\"zone1\")),\n               \"region2\", Suppliers.<Set<String>>ofInstance(ImmutableSet.of(\"zone2\", \"zone3\"))\n         ));\n   Supplier<Map<String, Supplier<Set<String>>>> locationToIsoCodes = Suppliers.<Map<String, Supplier<Set<String>>>>ofInstance(\n         ImmutableMap.of(\n               \"region1\", Suppliers.<Set<String>>ofInstance(ImmutableSet.of(\"US\")),\n               \"region2\", Suppliers.<Set<String>>ofInstance(ImmutableSet.of(\"US\")),\n               \"zone1\", Suppliers.<Set<String>>ofInstance(ImmutableSet.of(\"US-CA\")),\n               \"zone2\", Suppliers.<Set<String>>ofInstance(ImmutableSet.of(\"US-VA\")),\n               \"zone3\", Suppliers.<Set<String>>ofInstance(ImmutableSet.of(\"US-AK\"))\n               ));\n   \n   Location region1 = new LocationBuilder().scope(LocationScope.REGION).id(\"region1\").description(\"region1\").iso3166Codes(ImmutableSet.of(\"US\")).parent(provider).build();\n   Location region2 = new LocationBuilder().scope(LocationScope.REGION).id(\"region2\").description(\"region2\").iso3166Codes(ImmutableSet.of(\"US\")).parent(provider).build();\n   Location zone1 = new LocationBuilder().scope(LocationScope.ZONE).id(\"zone1\").description(\"zone1\").iso3166Codes(ImmutableSet.of(\"US-CA\")).parent(region1).build();\n   Location zone2 = new LocationBuilder().scope(LocationScope.ZONE).id(\"zone2\").description(\"zone2\").iso3166Codes(ImmutableSet.of(\"US-VA\")).parent(region2).build();\n   Location zone3 = new LocationBuilder().scope(LocationScope.ZONE).id(\"zone3\").description(\"zone3\").iso3166Codes(ImmutableSet.of(\"US-AK\")).parent(region2).build();\n\n   @Test\n   public void testGetAll() {\n      Supplier<Set<String>> regionIdsSupplier = Suppliers.<Set<String>> ofInstance(ImmutableSet.of(\"region1\", \"region2\"));\n      Supplier<Set<String>> zoneIdsSupplier = Suppliers.<Set<String>> ofInstance(ImmutableSet.of(\"zone1\", \"zone2\", \"zone3\"));\n      \n      RegionToProviderOrJustProvider regionToProviderOrJustProvider = new RegionToProviderOrJustProvider(justProvider, regionIdsSupplier, locationToIsoCodes);\n      ZoneToRegionToProviderOrJustProvider fn = new ZoneToRegionToProviderOrJustProvider(regionToProviderOrJustProvider, zoneIdsSupplier, locationToIsoCodes, regionToZones);\n      \n      assertEquals(fn.get(), ImmutableSet.of(region1, region2, zone1, zone2, zone3));\n   }\n   \n   @Test\n   public void testRegionAndZoneFilter() {\n      Supplier<Set<String>> regionIdsSupplier = Suppliers.<Set<String>> ofInstance(ImmutableSet.of(\"region2\"));\n      Supplier<Set<String>> zoneIdsSupplier = Suppliers.<Set<String>> ofInstance(ImmutableSet.<String> of(\"zone2\"));\n      \n      RegionToProviderOrJustProvider regionToProviderOrJustProvider = new RegionToProviderOrJustProvider(justProvider, regionIdsSupplier, locationToIsoCodes);\n      ZoneToRegionToProviderOrJustProvider fn = new ZoneToRegionToProviderOrJustProvider(regionToProviderOrJustProvider, zoneIdsSupplier, locationToIsoCodes, regionToZones);\n      \n      assertEquals(fn.get(), ImmutableSet.of(region2, zone2));\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/location/suppliers/derived/ZoneIdToURIFromJoinOnRegionIdToURITest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.suppliers.derived;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Maps;\n\n@Test\npublic class ZoneIdToURIFromJoinOnRegionIdToURITest {\n\n   public void zoneToRegionMappingsValid() {\n      Map<String, Supplier<URI>> regionIdToURIs = Maps.newLinkedHashMap();\n      regionIdToURIs.put(\"us-east-1\", Suppliers.ofInstance(URI.create(\"ec2.us-east-1.amazonaws.com\")));\n      regionIdToURIs.put(\"eu-central-1\", Suppliers.ofInstance(URI.create(\"ec2.eu-central-1.amazonaws.com\")));\n      Map<String, Supplier<Set<String>>> regionIdToZoneIds = Maps.newLinkedHashMap();\n      regionIdToZoneIds.put(\"us-east-1\", supplyZoneIds(\"us-east-1a\", \"us-east-1b\"));\n      regionIdToZoneIds.put(\"eu-central-1\", supplyZoneIds(\"eu-central-1a\"));\n\n      Map<String, Supplier<URI>> result = new ZoneIdToURIFromJoinOnRegionIdToURI(Suppliers.ofInstance(regionIdToURIs),\n            Suppliers.ofInstance(regionIdToZoneIds)).get();\n\n      assertEquals(result.size(), 3);\n      assertEquals(result.get(\"us-east-1a\"), regionIdToURIs.get(\"us-east-1\"));\n      assertEquals(result.get(\"us-east-1b\"), regionIdToURIs.get(\"us-east-1\"));\n      assertEquals(result.get(\"eu-central-1a\"), regionIdToURIs.get(\"eu-central-1\"));\n   }\n\n   @Test(expectedExceptions = IllegalStateException.class,\n         expectedExceptionsMessageRegExp = \"region eu-central-1 is not in the configured region to zone mappings: .*\")\n   public void zoneToRegionMappingsInconsistentOnKeys() {\n      Map<String, Supplier<URI>> regionIdToURIs = Maps.newLinkedHashMap();\n      regionIdToURIs.put(\"us-east-1\", Suppliers.ofInstance(URI.create(\"ec2.us-east-1.amazonaws.com\")));\n      regionIdToURIs.put(\"eu-central-1\", Suppliers.ofInstance(URI.create(\"ec2.eu-central-1.amazonaws.com\")));\n      Map<String, Supplier<Set<String>>> regionIdToZoneIds = Maps.newLinkedHashMap();\n      regionIdToZoneIds.put(\"us-east-1\", supplyZoneIds(\"us-east-1a\", \"us-east-1b\"));\n      // missing regionIdToZoneIds mapping for eu-central-1\n\n      new ZoneIdToURIFromJoinOnRegionIdToURI(Suppliers.ofInstance(regionIdToURIs),\n            Suppliers.ofInstance(regionIdToZoneIds)).get();\n   }\n\n   private static Supplier<Set<String>> supplyZoneIds(String... zoneIds) {\n      return Suppliers.<Set<String>>ofInstance(ImmutableSet.copyOf(zoneIds));\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/location/suppliers/implicit/FirstNetworkTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.suppliers.implicit;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.fail;\n\nimport java.util.NoSuchElementException;\nimport java.util.Set;\n\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code FirstNetwork}\n */\n@Test(groups = \"unit\", testName = \"FirstNetworkTest\")\npublic class FirstNetworkTest {\n   Location provider = new LocationBuilder().scope(LocationScope.PROVIDER).id(\"servo\").description(\"http://servo\")\n         .build();\n   Location region = new LocationBuilder().scope(LocationScope.REGION).id(\"servo-r\").description(\"http://r.servo\")\n         .parent(provider).build();\n   Location network = new LocationBuilder().scope(LocationScope.NETWORK).id(\"servo-n\").description(\"http://z.r.servo\")\n         .parent(region).build();\n\n   @Test\n   public void testDidntFindNetworkThrowsNSEEWithReasonableMessage() {\n      Supplier<Set<? extends Location>> supplier = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n            .<Location> of(provider, region));\n      FirstNetwork fn = new FirstNetwork(supplier);\n\n      try {\n         fn.get();\n         fail(\"Expected NoSuchElementException\");\n      } catch (NoSuchElementException e) {\n         assertEquals(e.getMessage(), \"none of the locations are scope NETWORK: [servo:PROVIDER, servo-r:REGION]\");\n      }\n   }\n\n   @Test\n   public void testFirstNetwork() {\n      Supplier<Set<? extends Location>> supplier = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n            .<Location> of(provider, region, network));\n      FirstNetwork fn = new FirstNetwork(supplier);\n      assertEquals(fn.get(), network);\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/location/suppliers/implicit/FirstRegionTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.suppliers.implicit;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.fail;\n\nimport java.util.NoSuchElementException;\nimport java.util.Set;\n\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code FirstRegion}\n */\n@Test(groups = \"unit\", testName = \"FirstRegionTest\")\npublic class FirstRegionTest {\n   Location provider = new LocationBuilder().scope(LocationScope.PROVIDER).id(\"servo\").description(\"http://servo\")\n         .build();\n   Location region = new LocationBuilder().scope(LocationScope.REGION).id(\"servo-r\").description(\"http://r.servo\")\n         .parent(provider).build();\n   Location zone = new LocationBuilder().scope(LocationScope.ZONE).id(\"servo-z\").description(\"http://z.r.servo\")\n         .parent(region).build();\n\n   @Test\n   public void testDidntFindRegionThrowsNSEEWithReasonableMessage() {\n      Supplier<Set<? extends Location>> supplier = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n            .<Location> of(provider, zone));\n      FirstRegion fn = new FirstRegion(supplier);\n\n      try {\n         fn.get();\n         fail(\"Expected NoSuchElementException\");\n      } catch (NoSuchElementException e) {\n         assertEquals(e.getMessage(), \"none to of the locations are scope REGION: [servo:PROVIDER, servo-z:ZONE]\");\n      }\n   }\n\n   @Test\n   public void testFirstRegion() {\n      Supplier<Set<? extends Location>> supplier = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n            .<Location> of(provider, region, zone));\n      FirstRegion fn = new FirstRegion(supplier);\n      assertEquals(fn.get(), region);\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/location/suppliers/implicit/FirstZoneTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.suppliers.implicit;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.fail;\n\nimport java.util.NoSuchElementException;\nimport java.util.Set;\n\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code FirstZone}\n */\n@Test(groups = \"unit\", testName = \"FirstZoneTest\")\npublic class FirstZoneTest {\n   Location provider = new LocationBuilder().scope(LocationScope.PROVIDER).id(\"servo\").description(\"http://servo\")\n         .build();\n   Location region = new LocationBuilder().scope(LocationScope.REGION).id(\"servo-r\").description(\"http://r.servo\")\n         .parent(provider).build();\n   Location zone = new LocationBuilder().scope(LocationScope.ZONE).id(\"servo-z\").description(\"http://z.r.servo\")\n         .parent(region).build();\n\n   @Test\n   public void testDidntFindZoneThrowsNSEEWithReasonableMessage() {\n      Supplier<Set<? extends Location>> supplier = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n            .<Location> of(provider, region));\n      FirstZone fn = new FirstZone(supplier);\n\n      try {\n         fn.get();\n         fail(\"Expected NoSuchElementException\");\n      } catch (NoSuchElementException e) {\n         assertEquals(e.getMessage(), \"none to of the locations are scope ZONE: [servo:PROVIDER, servo-r:REGION]\");\n      }\n   }\n\n   @Test\n   public void testFirstZone() {\n      Supplier<Set<? extends Location>> supplier = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n            .<Location> of(provider, region, zone));\n      FirstZone fn = new FirstZone(supplier);\n      assertEquals(fn.get(), zone);\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/location/suppliers/implicit/OnlyLocationOrFirstRegionOptionallyMatchingRegionIdTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.suppliers.implicit;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.fail;\n\nimport java.util.NoSuchElementException;\nimport java.util.Set;\n\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code OnlyLocationOrFirstRegionOptionallyMatchingRegionId}\n */\n@Test(groups = \"unit\", testName = \"OnlyLocationOrFirstRegionOptionallyMatchingRegionIdTest\")\npublic class OnlyLocationOrFirstRegionOptionallyMatchingRegionIdTest {\n   Location provider = new LocationBuilder().scope(LocationScope.PROVIDER).id(\"servo\").description(\"http://servo\")\n            .build();\n   Location region = new LocationBuilder().scope(LocationScope.REGION).id(\"servo-r1\").description(\"http://r1.servo\")\n            .parent(provider).build();\n   Location region2 = new LocationBuilder().scope(LocationScope.REGION).id(\"servo-r2\").description(\"http://r2.servo\")\n            .parent(provider).build();\n   Location zone = new LocationBuilder().scope(LocationScope.ZONE).id(\"servo-z\").description(\"http://z.r.servo\")\n            .parent(region).build();\n\n   @Test\n   public void testDidntMatchRegionIdThrowsNSEEWithReasonableMessage() {\n      Supplier<Set<? extends Location>> supplier = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n               .<Location> of(provider, region, region2, zone));\n      OnlyLocationOrFirstRegionOptionallyMatchingRegionId fn = new OnlyLocationOrFirstRegionOptionallyMatchingRegionId(\n               Suppliers.ofInstance(\"foo\"), supplier);\n\n      try {\n         fn.get();\n         fail(\"Expected NoSuchElementException\");\n      } catch (NoSuchElementException e) {\n         assertEquals(\n                  e.getMessage(),\n                  \"couldn't find region matching isRegionAndIdEqualsOrIsZoneParentIdEquals(foo) in [servo:PROVIDER, servo-r1:REGION, servo-r2:REGION, servo-z:ZONE]\");\n      }\n   }\n\n   @Test\n   public void testNoRegionUsesProvider() {\n      Supplier<Set<? extends Location>> supplier = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n               .<Location> of(provider));\n      OnlyLocationOrFirstRegionOptionallyMatchingRegionId fn = new OnlyLocationOrFirstRegionOptionallyMatchingRegionId(\n               Suppliers.<String>ofInstance(null), supplier);\n      assertEquals(fn.get(), provider);\n   }\n\n   @Test\n   public void testFirstRegion() {\n      Supplier<Set<? extends Location>> supplier = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n               .<Location> of(provider, region, region2, zone));\n      OnlyLocationOrFirstRegionOptionallyMatchingRegionId fn = new OnlyLocationOrFirstRegionOptionallyMatchingRegionId(\n               Suppliers.<String>ofInstance(null), supplier);\n      assertEquals(fn.get(), region);\n   }\n\n   @Test\n   public void testFindRegion() {\n      Supplier<Set<? extends Location>> supplier = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n               .<Location> of(provider, region, region2, zone));\n      OnlyLocationOrFirstRegionOptionallyMatchingRegionId fn = new OnlyLocationOrFirstRegionOptionallyMatchingRegionId(\n               Suppliers.ofInstance(region2.getId()), supplier);\n      assertEquals(fn.get(), region2);\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/location/suppliers/implicit/OnlyLocationOrFirstZoneTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.location.suppliers.implicit;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.fail;\n\nimport java.util.NoSuchElementException;\nimport java.util.Set;\n\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code OnlyLocationOrFirstZone}\n */\n@Test(groups = \"unit\", testName = \"OnlyLocationOrFirstZoneTest\")\npublic class OnlyLocationOrFirstZoneTest {\n   Location provider = new LocationBuilder().scope(LocationScope.PROVIDER).id(\"servo\").description(\"http://servo\")\n         .build();\n   Location region = new LocationBuilder().scope(LocationScope.REGION).id(\"servo-r\").description(\"http://r.servo\")\n         .parent(provider).build();\n   Location zone = new LocationBuilder().scope(LocationScope.ZONE).id(\"servo-z\").description(\"http://z.r.servo\")\n         .parent(region).build();\n\n   @Test\n   public void testDidntFindZoneThrowsNSEEWithReasonableMessage() {\n      Supplier<Set<? extends Location>> supplier = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n            .<Location> of(provider, region));\n      OnlyLocationOrFirstZone fn = new OnlyLocationOrFirstZone(supplier);\n\n      try {\n         fn.get();\n         fail(\"Expected NoSuchElementException\");\n      } catch (NoSuchElementException e) {\n         assertEquals(e.getMessage(), \"none to of the locations are scope ZONE: [servo:PROVIDER, servo-r:REGION]\");\n      }\n   }\n\n   @Test\n   public void testNoZoneUsesProvider() {\n      Supplier<Set<? extends Location>> supplier = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n            .<Location> of(provider));\n      OnlyLocationOrFirstZone fn = new OnlyLocationOrFirstZone(supplier);\n      assertEquals(fn.get(), provider);\n   }\n\n   @Test\n   public void testFirstZone() {\n      Supplier<Set<? extends Location>> supplier = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n            .<Location> of(provider, region, zone));\n      OnlyLocationOrFirstZone fn = new OnlyLocationOrFirstZone(supplier);\n      assertEquals(fn.get(), zone);\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/logging/BufferLogger.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.logging;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.logging.Level;\n\nimport com.google.common.base.Predicate;\n\n/** A logger implementation for use in testing; all log messages are remembered, \\\n * but not written anywhere. The messages can then be inspected {@link #getMessages()}\n * or certain assertions applied (see assertXxx methods on these instances) */\npublic class BufferLogger extends BaseLogger {\n\n   final String category;\n   Level level = Level.INFO;\n   List<Record> messages = Collections.synchronizedList(new ArrayList<Record>());\n\n   public static class Record {\n      Level level;\n      String message;\n      Throwable trace;\n      public Record(Level level, String message, Throwable trace) {\n         this.level = level;\n         this.message = message;\n         this.trace = trace;\n      }\n      public Level getLevel() {\n         return level;\n      }\n      public String getMessage() {\n         return message;\n      }\n      public Throwable getTrace() {\n         return trace;\n      }\n   }\n\n   \n   public BufferLogger(String category) {\n      this.category = category;\n   }\n   \n   public List<Record> getMessages() {\n      return messages;\n   }\n   \n   /** throws AssertionError if the log does not contain the indicated fragment;\n    * otherwise returns a record which does satisfy the constraint \n    */\n   public Record assertLogContains(String fragment) {\n      for (Record r : messages) {\n         if (r.getMessage() != null && r.getMessage().contains(fragment)) return r;\n      }\n      throw new AssertionError(\"log did not contain expected '\" + fragment + \"'\");\n   }\n   /** fails if log _does_ contain the indicated fragment */\n   public void assertLogDoesntContain(String fragment) {\n      for (Record r : messages) {\n         if (r.getMessage() != null && r.getMessage().contains(fragment))\n            throw new AssertionError(\"log contained unexpected '\" + fragment + \"'\");\n      }\n   }\n\n   /** throws AssertionError if the log does not contain the indicated fragment;\n    * otherwise returns a record which does satisfy the constraint \n    */\n   public Record assertLogContains(Predicate<Record> test) {\n      for (Record r : messages) {\n         if (r.getMessage() != null && test.apply(r)) return r;\n      }\n      throw new AssertionError(\"log did not contain any records satisfying expected predicate\");      \n   }\n   \n   @Override\n   public String getCategory() {\n      return category;\n   }\n\n   public void setLevel(Level level) {\n      this.level = level;\n   }\n   public void setAllLevelsEnabled() {\n      level = Level.ALL;\n   }\n   public void setAllLevelsDisabled() {\n      level = Level.OFF;\n   }\n   \n   @Override\n   public boolean isTraceEnabled() {\n      return level.intValue() <= Level.FINER.intValue();\n   }\n   @Override\n   public boolean isDebugEnabled() {\n      return level.intValue() <= Level.FINE.intValue();\n   }\n\n   @Override\n   public boolean isInfoEnabled() {\n      return level.intValue() <= Level.INFO.intValue();\n   }\n\n   @Override\n   public boolean isWarnEnabled() {\n      return level.intValue() <= Level.WARNING.intValue();\n   }\n\n   @Override\n   public boolean isErrorEnabled() {\n      return level.intValue() <= Level.SEVERE.intValue();\n   }\n   \n   \n   @Override\n   protected void logError(String message, Throwable e) {\n      getMessages().add(new Record(Level.SEVERE, message, e));\n   }\n\n   @Override\n   protected void logError(String message) {\n      getMessages().add(new Record(Level.SEVERE, message, null));\n   }\n\n   @Override\n   protected void logWarn(String message, Throwable e) {\n      getMessages().add(new Record(Level.WARNING, message, e));   \n   }\n\n   @Override\n   protected void logWarn(String message) {\n      getMessages().add(new Record(Level.WARNING, message, null));   \n   }\n\n   @Override\n   protected void logInfo(String message) {\n      getMessages().add(new Record(Level.INFO, message, null));   \n   }\n\n   @Override\n   protected void logDebug(String message) {\n      getMessages().add(new Record(Level.FINE, message, null));   \n   }\n\n   @Override\n   protected void logTrace(String message) {\n      getMessages().add(new Record(Level.FINER, message, null));   \n   }\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/logging/BufferLoggerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.logging;\n\nimport java.util.logging.Level;\n\nimport org.jclouds.logging.BufferLogger.Record;\nimport org.testng.Assert;\nimport org.testng.annotations.Test;\n\n@Test\npublic class BufferLoggerTest {\n\n   public void testLogCapturesRightMessages() {\n      BufferLogger b = new BufferLogger(\"foo\");\n      b.setLevel(Level.INFO);\n      b.info(\"hi 1\");\n      b.error(new Throwable(\"check\"), \"hi 2\");\n      b.debug(\"hi 3 nope\");\n      \n      Record r;\n      r = b.assertLogContains(\"hi 1\");\n      Assert.assertEquals(Level.INFO, r.getLevel());\n      Assert.assertNull(r.getTrace());\n      \n      r = b.assertLogContains(\"hi 2\");\n      Assert.assertEquals(Level.SEVERE, r.getLevel());\n      Assert.assertEquals(r.getTrace().getMessage(), \"check\");\n      \n      b.assertLogDoesntContain(\"hi 3\");\n   }\n   \n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/logging/config/BindLoggersAnnotatedWithResourceTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.logging.config;\n\nimport static com.google.inject.matcher.Matchers.any;\nimport static org.easymock.EasyMock.createMock;\nimport static org.testng.Assert.assertEquals;\n\nimport java.lang.reflect.Field;\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\n\nimport org.jclouds.logging.Logger;\nimport org.jclouds.logging.config.BindLoggersAnnotatedWithResource.AssignLoggerToField;\nimport org.jclouds.logging.config.BindLoggersAnnotatedWithResource.LoggerFieldsAnnotatedWithResource;\nimport org.jclouds.logging.jdk.JDKLogger;\nimport org.testng.annotations.BeforeMethod;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test\npublic class BindLoggersAnnotatedWithResourceTest {\n\n   private BindLoggersAnnotatedWithResource blawr;\n\n   public static class A {\n      @Resource\n      private Logger logger = Logger.NULL;\n   }\n\n   private static class B {\n      @Resource\n      private Logger logger = Logger.NULL;\n\n      @Resource\n      @Named(\"blogger\")\n      private Logger blogger = Logger.NULL;\n   }\n\n   @BeforeMethod\n   void createBlawr() {\n      blawr = new BindLoggersAnnotatedWithResource(new JDKLogger.JDKLoggerFactory());\n   }\n\n   @Test\n   void testHear() {\n      Injector i = Guice.createInjector(new AbstractModule() {\n\n         @Override\n         protected void configure() {\n            bindListener(any(), blawr);\n         }\n\n      });\n      assertEquals(i.getInstance(A.class).logger.getCategory(), getClass().getName() + \"$A\");\n      assertEquals(i.getInstance(B.class).logger.getCategory(), getClass().getName() + \"$B\");\n      assertEquals(i.getInstance(B.class).blogger.getCategory(), \"blogger\");\n   }\n\n   @Test\n   public void testAssignLoggerToField() throws SecurityException, NoSuchFieldException,\n            IllegalArgumentException, IllegalAccessException {\n      Logger logger = createMock(Logger.class);\n      A a = new A();\n      Field field = A.class.getDeclaredField(\"logger\");\n      AssignLoggerToField<A> assigner = new AssignLoggerToField<A>(logger, field);\n      assigner.afterInjection(a);\n      assert field.get(a).equals(logger);\n   }\n\n   @Test\n   public void testLoggerFieldsAnnotatedWithResource() throws SecurityException,\n            NoSuchFieldException {\n      LoggerFieldsAnnotatedWithResource predicate = new LoggerFieldsAnnotatedWithResource();\n      assert predicate.apply(A.class.getDeclaredField(\"logger\"));\n   }\n\n   public static class C {\n      @Inject\n      private Logger logger = Logger.NULL;\n   }\n\n   @Test\n   public void testLoggerFieldsAnnotatedWithInjectReturnsNull() throws SecurityException,\n            NoSuchFieldException {\n      LoggerFieldsAnnotatedWithResource predicate = new LoggerFieldsAnnotatedWithResource();\n      assert !predicate.apply(C.class.getDeclaredField(\"logger\"));\n   }\n\n   public static class D {\n      @Resource\n      private Logger logger = Logger.NULL;\n\n      @Resource\n      private Logger blogger;\n\n   }\n\n   @Test\n   public void testGetLoggerFieldsAnnotatedWithResourceNoLogger() {\n      Set<Field> fields = blawr.getLoggerFieldsAnnotatedWithResource(this.getClass());\n      assertEquals(fields.size(), 0);\n   }\n\n   @Test\n   public void testGetLoggerFieldsAnnotatedWithResourceOneLogger() {\n      Set<Field> fields = blawr.getLoggerFieldsAnnotatedWithResource(A.class);\n      assertEquals(fields.size(), 1);\n   }\n\n   @Test\n   public void testGetLoggerFieldsAnnotatedWithResourceTwoLoggers() {\n      Set<Field> fields = blawr.getLoggerFieldsAnnotatedWithResource(D.class);\n      assertEquals(fields.size(), 2);\n   }\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/osgi/BundlesTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.osgi;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.apis.JcloudsTestComputeApiMetadata;\nimport org.jclouds.providers.JcloudsTestBlobStoreProviderMetadata;\nimport org.jclouds.providers.JcloudsTestComputeProviderMetadata;\nimport org.jclouds.providers.JcloudsTestYetAnotherComputeProviderMetadata;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.osgi.framework.Bundle;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\npublic class BundlesTest {\n\n   @SuppressWarnings(\"rawtypes\")\n   @Test\n   public void testInstantiateAvailableClassesWhenAllAssignable() throws ClassNotFoundException {\n      Bundle bundle = createMock(Bundle.class);\n      expect((Class) bundle.loadClass(\"org.jclouds.providers.JcloudsTestBlobStoreProviderMetadata\")).andReturn(\n            JcloudsTestBlobStoreProviderMetadata.class);\n      expect((Class) bundle.loadClass(\"org.jclouds.providers.JcloudsTestComputeProviderMetadata\")).andReturn(\n            JcloudsTestComputeProviderMetadata.class);\n      expect((Class) bundle.loadClass(\"org.jclouds.providers.JcloudsTestYetAnotherComputeProviderMetadata\")).andReturn(\n            JcloudsTestYetAnotherComputeProviderMetadata.class);\n      replay(bundle);\n\n      Iterable<ProviderMetadata> providers = Bundles.instantiateAvailableClasses(bundle, ImmutableSet.of(\n            \"org.jclouds.providers.JcloudsTestBlobStoreProviderMetadata\",\n            \"org.jclouds.providers.JcloudsTestComputeProviderMetadata\",\n            \"org.jclouds.providers.JcloudsTestYetAnotherComputeProviderMetadata\"), ProviderMetadata.class);\n      assertEquals(providers, ImmutableSet.of(new JcloudsTestBlobStoreProviderMetadata(),\n            new JcloudsTestComputeProviderMetadata(), new JcloudsTestYetAnotherComputeProviderMetadata()));\n\n      verify(bundle);\n   }\n\n   @SuppressWarnings(\"rawtypes\")\n   @Test\n   public void testInstantiateAvailableClassesWhenNotAllAssignable() throws ClassNotFoundException {\n      Bundle bundle = createMock(Bundle.class);\n      expect((Class) bundle.loadClass(\"org.jclouds.providers.JcloudsTestBlobStoreProviderMetadata\")).andReturn(\n            JcloudsTestBlobStoreProviderMetadata.class);\n      expect((Class) bundle.loadClass(\"org.jclouds.apis.JcloudsTestComputeApiMetadata\")).andReturn(\n            JcloudsTestComputeApiMetadata.class);\n      expect((Class) bundle.loadClass(\"org.jclouds.providers.JcloudsTestYetAnotherComputeProviderMetadata\")).andReturn(\n            JcloudsTestYetAnotherComputeProviderMetadata.class);\n      replay(bundle);\n\n      Iterable<ProviderMetadata> providers = Bundles.instantiateAvailableClasses(bundle, ImmutableSet.of(\n            \"org.jclouds.providers.JcloudsTestBlobStoreProviderMetadata\",\n            \"org.jclouds.apis.JcloudsTestComputeApiMetadata\",\n            \"org.jclouds.providers.JcloudsTestYetAnotherComputeProviderMetadata\"), ProviderMetadata.class);\n      assertEquals(providers, ImmutableSet.of(new JcloudsTestBlobStoreProviderMetadata(),\n            new JcloudsTestYetAnotherComputeProviderMetadata()));\n\n      verify(bundle);\n   }\n\n   @Test\n   public void testStringsForResourcesInBundleWhenNoResources() throws Exception {\n\n      Bundle bundle = createMock(Bundle.class);\n      expect(bundle.getEntry(\"/META-INF/services/org.jclouds.apis.ApiMetadata\")).andReturn(null);\n      replay(bundle);\n\n      assertEquals(Bundles.stringsForResourceInBundle(\"/META-INF/services/org.jclouds.apis.ApiMetadata\", bundle),\n            ImmutableSet.of());\n\n      verify(bundle);\n   }\n\n   @Test\n   public void testStringsForResourcesInBundleWhenResourcePresent() throws Exception {\n\n      Bundle bundle = createMock(Bundle.class);\n      expect(bundle.getEntry(\"/META-INF/services/org.jclouds.providers.ProviderMetadata\")).andReturn(\n            getClass().getResource(\"/META-INF/services/org.jclouds.providers.ProviderMetadata\"));\n      replay(bundle);\n\n      assertEquals(Bundles.stringsForResourceInBundle(\"/META-INF/services/org.jclouds.providers.ProviderMetadata\",\n            bundle), ImmutableSet.of(\"org.jclouds.providers.JcloudsTestBlobStoreProviderMetadata\",\n            \"org.jclouds.providers.JcloudsTestComputeProviderMetadata\",\n            \"org.jclouds.providers.JcloudsTestYetAnotherComputeProviderMetadata\"));\n\n      verify(bundle);\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/osgi/MetadataBundleListenerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.osgi;\n\nimport static org.easymock.EasyMock.anyObject;\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.expectLastCall;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.List;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.apis.JcloudsTestBlobStoreApiMetadata;\nimport org.jclouds.apis.JcloudsTestComputeApiMetadata;\nimport org.jclouds.apis.JcloudsTestYetAnotherComputeApiMetadata;\nimport org.jclouds.providers.JcloudsTestBlobStoreProviderMetadata;\nimport org.jclouds.providers.JcloudsTestComputeProviderMetadata;\nimport org.jclouds.providers.JcloudsTestYetAnotherComputeProviderMetadata;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.osgi.framework.Bundle;\nimport org.osgi.framework.BundleEvent;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Lists;\n\npublic class MetadataBundleListenerTest {\n\n   @SuppressWarnings(\"rawtypes\")\n   @Test\n   public void testGetProviderMetadata() throws Exception {\n      MetadataBundleListener listener = new MetadataBundleListener();\n      Bundle bundle = createMock(Bundle.class);\n      expect(bundle.getEntry(\"/META-INF/services/org.jclouds.providers.ProviderMetadata\")).andReturn(\n            getClass().getResource(\"/META-INF/services/org.jclouds.providers.ProviderMetadata\")).anyTimes();\n      expect((Class) bundle.loadClass(\"org.jclouds.providers.JcloudsTestBlobStoreProviderMetadata\")).andReturn(\n            JcloudsTestBlobStoreProviderMetadata.class).anyTimes();\n      expect((Class) bundle.loadClass(\"org.jclouds.providers.JcloudsTestComputeProviderMetadata\")).andReturn(\n            JcloudsTestComputeProviderMetadata.class).anyTimes();\n      expect((Class) bundle.loadClass(\"org.jclouds.providers.JcloudsTestYetAnotherComputeProviderMetadata\")).andReturn(\n            JcloudsTestYetAnotherComputeProviderMetadata.class).anyTimes();\n      replay(bundle);\n      List<ProviderMetadata> providerMetadataList = Lists.newArrayList(listener.listProviderMetadata(bundle));\n      assertNotNull(providerMetadataList);\n      assertEquals(3, providerMetadataList.size());\n      assertTrue(providerMetadataList.contains(new JcloudsTestBlobStoreProviderMetadata()));\n      assertTrue(providerMetadataList.contains(new JcloudsTestComputeProviderMetadata()));\n      assertTrue(providerMetadataList.contains(new JcloudsTestYetAnotherComputeProviderMetadata()));\n      verify(bundle);\n   }\n\n   @SuppressWarnings(\"rawtypes\")\n   @Test\n   public void testProviderListener() throws Exception {\n      MetadataBundleListener listener = new MetadataBundleListener();\n      ProviderListener providerListener = createMock(ProviderListener.class);\n      listener.addProviderListener(providerListener);\n\n      Bundle bundle = createMock(Bundle.class);\n      expect(bundle.getBundleId()).andReturn(10L).anyTimes();\n      expect(bundle.getEntry(\"/META-INF/services/org.jclouds.providers.ProviderMetadata\")).andReturn(\n            getClass().getResource(\"/META-INF/services/org.jclouds.providers.ProviderMetadata\")).anyTimes();\n      expect(bundle.getEntry(\"/META-INF/services/org.jclouds.apis.ApiMetadata\")).andReturn(null).anyTimes();\n      expect((Class) bundle.loadClass(\"org.jclouds.providers.JcloudsTestBlobStoreProviderMetadata\")).andReturn(\n            JcloudsTestBlobStoreProviderMetadata.class).anyTimes();\n      expect((Class) bundle.loadClass(\"org.jclouds.providers.JcloudsTestComputeProviderMetadata\")).andReturn(\n            JcloudsTestComputeProviderMetadata.class).anyTimes();\n      expect((Class) bundle.loadClass(\"org.jclouds.providers.JcloudsTestYetAnotherComputeProviderMetadata\")).andReturn(\n            JcloudsTestYetAnotherComputeProviderMetadata.class).anyTimes();\n\n      providerListener.added(anyObject(JcloudsTestBlobStoreProviderMetadata.class));\n      expectLastCall().times(1);\n      providerListener.added(anyObject(JcloudsTestComputeProviderMetadata.class));\n      expectLastCall().times(1);\n      providerListener.added(anyObject(JcloudsTestYetAnotherComputeProviderMetadata.class));\n      expectLastCall().times(1);\n      replay(bundle, providerListener);\n\n      BundleEvent event = new BundleEvent(BundleEvent.STARTED, bundle);\n      listener.bundleChanged(event);\n      verify(bundle, providerListener);\n   }\n\n   @SuppressWarnings(\"rawtypes\")\n   @Test\n   public void testGetApiMetadata() throws Exception {\n      MetadataBundleListener listener = new MetadataBundleListener();\n      Bundle bundle = createMock(Bundle.class);\n      expect(bundle.getEntry(\"/META-INF/services/org.jclouds.apis.ApiMetadata\")).andReturn(\n            getClass().getResource(\"/META-INF/services/org.jclouds.apis.ApiMetadata\")).anyTimes();\n      expect((Class) bundle.loadClass(\"org.jclouds.apis.JcloudsTestBlobStoreApiMetadata\")).andReturn(\n            JcloudsTestBlobStoreApiMetadata.class).anyTimes();\n      expect((Class) bundle.loadClass(\"org.jclouds.apis.JcloudsTestComputeApiMetadata\")).andReturn(\n            JcloudsTestComputeApiMetadata.class).anyTimes();\n      expect((Class) bundle.loadClass(\"org.jclouds.apis.JcloudsTestYetAnotherComputeApiMetadata\")).andReturn(\n            JcloudsTestYetAnotherComputeApiMetadata.class).anyTimes();\n\n      replay(bundle);\n      List<ApiMetadata> apiMetadataList = Lists.newArrayList(listener.listApiMetadata(bundle));\n      assertNotNull(apiMetadataList);\n      assertEquals(3, apiMetadataList.size());\n      assertTrue(apiMetadataList.contains(new JcloudsTestBlobStoreApiMetadata()));\n      assertTrue(apiMetadataList.contains(new JcloudsTestComputeApiMetadata()));\n      assertTrue(apiMetadataList.contains(new JcloudsTestYetAnotherComputeApiMetadata()));\n      verify(bundle);\n   }\n\n   @SuppressWarnings(\"rawtypes\")\n   @Test\n   public void testApiListener() throws Exception {\n      MetadataBundleListener listener = new MetadataBundleListener();\n      ApiListener apiListener = createMock(ApiListener.class);\n      listener.addApiListenerListener(apiListener);\n\n      Bundle bundle = createMock(Bundle.class);\n      expect(bundle.getBundleId()).andReturn(10L).anyTimes();\n      expect(bundle.getEntry(\"/META-INF/services/org.jclouds.providers.ProviderMetadata\")).andReturn(null).anyTimes();\n      expect(bundle.getEntry(\"/META-INF/services/org.jclouds.apis.ApiMetadata\")).andReturn(\n            getClass().getResource(\"/META-INF/services/org.jclouds.apis.ApiMetadata\")).anyTimes();\n      expect((Class) bundle.loadClass(\"org.jclouds.apis.JcloudsTestBlobStoreApiMetadata\")).andReturn(\n            JcloudsTestBlobStoreApiMetadata.class).anyTimes();\n      expect((Class) bundle.loadClass(\"org.jclouds.apis.JcloudsTestComputeApiMetadata\")).andReturn(\n            JcloudsTestComputeApiMetadata.class).anyTimes();\n      expect((Class) bundle.loadClass(\"org.jclouds.apis.JcloudsTestYetAnotherComputeApiMetadata\")).andReturn(\n            JcloudsTestYetAnotherComputeApiMetadata.class).anyTimes();\n\n      apiListener.added(anyObject(JcloudsTestBlobStoreApiMetadata.class));\n      expectLastCall().times(1);\n      apiListener.added(anyObject(JcloudsTestBlobStoreApiMetadata.class));\n      expectLastCall().times(1);\n      apiListener.added(anyObject(JcloudsTestComputeApiMetadata.class));\n      expectLastCall().times(1);\n      replay(bundle, apiListener);\n\n      BundleEvent event = new BundleEvent(BundleEvent.STARTED, bundle);\n      listener.bundleChanged(event);\n      verify(bundle, apiListener);\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/providers/JcloudsTestBlobStoreProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.providers;\n\nimport java.net.URI;\n\nimport org.jclouds.apis.JcloudsTestBlobStoreApiMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\n\nimport com.google.auto.service.AutoService;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Implementation of {@link ProviderMetadata} for testing.\n */\n@AutoService(ProviderMetadata.class)\npublic class JcloudsTestBlobStoreProviderMetadata extends BaseProviderMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return Builder.class.cast(builder().fromProviderMetadata(this));\n   }\n\n   public JcloudsTestBlobStoreProviderMetadata() {\n      super(builder());\n   }\n\n   public JcloudsTestBlobStoreProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static class Builder extends BaseProviderMetadata.Builder {\n\n      protected Builder() {\n         id(\"test-blobstore-api\")\n         .name(\"Test Blobstore Provider\")\n         .endpoint(\"http://mock\")\n         .homepage(URI.create(\"http://jclouds.org\"))\n         .console(URI.create(\"http://jclouds.org/console\"))\n         .iso3166Codes(ImmutableSet.of(\"US-VA\", \"US-CA\", \"US-FL\"))\n         .apiMetadata(new JcloudsTestBlobStoreApiMetadata());\n      }\n\n      @Override\n      public JcloudsTestBlobStoreProviderMetadata build() {\n         return new JcloudsTestBlobStoreProviderMetadata(this);\n      }\n\n   }\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/providers/JcloudsTestComputeProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.providers;\n\nimport java.net.URI;\n\nimport org.jclouds.apis.JcloudsTestComputeApiMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\n\nimport com.google.auto.service.AutoService;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Implementation of {@link ProviderMetadata} for testing.\n */\n@AutoService(ProviderMetadata.class)\npublic class JcloudsTestComputeProviderMetadata extends BaseProviderMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return Builder.class.cast(builder().fromProviderMetadata(this));\n   }\n\n   public JcloudsTestComputeProviderMetadata() {\n      super(builder());\n   }\n\n   public JcloudsTestComputeProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static class Builder extends BaseProviderMetadata.Builder {\n\n      protected Builder() {\n         id(\"test-compute-api\")\n         .name(\"Test Compute Provider\")\n         .endpoint(\"mem2\")\n         .homepage(URI.create(\"http://jclouds.org\"))\n         .console(URI.create(\"http://jclouds.org/console\"))\n         .iso3166Codes(ImmutableSet.of(\"US-VA\", \"US-CA\"))\n         .apiMetadata(new JcloudsTestComputeApiMetadata());\n      }\n\n      @Override\n      public JcloudsTestComputeProviderMetadata build() {\n         return new JcloudsTestComputeProviderMetadata(this);\n      }\n\n   }\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/providers/JcloudsTestYetAnotherComputeProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.providers;\n\nimport java.net.URI;\n\nimport org.jclouds.apis.JcloudsTestComputeApiMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\n\nimport com.google.auto.service.AutoService;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Implementation of {@link ProviderMetadata} for testing.\n */\n@AutoService(ProviderMetadata.class)\npublic class JcloudsTestYetAnotherComputeProviderMetadata extends BaseProviderMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return Builder.class.cast(builder().fromProviderMetadata(this));\n   }\n\n   public JcloudsTestYetAnotherComputeProviderMetadata() {\n      super(builder());\n   }\n\n   public JcloudsTestYetAnotherComputeProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static class Builder extends BaseProviderMetadata.Builder {\n\n      protected Builder() {\n         id(\"test-yet-another-compute-provider\")\n         .name(\"Test Yet Another Compute Provider\")\n         .endpoint(\"mem3\")\n         .homepage(URI.create(\"http://jclouds.org\"))\n         .console(URI.create(\"http://jclouds.org/console\"))\n         .iso3166Codes(ImmutableSet.of(\"JP-13\"))\n         .apiMetadata(new JcloudsTestComputeApiMetadata());\n      }\n\n      @Override\n      public JcloudsTestYetAnotherComputeProviderMetadata build() {\n         return new JcloudsTestYetAnotherComputeProviderMetadata(this);\n      }\n\n   }\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/providers/ProvidersTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.providers;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotEquals;\nimport static org.testng.Assert.fail;\n\nimport java.util.NoSuchElementException;\n\nimport org.jclouds.apis.Balancer;\nimport org.jclouds.apis.Compute;\nimport org.jclouds.apis.Storage;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Iterables;\n\n/**\n * The ProvidersTest tests the org.jclouds.providers.Providers class.\n */\n@Test(groups = \"unit\", testName = \"ProvidersTest\")\npublic class ProvidersTest {\n\n   private final JcloudsTestBlobStoreProviderMetadata testBlobstoreProvider = new JcloudsTestBlobStoreProviderMetadata();\n   private final JcloudsTestComputeProviderMetadata testComputeProvider = new JcloudsTestComputeProviderMetadata();\n   private final JcloudsTestYetAnotherComputeProviderMetadata testYetAnotherComputeProvider = new JcloudsTestYetAnotherComputeProviderMetadata();\n\n   @Test\n   public void testWithId() {\n      ProviderMetadata providerMetadata;\n\n      try {\n         providerMetadata = Providers.withId(\"fake-id\");\n         fail(\"Looking for a provider with an id that doesn't exist should \" + \"throw an exception.\");\n      } catch (NoSuchElementException nsee) {\n         // expected\n      }\n\n      providerMetadata = Providers.withId(testBlobstoreProvider.getId());\n\n      assertEquals(testBlobstoreProvider, providerMetadata);\n      assertNotEquals(testBlobstoreProvider, testComputeProvider);\n      assertNotEquals(testBlobstoreProvider, testYetAnotherComputeProvider);\n   }\n\n   @Test\n   public void testTransformableTo() {\n      Iterable<ProviderMetadata> providersMetadata = Providers.viewableAs(Storage.class);\n\n      for (ProviderMetadata providerMetadata : providersMetadata) {\n         assertEquals(testBlobstoreProvider, providerMetadata);\n      }\n\n      providersMetadata = Providers.viewableAs(Compute.class);\n\n      for (ProviderMetadata providerMetadata : providersMetadata) {\n         if (providerMetadata.getName().equals(testComputeProvider.getName())) {\n            assertEquals(testComputeProvider, providerMetadata);\n         } else {\n            assertEquals(testYetAnotherComputeProvider, providerMetadata);\n         }\n      }\n\n      providersMetadata = Providers.viewableAs(Balancer.class);\n\n      assertEquals(false, providersMetadata.iterator().hasNext());\n   }\n   \n   @Test\n   public void testAll() {\n      Iterable<ProviderMetadata> providersMetadata = Providers.all();\n\n      for (ProviderMetadata providerMetadata : providersMetadata) {\n         if (providerMetadata.getName().equals(testBlobstoreProvider.getName())) {\n            assertEquals(testBlobstoreProvider, providerMetadata);\n         } else if (providerMetadata.getName().equals(testComputeProvider.getName())) {\n            assertEquals(testComputeProvider, providerMetadata);\n         } else {\n            assertEquals(testYetAnotherComputeProvider, providerMetadata);\n         }\n      }\n   }\n\n   @Test\n   public void testBoundedByIso3166Code() {\n      // Test filtering by ISO 3166 code alone\n      assertEquals(Iterables.size(Providers.boundedByIso3166Code(\"US-CA\")), 2);\n      assertEquals(Iterables.size(Providers.boundedByIso3166Code(\"US-FL\")), 1);\n      assertEquals(Iterables.size(Providers.boundedByIso3166Code(\"US\")), 2);\n      assertEquals(Iterables.size(Providers.boundedByIso3166Code(\"JP-13\")), 1);\n      assertEquals(Iterables.size(Providers.boundedByIso3166Code(\"JP\")), 1);\n      assertEquals(Iterables.size(Providers.boundedByIso3166Code(\"FAKE-CODE\")), 0);\n\n      // Test filtering by ISO 3166 code and type\n      assertEquals(Iterables.size(Providers.boundedByIso3166Code(\"US-CA\", Storage.class)), 1);\n      assertEquals(Iterables.size(Providers.boundedByIso3166Code(\"US-CA\", Compute.class)), 1);\n      assertEquals(Iterables.size(Providers.boundedByIso3166Code(\"US-FL\", Storage.class)), 1);\n      assertEquals(Iterables.size(Providers.boundedByIso3166Code(\"US-FL\", Compute.class)), 0);\n      assertEquals(Iterables.size(Providers.boundedByIso3166Code(\"US\", Storage.class)), 1);\n      assertEquals(Iterables.size(Providers.boundedByIso3166Code(\"US\", Compute.class)), 1);\n      assertEquals(Iterables.size(Providers.boundedByIso3166Code(\"FAKE-CODE\", Storage.class)), 0);\n      assertEquals(Iterables.size(Providers.boundedByIso3166Code(\"FAKE-CODE\", Compute.class)), 0);\n   }\n\n   @Test\n   public void testCollocatedWith() {\n      // Test filtering by collocation alone\n      assertEquals(Iterables.size(Providers.collocatedWith(testYetAnotherComputeProvider)), 0);\n      assertEquals(Iterables.size(Providers.collocatedWith(testBlobstoreProvider)), 1);\n      assertEquals(Iterables.size(Providers.collocatedWith(testComputeProvider)), 1);\n      assertEquals(Iterables.size(Providers.collocatedWith(testYetAnotherComputeProvider)), 0);\n\n      // Test filtering by collocation and type\n      assertEquals(Iterables.size(Providers.collocatedWith(testBlobstoreProvider, Storage.class)), 0);\n      assertEquals(Iterables.size(Providers.collocatedWith(testBlobstoreProvider, Compute.class)), 1);\n      assertEquals(Iterables.size(Providers.collocatedWith(testComputeProvider, Compute.class)), 0);\n      assertEquals(Iterables.size(Providers.collocatedWith(testComputeProvider, Storage.class)), 1);\n      assertEquals(Iterables.size(Providers.collocatedWith(testYetAnotherComputeProvider, Compute.class)), 0);\n      assertEquals(Iterables.size(Providers.collocatedWith(testYetAnotherComputeProvider, Storage.class)), 0);\n   }\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/providers/config/BindProviderMetadataContextAndCredentialsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.providers.config;\n\nimport static org.jclouds.providers.AnonymousProviderMetadata.forApiOnEndpoint;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Properties;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.Constants;\nimport org.jclouds.Context;\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.http.IntegrationTestClient;\nimport org.jclouds.internal.FilterStringsBoundToInjectorByName;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.location.Iso3166;\nimport org.jclouds.location.Provider;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.rest.annotations.Api;\nimport org.jclouds.rest.annotations.ApiVersion;\nimport org.jclouds.rest.annotations.BuildVersion;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicates;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.reflect.TypeToken;\nimport com.google.inject.Guice;\nimport com.google.inject.Key;\nimport com.google.inject.name.Names;\n\n@Test(groups = \"unit\", testName = \"BindProviderMetadataContextAndCredentialsTest\")\npublic class BindProviderMetadataContextAndCredentialsTest {\n\n   @SuppressWarnings(\"unused\")\n   private static class ExpectedBindings {\n      private final jakarta.inject.Provider<Context> backend;\n      private final ProviderMetadata providerMetadata;\n      private final Credentials creds;\n      private final String providerId;\n      private final Set<String> iso3166Codes;\n      private final String apiId;\n      private final String apiVersion;\n      private final String buildVersion;\n\n      @Inject\n      private ExpectedBindings(@Provider jakarta.inject.Provider<Context> backend, ProviderMetadata providerMetadata,\n            @Provider Supplier<Credentials> creds, @Provider String providerId, @Iso3166 Set<String> iso3166Codes,\n            @Api String apiId, @ApiVersion String apiVersion, @Nullable @BuildVersion String buildVersion,\n            @Provider TypeToken<? extends Context> backendToken, FilterStringsBoundToInjectorByName filter) {\n         this.backend = backend;\n         assertEquals(backendToken, providerMetadata.getApiMetadata().getContext());\n         this.providerMetadata = providerMetadata;\n         Properties props = new Properties();\n         props.putAll(filter.apply(Predicates.<String> alwaysTrue()));\n         Properties expected = new Properties();\n         expected.putAll(providerMetadata.getApiMetadata().getDefaultProperties());\n         expected.putAll(providerMetadata.getDefaultProperties());\n         assertEquals(props, expected);\n         this.creds = creds.get();\n         this.providerId = providerId;\n         assertEquals(providerId, providerMetadata.getId());\n         this.iso3166Codes = iso3166Codes;\n         assertEquals(iso3166Codes, providerMetadata.getIso3166Codes());\n         this.apiId = apiId;\n         assertEquals(apiId, providerMetadata.getApiMetadata().getId());\n         this.apiVersion = apiVersion;\n         assertEquals(apiVersion, providerMetadata.getApiMetadata().getVersion());\n         this.buildVersion = buildVersion;\n         assertEquals(buildVersion, providerMetadata.getApiMetadata().getBuildVersion().orNull());\n      }\n\n   }\n\n   @Test\n   public void testExpectedBindingsWhenCredentialIsNotNull() {\n      ProviderMetadata md = forApiOnEndpoint(IntegrationTestClient.class, \"http://localhost\");\n\n      Supplier<Credentials> creds = Suppliers.<Credentials> ofInstance(LoginCredentials.builder().user(\"user\")\n            .password(\"password\").build());\n\n      ExpectedBindings bindings = Guice.createInjector(new BindProviderMetadataContextAndCredentials(md, creds))\n               .getInstance(ExpectedBindings.class);\n      assertEquals(bindings.creds.identity, \"user\");\n      assertEquals(bindings.creds.credential, \"password\");\n   }\n\n   @Test\n   public void testExpectedBindingsWhenCredentialIsNull() {\n      ProviderMetadata md = forApiOnEndpoint(IntegrationTestClient.class, \"http://localhost\");\n\n      Supplier<Credentials> creds = Suppliers.<Credentials> ofInstance(LoginCredentials.builder().user(\"user\").build());\n\n      ExpectedBindings bindings = Guice.createInjector(new BindProviderMetadataContextAndCredentials(md, creds))\n               .getInstance(ExpectedBindings.class);\n      assertEquals(bindings.creds.identity, \"user\");\n      assertEquals(bindings.creds.credential, null);\n   }\n   \n   @Test\n   public void testExpectedBindingsWhenBuildVersionAbsent() {\n      ProviderMetadata md = forApiOnEndpoint(IntegrationTestClient.class, \"http://localhost\");\n\n      ApiMetadata apiMd = md.getApiMetadata().toBuilder().buildVersion(null).build();\n      md = md.toBuilder().apiMetadata(apiMd).build();\n      Supplier<Credentials> creds = Suppliers.<Credentials> ofInstance(LoginCredentials.builder().user(\"user\").build());\n\n      ExpectedBindings bindings = Guice.createInjector(new BindProviderMetadataContextAndCredentials(md, creds))\n               .getInstance(ExpectedBindings.class);\n      assertEquals(bindings.buildVersion, null);\n   }\n\n   @Test\n   public void testProviderOverridesApiMetadataProperty() {\n      ProviderMetadata md = forApiOnEndpoint(IntegrationTestClient.class, \"http://localhost\");\n\n      Properties defaultProps = md.getDefaultProperties();\n      defaultProps.setProperty(Constants.PROPERTY_SESSION_INTERVAL, Integer.MAX_VALUE + \"\");\n      md = md.toBuilder().defaultProperties(defaultProps).build();\n\n      Supplier<Credentials> creds = Suppliers.<Credentials> ofInstance(LoginCredentials.builder().user(\"user\").build());\n\n      int session = Guice.createInjector(new BindProviderMetadataContextAndCredentials(md, creds)).getInstance(\n               Key.get(int.class, Names.named(Constants.PROPERTY_SESSION_INTERVAL)));\n      assertEquals(session, Integer.MAX_VALUE);\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/providers/internal/BaseProviderMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.providers.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.reflect.Reflection2.typeToken;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Set;\nimport java.util.logging.Logger;\n\nimport org.jclouds.View;\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.Providers;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.reflect.TypeToken;\n\n@Test(groups = \"unit\")\npublic abstract class BaseProviderMetadataTest {\n\n   private final ProviderMetadata toTest;\n   private final ApiMetadata expectedApi;\n   private final Set<TypeToken<? extends View>> views;\n\n   public BaseProviderMetadataTest(ProviderMetadata toTest, ApiMetadata expectedApi) {\n      this.toTest = checkNotNull(toTest, \"toTest must be defined\");\n      this.expectedApi = checkNotNull(expectedApi, \"expectedApi must be defined\");\n      this.views = expectedApi.getViews();\n   }\n\n   @Test\n   public void testWithId() {\n      ProviderMetadata providerMetadata = Providers.withId(toTest.getId());\n\n      assertEquals(toTest, providerMetadata);\n      assert providerMetadata.getLinkedServices().contains(toTest.getId());\n   }\n\n   @Test\n   public void testOfApiContains() {\n      if (expectedApi == null)\n         Logger.getAnonymousLogger().warning(\"please update your test class\");\n      ImmutableSet<ProviderMetadata> ofApi = ImmutableSet.copyOf(Providers.apiMetadataAssignableFrom(typeToken(expectedApi.getClass())));\n      assert ofApi.contains(toTest) : String.format(\"%s not found in %s\", toTest, ofApi);\n   }\n\n   @Test\n   public void testTransformableToContains() {\n      for (TypeToken<? extends View> view : views) {\n         ImmutableSet<ProviderMetadata> ofType = ImmutableSet.copyOf(Providers.viewableAs(view));\n         assert ofType.contains(toTest) : String.format(\"%s not found in %s for %s\", toTest, ofType,\n                  view);\n      }\n   }\n\n   @Test\n   public void testAllContains() {\n      ImmutableSet<ProviderMetadata> all = ImmutableSet.copyOf(Providers.all());\n      assert all.contains(toTest) : String.format(\"%s not found in %s\", toTest, all);\n   }\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/providers/internal/UpdateProviderMetadataFromPropertiesTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.providers.internal;\n\nimport static org.jclouds.Constants.PROPERTY_ISO3166_CODES;\nimport static org.jclouds.providers.AnonymousProviderMetadata.forApiOnEndpoint;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Properties;\n\nimport org.jclouds.Constants;\nimport org.jclouds.http.IntegrationTestClient;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\", testName = \"UpdateProviderMetadataFromPropertiesTest\")\npublic class UpdateProviderMetadataFromPropertiesTest {\n\n   @Test\n   public void testProviderMetadataWithUpdatedEndpointUpdatesAndRetainsAllDefaultPropertiesExceptEndpoint() {\n      ProviderMetadata md = forApiOnEndpoint(IntegrationTestClient.class, \"http://localhost\");\n\n      Properties props = new Properties();\n      props.putAll(md.getDefaultProperties());\n      props.setProperty(Constants.PROPERTY_ENDPOINT, \"http://nonlocal\");\n\n      ProviderMetadata newMd = new UpdateProviderMetadataFromProperties(md).apply(props);\n\n      assertEquals(newMd.getEndpoint(), \"http://nonlocal\");\n      assertEquals(newMd.getDefaultProperties(), md.getDefaultProperties());\n   }\n   \n   @Test\n   public void testProviderMetadataWithUpdatedIso3166CodesUpdatesAndRetainsAllDefaultPropertiesExceptIso3166Codes() {\n      ProviderMetadata md = forApiOnEndpoint(IntegrationTestClient.class, \"http://localhost\");\n\n      Properties props = new Properties();\n      props.putAll(md.getDefaultProperties());\n      props.setProperty(PROPERTY_ISO3166_CODES, \"US-CA\");\n\n      ProviderMetadata newMd = new UpdateProviderMetadataFromProperties(md).apply(props);\n\n      assertEquals(newMd.getIso3166Codes(), ImmutableSet.of(\"US-CA\"));\n      assertEquals(newMd.getDefaultProperties(), md.getDefaultProperties());\n   }\n   \n   //TODO: add all the rest of the tests\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/proxy/ProxyForURITest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.proxy;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.lang.reflect.Field;\nimport java.net.InetSocketAddress;\nimport java.net.Proxy;\nimport java.net.Proxy.Type;\nimport java.net.URI;\nimport java.net.URISyntaxException;\n\nimport org.jclouds.domain.Credentials;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.net.HostAndPort;\n\npublic class ProxyForURITest {\n\n   private Optional<HostAndPort> noHostAndPort = Optional.absent();\n   private Optional<Credentials> noCreds = Optional.absent();\n   private Optional<HostAndPort> hostAndPort = Optional.of(HostAndPort.fromParts(\"proxy.example.com\", 8080));\n   private Optional<Credentials> creds = Optional.of(new Credentials(\"user\", \"pwd\"));\n\n   private static class MyProxyConfig implements ProxyConfig {\n      private boolean useSystem;\n      private boolean jvmProxyEnabled;\n      private Type type;\n      private Optional<HostAndPort> proxy;\n      private Optional<Credentials> credentials;\n\n      MyProxyConfig(boolean useSystem, boolean jvmProxyEnabled, Type type, Optional<HostAndPort> proxy, Optional<Credentials> credentials) {\n         this.useSystem = useSystem;\n         this.jvmProxyEnabled = jvmProxyEnabled;\n         this.type = type;\n         this.proxy = proxy;\n         this.credentials = credentials;\n      }\n\n      @Override\n      public boolean useSystem() {\n         return useSystem;\n      }\n\n      @Override\n      public Type getType() {\n         return type;\n      }\n\n      @Override\n      public Optional<HostAndPort> getProxy() {\n         return proxy;\n      }\n\n      @Override\n      public Optional<Credentials> getCredentials() {\n         return credentials;\n      }\n\n      @Override\n      public boolean isJvmProxyEnabled() {\n         return jvmProxyEnabled;\n      }\n   }\n\n   @Test\n   public void testDontUseProxyForSockets() throws Exception {\n      ProxyConfig config = new MyProxyConfig(false, false, Proxy.Type.HTTP, hostAndPort, creds);\n      ProxyForURI proxy = new ProxyForURI(config);\n      Field useProxyForSockets = proxy.getClass().getDeclaredField(\"useProxyForSockets\");\n      useProxyForSockets.setAccessible(true);\n      useProxyForSockets.setBoolean(proxy, false);\n      URI uri = new URI(\"socket://ssh.example.com:22\");\n      assertEquals(proxy.apply(uri), Proxy.NO_PROXY);\n   }\n\n   @Test\n   public void testUseProxyForSockets() throws Exception {\n      ProxyConfig config = new MyProxyConfig(false, false, Proxy.Type.HTTP, hostAndPort, creds);\n      ProxyForURI proxy = new ProxyForURI(config);\n      URI uri = new URI(\"socket://ssh.example.com:22\");\n      assertEquals(proxy.apply(uri), new Proxy(Proxy.Type.HTTP, new InetSocketAddress(\"proxy.example.com\", 8080)));\n   }\n\n   @Test\n   public void testUseProxyForSocketsSettingShouldntAffectHTTP() throws Exception {\n      ProxyConfig config = new MyProxyConfig(false, false, Proxy.Type.HTTP, hostAndPort, creds);\n      ProxyForURI proxy = new ProxyForURI(config);\n      Field useProxyForSockets = proxy.getClass().getDeclaredField(\"useProxyForSockets\");\n      useProxyForSockets.setAccessible(true);\n      useProxyForSockets.setBoolean(proxy, false);\n      URI uri = new URI(\"http://example.com/file\");\n      assertEquals(proxy.apply(uri), new Proxy(Proxy.Type.HTTP, new InetSocketAddress(\"proxy.example.com\", 8080)));\n   }\n\n   @Test\n   public void testHTTPDirect() throws URISyntaxException {\n      ProxyConfig config = new MyProxyConfig(false, false, Proxy.Type.DIRECT, noHostAndPort, noCreds);\n      URI uri = new URI(\"http://example.com/file\");\n      assertEquals(new ProxyForURI(config).apply(uri), Proxy.NO_PROXY);\n   }\n\n   @Test\n   public void testHTTPSDirect() throws URISyntaxException {\n      ProxyConfig config = new MyProxyConfig(false, false, Proxy.Type.DIRECT, noHostAndPort, noCreds);\n      URI uri = new URI(\"https://example.com/file\");\n      assertEquals(new ProxyForURI(config).apply(uri), Proxy.NO_PROXY);\n   }\n\n   @Test\n   public void testFTPDirect() throws URISyntaxException {\n      ProxyConfig config = new MyProxyConfig(false, false, Proxy.Type.DIRECT, noHostAndPort, noCreds);\n      URI uri = new URI(\"ftp://ftp.example.com/file\");\n      assertEquals(new ProxyForURI(config).apply(uri), Proxy.NO_PROXY);\n   }\n\n   @Test\n   public void testSocketDirect() throws URISyntaxException {\n      ProxyConfig config = new MyProxyConfig(false, false, Proxy.Type.DIRECT, noHostAndPort, noCreds);\n      URI uri = new URI(\"socket://ssh.example.com:22\");\n      assertEquals(new ProxyForURI(config).apply(uri), Proxy.NO_PROXY);\n   }\n\n   @Test\n   public void testHTTPThroughHTTPProxy() throws URISyntaxException {\n      ProxyConfig config = new MyProxyConfig(false, false, Proxy.Type.HTTP, hostAndPort, creds);\n      URI uri = new URI(\"http://example.com/file\");\n      assertEquals(new ProxyForURI(config).apply(uri), new Proxy(Proxy.Type.HTTP, new InetSocketAddress(\n            \"proxy.example.com\", 8080)));\n   }\n\n   @Test\n   public void testThroughJvmProxy() throws URISyntaxException {\n      ProxyConfig config = new MyProxyConfig(false, true, Proxy.Type.HTTP, noHostAndPort, noCreds);\n      URI uri = new URI(\"http://example.com/file\");\n      // could return a proxy, could return NO_PROXY, depends on the tester's environment\n      assertNotNull(new ProxyForURI(config).apply(uri));\n   }\n\n   @Test\n   public void testThroughSystemProxy() throws URISyntaxException {\n      ProxyConfig config = new MyProxyConfig(true, false, Proxy.Type.HTTP, noHostAndPort, noCreds);\n      URI uri = new URI(\"http://example.com/file\");\n      // could return a proxy, could return NO_PROXY, depends on the tester's environment\n      assertNotNull(new ProxyForURI(config).apply(uri));\n   }\n\n   @Test\n   public void testJcloudsProxyHostsPreferredOverJvmProxy() throws URISyntaxException {\n      ProxyConfig test = new MyProxyConfig(true, true, Proxy.Type.HTTP, hostAndPort, noCreds);\n      ProxyConfig jclouds = new MyProxyConfig(false, false, Proxy.Type.HTTP, hostAndPort, noCreds);\n      ProxyConfig jvm = new MyProxyConfig(false, true, Proxy.Type.HTTP, noHostAndPort, noCreds);\n      URI uri = new URI(\"http://example.com/file\");\n      assertEquals(new ProxyForURI(test).apply(uri), new ProxyForURI(jclouds).apply(uri));\n      assertNotEquals(new ProxyForURI(test).apply(uri), new ProxyForURI(jvm).apply(uri));\n   }\n\n   @Test\n   public void testJvmProxyAlwaysPreferredOverSystem() throws URISyntaxException {\n      ProxyConfig test = new MyProxyConfig(true, true, Proxy.Type.HTTP, noHostAndPort, noCreds);\n      ProxyConfig jvm = new MyProxyConfig(false, true, Proxy.Type.HTTP, noHostAndPort, noCreds);\n      URI uri = new URI(\"http://example.com/file\");\n      assertEquals(new ProxyForURI(test).apply(uri), new ProxyForURI(jvm).apply(uri));\n   }\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/reflect/FunctionalReflectionTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.reflect;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.Closeable;\nimport java.io.IOException;\nimport java.util.Set;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableList;\n\n@Test(singleThreaded = true)\npublic class FunctionalReflectionTest {\n   \n   @SuppressWarnings(\"unchecked\")\n   @Test(expectedExceptions = UnsupportedOperationException.class)\n   public void testNullArgsAreAllowedAndUnmodifiable() {\n      final Function<Invocation, Object> test = new Function<Invocation, Object>() {\n         public Object apply(Invocation e) {\n            assertNotNull(e.getArgs());\n            assertNull(e.getArgs().get(0));\n            e.getArgs().add(\"foo\");\n            throw new AssertionError(\"shouldn't be able to mutate the list!\");\n         }\n      };\n      FunctionalReflection.newProxy(Set.class, test).add(null);\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Test(expectedExceptions = UnsupportedOperationException.class)\n   public void testImmutableListWhenArgsAreNotNull() {\n      final Function<Invocation, Object> test = new Function<Invocation, Object>() {\n         public Object apply(Invocation e) {\n            assertNotNull(e.getArgs());\n            assertTrue(e.getArgs() instanceof ImmutableList);\n            assertEquals(e.getArgs().get(0), \"foo\");\n            e.getArgs().add(\"bar\");\n            throw new AssertionError(\"shouldn't be able to mutate the list!\");\n         }\n      };\n      FunctionalReflection.newProxy(Set.class, test).add(\"foo\");\n   }\n\n   @Test(expectedExceptions = IOException.class, expectedExceptionsMessageRegExp = \"io\")\n   public void testPropagatesDeclaredException() throws IOException {\n      final Function<Invocation, Object> test = new Function<Invocation, Object>() {\n         public Object apply(Invocation e) {\n            throw new RuntimeException(new IOException(\"io\"));\n         }\n      };\n      Closeable closeable = FunctionalReflection.newProxy(Closeable.class, test);\n      closeable.close();\n   }\n\n   /**\n    * for example, someone could have enabled assertions, or there could be a recoverable ServiceConfigurationError\n    */\n   @Test(expectedExceptions = AssertionError.class, expectedExceptionsMessageRegExp = \"assert\")\n   public void testPropagatesError() throws IOException {\n      final Function<Invocation, Object> test = new Function<Invocation, Object>() {\n         public Object apply(Invocation e) {\n            throw new AssertionError(\"assert\");\n         }\n      };\n      Closeable closeable = FunctionalReflection.newProxy(Closeable.class, test);\n      closeable.close();\n   }\n\n   public void testToStringEqualsFunction() {\n      final Function<Invocation, Object> test = new Function<Invocation, Object>() {\n         public Object apply(Invocation e) {\n            return \"foo\";\n         }\n\n         public String toString() {\n            return \"bar\";\n         }\n      };\n      Closeable closeable = FunctionalReflection.newProxy(Closeable.class, test);\n      assertEquals(closeable.toString(), \"bar\");\n   }\n\n   public void testHashCodeDifferentiatesOnInterface() {\n      final Function<Invocation, Object> test = new Function<Invocation, Object>() {\n         public Object apply(Invocation e) {\n            return null;\n         }\n\n         public int hashCode() {\n            return 1111;\n         }\n      };\n      Appendable appendable1 = FunctionalReflection.newProxy(Appendable.class, test);\n      Appendable appendable2 = FunctionalReflection.newProxy(Appendable.class, test);\n      assertEquals(appendable1.hashCode(), appendable2.hashCode());\n\n      Closeable closeable = FunctionalReflection.newProxy(Closeable.class, test);\n      assertNotEquals(appendable1.hashCode(), closeable.hashCode());\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/reflect/Reflection2CoreJavaClassesTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.reflect;\n\nimport static org.easymock.EasyMock.createNiceMock;\nimport static org.easymock.EasyMock.expectLastCall;\nimport static org.easymock.EasyMock.replay;\nimport static org.jclouds.reflect.Reflection2.methods;\n\nimport java.lang.reflect.Method;\nimport java.lang.reflect.ReflectPermission;\n\nimport org.easymock.IAnswer;\nimport org.testng.SkipException;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\n/**\n * Tests {@link Reflection2#methods()} on core Java classes where\n * reflective access may be limited by a {@link SecurityManager}.\n *\n * This test has been separated out into a separate class as it modifies\n * a system-wide setting (the {@code SecurityManager}) and needs to perform \n * cleanup to avoid affecting other tests.\n */\n@Test(singleThreaded = true)\npublic class Reflection2CoreJavaClassesTest {\n   private SecurityManager originalSecurityManager;\n   private boolean securityManagerOverridden = false;\n\n   @BeforeClass\n   public void backupSecurityManager() {\n      originalSecurityManager = System.getSecurityManager();\n   }\n\n   public void testCoreJavaMethodsNotMadeAccessible(final Method testMethod) {\n      // a nice mock is required because plenty of other checks will be made\n      SecurityManager mockSecurityManager = createNiceMock(SecurityManager.class);\n      // clunky way of failing if the following method is ever called\n      mockSecurityManager.checkPermission(new ReflectPermission(\"suppressAccessChecks\"));\n      expectLastCall().andStubAnswer(new IAnswer<Void>() {\n            @Override\n            public Void answer() throws Throwable {\n               try {\n                  // generate a stacktrace\n                  throw new Exception();\n               } catch (Exception exception) {\n                  // fail *only* if being called from this test\n                  for (StackTraceElement element : exception.getStackTrace()) {\n                     if (element.getMethodName().equals(testMethod.getName())) {\n                        throw new AssertionError(\"checkPermission(new ReflectPermission(\\\"suppressAccessChecks\\\")) should not be called\");\n                     }\n                  }\n               }\n               return null;\n            }\n         });\n      replay(mockSecurityManager);\n      try {\n         System.setSecurityManager(mockSecurityManager);\n      } catch (UnsupportedOperationException uoe) {\n         throw new SkipException(\"Not compatible with Java 21\", uoe);\n      }\n\n      securityManagerOverridden = true;\n      methods(Enum.class);\n   }\n\n   @AfterClass(alwaysRun = true)\n   public void restoreSecurityManager() {\n      // will only be true if we have permission to set the SecurityManager \n      if (securityManagerOverridden) {\n         System.setSecurityManager(originalSecurityManager);\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/reflect/Reflection2OverriddenMethodTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.reflect;\n\nimport static com.google.common.base.Throwables.propagate;\nimport static org.testng.Assert.assertEquals;\n\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\nimport java.util.Set;\nimport java.util.SortedSet;\nimport java.util.concurrent.ExecutionException;\n\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.cache.ForwardingLoadingCache.SimpleForwardingLoadingCache;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.reflect.Invokable;\nimport com.google.common.reflect.TypeToken;\n\n/**\n * Tests {@link Reflection2#method(Class, String, Class...)} where\n * the method overrides one in parent classes and so bridge methods\n * need to be ignored.\n * \n * This test has been separated out into a separate class as it requires\n * reflection to modify the internal static caches of {@code Reflection2}\n * and needs to perform cleanup to avoid affecting other tests.\n */\n@Test\npublic class Reflection2OverriddenMethodTest {\n   private LoadingCache<TypeToken<?>, Set<Invokable<?, ?>>> originalMethodsForTypeToken;\n\n   @BeforeClass\n   public void backupMethodsForTypeToken() {\n      originalMethodsForTypeToken = getStaticField(Reflection2.class, \"methodsForTypeToken\");\n   }\n   \n   private static class ParentWithMethod {\n      @SuppressWarnings(\"unused\")\n      public Set<Object> method() {\n         return null;\n      }\n   }\n\n   private static class ChildOverridesAndNarrowsMethod extends ParentWithMethod {\n      @Override\n      public SortedSet<Object> method() {\n         return null;\n      }\n   }\n\n   public void testOverriddenMethodWithNarrowedReturnType() throws NoSuchMethodException {\n      // expecting two methods: the declared \"method\" and the bridge version with return type Set\n      final Method[] methods = ChildOverridesAndNarrowsMethod.class.getDeclaredMethods();\n      /*\n       * Force Reflection2.methodsForTypeToken to reflect the fact that the declared methods\n       * of a class are not returned in any particular order.\n       */\n      setStaticField(Reflection2.class, \"methodsForTypeToken\", keyOverridingCache(\n            TypeToken.of(ChildOverridesAndNarrowsMethod.class),\n            ImmutableSet.<Invokable<?, ?>>of(Invokable.from(methods[0]), Invokable.from(methods[1]))));\n      // getMethod returns the method with the *narrowest* return type if one exists\n      Invokable<?, Object> mostSpecificMethod = Invokable.from(ChildOverridesAndNarrowsMethod.class.getMethod(\"method\"));\n      assertEquals(Reflection2.method(ChildOverridesAndNarrowsMethod.class, \"method\"), \n            mostSpecificMethod);\n      \n      // now the opposite order\n      Reflection2OverriddenMethodTest.<LoadingCache<?, ?>>\n      getStaticField(Reflection2.class, \"methodForParams\").invalidateAll();\n      setStaticField(Reflection2.class, \"methodsForTypeToken\", keyOverridingCache(\n            TypeToken.of(ChildOverridesAndNarrowsMethod.class),\n            ImmutableSet.<Invokable<?, ?>>of(Invokable.from(methods[1]), Invokable.from(methods[0]))));\n      assertEquals(Reflection2.method(ChildOverridesAndNarrowsMethod.class, \"method\"), \n            mostSpecificMethod);\n   }\n\n   private LoadingCache<TypeToken<?>, Set<Invokable<?, ?>>> keyOverridingCache(\n         final TypeToken<?> overriddenKey, final Set<Invokable<?, ?>> value) {\n      return new SimpleForwardingLoadingCache<TypeToken<?>, Set<Invokable<?, ?>>>(originalMethodsForTypeToken) {\n         @Override\n         public Set<Invokable<?, ?>> get(TypeToken<?> key) throws ExecutionException {\n            return key.equals(overriddenKey) ? value : super.get(key);\n         }\n      };\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   private static <T> T getStaticField(Class<?> declaringClass, String fieldName) {\n      try {\n         Field field = declaringClass.getDeclaredField(fieldName);\n         field.setAccessible(true);\n         // static field\n         return (T) field.get(null);\n      } catch (NoSuchFieldException exception) {\n         throw propagate(exception);\n      } catch (IllegalAccessException exception) {\n         throw propagate(exception);\n      }\n   }\n\n   private static void setStaticField(Class<?> declaringClass, String fieldName, Object value) {\n      try {\n         Field field = declaringClass.getDeclaredField(fieldName);\n         field.setAccessible(true);\n         // static field\n         field.set(null, value);\n      } catch (NoSuchFieldException exception) {\n         throw propagate(exception);\n      } catch (IllegalAccessException exception) {\n         throw propagate(exception);\n      }\n   }\n\n   @AfterClass(alwaysRun = true)\n   public void restoreMethodsForTypeToken() {\n      setStaticField(Reflection2.class, \"methodsForTypeToken\", originalMethodsForTypeToken);\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/reflect/Reflection2Test.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.reflect;\n\nimport static com.google.common.base.Functions.toStringFunction;\nimport static org.jclouds.reflect.Reflection2.constructors;\nimport static org.jclouds.reflect.Reflection2.method;\nimport static org.jclouds.reflect.Reflection2.methods;\nimport static org.jclouds.reflect.Reflection2.typeToken;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.HashSet;\nimport java.util.Set;\nimport java.util.SortedSet;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicates;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.reflect.Invokable;\nimport com.google.common.reflect.Parameter;\nimport com.google.common.reflect.TypeToken;\nimport com.google.inject.TypeLiteral;\n\n@Test\npublic class Reflection2Test {\n\n   /**\n    * useful when converting to and from type literals from other libraries such as guice and gson.\n    */\n   public void testTypeTokenForType() {\n      TypeLiteral<Set<String>> guice = new TypeLiteral<Set<String>>() {\n      };\n\n      assertEquals(typeToken(guice.getType()), new TypeToken<Set<String>>() {\n         private static final long serialVersionUID = 1L;\n      });\n   }\n\n   public void testConstructors() {\n      Set<String> ctorParams = FluentIterable.from(constructors(TypeToken.of(HashSet.class)))\n            .transform(new Function<Invokable<?, ?>, Iterable<Parameter>>() {\n               public Iterable<Parameter> apply(Invokable<?, ?> input) {\n                  return input.getParameters();\n               }\n            }).transform(toStringFunction()).toSet();\n\n      assertEquals(ctorParams, ImmutableSet.of(\"[]\", \"[java.util.Collection<? extends E> arg0]\",\n            \"[int arg0, float arg1]\", \"[int arg0]\", \"[int arg0, float arg1, boolean arg2]\"));\n   }\n\n   private abstract static class MyValue {\n      abstract String foo();\n\n      static MyValue create(String foo){\n         return null;\n      }\n   }\n\n   public void testConstructorsReturnsFactoryMethods() {\n      Set<String> ctorParams = FluentIterable.from(constructors(TypeToken.of(MyValue.class)))\n            .transform(new Function<Invokable<?, ?>, Iterable<Parameter>>() {\n               public Iterable<Parameter> apply(Invokable<?, ?> input) {\n                  return input.getParameters();\n               }\n            }).transform(toStringFunction()).toSet();\n\n      assertEquals(ctorParams, ImmutableSet.of(\"[]\", \"[java.lang.String arg0]\"));\n   }\n\n   public void testTypeTokenForClass() {\n      assertEquals(typeToken(String.class), TypeToken.of(String.class));\n   }\n\n   public void testMethodFromJavaMethod() throws SecurityException, NoSuchMethodException {\n      assertEquals(method(typeToken(String.class), String.class.getMethod(\"toString\")), TypeToken.of(String.class)\n            .method(String.class.getMethod(\"toString\")).returning(String.class));\n   }\n\n   public void testMethodFromClassAndNoParams() {\n      @SuppressWarnings(\"rawtypes\")\n      Invokable<Set, Object> methodInSuper = method(Set.class, \"iterator\");\n\n      assertEquals(methodInSuper.getOwnerType(), typeToken(Set.class));\n   }\n\n   public void testMethodFromClassAndParams() {\n      @SuppressWarnings(\"rawtypes\")\n      Invokable<Set, Object> methodInSuper = method(Set.class, \"equals\", Object.class);\n\n      assertEquals(methodInSuper.getOwnerType(), typeToken(Set.class));\n      assertEquals(methodInSuper.getParameters().get(0).getType().getRawType(), Object.class);\n   }\n\n   private static final ImmutableSet<String> SET_METHODS = ImmutableSet.of(\n         // Java 6 and 7 methods\n         \"add\",\n         \"addAll\",\n         \"clear\",\n         \"contains\",\n         \"containsAll\",\n         \"equals\",\n         \"hashCode\",\n         \"isEmpty\",\n         \"iterator\",\n         \"remove\",\n         \"removeAll\",\n         \"retainAll\",\n         \"size\",\n         \"toArray\",\n         // Java 8 methods\n         \"forEach\",\n         \"parallelStream\",\n         \"removeIf\",\n         \"spliterator\",\n         \"stream\",\n         // Java 9 methods\n         \"of\",\n         // Java 10 methods\n         \"copyOf\");\n\n   private static final ImmutableSet<String> SORTED_SET_METHODS = ImmutableSet.<String>builder()\n         .addAll(SET_METHODS)\n         .add(\"comparator\")\n         .add(\"first\")\n         .add(\"headSet\")\n         .add(\"last\")\n         .add(\"subSet\")\n         .add(\"tailSet\")\n         // Java 21 methods\n         .add(\"getFirst\")\n         .add(\"getLast\")\n         .add(\"addFirst\")\n         .add(\"addLast\")\n         .add(\"removeFirst\")\n         .add(\"removeLast\")\n         .add(\"reversed\")\n         .build();\n\n\n   public void testMethods() {\n      Set<String> methodNames = FluentIterable.from(methods(Set.class)).transform(invokableToName)\n            .transform(toStringFunction())\n            .filter(Predicates.not(Predicates.<String>in(SET_METHODS)))\n            .toSet();\n\n      assertEquals(methodNames, ImmutableSet.<String>of());\n   }\n\n   public void testMethodsSubClass() {\n      Set<String> methodNames = FluentIterable.from(methods(SortedSet.class)).transform(invokableToName)\n            .transform(toStringFunction())\n            .filter(Predicates.not(Predicates.<String>in(SORTED_SET_METHODS)))\n            .toSet();\n\n      assertEquals(methodNames, ImmutableSet.<String>of());\n   }\n\n   static final Function<Invokable<?, ?>, String> invokableToName = new Function<Invokable<?, ?>, String>() {\n      public String apply(Invokable<?, ?> input) {\n         return input.getName();\n      }\n   };\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/rest/CredentialStoreModuleTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.util.Map;\nimport java.util.concurrent.ConcurrentHashMap;\n\nimport org.jclouds.crypto.PemsTest;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.json.Json;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.rest.config.CredentialStoreModule;\nimport org.testng.annotations.DataProvider;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.base.Function;\nimport com.google.common.io.ByteSource;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport com.google.inject.Key;\nimport com.google.inject.TypeLiteral;\n\n@Test(groups = \"unit\", singleThreaded = true)\npublic class CredentialStoreModuleTest {\n   Json json = createInjector().getInstance(Json.class);\n\n   @DataProvider(name = \"credentials\")\n   public Object[][] createData() {\n      return new Object[][] {\n            { \"root\", PemsTest.PRIVATE_KEY },\n            { \"identity\", \"Base64==\" },\n            { \"user@domain\", \"pa$sw@rd\" },\n            { \"user\", \"unic₪de\" }\n      };\n   }\n\n   @Test(dataProvider = \"credentials\")\n   public void deleteObject(String identity, String credential) throws InterruptedException, IOException {\n      Injector injector = createInjector();\n      Map<String, ByteSource> map = getMap(injector);\n      check(map, getStore(injector), \"i-20312\", new Credentials(identity, credential));\n   }\n\n   public void testProvidedMapWithValue() throws IOException {\n      Map<String, ByteSource> map = new ConcurrentHashMap<String, ByteSource>();\n\n      map.put(\"test\", ByteSource.wrap(json.toJson(new Credentials(\"user\", \"pass\")).getBytes()));\n      checkConsistent(map, getStore(createInjectorWithProvidedMap(map)), \"test\", new Credentials(\"user\", \"pass\"));\n      checkConsistent(map, getStore(createInjectorWithProvidedMap(map)), \"test\", new Credentials(\"user\", \"pass\"));\n      remove(map, getStore(createInjectorWithProvidedMap(map)), \"test\");\n\n   }\n\n   public void testProvidedConsistentAcrossRepeatedWrites() throws IOException {\n      Map<String, ByteSource> map = new ConcurrentHashMap<String, ByteSource>();\n\n      Injector injector = createInjectorWithProvidedMap(map);\n      assertEquals(injector.getInstance(Key.get(new TypeLiteral<Map<String, ByteSource>>() {\n      })), map);\n      Map<String, Credentials> store = getStore(injector);\n\n      for (int i = 0; i < 10; i++)\n         check(map, store, \"test\" + i, new Credentials(\"user\" + i, \"pass\" + i));\n\n   }\n\n   public void testProvidedConsistentAcrossMultipleInjectors() throws IOException {\n      Map<String, ByteSource> map = new ConcurrentHashMap<String, ByteSource>();\n\n      put(map, getStore(createInjectorWithProvidedMap(map)), \"test\", new Credentials(\"user\", \"pass\"));\n      checkConsistent(map, getStore(createInjectorWithProvidedMap(map)), \"test\", new Credentials(\"user\", \"pass\"));\n      checkConsistent(map, getStore(createInjectorWithProvidedMap(map)), \"test\", new Credentials(\"user\", \"pass\"));\n      remove(map, getStore(createInjectorWithProvidedMap(map)), \"test\");\n\n   }\n\n   public void testDefaultDifferentAcrossMultipleInjectors() throws IOException {\n      Injector injector = createInjector();\n      Map<String, ByteSource> map = getMap(injector);\n      put(map, getStore(injector), \"test\", new Credentials(\"user\", \"pass\"));\n\n      Map<String, Credentials> anotherStore = getStore(createInjector());\n      assertEquals(anotherStore.size(), 0);\n      assertFalse(anotherStore.containsKey(\"test\"));\n   }\n\n   public void testLoginDifferentAcrossMultipleInjectorsAndLooksNice() throws IOException {\n      Injector injector = createInjector();\n      Map<String, ByteSource> map = getMap(injector);\n      LoginCredentials creds = LoginCredentials.builder().user(\"user\").password(\"pass\").build();\n      Map<String, Credentials> store = getStore(injector);\n      put(map, store, \"test\", creds);\n      checkConsistent(map, store, \"test\", creds, \"{\\\"user\\\":\\\"user\\\",\\\"password\\\":\\\"pass\\\"}\");\n      checkConsistent(map, store, \"test\", creds, \"{\\\"user\\\":\\\"user\\\",\\\"password\\\":\\\"pass\\\"}\");\n      remove(map, store, \"test\");\n   }\n\n   public void testLoginDifferentAcrossMultipleInjectorsAndLooksNiceWithSudo() throws IOException {\n      Injector injector = createInjector();\n      Map<String, ByteSource> map = getMap(injector);\n      LoginCredentials creds = LoginCredentials.builder().user(\"user\").password(\"pass\").authenticateSudo(true).build();\n      Map<String, Credentials> store = getStore(injector);\n      put(map, store, \"test\", creds);\n      checkConsistent(map, store, \"test\", creds,\n            \"{\\\"user\\\":\\\"user\\\",\\\"password\\\":\\\"pass\\\",\\\"authenticateSudo\\\":true}\");\n      checkConsistent(map, store, \"test\", creds,\n            \"{\\\"user\\\":\\\"user\\\",\\\"password\\\":\\\"pass\\\",\\\"authenticateSudo\\\":true}\");\n      remove(map, store, \"test\");\n   }\n\n   public void testCredentialsToByteSourceConversion() throws Exception {\n      Function<Credentials, ByteSource> toBytesFunc = getCredentialsToByteStoreFunction(createInjector());\n      Function<ByteSource, Credentials> fromBytesFunc = getByteStoreToCredentialsFunction(createInjector());\n      \n      LoginCredentials creds = LoginCredentials.builder().user(\"myuser\").password(\"mypass\").authenticateSudo(true).build();\n      ByteSource bytes = toBytesFunc.apply(creds);\n      LoginCredentials deserializedCreds = (LoginCredentials) fromBytesFunc.apply(bytes);\n      \n      String json = bytes.asCharSource(Charsets.UTF_8).read();\n      assertEquals(json, \"{\\\"user\\\":\\\"myuser\\\",\\\"password\\\":\\\"mypass\\\",\\\"authenticateSudo\\\":true}\");\n      \n      assertEquals(deserializedCreds.identity, creds.identity);\n      assertEquals(deserializedCreds.credential, creds.credential);\n      assertEquals(deserializedCreds.getUser(), creds.getUser());\n      assertEquals(deserializedCreds.getOptionalPassword(), creds.getOptionalPassword());\n      assertEquals(deserializedCreds.getOptionalPrivateKey(), creds.getOptionalPrivateKey());\n      assertEquals(deserializedCreds.shouldAuthenticateSudo(), creds.shouldAuthenticateSudo());\n   }\n   \n   protected Map<String, Credentials> getStore(Injector injector) {\n      return injector.getInstance(Key.get(new TypeLiteral<Map<String, Credentials>>() {\n      }));\n   }\n\n   protected Map<String, ByteSource> getMap(Injector injector) {\n      return injector.getInstance(Key.get(new TypeLiteral<Map<String, ByteSource>>() {\n      }));\n   }\n\n   protected Function<ByteSource, Credentials> getByteStoreToCredentialsFunction(Injector injector) {\n      return injector.getInstance(Key.get(new TypeLiteral<Function<ByteSource, Credentials>>() {\n      }));\n   }\n\n   protected Function<Credentials, ByteSource> getCredentialsToByteStoreFunction(Injector injector) {\n      return injector.getInstance(Key.get(new TypeLiteral<Function<Credentials, ByteSource>>() {\n      }));\n   }\n   \n   protected Injector createInjectorWithProvidedMap(Map<String, ByteSource> map) {\n      return Guice.createInjector(new CredentialStoreModule(map), new GsonModule());\n   }\n\n   protected Injector createInjector() {\n      return Guice.createInjector(new CredentialStoreModule(), new GsonModule());\n   }\n\n   protected void check(Map<String, ByteSource> map, Map<String, Credentials> store, String key, Credentials creds)\n         throws IOException {\n      put(map, store, key, creds);\n      checkConsistent(map, store, key, creds);\n      remove(map, store, key);\n   }\n\n   protected void remove(Map<String, ByteSource> map, Map<String, Credentials> store, String key) {\n      store.remove(key);\n      assertEquals(store.size(), 0);\n      assertEquals(map.size(), 0);\n      assertEquals(store.get(key), null);\n      assertEquals(map.get(key), null);\n   }\n\n   protected void checkConsistent(Map<String, ByteSource> map, Map<String, Credentials> store, String key,\n         Credentials creds) throws IOException {\n      checkConsistent(map, store, key, creds, json.toJson(creds));\n   }\n\n   protected void checkConsistent(Map<String, ByteSource> map, Map<String, Credentials> store, String key,\n         Credentials creds, String expected) throws IOException {\n      assertEquals(store.size(), 1);\n      assertEquals(map.size(), 1);\n      assertTrue(store.containsKey(key));\n      //System.out.println(\"YYYYYY \" + store.get(key));\n      //System.err.println(\"YYYYYY \" + store.get(key));\n      assertTrue(store.containsValue(creds));\n      // checkRepeatedRead\n      assertEquals(store.get(key), creds);\n      assertEquals(store.get(key), creds);\n      // checkRepeatedRead\n      checkToJson(map, key, expected);\n      checkToJson(map, key, expected);\n   }\n\n   protected void checkToJson(Map<String, ByteSource> map, String key, String expected) throws IOException {\n      assertEquals(map.get(key).asCharSource(Charsets.UTF_8).read(), expected);\n   }\n\n   protected void put(Map<String, ByteSource> map, Map<String, Credentials> store, String key, Credentials creds) {\n      assertEquals(store.size(), 0);\n      assertEquals(map.size(), 0);\n      assertFalse(store.containsKey(key));\n      assertFalse(store.containsValue(creds));\n      store.put(key, creds);\n      //System.err.printf(\"XXXXXXXXXX\\n\\nStore has %n: %s\\n\\nXXXXXXXXXX\\n\", store.size(), Joiner.on(\", \").withKeyValueSeparator(\"=\").useForNull(\"<<EMPTY>>\").join(store));\n      //System.out.printf(\"XXXXXXXXXX\\n\\nStore has %n: %s\\n\\nXXXXXXXXXX\\n\", store.size(), Joiner.on(\", \").withKeyValueSeparator(\"=\").useForNull(\"<<EMPTY>>\").join(store));\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/rest/InputParamValidatorTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest;\n\nimport static org.jclouds.providers.AnonymousProviderMetadata.forApiOnEndpoint;\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PathParam;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.IntegrationTestClient;\nimport org.jclouds.predicates.validators.AllLowerCaseValidator;\nimport org.jclouds.reflect.Invocation;\nimport org.jclouds.rest.annotations.ParamValidators;\nimport org.jclouds.rest.internal.RestAnnotationProcessor;\nimport org.testng.TestException;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.reflect.Invokable;\nimport com.google.inject.Injector;\n@Test(groups = \"unit\")\npublic class InputParamValidatorTest {\n\n   private interface InputParamValidatorForm {\n      @POST\n      @ParamValidators(AllLowerCaseValidator.class)\n      void allParamsValidated(@PathParam(\"param1\") String param1, @PathParam(\"param2\") String param2);\n\n      @POST\n      void oneParamValidated(@PathParam(\"param1\") String param1,\n            @ParamValidators(AllLowerCaseValidator.class) @PathParam(\"param2\") String param2);\n   }\n\n   /**\n    * Tests {@link AllLowerCaseValidator} against lowercase and uppercase inputs, both on method\n    * level and parameter level.\n    * \n    * @throws Exception\n    *            if methods aren't found\n    */\n   @Test\n   public void testInputParamsValidation() throws Exception {\n      Invokable<?, ?> allParamsValidatedMethod = method(InputParamValidatorForm.class, \"allParamsValidated\",\n            String.class, String.class);\n      Invokable<?, ?> oneParamValidatedMethod = method(InputParamValidatorForm.class, \"oneParamValidated\",\n            String.class, String.class);\n      restAnnotationProcessor.apply(Invocation.create(allParamsValidatedMethod, ImmutableList.<Object> of(\"blah\", \"blah\")));\n      restAnnotationProcessor.apply(Invocation.create(oneParamValidatedMethod, ImmutableList.<Object> of(\"blah\", \"blah\")));\n\n      try {\n         restAnnotationProcessor.apply(Invocation.create(allParamsValidatedMethod, ImmutableList.<Object> of(\"BLAH\", \"blah\")));\n         throw new TestException(\n                  \"AllLowerCaseValidator shouldn't have passed 'BLAH' as a parameter because it's uppercase.\");\n      } catch (IllegalArgumentException e) {\n         // supposed to happen - continue\n      }\n\n      restAnnotationProcessor.apply(Invocation.create(oneParamValidatedMethod, ImmutableList.<Object> of(\"BLAH\", \"blah\")));\n\n      try {\n         restAnnotationProcessor.apply(Invocation.create(oneParamValidatedMethod, ImmutableList.<Object> of(\"blah\", \"BLAH\")));\n         throw new TestException(\n                  \"AllLowerCaseValidator shouldn't have passed 'BLAH' as the second parameter because it's uppercase.\");\n      } catch (IllegalArgumentException e) {\n         // supposed to happen - continue\n      }\n   }\n\n   @Test\n   public void testNullParametersForAllLowerCaseValidator() {\n      new AllLowerCaseValidator().validate(null);\n   }\n\n   private interface WrongValidator {\n      @POST\n      @ParamValidators(AllLowerCaseValidator.class)\n      void method(@PathParam(\"param1\") Integer param1);\n   }\n\n   @Test(expectedExceptions = ClassCastException.class)\n   public void testWrongPredicateTypeLiteral() throws Exception {\n      Invocation invocation = Invocation.create(method(WrongValidator.class, \"method\", Integer.class),\n            ImmutableList.<Object> of(55));\n      new InputParamValidator(injector).validateMethodParametersOrThrow(invocation, invocation.getInvokable().getParameters());\n   }\n\n   Injector injector;\n   Function<Invocation, HttpRequest> restAnnotationProcessor;\n\n   @BeforeClass\n   void setupFactory() {\n      injector = ContextBuilder.newBuilder(forApiOnEndpoint(IntegrationTestClient.class, \"http://localhost:9999\"))\n            .buildInjector();\n      restAnnotationProcessor = injector.getInstance(RestAnnotationProcessor.class);\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/rest/annotationparsing/ClosableApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.annotationparsing;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\n\nimport java.io.Closeable;\nimport java.io.IOException;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.concurrent.config.ExecutorServiceModule;\nimport org.jclouds.providers.AnonymousProviderMetadata;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.inject.Module;\n\n/**\n * ensures that jclouds can be operated w/o reference to a context as the Api\n * itself is closeable.\n */\n@Test(groups = \"unit\", testName = \"ClosableApiTest\")\npublic class ClosableApiTest {\n\n   interface DelegatingApi extends Closeable {\n   }\n\n   ProviderMetadata provider = AnonymousProviderMetadata.forApiOnEndpoint(DelegatingApi.class, \"http://mock\");\n\n   public void testApiClosesExecutorServiceOnClose() throws IOException {\n      ListeningExecutorService executor = createMock(ListeningExecutorService.class);\n\n      expect(executor.shutdownNow()).andReturn(ImmutableList.<Runnable> of()).atLeastOnce();\n\n      replay(executor);\n\n      DelegatingApi api = ContextBuilder.newBuilder(provider)\n                                        .modules(ImmutableSet.<Module> builder()\n                                                             .add(new ExecutorServiceModule(executor))\n                                                             .build())\n                                        .buildApi(DelegatingApi.class);\n      api.close();\n      verify(executor);\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/rest/annotationparsing/DelegateAnnotationExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.annotationparsing;\n\nimport static org.jclouds.providers.AnonymousProviderMetadata.forApiOnEndpoint;\nimport static org.testng.Assert.assertTrue;\n\nimport jakarta.ws.rs.FormParam;\nimport jakarta.ws.rs.HEAD;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\n\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.annotations.Delegate;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.config.HttpApiModule;\nimport org.jclouds.rest.internal.BaseRestApiExpectTest;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Module;\n\n/**\n * Tests the ways that {@link Delegate}\n */\n@Test(groups = \"unit\", testName = \"DelegateAnnotationExpectTest\")\npublic class DelegateAnnotationExpectTest extends BaseRestApiExpectTest<DelegateAnnotationExpectTest.DelegatingApi> {\n\n   interface DelegatingApi {\n      @Delegate\n      DiskApi getDiskApiForProjectForm(@FormParam(\"project\") String projectName);\n\n      @Delegate\n      @Path(\"/projects/{project}\")\n      DiskApi getDiskApiForProject(@PayloadParam(\"project\") @PathParam(\"project\") String projectName);\n   }\n\n   interface DiskApi {\n      @POST\n      void form();\n\n      @POST\n      @Payload(\"<Sync>{project}</Sync>\")\n      void syncAll();\n\n      @HEAD\n      @Path(\"/disks/{disk}\")\n      @Fallback(FalseOnNotFoundOr404.class)\n      boolean exists(@PathParam(\"disk\") String diskName);\n   }\n\n   public void testDelegatingCallTakesIntoConsiderationAndCalleeFormParam() {\n\n      DelegatingApi client = requestSendsResponse(HttpRequest.builder().method(\"POST\").endpoint(\"http://mock\")\n            .addFormParam(\"project\", \"prod\").build(), HttpResponse.builder().statusCode(200).build());\n\n      client.getDiskApiForProjectForm(\"prod\").form();\n   }\n\n   public void testDelegatingCallTakesIntoConsiderationAndCalleePayloadParam() {\n\n      DelegatingApi client = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\")\n                       .endpoint(\"http://mock/projects/prod\")\n                       .payload(\"<Sync>prod</Sync>\").build(),\n            HttpResponse.builder().statusCode(200).build());\n\n      client.getDiskApiForProject(\"prod\").syncAll();\n   }\n\n   public void testDelegatingCallTakesIntoConsiderationCallerAndCalleePath() {\n\n      DelegatingApi client = requestSendsResponse(\n            HttpRequest.builder().method(\"HEAD\").endpoint(\"http://mock/projects/prod/disks/disk1\").build(),\n            HttpResponse.builder().statusCode(200).build());\n\n      assertTrue(client.getDiskApiForProject(\"prod\").exists(\"disk1\"));\n   }\n\n   // crufty junk until we inspect delegating api classes for all their client\n   // mappings and make a test helper for random classes.\n\n   @Override\n   public ProviderMetadata createProviderMetadata() {\n      return forApiOnEndpoint(DelegatingApi.class, \"http://mock\");\n   }\n\n   @Override\n   protected Module createModule() {\n      return new DelegatingHttpApiModule();\n   }\n\n   @ConfiguresHttpApi\n   static class DelegatingHttpApiModule extends HttpApiModule<DelegatingApi> {\n   }\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/rest/annotationparsing/JAXBResponseParserAnnotationExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.annotationparsing;\n\nimport static org.jclouds.providers.AnonymousProviderMetadata.forApiOnEndpoint;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.Closeable;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.core.MediaType;\nimport jakarta.xml.bind.annotation.XmlRootElement;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.rest.annotations.JAXBResponseParser;\nimport org.jclouds.rest.annotations.Transform;\nimport org.jclouds.rest.internal.BaseRestApiExpectTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Functions;\n\n/**\n * Tests the use of the {@link JAXBResponseParser} annotation.\n */\n@Test(groups = \"unit\", testName = \"JAXBResponseParserAnnotationExpectTest\")\npublic class JAXBResponseParserAnnotationExpectTest extends\n      BaseRestApiExpectTest<JAXBResponseParserAnnotationExpectTest.TestJAXBApi> {\n\n   @XmlRootElement(name = \"test\")\n   public static class TestJAXBDomain {\n      private String elem;\n\n      public String getElem() {\n         return elem;\n      }\n\n      public void setElem(String elem) {\n         this.elem = elem;\n      }\n\n      @Override\n      public String toString() {\n         return \"TestJAXBDomain [elem=\" + elem + \"]\";\n      }\n\n   }\n\n   public interface TestJAXBApi extends Closeable {\n      @GET\n      @Path(\"/jaxb/annotation\")\n      @JAXBResponseParser\n      TestJAXBDomain jaxbGetWithAnnotation();\n\n      @GET\n      @Path(\"/jaxb/custom\")\n      @JAXBResponseParser(TestJAXBDomain.class)\n      Object jaxbGetWithAnnotationAndCustomClass();\n\n      @GET\n      @Path(\"/jaxb/header\")\n      @Consumes(MediaType.APPLICATION_XML)\n      TestJAXBDomain jaxbGetWithAcceptHeader();\n\n      @GET\n      @Path(\"/jaxb/transformer\")\n      @JAXBResponseParser(TestJAXBDomain.class)\n      @Transform(ToString.class)\n      String jaxbGetWithTransformer();\n   }\n\n   private static class ToString implements Function<Object, String> {\n      @Override\n      public String apply(Object input) {\n         return Functions.toStringFunction().apply(input);\n      }\n   }\n\n   @Test\n   public void testJAXBResponseParserAnnotationWithoutValue() throws SecurityException, NoSuchMethodException {\n      TestJAXBApi api = requestSendsResponse( //\n            HttpRequest.builder().method(\"GET\").endpoint(\"http://mock/jaxb/annotation\").build(), //\n            HttpResponse.builder().statusCode(200).payload(\"<test><elem>Hello World</elem></test>\").build());\n\n      TestJAXBDomain result = api.jaxbGetWithAnnotation();\n      assertEquals(result.getElem(), \"Hello World\");\n   }\n\n   @Test\n   public void testJAXBResponseParserAnnotationWithCustomValue() throws SecurityException, NoSuchMethodException {\n      TestJAXBApi api = requestSendsResponse( //\n            HttpRequest.builder().method(\"GET\").endpoint(\"http://mock/jaxb/custom\").build(), //\n            HttpResponse.builder().statusCode(200).payload(\"<test><elem>Hello World</elem></test>\").build());\n\n      Object result = api.jaxbGetWithAnnotationAndCustomClass();\n      assertTrue(result instanceof TestJAXBDomain);\n      assertEquals(TestJAXBDomain.class.cast(result).getElem(), \"Hello World\");\n   }\n\n   @Test\n   public void testJAXBResponseParserAnnotationWithAcceptHeader() throws SecurityException, NoSuchMethodException {\n      TestJAXBApi api = requestSendsResponse( //\n            HttpRequest.builder().method(\"GET\").endpoint(\"http://mock/jaxb/header\")\n                  .addHeader(\"Accept\", MediaType.APPLICATION_XML).build(), //\n            HttpResponse.builder().statusCode(200).payload(\"<test><elem>Hello World</elem></test>\").build());\n\n      TestJAXBDomain result = api.jaxbGetWithAcceptHeader();\n      assertEquals(result.getElem(), \"Hello World\");\n   }\n\n   @Test\n   public void testJAXBResponseParserAnnotationWithTransformer() throws SecurityException, NoSuchMethodException {\n      TestJAXBApi api = requestSendsResponse( //\n            HttpRequest.builder().method(\"GET\").endpoint(\"http://mock/jaxb/transformer\").build(), //\n            HttpResponse.builder().statusCode(200).payload(\"<test><elem>Hello World</elem></test>\").build());\n\n      String result = api.jaxbGetWithTransformer();\n      assertEquals(result, \"TestJAXBDomain [elem=Hello World]\");\n   }\n\n   @Override\n   public ProviderMetadata createProviderMetadata() {\n      return forApiOnEndpoint(TestJAXBApi.class, \"http://mock\");\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/rest/annotationparsing/PATCHAnnotationExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.annotationparsing;\n\nimport static org.jclouds.providers.AnonymousProviderMetadata.forApiOnEndpoint;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.Closeable;\n\nimport jakarta.ws.rs.Path;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.rest.annotations.PATCH;\nimport org.jclouds.rest.internal.BaseRestApiExpectTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests the use of the {@link PATCH} annotation.\n */\n@Test(groups = \"unit\", testName = \"PATCHAnnotationExpectTest\")\npublic class PATCHAnnotationExpectTest extends\n      BaseRestApiExpectTest<PATCHAnnotationExpectTest.TestPATCHAnnotationApi> {\n\n   interface TestPATCHAnnotationApi extends Closeable {\n      @PATCH\n      @Path(\"/PATCH/annotation\")\n      HttpResponse method();\n   }\n\n   @Test\n   public void testPATCHAnnotation() {\n      HttpResponse response = HttpResponse.builder().statusCode(200).build();\n      TestPATCHAnnotationApi testPATCH = requestSendsResponse(\n            HttpRequest.builder().method(\"PATCH\").endpoint(\"http://mock/PATCH/annotation\").build(), response);\n      assertEquals(testPATCH.method(), response, \"PATCH\");\n   }\n\n   @Override\n   public ProviderMetadata createProviderMetadata() {\n      return forApiOnEndpoint(TestPATCHAnnotationApi.class, \"http://mock\");\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/rest/annotationparsing/ProvidesAnnotationExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.annotationparsing;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.Closeable;\nimport java.util.NoSuchElementException;\nimport java.util.Set;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.providers.AnonymousProviderMetadata;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.config.HttpApiModule;\nimport org.jclouds.rest.internal.BaseRestApiExpectTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\nimport com.google.inject.Provides;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.name.Names;\n\n/**\n * Tests that we can add {@link Provides} methods on interfaces\n */\n@Test(groups = \"unit\", testName = \"ProvidesAnnotationExpectTest\")\npublic class ProvidesAnnotationExpectTest extends BaseRestApiExpectTest<ProvidesAnnotationExpectTest.ProvidingApi> {\n\n   interface ProvidingApi extends Closeable {\n      @Provides\n      Set<String> set();\n\n      @Named(\"bar\")\n      @Provides\n      Set<String> foo();\n\n      @Named(\"exception\")\n      @Provides\n      Set<String> exception();\n\n      @Named(\"NoSuchElementException\")\n      @Provides\n      Set<String> noSuchElementException();\n   }\n\n   @Test\n   public void testProvidesWithGeneric() {\n      ProvidingApi client = requestsSendResponses(ImmutableMap.<HttpRequest, HttpResponse> of());\n      assertEquals(client.set(), ImmutableSet.of(\"foo\"));\n   }\n\n   @Test\n   public void testProvidesWithGenericQualified() {\n      ProvidingApi client = requestsSendResponses(ImmutableMap.<HttpRequest, HttpResponse> of());\n      assertEquals(client.foo(), ImmutableSet.of(\"bar\"));\n   }\n\n   @Test(expectedExceptions = AuthorizationException.class)\n   public void testProvidesWithGenericQualifiedAuthorizationException() {\n      ProvidingApi client = requestsSendResponses(ImmutableMap.<HttpRequest, HttpResponse> of());\n      client.exception();\n   }\n\n   @Test(expectedExceptions = NoSuchElementException.class)\n   public void testProvidesWithGenericQualifiedNoSuchElementException() {\n      ProvidingApi client = requestsSendResponses(ImmutableMap.<HttpRequest, HttpResponse> of());\n      client.noSuchElementException();\n   }\n\n   // crufty junk until we inspect delegating api classes for all their client\n   // mappings and make a test helper for random classes.\n\n   @Override\n   public ProviderMetadata createProviderMetadata() {\n      return AnonymousProviderMetadata.forApiOnEndpoint(ProvidingApi.class, \"http://mock\");\n   }\n\n   @Override\n   protected Module createModule() {\n      return new ProvidingHttpApiModule();\n   }\n\n   @ConfiguresHttpApi\n   static class ProvidingHttpApiModule extends HttpApiModule<ProvidingApi> {\n\n      @Override\n      protected void configure() {\n         super.configure();\n         bind(new TypeLiteral<Set<String>>() {\n         }).toInstance(ImmutableSet.of(\"foo\"));\n         bind(new TypeLiteral<Set<String>>() {\n         }).annotatedWith(Names.named(\"bar\")).toInstance(ImmutableSet.of(\"bar\"));\n      }\n\n      @Provides\n      @Named(\"exception\")\n      Set<String> exception() {\n         throw new AuthorizationException();\n      }\n\n      @Provides\n      @Named(\"NoSuchElementException\")\n      Set<String> noSuchElementException() {\n         throw new NoSuchElementException();\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/rest/binders/BindAsHostPrefixIfConfiguredTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.http.HttpRequest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code BindAsHostPrefix}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"BindAsHostPrefixTest\")\npublic class BindAsHostPrefixIfConfiguredTest {\n\n   public void testPrefixValid() {\n\n      BindAsHostPrefix binder = new BindAsHostPrefix();\n\n      HttpRequest request = binder.bindToRequest(HttpRequest.builder().method(\"GET\").endpoint(\"https://s3.amazonaws.com\").build(),\n            \"bucket\");\n      assertEquals(request.getRequestLine(), \"GET https://bucket.s3.amazonaws.com HTTP/1.1\");\n\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testPrefixInvalidHostname() {\n\n      BindAsHostPrefix binder = new BindAsHostPrefix();\n\n      binder.bindToRequest(HttpRequest.builder().method(\"GET\").endpoint(\"https://s3.amazonaws.com\").build(), \"b_ucket\");\n\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/rest/binders/BindMapToStringPayloadTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.binders;\n\nimport static org.jclouds.reflect.Reflection2.method;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.File;\n\nimport jakarta.ws.rs.PathParam;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.reflect.Invocation;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.reflect.Invokable;\n/**\n * Tests behavior of {@code BindMapToStringPayload}\n */\n@Test(groups = \"unit\")\npublic class BindMapToStringPayloadTest {\n   interface TestPayload {\n      @org.jclouds.rest.annotations.Payload(\"name {fooble}\")\n      void testPayload(@PathParam(\"foo\") String path);\n\n      void noPayload(String path);\n      \n      @Payload(\"%7B\\\"changePassword\\\":%7B\\\"adminPass\\\":\\\"{adminPass}\\\"%7D%7D\")\n      void changeAdminPass(@PayloadParam(\"adminPass\") String adminPass);\n   }\n\n   @Test\n   public void testCorrect() throws SecurityException, NoSuchMethodException {\n      Invokable<?, Object> testPayload = method(TestPayload.class, \"testPayload\", String.class);\n      GeneratedHttpRequest request = GeneratedHttpRequest.builder()\n            .invocation(Invocation.create(testPayload, ImmutableList.<Object> of(\"robot\")))\n            .method(\"POST\").endpoint(\"http://localhost\").build();\n\n      GeneratedHttpRequest newRequest = binder().bindToRequest(request,\n            ImmutableMap.<String, Object> of(\"fooble\", \"robot\"));\n\n      assertEquals(newRequest.getRequestLine(), request.getRequestLine());\n      assertEquals(newRequest.getPayload().getRawContent(), \"name robot\");\n   }\n   \n   @Test\n   public void testDecodes() throws SecurityException, NoSuchMethodException {\n      Invokable<?, Object> testPayload = method(TestPayload.class, \"changeAdminPass\", String.class);\n      GeneratedHttpRequest request = GeneratedHttpRequest.builder()\n            .invocation(Invocation.create(testPayload, ImmutableList.<Object> of(\"foo\")))\n            .method(\"POST\").endpoint(\"http://localhost\").build();\n\n      GeneratedHttpRequest newRequest = binder()\n            .bindToRequest(request, ImmutableMap.<String, Object>of(\"adminPass\", \"foo\"));\n\n      assertEquals(newRequest.getRequestLine(), request.getRequestLine());\n      assertEquals(newRequest.getPayload().getRawContent(), \"{\\\"changePassword\\\":{\\\"adminPass\\\":\\\"foo\\\"}}\");\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testMustHavePayloadAnnotation() throws SecurityException, NoSuchMethodException {\n      Invokable<?, Object> noPayload = method(TestPayload.class, \"noPayload\", String.class);\n      GeneratedHttpRequest request = GeneratedHttpRequest.builder()\n            .invocation(Invocation.create(noPayload, ImmutableList.<Object> of(\"robot\")))\n            .method(\"POST\").endpoint(\"http://localhost\").build();\n      binder().bindToRequest(request, ImmutableMap.<String, Object>of(\"fooble\", \"robot\"));\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testMustBeMap() {\n      BindMapToStringPayload binder = binder();\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      binder.bindToRequest(request, new File(\"foo\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testNullIsBad() {\n      BindMapToStringPayload binder = binder();\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").build();\n      binder.bindToRequest(request, null);\n   }\n\n   public BindMapToStringPayload binder() {\n      return new BindMapToStringPayload();\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/rest/binders/BindToJsonPayloadTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.File;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.json.Json;\nimport org.jclouds.json.config.GsonModule;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.inject.Guice;\n\n/**\n * Tests behavior of {@code BindToJsonPayload}\n */\n@Test(groups = \"unit\", testName = \"BindToJsonPayloadTest\")\npublic class BindToJsonPayloadTest {\n\n   private final Json json = Guice.createInjector(new GsonModule()).getInstance(Json.class);\n\n   @Test\n   public void testMap() throws SecurityException, NoSuchMethodException {\n      BindToJsonPayload binder = new BindToJsonPayload(json);\n\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").build();\n      request = binder.bindToRequest(request, ImmutableMap.of(\"imageName\", \"foo\", \"serverId\", \"2\"));\n      assertEquals(request.getPayload().getRawContent(), \"{\\\"imageName\\\":\\\"foo\\\",\\\"serverId\\\":\\\"2\\\"}\");\n      assertEquals(request.getPayload().getContentMetadata().getContentType(), \"application/json\");\n\n   }\n\n   private static class MyFile {\n      private MyFile(File path) {\n         this.path = path;\n      }\n      private final File path;\n   }\n\n   @Test\n   public void testSomethingNotAMap() throws SecurityException, NoSuchMethodException {\n      BindToJsonPayload binder = new BindToJsonPayload(json);\n\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").build();\n      request = binder.bindToRequest(request, new MyFile(new File(\"foo\")));\n      assertEquals(request.getPayload().getRawContent(), \"{\\\"path\\\":\\\"foo\\\"}\");\n      assertEquals(request.getPayload().getContentMetadata().getContentType(), \"application/json\");\n\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testNullIsBad() {\n      BindToJsonPayload binder = new BindToJsonPayload(json);\n      binder.bindToRequest(HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").build(), null);\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/rest/binders/BindToJsonPayloadWrappedWithTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.json.config.GsonModule;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport com.google.inject.assistedinject.FactoryModuleBuilder;\n\n/**\n * Tests behavior of {@code BindToJsonPayloadWrappedWith}\n */\n@Test(groups = \"unit\")\npublic class BindToJsonPayloadWrappedWithTest {\n\n   Injector injector = Guice.createInjector(new GsonModule(), new FactoryModuleBuilder()\n            .build(BindToJsonPayloadWrappedWith.Factory.class));\n\n   @Test\n   public void testCorrect() throws SecurityException, NoSuchMethodException {\n      BindToJsonPayloadWrappedWith binder = new BindToJsonPayloadWrappedWith(injector\n               .getInstance(BindToJsonPayload.class), \"envelope\");\n\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").build();\n      request = binder.bindToRequest(request, ImmutableMap.of(\"imageName\", \"foo\", \"serverId\", \"2\"));\n      assertEquals(request.getPayload().getRawContent(), \"{\\\"envelope\\\":{\\\"imageName\\\":\\\"foo\\\",\\\"serverId\\\":\\\"2\\\"}}\");\n\n   }\n\n   @Test\n   public void testFactoryCorrect() throws SecurityException, NoSuchMethodException {\n      BindToJsonPayloadWrappedWith binder = injector.getInstance(BindToJsonPayloadWrappedWith.Factory.class).create(\n               \"envelope\");\n\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").build();\n      request = binder.bindToRequest(request, ImmutableMap.of(\"imageName\", \"foo\", \"serverId\", \"2\"));\n      assertEquals(request.getPayload().getRawContent(), \"{\\\"envelope\\\":{\\\"imageName\\\":\\\"foo\\\",\\\"serverId\\\":\\\"2\\\"}}\");\n\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testNullIsBad() {\n      BindToJsonPayloadWrappedWith binder = new BindToJsonPayloadWrappedWith(injector\n               .getInstance(BindToJsonPayload.class), \"envelope\");\n      binder.bindToRequest(HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").build(), null);\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/rest/binders/BindToStringPayloadTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.File;\n\nimport org.jclouds.http.HttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Tests behavior of {@code BindToStringPayload}\n */\n@Test(groups = \"unit\", testName = \"BindToStringPayloadTest\")\npublic class BindToStringPayloadTest {\n\n   @Test\n   public void testMap() throws SecurityException, NoSuchMethodException {\n      BindToStringPayload binder = new BindToStringPayload();\n\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").build();\n      request = binder.bindToRequest(request, ImmutableMap.of(\"imageName\", \"foo\", \"serverId\", \"2\"));\n      assertEquals(request.getPayload().getRawContent(), \"{imageName=foo, serverId=2}\");\n      assertEquals(request.getPayload().getContentMetadata().getContentType(), \"application/unknown\");\n\n   }\n\n   @Test\n   public void testSomethingNotAMap() throws SecurityException, NoSuchMethodException {\n      BindToStringPayload binder = new BindToStringPayload();\n\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").build();\n      request = binder.bindToRequest(request, new File(\"foo\"));\n      assertEquals(request.getPayload().getRawContent(), \"foo\");\n      assertEquals(request.getPayload().getContentMetadata().getContentType(), \"application/unknown\");\n\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testNullIsBad() {\n      BindToStringPayload binder = new BindToStringPayload();\n      binder.bindToRequest(HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").build(), null);\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/rest/binders/BindToXMLPayloadTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.binders;\n\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.testng.Assert.assertEquals;\n\nimport jakarta.xml.bind.annotation.XmlRootElement;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.xml.XMLParser;\nimport org.jclouds.xml.internal.JAXBParser;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.Multimap;\n\n/**\n * Tests behavior of {@code BindToXMLPayload}.\n */\n@Test(groups = \"unit\", testName = \"BindToXMLPayloadTest\")\npublic class BindToXMLPayloadTest {\n   XMLParser xml = new JAXBParser(\"true\");\n\n   @Test\n   public void testBindJAXBObject() throws SecurityException, NoSuchMethodException {\n      BindToXMLPayload binder = new BindToXMLPayload(xml);\n\n      // Build the object to bind\n      TestJAXBDomain obj = new TestJAXBDomain();\n      obj.setElem(\"Hello World\");\n\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").build();\n      request = binder.bindToRequest(request, obj);\n      assertEquals(request.getPayload().getRawContent(), XMLParser.DEFAULT_XML_HEADER\n            + \"\\n<test>\\n    <elem>Hello World</elem>\\n</test>\\n\");\n      assertEquals(request.getPayload().getContentMetadata().getContentType(), \"application/xml\");\n   }\n\n   @Test\n   public void testHeaderIsChangedIfNeeded() throws SecurityException, NoSuchMethodException {\n      BindToXMLPayload binder = new BindToXMLPayload(xml);\n\n      // Build the object to bind\n      TestJAXBDomain obj = new TestJAXBDomain();\n      obj.setElem(\"Hello World\");\n\n      // Add the unknown content-type header to verify it is changed by the\n      // binder\n      Multimap<String, String> headers = ImmutableMultimap.<String, String> of(\"Content-type\", \"application/unknown\");\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").headers(headers).build();\n\n      request = binder.bindToRequest(request, obj);\n      assertEquals(request.getPayload().getRawContent(), XMLParser.DEFAULT_XML_HEADER\n            + \"\\n<test>\\n    <elem>Hello World</elem>\\n</test>\\n\");\n      assertEquals(request.getPayload().getContentMetadata().getContentType(), \"application/xml\");\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testNullIsBad() {\n      BindToXMLPayload binder = new BindToXMLPayload(xml);\n      binder.bindToRequest(HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").build(), null);\n   }\n\n   @Test(expectedExceptions = BindException.class)\n   public void testInvalidObjectBinding() {\n      BindToXMLPayload binder = new BindToXMLPayload(xml);\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").build();\n      request = binder.bindToRequest(request, new Object());\n   }\n\n   @Test\n   public void testJAXBParserBOM() throws Exception {\n      String input = \"\\uFEFF<test><elem>foo</elem></test>\";\n      TestJAXBDomain obj = xml.fromXML(input, TestJAXBDomain.class);\n      assertThat(obj.getElem()).isEqualTo(\"foo\");\n   }\n\n   @XmlRootElement(name = \"test\")\n   public static class TestJAXBDomain {\n      private String elem;\n\n      public String getElem() {\n         return elem;\n      }\n\n      public void setElem(String elem) {\n         this.elem = elem;\n      }\n\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/rest/config/ReadAnnotationsAndPropertiesTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.config;\n\nimport static org.jclouds.reflect.Reflection2.method;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Properties;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.internal.FilterStringsBoundToInjectorByName;\nimport org.jclouds.reflect.Invocation;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableList;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport com.google.inject.name.Names;\n\n@Test(groups = \"unit\", singleThreaded = true)\npublic class ReadAnnotationsAndPropertiesTest {\n\n   public interface ThingApi {\n      HttpResponse get();\n\n      @Named(\"ns:get\")\n      @Fallback(FalseOnNotFoundOr404.class)\n      HttpResponse namedGet();\n   }\n\n   private Invocation asyncGet;\n   private Invocation asyncNamedGet;\n   private org.jclouds.Fallback<Object> defaultFallback;\n\n   @BeforeClass\n   void setupInvocations() throws SecurityException, NoSuchMethodException {\n      asyncGet = Invocation.create(method(ThingApi.class, \"get\"), ImmutableList.of());\n      asyncNamedGet = Invocation.create(method(ThingApi.class, \"namedGet\"), ImmutableList.of());\n      defaultFallback = new NullOnNotFoundOr404();\n   }\n\n   /**\n    * this functionality will be removed once Named annotations are on all classes.\n    */\n   public void testInvocationsSetDefaultTimeoutOnAsyncMethods() throws Exception {\n      final Properties props = new Properties();\n      props.setProperty(\"jclouds.timeouts.default\", \"250\");\n      Injector injector = Guice.createInjector(new AbstractModule() {\n         protected void configure() {\n            Names.bindProperties(binder(), props);\n         }\n      });\n      ReadAnnotationsAndProperties config = new ReadAnnotationsAndProperties(injector,\n            new FilterStringsBoundToInjectorByName(injector), defaultFallback);\n      assertEquals(config.getTimeoutNanos(asyncGet), Optional.of(250000000L));\n      assertEquals(config.getTimeoutNanos(asyncNamedGet), Optional.of(250000000L));\n   }\n\n   public void testNamedInvocationGetsTimeoutOverrideOnAsyncMethods() throws Exception {\n      final Properties props = new Properties();\n      props.setProperty(\"jclouds.timeouts.default\", \"50\");\n      props.setProperty(\"jclouds.timeouts.ThingApi\", \"100\");\n      props.setProperty(\"jclouds.timeouts.ns:get\", \"250\");\n      Injector injector = Guice.createInjector(new AbstractModule() {\n         protected void configure() {\n            Names.bindProperties(binder(), props);\n         }\n      });\n      ReadAnnotationsAndProperties config = new ReadAnnotationsAndProperties(injector,\n            new FilterStringsBoundToInjectorByName(injector), defaultFallback);\n      assertEquals(config.getTimeoutNanos(asyncNamedGet), Optional.of(250000000L));\n   }\n\n   /**\n    * this functionality will be removed once Named annotations are on all async\n    * classes.\n    */\n   public void testNamingConventionOfUnnamedMethods() throws Exception {\n      Injector injector = Guice.createInjector();\n      ReadAnnotationsAndProperties config = new ReadAnnotationsAndProperties(injector,\n            new FilterStringsBoundToInjectorByName(injector), defaultFallback);\n      assertEquals(config.getCommandName(asyncGet), \"ThingApi.get\");\n   }\n\n   public void testNamingConventionOfNamedAsyncMethods() throws Exception {\n      Injector injector = Guice.createInjector();\n      ReadAnnotationsAndProperties config = new ReadAnnotationsAndProperties(injector,\n            new FilterStringsBoundToInjectorByName(injector), defaultFallback);\n      assertEquals(config.getCommandName(asyncNamedGet), \"ns:get\");\n   }\n\n   public void testFallbackOverride() throws Exception {\n      Injector injector = Guice.createInjector();\n      ReadAnnotationsAndProperties config = new ReadAnnotationsAndProperties(injector,\n            new FilterStringsBoundToInjectorByName(injector), defaultFallback);\n      assertEquals(config.getFallback(asyncNamedGet).getClass(), FalseOnNotFoundOr404.class);\n      assertEquals(config.getFallback(asyncGet), defaultFallback);\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/rest/functions/PresentWhenApiVersionLexicographicallyAtOrAfterSinceApiVersionTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.functions;\n\nimport static com.google.common.base.Throwables.propagate;\nimport static org.jclouds.reflect.Reflection2.method;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.concurrent.TimeUnit;\nimport java.util.logging.Logger;\n\nimport org.jclouds.reflect.Invocation;\nimport org.jclouds.reflect.InvocationSuccess;\nimport org.jclouds.rest.annotations.Delegate;\nimport org.jclouds.rest.annotations.SinceApiVersion;\nimport org.jclouds.rest.functions.PresentWhenApiVersionLexicographicallyAtOrAfterSinceApiVersion.Loader;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.base.Stopwatch;\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Allows you to use simple api version comparison to determine if a feature is\n * available.\n */\n@Test(groups = \"unit\")\npublic class PresentWhenApiVersionLexicographicallyAtOrAfterSinceApiVersionTest {\n\n   // feature present in base api\n   interface KeyPairApi {\n\n   }\n\n   @SinceApiVersion(\"2010-08-31\")\n   interface TagApi {\n\n   }\n\n   @SinceApiVersion(\"2011-01-01\")\n   interface VpcApi {\n\n   }\n\n   interface EC2Api {\n\n      @Delegate\n      Optional<TagApi> getTagApiForRegion(String region);\n\n      @Delegate\n      Optional<KeyPairApi> getKeyPairApiForRegion(String region);\n\n      @Delegate\n      Optional<VpcApi> getVpcApiForRegion(String region);\n\n   }\n\n   public void testPresentWhenSinceApiVersionUnset() {\n      ImplicitOptionalConverter fn = forApiVersion(\"2011-07-15\");\n      assertEquals(fn.apply(getKeyPairApi()), Optional.of(\"present\"));\n      assertEquals(fn.apply(getFloatingIPApi()), Optional.of(\"present\"));\n      assertEquals(fn.apply(getVpcApi()), Optional.of(\"present\"));\n   }\n\n   public void testPresentWhenSinceApiVersionUnsetOrEqualToApiVersion() {\n      ImplicitOptionalConverter fn = forApiVersion(\"2011-01-01\");\n      assertEquals(fn.apply(getKeyPairApi()), Optional.of(\"present\"));\n      assertEquals(fn.apply(getFloatingIPApi()), Optional.of(\"present\"));\n      assertEquals(fn.apply(getVpcApi()), Optional.of(\"present\"));\n   }\n\n   public void testNotPresentWhenSinceApiVersionSetAndGreaterThanApiVersion() throws SecurityException,\n         NoSuchMethodException {\n      ImplicitOptionalConverter fn = forApiVersion(\"2006-06-26\");\n      assertEquals(fn.apply(getKeyPairApi()), Optional.of(\"present\"));\n      assertEquals(fn.apply(getFloatingIPApi()), Optional.absent());\n      assertEquals(fn.apply(getVpcApi()), Optional.absent());\n   }\n\n   private ImplicitOptionalConverter forApiVersion(String apiVersion) {\n      return new PresentWhenApiVersionLexicographicallyAtOrAfterSinceApiVersion(apiVersion);\n   }\n\n   public void testLoaderPresentWhenSinceApiVersionUnset() {\n      Loader fn = new Loader(\"2011-07-15\");\n      assertEquals(fn.load(getKeyPairApi()), Optional.of(\"present\"));\n      assertEquals(fn.load(getFloatingIPApi()), Optional.of(\"present\"));\n      assertEquals(fn.load(getVpcApi()), Optional.of(\"present\"));\n   }\n\n   public void testLoaderPresentWhenSinceApiVersionUnsetOrEqualToApiVersion() {\n      Loader fn = new Loader(\"2011-01-01\");\n      assertEquals(fn.load(getKeyPairApi()), Optional.of(\"present\"));\n      assertEquals(fn.load(getFloatingIPApi()), Optional.of(\"present\"));\n      assertEquals(fn.load(getVpcApi()), Optional.of(\"present\"));\n   }\n\n   public void testLoaderNotPresentWhenSinceApiVersionSetAndGreaterThanApiVersion() throws SecurityException,\n         NoSuchMethodException {\n      Loader fn = new Loader(\"2006-06-26\");\n      assertEquals(fn.load(getKeyPairApi()), Optional.of(\"present\"));\n      assertEquals(fn.load(getFloatingIPApi()), Optional.absent());\n      assertEquals(fn.load(getVpcApi()), Optional.absent());\n   }\n\n   public void testCacheIsFasterWhenNoAnnotationPresent() {\n      InvocationSuccess keyPairApi = getKeyPairApi();\n      ImplicitOptionalConverter fn = forApiVersion(\"2011-07-15\");\n      Stopwatch watch = Stopwatch.createStarted();\n      fn.apply(keyPairApi);\n      long first = watch.stop().elapsed(TimeUnit.MICROSECONDS);\n      watch.reset().start();\n      fn.apply(keyPairApi);\n      long cached = watch.stop().elapsed(TimeUnit.MICROSECONDS);\n      assertTrue(cached < first, String.format(\"cached [%s] should be less than initial [%s]\", cached, first));\n      Logger.getAnonymousLogger().info(\n            \"lookup cache saved \" + (first - cached) + \" microseconds when no annotation present\");\n   }\n\n   public void testCacheIsFasterWhenAnnotationPresent() {\n      InvocationSuccess floatingIpApi = getKeyPairApi();\n      ImplicitOptionalConverter fn = forApiVersion(\"2011-07-15\");\n      Stopwatch watch = Stopwatch.createStarted();\n      fn.apply(floatingIpApi);\n      long first = watch.stop().elapsed(TimeUnit.MICROSECONDS);\n      watch.reset().start();\n      fn.apply(floatingIpApi);\n      long cached = watch.stop().elapsed(TimeUnit.MICROSECONDS);\n      assertTrue(cached < first, String.format(\"cached [%s] should be less than initial [%s]\", cached, first));\n      Logger.getAnonymousLogger().info(\n            \"lookup cache saved \" + (first - cached) + \" microseconds when annotation present\");\n\n   }\n\n   InvocationSuccess getFloatingIPApi() {\n      return getApi(\"Tag\", TagApi.class);\n   }\n\n   InvocationSuccess getKeyPairApi() {\n      return getApi(\"KeyPair\", KeyPairApi.class);\n   }\n\n   InvocationSuccess getVpcApi() {\n      return getApi(\"Vpc\", VpcApi.class);\n   }\n\n   InvocationSuccess getApi(String name, Class<?> target) {\n      try {\n         return InvocationSuccess.create(\n               Invocation.create(method(EC2Api.class, \"get\" + name + \"ApiForRegion\", String.class),\n                     ImmutableList.<Object> of(\"region\")), \"present\");\n      } catch (Exception e) {\n         throw propagate(e);\n      }\n   }\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/rest/internal/BaseHttpApiMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.internal;\nimport static org.jclouds.reflect.Reflection2.typeToken;\n\nimport java.util.Set;\n\nimport org.jclouds.View;\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.apis.Apis;\nimport org.jclouds.apis.internal.BaseApiMetadataTest;\nimport org.jclouds.rest.ApiContext;\nimport org.jclouds.rest.HttpApiMetadata;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.reflect.TypeToken;\n\n@Test(groups = \"unit\")\npublic abstract class BaseHttpApiMetadataTest extends BaseApiMetadataTest {\n\n   public BaseHttpApiMetadataTest(HttpApiMetadata<?> toTest, Set<TypeToken<? extends View>> views) {\n     super(toTest, views);\n   }\n\n   @Test\n   public void testContextAssignableFromRestContext() {\n      Set<ApiMetadata> all = ImmutableSet.copyOf(Apis.contextAssignableFrom(typeToken(ApiContext.class)));\n      assert all.contains(toTest) : String.format(\"%s not found in %s\", toTest, all);\n   }\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/rest/internal/BaseRestAnnotationProcessingTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.io.IOException;\nimport java.util.Properties;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.logging.config.NullLoggingModule;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Binder;\nimport com.google.inject.Injector;\nimport com.google.inject.Module;\n\n@Test(groups = \"unit\")\npublic abstract class BaseRestAnnotationProcessingTest<T> extends BaseRestApiTest {\n\n   protected RestAnnotationProcessor processor;\n\n   protected abstract void checkFilters(HttpRequest request);\n\n   protected Module createModule() {\n      return new Module() {\n\n         @Override\n         public void configure(Binder binder) {\n\n         }\n\n      };\n   }\n\n   @BeforeClass\n   protected void setupFactory() throws IOException {\n      injector = createInjector();\n      parserFactory = injector.getInstance(ParseSax.Factory.class);\n      processor = injector.getInstance(RestAnnotationProcessor.class);\n   }\n\n   protected String identity = \"identity\";\n   protected String credential = \"credential\";\n\n   /**\n    * @see org.jclouds.providers.Providers#withId\n    */\n   protected ProviderMetadata createProviderMetadata() {\n      return null;\n   }\n\n   /**\n    * @see org.jclouds.apis.Apis#withId\n    */\n   protected ApiMetadata createApiMetadata() {\n      return null;\n   }\n\n   protected Injector createInjector() {\n      ProviderMetadata pm = createProviderMetadata();\n\n      ContextBuilder builder = pm != null ? ContextBuilder.newBuilder(pm) : ContextBuilder.newBuilder(ApiMetadata.class\n            .cast(checkNotNull(createApiMetadata(),\n                  \"either createApiMetadata or createProviderMetadata must be overridden\")));\n\n      return builder.credentials(identity, credential)\n            .modules(ImmutableSet.of(new MockModule(), new NullLoggingModule(), createModule()))\n            .overrides(setupProperties()).buildInjector();\n   }\n\n   /**\n    * override this to supply context-specific parameters during tests.\n    */\n   protected Properties setupProperties() {\n      return new Properties();\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/rest/internal/BaseRestApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.util.concurrent.MoreExecutors.newDirectExecutorService;\nimport static com.google.inject.name.Names.named;\nimport static org.jclouds.Constants.PROPERTY_IDEMPOTENT_METHODS;\nimport static org.jclouds.Constants.PROPERTY_MAX_RETRIES;\nimport static org.jclouds.Constants.PROPERTY_USER_THREADS;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.NoSuchElementException;\nimport java.util.Properties;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.logging.Logger;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.custommonkey.xmlunit.Diff;\nimport org.custommonkey.xmlunit.Difference;\nimport org.custommonkey.xmlunit.DifferenceConstants;\nimport org.custommonkey.xmlunit.DifferenceListener;\nimport org.custommonkey.xmlunit.NodeDetail;\nimport org.custommonkey.xmlunit.XMLUnit;\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.concurrent.SingleThreaded;\nimport org.jclouds.concurrent.config.ConfiguresExecutorService;\nimport org.jclouds.date.internal.DateServiceDateCodecFactory;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.http.HttpCommandExecutorService;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpUtils;\nimport org.jclouds.http.IOExceptionRetryHandler;\nimport org.jclouds.http.config.ConfiguresHttpCommandExecutorService;\nimport org.jclouds.http.handlers.DelegatingErrorHandler;\nimport org.jclouds.http.handlers.DelegatingRetryHandler;\nimport org.jclouds.http.internal.BaseHttpCommandExecutorService;\nimport org.jclouds.http.internal.HttpWire;\nimport org.jclouds.io.ContentMetadataCodec;\nimport org.jclouds.io.ContentMetadataCodec.DefaultContentMetadataCodec;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.logging.config.NullLoggingModule;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.rest.HttpApiMetadata;\nimport org.jclouds.rest.config.CredentialStoreModule;\nimport org.jclouds.util.Strings2;\nimport org.w3c.dom.Node;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Function;\nimport com.google.common.base.Objects;\nimport com.google.common.base.Throwables;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.io.ByteSource;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.common.util.concurrent.SimpleTimeLimiter;\nimport com.google.common.util.concurrent.TimeLimiter;\nimport com.google.gson.JsonElement;\nimport com.google.gson.JsonParser;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Binder;\nimport com.google.inject.Injector;\nimport com.google.inject.Module;\nimport com.google.inject.Provides;\nimport com.google.inject.TypeLiteral;\n\n/**\n * \n * Allows us to test a client via its side effects.\n * \n * <p/>\n * Example usage:\n * \n * <pre>\n * \n * HttpRequest bucketFooExists = HttpRequest.builder().method(&quot;HEAD&quot;).endpoint(\n *          URI.create(&quot;https://s3.amazonaws.com/foo?max-keys=0&quot;)).headers(\n *          ImmutableMultimap.&lt;String, String&gt; builder().put(&quot;Date&quot;, CONSTANT_DATE)\n *                   .put(&quot;Authorization&quot;, &quot;AWS identity:86P4BBb7xT+gBqq7jxM8Tc28ktY=&quot;).build()).build();\n * \n * S3Client clientWhenBucketExists = requestSendsResponse(bucketFooExists, HttpResponse.builder().statusCode(200).build());\n * assert clientWhenBucketExists.bucketExists(&quot;foo&quot;);\n * \n * S3Client clientWhenBucketDoesntExist = requestSendsResponse(bucketFooExists, HttpResponse.builder().statusCode(404)\n *          .build());\n * assert !clientWhenBucketDoesntExist.bucketExists(&quot;foo&quot;);\n * </pre>\n */\n@Beta\npublic abstract class BaseRestApiExpectTest<S> {\n\n   protected String provider = \"mock\";\n\n   protected ContentMetadataCodec contentMetadataCodec = new DefaultContentMetadataCodec(\n            new DateServiceDateCodecFactory(new SimpleDateFormatDateService()));\n   \n   /**\n    * Override this to supply alternative bindings for use in the test. This is commonly used to\n    * override suppliers of dates so that the test results are predicatable.\n    * \n    * @return optional guice module which can override bindings\n    */\n   protected Module createModule() {\n      return new Module() {\n\n         @Override\n         public void configure(Binder binder) {\n\n         }\n\n      };\n   }\n\n   /**\n    * Convenience method used when creating a response that includes an http payload.\n    * \n    * <p/>\n    * ex.\n    * \n    * <pre>\n    * HttpResponse.builder().statusCode(200).payload(payloadFromResource(&quot;/ip_get_details.json&quot;)).build()\n    * </pre>\n    * \n    * @param resource\n    *           resource file such as {@code /serverlist.json}\n    * @return payload for use in http responses.\n    */\n   public Payload payloadFromResource(String resource) {\n      try {\n         return payloadFromString(Strings2.toStringAndClose(getClass().getResourceAsStream(resource)));\n      } catch (IOException e) {\n         throw Throwables.propagate(e);\n      }\n   }\n\n   public Payload payloadFromResourceWithContentType(String resource, String contentType) {\n      try {\n         return payloadFromStringWithContentType(Strings2.toStringAndClose(getClass().getResourceAsStream(resource)),\n                  contentType);\n      } catch (IOException e) {\n         throw Throwables.propagate(e);\n      }\n\n   }\n\n   public static Payload payloadFromString(String payload) {\n      return Payloads.newStringPayload(payload);\n   }\n\n   public static Payload payloadFromStringWithContentType(String payload, String contentType) {\n      Payload p = Payloads.newStringPayload(payload);\n      p.getContentMetadata().setContentType(contentType);\n      return p;\n   }\n\n   /**\n    * Mock executor service which uses the supplied function to return http responses.\n    */\n   @SingleThreaded\n   @Singleton\n   public static class ExpectHttpCommandExecutorService extends BaseHttpCommandExecutorService<HttpRequest> {\n\n      private final Function<HttpRequest, HttpResponse> fn;\n\n      @Inject\n      public ExpectHttpCommandExecutorService(Function<HttpRequest, HttpResponse> fn, HttpUtils utils,\n            ContentMetadataCodec contentMetadataCodec, IOExceptionRetryHandler ioRetryHandler,\n            DelegatingRetryHandler retryHandler, DelegatingErrorHandler errorHandler, HttpWire wire,\n            @Named(PROPERTY_IDEMPOTENT_METHODS) String idempotentMethods) {\n         super(utils, contentMetadataCodec, retryHandler, ioRetryHandler, errorHandler, wire, idempotentMethods);\n         this.fn = checkNotNull(fn, \"fn\");\n      }\n\n      @Override\n      public void cleanup(HttpRequest nativeResponse) {\n         if (nativeResponse != null && nativeResponse.getPayload() != null)\n            nativeResponse.getPayload().release();\n      }\n\n      @Override\n      public HttpRequest convert(HttpRequest request) throws IOException, InterruptedException {\n         return request;\n      }\n\n      @Override\n      public HttpResponse invoke(HttpRequest nativeRequest) throws IOException, InterruptedException {\n         return fn.apply(nativeRequest);\n      }\n   }\n\n   @ConfiguresHttpCommandExecutorService\n   @ConfiguresExecutorService\n   public static class ExpectModule extends AbstractModule {\n      private final Function<HttpRequest, HttpResponse> fn;\n\n      public ExpectModule(Function<HttpRequest, HttpResponse> fn) {\n         this.fn = checkNotNull(fn, \"fn\");\n      }\n\n      @Override\n      public void configure() {\n         bind(ListeningExecutorService.class).annotatedWith(named(PROPERTY_USER_THREADS)).toInstance(newDirectExecutorService());\n         bind(new TypeLiteral<Function<HttpRequest, HttpResponse>>() {\n         }).toInstance(fn);\n         bind(HttpCommandExecutorService.class).to(ExpectHttpCommandExecutorService.class);\n      }\n\n      @Provides\n      @Singleton\n      TimeLimiter timeLimiter(@Named(PROPERTY_USER_THREADS) ListeningExecutorService userExecutor) {\n         return SimpleTimeLimiter.create(userExecutor);\n      }\n   }\n\n   /**\n    * creates a client for a mock server which only responds to a single http request\n    * \n    * @param request\n    *           the http request the mock server responds to\n    * @param response\n    *           the response the mock server returns for the request\n    * @return a client configured with this behavior\n    */\n   public S requestSendsResponse(HttpRequest request, HttpResponse response) {\n      return requestSendsResponse(request, response, createModule());\n   }\n\n   public S requestSendsResponse(HttpRequest request, HttpResponse response, Module module) {\n      return requestsSendResponses(ImmutableMap.of(request, response), module);\n   }\n\n   /**\n    * creates a client for a mock server which only responds to two types of requests\n    * \n    * @param requestA\n    *           an http request the mock server responds to\n    * @param responseA\n    *           the response for {@code requestA}\n    * @param requestB\n    *           another http request the mock server responds to\n    * @param responseB\n    *           the response for {@code requestB}\n    * @return a client configured with this behavior\n    */\n   public S requestsSendResponses(HttpRequest requestA, HttpResponse responseA, HttpRequest requestB,\n            HttpResponse responseB) {\n      return requestsSendResponses(requestA, responseA, requestB, responseB, createModule());\n   }\n\n   public S requestsSendResponses(HttpRequest requestA, HttpResponse responseA, HttpRequest requestB,\n            HttpResponse responseB, Module module) {\n      return requestsSendResponses(ImmutableMap.of(requestA, responseA, requestB, responseB), module);\n   }\n\n   /**\n    * creates a client for a mock server which only responds to three types of requests\n    * \n    * @param requestA\n    *           an http request the mock server responds to\n    * @param responseA\n    *           the response for {@code requestA}\n    * @param requestB\n    *           another http request the mock server responds to\n    * @param responseB\n    *           the response for {@code requestB}\n    * @param requestC\n    *           another http request the mock server responds to\n    * @param responseC\n    *           the response for {@code requestC}\n    * @return a client configured with this behavior\n    */\n   public S requestsSendResponses(HttpRequest requestA, HttpResponse responseA, HttpRequest requestB,\n            HttpResponse responseB, HttpRequest requestC, HttpResponse responseC) {\n      return requestsSendResponses(requestA, responseA, requestB, responseB, requestC, responseC, createModule());\n   }\n\n   public S requestsSendResponses(HttpRequest requestA, HttpResponse responseA, HttpRequest requestB,\n            HttpResponse responseB, HttpRequest requestC, HttpResponse responseC, Module module) {\n      return requestsSendResponses(ImmutableMap.of(requestA, responseA, requestB, responseB, requestC, responseC),\n               module);\n   }\n\n   public S orderedRequestsSendResponses(HttpRequest requestA, HttpResponse responseA, HttpRequest requestB,\n            HttpResponse responseB) {\n      return orderedRequestsSendResponses(ImmutableList.of(requestA, requestB), ImmutableList.of(responseA, responseB));\n   }\n\n   public S orderedRequestsSendResponses(HttpRequest requestA, HttpResponse responseA, HttpRequest requestB,\n            HttpResponse responseB, HttpRequest requestC, HttpResponse responseC) {\n      return orderedRequestsSendResponses(ImmutableList.of(requestA, requestB, requestC), ImmutableList.of(responseA,\n               responseB, responseC));\n   }\n\n   public S orderedRequestsSendResponses(HttpRequest requestA, HttpResponse responseA, HttpRequest requestB,\n            HttpResponse responseB, HttpRequest requestC, HttpResponse responseC, HttpRequest requestD,\n            HttpResponse responseD) {\n      return orderedRequestsSendResponses(ImmutableList.of(requestA, requestB, requestC, requestD), ImmutableList.of(\n               responseA, responseB, responseC, responseD));\n   }\n\n   public S orderedRequestsSendResponses(final List<HttpRequest> requests, final List<HttpResponse> responses) {\n      final AtomicInteger counter = new AtomicInteger(0);\n\n      return createClient(new Function<HttpRequest, HttpResponse>() {\n         @Override\n         public HttpResponse apply(HttpRequest input) {\n            int index = counter.getAndIncrement();\n            if (index >= requests.size())\n               return HttpResponse.builder().statusCode(500).message(\n                        String.format(\"request %s is out of range (%s)\", index, requests.size())).payload(\n                        Payloads.newStringPayload(renderRequest(input))).build();\n            if (!httpRequestsAreEqual(input, requests.get(index))) {\n               assertEquals(renderRequest(input), renderRequest(requests.get(index)),\n                  \"Actual request did not match expected request \" + index);\n            }\n            return responses.get(index);\n         }\n      });\n   }\n\n   /**\n    * creates a client for a mock server which returns responses for requests based on the supplied\n    * Map parameter.\n    * \n    * @param requestToResponse\n    *           valid requests and responses for the mock to respond to\n    * @return a client configured with this behavior\n    */\n   public S requestsSendResponses(Map<HttpRequest, HttpResponse> requestToResponse) {\n      return requestsSendResponses(requestToResponse, createModule());\n   }\n\n   protected enum HttpRequestComparisonType {\n      XML, JSON, DEFAULT;\n   }\n\n   /**\n    * How should this HttpRequest be compared with others?\n    */\n   protected HttpRequestComparisonType compareHttpRequestAsType(HttpRequest input) {\n      return HttpRequestComparisonType.DEFAULT;\n   }\n\n   /**\n    * Compare two requests as instructed by {@link #compareHttpRequestAsType(HttpRequest)} - default\n    * is to compare using Objects.equal\n    */\n   public boolean httpRequestsAreEqual(HttpRequest a, HttpRequest b) {\n      try {\n         if (a == null || b == null || !Objects.equal(a.getRequestLine(), b.getRequestLine())\n               || !Objects.equal(a.getHeaders(), b.getHeaders())) {\n            return false;\n         }\n         if (a.getPayload() == null || b.getPayload() == null) {\n            return Objects.equal(a, b);\n         }\n \n         switch (compareHttpRequestAsType(a)) {\n            case XML: {\n               Diff diff = XMLUnit.compareXML(Strings2.toStringAndClose(a.getPayload().openStream()),\n                        Strings2.toStringAndClose(b.getPayload().openStream()));\n\n               // Ignoring whitespace in elements that have other children, xsi:schemaLocation and\n               // differences in namespace prefixes\n               diff.overrideDifferenceListener(new DifferenceListener() {\n                  @Override\n                  public int differenceFound(Difference diff) {\n                     if (diff.getId() == DifferenceConstants.SCHEMA_LOCATION_ID\n                              || diff.getId() == DifferenceConstants.NAMESPACE_PREFIX_ID) {\n                        return RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL;\n                     }\n                     if (diff.getId() == DifferenceConstants.TEXT_VALUE_ID) {\n                        for (NodeDetail detail : ImmutableSet.of(diff.getControlNodeDetail(), diff.getTestNodeDetail())) {\n                           if (detail.getNode().getParentNode().getChildNodes().getLength() < 2\n                                    || !detail.getValue().trim().isEmpty()) {\n                              return RETURN_ACCEPT_DIFFERENCE;\n                           }\n                        }\n                        return RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL;\n                     }\n                     return RETURN_ACCEPT_DIFFERENCE;\n                  }\n\n                  @Override\n                  public void skippedComparison(Node node, Node node1) {\n                  }\n               });\n\n               return diff.identical();\n            }\n            case JSON: {               \n               JsonParser parser = new JsonParser();\n               JsonElement payloadA = parser.parse(Strings2.toStringAndClose(a.getPayload().openStream()));\n               JsonElement payloadB = parser.parse(Strings2.toStringAndClose(b.getPayload().openStream()));\n               return Objects.equal(payloadA, payloadB);\n            }\n            default: {\n               return Objects.equal(a, b);\n            }\n         }\n      } catch (Exception e) {\n         throw Throwables.propagate(e);\n      }\n   }\n\n   public S requestsSendResponses(final Map<HttpRequest, HttpResponse> requestToResponse, Module module) {\n      return requestsSendResponses(requestToResponse, module, setupProperties());\n   }\n\n   public S requestsSendResponses(final Map<HttpRequest, HttpResponse> requestToResponse, Module module,\n            Properties props) {\n      return createClient(new Function<HttpRequest, HttpResponse>() {\n         \n         @Override\n         public HttpResponse apply(HttpRequest input) {\n            HttpRequest matchedRequest = null;\n            HttpResponse response = null;\n            for (Map.Entry<HttpRequest, HttpResponse> entry : requestToResponse.entrySet()) {\n               HttpRequest request = entry.getKey();\n               if (httpRequestsAreEqual(input, request)) {\n                  matchedRequest = request;\n                  response = entry.getValue();\n               }\n            }\n\n            if (response == null) {\n               StringBuilder payload = new StringBuilder(\"\\n\");\n               payload.append(\"\\n----------------------------------------\\n\");\n               payload.append(\"The following request is not configured:\\n\");\n               payload.append(\"----------------------------------------\\n\");\n               payload.append(renderRequest(input));\n               payload.append(\"\\n----------------------------------------\\n\");\n               payload.append(\"Configured requests:\\n\");\n               for (HttpRequest request : requestToResponse.keySet()) {\n                  payload.append(\"\\n----------------------------------------\\n\");\n                  payload.append(renderRequest(request));\n               }\n               response = HttpResponse.builder().statusCode(500).message(\"no response configured for request\").payload(\n                        Payloads.newStringPayload(payload.toString())).build();\n\n            } else if (compareHttpRequestAsType(input) == HttpRequestComparisonType.DEFAULT) {\n               // in case hashCode/equals doesn't do a full content check\n               assertEquals(renderRequest(input), renderRequest(matchedRequest));\n            }\n\n            return response;\n         }\n      }, module, props);\n   }\n\n   public String renderRequest(HttpRequest request) {\n      StringBuilder builder = new StringBuilder().append(request.getRequestLine()).append('\\n');\n      for (Entry<String, String> header : request.getHeaders().entries()) {\n         builder.append(header.getKey()).append(\": \").append(header.getValue()).append('\\n');\n      }\n      if (request.getPayload() != null) {\n         for (Entry<String, String> header : contentMetadataCodec.toHeaders(\n                  request.getPayload().getContentMetadata()).entries()) {\n            builder.append(header.getKey()).append(\": \").append(header.getValue()).append('\\n');\n         }\n         try {\n            builder.append('\\n').append(Strings2.toStringAndClose(request.getPayload().openStream()));\n         } catch (IOException e) {\n            throw Throwables.propagate(e);\n         }\n\n      } else {\n         builder.append('\\n');\n      }\n      return builder.toString();\n   }\n\n   public S createClient(Function<HttpRequest, HttpResponse> fn) {\n      return createClient(fn, createModule(), setupProperties());\n   }\n\n   public S createClient(Function<HttpRequest, HttpResponse> fn, Module module) {\n      return createClient(fn, module, setupProperties());\n   }\n\n   public S createClient(Function<HttpRequest, HttpResponse> fn, Properties props) {\n      return createClient(fn, createModule(), props);\n\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   public S createClient(Function<HttpRequest, HttpResponse> fn, Module module, Properties props) {\n      return (S) createInjector(fn, module, props).getInstance(api);\n   }\n\n   protected String identity = \"identity\";\n   protected String credential = \"credential\";\n   protected Class<?> api;\n\n   /**\n    * @see org.jclouds.providers.Providers#withId\n    */\n   protected ProviderMetadata createProviderMetadata() {\n      return null;\n   }\n\n   /**\n    * @see org.jclouds.apis.Apis#withId\n    */\n   protected ApiMetadata createApiMetadata() {\n      return null;\n   }\n\n   protected Injector createInjector(Function<HttpRequest, HttpResponse> fn, Module module, Properties props) {\n      ContextBuilder builder = null;\n      if (provider != null)\n         try {\n            builder = ContextBuilder.newBuilder(provider).credentials(identity, credential);\n         } catch (NoSuchElementException e) {\n            Logger\n                     .getAnonymousLogger()\n                     .warning(\n                              \"provider [\"\n                                       + provider\n                                       + \"] is not setup as META-INF/services/org.jclouds.apis.ApiMetadata or META-INF/services/org.jclouds.providers.ProviderMetadata\");\n         }\n      if (builder == null) {\n         ProviderMetadata pm = createProviderMetadata();\n         ApiMetadata am = (pm != null) ? pm.getApiMetadata() : checkNotNull(createApiMetadata(),\n                  \"either createApiMetadata or createProviderMetadata must be overridden\");\n\n         builder = pm != null ? ContextBuilder.newBuilder(pm) : ContextBuilder.newBuilder(am);\n      }\n      ApiMetadata am = builder.getApiMetadata();\n      if (am instanceof HttpApiMetadata) {\n         this.api = HttpApiMetadata.class.cast(am).getApi();\n      } else {\n         throw new UnsupportedOperationException(\"unsupported base type: \" + am);\n      }\n      // isolate tests from eachother, as default credentialStore is static\n      return builder.credentials(identity, credential)\n               .modules(ImmutableSet.of(new ExpectModule(fn), new NullLoggingModule(), new CredentialStoreModule(new ConcurrentHashMap<String, ByteSource>()), module))\n               .overrides(props)\n               .buildInjector();\n   }\n   \n   /**\n    * override this to supply context-specific parameters during tests.\n    */\n   protected Properties setupProperties() {\n      Properties props = new Properties();\n      props.put(PROPERTY_MAX_RETRIES, 1);\n      return props;\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/rest/internal/BaseRestApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.internal;\nimport static com.google.common.base.Throwables.propagate;\nimport static com.google.common.hash.Hashing.md5;\nimport static com.google.common.net.HttpHeaders.TRANSFER_ENCODING;\nimport static com.google.common.util.concurrent.MoreExecutors.newDirectExecutorService;\nimport static com.google.inject.name.Names.named;\nimport static org.easymock.EasyMock.createMock;\nimport static org.jclouds.Constants.PROPERTY_USER_THREADS;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\n\nimport java.io.IOException;\nimport java.util.Date;\nimport java.util.Map.Entry;\n\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.concurrent.config.ConfiguresExecutorService;\nimport org.jclouds.fallbacks.MapHttp4xxCodesToExceptions;\nimport org.jclouds.http.HttpCommandExecutorService;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.config.ConfiguresHttpCommandExecutorService;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.io.MutableContentMetadata;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.XMLResponseParser;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Multimap;\nimport com.google.common.collect.SortedSetMultimap;\nimport com.google.common.collect.TreeMultimap;\nimport com.google.common.reflect.Invokable;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.common.util.concurrent.SimpleTimeLimiter;\nimport com.google.common.util.concurrent.TimeLimiter;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Injector;\nimport com.google.inject.Provides;\n\n@Test(groups = \"unit\")\npublic abstract class BaseRestApiTest {\n\n   protected Injector injector;\n   protected ParseSax.Factory parserFactory;\n\n   @ConfiguresHttpCommandExecutorService\n   @ConfiguresExecutorService\n   public static class MockModule extends AbstractModule {\n      private final HttpCommandExecutorService mock;\n\n      public MockModule() {\n         this(createMock(HttpCommandExecutorService.class));\n      }\n\n      public MockModule(HttpCommandExecutorService mock) {\n         this.mock = mock;\n      }\n\n      @Override\n      protected void configure() {\n         bind(ListeningExecutorService.class).annotatedWith(named(PROPERTY_USER_THREADS)).toInstance(newDirectExecutorService());\n         bind(HttpCommandExecutorService.class).toInstance(mock);\n      }\n\n      @Provides\n      @Singleton\n      TimeLimiter timeLimiter(@Named(PROPERTY_USER_THREADS) ListeningExecutorService userExecutor) {\n         return SimpleTimeLimiter.create(userExecutor);\n      }\n   }\n\n   protected void assertPayloadEquals(HttpRequest request, String toMatch, String contentType, boolean contentMD5) {\n      assertPayloadEquals(request, toMatch, contentType, contentMD5, null);\n   }\n\n   protected void assertPayloadEquals(HttpRequest request, String toMatch, String contentType, boolean contentMD5, Date expires) {\n      assertPayloadEquals(request, toMatch, contentType, null, null, null, contentMD5, expires);\n   }\n\n   protected void assertPayloadEquals(HttpRequest request, String toMatch, String contentType,\n         String contentDispositon, String contentEncoding, String contentLanguage, boolean contentMD5) {\n      assertPayloadEquals(request, toMatch, contentType, contentDispositon, contentEncoding, contentLanguage, \n               contentMD5, null);\n   }\n\n   protected void assertPayloadEquals(HttpRequest request, String toMatch, String contentType,\n         String contentDispositon, String contentEncoding, String contentLanguage, boolean contentMD5,\n         Date expires) {\n      if (request.getPayload() == null) {\n         assertNull(toMatch);\n      } else {\n         String payload = null;\n         try {\n            payload = Strings2.toStringAndClose(request.getPayload().openStream());\n         } catch (IOException e) {\n            propagate(e);\n         }\n         assertEquals(payload, toMatch);\n         Long length = Long.valueOf(payload.getBytes().length);\n         assertContentHeadersEqual(request, contentType, contentDispositon, contentEncoding, contentLanguage,\n               length, contentMD5 ? md5().hashBytes(payload.getBytes()).asBytes() : null, expires);\n      }\n   }\n\n   protected void assertContentHeadersEqual(HttpRequest request, String contentType, String contentDispositon,\n         String contentEncoding, String contentLanguage, Long length, byte[] contentMD5, Date expires) {\n      MutableContentMetadata md = request.getPayload().getContentMetadata();\n      if (request.getFirstHeaderOrNull(TRANSFER_ENCODING) == null) {\n         assertEquals(md.getContentLength(), length);\n      } else {\n         assertEquals(request.getFirstHeaderOrNull(TRANSFER_ENCODING), \"chunked\");\n         assert md.getContentLength() == null || md.getContentLength().equals(length);\n      }\n      assertEquals(md.getContentType(), contentType);\n      assertEquals(md.getContentDisposition(), contentDispositon);\n      assertEquals(md.getContentEncoding(), contentEncoding);\n      assertEquals(md.getContentLanguage(), contentLanguage);\n      assertEquals(md.getContentMD5(), contentMD5);\n      assertEquals(md.getExpires(), expires);\n   }\n\n   // FIXME Shouldn't be assertPayloadHeadersEqual?\n   protected void assertNonPayloadHeadersEqual(HttpRequest request, String toMatch) {\n      assertEquals(sortAndConcatHeadersIntoString(request.getHeaders()), toMatch);\n   }\n\n   public static String sortAndConcatHeadersIntoString(Multimap<String, String> headers) {\n      StringBuilder buffer = new StringBuilder();\n      SortedSetMultimap<String, String> sortedMap = TreeMultimap.create();\n      sortedMap.putAll(headers);\n      for (Entry<String, String> header : sortedMap.entries()) {\n         if (header.getKey() != null)\n            buffer.append(String.format(\"%s: %s\\n\", header.getKey(), header.getValue()));\n      }\n      return buffer.toString();\n   }\n   \n   protected void assertRequestLineEquals(HttpRequest request, String toMatch) {\n      assertEquals(request.getRequestLine(), toMatch);\n   }\n\n   protected void assertFallbackClassEquals(Invokable<?, ?> method, @Nullable Class<?> expected) {\n      Fallback fallbackAnnotation = method.getAnnotation(Fallback.class);\n      Class<?> assigned = fallbackAnnotation != null ? fallbackAnnotation.value() : MapHttp4xxCodesToExceptions.class;\n      if (expected == null)\n         assertEquals(assigned, MapHttp4xxCodesToExceptions.class);\n      else\n         assertEquals(assigned, expected);\n   }\n\n   protected void assertSaxResponseParserClassEquals(Invokable<?, ?> method, @Nullable Class<?> parserClass) {\n      XMLResponseParser annotation = method.getAnnotation(XMLResponseParser.class);\n      Class<?> expected =  (annotation != null) ? annotation.value() : null;\n      assertEquals(expected, parserClass);\n   }\n\n   protected void assertResponseParserClassEquals(Invokable<?, ?> method, GeneratedHttpRequest request,\n         @Nullable Class<?> parserClass) {\n      assertEquals(injector.getInstance(TransformerForRequest.class).apply(request).getClass(), parserClass);\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/rest/internal/InvokeHttpMethodTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.internal;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.jclouds.reflect.Reflection2.method;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.concurrent.TimeUnit;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpCommandExecutorService;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.reflect.Invocation;\nimport org.jclouds.rest.config.InvocationConfig;\nimport org.jclouds.rest.internal.InvokeHttpMethod.InvokeAndTransform;\nimport org.testng.annotations.AfterMethod;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.BeforeMethod;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Functions;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.util.concurrent.TimeLimiter;\n\n@Test(groups = \"unit\", singleThreaded = true)\npublic class InvokeHttpMethodTest {\n\n   public interface ThingApi {\n      @Named(\"ns:get\")\n      HttpResponse get();\n   }\n\n   private Invocation get;\n   private HttpRequest getRequest = HttpRequest.builder().method(\"GET\").endpoint(\"http://get\").build();\n   private HttpCommand getCommand = new HttpCommand(getRequest);\n   private Function<Invocation, HttpRequest> toRequest;\n\n   @BeforeClass\n   void setupInvocations() throws SecurityException, NoSuchMethodException {\n      get = Invocation.create(method(ThingApi.class, \"get\"), ImmutableList.of());\n      toRequest = Functions.forMap(ImmutableMap.of(get, getRequest));\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   private Function<HttpRequest, Function<HttpResponse, ?>> transformerForRequest = Function.class.cast(Functions\n         .constant(Functions.identity()));\n\n   private HttpResponse response = HttpResponse.builder().statusCode(200).payload(\"foo\").build();\n   private HttpCommandExecutorService http;\n   private TimeLimiter timeLimiter;\n   @SuppressWarnings(\"rawtypes\")\n   private org.jclouds.Fallback fallback;\n   private InvocationConfig config;\n   private InvokeHttpMethod invokeHttpMethod;\n\n\n   @SuppressWarnings(\"unchecked\")\n   @BeforeMethod\n   void createMocks() {\n      http = createMock(HttpCommandExecutorService.class);\n      timeLimiter = createMock(TimeLimiter.class);\n      fallback = createMock(org.jclouds.Fallback.class);\n      config = createMock(InvocationConfig.class);\n      invokeHttpMethod = new InvokeHttpMethod(toRequest, http, transformerForRequest, timeLimiter, config);\n      expect(config.getCommandName(get)).andReturn(\"ns:get\");\n      expect(config.getFallback(get)).andReturn(fallback);\n   }\n\n   @AfterMethod\n   void verifyMocks() {\n      verify(http, timeLimiter, fallback, config);\n   }\n\n   public void testMethodWithTimeoutRunsTimeLimiter() throws Exception {\n      expect(config.getTimeoutNanos(get)).andReturn(Optional.of(250000000L));\n      InvokeAndTransform invoke = invokeHttpMethod.new InvokeAndTransform(\"ns:get\", getCommand);\n      expect(timeLimiter.callWithTimeout(invoke, 250000000, TimeUnit.NANOSECONDS)).andReturn(response);\n      replay(http, timeLimiter, fallback, config);\n      invokeHttpMethod.apply(get);\n   }\n\n   public void testMethodWithNoTimeoutCallGetDirectly() throws Exception {\n      expect(config.getTimeoutNanos(get)).andReturn(Optional.<Long> absent());\n      expect(http.invoke(new HttpCommand(getRequest))).andReturn(response);\n      replay(http, timeLimiter, fallback, config);\n      invokeHttpMethod.apply(get);\n   }\n\n   private HttpResponse fallbackResponse = HttpResponse.builder().statusCode(200).payload(\"bar\").build();\n\n   public void testDirectCallRunsFallbackCreateOrPropagate() throws Exception {\n      IllegalStateException exception = new IllegalStateException();\n      expect(config.getTimeoutNanos(get)).andReturn(Optional.<Long> absent());\n      expect(http.invoke(new HttpCommand(getRequest))).andThrow(exception);\n      expect(fallback.createOrPropagate(exception)).andReturn(fallbackResponse);\n      replay(http, timeLimiter, fallback, config);\n      assertEquals(invokeHttpMethod.apply(get), fallbackResponse);\n   }\n\n   public void testTimeLimitedRunsFallbackCreateOrPropagate() throws Exception {\n      IllegalStateException exception = new IllegalStateException();\n      expect(config.getTimeoutNanos(get)).andReturn(Optional.of(250000000L));\n      InvokeAndTransform invoke = invokeHttpMethod.new InvokeAndTransform(\"ns:get\", getCommand);\n      expect(timeLimiter.callWithTimeout(invoke, 250000000, TimeUnit.NANOSECONDS)).andThrow(exception);\n      expect(fallback.createOrPropagate(exception)).andReturn(fallbackResponse);\n      replay(http, timeLimiter, fallback, config);\n      assertEquals(invokeHttpMethod.apply(get), fallbackResponse);\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/rest/internal/RestAnnotationProcessorTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.internal;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_XML;\nimport static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown;\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.jclouds.io.Payloads.newInputStreamPayload;\nimport static org.jclouds.io.Payloads.newStringPayload;\nimport static org.jclouds.providers.AnonymousProviderMetadata.forApiOnEndpoint;\nimport static org.jclouds.reflect.Reflection2.method;\nimport static org.jclouds.util.Strings2.urlEncode;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.Assert.fail;\n\nimport java.io.Closeable;\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.UnsupportedEncodingException;\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\nimport java.net.URI;\nimport java.net.URLEncoder;\nimport java.security.NoSuchAlgorithmException;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.Set;\nimport java.util.concurrent.ExecutionException;\n\nimport jakarta.inject.Named;\nimport jakarta.inject.Qualifier;\nimport jakarta.inject.Singleton;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.Encoded;\nimport jakarta.ws.rs.FormParam;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.HeaderParam;\nimport jakarta.ws.rs.HttpMethod;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Constants;\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpCommandExecutorService;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpRequestFilter;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.IOExceptionRetryHandler;\nimport org.jclouds.http.filters.ConnectionCloseHeader;\nimport org.jclouds.http.filters.StripExpectHeader;\nimport org.jclouds.http.functions.ParseFirstJsonValueNamed;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.http.functions.ParseURIFromListOrLocationHeaderIf20x;\nimport org.jclouds.http.functions.ReturnInputStream;\nimport org.jclouds.http.functions.ReturnStringIf2xx;\nimport org.jclouds.http.functions.ReturnTrueIf2xx;\nimport org.jclouds.http.functions.UnwrapOnlyJsonValue;\nimport org.jclouds.http.internal.PayloadEnclosingImpl;\nimport org.jclouds.http.options.BaseHttpRequestOptions;\nimport org.jclouds.http.options.GetOptions;\nimport org.jclouds.http.options.HttpRequestOptions;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.PayloadEnclosing;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.logging.config.NullLoggingModule;\nimport org.jclouds.reflect.Invocation;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.InvocationContext;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Delegate;\nimport org.jclouds.rest.annotations.Endpoint;\nimport org.jclouds.rest.annotations.EndpointParam;\nimport org.jclouds.rest.annotations.FormParams;\nimport org.jclouds.rest.annotations.Headers;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.OnlyElement;\nimport org.jclouds.rest.annotations.OverrideRequestFilters;\nimport org.jclouds.rest.annotations.ParamParser;\nimport org.jclouds.rest.annotations.PartParam;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.PayloadParams;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.Transform;\nimport org.jclouds.rest.annotations.Unwrap;\nimport org.jclouds.rest.annotations.VirtualHost;\nimport org.jclouds.rest.annotations.WrapWith;\nimport org.jclouds.rest.binders.BindAsHostPrefix;\nimport org.jclouds.rest.binders.BindToJsonPayload;\nimport org.jclouds.rest.binders.BindToStringPayload;\nimport org.jclouds.rest.config.HttpApiModule;\nimport org.jclouds.util.Strings2;\nimport org.testng.Assert;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.DataProvider;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Joiner;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSortedSet;\nimport com.google.common.collect.Lists;\nimport com.google.common.collect.Multimap;\nimport com.google.common.hash.Hashing;\nimport com.google.common.io.ByteSource;\nimport com.google.common.io.Files;\nimport com.google.common.net.HttpHeaders;\nimport com.google.common.reflect.Invokable;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.ConfigurationException;\nimport com.google.inject.Injector;\nimport com.google.inject.Module;\nimport com.google.inject.Provides;\nimport com.google.inject.TypeLiteral;\n\n@Test(groups = \"unit\", testName = \"RestAnnotationProcessorTest\")\npublic class RestAnnotationProcessorTest extends BaseRestApiTest {\n\n   @ConfiguresHttpApi\n   protected static class CallerModule extends HttpApiModule<Caller> {\n\n      @Override\n      protected void configure() {\n         super.configure();\n         bind(new TypeLiteral<Supplier<URI>>() {\n         }).annotatedWith(Localhost2.class).toInstance(Suppliers.ofInstance(URI.create(\"http://localhost:1111\")));\n         bind(IOExceptionRetryHandler.class).toInstance(IOExceptionRetryHandler.NEVER_RETRY);\n      }\n   }\n\n   @Path(\"/client/{jclouds.api-version}\")\n   interface Callee extends Closeable {\n      @GET\n      @Path(\"/{path}\")\n      void onePath(@PathParam(\"path\") String path);\n\n      @POST\n      void testWithoutProducesAndConsumes();\n\n      @POST\n      @Produces(APPLICATION_XML)\n      @Consumes(APPLICATION_XML)\n      void testProducesAndConsumesOnMethod();\n\n      @GET\n      void testWithEndpointParam(@EndpointParam URI endpoint);\n\n      @GET\n      @Endpoint(Localhost2.class)\n      void testWithEndpoint();\n   }\n\n   @Path(\"/client/{jclouds.api-version}\")\n   @Produces(APPLICATION_XML)\n   @Consumes(APPLICATION_XML)\n   interface CalleeWithProducesAndConsumesOnClass extends Closeable {\n      @POST\n      void testProducesAndConsumesOnClass();\n   }\n\n   @Path(\"/client/{jclouds.api-version}\")\n   interface Callee2 {\n      @GET\n      @Path(\"/{path}/2\")\n      void onePath(@PathParam(\"path\") String path);\n   }\n\n   @Endpoint(Localhost2.class)\n   interface Caller extends Closeable {\n      @Provides\n      @Localhost2\n      URI getURI();\n\n      @Delegate\n      Callee getCallee();\n\n      @Delegate\n      Callee2 getCallee2();\n\n      @Delegate\n      Callee getCallee(@EndpointParam URI endpoint);\n\n      @Delegate\n      Optional<Callee> getOptionalCallee(@EndpointParam URI endpoint);\n\n      @Delegate\n      @Path(\"/testing/testing/{wibble}\")\n      Callee getCalleeWithPath(@EndpointParam URI endpoint, @PathParam(\"wibble\") String wibble);\n\n      @Delegate\n      Callee getCalleeWithHeader(@EndpointParam URI endpoint, @HeaderParam(\"header\") String header);\n\n      @Delegate\n      @Produces(APPLICATION_JSON)\n      @Consumes(APPLICATION_JSON)\n      Callee getCalleeWithoutProducesAndConsumes();\n\n      @Delegate\n      @Produces(APPLICATION_JSON)\n      @Consumes(APPLICATION_JSON)\n      Callee getCalleeWithProducesAndConsumesOnMethod();\n\n      @Delegate\n      @Produces(APPLICATION_JSON)\n      @Consumes(APPLICATION_JSON)\n      CalleeWithProducesAndConsumesOnClass getCalleeWithProducesAndConsumesOnClass();\n   }\n\n   public void testDelegateIsLazyLoadedAndRequestIncludesVersionAndPath() throws InterruptedException,\n         ExecutionException {\n      Injector child = injectorForCaller(new HttpCommandExecutorService() {\n         int callCounter = 0;\n         @Override\n         public HttpResponse invoke(HttpCommand command) {\n            if (callCounter == 1)\n               assertEquals(command.getCurrentRequest().getRequestLine(),\n                     \"GET http://localhost:1111/client/1/bar/2 HTTP/1.1\");\n            else\n               assertEquals(command.getCurrentRequest().getRequestLine(),\n                     \"GET http://localhost:1111/client/1/foo HTTP/1.1\");\n            callCounter++;\n            return HttpResponse.builder().build();\n         }\n      });\n\n      try {\n         child.getInstance(Callee.class);\n         fail(\"Callee shouldn't be bound yet\");\n      } catch (ConfigurationException e) {\n\n      }\n\n      child.getInstance(Caller.class).getCallee().onePath(\"foo\");\n      child.getInstance(Caller.class).getCallee2().onePath(\"bar\");\n      // Note if wrong method is picked up, we'll see \"http://localhost:1111/client/1/foo/2\"!\n      child.getInstance(Caller.class).getCallee().onePath(\"foo\");\n   }\n\n   public void testDelegateWithPathParamIsLazyLoadedAndRequestIncludesEndpointVersionAndPath()\n         throws InterruptedException, ExecutionException {\n      Injector child = injectorForCaller(new HttpCommandExecutorService() {\n         @Override\n         public HttpResponse invoke(HttpCommand command) {\n            assertEquals(command.getCurrentRequest().getRequestLine(),\n                  \"GET http://howdyboys/testing/testing/thepathparam/client/1/foo HTTP/1.1\");\n            return HttpResponse.builder().build();\n         }\n      });\n\n      try {\n         child.getInstance(Callee.class);\n         fail(\"Callee shouldn't be bound yet\");\n      } catch (ConfigurationException e) {\n\n      }\n\n      child.getInstance(Caller.class).getCalleeWithPath(URI.create(\"http://howdyboys\"), \"thepathparam\")\n            .onePath(\"foo\");\n\n      assertEquals(child.getInstance(Caller.class).getURI(), URI.create(\"http://localhost:1111\"));\n   }\n\n   public void testDelegateWithHeaderParamIsLazyLoadedAndRequestIncludesEndpointVersionAndHeader()\n         throws InterruptedException, ExecutionException {\n      Injector child = injectorForCaller(new HttpCommandExecutorService() {\n         @Override\n         public HttpResponse invoke(HttpCommand command) {\n            assertEquals(command.getCurrentRequest().getFirstHeaderOrNull(\"header\"), \"theheaderparam\");\n            return HttpResponse.builder().build();\n         }\n      });\n\n      try {\n         child.getInstance(Callee.class);\n         fail(\"Callee shouldn't be bound yet\");\n      } catch (ConfigurationException e) {\n\n      }\n\n      child.getInstance(Caller.class).getCalleeWithHeader(URI.create(\"http://howdyboys\"), \"theheaderparam\")\n            .onePath(\"foo\");\n   }\n\n   public void testDelegateWithoutProducesAndConsumes()\n         throws InterruptedException, ExecutionException {\n      Injector child = injectorForCaller(new HttpCommandExecutorService() {\n         @Override\n         public HttpResponse invoke(HttpCommand command) {\n            assertEquals(\n                  command.getCurrentRequest().getPayload().getContentMetadata().getContentType(),\n                  APPLICATION_JSON);\n            assertTrue(command.getCurrentRequest().getHeaders().get(\"Accept\").contains(APPLICATION_JSON));\n            return HttpResponse.builder().build();\n         }\n      });\n\n      try {\n         child.getInstance(Callee.class);\n         fail(\"Callee shouldn't be bound yet\");\n      } catch (ConfigurationException e) {\n\n      }\n\n      child.getInstance(Caller.class).getCalleeWithoutProducesAndConsumes().testWithoutProducesAndConsumes();\n   }\n\n   public void testDelegateWithProducesAndConsumesOnMethodIsLazyLoaded()\n         throws InterruptedException, ExecutionException {\n      Injector child = injectorForCaller(new HttpCommandExecutorService() {\n         @Override\n         public HttpResponse invoke(HttpCommand command) {\n            assertEquals(\n                  command.getCurrentRequest().getPayload().getContentMetadata().getContentType(),\n                  APPLICATION_XML);\n            assertTrue(command.getCurrentRequest().getHeaders().get(\"Accept\").contains(APPLICATION_XML));\n            return HttpResponse.builder().build();\n         }\n\n      });\n\n      try {\n         child.getInstance(Callee.class);\n         fail(\"Callee shouldn't be bound yet\");\n      } catch (ConfigurationException e) {\n\n      }\n\n      child.getInstance(Caller.class).getCalleeWithProducesAndConsumesOnMethod().testProducesAndConsumesOnMethod();\n   }\n\n   public void testDelegateWithProducesAndConsumesOnClassIsLazyLoaded()\n         throws InterruptedException, ExecutionException {\n      Injector child = injectorForCaller(new HttpCommandExecutorService() {\n         @Override\n         public HttpResponse invoke(HttpCommand command) {\n            assertEquals(\n                  command.getCurrentRequest().getPayload().getContentMetadata().getContentType(),\n                  APPLICATION_XML);\n            assertTrue(command.getCurrentRequest().getHeaders().get(\"Accept\").contains(APPLICATION_XML));\n            return HttpResponse.builder().build();\n         }\n      });\n\n      try {\n         child.getInstance(Callee.class);\n         fail(\"Callee shouldn't be bound yet\");\n      } catch (ConfigurationException e) {\n\n      }\n\n      child.getInstance(Caller.class).getCalleeWithProducesAndConsumesOnClass().testProducesAndConsumesOnClass();\n   }\n\n   public void testDelegateIsLazyLoadedAndRequestIncludesEndpointVersionAndPathOptionalPresent()\n         throws InterruptedException, ExecutionException {\n      Injector child = injectorForCaller(new HttpCommandExecutorService() {\n         @Override\n         public HttpResponse invoke(HttpCommand command) {\n            assertEquals(command.getCurrentRequest().getRequestLine(), \"GET http://howdyboys/client/1/foo HTTP/1.1\");\n            return HttpResponse.builder().build();\n         }\n      });\n\n      try {\n         child.getInstance(Callee.class);\n         fail(\"Callee shouldn't be bound yet\");\n      } catch (ConfigurationException e) {\n\n      }\n\n      child.getInstance(Caller.class).getOptionalCallee(URI.create(\"http://howdyboys\")).get().onePath(\"foo\");\n\n      assertEquals(child.getInstance(Caller.class).getURI(), URI.create(\"http://localhost:1111\"));\n\n   }\n\n   public void testDelegateIsLazyLoadedAndRequestIncludesEndpointParamFromCallee()\n         throws InterruptedException, ExecutionException {\n      Injector child = injectorForCaller(new HttpCommandExecutorService() {\n         @Override\n         public HttpResponse invoke(HttpCommand command) {\n            assertEquals(command.getCurrentRequest().getRequestLine(), \"GET http://foo/bar/client/1 HTTP/1.1\");\n            return HttpResponse.builder().build();\n         }\n      });\n\n      try {\n         child.getInstance(Callee.class);\n         failBecauseExceptionWasNotThrown(ConfigurationException.class);\n      } catch (ConfigurationException e) {\n\n      }\n\n      child.getInstance(Caller.class).getCallee(URI.create(\"http://howdyboys\")).testWithEndpointParam(URI.create(\"http://foo/bar\"));\n   }\n\n   public void testDelegateIsLazyLoadedAndRequestIncludesEndpointFromCallee()\n         throws InterruptedException, ExecutionException {\n      Injector child = injectorForCaller(new HttpCommandExecutorService() {\n         @Override\n         public HttpResponse invoke(HttpCommand command) {\n            assertEquals(command.getCurrentRequest().getRequestLine(), \"GET http://localhost:1111/client/1 HTTP/1.1\");\n            return HttpResponse.builder().build();\n         }\n      });\n\n      try {\n         child.getInstance(Callee.class);\n         failBecauseExceptionWasNotThrown(ConfigurationException.class);\n      } catch (ConfigurationException e) {\n\n      }\n\n      child.getInstance(Caller.class).getCallee(URI.create(\"http://howdyboys\")).testWithEndpoint();\n   }\n\n   public void testDelegateIsLazyLoadedAndRequestIncludesEndpointVersionAndPath() throws InterruptedException,\n         ExecutionException {\n      Injector child = injectorForCaller(new HttpCommandExecutorService() {\n         @Override\n         public HttpResponse invoke(HttpCommand command) {\n            assertEquals(command.getCurrentRequest().getRequestLine(), \"GET http://howdyboys/client/1/foo HTTP/1.1\");\n            return HttpResponse.builder().build();\n         }\n      });\n\n      try {\n         child.getInstance(Callee.class);\n         fail(\"Callee shouldn't be bound yet\");\n      } catch (ConfigurationException e) {\n\n      }\n\n      assertEquals(child.getInstance(Caller.class).getURI(), URI.create(\"http://localhost:1111\"));\n\n   }\n\n   private Injector injectorForCaller(HttpCommandExecutorService service, Module... modules) {\n      return ContextBuilder.newBuilder(forApiOnEndpoint(Caller.class, \"http://localhost:9999\"))\n                           .modules(ImmutableSet.<Module> builder()\n                                                .add(new MockModule(service))\n                                                .add(new NullLoggingModule())\n                                                .add(new CallerModule())\n                                                .addAll(Arrays.asList(modules)).build()).buildInjector();\n\n   }\n\n   @Target({ ElementType.METHOD })\n   @Retention(RetentionPolicy.RUNTIME)\n   @jakarta.ws.rs.HttpMethod(\"FOO\")\n   public @interface FOO {\n   }\n\n   @Retention(value = RetentionPolicy.RUNTIME)\n   @Target(value = { ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })\n   @Qualifier\n   public @interface Localhost2 {\n   }\n\n   @QueryParams(keys = \"x-ms-version\", values = \"2009-07-17\")\n   public static class TestQuery {\n      @FOO\n      @Path(\"/\")\n      @QueryParams(keys = \"x-ms-rubbish\", values = \"bin\")\n      public void foo() {\n      }\n\n      @FOO\n      @Path(\"/\")\n      @QueryParams(keys = { \"foo\", \"fooble\" }, values = { \"bar\", \"baz\" })\n      public void foo2() {\n      }\n\n      @FOO\n      @Path(\"/\")\n      @QueryParams(keys = { \"foo\", \"fooble\" }, values = { \"bar\", \"baz\" })\n      public void foo3(@QueryParam(\"robbie\") String robbie) {\n      }\n\n      @FOO\n      @Path(\"/\")\n      @QueryParams(keys = { \"foo\", \"fooble\" }, values = { \"bar\", \"baz\" })\n      public void foo3Nullable(@Nullable @QueryParam(\"robbie\") String robbie) {\n      }\n\n      @FOO\n      @Path(\"/\")\n      public void queryParamIterable(@Nullable @QueryParam(\"foo\") Iterable<String> bars) {\n      }\n\n      @FOO\n      @Path(\"/\")\n      @QueryParams(keys = { \"test param\"}, values = { \"foo bar\" })\n      public void queryKeyEncoded() {\n      }\n   }\n\n   public void testQuery() throws SecurityException, NoSuchMethodException {\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method(TestQuery.class, \"foo\")));\n      assertEquals(request.getEndpoint().getHost(), \"localhost\");\n      assertEquals(request.getEndpoint().getPath(), \"/\");\n      assertEquals(request.getEndpoint().getQuery(), \"x-ms-version=2009-07-17&x-ms-rubbish=bin\");\n      assertEquals(request.getMethod(), \"FOO\");\n   }\n\n   public void testQuery2() throws SecurityException, NoSuchMethodException {\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method(TestQuery.class, \"foo2\")));\n      assertEquals(request.getEndpoint().getHost(), \"localhost\");\n      assertEquals(request.getEndpoint().getPath(), \"/\");\n      assertEquals(request.getEndpoint().getQuery(), \"x-ms-version=2009-07-17&foo=bar&fooble=baz\");\n      assertEquals(request.getMethod(), \"FOO\");\n   }\n\n   public void testQuery3() throws SecurityException, NoSuchMethodException {\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method(TestQuery.class, \"foo3\", String.class),\n            ImmutableList.<Object> of(\"wonder\")));\n      assertEquals(request.getEndpoint().getHost(), \"localhost\");\n      assertEquals(request.getEndpoint().getPath(), \"/\");\n      assertEquals(request.getEndpoint().getQuery(), \"x-ms-version=2009-07-17&foo=bar&fooble=baz&robbie=wonder\");\n      assertEquals(request.getMethod(), \"FOO\");\n   }\n\n   @Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = \"param\\\\{robbie\\\\} for invocation TestQuery.foo3\")\n   public void testNiceNPEQueryParam() throws Exception {\n      processor.apply(Invocation.create(method(TestQuery.class, \"foo3\", String.class),\n            Lists.<Object> newArrayList((String) null)));\n   }\n\n   public void testNoNPEOnQueryParamWithNullable() throws SecurityException, NoSuchMethodException {\n      GeneratedHttpRequest request = processor.apply(Invocation.create(\n            method(TestQuery.class, \"foo3Nullable\", String.class), Lists.<Object> newArrayList((String) null)));\n      assertEquals(request.getEndpoint().getHost(), \"localhost\");\n      assertEquals(request.getEndpoint().getPath(), \"/\");\n      assertEquals(request.getEndpoint().getQuery(), \"x-ms-version=2009-07-17&foo=bar&fooble=baz\");\n      assertEquals(request.getMethod(), \"FOO\");\n   }\n\n   public void testQueryParamIterableOneString() throws SecurityException, NoSuchMethodException {\n      GeneratedHttpRequest request = processor.apply(Invocation.create(\n            method(TestQuery.class, \"queryParamIterable\", Iterable.class),\n            ImmutableList.<Object> of(ImmutableSet.of(\"1\"))));\n      assertEquals(request.getEndpoint().getHost(), \"localhost\");\n      assertEquals(request.getEndpoint().getPath(), \"/\");\n      assertEquals(request.getEndpoint().getQuery(), \"x-ms-version=2009-07-17&foo=1\");\n      assertEquals(request.getMethod(), \"FOO\");\n   }\n\n   public void testQueryParamIterableString() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> method = method(TestQuery.class, \"queryParamIterable\", Iterable.class);\n      Set<String> bars = ImmutableSortedSet.of(\"1\", \"2\", \"3\");\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method, ImmutableList.<Object> of(bars)));\n      assertEquals(request.getEndpoint().getHost(), \"localhost\");\n      assertEquals(request.getEndpoint().getPath(), \"/\");\n      assertEquals(request.getEndpoint().getQuery(), \"x-ms-version=2009-07-17&foo=1&foo=2&foo=3\");\n      assertEquals(request.getMethod(), \"FOO\");\n   }\n\n   public void testQueryParamIterableInteger() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> method = method(TestQuery.class, \"queryParamIterable\", Iterable.class);\n      Set<Integer> bars = ImmutableSortedSet.of(1, 2, 3);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method, ImmutableList.<Object> of(bars)));\n      assertEquals(request.getEndpoint().getHost(), \"localhost\");\n      assertEquals(request.getEndpoint().getPath(), \"/\");\n      assertEquals(request.getEndpoint().getQuery(), \"x-ms-version=2009-07-17&foo=1&foo=2&foo=3\");\n      assertEquals(request.getMethod(), \"FOO\");\n   }\n\n   public void testQueryParamIterableEmpty() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> method = method(TestQuery.class, \"queryParamIterable\", Iterable.class);\n      Set<String> bars = Collections.emptySet();\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method, ImmutableList.<Object> of(bars)));\n      assertEquals(request.getEndpoint().getHost(), \"localhost\");\n      assertEquals(request.getEndpoint().getPath(), \"/\");\n      assertEquals(request.getEndpoint().getQuery(), \"x-ms-version=2009-07-17\");\n      assertEquals(request.getMethod(), \"FOO\");\n   }\n\n   public void testQueryParamIterableNull() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> method = method(TestQuery.class, \"queryParamIterable\", Iterable.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method,\n            Lists.<Object> newArrayList((String) null)));\n      assertEquals(request.getEndpoint().getHost(), \"localhost\");\n      assertEquals(request.getEndpoint().getPath(), \"/\");\n      assertEquals(request.getEndpoint().getQuery(), \"x-ms-version=2009-07-17\");\n      assertEquals(request.getMethod(), \"FOO\");\n   }\n\n   public void testQueryEncodedKey() throws SecurityException, NoSuchMethodException {\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method(TestQuery.class, \"queryKeyEncoded\")));\n      assertEquals(request.getEndpoint().getHost(), \"localhost\");\n      assertEquals(request.getEndpoint().getPath(), \"/\");\n      assertEquals(request.getEndpoint().getRawQuery(), \"x-ms-version=2009-07-17&test%20param=foo%20bar\");\n      assertEquals(request.getMethod(), \"FOO\");\n   }\n\n   @QueryParams(keys = \"test%param\", values = \"percent%\")\n   public static class TestInterfaceQueryParam {\n      @FOO\n      @Path(\"/\")\n      public void query() {\n      }\n   }\n\n   public void testInterfaceEncodedKey() throws SecurityException, NoSuchMethodException {\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method(TestInterfaceQueryParam.class, \"query\")));\n      assertEquals(request.getEndpoint().getHost(), \"localhost\");\n      assertEquals(request.getEndpoint().getPath(), \"/\");\n      assertEquals(request.getEndpoint().getRawQuery(), \"test%25param=percent%25\");\n      assertEquals(request.getMethod(), \"FOO\");\n   }\n\n   interface TestPayloadParamVarargs {\n      @POST\n      void varargs(HttpRequestOptions... options);\n\n      @POST\n      void varargsWithReq(String required, HttpRequestOptions... options);\n\n      @POST\n      void post(HttpRequestOptions options);\n\n      @POST\n      @Produces(MediaType.APPLICATION_OCTET_STREAM)\n      void post();\n\n      @POST\n      @Produces(MediaType.APPLICATION_OCTET_STREAM)\n      void post(Payload payload);\n   }\n\n   public void testHttpRequestOptionsNoPayloadParam() throws Exception {\n      Invokable<?, ?> method = method(TestPayloadParamVarargs.class, \"post\");\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method));\n      assertRequestLineEquals(request, \"POST http://localhost:9999 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"\");\n      assertPayloadEquals(request, \"\", \"application/octet-stream\", false);\n   }\n\n   private static class TestHttpRequestOptions extends BaseHttpRequestOptions {\n      TestHttpRequestOptions payload(String payload) {\n         this.payload = payload;\n         return this;\n      }\n\n      TestHttpRequestOptions headerParams(Multimap<String, String> headers) {\n         this.headers.putAll(headers);\n         return this;\n      }\n\n      TestHttpRequestOptions queryParams(Multimap<String, String> params) {\n         this.queryParameters.putAll(params);\n         return this;\n      }\n   }\n\n   public void testHttpRequestOptionsPayloadParam() throws Exception {\n      Invokable<?, ?> method = method(TestPayloadParamVarargs.class, \"post\", Payload.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(Payloads.newStringPayload(\"foo\"))));\n      assertRequestLineEquals(request, \"POST http://localhost:9999 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"\");\n      assertPayloadEquals(request, \"foo\", \"application/octet-stream\", false);\n   }\n\n   public void testHttpRequestWithOnlyContentType() throws Exception {\n      Invokable<?, ?> method = method(TestPayloadParamVarargs.class, \"post\", HttpRequestOptions.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(new TestHttpRequestOptions().payload(\"fooya\"))));\n      assertRequestLineEquals(request, \"POST http://localhost:9999 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"\");\n      assertPayloadEquals(request, \"fooya\", \"application/unknown\", false);\n   }\n\n   public void testHeaderAndQueryVarargs() throws Exception {\n      Invokable<?, ?> method = method(TestPayloadParamVarargs.class, \"varargs\",\n            HttpRequestOptions[].class);\n      GeneratedHttpRequest request = processor.apply(\n            Invocation.create(method,\n            ImmutableList.<Object> of(new TestHttpRequestOptions().payload(\"fooya\"),\n                  new TestHttpRequestOptions().headerParams(ImmutableMultimap.of(\"X-header-1\", \"fooya\")),\n                  new TestHttpRequestOptions().queryParams(ImmutableMultimap.of(\"key\", \"value\")))));\n      assertRequestLineEquals(request, \"POST http://localhost:9999?key=value HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"X-header-1: fooya\\n\");\n      assertPayloadEquals(request, \"fooya\", \"application/unknown\", false);\n   }\n\n   public void testHeaderAndQueryVarargsPlusReq() throws Exception {\n      Invokable<?, ?> method = method(TestPayloadParamVarargs.class, \"varargsWithReq\", String.class,\n            HttpRequestOptions[].class);\n      GeneratedHttpRequest request = processor.apply(\n            Invocation.create(method,\n            ImmutableList.<Object> of(\"required param\", new TestHttpRequestOptions().payload(\"fooya\"),\n                  new TestHttpRequestOptions().headerParams(ImmutableMultimap.of(\"X-header-1\", \"fooya\")),\n                  new TestHttpRequestOptions().queryParams(ImmutableMultimap.of(\"key\", \"value\")))));\n      assertRequestLineEquals(request, \"POST http://localhost:9999?key=value HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"X-header-1: fooya\\n\");\n      assertPayloadEquals(request, \"fooya\", \"application/unknown\", false);\n   }\n\n   public void testQueryVarargsEncoding() throws Exception {\n      Invokable<?, ?> method = method(TestPayloadParamVarargs.class, \"varargsWithReq\", String.class,\n            HttpRequestOptions[].class);\n      GeneratedHttpRequest request = processor.apply(\n            Invocation.create(method,\n                  ImmutableList.<Object> of(\"required param\",\n                        new TestHttpRequestOptions().queryParams(ImmutableMultimap.of(\"key\", \"foo bar\")))));\n      assertRequestLineEquals(request, \"POST http://localhost:9999?key=foo%20bar HTTP/1.1\");\n   }\n\n   public void testDuplicateHeaderAndQueryVarargs() throws Exception {\n      Invokable<?, ?> method = method(TestPayloadParamVarargs.class, \"varargs\",\n            HttpRequestOptions[].class);\n      GeneratedHttpRequest request = processor.apply(\n            Invocation.create(method,\n            ImmutableList.<Object> of(new TestHttpRequestOptions().queryParams(ImmutableMultimap.of(\"key\", \"value\")),\n                  new TestHttpRequestOptions().payload(\"fooya\"),\n                  new TestHttpRequestOptions().headerParams(ImmutableMultimap.of(\"X-header-1\", \"fooya\")),\n                  new TestHttpRequestOptions().queryParams(ImmutableMultimap.of(\"key\", \"anothervalue\")),\n                  new TestHttpRequestOptions().headerParams(ImmutableMultimap.of(\"X-header-1\", \"fooya again!\")),\n                  new TestHttpRequestOptions().payload(\"last_payload_wins!\"))));\n      assertRequestLineEquals(request, \"POST http://localhost:9999?key=value&key=anothervalue HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"X-header-1: fooya\\nX-header-1: fooya again!\\n\");\n      assertPayloadEquals(request, \"last_payload_wins!\", \"application/unknown\", false);\n   }\n\n   public static class TestCustomMethod {\n      @FOO\n      public void foo() {\n      }\n   }\n\n   public void testCustomMethod() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> method = method(TestCustomMethod.class, \"foo\");\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method));\n      assertEquals(request.getEndpoint().getHost(), \"localhost\");\n      assertEquals(request.getEndpoint().getPath(), \"\");\n      assertEquals(request.getMethod(), \"FOO\");\n   }\n\n   interface Parent {\n      void foo();\n   }\n\n   public static class TestOverridden implements Parent {\n      @POST\n      public void foo() {\n      }\n   }\n\n   public void testOverriddenMethod() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> method = method(TestOverridden.class, \"foo\");\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method));\n      assertEquals(request.getEndpoint().getHost(), \"localhost\");\n      assertEquals(request.getEndpoint().getPath(), \"\");\n      assertEquals(request.getMethod(), \"POST\");\n   }\n\n   public static class TestOverriddenEndpoint implements Parent {\n\n      @POST\n      @Endpoint(Localhost2.class)\n      public void foo() {\n      }\n\n      @POST\n      public void foo(@EndpointParam URI endpoint) {\n      }\n   }\n\n   public void testOverriddenEndpointMethod() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> method = method(TestOverriddenEndpoint.class, \"foo\");\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method));\n      assertEquals(request.getEndpoint().getHost(), \"localhost\");\n      assertEquals(request.getEndpoint().getPort(), 1111);\n      assertEquals(request.getEndpoint().getPath(), \"\");\n      assertEquals(request.getMethod(), \"POST\");\n   }\n\n   public void testOverriddenEndpointParameter() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> method = method(TestOverriddenEndpoint.class, \"foo\", URI.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(URI.create(\"http://wowsa:8001\"))));\n      assertEquals(request.getEndpoint().getHost(), \"wowsa\");\n      assertEquals(request.getEndpoint().getPort(), 8001);\n      assertEquals(request.getEndpoint().getPath(), \"\");\n      assertEquals(request.getMethod(), \"POST\");\n   }\n\n   interface TestPost {\n      @POST\n      void post(@Nullable @BinderParam(BindToStringPayload.class) String content);\n\n      @POST\n      void postNonnull(@BinderParam(BindToStringPayload.class) String content);\n\n      @POST\n      void postAsJson(@BinderParam(BindToJsonPayload.class) String content);\n\n      @POST\n      @Path(\"/{foo}\")\n      void postWithPath(@PathParam(\"foo\") @PayloadParam(\"fooble\") String path, MapBinder content);\n\n      @POST\n      @Path(\"/{foo}\")\n      @MapBinder(BindToJsonPayload.class)\n      void postWithMethodBinder(@PathParam(\"foo\") @PayloadParam(\"fooble\") String path);\n\n      @POST\n      @Path(\"/{foo}\")\n      @PayloadParams(keys = \"rat\", values = \"atat\")\n      @MapBinder(BindToJsonPayload.class)\n      void postWithMethodBinderAndDefaults(@PathParam(\"foo\") @PayloadParam(\"fooble\") String path);\n\n      @POST\n      @Path(\"/{foo}\")\n      @PayloadParams(keys = \"rat\", values = \"atat\")\n      @org.jclouds.rest.annotations.Payload(\"name {fooble}\")\n      @Produces(MediaType.TEXT_PLAIN)\n      void testPayload(@PathParam(\"foo\") @PayloadParam(\"fooble\") String path);\n   }\n\n   public void testCreatePostRequest() throws Exception {\n      Invokable<?, ?> method = method(TestPost.class, \"post\", String.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method, ImmutableList.<Object> of(\"data\")));\n\n      assertRequestLineEquals(request, \"POST http://localhost:9999 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"\");\n      assertPayloadEquals(request, \"data\", \"application/unknown\", false);\n   }\n\n   public void testCreatePostRequestNullOk1() throws Exception {\n      Invokable<?, ?> method = method(TestPost.class, \"post\", String.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method,\n            Lists.<Object> newArrayList((String) null)));\n\n      assertRequestLineEquals(request, \"POST http://localhost:9999 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"\");\n      assertPayloadEquals(request, null, \"application/unknown\", false);\n   }\n\n   public void testCreatePostRequestNullOk2() throws Exception {\n      Invokable<?, ?> method = method(TestPost.class, \"post\", String.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method,\n            Lists.<Object> newArrayList((String) null)));\n\n      assertRequestLineEquals(request, \"POST http://localhost:9999 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"\");\n      assertPayloadEquals(request, null, \"application/unknown\", false);\n   }\n\n   public void testCreatePostRequestNullNotOk1() throws Exception {\n      Invokable<?, ?> method = method(TestPost.class, \"postNonnull\", String.class);\n      try {\n         GeneratedHttpRequest request = processor.apply(Invocation.create(method,\n               Lists.<Object> newArrayList((String) null)));\n         Assert.fail(\"call should have failed with illegal null parameter, not permitted \" + request + \" to be created\");\n      } catch (NullPointerException e) {\n         assertTrue(e.toString().indexOf(\"postNonnull parameter 1\") >= 0,\n            \"Error message should have referred to 'parameter 1': \" + e);\n      }\n   }\n\n   @Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = \"postNonnull parameter 1\")\n   public void testCreatePostRequestNullNotOk2() throws Exception {\n      Invokable<?, ?> method = method(TestPost.class, \"postNonnull\", String.class);\n      processor.apply(Invocation.create(method, Lists.<Object> newArrayList((String) null)));\n   }\n\n   public void testCreatePostJsonRequest() throws Exception {\n      Invokable<?, ?> method = method(TestPost.class, \"postAsJson\", String.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method, ImmutableList.<Object> of(\"data\")));\n\n      assertRequestLineEquals(request, \"POST http://localhost:9999 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"\");\n      assertPayloadEquals(request, \"\\\"data\\\"\", APPLICATION_JSON, false);\n   }\n\n   public void testCreatePostWithPathRequest() throws Exception {\n      Invokable<?, ?> method = method(TestPost.class, \"postWithPath\", String.class, MapBinder.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(\"data\", new org.jclouds.rest.MapBinder() {\n               @Override\n               public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n                  request.setPayload((String) postParams.get(\"fooble\"));\n                  return request;\n               }\n\n               @Override\n               public <R extends HttpRequest> R bindToRequest(R request, Object toBind) {\n                  throw new RuntimeException(\"this shouldn't be used in POST\");\n               }\n            })));\n      assertRequestLineEquals(request, \"POST http://localhost:9999/data HTTP/1.1\");\n      assertPayloadEquals(request, \"data\", \"application/unknown\", false);\n   }\n\n   public void testCreatePostWithMethodBinder() throws Exception {\n      Invokable<?, ?> method = method(TestPost.class, \"postWithMethodBinder\", String.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method, ImmutableList.<Object> of(\"data\")));\n\n      assertRequestLineEquals(request, \"POST http://localhost:9999/data HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"\");\n      assertPayloadEquals(request, \"{\\\"fooble\\\":\\\"data\\\"}\", APPLICATION_JSON, false);\n   }\n\n   public void testCreatePostWithMethodBinderAndDefaults() throws Exception {\n      Invokable<?, ?> method = method(TestPost.class, \"postWithMethodBinderAndDefaults\", String.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method, ImmutableList.<Object> of(\"data\")));\n\n      assertRequestLineEquals(request, \"POST http://localhost:9999/data HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"\");\n      assertPayloadEquals(request, \"{\\\"fooble\\\":\\\"data\\\",\\\"rat\\\":\\\"atat\\\"}\", APPLICATION_JSON, false);\n   }\n\n   public void testCreatePostWithPayload() throws Exception {\n      Invokable<?, ?> method = method(TestPost.class, \"testPayload\", String.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method, ImmutableList.<Object> of(\"data\")));\n\n      assertRequestLineEquals(request, \"POST http://localhost:9999/data HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"\");\n      assertPayloadEquals(request, \"name data\", \"text/plain\", false);\n   }\n\n   interface TestMultipartForm {\n      @POST\n      void withStringPart(@PartParam(name = \"fooble\") String path);\n\n      @POST\n      void withParamStringPart(@FormParam(\"name\") String name, @PartParam(name = \"file\") String path);\n\n      @POST\n      void withParamFilePart(@FormParam(\"name\") String name, @PartParam(name = \"file\") File path);\n\n      @POST\n      void withParamFileBinaryPart(@FormParam(\"name\") String name,\n            @PartParam(name = \"file\", contentType = MediaType.APPLICATION_OCTET_STREAM) File path);\n\n      @POST\n      void withParamByteArrayBinaryPart(\n            @FormParam(\"name\") String name,\n            @PartParam(name = \"file\", contentType = MediaType.APPLICATION_OCTET_STREAM, filename = \"{name}.tar.gz\") byte[] content);\n   }\n\n   public void testMultipartWithStringPart() throws Exception {\n      Invokable<?, ?> method = method(TestMultipartForm.class, \"withStringPart\", String.class);\n      GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(\"foobledata\")));\n      assertRequestLineEquals(httpRequest, \"POST http://localhost:9999 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest,\n            \"----JCLOUDS--\\r\\n\" + //\n                  \"Content-Disposition: form-data; name=\\\"fooble\\\"\\r\\n\" + //\n                  \"\\r\\n\" + //\n                  \"foobledata\\r\\n\" + //\n                  \"----JCLOUDS----\\r\\n\", \"multipart/form-data; boundary=--JCLOUDS--\", false);\n   }\n\n   @Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = \"fooble\")\n   public void testMultipartWithStringPartNullNotOkay() throws Exception {\n      Invokable<?, ?> method = method(TestMultipartForm.class, \"withStringPart\", String.class);\n      processor.apply(Invocation.create(method, Lists.<Object> newArrayList((String) null)));\n   }\n\n   public void testMultipartWithParamStringPart() throws Exception {\n      Invokable<?, ?> method = method(TestMultipartForm.class, \"withParamStringPart\", String.class,\n            String.class);\n      GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(\"name\", \"foobledata\")));\n      assertRequestLineEquals(httpRequest, \"POST http://localhost:9999 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest,\n            \"----JCLOUDS--\\r\\n\" + //\n                  \"Content-Disposition: form-data; name=\\\"name\\\"\\r\\n\" + //\n                  \"\\r\\n\" + //\n                  \"name\\r\\n\" + // /\n                  \"----JCLOUDS--\\r\\n\" + //\n                  \"Content-Disposition: form-data; name=\\\"file\\\"\\r\\n\" + //\n                  \"\\r\\n\" + //\n                  \"foobledata\\r\\n\" + //\n                  \"----JCLOUDS----\\r\\n\", \"multipart/form-data; boundary=--JCLOUDS--\", false);\n   }\n\n   @Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = \"param\\\\{name\\\\} for invocation TestMultipartForm.withParamStringPart\")\n   public void testMultipartWithParamStringPartNullNotOk() throws Exception {\n      Invokable<?, ?> method = method(TestMultipartForm.class, \"withParamStringPart\", String.class,\n            String.class);\n      processor.apply(Invocation.create(method, Lists.<Object> newArrayList(null, \"foobledata\")));\n   }\n\n   public void testMultipartWithParamFilePart() throws Exception {\n      Invokable<?, ?> method = method(TestMultipartForm.class, \"withParamFilePart\", String.class,\n            File.class);\n      File file = java.nio.file.Files.createTempFile(\"foo\", \"bar\").toFile();\n      try {\n         Files.append(\"foobledata\", file, UTF_8);\n\n         GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,\n               ImmutableList.<Object> of(\"name\", file)));\n         assertRequestLineEquals(httpRequest, \"POST http://localhost:9999 HTTP/1.1\");\n         assertNonPayloadHeadersEqual(httpRequest, \"\");\n         assertPayloadEquals(httpRequest,\n               \"----JCLOUDS--\\r\\n\" + //\n                     \"Content-Disposition: form-data; name=\\\"name\\\"\\r\\n\" + //\n                     \"\\r\\n\" + //\n                     \"name\\r\\n\" + // /\n                     \"----JCLOUDS--\\r\\n\" + //\n                     \"Content-Disposition: form-data; name=\\\"file\\\"; filename=\\\"\" + file.getName() + \"\\\"\\r\\n\" + //\n                     \"\\r\\n\" + //\n                     \"foobledata\\r\\n\" + //\n                     \"----JCLOUDS----\\r\\n\", \"multipart/form-data; boundary=--JCLOUDS--\", false);\n      } finally {\n         file.delete();\n      }\n   }\n\n   public void testMultipartWithParamByteArrayPart() throws Exception {\n      Invokable<?, ?> method = method(TestMultipartForm.class, \"withParamByteArrayBinaryPart\",\n            String.class, byte[].class);\n      GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(\"name\", \"goo\".getBytes())));\n      assertRequestLineEquals(httpRequest, \"POST http://localhost:9999 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest,\n            \"----JCLOUDS--\\r\\n\" + //\n                  \"Content-Disposition: form-data; name=\\\"name\\\"\\r\\n\" + //\n                  \"\\r\\n\" + //\n                  \"name\\r\\n\" + // /\n                  \"----JCLOUDS--\\r\\n\" + //\n                  \"Content-Disposition: form-data; name=\\\"file\\\"; filename=\\\"name.tar.gz\\\"\\r\\n\" + //\n                  \"Content-Type: application/octet-stream\\r\\n\" + //\n                  \"\\r\\n\" + //\n                  \"goo\\r\\n\" + //\n                  \"----JCLOUDS----\\r\\n\", \"multipart/form-data; boundary=--JCLOUDS--\", false);\n   };\n\n   public void testMultipartWithParamFileBinaryPart() throws Exception {\n      Invokable<?, ?> method = method(TestMultipartForm.class, \"withParamFileBinaryPart\",\n            String.class, File.class);\n      File file = java.nio.file.Files.createTempFile(\"foo\", \"bar\").toFile();\n      try {\n         Files.write(new byte[] { 17, 26, 39, 40, 50 }, file);\n\n         GeneratedHttpRequest httpRequest = processor.apply(Invocation.create(method,\n               ImmutableList.<Object> of(\"name\", file)));\n         assertRequestLineEquals(httpRequest, \"POST http://localhost:9999 HTTP/1.1\");\n         assertNonPayloadHeadersEqual(httpRequest, \"\");\n         assertPayloadEquals(httpRequest,\n               \"----JCLOUDS--\\r\\n\" + //\n                     \"Content-Disposition: form-data; name=\\\"name\\\"\\r\\n\" + //\n                     \"\\r\\n\" + //\n                     \"name\\r\\n\" + // /\n                     \"----JCLOUDS--\\r\\n\" + //\n                     \"Content-Disposition: form-data; name=\\\"file\\\"; filename=\\\"\" + file.getName() + \"\\\"\\r\\n\" + //\n                     \"Content-Type: application/octet-stream\\r\\n\" + //\n                     \"\\r\\n\" + //\n                     \"\u0011\u001a'(2\\r\\n\" + //\n                     \"----JCLOUDS----\\r\\n\", \"multipart/form-data; boundary=--JCLOUDS--\", false);\n      } finally {\n         file.delete();\n      }\n   }\n\n   interface TestPut {\n      @PUT\n      @Path(\"/{foo}\")\n      @MapBinder(BindToJsonPayload.class)\n      void putWithMethodBinder(@PathParam(\"foo\") @PayloadParam(\"fooble\") String path);\n\n      @PUT\n      @Path(\"/{foo}\")\n      @Produces(MediaType.TEXT_PLAIN)\n      void putWithMethodBinderProduces(@PathParam(\"foo\") @BinderParam(BindToStringPayload.class) String path);\n\n      @PUT\n      @Path(\"/{foo}\")\n      @MapBinder(BindToJsonPayload.class)\n      @Consumes(APPLICATION_JSON)\n      View putWithMethodBinderConsumes(@PathParam(\"foo\") @PayloadParam(\"fooble\") String path);\n\n      @GET\n      @Path(\"/\")\n      @Consumes(APPLICATION_JSON)\n      Map<String, String> testGeneric();\n\n      @GET\n      @Path(\"/\")\n      @Consumes(APPLICATION_JSON)\n      Map<String, String> testGeneric2();\n\n      @GET\n      @Path(\"/\")\n      @Consumes(APPLICATION_JSON)\n      Map<String, String> testGeneric3();\n\n      @GET\n      @Path(\"/\")\n      @Unwrap\n      @Consumes(APPLICATION_JSON)\n      String testUnwrap();\n\n      @GET\n      @Path(\"/\")\n      @SelectJson(\"foo\")\n      @Consumes(APPLICATION_JSON)\n      String testUnwrapValueNamed();\n\n      @POST\n      @Path(\"/\")\n      String testWrapWith(@WrapWith(\"foo\") String param);\n\n      @GET\n      @Path(\"/\")\n      @Unwrap\n      @Consumes(APPLICATION_JSON)\n      String testUnwrap2();\n\n      @GET\n      @Path(\"/\")\n      @Unwrap\n      @Consumes(APPLICATION_JSON)\n      Set<String> testUnwrap3();\n\n      @GET\n      @Path(\"/\")\n      @Unwrap\n      @Consumes(APPLICATION_JSON)\n      Set<String> testUnwrap4();\n\n      @GET\n      @Path(\"/\")\n      @SelectJson(\"jobid\")\n      Long selectLong();\n\n      @GET\n      @Path(\"/\")\n      @SelectJson(\"jobid\")\n      @Transform(AddOne.class)\n      Long selectLongAddOne();\n\n      static class AddOne implements Function<Long, Long> {\n\n         @Override\n         public Long apply(Long o) {\n            return o + 1;\n         }\n      }\n\n      @GET\n      @Path(\"/\")\n      @SelectJson(\"runit\")\n      @OnlyElement\n      @Consumes(APPLICATION_JSON)\n      String selectOnlyElement();\n\n      @Target({ ElementType.METHOD })\n      @Retention(RetentionPolicy.RUNTIME)\n      @HttpMethod(\"ROWDY\")\n      @interface ROWDY {\n      }\n\n      @ROWDY\n      @Path(\"/strings/{id}\")\n      Boolean rowdy(@PathParam(\"id\") String path);\n\n      @ROWDY\n      @Path(\"/ints/{id}\")\n      Boolean rowdy(@PathParam(\"id\") int path);\n   }\n\n   static class View {\n      String foo;\n   }\n\n   public void testAlternateHttpMethod() throws Exception {\n      Invokable<?, ?> method = method(TestPut.class, \"rowdy\", String.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method, ImmutableList.<Object> of(\"data\")));\n\n      assertRequestLineEquals(request, \"ROWDY http://localhost:9999/strings/data HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"\");\n      assertPayloadEquals(request, null, null, false);\n   }\n\n   public void testAlternateHttpMethodSameArity() throws Exception {\n      Invokable<?, ?> method = method(TestPut.class, \"rowdy\", int.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method, ImmutableList.<Object> of(\"data\")));\n\n      assertRequestLineEquals(request, \"ROWDY http://localhost:9999/ints/data HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"\");\n      assertPayloadEquals(request, null, null, false);\n   }\n\n   public void testCreatePutWithMethodBinder() throws Exception {\n      Invokable<?, ?> method = method(TestPut.class, \"putWithMethodBinder\", String.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method, ImmutableList.<Object> of(\"data\")));\n\n      assertRequestLineEquals(request, \"PUT http://localhost:9999/data HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"\");\n      assertPayloadEquals(request, \"{\\\"fooble\\\":\\\"data\\\"}\", APPLICATION_JSON, false);\n   }\n\n   public void testCreatePutWithMethodProduces() throws Exception {\n      Invokable<?, ?> method = method(TestPut.class, \"putWithMethodBinderProduces\", String.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method, ImmutableList.<Object> of(\"data\")));\n\n      assertRequestLineEquals(request, \"PUT http://localhost:9999/data HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"\");\n      assertPayloadEquals(request, \"data\", \"text/plain\", false);\n   }\n\n   public void testCreatePutWithMethodConsumes() throws Exception {\n      Invokable<?, ?> method = method(TestPut.class, \"putWithMethodBinderConsumes\", String.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method, ImmutableList.<Object> of(\"data\")));\n\n      assertRequestLineEquals(request, \"PUT http://localhost:9999/data HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Accept: application/json\\n\");\n      assertPayloadEquals(request, \"{\\\"fooble\\\":\\\"data\\\"}\", APPLICATION_JSON, false);\n\n      assertResponseParserClassEquals(method, request, ParseJson.class);\n      Function<HttpResponse, ?> parser = transformer.apply(request);\n\n      assertEquals(\n            View.class.cast(parser.apply(HttpResponse.builder().statusCode(200).message(\"ok\").payload(\"{ foo:\\\"bar\\\"}\").build())).foo,\n            \"bar\");\n\n   }\n\n   public void testGeneric1() throws Exception {\n      Invokable<?, ?> method = method(TestPut.class, \"testGeneric\");\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method));\n\n      assertResponseParserClassEquals(method, request, ParseJson.class);\n      Function<HttpResponse, ?> parser = transformer.apply(request);\n\n      assertEquals(\n            parser.apply(HttpResponse.builder().statusCode(200).message(\"ok\").payload(\"{ foo:\\\"bar\\\"}\").build()),\n            ImmutableMap.of(\"foo\", \"bar\"));\n   }\n\n   public void testGeneric2() throws Exception {\n      Invokable<?, ?> method = method(TestPut.class, \"testGeneric2\");\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method));\n\n      assertResponseParserClassEquals(method, request, ParseJson.class);\n      Function<HttpResponse, ?> parser = transformer.apply(request);\n\n      assertEquals(\n            parser.apply(HttpResponse.builder().statusCode(200).message(\"ok\").payload(\"{ foo:\\\"bar\\\"}\").build()),\n            ImmutableMap.of(\"foo\", \"bar\"));\n\n   }\n\n   public void testGeneric3() throws Exception {\n      Invokable<?, ?> method = method(TestPut.class, \"testGeneric3\");\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method));\n\n      assertResponseParserClassEquals(method, request, ParseJson.class);\n      Function<HttpResponse, ?> parser = transformer.apply(request);\n\n      assertEquals(\n            parser.apply(HttpResponse.builder().statusCode(200).message(\"ok\").payload(\"{ foo:\\\"bar\\\"}\").build()),\n            ImmutableMap.of(\"foo\", \"bar\"));\n\n   }\n\n   public void testUnwrap1() throws Exception {\n      Invokable<?, ?> method = method(TestPut.class, \"testUnwrap\");\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method));\n\n      assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);\n      Function<HttpResponse, ?> parser = transformer.apply(request);\n\n      assertEquals(\n            parser.apply(HttpResponse.builder().statusCode(200).message(\"ok\").payload(\"{ foo:\\\"bar\\\"}\").build()), \"bar\");\n\n   }\n\n   public void testUnwrapValueNamed() throws Exception {\n      Invokable<?, ?> method = method(TestPut.class, \"testUnwrapValueNamed\");\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method));\n\n      assertResponseParserClassEquals(method, request, ParseFirstJsonValueNamed.class);\n      Function<HttpResponse, ?> parser = transformer.apply(request);\n\n      assertEquals(\n            parser.apply(HttpResponse.builder().statusCode(200).message(\"ok\").payload(\"{ foo:\\\"bar\\\"}\").build()), \"bar\");\n\n   }\n\n   public void testWrapWith() throws Exception {\n      Invokable<?, ?> method = method(TestPut.class, \"testWrapWith\", String.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method, ImmutableList.<Object> of(\"bar\")));\n      assertPayloadEquals(request, \"{\\\"foo\\\":\\\"bar\\\"}\", APPLICATION_JSON, false);\n   }\n\n   public void testUnwrap2() throws Exception {\n      Invokable<?, ?> method = method(TestPut.class, \"testUnwrap2\");\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method));\n\n      assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);\n      Function<HttpResponse, ?> parser = transformer.apply(request);\n\n      assertEquals(\n            parser.apply(HttpResponse.builder().statusCode(200).message(\"ok\").payload(\"{ foo:\\\"bar\\\"}\").build()), \"bar\");\n\n   }\n\n   public void testUnwrap3() throws Exception {\n      Invokable<?, ?> method = method(TestPut.class, \"testUnwrap3\");\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method));\n\n      assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);\n      Function<HttpResponse, ?> parser = transformer.apply(request);\n\n      assertEquals(\n            parser.apply(HttpResponse.builder().statusCode(200).message(\"ok\")\n                  .payload(\"{\\\"runit\\\":[\\\"0.7.0\\\",\\\"0.7.1\\\"]}\").build()), ImmutableSet.of(\"0.7.0\", \"0.7.1\"));\n   }\n\n   public void testUnwrap4() throws Exception {\n      Invokable<?, ?> method = method(TestPut.class, \"testUnwrap4\");\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method));\n\n      assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);\n      Function<HttpResponse, ?> parser = transformer.apply(request);\n\n      assertEquals(\n            parser.apply(HttpResponse.builder().statusCode(200).message(\"ok\")\n                  .payload(\"{\\\"runit\\\":[\\\"0.7.0\\\",\\\"0.7.1\\\"]}\").build()), ImmutableSet.of(\"0.7.0\", \"0.7.1\"));\n   }\n\n   public void selectLong() throws Exception {\n      Invokable<?, ?> method = method(TestPut.class, \"selectLong\");\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method));\n\n      assertResponseParserClassEquals(method, request, ParseFirstJsonValueNamed.class);\n      Function<HttpResponse, ?> parser = transformer.apply(request);\n\n      assertEquals(\n            parser.apply(HttpResponse.builder().statusCode(200).message(\"ok\")\n                  .payload(\"{ \\\"destroyvirtualmachineresponse\\\" : {\\\"jobid\\\":4} }\").build()), Long.valueOf(4));\n   }\n\n   public void selectLongAddOne() throws Exception {\n      Invokable<?, ?> method = method(TestPut.class, \"selectLongAddOne\");\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method));\n      Function<HttpResponse, ?> parser = transformer.apply(request);\n\n      assertEquals(\n            parser.apply(HttpResponse.builder().statusCode(200).message(\"ok\")\n                  .payload(\"{ \\\"destroyvirtualmachineresponse\\\" : {\\\"jobid\\\":4} }\").build()), Long.valueOf(5));\n   }\n\n   HttpResponse oneTwoThree = HttpResponse.builder().statusCode(200).message(\"ok\").payload(\"[1,2,3]\").build();\n\n   @Consumes(APPLICATION_JSON)\n   interface TransformWhenConsumesJson {\n      @GET\n      @Path(\"/\")\n      @Transform(FirstElementInLongList.class) // Read the input type parameter to avoid declaring a ResponseParser.\n      Long get();\n\n      @GET\n      @Path(\"/\")\n      @Transform(FirstElementInLongListSubType.class)\n      Long getSubType();\n   }\n\n   static class FirstElementInLongList implements Function<List<Long>, Long> {\n      @Override public Long apply(List<Long> o) {\n         return o.get(0);\n      }\n   }\n\n   static class FirstElementInLongListSubType extends FirstElement<Long> {\n      @Override public Long apply(List<Long> o) {\n         return o.get(0);\n      }\n   }\n\n   static class FirstElement<T> implements Function<List<T>, T> {\n      @Override public T apply(List<T> o) {\n         return o.get(0);\n      }\n   }\n\n   public void TransformWhenConsumesJson() throws Exception {\n      Invokable<?, ?> method = method(TransformWhenConsumesJson.class, \"get\");\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method));\n      Function<HttpResponse, ?> parser = transformer.apply(request);\n\n      assertEquals(parser.apply(oneTwoThree), Long.valueOf(1));\n   }\n\n   public void TransformWhenConsumesJson_subType() throws Exception {\n      Invokable<?, ?> method = method(TransformWhenConsumesJson.class, \"getSubType\");\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method));\n      Function<HttpResponse, ?> parser = transformer.apply(request);\n\n      assertEquals(parser.apply(oneTwoThree), Long.valueOf(1));\n   }\n\n   static class TestRequestFilter1 implements HttpRequestFilter {\n      public HttpRequest filter(HttpRequest request) throws HttpException {\n         return request;\n      }\n   }\n\n   static class TestRequestFilter2 implements HttpRequestFilter {\n      public HttpRequest filter(HttpRequest request) throws HttpException {\n         return request;\n      }\n   }\n\n   @RequestFilters(TestRequestFilter1.class)\n   interface TestRequestFilter {\n      @GET\n      @RequestFilters(TestRequestFilter2.class)\n      void get();\n\n      @GET\n      @OverrideRequestFilters\n      @RequestFilters(TestRequestFilter2.class)\n      void getOverride();\n\n      @OverrideRequestFilters\n      @RequestFilters(TestRequestFilter2.class)\n      void getOverride(HttpRequest request);\n\n      @POST\n      void post();\n   }\n\n   @Test\n   public void testRequestFilter() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> method = method(TestRequestFilter.class, \"get\");\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method));\n      assertEquals(request.getFilters().size(), 2);\n      assertEquals(request.getFilters().get(0).getClass(), TestRequestFilter1.class);\n      assertEquals(request.getFilters().get(1).getClass(), TestRequestFilter2.class);\n   }\n\n   public void testRequestFilterOverride() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> method = method(TestRequestFilter.class, \"getOverride\");\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method));\n      assertEquals(request.getFilters().size(), 1);\n      assertEquals(request.getFilters().get(0).getClass(), TestRequestFilter2.class);\n   }\n\n   public void testRequestFilterOverrideOnRequest() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> method = method(TestRequestFilter.class, \"getOverride\", HttpRequest.class);\n      GeneratedHttpRequest request = processor.apply(\n            Invocation.create(method,\n            ImmutableList.<Object> of(HttpRequest.builder().method(\"GET\").endpoint(\"http://localhost\")\n                  .addHeader(\"foo\", \"bar\").build())));\n      assertEquals(request.getFilters().size(), 1);\n      assertEquals(request.getHeaders().size(), 1);\n      assertEquals(request.getFilters().get(0).getClass(), TestRequestFilter2.class);\n   }\n\n   @Test\n   public void testRequestFilterStripExpect() {\n      // First, verify that by default, the StripExpectHeader filter is not applied\n      Invokable<?, ?> method = method(TestRequestFilter.class, \"post\");\n      Invocation invocation = Invocation.create(method,\n         ImmutableList.<Object>of(HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\")\n            .addHeader(HttpHeaders.EXPECT, \"100-Continue\").build()));\n      GeneratedHttpRequest request = processor.apply(invocation);\n      assertEquals(request.getFilters().size(), 1);\n      assertEquals(request.getFilters().get(0).getClass(), TestRequestFilter1.class);\n\n      // Now let's create a new injector with the property set. Use that to create the annotation processor.\n      Properties overrides = new Properties();\n      overrides.setProperty(Constants.PROPERTY_STRIP_EXPECT_HEADER, \"true\");\n      Injector injector = ContextBuilder.newBuilder(forApiOnEndpoint(Callee.class, \"http://localhost:9999\"))\n         .modules(ImmutableSet.<Module> of(new MockModule(), new NullLoggingModule(), new AbstractModule() {\n            protected void configure() {\n               bind(new TypeLiteral<Supplier<URI>>() {\n               }).annotatedWith(Localhost2.class).toInstance(\n                  Suppliers.ofInstance(URI.create(\"http://localhost:1111\")));\n            }}))\n         .overrides(overrides).buildInjector();\n      RestAnnotationProcessor newProcessor = injector.getInstance(RestAnnotationProcessor.class);\n      // Verify that this time the filter is indeed applied as expected.\n      request = newProcessor.apply(invocation);\n      assertEquals(request.getFilters().size(), 2);\n      assertEquals(request.getFilters().get(1).getClass(), StripExpectHeader.class);\n   }\n\n   @Test\n   public void testRequestFilterAddConnection() {\n      // First, verify that by default, the StripExpectHeader filter is not applied\n      Invokable<?, ?> method = method(TestRequestFilter.class, \"post\");\n      Invocation invocation = Invocation.create(method,\n         ImmutableList.<Object>of(HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build()));\n      GeneratedHttpRequest request = processor.apply(invocation);\n      assertEquals(request.getFilters().size(), 1);\n      assertEquals(request.getFilters().get(0).getClass(), TestRequestFilter1.class);\n\n      // Now let's create a new injector with the property set. Use that to create the annotation processor.\n      Properties overrides = new Properties();\n      overrides.setProperty(Constants.PROPERTY_CONNECTION_CLOSE_HEADER, \"true\");\n      Injector injector = ContextBuilder.newBuilder(forApiOnEndpoint(Callee.class, \"http://localhost:9999\"))\n         .modules(ImmutableSet.<Module> of(new MockModule(), new NullLoggingModule(), new AbstractModule() {\n            protected void configure() {\n               bind(new TypeLiteral<Supplier<URI>>() {\n               }).annotatedWith(Localhost2.class).toInstance(\n                  Suppliers.ofInstance(URI.create(\"http://localhost:1111\")));\n            }}))\n         .overrides(overrides).buildInjector();\n      RestAnnotationProcessor newProcessor = injector.getInstance(RestAnnotationProcessor.class);\n      // Verify that this time the filter is indeed applied as expected.\n      request = newProcessor.apply(invocation);\n      assertEquals(request.getFilters().size(), 2);\n      assertEquals(request.getFilters().get(1).getClass(), ConnectionCloseHeader.class);\n   }\n\n   @Test\n   public void testZeroContentStripExpectHeader() {\n      Invokable<?, ?> method = method(TestRequestFilter.class, \"post\");\n      Invocation invocation = Invocation.create(method,\n              ImmutableList.<Object>of(HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\")\n                      .payload(new byte[0]).addHeader(HttpHeaders.EXPECT, \"100-Continue\")\n                      .build()));\n      GeneratedHttpRequest request = processor.apply(invocation);\n      assertThat(request.getFirstHeaderOrNull(HttpHeaders.EXPECT)).isNull();\n   }\n\n   public static class TestEncoding {\n      @GET\n      @Path(\"/{path1}/{path2}\")\n      public void twoPaths(@PathParam(\"path1\") String path, @PathParam(\"path2\") String path2) {\n      }\n   }\n\n   @Test\n   public void testSkipEncoding() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> method = method(TestEncoding.class, \"twoPaths\", String.class, String.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(\"1\", \"localhost\")));\n      assertEquals(request.getEndpoint().getPath(), \"/1/localhost\");\n      assertEquals(request.getMethod(), HttpMethod.GET);\n      assertEquals(request.getHeaders().size(), 0);\n   }\n\n   @Test\n   public void testEncodingPath() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> method = method(TestEncoding.class, \"twoPaths\", String.class, String.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(\"/\", \"localhost\")));\n      assertEquals(request.getEndpoint().getPath(), \"///localhost\");\n      assertEquals(request.getMethod(), HttpMethod.GET);\n      assertEquals(request.getHeaders().size(), 0);\n   }\n\n   @Path(\"/v1/{identity}\")\n   interface TestConstantPathParam {\n      @Named(\"testidentity\")\n      @PathParam(\"identity\")\n      void setUsername();\n\n      @GET\n      @Path(\"/{path1}/{path2}\")\n      void twoPaths(@PathParam(\"path1\") String path, @PathParam(\"path2\") String path2);\n   }\n\n   @Test(enabled = false)\n   public void testConstantPathParam() throws Exception {\n      Invokable<?, ?> method = method(TestConstantPathParam.class, \"twoPaths\", String.class,\n            String.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(\"1\", \"localhost\")));\n      assertRequestLineEquals(request, \"GET http://localhost:9999/v1/ralphie/1/localhost HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"\");\n      assertPayloadEquals(request, null, null, false);\n   }\n\n   public static class TestPath {\n      @GET\n      @Path(\"/{path}\")\n      public void onePath(@PathParam(\"path\") String path) {\n      }\n\n      @GET\n      @Path(\"/{paramA}/{paramB}/{paramC}\")\n      public void encodedParams(@PathParam(\"paramA\") @Encoded String a, @PathParam(\"paramB\") String b,\n                                        @PathParam(\"paramC\") @Encoded String c) {\n      }\n\n      @GET\n      @Path(\"/{path}\")\n      public void onePathNullable(@Nullable @PathParam(\"path\") String path) {\n      }\n\n      @GET\n      @Path(\"/{path1}/{path2}\")\n      public void twoPaths(@PathParam(\"path1\") String path, @PathParam(\"path2\") String path2) {\n      }\n\n      @GET\n      @Path(\"/{path2}/{path1}\")\n      public void twoPathsOutOfOrder(@PathParam(\"path1\") String path, @PathParam(\"path2\") String path2) {\n      }\n\n      @GET\n      @Path(\"/{path}\")\n      public void onePathParamExtractor(@PathParam(\"path\") @ParamParser(FirstCharacter.class) String path) {\n      }\n\n      @GET\n      @Path(\"/\")\n      public void oneQueryParamExtractor(@QueryParam(\"one\") @ParamParser(FirstCharacter.class) String one) {\n      }\n\n      @GET\n      @Path(\"/\")\n      public void oneQueryParam(@QueryParam(\"one\") String one) {\n      }\n\n      @GET\n      @Path(\"/\")\n      public void encodedQueryParam(@QueryParam(\"encoded\") @Encoded String encoded) {\n      }\n\n      @GET\n      @Path(\"/\")\n      public void encodedQueryListParam(@QueryParam(\"encoded\") @Encoded List<String> encodedStrings) {\n      }\n\n      @POST\n      @Path(\"/\")\n      public void oneFormParamExtractor(@FormParam(\"one\") @ParamParser(FirstCharacter.class) String one) {\n      }\n   }\n\n   @Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = \"param\\\\{path\\\\} for invocation TestPath.onePath\")\n   public void testNiceNPEPathParam() throws Exception {\n      Invokable<?, ?> method = method(TestPath.class, \"onePath\", String.class);\n      processor.apply(Invocation.create(method, Lists.<Object> newArrayList((String) null)));\n   }\n\n   @Test\n   public void testPathParamExtractor() throws Exception {\n      Invokable<?, ?> method = method(TestPath.class, \"onePathParamExtractor\", String.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(\"localhost\")));\n      assertRequestLineEquals(request, \"GET http://localhost:9999/l HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"\");\n      assertPayloadEquals(request, null, null, false);\n   }\n\n   @Test\n   public void testPathParamEncoding() throws Exception {\n      Invokable<?, ?> method = method(TestPath.class, \"onePath\", String.class);\n      // By default, \"/\" should not be encoded\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(\"foo/bar\")));\n      assertRequestLineEquals(request, \"GET http://localhost:9999/foo/bar HTTP/1.1\");\n\n      // If we pass an encoded string, it should be encoded twice\n      request = processor.apply(Invocation.create(method, ImmutableList.<Object> of(\"foo%2Fbar\")));\n      assertRequestLineEquals(request, \"GET http://localhost:9999/foo%252Fbar HTTP/1.1\");\n\n      // If we pass in a pre-encoded param, it should not be double encoded\n      method = method(TestPath.class, \"encodedParams\", String.class, String.class, String.class);\n      request = processor.apply(Invocation.create(method, ImmutableList.<Object>of(\"encoded%2Fparam\", \"encode%2Fdouble\",\n            \"foo%20bar\")));\n      assertRequestLineEquals(request,\n            \"GET http://localhost:9999/encoded%2Fparam/encode%252Fdouble/foo%20bar HTTP/1.1\");\n   }\n\n   @Test\n   public void testQueryParamExtractor() throws Exception {\n      Invokable<?, ?> method = method(TestPath.class, \"oneQueryParamExtractor\", String.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(\"localhost\")));\n      assertRequestLineEquals(request, \"GET http://localhost:9999/?one=l HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"\");\n      assertPayloadEquals(request, null, null, false);\n   }\n\n   @Test\n   public void testEncodedQueryParam() throws Exception {\n      Invokable<?, ?> method = method(TestPath.class, \"encodedQueryParam\", String.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(\"foo%20bar\")));\n      assertRequestLineEquals(request, \"GET http://localhost:9999/?encoded=foo%20bar HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"\");\n      assertPayloadEquals(request, null, null, false);\n\n      method = method(TestPath.class, \"encodedQueryListParam\", List.class);\n      String [] args = {\"foo%20bar\", \"foo/bar\"};\n      request = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(ImmutableList.of(\"foo%20bar\", \"foo/bar\"))));\n      assertRequestLineEquals(request, \"GET http://localhost:9999/?encoded=foo%20bar&encoded=foo/bar HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"\");\n      assertPayloadEquals(request, null, null, false);\n   }\n\n   @DataProvider(name = \"queryStrings\")\n   public Object[][] createQueryData() {\n      return new Object[][] { { \"normal\" }, { \"sp ace\" }, { \"qu?stion\" }, { \"unic₪de\" }, { \"path/foo\" }, { \"colon:\" },\n            { \"asteri*k\" }, { \"quote\\\"\" }, { \"great<r\" }, { \"lesst>en\" }, { \"p|pe\" } };\n   }\n\n   @Test(dataProvider = \"queryStrings\")\n   public void testQueryParam(String val) {\n      Invokable<?, ?> method = method(TestPath.class, \"oneQueryParam\", String.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(val)));\n      assertRequestLineEquals(request, String.format(\"GET http://localhost:9999/?one=%s HTTP/1.1\",\n            urlEncode(val, '/', ',')));\n      assertNonPayloadHeadersEqual(request, \"\");\n      assertPayloadEquals(request, null, null, false);\n   }\n\n   @Test\n   public void testFormParamExtractor() throws Exception {\n      Invokable<?, ?> method = method(TestPath.class, \"oneFormParamExtractor\", String.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(\"localhost\")));\n      assertRequestLineEquals(request, \"POST http://localhost:9999/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"\");\n      assertPayloadEquals(request, \"one=l\", \"application/x-www-form-urlencoded\", false);\n   }\n\n   @Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = \"param\\\\{one\\\\} for invocation TestPath.oneFormParamExtractor\")\n   public void testNiceNPEFormParam() throws Exception {\n      Invokable<?, ?> method = method(TestPath.class, \"oneFormParamExtractor\", String.class);\n      processor.apply(Invocation.create(method, Lists.<Object> newArrayList((String) null)));\n   }\n\n   static class FirstCharacter implements Function<Object, String> {\n      public String apply(Object from) {\n         return from.toString().substring(0, 1);\n      }\n   }\n\n   static class FirstCharacterFirstElement implements Function<Object, String> {\n      public String apply(Object from) {\n         return ((String) ((Object[]) from)[0]).substring(0, 1);\n      }\n   }\n\n   public static class TestHeader {\n      @GET\n      @Path(\"/\")\n      @Headers(keys = \"x-amz-copy-source\", values = \"/{bucket}\")\n      public void oneHeader(@PathParam(\"bucket\") String path) {\n      }\n\n      @GET\n      @Path(\"/\")\n      @Headers(keys = \"x-amz-copy-source\", values = \"/{bucket}\", urlEncode = true)\n      public void oneHeaderEncoded(@PathParam(\"bucket\") String path) {\n      }\n\n      @GET\n      @Path(\"/\")\n      @Headers(keys = { \"slash\", \"hyphen\" }, values = { \"/{bucket}\", \"-{bucket}\" })\n      public void twoHeader(@PathParam(\"bucket\") String path) {\n      }\n\n      @GET\n      @Path(\"/\")\n      @Headers(keys = \"x-amz-copy-source\", values = \"/{bucket}/{key}\")\n      public void twoHeaders(@PathParam(\"bucket\") String path, @PathParam(\"key\") String path2) {\n      }\n\n      @GET\n      @Path(\"/\")\n      @Headers(keys = \"x-amz-copy-source\", values = \"/{bucket}/{key}\")\n      public void twoHeadersOutOfOrder(@PathParam(\"key\") String path, @PathParam(\"bucket\") String path2) {\n      }\n\n      @GET\n      @Path(\"/\")\n      @Headers(keys = {\"unencoded\", \"x-amz-copy-source\"}, values = {\"/{bucket}\", \"/{bucket}\"}, urlEncode = {false, true})\n      public void twoHeadersMixedEncoding(@PathParam(\"bucket\") String path) {\n      }\n   }\n\n   @Test\n   public void testBuildTwoHeader() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> method = method(TestHeader.class, \"twoHeader\", String.class);\n      Multimap<String, String> headers = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(\"robot\"))).getHeaders();\n      assertEquals(headers.size(), 2);\n      assertEquals(headers.get(\"slash\"), ImmutableList.of(\"/robot\"));\n      assertEquals(headers.get(\"hyphen\"), ImmutableList.of(\"-robot\"));\n   }\n\n   @Headers(keys = \"x-amz-copy-source\", values = \"/{bucket}\")\n   public static class TestClassHeader {\n      @GET\n      @Path(\"/\")\n      public void oneHeader(@PathParam(\"bucket\") String path) {\n      }\n   }\n\n   @Test\n   public void testBuildOneClassHeader() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> method = method(TestClassHeader.class, \"oneHeader\", String.class);\n      Multimap<String, String> headers = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(\"robot\"))).getHeaders();\n      assertEquals(headers.size(), 1);\n      assertEquals(headers.get(\"x-amz-copy-source\"), ImmutableList.of(\"/robot\"));\n   }\n\n   @Test\n   public void testBuildOneHeader() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> method = method(TestHeader.class, \"oneHeader\", String.class);\n      Multimap<String, String> headers = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(\"robot\"))).getHeaders();\n      assertEquals(headers.size(), 1);\n      assertEquals(headers.get(\"x-amz-copy-source\"), ImmutableList.of(\"/robot\"));\n   }\n\n   @Test\n   public void testBuildOneHeaderUnencoded() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> method = method(TestHeader.class, \"oneHeader\", String.class);\n      Multimap<String, String> headers = processor.apply(Invocation.create(method,\n              ImmutableList.<Object> of(\"apples#?:$&'\\\"<>čॐ\"))).getHeaders();\n      assertEquals(headers.size(), 1);\n      assertEquals(headers.get(\"x-amz-copy-source\"), ImmutableList.of(\"/apples#?:$&'\\\"<>čॐ\"));\n   }\n\n   @Test\n   public void testBuildOneHeaderEncoded() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> method = method(TestHeader.class, \"oneHeaderEncoded\", String.class);\n      Multimap<String, String> headers = processor.apply(Invocation.create(method,\n              ImmutableList.<Object> of(\"apples#?:$&'\\\"<>čॐ\"))).getHeaders();\n      assertEquals(headers.size(), 1);\n      assertEquals(headers.get(\"x-amz-copy-source\"), ImmutableList.of(\"/apples%23%3F%3A%24%26%27%22%3C%3E%C4%8D%E0%A5%90\"));\n   }\n\n   @Test\n   public void testBuildTwoHeaders() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> method = method(TestHeader.class, \"twoHeaders\", String.class, String.class);\n      Multimap<String, String> headers = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(\"robot\", \"eggs\"))).getHeaders();\n      assertEquals(headers.size(), 1);\n      assertEquals(headers.get(\"x-amz-copy-source\"), ImmutableList.of(\"/robot/eggs\"));\n   }\n\n   @Test\n   public void testBuildTwoHeadersOutOfOrder() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> method = method(TestHeader.class, \"twoHeadersOutOfOrder\", String.class,\n            String.class);\n      Multimap<String, String> headers = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(\"robot\", \"eggs\"))).getHeaders();\n      assertEquals(headers.size(), 1);\n      assertEquals(headers.get(\"x-amz-copy-source\"), ImmutableList.of(\"/eggs/robot\"));\n   }\n\n   @Test\n   public void testBuildTwoHeadersMixedEncoding() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> method = method(TestHeader.class, \"twoHeadersMixedEncoding\", String.class);\n      Multimap<String, String> headers = processor.apply(Invocation.create(method,\n              ImmutableList.<Object> of(\"apples#?:$&'\\\"<>čॐ\"))).getHeaders();\n      assertEquals(headers.size(), 2);\n      assertEquals(headers.get(\"unencoded\"), ImmutableList.of(\"/apples#?:$&'\\\"<>čॐ\"));\n      assertEquals(headers.get(\"x-amz-copy-source\"), ImmutableList.of(\"/apples%23%3F%3A%24%26%27%22%3C%3E%C4%8D%E0%A5%90\"));\n   }\n\n   public static class TestReplaceQueryOptions extends BaseHttpRequestOptions {\n      public TestReplaceQueryOptions() {\n         this.queryParameters.put(\"x-amz-copy-source\", \"/{bucket}\");\n      }\n   }\n\n   @Test\n   public void testQueryInOptions() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> method = method(TestQueryReplace.class, \"queryInOptions\", String.class,\n            TestReplaceQueryOptions.class);\n      String query = processor\n            .apply(Invocation.create(method, ImmutableList.<Object> of(\"robot\", new TestReplaceQueryOptions()))).getEndpoint()\n            .getQuery();\n      assertEquals(query, \"x-amz-copy-source=/robot\");\n   }\n\n   public static class TestQueryReplace {\n\n      @GET\n      @Path(\"/\")\n      public void queryInOptions(@PathParam(\"bucket\") String path, TestReplaceQueryOptions options) {\n      }\n\n      @GET\n      @Path(\"/\")\n      @QueryParams(keys = \"x-amz-copy-source\", values = \"/{bucket}\")\n      public void oneQuery(@PathParam(\"bucket\") String path) {\n      }\n\n      @GET\n      @Path(\"/\")\n      @QueryParams(keys = { \"slash\", \"hyphen\" }, values = { \"/{bucket}\", \"-{bucket}\" })\n      public void twoQuery(@PathParam(\"bucket\") String path) {\n      }\n\n      @GET\n      @Path(\"/\")\n      @QueryParams(keys = \"x-amz-copy-source\", values = \"/{bucket}/{key}\")\n      public void twoQuerys(@PathParam(\"bucket\") String path, @PathParam(\"key\") String path2) {\n      }\n\n      @GET\n      @Path(\"/\")\n      @QueryParams(keys = \"x-amz-copy-source\", values = \"/{bucket}/{key}\")\n      public void twoQuerysOutOfOrder(@PathParam(\"key\") String path, @PathParam(\"bucket\") String path2) {\n      }\n   }\n\n   @Test\n   public void testBuildTwoQuery() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> method = method(TestQueryReplace.class, \"twoQuery\", String.class);\n      String query = processor.apply(Invocation.create(method, ImmutableList.<Object> of(\"robot\")))\n            .getEndpoint().getQuery();\n      assertEquals(query, \"slash=/robot&hyphen=-robot\");\n   }\n\n   @QueryParams(keys = \"x-amz-copy-source\", values = \"/{bucket}\")\n   public static class TestClassQuery {\n      @GET\n      @Path(\"/\")\n      public void oneQuery(@PathParam(\"bucket\") String path) {\n      }\n   }\n\n   @Test\n   public void testBuildOneClassQuery() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> method = method(TestClassQuery.class, \"oneQuery\", String.class);\n      String query = processor.apply(Invocation.create(method, ImmutableList.<Object> of(\"robot\")))\n            .getEndpoint().getQuery();\n      assertEquals(query, \"x-amz-copy-source=/robot\");\n   }\n\n   @Test\n   public void testBuildOneQuery() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> method = method(TestQueryReplace.class, \"oneQuery\", String.class);\n      String query = processor.apply(Invocation.create(method, ImmutableList.<Object> of(\"robot\")))\n            .getEndpoint().getQuery();\n      assertEquals(query, \"x-amz-copy-source=/robot\");\n   }\n\n   @Test\n   public void testBuildTwoQuerys() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> method = method(TestQueryReplace.class, \"twoQuerys\", String.class, String.class);\n      String query = processor\n            .apply(Invocation.create(method, ImmutableList.<Object> of(\"robot\", \"eggs\"))).getEndpoint().getQuery();\n      assertEquals(query, \"x-amz-copy-source=/robot/eggs\");\n   }\n\n   @Test\n   public void testBuildTwoQuerysOutOfOrder() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> method = method(TestQueryReplace.class, \"twoQuerysOutOfOrder\", String.class,\n            String.class);\n      String query = processor\n            .apply(Invocation.create(method, ImmutableList.<Object> of(\"robot\", \"eggs\"))).getEndpoint().getQuery();\n      assertEquals(query, \"x-amz-copy-source=/eggs/robot\");\n   }\n\n   interface TestTransformers {\n      @GET\n      Integer noTransformer();\n\n      @GET\n      @ResponseParser(ReturnStringIf2xx.class)\n      void oneTransformer();\n\n      @GET\n      @ResponseParser(ReturnStringIf200Context.class)\n      void oneTransformerWithContext();\n\n      @GET\n      InputStream inputStream();\n\n      @GET\n      URI uri();\n\n      @PUT\n      void put(Payload payload);\n\n      @PUT\n      @Headers(keys = \"Transfer-Encoding\", values = \"chunked\")\n      void putXfer(Payload payload);\n\n      @PUT\n      void put(PayloadEnclosing payload);\n   }\n\n   public void testPutPayloadEnclosing() throws Exception {\n      Invokable<?, ?> method = method(TestTransformers.class, \"put\", PayloadEnclosing.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(new PayloadEnclosingImpl(newStringPayload(\"whoops\")))));\n      assertRequestLineEquals(request, \"PUT http://localhost:9999 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"\");\n      assertPayloadEquals(request, \"whoops\", \"application/unknown\", false);\n   }\n\n   public void testPutPayloadEnclosingGenerateMD5() throws Exception {\n      Invokable<?, ?> method = method(TestTransformers.class, \"put\", PayloadEnclosing.class);\n      ByteSource byteSource = ByteSource.wrap(\"whoops\".getBytes(UTF_8));\n      PayloadEnclosing payloadEnclosing = new PayloadEnclosingImpl(Payloads.newByteSourcePayload(byteSource));\n      payloadEnclosing.getPayload().getContentMetadata().setContentLength(byteSource.size());\n      payloadEnclosing.getPayload().getContentMetadata().setContentMD5(byteSource.hash(Hashing.md5()).asBytes());\n\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(payloadEnclosing)));\n      assertRequestLineEquals(request, \"PUT http://localhost:9999 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"\");\n\n      assertPayloadEquals(request, \"whoops\", \"application/unknown\", true);\n   }\n\n   public void testPutInputStreamPayloadEnclosingGenerateMD5() throws SecurityException, NoSuchMethodException,\n         IOException {\n      Invokable<?, ?> method = method(TestTransformers.class, \"put\", PayloadEnclosing.class);\n      ByteSource byteSource = ByteSource.wrap(\"whoops\".getBytes(UTF_8));\n      PayloadEnclosing payloadEnclosing = new PayloadEnclosingImpl(\n            newInputStreamPayload(byteSource.openStream()));\n      payloadEnclosing.getPayload().getContentMetadata().setContentLength(byteSource.size());\n      payloadEnclosing.getPayload().getContentMetadata().setContentMD5(byteSource.hash(Hashing.md5()).asBytes());\n\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(payloadEnclosing)));\n      assertRequestLineEquals(request, \"PUT http://localhost:9999 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"\");\n\n      assertPayloadEquals(request, \"whoops\", \"application/unknown\", true);\n   }\n\n   public void testPutPayloadChunkedNoContentLength() throws Exception {\n      Invokable<?, ?> method = method(TestTransformers.class, \"putXfer\", Payload.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(newStringPayload(\"whoops\"))));\n      assertRequestLineEquals(request, \"PUT http://localhost:9999 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Transfer-Encoding: chunked\\n\");\n      assertPayloadEquals(request, \"whoops\", \"application/unknown\", false);\n   }\n\n   public void testPutPayload() throws Exception {\n      Invokable<?, ?> method = method(TestTransformers.class, \"put\", Payload.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(newStringPayload(\"whoops\"))));\n      assertRequestLineEquals(request, \"PUT http://localhost:9999 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"\");\n      assertPayloadEquals(request, \"whoops\", \"application/unknown\", false);\n   }\n\n   public void testPutPayloadContentDisposition() throws Exception {\n      Invokable<?, ?> method = method(TestTransformers.class, \"put\", Payload.class);\n      Payload payload = newStringPayload(\"whoops\");\n      payload.getContentMetadata().setContentDisposition(\"attachment; filename=photo.jpg\");\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(payload)));\n      assertRequestLineEquals(request, \"PUT http://localhost:9999 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"\");\n      assertPayloadEquals(request, \"whoops\", \"application/unknown\", \"attachment; filename=photo.jpg\", null, null, false);\n   }\n\n   public void testPutPayloadContentEncoding() throws Exception {\n      Invokable<?, ?> method = method(TestTransformers.class, \"put\", Payload.class);\n      Payload payload = newStringPayload(\"whoops\");\n      payload.getContentMetadata().setContentEncoding(\"gzip\");\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(payload)));\n      assertRequestLineEquals(request, \"PUT http://localhost:9999 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"\");\n      assertPayloadEquals(request, \"whoops\", \"application/unknown\", null, \"gzip\", null, false);\n   }\n\n   public void testPutPayloadContentLanguage() throws Exception {\n      Invokable<?, ?> method = method(TestTransformers.class, \"put\", Payload.class);\n      Payload payload = newStringPayload(\"whoops\");\n      payload.getContentMetadata().setContentLanguage(\"en\");\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(payload)));\n      assertRequestLineEquals(request, \"PUT http://localhost:9999 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"\");\n      assertPayloadEquals(request, \"whoops\", \"application/unknown\", null, null, \"en\", false);\n   }\n\n   public void testPutPayloadWithGeneratedMD5AndNoContentType() throws SecurityException, NoSuchMethodException,\n         IOException {\n      ByteSource byteSource = ByteSource.wrap(\"whoops\".getBytes(UTF_8));\n      Payload payload = Payloads.newByteSourcePayload(byteSource);\n      payload.getContentMetadata().setContentLength(byteSource.size());\n      payload.getContentMetadata().setContentMD5(byteSource.hash(Hashing.md5()).asBytes());\n\n      Invokable<?, ?> method = method(TestTransformers.class, \"put\", Payload.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(payload)));\n      assertRequestLineEquals(request, \"PUT http://localhost:9999 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"\");\n      assertPayloadEquals(request, \"whoops\", \"application/unknown\", true);\n   }\n\n   public void testPutInputStreamPayload() throws Exception {\n      Payload payload = newInputStreamPayload(Strings2.toInputStream(\"whoops\"));\n      payload.getContentMetadata().setContentLength((long) \"whoops\".length());\n      Invokable<?, ?> method = method(TestTransformers.class, \"put\", Payload.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(payload)));\n      assertRequestLineEquals(request, \"PUT http://localhost:9999 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"\");\n      assertPayloadEquals(request, \"whoops\", \"application/unknown\", false);\n   }\n\n   public void testPutInputStreamPayloadWithMD5() throws NoSuchAlgorithmException, IOException, SecurityException,\n         NoSuchMethodException {\n      ByteSource byteSource = ByteSource.wrap(\"whoops\".getBytes(UTF_8));\n      Payload payload = Payloads.newByteSourcePayload(byteSource);\n      payload.getContentMetadata().setContentLength(byteSource.size());\n      payload.getContentMetadata().setContentMD5(byteSource.hash(Hashing.md5()).asBytes());\n\n      Invokable<?, ?> method = method(TestTransformers.class, \"put\", Payload.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(payload)));\n      assertRequestLineEquals(request, \"PUT http://localhost:9999 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"\");\n      assertPayloadEquals(request, \"whoops\", \"application/unknown\", true);\n   }\n\n   public void testInputStream() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> method = method(TestTransformers.class, \"inputStream\");\n      assertEquals(unwrap(method), ReturnInputStream.class);\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   public Class<?> unwrap(Invokable<?, ?> method) {\n      return transformer.getParserOrThrowException(Invocation.create(method, ImmutableList.of())).getTypeLiteral()\n            .getRawType();\n   }\n\n   public void testURI() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> method = method(TestTransformers.class, \"uri\");\n      assertEquals(unwrap(method), ParseURIFromListOrLocationHeaderIf20x.class);\n   }\n\n   public static class ReturnStringIf200Context extends ReturnStringIf2xx implements\n         InvocationContext<ReturnStringIf200Context> {\n\n      public HttpRequest request;\n\n      public ReturnStringIf200Context setContext(HttpRequest request) {\n         this.request = request;\n         return this;\n      }\n\n   }\n\n   @Test(expectedExceptions = RuntimeException.class)\n   public void testNoTransformer() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> method = method(TestTransformers.class, \"noTransformer\");\n      unwrap(method);\n   }\n\n   public void oneTransformerWithContext() throws SecurityException, NoSuchMethodException {\n      GeneratedHttpRequest request = GeneratedHttpRequest.builder()\n            .method(\"GET\")\n            .endpoint(\"http://localhost\")\n            .invocation(\n                  Invocation.create(method(TestTransformers.class, \"oneTransformerWithContext\"),\n                        ImmutableList.of())).build();\n      Function<HttpResponse, ?> transformer = this.transformer.apply(request);\n      assertEquals(transformer.getClass(), ReturnStringIf200Context.class);\n      assertEquals(((ReturnStringIf200Context) transformer).request, request);\n   }\n\n   public void testOneTransformer() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> method = method(TestTransformers.class, \"oneTransformer\");\n      assertEquals(unwrap(method), ReturnStringIf2xx.class);\n   }\n\n   interface TestRequest {\n      @GET\n      @VirtualHost\n      @Path(\"/{id}\")\n      String get(@PathParam(\"id\") String id, HttpRequestOptions options);\n\n      @GET\n      @VirtualHost\n      @Path(\"/{id}\")\n      String get(@PathParam(\"id\") String id, HttpRequestOptions... options);\n\n      @GET\n      @Path(\"/{id}\")\n      @ResponseParser(ReturnStringIf2xx.class)\n      String get(@PathParam(\"id\") String id, @HeaderParam(HttpHeaders.HOST) String host);\n\n      @GET\n      @Path(\"/{id}\")\n      @QueryParams(keys = \"max-keys\", values = \"0\")\n      String getQuery(@PathParam(\"id\") String id);\n\n      @GET\n      @Path(\"/{id}\")\n      @QueryParams(keys = \"acl\")\n      String getQueryNull(@PathParam(\"id\") String id);\n\n      @GET\n      @Path(\"/{id}\")\n      @QueryParams(keys = \"acl\", values = \"\")\n      String getQueryEmpty(@PathParam(\"id\") String id);\n\n      @PUT\n      @Path(\"/{id}\")\n      String put(@PathParam(\"id\") @ParamParser(FirstCharacter.class) String id,\n            @BinderParam(BindToStringPayload.class) String payload);\n\n      @PUT\n      @Path(\"/{id}\")\n      @VirtualHost\n      String putOptions(@PathParam(\"id\") String id, HttpRequestOptions options);\n\n      @PUT\n      @Path(\"/{id}\")\n      @Headers(keys = \"foo\", values = \"--{id}--\")\n      @ResponseParser(ReturnTrueIf2xx.class)\n      String putHeader(@PathParam(\"id\") String id,\n            @BinderParam(BindToStringPayload.class) String payload);\n   }\n\n   public void testCreateGetVarArgOptionsThatProducesHeaders() throws SecurityException, NoSuchMethodException {\n      Date date = new Date();\n      GetOptions options = GetOptions.Builder.ifModifiedSince(date);\n      Invokable<?, ?> method = method(TestRequest.class, \"get\", String.class,\n            HttpRequestOptions[].class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(\"1\", options)));\n      assertEquals(request.getEndpoint().getHost(), \"localhost\");\n      assertEquals(request.getEndpoint().getPath(), \"/1\");\n      assertEquals(request.getMethod(), HttpMethod.GET);\n      assertEquals(request.getHeaders().size(), 2);\n      assertEquals(request.getHeaders().get(HttpHeaders.HOST), ImmutableList.of(\"localhost:9999\"));\n      assertEquals(request.getHeaders().get(HttpHeaders.IF_MODIFIED_SINCE),\n            ImmutableList.of(dateService.rfc822DateFormat(date)));\n   }\n\n   public void testCreateGetOptionsThatProducesHeaders() throws SecurityException, NoSuchMethodException {\n      Date date = new Date();\n      GetOptions options = GetOptions.Builder.ifModifiedSince(date);\n      Invokable<?, ?> method = method(TestRequest.class, \"get\", String.class, HttpRequestOptions.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(\"1\", options)));\n      assertEquals(request.getEndpoint().getHost(), \"localhost\");\n      assertEquals(request.getEndpoint().getPath(), \"/1\");\n      assertEquals(request.getMethod(), HttpMethod.GET);\n      assertEquals(request.getHeaders().size(), 2);\n      assertEquals(request.getHeaders().get(HttpHeaders.HOST), ImmutableList.of(\"localhost:9999\"));\n      assertEquals(request.getHeaders().get(HttpHeaders.IF_MODIFIED_SINCE),\n            ImmutableList.of(dateService.rfc822DateFormat(date)));\n   }\n\n   public static class PrefixOptions extends BaseHttpRequestOptions {\n      public PrefixOptions withPrefix(String prefix) {\n         queryParameters.put(\"prefix\", checkNotNull(prefix, \"prefix\"));\n         return this;\n      }\n   }\n\n   public void testCreateGetOptionsThatProducesQuery() throws Exception {\n      PrefixOptions options = new PrefixOptions().withPrefix(\"1\");\n      Invokable<?, ?> method = method(TestRequest.class, \"get\", String.class, HttpRequestOptions.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(\"1\", options)));\n      assertRequestLineEquals(request, \"GET http://localhost:9999/1?prefix=1 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: localhost:9999\\n\");\n      assertPayloadEquals(request, null, null, false);\n   }\n\n   public void testCreateGetQuery() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> method = method(TestRequest.class, \"getQuery\", String.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method, ImmutableList.<Object> of(\"1\")));\n      assertEquals(request.getEndpoint().getHost(), \"localhost\");\n      assertEquals(request.getEndpoint().getPath(), \"/1\");\n      assertEquals(request.getEndpoint().getQuery(), \"max-keys=0\");\n      assertEquals(request.getMethod(), HttpMethod.GET);\n      assertEquals(request.getHeaders().size(), 0);\n   }\n\n   public void testCreateGetQueryNull() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> method = method(TestRequest.class, \"getQueryNull\", String.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method, ImmutableList.<Object> of(\"1\")));\n      assertEquals(request.getEndpoint().getHost(), \"localhost\");\n      assertEquals(request.getEndpoint().getPath(), \"/1\");\n      assertEquals(request.getEndpoint().getQuery(), \"acl\");\n      assertEquals(request.getMethod(), HttpMethod.GET);\n      assertEquals(request.getHeaders().size(), 0);\n   }\n\n   public void testCreateGetQueryEmpty() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> method = method(TestRequest.class, \"getQueryEmpty\", String.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method, ImmutableList.<Object> of(\"1\")));\n      assertEquals(request.getEndpoint().getHost(), \"localhost\");\n      assertEquals(request.getEndpoint().getPath(), \"/1\");\n      assertEquals(request.getEndpoint().getQuery(), \"acl=\");\n      assertEquals(request.getMethod(), HttpMethod.GET);\n      assertEquals(request.getHeaders().size(), 0);\n   }\n\n   public static class PayloadOptions extends BaseHttpRequestOptions {\n      @Override\n      public String buildStringPayload() {\n         return \"foo\";\n      }\n   }\n\n   public void testCreateGetOptionsThatProducesPayload() throws Exception {\n      PayloadOptions options = new PayloadOptions();\n      Invokable<?, ?> method = method(TestRequest.class, \"putOptions\", String.class,\n            HttpRequestOptions.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(\"1\", options)));\n\n      assertRequestLineEquals(request, \"PUT http://localhost:9999/1 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: localhost:9999\\n\");\n      assertPayloadEquals(request, \"foo\", \"application/unknown\", false);\n   }\n\n   @DataProvider(name = \"strings\")\n   public Object[][] createData() {\n      return new Object[][] { { \"apples\" }, { \"sp ace\" }, { \"unic₪de\" }, { \"qu?stion\" } };\n   }\n\n   @Test(dataProvider = \"strings\")\n   public void testCreateGetRequest(String key) throws SecurityException, NoSuchMethodException,\n         UnsupportedEncodingException {\n      Invokable<?, ?> method = method(TestRequest.class, \"get\", String.class, String.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(key, \"localhost\")));\n      assertEquals(request.getEndpoint().getHost(), \"localhost\");\n      String expectedPath = \"/\" + URLEncoder.encode(key, \"UTF-8\").replaceAll(\"\\\\+\", \"%20\");\n      assertEquals(request.getEndpoint().getRawPath(), expectedPath);\n      assertEquals(request.getEndpoint().getPath(), \"/\" + key);\n      assertEquals(request.getMethod(), HttpMethod.GET);\n      assertEquals(request.getHeaders().size(), 1);\n      assertEquals(request.getHeaders().get(HttpHeaders.HOST), ImmutableList.of(\"localhost\"));\n   }\n\n   public void testCreatePutRequest() throws Exception {\n      Invokable<?, ?> method = method(TestRequest.class, \"put\", String.class, String.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(\"111\", \"data\")));\n\n      assertRequestLineEquals(request, \"PUT http://localhost:9999/1 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"\");\n      assertPayloadEquals(request, \"data\", \"application/unknown\", false);\n   }\n\n   public void testCreatePutHeader() throws Exception {\n      Invokable<?, ?> method = method(TestRequest.class, \"putHeader\", String.class, String.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(\"1\", \"data\")));\n\n      assertRequestLineEquals(request, \"PUT http://localhost:9999/1 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"foo: --1--\\n\");\n      assertPayloadEquals(request, \"data\", \"application/unknown\", false);\n   }\n\n   public static class TestVirtualHostMethod {\n      @GET\n      @Path(\"/{id}\")\n      @VirtualHost\n      public String get(@PathParam(\"id\") String id, String foo) {\n         return null;\n      }\n   }\n\n   @Test\n   public void testVirtualHostMethod() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> method = method(TestVirtualHostMethod.class, \"get\", String.class, String.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(\"1\", \"localhost\")));\n      assertEquals(request.getEndpoint().getHost(), \"localhost\");\n      assertEquals(request.getEndpoint().getPath(), \"/1\");\n      assertEquals(request.getMethod(), HttpMethod.GET);\n      assertEquals(request.getHeaders().size(), 1);\n      assertEquals(request.getHeaders().get(HttpHeaders.HOST), ImmutableList.of(\"localhost:9999\"));\n   }\n\n   interface TestVirtualHost {\n      @GET\n      @Path(\"/{id}\")\n      @VirtualHost\n      String get(@PathParam(\"id\") String id, String foo);\n\n      @GET\n      @Path(\"/{id}\")\n      String getPrefix(@PathParam(\"id\") String id, @BinderParam(BindAsHostPrefix.class) String foo);\n\n   }\n\n   @Test\n   public void testVirtualHost() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> method = method(TestVirtualHost.class, \"get\", String.class, String.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(\"1\", \"localhost\")));\n      assertEquals(request.getEndpoint().getHost(), \"localhost\");\n      assertEquals(request.getEndpoint().getPath(), \"/1\");\n      assertEquals(request.getMethod(), HttpMethod.GET);\n      assertEquals(request.getHeaders().size(), 1);\n      assertEquals(request.getHeaders().get(HttpHeaders.HOST), ImmutableList.of(\"localhost:9999\"));\n   }\n\n   @Test\n   public void testHostPrefix() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> method = method(TestVirtualHost.class, \"getPrefix\", String.class, String.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(\"1\", \"holy\")));\n      assertEquals(request.getEndpoint().getHost(), \"holy.localhost\");\n      assertEquals(request.getEndpoint().getPath(), \"/1\");\n      assertEquals(request.getMethod(), HttpMethod.GET);\n      assertEquals(request.getHeaders().size(), 0);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testHostPrefixEmpty() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> method = method(TestVirtualHost.class, \"getPrefix\", String.class, String.class);\n      processor.apply(Invocation.create(method, ImmutableList.<Object> of(\"1\", \"\")));\n   }\n\n   interface TestHeaders {\n      @GET\n      void oneHeader(@HeaderParam(\"header\") String header);\n\n      @GET\n      void oneIntHeader(@HeaderParam(\"header\") int header);\n\n      @GET\n      void twoDifferentHeaders(@HeaderParam(\"header1\") String header1, @HeaderParam(\"header2\") String header2);\n\n      @GET\n      void twoSameHeaders(@HeaderParam(\"header\") String header1, @HeaderParam(\"header\") String header2);\n   }\n\n   @Test\n   public void testOneHeader() throws SecurityException, NoSuchMethodException, ExecutionException {\n      Invokable<?, ?> method = method(TestHeaders.class, \"oneHeader\", String.class);\n      Multimap<String, String> headers = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(\"robot\"))).getHeaders();\n      assertEquals(headers.size(), 1);\n      assertEquals(headers.get(\"header\"), ImmutableList.of(\"robot\"));\n   }\n\n   @Test\n   public void testOneIntHeader() throws SecurityException, NoSuchMethodException, ExecutionException {\n      Invokable<?, ?> method = method(TestHeaders.class, \"oneIntHeader\", int.class);\n      Multimap<String, String> headers = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(1))).getHeaders();\n      assertEquals(headers.size(), 1);\n      assertEquals(headers.get(\"header\"), ImmutableList.of(\"1\"));\n   }\n\n   @Test\n   public void testTwoDifferentHeaders() throws SecurityException, NoSuchMethodException, ExecutionException {\n      Invokable<?, ?> method = method(TestHeaders.class, \"twoDifferentHeaders\", String.class,\n            String.class);\n      Multimap<String, String> headers = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(\"robot\", \"egg\"))).getHeaders();\n      assertEquals(headers.size(), 2);\n      assertEquals(headers.get(\"header1\"), ImmutableList.of(\"robot\"));\n      assertEquals(headers.get(\"header2\"), ImmutableList.of(\"egg\"));\n   }\n\n   @Test\n   public void testTwoSameHeaders() throws SecurityException, NoSuchMethodException, ExecutionException {\n      Invokable<?, ?> method = method(TestHeaders.class, \"twoSameHeaders\", String.class, String.class);\n      Multimap<String, String> headers = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(\"robot\", \"egg\"))).getHeaders();\n      assertEquals(headers.size(), 2);\n      Collection<String> values = headers.get(\"header\");\n      assert values.contains(\"robot\");\n      assert values.contains(\"egg\");\n   }\n\n   interface TestEndpointParams {\n      @GET\n      void oneEndpointParam(@EndpointParam(parser = ConvertToURI.class) String EndpointParam);\n\n      @Singleton\n      public static class ConvertToURI implements Function<Object, URI> {\n\n         @Override\n         public URI apply(Object from) {\n            return URI.create(from.toString());\n         }\n\n      }\n\n      @GET\n      void twoEndpointParams(@EndpointParam(parser = ConvertTwoToURI.class) String EndpointParam1,\n            @EndpointParam(parser = ConvertTwoToURI.class) String EndpointParam2);\n\n      @Singleton\n      public static class ConvertTwoToURI implements Function<Object, URI> {\n\n         @SuppressWarnings(\"unchecked\")\n         @Override\n         public URI apply(Object from) {\n            return URI.create(Joiner.on('/').join((Iterable<Object>) from));\n         }\n\n      }\n\n   }\n\n   @Test\n   public void testOneEndpointParam() throws SecurityException, NoSuchMethodException, ExecutionException {\n      Invokable<?, ?> method = method(TestEndpointParams.class, \"oneEndpointParam\", String.class);\n      URI uri = RestAnnotationProcessor.getEndpointInParametersOrNull(\n            Invocation.create(method, ImmutableList.<Object> of(\"robot\")), injector);\n      assertEquals(uri, URI.create(\"robot\"));\n\n   }\n\n   @Test(expectedExceptions = IllegalStateException.class)\n   public void testTwoDifferentEndpointParams() throws SecurityException, NoSuchMethodException, ExecutionException {\n      Invokable<?, ?> method = method(TestEndpointParams.class, \"twoEndpointParams\", String.class,\n            String.class);\n      RestAnnotationProcessor.getEndpointInParametersOrNull(\n            Invocation.create(method, ImmutableList.<Object> of(\"robot\", \"egg\")), injector);\n   }\n\n   interface TestPayload {\n      @PUT\n      void put(@BinderParam(BindToStringPayload.class) String content);\n\n      @PUT\n      @Path(\"/{foo}\")\n      void putWithPath(@PathParam(\"foo\") String path,\n            @BinderParam(BindToStringPayload.class) String content);\n\n      @PUT\n      void twoEntities(@BinderParam(BindToStringPayload.class) String payload1,\n            @BinderParam(BindToStringPayload.class) String payload2);\n   }\n\n   @Test\n   public void testPut() throws Exception {\n      Invokable<?, ?> method = method(TestPayload.class, \"put\", String.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(\"test\")));\n\n      assertRequestLineEquals(request, \"PUT http://localhost:9999 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"\");\n      assertPayloadEquals(request, \"test\", \"application/unknown\", false);\n   }\n\n   @Test\n   public void putWithPath() throws Exception {\n      Invokable<?, ?> method = method(TestPayload.class, \"putWithPath\", String.class, String.class);\n      GeneratedHttpRequest request = processor.apply(Invocation.create(method,\n            ImmutableList.<Object> of(\"rabble\", \"test\")));\n\n      assertRequestLineEquals(request, \"PUT http://localhost:9999/rabble HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"\");\n      assertPayloadEquals(request, \"test\", \"application/unknown\", false);\n   }\n\n   public static class TestReplaceFormOptions extends BaseHttpRequestOptions {\n      public TestReplaceFormOptions() {\n         this.formParameters.put(\"x-amz-copy-source\", \"/{bucket}\");\n      }\n   }\n\n   public static class TestFormReplace {\n\n      @POST\n      @Path(\"/\")\n      public void formInOptions(@PathParam(\"bucket\") String path, TestReplaceFormOptions options) {\n      }\n\n      @POST\n      @Path(\"/\")\n      @FormParams(keys = \"x-amz-copy-source\", values = \"/{bucket}\")\n      public void oneForm(@PathParam(\"bucket\") String path) {\n      }\n\n      @POST\n      @Path(\"/\")\n      @FormParams(keys = { \"slash\", \"hyphen\" }, values = { \"/{bucket}\", \"-{bucket}\" })\n      public void twoForm(@PathParam(\"bucket\") String path) {\n      }\n\n      @POST\n      @Path(\"/\")\n      @FormParams(keys = \"x-amz-copy-source\", values = \"/{bucket}/{key}\")\n      public void twoForms(@PathParam(\"bucket\") String path, @PathParam(\"key\") String path2) {\n      }\n\n      @POST\n      @Path(\"/\")\n      @FormParams(keys = \"x-amz-copy-source\", values = \"/{bucket}/{key}\")\n      public void twoFormsOutOfOrder(@PathParam(\"key\") String path, @PathParam(\"bucket\") String path2) {\n      }\n   }\n\n   @Test\n   public void testBuildTwoForm() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> method = method(TestFormReplace.class, \"twoForm\", String.class);\n      Object form = processor.apply(Invocation.create(method, ImmutableList.<Object> of(\"robot\")))\n            .getPayload().getRawContent();\n      assertEquals(form, \"slash=/robot&hyphen=-robot\");\n   }\n\n   @FormParams(keys = \"x-amz-copy-source\", values = \"/{bucket}\")\n   interface TestClassForm {\n      @POST\n      @Path(\"/\")\n      void oneForm(@PathParam(\"bucket\") String path);\n   }\n\n   @Test\n   public void testBuildOneClassForm() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> method = method(TestClassForm.class, \"oneForm\", String.class);\n      Object form = processor.apply(Invocation.create(method, ImmutableList.<Object> of(\"robot\")))\n            .getPayload().getRawContent();\n      assertEquals(form, \"x-amz-copy-source=/robot\");\n   }\n\n   @Test\n   public void testBuildOneForm() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> method = method(TestFormReplace.class, \"oneForm\", String.class);\n      Object form = processor.apply(Invocation.create(method, ImmutableList.<Object> of(\"robot\")))\n            .getPayload().getRawContent();\n      assertEquals(form, \"x-amz-copy-source=/robot\");\n   }\n\n   @Test\n   public void testBuildTwoForms() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> method = method(TestFormReplace.class, \"twoForms\", String.class, String.class);\n      Object form = processor.apply(Invocation.create(method, ImmutableList.<Object> of(\"robot\", \"eggs\")))\n            .getPayload().getRawContent();\n      assertEquals(form, \"x-amz-copy-source=/robot/eggs\");\n   }\n\n   @Test\n   public void testBuildTwoFormsOutOfOrder() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> method = method(TestFormReplace.class, \"twoFormsOutOfOrder\", String.class,\n            String.class);\n      Object form = processor.apply(Invocation.create(method, ImmutableList.<Object> of(\"robot\", \"eggs\")))\n            .getPayload().getRawContent();\n      assertEquals(form, \"x-amz-copy-source=/eggs/robot\");\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testAddHostNullWithHost() throws Exception {\n      assertNull(RestAnnotationProcessor.addHostIfMissing(null, null));\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testAddHostWithHostHasNoHost() throws Exception {\n      assertNull(RestAnnotationProcessor.addHostIfMissing(null, new URI(\"/no/host\")));\n   }\n\n   @Test\n   public void testAddHostNullOriginal() throws Exception {\n      assertNull(RestAnnotationProcessor.addHostIfMissing(null, new URI(\"http://foo\")));\n   }\n\n   @Test\n   public void testAddHostOriginalHasHost() throws Exception {\n\n      URI original = new URI(\"http://hashost/foo\");\n      URI result = RestAnnotationProcessor.addHostIfMissing(original, new URI(\"http://foo\"));\n      assertEquals(original, result);\n   }\n\n   @Test\n   public void testAddHostIfMissing() throws Exception {\n      URI result = RestAnnotationProcessor.addHostIfMissing(new URI(\"/bar\"), new URI(\"http://foo\"));\n      assertEquals(new URI(\"http://foo/bar\"), result);\n   }\n\n   @Test\n   public void testComplexHost() throws Exception {\n      URI result = RestAnnotationProcessor.addHostIfMissing(new URI(\"bar\"), new URI(\"http://foo/foobar\"));\n      assertEquals(new URI(\"http://foo/foobar/bar\"), result);\n   }\n\n\n   DateService dateService = new SimpleDateFormatDateService();\n   RestAnnotationProcessor processor;\n   TransformerForRequest transformer;\n\n   @BeforeClass\n   void setupFactory() {\n      injector = ContextBuilder\n            .newBuilder(forApiOnEndpoint(Callee.class, \"http://localhost:9999\"))\n            .modules(ImmutableSet.<Module> of(new MockModule(), new NullLoggingModule(), new AbstractModule() {\n               protected void configure() {\n                  bind(new TypeLiteral<Supplier<URI>>() {\n                  }).annotatedWith(Localhost2.class).toInstance(\n                        Suppliers.ofInstance(URI.create(\"http://localhost:1111\")));\n               }\n            })).buildInjector();\n      parserFactory = injector.getInstance(ParseSax.Factory.class);\n      processor = injector.getInstance(RestAnnotationProcessor.class);\n      transformer = injector.getInstance(TransformerForRequest.class);\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/rest/suppliers/MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplierTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.suppliers;\n\nimport static com.google.common.base.Suppliers.ofInstance;\nimport static com.google.common.util.concurrent.Atomics.newReference;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.suppliers.MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier.SetAndThrowAuthorizationExceptionSupplierBackedLoader;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.util.concurrent.UncheckedExecutionException;\nimport com.google.common.util.concurrent.Uninterruptibles;\n\n@Test(groups = \"unit\", testName = \"MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplierTest\")\npublic class MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplierTest {\n   @Test\n   public void testLoaderNormal() {\n      AtomicReference<AuthorizationException> authException = newReference();\n      assertEquals(new SetAndThrowAuthorizationExceptionSupplierBackedLoader<String>(ofInstance(\"foo\"), authException, new ValueLoadedCallback.NoOpCallback<String>()).load(\"KEY\").get(), \"foo\");\n      assertEquals(authException.get(), null);\n   }\n\n   @Test(expectedExceptions = AuthorizationException.class)\n   public void testLoaderThrowsAuthorizationExceptionAndAlsoSetsExceptionType() {\n      AtomicReference<AuthorizationException> authException = newReference();\n      try {\n         new SetAndThrowAuthorizationExceptionSupplierBackedLoader<String>(new Supplier<String>() {\n            public String get() {\n               throw new AuthorizationException();\n            }\n         }, authException, new ValueLoadedCallback.NoOpCallback<String>()).load(\"KEY\");\n      } finally {\n         assertEquals(authException.get().getClass(), AuthorizationException.class);\n      }\n   }\n\n   @Test(expectedExceptions = AuthorizationException.class)\n   public void testLoaderThrowsAuthorizationExceptionAndAlsoSetsExceptionTypeWhenNested() {\n      AtomicReference<AuthorizationException> authException = newReference();\n      try {\n         new SetAndThrowAuthorizationExceptionSupplierBackedLoader<String>(new Supplier<String>() {\n            public String get() {\n               throw new RuntimeException(new ExecutionException(new AuthorizationException()));\n            }\n         }, authException, new ValueLoadedCallback.NoOpCallback<String>()).load(\"KEY\");\n      } finally {\n         assertEquals(authException.get().getClass(), AuthorizationException.class);\n      }\n   }\n\n   @Test(expectedExceptions = AuthorizationException.class)\n   public void testLoaderThrowsAuthorizationExceptionAndAlsoSetsExceptionTypeWhenInUncheckedExecutionException() {\n      AtomicReference<AuthorizationException> authException = newReference();\n      try {\n         new SetAndThrowAuthorizationExceptionSupplierBackedLoader<String>(new Supplier<String>() {\n            public String get() {\n               throw new UncheckedExecutionException(new AuthorizationException());\n            }\n         }, authException, new ValueLoadedCallback.NoOpCallback<String>()).load(\"KEY\");\n      } finally {\n         assertEquals(authException.get().getClass(), AuthorizationException.class);\n      }\n   }\n\n   @Test(expectedExceptions = RuntimeException.class)\n   public void testLoaderThrowsOriginalExceptionAndAlsoSetsExceptionTypeWhenNestedAndNotAuthorizationException() {\n      AtomicReference<AuthorizationException> authException = newReference();\n      try {\n         new SetAndThrowAuthorizationExceptionSupplierBackedLoader<String>(new Supplier<String>() {\n            public String get() {\n               throw new RuntimeException(new IllegalArgumentException(\"foo\"));\n            }\n         }, authException, new ValueLoadedCallback.NoOpCallback<String>()).load(\"KEY\");\n      } finally {\n         assertEquals(authException.get().getClass(), RuntimeException.class);\n      }\n   }\n\n   @Test\n   public void testLoaderNotifiesAfterReloading() {\n      AtomicReference<AuthorizationException> authException = newReference();\n      ValueLoadedEventHandler handler = new ValueLoadedEventHandler();\n\n      Supplier<String> supplier = MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier.create(authException,\n            Suppliers.<String> ofInstance(\"foo\"), 3, TimeUnit.SECONDS, handler);\n\n      // The supplier loads the value initially and returns the cached values\n      assertEquals(handler.count.get(), 0);\n      supplier.get();\n      assertEquals(handler.count.get(), 1);\n      supplier.get();\n      assertEquals(handler.count.get(), 1);\n      \n      // Once expired, it reloads the values, notified the event, and updated the cache\n      Uninterruptibles.sleepUninterruptibly(4, TimeUnit.SECONDS);\n      supplier.get();\n      assertEquals(handler.count.get(), 2);\n      supplier.get();\n      assertEquals(handler.count.get(), 2);\n      supplier.get();\n      assertEquals(handler.count.get(), 2);\n   }\n\n   static class ValueLoadedEventHandler implements ValueLoadedCallback<String>{\n      AtomicInteger count = new AtomicInteger(0);\n\n      @Override\n      public void valueLoaded(Optional<String> value) {\n         count.incrementAndGet();\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/rest/suppliers/SetAndThrowAuthorizationExceptionSupplierTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rest.suppliers;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport org.jclouds.rest.AuthorizationException;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.util.concurrent.Atomics;\n\n@Test(groups = \"unit\", testName = \"MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplierTest\")\npublic class SetAndThrowAuthorizationExceptionSupplierTest {\n   @Test\n   public void testNormal() {\n      AtomicReference<AuthorizationException> authException = Atomics.newReference();\n      assertEquals(\n            new SetAndThrowAuthorizationExceptionSupplier<String>(Suppliers.ofInstance(\"foo\"), authException).get(),\n            \"foo\");\n      assertEquals(authException.get(), null);\n   }\n\n   @Test(expectedExceptions = AuthorizationException.class)\n   public void testThrowsAuthorizationExceptionAndAlsoSetsExceptionType() {\n      AtomicReference<AuthorizationException> authException = Atomics.newReference();\n      try {\n         new SetAndThrowAuthorizationExceptionSupplier<String>(new Supplier<String>() {\n\n            @Override\n            public String get() {\n               throw new AuthorizationException();\n            }\n         }, authException).get();\n      } finally {\n         assertEquals(authException.get().getClass(), AuthorizationException.class);\n      }\n   }\n\n   @Test(expectedExceptions = AuthorizationException.class)\n   public void testThrowsAuthorizationExceptionAndAlsoSetsExceptionTypeWhenNested() {\n      AtomicReference<AuthorizationException> authException = Atomics.newReference();\n      try {\n         new SetAndThrowAuthorizationExceptionSupplier<String>(new Supplier<String>() {\n\n            @Override\n            public String get() {\n               throw new RuntimeException(new ExecutionException(new AuthorizationException()));\n            }\n         }, authException).get();\n      } finally {\n         assertEquals(authException.get().getClass(), AuthorizationException.class);\n      }\n   }\n\n   @Test(expectedExceptions = RuntimeException.class)\n   public void testThrowsOriginalExceptionAndAlsoSetsExceptionTypeWhenNestedAndNotAuthorizationException() {\n      AtomicReference<AuthorizationException> authException = Atomics.newReference();\n      try {\n         new SetAndThrowAuthorizationExceptionSupplier<String>(new Supplier<String>() {\n\n            @Override\n            public String get() {\n               throw new RuntimeException(new IllegalArgumentException(\"foo\"));\n            }\n         }, authException).get();\n      } finally {\n         assertEquals(authException.get().getClass(), RuntimeException.class);\n      }\n   }\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/suppliers/SupplyKeyMatchingValueOrNullTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.suppliers;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\n\nimport java.util.Map;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableMap;\n\n@Test(groups = \"unit\", testName = \"SupplyKeyMatchingValueOrNullTest\")\npublic class SupplyKeyMatchingValueOrNullTest {\n\n   private static final Supplier<String> valueSupplier = Suppliers.ofInstance(\"v3\");\n\n   public void testValueFound() {\n      SupplyKeyMatchingValueOrNull<String, String> supplier = supplier(\"k1\", \"v1\", \"k2\", \"v2\", \"k3\", \"v3\");\n      assertEquals(supplier.get(), \"k3\");\n   }\n\n   public void testFirstKeyIsReturnedIfValueNotFound() {\n      SupplyKeyMatchingValueOrNull<String, String> supplier = supplier(\"k1\", \"v1\", \"k2\", \"v2\", \"k4\", \"v4\");\n      assertEquals(supplier.get(), \"k1\");\n   }\n\n   public void testFirstKeyIsReturnedIfMultipleValuesFound() {\n      SupplyKeyMatchingValueOrNull<String, String> supplier = supplier(\"k1\", \"v1\", \"k2\", \"v3\", \"k3\", \"v3\");\n      assertEquals(supplier.get(), \"k2\");\n   }\n\n   public void testReturnsNullIfEmptyMap() {\n      SupplyKeyMatchingValueOrNull<String, String> supplier = new SupplyKeyMatchingValueOrNull<String, String>(\n            Suppliers.<Map<String, Supplier<String>>> ofInstance(ImmutableMap.<String, Supplier<String>> of()),\n            valueSupplier);\n      assertNull(supplier.get());\n   }\n\n   private static SupplyKeyMatchingValueOrNull<String, String> supplier(String k1, String v1, String k2, String v2,\n         String k3, String v3) {\n      return new SupplyKeyMatchingValueOrNull<String, String>(map(k1, v1, k2, v2, k3, v3), valueSupplier);\n   }\n\n   private static Supplier<Map<String, Supplier<String>>> map(String k1, String v1, String k2, String v2, String k3,\n         String v3) {\n      return Suppliers.<Map<String, Supplier<String>>> ofInstance(ImmutableMap.of(k1, Suppliers.ofInstance(v1), k2,\n            Suppliers.ofInstance(v2), k3, Suppliers.ofInstance(v3)));\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/test/testng/UnitTestStatusListener.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.test.testng;\n\nimport java.util.concurrent.atomic.AtomicInteger;\n\nimport org.testng.IClass;\nimport org.testng.ITestContext;\nimport org.testng.ITestListener;\nimport org.testng.ITestResult;\n\n/**\n * adapted from the following class:\n * \n * @see org.UnitTestStatusListener.test.testng.UnitTestTestNGListener\n */\npublic class UnitTestStatusListener implements ITestListener {\n\n   /**\n    * Holds test classes actually running in all threads.\n    */\n   private ThreadLocal<IClass> threadTestClass = new ThreadLocal<IClass>();\n   private ThreadLocal<Long> threadTestStart = new ThreadLocal<Long>();\n\n   private AtomicInteger failed = new AtomicInteger(0);\n   private AtomicInteger succeded = new AtomicInteger(0);\n   private AtomicInteger skipped = new AtomicInteger(0);\n\n   public void onTestStart(ITestResult res) {\n      System.out.println(\"Starting test \" + getTestDesc(res));\n      threadTestClass.set(res.getTestClass());\n      threadTestStart.set(System.currentTimeMillis());\n   }\n\n   public synchronized void onTestSuccess(ITestResult arg0) {\n      System.out.println(getThreadId() + \" Test \" + getTestDesc(arg0) + \" succeeded: \"\n               + (System.currentTimeMillis() - threadTestStart.get()) + \"ms\");\n      succeded.incrementAndGet();\n      printStatus();\n   }\n\n   public synchronized void onTestFailure(ITestResult arg0) {\n      System.out.println(getThreadId() + \" Test \" + getTestDesc(arg0) + \" failed.\");\n      failed.incrementAndGet();\n      printStatus();\n   }\n\n   public synchronized void onTestSkipped(ITestResult arg0) {\n      System.out.println(getThreadId() + \" Test \" + getTestDesc(arg0) + \" skipped.\");\n      skipped.incrementAndGet();\n      printStatus();\n   }\n\n   public void onTestFailedButWithinSuccessPercentage(ITestResult arg0) {\n   }\n\n   public void onStart(ITestContext arg0) {\n   }\n\n   public void onFinish(ITestContext arg0) {\n   }\n\n   private String getThreadId() {\n      return \"[\" + Thread.currentThread().getName() + \"]\";\n   }\n\n   private String getTestDesc(ITestResult res) {\n      return res.getMethod().getMethodName() + \"(\" + res.getTestClass().getName() + \")\";\n   }\n\n   private void printStatus() {\n      System.out.println(\"Test suite progress: tests succeeded: \" + succeded.get() + \", failed: \"\n               + failed.get() + \", skipped: \" + skipped.get() + \".\");\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/util/HttpUtilsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.util;\n\nimport static com.google.common.base.Predicates.equalTo;\nimport static org.jclouds.http.HttpUtils.returnValueOnCodeOrNull;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.testng.annotations.Test;\n\n/**\n* \n */\n@Test(groups = \"unit\")\npublic class HttpUtilsTest  {\n\n   public void test404() {\n      Exception from = new HttpResponseException(\"message\", null, HttpResponse.builder().statusCode(404).message(\"not found\").build());\n      assertEquals(returnValueOnCodeOrNull(from, true, equalTo(404)), Boolean.TRUE);\n   }\n\n   public void testNullResponse() {\n      Exception from = new HttpResponseException(\"message\", null, null);\n      assertEquals(returnValueOnCodeOrNull(from, true, equalTo(404)), null);\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/util/InetAddresses2Test.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.util;\n\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class InetAddresses2Test {\n\n   @Test\n   public void testPrivateIPAddress() {\n      assert InetAddresses2.isPrivateIPAddress(\"10.0.0.0\");\n      assert !InetAddresses2.isPrivateIPAddress(\"11.0.0.0\");\n      assert InetAddresses2.isPrivateIPAddress(\"172.16.0.0\");\n      assert !InetAddresses2.isPrivateIPAddress(\"172.32.0.0\");\n      assert InetAddresses2.isPrivateIPAddress(\"172.16.0.0\");\n      assert !InetAddresses2.isPrivateIPAddress(\"192.169.0.0\");\n      assert InetAddresses2.isPrivateIPAddress(\"192.168.0.0\");\n   }\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/util/Maps2Test.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.util;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Map;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableMap;\n\n@Test(groups = \"unit\")\npublic class Maps2Test {\n\n   public void testTransformKeys() {\n      Map<String, String> map = ImmutableMap.of(\"prefix:foo\", \"bar\");\n      assertEquals(Maps2.transformKeys(map, new Function<String, String>() {\n\n         @Override\n         public String apply(String arg0) {\n            return arg0.replace(\"prefix:\", \"\");\n         }\n\n      }), ImmutableMap.of(\"foo\", \"bar\"));\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/util/Multimaps2Test.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.util;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.functions.ToLowerCase;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.Multimap;\n\n@Test(groups = \"unit\")\npublic class Multimaps2Test {\n\tpublic void testTransformKeysToLowerCase() {\n\t\tMultimap<String, String> map = ImmutableMultimap.of(\"oNe\", \"1\", \"TWO\", \"2\", \"three\", \"3\", \"Three\", \"3.0\");\n\t\tMultimap<String, String> expected = ImmutableMultimap.of(\"one\", \"1\", \"two\", \"2\", \"three\", \"3\", \"three\", \"3.0\");\n\t\tMultimap<String, String> transformed = Multimaps2.transformKeys(map, new ToLowerCase());\n\t\t\n\t\tassertEquals(transformed, expected);\n\t}\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/util/Optionals2Test.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.util;\nimport static org.jclouds.reflect.Reflection2.method;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.reflect.Invokable;\n\n@Test\npublic class Optionals2Test {\n\n   public interface Test {\n      Optional<String> getOptional();\n\n      String getNotOptional();\n   }\n\n   public void testReturnTypeOrTypeOfOptionalWhenOptional() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> invoked = method(Test.class, \"getOptional\");\n\n      assertEquals(Optionals2.unwrapIfOptional(invoked.getReturnType()), String.class);\n   }\n\n   public void testReturnTypeOrTypeOfOptionalWhenNotOptional() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> invoked = method(Test.class, \"getNotOptional\");\n\n      assertEquals(Optionals2.unwrapIfOptional(invoked.getReturnType()), String.class);\n   }\n\n   public void testIsReturnTypeOptionalWhenOptional() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> invoked = method(Test.class, \"getOptional\");\n\n      assertTrue(Optionals2.isReturnTypeOptional(invoked));\n   }\n\n   public void testIsReturnTypeOptionalWhenNotOptional() throws SecurityException, NoSuchMethodException {\n      Invokable<?, ?> invoked = method(Test.class, \"getNotOptional\");\n\n      assertFalse(Optionals2.isReturnTypeOptional(invoked));\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/util/PasswordGeneratorTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.util;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"PasswordGeneratorTest\")\npublic class PasswordGeneratorTest {\n   \n   @Test\n   public void emptyPassword() {\n      String password = new PasswordGenerator()\n            .lower().count(0)\n            .upper().count(0)\n            .numbers().count(0)\n            .symbols().count(0)\n            .generate();\n      assertEquals(password, \"\");\n   }\n\n   @Test\n   public void onlyLowerCase() {\n      String password = new PasswordGenerator()\n            .upper().count(0)\n            .numbers().count(0)\n            .symbols().count(0)\n            .generate();\n      assertTrue(password.matches(\"^[a-z]+$\"));\n   }\n   \n   @Test\n   public void lowerAndUpperWithConstrainedLength() {\n      String password = new PasswordGenerator()\n            .lower().min(2).max(5)\n            .upper().count(3)\n            .numbers().count(0)\n            .symbols().count(0)\n            .generate();\n      assertTrue(password.matches(\"^[a-zA-Z]+$\"));\n      assertTrue(password.replaceAll(\"[A-Z]\", \"\").matches(\"[a-z]{2,5}\"));\n      assertTrue(password.replaceAll(\"[a-z]\", \"\").matches(\"[A-Z]{3}\"));\n   }\n   \n   @Test\n   public void defaultGeneratorContainsAll() {\n      String password = new PasswordGenerator().generate();\n      assertTrue(password.matches(\".*[a-z].*[a-z].*\"));\n      assertTrue(password.matches(\".*[A-Z].*[A-Z].*\"));\n      assertTrue(password.matches(\".*[0-9].*[0-9].*\"));\n      assertTrue(password.replaceAll(\"[a-zA-Z0-9]\", \"\").length() > 0);\n   }\n   \n   @Test\n   public void characterExclusion() {\n      String password = new PasswordGenerator()\n            .lower().count(0)\n            .upper().count(0)\n            .numbers().exclude(\"012345\".toCharArray())\n            .symbols().count(0)\n            .generate();\n      assertTrue(password.matches(\"^[6-9]+$\"));\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/util/Predicates2Test.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.util;\n\nimport static java.util.concurrent.TimeUnit.MILLISECONDS;\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static org.jclouds.util.Predicates2.retry;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.Assert.fail;\n\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.TimeoutException;\n\nimport org.testng.Assert;\nimport org.testng.annotations.BeforeMethod;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Stopwatch;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.Lists;\n\n@Test(groups = \"unit\", singleThreaded = true)\npublic class Predicates2Test {\n   // Grace must be reasonably big; Thread.sleep can take a bit longer to wake up sometimes...\n   public static final int SLOW_BUILD_SERVER_GRACE = 250;\n\n   // Sometimes returns sooner than timer would predict (e.g. observed 2999ms, when expected 3000ms)\n   public static final int EARLY_RETURN_GRACE = 10;\n\n   private Stopwatch stopwatch;\n\n   @BeforeMethod\n   public void setUp() {\n      stopwatch = Stopwatch.createUnstarted();\n   }\n   \n   @Test\n   void testRetryReturnsFalseOnIllegalStateExeception() {\n      ensureImmediateReturnFor(new IllegalStateException());\n   }\n\n   @Test\n   void testRetryReturnsFalseOnExecutionException() {\n      ensureImmediateReturnFor(new ExecutionException(new Exception(\"Simulated cause\")));\n   }\n\n   @Test\n   void testRetryReturnsFalseOnTimeoutException() {\n      ensureImmediateReturnFor(new TimeoutException(\"Simulating exception\"));\n   }\n\n   @Test(expectedExceptions = RuntimeException.class)\n   void testRetryPropagatesOnException() {\n      ensureImmediateReturnFor(new Exception(\"Simulating exception\"));\n   }\n\n   private void ensureImmediateReturnFor(final Exception ex) {\n      Predicate<Supplier<String>> predicate = retry(\n               new Predicate<Supplier<String>>() {\n                  public boolean apply(Supplier<String> input) {\n                     return \"goo\".equals(input.get());\n                  }\n               }, 3, 1, SECONDS);\n      \n      stopwatch.start();\n      assertFalse(predicate.apply(new Supplier<String>() {\n\n         @Override\n         public String get() {\n            throw new RuntimeException(ex);\n         }\n\n      }));\n      long duration = stopwatch.elapsed(MILLISECONDS);\n      assertOrdered(duration, SLOW_BUILD_SERVER_GRACE);\n   }\n\n   @Test\n   void testRetryAlwaysFalseMillis() {\n      // maxWait=3; period=1; maxPeriod defaults to 1*10\n      // will call at 0, 1, 1+(1*1.5), 3\n      RepeatedAttemptsPredicate rawPredicate = new RepeatedAttemptsPredicate(Integer.MAX_VALUE);\n      Predicate<String> predicate = retry(rawPredicate, 3, 1, SECONDS);\n      stopwatch.start();\n      assertFalse(predicate.apply(\"\"));\n      long duration = stopwatch.elapsed(MILLISECONDS);\n      assertOrdered(3000 - EARLY_RETURN_GRACE, duration, 3000 + SLOW_BUILD_SERVER_GRACE);\n      assertCallTimes(rawPredicate.callTimes, 0, 1000, 1000 + 1500, 3000);\n   }\n\n   @Test\n   void testRetryFirstTimeTrue() {\n      RepeatedAttemptsPredicate rawPredicate = new RepeatedAttemptsPredicate(1);\n      Predicate<String> predicate = retry(rawPredicate, 4, 1, SECONDS);\n\n      stopwatch.start();\n      assertTrue(predicate.apply(\"\"));\n      long duration = stopwatch.elapsed(MILLISECONDS);\n      \n      assertOrdered(0, duration, 0 + SLOW_BUILD_SERVER_GRACE);\n      assertCallTimes(rawPredicate.callTimes, 0);\n   }\n\n   @Test\n   void testRetryWillRunOnceOnNegativeTimeout() {\n      RepeatedAttemptsPredicate rawPredicate = new RepeatedAttemptsPredicate(1);\n      Predicate<String> predicate = retry(rawPredicate, -1, 1, SECONDS);\n\n      stopwatch.start();\n      assertTrue(predicate.apply(\"\"));\n      long duration = stopwatch.elapsed(MILLISECONDS);\n      \n      assertOrdered(0, duration, 0 + SLOW_BUILD_SERVER_GRACE);\n      assertCallTimes(rawPredicate.callTimes, 0);\n   }\n\n   @Test\n   void testRetryThirdTimeTrue() {\n      // maxWait=4; period=1; maxPeriod defaults to 1*10\n      // will call at 0, 1, 1+(1*1.5)\n      RepeatedAttemptsPredicate rawPredicate = new RepeatedAttemptsPredicate(3);\n      Predicate<String> predicate = retry(rawPredicate, 4, 1, SECONDS);\n\n      stopwatch.start();\n      assertTrue(predicate.apply(\"\"));\n      long duration = stopwatch.elapsed(MILLISECONDS);\n      \n      assertOrdered(2500 - EARLY_RETURN_GRACE, duration, 2500 + SLOW_BUILD_SERVER_GRACE);\n      assertCallTimes(rawPredicate.callTimes, 0, 1000, 1000 + 1500);\n   }\n\n   @Test\n   void testRetryThirdTimeTrueLimitedMaxInterval() {\n      // maxWait=3; period=1; maxPeriod=1\n      // will call at 0, 1, 1+1\n      RepeatedAttemptsPredicate rawPredicate = new RepeatedAttemptsPredicate(3);\n      Predicate<String> predicate = retry(rawPredicate, 3, 1, 1, SECONDS);\n\n      stopwatch.start();\n      assertTrue(predicate.apply(\"\"));\n      long duration = stopwatch.elapsed(MILLISECONDS);\n      \n      assertOrdered(2000 - EARLY_RETURN_GRACE, duration, 2000 + SLOW_BUILD_SERVER_GRACE);\n      assertCallTimes(rawPredicate.callTimes, 0, 1000, 2000);\n   }\n   \n   public static class RepeatedAttemptsPredicate implements Predicate<String> {\n      final List<Long> callTimes = Lists.newArrayList();\n      private final int succeedOnAttempt;\n      private final Stopwatch stopwatch;\n      private int count = 0;\n      \n      RepeatedAttemptsPredicate(int succeedOnAttempt) {\n         this.succeedOnAttempt = succeedOnAttempt;\n         this.stopwatch = Stopwatch.createUnstarted();\n         stopwatch.start();\n      }\n      @Override\n      public boolean apply(String input) {\n         callTimes.add(stopwatch.elapsed(MILLISECONDS));\n         return ++count == succeedOnAttempt;\n      }\n   }\n   \n   @Test(enabled = false) // not a test, but picked up as such because public\n   public static void assertCallTimes(List<Long> actual, Integer... expected) {\n      Assert.assertEquals(actual.size(), expected.length, \"actual=\" + actual);\n      for (int i = 0; i < expected.length; i++) {\n         long callTime = actual.get(i);\n         assertOrdered(expected[i] - EARLY_RETURN_GRACE, callTime, expected[i] + SLOW_BUILD_SERVER_GRACE);\n      }\n   }\n   \n   private static void assertOrdered(long... values) {\n      long prevVal = values[0];\n      for (long val : values) {\n         if (val < prevVal) {\n            fail(String.format(\"%s should be ordered\", Arrays.toString(values)));\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/util/Strings2Test.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.util;\n\nimport static org.jclouds.util.Strings2.urlDecode;\nimport static org.jclouds.util.Strings2.urlEncode;\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMultimap;\n\n@Test(groups = \"unit\")\npublic class Strings2Test {\n\n   public void testReplaceTokens() {\n      assertEquals(Strings2.replaceTokens(\"hello {where}\", ImmutableMap.of(\"where\", \"world\")), \"hello world\");\n      assertEquals(Strings2.replaceTokens(\"hello {where}\", ImmutableMap.of(\"where\", \"$1,000,000 \\\\o/!\")), \"hello $1,000,000 \\\\o/!\");\n      assertEquals(Strings2.replaceTokens(\"hello {where}\", ImmutableMultimap.of(\"where\", \"$1,000,000 \\\\o/!\")), \"hello $1,000,000 \\\\o/!\");\n   }\n\n   public void testUrlEncodeDecodeShouldGiveTheSameString() {\n      String actual = \"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCc903twxU2zcQnIJdXv61RwZNZW94uId9qz08fgsBJsCOnHNIC4+L9k\" +\n         \"DOA2IHV9cUfEDBm1Be5TbpadWwSbS/05E+FARH2/MCO932UgcKUq5PGymS0249fLCBPci5zoLiG5vIym+1ij1hL/nHvkK99NIwe7io+Lmp\" +\n         \"9OcF3PTsm3Rgh5T09cRHGX9horp0VoAVa9vKJx6C1/IEHVnG8p0YPPa1lmemvx5kNBEiyoNQNYa34EiFkcJfP6rqNgvY8h/j4nE9SXoUCC\" +\n         \"/g6frhMFMOL0tzYqvz0Lczqm1Oh4RnSn3O9X4R934p28qqAobe337hmlLUdb6H5zuf+NwCh0HdZ\";\n      assertEquals(actual, urlDecode(urlEncode(actual)));\n   }\n\n   public void testIsCidrFormat() {\n      assert Strings2.isCidrFormat(\"1.2.3.4/5\");\n      assert Strings2.isCidrFormat(\"0.0.0.0/0\");\n      assert Strings2.isCidrFormat(\"fe80::/64\");\n      assert Strings2.isCidrFormat(\"fdcf:11a8:b89f::/64\");\n      assert Strings2.isCidrFormat(\"fe80:fd6d:96a8:b89f:abcd:11aa:1234:15af\");\n\n      for (int n = 0; n <= 128; n = n + 1) {\n         assert Strings2.isCidrFormat(\"fe80:fd6d:96a8:b89f:abcd:11aa:1234:15af/\" + n);\n      }\n\n      assert !Strings2.isCidrFormat(\"fe80:fd6d:96a8:b89f:abcd:11aa:1234:15af/129\");\n      assert !Strings2.isCidrFormat(\"fe80:fd6d:96a8:b89f:abcd:11aa:1234:15af/b\");\n      assert !Strings2.isCidrFormat(\"fe80:fd6d:96a8:b89f:abcd:11aa:1234:15af/*\");\n      assert !Strings2.isCidrFormat(\"fe80:fd6d:96a8:b89f:abcd:11aa:1234:15af/@\");\n      assert !Strings2.isCidrFormat(\"fe80:fd6d:96a8:b89f:abcd:11aa:1234:15af/00\");\n      assert !Strings2.isCidrFormat(\"fe80:fd6d:96a8:b89f:abcd:11aa:1234:15af/01\");\n      assert !Strings2.isCidrFormat(\"fe80:fd6d:96a8:b89f:abcd:11aa:1234:15af/\");\n\n      assert !Strings2.isCidrFormat(\"banana\");\n      assert !Strings2.isCidrFormat(\"1.2.3.4\");\n      assert !Strings2.isCidrFormat(\"500.500.500.500/2423\");\n   }\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/util/Suppliers2Test.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.util;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Map;\nimport java.util.NoSuchElementException;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableMap;\n\npublic class Suppliers2Test {\n\n   @Test\n   public void testGetLastValueInMap() {\n      assertEquals(\n               Suppliers2.<String, String> getLastValueInMap(\n                        Suppliers.<Map<String, Supplier<String>>> ofInstance(ImmutableMap.of(\"foo\",\n                                 Suppliers.ofInstance(\"bar\")))).get(), \"bar\");\n   }\n\n   @Test\n   public void testGetSpecificValueInMap() {\n      Supplier<Map<String, Supplier<String>>> testMap =  Suppliers.<Map<String, Supplier<String>>> ofInstance(\n               ImmutableMap.of(\"foo\", Suppliers.ofInstance(\"bar\")));\n\n      assertEquals(Suppliers2.<String, String> getValueInMapOrNull(testMap, \"foo\").get(), \"bar\");\n      assertEquals(Suppliers2.<String, String> getValueInMapOrNull(testMap, \"baz\").get(), null);\n   }\n\n   @Test\n   public void testOfInstanceFunction() {\n      assertEquals(Suppliers2.ofInstanceFunction().apply(\"foo\").get(), \"foo\");\n   }\n\n   @Test\n   public void testOrWhenFirstNull() {\n      assertEquals(Suppliers2.or(Suppliers.<String> ofInstance(null), Suppliers.ofInstance(\"foo\")).get(), \"foo\");\n   }\n\n   @Test\n   public void testOrWhenFirstNotNull() {\n      assertEquals(Suppliers2.or(Suppliers.<String> ofInstance(\"foo\"), Suppliers.ofInstance(\"bar\")).get(), \"foo\");\n   }\n\n   @Test\n   public void testOnThrowableWhenFirstThrowsMatchingException() {\n      assertEquals(Suppliers2.onThrowable(new Supplier<String>() {\n\n         @Override\n         public String get() {\n            throw new NoSuchElementException();\n         }\n\n      }, NoSuchElementException.class, Suppliers.ofInstance(\"foo\")).get(), \"foo\");\n   }\n\n   @Test(expectedExceptions = RuntimeException.class)\n   public void testOnThrowableWhenFirstThrowsUnmatchingException() {\n      Suppliers2.onThrowable(new Supplier<String>() {\n\n         @Override\n         public String get() {\n            throw new RuntimeException();\n         }\n\n      }, NoSuchElementException.class, Suppliers.ofInstance(\"foo\")).get();\n   }\n\n   @Test\n   public void testOnThrowableWhenFirstIsFine() {\n      assertEquals(\n               Suppliers2.onThrowable(Suppliers.<String> ofInstance(\"foo\"), NoSuchElementException.class,\n                        Suppliers.ofInstance(\"bar\")).get(), \"foo\");\n   }\n\n   \n   @Test\n   public void testCombination() {\n      Supplier<String> alternate = Suppliers.ofInstance(\"bar\");\n      Supplier<String> or = Suppliers2.or(Suppliers.<String> ofInstance(\"foo\"), alternate);\n      Supplier<String> combined = Suppliers2.onThrowable(or, NoSuchElementException.class, alternate);    \n      \n      assertEquals(combined.get(), \"foo\");\n   }\n\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/util/Throwables2Test.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.util;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.createNiceMock;\nimport static org.jclouds.reflect.Reflection2.typeToken;\nimport static org.jclouds.util.Throwables2.getFirstThrowableOfType;\nimport static org.jclouds.util.Throwables2.propagateIfPossible;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.net.SocketException;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.Future;\nimport java.util.concurrent.TimeoutException;\n\nimport org.jclouds.concurrent.TransformParallelException;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.InsufficientResourcesException;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.reflect.TypeToken;\nimport com.google.inject.CreationException;\nimport com.google.inject.ProvisionException;\nimport com.google.inject.spi.Message;\n\n@Test\npublic class Throwables2Test {\n\n   public void testGetFirstThrowableOfTypeSubclass() {\n      SocketException aex = createMock(SocketException.class);\n      assertEquals(getFirstThrowableOfType(aex, IOException.class), aex);\n   }\n\n   public void testGetFirstThrowableOfTypeOuter() {\n      AuthorizationException aex = createMock(AuthorizationException.class);\n      assertEquals(getFirstThrowableOfType(aex, AuthorizationException.class), aex);\n   }\n\n   public void testGetCause() {\n      AuthorizationException aex = createMock(AuthorizationException.class);\n      Message message = new Message(ImmutableList.of(), \"test\", aex);\n      ProvisionException pex = new ProvisionException(ImmutableSet.of(message));\n      assertEquals(getFirstThrowableOfType(pex, AuthorizationException.class), aex);\n   }\n\n   public void testGetFirstThrowableOfTypeInner() {\n      AuthorizationException aex = createMock(AuthorizationException.class);\n      Message message = new Message(ImmutableList.of(), \"test\", aex);\n      ProvisionException pex = new ProvisionException(ImmutableSet.of(message));\n      assertEquals(getFirstThrowableOfType(pex, AuthorizationException.class), aex);\n   }\n\n   public void testGetFirstThrowableOfTypeFail() {\n      TimeoutException aex = createMock(TimeoutException.class);\n      Message message = new Message(ImmutableList.of(), \"test\", aex);\n      ProvisionException pex = new ProvisionException(ImmutableSet.of(message));\n      assertEquals(getFirstThrowableOfType(pex, AuthorizationException.class), null);\n   }\n\n   public void testGetFirstThrowableOfTypeWhenCauseIsNull() {\n      Message message = new Message(ImmutableList.of(), \"test\", null);\n      ProvisionException pex = new ProvisionException(ImmutableSet.of(message));\n      assertEquals(getFirstThrowableOfType(pex, AuthorizationException.class), null);\n   }\n\n   public void testGetCauseCreation() {\n      AuthorizationException aex = createMock(AuthorizationException.class);\n      Message message = new Message(ImmutableList.of(), \"test\", aex);\n      CreationException pex = new CreationException(ImmutableSet.of(message));\n      assertEquals(getFirstThrowableOfType(pex, AuthorizationException.class), aex);\n   }\n\n   public void testGetFirstThrowableOfTypeInnerCreation() {\n      AuthorizationException aex = createMock(AuthorizationException.class);\n      Message message = new Message(ImmutableList.of(), \"test\", aex);\n      CreationException pex = new CreationException(ImmutableSet.of(message));\n      assertEquals(getFirstThrowableOfType(pex, AuthorizationException.class), aex);\n   }\n\n   public void testGetFirstThrowableOfTypeFailCreation() {\n      TimeoutException aex = createMock(TimeoutException.class);\n      Message message = new Message(ImmutableList.of(), \"test\", aex);\n      CreationException pex = new CreationException(ImmutableSet.of(message));\n      assertEquals(getFirstThrowableOfType(pex, AuthorizationException.class), null);\n   }\n\n   public void testGetFirstThrowableOfTypeWhenCauseIsNullCreation() {\n      Message message = new Message(ImmutableList.of(), \"test\", null);\n      CreationException pex = new CreationException(ImmutableSet.of(message));\n      assertEquals(getFirstThrowableOfType(pex, AuthorizationException.class), null);\n   }\n\n   public void testGetCauseTransformParallel() {\n      Exception aex = createMock(AuthorizationException.class);\n      TransformParallelException pex = new TransformParallelException(ImmutableMap.<Object, Future<?>> of(),\n            ImmutableMap.of(\"bad\", aex), \"test\");\n      assertEquals(getFirstThrowableOfType(pex, AuthorizationException.class), aex);\n   }\n\n   public void testGetFirstThrowableOfTypeInnerTransformParallel() {\n      Exception aex = createMock(AuthorizationException.class);\n      TransformParallelException pex = new TransformParallelException(ImmutableMap.<Object, Future<?>> of(),\n            ImmutableMap.of(\"bad\", (Exception) new ExecutionException(aex)), \"test\");\n      assertEquals(getFirstThrowableOfType(pex, AuthorizationException.class), aex);\n   }\n\n   public void testGetFirstThrowableOfTypeOuterTransformParallel() {\n      Exception aex = createMock(AuthorizationException.class);\n      TransformParallelException pex = new TransformParallelException(ImmutableMap.<Object, Future<?>> of(),\n            ImmutableMap.of(\"bad\", aex), \"test\");\n      assertEquals(getFirstThrowableOfType(new ExecutionException(pex), AuthorizationException.class), aex);\n   }\n\n   public void testGetFirstThrowableOfTypeFailTransformParallel() {\n      Exception aex = createMock(TimeoutException.class);\n      TransformParallelException pex = new TransformParallelException(ImmutableMap.<Object, Future<?>> of(),\n            ImmutableMap.of(\"bad\", aex), \"test\");\n      assertEquals(getFirstThrowableOfType(pex, AuthorizationException.class), null);\n   }\n\n   @Test(expectedExceptions = TestException.class)\n   public void testPropagateExceptionThatsInList() throws Throwable {\n      Exception e = new TestException();\n      propagateIfPossible(e, ImmutableSet.<TypeToken<? extends Throwable>> of(typeToken(TestException.class)));\n   }\n\n   @Test(expectedExceptions = TestException.class)\n   public void testPropagateWrappedExceptionThatsInList() throws Throwable {\n      Exception e = new TestException();\n      propagateIfPossible(new RuntimeException(e),\n            ImmutableSet.<TypeToken<? extends Throwable>> of(typeToken(TestException.class)));\n   }\n\n   public void testPropagateIfPossibleDoesnThrowExceptionNotInList() throws Throwable {\n      Exception e = new TestException();\n      propagateIfPossible(e, ImmutableSet.<TypeToken<? extends Throwable>> of());\n   }\n\n   @Test(expectedExceptions = IllegalStateException.class)\n   public void testPropagateStandardExceptionIllegalStateException() throws Throwable {\n      Exception e = new IllegalStateException();\n      propagateIfPossible(new RuntimeException(e), ImmutableSet.<TypeToken<? extends Throwable>> of());\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testPropagateStandardExceptionIllegalArgumentException() throws Throwable {\n      Exception e = new IllegalArgumentException();\n      propagateIfPossible(new RuntimeException(e), ImmutableSet.<TypeToken<? extends Throwable>> of());\n   }\n\n   @Test(expectedExceptions = UnsupportedOperationException.class)\n   public void testPropagateStandardExceptionUnsupportedOperationException() throws Throwable {\n      Exception e = new UnsupportedOperationException();\n      propagateIfPossible(new RuntimeException(e), ImmutableSet.<TypeToken<? extends Throwable>> of());\n   }\n\n   @Test(expectedExceptions = AssertionError.class)\n   public void testPropagateStandardExceptionAssertionError() throws Throwable {\n      AssertionError e = new AssertionError();\n      propagateIfPossible(new RuntimeException(e), ImmutableSet.<TypeToken<? extends Throwable>> of());\n   }\n\n   @Test(expectedExceptions = AuthorizationException.class)\n   public void testPropagateStandardExceptionAuthorizationException() throws Throwable {\n      Exception e = new AuthorizationException();\n      propagateIfPossible(new RuntimeException(e), ImmutableSet.<TypeToken<? extends Throwable>> of());\n   }\n\n   @Test(expectedExceptions = AuthorizationException.class)\n   public void testPropagateProvisionExceptionAuthorizationException() throws Throwable {\n      Exception e = new AuthorizationException();\n      propagateIfPossible(\n            new ProvisionException(ImmutableSet.of(new Message(ImmutableList.of(), \"Error in custom provider\", e))),\n            ImmutableSet.<TypeToken<? extends Throwable>> of());\n   }\n\n   @Test(expectedExceptions = AuthorizationException.class)\n   public void testPropagateCreationExceptionAuthorizationException() throws Throwable {\n      Exception e = new AuthorizationException();\n      propagateIfPossible(\n            new CreationException(ImmutableSet.of(new Message(ImmutableList.of(), \"Error in custom provider\", e))),\n            ImmutableSet.<TypeToken<? extends Throwable>> of());\n   }\n\n   @Test(expectedExceptions = InsufficientResourcesException.class)\n   public void testPropagateStandardExceptionInsufficientResourcesException() throws Throwable {\n      Exception e = new InsufficientResourcesException();\n      propagateIfPossible(new RuntimeException(e), ImmutableSet.<TypeToken<? extends Throwable>> of());\n   }\n\n   @Test(expectedExceptions = ResourceNotFoundException.class)\n   public void testPropagateStandardExceptionResourceNotFoundException() throws Throwable {\n      Exception e = new ResourceNotFoundException();\n      propagateIfPossible(new RuntimeException(e), ImmutableSet.<TypeToken<? extends Throwable>> of());\n   }\n\n   @Test(expectedExceptions = IllegalStateException.class)\n   public void testPropagateStandardExceptionIllegalStateExceptionNestedInHttpResponseException() throws Throwable {\n      Exception e = new IllegalStateException();\n      propagateIfPossible(new HttpResponseException(\"goo\", createNiceMock(HttpCommand.class), null, e),\n            ImmutableSet.<TypeToken<? extends Throwable>> of());\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testPropagateStandardExceptionIllegalArgumentExceptionNestedInHttpResponseException() throws Throwable {\n      Exception e = new IllegalArgumentException();\n      propagateIfPossible(new HttpResponseException(\"goo\", createNiceMock(HttpCommand.class), null, e),\n            ImmutableSet.<TypeToken<? extends Throwable>> of());\n   }\n\n   @Test(expectedExceptions = UnsupportedOperationException.class)\n   public void testPropagateStandardExceptionUnsupportedOperationExceptionNestedInHttpResponseException()\n         throws Throwable {\n      Exception e = new UnsupportedOperationException();\n      propagateIfPossible(new HttpResponseException(\"goo\", createNiceMock(HttpCommand.class), null, e),\n            ImmutableSet.<TypeToken<? extends Throwable>> of());\n   }\n\n   @Test(expectedExceptions = AuthorizationException.class)\n   public void testPropagateStandardExceptionAuthorizationExceptionNestedInHttpResponseException() throws Throwable {\n      Exception e = new AuthorizationException();\n      propagateIfPossible(new HttpResponseException(\"goo\", createNiceMock(HttpCommand.class), null, e),\n            ImmutableSet.<TypeToken<? extends Throwable>> of());\n   }\n\n   @Test(expectedExceptions = ResourceNotFoundException.class)\n   public void testPropagateStandardExceptionResourceNotFoundExceptionNestedInHttpResponseException() throws Throwable {\n      Exception e = new ResourceNotFoundException();\n      propagateIfPossible(new HttpResponseException(\"goo\", createNiceMock(HttpCommand.class), null, e),\n            ImmutableSet.<TypeToken<? extends Throwable>> of());\n   }\n\n   @Test(expectedExceptions = HttpResponseException.class)\n   public void testPropagateStandardExceptionHttpResponseException() throws Throwable {\n      Exception e = new HttpResponseException(\"goo\", createNiceMock(HttpCommand.class), null);\n      propagateIfPossible(new RuntimeException(e), ImmutableSet.<TypeToken<? extends Throwable>> of());\n   }\n\n   static class TestException extends Exception {\n      private static final long serialVersionUID = 1L;\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/utils/TestUtils.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.utils;\n\nimport java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.Random;\nimport java.util.zip.GZIPOutputStream;\n\nimport com.google.common.io.ByteSource;\n\n/**\n * Utility class for test\n */\npublic class TestUtils {\n\n   public static final Object[][] NO_INVOCATIONS = new Object[0][0];\n   public static final Object[][] SINGLE_NO_ARG_INVOCATION = { new Object[0] };\n\n   public static boolean isJava6() {\n      return System.getProperty(\"java.version\", \"\").contains(\"1.6.\");\n   }\n\n   public static ByteSource randomByteSource() {\n      return randomByteSource(0);\n   }\n\n   public static ByteSource randomByteSource(long seed) {\n      return new RandomByteSource(seed);\n   }\n\n   private static class RandomByteSource extends ByteSource {\n      private final long seed;\n\n      RandomByteSource(long seed) {\n         this.seed = seed;\n      }\n\n      @Override\n      public InputStream openStream() {\n         return new RandomInputStream(seed);\n      }\n   }\n\n   private static class RandomInputStream extends InputStream {\n      private final Random random;\n      private boolean closed = false;\n\n      RandomInputStream(long seed) {\n         this.random = new Random(seed);\n      }\n\n      @Override\n      public synchronized int read() throws IOException {\n         if (closed) {\n            throw new IOException(\"Stream already closed\");\n         }\n         // return value between 0 and 255\n         return random.nextInt() & 0xff;\n      }\n\n      @Override\n      public synchronized int read(byte[] b) throws IOException {\n         return read(b, 0, b.length);\n      }\n\n      @Override\n      public synchronized int read(byte[] b, int off, int len) throws IOException {\n         for (int i = 0; i < len; ++i) {\n            b[off + i] = (byte) read();\n         }\n         return len;\n      }\n\n      @Override\n      public void close() throws IOException {\n         super.close();\n         closed = true;\n      }\n   }\n\n   public static byte[] gzip(byte[] data) throws IOException {\n      ByteArrayOutputStream baos = new ByteArrayOutputStream(data.length);\n      GZIPOutputStream gos = new GZIPOutputStream(baos);\n      gos.write(data, 0, data.length);\n      gos.finish();\n      return baos.toByteArray();\n   }\n}\n"
  },
  {
    "path": "core/src/test/java/org/jclouds/utils/TestUtilsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.utils;\n\nimport static org.assertj.core.api.Assertions.assertThat;\n\nimport java.io.InputStream;\n\nimport com.google.common.io.ByteSource;\nimport com.google.common.io.ByteStreams;\nimport org.jclouds.util.Closeables2;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"TestUtilsTest\")\npublic class TestUtilsTest {\n   @Test\n   public void testRandomByteSource() throws Exception {\n      ByteSource byteSource = TestUtils.randomByteSource();\n      InputStream is1 = null;\n      InputStream is2 = null;\n      try {\n         is1 = byteSource.openStream();\n         is2 = byteSource.openStream();\n         byte[] bytes = new byte[16];\n         ByteStreams.readFully(is1, bytes);\n         for (byte b : bytes) {\n            assertThat(b).isEqualTo((byte) is2.read());\n         }\n      } finally {\n         Closeables2.closeQuietly(is1);\n         Closeables2.closeQuietly(is2);\n      }\n   }\n}\n"
  },
  {
    "path": "core/src/test/resources/META-INF/maven/org.apache.jclouds/jclouds-core/pom.properties",
    "content": "#\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\n#\n\n# Dummy pom.properties file for testing\nversion=0.0.0-SNAPSHOT\ngroupId=org.apache.jclouds\nartifactId=jclouds-core\n"
  },
  {
    "path": "core/src/test/resources/test",
    "content": "-----BEGIN RSA PRIVATE KEY-----\nMIIEogIBAAKCAQEAnJvA40x4OK+9nVYTS0N916VMjC6/qYe/IuDUdy6hdW1wz9IO\nMTS3CPxlE0KuoNO1/M7O7yFso6IragTxUkNqJ2mUOqV0Bf0CEkUIKzeYRGfpx+QM\nPorHbLQXjjFinWKwibZuv6lqtvqwcsrjW7bpWsz9x+0qqKM0o0UhjUMhTRqZoYxo\nE2zUH7WA8JRatE/bQkjv/nWBfI+/WzSDhJn7AjIql0Nd4Q+bxohIJEZu8yDw1H6T\npd7mw83m6UYBk4eZH79r3d2euuQMUKIunyLbw7vNJJ8qYTJQuNYIiJuWKnzzjxuJ\nUfumhdOqfjSobznhAjTLUbA/btZCiQ/TasV4cQIDAQABAoIBAEeOn1b8ZN455qDS\naKR2JTT4cX6ICckznnEYW9xNMTcPl4FN0HBJTuzLLn/bcyFHOxtVf5YiJpqqCb46\nne1hokp54mHdoaLu1Rh19GKS139CH77XA4U8Mh0IOM8e35lcM5/o/LeUeI89Aoyh\nCbupWvzDN543TsuZLv7/InKCXt/0dXhAQpq3UiBT63EITQbyom5fSPnMzqM3F8jD\nE9ZqkX4JsnTPC7FQDIpPCaKjG9YCZqoljz+1ssli3mN66V/JKefcCiVoubalmmT2\ndpvmRtFaKvhAmkWYakYybYg8aDi3YygAHSU1bzxlY4TNiQgPdnTTDAPyeqqVrE1D\nChi+18UCgYEAzlk7c+tFwxZ3ryycOe0loFudUNE5rviHhPgbOHoSTooXh0Hq1Vrb\n2ic+4FbRpoPHLpcLM9LX+arezUdeFBZ8qunjUG6MbUhAeAm/3cfMk+nZg3Skpg8+\nC1D3hxGX4qdhURHvc2QUH7VIUWbucvPgtL8pt1z5Su/EE1Cb2XVsvu8CgYEAwkqZ\n4vTZxI0XqJo6BfUnKGJEDC8xeWr10ELPdXLTCuNDpLSYNedQAxZi9XzvbnbWZ/MF\nZ7IWkzzyAjsX0gpI56cxxtas/chxUboBlUo6ZW8QcPDcU2sKJi318wzElqqvRMNM\nInfLf8nuPC9hyhe49/lFBBSZJeIo396DuqnTPp8CgYBO4NVVLm5wcLo3gDoH+psT\nfXHZXuFJ/T7wmVbuc9tjom30CkKWZDD+Z1olr4pcuKr/KEXj/YkJq0OX/Nv9mcr2\nGooGSPvtGl1qhW+Oe728HPxEv+XghJsXAFBelV8WCR2uO8jotyzqIgYO9+XWk1sm\nPJzZtvSkrJqrN3kb20NCiQKBgDDVP0hj8jgMnl2qJdtJesYTrLbDRdQWpiHqKOqE\nKbca1+2V1ov1z453GfhJpoRFKi6GTl15zWLEdq9I2vvXyesvgrtPSbufnZvE/JDh\nTzwfZip832O4C5z9AExOcTrNO7A0xfYD1goQXuiRoCqDO+JXrJkR9EwpQ8zAyKsp\n9AZRAoGAGq3TYpmlI5oucEURHKsHOrIBirHFD+RaXMynxzgwkRnt6Z5Mg10I7Ddr\nLiGK8/IrF8bg1F7weLVmj93zjvhQTh5yvb1jwVdFGXM2rbR7/P7F6n2f7xM4+lmv\nTq7E9Sv8UVuraAwJihlKCuBtpZM1t2JhcuNjXAZngj7R9j5HIZg=\n-----END RSA PRIVATE KEY-----\n"
  },
  {
    "path": "core/src/test/resources/test.pub",
    "content": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCcm8DjTHg4r72dVhNLQ33XpUyMLr+ph78i4NR3LqF1bXDP0g4xNLcI/GUTQq6g07X8zs7vIWyjoitqBPFSQ2onaZQ6pXQF/QISRQgrN5hEZ+nH5Aw+isdstBeOMWKdYrCJtm6/qWq2+rByyuNbtulazP3H7SqoozSjRSGNQyFNGpmhjGgTbNQftYDwlFq0T9tCSO/+dYF8j79bNIOEmfsCMiqXQ13hD5vGiEgkRm7zIPDUfpOl3ubDzebpRgGTh5kfv2vd3Z665AxQoi6fItvDu80knyphMlC41giIm5YqfPOPG4lR+6aF06p+NKhvOeECNMtRsD9u1kKJD9NqxXhx\n"
  },
  {
    "path": "drivers/apachehc/README.txt",
    "content": "#\n# A driver to use the Apache HTTP Components Client (http://hc.apache.org/) \n# as an encryption library in jclouds.\n#\n# TODO: Usage example.\n"
  },
  {
    "path": "drivers/apachehc/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.http.apachehc.*;version=\"${project.version}\";-noimport:=true"
  },
  {
    "path": "drivers/apachehc/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.driver</groupId>\n  <artifactId>jclouds-apachehc</artifactId>\n  <name>jclouds Apache Http Components Client</name>\n  <description>Apache HttpComponents client</description>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.httpcomponents</groupId>\n      <artifactId>httpclient</artifactId>\n      <version>4.5.14</version>\n      <scope>compile</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.eclipse.jetty</groupId>\n      <artifactId>jetty-security</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.squareup.okhttp3</groupId>\n      <artifactId>mockwebserver</artifactId>\n      <scope>test</scope>\n    </dependency>\n  </dependencies>\n\n</project>\n"
  },
  {
    "path": "drivers/apachehc/src/main/java/org/jclouds/http/apachehc/ApacheHCHttpCommandExecutorService.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.apachehc;\n\nimport static com.google.common.io.BaseEncoding.base64;\nimport static org.jclouds.Constants.PROPERTY_IDEMPOTENT_METHODS;\nimport static org.jclouds.Constants.PROPERTY_USER_AGENT;\nimport static org.jclouds.http.HttpUtils.filterOutContentHeaders;\n\nimport java.io.IOException;\nimport java.net.URI;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\n\nimport org.apache.http.Header;\nimport org.apache.http.HttpHeaders;\nimport org.apache.http.HttpHost;\nimport org.apache.http.client.ClientProtocolException;\nimport org.apache.http.client.HttpClient;\nimport org.apache.http.client.methods.HttpUriRequest;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpUtils;\nimport org.jclouds.http.IOExceptionRetryHandler;\nimport org.jclouds.http.handlers.DelegatingErrorHandler;\nimport org.jclouds.http.handlers.DelegatingRetryHandler;\nimport org.jclouds.http.internal.BaseHttpCommandExecutorService;\nimport org.jclouds.http.internal.HttpWire;\nimport org.jclouds.io.ContentMetadataCodec;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\n\nimport com.google.common.collect.LinkedHashMultimap;\nimport com.google.common.collect.Multimap;\n\n/**\n * Simple implementation of a {@link HttpCommandExecutorService}, Apache Components HttpClient 4.x.\n */\npublic class ApacheHCHttpCommandExecutorService extends BaseHttpCommandExecutorService<HttpUriRequest> {\n   private final HttpClient client;\n   private final ApacheHCUtils apacheHCUtils;\n   private final String userAgent;\n\n   @Inject\n   ApacheHCHttpCommandExecutorService(HttpUtils utils, ContentMetadataCodec contentMetadataCodec,\n         DelegatingRetryHandler retryHandler, IOExceptionRetryHandler ioRetryHandler,\n         DelegatingErrorHandler errorHandler, HttpWire wire, HttpClient client,\n         @Named(PROPERTY_IDEMPOTENT_METHODS) String idempotentMethods,\n         @Named(PROPERTY_USER_AGENT) String userAgent) {\n      super(utils, contentMetadataCodec, retryHandler, ioRetryHandler, errorHandler, wire, idempotentMethods);\n      this.client = client;\n      this.apacheHCUtils = new ApacheHCUtils(contentMetadataCodec);\n      this.userAgent = userAgent;\n   }\n\n   @Override\n   protected HttpUriRequest convert(HttpRequest request) throws IOException {\n      HttpUriRequest returnVal = apacheHCUtils.convertToApacheRequest(request);\n      if (request.getPayload() != null && request.getPayload().getContentMetadata().getContentMD5() != null) {\n         String md5 = base64().encode(request.getPayload().getContentMetadata().getContentMD5AsHashCode().asBytes());\n         returnVal.addHeader(\"Content-MD5\", md5);\n      }\n\n      if (!returnVal.containsHeader(HttpHeaders.USER_AGENT)) {\n         returnVal.addHeader(HttpHeaders.USER_AGENT, userAgent);\n      }\n\n      return returnVal;\n   }\n\n   @Override\n   protected HttpResponse invoke(HttpUriRequest nativeRequest) throws IOException {\n      org.apache.http.HttpResponse apacheResponse = executeRequest(nativeRequest);\n\n      Payload payload = null;\n      if (apacheResponse.getEntity() != null) {\n         try {\n            payload = Payloads.newInputStreamPayload(apacheResponse.getEntity().getContent());\n            if (apacheResponse.getEntity().getContentLength() >= 0)\n               payload.getContentMetadata().setContentLength(apacheResponse.getEntity().getContentLength());\n            if (apacheResponse.getEntity().getContentType() != null)\n               payload.getContentMetadata().setContentType(apacheResponse.getEntity().getContentType().getValue());\n         } catch (IOException e) {\n            logger.warn(e, \"couldn't receive payload for request: %s\", nativeRequest.getRequestLine());\n            throw e;\n         }\n      } else {\n         // still create a payload object on no entity responses (ex: to HEAD requests) as this is apparently where JClouds is\n         // exclusively looking for the content metadata (in order to fill in the BlobMetadata with correct size) \n         payload = Payloads.newStringPayload(\"\");\n      }\n      \n      Multimap<String, String> headers = LinkedHashMultimap.create();\n      for (Header header : apacheResponse.getAllHeaders()) {\n         headers.put(header.getName(), header.getValue());\n      }\n      \n      contentMetadataCodec.fromHeaders(payload.getContentMetadata(), headers);\n      headers = filterOutContentHeaders(headers);\n      \n      return HttpResponse.builder().statusCode(apacheResponse.getStatusLine().getStatusCode())\n                                   .message(apacheResponse.getStatusLine().getReasonPhrase())\n                                   .payload(payload)\n                                   .headers(headers).build();\n   }\n\n   private org.apache.http.HttpResponse executeRequest(HttpUriRequest nativeRequest) throws IOException,\n         ClientProtocolException {\n      URI endpoint = URI.create(nativeRequest.getRequestLine().getUri());\n      HttpHost host = new HttpHost(endpoint.getHost(), endpoint.getPort(), endpoint.getScheme());\n      org.apache.http.HttpResponse nativeResponse = client.execute(host, nativeRequest);\n      return nativeResponse;\n   }\n\n   @Override\n   protected void cleanup(HttpUriRequest nativeResponse) {\n      // No cleanup necessary\n   }\n}\n"
  },
  {
    "path": "drivers/apachehc/src/main/java/org/jclouds/http/apachehc/ApacheHCUtils.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.apachehc;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.UnsupportedEncodingException;\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Singleton;\nimport jakarta.ws.rs.HttpMethod;\n\nimport org.apache.http.HttpEntity;\nimport org.apache.http.HttpEntityEnclosingRequest;\nimport org.apache.http.client.methods.HttpDelete;\nimport org.apache.http.client.methods.HttpEntityEnclosingRequestBase;\nimport org.apache.http.client.methods.HttpGet;\nimport org.apache.http.client.methods.HttpHead;\nimport org.apache.http.client.methods.HttpPost;\nimport org.apache.http.client.methods.HttpPut;\nimport org.apache.http.client.methods.HttpRequestBase;\nimport org.apache.http.client.methods.HttpUriRequest;\nimport org.apache.http.entity.ByteArrayEntity;\nimport org.apache.http.entity.FileEntity;\nimport org.apache.http.entity.InputStreamEntity;\nimport org.apache.http.entity.StringEntity;\nimport org.apache.http.params.CoreProtocolPNames;\nimport org.apache.http.util.EntityUtils;\nimport org.jclouds.JcloudsVersion;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.io.ContentMetadataCodec;\nimport org.jclouds.io.MutableContentMetadata;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.payloads.BasePayload;\nimport org.jclouds.io.payloads.ByteArrayPayload;\nimport org.jclouds.io.payloads.DelegatingPayload;\nimport org.jclouds.io.payloads.FilePayload;\nimport org.jclouds.io.payloads.StringPayload;\n\nimport com.google.common.base.Throwables;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.net.HttpHeaders;\n\n@Singleton\npublic class ApacheHCUtils {\n   //TODO: look up httpclient version\n   public static final String USER_AGENT = String.format(\"jclouds/%s httpclient/%s\", JcloudsVersion.get(), \"4.1.1\");\n   \n   private final ContentMetadataCodec contentMetadataCodec;\n\n   public ApacheHCUtils(ContentMetadataCodec contentMetadataCodec) {\n      this.contentMetadataCodec = contentMetadataCodec;\n   }\n   \n   public HttpUriRequest convertToApacheRequest(HttpRequest request) {\n      HttpUriRequest apacheRequest;\n      if (request.getMethod().equals(HttpMethod.HEAD)) {\n         apacheRequest = new HttpHead(request.getEndpoint());\n      } else if (request.getMethod().equals(HttpMethod.GET)) {\n         apacheRequest = new HttpGet(request.getEndpoint());\n      } else if (request.getMethod().equals(HttpMethod.DELETE)) {\n         apacheRequest = new HttpDelete(request.getEndpoint());\n      } else if (request.getMethod().equals(HttpMethod.PUT)) {\n         apacheRequest = new HttpPut(request.getEndpoint());\n         apacheRequest.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true);\n      } else if (request.getMethod().equals(HttpMethod.POST)) {\n         apacheRequest = new HttpPost(request.getEndpoint());\n      } else {\n         final String method = request.getMethod();\n         if (request.getPayload() != null)\n            apacheRequest = new HttpEntityEnclosingRequestBase() {\n\n               @Override\n               public String getMethod() {\n                  return method;\n               }\n\n            };\n         else\n            apacheRequest = new HttpRequestBase() {\n\n               @Override\n               public String getMethod() {\n                  return method;\n               }\n\n            };\n         HttpRequestBase.class.cast(apacheRequest).setURI(request.getEndpoint());\n      }\n      Payload payload = request.getPayload();\n\n      // Since we may remove headers, ensure they are added to the apache\n      // request after this block\n      if (apacheRequest instanceof HttpEntityEnclosingRequest) {\n         if (payload != null) {\n            addEntityForContent(HttpEntityEnclosingRequest.class.cast(apacheRequest), payload);\n         }\n      } else {\n         apacheRequest.addHeader(HttpHeaders.CONTENT_LENGTH, \"0\");\n      }\n\n      for (Map.Entry<String, String> entry : request.getHeaders().entries()) {\n         String header = entry.getKey();\n         // apache automatically tries to add content length header\n         if (!header.equals(HttpHeaders.CONTENT_LENGTH))\n            apacheRequest.addHeader(header, entry.getValue());\n      }\n      apacheRequest.addHeader(HttpHeaders.USER_AGENT, USER_AGENT);\n      return apacheRequest;\n   }\n\n   public void addEntityForContent(HttpEntityEnclosingRequest apacheRequest, Payload payload) {\n      payload = payload instanceof DelegatingPayload ? DelegatingPayload.class.cast(payload).getDelegate() : payload;\n      if (payload instanceof StringPayload) {\n         StringEntity nStringEntity = null;\n         try {\n            nStringEntity = new StringEntity((String) payload.getRawContent());\n         } catch (UnsupportedEncodingException e) {\n            throw new UnsupportedOperationException(\"Encoding not supported\", e);\n         }\n         nStringEntity.setContentType(payload.getContentMetadata().getContentType());\n         apacheRequest.setEntity(nStringEntity);\n      } else if (payload instanceof FilePayload) {\n         apacheRequest.setEntity(new FileEntity((File) payload.getRawContent(), payload.getContentMetadata()\n               .getContentType()));\n      } else if (payload instanceof ByteArrayPayload) {\n         ByteArrayEntity Entity = new ByteArrayEntity((byte[]) payload.getRawContent());\n         Entity.setContentType(payload.getContentMetadata().getContentType());\n         apacheRequest.setEntity(Entity);\n      } else {\n         InputStream inputStream = payload.getInput();\n         if (payload.getContentMetadata().getContentLength() == null)\n            throw new IllegalArgumentException(\"you must specify size when content is an InputStream\");\n         InputStreamEntity entity = new InputStreamEntity(inputStream, payload.getContentMetadata().getContentLength());\n         entity.setContentType(payload.getContentMetadata().getContentType());\n         apacheRequest.setEntity(entity);\n      }\n      \n      // TODO Reproducing old behaviour exactly; ignoring Content-Type, Content-Length and Content-MD5\n      Set<String> desiredHeaders = ImmutableSet.of(\"Content-Disposition\", \"Content-Encoding\", \"Content-Language\", \"Expires\");\n      MutableContentMetadata md = payload.getContentMetadata();\n      for (Map.Entry<String, String> entry : contentMetadataCodec.toHeaders(md).entries()) {\n         if (desiredHeaders.contains(entry.getKey())) {\n            apacheRequest.addHeader(entry.getKey(), entry.getValue());\n         }\n      }\n      \n      assert apacheRequest.getEntity() != null;\n   }\n\n   public static class HttpEntityPayload extends BasePayload<HttpEntity> {\n\n      HttpEntityPayload(HttpEntity content) {\n         super(content);\n         getContentMetadata().setContentType(content.getContentType().getValue());\n         getContentMetadata().setContentLength(content.getContentLength());\n      }\n\n      @Override\n      public InputStream openStream() throws IOException {\n         try {\n            return content.getContent();\n         } catch (IllegalStateException e) {\n            throw Throwables.propagate(e);\n         }\n      }\n\n      @Override\n      public boolean isRepeatable() {\n         return content.isRepeatable();\n      }\n\n      @Override\n      public void release() {\n         try {\n            EntityUtils.consume(content);\n         } catch (IOException e) {\n         }\n      }\n   }\n\n}\n"
  },
  {
    "path": "drivers/apachehc/src/main/java/org/jclouds/http/apachehc/config/ApacheHCHttpCommandExecutorServiceModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.apachehc.config;\n\nimport java.io.Closeable;\nimport java.io.IOException;\nimport java.net.ProxySelector;\nimport java.security.KeyManagementException;\nimport java.security.NoSuchAlgorithmException;\n\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\nimport javax.net.ssl.SSLContext;\n\nimport org.apache.http.HttpVersion;\nimport org.apache.http.client.HttpClient;\nimport org.apache.http.conn.ClientConnectionManager;\nimport org.apache.http.conn.params.ConnManagerParams;\nimport org.apache.http.conn.params.ConnPerRoute;\nimport org.apache.http.conn.params.ConnPerRouteBean;\nimport org.apache.http.conn.scheme.PlainSocketFactory;\nimport org.apache.http.conn.scheme.Scheme;\nimport org.apache.http.conn.scheme.SchemeRegistry;\nimport org.apache.http.conn.ssl.SSLSocketFactory;\nimport org.apache.http.conn.ssl.X509HostnameVerifier;\nimport org.apache.http.impl.client.DefaultHttpClient;\nimport org.apache.http.impl.conn.ProxySelectorRoutePlanner;\nimport org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;\nimport org.apache.http.params.BasicHttpParams;\nimport org.apache.http.params.CoreConnectionPNames;\nimport org.apache.http.params.CoreProtocolPNames;\nimport org.apache.http.params.HttpParams;\nimport org.apache.http.params.HttpProtocolParams;\nimport org.jclouds.http.HttpCommandExecutorService;\nimport org.jclouds.http.HttpUtils;\nimport org.jclouds.http.apachehc.ApacheHCHttpCommandExecutorService;\nimport org.jclouds.http.config.ConfiguresHttpCommandExecutorService;\nimport org.jclouds.http.config.SSLModule;\nimport org.jclouds.lifecycle.Closer;\nimport org.jclouds.proxy.ProxyConfig;\n\nimport com.google.common.base.Supplier;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Provides;\nimport com.google.inject.Scopes;\n\n/**\n * Configures {@link ApacheHCHttpCommandExecutorService}.\n * \n * Note that this uses threads\n */\n@ConfiguresHttpCommandExecutorService\npublic class ApacheHCHttpCommandExecutorServiceModule extends AbstractModule {\n\n   @Override\n   protected void configure() {\n      install(new SSLModule());\n      bindClient();\n   }\n\n   @Singleton\n   @Provides\n   final HttpParams newBasicHttpParams(HttpUtils utils) {\n      BasicHttpParams params = new BasicHttpParams();\n\n      params.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024).setBooleanParameter(\n               CoreConnectionPNames.STALE_CONNECTION_CHECK, true).setBooleanParameter(CoreConnectionPNames.TCP_NODELAY,\n               true).setParameter(CoreProtocolPNames.ORIGIN_SERVER, \"jclouds/1.0\");\n\n      if (utils.getConnectionTimeout() > 0) {\n         params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, utils.getConnectionTimeout());\n      }\n\n      if (utils.getSocketOpenTimeout() > 0) {\n         params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, utils.getSocketOpenTimeout());\n      }\n\n      if (utils.getMaxConnections() > 0)\n         ConnManagerParams.setMaxTotalConnections(params, utils.getMaxConnections());\n\n      if (utils.getMaxConnectionsPerHost() > 0) {\n         ConnPerRoute connectionsPerRoute = new ConnPerRouteBean(utils.getMaxConnectionsPerHost());\n         ConnManagerParams.setMaxConnectionsPerRoute(params, connectionsPerRoute);\n      }\n      HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);\n      return params;\n   }\n\n   @Singleton\n   @Provides\n   final X509HostnameVerifier newHostnameVerifier(HttpUtils utils) {\n      return utils.relaxHostname() ? SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER\n               : SSLSocketFactory.STRICT_HOSTNAME_VERIFIER;\n   }\n\n   @Singleton\n   @Provides\n   final SSLContext newSSLContext(HttpUtils utils, @Named(\"untrusted\") Supplier<SSLContext> untrustedSSLContextProvider)\n            throws NoSuchAlgorithmException, KeyManagementException {\n      if (utils.trustAllCerts())\n         return untrustedSSLContextProvider.get();\n      SSLContext context = SSLContext.getInstance(\"TLS\");\n\n      context.init(null, null, null);\n      return context;\n   }\n\n   @Singleton\n   @Provides\n   final ClientConnectionManager newClientConnectionManager(HttpParams params, X509HostnameVerifier verifier,\n            SSLContext context, Closer closer) throws NoSuchAlgorithmException, KeyManagementException {\n\n      SchemeRegistry schemeRegistry = new SchemeRegistry();\n      schemeRegistry.register(new Scheme(\"http\", PlainSocketFactory.getSocketFactory(), 80));\n\n      SSLSocketFactory sf = new SSLSocketFactory(context);\n      sf.setHostnameVerifier(verifier);\n      schemeRegistry.register(new Scheme(\"https\", sf, 443));\n\n      final ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);\n      closer.addToClose(new Closeable() {\n         @Override\n         public void close() throws IOException {\n            cm.shutdown();\n         }\n      });\n      return cm;\n   }\n\n   @Provides\n   @Singleton\n   final HttpClient newDefaultHttpClient(ProxyConfig config, HttpParams params, ClientConnectionManager cm) {\n      DefaultHttpClient client = new DefaultHttpClient(cm, params);\n      if (config.useSystem()) {\n         ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(client.getConnectionManager()\n                  .getSchemeRegistry(), ProxySelector.getDefault());\n         client.setRoutePlanner(routePlanner);\n      }\n      return client;\n   }\n\n   protected void bindClient() {\n      bind(HttpCommandExecutorService.class).to(ApacheHCHttpCommandExecutorService.class).in(Scopes.SINGLETON);\n   }\n\n}\n"
  },
  {
    "path": "drivers/apachehc/src/test/java/org/jclouds/http/apachehc/ApacheHCHttpCommandExecutorServiceTestDisabled.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.apachehc;\n\nimport static org.jclouds.Constants.PROPERTY_CONNECTION_TIMEOUT;\nimport static org.jclouds.Constants.PROPERTY_MAX_CONNECTIONS_PER_CONTEXT;\nimport static org.jclouds.Constants.PROPERTY_MAX_CONNECTIONS_PER_HOST;\nimport static org.jclouds.Constants.PROPERTY_SO_TIMEOUT;\nimport static org.jclouds.Constants.PROPERTY_USER_THREADS;\n\nimport java.util.Properties;\n\nimport org.jclouds.http.BaseHttpCommandExecutorServiceIntegrationTest;\nimport org.jclouds.http.apachehc.config.ApacheHCHttpCommandExecutorServiceModule;\nimport org.testng.SkipException;\n\nimport com.google.inject.Module;\n\n/**\n * Tests the functionality of the {@link ApacheHCHttpCommandExecutorService}\n */\npublic class ApacheHCHttpCommandExecutorServiceTestDisabled extends BaseHttpCommandExecutorServiceIntegrationTest {\n\n   static {\n      System.setProperty(\"http.conn-manager.timeout\", 5000 + \"\");\n   }\n\n   protected Module createConnectionModule() {\n      return new ApacheHCHttpCommandExecutorServiceModule();\n   }\n\n   protected void addOverrideProperties(Properties props) {\n      props.setProperty(PROPERTY_MAX_CONNECTIONS_PER_CONTEXT, 20 + \"\");\n      props.setProperty(PROPERTY_MAX_CONNECTIONS_PER_HOST, 0 + \"\");\n      props.setProperty(PROPERTY_CONNECTION_TIMEOUT, 100 + \"\");\n      props.setProperty(PROPERTY_SO_TIMEOUT, 100 + \"\");\n      props.setProperty(PROPERTY_USER_THREADS, 0 + \"\");\n   }\n\n   @Override\n   public void testPostContentDisposition() {\n      throw new SkipException(\"http://code.google.com/p/jclouds/issues/detail?id=353\");\n   }\n\n   @Override\n   public void testPostContentEncoding() {\n      throw new SkipException(\"http://code.google.com/p/jclouds/issues/detail?id=353\");\n   }\n\n   @Override\n   public void testPostContentLanguage() {\n      throw new SkipException(\"http://code.google.com/p/jclouds/issues/detail?id=353\");\n   }\n\n}\n"
  },
  {
    "path": "drivers/bouncycastle/README.txt",
    "content": "#\n# A driver to use the Bouncy Castle Crypto API (http://www.bouncycastle.org/) \n# as an encryption library in jclouds.\n#\n# TODO: Usage example.\n"
  },
  {
    "path": "drivers/bouncycastle/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.encryption.bouncycastle.*;version=\"${project.version}\";-noimport:=true"
  },
  {
    "path": "drivers/bouncycastle/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.driver</groupId>\n  <artifactId>jclouds-bouncycastle</artifactId>\n  <name>jclouds bouncycastle EncryptionService Module</name>\n  <description>jclouds bouncycastle EncryptionService Module</description>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.bouncycastle</groupId>\n      <artifactId>bcprov-ext-jdk18on</artifactId>\n      <version>1.74</version>\n    </dependency>\n  </dependencies>\n\n</project>\n"
  },
  {
    "path": "drivers/bouncycastle/src/main/java/org/jclouds/encryption/bouncycastle/BouncyCastleCrypto.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.encryption.bouncycastle;\n\nimport java.security.NoSuchAlgorithmException;\nimport java.security.cert.CertificateException;\n\nimport javax.crypto.Cipher;\nimport javax.crypto.NoSuchPaddingException;\nimport jakarta.inject.Singleton;\n\nimport org.bouncycastle.jce.provider.BouncyCastleProvider;\nimport org.jclouds.encryption.internal.JCECrypto;\n\n@Singleton\npublic class BouncyCastleCrypto extends JCECrypto {\n\n   public BouncyCastleCrypto() throws NoSuchAlgorithmException, CertificateException {\n      super(new BouncyCastleProvider());\n   }\n\n   \n   /*******\n    * Override the standard implementation to convert the \"RSA\" algorithm to the String that bouncycastle expects.\n    * See org.jclouds.encryption.bouncycastle.BouncyCastlePasswordDecryptionTest for how this effects password decryption.\n    * \n    */\n   @Override\n   public Cipher cipher(String algorithm) throws NoSuchAlgorithmException, NoSuchPaddingException {\n      return super.cipher(\"RSA\".equals(algorithm) ? \"RSA/NONE/PKCS1Padding\" : algorithm);\n   }\n}\n"
  },
  {
    "path": "drivers/bouncycastle/src/main/java/org/jclouds/encryption/bouncycastle/config/BouncyCastleCryptoModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.encryption.bouncycastle.config;\n\nimport org.jclouds.crypto.Crypto;\nimport org.jclouds.encryption.bouncycastle.BouncyCastleCrypto;\n\nimport com.google.inject.AbstractModule;\n\n/**\n * Configures Crypto of type {@link BouncyCastleCrypto}\n */\npublic class BouncyCastleCryptoModule extends AbstractModule {\n\n   @Override\n   protected void configure() {\n      bind(Crypto.class).to(BouncyCastleCrypto.class);\n   }\n\n}\n"
  },
  {
    "path": "drivers/bouncycastle/src/test/java/org/jclouds/encryption/bouncycastle/BouncyCastleCryptoTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.encryption.bouncycastle;\n\nimport org.jclouds.crypto.Crypto;\nimport org.jclouds.encryption.bouncycastle.config.BouncyCastleCryptoModule;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\")\npublic class BouncyCastleCryptoTest  {\n\n   @BeforeTest\n   protected void createCrypto() {\n      Injector i = Guice.createInjector(new BouncyCastleCryptoModule());\n      Crypto crypto = i.getInstance(Crypto.class);\n      assert crypto instanceof BouncyCastleCrypto;\n   }\n}\n"
  },
  {
    "path": "drivers/bouncycastle/src/test/java/org/jclouds/encryption/bouncycastle/BouncyCastlePasswordDecryptionTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.encryption.bouncycastle;\n\nimport static com.google.common.io.BaseEncoding.base64;\nimport static org.testng.Assert.assertEquals;\n\nimport java.security.InvalidKeyException;\nimport java.security.KeyFactory;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.PrivateKey;\nimport java.security.spec.InvalidKeySpecException;\nimport java.security.spec.KeySpec;\n\nimport javax.crypto.BadPaddingException;\nimport javax.crypto.Cipher;\nimport javax.crypto.IllegalBlockSizeException;\nimport javax.crypto.NoSuchPaddingException;\n\nimport org.jclouds.crypto.Crypto;\nimport org.jclouds.crypto.Pems;\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.encryption.internal.JCECrypto;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Charsets;\n\npublic class BouncyCastlePasswordDecryptionTest {\n\n\tprivate static final String PRIVATE_KEY = \"-----BEGIN RSA PRIVATE KEY-----\\n\"\n\t\t\t+ \"MIIEowIBAAKCAQEAmN6GOSMnyGNWN19ETBh11tJB5OGs3Dps8kPWqAhF9RyL/mKwkW26vH+h/5Z5\\n\"\n\t\t\t+ \"cA5T80pK72kNnXObFaMHNoX3lavrc6yXF+8F3f1tlFX2Z+iB1pYXz1oBPqT6oOmc2XzcsJuJRakd\\n\"\n\t\t\t+ \"zwRwHDaqljpaW7+TZlxhMa1DmUkD/HHMxDCK8jbUIZDc6BZSrnj2uPwHwW737NRE4aC3fcu4LMwf\\n\"\n\t\t\t+ \"b2VotbNGNiAnNmrb/vtIIGkFE8NYEMpiz0WYTWX4eVKpJImv1PR6G1fMLSvudJs0ARObuLDvuonn\\n\"\n\t\t\t+ \"SCFFdkibrwMKYbHVGGh6FoY1Vy0sqI55dgQU1kSNouiDgOGxgx+TIwIDAQABAoIBAHCS/nk5QGS7\\n\"\n\t\t\t+ \"cpRYXa1EHhNSxx/MaUXM6MoH1x3q6cm1egqdlrWh/vAtdZkIsOkqQ/xX65Me493dcomegwNN6KOZ\\n\"\n\t\t\t+ \"9Uw7/xCq/sEZjga8vzaJ7IOgCGy0NVJyn/a70rv+zW5pO8/G2KLI+95rC3iSBFSoYd3xjcnNdIh/\\n\"\n\t\t\t+ \"UqYnD8oxYpKmf7418pMPsBrkglkFlbVBPiDXdpoSziqSN6uWQG4Yh0WR87aElhM9JJW50Hh6h7g5\\n\"\n\t\t\t+ \"OvgCBzS8G+KXCjqimk108+/ed5Nl6VhPAf79yCVZUueKBhaf2r0Kkyxg7M/Y+LJwcoUusIP7Cv7G\\n\"\n\t\t\t+ \"xyzG2vi21prWRCm2sVCUDyQy5qECgYEA92jGVAaB3OGEUIXn7eVE3U3FQH37XcJMGsHqBIzDG13p\\n\"\n\t\t\t+ \"C97HdN21rwRkz+G2eAsIxA+p9BsO7dSmtKC60kl6iMRgltS3W7xoC37N9BtjhpciHcLg8c70oyDx\\n\"\n\t\t\t+ \"qHiLKuDi90mZ1FPmWupO4FJnGEB3evHUKZSpTrVVMzt+tyEn/psCgYEAni1hrYoMkQgN3sEC3CKB\\n\"\n\t\t\t+ \"0jQkrOMvY219B8Tdf9LXSuP6z9POagDBDhkeT3xn8rAOmOfVGHYdO0CvPqmAkmXhf+g+OREdecQa\\n\"\n\t\t\t+ \"uY0FmvcTt+Dx0c6pRZmm5AhvUVXFXqONsSg79iviXbUy5Hik0k5HTs5E6B4obrh5W+xfMTUXghkC\\n\"\n\t\t\t+ \"gYBn92uAW8uumkYT4HF6EuJBbTD6zPYYjFGW3O4OQ2ip02jfSBrhDVoP1fTXNq6K+3gPi9WLcuNv\\n\"\n\t\t\t+ \"JfF37iMTwzTuzDcaqwDyV9YRHpRFhEzqfhAkGYSVmLZM5scmWKGCv0YhTJiMFUWz5sqGkZopIs4S\\n\"\n\t\t\t+ \"qBTT9FjBbooDIXk6U4CPCQKBgFdVBxEhnz6UC9RpDIMuKi88yuMJrChhUx7u+ryQVH3s0ZXdg6HT\\n\"\n\t\t\t+ \"OMPn6mxIa7v6qJSTq3wN+qW0WQ1n2Kz7wz0zpOctI/EO7RJ1YhrlP+XONLV6PMtIwnQ0lAF8MbTG\\n\"\n\t\t\t+ \"6HxfknugTyMd4DN0yMu0nHpOOI1P2VMIVzkBkK1CevBBAoGBALROGR7a+eijHdp0/A0chfUoBmud\\n\"\n\t\t\t+ \"/TsUt+0g/vf1p69rMt6DqEGMgMtp2jIRnwvLElS7gVqnCTEclxNU/0rCXR+V7ImJm8J4f0ff8m0Y\\n\"\n\t\t\t+ \"Fir9nfCYStszo25NvLFfynS9d/aoBuvqGJaiQyNXiyBJ4MaxxFYagzAWTnDX+kzTlkZ2\\n\"\n\t\t\t+ \"-----END RSA PRIVATE KEY-----\";\n\tprivate static final String ENCRYPTED_PASSWORD = \"gO1oMoIjjIifv2iqcfIKiQD7ziOTVXsuaBJFEQrZdb8uJH/LsAiJXZeGKEeXlHl/oMoR3HEIoYuHxl+p5iHdrpP889RmxWBDGOWC5iTUzK6CRa5mFmF1I5Lpt7v2YeVoQWihSM8B19BEdBdY1svQp9nyhPB4AqLDrY28x/OrmRh/qYq953i6Y4Z8c76OHqqGcUYM4ePysRlcizSgQjdkEDmKC10Ak3OFRRx3/LqYsFIMiOHeg47APg+UANNTyRiTIia5FDhSeHJzaeYCBRQ7UYH0z2rg4cX3YjOz/MoznjHiaaN4MO+5N3v84VawnqwKOvlwPyI2bmz0+9Tr6DKzqA==\";\n\n\tprotected final DateService dateService = new SimpleDateFormatDateService();\n\n\t/******\n\t * Tests that the bouncy castle crypto module correctly decrypts an\n\t * encrypted String using the provided key.\n\t * \n\t * @throws Exception\n\t */\n\t@Test\n\tpublic void testDecryptStringWithBouncyCastle() throws Exception {\n\t\tCrypto crypto = new BouncyCastleCrypto();\n\t\tdecryptAndVerify(crypto);\n\n\t}\n\n\t/*****\n\t * Adding JCE test as a verifier.\n\t * \n\t * @throws Exception .\n\t */\n\t@Test\n\tpublic void testDecryptStringWithJCE() throws Exception {\n\t\tCrypto crypto = new JCECrypto();\n\t\tdecryptAndVerify(crypto);\n\n\t}\n\n\t/****\n\t * Decryption code copied from org.jclouds.ec2.compute.functions.WindowsLoginCredentialsFromEncryptedData\n\n\t * @param crypto\n\t * @throws InvalidKeySpecException\n\t * @throws NoSuchAlgorithmException\n\t * @throws NoSuchPaddingException\n\t * @throws InvalidKeyException\n\t * @throws IllegalBlockSizeException\n\t * @throws BadPaddingException\n\t */\n\tprivate void decryptAndVerify(Crypto crypto)\n\t\t\tthrows InvalidKeySpecException, NoSuchAlgorithmException,\n\t\t\tNoSuchPaddingException, InvalidKeyException,\n\t\t\tIllegalBlockSizeException, BadPaddingException {\n\t\t\n\t\tKeySpec keySpec = Pems.privateKeySpec(PRIVATE_KEY);\n\t\tKeyFactory kf = crypto.rsaKeyFactory();\n\t\tPrivateKey privKey = kf.generatePrivate(keySpec);\n\n\t\tCipher cipher = crypto.cipher(\"RSA\");\n\t\tcipher.init(Cipher.DECRYPT_MODE, privKey);\n\t\tbyte[] cipherText = base64().decode(ENCRYPTED_PASSWORD);\n\t\tbyte[] plainText = cipher.doFinal(cipherText);\n\t\tString password = new String(plainText, Charsets.US_ASCII);\n\n\t\tassertEquals(password, \"u4.y9mb;nR.\");\n\t}\n}\n"
  },
  {
    "path": "drivers/enterprise/README.txt",
    "content": "#\n# Sets up most commonly requested options for enterprise Java support.\n#\n# Expects the joda-time and bcprov JARs (see drivers/joda and drivers/bouncycastle) to be present on your application's classpath.\n#\n# TODO: Usage example.\n"
  },
  {
    "path": "drivers/enterprise/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.enterprise.*;version=\"${project.version}\";-noimport:=true"
  },
  {
    "path": "drivers/enterprise/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.driver</groupId>\n  <artifactId>jclouds-enterprise</artifactId>\n  <name>jclouds enterprise Module</name>\n  <description>jclouds enterprise configuration</description>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>${project.groupId}</groupId>\n      <artifactId>jclouds-joda</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>${project.groupId}</groupId>\n      <artifactId>jclouds-bouncycastle</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.eclipse.jetty</groupId>\n      <artifactId>jetty-security</artifactId>\n      <scope>test</scope>\n    </dependency>\n  </dependencies>\n\n</project>\n"
  },
  {
    "path": "drivers/enterprise/src/main/java/org/jclouds/enterprise/config/EnterpriseConfigurationModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.enterprise.config;\n\nimport org.jclouds.concurrent.config.ConfiguresExecutorService;\nimport org.jclouds.concurrent.config.ExecutorServiceModule;\nimport org.jclouds.date.joda.config.JodaDateServiceModule;\nimport org.jclouds.encryption.bouncycastle.config.BouncyCastleCryptoModule;\n\nimport com.google.common.util.concurrent.ListeningExecutorService;\n\n/**\n * Configures Enterprise-grade components\n */\n@ConfiguresExecutorService\npublic class EnterpriseConfigurationModule extends ExecutorServiceModule {\n\n   /**\n    * @deprecated {@code ioExecutor} is no longer used. This constructor will be removed in jclouds v2.\n    * Use {@link #EnterpriseConfigurationModule(ListeningExecutorService)} instead.\n    */\n   @Deprecated\n   public EnterpriseConfigurationModule(ListeningExecutorService userExecutor, ListeningExecutorService ioExecutor) {\n      super(userExecutor, ioExecutor);\n   }\n\n   @Deprecated\n   public EnterpriseConfigurationModule(ListeningExecutorService userExecutor) {\n      super(userExecutor);\n   }\n\n   public EnterpriseConfigurationModule() {\n      super();\n   }\n\n   @Override\n   protected void configure() {\n      install(new BouncyCastleCryptoModule());\n      install(new JodaDateServiceModule());\n   }\n\n}\n"
  },
  {
    "path": "drivers/joda/README.txt",
    "content": "#\n# A driver to use Joda (http://joda-time.sourceforge.net/) as a time and date library\n# in jclouds.\n#\n# TODO: Usage example.\n"
  },
  {
    "path": "drivers/joda/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.date.joda.*;version=\"${project.version}\";-noimport:=true"
  },
  {
    "path": "drivers/joda/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.driver</groupId>\n  <artifactId>jclouds-joda</artifactId>\n  <name>jclouds joda DateService Module</name>\n  <description>jclouds joda DateService Module</description>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>joda-time</groupId>\n      <artifactId>joda-time</artifactId>\n      <version>2.1</version>\n      <scope>compile</scope>\n    </dependency>\n  </dependencies>\n\n</project>\n\n"
  },
  {
    "path": "drivers/joda/src/main/java/org/jclouds/date/joda/JodaDateService.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.date.joda;\n\nimport static org.jclouds.date.internal.DateUtils.findTZ;\nimport static org.jclouds.date.internal.DateUtils.trimTZ;\nimport static org.jclouds.date.internal.DateUtils.trimToMillis;\n\nimport java.util.Date;\nimport java.util.Locale;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.date.DateService;\nimport org.joda.time.DateTime;\nimport org.joda.time.DateTimeZone;\nimport org.joda.time.format.DateTimeFormat;\nimport org.joda.time.format.DateTimeFormatter;\n\n@Singleton\npublic class JodaDateService implements DateService {\n   \n   private static final DateTimeFormatter rfc822DateFormatter = DateTimeFormat.forPattern(\n            \"EEE, dd MMM yyyy HH:mm:ss 'GMT'\").withLocale(Locale.US).withZone(DateTimeZone.forID(\"GMT\"));\n\n   private static final DateTimeFormatter cDateFormatter = DateTimeFormat\n            .forPattern(\"EEE MMM dd HH:mm:ss Z yyyy\").withLocale(Locale.US).withZone(DateTimeZone.forID(\"GMT\"));\n\n   private static final DateTimeFormatter iso8601SecondsDateFormatter = DateTimeFormat.forPattern(\n            \"yyyy-MM-dd'T'HH:mm:ssZ\").withLocale(Locale.US).withZone(DateTimeZone.forID(\"GMT\"));\n\n   private static final DateTimeFormatter iso8601DateFormatter = DateTimeFormat.forPattern(\n            \"yyyy-MM-dd'T'HH:mm:ss.SSSZ\").withLocale(Locale.US).withZone(DateTimeZone.forID(\"GMT\"));\n\n   private static final DateTimeFormatter rfc1123DateFormat = DateTimeFormat.forPattern(\n            \"EEE, dd MMM yyyyy HH:mm:ss Z\").withLocale(Locale.US).withZone(DateTimeZone.forID(\"GMT\"));\n\n   public final Date fromSeconds(long seconds) {\n      return new Date(seconds * 1000);\n   }\n\n   public final String cDateFormat(Date dateTime) {\n      return cDateFormatter.print(new DateTime(dateTime));\n   }\n\n   public final String cDateFormat() {\n      return cDateFormat(new Date());\n   }\n\n   public final Date cDateParse(String toParse) {\n      return cDateFormatter.parseDateTime(toParse).toDate();\n   }\n\n   public final String rfc822DateFormat(Date dateTime) {\n      return rfc822DateFormatter.print(new DateTime(dateTime));\n   }\n\n   public final String rfc822DateFormat() {\n      return rfc822DateFormat(new Date());\n   }\n\n   public final Date rfc822DateParse(String toParse) {\n      return rfc822DateFormatter.parseDateTime(toParse).toDate();\n   }\n\n   public final String iso8601SecondsDateFormat(Date dateTime) {\n      String parsed = iso8601SecondsDateFormatter.print(new DateTime(dateTime));\n      String tz = findTZ(parsed);\n      if (tz.equals(\"+0000\")) {\n         parsed = trimTZ(parsed) + \"Z\";\n      }\n      return parsed;\n   }\n\n   public final String iso8601SecondsDateFormat() {\n      return iso8601SecondsDateFormat(new Date());\n   }\n\n   public final String iso8601DateFormat(Date date) {\n      String parsed = iso8601DateFormatter.print(new DateTime(date));\n      String tz = findTZ(parsed);\n      if (tz.equals(\"+0000\")) {\n         parsed = trimTZ(parsed) + \"Z\";\n      }\n      return parsed;\n   }\n\n   public final String iso8601DateFormat() {\n      return iso8601DateFormat(new Date());\n   }\n\n   public final Date iso8601DateParse(String toParse) {\n      if (toParse.length() < 10)\n         throw new IllegalArgumentException(\"incorrect date format \" + toParse);\n      toParse = adjustTz(toParse);\n      if (toParse.charAt(10) == ' ')\n         toParse = new StringBuilder(toParse).replace(10, 11, \"T\").toString();\n      return iso8601DateFormatter.parseDateTime(toParse).toDate();\n   }\n\n   private String adjustTz(String toParse) {\n      String tz = findTZ(toParse);\n      toParse = trimToMillis(toParse);\n      toParse = trimTZ(toParse);\n      toParse += tz;\n      return toParse.replace(\"UTC\", \"\");\n   }\n\n   public final Date iso8601SecondsDateParse(String toParse) {\n      if (toParse.length() < 10)\n         throw new IllegalArgumentException(\"incorrect date format \" + toParse);\n      toParse = adjustTz(toParse);\n      return iso8601SecondsDateFormatter.parseDateTime(toParse).toDate();\n   }\n\n   @Override\n   public Date iso8601DateOrSecondsDateParse(String toParse)\n         throws IllegalArgumentException {\n      try {\n         return iso8601DateParse(toParse);\n      } catch (IllegalArgumentException orig) {\n         try {\n            return iso8601SecondsDateParse(toParse);\n         } catch (IllegalArgumentException ignored) {\n            throw orig;\n         }\n      }\n   }\n\n   @Override\n   public final String rfc1123DateFormat(Date dateTime) {\n      return rfc1123DateFormat.print(new DateTime(dateTime));\n   }\n\n   @Override\n   public final String rfc1123DateFormat() {\n      return rfc1123DateFormat(new Date());\n   }\n\n   @Override\n   public final Date rfc1123DateParse(String toParse) {\n      return rfc1123DateFormat.parseDateTime(toParse).toDate();\n   }\n}\n"
  },
  {
    "path": "drivers/joda/src/main/java/org/jclouds/date/joda/config/JodaDateServiceModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.date.joda.config;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.joda.JodaDateService;\n\nimport com.google.inject.AbstractModule;\n\n/**\n * Configures DateService of type {@link JodaDateService}\n */\npublic class JodaDateServiceModule extends AbstractModule {\n\n   @Override\n   protected void configure() {\n      bind(DateService.class).to(JodaDateService.class);\n   }\n\n}\n"
  },
  {
    "path": "drivers/joda/src/test/java/org/jclouds/date/joda/JodaDateServiceTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.date.joda;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Date;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.DateServiceTest;\nimport org.jclouds.date.joda.config.JodaDateServiceModule;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n/* \n * TODO: Scrap any non-DateService references (eg Joda & Amazon) if/when\n * we confirm that the DateService is fast enough.\n */\n\n/**\n * Compares performance of date operations\n */\n//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"performance\", singleThreaded = true, timeOut = 2 * 60 * 1000, testName = \"JodaDateServiceTest\")\npublic class JodaDateServiceTest extends DateServiceTest {\n   @Override\n   @BeforeTest\n   protected void createDateService() {\n      Injector i = Guice.createInjector(new JodaDateServiceModule());\n      dateService = i.getInstance(DateService.class);\n      assert dateService instanceof JodaDateService;\n   }\n\n   @Override\n   @Test\n   public void testRfc822DateFormat() {\n      String dsString = dateService.rfc822DateFormat(testData[0].date);\n      assertEquals(dsString, testData[0].rfc822DateString);\n   }\n\n   @Override\n   @Test(enabled = false)\n   public void testRfc822DateParse() {\n      Date dsDate = dateService.rfc822DateParse(testData[0].rfc822DateString);\n      assertEquals(dsDate, testData[0].date);\n   }\n}\n"
  },
  {
    "path": "drivers/jsch/README.txt",
    "content": "#\n# A driver to use JSch (http://www.jcraft.com/jsch/) as the SSH connection provider\n# for jclouds.\n#\n# TODO: Usage example.\n"
  },
  {
    "path": "drivers/jsch/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.ssh.jsch.*;version=\"${project.version}\";-noimport:=true"
  },
  {
    "path": "drivers/jsch/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.driver</groupId>\n  <artifactId>jclouds-jsch</artifactId>\n  <name>jclouds jsch ssh client</name>\n  <description>jclouds jsch ssh client</description>\n\n  <properties>\n    <test.ssh.host>localhost</test.ssh.host>\n    <test.ssh.port>22</test.ssh.port>\n    <test.ssh.username />\n    <test.ssh.password />\n    <test.ssh.keyfile />\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-slf4j</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>ch.qos.logback</groupId>\n      <artifactId>logback-classic</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.jcraft</groupId>\n      <artifactId>jsch</artifactId>\n      <version>0.1.55</version>\n      <scope>compile</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.jcraft</groupId>\n      <artifactId>jsch.agentproxy.jsch</artifactId>\n      <version>0.0.9</version>\n    </dependency>\n    <dependency>\n      <groupId>com.jcraft</groupId>\n      <artifactId>jsch.agentproxy.connector-factory</artifactId>\n      <version>0.0.9</version>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <!-- note that the groups/excluded groups don't work due to some problem\n                       in surefire or testng. instead, we have to exclude via file path\n                       <groups>live,integration</groups>\n                       <excludedGroups>unit,performance</excludedGroups>\n                  -->\n                  <excludes>\n                    <exclude>none</exclude>\n                  </excludes>\n                  <includes>\n                    <include>**/*IntegrationTest.java</include>\n                    <include>**/*LiveTest.java</include>\n                  </includes>\n                  <systemPropertyVariables>\n                    <file.encoding>UTF-8</file.encoding>\n                    <test.ssh.host>${test.ssh.host}</test.ssh.host>\n                    <test.ssh.port>${test.ssh.port}</test.ssh.port>\n                    <test.ssh.username>${test.ssh.username}</test.ssh.username>\n                    <test.ssh.keyfile>${test.ssh.keyfile}</test.ssh.keyfile>\n                    <test.ssh.password>${test.ssh.password}</test.ssh.password>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n</project>\n"
  },
  {
    "path": "drivers/jsch/src/main/java/org/jclouds/ssh/jsch/JschSshClient.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ssh.jsch;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.common.base.Predicates.instanceOf;\nimport static com.google.common.base.Predicates.or;\nimport static com.google.common.base.Throwables.getCausalChain;\nimport static com.google.common.collect.Iterables.any;\nimport static com.google.common.hash.Hashing.md5;\nimport static com.google.common.io.BaseEncoding.base16;\nimport static org.jclouds.ssh.SshKeys.fingerprintPrivateKey;\nimport static org.jclouds.ssh.SshKeys.sha1PrivateKey;\n\nimport java.io.ByteArrayOutputStream;\nimport java.io.Closeable;\nimport java.io.FilterInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.net.ConnectException;\n\nimport jakarta.annotation.PreDestroy;\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\n\nimport org.jclouds.compute.domain.ExecChannel;\nimport org.jclouds.compute.domain.ExecResponse;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.http.handlers.BackoffLimitedRetryHandler;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.proxy.ProxyConfig;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.ssh.SshClient;\nimport org.jclouds.ssh.SshException;\nimport org.jclouds.util.Closeables2;\nimport org.jclouds.util.Strings2;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Predicates;\nimport com.google.common.base.Splitter;\nimport com.google.common.base.Supplier;\nimport com.google.common.net.HostAndPort;\nimport com.google.inject.Inject;\nimport com.jcraft.jsch.ChannelExec;\nimport com.jcraft.jsch.ChannelSftp;\nimport com.jcraft.jsch.JSchException;\nimport com.jcraft.jsch.Session;\nimport com.jcraft.jsch.agentproxy.Connector;\n\n/**\n * This class needs refactoring. It is not thread safe.\n */\npublic class JschSshClient implements SshClient {\n\n   private static final class CloseFtpChannelOnCloseInputStream extends FilterInputStream {\n\n      private final ChannelSftp sftp;\n\n      private CloseFtpChannelOnCloseInputStream(InputStream proxy, ChannelSftp sftp) {\n         super(proxy);\n         this.sftp = sftp;\n      }\n\n      @Override\n      public void close() throws IOException {\n         super.close();\n         if (sftp != null)\n            sftp.disconnect();\n      }\n   }\n   \n   private final String toString;\n\n   @Inject(optional = true)\n   @Named(\"jclouds.ssh.max-retries\")\n   @VisibleForTesting\n   int sshRetries = 5;\n\n   @Inject(optional = true)\n   @Named(\"jclouds.ssh.retry-auth\")\n   @VisibleForTesting\n   boolean retryAuth;\n\n   @Inject(optional = true)\n   @Named(\"jclouds.ssh.retryable-messages\")\n   @VisibleForTesting\n   String retryableMessages = \"failed to send channel request,channel is not opened,invalid data,End of IO Stream Read,Connection reset,connection is closed by foreign host,socket is not established\";\n\n   @Inject(optional = true)\n   @Named(\"jclouds.ssh.retry-predicate\")\n   Predicate<Throwable> retryPredicate = or(instanceOf(ConnectException.class), instanceOf(IOException.class));\n\n   @Resource\n   @Named(\"jclouds.ssh\")\n   protected Logger logger = Logger.NULL;\n\n   private final BackoffLimitedRetryHandler backoffLimitedRetryHandler;\n\n   final SessionConnection sessionConnection;\n   final String user;\n   final String host;\n\n\n   public JschSshClient(ProxyConfig proxyConfig, BackoffLimitedRetryHandler backoffLimitedRetryHandler, HostAndPort socket,\n            LoginCredentials loginCredentials, int timeout, Optional<Connector> agentConnector) {\n      this.user = checkNotNull(loginCredentials, \"loginCredentials\").getUser();\n      this.host = checkNotNull(socket, \"socket\").getHost();\n      checkArgument(socket.getPort() > 0, \"ssh port must be greater then zero\" + socket.getPort());\n      checkArgument(loginCredentials.getOptionalPassword().isPresent() || loginCredentials.hasUnencryptedPrivateKey() || agentConnector.isPresent(),\n               \"you must specify a password, a key or an SSH agent needs to be available\");\n      this.backoffLimitedRetryHandler = checkNotNull(backoffLimitedRetryHandler, \"backoffLimitedRetryHandler\");\n      if (loginCredentials.hasUnencryptedPrivateKey()) {\n         String fingerPrint = fingerprintPrivateKey(loginCredentials.getOptionalPrivateKey().get());\n         String sha1 = sha1PrivateKey(loginCredentials.getOptionalPrivateKey().get());\n         this.toString = String.format(\"%s:rsa[fingerprint(%s),sha1(%s)]@%s:%d\", loginCredentials.getUser(),\n                 fingerPrint, sha1, host, socket.getPort());\n      } else if (loginCredentials.getOptionalPassword().isPresent()) {\n         this.toString = String.format(\"%s:pw[%s]@%s:%d\", loginCredentials.getUser(),\n               base16().lowerCase().encode(md5().hashString(loginCredentials.getOptionalPassword().get(), UTF_8).asBytes()), host,\n               socket.getPort());\n      } else {\n         this.toString = String.format(\"%s:rsa[ssh-agent]@%s:%d\", loginCredentials.getUser(), host, socket.getPort());\n      }\n      sessionConnection = SessionConnection.builder().hostAndPort(HostAndPort.fromParts(host, socket.getPort())).loginCredentials(\n               loginCredentials).proxy(checkNotNull(proxyConfig, \"proxyConfig\")).connectTimeout(timeout).sessionTimeout(timeout)\n               .agentConnector(agentConnector).build();\n   }\n\n   @Override\n   public void put(String path, String contents) {\n      put(path, Payloads.newStringPayload(checkNotNull(contents, \"contents\")));\n   }\n\n   private void checkConnected() {\n      checkState(sessionConnection.getSession() != null && sessionConnection.getSession().isConnected(),\n               \"(%s) Session not connected!\", this);\n   }\n\n   public interface Connection<T> {\n      void clear();\n\n      T create() throws Exception;\n   }\n\n   public interface ConnectionWithStreams<T> extends Connection<T> {\n      InputStream getInputStream();\n      InputStream getErrStream();\n   }\n\n   protected <T, C extends Connection<T>> T acquire(C connection) {\n      connection.clear();\n      String errorMessage = String.format(\"(%s) error acquiring %s\", toString(), connection);\n      for (int i = 0; i < sshRetries; i++) {\n         try {\n            logger.debug(\">> (%s) acquiring %s\", toString(), connection);\n            T returnVal = connection.create();\n            logger.debug(\"<< (%s) acquired %s\", toString(), returnVal);\n            return returnVal;\n         } catch (Exception from) {\n            connection.clear();\n\n            if (i + 1 == sshRetries) {\n               throw propagate(from, errorMessage);\n            } else if (shouldRetry(from)) {\n               logger.warn(from, \"<< \" + errorMessage + \": \" + from.getMessage());\n               backoffForAttempt(i + 1, errorMessage + \": \" + from.getMessage());\n               continue;\n            }\n         }\n      }\n      throw new AssertionError(\"should not reach here\");\n   }\n\n   public void connect() {\n      acquire(sessionConnection);\n   }\n\n   Connection<ChannelSftp> sftpConnection = new Connection<ChannelSftp>() {\n\n      private ChannelSftp sftp;\n\n      @Override\n      public void clear() {\n         if (sftp != null)\n            sftp.disconnect();\n      }\n\n      @Override\n      public ChannelSftp create() throws JSchException {\n         checkConnected();\n         String channel = \"sftp\";\n         sftp = (ChannelSftp) sessionConnection.getSession().openChannel(channel);\n         sftp.connect();\n         return sftp;\n      }\n\n      @Override\n      public String toString() {\n         return \"ChannelSftp()\";\n      }\n   };\n\n   class GetConnection implements Connection<Payload> {\n      private final String path;\n      private ChannelSftp sftp;\n\n      GetConnection(String path) {\n         this.path = checkNotNull(path, \"path\");\n      }\n\n      @Override\n      public void clear() {\n         if (sftp != null)\n            sftp.disconnect();\n      }\n\n      @Override\n      public Payload create() throws Exception {\n         sftp = acquire(sftpConnection);\n         return Payloads.newInputStreamPayload(new CloseFtpChannelOnCloseInputStream(sftp.get(path), sftp));\n      }\n\n      @Override\n      public String toString() {\n         return \"Payload(path=[\" + path + \"])\";\n      }\n   };\n\n   public Payload get(String path) {\n      return acquire(new GetConnection(path));\n   }\n\n   class PutConnection implements Connection<Void> {\n      private final String path;\n      private final Payload contents;\n      private ChannelSftp sftp;\n\n      PutConnection(String path, Payload contents) {\n         this.path = checkNotNull(path, \"path\");\n         this.contents = checkNotNull(contents, \"contents\");\n      }\n\n      @Override\n      public void clear() {\n         if (sftp != null)\n            sftp.disconnect();\n      }\n\n      @Override\n      public Void create() throws Exception {\n         sftp = acquire(sftpConnection);\n         InputStream is = checkNotNull(contents.getInput(), \"inputstream for path %s\", path);\n         try {\n            sftp.put(is, path);\n         } finally {\n            Closeables2.closeQuietly(is);\n         }\n         return null;\n      }\n\n      @Override\n      public String toString() {\n         return \"Put(path=[\" + path + \"])\";\n      }\n   };\n\n   @Override\n   public void put(String path, Payload contents) {\n      acquire(new PutConnection(path, contents));\n   }\n\n   @VisibleForTesting\n   boolean shouldRetry(Exception from) {\n      Predicate<Throwable> predicate = retryAuth ? Predicates.<Throwable> or(retryPredicate,\n               instanceOf(AuthorizationException.class)) : retryPredicate;\n      if (any(getCausalChain(from), predicate))\n         return true;\n      if (!retryableMessages.equals(\"\"))\n         return any(Splitter.on(\",\").split(retryableMessages), causalChainHasMessageContaining(from));\n      return false;\n   }\n\n   @VisibleForTesting\n   Predicate<String> causalChainHasMessageContaining(final Exception from) {\n      return new Predicate<String>() {\n\n         @Override\n         public boolean apply(final String input) {\n            return any(getCausalChain(from), new Predicate<Throwable>() {\n\n               @Override\n               public boolean apply(Throwable arg0) {\n                  return (arg0.toString().indexOf(input) != -1)\n                           || (arg0.getMessage() != null && arg0.getMessage().indexOf(input) != -1);\n               }\n\n            });\n         }\n\n      };\n   }\n\n   private void backoffForAttempt(int retryAttempt, String message) {\n      backoffLimitedRetryHandler.imposeBackoffExponentialDelay(200L, 2, retryAttempt, sshRetries, message);\n   }\n\n   SshException propagate(Exception e, String message) {\n      message += \": \" + e.getMessage();\n      if (e.getMessage() != null && e.getMessage().indexOf(\"Auth fail\") != -1)\n         throw new AuthorizationException(\"(\" + toString() + \") \" + message, e);\n      throw e instanceof SshException ? SshException.class.cast(e) : new SshException(\n               \"(\" + toString() + \") \" + message, e);\n   }\n\n   @Override\n   public String toString() {\n      return toString;\n   }\n\n   @Override\n   @PreDestroy\n   public void disconnect() {\n      sessionConnection.clear();\n   }\n\n   @Override\n   public boolean isConnected() {\n      return sessionConnection.getSession().isConnected();\n   }\n\n   protected ConnectionWithStreams<ChannelExec> execConnection(final String command) {\n      checkNotNull(command, \"command\");\n      return new ConnectionWithStreams<ChannelExec>() {\n\n         private ChannelExec executor = null;\n         private InputStream inputStream;\n         private InputStream errStream;\n         \n         @Override\n         public void clear() {\n            if (inputStream != null)\n               Closeables2.closeQuietly(inputStream);\n            if (errStream != null)\n               Closeables2.closeQuietly(errStream);\n            if (executor != null)\n               executor.disconnect();\n         }\n\n         @Override\n         public ChannelExec create() throws Exception {\n            checkConnected();\n            String channel = \"exec\";\n            executor = (ChannelExec) sessionConnection.getSession().openChannel(channel);\n            executor.setPty(true);\n            executor.setCommand(command);\n            inputStream = executor.getInputStream();\n            errStream = executor.getErrStream();\n            executor.connect();\n            \n            return executor;\n         }\n\n         @Override\n         public InputStream getInputStream() {\n            return inputStream;\n         }\n\n         @Override\n         public InputStream getErrStream() {\n            return errStream;\n         }\n\n         @Override\n         public String toString() {\n            return \"ChannelExec()\";\n         }\n      };\n\n   }\n\n   class ExecConnection implements Connection<ExecResponse> {\n      private final String command;\n      private ChannelExec executor;\n\n      ExecConnection(String command) {\n         this.command = checkNotNull(command, \"command\");\n      }\n\n      @Override\n      public void clear() {\n         if (executor != null)\n            executor.disconnect();\n      }\n\n      @Override\n      public ExecResponse create() throws Exception {\n         try {\n            ConnectionWithStreams<ChannelExec> connection = execConnection(command);\n            executor = acquire(connection);\n            String outputString = Strings2.toStringAndClose(connection.getInputStream());\n            String errorString = Strings2.toStringAndClose(connection.getErrStream());\n            int errorStatus = executor.getExitStatus();\n            int i = 0;\n            String message = String.format(\"bad status -1 %s\", toString());\n            while ((errorStatus = executor.getExitStatus()) == -1 && i < JschSshClient.this.sshRetries) {\n               logger.warn(\"<< \" + message);\n               backoffForAttempt(++i, message);\n            }\n            if (errorStatus == -1)\n               throw new SshException(message);\n            return new ExecResponse(outputString, errorString, errorStatus);\n         } finally {\n            clear();\n         }\n      }\n\n      @Override\n      public String toString() {\n         return \"ExecResponse(command=[\" + command + \"])\";\n      }\n   }\n\n   public ExecResponse exec(String command) {\n      return acquire(new ExecConnection(command));\n   }\n\n   @Override\n   public String getHostAddress() {\n      return this.host;\n   }\n\n   @Override\n   public String getUsername() {\n      return this.user;\n   }\n\n   class ExecChannelConnection implements Connection<ExecChannel> {\n      private final String command;\n      private ChannelExec executor = null;\n      private Session sessionConnection;\n      \n      ExecChannelConnection(String command) {\n         this.command = checkNotNull(command, \"command\");\n      }\n\n      @Override\n      public void clear() {\n         if (executor != null)\n            executor.disconnect();\n         if (sessionConnection != null)\n            sessionConnection.disconnect();\n      }\n\n      @Override\n      public ExecChannel create() throws Exception {\n         this.sessionConnection = acquire(SessionConnection.builder().from(JschSshClient.this.sessionConnection)\n               .sessionTimeout(0).build());\n         String channel = \"exec\";\n         executor = (ChannelExec) sessionConnection.openChannel(channel);\n         executor.setCommand(command);\n         executor.setErrStream(new ByteArrayOutputStream());\n         InputStream inputStream = executor.getInputStream();\n         InputStream errStream = executor.getErrStream();\n         OutputStream outStream = executor.getOutputStream();\n         executor.connect();\n         return new ExecChannel(outStream, inputStream, errStream,\n                  new Supplier<Integer>() {\n\n                     @Override\n                     public Integer get() {\n                        int exitStatus = executor.getExitStatus();\n                        return exitStatus != -1 ? exitStatus : null;\n                     }\n\n                  }, new Closeable() {\n\n                     @Override\n                     public void close() throws IOException {\n                        clear();\n                     }\n\n                  });\n      }\n\n      @Override\n      public String toString() {\n         return \"ExecChannel(command=[\" + command + \"])\";\n      }\n   };\n\n   @Override\n   public ExecChannel execChannel(String command) {\n      return acquire(new ExecChannelConnection(command));\n   }\n\n}\n"
  },
  {
    "path": "drivers/jsch/src/main/java/org/jclouds/ssh/jsch/SessionConnection.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ssh.jsch;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.proxy.ProxyConfig;\nimport org.jclouds.ssh.jsch.JschSshClient.Connection;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.Optional;\nimport com.google.common.net.HostAndPort;\nimport com.jcraft.jsch.JSch;\nimport com.jcraft.jsch.Proxy;\nimport com.jcraft.jsch.ProxyHTTP;\nimport com.jcraft.jsch.ProxySOCKS5;\nimport com.jcraft.jsch.Session;\nimport com.jcraft.jsch.agentproxy.Connector;\nimport com.jcraft.jsch.agentproxy.RemoteIdentityRepository;\n\npublic final class SessionConnection implements Connection<Session> {\n\n   private Optional<Connector> agentConnector;\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static final class Builder {\n\n      private HostAndPort hostAndPort;\n      private LoginCredentials loginCredentials;\n      private Optional<Proxy> proxy = Optional.absent();\n      private int connectTimeout;\n      private int sessionTimeout;\n      private Optional<Connector> agentConnector;\n\n      /**\n       * @see SessionConnection#getHostAndPort()\n       */\n      public Builder hostAndPort(HostAndPort hostAndPort) {\n         this.hostAndPort = hostAndPort;\n         return this;\n      }\n\n      /**\n       * @see SessionConnection#getLoginCredentials()\n       */\n      public Builder loginCredentials(LoginCredentials loginCredentials) {\n         this.loginCredentials = loginCredentials;\n         return this;\n      }\n\n      /**\n       * @see SessionConnection#getProxy()\n       */\n      public Builder proxy(Proxy proxy) {\n         this.proxy = Optional.fromNullable(proxy);\n         return this;\n      }\n\n      /**\n       * @see #proxy(Proxy)\n       */\n      public Builder proxy(ProxyConfig proxyConfig) {\n         Optional<HostAndPort> proxyEndpoint = proxyConfig.getProxy();\n         if (!proxyEndpoint.isPresent())\n            return proxy((Proxy) null);\n\n         Optional<Credentials> creds = proxyConfig.getCredentials();\n         switch (proxyConfig.getType()) {\n         case HTTP:\n            ProxyHTTP httpProxy = new ProxyHTTP(proxyEndpoint.get().getHost(), proxyEndpoint.get().getPort());\n            if (creds.isPresent())\n               httpProxy.setUserPasswd(creds.get().identity, creds.get().credential);\n            return proxy(httpProxy);\n         case SOCKS:\n            ProxySOCKS5 socksProxy = new ProxySOCKS5(proxyEndpoint.get().getHost(), proxyEndpoint.get().getPort());\n            if (creds.isPresent())\n               socksProxy.setUserPasswd(creds.get().identity, creds.get().credential);\n            return proxy(socksProxy);\n         default:\n            throw new IllegalArgumentException(proxyConfig.getType() + \" not supported\");\n         }\n      }\n\n      /**\n       * @see SessionConnection#getConnectTimeout()\n       */\n      public Builder connectTimeout(int connectTimeout) {\n         this.connectTimeout = connectTimeout;\n         return this;\n      }\n\n      /**\n       * @see SessionConnection#getConnectTimeout()\n       */\n      public Builder sessionTimeout(int sessionTimeout) {\n         this.sessionTimeout = sessionTimeout;\n         return this;\n      }\n\n      public SessionConnection build() {\n         return new SessionConnection(hostAndPort, loginCredentials, proxy, connectTimeout, sessionTimeout, agentConnector);\n      }\n\n      public Builder from(SessionConnection in) {\n         return hostAndPort(in.hostAndPort).loginCredentials(in.loginCredentials).proxy(in.proxy.orNull())\n               .connectTimeout(in.connectTimeout).sessionTimeout(in.sessionTimeout).agentConnector(in.agentConnector);\n      }\n\n      public Builder agentConnector(Optional<Connector> agentConnector) {\n         this.agentConnector = agentConnector;\n         return this;\n      }\n\n   }\n\n   private SessionConnection(HostAndPort hostAndPort, LoginCredentials loginCredentials, Optional<Proxy> proxy,\n         int connectTimeout, int sessionTimeout, Optional<Connector> agentConnector) {\n      this.hostAndPort = checkNotNull(hostAndPort, \"hostAndPort\");\n      this.loginCredentials = checkNotNull(loginCredentials, \"loginCredentials for %\", hostAndPort);\n      this.connectTimeout = connectTimeout;\n      this.sessionTimeout = sessionTimeout;\n      this.proxy = checkNotNull(proxy, \"proxy for %\", hostAndPort);\n      this.agentConnector = checkNotNull(agentConnector, \"agentConnector for %\", hostAndPort);\n   }\n\n   private static final byte[] emptyPassPhrase = new byte[0];\n\n   private final HostAndPort hostAndPort;\n   private final LoginCredentials loginCredentials;\n   private final Optional<Proxy> proxy;\n   private final int connectTimeout;\n   private final int sessionTimeout;\n\n   private transient Session session;\n\n   @Override\n   public void clear() {\n      if (session != null && session.isConnected()) {\n         session.disconnect();\n         session = null;\n      }\n   }\n\n   @Override\n   public Session create() throws Exception {\n      JSch jsch = new JSch();\n      session = jsch\n            .getSession(loginCredentials.getUser(), hostAndPort.getHost(), hostAndPort.getPortOrDefault(22));\n      if (sessionTimeout != 0)\n         session.setTimeout(sessionTimeout);\n      if (loginCredentials.hasUnencryptedPrivateKey()) {\n         byte[] privateKey = loginCredentials.getOptionalPrivateKey().get().getBytes();\n         jsch.addIdentity(loginCredentials.getUser(), privateKey, null, emptyPassPhrase);\n      } else if (loginCredentials.getOptionalPassword().isPresent()) {\n          session.setPassword(loginCredentials.getOptionalPassword().orNull());\n      } else if (agentConnector.isPresent()) {\n         JSch.setConfig(\"PreferredAuthentications\", \"publickey\");\n         jsch.setIdentityRepository(new RemoteIdentityRepository(agentConnector.get()));\n      }\n      java.util.Properties config = new java.util.Properties();\n      config.put(\"StrictHostKeyChecking\", \"no\");\n      session.setConfig(config);\n      if (proxy.isPresent())\n         session.setProxy(proxy.get());\n      session.connect(connectTimeout);\n      return session;\n   }\n\n   /**\n    * @return host and port, where port if not present defaults to {@code 22}\n    */\n   public HostAndPort getHostAndPort() {\n      return hostAndPort;\n   }\n\n   /**\n    * \n    * @return login used in this session\n    */\n   public LoginCredentials getLoginCredentials() {\n      return loginCredentials;\n   }\n\n   /**\n    * \n    * @return proxy used for this connection\n    */\n   public Optional<Proxy> getProxy() {\n      return proxy;\n   }\n\n   /**\n    * \n    * @return how long to wait for the initial connection to be made\n    */\n   public int getConnectTimeout() {\n      return connectTimeout;\n   }\n\n   /**\n    * \n    * @return how long to keep the session open, or {@code 0} for indefinitely\n    */\n   public int getSessionTimeout() {\n      return sessionTimeout;\n   }\n\n   /**\n    * \n    * @return the current session or {@code null} if not connected\n    */\n   @Nullable\n   public Session getSession() {\n      return session;\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o)\n         return true;\n      if (o == null || getClass() != o.getClass())\n         return false;\n      SessionConnection that = SessionConnection.class.cast(o);\n      return equal(this.hostAndPort, that.hostAndPort) && equal(this.loginCredentials, that.loginCredentials)\n            && equal(this.session, that.session);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(hostAndPort, loginCredentials, session);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(\"\").omitNullValues()\n            .add(\"hostAndPort\", hostAndPort).add(\"loginUser\", loginCredentials.getUser())\n            .add(\"session\", session != null ? session.hashCode() : null)\n            .add(\"connectTimeout\", connectTimeout)\n            .add(\"proxy\", proxy.orNull())\n            .add(\"sessionTimeout\", sessionTimeout).toString();\n   }\n\n}\n"
  },
  {
    "path": "drivers/jsch/src/main/java/org/jclouds/ssh/jsch/config/JschSshClientModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ssh.jsch.config;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.Constants;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.http.handlers.BackoffLimitedRetryHandler;\nimport org.jclouds.proxy.ProxyConfig;\nimport org.jclouds.ssh.SshClient;\nimport org.jclouds.ssh.config.ConfiguresSshClient;\nimport org.jclouds.ssh.jsch.JschSshClient;\n\nimport com.google.common.base.Optional;\nimport com.google.common.net.HostAndPort;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Inject;\nimport com.google.inject.Injector;\nimport com.google.inject.Scopes;\nimport com.jcraft.jsch.agentproxy.AgentProxyException;\nimport com.jcraft.jsch.agentproxy.Connector;\nimport com.jcraft.jsch.agentproxy.ConnectorFactory;\n\n@ConfiguresSshClient\npublic class JschSshClientModule extends AbstractModule {\n\n   protected void configure() {\n      bind(SshClient.Factory.class).to(Factory.class).in(Scopes.SINGLETON);\n   }\n\n   private static class Factory implements SshClient.Factory {\n      @Named(Constants.PROPERTY_CONNECTION_TIMEOUT)\n      @Inject(optional = true)\n      int timeout = 60000;\n\n      Optional<Connector> agentConnector = getAgentConnector();\n\n      Optional<Connector> getAgentConnector() {\n         ConnectorFactory sshAgentOverNetcatOnly = new ConnectorFactory() {\n               {\n                  setPreferredConnectors(\"ssh-agent\");\n                  setPreferredUSocketFactories(\"nc\");\n               }\n            };\n         try {\n            return Optional.of(sshAgentOverNetcatOnly.createConnector());\n         } catch (final AgentProxyException e) {\n            return Optional.absent();\n         }\n      }\n\n      private final ProxyConfig proxyConfig;\n      private final BackoffLimitedRetryHandler backoffLimitedRetryHandler;\n      private final Injector injector;\n\n      @Inject\n      public Factory(ProxyConfig proxyConfig, BackoffLimitedRetryHandler backoffLimitedRetryHandler, Injector injector) {\n         this.proxyConfig = checkNotNull(proxyConfig, \"proxyConfig\");\n         this.backoffLimitedRetryHandler = checkNotNull(backoffLimitedRetryHandler, \"backoffLimitedRetryHandler\");\n         this.injector = checkNotNull(injector, \"injector\");\n      }\n\n      @Override\n      public SshClient create(HostAndPort socket, LoginCredentials credentials) {\n         SshClient client = new JschSshClient(proxyConfig, backoffLimitedRetryHandler, socket, credentials, timeout, getAgentConnector());\n         injector.injectMembers(client);  // add logger\n         return client;\n      }\n\n      @Override\n      public boolean isAgentAvailable() {\n         return agentConnector.isPresent();\n      }\n   }\n}\n"
  },
  {
    "path": "drivers/jsch/src/test/java/org/jclouds/ssh/jsch/JschSshClientLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ssh.jsch;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.ByteArrayOutputStream;\nimport java.io.Closeable;\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.io.IOException;\nimport java.io.PrintStream;\nimport java.net.InetAddress;\nimport java.util.List;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.TimeUnit;\n\nimport org.jclouds.compute.domain.ExecChannel;\nimport org.jclouds.compute.domain.ExecResponse;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.logging.slf4j.config.SLF4JLoggingModule;\nimport org.jclouds.ssh.SshClient;\nimport org.jclouds.ssh.jsch.config.JschSshClientModule;\nimport org.jclouds.util.Closeables2;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.BeforeGroups;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.base.Strings;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.Lists;\nimport com.google.common.io.Files;\nimport com.google.common.net.HostAndPort;\nimport com.google.common.util.concurrent.Futures;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.common.util.concurrent.MoreExecutors;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n/**\n * Tests the ability of a {@link JschSshClient}\n */\n@Test(groups = \"live\", testName = \"JschSshClientLiveTest\" )\npublic class JschSshClientLiveTest {\n   protected static final String sshHost = System.getProperty(\"test.ssh.host\", \"localhost\");\n   protected static final String sshPort = System.getProperty(\"test.ssh.port\", \"22\");\n   protected static final String sshUser = System.getProperty(\"test.ssh.username\");\n   protected static final String sshPass = System.getProperty(\"test.ssh.password\");\n   protected static final String sshKeyFile = System.getProperty(\"test.ssh.keyfile\");\n   private File temp;\n\n   @BeforeGroups(groups = { \"live\" })\n   public SshClient setupClient() throws NumberFormatException, FileNotFoundException, IOException {\n      int port = Integer.parseInt(sshPort);\n      if (sshUser == null\n            || ((sshPass == null || sshPass.trim().equals(\"\")) && (sshKeyFile == null || sshKeyFile.trim().equals(\"\")))\n            || sshUser.trim().equals(\"\")) {\n         System.err.println(\"ssh credentials not present.  Tests will be lame\");\n         return new SshClient() {\n\n            public void connect() {\n            }\n\n            public void disconnect() {\n            }\n\n            public boolean isConnected() {\n               return false;\n            }\n\n            public Payload get(String path) {\n               if (path.equals(\"/etc/passwd\")) {\n                  return Payloads.newStringPayload(\"root\");\n               } else if (path.equals(temp.getAbsolutePath())) {\n                  return Payloads.newStringPayload(\"rabbit\");\n               }\n               throw new RuntimeException(\"path \" + path + \" not stubbed\");\n            }\n\n            public ExecResponse exec(String command) {\n               if (command.equals(\"hostname\")) {\n                  return new ExecResponse(sshHost, \"\", 0);\n               }\n               throw new RuntimeException(\"command \" + command + \" not stubbed\");\n            }\n\n            @Override\n            public void put(String path, Payload contents) {\n\n            }\n\n            @Override\n            public String getHostAddress() {\n               return null;\n            }\n\n            @Override\n            public String getUsername() {\n               return null;\n            }\n\n            @Override\n            public void put(String path, String contents) {\n\n            }\n\n            @Override\n            public ExecChannel execChannel(String command) {\n               if (command.equals(\"hostname\")) {\n                  return new ExecChannel(new ByteArrayOutputStream(), new ByteArrayInputStream(sshHost.getBytes()),\n                           new ByteArrayInputStream(new byte[] {}), Suppliers.ofInstance(0), new Closeable() {\n\n                              @Override\n                              public void close() {\n\n                              }\n\n                           });\n               }\n               throw new RuntimeException(\"command \" + command + \" not stubbed\");\n            }\n\n         };\n      } else {\n         Injector i = Guice.createInjector(new JschSshClientModule(), new SLF4JLoggingModule());\n         SshClient.Factory factory = i.getInstance(SshClient.Factory.class);\n         SshClient connection;\n         if (Strings.emptyToNull(sshKeyFile) != null) {\n            connection = factory.create(HostAndPort.fromParts(sshHost, port), LoginCredentials.builder().user(sshUser)\n                  .privateKey(Files.toString(new File(sshKeyFile), Charsets.UTF_8)).build());\n         } else {\n            connection = factory.create(HostAndPort.fromParts(sshHost, port),\n                  LoginCredentials.builder().user(sshUser).password(sshPass).build());\n         }\n         connection.connect();\n         return connection;\n      }\n   }\n\n   @Test\n   public void testPutAndGet() throws IOException {\n      temp = java.nio.file.Files.createTempFile(\"foo\", \"bar\").toFile();\n      try {\n         SshClient client = setupClient();\n         client.put(temp.getAbsolutePath(), Payloads.newStringPayload(\"rabbit\"));\n         Payload input = setupClient().get(temp.getAbsolutePath());\n         String contents = Strings2.toStringAndClose(input.openStream());\n         assertEquals(contents, \"rabbit\");\n      } finally {\n         temp.delete();\n      }\n   }\n\n   @Test\n   public void testGetEtcPassword() throws IOException {\n      Payload input = setupClient().get(\"/etc/passwd\");\n      String contents = Strings2.toStringAndClose(input.openStream());\n      assert contents.indexOf(\"root\") >= 0 : \"no root in \" + contents;\n   }\n\n   @Test\n   public void testExecHostname() throws IOException {\n      SshClient client = setupClient();\n      try {\n         ExecResponse response = client.exec(\"hostname\");\n         assertEquals(response.getExitStatus(), 0);\n         assertEquals(response.getError(), \"\");\n         assertEquals(response.getOutput().trim(), \"localhost\".equals(sshHost) ? InetAddress.getLocalHost().getHostName()\n               : sshHost);\n      } finally {\n         client.disconnect();\n      }\n   }\n\n   @Test\n   public void testExecInvalidCommand() throws IOException {\n      SshClient client = setupClient();\n      try {\n         ExecResponse response = client.exec(\"thisCommandDoesNotExist\");\n         assertNotEquals(response.getExitStatus(), 0);\n         assertTrue(response.getOutput().contains(\"not found\") || response.getError().contains(\"not found\"), \n               \"stdout=\" + response.getOutput() + \"; stderr=\" + response.getError());\n      } finally {\n         client.disconnect();\n      }\n   }\n\n   // Added for issue #1016.\n   @Test(invocationCount = 100)\n   public void testExecHostnameRepeatedlyWithDifferentSessions() throws Exception {\n      testExecHostname();\n   }\n\n   // Added for issue #1016.\n   @Test\n   public void testExecHostnameRepeatedlyWithSameSessions() throws Exception {\n      final SshClient client = setupClient();\n      \n      try {\n         for (int i = 0; i < 100; i++) {\n            ExecResponse response = client.exec(\"hostname\");\n            assertEquals(response.getError(), \"\");\n            assertEquals(response.getOutput().trim(), \"localhost\".equals(sshHost) ? InetAddress.getLocalHost().getHostName()\n                     : sshHost);\n            //System.out.println(\"completed (sequentially) \" + i);\n         }\n      } finally {\n         client.disconnect();\n      }\n   }\n   \n   // Added for issue #1016.\n   // Note that some commands fail the first few attempt, but with default retries at 5 they do pass (for me locally).\n   // The error is \"JSchException: channel is not opened\".\n   // With the thread-pool size at 100, you get failures a lot more often.\n   @Test\n   public void testExecHostnameConcurrentlyWithSameSessions() throws Exception {\n      final SshClient client = setupClient();\n      ListeningExecutorService userExecutor = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10));\n      List<ListenableFuture<ExecResponse>> futures = Lists.newArrayList();\n      try {\n         for (int i = 0; i < 100; i++) {\n            futures.add(userExecutor.submit(new Callable<ExecResponse>() {\n               @Override\n               public ExecResponse call() {\n                  ExecResponse response = client.exec(\"hostname\");\n                  //System.out.println(\"completed (concurrently) \" + count.incrementAndGet());\n                  return response;\n                  \n               }\n            }));\n         }\n         List<ExecResponse> responses = Futures.allAsList(futures).get(3000, TimeUnit.SECONDS);\n         for (ExecResponse response : responses) {\n            assertEquals(response.getError(), \"\");\n            assertEquals(response.getOutput().trim(), \"localhost\".equals(sshHost) ? InetAddress.getLocalHost().getHostName()\n                     : sshHost);\n         }\n      } finally {\n         userExecutor.shutdownNow();\n         client.disconnect();\n      }\n   }\n   \n   @Test\n   public void testExecChannelTakesStdinAndNoEchoOfCharsInOuputAndOutlivesClient() throws IOException {\n      SshClient client = setupClient();\n      ExecChannel response = client.execChannel(\"cat <<EOF\");\n      client.disconnect();\n      assertEquals(response.getExitStatus().get(), null);\n      try {\n         PrintStream printStream = new PrintStream(response.getInput());\n         printStream.append(\"foo\\n\");\n         printStream.append(\"EOF\\n\");\n         printStream.close();\n         assertEquals(Strings2.toStringAndClose(response.getError()), \"\");\n         assertEquals(Strings2.toStringAndClose(response.getOutput()), \"\");\n      } finally {\n         Closeables2.closeQuietly(response);\n      }\n      assertEquals(response.getExitStatus().get(), Integer.valueOf(0));\n   }\n}\n"
  },
  {
    "path": "drivers/jsch/src/test/java/org/jclouds/ssh/jsch/JschSshClientTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ssh.jsch;\n\nimport static com.google.inject.name.Names.bindProperties;\n\nimport java.io.IOException;\nimport java.net.ConnectException;\nimport java.net.UnknownHostException;\nimport java.util.Properties;\n\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.logging.slf4j.config.SLF4JLoggingModule;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.ssh.SshClient;\nimport org.jclouds.ssh.jsch.config.JschSshClientModule;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.net.HostAndPort;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport com.google.inject.Module;\nimport com.jcraft.jsch.ChannelSftp;\nimport com.jcraft.jsch.JSchException;\nimport com.jcraft.jsch.SftpException;\n\n@Test\npublic class JschSshClientTest {\n\n   protected JschSshClient ssh;\n\n   @BeforeTest\n   public void setupSsh() throws UnknownHostException {\n      ssh = createClient(new Properties());\n   }\n\n   protected JschSshClient createClient() throws UnknownHostException {\n      return createClient(new Properties());\n   }\n\n   protected JschSshClient createClient(final Properties props) throws UnknownHostException {\n       Injector i = Guice.createInjector(module(), new AbstractModule() {\n         @Override\n         protected void configure() {\n            bindProperties(binder(), props);\n         }\n      }, new SLF4JLoggingModule());\n      SshClient.Factory factory = i.getInstance(SshClient.Factory.class);\n      JschSshClient ssh = JschSshClient.class.cast(factory.create(HostAndPort.fromParts(\"localhost\", 22), LoginCredentials\n            .builder().user(\"username\").password(\"password\").build()));\n      return ssh;\n   }\n\n   protected Module module() {\n      return new JschSshClientModule();\n   }\n\n   @Test(expectedExceptions = AuthorizationException.class)\n   public void testPropateConvertsAuthException() {\n      ssh.propagate(new JSchException(\"Auth fail\"), \"\");\n   }\n\n   public void testExceptionClassesRetry() {\n      assert ssh.shouldRetry(new JSchException(\"io error\", new IOException(\"socket closed\")));\n      assert ssh.shouldRetry(new JSchException(\"connect error\", new ConnectException(\"problem\")));\n      assert ssh.shouldRetry(new IOException(\"channel is not open\", new NullPointerException()));\n      assert ssh.shouldRetry(new IOException(\"channel is not open\", new NullPointerException(null)));\n   }\n\n   public void testOnlyRetryAuthWhenSet() throws UnknownHostException {\n      JschSshClient ssh1 = createClient();\n      assert !ssh1.shouldRetry(new AuthorizationException(\"problem\", null));\n      ssh1.retryAuth = true;\n      assert ssh1.shouldRetry(new AuthorizationException(\"problem\", null));\n   }\n\n   public void testOnlyRetryAuthWhenSetViaProperties() throws UnknownHostException {\n      Properties props = new Properties();\n      props.setProperty(\"jclouds.ssh.retry-auth\", \"true\");\n      JschSshClient ssh1 = createClient(props);\n      assert ssh1.shouldRetry(new AuthorizationException(\"problem\", null));\n   }\n\n   public void testExceptionMessagesRetry() {\n      assert !ssh.shouldRetry(new NullPointerException(\"\"));\n      assert !ssh.shouldRetry(new NullPointerException((String) null));\n      assert ssh.shouldRetry(new JSchException(\"Session.connect: java.io.IOException: End of IO Stream Read\"));\n      assert ssh.shouldRetry(new JSchException(\"Session.connect: invalid data\"));\n      assert ssh.shouldRetry(new JSchException(\"Session.connect: java.net.SocketException: Connection reset\"));\n   }\n\n   public void testDoNotRetryOnGeneralSftpError() {\n      // http://sourceforge.net/mailarchive/forum.php?thread_name=CAARMrHVhASeku48xoAgWEb-nEpUuYkMA03PoA5TvvFdk%3DjGKMA%40mail.gmail.com&forum_name=jsch-users\n      assert !ssh.shouldRetry(new SftpException(ChannelSftp.SSH_FX_FAILURE, new NullPointerException().toString()));\n   }\n\n   public void testCausalChainHasMessageContaining() {\n      assert ssh.causalChainHasMessageContaining(\n            new JSchException(\"Session.connect: java.io.IOException: End of IO Stream Read\")).apply(\n            \" End of IO Stream Read\");\n      assert ssh.causalChainHasMessageContaining(new JSchException(\"Session.connect: invalid data\")).apply(\n            \" invalid data\");\n      assert ssh.causalChainHasMessageContaining(\n            new JSchException(\"Session.connect: java.net.SocketException: Connection reset\")).apply(\"java.net.Socket\");\n      assert !ssh.causalChainHasMessageContaining(new NullPointerException()).apply(\" End of IO Stream Read\");\n   }\n\n   public void testRetryOnToStringNpe() throws UnknownHostException {\n      Exception nex = new NullPointerException();\n      Properties props = new Properties();\n      // ensure we test toString on the exception independently\n      props.setProperty(\"jclouds.ssh.retryable-messages\", nex.toString());\n      JschSshClient ssh1 = createClient(props);\n      assert ssh1.shouldRetry(new RuntimeException(nex));\n   }\n\n   private static class ExceptionWithStrangeToString extends RuntimeException {\n      private static final String MESSAGE = \"foo-bar-exception-tostring\";\n      public String toString() { return MESSAGE; }\n   }\n\n   public void testRetryOnToStringCustom() throws UnknownHostException {\n      Exception nex = new ExceptionWithStrangeToString();\n      Properties props = new Properties();\n      props.setProperty(\"jclouds.ssh.retryable-messages\", \"foo-bar\");\n      JschSshClient ssh1 = createClient(props);\n      assert ssh1.shouldRetry(new RuntimeException(nex));\n   }\n\n   public void testRetryNotOnToStringCustomMismatch() throws UnknownHostException {\n      Exception nex = new ExceptionWithStrangeToString();\n      Properties props = new Properties();\n      props.setProperty(\"jclouds.ssh.retryable-messages\", \"foo-baR\");\n      JschSshClient ssh1 = createClient(props);\n      assert !ssh1.shouldRetry(new RuntimeException(nex));\n   }\n\n}\n"
  },
  {
    "path": "drivers/jsch/src/test/java/org/jclouds/ssh/jsch/config/JschSshClientModuleTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ssh.jsch.config;\n\nimport java.net.UnknownHostException;\n\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.logging.slf4j.config.SLF4JLoggingModule;\nimport org.jclouds.ssh.SshClient;\nimport org.jclouds.ssh.jsch.JschSshClient;\nimport org.testng.annotations.Test;\n\nimport com.google.common.net.HostAndPort;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n/**\n * Tests the ability to configure a {@link JschSshClient}\n */\n@Test\npublic class JschSshClientModuleTest {\n\n   public void testConfigureBindsClient() throws UnknownHostException {\n\n      Injector i = Guice.createInjector(new JschSshClientModule(), new SLF4JLoggingModule());\n      SshClient.Factory factory = i.getInstance(SshClient.Factory.class);\n      SshClient connection = factory.create(HostAndPort.fromParts(\"localhost\", 22), LoginCredentials.builder().user(\"username\")\n            .password(\"password\").build());\n      assert connection instanceof JschSshClient;\n   }\n}\n"
  },
  {
    "path": "drivers/log4j/README.txt",
    "content": "#\n# A driver to use Log4j (http://logging.apache.org/log4j/) as the logging provider\n# for jclouds. \n#\n# Expects log4j to be present on your application's classpath.\n#\n# TODO: Usage example.\n"
  },
  {
    "path": "drivers/log4j/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.logging.log4j.*;version=\"${project.version}\";-noimport:=true"
  },
  {
    "path": "drivers/log4j/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.driver</groupId>\n  <artifactId>jclouds-log4j</artifactId>\n  <name>jclouds Log4J Logging Module</name>\n  <description>jclouds Log4J Logging Module</description>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.logging.log4j</groupId>\n      <artifactId>log4j-core</artifactId>\n      <scope>compile</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n</project>\n"
  },
  {
    "path": "drivers/log4j/src/main/java/org/jclouds/logging/log4j/Log4JLogger.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.logging.log4j;\n\nimport org.jclouds.logging.BaseLogger;\nimport org.jclouds.logging.Logger;\n\n/**\n * {@link org.apache.log4j.Logger} implementation of {@link Logger}.\n */\npublic class Log4JLogger extends BaseLogger {\n    private final org.apache.logging.log4j.Logger logger;\n    private final String category;\n\n    public static class Log4JLoggerFactory implements LoggerFactory {\n\tpublic Logger getLogger(String category) {\n\t    return new Log4JLogger(category, org.apache.logging.log4j.LogManager\n\t\t    .getLogger(category));\n\t}\n    }\n\n    public Log4JLogger(String category, org.apache.logging.log4j.Logger logger) {\n\tthis.category = category;\n\tthis.logger = logger;\n    }\n\n    @Override\n    protected void logTrace(String message) {\n\tlogger.trace(message);\n    }\n\n    public boolean isTraceEnabled() {\n\treturn logger.isTraceEnabled();\n    }\n\n    @Override\n    protected void logDebug(String message) {\n\tlogger.debug(message);\n    }\n\n    public boolean isDebugEnabled() {\n\treturn logger.isDebugEnabled();\n    }\n\n    @Override\n    protected void logInfo(String message) {\n\tlogger.info(message);\n    }\n\n    public boolean isInfoEnabled() {\n\treturn logger.isInfoEnabled();\n    }\n\n    @Override\n    protected void logWarn(String message) {\n\tlogger.warn(message);\n    }\n\n    @Override\n    protected void logWarn(String message, Throwable e) {\n\tlogger.warn(message, e);\n    }\n\n    public boolean isWarnEnabled() {\n\treturn logger.isWarnEnabled();\n    }\n\n    @Override\n    protected void logError(String message) {\n\tlogger.error(message);\n    }\n\n    @Override\n    protected void logError(String message, Throwable e) {\n\tlogger.error(message, e);\n    }\n\n    public boolean isErrorEnabled() {\n\treturn logger.isErrorEnabled();\n    }\n\n    public String getCategory() {\n\treturn category;\n    }\n}\n"
  },
  {
    "path": "drivers/log4j/src/main/java/org/jclouds/logging/log4j/config/Log4JLoggingModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.logging.log4j.config;\n\nimport org.jclouds.logging.Logger.LoggerFactory;\nimport org.jclouds.logging.config.LoggingModule;\nimport org.jclouds.logging.log4j.Log4JLogger;\n\nimport com.google.auto.service.AutoService;\n\n/**\n * Configures logging of type {@link Log4JLogger}\n */\n@AutoService(LoggingModule.class)\npublic class Log4JLoggingModule extends LoggingModule {\n\n    @Override\n    public LoggerFactory createLoggerFactory() {\n\treturn new Log4JLogger.Log4JLoggerFactory();\n    }\n}\n"
  },
  {
    "path": "drivers/log4j/src/test/java/org/jclouds/logging/log4j/config/Log4JLoggingModuleTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.logging.log4j.config;\n\nimport static org.testng.Assert.assertEquals;\n\nimport jakarta.annotation.Resource;\n\nimport org.jclouds.logging.Logger;\nimport org.jclouds.logging.log4j.Log4JLogger;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test\npublic class Log4JLoggingModuleTest {\n\n    static class A {\n\t@Resource\n\tLogger logger = Logger.NULL;\n    }\n\n    @Test\n    public void testConfigure() {\n\tInjector i = Guice.createInjector(new Log4JLoggingModule());\n\tA a = i.getInstance(A.class);\n\tassertEquals(a.logger.getClass(), Log4JLogger.class);\n\tassertEquals(a.logger.getCategory(), getClass().getName() + \"$A\");\n    }\n\n}\n"
  },
  {
    "path": "drivers/log4j/src/test/resources/log4j.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE log4j:configuration SYSTEM \"log4j.dtd\">\n\n    <!--\n        For more configuration infromation and examples see the Apache\n        Log4j website: http://logging.apache.org/log4j/\n    -->\n<log4j:configuration xmlns:log4j=\"http://jakarta.apache.org/log4j/\"\n    debug=\"false\">\n\n    <!-- A time/date based rolling appender -->\n    <appender name=\"WIREFILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds-wire.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n\n    <!-- A time/date based rolling appender -->\n    <appender name=\"FILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n\n    <appender name=\"ASYNC\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"FILE\" />\n    </appender>\n\n    <appender name=\"ASYNCWIRE\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"WIREFILE\" />\n    </appender>\n\n    <!-- ================ -->\n    <!-- Limit categories -->\n    <!-- ================ -->\n\n    <category name=\"org.jclouds\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNC\" />\n    </category>\n\n    <category name=\"jclouds.headers\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNCWIRE\" />\n    </category>\n\n    <category name=\"jclouds.wire\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNCWIRE\" />\n    </category>\n\n    <!-- ======================= -->\n    <!-- Setup the Root category -->\n    <!-- ======================= -->\n\n    <root>\n        <priority value=\"WARN\" />\n    </root>\n\n</log4j:configuration>\n"
  },
  {
    "path": "drivers/okhttp/README.md",
    "content": "jclouds OkHttp driver\n=====================\n\nA driver to use the OkHttp (http://square.github.io/okhttp/) client as an HTTP library in jclouds.\n\nTo use the driver, you just need to include the `OkHttpCommandExecutorServiceModule` when creating\nthe context:\n\n    ContextBuilder.newBuilder(\"provider\")\n        .endpoint(\"endpoint\")\n        .credentials(\"identity\", \"credential\")\n        .modules(ImmutableSet.of(new OkHttpCommandExecutorServiceModule()))\n        .build();\n"
  },
  {
    "path": "drivers/okhttp/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.http.okhttp.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "drivers/okhttp/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.driver</groupId>\n  <artifactId>jclouds-okhttp</artifactId>\n  <name>jclouds OkHttp Driver</name>\n  <description>OkHttp Driver</description>\n\n  <properties>\n    <okio.version>3.4.0</okio.version>\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.squareup.okhttp3</groupId>\n      <artifactId>okhttp</artifactId>\n      <version>${okhttp.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>com.squareup.okio</groupId>\n      <artifactId>okio</artifactId>\n      <version>${okio.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>com.squareup.okhttp3</groupId>\n      <artifactId>mockwebserver</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.squareup.okhttp3</groupId>\n      <artifactId>okhttp-tls</artifactId>\n      <scope>test</scope>\n    </dependency>\n  </dependencies>\n\n</project>\n"
  },
  {
    "path": "drivers/okhttp/src/main/java/org/jclouds/http/okhttp/DelegatingSocketFactory.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.okhttp;\n\nimport java.io.IOException;\nimport java.net.InetAddress;\nimport java.net.Socket;\n\nimport javax.net.SocketFactory;\n\n/**\n * The {@code DelegatingSocketFactory} class delegates instance of\n * SSLSocketFactory to SocketFactory.\n * \n * <p>\n * Note:\n * {@link okhttp3.OkHttpClient.Builder#sslSocketFactory(javax.net.ssl.SSLSocketFactory)}\n * method deprecated.\n * \n * <p>\n * Note: {@link okhttp3.OkHttpClient.Builder#socketFactory(SocketFactory)}\n * method doesn't accept {@code javax.net.ssl.SSLSocketFactory.getDefault()} at\n * runtime, throws {@code java.lang.IllegalArgumentException}.\n * \n */\npublic class DelegatingSocketFactory extends SocketFactory {\n\tprivate final SocketFactory delegate;\n\n\tpublic DelegatingSocketFactory(SocketFactory delegate) {\n\t\tthis.delegate = delegate;\n\t}\n\n\t@Override\n\tpublic Socket createSocket() throws IOException {\n\t\tSocket socket = delegate.createSocket();\n\t\treturn configureSocket(socket);\n\t}\n\n\t@Override\n\tpublic Socket createSocket(String host, int port) throws IOException {\n\t\tSocket socket = delegate.createSocket(host, port);\n\t\treturn configureSocket(socket);\n\t}\n\n\t@Override\n\tpublic Socket createSocket(String host, int port, InetAddress localAddress, int localPort) throws IOException {\n\t\tSocket socket = delegate.createSocket(host, port, localAddress, localPort);\n\t\treturn configureSocket(socket);\n\t}\n\n\t@Override\n\tpublic Socket createSocket(InetAddress host, int port) throws IOException {\n\t\tSocket socket = delegate.createSocket(host, port);\n\t\treturn configureSocket(socket);\n\t}\n\n\t@Override\n\tpublic Socket createSocket(InetAddress host, int port, InetAddress localAddress, int localPort) throws IOException {\n\t\tSocket socket = delegate.createSocket(host, port, localAddress, localPort);\n\t\treturn configureSocket(socket);\n\t}\n\n\tprotected Socket configureSocket(Socket socket) throws IOException {\n\t\t// No-op by default.\n\t\treturn socket;\n\t}\n}\n"
  },
  {
    "path": "drivers/okhttp/src/main/java/org/jclouds/http/okhttp/OkHttpClientSupplier.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.okhttp;\n\nimport okhttp3.OkHttpClient;\n\nimport org.jclouds.http.okhttp.OkHttpClientSupplier.NewOkHttpClient;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Supplier;\nimport com.google.inject.ImplementedBy;\n\n\n/**\n * Provides the OkHttp client used for all requests. This could be used to\n * designate a custom SSL context or limit TLS ciphers.\n * <p>\n * Note that it should configured it in the Guice module designated as\n * <code>@ConfiguresHttpApi</code>.\n */\n@Beta\n@ImplementedBy(NewOkHttpClient.class)\npublic interface OkHttpClientSupplier extends Supplier<OkHttpClient> {\n\n   static final class NewOkHttpClient implements OkHttpClientSupplier {\n      @Override\n      public OkHttpClient get() {\n         return new OkHttpClient();\n      }\n   }\n}\n"
  },
  {
    "path": "drivers/okhttp/src/main/java/org/jclouds/http/okhttp/OkHttpCommandExecutorService.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.okhttp;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.net.HttpHeaders.ACCEPT;\nimport static com.google.common.net.HttpHeaders.USER_AGENT;\nimport static org.jclouds.Constants.PROPERTY_IDEMPOTENT_METHODS;\nimport static org.jclouds.Constants.PROPERTY_USER_AGENT;\nimport static org.jclouds.http.HttpUtils.filterOutContentHeaders;\nimport static org.jclouds.io.Payloads.newInputStreamPayload;\n\nimport java.io.IOException;\nimport java.net.Proxy;\nimport java.net.URI;\nimport java.util.Map;\n\nimport jakarta.inject.Named;\nimport javax.net.ssl.SSLSocketFactory;\n\nimport okhttp3.Authenticator;\nimport okhttp3.Credentials;\nimport okhttp3.internal.http.HttpMethod;\nimport okhttp3.Headers;\nimport okhttp3.MediaType;\nimport okhttp3.OkHttpClient;\nimport okhttp3.Request;\nimport okhttp3.Route;\nimport okhttp3.RequestBody;\nimport okhttp3.Response;\n\nimport okio.BufferedSink;\nimport okio.Okio;\nimport okio.Source;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpUtils;\nimport org.jclouds.http.IOExceptionRetryHandler;\nimport org.jclouds.http.handlers.DelegatingErrorHandler;\nimport org.jclouds.http.handlers.DelegatingRetryHandler;\nimport org.jclouds.http.internal.BaseHttpCommandExecutorService;\nimport org.jclouds.http.internal.HttpWire;\nimport org.jclouds.io.ContentMetadataCodec;\nimport org.jclouds.io.MutableContentMetadata;\nimport org.jclouds.io.Payload;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.proxy.internal.GuiceProxyConfig;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableMultimap.Builder;\nimport com.google.inject.Inject;\n\n\npublic final class OkHttpCommandExecutorService extends BaseHttpCommandExecutorService<Request> {\n   private final Function<URI, Proxy> proxyForURI;\n   private final OkHttpClient globalClient;\n   private final String userAgent;\n   private final GuiceProxyConfig proxyConfig;\n\n   @Inject\n   OkHttpCommandExecutorService(HttpUtils utils, ContentMetadataCodec contentMetadataCodec,\n         DelegatingRetryHandler retryHandler, IOExceptionRetryHandler ioRetryHandler,\n         DelegatingErrorHandler errorHandler, HttpWire wire, Function<URI, Proxy> proxyForURI, OkHttpClient okHttpClient,\n         @Named(PROPERTY_IDEMPOTENT_METHODS) String idempotentMethods,\n         @Named(PROPERTY_USER_AGENT) String userAgent, GuiceProxyConfig proxyConfig) {\n      super(utils, contentMetadataCodec, retryHandler, ioRetryHandler, errorHandler, wire, idempotentMethods);\n      this.proxyForURI = proxyForURI;\n      this.globalClient = okHttpClient;\n      this.userAgent = userAgent;\n\t  this.proxyConfig = proxyConfig;\n   }\n\n   @Override\n   protected Request convert(HttpRequest request) throws IOException, InterruptedException {\n      Request.Builder builder = new Request.Builder();\n\n      builder.url(request.getEndpoint().toString());\n      populateHeaders(request, builder);\n\n      RequestBody body = null;\n      Payload payload = request.getPayload();\n\n      if (payload != null) {\n         Long length = checkNotNull(payload.getContentMetadata().getContentLength(), \"payload.getContentLength\");\n         if (length > 0) {\n            body = generateRequestBody(request, payload);\n         }\n      }\n\n      // OkHttp requires body (at least empty one) for some type of the requests, so let's generate it\n      if (body == null && HttpMethod.requiresRequestBody(request.getMethod())) {\n         body = generateEmptyRequestBody(payload);\n      }\n\n      builder.method(request.getMethod(), body);\n\n      return builder.build();\n   }\n\n   protected void populateHeaders(HttpRequest request, Request.Builder builder) {\n      // OkHttp does not set the Accept header if not present in the request.\n      // Make sure we send a flexible one.\n      if (request.getFirstHeaderOrNull(ACCEPT) == null) {\n         builder.addHeader(ACCEPT, \"*/*\");\n      }\n      if (request.getFirstHeaderOrNull(USER_AGENT) == null) {\n         builder.addHeader(USER_AGENT, userAgent);\n      }\n      for (Map.Entry<String, String> entry : request.getHeaders().entries()) {\n         builder.addHeader(entry.getKey(), entry.getValue());\n      }\n      if (request.getPayload() != null) {\n         MutableContentMetadata md = request.getPayload().getContentMetadata();\n         for (Map.Entry<String, String> entry : contentMetadataCodec.toHeaders(md).entries()) {\n            builder.addHeader(entry.getKey(), entry.getValue());\n         }\n      }\n   }\n\n   private RequestBody generateEmptyRequestBody(final Payload payload) {\n      return new RequestBody() {\n         @Nullable @Override public MediaType contentType() {\n            return payload != null ? MediaType.parse(payload.getContentMetadata().getContentType()) : null;\n         }\n\n         @Override public void writeTo(BufferedSink sink) throws IOException {\n            // nothing to do\n         }\n\n         @Override public long contentLength() throws IOException {\n            return 0;\n         }\n      };\n   }\n\n   protected RequestBody generateRequestBody(final HttpRequest request, final Payload payload) {\n      checkNotNull(payload.getContentMetadata().getContentType(), \"payload.getContentType\");\n      return new RequestBody() {\n         @Override\n         public void writeTo(BufferedSink sink) throws IOException {\n            Source source = Okio.source(payload.openStream());\n            try {\n               sink.writeAll(source);\n            } catch (IOException ex) {\n               logger.error(ex, \"error writing bytes to %s\", request.getEndpoint());\n               throw ex;\n            } finally {\n               source.close();\n            }\n         }\n\n         @Override\n         public long contentLength() throws IOException {\n            return payload.getContentMetadata().getContentLength();\n         }\n\n         @Override\n         public MediaType contentType() {\n            return MediaType.parse(payload.getContentMetadata().getContentType());\n         }\n      };\n   }\n\n   @Override\n   protected HttpResponse invoke(Request nativeRequest) throws IOException, InterruptedException {\n\t   \n\t  OkHttpClient.Builder okHttpClientBuilder = globalClient.newBuilder()\n\t\t\t\t.proxy(proxyForURI.apply(nativeRequest.url().uri()));\n\t\t\n\t\tif (proxyConfig.getCredentials().isPresent()) {\n\t\t\tAuthenticator proxyAuthenticator = new Authenticator() {\n\t\t\t\t@Override\n\t\t\t\tpublic Request authenticate(Route route, Response response) throws IOException {\n\t\t\t\t\tif (response != null && response.code() == 407\n\t\t\t\t\t\t\t&& !response.message().toLowerCase().contains(\"preemptive authenticate\")) {\n\t\t\t\t\t\treturn null;\n\t\t\t\t\t}\n\t\t\t\t\tString credential = Credentials.basic(proxyConfig.getCredentials().get().identity,\n\t\t\t\t\t\t\tproxyConfig.getCredentials().get().credential);\n\t\t\t\t\treturn response.request().newBuilder().header(\"Proxy-Authorization\", credential).build();\n\t\t\t\t}\n\t\t\t};\n\t\t\tokHttpClientBuilder.proxyAuthenticator(proxyAuthenticator);\n\t\t}\n\t\t\n\t\tif (proxyConfig.isSslProxyEnabled()) {\n\t\t\tokHttpClientBuilder.socketFactory(new DelegatingSocketFactory(SSLSocketFactory.getDefault()));\n\t\t}\n\t  OkHttpClient requestScopedClient = okHttpClientBuilder.build();\n\t  \n      Response response = requestScopedClient.newCall(nativeRequest).execute();\n\n      HttpResponse.Builder<?> builder = HttpResponse.builder();\n      builder.statusCode(response.code());\n      builder.message(response.message());\n\n      Builder<String, String> headerBuilder = ImmutableMultimap.builder();\n      Headers responseHeaders = response.headers();\n      for (String header : responseHeaders.names()) {\n         headerBuilder.putAll(header, responseHeaders.values(header));\n      }\n\n      ImmutableMultimap<String, String> headers = headerBuilder.build();\n\n      if (response.code() == 204 && response.body() != null) {\n         response.body().close();\n      } else {\n         Payload payload = newInputStreamPayload(response.body().byteStream());\n         contentMetadataCodec.fromHeaders(payload.getContentMetadata(), headers);\n         builder.payload(payload);\n      }\n\n      builder.headers(filterOutContentHeaders(headers));\n\n      return builder.build();\n   }\n\n   @Override\n   protected void cleanup(Request nativeResponse) {\n\n   }\n\n}\n"
  },
  {
    "path": "drivers/okhttp/src/main/java/org/jclouds/http/okhttp/config/OkHttpCommandExecutorServiceModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.okhttp.config;\n\nimport java.util.concurrent.TimeUnit;\n\nimport jakarta.inject.Named;\nimport javax.net.ssl.HostnameVerifier;\nimport javax.net.ssl.SSLContext;\nimport javax.net.ssl.X509TrustManager;\n\nimport okhttp3.OkHttpClient;\n\nimport org.jclouds.http.HttpCommandExecutorService;\nimport org.jclouds.http.HttpUtils;\nimport org.jclouds.http.config.ConfiguresHttpCommandExecutorService;\nimport org.jclouds.http.config.SSLModule;\nimport org.jclouds.http.okhttp.OkHttpClientSupplier;\nimport org.jclouds.http.okhttp.OkHttpCommandExecutorService;\n\nimport com.google.common.base.Supplier;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Inject;\nimport com.google.inject.Provider;\nimport com.google.inject.Scopes;\n\n\n/**\n * Configures the {@link OkHttpCommandExecutorService}.\n *\n * Note that this uses threads.\n */\n@ConfiguresHttpCommandExecutorService\npublic class OkHttpCommandExecutorServiceModule extends AbstractModule {\n\n   @Override\n   protected void configure() {\n      install(new SSLModule());\n      bind(HttpCommandExecutorService.class).to(OkHttpCommandExecutorService.class).in(Scopes.SINGLETON);\n      bind(OkHttpClient.class).toProvider(OkHttpClientProvider.class).in(Scopes.SINGLETON);\n   }\n\n   private static final class OkHttpClientProvider implements Provider<OkHttpClient> {\n      private final HostnameVerifier verifier;\n      private final Supplier<SSLContext> untrustedSSLContextProvider;\n      private final X509TrustManager trustAllCertsManager;\n      private final HttpUtils utils;\n      private final OkHttpClientSupplier clientSupplier;\n\n      @Inject\n      OkHttpClientProvider(HttpUtils utils, @Named(\"untrusted\") HostnameVerifier verifier,\n            @Named(\"untrusted\") Supplier<SSLContext> untrustedSSLContextProvider,\n            @Named(\"untrusted\") X509TrustManager trustAllCertsManager,\n            OkHttpClientSupplier clientSupplier) {\n         this.utils = utils;\n         this.verifier = verifier;\n         this.untrustedSSLContextProvider = untrustedSSLContextProvider;\n         this.trustAllCertsManager = trustAllCertsManager;\n         this.clientSupplier = clientSupplier;\n      }\n\n      @Override\n      public OkHttpClient get() {\n         OkHttpClient.Builder clientBuilder = clientSupplier.get().newBuilder()\n            .connectTimeout(utils.getConnectionTimeout(), TimeUnit.MILLISECONDS)\n            .readTimeout(utils.getSocketOpenTimeout(), TimeUnit.MILLISECONDS)\n            // do not follow redirects since https redirects don't work properly\n            // ex. Caused by: java.io.IOException: HTTPS hostname wrong: should be\n            // <adriancole.s3int0.s3-external-3.amazonaws.com>\n            .followRedirects(false);\n\n         if (utils.relaxHostname()) {\n            clientBuilder.hostnameVerifier(verifier);\n         }\n         if (utils.trustAllCerts()) {\n            clientBuilder.sslSocketFactory(untrustedSSLContextProvider.get().getSocketFactory(), trustAllCertsManager);\n         }\n\n         return clientBuilder.build();\n      }\n   }\n\n}\n"
  },
  {
    "path": "drivers/okhttp/src/test/java/org/jclouds/http/okhttp/OkHttpCommandExecutorServiceTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.http.okhttp;\n\nimport static org.jclouds.Constants.PROPERTY_MAX_CONNECTIONS_PER_CONTEXT;\nimport static org.jclouds.Constants.PROPERTY_MAX_CONNECTIONS_PER_HOST;\nimport static org.jclouds.Constants.PROPERTY_USER_THREADS;\nimport static org.jclouds.util.Closeables2.closeQuietly;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.io.Closeable;\nimport java.io.IOException;\nimport java.util.List;\nimport java.util.Properties;\n\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\n\nimport okhttp3.ConnectionSpec;\nimport okhttp3.OkHttpClient;\nimport okhttp3.TlsVersion;\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\nimport okhttp3.mockwebserver.RecordedRequest;\n\nimport org.jclouds.http.BaseHttpCommandExecutorServiceIntegrationTest;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.http.config.ConfiguresHttpCommandExecutorService;\nimport org.jclouds.http.okhttp.config.OkHttpCommandExecutorServiceModule;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.PATCH;\nimport org.jclouds.rest.binders.BindToStringPayload;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Module;\n\n\n/**\n * Tests the functionality of the {@link OkHttpCommandExecutorService}\n */\n@Test\npublic class OkHttpCommandExecutorServiceTest extends BaseHttpCommandExecutorServiceIntegrationTest {\n\n   @Override\n   protected Module createConnectionModule() {\n      return new OkHttpCommandExecutorServiceModule();\n   }\n\n   @Override\n   protected void addOverrideProperties(final Properties props) {\n      props.setProperty(PROPERTY_MAX_CONNECTIONS_PER_CONTEXT, 50 + \"\");\n      props.setProperty(PROPERTY_MAX_CONNECTIONS_PER_HOST, 0 + \"\");\n      props.setProperty(PROPERTY_USER_THREADS, 5 + \"\");\n   }\n\n   private interface PatchApi extends Closeable {\n      @PATCH\n      @Path(\"/objects/{id}\")\n      @Produces(\"text/plain\")\n      String patch(@PathParam(\"id\") String id, @BinderParam(BindToStringPayload.class) String body);\n\n      @PATCH\n      @Path(\"/objects/{id}\")\n      String patchNothing(@PathParam(\"id\") String id);\n   }\n\n   @Test\n   public void testPatch() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(\"fooPATCH\"));\n      PatchApi api = api(PatchApi.class, server.url(\"/\").toString());\n      try {\n         String result = api.patch(\"\", \"foo\");\n         // Verify that the body is properly populated\n         RecordedRequest request = server.takeRequest();\n         assertEquals(request.getMethod(), \"PATCH\");\n         assertEquals(request.getBody().readUtf8(), \"foo\");\n         assertEquals(result, \"fooPATCH\");\n         // Verify content headers are sent\n         assertNotNull(request.getHeader(\"Content-Type\"));\n         assertNotNull(request.getHeader(\"Content-Length\"));\n         assertEquals(request.getHeader(\"Content-Type\"), \"text/plain\");\n         assertEquals(Integer.valueOf(request.getHeader(\"Content-Length\")).intValue(), \"foo\".getBytes().length);\n      } finally {\n         closeQuietly(api);\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testPatchIsRetriedOnFailure() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(500),\n            new MockResponse().setBody(\"fooPATCH\"));\n      PatchApi api = api(PatchApi.class, server.url(\"/\").toString());\n      try {\n         String result = api.patch(\"\", \"foo\");\n         assertEquals(server.getRequestCount(), 2);\n         assertEquals(result, \"fooPATCH\");\n         // Verify that the body was properly sent in the two requests\n         RecordedRequest request = server.takeRequest();\n         assertEquals(request.getMethod(), \"PATCH\");\n         assertEquals(request.getBody().readUtf8(), \"foo\");\n         request = server.takeRequest();\n         assertEquals(request.getMethod(), \"PATCH\");\n         assertEquals(request.getBody().readUtf8(), \"foo\");\n      } finally {\n         closeQuietly(api);\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testPatchRedirect() throws Exception {\n      MockWebServer redirectTarget = mockWebServer(new MockResponse().setBody(\"fooPATCHREDIRECT\"));\n      redirectTarget.useHttps(sslSocketFactory(), false);\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(302).setHeader(\"Location\",\n            redirectTarget.url(\"/\").toString()));\n      PatchApi api = api(PatchApi.class, server.url(\"/\").toString());\n      try {\n         String result = api.patch(\"\", \"foo\");\n         assertEquals(result, \"fooPATCHREDIRECT\");\n         assertEquals(server.getRequestCount(), 1);\n         assertEquals(redirectTarget.getRequestCount(), 1);\n         // Verify that the body was populated after the redirect\n         RecordedRequest request = server.takeRequest();\n         assertEquals(request.getMethod(), \"PATCH\");\n         assertEquals(request.getBody().readUtf8(), \"foo\");\n         request = redirectTarget.takeRequest();\n         assertEquals(request.getMethod(), \"PATCH\");\n         assertEquals(request.getBody().readUtf8(), \"foo\");\n      } finally {\n         closeQuietly(api);\n         redirectTarget.shutdown();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testZeroLengthPatch() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse());\n      PatchApi api = api(PatchApi.class, server.url(\"/\").toString());\n      try {\n         api.patchNothing(\"\");\n         assertEquals(server.getRequestCount(), 1);\n         RecordedRequest request = server.takeRequest();\n         assertEquals(request.getMethod(), \"PATCH\");\n         assertEquals(request.getBody().readUtf8(), \"\");\n      } finally {\n         closeQuietly(api);\n         server.shutdown();\n      }\n   }\n\n   @Test(expectedExceptions = HttpResponseException.class, expectedExceptionsMessageRegExp = \"Unable to find acceptable protocols.*\")\n   public void testSSLConnectionFailsIfOnlyHttpConfigured() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse());\n      server.useHttps(sslSocketFactory(), false);\n      Module httpConfigModule = new ConnectionSpecModule(ConnectionSpec.CLEARTEXT);\n      PatchApi api = api(PatchApi.class, server.url(\"/\").toString(), httpConfigModule);\n      try {\n         api.patchNothing(\"\");\n      } finally {\n         closeQuietly(api);\n         server.shutdown();\n      }\n   }\n\n   @Test(expectedExceptions = HttpResponseException.class, expectedExceptionsMessageRegExp = \"CLEARTEXT communication not enabled for client.*\")\n   public void testHTTPConnectionFailsIfOnlySSLConfigured() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse());\n      Module httpConfigModule = new ConnectionSpecModule(ConnectionSpec.MODERN_TLS);\n      PatchApi api = api(PatchApi.class, server.url(\"/\").toString(), httpConfigModule);\n      try {\n         api.patchNothing(\"\");\n      } finally {\n         closeQuietly(api);\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testBothProtocolsSucceedIfSSLAndHTTPConfigured() throws Exception {\n      MockWebServer redirectTarget = mockWebServer(new MockResponse());\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(302).setHeader(\"Location\",\n            redirectTarget.url(\"/\").toString()));\n      server.useHttps(sslSocketFactory(), false);\n      Module httpConfigModule = new ConnectionSpecModule(ConnectionSpec.CLEARTEXT, ConnectionSpec.MODERN_TLS);\n      PatchApi api = api(PatchApi.class, server.url(\"/\").toString(), httpConfigModule);\n      try {\n         api.patchNothing(\"\");\n         assertEquals(server.getRequestCount(), 1);\n         assertEquals(redirectTarget.getRequestCount(), 1);\n      } finally {\n         closeQuietly(api);\n         server.shutdown();\n         redirectTarget.shutdown();\n      }\n   }\n\n   @Test\n   public void testRestrictedSSLProtocols() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse());\n      server.useHttps(sslSocketFactory(), false);\n      ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS).tlsVersions(TlsVersion.TLS_1_2)\n            .build();\n      PatchApi api = api(PatchApi.class, server.url(\"/\").toString(), new ConnectionSpecModule(spec));\n      try {\n         api.patchNothing(\"\");\n         assertEquals(server.getRequestCount(), 1);\n         RecordedRequest request = server.takeRequest();\n         assertEquals(request.getTlsVersion().javaName(), \"TLSv1.2\");\n      } finally {\n         closeQuietly(api);\n         server.shutdown();\n      }\n   }\n\n   protected static MockWebServer mockWebServer(MockResponse... responses) throws IOException {\n      MockWebServer server = new MockWebServer();\n      server.start(null, 0);\n      for (MockResponse response : responses) {\n         server.enqueue(response);\n      }\n      return server;\n   }\n\n   @ConfiguresHttpCommandExecutorService\n   private static final class ConnectionSpecModule extends AbstractModule {\n      private final List<ConnectionSpec> connectionSpecs;\n\n      public ConnectionSpecModule(ConnectionSpec... connectionSpecs) {\n         this.connectionSpecs = ImmutableList.copyOf(connectionSpecs);\n      }\n\n      @Override\n      protected void configure() {\n         install(new OkHttpCommandExecutorServiceModule());\n         bind(OkHttpClientSupplier.class).toInstance(new OkHttpClientSupplier() {\n            @Override\n            public OkHttpClient get() {\n               return new OkHttpClient.Builder()\n                   .connectionSpecs(connectionSpecs)\n                   .build();\n            }\n         });\n      }\n   }\n\n}\n"
  },
  {
    "path": "drivers/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <artifactId>jclouds-project</artifactId>\n    <groupId>org.apache.jclouds</groupId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../project/pom.xml</relativePath>\n  </parent>\n  <artifactId>jclouds-drivers-project</artifactId>\n  <packaging>pom</packaging>\n  <name>jclouds drivers project</name>\n  <modules>\n    <module>apachehc</module>\n    <module>bouncycastle</module>\n    <module>enterprise</module>\n    <module>joda</module>\n    <module>jsch</module>\n    <module>log4j</module>\n    <module>okhttp</module>\n    <module>slf4j</module>\n    <module>sshj</module>\n  </modules>\n</project>\n"
  },
  {
    "path": "drivers/slf4j/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.logging.slf4j.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "drivers/slf4j/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.driver</groupId>\n  <artifactId>jclouds-slf4j</artifactId>\n  <name>jclouds SLF4J Logging Module</name>\n  <description>jclouds SLF4J Logging Module</description>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.slf4j</groupId>\n      <artifactId>slf4j-api</artifactId>\n      <version>1.7.2</version>\n      <scope>compile</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n</project>\n"
  },
  {
    "path": "drivers/slf4j/src/main/java/org/jclouds/logging/slf4j/SLF4JLogger.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.logging.slf4j;\n\nimport org.jclouds.logging.BaseLogger;\nimport org.jclouds.logging.Logger;\n\n/**\n * {@link org.slf4j.LoggerFactory} implementation of {@link Logger}.\n */\npublic class SLF4JLogger extends BaseLogger {\n   static {\n      // force initialization to avoid http://www.slf4j.org/codes.html#substituteLogger messages\n      org.slf4j.LoggerFactory.getILoggerFactory();\n   }\n   \n   private final org.slf4j.Logger logger;\n   private final String category;\n\n   public static class SLF4JLoggerFactory implements LoggerFactory {\n      public Logger getLogger(String category) {\n         return new SLF4JLogger(category, org.slf4j.LoggerFactory.getLogger(category));\n      }\n   }\n\n   public SLF4JLogger(String category, org.slf4j.Logger logger) {\n      this.category = category;\n      this.logger = logger;\n   }\n\n   @Override\n   protected void logTrace(String message) {\n      logger.trace(message);\n   }\n\n   public boolean isTraceEnabled() {\n      return logger.isTraceEnabled();\n   }\n\n   @Override\n   protected void logDebug(String message) {\n      logger.debug(message);\n   }\n\n   public boolean isDebugEnabled() {\n      return logger.isDebugEnabled();\n   }\n\n   @Override\n   protected void logInfo(String message) {\n      logger.info(message);\n   }\n\n   public boolean isInfoEnabled() {\n      return logger.isInfoEnabled();\n   }\n\n   @Override\n   protected void logWarn(String message) {\n      logger.warn(message);\n   }\n\n   @Override\n   protected void logWarn(String message, Throwable e) {\n      logger.warn(message, e);\n   }\n\n   public boolean isWarnEnabled() {\n      return logger.isWarnEnabled();\n   }\n\n   @Override\n   protected void logError(String message) {\n      logger.error(message);\n   }\n\n   @Override\n   protected void logError(String message, Throwable e) {\n      logger.error(message, e);\n   }\n\n   public boolean isErrorEnabled() {\n      return logger.isErrorEnabled();\n   }\n\n   public String getCategory() {\n      return category;\n   }\n}\n"
  },
  {
    "path": "drivers/slf4j/src/main/java/org/jclouds/logging/slf4j/config/SLF4JLoggingModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.logging.slf4j.config;\n\nimport org.jclouds.logging.Logger.LoggerFactory;\nimport org.jclouds.logging.config.LoggingModule;\nimport org.jclouds.logging.slf4j.SLF4JLogger;\n\nimport com.google.auto.service.AutoService;\n\n/**\n * Configures logging of type {@link SLF4JLogger}\n */\n@AutoService(LoggingModule.class)\npublic class SLF4JLoggingModule extends LoggingModule {\n\n    @Override\n    public LoggerFactory createLoggerFactory() {\n\treturn new SLF4JLogger.SLF4JLoggerFactory();\n    }\n}\n"
  },
  {
    "path": "drivers/slf4j/src/test/java/org/jclouds/logging/slf4j/config/SLF4JLoggingModuleTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.logging.slf4j.config;\n\nimport static org.testng.Assert.assertEquals;\n\nimport jakarta.annotation.Resource;\n\nimport org.jclouds.logging.Logger;\nimport org.jclouds.logging.slf4j.SLF4JLogger;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test\npublic class SLF4JLoggingModuleTest {\n\n   static class A {\n      @Resource\n      Logger logger = Logger.NULL;\n   }\n\n   @Test\n   public void testConfigure() {\n      Injector i = Guice.createInjector(new SLF4JLoggingModule());\n      A a = i.getInstance(A.class);\n      assertEquals(a.logger.getClass(), SLF4JLogger.class);\n      assertEquals(a.logger.getCategory(), getClass().getName() + \"$A\");\n   }\n\n}\n"
  },
  {
    "path": "drivers/sshj/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.sshj.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "drivers/sshj/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.driver</groupId>\n  <artifactId>jclouds-sshj</artifactId>\n  <name>jclouds sshj ssh client</name>\n  <description>jclouds sshj ssh client</description>\n\n  <properties>\n    <test.ssh.host>localhost</test.ssh.host>\n    <test.ssh.port>22</test.ssh.port>\n    <test.ssh.username />\n    <test.ssh.password />\n    <test.ssh.keyfile />\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-slf4j</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>ch.qos.logback</groupId>\n      <artifactId>logback-classic</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-bouncycastle</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.hierynomus</groupId>\n      <artifactId>sshj</artifactId>\n      <version>0.27.0</version>\n      <exclusions>\n        <!-- provided by the jclouds-bouncycastle driver -->\n        <exclusion>\n          <groupId>org.bouncycastle</groupId>\n          <artifactId>bcprov-jdk15on</artifactId>\n        </exclusion>\n      </exclusions>\n    </dependency>\n    <dependency>\n      <groupId>com.jcraft</groupId>\n      <artifactId>jsch.agentproxy.sshj</artifactId>\n      <version>0.0.9</version>\n      <exclusions>\n        <!-- required due to sshj group ID change -->\n        <exclusion>\n          <groupId>net.schmizz</groupId>\n          <artifactId>sshj</artifactId>\n        </exclusion>\n      </exclusions>\n    </dependency>\n    <dependency>\n      <groupId>com.jcraft</groupId>\n      <artifactId>jsch.agentproxy.connector-factory</artifactId>\n      <version>0.0.9</version>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <!-- note that the groups/excluded groups don't work due to some problem\n                       in surefire or testng. instead, we have to exclude via file path\n                       <groups>live,integration</groups>\n                       <excludedGroups>unit,performance</excludedGroups> -->\n                  <excludes>\n                    <exclude>none</exclude>\n                  </excludes>\n                  <includes>\n                    <include>**/*IntegrationTest.java</include>\n                    <include>**/*LiveTest.java</include>\n                  </includes>\n                  <systemPropertyVariables>\n                    <file.encoding>UTF-8</file.encoding>\n                    <test.ssh.host>${test.ssh.host}</test.ssh.host>\n                    <test.ssh.port>${test.ssh.port}</test.ssh.port>\n                    <test.ssh.username>${test.ssh.username}</test.ssh.username>\n                    <test.ssh.keyfile>${test.ssh.keyfile}</test.ssh.keyfile>\n                    <test.ssh.password>${test.ssh.password}</test.ssh.password>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n</project>\n"
  },
  {
    "path": "drivers/sshj/src/main/java/org/jclouds/sshj/SSHClientConnection.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sshj;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.io.IOException;\nimport java.util.List;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\n\nimport net.schmizz.sshj.SSHClient;\nimport net.schmizz.sshj.common.Buffer.BufferException;\nimport net.schmizz.sshj.transport.verification.PromiscuousVerifier;\nimport net.schmizz.sshj.userauth.keyprovider.OpenSSHKeyFile;\nimport net.schmizz.sshj.userauth.method.AuthMethod;\n\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.sshj.SshjSshClient.Connection;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.net.HostAndPort;\n\nimport com.jcraft.jsch.agentproxy.AgentProxy;\nimport com.jcraft.jsch.agentproxy.Connector;\nimport com.jcraft.jsch.agentproxy.Identity;\nimport com.jcraft.jsch.agentproxy.sshj.AuthAgent;\n\npublic class SSHClientConnection implements Connection<SSHClient> {\n   private Optional<Connector> agentConnector;\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n\n      protected HostAndPort hostAndPort;\n      protected LoginCredentials loginCredentials;\n      protected int connectTimeout;\n      protected int sessionTimeout;\n      protected Optional<Connector> agentConnector;\n\n      /**\n       * @see SSHClientConnection#getHostAndPort()\n       */\n      public Builder hostAndPort(HostAndPort hostAndPort) {\n         this.hostAndPort = hostAndPort;\n         return this;\n      }\n\n      /**\n       * @see SSHClientConnection#getLoginCredentials()\n       */\n      public Builder loginCredentials(LoginCredentials loginCredentials) {\n         this.loginCredentials = loginCredentials;\n         return this;\n      }\n\n      /**\n       * @see SSHClientConnection#getConnectTimeout()\n       */\n      public Builder connectTimeout(int connectTimeout) {\n         this.connectTimeout = connectTimeout;\n         return this;\n      }\n\n      /**\n       * @see SSHClientConnection#getConnectTimeout()\n       */\n      public Builder sessionTimeout(int sessionTimeout) {\n         this.sessionTimeout = sessionTimeout;\n         return this;\n      }\n\n      /**\n       * @see SSHClientConnection#getAgentConnector()\n       */\n      public Builder agentConnector(Optional<Connector> agentConnector) {\n         this.agentConnector = agentConnector;\n         return this;\n      }\n\n      public SSHClientConnection build() {\n         return new SSHClientConnection(hostAndPort, loginCredentials, connectTimeout, sessionTimeout, agentConnector);\n      }\n\n      protected Builder fromSSHClientConnection(SSHClientConnection in) {\n         return hostAndPort(in.getHostAndPort()).connectTimeout(in.getConnectTimeout()).loginCredentials(\n                  in.getLoginCredentials()).sessionTimeout(in.getSessionTimeout()).agentConnector(in.getAgentConnector());\n      }\n   }\n\n   private SSHClientConnection(HostAndPort hostAndPort, LoginCredentials loginCredentials, int connectTimeout,\n            int sessionTimeout, Optional<Connector> agentConnector) {\n      this.hostAndPort = checkNotNull(hostAndPort, \"hostAndPort\");\n      this.loginCredentials = checkNotNull(loginCredentials, \"loginCredentials for %\", hostAndPort);\n      this.connectTimeout = connectTimeout;\n      this.sessionTimeout = sessionTimeout;\n      this.agentConnector = checkNotNull(agentConnector, \"agentConnector for %\", hostAndPort);\n   }\n   \n   @Resource\n   @Named(\"jclouds.ssh\")\n   protected Logger logger = Logger.NULL;\n   \n   private final HostAndPort hostAndPort;\n   private final LoginCredentials loginCredentials;\n   private final int connectTimeout;\n   private final int sessionTimeout;\n\n   @VisibleForTesting\n   transient SSHClient ssh;\n\n   @Override\n   public void clear() {\n      if (ssh != null && ssh.isConnected()) {\n         try {\n            ssh.disconnect();\n         } catch (AssertionError e) {\n            // already connected\n         } catch (IOException e) {\n            logger.debug(\"<< exception disconnecting from %s: %s\", e, e.getMessage());\n         }\n         ssh = null;\n      }\n   }\n\n   @Override\n   public SSHClient create() throws Exception {\n      ssh = new net.schmizz.sshj.SSHClient();\n      ssh.addHostKeyVerifier(new PromiscuousVerifier());\n      if (connectTimeout != 0) {\n         ssh.setConnectTimeout(connectTimeout);\n      }\n      if (sessionTimeout != 0) {\n         ssh.setTimeout(sessionTimeout);\n      }\n      ssh.connect(hostAndPort.getHost(), hostAndPort.getPortOrDefault(22));\n      if (loginCredentials.hasUnencryptedPrivateKey()) {\n         OpenSSHKeyFile key = new OpenSSHKeyFile();\n         key.init(loginCredentials.getOptionalPrivateKey().get(), null);\n         ssh.authPublickey(loginCredentials.getUser(), key);\n      } else if (loginCredentials.getOptionalPassword().isPresent()) {\n         ssh.authPassword(loginCredentials.getUser(), loginCredentials.getOptionalPassword().get());\n      } else if (agentConnector.isPresent()) {\n         AgentProxy proxy = new AgentProxy(agentConnector.get());\n         ssh.auth(loginCredentials.getUser(), getAuthMethods(proxy));\n      }\n      return ssh;\n   }\n\n   /**\n    * @return host and port, where port if not present defaults to {@code 22}\n    */\n   public HostAndPort getHostAndPort() {\n      return hostAndPort;\n   }\n\n   /**\n    * \n    * @return login used in this ssh\n    */\n   public LoginCredentials getLoginCredentials() {\n      return loginCredentials;\n   }\n\n   /**\n    * \n    * @return how long to wait for the initial connection to be made\n    */\n   public int getConnectTimeout() {\n      return connectTimeout;\n   }\n\n   /**\n    * \n    * @return how long to keep the ssh open, or {@code 0} for indefinitely\n    */\n   public int getSessionTimeout() {\n      return sessionTimeout;\n   }\n\n   /**\n    *\n    * @return Ssh agent connector\n    */\n   public Optional<Connector> getAgentConnector() {\n      return agentConnector;\n   }\n\n   /**\n    * \n    * @return the current ssh or {@code null} if not connected\n    */\n   public SSHClient getSSHClient() {\n      return ssh;\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o)\n         return true;\n      if (o == null || getClass() != o.getClass())\n         return false;\n      SSHClientConnection that = SSHClientConnection.class.cast(o);\n      return equal(this.hostAndPort, that.hostAndPort) && equal(this.loginCredentials, that.loginCredentials)\n               && equal(this.ssh, that.ssh);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(hostAndPort, loginCredentials, ssh);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(\"\").add(\"hostAndPort\", hostAndPort).add(\"loginUser\", loginCredentials.getUser())\n               .add(\"ssh\", ssh != null ? ssh.hashCode() : null).add(\"connectTimeout\", connectTimeout).add(\n                        \"sessionTimeout\", sessionTimeout).toString();\n   }\n\n   private static List<AuthMethod> getAuthMethods(AgentProxy agent) throws BufferException  {\n      ImmutableList.Builder<AuthMethod> identities = ImmutableList.builder();\n      for (Identity identity : agent.getIdentities()) {\n         identities.add(new AuthAgent(agent, identity));\n      }\n      return identities.build();\n   }\n\n}\n"
  },
  {
    "path": "drivers/sshj/src/main/java/org/jclouds/sshj/SshjSshClient.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sshj;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.common.base.Predicates.instanceOf;\nimport static com.google.common.base.Predicates.or;\nimport static com.google.common.base.Throwables.getCausalChain;\nimport static com.google.common.collect.Iterables.any;\nimport static com.google.common.hash.Hashing.md5;\nimport static com.google.common.io.BaseEncoding.base16;\nimport static org.jclouds.ssh.SshKeys.fingerprintPrivateKey;\nimport static org.jclouds.ssh.SshKeys.sha1PrivateKey;\n\nimport java.io.Closeable;\nimport java.io.FilterInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.net.ConnectException;\nimport java.net.SocketTimeoutException;\nimport java.util.concurrent.TimeUnit;\n\nimport jakarta.annotation.PreDestroy;\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\n\nimport net.schmizz.sshj.SSHClient;\nimport net.schmizz.sshj.common.IOUtils;\nimport net.schmizz.sshj.connection.ConnectionException;\nimport net.schmizz.sshj.connection.channel.direct.PTYMode;\nimport net.schmizz.sshj.connection.channel.direct.Session;\nimport net.schmizz.sshj.connection.channel.direct.Session.Command;\nimport net.schmizz.sshj.connection.channel.direct.SessionChannel;\nimport net.schmizz.sshj.sftp.RemoteFile;\nimport net.schmizz.sshj.sftp.SFTPClient;\nimport net.schmizz.sshj.sftp.SFTPException;\nimport net.schmizz.sshj.transport.TransportException;\nimport net.schmizz.sshj.userauth.UserAuthException;\nimport net.schmizz.sshj.xfer.InMemorySourceFile;\n\nimport org.jclouds.compute.domain.ExecChannel;\nimport org.jclouds.compute.domain.ExecResponse;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.http.handlers.BackoffLimitedRetryHandler;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.ssh.SshClient;\nimport org.jclouds.ssh.SshException;\nimport org.jclouds.util.Closeables2;\nimport org.jclouds.util.Throwables2;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Predicates;\nimport com.google.common.base.Splitter;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Throwables;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.net.HostAndPort;\nimport com.google.inject.Inject;\nimport com.jcraft.jsch.agentproxy.Connector;\n\n/**\n * This class needs refactoring. It is not thread safe.\n */\n@SuppressWarnings(\"unchecked\")\npublic class SshjSshClient implements SshClient {\n\n   private static final class CloseFtpChannelOnCloseInputStream extends FilterInputStream {\n\n      private final SFTPClient sftp;\n\n      private CloseFtpChannelOnCloseInputStream(InputStream proxy, SFTPClient sftp) {\n         super(proxy);\n         this.sftp = sftp;\n      }\n\n      @Override\n      public void close() throws IOException {\n         super.close();\n         if (sftp != null)\n            sftp.close();\n      }\n   }\n\n   private final String toString;\n\n   @Inject(optional = true)\n   @Named(\"jclouds.ssh.max-retries\")\n   @VisibleForTesting\n   int sshRetries = 5;\n\n   @Inject(optional = true)\n   @Named(\"jclouds.ssh.retry-auth\")\n   @VisibleForTesting\n   boolean retryAuth;\n\n   @Inject(optional = true)\n   @Named(\"jclouds.ssh.retryable-messages\")\n   @VisibleForTesting\n   String retryableMessages = \"\";\n\n   @Inject(optional = true)\n   @Named(\"jclouds.ssh.retry-predicate\")\n   // NOTE cannot retry io exceptions, as SSHException is a part of the chain\n   private Predicate<Throwable> retryPredicate = or(instanceOf(ConnectionException.class),\n            instanceOf(ConnectException.class), instanceOf(SocketTimeoutException.class),\n            instanceOf(TransportException.class),\n            // safe to retry sftp exceptions as they are idempotent\n            instanceOf(SFTPException.class));\n\n   @Resource\n   @Named(\"jclouds.ssh\")\n   protected Logger logger = Logger.NULL;\n\n   @VisibleForTesting\n   SSHClientConnection sshClientConnection;\n   \n   final String user;\n   final String host;\n\n   private final BackoffLimitedRetryHandler backoffLimitedRetryHandler;\n\n   public SshjSshClient(BackoffLimitedRetryHandler backoffLimitedRetryHandler, HostAndPort socket,\n            LoginCredentials loginCredentials, int timeout, Optional<Connector> agentConnector) {\n      this.user = checkNotNull(loginCredentials, \"loginCredentials\").getUser();\n      this.host = checkNotNull(socket, \"socket\").getHost();\n      checkArgument(socket.getPort() > 0, \"ssh port must be greater then zero\" + socket.getPort());\n      checkArgument(loginCredentials.getOptionalPassword().isPresent() || loginCredentials.hasUnencryptedPrivateKey() || agentConnector.isPresent(),\n              \"you must specify a password, a key or an SSH agent needs to be available\");\n      this.backoffLimitedRetryHandler = checkNotNull(backoffLimitedRetryHandler, \"backoffLimitedRetryHandler\");\n      if (loginCredentials.hasUnencryptedPrivateKey()) {\n         String fingerPrint = fingerprintPrivateKey(loginCredentials.getOptionalPrivateKey().get());\n         String sha1 = sha1PrivateKey(loginCredentials.getOptionalPrivateKey().get());\n         this.toString = String.format(\"%s:rsa[fingerprint(%s),sha1(%s)]@%s:%d\", loginCredentials.getUser(),\n                  fingerPrint, sha1, host, socket.getPort());\n      } else if (loginCredentials.getOptionalPassword().isPresent()) {\n         this.toString = String.format(\"%s:pw[%s]@%s:%d\", loginCredentials.getUser(),\n               base16().lowerCase().encode(md5().hashString(loginCredentials.getOptionalPassword().get(), UTF_8).asBytes()), host,\n               socket.getPort());\n      } else {\n          this.toString = String.format(\"%s:rsa[ssh-agent]@%s:%d\", loginCredentials.getUser(),\n                  host, socket.getPort());\n      }\n      sshClientConnection = SSHClientConnection.builder().hostAndPort(HostAndPort.fromParts(host, socket.getPort()))\n               .loginCredentials(loginCredentials).connectTimeout(timeout).sessionTimeout(timeout).agentConnector(agentConnector).build();\n   }\n\n   @Override\n   public void put(String path, String contents) {\n      put(path, Payloads.newStringPayload(checkNotNull(contents, \"contents\")));\n   }\n\n   private void checkConnected() {\n      checkState(sshClientConnection.ssh != null && sshClientConnection.ssh.isConnected(),\n               \"(%s) ssh not connected!\", this);\n   }\n\n   public interface Connection<T> {\n      void clear() throws Exception;\n\n      T create() throws Exception;\n   }\n\n   private void backoffForAttempt(int retryAttempt, String message) {\n      backoffLimitedRetryHandler.imposeBackoffExponentialDelay(200L, 2, retryAttempt, sshRetries, message);\n   }\n\n   protected <T, C extends Connection<T>> T acquire(C connection) {\n      String errorMessage = String.format(\"(%s) error acquiring %s\", toString(), connection);\n      for (int i = 0; i < sshRetries; i++) {\n         try {\n            connection.clear();\n            logger.debug(\">> (%s) acquiring %s\", toString(), connection);\n            T returnVal = connection.create();\n            logger.debug(\"<< (%s) acquired %s\", toString(), returnVal);\n            return returnVal;\n         } catch (Exception from) {\n            try {\n               disconnect();\n            } catch (Exception e1) {\n               logger.warn(from, \"<< (%s) error closing connection\", toString());\n            }\n            if (i + 1 == sshRetries) {\n               throw propagate(from, errorMessage + \" (out of retries - max \" + sshRetries + \")\");\n            } else if (shouldRetry(from)\n                     || (Throwables2.getFirstThrowableOfType(from, IllegalStateException.class) != null)) {\n               logger.info(\"<< \" + errorMessage + \" (attempt \" + (i + 1) + \" of \" + sshRetries + \"): \"\n                        + from.getMessage());\n               backoffForAttempt(i + 1, errorMessage + \": \" + from.getMessage());\n               if (connection != sshClientConnection)\n                  connect();\n               continue;\n            } else {\n               throw propagate(from, errorMessage + \" (not retryable)\");\n            }\n         }\n      }\n      throw new AssertionError(\"should not reach here\");\n   }\n\n   public void connect() {\n      try {\n         acquire(sshClientConnection);\n      } catch (Exception e) {\n         Throwables.propagate(e);\n      }\n   }\n\n   Connection<SFTPClient> sftpConnection = new Connection<SFTPClient>() {\n\n      private SFTPClient sftp;\n\n      @Override\n      public void clear() {\n         if (sftp != null)\n            try {\n               sftp.close();\n            } catch (IOException e) {\n               Throwables.propagate(e);\n            }\n      }\n\n      @Override\n      public SFTPClient create() throws IOException {\n         checkConnected();\n         sftp = sshClientConnection.ssh.newSFTPClient();\n         return sftp;\n      }\n\n      @Override\n      public String toString() {\n         return \"SFTPClient()\";\n      }\n   };\n\n   class GetConnection implements Connection<Payload> {\n      private final String path;\n      private SFTPClient sftp;\n\n      GetConnection(String path) {\n         this.path = checkNotNull(path, \"path\");\n      }\n\n      @Override\n      public void clear() throws IOException {\n         if (sftp != null)\n            sftp.close();\n      }\n\n      @Override\n      public Payload create() throws Exception {\n         sftp = acquire(sftpConnection);\n         final RemoteFile remoteFile = sftp.getSFTPEngine().open(path);\n         final InputStream in = remoteFile.new RemoteFileInputStream() {\n            @Override\n            public void close() throws IOException {\n               try {\n                  super.close();\n               } finally {\n                  remoteFile.close();\n               }\n            }\n         };\n         return Payloads.newInputStreamPayload(new CloseFtpChannelOnCloseInputStream(in, sftp));\n      }\n\n      @Override\n      public String toString() {\n         return \"Payload(path=[\" + path + \"])\";\n      }\n   };\n\n   public Payload get(String path) {\n      return acquire(new GetConnection(path));\n   }\n\n   class PutConnection implements Connection<Void> {\n      private final String path;\n      private final Payload contents;\n      private SFTPClient sftp;\n\n      PutConnection(String path, Payload contents) {\n         this.path = checkNotNull(path, \"path\");\n         this.contents = checkNotNull(contents, \"contents\");\n      }\n\n      @Override\n      public void clear() {\n         if (sftp != null)\n            try {\n               sftp.close();\n            } catch (IOException e) {\n               Throwables.propagate(e);\n            }\n      }\n\n      @Override\n      public Void create() throws Exception {\n         sftp = acquire(sftpConnection);\n         try {\n            sftp.put(new InMemorySourceFile() {\n\n               @Override\n               public String getName() {\n                  return path;\n               }\n\n               @Override\n               public long getLength() {\n                  Long length = contents.getContentMetadata().getContentLength();\n                  return length != null ? length : -1;\n               }\n\n               @Override\n               public InputStream getInputStream() throws IOException {\n                  return checkNotNull(contents.getInput(), \"inputstream for path %s\", path);\n               }\n\n            }, path);\n         } finally {\n            contents.release();\n         }\n         return null;\n      }\n\n      @Override\n      public String toString() {\n         return \"Put(path=[\" + path + \"])\";\n      }\n   };\n\n   @Override\n   public void put(String path, Payload contents) {\n      acquire(new PutConnection(path, contents));\n   }\n\n   @VisibleForTesting\n   boolean shouldRetry(Exception from) {\n      Predicate<Throwable> predicate = retryAuth ? Predicates.<Throwable> or(retryPredicate,\n               instanceOf(AuthorizationException.class), instanceOf(UserAuthException.class)) : retryPredicate;\n      if (any(getCausalChain(from), predicate))\n         return true;\n      if (!retryableMessages.equals(\"\"))\n         return any(Splitter.on(\",\").split(retryableMessages), causalChainHasMessageContaining(from));\n      return false;\n   }\n\n   @VisibleForTesting\n   Predicate<String> causalChainHasMessageContaining(final Exception from) {\n      return new Predicate<String>() {\n\n         @Override\n         public boolean apply(final String input) {\n            return any(getCausalChain(from), new Predicate<Throwable>() {\n\n               @Override\n               public boolean apply(Throwable arg0) {\n                  return (arg0.toString().indexOf(input) != -1)\n                           || (arg0.getMessage() != null && arg0.getMessage().indexOf(input) != -1);\n               }\n\n            });\n         }\n\n      };\n   }\n\n   @VisibleForTesting\n   SshException propagate(Exception e, String message) {\n      message += \": \" + e.getMessage();\n      logger.error(e, \"<< \" + message);\n      if (e instanceof UserAuthException)\n         throw new AuthorizationException(\"(\" + toString() + \") \" + message, e);\n      throw e instanceof SshException ? SshException.class.cast(e) : new SshException(\n               \"(\" + toString() + \") \" + message, e);\n   }\n\n   @Override\n   public String toString() {\n      return toString;\n   }\n\n   @PreDestroy\n   public void disconnect() {\n      try {\n         sshClientConnection.clear();\n      } catch (Exception e) {\n         Throwables.propagate(e);\n      }\n   }\n\n   @Override\n   public boolean isConnected() {\n      try {\n         return sshClientConnection.getSSHClient().isConnected();\n      } catch (Exception e) {\n         throw Throwables.propagate(e);\n      }\n   }\n\n   protected Connection<Session> execConnection() {\n\n      return new Connection<Session>() {\n\n         private Session session = null;\n\n         @Override\n         public void clear() throws TransportException, ConnectionException {\n            if (session != null)\n               session.close();\n         }\n\n         @Override\n         public Session create() throws Exception {\n            checkConnected();\n            session = sshClientConnection.ssh.startSession();\n            session.allocatePTY(\"vt100\", 80, 24, 0, 0, ImmutableMap.<PTYMode, Integer> of());\n            return session;\n         }\n\n         @Override\n         public String toString() {\n            return \"Session()\";\n         }\n      };\n\n   }\n\n   class ExecConnection implements Connection<ExecResponse> {\n      private final String command;\n      private Session session;\n\n      ExecConnection(String command) {\n         this.command = checkNotNull(command, \"command\");\n      }\n\n      @Override\n      public void clear() throws TransportException, ConnectionException {\n         if (session != null)\n            session.close();\n      }\n\n      @Override\n      public ExecResponse create() throws Exception {\n         try {\n            session = acquire(execConnection());\n            Command output = session.exec(checkNotNull(command, \"command\"));\n            String outputString = IOUtils.readFully(output.getInputStream()).toString();\n            output.join(sshClientConnection.getSessionTimeout(), TimeUnit.MILLISECONDS);\n            String errorString = IOUtils.readFully(output.getErrorStream()).toString();\n            return new ExecResponse(outputString, errorString, output.getExitStatus());\n         } finally {\n            clear();\n         }\n      }\n\n      @Override\n      public String toString() {\n         return \"ExecResponse(command=[\" + command + \"])\";\n      }\n   }\n\n   public ExecResponse exec(String command) {\n      return acquire(new ExecConnection(command));\n   }\n\n   protected Connection<Session> noPTYConnection() {\n\n      return new Connection<Session>() {\n\n         private Session session = null;\n         private SSHClient sshClientConnection;\n\n         @Override\n         public void clear() throws TransportException, ConnectionException {\n            if (session != null)\n               session.close();\n            if (sshClientConnection != null)\n               Closeables2.closeQuietly(sshClientConnection);\n         }\n\n         @Override\n         public Session create() throws Exception {\n            this.sshClientConnection = acquire(SSHClientConnection.builder().fromSSHClientConnection(\n                     SshjSshClient.this.sshClientConnection).sessionTimeout(0).build());\n            session = sshClientConnection.startSession();\n            return session;\n         }\n\n         @Override\n         public String toString() {\n            return \"Session()\";\n         }\n      };\n\n   }\n\n   class ExecChannelConnection implements Connection<ExecChannel> {\n      private final String command;\n      private Command output;\n      private Connection<Session> connection;\n\n      ExecChannelConnection(String command) {\n         this.command = checkNotNull(command, \"command\");\n      }\n\n      @Override\n      public void clear() {\n         Closeables2.closeQuietly(output);\n         try {\n             if (connection != null) {\n                 connection.clear();\n             }\n         } catch (Throwable e) {\n             Throwables.propagate(e);\n         }\n      }\n\n      @Override\n      public ExecChannel create() throws Exception {\n         connection = noPTYConnection();\n         output = SessionChannel.class.cast(acquire(connection)).exec(command);\n         return new ExecChannel(output.getOutputStream(), output.getInputStream(), output.getErrorStream(),\n                  new Supplier<Integer>() {\n\n                     @Override\n                     public Integer get() {\n                        return output.getExitStatus();\n                     }\n\n                  }, new Closeable() {\n\n                     @Override\n                     public void close() throws IOException {\n                        clear();\n                     }\n\n                  });\n\n      }\n\n      @Override\n      public String toString() {\n         return \"ExecChannel(command=[\" + command + \"])\";\n      }\n   }\n\n   @Override\n   public ExecChannel execChannel(String command) {\n      return acquire(new ExecChannelConnection(command));\n   }\n\n   @Override\n   public String getHostAddress() {\n      return this.host;\n   }\n\n   @Override\n   public String getUsername() {\n      return this.user;\n   }\n\n}\n"
  },
  {
    "path": "drivers/sshj/src/main/java/org/jclouds/sshj/config/SshjSshClientModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sshj.config;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.Constants;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.http.handlers.BackoffLimitedRetryHandler;\nimport org.jclouds.ssh.SshClient;\nimport org.jclouds.ssh.config.ConfiguresSshClient;\nimport org.jclouds.sshj.SshjSshClient;\n\nimport com.google.common.base.Optional;\nimport com.google.common.net.HostAndPort;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Inject;\nimport com.google.inject.Injector;\nimport com.google.inject.Scopes;\nimport com.jcraft.jsch.agentproxy.AgentProxyException;\nimport com.jcraft.jsch.agentproxy.Connector;\nimport com.jcraft.jsch.agentproxy.ConnectorFactory;\n\n@ConfiguresSshClient\npublic class SshjSshClientModule extends AbstractModule {\n\n   protected void configure() {\n      bind(SshClient.Factory.class).to(Factory.class).in(Scopes.SINGLETON);\n   }\n\n   private static class Factory implements SshClient.Factory {\n      @Named(Constants.PROPERTY_CONNECTION_TIMEOUT)\n      @Inject(optional = true)\n      int timeout = 60000;\n\n      Optional<Connector> agentConnector = getAgentConnector();\n\n      Optional<Connector> getAgentConnector() {\n         ConnectorFactory sshAgentOverNetcatOnly = new ConnectorFactory() {\n               {\n                  setPreferredConnectors(\"ssh-agent\");\n                  setPreferredUSocketFactories(\"nc\");\n               }\n            };\n         try {\n            return Optional.of(sshAgentOverNetcatOnly.createConnector());\n         } catch (final AgentProxyException e) {\n            return Optional.absent();\n         }\n      }\n\n      private final BackoffLimitedRetryHandler backoffLimitedRetryHandler;\n      private final Injector injector;\n\n      @Inject\n      public Factory(BackoffLimitedRetryHandler backoffLimitedRetryHandler, Injector injector) {\n         this.backoffLimitedRetryHandler = backoffLimitedRetryHandler;\n         this.injector = injector;\n      }\n\n      @Override\n      public SshClient create(HostAndPort socket, LoginCredentials credentials) {\n         SshClient client = new SshjSshClient(backoffLimitedRetryHandler, socket, credentials, timeout, getAgentConnector());\n         injector.injectMembers(client);  // add logger\n         return client;\n      }\n\n      @Override\n      public boolean isAgentAvailable() {\n         return agentConnector.isPresent();\n      }\n\n   }\n}\n"
  },
  {
    "path": "drivers/sshj/src/test/java/org/jclouds/sshj/SshjSshClientLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sshj;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.ByteArrayOutputStream;\nimport java.io.Closeable;\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.io.IOException;\nimport java.io.PrintStream;\nimport java.net.InetAddress;\n\nimport org.jclouds.compute.domain.ExecChannel;\nimport org.jclouds.compute.domain.ExecResponse;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.logging.slf4j.config.SLF4JLoggingModule;\nimport org.jclouds.ssh.SshClient;\nimport org.jclouds.sshj.config.SshjSshClientModule;\nimport org.jclouds.util.Closeables2;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.BeforeGroups;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.base.Strings;\nimport com.google.common.base.Suppliers;\nimport com.google.common.io.Files;\nimport com.google.common.net.HostAndPort;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n/**\n * Tests the ability of a {@link SshjSshClient}\n */\n@Test(groups = \"live\", testName = \"SshjSshClientLiveTest\")\npublic class SshjSshClientLiveTest {\n   protected static final String sshHost = System.getProperty(\"test.ssh.host\", \"localhost\");\n   protected static final String sshPort = System.getProperty(\"test.ssh.port\", \"22\");\n   protected static final String sshUser = System.getProperty(\"test.ssh.username\");\n   protected static final String sshPass = System.getProperty(\"test.ssh.password\");\n   protected static final String sshKeyFile = System.getProperty(\"test.ssh.keyfile\");\n   private File temp;\n\n   @BeforeGroups(groups = { \"live\" })\n   public SshClient setupClient() throws NumberFormatException, FileNotFoundException, IOException {\n      int port = Integer.parseInt(sshPort);\n      if (sshUser == null\n               || ((sshPass == null || sshPass.trim().equals(\"\")) && (sshKeyFile == null || sshKeyFile.trim()\n                        .equals(\"\"))) || sshUser.trim().equals(\"\")) {\n         System.err.println(\"ssh credentials not present.  Tests will be lame\");\n         return new SshClient() {\n\n            public void connect() {\n            }\n\n            public void disconnect() {\n            }\n\n            public boolean isConnected() {\n               return false;\n            }\n\n            public Payload get(String path) {\n               if (path.equals(\"/etc/passwd\")) {\n                  return Payloads.newStringPayload(\"root\");\n               } else if (path.equals(temp.getAbsolutePath())) {\n                  return Payloads.newStringPayload(\"rabbit\");\n               }\n               throw new RuntimeException(\"path \" + path + \" not stubbed\");\n            }\n\n            public ExecResponse exec(String command) {\n               if (command.equals(\"hostname\")) {\n                  return new ExecResponse(sshHost, \"\", 0);\n               }\n               throw new RuntimeException(\"command \" + command + \" not stubbed\");\n            }\n\n            @Override\n            public void put(String path, Payload contents) {\n\n            }\n\n            @Override\n            public String getHostAddress() {\n               return null;\n            }\n\n            @Override\n            public String getUsername() {\n               return null;\n            }\n\n            @Override\n            public void put(String path, String contents) {\n\n            }\n            \n            @Override\n            public ExecChannel execChannel(String command) {\n               if (command.equals(\"hostname\")) {\n                  return new ExecChannel(new ByteArrayOutputStream(), new ByteArrayInputStream(sshHost.getBytes()),\n                           new ByteArrayInputStream(new byte[] {}), Suppliers.ofInstance(0), new Closeable() {\n\n                              @Override\n                              public void close() {\n\n                              }\n\n                           });\n               }\n               throw new RuntimeException(\"command \" + command + \" not stubbed\");\n            }\n         };\n      } else {\n         Injector i = Guice.createInjector(new SshjSshClientModule(), new SLF4JLoggingModule());\n         SshClient.Factory factory = i.getInstance(SshClient.Factory.class);\n         SshClient connection;\n         if (Strings.emptyToNull(sshKeyFile) != null) {\n            connection = factory.create(HostAndPort.fromParts(sshHost, port), LoginCredentials.builder().user(sshUser)\n                  .privateKey(Files.toString(new File(sshKeyFile), Charsets.UTF_8)).build());\n         } else {\n            connection = factory.create(HostAndPort.fromParts(sshHost, port),\n                  LoginCredentials.builder().user(sshUser).password(sshPass).build());\n         }\n         connection.connect();\n         return connection;\n      }\n   }\n\n   public void testPutAndGet() throws IOException {\n      temp = java.nio.file.Files.createTempFile(\"foo\", \"bar\").toFile();\n      try {\n         SshClient client = setupClient();\n         client.put(temp.getAbsolutePath(), Payloads.newStringPayload(\"rabbit\"));\n         Payload input = client.get(temp.getAbsolutePath());\n         String contents = Strings2.toStringAndClose(input.openStream());\n         assertEquals(contents, \"rabbit\");\n      } finally {\n         temp.delete();\n      }\n   }\n\n   public void testGetEtcPassword() throws IOException {\n      Payload input = setupClient().get(\"/etc/passwd\");\n      String contents = Strings2.toStringAndClose(input.openStream());\n      assert contents.indexOf(\"root\") >= 0 : \"no root in \" + contents;\n   }\n\n   public void testExecHostname() throws IOException, InterruptedException {\n      SshClient client = setupClient();\n      ExecResponse response = client.exec(\"hostname\");\n      assertEquals(response.getError(), \"\");\n      assertEquals(response.getOutput().trim(), \"localhost\".equals(sshHost) ? InetAddress.getLocalHost().getHostName()\n               : sshHost);\n   }\n\n   public void testExecChannelTakesStdinAndNoEchoOfCharsInOuputAndOutlivesClient() throws IOException {\n      SshClient client = setupClient();\n      ExecChannel response = client.execChannel(\"cat <<EOF\");\n      client.disconnect();\n      assertEquals(response.getExitStatus().get(), null);\n      try {\n         PrintStream printStream = new PrintStream(response.getInput());\n         printStream.append(\"foo\\n\");\n         printStream.append(\"EOF\\n\");\n         printStream.close();\n         assertEquals(Strings2.toStringAndClose(response.getError()), \"\");\n         assertEquals(Strings2.toStringAndClose(response.getOutput()), \"\");\n      } finally {\n         Closeables2.closeQuietly(response);\n      }\n      assertEquals(response.getExitStatus().get(), Integer.valueOf(0));\n   }\n}\n"
  },
  {
    "path": "drivers/sshj/src/test/java/org/jclouds/sshj/SshjSshClientTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sshj;\n\nimport static com.google.inject.name.Names.bindProperties;\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.expectLastCall;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.net.ConnectException;\nimport java.net.SocketTimeoutException;\nimport java.util.Properties;\nimport java.util.concurrent.TimeUnit;\nimport java.util.logging.Level;\n\nimport net.schmizz.sshj.SSHClient;\nimport net.schmizz.sshj.common.SSHException;\nimport net.schmizz.sshj.connection.ConnectionException;\nimport net.schmizz.sshj.connection.channel.direct.PTYMode;\nimport net.schmizz.sshj.connection.channel.direct.Session;\nimport net.schmizz.sshj.connection.channel.direct.Session.Command;\nimport net.schmizz.sshj.sftp.SFTPException;\nimport net.schmizz.sshj.transport.TransportException;\nimport net.schmizz.sshj.userauth.UserAuthException;\n\nimport org.jclouds.compute.domain.ExecResponse;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.logging.BufferLogger;\nimport org.jclouds.logging.BufferLogger.Record;\nimport org.jclouds.logging.slf4j.config.SLF4JLoggingModule;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.ssh.SshClient;\nimport org.jclouds.sshj.config.SshjSshClientModule;\nimport org.testng.Assert;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.net.HostAndPort;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport com.google.inject.Module;\n\n\n@Test\npublic class SshjSshClientTest {\n\n   protected SshjSshClient ssh;\n\n   @BeforeTest\n   public void setupSsh() {\n      ssh = createClient();\n   }\n\n   protected SshjSshClient createClient() {\n      return createClient(new Properties());\n   }\n\n   protected SshjSshClient createClient(final Properties props) {\n      Injector i = Guice.createInjector(module(), new AbstractModule() {\n\n         @Override\n         protected void configure() {\n            bindProperties(binder(), props);\n         }\n\n      }, new SLF4JLoggingModule());\n      SshClient.Factory factory = i.getInstance(SshClient.Factory.class);\n      SshjSshClient ssh = SshjSshClient.class.cast(factory.create(HostAndPort.fromParts(\"localhost\", 22), LoginCredentials\n            .builder().user(\"username\").password(\"password\").build()));\n      return ssh;\n   }\n\n   protected Module module() {\n      return new SshjSshClientModule();\n   }\n\n   @Test(expectedExceptions = AuthorizationException.class)\n   public void testPropateConvertsAuthException() {\n      ssh.propagate(new UserAuthException(\"\"), \"\");\n   }\n\n   public void testExceptionClassesRetry() {\n      assert ssh.shouldRetry(new ConnectionException(\"Read timed out\", new SSHException(\"Read timed out\",\n            new SocketTimeoutException(\"Read timed out\"))));\n      assert ssh.shouldRetry(new SFTPException(\"Failure!\"));\n      assert ssh.shouldRetry(new SocketTimeoutException(\"connect timed out\"));\n      assert ssh.shouldRetry(new TransportException(\"socket closed\"));\n      assert ssh.shouldRetry(new ConnectionException(\"problem\"));\n      assert ssh.shouldRetry(new ConnectException(\"Connection refused\"));\n      assert !ssh.shouldRetry(new IOException(\"channel is not open\", new NullPointerException()));\n   }\n\n   public void testOnlyRetryAuthWhenSet() {\n      SshjSshClient ssh1 = createClient();\n      assert !ssh1.shouldRetry(new AuthorizationException(\"problem\", null));\n      assert !ssh1.shouldRetry(new UserAuthException(\"problem\", null));\n      ssh1.retryAuth = true;\n      assert ssh1.shouldRetry(new AuthorizationException(\"problem\", null));\n      assert ssh1.shouldRetry(new UserAuthException(\"problem\", null));\n   }\n\n   public void testOnlyRetryAuthWhenSetViaProperties() {\n      Properties props = new Properties();\n      props.setProperty(\"jclouds.ssh.retry-auth\", \"true\");\n      SshjSshClient ssh1 = createClient(props);\n      assert ssh1.shouldRetry(new AuthorizationException(\"problem\", null));\n      assert ssh1.shouldRetry(new UserAuthException(\"problem\", null));\n   }\n\n   public void testExceptionMessagesRetry() {\n      assert !ssh.shouldRetry(new SSHException(\"\"));\n      assert !ssh.shouldRetry(new NullPointerException((String) null));\n   }\n\n   public void testCausalChainHasMessageContaining() {\n      assert ssh.causalChainHasMessageContaining(\n            new SSHException(\"Session.connect: java.io.IOException: End of IO Stream Read\")).apply(\n            \" End of IO Stream Read\");\n      assert ssh.causalChainHasMessageContaining(\n            new SSHException(\"Session.connect: java.net.SocketException: Connection reset\")).apply(\"java.net.Socket\");\n      assert !ssh.causalChainHasMessageContaining(new NullPointerException()).apply(\" End of IO Stream Read\");\n   }\n\n   public void testRetryOnToStringNpe() {\n      Exception nex = new NullPointerException();\n      Properties props = new Properties();\n      // ensure we test toString on the exception independently\n      props.setProperty(\"jclouds.ssh.retryable-messages\", nex.toString());\n      SshjSshClient ssh1 = createClient(props);\n      assert ssh1.shouldRetry(new RuntimeException(nex));\n   }\n\n   private static class ExceptionWithStrangeToString extends RuntimeException {\n      private static final String MESSAGE = \"foo-bar-exception-tostring\";\n\n      public String toString() {\n         return MESSAGE;\n      }\n   }\n\n   public void testRetryOnToStringCustom() {\n      Exception nex = new ExceptionWithStrangeToString();\n      Properties props = new Properties();\n      props.setProperty(\"jclouds.ssh.retryable-messages\", \"foo-bar\");\n      SshjSshClient ssh1 = createClient(props);\n      assert ssh1.shouldRetry(new RuntimeException(nex));\n   }\n\n   public void testDontThrowIOExceptionOnClear() throws Exception {\n      SshjSshClient ssh1 = createClient();\n      SSHClient ssh = createMock(SSHClient.class);\n      expect(ssh.isConnected()).andReturn(true);\n      ssh.disconnect();\n      expectLastCall().andThrow(new ConnectionException(\"disconnected\"));\n      replay(ssh);\n      ssh1.sshClientConnection.ssh = ssh;\n      ssh1.sshClientConnection.clear();\n      verify(ssh);\n   }\n\n   public void testRetryNotOnToStringCustomMismatch() {\n      Exception nex = new ExceptionWithStrangeToString();\n      Properties props = new Properties();\n      props.setProperty(\"jclouds.ssh.retryable-messages\", \"foo-baR\");\n      SshjSshClient ssh1 = createClient(props);\n      assert !ssh1.shouldRetry(new RuntimeException(nex));\n   }\n\n   public void testRetriesLoggedAtInfoWithCount() throws Exception {\n      SSHClientConnection mockConnection = createMock(SSHClientConnection.class);\n      net.schmizz.sshj.SSHClient mockClient = createMock(net.schmizz.sshj.SSHClient.class);\n\n      mockConnection.clear(); expectLastCall();\n      mockConnection.create(); expectLastCall().andThrow(new ConnectionException(\"test1\"));\n      mockConnection.clear(); expectLastCall();\n      //currently does two clears, one on failure (above) and one on next iteration (below)\n      mockConnection.clear(); expectLastCall();\n      mockConnection.create(); expectLastCall().andReturn(mockClient);\n      replay(mockConnection);\n      replay(mockClient);\n      \n      ssh.sshClientConnection = mockConnection;\n      BufferLogger logcheck = new BufferLogger(ssh.getClass().getCanonicalName()); \n      ssh.logger = logcheck;\n      logcheck.setLevel(Level.INFO);\n      \n      ssh.connect();\n      \n      Assert.assertEquals(ssh.sshClientConnection, mockConnection);\n      verify(mockConnection);\n      verify(mockClient);\n      Record r = logcheck.assertLogContains(\"attempt 1 of 5\");\n      logcheck.assertLogDoesntContain(\"attempt 2 of 5\");\n      Assert.assertEquals(Level.INFO, r.getLevel());\n   }\n   \n   public void testExecResponseHasDefaultExitStatusIfDriverReturnsNullExitStatus() throws Exception {\n      SSHClientConnection mockConnection = createMock(SSHClientConnection.class);\n      net.schmizz.sshj.SSHClient mockClient = createMock(net.schmizz.sshj.SSHClient.class);\n      Session session = createMock(Session.class);\n      Command command = createMock(Command.class);\n      SshjSshClient client = createClient();\n      InputStream is = new ByteArrayInputStream( new byte[0] );\n\n      mockConnection.getSessionTimeout(); expectLastCall().andReturn(0);\n      mockClient.isConnected(); expectLastCall().andReturn(true);\n      mockClient.startSession(); expectLastCall().andReturn(session);\n      session.allocatePTY(\"vt100\", 80, 24, 0, 0, ImmutableMap.<PTYMode, Integer> of());\n      expectLastCall();\n      session.exec(\"some-command\"); expectLastCall().andReturn( command );\n      session.close(); expectLastCall();\n      command.join(0, TimeUnit.MILLISECONDS); expectLastCall();\n      command.getInputStream(); expectLastCall().andReturn(is);\n      command.getErrorStream(); expectLastCall().andReturn(is);\n      command.getExitStatus(); expectLastCall().andReturn(null);\n      replay(mockConnection);\n      replay(mockClient);\n      replay(session);\n      replay(command);\n      \n      mockConnection.ssh = mockClient;\n      client.sshClientConnection = mockConnection;\n      \n      ExecResponse response = client.exec( \"some-command\" );\n       \n      assertEquals(response.getExitStatus(), ExecResponse.DEFAULT_EXIT_STATUS);\n      verify(mockConnection, mockClient, session, command);\n   }\n\n}\n"
  },
  {
    "path": "drivers/sshj/src/test/java/org/jclouds/sshj/config/SshjSshClientModuleTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.sshj.config;\n\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.logging.slf4j.config.SLF4JLoggingModule;\nimport org.jclouds.ssh.SshClient;\nimport org.jclouds.sshj.SshjSshClient;\nimport org.testng.annotations.Test;\n\nimport com.google.common.net.HostAndPort;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n/**\n * Tests the ability to configure a {@link SshjSshClient}\n */\n@Test\npublic class SshjSshClientModuleTest {\n\n   public void testConfigureBindsClient() {\n\n      Injector i = Guice.createInjector(new SshjSshClientModule(), new SLF4JLoggingModule());\n      SshClient.Factory factory = i.getInstance(SshClient.Factory.class);\n      SshClient connection = factory.create(HostAndPort.fromParts(\"localhost\", 22), LoginCredentials.builder().user(\"username\")\n            .password(\"password\").build());\n      assert connection instanceof SshjSshClient;\n   }\n}\n"
  },
  {
    "path": "loadbalancer/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.loadbalancer.*;version=\"${project.version}\n\nFragment-Host: \\\n    jclouds-core"
  },
  {
    "path": "loadbalancer/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../project/pom.xml</relativePath>\n  </parent>\n  <artifactId>jclouds-loadbalancer</artifactId>\n  <name>jclouds loadbalancer core</name>\n  <description>jclouds components to access loadbalancer providers</description>\n\n  <dependencies>\n    <dependency>\n      <groupId>${project.groupId}</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>${project.groupId}</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>${project.groupId}</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>${project.groupId}</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-log4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.logging.log4j</groupId>\n      <artifactId>log4j-core</artifactId>\n      <scope>test</scope>\n    </dependency>\n  </dependencies>\n\n</project>\n"
  },
  {
    "path": "loadbalancer/src/main/java/org/jclouds/loadbalancer/LoadBalancerService.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.loadbalancer;\n\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.domain.Location;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.loadbalancer.domain.LoadBalancerMetadata;\nimport org.jclouds.loadbalancer.internal.BaseLoadBalancerService;\n\nimport com.google.common.annotations.Beta;\nimport com.google.inject.ImplementedBy;\n\n/**\n * Provides portable access to load balancer services.\n */\n@Beta\n@ImplementedBy(BaseLoadBalancerService.class)\npublic interface LoadBalancerService {\n\n   /**\n    * The list locations command returns all the valid locations for load balancers. A location has\n    * a scope, which is typically region or zone. A region is a general area, like eu-west, where a\n    * zone is similar to a datacenter. If a location has a parent, that implies it is within that\n    * location. For example a location can be a rack, whose parent is likely to be a zone.\n    */\n   Set<? extends Location> listAssignableLocations();\n\n   /**\n    * @return a reference to the context that created this LoadBalancerService.\n    */\n   LoadBalancerServiceContext getContext();\n\n   /**\n    * @param location\n    *           null if default\n    * @param loadBalancerName\n    *           Load balancer name\n    * @param protocol\n    *           LoadBalancer transport protocol to use for routing - TCP or HTTP. This property\n    *           cannot be modified for the life of the LoadBalancer.\n    * @param loadBalancerPort\n    *           The external TCP port of the LoadBalancer. Valid LoadBalancer ports are - 80, 443\n    *           and 1024 through 65535. This property cannot be modified for the life of the\n    *           LoadBalancer.\n    * @param instancePort\n    *           The InstancePort data type is simple type of type: integer. It is the TCP port on\n    *           which the server on the instance is listening. Valid instance ports are one (1)\n    *           through 65535. This property cannot be modified for the life of the LoadBalancer.\n    * @param nodes\n    *           nodes to loadbalance\n    * \n    * @see org.jclouds.compute.ComputeService\n    */\n   // TODO: this needs to be split up into 2 items: create load balancer and registernodes\n   @Beta\n   LoadBalancerMetadata createLoadBalancerInLocation(@Nullable Location location, String loadBalancerName,\n         String protocol, int loadBalancerPort, int instancePort, Iterable<? extends NodeMetadata> nodes);\n\n   @Beta\n   void destroyLoadBalancer(String id);\n\n   @Beta\n   Set<? extends LoadBalancerMetadata> listLoadBalancers();\n\n   LoadBalancerMetadata getLoadBalancerMetadata(String id);\n\n}\n"
  },
  {
    "path": "loadbalancer/src/main/java/org/jclouds/loadbalancer/LoadBalancerServiceAdapter.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.loadbalancer;\n\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.domain.Location;\nimport org.jclouds.javax.annotation.Nullable;\n\n/**\n * A means of specifying the interface between the {@link LoadBalancerService LoadBalancerServices}\n * and a concrete compute cloud implementation, jclouds or otherwise.\n */\npublic interface LoadBalancerServiceAdapter<B, L> {\n\n   /**\n    * \n    * @see LoadBalancerService#createLoadBalancerInLocation\n    */\n   B createLoadBalancerInLocation(@Nullable Location location, String loadBalancerName, String protocol,\n         int loadBalancerPort, int instancePort, Iterable<? extends NodeMetadata> nodes);\n\n   /**\n    * \n    * @see LoadBalancerService#listAssignableLocations\n    */\n   Iterable<L> listAssignableLocations();\n\n   /**\n    * \n    * @see LoadBalancerService#getLoadBalancerMetadata\n    */\n   B getLoadBalancer(String id);\n\n   /**\n    * \n    * @see LoadBalancerService#destroyLoadBalancer\n    */\n   void destroyLoadBalancer(String id);\n\n   /**\n    * \n    * @see LoadBalancerService#listLoadBalancers\n    */\n   Iterable<B> listLoadBalancers();\n\n}\n"
  },
  {
    "path": "loadbalancer/src/main/java/org/jclouds/loadbalancer/LoadBalancerServiceContext.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.loadbalancer;\n\nimport java.io.Closeable;\n\nimport org.jclouds.View;\nimport org.jclouds.loadbalancer.internal.LoadBalancerServiceContextImpl;\nimport org.jclouds.rest.Utils;\n\nimport com.google.inject.ImplementedBy;\n\n/**\n * Represents a cloud that has LoadBalancer functionality.\n */\n@ImplementedBy(LoadBalancerServiceContextImpl.class)\npublic interface LoadBalancerServiceContext extends Closeable, View {\n\n   LoadBalancerService getLoadBalancerService();\n\n   Utils utils();\n\n   @Override\n   void close();\n}\n"
  },
  {
    "path": "loadbalancer/src/main/java/org/jclouds/loadbalancer/config/BaseLoadBalancerServiceContextModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.loadbalancer.config;\n\nimport com.google.inject.AbstractModule;\n\npublic abstract class BaseLoadBalancerServiceContextModule extends AbstractModule {\n\n   @Override\n   protected void configure() {\n\n   }\n}\n"
  },
  {
    "path": "loadbalancer/src/main/java/org/jclouds/loadbalancer/config/BindLoadBalancerStrategiesByClass.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.loadbalancer.config;\n\nimport org.jclouds.loadbalancer.strategy.DestroyLoadBalancerStrategy;\nimport org.jclouds.loadbalancer.strategy.GetLoadBalancerMetadataStrategy;\nimport org.jclouds.loadbalancer.strategy.ListLoadBalancersStrategy;\nimport org.jclouds.loadbalancer.strategy.LoadBalanceNodesStrategy;\n\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Scopes;\n\npublic abstract class BindLoadBalancerStrategiesByClass extends AbstractModule {\n   protected void configure() {\n      bindLoadBalanceNodesStrategy(defineLoadBalanceNodesStrategy());\n      bindListLoadBalancersStrategy(defineListLoadBalancersStrategy());\n      bindGetLoadBalancerMetadataStrategy(defineGetLoadBalancerMetadataStrategy());\n      bindDestroyLoadBalancerStrategy(defineDestroyLoadBalancerStrategy());\n   }\n\n   protected void bindLoadBalanceNodesStrategy(Class<? extends LoadBalanceNodesStrategy> clazz) {\n      bind(LoadBalanceNodesStrategy.class).to(clazz).in(Scopes.SINGLETON);\n   }\n\n   protected void bindDestroyLoadBalancerStrategy(Class<? extends DestroyLoadBalancerStrategy> clazz) {\n      bind(DestroyLoadBalancerStrategy.class).to(clazz).in(Scopes.SINGLETON);\n   }\n\n   protected void bindGetLoadBalancerMetadataStrategy(Class<? extends GetLoadBalancerMetadataStrategy> clazz) {\n      bind(GetLoadBalancerMetadataStrategy.class).to(clazz).in(Scopes.SINGLETON);\n   }\n\n   protected void bindListLoadBalancersStrategy(Class<? extends ListLoadBalancersStrategy> clazz) {\n      bind(ListLoadBalancersStrategy.class).to(clazz).in(Scopes.SINGLETON);\n   }\n\n   protected abstract Class<? extends LoadBalanceNodesStrategy> defineLoadBalanceNodesStrategy();\n\n   protected abstract Class<? extends DestroyLoadBalancerStrategy> defineDestroyLoadBalancerStrategy();\n\n   protected abstract Class<? extends GetLoadBalancerMetadataStrategy> defineGetLoadBalancerMetadataStrategy();\n\n   protected abstract Class<? extends ListLoadBalancersStrategy> defineListLoadBalancersStrategy();\n}\n"
  },
  {
    "path": "loadbalancer/src/main/java/org/jclouds/loadbalancer/domain/LoadBalancerMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.loadbalancer.domain;\n\nimport java.util.Set;\n\nimport org.jclouds.domain.ResourceMetadata;\nimport org.jclouds.loadbalancer.domain.internal.LoadBalancerMetadataImpl;\n\nimport com.google.inject.ImplementedBy;\n\n/**\n */\n@ImplementedBy(LoadBalancerMetadataImpl.class)\npublic interface LoadBalancerMetadata extends ResourceMetadata<LoadBalancerType> {\n   /**\n    * Type of the resource, ex node, image, size\n    * \n    */\n   @Override\n   LoadBalancerType getType();\n\n   /**\n    * id of the server within the naming scope it was created. potentially generated by the service.\n    * \n    */\n   @Override\n   String getProviderId();\n\n   /**\n    * user defined name of the server.\n    * \n    */\n   @Override\n   String getName();\n\n   /**\n    * \n    * A means to uniquely address this resource within a provider. For example, if the namespace of\n    * a node or image is region based, the id will likely include both the region and the\n    * provider-supplied id encoded to avoid collisions.\n    * \n    */\n   String getId();\n\n   /**\n    * @return DNS Name of the load balancer; note we don't use InetAddress, as it is incompatible\n    *         with google appengine.\n    */\n   // TODO: this is no longer the case\n   Set<String> getAddresses();\n\n}\n"
  },
  {
    "path": "loadbalancer/src/main/java/org/jclouds/loadbalancer/domain/LoadBalancerType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.loadbalancer.domain;\n\npublic enum LoadBalancerType {\n\n   GSLB, LB;\n\n}\n"
  },
  {
    "path": "loadbalancer/src/main/java/org/jclouds/loadbalancer/domain/internal/LoadBalancerMetadataImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.loadbalancer.domain.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.net.URI;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.internal.ResourceMetadataImpl;\nimport org.jclouds.loadbalancer.domain.LoadBalancerMetadata;\nimport org.jclouds.loadbalancer.domain.LoadBalancerType;\n\nimport com.google.common.collect.ImmutableSet;\n\npublic class LoadBalancerMetadataImpl extends ResourceMetadataImpl<LoadBalancerType> implements LoadBalancerMetadata {\n\n   private final String id;\n   private final LoadBalancerType type;\n   private final Set<String> addresses;\n\n   public LoadBalancerMetadataImpl(LoadBalancerType type, String providerId, String name, String id, Location location,\n         URI uri, Map<String, String> userMetadata, Iterable<String> addresses) {\n      super(providerId, name, location, uri, userMetadata);\n      this.id = checkNotNull(id, \"id\");\n      this.type = checkNotNull(type, \"type\");\n      this.addresses = ImmutableSet.copyOf(checkNotNull(addresses, \"addresses\"));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public LoadBalancerType getType() {\n      return type;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String getId() {\n      return id;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Set<String> getAddresses() {\n      return addresses;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = super.hashCode();\n      result = prime * result + ((addresses == null) ? 0 : addresses.hashCode());\n      result = prime * result + ((id == null) ? 0 : id.hashCode());\n      result = prime * result + ((type == null) ? 0 : type.hashCode());\n      return result;\n   }\n\n   @Override\n   public String toString() {\n      return \"[id=\" + id + \", providerId=\" + getProviderId() + \", name=\" + getName() + \", location=\" + getLocation()\n            + \", uri=\" + getUri() + \", userMetadata=\" + getUserMetadata() + \", type=\" + type + \", addresses=\"\n            + addresses + \"]\";\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (!super.equals(obj))\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      LoadBalancerMetadataImpl other = (LoadBalancerMetadataImpl) obj;\n      if (addresses == null) {\n         if (other.addresses != null)\n            return false;\n      } else if (!addresses.equals(other.addresses))\n         return false;\n      if (id == null) {\n         if (other.id != null)\n            return false;\n      } else if (!id.equals(other.id))\n         return false;\n      if (type != other.type)\n         return false;\n      return true;\n   }\n\n}\n"
  },
  {
    "path": "loadbalancer/src/main/java/org/jclouds/loadbalancer/internal/BaseLoadBalancerService.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.loadbalancer.internal;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Sets.newLinkedHashSet;\nimport static java.util.concurrent.TimeUnit.MILLISECONDS;\nimport static org.jclouds.util.Predicates2.retry;\n\nimport java.util.LinkedHashSet;\nimport java.util.Set;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.domain.Location;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.loadbalancer.LoadBalancerService;\nimport org.jclouds.loadbalancer.LoadBalancerServiceContext;\nimport org.jclouds.loadbalancer.domain.LoadBalancerMetadata;\nimport org.jclouds.loadbalancer.reference.LoadBalancerConstants;\nimport org.jclouds.loadbalancer.strategy.DestroyLoadBalancerStrategy;\nimport org.jclouds.loadbalancer.strategy.GetLoadBalancerMetadataStrategy;\nimport org.jclouds.loadbalancer.strategy.ListLoadBalancersStrategy;\nimport org.jclouds.loadbalancer.strategy.LoadBalanceNodesStrategy;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.util.concurrent.Atomics;\nimport com.google.inject.Inject;\n\n@Singleton\npublic class BaseLoadBalancerService implements LoadBalancerService {\n\n   @Resource\n   @Named(LoadBalancerConstants.LOADBALANCER_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   protected final Supplier<Location> defaultLocationSupplier;\n   protected final LoadBalancerServiceContext context;\n   protected final LoadBalanceNodesStrategy loadBalancerStrategy;\n   protected final GetLoadBalancerMetadataStrategy getLoadBalancerMetadataStrategy;\n   protected final DestroyLoadBalancerStrategy destroyLoadBalancerStrategy;\n   protected final ListLoadBalancersStrategy listLoadBalancersStrategy;\n   protected final Supplier<Set<? extends Location>> locations;\n\n   @Inject\n   protected BaseLoadBalancerService(Supplier<Location> defaultLocationSupplier, LoadBalancerServiceContext context,\n         LoadBalanceNodesStrategy loadBalancerStrategy,\n         GetLoadBalancerMetadataStrategy getLoadBalancerMetadataStrategy,\n         DestroyLoadBalancerStrategy destroyLoadBalancerStrategy, ListLoadBalancersStrategy listLoadBalancersStrategy,\n         @Memoized Supplier<Set<? extends Location>> locations) {\n      this.defaultLocationSupplier = checkNotNull(defaultLocationSupplier, \"defaultLocationSupplier\");\n      this.context = checkNotNull(context, \"context\");\n      this.loadBalancerStrategy = checkNotNull(loadBalancerStrategy, \"loadBalancerStrategy\");\n      this.getLoadBalancerMetadataStrategy = checkNotNull(getLoadBalancerMetadataStrategy,\n            \"getLoadBalancerMetadataStrategy\");\n      this.destroyLoadBalancerStrategy = checkNotNull(destroyLoadBalancerStrategy, \"destroyLoadBalancerStrategy\");\n      this.listLoadBalancersStrategy = checkNotNull(listLoadBalancersStrategy, \"listLoadBalancersStrategy\");\n      this.locations = checkNotNull(locations, \"locations\");\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Set<? extends Location> listAssignableLocations() {\n      return locations.get();\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public LoadBalancerServiceContext getContext() {\n      return context;\n   }\n\n   @Override\n   public LoadBalancerMetadata createLoadBalancerInLocation(@Nullable Location location, String loadBalancerName,\n         String protocol, int loadBalancerPort, int instancePort, Iterable<? extends NodeMetadata> nodes) {\n      if (location == null)\n         location = defaultLocationSupplier.get();\n\n      checkNotNull(loadBalancerName, \"loadBalancerName\");\n      checkNotNull(protocol, \"protocol\");\n      checkArgument(protocol.toUpperCase().equals(\"HTTP\") || protocol.toUpperCase().equals(\"TCP\"),\n            \"Acceptable values for protocol are HTTP or TCP\");\n\n      logger.debug(\">> creating load balancer (%s)\", loadBalancerName);\n      LoadBalancerMetadata lb = loadBalancerStrategy.createLoadBalancerInLocation(location, loadBalancerName, protocol,\n            loadBalancerPort, instancePort, nodes);\n      logger.debug(\"<< created load balancer (%s)\", loadBalancerName, lb);\n      return lb;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public LoadBalancerMetadata getLoadBalancerMetadata(String id) {\n      checkNotNull(id, \"id\");\n      return getLoadBalancerMetadataStrategy.getLoadBalancer(id);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void destroyLoadBalancer(final String id) {\n      checkNotNull(id, \"id\");\n      logger.debug(\">> destroying load balancer(%s)\", id);\n      final AtomicReference<LoadBalancerMetadata> loadBalancer = Atomics.newReference();\n      Predicate<String> tester = retry(new Predicate<String>() {\n         public boolean apply(String input) {\n            try {\n               LoadBalancerMetadata md = destroyLoadBalancerStrategy.destroyLoadBalancer(id);\n               if (md != null)\n                  loadBalancer.set(md);\n               return true;\n            } catch (IllegalStateException e) {\n               logger.warn(\"<< illegal state destroying load balancer(%s)\", id);\n               return false;\n            }\n         }\n      }, 3000, 1000, MILLISECONDS);  // TODO make timeouts class like ComputeServiceconstants\n      boolean successful = tester.apply(id) && loadBalancer.get() == null; // TODO add load\n                                                                           // balancerTerminated\n      // retryable predicate\n      // (load balancer.get() == null ||\n      // load balancerTerminated.apply(load balancer.get()));\n      logger.debug(\"<< destroyed load balancer(%s) success(%s)\", id, successful);\n   }\n\n   public Set<? extends LoadBalancerMetadata> listLoadBalancers() {\n      logger.debug(\">> listing load balancers\");\n      LinkedHashSet<? extends LoadBalancerMetadata> set = newLinkedHashSet(listLoadBalancersStrategy.listLoadBalancers());\n      logger.debug(\"<< list(%d)\", set.size());\n      return set;\n   }\n\n}\n"
  },
  {
    "path": "loadbalancer/src/main/java/org/jclouds/loadbalancer/internal/LoadBalancerServiceContextImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.loadbalancer.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Context;\nimport org.jclouds.internal.BaseView;\nimport org.jclouds.loadbalancer.LoadBalancerService;\nimport org.jclouds.loadbalancer.LoadBalancerServiceContext;\nimport org.jclouds.location.Provider;\nimport org.jclouds.rest.Utils;\nimport org.jclouds.util.Closeables2;\n\nimport com.google.common.reflect.TypeToken;\n\n@Singleton\npublic class LoadBalancerServiceContextImpl extends BaseView implements LoadBalancerServiceContext {\n   private final LoadBalancerService loadBalancerService;\n   private final Utils utils;\n\n   @Inject\n   public LoadBalancerServiceContextImpl(@Provider Context backend,\n            @Provider TypeToken<? extends Context> backendType, LoadBalancerService loadBalancerService, Utils utils) {\n      super(backend, backendType);\n      this.utils = utils;\n      this.loadBalancerService = checkNotNull(loadBalancerService, \"loadBalancerService\");\n   }\n\n   @Override\n   public LoadBalancerService getLoadBalancerService() {\n      return loadBalancerService;\n   }\n\n   @Override\n   public Utils utils() {\n      return utils;\n   }\n\n   @Override\n   public void close() {\n      Closeables2.closeQuietly(delegate());\n   }\n\n   public int hashCode() {\n      return delegate().hashCode();\n   }\n\n   @Override\n   public String toString() {\n      return delegate().toString();\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      return delegate().equals(obj);\n   }\n\n}\n"
  },
  {
    "path": "loadbalancer/src/main/java/org/jclouds/loadbalancer/reference/LoadBalancerConstants.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.loadbalancer.reference;\n\npublic final class LoadBalancerConstants {\n\n   public static final String LOADBALANCER_LOGGER = \"jclouds.loadbalancer\";\n\n   private LoadBalancerConstants() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "loadbalancer/src/main/java/org/jclouds/loadbalancer/strategy/DestroyLoadBalancerStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.loadbalancer.strategy;\n\nimport org.jclouds.loadbalancer.domain.LoadBalancerMetadata;\n\nimport com.google.common.annotations.Beta;\n\n@Beta\npublic interface DestroyLoadBalancerStrategy {\n\n   LoadBalancerMetadata destroyLoadBalancer(String id);\n\n}\n"
  },
  {
    "path": "loadbalancer/src/main/java/org/jclouds/loadbalancer/strategy/GetLoadBalancerMetadataStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.loadbalancer.strategy;\n\nimport org.jclouds.loadbalancer.domain.LoadBalancerMetadata;\n\n/**\n * returns all details associated to the node below.\n */\npublic interface GetLoadBalancerMetadataStrategy {\n\n   LoadBalancerMetadata getLoadBalancer(String id);\n\n}\n"
  },
  {
    "path": "loadbalancer/src/main/java/org/jclouds/loadbalancer/strategy/ListLoadBalancersStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.loadbalancer.strategy;\n\nimport org.jclouds.loadbalancer.domain.LoadBalancerMetadata;\n\nimport com.google.common.annotations.Beta;\n\n@Beta\npublic interface ListLoadBalancersStrategy {\n\n   Iterable<? extends LoadBalancerMetadata> listLoadBalancers();\n\n}\n"
  },
  {
    "path": "loadbalancer/src/main/java/org/jclouds/loadbalancer/strategy/LoadBalanceNodesStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.loadbalancer.strategy;\n\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.domain.Location;\nimport org.jclouds.loadbalancer.domain.LoadBalancerMetadata;\n\nimport com.google.common.annotations.Beta;\n\n/**\n * Creates a load balancer for nodes listed\n */\npublic interface LoadBalanceNodesStrategy {\n   /**\n    * @param location\n    *           null if default\n    * @param loadBalancerName\n    *           Load balancer name\n    * @param protocol\n    *           LoadBalancer transport protocol to use for routing - TCP or HTTP. This property\n    *           cannot be modified for the life of the LoadBalancer.\n    * @param loadBalancerPort\n    *           The external TCP port of the LoadBalancer. Valid LoadBalancer ports are - 80, 443\n    *           and 1024 through 65535. This property cannot be modified for the life of the\n    *           LoadBalancer.\n    * @param instancePort\n    *           The InstancePort data type is simple type of type: integer. It is the TCP port on\n    *           which the server on the instance is listening. Valid instance ports are one (1)\n    *           through 65535. This property cannot be modified for the life of the LoadBalancer.\n    * @param nodes\n    *           nodes to loadbalance\n    * \n    * @return newly created loadbalancer\n    * @see org.jclouds.compute.ComputeService\n    */\n   @Beta\n   LoadBalancerMetadata createLoadBalancerInLocation(Location location, String name, String protocol, int loadBalancerPort,\n         int instancePort, Iterable<? extends NodeMetadata> nodes);\n\n}\n"
  },
  {
    "path": "loadbalancer/src/test/java/org/jclouds/loadbalancer/BaseLoadBalancerServiceLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.loadbalancer;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static org.jclouds.reflect.Reflection2.typeToken;\nimport static org.jclouds.util.Predicates2.retry;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.Properties;\nimport java.util.Set;\n\nimport org.jclouds.Constants;\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.apis.BaseViewLiveTest;\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.compute.RunNodesException;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.TemplateBuilder;\nimport org.jclouds.compute.domain.TemplateBuilderSpec;\nimport org.jclouds.compute.predicates.NodePredicates;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.domain.LoginCredentials.Builder;\nimport org.jclouds.loadbalancer.domain.LoadBalancerMetadata;\nimport org.jclouds.predicates.SocketOpen;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.Iterables;\nimport com.google.common.net.HostAndPort;\nimport com.google.common.reflect.TypeToken;\nimport com.google.inject.Guice;\nimport com.google.inject.Module;\n\n@Test(groups = \"live\", singleThreaded = true)\npublic abstract class BaseLoadBalancerServiceLiveTest extends BaseViewLiveTest<LoadBalancerServiceContext> {\n\n   protected TemplateBuilderSpec template;\n   protected LoginCredentials loginCredentials = LoginCredentials.builder().user(\"root\").build();\n\n   protected Properties setupComputeProperties() {\n      Properties overrides = new Properties();\n      overrides.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, \"true\");\n      overrides.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, \"true\");\n      computeProvider = setIfTestSystemPropertyPresent(overrides, provider + \".compute.provider\");\n      computeIdentity = setIfTestSystemPropertyPresent(overrides, provider + \".compute.identity\");\n      computeCredential = setIfTestSystemPropertyPresent(overrides, provider + \".compute.credential\");\n      computeEndpoint = setIfTestSystemPropertyPresent(overrides, provider + \".compute.endpoint\");\n      computeApiversion = setIfTestSystemPropertyPresent(overrides, provider + \".compute.api-version\");\n      computeBuildversion = setIfTestSystemPropertyPresent(overrides, provider + \".compute.build-version\");\n      String spec = setIfTestSystemPropertyPresent(overrides, provider + \".compute.template\");\n      if (spec != null) {\n         template = TemplateBuilderSpec.parse(spec);\n         if (template.getLoginUser() != null) {\n            Iterable<String> userPass = Splitter.on(':').split(template.getLoginUser());\n            Builder loginCredentialsBuilder = LoginCredentials.builder();\n            loginCredentialsBuilder.user(Iterables.get(userPass, 0));\n            if (Iterables.size(userPass) == 2)\n               loginCredentialsBuilder.password(Iterables.get(userPass, 1));\n            if (template.getAuthenticateSudo() != null)\n               loginCredentialsBuilder.authenticateSudo(template.getAuthenticateSudo());\n            loginCredentials = loginCredentialsBuilder.build();\n         }\n      }\n      return overrides;\n   }\n\n   protected String group;\n\n   protected Predicate<HostAndPort> socketTester;\n   protected Set<? extends NodeMetadata> nodes;\n   protected LoadBalancerMetadata loadbalancer;\n\n   protected String computeProvider;\n   protected String computeIdentity;\n   protected String computeCredential;\n   protected String computeEndpoint;\n   protected String computeApiversion;\n   protected String computeBuildversion;\n   protected ComputeServiceContext computeContext;\n\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   @Override\n   public void setupContext() {\n      super.setupContext();\n      if (group == null)\n         group = checkNotNull(provider, \"provider\");\n      // groups need to work with hyphens in them, so let's make sure there is\n      // one, without making it the first or last character\n      if (group.indexOf('-') == -1)\n         group = new StringBuilder(group).insert(1, \"-\").toString();\n      initializeComputeContext();\n      buildSocketTester();\n   }\n\n   protected void initializeComputeContext() {\n      if (computeContext != null)\n         computeContext.close();\n      Properties overrides = setupComputeProperties();\n      ContextBuilder builder = ContextBuilder.newBuilder(computeProvider)\n               .credentials(computeIdentity, computeCredential).overrides(overrides).modules(setupModules());\n      if (computeApiversion != null)\n         builder.apiVersion(computeApiversion);\n      if (computeBuildversion != null)\n         builder.buildVersion(computeBuildversion);\n\n      computeContext = builder.buildView(ComputeServiceContext.class);\n   }\n\n   protected void buildSocketTester() {\n      SocketOpen socketOpen = Guice.createInjector(getSshModule()).getInstance(SocketOpen.class);\n      socketTester = retry(socketOpen, 60, 1, SECONDS);\n   }\n\n   protected abstract Module getSshModule();\n\n   @BeforeClass(groups = { \"integration\", \"live\" }, dependsOnMethods = \"setupContext\")\n   public void createNodes() throws RunNodesException {\n      try {\n         TemplateBuilder builder = computeContext.getComputeService().templateBuilder();\n         if (template != null)\n            builder.from(template);\n         nodes = computeContext.getComputeService().createNodesInGroup(group, 2, builder.build());\n      } catch (RunNodesException e) {\n         nodes = e.getSuccessfulNodes();\n         throw e;\n      }\n   }\n\n   @Test(enabled = true)\n   public void testLoadBalanceNodesMatching() throws Exception {\n\n      // create load balancers\n      loadbalancer = view.getLoadBalancerService().createLoadBalancerInLocation(null, group, \"HTTP\", 80, 80, nodes);\n      assertNotNull(loadbalancer);\n      validateNodesInLoadBalancer();\n\n   }\n\n   // TODO create a LoadBalancerService method for this.\n   protected abstract void validateNodesInLoadBalancer();\n\n   @Test(enabled = true, dependsOnMethods = \"testLoadBalanceNodesMatching\")\n   public void testDestroyLoadBalancers() throws Exception {\n      view.getLoadBalancerService().destroyLoadBalancer(loadbalancer.getId());\n   }\n   \n   @AfterClass(groups = { \"integration\", \"live\" })\n   @Override\n   protected void tearDownContext() {\n      if (loadbalancer != null) {\n         view.getLoadBalancerService().destroyLoadBalancer(loadbalancer.getId());\n      }\n      if (nodes != null) {\n         computeContext.getComputeService().destroyNodesMatching(NodePredicates.inGroup(group));\n      }\n      computeContext.close();\n      super.tearDownContext();\n   }\n\n   @Override\n   protected TypeToken<LoadBalancerServiceContext> viewType() {\n      return typeToken(LoadBalancerServiceContext.class);\n   }\n}\n"
  },
  {
    "path": "loadbalancer/src/test/java/org/jclouds/loadbalancer/internal/BaseLoadBalancerServiceApiMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.loadbalancer.internal;\n\n\nimport static org.jclouds.reflect.Reflection2.typeToken;\n\nimport org.jclouds.View;\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.apis.internal.BaseApiMetadataTest;\nimport org.jclouds.loadbalancer.LoadBalancerServiceContext;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.reflect.TypeToken;\n\n@Test(groups = \"unit\")\npublic abstract class BaseLoadBalancerServiceApiMetadataTest extends BaseApiMetadataTest {\n\n   public BaseLoadBalancerServiceApiMetadataTest(ApiMetadata toTest) {\n     super(toTest, ImmutableSet.<TypeToken<? extends View>>of(typeToken(LoadBalancerServiceContext.class)));\n   }\n\n}\n"
  },
  {
    "path": "pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>        \n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>project/pom.xml</relativePath>\n  </parent>\n  <artifactId>jclouds</artifactId>\n  <name>Apache jclouds</name>\n  <packaging>pom</packaging>\n  <modules>\n    <module>project</module>\n    <module>resources</module>\n    <module>core</module>\n    <module>scriptbuilder</module>\n    <module>blobstore</module>\n    <module>compute</module>\n    <module>loadbalancer</module>\n    <module>common</module>\n    <module>apis</module>\n    <module>providers</module>\n    <module>skeletons</module>\n    <module>drivers</module>\n    <module>allcompute</module>\n    <module>allblobstore</module>\n    <module>allloadbalancer</module>\n    <module>all</module>\n  </modules>\n</project>\n"
  },
  {
    "path": "project/bnd.bnd",
    "content": "Bundle-Developers:\nBundle-DocURL:\nBundle-License:\nBundle-SCM:\nBundle-Vendor:\n\nSpecification-Title: \\\n    jclouds ${project.name}\\\n\nSpecification-Vendor: \\\n    jclouds\n\nImplementation-Vendor: \\\n    jclouds\n\nImplementation-Vendor-Id: \\\n    org.apache.jclouds\n\nImplementation-Version: \\\n    ${project.version}\n\nX-Compile-Source-JDK: \\\n    ${maven.compile.source}\n\nX-Compile-Target-JDK: \\\n    ${maven.compile.target}\n\nImport-Package: \\\n    com.google.common.*;version=\"[27.1,30.1.0)\", \\\n    *"
  },
  {
    "path": "project/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache</groupId>\n    <artifactId>apache</artifactId>\n    <version>14</version>\n    <relativePath />\n  </parent>\n  <groupId>org.apache.jclouds</groupId>\n  <artifactId>jclouds-project</artifactId>\n  <version>2.7.1-SNAPSHOT</version>\n  <packaging>pom</packaging>\n  <name>Apache jclouds Project</name>\n  <url>https://jclouds.apache.org/</url>\n  <description>Apache jclouds: Concurrent API for Cloud Services</description>\n  <inceptionYear>2009</inceptionYear>\n\n  <licenses>\n    <license>\n      <name>The Apache Software License, Version 2.0</name>\n      <url>https://www.apache.org/licenses/LICENSE-2.0.txt</url>\n      <distribution>repo</distribution>\n    </license>\n  </licenses>\n\n\n  <issueManagement>\n    <system>JIRA</system>\n    <url>https://issues.apache.org/jira/browse/JCLOUDS</url>\n  </issueManagement>\n\n\n  <mailingLists>\n    <mailingList>\n      <name>User List</name>\n      <subscribe>user-subscribe@jclouds.apache.org</subscribe>\n      <unsubscribe>user-unsubscribe@jclouds.apache.org</unsubscribe>\n      <post>user@jclouds.apache.org</post>\n      <archive>https://mail-archives.apache.org/mod_mbox/jclouds-user/</archive>\n    </mailingList>\n    <mailingList>\n      <name>Developer List</name>\n      <subscribe>dev-subscribe@jclouds.apache.org</subscribe>\n      <unsubscribe>dev-unsubscribe@jclouds.apache.org</unsubscribe>\n      <post>dev@jclouds.apache.org</post>\n      <archive>https://mail-archives.apache.org/mod_mbox/jclouds-dev/</archive>\n    </mailingList>\n    <mailingList>\n      <name>Commits List</name>\n      <subscribe>commits-subscribe@jclouds.apache.org</subscribe>\n      <unsubscribe>commits-unsubscribe@jclouds.apache.org</unsubscribe>\n      <archive>https://mail-archives.apache.org/mod_mbox/jclouds-commits/</archive>\n    </mailingList>\n    <mailingList>\n      <name>Issues List</name>\n      <subscribe>issues-subscribe@jclouds.apache.org</subscribe>\n      <unsubscribe>issues-unsubscribe@jclouds.apache.org</unsubscribe>\n      <archive>https://mail-archives.apache.org/mod_mbox/jclouds-issues/</archive>\n    </mailingList>\n  </mailingLists>\n\n  <scm>\n    <connection>scm:git:https://gitbox.apache.org/repos/asf/jclouds.git</connection>\n    <developerConnection>scm:git:https://gitbox.apache.org/repos/asf/jclouds.git</developerConnection>\n    <url>https://gitbox.apache.org/repos/asf?p=jclouds.git</url>\n    <tag>HEAD</tag>\n  </scm>\n\n  <repositories>\n    <repository>\n      <id>apache-snapshots</id>\n      <url>https://repository.apache.org/content/repositories/snapshots</url>\n      <releases>\n        <enabled>false</enabled>\n      </releases>\n      <snapshots>\n        <enabled>true</enabled>\n      </snapshots>\n    </repository>\n  </repositories>\n\n  <!-- to allow downstream projects to access jclouds-resources in plugin config -->\n  <pluginRepositories>\n    <pluginRepository>\n      <id>apache-snapshots</id>\n      <url>https://repository.apache.org/content/repositories/snapshots</url>\n      <releases>\n        <enabled>false</enabled>\n      </releases>\n      <snapshots>\n        <enabled>true</enabled>\n      </snapshots>\n    </pluginRepository>\n  </pluginRepositories>\n\n  <developers>\n    <developer>\n      <name>Andrew Bayer</name>\n      <id>abayer</id>\n      <roles>\n        <role>Committer</role>\n        <role>PMC Member</role>\n      </roles>\n    </developer>\n    <developer>\n      <name>Andrea Turli</name>\n      <id>andreaturli</id>\n      <roles>\n        <role>Committer</role>\n      </roles>\n    </developer>\n    <developer>\n      <name>Andrew Gaul</name>\n      <id>gaul</id>\n      <roles>\n        <role>Committer</role>\n        <role>PMC Member</role>\n      </roles>\n    </developer>\n    <developer>\n      <name>Andrew Phillips</name>\n      <id>andrewp</id>\n      <roles>\n        <role>Committer</role>\n        <role>PMC Member</role>\n      </roles>\n      <timezone>+1</timezone>\n    </developer>\n    <developer>\n      <name>Becca Woods</name>\n      <id>silkysun</id>\n      <roles>\n        <role>Committer</role>\n        <role>PMC Member</role>\n      </roles>\n    </developer>\n    <developer>\n      <name>Chris Custine</name>\n      <id>ccustine</id>\n      <roles>\n        <role>Committer</role>\n        <role>PMC Member</role>\n      </roles>\n    </developer>\n    <developer>\n      <name>Everett Toews</name>\n      <id>everett</id>\n      <roles>\n        <role>Committer</role>\n        <role>PMC Member</role>\n      </roles>\n    </developer>\n    <developer>\n      <name>Ignasi Barrera</name>\n      <id>nacx</id>\n      <roles>\n        <role>Committer</role>\n        <role>PMC Member</role>\n      </roles>\n    </developer>\n    <developer>\n      <name>Ioannis Canellos</name>\n      <id>iocanel</id>\n      <roles>\n        <role>Committer</role>\n        <role>PMC Member</role>\n      </roles>\n    </developer>\n    <developer>\n      <name>Jeremy Daggett</name>\n      <id>jdaggett</id>\n      <roles>\n        <role>Committer</role>\n      </roles>\n    </developer>\n    <developer>\n      <name>Matt Stephenson</name>\n      <id>mattstep</id>\n      <roles>\n        <role>Committer</role>\n        <role>PMC Member</role>\n      </roles>\n    </developer>\n    <developer>\n      <name>Zach Shoylev</name>\n      <id>zachsh</id>\n      <roles>\n        <role>Committer</role>\n      </roles>\n    </developer>\n  </developers>\n\n  <properties>\n    <jdk.version>11</jdk.version>\n    <maven.compile.source>${jdk.version}</maven.compile.source>\n    <maven.compile.target>${jdk.version}</maven.compile.target>\n    <maven.compile.deprecation>true</maven.compile.deprecation>\n    <project.build.outputTimestamp>1668154596</project.build.outputTimestamp>\n\n    <!-- Plugin versions -->\n    <maven-jar-plugin.version>3.3.0</maven-jar-plugin.version>\n    <maven-surefire-plugin.version>3.1.0</maven-surefire-plugin.version>\n\n    <!-- General dependency versions -->\n    <gson.version>2.11.0</gson.version>\n    <guava.version>33.4.0-jre</guava.version>\n    <guice.version>7.0.0</guice.version>\n\n    <okhttp.version>3.14.9</okhttp.version>\n    <auto-factory.version>1.1.0</auto-factory.version>\n    <auto-service.version>1.1.1</auto-service.version>\n    <auto-value.version>1.5.4</auto-value.version>\n\n    <jetty.version>9.4.56.v20240826</jetty.version>\n\n    <modernizer.version>3.1.0</modernizer.version>\n\n    <!-- Log dependency versions -->\n    <log4j.version>2.17.2</log4j.version>\n    <logback.version>1.5.16</logback.version>\n\n    <!-- OSGi dependency versions -->\n    <osgi.version>6.0.0</osgi.version>\n\n    <!-- Test dependency versions -->\n    <testng.version>7.5.1</testng.version>\n    <xmlunit.version>1.6</xmlunit.version>\n    <assertj-core.version>3.23.1</assertj-core.version>\n    <assertj-guava.version>1.3.0</assertj-guava.version>\n\n    <!-- Static analysis dependency versions -->\n    <jsr305.version>1.3.9</jsr305.version>\n\n    <http.proxyHost />\n    <http.proxyPort />\n    <jclouds.wire.httpstream.url>https://archive.apache.org/dist/commons/logging/binaries/commons-logging-1.1.1-bin.tar.gz</jclouds.wire.httpstream.url>\n    <jclouds.wire.httpstream.md5>e5de09672af9b386c30a311654d8541a</jclouds.wire.httpstream.md5>\n    <jclouds.blobstore.httpstream.url>${jclouds.wire.httpstream.url}</jclouds.blobstore.httpstream.url>\n    <jclouds.blobstore.httpstream.md5>${jclouds.wire.httpstream.md5}</jclouds.blobstore.httpstream.md5>\n    <jclouds.test.listener>org.jclouds.test.testng.UnitTestStatusListener</jclouds.test.listener>\n    <test.ssh.keyfile />\n    <sourceReleaseAssemblyDescriptor>source-release-zip-tar</sourceReleaseAssemblyDescriptor>\n  </properties>\n\n  <dependencyManagement>\n    <dependencies>\n      <!-- General dependencies -->\n      <dependency>\n        <groupId>com.google.code.gson</groupId>\n        <artifactId>gson</artifactId>\n        <version>${gson.version}</version>\n      </dependency>\n      <dependency>\n        <groupId>com.google.guava</groupId>\n        <artifactId>guava</artifactId>\n        <version>${guava.version}</version>\n      </dependency>\n      <dependency>\n        <groupId>com.google.inject</groupId>\n        <artifactId>guice</artifactId>\n        <version>${guice.version}</version>\n      </dependency>\n      <dependency>\n        <groupId>com.google.inject.extensions</groupId>\n        <artifactId>guice-assistedinject</artifactId>\n        <version>${guice.version}</version>\n      </dependency>\n\n      <dependency>\n        <groupId>com.google.auto.factory</groupId>\n        <artifactId>auto-factory</artifactId>\n        <version>${auto-factory.version}</version>\n      </dependency>\n      <dependency>\n        <groupId>com.google.auto.service</groupId>\n        <artifactId>auto-service</artifactId>\n        <version>${auto-service.version}</version>\n      </dependency>\n      <dependency>\n        <groupId>com.google.auto.value</groupId>\n        <artifactId>auto-value</artifactId>\n        <version>${auto-value.version}</version>\n      </dependency>\n\n      <dependency>\n        <groupId>org.eclipse.jetty</groupId>\n        <artifactId>jetty-security</artifactId>\n        <version>${jetty.version}</version>\n      </dependency>\n\n      <dependency>\n        <groupId>jakarta.ws.rs</groupId>\n        <artifactId>jakarta.ws.rs-api</artifactId>\n        <version>3.0.0</version>\n      </dependency>\n\n      <dependency>\n        <groupId>jakarta.annotation</groupId>\n        <artifactId>jakarta.annotation-api</artifactId>\n        <version>2.0.0</version>\n      </dependency>\n\n      <dependency>\n        <groupId>jakarta.inject</groupId>\n        <artifactId>jakarta.inject-api</artifactId>\n        <version>2.0.1</version>\n      </dependency>\n\n      <dependency>\n        <groupId>jakarta.xml.bind</groupId>\n        <artifactId>jakarta.xml.bind-api</artifactId>\n        <version>4.0.2</version>\n      </dependency>\n\n      <dependency>\n        <groupId>org.glassfish.jaxb</groupId>\n        <artifactId>jaxb-runtime</artifactId>\n        <version>4.0.5</version>\n      </dependency>\n\n      <dependency>\n        <groupId>org.gaul</groupId>\n        <artifactId>modernizer-maven-annotations</artifactId>\n        <version>${modernizer.version}</version>\n      </dependency>\n\n      <!-- Log dependencies -->\n      <dependency>\n        <groupId>org.apache.logging.log4j</groupId>\n        <artifactId>log4j-core</artifactId>\n        <version>${log4j.version}</version>\n      </dependency>\n      <dependency>\n        <groupId>ch.qos.logback</groupId>\n        <artifactId>logback-classic</artifactId>\n        <version>${logback.version}</version>\n      </dependency>\n      <dependency>\n        <groupId>ch.qos.logback</groupId>\n        <artifactId>logback-core</artifactId>\n        <version>${logback.version}</version>\n      </dependency>\n\n      <!-- OSGi dependencies -->\n      <dependency>\n        <groupId>org.osgi</groupId>\n        <artifactId>org.osgi.core</artifactId>\n        <version>${osgi.version}</version>\n      </dependency>\n      <dependency>\n        <groupId>org.osgi</groupId>\n        <artifactId>osgi.cmpn</artifactId>\n        <version>${osgi.version}</version>\n      </dependency>\n\n      <!-- Test dependencies -->\n      <dependency>\n        <groupId>org.testng</groupId>\n        <artifactId>testng</artifactId>\n        <version>${testng.version}</version>\n        <exclusions>\n          <exclusion>\n            <groupId>junit</groupId>\n            <artifactId>junit</artifactId>\n          </exclusion>\n        </exclusions>\n      </dependency>\n      <dependency>\n        <groupId>xmlunit</groupId>\n        <artifactId>xmlunit</artifactId>\n        <version>${xmlunit.version}</version>\n      </dependency>\n      <dependency>\n        <groupId>org.assertj</groupId>\n        <artifactId>assertj-core</artifactId>\n        <version>${assertj-core.version}</version>\n      </dependency>\n      <dependency>\n        <groupId>org.assertj</groupId>\n        <artifactId>assertj-guava</artifactId>\n        <version>${assertj-guava.version}</version>\n      </dependency>\n\n      <!-- Mock dependencies -->\n      <dependency>\n        <groupId>org.easymock</groupId>\n        <artifactId>easymock</artifactId>\n        <version>5.5.0</version>\n      </dependency>\n      <dependency>\n        <groupId>com.squareup.okhttp3</groupId>\n        <artifactId>mockwebserver</artifactId>\n        <version>${okhttp.version}</version>\n      </dependency>\n      <dependency>\n        <groupId>com.squareup.okhttp3</groupId>\n        <artifactId>okhttp-tls</artifactId>\n        <version>${okhttp.version}</version>\n      </dependency>\n\n      <!-- Static analysis dependencies -->\n      <dependency>\n        <groupId>com.google.code.findbugs</groupId>\n        <artifactId>jsr305</artifactId>\n        <version>${jsr305.version}</version>\n      </dependency>\n    </dependencies>\n  </dependencyManagement>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.testng</groupId>\n      <artifactId>testng</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.easymock</groupId>\n      <artifactId>easymock</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>xmlunit</groupId>\n      <artifactId>xmlunit</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.assertj</groupId>\n      <artifactId>assertj-core</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.assertj</groupId>\n      <artifactId>assertj-guava</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.code.findbugs</groupId>\n      <artifactId>jsr305</artifactId>\n      <scope>provided</scope>\n    </dependency>\n  </dependencies>\n\n  <build>\n    <resources>\n      <resource>\n        <directory>src/main/resources</directory>\n      </resource>\n      <!-- For AutoService generated services. -->\n      <resource>\n        <directory>target/classes</directory>\n        <includes>\n          <include>META-INF/services/*</include>\n        </includes>\n      </resource>\n    </resources>\n    <testResources>\n      <testResource>\n        <directory>src/test/resources</directory>\n      </testResource>\n    </testResources>\n    <plugins>\n      <plugin>\n        <groupId>org.apache.maven.plugins</groupId>\n        <artifactId>maven-release-plugin</artifactId>\n        <version>3.0.0-M7</version>\n        <configuration>\n          <useReleaseProfile>false</useReleaseProfile>\n          <goals>deploy</goals>\n          <arguments>-Pdoc -Papache-release ${arguments}</arguments>\n        </configuration>\n      </plugin>\n\n      <plugin>\n        <groupId>org.apache.rat</groupId>\n        <artifactId>apache-rat-plugin</artifactId>\n        <executions>\n          <execution>\n            <phase>package</phase>\n            <goals>\n              <goal>check</goal>\n            </goals>\n          </execution>\n        </executions>\n      </plugin>\n      <plugin>\n        <groupId>org.basepom.maven</groupId>\n        <artifactId>duplicate-finder-maven-plugin</artifactId>\n        <executions>\n          <execution>\n            <phase>verify</phase>\n            <goals>\n              <goal>check</goal>\n            </goals>\n          </execution>\n        </executions>\n      </plugin>\n      <plugin>\n        <groupId>org.codehaus.mojo</groupId>\n        <artifactId>animal-sniffer-maven-plugin</artifactId>\n        <version>1.20</version>\n        <executions>\n          <execution>\n            <phase>test</phase>\n            <goals>\n              <goal>check</goal>\n            </goals>\n          </execution>\n        </executions>\n        <configuration>\n          <signature>\n            <groupId>org.codehaus.mojo.signature</groupId>\n            <artifactId>java18</artifactId>\n            <version>1.0</version>\n          </signature>\n        </configuration>\n      </plugin>\n      <plugin>\n        <groupId>org.apache.maven.plugins</groupId>\n        <artifactId>maven-surefire-plugin</artifactId>\n        <version>${maven-surefire-plugin.version}</version>\n        <executions>\n          <execution>\n            <id>integration</id>\n            <phase>integration-test</phase>\n            <goals>\n              <goal>test</goal>\n            </goals>\n            <configuration>\n              <argLine>-Xmx512m -Xms256m -Djava.awt.headless=true -Xss256k</argLine>\n              <parallel>tests</parallel>\n              <threadCount>5</threadCount>\n              <!-- note that the groups/excluded groups don't work due to some problem\n                   in surefire or testng. instead, we have to exclude via file path\n                   <groups>integration</groups>\n                   <excludedGroups>unit,performance,live</excludedGroups> -->\n              <excludes>\n                <exclude>**/*LiveTest.java</exclude>\n              </excludes>\n              <includes>\n                <include>**/*IntegrationTest.java</include>\n              </includes>\n            </configuration>\n          </execution>\n        </executions>\n        <configuration>\n          <parallel>methods</parallel>\n          <threadCount>5</threadCount>\n          <!-- note that the groups/excluded groups don't work due to some problem\n               in surefire or testng. instead, we have to exclude via file path\n               <groups>unit,performance</groups>\n               <excludedGroups>integration,live</excludedGroups> -->\n          <excludes>\n            <exclude>**/*IntegrationTest.java</exclude>\n            <exclude>**/*LiveTest.java</exclude>\n          </excludes>\n          <properties>\n            <property>\n              <name>listener</name>\n              <value>${jclouds.test.listener}</value>\n            </property>\n          </properties>\n          <systemPropertyVariables>\n            <sun.net.http.allowRestrictedHeaders>true</sun.net.http.allowRestrictedHeaders>\n            <jclouds.wire.httpstream.url>${jclouds.wire.httpstream.url}</jclouds.wire.httpstream.url>\n            <jclouds.wire.httpstream.md5>${jclouds.wire.httpstream.md5}</jclouds.wire.httpstream.md5>\n          </systemPropertyVariables>\n        </configuration>\n      </plugin>\n      <plugin>\n        <groupId>org.apache.maven.plugins</groupId>\n        <artifactId>maven-resources-plugin</artifactId>\n        <version>2.6</version>\n        <configuration>\n          <encoding>${project.build.sourceEncoding}</encoding>\n        </configuration>\n      </plugin>\n      <plugin>\n        <artifactId>maven-checkstyle-plugin</artifactId>\n        <version>3.0.0</version>\n        <!-- configuration and dependencies set via profiles -->\n        <executions>\n          <execution>\n            <id>default</id>\n            <phase>verify</phase>\n            <goals>\n              <goal>check</goal>\n            </goals>\n          </execution>\n        </executions>\n      </plugin>\n      <plugin>\n        <groupId>org.gaul</groupId>\n        <artifactId>modernizer-maven-plugin</artifactId>\n        <version>${modernizer.version}</version>\n        <!-- configuration and dependencies set via profiles -->\n        <executions>\n          <execution>\n            <id>modernizer</id>\n            <phase>verify</phase>\n            <goals>\n              <goal>modernizer</goal>\n            </goals>\n          </execution>\n        </executions>\n      </plugin>\n    </plugins>\n    <pluginManagement>\n      <plugins>\n        <plugin>\n          <groupId>org.apache.maven.plugins</groupId>\n          <artifactId>maven-jar-plugin</artifactId>\n          <version>${maven-jar-plugin.version}</version>\n          <executions>\n            <execution>\n              <goals>\n                <goal>test-jar</goal>\n              </goals>\n            </execution>\n          </executions>\n        </plugin>\n        <plugin>\n          <groupId>org.apache.maven.plugins</groupId>\n          <artifactId>maven-assembly-plugin</artifactId>\n          <version>3.3.0</version>\n        </plugin>\n        <plugin>\n          <groupId>org.apache.maven.plugins</groupId>\n          <artifactId>maven-remote-resources-plugin</artifactId>\n          <version>1.7.0</version>\n        </plugin>\n        <plugin>\n          <groupId>org.apache.maven.plugins</groupId>\n          <artifactId>maven-source-plugin</artifactId>\n          <version>3.2.1</version>\n        </plugin>\n        <plugin>\n          <groupId>org.apache.maven.plugins</groupId>\n          <artifactId>maven-compiler-plugin</artifactId>\n          <version>3.8.0</version>\n          <configuration>\n            <encoding>${project.build.sourceEncoding}</encoding>\n            <source>${maven.compile.source}</source>\n            <target>${maven.compile.target}</target>\n            <showDeprecation>false</showDeprecation>\n            <showWarnings>true</showWarnings>\n            <compilerArgs>\n              <compilerArg>-Xlint</compilerArg>\n              <compilerArg>-Xlint:-deprecation</compilerArg>\n              <compilerArg>-Xlint:-processing</compilerArg>\n              <compilerArg>-Xlint:-rawtypes</compilerArg>\n              <compilerArg>-Xlint:-serial</compilerArg>\n              <compilerArg>-Xlint:-unchecked</compilerArg>\n            </compilerArgs>\n          </configuration>\n        </plugin>\n        <plugin>\n          <artifactId>maven-archetype-plugin</artifactId>\n          <version>3.2.0</version>\n        </plugin>\n        <plugin>\n          <artifactId>maven-deploy-plugin</artifactId>\n          <version>2.7</version>\n        </plugin>\n        <plugin>\n          <artifactId>maven-install-plugin</artifactId>\n          <version>2.4</version>\n        </plugin>\n        <plugin>\n          <groupId>com.github.spotbugs</groupId>\n          <artifactId>spotbugs-maven-plugin</artifactId>\n          <version>3.1.3</version>\n          <configuration>\n            <omitVisitors>\n              CloneIdiom,\n              ComparatorIdiom,\n              DefaultEncodingDetector,\n              EqualsOperandShouldHaveClassCompatibleWithThis,\n              FindBadCast2,\n              FindHEmismatch,\n              FindMaskedFields,\n              FindNullDeref,\n              FindReturnRef,\n              FindUnsatisfiedObligation,\n              FormatStringChecker,\n              MethodReturnCheck,\n              Naming,\n              NoteUnconditionalParamDerefs,\n              RuntimeExceptionCapture,\n              SwitchFallthrough,\n              UnreadFields,\n            </omitVisitors>\n          </configuration>\n        </plugin>\n        <plugin>\n          <groupId>org.apache.rat</groupId>\n          <artifactId>apache-rat-plugin</artifactId>\n          <version>0.12</version>\n          <configuration>\n            <excludes>\n              <!-- expectation files for unit tests -->\n              <exclude>**/src/test/resources/**/*.sh</exclude>\n              <exclude>**/src/test/resources/**/*.bat</exclude>\n              <exclude>**/src/test/resources/**/*.cmd</exclude>\n              <exclude>**/src/test/resources/**/*.txt</exclude>\n              <exclude>**/src/test/resources/**/*.gz</exclude>\n              <exclude>**/src/test/resources/**/*.xml</exclude>\n              <exclude>**/src/test/resources/**/*.crt</exclude>\n              <exclude>src/test/resources/html/*.html</exclude>\n\n              <!-- META-INF/services files -->\n              <exclude>**/services/*LoggingModule</exclude>\n              <exclude>**/services/*ApiMetadata</exclude>\n              <exclude>**/services/*ProviderMetadata</exclude>\n              <!-- OSGi metadata rules -->\n              <exclude>**/bnd.bnd</exclude>\n              <!-- prevent duplicating license -->\n              <exclude>**/LICENSE.txt</exclude>\n              <exclude>**/header.txt</exclude>\n\n              <!-- high-level project metadata -->\n              <exclude>**/NOTICE.txt</exclude>\n              <exclude>**/DISCLAIMER</exclude>\n              <exclude>**/BUILD.txt</exclude>\n              <exclude>**/CHANGES.txt</exclude>\n              <exclude>**/README.md</exclude>\n              <exclude>**/README.txt</exclude>\n              <exclude>**/DEPENDENCIES</exclude>\n              <exclude>**/CONTRIBUTING.md</exclude>\n\n              <!-- reference data lists -->\n              <exclude>**/*json</exclude>\n              <exclude>**/*readme</exclude>\n\n              <!-- SSH keys -->\n              <exclude>**/test</exclude>\n              <exclude>**/test.pub</exclude>\n              <exclude>**/src/test/resources/**/ssh-*.pub</exclude>\n\n              <!-- temporary exclude due to minimized module declaration -->\n              <exclude>**/providers/profitbricks/src/test/resources/html/maintenance-503.html</exclude>\n              <exclude>**/providers/profitbricks/src/test/resources/html/fault-401.html</exclude>\n\n              <!-- temporary files or those generated by IDE or SCM -->\n              <exclude>**/target/**</exclude>\n              <exclude>**/test-output/**</exclude>\n              <exclude>**/bin/**</exclude>\n              <exclude>**/.settings/**</exclude>\n              <exclude>**/.classpath</exclude>\n              <exclude>**/.dir-locals.el</exclude>\n              <exclude>**/.project</exclude>\n              <exclude>**/.idea/**</exclude>\n              <exclude>**/*.iml</exclude>\n              <exclude>**/*.eml</exclude>\n              <exclude>**/*.ipr</exclude>\n              <exclude>**/*.iws</exclude>\n              <exclude>**/*.DS_STORE</exclude>\n              <exclude>**/TAGS</exclude>\n              <exclude>**/.metadata/**</exclude>\n              <exclude>**/atlassian-ide-plugin.xml</exclude>\n              <exclude>**/.DS_Store</exclude>\n              <exclude>.mailmap</exclude>\n              <exclude>.git/**</exclude>\n              <exclude>**/.gitignore</exclude>\n              <exclude>**/.gitattributes</exclude>\n              <exclude>**/.java-version</exclude>\n              <exclude>**/modernizer_exclusions.txt</exclude>\n              <exclude>**/.factorypath</exclude>\n              <exclude>**/.apt_generated/**</exclude>\n              <exclude>**/.apt_generated_tests/**</exclude>\n              <exclude>**/.checkstyle</exclude>\n              <exclude>nb-configuration.xml</exclude>\n              <exclude>nbactions.xml</exclude>\n              <exclude>dependency-reduced-pom.xml</exclude>\n\n              <!-- Temporary files generated on CloudBees slaves -->\n              <exclude>.repository/**</exclude>\n              <exclude>gc.log</exclude>\n            </excludes>\n          </configuration>\n        </plugin>\n        <plugin>\n          <groupId>org.basepom.maven</groupId>\n          <artifactId>duplicate-finder-maven-plugin</artifactId>\n          <version>1.5.0</version>\n          <configuration>\n            <exceptions>\n              <exception>\n                <!-- Google App Engine Deps, some google classes are duplicated between packages -->\n                <conflictingDependencies>\n                  <dependency>\n                    <groupId>com.google.appengine</groupId>\n                    <artifactId>appengine-api-1.0-sdk</artifactId>\n                    <version>1.6.5</version>\n                  </dependency>\n                  <dependency>\n                    <groupId>com.google.appengine</groupId>\n                    <artifactId>appengine-testing</artifactId>\n                    <version>1.6.5</version>\n                    <scope>test</scope>\n                  </dependency>\n                </conflictingDependencies>\n                <packages>\n                  <package>com.google</package>\n                </packages>\n              </exception>\n              <exception>\n                <conflictingDependencies>\n                  <dependency>\n                    <groupId>com.jcraft</groupId>\n                    <artifactId>jsch.agentproxy.core</artifactId>\n                    <version>0.0.9</version>\n                  </dependency>\n                  <dependency>\n                    <groupId>com.jcraft</groupId>\n                    <artifactId>jsch.agentproxy.connector-factory</artifactId>\n                    <version>0.0.9</version>\n                  </dependency>\n                </conflictingDependencies>\n                <packages>\n                  <package>com.jcraft.jsch.agentproxy</package>\n                </packages>\n              </exception>\n            </exceptions>\n            <ignoredResourcePatterns>\n              <!-- For all the jetty packages -->\n              <ignoredResourcePattern>about\\.html</ignoredResourcePattern>\n              <!-- There are several situations where a test-jar and another test-jar or a bundle conflict on these artifacts -->\n              <ignoredResourcePattern>log4j.xml</ignoredResourcePattern>\n              <ignoredResourcePattern>os.xml</ignoredResourcePattern>\n              <ignoredResourcePattern>virtualhardwaresection.xml</ignoredResourcePattern>\n              <ignoredResourcePattern>logback.xml</ignoredResourcePattern>\n              <ignoredResourcePattern>amzn_images.xml</ignoredResourcePattern>\n              <ignoredResourcePattern>test.jks</ignoredResourcePattern>\n              <ignoredResourcePattern>test</ignoredResourcePattern>\n              <ignoredResourcePattern>CreateInternetService-options-test.xml</ignoredResourcePattern>\n              <ignoredResourcePattern>.gitattributes</ignoredResourcePattern>\n              <ignoredResourcePattern>functions/.gitattributes</ignoredResourcePattern>\n              <!-- For bouncycastle -->\n              <ignoredResourcePattern>META-INF/BCKEY.DSA</ignoredResourcePattern>\n              <ignoredResourcePattern>META-INF/BCKEY.SF</ignoredResourcePattern>\n            </ignoredResourcePatterns>\n            <failBuildInCaseOfConflict>true</failBuildInCaseOfConflict>\n            <skip>${skipDuplicateFinder}</skip>\n          </configuration>\n        </plugin>\n      </plugins>\n    </pluginManagement>\n  </build>\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <!-- note that the groups/excluded groups don't work due to some problem\n                       in surefire or testng. instead, we have to exclude via file path\n                       <groups>live,integration</groups>\n                       <excludedGroups>unit,performance</excludedGroups> -->\n                  <excludes>\n                    <exclude>none</exclude>\n                  </excludes>\n                  <includes>\n                    <include>**/*IntegrationTest.java</include>\n                    <include>**/*LiveTest.java</include>\n                  </includes>\n                  <systemPropertyVariables>\n                    <!--\n                        If you're behind a proxy, set this here\n                        https://docs.oracle.com/javase/6/docs/technotes/guides/net/proxies.html\n\n<https.proxyHost>proxy</https.proxyHost>\n<https.proxyPort>port</https.proxyPort>\n<https.noProxyHosts>localhost|10.150.4.49</https.noProxyHosts>\n                    -->\n                    <file.encoding>${project.build.sourceEncoding}</file.encoding>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n    <profile>\n      <id>jclouds-project</id>\n      <activation>\n        <file>\n          <!-- only in the jclouds-project module -->\n          <exists>src/etc/header.txt</exists>\n        </file>\n      </activation>\n\n      <build>\n        <plugins>\n          <plugin>\n            <!-- When building jclouds-project, override the config to use the local file -->\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-checkstyle-plugin</artifactId>\n            <configuration>\n              <configLocation>../resources/checkstyle.xml</configLocation>\n              <includeTestSourceDirectory>true</includeTestSourceDirectory>\n              <failOnViolation>true</failOnViolation>\n              <failsOnError>true</failsOnError>\n              <violationSeverity>warning</violationSeverity>\n            </configuration>\n          </plugin>\n          <plugin>\n            <groupId>org.gaul</groupId>\n            <artifactId>modernizer-maven-plugin</artifactId>\n            <configuration>\n              <!-- Fix fiolations before uncommenting\n              <javaVersion>${maven.compile.source}</javaVersion>\n              -->\n              <javaVersion>1.6</javaVersion>\n              <!-- in jclouds-project use the local file. ${project.basedir}\n                required here as 1.1.0 of the modernizer plugin can't find the\n                exclusions file otherwise -->\n              <exclusionsFile>${project.basedir}/../resources/modernizer_exclusions.txt</exclusionsFile>\n            </configuration>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n    <profile>\n      <id>not-jclouds-project</id>\n      <activation>\n        <file>\n          <!-- only in the jclouds-project module -->\n          <missing>src/etc/header.txt</missing>\n        </file>\n      </activation>\n      <build>\n        <plugins>\n          <plugin>\n            <artifactId>maven-checkstyle-plugin</artifactId>\n            <dependencies>\n              <dependency>\n                <groupId>org.apache.jclouds</groupId>\n                <artifactId>jclouds-resources</artifactId>\n                <version>${project.version}</version>\n              </dependency>\n            </dependencies>\n            <configuration>\n              <!-- jclouds-resources has the checkstyle config in the classpath -->\n              <configLocation>resources/checkstyle.xml</configLocation>\n              <suppressionsLocation>resources/checkstyle-suppressions.xml</suppressionsLocation>\n              <suppressionsFileExpression>checkstyle.suppressions.file</suppressionsFileExpression>\n              <includeTestSourceDirectory>true</includeTestSourceDirectory>\n              <failOnViolation>true</failOnViolation>\n              <failsOnError>true</failsOnError>\n              <violationSeverity>warning</violationSeverity>\n            </configuration>\n          </plugin>\n          <plugin>\n            <groupId>org.gaul</groupId>\n            <artifactId>modernizer-maven-plugin</artifactId>\n            <dependencies>\n              <dependency>\n                <groupId>org.apache.jclouds</groupId>\n                <artifactId>jclouds-resources</artifactId>\n                <version>${project.version}</version>\n              </dependency>\n            </dependencies>\n            <configuration>\n              <!-- Fix vioaltions and uncomment again\n              <javaVersion>${maven.compile.source}</javaVersion>\n              -->\n              <javaVersion>1.6</javaVersion>\n              <exclusionsFile>resources/modernizer_exclusions.txt</exclusionsFile>\n            </configuration>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n    <profile>\n      <id>doc</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-javadoc-plugin</artifactId>\n            <version>3.2.0</version>\n            <configuration>\n              <encoding>${project.build.sourceEncoding}</encoding>\n              <doclint>none</doclint>\n              <maxmemory>512m</maxmemory>\n              <quiet>true</quiet>\n            </configuration>\n            <executions>\n              <execution>\n                <id>javadoc</id>\n                <phase>package</phase>\n                <goals>\n                  <goal>jar</goal>\n                </goals>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n    <profile>\n      <id>src</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-source-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>attach-sources</id>\n                <goals>\n                  <goal>jar-no-fork</goal>\n                  <goal>test-jar-no-fork</goal>\n                </goals>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n</project>\n"
  },
  {
    "path": "project/src/etc/header.txt",
    "content": "Licensed to the Apache Software Foundation (ASF) under one or more\ncontributor license agreements.  See the NOTICE file distributed with\nthis work for additional information regarding copyright ownership.\nThe ASF licenses this file to You under the Apache License, Version 2.0\n(the \"License\"); you may not use this file except in compliance with\nthe License.  You may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n"
  },
  {
    "path": "providers/aws-cloudwatch/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.aws.cloudwatch.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "providers/aws-cloudwatch/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.provider</groupId>\n  <artifactId>aws-cloudwatch</artifactId>\n  <name>jclouds Amazon Elastic Load Balancer provider</name>\n  <description>Elastic Load Balancer implementation targeted to Amazon Web Services</description>\n\n  <properties>\n    <test.aws.identity>FIXME_IDENTITY</test.aws.identity>\n    <test.aws.credential>FIXME_CREDENTIAL</test.aws.credential>\n    <test.aws-cloudwatch.endpoint>https://monitoring.us-east-1.amazonaws.com</test.aws-cloudwatch.endpoint>\n    <test.aws-cloudwatch.api-version>2010-08-01</test.aws-cloudwatch.api-version>\n    <test.aws-cloudwatch.build-version />\n    <test.aws-cloudwatch.identity>${test.aws.identity}</test.aws-cloudwatch.identity>\n    <test.aws-cloudwatch.credential>${test.aws.credential}</test.aws-cloudwatch.credential>\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>cloudwatch</artifactId>\n      <version>${project.version}</version>\n      <type>jar</type>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>cloudwatch</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-log4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.aws-cloudwatch.endpoint>${test.aws-cloudwatch.endpoint}</test.aws-cloudwatch.endpoint>\n                    <test.aws-cloudwatch.api-version>${test.aws-cloudwatch.api-version}</test.aws-cloudwatch.api-version>\n                    <test.aws-cloudwatch.build-version>${test.aws-cloudwatch.build-version}</test.aws-cloudwatch.build-version>\n                    <test.aws-cloudwatch.identity>${test.aws-cloudwatch.identity}</test.aws-cloudwatch.identity>\n                    <test.aws-cloudwatch.credential>${test.aws-cloudwatch.credential}</test.aws-cloudwatch.credential>\n                    <test.aws-cloudwatch.compute.provider>${test.aws-cloudwatch.compute.provider}</test.aws-cloudwatch.compute.provider>\n                    <test.aws-cloudwatch.compute.endpoint>${test.aws-cloudwatch.compute.endpoint}</test.aws-cloudwatch.compute.endpoint>\n                    <test.aws-cloudwatch.compute.api-version>${test.aws-cloudwatch.compute.api-version}</test.aws-cloudwatch.compute.api-version>\n                    <test.aws-cloudwatch.compute.identity>${test.aws-cloudwatch.compute.identity}</test.aws-cloudwatch.compute.identity>\n                    <test.aws-cloudwatch.compute.credential>${test.aws-cloudwatch.compute.credential}</test.aws-cloudwatch.compute.credential>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n"
  },
  {
    "path": "providers/aws-cloudwatch/src/main/java/org/jclouds/aws/cloudwatch/AWSCloudWatchProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.cloudwatch;\n\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_REGION;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.aws.domain.Region;\nimport org.jclouds.cloudwatch.CloudWatchApiMetadata;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\n\nimport com.google.auto.service.AutoService;\n\n/**\n * Implementation of @ link org.jclouds.types.ProviderMetadata} for Amazon's CloudWatch\n * provider.\n*\n*/\n@AutoService(ProviderMetadata.class)\npublic class AWSCloudWatchProviderMetadata extends BaseProviderMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromProviderMetadata(this);\n   }\n   \n   public AWSCloudWatchProviderMetadata() {\n      super(builder());\n   }\n\n   public AWSCloudWatchProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = new Properties();\n      properties.putAll(Region.regionProperties());\n      properties.setProperty(PROPERTY_REGION + \".\" + Region.US_EAST_1 + \".endpoint\",\n            \"https://monitoring.us-east-1.amazonaws.com\");\n      properties.setProperty(PROPERTY_REGION + \".\" + Region.US_WEST_1 + \".endpoint\",\n            \"https://monitoring.us-west-1.amazonaws.com\");\n      properties.setProperty(PROPERTY_REGION + \".\" + Region.US_WEST_2 + \".endpoint\",\n            \"https://monitoring.us-west-2.amazonaws.com\");\n      properties.setProperty(PROPERTY_REGION + \".\" + Region.SA_EAST_1 + \".endpoint\",\n            \"https://monitoring.sa-east-1.amazonaws.com\");\n      properties.setProperty(PROPERTY_REGION + \".\" + Region.EU_WEST_1 + \".endpoint\",\n            \"https://monitoring.eu-west-1.amazonaws.com\");\n      properties.setProperty(PROPERTY_REGION + \".\" + Region.AP_SOUTHEAST_1 + \".endpoint\",\n            \"https://monitoring.ap-southeast-1.amazonaws.com\");\n      properties.setProperty(PROPERTY_REGION + \".\" + Region.AP_SOUTHEAST_2 + \".endpoint\",\n            \"https://monitoring.ap-southeast-2.amazonaws.com\");\n      properties.setProperty(PROPERTY_REGION + \".\" + Region.AP_NORTHEAST_1 + \".endpoint\",\n            \"https://monitoring.ap-northeast-1.amazonaws.com\");\n      return properties;\n   }\n   \n   public static class Builder extends BaseProviderMetadata.Builder {\n\n      protected Builder() {\n         id(\"aws-cloudwatch\")\n         .name(\"Amazon CloudWatch\")\n         .endpoint(\"https://monitoring.us-east-1.amazonaws.com\")\n         .homepage(URI.create(\"http://aws.amazon.com/cloudwatch\"))\n         .console(URI.create(\"https://console.aws.amazon.com/cloudwatch/home\"))\n         .linkedServices(\"aws-ec2\", \"aws-elb\", \"aws-cloudwatch\", \"aws-s3\", \"aws-simpledb\")\n         .iso3166Codes(\"US-VA\", \"US-CA\", \"BR-SP\", \"US-OR\", \"IE\", \"SG\", \"AU-NSW\", \"JP-13\")\n               .apiMetadata(\n                     new CloudWatchApiMetadata().toBuilder()\n                           .version(\"2010-08-01\").build())\n         .defaultProperties(AWSCloudWatchProviderMetadata.defaultProperties());\n      }\n\n      @Override\n      public AWSCloudWatchProviderMetadata build() {\n         return new AWSCloudWatchProviderMetadata(this);\n      }\n      \n      @Override\n      public Builder fromProviderMetadata(ProviderMetadata in) {\n         super.fromProviderMetadata(in);\n         return this;\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/aws-cloudwatch/src/test/java/org/jclouds/aws/cloudwatch/AWSCloudWatchProviderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.cloudwatch;\n\nimport org.jclouds.cloudwatch.CloudWatchApiMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.testng.annotations.Test;\n\n/**\n * The AWSCloudWatchProviderTest tests the org.jclouds.providers.AWSCloudWatchProvider class.\n */\n@Test(groups = \"unit\", testName = \"AWSCloudWatchProviderTest\")\npublic class AWSCloudWatchProviderTest extends BaseProviderMetadataTest {\n\n   public AWSCloudWatchProviderTest() {\n      super(new AWSCloudWatchProviderMetadata(), new CloudWatchApiMetadata());\n   }\n}\n"
  },
  {
    "path": "providers/aws-cloudwatch/src/test/java/org/jclouds/aws/cloudwatch/features/AWSMetricApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.cloudwatch.features;\n\nimport org.jclouds.cloudwatch.features.MetricApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"AWSMetricApiLiveTest\")\npublic class AWSMetricApiLiveTest extends MetricApiLiveTest {\n   public AWSMetricApiLiveTest() {\n      provider = \"aws-cloudwatch\";\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/README.txt",
    "content": "#\n# The jclouds provider for Amazon's EC2 (http://aws.amazon.com/ec2/).\n#\n# Expects the jclouds ec2 API to be present on your application's classpath.\n#\n# TODO: Implementation status.\n# TODO: Supported features.\n# TODO: Usage example.\n"
  },
  {
    "path": "providers/aws-ec2/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.aws.ec2.*;version=\"${project.version}\";-noimport:=true"
  },
  {
    "path": "providers/aws-ec2/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.provider</groupId>\n  <artifactId>aws-ec2</artifactId>\n  <name>jclouds Amazon EC2 provider</name>\n  <description>EC2 implementation targeted to Amazon Web Services</description>\n\n  <properties>\n    <test.aws.identity>FIXME_IDENTITY</test.aws.identity>\n    <test.aws.credential>FIXME_CREDENTIAL</test.aws.credential>\n    <test.aws-ec2.endpoint>https://ec2.us-east-1.amazonaws.com</test.aws-ec2.endpoint>\n    <test.aws-ec2.api-version>2012-06-01</test.aws-ec2.api-version>\n    <test.aws-ec2.build-version />\n    <test.aws-ec2.identity>${test.aws.identity}</test.aws-ec2.identity>\n    <test.aws-ec2.credential>${test.aws.credential}</test.aws-ec2.credential>\n\n    <test.aws-ec2.template />\n    <!-- Active EBS template as of 9/25/2013 -->\n    <test.aws-ec2.ebs-template>hardwareId=m1.small,imageId=us-east-1/ami-53b1ff3a</test.aws-ec2.ebs-template>\n    <!-- Windows_Server-2008-R2 with WinRM enabled (setup instructions at http://www.frontiertown.co.uk/2011/12/overthere-control-windows-from-java/) -->\n    <test.aws-ec2.windows-template>hardwareId=m1.small,imageId=us-east-1/ami-0cb76d65</test.aws-ec2.windows-template>\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>ec2</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.value</groupId>\n      <artifactId>auto-value</artifactId>\n      <scope>provided</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>ec2</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.provider</groupId>\n      <artifactId>aws-cloudwatch</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-log4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-sshj</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.squareup.okhttp3</groupId>\n      <artifactId>mockwebserver</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.aws-ec2.endpoint>${test.aws-ec2.endpoint}</test.aws-ec2.endpoint>\n                    <test.aws-ec2.api-version>${test.aws-ec2.api-version}</test.aws-ec2.api-version>\n                    <test.aws-ec2.build-version>${test.aws-ec2.build-version}</test.aws-ec2.build-version>\n                    <test.aws-ec2.identity>${test.aws-ec2.identity}</test.aws-ec2.identity>\n                    <test.aws-ec2.credential>${test.aws-ec2.credential}</test.aws-ec2.credential>\n                    <test.aws-ec2.template>${test.aws-ec2.template}</test.aws-ec2.template>\n                    <test.aws-ec2.ebs-template>${test.aws-ec2.ebs-template}</test.aws-ec2.ebs-template>\n                    <test.aws-ec2.windows-template>${test.aws-ec2.windows-template}</test.aws-ec2.windows-template>\n                    <test.aws-ec2.windows-owner>${test.aws-ec2.windows-owner}</test.aws-ec2.windows-owner>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n\n</project>\n\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/AWSEC2Api.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2;\n\nimport org.jclouds.aws.ec2.features.AWSAMIApi;\nimport org.jclouds.aws.ec2.features.AWSInstanceApi;\nimport org.jclouds.aws.ec2.features.AWSKeyPairApi;\nimport org.jclouds.aws.ec2.features.AWSSecurityGroupApi;\nimport org.jclouds.aws.ec2.features.AWSSubnetApi;\nimport org.jclouds.aws.ec2.features.InternetGatewayApi;\nimport org.jclouds.aws.ec2.features.MonitoringApi;\nimport org.jclouds.aws.ec2.features.PlacementGroupApi;\nimport org.jclouds.aws.ec2.features.RouteTableApi;\nimport org.jclouds.aws.ec2.features.SpotInstanceApi;\nimport org.jclouds.aws.ec2.features.VPCApi;\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.location.functions.RegionToEndpointOrProviderIfNull;\nimport org.jclouds.rest.annotations.Delegate;\nimport org.jclouds.rest.annotations.EndpointParam;\n\nimport com.google.common.base.Optional;\n\n/**\n * Provides synchronous access to EC2 services.\n */\npublic interface AWSEC2Api extends EC2Api {\n\n   /**\n    * {@inheritDoc}\n    */\n   @Delegate\n   @Override\n   Optional<? extends AWSInstanceApi> getInstanceApi();\n\n   @Delegate\n   @Override\n   Optional<? extends AWSInstanceApi> getInstanceApiForRegion(\n           @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region);\n\n   /**\n    * {@inheritDoc}\n    */\n   @Delegate\n   @Override\n   Optional<? extends AWSSecurityGroupApi> getSecurityGroupApi();\n\n   @Delegate\n   @Override\n   Optional<? extends AWSSecurityGroupApi> getSecurityGroupApiForRegion(\n           @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region);\n\n   /**\n    * {@inheritDoc}\n    */\n   @Delegate\n   @Override\n   Optional<? extends AWSAMIApi> getAMIApi();\n\n   @Delegate\n   @Override\n   Optional<? extends AWSAMIApi> getAMIApiForRegion(\n           @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region);\n\n\n   /**\n    * Provides synchronous access to PlacementGroup services.\n    */\n   @Delegate\n   Optional<? extends PlacementGroupApi> getPlacementGroupApi();\n\n   @Delegate\n   Optional<? extends PlacementGroupApi> getPlacementGroupApiForRegion(\n           @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region);\n\n   /**\n    * Provides synchronous access to Monitoring services.\n    */\n   @Delegate\n   Optional<? extends MonitoringApi> getMonitoringApi();\n\n   @Delegate\n   Optional<? extends MonitoringApi> getMonitoringApiForRegion(\n           @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region);\n\n   /**\n    * {@inheritDoc}\n    */\n   @Delegate\n   @Override\n   Optional<? extends AWSKeyPairApi> getKeyPairApi();\n\n   @Delegate\n   @Override\n   Optional<? extends AWSKeyPairApi> getKeyPairApiForRegion(\n           @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region);\n\n   /**\n    * Provides synchronous access to SpotInstance services.\n    */\n   @Delegate\n   Optional<? extends SpotInstanceApi> getSpotInstanceApi();\n\n   @Delegate\n   Optional<? extends SpotInstanceApi> getSpotInstanceApiForRegion(\n           @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region);\n\n   /**\n    * Provides synchronous access to VPC services.\n    */\n   @Delegate\n   Optional<? extends VPCApi> getVPCApi();\n\n   /**\n    * Provides access to Subnet services.\n    */\n   @Delegate\n   Optional<? extends AWSSubnetApi> getAWSSubnetApi();\n\n   @Delegate\n   Optional<? extends AWSSubnetApi> getAWSSubnetApiForRegion(\n           @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region);\n\n\n   /**\n    * Provides synchronous access to InternetGateway services.\n    */\n   @Delegate\n   Optional<? extends InternetGatewayApi> getInternetGatewayApi();\n\n   /**\n    * Provides synchronous access to Internet Gateway services in a given region.\n    */\n   @Delegate\n   Optional<? extends InternetGatewayApi> getInternetGatewayApiForRegion(\n      @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region\n   );\n\n   /**\n    * Provides synchronous access to Route Table services.\n    */\n   @Delegate\n   Optional<? extends RouteTableApi> getRouteTableApi();\n\n   /**\n    * Provides synchronous access to Route Table services in a given region.\n    */\n   @Delegate\n   Optional<? extends RouteTableApi> getRouteTableApiForRegion(\n      @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region\n   );\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/AWSEC2ApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2;\n\nimport static org.jclouds.ec2.reference.EC2Constants.PROPERTY_EC2_AMI_OWNERS;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.Constants;\nimport org.jclouds.aws.ec2.compute.AWSEC2ComputeServiceContext;\nimport org.jclouds.aws.ec2.compute.config.AWSEC2ComputeServiceContextModule;\nimport org.jclouds.aws.ec2.config.AWSEC2HttpApiModule;\nimport org.jclouds.ec2.EC2ApiMetadata;\nimport org.jclouds.ec2.compute.config.EC2ResolveImagesModule;\nimport org.jclouds.rest.internal.BaseHttpApiMetadata;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\npublic final class AWSEC2ApiMetadata extends BaseHttpApiMetadata<AWSEC2Api> {\n\n   @Override\n   public Builder toBuilder() {\n      return new Builder().fromApiMetadata(this);\n   }\n\n   public AWSEC2ApiMetadata() {\n      super(new Builder());\n   }\n\n   protected AWSEC2ApiMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = EC2ApiMetadata.defaultProperties();\n      properties.remove(PROPERTY_EC2_AMI_OWNERS);\n      // auth fail sometimes happens in EC2, as the rc.local script that injects the\n      // authorized key executes after ssh has started.  \n      properties.setProperty(\"jclouds.ssh.max-retries\", \"7\");\n      properties.setProperty(\"jclouds.ssh.retry-auth\", \"true\");\n      // required for custom retry handler \n      properties.setProperty(Constants.PROPERTY_IDEMPOTENT_METHODS, \"DELETE,GET,HEAD,OPTIONS,PUT,POST\");\n      return properties;\n   }\n\n   public static final class Builder extends BaseHttpApiMetadata.Builder<AWSEC2Api, Builder> {\n      public Builder() {\n         id(\"aws-ec2\")\n         .version(\"2012-06-01\")\n         .name(\"Amazon-specific EC2 API\")\n         .identityName(\"Access Key ID\")\n         .credentialName(\"Secret Access Key\")\n         .defaultEndpoint(\"https://ec2.us-east-1.amazonaws.com\")\n         .documentation(URI.create(\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference\"))\n         .defaultProperties(AWSEC2ApiMetadata.defaultProperties())\n         .view(AWSEC2ComputeServiceContext.class)\n         .defaultModules(ImmutableSet.<Class<? extends Module>>of(AWSEC2HttpApiModule.class, EC2ResolveImagesModule.class, AWSEC2ComputeServiceContextModule.class));\n      }\n\n      @Override\n      public AWSEC2ApiMetadata build() {\n         return new AWSEC2ApiMetadata(this);\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/AWSEC2ProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2;\n\nimport static org.jclouds.aws.ec2.reference.AWSEC2Constants.PROPERTY_EC2_AMI_QUERY;\nimport static org.jclouds.aws.ec2.reference.AWSEC2Constants.PROPERTY_EC2_CC_AMI_QUERY;\nimport static org.jclouds.aws.ec2.reference.AWSEC2Constants.PROPERTY_EC2_CC_REGIONS;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TEMPLATE;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_SUSPENDED;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.aws.domain.Region;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\n\nimport com.google.auto.service.AutoService;\n\n/**\n * Implementation of {@ link org.jclouds.types.ProviderMetadata} for Amazon's\n * Elastic Compute Cloud (EC2) provider.\n */\n@AutoService(ProviderMetadata.class)\npublic class AWSEC2ProviderMetadata extends BaseProviderMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromProviderMetadata(this);\n   }\n   \n   public AWSEC2ProviderMetadata() {\n      super(builder());\n   }\n\n   public AWSEC2ProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = new Properties();\n      // sometimes, like in ec2, stop takes a very long time, perhaps\n      // due to volume management. one example spent 2 minutes moving\n      // from stopping->stopped state on an ec2 micro\n      properties.setProperty(TIMEOUT_NODE_SUSPENDED, 120 * 1000 + \"\");\n      properties.putAll(Region.regionProperties());\n      // Amazon Linux, Amazon Windows, alestic, canonical, and rightscale\n      properties.setProperty(PROPERTY_EC2_AMI_QUERY,\n               \"owner-id=137112412989,801119661308,063491364108,099720109477,411009282317;state=available;image-type=machine\");\n      // amis that work with the cluster instances\n      properties.setProperty(PROPERTY_EC2_CC_REGIONS, Region.US_EAST_1 + \",\" + Region.US_WEST_2 + \",\" + Region.EU_WEST_1);\n      properties\n               .setProperty(\n                        PROPERTY_EC2_CC_AMI_QUERY,\n                        \"virtualization-type=hvm;architecture=x86_64;owner-id=137112412989,099720109477;hypervisor=xen;state=available;image-type=machine;root-device-type=ebs\");\n      properties.setProperty(TEMPLATE, \"osFamily=AMZN_LINUX,os64Bit=true\");\n      return properties;\n   }\n   \n   public static class Builder extends BaseProviderMetadata.Builder {\n\n      protected Builder() {\n         id(\"aws-ec2\")\n         .name(\"Amazon Elastic Compute Cloud (EC2)\")\n         .apiMetadata(new AWSEC2ApiMetadata())\n         .endpoint(\"https://ec2.us-east-1.amazonaws.com\")\n         .homepage(URI.create(\"http://aws.amazon.com/ec2\"))\n         .console(URI.create(\"https://console.aws.amazon.com/ec2/home\"))\n         .defaultProperties(AWSEC2ProviderMetadata.defaultProperties())\n         .linkedServices(\"aws-ec2\", \"aws-elb\", \"aws-cloudwatch\", \"aws-s3\", \"aws-simpledb\")\n               .iso3166Codes(\"US-VA\", \"US-OH\", \"US-CA\", \"US-OR\", \"CA\", \"BR-SP\", \"IE\", \"GB-LND\", \"FR-IDF\", \"DE-HE\",\n                     \"SG\", \"AU-NSW\", \"IN-MH\", \"JP-13\", \"KR-11\", \"CN-BJ\", \"CN-NX\", \"BH\");\n      }\n\n      @Override\n      public AWSEC2ProviderMetadata build() {\n         return new AWSEC2ProviderMetadata(this);\n      }\n\n      @Override\n      public Builder fromProviderMetadata(\n            ProviderMetadata in) {\n         super.fromProviderMetadata(in);\n         return this;\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/binders/BindInternetGatewayIdsToIndexedFormParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.binders;\n\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\n/**\n * Binds the String [] to form parameters named with InternetGatewayId.index\n */\npublic class BindInternetGatewayIdsToIndexedFormParams implements Binder {\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      return AWSUtils.indexStringArrayToFormValuesWithPrefix(request, \"InternetGatewayId\", input);\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/binders/BindLaunchSpecificationToFormParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\nimport java.util.Map.Entry;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.ec2.domain.LaunchSpecification;\nimport org.jclouds.aws.ec2.domain.LaunchSpecification.IAMInstanceProfileRequest;\nimport org.jclouds.aws.ec2.options.AWSRunInstancesOptions;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMap.Builder;\nimport com.google.common.collect.Multimaps;\n\n@Singleton\npublic class BindLaunchSpecificationToFormParams implements Binder, Function<LaunchSpecification, Map<String, String>> {\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkArgument(input instanceof LaunchSpecification, \"this binder is only valid for LaunchSpecifications!\");\n      LaunchSpecification launchSpec = LaunchSpecification.class.cast(input);\n      return (R) request.toBuilder().replaceFormParams(Multimaps.forMap(apply(launchSpec))).build();\n   }\n\n   @Override\n   public Map<String, String> apply(LaunchSpecification launchSpec) {\n      Builder<String, String> builder = ImmutableMap.builder();\n      builder.put(\"LaunchSpecification.ImageId\", checkNotNull(launchSpec.getImageId(), \"imageId\"));\n      if (launchSpec.getAvailabilityZone() != null)\n         builder.put(\"LaunchSpecification.Placement.AvailabilityZone\", launchSpec.getAvailabilityZone());\n\n      AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n      if (!launchSpec.getBlockDeviceMappings().isEmpty())\n         options.withBlockDeviceMappings(launchSpec.getBlockDeviceMappings());\n      if (!launchSpec.getSecurityGroupNames().isEmpty())\n         options.withSecurityGroups(launchSpec.getSecurityGroupNames());\n      if (!launchSpec.getSecurityGroupIds().isEmpty())\n         options.withSecurityGroupIds(launchSpec.getSecurityGroupIds());\n      options.asType(checkNotNull(launchSpec.getInstanceType(), \"instanceType\"));\n      if (launchSpec.getSubnetId() != null)\n         options.withSubnetId(launchSpec.getSubnetId());\n      if (launchSpec.getKernelId() != null)\n         options.withKernelId(launchSpec.getKernelId());\n      if (launchSpec.getKeyName() != null)\n         options.withKeyName(launchSpec.getKeyName());\n      if (launchSpec.getRamdiskId() != null)\n         options.withRamdisk(launchSpec.getRamdiskId());\n      if (Boolean.TRUE.equals(launchSpec.isMonitoringEnabled()))\n         options.enableMonitoring();\n      if (launchSpec.getUserData() != null)\n         options.withUserData(launchSpec.getUserData());\n      if (launchSpec.getIAMInstanceProfile().isPresent()) {\n         IAMInstanceProfileRequest profile = launchSpec.getIAMInstanceProfile().get();\n         if (profile.getArn().isPresent())\n            options.withIAMInstanceProfileArn(profile.getArn().get());\n         if (profile.getName().isPresent())\n            options.withIAMInstanceProfileName(profile.getName().get());\n      }\n      for (Entry<String, String> entry : options.buildFormParameters().entries()) {\n         builder.put(\"LaunchSpecification.\" + entry.getKey(), entry.getValue());\n      }\n      return builder.build();\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/binders/BindRouteTableIdsToIndexedFormParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.binders;\n\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\n/**\n * Binds the String [] to form parameters named with RouteTableId.index\n */\npublic class BindRouteTableIdsToIndexedFormParams implements Binder {\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      return AWSUtils.indexStringArrayToFormValuesWithPrefix(request, \"RouteTableId\", input);\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/binders/BindSpotInstanceRequestIdsToIndexedFormParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.binders;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\n/**\n * Binds the String [] to form parameters named with SpotInstanceRequestId.index\n */\n@Singleton\npublic class BindSpotInstanceRequestIdsToIndexedFormParams implements Binder {\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      return AWSUtils.indexStringArrayToFormValuesWithPrefix(request, \"SpotInstanceRequestId\", input);\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/binders/BindTagFiltersToIndexedFormParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\n\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\npublic class BindTagFiltersToIndexedFormParams implements Binder {\n    @Override\n    public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n        checkArgument(checkNotNull(input, \"input\") instanceof Map<?, ?>, \"this binder is only valid for Map<?, Iterable<?>>\");\n        return AWSUtils.indexMapOfIterableToFormValuesWithPrefix(request, \"Filter\", \"Name\", \"Value\", input);\n    }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/binders/BindTagsToIndexedFormParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\n\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\npublic class BindTagsToIndexedFormParams implements Binder {\n    @Override\n    public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n        checkArgument(checkNotNull(input, \"input\") instanceof Map, \"This binder is only valid for Map<String,String>\");\n        return AWSUtils.indexMapToFormValuesWithPrefix(request, \"Tag\", \"Key\", \"Value\", input);\n    }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/binders/BindVpcIdsToIndexedFormParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.binders;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\n/**\n * Binds the String [] to form parameters named with InstanceId.index\n */\n@Singleton\npublic class BindVpcIdsToIndexedFormParams implements Binder {\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      return AWSUtils.indexStringArrayToFormValuesWithPrefix(request, \"VpcId\", input);\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/compute/AWSEC2ComputeService.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.compute;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.common.base.Strings.emptyToNull;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_RUNNING;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_SUSPENDED;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_TERMINATED;\nimport static org.jclouds.ec2.reference.EC2Constants.PROPERTY_EC2_GENERATE_INSTANCE_NAMES;\n\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentMap;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Provider;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Constants;\nimport org.jclouds.aws.ec2.AWSEC2Api;\nimport org.jclouds.aws.ec2.domain.PlacementGroup;\nimport org.jclouds.aws.ec2.domain.PlacementGroup.State;\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.compute.callables.RunScriptOnNode;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.TemplateBuilder;\nimport org.jclouds.compute.extensions.ImageExtension;\nimport org.jclouds.compute.extensions.SecurityGroupExtension;\nimport org.jclouds.compute.extensions.internal.DelegatingImageExtension;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.compute.internal.PersistNodeCredentials;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.compute.reference.ComputeServiceConstants.Timeouts;\nimport org.jclouds.compute.strategy.CreateNodesInGroupThenAddToSet;\nimport org.jclouds.compute.strategy.DestroyNodeStrategy;\nimport org.jclouds.compute.strategy.GetImageStrategy;\nimport org.jclouds.compute.strategy.GetNodeMetadataStrategy;\nimport org.jclouds.compute.strategy.InitializeRunScriptOnNodeOrPlaceInBadMap;\nimport org.jclouds.compute.strategy.ListNodesStrategy;\nimport org.jclouds.compute.strategy.RebootNodeStrategy;\nimport org.jclouds.compute.strategy.ResumeNodeStrategy;\nimport org.jclouds.compute.strategy.SuspendNodeStrategy;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.domain.Location;\nimport org.jclouds.ec2.compute.EC2ComputeService;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.domain.KeyPair;\nimport org.jclouds.scriptbuilder.functions.InitAdminAccess;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.util.concurrent.ListeningExecutorService;\n\n@Singleton\npublic class AWSEC2ComputeService extends EC2ComputeService {\n\n   private final LoadingCache<RegionAndName, String> placementGroupMap;\n   private final Predicate<PlacementGroup> placementGroupDeleted;\n   private final AWSEC2Api client;\n\n   @Inject\n   protected AWSEC2ComputeService(ComputeServiceContext context, Map<String, Credentials> credentialStore,\n         @Memoized Supplier<Set<? extends Image>> images, @Memoized Supplier<Set<? extends Hardware>> sizes,\n         @Memoized Supplier<Set<? extends Location>> locations, ListNodesStrategy listNodesStrategy,\n         GetImageStrategy getImageStrategy, GetNodeMetadataStrategy getNodeMetadataStrategy,\n         CreateNodesInGroupThenAddToSet runNodesAndAddToSetStrategy, RebootNodeStrategy rebootNodeStrategy,\n         DestroyNodeStrategy destroyNodeStrategy, ResumeNodeStrategy startNodeStrategy,\n         SuspendNodeStrategy stopNodeStrategy, Provider<TemplateBuilder> templateBuilderProvider,\n         @Named(\"DEFAULT\") Provider<TemplateOptions> templateOptionsProvider,\n         @Named(TIMEOUT_NODE_RUNNING) Predicate<AtomicReference<NodeMetadata>> nodeRunning,\n         @Named(TIMEOUT_NODE_TERMINATED) Predicate<AtomicReference<NodeMetadata>> nodeTerminated,\n         @Named(TIMEOUT_NODE_SUSPENDED) Predicate<AtomicReference<NodeMetadata>> nodeSuspended,\n         InitializeRunScriptOnNodeOrPlaceInBadMap.Factory initScriptRunnerFactory,\n         RunScriptOnNode.Factory runScriptOnNodeFactory, InitAdminAccess initAdminAccess,\n         PersistNodeCredentials persistNodeCredentials, Timeouts timeouts,\n         @Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor, AWSEC2Api client,\n         ConcurrentMap<RegionAndName, KeyPair> credentialsMap,\n         @Named(\"SECURITY\") LoadingCache<RegionAndName, String> securityGroupMap,\n         @Named(\"PLACEMENT\") LoadingCache<RegionAndName, String> placementGroupMap,\n         @Named(\"DELETED\") Predicate<PlacementGroup> placementGroupDeleted, Optional<ImageExtension> imageExtension,\n         GroupNamingConvention.Factory namingConvention,\n         @Named(PROPERTY_EC2_GENERATE_INSTANCE_NAMES) boolean generateInstanceNames,\n         Optional<SecurityGroupExtension> securityGroupExtension,\n         DelegatingImageExtension.Factory delegatingImageExtension) {\n      super(context, credentialStore, images, sizes, locations, listNodesStrategy, getImageStrategy,\n            getNodeMetadataStrategy, runNodesAndAddToSetStrategy, rebootNodeStrategy, destroyNodeStrategy,\n            startNodeStrategy, stopNodeStrategy, templateBuilderProvider, templateOptionsProvider, nodeRunning,\n            nodeTerminated, nodeSuspended, initScriptRunnerFactory, runScriptOnNodeFactory, initAdminAccess,\n            persistNodeCredentials, timeouts, userExecutor, client, credentialsMap, securityGroupMap, imageExtension,\n            namingConvention, generateInstanceNames, securityGroupExtension, delegatingImageExtension);\n      this.client = client;\n      this.placementGroupMap = placementGroupMap;\n      this.placementGroupDeleted = placementGroupDeleted;\n   }\n\n   @VisibleForTesting\n   void deletePlacementGroup(String region, String group) {\n      checkNotNull(emptyToNull(group), \"group must be defined\");\n      // placementGroupName must be unique within an account per\n      // http://docs.amazonwebservices.com/AWSEC2/latest/UserGuide/index.html?using_cluster_computing.html\n      String placementGroup = String.format(\"jclouds#%s#%s\", group, region);\n      try {\n         if (!client.getPlacementGroupApi().get().describePlacementGroupsInRegion(region, placementGroup).isEmpty()) {\n            logger.debug(\">> deleting placementGroup(%s)\", placementGroup);\n            try {\n               client.getPlacementGroupApi().get().deletePlacementGroupInRegion(region, placementGroup);\n               checkState(placementGroupDeleted.apply(new PlacementGroup(region, placementGroup, \"cluster\",\n                        State.PENDING)), \"placementGroup region(%s) name(%s) failed to delete\", region,\n                        placementGroup);\n               placementGroupMap.invalidate(new RegionAndName(region, placementGroup));\n               logger.debug(\"<< deleted placementGroup(%s)\", placementGroup);\n            } catch (IllegalStateException e) {\n               logger.debug(\"<< inUse placementGroup(%s)\", placementGroup);\n            }\n         }\n      } catch (UnsupportedOperationException e) {\n         logger.trace(\"<< placementGroups unsupported in region %s\", region);\n      }\n   }\n\n   @Override\n   protected void cleanUpIncidentalResources(String region, String group) {\n      super.cleanUpIncidentalResources(region, group);\n      deletePlacementGroup(region, group);\n   }\n\n   /**\n    * returns template options, except of type {@link AWSEC2TemplateOptions}.\n    */\n   @Override\n   public AWSEC2TemplateOptions templateOptions() {\n      return AWSEC2TemplateOptions.class.cast(super.templateOptions());\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/compute/AWSEC2ComputeServiceContext.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.compute;\n\nimport org.jclouds.aws.ec2.compute.internal.AWSEC2ComputeServiceContextImpl;\nimport org.jclouds.ec2.compute.EC2ComputeServiceContext;\n\nimport com.google.inject.ImplementedBy;\n\n@ImplementedBy(AWSEC2ComputeServiceContextImpl.class)\npublic interface AWSEC2ComputeServiceContext extends EC2ComputeServiceContext {\n   @Override\n   AWSEC2ComputeService getComputeService();\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/compute/AWSEC2TemplateBuilderImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.compute;\n\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Provider;\n\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.TemplateBuilder;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.domain.Location;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.compute.internal.EC2TemplateBuilderImpl;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.LoadingCache;\n\npublic class AWSEC2TemplateBuilderImpl extends EC2TemplateBuilderImpl {\n\n   @Inject\n   protected AWSEC2TemplateBuilderImpl(@Memoized Supplier<Set<? extends Location>> locations,\n         @Memoized Supplier<Set<? extends Image>> images, @Memoized Supplier<Set<? extends Hardware>> sizes,\n         Supplier<Location> defaultLocation, @Named(\"DEFAULT\") Provider<TemplateOptions> optionsProvider,\n         @Named(\"DEFAULT\") Provider<TemplateBuilder> defaultTemplateProvider,\n         Supplier<LoadingCache<RegionAndName, ? extends Image>> imageMap) {\n      super(locations, images, sizes, defaultLocation, optionsProvider, defaultTemplateProvider, imageMap);\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/compute/AWSEC2TemplateOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.compute;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.common.base.Strings.emptyToNull;\n\nimport java.util.Calendar;\nimport java.util.Date;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.aws.ec2.options.RequestSpotInstancesOptions;\nimport org.jclouds.aws.ec2.options.Tenancy;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.ec2.compute.options.EC2TemplateOptions;\nimport org.jclouds.ec2.domain.BlockDeviceMapping;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.rest.annotations.SinceApiVersion;\nimport org.jclouds.scriptbuilder.domain.Statement;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\n\n/**\n * Contains options supported in the {@code ComputeService#runNode} operation on\n * the \"ec2\" provider. <h2>\n * Usage</h2> The recommended way to instantiate a AWSEC2TemplateOptions object\n * is to statically import AWSEC2TemplateOptions.* and invoke a static creation\n * method followed by an instance mutator (if needed):\n * <p/>\n * <code>\n * import static org.jclouds.aws.ec2.compute.options.AWSEC2TemplateOptions.Builder.*;\n * <p/>\n * ComputeService client = // get connection\n * templateBuilder.options(inboundPorts(22, 80, 8080, 443));\n * Set<? extends NodeMetadata> set = client.createNodesInGroup(tag, 2, templateBuilder.build());\n * <code>\n */\npublic class AWSEC2TemplateOptions extends EC2TemplateOptions implements Cloneable {\n   @Override\n   public AWSEC2TemplateOptions clone() {\n      AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n      copyTo(options);\n      return options;\n   }\n\n   @Override\n   public void copyTo(TemplateOptions to) {\n      super.copyTo(to);\n      if (to instanceof AWSEC2TemplateOptions) {\n         AWSEC2TemplateOptions eTo = AWSEC2TemplateOptions.class.cast(to);\n         if (getSubnetId() != null)\n            eTo.subnetId(getSubnetId());\n         if (getIAMInstanceProfileArn() != null)\n            eTo.iamInstanceProfileArn(getIAMInstanceProfileArn());\n         if (getIAMInstanceProfileName() != null)\n            eTo.iamInstanceProfileName(getIAMInstanceProfileName());\n         if (isMonitoringEnabled())\n            eTo.enableMonitoring();\n         if (!shouldAutomaticallyCreatePlacementGroup())\n            eTo.noPlacementGroup();\n         if (getPlacementGroup() != null)\n            eTo.placementGroup(getPlacementGroup());\n         if (!getGroupIds().isEmpty())\n            eTo.securityGroupIds(getGroupIds());\n         if (getSpotPrice() != null)\n            eTo.spotPrice(getSpotPrice());\n         if (getSpotOptions() != null)\n            eTo.spotOptions(getSpotOptions());\n         if (getPrivateIpAddress() != null)\n            eTo.privateIpAddress(getPrivateIpAddress());\n         if (getTenancy() != null)\n            eTo.tenancy(getTenancy());\n         if (getDedicatedHostId() != null)\n            eTo.dedicatedHostId(getDedicatedHostId());\n      }\n   }\n\n   private boolean monitoringEnabled;\n   private String placementGroup = null;\n   private boolean noPlacementGroup;\n   private String subnetId;\n   private Float spotPrice;\n   private RequestSpotInstancesOptions spotOptions = RequestSpotInstancesOptions.NONE;\n   private Set<String> groupIds = ImmutableSet.of();\n   private String iamInstanceProfileArn;\n   private String iamInstanceProfileName;\n   private String privateIpAddress;\n   private Tenancy tenancy;\n   private String dedicatedHostId;\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o)\n         return true;\n      if (o == null || getClass() != o.getClass())\n         return false;\n      AWSEC2TemplateOptions that = AWSEC2TemplateOptions.class.cast(o);\n      return super.equals(that) && equal(this.monitoringEnabled, that.monitoringEnabled)\n               && equal(this.placementGroup, that.placementGroup)\n               && equal(this.noPlacementGroup, that.noPlacementGroup) && equal(this.subnetId, that.subnetId)\n               && equal(this.spotPrice, that.spotPrice) && equal(this.spotOptions, that.spotOptions)\n               && equal(this.groupIds, that.groupIds) && equal(this.iamInstanceProfileArn, that.iamInstanceProfileArn)\n               && equal(this.iamInstanceProfileName, that.iamInstanceProfileName)\n               && equal(this.privateIpAddress, that.privateIpAddress)\n               && equal(this.tenancy, that.tenancy) && equal(this.dedicatedHostId, that.dedicatedHostId);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(super.hashCode(), monitoringEnabled, placementGroup, noPlacementGroup, subnetId,\n               spotPrice, spotOptions, groupIds, iamInstanceProfileArn, iamInstanceProfileName, privateIpAddress,\n               tenancy, dedicatedHostId);\n   }\n\n   @Override\n   public ToStringHelper string() {\n      ToStringHelper toString = super.string();\n      if (monitoringEnabled)\n         toString.add(\"monitoringEnabled\", monitoringEnabled);\n      toString.add(\"placementGroup\", placementGroup);\n      if (noPlacementGroup)\n         toString.add(\"noPlacementGroup\", noPlacementGroup);\n      toString.add(\"subnetId\", subnetId);\n      toString.add(\"spotPrice\", spotPrice);\n      if (spotOptions != RequestSpotInstancesOptions.NONE)\n         toString.add(\"spotOptions\", spotOptions);\n      if (!groupIds.isEmpty())\n         toString.add(\"groupIds\", groupIds);\n      toString.add(\"iamInstanceProfileArn\", iamInstanceProfileArn);\n      toString.add(\"iamInstanceProfileName\", iamInstanceProfileName);\n      toString.add(\"privateIpAddress\", privateIpAddress);\n      toString.add(\"tenancy\", tenancy);\n      toString.add(\"dedicatedHostId\", dedicatedHostId);\n      return toString;\n   }\n\n   public static final AWSEC2TemplateOptions NONE = new AWSEC2TemplateOptions();\n\n   /**\n    * Enable Cloudwatch monitoring\n    *\n    * @see CloudWatchClient\n    */\n   public AWSEC2TemplateOptions enableMonitoring() {\n      this.monitoringEnabled = true;\n      return this;\n   }\n\n   /**\n    * Specifies the keypair used to run instances with\n    */\n   public AWSEC2TemplateOptions placementGroup(String placementGroup) {\n      checkNotNull(emptyToNull(placementGroup), \"use noPlacementGroup option instead of passing null\");\n      checkState(!noPlacementGroup, \"you cannot specify both options placementGroup and noPlacementGroup\");\n      this.placementGroup = placementGroup;\n      return this;\n   }\n\n   /**\n    * Do not use a keypair on instances\n    */\n   public AWSEC2TemplateOptions noPlacementGroup() {\n      checkState(placementGroup == null, \"you cannot specify both options placementGroup and noPlacementGroup\");\n      this.noPlacementGroup = true;\n      return this;\n   }\n\n   /**\n    * Specifies the subnetId used to run instances in\n    */\n   public AWSEC2TemplateOptions subnetId(String subnetId) {\n      this.subnetId = checkNotNull(emptyToNull(subnetId), \"subnetId must be defined\");\n      return this;\n   }\n\n   /**\n    * @see org.jclouds.aws.ec2.options.AWSRunInstancesOptions#withIAMInstanceProfileArn(String)\n    */\n   @SinceApiVersion(\"2012-06-01\")\n   public AWSEC2TemplateOptions iamInstanceProfileArn(String arn) {\n      this.iamInstanceProfileArn = checkNotNull(emptyToNull(arn), \"arn must be defined\");\n      return this;\n   }\n\n   /**\n    * @see org.jclouds.aws.ec2.options.AWSRunInstancesOptions#withIAMInstanceProfileName(String)\n    */\n   @SinceApiVersion(\"2012-06-01\")\n   public AWSEC2TemplateOptions iamInstanceProfileName(String name) {\n      this.iamInstanceProfileName = checkNotNull(emptyToNull(name), \"name must be defined\");\n      return this;\n   }\n\n   public AWSEC2TemplateOptions privateIpAddress(String address) {\n      this.privateIpAddress = checkNotNull(emptyToNull(address), \"address must be defined\");\n      return this;\n   }\n\n   /**\n    * Specifies the tenancy used to run instances with\n    */\n   public AWSEC2TemplateOptions tenancy(Tenancy tenancy) {\n      this.tenancy = checkNotNull(tenancy, \"tenancy must be defined\");\n      return this;\n   }\n\n   /**\n    * Specifies the ID of the dedicated host on which the instance should resist.\n    */\n   public AWSEC2TemplateOptions dedicatedHostId(String hostId) {\n      this.dedicatedHostId = checkNotNull(emptyToNull(hostId), \"hostId must be defined\");\n      return this;\n   }\n\n   /**\n    * Specifies the maximum spot price to use\n    */\n   public AWSEC2TemplateOptions spotPrice(Float spotPrice) {\n      this.spotPrice = spotPrice;\n      return this;\n   }\n\n   /**\n    * Options for starting spot instances\n    */\n   public AWSEC2TemplateOptions spotOptions(RequestSpotInstancesOptions spotOptions) {\n      Calendar cal = Calendar.getInstance();\n      cal.setTime(new Date());\n      cal.add(Calendar.MINUTE, 30);\n      this.spotOptions = spotOptions != null ? spotOptions : RequestSpotInstancesOptions.Builder.validUntil(cal.getTime());\n      return this;\n   }\n\n   /**\n    *\n    * @see AWSEC2TemplateOptions#securityGroupIds(Iterable<String>)\n    */\n   public AWSEC2TemplateOptions securityGroupIds(String... groupIds) {\n      return securityGroupIds(ImmutableSet.copyOf(groupIds));\n   }\n\n   /**\n    * Specifies the security group ids to be used for nodes with this template\n    */\n   public AWSEC2TemplateOptions securityGroupIds(Iterable<String> groupIds) {\n      checkArgument(!Iterables.isEmpty(groupIds), \"you must specify at least one security group\");\n      for (String groupId : groupIds)\n         checkNotNull(emptyToNull(groupId), \"all security groups must be non-empty\");\n      this.groupIds = ImmutableSet.copyOf(groupIds);\n      return this;\n   }\n\n   public Set<String> getGroupIds() {\n      return groupIds;\n   }\n\n   public static class Builder {\n\n      public static AWSEC2TemplateOptions overrideLoginUser(String user) {\n         AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n         return options.overrideLoginUser(user);\n      }\n\n      public static AWSEC2TemplateOptions overrideLoginPassword(String password) {\n         AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n         return options.overrideLoginPassword(password);\n      }\n\n      public static AWSEC2TemplateOptions overrideLoginPrivateKey(String privateKey) {\n         AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n         return options.overrideLoginPrivateKey(privateKey);\n      }\n\n      public static AWSEC2TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo) {\n         AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n         return options.overrideAuthenticateSudo(authenticateSudo);\n      }\n\n      public static AWSEC2TemplateOptions overrideLoginCredentials(LoginCredentials credentials) {\n         AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n         return options.overrideLoginCredentials(credentials);\n      }\n\n      /**\n       * @see AWSEC2TemplateOptions#securityGroupIds(Iterable<String>)\n       */\n      public static AWSEC2TemplateOptions securityGroupIds(String... groupNames) {\n         AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n         return AWSEC2TemplateOptions.class.cast(options.securityGroupIds(groupNames));\n      }\n\n      /**\n       * @see AWSEC2TemplateOptions#securityGroupIds(Iterable<String>)\n       */\n      public static AWSEC2TemplateOptions securityGroupIds(Iterable<String> groupNames) {\n         AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n         return AWSEC2TemplateOptions.class.cast(options.securityGroupIds(groupNames));\n      }\n\n      /**\n       * @see EC2TemplateOptions#blockDeviceMappings\n       */\n      public static AWSEC2TemplateOptions blockDeviceMappings(Set<? extends BlockDeviceMapping> blockDeviceMappings) {\n         AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n         return options.blockDeviceMappings(blockDeviceMappings);\n      }\n\n      /**\n       * @see EC2TemplateOptions#mapEBSSnapshotToDeviceName\n       */\n      public static AWSEC2TemplateOptions mapEBSSnapshotToDeviceName(String deviceName, String snapshotId,\n            @Nullable Integer sizeInGib, boolean deleteOnTermination) {\n         AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n         return options.mapEBSSnapshotToDeviceName(deviceName, snapshotId, sizeInGib, deleteOnTermination);\n      }\n\n      /**\n       * @see EC2TemplateOptions#mapNewVolumeToDeviceName\n       */\n      public static AWSEC2TemplateOptions mapNewVolumeToDeviceName(String deviceName, int sizeInGib,\n            boolean deleteOnTermination) {\n         AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n         return options.mapNewVolumeToDeviceName(deviceName, sizeInGib, deleteOnTermination);\n      }\n\n      /**\n       * @see EC2TemplateOptions#mapEphemeralDeviceToDeviceName\n       */\n      public static AWSEC2TemplateOptions mapEphemeralDeviceToDeviceName(String deviceName, String virtualName) {\n         AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n         return options.mapEphemeralDeviceToDeviceName(deviceName, virtualName);\n      }\n\n      /**\n       * @see EC2TemplateOptions#unmapDeviceNamed\n       */\n      public static AWSEC2TemplateOptions unmapDeviceNamed(String deviceName) {\n         AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n         return options.unmapDeviceNamed(deviceName);\n      }\n\n      /**\n       * @see AWSEC2TemplateOptions#securityGroups(Iterable<String>)\n       */\n      public static AWSEC2TemplateOptions securityGroups(String... groupIds) {\n         AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n         return options.securityGroups(groupIds);\n      }\n\n      /**\n       * @see AWSEC2TemplateOptions#securityGroups(Iterable<String>)\n       */\n      public static AWSEC2TemplateOptions securityGroups(Iterable<String> groupIds) {\n         AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n         return options.securityGroups(groupIds);\n      }\n\n      /**\n       * @see AWSEC2TemplateOptions#keyPair\n       */\n      public static AWSEC2TemplateOptions keyPair(String keyPair) {\n         AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n         return options.keyPair(keyPair);\n      }\n\n      /**\n       * @see AWSEC2TemplateOptions#userData\n       */\n      public static AWSEC2TemplateOptions userData(byte[] unencodedData) {\n         AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n         return options.userData(unencodedData);\n      }\n\n      /**\n       * @see AWSEC2TemplateOptions#noKeyPair\n       */\n      public static AWSEC2TemplateOptions noKeyPair() {\n         AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n         return options.noKeyPair();\n      }\n\n      /**\n       * @see AWSEC2TemplateOptions#placementGroup\n       */\n      public static AWSEC2TemplateOptions placementGroup(String placementGroup) {\n         AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n         return options.placementGroup(placementGroup);\n      }\n\n      /**\n       * @see AWSEC2TemplateOptions#noPlacementGroup\n       */\n      public static AWSEC2TemplateOptions noPlacementGroup() {\n         AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n         return options.noPlacementGroup();\n      }\n\n      /**\n       * @see AWSEC2TemplateOptions#enableMonitoring\n       */\n      public static AWSEC2TemplateOptions enableMonitoring() {\n         AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n         return options.enableMonitoring();\n      }\n\n      // methods that only facilitate returning the correct object type\n      /**\n       * @see TemplateOptions#inboundPorts\n       */\n      public static AWSEC2TemplateOptions inboundPorts(int... ports) {\n         AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n         return options.inboundPorts(ports);\n      }\n\n      /**\n       * @see TemplateOptions#port\n       */\n      public static AWSEC2TemplateOptions blockOnPort(int port, int seconds) {\n         AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n         return options.blockOnPort(port, seconds);\n      }\n\n      /**\n       * @see TemplateOptions#installPrivateKey\n       */\n      public static AWSEC2TemplateOptions installPrivateKey(String rsaKey) {\n         AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n         return options.installPrivateKey(rsaKey);\n      }\n\n      /**\n       * @see TemplateOptions#authorizePublicKey\n       */\n      public static AWSEC2TemplateOptions authorizePublicKey(String rsaKey) {\n         AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n         return options.authorizePublicKey(rsaKey);\n      }\n\n      /**\n       * @see AWSEC2TemplateOptions#subnetId\n       */\n      public static AWSEC2TemplateOptions subnetId(String subnetId) {\n         AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n         return options.subnetId(subnetId);\n      }\n\n      /**\n       * @see AWSEC2TemplateOptions#iamInstanceProfileArn\n       */\n      @SinceApiVersion(\"2012-06-01\")\n      public static AWSEC2TemplateOptions iamInstanceProfileArn(String arn) {\n         AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n         return options.iamInstanceProfileArn(arn);\n      }\n\n      /**\n       * @see AWSEC2TemplateOptions#iamInstanceProfileName\n       */\n      @SinceApiVersion(\"2012-06-01\")\n      public static AWSEC2TemplateOptions iamInstanceProfileName(String name) {\n         AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n         return options.iamInstanceProfileName(name);\n      }\n\n      public static AWSEC2TemplateOptions privateIpAddress(String address) {\n         AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n         return options.privateIpAddress(address);\n      }\n\n      /**\n       * @see AWSEC2TemplateOptions#tenancy\n       */\n      public static AWSEC2TemplateOptions tenancy(Tenancy tenancy) {\n         AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n         return options.tenancy(tenancy);\n      }\n\n      /**\n       * @see AWSEC2TemplateOptions#dedicatedHostId\n       */\n      public static AWSEC2TemplateOptions dedicatedHostId(String hostId) {\n         AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n         return options.dedicatedHostId(hostId);\n      }\n\n      /**\n       * @see AWSEC2TemplateOptions#spotPrice\n       */\n      public static AWSEC2TemplateOptions spotPrice(Float spotPrice) {\n         AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n         return options.spotPrice(spotPrice);\n      }\n\n      /**\n       * @see AWSEC2TemplateOptions#spotOptions\n       */\n      public static AWSEC2TemplateOptions spotOptions(RequestSpotInstancesOptions spotOptions) {\n         AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n         return options.spotOptions(spotOptions);\n      }\n\n      /**\n       * @see TemplateOptions#userMetadata(Map)\n       */\n      public static AWSEC2TemplateOptions userMetadata(Map<String, String> userMetadata) {\n         AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n         return AWSEC2TemplateOptions.class.cast(options.userMetadata(userMetadata));\n      }\n\n      /**\n       * @see TemplateOptions#userMetadata(String, String)\n       */\n      public static AWSEC2TemplateOptions userMetadata(String key, String value) {\n         AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n         return AWSEC2TemplateOptions.class.cast(options.userMetadata(key, value));\n      }\n\n      public static AWSEC2TemplateOptions blockUntilRunning(boolean blockUntilRunning) {\n         AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n         return options.blockUntilRunning(blockUntilRunning);\n      }\n\n      /**\n       * @see TemplateOptions#nodeNames(Iterable)\n       */\n      public static AWSEC2TemplateOptions nodeNames(Iterable<String> nodeNames) {\n         AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n         return AWSEC2TemplateOptions.class.cast(options.nodeNames(nodeNames));\n      }\n\n      /**\n       * @see TemplateOptions#networks(Iterable)\n       */\n      public static AWSEC2TemplateOptions networks(Iterable<String> networks) {\n         AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n         return AWSEC2TemplateOptions.class.cast(options.networks(networks));\n      }\n   }\n\n   // methods that only facilitate returning the correct object type\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public AWSEC2TemplateOptions blockDeviceMappings(Iterable<? extends BlockDeviceMapping> blockDeviceMappings) {\n      return AWSEC2TemplateOptions.class.cast(super.blockDeviceMappings(blockDeviceMappings));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public AWSEC2TemplateOptions userMetadata(Map<String, String> userMetadata) {\n      return AWSEC2TemplateOptions.class.cast(super.userMetadata(userMetadata));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public AWSEC2TemplateOptions userMetadata(String key, String value) {\n      return AWSEC2TemplateOptions.class.cast(super.userMetadata(key, value));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public AWSEC2TemplateOptions nodeNames(Iterable<String> nodeNames) {\n      return AWSEC2TemplateOptions.class.cast(super.nodeNames(nodeNames));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public AWSEC2TemplateOptions networks(Iterable<String> networks) {\n      return AWSEC2TemplateOptions.class.cast(super.networks(networks));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public AWSEC2TemplateOptions keyPair(String keyPair) {\n      return AWSEC2TemplateOptions.class.cast(super.keyPair(keyPair));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n\n   @Override\n   public AWSEC2TemplateOptions mapEBSSnapshotToDeviceName(String deviceName, String snapshotId, Integer sizeInGib,\n         boolean deleteOnTermination) {\n      return AWSEC2TemplateOptions.class.cast(super.mapEBSSnapshotToDeviceName(deviceName, snapshotId, sizeInGib,\n            deleteOnTermination));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public AWSEC2TemplateOptions mapEphemeralDeviceToDeviceName(String deviceName, String virtualName) {\n      return AWSEC2TemplateOptions.class.cast(super.mapEphemeralDeviceToDeviceName(deviceName, virtualName));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public AWSEC2TemplateOptions mapNewVolumeToDeviceName(String deviceName, int sizeInGib, boolean deleteOnTermination) {\n      return AWSEC2TemplateOptions.class.cast(super\n            .mapNewVolumeToDeviceName(deviceName, sizeInGib, deleteOnTermination));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public AWSEC2TemplateOptions noKeyPair() {\n      return AWSEC2TemplateOptions.class.cast(super.noKeyPair());\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public AWSEC2TemplateOptions securityGroups(Iterable<String> groupIds) {\n      return AWSEC2TemplateOptions.class.cast(super.securityGroups(groupIds));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public AWSEC2TemplateOptions securityGroups(String... groupIds) {\n      return AWSEC2TemplateOptions.class.cast(super.securityGroups(groupIds));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public AWSEC2TemplateOptions unmapDeviceNamed(String deviceName) {\n      return AWSEC2TemplateOptions.class.cast(super.unmapDeviceNamed(deviceName));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public AWSEC2TemplateOptions userData(byte[] unencodedData) {\n      return AWSEC2TemplateOptions.class.cast(super.userData(unencodedData));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public AWSEC2TemplateOptions blockOnPort(int port, int seconds) {\n      return AWSEC2TemplateOptions.class.cast(super.blockOnPort(port, seconds));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public AWSEC2TemplateOptions inboundPorts(int... ports) {\n      return AWSEC2TemplateOptions.class.cast(super.inboundPorts(ports));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public AWSEC2TemplateOptions authorizePublicKey(String publicKey) {\n      return AWSEC2TemplateOptions.class.cast(super.authorizePublicKey(publicKey));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public AWSEC2TemplateOptions installPrivateKey(String privateKey) {\n      return AWSEC2TemplateOptions.class.cast(super.installPrivateKey(privateKey));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public AWSEC2TemplateOptions blockUntilRunning(boolean blockUntilRunning) {\n      return AWSEC2TemplateOptions.class.cast(super.blockUntilRunning(blockUntilRunning));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public AWSEC2TemplateOptions dontAuthorizePublicKey() {\n      return AWSEC2TemplateOptions.class.cast(super.dontAuthorizePublicKey());\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public AWSEC2TemplateOptions nameTask(String name) {\n      return AWSEC2TemplateOptions.class.cast(super.nameTask(name));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public AWSEC2TemplateOptions runAsRoot(boolean runAsRoot) {\n      return AWSEC2TemplateOptions.class.cast(super.runAsRoot(runAsRoot));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public AWSEC2TemplateOptions runScript(Statement script) {\n      return AWSEC2TemplateOptions.class.cast(super.runScript(script));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public AWSEC2TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials) {\n      return AWSEC2TemplateOptions.class.cast(super.overrideLoginCredentials(overridingCredentials));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public AWSEC2TemplateOptions overrideLoginPassword(String password) {\n      return AWSEC2TemplateOptions.class.cast(super.overrideLoginPassword(password));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public AWSEC2TemplateOptions overrideLoginPrivateKey(String privateKey) {\n      return AWSEC2TemplateOptions.class.cast(super.overrideLoginPrivateKey(privateKey));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public AWSEC2TemplateOptions overrideLoginUser(String loginUser) {\n      return AWSEC2TemplateOptions.class.cast(super.overrideLoginUser(loginUser));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public AWSEC2TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo) {\n      return AWSEC2TemplateOptions.class.cast(super.overrideAuthenticateSudo(authenticateSudo));\n   }\n\n   /**\n    * @return placementGroup to use when running the instance or null, to\n    *         generate a placementGroup.\n    */\n   public String getPlacementGroup() {\n      return placementGroup;\n   }\n\n   /**\n    * @return true (default) if we are supposed to use a placementGroup\n    */\n   public boolean shouldAutomaticallyCreatePlacementGroup() {\n      return !noPlacementGroup;\n   }\n\n   /**\n    * @return true (default) if we are supposed to enable cloudwatch\n    */\n   public boolean isMonitoringEnabled() {\n      return monitoringEnabled;\n   }\n\n   /**\n    * @return subnetId to use when running the instance or null.\n    */\n   public String getSubnetId() {\n      return subnetId;\n   }\n\n   /**\n    * @return maximum spot price or null.\n    */\n   public Float getSpotPrice() {\n      return spotPrice;\n   }\n\n   /**\n    * @return options for controlling spot instance requests.\n    */\n   public RequestSpotInstancesOptions getSpotOptions() {\n      return spotOptions;\n   }\n\n   /**\n    * The Amazon resource name (ARN) of the IAM Instance Profile (IIP) to associate with the instance.\n    *\n    * @see org.jclouds.aws.ec2.options.AWSRunInstancesOptions#withIAMInstanceProfileArn(String)\n    */\n   @SinceApiVersion(\"2012-06-01\")\n   public String getIAMInstanceProfileArn() {\n      return iamInstanceProfileArn;\n   }\n\n   /**\n    * The name of the IAM Instance Profile (IIP) to associate with the instance.\n    *\n    * @see org.jclouds.aws.ec2.options.AWSRunInstancesOptions#withIAMInstanceProfileName(String)\n    */\n   @SinceApiVersion(\"2012-06-01\")\n   public String getIAMInstanceProfileName() {\n      return iamInstanceProfileName;\n   }\n\n   public String getPrivateIpAddress() {\n      return privateIpAddress;\n   }\n\n   public Tenancy getTenancy() {\n      return tenancy;\n   }\n\n   public String getDedicatedHostId() {\n      return dedicatedHostId;\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/compute/config/AWSEC2BindComputeSuppliersByClass.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.compute.config;\n\nimport java.util.Set;\n\nimport org.jclouds.aws.ec2.compute.suppliers.AWSEC2ImageSupplier;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.ec2.compute.config.EC2BindComputeSuppliersByClass;\n\nimport com.google.common.base.Supplier;\npublic class AWSEC2BindComputeSuppliersByClass extends EC2BindComputeSuppliersByClass {\n   @Override\n   protected Class<? extends Supplier<Set<? extends Image>>> defineImageSupplier() {\n      return AWSEC2ImageSupplier.class;\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/compute/config/AWSEC2ComputeServiceContextModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.compute.config;\n\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.ec2.compute.AWSEC2TemplateBuilderImpl;\nimport org.jclouds.aws.ec2.compute.functions.AWSRunningInstanceToNodeMetadata;\nimport org.jclouds.aws.ec2.compute.functions.PresentSpotRequestsAndInstances;\nimport org.jclouds.aws.ec2.compute.strategy.AWSEC2CreateNodesInGroupThenAddToSet;\nimport org.jclouds.aws.ec2.compute.strategy.AWSEC2DestroyNodeStrategy;\nimport org.jclouds.aws.ec2.compute.strategy.AWSEC2GetNodeMetadataStrategy;\nimport org.jclouds.aws.ec2.compute.strategy.AWSEC2IOExceptionRetryHandler;\nimport org.jclouds.aws.ec2.compute.strategy.AWSEC2ListNodesStrategy;\nimport org.jclouds.aws.ec2.compute.strategy.AWSEC2ReviseParsedImage;\nimport org.jclouds.aws.ec2.compute.strategy.CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions;\nimport org.jclouds.aws.ec2.compute.suppliers.AWSEC2HardwareSupplier;\nimport org.jclouds.compute.config.BaseComputeServiceContextModule;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.ec2.compute.config.EC2BindComputeStrategiesByClass;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.compute.functions.PresentInstances;\nimport org.jclouds.ec2.compute.functions.RunningInstanceToNodeMetadata;\nimport org.jclouds.ec2.compute.internal.EC2TemplateBuilderImpl;\nimport org.jclouds.ec2.compute.loaders.RegionAndIdToImage;\nimport org.jclouds.ec2.compute.options.EC2TemplateOptions;\nimport org.jclouds.ec2.compute.strategy.CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions;\nimport org.jclouds.ec2.compute.strategy.EC2CreateNodesInGroupThenAddToSet;\nimport org.jclouds.ec2.compute.strategy.EC2DestroyNodeStrategy;\nimport org.jclouds.ec2.compute.strategy.EC2GetNodeMetadataStrategy;\nimport org.jclouds.ec2.compute.strategy.EC2ListNodesStrategy;\nimport org.jclouds.ec2.compute.strategy.ReviseParsedImage;\nimport org.jclouds.ec2.compute.suppliers.EC2HardwareSupplier;\nimport org.jclouds.ec2.compute.suppliers.RegionAndNameToImageSupplier;\nimport org.jclouds.http.IOExceptionRetryHandler;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.suppliers.SetAndThrowAuthorizationExceptionSupplier;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.base.Throwables;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.util.concurrent.Atomics;\nimport com.google.inject.Injector;\nimport com.google.inject.Key;\nimport com.google.inject.Provides;\nimport com.google.inject.TypeLiteral;\n\npublic class AWSEC2ComputeServiceContextModule extends BaseComputeServiceContextModule {\n   @Override\n   protected void configure() {\n      super.configure();\n      installDependencies();\n      install(new EC2BindComputeStrategiesByClass());\n      install(new AWSEC2BindComputeSuppliersByClass());\n      bind(ReviseParsedImage.class).to(AWSEC2ReviseParsedImage.class);\n      bind(CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class).to(\n               CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.class);\n      bind(EC2HardwareSupplier.class).to(AWSEC2HardwareSupplier.class);\n      bind(EC2TemplateBuilderImpl.class).to(AWSEC2TemplateBuilderImpl.class);\n      bind(EC2GetNodeMetadataStrategy.class).to(AWSEC2GetNodeMetadataStrategy.class);\n      bind(EC2ListNodesStrategy.class).to(AWSEC2ListNodesStrategy.class);\n      bind(EC2DestroyNodeStrategy.class).to(AWSEC2DestroyNodeStrategy.class);\n      bind(PresentInstances.class).to(PresentSpotRequestsAndInstances.class);\n      bind(EC2CreateNodesInGroupThenAddToSet.class).to(AWSEC2CreateNodesInGroupThenAddToSet.class);\n      bind(RunningInstanceToNodeMetadata.class).to(AWSRunningInstanceToNodeMetadata.class);\n      bind(IOExceptionRetryHandler.class).to(AWSEC2IOExceptionRetryHandler.class);\n   }\n\n   protected void installDependencies() {\n      install(new AWSEC2ComputeServiceDependenciesModule());\n   }\n\n   @Override\n   protected boolean shouldEagerlyParseImages(Injector injector) {\n      Map<String, String> queries = injector.getInstance(Key.get(new TypeLiteral<Map<String, String>>() {\n      }, ImageQuery.class));\n      // If no queries defined, then will never lookup all images\n      return !queries.isEmpty();\n   }\n\n   // duplicates EC2ComputeServiceContextModule; but that's easiest thing to do with guice; could extract to common util\n   // TODO: have a another look at this (Adrian)\n   @Override\n   protected Supplier<Set<? extends Image>> supplyNonParsingImages(final Supplier<Set<? extends Image>> imageSupplier,\n         Injector injector) {\n      final Supplier<LoadingCache<RegionAndName, ? extends Image>> cache = injector.getInstance(Key\n               .get(new TypeLiteral<Supplier<LoadingCache<RegionAndName, ? extends Image>>>() {\n               }));\n      return new Supplier<Set<? extends Image>>() {\n         @Override\n         public Set<? extends Image> get() {\n            return ImmutableSet.copyOf(cache.get().asMap().values());\n         }\n      };\n   }\n\n   // duplicates EC2ComputeServiceContextModule; but that's easiest thing to do with guice; could extract to common util\n   @Provides\n   @Singleton\n   protected final Supplier<CacheLoader<RegionAndName, Image>> guiceProvideRegionAndNameToImageSupplierCacheLoader(\n           final RegionAndIdToImage delegate) {\n      return provideRegionAndNameToImageSupplierCacheLoader(delegate);\n   }\n\n   protected Supplier<CacheLoader<RegionAndName, Image>> provideRegionAndNameToImageSupplierCacheLoader(\n            final RegionAndIdToImage delegate) {\n      return Suppliers.<CacheLoader<RegionAndName, Image>>ofInstance(new CacheLoader<RegionAndName, Image>() {\n         private final AtomicReference<AuthorizationException> authException = Atomics.newReference();\n\n         @Override\n         public Image load(final RegionAndName key) throws Exception {\n            // raw lookup of an image\n            Supplier<Image> rawSupplier = new Supplier<Image>() {\n               @Override public Image get() {\n                  try {\n                     return delegate.load(key);\n                  } catch (ExecutionException e) {\n                     throw Throwables.propagate(e);\n                  }\n               }\n            };\n            return new SetAndThrowAuthorizationExceptionSupplier<Image>(rawSupplier, authException).get();\n         }\n\n      });\n   }\n\n   @Provides\n   @Singleton\n   protected final Supplier<LoadingCache<RegionAndName, ? extends Image>> provideRegionAndNameToImageSupplierCache(\n            final RegionAndNameToImageSupplier supplier) {\n      return supplier;\n   }\n\n   /**\n    * With amazon linux 2011.09, ssh starts after package updates, which slows the boot process and\n    * runs us out of ssh retries (context property {@code \"jclouds.ssh.max-retries\"}).\n    *\n    * @see <a href=\"http://aws.amazon.com/amazon-linux-ami/latest-release-notes/\" />\n    * @see AWSEC2PropertiesBuilder#defaultProperties\n    */\n   @Override\n   protected TemplateOptions provideTemplateOptions(Injector injector, TemplateOptions options) {\n      return options.as(EC2TemplateOptions.class).userData(\"#cloud-config\\nrepo_upgrade: none\\n\".getBytes());\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/compute/config/AWSEC2ComputeServiceDependenciesModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.compute.config;\n\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static org.jclouds.aws.ec2.reference.AWSEC2Constants.PROPERTY_EC2_AMI_QUERY;\nimport static org.jclouds.aws.ec2.reference.AWSEC2Constants.PROPERTY_EC2_CC_AMI_QUERY;\nimport static org.jclouds.ec2.reference.EC2Constants.PROPERTY_EC2_AMI_OWNERS;\nimport static org.jclouds.util.Predicates2.retry;\n\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.logging.Logger;\n\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.ec2.compute.AWSEC2ComputeService;\nimport org.jclouds.aws.ec2.compute.AWSEC2TemplateOptions;\nimport org.jclouds.aws.ec2.compute.extensions.AWSEC2SecurityGroupExtension;\nimport org.jclouds.aws.ec2.compute.functions.AWSEC2SecurityGroupToSecurityGroup;\nimport org.jclouds.aws.ec2.compute.loaders.AWSEC2CreateSecurityGroupIfNeeded;\nimport org.jclouds.aws.ec2.compute.suppliers.CallForImages;\nimport org.jclouds.aws.ec2.domain.PlacementGroup;\nimport org.jclouds.aws.ec2.domain.RegionNameAndPublicKeyMaterial;\nimport org.jclouds.aws.ec2.functions.CreatePlacementGroupIfNeeded;\nimport org.jclouds.aws.ec2.functions.ImportOrReturnExistingKeypair;\nimport org.jclouds.aws.ec2.predicates.PlacementGroupAvailable;\nimport org.jclouds.aws.ec2.predicates.PlacementGroupDeleted;\nimport org.jclouds.compute.ComputeService;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.SecurityGroup;\nimport org.jclouds.compute.domain.TemplateBuilder;\nimport org.jclouds.compute.extensions.ImageExtension;\nimport org.jclouds.compute.extensions.SecurityGroupExtension;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.config.ValueOfConfigurationKeyOrNull;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.ec2.compute.config.EC2ComputeServiceDependenciesModule;\nimport org.jclouds.ec2.compute.domain.PasswordDataAndPrivateKey;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.compute.extensions.EC2ImageExtension;\nimport org.jclouds.ec2.compute.functions.CreateUniqueKeyPair;\nimport org.jclouds.ec2.compute.functions.CredentialsForInstance;\nimport org.jclouds.ec2.compute.functions.EC2ImageParser;\nimport org.jclouds.ec2.compute.functions.EC2SecurityGroupIdFromName;\nimport org.jclouds.ec2.compute.functions.PasswordCredentialsFromWindowsInstance;\nimport org.jclouds.ec2.compute.functions.WindowsLoginCredentialsFromEncryptedData;\nimport org.jclouds.ec2.compute.internal.EC2TemplateBuilderImpl;\nimport org.jclouds.ec2.compute.loaders.LoadPublicIpForInstanceOrNull;\nimport org.jclouds.ec2.compute.loaders.RegionAndIdToImage;\nimport org.jclouds.ec2.domain.KeyPair;\nimport org.jclouds.ec2.domain.RunningInstance;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Strings;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMap.Builder;\nimport com.google.common.collect.Sets;\nimport com.google.inject.Provides;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.assistedinject.FactoryModuleBuilder;\nimport com.google.inject.name.Names;\n\npublic class AWSEC2ComputeServiceDependenciesModule extends EC2ComputeServiceDependenciesModule {\n   @Override\n   protected void configure() {\n      bind(TemplateBuilder.class).to(EC2TemplateBuilderImpl.class);\n      bind(TemplateOptions.class).to(AWSEC2TemplateOptions.class);\n      bind(ComputeService.class).to(AWSEC2ComputeService.class);\n      bind(new TypeLiteral<CacheLoader<RunningInstance, Optional<LoginCredentials>>>() {\n      }).to(CredentialsForInstance.class);\n      bind(new TypeLiteral<CacheLoader<RegionAndName, String>>() {\n      }).annotatedWith(Names.named(\"SECURITY\")).to(AWSEC2CreateSecurityGroupIfNeeded.class);\n      bind(new TypeLiteral<CacheLoader<RegionAndName, String>>() {\n      }).annotatedWith(Names.named(\"ELASTICIP\")).to(LoadPublicIpForInstanceOrNull.class);\n      bind(new TypeLiteral<Function<String, String>>() {\n      }).annotatedWith(Names.named(\"SECGROUP_NAME_TO_ID\")).to(EC2SecurityGroupIdFromName.class);\n      bind(new TypeLiteral<Function<PasswordDataAndPrivateKey, LoginCredentials>>() {\n      }).to(WindowsLoginCredentialsFromEncryptedData.class);\n      bind(new TypeLiteral<Function<RunningInstance, LoginCredentials>>() {\n      }).to(PasswordCredentialsFromWindowsInstance.class);\n      bind(new TypeLiteral<Function<RegionAndName, KeyPair>>() {\n      }).to(CreateUniqueKeyPair.class);\n      bind(new TypeLiteral<Function<RegionNameAndPublicKeyMaterial, KeyPair>>() {\n      }).to(ImportOrReturnExistingKeypair.class);\n      bind(new TypeLiteral<CacheLoader<RegionAndName, Image>>() {\n      }).to(RegionAndIdToImage.class);\n      install(new FactoryModuleBuilder().build(CallForImages.Factory.class));\n      bind(new TypeLiteral<Function<org.jclouds.ec2.domain.Image, Image>>() {\n      }).to(EC2ImageParser.class);\n      bind(new TypeLiteral<Function<org.jclouds.ec2.domain.SecurityGroup, SecurityGroup>>() {\n      }).to(AWSEC2SecurityGroupToSecurityGroup.class);\n      bind(new TypeLiteral<ImageExtension>() {\n      }).to(EC2ImageExtension.class);\n      bind(new TypeLiteral<SecurityGroupExtension>() {\n      }).to(AWSEC2SecurityGroupExtension.class);\n   }\n\n   @Provides\n   @Singleton\n   @ImageQuery\n   protected final Map<String, String> imageQuery(ValueOfConfigurationKeyOrNull config) {\n      String amiQuery = Strings.emptyToNull(config.apply(PROPERTY_EC2_AMI_QUERY));\n      String owners = config.apply(PROPERTY_EC2_AMI_OWNERS);\n      if (\"\".equals(owners)) {\n         amiQuery = null;\n      } else if (owners != null) {\n         StringBuilder query = new StringBuilder();\n         if (\"*\".equals(owners))\n            query.append(\"state=available;image-type=machine\");\n         else\n            query.append(\"owner-id=\").append(owners).append(\";state=available;image-type=machine\");\n         Logger.getAnonymousLogger().warning(\n               String.format(\"Property %s is deprecated, please use new syntax: %s=%s\", PROPERTY_EC2_AMI_OWNERS,\n                     PROPERTY_EC2_AMI_QUERY, query.toString()));\n         amiQuery = query.toString();\n      }\n      Builder<String, String> builder = ImmutableMap.<String, String> builder();\n      if (amiQuery != null)\n         builder.put(PROPERTY_EC2_AMI_QUERY, amiQuery);\n      String ccQuery = Strings.emptyToNull(config.apply(PROPERTY_EC2_CC_AMI_QUERY));\n      if (ccQuery != null)\n         builder.put(PROPERTY_EC2_CC_AMI_QUERY, ccQuery);\n      return builder.build();\n   }\n\n   @Provides\n   @Singleton\n   @Named(\"AVAILABLE\")\n   protected final Predicate<PlacementGroup> placementGroupAvailable(PlacementGroupAvailable available) {\n      return retry(available, 60, 1, SECONDS);\n   }\n\n   @Provides\n   @Singleton\n   @Named(\"DELETED\")\n   protected final Predicate<PlacementGroup> placementGroupDeleted(PlacementGroupDeleted deleted) {\n      return retry(deleted, 60, 1, SECONDS);\n   }\n\n   @Provides\n   @Singleton\n   @Named(\"PLACEMENT\")\n   protected final LoadingCache<RegionAndName, String> placementGroupMap(CreatePlacementGroupIfNeeded in) {\n      return CacheBuilder.newBuilder().build(in);\n   }\n\n   @Provides\n   @ClusterCompute\n   @Singleton\n   protected final Set<String> provideClusterComputeIds() {\n      return Sets.newLinkedHashSet();\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/compute/config/ClusterCompute.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.compute.config;\n\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\nimport jakarta.inject.Qualifier;\n\n/**\n * Related to a ClusterCompute resource.\n */\n@Retention(value = RetentionPolicy.RUNTIME)\n@Target(value = { ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })\n@Qualifier\npublic @interface ClusterCompute {\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/compute/config/ImageQuery.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.compute.config;\n\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\nimport jakarta.inject.Qualifier;\n\n/**\n * Related to an Image Query\n */\n@Retention(value = RetentionPolicy.RUNTIME)\n@Target(value = { ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD })\n@Qualifier\npublic @interface ImageQuery {\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/compute/extensions/AWSEC2SecurityGroupExtension.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.compute.extensions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Predicates.notNull;\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static com.google.common.collect.Iterables.transform;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport java.util.Map;\nimport java.util.Set;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Multimap;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport org.jclouds.Constants;\nimport org.jclouds.aws.ec2.AWSEC2Api;\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.domain.SecurityGroup;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.domain.Location;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.compute.domain.RegionNameAndIngressRules;\nimport org.jclouds.ec2.compute.extensions.EC2SecurityGroupExtension;\nimport org.jclouds.location.Region;\nimport org.jclouds.net.domain.IpPermission;\nimport org.jclouds.net.domain.IpProtocol;\n\n/**\n * An extension to compute service to allow for the manipulation of {@link SecurityGroup}s. Implementation\n * is optional by providers.\n */\npublic class AWSEC2SecurityGroupExtension extends EC2SecurityGroupExtension {\n   protected final AWSEC2Api client;\n   protected final Function<String, String> groupNameToId;\n\n   @Inject\n   public AWSEC2SecurityGroupExtension(AWSEC2Api client,\n                                       @Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor,\n                                       @Region Supplier<Set<String>> regions,\n                                       Function<org.jclouds.ec2.domain.SecurityGroup, SecurityGroup> groupConverter,\n                                       @Memoized Supplier<Set<? extends Location>> locations,\n                                       @Named(\"SECURITY\") LoadingCache<RegionAndName, String> groupCreator,\n                                       GroupNamingConvention.Factory namingConvention,\n                                       @Named(\"SECGROUP_NAME_TO_ID\") Function<String, String> groupNameToId) {\n      super(client, userExecutor, regions, groupConverter, locations, groupCreator, namingConvention);\n      this.client = checkNotNull(client, \"client\");\n      this.groupNameToId = checkNotNull(groupNameToId, \"groupNameToId\");\n   }\n\n   @Override\n   public SecurityGroup createSecurityGroup(String name, String region) {\n      String markerGroup = namingConvention.create().sharedNameForGroup(name);\n      RegionNameAndIngressRules regionAndName = new RegionNameAndIngressRules(region, markerGroup, new int[] {},\n              false, null);\n\n      groupCreator.getUnchecked(regionAndName);\n      String groupId = groupNameToId.apply(regionAndName.slashEncode());\n      return getSecurityGroupById(regionAndName.getRegion() + \"/\" + groupId);\n   }\n\n   @Override\n   public SecurityGroup getSecurityGroupById(String id) {\n      checkNotNull(id, \"id\");\n      String[] parts = AWSUtils.parseHandle(id);\n      String region = parts[0];\n      String groupId = parts[1];\n\n      Set<? extends org.jclouds.ec2.domain.SecurityGroup> rawGroups =\n              client.getSecurityGroupApi().get().describeSecurityGroupsInRegionById(region, groupId);\n\n      return getOnlyElement(transform(filter(rawGroups, notNull()), groupConverter));\n   }\n\n   @Override\n   public boolean removeSecurityGroup(String id) {\n      checkNotNull(id, \"id\");\n      String[] parts = AWSUtils.parseHandle(id);\n      String region = parts[0];\n      String groupId = parts[1];\n\n      org.jclouds.ec2.domain.SecurityGroup group = Iterables.getFirst(\n              client.getSecurityGroupApi().get().describeSecurityGroupsInRegionById(region, groupId),\n              null);\n\n      if (group != null) {\n         client.getSecurityGroupApi().get().deleteSecurityGroupInRegionById(region, groupId);\n         groupCreator.invalidate(new RegionNameAndIngressRules(region, group.getName(), null, false, null));\n         return true;\n      } else {\n         for (Map.Entry<RegionAndName, String> cachedSg : groupCreator.asMap().entrySet()) {\n            if (groupId.equals(cachedSg.getValue())) {\n               groupCreator.invalidate(cachedSg.getKey());\n               break;\n            }\n         }\n         return false;\n      }\n   }\n\n   @Override\n   public SecurityGroup addIpPermission(IpPermission ipPermission, SecurityGroup group) {\n      String region = AWSUtils.getRegionFromLocationOrNull(group.getLocation());\n      String id = group.getProviderId();\n\n      client.getSecurityGroupApi().get().authorizeSecurityGroupIngressInRegion(region, id, ipPermission);\n\n      return getSecurityGroupById(group.getId());\n   }\n\n   @Override\n   public SecurityGroup addIpPermission(IpProtocol protocol, int startPort, int endPort,\n                                        Multimap<String, String> tenantIdGroupNamePairs,\n                                        Iterable<String> ipRanges,\n                                        Iterable<String> groupIds, SecurityGroup group) {\n      String region = AWSUtils.getRegionFromLocationOrNull(group.getLocation());\n      String id = group.getProviderId();\n\n      IpPermission.Builder builder = IpPermission.builder();\n\n      builder.ipProtocol(protocol);\n      builder.fromPort(startPort);\n      builder.toPort(endPort);\n\n      if (!Iterables.isEmpty(ipRanges)) {\n         for (String cidr : ipRanges) {\n            builder.cidrBlock(cidr);\n         }\n      }\n\n      if (!tenantIdGroupNamePairs.isEmpty()) {\n         for (String userId : tenantIdGroupNamePairs.keySet()) {\n            for (String groupString : tenantIdGroupNamePairs.get(userId)) {\n               String[] parts = AWSUtils.parseHandle(groupString);\n               String groupId = parts[1];\n               builder.tenantIdGroupNamePair(userId, groupId);\n            }\n         }\n      }\n\n      client.getSecurityGroupApi().get().authorizeSecurityGroupIngressInRegion(region, id, builder.build());\n\n      return getSecurityGroupById(group.getId());\n   }\n\n   @Override\n   public SecurityGroup removeIpPermission(IpPermission ipPermission, SecurityGroup group) {\n      String region = AWSUtils.getRegionFromLocationOrNull(group.getLocation());\n      String id = group.getProviderId();\n\n      client.getSecurityGroupApi().get().revokeSecurityGroupIngressInRegion(region, id, ipPermission);\n\n      return getSecurityGroupById(group.getId());\n   }\n\n   @Override\n   public SecurityGroup removeIpPermission(IpProtocol protocol, int startPort, int endPort,\n                                           Multimap<String, String> tenantIdGroupNamePairs,\n                                           Iterable<String> ipRanges,\n                                           Iterable<String> groupIds, SecurityGroup group) {\n      String region = AWSUtils.getRegionFromLocationOrNull(group.getLocation());\n      String id = group.getProviderId();\n\n      IpPermission.Builder builder = IpPermission.builder();\n\n      builder.ipProtocol(protocol);\n      builder.fromPort(startPort);\n      builder.toPort(endPort);\n\n      if (!Iterables.isEmpty(ipRanges)) {\n         for (String cidr : ipRanges) {\n            builder.cidrBlock(cidr);\n         }\n      }\n\n      if (!tenantIdGroupNamePairs.isEmpty()) {\n         for (String userId : tenantIdGroupNamePairs.keySet()) {\n            for (String groupString : tenantIdGroupNamePairs.get(userId)) {\n               String[] parts = AWSUtils.parseHandle(groupString);\n               String groupId = parts[1];\n               builder.tenantIdGroupNamePair(userId, groupId);\n            }\n         }\n      }\n\n      client.getSecurityGroupApi().get().revokeSecurityGroupIngressInRegion(region, id, builder.build());\n\n      return getSecurityGroupById(group.getId());\n   }\n\n   @Override\n   public boolean supportsTenantIdGroupNamePairs() {\n      return false;\n   }\n\n   @Override\n   public boolean supportsTenantIdGroupIdPairs() {\n      return true;\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/compute/functions/AWSEC2SecurityGroupToSecurityGroup.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.compute.functions;\n\nimport java.util.Set;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.domain.Location;\nimport org.jclouds.ec2.compute.functions.EC2SecurityGroupToSecurityGroup;\n\nimport com.google.common.base.Supplier;\nimport com.google.inject.Inject;\n\n\n/**\n * A function for transforming an EC2-specific SecurityGroup into a generic\n * SecurityGroup object.\n */\n@Singleton\npublic class AWSEC2SecurityGroupToSecurityGroup extends EC2SecurityGroupToSecurityGroup {\n\n   @Inject\n   public AWSEC2SecurityGroupToSecurityGroup(@Memoized Supplier<Set<? extends Location>> locations) {\n      super(locations);\n   }\n\n   @Override\n   protected String idOrName(org.jclouds.ec2.domain.SecurityGroup group) {\n      return group.getId();\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/compute/functions/AWSRunningInstanceToNodeMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.compute.functions;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.ec2.domain.AWSRunningInstance;\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.HardwareBuilder;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.NodeMetadata.Status;\nimport org.jclouds.compute.domain.NodeMetadataBuilder;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.compute.functions.RunningInstanceToNodeMetadata;\nimport org.jclouds.ec2.domain.InstanceState;\nimport org.jclouds.ec2.domain.RunningInstance;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.LoadingCache;\n\n@Singleton\npublic class AWSRunningInstanceToNodeMetadata extends RunningInstanceToNodeMetadata {\n\n   @Inject\n   protected AWSRunningInstanceToNodeMetadata(Map<InstanceState, Status> instanceToNodeStatus,\n         Map<String, Credentials> credentialStore, Supplier<LoadingCache<RegionAndName, ? extends Image>> imageMap,\n         @Memoized Supplier<Set<? extends Location>> locations, @Memoized Supplier<Set<? extends Hardware>> hardware,\n         GroupNamingConvention.Factory namingConvention) {\n      super(instanceToNodeStatus, credentialStore, imageMap, locations, hardware, namingConvention);\n   }\n\n   @Override\n   protected void addCredentialsForInstance(NodeMetadataBuilder builder, RunningInstance instance) {\n      LoginCredentials creds = LoginCredentials.fromCredentials(credentialStore.get(\"node#\" + instance.getRegion()\n            + \"/\" + instance.getId()));\n      String spotRequestId = AWSRunningInstance.class.cast(instance).getSpotInstanceRequestId();\n      if (creds == null && spotRequestId != null) {\n         creds = LoginCredentials.fromCredentials(credentialStore.get(\"node#\" + instance.getRegion() + \"/\"\n               + spotRequestId));\n         if (creds != null)\n            credentialStore.put(\"node#\" + instance.getRegion() + \"/\" + instance.getId(), creds);\n      }\n      if (creds != null)\n         builder.credentials(creds);\n   }\n   \n   protected Hardware parseHardware(RunningInstance instance) {\n      Hardware in = super.parseHardware(instance);\n      if (in == null)\n         return null;\n      AWSRunningInstance awsInstance = AWSRunningInstance.class.cast(instance);\n      return HardwareBuilder.fromHardware(in).hypervisor(awsInstance.getHypervisor().toString()).build();\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/compute/functions/PresentSpotRequestsAndInstances.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.compute.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Predicates.containsPattern;\nimport static com.google.common.collect.Iterables.any;\nimport static com.google.common.collect.Iterables.toArray;\nimport static com.google.common.collect.Iterables.transform;\nimport static com.google.common.collect.Multimaps.index;\nimport static com.google.common.collect.Multimaps.transformValues;\nimport static org.jclouds.ec2.compute.domain.RegionAndName.nameFunction;\nimport static org.jclouds.ec2.compute.domain.RegionAndName.regionFunction;\n\nimport java.util.Collection;\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.ec2.AWSEC2Api;\nimport org.jclouds.aws.ec2.domain.AWSRunningInstance;\nimport org.jclouds.aws.ec2.domain.SpotInstanceRequest;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.compute.functions.PresentInstances;\nimport org.jclouds.ec2.domain.RunningInstance;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicates;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\nimport com.google.common.collect.Multimap;\nimport com.google.inject.Inject;\n\n/**\n * returns either the instances present in the list, or spot instances, if they ids start with {@code sir-}. Makes a\n * single rest call per aggregate on region.\n */\n@Singleton\npublic class PresentSpotRequestsAndInstances extends PresentInstances {\n\n   private final AWSEC2Api client;\n   private final Function<SpotInstanceRequest, AWSRunningInstance> spotConverter;\n\n   @Inject\n   public PresentSpotRequestsAndInstances(AWSEC2Api client, Function<SpotInstanceRequest, AWSRunningInstance> spotConverter) {\n      super(client);\n      this.client = checkNotNull(client, \"client\");\n      this.spotConverter = checkNotNull(spotConverter, \"spotConverter\");\n   }\n\n   @Override\n   public Set<RunningInstance> apply(Set<RegionAndName> regionAndIds) {\n      if (checkNotNull(regionAndIds, \"regionAndIds\").isEmpty())\n         return ImmutableSet.of();\n      if (any(regionAndIds, Predicates.compose(containsPattern(\"sir-\"), nameFunction())))\n         return getSpots(regionAndIds);\n      return super.apply(regionAndIds);\n   }\n\n   protected Set<RunningInstance> getSpots(Set<RegionAndName> regionAndIds) {\n      Builder<RunningInstance> builder = ImmutableSet.<RunningInstance> builder();\n      Multimap<String, String> regionToSpotIds = transformValues(index(regionAndIds, regionFunction()), nameFunction());\n      for (Map.Entry<String, Collection<String>> entry : regionToSpotIds.asMap().entrySet()) {\n         String region = entry.getKey();\n         Collection<String> spotIds = entry.getValue();\n         logger.trace(\"looking for spots %s in region %s\", spotIds, region);\n         builder.addAll(transform(\n                                  client.getSpotInstanceApi().get().describeSpotInstanceRequestsInRegion(region,\n                     toArray(spotIds, String.class)), spotConverter));\n      }\n      return builder.build();\n   }\n\n   @Override\n   public String toString() {\n      return \"presentSpotRequestsAndInstances()\";\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/compute/internal/AWSEC2ComputeServiceContextImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.compute.internal;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Context;\nimport org.jclouds.aws.ec2.compute.AWSEC2ComputeService;\nimport org.jclouds.aws.ec2.compute.AWSEC2ComputeServiceContext;\nimport org.jclouds.compute.Utils;\nimport org.jclouds.ec2.compute.internal.EC2ComputeServiceContextImpl;\nimport org.jclouds.location.Provider;\n\nimport com.google.common.reflect.TypeToken;\n\n@Singleton\npublic class AWSEC2ComputeServiceContextImpl extends EC2ComputeServiceContextImpl implements\n         AWSEC2ComputeServiceContext {\n   @Inject\n   public AWSEC2ComputeServiceContextImpl(@Provider Context backend,\n            @Provider TypeToken<? extends Context> backendType, AWSEC2ComputeService computeService, Utils utils) {\n      super(backend, backendType, computeService, utils);\n   }\n\n   @Override\n   public AWSEC2ComputeService getComputeService() {\n      return AWSEC2ComputeService.class.cast(super.getComputeService());\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/compute/loaders/AWSEC2CreateSecurityGroupIfNeeded.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.compute.loaders;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.compute.util.ComputeServiceUtils.getPortRangesFromList;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.ec2.AWSEC2Api;\nimport org.jclouds.aws.ec2.features.AWSSecurityGroupApi;\nimport org.jclouds.aws.ec2.options.CreateSecurityGroupOptions;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.compute.domain.RegionNameAndIngressRules;\nimport org.jclouds.ec2.domain.SecurityGroup;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.net.domain.IpPermission;\nimport org.jclouds.net.domain.IpProtocol;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\n\n@Singleton\npublic class AWSEC2CreateSecurityGroupIfNeeded extends CacheLoader<RegionAndName, String> {\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n   protected final AWSSecurityGroupApi securityApi;\n   protected final Predicate<RegionAndName> securityGroupEventualConsistencyDelay;\n   protected final Function<String, String> groupNameToId;\n   @Inject\n   public AWSEC2CreateSecurityGroupIfNeeded(AWSEC2Api ec2Api,\n                                            @Named(\"SECGROUP_NAME_TO_ID\") Function<String, String> groupNameToId,\n                                            @Named(\"SECURITY\") Predicate<RegionAndName> securityGroupEventualConsistencyDelay) {\n      this(checkNotNull(ec2Api, \"ec2Api\").getSecurityGroupApi().get(), groupNameToId, securityGroupEventualConsistencyDelay);\n   }\n\n   public AWSEC2CreateSecurityGroupIfNeeded(AWSSecurityGroupApi securityApi,\n                                            @Named(\"SECGROUP_NAME_TO_ID\") Function<String, String> groupNameToId,\n                                            @Named(\"SECURITY\") Predicate<RegionAndName> securityGroupEventualConsistencyDelay) {\n      this.securityApi = checkNotNull(securityApi, \"securityApi\");\n      this.groupNameToId = checkNotNull(groupNameToId, \"groupNameToId\");\n      this.securityGroupEventualConsistencyDelay = checkNotNull(securityGroupEventualConsistencyDelay,\n            \"securityGroupEventualConsistencyDelay\");\n   }\n\n   @Override\n   public String load(RegionAndName from) {\n      RegionNameAndIngressRules realFrom = RegionNameAndIngressRules.class.cast(from);\n      return createSecurityGroupInRegion(from.getRegion(), from.getName(), realFrom.getVpcId(), realFrom.getPorts());\n   }\n\n   private String createSecurityGroupInRegion(String region, final String name, String vpcId, int... ports) {\n      checkNotNull(region, \"region\");\n      checkNotNull(name, \"name\");\n      logger.debug(\">> creating securityGroup region(%s) name(%s)\", region, name);\n\n      try {\n         CreateSecurityGroupOptions options = new CreateSecurityGroupOptions();\n         if (vpcId != null) {\n            options.vpcId(vpcId);\n         }\n         String id = securityApi.createSecurityGroupInRegionAndReturnId(region, name, name, options);\n         boolean created = securityGroupEventualConsistencyDelay.apply(new RegionAndName(region, name));\n         if (!created)\n            throw new RuntimeException(String.format(\"security group %s/%s is not available after creating\", region,\n                  name));\n         logger.debug(\"<< created securityGroup(%s)\", name);\n\n         ImmutableSet.Builder<IpPermission> permissions = ImmutableSet.builder();\n\n         if (ports.length > 0) {\n            for (Map.Entry<Integer, Integer> range : getPortRangesFromList(ports).entrySet()) {\n               permissions.add(IpPermission.builder()\n                               .fromPort(range.getKey())\n                               .toPort(range.getValue())\n                               .ipProtocol(IpProtocol.TCP)\n                               .cidrBlock(\"0.0.0.0/0\")\n                               .build());\n            }\n\n            // Use filter (as per `SecurityGroupPresent`, in securityGroupEventualConsistencyDelay)\n            Set<SecurityGroup> securityGroups = securityApi.describeSecurityGroupsInRegionById(region, id);\n            if (securityGroups.isEmpty()) {\n               throw new IllegalStateException(String.format(\"security group %s/%s not found after creating\", region, name));\n            } else if (securityGroups.size() > 1) {\n               throw new IllegalStateException(String.format(\"multiple security groups matching %s/%s found after creating: %s\", \n                     region, name, securityGroups));\n            }\n            SecurityGroup securityGroup = Iterables.getOnlyElement(securityGroups);\n            String myOwnerId = securityGroup.getOwnerId();\n            permissions.add(IpPermission.builder()\n                            .fromPort(0)\n                            .toPort(65535)\n                            .ipProtocol(IpProtocol.TCP)\n                            .tenantIdGroupNamePair(myOwnerId, id)\n                            .build());\n            permissions.add(IpPermission.builder()\n                            .fromPort(0)\n                            .toPort(65535)\n                            .ipProtocol(IpProtocol.UDP)\n                            .tenantIdGroupNamePair(myOwnerId, id)\n                            .build());\n         }\n\n         Set<IpPermission> perms = permissions.build();\n\n         if (!perms.isEmpty()) {\n            logger.debug(\">> authorizing securityGroup region(%s) name(%s) IpPermissions(%s)\", region, name, perms);\n            securityApi.authorizeSecurityGroupIngressInRegion(region, id, perms);\n            logger.debug(\"<< authorized securityGroup(%s)\", name);\n         }\n         return id;\n      } catch (IllegalStateException e) {\n         logger.debug(\"<< reused securityGroup(%s)\", name);\n         return groupNameToId.apply(new RegionAndName(region, name).slashEncode());\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/compute/strategy/AWSEC2CreateNodesInGroupThenAddToSet.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.compute.strategy;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.transform;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_RUNNING;\nimport static org.jclouds.ec2.reference.EC2Constants.PROPERTY_EC2_GENERATE_INSTANCE_NAMES;\n\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.ec2.AWSEC2Api;\nimport org.jclouds.aws.ec2.compute.AWSEC2TemplateOptions;\nimport org.jclouds.aws.ec2.compute.functions.PresentSpotRequestsAndInstances;\nimport org.jclouds.aws.ec2.domain.LaunchSpecification;\nimport org.jclouds.aws.ec2.functions.SpotInstanceRequestToAWSRunningInstance;\nimport org.jclouds.aws.ec2.options.AWSRunInstancesOptions;\nimport org.jclouds.aws.ec2.options.RequestSpotInstancesOptions;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.compute.util.ComputeUtils;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.compute.strategy.EC2CreateNodesInGroupThenAddToSet;\nimport org.jclouds.ec2.domain.RunningInstance;\nimport org.jclouds.ec2.options.RunInstancesOptions;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableSet;\n\n@Singleton\npublic class AWSEC2CreateNodesInGroupThenAddToSet extends EC2CreateNodesInGroupThenAddToSet {\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   private Logger logger = Logger.NULL;\n\n   @VisibleForTesting\n   private final AWSEC2Api client;\n   private final SpotInstanceRequestToAWSRunningInstance spotConverter;\n\n   @Inject\n   protected AWSEC2CreateNodesInGroupThenAddToSet(\n         AWSEC2Api client,\n         @Named(\"ELASTICIP\") LoadingCache<RegionAndName, String> elasticIpCache,\n         @Named(TIMEOUT_NODE_RUNNING) Predicate<AtomicReference<NodeMetadata>> nodeRunning,\n         @Named(PROPERTY_EC2_GENERATE_INSTANCE_NAMES) boolean generateInstanceNames,\n         CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions createKeyPairAndSecurityGroupsAsNeededAndReturncustomize,\n         PresentSpotRequestsAndInstances instancePresent,\n         Function<RunningInstance, NodeMetadata> runningInstanceToNodeMetadata,\n         LoadingCache<RunningInstance, Optional<LoginCredentials>> instanceToCredentials,\n         Map<String, Credentials> credentialStore, ComputeUtils utils,\n         SpotInstanceRequestToAWSRunningInstance spotConverter) {\n      super(client, elasticIpCache, nodeRunning, createKeyPairAndSecurityGroupsAsNeededAndReturncustomize,\n            instancePresent, runningInstanceToNodeMetadata, instanceToCredentials, credentialStore, utils);\n      this.client = checkNotNull(client, \"client\");\n      this.spotConverter = checkNotNull(spotConverter, \"spotConverter\");\n   }\n\n   @Override\n   protected Set<RunningInstance> createNodesInRegionAndZone(String region, String zone, String group,\n            int count, Template template, RunInstancesOptions instanceOptions) {\n      Float spotPrice = getSpotPriceOrNull(template.getOptions());\n      if (spotPrice != null) {\n         AWSEC2TemplateOptions awsOptions = AWSEC2TemplateOptions.class.cast(template.getOptions());\n         LaunchSpecification spec = AWSRunInstancesOptions.class.cast(instanceOptions).getLaunchSpecificationBuilder()\n               .imageId(template.getImage().getProviderId()).availabilityZone(zone).subnetId(awsOptions.getSubnetId())\n               .iamInstanceProfileArn(awsOptions.getIAMInstanceProfileArn())\n               .iamInstanceProfileName(awsOptions.getIAMInstanceProfileName()).build();\n         RequestSpotInstancesOptions options = awsOptions.getSpotOptions();\n         if (logger.isDebugEnabled())\n            logger.debug(\">> requesting %d spot instances region(%s) price(%f) spec(%s) options(%s)\", count, region,\n                     spotPrice, spec, options);\n         return ImmutableSet.<RunningInstance> copyOf(transform(client.getSpotInstanceApi().get()\n               .requestSpotInstancesInRegion(region, spotPrice, count, spec, options), spotConverter));\n      }\n      return super.createNodesInRegionAndZone(region, zone, group, count, template, instanceOptions);\n   }\n   \n   private Float getSpotPriceOrNull(TemplateOptions options) {\n      return options instanceof AWSEC2TemplateOptions ? AWSEC2TemplateOptions.class.cast(options).getSpotPrice() : null;\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/compute/strategy/AWSEC2DestroyNodeStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.compute.strategy;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.getOnlyElement;\n\nimport java.util.Map;\nimport java.util.NoSuchElementException;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.ec2.AWSEC2Api;\nimport org.jclouds.compute.strategy.GetNodeMetadataStrategy;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.compute.strategy.EC2DestroyNodeStrategy;\n\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.Iterables;\n\n@Singleton\npublic class AWSEC2DestroyNodeStrategy extends EC2DestroyNodeStrategy {\n\n   protected final AWSEC2Api client;\n   protected final Map<String, Credentials> credentialStore;\n\n   @Inject\n   protected AWSEC2DestroyNodeStrategy(AWSEC2Api client, GetNodeMetadataStrategy getNode,\n            @Named(\"ELASTICIP\") LoadingCache<RegionAndName, String> elasticIpCache,\n            Map<String, Credentials> credentialStore) {\n      super(client, getNode, elasticIpCache);\n      this.client = checkNotNull(client, \"client\");\n      this.credentialStore = checkNotNull(credentialStore, \"credentialStore\");\n   }\n\n   @Override\n   protected void destroyInstanceInRegion(String id, String region) {\n      String spotId = id;\n      if (id.indexOf(\"sir-\") != 0) {\n         try {\n            spotId = getOnlyElement(\n                                    Iterables.concat(client.getInstanceApi().get().describeInstancesInRegion(region, id)))\n                     .getSpotInstanceRequestId();\n            credentialStore.remove(\"node#\" + region + \"/\" + spotId);\n         } catch (NoSuchElementException e) {\n         }\n         super.destroyInstanceInRegion(id, region);\n      } else {\n         client.getSpotInstanceApi().get().cancelSpotInstanceRequestsInRegion(region, spotId);\n         credentialStore.remove(\"node#\" + region + \"/\" + id);\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/compute/strategy/AWSEC2GetNodeMetadataStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.compute.strategy;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.getOnlyElement;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.ec2.AWSEC2Api;\nimport org.jclouds.aws.ec2.domain.SpotInstanceRequest;\nimport org.jclouds.aws.ec2.functions.SpotInstanceRequestToAWSRunningInstance;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.ec2.compute.strategy.EC2GetNodeMetadataStrategy;\nimport org.jclouds.ec2.domain.RunningInstance;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class AWSEC2GetNodeMetadataStrategy extends EC2GetNodeMetadataStrategy {\n\n   private final AWSEC2Api client;\n   private final SpotInstanceRequestToAWSRunningInstance spotConverter;\n\n   @Inject\n   protected AWSEC2GetNodeMetadataStrategy(AWSEC2Api client,\n            Function<RunningInstance, NodeMetadata> runningInstanceToNodeMetadata,\n            SpotInstanceRequestToAWSRunningInstance spotConverter) {\n      super(client, runningInstanceToNodeMetadata);\n      this.client = checkNotNull(client, \"client\");\n      this.spotConverter = checkNotNull(spotConverter, \"spotConverter\");\n   }\n\n   @Override\n   public RunningInstance getRunningInstanceInRegion(String region, String id) {\n      if (id.indexOf(\"sir-\") != 0)\n         return super.getRunningInstanceInRegion(region, id);\n      SpotInstanceRequest spot = getOnlyElement(client.getSpotInstanceApi().get().describeSpotInstanceRequestsInRegion(\n               region, id));\n      if (spot.getState() == SpotInstanceRequest.State.ACTIVE)\n         return super.getRunningInstanceInRegion(region, spot.getInstanceId());\n      else\n         return spotConverter.apply(spot);\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/compute/strategy/AWSEC2IOExceptionRetryHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.compute.strategy;\n\nimport java.io.IOException;\n\nimport org.jclouds.aws.reference.FormParameters;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.handlers.BackoffLimitedRetryHandler;\nimport org.jclouds.io.Payload;\n\npublic class AWSEC2IOExceptionRetryHandler extends BackoffLimitedRetryHandler {\n\n   private static final String DESCRIBE_ACTION = FormParameters.ACTION + \"=Describe\";\n\n   @Override\n   public boolean shouldRetryRequest(HttpCommand command, IOException error) {\n      HttpRequest request = command.getCurrentRequest();\n      if (\"POST\".equals(request.getMethod())) {\n         Payload payload = request.getPayload();\n         if (!payload.getRawContent().toString().contains(DESCRIBE_ACTION)){\n            logger.error(\"Command not considered safe to retry because request method is POST and action may not be idempotent: %1$s\",\n               command);\n            return false;\n         }\n      }\n      return super.shouldRetryRequest(command, error);\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/compute/strategy/AWSEC2ListNodesStrategy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.compute.strategy;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Predicates.notNull;\nimport static com.google.common.collect.Iterables.concat;\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.toArray;\nimport static com.google.common.collect.Iterables.transform;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Constants;\nimport org.jclouds.aws.ec2.AWSEC2Api;\nimport org.jclouds.aws.ec2.domain.AWSRunningInstance;\nimport org.jclouds.aws.ec2.domain.SpotInstanceRequest;\nimport org.jclouds.aws.ec2.functions.SpotInstanceRequestToAWSRunningInstance;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.ec2.compute.strategy.EC2ListNodesStrategy;\nimport org.jclouds.ec2.domain.RunningInstance;\nimport org.jclouds.location.Region;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.Multimap;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.inject.Inject;\n\n@Singleton\npublic class AWSEC2ListNodesStrategy extends EC2ListNodesStrategy {\n\n   protected final AWSEC2Api client;\n   protected final SpotInstanceRequestToAWSRunningInstance spotConverter;\n\n   @Inject\n   protected AWSEC2ListNodesStrategy(AWSEC2Api client, @Region Supplier<Set<String>> regions,\n            Function<RunningInstance, NodeMetadata> runningInstanceToNodeMetadata,\n            @Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor,\n            SpotInstanceRequestToAWSRunningInstance spotConverter) {\n      super(client, regions, runningInstanceToNodeMetadata, userExecutor);\n      this.client = checkNotNull(client, \"client\");\n      this.spotConverter = checkNotNull(spotConverter, \"spotConverter\");\n   }\n\n   @Override\n   protected Iterable<? extends RunningInstance> pollRunningInstances() {\n      Iterable<? extends AWSRunningInstance> spots = filter(transform(concat(transform(regions.get(),\n                                                                                       allSpotInstancesInRegion())),\n                                                                      spotConverter), notNull());\n\n      return concat(super.pollRunningInstances(), spots);\n   }\n\n   @Override\n   protected Iterable<? extends RunningInstance> pollRunningInstancesByRegionsAndIds(final Multimap<String, String> idsByRegions) {\n      Iterable<? extends AWSRunningInstance> spots = filter(transform(concat(transform(idsByRegions.keySet(),\n                                                                                       spotInstancesByIdInRegion(idsByRegions))),\n\n                                                                      spotConverter), notNull());\n      Iterable<? extends RunningInstance> superInsts = super.pollRunningInstancesByRegionsAndIds(idsByRegions);\n      return concat(superInsts, spots);\n   }\n\n   protected Function<String, Set<SpotInstanceRequest>> allSpotInstancesInRegion() {\n      return new Function<String, Set<SpotInstanceRequest>>() {\n\n         @Override\n         public Set<SpotInstanceRequest> apply(String from) {\n            return client.getSpotInstanceApi().get().describeSpotInstanceRequestsInRegion(from);\n         }\n      };\n   }\n\n   protected Function<String, Set<SpotInstanceRequest>> spotInstancesByIdInRegion(final Multimap<String, String> idsByRegions) {\n      return new Function<String, Set<SpotInstanceRequest>>() {\n\n         @Override\n         public Set<SpotInstanceRequest> apply(String from) {\n            return client.getSpotInstanceApi().get()\n               .describeSpotInstanceRequestsInRegion(from, toArray(idsByRegions.get(from), String.class));\n         }\n      };\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/compute/strategy/AWSEC2ReviseParsedImage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.compute.strategy;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\nimport java.util.NoSuchElementException;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.domain.ImageBuilder;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.util.ComputeServiceUtils;\nimport org.jclouds.ec2.compute.strategy.ReviseParsedImage;\nimport org.jclouds.logging.Logger;\n\n@Singleton\npublic class AWSEC2ReviseParsedImage implements ReviseParsedImage {\n\n   // 137112412989/amzn-ami-0.9.7-beta.i386-ebs\n   // 137112412989/amzn-ami-0.9.7-beta.x86_64-ebs\n   // amzn-ami-us-east-1/amzn-ami-0.9.7-beta.x86_64.manifest.xml\n   // amzn-ami-us-east-1/amzn-ami-0.9.7-beta.i386.manifest.xml\n   public static final Pattern AMZN_PATTERN = Pattern\n            .compile(\".*/(amzn-hvm-|amzn-)?ami-(.*)\\\\.(i386|x86_64)(-ebs|\\\\.manifest.xml)?\");\n\n   // amazon/EC2 CentOS 5.4 HVM AMI\n   public static final Pattern AMAZON_PATTERN = Pattern.compile(\"amazon/EC2 ([^ ]+) ([^ ]+).*\");\n\n   // amazon/Windows_Server-2008-R2_SP1-English-64Bit-Base-2012.03.13\n   //        1111111        22222222222                    3333333333\n   public static final Pattern AMAZON_WINDOWS_PATTERN = Pattern.compile(\".*/(Windows)_Server-([^-]*-[^-]*)-.*-([^-]*)(\\\\.manifest.xml)?\");\n\n   public static final Pattern CENTOS_MARKETPLACE_PATTERN = Pattern.compile(\".*/(CentOS) Linux ([^ ]*) (.*)(\\\\.manifest.xml)?\");\n\n   public static final Pattern CANONICAL_PATTERN = Pattern.compile(\".*/([^-]*)-([^-]*)-.*-(.*)(\\\\.manifest.xml)?\");\n\n   // ex rightscale-us-east/CentOS_5.4_x64_v4.4.10.manifest.xml\n   public static final Pattern RIGHTSCALE_PATTERN = Pattern\n            .compile(\"[^/]*/([^_]*)_([^_]*)_[^vV]*[vV](.*)(\\\\.manifest.xml)?\");\n\n   // ex 411009282317/RightImage_Ubuntu_9.10_x64_v4.5.3_EBS_Alpha\n   // 411009282317/RightImage_Windows_2008_x64_v5.5.5\n   public static final Pattern RIGHTIMAGE_PATTERN = Pattern\n            .compile(\"[^/]*/RightImage[_ ]([^_]*)_([^_]*)_[^vV]*[vV](.*)(\\\\.manifest.xml)?\");\n   private final Map<OsFamily, Map<String, String>> osVersionMap;\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   @Inject\n   public AWSEC2ReviseParsedImage(Map<OsFamily, Map<String, String>> osVersionMap) {\n      this.osVersionMap = checkNotNull(osVersionMap, \"osVersionMap\");\n   }\n\n   @Override\n   public void reviseParsedImage(org.jclouds.ec2.domain.Image from, ImageBuilder builder, OsFamily family,\n            OperatingSystem.Builder osBuilder) {\n      try {\n         Matcher matcher = getMatcherAndFind(from.getImageLocation());\n         if (matcher.pattern() == AMZN_PATTERN) {\n            osBuilder.family(OsFamily.AMZN_LINUX);\n            osBuilder.version(matcher.group(2));\n            builder.version(matcher.group(2));\n         } else if (matcher.pattern() == AMAZON_PATTERN) {\n            family = OsFamily.fromValue(matcher.group(1));\n            osBuilder.family(family);\n            osBuilder.version(ComputeServiceUtils.parseVersionOrReturnEmptyString(family, matcher.group(2),\n                     osVersionMap));\n         } else {\n            family = OsFamily.fromValue(matcher.group(1));\n            osBuilder.family(family);\n            osBuilder.version(ComputeServiceUtils.parseVersionOrReturnEmptyString(family, matcher.group(2),\n                     osVersionMap));\n            builder.version(matcher.group(3).replace(\".manifest.xml\", \"\"));\n         }\n      } catch (IllegalArgumentException e) {\n         logger.debug(\"<< didn't match os(%s)\", from.getImageLocation());\n      } catch (NoSuchElementException e) {\n         logger.trace(\"<< didn't match at all(%s)\", from.getImageLocation());\n      }\n   }\n\n   /**\n    * \n    * @throws NoSuchElementException\n    *            if no configured matcher matches the manifest.\n    */\n   private Matcher getMatcherAndFind(String manifest) {\n      for (Pattern pattern : new Pattern[] { AMZN_PATTERN, AMAZON_PATTERN, AMAZON_WINDOWS_PATTERN,\n              CENTOS_MARKETPLACE_PATTERN, CANONICAL_PATTERN, RIGHTIMAGE_PATTERN, RIGHTSCALE_PATTERN }) {\n         Matcher matcher = pattern.matcher(manifest);\n         if (matcher.find())\n            return matcher;\n      }\n      throw new NoSuchElementException(manifest);\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/compute/strategy/CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.compute.strategy;\n\nimport static com.google.common.base.Predicates.and;\nimport static com.google.common.base.Predicates.or;\n\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentMap;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Provider;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.ec2.AWSEC2Api;\nimport org.jclouds.aws.ec2.compute.AWSEC2TemplateOptions;\nimport org.jclouds.aws.ec2.domain.RegionNameAndPublicKeyMaterial;\nimport org.jclouds.aws.ec2.functions.CreatePlacementGroupIfNeeded;\nimport org.jclouds.aws.ec2.options.AWSRunInstancesOptions;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.compute.options.EC2TemplateOptions;\nimport org.jclouds.ec2.compute.strategy.CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions;\nimport org.jclouds.ec2.domain.KeyPair;\nimport org.jclouds.ec2.domain.Subnet;\nimport org.jclouds.ec2.options.RunInstancesOptions;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Predicates;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.Iterables;\n\n@Singleton\npublic class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions extends\n      CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions {\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n   @VisibleForTesting\n   final LoadingCache<RegionAndName, String> placementGroupMap;\n   @VisibleForTesting\n   final CreatePlacementGroupIfNeeded createPlacementGroupIfNeeded;\n   @VisibleForTesting\n   final Function<RegionNameAndPublicKeyMaterial, KeyPair> importExistingKeyPair;\n   private final AWSEC2Api awsEC2Api;\n\n   @Inject\n   public CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions(\n         Function<RegionAndName, KeyPair> makeKeyPair, ConcurrentMap<RegionAndName, KeyPair> credentialsMap,\n         @Named(\"SECURITY\") LoadingCache<RegionAndName, String> securityGroupMap,\n         Provider<RunInstancesOptions> optionsProvider,\n         @Named(\"PLACEMENT\") LoadingCache<RegionAndName, String> placementGroupMap,\n         CreatePlacementGroupIfNeeded createPlacementGroupIfNeeded,\n         Function<RegionNameAndPublicKeyMaterial, KeyPair> importExistingKeyPair,\n         GroupNamingConvention.Factory namingConvention,\n         AWSEC2Api awsEC2Api) {\n      super(makeKeyPair, credentialsMap, securityGroupMap, optionsProvider, namingConvention);\n      this.placementGroupMap = placementGroupMap;\n      this.createPlacementGroupIfNeeded = createPlacementGroupIfNeeded;\n      this.importExistingKeyPair = importExistingKeyPair;\n      this.awsEC2Api = awsEC2Api;\n   }\n\n   public AWSRunInstancesOptions execute(String region, String group, Template template) {\n      AWSRunInstancesOptions instanceOptions = AWSRunInstancesOptions.class\n            .cast(super.execute(region, group, template));\n\n      String placementGroupName = template.getHardware().getId().startsWith(\"cc\") ? createNewPlacementGroupUnlessUserSpecifiedOtherwise(\n            region, group, template.getOptions()) : null;\n\n      if (placementGroupName != null)\n         instanceOptions.inPlacementGroup(placementGroupName);\n\n      AWSEC2TemplateOptions awsTemplateOptions = AWSEC2TemplateOptions.class.cast(template.getOptions());\n      if (awsTemplateOptions.isMonitoringEnabled())\n         instanceOptions.enableMonitoring();\n      if (awsTemplateOptions.getIAMInstanceProfileArn() != null)\n         instanceOptions.withIAMInstanceProfileArn(awsTemplateOptions.getIAMInstanceProfileArn());\n      if (awsTemplateOptions.getIAMInstanceProfileName() != null)\n         instanceOptions.withIAMInstanceProfileName(awsTemplateOptions.getIAMInstanceProfileName());\n      if (awsTemplateOptions.getPrivateIpAddress() != null)\n         instanceOptions.withPrivateIpAddress(awsTemplateOptions.getPrivateIpAddress());\n      if (awsTemplateOptions.getTenancy() != null)\n         instanceOptions.withTenancy(awsTemplateOptions.getTenancy());\n      if (awsTemplateOptions.getDedicatedHostId() != null)\n         instanceOptions.withDedicatedHostId(awsTemplateOptions.getDedicatedHostId());\n\n      return instanceOptions;\n   }\n\n   @VisibleForTesting\n   String createNewPlacementGroupUnlessUserSpecifiedOtherwise(String region, String group, TemplateOptions options) {\n      String placementGroupName = null;\n      boolean shouldAutomaticallyCreatePlacementGroup = true;\n      if (options instanceof EC2TemplateOptions) {\n         placementGroupName = AWSEC2TemplateOptions.class.cast(options).getPlacementGroup();\n         if (placementGroupName == null)\n            shouldAutomaticallyCreatePlacementGroup = AWSEC2TemplateOptions.class.cast(options)\n                  .shouldAutomaticallyCreatePlacementGroup();\n      }\n      if (placementGroupName == null && shouldAutomaticallyCreatePlacementGroup) {\n         // placementGroupName must be unique within an account per\n         // http://docs.amazonwebservices.com/AWSEC2/latest/UserGuide/index.html?using_cluster_computing.html\n         placementGroupName = String.format(\"jclouds#%s#%s\", group, region);\n         RegionAndName regionAndName = new RegionAndName(region, placementGroupName);\n         // make this entry as needed\n         placementGroupMap.getUnchecked(regionAndName);\n      }\n      return placementGroupName;\n   }\n\n   @Override\n   public String createNewKeyPairUnlessUserSpecifiedOtherwise(String region, String group, TemplateOptions options) {\n      RegionAndName key = new RegionAndName(region, group);\n      KeyPair pair;\n      if (and(hasPublicKeyMaterial, or(doesntNeedSshAfterImportingPublicKey, hasLoginCredential)).apply(options)) {\n         pair = importExistingKeyPair.apply(new RegionNameAndPublicKeyMaterial(region, group, options.getPublicKey()));\n         options.dontAuthorizePublicKey();\n         if (hasLoginCredential.apply(options))\n            pair = pair.toBuilder().keyMaterial(options.getLoginPrivateKey()).build();\n         credentialsMap.put(key, pair);\n      } else {\n         if (hasPublicKeyMaterial.apply(options)) {\n            logger.warn(\"to avoid creating temporary keys in aws-ec2, use templateOption overrideLoginCredentialWith(id_rsa)\");\n         }\n         return super.createNewKeyPairUnlessUserSpecifiedOtherwise(region, group, options);\n      }\n      return pair.getKeyName();\n   }\n\n   public static final Predicate<TemplateOptions> hasPublicKeyMaterial = new Predicate<TemplateOptions>() {\n\n      @Override\n      public boolean apply(TemplateOptions options) {\n         return options.getPublicKey() != null;\n      }\n\n   };\n\n   public static final Predicate<TemplateOptions> doesntNeedSshAfterImportingPublicKey = new Predicate<TemplateOptions>() {\n\n      @Override\n      public boolean apply(TemplateOptions options) {\n         return options.getRunScript() == null && options.getPrivateKey() == null;\n      }\n\n   };\n\n   public static final Predicate<TemplateOptions> hasLoginCredential = new Predicate<TemplateOptions>() {\n\n      @Override\n      public boolean apply(TemplateOptions options) {\n         return options.getLoginPrivateKey() != null;\n      }\n\n   };\n\n   @Override\n   protected boolean userSpecifiedTheirOwnGroups(TemplateOptions options) {\n      return (options instanceof AWSEC2TemplateOptions\n            && !AWSEC2TemplateOptions.class.cast(options).getGroupIds().isEmpty())\n            || super.userSpecifiedTheirOwnGroups(options);\n   }\n\n   @Override\n   protected void addSecurityGroups(String region, String group, Template template, RunInstancesOptions instanceOptions) {\n      AWSEC2TemplateOptions awsTemplateOptions = AWSEC2TemplateOptions.class.cast(template.getOptions());\n      AWSRunInstancesOptions awsInstanceOptions = AWSRunInstancesOptions.class.cast(instanceOptions);\n      if (!awsTemplateOptions.getGroupIds().isEmpty())\n         awsInstanceOptions.withSecurityGroupIds(awsTemplateOptions.getGroupIds());\n      String subnetId = awsTemplateOptions.getSubnetId();\n      if (subnetId != null) {\n         Set<String> groups = getSecurityGroupsForTagAndOptions(region, group, vpcIdForSubnet(region, subnetId), template.getOptions());\n         awsInstanceOptions.withSubnetId(subnetId);\n         awsInstanceOptions.withSecurityGroupIds(groups);\n      } else {\n         Set<String> groups = getSecurityGroupsForTagAndOptions(region, group, null, template.getOptions());\n         awsInstanceOptions.withSecurityGroupIds(groups);\n      }\n   }\n   \n   @VisibleForTesting\n   String vpcIdForSubnet(String region, String subnetId) {\n      Optional<Subnet> subnet = Iterables.tryFind(awsEC2Api.getAWSSubnetApi().get().describeSubnetsInRegion(region, subnetId), Predicates.<Subnet>notNull());\n      if (!subnet.isPresent()) {\n         throw new IllegalArgumentException(\"Subnet \" + subnetId + \" not found\");\n      }\n      return subnet.get().getVpcId();\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/compute/suppliers/AWSEC2HardwareSupplier.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.compute.suppliers;\n\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.a1_medium;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.a1_large;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.a1_xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.a1_2xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.a1_4xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.c1_medium;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.c1_xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.c3_2xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.c3_4xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.c3_8xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.c3_large;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.c3_xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.c4_large;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.c4_2xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.c4_4xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.c4_8xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.c4_xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.c5_large;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.c5_xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.c5_2xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.c5_4xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.c5_9xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.c5_18xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.c5d_large;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.c5d_xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.c5d_2xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.c5d_4xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.c5d_9xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.c5d_18xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.cc1_4xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.cc2_8xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.cg1_4xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.d2_2xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.d2_4xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.d2_8xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.d2_xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.g2_2xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.hi1_4xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.hs1_8xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.i2_2xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.i2_4xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.i2_8xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.i2_xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.m1_large;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.m1_medium;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.m1_small;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.m1_xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.m2_2xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.m2_4xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.m2_xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.m3_2xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.m3_large;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.m3_medium;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.m3_xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.m4_10xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.m4_16xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.m4_2xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.m4_4xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.m4_large;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.m4_xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.m5_large;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.m5_xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.m5_2xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.m5_4xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.m5_12xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.m5_24xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.m5d_large;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.m5d_xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.m5d_2xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.m5d_4xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.m5d_12xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.m5d_24xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.r3_large;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.r3_xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.r3_2xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.r3_4xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.r3_8xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.r4_16xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.r4_2xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.r4_4xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.r4_8xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.r4_large;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.r4_xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.t1_micro;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.t2_large;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.t2_medium;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.t2_micro;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.t2_nano;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.t2_small;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.t2_xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.t2_2xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.t3_nano;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.t3_micro;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.t3_small;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.t3_medium;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.t3_large;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.t3_xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.t3_2xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.x1_16xlarge;\nimport static org.jclouds.ec2.compute.domain.EC2HardwareBuilder.x1_32xlarge;\n\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.ec2.compute.config.ClusterCompute;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.ec2.compute.suppliers.EC2HardwareSupplier;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\n\n@Singleton\npublic class AWSEC2HardwareSupplier extends EC2HardwareSupplier {\n\n   private final Set<String> ccAmis;\n\n   @Inject\n   public AWSEC2HardwareSupplier(@ClusterCompute Set<String> ccAmis) {\n      this.ccAmis = ccAmis;\n   }\n\n   @Override\n   public Set<? extends Hardware> get() {\n      Builder<Hardware> sizes = ImmutableSet.builder();\n      sizes.add(cc1_4xlarge().supportsImageIds(ccAmis).build());\n      sizes.add(cg1_4xlarge().supportsImageIds(ccAmis).build());\n      sizes.add(cc2_8xlarge().supportsImageIds(ccAmis).build());\n      sizes.add(hi1_4xlarge().supportsImageIds(ccAmis).build());\n      sizes.add(hs1_8xlarge().supportsImageIds(ccAmis).build());\n      sizes.add(g2_2xlarge().supportsImageIds(ccAmis).build());\n\n      sizes.add(t1_micro().build());\n      sizes.add(t2_nano().build());\n      sizes.add(t2_micro().build());\n      sizes.add(t2_small().build());\n      sizes.add(t2_medium().build());\n      sizes.add(t2_large().build());\n      sizes.add(t2_xlarge().build());\n      sizes.add(t2_2xlarge().build());\n      sizes.add(t3_nano().build());\n      sizes.add(t3_micro().build());\n      sizes.add(t3_small().build());\n      sizes.add(t3_medium().build());\n      sizes.add(t3_large().build());\n      sizes.add(t3_xlarge().build());\n      sizes.add(t3_2xlarge().build());\n      sizes.add(c1_medium().build());\n      sizes.add(c1_xlarge().build());\n      sizes.add(c3_large().build());\n      sizes.add(c3_xlarge().build());\n      sizes.add(c3_2xlarge().build());\n      sizes.add(c3_4xlarge().build());\n      sizes.add(c3_8xlarge().build());\n      sizes.add(c4_large().build());\n      sizes.add(c4_xlarge().build());\n      sizes.add(c4_2xlarge().build());\n      sizes.add(c4_4xlarge().build());\n      sizes.add(c4_8xlarge().build());\n      sizes.add(c5_large().build());\n      sizes.add(c5_xlarge().build());\n      sizes.add(c5_2xlarge().build());\n      sizes.add(c5_4xlarge().build());\n      sizes.add(c5_9xlarge().build());\n      sizes.add(c5_18xlarge().build());\n      sizes.add(c5d_large().build());\n      sizes.add(c5d_xlarge().build());\n      sizes.add(c5d_2xlarge().build());\n      sizes.add(c5d_4xlarge().build());\n      sizes.add(c5d_9xlarge().build());\n      sizes.add(c5d_18xlarge().build());\n      sizes.add(i2_xlarge().build());\n      sizes.add(i2_2xlarge().build());\n      sizes.add(i2_4xlarge().build());\n      sizes.add(i2_8xlarge().build());\n      sizes.add(m1_large().build());\n      sizes.add(m1_small().build());\n      sizes.add(m1_medium().build());\n      sizes.add(m1_xlarge().build());\n      sizes.add(m2_xlarge().build());\n      sizes.add(m2_2xlarge().build());\n      sizes.add(m2_4xlarge().build());\n      sizes.add(m3_medium().build());\n      sizes.add(m3_large().build());\n      sizes.add(m3_xlarge().build());\n      sizes.add(m3_2xlarge().build());\n      sizes.add(m4_large().build());\n      sizes.add(m4_xlarge().build());\n      sizes.add(m4_2xlarge().build());\n      sizes.add(m4_4xlarge().build());\n      sizes.add(m4_10xlarge().build());\n      sizes.add(m4_16xlarge().build());\n      sizes.add(m5_large().build());\n      sizes.add(m5_xlarge().build());\n      sizes.add(m5_2xlarge().build());\n      sizes.add(m5_4xlarge().build());\n      sizes.add(m5_12xlarge().build());\n      sizes.add(m5_24xlarge().build());\n      sizes.add(m5d_large().build());\n      sizes.add(m5d_xlarge().build());\n      sizes.add(m5d_2xlarge().build());\n      sizes.add(m5d_4xlarge().build());\n      sizes.add(m5d_12xlarge().build());\n      sizes.add(m5d_24xlarge().build());\n      sizes.add(r3_large().build());\n      sizes.add(r3_xlarge().build());\n      sizes.add(r3_2xlarge().build());\n      sizes.add(r3_4xlarge().build());\n      sizes.add(r3_8xlarge().build());\n      sizes.add(r4_large().build());\n      sizes.add(r4_xlarge().build());\n      sizes.add(r4_2xlarge().build());\n      sizes.add(r4_4xlarge().build());\n      sizes.add(r4_8xlarge().build());\n      sizes.add(r4_16xlarge().build());\n      sizes.add(d2_xlarge().build());\n      sizes.add(d2_2xlarge().build());\n      sizes.add(d2_4xlarge().build());\n      sizes.add(d2_8xlarge().build());\n      sizes.add(x1_32xlarge().build());\n      sizes.add(x1_16xlarge().build());\n      sizes.add(a1_medium().build());\n      sizes.add(a1_large().build());\n      sizes.add(a1_xlarge().build());\n      sizes.add(a1_2xlarge().build());\n      sizes.add(a1_4xlarge().build());\n\n      return sizes.build();\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/compute/suppliers/AWSEC2ImageSupplier.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.compute.suppliers;\n\nimport static com.google.common.base.Predicates.in;\nimport static com.google.common.base.Throwables.propagate;\nimport static com.google.common.collect.Iterables.concat;\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.transform;\nimport static org.jclouds.Constants.PROPERTY_USER_THREADS;\nimport static org.jclouds.aws.ec2.reference.AWSEC2Constants.PROPERTY_EC2_AMI_QUERY;\nimport static org.jclouds.aws.ec2.reference.AWSEC2Constants.PROPERTY_EC2_CC_AMI_QUERY;\nimport static org.jclouds.aws.ec2.reference.AWSEC2Constants.PROPERTY_EC2_CC_REGIONS;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\n\nimport org.jclouds.aws.ec2.compute.config.ClusterCompute;\nimport org.jclouds.aws.ec2.compute.config.ImageQuery;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.compute.functions.ImagesToRegionAndIdMap;\nimport org.jclouds.location.Region;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Splitter;\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ForwardingSet;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Multimap;\nimport com.google.common.util.concurrent.Futures;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.ListeningExecutorService;\n\npublic final class AWSEC2ImageSupplier implements Supplier<Set<? extends Image>> {\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   private Logger logger = Logger.NULL;\n   \n   private final Set<String> clusterComputeIds;\n   private final CallForImages.Factory factory;\n   private final ListeningExecutorService userExecutor;\n\n   private final Supplier<Set<String>> regions;\n   private final Map<String, String> queries;\n   private final Iterable<String> clusterRegions;\n   private final Supplier<LoadingCache<RegionAndName, ? extends Image>> cache;\n   \n   @Inject AWSEC2ImageSupplier(@Region Supplier<Set<String>> regions, @ImageQuery Map<String, String> queries,\n         @Named(PROPERTY_EC2_CC_REGIONS) String clusterRegions,\n         Supplier<LoadingCache<RegionAndName, ? extends Image>> cache, CallForImages.Factory factory,\n         @ClusterCompute Set<String> clusterComputeIds,\n         @Named(PROPERTY_USER_THREADS) ListeningExecutorService userExecutor) {\n      this.factory = factory;\n      this.regions = regions;\n      this.queries = queries;\n      this.clusterRegions = Splitter.on(',').split(clusterRegions);\n      this.cache = cache;\n      this.clusterComputeIds = clusterComputeIds;\n      this.userExecutor = userExecutor;\n   }\n   \n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public Set<? extends Image> get() {\n      String amiQuery = queries.get(PROPERTY_EC2_AMI_QUERY);\n      String ccAmiQuery = queries.get(PROPERTY_EC2_CC_AMI_QUERY);\n\n      Set<String> regionIds = regions.get();\n\n      ListenableFuture<Iterable<Image>> normalImages = images(regionIds, amiQuery, PROPERTY_EC2_AMI_QUERY);\n      ImmutableSet<Image> clusterImages;\n      try {\n         clusterImages = ImmutableSet\n               .copyOf(images(filter(clusterRegions, in(regionIds)), ccAmiQuery, PROPERTY_EC2_CC_AMI_QUERY).get());\n      } catch (Exception e) {\n         logger.warn(e, \"Error parsing images in query %s\", ccAmiQuery);\n         throw propagate(e);\n      }\n      Iterables.addAll(clusterComputeIds, transform(clusterImages, new Function<Image, String>() {\n\n         @Override\n         public String apply(Image arg0) {\n            return arg0.getId();\n         }\n\n      }));\n\n      Iterable<? extends Image> parsedImages;\n      try {\n         parsedImages = ImmutableSet.copyOf(concat(clusterImages, normalImages.get()));\n      } catch (Exception e) {\n         logger.warn(e, \"Error parsing images in query %s\", amiQuery);\n         throw propagate(e);\n      }\n\n      Map<RegionAndName, ? extends Image> imageMap = ImagesToRegionAndIdMap.imagesToMap(parsedImages);\n      cache.get().invalidateAll();\n      cache.get().putAll(Map.class.cast(imageMap));\n      logger.debug(\"<< images(%d)\", imageMap.size());\n\n      // Forwarding so that later changes to the underlying cache are visible.\n      return new ForwardingSet<Image>() {\n         protected Set<Image> delegate() {\n            return (Set<Image>) ImmutableSet.copyOf(cache.get().asMap().values());\n         }\n      };\n   }\n   \n   private ListenableFuture<Iterable<Image>> images(Iterable<String> regions, String query, String tag) {\n      if (query == null) {\n         logger.debug(\">> no %s specified, skipping image parsing\", tag);\n         return Futures.<Iterable<Image>> immediateFuture(ImmutableSet.<Image> of());\n      } else {\n         return userExecutor.submit(factory.parseImagesFromRegionsUsingFilter(regions, QueryStringToMultimap.INSTANCE\n                  .apply(query)));\n      }\n   }\n\n   public static enum QueryStringToMultimap implements Function<String, Multimap<String, String>> {\n      INSTANCE;\n      @Override\n      public Multimap<String, String> apply(String arg0) {\n         ImmutableMultimap.Builder<String, String> builder = ImmutableMultimap.builder();\n         for (String pair : Splitter.on(';').split(arg0)) {\n            String[] keyValue = pair.split(\"=\");\n            if (keyValue.length == 1)\n               builder.putAll(keyValue[0], ImmutableSet.<String> of());\n            else\n               builder.putAll(keyValue[0], Splitter.on(',').split(keyValue[1]));\n         }\n         return builder.build();\n      }\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/compute/suppliers/CallForImages.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.compute.suppliers;\n\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.transform;\nimport static org.jclouds.aws.ec2.options.AWSDescribeImagesOptions.Builder.filters;\n\nimport java.util.Map.Entry;\nimport java.util.concurrent.Callable;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\n\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.ec2.compute.functions.EC2ImageParser;\nimport org.jclouds.ec2.compute.strategy.DescribeImagesParallel;\nimport org.jclouds.ec2.options.DescribeImagesOptions;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Predicates;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Multimap;\nimport com.google.common.collect.ImmutableMap.Builder;\nimport com.google.inject.assistedinject.Assisted;\n\npublic class CallForImages implements Callable<Iterable<Image>> {\n   public interface Factory {\n      CallForImages parseImagesFromRegionsUsingFilter(Iterable<String> regions, Multimap<String, String> filter);\n   }\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   private final Iterable<String> regions;\n   private final DescribeImagesParallel describer;\n   private final EC2ImageParser parser;\n   private final Multimap<String, String> filter;\n\n   @Inject\n   protected CallForImages(DescribeImagesParallel describer, EC2ImageParser parser, @Assisted Iterable<String> regions,\n            @Assisted Multimap<String, String> filter) {\n      this.regions = regions;\n      this.describer = describer;\n      this.filter = filter;\n      this.parser = parser;\n   }\n\n   public Iterable<Image> call() {\n\n      logger.debug(\">> providing images\");\n\n      Builder<String, DescribeImagesOptions> builder = ImmutableMap.builder();\n      for (String region : regions)\n         builder.put(region, filters(filter));\n\n      Iterable<Entry<String, DescribeImagesOptions>> queries = builder.build().entrySet();\n\n      Iterable<Image> returnVal = filter(transform(describer.apply(queries), parser), Predicates.notNull());\n      if (logger.isDebugEnabled())\n         logger.debug(\"<< images(%s)\", Iterables.size(returnVal));\n      return returnVal;\n   }\n\n   @Override\n   public String toString() {\n      return String.format(\"describingImages(filter=%s,regions=%s)\", filter, regions);\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/config/AWSEC2HttpApiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.config;\n\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\nimport java.util.TimeZone;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.ec2.AWSEC2Api;\nimport org.jclouds.aws.ec2.domain.AWSRunningInstance;\nimport org.jclouds.aws.ec2.domain.SpotInstanceRequest;\nimport org.jclouds.aws.ec2.functions.SpotInstanceRequestToAWSRunningInstance;\nimport org.jclouds.aws.ec2.options.AWSRunInstancesOptions;\nimport org.jclouds.aws.filters.FormSigner;\nimport org.jclouds.aws.filters.FormSignerV4;\nimport org.jclouds.date.DateService;\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.config.BaseEC2HttpApiModule;\nimport org.jclouds.ec2.features.AMIApi;\nimport org.jclouds.ec2.features.InstanceApi;\nimport org.jclouds.ec2.features.SecurityGroupApi;\nimport org.jclouds.ec2.options.RunInstancesOptions;\nimport org.jclouds.rest.ConfiguresHttpApi;\n\nimport com.google.common.base.Function;\nimport com.google.inject.Provides;\nimport com.google.inject.TypeLiteral;\n\n/**\n * Configures the EC2 connection.\n */\n@ConfiguresHttpApi\npublic class AWSEC2HttpApiModule extends BaseEC2HttpApiModule<AWSEC2Api> {\n\n   private final SimpleDateFormat iso8601 = new SimpleDateFormat(\"yyyyMMdd'T'HHmmss'Z'\");\n\n   public AWSEC2HttpApiModule() {\n      super(AWSEC2Api.class);\n      iso8601.setTimeZone(TimeZone.getTimeZone(\"GMT\"));\n   }\n\n   @Singleton\n   @Provides\n   final EC2Api provide(AWSEC2Api in) {\n      return in;\n   }\n\n   @Singleton\n   @Provides\n   final InstanceApi getInstanceApi(AWSEC2Api in) {\n      return in.getInstanceApi().get();\n   }\n\n   @Singleton\n   @Provides\n   final SecurityGroupApi getSecurityGroupApi(AWSEC2Api in) {\n      return in.getSecurityGroupApi().get();\n   }\n\n   @Singleton\n   @Provides\n   final AMIApi getAMIApi(AWSEC2Api in) {\n      return in.getAMIApi().get();\n   }\n\n   @Override\n   protected void configure() {\n      bind(FormSigner.class).to(FormSignerV4.class);\n      bind(RunInstancesOptions.class).to(AWSRunInstancesOptions.class);\n      bind(new TypeLiteral<Function<SpotInstanceRequest, AWSRunningInstance>>() {\n      }).to(SpotInstanceRequestToAWSRunningInstance.class);\n      super.configure();\n   }\n\n   @Override protected String provideTimeStamp(DateService dateService) {\n      // 20120416T155408Z not 2012-04-16T15:54:08Z\n      return iso8601.format(new Date());\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/domain/AWSRunningInstance.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Date;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.ec2.domain.BlockDevice;\nimport org.jclouds.ec2.domain.Hypervisor;\nimport org.jclouds.ec2.domain.InstanceState;\nimport org.jclouds.ec2.domain.RootDeviceType;\nimport org.jclouds.ec2.domain.RunningInstance;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.rest.annotations.SinceApiVersion;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Maps;\nimport com.google.common.collect.Sets;\n\n/**\n * \n * @see <a href=\n *      \"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-ItemType-RunningInstancesItemType.html\"\n *      />\n */\npublic class AWSRunningInstance extends RunningInstance {\n   \n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return new Builder().fromRunningInstance(this);\n   }\n   \n   public static class Builder extends org.jclouds.ec2.domain.RunningInstance.Builder<Builder> {\n      private MonitoringState monitoringState;\n      private String placementGroup;\n      private Set<String> productCodes = Sets.newLinkedHashSet();\n      private String subnetId;\n      private String spotInstanceRequestId;\n      private String vpcId;\n      private Hypervisor hypervisor;\n      private Map<String, String> securityGroupIdToNames = Maps.newLinkedHashMap();\n      private String iamInstanceProfileArn;\n      private String iamInstanceProfileId;\n\n      public Builder securityGroupIdToNames(Map<String, String> securityGroupIdToNames) {\n         this.securityGroupIdToNames = ImmutableMap.copyOf(checkNotNull(securityGroupIdToNames,\n               \"securityGroupIdToNames\"));\n         return this;\n      }\n\n      public Builder securityGroupIdToName(String key, String value) {\n         if (key != null && value != null)\n            this.securityGroupIdToNames.put(key, value);\n         return this;\n      }\n\n      public Builder monitoringState(MonitoringState monitoringState) {\n         this.monitoringState = monitoringState;\n         return this;\n      }\n\n      public Builder placementGroup(String placementGroup) {\n         this.placementGroup = placementGroup;\n         return this;\n      }\n\n      public Builder productCodes(Iterable<String> productCodes) {\n         this.productCodes = ImmutableSet.copyOf(checkNotNull(productCodes, \"productCodes\"));\n         return this;\n      }\n\n      public Builder productCode(String productCode) {\n         if (productCode != null)\n            this.productCodes.add(productCode);\n         return this;\n      }\n\n      public Builder subnetId(String subnetId) {\n         this.subnetId = subnetId;\n         return this;\n      }\n\n      public Builder spotInstanceRequestId(String spotInstanceRequestId) {\n         this.spotInstanceRequestId = spotInstanceRequestId;\n         return this;\n      }\n\n      public Builder vpcId(String vpcId) {\n         this.vpcId = vpcId;\n         return this;\n      }\n      \n      public Builder hypervisor(Hypervisor hypervisor) {\n         this.hypervisor = hypervisor;\n         return this;\n      }\n\n      /**\n       * @see AWSRunningInstance#getIAMInstanceProfile()\n       */\n      public Builder iamInstanceProfileArn(String iamInstanceProfileArn) {\n         this.iamInstanceProfileArn = iamInstanceProfileArn;\n         return this;\n      }\n\n      /**\n       * @see AWSRunningInstance#getIAMInstanceProfile()\n       */\n      public Builder iamInstanceProfileId(String iamInstanceProfileId) {\n         this.iamInstanceProfileId = iamInstanceProfileId;\n         return this;\n      }\n\n      @Override\n      public AWSRunningInstance build() {\n         Optional<IAMInstanceProfile> iamInstanceProfile = Optional.absent();\n         if (iamInstanceProfileArn != null && iamInstanceProfileId != null) {\n            iamInstanceProfile = Optional.of(IAMInstanceProfile.forArnAndId(iamInstanceProfileArn,\n                  iamInstanceProfileId));\n         }\n         return new AWSRunningInstance(region, securityGroupIdToNames, amiLaunchIndex, dnsName, imageId, instanceId,\n               instanceState, rawState, instanceType, ipAddress, kernelId, keyName, launchTime, availabilityZone,\n               virtualizationType, platform, privateDnsName, privateIpAddress, ramdiskId, reason, rootDeviceType,\n               rootDeviceName, ebsBlockDevices, monitoringState, placementGroup, productCodes, subnetId,\n               spotInstanceRequestId, vpcId, hypervisor, tags, iamInstanceProfile);\n      }\n      \n      @Override\n      public Builder fromRunningInstance(RunningInstance in) {\n         super.fromRunningInstance(in);\n         if (in instanceof AWSRunningInstance) {\n            AWSRunningInstance awsIn = AWSRunningInstance.class.cast(in);\n            monitoringState(awsIn.monitoringState).placementGroup(awsIn.placementGroup)\n                  .productCodes(awsIn.productCodes).subnetId(awsIn.subnetId)\n                  .spotInstanceRequestId(awsIn.spotInstanceRequestId).vpcId(awsIn.vpcId).hypervisor(awsIn.hypervisor)\n                  .securityGroupIdToNames(awsIn.securityGroupIdToNames);\n            if (awsIn.getIAMInstanceProfile().isPresent()) {\n               iamInstanceProfileArn(awsIn.getIAMInstanceProfile().get().getArn());\n               iamInstanceProfileId(awsIn.getIAMInstanceProfile().get().getId());\n            }\n         }\n         return this;\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n\n   }\n\n   private final MonitoringState monitoringState;\n   @Nullable\n   private final String placementGroup;\n   private final Set<String> productCodes;\n   @Nullable\n   private final String subnetId;\n   @Nullable\n   private final String spotInstanceRequestId;\n   @Nullable\n   private final String vpcId;\n   private final Hypervisor hypervisor;\n   private final Map<String, String> securityGroupIdToNames;\n   private final Optional<IAMInstanceProfile> iamInstanceProfile;\n\n   protected AWSRunningInstance(String region, Map<String, String> securityGroupIdToNames, String amiLaunchIndex,\n            String dnsName, String imageId, String instanceId, InstanceState instanceState, String rawState,\n            String instanceType, String ipAddress, String kernelId, String keyName, Date launchTime,\n            String availabilityZone, String virtualizationType, String platform, String privateDnsName,\n            String privateIpAddress, String ramdiskId, String reason, RootDeviceType rootDeviceType,\n            String rootDeviceName, Map<String, BlockDevice> ebsBlockDevices, MonitoringState monitoringState,\n            String placementGroup, Iterable<String> productCodes, String subnetId, String spotInstanceRequestId,\n            String vpcId, Hypervisor hypervisor, Map<String, String> tags, Optional<IAMInstanceProfile> iamInstanceProfile) {\n      super(region, securityGroupIdToNames.values(), amiLaunchIndex, dnsName, imageId, instanceId, instanceState,\n               rawState, instanceType, ipAddress, kernelId, keyName, launchTime, availabilityZone, virtualizationType,\n               platform, privateDnsName, privateIpAddress, ramdiskId, reason, rootDeviceType, rootDeviceName,\n               ebsBlockDevices, tags);\n      this.monitoringState = checkNotNull(monitoringState, \"monitoringState\");\n      this.placementGroup = placementGroup;\n      this.productCodes = ImmutableSet.copyOf(checkNotNull(productCodes, \"productCodes\"));\n      this.subnetId = subnetId;\n      this.spotInstanceRequestId = spotInstanceRequestId;\n      this.vpcId = vpcId;\n      this.hypervisor = checkNotNull(hypervisor, \"hypervisor\");\n      this.securityGroupIdToNames = ImmutableMap.<String, String> copyOf(checkNotNull(securityGroupIdToNames,\n            \"securityGroupIdToNames\"));\n      this.iamInstanceProfile = checkNotNull(iamInstanceProfile, \"iamInstanceProfile of %s\", instanceId);\n   }\n\n   public Map<String, String> getSecurityGroupIdToNames() {\n      return securityGroupIdToNames;\n   }\n\n   /**\n    * State of monitoring for the instance.\n    */\n   public MonitoringState getMonitoringState() {\n      return monitoringState;\n   }\n\n   /**\n    * The name of the placement group the instance is in (for cluster compute\n    * instances).\n    */\n   public String getPlacementGroup() {\n      return placementGroup;\n   }\n\n   /**\n    * Product codes attached to this instance.\n    */\n   public Set<String> getProductCodes() {\n      return productCodes;\n   }\n\n   /**\n    * The ID of the Spot Instance request\n    */\n   public String getSpotInstanceRequestId() {\n      return spotInstanceRequestId;\n   }\n\n   /**\n    * Specifies the VPC in which the instance is running (Amazon Virtual Private\n    * Cloud).\n    */\n   public String getVpcId() {\n      return vpcId;\n   }\n   \n   /**\n    * hypervisor of the VM\n    * @see Hypervisor\n    */\n   public Hypervisor getHypervisor() {\n      return hypervisor;\n   }\n   \n   /**\n    * Specifies the subnet ID in which the instance is running (Amazon Virtual\n    * Private Cloud).\n    */\n   public String getSubnetId() {\n      return subnetId;\n   }\n\n   /**\n    * The IAM Instance Profile (IIP) associated with the instance.\n    */\n   @SinceApiVersion(\"2012-06-01\")\n   public Optional<IAMInstanceProfile> getIAMInstanceProfile() {\n      return iamInstanceProfile;\n   }\n\n   @Override\n   protected ToStringHelper string() {\n      return super.string().add(\"monitoringState\", monitoringState).add(\"placementGroup\", placementGroup)\n               .add(\"subnetId\", subnetId).add(\"spotInstanceRequestId\", spotInstanceRequestId).add(\"vpcId\", vpcId)\n               .add(\"hypervisor\", hypervisor).add(\"iamInstanceProfile\", iamInstanceProfile.orNull());\n   }\n\n   public static class IAMInstanceProfile {\n      public static IAMInstanceProfile forArnAndId(String arn, String id) {\n         return new IAMInstanceProfile(arn, id);\n      }\n\n      private final String arn;\n      private final String id;\n\n      private IAMInstanceProfile(String arn, String id) {\n         this.arn = checkNotNull(arn, \"arn\");\n         this.id = checkNotNull(id, \"id for %s\", arn);\n      }\n\n      /**\n       * The Amazon resource name (ARN) of the IAM Instance Profile (IIP) to associate with the instance.\n       */\n      public String getArn() {\n         return arn;\n      }\n\n      /**\n       * The ID of the IAM Instance Profile ID (IIP) associated with the instance.\n       */\n      public String getId() {\n         return id;\n      }\n\n      @Override\n      public int hashCode() {\n         return Objects.hashCode(arn, id);\n      }\n\n      @Override\n      public boolean equals(Object obj) {\n         if (this == obj)\n            return true;\n         if (obj == null || getClass() != obj.getClass())\n            return false;\n         IAMInstanceProfile that = IAMInstanceProfile.class.cast(obj);\n         return equal(this.arn, that.arn) && equal(this.id, that.id);\n      }\n\n      @Override\n      public String toString() {\n         return toStringHelper(\"\").add(\"arn\", arn).add(\"id\", id).toString();\n      }\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/domain/InternetGateway.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.domain;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Amazon EC2 Internet Gateway.\n *\n * @see <a href=\"http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_InternetGateway.html\" >doc</a>\n */\n@AutoValue\npublic abstract class InternetGateway {\n\n   @Nullable\n   public abstract String id();\n\n   @Nullable\n   public abstract List<InternetGatewayAttachment> attachmentSet();\n\n   @Nullable\n   public abstract Map<String, String> tags();\n\n   @SerializedNames({\"internetGatewayId\", \"attachmentSet\", \"tagSet\"})\n   public static InternetGateway create(String id, List<InternetGatewayAttachment> attachmentSet,\n                                        Map<String, String> tags) {\n      return builder()\n         .id(id)\n         .attachmentSet(attachmentSet)\n         .tags(tags)\n         .build();\n   }\n\n   InternetGateway() {}\n\n   public static Builder builder() {\n      return new AutoValue_InternetGateway.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n\n      public abstract Builder id(String id);\n      public abstract Builder attachmentSet(List<InternetGatewayAttachment> attachmentSet);\n      public abstract Builder tags(Map<String, String> tags);\n\n      @Nullable abstract List<InternetGatewayAttachment> attachmentSet();\n      @Nullable abstract Map<String, String> tags();\n\n      abstract InternetGateway autoBuild();\n\n      public InternetGateway build() {\n         tags(tags() != null ? ImmutableMap.copyOf(tags()) : ImmutableMap.<String, String>of());\n         attachmentSet(attachmentSet() != null\n            ? ImmutableList.copyOf(attachmentSet()) : ImmutableList.<InternetGatewayAttachment>of());\n         return autoBuild();\n      }\n\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/domain/InternetGatewayAttachment.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.domain;\n\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.auto.value.AutoValue;\n\n/**\n * Amazon EC2 Internet Gateway attachment to VPC.\n *\n * @see <a href=\"http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_InternetGatewayAttachment.html\" >doc</a>\n */\n@AutoValue\npublic abstract class InternetGatewayAttachment {\n\n   public enum State {\n      UNRECOGNIZED,\n      ATTACHING,\n      ATTACHED,\n      AVAILABLE,\n      DETATCHING,\n      DETATCHED;\n\n      public String value() {\n         return name().toLowerCase();\n      }\n\n      public static State fromValue(String v) {\n         try {\n            return valueOf(v.toUpperCase());\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n   }\n\n   @Nullable\n   public abstract State state();\n\n   @Nullable\n   public abstract String vpcId();\n\n   InternetGatewayAttachment() {}\n\n   public static Builder builder() {\n      return new AutoValue_InternetGatewayAttachment.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n\n      public abstract Builder state(State state);\n\n      public abstract Builder vpcId(String vpcId);\n\n      public abstract InternetGatewayAttachment build();\n\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/domain/LaunchSpecification.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Arrays;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.ec2.domain.BlockDeviceMapping;\nimport org.jclouds.ec2.domain.BlockDeviceMapping.MapEBSSnapshotToDevice;\nimport org.jclouds.ec2.domain.BlockDeviceMapping.MapEphemeralDeviceToDevice;\nimport org.jclouds.ec2.domain.BlockDeviceMapping.MapNewVolumeToDevice;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.rest.annotations.SinceApiVersion;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSortedSet;\n\n/**\n * \n * @see <a href=\n *      \"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-RequestSpotInstances.html\"\n *      />\n */\npublic class LaunchSpecification {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n      protected ImmutableMap.Builder<String, String> securityGroupIdToNames = ImmutableMap.builder();\n      protected String imageId;\n      protected String instanceType;\n      protected String kernelId;\n      protected String keyName;\n      protected String availabilityZone;\n      protected String subnetId;\n      protected String ramdiskId;\n      protected Boolean monitoringEnabled;\n      protected ImmutableSet.Builder<BlockDeviceMapping> blockDeviceMappings = ImmutableSet\n            .builder();\n      protected ImmutableSet.Builder<String> securityGroupIds = ImmutableSet.builder();\n      protected ImmutableSet.Builder<String> securityGroupNames = ImmutableSet.builder();\n      protected byte[] userData;\n      private String iamInstanceProfileArn;\n      private String iamInstanceProfileName;\n\n      public void clear() {\n         securityGroupIdToNames = ImmutableMap.builder();\n         imageId = null;\n         instanceType = null;\n         kernelId = null;\n         keyName = null;\n         availabilityZone = null;\n         subnetId = null;\n         ramdiskId = null;\n         monitoringEnabled = false;\n         blockDeviceMappings = ImmutableSet.builder();\n         securityGroupIds = ImmutableSet.builder();\n         securityGroupNames = ImmutableSet.builder();\n         userData = null;\n         iamInstanceProfileArn = null;\n         iamInstanceProfileName = null;\n      }\n\n      public Builder securityGroupIdToNames(Map<String, String> securityGroupIdToNames) {\n         this.securityGroupIdToNames.putAll(checkNotNull(securityGroupIdToNames, \"securityGroupIdToNames\"));\n         return this;\n      }\n\n      public Builder securityGroupIdToName(String groupId, String groupName) {\n         if (groupId != null && groupName != null)\n            this.securityGroupIdToNames.put(checkNotNull(groupId, \"groupId\"), checkNotNull(groupName, \"groupName\"));\n         return this;\n      }\n\n      public Builder imageId(String imageId) {\n         this.imageId = imageId;\n         return this;\n      }\n\n      public Builder monitoringEnabled(Boolean monitoringEnabled) {\n         this.monitoringEnabled = monitoringEnabled;\n         return this;\n      }\n\n      public Builder instanceType(String instanceType) {\n         this.instanceType = instanceType;\n         return this;\n      }\n\n      public Builder kernelId(String kernelId) {\n         this.kernelId = kernelId;\n         return this;\n      }\n\n      public Builder keyName(String keyName) {\n         this.keyName = keyName;\n         return this;\n      }\n\n      public Builder availabilityZone(String availabilityZone) {\n         this.availabilityZone = availabilityZone;\n         return this;\n      }\n      \n      public Builder subnetId(String subnetId) {\n         this.subnetId = subnetId;\n         return this;\n      }\n      \n      public Builder ramdiskId(String ramdiskId) {\n         this.ramdiskId = ramdiskId;\n         return this;\n      }\n\n      public Builder mapEBSSnapshotToDevice(String deviceName, String snapshotId, @Nullable Integer sizeInGib,\n            boolean deleteOnTermination) {\n         return mapEBSSnapshotToDevice(deviceName, snapshotId, sizeInGib, deleteOnTermination, null, null, null);\n      }\n\n      public Builder mapEBSSnapshotToDevice(String deviceName, String snapshotId, @Nullable Integer sizeInGib,\n                                            boolean deleteOnTermination, @Nullable String volumeType,\n                                            @Nullable Integer iops, @Nullable Boolean encrypted) {\n         blockDeviceMappings.add(new MapEBSSnapshotToDevice(deviceName, snapshotId, sizeInGib, deleteOnTermination,\n                 volumeType, iops, encrypted));\n         return this;\n      }\n\n      public Builder mapNewVolumeToDevice(String deviceName, int sizeInGib, boolean deleteOnTermination) {\n         return mapNewVolumeToDevice(deviceName, sizeInGib, deleteOnTermination, null, null, null);\n      }\n\n      public Builder mapNewVolumeToDevice(String deviceName, int sizeInGib, boolean deleteOnTermination,\n                                          @Nullable String volumeType, @Nullable Integer iops,\n                                          @Nullable Boolean encrypted) {\n         blockDeviceMappings.add(new MapNewVolumeToDevice(deviceName, sizeInGib, deleteOnTermination,\n                 volumeType, iops, encrypted));\n         return this;\n      }\n\n      public Builder mapEphemeralDeviceToDevice(String deviceName, String virtualName) {\n         blockDeviceMappings.add(new MapEphemeralDeviceToDevice(deviceName, virtualName));\n         return this;\n      }\n\n      public Builder blockDeviceMapping(BlockDeviceMapping blockDeviceMapping) {\n         this.blockDeviceMappings.add(checkNotNull(blockDeviceMapping, \"blockDeviceMapping\"));\n         return this;\n      }\n\n      public Builder blockDeviceMappings(Iterable<? extends BlockDeviceMapping> blockDeviceMappings) {\n         this.blockDeviceMappings.addAll(checkNotNull(blockDeviceMappings, \"blockDeviceMappings\"));\n         return this;\n      }\n\n      public Builder securityGroupIds(Iterable<String> securityGroupIds) {\n         this.securityGroupIds.addAll(checkNotNull(securityGroupIds, \"securityGroupIds\"));\n         return this;\n      }\n\n      public Builder securityGroupId(String securityGroupId) {\n         if (securityGroupId != null)\n            this.securityGroupIds.add(securityGroupId);\n         return this;\n      }\n\n      public Builder securityGroupNames(Iterable<String> securityGroupNames) {\n         this.securityGroupNames.addAll(checkNotNull(securityGroupNames, \"securityGroupNames\"));\n         return this;\n      }\n\n      public Builder securityGroupName(String securityGroupName) {\n         if (securityGroupName != null)\n            this.securityGroupNames.add(securityGroupName);\n         return this;\n      }\n\n      public Builder userData(byte[] userData) {\n         this.userData = userData;\n         return this;\n      }\n\n      /**\n       * @see LaunchSpecification#getIAMInstanceProfile()\n       */\n      public Builder iamInstanceProfileArn(String iamInstanceProfileArn) {\n         this.iamInstanceProfileArn = iamInstanceProfileArn;\n         return this;\n      }\n\n      /**\n       * @see LaunchSpecification#getIAMInstanceProfile()\n       */\n      public Builder iamInstanceProfileName(String iamInstanceProfileName) {\n         this.iamInstanceProfileName = iamInstanceProfileName;\n         return this;\n      }\n\n      public LaunchSpecification build() {\n         Optional<IAMInstanceProfileRequest> iamInstanceProfile;\n         if (iamInstanceProfileArn != null && iamInstanceProfileName != null) {\n            iamInstanceProfile = Optional.of(IAMInstanceProfileRequest.forArnAndName(iamInstanceProfileArn,\n                  iamInstanceProfileName));\n         } else if (iamInstanceProfileArn != null) {\n            iamInstanceProfile = Optional.of(IAMInstanceProfileRequest.forArn(iamInstanceProfileArn));\n         } else if (iamInstanceProfileName != null) {\n            iamInstanceProfile = Optional.of(IAMInstanceProfileRequest.forName(iamInstanceProfileName));\n         } else {\n            iamInstanceProfile = Optional.absent();\n         }\n         return new LaunchSpecification(instanceType, imageId, kernelId, ramdiskId, availabilityZone, subnetId,\n               keyName, securityGroupIdToNames.build(), blockDeviceMappings.build(), monitoringEnabled,\n               securityGroupIds.build(), securityGroupNames.build(), userData, iamInstanceProfile);\n      }\n\n      public static Builder fromLaunchSpecification(LaunchSpecification in) {\n         Builder builder = new Builder();\n         builder.instanceType(in.getInstanceType()).imageId(in.getImageId()).kernelId(in.getKernelId())\n               .ramdiskId(in.getRamdiskId()).availabilityZone(in.getAvailabilityZone()).subnetId(in.getSubnetId())\n               .keyName(in.getKeyName()).securityGroupIdToNames(in.getSecurityGroupIdToNames())\n               .securityGroupIds(in.getSecurityGroupIds()).securityGroupNames(in.getSecurityGroupNames())\n               .blockDeviceMappings(in.getBlockDeviceMappings()).monitoringEnabled(in.isMonitoringEnabled())\n               .userData(in.getUserData());\n         if (in.getIAMInstanceProfile().isPresent()) {\n            builder.iamInstanceProfileArn(in.getIAMInstanceProfile().get().getArn().orNull());\n            builder.iamInstanceProfileName(in.getIAMInstanceProfile().get().getName().orNull());\n         }\n         return builder;\n      }\n   }\n\n   protected final String instanceType;\n   protected final String imageId;\n   protected final String kernelId;\n   protected final String ramdiskId;\n   protected final String availabilityZone;\n   protected final String subnetId;\n   protected final String keyName;\n   protected final Map<String, String> securityGroupIdToNames;\n   protected final Set<? extends BlockDeviceMapping> blockDeviceMappings;\n   protected final Set<String> securityGroupIds;\n   protected final Set<String> securityGroupNames;\n   protected final Boolean monitoringEnabled;\n   protected final byte[] userData;\n   protected final Optional<IAMInstanceProfileRequest> iamInstanceProfile;\n\n   public LaunchSpecification(String instanceType, String imageId, String kernelId, String ramdiskId,\n         String availabilityZone, String subnetId, String keyName, Map<String, String> securityGroupIdToNames,\n         Iterable<? extends BlockDeviceMapping> blockDeviceMappings, Boolean monitoringEnabled,\n         Set<String> securityGroupIds, Set<String> securityGroupNames, byte[] userData,\n         Optional<IAMInstanceProfileRequest> iamInstanceProfile) {\n      this.instanceType = checkNotNull(instanceType, \"instanceType\");\n      this.imageId = checkNotNull(imageId, \"imageId\");\n      this.kernelId = kernelId;\n      this.ramdiskId = ramdiskId;\n      this.availabilityZone = availabilityZone;\n      this.subnetId = subnetId;\n      this.keyName = keyName;\n      this.securityGroupIdToNames = ImmutableMap.copyOf(checkNotNull(securityGroupIdToNames, \"securityGroupIdToNames\"));\n      this.blockDeviceMappings = ImmutableSortedSet.copyOf(checkNotNull(blockDeviceMappings, \"blockDeviceMappings\"));\n      this.securityGroupIds = ImmutableSortedSet.copyOf(checkNotNull(securityGroupIds, \"securityGroupIds\"));\n      this.securityGroupNames = ImmutableSortedSet.copyOf(checkNotNull(securityGroupNames, \"securityGroupNames\"));\n      this.monitoringEnabled = monitoringEnabled;\n      this.userData = userData;\n      this.iamInstanceProfile = checkNotNull(iamInstanceProfile, \"iamInstanceProfile\");\n   }\n\n   public Map<String, String> getSecurityGroupIdToNames() {\n      return securityGroupIdToNames;\n   }\n\n   /**\n    * Image ID of the AMI used to launch the instance.\n    */\n   public String getImageId() {\n      return imageId;\n   }\n\n   /**\n    * CloudWatch support\n    */\n   public Boolean isMonitoringEnabled() {\n      return monitoringEnabled;\n   }\n\n   /**\n    * The instance type.\n    */\n   public String getInstanceType() {\n      return instanceType;\n   }\n\n   /**\n    * Optional. Kernel associated with this instance.\n    */\n   public String getKernelId() {\n      return kernelId;\n   }\n\n   /**\n    * If this instance was launched with an associated key pair, this displays\n    * the key pair name.\n    */\n   public String getKeyName() {\n      return keyName;\n   }\n\n   /**\n    * The location where the instance launched.\n    */\n   public String getAvailabilityZone() {\n      return availabilityZone;\n   }\n   \n   /**\n    * The ID of the subnet in which to launch the Spot Instance.\n    */\n   @Nullable\n   public String getSubnetId() {\n      return subnetId;\n   }\n\n   /**\n    * Optional. RAM disk associated with this instance.\n    */\n   public String getRamdiskId() {\n      return ramdiskId;\n   }\n\n   /**\n    * volumes mappings associated with the instance.\n    */\n   public Set<? extends BlockDeviceMapping> getBlockDeviceMappings() {\n      return blockDeviceMappings;\n   }\n\n   /**\n    * Names of the security groups.\n    */\n   public Set<String> getSecurityGroupNames() {\n      return securityGroupNames;\n   }\n\n   /**\n    * Ids of the security groups.\n    */\n   public Set<String> getSecurityGroupIds() {\n      return securityGroupIds;\n   }\n\n   /**\n    * User Data\n    */\n   public byte[] getUserData() {\n      return userData;\n   }\n\n   /**\n    * The IAM Instance Profile (IIP) associated with the instance.\n    */\n   @SinceApiVersion(\"2012-06-01\")\n   public Optional<IAMInstanceProfileRequest> getIAMInstanceProfile() {\n      return iamInstanceProfile;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((availabilityZone == null) ? 0 : availabilityZone.hashCode());\n      result = prime * result + ((subnetId == null) ? 0 : subnetId.hashCode());\n      result = prime * result + ((blockDeviceMappings == null) ? 0 : blockDeviceMappings.hashCode());\n      result = prime * result + ((imageId == null) ? 0 : imageId.hashCode());\n      result = prime * result + ((instanceType == null) ? 0 : instanceType.hashCode());\n      result = prime * result + ((kernelId == null) ? 0 : kernelId.hashCode());\n      result = prime * result + ((keyName == null) ? 0 : keyName.hashCode());\n      result = prime * result + ((monitoringEnabled == null) ? 0 : monitoringEnabled.hashCode());\n      result = prime * result + ((ramdiskId == null) ? 0 : ramdiskId.hashCode());\n      result = prime * result + ((securityGroupIdToNames == null) ? 0 : securityGroupIdToNames.hashCode());\n      result = prime * result + ((securityGroupIds == null) ? 0 : securityGroupIds.hashCode());\n      result = prime * result + ((securityGroupNames == null) ? 0 : securityGroupNames.hashCode());\n      result = prime * result + ((!iamInstanceProfile.isPresent()) ? 0 : iamInstanceProfile.get().hashCode());\n      result = prime * result + Arrays.hashCode(userData);\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      LaunchSpecification other = (LaunchSpecification) obj;\n      if (availabilityZone == null) {\n         if (other.availabilityZone != null)\n            return false;\n      } else if (!availabilityZone.equals(other.availabilityZone))\n         return false;\n      if (subnetId == null) {\n         if (other.subnetId != null)\n            return false;\n      } else if (!subnetId.equals(other.subnetId))\n         return false;      \n      if (blockDeviceMappings == null) {\n         if (other.blockDeviceMappings != null)\n            return false;\n      } else if (!blockDeviceMappings.equals(other.blockDeviceMappings))\n         return false;\n      if (imageId == null) {\n         if (other.imageId != null)\n            return false;\n      } else if (!imageId.equals(other.imageId))\n         return false;\n      if (instanceType == null) {\n         if (other.instanceType != null)\n            return false;\n      } else if (!instanceType.equals(other.instanceType))\n         return false;\n      if (kernelId == null) {\n         if (other.kernelId != null)\n            return false;\n      } else if (!kernelId.equals(other.kernelId))\n         return false;\n      if (keyName == null) {\n         if (other.keyName != null)\n            return false;\n      } else if (!keyName.equals(other.keyName))\n         return false;\n      if (monitoringEnabled == null) {\n         if (other.monitoringEnabled != null)\n            return false;\n      } else if (!monitoringEnabled.equals(other.monitoringEnabled))\n         return false;\n      if (ramdiskId == null) {\n         if (other.ramdiskId != null)\n            return false;\n      } else if (!ramdiskId.equals(other.ramdiskId))\n         return false;\n      if (securityGroupIdToNames == null) {\n         if (other.securityGroupIdToNames != null)\n            return false;\n      } else if (!securityGroupIdToNames.equals(other.securityGroupIdToNames))\n         return false;\n      if (securityGroupIds == null) {\n         if (other.securityGroupIds != null)\n            return false;\n      } else if (!securityGroupIds.equals(other.securityGroupIds))\n         return false;\n      if (securityGroupNames == null) {\n         if (other.securityGroupNames != null)\n            return false;\n      } else if (!securityGroupNames.equals(other.securityGroupNames))\n         return false;\n      if (!iamInstanceProfile.isPresent()) {\n         if (other.iamInstanceProfile.isPresent())\n            return false;\n      } else if (!iamInstanceProfile.get().equals(other.iamInstanceProfile.orNull()))\n         return false;\n      if (!Arrays.equals(userData, other.userData))\n         return false;\n      return true;\n   }\n\n   public Builder toBuilder() {\n      return Builder.fromLaunchSpecification(this);\n   }\n\n   @Override\n   public String toString() {\n      return \"[instanceType=\" + instanceType + \", imageId=\" + imageId + \", kernelId=\" + kernelId + \", ramdiskId=\"\n            + ramdiskId + \", availabilityZone=\" + availabilityZone + \", subnetId=\" + subnetId + \", keyName=\" + keyName\n            + \", securityGroupIdToNames=\" + securityGroupIdToNames + \", blockDeviceMappings=\" + blockDeviceMappings\n            + \", securityGroupIds=\" + securityGroupIds + \", securityGroupNames=\" + securityGroupNames\n            + \", monitoringEnabled=\" + monitoringEnabled + \", userData=\" + Arrays.toString(userData)\n            + \", iamInstanceProfile=\" + iamInstanceProfile.orNull() + \"]\";\n   }\n\n   @SinceApiVersion(\"2012-06-01\")\n   public static class IAMInstanceProfileRequest {\n\n      public static IAMInstanceProfileRequest forArn(String arn) {\n         return new IAMInstanceProfileRequest(Optional.of(checkNotNull(arn, \"arn\")), Optional.<String> absent());\n      }\n\n      public static IAMInstanceProfileRequest forName(String name) {\n         return new IAMInstanceProfileRequest(Optional.<String> absent(), Optional.of(checkNotNull(name, \"name\")));\n      }\n\n      public static IAMInstanceProfileRequest forArnAndName(String arn, String name) {\n         return new IAMInstanceProfileRequest(Optional.of(checkNotNull(arn, \"arn\")), Optional.of(checkNotNull(name, \"name\")));\n      }\n\n      private final Optional<String> arn;\n      private final Optional<String> name;\n\n      private IAMInstanceProfileRequest(Optional<String> arn, Optional<String> name) {\n         this.arn = checkNotNull(arn, \"arn\");\n         this.name = checkNotNull(name, \"name for %s\", arn);\n      }\n\n      /**\n       * The Amazon resource name (ARN) of the IAM Instance Profile (IIP) to associate with the instance.\n       */\n      public Optional<String> getArn() {\n         return arn;\n      }\n\n      /**\n       * The name of the IAM Instance Profile (IIP) to associate with the instance.\n       */\n      public Optional<String> getName() {\n         return name;\n      }\n\n      @Override\n      public int hashCode() {\n         return Objects.hashCode(arn, name);\n      }\n\n      @Override\n      public boolean equals(Object obj) {\n         if (this == obj)\n            return true;\n         if (obj == null || getClass() != obj.getClass())\n            return false;\n         IAMInstanceProfileRequest that = IAMInstanceProfileRequest.class.cast(obj);\n         return equal(this.arn, that.arn) && equal(this.name, that.name);\n      }\n\n      @Override\n      public String toString() {\n         return toStringHelper(\"\").omitNullValues().add(\"arn\", arn.orNull()).add(\"name\", name.orNull()).toString();\n      }\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/domain/MonitoringState.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\n/**\n * \n * State of monitoring for the instance.\n * \n * @see InstanceClient#runInstances\n * @see MonitoringClient#monitorInstances\n * @see MonitoringClient#UnmonitorInstances\n */\npublic enum MonitoringState {\n\n   PENDING, ENABLED, DISABLING, DISABLED, UNRECOGNIZED;\n\n   public String value() {\n      return name().toLowerCase();\n   }\n\n   @Override\n   public String toString() {\n      return value();\n   }\n\n   public static MonitoringState fromValue(String state) {\n      try {\n         return valueOf(checkNotNull(state, \"state\").toUpperCase());\n      } catch (IllegalArgumentException e) {\n         return UNRECOGNIZED;\n      }\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/domain/PlacementGroup.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\n/**\n * A placement group is a logical grouping of instances.\n * \n * <p/>\n * You first create a cluster placement group, then launch multiple cluster compute instances into\n * the group. Currently cluster compute instances are available only in the US-East (Northern\n * Virginia) Region. You must give each placement group a name that is unique within your account.\n * For more information about cluster placement groups, see Cluster Compute Instance Concepts.\n * <p/>\n * Note\n * <p/>\n * You can't merge cluster placement groups. Instead you must terminate the instances in one of the\n * groups, and then relaunch the instances into the other group.\n * \n * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribePlacementGroups.html\"\n *      />\n */\npublic class PlacementGroup implements Comparable<PlacementGroup> {\n   public static enum State {\n      PENDING, AVAILABLE, DELETING, DELETED, UNRECOGNIZED;\n      public String value() {\n         return name().toLowerCase();\n      }\n\n      @Override\n      public String toString() {\n         return value();\n      }\n\n      public static State fromValue(String state) {\n         try {\n            return valueOf(checkNotNull(state, \"state\").toUpperCase());\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n   }\n\n   private final String region;\n   private final String name;\n   private final String strategy;\n   private final State state;\n\n   public PlacementGroup(String region, String name, String strategy, State state) {\n      this.region = checkNotNull(region, \"region\");\n      this.name = checkNotNull(name, \"name\");\n      this.strategy = checkNotNull(strategy, \"strategy\");\n      this.state = checkNotNull(state, \"state\");\n   }\n\n   @Override\n   public int compareTo(PlacementGroup o) {\n      return name.compareTo(o.name);\n   }\n\n   /**\n    * To be removed in jclouds 1.6 <h4>Warning</h4>\n    * \n    * Especially on EC2 clones that may not support regions, this value is fragile. Consider\n    * alternate means to determine context.\n    */\n   @Deprecated\n   public String getRegion() {\n      return region;\n   }\n\n   /**\n    * @return Name of the placement group.\n    */\n   public String getName() {\n      return name;\n   }\n\n   /**\n    * @return The placement strategy.\n    */\n   public String getStrategy() {\n      return strategy;\n   }\n\n   /**\n    * @return Status of the placement group.\n    */\n   public State getState() {\n      return state;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((name == null) ? 0 : name.hashCode());\n      result = prime * result + ((region == null) ? 0 : region.hashCode());\n      result = prime * result + ((state == null) ? 0 : state.hashCode());\n      result = prime * result + ((strategy == null) ? 0 : strategy.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      PlacementGroup other = (PlacementGroup) obj;\n      if (name == null) {\n         if (other.name != null)\n            return false;\n      } else if (!name.equals(other.name))\n         return false;\n      if (region == null) {\n         if (other.region != null)\n            return false;\n      } else if (!region.equals(other.region))\n         return false;\n      if (state == null) {\n         if (other.state != null)\n            return false;\n      } else if (!state.equals(other.state))\n         return false;\n      if (strategy == null) {\n         if (other.strategy != null)\n            return false;\n      } else if (!strategy.equals(other.strategy))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"[name=\" + name + \", region=\" + region + \", state=\" + state + \", strategy=\" + strategy + \"]\";\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/domain/RegionNameAndPublicKeyMaterial.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.domain;\n\nimport org.jclouds.ec2.compute.domain.RegionAndName;\n\npublic class RegionNameAndPublicKeyMaterial extends RegionAndName {\n   private final String publicKeyMaterial;\n\n   public RegionNameAndPublicKeyMaterial(String region, String tag, String publicKeyMaterial) {\n      super(region, tag);\n      this.publicKeyMaterial = publicKeyMaterial;\n   }\n\n   // intentionally not overriding equals or hash-code so that we can search only by region/tag in a\n   // map\n\n   public String getPublicKeyMaterial() {\n      return publicKeyMaterial;\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/domain/Route.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.domain;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n/**\n * A route in an Amazon EC2 Route Table.\n *\n * @see <a href=\"http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_Route.html\" >doc</a>\n */\n@AutoValue\npublic abstract class Route {\n\n   public enum RouteState {\n\n      /**\n       * An active route.\n       */\n      ACTIVE,\n\n      /**\n       * Indicates that the route's target isn't available (for example, the specified gateway isn't attached\n       * to the VPC, or the specified NAT instance has been terminated).\n       */\n      BLACKHOLE,\n\n      /**\n       * Value supplied was not valid.\n       */\n      UNRECOGNIZED;\n\n      public String value() {\n         return name().toLowerCase();\n      }\n\n      public static RouteState fromValue(String v) {\n         if (v == null || v.isEmpty()) {\n            throw new IllegalArgumentException(\"Value cannot be null or empty\");\n         }\n         try {\n            return valueOf(v.toUpperCase());\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n   }\n\n\n   @Nullable\n   public abstract String destinationCidrBlock();\n\n   @Nullable\n   public abstract String gatewayId();\n\n   @Nullable\n   public abstract RouteState state();\n\n   @Nullable\n   public abstract String origin();\n\n   @SerializedNames({\"destinationCidrBlock\", \"gatewayId\", \"state\", \"origin\"})\n   public static Route create(String destinationCidrBlock, String gatewayId, RouteState state, String origin) {\n      return builder()\n         .destinationCidrBlock(destinationCidrBlock)\n         .gatewayId(gatewayId)\n         .state(state)\n         .origin(origin)\n         .build();\n   }\n\n   Route() {}\n\n   public static Builder builder() {\n      return new AutoValue_Route.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder destinationCidrBlock(String destinationCidrBlock);\n\n      public abstract Builder gatewayId(String gatewayId);\n\n      public abstract Builder state(RouteState state);\n\n      public abstract Builder origin(String origin);\n\n      public abstract Route build();\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/domain/RouteTable.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.domain;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Amazon EC2 Route Table.\n *\n * @see <a href=\"http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RouteTable.html\" >doc</a>\n */\n@AutoValue\npublic abstract class RouteTable {\n\n   @Nullable\n   public abstract String id();\n\n   @Nullable\n   public abstract String vpcId();\n\n   @Nullable\n   public abstract List<Route> routeSet();\n\n   @Nullable\n   public abstract List<RouteTableAssociation> associationSet();\n\n   @Nullable\n   public abstract Map<String, String> tags();\n\n   @SerializedNames({\"routeTableId\", \"vpcId\", \"routeSet\", \"associationSet\", \"tagSet\"})\n   public static RouteTable create(String id,\n                                   String vpcId,\n                                   List<Route> routeSet,\n                                   List<RouteTableAssociation> associationSet,\n                                   Map<String, String> tags) {\n      return builder()\n         .id(id)\n         .vpcId(vpcId)\n         .routeSet(routeSet)\n         .associationSet(associationSet)\n         .tags(tags)\n         .build();\n   }\n\n   RouteTable() {}\n\n   public static Builder builder() {\n      return new AutoValue_RouteTable.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n\n      public abstract Builder id(String id);\n      public abstract Builder vpcId(String vpcId);\n      public abstract Builder routeSet(List<Route> routeSet);\n      public abstract Builder associationSet(List<RouteTableAssociation> associationSet);\n      public abstract Builder tags(Map<String, String> tags);\n\n      @Nullable abstract List<Route> routeSet();\n      @Nullable abstract List<RouteTableAssociation> associationSet();\n      @Nullable abstract Map<String, String> tags();\n\n      abstract RouteTable autoBuild();\n\n      public RouteTable build() {\n         routeSet(routeSet() != null ? ImmutableList.copyOf(routeSet()) : ImmutableList.<Route>of());\n         associationSet(associationSet() != null\n            ? ImmutableList.copyOf(associationSet())\n            : ImmutableList.<RouteTableAssociation>of());\n         tags(tags() != null ? ImmutableMap.copyOf(tags()) : ImmutableMap.<String, String>of());\n         return autoBuild();\n      }\n\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/domain/RouteTableAssociation.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.domain;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n/**\n * An association of a route to a subnet.\n *\n * @see <a href=\"http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RouteTableAssociation.html\">AWS docs</a>\n */\n@AutoValue\npublic abstract class RouteTableAssociation {\n\n\n   @Nullable\n   public abstract String id();\n\n   @Nullable\n   public abstract String routeTableId();\n\n   @Nullable\n   public abstract String subnetId();\n\n   @Nullable\n   public abstract Boolean main();\n\n   @SerializedNames({\"routeTableAssociationId\", \"routeTableId\", \"subnetId\", \"main\"})\n   public static RouteTableAssociation create(String id, String routeTableId, String subnetId, Boolean main) {\n      return builder()\n         .id(id)\n         .routeTableId(routeTableId)\n         .subnetId(subnetId)\n         .main(main)\n         .build();\n   }\n\n   RouteTableAssociation() {}\n\n   public static Builder builder() {\n      return new AutoValue_RouteTableAssociation.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder id(String id);\n      public abstract Builder routeTableId(String routeTableId);\n      public abstract Builder subnetId(String subnetId);\n      public abstract Builder main(Boolean main);\n\n      public abstract RouteTableAssociation build();\n\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/domain/Spot.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Date;\n\n/**\n * @see <a href=\n *      \"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeSpotPriceHistory.html\"\n *      />\n */\npublic class Spot implements Comparable<Spot> {\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n      private String region;\n      private String instanceType;\n      private String productDescription;\n      private float spotPrice;\n      private Date timestamp;\n      private String availabilityZone;\n\n      public void clear() {\n         this.region = null;\n         this.instanceType = null;\n         this.productDescription = null;\n         this.spotPrice = 0.0f;\n         this.timestamp = null;\n         this.availabilityZone = null;\n      }\n\n      public Builder region(String region) {\n         this.region = region;\n         return this;\n      }\n\n      public Builder instanceType(String instanceType) {\n         this.instanceType = instanceType;\n         return this;\n      }\n\n      public Builder productDescription(String productDescription) {\n         this.productDescription = productDescription;\n         return this;\n      }\n\n      public Builder spotPrice(float spotPrice) {\n         this.spotPrice = spotPrice;\n         return this;\n      }\n\n      public Builder timestamp(Date timestamp) {\n         this.timestamp = timestamp;\n         return this;\n      }\n\n      public Builder availabilityZone(String availabilityZone) {\n         this.availabilityZone = availabilityZone;\n         return this;\n      }\n\n      public Spot build() {\n         return new Spot(region, instanceType, productDescription, spotPrice, timestamp, availabilityZone);\n      }\n   }\n\n   private final String region;\n   private final String instanceType;\n   private final String productDescription;\n   private final float spotPrice;\n   private final Date timestamp;\n   private final String availabilityZone;\n\n   public Spot(String region, String instanceType, String productDescription, float spotPrice, Date timestamp,\n               String availabilityZone) {\n      this.region = checkNotNull(region, \"region\");\n      this.instanceType = checkNotNull(instanceType, \"instanceType\");\n      this.productDescription = checkNotNull(productDescription, \"productDescription\");\n      this.spotPrice = spotPrice;\n      this.timestamp = checkNotNull(timestamp, \"timestamp\");\n      this.availabilityZone = checkNotNull(availabilityZone, \"availabilityZone\");\n   }\n\n   /**\n    * To be removed in jclouds 1.6 <h4>Warning</h4>\n    * \n    * Especially on EC2 clones that may not support regions, this value is fragile. Consider\n    * alternate means to determine context.\n    */\n   @Deprecated\n   public String getRegion() {\n      return region;\n   }\n\n   public String getInstanceType() {\n      return instanceType;\n   }\n\n   public String getProductDescription() {\n      return productDescription;\n   }\n\n   public float getSpotPrice() {\n      return spotPrice;\n   }\n\n   public Date getTimestamp() {\n      return timestamp;\n   }\n\n   public String getAvailabilityZone() {\n      return availabilityZone;\n   }\n\n   @Override\n   public int compareTo(Spot o) {\n      return Float.compare(spotPrice, o.spotPrice);\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((instanceType == null) ? 0 : instanceType.hashCode());\n      result = prime * result + ((productDescription == null) ? 0 : productDescription.hashCode());\n      result = prime * result + ((region == null) ? 0 : region.hashCode());\n      result = prime * result + Float.floatToIntBits(spotPrice);\n      result = prime * result + ((timestamp == null) ? 0 : timestamp.hashCode());\n      result = prime * result + ((availabilityZone == null) ? 0 : availabilityZone.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      Spot other = (Spot) obj;\n      if (instanceType == null) {\n         if (other.instanceType != null)\n            return false;\n      } else if (!instanceType.equals(other.instanceType))\n         return false;\n      if (productDescription == null) {\n         if (other.productDescription != null)\n            return false;\n      } else if (!productDescription.equals(other.productDescription))\n         return false;\n      if (region == null) {\n         if (other.region != null)\n            return false;\n      } else if (!region.equals(other.region))\n         return false;\n      if (Float.floatToIntBits(spotPrice) != Float.floatToIntBits(other.spotPrice))\n         return false;\n      if (timestamp == null) {\n         if (other.timestamp != null)\n            return false;\n      } else if (!timestamp.equals(other.timestamp))\n         return false;\n      if (availabilityZone == null) {\n         if (other.availabilityZone != null)\n            return false;\n      } else if (!availabilityZone.equals(other.availabilityZone)) {\n         return false;\n      }\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"[region=\" + region + \", instanceType=\" + instanceType + \", productDescription=\" + productDescription\n            + \", spotPrice=\" + spotPrice + \", timestamp=\" + timestamp + \", availabilityZone=\"\n              + availabilityZone + \"]\";\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/domain/SpotInstanceRequest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Date;\nimport java.util.Map;\n\nimport com.google.common.base.CaseFormat;\nimport com.google.common.base.Strings;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Maps;\nimport org.jclouds.javax.annotation.Nullable;\n\npublic class SpotInstanceRequest implements Comparable<SpotInstanceRequest> {\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n      private String region;\n      private String availabilityZoneGroup;\n      private String launchedAvailabilityZone;\n      private Date createTime;\n      private String faultCode;\n      private String faultMessage;\n      private String instanceId;\n      private String launchGroup;\n      private LaunchSpecification launchSpecification;\n      private String productDescription;\n      private String id;\n      private float spotPrice;\n      private State state;\n      private String rawState;\n      private Type type;\n      private Date validFrom;\n      private Date validUntil;\n      private String statusCode;\n      private String statusMessage;\n      private Date statusUpdateTime;\n      private Map<String, String> tags = Maps.newLinkedHashMap();\n\n      public Builder clear() {\n         this.region = null;\n         this.availabilityZoneGroup = null;\n         this.launchedAvailabilityZone = null;\n         this.createTime = null;\n         this.faultCode = null;\n         this.faultMessage = null;\n         this.instanceId = null;\n         this.launchGroup = null;\n         this.launchSpecification = null;\n         this.productDescription = null;\n         this.id = null;\n         this.spotPrice = 0;\n         this.state = null;\n         this.rawState = null;\n         this.type = null;\n         this.validFrom = null;\n         this.validUntil = null;\n         this.statusCode = null;\n         this.statusMessage = null;\n         this.statusUpdateTime = null;\n         tags = Maps.newLinkedHashMap();\n         return this;\n      }\n\n      public Builder region(String region) {\n         this.region = region;\n         return this;\n      }\n\n      public Builder tags(Map<String, String> tags) {\n         this.tags = ImmutableMap.copyOf(checkNotNull(tags, \"tags\"));\n         return this;\n      }\n\n      public Builder tag(String key, String value) {\n         if (key != null)\n            this.tags.put(key, Strings.nullToEmpty(value));\n         return this;\n      }\n      public Builder availabilityZoneGroup(String availabilityZoneGroup) {\n         this.availabilityZoneGroup = availabilityZoneGroup;\n         return this;\n      }\n\n      public Builder launchedAvailabilityZone(String launchedAvailabilityZone) {\n         this.launchedAvailabilityZone = launchedAvailabilityZone;\n         return this;\n      }\n\n      public Builder createTime(Date createTime) {\n         this.createTime = createTime;\n         return this;\n      }\n\n      public Builder faultCode(String faultCode) {\n         this.faultCode = faultCode;\n         return this;\n      }\n\n      public Builder faultMessage(String faultMessage) {\n         this.faultMessage = faultMessage;\n         return this;\n      }\n\n      public Builder instanceId(String instanceId) {\n         this.instanceId = instanceId;\n         return this;\n      }\n\n      public Builder launchGroup(String launchGroup) {\n         this.launchGroup = launchGroup;\n         return this;\n      }\n\n      public Builder launchSpecification(LaunchSpecification launchSpecification) {\n         this.launchSpecification = launchSpecification;\n         return this;\n      }\n\n      public Builder productDescription(String productDescription) {\n         this.productDescription = productDescription;\n         return this;\n      }\n\n      public Builder id(String id) {\n         this.id = id;\n         return this;\n      }\n\n      public Builder spotPrice(float spotPrice) {\n         this.spotPrice = spotPrice;\n         return this;\n      }\n\n      public Builder state(State state) {\n         this.state = state;\n         return this;\n      }\n      \n      public Builder rawState(String rawState) {\n         this.rawState = rawState;\n         return this;\n      }\n      \n      public Builder type(Type type) {\n         this.type = type;\n         return this;\n      }\n\n      public Builder validFrom(Date validFrom) {\n         this.validFrom = validFrom;\n         return this;\n      }\n\n      public Builder validUntil(Date validUntil) {\n         this.validUntil = validUntil;\n         return this;\n      }\n\n      public Builder statusCode(String statusCode) {\n         this.statusCode = statusCode;\n         return this;\n      }\n\n      public Builder statusMessage(String statusMessage) {\n         this.statusMessage = statusMessage;\n         return this;\n      }\n\n      public Builder statusUpdateTime(Date statusUpdateTime) {\n         this.statusUpdateTime = statusUpdateTime;\n         return this;\n      }\n\n      public SpotInstanceRequest build() {\n         return new SpotInstanceRequest(region, availabilityZoneGroup, launchedAvailabilityZone, createTime, faultCode,\n                  faultMessage, instanceId, launchGroup, launchSpecification, productDescription, id, spotPrice, state,\n                  rawState, type, validFrom, validUntil, statusCode, statusMessage, statusUpdateTime, tags);\n      }\n   }\n\n   public enum Type {\n      ONE_TIME, PERSISTENT, UNRECOGNIZED;\n\n      public String value() {\n         return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_HYPHEN, name());\n      }\n\n      @Override\n      public String toString() {\n         return value();\n      }\n\n      public static Type fromValue(String type) {\n         try {\n            return valueOf(CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_UNDERSCORE, checkNotNull(type, \"type\")));\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n   }\n\n   public enum State {\n      OPEN, ACTIVE, CANCELLED, CLOSED, UNRECOGNIZED;\n\n      public String value() {\n         return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_HYPHEN, name());\n      }\n\n      @Override\n      public String toString() {\n         return value();\n      }\n\n      public static State fromValue(String state) {\n         try {\n            return valueOf(CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_UNDERSCORE, checkNotNull(state, \"type\")));\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n   }\n\n   private final String region;\n   private final String availabilityZoneGroup;\n   private final String launchedAvailabilityZone;\n   private final Date createTime;\n   private final String faultCode;\n   private final String faultMessage;\n   private final String instanceId;\n   private final String launchGroup;\n   private final LaunchSpecification launchSpecification;\n   private final String productDescription;\n   private final String id;\n   private final float spotPrice;\n   private final State state;\n   private final String rawState;\n   private final Type type;\n   private final Date validFrom;\n   private final Date validUntil;\n   private final String statusCode;\n   private final String statusMessage;\n   private final Date statusUpdateTime;\n   private final Map<String, String> tags;\n\n   public SpotInstanceRequest(String region, String availabilityZoneGroup, @Nullable String launchedAvailabilityZone,\n            Date createTime, String faultCode, String faultMessage, String instanceId, String launchGroup,\n            LaunchSpecification launchSpecification, String productDescription, String id, float spotPrice,\n            State state, String rawState, Type type, Date validFrom, Date validUntil, String statusCode,\n            String statusMessage, Date statusUpdateTime, Map<String, String> tags) {\n      this.region = checkNotNull(region, \"region\");\n      this.availabilityZoneGroup = availabilityZoneGroup;\n      this.launchedAvailabilityZone = launchedAvailabilityZone;\n      this.createTime = createTime;\n      this.faultCode = faultCode;\n      this.faultMessage = faultMessage;\n      this.instanceId = instanceId;\n      this.launchGroup = launchGroup;\n      this.launchSpecification = launchSpecification;\n      this.productDescription = productDescription;\n      this.id = checkNotNull(id, \"id\");\n      this.spotPrice = spotPrice;\n      this.state = checkNotNull(state, \"state\");\n      this.rawState = checkNotNull(rawState, \"rawState\");\n      this.type = checkNotNull(type, \"type\");\n      this.validFrom = validFrom;\n      this.validUntil = validUntil;\n      this.statusCode = statusCode;\n      this.statusMessage = statusMessage;\n      this.statusUpdateTime = statusUpdateTime;\n      this.tags = ImmutableMap.<String, String> copyOf(checkNotNull(tags, \"tags\"));\n   }\n\n   /**\n    * @return spot instance requests are in a region\n    */\n   public String getRegion() {\n      return region;\n   }\n\n   public String getAvailabilityZoneGroup() {\n      return availabilityZoneGroup;\n   }\n\n   public String getLaunchedAvailabilityZone() {\n      return launchedAvailabilityZone;\n   }\n\n   public Date getCreateTime() {\n      return createTime;\n   }\n\n   public String getFaultCode() {\n      return faultCode;\n   }\n\n   public String getFaultMessage() {\n      return faultMessage;\n   }\n\n   public String getInstanceId() {\n      return instanceId;\n   }\n\n   public String getLaunchGroup() {\n      return launchGroup;\n   }\n\n   public LaunchSpecification getLaunchSpecification() {\n      return launchSpecification;\n   }\n\n   public String getProductDescription() {\n      return productDescription;\n   }\n\n   public String getId() {\n      return id;\n   }\n\n   public float getSpotPrice() {\n      return spotPrice;\n   }\n\n   public State getState() {\n      return state;\n   }\n   \n   public String getRawState() {\n      return rawState;\n   }\n   \n   public Type getType() {\n      return type;\n   }\n\n   public Date getValidFrom() {\n      return validFrom;\n   }\n\n   public Date getValidUntil() {\n      return validUntil;\n   }\n\n   public String getStatusCode() {\n      return statusCode;\n   }\n\n   public String getStatusMessage() {\n      return statusMessage;\n   }\n\n   public Date getStatusUpdateTime() {\n      return statusUpdateTime;\n   }\n\n   /**\n    * tags that are present in the instance\n    */\n   public Map<String, String> getTags() {\n      return tags;\n   }\n   \n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((availabilityZoneGroup == null) ? 0 : availabilityZoneGroup.hashCode());\n      result = prime * result + ((createTime == null) ? 0 : createTime.hashCode());\n      result = prime * result + ((faultCode == null) ? 0 : faultCode.hashCode());\n      result = prime * result + ((faultMessage == null) ? 0 : faultMessage.hashCode());\n      result = prime * result + ((id == null) ? 0 : id.hashCode());\n      result = prime * result + ((instanceId == null) ? 0 : instanceId.hashCode());\n      result = prime * result + ((launchGroup == null) ? 0 : launchGroup.hashCode());\n      result = prime * result + ((launchSpecification == null) ? 0 : launchSpecification.hashCode());\n      result = prime * result + ((launchedAvailabilityZone == null) ? 0 : launchedAvailabilityZone.hashCode());\n      result = prime * result + ((productDescription == null) ? 0 : productDescription.hashCode());\n      result = prime * result + ((region == null) ? 0 : region.hashCode());\n      result = prime * result + Float.floatToIntBits(spotPrice);\n      result = prime * result + ((state == null) ? 0 : state.hashCode());\n      result = prime * result + ((type == null) ? 0 : type.hashCode());\n      result = prime * result + ((validFrom == null) ? 0 : validFrom.hashCode());\n      result = prime * result + ((validUntil == null) ? 0 : validUntil.hashCode());\n      result = prime * result + ((statusCode == null) ? 0 : statusCode.hashCode());\n      result = prime * result + ((statusMessage == null) ? 0 : statusMessage.hashCode());\n      result = prime * result + ((statusUpdateTime == null) ? 0 : statusUpdateTime.hashCode());\n      result = prime * result + ((tags == null) ? 0 : tags.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      SpotInstanceRequest other = (SpotInstanceRequest) obj;\n      if (availabilityZoneGroup == null) {\n         if (other.availabilityZoneGroup != null)\n            return false;\n      } else if (!availabilityZoneGroup.equals(other.availabilityZoneGroup))\n         return false;\n      if (createTime == null) {\n         if (other.createTime != null)\n            return false;\n      } else if (!createTime.equals(other.createTime))\n         return false;\n      if (faultCode == null) {\n         if (other.faultCode != null)\n            return false;\n      } else if (!faultCode.equals(other.faultCode))\n         return false;\n      if (faultMessage == null) {\n         if (other.faultMessage != null)\n            return false;\n      } else if (!faultMessage.equals(other.faultMessage))\n         return false;\n      if (id == null) {\n         if (other.id != null)\n            return false;\n      } else if (!id.equals(other.id))\n         return false;\n      if (instanceId == null) {\n         if (other.instanceId != null)\n            return false;\n      } else if (!instanceId.equals(other.instanceId))\n         return false;\n      if (launchGroup == null) {\n         if (other.launchGroup != null)\n            return false;\n      } else if (!launchGroup.equals(other.launchGroup))\n         return false;\n      if (launchSpecification == null) {\n         if (other.launchSpecification != null)\n            return false;\n      } else if (!launchSpecification.equals(other.launchSpecification))\n         return false;\n      if (launchedAvailabilityZone == null) {\n         if (other.launchedAvailabilityZone != null)\n            return false;\n      } else if (!launchedAvailabilityZone.equals(other.launchedAvailabilityZone))\n         return false;\n      if (productDescription == null) {\n         if (other.productDescription != null)\n            return false;\n      } else if (!productDescription.equals(other.productDescription))\n         return false;\n      if (region == null) {\n         if (other.region != null)\n            return false;\n      } else if (!region.equals(other.region))\n         return false;\n      if (Float.floatToIntBits(spotPrice) != Float.floatToIntBits(other.spotPrice))\n         return false;\n      if (state != other.state)\n         return false;\n      if (type != other.type)\n         return false;\n      if (validFrom == null) {\n         if (other.validFrom != null)\n            return false;\n      } else if (!validFrom.equals(other.validFrom))\n         return false;\n      if (validUntil == null) {\n         if (other.validUntil != null)\n            return false;\n      } else if (!validUntil.equals(other.validUntil))\n         return false;\n      if (statusCode == null) {\n         if (other.statusCode != null)\n            return false;\n      } else if (!statusCode.equals(other.statusCode))\n         return false;\n      if (statusMessage == null) {\n         if (other.statusMessage != null)\n            return false;\n      } else if (!statusMessage.equals(other.statusMessage))\n         return false;\n      if (statusUpdateTime == null) {\n         if (other.statusUpdateTime != null)\n            return false;\n      } else if (!statusUpdateTime.equals(other.statusUpdateTime))\n         return false;\n      if (tags == null) {\n         if (other.tags != null)\n            return false;\n      } else if (!tags.equals(other.tags))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"[region=\" + region + \", availabilityZoneGroup=\" + availabilityZoneGroup + \", launchedAvailabilityZone=\"\n            + launchedAvailabilityZone + \", createTime=\" + createTime + \", faultCode=\" + faultCode + \", faultMessage=\"\n            + faultMessage + \", instanceId=\" + instanceId + \", launchGroup=\" + launchGroup + \", launchSpecification=\"\n            + launchSpecification + \", productDescription=\" + productDescription + \", id=\" + id + \", spotPrice=\"\n            + spotPrice + \", state=\" + rawState + \", type=\" + type + \", validFrom=\" + validFrom + \", validUntil=\"\n            + validUntil + \", statusCode=\" + statusCode + \", statusMessage=\" + statusMessage + \", statusUpdateTime=\"\n            + statusUpdateTime + \", tags=\" + tags + \"]\";\n   }\n\n   @Override\n   public int compareTo(SpotInstanceRequest arg0) {\n      return createTime.compareTo(arg0.createTime);\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/domain/VPC.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.domain;\n\nimport java.util.Map;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Amazon EC2 VPC.\n *\n * @see <a href=\"http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_Vpc.html\" >doc</a>\n */\n@AutoValue\npublic abstract class VPC {\n\n   public enum State {\n      /**\n       * The subnet is available for use.\n       */\n      AVAILABLE,\n      /**\n       * The subnet is not yet available for use.\n       */\n      PENDING, UNRECOGNIZED;\n      public String value() {\n         return name().toLowerCase();\n      }\n\n      public static State fromValue(String v) {\n         try {\n            return valueOf(v.toUpperCase());\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n   }\n\n   public enum InstanceTenancy {\n      /**\n       * The valid tenancy of instances launched into the VPC\n       */\n      DEFAULT,\n      DEDICATED,\n      HOST,\n      UNRECOGNIZED;\n      public String value() {\n         return name().toLowerCase();\n      }\n\n      public static InstanceTenancy fromValue(String v) {\n         try {\n            return valueOf(v.toUpperCase());\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n   }\n\n   @Nullable\n   public abstract String id();\n   @Nullable\n   public abstract State state();\n   @Nullable\n   public abstract String cidrBlock();\n   @Nullable\n   public abstract String dhcpOptionsId();\n   @Nullable\n   public abstract InstanceTenancy instanceTenancy();\n   @Nullable\n   public abstract Boolean isDefault();\n   @Nullable\n   public abstract Map<String, String> tags();\n\n\n   @SerializedNames({ \"vpcId\", \"state\", \"cidrBlock\", \"dhcpOptionsId\", \"instanceTenancy\", \"isDefault\", \"tagSet\" })\n   public static VPC create(String id, State state, String cidrBlock, String dhcpOptionsId, InstanceTenancy instanceTenancy, Boolean isDefault, Map<String, String> tags) {\n      return builder()\n              .id(id)\n              .state(state)\n              .isDefault(isDefault)\n              .cidrBlock(cidrBlock)\n              .dhcpOptionsId(dhcpOptionsId)\n              .instanceTenancy(instanceTenancy)\n              .tags(tags)\n              .build();\n   }\n\n   VPC() {}\n\n   public static Builder builder() {\n      return new AutoValue_VPC.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n\n      public abstract Builder id(String id);\n      public abstract Builder state(State state);\n      public abstract Builder cidrBlock(String cidrBlock);\n      public abstract Builder dhcpOptionsId(String dhcpOptionsId);\n      public abstract Builder instanceTenancy(InstanceTenancy instanceTenancy);\n      public abstract Builder isDefault(Boolean isDefault);\n      public abstract Builder tags(Map<String, String> tags);\n\n      @Nullable public abstract String id();\n      @Nullable public abstract State state();\n      @Nullable public abstract String cidrBlock();\n      @Nullable public abstract InstanceTenancy instanceTenancy();\n      @Nullable public abstract Boolean isDefault();\n      @Nullable public abstract Map<String, String> tags();\n\n      abstract VPC autoBuild();\n\n      public VPC build() {\n         tags(tags() != null ? ImmutableMap.copyOf(tags()) : ImmutableMap.<String, String>of());\n         return autoBuild();\n      }\n\n\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/features/AWSAMIApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.features;\n\nimport static org.jclouds.aws.reference.FormParameters.ACTION;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.FormParam;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\n\nimport org.jclouds.aws.ec2.xml.ProductCodesHandler;\nimport org.jclouds.aws.filters.FormSigner;\nimport org.jclouds.ec2.binders.BindProductCodesToIndexedFormParams;\nimport org.jclouds.ec2.features.AMIApi;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.location.functions.RegionToEndpointOrProviderIfNull;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.EndpointParam;\nimport org.jclouds.rest.annotations.FormParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.VirtualHost;\nimport org.jclouds.rest.annotations.XMLResponseParser;\n\n/**\n * Provides access to AMI Services.\n * <p/>\n */\n@RequestFilters(FormSigner.class)\n@VirtualHost\npublic interface AWSAMIApi extends AMIApi {\n   // TODO make AWSImage as it has product codes...\n\n   /**\n    * Returns the Product Codes of an image.\n    * \n    * @param region\n    *           AMIs are tied to the Region where its files are located within Amazon S3.\n    * @param imageId\n    *           The ID of the AMI for which an attribute will be described\n    * @see #describeImages\n    * @see #modifyImageAttribute\n    * @see #resetImageAttribute\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeImageAttribute.html\"\n    *      />\n    * @see DescribeImagesOptions\n    */\n   @Named(\"DescribeImageAttribute\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = { ACTION, \"Attribute\" }, values = { \"DescribeImageAttribute\", \"productCodes\" })\n   @XMLResponseParser(ProductCodesHandler.class)\n   Set<String> getProductCodesForImageInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n            @FormParam(\"ImageId\") String imageId);\n\n   /**\n    * Adds {@code productCode}s to an AMI.\n    * \n    * @param region\n    *           AMIs are tied to the Region where its files are located within Amazon S3.\n    * @param productCodes\n    *           Product Codes\n    * @param imageId\n    *           The AMI ID.\n    * \n    * @see #removeProductCodesFromImage\n    * @see #describeImageAttribute\n    * @see #resetImageAttribute\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-ModifyImageAttribute.html\"\n    *      />\n    */\n   @Named(\"ModifyImageAttribute\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = { ACTION, \"OperationType\", \"Attribute\" }, values = { \"ModifyImageAttribute\", \"add\",\n            \"productCodes\" })\n   void addProductCodesToImageInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n            @BinderParam(BindProductCodesToIndexedFormParams.class) Iterable<String> productCodes,\n            @FormParam(\"ImageId\") String imageId);\n\n   /**\n    * Removes {@code productCode}s from an AMI.\n    * \n    * @param region\n    *           AMIs are tied to the Region where its files are located within Amazon S3.\n    * @param productCodes\n    *           Product Codes\n    * @param imageId\n    *           The AMI ID.\n    * \n    * @see #addProductCodesToImage\n    * @see #describeImageAttribute\n    * @see #resetImageAttribute\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-ModifyImageAttribute.html\"\n    *      />\n    */\n   @Named(\"ModifyImageAttribute\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = { ACTION, \"OperationType\", \"Attribute\" }, values = { \"ModifyImageAttribute\", \"remove\",\n            \"productCodes\" })\n   void removeProductCodesFromImageInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n            @BinderParam(BindProductCodesToIndexedFormParams.class) Iterable<String> productCodes,\n            @FormParam(\"ImageId\") String imageId);\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/features/AWSInstanceApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.features;\n\nimport static org.jclouds.aws.reference.FormParameters.ACTION;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.FormParam;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.aws.ec2.domain.AWSRunningInstance;\nimport org.jclouds.aws.ec2.xml.AWSDescribeInstancesResponseHandler;\nimport org.jclouds.aws.ec2.xml.AWSRunInstancesResponseHandler;\nimport org.jclouds.aws.filters.FormSigner;\nimport org.jclouds.ec2.binders.BindFiltersToIndexedFormParams;\nimport org.jclouds.ec2.binders.BindInstanceIdsToIndexedFormParams;\nimport org.jclouds.ec2.binders.IfNotNullBindAvailabilityZoneToFormParam;\nimport org.jclouds.ec2.domain.Reservation;\nimport org.jclouds.ec2.features.InstanceApi;\nimport org.jclouds.ec2.options.RunInstancesOptions;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.location.functions.RegionToEndpointOrProviderIfNull;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.EndpointParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.FormParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.VirtualHost;\nimport org.jclouds.rest.annotations.XMLResponseParser;\n\nimport com.google.common.collect.Multimap;\n\n/**\n * Provides access to EC2 Instance Services via their REST API.\n * <p/>\n */\n@RequestFilters(FormSigner.class)\n@VirtualHost\npublic interface AWSInstanceApi extends InstanceApi {\n\n   @Named(\"DescribeInstances\")\n   @Override\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DescribeInstances\")\n   @XMLResponseParser(AWSDescribeInstancesResponseHandler.class)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<? extends Reservation<? extends AWSRunningInstance>> describeInstancesInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n            @BinderParam(BindInstanceIdsToIndexedFormParams.class) String... instanceIds);\n\n   @Named(\"DescribeInstances\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DescribeInstances\")\n   @XMLResponseParser(AWSDescribeInstancesResponseHandler.class)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<? extends Reservation<? extends AWSRunningInstance>> describeInstancesInRegionWithFilter(\n           @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n           @BinderParam(BindFiltersToIndexedFormParams.class) Multimap<String, String> filter);\n\n   @Named(\"RunInstances\")\n   @Override\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"RunInstances\")\n   @XMLResponseParser(AWSRunInstancesResponseHandler.class)\n   Reservation<? extends AWSRunningInstance> runInstancesInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n            @Nullable @BinderParam(IfNotNullBindAvailabilityZoneToFormParam.class) String nullableAvailabilityZone,\n            @FormParam(\"ImageId\") String imageId, @FormParam(\"MinCount\") int minCount,\n            @FormParam(\"MaxCount\") int maxCount, RunInstancesOptions... options);\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/features/AWSKeyPairApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.features;\n\nimport static org.jclouds.aws.reference.FormParameters.ACTION;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.FormParam;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\n\nimport org.jclouds.aws.filters.FormSigner;\nimport org.jclouds.ec2.domain.KeyPair;\nimport org.jclouds.ec2.functions.EncodedRSAPublicKeyToBase64;\nimport org.jclouds.ec2.features.KeyPairApi;\nimport org.jclouds.ec2.xml.KeyPairResponseHandler;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.location.functions.RegionToEndpointOrProviderIfNull;\nimport org.jclouds.rest.annotations.EndpointParam;\nimport org.jclouds.rest.annotations.FormParams;\nimport org.jclouds.rest.annotations.ParamParser;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.VirtualHost;\nimport org.jclouds.rest.annotations.XMLResponseParser;\n\n@RequestFilters(FormSigner.class)\n@VirtualHost\npublic interface AWSKeyPairApi extends KeyPairApi {\n\n   /**\n    * Imports the public key from an RSA key pair that you created with a third-party tool. Compare\n    * this with CreateKeyPair, in which AWS creates the key pair and gives the keys to you (AWS\n    * keeps a copy of the public key). With ImportKeyPair, you create the key pair and give AWS just\n    * the public key. The private key is never transferred between you and AWS.\n    * \n    * <p/>\n    * You can easily create an RSA key pair on Windows and Linux using the ssh-keygen command line\n    * tool (provided with the standard OpenSSH installation). Standard library support for RSA key\n    * pair creation is also available in Java, Ruby, Python, and many other programming languages.\n    * \n    * <p/>\n    * <h4>Supported Formats</h4>\n    * <ul>\n    * <li>OpenSSH public key format (e.g., the format in ~/.ssh/authorized_keys)</li>\n    * <li>Base64 encoded DER format</li>\n    * <li>SSH public key file format as specified in RFC4716</li>\n    * </ul>\n    * DSA keys are not supported. Make sure your key generator is set up to create RSA keys.\n    * <p/>\n    * Supported lengths: 1024, 2048, and 4096.\n    * <p/>\n    * \n    * @param region\n    *           region to import the key into\n    * @param keyName\n    *           A unique name for the key pair. Accepts alphanumeric characters, spaces, dashes, and\n    *           underscores.\n    * @param publicKeyMaterial\n    *           The public key\n    * @return imported key including fingerprint\n    */\n   @Named(\"ImportKeyPair\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"ImportKeyPair\")\n   @XMLResponseParser(KeyPairResponseHandler.class)\n   KeyPair importKeyPairInRegion(\n         @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n         @FormParam(\"KeyName\") String keyName,\n         @FormParam(\"PublicKeyMaterial\") @ParamParser(EncodedRSAPublicKeyToBase64.class) String publicKeyMaterial);\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/features/AWSSecurityGroupApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.features;\n\nimport static org.jclouds.aws.reference.FormParameters.ACTION;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.FormParam;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.aws.ec2.options.CreateSecurityGroupOptions;\nimport org.jclouds.aws.ec2.xml.AWSEC2DescribeSecurityGroupsResponseHandler;\nimport org.jclouds.aws.ec2.xml.CreateSecurityGroupResponseHandler;\nimport org.jclouds.aws.filters.FormSigner;\nimport org.jclouds.ec2.binders.BindFiltersToIndexedFormParams;\nimport org.jclouds.ec2.binders.BindGroupIdsToIndexedFormParams;\nimport org.jclouds.ec2.binders.BindGroupNamesToIndexedFormParams;\nimport org.jclouds.ec2.binders.BindIpPermissionToIndexedFormParams;\nimport org.jclouds.ec2.binders.BindIpPermissionsToIndexedFormParams;\nimport org.jclouds.ec2.domain.SecurityGroup;\nimport org.jclouds.ec2.features.SecurityGroupApi;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.location.functions.RegionToEndpointOrProviderIfNull;\nimport org.jclouds.net.domain.IpPermission;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.EndpointParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.FormParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.VirtualHost;\nimport org.jclouds.rest.annotations.XMLResponseParser;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.collect.Multimap;\n\n/**\n * Provides access to EC2 SecurityGroup Services via their REST API.\n * <p/>\n */\n@RequestFilters(FormSigner.class)\n@VirtualHost\n@Beta\npublic interface AWSSecurityGroupApi extends SecurityGroupApi {\n\n   @Named(\"CreateSecurityGroup\")\n   @POST\n   @Path(\"/\")\n   @XMLResponseParser(CreateSecurityGroupResponseHandler.class)\n   @FormParams(keys = ACTION, values = \"CreateSecurityGroup\")\n   String createSecurityGroupInRegionAndReturnId(\n         @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n         @FormParam(\"GroupName\") String name, @FormParam(\"GroupDescription\") String description,\n         CreateSecurityGroupOptions... options);\n\n   @Named(\"AuthorizeSecurityGroupIngress\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"AuthorizeSecurityGroupIngress\")\n   void authorizeSecurityGroupIngressInRegion(\n         @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n         @FormParam(\"GroupId\") String groupId, @BinderParam(BindIpPermissionToIndexedFormParams.class) IpPermission perm);\n\n   @Named(\"AuthorizeSecurityGroupIngress\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"AuthorizeSecurityGroupIngress\")\n   void authorizeSecurityGroupIngressInRegion(\n         @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n         @FormParam(\"GroupId\") String groupId,\n         @BinderParam(BindIpPermissionsToIndexedFormParams.class) Iterable<IpPermission> perms);\n\n   @Named(\"RevokeSecurityGroupIngress\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"RevokeSecurityGroupIngress\")\n   void revokeSecurityGroupIngressInRegion(\n         @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n         @FormParam(\"GroupId\") String groupId, @BinderParam(BindIpPermissionToIndexedFormParams.class) IpPermission perm);\n\n   @Named(\"RevokeSecurityGroupIngress\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"RevokeSecurityGroupIngress\")\n   void revokeSecurityGroupIngressInRegion(\n         @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n         @FormParam(\"GroupId\") String groupId,\n         @BinderParam(BindIpPermissionsToIndexedFormParams.class) Iterable<IpPermission> perms);\n\n   @Named(\"DeleteSecurityGroup\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DeleteSecurityGroup\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void deleteSecurityGroupInRegionById(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region, @FormParam(\"GroupId\") String name);\n\n   @Named(\"DescribeSecurityGroups\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DescribeSecurityGroups\")\n   @XMLResponseParser(AWSEC2DescribeSecurityGroupsResponseHandler.class)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<SecurityGroup> describeSecurityGroupsInRegionById(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n            @BinderParam(BindGroupIdsToIndexedFormParams.class) String... securityGroupNames);\n\n   @Named(\"DescribeSecurityGroups\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DescribeSecurityGroups\")\n   @XMLResponseParser(AWSEC2DescribeSecurityGroupsResponseHandler.class)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<SecurityGroup> describeSecurityGroupsInRegion(\n           @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n           @BinderParam(BindGroupNamesToIndexedFormParams.class) String... securityGroupNames);\n\n   @Named(\"DescribeSecurityGroups\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DescribeSecurityGroups\")\n   @XMLResponseParser(AWSEC2DescribeSecurityGroupsResponseHandler.class)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<SecurityGroup> describeSecurityGroupsInRegion(\n           @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region);\n   \n   @Named(\"DescribeSecurityGroups\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DescribeSecurityGroups\")\n   @XMLResponseParser(AWSEC2DescribeSecurityGroupsResponseHandler.class)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<SecurityGroup> describeSecurityGroupsInRegionWithFilter(\n           @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n           @BinderParam(BindFiltersToIndexedFormParams.class) Multimap<String, String> filter);\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/features/AWSSubnetApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.features;\n\nimport static org.jclouds.aws.reference.FormParameters.ACTION;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.FormParam;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\n\nimport org.jclouds.Fallbacks;\nimport org.jclouds.aws.ec2.options.CreateSubnetOptions;\nimport org.jclouds.aws.ec2.options.ModifySubnetAttributeOptions;\nimport org.jclouds.aws.ec2.xml.ReturnValueHandler;\nimport org.jclouds.aws.filters.FormSigner;\nimport org.jclouds.ec2.binders.BindFiltersToIndexedFormParams;\nimport org.jclouds.ec2.binders.BindSubnetIdsToIndexedFormParams;\nimport org.jclouds.ec2.domain.Subnet;\nimport org.jclouds.ec2.features.SubnetApi;\nimport org.jclouds.ec2.xml.DescribeSubnetsResponseHandler;\nimport org.jclouds.ec2.xml.SubnetHandler;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.location.functions.RegionToEndpointOrProviderIfNull;\nimport org.jclouds.rest.annotations.ApiVersionOverride;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.EndpointParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.FormParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SinceApiVersion;\nimport org.jclouds.rest.annotations.VirtualHost;\nimport org.jclouds.rest.annotations.XMLResponseParser;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.Multimap;\n\n/**\n * Provides access to Amazon EC2 via the Query API\n * <p/>\n *\n * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeSubnets.html\"\n * >doc</a>\n */\n@SinceApiVersion(\"2011-01-01\")\n@RequestFilters(FormSigner.class)\n@VirtualHost\npublic interface AWSSubnetApi extends SubnetApi {\n\n   /**\n    * Creates a subnet in an existing VPC.\n    *\n    * @param region\n    * @param vpcId     The ID of the VPC.\n    * @param cidrBlock The network range for the subnet, in CIDR notation. For example, 10.0.0.0/24.\n    * @param options\n    * @return AWS Subnet\n    */\n   @Named(\"CreateSubnet\")\n   @POST\n   @Path(\"/\")\n   @XMLResponseParser(SubnetHandler.class)\n   @FormParams(keys = ACTION, values = \"CreateSubnet\")\n   Subnet createSubnetInRegion(\n           @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n           @FormParam(\"VpcId\") String vpcId, @FormParam(\"CidrBlock\") String cidrBlock,\n           CreateSubnetOptions... options);\n\n   /**\n    * Deletes a subnet.\n    *\n    * @param region\n    * @param subnetId\n    * @see <a href=\"http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DeleteSubnet.html\"\n    * >doc</a>\n    */\n   @Named(\"DeleteSubnet\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DeleteSubnet\")\n   void deleteSubnetInRegion(\n         @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n           @FormParam(\"SubnetId\") String subnetId);\n\n   /**\n    * Describes one or more of your subnets.\n    *\n    * @param region       Subnet are Region-specific.\n    * @param subnetIds    Subnet to describe.\n    * @see <a href=\"http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeSubnets.html\"\n    * >doc</a>\n    */\n   @Named(\"DescribeSubnets\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DescribeSubnets\")\n   @XMLResponseParser(DescribeSubnetsResponseHandler.class)\n   @Fallback(Fallbacks.EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<Subnet> describeSubnetsInRegion(\n           @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n           @BinderParam(BindSubnetIdsToIndexedFormParams.class) String... subnetIds);\n\n   /**\n    * Returns information about subnets available to you. If you specify filters,\n    * information about subnets matching those filters is returned. Otherwise, all\n    * subnets you have access to are returned.\n    *\n    * @param region Subnets are Region-specific.\n    * @param filter Multimap of filter key/values.\n    * @see <a href=\"http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeSubnets.html\"\n    * >doc</a>\n    */\n   @Named(\"DescribeSubnets\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DescribeSubnets\")\n   @XMLResponseParser(DescribeSubnetsResponseHandler.class)\n   @Fallback(Fallbacks.EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<Subnet> describeSubnetsInRegionWithFilter(\n           @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n           @BinderParam(BindFiltersToIndexedFormParams.class) Multimap<String, String> filter);\n\n   /**\n    * Modifies a subnet attribute. You can only modify one attribute at a time.\n    *\n    * @param region The region for the subnet\n    * @param subnetId The ID of the subnet\n    * @param options The options containing the attribute to modify. You can only modify one attribute at a time.\n    * @return true if the modification was successful\n    */\n   @ApiVersionOverride(\"2014-06-15\")\n   @Named(\"ModifySubnetAttribute\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"ModifySubnetAttribute\")\n   @XMLResponseParser(ReturnValueHandler.class)\n   @Fallback(Fallbacks.FalseOnNotFoundOr404.class)\n   boolean modifySubnetAttribute(\n      @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n      @FormParam(\"SubnetId\") String subnetId,\n      ModifySubnetAttributeOptions options);\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/features/InternetGatewayApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.features;\n\nimport static org.jclouds.aws.reference.FormParameters.ACTION;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.FormParam;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\n\nimport org.jclouds.Fallbacks.EmptyFluentIterableOnNotFoundOr404;\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.aws.ec2.binders.BindInternetGatewayIdsToIndexedFormParams;\nimport org.jclouds.aws.ec2.domain.InternetGateway;\nimport org.jclouds.aws.ec2.options.InternetGatewayOptions;\nimport org.jclouds.aws.ec2.xml.DescribeInternetGatewaysResponseHandler;\nimport org.jclouds.aws.ec2.xml.InternetGatewayHandler;\nimport org.jclouds.aws.ec2.xml.ReturnValueHandler;\nimport org.jclouds.aws.filters.FormSigner;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.location.functions.RegionToEndpointOrProviderIfNull;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.EndpointParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.FormParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.VirtualHost;\nimport org.jclouds.rest.annotations.XMLResponseParser;\n\nimport com.google.common.collect.FluentIterable;\n\n/**\n * Provides access to InternetGateway Services.\n *\n * @see <a href=\"http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_InternetGateway.html\">InternetGateway docs</a>\n * <p/>\n */\n@RequestFilters(FormSigner.class)\n@VirtualHost\n@Path(\"/\")\npublic interface InternetGatewayApi {\n\n   /**\n    * Detaches an {@link InternetGateway} from a {@link org.jclouds.aws.ec2.domain.VPC}\n    *\n    * @param region Region where the VPC exists\n    * @param internetGatewayId ID of the gateway to detach\n    * @param vpcId The ID of the VPC\n    */\n   @Named(\"DetachInternetGateway\")\n   @POST\n   @FormParams(keys = ACTION, values = \"DetachInternetGateway\")\n   @XMLResponseParser(ReturnValueHandler.class)\n   @Fallback(FalseOnNotFoundOr404.class)\n   Boolean detachInternetGateway(\n      @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n      @FormParam(\"InternetGatewayId\") String internetGatewayId,\n      @FormParam(\"VpcId\") String vpcId);\n\n   /**\n    * Detaches an {@link InternetGateway} from a {@link org.jclouds.aws.ec2.domain.VPC}, supplying options.\n    *\n    * @param region Region where the VPC exists\n    * @param internetGatewayId ID of the gateway to detach\n    * @param vpcId The ID of the VPC\n    * @param options Options for the request\n    */\n   @Named(\"DetachInternetGateway\")\n   @POST\n   @FormParams(keys = ACTION, values = \"DetachInternetGateway\")\n   @XMLResponseParser(ReturnValueHandler.class)\n   @Fallback(FalseOnNotFoundOr404.class)\n   Boolean detachInternetGateway(\n      @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n      @FormParam(\"InternetGatewayId\") String internetGatewayId,\n      @FormParam(\"VpcId\") String vpcId,\n      InternetGatewayOptions options);\n\n   /**\n    * Attaches an {@link InternetGateway} to a {@link org.jclouds.aws.ec2.domain.VPC}\n    *\n    * @param region Region where the VPC exists\n    * @param internetGatewayId ID of the gateway to attach\n    * @param vpcId The ID of the VPC\n    */\n   @Named(\"AttachInternetGateway\")\n   @POST\n   @FormParams(keys = ACTION, values = \"AttachInternetGateway\")\n   @XMLResponseParser(ReturnValueHandler.class)\n   @Fallback(FalseOnNotFoundOr404.class)\n   Boolean attachInternetGateway(\n      @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n      @FormParam(\"InternetGatewayId\") String internetGatewayId,\n      @FormParam(\"VpcId\") String vpcId);\n\n   /**\n    * Attaches an {@link InternetGateway} to a {@link org.jclouds.aws.ec2.domain.VPC}, supplying options.\n    *\n    * @param region Region where the VPC exists\n    * @param internetGatewayId ID of the gateway to attach\n    * @param vpcId The ID of the VPC\n    * @param options Options for the request\n    */\n   @Named(\"AttachInternetGateway\")\n   @POST\n   @FormParams(keys = ACTION, values = \"AttachInternetGateway\")\n   @XMLResponseParser(ReturnValueHandler.class)\n   @Fallback(FalseOnNotFoundOr404.class)\n   Boolean attachInternetGateway(\n      @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n      @FormParam(\"InternetGatewayId\") String internetGatewayId,\n      @FormParam(\"VpcId\") String vpcId,\n      InternetGatewayOptions options);\n\n   /**\n    * Creates an {@link InternetGateway}\n    *\n    * @param region The region to create the gateway in.\n    */\n   @Named(\"CreateInternetGateway\")\n   @POST\n   @FormParams(keys = ACTION, values = \"CreateInternetGateway\")\n   @XMLResponseParser(InternetGatewayHandler.class)\n   InternetGateway createInternetGateway(\n      @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region);\n\n   /**\n    * Creates an {@link InternetGateway}, supplying options.\n    *\n    * @param region The region to create the gateway in\n    * @param options Options for the request\n    */\n   @Named(\"CreateInternetGateway\")\n   @POST\n   @FormParams(keys = ACTION, values = \"CreateInternetGateway\")\n   @XMLResponseParser(InternetGatewayHandler.class)\n   InternetGateway createInternetGateway(\n      @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n      InternetGatewayOptions options);\n\n   /**\n    * Deletes an {@code InternetGateway}.\n    *\n    * @param region gateways are tied to the Region where its files are located within Amazon S3.\n    * @param internetGatewayId  The gateway ID.\n    */\n   @Named(\"DeleteInternetGateway\")\n   @POST\n   @FormParams(keys = ACTION, values = \"DeleteInternetGateway\")\n   @XMLResponseParser(ReturnValueHandler.class)\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean deleteInternetGateway(\n      @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n      @FormParam(\"InternetGatewayId\") String internetGatewayId);\n\n   /**\n    * Deletes an {@code InternetGateway}, supplying options.\n    *\n    * @param region gateways are tied to the Region where its files are located within Amazon S3.\n    * @param internetGatewayId  The gateway ID.\n    * @param options Options for the request\n    */\n   @Named(\"DeleteInternetGateway\")\n   @POST\n   @FormParams(keys = ACTION, values = \"DeleteInternetGateway\")\n   @XMLResponseParser(ReturnValueHandler.class)\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean deleteInternetGateway(\n      @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n      @FormParam(\"InternetGatewayId\") String internetGatewayId,\n      InternetGatewayOptions options);\n\n   /**\n    * Describes {@link InternetGateway}s.\n    *\n    * @return InternetGateways or empty if there are none.\n    *\n    * @param region The region to search for gateways.\n    * @param internetGatewayIds Optional list of known gateway ids to restrict the search\n    */\n   @Named(\"DescribeInternetGateways\")\n   @POST\n   @FormParams(keys = ACTION, values = \"DescribeInternetGateways\")\n   @XMLResponseParser(DescribeInternetGatewaysResponseHandler.class)\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<InternetGateway> describeInternetGatewaysInRegion(\n      @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n      @BinderParam(BindInternetGatewayIdsToIndexedFormParams.class) String... internetGatewayIds);\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/features/MonitoringApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.features;\n\nimport static org.jclouds.aws.reference.FormParameters.ACTION;\n\nimport java.util.Map;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.FormParam;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\n\nimport org.jclouds.aws.ec2.domain.MonitoringState;\nimport org.jclouds.aws.ec2.xml.MonitoringStateHandler;\nimport org.jclouds.aws.filters.FormSigner;\nimport org.jclouds.ec2.binders.BindInstanceIdsToIndexedFormParams;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.location.functions.RegionToEndpointOrProviderIfNull;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.EndpointParam;\nimport org.jclouds.rest.annotations.FormParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.VirtualHost;\nimport org.jclouds.rest.annotations.XMLResponseParser;\n\n/**\n * Provides access to EC2 Monitoring Services via their REST API.\n * <p/>\n */\n@RequestFilters(FormSigner.class)\n@VirtualHost\npublic interface MonitoringApi {\n\n   /**\n    * Enables monitoring for a running instance. For more information, refer to the Amazon\n    * CloudWatch Developer Guide.\n    * \n    * @param region\n    *           Instances are tied to Availability Zones. However, the instance ID is tied to the\n    *           Region.\n    * @see InstanceApi#runInstances\n    * @see #unmonitorInstances\n    * \n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-MonitorInstances.html\"\n    *      />\n    */\n   @Named(\"MonitorInstances\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"MonitorInstances\")\n   @XMLResponseParser(MonitoringStateHandler.class)\n   Map<String, MonitoringState> monitorInstancesInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n            @FormParam(\"InstanceId.0\") String instanceId,\n            @BinderParam(BindInstanceIdsToIndexedFormParams.class) String... instanceIds);\n\n   /**\n    * Disables monitoring for a running instance. For more information, refer to the Amazon\n    * CloudWatch Developer Guide.\n    * \n    * @param region\n    *           Instances are tied to Availability Zones. However, the instance ID is tied to the\n    *           Region.\n    * \n    * @see InstanceApi#runInstances\n    * @see #monitorInstances\n    * \n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-UnmonitorInstances.html\"\n    *      />\n    */\n   @Named(\"UnmonitorInstances\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"UnmonitorInstances\")\n   @XMLResponseParser(MonitoringStateHandler.class)\n   Map<String, MonitoringState> unmonitorInstancesInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n            @FormParam(\"InstanceId.0\") String instanceId,\n            @BinderParam(BindInstanceIdsToIndexedFormParams.class) String... instanceIds);\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/features/PlacementGroupApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.features;\n\nimport static org.jclouds.aws.reference.FormParameters.ACTION;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.FormParam;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.aws.ec2.domain.PlacementGroup;\nimport org.jclouds.aws.ec2.xml.DescribePlacementGroupsResponseHandler;\nimport org.jclouds.aws.filters.FormSigner;\nimport org.jclouds.ec2.binders.BindFiltersToIndexedFormParams;\nimport org.jclouds.ec2.binders.BindGroupNamesToIndexedFormParams;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.location.functions.RegionToEndpointOrProviderIfNull;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.EndpointParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.FormParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.VirtualHost;\nimport org.jclouds.rest.annotations.XMLResponseParser;\n\nimport com.google.common.collect.Multimap;\n\n/**\n * Provides access to EC2 Placement Groups via their REST API.\n * <p/>\n */\n@RequestFilters(FormSigner.class)\n@VirtualHost\npublic interface PlacementGroupApi {\n\n   /**\n    * Creates a placement group that you launch cluster compute instances into. You must give the\n    * group a name unique within the scope of your account.\n    * \n    * @param region\n    *           Region to create the placement group in.\n    * @param name\n    *           The name of the placement group..\n    * @param strategy\n    *           The placement group strategy.\n    * @see #describePlacementGroupsInRegion\n    * @see #deletePlacementGroupInRegion\n    * \n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CreatePlacementGroup.html\"\n    *      />\n    */\n   @Named(\"CreatePlacementGroup\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"CreatePlacementGroup\")\n   void createPlacementGroupInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n            @FormParam(\"GroupName\") String name, @FormParam(\"Strategy\") String strategy);\n\n   /**\n    * like {@link #createPlacementGroupInRegion(String,String,String) except that the strategy is default: \"cluster\".\n    */\n   @Named(\"CreatePlacementGroup\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = { ACTION, \"Strategy\" }, values = { \"CreatePlacementGroup\", \"cluster\" })\n   void createPlacementGroupInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region, @FormParam(\"GroupName\") String name);\n\n   /**\n    * Deletes a placement group from your account. You must terminate all instances in the placement group before deleting it.\n    * \n    * @param region\n    *           Region to delete the placement from from\n    * @param name\n    *           Name of the security group to delete.\n    * \n    * @see #describePlacementGroupsInRegion\n    * @see #createPlacementGroupInRegion\n    * \n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DeletePlacementGroup.html\"\n    *      />\n    */\n   @Named(\"DeletePlacementGroup\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DeletePlacementGroup\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void deletePlacementGroupInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region, @FormParam(\"GroupName\") String name);\n\n   /**\n    * \n    * Returns information about one or more placement groups in your account.\n    * \n    * @param region\n    *           The bundleTask ID is tied to the Region.\n    * @param groupNames\n    *           The name of the placement group. You can specify more than one in the request, or\n    *           omit the parameter if you want information about all your placement groups. By\n    *           default, all placement groups are described\n    * \n    * @see #deletePlacementGroupInRegion\n    * @see #createPlacementGroupInRegion\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribePlacementGroups.html\"\n    *      />\n    */\n   @Named(\"DescribePlacementGroups\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DescribePlacementGroups\")\n   @XMLResponseParser(DescribePlacementGroupsResponseHandler.class)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<PlacementGroup> describePlacementGroupsInRegion(\n            @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n            @BinderParam(BindGroupNamesToIndexedFormParams.class) String... placementGroupIds);\n\n   /**\n    *\n    * Returns information about one or more placement groups in your account.\n    *\n    * @param region\n    *           The bundleTask ID is tied to the Region.\n    * @param filter\n    *           Multimap of filter key/values\n    *\n    * @see #deletePlacementGroupInRegion\n    * @see #createPlacementGroupInRegion\n    * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribePlacementGroups.html\"\n    *      />\n    */\n   @Named(\"DescribePlacementGroups\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DescribePlacementGroups\")\n   @XMLResponseParser(DescribePlacementGroupsResponseHandler.class)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<PlacementGroup> describePlacementGroupsInRegionWithFilter(\n           @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n           @BinderParam(BindFiltersToIndexedFormParams.class) Multimap<String, String> filter);\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/features/RouteTableApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.features;\n\nimport static org.jclouds.aws.reference.FormParameters.ACTION;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.FormParam;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\n\nimport org.jclouds.Fallbacks;\nimport org.jclouds.aws.ec2.binders.BindRouteTableIdsToIndexedFormParams;\nimport org.jclouds.aws.ec2.domain.RouteTable;\nimport org.jclouds.aws.ec2.options.RouteOptions;\nimport org.jclouds.aws.ec2.options.RouteTableOptions;\nimport org.jclouds.aws.ec2.xml.AssociateRouteTableResponseHandler;\nimport org.jclouds.aws.ec2.xml.CreateRouteTableResponseHandler;\nimport org.jclouds.aws.ec2.xml.DescribeRouteTablesResponseHandler;\nimport org.jclouds.aws.ec2.xml.ReturnValueHandler;\nimport org.jclouds.aws.filters.FormSigner;\nimport org.jclouds.ec2.binders.BindFiltersToIndexedFormParams;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.location.functions.RegionToEndpointOrProviderIfNull;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.EndpointParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.FormParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.VirtualHost;\nimport org.jclouds.rest.annotations.XMLResponseParser;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.Multimap;\n\n/**\n * Provides access to AWS Route Table services.\n *\n * @see <a href=\"http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RouteTable.html\">RouteTable docs</a>\n */\n@RequestFilters(FormSigner.class)\n@VirtualHost\n@Path(\"/\")\npublic interface RouteTableApi {\n\n   /**\n    * Creates a {@link RouteTable}\n    *\n    * @param region The region to create the table in.\n    * @param vpcId The ID of the VPC\n    * @return The route table\n    */\n   @Named(\"CreateRouteTable\")\n   @POST\n   @FormParams(keys = ACTION, values = \"CreateRouteTable\")\n   @XMLResponseParser(CreateRouteTableResponseHandler.class)\n   RouteTable createRouteTable(\n      @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n      @FormParam(\"VpcId\") String vpcId);\n\n   /**\n    * Creates a {@link RouteTable}, supplying options.\n    *\n    * @param region  The region to create the table in\n    * @param vpcId The ID of the VPC\n    * @param options Options for the request\n    * @return The route table\n    */\n   @Named(\"CreateRouteTable\")\n   @POST\n   @FormParams(keys = ACTION, values = \"CreateRouteTable\")\n   @XMLResponseParser(CreateRouteTableResponseHandler.class)\n   RouteTable createRouteTable(\n      @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n      @FormParam(\"VpcId\") String vpcId,\n      RouteTableOptions options);\n\n   /**\n    * Deletes a {@link RouteTable}\n    *\n    * @param region The region to delete the table from\n    * @param routeTableId The ID of the table to delete\n    * @return true if the route table was found and deleted\n    */\n   @Named(\"DeleteRouteTable\")\n   @POST\n   @FormParams(keys = ACTION, values = \"DeleteRouteTable\")\n   @XMLResponseParser(ReturnValueHandler.class)\n   @Fallback(Fallbacks.FalseOnNotFoundOr404.class)\n   boolean deleteRouteTable(\n      @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n      @FormParam(\"RouteTableId\") String routeTableId);\n\n   /**\n    * Delete a {@link RouteTable}, supplying options.\n    *\n    * @param region  The region to delete the table from\n    * @param routeTableId The ID of the table to delete\n    * @param options Options for the request\n    * @return true if the route table was found and deleted\n    */\n   @Named(\"DeleteRouteTable\")\n   @POST\n   @FormParams(keys = ACTION, values = \"DeleteRouteTable\")\n   @XMLResponseParser(ReturnValueHandler.class)\n   @Fallback(Fallbacks.FalseOnNotFoundOr404.class)\n   boolean deleteRouteTable(\n      @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n      @FormParam(\"RouteTableId\") String routeTableId,\n      RouteTableOptions options);\n\n   /**\n    * Associates a subnet with a route table. The subnet and route table must be in the same VPC.\n    * This association causes traffic originating from the subnet to be routed according to the routes in the route table.\n    * The action returns an association ID, which you need in order to disassociate the route table from the subnet later.\n    * A route table can be associated with multiple subnets.\n    *\n    * @param region Region of the VPC for the route table\n    * @param routeTableId ID of the route table\n    * @param subnetId ID of the subnet to associate\n    *\n    * @return The association ID which you need in order to disassociate the route table from the subnet later.\n    */\n   @Named(\"AssociateRouteTable\")\n   @POST\n   @FormParams(keys = ACTION, values = \"AssociateRouteTable\")\n   @XMLResponseParser(AssociateRouteTableResponseHandler.class)\n   @Fallback(Fallbacks.NullOnNotFoundOr404.class)\n   String associateRouteTable(\n      @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n      @FormParam(\"RouteTableId\") String routeTableId,\n      @FormParam(\"SubnetId\") String subnetId);\n\n   /**\n    * @see #associateRouteTable(java.lang.String, java.lang.String, java.lang.String)\n    *\n    * @param region Region of the VPC for the route table\n    * @param routeTableId ID of the route table\n    * @param subnetId ID of the subnet to associate\n    * @param options Options for the request\n    *\n    * @return The association ID which you need in order to disassociate the route table from the subnet later.\n    */\n   @Named(\"AssociateRouteTable\")\n   @POST\n   @FormParams(keys = ACTION, values = \"AssociateRouteTable\")\n   @XMLResponseParser(AssociateRouteTableResponseHandler.class)\n   @Fallback(Fallbacks.NullOnNotFoundOr404.class)\n   String associateRouteTable(\n      @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n      @FormParam(\"RouteTableId\") String routeTableId,\n      @FormParam(\"SubnetId\") String subnetId,\n      RouteTableOptions options);\n\n   /**\n    * Disassociates a subnet from a route table.\n    * After you perform this action, the subnet no longer uses the routes in the route table.\n    * Instead, it uses the routes in the VPC's main route table.\n    * @param region Region of the route table\n    * @param associationId association id returned by {@link #associateRouteTable(String, String, String)}\n    * @return true if the subnet was found and disassociated.\n    */\n   @Named(\"DisassociateRouteTable\")\n   @POST\n   @FormParams(keys = ACTION, values = \"DisassociateRouteTable\")\n   @XMLResponseParser(ReturnValueHandler.class)\n   @Fallback(Fallbacks.FalseOnNotFoundOr404.class)\n   boolean disassociateRouteTable(\n      @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n      @FormParam(\"AssociationId\") String associationId);\n\n   /**\n    * @see #disassociateRouteTable(String, String)\n    * @param region Region of the route table\n    * @param associationId association id returned by {@link #associateRouteTable(String, String, String)}\n    * @param options Options for the request\n    * @return true if the subnet was found and disassociated.\n    */\n   @Named(\"DisassociateRouteTable\")\n   @POST\n   @FormParams(keys = ACTION, values = \"DisassociateRouteTable\")\n   @XMLResponseParser(ReturnValueHandler.class)\n   @Fallback(Fallbacks.FalseOnNotFoundOr404.class)\n   boolean disassociateRouteTable(\n      @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n      @FormParam(\"AssociationId\") String associationId,\n      RouteTableOptions options);\n\n   /**\n    * Creates a route in a route table within a VPC.\n    *\n    * @param region region of the VPC\n    * @param routeTableId ID of the route table to put the route in\n    * @param options You must specify one of the following targets: Internet gateway or virtual\n    *                private gateway, NAT instance, NAT gateway, VPC peering connection,\n    *                network interface, or egress-only Internet gateway.\n    * @return true if the route was created\n    */\n   @Named(\"CreateRoute\")\n   @POST\n   @FormParams(keys = ACTION, values = \"CreateRoute\")\n   @XMLResponseParser(ReturnValueHandler.class)\n   @Fallback(Fallbacks.FalseOnNotFoundOr404.class)\n   boolean createRoute(\n      @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n      @FormParam(\"RouteTableId\") String routeTableId,\n      RouteOptions options);\n\n   /**\n    * Replaces a route in a route table within a VPC.\n    *\n    * @param region region of the VPC\n    * @param routeTableId ID of the route table containing the route to replace\n    * @param options You must specify only one of the following targets: Internet gateway or virtual\n    *                private gateway, NAT instance, NAT gateway, VPC peering connection,\n    *                network interface, or egress-only Internet gateway.\n    * @return true if the route was found and replaced\n    */\n   @Named(\"ReplaceRoute\")\n   @POST\n   @FormParams(keys = ACTION, values = \"ReplaceRoute\")\n   @XMLResponseParser(ReturnValueHandler.class)\n   @Fallback(Fallbacks.FalseOnNotFoundOr404.class)\n   boolean replaceRoute(\n      @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n      @FormParam(\"RouteTableId\") String routeTableId,\n      RouteOptions options);\n\n   /**\n    * Delete a route from a route table.\n    *\n    * @param region region of the VPC\n    * @param routeTableId ID of the route table owning the route\n    * @param options This should include the destination CIDR block of the route to delete\n    *\n    * @return true if the route was found and deleted\n    *\n    * <p>\n    * <b>Example:</b>\n    * <pre>\n    *    api.deleteRoute(region, routeTable.id(), destinationCidrBlock(\"10.20.30.0/24\"))\n    * </pre>\n    * </p>\n    */\n   @Named(\"DeleteRoute\")\n   @POST\n   @FormParams(keys = ACTION, values = \"DeleteRoute\")\n   @XMLResponseParser(ReturnValueHandler.class)\n   @Fallback(Fallbacks.FalseOnNotFoundOr404.class)\n   boolean deleteRoute(\n      @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n      @FormParam(\"RouteTableId\") String routeTableId,\n      RouteOptions options);\n\n   /**\n    * Describes route tables.\n    * @param region The region to search for route tables.\n    * @param routeTableIds One or more identifiers for existing RouteTable instances\n    *\n    * @return a set of RouteTable objects that matched the routeTableIds passed\n    *\n    */\n   @Named(\"DescribeRouteTables\")\n   @POST\n   @FormParams(keys = ACTION, values = \"DescribeRouteTables\")\n   @XMLResponseParser(DescribeRouteTablesResponseHandler.class)\n   @Fallback(Fallbacks.EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<RouteTable> describeRouteTables(\n      @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n      @BinderParam(BindRouteTableIdsToIndexedFormParams.class) String... routeTableIds);\n\n   /**\n    * Describes route tables.\n    * @param region The region to search for route tables.\n    * @param filter One or more filters utilized to search for RouteTable instances\n    *\n    * @link <a href=\"https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeRouteTables.html\">...</a>\n    */\n   @Named(\"DescribeRouteTables\")\n   @POST\n   @FormParams(keys = ACTION, values = \"DescribeRouteTables\")\n   @XMLResponseParser(DescribeRouteTablesResponseHandler.class)\n   @Fallback(Fallbacks.EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<RouteTable> describeRouteTablesWithFilter(\n           @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n           @BinderParam(BindFiltersToIndexedFormParams.class) Multimap<String, String> filter);\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/features/SpotInstanceApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.features;\n\nimport static org.jclouds.aws.reference.FormParameters.ACTION;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.FormParam;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.aws.ec2.binders.BindLaunchSpecificationToFormParams;\nimport org.jclouds.aws.ec2.binders.BindSpotInstanceRequestIdsToIndexedFormParams;\nimport org.jclouds.aws.ec2.domain.LaunchSpecification;\nimport org.jclouds.aws.ec2.domain.Spot;\nimport org.jclouds.aws.ec2.domain.SpotInstanceRequest;\nimport org.jclouds.aws.ec2.options.DescribeSpotPriceHistoryOptions;\nimport org.jclouds.aws.ec2.options.RequestSpotInstancesOptions;\nimport org.jclouds.aws.ec2.xml.DescribeSpotPriceHistoryResponseHandler;\nimport org.jclouds.aws.ec2.xml.SpotInstanceHandler;\nimport org.jclouds.aws.ec2.xml.SpotInstancesHandler;\nimport org.jclouds.aws.filters.FormSigner;\nimport org.jclouds.ec2.binders.BindFiltersToIndexedFormParams;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.location.functions.RegionToEndpointOrProviderIfNull;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.EndpointParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.FormParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.VirtualHost;\nimport org.jclouds.rest.annotations.XMLResponseParser;\n\nimport com.google.common.collect.Multimap;\n\n/**\n * Provides access to EC2 Spot Instances via their REST API.\n * <p/>\n */\n@RequestFilters(FormSigner.class)\n@VirtualHost\npublic interface SpotInstanceApi {\n\n   /**\n    * Describes Spot Instance requests. Spot Instances are instances that Amazon EC2 starts on your\n    * behalf when the maximum price that you specify exceeds the current Spot Price. Amazon EC2\n    * periodically sets the Spot Price based on available Spot Instance capacity and current spot\n    * instance requests. For conceptual information about Spot Instances, refer to the Amazon\n    * Elastic Compute Cloud Developer Guide or Amazon Elastic Compute Cloud User Guide.\n    * \n    * @param region\n    *           Region where the spot instance service is running\n    * @param requestIds\n    *           Specifies the ID of the Spot Instance request.\n    * \n    * @see #requestSpotInstancesInRegion\n    * @see #cancelSpotInstanceRequestsInRegion\n    * @see #describeSpotPriceHistoryInRegion\n    * @see <a href=\n    *      \"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeSpotInstanceRequests.html\"\n    *      />\n    * @return TODO\n    */\n   @Named(\"DescribeSpotInstanceRequests\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DescribeSpotInstanceRequests\")\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   @XMLResponseParser(SpotInstancesHandler.class)\n   Set<SpotInstanceRequest> describeSpotInstanceRequestsInRegion(\n         @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n         @BinderParam(BindSpotInstanceRequestIdsToIndexedFormParams.class) String... requestIds);\n\n   /**\n    * Describes Spot Instance requests. Spot Instances are instances that Amazon EC2 starts on your\n    * behalf when the maximum price that you specify exceeds the current Spot Price. Amazon EC2\n    * periodically sets the Spot Price based on available Spot Instance capacity and current spot\n    * instance requests. For conceptual information about Spot Instances, refer to the Amazon\n    * Elastic Compute Cloud Developer Guide or Amazon Elastic Compute Cloud User Guide.\n    *\n    * @param region\n    *           Region where the spot instance service is running\n    * @param filter\n    *           Mulitmap of filter key/values.\n    *\n    * @see #requestSpotInstancesInRegion\n    * @see #cancelSpotInstanceRequestsInRegion\n    * @see #describeSpotPriceHistoryInRegion\n    * @see <a href=\n    *      \"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeSpotInstanceRequests.html\"\n    *      />\n    * @return TODO\n    */\n   @Named(\"DescribeSpotInstanceRequests\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DescribeSpotInstanceRequests\")\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   @XMLResponseParser(SpotInstancesHandler.class)\n   Set<SpotInstanceRequest> describeSpotInstanceRequestsInRegionWithFilter(\n           @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n           @BinderParam(BindFiltersToIndexedFormParams.class) Multimap<String, String> filter);\n\n   /**\n    * request a single spot instance\n    * \n    * @param region\n    *           Region where the spot instance service is running\n    * @param spotPrice\n    *           Specifies the maximum hourly price for any Spot Instance launched to fulfill the\n    *           request.\n    * @param imageId\n    *           The AMI ID.\n    * @param instanceType\n    *           The instance type (ex. m1.small)\n    * @return spot instance request\n    * @see #requestSpotInstancesInRegion\n    */\n   @Named(\"RequestSpotInstances\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"RequestSpotInstances\")\n   @XMLResponseParser(SpotInstanceHandler.class)\n   SpotInstanceRequest requestSpotInstanceInRegion(\n         @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n         @FormParam(\"SpotPrice\") float spotPrice, @FormParam(\"LaunchSpecification.ImageId\") String imageId,\n         @FormParam(\"LaunchSpecification.InstanceType\") String instanceType);\n\n   /**\n    * Creates a Spot Instance request. Spot Instances are instances that Amazon EC2 starts on your\n    * behalf when the maximum price that you specify exceeds the current Spot Price. Amazon EC2\n    * periodically sets the Spot Price based on available Spot Instance capacity and current spot\n    * instance requests. For conceptual information about Spot Instances, refer to the Amazon\n    * Elastic Compute Cloud Developer Guide or Amazon Elastic Compute Cloud User Guide.\n    * \n    * @param region\n    *           Region where the spot instance service is running\n    * @param spotPrice\n    *           Specifies the maximum hourly price for any Spot Instance launched to fulfill the\n    *           request.\n    * @param instanceCount\n    *           number of instances to request\n    * @param launchSpec\n    *           includes at least The AMI ID and instance type (ex. m1.small)\n    * @param options\n    *           options including expiration time or grouping\n    * \n    * @see #describeSpotInstanceRequestsInRegion\n    * @see #cancelSpotInstanceRequestsInRegion\n    * @see #describeSpotPriceHistoryInRegion\n    * @see <a href=\n    *      \"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-RequestSpotInstances.html\"\n    *      />\n    * @return set of spot instance requests\n    */\n   @Named(\"RequestSpotInstances\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"RequestSpotInstances\")\n   @XMLResponseParser(SpotInstancesHandler.class)\n   Set<SpotInstanceRequest> requestSpotInstancesInRegion(\n         @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n         @FormParam(\"SpotPrice\") float spotPrice, @FormParam(\"InstanceCount\") int instanceCount,\n         @BinderParam(BindLaunchSpecificationToFormParams.class) LaunchSpecification launchSpec,\n         RequestSpotInstancesOptions... options);\n\n   /**\n    * \n    * Describes Spot Price history. Spot Instances are instances that Amazon EC2 starts on your\n    * behalf when the maximum price that you specify exceeds the current Spot Price. Amazon EC2\n    * periodically sets the Spot Price based on available Spot Instance capacity and current spot\n    * instance requests. For conceptual information about Spot Instances, refer to the Amazon\n    * Elastic Compute Cloud Developer Guide or Amazon Elastic Compute Cloud User Guide.\n    * \n    * @param region\n    *           Region where the spot instance service is running\n    * @param options\n    *           options to control the describeVpcsInRegion\n    * \n    * @see #describeSpotInstanceRequestsInRegion\n    * @see #requestSpotInstancesInRegion\n    * @see #cancelSpotInstanceRequestsInRegion\n    * @see <a href=\n    *      \"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeSpotInstanceRequests.html\"\n    *      />\n    * @return TODO\n    */\n   @Named(\"DescribeSpotPriceHistory\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"DescribeSpotPriceHistory\")\n   @XMLResponseParser(DescribeSpotPriceHistoryResponseHandler.class)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<Spot> describeSpotPriceHistoryInRegion(\n         @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n         DescribeSpotPriceHistoryOptions... options);\n\n   /**\n    * Cancels one or more Spot Instance requests. Spot Instances are instances that Amazon EC2\n    * starts on your behalf when the maximum price that you specify exceeds the current Spot Price.\n    * Amazon EC2 periodically sets the Spot Price based on available Spot Instance capacity and\n    * current spot instance requests. For conceptual information about Spot Instances, refer to the\n    * Amazon Elastic Compute Cloud Developer Guide or Amazon Elastic Compute Cloud User Guide.\n    * \n    * @param region\n    *           Region where the spot instance service is running\n    * @param requestIds\n    *           Specifies the ID of the Spot Instance request.\n    * \n    * @see #describeSpotInstanceRequestsInRegion\n    * @see #requestSpotInstancesInRegion\n    * @see #describeSpotPriceHistoryInRegion\n    * @see <a href=\n    *      \"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-CancelSpotInstanceRequests.html\"\n    *      />\n    * @return TODO\n    */\n   @Named(\"CancelSpotInstanceRequests\")\n   @POST\n   @Path(\"/\")\n   @FormParams(keys = ACTION, values = \"CancelSpotInstanceRequests\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void cancelSpotInstanceRequestsInRegion(\n         @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n         @BinderParam(BindSpotInstanceRequestIdsToIndexedFormParams.class) String... requestIds);\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/features/VPCApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.features;\n\nimport static org.jclouds.aws.reference.FormParameters.ACTION;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.FormParam;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\n\nimport org.jclouds.Fallbacks.EmptyFluentIterableOnNotFoundOr404;\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.aws.ec2.binders.BindVpcIdsToIndexedFormParams;\nimport org.jclouds.aws.ec2.domain.VPC;\nimport org.jclouds.aws.ec2.options.CreateVpcOptions;\nimport org.jclouds.aws.ec2.xml.DescribeVPCsResponseHandler;\nimport org.jclouds.aws.ec2.xml.ReturnValueHandler;\nimport org.jclouds.aws.ec2.xml.VPCHandler;\nimport org.jclouds.aws.filters.FormSigner;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.location.functions.RegionToEndpointOrProviderIfNull;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.EndpointParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.FormParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.VirtualHost;\nimport org.jclouds.rest.annotations.XMLResponseParser;\n\nimport com.google.common.collect.FluentIterable;\n\n/**\n * Provides access to VPC Services.\n * <p/>\n */\n@RequestFilters(FormSigner.class)\n@VirtualHost\n@Path(\"/\")\npublic interface VPCApi {\n\n   /**\n    * Describes all of your VPCs\n    *\n    * @return VPCs or empty if there are none\n    * @see <a href=\n    *      \"http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeVpcs.html\"\n    *      >docs</href>\n    */\n   @Named(\"DescribeVpcs\")\n   @POST\n   @FormParams(keys = ACTION, values = \"DescribeVpcs\")\n   @XMLResponseParser(DescribeVPCsResponseHandler.class)\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<VPC> describeVpcsInRegion(\n           @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n           @BinderParam(BindVpcIdsToIndexedFormParams.class) String... vpcIds);\n\n   /**\n    * Creates a VPC with the specified CIDR block.\n    *\n    * @param region\n    *           VPCs are tied to the Region.\n    *\n    * @param cidrBlock\n    *           The network range for the VPC, in CIDR notation. For example, 10.0.0.0/16.\n    * @return vpc\n    *\n    * @see <a href=\"http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateVpc.html\"\n    *      />\n    * @see CreateVpcOptions\n    * @see <a href=\n    *      \"http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateVpc.html\"\n    *      />\n    */\n   @Named(\"CreateVpc\")\n   @POST\n   @FormParams(keys = ACTION, values = \"CreateVpc\")\n   @XMLResponseParser(VPCHandler.class)\n   VPC createVpc(\n           @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n           @FormParam(\"CidrBlock\") String cidrBlock, CreateVpcOptions... options);\n   /**\n    * Deletes {@code VPC}.\n    *\n    * @param region\n    *           VPCs are tied to the Region where its files are located within Amazon S3.\n    * @param vpcId\n    *           The VPC ID.\n    *\n    */\n   @Named(\"DeleteVpc\")\n   @POST\n   @FormParams(keys = ACTION, values = \"DeleteVpc\")\n   @XMLResponseParser(ReturnValueHandler.class)\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean deleteVpc(\n           @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region,\n           @FormParam(\"VpcId\") String vpcId);\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/functions/CreatePlacementGroupIfNeeded.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.AWSResponseException;\nimport org.jclouds.aws.ec2.AWSEC2Api;\nimport org.jclouds.aws.ec2.domain.PlacementGroup;\nimport org.jclouds.aws.ec2.domain.PlacementGroup.State;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.cache.CacheLoader;\n\n@Singleton\npublic class CreatePlacementGroupIfNeeded extends CacheLoader<RegionAndName, String> {\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n   protected final AWSEC2Api ec2Api;\n   protected final Predicate<PlacementGroup> placementGroupAvailable;\n\n   @Inject\n   public CreatePlacementGroupIfNeeded(AWSEC2Api ec2Api,\n            @Named(\"AVAILABLE\") Predicate<PlacementGroup> placementGroupAvailable) {\n      this.ec2Api = ec2Api;\n      this.placementGroupAvailable = placementGroupAvailable;\n   }\n\n   @Override\n   public String load(RegionAndName from) {\n      createPlacementGroupInRegion(from.getRegion(), from.getName());\n      return from.getName();\n   }\n\n   private void createPlacementGroupInRegion(String region, String name) {\n      checkNotNull(region, \"region\");\n      checkNotNull(name, \"name\");\n      logger.debug(\">> creating placementGroup region(%s) name(%s)\", region, name);\n      try {\n         ec2Api.getPlacementGroupApi().get().createPlacementGroupInRegion(region, name);\n         logger.debug(\"<< created placementGroup(%s)\", name);\n         checkState(placementGroupAvailable.apply(new PlacementGroup(region, name, \"cluster\", State.PENDING)),\n                  \"placementGroup region(%s) name(%s) failed to become available\", region, name);\n      } catch (AWSResponseException e) {\n         if (e.getError().getCode().equals(\"InvalidPlacementGroup.Duplicate\")) {\n            logger.debug(\"<< reused placementGroup(%s)\", name);\n         } else {\n            throw e;\n         }\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/functions/ImportOrReturnExistingKeypair.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.ssh.SshKeys.fingerprintPublicKey;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.ec2.AWSEC2Api;\nimport org.jclouds.aws.ec2.domain.RegionNameAndPublicKeyMaterial;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.ec2.domain.KeyPair;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Function;\nimport com.google.common.collect.Iterables;\n\n@Singleton\npublic class ImportOrReturnExistingKeypair implements Function<RegionNameAndPublicKeyMaterial, KeyPair> {\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n   protected final AWSEC2Api ec2Api;\n\n   @Inject\n   public ImportOrReturnExistingKeypair(AWSEC2Api ec2Api) {\n      this.ec2Api = ec2Api;\n   }\n\n   @Override\n   public KeyPair apply(RegionNameAndPublicKeyMaterial from) {\n      return importOrReturnExistingKeypair(from.getRegion(), from.getName(), from.getPublicKeyMaterial());\n   }\n\n   @VisibleForTesting\n   KeyPair importOrReturnExistingKeypair(String region, String group, String publicKeyMaterial) {\n      checkNotNull(region, \"region\");\n      checkNotNull(group, \"group\");\n      checkNotNull(publicKeyMaterial, \"publicKeyMaterial\");\n      logger.debug(\">> importing keyPair region(%s) group(%s)\", region, group);\n      KeyPair keyPair = null;\n      // loop for eventual consistency or race condition.\n      // as this command is idempotent, it should be ok\n      while (keyPair == null)\n         try {\n            keyPair = ec2Api.getKeyPairApi().get().importKeyPairInRegion(region, \"jclouds#\" + group,\n                     publicKeyMaterial);\n            keyPair = addFingerprintToKeyPair(publicKeyMaterial, keyPair);\n            logger.debug(\"<< imported keyPair(%s)\", keyPair);\n         } catch (IllegalStateException e) {\n            keyPair = Iterables.getFirst(ec2Api.getKeyPairApi().get().describeKeyPairsInRegion(region,\n                     \"jclouds#\" + group), null);\n            if (keyPair != null) {\n               keyPair = addFingerprintToKeyPair(publicKeyMaterial, keyPair);\n               logger.debug(\"<< retrieved existing keyPair(%s)\", keyPair);\n            }\n         }\n      return keyPair;\n   }\n\n   public KeyPair addFingerprintToKeyPair(String publicKeyMaterial, KeyPair keyPair) {\n      // add in the fingerprint as it makes correlating keys in ssh logs possible\n      keyPair = keyPair.toBuilder().fingerprint(fingerprintPublicKey(publicKeyMaterial)).build();\n      return keyPair;\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/functions/SpotInstanceRequestToAWSRunningInstance.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.functions;\n\nimport org.jclouds.aws.ec2.domain.AWSRunningInstance;\nimport org.jclouds.aws.ec2.domain.LaunchSpecification;\nimport org.jclouds.aws.ec2.domain.MonitoringState;\nimport org.jclouds.aws.ec2.domain.SpotInstanceRequest;\nimport org.jclouds.ec2.domain.Hypervisor;\nimport org.jclouds.ec2.domain.InstanceState;\n\nimport com.google.common.base.Function;\n\npublic class SpotInstanceRequestToAWSRunningInstance implements Function<SpotInstanceRequest, AWSRunningInstance> {\n\n   @Override\n   public AWSRunningInstance apply(SpotInstanceRequest request) {\n      if (request == null)\n         return null;\n      if (request.getState() != SpotInstanceRequest.State.OPEN)\n         return null;\n      AWSRunningInstance.Builder builder = AWSRunningInstance.builder();\n      builder.spotInstanceRequestId(request.getId());\n      builder.instanceId(request.getId());\n      builder.instanceState(InstanceState.PENDING);\n      builder.rawState(request.getRawState());\n      builder.region(request.getRegion());\n      builder.tags(request.getTags());\n      LaunchSpecification spec = request.getLaunchSpecification();\n      builder.availabilityZone(spec.getAvailabilityZone());\n      // TODO convert\n      // builder.devices(spec.getBlockDeviceMappings());\n      builder.groupNames(spec.getSecurityGroupNames());\n      builder.imageId(spec.getImageId());\n      builder.instanceType(spec.getInstanceType());\n      builder.kernelId(spec.getKernelId());\n      builder.keyName(spec.getKeyName());\n      builder.ramdiskId(spec.getRamdiskId());\n      builder.monitoringState(Boolean.TRUE.equals(spec.isMonitoringEnabled()) ? MonitoringState.PENDING\n               : MonitoringState.DISABLED);\n      //TODO: determine the exact hypervisor\n      builder.hypervisor(Hypervisor.XEN);\n      return builder.build();\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/options/AWSDescribeImagesOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Collection;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\nimport org.jclouds.ec2.options.DescribeImagesOptions;\n\nimport com.google.common.collect.Multimap;\nimport com.google.common.collect.Multimaps;\n\n/**\n * Extra options only available in Amazon's implementation\n * \n * @see DescribeImagesOptions\n */\npublic class AWSDescribeImagesOptions extends DescribeImagesOptions {\n   public static final AWSDescribeImagesOptions NONE = new AWSDescribeImagesOptions();\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public AWSDescribeImagesOptions executableBy(String identityId) {\n      super.executableBy(identityId);\n      return this;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public AWSDescribeImagesOptions imageIds(String... imageIds) {\n      super.imageIds(imageIds);\n      return this;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public AWSDescribeImagesOptions imageIds(Iterable<String> imageIds) {\n      super.imageIds(imageIds);\n      return this;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public AWSDescribeImagesOptions ownedBy(String... owners) {\n      super.ownedBy(owners);\n      return this;\n   }\n\n   /**\n    * You can filter the results to return information only about images that match criteria you\n    * specify. For example, you could get information only about images that use a certain kernel.\n    * You can specify multiple values for a filter (e.g., the image uses either kernel aki-1a2b3c4d\n    * or kernel aki-9b8c7d6f). An image must match at least one of the specified values for it to be\n    * included in the results.\n    * <p/>\n    * You can specify multiple filters (e.g., the image uses a certain kernel, and uses an Amazon\n    * EBS volume as the root device). The result includes information for a particular image only if\n    * it matches all your filters. If there's no match, no special message is returned; the response\n    * is simply empty.\n    * <p/>\n    * You can use wildcards with the filter values: * matches zero or more characters, and ? matches\n    * exactly one character. You can escape special characters using a backslash before the\n    * character. For example, a value of \\*amazon\\?\\\\ searches for the literal string *amazon?\\.\n    * \n    */\n   public AWSDescribeImagesOptions filters(Multimap<String, String> filters) {\n      int i = 0;\n      for (Entry<String, Collection<String>> filter : checkNotNull(filters, \"filters\").asMap().entrySet()) {\n         String filterPrefix = String.format(\"Filter.%s.\", ++i);\n         formParameters.put(filterPrefix + \"Name\", filter.getKey());\n         indexFormValuesWithPrefix(filterPrefix + \"Value\", filter.getValue());\n      }\n      return this;\n   }\n\n   /**\n    * @see #filters(Multimap)\n    */\n   public AWSDescribeImagesOptions filters(Map<String, String> filters) {\n      return filters(Multimaps.forMap(checkNotNull(filters, \"filters\")));\n   }\n\n   public static class Builder extends DescribeImagesOptions.Builder {\n\n      /**\n       * @see AWSDescribeImagesOptions#executableBy\n       */\n      public static AWSDescribeImagesOptions executableBy(String identityId) {\n         AWSDescribeImagesOptions options = new AWSDescribeImagesOptions();\n         return options.executableBy(identityId);\n      }\n\n      /**\n       * @see AWSDescribeImagesOptions#imageIds\n       */\n      public static AWSDescribeImagesOptions imageIds(String... imageIds) {\n         AWSDescribeImagesOptions options = new AWSDescribeImagesOptions();\n         return options.imageIds(imageIds);\n      }\n\n      /**\n       * @see AWSDescribeImagesOptions#filters(Multimap)\n       */\n      public static AWSDescribeImagesOptions filters(Multimap<String, String> filters) {\n         AWSDescribeImagesOptions options = new AWSDescribeImagesOptions();\n         return options.filters(filters);\n      }\n\n      /**\n       * @see AWSDescribeImagesOptions#filters(Map)\n       */\n      public static AWSDescribeImagesOptions filters(Map<String, String> filters) {\n         AWSDescribeImagesOptions options = new AWSDescribeImagesOptions();\n         return options.filters(filters);\n      }\n\n      /**\n       * @see AWSDescribeImagesOptions#ownedBy\n       */\n      public static AWSDescribeImagesOptions ownedBy(String... owners) {\n         AWSDescribeImagesOptions options = new AWSDescribeImagesOptions();\n         return options.ownedBy(owners);\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/options/AWSRunInstancesOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Set;\n\nimport org.jclouds.aws.ec2.domain.LaunchSpecification;\nimport org.jclouds.ec2.domain.BlockDeviceMapping;\nimport org.jclouds.ec2.options.RunInstancesOptions;\nimport org.jclouds.rest.annotations.SinceApiVersion;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Contains options supported in the Form API for the RunInstances operation. <h2>\n * Usage</h2> The recommended way to instantiate a RunInstancesOptions object is to statically\n * import RunInstancesOptions.Builder.* and invoke a static creation method followed by an instance\n * mutator (if needed):\n * <p/>\n * <code>\n * import static org.jclouds.aws.ec2.options.RunInstancesOptions.Builder.*\n * <p/>\n * EC2Api connection = // get connection\n * Future<ReservationInfo> instances = connection.runInstances(executableBy(\"123125\").imageIds(1000, 1004));\n * <code>\n * \n * @see <a href=\n *      \"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-form-RunInstances.html\"\n *      />\n */\npublic class AWSRunInstancesOptions extends RunInstancesOptions {\n   private LaunchSpecification.Builder launchSpecificationBuilder = LaunchSpecification.builder();\n   public static final AWSRunInstancesOptions NONE = new AWSRunInstancesOptions();\n\n   /**\n    * Specifies the name of an existing placement group you want to launch the instance into (for\n    * cluster compute instances).\n    * \n    * @param placementGroup\n    *           name of an existing placement group\n    */\n   public AWSRunInstancesOptions inPlacementGroup(String placementGroup) {\n      formParameters.put(\"Placement.GroupName\", checkNotNull(placementGroup, \"placementGroup\"));\n      return this;\n   }\n\n   /**\n    * Specifies the tenancy of the instance within which to launch the instance(s).\n    */\n   public AWSRunInstancesOptions withTenancy(Tenancy tenancy) {\n      formParameters.put(\"Placement.Tenancy\", checkNotNull(tenancy, \"tenancy\").toString());\n      return this;\n   }\n\n   /**\n    * Specifies the ID of the dedicated host on which the instance should resist.\n    */\n   public AWSRunInstancesOptions withDedicatedHostId(String hostId) {\n      formParameters.put(\"Placement.HostId\", checkNotNull(hostId, \"hostId\"));\n      return this;\n   }\n\n   /**\n    * Enables monitoring for the instance.\n    */\n   public AWSRunInstancesOptions enableMonitoring() {\n      formParameters.put(\"Monitoring.Enabled\", \"true\");\n      launchSpecificationBuilder.monitoringEnabled(true);\n      return this;\n   }\n\n   /**\n    * Specifies the subnet ID within which to launch the instance(s) for Amazon Virtual Private\n    * Cloud.\n    */\n   public AWSRunInstancesOptions withSubnetId(String subnetId) {\n      formParameters.put(\"SubnetId\", checkNotNull(subnetId, \"subnetId\"));\n      return this;\n   }\n\n   public AWSRunInstancesOptions withSecurityGroupId(String securityGroup) {\n      return withSecurityGroupIds(securityGroup);\n   }\n\n   public AWSRunInstancesOptions withSecurityGroupIds(Iterable<String> securityGroupIds) {\n      launchSpecificationBuilder.securityGroupIds(securityGroupIds);\n      indexFormValuesWithPrefix(\"SecurityGroupId\", securityGroupIds);\n      return this;\n   }\n\n   public AWSRunInstancesOptions withSecurityGroupIds(String... securityGroupIds) {\n      return withSecurityGroupIds(ImmutableSet.copyOf(securityGroupIds));\n   }\n\n   /**\n    * Amazon resource name (ARN) of the IAM Instance Profile (IIP) to associate with the instances.\n    * \n    * @see org.jclouds.aws.ec2.domain.AWSRunningInstance#getIAMInstanceProfile()\n    */\n   @SinceApiVersion(\"2012-06-01\")\n   public AWSRunInstancesOptions withIAMInstanceProfileArn(String arn) {\n      formParameters.put(\"IamInstanceProfile.Arn\", checkNotNull(arn, \"arn\"));\n      return this;\n   }\n\n   /**\n    * The name of the IAM Instance Profile (IIP) to associate with the instances.\n    * \n    * @see org.jclouds.aws.ec2.domain.AWSRunningInstance#getIAMInstanceProfile()\n    */\n   @SinceApiVersion(\"2012-06-01\")\n   public AWSRunInstancesOptions withIAMInstanceProfileName(String name) {\n      formParameters.put(\"IamInstanceProfile.Name\", checkNotNull(name, \"name\"));\n      return this;\n   }\n\n   /**\n    * The primary IP address for VPC instance. You must specify a value from the IP address range of the subnet.\n    *\n    * @see org.jclouds.aws.ec2.domain.AWSRunningInstance#getPrivateIpAddress()\n    */\n   public AWSRunInstancesOptions withPrivateIpAddress(String address) {\n      formParameters.put(\"PrivateIpAddress\", checkNotNull(address, \"address\"));\n      return this;\n   }\n\n   public static class Builder extends RunInstancesOptions.Builder {\n\n      /**\n       * @see AWSRunInstancesOptions#withSecurityGroupId(String)\n       */\n      public static AWSRunInstancesOptions withSecurityGroupId(String securityGroup) {\n         AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n         return options.withSecurityGroupId(securityGroup);\n      }\n\n      /**\n       * @see AWSRunInstancesOptions#inPlacementGroup(String)\n       */\n      public static AWSRunInstancesOptions inPlacementGroup(String placementGroup) {\n         AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n         return options.inPlacementGroup(placementGroup);\n      }\n\n      /**\n       * @see AWSRunInstancesOptions#withTenancy(Tenancy)\n       */\n      public static AWSRunInstancesOptions withTenancy(Tenancy tenancy) {\n         AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n         return options.withTenancy(tenancy);\n      }\n\n      /**\n       * @see AWSRunInstancesOptions#withDedicatedHostId(String)\n       */\n      public static AWSRunInstancesOptions withDedicatedHostId(String hostId) {\n         AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n         return options.withDedicatedHostId(hostId);\n      }\n\n      /**\n       * @see AWSRunInstancesOptions#enableMonitoring()\n       */\n      public static AWSRunInstancesOptions enableMonitoring() {\n         AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n         return options.enableMonitoring();\n      }\n\n      /**\n       * @see AWSRunInstancesOptions#withSubnetId(String)\n       */\n      public static AWSRunInstancesOptions withSubnetId(String subnetId) {\n         AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n         return options.withSubnetId(subnetId);\n      }\n\n      /**\n       * @see AWSRunInstancesOptions#withIAMInstanceProfileArn(String)\n       */\n      public static AWSRunInstancesOptions withIAMInstanceProfileArn(String arn) {\n         AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n         return options.withIAMInstanceProfileArn(arn);\n      }\n\n      /**\n       * @see AWSRunInstancesOptions#withIAMInstanceProfileName(String)\n       */\n      public static AWSRunInstancesOptions withIAMInstanceProfileName(String id) {\n         AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n         return options.withIAMInstanceProfileName(id);\n      }\n\n      /**\n       * @see AWSRunInstancesOptions#withKeyName(String)\n       */\n      public static AWSRunInstancesOptions withKeyName(String keyName) {\n         AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n         return options.withKeyName(keyName);\n      }\n\n      /**\n       * @see AWSRunInstancesOptions#withSecurityGroup(String)\n       */\n      public static AWSRunInstancesOptions withSecurityGroup(String securityGroup) {\n         AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n         return options.withSecurityGroup(securityGroup);\n      }\n\n      /**\n       * @see AWSRunInstancesOptions#withUserData(byte [])\n       */\n      public static AWSRunInstancesOptions withUserData(byte[] unencodedData) {\n         AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n         return options.withUserData(unencodedData);\n      }\n\n      /**\n       * @see AWSRunInstancesOptions#asType(InstanceType)\n       */\n      public static AWSRunInstancesOptions asType(String instanceType) {\n         AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n         return options.asType(instanceType);\n      }\n\n      /**\n       * @see AWSRunInstancesOptions#withKernelId(String)\n       */\n      public static AWSRunInstancesOptions withKernelId(String kernelId) {\n         AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n         return options.withKernelId(kernelId);\n      }\n\n      /**\n       * @see AWSRunInstancesOptions#withRamdisk(String)\n       */\n      public static AWSRunInstancesOptions withRamdisk(String ramdiskId) {\n         AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n         return options.withRamdisk(ramdiskId);\n      }\n\n      /**\n       * @see AWSRunInstancesOptions#withBlockDeviceMappings(Set<BlockDeviceMapping> mappings)\n       */\n      public static AWSRunInstancesOptions withBlockDeviceMappings(Set<? extends BlockDeviceMapping> mappings) {\n         AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n         return options.withBlockDeviceMappings(mappings);\n      }\n\n      /**\n       * @see AWSRunInstancesOptions#withPrivateIpAddress(String)\n       */\n      public static AWSRunInstancesOptions withPrivateIpAdress(String address) {\n         AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n         return options.withPrivateIpAddress(address);\n      }\n\n   }\n\n   @Override\n   public AWSRunInstancesOptions withBlockDeviceMappings(Set<? extends BlockDeviceMapping> mappings) {\n      launchSpecificationBuilder.blockDeviceMappings(mappings);\n      return AWSRunInstancesOptions.class.cast(super.withBlockDeviceMappings(mappings));\n   }\n\n   @Override\n   public AWSRunInstancesOptions withKernelId(String kernelId) {\n      launchSpecificationBuilder.kernelId(kernelId);\n      return AWSRunInstancesOptions.class.cast(super.withKernelId(kernelId));\n   }\n\n   @Override\n   public AWSRunInstancesOptions withKeyName(String keyName) {\n      launchSpecificationBuilder.keyName(keyName);\n      return AWSRunInstancesOptions.class.cast(super.withKeyName(keyName));\n   }\n\n   @Override\n   public AWSRunInstancesOptions withRamdisk(String ramDiskId) {\n      launchSpecificationBuilder.ramdiskId(ramDiskId);\n      return AWSRunInstancesOptions.class.cast(super.withRamdisk(ramDiskId));\n   }\n\n   @Override\n   public AWSRunInstancesOptions withSecurityGroup(String securityGroup) {\n      launchSpecificationBuilder.securityGroupName(securityGroup);\n      return AWSRunInstancesOptions.class.cast(super.withSecurityGroup(securityGroup));\n   }\n\n   @Override\n   public AWSRunInstancesOptions withSecurityGroups(Iterable<String> securityGroups) {\n      launchSpecificationBuilder.securityGroupNames(securityGroups);\n      return AWSRunInstancesOptions.class.cast(super.withSecurityGroups(securityGroups));\n   }\n\n   @Override\n   public AWSRunInstancesOptions withSecurityGroups(String... securityGroups) {\n      launchSpecificationBuilder.securityGroupNames(ImmutableSet.copyOf(securityGroups));\n      return AWSRunInstancesOptions.class.cast(super.withSecurityGroups(securityGroups));\n   }\n\n   @Override\n   public AWSRunInstancesOptions withUserData(byte[] unencodedData) {\n      launchSpecificationBuilder.userData(unencodedData);\n      return AWSRunInstancesOptions.class.cast(super.withUserData(unencodedData));\n   }\n\n   @Override\n   public AWSRunInstancesOptions asType(String type) {\n      launchSpecificationBuilder.instanceType(type);\n      return AWSRunInstancesOptions.class.cast(super.asType(type));\n   }\n\n   public synchronized LaunchSpecification.Builder getLaunchSpecificationBuilder() {\n      try {\n         return launchSpecificationBuilder.imageId(\"fake\").build().toBuilder().imageId(null);\n      } finally {\n         launchSpecificationBuilder.imageId(null);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/options/CreateSecurityGroupOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.ec2.options.internal.BaseEC2RequestOptions;\n\n/**\n * Contains options supported in the Form API for the CreateSecurityGroup\n * operation. <h2>\n * Usage</h2> The recommended way to instantiate a CreateSecurityGroupOptions\n * object is to statically import CreateSecurityGroupOptions.Builder.* and\n * invoke a static creation method followed by an instance mutator (if needed):\n * <p/>\n * <code>\n * import static org.jclouds.aws.ec2.options.CreateSecurityGroupOptions.Builder.*\n * <p/>\n * AWSEC2Api connection = // get connection\n * group = connection.getAMIServices().createSecurityGroup(vpcId(\"123125\"));\n * <code>\n * \n * @see <a href=\n *      \"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-form-CreateSecurityGroup.html\"\n *      />\n */\npublic class CreateSecurityGroupOptions extends BaseEC2RequestOptions {\n\n   /**\n    * ID of the VPC.\n    */\n   public CreateSecurityGroupOptions vpcId(String vpcId) {\n      formParameters.put(\"VpcId\", checkNotNull(vpcId, \"vpcId\"));\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see CreateSecurityGroupOptions#vpcId(String )\n       */\n      public static CreateSecurityGroupOptions vpcId(String vpcId) {\n         CreateSecurityGroupOptions options = new CreateSecurityGroupOptions();\n         return options.vpcId(vpcId);\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/options/CreateSubnetOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.ec2.options.internal.BaseEC2RequestOptions;\n\n/**\n * Contains options supported in the Form API for the CreateSubnet\n * operation. <h2>\n * Usage</h2> The recommended way to instantiate a CreateSubnetOptions\n * object is to statically import CreateSubnetOptions.Builder.* and\n * invoke a static creation method followed by an instance mutator (if needed):\n * <p/>\n * <code>\n * import static org.jclouds.aws.ec2.options.CreateSubnetOptions.Builder.*\n * <p/>\n * AWSEC2Api connection = // get connection\n * String vpcId = \"vpc-1a2b3c4d\";\n * String cidrBlock = \"10.0.1.0/24\";\n * group = connection.getAWSSubnetApi().createSubnetInRegion(vpcId, cirdBlock, availabilityZone(\"us-east-1a\"));\n * <code>\n * \n * @see <a href=\n *      \"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-form-CreateSubnet.html\"\n *      />\n */\npublic class CreateSubnetOptions extends BaseEC2RequestOptions {\n\n   /**\n    * The Availability Zone for the subnet.\n    */\n   public CreateSubnetOptions availabilityZone(String availabilityZone) {\n      formParameters.put(\"AvailabilityZone\", checkNotNull(availabilityZone, \"availabilityZone\"));\n      return this;\n   }\n\n   public String getAvailabilityZone() {\n      return getFirstFormOrNull(\"AvailabilityZone\");\n   }\n\n   public CreateSubnetOptions dryRun() {\n      formParameters.put(\"DryRun\", \"true\");\n      return this;\n   }\n\n   public boolean isDryRun() {\n      return Boolean.parseBoolean(getFirstFormOrNull(\"DryRun\"));\n   }\n\n   public static class Builder {\n\n      /**\n       * @see CreateSubnetOptions#availabilityZone(String )\n       */\n      public static CreateSubnetOptions availabilityZone(String availabilityZone) {\n         CreateSubnetOptions options = new CreateSubnetOptions();\n         return options.availabilityZone(availabilityZone);\n      }\n\n      /**\n       * @see CreateSubnetOptions#dryRun()\n       */\n      public static CreateSubnetOptions dryRun() {\n         CreateSubnetOptions options = new CreateSubnetOptions();\n         return options.dryRun();\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/options/CreateVpcOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.ec2.options.internal.BaseEC2RequestOptions;\n\n/**\n * Contains options supported in the Form API for the CreateVpc operation. <h2>\n * Usage</h2> The recommended way to instantiate a CreateImageOptions object is to statically import\n * CreateVpcOptions.Builder.* and invoke a static creation method followed by an instance mutator\n * (if needed):\n * <p/>\n * <code>\n * import static org.jclouds.ec2.options.CreateVpcOptions.Builder.*\n * <p/>\n * EC2Api connection = // get connection\n * Future<Set<ImageMetadata>> images = connection.getVpcApi().get().createVpc(withDescription(\"123125\").noReboot());\n * <code>\n * \n * @see <a\n *      href=\"http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateVpc.html\"\n *      />\n */\npublic class CreateVpcOptions extends BaseEC2RequestOptions {\n   \n   public static final CreateVpcOptions NONE = new CreateVpcOptions();\n\n   /**\n    * The instanceTenancy of the VPC that was provided during image creation.\n    * <p/>\n    * \n    * Default: default, Valid Values: default | dedicated | host\n    */\n   public CreateVpcOptions withInstanceTenancy(String instanceTenancy) {\n      formParameters.put(\"InstanceTenancy\", checkNotNull(instanceTenancy, \"instanceTenancy\"));\n      return this;\n   }\n\n   public String getInstanceTenancy() {\n      return getFirstFormOrNull(\"InstanceTenancy\");\n\n   }\n\n   /**\n    * Checks whether you have the required permissions for the action, without actually making the request, and provides an error response.\n    */\n   public CreateVpcOptions dryRun() {\n      formParameters.put(\"DryRun\", \"true\");\n      return this;\n   }\n\n   public boolean isDryRun() {\n      return getFirstFormOrNull(\"DryRun\") != null;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see CreateVpcOptions#withInstanceTenancy(String )\n       */\n      public static CreateVpcOptions withInstanceTenancy(String instanceTenancy) {\n         CreateVpcOptions options = new CreateVpcOptions();\n         return options.withInstanceTenancy(instanceTenancy);\n      }\n\n      /**\n       * @see CreateVpcOptions#dryRun()\n       */\n      public static CreateVpcOptions dryRun() {\n         CreateVpcOptions options = new CreateVpcOptions();\n         return options.dryRun();\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/options/DescribeSpotPriceHistoryOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Date;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.ec2.options.internal.BaseEC2RequestOptions;\n\n/**\n * Contains options supported in the Form API for the DescribeSpotPriceHistory operation. <h2>\n * Usage</h2> The recommended way to instantiate a DescribeSpotPriceHistoryOptions object is to\n * statically import DescribeSpotPriceHistoryOptions.Builder.* and invoke a static creation method\n * followed by an instance mutator (if needed):\n * <p/>\n * <code>\n * import static org.jclouds.aws.ec2.options.DescribeSpotPriceHistoryOptions.Builder.*\n * <p/>\n * AWSEC2Api client = // get connection\n * history = client.getSpotInstanceServices().describeSpotPriceHistoryInRegion(from(yesterday).instanceType(\"m1.small\"));\n * <code>\n * \n * @see <a href=\n *      \"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-form-DescribeSpotPriceHistory.html\"\n *      />\n */\npublic class DescribeSpotPriceHistoryOptions extends BaseEC2RequestOptions {\n   public static final DescribeSpotPriceHistoryOptions NONE = new DescribeSpotPriceHistoryOptions();\n   private static final DateService service = new SimpleDateFormatDateService();\n\n   /**\n    * Start date and time of the Spot Instance price history data.\n    */\n   public DescribeSpotPriceHistoryOptions from(Date start) {\n      formParameters.put(\"StartTime\", service.iso8601DateFormat(checkNotNull(start, \"start\")));\n      return this;\n   }\n\n   /**\n    * End date and time of the Spot Instance price history data.\n    */\n   public DescribeSpotPriceHistoryOptions to(Date end) {\n      formParameters.put(\"EndTime\", service.iso8601DateFormat(checkNotNull(end, \"end\")));\n      return this;\n   }\n\n   /**\n    * Specifies the instance type to return.\n    */\n   public DescribeSpotPriceHistoryOptions instanceType(String type) {\n      formParameters.put(\"InstanceType.1\", checkNotNull(type, \"type\"));\n      return this;\n   }\n\n   /**\n    * The description of the AMI.\n    */\n   public DescribeSpotPriceHistoryOptions productDescription(String description) {\n      formParameters.put(\"ProductDescription\", checkNotNull(description, \"description\"));\n      return this;\n   }\n\n   public static class Builder {\n      /**\n       * @see DescribeSpotPriceHistoryOptions#from\n       */\n      public static DescribeSpotPriceHistoryOptions from(Date start) {\n         DescribeSpotPriceHistoryOptions options = new DescribeSpotPriceHistoryOptions();\n         return options.from(start);\n      }\n\n      /**\n       * @see DescribeSpotPriceHistoryOptions#to\n       */\n      public static DescribeSpotPriceHistoryOptions to(Date end) {\n         DescribeSpotPriceHistoryOptions options = new DescribeSpotPriceHistoryOptions();\n         return options.to(end);\n      }\n\n      /**\n       * @see DescribeSpotPriceHistoryOptions#instanceType(InstanceType)\n       */\n      public static DescribeSpotPriceHistoryOptions instanceType(String instanceType) {\n         DescribeSpotPriceHistoryOptions options = new DescribeSpotPriceHistoryOptions();\n         return options.instanceType(instanceType);\n      }\n\n      /**\n       * @see DescribeSpotPriceHistoryOptions#productDescription(String)\n       */\n      public static DescribeSpotPriceHistoryOptions productDescription(String description) {\n         DescribeSpotPriceHistoryOptions options = new DescribeSpotPriceHistoryOptions();\n         return options.productDescription(description);\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/options/InternetGatewayOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.options;\n\nimport org.jclouds.ec2.options.internal.BaseEC2RequestOptions;\n\n/**\n * Contains options supported in the Form API for the InternetGateway operations. <h2>\n * Usage</h2> The recommended way to instantiate such an object is to statically import\n * InternetGatewayOptions.Builder.* and invoke a static creation method followed by an instance mutator\n * (if needed):\n * <p/>\n * <code>\n * import static org.jclouds.ec2.options.InternetGatewayOptions.Builder.*\n * <p/>\n * EC2Api connection = // get connection\n * InternetGateway gw =\n * connection.getInternetGatewayApi().get().createInternetGateway(region, dryRun());\n * <code>\n *\n * @see <a\n * href=\"http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateInternetGateway.html\"\n * />\n */\npublic class InternetGatewayOptions extends BaseEC2RequestOptions {\n\n   public static final InternetGatewayOptions NONE = new InternetGatewayOptions();\n\n   /**\n    * Checks whether you have the required permissions for the action, without actually making the request,\n    * and provides an error response.\n    */\n   public InternetGatewayOptions dryRun() {\n      formParameters.put(\"DryRun\", \"true\");\n      return this;\n   }\n\n   public boolean isDryRun() {\n      return getFirstFormOrNull(\"DryRun\") != null;\n   }\n\n   public static class Builder {\n      /**\n       * @see InternetGatewayOptions#dryRun()\n       */\n      public static InternetGatewayOptions dryRun() {\n         InternetGatewayOptions options = new InternetGatewayOptions();\n         return options.dryRun();\n      }\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/options/ModifySubnetAttributeOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.ec2.options.internal.BaseEC2RequestOptions;\nimport org.jclouds.rest.annotations.SinceApiVersion;\n\n/**\n * Contains options supported in the Form API for the ModifySubnetAttribute\n * operation. <h2>\n * Usage</h2> The recommended way to instantiate a ModifySubnetAttributeOptions\n * object is to statically import ModifySubnetAttributeOptions.Builder.* and\n * invoke a static creation method followed by an instance mutator (if needed):\n * <p/>\n * <code>\n * import static org.jclouds.aws.ec2.options.ModifySubnetAttributeOptions.Builder.*\n * <p/>\n * group = connection.getAWSSubnetApi().modifySubnetAttribute(region, subnetId, mapPublicIpOnLaunch(true));\n * <code>\n * \n * @see <a href=\n *      \"http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ModifySubnetAttribute.html\"\n *      />\n */\n@SinceApiVersion(\"2014-06-15\")\npublic class ModifySubnetAttributeOptions extends BaseEC2RequestOptions {\n\n   /**\n    * The Availability Zone for the subnet.\n    */\n   public ModifySubnetAttributeOptions assignIpv6AddressOnCreation(Boolean assignIpv6AddressOnCreation) {\n      formParameters.put(\"AssignIpv6AddressOnCreation.Value\",\n         checkNotNull(assignIpv6AddressOnCreation, \"assignIpv6AddressOnCreation\").toString());\n      return this;\n   }\n\n   public Boolean isAssignIpv6AddressOnCreation() {\n      return Boolean.parseBoolean(\"AssignIpv6AddressOnCreation.Value\");\n   }\n\n   public ModifySubnetAttributeOptions mapPublicIpOnLaunch(Boolean mapPublicIpOnLaunch) {\n      formParameters.put(\"MapPublicIpOnLaunch.Value\",\n         checkNotNull(mapPublicIpOnLaunch, \"mapPublicIpOnLaunch\").toString());\n      return this;\n   }\n\n   public Boolean isMapPublicIpOnLaunch() {\n      return Boolean.parseBoolean(getFirstFormOrNull(\"MapPublicIpOnLaunch.Value\"));\n   }\n\n   public static class Builder {\n\n      /**\n       * @see ModifySubnetAttributeOptions#assignIpv6AddressOnCreation(Boolean )\n       */\n      public static ModifySubnetAttributeOptions assignIpv6AddressOnCreation(Boolean assignIpv6AddressOnCreation) {\n         ModifySubnetAttributeOptions options = new ModifySubnetAttributeOptions();\n         return options.assignIpv6AddressOnCreation(assignIpv6AddressOnCreation);\n      }\n\n      /**\n       * @see ModifySubnetAttributeOptions#mapPublicIpOnLaunch(Boolean)\n       */\n      public static ModifySubnetAttributeOptions mapPublicIpOnLaunch(Boolean mapPublicIpOnLaunch) {\n         ModifySubnetAttributeOptions options = new ModifySubnetAttributeOptions();\n         return options.mapPublicIpOnLaunch(mapPublicIpOnLaunch);\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/options/RequestSpotInstancesOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Date;\n\nimport org.jclouds.aws.ec2.domain.SpotInstanceRequest;\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.ec2.options.internal.BaseEC2RequestOptions;\n\n/**\n * Contains options supported in the Form API for the RequestSpotInstances operation. <h2>\n * Usage</h2> The recommended way validUntil instantiate a RequestSpotInstancesOptions object is\n * validUntil statically import RequestSpotInstancesOptions.Builder.* and invoke a static creation\n * method followed by an instance mutator (if needed):\n * <p/>\n * <code>\n * import static org.jclouds.aws.ec2.options.RequestSpotInstancesOptions.Builder.*\n * <p/>\n * AWSEC2Api client = // get connection\n * history = client.getSpotInstanceServices().requestSpotInstancesInRegion(\"us-east-1\",validFrom(yesterday).type(\"m1.small\"));\n * <code>\n * \n * @see <a href=\n *      \"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-form-RequestSpotInstances.html\"\n *      />\n */\npublic class RequestSpotInstancesOptions extends BaseEC2RequestOptions {\n   public static final RequestSpotInstancesOptions NONE = new RequestSpotInstancesOptions();\n   private static final DateService service = new SimpleDateFormatDateService();\n\n   /**\n    * Start date of the request. If this is a one-time request, the request becomes active at this\n    * date and time and remains active until all instances launch, the request expires, or the\n    * request is canceled. If the request is persistent, the request becomes active at this date and\n    * time and remains active until it expires or is canceled.\n    */\n   public RequestSpotInstancesOptions validFrom(Date start) {\n      formParameters.put(\"ValidFrom\", service.iso8601SecondsDateFormat(checkNotNull(start, \"start\")));\n      return this;\n   }\n\n   /**\n    * End date of the request. If this is a one-time request, the request remains active until all\n    * instances launch, the request is canceled, or this date is reached. If the request is\n    * persistent, it remains active until it is canceled or this date and time is reached.\n    */\n   public RequestSpotInstancesOptions validUntil(Date end) {\n      formParameters.put(\"ValidUntil\", service.iso8601SecondsDateFormat(checkNotNull(end, \"end\")));\n      return this;\n   }\n\n   /**\n    * Specifies the Spot Instance type.\n    */\n   public RequestSpotInstancesOptions type(SpotInstanceRequest.Type type) {\n      formParameters.put(\"Type\", checkNotNull(type, \"type\").toString());\n      return this;\n   }\n\n   /**\n    * Specifies the instance launch group. Launch groups are Spot Instances that launch together and\n    * terminate together.\n    */\n   public RequestSpotInstancesOptions launchGroup(String launchGroup) {\n      formParameters.put(\"LaunchGroup\", checkNotNull(launchGroup, \"launchGroup\"));\n      return this;\n   }\n\n   /**\n    * Specifies the Availability Zone group. If you specify the same Availability Zone group for all\n    * Spot Instance requests, all Spot Instances are launched in the same Availability Zone.\n    */\n   public RequestSpotInstancesOptions availabilityZoneGroup(String availabilityZoneGroup) {\n      formParameters.put(\"AvailabilityZoneGroup\", checkNotNull(availabilityZoneGroup, \"availabilityZoneGroup\"));\n      return this;\n   }\n\n   public static class Builder {\n      /**\n       * @see RequestSpotInstancesOptions#validFrom\n       */\n      public static RequestSpotInstancesOptions validFrom(Date start) {\n         RequestSpotInstancesOptions options = new RequestSpotInstancesOptions();\n         return options.validFrom(start);\n      }\n\n      /**\n       * @see RequestSpotInstancesOptions#validUntil\n       */\n      public static RequestSpotInstancesOptions validUntil(Date end) {\n         RequestSpotInstancesOptions options = new RequestSpotInstancesOptions();\n         return options.validUntil(end);\n      }\n\n      /**\n       * @see RequestSpotInstancesOptions#type\n       */\n      public static RequestSpotInstancesOptions type(SpotInstanceRequest.Type type) {\n         RequestSpotInstancesOptions options = new RequestSpotInstancesOptions();\n         return options.type(type);\n      }\n\n      /**\n       * @see RequestSpotInstancesOptions#launchGroup(String)\n       */\n      public static RequestSpotInstancesOptions launchGroup(String launchGroup) {\n         RequestSpotInstancesOptions options = new RequestSpotInstancesOptions();\n         return options.launchGroup(launchGroup);\n      }\n\n      /**\n       * @see RequestSpotInstancesOptions#availabilityZoneGroup\n       */\n      public static RequestSpotInstancesOptions availabilityZoneGroup(String availabilityZoneGroup) {\n         RequestSpotInstancesOptions options = new RequestSpotInstancesOptions();\n         return options.availabilityZoneGroup(availabilityZoneGroup);\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/options/RouteOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.ec2.options.internal.BaseEC2RequestOptions;\n\n/**\n * Contains options supported in the Form API for the Route operations. <h2>\n * Usage</h2> The recommended way to instantiate such an object is to statically import\n * RouteOptions.Builder.* and invoke a static creation method followed by an instance mutator\n * (if needed):\n * <p/>\n * <code>\n * import static org.jclouds.ec2.options.RouteOptions.Builder.*\n * <p/>\n * EC2Api connection = // get connection\n * Route r = connection.getRouteTableApi().get()\n *   .createRoute(region, routeTableId, gatewayId(\"igw-97e68af3\").destinationCidrBlock(\"172.18.19.0/24\"));\n * <code>\n *\n * @see <a\n * href=\"http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateRoute.html\"\n * />\n */\npublic class RouteOptions extends BaseEC2RequestOptions {\n\n   /**\n    * Checks whether you have the required permissions for the action, without actually making the request,\n    * and provides an error response.\n    */\n   public RouteOptions dryRun() {\n      formParameters.put(\"DryRun\", \"true\");\n      return this;\n   }\n\n   public boolean isDryRun() {\n      return getFirstFormOrNull(\"DryRun\") != null;\n   }\n\n   /**\n    * The IPv4 CIDR address block used for the destination match.\n    * Routing decisions are based on the most specific match.\n    */\n   public RouteOptions destinationCidrBlock(String destinationCidrBlock) {\n      formParameters.put(\"DestinationCidrBlock\", checkNotNull(destinationCidrBlock, \"destinationCidrBlock\"));\n      return this;\n   }\n\n   /**\n    * @see RouteOptions#destinationCidrBlock(java.lang.String)\n    */\n   public String getDestinationCidrBlock() {\n      return getFirstFormOrNull(\"DestinationCidrBlock\");\n   }\n\n   /**\n    * The IPv6 CIDR block used for the destination match. Routing decisions are based on the most specific match.\n    */\n   public RouteOptions destinationIpv6CidrBlock(String destinationIpv6CidrBlock) {\n      formParameters.put(\"DestinationIpv6CidrBlock\", checkNotNull(destinationIpv6CidrBlock, \"destinationIpv6CidrBlock\"));\n      return this;\n   }\n\n   /**\n    * @see RouteOptions#destinationIpv6CidrBlock(java.lang.String)\n    */\n   public String getDestinationIpv6CidrBlock() {\n      return getFirstFormOrNull(\"DestinationIpv6CidrBlock\");\n   }\n\n   /**\n    * The ID of an Internet gateway or virtual private gateway attached to your VPC.\n    */\n   public RouteOptions gatewayId(String gatewayId) {\n      formParameters.put(\"GatewayId\", checkNotNull(gatewayId, \"gatewayId\"));\n      return this;\n   }\n\n   /**\n    * @see RouteOptions#gatewayId(java.lang.String)\n    */\n   public String getGatewayId() {\n      return getFirstFormOrNull(\"GatewayId\");\n   }\n\n   /**\n    * [IPv6 traffic only] The ID of an egress-only Internet gateway.\n    */\n   public RouteOptions egressOnlyInternetGatewayId(String egressOnlyInternetGatewayId) {\n      formParameters.put(\"EgressOnlyInternetGatewayId\",\n         checkNotNull(egressOnlyInternetGatewayId, \"egressOnlyInternetGatewayId\"));\n      return this;\n   }\n\n   /**\n    * @see RouteOptions#egressOnlyInternetGatewayId(java.lang.String)\n    */\n   public String getEgressOnlyInternetGatewayId() {\n      return getFirstFormOrNull(\"EgressOnlyInternetGatewayId\");\n   }\n\n   /**\n    * [IPv4 traffic only] The ID of a NAT gateway.\n    */\n   public RouteOptions natGatewayId(String natGatewayId) {\n      formParameters.put(\"NatGatewayId\", checkNotNull(natGatewayId, \"natGatewayId\"));\n      return this;\n   }\n\n   /**\n    * @see RouteOptions#natGatewayId(String)\n    */\n   public String getNatGatewayId() {\n      return getFirstFormOrNull(\"NatGatewayId\");\n   }\n\n   /**\n    * The ID of a network interface.\n    */\n   public RouteOptions networkInterfaceId(String networkInterfaceId) {\n      formParameters.put(\"NetworkInterfaceId\", checkNotNull(networkInterfaceId, \"networkInterfaceId\"));\n      return this;\n   }\n\n   /**\n    * @see RouteOptions#networkInterfaceId(String)\n    */\n   public String getNetworkInterfaceId() {\n      return getFirstFormOrNull(\"NetworkInterfaceId\");\n   }\n\n   /**\n    * The ID of a NAT instance in your VPC. The operation fails if you specify an instance ID unless\n    * exactly one network interface is attached.\n    */\n   public RouteOptions instanceId(String instanceId) {\n      formParameters.put(\"InstanceId\", checkNotNull(instanceId, \"instanceId\"));\n      return this;\n   }\n\n   /**\n    * @see RouteOptions#instanceId(String)\n    */\n   public String getInstanceId() {\n      return getFirstFormOrNull(\"InstanceId\");\n   }\n\n   /**\n    * The ID of a VPC peering connection.\n    */\n   public RouteOptions vpcPeeringConnectionId(String vpcPeeringConnectionId) {\n      formParameters.put(\"VpcPeeringConnectionId\", checkNotNull(vpcPeeringConnectionId, \"vpcPeeringConnectionId\"));\n      return this;\n   }\n\n   /**\n    * @see RouteOptions#vpcPeeringConnectionId(String)\n    */\n   public String getVpcPeeringConnectionId() {\n      return getFirstFormOrNull(\"VpcPeeringConnectionId\");\n   }\n\n\n   public static class Builder {\n      /**\n       * @see RouteOptions#dryRun()\n       */\n      public static RouteOptions dryRun() {\n         RouteOptions options = new RouteOptions();\n         return options.dryRun();\n      }\n\n      /**\n       * @see RouteOptions#destinationCidrBlock(java.lang.String)\n       */\n      public static RouteOptions destinationCidrBlock(String destinationCidrBlock) {\n         RouteOptions options = new RouteOptions();\n         return options.destinationCidrBlock(destinationCidrBlock);\n      }\n\n      /**\n       * @see RouteOptions#destinationIpv6CidrBlock(java.lang.String)\n       */\n      public static RouteOptions destinationIpv6CidrBlock(String destinationIpv6CidrBlock) {\n         RouteOptions options = new RouteOptions();\n         return options.destinationIpv6CidrBlock(destinationIpv6CidrBlock);\n      }\n\n      /**\n       * @see RouteOptions#gatewayId(java.lang.String)\n       */\n      public static RouteOptions gatewayId(String gatewayId) {\n         RouteOptions options = new RouteOptions();\n         return options.gatewayId(gatewayId);\n      }\n\n      /**\n       * @see RouteOptions#egressOnlyInternetGatewayId(java.lang.String)\n       */\n      public static RouteOptions egressOnlyInternetGatewayId(String egressOnlyInternetGatewayId) {\n         RouteOptions options = new RouteOptions();\n         return options.egressOnlyInternetGatewayId(egressOnlyInternetGatewayId);\n      }\n\n      /**\n       * @see RouteOptions#natGatewayId(String)\n       */\n      public static RouteOptions natGatewayId(String natGatewayId) {\n         RouteOptions options = new RouteOptions();\n         return options.natGatewayId(natGatewayId);\n      }\n\n      /**\n       * @see RouteOptions#networkInterfaceId(String)\n       */\n      public static RouteOptions networkInterfaceId(String networkInterfaceId) {\n         RouteOptions options = new RouteOptions();\n         return options.networkInterfaceId(networkInterfaceId);\n      }\n\n      /**\n       * @see RouteOptions#vpcPeeringConnectionId(String)\n       */\n      public static RouteOptions vpcPeeringConnectionId(String vpcPeeringConnectionId) {\n         RouteOptions options = new RouteOptions();\n         return options.vpcPeeringConnectionId(vpcPeeringConnectionId);\n      }\n\n      /**\n       * @see RouteOptions#instanceId(String)\n       */\n      public static RouteOptions instanceId(String instanceId) {\n         RouteOptions options = new RouteOptions();\n         return options.instanceId(instanceId);\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/options/RouteTableOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.ec2.options.internal.BaseEC2RequestOptions;\n\n/**\n * Contains options supported in the Form API for the RouteTable operations. <h2>\n * Usage</h2> The recommended way to instantiate such an object is to statically import\n * RouteTableOptions.Builder.* and invoke a static creation method followed by an instance mutator\n * (if needed):\n * <p/>\n * <code>\n * import static org.jclouds.ec2.options.RouteTableOptions.Builder.*\n * <p/>\n * EC2Api connection = // get connection\n * RouteTable table = connection.getRouteTableApi().get().createRouteTable(vpcId, dryRun());\n * <code>\n *\n * @see <a\n * href=\"http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateRouteTable.html\"\n * />\n */\npublic class RouteTableOptions extends BaseEC2RequestOptions {\n\n   /**\n    * Checks whether you have the required permissions for the action, without actually making the request,\n    * and provides an error response.\n    */\n   public RouteTableOptions dryRun() {\n      formParameters.put(\"DryRun\", \"true\");\n      return this;\n   }\n\n   public boolean isDryRun() {\n      return getFirstFormOrNull(\"DryRun\") != null;\n   }\n\n   /**\n    * The IPv4 CIDR address block used for the destination match.\n    * Routing decisions are based on the most specific match.\n    */\n   public RouteTableOptions destinationCidrBlock(String destinationCidrBlock) {\n      formParameters.put(\"DestinationCidrBlock\", checkNotNull(destinationCidrBlock, \"destinationCidrBlock\"));\n      return this;\n   }\n\n\n   public static class Builder {\n      /**\n       * @see RouteTableOptions#dryRun()\n       */\n      public static RouteTableOptions dryRun() {\n         RouteTableOptions options = new RouteTableOptions();\n         return options.dryRun();\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/options/Tenancy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.options;\n\n/**\n * Contains valid values for the 'Placement.Tenancy' parameter in the Form API for the RunInstances operation.\n */\npublic enum Tenancy {\n   DEFAULT(\"default\"),\n   DEDICATED(\"dedicated\"),\n   HOST(\"host\");\n\n   private final String value;\n\n   Tenancy(String value) {\n      this.value = value;\n   }\n\n   @Override\n   public String toString() {\n      return value;\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/predicates/PlacementGroupAvailable.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.predicates;\n\nimport java.util.NoSuchElementException;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.ec2.AWSEC2Api;\nimport org.jclouds.aws.ec2.domain.PlacementGroup;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.rest.ResourceNotFoundException;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Iterables;\nimport com.google.inject.Inject;\n\n@Singleton\npublic class PlacementGroupAvailable implements Predicate<PlacementGroup> {\n\n   private final AWSEC2Api client;\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   @Inject\n   public PlacementGroupAvailable(AWSEC2Api client) {\n      this.client = client;\n   }\n\n   public boolean apply(PlacementGroup group) {\n      logger.trace(\"looking for state on group %s\", group);\n      try {\n         group = refresh(group);\n         logger.trace(\"%s: looking for group state %s: currently: %s\", group.getName(), PlacementGroup.State.AVAILABLE,\n                  group.getState());\n         return group.getState() == PlacementGroup.State.AVAILABLE;\n      } catch (ResourceNotFoundException e) {\n         return false;\n      } catch (NoSuchElementException e) {\n         return false;\n      }\n   }\n\n   private PlacementGroup refresh(PlacementGroup group) {\n      return Iterables.getOnlyElement(client.getPlacementGroupApi().get().describePlacementGroupsInRegion(\n               group.getRegion(), group.getName()));\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/predicates/PlacementGroupDeleted.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.predicates;\n\nimport java.util.NoSuchElementException;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.ec2.AWSEC2Api;\nimport org.jclouds.aws.ec2.domain.PlacementGroup;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Iterables;\nimport com.google.inject.Inject;\n\n@Singleton\npublic class PlacementGroupDeleted implements Predicate<PlacementGroup> {\n\n   private final AWSEC2Api client;\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   @Inject\n   public PlacementGroupDeleted(AWSEC2Api client) {\n      this.client = client;\n   }\n\n   public boolean apply(PlacementGroup group) {\n      logger.trace(\"looking for state on group %s\", group);\n      try {\n         group = refresh(group);\n      } catch (NoSuchElementException e) {\n         return true;\n      }\n      logger.trace(\"%s: looking for group state %s: currently: %s\", group.getName(), PlacementGroup.State.DELETED,\n               group.getState());\n      return group.getState() == PlacementGroup.State.DELETED;\n   }\n\n   private PlacementGroup refresh(PlacementGroup group) {\n      return Iterables.getOnlyElement(client.getPlacementGroupApi().get().describePlacementGroupsInRegion(\n               group.getRegion(), group.getName()));\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/predicates/SpotInstanceRequestActive.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.predicates;\n\nimport java.util.NoSuchElementException;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.ec2.AWSEC2Api;\nimport org.jclouds.aws.ec2.domain.SpotInstanceRequest;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.rest.ResourceNotFoundException;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Iterables;\nimport com.google.inject.Inject;\n\n@Singleton\npublic class SpotInstanceRequestActive implements Predicate<SpotInstanceRequest> {\n\n   private final AWSEC2Api client;\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   @Inject\n   public SpotInstanceRequestActive(AWSEC2Api client) {\n      this.client = client;\n   }\n\n   public boolean apply(SpotInstanceRequest spot) {\n      logger.trace(\"looking for state on spot %s\", spot);\n      try {\n         spot = refresh(spot);\n         logger.trace(\"%s: looking for spot state %s: currently: %s\", spot.getId(), SpotInstanceRequest.State.ACTIVE,\n                  spot.getState());\n         if (spot.getState() == SpotInstanceRequest.State.CANCELLED\n                  || spot.getState() == SpotInstanceRequest.State.CLOSED)\n            throw new IllegalStateException(String.format(\"spot request %s %s\", spot.getId(), spot.getState()));\n         if (spot.getFaultCode() != null)\n            throw new IllegalStateException(String.format(\"spot request %s fault code(%s) message(%s)\", spot.getId(),\n                     spot.getFaultCode(), spot.getFaultMessage()));\n         return spot.getState() == SpotInstanceRequest.State.ACTIVE;\n      } catch (ResourceNotFoundException e) {\n         return false;\n      } catch (NoSuchElementException e) {\n         return false;\n      }\n   }\n\n   private SpotInstanceRequest refresh(SpotInstanceRequest spot) {\n      return Iterables.getOnlyElement(client.getSpotInstanceApi().get().describeSpotInstanceRequestsInRegion(\n               spot.getRegion(), spot.getId()));\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/reference/AWSEC2Constants.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.reference;\n\nimport org.jclouds.ec2.reference.EC2Constants;\n\n/**\n * Configuration properties and constants used in EC2 connections.\n */\npublic final class AWSEC2Constants extends EC2Constants {\n   /**\n    * expression to find amis that work on the cluster instance type <br/>\n    * ex. {@code\n    * virtualization-type=hvm;architecture=x86_64;owner-id=137112412989,099720109477;hypervisor=xen;\n    * state=available;image-type=machine;root-device-type=ebs}\n    * \n    * @see InstanceType.CC1_4XLARGE\n    */\n   public static final String PROPERTY_EC2_CC_AMI_QUERY = \"jclouds.ec2.cc-ami-query\";\n   public static final String PROPERTY_EC2_CC_REGIONS = \"jclouds.ec2.cc-regions\";\n   public static final String PROPERTY_EC2_AMI_QUERY = \"jclouds.ec2.ami-query\";\n\n   private AWSEC2Constants() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/xml/AWSDescribeInstancesResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.xml;\n\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.ec2.domain.Reservation;\nimport org.jclouds.ec2.domain.RunningInstance;\nimport org.jclouds.ec2.xml.TagSetHandler;\nimport org.jclouds.location.Region;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\n\n/**\n * Parses the following XML document:\n * <p/>\n * DescribeImagesResponse xmlns=\"http:\n * \n * @see <a href=\"http: />\n */\npublic class AWSDescribeInstancesResponseHandler extends\n      BaseAWSReservationHandler<Set<Reservation<? extends RunningInstance>>> {\n   private final TagSetHandler tagSetHandler;\n   private Builder<Reservation<? extends RunningInstance>> reservations = ImmutableSet.<Reservation<? extends RunningInstance>>builder();\n   private boolean inTagSet;\n\n   @Inject\n   AWSDescribeInstancesResponseHandler(DateService dateService, @Region Supplier<String> defaultRegion,\n         TagSetHandler tagSetHandler) {\n      super(dateService, defaultRegion);\n      this.tagSetHandler = tagSetHandler;\n   }\n\n   @Override\n   public void startElement(String uri, String name, String qName, Attributes attrs) throws SAXException {\n      super.startElement(uri, name, qName, attrs);\n      if (equalsOrSuffix(qName, \"tagSet\")) {\n         inTagSet = true;\n      }\n      if (inTagSet) {\n         tagSetHandler.startElement(uri, name, qName, attrs);\n      }\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      if (inTagSet) {\n         tagSetHandler.characters(ch, start, length);\n      } else {\n         super.characters(ch, start, length);\n      }\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) {\n      if (equalsOrSuffix(qName, \"tagSet\")) {\n         inTagSet = false;\n         builder.tags(tagSetHandler.getResult());\n      } else if (inTagSet) {\n         tagSetHandler.endElement(uri, name, qName);\n      }\n      super.endElement(uri, name, qName);\n   }\n\n   @Override\n   public Set<Reservation<? extends RunningInstance>> getResult() {\n      return reservations.build();\n   }\n\n   protected boolean endOfReservationItem() {\n      return itemDepth == 1;\n   }\n\n   @Override\n   protected void inItem() {\n      if (endOfReservationItem()) {\n         reservations.add(super.newReservation());\n      } else {\n         super.inItem();\n      }\n   }\n\n   protected boolean endOfInstanceItem() {\n      return itemDepth == 2 && inInstancesSet;\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/xml/AWSEC2DescribeSecurityGroupsResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.xml;\n\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.ec2.domain.SecurityGroup;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.functions.ParseSax.HandlerForGeneratedRequestWithResult;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\n\n/**\n * Parses: DescribeSecurityGroupsResponse\n * xmlns=\"http://ec2.amazonaws.com/doc/2010-06-15/\"\n *\n * @see <a href=\n *      \"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-query-DescribesecurityGroupInfo.html\"\n *      />\n */\npublic class AWSEC2DescribeSecurityGroupsResponseHandler extends\n      HandlerForGeneratedRequestWithResult<Set<SecurityGroup>> {\n\n   private final AWSEC2SecurityGroupHandler securityGroupHandler;\n\n   private StringBuilder currentText = new StringBuilder();\n   private Builder<SecurityGroup> securityGroups = ImmutableSet.<SecurityGroup> builder();\n   private boolean inSecurityGroupInfo;\n\n   protected int itemDepth;\n\n   @Inject\n   public AWSEC2DescribeSecurityGroupsResponseHandler(AWSEC2SecurityGroupHandler securityGroupHandler) {\n      this.securityGroupHandler = securityGroupHandler;\n   }\n\n   @Override\n   public HandlerForGeneratedRequestWithResult<Set<SecurityGroup>> setContext(HttpRequest request) {\n      securityGroupHandler.setContext(request);\n      return super.setContext(request);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Set<SecurityGroup> getResult() {\n      return securityGroups.build();\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void startElement(String url, String name, String qName, Attributes attributes) throws SAXException {\n      if (equalsOrSuffix(qName, \"item\")) {\n         itemDepth++;\n      } else if (equalsOrSuffix(qName, \"securityGroupInfo\")) {\n         inSecurityGroupInfo = true;\n      }\n      if (inSecurityGroupInfo) {\n         securityGroupHandler.startElement(url, name, qName, attributes);\n      }\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void endElement(String uri, String name, String qName) throws SAXException {\n      if (equalsOrSuffix(qName, \"item\")) {\n         endItem(uri, name, qName);\n         itemDepth--;\n      } else if (equalsOrSuffix(qName, \"securityGroupInfo\")) {\n         inSecurityGroupInfo = false;\n      } else if (inSecurityGroupInfo) {\n         securityGroupHandler.endElement(uri, name, qName);\n      }\n      currentText.setLength(0);\n   }\n\n   protected void endItem(String uri, String name, String qName) throws SAXException {\n      if (inSecurityGroupInfo) {\n         if (itemDepth == 1)\n            securityGroups.add(securityGroupHandler.getResult());\n         else\n            securityGroupHandler.endElement(uri, name, qName);\n      }\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      if (inSecurityGroupInfo) {\n         securityGroupHandler.characters(ch, start, length);\n      } else {\n         currentText.append(ch, start, length);\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/xml/AWSEC2IpPermissionHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.xml;\n\nimport static org.jclouds.util.SaxUtils.currentOrNull;\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.net.domain.IpPermission;\nimport org.jclouds.net.domain.IpProtocol;\nimport org.xml.sax.SAXException;\n\npublic class AWSEC2IpPermissionHandler extends ParseSax.HandlerForGeneratedRequestWithResult<IpPermission> {\n\n   private StringBuilder currentText = new StringBuilder();\n   private IpPermission.Builder builder = IpPermission.builder();\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public IpPermission getResult() {\n      try {\n         return builder.build();\n      } finally {\n         builder = IpPermission.builder();\n      }\n   }\n\n   private String userId;\n   private String groupId;\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void endElement(String uri, String name, String qName) throws SAXException {\n      if (equalsOrSuffix(qName, \"ipProtocol\")) {\n         // Algorete: ipProtocol can be an empty tag on EC2 clone (e.g.\n         // OpenStack EC2)\n         builder.ipProtocol(IpProtocol.fromValue(currentOrNegative(currentText)));\n      } else if (equalsOrSuffix(qName, \"fromPort\")) {\n         // Algorete: fromPort can be an empty tag on EC2 clone (e.g. OpenStack\n         // EC2)\n         builder.fromPort(Integer.parseInt(currentOrNegative(currentText)));\n      } else if (equalsOrSuffix(qName, \"toPort\")) {\n         // Algorete: toPort can be an empty tag on EC2 clone (e.g. OpenStack\n         // EC2)\n         builder.toPort(Integer.parseInt(currentOrNegative(currentText)));\n      } else if (equalsOrSuffix(qName, \"cidrIp\")) {\n         builder.cidrBlock(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"userId\")) {\n         this.userId = currentOrNull(currentText);\n      } else if (equalsOrSuffix(qName, \"groupId\")) {\n         this.groupId = currentOrNull(currentText);\n      } else if (equalsOrSuffix(qName, \"item\")) {\n         if (userId != null && groupId != null)\n            builder.tenantIdGroupNamePair(userId, groupId);\n         userId = groupId = null;\n      }\n      currentText.setLength(0);\n   }\n\n   private static String currentOrNegative(StringBuilder currentText) {\n      String returnVal = currentText.toString().trim();\n      return returnVal.equals(\"\") ? \"-1\" : returnVal;\n   }\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/xml/AWSEC2SecurityGroupHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.xml;\n\nimport static org.jclouds.util.SaxUtils.currentOrNull;\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.ec2.domain.SecurityGroup;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.functions.ParseSax.HandlerForGeneratedRequestWithResult;\nimport org.jclouds.location.Region;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\n\nimport com.google.common.base.Supplier;\nimport com.google.inject.Inject;\n\npublic class AWSEC2SecurityGroupHandler extends HandlerForGeneratedRequestWithResult<SecurityGroup> {\n\n   protected final AWSEC2IpPermissionHandler ipPermissionHandler;\n   protected final Supplier<String> defaultRegion;\n\n   protected StringBuilder currentText = new StringBuilder();\n   protected SecurityGroup.Builder<?> builder;\n   protected boolean inIpPermissions;\n\n   protected int itemDepth;\n\n   protected String region;\n\n   @Inject\n   public AWSEC2SecurityGroupHandler(AWSEC2IpPermissionHandler ipPermissionHandler, @Region Supplier<String> defaultRegion) {\n      this.ipPermissionHandler = ipPermissionHandler;\n      this.defaultRegion = defaultRegion;\n   }\n\n   protected SecurityGroup.Builder<?> builder() {\n      return SecurityGroup.builder().region(region);\n   }\n\n   @Override\n   public HandlerForGeneratedRequestWithResult<SecurityGroup> setContext(HttpRequest request) {\n      region = AWSUtils.findRegionInArgsOrNull(GeneratedHttpRequest.class.cast(request));\n      if (region == null)\n         region = defaultRegion.get();\n      builder = builder();\n      return super.setContext(request);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public SecurityGroup getResult() {\n      try {\n         return builder.build();\n      } finally {\n         builder = builder();\n      }\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void startElement(String url, String name, String qName, Attributes attributes) throws SAXException {\n      if (equalsOrSuffix(qName, \"item\")) {\n         itemDepth++;\n      } else if (equalsOrSuffix(qName, \"ipPermissions\")) {\n         inIpPermissions = true;\n      }\n      if (inIpPermissions) {\n         ipPermissionHandler.startElement(url, name, qName, attributes);\n      }\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void endElement(String uri, String name, String qName) throws SAXException {\n      if (equalsOrSuffix(qName, \"item\")) {\n         endItem(uri, name, qName);\n         itemDepth--;\n      } else if (equalsOrSuffix(qName, \"ipPermissions\")) {\n         inIpPermissions = false;\n         itemDepth = 0;\n      } else if (inIpPermissions) {\n         ipPermissionHandler.endElement(uri, name, qName);\n      } else if (equalsOrSuffix(qName, \"groupName\")) {\n         builder.name(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"groupId\")) {\n         builder.id(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"ownerId\")) {\n         builder.ownerId(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"groupDescription\")) {\n         builder.description(currentOrNull(currentText));\n      }\n      currentText.setLength(0);\n   }\n\n   protected void endItem(String uri, String name, String qName) throws SAXException {\n      if (inIpPermissions) {\n         if (itemDepth == 2)\n            builder.ipPermission(ipPermissionHandler.getResult());\n         else\n            ipPermissionHandler.endElement(uri, name, qName);\n      }\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      if (inIpPermissions) {\n         ipPermissionHandler.characters(ch, start, length);\n      } else {\n         currentText.append(ch, start, length);\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/xml/AWSRunInstancesResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.xml;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.ec2.domain.Reservation;\nimport org.jclouds.ec2.domain.RunningInstance;\nimport org.jclouds.location.Region;\n\nimport com.google.common.base.Supplier;\n\n/**\n * Parses the following XML document:\n * <p/>\n * RunInstancesResponse xmlns=\"http:\n * \n * @see <a href=\"http: />\n */\npublic class AWSRunInstancesResponseHandler extends BaseAWSReservationHandler<Reservation<? extends RunningInstance>> {\n\n   @Inject\n   AWSRunInstancesResponseHandler(DateService dateService, @Region Supplier<String> defaultRegion) {\n      super(dateService, defaultRegion);\n   }\n\n   @Override\n   public Reservation<? extends RunningInstance> getResult() {\n      return newReservation();\n   }\n\n   protected boolean endOfInstanceItem() {\n      return itemDepth == 1 && inInstancesSet;\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/xml/AssociateRouteTableResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.xml;\n\nimport org.jclouds.http.functions.ParseSax;\n\npublic class AssociateRouteTableResponseHandler extends ParseSax.HandlerWithResult<String> {\n\n   private StringBuilder currentText = new StringBuilder();\n   private String value;\n\n   public String getResult() {\n      return value;\n   }\n\n   public void endElement(String uri, String name, String qName) {\n      if (qName.equalsIgnoreCase(\"associationId\")) {\n         this.value = currentText.toString().trim();\n      }\n      currentText.setLength(0);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/xml/BaseAWSReservationHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.xml;\n\nimport static org.jclouds.util.SaxUtils.currentOrNull;\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport java.util.Date;\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\n\nimport org.jclouds.aws.ec2.domain.AWSRunningInstance;\nimport org.jclouds.aws.ec2.domain.MonitoringState;\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.date.DateService;\nimport org.jclouds.ec2.domain.Attachment;\nimport org.jclouds.ec2.domain.BlockDevice;\nimport org.jclouds.ec2.domain.Hypervisor;\nimport org.jclouds.ec2.domain.InstanceState;\nimport org.jclouds.ec2.domain.Reservation;\nimport org.jclouds.ec2.domain.RootDeviceType;\nimport org.jclouds.ec2.domain.RunningInstance;\nimport org.jclouds.http.functions.ParseSax.HandlerForGeneratedRequestWithResult;\nimport org.jclouds.location.Region;\nimport org.jclouds.logging.Logger;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.Maps;\nimport com.google.common.collect.Sets;\n\npublic abstract class BaseAWSReservationHandler<T> extends HandlerForGeneratedRequestWithResult<T> {\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   protected final DateService dateService;\n   protected final Supplier<String> defaultRegion;\n\n   protected BaseAWSReservationHandler(DateService dateService, @Region Supplier<String> defaultRegion) {\n      this.dateService = dateService;\n      this.defaultRegion = defaultRegion;\n   }\n\n   protected AWSRunningInstance.Builder builder = newBuilder();\n\n   protected AWSRunningInstance.Builder newBuilder() {\n      return AWSRunningInstance.builder();\n   }\n\n   protected StringBuilder currentText = new StringBuilder();\n   \n   protected int itemDepth;\n   boolean inInstancesSet;\n   // attachments\n   private String volumeId;\n   private Attachment.Status attachmentStatus;\n   private Date attachTime;\n   private boolean deleteOnTermination;\n   private String deviceName;\n\n   // reservation stuff\n   private String groupId;\n   private Map<String, String> reservationGroupIdToNames = Maps.newLinkedHashMap();\n   private String ownerId;\n   private String requesterId;\n   private String reservationId;\n\n   private Set<RunningInstance> instances = Sets.newLinkedHashSet();\n\n   private boolean inPlacement;\n   private boolean inIamInstanceProfile;\n\n   @Override\n   public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException {\n      if (equalsOrSuffix(qName, \"item\")) {\n         itemDepth++;\n      } else if (equalsOrSuffix(qName, \"instancesSet\")) {\n         inInstancesSet = true;\n      } else if (equalsOrSuffix(qName, \"placement\")) {\n         inPlacement = true;\n      } else if (equalsOrSuffix(qName, \"iamInstanceProfile\")) {\n         inIamInstanceProfile = true;\n      }\n   }\n\n   public void endElement(String uri, String name, String qName) {\n      if (equalsOrSuffix(qName, \"item\")) {\n         inItem();\n         itemDepth--;\n      } else if (equalsOrSuffix(qName, \"state\")) {\n         builder.monitoringState(MonitoringState.fromValue(currentOrNull(currentText)));\n      } else if (equalsOrSuffix(qName, \"groupId\")) {\n         groupId = currentOrNull(currentText);\n      } else if (equalsOrSuffix(qName, \"groupName\") && inPlacement) {\n         builder.placementGroup(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"arn\") && inIamInstanceProfile) {\n         builder.iamInstanceProfileArn(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"id\") && inIamInstanceProfile) {\n         builder.iamInstanceProfileId(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"groupName\")) {\n         switch (itemDepth) {\n         case 2:\n            reservationGroupIdToNames.put(groupId, currentOrNull(currentText));\n            break;\n         case 3:\n            builder.securityGroupIdToName(groupId, currentOrNull(currentText));\n            break;\n         }\n         groupId = null;\n      } else if (equalsOrSuffix(qName, \"subnetId\")) {\n         builder.subnetId(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"spotInstanceRequestId\")) {\n         builder.spotInstanceRequestId(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"vpcId\")) {\n         builder.vpcId(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"hypervisor\")) {\n         builder.hypervisor(Hypervisor.fromValue(currentOrNull(currentText)));\n      } else if (equalsOrSuffix(qName, \"productCode\")) {\n         builder.productCode(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"instancesSet\")) {\n         inInstancesSet = false;\n      } else if (equalsOrSuffix(qName, \"placement\")) {\n         inPlacement = false;\n      } else if (equalsOrSuffix(qName, \"iamInstanceProfile\")) {\n         inIamInstanceProfile = false;\n      } else if (equalsOrSuffix(qName, \"ownerId\")) {\n         ownerId = currentOrNull(currentText);\n      } else if (equalsOrSuffix(qName, \"requesterId\")) {\n         requesterId = currentOrNull(currentText);\n      } else if (equalsOrSuffix(qName, \"reservationId\")) {\n         reservationId = currentOrNull(currentText);\n      } else if (equalsOrSuffix(qName, \"amiLaunchIndex\")) {\n         builder.amiLaunchIndex(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"dnsName\")) {\n         builder.dnsName(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"imageId\")) {\n         builder.imageId(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"instanceId\")) {\n         builder.instanceId(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"name\")) {\n         String rawState = currentOrNull(currentText);\n         builder.rawState(rawState);\n         builder.instanceState(InstanceState.fromValue(rawState));\n      } else if (equalsOrSuffix(qName, \"instanceType\")) {\n         builder.instanceType(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"ipAddress\")) {\n         builder.ipAddress(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"kernelId\")) {\n         builder.kernelId(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"keyName\")) {\n         builder.keyName(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"launchTime\")) {\n         builder.launchTime(dateService.iso8601DateOrSecondsDateParse(currentOrNull(currentText)));\n      } else if (equalsOrSuffix(qName, \"availabilityZone\")) {\n         builder.availabilityZone(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"virtualizationType\")) {\n         builder.virtualizationType(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"platform\")) {\n         builder.platform(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"privateDnsName\")) {\n         builder.privateDnsName(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"privateIpAddress\")) {\n         builder.privateIpAddress(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"ramdiskId\")) {\n         builder.ramdiskId(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"reason\")) {\n         builder.reason(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"rootDeviceType\")) {\n         builder.rootDeviceType(RootDeviceType.fromValue(currentOrNull(currentText)));\n      } else if (equalsOrSuffix(qName, \"rootDeviceName\")) {\n         builder.rootDeviceName(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"deviceName\")) {\n         deviceName = currentOrNull(currentText);\n      } else if (equalsOrSuffix(qName, \"volumeId\")) {\n         volumeId = currentOrNull(currentText);\n      } else if (equalsOrSuffix(qName, \"status\")) {\n         attachmentStatus = Attachment.Status.fromValue(currentText.toString().trim());\n      } else if (equalsOrSuffix(qName, \"attachTime\")) {\n         attachTime = dateService.iso8601DateOrSecondsDateParse(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"deleteOnTermination\")) {\n         deleteOnTermination = Boolean.parseBoolean(currentText.toString().trim());\n      } else if (equalsOrSuffix(qName, \"ebs\")) {\n         builder.device(deviceName, new BlockDevice(volumeId, attachmentStatus, attachTime, deleteOnTermination));\n         this.deviceName = null;\n         this.volumeId = null;\n         this.attachmentStatus = null;\n         this.attachTime = null;\n         this.deleteOnTermination = true;\n      }\n      currentText.setLength(0);\n   }\n   \n   protected void inItem() {\n      if (endOfInstanceItem()) {\n         refineBuilderBeforeAddingInstance();\n         instances.add(builder.build());\n         builder = newBuilder();\n      }\n   }\n\n   protected void refineBuilderBeforeAddingInstance() {\n      String region = getRequest() != null ? AWSUtils.findRegionInArgsOrNull(getRequest()) : null;\n      builder.region((region == null) ? defaultRegion.get() : region);\n   }\n\n   protected abstract boolean endOfInstanceItem();\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n\n   protected Reservation<? extends RunningInstance> newReservation() {\n      String region = getRequest() != null ? AWSUtils.findRegionInArgsOrNull(getRequest()) : null;\n      if (region == null)\n         region = defaultRegion.get();\n      Reservation<? extends RunningInstance> info = new Reservation<RunningInstance>(region,\n            reservationGroupIdToNames.values(), instances, ownerId, requesterId, reservationId);\n      this.reservationGroupIdToNames = Maps.newLinkedHashMap();\n      this.instances = Sets.newLinkedHashSet();\n      this.ownerId = null;\n      this.requesterId = null;\n      this.reservationId = null;\n      return info;\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/xml/CreateRouteTableResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.xml;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.aws.ec2.domain.RouteTable;\nimport org.jclouds.http.functions.ParseSax;\nimport org.xml.sax.Attributes;\n\n/**\n * @see <a href=\"http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RouteTable.html\">RouteTable docs</a>\n */\npublic class CreateRouteTableResponseHandler extends ParseSax.HandlerForGeneratedRequestWithResult<RouteTable> {\n\n   private RouteTableHandler routeTableHandler;\n\n   @Inject\n   CreateRouteTableResponseHandler(RouteTableHandler routeTableHandler) {\n      this.routeTableHandler = routeTableHandler;\n   }\n\n   public RouteTable getResult() {\n      return routeTableHandler.getResult();\n   }\n\n   @Override\n   public void startElement(String uri, String name, String qName, Attributes attrs) {\n      routeTableHandler.startElement(uri, name, qName, attrs);\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) {\n      routeTableHandler.endElement(uri, name, qName);\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      routeTableHandler.characters(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/xml/CreateSecurityGroupResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.xml;\n\nimport org.jclouds.http.functions.ParseSax;\n\npublic class CreateSecurityGroupResponseHandler extends ParseSax.HandlerWithResult<String> {\n\n   private StringBuilder currentText = new StringBuilder();\n   String id;\n\n   public String getResult() {\n      return id;\n   }\n\n   public void endElement(String uri, String name, String qName) {\n      if (qName.equals(\"groupId\")) {\n         id = currentText.toString().trim();\n      }\n      currentText.setLength(0);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/xml/DescribeInternetGatewaysResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.xml;\n\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport org.jclouds.aws.ec2.domain.InternetGateway;\nimport org.jclouds.http.functions.ParseSax;\nimport org.xml.sax.Attributes;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\nimport com.google.inject.Inject;\n\n/**\n * @see <a href=\"http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeVpcs.html\">xml</a>\n */\npublic class DescribeInternetGatewaysResponseHandler extends\n      ParseSax.HandlerForGeneratedRequestWithResult<FluentIterable<InternetGateway>> {\n   private final InternetGatewayHandler gatewayHandler;\n   private boolean inAttachmentSet;\n   private boolean inTagSet;\n   private Builder<InternetGateway> gateways = ImmutableSet.builder();\n\n   @Inject\n   DescribeInternetGatewaysResponseHandler(InternetGatewayHandler gatewayHandler) {\n      this.gatewayHandler = gatewayHandler;\n   }\n\n   @Override\n   public FluentIterable<InternetGateway> getResult() {\n      try {\n         return FluentIterable.from(gateways.build());\n      } finally {\n         gateways = ImmutableSet.builder();\n      }\n   }\n\n   @Override\n   public void startElement(String url, String name, String qName, Attributes attributes) {\n      if (equalsOrSuffix(qName, \"attachmentSet\")) {\n         inAttachmentSet = true;\n      } else if (equalsOrSuffix(qName, \"tagSet\")) {\n         inTagSet = true;\n      }\n      gatewayHandler.startElement(url, name, qName, attributes);\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) {\n      if (equalsOrSuffix(qName, \"attachmentSet\")) {\n         inAttachmentSet = false;\n         gatewayHandler.endElement(uri, name, qName);\n      } else if (equalsOrSuffix(qName, \"tagSet\")) {\n         inTagSet = false;\n         gatewayHandler.endElement(uri, name, qName);\n      } else if (equalsOrSuffix(qName, \"item\") && !inTagSet && !inAttachmentSet) {\n         gateways.add(gatewayHandler.getResult());\n      } else {\n         gatewayHandler.endElement(uri, name, qName);\n      }\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      gatewayHandler.characters(ch, start, length);\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/xml/DescribePlacementGroupsResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.xml;\n\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.aws.ec2.domain.PlacementGroup;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.http.functions.ParseSax.HandlerWithResult;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\n\nimport com.google.common.collect.Sets;\n\npublic class DescribePlacementGroupsResponseHandler extends\n         ParseSax.HandlerWithResult<Set<PlacementGroup>> {\n\n   private Set<PlacementGroup> bundleTasks = Sets.newLinkedHashSet();\n   private final PlacementGroupHandler bundleTaskHandler;\n\n   @Inject\n   public DescribePlacementGroupsResponseHandler(PlacementGroupHandler bundleTaskHandler) {\n      this.bundleTaskHandler = bundleTaskHandler;\n   }\n\n   public Set<PlacementGroup> getResult() {\n      return bundleTasks;\n   }\n\n   @Override\n   public HandlerWithResult<Set<PlacementGroup>> setContext(HttpRequest request) {\n      bundleTaskHandler.setContext(request);\n      return super.setContext(request);\n   }\n\n   @Override\n   public void startElement(String uri, String localName, String qName, Attributes attributes)\n            throws SAXException {\n      if (!qName.equals(\"item\"))\n         bundleTaskHandler.startElement(uri, localName, qName, attributes);\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) throws SAXException {\n      if (qName.equals(\"item\")) {\n         bundleTasks.add(bundleTaskHandler.getResult());\n      }\n      bundleTaskHandler.endElement(uri, localName, qName);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      bundleTaskHandler.characters(ch, start, length);\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/xml/DescribeReservedInstancesOfferingResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.xml;\n\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.ec2.domain.ReservedInstancesOffering;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.http.functions.ParseSax.HandlerWithResult;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\n\nimport com.google.common.collect.Sets;\n\npublic class DescribeReservedInstancesOfferingResponseHandler extends\n      ParseSax.HandlerWithResult<Set<ReservedInstancesOffering>> {\n\n   private Set<ReservedInstancesOffering> reservedInstancesOfferings = Sets.newLinkedHashSet();\n   private final ReservedInstancesOfferingHandler reservedInstancesOffering;\n\n   @Inject\n   public DescribeReservedInstancesOfferingResponseHandler(ReservedInstancesOfferingHandler reservedInstancesOffering) {\n      this.reservedInstancesOffering = reservedInstancesOffering;\n   }\n\n   public Set<ReservedInstancesOffering> getResult() {\n      return reservedInstancesOfferings;\n   }\n\n   @Override\n   public HandlerWithResult<Set<ReservedInstancesOffering>> setContext(HttpRequest request) {\n      reservedInstancesOffering.setContext(request);\n      return super.setContext(request);\n   }\n\n   @Override\n   public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {\n      if (!qName.equals(\"item\"))\n         reservedInstancesOffering.startElement(uri, localName, qName, attributes);\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) throws SAXException {\n      if (qName.equals(\"item\")) {\n         reservedInstancesOfferings.add(reservedInstancesOffering.getResult());\n      }\n      reservedInstancesOffering.endElement(uri, localName, qName);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      reservedInstancesOffering.characters(ch, start, length);\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/xml/DescribeRouteTablesResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.xml;\n\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport java.util.List;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.aws.ec2.domain.RouteTable;\nimport org.jclouds.http.functions.ParseSax;\nimport org.xml.sax.Attributes;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.Lists;\n\n/**\n * @see <a href=\"http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RouteTable.html\">RouteTable docs</a>\n */\npublic class DescribeRouteTablesResponseHandler\n   extends ParseSax.HandlerForGeneratedRequestWithResult<FluentIterable<RouteTable>> {\n\n   private RouteTableHandler routeTableHandler;\n   private List<RouteTable> tables = Lists.newArrayList();\n\n   private boolean inRouteSet;\n   private boolean inAssociationSet;\n   private boolean inPropagatingVgwSet;\n   private boolean inTagSet;\n\n   @Inject\n   DescribeRouteTablesResponseHandler(RouteTableHandler routeTableHandler) {\n      this.routeTableHandler = routeTableHandler;\n   }\n\n   public FluentIterable<RouteTable> getResult() {\n      try {\n         return FluentIterable.from(tables);\n      } finally {\n         tables = Lists.newArrayList();\n      }\n   }\n\n   @Override\n   public void startElement(String uri, String name, String qName, Attributes attrs) {\n      if (equalsOrSuffix(qName, \"routeSet\")) {\n         inRouteSet = true;\n      } else if (equalsOrSuffix(qName, \"associationSet\")) {\n         inAssociationSet = true;\n      } else if (equalsOrSuffix(qName, \"tagSet\")) {\n         inTagSet = true;\n      } else if (equalsOrSuffix(qName, \"propagatingVgwSet\")) {\n         inPropagatingVgwSet = true;\n      }\n      routeTableHandler.startElement(uri, name, qName, attrs);\n   }\n\n   private boolean inSubElement() {\n      return inRouteSet || inTagSet || inAssociationSet || inPropagatingVgwSet;\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) {\n      if (equalsOrSuffix(qName, \"routeSet\")) {\n         inRouteSet = false;\n         routeTableHandler.endElement(uri, name, qName);\n      } else if (equalsOrSuffix(qName, \"associationSet\")) {\n         inAssociationSet = false;\n         routeTableHandler.endElement(uri, name, qName);\n      } else if (equalsOrSuffix(qName, \"tagSet\")) {\n         inTagSet = false;\n         routeTableHandler.endElement(uri, name, qName);\n      } else if (equalsOrSuffix(qName, \"item\") && !inSubElement()) {\n         final RouteTable table = routeTableHandler.getResult();\n         tables.add(table);\n      } else {\n         routeTableHandler.endElement(uri, name, qName);\n      }\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      routeTableHandler.characters(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/xml/DescribeSpotPriceHistoryResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.xml;\n\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.aws.ec2.domain.Spot;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.http.functions.ParseSax.HandlerWithResult;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\n\npublic class DescribeSpotPriceHistoryResponseHandler extends\n         ParseSax.HandlerWithResult<Set<Spot>> {\n\n   private Builder<Spot> spots = ImmutableSet.builder();\n   private final SpotHandler spotHandler;\n\n   @Inject\n   public DescribeSpotPriceHistoryResponseHandler(SpotHandler spotHandler) {\n      this.spotHandler = spotHandler;\n   }\n\n   public Set<Spot> getResult() {\n      return spots.build();\n   }\n\n   @Override\n   public HandlerWithResult<Set<Spot>> setContext(HttpRequest request) {\n      spotHandler.setContext(request);\n      return super.setContext(request);\n   }\n\n   @Override\n   public void startElement(String uri, String localName, String qName, Attributes attributes)\n            throws SAXException {\n      if (!qName.equals(\"item\"))\n         spotHandler.startElement(uri, localName, qName, attributes);\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) throws SAXException {\n      if (qName.equals(\"item\")) {\n         spots.add(spotHandler.getResult());\n      }\n      spotHandler.endElement(uri, localName, qName);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      spotHandler.characters(ch, start, length);\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/xml/DescribeVPCsResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.xml;\n\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport org.jclouds.aws.ec2.domain.VPC;\nimport org.jclouds.http.functions.ParseSax;\nimport org.xml.sax.Attributes;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\nimport com.google.inject.Inject;\n\n/**\n * @see <a href=\"http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeVpcs.html\">xml</a>\n */\npublic class DescribeVPCsResponseHandler extends\n      ParseSax.HandlerForGeneratedRequestWithResult<FluentIterable<VPC>> {\n   private final VPCHandler vpcHandler;\n\n   private StringBuilder currentText = new StringBuilder();\n   private boolean inVpcSet;\n   private boolean inTagSet;\n   private Builder<VPC> vpcs = ImmutableSet.builder();\n\n   @Inject\n   public DescribeVPCsResponseHandler(VPCHandler vpcHandler) {\n      this.vpcHandler = vpcHandler;\n   }\n\n   @Override\n   public FluentIterable<VPC> getResult() {\n      return FluentIterable.from(vpcs.build());\n   }\n\n   @Override\n   public void startElement(String url, String name, String qName, Attributes attributes) {\n      if (equalsOrSuffix(qName, \"vpcSet\")) {\n         inVpcSet = true;\n      } else if (inVpcSet) {\n         if (equalsOrSuffix(qName, \"tagSet\")) {\n            inTagSet = true;\n         }\n         vpcHandler.startElement(url, name, qName, attributes);\n      }\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) {\n      if (equalsOrSuffix(qName, \"vpcSet\")) {\n         inVpcSet = false;\n      } else if (equalsOrSuffix(qName, \"tagSet\")) {\n         inTagSet = false;\n         vpcHandler.endElement(uri, name, qName);\n      } else if (equalsOrSuffix(qName, \"item\") && !inTagSet) {\n         vpcs.add(vpcHandler.getResult());\n      } else if (inVpcSet) {\n         vpcHandler.endElement(uri, name, qName);\n      }\n\n      currentText.setLength(0);\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      if (inVpcSet) {\n         vpcHandler.characters(ch, start, length);\n      } else {\n         currentText.append(ch, start, length);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/xml/InternetGatewayAttachmentSetHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.xml;\n\n\nimport java.util.List;\n\nimport org.jclouds.aws.ec2.domain.InternetGatewayAttachment;\nimport org.jclouds.http.functions.ParseSax;\nimport org.xml.sax.Attributes;\n\nimport com.google.common.collect.Lists;\n\npublic class InternetGatewayAttachmentSetHandler extends ParseSax.HandlerWithResult<List<InternetGatewayAttachment>> {\n\n   private StringBuilder currentText = new StringBuilder();\n   private List<InternetGatewayAttachment> result = Lists.newArrayList();\n   private InternetGatewayAttachment.Builder itemBuilder;\n\n   @Override\n   public void startElement(String uri, String name, String qName, Attributes attrs) {\n      currentText.setLength(0);\n      if (qName.equalsIgnoreCase(\"item\")) {\n         itemBuilder = InternetGatewayAttachment.builder();\n      }\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) {\n      if (itemBuilder == null) {\n         return;\n      }\n      if (qName.equalsIgnoreCase(\"item\")) {\n         result.add(itemBuilder.build());\n         itemBuilder = null;\n      } else if (qName.equalsIgnoreCase(\"vpcId\")) {\n         itemBuilder.vpcId(currentText.toString());\n      } else if (qName.equalsIgnoreCase(\"state\")) {\n         itemBuilder.state(InternetGatewayAttachment.State.valueOf(currentText.toString().toUpperCase()));\n      }\n   }\n\n   @Override\n   public List<InternetGatewayAttachment> getResult() {\n      try {\n         return result;\n      } finally {\n         result = Lists.newArrayList();\n      }\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/xml/InternetGatewayHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.xml;\n\nimport static org.jclouds.util.SaxUtils.currentOrNull;\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.aws.ec2.domain.InternetGateway;\nimport org.jclouds.ec2.xml.TagSetHandler;\nimport org.jclouds.http.functions.ParseSax;\nimport org.xml.sax.Attributes;\n\n/**\n * @see <a href=\"http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_InternetGateway.html\">InternetGateway docs</a>\n */\npublic class InternetGatewayHandler extends ParseSax.HandlerForGeneratedRequestWithResult<InternetGateway> {\n   private StringBuilder currentText = new StringBuilder();\n   private InternetGateway.Builder builder = InternetGateway.builder();\n   private final TagSetHandler tagSetHandler;\n   private final InternetGatewayAttachmentSetHandler attachmentSetHandler;\n   private boolean inTagSet;\n   private boolean inAttachmentSet;\n\n\n   @Inject\n   InternetGatewayHandler(TagSetHandler tagSetHandler, InternetGatewayAttachmentSetHandler attachmentHandler) {\n      this.tagSetHandler = tagSetHandler;\n      this.attachmentSetHandler = attachmentHandler;\n   }\n\n   @Override\n   public InternetGateway getResult() {\n      try {\n         return builder.build();\n      } finally {\n         builder = InternetGateway.builder();\n      }\n   }\n\n   @Override\n   public void startElement(String uri, String name, String qName, Attributes attrs) {\n      currentText.setLength(0);\n      if (equalsOrSuffix(qName, \"tagSet\")) {\n         inTagSet = true;\n      }\n      if (equalsOrSuffix(qName, \"attachmentSet\")) {\n         inAttachmentSet = true;\n      }\n      if (inTagSet) {\n         tagSetHandler.startElement(uri, name, qName, attrs);\n      } else if (inAttachmentSet) {\n         attachmentSetHandler.startElement(uri, name, qName, attrs);\n      }\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) {\n      if (equalsOrSuffix(qName, \"tagSet\")) {\n         inTagSet = false;\n         builder.tags(tagSetHandler.getResult());\n      } else if (equalsOrSuffix(qName, \"attachmentSet\")) {\n         inAttachmentSet = false;\n         builder.attachmentSet(attachmentSetHandler.getResult());\n      } else if (inTagSet) {\n         tagSetHandler.endElement(uri, name, qName);\n      } else if (inAttachmentSet) {\n         attachmentSetHandler.endElement(uri, name, qName);\n      } else if (equalsOrSuffix(qName, \"internetGatewayId\")) {\n         builder.id(currentOrNull(currentText));\n      }\n      currentText.setLength(0);\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      if (inTagSet) {\n         tagSetHandler.characters(ch, start, length);\n      } else if (inAttachmentSet) {\n         attachmentSetHandler.characters(ch, start, length);\n      } else {\n        currentText.append(ch, start, length);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/xml/LaunchSpecificationHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.xml;\n\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\n\nimport org.jclouds.aws.ec2.domain.LaunchSpecification;\nimport org.jclouds.aws.ec2.domain.LaunchSpecification.Builder;\nimport org.jclouds.ec2.domain.BlockDeviceMapping;\nimport org.jclouds.http.functions.ParseSax.HandlerForGeneratedRequestWithResult;\nimport org.jclouds.logging.Logger;\nimport org.xml.sax.Attributes;\n\npublic class LaunchSpecificationHandler extends HandlerForGeneratedRequestWithResult<LaunchSpecification> {\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   protected final Builder builder;\n   protected final BlockDeviceMapping.Builder blockDeviceMappingBuilder;\n\n   @Inject\n   public LaunchSpecificationHandler(LaunchSpecification.Builder builder, BlockDeviceMapping.Builder blockDeviceMappingBuilder) {\n      this.builder = builder;\n      this.blockDeviceMappingBuilder = blockDeviceMappingBuilder;\n   }\n\n   protected String currentOrNull() {\n      String returnVal = currentText.toString().trim();\n      return returnVal.equals(\"\") ? null : returnVal;\n   }\n\n   protected StringBuilder currentText = new StringBuilder();\n\n   private boolean inBlockDeviceMapping;\n   private boolean inIamInstanceProfile;\n\n   private String groupId;\n\n   public void startElement(String uri, String name, String qName, Attributes attrs) {\n      if (qName.equals(\"blockDeviceMapping\")) {\n         inBlockDeviceMapping = true;\n      } else if (equalsOrSuffix(qName, \"iamInstanceProfile\")) {\n         inIamInstanceProfile = true;\n      }\n   }\n\n   public void endElement(String uri, String name, String qName) {\n      if (qName.equals(\"blockDeviceMapping\")) {\n         inBlockDeviceMapping = false;\n      } else if (equalsOrSuffix(qName, \"iamInstanceProfile\")) {\n         inIamInstanceProfile = false;\n      } else if (qName.equals(\"item\") && inBlockDeviceMapping) {\n         try {\n            builder.blockDeviceMapping(blockDeviceMappingBuilder.build());\n         } finally {\n            blockDeviceMappingBuilder.clear();\n         }\n      } else if (equalsOrSuffix(qName, \"arn\") && inIamInstanceProfile) {\n         builder.iamInstanceProfileArn(currentOrNull());\n      } else if (equalsOrSuffix(qName, \"name\") && inIamInstanceProfile) {\n         builder.iamInstanceProfileName(currentOrNull());         \n      } else if (qName.equals(\"deviceName\")) {\n         blockDeviceMappingBuilder.deviceName(currentOrNull());\n      } else if (qName.equals(\"virtualName\")) {\n         blockDeviceMappingBuilder.virtualName(currentOrNull());\n      } else if (qName.equals(\"snapshotId\")) {\n         blockDeviceMappingBuilder.snapshotId(currentOrNull());\n      } else if (qName.equals(\"volumeSize\")) {\n         String volumeSize = currentOrNull();\n         if (volumeSize != null)\n            blockDeviceMappingBuilder.sizeInGib(Integer.parseInt(volumeSize));\n      } else if (qName.equals(\"noDevice\")) {\n         String noDevice = currentOrNull();\n         if (noDevice != null)\n            blockDeviceMappingBuilder.noDevice(Boolean.parseBoolean(noDevice));\n      } else if (qName.equals(\"deleteOnTermination\")) {\n         String deleteOnTermination = currentOrNull();\n         if (deleteOnTermination != null)\n            blockDeviceMappingBuilder.deleteOnTermination(Boolean.parseBoolean(deleteOnTermination));\n      } else if (qName.equals(\"groupId\")) {\n         groupId = currentOrNull();\n      } else if (qName.equals(\"groupName\")) {\n         builder.securityGroupIdToName(groupId, currentOrNull());\n         groupId = null;\n      } else if (qName.equals(\"imageId\")) {\n         builder.imageId(currentOrNull());\n      } else if (qName.equals(\"instanceType\")) {\n         builder.instanceType(currentOrNull());\n      } else if (qName.equals(\"kernelId\")) {\n         builder.kernelId(currentOrNull());\n      } else if (qName.equals(\"keyName\")) {\n         builder.keyName(currentOrNull());\n      } else if (qName.equals(\"availabilityZone\")) {\n         builder.availabilityZone(currentOrNull());\n      } else if (qName.equals(\"subnetId\")) {\n         builder.subnetId(currentOrNull());\n      } else if (qName.equals(\"ramdiskId\")) {\n         builder.ramdiskId(currentOrNull());\n      } else if (qName.equals(\"enabled\")) {\n         String monitoringEnabled = currentOrNull();\n         if (monitoringEnabled != null)\n            builder.monitoringEnabled(Boolean.valueOf(monitoringEnabled));\n      }\n      currentText.setLength(0);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n\n   @Override\n   public LaunchSpecification getResult() {\n      try {\n         return builder.build();\n      } finally {\n         builder.clear();\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/xml/MonitoringStateHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.xml;\n\nimport java.util.Map;\n\nimport org.jclouds.aws.ec2.domain.MonitoringState;\nimport org.jclouds.http.functions.ParseSax;\n\nimport com.google.common.collect.Maps;\n\npublic class MonitoringStateHandler extends\n         ParseSax.HandlerWithResult<Map<String, MonitoringState>> {\n   private StringBuilder currentText = new StringBuilder();\n\n   private Map<String, MonitoringState> monitoringState = Maps.newHashMap();\n   private String instanceId;\n   private MonitoringState state;\n\n   public Map<String, MonitoringState> getResult() {\n      return monitoringState;\n   }\n\n   public void endElement(String uri, String name, String qName) {\n      if (qName.equals(\"instanceId\")) {\n         instanceId = currentText.toString().trim();\n      } else if (qName.equals(\"state\")) {\n         state = MonitoringState.fromValue(currentText.toString().trim());\n      } else if (qName.equals(\"item\")) {\n         monitoringState.put(instanceId, state);\n         this.instanceId = null;\n         this.state = null;\n      }\n      currentText.setLength(0);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/xml/PlacementGroupHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.xml;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.aws.ec2.domain.PlacementGroup;\nimport org.jclouds.aws.ec2.domain.PlacementGroup.State;\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.location.Region;\n\nimport com.google.common.base.Supplier;\n\npublic class PlacementGroupHandler extends\n         ParseSax.HandlerForGeneratedRequestWithResult<PlacementGroup> {\n   private StringBuilder currentText = new StringBuilder();\n\n   @Inject\n   @Region\n   Supplier<String> defaultRegion;\n\n   private String name;\n   private String strategy = \"cluster\";\n   private State state;\n\n   public PlacementGroup getResult() {\n      String region = AWSUtils.findRegionInArgsOrNull(getRequest());\n      if (region == null)\n         region = defaultRegion.get();\n      PlacementGroup returnVal = new PlacementGroup(region, name, strategy, state);\n      this.name = null;\n      this.strategy = \"cluster\";\n      this.state = null;\n      return returnVal;\n   }\n\n   public void endElement(String uri, String name, String qName) {\n      if (qName.equals(\"groupName\")) {\n         this.name = currentText.toString().trim();\n      } else if (qName.equals(\"strategy\")) {\n         strategy = currentText.toString().trim();\n      } else if (qName.equals(\"state\")) {\n         state = PlacementGroup.State.fromValue(currentText.toString().trim());\n      }\n      currentText.setLength(0);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/xml/ProductCodesHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.xml;\n\nimport java.util.Set;\n\nimport org.jclouds.http.functions.ParseSax;\n\nimport com.google.common.collect.Sets;\n\n/**\n * \n * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-query-DescribeImageAttribute.html\"\n *      />\n */\npublic class ProductCodesHandler extends ParseSax.HandlerWithResult<Set<String>> {\n\n   private StringBuilder currentText = new StringBuilder();\n   private Set<String> productCodes = Sets.newHashSet();\n\n   public Set<String> getResult() {\n      return productCodes;\n   }\n\n   public void endElement(String uri, String name, String qName) {\n\n      if (qName.equalsIgnoreCase(\"productCode\")) {\n         productCodes.add(currentText.toString().trim());\n      }\n      currentText.setLength(0);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/xml/ReservedInstancesOfferingHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.xml;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.ec2.domain.ReservedInstancesOffering;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.location.Region;\n\nimport com.google.common.base.Supplier;\n\n/**\n * \n * @see <a href=\"http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/index.html?ApiReference-query-DescribeReservedInstancesOfferingsResponseSetItemType.html\"\n *      />\n */\npublic class ReservedInstancesOfferingHandler extends\n      ParseSax.HandlerForGeneratedRequestWithResult<ReservedInstancesOffering> {\n   @Inject\n   @Region\n   Supplier<String> defaultRegion;\n\n   private StringBuilder currentText = new StringBuilder();\n\n   private String availabilityZone;\n   private long duration = 0;\n   private float fixedPrice = 0;\n   private String instanceType;\n   private String productDescription;\n   private String id;\n   private float usagePrice = 0;\n\n   public ReservedInstancesOffering getResult() {\n      String region = AWSUtils.findRegionInArgsOrNull(getRequest());\n      if (region == null)\n         region = defaultRegion.get();\n\n      ReservedInstancesOffering returnVal = new ReservedInstancesOffering(region, availabilityZone, duration,\n            fixedPrice, instanceType, productDescription, id, usagePrice);\n      this.availabilityZone = null;\n      this.duration = 0;\n      this.fixedPrice = 0;\n      this.instanceType = null;\n      this.productDescription = null;\n      this.id = null;\n      this.usagePrice = 0;\n      return returnVal;\n   }\n\n   public void endElement(String uri, String name, String qName) {\n\n      if (qName.equalsIgnoreCase(\"reservedInstancesOfferingId\")) {\n         this.id = currentText.toString().trim();\n      } else if (qName.equalsIgnoreCase(\"availabilityZone\")) {\n         this.availabilityZone = currentText.toString().trim();\n      } else if (qName.equalsIgnoreCase(\"duration\")) {\n         this.duration = Long.parseLong(currentText.toString().trim());\n      } else if (qName.equalsIgnoreCase(\"fixedPrice\")) {\n         this.fixedPrice = Float.parseFloat(currentText.toString().trim());\n      } else if (qName.equalsIgnoreCase(\"instanceType\")) {\n         this.instanceType = currentText.toString().trim();\n      } else if (qName.equalsIgnoreCase(\"productDescription\")) {\n         this.productDescription = currentText.toString().trim();\n      } else if (qName.equalsIgnoreCase(\"usagePrice\")) {\n         this.usagePrice = Float.parseFloat(currentText.toString().trim());\n      }\n      currentText.setLength(0);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/xml/ReturnValueHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.xml;\n\nimport org.jclouds.http.functions.ParseSax;\n\npublic class ReturnValueHandler extends ParseSax.HandlerWithResult<Boolean> {\n\n   private StringBuilder currentText = new StringBuilder();\n   private boolean value;\n\n   public Boolean getResult() {\n      return value;\n   }\n\n   public void endElement(String uri, String name, String qName) {\n      if (qName.equalsIgnoreCase(\"return\")) {\n         this.value = Boolean.parseBoolean(currentText.toString().trim());\n      }\n      currentText.setLength(0);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/xml/RouteHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.xml;\n\nimport org.jclouds.aws.ec2.domain.Route;\nimport org.jclouds.http.functions.ParseSax;\nimport org.xml.sax.Attributes;\n\npublic class RouteHandler extends ParseSax.HandlerForGeneratedRequestWithResult<Route> {\n\n   private StringBuilder currentText = new StringBuilder();\n\n   Route.Builder builder = Route.builder();\n\n   @Override\n   public void startElement(String uri, String localName, String qName, Attributes attributes) {\n\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName)  {\n\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n\n   @Override\n   public Route getResult() {\n      return builder.build();\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/xml/RouteSetHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.xml;\n\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport java.util.List;\n\nimport org.jclouds.aws.ec2.domain.Route;\nimport org.jclouds.aws.ec2.domain.Route.RouteState;\nimport org.jclouds.http.functions.ParseSax;\nimport org.xml.sax.Attributes;\n\nimport com.google.common.collect.Lists;\n\npublic class RouteSetHandler extends ParseSax.HandlerForGeneratedRequestWithResult<List<Route>> {\n\n   private StringBuilder currentText = new StringBuilder();\n   List<Route> results = Lists.newArrayList();\n\n   Route.Builder builder;\n\n   @Override\n   public List<Route> getResult() {\n      try {\n         return results;\n      } finally {\n         results = Lists.newArrayList();\n      }\n   }\n\n   @Override\n   public void startElement(String uri, String localName, String qName, Attributes attributes) {\n      currentText.setLength(0);\n      if (qName.equalsIgnoreCase(\"item\")) {\n         builder = Route.builder();\n      }\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) {\n      if (builder == null) {\n         return;\n      }\n      if (equalsOrSuffix(qName, \"item\")) {\n         results.add(builder.build());\n         builder = null;\n      } else if (equalsOrSuffix(qName, \"destinationCidrBlock\")) {\n         builder.destinationCidrBlock(currentText.toString());\n      } else if (equalsOrSuffix(qName, \"gatewayId\")) {\n         builder.gatewayId(currentText.toString());\n      } else if (equalsOrSuffix(qName, \"state\")) {\n         builder.state(RouteState.fromValue(currentText.toString()));\n      } else if (equalsOrSuffix(qName, \"origin\")) {\n         builder.origin(currentText.toString());\n      }\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/xml/RouteTableAssociationSetHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.xml;\n\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport java.util.List;\n\nimport org.jclouds.aws.ec2.domain.RouteTableAssociation;\nimport org.jclouds.http.functions.ParseSax;\nimport org.xml.sax.Attributes;\n\nimport com.google.common.collect.Lists;\n\npublic class RouteTableAssociationSetHandler extends\n   ParseSax.HandlerForGeneratedRequestWithResult<List<RouteTableAssociation>> {\n\n   private StringBuilder currentText = new StringBuilder();\n   RouteTableAssociation.Builder builder;\n\n   List<RouteTableAssociation> results = Lists.newArrayList();\n\n   @Override\n   public List<RouteTableAssociation> getResult() {\n      try {\n         return results;\n      } finally {\n         results = Lists.newArrayList();\n      }\n   }\n\n\n   @Override\n   public void startElement(String uri, String localName, String qName, Attributes attributes) {\n      currentText.setLength(0);\n      if (qName.equalsIgnoreCase(\"item\")) {\n         builder = RouteTableAssociation.builder();\n      }\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) {\n      if (builder == null) {\n         return;\n      }\n      if (equalsOrSuffix(qName, \"item\")) {\n         results.add(builder.build());\n         builder = null;\n      } else if (equalsOrSuffix(qName, \"routeTableAssociationId\")) {\n         builder.id(currentText.toString());\n      } else if (equalsOrSuffix(qName, \"routeTableId\")) {\n         builder.routeTableId(currentText.toString());\n      } else if (equalsOrSuffix(qName, \"subnetId\")) {\n         builder.subnetId(currentText.toString());\n      } else if (equalsOrSuffix(qName, \"main\")) {\n         builder.main(Boolean.valueOf(currentText.toString()));\n      }\n   }\n\n   @Override\n   public void characters (char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/xml/RouteTableHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.xml;\n\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.aws.ec2.domain.RouteTable;\nimport org.jclouds.ec2.xml.TagSetHandler;\nimport org.jclouds.http.functions.ParseSax;\nimport org.xml.sax.Attributes;\n\npublic class RouteTableHandler extends ParseSax.HandlerWithResult<RouteTable> {\n\n   RouteTable.Builder builder = RouteTable.builder();\n   private StringBuilder currentText = new StringBuilder();\n   private RouteSetHandler routeSetHandler;\n   private RouteTableAssociationSetHandler routeTableAssociationSetHandler;\n   private TagSetHandler tagSetHandler;\n   boolean inRouteSet;\n   boolean inRouteTableAssociationSet;\n   boolean inTagSet;\n   // TODO propagatingVgwSetHandler\n\n\n   @Inject\n   RouteTableHandler(TagSetHandler tagSetHandler, RouteSetHandler routeSetHandler,\n                     RouteTableAssociationSetHandler routeTableAssociationSetHandler) {\n      this.tagSetHandler = tagSetHandler;\n      this.routeSetHandler = routeSetHandler;\n      this.routeTableAssociationSetHandler = routeTableAssociationSetHandler;\n   }\n\n   @Override\n   public RouteTable getResult() {\n      try {\n         return builder.build();\n      } finally {\n         builder = RouteTable.builder();\n      }\n   }\n\n\n   @Override\n   public void startElement(String uri, String name, String qName, Attributes attrs) {\n      currentText.setLength(0);\n      if (equalsOrSuffix(qName, \"routeSet\")) {\n         inRouteSet = true;\n      } else if (equalsOrSuffix(qName, \"associationSet\")) {\n         inRouteTableAssociationSet = true;\n      } else if (equalsOrSuffix(qName, \"tagSet\")) {\n         inTagSet = true;\n      }\n\n      if (inTagSet) {\n         tagSetHandler.startElement(uri, name, qName, attrs);\n      } else if (inRouteTableAssociationSet) {\n         routeTableAssociationSetHandler.startElement(uri, name, qName, attrs);\n      } else if (inRouteSet) {\n         routeSetHandler.startElement(uri, name, qName, attrs);\n      }\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) {\n      if (equalsOrSuffix(qName, \"tagSet\")) {\n         inTagSet = false;\n         builder.tags(tagSetHandler.getResult());\n      } else if (equalsOrSuffix(qName, \"routeSet\")) {\n         inRouteSet = false;\n         builder.routeSet(routeSetHandler.getResult());\n      } else if (equalsOrSuffix(qName, \"associationSet\")) {\n         inRouteTableAssociationSet = false;\n         builder.associationSet(routeTableAssociationSetHandler.getResult());\n      } else if (inRouteSet) {\n         routeSetHandler.endElement(uri, name, qName);\n      } else if (inRouteTableAssociationSet) {\n         routeTableAssociationSetHandler.endElement(uri, name, qName);\n      } else if (inTagSet) {\n         tagSetHandler.endElement(uri, name, qName);\n      } else if (equalsOrSuffix(qName, \"vpcId\")) {\n         builder.vpcId(currentText.toString());\n      } else if (equalsOrSuffix(qName, \"routeTableId\")) {\n         builder.id(currentText.toString());\n      }\n      currentText.setLength(0);\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      if (inRouteSet) {\n         routeSetHandler.characters(ch, start, length);\n      } else if (inRouteTableAssociationSet) {\n         routeTableAssociationSetHandler.characters(ch, start, length);\n      } else if (inTagSet) {\n         tagSetHandler.characters(ch, start, length);\n      } else {\n         currentText.append(ch, start, length);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/xml/SpotHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.xml;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.aws.ec2.domain.Spot;\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.date.DateService;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.location.Region;\n\nimport com.google.common.base.Supplier;\n\npublic class SpotHandler extends ParseSax.HandlerForGeneratedRequestWithResult<Spot> {\n   private StringBuilder currentText = new StringBuilder();\n\n   protected final DateService dateService;\n   protected final Supplier<String> defaultRegion;\n\n   @Inject\n   public SpotHandler(DateService dateService, @Region Supplier<String> defaultRegion) {\n      this.dateService = dateService;\n      this.defaultRegion = defaultRegion;\n   }\n\n   private Spot.Builder builder = Spot.builder();\n\n   public Spot getResult() {\n      try {\n         String region = getRequest() == null ? null : AWSUtils.findRegionInArgsOrNull(getRequest());\n         if (region == null)\n            region = defaultRegion.get();\n         return builder.region(region).build();\n      } finally {\n         builder.clear();\n      }\n   }\n\n   public void endElement(String uri, String name, String qName) {\n      if (qName.equals(\"instanceType\")) {\n         builder.instanceType(currentText.toString().trim());\n      } else if (qName.equals(\"productDescription\")) {\n         builder.productDescription(currentText.toString().trim());\n      } else if (qName.equals(\"spotPrice\")) {\n         builder.spotPrice(Float.parseFloat(currentText.toString().trim()));\n      } else if (qName.equals(\"timestamp\")) {\n         builder.timestamp(dateService.iso8601DateOrSecondsDateParse(currentText.toString().trim()));\n      } else if (qName.equals(\"availabilityZone\")) {\n         builder.availabilityZone(currentText.toString().trim());\n      }\n      currentText.setLength(0);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/xml/SpotInstanceHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.xml;\n\nimport static org.jclouds.util.SaxUtils.currentOrNull;\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.aws.ec2.domain.SpotInstanceRequest;\nimport org.jclouds.aws.ec2.domain.SpotInstanceRequest.Builder;\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.date.DateService;\nimport org.jclouds.ec2.xml.TagSetHandler;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.location.Region;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\n\nimport com.google.common.base.Supplier;\n\npublic class SpotInstanceHandler extends ParseSax.HandlerForGeneratedRequestWithResult<SpotInstanceRequest> {\n   private StringBuilder currentText = new StringBuilder();\n\n   protected final DateService dateService;\n   protected final Supplier<String> defaultRegion;\n   protected final Builder builder;\n   protected boolean inFault;\n   protected boolean inStatus;\n   protected boolean inLaunchSpecification;\n   protected final LaunchSpecificationHandler launchSpecificationHandler;\n   protected boolean inTagSet;\n   protected final TagSetHandler tagSetHandler;\n\n   @Inject\n   public SpotInstanceHandler(DateService dateService, @Region Supplier<String> defaultRegion,\n         LaunchSpecificationHandler launchSpecificationHandler, TagSetHandler tagSetHandler,\n         SpotInstanceRequest.Builder builder) {\n      this.dateService = dateService;\n      this.defaultRegion = defaultRegion;\n      this.launchSpecificationHandler = launchSpecificationHandler;\n      this.tagSetHandler = tagSetHandler;\n      this.builder = builder;\n   }\n\n   public SpotInstanceRequest getResult() {\n      try {\n         String region = getRequest() != null ? AWSUtils.findRegionInArgsOrNull(getRequest()) : null;\n         if (region == null)\n            region = defaultRegion.get();\n         return builder.region(region).build();\n      } finally {\n         builder.clear();\n      }\n   }\n\n   @Override\n   public void startElement(String uri, String name, String qName, Attributes attrs) throws SAXException {\n      if (equalsOrSuffix(qName, \"launchSpecification\")) {\n         inLaunchSpecification = true;\n      } else if (equalsOrSuffix(qName, \"tagSet\")) {\n         inTagSet = true;\n      } else if (equalsOrSuffix(qName, \"fault\")) {\n         inFault = true;\n      } else if (equalsOrSuffix(qName, \"status\")) {\n         inStatus = true;\n      }\n      if (inLaunchSpecification) {\n          launchSpecificationHandler.startElement(uri, name, qName, attrs);\n      } else if (inTagSet) {\n          tagSetHandler.startElement(uri, name, qName, attrs);\n      }\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) throws SAXException {\n      if (equalsOrSuffix(qName, \"tagSet\")) {\n         inTagSet = false;\n         builder.tags(tagSetHandler.getResult());\n      } else if (inTagSet) {\n         tagSetHandler.endElement(uri, name, qName);\n      }\n\n      if (qName.equals(\"launchSpecification\")) {\n         inLaunchSpecification = false;\n         builder.launchSpecification(launchSpecificationHandler.getResult());\n      } else if (inLaunchSpecification) {\n         launchSpecificationHandler.endElement(uri, name, qName);\n      }\n\n      if (qName.equals(\"fault\")) {\n         inFault = false;\n      }\n\n      if (qName.equals(\"status\")) {\n         inStatus = false;\n      }\n\n      if (qName.equals(\"spotInstanceRequestId\")) {\n         builder.id(currentOrNull(currentText));\n      } else if (qName.equals(\"instanceId\")) {\n         builder.instanceId(currentOrNull(currentText));\n      } else if (qName.equals(\"launchedAvailabilityZone\")) {\n         builder.launchedAvailabilityZone(currentOrNull(currentText));\n      } else if (qName.equals(\"availabilityZoneGroup\")) {\n         builder.availabilityZoneGroup(currentOrNull(currentText));\n      } else if (qName.equals(\"launchGroup\")) {\n         builder.launchGroup(currentOrNull(currentText));\n      } else if (qName.equals(\"spotPrice\")) {\n         String price = currentOrNull(currentText);\n         if (price != null)\n            builder.spotPrice(Float.parseFloat(price));\n      } else if (qName.equals(\"type\")) {\n         String type = currentOrNull(currentText);\n         if (type != null)\n            builder.type(SpotInstanceRequest.Type.fromValue(type));\n      } else if (qName.equals(\"state\")) {\n         String rawState = currentOrNull(currentText);\n         if (rawState != null) {\n            builder.rawState(rawState);\n            builder.state(SpotInstanceRequest.State.fromValue(rawState));\n         }\n      } else if (qName.equals(\"createTime\")) {\n         String createTime = currentOrNull(currentText);\n         if (createTime != null)\n            builder.createTime(dateService.iso8601DateOrSecondsDateParse(createTime));\n      } else if (qName.equals(\"productDescription\")) {\n         builder.productDescription(currentOrNull(currentText));\n      } else if (inFault) {\n         if (qName.equals(\"code\")) {\n            builder.faultCode(currentOrNull(currentText));\n         } else if (qName.equals(\"message\")) {\n            builder.faultMessage(currentOrNull(currentText));\n         }\n      } else if (inStatus) {\n         if (qName.equals(\"code\")) {\n            builder.statusCode(currentOrNull(currentText));\n         } else if (qName.equals(\"message\")) {\n            builder.statusMessage(currentOrNull(currentText));\n         } else if (qName.equals(\"updateTime\")) {\n            String updateTime = currentOrNull(currentText);\n            if (updateTime != null)\n               builder.statusUpdateTime(dateService.iso8601DateOrSecondsDateParse(updateTime));\n         }\n      } else if (qName.equals(\"validFrom\")) {\n         String validFrom = currentOrNull(currentText);\n         if (validFrom != null)\n            builder.validFrom(dateService.iso8601DateOrSecondsDateParse(validFrom));\n      } else if (qName.equals(\"validUntil\")) {\n         String validUntil = currentOrNull(currentText);\n         if (validUntil != null)\n            builder.validUntil(dateService.iso8601DateOrSecondsDateParse(validUntil));\n      }\n      currentText.setLength(0);\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      if (inLaunchSpecification) {\n         launchSpecificationHandler.characters(ch, start, length);\n      } else if (inTagSet) {\n         tagSetHandler.characters(ch, start, length);\n      } else {\n         currentText.append(ch, start, length);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/xml/SpotInstancesHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.xml;\n\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.aws.ec2.domain.SpotInstanceRequest;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.http.functions.ParseSax.HandlerWithResult;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\n\npublic class SpotInstancesHandler extends ParseSax.HandlerWithResult<Set<SpotInstanceRequest>> {\n\n   private final Builder<SpotInstanceRequest> spotRequests = ImmutableSet.builder();\n   private final SpotInstanceHandler spotRequestHandler;\n   private int itemDepth;\n\n   @Inject\n   public SpotInstancesHandler(SpotInstanceHandler spotRequestHandler) {\n      this.spotRequestHandler = spotRequestHandler;\n   }\n\n   public Set<SpotInstanceRequest> getResult() {\n      return spotRequests.build();\n   }\n\n   @Override\n   public HandlerWithResult<Set<SpotInstanceRequest>> setContext(HttpRequest request) {\n      spotRequestHandler.setContext(request);\n      return super.setContext(request);\n   }\n\n   @Override\n   public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {\n      if (qName.equals(\"item\"))\n         itemDepth++;\n      if (itemDepth >= 1)\n         spotRequestHandler.startElement(uri, localName, qName, attributes);\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) throws SAXException {\n      if (qName.equals(\"item\") && itemDepth == 1) {\n         spotRequests.add(spotRequestHandler.getResult());\n      }\n      if (qName.equals(\"item\"))\n         itemDepth--;\n      if (itemDepth >= 1)\n         spotRequestHandler.endElement(uri, localName, qName);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      if (itemDepth >= 1)\n         spotRequestHandler.characters(ch, start, length);\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/xml/VPCHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.xml;\n\nimport static org.jclouds.util.SaxUtils.currentOrNull;\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.aws.ec2.domain.VPC;\nimport org.jclouds.ec2.xml.TagSetHandler;\nimport org.jclouds.http.functions.ParseSax;\nimport org.xml.sax.Attributes;\n\n/**\n * @see <a href=\"http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_Vpc.html\" >xml</a>\n */\npublic class VPCHandler extends ParseSax.HandlerForGeneratedRequestWithResult<VPC> {\n   private StringBuilder currentText = new StringBuilder();\n   private VPC.Builder builder = VPC.builder();\n   private final TagSetHandler tagSetHandler;\n   private boolean inTagSet;\n\n   @Inject\n   public VPCHandler(TagSetHandler tagSetHandler) {\n      this.tagSetHandler = tagSetHandler;\n   }\n\n   @Override\n   public VPC getResult() {\n      try {\n         return builder.build();\n      } finally {\n         builder = VPC.builder();\n      }\n   }\n\n   @Override\n   public void startElement(String uri, String name, String qName, Attributes attrs) {\n      if (equalsOrSuffix(qName, \"tagSet\")) {\n         inTagSet = true;\n      }\n      if (inTagSet) {\n         tagSetHandler.startElement(uri, name, qName, attrs);\n      }\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) {\n      if (equalsOrSuffix(qName, \"tagSet\")) {\n         inTagSet = false;\n         builder.tags(tagSetHandler.getResult());\n      } else if (inTagSet) {\n         tagSetHandler.endElement(uri, name, qName);\n      } else if (equalsOrSuffix(qName, \"dhcpOptionsId\")) {\n         builder.dhcpOptionsId(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"state\")) {\n         builder.state(VPC.State.fromValue(currentOrNull(currentText)));\n      } else if (equalsOrSuffix(qName, \"vpcId\")) {\n         builder.id(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"cidrBlock\")) {\n         builder.cidrBlock(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"instanceTenancy\")) {\n         builder.instanceTenancy(VPC.InstanceTenancy.fromValue(currentOrNull(currentText)));\n      } else if (equalsOrSuffix(qName, \"isDefault\")) {\n         builder.isDefault(Boolean.parseBoolean(currentText.toString().trim()));\n      }\n      currentText.setLength(0);\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      if (inTagSet) {\n         tagSetHandler.characters(ch, start, length);\n      } else {\n         currentText.append(ch, start, length);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/AWSEC2ContextBuilderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2;\n\nimport static org.jclouds.aws.ec2.reference.AWSEC2Constants.PROPERTY_EC2_AMI_QUERY;\nimport static org.jclouds.ec2.reference.EC2Constants.PROPERTY_EC2_AMI_OWNERS;\nimport static org.jclouds.reflect.Reflection2.typeToken;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Map;\nimport java.util.Properties;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.View;\nimport org.jclouds.aws.ec2.compute.config.ImageQuery;\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.ec2.EC2Api;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Key;\nimport com.google.inject.TypeLiteral;\n\n@Test(groups = \"unit\", testName = \"AWSEC2ContextBuilderTest\")\npublic class AWSEC2ContextBuilderTest {\n   private Map<String, String> queriesForProperties(Properties input) {\n      return ContextBuilder.newBuilder(new AWSEC2ProviderMetadata()).overrides(input).credentials(\"foo\", \"bar\")\n               .buildInjector().getInstance(Key.get(new TypeLiteral<Map<String, String>>() {\n               }, ImageQuery.class));\n   }\n\n   public void testAssignability() {\n      View view = ContextBuilder.newBuilder(new AWSEC2ProviderMetadata()).credentials(\"foo\", \"bar\")\n              .buildView(typeToken(ComputeServiceContext.class));\n      view.unwrapApi(EC2Api.class);\n      view.unwrapApi(AWSEC2Api.class);\n   }\n\n   public void testConvertImageSyntax() {\n      Properties input = new Properties();\n      input.setProperty(PROPERTY_EC2_AMI_OWNERS, \"137112412989,063491364108,099720109477,411009282317\");\n      Map<String, String> queries = queriesForProperties(input);\n      assertEquals(queries.get(PROPERTY_EC2_AMI_OWNERS), null);\n      assertEquals(queries.get(PROPERTY_EC2_AMI_QUERY),\n               \"owner-id=137112412989,063491364108,099720109477,411009282317;state=available;image-type=machine\");\n   }\n\n   public void testConvertImageSyntaxWhenStar() {\n      Properties input = new Properties();\n      input.setProperty(PROPERTY_EC2_AMI_OWNERS, \"*\");\n      Map<String, String> queries = queriesForProperties(input);\n      assertEquals(queries.get(PROPERTY_EC2_AMI_OWNERS), null);\n      assertEquals(queries.get(PROPERTY_EC2_AMI_QUERY), \"state=available;image-type=machine\");\n   }\n\n   public void testBlankAmiOwnersRemovesAmiQuery() {\n      Properties input = new Properties();\n      input.setProperty(PROPERTY_EC2_AMI_OWNERS, \"\");\n      Map<String, String> queries = queriesForProperties(input);\n      assertEquals(queries.get(PROPERTY_EC2_AMI_OWNERS), null);\n      assertEquals(queries.get(PROPERTY_EC2_AMI_QUERY), null);\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/AWSEC2ProviderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2;\n\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.testng.annotations.Test;\n\n/**\n * The AWSEC2ProviderTest tests the org.jclouds.providers.AWSEC2Provider class.\n */\n@Test(groups = \"unit\", testName = \"AWSEC2ProviderTest\")\npublic class AWSEC2ProviderTest extends BaseProviderMetadataTest {\n\n   public AWSEC2ProviderTest() {\n      super(new AWSEC2ProviderMetadata(), new AWSEC2ApiMetadata());\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/binders/BindLaunchSpecificationToFormParamsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.binders;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.io.BaseEncoding.base64;\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.UnknownHostException;\n\nimport org.jclouds.aws.ec2.domain.LaunchSpecification;\nimport org.jclouds.ec2.domain.InstanceType;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\n\n@Test(groups = \"unit\")\npublic class BindLaunchSpecificationToFormParamsTest {\n   BindLaunchSpecificationToFormParams binder = new BindLaunchSpecificationToFormParams();\n\n   @Test\n   public void testApplyWithBlockDeviceMappings() throws UnknownHostException {\n      LaunchSpecification spec = LaunchSpecification.builder().instanceType(InstanceType.T1_MICRO).imageId(\"ami-123\")\n            .mapNewVolumeToDevice(\"/dev/sda1\", 120, true).build();\n\n      assertEquals(binder.apply(spec), ImmutableMap.of(\"LaunchSpecification.InstanceType\", \"t1.micro\",\n            \"LaunchSpecification.ImageId\", \"ami-123\", \"LaunchSpecification.BlockDeviceMapping.1.DeviceName\",\n            \"/dev/sda1\", \"LaunchSpecification.BlockDeviceMapping.1.Ebs.VolumeSize\", \"120\",\n            \"LaunchSpecification.BlockDeviceMapping.1.Ebs.DeleteOnTermination\", \"true\"));\n   }\n\n   @Test\n   public void testApplyWithUserData() throws UnknownHostException {\n      LaunchSpecification spec = LaunchSpecification.builder().instanceType(InstanceType.T1_MICRO).imageId(\"ami-123\")\n            .userData(\"hello\".getBytes()).build();\n\n      assertEquals(binder.apply(spec), ImmutableMap.of(\"LaunchSpecification.InstanceType\", \"t1.micro\",\n            \"LaunchSpecification.ImageId\", \"ami-123\", \"LaunchSpecification.UserData\",\n            base64().encode(\"hello\".getBytes(UTF_8))));\n   }\n\n   @Test\n   public void testApplyWithSecurityId() throws UnknownHostException {\n      LaunchSpecification spec = LaunchSpecification.builder().instanceType(InstanceType.T1_MICRO).imageId(\"ami-123\")\n            .securityGroupId(\"sid-foo\").build();\n\n      assertEquals(binder.apply(spec), ImmutableMap.of(\"LaunchSpecification.InstanceType\", \"t1.micro\",\n            \"LaunchSpecification.ImageId\", \"ami-123\", \"LaunchSpecification.SecurityGroupId.1\", \"sid-foo\"));\n   }\n\n   @Test\n   public void testApplyWithSubnetId() throws UnknownHostException {\n      LaunchSpecification spec = LaunchSpecification.builder().instanceType(InstanceType.T1_MICRO).imageId(\"ami-123\")\n            .subnetId(\"subnet-xyz\").build();\n\n      assertEquals(binder.apply(spec), ImmutableMap.of(\"LaunchSpecification.InstanceType\", \"t1.micro\",\n            \"LaunchSpecification.ImageId\", \"ami-123\", \"LaunchSpecification.SubnetId\", \"subnet-xyz\"));\n   }\n\n   @Test\n   public void testApplyWithIAMInstanceProfileArn() {\n      LaunchSpecification spec = LaunchSpecification.builder()\n            .instanceType(InstanceType.T1_MICRO)\n            .imageId(\"ami-123\")\n            .iamInstanceProfileArn(\"arn:aws:iam::123456789012:instance-profile/application_abc/component_xyz/Webserver\")\n            .build();\n\n      assertEquals(binder.apply(spec), ImmutableMap.of(\"LaunchSpecification.InstanceType\", \"t1.micro\",\n            \"LaunchSpecification.ImageId\", \"ami-123\", \"LaunchSpecification.IamInstanceProfile.Arn\",\n            \"arn:aws:iam::123456789012:instance-profile/application_abc/component_xyz/Webserver\"));\n   }\n\n   @Test\n   public void testApplyWithIAMInstanceProfileName() {\n      LaunchSpecification spec = LaunchSpecification.builder().instanceType(InstanceType.T1_MICRO).imageId(\"ami-123\")\n            .iamInstanceProfileName(\"Webserver\").build();\n\n      assertEquals(binder.apply(spec), ImmutableMap.of(\"LaunchSpecification.InstanceType\", \"t1.micro\",\n            \"LaunchSpecification.ImageId\", \"ami-123\", \"LaunchSpecification.IamInstanceProfile.Name\", \"Webserver\"));\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/binders/BindTagsToIndexedFormParamsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.File;\n\nimport org.jclouds.http.HttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n/**\n * Tests behavior of {@code BindTagsToIndexedFormParams}\n */\n@Test(groups = \"unit\")\npublic class BindTagsToIndexedFormParamsTest {\n   Injector injector = Guice.createInjector();\n   BindTagsToIndexedFormParams binder = injector.getInstance(BindTagsToIndexedFormParams.class);\n\n   public void test() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      request = binder.bindToRequest(request, ImmutableMap.<String, String>builder().put(\"one\", \"alpha\").put(\"two\", \"beta\").build());\n      assertEquals(request.getPayload().getRawContent(), \"Tag.1.Key=one&Tag.1.Value=alpha&Tag.2.Key=two&Tag.2.Value=beta\");\n   }\n\n   public void testEmpty() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      request = binder.bindToRequest(request, ImmutableMap.<String, String>builder().put(\"empty\", \"\").build());\n      assertEquals(request.getPayload().getRawContent(), \"Tag.1.Key=empty&Tag.1.Value=\");\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testMustBeArray() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      binder.bindToRequest(request, new File(\"foo\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testNullIsBad() {\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").build();\n      binder.bindToRequest(request, null);\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/AWSEC2ComputeServiceApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.compute;\n\nimport static org.jclouds.aws.ec2.compute.AWSEC2TemplateOptions.Builder.blockUntilRunning;\nimport static org.testng.Assert.assertEquals;\n\nimport okhttp3.mockwebserver.MockResponse;\n\nimport org.jclouds.aws.ec2.internal.BaseAWSEC2ApiMockTest;\nimport org.jclouds.aws.ec2.options.Tenancy;\nimport org.jclouds.compute.ComputeService;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.predicates.NodePredicates;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Iterables;\n\n@Test(groups = \"unit\", testName = \"AWSEC2ComputeServiceMockTest\", singleThreaded = true)\npublic class AWSEC2ComputeServiceApiMockTest extends BaseAWSEC2ApiMockTest {\n\n   protected String getDefaultSmallestInstanceType() {\n      // NOT t2.xxx because that requires a VPC\n      return \"a1.medium\";\n   }\n     \n   protected String getDefaultParavirtualInstanceType() {\n      // smallest non-deprecated instance type supporting paravirtual\n       return \"m3.medium\";\n   }\n\n   protected String getDefaultImageId() {\n       return \"7ea24a17\";\n   }\n   \n   public void launchVPCSpotInstanceSubnetId() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(DEFAULT_REGION, \"/availabilityZones.xml\");\n      enqueueXml(DEFAULT_REGION, \"/describe_images.xml\");\n      enqueueXml(DEFAULT_REGION, \"/describe_images_cc.xml\");\n      enqueueXml(DEFAULT_REGION, \"/describe_subnets.xml\");\n      enqueueXml(DEFAULT_REGION, \"/created_securitygroup.xml\");\n      enqueueXml(DEFAULT_REGION, \"/new_securitygroup.xml\");\n      enqueueXml(DEFAULT_REGION, \"/new_securitygroup.xml\");\n      enqueueXml(DEFAULT_REGION, \"/authorize_securitygroup_ingress_response.xml\");\n      enqueueXml(DEFAULT_REGION, \"/request_spot_instances-ebs.xml\");\n      enqueueXml(DEFAULT_REGION, \"/request_spot_instances-ebs.xml\");\n      enqueueXml(DEFAULT_REGION, \"/describe_images_ebs.xml\");\n      enqueue(DEFAULT_REGION, new MockResponse()); // create tags\n\n      ComputeService computeService = computeService();\n\n      Template template = computeService.templateBuilder().locationId(\"us-east-1a\").build();\n\n      template.getOptions().as(AWSEC2TemplateOptions.class)\n            .spotPrice(1f).subnetId(\"subnet-9d4a7b6c\").keyPair(\"Demo\").blockUntilRunning(false);\n\n      NodeMetadata node = Iterables.getOnlyElement(computeService.createNodesInGroup(\"test\", 1, template));\n      assertEquals(node.getId(), \"us-east-1/sir-228e6406\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeAvailabilityZones\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeImages&Filter.1.Name=owner-id&Filter.1.Value.1=137112412989&Filter.1.Value.2=801119661308&Filter.1.Value.3=063491364108&Filter.1.Value.4=099720109477&Filter.1.Value.5=411009282317&Filter.2.Name=state&Filter.2.Value.1=available&Filter.3.Name=image-type&Filter.3.Value.1=machine\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeImages&Filter.1.Name=virtualization-type&Filter.1.Value.1=hvm&Filter.2.Name=architecture&Filter.2.Value.1=x86_64&Filter.3.Name=owner-id&Filter.3.Value.1=137112412989&Filter.3.Value.2=099720109477&Filter.4.Name=hypervisor&Filter.4.Value.1=xen&Filter.5.Name=state&Filter.5.Value.1=available&Filter.6.Name=image-type&Filter.6.Value.1=machine&Filter.7.Name=root-device-type&Filter.7.Value.1=ebs\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeSubnets&SubnetId.1=subnet-9d4a7b6c\");\n      assertPosted(DEFAULT_REGION, \"Action=CreateSecurityGroup&GroupName=jclouds%23test&GroupDescription=jclouds%23test&VpcId=vpc-1a2b3c4d\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeSecurityGroups&Filter.1.Name=group-name&Filter.1.Value.1=jclouds%23test\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeSecurityGroups&GroupId.1=sg-3c6ef654\");\n      assertPosted(DEFAULT_REGION, \"Action=AuthorizeSecurityGroupIngress&GroupId=sg-3c6ef654&IpPermissions.0.IpProtocol=tcp&IpPermissions.0.FromPort=22&IpPermissions.0.ToPort=22&IpPermissions.0.IpRanges.0.CidrIp=0.0.0.0/0&IpPermissions.1.IpProtocol=tcp&IpPermissions.1.FromPort=0&IpPermissions.1.ToPort=65535&IpPermissions.1.Groups.0.UserId=993194456877&IpPermissions.1.Groups.0.GroupId=sg-3c6ef654&IpPermissions.2.IpProtocol=udp&IpPermissions.2.FromPort=0&IpPermissions.2.ToPort=65535&IpPermissions.2.Groups.0.UserId=993194456877&IpPermissions.2.Groups.0.GroupId=sg-3c6ef654\");\n      assertPosted(DEFAULT_REGION, \"Action=RequestSpotInstances&SpotPrice=1.0&InstanceCount=1&LaunchSpecification.ImageId=ami-\" + getDefaultImageId() + \"&LaunchSpecification.Placement.AvailabilityZone=us-east-1a&LaunchSpecification.SecurityGroupId.1=sg-3c6ef654&LaunchSpecification.InstanceType=\" + getDefaultSmallestInstanceType() + \"&LaunchSpecification.SubnetId=subnet-9d4a7b6c&LaunchSpecification.KeyName=Demo&LaunchSpecification.UserData=I2Nsb3VkLWNvbmZpZwpyZXBvX3VwZ3JhZGU6IG5vbmUK\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeSpotInstanceRequests&SpotInstanceRequestId.1=sir-228e6406\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeImages&ImageId.1=ami-595a0a1c\");\n      assertPosted(DEFAULT_REGION, \"Action=CreateTags&Tag.1.Key=Name&Tag.1.Value=test-228e6406&ResourceId.1=sir-228e6406\");\n   }\n\n   String iamInstanceProfileArn = \"arn:aws:iam::123456789012:instance-profile/application_abc/component_xyz/Webserver\";\n\n   public void launchSpotInstanceIAMInstanceProfileArn() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(DEFAULT_REGION, \"/availabilityZones.xml\");\n      enqueueXml(DEFAULT_REGION, \"/describe_images.xml\");\n      enqueueXml(DEFAULT_REGION, \"/describe_images_cc.xml\");\n      enqueueXml(DEFAULT_REGION, \"/created_securitygroup.xml\");\n      enqueueXml(DEFAULT_REGION, \"/new_securitygroup.xml\");\n      enqueueXml(DEFAULT_REGION, \"/new_securitygroup.xml\");\n      enqueueXml(DEFAULT_REGION, \"/authorize_securitygroup_ingress_response.xml\");\n      enqueueXml(DEFAULT_REGION, \"/request_spot_instances-ebs.xml\");\n      enqueueXml(DEFAULT_REGION, \"/request_spot_instances-ebs.xml\");\n      enqueueXml(DEFAULT_REGION, \"/describe_images_ebs.xml\");\n      enqueue(DEFAULT_REGION, new MockResponse()); // create tags\n\n      ComputeService computeService = computeService();\n\n      Template template = computeService.templateBuilder().locationId(\"us-east-1a\").build();\n\n      template.getOptions().as(AWSEC2TemplateOptions.class).spotPrice(1f).iamInstanceProfileArn(iamInstanceProfileArn)\n            .noKeyPair().blockUntilRunning(false);\n\n      NodeMetadata node = Iterables.getOnlyElement(computeService.createNodesInGroup(\"test\", 1, template));\n      assertEquals(node.getId(), \"us-east-1/sir-228e6406\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeAvailabilityZones\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeImages&Filter.1.Name=owner-id&Filter.1.Value.1=137112412989&Filter.1.Value.2=801119661308&Filter.1.Value.3=063491364108&Filter.1.Value.4=099720109477&Filter.1.Value.5=411009282317&Filter.2.Name=state&Filter.2.Value.1=available&Filter.3.Name=image-type&Filter.3.Value.1=machine\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeImages&Filter.1.Name=virtualization-type&Filter.1.Value.1=hvm&Filter.2.Name=architecture&Filter.2.Value.1=x86_64&Filter.3.Name=owner-id&Filter.3.Value.1=137112412989&Filter.3.Value.2=099720109477&Filter.4.Name=hypervisor&Filter.4.Value.1=xen&Filter.5.Name=state&Filter.5.Value.1=available&Filter.6.Name=image-type&Filter.6.Value.1=machine&Filter.7.Name=root-device-type&Filter.7.Value.1=ebs\");\n      assertPosted(DEFAULT_REGION, \"Action=CreateSecurityGroup&GroupName=jclouds%23test&GroupDescription=jclouds%23test\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeSecurityGroups&Filter.1.Name=group-name&Filter.1.Value.1=jclouds%23test\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeSecurityGroups&GroupId.1=sg-3c6ef654\");\n      assertPosted(DEFAULT_REGION, \"Action=AuthorizeSecurityGroupIngress&GroupId=sg-3c6ef654&IpPermissions.0.IpProtocol=tcp&IpPermissions.0.FromPort=22&IpPermissions.0.ToPort=22&IpPermissions.0.IpRanges.0.CidrIp=0.0.0.0/0&IpPermissions.1.IpProtocol=tcp&IpPermissions.1.FromPort=0&IpPermissions.1.ToPort=65535&IpPermissions.1.Groups.0.UserId=993194456877&IpPermissions.1.Groups.0.GroupId=sg-3c6ef654&IpPermissions.2.IpProtocol=udp&IpPermissions.2.FromPort=0&IpPermissions.2.ToPort=65535&IpPermissions.2.Groups.0.UserId=993194456877&IpPermissions.2.Groups.0.GroupId=sg-3c6ef654\");\n      assertPosted(DEFAULT_REGION, \"Action=RequestSpotInstances&SpotPrice=1.0&InstanceCount=1&LaunchSpecification.ImageId=ami-\" + getDefaultImageId() + \"&LaunchSpecification.Placement.AvailabilityZone=us-east-1a&LaunchSpecification.SecurityGroupId.1=sg-3c6ef654&LaunchSpecification.InstanceType=\" + getDefaultSmallestInstanceType() + \"&LaunchSpecification.UserData=I2Nsb3VkLWNvbmZpZwpyZXBvX3VwZ3JhZGU6IG5vbmUK&LaunchSpecification.IamInstanceProfile.Arn=arn%3Aaws%3Aiam%3A%3A123456789012%3Ainstance-profile/application_abc/component_xyz/Webserver\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeSpotInstanceRequests&SpotInstanceRequestId.1=sir-228e6406\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeImages&ImageId.1=ami-595a0a1c\");\n      assertPosted(DEFAULT_REGION, \"Action=CreateTags&Tag.1.Key=Name&Tag.1.Value=test-228e6406&ResourceId.1=sir-228e6406\");\n   }\n\n   public void launchSpotInstanceIAMInstanceProfileName() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(DEFAULT_REGION, \"/availabilityZones.xml\");\n      enqueueXml(DEFAULT_REGION, \"/describe_images.xml\");\n      enqueueXml(DEFAULT_REGION, \"/describe_images_cc.xml\");\n      enqueueXml(DEFAULT_REGION, \"/created_securitygroup.xml\");\n      enqueueXml(DEFAULT_REGION, \"/new_securitygroup.xml\");\n      enqueueXml(DEFAULT_REGION, \"/new_securitygroup.xml\");\n      enqueueXml(DEFAULT_REGION, \"/authorize_securitygroup_ingress_response.xml\");\n      enqueueXml(DEFAULT_REGION, \"/request_spot_instances-ebs.xml\");\n      enqueueXml(DEFAULT_REGION, \"/request_spot_instances-ebs.xml\");\n      enqueueXml(DEFAULT_REGION, \"/describe_images_ebs.xml\");\n      enqueue(DEFAULT_REGION, new MockResponse()); // create tags\n\n      ComputeService computeService = computeService();\n\n      Template template = computeService.templateBuilder().locationId(\"us-east-1a\").build();\n\n      template.getOptions().as(AWSEC2TemplateOptions.class).spotPrice(1f).iamInstanceProfileName(\"Webserver\")\n            .noKeyPair().blockUntilRunning(false);\n\n      NodeMetadata node = Iterables.getOnlyElement(computeService.createNodesInGroup(\"test\", 1, template));\n      assertEquals(node.getId(), \"us-east-1/sir-228e6406\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeAvailabilityZones\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeImages&Filter.1.Name=owner-id&Filter.1.Value.1=137112412989&Filter.1.Value.2=801119661308&Filter.1.Value.3=063491364108&Filter.1.Value.4=099720109477&Filter.1.Value.5=411009282317&Filter.2.Name=state&Filter.2.Value.1=available&Filter.3.Name=image-type&Filter.3.Value.1=machine\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeImages&Filter.1.Name=virtualization-type&Filter.1.Value.1=hvm&Filter.2.Name=architecture&Filter.2.Value.1=x86_64&Filter.3.Name=owner-id&Filter.3.Value.1=137112412989&Filter.3.Value.2=099720109477&Filter.4.Name=hypervisor&Filter.4.Value.1=xen&Filter.5.Name=state&Filter.5.Value.1=available&Filter.6.Name=image-type&Filter.6.Value.1=machine&Filter.7.Name=root-device-type&Filter.7.Value.1=ebs\");\n      assertPosted(DEFAULT_REGION, \"Action=CreateSecurityGroup&GroupName=jclouds%23test&GroupDescription=jclouds%23test\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeSecurityGroups&Filter.1.Name=group-name&Filter.1.Value.1=jclouds%23test\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeSecurityGroups&GroupId.1=sg-3c6ef654\");\n      assertPosted(DEFAULT_REGION, \"Action=AuthorizeSecurityGroupIngress&GroupId=sg-3c6ef654&IpPermissions.0.IpProtocol=tcp&IpPermissions.0.FromPort=22&IpPermissions.0.ToPort=22&IpPermissions.0.IpRanges.0.CidrIp=0.0.0.0/0&IpPermissions.1.IpProtocol=tcp&IpPermissions.1.FromPort=0&IpPermissions.1.ToPort=65535&IpPermissions.1.Groups.0.UserId=993194456877&IpPermissions.1.Groups.0.GroupId=sg-3c6ef654&IpPermissions.2.IpProtocol=udp&IpPermissions.2.FromPort=0&IpPermissions.2.ToPort=65535&IpPermissions.2.Groups.0.UserId=993194456877&IpPermissions.2.Groups.0.GroupId=sg-3c6ef654\");\n      assertPosted(DEFAULT_REGION, \"Action=RequestSpotInstances&SpotPrice=1.0&InstanceCount=1&LaunchSpecification.ImageId=ami-\" + getDefaultImageId() + \"&LaunchSpecification.Placement.AvailabilityZone=us-east-1a&LaunchSpecification.SecurityGroupId.1=sg-3c6ef654&LaunchSpecification.InstanceType=\" + getDefaultSmallestInstanceType() + \"&LaunchSpecification.UserData=I2Nsb3VkLWNvbmZpZwpyZXBvX3VwZ3JhZGU6IG5vbmUK&LaunchSpecification.IamInstanceProfile.Name=Webserver\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeSpotInstanceRequests&SpotInstanceRequestId.1=sir-228e6406\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeImages&ImageId.1=ami-595a0a1c\");\n      assertPosted(DEFAULT_REGION, \"Action=CreateTags&Tag.1.Key=Name&Tag.1.Value=test-228e6406&ResourceId.1=sir-228e6406\");\n   }\n\n   public void createNodeWithIAMInstanceProfileArn() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(DEFAULT_REGION, \"/amzn_images.xml\");\n      enqueueXml(DEFAULT_REGION, \"/describe_images_cc.xml\");\n      enqueueXml(DEFAULT_REGION, \"/availabilityZones.xml\");\n      enqueueXml(DEFAULT_REGION, \"/created_securitygroup.xml\");\n      enqueueXml(DEFAULT_REGION, \"/new_securitygroup.xml\");\n      enqueueXml(DEFAULT_REGION, \"/new_securitygroup.xml\");\n      enqueueXml(DEFAULT_REGION, \"/authorize_securitygroup_ingress_response.xml\");\n      enqueueXml(DEFAULT_REGION, \"/new_instance.xml\");\n      enqueueXml(DEFAULT_REGION, \"/describe_instances_running-1.xml\");\n      enqueueXml(DEFAULT_REGION, \"/describe_images.xml\");\n      enqueue(DEFAULT_REGION, new MockResponse()); // create tags\n\n      ComputeService computeService = computeService();\n\n      NodeMetadata node = Iterables.getOnlyElement(computeService.createNodesInGroup(\"test\", 1,\n            blockUntilRunning(false).iamInstanceProfileArn(iamInstanceProfileArn).noKeyPair()));\n      assertEquals(node.getId(), \"us-east-1/i-2baa5550\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeImages&Filter.1.Name=owner-id&Filter.1.Value.1=137112412989&Filter.1.Value.2=801119661308&Filter.1.Value.3=063491364108&Filter.1.Value.4=099720109477&Filter.1.Value.5=411009282317&Filter.2.Name=state&Filter.2.Value.1=available&Filter.3.Name=image-type&Filter.3.Value.1=machine\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeImages&Filter.1.Name=virtualization-type&Filter.1.Value.1=hvm&Filter.2.Name=architecture&Filter.2.Value.1=x86_64&Filter.3.Name=owner-id&Filter.3.Value.1=137112412989&Filter.3.Value.2=099720109477&Filter.4.Name=hypervisor&Filter.4.Value.1=xen&Filter.5.Name=state&Filter.5.Value.1=available&Filter.6.Name=image-type&Filter.6.Value.1=machine&Filter.7.Name=root-device-type&Filter.7.Value.1=ebs\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeAvailabilityZones\");\n      assertPosted(DEFAULT_REGION, \"Action=CreateSecurityGroup&GroupName=jclouds%23test&GroupDescription=jclouds%23test\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeSecurityGroups&Filter.1.Name=group-name&Filter.1.Value.1=jclouds%23test\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeSecurityGroups&GroupId.1=sg-3c6ef654\");\n      assertPosted(DEFAULT_REGION, \"Action=AuthorizeSecurityGroupIngress&GroupId=sg-3c6ef654&IpPermissions.0.IpProtocol=tcp&IpPermissions.0.FromPort=22&IpPermissions.0.ToPort=22&IpPermissions.0.IpRanges.0.CidrIp=0.0.0.0/0&IpPermissions.1.IpProtocol=tcp&IpPermissions.1.FromPort=0&IpPermissions.1.ToPort=65535&IpPermissions.1.Groups.0.UserId=993194456877&IpPermissions.1.Groups.0.GroupId=sg-3c6ef654&IpPermissions.2.IpProtocol=udp&IpPermissions.2.FromPort=0&IpPermissions.2.ToPort=65535&IpPermissions.2.Groups.0.UserId=993194456877&IpPermissions.2.Groups.0.GroupId=sg-3c6ef654\");\n      assertPosted(DEFAULT_REGION, \"Action=RunInstances&ImageId=ami-8ce4b5c9&MinCount=1&MaxCount=1&InstanceType=\" + getDefaultParavirtualInstanceType() + \"&SecurityGroupId.1=sg-3c6ef654&UserData=I2Nsb3VkLWNvbmZpZwpyZXBvX3VwZ3JhZGU6IG5vbmUK&IamInstanceProfile.Arn=arn%3Aaws%3Aiam%3A%3A123456789012%3Ainstance-profile/application_abc/component_xyz/Webserver\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeInstances&InstanceId.1=i-2baa5550\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeImages&ImageId.1=ami-aecd60c7\");\n      assertPosted(DEFAULT_REGION, \"Action=CreateTags&Tag.1.Key=Name&Tag.1.Value=test-2baa5550&ResourceId.1=i-2baa5550\");\n   }\n\n   public void createNodeWithIAMInstanceProfileName() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(DEFAULT_REGION, \"/amzn_images.xml\");\n      enqueueXml(DEFAULT_REGION, \"/describe_images_cc.xml\");\n      enqueueXml(DEFAULT_REGION, \"/availabilityZones.xml\");\n      enqueueXml(DEFAULT_REGION, \"/created_securitygroup.xml\");\n      enqueueXml(DEFAULT_REGION, \"/new_securitygroup.xml\");\n      enqueueXml(DEFAULT_REGION, \"/new_securitygroup.xml\");\n      enqueueXml(DEFAULT_REGION, \"/authorize_securitygroup_ingress_response.xml\");\n      enqueueXml(DEFAULT_REGION, \"/new_instance.xml\");\n      enqueueXml(DEFAULT_REGION, \"/describe_instances_running-1.xml\");\n      enqueueXml(DEFAULT_REGION, \"/describe_images.xml\");\n      enqueue(DEFAULT_REGION, new MockResponse()); // create tags\n\n      ComputeService computeService = computeService();\n\n      NodeMetadata node = Iterables.getOnlyElement(computeService.createNodesInGroup(\"test\", 1,\n            blockUntilRunning(false).iamInstanceProfileName(\"Webserver\").noKeyPair()));\n      assertEquals(node.getId(), \"us-east-1/i-2baa5550\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeImages&Filter.1.Name=owner-id&Filter.1.Value.1=137112412989&Filter.1.Value.2=801119661308&Filter.1.Value.3=063491364108&Filter.1.Value.4=099720109477&Filter.1.Value.5=411009282317&Filter.2.Name=state&Filter.2.Value.1=available&Filter.3.Name=image-type&Filter.3.Value.1=machine\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeImages&Filter.1.Name=virtualization-type&Filter.1.Value.1=hvm&Filter.2.Name=architecture&Filter.2.Value.1=x86_64&Filter.3.Name=owner-id&Filter.3.Value.1=137112412989&Filter.3.Value.2=099720109477&Filter.4.Name=hypervisor&Filter.4.Value.1=xen&Filter.5.Name=state&Filter.5.Value.1=available&Filter.6.Name=image-type&Filter.6.Value.1=machine&Filter.7.Name=root-device-type&Filter.7.Value.1=ebs\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeAvailabilityZones\");\n      assertPosted(DEFAULT_REGION, \"Action=CreateSecurityGroup&GroupName=jclouds%23test&GroupDescription=jclouds%23test\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeSecurityGroups&Filter.1.Name=group-name&Filter.1.Value.1=jclouds%23test\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeSecurityGroups&GroupId.1=sg-3c6ef654\");\n      assertPosted(DEFAULT_REGION, \"Action=AuthorizeSecurityGroupIngress&GroupId=sg-3c6ef654&IpPermissions.0.IpProtocol=tcp&IpPermissions.0.FromPort=22&IpPermissions.0.ToPort=22&IpPermissions.0.IpRanges.0.CidrIp=0.0.0.0/0&IpPermissions.1.IpProtocol=tcp&IpPermissions.1.FromPort=0&IpPermissions.1.ToPort=65535&IpPermissions.1.Groups.0.UserId=993194456877&IpPermissions.1.Groups.0.GroupId=sg-3c6ef654&IpPermissions.2.IpProtocol=udp&IpPermissions.2.FromPort=0&IpPermissions.2.ToPort=65535&IpPermissions.2.Groups.0.UserId=993194456877&IpPermissions.2.Groups.0.GroupId=sg-3c6ef654\");\n      assertPosted(DEFAULT_REGION, \"Action=RunInstances&ImageId=ami-8ce4b5c9&MinCount=1&MaxCount=1&InstanceType=\" + getDefaultParavirtualInstanceType() + \"&SecurityGroupId.1=sg-3c6ef654&UserData=I2Nsb3VkLWNvbmZpZwpyZXBvX3VwZ3JhZGU6IG5vbmUK&IamInstanceProfile.Name=Webserver\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeInstances&InstanceId.1=i-2baa5550\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeImages&ImageId.1=ami-aecd60c7\");\n      assertPosted(DEFAULT_REGION, \"Action=CreateTags&Tag.1.Key=Name&Tag.1.Value=test-2baa5550&ResourceId.1=i-2baa5550\");\n   }\n\n   public void createNodeWithDedicatedTenancyAndHostId() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(DEFAULT_REGION, \"/amzn_images.xml\");\n      enqueueXml(DEFAULT_REGION, \"/describe_images_cc.xml\");\n      enqueueXml(DEFAULT_REGION, \"/availabilityZones.xml\");\n      enqueueXml(DEFAULT_REGION, \"/created_securitygroup.xml\");\n      enqueueXml(DEFAULT_REGION, \"/new_securitygroup.xml\");\n      enqueueXml(DEFAULT_REGION, \"/new_securitygroup.xml\");\n      enqueueXml(DEFAULT_REGION, \"/authorize_securitygroup_ingress_response.xml\");\n      enqueueXml(DEFAULT_REGION, \"/new_instance.xml\");\n      enqueueXml(DEFAULT_REGION, \"/describe_instances_running-1.xml\");\n      enqueueXml(DEFAULT_REGION, \"/describe_images.xml\");\n      enqueue(DEFAULT_REGION, new MockResponse()); // create tags\n\n      ComputeService computeService = computeService();\n\n      NodeMetadata node = Iterables.getOnlyElement(computeService.createNodesInGroup(\"test\", 1,\n            blockUntilRunning(false).noKeyPair().tenancy(Tenancy.HOST).dedicatedHostId(\"TestHostId\")));\n      assertEquals(node.getId(), \"us-east-1/i-2baa5550\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeImages&Filter.1.Name=owner-id&Filter.1.Value.1=137112412989&Filter.1.Value.2=801119661308&Filter.1.Value.3=063491364108&Filter.1.Value.4=099720109477&Filter.1.Value.5=411009282317&Filter.2.Name=state&Filter.2.Value.1=available&Filter.3.Name=image-type&Filter.3.Value.1=machine\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeImages&Filter.1.Name=virtualization-type&Filter.1.Value.1=hvm&Filter.2.Name=architecture&Filter.2.Value.1=x86_64&Filter.3.Name=owner-id&Filter.3.Value.1=137112412989&Filter.3.Value.2=099720109477&Filter.4.Name=hypervisor&Filter.4.Value.1=xen&Filter.5.Name=state&Filter.5.Value.1=available&Filter.6.Name=image-type&Filter.6.Value.1=machine&Filter.7.Name=root-device-type&Filter.7.Value.1=ebs\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeAvailabilityZones\");\n      assertPosted(DEFAULT_REGION, \"Action=CreateSecurityGroup&GroupName=jclouds%23test&GroupDescription=jclouds%23test\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeSecurityGroups&Filter.1.Name=group-name&Filter.1.Value.1=jclouds%23test\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeSecurityGroups&GroupId.1=sg-3c6ef654\");\n      assertPosted(DEFAULT_REGION, \"Action=AuthorizeSecurityGroupIngress&GroupId=sg-3c6ef654&IpPermissions.0.IpProtocol=tcp&IpPermissions.0.FromPort=22&IpPermissions.0.ToPort=22&IpPermissions.0.IpRanges.0.CidrIp=0.0.0.0/0&IpPermissions.1.IpProtocol=tcp&IpPermissions.1.FromPort=0&IpPermissions.1.ToPort=65535&IpPermissions.1.Groups.0.UserId=993194456877&IpPermissions.1.Groups.0.GroupId=sg-3c6ef654&IpPermissions.2.IpProtocol=udp&IpPermissions.2.FromPort=0&IpPermissions.2.ToPort=65535&IpPermissions.2.Groups.0.UserId=993194456877&IpPermissions.2.Groups.0.GroupId=sg-3c6ef654\");\n      assertPosted(DEFAULT_REGION, \"Action=RunInstances&ImageId=ami-8ce4b5c9&MinCount=1&MaxCount=1&InstanceType=\" + getDefaultParavirtualInstanceType() + \"&SecurityGroupId.1=sg-3c6ef654&UserData=I2Nsb3VkLWNvbmZpZwpyZXBvX3VwZ3JhZGU6IG5vbmUK&Placement.Tenancy=host&Placement.HostId=TestHostId\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeInstances&InstanceId.1=i-2baa5550\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeImages&ImageId.1=ami-aecd60c7\");\n      assertPosted(DEFAULT_REGION, \"Action=CreateTags&Tag.1.Key=Name&Tag.1.Value=test-2baa5550&ResourceId.1=i-2baa5550\");\n   }\n\n   public void listNodesWhereImageDoesntExist() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(DEFAULT_REGION, \"/describe_instances_running-1.xml\");\n      enqueueXml(DEFAULT_REGION, \"/availabilityZones.xml\");\n      enqueue(DEFAULT_REGION, new MockResponse().setBody(\"<DescribeImagesResponse><imagesSet></imagesSet></DescribeImagesResponse>\"));\n      enqueue(DEFAULT_REGION, new MockResponse().setBody(\"<DescribeSpotInstanceRequestsResponse><spotInstanceRequestSet></spotInstanceRequestSet></DescribeSpotInstanceRequestsResponse>\"));\n\n      ComputeService computeService = computeService();\n\n      NodeMetadata node = Iterables.getOnlyElement(computeService.listNodesDetailsMatching(NodePredicates.all()));\n      assertEquals(node.getId(), \"us-east-1/i-2baa5550\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeInstances\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeAvailabilityZones\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeImages&ImageId.1=ami-aecd60c7\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeSpotInstanceRequests\");\n   }\n   \n   public void deleteIncidentalResourcesSuccessfully() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(DEFAULT_REGION, \"/describe_securitygroups_extension_single.xml\");\n      enqueueXml(DEFAULT_REGION, \"/delete_securitygroup.xml\");\n      enqueueXml(DEFAULT_REGION, \"/describe_keypairs_jcloudssingle.xml\");\n      enqueueXml(DEFAULT_REGION, \"/describe_instances_empty.xml\");\n      enqueueXml(DEFAULT_REGION, \"/delete_keypair.xml\");\n      enqueueXml(DEFAULT_REGION, \"/describe_placement_groups.xml\");\n      enqueueXml(DEFAULT_REGION, \"/delete_placementgroup.xml\");\n      enqueueXml(DEFAULT_REGION, \"/describe_placement_groups_empty.xml\");\n\n      AWSEC2ComputeService computeService = (AWSEC2ComputeService) computeService();\n\n      computeService.cleanUpIncidentalResources(DEFAULT_REGION, \"sg-3c6ef654\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeSecurityGroups&Filter.1.Name=group-name&Filter.1.Value.1=jclouds%23sg-3c6ef654\");\n      assertPosted(DEFAULT_REGION, \"Action=DeleteSecurityGroup&GroupId=sg-3c6ef654\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeKeyPairs&Filter.1.Name=key-name&Filter.1.Value.1=jclouds%23sg-3c6ef654%23%2A\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeInstances&Filter.1.Name=instance-state-name&Filter.1.Value.1=terminated&Filter.1.Value.2=shutting-down&Filter.2.Name=key-name&Filter.2.Value.1=jclouds%23sg-3c6ef654\");\n      assertPosted(DEFAULT_REGION, \"Action=DeleteKeyPair&KeyName=jclouds%23sg-3c6ef654\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribePlacementGroups&GroupName.1=jclouds%23sg-3c6ef654%23us-east-1\");\n      assertPosted(DEFAULT_REGION, \"Action=DeletePlacementGroup&GroupName=jclouds%23sg-3c6ef654%23us-east-1\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribePlacementGroups&GroupName.1=jclouds%23sg-3c6ef654%23us-east-1\");\n   }\n\n   public void deleteIncidentalResourcesGivingDependencyViolationForSecurityGroup() throws Exception {\n      runDeleteIncidentalResourcesGivingErrForSecurityGroup(\"DependencyViolation\");\n   }\n   \n   public void deleteIncidentalResourcesGivingInUseForSecurityGroup() throws Exception {\n      runDeleteIncidentalResourcesGivingErrForSecurityGroup(\"InvalidGroup.InUse\");\n   }\n   \n   protected void runDeleteIncidentalResourcesGivingErrForSecurityGroup(String errCode) throws Exception {\n      // Does not return delete_securitygroup.xml, but instead gives a 400 error.\n      // Because super.builder has set TIMEOUT_CLEANUP_INCIDENTAL_RESOURCES to 0, it will not retry.\n\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(DEFAULT_REGION, \"/describe_securitygroups_extension_single.xml\");\n      enqueue(DEFAULT_REGION, new MockResponse().setResponseCode(400).setBody(\"<Response><Errors><Error><Code>\" + errCode + \"</Code><Message>resource sg-3c6ef654 has a dependent object</Message></Error></Errors><RequestID>e4f4c78f-4455-43dd-b5cb-9af0bc4bc804</RequestID></Response>\"));\n      enqueueXml(DEFAULT_REGION, \"/describe_placement_groups.xml\");\n      enqueueXml(DEFAULT_REGION, \"/delete_placementgroup.xml\");\n      enqueueXml(DEFAULT_REGION, \"/describe_placement_groups_empty.xml\");\n\n      AWSEC2ComputeService computeService = (AWSEC2ComputeService) computeService();\n\n      computeService.cleanUpIncidentalResources(DEFAULT_REGION, \"sg-3c6ef654\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeSecurityGroups&Filter.1.Name=group-name&Filter.1.Value.1=jclouds%23sg-3c6ef654\");\n      assertPosted(DEFAULT_REGION, \"Action=DeleteSecurityGroup&GroupId=sg-3c6ef654\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribePlacementGroups&GroupName.1=jclouds%23sg-3c6ef654%23us-east-1\");\n      assertPosted(DEFAULT_REGION, \"Action=DeletePlacementGroup&GroupName=jclouds%23sg-3c6ef654%23us-east-1\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribePlacementGroups&GroupName.1=jclouds%23sg-3c6ef654%23us-east-1\");\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/AWSEC2ComputeServiceLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.compute;\n\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static org.jclouds.compute.domain.OsFamily.AMZN_LINUX;\nimport static org.jclouds.compute.options.RunScriptOptions.Builder.runAsRoot;\nimport static org.jclouds.compute.util.ComputeServiceUtils.getCores;\nimport static org.jclouds.ec2.util.IpPermissions.permit;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Date;\nimport java.util.Set;\nimport java.util.concurrent.TimeUnit;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.aws.cloudwatch.AWSCloudWatchProviderMetadata;\nimport org.jclouds.aws.ec2.AWSEC2Api;\nimport org.jclouds.aws.ec2.domain.AWSRunningInstance;\nimport org.jclouds.aws.ec2.domain.MonitoringState;\nimport org.jclouds.aws.ec2.features.AWSSecurityGroupApi;\nimport org.jclouds.cloudwatch.CloudWatchApi;\nimport org.jclouds.cloudwatch.domain.Dimension;\nimport org.jclouds.cloudwatch.domain.EC2Constants;\nimport org.jclouds.cloudwatch.domain.GetMetricStatistics;\nimport org.jclouds.cloudwatch.domain.GetMetricStatisticsResponse;\nimport org.jclouds.cloudwatch.domain.Statistics;\nimport org.jclouds.cloudwatch.domain.Unit;\nimport org.jclouds.compute.domain.ExecResponse;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.predicates.NodePredicates;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.ec2.compute.EC2ComputeServiceLiveTest;\nimport org.jclouds.ec2.domain.KeyPair;\nimport org.jclouds.ec2.domain.Reservation;\nimport org.jclouds.ec2.domain.RunningInstance;\nimport org.jclouds.ec2.features.InstanceApi;\nimport org.jclouds.ec2.features.KeyPairApi;\nimport org.jclouds.net.domain.IpProtocol;\nimport org.jclouds.scriptbuilder.domain.Statements;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.util.concurrent.ListenableFuture;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"AWSEC2ComputeServiceLiveTest\")\npublic class AWSEC2ComputeServiceLiveTest extends EC2ComputeServiceLiveTest {\n\n   public AWSEC2ComputeServiceLiveTest() {\n      provider = \"aws-ec2\";\n      group = \"ec2\";\n   }\n\n   @Override\n   protected void checkVolumes(Hardware hardware) {\n      // Not all hardware profiles define volumes. Don't check their size\n   }\n\n   @Override\n   @Test\n   public void testExtendedOptionsAndLogin() throws Exception {\n      String region = \"us-west-2\";\n\n      AWSSecurityGroupApi securityGroupApi = view.unwrapApi(AWSEC2Api.class).getSecurityGroupApi().get();\n\n      KeyPairApi keyPairApi = view.unwrapApi(AWSEC2Api.class).getKeyPairApi().get();\n\n      InstanceApi instanceApi = view.unwrapApi(AWSEC2Api.class).getInstanceApi().get();\n\n      String group = this.group + \"o\";\n\n      Date before = new Date();\n\n      ImmutableMap<String, String> userMetadata = ImmutableMap.<String, String> of(\"test\", group);\n\n      ImmutableSet<String> tags = ImmutableSet.of(group);\n\n      // note that if you change the location, you must also specify image parameters\n      Template template = client.templateBuilder().locationId(region).osFamily(AMZN_LINUX).os64Bit(true).build();\n      template.getOptions().tags(tags);\n      template.getOptions().userMetadata(userMetadata);\n      template.getOptions().tags(tags);\n      template.getOptions().as(AWSEC2TemplateOptions.class).enableMonitoring();\n      template.getOptions().as(AWSEC2TemplateOptions.class).spotPrice(0.05f);\n\n      String startedId = null;\n      try {\n         cleanupExtendedStuffInRegion(region, securityGroupApi, keyPairApi, group);\n\n         Thread.sleep(3000);  // eventual consistency if deletes actually occurred.\n\n         // create a security group that allows ssh in so that our scripts later\n         // will work\n         String groupId = securityGroupApi.createSecurityGroupInRegionAndReturnId(region, group, group);\n\n         securityGroupApi.authorizeSecurityGroupIngressInRegion(region, groupId, permit(IpProtocol.TCP).port(22));\n\n         template.getOptions().as(AWSEC2TemplateOptions.class).securityGroupIds(groupId);\n\n         // create a keypair to pass in as well\n         KeyPair result = keyPairApi.createKeyPairInRegion(region, group);\n         template.getOptions().as(AWSEC2TemplateOptions.class).keyPair(result.getKeyName());\n\n         // pass in the private key, so that we can run a script with it\n         assert result.getKeyMaterial() != null : result;\n         template.getOptions().overrideLoginPrivateKey(result.getKeyMaterial());\n\n         Set<? extends NodeMetadata> nodes = client.createNodesInGroup(group, 1, template);\n         NodeMetadata first = getOnlyElement(nodes);\n\n         checkUserMetadataContains(first, userMetadata);\n         checkTagsInNodeEquals(first, tags);\n\n         assert first.getCredentials() != null : first;\n         assert first.getCredentials().identity != null : first;\n\n         startedId = first.getProviderId();\n\n         Reservation<? extends RunningInstance> reservation = getOnlyElement(instanceApi\n                  .describeInstancesInRegion(region, startedId));\n         AWSRunningInstance instance = AWSRunningInstance.class.cast(getOnlyElement(reservation));\n\n         assertEquals(instance.getKeyName(), group);\n         assert instance.getSpotInstanceRequestId() != null;\n         assertEquals(instance.getMonitoringState(), MonitoringState.ENABLED);\n\n         // generate some load\n         ListenableFuture<ExecResponse> future = client.submitScriptOnNode(first.getId(), Statements\n                  .exec(\"while true; do true; done\"), runAsRoot(false).nameTask(\"cpuSpinner\"));\n\n         // monitoring granularity for free tier is 5 minutes, so lets make sure we have data.\n         Thread.sleep(TimeUnit.MILLISECONDS.convert(5, TimeUnit.MINUTES));\n\n         // stop the spinner\n         future.cancel(true);\n\n         CloudWatchApi monitoringApi = ContextBuilder.newBuilder(new AWSCloudWatchProviderMetadata())\n                                                     .credentials(identity, credential)\n                                                     .modules(setupModules())\n                                                     .buildApi(CloudWatchApi.class);\n\n         try {\n            GetMetricStatisticsResponse datapoints = monitoringApi.getMetricApiForRegion(instance.getRegion())\n                     .getMetricStatistics(GetMetricStatistics.builder()\n                                                             .dimension(new Dimension(EC2Constants.Dimension.INSTANCE_ID, instance.getId()))\n                                                             .unit(Unit.PERCENT)\n                                                             .namespace(\"AWS/EC2\")\n                                                             .metricName(\"CPUUtilization\")\n                                                             .startTime(before)\n                                                             .endTime(new Date())\n                                                             .period(60)\n                                                             .statistic(Statistics.AVERAGE)\n                                                             .build());\n            assert !datapoints.isEmpty() : instance;\n         } finally {\n            monitoringApi.close();\n         }\n\n         // try to run a script with the original keyPair\n         runScriptWithCreds(group, first.getOperatingSystem(), LoginCredentials.builder().user(\n                  first.getCredentials().identity).privateKey(result.getKeyMaterial()).build());\n\n      } finally {\n         client.destroyNodesMatching(NodePredicates.inGroup(group));\n         if (startedId != null) {\n            // ensure we didn't delete these resources!\n            assertEquals(keyPairApi.describeKeyPairsInRegion(region, group).size(), 1);\n            assertEquals(securityGroupApi.describeSecurityGroupsInRegion(region, group).size(), 1);\n         }\n         cleanupExtendedStuffInRegion(region, securityGroupApi, keyPairApi, group);\n      }\n   }\n   \n   @Override\n   protected void doCompareSizes() throws Exception {\n      Hardware defaultSize = view.getComputeService().templateBuilder().build().getHardware();\n\n      Hardware smallest = view.getComputeService().templateBuilder().smallest().build().getHardware();\n      Hardware fastest = view.getComputeService().templateBuilder().fastest().build().getHardware();\n      Hardware biggest = view.getComputeService().templateBuilder().biggest().build().getHardware();\n\n      assertEquals(defaultSize, smallest);\n\n      assert getCores(smallest) <= getCores(fastest) : String.format(\"%s ! <= %s\", smallest, fastest);\n      // m4.10xlarge is slower but has more cores than c4.8xlarge\n      // assert getCores(biggest) <= getCores(fastest) : String.format(\"%s ! <= %s\", biggest, fastest);\n      // assert getCores(fastest) >= getCores(biggest) : String.format(\"%s ! >= %s\", fastest, biggest);\n\n      assert biggest.getRam() >= fastest.getRam() : String.format(\"%s ! >= %s\", biggest, fastest);\n      assert biggest.getRam() >= smallest.getRam() : String.format(\"%s ! >= %s\", biggest, smallest);\n\n      assert getCores(fastest) >= getCores(smallest) : String.format(\"%s ! >= %s\", fastest, smallest);\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/AWSEC2TemplateBuilderLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.compute;\n\nimport static org.jclouds.compute.domain.OsFamily.AMZN_LINUX;\nimport static org.jclouds.compute.util.ComputeServiceUtils.getCores;\nimport static org.jclouds.http.internal.TrackingJavaUrlHttpCommandExecutorService.getInvokerOfRequestAtIndex;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.util.List;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport org.jclouds.aws.domain.Region;\nimport org.jclouds.aws.ec2.AWSEC2Api;\nimport org.jclouds.aws.ec2.AWSEC2ProviderMetadata;\nimport org.jclouds.aws.ec2.reference.AWSEC2Constants;\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.compute.EC2TemplateBuilderLiveTest;\nimport org.jclouds.ec2.compute.predicates.EC2ImagePredicates;\nimport org.jclouds.ec2.domain.InstanceType;\nimport org.jclouds.ec2.domain.RootDeviceType;\nimport org.jclouds.ec2.features.AvailabilityZoneAndRegionApi;\nimport org.jclouds.ec2.options.DescribeAvailabilityZonesOptions;\nimport org.jclouds.ec2.options.DescribeRegionsOptions;\nimport org.jclouds.ec2.reference.EC2Constants;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.internal.TrackingJavaUrlHttpCommandExecutorService;\nimport org.jclouds.location.reference.LocationConstants;\nimport org.jclouds.logging.log4j.config.Log4JLoggingModule;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Lists;\nimport com.google.common.reflect.Invokable;\nimport com.google.inject.Module;\n\n@Test(groups = \"live\", testName = \"AWSEC2TemplateBuilderLiveTest\")\npublic class AWSEC2TemplateBuilderLiveTest extends EC2TemplateBuilderLiveTest {\n\n   public AWSEC2TemplateBuilderLiveTest() {\n      provider = \"aws-ec2\";\n   }\n\n   @Override public ProviderMetadata createProviderMetadata() {\n      return new AWSEC2ProviderMetadata();\n   }\n\n   @Test\n   public void testTemplateBuilderM1MEDIUMWithNegativeLookaroundDoesntMatchTestImages() {\n\n      Template template = view.getComputeService().templateBuilder().hardwareId(InstanceType.M1_MEDIUM)\n      // need to select versions with double-digits so that lexicographic\n      // doesn't end up prefering 9.x vs 11.x\n            .osVersionMatches(\"1[012].[10][04]\")\n            // negative lookahead for daily and testing, but ensure match\n            // ubuntu-images\n            // http://www.regular-expressions.info/lookaround.html\n            .imageDescriptionMatches(\"^(?!.*(daily|testing)).*ubuntu-images.*$\").osFamily(OsFamily.UBUNTU).build();\n\n      assert template.getImage().getProviderId().startsWith(\"ami-\") : template;\n      assert template.getImage().getDescription().indexOf(\"test\") == -1 : template;\n      assert template.getImage().getDescription().indexOf(\"daily\") == -1 : template;\n      assertEquals(template.getImage().getVersion(), \"20100224\");\n      assertEquals(template.getImage().getOperatingSystem().getVersion(), \"10.04\");\n      assertEquals(template.getImage().getOperatingSystem().is64Bit(), false);\n      assertEquals(template.getImage().getOperatingSystem().getFamily(), OsFamily.UBUNTU);\n      assertEquals(template.getImage().getUserMetadata().get(\"rootDeviceType\"), \"instance-store\");\n      assertEquals(template.getLocation().getId(), \"us-east-1\");\n      assertEquals(getCores(template.getHardware()), 1.0d);\n      assertEquals(template.getHardware().getId(), InstanceType.M1_MEDIUM);\n      assertEquals(template.getImage().getOperatingSystem().getArch(), \"paravirtual\");\n   }\n\n   @Test\n   public void testUbuntuInstanceStoreGoesM3MediumNegativeLookaroundDoesntMatchTestImages() {\n\n      Template template = view.getComputeService().templateBuilder()\n            .imageMatches(EC2ImagePredicates.rootDeviceType(RootDeviceType.INSTANCE_STORE))\n            // need to select versions with double-digits so that lexicographic\n            // doesn't end up prefering 9.x vs 11.x\n            .osVersionMatches(\"1[012].[10][04]\")\n            // negative lookahead for daily and testing, but ensure match\n            // ubuntu-images\n            // http://www.regular-expressions.info/lookaround.html\n            .imageDescriptionMatches(\"^(?!.*(daily|testing)).*ubuntu-images.*$\").osFamily(OsFamily.UBUNTU).build();\n\n      assert template.getImage().getProviderId().startsWith(\"ami-\") : template;\n      assert template.getImage().getDescription().indexOf(\"test\") == -1 : template;\n      assert template.getImage().getDescription().indexOf(\"daily\") == -1 : template;\n      assertEquals(template.getImage().getOperatingSystem().getVersion(), \"10.04\");\n      assertEquals(template.getImage().getOperatingSystem().is64Bit(), false);\n      assertEquals(template.getImage().getOperatingSystem().getFamily(), OsFamily.UBUNTU);\n      assertEquals(template.getImage().getUserMetadata().get(\"rootDeviceType\"), \"instance-store\");\n      assertEquals(template.getLocation().getId(), \"us-east-1\");\n      assertEquals(getCores(template.getHardware()), 1.0d);\n      assertEquals(template.getHardware().getId(), InstanceType.M3_MEDIUM);  // smallest non-deprecated supporting PV\n      assertEquals(template.getImage().getOperatingSystem().getArch(), \"paravirtual\");\n   }\n\n   @Test\n   public void testTemplateBuilderCanUseImageIdAndHardwareIdAndAZ() {\n\n      Template template = view.getComputeService().templateBuilder().imageId(\"us-east-1/ami-ccb35ea5\")\n            .hardwareId(InstanceType.M2_2XLARGE).locationId(\"us-east-1b\").build();\n\n      assert template.getImage().getProviderId().startsWith(\"ami-\") : template;\n      assertEquals(template.getImage().getOperatingSystem().getVersion(), \"5.4\");\n      assertEquals(template.getImage().getOperatingSystem().is64Bit(), true);\n      assertEquals(template.getImage().getOperatingSystem().getFamily(), OsFamily.CENTOS);\n      assertEquals(template.getImage().getVersion(), \"4.4.10\");\n      assertEquals(template.getImage().getUserMetadata().get(\"rootDeviceType\"), \"instance-store\");\n      assertEquals(template.getLocation().getId(), \"us-east-1b\");\n      assertEquals(template.getImage().getLocation().getId(), \"us-east-1\");\n      assertEquals(getCores(template.getHardware()), 4.0d);\n      assertEquals(template.getHardware().getId(), InstanceType.M2_2XLARGE);\n      assertEquals(template.getImage().getOperatingSystem().getArch(), \"paravirtual\");\n   }\n\n   @Test\n   public void testDefaultTemplateBuilder() throws IOException {\n      Template defaultTemplate = view.getComputeService().templateBuilder().build();\n      assert defaultTemplate.getImage().getProviderId().startsWith(\"ami-\") : defaultTemplate;\n      assertTrue(defaultTemplate.getImage().getOperatingSystem().getVersion().contains(\"201\"),\n              \"Default template version should include '201' but is \"\n                      + defaultTemplate.getImage().getOperatingSystem().getVersion());\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true);\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), AMZN_LINUX);\n      assertEquals(defaultTemplate.getImage().getUserMetadata().get(\"rootDeviceType\"), \"ebs\");\n      assertEquals(defaultTemplate.getLocation().getId(), \"us-east-1\");\n      assertEquals(getCores(defaultTemplate.getHardware()), 1.0d);\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().getArch(), \"hvm\");\n   }\n\n   @Test\n   public void testAmazonLinuxInstanceStore() throws IOException {\n\n      Template defaultTemplate = view.getComputeService().templateBuilder().osFamily(AMZN_LINUX)\n            .imageMatches(EC2ImagePredicates.rootDeviceType(RootDeviceType.INSTANCE_STORE)).build();\n      assert defaultTemplate.getImage().getProviderId().startsWith(\"ami-\") : defaultTemplate;\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true);\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), AMZN_LINUX);\n      assertEquals(defaultTemplate.getImage().getUserMetadata().get(\"rootDeviceType\"), \"instance-store\");\n      assertEquals(defaultTemplate.getLocation().getId(), \"us-east-1\");\n      assertEquals(getCores(defaultTemplate.getHardware()), 1.0d);\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().getArch(), \"paravirtual\");\n   }\n\n   @Test\n   public void testFastestTemplateBuilder() throws IOException {\n      Template fastestTemplate = view.getComputeService().templateBuilder().fastest().osFamily(AMZN_LINUX).build();\n      assert fastestTemplate.getImage().getProviderId().startsWith(\"ami-\") : fastestTemplate;\n      assertEquals(fastestTemplate.getHardware().getProviderId(), InstanceType.C4_8XLARGE);\n      assertEquals(fastestTemplate.getImage().getOperatingSystem().is64Bit(), true);\n      assertEquals(fastestTemplate.getImage().getOperatingSystem().getFamily(), AMZN_LINUX);\n      assertEquals(fastestTemplate.getImage().getUserMetadata().get(\"rootDeviceType\"), \"ebs\");\n      assertEquals(fastestTemplate.getLocation().getId(), \"us-east-1\");\n      assertEquals(getCores(fastestTemplate.getHardware()), 36.0d);\n      assertEquals(fastestTemplate.getImage().getOperatingSystem().getArch(), \"hvm\");\n   }\n\n   @Test\n   public void testTemplateBuilderMicro() throws IOException {\n\n      Template microTemplate = view.getComputeService().templateBuilder().hardwareId(InstanceType.T1_MICRO)\n            .osFamily(OsFamily.UBUNTU).osVersionMatches(\"10.10\").os64Bit(true).build();\n\n      assert microTemplate.getImage().getProviderId().startsWith(\"ami-\") : microTemplate;\n      assertEquals(microTemplate.getImage().getOperatingSystem().getVersion(), \"10.10\");\n      assertEquals(microTemplate.getImage().getOperatingSystem().is64Bit(), true);\n      assertEquals(microTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.UBUNTU);\n      assertEquals(microTemplate.getImage().getUserMetadata().get(\"rootDeviceType\"), \"ebs\");\n      assertEquals(microTemplate.getLocation().getId(), \"us-east-1\");\n      assertEquals(getCores(microTemplate.getHardware()), 1.0d);\n      assertEquals(microTemplate.getImage().getOperatingSystem().getArch(), \"paravirtual\");\n   }\n\n   @Test\n   public void testTemplateBuilderWithNoOwnersParsesImageOnDemand() throws IOException {\n      ComputeServiceContext context = null;\n      try {\n         Properties overrides = setupProperties();\n         // set owners to nothing\n         overrides.setProperty(AWSEC2Constants.PROPERTY_EC2_AMI_QUERY, \"\");\n         overrides.setProperty(AWSEC2Constants.PROPERTY_EC2_CC_AMI_QUERY, \"\");\n\n         context = createView(overrides, setupModules());\n\n         assertEquals(context.getComputeService().listImages().size(), 0);\n\n         Template template = context.getComputeService().templateBuilder().imageId(\"us-east-1/ami-ccb35ea5\").build();\n         assert template.getImage().getProviderId().startsWith(\"ami-\") : template;\n         assertEquals(template.getImage().getOperatingSystem().getVersion(), \"5.4\");\n         assertEquals(template.getImage().getOperatingSystem().is64Bit(), true);\n         assertEquals(template.getImage().getOperatingSystem().getFamily(), OsFamily.CENTOS);\n         assertEquals(template.getImage().getVersion(), \"4.4.10\");\n         assertEquals(template.getImage().getUserMetadata().get(\"rootDeviceType\"), \"instance-store\");\n         assertEquals(template.getLocation().getId(), \"us-east-1\");\n         assertEquals(getCores(template.getHardware()), 1.0d);\n         assertEquals(template.getHardware().getId(), \"m3.medium\"); // smallest non-deprecated supporting PV\n\n         // ensure we cache the new image for next time\n         assertEquals(context.getComputeService().listImages().size(), 1);\n\n      } finally {\n         if (context != null)\n            context.close();\n      }\n   }\n\n   @Test\n   public void testTemplateBuilderWithNoOwnersParsesImageOnDemandDeprecated() throws IOException {\n      ComputeServiceContext context = null;\n      try {\n         Properties overrides = setupProperties();\n         // set owners to nothing\n         overrides.setProperty(EC2Constants.PROPERTY_EC2_AMI_OWNERS, \"\");\n         overrides.setProperty(AWSEC2Constants.PROPERTY_EC2_CC_AMI_QUERY, \"\");\n\n         context = createView(overrides, setupModules());\n\n         assertEquals(context.getComputeService().listImages().size(), 0);\n\n         Template template = context.getComputeService().templateBuilder().imageId(\"us-east-1/ami-ccb35ea5\").build();\n         assert template.getImage().getProviderId().startsWith(\"ami-\") : template;\n         assertEquals(template.getImage().getOperatingSystem().getVersion(), \"5.4\");\n         assertEquals(template.getImage().getOperatingSystem().is64Bit(), true);\n         assertEquals(template.getImage().getOperatingSystem().getFamily(), OsFamily.CENTOS);\n         assertEquals(template.getImage().getVersion(), \"4.4.10\");\n         assertEquals(template.getImage().getUserMetadata().get(\"rootDeviceType\"), \"instance-store\");\n         assertEquals(template.getLocation().getId(), \"us-east-1\");\n         assertEquals(getCores(template.getHardware()), 1.0d);\n         assertEquals(template.getHardware().getId(), \"m3.medium\");  // smallest non-deprecated supporting PV\n\n         // ensure we cache the new image for next time\n         assertEquals(context.getComputeService().listImages().size(), 1);\n\n      } finally {\n         if (context != null)\n            context.close();\n      }\n   }\n\n   @Test\n   public void testTemplateBuilderWithLessRegions() throws IOException, SecurityException, NoSuchMethodException {\n      ComputeServiceContext context = null;\n      try {\n         Properties overrides = setupProperties();\n         // set regions to only 1\n         overrides.setProperty(LocationConstants.PROPERTY_REGIONS, Region.EU_WEST_1);\n         overrides.setProperty(AWSEC2Constants.PROPERTY_EC2_CC_REGIONS, \"\");\n         overrides.setProperty(AWSEC2Constants.PROPERTY_EC2_AMI_QUERY, \"\");\n         overrides.setProperty(AWSEC2Constants.PROPERTY_EC2_CC_AMI_QUERY, \"\");\n\n         final List<HttpCommand> commandsInvoked = Lists.newArrayList();\n         \n         context = createView(\n               overrides,\n               ImmutableSet.<Module> of(new Log4JLoggingModule(),\n                     TrackingJavaUrlHttpCommandExecutorService.newTrackingModule(commandsInvoked)));\n\n         assert context.getComputeService().listAssignableLocations().size() < this.view.getComputeService()\n               .listAssignableLocations().size();\n\n         assertOnlyOneRegionQueriedForAvailabilityZone(commandsInvoked);\n\n         assert context.getComputeService().listImages().size() < this.view.getComputeService().listImages().size();\n\n         Template template = context.getComputeService().templateBuilder().imageId(\"eu-west-1/ami-a33b06d7\").build();\n         assert template.getImage().getProviderId().startsWith(\"ami-\") : template;\n         assertEquals(template.getImage().getOperatingSystem().is64Bit(), true);\n         assertEquals(template.getImage().getOperatingSystem().getFamily(), AMZN_LINUX);\n         assertEquals(template.getImage().getVersion(), \"2011.09.2\");\n         assertEquals(template.getImage().getUserMetadata().get(\"rootDeviceType\"), \"instance-store\");\n         assertEquals(template.getLocation().getId(), \"eu-west-1\");\n         assertEquals(getCores(template.getHardware()), 1.0d);\n         assertEquals(template.getHardware().getId(), \"m3.medium\");  // smallest non-deprecated supporting PV\n\n      } finally {\n         if (context != null)\n            context.close();\n      }\n   }\n\n   private static void assertOnlyOneRegionQueriedForAvailabilityZone(List<HttpCommand> commandsInvoked)\n         throws NoSuchMethodException {\n      assert commandsInvoked.size() == 2 : commandsInvoked;\n      assertInvokedCommand(getInvokerOfRequestAtIndex(commandsInvoked, 0), Invokable.from(\n            AvailabilityZoneAndRegionApi.class.getMethod(\"describeRegions\", DescribeRegionsOptions[].class)));\n      assertInvokedCommand(getInvokerOfRequestAtIndex(commandsInvoked, 1), Invokable.from(\n            AvailabilityZoneAndRegionApi.class.getMethod(\"describeAvailabilityZonesInRegion\", String.class,\n                  DescribeAvailabilityZonesOptions[].class)));\n   }\n\n   @Test\n   public void testTemplateBuilderCanUseImageIdFromNonDefaultOwner() {\n      // This is the id of a public image, not owned by one of the four default\n      // owners\n      String imageId = \"us-east-1/ami-44d02f2d\";\n      Template defaultTemplate = view.getComputeService().templateBuilder().imageId(imageId)\n            .imageMatches(EC2ImagePredicates.rootDeviceType(RootDeviceType.INSTANCE_STORE)).build();\n      assert defaultTemplate.getImage().getProviderId().startsWith(\"ami-\") : defaultTemplate;\n      assertEquals(defaultTemplate.getImage().getId(), imageId);\n   }\n   \n   @Override\n   public void testCompareSizes() throws Exception {\n      Hardware defaultSize = view.getComputeService().templateBuilder().build().getHardware();\n\n      Hardware smallest = view.getComputeService().templateBuilder().smallest().build().getHardware();\n      Hardware fastest = view.getComputeService().templateBuilder().fastest().build().getHardware();\n      Hardware biggest = view.getComputeService().templateBuilder().biggest().build().getHardware();\n\n      assertEquals(defaultSize, smallest);\n\n      assert getCores(smallest) <= getCores(fastest) : String.format(\"%s ! <= %s\", smallest, fastest);\n      // m4.10xlarge is slower but has more cores than c4.8xlarge\n      // assert getCores(biggest) <= getCores(fastest) : String.format(\"%s ! <= %s\", biggest, fastest);\n      // assert getCores(fastest) >= getCores(biggest) : String.format(\"%s ! >= %s\", fastest, biggest);\n\n      assert biggest.getRam() >= fastest.getRam() : String.format(\"%s ! >= %s\", biggest, fastest);\n      assert biggest.getRam() >= smallest.getRam() : String.format(\"%s ! >= %s\", biggest, smallest);\n\n      assert getCores(fastest) >= getCores(smallest) : String.format(\"%s ! >= %s\", fastest, smallest);\n   }\n   \n   @Test\n   public void testAssignability() {\n      view.unwrapApi(EC2Api.class);\n      view.unwrapApi(AWSEC2Api.class);\n   }\n\n   @Override\n   protected Set<String> getIso3166Codes() {\n      return ImmutableSet.of(\"US-VA\", \"US-OH\", \"US-CA\", \"US-OR\", \"CA\", \"BR-SP\",\n            \"IE\", \"GB-LND\", \"FR-IDF\", \"IT-MI\", \"ES\", \"DE-HE\", \"CH-ZH\", \"SE-AB\",\n            \"SG\", \"AU-NSW\", \"IN-MH\", \"JP-13\", \"KR-11\",\n            \"CN-BJ\", \"CN-NX\", \"BH\");\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/config/AWSEC2ComputeServiceContextModuleTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.compute.config;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.testng.Assert.fail;\n\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.compute.loaders.RegionAndIdToImage;\nimport org.jclouds.rest.AuthorizationException;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.CacheLoader;\n\n@Test(groups = \"unit\")\npublic class AWSEC2ComputeServiceContextModuleTest {\n   \n   @Test\n   public void testCacheLoaderDoesNotReloadAfterAuthorizationException() throws Exception {\n      AWSEC2ComputeServiceContextModule module = new AWSEC2ComputeServiceContextModule() {\n         public Supplier<CacheLoader<RegionAndName, Image>> provideRegionAndNameToImageSupplierCacheLoader(RegionAndIdToImage delegate) {\n            return super.provideRegionAndNameToImageSupplierCacheLoader(delegate);\n         }\n      };\n      \n      RegionAndName regionAndName = new RegionAndName(\"myregion\", \"myname\");\n      AuthorizationException authException = new AuthorizationException();\n      \n      RegionAndIdToImage mockRegionAndIdToImage = createMock(RegionAndIdToImage.class);\n      expect(mockRegionAndIdToImage.load(regionAndName)).andThrow(authException).once();\n      replay(mockRegionAndIdToImage);\n      \n      CacheLoader<RegionAndName, Image> cacheLoader = module.provideRegionAndNameToImageSupplierCacheLoader(mockRegionAndIdToImage).get();\n\n      for (int i = 0; i < 2; i++) {\n         try {\n            Image image = cacheLoader.load(regionAndName);\n            fail(\"Expected Authorization exception, but got \" + image);\n         } catch (AuthorizationException e) {\n            // success\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/extensions/AWSEC2ImageExtensionLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.compute.extensions;\n\nimport static com.google.common.collect.Iterables.transform;\n\nimport org.jclouds.aws.ec2.AWSEC2Api;\nimport org.jclouds.aws.util.AWSUtils;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.extensions.ImageExtension;\nimport org.jclouds.ec2.compute.extensions.EC2ImageExtensionLiveTest;\nimport org.jclouds.ec2.compute.functions.EC2ImageParser;\nimport org.jclouds.ec2.options.DescribeImagesOptions;\nimport org.jclouds.sshj.config.SshjSshClientModule;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Module;\n\n/**\n * Live test for aws-ec2 {@link ImageExtension} implementation\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"AWSEC2ImageExtensionLiveTest\")\npublic class AWSEC2ImageExtensionLiveTest extends EC2ImageExtensionLiveTest {\n\n   public AWSEC2ImageExtensionLiveTest() {\n      provider = \"aws-ec2\";\n   }\n\n   @Override\n   protected Iterable<? extends Image> listImages() {\n      AWSEC2Api client = view.unwrapApi(AWSEC2Api.class);\n      String[] parts = AWSUtils.parseHandle(imageId);\n      String region = parts[0];\n      String imageId = parts[1];\n      EC2ImageParser parser = view.utils().injector().getInstance(EC2ImageParser.class);\n      return transform(\n                       client.getAMIApi().get().describeImagesInRegion(region, new DescribeImagesOptions().imageIds(imageId)),\n            parser);\n   }\n\n   @Override\n   protected Module getSshModule() {\n      return new SshjSshClientModule();\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/extensions/AWSEC2SecurityGroupExtensionApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.compute.extensions;\n\nimport static org.jclouds.domain.LocationScope.REGION;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.aws.ec2.internal.BaseAWSEC2ApiMockTest;\nimport org.jclouds.compute.domain.SecurityGroup;\nimport org.jclouds.compute.domain.SecurityGroupBuilder;\nimport org.jclouds.compute.extensions.SecurityGroupExtension;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.net.domain.IpPermission;\nimport org.jclouds.net.domain.IpProtocol;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Iterables;\n\n@Test(groups = \"unit\", testName = \"AWSEC2SecurityGroupExtensionMockTest\", singleThreaded = true)\npublic class AWSEC2SecurityGroupExtensionApiMockTest extends BaseAWSEC2ApiMockTest {\n\n   SecurityGroup group = new SecurityGroupBuilder() //\n         .id(DEFAULT_REGION + \"/sg-3c6ef654\") //\n         .providerId(\"sg-3c6ef654\") //\n         .name(\"jclouds#some-group\") //\n         .ownerId(\"993194456877\")\n         .location(new LocationBuilder().scope(REGION).id(DEFAULT_REGION).description(\"\").build()).build();\n\n   IpPermission permByCidrBlock = IpPermission.builder() //\n         .ipProtocol(IpProtocol.TCP) //\n         .fromPort(22) //\n         .toPort(40) //\n         .cidrBlock(\"0.0.0.0/0\").build();\n\n   public void addIpPermissionCidrFromIpPermission() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(DEFAULT_REGION, \"/authorize_securitygroup_ingress_response.xml\");\n      enqueueXml(DEFAULT_REGION, \"/describe_securitygroups_extension_cidr.xml\");\n      enqueueXml(DEFAULT_REGION, \"/availabilityZones.xml\");\n\n      SecurityGroup newGroup = extension().addIpPermission(permByCidrBlock, group);\n\n      assertEquals(1, newGroup.getIpPermissions().size());\n\n      IpPermission newPerm = Iterables.getOnlyElement(newGroup.getIpPermissions());\n      assertEquals(newPerm, permByCidrBlock);\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION,\n            \"Action=AuthorizeSecurityGroupIngress&GroupId=sg-3c6ef654&IpPermissions.0.IpProtocol=tcp&IpPermissions.0.FromPort=22&IpPermissions.0.ToPort=40&IpPermissions.0.IpRanges.0.CidrIp=0.0.0.0/0\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeSecurityGroups&GroupId.1=sg-3c6ef654\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeAvailabilityZones\");\n   }\n\n   public void addIpPermissionCidrFromParams() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(DEFAULT_REGION, \"/authorize_securitygroup_ingress_response.xml\");\n      enqueueXml(DEFAULT_REGION, \"/describe_securitygroups_extension_cidr.xml\");\n      enqueueXml(DEFAULT_REGION, \"/availabilityZones.xml\");\n\n      SecurityGroup newGroup = extension()\n            .addIpPermission(permByCidrBlock.getIpProtocol(), permByCidrBlock.getFromPort(),\n                  permByCidrBlock.getToPort(), permByCidrBlock.getTenantIdGroupNamePairs(),\n                  permByCidrBlock.getCidrBlocks(), permByCidrBlock.getGroupIds(), group);\n\n      IpPermission newPerm = Iterables.getOnlyElement(newGroup.getIpPermissions());\n      assertEquals(newPerm, permByCidrBlock);\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION,\n            \"Action=AuthorizeSecurityGroupIngress&GroupId=sg-3c6ef654&IpPermissions.0.IpProtocol=tcp&IpPermissions.0.FromPort=22&IpPermissions.0.ToPort=40&IpPermissions.0.IpRanges.0.CidrIp=0.0.0.0/0\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeSecurityGroups&GroupId.1=sg-3c6ef654\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeAvailabilityZones\");\n   }\n\n   IpPermission permByGroup = IpPermission.builder() //\n         .ipProtocol(IpProtocol.TCP) //\n         .fromPort(22) //\n         .toPort(40) //\n         .tenantIdGroupNamePair(group.getOwnerId(), group.getProviderId()).build();\n\n   public void addIpPermissionGroupFromIpPermission() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(DEFAULT_REGION, \"/authorize_securitygroup_ingress_response.xml\");\n      enqueueXml(DEFAULT_REGION, \"/describe_securitygroups_extension_group.xml\");\n      enqueueXml(DEFAULT_REGION, \"/availabilityZones.xml\");\n\n      SecurityGroup newGroup = extension().addIpPermission(permByGroup, group);\n\n      assertEquals(1, newGroup.getIpPermissions().size());\n\n      IpPermission newPerm = Iterables.getOnlyElement(newGroup.getIpPermissions());\n      assertEquals(newPerm, permByGroup);\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION,\n            \"Action=AuthorizeSecurityGroupIngress&GroupId=sg-3c6ef654&IpPermissions.0.IpProtocol=tcp&IpPermissions.0.FromPort=22&IpPermissions.0.ToPort=40&IpPermissions.0.Groups.0.UserId=993194456877&IpPermissions.0.Groups.0.GroupId=sg-3c6ef654\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeSecurityGroups&GroupId.1=sg-3c6ef654\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeAvailabilityZones\");\n   }\n\n   public void addIpPermissionGroupFromParams() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(DEFAULT_REGION, \"/authorize_securitygroup_ingress_response.xml\");\n      enqueueXml(DEFAULT_REGION, \"/describe_securitygroups_extension_group.xml\");\n      enqueueXml(DEFAULT_REGION, \"/availabilityZones.xml\");\n\n      SecurityGroup newGroup = extension()\n            .addIpPermission(permByGroup.getIpProtocol(), permByGroup.getFromPort(), permByGroup.getToPort(),\n                  permByGroup.getTenantIdGroupNamePairs(), permByGroup.getCidrBlocks(), permByGroup.getGroupIds(),\n                  group);\n\n      IpPermission newPerm = Iterables.getOnlyElement(newGroup.getIpPermissions());\n      assertEquals(newPerm, permByGroup);\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION,\n            \"Action=AuthorizeSecurityGroupIngress&GroupId=sg-3c6ef654&IpPermissions.0.IpProtocol=tcp&IpPermissions.0.FromPort=22&IpPermissions.0.ToPort=40&IpPermissions.0.Groups.0.UserId=993194456877&IpPermissions.0.Groups.0.GroupId=sg-3c6ef654\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeSecurityGroups&GroupId.1=sg-3c6ef654\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeAvailabilityZones\");\n   }\n\n   public void createSecurityGroup() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(DEFAULT_REGION, \"/created_securitygroup.xml\");\n      // TODO: ridiculously chatty\n      enqueueXml(DEFAULT_REGION, \"/describe_securitygroups_extension_single.xml\");\n      enqueueXml(DEFAULT_REGION, \"/describe_securitygroups_extension_single.xml\");\n      enqueueXml(DEFAULT_REGION, \"/describe_securitygroups_extension_single.xml\");\n      enqueueXml(DEFAULT_REGION, \"/availabilityZones.xml\");\n\n      SecurityGroup newGroup = extension()\n            .createSecurityGroup(group.getName().replace(\"jclouds#\", \"\"), group.getLocation());\n      assertEquals(newGroup.getId(), group.getId());\n      assertEquals(newGroup.getProviderId(), group.getProviderId());\n      assertEquals(newGroup.getName(), group.getName());\n      assertEquals(newGroup.getLocation().getId(), group.getLocation().getId()); // One from response has a parent\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION,\n            \"Action=CreateSecurityGroup&GroupName=jclouds%23some-group&GroupDescription=jclouds%23some-group\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeSecurityGroups&Filter.1.Name=group-name&Filter.1.Value.1=jclouds%23some-group\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeSecurityGroups&Filter.1.Name=group-name&Filter.1.Value.1=jclouds%23some-group\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeSecurityGroups&GroupId.1=sg-3c6ef654\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeAvailabilityZones\");\n   }\n\n   private SecurityGroupExtension extension() {\n      return computeService().getSecurityGroupExtension().get();\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/extensions/AWSEC2SecurityGroupExtensionLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.compute.extensions;\n\n\nimport org.jclouds.compute.extensions.internal.BaseSecurityGroupExtensionLiveTest;\nimport org.testng.annotations.Test;\n\n\n/**\n * Live test for aws-ec2 {@link SecurityGroupExtension} implementation\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"AWSEC2SecurityGroupExtensionLiveTest\")\npublic class AWSEC2SecurityGroupExtensionLiveTest extends BaseSecurityGroupExtensionLiveTest {\n\n   public AWSEC2SecurityGroupExtensionLiveTest() {\n      provider = \"aws-ec2\";\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/functions/AWSEC2SecurityGroupToSecurityGroupTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.compute.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.SecurityGroup;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.ec2.util.IpPermissions;\nimport org.jclouds.net.domain.IpPermission;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\", testName = \"AWSEC2SecurityGroupToSecurityGroupTest\")\npublic class AWSEC2SecurityGroupToSecurityGroupTest {\n\n   static Location provider = new LocationBuilder().scope(LocationScope.REGION).id(\"us-east-1\")\n         .description(\"us-east-1\").build();\n\n   @Test\n   public void testApply() {\n      IpPermissions authorization = IpPermissions.permitAnyProtocol();\n\n      org.jclouds.ec2.domain.SecurityGroup origGroup = org.jclouds.ec2.domain.SecurityGroup.builder()\n         .region(\"us-east-1\")\n         .id(\"some-id\")\n         .name(\"some-group\")\n         .ownerId(\"some-owner\")\n         .description(\"some-description\")\n         .ipPermission(authorization)\n         .build();\n\n      AWSEC2SecurityGroupToSecurityGroup parser = createGroupParser(ImmutableSet.of(provider));\n\n      SecurityGroup group = parser.apply(origGroup);\n      \n      assertEquals(group.getLocation(), provider);\n      assertEquals(group.getId(), provider.getId() + \"/\" + origGroup.getId());\n      assertEquals(group.getProviderId(), origGroup.getId());\n      assertEquals(group.getName(), origGroup.getName());\n      assertEquals(group.getIpPermissions(), (Set<IpPermission>)origGroup);\n      assertEquals(group.getOwnerId(), origGroup.getOwnerId());\n   }\n\n   private AWSEC2SecurityGroupToSecurityGroup createGroupParser(final ImmutableSet<Location> locations) {\n      Supplier<Set<? extends Location>> locationSupplier = new Supplier<Set<? extends Location>>() {\n\n         @Override\n         public Set<? extends Location> get() {\n            return locations;\n         }\n\n      };\n\n      AWSEC2SecurityGroupToSecurityGroup parser = new AWSEC2SecurityGroupToSecurityGroup(locationSupplier);\n\n      return parser;\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/functions/AWSRunningInstanceToNodeMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.compute.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.aws.ec2.AWSEC2ApiMetadata;\nimport org.jclouds.aws.ec2.domain.AWSRunningInstance;\nimport org.jclouds.aws.ec2.domain.MonitoringState;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.NodeMetadataBuilder;\nimport org.jclouds.compute.domain.NodeMetadata.Status;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.date.DateService;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.ec2.compute.config.EC2ComputeServiceDependenciesModule;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.compute.functions.ImagesToRegionAndIdMap;\nimport org.jclouds.ec2.domain.Attachment;\nimport org.jclouds.ec2.domain.BlockDevice;\nimport org.jclouds.ec2.domain.Hypervisor;\nimport org.jclouds.ec2.domain.InstanceState;\nimport org.jclouds.ec2.domain.RootDeviceType;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.name.Names;\n\n@Test(groups = \"unit\")\npublic class AWSRunningInstanceToNodeMetadataTest {\n\n   private static final String defaultRegion = \"us-east-1\";\n   static Location provider = new LocationBuilder().scope(LocationScope.REGION).id(defaultRegion).description(\n            defaultRegion).build();\n\n   private DateService dateService;\n\n   @BeforeTest\n   protected void setUpInjector() {\n      dateService = Guice.createInjector().getInstance(DateService.class);\n      assert dateService != null;\n   }\n\n   @Test\n   public void test2Nodes() {\n\n      AWSRunningInstanceToNodeMetadata parser = createNodeParser(ImmutableSet.<Hardware> of(), ImmutableSet\n               .<Location> of(), ImmutableSet.<Image> of(), ImmutableMap.<String, Credentials> of());\n\n      ImmutableSet<AWSRunningInstance> contents = ImmutableSet.of(new AWSRunningInstance.Builder()\n               .region(defaultRegion)\n               .instanceId(\"i-911444f0\")\n               .imageId(\"ami-63be790a\")\n               .instanceState(InstanceState.RUNNING)\n               .rawState(\"running\")\n               .privateDnsName(\"ip-10-212-81-7.ec2.internal\")\n               .dnsName(\"ec2-174-129-173-155.compute-1.amazonaws.com\")\n               .keyName(\"jclouds#zkclustertest#23\")\n               .amiLaunchIndex(\"0\")\n               .instanceType(\"t1.micro\")\n               .launchTime(dateService.iso8601DateParse(\"2011-08-16T13:40:50.000Z\"))\n               .availabilityZone(\"us-east-1c\")\n               .kernelId(\"aki-427d952b\")\n               .monitoringState(MonitoringState.DISABLED)\n               .privateIpAddress(\"10.212.81.7\")\n               .ipAddress(\"174.129.173.155\")\n               .securityGroupIdToNames(ImmutableMap.<String, String> of(\"sg-ef052b86\", \"jclouds#zkclustertest\"))\n               .rootDeviceType(RootDeviceType.EBS)\n               .rootDeviceName(\"/dev/sda1\")\n               .device(\"/dev/sda1\", new BlockDevice(\"vol-5829fc32\", Attachment.Status.ATTACHED, dateService.iso8601DateParse(\"2011-08-16T13:41:19.000Z\"), true))\n               .virtualizationType(\"paravirtual\")\n               .tag(\"Name\", \"foo\")\n               .tag(\"Empty\", \"\")\n               .hypervisor(Hypervisor.XEN)\n               .build(),\n               new AWSRunningInstance.Builder()\n                        .region(defaultRegion)\n                        .instanceId(\"i-931444f2\")\n                        .imageId(\"ami-63be790a\")\n                        .instanceState(InstanceState.RUNNING)\n                        .rawState(\"running\")\n                        .privateDnsName(\"ip-10-212-185-8.ec2.internal\")\n                        .dnsName(\"ec2-50-19-207-248.compute-1.amazonaws.com\")\n                        .keyName(\"jclouds#zkclustertest#23\")\n                        .amiLaunchIndex(\"0\")\n                        .instanceType(\"t1.micro\")\n                        .launchTime(dateService.iso8601DateParse(\"2011-08-16T13:40:50.000Z\"))\n                        .availabilityZone(\"us-east-1c\")\n                        .kernelId(\"aki-427d952b\")\n                        .monitoringState(MonitoringState.DISABLED)\n                        .privateIpAddress(\"10.212.185.8\")\n                        .ipAddress(\"50.19.207.248\")\n                        .securityGroupIdToNames(ImmutableMap.<String, String>of(\"sg-ef052b86\", \"jclouds#zkclustertest\"))\n                        .rootDeviceType(RootDeviceType.EBS)\n                        .rootDeviceName(\"/dev/sda1\")\n                        .device(\"/dev/sda1\", new BlockDevice(\"vol-5029fc3a\", Attachment.Status.ATTACHED, dateService.iso8601DateParse(\"2011-08-16T13:41:19.000Z\"), true))\n                        .virtualizationType(\"paravirtual\")\n                        .hypervisor(Hypervisor.XEN)\n                        .build());\n\n      assertEquals(\n            parser.apply(Iterables.get(contents, 0)).toString(),\n            new NodeMetadataBuilder()\n                  .status(Status.RUNNING)\n                  .backendStatus(\"running\")\n                  .group(\"zkclustertest\")\n                  .name(\"foo\")\n                  .hostname(\"ip-10-212-81-7\")\n                  .privateAddresses(ImmutableSet.of(\"10.212.81.7\"))\n                  .publicAddresses(ImmutableSet.of(\"174.129.173.155\"))\n                  .imageId(\"us-east-1/ami-63be790a\")\n                  .id(\"us-east-1/i-911444f0\")\n                  .providerId(\"i-911444f0\")\n                  .tags(ImmutableSet.of(\"Empty\"))\n                  .userMetadata(ImmutableMap.of(\"Name\", \"foo\")).build().toString());\n      assertEquals(\n              parser.apply(Iterables.get(contents, 1)).toString(), \n              new NodeMetadataBuilder()\n                  .status(Status.RUNNING)\n                  .backendStatus(\"running\")\n                  .group(\"zkclustertest\")\n                  .hostname(\"ip-10-212-185-8\")\n                  .privateAddresses(ImmutableSet.of(\"10.212.185.8\"))\n                  .publicAddresses(ImmutableSet.of(\"50.19.207.248\"))\n                  .imageId(\"us-east-1/ami-63be790a\")\n                  .id(\"us-east-1/i-931444f2\")\n                  .providerId(\"i-931444f2\")\n                  .build().toString());\n   }\n\n   protected AWSRunningInstanceToNodeMetadata createNodeParser(final ImmutableSet<Hardware> hardware,\n            final ImmutableSet<Location> locations, Set<org.jclouds.compute.domain.Image> images,\n            Map<String, Credentials> credentialStore) {\n      Map<InstanceState, Status> instanceToNodeStatus = EC2ComputeServiceDependenciesModule.toPortableNodeStatus;\n\n      final Map<RegionAndName, ? extends Image> backing = ImagesToRegionAndIdMap.imagesToMap(images);\n\n      LoadingCache<RegionAndName, Image> instanceToImage = CacheBuilder.newBuilder().build(new CacheLoader<RegionAndName, Image>() {\n    \n         @Override\n         public Image load(RegionAndName key) throws Exception {\n            return backing.get(key);\n         }\n         \n      });\n            \n          \n      return createNodeParser(hardware, locations, credentialStore, instanceToNodeStatus, instanceToImage);\n   }\n\n   private AWSRunningInstanceToNodeMetadata createNodeParser(final ImmutableSet<Hardware> hardware,\n            final ImmutableSet<Location> locations, Map<String, Credentials> credentialStore,\n            Map<InstanceState, Status> instanceToNodeStatus, LoadingCache<RegionAndName, ? extends Image> instanceToImage) {\n      Supplier<Set<? extends Location>> locationSupplier = new Supplier<Set<? extends Location>>() {\n\n         @Override\n         public Set<? extends Location> get() {\n            return locations;\n         }\n\n      };\n      Supplier<Set<? extends Hardware>> hardwareSupplier = new Supplier<Set<? extends Hardware>>() {\n\n         @Override\n         public Set<? extends Hardware> get() {\n            return hardware;\n         }\n\n      };\n      \n      GroupNamingConvention.Factory namingConvention = Guice.createInjector(new AbstractModule() {\n\n         @Override\n         protected void configure() {\n            Names.bindProperties(binder(), new AWSEC2ApiMetadata().getDefaultProperties());\n         }\n\n      }).getInstance(GroupNamingConvention.Factory.class);\n\n      AWSRunningInstanceToNodeMetadata parser = new AWSRunningInstanceToNodeMetadata(instanceToNodeStatus,\n            credentialStore, Suppliers.<LoadingCache<RegionAndName, ? extends Image>> ofInstance(instanceToImage),\n            locationSupplier, hardwareSupplier, namingConvention);\n      return parser;\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/functions/PresentSpotRequestsAndInstancesTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.compute.functions;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Set;\n\nimport org.jclouds.aws.ec2.AWSEC2Api;\nimport org.jclouds.aws.ec2.domain.AWSRunningInstance;\nimport org.jclouds.aws.ec2.domain.SpotInstanceRequest;\nimport org.jclouds.aws.ec2.features.AWSInstanceApi;\nimport org.jclouds.aws.ec2.features.SpotInstanceApi;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.domain.Reservation;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Functions;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\")\npublic class PresentSpotRequestsAndInstancesTest {\n   AWSRunningInstance instance1 = createMock(AWSRunningInstance.class);\n   AWSRunningInstance instance2 = createMock(AWSRunningInstance.class);\n\n   @SuppressWarnings(\"unchecked\")\n   @Test\n   public void testWhenInstancesPresentSingleCall() {\n\n      AWSEC2Api client = createMock(AWSEC2Api.class);\n      AWSInstanceApi instanceApi = createMock(AWSInstanceApi.class);\n      Function<SpotInstanceRequest, AWSRunningInstance> converter = createMock(Function.class);\n\n      expect(client.getInstanceApi()).andReturn((Optional) Optional.of(instanceApi));\n      \n      // avoid imatcher fail.  if you change this, be sure to check multiple jres\n      expect(instanceApi.describeInstancesInRegion(\"us-east-1\", \"i-aaaa\", \"i-bbbb\")).andReturn(\n            Set.class.cast(ImmutableSet.of(Reservation.<AWSRunningInstance> builder().region(\"us-east-1\")\n                  .instances(ImmutableSet.of(instance1, instance2)).build())));\n\n      replay(client, instanceApi, converter);\n\n      PresentSpotRequestsAndInstances fn = new PresentSpotRequestsAndInstances(client, converter);\n\n      assertEquals(fn.apply(ImmutableSet.of(new RegionAndName(\"us-east-1\", \"i-aaaa\"), new RegionAndName(\"us-east-1\",\n            \"i-bbbb\"))), ImmutableSet.of(instance1, instance2));\n\n      verify(client, instanceApi, converter);\n   }\n\n   SpotInstanceRequest spot1 = createMock(SpotInstanceRequest.class);\n   SpotInstanceRequest spot2 = createMock(SpotInstanceRequest.class);\n\n   @Test\n   public void testWhenSpotsPresentSingleCall() {\n\n      Function<SpotInstanceRequest, AWSRunningInstance> converter = Functions.forMap(ImmutableMap.of(spot1, instance1,\n            spot2, instance2));\n\n      AWSEC2Api client = createMock(AWSEC2Api.class);\n      SpotInstanceApi spotApi = createMock(SpotInstanceApi.class);\n\n      expect(client.getSpotInstanceApi()).andReturn((Optional) Optional.of(spotApi));\n      expect(spotApi.describeSpotInstanceRequestsInRegion(\"us-east-1\", \"sir-aaaa\", \"sir-bbbb\")).andReturn(\n            ImmutableSet.of(spot1, spot2));\n\n      replay(client, spotApi);\n\n      PresentSpotRequestsAndInstances fn = new PresentSpotRequestsAndInstances(client, converter);\n\n      assertEquals(fn.apply(ImmutableSet.of(new RegionAndName(\"us-east-1\", \"sir-aaaa\"), new RegionAndName(\"us-east-1\",\n            \"sir-bbbb\"))), ImmutableSet.of(instance1, instance2));\n\n      verify(client, spotApi);\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/loaders/AWSEC2CreateSecurityGroupIfNeededTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.compute.loaders;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.createNiceMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Set;\nimport java.util.concurrent.ExecutionException;\n\nimport org.jclouds.aws.ec2.features.AWSSecurityGroupApi;\nimport org.jclouds.aws.ec2.options.CreateSecurityGroupOptions;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.compute.domain.RegionNameAndIngressRules;\nimport org.jclouds.ec2.compute.functions.EC2SecurityGroupIdFromName;\nimport org.jclouds.ec2.domain.SecurityGroup;\nimport org.jclouds.net.domain.IpPermission;\nimport org.jclouds.net.domain.IpProtocol;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Predicates;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\", singleThreaded = true, testName = \"AWSEC2CreateSecurityGroupIfNeeded\")\npublic class AWSEC2CreateSecurityGroupIfNeededTest {\n\n   @SuppressWarnings(\"unchecked\")\n   @Test\n   public void testWhenPort22AndToItselfAuthorizesIngressOnce() throws ExecutionException {\n\n      AWSSecurityGroupApi client = createMock(AWSSecurityGroupApi.class);\n      Predicate<RegionAndName> tester = Predicates.alwaysTrue();\n\n      SecurityGroup group = createNiceMock(SecurityGroup.class);\n      Set<SecurityGroup> groups = ImmutableSet.<SecurityGroup> of(group);\n\n      EC2SecurityGroupIdFromName groupIdFromName = createMock(EC2SecurityGroupIdFromName.class);\n\n      ImmutableSet.Builder<IpPermission> permissions = ImmutableSet.builder();\n\n      permissions.add(IpPermission.builder()\n                      .fromPort(22)\n                      .toPort(22)\n                      .ipProtocol(IpProtocol.TCP)\n                      .cidrBlock(\"0.0.0.0/0\")\n                      .build());\n\n      permissions.add(IpPermission.builder()\n                      .fromPort(0)\n                      .toPort(65535)\n                      .ipProtocol(IpProtocol.TCP)\n                      .tenantIdGroupNamePair(\"ownerId\", \"sg-123456\")\n                      .build());\n      permissions.add(IpPermission.builder()\n                      .fromPort(0)\n                      .toPort(65535)\n                      .ipProtocol(IpProtocol.UDP)\n                      .tenantIdGroupNamePair(\"ownerId\", \"sg-123456\")\n                      .build());\n      \n      expect(\n            client.createSecurityGroupInRegionAndReturnId(\"region\", \"group\", \"group\",\n                  new CreateSecurityGroupOptions().vpcId(\"vpc\"))).andReturn(\"sg-123456\");\n      expect(group.getOwnerId()).andReturn(\"ownerId\");\n      client.authorizeSecurityGroupIngressInRegion(\"region\", \"sg-123456\", permissions.build());\n      expect(client.describeSecurityGroupsInRegionById(\"region\", \"sg-123456\"))\n               .andReturn(Set.class.cast(groups));\n\n\n      replay(client);\n      replay(group);\n      replay(groupIdFromName);\n\n      AWSEC2CreateSecurityGroupIfNeeded function = new AWSEC2CreateSecurityGroupIfNeeded(client, groupIdFromName, tester);\n\n      assertEquals(\"sg-123456\", function.load(new RegionNameAndIngressRules(\"region\", \"group\", new int[] { 22 }, true, \"vpc\")));\n\n      verify(client);\n      verify(group);\n      verify(groupIdFromName);\n\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/options/AWSEC2TemplateOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.compute.options;\n\nimport static org.jclouds.aws.ec2.compute.AWSEC2TemplateOptions.Builder.authorizePublicKey;\nimport static org.jclouds.aws.ec2.compute.AWSEC2TemplateOptions.Builder.blockOnPort;\nimport static org.jclouds.aws.ec2.compute.AWSEC2TemplateOptions.Builder.dedicatedHostId;\nimport static org.jclouds.aws.ec2.compute.AWSEC2TemplateOptions.Builder.enableMonitoring;\nimport static org.jclouds.aws.ec2.compute.AWSEC2TemplateOptions.Builder.iamInstanceProfileArn;\nimport static org.jclouds.aws.ec2.compute.AWSEC2TemplateOptions.Builder.iamInstanceProfileName;\nimport static org.jclouds.aws.ec2.compute.AWSEC2TemplateOptions.Builder.inboundPorts;\nimport static org.jclouds.aws.ec2.compute.AWSEC2TemplateOptions.Builder.installPrivateKey;\nimport static org.jclouds.aws.ec2.compute.AWSEC2TemplateOptions.Builder.keyPair;\nimport static org.jclouds.aws.ec2.compute.AWSEC2TemplateOptions.Builder.noKeyPair;\nimport static org.jclouds.aws.ec2.compute.AWSEC2TemplateOptions.Builder.privateIpAddress;\nimport static org.jclouds.aws.ec2.compute.AWSEC2TemplateOptions.Builder.securityGroupIds;\nimport static org.jclouds.aws.ec2.compute.AWSEC2TemplateOptions.Builder.securityGroups;\nimport static org.jclouds.aws.ec2.compute.AWSEC2TemplateOptions.Builder.tenancy;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\n\nimport org.jclouds.aws.ec2.compute.AWSEC2TemplateOptions;\nimport org.jclouds.aws.ec2.options.Tenancy;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests possible uses of AWSEC2TemplateOptions and\n * AWSEC2TemplateOptions.Builder.*\n */\npublic class AWSEC2TemplateOptionsTest {\n\n   public void testAs() {\n      TemplateOptions options = new AWSEC2TemplateOptions();\n      assertEquals(options.as(AWSEC2TemplateOptions.class), options);\n   }\n\n   @Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = \"all security groups must be non-empty\")\n   public void testsecurityGroupIdsIterableBadFormat() {\n      AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n      options.securityGroupIds(ImmutableSet.of(\"groupId1\", \"\"));\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testsecurityGroupIdsIterableEmptyNotOk() {\n      AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n      options.securityGroupIds(ImmutableSet.<String> of());\n   }\n\n   @Test\n   public void testsecurityGroupIdsIterable() {\n      AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n      options.securityGroupIds(ImmutableSet.of(\"groupId1\", \"groupId2\"));\n      assertEquals(options.getGroupIds(), ImmutableSet.of(\"groupId1\", \"groupId2\"));\n\n   }\n\n   @Test\n   public void testsecurityGroupIdsIterableStatic() {\n      AWSEC2TemplateOptions options = securityGroupIds(ImmutableSet.of(\"groupId1\", \"groupId2\"));\n      assertEquals(options.getGroupIds(), ImmutableSet.of(\"groupId1\", \"groupId2\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = \"all security groups must be non-empty\")\n   public void testsecurityGroupIdsVarArgsBadFormat() {\n      AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n      options.securityGroupIds(\"mygroupId\", \"\");\n   }\n\n   @Test\n   public void testsecurityGroupIdsVarArgs() {\n      AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n      options.securityGroupIds(\"groupId1\", \"groupId2\");\n      assertEquals(options.getGroupIds(), ImmutableSet.of(\"groupId1\", \"groupId2\"));\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testsecurityGroupIdsVarArgsEmptyNotOk() {\n      AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n      options.securityGroupIds();\n   }\n\n   @Test\n   public void testDefaultGroupIdsVarArgsEmpty() {\n      AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n      assertEquals(options.getGroupIds(), ImmutableSet.of());\n   }\n\n   @Test\n   public void testsecurityGroupIdsVarArgsStatic() {\n      AWSEC2TemplateOptions options = securityGroupIds(\"groupId1\", \"groupId2\");\n      assertEquals(options.getGroupIds(), ImmutableSet.of(\"groupId1\", \"groupId2\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = \"all security groups must be non-empty\")\n   public void testsecurityGroupsIterableBadFormat() {\n      AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n      options.securityGroups(ImmutableSet.of(\"group1\", \"\"));\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testsecurityGroupsIterableEmptyNotOk() {\n      AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n      options.securityGroups(ImmutableSet.<String> of());\n   }\n\n   @Test\n   public void testsecurityGroupsIterable() {\n      AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n      options.securityGroups(ImmutableSet.of(\"group1\", \"group2\"));\n      assertEquals(options.getGroups(), ImmutableSet.of(\"group1\", \"group2\"));\n\n   }\n\n   @Test\n   public void testsecurityGroupsIterableStatic() {\n      AWSEC2TemplateOptions options = securityGroups(ImmutableSet.of(\"group1\", \"group2\"));\n      assertEquals(options.getGroups(), ImmutableSet.of(\"group1\", \"group2\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = \"all security groups must be non-empty\")\n   public void testsecurityGroupsVarArgsBadFormat() {\n      AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n      options.securityGroups(\"mygroup\", \"\");\n   }\n\n   @Test\n   public void testsecurityGroupsVarArgs() {\n      AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n      options.securityGroups(\"group1\", \"group2\");\n      assertEquals(options.getGroups(), ImmutableSet.of(\"group1\", \"group2\"));\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testsecurityGroupsVarArgsEmptyNotOk() {\n      AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n      options.securityGroups();\n   }\n\n   @Test\n   public void testDefaultGroupsVarArgsEmpty() {\n      AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n      assertEquals(options.getGroups(), ImmutableSet.of());\n   }\n\n   @Test\n   public void testsecurityGroupsVarArgsStatic() {\n      AWSEC2TemplateOptions options = securityGroups(\"group1\", \"group2\");\n      assertEquals(options.getGroups(), ImmutableSet.of(\"group1\", \"group2\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = \"use noKeyPair option to request boot without a keypair\")\n   public void testkeyPairBadFormat() {\n      AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n      options.keyPair(\"\");\n   }\n\n   @Test(expectedExceptions = IllegalStateException.class)\n   public void testkeyPairAndNoKeyPair() {\n      AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n      options.keyPair(\"mykeypair\");\n      options.noKeyPair();\n   }\n\n   @Test(expectedExceptions = IllegalStateException.class)\n   public void testNoKeyPairAndKeyPair() {\n      AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n      options.noKeyPair();\n      options.keyPair(\"mykeypair\");\n   }\n\n   @Test\n   public void testkeyPair() {\n      AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n      options.keyPair(\"mykeypair\");\n      assertEquals(options.getKeyPair(), \"mykeypair\");\n   }\n\n   @Test\n   public void testNullkeyPair() {\n      AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n      assertEquals(options.getKeyPair(), null);\n   }\n\n   @Test\n   public void testkeyPairStatic() {\n      AWSEC2TemplateOptions options = keyPair(\"mykeypair\");\n      assertEquals(options.getKeyPair(), \"mykeypair\");\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testkeyPairNPE() {\n      keyPair(null);\n   }\n\n   @Test\n   public void testnoKeyPair() {\n      AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n      options.noKeyPair();\n      assertEquals(options.getKeyPair(), null);\n      assert !options.shouldAutomaticallyCreateKeyPair();\n   }\n\n   @Test\n   public void testFalsenoKeyPair() {\n      AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n      assertEquals(options.getKeyPair(), null);\n      assert options.shouldAutomaticallyCreateKeyPair();\n   }\n\n   @Test\n   public void testnoKeyPairStatic() {\n      AWSEC2TemplateOptions options = noKeyPair();\n      assertEquals(options.getKeyPair(), null);\n      assert !options.shouldAutomaticallyCreateKeyPair();\n   }\n\n   @Test\n   public void testMonitoringEnabledDefault() {\n      AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n      assert !options.isMonitoringEnabled();\n   }\n\n   @Test\n   public void testMonitoringEnabled() {\n      AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n      options.enableMonitoring();\n      assert options.isMonitoringEnabled();\n   }\n\n   @Test\n   public void testEnableMonitoringStatic() {\n      AWSEC2TemplateOptions options = enableMonitoring();\n      assertEquals(options.getKeyPair(), null);\n      assert options.isMonitoringEnabled();\n   }\n\n   // superclass tests\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testinstallPrivateKeyBadFormat() {\n      AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n      options.installPrivateKey(\"whompy\");\n   }\n\n   @Test\n   public void testinstallPrivateKey() throws IOException {\n      AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n      options.installPrivateKey(\"-----BEGIN RSA PRIVATE KEY-----\");\n      assertEquals(options.getPrivateKey(), \"-----BEGIN RSA PRIVATE KEY-----\");\n   }\n\n   @Test\n   public void testNullinstallPrivateKey() {\n      AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n      assertEquals(options.getPrivateKey(), null);\n   }\n\n   @Test\n   public void testinstallPrivateKeyStatic() throws IOException {\n      AWSEC2TemplateOptions options = installPrivateKey(\"-----BEGIN RSA PRIVATE KEY-----\");\n      assertEquals(options.getPrivateKey(), \"-----BEGIN RSA PRIVATE KEY-----\");\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testinstallPrivateKeyNPE() {\n      installPrivateKey(null);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testauthorizePublicKeyBadFormat() {\n      AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n      options.authorizePublicKey(\"whompy\");\n   }\n\n   @Test\n   public void testauthorizePublicKey() throws IOException {\n      AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n      options.authorizePublicKey(\"ssh-rsa\");\n      assertEquals(options.getPublicKey(), \"ssh-rsa\");\n   }\n\n   @Test\n   public void testNullauthorizePublicKey() {\n      AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n      assertEquals(options.getPublicKey(), null);\n   }\n\n   @Test\n   public void testauthorizePublicKeyStatic() throws IOException {\n      AWSEC2TemplateOptions options = authorizePublicKey(\"ssh-rsa\");\n      assertEquals(options.getPublicKey(), \"ssh-rsa\");\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testauthorizePublicKeyNPE() {\n      authorizePublicKey(null);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testblockOnPortBadFormat() {\n      AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n      options.blockOnPort(-1, -1);\n   }\n\n   @Test\n   public void testblockOnPort() {\n      AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n      options.blockOnPort(22, 30);\n      assertEquals(options.getPort(), 22);\n      assertEquals(options.getSeconds(), 30);\n\n   }\n\n   @Test\n   public void testNullblockOnPort() {\n      AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n      assertEquals(options.getPort(), -1);\n      assertEquals(options.getSeconds(), -1);\n   }\n\n   @Test\n   public void testblockOnPortStatic() {\n      AWSEC2TemplateOptions options = blockOnPort(22, 30);\n      assertEquals(options.getPort(), 22);\n      assertEquals(options.getSeconds(), 30);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testinboundPortsBadFormat() {\n      AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n      options.inboundPorts(-1, -1);\n   }\n\n   @Test\n   public void testinboundPorts() {\n      AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n      options.inboundPorts(22, 30);\n      assertEquals(options.getInboundPorts()[0], 22);\n      assertEquals(options.getInboundPorts()[1], 30);\n\n   }\n\n   @Test\n   public void testDefaultOpen22() {\n      AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n      assertEquals(options.getInboundPorts()[0], 22);\n   }\n\n   @Test\n   public void testinboundPortsStatic() {\n      AWSEC2TemplateOptions options = inboundPorts(22, 30);\n      assertEquals(options.getInboundPorts()[0], 22);\n      assertEquals(options.getInboundPorts()[1], 30);\n   }\n\n   @Test\n   public void testIAMInstanceProfileArn() {\n      AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n      options.iamInstanceProfileArn(\"arn:aws:iam::123456789012:instance-profile/application_abc/component_xyz/Webserver\");\n      assertEquals(options.getIAMInstanceProfileArn(), \"arn:aws:iam::123456789012:instance-profile/application_abc/component_xyz/Webserver\");\n   }\n\n   @Test\n   public void testNullIAMInstanceProfileArn() {\n      AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n      assertEquals(options.getIAMInstanceProfileArn(), null);\n   }\n\n   @Test\n   public void testIAMInstanceProfileArnStatic() {\n      AWSEC2TemplateOptions options = iamInstanceProfileArn(\"arn:aws:iam::123456789012:instance-profile/application_abc/component_xyz/Webserver\");\n      assertEquals(options.getIAMInstanceProfileArn(), \"arn:aws:iam::123456789012:instance-profile/application_abc/component_xyz/Webserver\");\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testIAMInstanceProfileArnNPE() {\n      iamInstanceProfileArn(null);\n   }\n\n   @Test\n   public void testIAMInstanceProfileName() {\n      AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n      options.iamInstanceProfileName(\"Webserver\");\n      assertEquals(options.getIAMInstanceProfileName(), \"Webserver\");\n   }\n\n   @Test\n   public void testNullIAMInstanceProfileName() {\n      AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n      assertEquals(options.getIAMInstanceProfileName(), null);\n   }\n\n   @Test\n   public void testIAMInstanceProfileNameStatic() {\n      AWSEC2TemplateOptions options = iamInstanceProfileName(\"Webserver\");\n      assertEquals(options.getIAMInstanceProfileName(), \"Webserver\");\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testIAMInstanceProfileNameNPE() {\n      iamInstanceProfileName(null);\n   }\n\n   @Test\n   public void testPrivateIpAddressStatic() {\n      AWSEC2TemplateOptions options = privateIpAddress(\"10.0.0.1\");\n      assertEquals(options.getPrivateIpAddress(), \"10.0.0.1\");\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testPrivateIpAddressNPE() {\n      privateIpAddress(null);\n   }\n\n   @Test\n   public void testTenancy() {\n      AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n      options.tenancy(Tenancy.DEDICATED);\n      assertEquals(options.getTenancy(), Tenancy.DEDICATED);\n   }\n\n   @Test\n   public void testTenancyStatic() {\n      AWSEC2TemplateOptions options = tenancy(Tenancy.HOST);\n      assertEquals(options.getTenancy(), Tenancy.HOST);\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testTenancyNPE() {\n      tenancy(null);\n   }\n\n   @Test\n   public void testDedicatedHostId() {\n      AWSEC2TemplateOptions options = new AWSEC2TemplateOptions();\n      options.dedicatedHostId(\"hostId-1234\");\n      assertEquals(options.getDedicatedHostId(), \"hostId-1234\");\n   }\n\n   @Test\n   public void testDedicatedHostIdStatic() {\n      AWSEC2TemplateOptions options = dedicatedHostId(\"hostId-5678\");\n      assertEquals(options.getDedicatedHostId(), \"hostId-5678\");\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testDedicatedHostIdStaticNPE() {\n      dedicatedHostId(null);\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/strategy/AWSEC2IOExceptionRetryHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.compute.strategy;\n\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.Assert.assertFalse;\n\nimport java.io.IOException;\n\nimport org.jclouds.aws.reference.FormParameters;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpRequest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"AWSEC2IOExceptionRetryHandlerTest\")\npublic class AWSEC2IOExceptionRetryHandlerTest {\n\n   @Test\n   public void testDescribeMethodIsRetried() throws Exception {\n\n      AWSEC2IOExceptionRetryHandler handler = new AWSEC2IOExceptionRetryHandler();\n      IOException e = new IOException(\"test exception\");\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://test.endpoint.com/\").addFormParam(FormParameters.ACTION, \"DescribeInstance\").build();\n      HttpCommand command = new HttpCommand(request);\n\n      assertTrue(handler.shouldRetryRequest(command, e));\n    \t\n   }\n    \n   @Test\n   public void testNonDescribeMethodIsNotRetried() throws Exception {\n    \t\n      AWSEC2IOExceptionRetryHandler handler = new AWSEC2IOExceptionRetryHandler();\n      IOException e = new IOException(\"test exception\");\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://test.endpoint.com/\").addFormParam(FormParameters.ACTION, \"RunInstances\").build();\n      HttpCommand command = new HttpCommand(request);\n    \t\n      assertFalse(handler.shouldRetryRequest(command, e));\n    \t\n    }\n    \n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/strategy/AWSEC2ImageParserTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.compute.strategy;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.compute.config.BaseComputeServiceContextModule;\nimport org.jclouds.compute.domain.ImageBuilder;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.ec2.compute.config.EC2ComputeServiceDependenciesModule;\nimport org.jclouds.ec2.compute.functions.EC2ImageParser;\nimport org.jclouds.ec2.compute.strategy.EC2PopulateDefaultLoginCredentialsForImageStrategy;\nimport org.jclouds.ec2.domain.Image;\nimport org.jclouds.ec2.xml.DescribeImagesResponseHandlerTest;\nimport org.jclouds.json.Json;\nimport org.jclouds.json.config.GsonModule;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicates;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Sets;\nimport com.google.gson.Gson;\nimport com.google.inject.Guice;\n\n@Test(groups = \"unit\", testName = \"AWSEC2ImageParserTest\")\npublic class AWSEC2ImageParserTest {\n   public void testParseAlesticCanonicalImage() {\n\n      Set<org.jclouds.compute.domain.Image> result = convertImages(\"/alestic_canonical.xml\");\n\n      assertEquals(\n            Iterables.get(result, 0),\n            new ImageBuilder()\n                  .operatingSystem(\n                        new OperatingSystem.Builder().family(OsFamily.UBUNTU).arch(\"paravirtual\").version(\"8.04\")\n                              .description(\"ubuntu-images-us/ubuntu-hardy-8.04-i386-server-20091130.manifest.xml\")\n                              .is64Bit(false).build())\n                  .description(\"ubuntu-images-us/ubuntu-hardy-8.04-i386-server-20091130.manifest.xml\")\n                  .defaultCredentials(LoginCredentials.builder().user(\"ubuntu\").build()).id(\"us-east-1/ami-7e28ca17\")\n                  .providerId(\"ami-7e28ca17\").location(defaultLocation).version(\"20091130\")\n                  .userMetadata(ImmutableMap.of(\n                     \"owner\", \"099720109477\",\n                     \"rootDeviceType\", \"instance-store\",\n                     \"virtualizationType\", \"paravirtual\",\n                     \"hypervisor\", \"xen\"))\n                  .status(org.jclouds.compute.domain.Image.Status.AVAILABLE)\n                  .backendStatus(\"available\")\n                  .build());\n      assertEquals(Iterables.get(result, 0).getStatus(), org.jclouds.compute.domain.Image.Status.AVAILABLE);\n\n      assertEquals(\n            Iterables.get(result, 4),\n            new ImageBuilder()\n                  .operatingSystem(\n                        new OperatingSystem.Builder().family(OsFamily.UBUNTU).arch(\"paravirtual\").version(\"8.04\")\n                              .description(\"alestic/ubuntu-8.04-hardy-base-20080905.manifest.xml\").is64Bit(false)\n                              .build()).description(\"alestic/ubuntu-8.04-hardy-base-20080905.manifest.xml\")\n                  .defaultCredentials(LoginCredentials.builder().user(\"ubuntu\").build()).id(\"us-east-1/ami-c0fa1ea9\")\n                  .providerId(\"ami-c0fa1ea9\").location(defaultLocation).version(\"20080905\")\n                  .userMetadata(ImmutableMap.of(\"owner\", \"063491364108\", \"rootDeviceType\", \"instance-store\"))\n                  .status(org.jclouds.compute.domain.Image.Status.AVAILABLE).backendStatus(\"available\").build());\n      assertEquals(Iterables.get(result, 4).getStatus(), org.jclouds.compute.domain.Image.Status.AVAILABLE);\n\n      assertEquals(\n            Iterables.get(result, 6),\n            new ImageBuilder()\n                  .name(\"ebs/ubuntu-images/ubuntu-lucid-10.04-i386-server-20100827\")\n                  .operatingSystem(\n                        new OperatingSystem.Builder().family(OsFamily.UBUNTU).arch(\"paravirtual\").version(\"10.04\")\n                              .description(\"099720109477/ebs/ubuntu-images/ubuntu-lucid-10.04-i386-server-20100827\")\n                              .is64Bit(false).build())\n                  .description(\"099720109477/ebs/ubuntu-images/ubuntu-lucid-10.04-i386-server-20100827\")\n                  .defaultCredentials(LoginCredentials.builder().user(\"ubuntu\").build()).id(\"us-east-1/ami-10f3a255\")\n                  .providerId(\"ami-10f3a255\").location(defaultLocation).version(\"20100827\")\n                  .userMetadata(ImmutableMap.of(\n                     \"owner\", \"099720109477\",\n                     \"rootDeviceType\", \"ebs\",\n                     \"virtualizationType\", \"paravirtual\",\n                     \"hypervisor\", \"xen\"))\n                  .status(org.jclouds.compute.domain.Image.Status.AVAILABLE).backendStatus(\"available\").build());\n      assertEquals(Iterables.get(result, 6).getStatus(), org.jclouds.compute.domain.Image.Status.AVAILABLE);\n\n   }\n\n   public void testParseVostokImage() {\n\n      Set<org.jclouds.compute.domain.Image> result = convertImages(\"/vostok.xml\");\n\n      assertEquals(\n            Iterables.get(result, 0),\n            new ImageBuilder()\n                  .operatingSystem(\n                        new OperatingSystem.Builder().family(OsFamily.UNRECOGNIZED).arch(\"paravirtual\").version(\"\")\n                              .description(\"vostok-builds/vostok-0.95-5622/vostok-0.95-5622.manifest.xml\")\n                              .is64Bit(false).build())\n                  .description(\"vostok-builds/vostok-0.95-5622/vostok-0.95-5622.manifest.xml\")\n                  .defaultCredentials(LoginCredentials.builder().user(\"root\").build()).id(\"us-east-1/ami-870de2ee\")\n                  .providerId(\"ami-870de2ee\").location(defaultLocation).version(\"5622\")\n                  .userMetadata(ImmutableMap.of(\"owner\", \"133804938231\", \"rootDeviceType\", \"instance-store\"))\n                  .status(org.jclouds.compute.domain.Image.Status.AVAILABLE).build());\n\n   }\n\n   public void testParseCCImage() {\n\n      Set<org.jclouds.compute.domain.Image> result = convertImages(\"/describe_images_cc.xml\");\n\n      assertEquals(\n            Iterables.get(result, 0),\n            new ImageBuilder()\n                  .name(\"EC2 CentOS 5.4 HVM AMI\")\n                  .operatingSystem(\n                        new OperatingSystem.Builder().family(OsFamily.CENTOS).arch(\"hvm\").version(\"5.4\")\n                              .description(\"amazon/EC2 CentOS 5.4 HVM AMI\").is64Bit(true).build())\n                  .description(\"EC2 CentOS 5.4 HVM AMI\")\n                  .defaultCredentials(LoginCredentials.builder().user(\"root\").build()).id(\"us-east-1/ami-7ea24a17\")\n                  .providerId(\"ami-7ea24a17\").location(defaultLocation)\n                  .userMetadata(ImmutableMap.of(\n                     \"owner\", \"206029621532\",\n                     \"rootDeviceType\", \"ebs\",\n                     \"virtualizationType\", \"hvm\",\n                     \"hypervisor\", \"xen\"))\n                  .status(org.jclouds.compute.domain.Image.Status.AVAILABLE).build());\n      assertEquals(Iterables.get(result, 0).getStatus(), org.jclouds.compute.domain.Image.Status.AVAILABLE);\n\n   }\n\n   public void testParseRightScaleImage() {\n\n      Set<org.jclouds.compute.domain.Image> result = convertImages(\"/rightscale_images.xml\");\n\n      assertEquals(\n            Iterables.get(result, 0),\n            new ImageBuilder()\n                  .operatingSystem(\n                        new OperatingSystem.Builder().family(OsFamily.CENTOS).arch(\"paravirtual\").version(\"5.4\")\n                              .description(\"rightscale-us-east/CentOS_5.4_x64_v4.4.10.manifest.xml\").is64Bit(true)\n                              .build()).description(\"rightscale-us-east/CentOS_5.4_x64_v4.4.10.manifest.xml\")\n                  .defaultCredentials(LoginCredentials.builder().user(\"root\").build()).id(\"us-east-1/ami-ccb35ea5\")\n                  .providerId(\"ami-ccb35ea5\").location(defaultLocation).version(\"4.4.10\")\n                  .userMetadata(ImmutableMap.of(\"owner\", \"admin\", \"rootDeviceType\", \"instance-store\"))\n                  .status(org.jclouds.compute.domain.Image.Status.AVAILABLE).backendStatus(\"available\").build());\n      assertEquals(Iterables.get(result, 0).getStatus(), org.jclouds.compute.domain.Image.Status.AVAILABLE);\n\n      assertEquals(\n            new Gson().toJson(Iterables.get(result, 1)),\n            \"{\\\"operatingSystem\\\":{\\\"family\\\":\\\"UBUNTU\\\",\\\"arch\\\":\\\"paravirtual\\\",\\\"version\\\":\\\"9.10\\\",\\\"description\\\":\\\"411009282317/RightImage_Ubuntu_9.10_x64_v4.5.3_EBS_Alpha\\\",\\\"is64Bit\\\":true},\\\"status\\\":\\\"AVAILABLE\\\",\\\"backendStatus\\\":\\\"available\\\",\\\"version\\\":\\\"4.5.3_EBS_Alpha\\\",\\\"description\\\":\\\"RightImage_Ubuntu_9.10_x64_v4.5.3_EBS_Alpha\\\",\\\"defaultCredentials\\\":{\\\"authenticateSudo\\\":false,\\\"password\\\":{},\\\"privateKey\\\":{},\\\"identity\\\":\\\"root\\\"},\\\"id\\\":\\\"us-east-1/ami-c19db6b5\\\",\\\"type\\\":\\\"IMAGE\\\",\\\"tags\\\":[],\\\"providerId\\\":\\\"ami-c19db6b5\\\",\\\"name\\\":\\\"RightImage_Ubuntu_9.10_x64_v4.5.3_EBS_Alpha\\\",\\\"location\\\":{\\\"scope\\\":\\\"REGION\\\",\\\"id\\\":\\\"us-east-1\\\",\\\"description\\\":\\\"us-east-1\\\",\\\"iso3166Codes\\\":[],\\\"metadata\\\":{}},\\\"userMetadata\\\":{\\\"owner\\\":\\\"411009282317\\\",\\\"rootDeviceType\\\":\\\"ebs\\\",\\\"virtualizationType\\\":\\\"paravirtual\\\",\\\"hypervisor\\\":\\\"xen\\\"}}\");\n\n      assertEquals(\n              new Gson().toJson(Iterables.get(result, 2)),\n              \"{\\\"operatingSystem\\\":{\\\"family\\\":\\\"WINDOWS\\\",\\\"arch\\\":\\\"hvm\\\",\\\"version\\\":\\\"2003\\\",\\\"description\\\":\\\"411009282317/RightImage Windows_2003_i386_v5.4.3\\\",\\\"is64Bit\\\":false},\\\"status\\\":\\\"AVAILABLE\\\",\\\"backendStatus\\\":\\\"available\\\",\\\"version\\\":\\\"5.4.3\\\",\\\"description\\\":\\\"Built by RightScale\\\",\\\"defaultCredentials\\\":{\\\"authenticateSudo\\\":false,\\\"password\\\":{},\\\"privateKey\\\":{},\\\"identity\\\":\\\"root\\\"},\\\"id\\\":\\\"us-east-1/ami-710c2605\\\",\\\"type\\\":\\\"IMAGE\\\",\\\"tags\\\":[],\\\"providerId\\\":\\\"ami-710c2605\\\",\\\"name\\\":\\\"RightImage Windows_2003_i386_v5.4.3\\\",\\\"location\\\":{\\\"scope\\\":\\\"REGION\\\",\\\"id\\\":\\\"us-east-1\\\",\\\"description\\\":\\\"us-east-1\\\",\\\"iso3166Codes\\\":[],\\\"metadata\\\":{}},\\\"userMetadata\\\":{\\\"owner\\\":\\\"411009282317\\\",\\\"rootDeviceType\\\":\\\"ebs\\\",\\\"virtualizationType\\\":\\\"hvm\\\",\\\"hypervisor\\\":\\\"xen\\\"}}\");\n\n      assertEquals(\n              new Gson().toJson(Iterables.get(result, 3)),\n              \"{\\\"operatingSystem\\\":{\\\"family\\\":\\\"CENTOS\\\",\\\"arch\\\":\\\"paravirtual\\\",\\\"version\\\":\\\"6.5\\\",\\\"description\\\":\\\"411009282317/RightImage_CentOS_6.5_x64_v13.5.2.2_EBS\\\",\\\"is64Bit\\\":true},\\\"status\\\":\\\"AVAILABLE\\\",\\\"backendStatus\\\":\\\"available\\\",\\\"version\\\":\\\"13.5.2.2_EBS\\\",\\\"description\\\":\\\"RightImage_CentOS_6.5_x64_v13.5.2.2_EBS\\\",\\\"defaultCredentials\\\":{\\\"authenticateSudo\\\":false,\\\"password\\\":{},\\\"privateKey\\\":{},\\\"identity\\\":\\\"root\\\"},\\\"id\\\":\\\"us-east-1/ami-05ebd06c\\\",\\\"type\\\":\\\"IMAGE\\\",\\\"tags\\\":[],\\\"providerId\\\":\\\"ami-05ebd06c\\\",\\\"name\\\":\\\"RightImage_CentOS_6.5_x64_v13.5.2.2_EBS\\\",\\\"location\\\":{\\\"scope\\\":\\\"REGION\\\",\\\"id\\\":\\\"us-east-1\\\",\\\"description\\\":\\\"us-east-1\\\",\\\"iso3166Codes\\\":[],\\\"metadata\\\":{}},\\\"userMetadata\\\":{\\\"owner\\\":\\\"411009282317\\\",\\\"rootDeviceType\\\":\\\"ebs\\\",\\\"virtualizationType\\\":\\\"paravirtual\\\",\\\"hypervisor\\\":\\\"xen\\\"}}\");\n\n      assertEquals(\n              new Gson().toJson(Iterables.get(result, 4)),\n              \"{\\\"operatingSystem\\\":{\\\"family\\\":\\\"UBUNTU\\\",\\\"arch\\\":\\\"paravirtual\\\",\\\"version\\\":\\\"10.04\\\",\\\"description\\\":\\\"411009282317/RightImage_Ubuntu_10.04_x64_v12.11.4_EBS\\\",\\\"is64Bit\\\":true},\\\"status\\\":\\\"AVAILABLE\\\",\\\"backendStatus\\\":\\\"available\\\",\\\"version\\\":\\\"12.11.4_EBS\\\",\\\"description\\\":\\\"RightImage_Ubuntu_10.04_x64_v12.11.4_EBS\\\",\\\"defaultCredentials\\\":{\\\"authenticateSudo\\\":false,\\\"password\\\":{},\\\"privateKey\\\":{},\\\"identity\\\":\\\"root\\\"},\\\"id\\\":\\\"us-east-1/ami-08bffe61\\\",\\\"type\\\":\\\"IMAGE\\\",\\\"tags\\\":[],\\\"providerId\\\":\\\"ami-08bffe61\\\",\\\"name\\\":\\\"RightImage_Ubuntu_10.04_x64_v12.11.4_EBS\\\",\\\"location\\\":{\\\"scope\\\":\\\"REGION\\\",\\\"id\\\":\\\"us-east-1\\\",\\\"description\\\":\\\"us-east-1\\\",\\\"iso3166Codes\\\":[],\\\"metadata\\\":{}},\\\"userMetadata\\\":{\\\"owner\\\":\\\"411009282317\\\",\\\"rootDeviceType\\\":\\\"ebs\\\",\\\"virtualizationType\\\":\\\"paravirtual\\\",\\\"hypervisor\\\":\\\"xen\\\"}}\");\n\n   }\n\n   public void testParseAmznImage() {\n\n      Set<org.jclouds.compute.domain.Image> result = convertImages(\"/amzn_images.xml\");\n\n      assertEquals(\n            Iterables.get(result, 0),\n            new ImageBuilder()\n                  .name(\"amzn-ami-0.9.7-beta.i386-ebs\")\n                  .operatingSystem(\n                        new OperatingSystem.Builder().family(OsFamily.AMZN_LINUX).arch(\"paravirtual\")\n                              .version(\"0.9.7-beta\").description(\"137112412989/amzn-ami-0.9.7-beta.i386-ebs\")\n                              .is64Bit(false).build()).description(\"Amazon\")\n                  .defaultCredentials(LoginCredentials.builder().user(\"ec2-user\").build()).id(\"us-east-1/ami-82e4b5c7\")\n                  .providerId(\"ami-82e4b5c7\").location(defaultLocation).version(\"0.9.7-beta\")\n                  .userMetadata(ImmutableMap.of(\n                     \"owner\", \"137112412989\",\n                     \"rootDeviceType\", \"ebs\",\n                     \"virtualizationType\", \"paravirtual\",\n                     \"hypervisor\", \"xen\"))\n                  .status(org.jclouds.compute.domain.Image.Status.AVAILABLE).build());\n      assertEquals(Iterables.get(result, 0).getStatus(), org.jclouds.compute.domain.Image.Status.AVAILABLE);\n\n      assertEquals(\n            Iterables.get(result, 3),\n            new ImageBuilder()\n                  .name(\"amzn-ami-0.9.7-beta.x86_64-S3\")\n                  .operatingSystem(\n                        new OperatingSystem.Builder().family(OsFamily.AMZN_LINUX).arch(\"paravirtual\")\n                              .version(\"0.9.7-beta\")\n                              .description(\"amzn-ami-us-west-1/amzn-ami-0.9.7-beta.x86_64.manifest.xml\").is64Bit(true)\n                              .build()).description(\"Amazon Linux AMI x86_64 S3\")\n                  .defaultCredentials(LoginCredentials.builder().user(\"ec2-user\").build()).id(\"us-east-1/ami-f2e4b5b7\")\n                  .providerId(\"ami-f2e4b5b7\").location(defaultLocation).version(\"0.9.7-beta\")\n                  .userMetadata(ImmutableMap.of(\n                     \"owner\", \"137112412989\",\n                     \"rootDeviceType\", \"ebs\",\n                     \"virtualizationType\", \"paravirtual\",\n                     \"hypervisor\", \"xen\"))\n                  .status(org.jclouds.compute.domain.Image.Status.AVAILABLE).build());\n      assertEquals(Iterables.get(result, 3).getStatus(), org.jclouds.compute.domain.Image.Status.AVAILABLE);\n\n   }\n\n   public void testParseCentOsOnMarketplaceImage() {\n\n      Set<org.jclouds.compute.domain.Image> result = convertImages(\"/centos_marketplace_images.xml\");\n\n      assertEquals(\n            Iterables.get(result, 0),\n            new ImageBuilder()\n                  .name(\"CentOS Linux 7 x86_64 HVM EBS 1704_01-b7ee8a69-ee97-4a49-9e68-afaee216db2e-ami-d52f5bc3.4\")\n                  .operatingSystem(\n                        new OperatingSystem.Builder().family(OsFamily.CENTOS).arch(\"x86_64\")\n                              .version(\"7\").description(\"aws-marketplace/CentOS Linux 7 x86_64 HVM EBS 1704_01-b7ee8a69-ee97-4a49-9e68-afaee216db2e-ami-d52f5bc3.4\")\n                              .is64Bit(true).build()).description(\"CentOS Linux 7 x86_64 HVM EBS 1704_01\")\n                  .defaultCredentials(LoginCredentials.builder().user(\"centos\").build()).id(\"us-east-1/ami-061b1560\")\n                  .providerId(\"ami-061b1560\").location(defaultLocation).version(\"7\")\n                  .userMetadata(ImmutableMap.of(\n                     \"owner\", \"679593333241\",\n                     \"rootDeviceType\", \"ebs\",\n                     \"virtualizationType\", \"hvm\",\n                     \"hypervisor\", \"xen\"))\n                  .status(org.jclouds.compute.domain.Image.Status.AVAILABLE).build());\n      assertEquals(Iterables.get(result, 0).getStatus(), org.jclouds.compute.domain.Image.Status.AVAILABLE);\n\n   }\n\n   static Location defaultLocation = new LocationBuilder().scope(LocationScope.REGION).id(\"us-east-1\")\n         .description(\"us-east-1\").build();\n\n   public static Set<org.jclouds.compute.domain.Image> convertImages(String resource) {\n\n      Map<OsFamily, Map<String, String>> map = new BaseComputeServiceContextModule() {\n      }.provideOsVersionMap(new ComputeServiceConstants.ReferenceData(), Guice.createInjector(new GsonModule())\n            .getInstance(Json.class));\n\n      Set<Image> result = DescribeImagesResponseHandlerTest.parseImages(resource);\n      EC2ImageParser parser = new EC2ImageParser(EC2ComputeServiceDependenciesModule.toPortableImageStatus,\n               new EC2PopulateDefaultLoginCredentialsForImageStrategy(), map, Suppliers\n                        .<Set<? extends Location>> ofInstance(ImmutableSet.<Location> of(defaultLocation)), Suppliers\n                        .ofInstance(defaultLocation), new AWSEC2ReviseParsedImage(map));\n      return Sets.newLinkedHashSet(Iterables.filter(Iterables.transform(result, parser), Predicates.notNull()));\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/strategy/AWSEC2ReviseParsedImageTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.compute.strategy;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Map;\n\nimport org.jclouds.compute.config.BaseComputeServiceContextModule;\nimport org.jclouds.compute.domain.ImageBuilder;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.ec2.compute.strategy.ReviseParsedImage;\nimport org.jclouds.ec2.domain.Hypervisor;\nimport org.jclouds.ec2.domain.Image;\nimport org.jclouds.ec2.domain.RootDeviceType;\nimport org.jclouds.ec2.domain.VirtualizationType;\nimport org.jclouds.json.Json;\nimport org.jclouds.json.config.GsonModule;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\n\npublic class AWSEC2ReviseParsedImageTest {\n    private Map<OsFamily, Map<String, String>> osVersionMap;\n\n    @BeforeClass\n    public void testFixtureSetUp() {\n        osVersionMap = new BaseComputeServiceContextModule() {\n        }.provideOsVersionMap(new ComputeServiceConstants.ReferenceData(), Guice.createInjector(new GsonModule())\n                .getInstance(Json.class));\n    }\n\n    @Test\n    public void testNewWindowsName() throws Exception {\n\n        ReviseParsedImage rpi = new AWSEC2ReviseParsedImage(osVersionMap);\n\n        Image from = newImage(\"amazon\", \"Windows_Server-2008-R2_SP1-English-64Bit-Base-2012.03.13\");\n        OperatingSystem.Builder osBuilder = OperatingSystem.builder().description(\"test\");\n      ImageBuilder builder = new ImageBuilder().id(\"1\").operatingSystem(osBuilder.build()).status(\n               org.jclouds.compute.domain.Image.Status.AVAILABLE).description(\"test\");\n        OsFamily family = OsFamily.WINDOWS;\n\n        rpi.reviseParsedImage(from, builder, family, osBuilder);\n        OperatingSystem os = osBuilder.build();\n        assertEquals(os.getFamily(), OsFamily.WINDOWS);\n        assertEquals(os.getVersion(), \"2008\");\n        assertEquals(builder.build().getVersion(), \"2012.03.13\");\n    }\n\n    @Test\n    public void testOldWindowsName() throws Exception {\n\n        ReviseParsedImage rpi = new AWSEC2ReviseParsedImage(osVersionMap);\n\n        Image from = newImage(\"amazon\", \"Windows-2008R2-SP1-English-Base-2012.01.12\");\n        OperatingSystem.Builder osBuilder = OperatingSystem.builder().description(\"test\");\n        ImageBuilder builder = new ImageBuilder().id(\"1\").operatingSystem(osBuilder.build()).status(\n                 org.jclouds.compute.domain.Image.Status.AVAILABLE).description(\"test\");\n        OsFamily family = OsFamily.WINDOWS;\n\n        rpi.reviseParsedImage(from, builder, family, osBuilder);\n        OperatingSystem os = osBuilder.build();\n        assertEquals(os.getFamily(), OsFamily.WINDOWS);\n        assertEquals(os.getVersion(), \"2008\");\n        assertEquals(builder.build().getVersion(), \"2012.01.12\");\n    }\n\n    private static Image newImage(String imageOwnerId, String imageName) {\n        String region = \"us-east-1\";\n        Image.Architecture architecture = Image.Architecture.X86_64;\n        String description = \"\";\n        String imageId = \"\";\n        Image.ImageState imageState = Image.ImageState.AVAILABLE;\n        Image.ImageType imageType = Image.ImageType.MACHINE;\n        boolean isPublic = true;\n        Iterable<String> productCodes = ImmutableSet.of();\n        String kernelId = \"\";\n        String platform = \"\";\n        String ramdiskId = \"\";\n        RootDeviceType rootDeviceType = RootDeviceType.EBS;\n        String rootDeviceName = \"\";\n        Map<String, Image.EbsBlockDevice> ebsBlockDevices = ImmutableMap.of();\n        Map<String, String> tags = ImmutableMap.of();\n        VirtualizationType virtualizationType = VirtualizationType.HVM;\n        Hypervisor hypervisor = Hypervisor.XEN;\n      Image from = new Image(region, architecture, imageName, description, imageId, imageOwnerId + \"/\" + imageName,\n            imageOwnerId, imageState, \"available\", imageType, isPublic, productCodes, kernelId, platform, ramdiskId,\n            rootDeviceType, rootDeviceName, ebsBlockDevices, tags, virtualizationType, hypervisor);\n        return from;\n    }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/strategy/CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.compute.strategy;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.io.BaseEncoding.base64;\nimport static org.easymock.EasyMock.anyObject;\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.partialMockBuilder;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.jclouds.aws.ec2.compute.AWSEC2TemplateOptions.Builder.keyPair;\nimport static org.jclouds.ec2.compute.strategy.CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptionsTest.CREDENTIALS;\nimport static org.jclouds.ec2.compute.strategy.CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptionsTest.KEYPAIR;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentMap;\n\nimport jakarta.inject.Provider;\n\nimport org.jclouds.aws.domain.Region;\nimport org.jclouds.aws.ec2.AWSEC2Api;\nimport org.jclouds.aws.ec2.compute.AWSEC2TemplateOptions;\nimport org.jclouds.aws.ec2.domain.PlacementGroup;\nimport org.jclouds.aws.ec2.domain.RegionNameAndPublicKeyMaterial;\nimport org.jclouds.aws.ec2.functions.CreatePlacementGroupIfNeeded;\nimport org.jclouds.aws.ec2.options.AWSRunInstancesOptions;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.ec2.compute.domain.EC2HardwareBuilder;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.ec2.compute.domain.RegionNameAndIngressRules;\nimport org.jclouds.ec2.compute.options.EC2TemplateOptions;\nimport org.jclouds.ec2.compute.strategy.CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions;\nimport org.jclouds.ec2.domain.BlockDeviceMapping;\nimport org.jclouds.ec2.domain.KeyPair;\nimport org.jclouds.ec2.options.RunInstancesOptions;\nimport org.jclouds.scriptbuilder.domain.Statements;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\", singleThreaded = true, testName = \"CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsTest\")\npublic class CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptionsTest {\n   private static final Provider<RunInstancesOptions> OPTIONS_PROVIDER = new jakarta.inject.Provider<RunInstancesOptions>() {\n\n      @Override\n      public RunInstancesOptions get() {\n         return new AWSRunInstancesOptions();\n      }\n\n   };\n\n   @Test(enabled = false)\n   public void testExecuteWithDefaultOptionsEC2() throws SecurityException, NoSuchMethodException {\n      // setup constants\n      String region = Region.AP_SOUTHEAST_1;\n      String group = \"group\";\n      Hardware size = EC2HardwareBuilder.m1_small().build();\n      String systemGeneratedKeyPairName = \"systemGeneratedKeyPair\";\n      String generatedGroup = \"group\";\n      Set<String> generatedGroups = ImmutableSet.of(generatedGroup);\n\n      // create mocks\n      CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions strategy = partialMockBuilder(\n            CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.class)\n            .addMockedMethod(\n                  CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class\n                        .getDeclaredMethod(\"getOptionsProvider\"))\n            .addMockedMethod(\n                  CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod(\n                        \"createNewKeyPairUnlessUserSpecifiedOtherwise\", String.class, String.class,\n                        TemplateOptions.class))\n            .addMockedMethod(\n                  CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod(\n                        \"createNewPlacementGroupUnlessUserSpecifiedOtherwise\", String.class, String.class,\n                        TemplateOptions.class))\n            .addMockedMethod(\n                  CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod(\n                        \"getSecurityGroupsForTagAndOptions\", String.class, String.class, String.class,\n                        TemplateOptions.class))\n            .createMock();\n\n      AWSEC2TemplateOptions options = createMock(AWSEC2TemplateOptions.class);\n      Template template = createMock(Template.class);\n\n      // setup expectations\n      expect(strategy.getOptionsProvider()).andReturn(OPTIONS_PROVIDER);\n      expect(template.getHardware()).andReturn(size).atLeastOnce();\n      expect(template.getOptions()).andReturn(options).atLeastOnce();\n      expect(options.getBlockDeviceMappings()).andReturn(ImmutableSet.<BlockDeviceMapping> of()).atLeastOnce();\n      expect(strategy.createNewKeyPairUnlessUserSpecifiedOtherwise(region, group, options)).andReturn(\n            systemGeneratedKeyPairName);\n      expect(strategy.getSecurityGroupsForTagAndOptions(region, group, null, options)).andReturn(generatedGroups);\n      expect(options.getGroupIds()).andReturn(ImmutableSet.<String> of());\n      expect(options.getSubnetId()).andReturn(null);\n      expect(options.getUserData()).andReturn(null);\n      expect(options.isMonitoringEnabled()).andReturn(false);\n\n      // replay mocks\n      replay(options);\n      replay(template);\n      replay(strategy);\n\n      // run\n      RunInstancesOptions customize = strategy.execute(region, group, template);\n      assertEquals(customize.buildQueryParameters(), ImmutableMultimap.<String, String> of());\n      assertEquals(\n            customize.buildFormParameters().entries(),\n            ImmutableMultimap.<String, String> of(\"InstanceType\", size.getProviderId(), \"SecurityGroup.1\",\n                  generatedGroup, \"KeyName\", systemGeneratedKeyPairName).entries());\n      assertEquals(customize.buildRequestHeaders(), ImmutableMultimap.<String, String> of());\n      assertEquals(customize.buildStringPayload(), null);\n\n      // verify mocks\n      verify(options);\n      verify(template);\n      verify(strategy);\n   }\n\n   @Test(enabled = false)\n   public void testExecuteForCCAutomatic() throws SecurityException, NoSuchMethodException {\n      // setup constants\n      String region = Region.US_EAST_1;\n      String group = \"group\";\n      Hardware size = EC2HardwareBuilder.cc1_4xlarge().build();\n      String systemGeneratedKeyPairName = \"systemGeneratedKeyPair\";\n      String generatedGroup = \"group\";\n      Set<String> generatedGroups = ImmutableSet.of(generatedGroup);\n\n      // create mocks\n      CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions strategy = partialMockBuilder(\n            CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.class)\n            .addMockedMethod(\n                  CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class\n                        .getDeclaredMethod(\"getOptionsProvider\"))\n            .addMockedMethod(\n                  CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod(\n                        \"createNewKeyPairUnlessUserSpecifiedOtherwise\", String.class, String.class,\n                        TemplateOptions.class))\n            .addMockedMethod(\n                  CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod(\n                        \"createNewPlacementGroupUnlessUserSpecifiedOtherwise\", String.class, String.class,\n                        TemplateOptions.class))\n            .addMockedMethod(\n                  CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod(\n                        \"getSecurityGroupsForTagAndOptions\", String.class, String.class, String.class,\n                        TemplateOptions.class))\n            .createMock();\n\n      AWSEC2TemplateOptions options = createMock(AWSEC2TemplateOptions.class);\n      Template template = createMock(Template.class);\n\n      // setup expectations\n      expect(strategy.getOptionsProvider()).andReturn(OPTIONS_PROVIDER);\n      expect(template.getHardware()).andReturn(size).atLeastOnce();\n      expect(template.getOptions()).andReturn(options).atLeastOnce();\n      expect(options.getBlockDeviceMappings()).andReturn(ImmutableSet.<BlockDeviceMapping> of()).atLeastOnce();\n      expect(strategy.createNewKeyPairUnlessUserSpecifiedOtherwise(region, group, options)).andReturn(\n            systemGeneratedKeyPairName);\n      expect(strategy.createNewPlacementGroupUnlessUserSpecifiedOtherwise(region, group, options)).andReturn(\n            generatedGroup);\n      expect(strategy.getSecurityGroupsForTagAndOptions(region, group, null, options)).andReturn(generatedGroups);\n      expect(options.getGroupIds()).andReturn(ImmutableSet.<String> of());\n      expect(options.getSubnetId()).andReturn(null);\n      expect(options.getUserData()).andReturn(null);\n      expect(options.isMonitoringEnabled()).andReturn(false);\n\n      // replay mocks\n      replay(options);\n      replay(template);\n      replay(strategy);\n\n      // run\n      RunInstancesOptions customize = strategy.execute(region, group, template);\n      assertEquals(customize.buildQueryParameters(), ImmutableMultimap.<String, String> of());\n      assertEquals(\n            customize.buildFormParameters().entries(),\n            ImmutableMultimap.<String, String> of(\"InstanceType\", size.getProviderId(), \"SecurityGroup.1\",\n                  generatedGroup, \"KeyName\", systemGeneratedKeyPairName, \"Placement.GroupName\", generatedGroup)\n                  .entries());\n      assertEquals(customize.buildRequestHeaders(), ImmutableMultimap.<String, String> of());\n      assertEquals(customize.buildStringPayload(), null);\n\n      // verify mocks\n      verify(options);\n      verify(template);\n      verify(strategy);\n   }\n\n   @Test(enabled = false)\n   public void testExecuteForCCUserSpecified() throws SecurityException, NoSuchMethodException {\n      // setup constants\n      String region = Region.US_EAST_1;\n      String group = \"group\";\n      Hardware size = EC2HardwareBuilder.cc1_4xlarge().build();\n      String systemGeneratedKeyPairName = \"systemGeneratedKeyPair\";\n      String generatedGroup = \"group\";\n      Set<String> generatedGroups = ImmutableSet.of(generatedGroup);\n\n      // create mocks\n      CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions strategy = partialMockBuilder(\n            CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.class)\n            .addMockedMethod(\n                  CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class\n                        .getDeclaredMethod(\"getOptionsProvider\"))\n            .addMockedMethod(\n                  CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod(\n                        \"createNewKeyPairUnlessUserSpecifiedOtherwise\", String.class, String.class,\n                        TemplateOptions.class))\n            .addMockedMethod(\n                  CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod(\n                        \"createNewPlacementGroupUnlessUserSpecifiedOtherwise\", String.class, String.class,\n                        TemplateOptions.class))\n            .addMockedMethod(\n                  CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod(\n                        \"getSecurityGroupsForTagAndOptions\", String.class, String.class, String.class,\n                        TemplateOptions.class))\n            .createMock();\n\n      AWSEC2TemplateOptions options = createMock(AWSEC2TemplateOptions.class);\n      Template template = createMock(Template.class);\n\n      // setup expectations\n      expect(strategy.getOptionsProvider()).andReturn(OPTIONS_PROVIDER);\n      expect(template.getHardware()).andReturn(size).atLeastOnce();\n      expect(template.getOptions()).andReturn(options).atLeastOnce();\n      expect(options.getBlockDeviceMappings()).andReturn(ImmutableSet.<BlockDeviceMapping> of()).atLeastOnce();\n      expect(strategy.createNewKeyPairUnlessUserSpecifiedOtherwise(region, group, options)).andReturn(\n            systemGeneratedKeyPairName);\n      expect(strategy.createNewPlacementGroupUnlessUserSpecifiedOtherwise(region, group, options)).andReturn(\n            generatedGroup);\n      expect(strategy.getSecurityGroupsForTagAndOptions(region, group, null, options)).andReturn(generatedGroups);\n      expect(options.getGroupIds()).andReturn(ImmutableSet.<String> of());\n      expect(options.getSubnetId()).andReturn(null);\n      expect(options.getUserData()).andReturn(null);\n      expect(options.isMonitoringEnabled()).andReturn(false);\n\n      // replay mocks\n      replay(options);\n      replay(template);\n      replay(strategy);\n\n      // run\n      RunInstancesOptions customize = strategy.execute(region, group, template);\n      assertEquals(customize.buildQueryParameters(), ImmutableMultimap.<String, String> of());\n      assertEquals(\n            customize.buildFormParameters().entries(),\n            ImmutableMultimap.<String, String> of(\"InstanceType\", size.getProviderId(), \"SecurityGroup.1\",\n                  generatedGroup, \"KeyName\", systemGeneratedKeyPairName, \"Placement.GroupName\", generatedGroup)\n                  .entries());\n      assertEquals(customize.buildRequestHeaders(), ImmutableMultimap.<String, String> of());\n      assertEquals(customize.buildStringPayload(), null);\n\n      // verify mocks\n      verify(options);\n      verify(template);\n      verify(strategy);\n   }\n\n   @Test(enabled = false)\n   public void testExecuteWithSubnet() throws SecurityException, NoSuchMethodException {\n      // setup constants\n      String region = Region.AP_SOUTHEAST_1;\n      String group = \"group\";\n      Hardware size = EC2HardwareBuilder.m1_small().build();\n      String systemGeneratedKeyPairName = \"systemGeneratedKeyPair\";\n\n      // create mocks\n      CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions strategy = partialMockBuilder(\n            CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.class)\n            .addMockedMethod(\n                  CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class\n                        .getDeclaredMethod(\"getOptionsProvider\"))\n            .addMockedMethod(\n                  CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod(\n                        \"createNewKeyPairUnlessUserSpecifiedOtherwise\", String.class, String.class,\n                        TemplateOptions.class))\n            .addMockedMethod(\n                  CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod(\n                        \"createNewPlacementGroupUnlessUserSpecifiedOtherwise\", String.class, String.class,\n                        TemplateOptions.class))\n            .addMockedMethod(\n                  CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod(\n                        \"getSecurityGroupsForTagAndOptions\", String.class, String.class, String.class,\n                        TemplateOptions.class))\n            .addMockedMethod(\n                  CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod(\n                        \"vpcIdForSubnet\", String.class))\n            .createMock();\n\n      AWSEC2TemplateOptions options = createMock(AWSEC2TemplateOptions.class);\n      Template template = createMock(Template.class);\n\n      // setup expectations\n      expect(strategy.getOptionsProvider()).andReturn(OPTIONS_PROVIDER);\n      expect(template.getHardware()).andReturn(size).atLeastOnce();\n      expect(template.getOptions()).andReturn(options).atLeastOnce();\n      expect(options.getBlockDeviceMappings()).andReturn(ImmutableSet.<BlockDeviceMapping> of()).atLeastOnce();\n      expect(strategy.createNewKeyPairUnlessUserSpecifiedOtherwise(region, group, options)).andReturn(\n            systemGeneratedKeyPairName);\n      expect(options.getGroupIds()).andReturn(ImmutableSet.<String> of());\n      expect(options.getSubnetId()).andReturn(\"1\");\n      expect(options.getUserData()).andReturn(null);\n      expect(options.isMonitoringEnabled()).andReturn(false);\n      expect(strategy.vpcIdForSubnet(\"\", \"1\")).andReturn(\"vpc1\");\n\n      // replay mocks\n      replay(options);\n      replay(template);\n      replay(strategy);\n\n      // run\n      RunInstancesOptions customize = strategy.execute(region, group, template);\n      assertEquals(customize.buildQueryParameters(), ImmutableMultimap.<String, String> of());\n      assertEquals(\n            customize.buildFormParameters().entries(),\n            ImmutableMultimap.<String, String> of(\"InstanceType\", size.getProviderId(), \"SubnetId\", \"1\", \"KeyName\",\n                  systemGeneratedKeyPairName).entries());\n      assertEquals(customize.buildRequestHeaders(), ImmutableMultimap.<String, String> of());\n      assertEquals(customize.buildStringPayload(), null);\n\n      // verify mocks\n      verify(options);\n      verify(template);\n      verify(strategy);\n   }\n\n   @Test(enabled = false)\n   public void testExecuteWithUserData() throws SecurityException, NoSuchMethodException {\n      // setup constants\n      String region = Region.AP_SOUTHEAST_1;\n      String group = \"group\";\n      Hardware size = EC2HardwareBuilder.m1_small().build();\n      String systemGeneratedKeyPairName = \"systemGeneratedKeyPair\";\n      String generatedGroup = \"group\";\n      Set<String> generatedGroups = ImmutableSet.of(generatedGroup);\n\n      // create mocks\n      CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions strategy = partialMockBuilder(\n            CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.class)\n            .addMockedMethod(\n                  CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class\n                        .getDeclaredMethod(\"getOptionsProvider\"))\n            .addMockedMethod(\n                  CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod(\n                        \"createNewKeyPairUnlessUserSpecifiedOtherwise\", String.class, String.class,\n                        TemplateOptions.class))\n            .addMockedMethod(\n                  CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod(\n                        \"createNewPlacementGroupUnlessUserSpecifiedOtherwise\", String.class, String.class,\n                        TemplateOptions.class))\n            .addMockedMethod(\n                  CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class.getDeclaredMethod(\n                        \"getSecurityGroupsForTagAndOptions\", String.class, String.class, String.class,\n                        TemplateOptions.class))\n            .createMock();\n\n      AWSEC2TemplateOptions options = createMock(AWSEC2TemplateOptions.class);\n      Template template = createMock(Template.class);\n\n      // setup expectations\n      expect(strategy.getOptionsProvider()).andReturn(OPTIONS_PROVIDER);\n      expect(template.getHardware()).andReturn(size).atLeastOnce();\n      expect(template.getOptions()).andReturn(options).atLeastOnce();\n      expect(options.getBlockDeviceMappings()).andReturn(ImmutableSet.<BlockDeviceMapping> of()).atLeastOnce();\n      expect(strategy.createNewKeyPairUnlessUserSpecifiedOtherwise(region, group, options)).andReturn(\n            systemGeneratedKeyPairName);\n      expect(strategy.getSecurityGroupsForTagAndOptions(region, group, null, options)).andReturn(generatedGroups);\n      expect(options.getGroupIds()).andReturn(ImmutableSet.<String> of());\n      expect(options.getSubnetId()).andReturn(null);\n      expect(options.getUserData()).andReturn(\"hello\".getBytes());\n      expect(options.isMonitoringEnabled()).andReturn(false);\n\n      // replay mocks\n      replay(options);\n      replay(template);\n      replay(strategy);\n\n      // run\n      RunInstancesOptions customize = strategy.execute(region, group, template);\n      assertEquals(customize.buildQueryParameters(), ImmutableMultimap.<String, String> of());\n      assertEquals(\n            customize.buildFormParameters().entries(),\n            ImmutableMultimap.<String, String> of(\"InstanceType\", size.getProviderId(), \"SecurityGroup.1\", \"group\",\n                  \"KeyName\", systemGeneratedKeyPairName, \"UserData\", base64().encode(\"hello\".getBytes(UTF_8))).entries());\n      assertEquals(customize.buildRequestHeaders(), ImmutableMultimap.<String, String> of());\n      assertEquals(customize.buildStringPayload(), null);\n\n      // verify mocks\n      verify(options);\n      verify(template);\n      verify(strategy);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testCreateNewKeyPairUnlessUserSpecifiedOtherwise_reusesKeyWhenToldToWithRunScriptButNoCredentials() {\n      // setup constants\n      String region = Region.AP_SOUTHEAST_1;\n      String group = \"group\";\n      String userSuppliedKeyPair = \"myKeyPair\";\n\n      // create mocks\n      CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions strategy = setupStrategy();\n      EC2TemplateOptions options = createMock(EC2TemplateOptions.class);\n      KeyPair keyPair = createMock(KeyPair.class);\n\n      // setup expectations\n      expect(options.getKeyPair()).andReturn(userSuppliedKeyPair);\n      expect(options.getPublicKey()).andReturn(null).times(2);\n      expect(options.getLoginPrivateKey()).andReturn(null);\n      expect(options.getRunScript()).andReturn(Statements.exec(\"echo foo\"));\n      expect(strategy.credentialsMap.containsKey(new RegionAndName(region, userSuppliedKeyPair))).andReturn(false);\n\n      // replay mocks\n      replay(options);\n      replay(keyPair);\n      replayStrategy(strategy);\n\n      // run\n      assertEquals(strategy.createNewKeyPairUnlessUserSpecifiedOtherwise(region, group, options), userSuppliedKeyPair);\n\n      // verify mocks\n      verify(options);\n      verify(keyPair);\n      verifyStrategy(strategy);\n   }\n\n   public void testCreateNewKeyPairUnlessUserSpecifiedOtherwise_reusesKeyWhenToldToWithRunScriptAndCredentialsAlreadyInMap() {\n      // setup constants\n      String region = Region.AP_SOUTHEAST_1;\n      String group = \"group\";\n      String userSuppliedKeyPair = \"myKeyPair\";\n\n      // create mocks\n      CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions strategy = setupStrategy();\n      EC2TemplateOptions options = createMock(EC2TemplateOptions.class);\n      KeyPair keyPair = createMock(KeyPair.class);\n\n      // setup expectations\n      expect(options.getPublicKey()).andReturn(null).times(2);\n      expect(options.getKeyPair()).andReturn(userSuppliedKeyPair);\n      expect(options.getLoginPrivateKey()).andReturn(null);\n      expect(options.getRunScript()).andReturn(Statements.exec(\"echo foo\"));\n      expect(strategy.credentialsMap.containsKey(new RegionAndName(region, userSuppliedKeyPair))).andReturn(true);\n\n      // replay mocks\n      replay(options);\n      replay(keyPair);\n      replayStrategy(strategy);\n\n      // run\n      assertEquals(strategy.createNewKeyPairUnlessUserSpecifiedOtherwise(region, group, options), userSuppliedKeyPair);\n\n      // verify mocks\n      verify(options);\n      verify(keyPair);\n      verifyStrategy(strategy);\n   }\n\n   public void testCreateNewKeyPairUnlessUserSpecifiedOtherwise_ImportPublicKeyWhenOptionIsSet() {\n      // setup constants\n      String region = Region.AP_SOUTHEAST_1;\n      String group = \"group\";\n      String userSuppliedKeyPair = \"myKeyPair\";\n\n      // create mocks\n      CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions strategy = setupStrategy();\n      EC2TemplateOptions options = createMock(EC2TemplateOptions.class);\n      KeyPair keyPair = createMock(KeyPair.class);\n\n      // we specify we have a public key we want to use for authentication\n      expect(options.getPublicKey()).andReturn(\"ssh-rsa\").times(2);\n      expect(options.getLoginPrivateKey()).andReturn(CREDENTIALS.getOptionalPrivateKey().get()).atLeastOnce();\n\n      // Here, we import the keypair and place it into the cache\n      expect(strategy.importExistingKeyPair.apply(new RegionNameAndPublicKeyMaterial(region, group, \"ssh-rsa\")))\n            .andReturn(KEYPAIR);\n      expect(options.dontAuthorizePublicKey()).andReturn(options);\n      expect(strategy.credentialsMap.put(new RegionAndName(region, group), KEYPAIR)).andReturn(null);\n      expect(options.getRunScript()).andReturn(Statements.exec(\"echo foo\"));\n\n      // replay mocks\n      replay(options);\n      replay(keyPair);\n      replayStrategy(strategy);\n\n      // run\n      assertEquals(strategy.createNewKeyPairUnlessUserSpecifiedOtherwise(region, group, options), userSuppliedKeyPair);\n\n      // verify mocks\n      verify(options);\n      verify(keyPair);\n      verifyStrategy(strategy);\n   }\n\n   @Test\n   public void testCreateNewKeyPairUnlessUserSpecifiedOtherwise_importsKeyPairAndUnsetsTemplateInstructionWhenPublicKeySuppliedAndAddsCredentialToMapWhenOverridingCredsAreSet() {\n      // setup constants\n      String region = Region.AP_SOUTHEAST_1;\n      String group = \"group\";\n\n      // create mocks\n      CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions strategy = setupStrategy();\n      AWSEC2TemplateOptions options = keyPair(group).authorizePublicKey(\"ssh-rsa\").overrideLoginCredentials(\n            LoginCredentials.builder().user(\"foo\").privateKey(CREDENTIALS.credential).build());\n      KeyPair keyPair = new KeyPair(region, group, \"//TODO\", null, null);\n\n      // setup expectations\n      expect(\n            strategy.importExistingKeyPair.apply(new RegionNameAndPublicKeyMaterial(region, group,\n                  CREDENTIALS.credential))).andReturn(keyPair);\n      expect(\n            strategy.credentialsMap.put(new RegionAndName(region, group),\n                  keyPair.toBuilder().keyMaterial(CREDENTIALS.credential).build())).andReturn(null);\n\n      // replay mocks\n      replayStrategy(strategy);\n\n      // run\n      assertEquals(strategy.createNewKeyPairUnlessUserSpecifiedOtherwise(region, group, options), group);\n\n      // verify mocks\n      verifyStrategy(strategy);\n   }\n\n   @Test\n   public void testCreateNewKeyPairUnlessUserSpecifiedOtherwise_importsKeyPairAndUnsetsTemplateInstructionWhenPublicKeySupplied() {\n      // setup constants\n      String region = Region.AP_SOUTHEAST_1;\n      String group = \"group\";\n      AWSEC2TemplateOptions options = keyPair(group).authorizePublicKey(\"ssh-rsa\");\n\n      // create mocks\n      CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions strategy = setupStrategy();\n\n      KeyPair keyPair = new KeyPair(region, \"jclouds#\" + group, \"fingerprint\", null, null);\n\n      // setup expectations\n      expect(strategy.importExistingKeyPair.apply(new RegionNameAndPublicKeyMaterial(region, group, \"ssh-rsa\")))\n            .andReturn(keyPair);\n      expect(strategy.credentialsMap.put(new RegionAndName(region, group), keyPair)).andReturn(null);\n\n      // replay mocks\n      replayStrategy(strategy);\n\n      // run\n      assertEquals(strategy.createNewKeyPairUnlessUserSpecifiedOtherwise(region, group, options), \"jclouds#\" + group);\n\n      // verify mocks\n      verifyStrategy(strategy);\n   }\n\n   public void testCreateNewKeyPairUnlessUserSpecifiedOtherwise_createsNewKeyPairAndReturnsItsNameWhenNoPublicKeySupplied() {\n      // setup constants\n      String region = Region.AP_SOUTHEAST_1;\n      String group = \"group\";\n      String userSuppliedKeyPair = null;\n      boolean shouldAutomaticallyCreateKeyPair = true;\n      String systemGeneratedKeyPairName = \"systemGeneratedKeyPair\";\n\n      // create mocks\n      CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions strategy = setupStrategy();\n      AWSEC2TemplateOptions options = createMock(AWSEC2TemplateOptions.class);\n      KeyPair keyPair = createMock(KeyPair.class);\n\n      // setup expectations\n      expect(options.getKeyPair()).andReturn(userSuppliedKeyPair);\n      expect(options.shouldAutomaticallyCreateKeyPair()).andReturn(shouldAutomaticallyCreateKeyPair);\n      expect(strategy.credentialsMap.putIfAbsent(anyObject(RegionAndName.class), anyObject(KeyPair.class))).andReturn(keyPair);\n      expect(options.getPublicKey()).andReturn(null).times(2);\n      expect(keyPair.getKeyName()).andReturn(systemGeneratedKeyPairName).atLeastOnce();\n      expect(options.getRunScript()).andReturn(null);\n\n      // replay mocks\n      replay(options);\n      replay(keyPair);\n      replayStrategy(strategy);\n\n      // run\n      assertEquals(strategy.createNewKeyPairUnlessUserSpecifiedOtherwise(region, group, options),\n            systemGeneratedKeyPairName);\n\n      // verify mocks\n      verify(options);\n      verify(keyPair);\n      verifyStrategy(strategy);\n   }\n\n   public void testCreateNewKeyPairUnlessUserSpecifiedOtherwise_returnsExistingKeyIfAlreadyPresent() {\n      // setup constants\n      String region = Region.AP_SOUTHEAST_1;\n      String group = \"group\";\n      String systemGeneratedKeyPairName = \"systemGeneratedKeyPair\";\n\n      // create mocks\n      CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions strategy = setupStrategy();\n      AWSEC2TemplateOptions options = createMock(AWSEC2TemplateOptions.class);\n      KeyPair keyPair = createMock(KeyPair.class);\n\n      // setup expectations\n      expect(options.getLoginPrivateKey()).andReturn(null);\n      expect(options.getRunScript()).andReturn(Statements.exec(\"echo hello\"));\n      expect(options.getPublicKey()).andReturn(null).times(2);\n      expect(options.getKeyPair()).andReturn(systemGeneratedKeyPairName);\n      expect(strategy.credentialsMap.containsKey(new RegionAndName(region, systemGeneratedKeyPairName)))\n            .andReturn(true);\n\n      // replay mocks\n      replay(options);\n      replay(keyPair);\n      replayStrategy(strategy);\n\n      // run\n      assertEquals(strategy.createNewKeyPairUnlessUserSpecifiedOtherwise(region, group, options),\n            systemGeneratedKeyPairName);\n\n      // verify mocks\n      verify(options);\n      verify(keyPair);\n      verifyStrategy(strategy);\n   }\n\n   public void testCreateNewKeyPairUnlessUserSpecifiedOtherwise_doesntCreateAKeyPairAndReturnsNullWhenToldNotTo() {\n      // setup constants\n      String region = Region.AP_SOUTHEAST_1;\n      String group = \"group\";\n      String userSuppliedKeyPair = null;\n      boolean shouldAutomaticallyCreateKeyPair = false; // here's the important\n      // part!\n\n      // create mocks\n      CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions strategy = setupStrategy();\n      AWSEC2TemplateOptions options = createMock(AWSEC2TemplateOptions.class);\n      KeyPair keyPair = createMock(KeyPair.class);\n\n      // setup expectations\n      expect(options.getPublicKey()).andReturn(null).times(2);\n      expect(options.getKeyPair()).andReturn(userSuppliedKeyPair);\n      expect(options.getRunScript()).andReturn(null);\n      expect(options.shouldAutomaticallyCreateKeyPair()).andReturn(shouldAutomaticallyCreateKeyPair);\n\n      // replay mocks\n      replay(options);\n      replay(keyPair);\n      replayStrategy(strategy);\n\n      // run\n      assertEquals(strategy.createNewKeyPairUnlessUserSpecifiedOtherwise(region, group, options), null);\n\n      // verify mocks\n      verify(options);\n      verify(keyPair);\n      verifyStrategy(strategy);\n   }\n\n   public void testGetSecurityGroupsForTagAndOptions_createsNewGroupByDefaultWhenNoPortsAreSpecifiedWhenDoesntExist() {\n      // setup constants\n      String region = Region.AP_SOUTHEAST_1;\n      String group = \"group\";\n      String generatedMarkerGroup = \"jclouds#group\";\n      Set<String> groupNames = ImmutableSet.<String> of();\n      int[] ports = {};\n      boolean shouldAuthorizeSelf = true;\n      Set<String> returnVal = ImmutableSet.<String> of(\"sg-12345\");\n\n      // create mocks\n      CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions strategy = setupStrategy();\n      AWSEC2TemplateOptions options = createMock(AWSEC2TemplateOptions.class);\n\n      // setup expectations\n      expect(options.getGroupIds()).andReturn(ImmutableSet.<String> of());\n      expect(options.getGroups()).andReturn(groupNames).atLeastOnce();\n      expect(options.getInboundPorts()).andReturn(ports).atLeastOnce();\n      RegionNameAndIngressRules regionNameAndIngressRules = new RegionNameAndIngressRules(region, generatedMarkerGroup,\n            ports, shouldAuthorizeSelf, null);\n      expect(strategy.securityGroupMap.getUnchecked(regionNameAndIngressRules)).andReturn(\"sg-12345\");\n\n      // replay mocks\n      replay(options);\n      replayStrategy(strategy);\n\n      // run\n      assertEquals(strategy.getSecurityGroupsForTagAndOptions(region, group, null, options), returnVal);\n\n      // verify mocks\n      verify(options);\n      verifyStrategy(strategy);\n   }\n\n   public void testGetSecurityGroupsForTagAndOptions_createsNewGroupByDefaultWhenPortsAreSpecifiedWhenDoesntExist() {\n      // setup constants\n      String region = Region.AP_SOUTHEAST_1;\n      String group = \"group\";\n      String generatedMarkerGroup = \"jclouds#group\";\n      Set<String> groupNames = ImmutableSet.<String> of();\n      int[] ports = { 22, 80 };\n      boolean shouldAuthorizeSelf = true;\n      Set<String> returnVal = ImmutableSet.<String> of(\"sg-12345\");\n\n      // create mocks\n      CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions strategy = setupStrategy();\n      AWSEC2TemplateOptions options = createMock(AWSEC2TemplateOptions.class);\n\n      // setup expectations\n      expect(options.getGroupIds()).andReturn(ImmutableSet.<String> of());\n      expect(options.getGroups()).andReturn(groupNames).atLeastOnce();\n      expect(options.getInboundPorts()).andReturn(ports).atLeastOnce();\n      RegionNameAndIngressRules regionNameAndIngressRules = new RegionNameAndIngressRules(region, generatedMarkerGroup,\n            ports, shouldAuthorizeSelf, null);\n      expect(strategy.securityGroupMap.getUnchecked(regionNameAndIngressRules)).andReturn(\"sg-12345\");\n\n      // replay mocks\n      replay(options);\n      replayStrategy(strategy);\n\n      // run\n      assertEquals(strategy.getSecurityGroupsForTagAndOptions(region, group, null, options), returnVal);\n\n      // verify mocks\n      verify(options);\n      verifyStrategy(strategy);\n   }\n\n   public void testGetSecurityGroupsForTagAndOptions_reusesGroupByDefaultWhenNoPortsAreSpecifiedWhenDoesExist() {\n      // setup constants\n      String region = Region.AP_SOUTHEAST_1;\n      String group = \"group\";\n      String generatedMarkerGroup = \"jclouds#group\";\n      Set<String> groupNames = ImmutableSet.<String> of();\n      int[] ports = {};\n      boolean shouldAuthorizeSelf = true;\n      Set<String> returnVal = ImmutableSet.<String> of(\"sg-12345\");\n\n      // create mocks\n      CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions strategy = setupStrategy();\n      AWSEC2TemplateOptions options = createMock(AWSEC2TemplateOptions.class);\n\n      // setup expectations\n      expect(options.getGroupIds()).andReturn(ImmutableSet.<String> of());\n      expect(options.getGroups()).andReturn(groupNames).atLeastOnce();\n      expect(options.getInboundPorts()).andReturn(ports).atLeastOnce();\n      RegionNameAndIngressRules regionNameAndIngressRules = new RegionNameAndIngressRules(region, generatedMarkerGroup,\n            ports, shouldAuthorizeSelf, null);\n      expect(strategy.securityGroupMap.getUnchecked(regionNameAndIngressRules)).andReturn(\"sg-12345\");\n\n      // replay mocks\n      replay(options);\n      replayStrategy(strategy);\n\n      // run\n      assertEquals(strategy.getSecurityGroupsForTagAndOptions(region, group, null, options), returnVal);\n\n      // verify mocks\n      verify(options);\n      verifyStrategy(strategy);\n   }\n\n   public void testGetSecurityGroupsForTagAndOptions_DoesNotReuseGroupByDefaultWhenNoPortsAreSpecifiedWhenDoesExistAndAcceptsUserSuppliedGroups() {\n      // setup constants\n      String region = Region.AP_SOUTHEAST_1;\n      String group = \"group\";\n      Set<String> groupNames = ImmutableSet.<String> of(\"group1\", \"group2\");\n      Set<String> returnVal = ImmutableSet.<String> of(\"group1\", \"group2\");\n\n      // create mocks\n      CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions strategy = setupStrategy();\n      AWSEC2TemplateOptions options = createMock(AWSEC2TemplateOptions.class);\n\n      // setup expectations\n      expect(options.getGroupIds()).andReturn(ImmutableSet.<String> of());\n      expect(options.getGroups()).andReturn(groupNames).atLeastOnce();\n\n      // replay mocks\n      replay(options);\n      replayStrategy(strategy);\n\n      // run\n      assertEquals(strategy.getSecurityGroupsForTagAndOptions(region, group, null, options), returnVal);\n\n      // verify mocks\n      verify(options);\n      verifyStrategy(strategy);\n   }\n\n   public void testGetSecurityGroupsForTagAndOptions_DoesNotReuseGroupByDefaultWhenNoPortsAreSpecifiedWhenDoesExistAndAcceptsUserSuppliedGroupIds() {\n      // setup constants\n      String region = Region.AP_SOUTHEAST_1;\n      String group = \"group\";\n      Set<String> groupNames = ImmutableSet.<String> of();\n      Set<String> returnVal = ImmutableSet.<String> of();\n\n      // create mocks\n      CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions strategy = setupStrategy();\n      AWSEC2TemplateOptions options = createMock(AWSEC2TemplateOptions.class);\n\n      // setup expectations\n      expect(options.getGroupIds()).andReturn(ImmutableSet.<String> of(\"group1\", \"group2\"));\n      expect(options.getGroups()).andReturn(groupNames).atLeastOnce();\n\n      // replay mocks\n      replay(options);\n      replayStrategy(strategy);\n\n      // run\n      assertEquals(strategy.getSecurityGroupsForTagAndOptions(region, group, null, options), returnVal);\n\n      // verify mocks\n      verify(options);\n      verifyStrategy(strategy);\n   }\n\n   public void testCreateNewPlacementGroupUnlessUserSpecifiedOtherwise_reusesKeyWhenToldTo() {\n      // setup constants\n      String region = Region.AP_SOUTHEAST_1;\n      String group = \"group\";\n      String userSuppliedPlacementGroup = \"myPlacementGroup\";\n\n      // create mocks\n      CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions strategy = setupStrategy();\n      AWSEC2TemplateOptions options = createMock(AWSEC2TemplateOptions.class);\n      PlacementGroup placementGroup = createMock(PlacementGroup.class);\n\n      // setup expectations\n      expect(options.getPlacementGroup()).andReturn(userSuppliedPlacementGroup);\n\n      // replay mocks\n      replay(options);\n      replay(placementGroup);\n      replayStrategy(strategy);\n\n      // run\n      assertEquals(strategy.createNewPlacementGroupUnlessUserSpecifiedOtherwise(region, group, options),\n            userSuppliedPlacementGroup);\n\n      // verify mocks\n      verify(options);\n      verify(placementGroup);\n      verifyStrategy(strategy);\n   }\n\n   public void testCreateNewPlacementGroupUnlessUserSpecifiedOtherwise_createsNewPlacementGroupAndReturnsItsNameByDefault() {\n      // setup constants\n      String region = Region.AP_SOUTHEAST_1;\n      String group = \"group\";\n      String userSuppliedPlacementGroup = null;\n      boolean shouldAutomaticallyCreatePlacementGroup = true;\n      String generatedMarkerGroup = \"jclouds#group#\" + Region.AP_SOUTHEAST_1;\n\n      // create mocks\n      CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions strategy = setupStrategy();\n      AWSEC2TemplateOptions options = createMock(AWSEC2TemplateOptions.class);\n\n      // setup expectations\n      expect(options.getPlacementGroup()).andReturn(userSuppliedPlacementGroup);\n      expect(options.shouldAutomaticallyCreatePlacementGroup()).andReturn(shouldAutomaticallyCreatePlacementGroup);\n      expect(strategy.placementGroupMap.getUnchecked(new RegionAndName(region, generatedMarkerGroup))).andReturn(\n            generatedMarkerGroup);\n\n      // replay mocks\n      replay(options);\n      replayStrategy(strategy);\n\n      // run\n      assertEquals(strategy.createNewPlacementGroupUnlessUserSpecifiedOtherwise(region, group, options),\n            generatedMarkerGroup);\n\n      // verify mocks\n      verify(options);\n      verifyStrategy(strategy);\n   }\n\n   public void testCreateNewPlacementGroupUnlessUserSpecifiedOtherwise_doesntCreateAPlacementGroupAndReturnsNullWhenToldNotTo() {\n      // setup constants\n      String region = Region.AP_SOUTHEAST_1;\n      String group = \"group\";\n      String userSuppliedPlacementGroup = null;\n      boolean shouldAutomaticallyCreatePlacementGroup = false; // here's the\n                                                               // important\n      // part!\n\n      // create mocks\n      CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions strategy = setupStrategy();\n      AWSEC2TemplateOptions options = createMock(AWSEC2TemplateOptions.class);\n      PlacementGroup placementGroup = createMock(PlacementGroup.class);\n\n      // setup expectations\n      expect(options.getPlacementGroup()).andReturn(userSuppliedPlacementGroup);\n      expect(options.shouldAutomaticallyCreatePlacementGroup()).andReturn(shouldAutomaticallyCreatePlacementGroup);\n\n      // replay mocks\n      replay(options);\n      replay(placementGroup);\n      replayStrategy(strategy);\n\n      // run\n      assertEquals(strategy.createNewPlacementGroupUnlessUserSpecifiedOtherwise(region, group, options), null);\n\n      // verify mocks\n      verify(options);\n      verify(placementGroup);\n      verifyStrategy(strategy);\n   }\n\n   private void verifyStrategy(CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions strategy) {\n      verify(strategy.makeKeyPair);\n      verify(strategy.credentialsMap);\n      verify(strategy.securityGroupMap);\n      verify(strategy.placementGroupMap);\n      verify(strategy.importExistingKeyPair);\n      verify(strategy.createPlacementGroupIfNeeded);\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   private CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions setupStrategy() {\n      Function<RegionAndName, KeyPair> makeKeyPair = createMock(Function.class);\n      ConcurrentMap<RegionAndName, KeyPair> credentialsMap = createMock(ConcurrentMap.class);\n      LoadingCache<RegionAndName, String> securityGroupMap = createMock(LoadingCache.class);\n      LoadingCache<RegionAndName, String> placementGroupMap = createMock(LoadingCache.class);\n      Function<RegionNameAndPublicKeyMaterial, KeyPair> importExistingKeyPair = createMock(Function.class);\n      CreatePlacementGroupIfNeeded createPlacementGroupIfNeeded = createMock(CreatePlacementGroupIfNeeded.class);\n      GroupNamingConvention.Factory namingConventionFactory = createMock(GroupNamingConvention.Factory.class);\n      GroupNamingConvention namingConvention = createMock(GroupNamingConvention.class);\n      AWSEC2Api api = createMock(AWSEC2Api.class);\n      expect(namingConventionFactory.create()).andReturn(namingConvention).anyTimes();\n      expect(namingConvention.sharedNameForGroup(\"group\")).andReturn(\"jclouds#group\").anyTimes();\n      expect(makeKeyPair.apply(anyObject(RegionAndName.class))).andReturn(null).anyTimes();\n      replay(namingConventionFactory);\n      replay(namingConvention);\n\n      return new CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions(makeKeyPair, credentialsMap,\n            securityGroupMap, OPTIONS_PROVIDER, placementGroupMap, createPlacementGroupIfNeeded, importExistingKeyPair,\n            namingConventionFactory, api);\n   }\n\n   private void replayStrategy(CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions strategy) {\n      replay(strategy.makeKeyPair);\n      replay(strategy.credentialsMap);\n      replay(strategy.securityGroupMap);\n      replay(strategy.placementGroupMap);\n      replay(strategy.importExistingKeyPair);\n      replay(strategy.createPlacementGroupIfNeeded);\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/features/AWSAMIApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.features;\n\nimport static com.google.common.collect.Iterables.concat;\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static org.jclouds.aws.ec2.options.AWSDescribeImagesOptions.Builder.filters;\nimport static org.jclouds.ec2.options.RegisterImageBackedByEbsOptions.Builder.addNewBlockDevice;\nimport static org.jclouds.ec2.options.RunInstancesOptions.Builder.withBlockDeviceMappings;\nimport static org.jclouds.util.Predicates2.retry;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Properties;\nimport java.util.Set;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport org.jclouds.Constants;\nimport org.jclouds.aws.domain.Region;\nimport org.jclouds.compute.RunNodesException;\nimport org.jclouds.ec2.domain.BlockDevice;\nimport org.jclouds.ec2.domain.BlockDeviceMapping;\nimport org.jclouds.ec2.domain.Image;\nimport org.jclouds.ec2.domain.RunningInstance;\nimport org.jclouds.ec2.domain.Snapshot;\nimport org.jclouds.ec2.domain.Volume;\nimport org.jclouds.ec2.features.AMIApiLiveTest;\nimport org.jclouds.ec2.options.RegisterImageBackedByEbsOptions;\nimport org.jclouds.ec2.options.RunInstancesOptions;\nimport org.jclouds.ec2.predicates.SnapshotCompleted;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code AMIApi}\n */\n@Test(groups = \"live\", singleThreaded = true)\npublic class AWSAMIApiLiveTest extends AMIApiLiveTest {\n\n   public AWSAMIApiLiveTest() {\n      provider = \"aws-ec2\";\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties overrides = super.setupProperties();\n      overrides.put(Constants.PROPERTY_API_VERSION, \"2014-05-01\");\n      return overrides;\n   }\n\n   public void testDescribeImagesCC() {\n      Set<? extends Image> ccResults = client.describeImagesInRegion(Region.US_EAST_1,\n            filters(ImmutableMultimap.<String, String> builder()//\n                  .put(\"virtualization-type\", \"hvm\")//\n                  .put(\"architecture\", \"x86_64\")//\n                  .putAll(\"owner-id\", ImmutableSet.<String> of(\"137112412989\", \"099720109477\"))//\n                  .put(\"hypervisor\", \"xen\")//\n                  .put(\"state\", \"available\")//\n                  .put(\"image-type\", \"machine\")//\n                  .put(\"root-device-type\", \"ebs\")//\n                  .build()).ownedBy(\"137112412989\", \"099720109477\"));\n      assertNotNull(ccResults);\n      assert ccResults.size() >= 34 : ccResults;\n   }\n\n   protected RegisterImageBackedByEbsOptions newBlockDeviceOption() {\n      return addNewBlockDevice(\"/dev/sda2\", \"myvirtual\", 5, false, \"gp2\", null, false).withDescription(\"adrian\");\n   }\n\n   protected Image.EbsBlockDevice newBlockDeviceInfo() {\n      return new Image.EbsBlockDevice(null, 5, false, \"gp2\", null, false);\n   }\n\n\n   @Override\n   protected Snapshot createSnapshot() throws RunNodesException {\n\n      String instanceId = null;\n      try {\n         BlockDeviceMapping mapping = new BlockDeviceMapping.MapNewVolumeToDevice(\"/dev/sdb\", 1, true, \"gp2\", null, false);\n         RunInstancesOptions options = withBlockDeviceMappings(ImmutableSet\n                 .<BlockDeviceMapping> of(mapping));\n\n         RunningInstance instance = getOnlyElement(concat(ec2Api.getInstanceApi().get().runInstancesInRegion(\n                 regionId, null, imageId, 1, 1, options)));\n         instanceId = instance.getId();\n\n         assertTrue(runningTester.apply(instance), instanceId + \"didn't achieve the state running!\");\n\n         instance = getOnlyElement(concat(ec2Api.getInstanceApi().get().describeInstancesInRegion(regionId,\n                 instanceId)));\n         BlockDevice gp2Device = instance.getEbsBlockDevices().get(\"/dev/sdb\");\n         assertNotNull(gp2Device, \"device /dev/sdb not present on \" + instance);\n         Volume gp2Volume = Iterables.getOnlyElement(ec2Api.getElasticBlockStoreApi().get().describeVolumesInRegion(regionId, gp2Device.getVolumeId()));\n         assertNotNull(gp2Volume, \"/dev/sdb volume is null\");\n         assertEquals(gp2Volume.getVolumeType(), \"gp2\");\n         BlockDevice device = instance.getEbsBlockDevices().get(\"/dev/sda1\");\n         assertNotNull(device, \"device: /dev/sda1 not present on: \" + instance);\n         Snapshot snapshot = ec2Api.getElasticBlockStoreApi().get().createSnapshotInRegion(regionId,\n                 device.getVolumeId());\n         snapshotsToDelete.add(snapshot.getId());\n         Predicate<Snapshot> snapshotted = retry(new SnapshotCompleted(ec2Api.getElasticBlockStoreApi().get()), 600, 10, SECONDS);\n         assert snapshotted.apply(snapshot);\n         return snapshot;\n      } finally {\n         if (instanceId != null)\n            ec2Api.getInstanceApi().get().terminateInstancesInRegion(regionId, instanceId);\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/features/AWSAMIApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.features;\n\nimport static org.jclouds.ec2.options.DescribeImagesOptions.Builder.executableBy;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport okhttp3.mockwebserver.MockResponse;\n\nimport org.jclouds.aws.ec2.internal.BaseAWSEC2ApiMockTest;\nimport org.jclouds.ec2.domain.Image;\nimport org.jclouds.ec2.domain.Permission;\nimport org.jclouds.ec2.options.CreateImageOptions;\nimport org.jclouds.ec2.options.RegisterImageBackedByEbsOptions;\nimport org.jclouds.ec2.options.RegisterImageOptions;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"AWSAMIApiMockTest\", singleThreaded = true)\npublic class AWSAMIApiMockTest extends BaseAWSEC2ApiMockTest {\n\n   public void describeImagesInRegion() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(DEFAULT_REGION, \"/amzn_images.xml\");\n\n      Set<? extends Image> result = amiApi().describeImagesInRegion(DEFAULT_REGION);\n\n      assertFalse(result.isEmpty());\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeImages\");\n   }\n\n   public void describeImagesInRegion_options() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(DEFAULT_REGION, \"/amzn_images.xml\");\n\n      Set<? extends Image> result = amiApi()\n            .describeImagesInRegion(DEFAULT_REGION, executableBy(\"me\").ownedBy(\"fred\", \"nancy\").imageIds(\"1\", \"2\"));\n\n      assertFalse(result.isEmpty());\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeImages&ExecutableBy=me&Owner.1=fred&Owner.2=nancy&ImageId.1=1&ImageId.2=2\");\n   }\n\n   public void describeImagesInRegion_404() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION, new MockResponse().setResponseCode(404));\n\n      Set<? extends Image> result = amiApi().describeImagesInRegion(DEFAULT_REGION);\n\n      assertTrue(result.isEmpty());\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeImages\");\n   }\n\n   public void createImageInRegion() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION, new MockResponse().setBody(\"<CreateImageResponse><ImageId>ami-246f8d4d</ImageId></CreateImageResponse>\"));\n\n      String result = amiApi().createImageInRegion(DEFAULT_REGION, \"name\", \"instanceId\");\n      assertEquals(result, \"ami-246f8d4d\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=CreateImage&Name=name&InstanceId=instanceId\");\n   }\n\n   public void createImageInRegion_options() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION,\n            new MockResponse().setBody(\"<CreateImageResponse><ImageId>ami-246f8d4d</ImageId></CreateImageResponse>\"));\n\n      String result = amiApi().createImageInRegion(DEFAULT_REGION, \"name\", \"instanceId\",\n            new CreateImageOptions().withDescription(\"description\").noReboot());\n      assertEquals(result, \"ami-246f8d4d\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=CreateImage&Name=name&InstanceId=instanceId&Description=description&NoReboot=true\");\n   }\n\n   public void registerImageFromManifestInRegion() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION, new MockResponse().setBody(\"<RegisterImageResponse><ImageId>ami-246f8d4d</ImageId></RegisterImageResponse>\"));\n\n      String result = amiApi().registerImageFromManifestInRegion(DEFAULT_REGION, \"name\", \"pathToManifest\");\n      assertEquals(result, \"ami-246f8d4d\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=RegisterImage&Name=name&ImageLocation=pathToManifest\");\n   }\n\n   public void registerImageFromManifestInRegion_options() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION, new MockResponse().setBody(\"<RegisterImageResponse><ImageId>ami-246f8d4d</ImageId></RegisterImageResponse>\"));\n\n      String result = amiApi().registerImageFromManifestInRegion(DEFAULT_REGION, \"name\", \"pathToManifest\",\n            new RegisterImageOptions().withDescription(\"description\"));\n      assertEquals(result, \"ami-246f8d4d\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=RegisterImage&Name=name&ImageLocation=pathToManifest&Description=description\");\n   }\n\n   public void registerUnixImageBackedByEbsInRegion() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION, new MockResponse()\n            .setBody(\"<RegisterImageResponse><ImageId>ami-246f8d4d</ImageId></RegisterImageResponse>\"));\n\n      String result = amiApi().registerUnixImageBackedByEbsInRegion(DEFAULT_REGION, \"imageName\", \"snapshotId\");\n      assertEquals(result, \"ami-246f8d4d\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=RegisterImage&RootDeviceName=/dev/sda1&BlockDeviceMapping.0.DeviceName=/dev/sda1&Name=imageName&BlockDeviceMapping.0.Ebs.SnapshotId=snapshotId\");\n   }\n\n   public void registerUnixImageBackedByEbsInRegion_options() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION, new MockResponse().setBody(\"<RegisterImageResponse><ImageId>ami-246f8d4d</ImageId></RegisterImageResponse>\"));\n\n      String result = amiApi().registerUnixImageBackedByEbsInRegion(DEFAULT_REGION, \"imageName\", \"snapshotId\",\n            new RegisterImageBackedByEbsOptions().withDescription(\"description\")\n                  .addBlockDeviceFromSnapshot(\"/dev/device\", null, \"snapshot\", false, \"gp2\", null, false)\n                  .addNewBlockDevice(\"/dev/newdevice\", \"newblock\", 100));\n      assertEquals(result, \"ami-246f8d4d\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=RegisterImage&RootDeviceName=/dev/sda1&BlockDeviceMapping.0.DeviceName=/dev/sda1&Name=imageName&BlockDeviceMapping.0.Ebs.SnapshotId=snapshotId&Description=description&BlockDeviceMapping.1.Ebs.DeleteOnTermination=false&BlockDeviceMapping.1.Ebs.VolumeType=gp2&BlockDeviceMapping.1.DeviceName=/dev/device&BlockDeviceMapping.1.Ebs.SnapshotId=snapshot&BlockDeviceMapping.2.Ebs.DeleteOnTermination=false&BlockDeviceMapping.2.DeviceName=/dev/newdevice&BlockDeviceMapping.2.VirtualName=newblock&BlockDeviceMapping.2.Ebs.VolumeSize=100\");\n   }\n\n   public void deregisterImageInRegion() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION, new MockResponse());\n\n      amiApi().deregisterImageInRegion(DEFAULT_REGION, \"ami-246f8d4d\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DeregisterImage&ImageId=ami-246f8d4d\");\n   }\n\n   public void getBlockDeviceMappingsForImageInRegion() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(DEFAULT_REGION, \"/describe_image_attribute_blockDeviceMapping.xml\");\n\n      Map<String, Image.EbsBlockDevice> result = amiApi()\n            .getBlockDeviceMappingsForImageInRegion(DEFAULT_REGION, \"ami-246f8d4d\");\n\n      assertFalse(result.isEmpty());\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeImageAttribute&Attribute=blockDeviceMapping&ImageId=ami-246f8d4d\");\n   }\n\n   public void getLaunchPermissionForImageInRegion() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(DEFAULT_REGION, \"/describe_image_attribute_launchPermission.xml\");\n\n      Permission result = amiApi().getLaunchPermissionForImageInRegion(DEFAULT_REGION, \"ami-246f8d4d\");\n\n      assertNotNull(result);\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeImageAttribute&Attribute=launchPermission&ImageId=ami-246f8d4d\");\n   }\n\n   public void addLaunchPermissionsToImageInRegion() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION, new MockResponse());\n\n      amiApi().addLaunchPermissionsToImageInRegion(DEFAULT_REGION, ImmutableList.of(\"bob\", \"sue\"),\n            ImmutableList.of(\"all\"), \"imageId\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=ModifyImageAttribute&OperationType=add&Attribute=launchPermission&ImageId=imageId&UserId.1=bob&UserId.2=sue&UserGroup.1=all\");\n   }\n\n   public void removeLaunchPermissionsFromImageInRegion() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION, new MockResponse());\n\n      amiApi().removeLaunchPermissionsFromImageInRegion(DEFAULT_REGION, ImmutableList.of(\"bob\", \"sue\"),\n            ImmutableList.of(\"all\"), \"imageId\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=ModifyImageAttribute&OperationType=remove&Attribute=launchPermission&ImageId=imageId&UserId.1=bob&UserId.2=sue&UserGroup.1=all\");\n   }\n\n   public void resetLaunchPermissionsOnImageInRegion() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION, new MockResponse());\n\n      amiApi().resetLaunchPermissionsOnImageInRegion(DEFAULT_REGION, \"imageId\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=ResetImageAttribute&Attribute=launchPermission&ImageId=imageId\");\n   }\n\n   public void getProductCodesForImageInRegion() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(DEFAULT_REGION, \"/describe_image_attribute_productCodes.xml\");\n\n      Set<String> result = amiApi().getProductCodesForImageInRegion(DEFAULT_REGION, \"ami-246f8d4d\");\n\n      assertFalse(result.isEmpty());\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeImageAttribute&Attribute=productCodes&ImageId=ami-246f8d4d\");\n   }\n\n   public void addProductCodesToImageInRegion() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION, new MockResponse());\n\n      amiApi().addProductCodesToImageInRegion(DEFAULT_REGION, ImmutableList.of(\"code1\", \"code2\"), \"imageId\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=ModifyImageAttribute&OperationType=add&Attribute=productCodes&ImageId=imageId&ProductCode.1=code1&ProductCode.2=code2\");\n   }\n\n   public void removeProductCodesFromImageInRegion() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION, new MockResponse());\n\n      amiApi().removeProductCodesFromImageInRegion(DEFAULT_REGION, ImmutableList.of(\"code1\", \"code2\"), \"imageId\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=ModifyImageAttribute&OperationType=remove&Attribute=productCodes&ImageId=imageId&ProductCode.1=code1&ProductCode.2=code2\");\n   }\n\n   private AWSAMIApi amiApi() {\n      return api().getAMIApi().get();\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/features/AWSElasticBlockStoreApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.features;\n\nimport static org.jclouds.ec2.options.CreateVolumeOptions.Builder.volumeType;\nimport static org.jclouds.ec2.options.CreateVolumeOptions.Builder.withSize;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.Properties;\nimport java.util.Set;\n\nimport com.google.common.collect.Sets;\nimport org.jclouds.Constants;\nimport org.jclouds.ec2.domain.Volume;\nimport org.jclouds.ec2.features.ElasticBlockStoreApiLiveTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code ElasticBlockStoreApi}\n */\n@Test(groups = \"live\", singleThreaded = true)\npublic class AWSElasticBlockStoreApiLiveTest extends ElasticBlockStoreApiLiveTest {\n\n   public AWSElasticBlockStoreApiLiveTest() {\n      provider = \"aws-ec2\";\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties overrides = super.setupProperties();\n      overrides.put(Constants.PROPERTY_API_VERSION, \"2014-05-01\");\n      return overrides;\n   }\n\n   @Test\n   void testCreateVolumeInAvailabilityZoneWithVolumeType() {\n      Volume expected = client.createVolumeInAvailabilityZone(defaultZone,\n              volumeType(\"gp2\"), withSize(1));\n      assertNotNull(expected);\n      assertEquals(expected.getAvailabilityZone(), defaultZone);\n      assertEquals(expected.getVolumeType(), \"gp2\");\n\n      Set<Volume> result = Sets.newLinkedHashSet(client.describeVolumesInRegion(defaultRegion, expected.getId()));\n      assertNotNull(result);\n      assertEquals(result.size(), 1);\n      Volume volume = result.iterator().next();\n      assertEquals(volume.getId(), expected.getId());\n      assertEquals(volume.getVolumeType(), expected.getVolumeType());\n\n      client.deleteVolumeInRegion(volume.getRegion(), volume.getId());\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/features/AWSInstanceApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.features;\n\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.Set;\n\nimport org.jclouds.aws.ec2.AWSEC2Api;\nimport org.jclouds.compute.internal.BaseComputeServiceContextLiveTest;\nimport org.jclouds.ec2.domain.Reservation;\nimport org.jclouds.ec2.domain.RunningInstance;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code AWSEC2Api}\n */\n@Test(groups = \"live\", singleThreaded = true)\npublic class AWSInstanceApiLiveTest extends BaseComputeServiceContextLiveTest {\n   public AWSInstanceApiLiveTest() {\n      provider = \"aws-ec2\";\n   }\n   \n   public static final String PREFIX = System.getProperty(\"user.name\") + \"-ec2\";\n\n   private AWSInstanceApi client;\n   \n   @Override\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   public void setupContext() {\n      super.setupContext();\n      client = view.unwrapApi(AWSEC2Api.class).getInstanceApi().get();\n   }\n\n   @Test\n   void testDescribeInstances() {\n      for (String region : view.unwrapApi(AWSEC2Api.class).getAvailabilityZoneAndRegionApi().get().describeRegions().keySet()) {\n         Set<? extends Reservation<? extends RunningInstance>> allResults = client.describeInstancesInRegion(region);\n         assertNotNull(allResults);\n         for (Reservation<? extends RunningInstance> result : allResults) {\n            assertNotNull(result.getReservationId());\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/features/AWSInstanceApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.features;\n\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport java.io.IOException;\nimport java.util.Map;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.aws.ec2.options.AWSRunInstancesOptions;\nimport org.jclouds.aws.ec2.options.Tenancy;\nimport org.jclouds.aws.ec2.xml.AWSDescribeInstancesResponseHandler;\nimport org.jclouds.aws.ec2.xml.AWSRunInstancesResponseHandler;\nimport org.jclouds.ec2.domain.BlockDevice;\nimport org.jclouds.ec2.domain.InstanceType;\nimport org.jclouds.ec2.domain.Volume.InstanceInitiatedShutdownBehavior;\nimport org.jclouds.ec2.options.RunInstancesOptions;\nimport org.jclouds.ec2.xml.BlockDeviceMappingHandler;\nimport org.jclouds.ec2.xml.BooleanValueHandler;\nimport org.jclouds.ec2.xml.InstanceInitiatedShutdownBehaviorHandler;\nimport org.jclouds.ec2.xml.InstanceStateChangeHandler;\nimport org.jclouds.ec2.xml.InstanceTypeHandler;\nimport org.jclouds.ec2.xml.StringValueHandler;\nimport org.jclouds.ec2.xml.UnencodeStringValueHandler;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.http.functions.ReleasePayloadAndReturn;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Lists;\nimport com.google.common.collect.Maps;\nimport com.google.common.reflect.Invokable;\n/**\n * Tests behavior of {@code AWSInstanceApi}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"AWSInstanceApiTest\")\npublic class AWSInstanceApiTest extends BaseAWSEC2ApiTest<AWSInstanceApi> {\n   public void testDescribeInstances() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AWSInstanceApi.class, \"describeInstancesInRegion\", String.class, String[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList((String) null));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, \"Action=DescribeInstances\", \"application/x-www-form-urlencoded\",\n            false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, AWSDescribeInstancesResponseHandler.class);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(request);\n   }\n\n   public void testDescribeInstancesArgs() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AWSInstanceApi.class, \"describeInstancesInRegion\", String.class, String[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"1\", \"2\"));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, \"Action=DescribeInstances&InstanceId.1=1&InstanceId.2=2\",\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, AWSDescribeInstancesResponseHandler.class);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(request);\n   }\n\n   public void testTerminateInstances() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AWSInstanceApi.class, \"terminateInstancesInRegion\", String.class, String[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"1\", \"2\"));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, \"Action=TerminateInstances&InstanceId.1=1&InstanceId.2=2\",\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, InstanceStateChangeHandler.class);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(request);\n   }\n\n   public void testRunInstances() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AWSInstanceApi.class, \"runInstancesInRegion\", String.class, String.class,\n            String.class, int.class, int.class, RunInstancesOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, null, \"ami-voo\", 1, 1));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, \"Action=RunInstances&ImageId=ami-voo&MinCount=1&MaxCount=1\",\n            \"application/x-www-form-urlencoded\", false);\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, AWSRunInstancesResponseHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testRunInstancesOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AWSInstanceApi.class, \"runInstancesInRegion\", String.class, String.class,\n            String.class, int.class, int.class, RunInstancesOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(\n            method,\n            Lists.<Object> newArrayList(\n                  \"us-east-1\",\n                  \"us-east-1a\",\n                  \"ami-voo\",\n                  1,\n                  5,\n                  new AWSRunInstancesOptions().withKernelId(\"kernelId\").enableMonitoring()\n                        .withSecurityGroups(\"group1\", \"group2\")\n                        .withTenancy(Tenancy.HOST).withDedicatedHostId(\"hostId\")));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(\n            request,\n            \"Action=RunInstances&ImageId=ami-voo&MinCount=1&MaxCount=5&KernelId=kernelId&Monitoring.Enabled=true&SecurityGroup.1=group1&SecurityGroup.2=group2&Placement.Tenancy=host&Placement.HostId=hostId&Placement.AvailabilityZone=us-east-1a\",\n            \"application/x-www-form-urlencoded\", false);\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, AWSRunInstancesResponseHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testStopInstances() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AWSInstanceApi.class, \"stopInstancesInRegion\", String.class, boolean.class,\n            String[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, true, \"1\", \"2\"));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, \"Action=StopInstances&Force=true&InstanceId.1=1&InstanceId.2=2\",\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, InstanceStateChangeHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testRebootInstances() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AWSInstanceApi.class, \"rebootInstancesInRegion\", String.class,\n            String[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"1\", \"2\"));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, \"Action=RebootInstances&InstanceId.1=1&InstanceId.2=2\",\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testStartInstances() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AWSInstanceApi.class, \"startInstancesInRegion\", String.class,\n            String[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"1\", \"2\"));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, \"Action=StartInstances&InstanceId.1=1&InstanceId.2=2\",\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, InstanceStateChangeHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testGetUserDataForInstanceInRegion() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AWSInstanceApi.class, \"getUserDataForInstanceInRegion\", String.class,\n            String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"1\"));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request,\n            \"Action=DescribeInstanceAttribute&Attribute=userData&InstanceId=1\",\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, UnencodeStringValueHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testGetRootDeviceNameForInstanceInRegion() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AWSInstanceApi.class, \"getRootDeviceNameForInstanceInRegion\", String.class,\n            String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"1\"));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request,\n            \"Action=DescribeInstanceAttribute&Attribute=rootDeviceName&InstanceId=1\",\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, StringValueHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testGetRamdiskForInstanceInRegion() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AWSInstanceApi.class, \"getRamdiskForInstanceInRegion\", String.class,\n            String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"1\"));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request,\n            \"Action=DescribeInstanceAttribute&Attribute=ramdisk&InstanceId=1\",\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, StringValueHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testGetDisableApiTerminationForInstanceInRegion() throws SecurityException, NoSuchMethodException,\n         IOException {\n      Invokable<?, ?> method = method(AWSInstanceApi.class, \"isApiTerminationDisabledForInstanceInRegion\",\n            String.class, String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"1\"));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request,\n            \"Action=DescribeInstanceAttribute&Attribute=disableApiTermination&InstanceId=1\",\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, BooleanValueHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testGetKernelForInstanceInRegion() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AWSInstanceApi.class, \"getKernelForInstanceInRegion\", String.class, String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"1\"));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, \"Action=DescribeInstanceAttribute&Attribute=kernel&InstanceId=1\",\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, StringValueHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testGetInstanceTypeForInstanceInRegion() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AWSInstanceApi.class, \"getInstanceTypeForInstanceInRegion\", String.class,\n            String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"1\"));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request,\n            \"Action=DescribeInstanceAttribute&Attribute=instanceType&InstanceId=1\",\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, InstanceTypeHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testGetInstanceInitiatedShutdownBehaviorForInstanceInRegion() throws SecurityException,\n         NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AWSInstanceApi.class, \"getInstanceInitiatedShutdownBehaviorForInstanceInRegion\",\n            String.class, String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"1\"));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(\n            request,\n            \"Action=DescribeInstanceAttribute&Attribute=instanceInitiatedShutdownBehavior&InstanceId=1\",\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, InstanceInitiatedShutdownBehaviorHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testGetBlockDeviceMappingForInstanceInRegion() throws SecurityException, NoSuchMethodException,\n         IOException {\n      Invokable<?, ?> method = method(AWSInstanceApi.class, \"getBlockDeviceMappingForInstanceInRegion\", String.class,\n            String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"1\"));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request,\n            \"Action=DescribeInstanceAttribute&Attribute=blockDeviceMapping&InstanceId=1\",\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, BlockDeviceMappingHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   HttpRequest setUserDataForInstance = HttpRequest.builder().method(\"POST\")\n                                                   .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                                                   .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                                                   .addFormParam(\"Action\", \"ModifyInstanceAttribute\")\n                                                   .addFormParam(\"Attribute\", \"userData\")\n                                                   .addFormParam(\"InstanceId\", \"1\")\n                                                   .addFormParam(\"Value\", \"dGVzdA==\").build();\n\n   public void testSetUserDataForInstanceInRegion() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AWSInstanceApi.class, \"setUserDataForInstanceInRegion\", String.class, String.class,\n               byte[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"1\", \"test\".getBytes()));\n\n      request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, filter.filter(setUserDataForInstance).getPayload().getRawContent().toString(),\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   HttpRequest setRamdiskForInstance = HttpRequest.builder().method(\"POST\")\n                                                  .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                                                  .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                                                  .addFormParam(\"Action\", \"ModifyInstanceAttribute\")\n                                                  .addFormParam(\"Attribute\", \"ramdisk\")\n                                                  .addFormParam(\"InstanceId\", \"1\")\n                                                  .addFormParam(\"Value\", \"test\").build();\n\n   public void testSetRamdiskForInstanceInRegion() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AWSInstanceApi.class, \"setRamdiskForInstanceInRegion\", String.class, String.class,\n               String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"1\", \"test\"));\n\n      request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, filter.filter(setRamdiskForInstance).getPayload().getRawContent().toString(),\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   HttpRequest setKernelForInstance = HttpRequest.builder().method(\"POST\")\n                                                 .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                                                 .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                                                 .addFormParam(\"Action\", \"ModifyInstanceAttribute\")\n                                                 .addFormParam(\"Attribute\", \"kernel\")\n                                                 .addFormParam(\"InstanceId\", \"1\")\n                                                 .addFormParam(\"Value\", \"test\").build();\n\n   public void testSetKernelForInstanceInRegion() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AWSInstanceApi.class, \"setKernelForInstanceInRegion\", String.class, String.class,\n               String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"1\", \"test\"));\n\n      request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, filter.filter(setKernelForInstance).getPayload().getRawContent().toString(),\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   HttpRequest setApiTerminationDisabled = HttpRequest.builder().method(\"POST\")\n                                                      .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                                                      .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                                                      .addFormParam(\"Action\", \"ModifyInstanceAttribute\")\n                                                      .addFormParam(\"Attribute\", \"disableApiTermination\")\n                                                      .addFormParam(\"InstanceId\", \"1\")\n                                                      .addFormParam(\"Value\", \"true\").build();\n\n   public void testSetApiTerminationDisabledForInstanceInRegion() throws SecurityException, NoSuchMethodException,\n            IOException {\n      Invokable<?, ?> method = method(AWSInstanceApi.class, \"setApiTerminationDisabledForInstanceInRegion\", String.class,\n               String.class, boolean.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"1\", true));\n\n      request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, filter.filter(setApiTerminationDisabled).getPayload().getRawContent().toString(),\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   HttpRequest instanceTypeForInstance = HttpRequest.builder().method(\"POST\")\n                                                    .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                                                    .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                                                    .addFormParam(\"Action\", \"ModifyInstanceAttribute\")\n                                                    .addFormParam(\"Attribute\", \"instanceType\")\n                                                    .addFormParam(\"InstanceId\", \"1\")\n                                                    .addFormParam(\"Value\", \"c1.medium\").build();\n\n   public void testSetInstanceTypeForInstanceInRegion() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AWSInstanceApi.class, \"setInstanceTypeForInstanceInRegion\", String.class,\n               String.class, String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"1\", InstanceType.C1_MEDIUM));\n\n      request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, filter.filter(instanceTypeForInstance).getPayload().getRawContent().toString(),\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   HttpRequest setInstanceInitiatedShutdownBehavior = HttpRequest.builder().method(\"POST\")\n                                                                 .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                                                                 .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                                                                 .addFormParam(\"Action\", \"ModifyInstanceAttribute\")\n                                                                 .addFormParam(\"Attribute\", \"instanceInitiatedShutdownBehavior\")\n                                                                 .addFormParam(\"InstanceId\", \"1\")\n                                                                 .addFormParam(\"Value\", \"terminate\").build();\n\n   public void testSetInstanceInitiatedShutdownBehaviorForInstanceInRegion() throws SecurityException,\n            NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AWSInstanceApi.class, \"setInstanceInitiatedShutdownBehaviorForInstanceInRegion\",\n               String.class, String.class, InstanceInitiatedShutdownBehavior.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"1\", InstanceInitiatedShutdownBehavior.TERMINATE));\n\n      request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, filter.filter(setInstanceInitiatedShutdownBehavior).getPayload().getRawContent()\n            .toString(), \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   HttpRequest setBlockDeviceMapping = HttpRequest.builder().method(\"POST\")\n                                                           .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                                                           .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                                                           .addFormParam(\"Action\", \"ModifyInstanceAttribute\")\n                                                           .addFormParam(\"BlockDeviceMapping.1.DeviceName\", \"/dev/sda1\")\n                                                           .addFormParam(\"BlockDeviceMapping.1.Ebs.DeleteOnTermination\", \"true\")\n                                                           .addFormParam(\"BlockDeviceMapping.1.Ebs.VolumeId\", \"vol-test1\")\n                                                           .addFormParam(\"InstanceId\", \"1\").build();\n\n   public void testSetBlockDeviceMappingForInstanceInRegion() throws SecurityException, NoSuchMethodException,\n         IOException {\n      Invokable<?, ?> method = method(AWSInstanceApi.class, \"setBlockDeviceMappingForInstanceInRegion\", String.class,\n            String.class, Map.class);\n\n      Map<String, BlockDevice> mapping = Maps.newLinkedHashMap();\n      mapping.put(\"/dev/sda1\", new BlockDevice(\"vol-test1\", true));\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"1\", mapping));\n\n      request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, filter.filter(setBlockDeviceMapping).getPayload().getRawContent().toString(),\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/features/AWSKeyPairApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.features;\n\nimport static com.google.common.collect.Iterables.get;\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static com.google.common.collect.Sets.newTreeSet;\nimport static org.jclouds.compute.options.TemplateOptions.Builder.overrideLoginCredentials;\nimport static org.jclouds.compute.predicates.NodePredicates.inGroup;\nimport static org.jclouds.compute.predicates.NodePredicates.runningInGroup;\nimport static org.jclouds.scriptbuilder.domain.Statements.exec;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.fail;\n\nimport java.io.FileNotFoundException;\nimport java.io.IOException;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.SortedSet;\n\nimport org.jclouds.aws.domain.Region;\nimport org.jclouds.aws.ec2.AWSEC2Api;\nimport org.jclouds.aws.ec2.compute.AWSEC2TemplateOptions;\nimport org.jclouds.aws.ec2.domain.AWSRunningInstance;\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.compute.ComputeTestUtils;\nimport org.jclouds.compute.domain.ExecResponse;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.internal.BaseComputeServiceContextLiveTest;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.ec2.domain.KeyPair;\nimport org.jclouds.ec2.domain.Reservation;\nimport org.jclouds.logging.log4j.config.Log4JLoggingModule;\nimport org.jclouds.sshj.config.SshjSshClientModule;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n/**\n * Tests behavior of {@code AWSKeyPairApi}\n */\n@Test(groups = \"live\", singleThreaded = true)\npublic class AWSKeyPairApiLiveTest extends BaseComputeServiceContextLiveTest {\n   public AWSKeyPairApiLiveTest() {\n      provider = \"aws-ec2\";\n   }\n\n   private AWSKeyPairApi client;\n   \n   @Override\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   public void setupContext() {\n      super.setupContext();\n      client = view.unwrapApi(AWSEC2Api.class).getKeyPairApi().get();\n   }\n\n   public void testNoSsh() throws Exception {\n\n      Map<String, String> keyPair = ComputeTestUtils.setupKeyPair();\n\n      AWSInstanceApi instanceApi = view.unwrapApi(AWSEC2Api.class).getInstanceApi().get();\n\n      String group = PREFIX + \"unssh\";\n      view.getComputeService().destroyNodesMatching(inGroup(group));\n\n      TemplateOptions options = view.getComputeService().templateOptions();\n\n      options.authorizePublicKey(keyPair.get(\"public\")).as(AWSEC2TemplateOptions.class);\n\n      ComputeServiceContext noSshContext = null;\n      try {\n         noSshContext = createView(setupProperties(), ImmutableSet.<Module> of(new Log4JLoggingModule()));\n\n         Set<? extends NodeMetadata> nodes = noSshContext.getComputeService().createNodesInGroup(group, 1, options);\n\n         NodeMetadata first = get(nodes, 0);\n         assert first.getCredentials() != null : first;\n         assert first.getCredentials().identity != null : first;\n         // credentials should not be present as the import public key call doesn't have access to\n         // the related private key\n         assert first.getCredentials().credential == null : first;\n\n         AWSRunningInstance instance = getInstance(instanceApi, first.getProviderId());\n\n         assertEquals(instance.getKeyName(), \"jclouds#\" + group);\n\n         Map<? extends NodeMetadata, ExecResponse> responses = view.getComputeService()\n               .runScriptOnNodesMatching(\n                     runningInGroup(group),\n                     exec(\"echo hello\"),\n                     overrideLoginCredentials(\n                           LoginCredentials.builder().user(first.getCredentials().identity)\n                                 .privateKey(keyPair.get(\"private\")).build()).wrapInInitScript(false).runAsRoot(false));\n\n         ExecResponse hello = getOnlyElement(responses.values());\n         assertEquals(hello.getOutput().trim(), \"hello\");\n\n      } finally {\n         noSshContext.close();\n         view.getComputeService().destroyNodesMatching(inGroup(group));\n      }\n   }\n\n   @Test\n   void testDescribeAWSKeyPairs() {\n      for (String region : Region.DEFAULT_REGIONS) {\n\n         SortedSet<KeyPair> allResults = newTreeSet(client.describeKeyPairsInRegion(region));\n         assertNotNull(allResults);\n         if (allResults.size() >= 1) {\n            KeyPair pair = allResults.last();\n            SortedSet<KeyPair> result = newTreeSet(client.describeKeyPairsInRegion(region, pair.getKeyName()));\n            assertNotNull(result);\n            KeyPair compare = result.last();\n            assertEquals(compare, pair);\n         }\n      }\n   }\n\n   public static final String PREFIX = System.getProperty(\"user.name\") + \"-ec2\";\n\n   @Test\n   void testCreateKeyPair() {\n      String keyName = PREFIX + \"1\";\n      cleanupKeyPair(keyName);\n      try {\n         KeyPair keyPair = client.createKeyPairInRegion(null, keyName);\n         checkKeyPair(keyName, keyPair);\n         assertNotNull(keyPair.getKeyMaterial());\n      } finally {\n         cleanupKeyPair(keyName);\n      }\n   }\n\n   protected void cleanupKeyPair(String keyName) {\n      try {\n         client.deleteKeyPairInRegion(null, keyName);\n      } catch (Exception e) {\n\n      }\n      client.deleteKeyPairInRegion(null, keyName);\n   }\n\n   @Test\n   void testImportKeyPair() throws FileNotFoundException, IOException {\n      String keyName = PREFIX + \"2\";\n      cleanupKeyPair(keyName);\n      Map<String, String> myKey = ComputeTestUtils.setupKeyPair();\n      try {\n         KeyPair keyPair = client.importKeyPairInRegion(null, keyName, myKey.get(\"public\"));\n         checkKeyPair(keyName, keyPair);\n         // TODO generate correct fingerprint and check\n         // assertEquals(keyPair.getKeyFingerprint(),\n         // CryptoStreams.hex(CryptoStreams.md5(myKey.get(\"public\").getBytes())));\n\n         // try again to see if there's an error\n         try {\n            client.importKeyPairInRegion(null, keyName, myKey.get(\"public\"));\n            fail(\"Expected IllegalStateException\");\n         } catch (IllegalStateException e) {\n\n         }\n      } finally {\n         cleanupKeyPair(keyName);\n      }\n   }\n\n   protected void checkKeyPair(String keyName, KeyPair keyPair) {\n      assertNotNull(keyPair);\n      assertNotNull(keyPair.getSha1OfPrivateKey());\n      assertEquals(keyPair.getKeyName(), keyName);\n\n      Set<KeyPair> twoResults = client.describeKeyPairsInRegion(null, keyName);\n      assertNotNull(twoResults);\n      assertEquals(twoResults.size(), 1);\n      KeyPair listPair = twoResults.iterator().next();\n      assertEquals(listPair.getKeyName(), keyPair.getKeyName());\n      assertEquals(listPair.getSha1OfPrivateKey(), keyPair.getSha1OfPrivateKey());\n   }\n\n   protected AWSRunningInstance getInstance(AWSInstanceApi instanceApi, String id) {\n      Reservation<? extends AWSRunningInstance> reservation = getOnlyElement(instanceApi.describeInstancesInRegion(null, id));\n      return getOnlyElement(reservation);\n   }\n   \n   @Override\n   protected Module getSshModule() {\n      return new SshjSshClientModule();\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/features/AWSKeyPairApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.features;\n\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport java.io.IOException;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.ec2.xml.DescribeKeyPairsResponseHandler;\nimport org.jclouds.ec2.xml.KeyPairResponseHandler;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.http.functions.ReleasePayloadAndReturn;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Lists;\nimport com.google.common.reflect.Invokable;\n/**\n * Tests behavior of {@code AWSKeyPairApi}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"AWSKeyPairApiTest\")\npublic class AWSKeyPairApiTest extends BaseAWSEC2ApiTest<AWSKeyPairApi> {\n\n   public void testCreateKeyPair() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AWSKeyPairApi.class, \"createKeyPairInRegion\", String.class, String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"mykey\"));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, \"Action=CreateKeyPair&KeyName=mykey\",\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, KeyPairResponseHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   HttpRequest importKeyPair = HttpRequest.builder().method(\"POST\")\n                                          .endpoint(\"https://ec2.us-east-1.amazonaws.com/\")\n                                          .addHeader(\"Host\", \"ec2.us-east-1.amazonaws.com\")\n                                          .addFormParam(\"Action\", \"ImportKeyPair\")\n                                          .addFormParam(\"KeyName\", \"mykey\")\n                                          .addFormParam(\"PublicKeyMaterial\", \"c3NoLXJzYSBBQQ==\").build();\n\n   public void testImportKeyPair() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AWSKeyPairApi.class, \"importKeyPairInRegion\", String.class, String.class,\n            String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"mykey\", \"ssh-rsa AA\"));\n\n      request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, filter.filter(importKeyPair).getPayload().getRawContent().toString(),\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, KeyPairResponseHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testDeleteKeyPair() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AWSKeyPairApi.class, \"deleteKeyPairInRegion\", String.class, String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"mykey\"));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, \"Action=DeleteKeyPair&KeyName=mykey\",\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testDescribeKeyPairs() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AWSKeyPairApi.class, \"describeKeyPairsInRegion\", String.class,\n            String[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList((String) null));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, \"Action=DescribeKeyPairs\", \"application/x-www-form-urlencoded\",\n            false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, DescribeKeyPairsResponseHandler.class);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(request);\n   }\n\n   public void testDescribeKeyPairsArgs() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AWSKeyPairApi.class, \"describeKeyPairsInRegion\", String.class,\n            String[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"1\", \"2\"));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, \"Action=DescribeKeyPairs&KeyName.1=1&KeyName.2=2\",\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, DescribeKeyPairsResponseHandler.class);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(request);\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/features/AWSSecurityGroupApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.Random;\nimport java.util.Set;\n\nimport org.jclouds.aws.ec2.AWSEC2Api;\nimport org.jclouds.aws.ec2.domain.VPC;\nimport org.jclouds.aws.ec2.options.CreateSecurityGroupOptions;\nimport org.jclouds.aws.ec2.options.CreateVpcOptions;\nimport org.jclouds.ec2.EC2Api;\nimport org.jclouds.ec2.domain.SecurityGroup;\nimport org.jclouds.ec2.domain.UserIdGroupPair;\nimport org.jclouds.ec2.features.SecurityGroupApiLiveTest;\nimport org.jclouds.ec2.util.IpPermissions;\nimport org.jclouds.net.domain.IpPermission;\nimport org.jclouds.net.domain.IpProtocol;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.Iterables;\n\n@Test(groups = \"live\", singleThreaded = true)\npublic class AWSSecurityGroupApiLiveTest extends SecurityGroupApiLiveTest {\n   public AWSSecurityGroupApiLiveTest() {\n      provider = \"aws-ec2\";\n   }\n\n   @Test\n   void testAuthorizeSecurityGroupIngressSourceGroup() {\n      final String group1Name = PREFIX + \"ingress1\";\n      String group2Name = PREFIX + \"ingress2\";\n      cleanupAndSleep(group2Name);\n      cleanupAndSleep(group1Name);\n      try {\n         final String group1Id = AWSSecurityGroupApi.class.cast(client).createSecurityGroupInRegionAndReturnId(null,\n                 group1Name, group1Name);\n         String group2Id = AWSSecurityGroupApi.class.cast(client).createSecurityGroupInRegionAndReturnId(null,\n                 group2Name, group2Name);\n         ensureGroupsExist(group1Name, group2Name);\n         client.authorizeSecurityGroupIngressInRegion(null, group1Name, IpProtocol.TCP, 80, 80, \"0.0.0.0/0\");\n         assertEventually(new GroupHasPermission(client, group1Name, new TCPPort80AllIPs()));\n         Set<SecurityGroup> oneResult = client.describeSecurityGroupsInRegion(null, group1Name);\n         assertNotNull(oneResult);\n         assertEquals(oneResult.size(), 1);\n         final SecurityGroup group = oneResult.iterator().next();\n         assertEquals(group.getName(), group1Name);\n         final UserIdGroupPair to = new UserIdGroupPair(group.getOwnerId(), group1Name);\n         client.authorizeSecurityGroupIngressInRegion(null, group2Name, to);\n         assertEventually(new GroupHasPermission(client, group2Name, new Predicate<IpPermission>() {\n            @Override\n            public boolean apply(IpPermission arg0) {\n               return arg0.getTenantIdGroupNamePairs().equals(ImmutableMultimap.of(group.getOwnerId(), group1Id));\n            }\n         }));\n\n         client.revokeSecurityGroupIngressInRegion(null, group2Name,\n                 new UserIdGroupPair(group.getOwnerId(), group1Name));\n         assertEventually(new GroupHasNoPermissions(client, group2Name));\n      } finally {\n         client.deleteSecurityGroupInRegion(null, group2Name);\n         client.deleteSecurityGroupInRegion(null, group1Name);\n      }\n   }\n\n   @Test\n   void testAuthorizeSecurityGroupIngressIpPermission() throws InterruptedException {\n      final String group1Name = PREFIX + \"ingress11\";\n      String group2Name = PREFIX + \"ingress12\";\n      cleanupAndSleep(group2Name);\n      cleanupAndSleep(group1Name);\n      try {\n         final String group1Id = AWSSecurityGroupApi.class.cast(client).createSecurityGroupInRegionAndReturnId(null,\n               group1Name, group1Name);\n         final String group2Id = AWSSecurityGroupApi.class.cast(client).createSecurityGroupInRegionAndReturnId(null,\n               group2Name, group2Name);\n         Thread.sleep(100);  // eventual consistent\n         ensureGroupsExist(group1Name, group2Name);\n         AWSSecurityGroupApi.class.cast(client).authorizeSecurityGroupIngressInRegion(null, group1Id,\n               IpPermissions.permit(IpProtocol.TCP).port(80));\n         assertEventually(new GroupHasPermission(client, group1Name, new TCPPort80AllIPs()));\n         Set<SecurityGroup> oneResult = client.describeSecurityGroupsInRegion(null, group1Name);\n         assertNotNull(oneResult);\n         assertEquals(oneResult.size(), 1);\n         final SecurityGroup group = oneResult.iterator().next();\n         assertEquals(group.getName(), group1Name);\n         IpPermissions group2CanHttpGroup1 = IpPermissions.permit(IpProtocol.TCP).port(80)\n               .originatingFromSecurityGroupId(group1Id);\n         AWSSecurityGroupApi.class.cast(client).authorizeSecurityGroupIngressInRegion(null, group2Id,\n               group2CanHttpGroup1);\n         assertEventually(new GroupHasPermission(client, group2Name, new Predicate<IpPermission>() {\n            @Override\n            public boolean apply(IpPermission arg0) {\n               return arg0.getTenantIdGroupNamePairs().equals(ImmutableMultimap.of(group.getOwnerId(), group1Id))\n                     && arg0.getFromPort() == 80 && arg0.getToPort() == 80 && arg0.getIpProtocol() == IpProtocol.TCP;\n            }\n         }));\n\n         AWSSecurityGroupApi.class.cast(client).revokeSecurityGroupIngressInRegion(null, group2Id,\n               group2CanHttpGroup1);\n         assertEventually(new GroupHasNoPermissions(client, group2Name));\n      } finally {\n         client.deleteSecurityGroupInRegion(null, group2Name);\n         client.deleteSecurityGroupInRegion(null, group1Name);\n      }\n   }\n\n   @Override\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   public void setupContext() {\n      super.setupContext();\n      ec2Api = view.unwrapApi(EC2Api.class);\n      client = ec2Api.getSecurityGroupApi().get();\n   }\n\n   @Test\n   void testCreateSecurityGroupInVpc() {\n      String region = \"us-west-2\";\n      String groupName = PREFIX + \"1\" + new Random().nextInt(10000);\n      String description = \"jclouds testCreateSecurityGroupInVpc\";\n      \n      VPCApi vpcClient = AWSEC2Api.class.cast(ec2Api).getVPCApi().get();\n      AWSSecurityGroupApi sgClient = AWSSecurityGroupApi.class.cast(client);\n\n      VPC vpc = vpcClient.createVpc(region, \"10.0.0.0/16\", CreateVpcOptions.NONE);\n      try {\n         String sgId = sgClient.createSecurityGroupInRegionAndReturnId(\n               region, groupName, description, CreateSecurityGroupOptions.Builder.vpcId(vpc.id()));\n\n         try {\n            Set<SecurityGroup> securityGroups = sgClient.describeSecurityGroupsInRegionWithFilter(\n                  region, ImmutableMultimap.of(\"vpc-id\", vpc.id(), \"group-id\", sgId));\n            SecurityGroup sg = Iterables.getOnlyElement(securityGroups);\n            assertEquals(sg.getId(), sgId);\n            assertEquals(sg.getId(), sgId);\n         } finally {\n            sgClient.deleteSecurityGroupInRegionById(region, sgId);\n         }\n      } finally {\n         vpcClient.deleteVpc(region, vpc.id());\n      }\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/features/AWSSecurityGroupApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.features;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Set;\n\nimport okhttp3.mockwebserver.MockResponse;\n\nimport org.jclouds.aws.ec2.internal.BaseAWSEC2ApiMockTest;\nimport org.jclouds.aws.ec2.options.CreateSecurityGroupOptions;\nimport org.jclouds.ec2.domain.SecurityGroup;\nimport org.jclouds.net.domain.IpPermission;\nimport org.jclouds.net.domain.IpProtocol;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Joiner;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\n\n@Test(groups = \"unit\", testName = \"AWSSecurityGroupApiMockTest\", singleThreaded = true)\npublic class AWSSecurityGroupApiMockTest extends BaseAWSEC2ApiMockTest {\n\n   private final String describeSecurityGroupsResponse = Joiner.on(\"\\n\").join(\n         \"<DescribeSecurityGroupsResponse xmlns=\\\"http://ec2.amazonaws.com/doc/2016-11-15/\\\">\",\n         \"  <requestId>59dbff89-35bd-4eac-99ed-be587EXAMPLE</requestId>\",\n         \"  <securityGroupInfo>\",\n         \"    <item>\",\n         \"      <ownerId>123456789012</ownerId>\",\n         \"      <groupId>sg-1a2b3c4d</groupId>\",\n         \"      <groupName>WebServers</groupName>\",\n         \"      <groupDescription>Web Servers</groupDescription>\",\n         \"      <vpcId>vpc-614cc409</vpcId>\",\n         \"      <ipPermissions>\",\n         \"        <item>\",\n         \"          <ipProtocol>-1</ipProtocol>\",\n         \"          <groups>\",\n         \"            <item>\",\n         \"              <userId>123456789012</userId>\",\n         \"              <groupId>sg-af8661c0</groupId>\",\n         \"            </item>\",\n         \"          </groups>\",\n         \"          <ipRanges/>\",\n         \"          <prefixListIds/>\",\n         \"        </item>\",\n         \"        <item>\",\n         \"          <ipProtocol>tcp</ipProtocol>\",\n         \"          <fromPort>22</fromPort>\",\n         \"          <toPort>22</toPort>\",\n         \"          <groups/>\",\n         \"          <ipRanges>\",\n         \"            <item>\",\n         \"              <cidrIp>204.246.162.38/32</cidrIp>\",\n         \"            </item>\",\n         \"          </ipRanges>\",\n         \"          <prefixListIds/>\",\n         \"        </item>\",\n         \"      </ipPermissions>\",\n         \"      <ipPermissionsEgress>\",\n         \"        <item>\",\n         \"          <ipProtocol>-1</ipProtocol>\",\n         \"          <groups/>\",\n         \"          <ipRanges>\",\n         \"            <item>\",\n         \"              <cidrIp>0.0.0.0/0</cidrIp>\",\n         \"            </item>\",\n         \"          </ipRanges>\",\n         \"          <prefixListIds/>\",\n         \"        </item>\",\n         \"      </ipPermissionsEgress>\",\n         \"    </item>\",\n         \"  </securityGroupInfo>\",\n         \"</DescribeSecurityGroupsResponse>\");\n\n   private final String createSecurityGroupResponse = Joiner.on(\"\\n\").join(\n         \"<CreateSecurityGroupResponse xmlns=\\\"http://ec2.amazonaws.com/doc/2016-11-15/\\\">\",\n         \"  <requestId>59dbff89-35bd-4eac-99ed-be587EXAMPLE</requestId>\",\n         \"  <return>true</return>\",\n         \"  <groupId>sg-0a42d66a</groupId>\",\n         \"</CreateSecurityGroupResponse>\");\n\n   private final String authorizeSecurityGroupIngressResponse = Joiner.on(\"\\n\").join(\n            \"<AuthorizeSecurityGroupIngressResponse xmlns=\\\"http://ec2.amazonaws.com/doc/2016-11-15/\\\">\",\n            \"  <requestId>59dbff89-35bd-4eac-99ed-be587EXAMPLE</requestId>\",\n            \"  <return>true</return>\",\n            \"</AuthorizeSecurityGroupIngressResponse>\");\n\n   private final String revokeSecurityGroupIngressResponse = Joiner.on(\"\\n\").join(\n         \"<RevokeSecurityGroupIngressResponse xmlns=\\\"http://ec2.amazonaws.com/doc/2016-11-15/\\\">\",\n         \"  <requestId>59dbff89-35bd-4eac-99ed-be587EXAMPLE</requestId>\",\n         \"  <return>true</return>\",\n         \"</RevokeSecurityGroupIngressResponse>\");\n\n   private final String deleteSecurityGroupResponse = Joiner.on(\"\\n\").join(\n         \"<DeleteSecurityGroupResponse xmlns=\\\"http://ec2.amazonaws.com/doc/2016-11-15/\\\">\",\n         \"  <requestId>59dbff89-35bd-4eac-99ed-be587EXAMPLE</requestId>\",\n         \"  <return>true</return>\",\n         \"</DeleteSecurityGroupResponse>\");\n\n   @SuppressWarnings(\"deprecation\")\n   public void describeSecurityGroups() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION, new MockResponse().setBody(describeSecurityGroupsResponse));\n\n      Set<SecurityGroup> results = securityGroupApi().describeSecurityGroupsInRegion(DEFAULT_REGION);\n      SecurityGroup result = Iterables.getOnlyElement(results);\n      assertEquals(result.getId(), \"sg-1a2b3c4d\");\n      assertEquals(result.getRegion(), \"us-east-1\");\n      assertEquals(result.getName(), \"WebServers\");\n      assertEquals(result.getOwnerId(), \"123456789012\");\n      assertEquals(result.getDescription(), \"Web Servers\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeSecurityGroups\");\n   }\n\n   public void describeSecurityGroupsGiving404() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION, new MockResponse().setResponseCode(404));\n\n      Set<SecurityGroup> results = securityGroupApi().describeSecurityGroupsInRegion(DEFAULT_REGION);\n      assertEquals(results, ImmutableSet.of());\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeSecurityGroups\");\n   }\n\n   public void describeSecurityGroupsById() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION, new MockResponse().setBody(describeSecurityGroupsResponse));\n\n      Set<SecurityGroup> results = securityGroupApi().describeSecurityGroupsInRegionById(DEFAULT_REGION, \"sg-1a2b3c4d\");\n      SecurityGroup result = Iterables.getOnlyElement(results);\n      assertEquals(result.getId(), \"sg-1a2b3c4d\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeSecurityGroups&GroupId.1=sg-1a2b3c4d\");\n   }\n\n   public void describeSecurityGroupsByName() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION, new MockResponse().setBody(describeSecurityGroupsResponse));\n\n      Set<SecurityGroup> results = securityGroupApi().describeSecurityGroupsInRegion(DEFAULT_REGION, \"WebServers\");\n      SecurityGroup result = Iterables.getOnlyElement(results);\n      assertEquals(result.getId(), \"sg-1a2b3c4d\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeSecurityGroups&GroupName.1=WebServers\");\n   }\n\n   public void describeSecurityGroupsFiltered() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION, new MockResponse().setBody(describeSecurityGroupsResponse));\n\n      Set<SecurityGroup> results = securityGroupApi().describeSecurityGroupsInRegionWithFilter(DEFAULT_REGION, \n            ImmutableMultimap.of(\"group-name\", \"WebServers\", \"vpc-id\", \"vpc-614cc409\"));\n      SecurityGroup result = Iterables.getOnlyElement(results);\n      assertEquals(result.getId(), \"sg-1a2b3c4d\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeSecurityGroups&Filter.1.Name=group-name&Filter.1.Value.1=WebServers&Filter.2.Name=vpc-id&Filter.2.Value.1=vpc-614cc409\");\n   }\n\n   public void describeSecurityGroupsDifferentRegion() throws Exception {\n      String region = \"us-west-2\";\n      enqueueRegions(DEFAULT_REGION, region);\n      enqueue(region, new MockResponse().setBody(describeSecurityGroupsResponse));\n\n      Set<SecurityGroup> results = securityGroupApi().describeSecurityGroupsInRegion(region);\n      SecurityGroup result = Iterables.getOnlyElement(results);\n      assertEquals(result.getId(), \"sg-1a2b3c4d\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(region, \"Action=DescribeSecurityGroups\");\n   }\n\n   public void createSecurityGroupsInRegionAndReturnId() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION, new MockResponse().setBody(createSecurityGroupResponse));\n\n      String result = securityGroupApi().createSecurityGroupInRegionAndReturnId(DEFAULT_REGION, \"WebServers\", \"Web Servers\", CreateSecurityGroupOptions.Builder.vpcId(\"vpc-614cc409\"));\n      assertEquals(result, \"sg-0a42d66a\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=CreateSecurityGroup&GroupName=WebServers&GroupDescription=Web%20Servers&VpcId=vpc-614cc409\");\n   }\n\n   public void authorizeSecurityGroupIngress() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION, new MockResponse().setBody(authorizeSecurityGroupIngressResponse));\n\n      IpPermission perm = IpPermission.builder().ipProtocol(IpProtocol.TCP).cidrBlock(\"0.0.0.0/0\")\n            .fromPort(8080).toPort(8080).build();\n      securityGroupApi().authorizeSecurityGroupIngressInRegion(DEFAULT_REGION, \"sg-1a2b3c4d\", perm);\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=AuthorizeSecurityGroupIngress&GroupId=sg-1a2b3c4d&IpPermissions.0.IpProtocol=tcp&IpPermissions.0.FromPort=8080&IpPermissions.0.ToPort=8080&IpPermissions.0.IpRanges.0.CidrIp=0.0.0.0/0\");\n   }\n\n   public void authorizeSecurityGroupIngressList() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION, new MockResponse().setBody(authorizeSecurityGroupIngressResponse));\n\n      IpPermission perm = IpPermission.builder().ipProtocol(IpProtocol.TCP).cidrBlock(\"0.0.0.0/0\")\n            .fromPort(8080).toPort(8080).build();\n      IpPermission perm2 = IpPermission.builder().ipProtocol(IpProtocol.TCP).cidrBlock(\"0.0.0.0/0\")\n            .fromPort(8443).toPort(8443).build();\n      securityGroupApi().authorizeSecurityGroupIngressInRegion(DEFAULT_REGION, \"sg-1a2b3c4d\", ImmutableList.of(perm, perm2));\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=AuthorizeSecurityGroupIngress&GroupId=sg-1a2b3c4d&IpPermissions.0.IpProtocol=tcp&IpPermissions.0.FromPort=8080&IpPermissions.0.ToPort=8080&IpPermissions.0.IpRanges.0.CidrIp=0.0.0.0/0&IpPermissions.1.IpProtocol=tcp&IpPermissions.1.FromPort=8443&IpPermissions.1.ToPort=8443&IpPermissions.1.IpRanges.0.CidrIp=0.0.0.0/0\");\n   }\n\n   public void revokeSecurityGroupIngress() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION, new MockResponse().setBody(revokeSecurityGroupIngressResponse));\n\n      IpPermission perm = IpPermission.builder().ipProtocol(IpProtocol.TCP).cidrBlock(\"0.0.0.0/0\")\n            .fromPort(8080).toPort(8080).build();\n      securityGroupApi().revokeSecurityGroupIngressInRegion(DEFAULT_REGION, \"sg-1a2b3c4d\", perm);\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=RevokeSecurityGroupIngress&GroupId=sg-1a2b3c4d&IpPermissions.0.IpProtocol=tcp&IpPermissions.0.FromPort=8080&IpPermissions.0.ToPort=8080&IpPermissions.0.IpRanges.0.CidrIp=0.0.0.0/0\");\n   }\n\n   public void revokeSecurityGroupIngressList() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION, new MockResponse().setBody(revokeSecurityGroupIngressResponse));\n\n      IpPermission perm = IpPermission.builder().ipProtocol(IpProtocol.TCP).cidrBlock(\"0.0.0.0/0\")\n            .fromPort(8080).toPort(8080).build();\n      IpPermission perm2 = IpPermission.builder().ipProtocol(IpProtocol.TCP).cidrBlock(\"0.0.0.0/0\")\n            .fromPort(8443).toPort(8443).build();\n      securityGroupApi().revokeSecurityGroupIngressInRegion(DEFAULT_REGION, \"sg-1a2b3c4d\", ImmutableList.of(perm, perm2));\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=RevokeSecurityGroupIngress&GroupId=sg-1a2b3c4d&IpPermissions.0.IpProtocol=tcp&IpPermissions.0.FromPort=8080&IpPermissions.0.ToPort=8080&IpPermissions.0.IpRanges.0.CidrIp=0.0.0.0/0&IpPermissions.1.IpProtocol=tcp&IpPermissions.1.FromPort=8443&IpPermissions.1.ToPort=8443&IpPermissions.1.IpRanges.0.CidrIp=0.0.0.0/0\");\n   }\n\n   public void deleteSecurityGroups() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION, new MockResponse().setBody(deleteSecurityGroupResponse));\n\n      securityGroupApi().deleteSecurityGroupInRegionById(DEFAULT_REGION, \"sg-1a2b3c4d\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DeleteSecurityGroup&GroupId=sg-1a2b3c4d\");\n   }\n\n   private AWSSecurityGroupApi securityGroupApi() {\n      return api().getSecurityGroupApi().get();\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/features/AWSSecurityGroupApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.features;\n\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport java.io.IOException;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.aws.ec2.xml.AWSEC2DescribeSecurityGroupsResponseHandler;\nimport org.jclouds.ec2.util.IpPermissions;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.http.functions.ReleasePayloadAndReturn;\nimport org.jclouds.net.domain.IpPermission;\nimport org.jclouds.net.domain.IpProtocol;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Lists;\nimport com.google.common.reflect.Invokable;\n/**\n * Tests behavior of {@code AWSSecurityGroupApi}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"AWSSecurityGroupApiTest\")\npublic class AWSSecurityGroupApiTest extends BaseAWSEC2ApiTest<AWSSecurityGroupApi> {\n   public AWSSecurityGroupApiTest() {\n      provider = \"aws-ec2\";\n   }\n\n   public void testDeleteSecurityGroup() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AWSSecurityGroupApi.class, \"deleteSecurityGroupInRegionById\", String.class,\n            String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"id\"));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, \"Action=DeleteSecurityGroup&GroupId=id\",\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, VoidOnNotFoundOr404.class);\n\n      checkFilters(request);\n   }\n\n   public void testDescribeSecurityGroups() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AWSSecurityGroupApi.class, \"describeSecurityGroupsInRegionById\", String.class,\n            String[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList((String) null));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, \"Action=DescribeSecurityGroups\",\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, AWSEC2DescribeSecurityGroupsResponseHandler.class);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(request);\n   }\n\n   public void testDescribeSecurityGroupsArgs() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AWSSecurityGroupApi.class, \"describeSecurityGroupsInRegionById\", String.class,\n            String[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"1\", \"2\"));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, \"Action=DescribeSecurityGroups&GroupId.1=1&GroupId.2=2\",\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, AWSEC2DescribeSecurityGroupsResponseHandler.class);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(request);\n   }\n\n   public void testCreateSecurityGroup() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AWSSecurityGroupApi.class, \"createSecurityGroupInRegion\", String.class,\n            String.class, String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"name\", \"description\"));\n\n      request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(request, \"Action=CreateSecurityGroup&GroupName=name&GroupDescription=description&Version=2012-06-01\",\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testAuthorizeSecurityGroupIpPermission() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AWSSecurityGroupApi.class, \"authorizeSecurityGroupIngressInRegion\",\n            String.class, String.class, IpPermission.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"group\", IpPermissions.permitAnyProtocol()));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(\n            request,\n            \"Action=AuthorizeSecurityGroupIngress&GroupId=group&IpPermissions.0.IpProtocol=-1&IpPermissions.0.FromPort=1&IpPermissions.0.ToPort=65535&IpPermissions.0.IpRanges.0.CidrIp=0.0.0.0/0\",\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testAuthorizeSecurityGroupIpPermissions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AWSSecurityGroupApi.class, \"authorizeSecurityGroupIngressInRegion\",\n            String.class, String.class, Iterable.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"group\", ImmutableSet.<IpPermission> of(IpPermissions\n            .permit(IpProtocol.TCP).originatingFromCidrBlock(\"1.1.1.1/32\"), IpPermissions.permitICMP().type(8).andCode(0)\n            .originatingFromSecurityGroupId(\"groupId\"))));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(\n            request,\n            \"Action=AuthorizeSecurityGroupIngress&GroupId=group&IpPermissions.0.IpProtocol=tcp&IpPermissions.0.FromPort=1&IpPermissions.0.ToPort=65535&IpPermissions.0.IpRanges.0.CidrIp=1.1.1.1/32&IpPermissions.1.IpProtocol=icmp&IpPermissions.1.FromPort=8&IpPermissions.1.ToPort=0&IpPermissions.1.Groups.0.GroupId=groupId\",\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testRevokeSecurityGroupIpPermission() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AWSSecurityGroupApi.class, \"revokeSecurityGroupIngressInRegion\", String.class,\n            String.class, IpPermission.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"group\", IpPermissions.permitAnyProtocol()));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(\n            request,\n            \"Action=RevokeSecurityGroupIngress&GroupId=group&IpPermissions.0.IpProtocol=-1&IpPermissions.0.FromPort=1&IpPermissions.0.ToPort=65535&IpPermissions.0.IpRanges.0.CidrIp=0.0.0.0/0\",\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   public void testRevokeSecurityGroupIpPermissions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AWSSecurityGroupApi.class, \"revokeSecurityGroupIngressInRegion\", String.class,\n            String.class, Iterable.class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList(null, \"group\", ImmutableSet.<IpPermission> of(IpPermissions\n            .permit(IpProtocol.TCP).originatingFromCidrBlock(\"1.1.1.1/32\"), IpPermissions.permitICMP().type(8).andCode(0)\n            .originatingFromSecurityGroupId(\"groupId\"))));\n\n      assertRequestLineEquals(request, \"POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: ec2.us-east-1.amazonaws.com\\n\");\n      assertPayloadEquals(\n            request,\n            \"Action=RevokeSecurityGroupIngress&GroupId=group&IpPermissions.0.IpProtocol=tcp&IpPermissions.0.FromPort=1&IpPermissions.0.ToPort=65535&IpPermissions.0.IpRanges.0.CidrIp=1.1.1.1/32&IpPermissions.1.IpProtocol=icmp&IpPermissions.1.FromPort=8&IpPermissions.1.ToPort=0&IpPermissions.1.Groups.0.GroupId=groupId\",\n            \"application/x-www-form-urlencoded\", false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/features/AWSSubnetApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.features;\n\nimport static org.jclouds.aws.ec2.options.ModifySubnetAttributeOptions.Builder.mapPublicIpOnLaunch;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Random;\n\nimport org.jclouds.aws.ec2.AWSEC2Api;\nimport org.jclouds.aws.ec2.domain.VPC;\nimport org.jclouds.aws.ec2.options.CreateVpcOptions;\nimport org.jclouds.compute.internal.BaseComputeServiceContextLiveTest;\nimport org.jclouds.ec2.domain.Subnet;\nimport org.jclouds.ec2.features.TagApi;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.Iterables;\n\n/**\n * Tests behavior of {@code VPCApi}\n */\n@Test(groups = \"live\", singleThreaded = true)\npublic class AWSSubnetApiLiveTest extends BaseComputeServiceContextLiveTest {\n\n   private String region;\n\n   private AWSEC2Api api;\n   private AWSSubnetApi subnetClient;\n   private VPCApi vpcClient;\n   private TagApi tagApi;\n   private String simpleName = getClass().getSimpleName() + new Random().nextInt(10000);\n\n   private Subnet subnet;\n   private VPC vpc;\n\n   public AWSSubnetApiLiveTest() {\n      provider = \"aws-ec2\";\n      region = \"eu-west-1\";\n   }\n\n   @Override\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   public void setupContext() {\n      super.setupContext();\n      api = view.unwrapApi(AWSEC2Api.class);\n      subnetClient = api.getAWSSubnetApi().get();\n      vpcClient = view.unwrapApi(AWSEC2Api.class).getVPCApi().get();\n      tagApi = api.getTagApiForRegion(region).get();\n   }\n\n   @Override\n   @AfterClass(groups = { \"integration\", \"live\" })\n   public void tearDownContext() {\n      try {\n         try {\n            if (subnet != null) {\n               subnetClient.deleteSubnetInRegion(region, subnet.getSubnetId());\n            }\n         } finally {\n            if (vpc != null) {\n               vpcClient.deleteVpc(region, vpc.id());\n            }\n         }\n      } finally {\n         super.tearDownContext();\n      }\n   }\n\n   @Test\n   public void testCreateSubnetInRegion() {\n      vpc = vpcClient.createVpc(region, \"10.21.0.0/16\", CreateVpcOptions.NONE);\n      // tag the VPC for ease of identification in console if things go wrong\n      tagApi.applyToResources(ImmutableMap.of(\"Name\", simpleName), ImmutableList.of(vpc.id()));\n      subnet = subnetClient.createSubnetInRegion(region, vpc.id(), \"10.21.0.0/20\");\n      assertNotNull(subnet);\n      assertEquals(subnet.getCidrBlock(), \"10.21.0.0/20\");\n   }\n\n   @Test(dependsOnMethods = \"testCreateSubnetInRegion\")\n   public void testGet() {\n      FluentIterable<Subnet> subnets = subnetClient.describeSubnetsInRegion(region, subnet.getSubnetId());\n      Subnet subnetFound = Iterables.getOnlyElement(subnets);\n      assertEquals(subnetFound.getSubnetId(), subnet.getSubnetId());\n   }\n\n   @Test(dependsOnMethods = \"testCreateSubnetInRegion\")\n   public void testFilter() {\n      FluentIterable<Subnet> subnets = subnetClient.describeSubnetsInRegionWithFilter(region, \n            ImmutableMultimap.of(\"subnet-id\", subnet.getSubnetId()));\n      Subnet subnetFound = Iterables.getOnlyElement(subnets);\n      assertEquals(subnetFound.getSubnetId(), subnet.getSubnetId());\n   }\n\n   @Test(dependsOnMethods = \"testCreateSubnetInRegion\")\n   public void testModifySubnetAttribute() {\n      final boolean result = subnetClient.modifySubnetAttribute(region, subnet.getSubnetId(), mapPublicIpOnLaunch(true));\n      assertTrue(result, \"Failed to modify subnet attribute\");\n   }\n\n   @Test(dependsOnMethods = \"testCreateSubnetInRegion\")\n   public void testList() {\n      FluentIterable<Subnet> subnets = subnetClient.describeSubnetsInRegionWithFilter(region, \n            ImmutableMultimap.<String, String>of());\n      Optional<Subnet> subnetFound = Iterables.tryFind(subnets, new Predicate<Subnet>() {\n         @Override\n         public boolean apply(Subnet input) {\n            return input != null && input.getSubnetId().equals(subnet.getSubnetId());\n         }\n      });\n      assertTrue(subnetFound.isPresent(), \"subnets=\" + ImmutableList.copyOf(subnets));\n   }\n\n   @Test(dependsOnMethods = {\"testGet\", \"testFilter\", \"testList\"}, alwaysRun = true)\n   public void testDelete() {\n      if (subnet != null) {\n         String subnetId = subnet.getSubnetId();\n         subnet = null;\n         subnetClient.deleteSubnetInRegion(region, subnetId);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/features/AWSSubnetApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.features;\n\nimport static org.jclouds.aws.ec2.options.ModifySubnetAttributeOptions.Builder.mapPublicIpOnLaunch;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport okhttp3.mockwebserver.MockResponse;\n\nimport org.jclouds.aws.ec2.internal.BaseAWSEC2ApiMockTest;\nimport org.jclouds.aws.ec2.options.CreateSubnetOptions;\nimport org.jclouds.ec2.domain.Subnet;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.Iterables;\n\n@Test(groups = \"unit\", testName = \"AWSSubnetApiMockTest\", singleThreaded = true)\npublic class AWSSubnetApiMockTest extends BaseAWSEC2ApiMockTest {\n\n   private final String describeSubnetsResponse = \"<DescribeSubnetsResponse xmlns=\\\"http://ec2.amazonaws.com/doc/2016-11-15/\\\">\\n\" +\n         \"  <requestId>7a62c49f-347e-4fc4-9331-6e8eEXAMPLE</requestId>\\n\" +\n         \"  <subnetSet>\\n\" +\n         \"    <item>\\n\" +\n         \"      <subnetId>subnet-9d4a7b6c</subnetId>\\n\" +\n         \"      <state>available</state>\\n\" +\n         \"      <vpcId>vpc-1a2b3c4d</vpcId>\\n\" +\n         \"      <cidrBlock>10.0.1.0/24</cidrBlock> \\n\" +\n         \"      <ipv6CidrBlockAssociationSet>\\n\" +\n         \"        <item>\\n\" +\n         \"          <ipv6CidrBlock>2001:db8:1234:1a00::/64</ipv6CidrBlock>\\n\" +\n         \"          <associationId>subnet-cidr-assoc-abababab</associationId>\\n\" +\n         \"          <ipv6CidrBlockState>\\n\" +\n         \"          <state>ASSOCIATED</state>\\n\" +\n         \"          </ipv6CidrBlockState>\\n\" +\n         \"        </item>\\n\" +\n         \"      </ipv6CidrBlockAssociationSet>\\n\" +\n         \"      <availableIpAddressCount>251</availableIpAddressCount>\\n\" +\n         \"      <availabilityZone>us-east-1a</availabilityZone>\\n\" +\n         \"      <defaultForAz>false</defaultForAz>\\n\" +\n         \"      <mapPublicIpOnLaunch>false</mapPublicIpOnLaunch>\\n\" +\n         \"      <tagSet/>\\n\" +\n         \"      <assignIpv6AddressOnCreation>false</assignIpv6AddressOnCreation>\\n\" +\n         \"    </item>\\n\" +\n         \"  </subnetSet>\\n\" +\n         \"</DescribeSubnetsResponse>\";\n\n   public void createSubnetInRegion() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION, new MockResponse().setBody(\"<CreateSubnetResponse xmlns=\\\"http://ec2.amazonaws.com/doc/2016-09-15/\\\">\\n\" +\n              \"  <requestId>7a62c49f-347e-4fc4-9331-6e8eEXAMPLE</requestId>\\n\" +\n              \"  <subnet>\\n\" +\n              \"    <subnetId>subnet-9d4a7b6c</subnetId>\\n\" +\n              \"    <state>pending</state>\\n\" +\n              \"    <vpcId>vpc-1a2b3c4d</vpcId>\\n\" +\n              \"    <cidrBlock>10.0.1.0/24</cidrBlock> \\n\" +\n              \"    <availableIpAddressCount>251</availableIpAddressCount>\\n\" +\n              \"    <availabilityZone>us-east-1a</availabilityZone>\\n\" +\n              \"    <tagSet/>\\n\" +\n              \"  </subnet>\\n\" +\n              \"</CreateSubnetResponse>\"));\n\n      Subnet result = subnetApi().createSubnetInRegion(DEFAULT_REGION, \"vpc-1a2b3c4d\", \"10.0.1.0/24\");\n      assertEquals(result.getVpcId(), \"vpc-1a2b3c4d\");\n      assertEquals(result.getCidrBlock(), \"10.0.1.0/24\");\n      assertEquals(result.getAvailabilityZone(), \"us-east-1a\");\n      assertEquals(result.getSubnetId(), \"subnet-9d4a7b6c\");\n      assertEquals(result.getSubnetState().value(), \"pending\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=CreateSubnet&VpcId=vpc-1a2b3c4d&CidrBlock=10.0.1.0/24\");\n   }\n\n   public void createSubnetInRegion_options() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION,\n            new MockResponse().setBody(\"<CreateSubnetResponse xmlns=\\\"http://ec2.amazonaws.com/doc/2016-09-15/\\\">\\n\" +\n                    \"  <requestId>7a62c49f-347e-4fc4-9331-6e8eEXAMPLE</requestId>\\n\" +\n                    \"  <subnet>\\n\" +\n                    \"    <subnetId>subnet-9d4a7b6c</subnetId>\\n\" +\n                    \"    <state>pending</state>\\n\" +\n                    \"    <vpcId>vpc-1a2b3c4d</vpcId>\\n\" +\n                    \"    <cidrBlock>10.0.1.0/24</cidrBlock> \\n\" +\n                    \"    <availableIpAddressCount>251</availableIpAddressCount>\\n\" +\n                    \"    <availabilityZone>us-east-1a</availabilityZone>\\n\" +\n                    \"    <tagSet/>\\n\" +\n                    \"  </subnet>\\n\" +\n                    \"</CreateSubnetResponse>\"));\n\n      Subnet result = subnetApi().createSubnetInRegion(DEFAULT_REGION, \"vpc-1a2b3c4d\", \"10.0.1.0/24\",\n            new CreateSubnetOptions().dryRun().availabilityZone(\"us-east-1a\"));\n      assertEquals(result.getVpcId(), \"vpc-1a2b3c4d\");\n      assertEquals(result.getCidrBlock(), \"10.0.1.0/24\");\n      assertEquals(result.getAvailabilityZone(), \"us-east-1a\");\n      assertEquals(result.getSubnetId(), \"subnet-9d4a7b6c\");\n      assertEquals(result.getSubnetState().value(), \"pending\");\n      \n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=CreateSubnet&VpcId=vpc-1a2b3c4d&CidrBlock=10.0.1.0/24&DryRun=true&AvailabilityZone=us-east-1a\");\n   }\n\n   public void deleteSubnetInRegion() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION,\n            new MockResponse().setBody(\"<DeleteSubnetResponse xmlns=\\\"http://ec2.amazonaws.com/doc/2016-09-15/\\\">\\n\" +\n                    \"  <requestId>7a62c49f-347e-4fc4-9331-6e8eEXAMPLE</requestId>\\n\" +\n                    \"  <return>true</return>\\n\" +\n                    \"</DeleteSubnetResponse>\"));\n\n      subnetApi().deleteSubnetInRegion(DEFAULT_REGION, \"subnet-9d4a7b6c\");\n      \n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DeleteSubnet&SubnetId=subnet-9d4a7b6c\");\n   }\n\n   public void describeSubnetInRegion() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION,\n            new MockResponse().setBody(describeSubnetsResponse));\n\n      FluentIterable<Subnet> results = subnetApi().describeSubnetsInRegion(DEFAULT_REGION);\n      Subnet result = Iterables.getOnlyElement(results);\n      assertEquals(result.getSubnetId(), \"subnet-9d4a7b6c\");\n      assertEquals(result.getSubnetState().value(), \"available\");\n      assertEquals(result.getVpcId(), \"vpc-1a2b3c4d\");\n      assertEquals(result.getCidrBlock(), \"10.0.1.0/24\");\n      assertEquals(result.getAvailabilityZone(), \"us-east-1a\");\n      assertEquals(result.getAvailableIpAddressCount(), 251);\n      \n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeSubnets\");\n   }\n\n   public void describeSubnetInRegionWithFilter() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION,\n            new MockResponse().setBody(describeSubnetsResponse));\n\n      FluentIterable<Subnet> results = subnetApi().describeSubnetsInRegionWithFilter(DEFAULT_REGION,\n            ImmutableMultimap.of(\"vpc-id\", \"vpc-1a2b3c4d\", \"availabilityZone\", \"us-east-1a\"));\n      Subnet result = Iterables.getOnlyElement(results);\n      assertEquals(result.getSubnetId(), \"subnet-9d4a7b6c\");\n      assertEquals(result.getSubnetState().value(), \"available\");\n      assertEquals(result.getVpcId(), \"vpc-1a2b3c4d\");\n      assertEquals(result.getCidrBlock(), \"10.0.1.0/24\");\n      assertEquals(result.getAvailabilityZone(), \"us-east-1a\");\n      assertEquals(result.getAvailableIpAddressCount(), 251);\n      \n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeSubnets&Filter.1.Name=vpc-id&Filter.1.Value.1=vpc-1a2b3c4d&Filter.2.Name=availabilityZone&Filter.2.Value.1=us-east-1a\");\n   }\n\n   public void describeSubnetInRegionWhen404() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION,\n            new MockResponse().setResponseCode(404));\n\n      FluentIterable<Subnet> results = subnetApi().describeSubnetsInRegion(DEFAULT_REGION);\n      assertTrue(Iterables.isEmpty(results));\n      \n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeSubnets\");\n   }\n\n   public void describeSubnetInRegionWithFilterWhen404() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION,\n            new MockResponse().setResponseCode(404));\n\n      FluentIterable<Subnet> results = subnetApi().describeSubnetsInRegionWithFilter(DEFAULT_REGION,\n            ImmutableMultimap.of(\"vpc-id\", \"vpc-1a2b3c4d\"));\n      assertTrue(Iterables.isEmpty(results));\n      \n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeSubnets&Filter.1.Name=vpc-id&Filter.1.Value.1=vpc-1a2b3c4d\");\n   }\n\n   public void describeSubnetInNonDefaultRegionWhen404() throws Exception {\n      String region = \"us-west-2\";\n      \n      enqueueRegions(DEFAULT_REGION, region);\n      enqueue(region,\n            new MockResponse().setResponseCode(404));\n\n      FluentIterable<Subnet> results = subnetApiForRegion(region).list();\n      assertTrue(Iterables.isEmpty(results));\n      \n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(region, \"Action=DescribeSubnets\");\n   }\n\n   public void modifySubnetAttribute() throws Exception {\n      String region = \"us-west-2\";\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION,\n         new MockResponse().setBody(\"<ModifySubnetAttributeResponse xmlns=\\\"http://ec2.amazonaws.com/doc/2016-09-15/\\\">\\n\" +\n            \"  <requestId>7a62c49f-347e-4fc4-9331-6e8eEXAMPLE</requestId>\\n\" +\n            \"  <return>true</return>\\n\" +\n            \"</ModifySubnetAttributeResponse>\"));\n\n      final boolean result =\n         subnetApiForRegion(DEFAULT_REGION).modifySubnetAttribute(DEFAULT_REGION, \"subnet-9d4a7b6c\", mapPublicIpOnLaunch(true));\n      assertTrue(result, \"Failed to match expected test result of 'true'\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION,\n         \"Action=ModifySubnetAttribute&SubnetId=subnet-9d4a7b6c&MapPublicIpOnLaunch.Value=true\",\n         \"2014-06-15\");\n\n   }\n\n   private AWSSubnetApi subnetApi() {\n      return api().getAWSSubnetApi().get();\n   }\n   \n   private AWSSubnetApi subnetApiForRegion(String region) {\n      return api().getAWSSubnetApiForRegion(region).get();\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/features/BaseAWSEC2ApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.features;\n\nimport static com.google.common.collect.Maps.transformValues;\nimport static com.google.common.net.HttpHeaders.AUTHORIZATION;\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.net.URI;\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.domain.Region;\nimport org.jclouds.aws.ec2.AWSEC2ProviderMetadata;\nimport org.jclouds.aws.ec2.config.AWSEC2HttpApiModule;\nimport org.jclouds.aws.filters.FormSignerV4;\nimport org.jclouds.aws.filters.FormSignerV4.ServiceAndRegion;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.date.DateService;\nimport org.jclouds.ec2.compute.domain.RegionAndName;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.location.config.LocationModule;\nimport org.jclouds.location.suppliers.RegionIdToURISupplier;\nimport org.jclouds.location.suppliers.RegionIdToZoneIdsSupplier;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.internal.BaseRestAnnotationProcessingTest;\nimport org.jclouds.util.Suppliers2;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.LinkedHashMultimap;\nimport com.google.common.collect.Multimap;\nimport com.google.inject.Module;\nimport com.google.inject.Provides;\n\n@Test(groups = \"unit\")\npublic abstract class BaseAWSEC2ApiTest<T> extends BaseRestAnnotationProcessingTest<T> {\n\n   @ConfiguresHttpApi\n   protected static class StubAWSEC2HttpApiModule extends AWSEC2HttpApiModule {\n\n      @Override\n      protected String provideTimeStamp(DateService dateService) {\n         return \"20120416T155408Z\";\n      }\n\n      @Provides\n      @Singleton\n      LoadingCache<RegionAndName, Image> provide() {\n         return CacheBuilder.newBuilder().build(new CacheLoader<RegionAndName, Image>() {\n\n            @Override\n            public Image load(RegionAndName key) throws Exception {\n               return null;\n            }\n\n         });\n      }\n\n      @Override\n      protected void installLocations() {\n         install(new LocationModule());\n         bind(RegionIdToURISupplier.class).toInstance(new RegionIdToURISupplier() {\n\n            @Override\n            public Map<String, Supplier<URI>> get() {\n               return transformValues(ImmutableMap\n                     .<String, URI>of(Region.EU_WEST_1, URI.create(\"https://ec2.eu-west-1.amazonaws.com\"),\n                           Region.US_EAST_1, URI.create(\"https://ec2.us-east-1.amazonaws.com\"), Region.US_WEST_1,\n                           URI.create(\"https://ec2.us-west-1.amazonaws.com\")), Suppliers2.<URI>ofInstanceFunction());\n            }\n\n         });\n         bind(RegionIdToZoneIdsSupplier.class).toInstance(new RegionIdToZoneIdsSupplier() {\n\n            @Override\n            public Map<String, Supplier<Set<String>>> get() {\n               return transformValues(ImmutableMap.<String, Set<String>> of(\"us-east-1\", ImmutableSet.of(\"us-east-1a\",\n                        \"us-east-1b\", \"us-east-1c\", \"us-east-1b\")), Suppliers2.<Set<String>> ofInstanceFunction());\n            }\n\n         });\n      }\n\n      @Provides ServiceAndRegion ServiceAndRegion(){\n         return new ServiceAndRegion() {\n            @Override public String service() {\n               return \"ec2\";\n            }\n\n            @Override public String region(String host) {\n               return \"us-east-1\";\n            }\n         };\n      }\n   }\n\n   @Override protected void assertNonPayloadHeadersEqual(HttpRequest request, String toMatch) {\n      Multimap<String, String> headersToCheck = LinkedHashMultimap.create();\n      for (String key : request.getHeaders().keySet()) {\n         if (key.equals(\"X-Amz-Date\")) {\n            assertEquals(request.getFirstHeaderOrNull(key), \"20120416T155408Z\");\n         } else if (key.equals(\"Authorization\")) {\n            assertThat(request.getFirstHeaderOrNull(AUTHORIZATION)).startsWith(\n                  \"AWS4-HMAC-SHA256 Credential=identity/20120416/\"\n                        + \"us-east-1/ec2/aws4_request, SignedHeaders=content-type;host;x-amz-date, Signature=\");\n         } else {\n            headersToCheck.putAll(key, request.getHeaders().get(key));\n         }\n      }\n      assertEquals(sortAndConcatHeadersIntoString(headersToCheck), toMatch);\n   }\n\n   protected FormSignerV4 filter;\n\n   @Override\n   protected void checkFilters(HttpRequest request) {\n      assertEquals(request.getFilters().size(), 1);\n      assertTrue(request.getFilters().get(0) instanceof FormSignerV4);\n   }\n\n   @Override\n   @BeforeTest\n   protected void setupFactory() throws IOException {\n      super.setupFactory();\n      this.filter = injector.getInstance(FormSignerV4.class);\n   }\n\n   @Override\n   protected Module createModule() {\n      return new StubAWSEC2HttpApiModule();\n   }\n\n   protected String provider = \"aws-ec2\";\n\n   @Override\n   public AWSEC2ProviderMetadata createProviderMetadata() {\n      return new AWSEC2ProviderMetadata();\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/features/InternetGatewayApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.features;\n\nimport static java.util.logging.Logger.getAnonymousLogger;\nimport static org.jclouds.aws.ec2.options.InternetGatewayOptions.Builder.dryRun;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.List;\nimport java.util.Random;\n\nimport org.jclouds.apis.BaseApiLiveTest;\nimport org.jclouds.aws.AWSResponseException;\nimport org.jclouds.aws.ec2.AWSEC2Api;\nimport org.jclouds.aws.ec2.domain.InternetGateway;\nimport org.jclouds.aws.ec2.domain.InternetGatewayAttachment;\nimport org.jclouds.aws.ec2.domain.VPC;\nimport org.jclouds.aws.ec2.options.CreateVpcOptions;\nimport org.jclouds.aws.ec2.options.InternetGatewayOptions;\nimport org.jclouds.ec2.features.TagApi;\nimport org.testng.Assert;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Tests behavior of {@link InternetGatewayApi}\n */\n@Test(groups = \"live\")\npublic class InternetGatewayApiLiveTest extends BaseApiLiveTest<AWSEC2Api> {\n\n   // Define -Djclouds.test.region=whatever to test in your preferred region;\n   // defaults to null, jclouds will pick the provider's default region\n   private static final String TEST_REGION = System.getProperty(\"jclouds.test.region\");\n\n   public InternetGatewayApiLiveTest() {\n      provider = \"aws-ec2\";\n   }\n\n   private InternetGatewayApi gwClient;\n   private TagApi tagger;\n\n   private VPCApi vpcClient;\n   private VPC vpc;\n   private InternetGateway gateway;\n\n   private String simpleName = InternetGatewayApiLiveTest.class.getSimpleName() + new Random().nextInt(10000);\n\n   @BeforeClass(groups = {\"integration\", \"live\"})\n   public void setupContext() {\n      gwClient = api.getInternetGatewayApiForRegion(TEST_REGION).get();\n      vpcClient = api.getVPCApi().get();\n      tagger = api.getTagApiForRegion(TEST_REGION).get();\n   }\n\n   @Test\n   public void testCreate() {\n      gateway = gwClient.createInternetGateway(TEST_REGION, InternetGatewayOptions.NONE);\n      assertNotNull(gateway, \"Gateway was not successfully created\");\n\n      assertEquals(gateway.tags().size(), 0, \"Freshly created gateway has tags\");\n      assertEquals(gateway.attachmentSet().size(), 0, \"Freshly created gateway is attached\");\n\n      tagger.applyToResources(ImmutableMap.of(\"Name\", simpleName), ImmutableList.of(gateway.id()));\n      getAnonymousLogger().info(\"Created gateway \" +  simpleName + \" with id \" + gateway.id());\n   }\n\n\n   @Test(dependsOnMethods = \"testCreate\")\n   public void testAttach() {\n      vpc = vpcClient.createVpc(TEST_REGION, \"10.20.30.0/24\", CreateVpcOptions.NONE);\n      assertNotNull(vpc, \"Failed to create VPC to test attachments\");\n      tagger.applyToResources(ImmutableMap.of(\"Name\", simpleName), ImmutableList.of(vpc.id()));\n\n      final Boolean attached = gwClient.attachInternetGateway(TEST_REGION, gateway.id(), vpc.id());\n      assertTrue(attached, \"Gateway \" + gateway.id() + \" failed to attach to VPC \" + vpc.id());\n   }\n\n   @Test(dependsOnMethods = \"testAttach\")\n   public void testGetAndVerifyAttach() {\n      getAnonymousLogger().info(\"Testing retrieval of gateway \" + simpleName);\n      FluentIterable<InternetGateway> gateways = gwClient.describeInternetGatewaysInRegion(TEST_REGION, gateway.id());\n      final ImmutableList<InternetGateway> internetGateways = gateways.toList();\n      getAnonymousLogger().info(\"Gateway count \" + internetGateways.size());\n      assertTrue(internetGateways.size() == 1, \"Failed to retrieve list with expected gateway \" + gateway.id());\n\n      final InternetGateway gw = internetGateways.get(0);\n      getAnonymousLogger().info(\"Found gateway \" + gw.id() + \" with \" +  gw.tags().size() + \" tags\");\n      assertEquals(gw.tags().get(\"Name\"), simpleName);\n\n      final List<InternetGatewayAttachment> attachments = gw.attachmentSet();\n      assertEquals(attachments.size(), 1, \"Gateway \" + gateway.id() + \" has no attachments, should have \" + vpc.id());\n      final String attached = attachments.get(0).vpcId();\n      assertEquals(attached, vpc.id(), \"Gateway \" + gateway.id() + \" attached to \" + attached + \" not \" + vpc.id());\n   }\n\n   @Test(dependsOnMethods = \"testGetAndVerifyAttach\")\n   public void testDetach() {\n      final Boolean detached = gwClient.detachInternetGateway(TEST_REGION, gateway.id(), vpc.id());\n      assertTrue(detached, \"Gateway \" + gateway.id() + \" was not detached from VPC \" + vpc.id());\n   }\n\n   @Test(dependsOnMethods = \"testDetach\")\n   public void testListAndVerifyResultsOfDetach() {\n      FluentIterable<InternetGateway> gateways = gwClient.describeInternetGatewaysInRegion(TEST_REGION);\n      final ImmutableList<InternetGateway> asList = gateways.toList();\n      assertFalse(asList.isEmpty());\n      boolean found = false;\n      for (InternetGateway gw : asList) {\n         if (gw.id().equals(gateway.id())) {\n            found = true;\n            assertEquals(gw.attachmentSet().size(), 0, \"Gateway \" + gw.id() + \" is attached to \" + gw.attachmentSet());\n         }\n      }\n      assertTrue(found, \"Could not find gateway \" + gateway.id() + \" in result of list\");\n   }\n\n   @Test(dependsOnMethods = \"testListAndVerifyResultsOfDetach\", alwaysRun = true)\n   public void testDelete() {\n      if (gateway != null) {\n         assertTrue(gwClient.deleteInternetGateway(TEST_REGION, gateway.id()));\n      }\n      if (vpc != null) {\n         assertTrue(vpcClient.deleteVpc(TEST_REGION, vpc.id()));\n      }\n   }\n\n   @Test\n   public void testWithOptions() {\n      FluentIterable<InternetGateway> before = gwClient.describeInternetGatewaysInRegion(TEST_REGION);\n\n      try {\n         gwClient.createInternetGateway(TEST_REGION, dryRun());\n         Assert.fail(\"Operation completed when exception was expected\");\n      } catch (AWSResponseException e) {\n         assertEquals(e.getError().getCode(), \"DryRunOperation\", \"Expected DryRunOperation but got \" + e.getError());\n      }\n\n      FluentIterable<InternetGateway> after = gwClient.describeInternetGatewaysInRegion(TEST_REGION);\n\n      assertNotEquals(before, after, \"Dry run 'CreateInternetGateway' operation modified live account\");\n\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/features/InternetGatewayApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.features;\n\nimport static jakarta.ws.rs.core.Response.Status.PRECONDITION_FAILED;\nimport static org.jclouds.aws.ec2.options.InternetGatewayOptions.Builder.dryRun;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.List;\n\nimport okhttp3.mockwebserver.MockResponse;\n\nimport org.jclouds.aws.AWSResponseException;\nimport org.jclouds.aws.ec2.domain.InternetGateway;\nimport org.jclouds.aws.ec2.domain.InternetGatewayAttachment;\nimport org.jclouds.aws.ec2.internal.BaseAWSEC2ApiMockTest;\nimport org.jclouds.aws.ec2.options.InternetGatewayOptions;\nimport org.testng.Assert;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Lists;\n\n@Test(groups = \"unit\", testName = \"InternetGatewayApiMockTest\", singleThreaded = true)\npublic class InternetGatewayApiMockTest extends BaseAWSEC2ApiMockTest {\n\n   public void createInternetGateway() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(DEFAULT_REGION, \"/create_internet_gateway.xml\");\n      InternetGateway result = gatewayApi().createInternetGateway(DEFAULT_REGION, InternetGatewayOptions.NONE);\n\n      assertNotNull(result, \"Failed to create InternetGateway object\");\n      assertEquals(result.id(), \"igw-fada7c9c\", \"Gateway id does not match mock data: \" + result.id());\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=CreateInternetGateway\");\n   }\n\n   public void attachInternetGateway() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(DEFAULT_REGION, \"/attach_internet_gateway.xml\");\n\n      final Boolean attached = gatewayApi().attachInternetGateway(DEFAULT_REGION, \"igw-fada7c9c\", \"vpc-6250b91b\");\n      assertTrue(attached, \"Failed to attach InternetGateway\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=AttachInternetGateway&InternetGatewayId=igw-fada7c9c&VpcId=vpc-6250b91b\");\n   }\n\n   public void attachInternetGatewayFail() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(DEFAULT_REGION, \"/attach_internet_gateway_failed.xml\");\n\n      final Boolean attached = gatewayApi().attachInternetGateway(DEFAULT_REGION, \"igw-fada7c9c\", \"vpc-6250b91b\");\n      assertFalse(attached, \"Gateway reported as created despite failure response\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=AttachInternetGateway&InternetGatewayId=igw-fada7c9c&VpcId=vpc-6250b91b\");\n   }\n\n   public void attachInternetGatewayNotFound() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION, new MockResponse().setResponseCode(404));\n\n      final Boolean attached = gatewayApi().attachInternetGateway(DEFAULT_REGION, \"igw-fada7c9c\", \"vpc-6250b91b\");\n      assertFalse(attached, \"Somehow attached gateway despite NotFound response\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=AttachInternetGateway&InternetGatewayId=igw-fada7c9c&VpcId=vpc-6250b91b\");\n   }\n\n   public void detachInternetGateway() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(DEFAULT_REGION, \"/detach_internet_gateway.xml\");\n\n      final Boolean detached = gatewayApi().detachInternetGateway(DEFAULT_REGION, \"igw-fada7c9c\", \"vpc-6250b91b\");\n      assertTrue(detached, \"Gateway not successfully detached\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DetachInternetGateway&InternetGatewayId=igw-fada7c9c&VpcId=vpc-6250b91b\");\n\n   }\n\n   public void detachInternetGatewayNotFound() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION, new MockResponse().setResponseCode(404));\n\n      final Boolean detached = gatewayApi().detachInternetGateway(DEFAULT_REGION, \"igw-fada7c9c\", \"vpc-6250b91b\");\n      assertFalse(detached, \"Non-existent gateway somehow successfully detached\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DetachInternetGateway&InternetGatewayId=igw-fada7c9c&VpcId=vpc-6250b91b\");\n\n   }\n\n   public void getInternetGateway() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(DEFAULT_REGION, \"/get_internet_gateway.xml\");\n\n      final String igwId = \"igw-fada7c9c\";\n      final FluentIterable<InternetGateway> internetGateways =\n         gatewayApi().describeInternetGatewaysInRegion(DEFAULT_REGION, igwId);\n\n      final ImmutableList<InternetGateway> gateways = internetGateways.toList();\n      assertEquals(gateways.size(), 1);\n      assertEquals(gateways.get(0).id(), igwId);\n      assertEquals(gateways.get(0).tags().get(\"Name\"), \"get_internet_gateway_test\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeInternetGateways&InternetGatewayId.1=igw-fada7c9c\");\n   }\n\n   public void getInternetGatewayNotFound() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION, new MockResponse().setResponseCode(404));\n\n      final String igwId = \"igw-fada7c9c\";\n      final FluentIterable<InternetGateway> internetGateways =\n         gatewayApi().describeInternetGatewaysInRegion(DEFAULT_REGION, igwId);\n\n      final ImmutableList<InternetGateway> gateways = internetGateways.toList();\n      assertEquals(gateways.size(), 0);\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeInternetGateways&InternetGatewayId.1=igw-fada7c9c\");\n\n   }\n\n   public void describeInternetGateways() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(DEFAULT_REGION, \"/describe_internet_gateways.xml\");\n\n      final FluentIterable<InternetGateway> internetGateways =\n         gatewayApi().describeInternetGatewaysInRegion(DEFAULT_REGION);\n\n      final List<InternetGateway> gateways = Lists.newArrayList(internetGateways.toList());\n\n      assertEquals(gateways.size(), 3);\n      final ImmutableMap<String, InternetGateway> asMap =\n         ImmutableMap.of(gateways.get(0).id(), gateways.get(0),\n            gateways.get(1).id(), gateways.get(1),\n            gateways.get(2).id(), gateways.get(2));\n\n      assertEquals(asMap.get(\"igw-fada7c9c\").tags().get(\"Name\"), \"describe_internet_gateways_test\");\n      final InternetGatewayAttachment gw6bca130c = asMap.get(\"igw-6bca130c\").attachmentSet().iterator().next();\n      assertEquals(gw6bca130c.vpcId(), \"vpc-a13d29c6\");\n      assertEquals(gw6bca130c.state(), InternetGatewayAttachment.State.AVAILABLE);\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeInternetGateways\");\n   }\n\n   public void deleteInternetGateway() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(DEFAULT_REGION, \"/delete_internet_gateway.xml\");\n\n      final boolean deleted = gatewayApi().deleteInternetGateway(DEFAULT_REGION, \"igw-fada7c9c\");\n      assertTrue(deleted, \"Failed to delete gateway\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DeleteInternetGateway&InternetGatewayId=igw-fada7c9c\");\n   }\n\n   public void deleteInternetGatewayNotFound() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION, new MockResponse().setResponseCode(404));\n\n      final boolean deleted = gatewayApi().deleteInternetGateway(DEFAULT_REGION, \"igw-fada7c9c\");\n      assertFalse(deleted, \"Somehow deleted a gateway that does not exist\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DeleteInternetGateway&InternetGatewayId=igw-fada7c9c\");\n   }\n\n   @Test\n   public void testWithOptions() throws Exception {\n\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(PRECONDITION_FAILED, DEFAULT_REGION, \"/dry_run.xml\");\n\n      try {\n         gatewayApi().createInternetGateway(DEFAULT_REGION, dryRun());\n         Assert.fail(\"Expected 'DryRunOperation' exception was not thrown\");\n      } catch (AWSResponseException e) {\n         assertEquals(e.getError().getCode(), \"DryRunOperation\", \"Expected DryRunOperation but got \" + e.getError());\n      }\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=CreateInternetGateway&DryRun=true\");\n   }\n\n   private InternetGatewayApi gatewayApi() {\n      return api().getInternetGatewayApi().get();\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/features/MonitoringApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.features;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Map;\n\nimport org.jclouds.aws.ec2.AWSEC2Api;\nimport org.jclouds.aws.ec2.domain.MonitoringState;\nimport org.jclouds.compute.internal.BaseComputeServiceContextLiveTest;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code MonitoringApi}\n */\n@Test(groups = \"live\", singleThreaded = true)\npublic class MonitoringApiLiveTest extends BaseComputeServiceContextLiveTest {\n   public MonitoringApiLiveTest() {\n      provider = \"aws-ec2\";\n   }\n\n   private MonitoringApi client;\n   private static final String DEFAULT_INSTANCE = \"i-TODO\";\n\n   \n   @Override\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   public void setupContext() {\n      super.setupContext();\n      client = view.unwrapApi(AWSEC2Api.class).getMonitoringApi().get();\n   }\n\n   @Test(enabled = false)\n   // TODO get instance\n   public void testMonitorInstances() {\n      Map<String, MonitoringState> monitoringState = client.monitorInstancesInRegion(null, DEFAULT_INSTANCE);\n      assertEquals(monitoringState.get(DEFAULT_INSTANCE), MonitoringState.PENDING);\n   }\n\n   @Test(enabled = false)\n   // TODO get instance\n   public void testUnmonitorInstances() {\n      Map<String, MonitoringState> monitoringState = client.unmonitorInstancesInRegion(null, DEFAULT_INSTANCE);\n      assertEquals(monitoringState.get(DEFAULT_INSTANCE), MonitoringState.PENDING);\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/features/MonitoringApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.features;\n\nimport static org.testng.Assert.assertFalse;\n\nimport java.util.Map;\n\nimport org.jclouds.aws.ec2.domain.MonitoringState;\nimport org.jclouds.aws.ec2.internal.BaseAWSEC2ApiMockTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"MonitoringApiMockTest\", singleThreaded = true)\npublic class MonitoringApiMockTest extends BaseAWSEC2ApiMockTest {\n\n   public void monitorInstancesInRegion() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(DEFAULT_REGION, \"/monitoring.xml\");\n\n      Map<String, MonitoringState> result = monitoringApi()\n            .monitorInstancesInRegion(DEFAULT_REGION, \"i-911444f0\", \"i-911444f1\");\n\n      assertFalse(result.isEmpty());\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=MonitorInstances&InstanceId.0=i-911444f0&InstanceId.1=i-911444f1\");\n   }\n\n   public void unmonitorInstancesInRegion() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(DEFAULT_REGION, \"/monitoring.xml\");\n\n      Map<String, MonitoringState> result = monitoringApi()\n            .unmonitorInstancesInRegion(DEFAULT_REGION, \"i-911444f0\", \"i-911444f1\");\n\n      assertFalse(result.isEmpty());\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=UnmonitorInstances&InstanceId.0=i-911444f0&InstanceId.1=i-911444f1\");\n   }\n\n   private MonitoringApi monitoringApi() {\n      return api().getMonitoringApi().get();\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/features/PlacementGroupApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.features;\n\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static com.google.common.collect.Sets.newTreeSet;\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static org.jclouds.util.Predicates2.retry;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.fail;\n\nimport java.util.Set;\nimport java.util.SortedSet;\n\nimport org.jclouds.aws.AWSResponseException;\nimport org.jclouds.aws.domain.Region;\nimport org.jclouds.aws.ec2.AWSEC2Api;\nimport org.jclouds.aws.ec2.domain.PlacementGroup;\nimport org.jclouds.aws.ec2.domain.PlacementGroup.State;\nimport org.jclouds.aws.ec2.predicates.PlacementGroupAvailable;\nimport org.jclouds.aws.ec2.predicates.PlacementGroupDeleted;\nimport org.jclouds.compute.RunNodesException;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.internal.BaseComputeServiceContextLiveTest;\nimport org.jclouds.compute.predicates.NodePredicates;\nimport org.jclouds.ec2.compute.domain.EC2HardwareBuilder;\nimport org.jclouds.ec2.domain.InstanceType;\nimport org.jclouds.ec2.domain.Reservation;\nimport org.jclouds.ec2.domain.RunningInstance;\nimport org.jclouds.scriptbuilder.domain.Statements;\nimport org.jclouds.scriptbuilder.statements.java.InstallJDK;\nimport org.jclouds.scriptbuilder.statements.login.AdminAccess;\nimport org.jclouds.sshj.config.SshjSshClientModule;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Throwables;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.inject.Module;\n\n/**\n * Tests behavior of {@code PlacementGroupApi}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"PlacementGroupApiLiveTest\")\npublic class PlacementGroupApiLiveTest extends BaseComputeServiceContextLiveTest {\n   private final Set<String> supportedRegions = Region.DEFAULT_REGIONS;\n\n   public PlacementGroupApiLiveTest() {\n      provider = \"aws-ec2\";\n   }\n\n   private AWSEC2Api client;\n   private Predicate<PlacementGroup> availableTester;\n   private Predicate<PlacementGroup> deletedTester;\n   private PlacementGroup group;\n\n   @Override\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   public void setupContext() {\n      super.setupContext();\n      client = view.unwrapApi(AWSEC2Api.class);\n      availableTester = retry(new PlacementGroupAvailable(client), 60, 1, SECONDS);\n      deletedTester = retry(new PlacementGroupDeleted(client), 60, 1, SECONDS);\n   }\n\n   @Test\n   public void testDescribe() {\n      for (String region : supportedRegions) {\n         SortedSet<PlacementGroup> allResults = newTreeSet(client.getPlacementGroupApi().get()\n                  .describePlacementGroupsInRegion(region));\n         assertNotNull(allResults);\n         if (allResults.size() >= 1) {\n            PlacementGroup group = allResults.last();\n            SortedSet<PlacementGroup> result = newTreeSet(client.getPlacementGroupApi().get()\n                     .describePlacementGroupsInRegion(region, group.getName()));\n            assertNotNull(result);\n            PlacementGroup compare = result.last();\n            assertEquals(compare, group);\n         }\n      }\n\n      for (String region : client.getAvailabilityZoneAndRegionApi().get().describeRegions().keySet()) {\n         if (!supportedRegions.contains(region))\n            try {\n               client.getPlacementGroupApi().get().describePlacementGroupsInRegion(region);\n               fail(\"should be unsupported for region: \" + region);\n            } catch (UnsupportedOperationException e) {\n            }\n      }\n   }\n\n   @Test\n   public void testFilter() {\n      for (String region : supportedRegions) {\n         SortedSet<PlacementGroup> allResults = newTreeSet(client.getPlacementGroupApi().get()\n                 .describePlacementGroupsInRegion(region));\n         assertNotNull(allResults);\n         if (allResults.size() >= 1) {\n            PlacementGroup group = allResults.last();\n            SortedSet<PlacementGroup> result = newTreeSet(client.getPlacementGroupApi().get()\n                    .describePlacementGroupsInRegionWithFilter(region,\n                            ImmutableMultimap.<String, String>builder()\n                            .put(\"group-name\", group.getName()).build()));\n            assertNotNull(result);\n            PlacementGroup compare = result.last();\n            assertEquals(compare, group);\n         }\n      }\n   }\n\n   @Test(expectedExceptions = AWSResponseException.class)\n   public void testFilterInvalid() {\n      for (String region : supportedRegions) {\n         SortedSet<PlacementGroup> allResults = newTreeSet(client.getPlacementGroupApi().get()\n                 .describePlacementGroupsInRegion(region));\n         assertNotNull(allResults);\n         if (allResults.size() >= 1) {\n            PlacementGroup group = allResults.last();\n            client.getPlacementGroupApi().get()\n                    .describePlacementGroupsInRegionWithFilter(region,\n                            ImmutableMultimap.<String, String>builder()\n                                    .put(\"invalid-filter\", group.getName()).build());\n         }\n      }\n   }\n\n   @Test\n   public void testCreatePlacementGroup() {\n      String groupName = PREFIX + \"1\";\n      for (String region : supportedRegions) {\n\n         client.getPlacementGroupApi().get().deletePlacementGroupInRegion(region, groupName);\n         client.getPlacementGroupApi().get().createPlacementGroupInRegion(region, groupName);\n\n         verifyPlacementGroup(region, groupName);\n      }\n   }\n\n   private void verifyPlacementGroup(String region, String groupName) {\n      assert availableTester.apply(new PlacementGroup(region, groupName, \"cluster\", State.PENDING)) : group;\n      Set<PlacementGroup> oneResult = client.getPlacementGroupApi().get().describePlacementGroupsInRegion(region,\n               groupName);\n      assertNotNull(oneResult);\n      assertEquals(oneResult.size(), 1);\n      group = oneResult.iterator().next();\n      assertEquals(group.getName(), groupName);\n      assertEquals(group.getStrategy(), \"cluster\");\n      assert availableTester.apply(group) : group;\n   }\n\n   @SuppressWarnings(\"CheckReturnValue\")\n   public void testStartHS1Instance() throws Exception {\n\n      Template template = view.getComputeService().templateBuilder()\n               .fromHardware(EC2HardwareBuilder.hs1_8xlarge().build()).osFamily(OsFamily.AMZN_LINUX).build();\n      assert template != null : \"The returned template was null, but it should have a value.\";\n      assertEquals(template.getHardware().getProviderId(), InstanceType.HS1_8XLARGE);\n      assertEquals(template.getImage().getUserMetadata().get(\"virtualizationType\"), \"hvm\");\n      assertEquals(template.getImage().getUserMetadata().get(\"hypervisor\"), \"xen\");\n\n      template.getOptions().runScript(Statements.newStatementList(AdminAccess.standard(), InstallJDK.fromOpenJDK()));\n\n      String group = PREFIX + \"cccluster\";\n      view.getComputeService().destroyNodesMatching(NodePredicates.inGroup(group));\n      // TODO make this not lookup an explicit region\n      client.getPlacementGroupApi().get().deletePlacementGroupInRegion(null, \"jclouds#\" + group + \"#us-east-1\");\n\n      try {\n         Set<? extends NodeMetadata> nodes = view.getComputeService().createNodesInGroup(group, 1, template);\n         NodeMetadata node = getOnlyElement(nodes);\n\n         Reservation<? extends RunningInstance> reservation = getOnlyElement(client.getInstanceApi().get().describeInstancesInRegion(null,\n                  node.getProviderId()));\n         getOnlyElement(reservation);\n\n      } catch (RunNodesException e) {\n         System.err.println(e.getNodeErrors().keySet());\n         Throwables.propagate(e);\n      } finally {\n         view.getComputeService().destroyNodesMatching(NodePredicates.inGroup(group));\n      }\n   }\n\n   public static final String PREFIX = System.getProperty(\"user.name\") + \"ec2\";\n\n   @Override\n   @AfterClass(groups = { \"integration\", \"live\" })\n   protected void tearDownContext() {\n      if (group != null) {\n         client.getPlacementGroupApi().get().deletePlacementGroupInRegion(group.getRegion(), group.getName());\n         assert deletedTester.apply(group) : group;\n      }\n      super.tearDownContext();\n   }\n\n   @Override\n   protected Module getSshModule() {\n      return new SshjSshClientModule();\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/features/PlacementGroupApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.features;\n\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static org.testng.Assert.assertEquals;\n\nimport okhttp3.mockwebserver.MockResponse;\n\nimport org.jclouds.aws.ec2.domain.PlacementGroup;\nimport org.jclouds.aws.ec2.internal.BaseAWSEC2ApiMockTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\", testName = \"PlacementGroupApiMockTest\", singleThreaded = true)\npublic class PlacementGroupApiMockTest extends BaseAWSEC2ApiMockTest {\n\n   public void describePlacementGroupsInRegionWithFilter() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(DEFAULT_REGION, \"/describe_placement_groups.xml\");\n\n      PlacementGroup result = getOnlyElement(placementApi()\n            .describePlacementGroupsInRegionWithFilter(DEFAULT_REGION, ImmutableMultimap.of(\"strategy\", \"cluster\")));\n\n      assertEquals(result.getName(), \"XYZ-cluster\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribePlacementGroups&Filter.1.Name=strategy&Filter.1.Value.1=cluster\");\n   }\n\n   public void describePlacementGroupsInRegionWithFilter_404() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION, new MockResponse().setResponseCode(404));\n\n      assertEquals(placementApi().describePlacementGroupsInRegionWithFilter(DEFAULT_REGION,\n                  ImmutableMultimap.of(\"strategy\", \"cluster\")), ImmutableSet.of());\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribePlacementGroups&Filter.1.Name=strategy&Filter.1.Value.1=cluster\");\n   }\n\n   public void deletePlacementGroupInRegion() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION, new MockResponse());\n\n      placementApi().deletePlacementGroupInRegion(DEFAULT_REGION, \"name\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DeletePlacementGroup&GroupName=name\");\n   }\n\n   public void deletePlacementGroupInRegion_404() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION, new MockResponse().setResponseCode(404));\n\n      placementApi().deletePlacementGroupInRegion(DEFAULT_REGION, \"name\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DeletePlacementGroup&GroupName=name\");\n   }\n\n   public void createPlacementGroupInRegion() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION, new MockResponse());\n\n      placementApi().createPlacementGroupInRegion(DEFAULT_REGION, \"name\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=CreatePlacementGroup&Strategy=cluster&GroupName=name\");\n   }\n\n   public void createPlacementGroupInRegion_strategy() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION, new MockResponse());\n\n      placementApi().createPlacementGroupInRegion(DEFAULT_REGION, \"name\", \"cluster\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=CreatePlacementGroup&GroupName=name&Strategy=cluster\");\n   }\n\n   private PlacementGroupApi placementApi() {\n      return api().getPlacementGroupApi().get();\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/features/RouteTableApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.features;\n\nimport static java.util.logging.Logger.getAnonymousLogger;\nimport static org.jclouds.aws.ec2.options.RouteOptions.Builder.destinationCidrBlock;\nimport static org.jclouds.aws.ec2.options.RouteOptions.Builder.gatewayId;\nimport static org.jclouds.aws.ec2.options.RouteTableOptions.Builder.dryRun;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.List;\nimport java.util.Random;\n\nimport org.jclouds.apis.BaseApiLiveTest;\nimport org.jclouds.aws.AWSResponseException;\nimport org.jclouds.aws.ec2.AWSEC2Api;\nimport org.jclouds.aws.ec2.domain.InternetGateway;\nimport org.jclouds.aws.ec2.domain.Route;\nimport org.jclouds.aws.ec2.domain.RouteTable;\nimport org.jclouds.aws.ec2.domain.VPC;\nimport org.jclouds.aws.ec2.options.InternetGatewayOptions;\nimport org.jclouds.ec2.domain.Subnet;\nimport org.jclouds.ec2.features.TagApi;\nimport org.testng.Assert;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.ImmutableMultimap;\n\n/**\n * Tests behavior of {@link RouteTableApi}\n */\n@Test(groups = \"live\")\npublic class RouteTableApiLiveTest extends BaseApiLiveTest<AWSEC2Api> {\n\n   // Define -Djclouds.test.region=whatever to test in your preferred region;\n   // defaults to null, jclouds will pick the provider's default region\n   public static final String TEST_REGION = System.getProperty(\"jclouds.test.region\");\n   public static final String TEST_DESTINATION_CIDR = \"172.18.19.0/24\";\n   public static final String VPC_CIDR = \"10.20.30.0/24\";\n   public static final String VPC_SUBNET = \"10.20.30.0/28\";\n\n   public RouteTableApiLiveTest() {\n      provider = \"aws-ec2\";\n   }\n\n   private RouteTableApi routeTableApi;\n   private InternetGatewayApi gwApi;\n   private TagApi tagger;\n   private VPCApi vpcClient;\n   private AWSSubnetApi subnetApi;\n\n   private VPC vpc;\n   private InternetGateway gateway;\n\n   private RouteTable routeTable;\n   private String associationId;\n   private Subnet subnet;\n\n   private String simpleName = RouteTableApiLiveTest.class.getSimpleName() + new Random().nextInt(10000);\n\n   @BeforeClass(groups = {\"integration\", \"live\"})\n   public void setupContext() {\n      routeTableApi = api.getRouteTableApiForRegion(TEST_REGION).get();\n      vpcClient = api.getVPCApi().get();\n      tagger = api.getTagApiForRegion(TEST_REGION).get();\n      gwApi = api.getInternetGatewayApiForRegion(TEST_REGION).get();\n      subnetApi = api.getAWSSubnetApi().get();\n   }\n\n   @Test\n   public void testDescribe() {\n      vpc = vpcClient.createVpc(TEST_REGION, VPC_CIDR);\n      assertNotNull(vpc, \"Failed to create VPC to test attachments\");\n      tagger.applyToResources(ImmutableMap.of(\"Name\", simpleName), ImmutableList.of(vpc.id()));\n\n      // When you create a VPC it automatically gets a route table whose single route has the CIDR of the VPC\n      // and whose \"target\" is \"local\".\n      final FluentIterable<RouteTable> routeTables = routeTableApi.describeRouteTables(TEST_REGION);\n      assertNotNull(routeTables, \"Failed to return list of RouteTables\");\n      Optional<RouteTable> vpcRT = Iterables.tryFind(routeTables, new Predicate<RouteTable>() {\n         @Override public boolean apply(RouteTable input) {\n            return vpc.id().equals(input.vpcId());\n         }\n      });\n      assertTrue(vpcRT.isPresent(), \"Could not find VPC \" + vpc.id() + \" in described route tables\");\n\n      //Now test the Find by Filter version of the describeRouteTables\n      final FluentIterable<RouteTable> routeTablesByFilter = routeTableApi.describeRouteTablesWithFilter(TEST_REGION,\n              ImmutableMultimap.<String, String>builder()\n                      .put(\"vpc-id\", vpc.id())\n                      .build()\n      );\n      assertNotNull(routeTablesByFilter, \"Failed to return list of routeTablesByFilter\");\n      Optional<RouteTable> vpcRTByFilter = Iterables.tryFind(routeTablesByFilter, new Predicate<RouteTable>() {\n         @Override public boolean apply(RouteTable input) {\n            return vpc.id().equals(input.vpcId());\n         }\n      });\n      assertTrue(vpcRTByFilter.isPresent(), \"Could not find VPC \" + vpc.id() + \" in described route tables\");\n\n\n      RouteTable rt = vpcRT.get();\n      assertEquals(rt.associationSet().size(), 1,\n         \"Route for test VPC has wrong number of associations, should be 1: \" + rt.associationSet());\n      assertTrue(rt.associationSet().get(0).main(), \"Association for route \" + rt.id() + \"should be 'main'\");\n      assertEquals(rt.routeSet().size(), 1,\n         \"Wrong number of routes in default route table for VPC \" + vpc.id());\n      final String defaultCidr = rt.routeSet().get(0).destinationCidrBlock();\n      assertEquals(defaultCidr, vpc.cidrBlock(),\n         \"Route in default route table does not match CIDR of VPC, \" + defaultCidr + \" should be \" + vpc.cidrBlock());\n\n   }\n\n   @Test(dependsOnMethods = \"testDescribe\")\n   public void testCreate() {\n\n      // When you create a new route table for the VPC it automatically gets a route to match the VPC CIDR\n      routeTable = routeTableApi.createRouteTable(TEST_REGION, vpc.id());\n      assertNotNull(routeTable, \"Gateway was not successfully created\");\n\n      assertEquals(routeTable.vpcId(), vpc.id(),\n         \"RouteTable VPC ID \" + routeTable.vpcId() + \" does not match VPC's ID \" + vpc.id());\n      final List<Route> routes = routeTable.routeSet();\n      assertEquals(routes.size(), 1, \"Unexpected number of routes in new table: \" + routes.size());\n      assertEquals(routes.get(0).destinationCidrBlock(), vpc.cidrBlock(),\n         \"CIDR for route table \" + routes.get(0).destinationCidrBlock() +\n            \" does not match VPC CIDR\" + vpc.cidrBlock());\n      assertEquals(routes.get(0).state(), Route.RouteState.ACTIVE, \"Route should be active\");\n      assertEquals(routeTable.tags().size(), 0, \"Freshly created routeTable has tags\");\n\n      tagger.applyToResources(ImmutableMap.of(\"Name\", simpleName), ImmutableList.of(routeTable.id()));\n      getAnonymousLogger().info(\"Created routeTable \" +  simpleName + \" with id \" + routeTable.id());\n   }\n\n   @Test(dependsOnMethods = \"testDescribe\")\n   public void testCreateWithOptions() {\n\n     try {\n        routeTableApi.createRouteTable(TEST_REGION, vpc.id(), dryRun());\n        Assert.fail(\"Expected 'DryRunOperation' exception was not thrown\");\n     } catch (AWSResponseException e) {\n        assertDryRun(e);\n     }\n   }\n\n   @Test(dependsOnMethods = \"testCreate\")\n   public void testAssociateWithOptions() {\n      subnet = subnetApi.createSubnetInRegion(TEST_REGION, vpc.id(), VPC_SUBNET);\n      assertNotNull(subnet, \"Failed to create subnet in \" + vpc.id());\n\n      try {\n         routeTableApi.associateRouteTable(TEST_REGION, routeTable.id(), subnet.getSubnetId(), dryRun());\n         Assert.fail(\"Expected 'DryRunOperation' exception was not thrown\");\n      } catch (AWSResponseException e) {\n         assertDryRun(e);\n      }\n   }\n\n   @Test(dependsOnMethods = \"testAssociateWithOptions\")\n   public void testAssociate() {\n      associationId = routeTableApi.associateRouteTable(TEST_REGION, routeTable.id(), subnet.getSubnetId());\n      assertNotNull(associationId,\n         \"Failed to obtain association id for \" + routeTable.id() + \" and \" + subnet.getSubnetId());\n\n      routeTable = routeTableApi.describeRouteTables(TEST_REGION, routeTable.id()).toList().get(0);\n      assertEquals(routeTable.associationSet().size(), 1,\n         \"Could not find expected association in routeTable \" + routeTable.id());\n   }\n\n   @Test(dependsOnMethods = \"testAssociate\")\n   public void testDisassociateWithOptions() {\n      try {\n         routeTableApi.disassociateRouteTable(TEST_REGION, associationId, dryRun());\n         Assert.fail(\"Expected 'DryRunOperation' exception was not thrown\");\n      } catch (AWSResponseException e) {\n         assertDryRun(e);\n      }\n   }\n\n   @Test(dependsOnMethods = \"testDisassociateWithOptions\")\n   public void testDisassociate() {\n      final boolean result = routeTableApi.disassociateRouteTable(TEST_REGION, associationId);\n      assertTrue(result, \"Failed to disassociate \" + associationId + \" from \" + routeTable.id());\n\n      routeTable = routeTableApi.describeRouteTables(TEST_REGION, routeTable.id()).toList().get(0);\n      assertEquals(routeTable.associationSet().size(), 0,\n         \"Found associations where none should exist in  \" + routeTable.id() + \": \" + routeTable.associationSet());\n\n      subnetApi.deleteSubnetInRegion(TEST_REGION, subnet.getSubnetId());\n   }\n\n   @Test(dependsOnMethods = \"testCreate\")\n   public void testCreateRoute() {\n\n      // If you attach an Internet Gateway, Network Interface, or Virtual Private Gateway to the VPC\n      // you can then add a route through it to the route table. Issue a CreateRoute request specifying\n      // the gateway (or network interface id etc.) to route through, and supplying the CIDR range that should\n      // be routed through it. This can be any CIDR.\n\n      gateway = gwApi.createInternetGateway(TEST_REGION, InternetGatewayOptions.NONE);\n      assertNotNull(gateway, \"Gateway was not successfully created\");\n\n      final Boolean attached = gwApi.attachInternetGateway(TEST_REGION, gateway.id(), vpc.id());\n      assertTrue(attached, \"Gateway \" + gateway.id() + \" failed to attach to VPC \" + vpc.id());\n\n      final boolean created = routeTableApi.createRoute(TEST_REGION, routeTable.id(),\n         gatewayId(gateway.id())\n            .destinationCidrBlock(TEST_DESTINATION_CIDR));\n      assertTrue(created, \"Failed to add route to table \" + routeTable.id());\n\n      final ImmutableList<RouteTable> routeTables =\n         routeTableApi.describeRouteTables(TEST_REGION, routeTable.id()).toList();\n      assertEquals(routeTables.size(), 1, \"Could not find existing route table \" + routeTable.id());\n      Optional<Route> optRoute = Iterables.tryFind(routeTables.get(0).routeSet(), new Predicate<Route>() {\n         @Override\n         public boolean apply(Route route) {\n            return route.gatewayId().equals(gateway.id());\n         }\n      });\n      assertTrue(optRoute.isPresent(), \"Could not find route added to gateway \" + gateway.id());\n      Route route = optRoute.get();\n      assertEquals(route.destinationCidrBlock(), TEST_DESTINATION_CIDR,\n         \"CIDR routed through \" + gateway.id() + \" does not match specification \"  + TEST_DESTINATION_CIDR);\n   }\n\n   @Test(dependsOnMethods = \"testCreateRoute\")\n   public void testDeleteRoute() {\n      final boolean deleted =\n         routeTableApi.deleteRoute(TEST_REGION, routeTable.id(), destinationCidrBlock(TEST_DESTINATION_CIDR));\n      assertTrue(deleted, \"Failed to delete \" + TEST_DESTINATION_CIDR + \" route from route table \" + routeTable.id());\n\n      // clean up the test gateway\n      final Boolean cleaned = gwApi.detachInternetGateway(TEST_REGION, gateway.id(), vpc.id());\n      assertTrue(cleaned, \"Failed to delete gateway \" + gateway.id());\n\n      final boolean gatewayDeleted = gwApi.deleteInternetGateway(TEST_REGION, gateway.id());\n      assertTrue(gatewayDeleted, \"Failed to delete test gateway \" + gateway.id());\n   }\n\n   @Test(enabled = false  /* dependsOnMethods = \"testCreateRoute\" */)\n   public void testReplaceRoute() {\n      // TODO:\n      // At present there is support for creating internet gateways and attaching them to VPCs.\n      // However, you can't attach two internet gateways to the same VPC, so the replaceRoute test must replace\n      // the internet gateway target with one of an virtual private gateway, NAT instance,\n      // NAT gateway, VPC peering connection, network interface, or egress-only Internet gateway.\n      // Add this test when e.g. NATGatewayApi is added.\n   }\n\n   @Test(dependsOnMethods = \"testDeleteRoute\")\n   public void testDeleteRouteTableWithOptions() {\n      try {\n         routeTableApi.deleteRouteTable(TEST_REGION, routeTable.id(), dryRun());\n         Assert.fail(\"Expected 'DryRunOperation' exception was not thrown\");\n      } catch (AWSResponseException e) {\n         assertDryRun(e);\n      }\n   }\n\n   @Test(dependsOnMethods = \"testDeleteRouteTableWithOptions\")\n   public void testDeleteRouteTable() {\n\n      final ImmutableList<RouteTable> before =\n         routeTableApi.describeRouteTables(TEST_REGION, routeTable.id()).toList();\n      assertEquals(before.size(), 1, \"Unexpected response to describe of \" + routeTable.id() + \": \" + before);\n      assertEquals(before.get(0).id(), routeTable.id(), \"Wrong table returned for \" + routeTable.id() + \": \" + before);\n\n      final boolean deleted = routeTableApi.deleteRouteTable(TEST_REGION, routeTable.id());\n      assertTrue(deleted, \"Failed to delete route table \" + routeTable.id());\n\n      final ImmutableList<RouteTable> after = routeTableApi.describeRouteTables(TEST_REGION, routeTable.id()).toList();\n      assertEquals(after.size(), 0, \"Unexpected response to describe after deleting \" + routeTable.id() + \": \" + after);\n   }\n\n   @AfterClass(alwaysRun = true)\n   public void cleanup() {\n      if (vpc != null) {\n         assertTrue(vpcClient.deleteVpc(TEST_REGION, vpc.id()));\n      }\n   }\n\n   private void assertDryRun(AWSResponseException e) {\n      assertEquals(e.getError().getCode(), \"DryRunOperation\", \"Expected DryRunOperation but got \" + e.getError());\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/features/RouteTableApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.features;\n\nimport static jakarta.ws.rs.core.Response.Status.PRECONDITION_FAILED;\nimport static org.jclouds.aws.ec2.options.RouteOptions.Builder.destinationCidrBlock;\nimport static org.jclouds.aws.ec2.options.RouteOptions.Builder.gatewayId;\nimport static org.jclouds.aws.ec2.options.RouteTableOptions.Builder.dryRun;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport okhttp3.mockwebserver.MockResponse;\n\nimport org.jclouds.aws.AWSResponseException;\nimport org.jclouds.aws.ec2.domain.Route;\nimport org.jclouds.aws.ec2.domain.RouteTable;\nimport org.jclouds.aws.ec2.internal.BaseAWSEC2ApiMockTest;\nimport org.testng.Assert;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"RouteTableApiMockTest\", singleThreaded = true)\npublic class RouteTableApiMockTest extends BaseAWSEC2ApiMockTest {\n\n   public void describeRouteTables() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION, new MockResponse().setResponseCode(404));\n      final ImmutableList<RouteTable> routeTables = routeTableApi().describeRouteTables(DEFAULT_REGION).toList();\n\n      assertTrue(routeTables.isEmpty(), \"Returned \" + routeTables.size() + \" results for 404 response: \" + routeTables);\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRouteTables\");\n   }\n\n   public void describeRouteTablesNotFound() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(DEFAULT_REGION, \"/describe_route_tables.xml\");\n      final ImmutableList<RouteTable> routeTables = routeTableApi().describeRouteTables(DEFAULT_REGION).toList();\n\n      assertNotNull(routeTables, \"Failed to create route table description object\");\n      assertEquals(routeTables.size(), 3, \"Failed to return all entries from test data, returned: \" + routeTables);\n\n      for (RouteTable table : routeTables) {\n         if (ImmutableList.of(\"rtb-80a3fae4\", \"rtb-d4605bb0\").contains(table.id())) {\n            assertRoutesForNormalVpc(table, table.id());\n         } else if (table.id().equals(\"rtb-e6c98381\")) {\n            assertRoutesForTestVpc(table, table.id());\n         }\n      }\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRouteTables\");\n   }\n\n   public void describeRouteTablesWithInvalidStateValue() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(DEFAULT_REGION, \"/describe_route_tables_invalid.xml\");\n      final ImmutableList<RouteTable> routeTables = routeTableApi().describeRouteTables(DEFAULT_REGION).toList();\n\n      assertNotNull(routeTables, \"Failed to create route table description object\");\n      assertEquals(routeTables.size(), 1, \"Failed to return expected entry from test data, returned: \" + routeTables);\n\n      assertEquals(routeTables.get(0).routeSet().get(0).state(), Route.RouteState.UNRECOGNIZED);\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRouteTables\");\n   }\n\n   private void assertRoutesForNormalVpc(RouteTable table, String id) {\n      assertEquals(table.routeSet().size(), 2, \"Failed to match test data route set size for \" + id);\n      final String actual = table.associationSet().get(0).routeTableId();\n      assertEquals(actual, id, \"Test data mismatch in \" + id + \" association set routeTableId(): \" + actual);\n      assertTrue(table.associationSet().get(0).main(), \"Test data mismatch in \" + id + \" association 'main'\");\n   }\n\n   private void assertRoutesForTestVpc(RouteTable table, String id) {\n      assertEquals(table.routeSet().size(), 1, \"Failed to match test data route set size for \" + id);\n\n      assertEquals(table.routeSet().get(0).destinationCidrBlock(), \"10.20.30.0/24\",\n         \"Mismatch in test data for \" + id + \" route set destinationCidrBlock\");\n      assertEquals(table.routeSet().get(0).gatewayId(), \"local\",\n         \"Mismatch in test data for \" + id + \" route set gatewayId\");\n      assertEquals(table.routeSet().get(0).state(), Route.RouteState.ACTIVE,\n         \"Mismatch in test data for \" + id + \" route set state\");\n\n      final String actual = table.associationSet().get(0).routeTableId();\n      assertEquals(actual, id, \"Test data mismatch in \" + id + \" association set routeTableId(): \" + actual);\n      assertTrue(table.associationSet().get(0).main(), \"Test data mismatch in \" + id + \" association 'main'\");\n   }\n\n   public void createRouteTable() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(DEFAULT_REGION, \"/create_route_table.xml\");\n      RouteTable result = routeTableApi().createRouteTable(DEFAULT_REGION, \"vpc-1a2b3c4d\");\n\n      assertNotNull(result, \"Failed to create RouteTable object\");\n      assertEquals(result.id(), \"rtb-8bda6cef\", \"Gateway id does not match mock data: \" + result.id());\n      assertEquals(result.routeSet().size(), 2, \"Should have 2 routes\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=CreateRouteTable&VpcId=vpc-1a2b3c4d\");\n   }\n\n   public void createRouteTableWithOptions() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(PRECONDITION_FAILED, DEFAULT_REGION, \"/dry_run.xml\");\n      try {\n         routeTableApi().createRouteTable(DEFAULT_REGION, \"vpc-1a2b3c4d\", dryRun());\n         Assert.fail(\"Expected 'DryRunOperation' exception was not thrown\");\n      } catch (AWSResponseException e) {\n         assertDryRun(e);\n      }\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=CreateRouteTable&VpcId=vpc-1a2b3c4d&DryRun=true\");\n   }\n\n   public void deleteRouteTable() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(DEFAULT_REGION, \"/delete_route_table.xml\");\n      final boolean deleted = routeTableApi().deleteRouteTable(DEFAULT_REGION, \"rtb-8bda6cef\");\n      assertTrue(deleted, \"Failed to match 'true' data in test response\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DeleteRouteTable&RouteTableId=rtb-8bda6cef\");\n   }\n\n   public void deleteRouteTableWithOptions() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(PRECONDITION_FAILED, DEFAULT_REGION, \"/dry_run.xml\");\n      try {\n         routeTableApi().deleteRouteTable(DEFAULT_REGION, \"rtb-8bda6cef\", dryRun());\n         Assert.fail(\"Expected 'DryRunOperation' exception was not thrown\");\n      } catch (AWSResponseException e) {\n         assertDryRun(e);\n      }\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DeleteRouteTable&RouteTableId=rtb-8bda6cef&DryRun=true\");\n   }\n\n   public void deleteRouteTableNotFound() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION, new MockResponse().setResponseCode(404));\n      final boolean deleted = routeTableApi().deleteRouteTable(DEFAULT_REGION, \"rtb-8bda6cef\");\n      assertFalse(deleted, \"Non-existent table reported as successfully deleted\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DeleteRouteTable&RouteTableId=rtb-8bda6cef\");\n   }\n\n   public void associateRouteTable() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(DEFAULT_REGION, \"/associate_route_table.xml\");\n      final String associationId = routeTableApi().associateRouteTable(DEFAULT_REGION, \"rtb-8c95c0eb\", \"subnet-6986410e\");\n      assertEquals(associationId, \"rtbassoc-fb7fed9d\", \"Failed to associate route\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=AssociateRouteTable&RouteTableId=rtb-8c95c0eb&SubnetId=subnet-6986410e\");\n   }\n\n   public void associateRouteTableNotFound() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION, new MockResponse().setResponseCode(404));\n      final String associationId = routeTableApi().associateRouteTable(DEFAULT_REGION, \"rtb-8c95c0eb\", \"subnet-6986410e\");\n      assertNull(associationId, \"Returned id for non-existent route table: \" + associationId);\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=AssociateRouteTable&RouteTableId=rtb-8c95c0eb&SubnetId=subnet-6986410e\");\n   }\n\n   public void associateRouteTableWithOptions() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(PRECONDITION_FAILED, DEFAULT_REGION, \"/dry_run.xml\");\n      try {\n         routeTableApi().associateRouteTable(DEFAULT_REGION, \"rtb-8c95c0eb\", \"subnet-6986410e\", dryRun());\n      } catch (AWSResponseException e) {\n         assertDryRun(e);\n      }\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION,\n         \"Action=AssociateRouteTable&RouteTableId=rtb-8c95c0eb&SubnetId=subnet-6986410e&DryRun=true\");\n   }\n\n   public void disassociateRouteTable() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(DEFAULT_REGION, \"/disassociate_route_table.xml\");\n      final boolean result = routeTableApi().disassociateRouteTable(DEFAULT_REGION, \"rtbassoc-fb7fed9d\");\n      assertTrue(result, \"Failed to disassociate route\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DisassociateRouteTable&AssociationId=rtbassoc-fb7fed9d\");\n   }\n\n   public void disassociateRouteTableNotFound() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION, new MockResponse().setResponseCode(404));\n      final boolean result = routeTableApi().disassociateRouteTable(DEFAULT_REGION, \"rtbassoc-fb7fed9d\");\n      assertFalse(result, \"Non-existent table reported as successfully disassociated\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DisassociateRouteTable&AssociationId=rtbassoc-fb7fed9d\");\n   }\n\n   public void disassociateRouteTablewithOptions() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(PRECONDITION_FAILED, DEFAULT_REGION, \"/dry_run.xml\");\n      try {\n         routeTableApi().disassociateRouteTable(DEFAULT_REGION, \"rtbassoc-fb7fed9d\", dryRun());\n      } catch (AWSResponseException e) {\n         assertDryRun(e);\n      }\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DisassociateRouteTable&AssociationId=rtbassoc-fb7fed9d&DryRun=true\");\n   }\n\n   public void createRoute() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(DEFAULT_REGION, \"/create_route.xml\");\n      final boolean created = routeTableApi().createRoute(DEFAULT_REGION, \"rtb-a77f2ac0\",\n            gatewayId(\"igw-97e68af3\").destinationCidrBlock(\"172.18.19.0/24\"));\n      assertTrue(created, \"Failed to match 'true' in test data response\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION,\n         \"Action=CreateRoute&RouteTableId=rtb-a77f2ac0&GatewayId=igw-97e68af3&DestinationCidrBlock=172.18.19.0/24\");\n   }\n\n   public void createRouteNotFound() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(DEFAULT_REGION, \"/create_route.xml\");\n      final boolean created = routeTableApi().createRoute(DEFAULT_REGION, \"rtb-a77f2ac0\",\n            gatewayId(\"igw-97e68af3\").destinationCidrBlock(\"172.18.19.0/24\"));\n      assertTrue(created, \"Failed to match 'true' in test data response\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION,\n         \"Action=CreateRoute&RouteTableId=rtb-a77f2ac0&GatewayId=igw-97e68af3&DestinationCidrBlock=172.18.19.0/24\");\n   }\n\n   public void replaceRoute() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION, new MockResponse().setResponseCode(404));\n      final boolean created = routeTableApi().replaceRoute(DEFAULT_REGION, \"rtb-a77f2ac0\",\n         gatewayId(\"vgw-1d00376e\").destinationCidrBlock(\"172.18.19.0/24\"));\n      assertFalse(created, \"Reported successful replace of route in non-existent route table\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION,\n         \"Action=ReplaceRoute&RouteTableId=rtb-a77f2ac0&GatewayId=vgw-1d00376e&DestinationCidrBlock=172.18.19.0/24\");\n   }\n\n   public void replaceRouteNotFound() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(DEFAULT_REGION, \"/replace_route.xml\");\n      final boolean created = routeTableApi().replaceRoute(DEFAULT_REGION, \"rtb-a77f2ac0\",\n         gatewayId(\"vgw-1d00376e\").destinationCidrBlock(\"172.18.19.0/24\"));\n      assertTrue(created, \"Failed to match 'true' in test data response\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION,\n         \"Action=ReplaceRoute&RouteTableId=rtb-a77f2ac0&GatewayId=vgw-1d00376e&DestinationCidrBlock=172.18.19.0/24\");\n   }\n\n   public void deleteRoute() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(DEFAULT_REGION, \"/delete_route.xml\");\n      final boolean deleted = routeTableApi().deleteRoute(DEFAULT_REGION, \"rtb-a77f2ac0\",\n         destinationCidrBlock(\"172.18.19.0/24\"));\n      assertTrue(deleted, \"Failed to match 'true' in test data response\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DeleteRoute&RouteTableId=rtb-a77f2ac0&DestinationCidrBlock=172.18.19.0/24\");\n   }\n\n   public void deleteRouteNotFound() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION, new MockResponse().setResponseCode(404));\n      final boolean deleted = routeTableApi().deleteRoute(DEFAULT_REGION, \"rtb-a77f2ac0\",\n         destinationCidrBlock(\"172.18.19.0/24\"));\n      assertFalse(deleted, \"Reported successful delete of route in non-existent route table\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DeleteRoute&RouteTableId=rtb-a77f2ac0&DestinationCidrBlock=172.18.19.0/24\");\n   }\n\n   private void assertDryRun(AWSResponseException e) {\n      assertEquals(e.getError().getCode(), \"DryRunOperation\", \"Expected DryRunOperation but got \" + e.getError());\n   }\n\n   private RouteTableApi routeTableApi() {\n      return api().getRouteTableApi().get();\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/features/SpotInstanceApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.features;\n\nimport static com.google.common.base.Predicates.in;\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static org.jclouds.aws.ec2.options.DescribeSpotPriceHistoryOptions.Builder.from;\nimport static org.jclouds.aws.ec2.options.RequestSpotInstancesOptions.Builder.launchGroup;\nimport static org.jclouds.util.Predicates2.retry;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.Date;\nimport java.util.Set;\nimport java.util.SortedSet;\nimport java.util.concurrent.TimeUnit;\n\nimport org.jclouds.aws.AWSResponseException;\nimport org.jclouds.aws.domain.Region;\nimport org.jclouds.aws.ec2.AWSEC2Api;\nimport org.jclouds.aws.ec2.domain.AWSRunningInstance;\nimport org.jclouds.aws.ec2.domain.LaunchSpecification;\nimport org.jclouds.aws.ec2.domain.Spot;\nimport org.jclouds.aws.ec2.domain.SpotInstanceRequest;\nimport org.jclouds.aws.ec2.predicates.SpotInstanceRequestActive;\nimport org.jclouds.compute.internal.BaseComputeServiceContextLiveTest;\nimport org.jclouds.ec2.domain.InstanceType;\nimport org.jclouds.ec2.domain.Reservation;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSortedSet;\n\n/**\n * Tests behavior of {@code SpotInstanceApi}\n */\n@Test(groups = \"live\", singleThreaded = true)\npublic class SpotInstanceApiLiveTest  extends BaseComputeServiceContextLiveTest {\n   public SpotInstanceApiLiveTest() {\n      provider = \"aws-ec2\";\n   }\n\n   private static final int SPOT_DELAY_SECONDS = 600;\n   private AWSEC2Api client;\n   private Predicate<SpotInstanceRequest> activeTester;\n   private Set<SpotInstanceRequest> requests;\n   private AWSRunningInstance instance;\n   private long start;\n\n   @Override\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   public void setupContext() {\n      super.setupContext();\n      client = view.unwrapApi(AWSEC2Api.class);\n      activeTester = retry(new SpotInstanceRequestActive(client), SPOT_DELAY_SECONDS, 1, 1, SECONDS);\n   }\n\n   @Test\n   public void testDescribeSpotRequestsInRegion() {\n      for (String region : Region.DEFAULT_REGIONS) {\n         SortedSet<SpotInstanceRequest> allResults = ImmutableSortedSet.copyOf(client.getSpotInstanceApi().get()\n                  .describeSpotInstanceRequestsInRegion(region));\n         assertNotNull(allResults);\n         if (allResults.size() >= 1) {\n            SpotInstanceRequest request = allResults.last();\n            SortedSet<SpotInstanceRequest> result = ImmutableSortedSet.copyOf(client.getSpotInstanceApi().get()\n                     .describeSpotInstanceRequestsInRegion(region, request.getId()));\n            assertNotNull(result);\n            SpotInstanceRequest compare = result.last();\n            assertEquals(compare, request);\n         }\n      }\n\n   }\n\n   @Test\n   public void testDescribeSpotRequestsInRegionFilter() {\n      for (String region : Region.DEFAULT_REGIONS) {\n         SortedSet<SpotInstanceRequest> allResults = ImmutableSortedSet.copyOf(client.getSpotInstanceApi().get()\n                 .describeSpotInstanceRequestsInRegion(region));\n         assertNotNull(allResults);\n         if (allResults.size() >= 1) {\n            SpotInstanceRequest request = allResults.last();\n            SortedSet<SpotInstanceRequest> result = ImmutableSortedSet.copyOf(client.getSpotInstanceApi().get()\n                    .describeSpotInstanceRequestsInRegionWithFilter(region,\n                            ImmutableMultimap.<String, String>builder()\n                                    .put(\"spot-instance-request-id\", request.getId()).build()));\n\n            assertNotNull(result);\n            SpotInstanceRequest compare = result.last();\n            assertEquals(compare, request);\n         }\n      }\n\n   }\n\n   @Test(expectedExceptions = AWSResponseException.class)\n   public void testDescribeSpotRequestsInRegionFilterInvalid() {\n      for (String region : Region.DEFAULT_REGIONS) {\n         SortedSet<SpotInstanceRequest> allResults = ImmutableSortedSet.copyOf(client.getSpotInstanceApi().get()\n                 .describeSpotInstanceRequestsInRegion(region));\n         assertNotNull(allResults);\n         if (allResults.size() >= 1) {\n            SpotInstanceRequest request = allResults.last();\n            SortedSet<SpotInstanceRequest> result = ImmutableSortedSet.copyOf(client.getSpotInstanceApi().get()\n                    .describeSpotInstanceRequestsInRegionWithFilter(region,\n                            ImmutableMultimap.<String, String>builder()\n                                    .put(\"invalid-filter\", request.getId()).build()));\n         }\n      }\n\n   }\n\n   @Test\n   public void testDescribeSpotPriceHistoryInRegion() {\n      for (String region : Region.DEFAULT_REGIONS) {\n         Set<Spot> spots = client.getSpotInstanceApi().get().describeSpotPriceHistoryInRegion(region, from(new Date()));\n         assertNotNull(spots);\n         assert !spots.isEmpty();\n         for (Spot spot : spots) {\n            assert spot.getSpotPrice() > 0 : spots;\n            assertEquals(spot.getRegion(), region);\n            assert in(\n                    ImmutableSet.of(\"Linux/UNIX\", \"Linux/UNIX (Amazon VPC)\", \"SUSE Linux\", \"SUSE Linux (Amazon VPC)\",\n                              \"Windows\", \"Windows (Amazon VPC)\")).apply(spot.getProductDescription()) : spot;\n            assert // sometimes get D2 type, which we don't yet enumerate\n                    spot.getInstanceType().startsWith(\"d2.\") ||\n                    in(ImmutableSet.of(\"c1.medium\", \"c1.xlarge\", \"cc1.4xlarge\", \"cg1.4xlarge\", \"cc2.8xlarge\", \"m1.large\",\n                              \"m1.small\", \"m1.medium\", \"m1.xlarge\", \"m2.2xlarge\", \"m2.4xlarge\", \"m2.xlarge\", \"m3.xlarge\",\n                              \"m3.2xlarge\", \"t1.micro\", \"cr1.8xlarge\", \"c4.large\", \"c4.xlarge\", \"c4.2xlarge\", \"c4.4xlarge\",\n                              \"c4.8xlarge\")).apply(spot.getInstanceType()) : spot;\n         }\n      }\n\n   }\n\n   @Test(enabled = true)\n   public void testCreateSpotInstance() {\n      String launchGroup = PREFIX + \"1\";\n      for (String region : Region.DEFAULT_REGIONS)\n         for (SpotInstanceRequest request : client.getSpotInstanceApi().get().describeSpotInstanceRequestsInRegion(\n                  region))\n            if (launchGroup.equals(request.getLaunchGroup()))\n               client.getSpotInstanceApi().get().cancelSpotInstanceRequestsInRegion(region, request.getId());\n\n      start = System.currentTimeMillis();\n\n      requests = client.getSpotInstanceApi().get().requestSpotInstancesInRegion(\n               \"sa-east-1\",\n               0.09f,\n               1,\n               LaunchSpecification.builder().imageId(\"ami-3e3be423\").instanceType(InstanceType.M1_SMALL).build(),\n               launchGroup(launchGroup).availabilityZoneGroup(launchGroup).validFrom(\n                        new Date(System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(2))).validUntil(\n                        new Date(System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(SPOT_DELAY_SECONDS))));\n      assertNotNull(requests);\n\n      for (SpotInstanceRequest request : requests)\n         verifySpotInstance(request);\n   }\n\n   private void verifySpotInstance(SpotInstanceRequest request) {\n      SpotInstanceRequest spot = refresh(request);\n      assertNotNull(spot);\n      assertEquals(spot, request);\n      assert activeTester.apply(request) : refresh(request);\n      System.out.println(System.currentTimeMillis() - start);\n      spot = refresh(request);\n      assert spot.getInstanceId() != null : spot;\n      Reservation<? extends AWSRunningInstance> reservation = getOnlyElement(client.getInstanceApi().get().describeInstancesInRegion(spot.getRegion(),\n               spot.getInstanceId()));\n      instance = getOnlyElement(reservation);\n      assertEquals(instance.getSpotInstanceRequestId(), spot.getId());\n   }\n\n   public SpotInstanceRequest refresh(SpotInstanceRequest request) {\n      return getOnlyElement(client.getSpotInstanceApi().get().describeSpotInstanceRequestsInRegion(request.getRegion(),\n               request.getId()));\n   }\n\n   public static final String PREFIX = System.getProperty(\"user.name\") + \"ec2\";\n\n   @Override\n   @AfterClass(groups = { \"integration\", \"live\" })\n   protected void tearDownContext() {\n      if (requests != null) {\n         for (SpotInstanceRequest request : requests)\n            client.getSpotInstanceApi().get().cancelSpotInstanceRequestsInRegion(request.getRegion(), request.getId());\n         // assert deletedTester.apply(request) : request;\n      }\n      if (instance != null) {\n         client.getInstanceApi().get().terminateInstancesInRegion(instance.getRegion(), instance.getId());\n      }\n      super.tearDownContext();\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/features/SpotInstanceApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.features;\n\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static org.jclouds.aws.ec2.options.DescribeSpotPriceHistoryOptions.Builder.from;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Date;\nimport java.util.Set;\n\nimport okhttp3.mockwebserver.MockResponse;\n\nimport org.jclouds.aws.ec2.domain.Spot;\nimport org.jclouds.aws.ec2.domain.SpotInstanceRequest;\nimport org.jclouds.aws.ec2.internal.BaseAWSEC2ApiMockTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\n\n   @Test(groups = \"unit\", testName = \"SpotInstanceApiMockTest\", singleThreaded = true)\n   public class SpotInstanceApiMockTest extends BaseAWSEC2ApiMockTest {\n\n      public void describeSpotInstanceRequestsInRegionWithFilter() throws Exception {\n         enqueueRegions(DEFAULT_REGION);\n         enqueueXml(DEFAULT_REGION, \"/describe_spot_instance.xml\");\n\n         SpotInstanceRequest result = getOnlyElement(spotApi()\n               .describeSpotInstanceRequestsInRegionWithFilter(DEFAULT_REGION,\n                     ImmutableMultimap.of(\"instance-id\", \"i-ef308e8e\")));\n\n         assertEquals(result.getId(), \"sir-1ede0012\");\n\n         assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n         assertPosted(DEFAULT_REGION, \"Action=DescribeSpotInstanceRequests&Filter.1.Name=instance-id&Filter.1.Value.1=i-ef308e8e\");\n      }\n\n      public void describeSpotInstanceRequestsInRegionWithFilter_404() throws Exception {\n         enqueueRegions(DEFAULT_REGION);\n         enqueue(DEFAULT_REGION, new MockResponse().setResponseCode(404));\n\n         assertEquals(spotApi().describeSpotInstanceRequestsInRegionWithFilter(DEFAULT_REGION,\n               ImmutableMultimap.of(\"instance-id\", \"i-ef308e8e\")), ImmutableSet.of());\n\n         assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n         assertPosted(DEFAULT_REGION, \"Action=DescribeSpotInstanceRequests&Filter.1.Name=instance-id&Filter.1.Value.1=i-ef308e8e\");\n      }\n\n      public void cancelSpotInstanceRequestsInRegion() throws Exception {\n         enqueueRegions(DEFAULT_REGION);\n         enqueue(DEFAULT_REGION, new MockResponse());\n\n         spotApi().cancelSpotInstanceRequestsInRegion(DEFAULT_REGION, \"sir-f4d44212\");\n\n         assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n         assertPosted(DEFAULT_REGION, \"Action=CancelSpotInstanceRequests&SpotInstanceRequestId.1=sir-f4d44212\");\n      }\n\n      public void cancelSpotInstanceRequestsInRegion_404() throws Exception {\n         enqueueRegions(DEFAULT_REGION);\n         enqueue(DEFAULT_REGION, new MockResponse().setResponseCode(404));\n\n         spotApi().cancelSpotInstanceRequestsInRegion(DEFAULT_REGION, \"sir-f4d44212\");\n\n         assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n         assertPosted(DEFAULT_REGION, \"Action=CancelSpotInstanceRequests&SpotInstanceRequestId.1=sir-f4d44212\");\n      }\n\n      public void describeSpotPriceHistoryInRegion() throws Exception {\n         enqueueRegions(DEFAULT_REGION);\n         enqueueXml(DEFAULT_REGION, \"/describe_spot_price_history.xml\");\n\n         Set<Spot> result = spotApi().describeSpotPriceHistoryInRegion(DEFAULT_REGION);\n\n         assertEquals(result.size(), 3);\n\n         assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n         assertPosted(DEFAULT_REGION, \"Action=DescribeSpotPriceHistory\");\n      }\n\n      public void describeSpotPriceHistoryInRegion_404() throws Exception {\n         enqueueRegions(DEFAULT_REGION);\n         enqueue(DEFAULT_REGION, new MockResponse().setResponseCode(404));\n\n         Set<Spot> result = spotApi().describeSpotPriceHistoryInRegion(DEFAULT_REGION);\n\n         assertTrue(result.isEmpty());\n\n         assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n         assertPosted(DEFAULT_REGION, \"Action=DescribeSpotPriceHistory\");\n      }\n\n      public void describeSpotPriceHistoryInRegionOptions() throws Exception {\n         enqueueRegions(DEFAULT_REGION);\n         enqueueXml(DEFAULT_REGION, \"/describe_spot_price_history.xml\");\n\n         Date from = new Date(12345678910L);\n         Date to = new Date(1234567891011L);\n\n         Set<Spot> result = spotApi().describeSpotPriceHistoryInRegion(DEFAULT_REGION,\n               from(from).to(to).productDescription(\"description\").instanceType(\"m1.small\"));\n\n         assertEquals(result.size(), 3);\n\n         assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n         assertPosted(DEFAULT_REGION, \"Action=DescribeSpotPriceHistory&StartTime=1970-05-23T21%3A21%3A18.910Z&EndTime=2009-02-13T23%3A31%3A31.011Z&ProductDescription=description&InstanceType.1=m1.small\");\n      }\n\n      private SpotInstanceApi spotApi() {\n         return api().getSpotInstanceApi().get();\n      }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/features/TagSecurityGroupLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.features;\n\nimport static org.jclouds.ec2.domain.Tag.ResourceType.SECURITY_GROUP;\n\nimport org.jclouds.aws.ec2.AWSEC2Api;\nimport org.jclouds.ec2.features.internal.BaseTagApiLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Iterables;\n\n@Test(groups = \"live\", singleThreaded = true)\npublic class TagSecurityGroupLiveTest extends BaseTagApiLiveTest {\n   public TagSecurityGroupLiveTest() {\n      provider = \"aws-ec2\";\n   }\n\n   @Override\n   protected Resource createResourceForTagging(String prefix) {\n      try {\n         return new Resource(securityGroupApi().createSecurityGroupInRegionAndReturnId(null, prefix, prefix),\n               SECURITY_GROUP);\n      } catch (IllegalStateException e) {\n         return new Resource(Iterables.get(securityGroupApi().describeSecurityGroupsInRegion(null, prefix), 0).getId(),\n               SECURITY_GROUP);\n      }\n   }\n\n   @Override\n   protected void cleanupResource(Resource resource) {\n      securityGroupApi().deleteSecurityGroupInRegionById(null, resource.id);\n   }\n\n   private AWSSecurityGroupApi securityGroupApi() {\n      return AWSEC2Api.class.cast(api).getSecurityGroupApi().get();\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/features/VPCApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.features;\n\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.aws.ec2.AWSEC2Api;\nimport org.jclouds.aws.ec2.domain.VPC;\nimport org.jclouds.aws.ec2.options.CreateVpcOptions;\nimport org.jclouds.compute.internal.BaseComputeServiceContextLiveTest;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.FluentIterable;\n\n/**\n * Tests behavior of {@code VPCApi}\n */\n@Test(groups = \"live\", singleThreaded = true)\npublic class VPCApiLiveTest extends BaseComputeServiceContextLiveTest {\n   public VPCApiLiveTest() {\n      provider = \"aws-ec2\";\n   }\n\n   private VPCApi client;\n   private VPC vpc;\n\n   @Override\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   public void setupContext() {\n      super.setupContext();\n      client = view.unwrapApi(AWSEC2Api.class).getVPCApi().get();\n   }\n\n   @Override\n   @AfterClass(groups = { \"integration\", \"live\" })\n   public void tearDownContext() {\n      try {\n         if (vpc != null) {\n            client.deleteVpc(null, vpc.id());\n         }\n      } finally {\n         super.tearDownContext();\n      }\n   }\n\n   @Test\n   public void testCreate() {\n      vpc = client.createVpc(null, \"10.0.0.0/16\", CreateVpcOptions.NONE);\n      assertNotNull(vpc);\n   }\n\n   @Test(dependsOnMethods = \"testCreate\")\n   public void testGet() {\n      FluentIterable<VPC> vpcs = client.describeVpcsInRegion(null, vpc.id());\n      assertTrue(vpcs.toList().size() == 1);\n   }\n\n   @Test(dependsOnMethods = \"testCreate\")\n   public void testList() {\n      FluentIterable<VPC> vpcs = client.describeVpcsInRegion(null);\n      assertFalse(vpcs.toList().isEmpty());\n   }\n\n   @Test(dependsOnMethods = {\"testList\", \"testGet\"}, alwaysRun = true)\n   public void testDelete() {\n      if (vpc != null) {\n         String vpcId = vpc.id();\n         vpc = null;\n         assertTrue(client.deleteVpc(null, vpcId));\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/features/VPCApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport okhttp3.mockwebserver.MockResponse;\n\nimport org.jclouds.aws.ec2.domain.VPC;\nimport org.jclouds.aws.ec2.internal.BaseAWSEC2ApiMockTest;\nimport org.jclouds.aws.ec2.options.CreateVpcOptions;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\", testName = \"VPCApiMockTest\", singleThreaded = true)\npublic class VPCApiMockTest extends BaseAWSEC2ApiMockTest {\n\n   public void createVpc() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(DEFAULT_REGION, \"/create_vpc.xml\");\n      VPC result = vpcApi().createVpc(DEFAULT_REGION, \"10.0.0.0/16\", CreateVpcOptions.NONE);\n\n      assertNotNull(result);\n      assertEquals(result.id(), \"vpc-1a2b3c4d\");\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=CreateVpc&CidrBlock=10.0.0.0/16\");\n   }\n\n   public void describeVpcsInRegion() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(DEFAULT_REGION, \"/describe_vpcs.xml\");\n      FluentIterable<VPC> result = vpcApi().describeVpcsInRegion(DEFAULT_REGION);\n\n      assertFalse(result.isEmpty());\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeVpcs\");\n   }\n\n   public void describeVpcsInRegionReturns404() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION, new MockResponse().setResponseCode(404));\n\n      assertEquals(vpcApi().describeVpcsInRegion(DEFAULT_REGION), FluentIterable.from(ImmutableSet.of()));\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DescribeVpcs\");\n   }\n\n   public void deleteVpc() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueueXml(DEFAULT_REGION, \"/delete_vpc.xml\");\n\n      assertTrue(vpcApi().deleteVpc(DEFAULT_REGION, \"vpc-id\"));\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DeleteVpc&VpcId=vpc-id\");\n   }\n\n   public void deleteVpcReturns404() throws Exception {\n      enqueueRegions(DEFAULT_REGION);\n      enqueue(DEFAULT_REGION, new MockResponse().setResponseCode(404));\n\n      assertFalse(vpcApi().deleteVpc(DEFAULT_REGION, \"vpc-id\"));\n\n      assertPosted(DEFAULT_REGION, \"Action=DescribeRegions\");\n      assertPosted(DEFAULT_REGION, \"Action=DeleteVpc&VpcId=vpc-id\");\n   }\n\n   private VPCApi vpcApi() {\n      return api().getVPCApi().get();\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/functions/ImportOrReturnExistingKeypairTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.functions;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.jclouds.ssh.SshKeys.fingerprintPublicKey;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.aws.ec2.AWSEC2Api;\nimport org.jclouds.aws.ec2.features.AWSKeyPairApi;\nimport org.jclouds.ec2.domain.KeyPair;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\")\npublic class ImportOrReturnExistingKeypairTest {\n   private static final String PUBLIC_KEY = \"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCcm8DjTHg4r72dVhNLQ33XpUyMLr+ph78i4NR3LqF1bXDP0g4xNLcI/GUTQq6g07X8zs7vIWyjoitqBPFSQ2onaZQ6pXQF/QISRQgrN5hEZ+nH5Aw+isdstBeOMWKdYrCJtm6/qWq2+rByyuNbtulazP3H7SqoozSjRSGNQyFNGpmhjGgTbNQftYDwlFq0T9tCSO/+dYF8j79bNIOEmfsCMiqXQ13hD5vGiEgkRm7zIPDUfpOl3ubDzebpRgGTh5kfv2vd3Z665AxQoi6fItvDu80knyphMlC41giIm5YqfPOPG4lR+6aF06p+NKhvOeECNMtRsD9u1kKJD9NqxXhx\";\n\n   private static final KeyPair pair = KeyPair.builder().region(\"region\").keyName(\"jclouds#group\").sha1OfPrivateKey(\n            \"foo\").build();\n   private static final KeyPair pairWithFingerprint = pair.toBuilder().fingerprint(fingerprintPublicKey(PUBLIC_KEY))\n            .build();\n\n   @Test\n   public void testApply() {\n      AWSEC2Api client = createMock(AWSEC2Api.class);\n      AWSKeyPairApi keyApi = createMock(AWSKeyPairApi.class);\n\n      expect(client.getKeyPairApi()).andReturn((Optional) Optional.of(keyApi)).atLeastOnce();\n\n      expect(keyApi.importKeyPairInRegion(\"region\", \"jclouds#group\", PUBLIC_KEY)).andReturn(pair);\n\n      replay(client);\n      replay(keyApi);\n\n      ImportOrReturnExistingKeypair parser = new ImportOrReturnExistingKeypair(client);\n\n      assertEquals(parser.importOrReturnExistingKeypair(\"region\", \"group\", PUBLIC_KEY), pairWithFingerprint);\n\n      verify(client);\n      verify(keyApi);\n   }\n\n   @Test\n   public void testApplyWithIllegalStateExceptionReturnsExistingKey() {\n      AWSEC2Api client = createMock(AWSEC2Api.class);\n      AWSKeyPairApi keyApi = createMock(AWSKeyPairApi.class);\n\n      expect(client.getKeyPairApi()).andReturn((Optional) Optional.of(keyApi)).atLeastOnce();\n\n      expect(keyApi.importKeyPairInRegion(\"region\", \"jclouds#group\", PUBLIC_KEY)).andThrow(\n               new IllegalStateException());\n      expect(keyApi.describeKeyPairsInRegion(\"region\", \"jclouds#group\")).andReturn(ImmutableSet.of(pair));\n\n      replay(client);\n      replay(keyApi);\n\n      ImportOrReturnExistingKeypair parser = new ImportOrReturnExistingKeypair(client);\n\n      // enriching to include the ssh fingerprint so that ssh logs are easier to correlate\n      assertEquals(parser.importOrReturnExistingKeypair(\"region\", \"group\", PUBLIC_KEY), pairWithFingerprint);\n\n      verify(client);\n      verify(keyApi);\n\n   }\n\n   @Test\n   public void testApplyWithIllegalStateExceptionRetriesWhenExistingKeyNotFound() {\n      AWSEC2Api client = createMock(AWSEC2Api.class);\n      AWSKeyPairApi keyApi = createMock(AWSKeyPairApi.class);\n\n      expect(client.getKeyPairApi()).andReturn((Optional) Optional.of(keyApi)).atLeastOnce();\n\n      expect(keyApi.importKeyPairInRegion(\"region\", \"jclouds#group\", PUBLIC_KEY)).andThrow(\n               new IllegalStateException());\n      expect(keyApi.describeKeyPairsInRegion(\"region\", \"jclouds#group\")).andReturn(ImmutableSet.<KeyPair> of());\n      expect(keyApi.importKeyPairInRegion(\"region\", \"jclouds#group\", PUBLIC_KEY)).andThrow(\n               new IllegalStateException());\n      expect(keyApi.describeKeyPairsInRegion(\"region\", \"jclouds#group\")).andReturn(ImmutableSet.<KeyPair> of(pair));\n\n      replay(client);\n      replay(keyApi);\n\n      ImportOrReturnExistingKeypair parser = new ImportOrReturnExistingKeypair(client);\n\n      assertEquals(parser.importOrReturnExistingKeypair(\"region\", \"group\", PUBLIC_KEY), pairWithFingerprint);\n\n      verify(client);\n      verify(keyApi);\n\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/functions/SpotInstanceRequestToAWSRunningInstanceTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.aws.ec2.domain.AWSRunningInstance;\nimport org.jclouds.aws.ec2.domain.LaunchSpecification;\nimport org.jclouds.aws.ec2.domain.MonitoringState;\nimport org.jclouds.aws.ec2.domain.SpotInstanceRequest;\nimport org.jclouds.aws.ec2.domain.SpotInstanceRequest.State;\nimport org.jclouds.aws.ec2.domain.SpotInstanceRequest.Type;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.ec2.domain.Hypervisor;\nimport org.jclouds.ec2.domain.InstanceState;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code SpotInstanceRequestToAWSRunningInstance}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"SpotInstanceRequestToAWSRunningInstanceTest\")\npublic class SpotInstanceRequestToAWSRunningInstanceTest {\n\n   public void testConvert() {\n\n      SpotInstanceRequest input = SpotInstanceRequest\n            .builder()\n            .region(\"us-east-1\")\n            .id(\"sir-228e6406\")\n            .spotPrice(0.001f)\n            .type(Type.ONE_TIME)\n            .state(State.OPEN)\n            .rawState(\"open\")\n            .launchSpecification(\n                  LaunchSpecification.builder().imageId(\"ami-595a0a1c\").securityGroupName(\"default\")\n                        .instanceType(\"m1.large\").mapNewVolumeToDevice(\"/dev/sda1\", 1, true)\n                        .mapEBSSnapshotToDevice(\"/dev/sda2\", \"snap-1ea27576\", 1, true)\n                        .mapEphemeralDeviceToDevice(\"/dev/sda3\", \"vre1\").monitoringEnabled(false).build())\n            .createTime(new SimpleDateFormatDateService().iso8601DateParse(\"2011-03-08T03:30:36.000Z\"))\n            .productDescription(\"Linux/UNIX\")\n            .tag(\"foo\", \"bar\")\n            .tag(\"empty\", \"\")\n            .build();\n\n      assertEquals(\n            new SpotInstanceRequestToAWSRunningInstance().apply(input).toString(),\n            AWSRunningInstance.builder().region(\"us-east-1\").instanceId(\"sir-228e6406\")\n                  .spotInstanceRequestId(\"sir-228e6406\").instanceState(InstanceState.PENDING)\n                  .rawState(\"open\").imageId(\"ami-595a0a1c\")\n                  .groupName(\"default\").instanceType(\"m1.large\")\n                  .tag(\"foo\", \"bar\")\n                  .tag(\"empty\", \"\")\n                  .hypervisor(Hypervisor.XEN)\n                  .monitoringState(MonitoringState.DISABLED).build().toString());\n   }\n\n   public void testConvertWhenNotOpenReturnsNull() {\n\n      assertEquals(\n            new SpotInstanceRequestToAWSRunningInstance().apply(SpotInstanceRequest.builder().region(\"us-east-1\")\n                  .id(\"sir-228e6406\").type(Type.ONE_TIME).state(State.ACTIVE).rawState(\"active\")\n                  .build()), null);\n\n      assertEquals(\n            new SpotInstanceRequestToAWSRunningInstance().apply(SpotInstanceRequest.builder().region(\"us-east-1\")\n                  .id(\"sir-228e6406\").type(Type.ONE_TIME).rawState(\"one-time\")\n                  .state(State.CANCELLED).build()), null);\n\n      assertEquals(\n            new SpotInstanceRequestToAWSRunningInstance().apply(SpotInstanceRequest.builder().region(\"us-east-1\")\n                  .id(\"sir-228e6406\").type(Type.ONE_TIME).rawState(\"one-time\")\n                  .state(State.UNRECOGNIZED).build()), null);\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/internal/BaseAWSEC2ApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.internal;\n\nimport static com.google.common.base.Throwables.propagate;\nimport static com.google.common.net.HttpHeaders.AUTHORIZATION;\nimport static com.google.common.net.HttpHeaders.CONTENT_TYPE;\nimport static com.google.common.util.concurrent.MoreExecutors.newDirectExecutorService;\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_XML;\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.jclouds.util.Strings2.toStringAndClose;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport jakarta.ws.rs.core.Response;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\nimport okhttp3.mockwebserver.RecordedRequest;\n\nimport org.jclouds.Constants;\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.aws.ec2.AWSEC2Api;\nimport org.jclouds.aws.ec2.AWSEC2ProviderMetadata;\nimport org.jclouds.aws.ec2.config.AWSEC2HttpApiModule;\nimport org.jclouds.aws.filters.FormSignerV4.ServiceAndRegion;\nimport org.jclouds.compute.ComputeService;\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.compute.config.ComputeServiceProperties;\nimport org.jclouds.concurrent.config.ExecutorServiceModule;\nimport org.jclouds.date.DateService;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.testng.annotations.AfterMethod;\nimport org.testng.annotations.BeforeMethod;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Maps;\nimport com.google.inject.Module;\nimport com.google.inject.Provides;\n\n/**\n * Tests need to run {@code singleThreaded = true} as otherwise tests will clash on the regionToServers field.\n * Sharing the regionToServers field means less code to write.\n */\npublic class BaseAWSEC2ApiMockTest {\n   protected static final String DEFAULT_REGION = \"us-east-1\";\n\n   // Example keys from http://docs.aws.amazon.com/general/latest/gr/signature-version-2.html\n   private static final String ACCESS_KEY = \"AKIAIOSFODNN7EXAMPLE\";\n   private static final String SECRET_KEY = \"wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY\";\n\n   private Map<String, MockWebServer> regionToServers = Maps.newLinkedHashMap();\n\n   protected AWSEC2Api api() {\n      return builder(new Properties()).buildApi(AWSEC2Api.class);\n   }\n\n   protected ComputeService computeService() {\n      return builder(new Properties()).buildView(ComputeServiceContext.class).getComputeService();\n   }\n\n   protected ContextBuilder builder(Properties overrides) {\n      MockWebServer defaultServer = regionToServers.get(DEFAULT_REGION);\n      overrides.setProperty(Constants.PROPERTY_MAX_RETRIES, \"1\");\n      overrides.setProperty(ComputeServiceProperties.TIMEOUT_CLEANUP_INCIDENTAL_RESOURCES, \"0\");\n      return ContextBuilder.newBuilder(new AWSEC2ProviderMetadata())\n            .credentials(ACCESS_KEY, SECRET_KEY)\n            .endpoint(defaultServer.url(\"\").toString())\n            .overrides(overrides)\n            .modules(modules);\n   }\n\n   private final Set<Module> modules = ImmutableSet\n         .<Module>of(new MockAWSEC2HttpApiModule(), new ExecutorServiceModule(newDirectExecutorService()));\n\n   @ConfiguresHttpApi\n   class MockAWSEC2HttpApiModule extends AWSEC2HttpApiModule {\n\n      @Override\n      protected String provideTimeStamp(DateService dateService) {\n         return \"20120416T155408Z\";\n      }\n\n      @Provides ServiceAndRegion serviceAndRegion(){\n         return new ServiceAndRegion() {\n            @Override public String service() {\n               return \"ec2\";\n            }\n\n            @Override public String region(String host) {\n               for (Map.Entry<String, MockWebServer> regionToServer : regionToServers.entrySet()) {\n                  MockWebServer server = regionToServer.getValue();\n                  if (host.equals(server.getHostName() + \":\" + regionToServer.getValue().getPort())) {\n                     return regionToServer.getKey();\n                  }\n               }\n               throw new IllegalStateException(host + \" not found\");\n            }\n         };\n      }\n   }\n\n   @BeforeMethod(alwaysRun = true)\n   public void start() throws IOException {\n      MockWebServer server = new MockWebServer();\n      server.start();\n      regionToServers.put(DEFAULT_REGION, server);\n   }\n\n   @AfterMethod(alwaysRun = true)\n   public void stop() throws IOException {\n      for (MockWebServer server : regionToServers.values()) {\n         server.shutdown();\n      }\n   }\n\n   protected void enqueue(String region, MockResponse response) {\n      regionToServers.get(region).enqueue(response);\n   }\n\n   protected void enqueueRegions(String... regions) throws IOException {\n      StringBuilder describeRegionsResponse = new StringBuilder();\n      describeRegionsResponse.append(\"<DescribeRegionsResponse>\");\n      for (String region : regions) {\n         describeRegionsResponse.append(\"<item>\");\n         describeRegionsResponse.append(\"<regionName>\").append(region).append(\"</regionName>\");\n         if (!regionToServers.containsKey(region)) {\n            MockWebServer server = new MockWebServer();\n            server.start();\n            regionToServers.put(region, server);\n         }\n         MockWebServer server = regionToServers.get(region);\n         String regionEndpoint = server.url(\"\").toString();\n         describeRegionsResponse.append(\"<regionEndpoint>\").append(regionEndpoint).append(\"</regionEndpoint>\");\n         describeRegionsResponse.append(\"</item>\");\n      }\n      describeRegionsResponse.append(\"</DescribeRegionsResponse>\");\n      enqueue(DEFAULT_REGION,\n            new MockResponse().addHeader(CONTENT_TYPE, APPLICATION_XML).setBody(describeRegionsResponse.toString()));\n   }\n\n   protected void enqueueXml(Response.Status status, String region, String resource) {\n      enqueue(region, new MockResponse()\n         .setStatus(\"HTTP/1.1 \" + status.getStatusCode() + \" \" + status.getReasonPhrase())\n         .addHeader(CONTENT_TYPE, APPLICATION_XML)\n         .setBody(stringFromResource(resource)));\n   }\n\n   protected void enqueueXml(String region, String resource) {\n      enqueue(region,\n            new MockResponse().addHeader(CONTENT_TYPE, APPLICATION_XML).setBody(stringFromResource(resource)));\n   }\n\n   protected String stringFromResource(String resourceName) {\n      try {\n         final InputStream resourceAsStream = getClass().getResourceAsStream(resourceName);\n         if (resourceAsStream == null) {\n            throw new IllegalArgumentException(\n               \"Could not find resource '\" + resourceName + \"' in class \" + getClass().getSimpleName());\n         }\n         return toStringAndClose(resourceAsStream);\n      } catch (IOException e) {\n         throw propagate(e);\n      }\n   }\n\n\n   protected RecordedRequest assertPosted(String region, String postParams) throws InterruptedException {\n      return assertPosted(region, postParams, \"2012-06-01\");\n   }\n\n   protected RecordedRequest assertPosted(String region, String postParams, String apiVersion) throws InterruptedException {\n      RecordedRequest request = regionToServers.get(region).takeRequest();\n      assertEquals(request.getMethod(), \"POST\");\n      assertEquals(request.getPath(), \"/\");\n      assertEquals(request.getHeader(\"X-Amz-Date\"), \"20120416T155408Z\");\n      assertThat(\n            request.getHeader(AUTHORIZATION)).startsWith(\"AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20120416/\" +\n            region + \"/ec2/aws4_request, SignedHeaders=content-type;host;x-amz-date, Signature=\");\n      String body = request.getBody().readUtf8();\n      assertThat(body).contains(\"&Version=\" + apiVersion);\n      assertEquals(body.replace(\"&Version=\" + apiVersion, \"\"), postParams);\n      return request;\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/options/AWSDescribeImagesOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.options;\n\nimport static org.jclouds.aws.ec2.options.AWSDescribeImagesOptions.Builder.executableBy;\nimport static org.jclouds.aws.ec2.options.AWSDescribeImagesOptions.Builder.filters;\nimport static org.jclouds.aws.ec2.options.AWSDescribeImagesOptions.Builder.imageIds;\nimport static org.jclouds.aws.ec2.options.AWSDescribeImagesOptions.Builder.ownedBy;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.http.options.HttpRequestOptions;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMultimap;\n\n/**\n * Tests possible uses of AWSDescribeImagesOptions and AWSDescribeImagesOptions.Builder.*\n */\npublic class AWSDescribeImagesOptionsTest {\n\n   @Test\n   public void testAssignability() {\n      assert HttpRequestOptions.class.isAssignableFrom(AWSDescribeImagesOptions.class);\n      assert !String.class.isAssignableFrom(AWSDescribeImagesOptions.class);\n   }\n\n   @Test\n   public void testExecutableBy() {\n      AWSDescribeImagesOptions options = new AWSDescribeImagesOptions();\n      options.executableBy(\"test\");\n      assertEquals(options.buildFormParameters().get(\"ExecutableBy\"), ImmutableList.of(\"test\"));\n   }\n\n   @Test\n   public void testNullExecutableBy() {\n      AWSDescribeImagesOptions options = new AWSDescribeImagesOptions();\n      assertEquals(options.buildFormParameters().get(\"ExecutableBy\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testExecutableByStatic() {\n      AWSDescribeImagesOptions options = executableBy(\"test\");\n      assertEquals(options.buildFormParameters().get(\"ExecutableBy\"), ImmutableList.of(\"test\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testExecutableByNPE() {\n      executableBy(null);\n   }\n\n   @Test\n   public void testOwners() {\n      AWSDescribeImagesOptions options = new AWSDescribeImagesOptions();\n      options.ownedBy(\"test\");\n      assertEquals(options.buildFormParameters().get(\"Owner.1\"), ImmutableList.of(\"test\"));\n   }\n\n   @Test\n   public void testMultipleOwners() {\n      AWSDescribeImagesOptions options = new AWSDescribeImagesOptions();\n      options.ownedBy(\"test\", \"trouble\");\n      assertEquals(options.buildFormParameters().get(\"Owner.1\"), ImmutableList.of(\"test\"));\n      assertEquals(options.buildFormParameters().get(\"Owner.2\"), ImmutableList.of(\"trouble\"));\n   }\n\n   @Test\n   public void testNullOwners() {\n      AWSDescribeImagesOptions options = new AWSDescribeImagesOptions();\n      assertEquals(options.buildFormParameters().get(\"Owner.1\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testOwnersStatic() {\n      AWSDescribeImagesOptions options = ownedBy(\"test\");\n      assertEquals(options.buildFormParameters().get(\"Owner.1\"), ImmutableList.of(\"test\"));\n   }\n\n   public void testNoOwners() {\n      ownedBy();\n   }\n\n   @Test\n   public void testImageIds() {\n      AWSDescribeImagesOptions options = new AWSDescribeImagesOptions();\n      options.imageIds(\"test\");\n      assertEquals(options.buildFormParameters().get(\"ImageId.1\"), ImmutableList.of(\"test\"));\n   }\n\n   @Test\n   public void testMultipleImageIds() {\n      AWSDescribeImagesOptions options = new AWSDescribeImagesOptions();\n      options.imageIds(\"test\", \"trouble\");\n      assertEquals(options.buildFormParameters().get(\"ImageId.1\"), ImmutableList.of(\"test\"));\n      assertEquals(options.buildFormParameters().get(\"ImageId.2\"), ImmutableList.of(\"trouble\"));\n   }\n\n   @Test\n   public void testNullImageIds() {\n      AWSDescribeImagesOptions options = new AWSDescribeImagesOptions();\n      assertEquals(options.buildFormParameters().get(\"ImageId.1\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testImageIdsStatic() {\n      AWSDescribeImagesOptions options = imageIds(\"test\");\n      assertEquals(options.buildFormParameters().get(\"ImageId.1\"), ImmutableList.of(\"test\"));\n   }\n\n   public void testNoImageIds() {\n      imageIds();\n   }\n\n   @Test\n   public void testMapFilters() {\n      AWSDescribeImagesOptions options = new AWSDescribeImagesOptions();\n      options.filters(ImmutableMap.of(\"is-public\", \"true\", \"architecture\", \"x86_64\", \"platform\", \"windows\"));\n      testMapFilters(options);\n   }\n\n   private void testMapFilters(AWSDescribeImagesOptions options) {\n      assertEquals(options.buildFormParameters().get(\"Filter.1.Name\"), ImmutableList.of(\"is-public\"));\n      assertEquals(options.buildFormParameters().get(\"Filter.1.Value.1\"), ImmutableList.of(\"true\"));\n      assertEquals(options.buildFormParameters().get(\"Filter.2.Name\"), ImmutableList.of(\"architecture\"));\n      assertEquals(options.buildFormParameters().get(\"Filter.2.Value.1\"), ImmutableList.of(\"x86_64\"));\n      assertEquals(options.buildFormParameters().get(\"Filter.3.Name\"), ImmutableList.of(\"platform\"));\n      assertEquals(options.buildFormParameters().get(\"Filter.3.Value.1\"), ImmutableList.of(\"windows\"));\n   }\n\n   @Test\n   public void testMapFiltersStatic() {\n      AWSDescribeImagesOptions options = filters(ImmutableMap.of(\"is-public\", \"true\", \"architecture\", \"x86_64\",\n               \"platform\", \"windows\"));\n      testMapFilters(options);\n   }\n   \n\n   @Test\n   public void testMultimapFilters() {\n      AWSDescribeImagesOptions options = new AWSDescribeImagesOptions();\n      options.filters(ImmutableMultimap.of(\"is-public\", \"true\", \"architecture\", \"x86_64\", \"platform\", \"windows\"));\n      testMultimapFilters(options);\n   }\n\n   private void testMultimapFilters(AWSDescribeImagesOptions options) {\n      assertEquals(options.buildFormParameters().get(\"Filter.1.Name\"), ImmutableList.of(\"is-public\"));\n      assertEquals(options.buildFormParameters().get(\"Filter.1.Value.1\"), ImmutableList.of(\"true\"));\n      assertEquals(options.buildFormParameters().get(\"Filter.2.Name\"), ImmutableList.of(\"architecture\"));\n      assertEquals(options.buildFormParameters().get(\"Filter.2.Value.1\"), ImmutableList.of(\"x86_64\"));\n      assertEquals(options.buildFormParameters().get(\"Filter.3.Name\"), ImmutableList.of(\"platform\"));\n      assertEquals(options.buildFormParameters().get(\"Filter.3.Value.1\"), ImmutableList.of(\"windows\"));\n   }\n\n   @Test\n   public void testMultimapFiltersStatic() {\n      AWSDescribeImagesOptions options = filters(ImmutableMultimap.of(\"is-public\", \"true\", \"architecture\", \"x86_64\",\n               \"platform\", \"windows\"));\n      testMultimapFilters(options);\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/options/AWSRunInstancesOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.options;\n\nimport static org.jclouds.aws.ec2.options.AWSRunInstancesOptions.Builder.asType;\nimport static org.jclouds.aws.ec2.options.AWSRunInstancesOptions.Builder.enableMonitoring;\nimport static org.jclouds.aws.ec2.options.AWSRunInstancesOptions.Builder.withBlockDeviceMappings;\nimport static org.jclouds.aws.ec2.options.AWSRunInstancesOptions.Builder.withDedicatedHostId;\nimport static org.jclouds.aws.ec2.options.AWSRunInstancesOptions.Builder.withIAMInstanceProfileArn;\nimport static org.jclouds.aws.ec2.options.AWSRunInstancesOptions.Builder.withIAMInstanceProfileName;\nimport static org.jclouds.aws.ec2.options.AWSRunInstancesOptions.Builder.withKernelId;\nimport static org.jclouds.aws.ec2.options.AWSRunInstancesOptions.Builder.withKeyName;\nimport static org.jclouds.aws.ec2.options.AWSRunInstancesOptions.Builder.withPrivateIpAdress;\nimport static org.jclouds.aws.ec2.options.AWSRunInstancesOptions.Builder.withRamdisk;\nimport static org.jclouds.aws.ec2.options.AWSRunInstancesOptions.Builder.withSecurityGroup;\nimport static org.jclouds.aws.ec2.options.AWSRunInstancesOptions.Builder.withSecurityGroupId;\nimport static org.jclouds.aws.ec2.options.AWSRunInstancesOptions.Builder.withSubnetId;\nimport static org.jclouds.aws.ec2.options.AWSRunInstancesOptions.Builder.withTenancy;\nimport static org.jclouds.aws.ec2.options.AWSRunInstancesOptions.Builder.withUserData;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.ec2.domain.BlockDeviceMapping;\nimport org.jclouds.ec2.domain.InstanceType;\nimport org.jclouds.http.options.HttpRequestOptions;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests possible uses of AWSRunInstancesOptions and AWSRunInstancesOptions.Builder.*\n */\npublic class AWSRunInstancesOptionsTest {\n\n   @Test\n   public void testAssignability() {\n      assert HttpRequestOptions.class.isAssignableFrom(AWSRunInstancesOptions.class);\n      assert !String.class.isAssignableFrom(AWSRunInstancesOptions.class);\n   }\n\n   @Test\n   public void testWithKeyName() {\n      AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n      options.withKeyName(\"test\");\n      assertEquals(options.buildFormParameters().get(\"KeyName\"), ImmutableList.of(\"test\"));\n   }\n\n   @Test\n   public void testNullWithKeyName() {\n      AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n      assertEquals(options.buildFormParameters().get(\"KeyName\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testWithKeyNameStatic() {\n      AWSRunInstancesOptions options = withKeyName(\"test\");\n      assertEquals(options.buildFormParameters().get(\"KeyName\"), ImmutableList.of(\"test\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testWithKeyNameNPE() {\n      withKeyName(null);\n   }\n\n   @Test\n   public void testWithSecurityGroup() {\n      AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n      options.withSecurityGroup(\"test\");\n      assertEquals(options.buildFormParameters().get(\"SecurityGroup.1\"), ImmutableList.of(\"test\"));\n   }\n\n   @Test\n   public void testNullWithSecurityGroup() {\n      AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n      assertEquals(options.buildFormParameters().get(\"SecurityGroup\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testWithSecurityGroupStatic() {\n      AWSRunInstancesOptions options = withSecurityGroup(\"test\");\n      assertEquals(options.buildFormParameters().get(\"SecurityGroup.1\"), ImmutableList.of(\"test\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testWithSecurityGroupNPE() {\n      withSecurityGroup(null);\n   }\n   \n\n   @Test\n   public void testWithSecurityGroupId() {\n      AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n      options.withSecurityGroupId(\"test\");\n      assertEquals(options.buildFormParameters().get(\"SecurityGroupId.1\"), ImmutableList.of(\"test\"));\n   }\n\n   @Test\n   public void testNullWithSecurityGroupId() {\n      AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n      assertEquals(options.buildFormParameters().get(\"SecurityGroupId\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testWithSecurityGroupIdStatic() {\n      AWSRunInstancesOptions options = withSecurityGroupId(\"test\");\n      assertEquals(options.buildFormParameters().get(\"SecurityGroupId.1\"), ImmutableList.of(\"test\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testWithSecurityGroupIdNPE() {\n      withSecurityGroupId(null);\n   }\n\n   @Test\n   public void testNullWithAdditionalInfo() {\n      AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n      assertEquals(options.buildFormParameters().get(\"AdditionalInfo\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testWithUserData() {\n      AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n      options.withUserData(\"test\".getBytes());\n      assertEquals(options.buildFormParameters().get(\"UserData\"), ImmutableList.of(\"dGVzdA==\"));\n   }\n\n   @Test\n   public void testNullWithUserData() {\n      AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n      assertEquals(options.buildFormParameters().get(\"UserData\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testWithUserDataStatic() {\n      AWSRunInstancesOptions options = withUserData(\"test\".getBytes());\n      assertEquals(options.buildFormParameters().get(\"UserData\"), ImmutableList.of(\"dGVzdA==\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testWithUserDataNPE() {\n      withUserData(null);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testWithUserDataEmpty() {\n      withUserData(\"\".getBytes());\n   }\n\n   @Test\n   public void testWithInstanceType() {\n      AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n      options.asType(InstanceType.C1_XLARGE);\n      assertEquals(options.buildFormParameters().get(\"InstanceType\"), ImmutableList.of(\"c1.xlarge\"));\n   }\n\n   @Test\n   public void testNullWithInstanceType() {\n      AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n      assertEquals(options.buildFormParameters().get(\"InstanceType\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testWithInstanceTypeStatic() {\n      AWSRunInstancesOptions options = asType(InstanceType.C1_XLARGE);\n      assertEquals(options.buildFormParameters().get(\"InstanceType\"), ImmutableList.of(\"c1.xlarge\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testWithInstanceTypeNPE() {\n      asType(null);\n   }\n\n   @Test\n   public void testWithKernelId() {\n      AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n      options.withKernelId(\"test\");\n      assertEquals(options.buildFormParameters().get(\"KernelId\"), ImmutableList.of(\"test\"));\n   }\n\n   @Test\n   public void testNullWithKernelId() {\n      AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n      assertEquals(options.buildFormParameters().get(\"KernelId\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testWithKernelIdStatic() {\n      AWSRunInstancesOptions options = withKernelId(\"test\");\n      assertEquals(options.buildFormParameters().get(\"KernelId\"), ImmutableList.of(\"test\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testWithKernelIdNPE() {\n      withKernelId(null);\n   }\n\n   @Test\n   public void testWithMonitoringEnabled() {\n      AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n      options.enableMonitoring();\n      assertEquals(options.buildFormParameters().get(\"Monitoring.Enabled\"), ImmutableList.of(\"true\"));\n   }\n\n   @Test\n   public void testNullWithMonitoringEnabled() {\n      AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n      assertEquals(options.buildFormParameters().get(\"Monitoring.Enabled\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testWithMonitoringEnabledStatic() {\n      AWSRunInstancesOptions options = enableMonitoring();\n      assertEquals(options.buildFormParameters().get(\"Monitoring.Enabled\"), ImmutableList.of(\"true\"));\n   }\n\n   @Test\n   public void testWithSubnetId() {\n      AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n      options.withSubnetId(\"test\");\n      assertEquals(options.buildFormParameters().get(\"SubnetId\"), ImmutableList.of(\"test\"));\n   }\n\n   @Test\n   public void testNullWithSubnetId() {\n      AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n      assertEquals(options.buildFormParameters().get(\"SubnetId\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testWithSubnetIdStatic() {\n      AWSRunInstancesOptions options = withSubnetId(\"test\");\n      assertEquals(options.buildFormParameters().get(\"SubnetId\"), ImmutableList.of(\"test\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testWithSubnetIdNPE() {\n      withSubnetId(null);\n   }\n\n   @Test\n   public void testWithIAMInstanceProfileArn() {\n      AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n      options\n            .withIAMInstanceProfileArn(\"arn:aws:iam::123456789012:instance-profile/application_abc/component_xyz/Webserver\");\n      assertEquals(options.buildFormParameters().get(\"IamInstanceProfile.Arn\"),\n            ImmutableList.of(\"arn:aws:iam::123456789012:instance-profile/application_abc/component_xyz/Webserver\"));\n   }\n\n   @Test\n   public void testNullWithIAMInstanceProfileArn() {\n      AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n      assertEquals(options.buildFormParameters().get(\"IamInstanceProfile.Arn\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testWithIAMInstanceProfileArnStatic() {\n      AWSRunInstancesOptions options = withIAMInstanceProfileArn(\"arn:aws:iam::123456789012:instance-profile/application_abc/component_xyz/Webserver\");\n      assertEquals(options.buildFormParameters().get(\"IamInstanceProfile.Arn\"),\n            ImmutableList.of(\"arn:aws:iam::123456789012:instance-profile/application_abc/component_xyz/Webserver\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testWithIAMInstanceProfileArnNPE() {\n      withIAMInstanceProfileArn(null);\n   }\n\n   @Test\n   public void testWithIAMInstanceProfileName() {\n      AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n      options.withIAMInstanceProfileName(\"Webserver\");\n      assertEquals(options.buildFormParameters().get(\"IamInstanceProfile.Name\"), ImmutableList.of(\"Webserver\"));\n   }\n\n   @Test\n   public void testNullWithIAMInstanceProfileName() {\n      AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n      assertEquals(options.buildFormParameters().get(\"IamInstanceProfile.Name\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testWithIAMInstanceProfileNameStatic() {\n      AWSRunInstancesOptions options = withIAMInstanceProfileName(\"Webserver\");\n      assertEquals(options.buildFormParameters().get(\"IamInstanceProfile.Name\"), ImmutableList.of(\"Webserver\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testWithIAMInstanceProfileNameNPE() {\n      withIAMInstanceProfileName(null);\n   }\n\n   @Test\n   public void testWithRamdisk() {\n      AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n      options.withRamdisk(\"test\");\n      assertEquals(options.buildFormParameters().get(\"RamdiskId\"), ImmutableList.of(\"test\"));\n   }\n\n   @Test\n   public void testNullWithRamdisk() {\n      AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n      assertEquals(options.buildFormParameters().get(\"RamdiskId\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testWithRamdiskStatic() {\n      AWSRunInstancesOptions options = withRamdisk(\"test\");\n      assertEquals(options.buildFormParameters().get(\"RamdiskId\"), ImmutableList.of(\"test\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testWithRamdiskNPE() {\n      withRamdisk(null);\n   }\n\n   @Test\n   public void testNullWithVirtualName() {\n      AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n      assertEquals(options.buildFormParameters().get(\"BlockDeviceMapping.VirtualName\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testWithBlockDeviceMapping() {\n      BlockDeviceMapping mapping = new BlockDeviceMapping.MapNewVolumeToDevice(\"/dev/sda1\", 120, true, \"gp2\", 10, true);\n      AWSRunInstancesOptions options = new AWSRunInstancesOptions().withBlockDeviceMappings(ImmutableSet\n               .<BlockDeviceMapping> of(mapping));\n      assertEquals(options.buildFormParameters().get(\"BlockDeviceMapping.1.DeviceName\"),\n               ImmutableList.of(\"/dev/sda1\"));\n      assertEquals(options.buildFormParameters().get(\"BlockDeviceMapping.1.Ebs.VolumeSize\"),\n               ImmutableList.of(\"120\"));\n      assertEquals(options.buildFormParameters().get(\"BlockDeviceMapping.1.Ebs.DeleteOnTermination\"),\n               ImmutableList.of(\"true\"));\n      assertEquals(options.buildFormParameters().get(\"BlockDeviceMapping.1.Ebs.VolumeType\"),\n              ImmutableList.of(\"gp2\"));\n      assertEquals(options.buildFormParameters().get(\"BlockDeviceMapping.1.Ebs.Iops\"),\n              ImmutableList.of(\"10\"));\n      assertEquals(options.buildFormParameters().get(\"BlockDeviceMapping.1.Ebs.Encrypted\"),\n              ImmutableList.of(\"true\"));\n   }\n\n   @Test\n   public void testNullWithBlockDeviceMapping() {\n      AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n      assertEquals(options.buildFormParameters().get(\"BlockDeviceMapping\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testWithBlockDeviceMappingStatic() {\n      BlockDeviceMapping mapping = new BlockDeviceMapping.MapNewVolumeToDevice(\"/dev/sda1\", 120, true, null, null, false);\n      AWSRunInstancesOptions options = withBlockDeviceMappings(ImmutableSet.<BlockDeviceMapping> of(mapping));\n      assertEquals(options.buildFormParameters().get(\"BlockDeviceMapping.1.DeviceName\"),\n               ImmutableList.of(\"/dev/sda1\"));\n      assertEquals(options.buildFormParameters().get(\"BlockDeviceMapping.1.Ebs.VolumeSize\"),\n               ImmutableList.of(\"120\"));\n      assertEquals(options.buildFormParameters().get(\"BlockDeviceMapping.1.Ebs.DeleteOnTermination\"),\n               ImmutableList.of(\"true\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testWithBlockDeviceMappingNPE() {\n      withBlockDeviceMappings(null);\n   }\n\n   @Test\n   public void testWithPrivateIpAddressStatic() {\n      AWSRunInstancesOptions options = withPrivateIpAdress(\"10.0.0.1\");\n      assertEquals(options.buildFormParameters().get(\"PrivateIpAddress\"), ImmutableList.of(\"10.0.0.1\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testWithPrivateIpAddressStaticNPE() {\n      withPrivateIpAdress(null);\n   }\n\n   @Test\n   public void testNullWithTenancy() {\n      AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n      assertEquals(options.buildFormParameters().get(\"Placement.Tenancy\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testWithTenancy() {\n      AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n      options.withTenancy(Tenancy.DEDICATED);\n      assertEquals(options.buildFormParameters().get(\"Placement.Tenancy\"), ImmutableList.of(\"dedicated\"));\n   }\n\n   @Test\n   public void testWithTenancyStatic() {\n      AWSRunInstancesOptions options = withTenancy(Tenancy.HOST);\n      assertEquals(options.buildFormParameters().get(\"Placement.Tenancy\"), ImmutableList.of(\"host\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testWithTenancyStaticNPE() {\n      withTenancy(null);\n   }\n\n   @Test\n   public void testNullWithDedicatedHostId() {\n      AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n      assertEquals(options.buildFormParameters().get(\"Placement.HostId\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testWithDedicatedHostId() {\n      AWSRunInstancesOptions options = new AWSRunInstancesOptions();\n      options.withDedicatedHostId(\"hostId-1234\");\n      assertEquals(options.buildFormParameters().get(\"Placement.HostId\"), ImmutableList.of(\"hostId-1234\"));\n   }\n\n   @Test\n   public void testWithDedicatedHostIdStatic() {\n      AWSRunInstancesOptions options = withDedicatedHostId(\"hostId-5678\");\n      assertEquals(options.buildFormParameters().get(\"Placement.HostId\"), ImmutableList.of(\"hostId-5678\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testWithDedicatedHostIdStaticNPE() {\n      withDedicatedHostId(null);\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/options/DescribeSpotPriceHistoryOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.options;\n\nimport static org.jclouds.aws.ec2.options.DescribeSpotPriceHistoryOptions.Builder.from;\nimport static org.jclouds.aws.ec2.options.DescribeSpotPriceHistoryOptions.Builder.instanceType;\nimport static org.jclouds.aws.ec2.options.DescribeSpotPriceHistoryOptions.Builder.productDescription;\nimport static org.jclouds.aws.ec2.options.DescribeSpotPriceHistoryOptions.Builder.to;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Date;\n\nimport com.google.common.collect.ImmutableList;\nimport org.jclouds.http.options.HttpRequestOptions;\nimport org.testng.annotations.Test;\n\n/**\n * Tests possible uses of DescribeSpotPriceHistoryOptions and\n * DescribeSpotPriceHistoryOptions.Builder.*\n */\npublic class DescribeSpotPriceHistoryOptionsTest {\n\n   @Test\n   public void testAssignability() {\n      assert HttpRequestOptions.class.isAssignableFrom(DescribeSpotPriceHistoryOptions.class);\n      assert !String.class.isAssignableFrom(DescribeSpotPriceHistoryOptions.class);\n   }\n\n   @Test\n   public void testDescription() {\n      DescribeSpotPriceHistoryOptions options = new DescribeSpotPriceHistoryOptions();\n      options.productDescription(\"test\");\n      assertEquals(options.buildFormParameters().get(\"ProductDescription\"), ImmutableList.of(\"test\"));\n   }\n\n   @Test\n   public void testDescriptionStatic() {\n      DescribeSpotPriceHistoryOptions options = productDescription(\"test\");\n      assertEquals(options.buildFormParameters().get(\"ProductDescription\"), ImmutableList.of(\"test\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testDescriptionNPE() {\n      productDescription(null);\n   }\n\n   @Test\n   public void testInstanceType() {\n      DescribeSpotPriceHistoryOptions options = new DescribeSpotPriceHistoryOptions();\n      options.instanceType(\"test\");\n      assertEquals(options.buildFormParameters().get(\"InstanceType.1\"), ImmutableList.of(\"test\"));\n   }\n\n   @Test\n   public void testInstanceTypeStatic() {\n      DescribeSpotPriceHistoryOptions options = instanceType(\"test\");\n      assertEquals(options.buildFormParameters().get(\"InstanceType.1\"), ImmutableList.of(\"test\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testInstanceTypeNPE() {\n      instanceType(null);\n   }\n\n   @Test\n   public void testFrom() {\n      DescribeSpotPriceHistoryOptions options = new DescribeSpotPriceHistoryOptions();\n      options.from(test);\n      assertEquals(options.buildFormParameters().get(\"StartTime\"), ImmutableList.of(\"1970-05-23T21:21:18.910Z\"));\n   }\n\n   Date test = new Date(12345678910L);\n\n   @Test\n   public void testFromStatic() {\n      DescribeSpotPriceHistoryOptions options = from(test);\n      assertEquals(options.buildFormParameters().get(\"StartTime\"), ImmutableList.of(\"1970-05-23T21:21:18.910Z\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testFromNPE() {\n      from(null);\n   }\n\n   @Test\n   public void testTo() {\n      DescribeSpotPriceHistoryOptions options = new DescribeSpotPriceHistoryOptions();\n      options.to(test);\n      assertEquals(options.buildFormParameters().get(\"EndTime\"), ImmutableList.of(\"1970-05-23T21:21:18.910Z\"));\n   }\n\n   @Test\n   public void testToStatic() {\n      DescribeSpotPriceHistoryOptions options = to(test);\n      assertEquals(options.buildFormParameters().get(\"EndTime\"), ImmutableList.of(\"1970-05-23T21:21:18.910Z\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testToNPE() {\n      to(null);\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/options/RequestSpotInstancesOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.options;\n\nimport static org.jclouds.aws.ec2.options.RequestSpotInstancesOptions.Builder.availabilityZoneGroup;\nimport static org.jclouds.aws.ec2.options.RequestSpotInstancesOptions.Builder.launchGroup;\nimport static org.jclouds.aws.ec2.options.RequestSpotInstancesOptions.Builder.type;\nimport static org.jclouds.aws.ec2.options.RequestSpotInstancesOptions.Builder.validFrom;\nimport static org.jclouds.aws.ec2.options.RequestSpotInstancesOptions.Builder.validUntil;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Date;\n\nimport com.google.common.collect.ImmutableList;\n\nimport org.jclouds.aws.ec2.domain.SpotInstanceRequest;\nimport org.jclouds.http.options.HttpRequestOptions;\nimport org.testng.annotations.Test;\n\n/**\n * Tests possible uses of RequestSpotInstancesOptions and RequestSpotInstancesOptions.Builder.*\n */\npublic class RequestSpotInstancesOptionsTest {\n\n   @Test\n   public void testAssignability() {\n      assert HttpRequestOptions.class.isAssignableFrom(RequestSpotInstancesOptions.class);\n      assert !String.class.isAssignableFrom(RequestSpotInstancesOptions.class);\n   }\n\n   @Test\n   public void testAvailabilityZoneGroup() {\n      RequestSpotInstancesOptions options = new RequestSpotInstancesOptions();\n      options.availabilityZoneGroup(\"test\");\n      assertEquals(options.buildFormParameters().get(\"AvailabilityZoneGroup\"), ImmutableList.of(\"test\"));\n   }\n\n   @Test\n   public void testAvailabilityZoneGroupStatic() {\n      RequestSpotInstancesOptions options = availabilityZoneGroup(\"test\");\n      assertEquals(options.buildFormParameters().get(\"AvailabilityZoneGroup\"), ImmutableList.of(\"test\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testAvailabilityZoneGroupNPE() {\n      availabilityZoneGroup(null);\n   }\n\n   @Test\n   public void testLaunchGroup() {\n      RequestSpotInstancesOptions options = new RequestSpotInstancesOptions();\n      options.launchGroup(\"test\");\n      assertEquals(options.buildFormParameters().get(\"LaunchGroup\"), ImmutableList.of(\"test\"));\n   }\n\n   @Test\n   public void testLaunchGroupStatic() {\n      RequestSpotInstancesOptions options = launchGroup(\"test\");\n      assertEquals(options.buildFormParameters().get(\"LaunchGroup\"), ImmutableList.of(\"test\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testLaunchGroupNPE() {\n      launchGroup(null);\n   }\n\n   @Test\n   public void testInstanceType() {\n      RequestSpotInstancesOptions options = new RequestSpotInstancesOptions();\n      options.type(SpotInstanceRequest.Type.PERSISTENT);\n      assertEquals(options.buildFormParameters().get(\"Type\"), ImmutableList.of(\"persistent\"));\n   }\n\n   @Test\n   public void testInstanceTypeStatic() {\n      RequestSpotInstancesOptions options = type(SpotInstanceRequest.Type.PERSISTENT);\n      assertEquals(options.buildFormParameters().get(\"Type\"), ImmutableList.of(\"persistent\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testInstanceTypeNPE() {\n      type(null);\n   }\n\n   @Test\n   public void testFrom() {\n      RequestSpotInstancesOptions options = new RequestSpotInstancesOptions();\n      options.validFrom(test);\n      assertEquals(options.buildFormParameters().get(\"ValidFrom\"),\n            ImmutableList.of(\"1970-05-23T21:21:18Z\"));\n   }\n\n   Date test = new Date(12345678910L);\n\n   @Test\n   public void testFromStatic() {\n      RequestSpotInstancesOptions options = validFrom(test);\n      assertEquals(options.buildFormParameters().get(\"ValidFrom\"),\n            ImmutableList.of(\"1970-05-23T21:21:18Z\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testFromNPE() {\n      validFrom(null);\n   }\n\n   @Test\n   public void testTo() {\n      RequestSpotInstancesOptions options = new RequestSpotInstancesOptions();\n      options.validUntil(test);\n      assertEquals(options.buildFormParameters().get(\"ValidUntil\"),\n            ImmutableList.of(\"1970-05-23T21:21:18Z\"));\n   }\n\n   @Test\n   public void testToStatic() {\n      RequestSpotInstancesOptions options = validUntil(test);\n      assertEquals(options.buildFormParameters().get(\"ValidUntil\"),\n            ImmutableList.of(\"1970-05-23T21:21:18Z\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testToNPE() {\n      validUntil(null);\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/parse/DescribeInstancesResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.parse;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\nimport java.util.Set;\n\nimport org.jclouds.aws.ec2.domain.AWSRunningInstance;\nimport org.jclouds.aws.ec2.domain.MonitoringState;\nimport org.jclouds.aws.ec2.xml.AWSDescribeInstancesResponseHandler;\nimport org.jclouds.date.DateService;\nimport org.jclouds.ec2.domain.Attachment;\nimport org.jclouds.ec2.domain.BlockDevice;\nimport org.jclouds.ec2.domain.Hypervisor;\nimport org.jclouds.ec2.domain.InstanceState;\nimport org.jclouds.ec2.domain.Reservation;\nimport org.jclouds.ec2.domain.RootDeviceType;\nimport org.jclouds.ec2.domain.RunningInstance;\nimport org.jclouds.ec2.xml.BaseEC2HandlerTest;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code AWSDescribeInstancesResponseHandler}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"DescribeInstancesResponseHandlerTest\")\npublic class DescribeInstancesResponseTest extends BaseEC2HandlerTest {\n\n   private DateService dateService;\n\n   @BeforeTest\n   @Override\n   protected void setUpInjector() {\n      super.setUpInjector();\n      dateService = injector.getInstance(DateService.class);\n      assert dateService != null;\n   }\n\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/describe_instances_pending.xml\");\n\n      Set<Reservation<AWSRunningInstance>> expected = expected();\n\n      AWSDescribeInstancesResponseHandler handler = injector.getInstance(AWSDescribeInstancesResponseHandler.class);\n      Set<Reservation<? extends RunningInstance>> result = factory.create(handler).parse(is);\n\n      assertEquals(result.toString(), expected.toString());\n\n   }\n\n   public Set<Reservation<AWSRunningInstance>> expected() {\n      return ImmutableSet.of(Reservation.<AWSRunningInstance>builder()\n                         .region(defaultRegion)\n                         .reservationId(\"r-3f056a58\")\n                         .ownerId(\"095072994936\")\n//                                             <groupId>sg-f788299f</groupId>\n                         .groupName(\"launchpad_sec_group\")\n//                                             <groupId>sg-7e512116</groupId>\n                         .groupName(\"jclouds#4c858090-f66c-4225-aa57-6fcaa42198ae\")\n                         .instance(AWSRunningInstance.builder()\n                                  .region(defaultRegion)\n                                  .instanceId(\"i-32451248\")\n                                  .imageId(\"ami-bf8131d6\")\n                                  .rawState(\"pending\")\n                                  .instanceState(InstanceState.PENDING)\n                                  .privateDnsName(\"ip-10-194-149-220.ec2.internal\")\n                                  .dnsName(\"ec2-23-20-17-42.compute-1.amazonaws.com\")\n                                  .keyName(\"jclouds#4c858090-f66c-4225-aa57-6fcaa42198ae#105\")\n                                  .amiLaunchIndex(\"0\")\n                                  .instanceType(\"c1.medium\")\n                                  .launchTime(dateService.iso8601DateParse(\"2012-09-14T20:01:34.000Z\"))\n                                  .availabilityZone(\"us-east-1d\")\n//                                  .tenancy(\"default\")\n                                  .kernelId(\"aki-825ea7eb\")\n                                  .monitoringState(MonitoringState.DISABLED)\n                                  .privateIpAddress(\"10.194.149.220\")\n                                  .ipAddress(\"23.20.17.42\")\n                                  .securityGroupIdToName(\"sg-f788299f\", \"launchpad_sec_group\")\n                                  .securityGroupIdToName(\"sg-7e512116\", \"jclouds#4c858090-f66c-4225-aa57-6fcaa42198ae\")\n//                                  .architecture(\"x86_64\")\n                                  .rootDeviceType(RootDeviceType.EBS)\n                                  .rootDeviceName(\"/dev/sda1\")\n                                  .device(\"/dev/sda1\", new BlockDevice(\"vol-b2beb3c9\", Attachment.Status.ATTACHING, dateService.iso8601DateParse(\"2012-09-14T20:01:37.000Z\"), true))\n                                  .virtualizationType(\"paravirtual\")\n                                  .tag(\"Name\", \"4c858090-f66c-4225-aa57-6fcaa42198ae-32451248\")\n                                  .hypervisor(Hypervisor.XEN)\n                                  .build()).build());\n   }\n   \n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/parse/DescribeSecurityGroupsResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.parse;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\nimport java.util.Set;\n\nimport org.jclouds.ec2.domain.SecurityGroup;\nimport org.jclouds.ec2.xml.BaseEC2HandlerTest;\nimport org.jclouds.ec2.xml.DescribeSecurityGroupsResponseHandler;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.net.domain.IpPermission;\nimport org.jclouds.net.domain.IpProtocol;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"DescribeSecurityGroupsResponseTest\")\npublic class DescribeSecurityGroupsResponseTest extends BaseEC2HandlerTest {\n\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/describe_security_groups_vpc.xml\");\n\n      Set<SecurityGroup> expected = expected();\n\n      DescribeSecurityGroupsResponseHandler handler = injector.getInstance(DescribeSecurityGroupsResponseHandler.class);\n      addDefaultRegionToHandler(handler);\n      Set<SecurityGroup> result = factory.create(handler).parse(is);\n\n      assertEquals(result.toString(), expected.toString());\n   }\n\n   public Set<SecurityGroup> expected() {\n      return ImmutableSet.of(SecurityGroup.builder()\n                                          .region(defaultRegion)\n                                          .ownerId(\"123123123123\")\n                                          .id(\"sg-11111111\")\n                                          .name(\"default\")\n                                          .description(\"default VPC security group\")\n//                                          .vpcId(\"vpc-99999999\")\n                                          .ipPermission(IpPermission.builder()\n                                                                    .ipProtocol(IpProtocol.ALL)\n                                                                    .tenantIdGroupNamePair(\"123123123123\", \"sg-11111111\").build())\n//                                          .ipPermissionEgress(IpPermission.builder()\n//                                                                    .ipProtocol(IpProtocol.ALL)\n//                                                                    .ipRange(\"0.0.0.0/0\").build())\n                                          .build());\n\n   }\n\n   private void addDefaultRegionToHandler(ParseSax.HandlerWithResult<?> handler) {\n      handler.setContext(request);\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/xml/AWSDescribeInstancesResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.xml;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\nimport java.net.UnknownHostException;\nimport java.util.Set;\n\nimport org.jclouds.aws.ec2.domain.AWSRunningInstance;\nimport org.jclouds.aws.ec2.domain.MonitoringState;\nimport org.jclouds.date.DateService;\nimport org.jclouds.ec2.domain.Attachment;\nimport org.jclouds.ec2.domain.BlockDevice;\nimport org.jclouds.ec2.domain.Hypervisor;\nimport org.jclouds.ec2.domain.InstanceState;\nimport org.jclouds.ec2.domain.Reservation;\nimport org.jclouds.ec2.domain.RootDeviceType;\nimport org.jclouds.ec2.domain.RunningInstance;\nimport org.jclouds.ec2.xml.BaseEC2HandlerTest;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.http.functions.config.SaxParserModule;\nimport org.jclouds.location.Region;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport com.google.inject.TypeLiteral;\n\n/**\n * Tests behavior of {@code AWSDescribeInstancesResponseHandler}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"AWSDescribeInstancesResponseHandlerTest\")\npublic class AWSDescribeInstancesResponseHandlerTest extends BaseEC2HandlerTest {\n\n   private DateService dateService;\n\n   @BeforeTest\n   @Override\n   protected void setUpInjector() {\n      super.setUpInjector();\n      dateService = injector.getInstance(DateService.class);\n      assert dateService != null;\n   }\n\n\n   public void testWhenRunningLatest() throws UnknownHostException {\n      Set<Reservation<AWSRunningInstance>> contents = ImmutableSet.of(Reservation.<AWSRunningInstance>builder()\n               .region(defaultRegion)\n               .reservationId(\"r-0f4c2160\")\n               .groupName(\"jclouds#zkclustertest#us-east-1\")\n               .instance(AWSRunningInstance.builder()\n                        .region(defaultRegion)\n                        .instanceId(\"i-911444f0\")\n                        .imageId(\"ami-63be790a\")\n                        .instanceState(InstanceState.RUNNING)\n                        .rawState(\"running\")\n                        .privateDnsName(\"ip-10-212-81-7.ec2.internal\")\n                        .dnsName(\"ec2-174-129-173-155.compute-1.amazonaws.com\")\n                        .keyName(\"jclouds#zkclustertest#us-east-1#23\")\n                        .amiLaunchIndex(\"0\")\n                        .instanceType(\"t1.micro\")\n                        .launchTime(dateService.iso8601DateParse(\"2011-08-16T13:40:50.000Z\"))\n                        .availabilityZone(\"us-east-1c\")\n                        .kernelId(\"aki-427d952b\")\n                        .monitoringState(MonitoringState.DISABLED)\n                        .privateIpAddress(\"10.212.81.7\")\n                        .ipAddress(\"174.129.173.155\")\n                        .securityGroupIdToName(\"sg-ef052b86\", \"jclouds#zkclustertest#us-east-1\")\n                        .tag(\"Name\", \"ec2-o\")\n                        .tag(\"Empty\", \"\")\n                        .rootDeviceType(RootDeviceType.EBS)\n                        .rootDeviceName(\"/dev/sda1\")\n                        .device(\n                              \"/dev/sda1\",\n                              new BlockDevice(\"vol-5829fc32\", Attachment.Status.ATTACHED, dateService\n                                    .iso8601DateParse(\"2011-08-16T13:41:19.000Z\"), true))\n                        .hypervisor(Hypervisor.XEN)\n                        .virtualizationType(\"paravirtual\").build())\n               .instance(AWSRunningInstance.builder()\n                        .region(defaultRegion)\n                        .instanceId(\"i-931444f2\")\n                        .imageId(\"ami-63be790a\")\n                        .instanceState(InstanceState.RUNNING)\n                        .rawState(\"running\")\n                        .privateDnsName(\"ip-10-212-185-8.ec2.internal\")\n                        .dnsName(\"ec2-50-19-207-248.compute-1.amazonaws.com\")\n                        .keyName(\"jclouds#zkclustertest#us-east-1#23\")\n                        .amiLaunchIndex(\"0\")\n                        .instanceType(\"t1.micro\")\n                        .launchTime(dateService.iso8601DateParse(\"2011-08-16T13:40:50.000Z\"))\n                        .availabilityZone(\"us-east-1c\")\n                        .kernelId(\"aki-427d952b\")\n                        .monitoringState(MonitoringState.DISABLED)\n                        .privateIpAddress(\"10.212.185.8\")\n                        .ipAddress(\"50.19.207.248\")\n                        .securityGroupIdToNames(\n                              ImmutableMap.<String, String> of(\"sg-ef052b86\", \"jclouds#zkclustertest#us-east-1\"))\n                        .rootDeviceType(RootDeviceType.EBS)\n                        .rootDeviceName(\"/dev/sda1\")\n                        .device(\n                              \"/dev/sda1\",\n                              new BlockDevice(\"vol-5029fc3a\", Attachment.Status.ATTACHED, dateService\n                                    .iso8601DateParse(\"2011-08-16T13:41:19.000Z\"), true))\n                        .hypervisor(Hypervisor.XEN)\n                        .virtualizationType(\"paravirtual\")\n                        .iamInstanceProfileArn(\"arn:aws:iam::123456789012:instance-profile/application_abc/component_xyz/Webserver\")\n                        .iamInstanceProfileId(\"AIPAD5ARO2C5EXAMPLE3G\")\n                        .build()).build());\n\n      Set<Reservation<? extends RunningInstance>> result = parseAWSRunningInstances(\"/describe_instances_latest.xml\");\n\n      assertEquals(result.toString(), contents.toString());\n   }\n\n   public void testParseNoNPE() {\n      parseAWSRunningInstances(\"/describe_instances_1.xml\");\n      parseAWSRunningInstances(\"/describe_instances_2.xml\");\n      parseAWSRunningInstances(\"/describe_instances_3.xml\");\n   }\n\n   static ParseSax<Set<Reservation<? extends RunningInstance>>> createParser() {\n      Injector injector = Guice.createInjector(new SaxParserModule(), new AbstractModule() {\n\n         @Override\n         protected void configure() {\n            bind(new TypeLiteral<Supplier<String>>(){}).annotatedWith(Region.class).toInstance(Suppliers.ofInstance(\"us-east-1\"));\n            bind(RunningInstance.Builder.class).to(AWSRunningInstance.Builder.class);\n         }\n\n      });\n      ParseSax<Set<Reservation<? extends RunningInstance>>> parser = injector\n            .getInstance(ParseSax.Factory.class)\n            .create(injector.getInstance(AWSDescribeInstancesResponseHandler.class));\n      return parser;\n   }\n\n   public static Set<Reservation<? extends RunningInstance>> parseAWSRunningInstances(String resource) {\n      InputStream is = AWSDescribeInstancesResponseHandlerTest.class.getResourceAsStream(resource);\n      return createParser().parse(is);\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/xml/AWSRunInstancesResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.xml;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.aws.ec2.domain.AWSRunningInstance;\nimport org.jclouds.aws.ec2.domain.MonitoringState;\nimport org.jclouds.date.DateService;\nimport org.jclouds.ec2.domain.Hypervisor;\nimport org.jclouds.ec2.domain.InstanceState;\nimport org.jclouds.ec2.domain.InstanceType;\nimport org.jclouds.ec2.domain.Reservation;\nimport org.jclouds.ec2.domain.RunningInstance;\nimport org.jclouds.ec2.xml.BaseEC2HandlerTest;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.http.functions.config.SaxParserModule;\nimport org.jclouds.location.Region;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.TypeLiteral;\n\n/**\n * Tests behavior of {@code RunInstancesResponseHandler}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"RunInstancesResponseHandlerTest\")\npublic class AWSRunInstancesResponseHandlerTest extends BaseEC2HandlerTest {\n\n   private DateService dateService;\n\n   @BeforeTest\n   @Override\n   protected void setUpInjector() {\n      injector = Guice.createInjector(new SaxParserModule(), new AbstractModule() {\n\n         @Override\n         protected void configure() {\n            bind(new TypeLiteral<Supplier<String>>(){}).annotatedWith(Region.class).toInstance(Suppliers.ofInstance(\"us-east-1\"));\n            bind(RunningInstance.Builder.class).to(AWSRunningInstance.Builder.class);\n         }\n\n      });\n      factory = injector.getInstance(ParseSax.Factory.class);\n      dateService = injector.getInstance(DateService.class);\n      assert dateService != null;\n   }\n\n   public void testApplyInputStream() {\n\n      InputStream is = getClass().getResourceAsStream(\"/run_instances.xml\");\n\n      Reservation<? extends AWSRunningInstance> expected = Reservation.<AWSRunningInstance>builder()\n               .region(defaultRegion)\n               .instance(AWSRunningInstance.builder().region(defaultRegion).groupName(\"default\").amiLaunchIndex(\"0\").imageId(\n                        \"ami-60a54009\").instanceId(\"i-2ba64342\").instanceState(InstanceState.PENDING).rawState(\n                        \"pending\").instanceType(InstanceType.M1_SMALL).keyName(\"example-key-name\").launchTime(\n                        dateService.iso8601DateParse(\"2007-08-07T11:51:50.000Z\")).hypervisor(Hypervisor.XEN)\n                        .monitoringState(MonitoringState.ENABLED).availabilityZone(\"us-east-1b\").build())\n               .instance(AWSRunningInstance.builder().region(defaultRegion).groupName(\"default\").amiLaunchIndex(\"1\").imageId(\n                        \"ami-60a54009\").instanceId(\"i-2bc64242\").instanceState(InstanceState.PENDING).rawState(\n                        \"pending\").instanceType(InstanceType.M1_SMALL).keyName(\"example-key-name\").launchTime(\n                        dateService.iso8601DateParse(\"2007-08-07T11:51:50.000Z\")).hypervisor(Hypervisor.XEN)\n                        .monitoringState(MonitoringState.ENABLED).availabilityZone(\"us-east-1b\").build())\n               .instance(AWSRunningInstance.builder().region(defaultRegion).groupName(\"default\").amiLaunchIndex(\"2\").imageId(\n                        \"ami-60a54009\").instanceId(\"i-2be64332\").instanceState(InstanceState.PENDING).rawState(\n                        \"pending\").instanceType(InstanceType.M1_SMALL).keyName(\"example-key-name\").launchTime(\n                        dateService.iso8601DateParse(\"2007-08-07T11:51:50.000Z\")).hypervisor(Hypervisor.XEN)\n                        .monitoringState(MonitoringState.ENABLED).availabilityZone(\"us-east-1b\").build())\n               .ownerId(\"AIDADH4IGTRXXKCD\")\n               .reservationId(\"r-47a5402e\").build();\n\n      AWSRunInstancesResponseHandler handler = injector.getInstance(AWSRunInstancesResponseHandler.class);\n      addDefaultRegionToHandler(handler);\n      Reservation<? extends RunningInstance> result = factory.create(handler).parse(is);\n      assertEquals(result.toString(), expected.toString());\n   }\n\n   public void testApplyInputStreamDoesntNPE() {\n\n      InputStream is = getClass().getResourceAsStream(\"/run_instances_1.xml\");\n      AWSRunInstancesResponseHandler handler = injector.getInstance(AWSRunInstancesResponseHandler.class);\n      addDefaultRegionToHandler(handler);\n      factory.create(handler).parse(is);\n   }\n\n   private void addDefaultRegionToHandler(ParseSax.HandlerWithResult<?> handler) {\n      handler.setContext(request);\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/xml/DescribePlacementGroupsResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.xml;\n\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.aws.ec2.domain.PlacementGroup;\nimport org.jclouds.ec2.xml.BaseEC2HandlerTest;\nimport org.jclouds.http.functions.ParseSax;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code DescribePlacementGroupsResponseHandler}\n */\n//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"DescribePlacementGroupsResponseHandlerTest\")\npublic class DescribePlacementGroupsResponseHandlerTest extends BaseEC2HandlerTest {\n   public void testApplyInputStream() {\n      InputStream is = getClass().getResourceAsStream(\"/describe_placement_groups.xml\");\n\n      PlacementGroup expected = new PlacementGroup(defaultRegion, \"XYZ-cluster\", \"cluster\",\n               PlacementGroup.State.AVAILABLE);\n      DescribePlacementGroupsResponseHandler handler = injector\n               .getInstance(DescribePlacementGroupsResponseHandler.class);\n      addDefaultRegionToHandler(handler);\n      PlacementGroup result = getOnlyElement(factory.create(handler).parse(is));\n\n      assertEquals(result, expected);\n   }\n\n   private void addDefaultRegionToHandler(ParseSax.HandlerWithResult<?> handler) {\n      handler.setContext(request);\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/xml/DescribeReservedInstancesOfferingResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.xml;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.ec2.domain.ReservedInstancesOffering;\nimport org.jclouds.ec2.xml.BaseEC2HandlerTest;\nimport org.jclouds.http.functions.ParseSax;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Iterables;\n\n/**\n * Tests behavior of {@code DescribeReservedInstancesOfferingResponseHandler}\n */\n//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"DescribeReservedInstancesOfferingResponseHandlerTest\")\npublic class DescribeReservedInstancesOfferingResponseHandlerTest extends BaseEC2HandlerTest {\n   public void testApplyInputStream() {\n      InputStream is = getClass().getResourceAsStream(\"/describe_reserved_instances_offerings.xml\");\n\n      ReservedInstancesOffering expected = new ReservedInstancesOffering(\"us-east-1\", \"us-east-1a\", 12, 0.0f, \"m1.small\",\n            \"m1.small offering in us-east-1a\", \"4b2293b4-5813-4cc8-9ce3-1957fc1dcfc8\", 0.0f);\n\n      DescribeReservedInstancesOfferingResponseHandler handler = injector\n            .getInstance(DescribeReservedInstancesOfferingResponseHandler.class);\n      addDefaultRegionToHandler(handler);\n      ReservedInstancesOffering result = Iterables.getOnlyElement(factory.create(handler).parse(is));\n\n      assertEquals(result, expected);\n   }\n\n   private void addDefaultRegionToHandler(ParseSax.HandlerWithResult<?> handler) {\n      handler.setContext(request);\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/xml/DescribeSpotPriceHistoryResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.xml;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\nimport java.util.Set;\n\nimport org.jclouds.aws.ec2.domain.Spot;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.location.Region;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.TypeLiteral;\n\n/**\n * Tests behavior of {@code DescribeSpotPriceHistoryResponseHandler}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"DescribeSpotPriceHistoryResponseHandlerTest\")\npublic class DescribeSpotPriceHistoryResponseHandlerTest extends BaseHandlerTest {\n   public void testApplyInputStream() {\n\n      InputStream is = getClass().getResourceAsStream(\"/describe_spot_price_history.xml\");\n\n      Set<Spot> expected = ImmutableSet.of(\n              Spot.builder().region(\"us-west-1\").instanceType(\"t1.micro\").productDescription(\"SUSE Linux\").spotPrice(0.013f)\n                      .timestamp(new SimpleDateFormatDateService().iso8601DateParse(\"2011-03-07T12:17:19.000Z\"))\n                      .availabilityZone(\"us-west-1a\").build(),\n              Spot.builder().region(\"us-west-1\").instanceType(\"m1.large\").productDescription(\"Linux/UNIX\").spotPrice(0.119f)\n                      .timestamp(new SimpleDateFormatDateService().iso8601DateParse(\"2011-03-07T16:29:16.000Z\"))\n                      .availabilityZone(\"us-west-1b\").build(),\n              Spot.builder().region(\"us-west-1\").instanceType(\"t1.micro\").productDescription(\"Windows\").spotPrice(0.013f)\n                      .timestamp(new SimpleDateFormatDateService().iso8601DateParse(\"2011-03-07T17:56:54.000Z\"))\n                      .availabilityZone(\"us-west-1c\").build()\n\n      );\n\n      Set<Spot> result = factory.create(injector.createChildInjector(new AbstractModule() {\n\n         @Override\n         protected void configure() {\n            bind(new TypeLiteral<Supplier<String>>(){}).annotatedWith(Region.class).toInstance(Suppliers.ofInstance(\"us-west-1\"));\n         }\n         \n      }).getInstance(DescribeSpotPriceHistoryResponseHandler.class)).parse(is);\n\n      assertEquals(result, expected);\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/xml/MonitoringStateHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.xml;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\nimport java.util.Map;\n\nimport org.jclouds.aws.ec2.domain.MonitoringState;\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Tests behavior of {@code MonitoringStateHandler}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"MonitoringStateHandlerTest\")\npublic class MonitoringStateHandlerTest extends BaseHandlerTest {\n   public void testApplyInputStream() {\n\n      InputStream is = getClass().getResourceAsStream(\"/monitoring.xml\");\n\n      Map<String, MonitoringState> expected = ImmutableMap.<String, MonitoringState> of(\n               \"i-43a4412a\", MonitoringState.PENDING, \"i-23a3397d\", MonitoringState.PENDING);\n\n      Map<String, MonitoringState> result = factory.create(\n               injector.getInstance(MonitoringStateHandler.class)).parse(is);\n\n      assertEquals(result, expected);\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/xml/ProductCodesHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.xml;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\nimport java.util.Set;\n\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests behavior of {@code ProductCodesHandler}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"ProductCodesHandlerTest\")\npublic class ProductCodesHandlerTest extends BaseHandlerTest {\n   public void testApplyInputStream() {\n\n      InputStream is = getClass().getResourceAsStream(\n               \"/describe_image_attribute_productCodes.xml\");\n\n      Set<String> expected = ImmutableSet.of(\"774F4FF8\");\n\n      Set<String> result = factory.create(injector.getInstance(ProductCodesHandler.class))\n               .parse(is);\n\n      assertEquals(result, expected);\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/xml/SpotInstanceHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.xml;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.aws.ec2.domain.LaunchSpecification;\nimport org.jclouds.aws.ec2.domain.SpotInstanceRequest;\nimport org.jclouds.aws.ec2.domain.SpotInstanceRequest.State;\nimport org.jclouds.aws.ec2.domain.SpotInstanceRequest.Type;\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.ec2.xml.BaseEC2HandlerTest;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.http.functions.config.SaxParserModule;\nimport org.jclouds.location.Region;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.TypeLiteral;\n\n/**\n * Tests behavior of {@code SpotInstanceHandler}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"SpotInstanceHandlerTest\")\npublic class SpotInstanceHandlerTest extends BaseEC2HandlerTest {\n\n   private DateService dateService;\n\n   @BeforeTest\n   @Override\n   protected void setUpInjector() {\n      injector = Guice.createInjector(new SaxParserModule(), new AbstractModule() {\n\n         @Override\n         protected void configure() {\n            bind(new TypeLiteral<Supplier<String>>(){}).annotatedWith(Region.class).toInstance(Suppliers.ofInstance(\"us-east-1\"));\n         }\n\n      });\n      factory = injector.getInstance(ParseSax.Factory.class);\n      dateService = injector.getInstance(DateService.class);\n      assert dateService != null;\n   }\n\n   public void testApplyInputStream() {\n\n      InputStream is = getClass().getResourceAsStream(\"/request_spot_instances-ebs.xml\");\n\n      SpotInstanceRequest expected = SpotInstanceRequest\n            .builder()\n            .region(\"us-east-1\")\n            .id(\"sir-228e6406\")\n            .spotPrice(0.001f)\n            .type(Type.ONE_TIME)\n            .state(State.OPEN)\n            .rawState(\"open\")\n            .statusCode(\"pending-fulfillment\")\n            .statusMessage(\"Pending fulfillment\")\n            .statusUpdateTime(new SimpleDateFormatDateService().iso8601DateParse(\"2011-03-08T03:30:36.000Z\"))\n            .validFrom(new SimpleDateFormatDateService().iso8601DateParse(\"2011-03-08T03:30:36.000Z\"))\n            .validUntil(new SimpleDateFormatDateService().iso8601DateParse(\"2011-03-08T03:30:36.000Z\"))\n            .launchSpecification(\n                  LaunchSpecification.builder().imageId(\"ami-595a0a1c\").securityGroupIdToName(\"sg-83e1c4ea\", \"default\")\n                        .instanceType(\"m1.large\").mapNewVolumeToDevice(\"/dev/sda1\", 1, true)\n                        .mapEBSSnapshotToDevice(\"/dev/sda2\", \"snap-1ea27576\", 1, true)\n                        .mapEphemeralDeviceToDevice(\"/dev/sda3\", \"vre1\").monitoringEnabled(false)\n                        .iamInstanceProfileArn(\"arn:aws:iam::123456789012:instance-profile/application_abc/component_xyz/Webserver\")\n                        .iamInstanceProfileName(\"Webserver\").build())\n            .createTime(new SimpleDateFormatDateService().iso8601DateParse(\"2011-03-08T03:30:36.000Z\"))\n            .productDescription(\"Linux/UNIX\").build();\n      SpotInstanceHandler handler = injector.getInstance(SpotInstanceHandler.class);\n      addDefaultRegionToHandler(handler);\n      SpotInstanceRequest result = factory.create(handler).parse(is);\n      assertEquals(result.toString(), expected.toString());\n      assertEquals(result.getState(), State.OPEN);\n      assertEquals(result.getRawState(), \"open\");\n      assertEquals(result.getLaunchSpecification().getIAMInstanceProfile().get().getArn().get(),\n            \"arn:aws:iam::123456789012:instance-profile/application_abc/component_xyz/Webserver\");\n      assertEquals(result.getLaunchSpecification().getIAMInstanceProfile().get().getName().get(), \"Webserver\");\n   }\n\n   public void testApplyInputStream1() {\n\n      InputStream is = getClass().getResourceAsStream(\"/describe_spot_instance.xml\");\n\n      SpotInstanceRequest expected = SpotInstanceRequest\n            .builder()\n            .region(\"us-east-1\")\n            .id(\"sir-1ede0012\")\n            .instanceId(\"i-ef308e8e\")\n            .spotPrice(0.300000f)\n            .type(Type.ONE_TIME)\n            .state(State.ACTIVE)\n            .rawState(\"active\")\n            .statusCode(\"fulfilled\")\n            .statusMessage(\"Fulfilled\")\n            .statusUpdateTime(new SimpleDateFormatDateService().iso8601DateParse(\"2011-07-29T05:27:39.000Z\"))\n            .launchedAvailabilityZone(\"us-east-1b\")\n            .launchSpecification(\n                  LaunchSpecification.builder().imageId(\"ami-8e1fece7\")\n                        .securityGroupIdToName(\"sg-83e1c4eb\", \"jclouds#adriancole-ec2unssh#us-east-1\")\n                        .instanceType(\"t1.micro\").monitoringEnabled(false).keyName(\"jclouds#adriancole-ec2unssh\")\n                        .build())\n            .createTime(new SimpleDateFormatDateService().iso8601DateParse(\"2011-07-29T05:27:39.000Z\"))\n            .validFrom(new SimpleDateFormatDateService().iso8601DateParse(\"2011-07-29T05:27:39.000Z\"))\n            .validUntil(new SimpleDateFormatDateService().iso8601DateParse(\"2011-07-29T05:27:39.000Z\"))\n            .productDescription(\"Linux/UNIX\")\n            .tag(\"Name\", \"ec2-o\")\n            .tag(\"Spot\", \"spot-value\")\n            .tag(\"Empty\", \"\")\n            .build();\n      SpotInstanceHandler handler = injector.getInstance(SpotInstanceHandler.class);\n      addDefaultRegionToHandler(handler);\n      SpotInstanceRequest result = factory.create(handler).parse(is);\n      assertEquals(result.toString(), expected.toString());\n      assertEquals(result.getState(), State.ACTIVE);\n      assertEquals(result.getRawState(), \"active\");\n   }\n\n   private void addDefaultRegionToHandler(ParseSax.HandlerWithResult<?> handler) {\n      handler.setContext(request);\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/xml/SpotInstancesHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.ec2.xml;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.aws.ec2.domain.SpotInstanceRequest;\nimport org.jclouds.date.DateService;\nimport org.jclouds.ec2.xml.BaseEC2HandlerTest;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.http.functions.config.SaxParserModule;\nimport org.jclouds.location.Region;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.TypeLiteral;\n\n/**\n * Tests behavior of {@code SpotInstancesHandler}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"SpotInstancesHandlerTest\")\npublic class SpotInstancesHandlerTest extends BaseEC2HandlerTest {\n\n   private DateService dateService;\n\n   @BeforeTest\n   @Override\n   protected void setUpInjector() {\n      injector = Guice.createInjector(new SaxParserModule(), new AbstractModule() {\n\n         @Override\n         protected void configure() {\n            bind(new TypeLiteral<Supplier<String>>(){}).annotatedWith(Region.class).toInstance(Suppliers.ofInstance(\"us-east-1\"));\n         }\n\n      });\n      factory = injector.getInstance(ParseSax.Factory.class);\n      dateService = injector.getInstance(DateService.class);\n      assert dateService != null;\n   }\n\n   public void testDescribe() {\n\n      InputStream is = getClass().getResourceAsStream(\"/describe_spot_instance_requests.xml\");\n      SpotInstancesHandler handler = injector.getInstance(SpotInstancesHandler.class);\n      addDefaultRegionToHandler(handler);\n      Set<SpotInstanceRequest> result = factory.create(handler).parse(is);\n      assertEquals(result.size(), 18);\n   }\n\n   public void testRequest() {\n      InputStream is = getClass().getResourceAsStream(\"/request_spot_instances.xml\");\n      SpotInstancesHandler handler = injector.getInstance(SpotInstancesHandler.class);\n      addDefaultRegionToHandler(handler);\n      Set<SpotInstanceRequest> result = factory.create(handler).parse(is);\n      assertEquals(result.size(), 3);\n   }\n\n   public void testParseTags() {\n       Set<SpotInstanceRequest> result = factory.create(injector.getInstance(SpotInstancesHandler.class)).parse(\n            getClass().getResourceAsStream(\"/describe_spot_instance_tags.xml\"));\n       Iterable<Map<String, String>> tags = Iterables.transform(result, new Function<SpotInstanceRequest, Map<String, String>>() {\n\t       @Override\n\t       public Map<String, String> apply(SpotInstanceRequest input) {\n\t\t       return input.getTags();\n\t       }\n       });\n\n       assertEquals(\n               Iterables.get(tags, 0),\n               ImmutableMap.of(\"One\", \"one\", \"Two\", \"one\"));\n       assertEquals(\n               Iterables.get(tags, 1),\n               ImmutableMap.of(\"One\", \"two\", \"Two\", \"two\"));\n       assertEquals(\n               Iterables.get(tags, 2),\n               ImmutableMap.of(\"Two\", \"three\", \"Three\", \"three\", \"Four\", \"\"));\n   }\n\n   public void testParseNoNPE() {\n      factory.create(injector.getInstance(SpotInstancesHandler.class)).parse(\n            getClass().getResourceAsStream(\"/describe_spot_instances_1.xml\"));\n   }\n\n   private void addDefaultRegionToHandler(ParseSax.HandlerWithResult<?> handler) {\n      handler.setContext(request);\n   }\n}\n"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/alestic_canonical.xml",
    "content": "<?xml version=\"1.0\"?>\n<DescribeImagesResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n    <requestId>6104eee1-affd-49d7-92a0-516cab8a8ba6</requestId>\n    <imagesSet>\n        <item>\n            <imageId>ami-7e28ca17</imageId>\n            <imageLocation>ubuntu-images-us/ubuntu-hardy-8.04-i386-server-20091130.manifest.xml</imageLocation>\n            <imageState>available</imageState>\n            <imageOwnerId>099720109477</imageOwnerId>\n            <isPublic>true</isPublic>\n            <architecture>i386</architecture>\n            <imageType>machine</imageType>\n            <kernelId>aki-92ba58fb</kernelId>\n            <ramdiskId>ari-94ba58fd</ramdiskId>\n            <rootDeviceType>instance-store</rootDeviceType>\n            <blockDeviceMapping />\n        </item>\n        <item>\n            <imageId>ami-19a34270</imageId>\n            <imageLocation>alestic/ubuntu-9.10-karmic-base-20090623.manifest.xml</imageLocation>\n            <imageState>available</imageState>\n            <imageOwnerId>063491364108</imageOwnerId>\n            <isPublic>true</isPublic>\n            <architecture>i386</architecture>\n            <imageType>machine</imageType>\n            <kernelId>aki-a71cf9ce</kernelId>\n            <ramdiskId>ari-a51cf9cc</ramdiskId>\n            <rootDeviceType>instance-store</rootDeviceType>\n            <blockDeviceMapping />\n        </item>\n        <item>\n            <imageId>ami-bb709dd2</imageId>\n            <imageLocation>ubuntu-images-us/ubuntu-karmic-9.10-i386-server-20100121.manifest.xml</imageLocation>\n            <imageState>available</imageState>\n            <imageOwnerId>099720109477</imageOwnerId>\n            <isPublic>true</isPublic>\n            <architecture>i386</architecture>\n            <imageType>machine</imageType>\n            <kernelId>aki-5f15f636</kernelId>\n            <ramdiskId>ari-d5709dbc</ramdiskId>\n            <rootDeviceType>instance-store</rootDeviceType>\n            <blockDeviceMapping />\n        </item>\n        <item>\n            <imageId>ami-190fe070</imageId>\n            <imageLocation>ubuntu-images-testing-us/ubuntu-lucid-daily-amd64-desktop-20100317.manifest.xml</imageLocation>\n            <imageState>available</imageState>\n            <imageOwnerId>099720109477</imageOwnerId>\n            <isPublic>true</isPublic>\n            <architecture>x86_64</architecture>\n            <imageType>machine</imageType>\n            <kernelId>aki-11c72878</kernelId>\n            <name>ubuntu-images-testing/ubuntu-lucid-daily-amd64-desktop-20100317</name>\n            <rootDeviceType>instance-store</rootDeviceType>\n            <blockDeviceMapping />\n        </item>\n        <item>\n            <imageId>ami-c0fa1ea9</imageId>\n            <imageLocation>alestic/ubuntu-8.04-hardy-base-20080905.manifest.xml</imageLocation>\n            <imageState>available</imageState>\n            <imageOwnerId>063491364108</imageOwnerId>\n            <isPublic>true</isPublic>\n            <architecture>i386</architecture>\n            <imageType>machine</imageType>\n            <kernelId>aki-a71cf9ce</kernelId>\n            <ramdiskId>ari-a51cf9cc</ramdiskId>\n            <rootDeviceType>instance-store</rootDeviceType>\n            <blockDeviceMapping />\n        </item>\n        <item>\n            <imageId>ami-c597c680</imageId>\n            <imageLocation>ubuntu-images-us-west-1/ubuntu-lucid-10.04-i386-server-20100427.1.manifest.xml</imageLocation>\n            <imageState>available</imageState>\n            <imageOwnerId>099720109477</imageOwnerId>\n            <isPublic>true</isPublic>\n            <architecture>i386</architecture>\n            <imageType>machine</imageType>\n            <kernelId>aki-3197c674</kernelId>\n            <name>ubuntu-images/ubuntu-lucid-10.04-i386-server-20100427.1</name>\n            <rootDeviceType>instance-store</rootDeviceType>\n            <blockDeviceMapping/>        \n        </item>\n        <item>\n            <imageId>aki-fd15f694</imageId>\n            <imageLocation>ubuntu-kernels-us/ubuntu-karmic-amd64-linux-image-2.6.31-302-ec2-v-2.6.31-302.7-kernel.img.manifest.xml</imageLocation>\n            <imageState>available</imageState>\n            <imageOwnerId>099720109477</imageOwnerId>\n            <isPublic>true</isPublic>\n            <architecture>x86_64</architecture>\n            <imageType>kernel</imageType>\n            <rootDeviceType>instance-store</rootDeviceType>\n            <blockDeviceMapping />\n        </item>\n        <item>\n            <imageId>ami-10f3a255</imageId>\n            <imageLocation>099720109477/ebs/ubuntu-images/ubuntu-lucid-10.04-i386-server-20100827</imageLocation>\n            <imageState>available</imageState>\n            <imageOwnerId>099720109477</imageOwnerId>\n            <isPublic>true</isPublic>\n            <architecture>i386</architecture>\n            <imageType>machine</imageType>\n            <kernelId>aki-a8f0a1ed</kernelId>\n            <name>ebs/ubuntu-images/ubuntu-lucid-10.04-i386-server-20100827</name>\n            <rootDeviceType>ebs</rootDeviceType>\n            <rootDeviceName>/dev/sda1</rootDeviceName>\n            <blockDeviceMapping>\n                <item>\n                    <deviceName>/dev/sda1</deviceName>\n                    <ebs>\n                        <snapshotId>snap-76eff01e</snapshotId>\n                        <volumeSize>15</volumeSize>\n                        <deleteOnTermination>true</deleteOnTermination>\n                    </ebs>\n                </item>\n            </blockDeviceMapping>\n            <virtualizationType>paravirtual</virtualizationType>\n        </item>\n    </imagesSet>\n</DescribeImagesResponse>\n"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/amzn_images.xml",
    "content": "<?xml version=\"1.0\"?>\n<DescribeImagesResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n    <requestId>6104eee1-affd-49d7-92a0-516cab8a8ba6</requestId>\n    <imagesSet>\n        <item>\n            <imageId>ami-82e4b5c7</imageId>\n            <imageLocation>137112412989/amzn-ami-0.9.7-beta.i386-ebs</imageLocation>\n            <imageState>available</imageState>\n            <imageOwnerId>137112412989</imageOwnerId>\n            <isPublic>true</isPublic>\n            <architecture>i386</architecture>\n            <imageType>machine</imageType>\n            <kernelId>aki-99a0f1dc</kernelId>\n            <name>amzn-ami-0.9.7-beta.i386-ebs</name>\n            <description>Amazon</description>\n            <rootDeviceType>ebs</rootDeviceType>\n            <rootDeviceName>/dev/sda1</rootDeviceName>\n            <blockDeviceMapping>\n                <item>\n                    <deviceName>/dev/sda1</deviceName>\n                    <ebs>\n                        <snapshotId>snap-e98b7b82</snapshotId>\n                        <volumeSize>10</volumeSize>\n                        <deleteOnTermination>true</deleteOnTermination>\n                    </ebs>\n                </item>\n            </blockDeviceMapping>\n            <virtualizationType>paravirtual</virtualizationType>\n        </item>\n        <item>\n            <imageId>ami-8ce4b5c9</imageId>\n            <imageLocation>137112412989/amzn-ami-0.9.7-beta.x86_64-ebs</imageLocation>\n            <imageState>available</imageState>\n            <imageOwnerId>137112412989</imageOwnerId>\n            <isPublic>true</isPublic>\n            <architecture>x86_64</architecture>\n            <imageType>machine</imageType>\n            <kernelId>aki-9ba0f1de</kernelId>\n            <name>amzn-ami-0.9.7-beta.x86_64-ebs</name>\n            <description>Amazon</description>\n            <rootDeviceType>ebs</rootDeviceType>\n            <rootDeviceName>/dev/sda1</rootDeviceName>\n            <blockDeviceMapping>\n                <item>\n                    <deviceName>/dev/sda1</deviceName>\n                    <ebs>\n                        <snapshotId>snap-8d8b7be6</snapshotId>\n                        <volumeSize>10</volumeSize>\n                        <deleteOnTermination>true</deleteOnTermination>\n                    </ebs>\n                </item>\n            </blockDeviceMapping>\n            <virtualizationType>paravirtual</virtualizationType>\n        </item>\n        <item>\n            <imageId>ami-f0e4b5b5</imageId>\n            <imageLocation>amzn-ami-us-west-1/amzn-ami-0.9.7-beta.i386.manifest.xml</imageLocation>\n            <imageState>available</imageState>\n            <imageOwnerId>137112412989</imageOwnerId>\n            <isPublic>true</isPublic>\n            <architecture>i386</architecture>\n            <imageType>machine</imageType>\n            <kernelId>aki-99a0f1dc</kernelId>\n            <name>amzn-ami-0.9.7-beta.i386-S3</name>\n            <description>Amazon Linux AMI i386 S3</description>\n            <rootDeviceType>instance-store</rootDeviceType>\n            <blockDeviceMapping/>\n            <virtualizationType>paravirtual</virtualizationType>\n        </item>\n        <item>\n            <imageId>ami-f2e4b5b7</imageId>\n            <imageLocation>amzn-ami-us-west-1/amzn-ami-0.9.7-beta.x86_64.manifest.xml</imageLocation>\n            <imageState>available</imageState>\n            <imageOwnerId>137112412989</imageOwnerId>\n            <isPublic>true</isPublic>\n            <architecture>x86_64</architecture>\n            <imageType>machine</imageType>\n            <kernelId>aki-9ba0f1de</kernelId>\n            <name>amzn-ami-0.9.7-beta.x86_64-S3</name>\n            <description>Amazon Linux AMI x86_64 S3</description>\n            <rootDeviceType>instance-store</rootDeviceType>\n            <blockDeviceMapping/>\n            <virtualizationType>paravirtual</virtualizationType>\n        </item>\n    </imagesSet>\n</DescribeImagesResponse>\n"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/associate_route_table.xml",
    "content": "<AssociateRouteTableResponse xmlns=\"http://ec2.amazonaws.com/doc/2012-06-01/\">\n    <requestId>f87d1645-3919-4e26-b98f-852c47def4ee</requestId>\n    <associationId>rtbassoc-fb7fed9d</associationId>\n</AssociateRouteTableResponse>"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/attach_internet_gateway.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<AttachInternetGatewayResponse xmlns=\"http://ec2.amazonaws.com/doc/2012-06-01/\">\n    <requestId>87565c19-59bf-4f71-8f9a-9dcfec2b6640</requestId>\n    <return>true</return>\n</AttachInternetGatewayResponse>"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/attach_internet_gateway_failed.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<AttachInternetGatewayResponse xmlns=\"http://ec2.amazonaws.com/doc/2012-06-01/\">\n    <requestId>87565c19-59bf-4f71-8f9a-9dcfec2b6640</requestId>\n    <return>false</return>\n</AttachInternetGatewayResponse>"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/centos_marketplace_images.xml",
    "content": "<?xml version=\"1.0\"?>\n<DescribeImagesResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n    <requestId>6104eee1-affd-49d7-92a0-516cab8a8ba6</requestId>\n    <imagesSet>\n        <item>\n            <imageId>ami-061b1560</imageId>\n            <imageLocation>aws-marketplace/CentOS Linux 7 x86_64 HVM EBS 1704_01-b7ee8a69-ee97-4a49-9e68-afaee216db2e-ami-d52f5bc3.4</imageLocation>\n            <imageState>available</imageState>\n            <imageOwnerId>679593333241</imageOwnerId>\n            <isPublic>true</isPublic>\n            <productCodes>\n                <item>\n                    <productCode>aw0evgkw8e5c1q413zgy5pjce</productCode>\n                    <type>marketplace</type>\n                </item>\n            </productCodes>\n            <architecture>x86_64</architecture>\n            <imageType>machine</imageType>\n            <imageOwnerAlias>aws-marketplace</imageOwnerAlias>\n            <name>CentOS Linux 7 x86_64 HVM EBS 1704_01-b7ee8a69-ee97-4a49-9e68-afaee216db2e-ami-d52f5bc3.4</name>\n            <description>CentOS Linux 7 x86_64 HVM EBS 1704_01</description>\n            <rootDeviceType>ebs</rootDeviceType>\n            <rootDeviceName>/dev/sda1</rootDeviceName>\n            <blockDeviceMapping>\n                <item>\n                    <deviceName>/dev/sda1</deviceName>\n                    <ebs>\n                        <snapshotId>snap-00f18f3f6413c7879</snapshotId>\n                        <volumeSize>8</volumeSize>\n                        <deleteOnTermination>false</deleteOnTermination>\n                    </ebs>\n                </item>\n            </blockDeviceMapping>\n            <virtualizationType>hvm</virtualizationType>\n            <hypervisor>xen</hypervisor>\n        </item>\n    </imagesSet>\n</DescribeImagesResponse>\n"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/create_internet_gateway.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<CreateInternetGatewayResponse xmlns=\"http://ec2.amazonaws.com/doc/2012-06-01/\">\n    <requestId>85c22645-f966-4025-9cb3-64bb5c833a54</requestId>\n    <internetGateway>\n        <internetGatewayId>igw-fada7c9c</internetGatewayId>\n        <attachmentSet/>\n        <tagSet/>\n    </internetGateway>\n</CreateInternetGatewayResponse>"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/create_route.xml",
    "content": "<CreateRouteResponse xmlns=\"http://ec2.amazonaws.com/doc/2012-06-01/\">\n    <requestId>3b1d5abc-0d50-4367-87c1-a4dcc2f8b928</requestId>\n    <return>true</return>\n</CreateRouteResponse>\n"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/create_route_table.xml",
    "content": "<CreateRouteTableResponse xmlns=\"http://ec2.amazonaws.com/doc/2012-06-01/\">\n    <requestId>59dbff89-35bd-4eac-99ed-be587EXAMPLE</requestId>\n    <routeTable>\n        <routeTableId>rtb-8bda6cef</routeTableId>\n        <vpcId>vpc-1a2b3c4d</vpcId>\n        <routeSet>\n            <item>\n                <destinationCidrBlock>10.0.0.0/16</destinationCidrBlock>\n                <gatewayId>local</gatewayId>\n                <state>active</state>\n                <origin>CreateRouteTable</origin>\n            </item>\n            <item>\n                <destinationIpv6CidrBlock>2001:db8:1234:1a00::/56</destinationIpv6CidrBlock>\n                <gatewayId>local</gatewayId>\n                <state>active</state>\n                <origin>CreateRouteTable</origin>\n            </item>\n        </routeSet>\n        <associationSet/>\n        <propagatingVgwSet/>\n        <tagSet/>\n    </routeTable>\n</CreateRouteTableResponse>"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/create_vpc.xml",
    "content": "<CreateVpcResponse xmlns=\"http://ec2.amazonaws.com/doc/2016-09-15/\">\n    <requestId>7a62c49f-347e-4fc4-9331-6e8eEXAMPLE</requestId>\n    <vpc>\n        <vpcId>vpc-1a2b3c4d</vpcId>\n        <state>pending</state>\n        <cidrBlock>10.0.0.0/16</cidrBlock>\n        <dhcpOptionsId>dopt-1a2b3c4d2</dhcpOptionsId>\n        <instanceTenancy>default</instanceTenancy>\n        <tagSet/>\n    </vpc>\n</CreateVpcResponse>\n"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/delete_internet_gateway.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<DeleteInternetGatewayResponse xmlns=\"http://ec2.amazonaws.com/doc/2012-06-01/\">\n    <requestId>de1da0ea-085f-4783-b270-af5338060497</requestId>\n    <return>true</return>\n</DeleteInternetGatewayResponse>\n\n"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/delete_route.xml",
    "content": "<DeleteRouteResponse xmlns=\"http://ec2.amazonaws.com/doc/2012-06-01/\">\n    <requestId>6d6d0513-5af2-46ae-8f8a-24c8c3ab0f70</requestId>\n    <return>true</return>\n</DeleteRouteResponse>\n"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/delete_route_table.xml",
    "content": "<DeleteRouteTableResponse xmlns=\"http://ec2.amazonaws.com/doc/2012-06-01/\">\n    <requestId>59dbff89-35bd-4eac-99ed-be587EXAMPLE</requestId>\n    <return>true</return>\n</DeleteRouteTableResponse>"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/delete_vpc.xml",
    "content": "<DeleteVpcResponse xmlns=\"http://ec2.amazonaws.com/doc/2016-09-15/\">\n    <requestId>7a62c49f-347e-4fc4-9331-6e8eEXAMPLE</requestId>\n    <return>true</return>\n</DeleteVpcResponse>\n"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/describe_image_attribute_productCodes.xml",
    "content": "<DescribeImageAttributeResponse\n    xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n    <imageId>ami-61a54008</imageId>\n    <productCodes>\n        <item>\n            <productCode>774F4FF8</productCode>\n        </item>\n    </productCodes>\n</DescribeImageAttributeResponse>"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/describe_images_cc.xml",
    "content": "<?xml version=\"1.0\"?>\n<DescribeImagesResponse xmlns=\"http://ec2.amazonaws.com/doc/2010-06-15/\">\n    <requestId>31e35e56-dd3e-43d3-9c3b-656cb202d6e7</requestId>\n    <imagesSet>\n        <item>\n            <imageId>ami-7ea24a17</imageId>\n            <imageLocation>amazon/EC2 CentOS 5.4 HVM AMI</imageLocation>\n            <imageState>available</imageState>\n            <imageOwnerId>206029621532</imageOwnerId>\n            <isPublic>true</isPublic>\n            <architecture>x86_64</architecture>\n            <imageType>machine</imageType>\n            <imageOwnerAlias>amazon</imageOwnerAlias>\n            <name>EC2 CentOS 5.4 HVM AMI</name>\n            <description>EC2 CentOS 5.4 HVM AMI</description>\n            <rootDeviceType>ebs</rootDeviceType>\n            <rootDeviceName>/dev/sda1</rootDeviceName>\n            <blockDeviceMapping>\n                <item>\n                    <deviceName>/dev/sda1</deviceName>\n                    <ebs>\n                        <snapshotId>snap-1099e578</snapshotId>\n                        <volumeSize>20</volumeSize>\n                        <deleteOnTermination>true</deleteOnTermination>\n                    </ebs>\n                </item>\n            </blockDeviceMapping>\n            <virtualizationType>hvm</virtualizationType>\n        </item>\n    </imagesSet>\n</DescribeImagesResponse>\n"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/describe_instances_1.xml",
    "content": "<DescribeInstancesResponse xmlns=\"http://ec2.amazonaws.com/doc/2012-06-01/\">\n    <requestId>b3e1c7ee-1f34-4582-9493-695c9425c679</requestId>\n    <reservationSet>\n        <item>\n            <reservationId>r-51cb663e</reservationId>\n            <ownerId>993194456877</ownerId>\n            <groupSet>\n                <item>\n                    <groupId>sg-15f4d17c</groupId>\n                    <groupName>jclouds#ec2-e#us-east-1</groupName>\n                </item>\n            </groupSet>\n            <instancesSet>\n                <item>\n                    <instanceId>i-059c2564</instanceId>\n                    <imageId>ami-eb71b682</imageId>\n                    <instanceState>\n                        <code>0</code>\n                        <name>pending</name>\n                    </instanceState>\n                    <privateDnsName/>\n                    <dnsName/>\n                    <reason/>\n                    <keyName>jclouds#ec2-e#us-east-1#85</keyName>\n                    <amiLaunchIndex>0</amiLaunchIndex>\n                    <productCodes/>\n                    <instanceType>m1.small</instanceType>\n                    <launchTime>2011-07-29T08:29:49.000Z</launchTime>\n                    <placement>\n                        <availabilityZone>us-east-1c</availabilityZone>\n                        <groupName/>\n                        <tenancy>default</tenancy>\n                    </placement>\n                    <kernelId>aki-407d9529</kernelId>\n                    <monitoring>\n                        <state>disabled</state>\n                    </monitoring>\n                    <groupSet>\n                        <item>\n                            <groupId>sg-15f4d17c</groupId>\n                            <groupName>jclouds#ec2-e#us-east-1</groupName>\n                        </item>\n                    </groupSet>\n                    <architecture>i386</architecture>\n                    <rootDeviceType>ebs</rootDeviceType>\n                    <rootDeviceName>/dev/sda1</rootDeviceName>\n                    <blockDeviceMapping/>\n                    <virtualizationType>paravirtual</virtualizationType>\n                    <clientToken/>\n                    <hypervisor>xen</hypervisor>\n                </item>\n            </instancesSet>\n        </item>\n    </reservationSet>\n</DescribeInstancesResponse>"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/describe_instances_2.xml",
    "content": "<DescribeInstancesResponse xmlns=\"http://ec2.amazonaws.com/doc/2012-06-01/\">\n    <requestId>b2238f71-750f-4eed-8f5c-eb4e6f66b687</requestId>\n    <reservationSet>\n        <item>\n            <reservationId>r-7f54f610</reservationId>\n            <ownerId>993194456877</ownerId>\n            <groupSet>\n                <item>\n                    <groupId>sg-1df4d174</groupId>\n                    <groupName>jclouds#ec2-#us-east-1</groupName>\n                </item>\n            </groupSet>\n            <instancesSet>\n                <item>\n                    <instanceId>i-8f348aee</instanceId>\n                    <imageId>ami-8e1fece7</imageId>\n                    <instanceState>\n                        <code>48</code>\n                        <name>terminated</name>\n                    </instanceState>\n                    <privateDnsName/>\n                    <dnsName/>\n                    <reason>User initiated (2011-07-29 08:04:49 GMT)</reason>\n                    <keyName>jclouds#ec2-#us-east-1#95</keyName>\n                    <amiLaunchIndex>0</amiLaunchIndex>\n                    <productCodes/>\n                    <instanceType>t1.micro</instanceType>\n                    <launchTime>2011-07-29T05:35:18.000Z</launchTime>\n                    <placement>\n                        <availabilityZone>us-east-1b</availabilityZone>\n                        <groupName/>\n                        <tenancy>default</tenancy>\n                    </placement>\n                    <kernelId>aki-427d952b</kernelId>\n                    <monitoring>\n                        <state>disabled</state>\n                    </monitoring>\n                    <groupSet>\n                        <item>\n                            <groupId>sg-1df4d174</groupId>\n                            <groupName>jclouds#ec2-#us-east-1</groupName>\n                        </item>\n                    </groupSet>\n                    <stateReason>\n                        <code>Client.UserInitiatedShutdown</code>\n                        <message>Client.UserInitiatedShutdown: User initiated shutdown</message>\n                    </stateReason>\n                    <architecture>x86_64</architecture>\n                    <rootDeviceType>ebs</rootDeviceType>\n                    <rootDeviceName>/dev/sda1</rootDeviceName>\n                    <blockDeviceMapping/>\n                    <virtualizationType>paravirtual</virtualizationType>\n                    <clientToken/>\n                    <hypervisor>xen</hypervisor>\n                </item>\n                <item>\n                    <instanceId>i-91348af0</instanceId>\n                    <imageId>ami-8e1fece7</imageId>\n                    <instanceState>\n                        <code>48</code>\n                        <name>terminated</name>\n                    </instanceState>\n                    <privateDnsName/>\n                    <dnsName/>\n                    <reason>User initiated (2011-07-29 08:14:38 GMT)</reason>\n                    <keyName>jclouds#ec2-#us-east-1#95</keyName>\n                    <amiLaunchIndex>1</amiLaunchIndex>\n                    <productCodes/>\n                    <instanceType>t1.micro</instanceType>\n                    <launchTime>2011-07-29T05:35:18.000Z</launchTime>\n                    <placement>\n                        <availabilityZone>us-east-1b</availabilityZone>\n                        <groupName/>\n                        <tenancy>default</tenancy>\n                    </placement>\n                    <kernelId>aki-427d952b</kernelId>\n                    <monitoring>\n                        <state>disabled</state>\n                    </monitoring>\n                    <groupSet>\n                        <item>\n                            <groupId>sg-1df4d174</groupId>\n                            <groupName>jclouds#ec2-#us-east-1</groupName>\n                        </item>\n                    </groupSet>\n                    <stateReason>\n                        <code>Client.UserInitiatedShutdown</code>\n                        <message>Client.UserInitiatedShutdown: User initiated shutdown</message>\n                    </stateReason>\n                    <architecture>x86_64</architecture>\n                    <rootDeviceType>ebs</rootDeviceType>\n                    <rootDeviceName>/dev/sda1</rootDeviceName>\n                    <blockDeviceMapping/>\n                    <virtualizationType>paravirtual</virtualizationType>\n                    <clientToken/>\n                    <hypervisor>xen</hypervisor>\n                </item>\n            </instancesSet>\n        </item>\n        <item>\n            <reservationId>r-7be24f14</reservationId>\n            <ownerId>993194456877</ownerId>\n            <groupSet>\n                <item>\n                    <groupId>sg-dbf5d0b2</groupId>\n                    <groupName>jclouds#ec2-o#us-east-1</groupName>\n                </item>\n                <item>\n                    <groupId>sg-d9f5d0b0</groupId>\n                    <groupName>ec2-o</groupName>\n                </item>\n            </groupSet>\n            <instancesSet>\n                <item>\n                    <instanceId>i-43b00922</instanceId>\n                    <imageId>ami-8e1fece7</imageId>\n                    <instanceState>\n                        <code>48</code>\n                        <name>terminated</name>\n                    </instanceState>\n                    <privateDnsName/>\n                    <dnsName/>\n                    <reason>User initiated (2011-07-29 08:03:24 GMT)</reason>\n                    <keyName>ec2-o</keyName>\n                    <amiLaunchIndex>0</amiLaunchIndex>\n                    <productCodes/>\n                    <instanceType>t1.micro</instanceType>\n                    <launchTime>2011-07-29T07:57:49.000Z</launchTime>\n                    <placement>\n                        <availabilityZone>us-east-1c</availabilityZone>\n                        <groupName/>\n                        <tenancy>default</tenancy>\n                    </placement>\n                    <kernelId>aki-427d952b</kernelId>\n                    <monitoring>\n                        <state>enabled</state>\n                    </monitoring>\n                    <groupSet>\n                        <item>\n                            <groupId>sg-dbf5d0b2</groupId>\n                            <groupName>jclouds#ec2-o#us-east-1</groupName>\n                        </item>\n                        <item>\n                            <groupId>sg-d9f5d0b0</groupId>\n                            <groupName>ec2-o</groupName>\n                        </item>\n                    </groupSet>\n                    <stateReason>\n                        <code>Client.UserInitiatedShutdown</code>\n                        <message>Client.UserInitiatedShutdown: User initiated shutdown</message>\n                    </stateReason>\n                    <architecture>x86_64</architecture>\n                    <rootDeviceType>ebs</rootDeviceType>\n                    <rootDeviceName>/dev/sda1</rootDeviceName>\n                    <blockDeviceMapping/>\n                    <instanceLifecycle>spot</instanceLifecycle>\n                    <spotInstanceRequestId>sir-cc233214</spotInstanceRequestId>\n                    <virtualizationType>paravirtual</virtualizationType>\n                    <clientToken/>\n                    <hypervisor>xen</hypervisor>\n                </item>\n            </instancesSet>\n            <requesterId>854251627541</requesterId>\n        </item>\n        <item>\n            <reservationId>r-7bfe5314</reservationId>\n            <ownerId>993194456877</ownerId>\n            <groupSet>\n                <item>\n                    <groupId>sg-25f4d14c</groupId>\n                    <groupName>jclouds#ec2-r#us-east-1</groupName>\n                </item>\n            </groupSet>\n            <instancesSet>\n                <item>\n                    <instanceId>i-ddb70ebc</instanceId>\n                    <imageId>ami-8e1fece7</imageId>\n                    <instanceState>\n                        <code>48</code>\n                        <name>terminated</name>\n                    </instanceState>\n                    <privateDnsName/>\n                    <dnsName/>\n                    <reason>User initiated (2011-07-29 08:04:22 GMT)</reason>\n                    <keyName>jclouds#ec2-r#us-east-1#3</keyName>\n                    <amiLaunchIndex>0</amiLaunchIndex>\n                    <productCodes/>\n                    <instanceType>t1.micro</instanceType>\n                    <launchTime>2011-07-29T08:04:18.000Z</launchTime>\n                    <placement>\n                        <availabilityZone>us-east-1b</availabilityZone>\n                        <groupName/>\n                        <tenancy>default</tenancy>\n                    </placement>\n                    <kernelId>aki-427d952b</kernelId>\n                    <monitoring>\n                        <state>disabled</state>\n                    </monitoring>\n                    <groupSet>\n                        <item>\n                            <groupId>sg-25f4d14c</groupId>\n                            <groupName>jclouds#ec2-r#us-east-1</groupName>\n                        </item>\n                    </groupSet>\n                    <stateReason>\n                        <code>Client.UserInitiatedShutdown</code>\n                        <message>Client.UserInitiatedShutdown: User initiated shutdown</message>\n                    </stateReason>\n                    <architecture>x86_64</architecture>\n                    <rootDeviceType>ebs</rootDeviceType>\n                    <rootDeviceName>/dev/sda1</rootDeviceName>\n                    <blockDeviceMapping/>\n                    <virtualizationType>paravirtual</virtualizationType>\n                    <clientToken/>\n                    <hypervisor>xen</hypervisor>\n                </item>\n            </instancesSet>\n        </item>\n        <item>\n            <reservationId>r-7bf95414</reservationId>\n            <ownerId>993194456877</ownerId>\n            <groupSet>\n                <item>\n                    <groupId>sg-1df4d174</groupId>\n                    <groupName>jclouds#ec2-#us-east-1</groupName>\n                </item>\n            </groupSet>\n            <instancesSet>\n                <item>\n                    <instanceId>i-e9a91088</instanceId>\n                    <imageId>ami-8e1fece7</imageId>\n                    <instanceState>\n                        <code>48</code>\n                        <name>terminated</name>\n                    </instanceState>\n                    <privateDnsName/>\n                    <dnsName/>\n                    <reason>User initiated (2011-07-29 08:14:38 GMT)</reason>\n                    <keyName>jclouds#ec2-#us-east-1#73</keyName>\n                    <amiLaunchIndex>0</amiLaunchIndex>\n                    <productCodes/>\n                    <instanceType>t1.micro</instanceType>\n                    <launchTime>2011-07-29T08:05:48.000Z</launchTime>\n                    <placement>\n                        <availabilityZone>us-east-1b</availabilityZone>\n                        <groupName/>\n                        <tenancy>default</tenancy>\n                    </placement>\n                    <kernelId>aki-427d952b</kernelId>\n                    <monitoring>\n                        <state>disabled</state>\n                    </monitoring>\n                    <groupSet>\n                        <item>\n                            <groupId>sg-1df4d174</groupId>\n                            <groupName>jclouds#ec2-#us-east-1</groupName>\n                        </item>\n                    </groupSet>\n                    <stateReason>\n                        <code>Client.UserInitiatedShutdown</code>\n                        <message>Client.UserInitiatedShutdown: User initiated shutdown</message>\n                    </stateReason>\n                    <architecture>x86_64</architecture>\n                    <rootDeviceType>ebs</rootDeviceType>\n                    <rootDeviceName>/dev/sda1</rootDeviceName>\n                    <blockDeviceMapping/>\n                    <virtualizationType>paravirtual</virtualizationType>\n                    <clientToken/>\n                    <hypervisor>xen</hypervisor>\n                </item>\n                <item>\n                    <instanceId>i-eba9108a</instanceId>\n                    <imageId>ami-8e1fece7</imageId>\n                    <instanceState>\n                        <code>48</code>\n                        <name>terminated</name>\n                    </instanceState>\n                    <privateDnsName/>\n                    <dnsName/>\n                    <reason>User initiated (2011-07-29 08:14:38 GMT)</reason>\n                    <keyName>jclouds#ec2-#us-east-1#73</keyName>\n                    <amiLaunchIndex>1</amiLaunchIndex>\n                    <productCodes/>\n                    <instanceType>t1.micro</instanceType>\n                    <launchTime>2011-07-29T08:05:48.000Z</launchTime>\n                    <placement>\n                        <availabilityZone>us-east-1b</availabilityZone>\n                        <groupName/>\n                        <tenancy>default</tenancy>\n                    </placement>\n                    <kernelId>aki-427d952b</kernelId>\n                    <monitoring>\n                        <state>disabled</state>\n                    </monitoring>\n                    <groupSet>\n                        <item>\n                            <groupId>sg-1df4d174</groupId>\n                            <groupName>jclouds#ec2-#us-east-1</groupName>\n                        </item>\n                    </groupSet>\n                    <stateReason>\n                        <code>Client.UserInitiatedShutdown</code>\n                        <message>Client.UserInitiatedShutdown: User initiated shutdown</message>\n                    </stateReason>\n                    <architecture>x86_64</architecture>\n                    <rootDeviceType>ebs</rootDeviceType>\n                    <rootDeviceName>/dev/sda1</rootDeviceName>\n                    <blockDeviceMapping/>\n                    <virtualizationType>paravirtual</virtualizationType>\n                    <clientToken/>\n                    <hypervisor>xen</hypervisor>\n                </item>\n            </instancesSet>\n        </item>\n        <item>\n            <reservationId>r-5df95432</reservationId>\n            <ownerId>993194456877</ownerId>\n            <groupSet>\n                <item>\n                    <groupId>sg-1ff4d176</groupId>\n                    <groupName>jclouds#ec2-block#us-east-1</groupName>\n                </item>\n            </groupSet>\n            <instancesSet>\n                <item>\n                    <instanceId>i-c9a910a8</instanceId>\n                    <imageId>ami-8e1fece7</imageId>\n                    <instanceState>\n                        <code>48</code>\n                        <name>terminated</name>\n                    </instanceState>\n                    <privateDnsName/>\n                    <dnsName/>\n                    <reason>User initiated (2011-07-29 08:06:01 GMT)</reason>\n                    <keyName>jclouds#ec2-block#us-east-1#61</keyName>\n                    <amiLaunchIndex>0</amiLaunchIndex>\n                    <productCodes/>\n                    <instanceType>t1.micro</instanceType>\n                    <launchTime>2011-07-29T08:05:58.000Z</launchTime>\n                    <placement>\n                        <availabilityZone>us-east-1b</availabilityZone>\n                        <groupName/>\n                        <tenancy>default</tenancy>\n                    </placement>\n                    <kernelId>aki-427d952b</kernelId>\n                    <monitoring>\n                        <state>disabled</state>\n                    </monitoring>\n                    <groupSet>\n                        <item>\n                            <groupId>sg-1ff4d176</groupId>\n                            <groupName>jclouds#ec2-block#us-east-1</groupName>\n                        </item>\n                    </groupSet>\n                    <stateReason>\n                        <code>Client.UserInitiatedShutdown</code>\n                        <message>Client.UserInitiatedShutdown: User initiated shutdown</message>\n                    </stateReason>\n                    <architecture>x86_64</architecture>\n                    <rootDeviceType>ebs</rootDeviceType>\n                    <rootDeviceName>/dev/sda1</rootDeviceName>\n                    <blockDeviceMapping/>\n                    <virtualizationType>paravirtual</virtualizationType>\n                    <clientToken/>\n                    <hypervisor>xen</hypervisor>\n                </item>\n            </instancesSet>\n        </item>\n        <item>\n            <reservationId>r-f3f9549c</reservationId>\n            <ownerId>993194456877</ownerId>\n            <groupSet>\n                <item>\n                    <groupId>sg-15f4d17c</groupId>\n                    <groupName>jclouds#ec2-e#us-east-1</groupName>\n                </item>\n            </groupSet>\n            <instancesSet>\n                <item>\n                    <instanceId>i-77a81116</instanceId>\n                    <imageId>ami-eb71b682</imageId>\n                    <instanceState>\n                        <code>48</code>\n                        <name>terminated</name>\n                    </instanceState>\n                    <privateDnsName/>\n                    <dnsName/>\n                    <reason>User initiated (2011-07-29 08:06:19 GMT)</reason>\n                    <keyName>jclouds#ec2-e#us-east-1#6</keyName>\n                    <amiLaunchIndex>0</amiLaunchIndex>\n                    <productCodes/>\n                    <instanceType>m1.small</instanceType>\n                    <launchTime>2011-07-29T08:06:15.000Z</launchTime>\n                    <placement>\n                        <availabilityZone>us-east-1b</availabilityZone>\n                        <groupName/>\n                        <tenancy>default</tenancy>\n                    </placement>\n                    <kernelId>aki-407d9529</kernelId>\n                    <monitoring>\n                        <state>disabled</state>\n                    </monitoring>\n                    <groupSet>\n                        <item>\n                            <groupId>sg-15f4d17c</groupId>\n                            <groupName>jclouds#ec2-e#us-east-1</groupName>\n                        </item>\n                    </groupSet>\n                    <stateReason>\n                        <code>Client.UserInitiatedShutdown</code>\n                        <message>Client.UserInitiatedShutdown: User initiated shutdown</message>\n                    </stateReason>\n                    <architecture>i386</architecture>\n                    <rootDeviceType>ebs</rootDeviceType>\n                    <rootDeviceName>/dev/sda1</rootDeviceName>\n                    <blockDeviceMapping/>\n                    <virtualizationType>paravirtual</virtualizationType>\n                    <clientToken/>\n                    <hypervisor>xen</hypervisor>\n                </item>\n            </instancesSet>\n        </item>\n        <item>\n            <reservationId>r-2df85542</reservationId>\n            <ownerId>993194456877</ownerId>\n            <groupSet>\n                <item>\n                    <groupId>sg-43eacf2a</groupId>\n                    <groupName>jclouds#ec2-s#us-east-1</groupName>\n                </item>\n            </groupSet>\n            <instancesSet>\n                <item>\n                    <instanceId>i-a5a811c4</instanceId>\n                    <imageId>ami-8e1fece7</imageId>\n                    <instanceState>\n                        <code>48</code>\n                        <name>terminated</name>\n                    </instanceState>\n                    <privateDnsName/>\n                    <dnsName/>\n                    <reason>User initiated (2011-07-29 08:06:59 GMT)</reason>\n                    <keyName>jclouds#ec2-s#us-east-1#40</keyName>\n                    <amiLaunchIndex>0</amiLaunchIndex>\n                    <productCodes/>\n                    <instanceType>t1.micro</instanceType>\n                    <launchTime>2011-07-29T08:06:55.000Z</launchTime>\n                    <placement>\n                        <availabilityZone>us-east-1b</availabilityZone>\n                        <groupName/>\n                        <tenancy>default</tenancy>\n                    </placement>\n                    <kernelId>aki-427d952b</kernelId>\n                    <monitoring>\n                        <state>disabled</state>\n                    </monitoring>\n                    <groupSet>\n                        <item>\n                            <groupId>sg-43eacf2a</groupId>\n                            <groupName>jclouds#ec2-s#us-east-1</groupName>\n                        </item>\n                    </groupSet>\n                    <stateReason>\n                        <code>Client.UserInitiatedShutdown</code>\n                        <message>Client.UserInitiatedShutdown: User initiated shutdown</message>\n                    </stateReason>\n                    <architecture>x86_64</architecture>\n                    <rootDeviceType>ebs</rootDeviceType>\n                    <rootDeviceName>/dev/sda1</rootDeviceName>\n                    <blockDeviceMapping/>\n                    <virtualizationType>paravirtual</virtualizationType>\n                    <clientToken/>\n                    <hypervisor>xen</hypervisor>\n                </item>\n            </instancesSet>\n        </item>\n        <item>\n            <reservationId>r-bffb56d0</reservationId>\n            <ownerId>993194456877</ownerId>\n            <groupSet>\n                <item>\n                    <groupId>sg-65eacf0c</groupId>\n                    <groupName>jclouds#adriancole-ec2unssh#us-east-1</groupName>\n                </item>\n            </groupSet>\n            <instancesSet>\n                <item>\n                    <instanceId>i-1faa137e</instanceId>\n                    <imageId>ami-8e1fece7</imageId>\n                    <instanceState>\n                        <code>48</code>\n                        <name>terminated</name>\n                    </instanceState>\n                    <privateDnsName/>\n                    <dnsName/>\n                    <reason>User initiated (2011-07-29 08:10:04 GMT)</reason>\n                    <keyName>jclouds#adriancole-ec2unssh</keyName>\n                    <amiLaunchIndex>0</amiLaunchIndex>\n                    <productCodes/>\n                    <instanceType>t1.micro</instanceType>\n                    <launchTime>2011-07-29T08:09:14.000Z</launchTime>\n                    <placement>\n                        <availabilityZone>us-east-1c</availabilityZone>\n                        <groupName/>\n                        <tenancy>default</tenancy>\n                    </placement>\n                    <kernelId>aki-427d952b</kernelId>\n                    <monitoring>\n                        <state>disabled</state>\n                    </monitoring>\n                    <groupSet>\n                        <item>\n                            <groupId>sg-65eacf0c</groupId>\n                            <groupName>jclouds#adriancole-ec2unssh#us-east-1</groupName>\n                        </item>\n                    </groupSet>\n                    <stateReason>\n                        <code>Client.UserInitiatedShutdown</code>\n                        <message>Client.UserInitiatedShutdown: User initiated shutdown</message>\n                    </stateReason>\n                    <architecture>x86_64</architecture>\n                    <rootDeviceType>ebs</rootDeviceType>\n                    <rootDeviceName>/dev/sda1</rootDeviceName>\n                    <blockDeviceMapping/>\n                    <instanceLifecycle>spot</instanceLifecycle>\n                    <spotInstanceRequestId>sir-cf9dd211</spotInstanceRequestId>\n                    <virtualizationType>paravirtual</virtualizationType>\n                    <clientToken/>\n                    <hypervisor>xen</hypervisor>\n                </item>\n            </instancesSet>\n            <requesterId>854251627541</requesterId>\n        </item>\n        <item>\n            <reservationId>r-c3cf62ac</reservationId>\n            <ownerId>993194456877</ownerId>\n            <groupSet>\n                <item>\n                    <groupId>sg-dbf5d0b2</groupId>\n                    <groupName>jclouds#ec2-o#us-east-1</groupName>\n                </item>\n                <item>\n                    <groupId>sg-d9f5d0b0</groupId>\n                    <groupName>ec2-o</groupName>\n                </item>\n            </groupSet>\n            <instancesSet>\n                <item>\n                    <instanceId>i-15982174</instanceId>\n                    <imageId>ami-8e1fece7</imageId>\n                    <instanceState>\n                        <code>48</code>\n                        <name>terminated</name>\n                    </instanceState>\n                    <privateDnsName/>\n                    <dnsName/>\n:\n                    <reason>User initiated (2011-07-29 08:27:01 GMT)</reason>\n                    <keyName>ec2-o</keyName>\n                    <amiLaunchIndex>0</amiLaunchIndex>\n                    <productCodes/>\n                    <instanceType>t1.micro</instanceType>\n                    <launchTime>2011-07-29T08:25:33.000Z</launchTime>\n                    <placement>\n                        <availabilityZone>us-east-1c</availabilityZone>\n                        <groupName/>\n                        <tenancy>default</tenancy>\n                    </placement>\n                    <kernelId>aki-427d952b</kernelId>\n                    <monitoring>\n                        <state>enabled</state>\n                    </monitoring>\n                    <groupSet>\n                        <item>\n                            <groupId>sg-dbf5d0b2</groupId>\n                            <groupName>jclouds#ec2-o#us-east-1</groupName>\n                        </item>\n                        <item>\n                            <groupId>sg-d9f5d0b0</groupId>\n                            <groupName>ec2-o</groupName>\n                        </item>\n                    </groupSet>\n                    <stateReason>\n                        <code>Client.UserInitiatedShutdown</code>\n                        <message>Client.UserInitiatedShutdown: User initiated shutdown</message>\n                    </stateReason>\n                    <architecture>x86_64</architecture>\n                    <rootDeviceType>ebs</rootDeviceType>\n                    <rootDeviceName>/dev/sda1</rootDeviceName>\n                    <blockDeviceMapping/>\n                    <instanceLifecycle>spot</instanceLifecycle>\n                    <spotInstanceRequestId>sir-6bba1e14</spotInstanceRequestId>\n                    <virtualizationType>paravirtual</virtualizationType>\n                    <clientToken/>\n                    <hypervisor>xen</hypervisor>\n                </item>\n            </instancesSet>\n            <requesterId>854251627541</requesterId>\n        </item>\n        <item>\n            <reservationId>r-b1c964de</reservationId>\n            <ownerId>993194456877</ownerId>\n            <groupSet>\n                <item>\n                    <groupId>sg-25f4d14c</groupId>\n                    <groupName>jclouds#ec2-r#us-east-1</groupName>\n                </item>\n            </groupSet>\n            <instancesSet>\n                <item>\n                    <instanceId>i-b19a23d0</instanceId>\n                    <imageId>ami-8e1fece7</imageId>\n                    <instanceState>\n                        <code>48</code>\n                        <name>terminated</name>\n                    </instanceState>\n                    <privateDnsName/>\n                    <dnsName/>\n                    <reason>User initiated (2011-07-29 08:28:17 GMT)</reason>\n                    <keyName>jclouds#ec2-r#us-east-1#63</keyName>\n                    <amiLaunchIndex>0</amiLaunchIndex>\n                    <productCodes/>\n                    <instanceType>t1.micro</instanceType>\n                    <launchTime>2011-07-29T08:28:06.000Z</launchTime>\n                    <placement>\n                        <availabilityZone>us-east-1c</availabilityZone>\n                        <groupName/>\n                        <tenancy>default</tenancy>\n                    </placement>\n                    <kernelId>aki-427d952b</kernelId>\n                    <monitoring>\n                        <state>disabled</state>\n                    </monitoring>\n                    <groupSet>\n                        <item>\n                            <groupId>sg-25f4d14c</groupId>\n                            <groupName>jclouds#ec2-r#us-east-1</groupName>\n                        </item>\n                    </groupSet>\n                    <stateReason>\n                        <code>Client.UserInitiatedShutdown</code>\n                        <message>Client.UserInitiatedShutdown: User initiated shutdown</message>\n                    </stateReason>\n                    <architecture>x86_64</architecture>\n                    <rootDeviceType>ebs</rootDeviceType>\n                    <rootDeviceName>/dev/sda1</rootDeviceName>\n                    <blockDeviceMapping/>\n                    <virtualizationType>paravirtual</virtualizationType>\n                    <clientToken/>\n                    <hypervisor>xen</hypervisor>\n                </item>\n            </instancesSet>\n        </item>\n        <item>\n            <reservationId>r-87c865e8</reservationId>\n            <ownerId>993194456877</ownerId>\n            <groupSet>\n                <item>\n                    <groupId>sg-1df4d174</groupId>\n                    <groupName>jclouds#ec2-#us-east-1</groupName>\n                </item>\n            </groupSet>\n            <instancesSet>\n                <item>\n                    <instanceId>i-679c2506</instanceId>\n                    <imageId>ami-8e1fece7</imageId>\n                    <instanceState>\n                        <code>16</code>\n                        <name>running</name>\n                    </instanceState>\n                    <privateDnsName>domU-12-31-39-09-F9-1C.compute-1.internal</privateDnsName>\n                    <dnsName>ec2-50-19-39-139.compute-1.amazonaws.com</dnsName>\n                    <reason/>\n                    <keyName>jclouds#ec2-#us-east-1#99</keyName>\n                    <amiLaunchIndex>0</amiLaunchIndex>\n                    <productCodes/>\n                    <instanceType>t1.micro</instanceType>\n                    <launchTime>2011-07-29T08:29:21.000Z</launchTime>\n                    <placement>\n                        <availabilityZone>us-east-1b</availabilityZone>\n                        <groupName/>\n                        <tenancy>default</tenancy>\n                    </placement>\n                    <kernelId>aki-427d952b</kernelId>\n                    <monitoring>\n                        <state>disabled</state>\n                    </monitoring>\n                    <privateIpAddress>10.210.254.234</privateIpAddress>\n                    <ipAddress>50.19.39.139</ipAddress>\n                    <groupSet>\n                        <item>\n                            <groupId>sg-1df4d174</groupId>\n                            <groupName>jclouds#ec2-#us-east-1</groupName>\n                        </item>\n                    </groupSet>\n                    <architecture>x86_64</architecture>\n                    <rootDeviceType>ebs</rootDeviceType>\n                    <rootDeviceName>/dev/sda1</rootDeviceName>\n                    <blockDeviceMapping>\n                        <item>\n                            <deviceName>/dev/sda1</deviceName>\n                            <ebs>\n                                <volumeId>vol-6d7b6306</volumeId>\n                                <status>attached</status>\n                                <attachTime>2011-07-29T08:29:39.000Z</attachTime>\n                                <deleteOnTermination>true</deleteOnTermination>\n                            </ebs>\n                        </item>\n                    </blockDeviceMapping>\n                    <virtualizationType>paravirtual</virtualizationType>\n                    <clientToken/>\n                    <hypervisor>xen</hypervisor>\n                </item>\n                <item>\n                    <instanceId>i-699c2508</instanceId>\n                    <imageId>ami-8e1fece7</imageId>\n                    <instanceState>\n                        <code>16</code>\n                        <name>running</name>\n                    </instanceState>\n                    <privateDnsName>domU-12-31-39-09-86-A9.compute-1.internal</privateDnsName>\n                    <dnsName>ec2-184-72-215-58.compute-1.amazonaws.com</dnsName>\n                    <reason/>\n                    <keyName>jclouds#ec2-#us-east-1#99</keyName>\n                    <amiLaunchIndex>1</amiLaunchIndex>\n                    <productCodes/>\n                    <instanceType>t1.micro</instanceType>\n                    <launchTime>2011-07-29T08:29:21.000Z</launchTime>\n                    <placement>\n                        <availabilityZone>us-east-1b</availabilityZone>\n                        <groupName/>\n                        <tenancy>default</tenancy>\n                    </placement>\n                    <kernelId>aki-427d952b</kernelId>\n                    <monitoring>\n                        <state>disabled</state>\n                    </monitoring>\n                    <privateIpAddress>10.210.137.83</privateIpAddress>\n                    <ipAddress>184.72.215.58</ipAddress>\n                    <groupSet>\n                        <item>\n                            <groupId>sg-1df4d174</groupId>\n                            <groupName>jclouds#ec2-#us-east-1</groupName>\n                        </item>\n                    </groupSet>\n                    <architecture>x86_64</architecture>\n                    <rootDeviceType>ebs</rootDeviceType>\n                    <rootDeviceName>/dev/sda1</rootDeviceName>\n                    <blockDeviceMapping>\n                        <item>\n                            <deviceName>/dev/sda1</deviceName>\n                            <ebs>\n                                <volumeId>vol-617b630a</volumeId>\n                                <status>attached</status>\n                                <attachTime>2011-07-29T08:29:42.000Z</attachTime>\n                                <deleteOnTermination>true</deleteOnTermination>\n                            </ebs>\n                        </item>\n                    </blockDeviceMapping>\n                    <virtualizationType>paravirtual</virtualizationType>\n                    <clientToken/>\n                    <hypervisor>xen</hypervisor>\n                </item>\n            </instancesSet>\n        </item>\n        <item>\n            <reservationId>r-61cb660e</reservationId>\n            <ownerId>993194456877</ownerId>\n            <groupSet>\n                <item>\n                    <groupId>sg-1ff4d176</groupId>\n                    <groupName>jclouds#ec2-block#us-east-1</groupName>\n                </item>\n            </groupSet>\n            <instancesSet>\n                <item>\n                    <instanceId>i-539c2532</instanceId>\n                    <imageId>ami-8e1fece7</imageId>\n                    <instanceState>\n                        <code>48</code>\n                        <name>terminated</name>\n                    </instanceState>\n                    <privateDnsName/>\n                    <dnsName/>\n                    <reason>User initiated (2011-07-29 08:29:36 GMT)</reason>\n                    <keyName>jclouds#ec2-block#us-east-1#48</keyName>\n                    <amiLaunchIndex>0</amiLaunchIndex>\n                    <productCodes/>\n                    <instanceType>t1.micro</instanceType>\n                    <launchTime>2011-07-29T08:29:32.000Z</launchTime>\n                    <placement>\n                        <availabilityZone>us-east-1b</availabilityZone>\n                        <groupName/>\n                        <tenancy>default</tenancy>\n                    </placement>\n                    <kernelId>aki-427d952b</kernelId>\n                    <monitoring>\n                        <state>disabled</state>\n                    </monitoring>\n                    <groupSet>\n                        <item>\n                            <groupId>sg-1ff4d176</groupId>\n                            <groupName>jclouds#ec2-block#us-east-1</groupName>\n                        </item>\n                    </groupSet>\n                    <stateReason>\n                        <code>Client.UserInitiatedShutdown</code>\n                        <message>Client.UserInitiatedShutdown: User initiated shutdown</message>\n                    </stateReason>\n                    <architecture>x86_64</architecture>\n                    <rootDeviceType>ebs</rootDeviceType>\n                    <rootDeviceName>/dev/sda1</rootDeviceName>\n                    <blockDeviceMapping/>\n                    <virtualizationType>paravirtual</virtualizationType>\n                    <clientToken/>\n                    <hypervisor>xen</hypervisor>\n                </item>\n            </instancesSet>\n        </item>\n        <item>\n            <reservationId>r-51cb663e</reservationId>\n            <ownerId>993194456877</ownerId>\n            <groupSet>\n                <item>\n                    <groupId>sg-15f4d17c</groupId>\n                    <groupName>jclouds#ec2-e#us-east-1</groupName>\n                </item>\n            </groupSet>\n            <instancesSet>\n                <item>\n                    <instanceId>i-059c2564</instanceId>\n                    <imageId>ami-eb71b682</imageId>\n                    <instanceState>\n                        <code>0</code>\n                        <name>pending</name>\n                    </instanceState>\n                    <dnsName>ec2-184-72-215-58.compute-1.amazonaws.com</dnsName>\n                    <reason/>\n                    <keyName>jclouds#ec2-#us-east-1#99</keyName>\n                    <amiLaunchIndex>1</amiLaunchIndex>\n                    <productCodes/>\n                    <instanceType>t1.micro</instanceType>\n                    <launchTime>2011-07-29T08:29:21.000Z</launchTime>\n                    <placement>\n                        <availabilityZone>us-east-1b</availabilityZone>\n                        <groupName/>\n                        <tenancy>default</tenancy>\n                    </placement>\n                    <kernelId>aki-427d952b</kernelId>\n                    <monitoring>\n                        <state>disabled</state>\n                    </monitoring>\n                    <privateIpAddress>10.210.137.83</privateIpAddress>\n                    <ipAddress>184.72.215.58</ipAddress>\n                    <groupSet>\n                        <item>\n                            <groupId>sg-1df4d174</groupId>\n                            <groupName>jclouds#ec2-#us-east-1</groupName>\n                        </item>\n                    </groupSet>\n                    <architecture>x86_64</architecture>\n                    <rootDeviceType>ebs</rootDeviceType>\n                    <rootDeviceName>/dev/sda1</rootDeviceName>\n                    <blockDeviceMapping>\n                        <item>\n                            <deviceName>/dev/sda1</deviceName>\n                            <ebs>\n                                <volumeId>vol-617b630a</volumeId>\n                                <status>attached</status>\n                                <attachTime>2011-07-29T08:29:42.000Z</attachTime>\n                                <deleteOnTermination>true</deleteOnTermination>\n                            </ebs>\n                        </item>\n                    </blockDeviceMapping>\n                    <virtualizationType>paravirtual</virtualizationType>\n                    <clientToken/>\n                    <hypervisor>xen</hypervisor>\n                </item>\n            </instancesSet>\n        </item>\n        <item>\n            <reservationId>r-61cb660e</reservationId>\n            <ownerId>993194456877</ownerId>\n            <groupSet>\n                <item>\n                    <groupId>sg-1ff4d176</groupId>\n                    <groupName>jclouds#ec2-block#us-east-1</groupName>\n                </item>\n            </groupSet>\n            <instancesSet>\n                <item>\n                    <instanceId>i-539c2532</instanceId>\n                    <imageId>ami-8e1fece7</imageId>\n                    <instanceState>\n                        <code>48</code>\n                        <name>terminated</name>\n                    </instanceState>\n                    <privateDnsName/>\n                    <dnsName/>\n                    <reason>User initiated (2011-07-29 08:29:36 GMT)</reason>\n                    <keyName>jclouds#ec2-block#us-east-1#48</keyName>\n                    <amiLaunchIndex>0</amiLaunchIndex>\n                    <productCodes/>\n                    <instanceType>t1.micro</instanceType>\n                    <launchTime>2011-07-29T08:29:32.000Z</launchTime>\n                    <placement>\n                        <availabilityZone>us-east-1b</availabilityZone>\n                        <groupName/>\n                        <tenancy>default</tenancy>\n                    </placement>\n                    <kernelId>aki-427d952b</kernelId>\n                    <monitoring>\n                        <state>disabled</state>\n                    </monitoring>\n                    <groupSet>\n                        <item>\n                            <groupId>sg-1ff4d176</groupId>\n                            <groupName>jclouds#ec2-block#us-east-1</groupName>\n                        </item>\n                    </groupSet>\n                    <stateReason>\n                        <code>Client.UserInitiatedShutdown</code>\n                        <message>Client.UserInitiatedShutdown: User initiated shutdown</message>\n                    </stateReason>\n                    <architecture>x86_64</architecture>\n                    <rootDeviceType>ebs</rootDeviceType>\n                    <rootDeviceName>/dev/sda1</rootDeviceName>\n                    <blockDeviceMapping/>\n                    <virtualizationType>paravirtual</virtualizationType>\n                    <clientToken/>\n                    <hypervisor>xen</hypervisor>\n                </item>\n            </instancesSet>\n        </item>\n        <item>\n            <reservationId>r-51cb663e</reservationId>\n            <ownerId>993194456877</ownerId>\n            <groupSet>\n                <item>\n                    <groupId>sg-15f4d17c</groupId>\n                    <groupName>jclouds#ec2-e#us-east-1</groupName>\n                </item>\n            </groupSet>\n            <instancesSet>\n                <item>\n                    <instanceId>i-059c2564</instanceId>\n                    <imageId>ami-eb71b682</imageId>\n                    <instanceState>\n                        <code>0</code>\n                        <name>pending</name>\n                    </instanceState>\n                    <privateDnsName/>\n                    <dnsName/>\n                    <reason/>\n                    <keyName>jclouds#ec2-e#us-east-1#85</keyName>\n                    <amiLaunchIndex>0</amiLaunchIndex>\n                    <productCodes/>\n                    <instanceType>m1.small</instanceType>\n                    <launchTime>2011-07-29T08:29:49.000Z</launchTime>\n                    <placement>\n                        <availabilityZone>us-east-1c</availabilityZone>\n                        <groupName/>\n                        <tenancy>default</tenancy>\n                    </placement>\n                    <kernelId>aki-407d9529</kernelId>\n                    <monitoring>\n                        <state>disabled</state>\n                    </monitoring>\n                    <groupSet>\n                        <item>\n                            <groupId>sg-15f4d17c</groupId>\n                            <groupName>jclouds#ec2-e#us-east-1</groupName>\n                        </item>\n                    </groupSet>\n                    <architecture>i386</architecture>\n                    <rootDeviceType>ebs</rootDeviceType>\n                    <rootDeviceName>/dev/sda1</rootDeviceName>\n                    <blockDeviceMapping/>\n                    <virtualizationType>paravirtual</virtualizationType>\n                    <clientToken/>\n                    <hypervisor>xen</hypervisor>\n                </item>\n            </instancesSet>\n        </item>\n    </reservationSet>\n</DescribeInstancesResponse>"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/describe_instances_3.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<DescribeInstancesResponse xmlns=\"http://ec2.amazonaws.com/doc/2012-06-01/\">\n    <requestId>440faed2-0331-488d-a04d-d8c9aba85307</requestId>\n    <reservationSet/>\n</DescribeInstancesResponse>\n"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/describe_instances_latest.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<DescribeInstancesResponse xmlns=\"http://ec2.amazonaws.com/doc/2012-06-01/\">\n    <requestId>a03c1896-0543-485f-a732-ebc83873a3ca</requestId>\n    <reservationSet>\n        <item>\n            <reservationId>r-0f4c2160</reservationId>\n            <ownerId>993194456877</ownerId>\n            <groupSet>\n                <item>\n                    <groupId>sg-ef052b86</groupId>\n                    <groupName>jclouds#zkclustertest#us-east-1</groupName>\n                </item>\n            </groupSet>\n            <instancesSet>\n                <item>\n                    <instanceId>i-911444f0</instanceId>\n                    <imageId>ami-63be790a</imageId>\n                    <instanceState>\n                        <code>16</code>\n                        <name>running</name>\n                    </instanceState>\n                    <privateDnsName>ip-10-212-81-7.ec2.internal</privateDnsName>\n                    <dnsName>ec2-174-129-173-155.compute-1.amazonaws.com</dnsName>\n                    <reason/>\n                    <keyName>jclouds#zkclustertest#us-east-1#23</keyName>\n                    <amiLaunchIndex>0</amiLaunchIndex>\n                    <productCodes/>\n                    <instanceType>t1.micro</instanceType>\n                    <launchTime>2011-08-16T13:40:50.000Z</launchTime>\n                    <placement>\n                        <availabilityZone>us-east-1c</availabilityZone>\n                        <groupName/>\n                        <tenancy>default</tenancy>\n                    </placement>\n                    <kernelId>aki-427d952b</kernelId>\n                    <monitoring>\n                        <state>disabled</state>\n                    </monitoring>\n                    <privateIpAddress>10.212.81.7</privateIpAddress>\n                    <ipAddress>174.129.173.155</ipAddress>\n                    <groupSet>\n                        <item>\n                            <groupId>sg-ef052b86</groupId>\n                            <groupName>jclouds#zkclustertest#us-east-1</groupName>\n                        </item>\n                    </groupSet>\n                    <architecture>x86_64</architecture>\n                    <rootDeviceType>ebs</rootDeviceType>\n                    <rootDeviceName>/dev/sda1</rootDeviceName>\n                    <blockDeviceMapping>\n                        <item>\n                            <deviceName>/dev/sda1</deviceName>\n                            <ebs>\n                                <volumeId>vol-5829fc32</volumeId>\n                                <status>attached</status>\n                                <attachTime>2011-08-16T13:41:19.000Z</attachTime>\n                                <deleteOnTermination>true</deleteOnTermination>\n                            </ebs>\n                        </item>\n                    </blockDeviceMapping>\n                    <virtualizationType>paravirtual</virtualizationType>\n                    <clientToken/>\n                    <hypervisor>xen</hypervisor>\n                    <tagSet>\n                       <item>\n                           <key>Name</key>\n                           <value>ec2-o</value>\n                       </item>\n                       <item>\n                           <key>Empty</key>\n                           <value />\n                       </item>\n                    </tagSet>            \n                </item>\n                <item>\n                    <instanceId>i-931444f2</instanceId>\n                    <imageId>ami-63be790a</imageId>\n                    <instanceState>\n                        <code>16</code>\n                        <name>running</name>\n                    </instanceState>\n                    <privateDnsName>ip-10-212-185-8.ec2.internal</privateDnsName>\n                    <dnsName>ec2-50-19-207-248.compute-1.amazonaws.com</dnsName>\n                    <reason/>\n                    <keyName>jclouds#zkclustertest#us-east-1#23</keyName>\n                    <amiLaunchIndex>1</amiLaunchIndex>\n                    <productCodes/>\n                    <instanceType>t1.micro</instanceType>\n                    <launchTime>2011-08-16T13:40:50.000Z</launchTime>\n                    <placement>\n                        <availabilityZone>us-east-1c</availabilityZone>\n                        <groupName/>\n                        <tenancy>default</tenancy>\n                    </placement>\n                    <kernelId>aki-427d952b</kernelId>\n                    <monitoring>\n                        <state>disabled</state>\n                    </monitoring>\n                    <privateIpAddress>10.212.185.8</privateIpAddress>\n                    <ipAddress>50.19.207.248</ipAddress>\n                    <groupSet>\n                        <item>\n                            <groupId>sg-ef052b86</groupId>\n                            <groupName>jclouds#zkclustertest#us-east-1</groupName>\n                        </item>\n                    </groupSet>\n                    <architecture>x86_64</architecture>\n                    <rootDeviceType>ebs</rootDeviceType>\n                    <rootDeviceName>/dev/sda1</rootDeviceName>\n                    <blockDeviceMapping>\n                        <item>\n                            <deviceName>/dev/sda1</deviceName>\n                            <ebs>\n                                <volumeId>vol-5029fc3a</volumeId>\n                                <status>attached</status>\n                                <attachTime>2011-08-16T13:41:19.000Z</attachTime>\n                                <deleteOnTermination>true</deleteOnTermination>\n                            </ebs>\n                        </item>\n                    </blockDeviceMapping>\n                    <virtualizationType>paravirtual</virtualizationType>\n                    <clientToken/>\n                    <hypervisor>xen</hypervisor>\n                    <iamInstanceProfile>\n                        <arn>arn:aws:iam::123456789012:instance-profile/application_abc/component_xyz/Webserver</arn>\n                        <id>AIPAD5ARO2C5EXAMPLE3G</id>\n                    </iamInstanceProfile>\n                </item>\n            </instancesSet>\n        </item>\n    </reservationSet>\n</DescribeInstancesResponse>"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/describe_instances_pending.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<DescribeInstancesResponse xmlns=\"http://ec2.amazonaws.com/doc/2012-06-01/\">\n    <requestId>dcd37ecf-e5b6-462b-99a8-112427b3e3a2</requestId>\n    <reservationSet>\n        <item>\n            <reservationId>r-3f056a58</reservationId>\n            <ownerId>095072994936</ownerId>\n            <groupSet>\n                <item>\n                    <groupId>sg-f788299f</groupId>\n                    <groupName>launchpad_sec_group</groupName>\n                </item>\n                <item>\n                    <groupId>sg-7e512116</groupId>\n                    <groupName>jclouds#4c858090-f66c-4225-aa57-6fcaa42198ae</groupName>\n                </item>\n            </groupSet>\n            <instancesSet>\n                <item>\n                    <instanceId>i-32451248</instanceId>\n                    <imageId>ami-bf8131d6</imageId>\n                    <instanceState>\n                        <code>0</code>\n                        <name>pending</name>\n                    </instanceState>\n                    <privateDnsName>ip-10-194-149-220.ec2.internal</privateDnsName>\n                    <dnsName>ec2-23-20-17-42.compute-1.amazonaws.com</dnsName>\n                    <reason/>\n                    <keyName>jclouds#4c858090-f66c-4225-aa57-6fcaa42198ae#105</keyName>\n                    <amiLaunchIndex>0</amiLaunchIndex>\n                    <productCodes/>\n                    <instanceType>c1.medium</instanceType>\n                    <launchTime>2012-09-14T20:01:34.000Z</launchTime>\n                    <placement>\n                        <availabilityZone>us-east-1d</availabilityZone>\n                        <groupName/>\n                        <tenancy>default</tenancy>\n                    </placement>\n                    <kernelId>aki-825ea7eb</kernelId>\n                    <monitoring>\n                        <state>disabled</state>\n                    </monitoring>\n                    <privateIpAddress>10.194.149.220</privateIpAddress>\n                    <ipAddress>23.20.17.42</ipAddress>\n                    <groupSet>\n                        <item>\n                            <groupId>sg-f788299f</groupId>\n                            <groupName>launchpad_sec_group</groupName>\n                        </item>\n                        <item>\n                            <groupId>sg-7e512116</groupId>\n                            <groupName>jclouds#4c858090-f66c-4225-aa57-6fcaa42198ae</groupName>\n                        </item>\n                    </groupSet>\n                    <architecture>x86_64</architecture>\n                    <rootDeviceType>ebs</rootDeviceType>\n                    <rootDeviceName>/dev/sda1</rootDeviceName>\n                    <blockDeviceMapping>\n                        <item>\n                            <deviceName>/dev/sda1</deviceName>\n                            <ebs>\n                                <volumeId>vol-b2beb3c9</volumeId>\n                                <status>attaching</status>\n                                <attachTime>2012-09-14T20:01:37.000Z</attachTime>\n                                <deleteOnTermination>true</deleteOnTermination>\n                            </ebs>\n                        </item>\n                    </blockDeviceMapping>\n                    <virtualizationType>paravirtual</virtualizationType>\n                    <clientToken/>\n                    <tagSet>\n                        <item>\n                            <key>Name</key>\n                            <value>4c858090-f66c-4225-aa57-6fcaa42198ae-32451248</value>\n                        </item>\n                    </tagSet>\n                    <hypervisor>xen</hypervisor>\n                </item>\n            </instancesSet>\n        </item>\n    </reservationSet>\n</DescribeInstancesResponse>"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/describe_internet_gateways.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<DescribeInternetGatewaysResponse xmlns=\"http://ec2.amazonaws.com/doc/2012-06-01/\">\n    <requestId>3ed08c74-7a82-48b1-96d6-58ec1a41e560</requestId>\n    <internetGatewaySet>\n        <item>\n            <internetGatewayId>igw-fada7c9c</internetGatewayId>\n            <attachmentSet/>\n            <tagSet>\n                <item>\n                    <key>Name</key>\n                    <value>describe_internet_gateways_test</value>\n                </item>\n            </tagSet>\n        </item>\n        <item>\n            <internetGatewayId>igw-6bca130c</internetGatewayId>\n            <attachmentSet>\n                <item>\n                    <vpcId>vpc-a13d29c6</vpcId>\n                    <state>available</state>\n                </item>\n            </attachmentSet>\n            <tagSet/>\n        </item>\n        <item>\n            <internetGatewayId>igw-d09a79b6</internetGatewayId>\n            <attachmentSet>\n                <item>\n                    <vpcId>vpc-17587171</vpcId>\n                    <state>available</state>\n                </item>\n            </attachmentSet>\n            <tagSet/>\n        </item>\n    </internetGatewaySet>\n</DescribeInternetGatewaysResponse>\n\n"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/describe_placement_groups.xml",
    "content": "<DescribePlacementGroupsResponse xmlns=\"http://ec2.amazonaws.com/doc/2010-06-15/\">\n   <requestID>d4904fd9-82c2-4ea5-adfe-a9cc3EXAMPLE</requestID>\n   <placementGroupSet>\n      <item>\n         <groupName>XYZ-cluster</groupName>\n         <strategy>cluster</strategy>\n         <state>available</state>\n      </item>\n   </placementGroupSet>\n</DescribePlacementGroupsResponse>"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/describe_placement_groups_empty.xml",
    "content": "<DescribePlacementGroupsResponse xmlns=\"http://ec2.amazonaws.com/doc/2010-06-15/\">\n   <requestID>d4904fd9-82c2-4ea5-adfe-a9cc3EXAMPLE</requestID>\n   <placementGroupSet>\n   </placementGroupSet>\n</DescribePlacementGroupsResponse>"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/describe_reserved_instances_offerings.xml",
    "content": "<DescribeReservedInstancesOfferingsResponse\n\txmlns=\"http://ec2.amazonaws.com/doc/2009-04-04/\">\n\t<reservedInstancesOfferingsSet>\n\t\t<item>\n\t\t\t<reservedInstancesOfferingId>4b2293b4-5813-4cc8-9ce3-1957fc1dcfc8\n\t\t\t</reservedInstancesOfferingId>\n\t\t\t<instanceType>m1.small</instanceType>\n\t\t\t<availabilityZone>us-east-1a</availabilityZone>\n\t\t\t<duration>12</duration>\n\t\t\t<fixedPrice>0.00</fixedPrice>\n\t\t\t<usagePrice>0.00</usagePrice>\n\t\t\t<productDescription>m1.small offering in us-east-1a</productDescription>\n\t\t</item>\n\t</reservedInstancesOfferingsSet>\n</DescribeReservedInstancesOfferingsResponse>"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/describe_route_tables.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<DescribeRouteTablesResponse xmlns=\"http://ec2.amazonaws.com/doc/2012-06-01/\">\n    <requestId>0fe3e6ca-5b09-4722-9d81-1f341376c830</requestId>\n    <routeTableSet>\n        <item>\n            <routeTableId>rtb-80a3fae4</routeTableId>\n            <vpcId>vpc-6dcb5609</vpcId>\n            <routeSet>\n                <item>\n                    <destinationCidrBlock>172.31.0.0/16</destinationCidrBlock>\n                    <gatewayId>local</gatewayId>\n                    <state>active</state>\n                </item>\n                <item>\n                    <destinationCidrBlock>0.0.0.0/0</destinationCidrBlock>\n                    <gatewayId>igw-dcdcc7b9</gatewayId>\n                    <state>active</state>\n                </item>\n            </routeSet>\n            <associationSet>\n                <item>\n                    <routeTableAssociationId>rtbassoc-f173c296</routeTableAssociationId>\n                    <routeTableId>rtb-80a3fae4</routeTableId>\n                    <main>true</main>\n                </item>\n            </associationSet>\n            <tagSet/>\n        </item>\n        <item>\n            <routeTableId>rtb-d4605bb0</routeTableId>\n            <vpcId>vpc-924731f6</vpcId>\n            <routeSet>\n                <item>\n                    <destinationCidrBlock>10.0.0.0/16</destinationCidrBlock>\n                    <gatewayId>local</gatewayId>\n                    <state>active</state>\n                </item>\n                <item>\n                    <destinationCidrBlock>0.0.0.0/0</destinationCidrBlock>\n                    <gatewayId>igw-5af2023e</gatewayId>\n                    <state>active</state>\n                </item>\n            </routeSet>\n            <associationSet>\n                <item>\n                    <routeTableAssociationId>rtbassoc-a08aefc7</routeTableAssociationId>\n                    <routeTableId>rtb-d4605bb0</routeTableId>\n                    <main>true</main>\n                </item>\n            </associationSet>\n            <tagSet/>\n        </item>\n        <item>\n            <routeTableId>rtb-e6c98381</routeTableId>\n            <vpcId>vpc-6fa76308</vpcId>\n            <routeSet>\n                <item>\n                    <destinationCidrBlock>10.20.30.0/24</destinationCidrBlock>\n                    <gatewayId>local</gatewayId>\n                    <state>active</state>\n                </item>\n            </routeSet>\n            <associationSet>\n                <item>\n                    <routeTableAssociationId>rtbassoc-2d2dbe4b</routeTableAssociationId>\n                    <routeTableId>rtb-e6c98381</routeTableId>\n                    <main>true</main>\n                </item>\n            </associationSet>\n            <tagSet/>\n        </item>\n    </routeTableSet>\n</DescribeRouteTablesResponse>\n\n"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/describe_route_tables_invalid.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<DescribeRouteTablesResponse xmlns=\"http://ec2.amazonaws.com/doc/2012-06-01/\">\n    <requestId>0fe3e6ca-5b09-4722-9d81-1f341376c830</requestId>\n    <routeTableSet>\n        <item>\n            <routeTableId>rtb-80a3fae4</routeTableId>\n            <vpcId>vpc-6dcb5609</vpcId>\n            <routeSet>\n                <item>\n                    <destinationCidrBlock>172.31.0.0/16</destinationCidrBlock>\n                    <gatewayId>local</gatewayId>\n                    <state>bogus</state>\n                </item>\n            </routeSet>\n            <associationSet/>\n            <tagSet/>\n        </item>\n    </routeTableSet>\n</DescribeRouteTablesResponse>\n\n"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/describe_security_groups_vpc.xml",
    "content": "<DescribeSecurityGroupsResponse xmlns=\"http://ec2.amazonaws.com/doc/2012-06-01/\">\n        <requestId>xxxxxxxxxxxxxxxx</requestId>\n        <securityGroupInfo>\n            <item>\n                <ownerId>123123123123</ownerId>\n                <groupId>sg-11111111</groupId>\n                <groupName>default</groupName>\n                <groupDescription>default VPC security group</groupDescription>\n                <vpcId>vpc-99999999</vpcId>\n                <ipPermissions>\n                    <item>\n                        <ipProtocol>-1</ipProtocol>\n                        <groups>\n                            <item>\n                                <userId>123123123123</userId>\n                                <groupId>sg-11111111</groupId>\n                            </item>\n                        </groups>\n                        <ipRanges/>\n                    </item>\n                </ipPermissions>\n                <ipPermissionsEgress>\n                    <item>\n                        <ipProtocol>-1</ipProtocol>\n                        <groups/>\n                        <ipRanges>\n                            <item>\n                                <cidrIp>0.0.0.0/0</cidrIp>\n                            </item>\n                        </ipRanges>\n                    </item>\n                </ipPermissionsEgress>\n            </item>\n    </securityGroupInfo>\n</DescribeSecurityGroupsResponse>"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/describe_spot_instance.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<DescribeSpotInstanceRequestsResponse xmlns=\"http://ec2.amazonaws.com/doc/2012-06-01/\">\n    <requestId>d9da716a-5cd4-492e-83b9-6777ac16d6cf</requestId>\n    <spotInstanceRequestSet>\n        <item>\n            <spotInstanceRequestId>sir-1ede0012</spotInstanceRequestId>\n            <spotPrice>0.300000</spotPrice>\n            <type>one-time</type>\n            <state>active</state>\n            <launchSpecification>\n                <imageId>ami-8e1fece7</imageId>\n                <keyName>jclouds#adriancole-ec2unssh</keyName>\n                <groupSet>\n                    <item>\n                        <groupId>sg-83e1c4eb</groupId>\n                        <groupName>jclouds#adriancole-ec2unssh#us-east-1</groupName>\n                    </item>\n                </groupSet>\n                <instanceType>t1.micro</instanceType>\n                <blockDeviceMapping/>\n                <monitoring>\n                    <enabled>false</enabled>\n                </monitoring>\n            </launchSpecification>\n            <instanceId>i-ef308e8e</instanceId>\n            <status>\n                <code>fulfilled</code>\n                <message>Fulfilled</message>\n                <updateTime>2011-07-29T05:27:39.000Z</updateTime>\n            </status>\n            <createTime>2011-07-29T05:27:39.000Z</createTime>\n            <validFrom>2011-07-29T05:27:39.000Z</validFrom>\n            <validUntil>2011-07-29T05:27:39.000Z</validUntil>\n            <productDescription>Linux/UNIX</productDescription>\n            <tagSet>\n                <item>\n                    <key>Name</key>\n                    <value>ec2-o</value>\n                </item>\n                <item>\n                    <key>Spot</key>\n                    <value>spot-value</value>\n                </item>\n                <item>\n                    <key>Empty</key>\n                    <value />\n                </item>\n            </tagSet>            \n            <launchedAvailabilityZone>us-east-1b</launchedAvailabilityZone>\n        </item>\n    </spotInstanceRequestSet>\n</DescribeSpotInstanceRequestsResponse>"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/describe_spot_instance_requests.xml",
    "content": "<DescribeSpotInstanceRequestsResponse xmlns=\"http://ec2.amazonaws.com/doc/2012-06-01/\">\n    <requestId>7c4dd2bd-106d-4cd3-987c-35ee819180a6</requestId>\n    <spotInstanceRequestSet>\n        <item>\n            <spotInstanceRequestId>sir-067a4805</spotInstanceRequestId>\n            <spotPrice>0.040000</spotPrice>\n            <type>one-time</type>\n            <state>cancelled</state>\n            <launchSpecification>\n                <imageId>ami-595a0a1c</imageId>\n                <groupSet>\n                    <item>\n                        <groupId>sg-83e1c4ea</groupId>\n                        <groupName>default</groupName>\n                    </item>\n                </groupSet>\n                <instanceType>t1.micro</instanceType>\n                <blockDeviceMapping/>\n                <monitoring>\n                    <enabled>false</enabled>\n                </monitoring>\n            </launchSpecification>\n            <createTime>2011-03-07T20:13:07.000Z</createTime>\n            <productDescription>Linux/UNIX</productDescription>\n        </item>\n        <item>\n            <spotInstanceRequestId>sir-aa67d410</spotInstanceRequestId>\n            <spotPrice>0.040000</spotPrice>\n            <type>one-time</type>\n            <state>cancelled</state>\n            <launchSpecification>\n                <imageId>ami-595a0a1c</imageId>\n                <groupSet>\n                    <item>\n                        <groupId>sg-83e1c4ea</groupId>\n                        <groupName>default</groupName>\n                    </item>\n                </groupSet>\n                <instanceType>t1.micro</instanceType>\n                <blockDeviceMapping/>\n                <monitoring>\n                    <enabled>false</enabled>\n                </monitoring>\n            </launchSpecification>\n            <createTime>2011-03-07T20:13:57.000Z</createTime>\n            <productDescription>Linux/UNIX</productDescription>\n        </item>\n        <item>\n            <spotInstanceRequestId>sir-32e32810</spotInstanceRequestId>\n            <spotPrice>0.010000</spotPrice>\n            <type>one-time</type>\n            <state>cancelled</state>\n            <launchSpecification>\n                <imageId>ami-595a0a1c</imageId>\n                <groupSet>\n                    <item>\n                        <groupId>sg-83e1c4ea</groupId>\n                        <groupName>default</groupName>\n                    </item>\n                </groupSet>\n                <instanceType>t1.micro</instanceType>\n                <blockDeviceMapping/>\n                <monitoring>\n                    <enabled>false</enabled>\n                </monitoring>\n            </launchSpecification>\n            <createTime>2011-03-07T20:15:52.000Z</createTime>\n            <productDescription>Linux/UNIX</productDescription>\n        </item>\n        <item>\n            <spotInstanceRequestId>sir-46a36210</spotInstanceRequestId>\n            <spotPrice>0.010000</spotPrice>\n            <type>one-time</type>\n            <state>cancelled</state>\n            <validUntil>2011-03-07T20:20:00.000Z</validUntil>\n            <launchGroup>foo</launchGroup>\n            <availabilityZoneGroup>azfoo</availabilityZoneGroup>\n            <launchSpecification>\n                <imageId>ami-595a0a1c</imageId>\n                <keyName>default</keyName>\n                <groupSet>\n                    <item>\n                        <groupId>sg-83e1c4eb</groupId>\n                        <groupName>quick-start-1</groupName>\n                    </item>\n                </groupSet>\n                <instanceType>t1.micro</instanceType>\n                <blockDeviceMapping/>\n                <monitoring>\n                    <enabled>true</enabled>\n                </monitoring>\n            </launchSpecification>\n            <createTime>2011-03-07T20:18:25.000Z</createTime>\n            <productDescription>Linux/UNIX</productDescription>\n        </item>\n        <item>\n            <spotInstanceRequestId>sir-91780010</spotInstanceRequestId>\n            <spotPrice>0.010000</spotPrice>\n            <type>one-time</type>\n            <state>cancelled</state>\n            <validUntil>2011-03-07T20:20:00.000Z</validUntil>\n            <launchGroup>foo</launchGroup>\n            <availabilityZoneGroup>azfoo</availabilityZoneGroup>\n            <launchSpecification>\n                <imageId>ami-595a0a1c</imageId>\n                <keyName>default</keyName>\n                <groupSet>\n                    <item>\n                        <groupId>sg-83e1c4eb</groupId>\n                        <groupName>quick-start-1</groupName>\n                    </item>                </groupSet>\n                <instanceType>t1.micro</instanceType>\n                <blockDeviceMapping/>\n                <monitoring>\n                    <enabled>true</enabled>\n                </monitoring>\n            </launchSpecification>\n            <createTime>2011-03-07T20:18:25.000Z</createTime>\n            <productDescription>Linux/UNIX</productDescription>\n        </item>\n        <item>\n            <spotInstanceRequestId>sir-6f1fa605</spotInstanceRequestId>\n            <spotPrice>0.001000</spotPrice>\n            <type>one-time</type>\n            <state>cancelled</state>\n            <launchSpecification>\n                <imageId>ami-595a0a1c</imageId>\n                <groupSet>\n                    <item>\n                        <groupId>sg-83e1c4ea</groupId>\n                        <groupName>default</groupName>\n                    </item>\n                </groupSet>\n                <instanceType>t1.micro</instanceType>\n                <blockDeviceMapping/>\n                <monitoring>\n                    <enabled>false</enabled>\n                </monitoring>\n            </launchSpecification>\n            <createTime>2011-03-07T20:19:27.000Z</createTime>\n            <productDescription>Linux/UNIX</productDescription>\n        </item>\n        <item>\n            <spotInstanceRequestId>sir-a33eee10</spotInstanceRequestId>\n            <spotPrice>0.001000</spotPrice>\n            <type>one-time</type>\n            <state>cancelled</state>\n            <launchSpecification>\n                <imageId>ami-595a0a1c</imageId>\n                <groupSet>\n                    <item>\n                        <groupId>sg-83e1c4ea</groupId>\n                        <groupName>default</groupName>\n                    </item>\n                </groupSet>\n                <instanceType>t1.micro</instanceType>\n                <blockDeviceMapping/>\n                <monitoring>\n                    <enabled>false</enabled>\n                </monitoring>\n            </launchSpecification>\n            <createTime>2011-03-07T20:21:16.000Z</createTime>\n            <productDescription>Linux/UNIX</productDescription>\n        </item>\n        <item>\n            <spotInstanceRequestId>sir-aa690410</spotInstanceRequestId>\n            <spotPrice>0.001000</spotPrice>\n            <type>one-time</type>\n            <state>cancelled</state>\n            <launchSpecification>\n                <imageId>ami-595a0a1c</imageId>\n                <groupSet>\n                    <item>\n                        <groupId>sg-83e1c4ea</groupId>\n                        <groupName>default</groupName>\n                    </item>\n                </groupSet>\n                <instanceType>t1.micro</instanceType>\n                <blockDeviceMapping/>\n                <monitoring>\n                    <enabled>false</enabled>\n                </monitoring>\n            </launchSpecification>\n            <createTime>2011-03-07T20:21:52.000Z</createTime>\n            <productDescription>Linux/UNIX</productDescription>\n        </item>\n        <item>\n            <spotInstanceRequestId>sir-99ba4e06</spotInstanceRequestId>\n            <spotPrice>0.010000</spotPrice>\n            <type>one-time</type>\n            <state>cancelled</state>\n            <validUntil>2011-03-07T20:26:00.000Z</validUntil>\n            <launchGroup>doo</launchGroup>\n            <availabilityZoneGroup>dooo</availabilityZoneGroup>\n            <launchSpecification>\n                <imageId>ami-595a0a1c</imageId>\n                <keyName>default</keyName>\n                <groupSet>\n                    <item>\n                        <groupId>sg-83e1c4eb</groupId>\n                        <groupName>quick-start-1</groupName>\n                    </item>                </groupSet>\n                <instanceType>t1.micro</instanceType>\n                <blockDeviceMapping/>\n                <monitoring>\n                    <enabled>true</enabled>\n                </monitoring>\n            </launchSpecification>\n            <createTime>2011-03-07T20:24:30.000Z</createTime>\n            <productDescription>Linux/UNIX</productDescription>\n        </item>\n        <item>\n            <spotInstanceRequestId>sir-a617c406</spotInstanceRequestId>\n            <spotPrice>0.010000</spotPrice>\n            <type>one-time</type>\n            <state>cancelled</state>\n            <validUntil>2011-03-07T20:26:00.000Z</validUntil>\n            <launchGroup>doo</launchGroup>\n            <availabilityZoneGroup>dooo</availabilityZoneGroup>\n            <launchSpecification>\n                <imageId>ami-595a0a1c</imageId>\n                <keyName>default</keyName>\n                <groupSet>\n                    <item>\n                        <groupId>sg-83e1c4eb</groupId>\n                        <groupName>quick-start-1</groupName>\n                    </item>                </groupSet>\n                <instanceType>t1.micro</instanceType>\n                <blockDeviceMapping/>\n                <monitoring>\n                    <enabled>true</enabled>\n                </monitoring>\n            </launchSpecification>\n            <createTime>2011-03-07T20:24:30.000Z</createTime>\n            <productDescription>Linux/UNIX</productDescription>\n        </item>\n        <item>\n            <spotInstanceRequestId>sir-2147a405</spotInstanceRequestId>\n            <spotPrice>0.001000</spotPrice>\n            <type>one-time</type>\n            <state>cancelled</state>\n            <launchSpecification>\n                <imageId>ami-595a0a1c</imageId>\n                <groupSet>\n                    <item>\n                        <groupId>sg-83e1c4ea</groupId>\n                        <groupName>default</groupName>\n                    </item>\n                </groupSet>\n                <instanceType>t1.micro</instanceType>\n                <blockDeviceMapping/>\n                <monitoring>\n                    <enabled>false</enabled>\n                </monitoring>\n            </launchSpecification>\n            <createTime>2011-03-07T20:25:19.000Z</createTime>\n            <productDescription>Linux/UNIX</productDescription>\n        </item>\n        <item>\n            <spotInstanceRequestId>sir-c441c805</spotInstanceRequestId>\n            <spotPrice>0.001000</spotPrice>\n            <type>one-time</type>\n            <state>cancelled</state>\n            <launchSpecification>\n                <imageId>ami-595a0a1c</imageId>\n                <groupSet>\n                    <item>\n                        <groupId>sg-83e1c4ea</groupId>\n                        <groupName>default</groupName>\n                    </item>\n                </groupSet>\n                <instanceType>t1.micro</instanceType>\n                <blockDeviceMapping/>\n                <monitoring>\n                    <enabled>false</enabled>\n                </monitoring>\n            </launchSpecification>\n            <createTime>2011-03-07T20:29:09.000Z</createTime>\n            <productDescription>Linux/UNIX</productDescription>\n        </item>\n        <item>\n            <spotInstanceRequestId>sir-4658fe10</spotInstanceRequestId>\n            <spotPrice>0.010000</spotPrice>\n            <type>one-time</type>\n            <state>cancelled</state>\n            <validUntil>2011-03-07T21:10:00.000Z</validUntil>\n            <launchGroup>check3</launchGroup>\n            <availabilityZoneGroup>check3</availabilityZoneGroup>\n            <launchSpecification>\n                <imageId>ami-595a0a1c</imageId>\n                <keyName>default</keyName>\n                <groupSet>\n                    <item>\n                        <groupId>sg-83e1c4eb</groupId>\n                        <groupName>quick-start-1</groupName>\n                    </item>                </groupSet>\n                <instanceType>t1.micro</instanceType>\n                <blockDeviceMapping/>\n                <monitoring>\n                    <enabled>false</enabled>\n                </monitoring>\n            </launchSpecification>\n            <createTime>2011-03-07T20:31:34.000Z</createTime>\n            <productDescription>Linux/UNIX</productDescription>\n        </item>\n        <item>\n            <spotInstanceRequestId>sir-49a3ce10</spotInstanceRequestId>\n            <spotPrice>0.010000</spotPrice>\n            <type>one-time</type>\n            <state>cancelled</state>\n            <validUntil>2011-03-07T21:10:00.000Z</validUntil>\n            <launchGroup>check3</launchGroup>\n            <availabilityZoneGroup>check3</availabilityZoneGroup>\n            <launchSpecification>\n                <imageId>ami-595a0a1c</imageId>\n                <keyName>default</keyName>\n                <groupSet>\n                    <item>\n                        <groupId>sg-83e1c4eb</groupId>\n                        <groupName>quick-start-1</groupName>\n                    </item>                </groupSet>\n                <instanceType>t1.micro</instanceType>\n                <blockDeviceMapping/>\n                <monitoring>\n                    <enabled>false</enabled>\n                </monitoring>\n            </launchSpecification>\n            <createTime>2011-03-07T20:31:34.000Z</createTime>\n            <productDescription>Linux/UNIX</productDescription>\n        </item>\n        <item>\n            <spotInstanceRequestId>sir-91b30610</spotInstanceRequestId>\n            <spotPrice>0.010000</spotPrice>\n            <type>one-time</type>\n            <state>cancelled</state>\n            <validUntil>2011-03-07T21:10:00.000Z</validUntil>\n            <launchGroup>check3</launchGroup>\n            <availabilityZoneGroup>check3</availabilityZoneGroup>\n            <launchSpecification>\n                <imageId>ami-595a0a1c</imageId>\n                <keyName>default</keyName>\n                <groupSet>\n                    <item>\n                        <groupId>sg-83e1c4eb</groupId>\n                        <groupName>quick-start-1</groupName>\n                    </item>\n                                    </groupSet>\n                <instanceType>t1.micro</instanceType>\n                <blockDeviceMapping/>\n                <monitoring>\n                    <enabled>false</enabled>\n                </monitoring>\n            </launchSpecification>\n            <createTime>2011-03-07T20:31:34.000Z</createTime>\n            <productDescription>Linux/UNIX</productDescription>\n        </item>\n        <item>\n            <spotInstanceRequestId>sir-d8561606</spotInstanceRequestId>\n            <spotPrice>0.001000</spotPrice>\n            <type>one-time</type>\n            <state>cancelled</state>\n            <launchSpecification>\n                <imageId>ami-595a0a1c</imageId>\n                <groupSet>\n                    <item>\n                        <groupId>sg-83e1c4ea</groupId>\n                        <groupName>default</groupName>\n                    </item>\n                </groupSet>\n                <instanceType>t1.micro</instanceType>\n                <blockDeviceMapping/>\n                <monitoring>\n                    <enabled>false</enabled>\n                </monitoring>\n            </launchSpecification>\n            <createTime>2011-03-07T20:34:10.000Z</createTime>\n            <productDescription>Linux/UNIX</productDescription>\n        </item>\n        <item>\n            <spotInstanceRequestId>sir-4cdaa406</spotInstanceRequestId>\n            <spotPrice>0.001000</spotPrice>\n            <type>persistent</type>\n            <state>cancelled</state>\n            <validUntil>2011-03-07T22:25:00.000Z</validUntil>\n            <launchSpecification>\n                <imageId>ami-595a0a1c</imageId>\n                <keyName>default</keyName>\n                <groupSet>\n                    <item>\n                        <groupId>sg-83e1c4eb</groupId>\n                        <groupName>quick-start-1</groupName>\n                    </item>                </groupSet>\n                <instanceType>t1.micro</instanceType>\n                <blockDeviceMapping/>\n                <monitoring>\n                    <enabled>false</enabled>\n                </monitoring>\n            </launchSpecification>\n            <createTime>2011-03-07T22:23:19.000Z</createTime>\n            <productDescription>Linux/UNIX</productDescription>\n        </item>\n        <item>\n            <spotInstanceRequestId>sir-e19f2206</spotInstanceRequestId>\n            <spotPrice>0.001000</spotPrice>\n            <type>one-time</type>\n            <state>open</state>\n            <launchSpecification>\n                <imageId>ami-595a0a1c</imageId>\n                <groupSet>\n                    <item>\n                        <groupId>sg-83e1c4ea</groupId>\n                        <groupName>default</groupName>\n                    </item>\n                </groupSet>\n                <instanceType>t1.micro</instanceType>\n                <blockDeviceMapping/>\n                <monitoring>\n                    <enabled>false</enabled>\n                </monitoring>\n            </launchSpecification>\n            <createTime>2011-03-07T22:32:50.000Z</createTime>\n            <productDescription>Linux/UNIX</productDescription>\n        </item>\n    </spotInstanceRequestSet>\n</DescribeSpotInstanceRequestsResponse>"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/describe_spot_instance_tags.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<DescribeSpotInstanceRequestsResponse xmlns=\"http://ec2.amazonaws.com/doc/2012-06-01/\">\n    <requestId>f2247378-7df0-4725-b55f-8ef58b557dcd</requestId>\n    <spotInstanceRequestSet>\n        <item>\n            <spotInstanceRequestId>sir-f4d44212</spotInstanceRequestId>\n            <spotPrice>0.300000</spotPrice>\n            <type>one-time</type>\n            <state>cancelled</state>\n            <launchSpecification>\n                <imageId>ami-8e1fece7</imageId>\n                <keyName>ec2-o</keyName>\n                <groupSet>\n                    <item>\n                        <groupName>jclouds#ec2-o#us-east-1</groupName>\n                    </item>\n                    <item>\n                        <groupName>ec2-o</groupName>\n                    </item>\n                </groupSet>\n                <instanceType>t1.micro</instanceType>\n                <blockDeviceMapping/>\n                <monitoring>\n                    <enabled>true</enabled>\n                </monitoring>\n            </launchSpecification>\n            <createTime>2011-07-29T04:01:12.000Z</createTime>\n            <productDescription>Linux/UNIX</productDescription>\n            <tagSet>\n                <item>\n                    <key>One</key>\n                    <value>one</value>\n                </item>\n                <item>\n                    <key>Two</key>\n                    <value>one</value>\n                </item>\n            </tagSet>            \n            <launchedAvailabilityZone>us-east-1b</launchedAvailabilityZone>\n        </item>\n        <item>\n            <spotInstanceRequestId>sir-43408412</spotInstanceRequestId>\n            <spotPrice>0.300000</spotPrice>\n            <type>one-time</type>\n            <state>cancelled</state>\n            <launchSpecification>\n                <imageId>ami-8e1fece7</imageId>\n                <keyName>jclouds#adriancole-ec2unssh</keyName>\n                <groupSet>\n                    <item>\n                        <groupName>jclouds#adriancole-ec2unssh#us-east-1</groupName>\n                    </item>\n                </groupSet>\n                <instanceType>t1.micro</instanceType>\n                <blockDeviceMapping/>\n                <monitoring>\n                    <enabled>false</enabled>\n                </monitoring>\n            </launchSpecification>\n            <createTime>2011-07-29T04:02:53.000Z</createTime>\n            <productDescription>Linux/UNIX</productDescription>\n            <tagSet>\n                <item>\n                    <key>One</key>\n                    <value>two</value>\n                </item>\n                <item>\n                    <key>Two</key>\n                    <value>two</value>\n                </item>\n            </tagSet>            \n            <launchedAvailabilityZone>us-east-1b</launchedAvailabilityZone>\n        </item>\n        <item>\n            <spotInstanceRequestId>sir-e4c3fa14</spotInstanceRequestId>\n            <spotPrice>0.300000</spotPrice>\n            <type>one-time</type>\n            <state>closed</state>\n            <launchSpecification>\n                <imageId>ami-8e1fece7</imageId>\n                <keyName>ec2-o</keyName>\n                <groupSet>\n                    <item>\n                        <groupName>jclouds#ec2-o#us-east-1</groupName>\n                    </item>\n                    <item>\n                        <groupName>ec2-o</groupName>\n                    </item>\n                </groupSet>\n                <instanceType>t1.micro</instanceType>\n                <blockDeviceMapping/>\n                <monitoring>\n                    <enabled>true</enabled>\n                </monitoring>\n            </launchSpecification>\n            <createTime>2011-07-29T05:25:49.000Z</createTime>\n            <productDescription>Linux/UNIX</productDescription>\n            <tagSet>\n                <item>\n                    <key>Two</key>\n                    <value>three</value>\n                </item>\n                <item>\n                    <key>Three</key>\n                    <value>three</value>\n                </item>\n                <item>\n                    <key>Four</key>\n                    <value />\n                </item>\n            </tagSet>            \n            <launchedAvailabilityZone>us-east-1c</launchedAvailabilityZone>\n        </item>\n    </spotInstanceRequestSet>\n</DescribeSpotInstanceRequestsResponse>"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/describe_spot_instances_1.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<DescribeSpotInstanceRequestsResponse xmlns=\"http://ec2.amazonaws.com/doc/2012-06-01/\">\n    <requestId>f2247378-7df0-4725-b55f-8ef58b557dcd</requestId>\n    <spotInstanceRequestSet>\n        <item>\n            <spotInstanceRequestId>sir-f4d44212</spotInstanceRequestId>\n            <spotPrice>0.300000</spotPrice>\n            <type>one-time</type>\n            <state>cancelled</state>\n            <launchSpecification>\n                <imageId>ami-8e1fece7</imageId>\n                <keyName>ec2-o</keyName>\n                <groupSet>\n                    <item>\n                        <groupName>jclouds#ec2-o#us-east-1</groupName>\n                    </item>\n                    <item>\n                        <groupName>ec2-o</groupName>\n                    </item>\n                </groupSet>\n                <instanceType>t1.micro</instanceType>\n                <blockDeviceMapping/>\n                <monitoring>\n                    <enabled>true</enabled>\n                </monitoring>\n            </launchSpecification>\n            <createTime>2011-07-29T04:01:12.000Z</createTime>\n            <productDescription>Linux/UNIX</productDescription>\n            <launchedAvailabilityZone>us-east-1b</launchedAvailabilityZone>\n        </item>\n        <item>\n            <spotInstanceRequestId>sir-43408412</spotInstanceRequestId>\n            <spotPrice>0.300000</spotPrice>\n            <type>one-time</type>\n            <state>cancelled</state>\n            <launchSpecification>\n                <imageId>ami-8e1fece7</imageId>\n                <keyName>jclouds#adriancole-ec2unssh</keyName>\n                <groupSet>\n                    <item>\n                        <groupName>jclouds#adriancole-ec2unssh#us-east-1</groupName>\n                    </item>\n                </groupSet>\n                <instanceType>t1.micro</instanceType>\n                <blockDeviceMapping/>\n                <monitoring>\n                    <enabled>false</enabled>\n                </monitoring>\n            </launchSpecification>\n            <createTime>2011-07-29T04:02:53.000Z</createTime>\n            <productDescription>Linux/UNIX</productDescription>\n            <launchedAvailabilityZone>us-east-1b</launchedAvailabilityZone>\n        </item>\n        <item>\n            <spotInstanceRequestId>sir-e4c3fa14</spotInstanceRequestId>\n            <spotPrice>0.300000</spotPrice>\n            <type>one-time</type>\n            <state>closed</state>\n            <launchSpecification>\n                <imageId>ami-8e1fece7</imageId>\n                <keyName>ec2-o</keyName>\n                <groupSet>\n                    <item>\n                        <groupName>jclouds#ec2-o#us-east-1</groupName>\n                    </item>\n                    <item>\n                        <groupName>ec2-o</groupName>\n                    </item>\n                </groupSet>\n                <instanceType>t1.micro</instanceType>\n                <blockDeviceMapping/>\n                <monitoring>\n                    <enabled>true</enabled>\n                </monitoring>\n            </launchSpecification>\n            <createTime>2011-07-29T05:25:49.000Z</createTime>\n            <productDescription>Linux/UNIX</productDescription>\n            <launchedAvailabilityZone>us-east-1c</launchedAvailabilityZone>\n        </item>\n        <item>\n            <spotInstanceRequestId>sir-1ede0012</spotInstanceRequestId>\n            <spotPrice>0.300000</spotPrice>\n            <type>one-time</type>\n            <state>closed</state>\n            <launchSpecification>\n                <imageId>ami-8e1fece7</imageId>\n                <keyName>jclouds#adriancole-ec2unssh</keyName>\n                <groupSet>\n                    <item>\n                        <groupName>jclouds#adriancole-ec2unssh#us-east-1</groupName>\n                    </item>\n                </groupSet>\n                <instanceType>t1.micro</instanceType>\n                <blockDeviceMapping/>\n                <monitoring>\n                    <enabled>false</enabled>\n                </monitoring>\n            </launchSpecification>\n            <createTime>2011-07-29T05:27:39.000Z</createTime>\n            <productDescription>Linux/UNIX</productDescription>\n            <launchedAvailabilityZone>us-east-1b</launchedAvailabilityZone>\n        </item>\n        <item>\n            <spotInstanceRequestId>sir-596fa211</spotInstanceRequestId>\n            <spotPrice>0.300000</spotPrice>\n            <type>one-time</type>\n            <state>closed</state>\n            <launchSpecification>\n                <imageId>ami-8e1fece7</imageId>\n                <keyName>ec2-o</keyName>\n                <groupSet>\n                    <item>\n                        <groupName>jclouds#ec2-o#us-east-1</groupName>\n                    </item>\n                    <item>\n                        <groupName>ec2-o</groupName>\n                    </item>\n                </groupSet>\n                <instanceType>t1.micro</instanceType>\n                <blockDeviceMapping/>\n                <monitoring>\n                    <enabled>true</enabled>\n                </monitoring>\n            </launchSpecification>\n            <createTime>2011-07-29T06:22:37.000Z</createTime>\n            <productDescription>Linux/UNIX</productDescription>\n            <launchedAvailabilityZone>us-east-1b</launchedAvailabilityZone>\n        </item>\n        <item>\n            <spotInstanceRequestId>sir-cc233214</spotInstanceRequestId>\n            <spotPrice>0.300000</spotPrice>\n            <type>one-time</type>\n            <state>closed</state>\n            <launchSpecification>\n                <imageId>ami-8e1fece7</imageId>\n                <keyName>ec2-o</keyName>\n                <groupSet>\n                    <item>\n                        <groupName>jclouds#ec2-o#us-east-1</groupName>\n                    </item>\n                    <item>\n                        <groupName>ec2-o</groupName>\n                    </item>\n                </groupSet>\n                <instanceType>t1.micro</instanceType>\n                <blockDeviceMapping/>\n                <monitoring>\n                    <enabled>true</enabled>\n                </monitoring>\n            </launchSpecification>\n            <createTime>2011-07-29T07:48:03.000Z</createTime>\n            <productDescription>Linux/UNIX</productDescription>\n            <launchedAvailabilityZone>us-east-1c</launchedAvailabilityZone>\n        </item>\n        <item>\n            <spotInstanceRequestId>sir-cf9dd211</spotInstanceRequestId>\n            <spotPrice>0.300000</spotPrice>\n            <type>one-time</type>\n            <state>active</state>\n            <launchSpecification>\n                <imageId>ami-8e1fece7</imageId>\n                <keyName>jclouds#adriancole-ec2unssh</keyName>\n                <groupSet>\n                    <item>\n                        <groupName>jclouds#adriancole-ec2unssh#us-east-1</groupName>\n                    </item>\n                </groupSet>\n                <instanceType>t1.micro</instanceType>\n                <blockDeviceMapping/>\n                <monitoring>\n                    <enabled>false</enabled>\n                </monitoring>\n            </launchSpecification>\n            <instanceId>i-1faa137e</instanceId>\n            <createTime>2011-07-29T08:05:45.000Z</createTime>\n            <productDescription>Linux/UNIX</productDescription>\n            <launchedAvailabilityZone>us-east-1c</launchedAvailabilityZone>\n        </item>\n        <item>\n            <spotInstanceRequestId>sir-6bba1e14</spotInstanceRequestId>\n            <spotPrice>0.300000</spotPrice>\n            <type>one-time</type>\n            <state>active</state>\n            <launchSpecification>\n                <imageId>ami-8e1fece7</imageId>\n                <keyName>ec2-o</keyName>\n                <groupSet>\n                    <item>\n                        <groupName>jclouds#ec2-o#us-east-1</groupName>\n                    </item>\n                    <item>\n                        <groupName>ec2-o</groupName>\n                    </item>\n                </groupSet>\n                <instanceType>t1.micro</instanceType>\n                <blockDeviceMapping/>\n                <monitoring>\n                    <enabled>true</enabled>\n                </monitoring>\n            </launchSpecification>\n            <instanceId>i-15982174</instanceId>\n            <createTime>2011-07-29T08:20:27.000Z</createTime>\n            <productDescription>Linux/UNIX</productDescription>\n            <launchedAvailabilityZone>us-east-1c</launchedAvailabilityZone>\n        </item>\n    </spotInstanceRequestSet>\n</DescribeSpotInstanceRequestsResponse>"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/describe_spot_price_history.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<DescribeSpotPriceHistoryResponse xmlns=\"http://ec2.amazonaws.com/doc/2012-06-01/\">\n    <requestId>99777a75-2a2b-4296-a305-650c442d2d63</requestId>\n    <spotPriceHistorySet>\n        <item>\n            <instanceType>t1.micro</instanceType>\n            <productDescription>SUSE Linux</productDescription>\n            <spotPrice>0.013000</spotPrice>\n            <timestamp>2011-03-07T12:17:19.000Z</timestamp>\n            <availabilityZone>us-west-1a</availabilityZone>\n        </item>\n        <item>\n            <instanceType>m1.large</instanceType>\n            <productDescription>Linux/UNIX</productDescription>\n            <spotPrice>0.119000</spotPrice>\n            <timestamp>2011-03-07T16:29:16.000Z</timestamp>\n            <availabilityZone>us-west-1b</availabilityZone>\n        </item>\n        <item>\n            <instanceType>t1.micro</instanceType>\n            <productDescription>Windows</productDescription>\n            <spotPrice>0.013000</spotPrice>\n            <timestamp>2011-03-07T17:56:54.000Z</timestamp>\n            <availabilityZone>us-west-1c</availabilityZone>\n        </item>\n    </spotPriceHistorySet>\n</DescribeSpotPriceHistoryResponse>"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/describe_vpcs.xml",
    "content": "<DescribeVpcsResponse xmlns=\"http://ec2.amazonaws.com/doc/2016-09-15/\">\n    <requestId>7a62c49f-347e-4fc4-9331-6e8eEXAMPLE</requestId>\n    <vpcSet>\n        <item>\n            <vpcId>vpc-1a2b3c4d</vpcId>\n            <state>available</state>\n            <cidrBlock>10.0.0.0/23</cidrBlock>\n            <dhcpOptionsId>dopt-7a8b9c2d</dhcpOptionsId>\n            <instanceTenancy>default</instanceTenancy>\n            <isDefault>false</isDefault>\n            <tagSet/>\n        </item>\n    </vpcSet>\n</DescribeVpcsResponse>\n"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/detach_internet_gateway.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<DetachInternetGatewayResponse xmlns=\"http://ec2.amazonaws.com/doc/2012-06-01/\">\n    <requestId>3aa4e5fb-2395-4560-bd0d-d229bdc75391</requestId>\n    <return>true</return>\n</DetachInternetGatewayResponse>\n"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/disassociate_route_table.xml",
    "content": "<DisassociateRouteTableResponse xmlns=\"http://ec2.amazonaws.com/doc/2012-06-01/\">\n    <requestId>36e6a0e6-cd7a-45fc-8539-ba05cc070a3f</requestId>\n    <return>true</return>\n</DisassociateRouteTableResponse>"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/dry_run.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Response>\n    <Errors>\n        <Error>\n            <Code>DryRunOperation</Code>\n            <Message>Request would have succeeded, but DryRun flag is set.</Message>\n        </Error>\n    </Errors>\n    <RequestID>344ef005-e34b-42fb-a334-1180fe317e7c</RequestID>\n</Response>\n\n"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/get_internet_gateway.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<DescribeInternetGatewaysResponse xmlns=\"http://ec2.amazonaws.com/doc/2012-06-01/\">\n    <requestId>b4064e62-7923-4559-8b7c-d8e6b4174d48</requestId>\n    <internetGatewaySet>\n        <item>\n            <internetGatewayId>igw-fada7c9c</internetGatewayId>\n            <attachmentSet>\n                <item>\n                    <vpcId>vpc-6250b91b</vpcId>\n                    <state>available</state>\n                </item>\n            </attachmentSet>\n            <tagSet>\n                <item>\n                    <key>Name</key>\n                    <value>get_internet_gateway_test</value>\n                </item>\n            </tagSet>\n        </item>\n    </internetGatewaySet>\n</DescribeInternetGatewaysResponse>"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/logback-test.xml",
    "content": "<?xml version=\"1.0\"?>\n<configuration scan=\"false\">\n    <appender name=\"FILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds.log</file>\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n    <appender name=\"WIREFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds-wire.log</file>\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n    <appender name=\"COMPUTEFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds-compute.log</file>\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <logger name=\"org.jclouds\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"FILE\" />\n    </logger>\n    <logger name=\"jclouds.compute\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"COMPUTEFILE\" />\n    </logger>\n    <logger name=\"jclouds.wire\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n    <logger name=\"jclouds.headers\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n\n    <root>\n        <level value=\"INFO\" />\n    </root>\n</configuration>\n"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/monitoring.xml",
    "content": "<UnmonitorInstancesResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n    <instancesSet>\n\t  <item>\n\t    <instanceId> i-43a4412a</instanceId>\n\t    <monitoring>\n\t      <state>pending</state>\n\t    </monitoring>\n\t  </item>\n\t  <item>\n\t    <instanceId>i-23a3397d</instanceId>\n\t    <monitoring>\n\t      <state>pending</state>\n\t    </monitoring>\n\t  </item>\n    </instancesSet>\n</UnmonitorInstancesResponse>"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/replace_route.xml",
    "content": "<ReplaceRouteResponse xmlns=\"http://ec2.amazonaws.com/doc/2016-11-15/\">\n    <requestId>59dbff89-35bd-4eac-99ed-be587EXAMPLE</requestId>\n    <return>true</return>\n</ReplaceRouteResponse>"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/request_spot_instances-ebs.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<RequestSpotInstancesResponse xmlns=\"http://ec2.amazonaws.com/doc/2012-06-01/\">\n    <requestId>02401e8e-a4f5-4285-8ea8-6d742fbaadd8</requestId>\n    <spotInstanceRequestSet>\n        <item>\n            <spotInstanceRequestId>sir-228e6406</spotInstanceRequestId>\n            <spotPrice>0.001000</spotPrice>\n            <type>one-time</type>\n            <state>open</state>\n            <launchSpecification>\n                <imageId>ami-595a0a1c</imageId>\n                <groupSet>\n                    <item>\n                        <groupId>sg-83e1c4ea</groupId>\n                        <groupName>default</groupName>\n                    </item>\n                </groupSet>\n                <instanceType>m1.large</instanceType>\n                <blockDeviceMapping>\n                    <item>\n                        <deviceName>/dev/sda1</deviceName>\n                        <ebs>\n                            <volumeSize>1</volumeSize>\n                            <deleteOnTermination>true</deleteOnTermination>\n                        </ebs>\n                    </item>\n                    <item>\n                        <deviceName>/dev/sda3</deviceName>\n                        <virtualName>vre1</virtualName>\n                    </item>\n                    <item>\n                        <deviceName>/dev/sda2</deviceName>\n                        <ebs>\n                            <snapshotId>snap-1ea27576</snapshotId>\n                            <volumeSize>1</volumeSize>\n                            <deleteOnTermination>true</deleteOnTermination>\n                        </ebs>\n                    </item>\n                </blockDeviceMapping>\n                <monitoring>\n                    <enabled>false</enabled>\n                </monitoring>\n                <iamInstanceProfile>\n                     <arn>arn:aws:iam::123456789012:instance-profile/application_abc/component_xyz/Webserver</arn>\n                     <name>Webserver</name>\n                </iamInstanceProfile>\n            </launchSpecification>\n            <status>\n                <code>pending-fulfillment</code>\n                <message>Pending fulfillment</message>\n                <updateTime>2011-03-08T03:30:36.000Z</updateTime>\n            </status>\n            <createTime>2011-03-08T03:30:36.000Z</createTime>\n            <validFrom>2011-03-08T03:30:36.000Z</validFrom>\n            <validUntil>2011-03-08T03:30:36.000Z</validUntil>\n            <productDescription>Linux/UNIX</productDescription>\n        </item>\n    </spotInstanceRequestSet>\n</RequestSpotInstancesResponse>"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/request_spot_instances.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<RequestSpotInstancesResponse xmlns=\"http://ec2.amazonaws.com/doc/2012-06-01/\">\n    <requestId>2ffc645f-6835-4d23-bd18-f6f53c253067</requestId>\n    <spotInstanceRequestSet>\n        <item>\n            <spotInstanceRequestId>sir-7c74f805</spotInstanceRequestId>\n            <spotPrice>0.001000</spotPrice>\n            <type>one-time</type>\n            <state>open</state>\n            <launchSpecification>\n                <imageId>ami-595a0a1c</imageId>\n                <groupSet>\n                    <item>\n                        <groupId>default</groupId>\n                    </item>\n                </groupSet>\n                <instanceType>t1.micro</instanceType>\n                <blockDeviceMapping>\n                    <item>\n                        <deviceName>/dev/sda1</deviceName>\n                        <ebs>\n                            <volumeSize>120</volumeSize>\n                            <deleteOnTermination>true</deleteOnTermination>\n                        </ebs>\n                    </item>\n                </blockDeviceMapping>\n                <monitoring>\n                    <enabled>false</enabled>\n                </monitoring>\n            </launchSpecification>\n            <createTime>2011-03-08T02:36:32.000Z</createTime>\n            <productDescription>Linux/UNIX</productDescription>\n        </item>\n        <item>\n            <spotInstanceRequestId>sir-78ca7605</spotInstanceRequestId>\n            <spotPrice>0.001000</spotPrice>\n            <type>one-time</type>\n            <state>open</state>\n            <launchSpecification>\n                <imageId>ami-595a0a1c</imageId>\n                <groupSet>\n                    <item>\n                        <groupId>default</groupId>\n                    </item>\n                </groupSet>\n                <instanceType>t1.micro</instanceType>\n                <blockDeviceMapping>\n                    <item>\n                        <deviceName>/dev/sda1</deviceName>\n                        <ebs>\n                            <volumeSize>120</volumeSize>\n                            <deleteOnTermination>true</deleteOnTermination>\n                        </ebs>\n                    </item>\n                </blockDeviceMapping>\n                <monitoring>\n                    <enabled>false</enabled>\n                </monitoring>\n            </launchSpecification>\n            <createTime>2011-03-08T02:36:32.000Z</createTime>\n            <productDescription>Linux/UNIX</productDescription>\n        </item>\n        <item>\n            <spotInstanceRequestId>sir-7e0f6005</spotInstanceRequestId>\n            <spotPrice>0.001000</spotPrice>\n            <type>one-time</type>\n            <state>open</state>\n            <launchSpecification>\n                <imageId>ami-595a0a1c</imageId>\n                <groupSet>\n                    <item>\n                        <groupId>default</groupId>\n                    </item>\n                </groupSet>\n                <instanceType>t1.micro</instanceType>\n                <blockDeviceMapping>\n                    <item>\n                        <deviceName>/dev/sda1</deviceName>\n                        <ebs>\n                            <volumeSize>120</volumeSize>\n                            <deleteOnTermination>true</deleteOnTermination>\n                        </ebs>\n                    </item>\n                </blockDeviceMapping>\n                <monitoring>\n                    <enabled>false</enabled>\n                </monitoring>\n            </launchSpecification>\n            <createTime>2011-03-08T02:36:32.000Z</createTime>\n            <productDescription>Linux/UNIX</productDescription>\n        </item>\n    </spotInstanceRequestSet>\n</RequestSpotInstancesResponse>"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/rightscale_images.xml",
    "content": "<?xml version=\"1.0\"?>\n<DescribeImagesResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n    <requestId>50c73a72-cf38-462f-aba2-f59116380d36</requestId>\n    <imagesSet>\n        <item>\n            <imageId>ami-ccb35ea5</imageId>\n            <imageLocation>rightscale-us-east/CentOS_5.4_x64_v4.4.10.manifest.xml</imageLocation>\n            <imageState>available</imageState>\n            <imageOwnerId>411009282317</imageOwnerId>\n            <isPublic>true</isPublic>\n            <architecture>x86_64</architecture>\n            <imageType>machine</imageType>\n            <kernelId>aki-b51cf9dc</kernelId>\n            <ramdiskId>ari-b31cf9da</ramdiskId>\n            <rootDeviceType>instance-store</rootDeviceType>\n            <rootDeviceName>/dev/sda1</rootDeviceName>\n            <blockDeviceMapping/>\n        </item>\n        <item>\n            <imageId>ami-c19db6b5</imageId>\n            <imageLocation>411009282317/RightImage_Ubuntu_9.10_x64_v4.5.3_EBS_Alpha</imageLocation>\n            <imageState>available</imageState>\n            <imageOwnerId>411009282317</imageOwnerId>\n            <isPublic>true</isPublic>\n            <architecture>x86_64</architecture>\n            <imageType>machine</imageType>\n            <kernelId>aki-a22a01d6</kernelId>\n            <ramdiskId>ari-ac2a01d8</ramdiskId>\n            <name>RightImage_Ubuntu_9.10_x64_v4.5.3_EBS_Alpha</name>\n            <description>RightImage_Ubuntu_9.10_x64_v4.5.3_EBS_Alpha</description>\n            <rootDeviceType>ebs</rootDeviceType>\n            <rootDeviceName>/dev/sda1</rootDeviceName>\n            <blockDeviceMapping>\n                <item>\n                    <deviceName>/dev/sda1</deviceName>\n                    <ebs>\n                        <snapshotId>snap-a222ddcb</snapshotId>\n                        <volumeSize>10</volumeSize>\n                        <deleteOnTermination>true</deleteOnTermination>\n                    </ebs>\n                </item>\n            </blockDeviceMapping>\n        </item>\n        <item>\n            <imageId>ami-710c2605</imageId>\n            <imageLocation>411009282317/RightImage Windows_2003_i386_v5.4.3</imageLocation>\n            <imageState>available</imageState>\n            <imageOwnerId>411009282317</imageOwnerId>\n            <isPublic>true</isPublic>\n            <architecture>i386</architecture>\n            <imageType>machine</imageType>\n            <platform>windows</platform>\n            <name>RightImage Windows_2003_i386_v5.4.3</name>\n            <description>Built by RightScale</description>\n            <rootDeviceType>ebs</rootDeviceType>\n            <rootDeviceName>/dev/sda1</rootDeviceName>\n            <blockDeviceMapping>\n                <item>\n                    <deviceName>/dev/sda1</deviceName>\n                    <ebs>\n                        <snapshotId>snap-9460affd</snapshotId>\n                        <volumeSize>35</volumeSize>\n                        <deleteOnTermination>true</deleteOnTermination>\n                    </ebs>\n                </item>\n            </blockDeviceMapping>\n            <virtualizationType>hvm</virtualizationType>\n        </item>\n        <item>\n            <imageId>ami-c6a882b2</imageId>\n            <imageLocation>411009282317/RightImage_Windows_2008_x64_v5.5.5</imageLocation>\n            <imageOwnerId>411009282317</imageOwnerId>\n            <isPublic>true</isPublic>\n            <architecture>x86_64</architecture>\n            <imageType>machine</imageType>\n            <platform>windows</platform>\n            <name>RightImage_Windows_2008_x64_v5.5.5</name>            \n            <description>Built by RightScale</description>\n            <rootDeviceType>ebs</rootDeviceType>\n            <rootDeviceName>/dev/sda1</rootDeviceName> \n            <blockDeviceMapping>\n                <item>\n                    <deviceName>/dev/sda1</deviceName> \n                    <ebs>\n                        <snapshotId>snap-68b26c01</snapshotId>                     \n                        <volumeSize>80</volumeSize> \n                        <deleteOnTermination>true</deleteOnTermination>            \n                    </ebs>\n                </item>\n            </blockDeviceMapping>\n            <virtualizationType>hvm</virtualizationType>\n        </item>\n        <item>\n            <imageId>ami-05ebd06c</imageId>\n            <imageLocation>411009282317/RightImage_CentOS_6.5_x64_v13.5.2.2_EBS</imageLocation>\n            <imageState>available</imageState>\n            <imageOwnerId>411009282317</imageOwnerId>\n            <isPublic>true</isPublic>\n            <architecture>x86_64</architecture>\n            <imageType>machine</imageType>\n            <kernelId>aki-88aa75e1</kernelId>\n            <name>RightImage_CentOS_6.5_x64_v13.5.2.2_EBS</name>\n            <description>RightImage_CentOS_6.5_x64_v13.5.2.2_EBS</description>\n            <rootDeviceType>ebs</rootDeviceType>\n            <rootDeviceName>/dev/sda1</rootDeviceName>\n            <blockDeviceMapping>\n                <item>\n                    <deviceName>/dev/sda1</deviceName>\n                    <ebs>\n                        <snapshotId>snap-f746a235</snapshotId>\n                        <volumeSize>10</volumeSize>\n                        <deleteOnTermination>true</deleteOnTermination>\n                    </ebs>\n                </item>\n            </blockDeviceMapping>\n            <virtualizationType>paravirtual</virtualizationType>\n            <hypervisor>xen</hypervisor>\n        </item>\n        <item>\n            <imageId>ami-08bffe61</imageId>\n            <imageLocation>411009282317/RightImage_Ubuntu_10.04_x64_v12.11.4_EBS</imageLocation>\n            <imageState>available</imageState>\n            <imageOwnerId>411009282317</imageOwnerId>\n            <isPublic>true</isPublic>\n            <architecture>x86_64</architecture>\n            <imageType>machine</imageType>\n            <kernelId>aki-88aa75e1</kernelId>\n            <name>RightImage_Ubuntu_10.04_x64_v12.11.4_EBS</name>\n            <description>RightImage_Ubuntu_10.04_x64_v12.11.4_EBS</description>\n            <rootDeviceType>ebs</rootDeviceType>\n            <rootDeviceName>/dev/sda1</rootDeviceName>\n            <blockDeviceMapping>\n                <item>\n                    <deviceName>/dev/sda1</deviceName>\n                    <ebs>\n                        <snapshotId>snap-3567d562</snapshotId>\n                        <volumeSize>10</volumeSize>\n                        <deleteOnTermination>true</deleteOnTermination>\n                    </ebs>\n                </item>\n            </blockDeviceMapping>\n            <virtualizationType>paravirtual</virtualizationType>\n            <hypervisor>xen</hypervisor>\n        </item>        \n    </imagesSet>\n</DescribeImagesResponse>\n"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/run_instances_1.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<RunInstancesResponse xmlns=\"http://ec2.amazonaws.com/doc/2012-06-01/\">\n    <requestId>7faf9500-67ef-484b-9fa5-73b6df638bc8</requestId>\n    <reservationId>r-d3b815bc</reservationId>\n    <ownerId>993194456877</ownerId>\n    <groupSet>\n        <item>\n            <groupId>sg-3ffcd956</groupId>\n            <groupName>jclouds#adriancoleec2cccluster#us-east-1</groupName>\n        </item>\n    </groupSet>\n    <instancesSet>\n        <item>\n            <instanceId>i-8949f0e8</instanceId>\n            <imageId>ami-ab5b9cc2</imageId>\n            <instanceState>\n                <code>0</code>\n                <name>pending</name>\n            </instanceState>\n            <privateDnsName/>\n            <dnsName/>\n            <reason/>\n            <keyName>jclouds#adriancoleec2cccluster</keyName>\n            <amiLaunchIndex>0</amiLaunchIndex>\n            <productCodes/>\n            <instanceType>cc1.4xlarge</instanceType>\n            <launchTime>2011-07-29T09:46:48.000Z</launchTime>\n            <placement>\n                <availabilityZone>us-east-1d</availabilityZone>\n                <groupName>jclouds#adriancoleec2cccluster#us-east-1</groupName>\n                <tenancy>default</tenancy>\n            </placement>\n            <monitoring>\n                <state>disabled</state>\n            </monitoring>\n            <groupSet>\n                <item>\n                    <groupId>sg-3ffcd956</groupId>\n                    <groupName>jclouds#adriancoleec2cccluster#us-east-1</groupName>\n                </item>\n            </groupSet>\n            <stateReason>\n                <code>pending</code>\n                <message>pending</message>\n            </stateReason>\n            <rootDeviceType>ebs</rootDeviceType>\n            <rootDeviceName>/dev/sda1</rootDeviceName>\n            <blockDeviceMapping/>\n            <virtualizationType>hvm</virtualizationType>\n            <clientToken/>\n            <hypervisor>xen</hypervisor>\n        </item>\n    </instancesSet>\n</RunInstancesResponse>"
  },
  {
    "path": "providers/aws-ec2/src/test/resources/vostok.xml",
    "content": "<?xml version=\"1.0\"?>\n<DescribeImagesResponse xmlns=\"http://ec2.amazonaws.com/doc/2009-11-30/\">\n    <requestId>6104eee1-affd-49d7-92a0-516cab8a8ba6</requestId>\n    <imagesSet>\n        <item>\n            <imageId>ami-870de2ee</imageId>\n            <imageLocation>vostok-builds/vostok-0.95-5622/vostok-0.95-5622.manifest.xml</imageLocation>\n            <imageState>available</imageState>\n            <imageOwnerId>133804938231</imageOwnerId>\n            <isPublic>false</isPublic>\n            <architecture>i386</architecture>\n            <imageType>machine</imageType>\n            <kernelId>aki-94c527fd</kernelId>\n            <ramdiskId>ari-96c527ff</ramdiskId>\n            <rootDeviceType>instance-store</rootDeviceType>\n            <blockDeviceMapping />\n        </item>\n    </imagesSet>\n</DescribeImagesResponse>\n"
  },
  {
    "path": "providers/aws-route53/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.aws.route53.*;version=\"${project.version}\";-noimport:=true"
  },
  {
    "path": "providers/aws-route53/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.provider</groupId>\n  <artifactId>aws-route53</artifactId>\n  <name>jclouds Amazon Route 53 provider</name>\n  <description>Route 53 targeted to Amazon Web Services</description>\n\n  <properties>\n    <test.aws.identity>FIXME_IDENTITY</test.aws.identity>\n    <test.aws.credential>FIXME_CREDENTIAL</test.aws.credential>\n    <test.aws-route53.endpoint>https://route53.amazonaws.com</test.aws-route53.endpoint>\n    <test.aws-route53.api-version>2012-02-29</test.aws-route53.api-version>\n    <test.aws-route53.build-version />\n    <test.aws-route53.identity>${test.aws.identity}</test.aws-route53.identity>\n    <test.aws-route53.credential>${test.aws.credential}</test.aws-route53.credential>\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>route53</artifactId>\n      <version>${project.version}</version>\n      <type>jar</type>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>route53</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-log4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.aws-route53.endpoint>${test.aws-route53.endpoint}</test.aws-route53.endpoint>\n                    <test.aws-route53.api-version>${test.aws-route53.api-version}</test.aws-route53.api-version>\n                    <test.aws-route53.build-version>${test.aws-route53.build-version}</test.aws-route53.build-version>\n                    <test.aws-route53.identity>${test.aws-route53.identity}</test.aws-route53.identity>\n                    <test.aws-route53.credential>${test.aws-route53.credential}</test.aws-route53.credential>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n"
  },
  {
    "path": "providers/aws-route53/src/main/java/org/jclouds/aws/route53/AWSRoute53ProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.route53;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.route53.Route53ApiMetadata;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\n\nimport com.google.auto.service.AutoService;\n\n/**\n * Implementation of @ link org.jclouds.types.ProviderMetadata} for Amazon's Route53\n * provider.\n*\n*/\n@AutoService(ProviderMetadata.class)\npublic class AWSRoute53ProviderMetadata extends BaseProviderMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromProviderMetadata(this);\n   }\n   \n   public AWSRoute53ProviderMetadata() {\n      super(builder());\n   }\n\n   public AWSRoute53ProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = new Properties();\n      return properties;\n   }\n   \n   public static class Builder extends BaseProviderMetadata.Builder {\n\n      protected Builder() {\n         id(\"aws-route53\")\n         .name(\"Amazon Route53\")\n         .endpoint(\"https://route53.amazonaws.com\")\n         .homepage(URI.create(\"http://aws.amazon.com/route53/\"))\n         .console(URI.create(\"https://console.aws.amazon.com/route53/home\"))\n         .linkedServices(\"aws-ec2\", \"aws-elb\", \"aws-iam\", \"aws-route53\", \"aws-sts\", \"aws-cloudwatch\", \"aws-s3\",\n                     \"aws-sqs\", \"aws-simpledb\")\n         .iso3166Codes(\"US-VA\")\n         .apiMetadata(new Route53ApiMetadata())\n         .defaultProperties(AWSRoute53ProviderMetadata.defaultProperties());\n      }\n\n      @Override\n      public AWSRoute53ProviderMetadata build() {\n         return new AWSRoute53ProviderMetadata(this);\n      }\n      \n      @Override\n      public Builder fromProviderMetadata(ProviderMetadata in) {\n         super.fromProviderMetadata(in);\n         return this;\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/aws-route53/src/test/java/org/jclouds/aws/route53/AWSRoute53ApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.route53;\n\nimport org.jclouds.route53.Route53ApiLiveTest;\nimport org.testng.annotations.Test;\n\n/**\n * Teroute53 behavior of {@code Route53Api}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"AWSRoute53ApiLiveTest\")\npublic class AWSRoute53ApiLiveTest extends Route53ApiLiveTest {\n   public AWSRoute53ApiLiveTest() {\n      provider = \"aws-route53\";\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-route53/src/test/java/org/jclouds/aws/route53/AWSRoute53ProviderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.route53;\n\nimport org.jclouds.route53.Route53ApiMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.testng.annotations.Test;\n\n/**\n * The AWSRoute53ProviderTest teroute53 the org.jclouds.providers.AWSRoute53Provider class.\n */\n@Test(groups = \"unit\", testName = \"AWSRoute53ProviderTest\")\npublic class AWSRoute53ProviderTest extends BaseProviderMetadataTest {\n\n   public AWSRoute53ProviderTest() {\n      super(new AWSRoute53ProviderMetadata(), new Route53ApiMetadata());\n   }\n}\n"
  },
  {
    "path": "providers/aws-route53/src/test/java/org/jclouds/aws/route53/features/AWSHostedZoneApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.route53.features;\n\nimport org.jclouds.route53.features.HostedZoneApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"AWSHostedZoneApiLiveTest\")\npublic class AWSHostedZoneApiLiveTest extends HostedZoneApiLiveTest {\n   public AWSHostedZoneApiLiveTest() {\n      provider = \"aws-route53\";\n   }\n}\n"
  },
  {
    "path": "providers/aws-route53/src/test/java/org/jclouds/aws/route53/features/AWSResourceRecordSetApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.route53.features;\n\nimport org.jclouds.route53.features.ResourceRecordSetApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"AWSResourceResourceRecordSetApiLiveTest\")\npublic class AWSResourceRecordSetApiLiveTest extends ResourceRecordSetApiLiveTest {\n   public AWSResourceRecordSetApiLiveTest() {\n      provider = \"aws-route53\";\n   }\n}\n"
  },
  {
    "path": "providers/aws-s3/README.md",
    "content": "# The jclouds provider for Amazon's S3 (http://aws.amazon.com/s3/)\n\nExpects the jclouds s3 API to be present on your application's classpath.\n\n* **TODO**: Implementation status.\n* **TODO**: Supported features.\n* **TODO**: Usage example.\n\n## Running live tests\n\nTry\n\n```sh\nmvn clean install -Plive -pl :aws-s3 -Dtest=AWSS3ClientLiveTest -Dtest.aws-s3.identity=<aws_access_key_id> -Dtest.aws-s3.credential=<aws_secret_access_key>\n```\n\noptionally adding\n\n```sh\n-Dtest.aws-s3.sessionToken=<aws_session_token>\n```\n"
  },
  {
    "path": "providers/aws-s3/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.aws.s3.*;version=\"${project.version}\";-noimport:=true"
  },
  {
    "path": "providers/aws-s3/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.provider</groupId>\n  <artifactId>aws-s3</artifactId>\n  <name>jclouds Amazon Simple Storage Service (S3) provider</name>\n  <description>Simple Storage Service (S3) implementation targeted to Amazon Web Services</description>\n\n  <properties>\n    <test.aws.identity>FIXME_IDENTITY</test.aws.identity>\n    <test.aws.credential>FIXME_CREDENTIAL</test.aws.credential>\n    <test.initializer>org.jclouds.aws.s3.blobstore.integration.AWSS3TestInitializer</test.initializer>\n    <test.aws-s3.endpoint>https://s3.amazonaws.com</test.aws-s3.endpoint>\n    <test.aws-s3.api-version>2006-03-01</test.aws-s3.api-version>\n    <test.aws-s3.build-version />\n    <test.aws-s3.identity>${test.aws.identity}</test.aws-s3.identity>\n    <test.aws-s3.credential>${test.aws.credential}</test.aws-s3.credential>\n    <test.aws-s3.sessionToken>${test.aws.sessionToken}</test.aws-s3.sessionToken>\n    <test.blobstore.container-count>25</test.blobstore.container-count>\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>s3</artifactId>\n      <version>${project.version}</version>\n      <type>jar</type>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>s3</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-blobstore</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-log4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-apachehc</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-enterprise</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.squareup.okhttp3</groupId>\n      <artifactId>mockwebserver</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.aws-s3.endpoint>${test.aws-s3.endpoint}</test.aws-s3.endpoint>\n                    <test.aws-s3.api-version>${test.aws-s3.api-version}</test.aws-s3.api-version>\n                    <test.aws-s3.build-version>${test.aws-s3.build-version}</test.aws-s3.build-version>\n                    <test.aws-s3.identity>${test.aws-s3.identity}</test.aws-s3.identity>\n                    <test.aws-s3.credential>${test.aws-s3.credential}</test.aws-s3.credential>\n                    <test.aws-s3.sessionToken>${test.aws-s3.sessionToken}</test.aws-s3.sessionToken>\n                    <test.initializer>${test.initializer}</test.initializer>\n                    <jclouds.blobstore.httpstream.url>${jclouds.blobstore.httpstream.url}</jclouds.blobstore.httpstream.url>\n                    <jclouds.blobstore.httpstream.md5>${jclouds.blobstore.httpstream.md5}</jclouds.blobstore.httpstream.md5>\n                    <test.blobstore.container-count>${test.blobstore.container-count}</test.blobstore.container-count>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n\n"
  },
  {
    "path": "providers/aws-s3/src/main/java/org/jclouds/aws/s3/AWSS3ApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.s3;\n\nimport static org.jclouds.reflect.Reflection2.typeToken;\nimport static org.jclouds.s3.reference.S3Constants.PROPERTY_S3_VIRTUAL_HOST_BUCKETS;\nimport static org.jclouds.s3.reference.S3Constants.PROPERTY_SIGNER_VERSION;\n\nimport java.util.Properties;\n\nimport org.jclouds.aws.s3.blobstore.AWSS3BlobStoreContext;\nimport org.jclouds.aws.s3.blobstore.config.AWSS3BlobStoreContextModule;\nimport org.jclouds.aws.s3.config.AWSS3HttpApiModule;\nimport org.jclouds.s3.S3ApiMetadata;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n/**\n * Implementation of {@link S3ApiMetadata} for the Amazon-specific S3 API\n */\npublic class AWSS3ApiMetadata extends S3ApiMetadata {\n\n   @Override\n   public Builder toBuilder() {\n      return new Builder().fromApiMetadata(this);\n   }\n\n   public AWSS3ApiMetadata() {\n      this(new Builder());\n   }\n\n   protected AWSS3ApiMetadata(Builder builder) {\n      super(builder);\n   }\n   \n   public static Properties defaultProperties() {\n      Properties properties = S3ApiMetadata.defaultProperties();\n      properties.setProperty(PROPERTY_S3_VIRTUAL_HOST_BUCKETS, \"true\");\n      properties.setProperty(PROPERTY_SIGNER_VERSION, \"4\");\n      return properties;\n   }\n\n   public static class Builder extends S3ApiMetadata.Builder<AWSS3Client, Builder> {\n      protected Builder() {\n         super(AWSS3Client.class);\n         id(\"aws-s3\")\n         .name(\"Amazon-specific S3 API\")\n         .defaultEndpoint(\"https://s3.amazonaws.com\")\n         .defaultProperties(AWSS3ApiMetadata.defaultProperties())\n         .view(typeToken(AWSS3BlobStoreContext.class))\n         .defaultModules(ImmutableSet.<Class<? extends Module>>of(AWSS3HttpApiModule.class, AWSS3BlobStoreContextModule.class));\n      }\n      \n      @Override\n      public AWSS3ApiMetadata build() {\n         return new AWSS3ApiMetadata(this);\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "providers/aws-s3/src/main/java/org/jclouds/aws/s3/AWSS3Client.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.s3;\n\nimport static org.jclouds.blobstore.attr.BlobScopes.CONTAINER;\n\nimport org.jclouds.blobstore.attr.BlobScope;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.s3.S3Client;\nimport org.jclouds.s3.filters.RequestAuthorizeSignature;\n\n/**\n * Provides access to amazon-specific S3 features\n */\n@RequestFilters(RequestAuthorizeSignature.class)\n@BlobScope(CONTAINER)\npublic interface AWSS3Client extends S3Client {\n}\n"
  },
  {
    "path": "providers/aws-s3/src/main/java/org/jclouds/aws/s3/AWSS3ProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.s3;\n\nimport static org.jclouds.Constants.PROPERTY_ENDPOINT;\nimport static org.jclouds.aws.domain.Region.AP_NORTHEAST_1;\nimport static org.jclouds.aws.domain.Region.AP_NORTHEAST_2;\nimport static org.jclouds.aws.domain.Region.AP_SOUTHEAST_1;\nimport static org.jclouds.aws.domain.Region.AP_SOUTHEAST_2;\nimport static org.jclouds.aws.domain.Region.AP_SOUTH_1;\nimport static org.jclouds.aws.domain.Region.CA_CENTRAL_1;\nimport static org.jclouds.aws.domain.Region.CN_NORTHWEST_1;\nimport static org.jclouds.aws.domain.Region.CN_NORTH_1;\nimport static org.jclouds.aws.domain.Region.EU_CENTRAL_1;\nimport static org.jclouds.aws.domain.Region.EU_CENTRAL_2;\nimport static org.jclouds.aws.domain.Region.EU_NORTH_1;\nimport static org.jclouds.aws.domain.Region.EU_SOUTH_1;\nimport static org.jclouds.aws.domain.Region.EU_SOUTH_2;\nimport static org.jclouds.aws.domain.Region.EU_WEST_1;\nimport static org.jclouds.aws.domain.Region.EU_WEST_2;\nimport static org.jclouds.aws.domain.Region.EU_WEST_3;\nimport static org.jclouds.aws.domain.Region.ME_SOUTH_1;\nimport static org.jclouds.aws.domain.Region.SA_EAST_1;\nimport static org.jclouds.aws.domain.Region.US_EAST_2;\nimport static org.jclouds.aws.domain.Region.US_STANDARD;\nimport static org.jclouds.aws.domain.Region.US_WEST_1;\nimport static org.jclouds.aws.domain.Region.US_WEST_2;\nimport static org.jclouds.location.reference.LocationConstants.ENDPOINT;\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_REGION;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.aws.domain.Region;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\n\nimport com.google.auto.service.AutoService;\n\n/**\n * Implementation of {@link org.jclouds.providers.ProviderMetadata} for Amazon's Simple Storage Service\n * (S3) provider.\n */\n@AutoService(ProviderMetadata.class)\npublic class AWSS3ProviderMetadata extends BaseProviderMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromProviderMetadata(this);\n   }\n   \n   public AWSS3ProviderMetadata() {\n      super(builder());\n   }\n\n   public AWSS3ProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = new Properties();\n      properties.putAll(Region.regionPropertiesS3());\n      properties.setProperty(PROPERTY_ENDPOINT, \"https://s3.amazonaws.com\");\n      properties.setProperty(PROPERTY_REGION + \".\" + US_STANDARD + \".\" + ENDPOINT, \"https://s3.amazonaws.com\");\n      properties.setProperty(PROPERTY_REGION + \".\" + US_EAST_2 + \".\" + ENDPOINT, \"https://s3-us-east-2.amazonaws.com\");\n      properties.setProperty(PROPERTY_REGION + \".\" + US_WEST_1 + \".\" + ENDPOINT, \"https://s3-us-west-1.amazonaws.com\");\n      properties.setProperty(PROPERTY_REGION + \".\" + US_WEST_2 + \".\" + ENDPOINT, \"https://s3-us-west-2.amazonaws.com\");\n      properties.setProperty(PROPERTY_REGION + \".\" + CA_CENTRAL_1 + \".\" + ENDPOINT, \"https://s3-ca-central-1.amazonaws.com\");\n      properties.setProperty(PROPERTY_REGION + \".\" + SA_EAST_1 + \".\" + ENDPOINT, \"https://s3-sa-east-1.amazonaws.com\");\n\n      properties.setProperty(PROPERTY_REGION + \".\" + EU_WEST_1 + \".\" + ENDPOINT, \"https://s3-eu-west-1.amazonaws.com\");\n      properties.setProperty(PROPERTY_REGION + \".\" + EU_WEST_2 + \".\" + ENDPOINT, \"https://s3-eu-west-2.amazonaws.com\");\n      properties.setProperty(PROPERTY_REGION + \".\" + EU_WEST_3 + \".\" + ENDPOINT, \"https://s3-eu-west-3.amazonaws.com\");\n      properties.setProperty(PROPERTY_REGION + \".\" + EU_SOUTH_1 + \".\" + ENDPOINT, \"https://s3-eu-south-1.amazonaws.com\");\n      properties.setProperty(PROPERTY_REGION + \".\" + EU_SOUTH_2 + \".\" + ENDPOINT, \"https://s3-eu-south-2.amazonaws.com\");\n      properties.setProperty(PROPERTY_REGION + \".\" + EU_CENTRAL_1 + \".\" + ENDPOINT, \"https://s3-eu-central-1.amazonaws.com\");\n      properties.setProperty(PROPERTY_REGION + \".\" + EU_CENTRAL_2 + \".\" + ENDPOINT, \"https://s3-eu-central-2.amazonaws.com\");\n      properties.setProperty(PROPERTY_REGION + \".\" + EU_NORTH_1 + \".\" + ENDPOINT, \"https://s3-eu-north-1.amazonaws.com\");\n\n      properties.setProperty(PROPERTY_REGION + \".\" + AP_SOUTHEAST_1 + \".\" + ENDPOINT,\n            \"https://s3-ap-southeast-1.amazonaws.com\");\n      properties.setProperty(PROPERTY_REGION + \".\" + AP_SOUTHEAST_2 + \".\" + ENDPOINT,\n            \"https://s3-ap-southeast-2.amazonaws.com\");\n      properties.setProperty(PROPERTY_REGION + \".\" + AP_SOUTH_1 + \".\" + ENDPOINT,\n          \"https://s3-ap-south-1.amazonaws.com\");\n      properties.setProperty(PROPERTY_REGION + \".\" + AP_NORTHEAST_1 + \".\" + ENDPOINT,\n            \"https://s3-ap-northeast-1.amazonaws.com\");\n      properties.setProperty(PROPERTY_REGION + \".\" + AP_NORTHEAST_2 + \".\" + ENDPOINT,\n          \"https://s3-ap-northeast-2.amazonaws.com\");\n      properties.setProperty(PROPERTY_REGION + \".\" + CN_NORTH_1 + \".\" + ENDPOINT,\n            \"https://s3.cn-north-1.amazonaws.com.cn\");\n      properties.setProperty(PROPERTY_REGION + \".\" + CN_NORTHWEST_1 + \".\" + ENDPOINT,\n            \"https://s3.cn-north-s3.cn-northwest-1.amazonaws.com.cn\");\n      properties.setProperty(PROPERTY_REGION + \".\" + ME_SOUTH_1 + \".\" + ENDPOINT, \"https://s3.me-south-1.amazonaws.com\");\n      return properties;\n   }\n   \n   public static class Builder extends BaseProviderMetadata.Builder {\n\n      protected Builder() {\n         id(\"aws-s3\")\n         .name(\"Amazon Simple Storage Service (S3)\")\n         .apiMetadata(new AWSS3ApiMetadata())\n         .homepage(URI.create(\"http://aws.amazon.com/s3\"))\n         .console(URI.create(\"https://console.aws.amazon.com/s3/home\"))\n         .linkedServices(\"aws-ec2\", \"aws-elb\", \"aws-cloudwatch\", \"aws-s3\", \"aws-simpledb\")\n               .iso3166Codes(\"US\", \"US-OH\", \"US-CA\", \"US-OR\", \"CA\", \"BR-SP\",\n                     \"IE\", \"GB-LND\", \"FR-IDF\", \"IT-MI\", \"ES\", \"DE-HE\", \"CH-ZH\", \"SE-AB\",\n                     \"SG\", \"AU-NSW\", \"IN-MH\", \"JP-13\", \"KR-11\",\n                     \"CN-BJ\", \"CN-NX\", \"BH\")\n         .defaultProperties(AWSS3ProviderMetadata.defaultProperties());\n      }\n\n      @Override\n      public AWSS3ProviderMetadata build() {\n         return new AWSS3ProviderMetadata(this);\n      }\n      \n      @Override\n      public Builder fromProviderMetadata(\n            ProviderMetadata in) {\n         super.fromProviderMetadata(in);\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "providers/aws-s3/src/main/java/org/jclouds/aws/s3/blobstore/AWSS3BlobRequestSignerV4.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.s3.blobstore;\n\nimport static org.jclouds.blobstore.util.BlobStoreUtils.cleanRequest;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.aws.s3.AWSS3Client;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.functions.BlobToHttpGetOptions;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.reflect.Invocation;\nimport org.jclouds.rest.internal.RestAnnotationProcessor;\nimport org.jclouds.s3.blobstore.S3BlobRequestSigner;\nimport org.jclouds.s3.blobstore.functions.BlobToObject;\nimport org.jclouds.s3.filters.RequestAuthorizeSignature;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.inject.Inject;\n\npublic class AWSS3BlobRequestSignerV4 extends S3BlobRequestSigner<AWSS3Client> {\n\n   private final RequestAuthorizeSignature authSigner;\n\n   @Inject\n   public AWSS3BlobRequestSignerV4(RestAnnotationProcessor processor, BlobToObject blobToObject,\n                                   BlobToHttpGetOptions blob2HttpGetOptions, Class<AWSS3Client> interfaceClass,\n                                   RequestAuthorizeSignature authSigner) throws SecurityException, NoSuchMethodException {\n      super(processor, blobToObject, blob2HttpGetOptions, interfaceClass, authSigner);\n      this.authSigner = authSigner;\n   }\n\n   @Override\n   public HttpRequest signGetBlob(String container, String name, long timeInSeconds) {\n      checkNotNull(container, \"container\");\n      checkNotNull(name, \"name\");\n      HttpRequest request = processor.apply(Invocation.create(getMethod, ImmutableList.<Object>of(container, name)));\n      request = authSigner.signForTemporaryAccess(request, timeInSeconds);\n      return cleanRequest(request);\n   }\n\n   @Override\n   public HttpRequest signPutBlob(String container, Blob blob, long timeInSeconds) {\n      checkNotNull(container, \"container\");\n      checkNotNull(blob, \"blob\");\n      HttpRequest request = processor.apply(Invocation.create(createMethod,\n         ImmutableList.<Object>of(container, blobToObject.apply(blob))));\n      request = authSigner.signForTemporaryAccess(request, timeInSeconds);\n      return cleanRequest(request);\n   }\n}\n"
  },
  {
    "path": "providers/aws-s3/src/main/java/org/jclouds/aws/s3/blobstore/AWSS3BlobStore.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.s3.blobstore;\n\nimport static org.jclouds.s3.domain.ObjectMetadata.StorageClass.REDUCED_REDUNDANCY;\n\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Provider;\n\nimport org.jclouds.aws.domain.Region;\nimport org.jclouds.aws.s3.AWSS3Client;\nimport org.jclouds.aws.s3.blobstore.options.AWSS3PutObjectOptions;\nimport org.jclouds.aws.s3.blobstore.options.AWSS3PutOptions;\nimport org.jclouds.blobstore.BlobStoreContext;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.ContainerAccess;\nimport org.jclouds.blobstore.domain.PageSet;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.functions.BlobToHttpGetOptions;\nimport org.jclouds.blobstore.options.CreateContainerOptions;\nimport org.jclouds.blobstore.options.PutOptions;\nimport org.jclouds.blobstore.strategy.internal.FetchBlobMetadata;\nimport org.jclouds.blobstore.util.BlobUtils;\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.domain.Location;\nimport org.jclouds.io.PayloadSlicer;\nimport org.jclouds.s3.blobstore.S3BlobStore;\nimport org.jclouds.s3.blobstore.functions.BlobToObject;\nimport org.jclouds.s3.blobstore.functions.BlobToObjectMetadata;\nimport org.jclouds.s3.blobstore.functions.BucketToResourceList;\nimport org.jclouds.s3.blobstore.functions.ContainerToBucketListOptions;\nimport org.jclouds.s3.blobstore.functions.ObjectToBlob;\nimport org.jclouds.s3.blobstore.functions.ObjectToBlobMetadata;\nimport org.jclouds.s3.domain.BucketMetadata;\nimport org.jclouds.s3.domain.CannedAccessPolicy;\nimport org.jclouds.s3.domain.ObjectMetadata;\nimport org.jclouds.s3.domain.PublicAccessBlockConfiguration;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\n\n/**\n * Provide AWS S3 specific extensions.\n */\npublic class AWSS3BlobStore extends S3BlobStore {\n\n   private final BlobToObject blob2Object;\n   private final AWSS3Client awsSync;\n\n   @Inject\n   AWSS3BlobStore(BlobStoreContext context, BlobUtils blobUtils, Supplier<Location> defaultLocation,\n            @Memoized Supplier<Set<? extends Location>> locations, PayloadSlicer slicer, AWSS3Client sync,\n            Function<Set<BucketMetadata>, PageSet<? extends StorageMetadata>> convertBucketsToStorageMetadata,\n            ContainerToBucketListOptions container2BucketListOptions, BucketToResourceList bucket2ResourceList,\n            ObjectToBlob object2Blob, BlobToHttpGetOptions blob2ObjectGetOptions, BlobToObject blob2Object,\n            BlobToObjectMetadata blob2ObjectMetadata,\n            ObjectToBlobMetadata object2BlobMd, Provider<FetchBlobMetadata> fetchBlobMetadataProvider) {\n      super(context, blobUtils, defaultLocation, locations, slicer, sync, convertBucketsToStorageMetadata,\n               container2BucketListOptions, bucket2ResourceList, object2Blob, blob2ObjectGetOptions, blob2Object,\n               blob2ObjectMetadata, object2BlobMd, fetchBlobMetadataProvider);\n      this.awsSync = sync;\n      this.blob2Object = blob2Object;\n   }\n\n   @Override\n   public String putBlob(String container, Blob blob, PutOptions options) {\n      if (options.isMultipart()) {\n         return putMultipartBlob(container, blob, options);\n      } else if ((options instanceof AWSS3PutOptions) &&\n         (((AWSS3PutOptions) options).getStorageClass() == REDUCED_REDUNDANCY)) {\n         return putBlobWithReducedRedundancy(container, blob);\n\n      } else {\n         return super.putBlob(container, blob, options);\n      }\n   }\n\n   private String putBlobWithReducedRedundancy(String container, Blob blob) {\n      AWSS3PutObjectOptions options = new AWSS3PutObjectOptions();\n      options.storageClass(ObjectMetadata.StorageClass.REDUCED_REDUNDANCY);\n      return getContext().unwrapApi(AWSS3Client.class).putObject(container, blob2Object.apply(blob), options);\n   }\n\n   @Override\n   public boolean createContainerInLocation(Location location, String container,\n                                            CreateContainerOptions options) {\n      if ((location == null || location.getId().equals(Region.US_STANDARD)) &&\n           containerExists(container)) {\n         // AWS-S3 returns the incorrect creation status when a container\n         // already exists in the us-standard (or default) region.  See\n         // JCLOUDS-334 for details.\n         return false;\n      }\n      // AWS blocks creating buckets with public-read canned ACL by default since 25 April 2023.  Instead create a bucket, override the block, and set the ACL.\n      if (options.isPublicRead()) {\n         boolean created = super.createContainerInLocation(location, container, new CreateContainerOptions());\n         if (!created) {\n            return false;\n         }\n         awsSync.putBucketOwnershipControls(container, \"ObjectWriter\");\n         awsSync.putPublicAccessBlock(container, PublicAccessBlockConfiguration.create(\n               /*blockPublicAcls=*/ false, /*ignorePublicAcls=*/ false, /*blockPublicPolicy=*/ false, /*restrictPublicBuckets=*/ false));\n         awsSync.updateBucketCannedACL(container, CannedAccessPolicy.PUBLIC_READ);\n         return true;\n      }\n      return super.createContainerInLocation(location, container, options);\n   }\n\n   @Override\n   public void setContainerAccess(String container, ContainerAccess access) {\n      CannedAccessPolicy acl = CannedAccessPolicy.PRIVATE;\n      if (access == ContainerAccess.PUBLIC_READ) {\n         acl = CannedAccessPolicy.PUBLIC_READ;\n         awsSync.putBucketOwnershipControls(container, \"ObjectWriter\");\n         awsSync.putPublicAccessBlock(container, PublicAccessBlockConfiguration.create(\n               /*blockPublicAcls=*/ false, /*ignorePublicAcls=*/ false, /*blockPublicPolicy=*/ false, /*restrictPublicBuckets=*/ false));\n      }\n      awsSync.updateBucketCannedACL(container, acl);\n   }\n}\n"
  },
  {
    "path": "providers/aws-s3/src/main/java/org/jclouds/aws/s3/blobstore/AWSS3BlobStoreContext.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.s3.blobstore;\n\nimport org.jclouds.aws.s3.blobstore.internal.AWSS3BlobStoreContextImpl;\nimport org.jclouds.s3.blobstore.S3BlobStoreContext;\n\nimport com.google.inject.ImplementedBy;\n\n@ImplementedBy(AWSS3BlobStoreContextImpl.class)\npublic interface AWSS3BlobStoreContext extends S3BlobStoreContext {\n\n   @Override\n   AWSS3BlobStore getBlobStore();\n}\n"
  },
  {
    "path": "providers/aws-s3/src/main/java/org/jclouds/aws/s3/blobstore/config/AWSS3BlobStoreContextModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.s3.blobstore.config;\n\nimport org.jclouds.aws.s3.blobstore.AWSS3BlobRequestSignerV4;\nimport org.jclouds.aws.s3.blobstore.AWSS3BlobStore;\nimport org.jclouds.blobstore.BlobRequestSigner;\nimport org.jclouds.s3.blobstore.S3BlobStore;\nimport org.jclouds.s3.blobstore.config.S3BlobStoreContextModule;\n\nimport com.google.inject.Scopes;\n\npublic class AWSS3BlobStoreContextModule extends S3BlobStoreContextModule {\n\n   @Override\n   protected void configure() {\n      super.configure();\n      bind(S3BlobStore.class).to(AWSS3BlobStore.class).in(Scopes.SINGLETON);\n   }\n\n   @Override\n   protected void bindRequestSigner() {\n      bind(BlobRequestSigner.class).to(AWSS3BlobRequestSignerV4.class);\n   }\n}\n"
  },
  {
    "path": "providers/aws-s3/src/main/java/org/jclouds/aws/s3/blobstore/internal/AWSS3BlobStoreContextImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.s3.blobstore.internal;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Context;\nimport org.jclouds.aws.s3.blobstore.AWSS3BlobStore;\nimport org.jclouds.aws.s3.blobstore.AWSS3BlobStoreContext;\nimport org.jclouds.blobstore.BlobRequestSigner;\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.attr.ConsistencyModel;\nimport org.jclouds.location.Provider;\nimport org.jclouds.rest.Utils;\nimport org.jclouds.s3.blobstore.internal.S3BlobStoreContextImpl;\n\nimport com.google.common.reflect.TypeToken;\n\n@Singleton\npublic class AWSS3BlobStoreContextImpl extends S3BlobStoreContextImpl implements AWSS3BlobStoreContext {\n\n   @Inject\n   public AWSS3BlobStoreContextImpl(@Provider Context backend, @Provider TypeToken<? extends Context> backendType,\n         Utils utils, ConsistencyModel consistencyModel, BlobStore blobStore, BlobRequestSigner blobRequestSigner) {\n      super(backend, backendType, utils, consistencyModel, blobStore, blobRequestSigner);\n   }\n\n   @Override\n   public AWSS3BlobStore getBlobStore() {\n      return AWSS3BlobStore.class.cast(super.getBlobStore());\n   }\n}\n"
  },
  {
    "path": "providers/aws-s3/src/main/java/org/jclouds/aws/s3/blobstore/options/AWSS3PutObjectOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.s3.blobstore.options;\n\nimport org.jclouds.s3.domain.CannedAccessPolicy;\nimport org.jclouds.s3.domain.ObjectMetadata;\nimport org.jclouds.s3.options.PutObjectOptions;\nimport org.jclouds.s3.reference.S3Headers;\n\n/**\n * Contains options supported in the AWS S3 REST API for the PUT object operation\n *\n * @see PutObjectOptions\n */\npublic class AWSS3PutObjectOptions extends PutObjectOptions {\n\n   public static class Builder {\n\n      /**\n       * @see AWSS3PutObjectOptions#storageClass\n       */\n      @Deprecated\n      public static AWSS3PutObjectOptions storageClass(ObjectMetadata.StorageClass storageClass) {\n         AWSS3PutObjectOptions options = new AWSS3PutObjectOptions();\n         return options.storageClass(storageClass);\n      }\n\n      /**\n       * @see AWSS3PutObjectOptions#withAcl\n       */\n      public static AWSS3PutObjectOptions withAcl(CannedAccessPolicy acl) {\n         AWSS3PutObjectOptions options = new AWSS3PutObjectOptions();\n         return options.withAcl(acl);\n      }\n   }\n\n   private ObjectMetadata.StorageClass storageClass = ObjectMetadata.StorageClass.STANDARD;\n\n   @Deprecated\n   public AWSS3PutObjectOptions storageClass(ObjectMetadata.StorageClass storageClass) {\n      this.storageClass = storageClass;\n      if (storageClass != ObjectMetadata.StorageClass.STANDARD) {\n         this.replaceHeader(S3Headers.STORAGE_CLASS, this.storageClass.toString());\n      }\n      return this;\n   }\n\n   @Deprecated\n   public ObjectMetadata.StorageClass getStorageClass() {\n      return storageClass;\n   }\n\n   @Override\n   public AWSS3PutObjectOptions withAcl(CannedAccessPolicy acl) {\n      return (AWSS3PutObjectOptions) super.withAcl(acl);\n   }\n}\n"
  },
  {
    "path": "providers/aws-s3/src/main/java/org/jclouds/aws/s3/blobstore/options/AWSS3PutOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.s3.blobstore.options;\n\nimport org.jclouds.blobstore.options.PutOptions;\nimport org.jclouds.s3.domain.ObjectMetadata;\n\n/**\n * Contains AWS-S3 specific options supported in the put blob operation\n */\npublic class AWSS3PutOptions extends PutOptions {\n\n   public static class Builder {\n\n      /**\n       * @see AWSS3PutOptions#multipart()\n       */\n      public static AWSS3PutOptions multipart() {\n         AWSS3PutOptions options = new AWSS3PutOptions();\n         return (AWSS3PutOptions) options.multipart();\n      }\n\n      /**\n       * @see AWSS3PutOptions#storageClass\n       */\n      public static AWSS3PutOptions storageClass(ObjectMetadata.StorageClass storageClass) {\n         AWSS3PutOptions options = new AWSS3PutOptions();\n         return options.storageClass(storageClass);\n      }\n   }\n\n   private ObjectMetadata.StorageClass storageClass;\n\n   public AWSS3PutOptions() {\n      storageClass = ObjectMetadata.StorageClass.STANDARD;\n   }\n\n   public AWSS3PutOptions(boolean multipart, ObjectMetadata.StorageClass storageClass) {\n      super(multipart);\n      this.storageClass = storageClass;\n   }\n\n   public AWSS3PutOptions storageClass(ObjectMetadata.StorageClass storageClass) {\n      this.storageClass = storageClass;\n      return this;\n   }\n\n   public ObjectMetadata.StorageClass getStorageClass() {\n      return storageClass;\n   }\n\n   @Override\n   public AWSS3PutOptions clone() {\n      return new AWSS3PutOptions(isMultipart(), storageClass);\n   }\n\n   @Override\n   public String toString() {\n      return \"[multipart=\" + isMultipart() +\n         \" storageClass=\" + storageClass + \"]\";\n   }\n}\n"
  },
  {
    "path": "providers/aws-s3/src/main/java/org/jclouds/aws/s3/config/AWSS3HttpApiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.s3.config;\n\nimport static org.jclouds.aws.domain.Region.US_STANDARD;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.aws.s3.AWSS3Client;\nimport org.jclouds.aws.s3.filters.AWSRequestAuthorizeSignatureV4;\nimport org.jclouds.aws.s3.predicates.validators.AWSS3BucketNameValidator;\nimport org.jclouds.location.Region;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.s3.S3Client;\nimport org.jclouds.s3.config.S3HttpApiModule;\nimport org.jclouds.s3.filters.RequestAuthorizeSignature;\nimport org.jclouds.s3.predicates.validators.BucketNameValidator;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.inject.Injector;\nimport com.google.inject.Provides;\n\n/**\n * Configures the S3 connection.\n */\n@ConfiguresHttpApi\npublic class AWSS3HttpApiModule extends S3HttpApiModule<AWSS3Client> {\n   \n   public AWSS3HttpApiModule() {\n      super(AWSS3Client.class);\n   }\n   \n   @Override\n   protected Supplier<String> defaultRegionForBucket(@Region Supplier<String> defaultRegion) {\n      return Suppliers.ofInstance(US_STANDARD);\n   }\n   \n   @Override\n   protected void configure() {\n      bind(BucketNameValidator.class).to(AWSS3BucketNameValidator.class);\n      super.configure();\n   }\n\n   @Override\n   protected RequestAuthorizeSignature providesRequestAuthorizeSignature(Injector i, int version) {\n      return i.getInstance(AWSRequestAuthorizeSignatureV4.class);\n   }\n\n   @Singleton\n   @Provides\n   final S3Client provide(AWSS3Client in) {\n      return in;\n   }\n}\n"
  },
  {
    "path": "providers/aws-s3/src/main/java/org/jclouds/aws/s3/filters/AWSRequestAuthorizeSignature.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.s3.filters;\n\nimport static org.jclouds.aws.reference.AWSConstants.PROPERTY_AUTH_TAG;\nimport static org.jclouds.aws.reference.AWSConstants.PROPERTY_HEADER_TAG;\nimport static org.jclouds.http.utils.Queries.queryParser;\nimport static org.jclouds.s3.reference.S3Constants.PROPERTY_S3_SERVICE_PATH;\nimport static org.jclouds.s3.reference.S3Constants.PROPERTY_S3_VIRTUAL_HOST_BUCKETS;\nimport static org.jclouds.s3.reference.S3Constants.TEMPORARY_SIGNATURE_PARAM;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Provider;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.crypto.Crypto;\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpUtils;\nimport org.jclouds.http.internal.SignatureWire;\nimport org.jclouds.s3.filters.RequestAuthorizeSignatureV2;\n\nimport com.google.common.base.Supplier;\n\n/** Signs the AWS S3 request, supporting temporary signatures. */\n@Singleton\npublic class AWSRequestAuthorizeSignature extends RequestAuthorizeSignatureV2 {\n\n   @Inject\n   public AWSRequestAuthorizeSignature(SignatureWire signatureWire, @Named(PROPERTY_AUTH_TAG) String authTag,\n            @Named(PROPERTY_S3_VIRTUAL_HOST_BUCKETS) boolean isVhostStyle,\n            @Named(PROPERTY_S3_SERVICE_PATH) String servicePath, @Named(PROPERTY_HEADER_TAG) String headerTag,\n            @org.jclouds.location.Provider Supplier<Credentials> creds,\n            @TimeStamp Provider<String> timeStampProvider, Crypto crypto, HttpUtils utils,\n            DateService dateService) {\n      super(signatureWire, authTag, isVhostStyle, servicePath, headerTag, creds, timeStampProvider, crypto, \n             utils, dateService);\n   }\n\n   @Override\n   protected HttpRequest replaceAuthorizationHeader(HttpRequest request, String signature) {\n      /* \n       * Only add the Authorization header if the query string doesn't already contain\n       * the 'Signature' parameter, otherwise S3 will fail the request complaining about\n       * duplicate authentication methods. The 'Signature' parameter will be added for signed URLs\n       * with expiration.\n       */\n      if (queryParser().apply(request.getEndpoint().getQuery()).containsKey(TEMPORARY_SIGNATURE_PARAM)) {\n         return request;\n      }\n      return super.replaceAuthorizationHeader(request, signature);\n   }\n}\n"
  },
  {
    "path": "providers/aws-s3/src/main/java/org/jclouds/aws/s3/filters/AWSRequestAuthorizeSignatureV4.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.s3.filters;\n\nimport static org.jclouds.http.utils.Queries.queryParser;\nimport static org.jclouds.s3.filters.AwsSignatureV4Constants.AMZ_SIGNATURE_PARAM;\nimport static org.jclouds.s3.reference.S3Constants.TEMPORARY_SIGNATURE_PARAM;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport com.google.common.collect.Multimap;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.s3.filters.Aws4SignerForAuthorizationHeader;\nimport org.jclouds.s3.filters.Aws4SignerForChunkedUpload;\nimport org.jclouds.s3.filters.Aws4SignerForQueryString;\nimport org.jclouds.s3.filters.RequestAuthorizeSignatureV4;\n\n/**\n * Signs the AWS S3 request, supporting temporary signatures.\n */\n@Singleton\npublic class AWSRequestAuthorizeSignatureV4 extends RequestAuthorizeSignatureV4 {\n\n   @Inject\n   public AWSRequestAuthorizeSignatureV4(Aws4SignerForAuthorizationHeader signerForAuthorizationHeader,\n         Aws4SignerForChunkedUpload signerForChunkedUpload,\n         Aws4SignerForQueryString signerForQueryString) {\n      super(signerForAuthorizationHeader, signerForChunkedUpload, signerForQueryString);\n   }\n\n   @Override\n   protected HttpRequest signForAuthorizationHeader(HttpRequest request) {\n      /*\n      * Only add the Authorization header if the query string doesn't already contain\n      * the 'X-Amz-Signature' parameter, otherwise S3 will fail the request complaining about\n      * duplicate authentication methods. The 'Signature' parameter will be added for signed URLs\n      * with expiration.\n      */\n\n      // Do not replace URI.getRawQuery() with URI.getQuery() see: JCLOUDS-1631\n      Multimap<String, String> queryMap = queryParser().apply(request.getEndpoint().getRawQuery());\n      if (queryMap.containsKey(AMZ_SIGNATURE_PARAM) || queryMap.containsKey(TEMPORARY_SIGNATURE_PARAM)) {\n         return request;\n      }\n      return super.signForAuthorizationHeader(request);\n   }\n}\n"
  },
  {
    "path": "providers/aws-s3/src/main/java/org/jclouds/aws/s3/filters/package-info.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** This package contains HttpRequestFilters needed to operate the REST api. */\npackage org.jclouds.aws.s3.filters;\n"
  },
  {
    "path": "providers/aws-s3/src/main/java/org/jclouds/aws/s3/predicates/validators/AWSS3BucketNameValidator.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.s3.predicates.validators;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.s3.predicates.validators.BucketNameValidator;\n\nimport com.google.inject.Singleton;\n\n/**\n * Validates name for AWS S3 buckets. The complete requirements are listed at:\n * http://docs.amazonwebservices.com/AmazonS3/latest/index.html?BucketRestrictions.html\n * \n * @see org.jclouds.rest.InputParamValidator\n * @see org.jclouds.predicates.Validator\n */\n@Singleton\npublic class AWSS3BucketNameValidator extends BucketNameValidator {\n\n   @Inject\n   AWSS3BucketNameValidator() {\n      super();\n   }\n\n   public void validate(String containerName) {\n      // AWS S3 allows for upper case characters in bucket names (US Standard region only) and behind the scenes will\n      // use the lower-cased version of the bucket name for its DNS name.  So for AWS S3, we will lowercase the bucket\n      // name prior to validation.  For all other regions than US Standard region, we will let AWS throw handle the\n      // error.\n      //\n      // http://code.google.com/p/jclouds/issues/detail?id=992\n      //\n      // It would be nice to scope this more lax validator to only the us regions, since based on AWS S3 documentation,\n      // this is only necessary for the us regions.\n      super.validate(containerName.toLowerCase());\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-s3/src/test/java/org/jclouds/aws/s3/AWSS3ClientExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.s3;\n\nimport static org.jclouds.aws.s3.blobstore.options.AWSS3PutObjectOptions.Builder.storageClass;\n\nimport org.jclouds.aws.s3.internal.BaseAWSS3ClientExpectTest;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.BlobBuilder;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.s3.blobstore.functions.BlobToObject;\nimport org.jclouds.s3.domain.ObjectMetadata.StorageClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Functions;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.inject.Injector;\n\n@Test\npublic class AWSS3ClientExpectTest extends BaseAWSS3ClientExpectTest {\n\n   HttpRequest bucketLocationRequest = HttpRequest.builder()\n                                                  .method(\"GET\")\n                                                  .endpoint(\"https://s3.amazonaws.com/test?location\")\n                                                  .addHeader(\"Date\", CONSTANT_DATE)\n                                                  .addHeader(\"Authorization\", \"AWS identity:sOZnJSLuwnMVn7CiEKcVmpFI0rU=\").build();\n\n   HttpResponse bucketLocationResponse = HttpResponse.builder()\n                                                     .statusCode(200)\n                                                     .payload(payloadFromStringWithContentType(\"<LocationConstraint xmlns=\\\"http://s3.amazonaws.com/doc/2006-03-01/\\\">eu-west-1</LocationConstraint>\", \"application/xml\"))\n                                                     .addHeader(\"x-amz-id-2\", \"BtioT9wIK04YkE2DPgWUrQFiAbjwJVP8cLyfOkJ1FHMbn2hVjBZvkMMuXPDHfGVw\")\n                                                     .addHeader(\"x-amz-request-id\", \"51BF4F45D49B1B34\")\n                                                     .addHeader(\"Date\", CONSTANT_DATE)\n                                                     .addHeader(\"Server\", \"AmazonS3\").build();\n\n   @Test\n   public void testPutWithReducedRedundancy() {\n      Injector injector = createInjector(Functions.forMap(ImmutableMap.<HttpRequest, HttpResponse>of()), createModule(), setupProperties());\n\n      Blob blob = injector.getInstance(BlobBuilder.class).name(\"test\").payload(\"content\").build();\n      BlobToObject blobToObject = injector.getInstance(BlobToObject.class);\n\n      AWSS3Client client = requestsSendResponses(bucketLocationRequest, bucketLocationResponse,\n         HttpRequest.builder()\n                    .method(\"PUT\")\n                    .endpoint(\"https://test.s3-eu-west-1.amazonaws.com/test\")\n                    .addHeader(\"Expect\", \"100-continue\")\n                    .addHeader(\"x-amz-storage-class\", \"REDUCED_REDUNDANCY\")\n                    .addHeader(\"Host\", \"test.s3-eu-west-1.amazonaws.com\")\n                    .addHeader(\"Date\", CONSTANT_DATE)\n                    .addHeader(\"Authorization\", \"AWS identity:1mJrW85/mqZpYTFIK5Ebtt2MM6E=\")\n                    .payload(\"content\").build(),\n         HttpResponse.builder()\n                     .statusCode(200)\n                     .addHeader(\"x-amz-id-2\", \"w0rL+9fALQiCOToesVQefs8WalIgn+ZhMD7hHMKYud/xv7MyKkAWQOtFNEfK97Ri\")\n                     .addHeader(\"x-amz-request-id\", \"7A84C3CD4437A4C0\")\n                     .addHeader(\"Date\", CONSTANT_DATE)\n                     .addHeader(\"ETag\", \"437b930db84b8079c2dd804a71936b5f\")\n                     .addHeader(\"Server\", \"AmazonS3\").build()\n      );\n\n      client.putObject(\"test\", blobToObject.apply(blob),\n         storageClass(StorageClass.REDUCED_REDUNDANCY));\n   }\n}\n"
  },
  {
    "path": "providers/aws-s3/src/test/java/org/jclouds/aws/s3/AWSS3ClientLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.s3;\n\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.jclouds.aws.s3.blobstore.options.AWSS3PutObjectOptions.Builder.storageClass;\nimport static org.jclouds.s3.options.ListBucketOptions.Builder.withPrefix;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.fail;\n\nimport com.google.common.collect.Iterables;\nimport org.jclouds.aws.AWSResponseException;\nimport org.jclouds.aws.domain.Region;\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.domain.Location;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.location.predicates.LocationPredicates;\nimport org.jclouds.rest.HttpClient;\nimport org.jclouds.s3.S3ClientLiveTest;\nimport org.jclouds.s3.domain.ListBucketResponse;\nimport org.jclouds.s3.domain.ObjectMetadata;\nimport org.jclouds.s3.domain.ObjectMetadata.StorageClass;\nimport org.jclouds.s3.domain.PublicAccessBlockConfiguration;\nimport org.jclouds.s3.domain.S3Object;\nimport org.testng.ITestContext;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code S3Client}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"AWSS3ClientLiveTest\")\npublic class AWSS3ClientLiveTest extends S3ClientLiveTest {\n   public AWSS3ClientLiveTest() {\n      provider = \"aws-s3\";\n   }\n\n   @Override\n   public AWSS3Client getApi() {\n      return view.unwrapApi(AWSS3Client.class);\n   }\n\n   @Override\n   protected void allowPublicReadable(String containerName) {\n      getApi().putBucketOwnershipControls(containerName, \"ObjectWriter\");\n      getApi().putPublicAccessBlock(containerName, PublicAccessBlockConfiguration.create(\n            /*blockPublicAcls=*/ false, /*ignorePublicAcls=*/ false, /*blockPublicPolicy=*/ false, /*restrictPublicBuckets=*/ false));\n   }\n\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   @Override\n   public void setUpResourcesOnThisThread(ITestContext testContext) throws Exception {\n      super.setUpResourcesOnThisThread(testContext);\n   }\n\n   public void testPutWithStorageClass() throws Exception {\n      String containerName = getContainerName();\n      AWSS3Client s3Client = getApi();\n      try {\n         for (StorageClass storageClass : StorageClass.values()) {\n            String blobName = \"test-\" + storageClass;\n            BlobStore blobStore = view.getBlobStore();\n            blobStore.createContainerInLocation(null, containerName);\n\n            S3Object object = s3Client.newS3Object();\n            object.getMetadata().setKey(blobName);\n            object.setPayload(\"something\");\n            s3Client.putObject(containerName, object, storageClass(storageClass));\n\n            ListBucketResponse response = s3Client.listBucket(containerName, withPrefix(blobName));\n\n            ObjectMetadata metadata = response.iterator().next();\n            assertThat(metadata.getStorageClass()).isEqualTo(storageClass);\n         }\n\n      } finally {\n         returnContainer(containerName);\n      }\n   }\n\n   /**\n    * http://code.google.com/p/jclouds/issues/detail?id=992\n    */\n   public void testUseBucketWithUpperCaseName() throws Exception {\n      String bucketName = CONTAINER_PREFIX + \"-TestBucket\";\n      BlobStore store = view.getBlobStore();\n\n       // As of March 1 2018, bucket names must be DNS compliant in all regions\n\n      try {\n         store.createContainerInLocation(null, bucketName);\n         fail(\"Should have failed because mixed-case bucket names are invalid.\");\n      } catch (AWSResponseException e) {\n         assertEquals(\"InvalidBucketName\", e.getError().getCode());\n      }\n   }\n\n   public void testDirectoryEndingWithSlash() throws InterruptedException {\n\t   String containerName = getContainerName();\n\t   try {\n\t\t   BlobStore blobStore = view.getBlobStore();\n\t\t   blobStore.createDirectory(containerName, \"someDir\");\n\n\t\t   // According to the S3 documentation, a directory is nothing but a blob\n\t\t   // whose name ends with a '/'. So let's try to remove the blob we just\n\t\t   // created.\n\t\t   blobStore.removeBlob(containerName, \"someDir/\");\n\n\t\t   // The directory \"someDir\" shouldn't exist since we removed it. If this\n\t\t   // test succeeds, it confirms that a directory (or folder) is nothing\n\t\t   // but a blob with a name ending in '/'.\n\t\t   assertEquals(blobStore.directoryExists(containerName, \"someDir\"), false);\n\t   } finally {\n\t\t   returnContainer(containerName);\n\t   }\n   }\n\n   /**\n    * Test signed get/put operations using signature v4. This is done by explicitly\n    * using the \"eu-central-1\" region which only support signature v4.\n    */\n   public void testV4SignatureOps() throws InterruptedException {\n       String containerName = getScratchContainerName() + \"eu\";\n\t   try {\n           BlobStore blobStore = view.getBlobStore();\n           Location location = Iterables.tryFind(blobStore.listAssignableLocations(),\n               LocationPredicates.idEquals(Region.EU_CENTRAL_1)).orNull();\n           assertNotNull(location);\n           blobStore.createContainerInLocation(location, containerName);\n\n           final HttpClient client = view.utils().http();\n           String blobName = \"test-blob\";\n           Blob blob = blobStore.blobBuilder(blobName).payload(\"something\").build();\n\n           // Signed put, no timeout.\n           HttpRequest request = view.getSigner().signPutBlob(containerName, blob);\n           assertNotNull(request);\n           HttpResponse response = client.invoke(request);\n           assertEquals(response.getStatusCode(), 200);\n\n           // Signed get, no timeout.\n           request = view.getSigner().signGetBlob(containerName, blobName);\n           assertNotNull(request);\n           response = client.invoke(request);\n           assertEquals(response.getStatusCode(), 200);\n\n           blobStore.removeBlob(containerName, blobName);\n\n           // Signed put with timeout.\n           request = view.getSigner().signPutBlob(containerName, blob, /*seconds=*/ 60);\n           assertNotNull(request);\n           response = client.invoke(request);\n           assertEquals(response.getStatusCode(), 200);\n\n           // Signed get with timeout.\n           request = view.getSigner().signGetBlob(containerName, blobName, /*seconds=*/ 60);\n           assertNotNull(request);\n           response = client.invoke(request);\n           assertEquals(response.getStatusCode(), 200);\n\n           // Cleanup the container.\n           blobStore.removeBlob(containerName, blobName);\n       } finally {\n           destroyContainer(containerName);\n       }\n   }\n}\n"
  },
  {
    "path": "providers/aws-s3/src/test/java/org/jclouds/aws/s3/AWSS3ClientTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.s3;\n\nimport static org.jclouds.reflect.Reflection2.method;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.util.Set;\n\nimport org.jclouds.aws.s3.config.AWSS3HttpApiModule;\nimport org.jclouds.aws.s3.filters.AWSRequestAuthorizeSignature;\nimport org.jclouds.blobstore.binders.BindBlobToMultipartFormTest;\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.functions.ParseETagHeader;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.http.functions.ReturnTrueIf2xx;\nimport org.jclouds.location.Region;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.jclouds.s3.S3Client;\nimport org.jclouds.s3.S3ClientTest;\nimport org.jclouds.s3.domain.S3Object;\nimport org.jclouds.s3.fallbacks.FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists;\nimport org.jclouds.s3.filters.RequestAuthorizeSignature;\nimport org.jclouds.s3.options.CopyObjectOptions;\nimport org.jclouds.s3.options.PutBucketOptions;\nimport org.jclouds.s3.options.PutObjectOptions;\nimport org.jclouds.s3.xml.LocationConstraintHandler;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Functions;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Lists;\nimport com.google.common.reflect.Invokable;\nimport com.google.inject.Injector;\nimport com.google.inject.Module;\n\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"AWSS3ClientTest\")\npublic class AWSS3ClientTest extends S3ClientTest<AWSS3Client> {\n\n   @Override\n   protected void checkFilters(HttpRequest request) {\n      assertEquals(request.getFilters().size(), 1);\n      assertEquals(request.getFilters().get(0).getClass(), AWSRequestAuthorizeSignature.class);\n   }\n\n   @Override\n   public void testCopyObjectInvalidName() throws ArrayIndexOutOfBoundsException, SecurityException,\n                                                  IllegalArgumentException, NoSuchMethodException, IOException {\n      // For AWS S3, S3ClientTest#testCopyObjectInvalidName() will not throw an exception\n      Invokable<?, ?> method = method(AWSS3Client.class, \"copyObject\", String.class, String.class, String.class,\n                                                    String.class,\n                                                    CopyObjectOptions[].class);\n      processor.createRequest(method, ImmutableList.<Object> of(\"sourceBucket\", \"sourceObject\", \"destinationbucket\", \"destinationObject\"));\n   }\n\n   public void testGetBucketLocationEUIsStillDefault() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AWSS3Client.class, \"getBucketLocation\", String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"bucket-eu-west-1\"));\n\n      assertRequestLineEquals(request, \"GET https://s3.amazonaws.com/bucket-eu-west-1?location HTTP/1.1\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, LocationConstraintHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   @Override\n   public void testPutObject() throws ArrayIndexOutOfBoundsException, SecurityException, IllegalArgumentException,\n         NoSuchMethodException, IOException {\n\n      Invokable<?, ?> method = method(AWSS3Client.class, \"putObject\", String.class, S3Object.class,\n            PutObjectOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"bucket\",\n            blobToS3Object.apply(BindBlobToMultipartFormTest.TEST_BLOB)));\n\n      assertRequestLineEquals(request, \"PUT https://bucket.\" + url + \"/hello HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Expect: 100-continue\\nHost: bucket.\" + url + \"\\n\");\n      assertPayloadEquals(request, \"hello\", \"text/plain\", false);\n\n      assertResponseParserClassEquals(method, request, ParseETagHeader.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   @Override\n   public void testGetBucketLocation() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AWSS3Client.class, \"getBucketLocation\", String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"bucket\"));\n\n      assertRequestLineEquals(request, \"GET https://s3.amazonaws.com/bucket?location HTTP/1.1\");\n      assertPayloadEquals(request, null, null, false);\n\n      request = (GeneratedHttpRequest) filter.filter(request);\n\n      assertRequestLineEquals(request, \"GET https://s3.amazonaws.com/bucket?location HTTP/1.1\");\n      assertNonPayloadHeadersEqual(\n            request,\n            \"Authorization: AWS identity:f1Pt8/8Yr/HZahuc6KPI1B2+Mw4=\\nDate: 2009-11-08T15:54:08.897Z\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, LocationConstraintHandler.class);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   @Override\n   public void testPutBucketDefault() throws ArrayIndexOutOfBoundsException, SecurityException,\n         IllegalArgumentException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AWSS3Client.class, \"putBucketInRegion\", String.class, String.class,\n            PutBucketOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, Lists.<Object> newArrayList((String) null, \"bucket\"));\n\n      assertRequestLineEquals(request, \"PUT https://bucket.s3.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: bucket.s3.amazonaws.com\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ReturnTrueIf2xx.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists.class);\n\n      checkFilters(request);\n   }\n\n   public void testPutBucketEu() throws ArrayIndexOutOfBoundsException, SecurityException, IllegalArgumentException,\n         NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AWSS3Client.class, \"putBucketInRegion\", String.class, String.class,\n            PutBucketOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"EU\", \"bucket\"));\n\n      assertRequestLineEquals(request, \"PUT https://bucket.s3.amazonaws.com/ HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Host: bucket.s3.amazonaws.com\\n\");\n      assertPayloadEquals(request,\n            \"<CreateBucketConfiguration><LocationConstraint>EU</LocationConstraint></CreateBucketConfiguration>\",\n            \"text/xml\", false);\n\n      assertResponseParserClassEquals(method, request, ReturnTrueIf2xx.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists.class);\n\n      checkFilters(request);\n   }\n\n   @ConfiguresHttpApi\n   private static final class TestAWSS3HttpApiModule extends AWSS3HttpApiModule {\n\n      @Override\n      protected CacheLoader<String, Optional<String>> bucketToRegion(@Region Supplier<Set<String>> regionSupplier,\n               final S3Client client) {\n         return CacheLoader.<String, Optional<String>> from(Functions.forMap(ImmutableMap\n                           .<String, Optional<String>> builder()\n                           .put(\"bucket\", Optional.<String> absent())\n                           .put(\"destinationbucket\", Optional.<String> absent())\n                           .put(\"bucket-us-standard\", Optional.of(\"us-standard\"))\n                           .put(\"bucket-us-west-1\", Optional.of(\"us-west-1\"))\n                           .put(\"bucket-us-west-2\", Optional.of(\"us-west-2\"))\n                           .put(\"bucket-eu-west-1\", Optional.of(\"eu-west-1\"))\n                           .put(\"bucket-sa-east-1\", Optional.of(\"sa-east-1\"))\n                           .put(\"bucket-ap-southeast-1\", Optional.of(\"ap-southeast-1\"))\n                           .put(\"bucket-ap-northeast-1\", Optional.of(\"ap-northeast-1\"))\n                           .build()));\n      }\n\n      @Override\n      protected String provideTimeStamp(@TimeStamp Supplier<String> cache) {\n         return \"2009-11-08T15:54:08.897Z\";\n      }\n\n      // subclass expects v2 signatures\n      @Override\n      protected RequestAuthorizeSignature providesRequestAuthorizeSignature(Injector i, int version) {\n         return i.getInstance(AWSRequestAuthorizeSignature.class);\n      }\n   }\n\n   @Override\n   protected Module createModule() {\n      return new TestAWSS3HttpApiModule();\n   }\n   \n   @Override\n   public AWSS3ProviderMetadata createProviderMetadata() {\n      return new AWSS3ProviderMetadata();\n   }\n}\n"
  },
  {
    "path": "providers/aws-s3/src/test/java/org/jclouds/aws/s3/AWSS3ProviderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.s3;\n\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.testng.annotations.Test;\n\n/**\n * The AWSS3ProviderTest tests the {@link org.jclouds.aws.s3.AWSS3ProviderMetadata} class.\n */\n@Test(groups = \"unit\", testName = \"AWSS3ProviderTest\")\npublic class AWSS3ProviderTest extends BaseProviderMetadataTest {\n\n   public AWSS3ProviderTest() {\n      super(new AWSS3ProviderMetadata(), new AWSS3ApiMetadata());\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-s3/src/test/java/org/jclouds/aws/s3/blobstore/AWSS3BlobSignerExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.s3.blobstore;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Date;\nimport java.util.Map;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.Constants;\nimport org.jclouds.aws.s3.config.AWSS3HttpApiModule;\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.s3.blobstore.S3BlobSignerExpectTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Splitter;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.inject.Module;\n\n@Test(groups = \"unit\", testName = \"AWSS3BlobSignerExpectTest\")\npublic class AWSS3BlobSignerExpectTest extends S3BlobSignerExpectTest {\n   private static final String DATE = \"Thu, 05 Jun 2008 16:38:19 GMT\";\n   private static final String HOST = \"container.s3.amazonaws.com\";\n\n   public AWSS3BlobSignerExpectTest() {\n      provider = \"aws-s3\";\n   }\n\n   @Override\n   protected HttpRequest getBlob() {\n      return HttpRequest.builder().method(\"GET\")\n            .endpoint(\"https://container.s3.amazonaws.com/name\")\n            .addQueryParam(\"X-Amz-Algorithm\", \"AWS4-HMAC-SHA256\")\n            .addQueryParam(\"X-Amz-Credential\", \"identity/20080605/us-east-1/s3/aws4_request\")\n            .addQueryParam(\"X-Amz-Date\", \"20080605T163819Z\")\n            .addQueryParam(\"X-Amz-Expires\", \"900\")\n            .addQueryParam(\"X-Amz-SignedHeaders\", \"host\")\n            .addQueryParam(\"X-Amz-Signature\", \"1aa13b18ef9c4a9a98db7539e9eeb2c63afadbab649e14e28d5b765dfd96c32b\")\n            .addHeader(\"Host\", HOST)\n            .build();\n   }\n\n   @Override\n   protected HttpRequest getBlobWithTime() {\n      return HttpRequest.builder().method(\"GET\")\n            .endpoint(\"https://container.s3.amazonaws.com/name\")\n            .addQueryParam(\"Expires\", \"1212683902\")\n            .addQueryParam(\"AWSAccessKeyId\", \"identity\")\n            .addQueryParam(\"Signature\", \"Y4Ac4sZfBemGZmgfG78F7IX+IFg=\")\n            .addHeader(\"Host\", \"container.s3.amazonaws.com\")\n            .addHeader(\"Date\", DATE).build();\n   }\n\n   @Override\n   protected HttpRequest getBlobWithOptions() {\n      return HttpRequest.builder().method(\"GET\")\n            .endpoint(\"https://container.s3.amazonaws.com/name\")\n            .addHeader(\"Host\", HOST)\n            .addHeader(\"Range\", \"bytes=0-1\")\n            .addHeader(\"x-amz-content-sha256\", \"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\")\n            .addHeader(\"X-Amz-Date\", \"20080605T163819Z\")\n            .addHeader(\"Authorization\", \"AWS4-HMAC-SHA256 Credential=identity/20080605/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=8f6a70bf43f31c92a67095510b080f574154df8a5ccb988ec8a6cbcce03dd5b8\")\n            .build();\n   }\n\n   private void compareRequestComponents(final HttpRequest request, final HttpRequest compare) {\n      assertEquals(request.getMethod(), compare.getMethod());\n      String query = request.getEndpoint().toString().split(\"\\\\?\")[1];\n      final Map<String, String> params = Splitter.on('&').trimResults().withKeyValueSeparator(\"=\").split(query);\n      assertEquals(params.get(\"X-Amz-Algorithm\"), \"AWS4-HMAC-SHA256\");\n      assertEquals(params.get(\"X-Amz-Expires\"), \"900\");\n      assertEquals(params.get(\"X-Amz-SignedHeaders\"), \"host\");\n   }\n\n   @Override\n   @Test\n   public void testSignGetBlobWithTime() {\n      BlobStore getBlobWithTime = requestsSendResponses(init());\n      HttpRequest compare = getBlobWithTime();\n      HttpRequest request = getBlobWithTime.getContext().getSigner().signGetBlob(container, name, 900L /* seconds */);\n      compareRequestComponents(request, compare);\n   }\n\n   @Override\n   protected HttpRequest putBlob() {\n      return HttpRequest.builder().method(\"PUT\")\n            .endpoint(\"https://container.s3.amazonaws.com/name\")\n            .addHeader(\"Host\", HOST)\n            .addHeader(\"Expect\", \"100-continue\")\n            .addHeader(\"Date\", \"Thu, 05 Jun 2008 16:38:19 GMT\")\n            .addHeader(\"Authorization\", \"AWS identity:zM2oT+71KcoOSxv1SU5L12UXnT8=\").build();\n   }\n\n   @Override\n   protected HttpRequest putBlobWithTime() {\n      return HttpRequest.builder().method(\"PUT\")\n            .endpoint(\"https://container.s3.amazonaws.com/name\")\n            .addQueryParam(\"Expires\", \"1212683902\")\n            .addQueryParam(\"AWSAccessKeyId\", \"identity\")\n            .addQueryParam(\"Signature\", \"genkB2vLxe3AWV/bPvRTMqQts7E=\")\n            .addHeader(\"Expect\", \"100-continue\")\n            .addHeader(\"Host\", \"container.s3.amazonaws.com\")\n            .addHeader(\"Date\", DATE)\n            .build();\n   }\n\n   @Override\n   protected HttpRequest removeBlob() {\n      return HttpRequest.builder().method(\"DELETE\")\n            .endpoint(\"https://container.s3.amazonaws.com/name\")\n            .addHeader(\"x-amz-content-sha256\", \"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\")\n            .addHeader(\"X-Amz-Date\", \"20080605T163819Z\")\n            .addHeader(\"Authorization\", \"AWS4-HMAC-SHA256 Credential=identity/20080605/us-east-1/s3/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=b068a3b2a76f06bf1d73b907243602f43962f5572ea1e588ed193c8c656118fe\")\n            .addHeader(\"Host\", HOST)\n            .build();\n   }\n\n   @Override\n   @Test\n   public void testSignPutBlob() throws Exception {\n      BlobStore signPutBloblWithTime = requestsSendResponses(init());\n      Blob blob = signPutBloblWithTime.blobBuilder(name).payload(text).contentType(\"text/plain\").build();\n      HttpRequest compare = putBlobWithTime();\n      compare.setPayload(blob.getPayload());\n      HttpRequest request = signPutBloblWithTime.getContext().getSigner().signPutBlob(container, blob);\n      compareRequestComponents(request, compare);\n      assertEquals(request.getPayload(), compare.getPayload());\n   }\n\n   @Override\n   @Test\n   public void testSignPutBlobWithTime() throws Exception {\n      BlobStore signPutBloblWithTime = requestsSendResponses(init());\n      Blob blob = signPutBloblWithTime.blobBuilder(name).payload(text).contentType(\"text/plain\").build();\n      HttpRequest compare = putBlobWithTime();\n      compare.setPayload(blob.getPayload());\n      HttpRequest request = signPutBloblWithTime.getContext().getSigner().signPutBlob(container, blob, 900L /* seconds */);\n      compareRequestComponents(request, compare);\n      assertEquals(request.getPayload(), compare.getPayload());\n   }\n\n   @Override\n   protected Module createModule() {\n      return new TestAWSS3HttpApiModule();\n   }\n\n   @ConfiguresHttpApi\n   private static final class TestAWSS3HttpApiModule extends AWSS3HttpApiModule {\n      @Override\n      @TimeStamp\n      protected String provideTimeStamp(@TimeStamp Supplier<String> cache) {\n         return DATE;\n      }\n\n      @Override\n      @TimeStamp\n      protected Supplier<Date> provideTimeStampCacheDate(\n            @Named(Constants.PROPERTY_SESSION_INTERVAL) long seconds,\n            @TimeStamp final Supplier<String> timestamp,\n            final DateService dateService) {\n         return Suppliers.ofInstance(new Date(1212683899000L));\n      }\n   }\n}\n"
  },
  {
    "path": "providers/aws-s3/src/test/java/org/jclouds/aws/s3/blobstore/AWSS3BlobSignerV4ExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.s3.blobstore;\n\nimport static org.jclouds.Constants.PROPERTY_CREDENTIAL;\nimport static org.jclouds.Constants.PROPERTY_IDENTITY;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Date;\nimport java.util.Properties;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.Constants;\nimport org.jclouds.aws.s3.AWSS3ApiMetadata;\nimport org.jclouds.aws.s3.AWSS3ProviderMetadata;\nimport org.jclouds.aws.s3.blobstore.config.AWSS3BlobStoreContextModule;\nimport org.jclouds.aws.s3.config.AWSS3HttpApiModule;\nimport org.jclouds.aws.s3.filters.AWSRequestAuthorizeSignatureV4;\nimport org.jclouds.blobstore.BlobRequestSigner;\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.s3.blobstore.S3BlobSignerExpectTest;\nimport org.jclouds.s3.filters.RequestAuthorizeSignature;\nimport org.testng.SkipException;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.net.HttpHeaders;\nimport com.google.inject.Injector;\nimport com.google.inject.Module;\n\n@Test(groups = \"unit\", testName = \"AWSS3BlobSignerV4ExpectTest\")\npublic class AWSS3BlobSignerV4ExpectTest extends S3BlobSignerExpectTest {\n   private static final String IDENTITY = \"AKIAPAEBI3QI4EXAMPLE\";\n   private static final String CREDENTIAL = \"oHkkcPcOjJnoAXpjT8GXdNeBjo6Ru7QeFExAmPlE\";\n   private static final String TIMESTAMP = \"Thu, 03 Feb 2015 07:11:11 GMT\";\n\n   private static final String BUCKET_NAME = \"test-bucket\";\n   private static final String OBJECT_NAME = \"ExampleObject.txt\";\n   private static final String HOST = BUCKET_NAME + \".s3.amazonaws.com\";\n\n   public AWSS3BlobSignerV4ExpectTest() {\n      provider = null;\n   }\n\n   @Override\n   protected HttpRequest getBlobWithTime() {\n      return HttpRequest.builder().method(\"GET\")\n            .endpoint(\"https://\" + HOST + \"/\" + OBJECT_NAME\n                  + \"?X-Amz-Algorithm=AWS4-HMAC-SHA256\"\n                  + \"&X-Amz-Credential=AKIAPAEBI3QI4EXAMPLE/20150203/us-east-1/s3/aws4_request\"\n                  + \"&X-Amz-Date=20150203T071111Z\"\n                  + \"&X-Amz-Expires=86400\"\n                  + \"&X-Amz-SignedHeaders=host\"\n                  + \"&X-Amz-Signature=0bafb6a0d99c8b7c39abe5496e9897e8c442b09278f1a647267acb25e8d1c550\")\n            .addHeader(HttpHeaders.HOST, HOST)\n            .build();\n   }\n\n   @Test\n   @Override\n   public void testSignGetBlobWithTime() {\n      BlobStore getBlobWithTime = requestsSendResponses(init());\n      HttpRequest compare = getBlobWithTime();\n      HttpRequest signedRequest = getBlobWithTime.getContext().getSigner().signGetBlob(BUCKET_NAME, OBJECT_NAME,\n            86400L /* seconds */);\n      assertEquals(signedRequest, compare);\n   }\n\n   protected HttpRequest _putBlobWithTime() {\n      return HttpRequest.builder().method(\"PUT\")\n            .endpoint(\"https://\" + HOST + \"/\" + OBJECT_NAME\n                  + \"?X-Amz-Algorithm=AWS4-HMAC-SHA256\"\n                  + \"&X-Amz-Credential=AKIAPAEBI3QI4EXAMPLE/20150203/us-east-1/s3/aws4_request\"\n                  + \"&X-Amz-Date=20150203T071111Z\"\n                  + \"&X-Amz-Expires=86400\"\n                  + \"&X-Amz-SignedHeaders=host\"\n                  + \"&X-Amz-Signature=41484fb83e0c51b289907979ff96b2c743f6faf8dc70fca1c6fa78d8aeda132f\")\n            .addHeader(HttpHeaders.EXPECT, \"100-continue\")\n            .addHeader(HttpHeaders.HOST, HOST)\n            .build();\n   }\n\n   @Test\n   @Override\n   public void testSignPutBlobWithTime() throws Exception {\n      BlobStore signPutBloblWithTime = requestsSendResponses(init());\n      Blob blob = signPutBloblWithTime.blobBuilder(OBJECT_NAME).payload(text).contentType(\"text/plain\").build();\n      HttpRequest compare = _putBlobWithTime();\n      compare.setPayload(blob.getPayload());\n      HttpRequest signedRequest = signPutBloblWithTime.getContext().getSigner().signPutBlob(BUCKET_NAME, blob,\n            86400L /* seconds */);\n      assertEquals(signedRequest, compare);\n   }\n\n   @Override\n   protected HttpRequest putBlob() {\n      throw new SkipException(\"skip putBlob\");\n   }\n\n   @Override\n   public void testSignPutBlob() {\n      throw new SkipException(\"skip testSignPutBlob\");\n   }\n\n   @Override\n   public void testSignGetBlob() {\n      throw new SkipException(\"skip testSignGetBlob\");\n   }\n\n   @Override\n   public void testSignGetBlobWithOptions() {\n      throw new SkipException(\"skip testSignGetBlobWithOptions\");\n   }\n\n   @Override\n   protected Module createModule() {\n      return new TestAWSS3SignerV4HttpApiModule();\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      props.put(PROPERTY_IDENTITY, IDENTITY);\n      props.put(PROPERTY_CREDENTIAL, CREDENTIAL);\n      return props;\n   }\n\n   @Override\n   protected ProviderMetadata createProviderMetadata() {\n      AWSS3ApiMetadata.Builder apiBuilder = new AWSS3ApiMetadata().toBuilder();\n      apiBuilder.defaultModules(ImmutableSet.<Class<? extends Module>>of(TestAWSS3SignerV4HttpApiModule.class,\n            TestAWSS3BlobStoreContextModule.class));\n      return new AWSS3ProviderMetadata().toBuilder().apiMetadata(apiBuilder.build()).build();\n   }\n\n   public static final class TestAWSS3BlobStoreContextModule extends AWSS3BlobStoreContextModule {\n\n      @Override\n      protected void bindRequestSigner() {\n         // replace AWSS3BlobRequestSigner aws s3 with AWSS3BlobRequestSignerV4\n         bind(BlobRequestSigner.class).to(AWSS3BlobRequestSignerV4.class);\n      }\n\n   }\n\n   @ConfiguresHttpApi\n   public static final class TestAWSS3SignerV4HttpApiModule extends AWSS3HttpApiModule {\n      @Override\n      protected void configure() {\n         super.configure();\n      }\n\n      @Override\n      protected RequestAuthorizeSignature providesRequestAuthorizeSignature(Injector i, int version) {\n         return i.getInstance(AWSRequestAuthorizeSignatureV4.class);\n      }\n\n      @Override\n      @TimeStamp\n      protected String provideTimeStamp(@TimeStamp Supplier<String> cache) {\n         return TIMESTAMP;\n      }\n\n      @Override\n      @TimeStamp\n      protected Supplier<Date> provideTimeStampCacheDate(\n            @Named(Constants.PROPERTY_SESSION_INTERVAL) long seconds,\n            @TimeStamp final Supplier<String> timestamp,\n            final DateService dateService) {\n         return Suppliers.ofInstance(dateService.rfc822DateParse(TIMESTAMP));\n      }\n   }\n}\n"
  },
  {
    "path": "providers/aws-s3/src/test/java/org/jclouds/aws/s3/blobstore/integration/AWSS3BlobIntegrationLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.s3.blobstore.integration;\n\nimport org.jclouds.s3.S3Client;\nimport org.jclouds.s3.blobstore.integration.S3BlobIntegrationLiveTest;\nimport org.jclouds.s3.domain.PublicAccessBlockConfiguration;\nimport org.testng.annotations.Test;\nimport org.testng.SkipException;\n\n@Test(groups = \"live\", testName = \"AWSS3BlobIntegrationLiveTest\")\npublic class AWSS3BlobIntegrationLiveTest extends S3BlobIntegrationLiveTest {\n   public AWSS3BlobIntegrationLiveTest() {\n      provider = \"aws-s3\";\n   }\n\n   @Override\n   protected void allowPublicReadable(String containerName) {\n      S3Client client = view.unwrapApi(S3Client.class);\n      client.putBucketOwnershipControls(containerName, \"ObjectWriter\");\n      client.putPublicAccessBlock(containerName, PublicAccessBlockConfiguration.create(\n            /*blockPublicAcls=*/ false, /*ignorePublicAcls=*/ false, /*blockPublicPolicy=*/ false, /*restrictPublicBuckets=*/ false));\n   }\n\n   @Override\n   public void testCopyIfModifiedSinceNegative() throws Exception {\n      throw new SkipException(\"S3 supports copyIfModifiedSince but test uses time in the future which Amazon does not support\");\n   }\n}\n"
  },
  {
    "path": "providers/aws-s3/src/test/java/org/jclouds/aws/s3/blobstore/integration/AWSS3BlobLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.s3.blobstore.integration;\n\nimport org.jclouds.s3.blobstore.integration.S3BlobLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"AWSS3BlobLiveTest\")\npublic class AWSS3BlobLiveTest extends S3BlobLiveTest {\n   public AWSS3BlobLiveTest() {\n      provider = \"aws-s3\";\n   }\n}\n"
  },
  {
    "path": "providers/aws-s3/src/test/java/org/jclouds/aws/s3/blobstore/integration/AWSS3BlobSignerLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.s3.blobstore.integration;\n\nimport java.util.Properties;\n\nimport org.jclouds.Constants;\nimport org.jclouds.s3.blobstore.integration.S3BlobSignerLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"AWSS3BlobSignerLiveTest\")\npublic class AWSS3BlobSignerLiveTest extends S3BlobSignerLiveTest {\n   public AWSS3BlobSignerLiveTest() {\n      provider = \"aws-s3\";\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties overrides = super.setupProperties();\n      overrides.setProperty(Constants.PROPERTY_STRIP_EXPECT_HEADER, \"true\");\n      overrides.setProperty(Constants.PROPERTY_SESSION_INTERVAL, \"1\");\n      return overrides;\n   }\n}\n"
  },
  {
    "path": "providers/aws-s3/src/test/java/org/jclouds/aws/s3/blobstore/integration/AWSS3ContainerIntegrationLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.s3.blobstore.integration;\n\nimport org.jclouds.s3.blobstore.integration.S3ContainerIntegrationLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups =  \"live\", testName = \"AWSS3ContainerIntegrationLiveTest\")\npublic class AWSS3ContainerIntegrationLiveTest extends S3ContainerIntegrationLiveTest {\n   public AWSS3ContainerIntegrationLiveTest() {\n      provider = \"aws-s3\";\n   }\n}\n"
  },
  {
    "path": "providers/aws-s3/src/test/java/org/jclouds/aws/s3/blobstore/integration/AWSS3ContainerLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.s3.blobstore.integration;\n\nimport org.jclouds.s3.blobstore.integration.S3ContainerLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"AWSS3ContainerLiveTest\")\npublic class AWSS3ContainerLiveTest extends S3ContainerLiveTest {\n   public AWSS3ContainerLiveTest() {\n      provider = \"aws-s3\";\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-s3/src/test/java/org/jclouds/aws/s3/blobstore/integration/AWSS3ServiceIntegrationLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.s3.blobstore.integration;\n\nimport java.util.Set;\n\nimport org.jclouds.domain.Location;\nimport org.jclouds.s3.blobstore.integration.S3ServiceIntegrationLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"live\", testName = \"AWSS3ServiceIntegrationLiveTest\")\npublic class AWSS3ServiceIntegrationLiveTest extends S3ServiceIntegrationLiveTest {\n   public AWSS3ServiceIntegrationLiveTest() {\n      provider = \"aws-s3\";\n   }\n   \n   @Override\n   protected Set<String> getIso3166Codes() {\n      return ImmutableSet.<String> of(\n            \"AU-NSW\",\n            \"BH\",\n            \"BR-SP\",\n            \"CA\",\n            \"CH-ZH\",\n            \"CN-BJ\",\n            \"CN-NX\",\n            \"DE-HE\",\n            \"ES\",\n            \"FR-IDF\",\n            \"GB-LND\",\n            \"IE\",\n            \"IN-MH\",\n            \"IT-MI\",\n            \"JP-13\",\n            \"KR-11\",\n            \"SE-AB\",\n            \"SG\",\n            \"US\",\n            \"US-CA\",\n            \"US-OH\",\n            \"US-OR\");\n   }\n\n   // Amazon returns null instead of us-standard in some situations\n   @Override\n   protected boolean locationEquals(Location location1, Location location2) {\n      Location usStandard = null;\n      for (Location location : view.getBlobStore().listAssignableLocations()) {\n         if (location.getId().equals(\"us-standard\")) {\n            usStandard = location;\n            break;\n         }\n      }\n      return super.locationEquals(location1 == null ? usStandard : location1,\n                                  location2 == null ? usStandard : location2);\n   }\n}\n"
  },
  {
    "path": "providers/aws-s3/src/test/java/org/jclouds/aws/s3/blobstore/integration/PathBasedContainerLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.s3.blobstore.integration;\n\nimport static org.jclouds.s3.reference.S3Constants.PROPERTY_S3_VIRTUAL_HOST_BUCKETS;\n\nimport java.util.Properties;\n\nimport org.jclouds.s3.blobstore.integration.S3ContainerLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"PathBasedContainerLiveTest\")\npublic class PathBasedContainerLiveTest  extends S3ContainerLiveTest {\n   public PathBasedContainerLiveTest() {\n      provider = \"aws-s3\";\n   }\n\n   @Override\n   public Properties setupProperties() {\n      Properties properties = super.setupProperties();\n      properties.setProperty(PROPERTY_S3_VIRTUAL_HOST_BUCKETS, \"false\");\n      return properties;\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-s3/src/test/java/org/jclouds/aws/s3/filter/AwsRequestAuthorizeSignatureV4Test.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.s3.filter;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.net.HttpHeaders;\nimport org.jclouds.aws.s3.filters.AWSRequestAuthorizeSignatureV4;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.reflect.Invocation;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.jclouds.s3.S3Client;\nimport org.jclouds.s3.filters.RequestAuthorizeSignatureV4;\nimport org.jclouds.s3.filters.RequestAuthorizeSignatureV4Test;\nimport org.jclouds.s3.options.ListBucketOptions;\nimport org.testng.annotations.Test;\n\nimport static org.jclouds.reflect.Reflection2.method;\nimport static org.testng.Assert.assertEquals;\n\n/**\n * Tests behavior of {@code AWSRequestAuthorizeSignatureV4}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"AwsRequestAuthorizeSignatureV4Test\")\npublic class AwsRequestAuthorizeSignatureV4Test extends RequestAuthorizeSignatureV4Test {\n\n    private static final String LIST_BUCKET_AUTHORIZATION_HEADER_RESULT = \"AWS4-HMAC-SHA256 Credential=AKIAPAEBI3QI4EXAMPLE/20150203/cn-north-1/s3/aws4_request,\" +\n            \" SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=ec72ac5f67bf86e3b95d122f690a2898224f28328d39131c48221a5dcf0c2cee\";\n\n    @Override\n    public RequestAuthorizeSignatureV4 filter(Credentials creds) {\n        return injector(creds).getInstance(AWSRequestAuthorizeSignatureV4.class);\n    }\n\n\n    // JCLOUDS-1631\n    @Test\n    void testListBucketWithSpecialChars() {\n        Invocation invocation = Invocation.create(method(S3Client.class, \"listBucket\", String.class,\n                        ListBucketOptions[].class),\n                // Simulating ListBucketOptions.Builder.withPrefix(\"Folder (`~!@#$%^&*-_+[]'|<>.?) Name/\") with manual endpoint:\n                ImmutableList.<Object>of(RequestAuthorizeSignatureV4Test.BUCKET_NAME, new ListBucketOptions[0]));\n\n        HttpRequest getObject = GeneratedHttpRequest.builder().method(\"GET\")\n                .invocation(invocation)\n                .endpoint(\"https://\" + BUCKET_NAME + \".s3.cn-north-1.amazonaws.com.cn/?delimiter=/&prefix=Folder%20%28%60%7E%21%40%23%24%25%5E%26%2A-_%2B%5B%5D%27%7C%3C%3E.%3F%29%20Name/\")\n                .addHeader(HttpHeaders.HOST, BUCKET_NAME + \".s3.cn-north-1.amazonaws.com.cn\")\n                .build();\n\n\n        HttpRequest filtered = filter(temporaryCredentials).filter(getObject);\n        assertEquals(filtered.getFirstHeaderOrNull(\"Authorization\"), LIST_BUCKET_AUTHORIZATION_HEADER_RESULT);\n    }\n}\n"
  },
  {
    "path": "providers/aws-s3/src/test/java/org/jclouds/aws/s3/internal/BaseAWSS3ClientExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.s3.internal;\n\nimport org.jclouds.aws.s3.AWSS3Client;\nimport org.jclouds.aws.s3.AWSS3ProviderMetadata;\nimport org.jclouds.aws.s3.config.AWSS3HttpApiModule;\nimport org.jclouds.aws.s3.filters.AWSRequestAuthorizeSignature;\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.internal.BaseRestApiExpectTest;\nimport org.jclouds.s3.filters.RequestAuthorizeSignature;\n\nimport com.google.common.base.Supplier;\nimport com.google.inject.Injector;\nimport com.google.inject.Module;\n\n/**\n * Base class for writing Expect tests for AWS-S3\n */\npublic class BaseAWSS3ClientExpectTest extends BaseRestApiExpectTest<AWSS3Client> {\n\n   protected static final String CONSTANT_DATE = \"2009-11-08T15:54:08.897Z\";\n   \n\n   public BaseAWSS3ClientExpectTest() {\n      provider = \"aws-s3\";\n   }\n   \n   @Override\n   public ProviderMetadata createProviderMetadata() {\n      return new AWSS3ProviderMetadata();\n   }\n\n      @ConfiguresHttpApi\n   private static final class TestAWSS3HttpApiModule extends AWSS3HttpApiModule {\n      @Override\n      protected String provideTimeStamp(@TimeStamp Supplier<String> cache) {\n         return CONSTANT_DATE;\n      }\n\n      // subclass expects v2 signatures\n      @Override\n      protected RequestAuthorizeSignature providesRequestAuthorizeSignature(Injector i, int version) {\n         return i.getInstance(AWSRequestAuthorizeSignature.class);\n      }\n   }\n\n   @Override\n   protected Module createModule() {\n      return new TestAWSS3HttpApiModule();\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-s3/src/test/java/org/jclouds/aws/s3/services/AWSBucketsLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.s3.services;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.aws.domain.Region;\nimport org.jclouds.s3.domain.AccessControlList;\nimport org.jclouds.s3.domain.AccessControlList.GroupGranteeURI;\nimport org.jclouds.s3.domain.AccessControlList.Permission;\nimport org.jclouds.s3.domain.CannedAccessPolicy;\nimport org.jclouds.s3.domain.PublicAccessBlockConfiguration;\nimport org.jclouds.s3.services.BucketsLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Throwables;\n\n@Test(groups = \"live\", testName = \"AWSBucketsLiveTest\")\npublic class AWSBucketsLiveTest extends BucketsLiveTest {\n   public AWSBucketsLiveTest() {\n      provider = \"aws-s3\";\n   }\n\n   @Override\n   protected void allowPublicReadable(String containerName) {\n      getApi().putBucketOwnershipControls(containerName, \"ObjectWriter\");\n      getApi().putPublicAccessBlock(containerName, PublicAccessBlockConfiguration.create(\n            /*blockPublicAcls=*/ false, /*ignorePublicAcls=*/ false, /*blockPublicPolicy=*/ false, /*restrictPublicBuckets=*/ false));\n   }\n\n   public void testDefaultBucketLocation() throws Exception {\n\n      String bucketName = getContainerName();\n      try {\n         String location = getApi().getBucketLocation(bucketName);\n         assert location.equals(Region.US_STANDARD) : \"bucket: \" + bucketName + \" location: \" + location;\n      } finally {\n         returnContainer(bucketName);\n      }\n   }\n\n   /**\n    * using scratch bucketName as we are changing location\n    */\n   public void testEu() throws Exception {\n      final String bucketName = getScratchContainerName();\n      try {\n         getApi().putBucketInRegion(Region.EU_WEST_1, bucketName);\n         allowPublicReadable(bucketName);\n         getApi().updateBucketCannedACL(bucketName, CannedAccessPolicy.PUBLIC_READ);\n         assertConsistencyAware(new Runnable() {\n            public void run() {\n               try {\n                  AccessControlList acl = getApi().getBucketACL(bucketName + \"eu\");\n                  assertTrue(acl.hasPermission(GroupGranteeURI.ALL_USERS, Permission.READ), acl.toString());\n               } catch (Exception e) {\n                  Throwables.propagateIfPossible(e);\n               }\n            }\n         });\n         assertEquals(Region.EU_WEST_1, getApi().getBucketLocation(bucketName + \"eu\"));\n         // TODO: I believe that the following should work based on the above acl assertion passing.\n         // However, it fails on 403\n         // URL url = new URL(String.format(\"http://%s.s3.amazonaws.com\", bucketName));\n         // Utils.toStringAndClose(url.openStream());\n      } finally {\n         destroyContainer(bucketName + \"eu\");\n      }\n   }\n}\n"
  },
  {
    "path": "providers/aws-s3/src/test/resources/log4j.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE log4j:configuration SYSTEM \"log4j.dtd\">\n\n    <!--\n        For more configuration infromation and examples see the Apache\n        Log4j website: http://logging.apache.org/log4j/\n    -->\n<log4j:configuration xmlns:log4j=\"http://jakarta.apache.org/log4j/\"\n    debug=\"false\">\n\n    <!-- A time/date based rolling appender -->\n    <appender name=\"HTTPWIREFILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/http-wire.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n    \n    <!-- A time/date based rolling appender -->\n    <appender name=\"WIREFILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds-wire.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n\n    <!-- A time/date based rolling appender -->\n    <appender name=\"FILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n    <!-- A time/date based rolling appender -->\n    <appender name=\"BLOBSTOREFILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds-blobstore.log\" />\n        <param name=\"Append\" value=\"true\" />\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n        <param name=\"Threshold\" value=\"TRACE\" />\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n        </layout>\n    </appender>\n\n    <appender name=\"ASYNC\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"FILE\" />\n    </appender>\n\n    <appender name=\"ASYNCHTTPWIRE\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"HTTPWIREFILE\" />\n    </appender>\n\n    <appender name=\"ASYNCWIRE\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"WIREFILE\" />\n    </appender>\n\n    <appender name=\"ASYNCBLOBSTORE\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"BLOBSTOREFILE\" />\n    </appender>\n    <!-- ================ -->\n    <!-- Limit categories -->\n    <!-- ================ -->\n\n    <category name=\"org.jclouds\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNC\" />\n    </category>\n\n\t<category name=\"org.apache.http\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNCHTTPWIRE\" />\n    </category>\n\t<category name=\"org.apache.http.wire\">\n        <priority value=\"ERROR\" />\n        <appender-ref ref=\"ASYNCHTTPWIRE\" />\n    </category>\n    \n    <category name=\"jclouds.headers\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNCWIRE\" />\n    </category><!--\n    <category name=\"jclouds.wire\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNCWIRE\" />\n    </category>\n    --><category name=\"jclouds.blobstore\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNCBLOBSTORE\" />\n    </category>\n    <!-- ======================= -->\n    <!-- Setup the Root category -->\n    <!-- ======================= -->\n\n    <root>\n        <priority value=\"WARN\" />\n    </root>\n\n</log4j:configuration>\n"
  },
  {
    "path": "providers/aws-sqs/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.aws.sqs.*;version=\"${project.version}\";-noimport:=true"
  },
  {
    "path": "providers/aws-sqs/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.provider</groupId>\n  <artifactId>aws-sqs</artifactId>\n  <name>jclouds Amazon Simple Queue Service provider</name>\n  <description>Simple Queue Service implementation targeted to Amazon Web Services</description>\n\n  <properties>\n    <test.aws.identity>FIXME_IDENTITY</test.aws.identity>\n    <test.aws.credential>FIXME_CREDENTIAL</test.aws.credential>\n    <test.aws-sqs.endpoint>https://sqs.us-east-1.amazonaws.com</test.aws-sqs.endpoint>\n    <test.aws-sqs.api-version>2011-10-01</test.aws-sqs.api-version>\n    <test.aws-sqs.build-version />\n    <test.aws-sqs.identity>${test.aws.identity}</test.aws-sqs.identity>\n    <test.aws-sqs.credential>${test.aws.credential}</test.aws-sqs.credential>\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>sqs</artifactId>\n      <version>${project.version}</version>\n      <type>jar</type>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>sqs</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-slf4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>ch.qos.logback</groupId>\n      <artifactId>logback-classic</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.aws-sqs.endpoint>${test.aws-sqs.endpoint}</test.aws-sqs.endpoint>\n                    <test.aws-sqs.api-version>${test.aws-sqs.api-version}</test.aws-sqs.api-version>\n                    <test.aws-sqs.build-version>${test.aws-sqs.build-version}</test.aws-sqs.build-version>\n                    <test.aws-sqs.identity>${test.aws-sqs.identity}</test.aws-sqs.identity>\n                    <test.aws-sqs.credential>${test.aws-sqs.credential}</test.aws-sqs.credential>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n"
  },
  {
    "path": "providers/aws-sqs/src/main/java/org/jclouds/aws/sqs/AWSSQSProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.sqs;\n\nimport static org.jclouds.aws.domain.Region.AP_NORTHEAST_1;\nimport static org.jclouds.aws.domain.Region.AP_SOUTHEAST_1;\nimport static org.jclouds.aws.domain.Region.AP_SOUTHEAST_2;\nimport static org.jclouds.aws.domain.Region.EU_WEST_1;\nimport static org.jclouds.aws.domain.Region.SA_EAST_1;\nimport static org.jclouds.aws.domain.Region.US_EAST_1;\nimport static org.jclouds.aws.domain.Region.US_WEST_1;\nimport static org.jclouds.aws.domain.Region.US_WEST_2;\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_REGION;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.aws.domain.Region;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\nimport org.jclouds.sqs.SQSApiMetadata;\n\nimport com.google.auto.service.AutoService;\n\n/**\n * Implementation of @ link org.jclouds.types.ProviderMetadata} for Amazon's Simple Queue Service\n * provider.\n */\n@AutoService(ProviderMetadata.class)\npublic class AWSSQSProviderMetadata extends BaseProviderMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return Builder.class.cast(builder().fromProviderMetadata(this));\n   }\n   \n   public AWSSQSProviderMetadata() {\n      super(builder());\n   }\n\n   public AWSSQSProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = new Properties();\n      properties.putAll(Region.regionProperties());\n      properties.setProperty(PROPERTY_REGION + \".\" + US_EAST_1 + \".endpoint\",\n            \"https://sqs.us-east-1.amazonaws.com\");\n      properties.setProperty(PROPERTY_REGION + \".\" + US_WEST_1 + \".endpoint\",\n            \"https://sqs.us-west-1.amazonaws.com\");\n      properties.setProperty(PROPERTY_REGION + \".\" + US_WEST_2 + \".endpoint\",\n            \"https://sqs.us-west-2.amazonaws.com\");\n      properties.setProperty(PROPERTY_REGION + \".\" + SA_EAST_1 + \".endpoint\",\n            \"https://sqs.sa-east-1.amazonaws.com\");      \n      properties.setProperty(PROPERTY_REGION + \".\" + EU_WEST_1 + \".endpoint\",\n            \"https://sqs.eu-west-1.amazonaws.com\");\n      properties.setProperty(PROPERTY_REGION + \".\" + AP_SOUTHEAST_1 + \".endpoint\",\n            \"https://sqs.ap-southeast-1.amazonaws.com\");\n      properties.setProperty(PROPERTY_REGION + \".\" + AP_SOUTHEAST_2 + \".endpoint\",\n            \"https://sqs.ap-southeast-2.amazonaws.com\");\n      properties.setProperty(PROPERTY_REGION + \".\" + AP_NORTHEAST_1 + \".endpoint\",\n            \"https://sqs.ap-northeast-1.amazonaws.com\");\n      return properties;\n   }\n   \n   public static class Builder extends BaseProviderMetadata.Builder {\n\n      protected Builder() {\n         id(\"aws-sqs\")\n         .name(\"Amazon Simple Queue Service\")\n         .endpoint(\"https://sqs.us-east-1.amazonaws.com\")\n         .homepage(URI.create(\"http://aws.amazon.com/sqs\"))\n         .console(URI.create(\"https://console.aws.amazon.com/ec2/home\"))\n         .linkedServices(\"aws-ec2\", \"aws-rds\", \"aws-sqs\", \"aws-elb\", \"aws-iam\", \"aws-cloudwatch\", \"aws-s3\", \"aws-simpledb\")\n         .iso3166Codes(\"US-VA\", \"US-CA\", \"BR-SP\", \"US-OR\", \"IE\", \"SG\", \"AU-NSW\", \"JP-13\")\n         .apiMetadata(new SQSApiMetadata())\n         .defaultProperties(AWSSQSProviderMetadata.defaultProperties());\n      }\n\n      @Override\n      public Builder fromProviderMetadata(\n            ProviderMetadata in) {\n         super.fromProviderMetadata(in);\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "providers/aws-sqs/src/test/java/org/jclouds/aws/sqs/AWSSQSProviderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.sqs;\n\nimport org.jclouds.sqs.SQSApiMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.testng.annotations.Test;\n\n/**\n * The AWSSQSProviderTest tests the org.jclouds.providers.AWSSQSProvider class.\n */\n@Test(groups = \"unit\", testName = \"AWSSQSProviderTest\")\npublic class AWSSQSProviderTest extends BaseProviderMetadataTest {\n\n   public AWSSQSProviderTest() {\n      super(new AWSSQSProviderMetadata(), new SQSApiMetadata());\n   }\n}\n"
  },
  {
    "path": "providers/aws-sqs/src/test/java/org/jclouds/aws/sqs/features/AWSMessageApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.sqs.features;\n\nimport org.jclouds.sqs.features.MessageApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"AWSMessageApiLiveTest\")\npublic class AWSMessageApiLiveTest extends MessageApiLiveTest {\n\n   public AWSMessageApiLiveTest() {\n      provider = \"aws-sqs\";\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-sqs/src/test/java/org/jclouds/aws/sqs/features/AWSPermissionApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.sqs.features;\n\nimport org.jclouds.sqs.features.PermissionApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"AWSPermissionApiLiveTest\")\npublic class AWSPermissionApiLiveTest extends PermissionApiLiveTest {\n\n   public AWSPermissionApiLiveTest() {\n      provider = \"aws-sqs\";\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-sqs/src/test/java/org/jclouds/aws/sqs/features/AWSQueueApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.sqs.features;\n\nimport org.jclouds.sqs.features.QueueApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"AWSQueueApiLiveTest\")\npublic class AWSQueueApiLiveTest extends QueueApiLiveTest {\n\n   public AWSQueueApiLiveTest() {\n      provider = \"aws-sqs\";\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-sts/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.aws.sts.*;version=\"${project.version}\";-noimport:=true"
  },
  {
    "path": "providers/aws-sts/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.provider</groupId>\n  <artifactId>aws-sts</artifactId>\n  <name>jclouds Amazon Identity and Access Management (STS) provider</name>\n  <description>Identity and Access Management (STS) to Amazon Web Services</description>\n\n  <properties>\n    <test.aws.identity>FIXME_IDENTITY</test.aws.identity>\n    <test.aws.credential>FIXME_CREDENTIAL</test.aws.credential>\n    <test.aws-sts.endpoint>https://sts.amazonaws.com</test.aws-sts.endpoint>\n    <test.aws-sts.api-version>2011-06-15</test.aws-sts.api-version>\n    <test.aws-sts.build-version />\n    <test.aws-sts.identity>${test.aws.identity}</test.aws-sts.identity>\n    <test.aws-sts.credential>${test.aws.credential}</test.aws-sts.credential>\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>sts</artifactId>\n      <version>${project.version}</version>\n      <type>jar</type>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>sts</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-log4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.aws-sts.endpoint>${test.aws-sts.endpoint}</test.aws-sts.endpoint>\n                    <test.aws-sts.api-version>${test.aws-sts.api-version}</test.aws-sts.api-version>\n                    <test.aws-sts.build-version>${test.aws-sts.build-version}</test.aws-sts.build-version>\n                    <test.aws-sts.identity>${test.aws-sts.identity}</test.aws-sts.identity>\n                    <test.aws-sts.credential>${test.aws-sts.credential}</test.aws-sts.credential>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n"
  },
  {
    "path": "providers/aws-sts/src/main/java/org/jclouds/aws/sts/AWSSTSProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.sts;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.sts.STSApiMetadata;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\n\nimport com.google.auto.service.AutoService;\n\n/**\n * Implementation of @ link org.jclouds.types.ProviderMetadata} for Amazon's STS\n * provider.\n*\n*/\n@AutoService(ProviderMetadata.class)\npublic class AWSSTSProviderMetadata extends BaseProviderMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromProviderMetadata(this);\n   }\n   \n   public AWSSTSProviderMetadata() {\n      super(builder());\n   }\n\n   public AWSSTSProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = new Properties();\n      return properties;\n   }\n   \n   public static class Builder extends BaseProviderMetadata.Builder {\n\n      protected Builder() {\n         id(\"aws-sts\")\n         .name(\"Amazon STS\")\n         .endpoint(\"https://sts.amazonaws.com\")\n         .homepage(URI.create(\"http://aws.amazon.com/iam/\"))\n         .console(URI.create(\"https://console.aws.amazon.com/iam/home\"))\n         .linkedServices(\"aws-ec2\", \"aws-elb\", \"aws-iam\", \"aws-sts\", \"aws-cloudwatch\", \"aws-s3\", \"aws-sqs\", \"aws-simpledb\")\n         .iso3166Codes(\"US-VA\")\n         .apiMetadata(new STSApiMetadata())\n         .defaultProperties(AWSSTSProviderMetadata.defaultProperties());\n      }\n\n      @Override\n      public AWSSTSProviderMetadata build() {\n         return new AWSSTSProviderMetadata(this);\n      }\n      \n      @Override\n      public Builder fromProviderMetadata(ProviderMetadata in) {\n         super.fromProviderMetadata(in);\n         return this;\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/aws-sts/src/test/java/org/jclouds/aws/sts/AWSSTSApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.sts;\n\nimport org.jclouds.sts.STSApiLiveTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code STSApi}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"AWSSTSApiLiveTest\")\npublic class AWSSTSApiLiveTest extends STSApiLiveTest {\n   public AWSSTSApiLiveTest() {\n      provider = \"aws-sts\";\n   }\n\n}\n"
  },
  {
    "path": "providers/aws-sts/src/test/java/org/jclouds/aws/sts/AWSSTSProviderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.aws.sts;\n\nimport org.jclouds.sts.STSApiMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.testng.annotations.Test;\n\n/**\n * The AWSSTSProviderTest tests the org.jclouds.providers.AWSSTSProvider class.\n */\n@Test(groups = \"unit\", testName = \"AWSSTSProviderTest\")\npublic class AWSSTSProviderTest extends BaseProviderMetadataTest {\n\n   public AWSSTSProviderTest() {\n      super(new AWSSTSProviderMetadata(), new STSApiMetadata());\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/README.md",
    "content": "# The jclouds provider for Windows Azure's Storage (http://www.microsoft.com/windowsazure/storage/default.aspx).\n\n* **TODO**: Implementation status.\n* **TODO**: Supported features.\n* **TODO**: Usage example.\n\n## Running live tests\n\nTry\n\n```sh\nmvn clean install -Plive -pl :azureblob -Dtest=AzureBlobClientLiveTest -Dtest.azureblob.identity==<azure_storage_account_name> -Dtest.azureblob.credential=<azure_storage_account_access_key>\n```\n"
  },
  {
    "path": "providers/azureblob/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.azureblob.*;version=\"${project.version}\";-noimport:=true,\\\n    org.jclouds.azure.storage.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "providers/azureblob/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.provider</groupId>\n  <artifactId>azureblob</artifactId>\n  <name>jclouds Azure Storage provider</name>\n  <description>jclouds components to access Azure Blob Service</description>\n\n  <properties>\n    <test.azureblob.endpoint>https://${jclouds.identity}.blob.core.windows.net</test.azureblob.endpoint>\n    <test.azureblob.api-version>2017-04-17</test.azureblob.api-version>\n    <test.azureblob.build-version />\n    <test.azureblob.identity>${test.azure.identity}</test.azureblob.identity>\n    <test.azureblob.credential>${test.azure.credential}</test.azureblob.credential>\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-blobstore</artifactId>\n      <version>${project.version}</version>\n      <type>jar</type>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-blobstore</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-log4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>oauth</artifactId>\n      <version>${project.version}</version>\n      <scope>compile</scope>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.azureblob.endpoint>${test.azureblob.endpoint}</test.azureblob.endpoint>\n                    <test.azureblob.api-version>${test.azureblob.api-version}</test.azureblob.api-version>\n                    <test.azureblob.build-version>${test.azureblob.build-version}</test.azureblob.build-version>\n                    <test.azureblob.identity>${test.azureblob.identity}</test.azureblob.identity>\n                    <test.azureblob.credential>${test.azureblob.credential}</test.azureblob.credential>\n                    <jclouds.blobstore.httpstream.url>${jclouds.blobstore.httpstream.url}</jclouds.blobstore.httpstream.url>\n                    <jclouds.blobstore.httpstream.md5>${jclouds.blobstore.httpstream.md5}</jclouds.blobstore.httpstream.md5>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azure/storage/AzureStorageResponseException.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azure.storage;\n\nimport org.jclouds.azure.storage.domain.AzureStorageError;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.javax.annotation.Nullable;\n\n/**\n * Encapsulates an Error from Azure Storage Services.\n * \n * @see <a href=\"http://docs.amazonwebservices.com/AmazonS3/2006-03-01/UsingRESTError.html\" />\n * @see AzureStorageError\n * @see org.jclouds.aws.handlers.ParseAzureStorageErrorFromXmlContent\n */\npublic class AzureStorageResponseException extends HttpResponseException {\n\n   private transient AzureStorageError error = new AzureStorageError();\n\n   public AzureStorageResponseException(HttpCommand command, HttpResponse response, AzureStorageError error) {\n      super(String.format(\"command %s failed with code %s, error: %s\", command.toString(), response\n               .getStatusCode(), error.toString()), command, response);\n      this.setError(error);\n\n   }\n\n   public AzureStorageResponseException(HttpCommand command, HttpResponse response, AzureStorageError error,\n            Throwable cause) {\n      super(String.format(\"command %1$s failed with error: %2$s\", command.toString(), error\n               .toString()), command, response, cause);\n      this.setError(error);\n\n   }\n\n   public AzureStorageResponseException(String message, HttpCommand command, HttpResponse response,\n            AzureStorageError error) {\n      super(message, command, response);\n      this.setError(error);\n\n   }\n\n   public AzureStorageResponseException(String message, HttpCommand command, HttpResponse response,\n            AzureStorageError error, Throwable cause) {\n      super(message, command, response, cause);\n      this.setError(error);\n\n   }\n\n   public void setError(AzureStorageError error) {\n      this.error = error;\n   }\n\n   @Nullable\n   public AzureStorageError getError() {\n      return error;\n   }\n\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azure/storage/config/AuthType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azure.storage.config;\n\nimport static com.google.common.base.CaseFormat.LOWER_CAMEL;\nimport static com.google.common.base.CaseFormat.UPPER_UNDERSCORE;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\npublic enum AuthType {\n    /** Includes both the API key and SAS credentials */\n    AZURE_KEY,\n    /** Azure AD credentials */\n    AZURE_AD,\n    /** Uses the SharedKey scheme, rather than SharedKeyLite */\n    AZURE_SHARED_KEY;\n\n    @Override\n    public String toString() {\n        return UPPER_UNDERSCORE.to(LOWER_CAMEL, name());\n    }\n\n    public static AuthType fromValue(String authType) {\n        return valueOf(LOWER_CAMEL.to(UPPER_UNDERSCORE, checkNotNull(authType, \"authType\")));\n    }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azure/storage/config/AzureStorageOAuthConfigFactory.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azure.storage.config;\n\nimport com.google.inject.Inject;\nimport com.google.inject.name.Named;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.oauth.v2.config.OAuthConfigFactory;\nimport org.jclouds.oauth.v2.config.OAuthScopes;\n\nimport static org.jclouds.azure.storage.config.AzureStorageProperties.ACCOUNT;\nimport static org.jclouds.oauth.v2.config.OAuthProperties.AUDIENCE;\nimport static org.jclouds.oauth.v2.config.OAuthProperties.RESOURCE;\n\npublic class AzureStorageOAuthConfigFactory implements OAuthConfigFactory {\n    private final OAuthScopes scopes;\n\n    @Named(AUDIENCE)\n    @Inject(optional = true)\n    private String audience;\n\n    @Named(RESOURCE)\n    @Inject(optional = true)\n    private String resource;\n\n    @Named(ACCOUNT)\n    @Inject\n    private String account;\n\n    @Inject\n    AzureStorageOAuthConfigFactory(OAuthScopes scopes) { this.scopes = scopes; }\n\n    @Override\n    public OAuthConfig forRequest(HttpRequest input) {\n        String authResource = resource;\n        if (authResource == null) {\n            authResource = \"https://\" + account + \".blob.core.windows.net\";\n        }\n        String authAudience = audience;\n        if (authAudience == null) {\n            authAudience = \"https://\" + account + \".blob.core.windows.net\";\n        }\n        return OAuthConfig.create(scopes.forRequest(input), authAudience, authResource);\n    }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azure/storage/config/AzureStorageProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azure.storage.config;\n\npublic final class AzureStorageProperties {\n    public static final String AUTH_TYPE = \"jclouds.azureblob.auth\";\n    public static final String ACCOUNT = \"jclouds.azureblob.account\";\n    public static final String TENANT_ID = \"jclouds.azureblob.tenantId\";\n\n    private AzureStorageProperties() {\n        throw new AssertionError(\"intentionally unimplemented\");\n    }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azure/storage/domain/AzureStorageError.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azure.storage.domain;\n\nimport java.util.Map;\n\nimport com.google.common.collect.Maps;\n\n/**\n * When an Azure Storage request is in error, the client receives an error response.\n *\n * @see <a href=\"http://msdn.microsoft.com/en-us/library/dd573365.aspx\" />\n */\npublic class AzureStorageError {\n   private String code;\n   private String message;\n   private String requestId;\n   private Map<String, String> details = Maps.newHashMap();\n   private String stringSigned;\n   private String signature;\n\n   @Override\n   public String toString() {\n      final StringBuilder sb = new StringBuilder();\n      sb.append(\"AzureError\");\n      sb.append(\"{requestId='\").append(requestId).append('\\'');\n      if (code != null)\n         sb.append(\", code='\").append(code).append('\\'');\n      if (message != null)\n         sb.append(\", message='\").append(message).append('\\'');\n      if (stringSigned != null)\n         sb.append(\", stringSigned='\").append(stringSigned).append('\\'');\n      if (getSignature() != null)\n         sb.append(\", signature='\").append(getSignature()).append('\\'');\n      if (!details.isEmpty())\n         sb.append(\", context='\").append(details.toString()).append('\\'').append('}');\n      return sb.toString();\n   }\n\n   public void setCode(String code) {\n      this.code = code;\n   }\n\n   public String getCode() {\n      return code;\n   }\n\n   public void setMessage(String message) {\n      this.message = message;\n   }\n\n   public String getMessage() {\n      return message;\n   }\n\n   public void setRequestId(String requestId) {\n      this.requestId = requestId;\n   }\n\n   /**\n    * If a request is consistently failing and you have verified that the request is properly\n    * formulated, you may use this value to report the error to Microsoft. In your report, include\n    * the value of x-ms-request-id, the approximate time that the request was made, the storage\n    * service against which the request was made, and the type of operation that the request\n    * attempted\n    */\n   public String getRequestId() {\n      return requestId;\n   }\n\n   public void setStringSigned(String stringSigned) {\n      this.stringSigned = stringSigned;\n   }\n\n   /**\n    * @return what jclouds signed before sending the request.\n    */\n   public String getStringSigned() {\n      return stringSigned;\n   }\n\n   public void setDetails(Map<String, String> context) {\n      this.details = context;\n   }\n\n   /**\n    * @return additional details surrounding the error.\n    */\n   public Map<String, String> getDetails() {\n      return details;\n   }\n\n   public void setSignature(String signature) {\n      this.signature = signature;\n   }\n\n   public String getSignature() {\n      return signature;\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azure/storage/domain/BoundedSet.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azure.storage.domain;\n\nimport java.net.URI;\nimport java.util.Set;\n\npublic interface BoundedSet<T> extends Set<T> {\n   URI getUrl();\n\n   String getPrefix();\n\n   String getMarker();\n\n   int getMaxResults();\n\n   String getNextMarker();\n\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azure/storage/domain/internal/BoundedHashSet.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azure.storage.domain.internal;\n\nimport java.net.URI;\nimport java.util.LinkedHashSet;\n\nimport org.jclouds.azure.storage.domain.BoundedSet;\n\nimport com.google.common.collect.Iterables;\n\npublic class BoundedHashSet<T> extends LinkedHashSet<T> implements BoundedSet<T> {\n\n   protected final URI url;\n   protected final String prefix;\n   protected final String marker;\n   protected final Integer maxResults;\n   protected final String nextMarker;\n\n   public BoundedHashSet(Iterable<T> contents, URI url, String prefix, String marker,\n            Integer maxResults, String nextMarker) {\n      Iterables.addAll(this, contents);\n      this.url = url;\n      this.prefix = prefix;\n      this.nextMarker = nextMarker;\n      this.maxResults = maxResults;\n      this.marker = marker;\n   }\n\n   public String getPrefix() {\n      return prefix;\n   }\n\n   public String getMarker() {\n      return marker;\n   }\n\n   public int getMaxResults() {\n      return maxResults;\n   }\n\n   public String getNextMarker() {\n      return nextMarker;\n   }\n\n   public URI getUrl() {\n      return url;\n   }\n\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azure/storage/filters/SharedKeyLiteAuthentication.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azure.storage.filters;\n\nimport static com.google.common.io.BaseEncoding.base64;\nimport static com.google.common.io.ByteStreams.readBytes;\nimport static org.jclouds.crypto.Macs.asByteProcessor;\nimport static org.jclouds.util.Patterns.NEWLINE_PATTERN;\nimport static org.jclouds.util.Strings2.toInputStream;\n\nimport java.net.URI;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Provider;\nimport jakarta.inject.Singleton;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Maps;\nimport com.google.common.collect.Multimap;\nimport com.google.common.collect.Multimaps;\nimport com.google.common.collect.Multiset;\nimport com.google.common.collect.TreeMultiset;\nimport org.jclouds.Constants;\nimport org.jclouds.azure.storage.config.AuthType;\nimport org.jclouds.azure.storage.util.storageurl.StorageUrlSupplier;\nimport org.jclouds.crypto.Crypto;\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpRequestFilter;\nimport org.jclouds.http.HttpUtils;\nimport org.jclouds.http.Uris;\nimport org.jclouds.http.Uris.UriBuilder;\nimport org.jclouds.http.internal.SignatureWire;\nimport org.jclouds.io.ContentMetadata;\nimport org.jclouds.io.Payload;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.util.Strings2;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Function;\nimport com.google.common.base.Joiner;\nimport com.google.common.base.Strings;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableMap.Builder;\nimport com.google.common.io.ByteProcessor;\nimport com.google.common.net.HttpHeaders;\n\n/**\n * Signs the Azure Storage request.\n * \n * @see <a href= \"http://msdn.microsoft.com/en-us/library/dd179428.aspx\" />\n */\n@Singleton\npublic class SharedKeyLiteAuthentication implements HttpRequestFilter {\n   private static final Collection<String> FIRST_HEADERS_TO_SIGN = ImmutableList.of(HttpHeaders.DATE);\n   private static final Collection<String> FIRST_HEADERS_TO_SIGN_FOR_SHARED_KEY =\n           ImmutableList.of(HttpHeaders.DATE, HttpHeaders.IF_MODIFIED_SINCE, HttpHeaders.IF_MATCH,\n                   HttpHeaders.IF_NONE_MATCH, HttpHeaders.IF_UNMODIFIED_SINCE, HttpHeaders.RANGE);\n   private final SignatureWire signatureWire;\n   private final Supplier<Credentials> creds;\n   private final Provider<String> timeStampProvider;\n   private final Crypto crypto;\n   private final String credential;\n   private final HttpUtils utils;\n   private final URI storageUrl;\n   private final boolean isSAS;\n   private final AuthType authType;\n   private final OAuthFilter oAuthFilter;\n\n   @Resource\n   @Named(Constants.LOGGER_SIGNATURE)\n   Logger signatureLog = Logger.NULL;\n\n   @Inject\n   public SharedKeyLiteAuthentication(SignatureWire signatureWire,\n         @org.jclouds.location.Provider Supplier<Credentials> creds, @TimeStamp Provider<String> timeStampProvider,\n         Crypto crypto, HttpUtils utils, @Named(\"sasAuth\") boolean sasAuthentication,\n         StorageUrlSupplier storageUrlSupplier, AuthType authType,\n         OAuthFilter oAuthFilter) {\n      this.crypto = crypto;\n      this.utils = utils;\n      this.signatureWire = signatureWire;\n      this.storageUrl = storageUrlSupplier.get();\n      this.creds = creds;\n      this.credential = creds.get().credential;\n      this.timeStampProvider = timeStampProvider;\n      this.isSAS = sasAuthentication;\n      this.authType = authType;\n      this.oAuthFilter = oAuthFilter;\n   }\n   \n   /** \n    * this is an updated filter method, which decides whether the SAS or SharedKeyLite \n    * is used and applies the right filtering.  \n    */\n   public HttpRequest filter(HttpRequest request) throws HttpException {\n      if (this.authType == AuthType.AZURE_AD) {\n         request = this.oAuthFilter.filter(request);\n      } else if (this.authType == AuthType.AZURE_SHARED_KEY){\n         request = this.isSAS ? filterSAS(request, this.credential) : filterSharedKey(request);\n      } else {\n         request = this.isSAS ? filterSAS(request, this.credential) : filterKey(request);\n      }\n      utils.logRequest(signatureLog, request, \"<<\");\n      return request;\n   }\n\n   /** \n    * this filter method is applied only for the cases with SAS Authentication. \n    */\n   public HttpRequest filterSAS(HttpRequest request, String credential) throws HttpException, IllegalArgumentException {\n      URI requestUri = request.getEndpoint();\n      String formattedCredential = credential.startsWith(\"?\") ? credential.substring(1) : credential;\n      String initialQuery = requestUri.getQuery();\n      String finalQuery = initialQuery == null ? formattedCredential : initialQuery + \"&\" + formattedCredential;\n      String[] parametersArray = cutUri(requestUri); \n      String containerName = parametersArray[1]; \n      UriBuilder endpoint = Uris.uriBuilder(storageUrl).appendPath(containerName);\n      if (parametersArray.length >= 3) {\n         String[] blobNameParts = Arrays.copyOfRange(parametersArray, 2, parametersArray.length);\n         String blobName = Joiner.on(\"/\").join(blobNameParts);\n         endpoint.appendPath(blobName).query(finalQuery);\n      } else {\n         endpoint.query(\"restype=container&\" + finalQuery);\n      }\n      return removeAuthorizationHeader(\n         replaceDateHeader(request.toBuilder()\n            .endpoint(endpoint.build())\n            .build()));\n   }\n   \n   /**\n    * this is a 'standard' filter method, applied when SharedKeyLite authentication is used. \n    */\n   public HttpRequest filterKey(HttpRequest request) throws HttpException {\n      request = replaceDateHeader(request);\n      String signature = calculateSignature(createStringToSign(request));\n      return replaceAuthorizationHeader(request, signature);\n   }\n\n   /**\n    * this is a 'standard' filter method, applied when SharedKey authentication is used.\n    */\n   public HttpRequest filterSharedKey(HttpRequest request) throws HttpException {\n      request = replaceDateHeader(request);\n      String signature = calculateSignature(createStringToSignForSharedKey(request));\n      return replaceAuthorizationHeaderForSharedKey(request, signature);\n   }\n\n   HttpRequest replaceAuthorizationHeaderForSharedKey(HttpRequest request, String signature) {\n      return request.toBuilder()\n              .replaceHeader(HttpHeaders.AUTHORIZATION, \"SharedKey \" + creds.get().identity + \":\" + signature)\n              .build();\n   }\n\n   HttpRequest replaceAuthorizationHeader(HttpRequest request, String signature) {\n      return request.toBuilder()\n            .replaceHeader(HttpHeaders.AUTHORIZATION, \"SharedKeyLite \" + creds.get().identity + \":\" + signature)\n            .build();\n   }\n   \n   /**\n    * this method removes Authorisation header, since it is not needed for SAS Authentication \n    */\n   HttpRequest removeAuthorizationHeader(HttpRequest request) {\n      return request.toBuilder()\n            .removeHeader(HttpHeaders.AUTHORIZATION)\n            .build();\n   }\n\n   HttpRequest replaceDateHeader(HttpRequest request) {\n      Builder<String, String> builder = ImmutableMap.builder();\n      String date = timeStampProvider.get();\n      builder.put(HttpHeaders.DATE, date);\n      request = request.toBuilder().replaceHeaders(Multimaps.forMap(builder.build())).build();\n      return request;\n   }\n   \n   /**\n    * this is the method to parse container name and blob name from the HttpRequest. \n    */ \n   public String[] cutUri(URI uri) throws IllegalArgumentException {\n      String path = uri.getPath();\n      String[] result = path.split(\"/\");\n      if (result.length < 2) {\n         throw new IllegalArgumentException(\"there is neither ContainerName nor BlobName in the URI path\");\n      }\n      return result;\n   }\n\n   public String createStringToSignForSharedKey(HttpRequest request) {\n      utils.logRequest(signatureLog, request, \">>\");\n      StringBuilder buffer = new StringBuilder();\n      // re-sign the request\n      appendMethod(request, buffer);\n      appendPayloadMetadataForSharedKey(request, buffer);\n      appendHttpHeadersForSharedKey(request, buffer);\n      appendCanonicalizedHeaders(request, buffer);\n      appendCanonicalizedResourceForSharedKey(request, buffer);\n      if (signatureWire.enabled())\n         signatureWire.output(buffer.toString());\n      return buffer.toString();\n   }\n\n   public String createStringToSign(HttpRequest request) {\n      utils.logRequest(signatureLog, request, \">>\");\n      StringBuilder buffer = new StringBuilder();\n      // re-sign the request\n      appendMethod(request, buffer);\n      appendPayloadMetadata(request, buffer);\n      appendHttpHeaders(request, buffer);\n      appendCanonicalizedHeaders(request, buffer);\n      appendCanonicalizedResource(request, buffer);\n      if (signatureWire.enabled())\n         signatureWire.output(buffer.toString());\n      return buffer.toString();\n   }\n\n   private void appendPayloadMetadataForSharedKey(HttpRequest request, StringBuilder buffer) {\n      Payload payload = request.getPayload();\n      if (payload == null) {\n         buffer.append(\"\\n\\n\\n\\n\\n\");\n         return;\n      }\n\n      ContentMetadata contentMetadata = payload.getContentMetadata();\n      buffer.append(Strings.nullToEmpty(contentMetadata.getContentEncoding()))\n              .append(\"\\n\");\n      buffer.append(Strings.nullToEmpty(contentMetadata.getContentLanguage()))\n              .append(\"\\n\");\n      buffer.append(HttpUtils.nullOrZeroToEmpty(contentMetadata.getContentLength()))\n              .append(\"\\n\");\n      buffer.append(HttpUtils.nullToEmpty(contentMetadata.getContentMD5()))\n              .append(\"\\n\");\n      buffer.append(Strings.nullToEmpty(contentMetadata.getContentType()))\n              .append(\"\\n\");\n   }\n\n   private void appendPayloadMetadata(HttpRequest request, StringBuilder buffer) {\n      buffer.append(\n            HttpUtils.nullToEmpty(request.getPayload() == null ? null : request.getPayload().getContentMetadata()\n                  .getContentMD5())).append(\"\\n\");\n      buffer.append(\n            Strings.nullToEmpty(request.getPayload() == null ? null : request.getPayload().getContentMetadata()\n                  .getContentType())).append(\"\\n\");\n   }\n\n   public String calculateSignature(String toSign) throws HttpException {\n      String signature = signString(toSign);\n      if (signatureWire.enabled())\n         signatureWire.input(Strings2.toInputStream(signature));\n      return signature;\n   }\n\n   public String signString(String toSign) {\n      try {\n         ByteProcessor<byte[]> hmacSHA256 = asByteProcessor(crypto.hmacSHA256(base64().decode(creds.get().credential)));\n         return base64().encode(readBytes(toInputStream(toSign), hmacSHA256));\n      } catch (Exception e) {\n         throw new HttpException(\"error signing request\", e);\n      }\n   }\n\n   private void appendMethod(HttpRequest request, StringBuilder toSign) {\n      toSign.append(request.getMethod()).append(\"\\n\");\n   }\n\n   private void appendCanonicalizedHeaders(HttpRequest request, StringBuilder toSign) {\n      // TreeMap == Sort the headers alphabetically.\n      Map<String, String> headers = Maps.newTreeMap();\n      Multimap<String, String> requestHeaders = request.getHeaders();\n      for (String header : requestHeaders.keySet()) {\n         if (header.startsWith(\"x-ms-\")) {\n            String value = Joiner.on(\",\").join(Iterables.transform(requestHeaders.get(header),\n                new Function<String, Object>()\n                {\n                   @Override\n                   public Object apply(final String value) {\n                      return NEWLINE_PATTERN.matcher(value).replaceAll(\"\");\n                   }\n                })\n            );\n            headers.put(header.toLowerCase(), value);\n         }\n      }\n      for (Entry<String, String> entry : headers.entrySet()) {\n         toSign.append(entry.getKey()).append(\":\").append(entry.getValue()).append(\"\\n\");\n      }\n   }\n\n   private void appendHttpHeaders(HttpRequest request, StringBuilder toSign) {\n      for (String header : FIRST_HEADERS_TO_SIGN)\n         toSign.append(HttpUtils.nullToEmpty(request.getHeaders().get(header))).append(\"\\n\");\n   }\n\n   private void appendHttpHeadersForSharedKey(HttpRequest request, StringBuilder toSign) {\n      for (String header : FIRST_HEADERS_TO_SIGN_FOR_SHARED_KEY)\n         toSign.append(HttpUtils.nullToEmpty(request.getHeaders().get(header))).append(\"\\n\");\n   }\n\n   @VisibleForTesting\n   void appendCanonicalizedResource(HttpRequest request, StringBuilder toSign) {\n      // 1. Beginning with an empty string (\"\"), append a forward slash (/), followed by the name of\n      // the identity that owns the resource being accessed.\n      toSign.append(\"/\").append(creds.get().identity);\n      appendUriPath(request, toSign);\n   }\n\n   void appendCanonicalizedResourceForSharedKey(HttpRequest request, StringBuilder toSign) {\n      // 1. Beginning with an empty string (\"\"), append a forward slash (/), followed by the name of\n      // the identity that owns the resource being accessed.\n      toSign.append(\"/\").append(creds.get().identity);\n      // 2. Append the resource's encoded URI path\n      toSign.append(request.getEndpoint().getRawPath());\n      appendQueryParametersForSharedKey(request, toSign);\n   }\n\n   void appendQueryParametersForSharedKey(HttpRequest request, StringBuilder toSign) {\n      // 3. Append each query parameter as a new line\n      Map<String, Multiset<String>> sortedParams = Maps.newTreeMap();\n      if (request.getEndpoint().getQuery() != null) {\n         String[] params = request.getEndpoint().getQuery().split(\"&\");\n         for (String param : params) {\n            String[] paramNameAndValue = param.split(\"=\");\n            String key = paramNameAndValue[0];\n            String value = paramNameAndValue.length > 1 ? paramNameAndValue[1] : \"\";\n            if (sortedParams.containsKey(key)) {\n               sortedParams.get(key).add(value);\n            } else {\n               Multiset<String> values = TreeMultiset.create();\n               values.add(value);\n               sortedParams.put(key, values);\n            }\n         }\n      }\n\n      for (Entry<String, Multiset<String>> entry : sortedParams.entrySet()) {\n         String key = entry.getKey();\n         Multiset<String> values = entry.getValue();\n         toSign.append(\"\\n\");\n         toSign.append(key);\n         toSign.append(\":\");\n         boolean first = true;\n         for (String value : values) {\n            if (!first) {\n               toSign.append(\",\");\n            }\n            toSign.append(value);\n            first = false;\n         }\n      }\n   }\n\n   @VisibleForTesting\n   void appendUriPath(HttpRequest request, StringBuilder toSign) {\n      // 2. Append the resource's encoded URI path\n      toSign.append(request.getEndpoint().getRawPath());\n\n      // If the request URI addresses a component of the\n      // resource, append the appropriate query string. The query string should include the question\n      // mark and the comp parameter (for example, ?comp=metadata). No other parameters should be\n      // included on the query string.\n      if (request.getEndpoint().getQuery() != null) {\n         StringBuilder paramsToSign = new StringBuilder(\"?\");\n\n         String[] params = request.getEndpoint().getQuery().split(\"&\");\n         for (String param : params) {\n            String[] paramNameAndValue = param.split(\"=\");\n\n            if (\"comp\".equals(paramNameAndValue[0])) {\n               paramsToSign.append(param);\n            }\n         }\n\n         if (paramsToSign.length() > 1) {\n            toSign.append(paramsToSign);\n         }\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azure/storage/handlers/AzureStorageClientErrorRetryHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azure.storage.handlers;\n\nimport java.io.ByteArrayInputStream;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\n\nimport org.jclouds.Constants;\nimport org.jclouds.azure.storage.domain.AzureStorageError;\nimport org.jclouds.azure.storage.util.AzureStorageUtils;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpRetryHandler;\nimport org.jclouds.http.HttpUtils;\nimport org.jclouds.http.handlers.BackoffLimitedRetryHandler;\nimport org.jclouds.logging.Logger;\n\nimport com.google.inject.Inject;\n\n/**\n * Handles Retryable responses with error codes in the 4xx range\n */\npublic class AzureStorageClientErrorRetryHandler implements HttpRetryHandler {\n\n   @Inject(optional = true)\n   @Named(Constants.PROPERTY_MAX_RETRIES)\n   private int retryCountLimit = 5;\n\n   private final AzureStorageUtils utils;\n   private final BackoffLimitedRetryHandler backoffHandler;\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   @Inject\n   public AzureStorageClientErrorRetryHandler(BackoffLimitedRetryHandler backoffHandler,\n            AzureStorageUtils utils) {\n      this.backoffHandler = backoffHandler;\n      this.utils = utils;\n   }\n\n   public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) {\n      byte[] content = HttpUtils.closeClientButKeepContentStream(response);\n      command.incrementFailureCount();\n      if (!command.isReplayable()) {\n         logger.warn(\"Cannot retry after server error, command is not replayable: %1$s\", command);\n         return false;\n      } else if (command.getFailureCount() > retryCountLimit) {\n         logger.warn(\n                  \"Cannot retry after server error, command has exceeded retry limit %1$d: %2$s\",\n                  retryCountLimit, command);\n         return false;\n      } else if (response.getStatusCode() == 409) {\n         // Content can be null in the case of HEAD requests\n         if (content != null) {\n            try {\n               AzureStorageError error = utils.parseAzureStorageErrorFromContent(command, response,\n                        new ByteArrayInputStream(content));\n               if (\"ContainerBeingDeleted\".equals(error.getCode())) {\n                  backoffHandler.imposeBackoffExponentialDelay(100L, 3, retryCountLimit, command\n                           .getFailureCount(), command.toString());\n                  return true;\n               }\n            } catch (HttpException e) {\n               logger.warn(e, \"error parsing response: %s\", new String(content));\n            }\n         }\n      }\n      return false;\n   }\n\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azure/storage/handlers/ParseAzureStorageErrorFromXmlContent.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azure.storage.handlers;\n\nimport static org.jclouds.http.HttpUtils.releasePayload;\n\nimport java.io.IOException;\nimport java.util.regex.Pattern;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\n\nimport org.jclouds.azure.storage.AzureStorageResponseException;\nimport org.jclouds.azure.storage.domain.AzureStorageError;\nimport org.jclouds.azure.storage.util.AzureStorageUtils;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.jclouds.util.Strings2;\n\n/**\n * This will parse and set an appropriate exception on the command object.\n * \n * @see AzureStorageError\n */\npublic class ParseAzureStorageErrorFromXmlContent implements HttpErrorHandler {\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   private final AzureStorageUtils utils;\n\n   @Inject\n   public ParseAzureStorageErrorFromXmlContent(AzureStorageUtils utils) {\n      this.utils = utils;\n   }\n\n   public static final Pattern CONTAINER_PATH = Pattern.compile(\"^[/]?([^/]+)$\");\n   public static final Pattern CONTAINER_KEY_PATH = Pattern.compile(\"^[/]?([^/]+)/(.*)$\");\n\n   public void handleError(HttpCommand command, HttpResponse response) {\n      Exception exception = new HttpResponseException(command, response);\n      String message = null;\n      AzureStorageError error = null;\n      try {\n         if (response.getPayload() != null) {\n            String contentType = response.getPayload().getContentMetadata().getContentType();\n            if (contentType != null && (contentType.indexOf(\"xml\") != -1 || contentType.indexOf(\"unknown\") != -1)\n                     && !Long.valueOf(0).equals(response.getPayload().getContentMetadata().getContentLength())) {\n               try {\n                  error = utils.parseAzureStorageErrorFromContent(command, response, response.getPayload().getInput());\n                  if (error != null) {\n                     message = error.getMessage();\n                     exception = new AzureStorageResponseException(command, response, error);\n                  }\n               } catch (RuntimeException e) {\n                  try {\n                     message = Strings2.toStringAndClose(response.getPayload().openStream());\n                     exception = new HttpResponseException(command, response, message);\n                  } catch (IOException e1) {\n                  }\n               }\n            } else {\n               try {\n                  message = Strings2.toStringAndClose(response.getPayload().openStream());\n                  exception = new HttpResponseException(command, response, message);\n               } catch (IOException e) {\n               }\n            }\n         }\n         message = message != null ? message : String.format(\"%s -> %s\", command.getCurrentRequest().getRequestLine(),\n                  response.getStatusLine());\n         exception = refineException(command, response, exception, error, message);\n      } finally {\n         releasePayload(response);\n         command.setException(exception);\n      }\n   }\n\n   protected Exception refineException(HttpCommand command, HttpResponse response, Exception exception,\n            AzureStorageError error, String message) {\n      switch (response.getStatusCode()) {\n         case 400:\n            if (error.getCode().equals(\"InvalidQueryParameterValue\")) {\n                exception = new IllegalArgumentException(message, exception);\n            }\n            break;\n         case 401:\n            exception = new AuthorizationException(message, exception);\n            break;\n         case 404:\n            if (!command.getCurrentRequest().getMethod().equals(\"DELETE\")) {\n               exception = new ResourceNotFoundException(message, exception);\n            }\n            break;\n         case 411:\n            exception = new IllegalArgumentException(message);\n            break;\n      }\n      return exception;\n   }\n\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azure/storage/options/CreateOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azure.storage.options;\n\nimport java.util.Map.Entry;\n\nimport org.jclouds.azure.storage.reference.AzureStorageHeaders;\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.Multimap;\n\n/**\n * Contains common options supported in the REST API for the Create operation. <h2>\n * Usage</h2> The recommended way to instantiate a CreateOptions object is to statically import\n * CreateOptions.* and invoke a static creation method followed by an instance mutator (if\n * needed):\n * <p/>\n * <code>\n * import static CreateOptions.Builder.*\n * import org.jclouds.azure.storage.queue.AzureQueueClient;\n * <p/>\n * AzureQueueClient connection = // get connection\n * Multimap<String,String> metadata = // ...\n * boolean createdWithPublicAcl = connection.createQueue(\"containerName\", withMetadata(metadata));\n * <code> *\n * \n * @see <a href=\"http://msdn.microsoft.com/en-us/library/dd179466.aspx\" />\n */\npublic class CreateOptions extends BaseHttpRequestOptions {\n   public static final CreateOptions NONE = new CreateOptions();\n\n   /**\n    * A name-value pair to associate with the container as metadata.\n    * \n    * Note that these are stored at the server under the prefix: x-ms-meta-\n    */\n   public CreateOptions withMetadata(Multimap<String, String> metadata) {\n      for (Entry<String, String> entry : metadata.entries()) {\n         if (entry.getKey().startsWith(AzureStorageHeaders.USER_METADATA_PREFIX))\n            headers.put(entry.getKey(), entry.getValue());\n         else\n            headers\n                     .put(AzureStorageHeaders.USER_METADATA_PREFIX + entry.getKey(), entry\n                              .getValue());\n      }\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see CreateOptions#withMetadata(Multimap<String, String>)\n       */\n      public static CreateOptions withMetadata(Multimap<String, String> metadata) {\n         CreateOptions options = new CreateOptions();\n         return options.withMetadata(metadata);\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azure/storage/options/ListOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azure.storage.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options used to control paginated results (aka list commands).\n * \n * @see <a href=\"http://msdn.microsoft.com/en-us/library/dd179466.aspx\" />\n */\npublic class ListOptions extends BaseHttpRequestOptions {\n   public static final ListOptions NONE = new ListOptions();\n\n   /**\n    * Include this parameter to specify that the container's metadata be returned as part of the\n    * response body.\n    * \n    * Note that metadata requested with this parameter must be stored in accordance with the naming\n    * restrictions imposed by the 2009-09-19 version of the Blob service. Beginning with this\n    * version, all metadata names must adhere to the naming conventions for C# identifiers.\n    */\n   public ListOptions includeMetadata() {\n      this.queryParameters.replaceValues(\"include\", ImmutableSet.of(\"metadata\"));\n      return this;\n   }\n\n   public boolean getIncludeMetadata() {\n      return getFirstQueryOrNull(\"include\").equals(\"metadata\");\n   }\n\n   /**\n    * Filters the results to return only objects whose name begins with the specified prefix.\n    */\n   public ListOptions prefix(String prefix) {\n      this.queryParameters.put(\"prefix\", checkNotNull(prefix, \"prefix\"));\n      return this;\n   }\n\n   public String getPrefix() {\n      return getFirstQueryOrNull(\"prefix\");\n   }\n\n   /**\n    * A string value that identifies the portion of the list to be returned with the next list\n    * operation. The operation returns a marker value within the response body if the list returned\n    * was not complete. The marker value may then be used in a subsequent call to request the next\n    * set of list items.\n    * <p/>\n    * The marker value is opaque to the client.\n    */\n   public ListOptions marker(String marker) {\n      this.queryParameters.put(\"marker\", checkNotNull(marker, \"marker\"));\n      return this;\n   }\n\n   public String getMarker() {\n      return getFirstQueryOrNull(\"marker\");\n   }\n\n   /**\n    * Specifies the maximum number of containers to return. If maxresults is not specified, the\n    * server will return up to 5,000 items. If the parameter is set to a value greater than 5,000,\n    * the server will return a Bad Request (400) error\n    */\n   public ListOptions maxResults(int maxresults) {\n      checkState(maxresults >= 0, \"maxresults must be >= 0\");\n      checkState(maxresults <= 10000, \"maxresults must be <= 5000\");\n      queryParameters.put(\"maxresults\", Integer.toString(maxresults));\n      return this;\n   }\n\n   public Integer getMaxResults() {\n      String maxresults = getFirstQueryOrNull(\"maxresults\");\n      return (maxresults != null) ? Integer.valueOf(maxresults) : null;\n   }\n\n   public static class Builder {\n      /**\n       * @see ListOptions#includeMetadata()\n       */\n      public static ListOptions includeMetadata() {\n         ListOptions options = new ListOptions();\n         return options.includeMetadata();\n      }\n\n      /**\n       * @see ListOptions#prefix(String)\n       */\n      public static ListOptions prefix(String prefix) {\n         ListOptions options = new ListOptions();\n         return options.prefix(prefix);\n      }\n\n      /**\n       * @see ListOptions#marker(String)\n       */\n      public static ListOptions marker(String marker) {\n         ListOptions options = new ListOptions();\n         return options.marker(marker);\n      }\n\n      /**\n       * @see ListOptions#maxResults(long)\n       */\n      public static ListOptions maxResults(int maxKeys) {\n         ListOptions options = new ListOptions();\n         return options.maxResults(maxKeys);\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azure/storage/reference/AzureStorageHeaders.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azure.storage.reference;\n\n/**\n * Additional headers specified by Azure Storage REST API.\n * \n * @see <a href=\"http://msdn.microsoft.com/en-us/library/dd179357.aspx\" />\n */\npublic final class AzureStorageHeaders {\n\n   public static final String CACHE_CONTROL = \"x-ms-blob-cache-control\";\n   public static final String CONTENT_DISPOSITION = \"x-ms-blob-content-disposition\";\n   public static final String CONTENT_ENCODING = \"x-ms-blob-content-encoding\";\n   public static final String CONTENT_LANGUAGE = \"x-ms-blob-content-language\";\n   public static final String CONTENT_TYPE = \"x-ms-blob-content-type\";\n\n   public static final String USER_METADATA_PREFIX = \"x-ms-meta-\";\n\n   public static final String COPY_SOURCE = \"x-ms-copy-source\";\n   public static final String COPY_SOURCE_IF_MODIFIED_SINCE = \"x-ms-source-if-modified-since\";\n   public static final String COPY_SOURCE_IF_UNMODIFIED_SINCE = \"x-ms-source-if-unmodified-since\";\n   public static final String COPY_SOURCE_IF_MATCH = \"x-ms-source-if-match\";\n   public static final String COPY_SOURCE_IF_NONE_MATCH = \"x-ms-source-if-none-match\";\n\n   public static final String REQUEST_ID = \"x-ms-request-id\";\n   public static final String VERSION = \"x-ms-version\";\n\n   private AzureStorageHeaders() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azure/storage/util/AzureStorageUtils.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azure.storage.util;\n\nimport java.io.InputStream;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Provider;\n\nimport org.jclouds.azure.storage.domain.AzureStorageError;\nimport org.jclouds.azure.storage.filters.SharedKeyLiteAuthentication;\nimport org.jclouds.azure.storage.reference.AzureStorageHeaders;\nimport org.jclouds.azure.storage.xml.ErrorHandler;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseSax;\n\n/**\n * Encryption, Hashing, and IO Utilities needed to sign and verify Azure Storage requests and\n * responses.\n */\npublic class AzureStorageUtils {\n\n   @Inject\n   SharedKeyLiteAuthentication signer;\n\n   @Inject\n   ParseSax.Factory factory;\n\n   @Inject\n   Provider<ErrorHandler> errorHandlerProvider;\n\n   public AzureStorageError parseAzureStorageErrorFromContent(HttpCommand command,\n            HttpResponse response, InputStream content) throws HttpException {\n      AzureStorageError error = factory.create(errorHandlerProvider.get()).parse(content);\n      error.setRequestId(response.getFirstHeaderOrNull(AzureStorageHeaders.REQUEST_ID));\n      if (\"AuthenticationFailed\".equals(error.getCode())) {\n         // this signature is incorrect for URLs from AzureBlobRequestSigner\n         error.setStringSigned(signer.createStringToSign(command.getCurrentRequest()));\n         error.setSignature(signer.signString(error.getStringSigned()));\n      }\n      return error;\n   }\n\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azure/storage/util/storageurl/AppendAccountToEndpoint.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azure.storage.util.storageurl;\n\nimport com.google.common.base.Preconditions;\nimport com.google.common.base.Supplier;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.location.Provider;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport static org.jclouds.azure.storage.util.storageurl.TrailingSlashUtil.ensureTrailingSlash;\nimport java.net.URI;\n\n@Singleton\npublic class AppendAccountToEndpoint implements StorageUrlSupplier {\n\n   private final Supplier<URI> endpointSupplier;\n   private final Supplier<Credentials> credentialsSupplier;\n\n   @Inject\n   public AppendAccountToEndpoint(@Provider Supplier<URI> endpointSupplier, @Provider Supplier<Credentials> credentialsSupplier) {\n      this.endpointSupplier = endpointSupplier;\n      this.credentialsSupplier = credentialsSupplier;\n   }\n\n   @Override\n   public URI get() {\n\n      URI endpoint = endpointSupplier.get();\n\n      Preconditions.checkNotNull(endpoint, \"An endpoint must be configured in order to use AppendAccountToEndpoint module\");\n\n      String endpointTrailingSlash = new StringBuilder(ensureTrailingSlash(endpoint))\n            .append(credentialsSupplier.get().identity)\n            .append(\"/\")\n            .toString();\n\n      return URI.create(endpointTrailingSlash);\n      \n   }\n\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azure/storage/util/storageurl/StorageAccountInVhost.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azure.storage.util.storageurl;\n\nimport com.google.common.base.Supplier;\nimport org.jclouds.azure.storage.config.AuthType;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.location.Provider;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\nimport java.net.URI;\nimport static org.jclouds.azure.storage.config.AzureStorageProperties.ACCOUNT;\nimport static org.jclouds.azure.storage.util.storageurl.TrailingSlashUtil.ensureTrailingSlash;\n\n@Singleton\npublic class StorageAccountInVhost implements StorageUrlSupplier {\n\n   private final Supplier<URI> endpointSupplier;\n   private final Supplier<Credentials> credentialsSupplier;\n   private final AuthType authType;\n   private final String account;\n\n   @Inject\n   public StorageAccountInVhost(@Provider Supplier<URI> endpointSupplier,\n                                @Provider Supplier<Credentials> credentialsSupplier,\n                                AuthType authType,\n                                @Named(ACCOUNT) String account) {\n      this.endpointSupplier = endpointSupplier;\n      this.credentialsSupplier = credentialsSupplier;\n      this.authType = authType;\n      this.account = account;\n   }\n\n   @Override\n   public URI get() {\n\n      URI endpoint = endpointSupplier.get();\n\n      String uri = endpoint == null ? buildUri() : ensureTrailingSlash(endpoint);\n\n      return URI.create(uri);\n      \n   }\n\n   private String buildUri() {\n      String account = this.account;\n      if (account == null) {\n         account = credentialsSupplier.get().identity;\n      }\n      return \"https://\" + account + \".blob.core.windows.net/\";\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azure/storage/util/storageurl/StorageUrlSupplier.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azure.storage.util.storageurl;\n\nimport com.google.common.base.Supplier;\nimport com.google.inject.ImplementedBy;\n\nimport java.net.URI;\n\n@ImplementedBy(StorageAccountInVhost.class)\npublic interface StorageUrlSupplier extends Supplier<URI> {\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azure/storage/util/storageurl/TrailingSlashUtil.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azure.storage.util.storageurl;\n\nimport java.net.URI;\n\npublic class TrailingSlashUtil {\n\n   static String ensureTrailingSlash(URI endpointUri) {\n      String endpoint = endpointUri.toString();\n      return endpoint.endsWith(\"/\") ? endpoint : endpoint + \"/\";\n   }\n\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azure/storage/xml/ErrorHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azure.storage.xml;\n\nimport org.jclouds.azure.storage.domain.AzureStorageError;\nimport org.jclouds.http.functions.ParseSax;\n\n/**\n * Parses the error from the Amazon S3 REST API.\n * \n * @see <a\n *      href=\"http://docs.amazonwebservices.com/AmazonS3/2006-03-01/index.html?UsingRESTError.html\"\n *      />\n */\npublic class ErrorHandler extends ParseSax.HandlerWithResult<AzureStorageError> {\n\n   private AzureStorageError error = new AzureStorageError();\n   private StringBuilder currentText = new StringBuilder();\n\n   public AzureStorageError getResult() {\n      return error;\n   }\n\n   public void endElement(String uri, String name, String qName) {\n\n      if (qName.equals(\"Code\")) {\n         error.setCode(currentText.toString().trim());\n      } else if (qName.equals(\"Message\")) {\n         error.setMessage(currentText.toString().trim());\n      } else if (!qName.equals(\"Error\")) {\n         error.getDetails().put(qName, currentText.toString());\n      }\n      currentText.setLength(0);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/AzureBlobApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob;\n\nimport static org.jclouds.azure.storage.config.AzureStorageProperties.ACCOUNT;\nimport static org.jclouds.azure.storage.config.AzureStorageProperties.AUTH_TYPE;\nimport static org.jclouds.azure.storage.config.AzureStorageProperties.TENANT_ID;\nimport static org.jclouds.blobstore.reference.BlobStoreConstants.PROPERTY_USER_METADATA_PREFIX;\nimport static org.jclouds.reflect.Reflection2.typeToken;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.azure.storage.config.AuthType;\nimport org.jclouds.azureblob.blobstore.config.AzureBlobStoreContextModule;\nimport org.jclouds.azureblob.config.AzureBlobHttpApiModule;\nimport org.jclouds.blobstore.BlobStoreContext;\nimport org.jclouds.oauth.v2.config.OAuthModule;\nimport org.jclouds.rest.internal.BaseHttpApiMetadata;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\npublic class AzureBlobApiMetadata extends BaseHttpApiMetadata {\n\n   private static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromApiMetadata(this);\n   }\n\n   public AzureBlobApiMetadata() {\n      this(builder());\n   }\n\n   protected AzureBlobApiMetadata(Builder builder) {\n      super(builder);\n   }\n  \n   public static Properties defaultProperties() {\n      Properties properties = BaseHttpApiMetadata.defaultProperties();\n      properties.setProperty(PROPERTY_USER_METADATA_PREFIX, \"x-ms-meta-\");\n      properties.setProperty(AUTH_TYPE, AuthType.AZURE_KEY.toString());\n      properties.setProperty(ACCOUNT, \"\");\n      properties.setProperty(TENANT_ID, \"\");\n      return properties;\n   }\n   \n   public static class Builder extends BaseHttpApiMetadata.Builder<AzureBlobClient, Builder> {\n      protected Builder() {\n         super(AzureBlobClient.class);\n         id(\"azureblob\")\n         .name(\"Microsoft Azure Blob Service API\")\n         .identityName(\"Account Name\")\n         .credentialName(\"Access Key\")\n         .version(\"2017-11-09\")\n         .defaultEndpoint(\"https://${jclouds.identity}.blob.core.windows.net\")\n         .documentation(URI.create(\"http://msdn.microsoft.com/en-us/library/dd135733.aspx\"))\n         .defaultProperties(AzureBlobApiMetadata.defaultProperties())\n         .view(typeToken(BlobStoreContext.class))\n         .defaultModules(ImmutableSet.<Class<? extends Module>>of(\n                 AzureBlobHttpApiModule.class,\n                 AzureBlobStoreContextModule.class,\n                 OAuthModule.class));\n      }\n      \n      @Override\n      public AzureBlobApiMetadata build() {\n         return new AzureBlobApiMetadata(this);\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/AzureBlobClient.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob;\n\nimport static com.google.common.net.HttpHeaders.EXPECT;\n\nimport java.io.Closeable;\nimport java.net.URI;\nimport java.util.List;\nimport java.util.Map;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.HEAD;\nimport jakarta.ws.rs.HeaderParam;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.QueryParam;\n\nimport org.jclouds.Fallbacks.TrueOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.azure.storage.domain.BoundedSet;\nimport org.jclouds.azure.storage.filters.SharedKeyLiteAuthentication;\nimport org.jclouds.azure.storage.options.ListOptions;\nimport org.jclouds.azure.storage.reference.AzureStorageHeaders;\nimport org.jclouds.azureblob.AzureBlobFallbacks.FalseIfContainerAlreadyExists;\nimport org.jclouds.azureblob.binders.BindAzureBlobMetadataToRequest;\nimport org.jclouds.azureblob.binders.BindAzureBlobMetadataToMultipartRequest;\nimport org.jclouds.azureblob.binders.BindAzureBlocksToRequest;\nimport org.jclouds.azureblob.binders.BindAzureContentMetadataToRequest;\nimport org.jclouds.azureblob.binders.BindAzureCopyOptionsToRequest;\nimport org.jclouds.azureblob.binders.BindPublicAccessToRequest;\nimport org.jclouds.azureblob.domain.AccessTier;\nimport org.jclouds.azureblob.domain.AzureBlob;\nimport org.jclouds.azureblob.domain.BlobProperties;\nimport org.jclouds.azureblob.domain.ContainerProperties;\nimport org.jclouds.azureblob.domain.ListBlobBlocksResponse;\nimport org.jclouds.azureblob.domain.ListBlobsResponse;\nimport org.jclouds.azureblob.domain.PublicAccess;\nimport org.jclouds.azureblob.functions.BlobName;\nimport org.jclouds.azureblob.functions.ParseBlobFromHeadersAndHttpContent;\nimport org.jclouds.azureblob.functions.ParseBlobPropertiesFromHeaders;\nimport org.jclouds.azureblob.functions.ParseContainerPropertiesFromHeaders;\nimport org.jclouds.azureblob.functions.ParsePublicAccessHeader;\nimport org.jclouds.azureblob.options.CopyBlobOptions;\nimport org.jclouds.azureblob.options.CreateContainerOptions;\nimport org.jclouds.azureblob.options.ListBlobsOptions;\nimport org.jclouds.azureblob.predicates.validators.BlockIdValidator;\nimport org.jclouds.azureblob.predicates.validators.ContainerNameValidator;\nimport org.jclouds.azureblob.xml.AccountNameEnumerationResultsHandler;\nimport org.jclouds.azureblob.xml.BlobBlocksResultsHandler;\nimport org.jclouds.azureblob.xml.ContainerNameEnumerationResultsHandler;\nimport org.jclouds.blobstore.BlobStoreFallbacks.FalseOnContainerNotFound;\nimport org.jclouds.blobstore.BlobStoreFallbacks.FalseOnKeyNotFound;\nimport org.jclouds.blobstore.BlobStoreFallbacks.NullOnContainerNotFound;\nimport org.jclouds.blobstore.BlobStoreFallbacks.NullOnKeyNotFound;\nimport org.jclouds.blobstore.binders.BindMapToHeadersWithPrefix;\nimport org.jclouds.http.functions.ParseETagHeader;\nimport org.jclouds.http.options.GetOptions;\nimport org.jclouds.io.ContentMetadata;\nimport org.jclouds.io.Payload;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.Headers;\nimport org.jclouds.rest.annotations.ParamParser;\nimport org.jclouds.rest.annotations.ParamValidators;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SkipEncoding;\nimport org.jclouds.rest.annotations.XMLResponseParser;\n\nimport com.google.inject.Provides;\n\n/** Provides access to Azure Blob via their REST API.  */\n@RequestFilters(SharedKeyLiteAuthentication.class)\n@Headers(keys = AzureStorageHeaders.VERSION, values = \"{jclouds.api-version}\")\n@SkipEncoding({ '/', '$' })\n@Path(\"/\")\npublic interface AzureBlobClient extends Closeable {\n   @Provides\n   AzureBlob newBlob();\n\n   /**\n    * The List Containers operation returns a list of the containers under the specified identity.\n    * <p />\n    * The 2009-07-17 version of the List Containers operation times out after 30 seconds.\n    * \n    * @param listOptions\n    *           controls the number or type of results requested\n    * @see ListOptions\n    */\n   @Named(\"ListContainers\")\n   @GET\n   @XMLResponseParser(AccountNameEnumerationResultsHandler.class)\n   @QueryParams(keys = \"comp\", values = \"list\")\n   BoundedSet<ContainerProperties> listContainers(ListOptions... listOptions);\n\n\n   /**\n    * The Create Container operation creates a new container under the specified identity. If the\n    * container with the same name already exists, the operation fails.\n    * <p/>\n    * The container resource includes metadata and properties for that container. It does not\n    * include a list of the blobs contained by the container.\n    * \n    * @return true, if the bucket was created or false, if the container was already present\n    * \n    * @see CreateContainerOptions\n    * \n    */\n   @Named(\"CreateContainer\")\n   @PUT\n   @Path(\"{container}\")\n   @Fallback(FalseIfContainerAlreadyExists.class)\n   @QueryParams(keys = \"restype\", values = \"container\")\n   boolean createContainer(@PathParam(\"container\") @ParamValidators(ContainerNameValidator.class) String container,\n         CreateContainerOptions... options);\n\n\n   /**\n    * The Get Container Properties operation returns all user-defined metadata and system properties\n    * for the specified container. The data returned does not include the container's list of blobs.\n    */\n   @Named(\"GetContainerProperties\")\n   @HEAD\n   @Path(\"{container}\")\n   @QueryParams(keys = \"restype\", values = \"container\")\n   @ResponseParser(ParseContainerPropertiesFromHeaders.class)\n   @Fallback(NullOnContainerNotFound.class)\n   ContainerProperties getContainerProperties(\n         @PathParam(\"container\") @ParamValidators(ContainerNameValidator.class) String container);\n\n\n   /**\n    * Issues a HEAD command to determine if the container exists or not.\n    */\n   @Named(\"GetContainerProperties\")\n   @HEAD\n   @Path(\"{container}\")\n   @QueryParams(keys = \"restype\", values = \"container\")\n   @Fallback(FalseOnContainerNotFound.class)\n   boolean containerExists(@PathParam(\"container\") @ParamValidators(ContainerNameValidator.class) String container);\n\n   /**\n    * The Set Container Metadata operation sets one or more user-defined name/value pairs for the\n    * specified container. <h4>Remarks</h4>\n    * \n    * \n    * Calling the Set Container Metadata operation overwrites all existing metadata that is\n    * associated with the container. It's not possible to modify an individual name/value pair.\n    * <p/>\n    * You may also set metadata for a container at the time it is created.\n    * <p/>\n    * Calling Set Container Metadata updates the ETag for the container.\n    */\n   @Named(\"SetContainerMetadata\")\n   @PUT\n   @Path(\"{container}\")\n   @QueryParams(keys = { \"restype\", \"comp\" }, values = { \"container\", \"metadata\" })\n   void setResourceMetadata(\n         @PathParam(\"container\") @ParamValidators(ContainerNameValidator.class) String container,\n         @BinderParam(BindMapToHeadersWithPrefix.class) Map<String, String> metadata);\n\n\n   /**\n    * The Delete Container operation marks the specified container for deletion. The container and\n    * any blobs contained within it are later deleted during garbage collection.\n    * <p/>\n    * When a container is deleted, a container with the same name cannot be created for at least 30\n    * seconds; the container may not be available for more than 30 seconds if the service is still\n    * processing the request. While the container is being deleted, attempts to create a container\n    * of the same name will fail with status code 409 (Conflict), with the service returning\n    * additional error information indicating that the container is being deleted. All other\n    * operations, including operations on any blobs under the container, will fail with status code\n    * 404 (Not Found) while the container is being deleted.\n    * \n    */\n   @Named(\"DeleteContainer\")\n   @DELETE\n   @Path(\"{container}\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   @QueryParams(keys = \"restype\", values = \"container\")\n   void deleteContainer(@PathParam(\"container\") @ParamValidators(ContainerNameValidator.class) String container);\n\n   /**\n    * The root container is a default container that may be inferred from a URL requesting a blob\n    * resource. The root container makes it possible to reference a blob from the top level of the\n    * storage identity hierarchy, without referencing the container name.\n    * <p/>\n    * The container resource includes metadata and properties for that container. It does not\n    * include a list of the blobs contained by the container.\n    * \n    * @see CreateContainerOptions\n    * \n    */\n   @Named(\"CreateContainer\")\n   @PUT\n   @Path(\"$root\")\n   @Fallback(FalseIfContainerAlreadyExists.class)\n   @QueryParams(keys = \"restype\", values = \"container\")\n   boolean createRootContainer(CreateContainerOptions... options);\n\n   /**\n    * Returns whether data in the container may be accessed publicly and the level of access\n    */\n   @Named(\"GetContainerACL\")\n   @HEAD\n   @Path(\"{container}\")\n   @QueryParams(keys = { \"restype\", \"comp\" }, values = { \"container\", \"acl\" })\n   @ResponseParser(ParsePublicAccessHeader.class)\n   @Fallback(NullOnContainerNotFound.class)\n   PublicAccess getPublicAccessForContainer(\n         @PathParam(\"container\") @ParamValidators(ContainerNameValidator.class) String container);\n\n   /**\n    * Returns whether data in the container may be accessed publicly and the level of access\n    */\n   @Named(\"SetContainerACL\")\n   @PUT\n   @Path(\"{container}\")\n   @QueryParams(keys = { \"restype\", \"comp\" }, values = { \"container\", \"acl\" })\n   @ResponseParser(ParseETagHeader.class)\n   String setPublicAccessForContainer(\n         @PathParam(\"container\") @ParamValidators(ContainerNameValidator.class) String container,\n         @BinderParam(BindPublicAccessToRequest.class) PublicAccess access);\n\n   /**\n    * The Delete Container operation marks the specified container for deletion. The container and\n    * any blobs contained within it are later deleted during garbage collection. <h4>Remarks</h4>\n    * When a container is deleted, a container with the same name cannot be created for at least 30\n    * seconds; the container may not be available for more than 30 seconds if the service is still\n    * processing the request. While the container is being deleted, attempts to create a container\n    * of the same name will fail with status code 409 (Conflict), with the service returning\n    * additional error information indicating that the container is being deleted. All other\n    * operations, including operations on any blobs under the container, will fail with status code\n    * 404 (Not Found) while the container is being deleted.\n    * \n    * @see #deleteContainer(String)\n    * @see #createRootContainer(CreateContainerOptions...)\n    */\n   @Named(\"DeleteContainer\")\n   @DELETE\n   @Path(\"$root\")\n   @Fallback(TrueOnNotFoundOr404.class)\n   @QueryParams(keys = \"restype\", values = \"container\")\n   void deleteRootContainer();\n\n   /**\n    * The List Blobs operation enumerates the list of blobs under the specified container.\n    * <p/>\n    * <h4>Authorization</h4>\n    * \n    * If the container's access control list (ACL) is set to allow anonymous access, any client may\n    * call this operation.\n    * <h4>Remarks</h4>\n    * \n    * If you specify a value for the maxresults parameter and the number of blobs to return exceeds\n    * this value, or exceeds the default value for maxresults, the response body will contain a\n    * NextMarker element that indicates the next blob to return on a subsequent request. To return\n    * the next set of items, specify the value of NextMarker as the marker parameter on the URI for\n    * the subsequent request.\n    * <p/>\n    * Note that the value of NextMarker should be treated as opaque.\n    * <p/>\n    * The delimiter parameter enables the caller to traverse the blob keyspace by using a\n    * user-configured delimiter. The delimiter may be a single character or a string. When the\n    * request includes this parameter, the operation returns a BlobPrefix element. The BlobPrefix\n    * element is returned in place of all blobs whose keys begin with the same substring up to the\n    * appearance of the delimiter character. The value of the BlobPrefix element is\n    * substring+delimiter, where substring is the common substring that begins one or more blob\n    * keys, and delimiter is the value of the delimiter parameter.\n    * <p/>\n    * You can use the value of BlobPrefix to make a subsequent call to list the blobs that begin\n    * with this prefix, by specifying the value of BlobPrefix for the prefix parameter on the\n    * request URI. In this way, you can traverse a virtual hierarchy of blobs as though it were a\n    * file system.\n    * <p/>\n    * Note that each BlobPrefix element returned counts toward the maximum result, just as each Blob\n    * element does.\n    * <p/>\n    * Blobs are listed in alphabetical order in the response body.\n    */\n   @Named(\"ListBlobs\")\n   @GET\n   @XMLResponseParser(ContainerNameEnumerationResultsHandler.class)\n   @Path(\"{container}\")\n   @QueryParams(keys = { \"restype\", \"comp\" }, values = { \"container\", \"list\" })\n   ListBlobsResponse listBlobs(@PathParam(\"container\") @ParamValidators(ContainerNameValidator.class) String container,\n         ListBlobsOptions... options);\n\n\n   @Named(\"ListBlobs\")\n   @GET\n   @XMLResponseParser(ContainerNameEnumerationResultsHandler.class)\n   @Path(\"$root\")\n   @QueryParams(keys = { \"restype\", \"comp\" }, values = { \"container\", \"list\" })\n   ListBlobsResponse listBlobs(ListBlobsOptions... options);\n\n   /**\n    * The Put Blob operation creates a new blob or updates the content of an existing blob.\n    * <p/>\n    * Updating an existing blob overwrites any existing metadata on the blob. Partial updates are\n    * not supported; the content of the existing blob is overwritten with the content of the new\n    * blob.\n    * <p/>\n    * <h4>Remarks</h4>\n    * The maximum upload size for a blob is 256 MB. If your blob is larger than 256 MB, you may upload\n    * it as a set of blocks. For more information, see the Put Block and Put Block List operations.\n    * <p/>\n    * If you attempt to upload a blob that is larger than 256 MB, the service returns status code 413\n    * (Request Payload Too Large). The Blob service also returns additional information about the\n    * error in the response, including the maximum blob size permitted in bytes.\n    */\n   @Named(\"PutBlob\")\n   @PUT\n   @Path(\"{container}/{name}\")\n   @Headers(keys = EXPECT, values = \"100-continue\")\n   @ResponseParser(ParseETagHeader.class)\n   String putBlob(@PathParam(\"container\") @ParamValidators(ContainerNameValidator.class) String container,\n         @PathParam(\"name\") @ParamParser(BlobName.class) @BinderParam(BindAzureBlobMetadataToRequest.class)\n         AzureBlob object);\n\n\n   /**\n    * The Get Blob operation reads or downloads a blob from the system, including its metadata and\n    * properties.\n    */\n   @Named(\"GetBlob\")\n   @GET\n   @ResponseParser(ParseBlobFromHeadersAndHttpContent.class)\n   @Fallback(NullOnKeyNotFound.class)\n   @Path(\"{container}/{name}\")\n   AzureBlob getBlob(@PathParam(\"container\") @ParamValidators(ContainerNameValidator.class) String container,\n         @PathParam(\"name\") String name, GetOptions... options);\n\n   /**\n    *  The Put Block operation creates a block blob on Azure which can be later assembled into\n    *  a single, large blob object with the Put Block List operation.\n    */\n   @Named(\"PutBlock\")\n   @PUT\n   @Path(\"{container}/{name}\")\n   @QueryParams(keys = { \"comp\" }, values = { \"block\" })\n   void putBlock(@PathParam(\"container\") @ParamValidators(ContainerNameValidator.class) String container,\n         @PathParam(\"name\") String name,\n         @QueryParam(\"blockid\") @ParamValidators(BlockIdValidator.class) String blockId, Payload part);\n\n\n   /**\n    *  The Put Block List assembles a list of blocks previously uploaded with Put Block into a single\n    *  blob. Blocks are either already committed to a blob or uncommitted. The blocks ids passed here\n    *  are searched for first in the uncommitted block list; then committed using the \"latest\" strategy.\n    *\n    *  @deprecated call putBlockList(String, AzureBlob, List&lt;String&gt;) instead\n    */\n   @Deprecated\n   @Named(\"PutBlockList\")\n   @PUT\n   @Path(\"{container}/{name}\")\n   @ResponseParser(ParseETagHeader.class)\n   @QueryParams(keys = { \"comp\" }, values = { \"blocklist\" })\n   String putBlockList(@PathParam(\"container\") @ParamValidators(ContainerNameValidator.class) String container,\n         @PathParam(\"name\") String name,\n         @BinderParam(BindAzureBlocksToRequest.class) List<String> blockIdList);\n\n   /**\n    *  The Put Block List assembles a list of blocks previously uploaded with Put Block into a single\n    *  blob. Blocks are either already committed to a blob or uncommitted. The blocks ids passed here\n    *  are searched for first in the uncommitted block list; then committed using the \"latest\" strategy.\n    */\n   @Named(\"PutBlockList\")\n   @PUT\n   @Path(\"{container}/{name}\")\n   @ResponseParser(ParseETagHeader.class)\n   @QueryParams(keys = { \"comp\" }, values = { \"blocklist\" })\n   String putBlockList(@PathParam(\"container\") @ParamValidators(ContainerNameValidator.class) String container,\n         @PathParam(\"name\") @ParamParser(BlobName.class) @BinderParam(BindAzureBlobMetadataToMultipartRequest.class) AzureBlob object,\n         @BinderParam(BindAzureBlocksToRequest.class) List<String> blockIdList);\n\n   @Deprecated\n   @Named(\"GetBlockList\")\n   @GET\n   @Path(\"{container}/{name}\")\n   @XMLResponseParser(BlobBlocksResultsHandler.class)\n   @QueryParams(keys = { \"comp\", \"blocklisttype\" }, values = { \"blocklist\", \"all\" })\n   ListBlobBlocksResponse getBlockList(\n         @PathParam(\"container\") @ParamValidators(ContainerNameValidator.class) String container,\n         @PathParam(\"name\") String name);\n\n   @Named(\"GetBlockList\")\n   @GET\n   @Path(\"{container}/{name}\")\n   @XMLResponseParser(BlobBlocksResultsHandler.class)\n   @QueryParams(keys = { \"comp\" }, values = { \"blocklist\" })\n   ListBlobBlocksResponse getBlockList(\n         @PathParam(\"container\") @ParamValidators(ContainerNameValidator.class) String container,\n         @PathParam(\"name\") String name,\n         // valid values are committed, uncommitted, or all\n         @QueryParam(\"blocklisttype\") String blockListType);\n\n   /**\n    * The Get Blob Properties operation returns all user-defined metadata, standard HTTP properties,\n    * and system properties for the blob. It does not return the content of the blob.\n    */\n   @Named(\"GetBlobProperties\")\n   @HEAD\n   @ResponseParser(ParseBlobPropertiesFromHeaders.class)\n   @Fallback(NullOnKeyNotFound.class)\n   @Path(\"{container}/{name}\")\n   BlobProperties getBlobProperties(\n         @PathParam(\"container\") @ParamValidators(ContainerNameValidator.class) String container,\n         @PathParam(\"name\") String name);\n\n   @Named(\"SetBlobProperties\")\n   @PUT\n   @Path(\"{container}/{name}\")\n   @QueryParams(keys = { \"comp\" }, values = { \"properties\" })\n   @ResponseParser(ParseETagHeader.class)\n   String setBlobProperties(\n         @PathParam(\"container\") @ParamValidators(ContainerNameValidator.class) String container,\n         @PathParam(\"name\") String name,\n         @BinderParam(BindAzureContentMetadataToRequest.class) ContentMetadata contentMetadata);\n\n   @Named(\"SetBlobMetadata\")\n   @PUT\n   @Path(\"{container}/{name}\")\n   @QueryParams(keys = { \"comp\" }, values = { \"metadata\" })\n   @ResponseParser(ParseETagHeader.class)\n   String setBlobMetadata(\n         @PathParam(\"container\") @ParamValidators(ContainerNameValidator.class) String container,\n         @PathParam(\"name\") String name, @BinderParam(BindMapToHeadersWithPrefix.class) Map<String, String> metadata);\n\n   @Named(\"SetAccessTier\")\n   @PUT\n   @Path(\"{container}/{name}\")\n   @QueryParams(keys = { \"comp\" }, values = { \"tier\" })\n   void setBlobTier(\n         @PathParam(\"container\") @ParamValidators(ContainerNameValidator.class) String container,\n         @PathParam(\"name\") String name, @HeaderParam(\"x-ms-access-tier\") AccessTier tier);\n\n   /**\n    * The Delete Blob operation marks the specified blob for deletion. The blob is later deleted\n    * during garbage collection.\n    */\n   @Named(\"DeleteBlob\")\n   @DELETE\n   @Fallback(VoidOnNotFoundOr404.class)\n   @Path(\"{container}/{name}\")\n   void deleteBlob(\n         @PathParam(\"container\") @ParamValidators(ContainerNameValidator.class) String container,\n         @PathParam(\"name\") String name);\n   /**\n    * @throws org.jclouds.blobstore.ContainerNotFoundException if the container is not present.\n    */\n   @Named(\"GetBlobProperties\")\n   @HEAD\n   @Fallback(FalseOnKeyNotFound.class)\n   @Path(\"{container}/{name}\")\n   boolean blobExists(\n         @PathParam(\"container\") @ParamValidators(ContainerNameValidator.class) String container,\n         @PathParam(\"name\") String name);\n\n   /**\n    * @throws ContainerNotFoundException if the container is not present.\n    */\n   @Named(\"CopyBlob\")\n   @PUT\n   @Path(\"{toContainer}/{toName}\")\n   @Headers(keys = AzureStorageHeaders.COPY_SOURCE, values = \"{copySource}\")\n   @ResponseParser(ParseETagHeader.class)\n   String copyBlob(\n         @PathParam(\"copySource\") URI copySource,\n         @PathParam(\"toContainer\") @ParamValidators(ContainerNameValidator.class) String toContainer, @PathParam(\"toName\") String toName,\n         @BinderParam(BindAzureCopyOptionsToRequest.class) CopyBlobOptions options);\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/AzureBlobFallbacks.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Throwables.propagate;\n\nimport org.jclouds.Fallback;\nimport org.jclouds.azure.storage.AzureStorageResponseException;\n\npublic final class AzureBlobFallbacks {\n   private AzureBlobFallbacks() {\n   }\n\n   public static final class FalseIfContainerAlreadyExists implements Fallback<Boolean> {\n      @Override\n      public Boolean createOrPropagate(Throwable t) throws Exception {\n         if (checkNotNull(t, \"throwable\") instanceof AzureStorageResponseException) {\n            AzureStorageResponseException responseException = AzureStorageResponseException.class.cast(t);\n            if (\"ContainerAlreadyExists\".equals(responseException.getError().getCode())) {\n               return false;\n            }\n         }\n         throw propagate(t);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/AzureBlobProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\n\nimport com.google.auto.service.AutoService;\n\nimport static org.jclouds.azure.storage.config.AzureStorageProperties.ACCOUNT;\nimport static org.jclouds.azure.storage.config.AzureStorageProperties.TENANT_ID;\nimport static org.jclouds.oauth.v2.config.CredentialType.CLIENT_CREDENTIALS_SECRET;\nimport static org.jclouds.oauth.v2.config.OAuthProperties.CREDENTIAL_TYPE;\nimport static org.jclouds.oauth.v2.config.OAuthProperties.RESOURCE;\n\n/**\n * Implementation of {@link org.jclouds.types.ProviderMetadata} for Microsoft Azure Blob Service.\n */\n@AutoService(ProviderMetadata.class)\npublic class AzureBlobProviderMetadata extends BaseProviderMetadata {\n   \n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromProviderMetadata(this);\n   }\n\n   public AzureBlobProviderMetadata() {\n      super(builder());\n   }\n\n   public AzureBlobProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = new Properties();\n      properties.put(\"oauth.endpoint\", \"https://login.microsoft.com/${\" + TENANT_ID + \"}/oauth2/token\");\n      properties.put(RESOURCE, \"https://storage.azure.com\");\n      properties.put(CREDENTIAL_TYPE, CLIENT_CREDENTIALS_SECRET.toString());\n      properties.put(ACCOUNT, \"${jclouds.identity}\");\n      return properties;\n   }\n   public static class Builder extends BaseProviderMetadata.Builder {\n      protected Builder() {\n            id(\"azureblob\")\n            .name(\"Microsoft Azure Blob Service\")\n            .apiMetadata(new AzureBlobApiMetadata())\n            .endpoint(\"https://${\" + ACCOUNT + \"}.blob.core.windows.net\")\n            .homepage(URI.create(\"http://www.microsoft.com/windowsazure/storage/\"))\n            .console(URI.create(\"https://windows.azure.com/default.aspx\"))\n            .linkedServices(\"azureblob\", \"azurequeue\", \"azuretable\")\n            .iso3166Codes(\"US-TX\", \"US-IL\", \"IE-D\", \"SG\", \"NL-NH\", \"HK\")\n            .defaultProperties(AzureBlobProviderMetadata.defaultProperties());\n      }\n\n      @Override\n      public AzureBlobProviderMetadata build() {\n         return new AzureBlobProviderMetadata(this);\n      }\n      \n      @Override\n      public Builder fromProviderMetadata(\n            ProviderMetadata in) {\n         super.fromProviderMetadata(in);\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/binders/BindAzureBlobMetadataToMultipartRequest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Multimaps;\n\nimport org.jclouds.azureblob.blobstore.functions.AzureBlobToBlob;\nimport org.jclouds.azureblob.domain.AzureBlob;\nimport org.jclouds.blobstore.binders.BindUserMetadataToHeadersWithPrefix;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.io.ContentMetadata;\nimport org.jclouds.rest.Binder;\n\npublic class BindAzureBlobMetadataToMultipartRequest implements Binder {\n\n   private final AzureBlobToBlob azureBlob2Blob;\n   private final BindUserMetadataToHeadersWithPrefix blobBinder;\n\n   @Inject\n   BindAzureBlobMetadataToMultipartRequest(AzureBlobToBlob azureBlob2Blob, BindUserMetadataToHeadersWithPrefix blobBinder) {\n      this.azureBlob2Blob = azureBlob2Blob;\n      this.blobBinder = blobBinder;\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkArgument(checkNotNull(input, \"input\") instanceof AzureBlob, \"this binder is only valid for AzureBlobs!\");\n      checkNotNull(request, \"request\");\n      AzureBlob blob = AzureBlob.class.cast(input);\n\n      checkArgument(blob.getPayload().getContentMetadata().getContentLength() != null\n            && blob.getPayload().getContentMetadata().getContentLength() >= 0, \"size must be set\");\n\n      // bind BlockList-specific headers\n      ImmutableMap.Builder<String, String> headers = ImmutableMap.builder();\n      ContentMetadata contentMetadata = blob.getProperties().getContentMetadata();\n      String cacheControl = contentMetadata.getCacheControl();\n      if (cacheControl != null) {\n         headers.put(\"x-ms-blob-cache-control\", cacheControl);\n      }\n      String contentDisposition = contentMetadata.getContentDisposition();\n      if (contentDisposition != null) {\n         headers.put(\"x-ms-blob-content-disposition\", contentDisposition);\n      }\n      String contentEncoding = contentMetadata.getContentEncoding();\n      if (contentEncoding != null) {\n         headers.put(\"x-ms-blob-content-encoding\", contentEncoding);\n      }\n      String contentLanguage = contentMetadata.getContentLanguage();\n      if (contentLanguage != null) {\n         headers.put(\"x-ms-blob-content-language\", contentLanguage);\n      }\n      String contentType = contentMetadata.getContentType();\n      if (contentType != null) {\n         headers.put(\"x-ms-blob-content-type\", contentType);\n      }\n      request = (R) request.toBuilder().replaceHeaders(Multimaps.forMap(headers.build())).build();\n\n      return blobBinder.bindToRequest(request, azureBlob2Blob.apply(blob));\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/binders/BindAzureBlobMetadataToRequest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.azure.storage.reference.AzureStorageHeaders;\nimport org.jclouds.azureblob.blobstore.functions.AzureBlobToBlob;\nimport org.jclouds.azureblob.domain.AzureBlob;\nimport org.jclouds.blobstore.binders.BindUserMetadataToHeadersWithPrefix;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMap.Builder;\nimport com.google.common.collect.Multimaps;\nimport com.google.common.net.HttpHeaders;\n\n@Singleton\npublic class BindAzureBlobMetadataToRequest implements Binder {\n\n   private final AzureBlobToBlob azureBlob2Blob;\n   private final BindUserMetadataToHeadersWithPrefix blobBinder;\n\n   @Inject\n   public BindAzureBlobMetadataToRequest(AzureBlobToBlob azureBlob2Blob, BindUserMetadataToHeadersWithPrefix blobBinder) {\n      this.azureBlob2Blob = checkNotNull(azureBlob2Blob, \"azureBlob2Blob\");\n      this.blobBinder = checkNotNull(blobBinder, \"blobBinder\");\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkArgument(checkNotNull(input, \"input\") instanceof AzureBlob, \"this binder is only valid for AzureBlobs!\");\n      checkNotNull(request, \"request\");\n      AzureBlob blob = AzureBlob.class.cast(input);\n\n      checkArgument(blob.getPayload().getContentMetadata().getContentLength() != null\n            && blob.getPayload().getContentMetadata().getContentLength() >= 0, \"size must be set\");\n\n      Builder<String, String> headers = ImmutableMap.builder();\n\n      String cacheControl = blob.getPayload().getContentMetadata().getCacheControl();\n      if (cacheControl != null) {\n         headers.put(AzureStorageHeaders.CACHE_CONTROL, cacheControl);\n      }\n\n      headers.put(\"x-ms-blob-type\", blob.getProperties().getType().toString());\n\n      String contentDisposition = blob.getPayload().getContentMetadata().getContentDisposition();\n      if (contentDisposition != null) {\n         headers.put(\"x-ms-blob-content-disposition\", contentDisposition);\n      }\n\n      switch (blob.getProperties().getType()) {\n      case PAGE_BLOB:\n         headers.put(HttpHeaders.CONTENT_LENGTH, \"0\");\n         headers.put(\"x-ms-blob-content-length\", blob.getPayload().getContentMetadata().getContentLength().toString());\n         break;\n      case BLOCK_BLOB:\n         // see https://docs.microsoft.com/en-us/rest/api/storageservices/understanding-block-blobs--append-blobs--and-page-blobs\n         // see AzureBlobApiMetadata#version (current API version used is 2017-11-09)\n         checkArgument(\n               checkNotNull(blob.getPayload().getContentMetadata().getContentLength(), \"blob.getContentLength()\") <= 256L * 1024 * 1024,\n               \"maximum size for put Blob is 256MB\");\n         break;\n      }\n      request = (R) request.toBuilder().replaceHeaders(Multimaps.forMap(headers.build())).build();\n\n      return blobBinder.bindToRequest(request, azureBlob2Blob.apply(blob));\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/binders/BindAzureBlocksToRequest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.binders;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\nimport java.util.List;\n\n/**\n * Binds a list of blocks to a putBlockList request\n *\n * <?xml version=\"1.0\" encoding=\"utf-8\"?>\n * <BlockList>\n *   <Committed>first-base64-encoded-block-id</Committed>\n *   <Uncommitted>second-base64-encoded-block-id</Uncommitted>\n *   <Latest>third-base64-encoded-block-id</Latest>\n *   ...\n * </BlockList>\n */\npublic class BindAzureBlocksToRequest implements Binder {\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      List<String> blockIds = (List<String>)input;\n      StringBuilder content = new StringBuilder();\n      content.append(\"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\");\n      content.append(\"<BlockList>\");\n      for (String id : blockIds) {\n         content.append(\"<Latest>\").append(id).append(\"</Latest>\");\n      }\n      content.append(\"</BlockList>\");\n      request.setPayload(content.toString());\n      return request;\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/binders/BindAzureContentMetadataToRequest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.azure.storage.reference.AzureStorageHeaders;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.io.ContentMetadata;\nimport org.jclouds.rest.Binder;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Multimaps;\n\n@Singleton\npublic class BindAzureContentMetadataToRequest implements Binder {\n\n   public BindAzureContentMetadataToRequest() {\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkArgument(checkNotNull(input, \"input\") instanceof ContentMetadata,\n         \"this binder is only valid for ContentMetadata\");\n      checkNotNull(request, \"request\");\n      ContentMetadata contentMetadata = (ContentMetadata) input;\n\n      ImmutableMap.Builder<String, String> headers = ImmutableMap.builder();\n\n      String cacheControl = contentMetadata.getCacheControl();\n      if (cacheControl != null) {\n         headers.put(AzureStorageHeaders.CACHE_CONTROL, cacheControl);\n      }\n\n      String contentDisposition = contentMetadata.getContentDisposition();\n      if (contentDisposition != null) {\n         headers.put(AzureStorageHeaders.CONTENT_DISPOSITION, contentDisposition);\n      }\n\n      String contentEncoding = contentMetadata.getContentEncoding();\n      if (contentEncoding != null) {\n         headers.put(AzureStorageHeaders.CONTENT_ENCODING, contentEncoding);\n      }\n\n      String contentLanguage = contentMetadata.getContentLanguage();\n      if (contentLanguage != null) {\n         headers.put(AzureStorageHeaders.CONTENT_LANGUAGE, contentLanguage);\n      }\n\n      String contentType = contentMetadata.getContentType();\n      if (contentType != null) {\n         headers.put(AzureStorageHeaders.CONTENT_TYPE, contentType);\n      }\n\n      return (R) request.toBuilder().replaceHeaders(Multimaps.forMap(headers.build())).build();\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/binders/BindAzureCopyOptionsToRequest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.azureblob.binders;\n\nimport java.util.Date;\nimport java.util.Map;\n\nimport org.jclouds.azure.storage.reference.AzureStorageHeaders;\nimport org.jclouds.azureblob.options.CopyBlobOptions;\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\nimport com.google.common.base.Optional;\n\n/** Binds options to a copyBlob request. */\npublic class BindAzureCopyOptionsToRequest implements Binder {\n   private static final DateService dateService = new SimpleDateFormatDateService();\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      HttpRequest.Builder builder = request.toBuilder();\n      CopyBlobOptions options = (CopyBlobOptions) input;\n\n      Optional<Map<String, String>> userMetadata = options.getUserMetadata();\n      if (userMetadata.isPresent()) {\n         for (Map.Entry<String, String> entry : userMetadata.get().entrySet()) {\n            builder.addHeader(AzureStorageHeaders.USER_METADATA_PREFIX + entry.getKey(), entry.getValue());\n         }\n      }\n\n      Optional<Date> ifModifiedSince = options.getIfModifiedSince();\n      if (ifModifiedSince.isPresent()) {\n         builder.addHeader(AzureStorageHeaders.COPY_SOURCE_IF_MODIFIED_SINCE, dateService.rfc822DateFormat(ifModifiedSince.get()));\n      }\n\n      Optional<Date> ifUnmodifiedSince = options.getIfUnmodifiedSince();\n      if (ifUnmodifiedSince.isPresent()) {\n         builder.addHeader(AzureStorageHeaders.COPY_SOURCE_IF_UNMODIFIED_SINCE, dateService.rfc822DateFormat(ifUnmodifiedSince.get()));\n      }\n\n      Optional<String> ifMatch = options.getIfMatch();\n      if (ifMatch.isPresent()) {\n         builder.addHeader(AzureStorageHeaders.COPY_SOURCE_IF_MATCH, ifMatch.get());\n      }\n\n      Optional<String> ifNoneMatch = options.getIfNoneMatch();\n      if (ifNoneMatch.isPresent()) {\n         builder.addHeader(AzureStorageHeaders.COPY_SOURCE_IF_NONE_MATCH, ifNoneMatch.get());\n      }\n\n      return (R) builder.build();\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/binders/BindPublicAccessToRequest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.azureblob.domain.PublicAccess;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\n@Singleton\npublic final class BindPublicAccessToRequest implements Binder {\n\n   @Inject\n   public BindPublicAccessToRequest() {\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkNotNull(request, \"request\");\n      checkArgument(checkNotNull(input, \"input\") instanceof PublicAccess, \"this binder is only valid for PublicAccess\");\n      PublicAccess access = (PublicAccess) input;\n\n      switch (access) {\n      case PRIVATE:\n         // Without a header Azure sets the container to private access.\n         break;\n      default:\n         request = (R) request.toBuilder()\n               .replaceHeader(\"x-ms-blob-public-access\", access.name().toLowerCase())\n               .build();\n         break;\n      }\n\n      return request;\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/blobstore/AzureBlobRequestSigner.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.blobstore;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.concurrent.TimeUnit;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.azure.storage.config.AuthType;\nimport org.jclouds.azure.storage.filters.SharedKeyLiteAuthentication;\nimport org.jclouds.azure.storage.util.storageurl.StorageUrlSupplier;\nimport org.jclouds.blobstore.BlobRequestSigner;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.functions.BlobToHttpGetOptions;\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.Uris;\nimport org.jclouds.http.options.GetOptions;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.net.HttpHeaders;\nimport com.google.inject.Provider;\n\n\n@Singleton\npublic class AzureBlobRequestSigner implements BlobRequestSigner {\n   private static final int DEFAULT_EXPIRY_SECONDS = 15 * 60;\n   private static final String API_VERSION = \"2017-11-09\";\n\n   private final String identity;\n   private final URI storageUrl;\n   private final BlobToHttpGetOptions blob2HttpGetOptions;\n   private final Provider<String> timeStampProvider;\n   private final DateService dateService;\n   private final SharedKeyLiteAuthentication auth;\n   private final String credential;\n   private final boolean isSAS;\n   private final AuthType authType;\n\n   @Inject\n   public AzureBlobRequestSigner(\n         BlobToHttpGetOptions blob2HttpGetOptions, @TimeStamp Provider<String> timeStampProvider,\n         DateService dateService, SharedKeyLiteAuthentication auth,\n         @org.jclouds.location.Provider Supplier<Credentials> creds, @Named(\"sasAuth\") boolean sasAuthentication,\n         StorageUrlSupplier storageUriSupplier, AuthType authType)\n         throws SecurityException, NoSuchMethodException {\n      this.identity = creds.get().identity;\n      this.credential = creds.get().credential;\n      this.storageUrl = storageUriSupplier.get();\n      this.blob2HttpGetOptions = checkNotNull(blob2HttpGetOptions, \"blob2HttpGetOptions\");\n      this.timeStampProvider = checkNotNull(timeStampProvider, \"timeStampProvider\");\n      this.dateService = checkNotNull(dateService, \"dateService\");\n      this.auth = auth;\n      this.isSAS = sasAuthentication;\n      this.authType = authType;\n   }\n\n   @Override\n   public HttpRequest signGetBlob(String container, String name) {\n      return signGetBlob(container, name, DEFAULT_EXPIRY_SECONDS);\n   }\n\n   @Override\n   public HttpRequest signGetBlob(String container, String name, long timeInSeconds) {\n      checkNotNull(container, \"container\");\n      checkNotNull(name, \"name\");\n      return sign(\"GET\", container, name, null, timeInSeconds, null, null);\n   }\n\n   @Override\n   public HttpRequest signPutBlob(String container, Blob blob) {\n      return signPutBlob(container, blob, DEFAULT_EXPIRY_SECONDS);\n   }\n\n   @Override\n   public HttpRequest signPutBlob(String container, Blob blob, long timeInSeconds) {\n      checkNotNull(container, \"container\");\n      checkNotNull(blob, \"blob\");\n      return sign(\"PUT\", container, blob.getMetadata().getName(), null, timeInSeconds,\n            blob.getMetadata().getContentMetadata().getContentLength(),\n            blob.getMetadata().getContentMetadata().getContentType());\n   }\n\n   public HttpRequest signRemoveBlob(String container, String name) {\n      checkNotNull(container, \"container\");\n      checkNotNull(name, \"name\");\n      return sign(\"DELETE\", container, name, null, DEFAULT_EXPIRY_SECONDS, null, null);\n   }\n\n   @Override\n   public HttpRequest signGetBlob(String container, String name, org.jclouds.blobstore.options.GetOptions options) {\n      checkNotNull(container, \"container\");\n      checkNotNull(name, \"name\");\n      return sign(\"GET\", container, name, blob2HttpGetOptions.apply(checkNotNull(options, \"options\")),\n            DEFAULT_EXPIRY_SECONDS, null, null);\n   }\n   \n   /**\n    * method to sign HttpRequest when SharedKey Authentication is used \n    */\n   private HttpRequest signKey(String method, String container, String name, @Nullable GetOptions options, long expires, @Nullable Long contentLength, @Nullable String contentType) { \n      checkNotNull(method, \"method\");\n      checkNotNull(container, \"container\");\n      checkNotNull(name, \"name\");\n      String nowString = timeStampProvider.get();\n      Date now = dateService.rfc1123DateParse(nowString);\n      Date expiration = new Date(now.getTime() + TimeUnit.SECONDS.toMillis(expires));\n      String iso8601 = dateService.iso8601SecondsDateFormat(expiration);\n      String signedPermission;\n      if (method.equals(\"PUT\")) {\n         signedPermission = \"w\";\n      } else if (method.equals(\"DELETE\")) {\n         signedPermission = \"d\";\n      } else {\n         signedPermission = \"r\";\n      }\n      HttpRequest.Builder request = HttpRequest.builder()\n            .method(method)\n            .endpoint(Uris.uriBuilder(storageUrl).appendPath(container).appendPath(name).build())\n            .replaceHeader(HttpHeaders.DATE, nowString)\n            .addQueryParam(\"sv\", API_VERSION)\n            .addQueryParam(\"se\", iso8601)\n            .addQueryParam(\"sr\", \"b\")  // blob resource\n            .addQueryParam(\"sp\", signedPermission);  // permission\n      request = setHeaders(request, method, options, contentLength, contentType);\n      String stringToSign =\n            signedPermission + \"\\n\" +  // signedpermission\n            \"\\n\" +  // signedstart\n            iso8601 + \"\\n\" +  // signedexpiry\n            \"/blob/\" + identity + \"/\" + container + \"/\" + name + \"\\n\" +  // canonicalizedresource\n            \"\\n\" + // signedidentifier\n            \"\\n\" + // signedIP\n            \"\\n\" + // signedProtocol\n            API_VERSION + \"\\n\" +  // signedversion\n            \"\\n\" +  // rscc\n            \"\\n\" +  // rscd\n            \"\\n\" +  // rsce\n            \"\\n\" +  // rscl\n            \"\";  // rsct\n      String signature = auth.calculateSignature(stringToSign);\n      request.addQueryParam(\"sig\", signature);\n      return request.build();\n   }\n   \n   private HttpRequest.Builder setHeaders(HttpRequest.Builder request, String method, @Nullable GetOptions options, @Nullable Long contentLength, @Nullable String contentType){\n      if (contentLength != null) {\n         request.replaceHeader(HttpHeaders.CONTENT_LENGTH, contentLength.toString());\n      }\n      if (contentType != null) {\n         request.replaceHeader(\"x-ms-blob-content-type\", contentType);\n      }\n      if (options != null) {\n         request.headers(options.buildRequestHeaders());\n      }\n      if (method.equals(\"PUT\")) {\n         request.replaceHeader(\"x-ms-blob-type\", \"BlockBlob\");\n      }\n      return request; \n   }\n   \n   /** \n    * method, compatible with SAS Authentication \n    */\n   private HttpRequest signSAS(String method, String container, String name, @Nullable GetOptions options, long expires, @Nullable Long contentLength, @Nullable String contentType) {\n      checkNotNull(method, \"method\");\n      checkNotNull(container, \"container\");\n      checkNotNull(name, \"name\");\n      String nowString = timeStampProvider.get();\n      HttpRequest.Builder request = HttpRequest.builder()\n            .method(method)\n            .endpoint(Uris.uriBuilder(storageUrl).appendPath(container).appendPath(name).query(this.credential).build())\n            .replaceHeader(HttpHeaders.DATE, nowString);\n      request = setHeaders(request, method, options, contentLength, contentType);\n      return request.build();\n   }\n\n   private HttpRequest signAD(String method, String container, String name,\n                              @Nullable GetOptions options, long expires,\n                              @Nullable Long contentLength, @Nullable String contentType) {\n      checkNotNull(method, \"method\");\n      checkNotNull(container, \"container\");\n      checkNotNull(name, \"name\");\n      String nowString = timeStampProvider.get();\n      HttpRequest.Builder request = HttpRequest.builder()\n              .method(method)\n              .endpoint(Uris.uriBuilder(storageUrl).appendPath(container).appendPath(name).build())\n              .replaceHeader(HttpHeaders.DATE, nowString);\n      request = setHeaders(request, method, options, contentLength, contentType);\n      return request.build();\n   }\n   \n   /**\n    * modified sign() method, which acts depending on the Auth input. \n    */\n   public HttpRequest sign(String method, String container, String name, @Nullable GetOptions options, long expires, @Nullable Long contentLength, @Nullable String contentType) {\n      if (authType == AuthType.AZURE_AD) {\n         return signAD(method, container, name, options, expires, contentLength, contentType);\n      }\n      if (isSAS) {\n         return signSAS(method, container, name, options, expires, contentLength, contentType);\n      }\n      return signKey(method, container, name, options, expires, contentLength, contentType);\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/blobstore/AzureBlobStore.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.blobstore;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.azure.storage.options.ListOptions.Builder.includeMetadata;\n\nimport java.io.InputStream;\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.EnumSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.UUID;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.azure.storage.domain.BoundedSet;\nimport org.jclouds.azureblob.AzureBlobClient;\nimport org.jclouds.azureblob.blobstore.functions.AzureBlobToBlob;\nimport org.jclouds.azureblob.blobstore.functions.BlobPropertiesToBlobMetadata;\nimport org.jclouds.azureblob.blobstore.functions.BlobToAzureBlob;\nimport org.jclouds.azureblob.blobstore.functions.ContainerToResourceMetadata;\nimport org.jclouds.azureblob.blobstore.functions.ListBlobsResponseToResourceList;\nimport org.jclouds.azureblob.blobstore.functions.ListOptionsToListBlobsOptions;\nimport org.jclouds.azureblob.domain.AccessTier;\nimport org.jclouds.azureblob.domain.AzureBlob;\nimport org.jclouds.azureblob.domain.BlobBlockProperties;\nimport org.jclouds.azureblob.domain.BlobProperties;\nimport org.jclouds.azureblob.domain.ContainerProperties;\nimport org.jclouds.azureblob.domain.ListBlobBlocksResponse;\nimport org.jclouds.azureblob.domain.ListBlobsInclude;\nimport org.jclouds.azureblob.domain.ListBlobsResponse;\nimport org.jclouds.azureblob.domain.PublicAccess;\nimport org.jclouds.azureblob.options.CopyBlobOptions;\nimport org.jclouds.azureblob.options.ListBlobsOptions;\nimport org.jclouds.blobstore.BlobStoreContext;\nimport org.jclouds.blobstore.KeyNotFoundException;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.BlobAccess;\nimport org.jclouds.blobstore.domain.BlobMetadata;\nimport org.jclouds.blobstore.domain.ContainerAccess;\nimport org.jclouds.blobstore.domain.MultipartPart;\nimport org.jclouds.blobstore.domain.MultipartUpload;\nimport org.jclouds.blobstore.domain.PageSet;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.domain.Tier;\nimport org.jclouds.blobstore.domain.internal.PageSetImpl;\nimport org.jclouds.blobstore.functions.BlobToHttpGetOptions;\nimport org.jclouds.blobstore.internal.BaseBlobStore;\nimport org.jclouds.blobstore.options.CopyOptions;\nimport org.jclouds.blobstore.options.CreateContainerOptions;\nimport org.jclouds.blobstore.options.ListContainerOptions;\nimport org.jclouds.blobstore.options.PutOptions;\nimport org.jclouds.blobstore.util.BlobUtils;\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.domain.Location;\nimport org.jclouds.http.options.GetOptions;\nimport org.jclouds.io.ContentMetadata;\nimport org.jclouds.io.MutableContentMetadata;\nimport org.jclouds.io.PayloadSlicer;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Iterables;\nimport com.google.common.io.BaseEncoding;\nimport com.google.common.primitives.Ints;\nimport org.jclouds.io.ContentMetadataBuilder;\nimport org.jclouds.io.Payload;\n\n@Singleton\npublic class AzureBlobStore extends BaseBlobStore {\n   private final AzureBlobClient sync;\n   private final ContainerToResourceMetadata container2ResourceMd;\n   private final ListOptionsToListBlobsOptions blobStore2AzureContainerListOptions;\n   private final ListBlobsResponseToResourceList azure2BlobStoreResourceList;\n   private final AzureBlobToBlob azureBlob2Blob;\n   private final BlobToAzureBlob blob2AzureBlob;\n   private final BlobPropertiesToBlobMetadata blob2BlobMd;\n   private final BlobToHttpGetOptions blob2ObjectGetOptions;\n\n\n   @Inject\n   AzureBlobStore(BlobStoreContext context, BlobUtils blobUtils, Supplier<Location> defaultLocation,\n            @Memoized Supplier<Set<? extends Location>> locations, PayloadSlicer slicer, AzureBlobClient sync,\n            ContainerToResourceMetadata container2ResourceMd,\n            ListOptionsToListBlobsOptions blobStore2AzureContainerListOptions,\n            ListBlobsResponseToResourceList azure2BlobStoreResourceList, AzureBlobToBlob azureBlob2Blob,\n            BlobToAzureBlob blob2AzureBlob, BlobPropertiesToBlobMetadata blob2BlobMd,\n            BlobToHttpGetOptions blob2ObjectGetOptions) {\n      super(context, blobUtils, defaultLocation, locations, slicer);\n      this.sync = checkNotNull(sync, \"sync\");\n      this.container2ResourceMd = checkNotNull(container2ResourceMd, \"container2ResourceMd\");\n      this.blobStore2AzureContainerListOptions = checkNotNull(blobStore2AzureContainerListOptions,\n               \"blobStore2AzureContainerListOptions\");\n      this.azure2BlobStoreResourceList = checkNotNull(azure2BlobStoreResourceList, \"azure2BlobStoreResourceList\");\n      this.azureBlob2Blob = checkNotNull(azureBlob2Blob, \"azureBlob2Blob\");\n      this.blob2AzureBlob = checkNotNull(blob2AzureBlob, \"blob2AzureBlob\");\n      this.blob2BlobMd = checkNotNull(blob2BlobMd, \"blob2BlobMd\");\n      this.blob2ObjectGetOptions = checkNotNull(blob2ObjectGetOptions, \"blob2ObjectGetOptions\");\n   }\n\n   /**\n    * This implementation invokes {@link AzureBlobClient#listContainers}\n    */\n   @Override\n   public PageSet<? extends StorageMetadata> list() {\n      return new Function<BoundedSet<ContainerProperties>, org.jclouds.blobstore.domain.PageSet<? extends StorageMetadata>>() {\n         public org.jclouds.blobstore.domain.PageSet<? extends StorageMetadata> apply(\n                  BoundedSet<ContainerProperties> from) {\n            return new PageSetImpl<StorageMetadata>(Iterables.transform(from, container2ResourceMd), from\n                     .getNextMarker());\n         }\n         // TODO this may be a list that isn't complete due to 1000 container limit\n      }.apply(sync.listContainers(includeMetadata()));\n   }\n\n   /**\n    * This implementation invokes {@link AzureBlobClient#bucketExists}\n    *\n    * @param container\n    *           container name\n    */\n   @Override\n   public boolean containerExists(String container) {\n      return sync.containerExists(container);\n   }\n\n   /**\n    * This implementation invokes {@link AzureBlobClient#putBucketInRegion}\n    *\n    * @param location\n    *           currently ignored\n    * @param container\n    *           container name\n    */\n   @Override\n   public boolean createContainerInLocation(Location location, String container) {\n      return sync.createContainer(container);\n   }\n\n   /**\n    * This implementation invokes {@link AzureBlobClient#listBlobs}\n    *\n    * @param container\n    *           container name\n    */\n   @Override\n   public PageSet<? extends StorageMetadata> list(String container, ListContainerOptions options) {\n      ListBlobsOptions azureOptions = blobStore2AzureContainerListOptions.apply(options);\n      return azure2BlobStoreResourceList.apply(sync.listBlobs(container, azureOptions.includeMetadata()));\n   }\n\n   /**\n    * This implementation invokes {@link AzureBlobClient#deleteContainer}\n    *\n    * @param container\n    *           container name\n    */\n   @Override\n   public void deleteContainer(final String container) {\n      sync.deleteContainer(container);\n   }\n\n   /**\n    * This implementation invokes {@link AzureBlobClient#blobExists}\n    *\n    * @param container\n    *           container name\n    * @param key\n    *           blob key\n    */\n   @Override\n   public boolean blobExists(String container, String key) {\n      return sync.blobExists(container, key);\n   }\n\n   /**\n    * This implementation invokes {@link AzureBlobClient#getBlob}\n    *\n    * @param container\n    *           container name\n    * @param key\n    *           blob key\n    */\n   @Override\n   public Blob getBlob(String container, String key, org.jclouds.blobstore.options.GetOptions options) {\n      GetOptions azureOptions = blob2ObjectGetOptions.apply(options);\n      return azureBlob2Blob.apply(sync.getBlob(container, key, azureOptions));\n\n   }\n\n   /**\n    * This implementation invokes {@link AzureBlobClient#putObject}\n    *\n    * @param container\n    *           container name\n    * @param blob\n    *           object\n    */\n   @Override\n   public String putBlob(String container, Blob blob) {\n      return putBlob(container, blob, new PutOptions());\n   }\n\n   /**\n    * This implementation invokes {@link AzureBlobClient#putObject}\n    *\n    * @param container\n    *           container name\n    * @param blob\n    *           object\n    */\n   @Override\n   public String putBlob(String container, Blob blob, PutOptions options) {\n      if (options.getBlobAccess() != BlobAccess.PRIVATE) {\n         throw new UnsupportedOperationException(\"blob access not supported by Azure\");\n      }\n      String eTag;\n      if (options.isMultipart()) {\n         eTag = putMultipartBlob(container, blob, options);\n      } else {\n         eTag = sync.putBlob(container, blob2AzureBlob.apply(blob));\n      }\n      Tier tier = blob.getMetadata().getTier();\n      if (tier != Tier.STANDARD) {\n         sync.setBlobTier(container, blob.getMetadata().getName(), AccessTier.fromTier(tier));\n      }\n      return eTag;\n   }\n\n   @Override\n   public String copyBlob(String fromContainer, String fromName, String toContainer, String toName,\n         CopyOptions options) {\n      CopyBlobOptions.Builder azureOptions = CopyBlobOptions.builder();\n\n      if (options.ifMatch() != null) {\n         azureOptions.ifMatch(options.ifMatch());\n      }\n      if (options.ifNoneMatch() != null) {\n         azureOptions.ifNoneMatch(options.ifNoneMatch());\n      }\n      if (options.ifModifiedSince() != null) {\n         azureOptions.ifModifiedSince(options.ifModifiedSince());\n      }\n      if (options.ifUnmodifiedSince() != null) {\n         azureOptions.ifUnmodifiedSince(options.ifUnmodifiedSince());\n      }\n\n      Map<String, String> userMetadata = options.userMetadata();\n      if (userMetadata != null) {\n         azureOptions.overrideUserMetadata(userMetadata);\n      }\n\n      URI source = context.getSigner().signGetBlob(fromContainer, fromName).getEndpoint();\n      String eTag = sync.copyBlob(source, toContainer, toName, azureOptions.build());\n\n      ContentMetadata contentMetadata = options.contentMetadata();\n      if (contentMetadata != null) {\n         ContentMetadataBuilder builder = ContentMetadataBuilder.create();\n\n         String cacheControl = contentMetadata.getCacheControl();\n         if (cacheControl != null) {\n            builder.cacheControl(cacheControl);\n         }\n\n         String contentDisposition = contentMetadata.getContentDisposition();\n         if (contentDisposition != null) {\n            builder.contentDisposition(contentDisposition);\n         }\n\n         String contentEncoding = contentMetadata.getContentEncoding();\n         if (contentEncoding != null) {\n            builder.contentEncoding(contentEncoding);\n         }\n\n         String contentLanguage = contentMetadata.getContentLanguage();\n         if (contentLanguage != null) {\n            builder.contentLanguage(contentLanguage);\n         }\n\n         String contentType = contentMetadata.getContentType();\n         if (contentType != null) {\n            builder.contentType(contentType);\n         }\n\n         eTag = sync.setBlobProperties(toContainer, toName, builder.build());\n      }\n\n      return eTag;\n   }\n\n   /**\n    * This implementation invokes {@link AzureBlobClient#deleteObject}\n    *\n    * @param container\n    *           container name\n    * @param key\n    *           blob key\n    */\n   @Override\n   public void removeBlob(String container, String key) {\n      sync.deleteBlob(container, key);\n   }\n\n   /**\n    *  The Put Block operation creates a block blob on Azure which can be later assembled into\n    *  a single, large blob object with the Put Block List operation.\n    */\n   public void putBlock(String container, String name, String blockId, Payload block) {\n      sync.putBlock(container, name, blockId, block);\n   }\n\n\n   /**\n    *  The Put Block operation creates a block blob on Azure which can be later assembled into\n    *  a single, large blob object with the Put Block List operation. Azure will search the\n    *  latest blocks uploaded with putBlock to assemble the blob.\n    */\n   public String putBlockList(String container, String name, List<String> blockIdList) {\n      return sync.putBlockList(container, name, blockIdList);\n   }\n\n   /**\n    * Get Block ID List for a blob\n    */\n   public ListBlobBlocksResponse getBlockList(String container, String name) {\n      return sync.getBlockList(container, name);\n   }\n\n    /**\n    * This implementation invokes {@link AzureBlobClient#getBlobProperties}\n    *\n    * @param container\n    *           container name\n    * @param key\n    *           blob key\n    */\n   @Override\n   public BlobMetadata blobMetadata(String container, String key) {\n      return blob2BlobMd.apply(sync.getBlobProperties(container, key));\n   }\n\n   @Override\n   protected boolean deleteAndVerifyContainerGone(String container) {\n      // Azure deleteContainer supports deleting empty containers so emulate\n      // deleteIfEmpty by listing.\n      if (!list(container).isEmpty()) {\n         return false;\n      }\n      sync.deleteContainer(container);\n      return true;\n   }\n\n   @Override\n   public boolean createContainerInLocation(Location location, String container, CreateContainerOptions options) {\n      org.jclouds.azureblob.options.CreateContainerOptions createContainerOptions = new org.jclouds.azureblob.options.CreateContainerOptions();\n      if (options.isPublicRead())\n         createContainerOptions.withPublicAccess(PublicAccess.CONTAINER);\n      return sync.createContainer(container, createContainerOptions);\n   }\n\n   @Override\n   public ContainerAccess getContainerAccess(String container) {\n      PublicAccess access = sync.getPublicAccessForContainer(container);\n      if (access == PublicAccess.CONTAINER) {\n         return ContainerAccess.PUBLIC_READ;\n      } else {\n         return ContainerAccess.PRIVATE;\n      }\n   }\n\n   @Override\n   public void setContainerAccess(String container, ContainerAccess access) {\n      PublicAccess publicAccess;\n      if (access == ContainerAccess.PUBLIC_READ) {\n         publicAccess = PublicAccess.CONTAINER;\n      } else {\n         publicAccess = PublicAccess.PRIVATE;\n      }\n      sync.setPublicAccessForContainer(container, publicAccess);\n   }\n\n   @Override\n   public BlobAccess getBlobAccess(String container, String key) {\n      return BlobAccess.PRIVATE;\n   }\n\n   @Override\n   public void setBlobAccess(String container, String key, BlobAccess access) {\n      throw new UnsupportedOperationException(\"unsupported in Azure\");\n   }\n\n   @Override\n   public MultipartUpload initiateMultipartUpload(String container, BlobMetadata blobMetadata, PutOptions options) {\n      String uploadId = UUID.randomUUID().toString();\n      return MultipartUpload.create(container, blobMetadata.getName(), uploadId, blobMetadata, options);\n   }\n\n   @Override\n   public void abortMultipartUpload(MultipartUpload mpu) {\n      // Azure automatically removes uncommitted blocks after 7 days:\n      // http://gauravmantri.com/2012/05/11/comparing-windows-azure-blob-storage-and-amazon-simple-storage-service-s3part-ii/#f020\n   }\n\n   @Override\n   public String completeMultipartUpload(MultipartUpload mpu, List<MultipartPart> parts) {\n      AzureBlob azureBlob = sync.newBlob();\n\n      // fake values to satisfy BindAzureBlobMetadataToMultipartRequest\n      azureBlob.setPayload(new byte[0]);\n      azureBlob.getProperties().setContainer(mpu.containerName());\n      azureBlob.getProperties().setName(mpu.blobName());\n\n      azureBlob.getProperties().setContentMetadata((MutableContentMetadata) mpu.blobMetadata().getContentMetadata());\n      azureBlob.getProperties().setMetadata(mpu.blobMetadata().getUserMetadata());\n\n      ImmutableList.Builder<String> blocks = ImmutableList.builder();\n      for (MultipartPart part : parts) {\n         String blockId = makeBlockId(part.partNumber());\n         blocks.add(blockId);\n      }\n      return sync.putBlockList(mpu.containerName(), azureBlob, blocks.build());\n   }\n\n  static String makeBlockId(int partNumber) {\n      // Azure expects a base64-encoded string ONLY. It does not support base64url encoding. \n     return BaseEncoding.base64().encode(Ints.toByteArray(partNumber));\n  }\n   \n   @Override\n   public MultipartPart uploadMultipartPart(MultipartUpload mpu, int partNumber, Payload payload) {\n      String blockId = makeBlockId(partNumber);\n      sync.putBlock(mpu.containerName(), mpu.blobName(), blockId, payload);\n      String eTag = \"\";  // putBlock does not return ETag\n      Date lastModified = null;  // putBlob does not return Last-Modified\n      return MultipartPart.create(partNumber, payload.getContentMetadata().getContentLength(), eTag);\n   }\n\n   @Override\n   public List<MultipartPart> listMultipartUpload(MultipartUpload mpu) {\n      ListBlobBlocksResponse response;\n      try {\n         response = sync.getBlockList(mpu.containerName(), mpu.blobName(), \"uncommitted\");\n      } catch (KeyNotFoundException knfe) {\n         return ImmutableList.<MultipartPart>of();\n      }\n\n      ImmutableList.Builder<MultipartPart> parts = ImmutableList.builder();\n      for (BlobBlockProperties properties : response.getBlocks()) {\n         int partNumber = Ints.fromByteArray(BaseEncoding.base64().decode(properties.getBlockName()));\n         String eTag = \"\";  // getBlockList does not return ETag\n         Date lastModified = null;  // getBlockList does not return LastModified\n         parts.add(MultipartPart.create(partNumber, properties.getContentLength(), eTag, lastModified));\n      }\n      return parts.build();\n   }\n\n   @Override\n   public List<MultipartUpload> listMultipartUploads(String container) {\n      ImmutableList.Builder<MultipartUpload> builder = ImmutableList.builder();\n      String marker = null;\n      while (true) {\n         ListBlobsOptions options = new ListBlobsOptions().include(EnumSet.of(ListBlobsInclude.UNCOMMITTEDBLOBS));\n         if (marker != null) {\n            options.marker(marker);\n         }\n         ListBlobsResponse response = sync.listBlobs(container, options);\n         for (BlobProperties properties : response) {\n            // only uncommitted blobs lack ETags\n            if (properties.getETag() != null) {\n               continue;\n            }\n            // TODO: bogus uploadId\n            String uploadId = UUID.randomUUID().toString();\n            builder.add(MultipartUpload.create(properties.getContainer(), properties.getName(), uploadId, null, null));\n         }\n         marker = response.getNextMarker();\n         if (marker == null) {\n            break;\n         }\n      }\n      return builder.build();\n   }\n\n   @Override\n   public long getMinimumMultipartPartSize() {\n      return 1;\n   }\n\n   @Override\n   public long getMaximumMultipartPartSize() {\n      return 100 * 1024 * 1024;\n   }\n\n   @Override\n   public int getMaximumNumberOfParts() {\n      return 50 * 1000;\n   }\n\n   @Override\n   public InputStream streamBlob(String container, String name) {\n      throw new UnsupportedOperationException(\"Azure does not support streaming a blob\");\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/blobstore/config/AzureBlobStoreContextModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.blobstore.config;\n\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Provides;\nimport com.google.inject.Scopes;\nimport org.jclouds.azure.storage.config.AuthType;\nimport org.jclouds.azureblob.AzureBlobClient;\nimport org.jclouds.azureblob.blobstore.AzureBlobRequestSigner;\nimport org.jclouds.azureblob.blobstore.AzureBlobStore;\nimport org.jclouds.azureblob.config.InsufficientAccessRightsException;\nimport org.jclouds.azureblob.domain.PublicAccess;\nimport org.jclouds.blobstore.BlobRequestSigner;\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.attr.ConsistencyModel;\n\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\nimport java.util.concurrent.TimeUnit;\n\npublic class AzureBlobStoreContextModule extends AbstractModule {\n\n   @Override\n   protected void configure() {\n      bind(ConsistencyModel.class).toInstance(ConsistencyModel.STRICT);\n      bind(BlobStore.class).to(AzureBlobStore.class).in(Scopes.SINGLETON);\n      bind(BlobRequestSigner.class).to(AzureBlobRequestSigner.class);\n   }\n\n   @Provides\n   @Singleton\n   protected final LoadingCache<String, PublicAccess> containerAcls(final AzureBlobClient client, @Named(\"sasAuth\") final boolean sasAuthentication, AuthType authType) {\n      return CacheBuilder.newBuilder().expireAfterWrite(30, TimeUnit.SECONDS).build(\n               new CacheLoader<String, PublicAccess>() {\n                  @Override\n                  public PublicAccess load(String container) throws CacheLoader.InvalidCacheLoadException {\n                     if (!sasAuthentication && authType == AuthType.AZURE_KEY) {\n                        return client.getPublicAccessForContainer(container);\n                     }\n                     throw new InsufficientAccessRightsException(\"SAS Authentication does not support getAcl and setAcl calls.\");\n                  }\n\n                  @Override\n                  public String toString() {\n                     return \"getPublicAccessForContainer()\";\n                  }\n               });\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/blobstore/functions/AzureBlobToBlob.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.blobstore.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.azureblob.domain.AzureBlob;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.Blob.Factory;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class AzureBlobToBlob implements Function<AzureBlob, Blob> {\n   private final Factory blobFactory;\n   private final BlobPropertiesToBlobMetadata blobPr2BlobMd;\n\n   @Inject\n   AzureBlobToBlob(Factory blobFactory, BlobPropertiesToBlobMetadata blobPr2BlobMd) {\n      this.blobFactory = checkNotNull(blobFactory, \"blobFactory\");\n      this.blobPr2BlobMd = checkNotNull(blobPr2BlobMd, \"blobPr2BlobMd\");\n   }\n\n   public Blob apply(AzureBlob from) {\n      if (from == null)\n         return null;\n      Blob blob = blobFactory.create(blobPr2BlobMd.apply(from.getProperties()));\n      blob.setPayload(checkNotNull(from.getPayload(), \"payload: \" + from));\n      blob.setAllHeaders(from.getAllHeaders());\n      return blob;\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/blobstore/functions/BlobMetadataToBlobProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.blobstore.functions;\n\nimport java.util.Map.Entry;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.azureblob.domain.MutableBlobProperties;\nimport org.jclouds.azureblob.domain.internal.MutableBlobPropertiesImpl;\nimport org.jclouds.blobstore.domain.BlobMetadata;\nimport org.jclouds.http.HttpUtils;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class BlobMetadataToBlobProperties implements Function<BlobMetadata, MutableBlobProperties> {\n   public MutableBlobProperties apply(BlobMetadata from) {\n      if (from == null)\n         return null;\n      MutableBlobProperties to = new MutableBlobPropertiesImpl();\n      HttpUtils.copy(from.getContentMetadata(), to.getContentMetadata());\n      to.setETag(from.getETag());\n      to.setName(from.getName());\n      to.setUrl(from.getUri());\n      to.setLastModified(from.getLastModified());\n      if (from.getUserMetadata() != null) {\n         for (Entry<String, String> entry : from.getUserMetadata().entrySet())\n            to.getMetadata().put(entry.getKey().toLowerCase(), entry.getValue());\n      }\n      return to;\n   }\n\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/blobstore/functions/BlobPropertiesToBlobMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.blobstore.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.azureblob.domain.AccessTier;\nimport org.jclouds.azureblob.domain.BlobProperties;\nimport org.jclouds.azureblob.domain.PublicAccess;\nimport org.jclouds.blobstore.domain.MutableBlobMetadata;\nimport org.jclouds.blobstore.domain.StorageType;\nimport org.jclouds.blobstore.domain.internal.MutableBlobMetadataImpl;\nimport org.jclouds.http.HttpUtils;\nimport org.jclouds.azureblob.config.InsufficientAccessRightsException;\nimport org.jclouds.util.Throwables2;\n\nimport com.google.common.base.Function;\nimport com.google.common.cache.LoadingCache;\n\n\n@Singleton\npublic class BlobPropertiesToBlobMetadata implements Function<BlobProperties, MutableBlobMetadata> {\n   private final LoadingCache<String, PublicAccess> containerAcls;\n\n   @Inject\n   public BlobPropertiesToBlobMetadata(LoadingCache<String, PublicAccess> containerAcls) {\n      this.containerAcls = checkNotNull(containerAcls, \"containerAcls\");\n   }\n\n   public MutableBlobMetadata apply(BlobProperties from) {\n      if (from == null)\n         return null;\n      MutableBlobMetadata to = new MutableBlobMetadataImpl();\n      HttpUtils.copy(from.getContentMetadata(), to.getContentMetadata());\n      to.setUserMetadata(from.getMetadata());\n      to.setETag(from.getETag());\n      to.setLastModified(from.getLastModified());\n      to.setName(from.getName());\n      to.setContainer(from.getContainer());\n      to.setUri(from.getUrl());\n      if (from.getContainer() != null)\n         try {\n            PublicAccess containerAcl = containerAcls.getUnchecked(from.getContainer());\n            if (containerAcl != PublicAccess.PRIVATE)\n               to.setPublicUri(from.getUrl());\n         } catch (RuntimeException ex) {\n            //AzureBlob is not a publicly accessible object, but it is impossible to obtain ACL using SAS Auth. \n            InsufficientAccessRightsException iare = Throwables2.getFirstThrowableOfType(ex, InsufficientAccessRightsException.class);\n            if (iare == null) throw ex;  \n         }\n      if (to.getContentMetadata() != null && to.getContentMetadata().getContentType() != null &&\n            to.getContentMetadata().getContentType().equals(\"application/directory\")) {\n         to.setType(StorageType.FOLDER);\n      } else {\n         to.setType(StorageType.BLOB);\n      }\n      to.setSize(from.getContentMetadata().getContentLength());\n      AccessTier tier = from.getTier();\n      to.setTier((tier != null ? tier : AccessTier.HOT).toTier());\n      return to;\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/blobstore/functions/BlobToAzureBlob.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.blobstore.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.azureblob.domain.AzureBlob;\nimport org.jclouds.blobstore.domain.Blob;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class BlobToAzureBlob implements Function<Blob, AzureBlob> {\n   private final BlobMetadataToBlobProperties blob2ObjectMd;\n   private final AzureBlob.Factory objectProvider;\n\n   @Inject\n   BlobToAzureBlob(BlobMetadataToBlobProperties blob2ObjectMd, AzureBlob.Factory objectProvider) {\n      this.blob2ObjectMd = blob2ObjectMd;\n      this.objectProvider = objectProvider;\n   }\n\n   public AzureBlob apply(Blob from) {\n      if (from == null)\n         return null;\n      AzureBlob object = objectProvider.create(blob2ObjectMd.apply(from.getMetadata()));\n      object.setPayload(checkNotNull(from.getPayload(), \"payload: \" + from));\n      object.setAllHeaders(from.getAllHeaders());\n      return object;\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/blobstore/functions/ContainerToResourceMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.blobstore.functions;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.azureblob.domain.ContainerProperties;\nimport org.jclouds.blobstore.domain.MutableStorageMetadata;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.domain.StorageType;\nimport org.jclouds.blobstore.domain.internal.MutableStorageMetadataImpl;\nimport org.jclouds.domain.Location;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\n\n@Singleton\npublic class ContainerToResourceMetadata implements Function<ContainerProperties, StorageMetadata> {\n   private Supplier<Location> defaultLocation;\n\n   @Inject\n   ContainerToResourceMetadata(Supplier<Location> defaultLocation) {\n      this.defaultLocation = defaultLocation;\n   }\n\n   public StorageMetadata apply(ContainerProperties from) {\n      MutableStorageMetadata to = new MutableStorageMetadataImpl();\n      to.setName(from.getName());\n      to.setLocation(defaultLocation.get());\n      to.setETag(from.getETag());\n      to.setLastModified(from.getLastModified());\n      to.setUri(from.getUrl());\n      to.setType(StorageType.CONTAINER);\n      to.setUserMetadata(from.getMetadata());\n      return to;\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/blobstore/functions/ListBlobsResponseToResourceList.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.blobstore.functions;\n\nimport java.util.SortedSet;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.azureblob.domain.ListBlobsResponse;\nimport org.jclouds.blobstore.domain.PageSet;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.domain.internal.PageSetImpl;\nimport org.jclouds.blobstore.functions.PrefixToResourceMetadata;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Sets;\n\n@Singleton\npublic class ListBlobsResponseToResourceList implements\n         Function<ListBlobsResponse, PageSet<? extends StorageMetadata>> {\n   private final BlobPropertiesToBlobMetadata object2blobMd;\n   private final PrefixToResourceMetadata prefix2ResourceMd;\n\n   protected final Function<StorageMetadata, String> indexer = new Function<StorageMetadata, String>() {\n      @Override\n      public String apply(StorageMetadata from) {\n         return from.getName();\n      }\n   };\n\n   @Inject\n   public ListBlobsResponseToResourceList(BlobPropertiesToBlobMetadata object2blobMd,\n            PrefixToResourceMetadata prefix2ResourceMd) {\n      this.object2blobMd = object2blobMd;\n      this.prefix2ResourceMd = prefix2ResourceMd;\n   }\n\n   public PageSet<? extends StorageMetadata> apply(ListBlobsResponse from) {\n      // use sorted set to order relative paths correctly\n      SortedSet<StorageMetadata> contents = Sets.<StorageMetadata> newTreeSet(Iterables.transform(from,\n               object2blobMd));\n\n      for (String prefix : from.getBlobPrefixes()) {\n         contents.add(prefix2ResourceMd.apply(prefix));\n      }\n      return new PageSetImpl<StorageMetadata>(contents, from.getNextMarker());\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/blobstore/functions/ListOptionsToListBlobsOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.blobstore.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.azureblob.options.ListBlobsOptions;\nimport org.jclouds.blobstore.options.ListContainerOptions;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class ListOptionsToListBlobsOptions implements\n         Function<ListContainerOptions, ListBlobsOptions> {\n   public ListBlobsOptions apply(ListContainerOptions from) {\n      checkNotNull(from, \"set options to instance NONE instead of passing null\");\n      if (from.getDir() != null && from.getPrefix() != null) {\n         throw new IllegalArgumentException(\"Cannot set both directory and prefix\");\n      }\n      if (((from.getDir() != null) || from.isRecursive()) && from.getDelimiter() != null) {\n         throw new IllegalArgumentException(\"Cannot set delimiter and directory or recursive options together\");\n      }\n\n      ListBlobsOptions httpOptions = new ListBlobsOptions();\n      if (from.getDelimiter() != null) {\n         httpOptions.delimiter(from.getDelimiter());\n      }\n      if (!from.isRecursive() && httpOptions.getDelimiter() == null) {\n         httpOptions.delimiter(\"/\");\n      }\n      if (from.getDir() != null) {\n         httpOptions.prefix(from.getDir().endsWith(\"/\") ? from.getDir() : from.getDir() + \"/\");\n      }\n      if (from.getPrefix() != null) {\n         httpOptions.prefix(from.getPrefix());\n      }\n      if (from.getMarker() != null) {\n         httpOptions.marker(from.getMarker());\n      }\n      if (from.getMaxResults() != null) {\n         httpOptions.maxResults(from.getMaxResults());\n      }\n      if (from.isDetailed()) {\n         httpOptions.includeMetadata();\n      }\n      return httpOptions;\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/config/AppendAccountToEndpointModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.config;\n\nimport com.google.inject.AbstractModule;\nimport org.jclouds.azure.storage.util.storageurl.AppendAccountToEndpoint;\nimport org.jclouds.azure.storage.util.storageurl.StorageUrlSupplier;\n\npublic class AppendAccountToEndpointModule extends AbstractModule {\n   \n   @Override\n   protected void configure() {\n      bind(StorageUrlSupplier.class).to(AppendAccountToEndpoint.class);\n   }\n   \n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/config/AzureBlobHttpApiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.config;\n\nimport static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL;\n\nimport static com.google.common.base.Predicates.in;\n\nimport static com.google.common.collect.Iterables.all;\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.ImmutableList;\n\nimport java.util.concurrent.TimeUnit;\nimport java.util.Map;\nimport java.util.List;\n\nimport jakarta.inject.Named;\n\nimport com.google.inject.Scopes;\nimport org.jclouds.azure.storage.config.AzureStorageOAuthConfigFactory;\nimport org.jclouds.azure.storage.handlers.AzureStorageClientErrorRetryHandler;\nimport org.jclouds.azureblob.AzureBlobClient;\nimport org.jclouds.azureblob.handlers.ParseAzureBlobErrorFromXmlContent;\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpRetryHandler;\nimport org.jclouds.http.annotation.ClientError;\nimport org.jclouds.http.annotation.Redirection;\nimport org.jclouds.http.annotation.ServerError;\nimport org.jclouds.json.config.GsonModule.DateAdapter;\nimport org.jclouds.json.config.GsonModule.Iso8601DateAdapter;\nimport org.jclouds.oauth.v2.config.OAuthConfigFactory;\nimport org.jclouds.oauth.v2.config.OAuthScopes;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.config.HttpApiModule;\nimport org.jclouds.domain.Credentials;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.inject.Provides;\n\n/**\n * Configures the Azure Blob Service connection, including logging and http transport.\n */\n@ConfiguresHttpApi\npublic class AzureBlobHttpApiModule extends HttpApiModule<AzureBlobClient> {\n   @Override\n   protected void configure() {\n      install(new AzureBlobModule());\n      bind(DateAdapter.class).to(Iso8601DateAdapter.class);\n      bind(OAuthScopes.class).toInstance(OAuthScopes.NoScopes.create());\n      bind(OAuthConfigFactory.class).to(AzureStorageOAuthConfigFactory.class).in(Scopes.SINGLETON);\n      super.configure();\n   }\n\n   @Provides\n   @TimeStamp\n   protected final String guiceProvideTimeStamp(@TimeStamp Supplier<String> cache) {\n      return provideTimeStamp(cache);\n   }\n\n   protected String provideTimeStamp(@TimeStamp Supplier<String> cache) {\n      return cache.get();\n   }\n   \n   /** \n    * checks which Authentication type is used \n    */\n   @Named(\"sasAuth\")\n   @Provides\n   protected boolean authSAS(@org.jclouds.location.Provider Supplier<Credentials> creds) {\n      String credential = creds.get().credential;\n      String formattedCredential = credential.startsWith(\"?\") ? credential.substring(1) : credential;\n      List<String> required = ImmutableList.of(\"sv\", \"sig\"); \n      try {\n         Map<String, String> tokens = Splitter.on('&').withKeyValueSeparator('=').split(formattedCredential);\n         return all(required, in(tokens.keySet()));\n      } catch (Exception ex) {\n         return false;\n      }\n   }\n\n   /**\n    * borrowing concurrency code to ensure that caching takes place properly\n    */\n   @Provides\n   @TimeStamp\n   protected Supplier<String> provideTimeStampCache(@Named(PROPERTY_SESSION_INTERVAL) long seconds,\n         final DateService dateService) {\n      return Suppliers.memoizeWithExpiration(new Supplier<String>() {\n         @Override\n         public String get() {\n            return dateService.rfc822DateFormat();\n         }\n      }, seconds, TimeUnit.SECONDS);\n   }\n\n   @Override\n   protected void bindRetryHandlers() {\n      bind(HttpRetryHandler.class).annotatedWith(ClientError.class).to(AzureStorageClientErrorRetryHandler.class);\n   }\n\n   @Override\n   protected void bindErrorHandlers() {\n      bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(ParseAzureBlobErrorFromXmlContent.class);\n      bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(ParseAzureBlobErrorFromXmlContent.class);\n      bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(ParseAzureBlobErrorFromXmlContent.class);\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/config/AzureBlobModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.config;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Provider;\n\nimport org.jclouds.azure.storage.config.AuthType;\nimport org.jclouds.azureblob.domain.AzureBlob;\nimport org.jclouds.azureblob.domain.MutableBlobProperties;\nimport org.jclouds.azureblob.domain.internal.AzureBlobImpl;\nimport org.jclouds.blobstore.config.BlobStoreObjectModule;\n\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Provides;\nimport com.google.inject.Scopes;\n\nimport static org.jclouds.azure.storage.config.AzureStorageProperties.AUTH_TYPE;\n\n/**\n * Configures the domain object mappings needed for all Azure Blob implementations\n */\npublic class AzureBlobModule extends AbstractModule {\n\n   /**\n    * explicit factories are created here as it has been shown that Assisted Inject is extremely\n    * inefficient. http://code.google.com/p/google-guice/issues/detail?id=435\n    */\n   @Override\n   protected void configure() {\n      // for converters\n      install(new BlobStoreObjectModule());\n      bind(AzureBlob.Factory.class).to(AzureBlobFactory.class).in(Scopes.SINGLETON);\n   }\n\n   private static class AzureBlobFactory implements AzureBlob.Factory {\n      @Inject\n      Provider<MutableBlobProperties> metadataProvider;\n\n      public AzureBlob create(MutableBlobProperties metadata) {\n         return new AzureBlobImpl(metadata != null ? metadata : metadataProvider.get());\n      }\n   }\n\n   @Provides\n   final AzureBlob provideAzureBlob(AzureBlob.Factory factory) {\n      return factory.create(null);\n   }\n\n   @Inject\n   @Provides\n   final AuthType AuthTypeFromPropertyOrDefault(@Named(AUTH_TYPE) String authType) {\n      return AuthType.fromValue(authType);\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/config/InsufficientAccessRightsException.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n \n \n/**\n * Handles the inability of SAS Authentication string to authenticate the getAcl and setAcl requests.\n * \n */\n \npackage org.jclouds.azureblob.config;\n\npublic class InsufficientAccessRightsException extends RuntimeException {\n\n   public InsufficientAccessRightsException(String message) {\n      super(message);\n   }\n\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/domain/AccessTier.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.blobstore.domain.Tier;\n\nimport com.google.common.base.CaseFormat;\n\npublic enum AccessTier {\n   HOT(Tier.STANDARD),\n   COOL(Tier.COOL),\n   COLD(Tier.COLD),\n   ARCHIVE(Tier.ARCHIVE);\n\n   private final Tier tier;\n\n   private AccessTier(Tier tier) {\n      this.tier = checkNotNull(tier);\n   }\n\n   public String value() {\n      return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name());\n   }\n\n   @Override\n   public String toString() {\n      return value();\n   }\n\n   // TODO: call valueOf instead like GCS?\n   public static AccessTier fromValue(String tier) {\n      return valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, checkNotNull(tier, \"tier\")));\n   }\n\n   public static AccessTier fromTier(Tier tier) {\n      switch (tier) {\n      case STANDARD: return AccessTier.HOT;\n      case INFREQUENT: return AccessTier.COOL;\n      case COOL: return AccessTier.COOL;\n      case COLD: return AccessTier.COLD;\n      case ARCHIVE: return AccessTier.ARCHIVE;\n      }\n      throw new IllegalArgumentException(\"invalid tier: \" + tier);\n   }\n\n   public Tier toTier() {\n      return tier;\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/domain/AzureBlob.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.domain;\n\nimport org.jclouds.io.PayloadEnclosing;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.collect.Multimap;\n\n\n/**\n * Amazon S3 is designed to store objects. Objects are stored in buckets and consist of a\n * {@link ObjectPropertiesBlob#getInput() value}, a {@link ObjectProperties#getKey key},\n * {@link ObjectProperties#getUserProperties() metadata}, and an access control policy.\n *\n * @see <a href=\"http://docs.amazonwebservices.com/AmazonS3/2006-03-01/index.html?UsingObjects.html\"\n *      />\n */\npublic interface AzureBlob extends PayloadEnclosing, Comparable<AzureBlob> {\n\n\n   public interface Factory {\n      AzureBlob create(@Nullable MutableBlobProperties properties);\n   }\n\n   /**\n    * @return System and User metadata relevant to this object.\n    */\n   MutableBlobProperties getProperties();\n\n   Multimap<String, String> getAllHeaders();\n\n   void setAllHeaders(Multimap<String, String> allHeaders);\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/domain/BlobBlockProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.domain;\n\n/**\n * Properties on a specific block within a blob\n */\npublic interface BlobBlockProperties {\n   String getBlockName();\n   boolean isCommitted();\n   long getContentLength();\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/domain/BlobProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.domain;\n\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.Map;\n\nimport org.jclouds.io.ContentMetadata;\n\npublic interface BlobProperties extends Comparable<BlobProperties> {\n\n   Map<String, String> getMetadata();\n\n   /**\n    *  \n    */\n   BlobType getType();\n\n   /** @return access tier or null if not set */\n   AccessTier getTier();\n\n   LeaseStatus getLeaseStatus();\n\n   URI getUrl();\n\n   String getName();\n\n   String getContainer();\n\n   Date getLastModified();\n\n   String getETag();\n\n   ContentMetadata getContentMetadata();\n\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/domain/BlobType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.CaseFormat;\n\npublic enum BlobType {\n   BLOCK_BLOB, PAGE_BLOB, UNRECOGNIZED;\n\n   public String value() {\n      return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name());\n   }\n\n   @Override\n   public String toString() {\n      return value();\n   }\n\n   public static BlobType fromValue(String type) {\n      try {\n         return valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, checkNotNull(type, \"type\")));\n      } catch (IllegalArgumentException e) {\n         return UNRECOGNIZED;\n      }\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/domain/ContainerProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.domain;\n\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.Map;\n\npublic interface ContainerProperties extends Comparable<ContainerProperties> {\n   URI getUrl();\n\n   String getName();\n\n   Date getLastModified();\n\n   String getETag();\n\n   PublicAccess getPublicAccess();\n\n   Map<String, String> getMetadata();\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/domain/LeaseStatus.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.CaseFormat;\n\npublic enum LeaseStatus {\n   LOCKED, UNLOCKED, UNRECOGNIZED;\n\n   public String value() {\n      return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name());\n   }\n\n   @Override\n   public String toString() {\n      return value();\n   }\n\n   public static LeaseStatus fromValue(String type) {\n      try {\n         return valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, checkNotNull(type, \"type\")));\n      } catch (IllegalArgumentException e) {\n         return UNRECOGNIZED;\n      }\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/domain/ListBlobBlocksResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.domain;\n\nimport java.util.List;\n\n/**\n * Typed response from Get Blob Block List operation\n */\npublic interface ListBlobBlocksResponse {\n    List<BlobBlockProperties> getBlocks();\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/domain/ListBlobsInclude.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.domain;\n\npublic enum ListBlobsInclude {\n   COPY,\n   METADATA,\n   SNAPSHOTS,\n   UNCOMMITTEDBLOBS;\n\n   public static ListBlobsInclude fromValue(String symbol) {\n      return ListBlobsInclude.valueOf(symbol.toUpperCase());\n   }\n\n   @Override\n   public String toString() {\n      return name().toLowerCase();\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/domain/ListBlobsResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.domain;\n\nimport java.util.Set;\n\nimport org.jclouds.azure.storage.domain.BoundedSet;\n\npublic interface ListBlobsResponse extends BoundedSet<BlobProperties> {\n\n   String getDelimiter();\n\n   Set<String> getBlobPrefixes();\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/domain/MutableBlobProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.domain;\n\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.Map;\n\nimport org.jclouds.azureblob.domain.internal.MutableBlobPropertiesImpl;\nimport org.jclouds.io.MutableContentMetadata;\n\nimport com.google.inject.ImplementedBy;\n\n@ImplementedBy(MutableBlobPropertiesImpl.class)\npublic interface MutableBlobProperties extends BlobProperties {\n   /**\n    * @see ListableContainerProperties#getUrl\n    */\n   void setUrl(URI url);\n\n   /**\n    * @see ListableContainerProperties#getName\n    */\n   void setName(String name);\n   /**\n    * @see ListableContainerProperties#getContainer\n    */\n   void setContainer(String container);\n\n   void setTier(AccessTier tier);\n   \n   /**\n    * @see ListableContainerProperties#getLastModified\n    */\n   void setLastModified(Date lastModified);\n\n   /**\n    * @see ListableContainerProperties#getETag\n    */\n   void setETag(String eTag);\n\n   MutableContentMetadata getContentMetadata();\n\n   void setContentMetadata(MutableContentMetadata md);\n\n   /**\n    * @see ListableContainerProperties#getMetadata\n    */\n   void setMetadata(Map<String, String> metadata);\n\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/domain/MutableContainerPropertiesWithMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.domain;\n\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.Map;\n\nimport org.jclouds.azureblob.domain.internal.MutableContainerPropertiesWithMetadataImpl;\n\nimport com.google.inject.ImplementedBy;\n\n@ImplementedBy(MutableContainerPropertiesWithMetadataImpl.class)\npublic interface MutableContainerPropertiesWithMetadata extends ContainerProperties {\n   /**\n    * @see ListableContainerProperties#setUrl\n    */\n   void setUrl(URI url);\n\n   /**\n    * @see ListableContainerProperties#setName\n    */\n   void setName(String name);\n\n   /**\n    * @see ListableContainerProperties#setLastModified\n    */\n   void setLastModified(Date lastModified);\n\n   /**\n    * @see ListableContainerProperties#setETag\n    */\n   void setETag(String eTag);\n\n   void setPublicAccess(PublicAccess publicAccess);\n\n   /**\n    * @see ListableContainerProperties#setMetadata\n    */\n   void setMetadata(Map<String, String> metadata);\n\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/domain/PublicAccess.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.domain;\n\n/**\n * Indicates whether data in the container may be accessed publicly and the level of access.\n * \n * \n * @see <a href=\"http://msdn.microsoft.com/en-us/library/dd179469.aspx\"/>\n */\npublic enum PublicAccess {\n   /**\n    * Indicates full public read access for container and blob data. Clients can enumerate blobs\n    * within the container via anonymous request, but cannot enumerate containers within the storage\n    * account.\n    */\n   CONTAINER,\n   /**\n    * Indicates public read access for blobs. Blob data within this container can be read via\n    * anonymous request, but container data is not available. Clients cannot enumerate blobs within\n    * the container via anonymous request.\n    */\n   BLOB,\n   /**\n    * the container is private to the account owner.\n    */\n   PRIVATE;\n\n   public static PublicAccess fromString(String string) {\n      return valueOf(string.toUpperCase());\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/domain/internal/AzureBlobImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.domain.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.azureblob.domain.AzureBlob;\nimport org.jclouds.azureblob.domain.MutableBlobProperties;\nimport org.jclouds.http.internal.PayloadEnclosingImpl;\nimport org.jclouds.io.Payload;\n\nimport com.google.common.collect.LinkedHashMultimap;\nimport com.google.common.collect.Multimap;\n\n/**\n * Default Implementation of {@link AzureBlob}.\n */\npublic class AzureBlobImpl extends PayloadEnclosingImpl implements AzureBlob, Comparable<AzureBlob> {\n\n   private final MutableBlobProperties properties;\n   private Multimap<String, String> allHeaders = LinkedHashMultimap.create();\n\n   @Inject\n   public AzureBlobImpl(MutableBlobProperties properties) {\n      super();\n      this.properties = properties;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public MutableBlobProperties getProperties() {\n      return properties;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Multimap<String, String> getAllHeaders() {\n      return allHeaders;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void setAllHeaders(Multimap<String, String> allHeaders) {\n      this.allHeaders = checkNotNull(allHeaders, \"allHeaders\");\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public int compareTo(AzureBlob o) {\n      if (getProperties().getName() == null)\n         return -1;\n      return (this == o) ? 0 : getProperties().getName().compareTo(o.getProperties().getName());\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = super.hashCode();\n      result = prime * result + ((properties == null) ? 0 : properties.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (!super.equals(obj))\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      AzureBlobImpl other = (AzureBlobImpl) obj;\n      if (properties == null) {\n         if (other.properties != null)\n            return false;\n      } else if (!properties.equals(other.properties))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"[properties=\" + properties + \"]\";\n   }\n\n   @Override\n   public void setPayload(Payload data) {\n      super.setPayload(data);\n      properties.setContentMetadata(data.getContentMetadata());\n   }\n\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/domain/internal/BlobBlockPropertiesImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.domain.internal;\n\nimport org.jclouds.azureblob.domain.BlobBlockProperties;\n\nimport com.google.common.base.Objects;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\n/**\n * Representation of the blocks which compose a Blob\n */\npublic class BlobBlockPropertiesImpl implements BlobBlockProperties {\n   private final String blockName;\n   private final long contentLength;\n   private final boolean committed;\n\n   public BlobBlockPropertiesImpl(String blockName, long contentLength, boolean committed) {\n      this.blockName = checkNotNull(blockName);\n      this.contentLength = contentLength;\n      this.committed = committed;\n   }\n\n   @Override\n   public String getBlockName() {\n      return blockName;\n   }\n\n   @Override\n   public boolean isCommitted() {\n      return committed;\n   }\n\n   @Override\n   public long getContentLength() {\n      return contentLength;\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o) return true;\n      if (o == null || getClass() != o.getClass()) return false;\n      BlobBlockPropertiesImpl that = (BlobBlockPropertiesImpl) o;\n      return Objects.equal(blockName, that.blockName)\n            && Objects.equal(committed, that.committed)\n            && Objects.equal(contentLength, that.contentLength);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(blockName, contentLength, committed);\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/domain/internal/BlobPropertiesImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.domain.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.Map;\n\nimport org.jclouds.azureblob.domain.BlobProperties;\nimport org.jclouds.azureblob.domain.AccessTier;\nimport org.jclouds.azureblob.domain.BlobType;\nimport org.jclouds.azureblob.domain.LeaseStatus;\nimport org.jclouds.io.ContentMetadata;\nimport org.jclouds.io.payloads.BaseImmutableContentMetadata;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.collect.Maps;\n\n/**\n * Allows you to manipulate metadata.\n */\npublic class BlobPropertiesImpl implements BlobProperties {\n\n   private final BlobType type;\n   private final AccessTier tier;\n   private final String name;\n   private final String container;\n   private final URI url;\n   private final Date lastModified;\n   private final String eTag;\n   private final Map<String, String> metadata = Maps.newLinkedHashMap();\n   private final LeaseStatus leaseStatus;\n   private final BaseImmutableContentMetadata contentMetadata;\n\n   @Deprecated\n   public BlobPropertiesImpl(BlobType type, String name, String container, URI url, @Nullable Date lastModified, @Nullable String eTag,\n            long size, String contentType, @Nullable byte[] contentMD5, @Nullable String contentMetadata,\n            @Nullable String contentLanguage, @Nullable Date currentExpires, LeaseStatus leaseStatus, \n            Map<String, String> metadata) {\n      this(type, null, name, container, url, lastModified, eTag, size, contentType, contentMD5, contentMetadata, contentLanguage, currentExpires, leaseStatus, metadata);\n   }\n\n   // TODO: should this take Cache-Control as well?\n   public BlobPropertiesImpl(BlobType type, @Nullable AccessTier tier, String name, String container, URI url, @Nullable Date lastModified, @Nullable String eTag,\n            long size, String contentType, @Nullable byte[] contentMD5, @Nullable String contentMetadata,\n            @Nullable String contentLanguage, @Nullable Date currentExpires, LeaseStatus leaseStatus,\n            Map<String, String> metadata) {\n      this.type = checkNotNull(type, \"type\");\n      this.tier = tier;\n      this.leaseStatus = checkNotNull(leaseStatus, \"leaseStatus\");\n      this.name = checkNotNull(name, \"name\");\n      this.container = checkNotNull(container, \"container\");\n      this.url = checkNotNull(url, \"url\");\n      this.lastModified = lastModified;\n      this.eTag = eTag;\n      this.contentMetadata = new BaseImmutableContentMetadata(contentType, size, contentMD5, null, contentLanguage,\n               contentMetadata, currentExpires);\n      this.metadata.putAll(checkNotNull(metadata, \"metadata\"));\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public BlobType getType() {\n      return type;\n   }\n\n   @Override\n   public AccessTier getTier() {\n      return tier;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public String getName() {\n      return name;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public String getContainer() {\n      return container;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public Date getLastModified() {\n      return lastModified;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public String getETag() {\n      return eTag;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public int compareTo(BlobProperties o) {\n      return (this == o) ? 0 : getName().compareTo(o.getName());\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public Map<String, String> getMetadata() {\n      return metadata;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public URI getUrl() {\n      return url;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public LeaseStatus getLeaseStatus() {\n      return leaseStatus;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public ContentMetadata getContentMetadata() {\n      return contentMetadata;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((url == null) ? 0 : url.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      BlobPropertiesImpl other = (BlobPropertiesImpl) obj;\n      if (url == null) {\n         if (other.url != null)\n            return false;\n      } else if (!url.equals(other.url))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return String\n               .format(\n                        \"[name=%s, container=%s, url=%s, contentMetadata=%s, eTag=%s, lastModified=%s, leaseStatus=%s, metadata=%s, type=%s]\",\n                        name, container, url, contentMetadata, eTag, lastModified, leaseStatus, metadata, type);\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/domain/internal/ContainerPropertiesImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.domain.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.Map;\n\nimport org.jclouds.azureblob.domain.ContainerProperties;\nimport org.jclouds.azureblob.domain.PublicAccess;\n\nimport com.google.common.collect.Maps;\n\n/**\n * Allows you to manipulate metadata.\n */\npublic class ContainerPropertiesImpl implements ContainerProperties {\n\n   private final String name;\n   private final URI url;\n   private final Date lastModified;\n   private final String eTag;\n   private final PublicAccess publicAccess;\n   private final Map<String, String> metadata = Maps.newLinkedHashMap();\n\n   public ContainerPropertiesImpl(URI url, Date lastModified, String eTag, Map<String, String> metadata, PublicAccess publicAccess) {\n      this.url = checkNotNull(url, \"url\");\n      this.name = checkNotNull(url.getPath(), \"url.getPath()\").replaceFirst(\"/\", \"\");\n      this.lastModified = checkNotNull(lastModified, \"lastModified\");\n      this.eTag = checkNotNull(eTag, \"eTag\");\n      this.metadata.putAll(checkNotNull(metadata, \"metadata\"));\n      this.publicAccess = checkNotNull(publicAccess);\n   }\n\n   @Deprecated\n   public ContainerPropertiesImpl(URI url, Date lastModified, String eTag, Map<String, String> metadata) {\n      this(url, lastModified, eTag, metadata, PublicAccess.PRIVATE);\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public String getName() {\n      return name;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public Date getLastModified() {\n      return lastModified;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public String getETag() {\n      return eTag;\n   }\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public int compareTo(ContainerProperties o) {\n      return (this == o) ? 0 : getName().compareTo(o.getName());\n   }\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public Map<String, String> getMetadata() {\n      return metadata;\n   }   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public URI getUrl() {\n      return url;\n   }\n\n   @Override\n   public PublicAccess getPublicAccess() {\n      return publicAccess;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((eTag == null) ? 0 : eTag.hashCode());\n      result = prime * result + ((lastModified == null) ? 0 : lastModified.hashCode());\n      result = prime * result + ((name == null) ? 0 : name.hashCode());\n      result = prime * result + ((url == null) ? 0 : url.hashCode());\n      result = prime * result + ((publicAccess == null) ? 0 : publicAccess.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      ContainerPropertiesImpl other = (ContainerPropertiesImpl) obj;\n      if (eTag == null) {\n         if (other.eTag != null)\n            return false;\n      } else if (!eTag.equals(other.eTag))\n         return false;\n      if (lastModified == null) {\n         if (other.lastModified != null)\n            return false;\n      } else if (!lastModified.equals(other.lastModified))\n         return false;\n      if (name == null) {\n         if (other.name != null)\n            return false;\n      } else if (!name.equals(other.name))\n         return false;\n      if (url == null) {\n         if (other.url != null)\n            return false;\n      } else if (!url.equals(other.url))\n         return false;\n      if (publicAccess == null) {\n         if (other.publicAccess != null)\n            return false;\n      } else if (!publicAccess.equals(other.publicAccess))\n         return false;\n      return true;\n   }\n\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/domain/internal/HashSetListBlobsResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.domain.internal;\n\nimport java.net.URI;\nimport java.util.Set;\n\nimport org.jclouds.azure.storage.domain.internal.BoundedHashSet;\nimport org.jclouds.azureblob.domain.BlobProperties;\nimport org.jclouds.azureblob.domain.ListBlobsResponse;\n\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Sets;\n\npublic class HashSetListBlobsResponse extends BoundedHashSet<BlobProperties> implements\n         ListBlobsResponse {\n\n   protected final String delimiter;\n   protected final Set<String> blobPrefixes = Sets.newHashSet();\n\n   public HashSetListBlobsResponse(Iterable<BlobProperties> contents, URI url, String prefix,\n            String marker, Integer maxResults, String nextMarker, String delimiter,\n            Iterable<String> blobPrefixes) {\n      super(contents, url, prefix, marker, maxResults, nextMarker);\n      this.delimiter = delimiter;\n      Iterables.addAll(this.blobPrefixes, blobPrefixes);\n   }\n\n   public String getDelimiter() {\n      return delimiter;\n   }\n\n   public Set<String> getBlobPrefixes() {\n      return blobPrefixes;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = super.hashCode();\n      result = prime * result + ((blobPrefixes == null) ? 0 : blobPrefixes.hashCode());\n      result = prime * result + ((delimiter == null) ? 0 : delimiter.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (!super.equals(obj))\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      HashSetListBlobsResponse other = (HashSetListBlobsResponse) obj;\n      if (blobPrefixes == null) {\n         if (other.blobPrefixes != null)\n            return false;\n      } else if (!blobPrefixes.equals(other.blobPrefixes))\n         return false;\n      if (delimiter == null) {\n         if (other.delimiter != null)\n            return false;\n      } else if (!delimiter.equals(other.delimiter))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"[blobPrefixes=\" + blobPrefixes + \", delimiter=\" + delimiter\n               + \"]\";\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/domain/internal/ListBlobBlocksResponseImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.domain.internal;\n\nimport org.jclouds.azureblob.domain.BlobBlockProperties;\nimport org.jclouds.azureblob.domain.ListBlobBlocksResponse;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\n\nimport java.util.List;\nimport com.google.common.base.Objects;\n\n/**\n * Represents the list of blocks which compose a blob\n */\npublic class ListBlobBlocksResponseImpl implements ListBlobBlocksResponse {\n   private final List<BlobBlockProperties> blocks;\n\n   public ListBlobBlocksResponseImpl(List<BlobBlockProperties> blocks) {\n      this.blocks = checkNotNull(blocks, \"block list must not be null\");\n   }\n\n   @Override\n   public List<BlobBlockProperties> getBlocks() {\n      return blocks;\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o) return true;\n      if (o == null || getClass() != o.getClass()) return false;\n\n      ListBlobBlocksResponseImpl that = (ListBlobBlocksResponseImpl) o;\n      return Objects.equal(blocks, that.blocks);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(blocks);\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/domain/internal/MutableBlobPropertiesImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.domain.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.Map;\n\nimport org.jclouds.azureblob.domain.AccessTier;\nimport org.jclouds.azureblob.domain.BlobProperties;\nimport org.jclouds.azureblob.domain.BlobType;\nimport org.jclouds.azureblob.domain.LeaseStatus;\nimport org.jclouds.azureblob.domain.MutableBlobProperties;\nimport org.jclouds.http.HttpUtils;\nimport org.jclouds.io.MutableContentMetadata;\nimport org.jclouds.io.payloads.BaseMutableContentMetadata;\n\nimport com.google.common.collect.Maps;\n\n/**\n * Allows you to manipulate metadata.\n */\npublic class MutableBlobPropertiesImpl implements MutableBlobProperties {\n\n   private BlobType type = BlobType.BLOCK_BLOB;\n   private AccessTier tier;\n   private LeaseStatus leaseStatus = LeaseStatus.UNLOCKED;\n\n   private String name;\n   private String container;\n   private URI url;\n   private Date lastModified;\n   private String eTag;\n   private MutableContentMetadata contentMetadata;\n   private Map<String, String> metadata = Maps.newHashMap();\n\n   public MutableBlobPropertiesImpl() {\n      super();\n      this.contentMetadata = new BaseMutableContentMetadata();\n   }\n\n   public MutableBlobPropertiesImpl(BlobProperties from) {\n      this.contentMetadata = new BaseMutableContentMetadata();\n      this.name = from.getName();\n      this.container = from.getContainer();\n      this.url = from.getUrl();\n      this.lastModified = from.getLastModified();\n      this.eTag = from.getETag();\n      this.metadata.putAll(from.getMetadata());\n      HttpUtils.copy(from.getContentMetadata(), this.contentMetadata);\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public BlobType getType() {\n      return type;\n   }\n\n   /**\n    * Set the blob type.\n    */\n   public void setType(BlobType type) {\n      this.type = type;\n   }\n\n   @Override\n   public AccessTier getTier() {\n      return tier;\n   }\n\n   @Override\n   public void setTier(AccessTier tier) {\n      this.tier = checkNotNull(tier);\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public String getName() {\n      return name;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public Date getLastModified() {\n      return lastModified;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public String getETag() {\n      return eTag;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public int compareTo(BlobProperties o) {\n      return (this == o) ? 0 : getName().compareTo(o.getName());\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public Map<String, String> getMetadata() {\n      return metadata;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public LeaseStatus getLeaseStatus() {\n      return leaseStatus;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public void setETag(String eTag) {\n      this.eTag = eTag;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public void setName(String name) {\n      this.name = name;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public void setLastModified(Date lastModified) {\n      this.lastModified = lastModified;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public void setMetadata(Map<String, String> metadata) {\n      this.metadata = metadata;\n   }\n\n   public void setUrl(URI url) {\n      this.url = url;\n   }\n\n   public URI getUrl() {\n      return url;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((url == null) ? 0 : url.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      MutableBlobPropertiesImpl other = (MutableBlobPropertiesImpl) obj;\n      if (url == null) {\n         if (other.url != null)\n            return false;\n      } else if (!url.equals(other.url))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return String\n               .format(\n                        \"[name=%s, container=%s, url=%s, contentMetadata=%s, eTag=%s, lastModified=%s, leaseStatus=%s, metadata=%s, type=%s]\",\n                        name, container, url, contentMetadata, eTag, lastModified, leaseStatus, metadata, type);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public MutableContentMetadata getContentMetadata() {\n      return contentMetadata;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public void setContentMetadata(MutableContentMetadata contentMetadata) {\n      this.contentMetadata = contentMetadata;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public String getContainer() {\n      return container;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public void setContainer(String container) {\n      this.container = container;\n   }\n\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/domain/internal/MutableContainerPropertiesWithMetadataImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.domain.internal;\n\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.Map;\n\nimport org.jclouds.azureblob.domain.ContainerProperties;\nimport org.jclouds.azureblob.domain.MutableContainerPropertiesWithMetadata;\nimport org.jclouds.azureblob.domain.PublicAccess;\n\nimport com.google.common.collect.Maps;\n\n/**\n * Allows you to manipulate metadata.\n */\npublic class MutableContainerPropertiesWithMetadataImpl implements\n         MutableContainerPropertiesWithMetadata {\n\n   private String name;\n   private URI url;\n   private Date lastModified;\n   private String eTag;\n   private PublicAccess publicAccess;\n\n   private Map<String, String> metadata = Maps.newHashMap();\n\n   public MutableContainerPropertiesWithMetadataImpl() {\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public String getName() {\n      return name;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public Date getLastModified() {\n      return lastModified;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public String getETag() {\n      return eTag;\n   }\n\n   @Override\n   public PublicAccess getPublicAccess() {\n      return publicAccess;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public int compareTo(ContainerProperties o) {\n      return (this == o) ? 0 : getName().compareTo(o.getName());\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public Map<String, String> getMetadata() {\n      return metadata;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public void setETag(String eTag) {\n      this.eTag = eTag;\n   }\n\n   @Override\n   public void setPublicAccess(PublicAccess publicAccess) {\n      this.publicAccess = publicAccess;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public void setName(String name) {\n      this.name = name;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public void setLastModified(Date lastModified) {\n      this.lastModified = lastModified;\n   }\n\n   /**\n    *{@inheritDoc}\n    */\n   @Override\n   public void setMetadata(Map<String, String> metadata) {\n      this.metadata = metadata;\n   }\n\n   public void setUrl(URI url) {\n      this.url = url;\n   }\n\n   public URI getUrl() {\n      return url;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((eTag == null) ? 0 : eTag.hashCode());\n      result = prime * result + ((lastModified == null) ? 0 : lastModified.hashCode());\n      result = prime * result + ((metadata == null) ? 0 : metadata.hashCode());\n      result = prime * result + ((name == null) ? 0 : name.hashCode());\n      result = prime * result + ((url == null) ? 0 : url.hashCode());\n      result = prime * result + ((publicAccess == null) ? 0 : publicAccess.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      MutableContainerPropertiesWithMetadataImpl other = (MutableContainerPropertiesWithMetadataImpl) obj;\n      if (eTag == null) {\n         if (other.eTag != null)\n            return false;\n      } else if (!eTag.equals(other.eTag))\n         return false;\n      if (lastModified == null) {\n         if (other.lastModified != null)\n            return false;\n      } else if (!lastModified.equals(other.lastModified))\n         return false;\n      if (metadata == null) {\n         if (other.metadata != null)\n            return false;\n      } else if (!metadata.equals(other.metadata))\n         return false;\n      if (name == null) {\n         if (other.name != null)\n            return false;\n      } else if (!name.equals(other.name))\n         return false;\n      if (url == null) {\n         if (other.url != null)\n            return false;\n      } else if (!url.equals(other.url))\n         return false;\n      if (publicAccess == null) {\n         if (other.publicAccess != null)\n            return false;\n      } else if (!publicAccess.equals(other.publicAccess))\n         return false;\n      return true;\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/functions/BlobName.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.functions;\n\nimport org.jclouds.azureblob.domain.AzureBlob;\n\nimport com.google.common.base.Function;\n\npublic class BlobName implements Function<Object, String> {\n\n   public String apply(Object from) {\n      return ((AzureBlob) from).getProperties().getName();\n   }\n\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/functions/ParseBlobFromHeadersAndHttpContent.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.functions;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.azureblob.domain.AzureBlob;\nimport org.jclouds.azureblob.domain.MutableBlobProperties;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rest.InvocationContext;\n\nimport com.google.common.base.Function;\n\n/**\n * Parses response headers and creates a new AzureBlob from them and the HTTP content.\n * \n * @see ParseMetadataFromHeaders\n */\n@Singleton\npublic class ParseBlobFromHeadersAndHttpContent implements Function<HttpResponse, AzureBlob>,\n      InvocationContext<ParseBlobFromHeadersAndHttpContent> {\n\n   private final ParseBlobPropertiesFromHeaders metadataParser;\n   private final AzureBlob.Factory blobFactory;\n\n   @Inject\n   public ParseBlobFromHeadersAndHttpContent(ParseBlobPropertiesFromHeaders metadataParser,\n         AzureBlob.Factory blobFactory) {\n      this.metadataParser = metadataParser;\n      this.blobFactory = blobFactory;\n   }\n\n   public AzureBlob apply(HttpResponse from) {\n      MutableBlobProperties metadata = metadataParser.apply(from);\n      AzureBlob blob = blobFactory.create(metadata);\n      blob.getAllHeaders().putAll(from.getHeaders());\n      blob.setPayload(from.getPayload());\n      return blob;\n   }\n\n   @Override\n   public ParseBlobFromHeadersAndHttpContent setContext(HttpRequest request) {\n      metadataParser.setContext(request);\n      return this;\n   }\n\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/functions/ParseBlobPropertiesFromHeaders.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.functions;\n\nimport static com.google.common.base.Preconditions.checkArgument;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.azureblob.blobstore.functions.BlobMetadataToBlobProperties;\nimport org.jclouds.azureblob.domain.AccessTier;\nimport org.jclouds.azureblob.domain.MutableBlobProperties;\nimport org.jclouds.blobstore.domain.BlobMetadata;\nimport org.jclouds.blobstore.functions.ParseSystemAndUserMetadataFromHeaders;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rest.InvocationContext;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\n\nimport com.google.common.base.Function;\n\n/**\n * This parses @{link {@link org.jclouds.azureblob.domain.BlobProperties} from HTTP\n * headers.\n */\npublic class ParseBlobPropertiesFromHeaders implements Function<HttpResponse, MutableBlobProperties>,\n      InvocationContext<ParseBlobPropertiesFromHeaders> {\n   private final ParseSystemAndUserMetadataFromHeaders blobMetadataParser;\n   private final BlobMetadataToBlobProperties blobToBlobProperties;\n   private String container;\n\n   @Inject\n   public ParseBlobPropertiesFromHeaders(ParseSystemAndUserMetadataFromHeaders blobMetadataParser,\n         BlobMetadataToBlobProperties blobToBlobProperties) {\n      this.blobMetadataParser = blobMetadataParser;\n      this.blobToBlobProperties = blobToBlobProperties;\n   }\n\n   /**\n    * parses the http response headers to create a new {@link MutableBlobProperties} object.\n    */\n   public MutableBlobProperties apply(HttpResponse from) {\n      BlobMetadata base = blobMetadataParser.apply(from);\n      MutableBlobProperties to = blobToBlobProperties.apply(base);\n      to.setContainer(container);\n      String tier = from.getFirstHeaderOrNull(\"x-ms-access-tier\");\n      if (tier != null) {\n         to.setTier(AccessTier.fromValue(tier));\n      }\n      return to;\n   }\n\n\n   @Override\n   public ParseBlobPropertiesFromHeaders setContext(HttpRequest request) {\n      checkArgument(request instanceof GeneratedHttpRequest, \"note this handler requires a GeneratedHttpRequest\");\n      blobMetadataParser.setContext(request);\n      return setContainer(GeneratedHttpRequest.class.cast(request).getInvocation().getArgs().get(0).toString());\n   }\n\n   private ParseBlobPropertiesFromHeaders setContainer(String container) {\n      this.container = container;\n      return this;\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/functions/ParseContainerPropertiesFromHeaders.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.functions;\n\nimport static com.google.common.base.Preconditions.checkArgument;\n\nimport java.util.Map.Entry;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\n\nimport org.jclouds.azureblob.domain.ContainerProperties;\nimport org.jclouds.azureblob.domain.MutableContainerPropertiesWithMetadata;\nimport org.jclouds.azureblob.domain.internal.MutableContainerPropertiesWithMetadataImpl;\nimport org.jclouds.blobstore.reference.BlobStoreConstants;\nimport org.jclouds.date.DateService;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rest.InvocationContext;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Function;\nimport com.google.common.net.HttpHeaders;\n\n/**\n * This parses @{link {@link org.jclouds.azureblob.domain.ListableContainerProperties} from\n * HTTP headers.\n */\npublic class ParseContainerPropertiesFromHeaders implements Function<HttpResponse, ContainerProperties>,\n      InvocationContext<ParseContainerPropertiesFromHeaders> {\n\n   private final DateService dateParser;\n   private final String metadataPrefix;\n   private GeneratedHttpRequest request;\n\n   @Inject\n   public ParseContainerPropertiesFromHeaders(DateService dateParser,\n         @Named(BlobStoreConstants.PROPERTY_USER_METADATA_PREFIX) String metadataPrefix) {\n      this.dateParser = dateParser;\n      this.metadataPrefix = metadataPrefix;\n   }\n\n   public ContainerProperties apply(HttpResponse from) {\n      MutableContainerPropertiesWithMetadata to = new MutableContainerPropertiesWithMetadataImpl();\n      to.setName(request.getInvocation().getArgs().get(0).toString());\n      addUserMetadataTo(from, to);\n      parseLastModifiedOrThrowException(from, to);\n      addETagTo(from, to);\n      to.setUrl(request.getEndpoint());\n      to.setPublicAccess(new ParsePublicAccessHeader().apply(from));\n      return to;\n   }\n\n   @VisibleForTesting\n   void addUserMetadataTo(HttpResponse from, MutableContainerPropertiesWithMetadata metadata) {\n      for (Entry<String, String> header : from.getHeaders().entries()) {\n         if (header.getKey() != null && header.getKey().startsWith(metadataPrefix))\n            metadata.getMetadata().put((header.getKey().substring(metadataPrefix.length())).toLowerCase(),\n                  header.getValue());\n      }\n   }\n\n   @VisibleForTesting\n   void parseLastModifiedOrThrowException(HttpResponse from, MutableContainerPropertiesWithMetadata metadata)\n         throws HttpException {\n      String lastModified = from.getFirstHeaderOrNull(HttpHeaders.LAST_MODIFIED);\n      if (lastModified == null)\n         throw new HttpException(HttpHeaders.LAST_MODIFIED + \" header not present in response: \" + from);\n      metadata.setLastModified(dateParser.rfc822DateParse(lastModified));\n      if (metadata.getLastModified() == null)\n         throw new HttpException(\"could not parse: \" + HttpHeaders.LAST_MODIFIED + \": \" + lastModified);\n   }\n\n   @VisibleForTesting\n   protected void addETagTo(HttpResponse from, MutableContainerPropertiesWithMetadata metadata) {\n      String eTag = from.getFirstHeaderOrNull(HttpHeaders.ETAG);\n      if (metadata.getETag() == null && eTag != null) {\n         metadata.setETag(eTag);\n      }\n   }\n\n   @Override\n   public ParseContainerPropertiesFromHeaders setContext(HttpRequest request) {\n      checkArgument(request instanceof GeneratedHttpRequest, \"note this handler requires a GeneratedHttpRequest\");\n      this.request = (GeneratedHttpRequest) request;\n      return this;\n   }\n\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/functions/ParsePublicAccessHeader.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.functions;\n\nimport static org.jclouds.http.HttpUtils.releasePayload;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.azureblob.domain.PublicAccess;\nimport org.jclouds.http.HttpResponse;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class ParsePublicAccessHeader implements Function<HttpResponse, PublicAccess> {\n\n   public PublicAccess apply(HttpResponse from) {\n      releasePayload(from);\n      String access = from.getFirstHeaderOrNull(\"x-ms-blob-public-access\");\n      if (access == null) {\n         return PublicAccess.PRIVATE;\n      }\n      return PublicAccess.valueOf(access.toUpperCase());\n   }\n\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/handlers/ParseAzureBlobErrorFromXmlContent.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.handlers;\n\nimport java.util.List;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.azure.storage.domain.AzureStorageError;\nimport org.jclouds.azure.storage.handlers.ParseAzureStorageErrorFromXmlContent;\nimport org.jclouds.azure.storage.util.AzureStorageUtils;\nimport org.jclouds.blobstore.ContainerNotFoundException;\nimport org.jclouds.blobstore.KeyNotFoundException;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rest.ResourceNotFoundException;\n\nimport com.google.common.base.Joiner;\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.Lists;\n\n@Singleton\npublic class ParseAzureBlobErrorFromXmlContent extends ParseAzureStorageErrorFromXmlContent {\n\n   @Inject\n   ParseAzureBlobErrorFromXmlContent(AzureStorageUtils utils) {\n      super(utils);\n   }\n\n   protected Exception refineException(HttpCommand command, HttpResponse response, Exception exception,\n            AzureStorageError error, String message) {\n      switch (response.getStatusCode()) {\n         case 404:\n            if (!command.getCurrentRequest().getMethod().equals(\"DELETE\")) {\n               exception = new ResourceNotFoundException(message, exception);\n               List<String> parts = Lists.newArrayList(Splitter.on('/').split(\n                        command.getCurrentRequest().getEndpoint().getPath()));\n               parts.remove(\"\");\n               if (!parts.isEmpty()) {\n                  String container = parts.remove(0);\n                  String query = command.getCurrentRequest().getEndpoint().getQuery();\n                  if (query != null && query.indexOf(\"container\") != -1) {\n                     exception = new ContainerNotFoundException(container, message);\n                  } else {\n                     exception = new KeyNotFoundException(container, Joiner.on('/').join(parts), message);\n                  }\n               }\n            }\n            return exception;\n         default:\n            return super.refineException(command, response, exception, error, message);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/options/CopyBlobOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.azureblob.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Date;\nimport java.util.Map;\n\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableMap;\n\npublic final class CopyBlobOptions {\n   public static final CopyBlobOptions NONE = CopyBlobOptions.builder().build();\n\n   private final Optional<Map<String, String>> userMetadata;\n   private final Optional<Date> ifModifiedSince;\n   private final Optional<Date> ifUnmodifiedSince;\n   private final Optional<String> ifMatch;\n   private final Optional<String> ifNoneMatch;\n\n   private CopyBlobOptions(Map<String, String> userMetadata, Date ifModifiedSince, Date ifUnmodifiedSince,\n         String ifMatch, String ifNoneMatch) {\n      this.userMetadata = Optional.fromNullable(userMetadata);\n      this.ifModifiedSince = Optional.fromNullable(ifModifiedSince);\n      this.ifUnmodifiedSince = Optional.fromNullable(ifUnmodifiedSince);\n      this.ifMatch = Optional.fromNullable(ifMatch);\n      this.ifNoneMatch = Optional.fromNullable(ifNoneMatch);\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Optional<Map<String, String>> getUserMetadata() {\n      return userMetadata;\n   }\n\n   public Optional<Date> getIfModifiedSince() {\n      return Optional.fromNullable(ifModifiedSince.isPresent() ? (Date) ifModifiedSince.get().clone() : null);\n   }\n\n   public Optional<Date> getIfUnmodifiedSince() {\n      return Optional.fromNullable(ifUnmodifiedSince.isPresent() ? (Date) ifUnmodifiedSince.get().clone() : null);\n   }\n\n   public Optional<String> getIfMatch() {\n      return ifMatch;\n   }\n\n   public Optional<String> getIfNoneMatch() {\n      return ifNoneMatch;\n   }\n\n   public static class Builder {\n      private Map<String, String> userMetadata;\n      private Date ifModifiedSince;\n      private Date ifUnmodifiedSince;\n      private String ifMatch;\n      private String ifNoneMatch;\n\n      Builder() {\n      }\n\n      public Builder overrideUserMetadata(Map<String, String> userMetadata) {\n         this.userMetadata = ImmutableMap.copyOf(checkNotNull(userMetadata, \"userMetadata\"));\n         return this;\n      }\n\n      public Builder ifModifiedSince(Date ifModifiedSince) {\n         this.ifModifiedSince = (Date) checkNotNull(ifModifiedSince, \"ifModifiedSince\").clone();\n         return this;\n      }\n\n      public Builder ifUnmodifiedSince(Date ifUnmodifiedSince) {\n         this.ifUnmodifiedSince = (Date) checkNotNull(ifUnmodifiedSince, \"ifUnmodifiedSince\").clone();\n         return this;\n      }\n\n      public Builder ifMatch(String ifMatch) {\n         this.ifMatch = checkNotNull(ifMatch, \"ifMatch\");\n         return this;\n      }\n\n      public Builder ifNoneMatch(String ifNoneMatch) {\n         this.ifNoneMatch = checkNotNull(ifNoneMatch, \"ifNoneMatch\");\n         return this;\n      }\n\n      public CopyBlobOptions build() {\n         return new CopyBlobOptions(userMetadata, ifModifiedSince, ifUnmodifiedSince, ifMatch, ifNoneMatch);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/options/CreateContainerOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.options;\n\nimport org.jclouds.azure.storage.options.CreateOptions;\nimport org.jclouds.azureblob.domain.PublicAccess;\n\nimport com.google.common.collect.Multimap;\n\n/**\n * Contains options supported in the REST API for the Create Container operation. <h2>\n * Usage</h2> The recommended way to instantiate a CreateContainerOptions object is to statically\n * import CreateContainerOptions.* and invoke a static creation method followed by an instance\n * mutator (if needed):\n * <p/>\n * <code>\n * import static org.jclouds.azureblob.options.CreateContainerOptions.Builder.*\n * import org.jclouds.azureblob.AzureBlobClient;\n * <p/>\n * AzureBlobClient connection = // get connection\n * boolean createdWithPublicAccess = connection.createContainer(\"containerName\", withPublicAccess(PublicAccess.BLOB));\n * <code> *\n * \n * @see <a href=\"http://msdn.microsoft.com/en-us/library/dd179466.aspx\" />\n */\npublic class CreateContainerOptions extends CreateOptions {\n   public static final CreateContainerOptions NONE = new CreateContainerOptions();\n\n   @Override\n   public CreateContainerOptions withMetadata(Multimap<String, String> metadata) {\n      return (CreateContainerOptions) super.withMetadata(metadata);\n   }\n\n   /**\n    * Indicates whether a container may be accessed publicly\n    */\n   public CreateContainerOptions withPublicAccess(PublicAccess access) {\n      if (access != PublicAccess.PRIVATE)\n         this.headers.put(\"x-ms-blob-public-access\", access.name().toLowerCase());\n      return this;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see CreateContainerOptions#withPublicAccess\n       */\n      public static CreateContainerOptions withPublicAccess(PublicAccess access) {\n         CreateContainerOptions options = new CreateContainerOptions();\n         return options.withPublicAccess(access);\n      }\n\n      /**\n       * @see CreateContainerOptions#withMetadata(Multimap<String, String>)\n       */\n      public static CreateContainerOptions withMetadata(Multimap<String, String> metadata) {\n         CreateContainerOptions options = new CreateContainerOptions();\n         return options.withMetadata(metadata);\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/options/ListBlobsOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.options;\n\nimport java.util.Set;\n\nimport org.jclouds.azure.storage.options.ListOptions;\nimport org.jclouds.azureblob.domain.ListBlobsInclude;\n\nimport com.google.common.base.Joiner;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Contains options supported in the REST API for the List Blobs operation. <h2>\n * Usage</h2> The recommended way to instantiate a ListBlobsOptions object is to statically import\n * ListBlobsOptions.* and invoke a static creation method followed by an instance mutator (if\n * needed):\n * <p/>\n * <code>\n * import static org.jclouds.azureblob.options.ListBlobsOptions.Builder.*\n * import org.jclouds.azureblob.AzureBlobClient;\n * <p/>\n * AzureBlobClient connection = // get connection\n * Set<BlobMetadata> blobs = connection.listBlobs(\"containerName\", delimiter(\"/\"));\n * <code> *\n * \n * @see <a href=\"http://msdn.microsoft.com/en-us/library/dd179466.aspx\" />\n */\npublic class ListBlobsOptions extends ListOptions {\n   private Set<String> datasets;\n\n   /**\n    * When the request includes this parameter, the operation returns a {@code BlobPrefix} element\n    * in the response body that acts as a placeholder for all blobs whose names begin with the same\n    * substring up to the appearance of the delimiter character.\n    * \n    * @param delimiter\n    *           a single character or a string.\n    */\n   public ListBlobsOptions delimiter(String delimiter) {\n      this.queryParameters.put(\"delimiter\", delimiter);\n      return this;\n   }\n\n   public String getDelimiter() {\n      return this.getFirstQueryOrNull(\"delimiter\");\n   }\n\n   public static class Builder {\n\n      /**\n       * @see ListBlobsOptions#delimiter(String)\n       */\n      public static ListBlobsOptions delimiter(String delimiter) {\n         ListBlobsOptions options = new ListBlobsOptions();\n         return options.delimiter(delimiter);\n      }\n\n      /**\n       * @see ListOptions#includeMetadata()\n       */\n      public static ListBlobsOptions includeMetadata() {\n         ListBlobsOptions options = new ListBlobsOptions();\n         return options.includeMetadata();\n      }\n\n      /**\n       * @see ListOptions#prefix(String)\n       */\n      public static ListBlobsOptions prefix(String prefix) {\n         ListBlobsOptions options = new ListBlobsOptions();\n         return options.prefix(prefix);\n      }\n\n      /**\n       * @see ListOptions#marker(String)\n       */\n      public static ListBlobsOptions marker(String marker) {\n         ListBlobsOptions options = new ListBlobsOptions();\n         return options.marker(marker);\n      }\n\n      /**\n       * @see ListOptions#maxResults(long)\n       */\n      public static ListBlobsOptions maxResults(int maxKeys) {\n         ListBlobsOptions options = new ListBlobsOptions();\n         return options.maxResults(maxKeys);\n      }\n\n      public static ListBlobsOptions include(Set<ListBlobsInclude> datasets) {\n         ListBlobsOptions options = new ListBlobsOptions();\n         return options.include(datasets);\n      }\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ListBlobsOptions includeMetadata() {\n      return (ListBlobsOptions) super.includeMetadata();\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ListBlobsOptions marker(String marker) {\n      return (ListBlobsOptions) super.marker(marker);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ListBlobsOptions maxResults(int maxresults) {\n      return (ListBlobsOptions) super.maxResults(maxresults);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public ListBlobsOptions prefix(String prefix) {\n      return (ListBlobsOptions) super.prefix(prefix);\n   }\n\n   public ListBlobsOptions include(Set<ListBlobsInclude> datasets) {\n      ImmutableSet.Builder<String> builder = ImmutableSet.builder();\n      for (ListBlobsInclude dataset : datasets) {\n         builder.add(dataset.toString());\n      }\n      this.datasets = builder.build();\n      this.queryParameters.put(\"include\", Joiner.on(\",\").join(this.datasets));\n      return this;\n   }\n\n   public Set<String> getInclude() {\n      return datasets;\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/predicates/validators/BlockIdValidator.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.predicates.validators;\n\nimport com.google.inject.Singleton;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.predicates.Validator;\n\n/**\n * Validates Block IDs used in Put Block:\n *\n * \"A valid Base64 string value that identifies the block. Prior to encoding, the string must\n * be less than or equal to 64 bytes in size. For a given blob, the length of the value\n * specified for the blockid parameter must be the same size for each block. Note that the\n * Base64 string must be URL-encoded.\"\n *\n * @see {http://msdn.microsoft.com/en-us/library/windowsazure/dd135726.aspx}\n */\n@Singleton\npublic class BlockIdValidator extends Validator<String> {\n   @Override\n   public void validate(@Nullable String s) throws IllegalArgumentException {\n      if (s == null || s.length() > 64)\n         throw new IllegalArgumentException(\"block id:\" + s + \"; Block Ids must be less than or equal to 64 bytes in size\");\n\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/predicates/validators/ContainerNameValidator.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.predicates.validators;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.predicates.validators.DnsNameValidator;\n\nimport com.google.inject.Singleton;\n\n/**\n * Validates name for Azure container. The complete requirements are listed at:\n * http://weblogs.asp.net\n * /vblasberg/archive/2009/02/17/azure-details-and-limitations-blobs-tables-and-queues.aspx\n * \n * @see org.jclouds.rest.InputParamValidator\n * @see org.jclouds.predicates.Validator\n */\n@Singleton\npublic class ContainerNameValidator extends DnsNameValidator {\n\n   @Inject\n   ContainerNameValidator() {\n      super(3, 63);\n   }\n\n   public void validate(String containerName) {\n      super.validate(containerName);\n      if (containerName.contains(\"--\"))\n         throw exception(containerName, \"Every dash must be followed by letter or number\");\n      if (containerName.endsWith(\"-\"))\n         throw exception(containerName, \"Shouldn't end with a dash\");\n   }\n\n   @Override\n   protected IllegalArgumentException exception(String containerName, String reason) {\n      return new IllegalArgumentException(\n               String\n                        .format(\n                                 \"Object '%s' doesn't match Azure container naming convention. \"\n                                          + \"Reason: %s. For more info, please refer to http://weblogs.asp.net/vblasberg/archive/2009/02/17/\"\n                                          + \"azure-details-and-limitations-blobs-tables-and-queues.aspx.\",\n                                 containerName, reason));\n   }\n\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/xml/AccountNameEnumerationResultsHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.xml;\n\nimport static com.google.common.base.Throwables.propagate;\n\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.util.Date;\nimport java.util.Map;\nimport java.util.SortedSet;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.azure.storage.domain.BoundedSet;\nimport org.jclouds.azure.storage.domain.internal.BoundedHashSet;\nimport org.jclouds.azureblob.domain.ContainerProperties;\nimport org.jclouds.azureblob.domain.PublicAccess;\nimport org.jclouds.azureblob.domain.internal.ContainerPropertiesImpl;\nimport org.jclouds.date.DateService;\nimport org.jclouds.http.functions.ParseSax;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\n\nimport com.google.common.collect.Maps;\nimport com.google.common.collect.Sets;\n\n/**\n * Parses the following XML document:\n * <p/>\n * EnumerationResults AccountName=\"http://myaccount.blob.core.windows.net\"\n * \n * @see <a href=\"http://msdn.microsoft.com/en-us/library/dd179352.aspx\" />\n */\npublic class AccountNameEnumerationResultsHandler extends\n         ParseSax.HandlerWithResult<BoundedSet<ContainerProperties>> {\n\n   private SortedSet<ContainerProperties> containerMetadata = Sets.newTreeSet();\n   private String prefix;\n   private String marker;\n   private int maxResults;\n   private String nextMarker;\n   private String currentName;\n   private Date currentLastModified;\n   private String currentETag;\n   private PublicAccess currentPublicAccess = PublicAccess.PRIVATE;\n   private boolean inMetadata;\n\n   private Map<String, String> currentMetadata = Maps.newHashMap();\n\n   private StringBuilder currentText = new StringBuilder();\n\n   private final DateService dateParser;\n   private URI accountUrl;\n\n   @Inject\n   public AccountNameEnumerationResultsHandler(DateService dateParser) {\n      this.dateParser = dateParser;\n   }\n\n   @Override\n   public void startElement(String uri, String localName, String qName, Attributes attributes)\n            throws SAXException {\n      if (qName.equals(\"Container\")) {\n         inMetadata = false;\n      } else if (qName.equals(\"Metadata\")) {\n         inMetadata = true;\n      } else if (qName.equals(\"EnumerationResults\")) {\n         accountUrl = URI.create(attributes.getValue(\"ServiceEndpoint\").trim());\n      }\n   }\n\n   public BoundedSet<ContainerProperties> getResult() {\n      return new BoundedHashSet<ContainerProperties>(containerMetadata, accountUrl, prefix, marker,\n               maxResults, nextMarker);\n   }\n\n   public void endElement(String uri, String name, String qName) {\n      if (inMetadata && !qName.equals(\"Metadata\")) {\n         currentMetadata.put(qName, currentText.toString().trim());\n      } else if (qName.equals(\"Metadata\")) {\n         inMetadata = false;\n      } else if (qName.equals(\"MaxResults\")) {\n         maxResults = Integer.parseInt(currentText.toString().trim());\n      } else if (qName.equals(\"Marker\")) {\n         marker = currentText.toString().trim();\n         marker = (marker.equals(\"\")) ? null : marker;\n      } else if (qName.equals(\"Prefix\")) {\n         prefix = currentText.toString().trim();\n         prefix = (prefix.equals(\"\")) ? null : prefix;\n      } else if (qName.equals(\"NextMarker\")) {\n         nextMarker = currentText.toString().trim();\n         nextMarker = (nextMarker.equals(\"\")) ? null : nextMarker;\n      } else if (qName.equals(\"Container\")) {\n         URI currentUrl;\n         try {\n            currentUrl = new URI(accountUrl.getScheme(), accountUrl.getHost(), \"/\" + currentName, null);\n         } catch (URISyntaxException use) {\n            throw propagate(use);\n         }\n         containerMetadata.add(new ContainerPropertiesImpl(currentUrl, currentLastModified,\n                  currentETag, currentMetadata, currentPublicAccess));\n         currentName = null;\n         currentLastModified = null;\n         currentETag = null;\n         currentPublicAccess = PublicAccess.PRIVATE;\n         currentMetadata = Maps.newHashMap();\n      } else if (qName.equals(\"Name\")) {\n         currentName = currentText.toString().trim();\n      } else if (qName.equals(\"Last-Modified\")) {\n         currentLastModified = dateParser.rfc822DateParse(currentText.toString().trim());\n      } else if (qName.equals(\"Etag\")) {\n         currentETag = currentText.toString().trim();\n      } else if (qName.equals(\"PublicAccess\")) {\n         currentPublicAccess = PublicAccess.fromString(currentText.toString().trim());\n      }\n      currentText.setLength(0);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/xml/BlobBlocksResultsHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.xml;\n\nimport java.util.List;\n\nimport org.jclouds.azureblob.domain.BlobBlockProperties;\nimport org.jclouds.azureblob.domain.ListBlobBlocksResponse;\nimport org.jclouds.azureblob.domain.internal.BlobBlockPropertiesImpl;\nimport org.jclouds.azureblob.domain.internal.ListBlobBlocksResponseImpl;\nimport org.jclouds.http.functions.ParseSax;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\n\nimport com.google.common.collect.Lists;\n\n/**\n * Parses the following document:\n * <pre>\n * <?xml version=\"1.0\" encoding=\"utf-8\"?>\n * <BlockList>\n * <CommittedBlocks>\n * <Block>\n * <Name>base64-encoded-block-id</Name>\n * <Size>size-in-bytes</Size>\n * </Block>\n * <CommittedBlocks>\n * </BlockList>\n * </pre>\n */\npublic class BlobBlocksResultsHandler extends ParseSax.HandlerWithResult<ListBlobBlocksResponse> {\n\n   private StringBuilder currentText = new StringBuilder();\n   private boolean inCommitted = false;\n   private boolean inBlock = false;\n   private boolean inName = false;\n   private boolean inSize = false;\n   private String blockName;\n   private long size;\n   private List<BlobBlockProperties> blocks = Lists.newArrayList();\n\n   @Override\n   public ListBlobBlocksResponse getResult() {\n      return new ListBlobBlocksResponseImpl(blocks);\n   }\n\n   @Override\n   public void startElement(String uri, String localName, String qName, Attributes attributes)\n         throws SAXException {\n      if (\"CommittedBlocks\".equals(qName)) {\n         inCommitted = true;\n      } else if (\"UncommittedBlocks\".equals(qName)) {\n         inCommitted = false;\n      } else if (\"Block\".equals(qName)) {\n         inBlock = true;\n      } else if (\"Name\".equals(qName)) {\n         inName = true;\n      } else if (\"Size\".equals(qName)) {\n         inSize = true;\n      }\n   }\n\n   public void endElement(String uri, String name, String qName) {\n      if (\"CommittedBlocks\".equals(qName)) {\n         inCommitted = false;\n      } else if (\"UncommittedBlocks\".equals(qName)) {\n         inCommitted = false;\n      } else if (\"Block\".equals(qName)) {\n         BlobBlockProperties block = new BlobBlockPropertiesImpl(blockName, size, inCommitted);\n         blocks.add(block);\n         inBlock = false;\n      } else if (\"Name\".equals(qName)) {\n         blockName = currentText.toString().trim();\n         inName = false;\n      } else if (\"Size\".equals(qName)) {\n         size = Long.parseLong(currentText.toString().trim());\n         inSize = false;\n      }\n      currentText.setLength(0);\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n\n}\n"
  },
  {
    "path": "providers/azureblob/src/main/java/org/jclouds/azureblob/xml/ContainerNameEnumerationResultsHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.xml;\n\nimport static com.google.common.io.BaseEncoding.base64;\nimport static org.jclouds.http.Uris.uriBuilder;\n\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.azureblob.domain.AccessTier;\nimport org.jclouds.azureblob.domain.BlobProperties;\nimport org.jclouds.azureblob.domain.BlobType;\nimport org.jclouds.azureblob.domain.LeaseStatus;\nimport org.jclouds.azureblob.domain.ListBlobsResponse;\nimport org.jclouds.azureblob.domain.internal.BlobPropertiesImpl;\nimport org.jclouds.azureblob.domain.internal.HashSetListBlobsResponse;\nimport org.jclouds.date.DateService;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.io.ContentMetadataCodec;\nimport org.jclouds.util.Strings2;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\n\nimport com.google.common.collect.Maps;\nimport com.google.common.collect.Sets;\n\n/**\n * Parses the following XML document:\n * <p/>\n * EnumerationResults ContainerName=\"http://myaccount.blob.core.windows.net/mycontainer\"\n * \n * @see <a href=\"http://msdn.microsoft.com/en-us/library/dd135734.aspx#samplerequestandresponse\" />\n */\npublic class ContainerNameEnumerationResultsHandler extends ParseSax.HandlerWithResult<ListBlobsResponse> {\n   private Set<BlobProperties> blobMetadata = Sets.newLinkedHashSet();\n   private String prefix;\n   private String marker;\n   private int maxResults;\n   private String nextMarker;\n   private URI containerUrl;\n   private Date currentLastModified;\n   private String currentETag;\n\n   private StringBuilder currentText = new StringBuilder();\n\n   private final DateService dateParser;\n   private final ContentMetadataCodec contentMetadataCodec;\n   private String delimiter;\n   private String currentName;\n   private long currentSize;\n   private String currentContentType;\n   private String currentContentEncoding;\n   private String currentContentLanguage;\n   private BlobType currentBlobType;\n   private AccessTier currentAccessTier;\n   private Date currentExpires;\n   private boolean inBlob;\n   private boolean inBlobPrefix;\n   private boolean inMetadata;\n   private Set<String> blobPrefixes = Sets.newHashSet();\n   private byte[] currentContentMD5;\n   private Map<String, String> currentMetadata = Maps.newHashMap();\n   private LeaseStatus currentLeaseStatus;\n\n   @Inject\n   public ContainerNameEnumerationResultsHandler(DateService dateParser, ContentMetadataCodec contentMetadataCodec) {\n      this.dateParser = dateParser;\n      this.contentMetadataCodec = contentMetadataCodec;\n   }\n\n   public ListBlobsResponse getResult() {\n      return new HashSetListBlobsResponse(blobMetadata, containerUrl, prefix, marker, maxResults, nextMarker,\n               delimiter, blobPrefixes);\n   }\n\n   @Override\n   public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {\n      if (qName.equals(\"Blob\")) {\n         inBlob = true;\n         inBlobPrefix = false;\n         inMetadata = false;\n      } else if (qName.equals(\"BlobPrefix\")) {\n         inBlob = false;\n         inBlobPrefix = true;\n      } else if (qName.equals(\"Metadata\")) {\n         inBlob = true;\n         inMetadata = true;\n      } else if (qName.equals(\"EnumerationResults\")) {\n         containerUrl = URI.create(attributes.getValue(\"ServiceEndpoint\").trim() + attributes.getValue(\"ContainerName\").trim());\n      }\n      currentText.setLength(0);\n   }\n\n   public void endElement(String uri, String name, String qName) {\n      if (inMetadata && !qName.equals(\"Metadata\")) {\n         currentMetadata.put(qName, currentText.toString());\n      } else if (qName.equals(\"Metadata\")) {\n         inMetadata = false;\n      } else if (qName.equals(\"MaxResults\")) {\n         maxResults = Integer.parseInt(currentText.toString());\n      } else if (qName.equals(\"Marker\")) {\n         marker = currentText.toString();\n         marker = (marker.equals(\"\")) ? null : marker;\n      } else if (qName.equals(\"Prefix\")) {\n         prefix = currentText.toString();\n         prefix = (prefix.equals(\"\")) ? null : prefix;\n      } else if (qName.equals(\"Delimiter\")) {\n         delimiter = currentText.toString();\n         delimiter = (delimiter.equals(\"\")) ? null : delimiter;\n      } else if (qName.equals(\"NextMarker\")) {\n         nextMarker = currentText.toString();\n         nextMarker = (nextMarker.equals(\"\")) ? null : nextMarker;\n      } else if (qName.equals(\"BlobType\")) {\n         currentBlobType = BlobType.fromValue(currentText.toString());\n      } else if (qName.equals(\"AccessTier\")) {\n         currentAccessTier = AccessTier.fromValue(currentText.toString());\n      } else if (qName.equals(\"LeaseStatus\")) {\n         currentLeaseStatus = LeaseStatus.fromValue(currentText.toString());\n      } else if (qName.equals(\"Blob\")) {\n         URI currentUrl = uriBuilder(containerUrl).appendPath(Strings2.urlEncode(currentName)).build();\n         BlobProperties md = new BlobPropertiesImpl(currentBlobType, currentAccessTier, currentName, containerUrl.getPath().replace(\"/\",\n                  \"\"), currentUrl, currentLastModified, currentETag, currentSize, currentContentType,\n                  currentContentMD5, currentContentEncoding, currentContentLanguage, currentExpires,\n                  currentLeaseStatus, currentMetadata);\n         blobMetadata.add(md);\n         currentBlobType = null;\n         currentAccessTier = null;\n         currentName = null;\n         currentLastModified = null;\n         currentETag = null;\n         currentSize = -1;\n         currentContentType = null;\n         currentContentEncoding = null;\n         currentContentLanguage = null;\n         currentContentMD5 = null;\n         currentLeaseStatus = null;\n         currentExpires = null;\n         currentMetadata = Maps.newHashMap();\n      } else if (qName.equals(\"Last-Modified\")) {\n         currentLastModified = dateParser.rfc822DateParse(currentText.toString());\n      } else if (qName.equals(\"Etag\")) {\n         currentETag = currentText.toString();\n      } else if (qName.equals(\"Name\")) {\n         if (inBlob)\n            currentName = currentText.toString();\n         else if (inBlobPrefix)\n            blobPrefixes.add(currentText.toString());\n      } else if (qName.equals(\"Content-Length\")) {\n         currentSize = Long.parseLong(currentText.toString());\n      } else if (qName.equals(\"Content-MD5\")) {\n         if (!currentText.toString().equals(\"\"))\n            currentContentMD5 = base64().decode(currentText.toString());\n      } else if (qName.equals(\"Content-Type\")) {\n         currentContentType = currentText.toString();\n      } else if (qName.equals(\"Content-Encoding\")) {\n         currentContentEncoding = currentText.toString();\n         if (currentContentEncoding.equals(\"\"))\n            currentContentEncoding = null;\n      } else if (qName.equals(\"Content-Language\")) {\n         currentContentLanguage = currentText.toString();\n         if (currentContentLanguage.equals(\"\"))\n            currentContentLanguage = null;\n      } else if (qName.equals(\"Expires\")) {\n         String expiration = currentText.toString();\n         if (expiration.equals(\"\")) {\n            currentExpires = null;\n         } else {\n            currentExpires = contentMetadataCodec.parseExpires(expiration);\n         }\n      }\n   }\n\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/test/java/org/jclouds/azure/storage/filters/SharedKeyLiteAuthenticationTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azure.storage.filters;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.net.URI;\n\nimport jakarta.ws.rs.HttpMethod;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.logging.config.NullLoggingModule;\nimport org.jclouds.rest.internal.BaseRestApiTest.MockModule;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.DataProvider;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.net.HttpHeaders;\nimport com.google.inject.Injector;\nimport com.google.inject.Module;\n\n@Test(groups = \"unit\")\npublic class SharedKeyLiteAuthenticationTest {\n\n   private static final String ACCOUNT = \"foo\";\n   private Injector injector;\n   private SharedKeyLiteAuthentication filter;\n   private SharedKeyLiteAuthentication filterSAS;\n   private SharedKeyLiteAuthentication filterSASQuestionMark;\n   private SharedKeyLiteAuthentication filterSASCustomEndpoint;\n\n   @DataProvider(parallel = true)\n   public Object[][] dataProvider() {\n      return new Object[][] {\n            { HttpRequest.builder().method(HttpMethod.PUT).endpoint(\"http://\" + ACCOUNT\n                  + \".blob.core.windows.net/movies/MOV1.avi?comp=block&blockid=BlockId1&timeout=60\").build() },\n            { HttpRequest.builder().method(HttpMethod.PUT).endpoint(\"http://\" + ACCOUNT\n                  + \".blob.core.windows.net/movies/MOV1.avi?comp=blocklist&timeout=120\").build() },\n            { HttpRequest.builder().method(HttpMethod.GET).endpoint(\"http://\" + ACCOUNT + \".blob.core.windows.net/movies/MOV1.avi\").build() } };\n   }\n   \n   @DataProvider(name = \"auth-sas-data\", parallel = true)\n   public Object[][] requests(){\n      return new Object[][]{\n            { HttpRequest.builder().method(HttpMethod.PUT).endpoint(\"https://\" + ACCOUNT \n                  + \".blob.core.windows.net/movies/MOV1.avi?comp=block&blockid=BlockId1&timeout=60\").build(), filterSAS, \"https://foo.blob.core.windows.net/movies/MOV1.avi?comp=block&blockid=BlockId1&timeout=60&sv=2018-03-28&ss=b&srt=sco&sp=rwdlac&se=2019-02-13T17%3A18%3A22Z&st=2019-02-13T09%3A18%3A22Z&spr=https&sig=sMnaKSD94CzEPeGnWauTT0wBNIn%2B4ySkZO5PEAW7zs%3D\"},\n            { HttpRequest.builder().method(HttpMethod.PUT).endpoint(\"https://\" + ACCOUNT\n                  + \".blob.core.windows.net/movies/MOV1.avi?comp=blocklist&timeout=120\").build(), filterSAS, \"https://foo.blob.core.windows.net/movies/MOV1.avi?comp=blocklist&timeout=120&sv=2018-03-28&ss=b&srt=sco&sp=rwdlac&se=2019-02-13T17%3A18%3A22Z&st=2019-02-13T09%3A18%3A22Z&spr=https&sig=sMnaKSD94CzEPeGnWauTT0wBNIn%2B4ySkZO5PEAW7zs%3D\" },\n            { HttpRequest.builder().method(HttpMethod.PUT).endpoint(\"https://\" + ACCOUNT\n                  + \".blob.core.windows.net/movies/comedy/MOV1.avi?comp=block&blockid=BlockId1&timeout=60\").build(), filterSAS, \"https://foo.blob.core.windows.net/movies/comedy/MOV1.avi?comp=block&blockid=BlockId1&timeout=60&sv=2018-03-28&ss=b&srt=sco&sp=rwdlac&se=2019-02-13T17%3A18%3A22Z&st=2019-02-13T09%3A18%3A22Z&spr=https&sig=sMnaKSD94CzEPeGnWauTT0wBNIn%2B4ySkZO5PEAW7zs%3D\"},\n            { HttpRequest.builder().method(HttpMethod.GET).endpoint(\"https://\" + ACCOUNT\n                  + \".blob.core.windows.net/movies/MOV1.avi\").build(), filterSAS, \"https://foo.blob.core.windows.net/movies/MOV1.avi?sv=2018-03-28&ss=b&srt=sco&sp=rwdlac&se=2019-02-13T17%3A18%3A22Z&st=2019-02-13T09%3A18%3A22Z&spr=https&sig=sMnaKSD94CzEPeGnWauTT0wBNIn%2B4ySkZO5PEAW7zs%3D\" }, \n            { HttpRequest.builder().method(HttpMethod.GET).endpoint(\"https://\" + ACCOUNT\n                  + \".blob.core.windows.net/movies/MOV1.avi\").build(), filterSASQuestionMark, \"https://foo.blob.core.windows.net/movies/MOV1.avi?sv=2018-03-28&ss=b&srt=sco&sp=rwdlac&se=2019-02-13T17%3A18%3A22Z&st=2019-02-13T09%3A18%3A22Z&spr=https&sig=sMnaKSD94CzEPeGnWauTT0wBNIn%2B4ySkZO5PEAW7zs%3D\" },\n            { HttpRequest.builder().method(HttpMethod.GET).endpoint(\"http://my-custom-endpoint.net/movies/MOV1.avi\").build(), filterSASCustomEndpoint,\n               \"http://my-custom-endpoint.net/movies/MOV1.avi?sv=2018-03-28&ss=b&srt=sco&sp=rwdlac&se=2019-02-13T17%3A18%3A22Z&st=2019-02-13T09%3A18%3A22Z&spr=https&sig=sMnaKSD94CzEPeGnWauTT0wBNIn%2B4ySkZO5PEAW7zs%3D\" } };\n\n}\n\n   /**\n    * NOTE this test is dependent on how frequently the timestamp updates. At\n    * the time of writing, this was once per second. If this timestamp update\n    * interval is increased, it could make this test appear to hang for a long\n    * time.\n    */\n   @Test(threadPoolSize = 3, dataProvider = \"dataProvider\", timeOut = 3000)\n   void testIdempotent(HttpRequest request) {\n      request = filter.filter(request);\n      String signature = request.getFirstHeaderOrNull(HttpHeaders.AUTHORIZATION);\n      String date = request.getFirstHeaderOrNull(HttpHeaders.DATE);\n      int iterations = 1;\n      while (request.getFirstHeaderOrNull(HttpHeaders.DATE).equals(date)) {\n         date = request.getFirstHeaderOrNull(HttpHeaders.DATE);\n         iterations++;\n         assertEquals(signature, request.getFirstHeaderOrNull(HttpHeaders.AUTHORIZATION));\n         request = filter.filter(request);\n      }\n      System.out.printf(\"%s: %d iterations before the timestamp updated %n\", Thread.currentThread().getName(),\n            iterations);\n   }\n   \n   /**\n    * this test is similar to testIdempotent; it checks whether request is properly filtered when it comes to SAS Authentication\n    */\n   @Test(dataProvider = \"auth-sas-data\") \n   void testFilter(HttpRequest request, SharedKeyLiteAuthentication filter, String expected) {\n      request = filter.filter(request);\n      assertEquals(request.getEndpoint().toString(), expected);\n   }\n\n   @Test\n   void testAclQueryStringRoot() {\n      URI host = URI.create(\"http://\" + ACCOUNT + \".blob.core.windows.net/?comp=list\");\n      HttpRequest request = HttpRequest.builder().method(HttpMethod.GET).endpoint(host).build();\n      StringBuilder builder = new StringBuilder();\n      filter.appendUriPath(request, builder);\n      assertEquals(builder.toString(), \"/?comp=list\");\n   }\n\n   @Test\n   void testAclQueryStringResTypeNotSignificant() {\n      URI host = URI.create(\"http://\" + ACCOUNT + \".blob.core.windows.net/mycontainer?restype=container\");\n      HttpRequest request = HttpRequest.builder().method(HttpMethod.GET).endpoint(host).build();\n      StringBuilder builder = new StringBuilder();\n      filter.appendUriPath(request, builder);\n      assertEquals(builder.toString(), \"/mycontainer\");\n   }\n\n   @Test\n   void testAclQueryStringComp() {\n      URI host = URI.create(\"http://\" + ACCOUNT + \".blob.core.windows.net/mycontainer?comp=list\");\n      HttpRequest request = HttpRequest.builder().method(HttpMethod.GET).endpoint(host).build();\n      StringBuilder builder = new StringBuilder();\n      filter.appendUriPath(request, builder);\n      assertEquals(builder.toString(), \"/mycontainer?comp=list\");\n   }\n\n   @Test\n   void testAclQueryStringRelativeWithExtraJunk() {\n      URI host = URI.create(\"http://\" + ACCOUNT\n            + \".blob.core.windows.net/mycontainer?comp=list&marker=marker&maxresults=1&prefix=prefix\");\n      HttpRequest request = HttpRequest.builder().method(HttpMethod.GET).endpoint(host).build();\n      StringBuilder builder = new StringBuilder();\n      filter.appendUriPath(request, builder);\n      assertEquals(builder.toString(), \"/mycontainer?comp=list\");\n   }\n\n   /**\n    * before class, as we need to ensure that the filter is threadsafe.\n    * \n    * @throws IOException\n    * \n    */\n   @BeforeClass\n   protected void createFilter() throws IOException {\n      injector = ContextBuilder\n            .newBuilder(\"azureblob\")\n            .endpoint(\"https://${jclouds.identity}.blob.core.windows.net\")\n            .credentials(ACCOUNT, \"credential\")\n            .modules(ImmutableSet.<Module> of(new MockModule(), new NullLoggingModule()))\n            .buildInjector();\n      filter = injector.getInstance(SharedKeyLiteAuthentication.class);\n      injector = ContextBuilder\n            .newBuilder(\"azureblob\")\n            .endpoint(\"https://${jclouds.identity}.blob.core.windows.net\")\n            .credentials(ACCOUNT, \"sv=2018-03-28&ss=b&srt=sco&sp=rwdlac&se=2019-02-13T17:18:22Z&st=2019-02-13T09:18:22Z&spr=https&sig=sMnaKSD94CzEPeGnWauTT0wBNIn%2B4ySkZO5PEAW7zs%3D\")\n            .modules(ImmutableSet.<Module> of(new MockModule(), new NullLoggingModule()))\n            .buildInjector(); \n      filterSAS = injector.getInstance(SharedKeyLiteAuthentication.class);\n      injector = ContextBuilder\n            .newBuilder(\"azureblob\")\n            .endpoint(\"https://${jclouds.identity}.blob.core.windows.net\")\n            .credentials(ACCOUNT, \"?sv=2018-03-28&ss=b&srt=sco&sp=rwdlac&se=2019-02-13T17:18:22Z&st=2019-02-13T09:18:22Z&spr=https&sig=sMnaKSD94CzEPeGnWauTT0wBNIn%2B4ySkZO5PEAW7zs%3D\")\n            .modules(ImmutableSet.<Module> of(new MockModule(), new NullLoggingModule()))\n            .buildInjector(); \n      filterSASQuestionMark = injector.getInstance(SharedKeyLiteAuthentication.class);\n      injector = ContextBuilder\n            .newBuilder(\"azureblob\")\n            .endpoint(\"http://my-custom-endpoint.net\")\n            .credentials(ACCOUNT, \"?sv=2018-03-28&ss=b&srt=sco&sp=rwdlac&se=2019-02-13T17:18:22Z&st=2019-02-13T09:18:22Z&spr=https&sig=sMnaKSD94CzEPeGnWauTT0wBNIn%2B4ySkZO5PEAW7zs%3D\")\n            .modules(ImmutableSet.<Module> of(new MockModule(), new NullLoggingModule()))\n            .buildInjector();\n      filterSASCustomEndpoint = injector.getInstance(SharedKeyLiteAuthentication.class);\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/test/java/org/jclouds/azure/storage/handlers/ParseAzureBlobErrorFromXmlContentTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azure.storage.handlers;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.reportMatcher;\nimport static org.easymock.EasyMock.verify;\n\nimport java.net.URI;\n\nimport org.easymock.IArgumentMatcher;\nimport org.jclouds.azure.storage.filters.SharedKeyLiteAuthentication;\nimport org.jclouds.azureblob.handlers.ParseAzureBlobErrorFromXmlContent;\nimport org.jclouds.blobstore.ContainerNotFoundException;\nimport org.jclouds.blobstore.KeyNotFoundException;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.config.SaxParserModule;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\n\n@Test(groups = { \"unit\" })\npublic class ParseAzureBlobErrorFromXmlContentTest {\n\n   @Test\n   public void test404OnContainerIsContainerNotFound() {\n      assertCodeMakes(\"GET\", URI\n               .create(\"https://jclouds.blob.core.windows.net/adriancole-azureblob-413790770?restype=container\"), 404,\n               \"Not Found\", \"text/html; charset=us-ascii\", \"<HTML><HEAD><TITLE>Not Found</TITLE>\\r\\n\",\n               ContainerNotFoundException.class);\n   }\n\n   @Test\n   public void test404WithoutContainerIsKeyNotFound() {\n      assertCodeMakes(\"GET\", URI.create(\"https://jclouds.blob.core.windows.net/adriancole-blobstore0/apples\"), 404,\n               \"Not Found\", \"text/html; charset=us-ascii\", \"<HTML><HEAD><TITLE>Not Found</TITLE>\\r\\n\",\n               KeyNotFoundException.class);\n   }\n\n   private void assertCodeMakes(String method, URI uri, int statusCode, String message, String contentType,\n            String content, Class<? extends Exception> expected) {\n\n      ParseAzureBlobErrorFromXmlContent function = Guice.createInjector(new SaxParserModule(), new AbstractModule() {\n\n         @Override\n         protected void configure() {\n            bind(SharedKeyLiteAuthentication.class).toInstance(createMock(SharedKeyLiteAuthentication.class));\n         }\n\n      }).getInstance(ParseAzureBlobErrorFromXmlContent.class);\n\n      HttpCommand command = createMock(HttpCommand.class);\n      HttpRequest request = HttpRequest.builder().method(method).endpoint(uri).build();\n      HttpResponse response = HttpResponse.builder().statusCode(statusCode).message(message).payload(content).build();\n      response.getPayload().getContentMetadata().setContentType(contentType);\n\n      expect(command.getCurrentRequest()).andReturn(request).atLeastOnce();\n      command.setException(classEq(expected));\n\n      replay(command);\n\n      function.handleError(command, response);\n\n      verify(command);\n   }\n\n   public static Exception classEq(final Class<? extends Exception> in) {\n      reportMatcher(new IArgumentMatcher() {\n\n         @Override\n         public void appendTo(StringBuffer buffer) {\n            buffer.append(\"classEq(\");\n            buffer.append(in);\n            buffer.append(\")\");\n         }\n\n         @Override\n         public boolean matches(Object arg) {\n            return arg.getClass() == in;\n         }\n\n      });\n      return null;\n   }\n\n}\n"
  },
  {
    "path": "providers/azureblob/src/test/java/org/jclouds/azure/storage/handlers/ParseAzureErrorFromXmlContentTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azure.storage.handlers;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.reportMatcher;\nimport static org.easymock.EasyMock.verify;\n\nimport java.net.URI;\n\nimport org.easymock.IArgumentMatcher;\nimport org.jclouds.azure.storage.AzureStorageResponseException;\nimport org.jclouds.azure.storage.filters.SharedKeyLiteAuthentication;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.config.SaxParserModule;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\n\n@Test(groups = { \"unit\" })\npublic class ParseAzureErrorFromXmlContentTest {\n\n   @Test\n   public void test411WithTextHtmlIllegalArgumentException() {\n      assertCodeMakes(\"PUT\",\n            URI.create(\"https://jclouds.blob.core.windows.net/adriancole-azureblob-413790770?restype=container\"), 411,\n            \"Length Required\", \"text/html; charset=us-ascii\", \"<HTML><HEAD><TITLE>Length Required</TITLE>\\r\\n\",\n            IllegalArgumentException.class);\n   }\n\n   @Test\n   public void test304WithNoContentIllegalArgumentException() {\n      assertCodeMakes(\"GET\", URI.create(\"https://jclouds.blob.core.windows.net/adriancole-blobstore0/apples\"), 411,\n            \"HTTP/1.1 304 The condition specified using HTTP conditional header(s) is not met.\", \"application/unknown\",\n            \"\", IllegalArgumentException.class);\n   }\n\n   \n   @Test\n   public void test412WithTextHtmlHttpResponseException() {\n      assertCodeMakes(\n            \"GET\",\n            URI.create(\"https://jclouds.blob.core.windows.net/adriancole-blobstore2?restype=container&comp=list&prefix=apps/apps/apps/&include=metadata\"),\n            412,\n            \"HTTP/1.1 412 The condition specified using HTTP conditional header(s) is not met.\",\n            \"application/xml\",\n            \"<?xml version=\\\"1.0\\\" encoding=\\\"utf-8\\\"?><Error><Code>ConditionNotMet</Code><Message>The condition specified using HTTP conditional header(s) is not met.\\nRequestId:921efcad-84bc-4e0a-863d-24810d1096e1\\nTime:2010-11-04T15:03:07.8694513Z</Message></Error>\",\n            AzureStorageResponseException.class);\n   }\n\n   private void assertCodeMakes(String method, URI uri, int statusCode, String message, String contentType,\n         String content, Class<? extends Exception> expected) {\n\n      ParseAzureStorageErrorFromXmlContent function = Guice.createInjector(new SaxParserModule(), new AbstractModule() {\n\n         @Override\n         protected void configure() {\n            bind(SharedKeyLiteAuthentication.class).toInstance(createMock(SharedKeyLiteAuthentication.class));\n         }\n\n      }).getInstance(ParseAzureStorageErrorFromXmlContent.class);\n\n      HttpCommand command = createMock(HttpCommand.class);\n      HttpRequest request = HttpRequest.builder().method(method).endpoint(uri).build();\n      HttpResponse response = HttpResponse.builder().statusCode(statusCode).message(message).payload(content).build();\n      response.getPayload().getContentMetadata().setContentType(contentType);\n\n      expect(command.getCurrentRequest()).andReturn(request).atLeastOnce();\n      command.setException(classEq(expected));\n\n      replay(command);\n\n      function.handleError(command, response);\n\n      verify(command);\n   }\n\n   public static Exception classEq(final Class<? extends Exception> in) {\n      reportMatcher(new IArgumentMatcher() {\n\n         @Override\n         public void appendTo(StringBuffer buffer) {\n            buffer.append(\"classEq(\");\n            buffer.append(in);\n            buffer.append(\")\");\n         }\n\n         @Override\n         public boolean matches(Object arg) {\n            return arg.getClass() == in;\n         }\n\n      });\n      return null;\n   }\n\n}\n"
  },
  {
    "path": "providers/azureblob/src/test/java/org/jclouds/azure/storage/options/CreateOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azure.storage.options;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.azure.storage.reference.AzureStorageHeaders;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMultimap;\n\n/**\n * Tests behavior of {@code CreateOptions}\n */\n@Test(groups = \"unit\")\npublic class CreateOptionsTest {\n\n   public void testMetadata() {\n      CreateOptions options = new CreateOptions().withMetadata(ImmutableMultimap.of(\n               \"test\", \"foo\"));\n      assertEquals(ImmutableList.of(\"foo\"), options.buildRequestHeaders().get(\n               AzureStorageHeaders.USER_METADATA_PREFIX + \"test\"));\n   }\n\n   public void testMetadataAlreadyPrefixed() {\n      CreateOptions options = new CreateOptions().withMetadata(ImmutableMultimap.of(\n               AzureStorageHeaders.USER_METADATA_PREFIX + \"test\", \"foo\"));\n      assertEquals(ImmutableList.of(\"foo\"), options.buildRequestHeaders().get(\n               AzureStorageHeaders.USER_METADATA_PREFIX + \"test\"));\n   }\n\n   public void testMetadataStatic() {\n      CreateOptions options = CreateOptions.Builder.withMetadata(ImmutableMultimap.of(\n               \"test\", \"foo\"));\n      assertEquals(ImmutableList.of(\"foo\"), options.buildRequestHeaders().get(\n               AzureStorageHeaders.USER_METADATA_PREFIX + \"test\"));\n   }\n\n}\n"
  },
  {
    "path": "providers/azureblob/src/test/java/org/jclouds/azure/storage/options/ListOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azure.storage.options;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tests behavior of {@code ListOptions}\n */\n@Test(groups = \"unit\")\npublic class ListOptionsTest {\n   public void testIncludeMetadata() {\n      ListOptions options = new ListOptions().includeMetadata();\n      assertEquals(ImmutableList.of(\"metadata\"), options.buildQueryParameters().get(\"include\"));\n   }\n\n   public void testIncludeMetadataStatic() {\n      ListOptions options = ListOptions.Builder.includeMetadata();\n      assertEquals(ImmutableList.of(\"metadata\"), options.buildQueryParameters().get(\"include\"));\n   }\n\n   public void testPrefix() {\n      ListOptions options = new ListOptions().prefix(\"a\");\n      assertEquals(ImmutableList.of(\"a\"), options.buildQueryParameters().get(\"prefix\"));\n   }\n\n   public void testMarker() {\n      ListOptions options = new ListOptions().marker(\"a\");\n      assertEquals(ImmutableList.of(\"a\"), options.buildQueryParameters().get(\"marker\"));\n   }\n\n   public void testMaxResults() {\n      int limit = 1;\n      ListOptions options = new ListOptions().maxResults(limit);\n      assertEquals(ImmutableList.of(\"1\"), options.buildQueryParameters().get(\"maxresults\"));\n   }\n\n   public void testPrefixStatic() {\n      ListOptions options = ListOptions.Builder.prefix(\"a\");\n      assertEquals(ImmutableList.of(\"a\"), options.buildQueryParameters().get(\"prefix\"));\n   }\n\n   public void testMarkerStatic() {\n      ListOptions options = ListOptions.Builder.marker(\"a\");\n      assertEquals(ImmutableList.of(\"a\"), options.buildQueryParameters().get(\"marker\"));\n   }\n\n   public void testMaxResultsStatic() {\n      int limit = 1;\n      ListOptions options = ListOptions.Builder.maxResults(limit);\n      assertEquals(ImmutableList.of(\"1\"), options.buildQueryParameters().get(\"maxresults\"));\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/test/java/org/jclouds/azure/storage/util/storageurl/AppendAccountToEndpointTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azure.storage.util.storageurl;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.azureblob.config.AppendAccountToEndpointModule;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.logging.config.NullLoggingModule;\nimport org.jclouds.rest.internal.BaseRestApiTest;\nimport org.testng.annotations.Test;\n\nimport java.net.URI;\n\nimport static org.testng.Assert.assertEquals;\n\n@Test(groups = \"unit\")\npublic class AppendAccountToEndpointTest {\n   \n   private static final String ACCOUNT = \"foo\";\n   \n   @Test(expectedExceptions = NullPointerException.class)\n   void testThrowsErrorWhenNoEndpointSupplied() {\n      \n      AppendAccountToEndpoint target = new AppendAccountToEndpoint(\n            () -> null, \n            () -> new Credentials(ACCOUNT, \"creds\")\n      );\n      target.get();\n   }\n   \n   @Test\n   void testCustomEndpointWithoutTrailingSlash() {\n\n      AppendAccountToEndpoint target = new AppendAccountToEndpoint(\n            () -> URI.create(\"http://localhost:10000\"),\n            () -> new Credentials(ACCOUNT, \"creds\")\n      );\n      \n      assertEquals(target.get().toString(), \"http://localhost:10000/foo/\");\n   }\n\n   @Test\n   void testCustomEndpointWithTrailingSlash() {\n\n      AppendAccountToEndpoint target = new AppendAccountToEndpoint(\n            () -> URI.create(\"http://localhost:10000/\"),\n            () -> new Credentials(ACCOUNT, \"creds\")\n      );\n\n      assertEquals(target.get().toString(), \"http://localhost:10000/foo/\");\n\n   }\n   \n   @Test\n   void testInsideContext() {\n      String adjustedUri = ContextBuilder\n            .newBuilder(\"azureblob\")\n            .endpoint(\"http://localhost:10000\")\n            .credentials(ACCOUNT, \"?creds\")\n            .modules(ImmutableSet.<Module> of(new BaseRestApiTest.MockModule(), new NullLoggingModule(), new AppendAccountToEndpointModule()))\n            .buildInjector()\n            .getInstance(AppendAccountToEndpoint.class)\n            .get()\n            .toString();\n\n      assertEquals(adjustedUri, \"http://localhost:10000/foo/\");\n\n   }\n   \n\n}\n"
  },
  {
    "path": "providers/azureblob/src/test/java/org/jclouds/azure/storage/util/storageurl/StorageAccountInVhostTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azure.storage.util.storageurl;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\nimport com.google.inject.util.Modules;\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.azure.storage.config.AuthType;\nimport org.jclouds.azureblob.config.AppendAccountToEndpointModule;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.logging.config.NullLoggingModule;\nimport org.jclouds.rest.internal.BaseRestApiTest;\nimport org.testng.annotations.Test;\n\nimport java.net.URI;\n\nimport static org.testng.Assert.assertEquals;\n\n@Test(groups = \"unit\")\npublic class StorageAccountInVhostTest {\n\n   private static final String ACCOUNT = \"foo\";\n\n   @Test\n   void testDefaultEndpointWhenNoneSupplied() {\n\n      StorageAccountInVhost target = new StorageAccountInVhost(\n            () -> null,\n            () -> new Credentials(ACCOUNT, \"creds\"),\n            AuthType.AZURE_KEY,\n            null\n      );\n      \n      assertEquals(target.get().toString(), \"https://foo.blob.core.windows.net/\");\n   }\n\n   @Test\n   void testCustomEndpointWithoutTrailingSlash() {\n\n      StorageAccountInVhost target = new StorageAccountInVhost(\n            () -> URI.create(\"https://foo2.blob.core.windows.net/\"),\n            () -> new Credentials(ACCOUNT, \"creds\"),\n            AuthType.AZURE_KEY,\n            \"\"\n      );\n\n      assertEquals(target.get().toString(), \"https://foo2.blob.core.windows.net/\");\n   }\n\n   @Test\n   void testCustomEndpointWithTrailingSlash() {\n\n      StorageAccountInVhost target = new StorageAccountInVhost(\n            () -> URI.create(\"https://foo2.blob.core.windows.net/\"),\n            () -> new Credentials(ACCOUNT, \"creds\"),\n            AuthType.AZURE_KEY,\n            \"\"\n      );\n\n      assertEquals(target.get().toString(), \"https://foo2.blob.core.windows.net/\");\n\n   }\n\n   @Test\n   void testInsideContext() {\n      String adjustedUri = ContextBuilder\n            .newBuilder(\"azureblob\")\n            .endpoint(\"https://foo2.blob.core.windows.net\")\n            .credentials(ACCOUNT, \"?creds\")\n            .modules(ImmutableSet.<Module> of(new BaseRestApiTest.MockModule(), new NullLoggingModule()))\n            .buildInjector()\n            .getInstance(StorageAccountInVhost.class)\n            .get()\n            .toString();\n      Modules.override(new AppendAccountToEndpointModule());\n      assertEquals(adjustedUri, \"https://foo2.blob.core.windows.net/\");\n\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/test/java/org/jclouds/azure/storage/xml/ErrorHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azure.storage.xml;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.azure.storage.domain.AzureStorageError;\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.http.functions.ParseSax;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code ErrorHandler}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"ErrorHandlerTest\")\npublic class ErrorHandlerTest extends BaseHandlerTest {\n\n   ParseSax<AzureStorageError> createParser() {\n      ParseSax<AzureStorageError> parser = factory.create(injector\n               .getInstance(ErrorHandler.class));\n      return parser;\n   }\n\n   public void testApplyInputStream() {\n      InputStream is = getClass().getResourceAsStream(\"/test_error.xml\");\n      ParseSax<AzureStorageError> parser = createParser();\n      AzureStorageError result = parser.parse(is);\n      assertEquals(result.getCode(), \"AuthenticationFailed\");\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/test/java/org/jclouds/azureblob/AzureBlobClientAdTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.reflect.Invokable;\nimport org.jclouds.azure.storage.filters.SharedKeyLiteAuthentication;\nimport org.jclouds.azure.storage.options.ListOptions;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.internal.BaseRestAnnotationProcessingTest;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport java.io.IOException;\nimport java.util.Properties;\n\nimport static org.jclouds.azure.storage.config.AzureStorageProperties.ACCOUNT;\nimport static org.jclouds.azure.storage.config.AzureStorageProperties.AUTH_TYPE;\nimport static org.jclouds.azure.storage.config.AzureStorageProperties.TENANT_ID;\nimport static org.jclouds.reflect.Reflection2.method;\nimport static org.testng.Assert.assertEquals;\n\n@Test(groups = \"unit\", testName = \"AzureBlobClientAdTest\")\npublic class AzureBlobClientAdTest extends BaseRestAnnotationProcessingTest<AzureBlobClient> {\n    @Override\n    protected void checkFilters(HttpRequest request) {\n        assertEquals(request.getFilters().size(), 1);\n        assertEquals(request.getFilters().get(0).getClass(), SharedKeyLiteAuthentication.class);\n    }\n\n    @Override\n    public AzureBlobProviderMetadata createProviderMetadata() {\n        return new AzureBlobProviderMetadata();\n    }\n\n    @Override\n    protected Properties setupProperties() {\n        Properties adProperties = new Properties();\n        adProperties.setProperty(TENANT_ID, \"tenant\");\n        adProperties.setProperty(ACCOUNT, \"ad-account\");\n        adProperties.setProperty(AUTH_TYPE, \"azureAd\");\n        return adProperties;\n    }\n\n    public void testListContainersAD() throws SecurityException, NoSuchMethodException, IOException {\n        Invokable<?, ?> method = method(AzureBlobClient.class, \"listContainers\", ListOptions[].class);\n        GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.of());\n\n        assertRequestLineEquals(request, \"GET https://ad-account.blob.core.windows.net/?comp=list HTTP/1.1\");\n        assertNonPayloadHeadersEqual(request, \"x-ms-version: 2017-11-09\\n\");\n        assertPayloadEquals(request, null, null, false);\n    }\n}\n"
  },
  {
    "path": "providers/azureblob/src/test/java/org/jclouds/azureblob/AzureBlobClientLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob;\n\nimport static com.google.common.io.BaseEncoding.base16;\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.assertj.core.api.Fail.failBecauseExceptionWasNotThrown;\nimport static org.jclouds.azure.storage.config.AzureStorageProperties.AUTH_TYPE;\nimport static org.jclouds.azure.storage.options.ListOptions.Builder.includeMetadata;\nimport static org.jclouds.azureblob.options.CreateContainerOptions.Builder.withMetadata;\nimport static org.jclouds.azureblob.options.CreateContainerOptions.Builder.withPublicAccess;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.ByteArrayInputStream;\nimport java.lang.reflect.UndeclaredThrowableException;\nimport java.net.URI;\nimport java.security.SecureRandom;\nimport java.util.Arrays;\nimport java.util.Date;\nimport java.util.EnumSet;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.azure.storage.AzureStorageResponseException;\nimport org.jclouds.azure.storage.config.AuthType;\nimport org.jclouds.azure.storage.domain.BoundedSet;\nimport org.jclouds.azure.storage.options.ListOptions;\nimport org.jclouds.azureblob.domain.AccessTier;\nimport org.jclouds.azureblob.domain.AzureBlob;\nimport org.jclouds.azureblob.domain.BlobProperties;\nimport org.jclouds.azureblob.domain.ContainerProperties;\nimport org.jclouds.azureblob.domain.ListBlobBlocksResponse;\nimport org.jclouds.azureblob.domain.ListBlobsInclude;\nimport org.jclouds.azureblob.domain.ListBlobsResponse;\nimport org.jclouds.azureblob.domain.PublicAccess;\nimport org.jclouds.azureblob.options.CopyBlobOptions;\nimport org.jclouds.azureblob.options.ListBlobsOptions;\nimport org.jclouds.blobstore.ContainerNotFoundException;\nimport org.jclouds.blobstore.integration.internal.BaseBlobStoreIntegrationTest;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.http.options.GetOptions;\nimport org.jclouds.io.ByteStreams2;\nimport org.jclouds.io.ContentMetadata;\nimport org.jclouds.io.ContentMetadataBuilder;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.util.Strings2;\nimport org.jclouds.util.Throwables2;\nimport org.jclouds.utils.TestUtils;\nimport org.testng.SkipException;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.Iterables;\nimport com.google.common.hash.Hashing;\nimport com.google.common.io.BaseEncoding;\nimport com.google.common.io.ByteSource;\n\n@Test(groups = \"live\", singleThreaded = true)\npublic class AzureBlobClientLiveTest extends BaseBlobStoreIntegrationTest {\n   public AzureBlobClientLiveTest() { provider = \"azureblob\"; }\n\n   public AzureBlobClient getApi() {\n      return view.unwrapApi(AzureBlobClient.class);\n   }\n\n   @Test\n   public void testListContainers() throws Exception {\n      Set<ContainerProperties> response = getApi().listContainers();\n      assert null != response;\n      long initialContainerCount = response.size();\n      assertTrue(initialContainerCount >= 0);\n\n   }\n\n   String privateContainer;\n   String publicContainer;\n\n   @Test(timeOut = 5 * 60 * 1000)\n   public void testCreateContainer() throws Exception {\n      boolean created = false;\n      while (!created) {\n         // testListOwnedContainers requires a unique prefix\n         privateContainer = CONTAINER_PREFIX + \"unique-\" + containerIndex.incrementAndGet();\n         try {\n            created = getApi().createContainer(privateContainer, withMetadata(ImmutableMultimap.of(\"foo\", \"bar\")));\n         } catch (UndeclaredThrowableException e) {\n            HttpResponseException htpe = (HttpResponseException) e.getCause().getCause();\n            if (htpe.getResponse().getStatusCode() == 409)\n               continue;\n            throw e;\n         }\n      }\n      Set<ContainerProperties> response = getApi().listContainers(includeMetadata());\n      assert null != response;\n      long containerCount = response.size();\n      assertTrue(containerCount >= 1);\n      ListBlobsResponse list = getApi().listBlobs(privateContainer);\n      assertThat(list.getUrl().toString()).endsWith(\n              String.format(\".blob.core.windows.net/%s\", privateContainer));\n      // TODO .. check to see the container actually exists\n   }\n\n   @Test(timeOut = 5 * 60 * 1000)\n   public void testCreatePublicContainer() throws Exception {\n      boolean created = false;\n      while (!created) {\n         publicContainer = CONTAINER_PREFIX + containerIndex.incrementAndGet();\n         try {\n            created = getApi().createContainer(publicContainer, withPublicAccess(PublicAccess.BLOB));\n         } catch (UndeclaredThrowableException e) {\n            HttpResponseException htpe = (HttpResponseException) e.getCause().getCause();\n            if (htpe.getResponse().getStatusCode() == 409)\n               continue;\n            throw e;\n         }\n      }\n\n      ContainerProperties properties = null;\n      for (ContainerProperties p : getApi().listContainers(includeMetadata())) {\n         if (p.getName().equals(publicContainer)) {\n            properties = p;\n            break;\n         }\n      }\n      assertThat(properties.getPublicAccess()).isEqualTo(PublicAccess.BLOB);\n\n      properties = getApi().getContainerProperties(publicContainer);\n      assertThat(properties.getPublicAccess()).isEqualTo(PublicAccess.BLOB);\n   }\n\n   @Test(timeOut = 10 * 60 * 1000)\n   public void testCreatePublicRootContainer() throws Exception {\n      try {\n         getApi().deleteRootContainer();\n      } catch (ContainerNotFoundException e) {\n         Thread.sleep(5000);\n      } catch (AzureStorageResponseException htpe) {\n         if (htpe.getResponse().getStatusCode() == 409) {// TODO look for\n                                                         // specific message\n            Thread.sleep(5000);\n         } else {\n            throw htpe;\n         }\n      }\n\n      boolean created = false;\n      while (!created) {\n         try {\n            created = getApi().createRootContainer();\n         } catch (AzureStorageResponseException htpe) {\n            if (htpe.getResponse().getStatusCode() == 409) {// TODO look for\n                                                            // specific message\n               Thread.sleep(5000);\n               continue;\n            } else {\n               throw htpe;\n            }\n         }\n      }\n      ListBlobsResponse list = getApi().listBlobs();\n      assertThat(list.getUrl().toString()).endsWith(\".blob.core.windows.net/$root\");\n   }\n\n   @Test\n   public void testListContainersWithOptions() throws Exception {\n\n      BoundedSet<ContainerProperties> response = getApi().listContainers(\n            ListOptions.Builder.prefix(privateContainer).maxResults(1).includeMetadata());\n      assert null != response;\n      long initialContainerCount = response.size();\n      assertTrue(initialContainerCount >= 0);\n      assertEquals(privateContainer, response.getPrefix());\n      assertEquals(1, response.getMaxResults());\n   }\n\n   @Test(timeOut = 5 * 60 * 1000, dependsOnMethods = { \"testCreatePublicRootContainer\" })\n   public void testDeleteRootContainer() throws Exception {\n      getApi().deleteRootContainer();\n      // TODO loop for up to 30 seconds checking if they are really gone\n   }\n\n   @Test(timeOut = 5 * 60 * 1000, dependsOnMethods = { \"testCreateContainer\", \"testCreatePublicContainer\" })\n   public void testListOwnedContainers() throws Exception {\n\n      // Test default listing\n      Set<ContainerProperties> response = getApi().listContainers();\n      // assertEquals(response.size(), initialContainerCount + 2);// if the\n      // containers already\n      // exist, this will fail\n\n      // Test listing with options\n      response = getApi().listContainers(\n            ListOptions.Builder.prefix(privateContainer.substring(0, privateContainer.length() - 1)).maxResults(1)\n                  .includeMetadata());\n      assertEquals(response.size(), 1);\n      assertEquals(Iterables.getOnlyElement(response).getName(), privateContainer);\n      assertEquals(Iterables.getOnlyElement(response).getMetadata(), ImmutableMap.of(\"foo\", \"bar\"));\n\n      response = getApi().listContainers(ListOptions.Builder.prefix(publicContainer).maxResults(1));\n      assertEquals(response.size(), 1);\n      assertEquals(Iterables.getOnlyElement(response).getName(), publicContainer);\n\n   }\n\n   @Test\n   public void testDeleteOneContainer() throws Exception {\n      getApi().deleteContainer(\"does-not-exist\");\n   }\n\n   @Test(timeOut = 5 * 60 * 1000, dependsOnMethods = { \"testListOwnedContainers\", \"testObjectOperations\" })\n   public void testDeleteContainer() throws Exception {\n      getApi().deleteContainer(privateContainer);\n      getApi().deleteContainer(publicContainer);\n      // TODO loop for up to 30 seconds checking if they are really gone\n   }\n\n   @Test(timeOut = 5 * 60 * 1000, dependsOnMethods = { \"testCreateContainer\", \"testCreatePublicContainer\" })\n   public void testObjectOperations() throws Exception {\n      String data = \"Here is my data\";\n\n      // Test PUT with string data, ETag hash, and a piece of metadata\n      AzureBlob object = getApi().newBlob();\n      object.getProperties().setName(\"object\");\n      object.setPayload(data);\n      object.getProperties().getContentMetadata().setContentMD5(Hashing.md5().hashString(data, Charsets.UTF_8).asBytes());\n      object.getProperties().getContentMetadata().setContentType(\"text/plain\");\n      object.getProperties().getMetadata().put(\"mykey\", \"metadata-value\");\n      byte[] md5 = object.getProperties().getContentMetadata().getContentMD5();\n      String newEtag = getApi().putBlob(privateContainer, object);\n      assertEquals(base16().lowerCase().encode(md5),\n            base16().lowerCase().encode(object.getProperties().getContentMetadata().getContentMD5()));\n      // Test HEAD of missing object\n      assert getApi().getBlobProperties(privateContainer, \"non-existent-object\") == null;\n\n      // Test HEAD of object\n      BlobProperties metadata = getApi().getBlobProperties(privateContainer, object.getProperties().getName());\n      assertEquals(metadata.getName(), object.getProperties().getName());\n      assertEquals(metadata.getContentMetadata().getContentLength(), Long.valueOf(data.length()));\n      assertEquals(metadata.getContentMetadata().getContentType(), \"text/plain\");\n      assertEquals(base16().lowerCase().encode(metadata.getContentMetadata().getContentMD5()),\n            base16().lowerCase().encode(object.getProperties().getContentMetadata().getContentMD5()));\n      assertEquals(metadata.getETag(), newEtag);\n      assertEquals(metadata.getMetadata().entrySet().size(), 1);\n      assertEquals(metadata.getMetadata().get(\"mykey\"), \"metadata-value\");\n\n      // Test POST to update object's metadata\n      Map<String, String> userMetadata = ImmutableMap.<String, String>builder()\n            .put(\"new_metadata_1\", \"value-1\")\n            .put(\"new_metadata_2\", \"value-2\")\n            .build();\n      String eTag = getApi().setBlobMetadata(privateContainer, object.getProperties().getName(), userMetadata);\n      assertThat(eTag).isNotNull();\n\n      // Azure ETag are timestamps not content hash\n      String eTag2 = getApi().setBlobMetadata(privateContainer, object.getProperties().getName(), userMetadata);\n      assertThat(eTag2).isNotNull().isNotEqualTo(eTag);\n\n      // Test GET of missing object\n      assert getApi().getBlob(privateContainer, \"non-existent-object\") == null;\n\n      // Test GET of object (including updated metadata)\n      AzureBlob getBlob = getApi().getBlob(privateContainer, object.getProperties().getName());\n      assertEquals(Strings2.toStringAndClose(getBlob.getPayload().openStream()), data);\n      assertEquals(getBlob.getProperties().getName(), object.getProperties().getName());\n      assertEquals(getBlob.getPayload().getContentMetadata().getContentLength(), Long.valueOf(data.length()));\n      assertEquals(getBlob.getProperties().getContentMetadata().getContentType(), \"text/plain\");\n      assertEquals(base16().lowerCase().encode(md5),\n            base16().lowerCase().encode(getBlob.getProperties().getContentMetadata().getContentMD5()));\n      assertEquals(getBlob.getProperties().getMetadata().size(), 2);\n      assertEquals(getBlob.getProperties().getMetadata().get(\"new_metadata_1\"), \"value-1\");\n      assertEquals(getBlob.getProperties().getMetadata().get(\"new_metadata_2\"), \"value-2\");\n      assertEquals(metadata.getMetadata().entrySet().size(), 1);\n      assertEquals(metadata.getMetadata().get(\"mykey\"), \"metadata-value\");\n\n      // test listing\n      ListBlobsResponse response = getApi().listBlobs(\n            privateContainer,\n            ListBlobsOptions.Builder\n                  .prefix(object.getProperties().getName().substring(0, object.getProperties().getName().length() - 1))\n                  .maxResults(1).includeMetadata());\n      assertEquals(response.size(), 1);\n      assertEquals(Iterables.getOnlyElement(response).getName(), object.getProperties().getName());\n      assertEquals(Iterables.getOnlyElement(response).getMetadata().size(), 2);\n      assertEquals(Iterables.getOnlyElement(response).getMetadata().get(\"new_metadata_1\"), \"value-1\");\n      assertEquals(Iterables.getOnlyElement(response).getMetadata().get(\"new_metadata_2\"), \"value-2\");\n\n      // Test PUT with invalid ETag (as if object's data was corrupted in\n      // transit)\n      String correctEtag = newEtag;\n      String incorrectEtag = \"0\" + correctEtag.substring(1);\n      object.getProperties().setETag(incorrectEtag);\n      try {\n         getApi().putBlob(privateContainer, object);\n      } catch (Throwable e) {\n         assertEquals(e.getCause().getClass(), HttpResponseException.class);\n         assertEquals(((HttpResponseException) e.getCause()).getResponse().getStatusCode(), 422);\n      }\n\n      ByteArrayInputStream bais = new ByteArrayInputStream(data.getBytes(Charsets.UTF_8));\n      object = getApi().newBlob();\n      object.getProperties().setName(\"chunked-object\");\n      object.setPayload(bais);\n      object.getPayload().getContentMetadata().setContentLength(Long.valueOf(data.getBytes().length));\n      newEtag = getApi().putBlob(privateContainer, object);\n      assertEquals(base16().lowerCase().encode(md5),\n            base16().lowerCase().encode(getBlob.getProperties().getContentMetadata().getContentMD5()));\n\n      // Test GET with options\n      // Non-matching ETag\n      try {\n         getApi().getBlob(privateContainer, object.getProperties().getName(),\n               GetOptions.Builder.ifETagDoesntMatch(newEtag));\n      } catch (Exception e) {\n         HttpResponseException httpEx = Throwables2.getFirstThrowableOfType(e, HttpResponseException.class);\n         assert httpEx != null : \"expected http exception, not \" + e;\n         assertEquals(httpEx.getResponse().getStatusCode(), 304);\n      }\n\n      // Matching ETag TODO this shouldn't fail!!!\n      try {\n         getBlob = getApi().getBlob(privateContainer, object.getProperties().getName(),\n               GetOptions.Builder.ifETagMatches(newEtag));\n         assertEquals(getBlob.getProperties().getETag(), newEtag);\n      } catch (HttpResponseException e) {\n         assertEquals(e.getResponse().getStatusCode(), 412);\n      }\n\n      getBlob = getApi().getBlob(privateContainer, object.getProperties().getName(), GetOptions.Builder.startAt(8));\n      assertEquals(Strings2.toStringAndClose(getBlob.getPayload().openStream()), data.substring(8));\n\n      getApi().deleteBlob(privateContainer, \"object\");\n      getApi().deleteBlob(privateContainer, \"chunked-object\");\n   }\n\n   @Test(timeOut = 5 * 60 * 1000)\n   public void testBlockOperations() throws Exception {\n      String blockContainer = CONTAINER_PREFIX + containerIndex.incrementAndGet();\n      String blockBlob = \"myblockblob-\" + new SecureRandom().nextInt();\n      String A = \"A\";\n      String B = \"B\";\n      String C = \"C\";\n\n      String blockIdA = BaseEncoding.base64().encode((blockBlob + \"-\" + A).getBytes());\n      String blockIdB = BaseEncoding.base64().encode((blockBlob + \"-\" + B).getBytes());\n      String blockIdC = BaseEncoding.base64().encode((blockBlob + \"-\" + C).getBytes());\n\n      getApi().createContainer(blockContainer);\n\n      getApi().putBlock(blockContainer, blockBlob, blockIdA, Payloads.newByteArrayPayload(A.getBytes()));\n      getApi().putBlock(blockContainer, blockBlob, blockIdB, Payloads.newByteArrayPayload(B.getBytes()));\n      getApi().putBlock(blockContainer, blockBlob, blockIdC, Payloads.newByteArrayPayload(C.getBytes()));\n\n      ListBlobsResponse blobs = getApi().listBlobs(blockContainer);\n      assertThat(blobs).isEmpty();\n      blobs = getApi().listBlobs(blockContainer, new ListBlobsOptions().include(EnumSet.allOf(ListBlobsInclude.class)));\n      assertThat(blobs).hasSize(1);\n\n      getApi().putBlockList(blockContainer, blockBlob, Arrays.asList(blockIdA, blockIdB, blockIdC));\n\n      ListBlobBlocksResponse blocks = getApi().getBlockList(blockContainer, blockBlob);\n      assertEquals(3, blocks.getBlocks().size());\n      assertEquals(blockIdA, blocks.getBlocks().get(0).getBlockName());\n      assertEquals(blockIdB, blocks.getBlocks().get(1).getBlockName());\n      assertEquals(blockIdC, blocks.getBlocks().get(2).getBlockName());\n      assertEquals(1, blocks.getBlocks().get(0).getContentLength());\n      assertEquals(1, blocks.getBlocks().get(1).getContentLength());\n      assertEquals(1, blocks.getBlocks().get(2).getContentLength());\n\n      getApi().deleteContainer(blockContainer);\n   }\n\n   @Test\n   public void testGetSetACL() throws Exception {\n      String authType = System.getProperty(AUTH_TYPE);\n      if (authType != null && AuthType.fromValue(authType) == AuthType.AZURE_AD) {\n         throw new SkipException(\"Get/Set ACL unsupported with Azure AD\");\n      }\n      AzureBlobClient client = getApi();\n      String blockContainer = CONTAINER_PREFIX + containerIndex.incrementAndGet();\n      client.createContainer(blockContainer);\n      try {\n         assertThat(client.getPublicAccessForContainer(blockContainer)).isEqualTo(PublicAccess.PRIVATE);\n\n         setAndVerifyACL(client, blockContainer, PublicAccess.CONTAINER);\n         setAndVerifyACL(client, blockContainer, PublicAccess.BLOB);\n         setAndVerifyACL(client, blockContainer, PublicAccess.PRIVATE);\n      } finally {\n         client.deleteContainer(blockContainer);\n      }\n   }\n\n   private static void setAndVerifyACL(AzureBlobClient client, String blockContainer, PublicAccess access)\n         throws Exception {\n      client.setPublicAccessForContainer(blockContainer, access);\n      assertThat(client.getPublicAccessForContainer(blockContainer)).isEqualTo(access);\n   }\n\n   @Test(timeOut = 5 * 60 * 1000, dependsOnMethods = { \"testCreateContainer\" })\n   public void testCopyBlob() throws Exception {\n      ByteSource byteSource = TestUtils.randomByteSource().slice(0, 1024);\n\n      // create blob\n      AzureBlob object = getApi().newBlob();\n      object.getProperties().setName(\"from\");\n      object.setPayload(byteSource.read());\n      getApi().putBlob(privateContainer, object);\n\n      // copy blob\n      URI copySource = view.getSigner().signGetBlob(privateContainer, \"from\").getEndpoint();\n      getApi().copyBlob(copySource, privateContainer, \"to\", CopyBlobOptions.NONE);\n\n      // ensure copied blob matches original\n      AzureBlob getBlob = getApi().getBlob(privateContainer, \"to\");\n      assertEquals(ByteStreams2.toByteArrayAndClose(getBlob.getPayload().openStream()), byteSource.read());\n      assertThat(getBlob.getProperties().getMetadata().isEmpty());\n   }\n\n   @Test(timeOut = 5 * 60 * 1000, dependsOnMethods = { \"testCreateContainer\" })\n   public void testCopyBlobReplaceMetadata() throws Exception {\n      ByteSource byteSource = TestUtils.randomByteSource().slice(0, 1024);\n\n      // create blob\n      AzureBlob object = getApi().newBlob();\n      object.getProperties().setName(\"from\");\n      object.setPayload(byteSource.read());\n      getApi().putBlob(privateContainer, object);\n\n      // copy blob\n      URI copySource = view.getSigner().signGetBlob(privateContainer, \"from\").getEndpoint();\n      Map<String, String> newMetadata = ImmutableMap.of(\"foo\", \"bar\");\n      getApi().copyBlob(copySource, privateContainer, \"to\", CopyBlobOptions.builder().overrideUserMetadata(newMetadata).build());\n\n      // ensure copied blob matches original\n      AzureBlob getBlob = getApi().getBlob(privateContainer, \"to\");\n      assertEquals(ByteStreams2.toByteArrayAndClose(getBlob.getPayload().openStream()), byteSource.read());\n      assertThat(getBlob.getProperties().getMetadata()).isEqualTo(newMetadata);\n   }\n\n   @Test(timeOut = 5 * 60 * 1000, dependsOnMethods = { \"testCreateContainer\" })\n   public void testCopyBlobIfModifiedSince() throws Exception {\n      ByteSource byteSource = TestUtils.randomByteSource().slice(0, 1024);\n\n      // create blob\n      AzureBlob object = getApi().newBlob();\n      object.getProperties().setName(\"from\");\n      object.setPayload(byteSource.read());\n      String eTag = getApi().putBlob(privateContainer, object);\n\n      long now = System.currentTimeMillis();\n      Date before = new Date(now - 1000 * 1000);\n      Date after = new Date(now + 1000 * 1000);\n      URI copySource = view.getSigner().signGetBlob(privateContainer, \"from\").getEndpoint();\n\n      // failure case\n      try {\n         getApi().copyBlob(copySource, privateContainer, \"to-if-modified-since\", CopyBlobOptions.builder().ifModifiedSince(after).build());\n         failBecauseExceptionWasNotThrown(AzureStorageResponseException.class);\n      } catch (AzureStorageResponseException asre) {\n         assertThat(asre.getResponse().getStatusCode()).as(\"status code\").isEqualTo(412);\n      }\n\n      // success case\n      getApi().copyBlob(copySource, privateContainer, \"to-if-modified-since\", CopyBlobOptions.builder().ifModifiedSince(before).build());\n      AzureBlob getBlob = getApi().getBlob(privateContainer, \"to-if-modified-since\");\n      assertEquals(ByteStreams2.toByteArrayAndClose(getBlob.getPayload().openStream()), byteSource.read());\n   }\n\n   @Test(timeOut = 5 * 60 * 1000, dependsOnMethods = { \"testCreateContainer\" })\n   public void testCopyBlobIfUnmodifiedSince() throws Exception {\n      ByteSource byteSource = TestUtils.randomByteSource().slice(0, 1024);\n\n      // create blob\n      AzureBlob object = getApi().newBlob();\n      object.getProperties().setName(\"from\");\n      object.setPayload(byteSource.read());\n      String eTag = getApi().putBlob(privateContainer, object);\n\n      long now = System.currentTimeMillis();\n      Date before = new Date(now - 1000 * 1000);\n      Date after = new Date(now + 1000 * 1000);\n      URI copySource = view.getSigner().signGetBlob(privateContainer, \"from\").getEndpoint();\n\n      // failure case\n      try {\n         getApi().copyBlob(copySource, privateContainer, \"to-if-unmodifed-since\", CopyBlobOptions.builder().ifUnmodifiedSince(before).build());\n         failBecauseExceptionWasNotThrown(AzureStorageResponseException.class);\n      } catch (AzureStorageResponseException asre) {\n         assertThat(asre.getResponse().getStatusCode()).as(\"status code\").isEqualTo(412);\n      }\n\n      // success case\n      getApi().copyBlob(copySource, privateContainer, \"to-if-unmodifed-since\", CopyBlobOptions.builder().ifUnmodifiedSince(after).build());\n      AzureBlob getBlob = getApi().getBlob(privateContainer, \"to-if-unmodifed-since\");\n      assertEquals(ByteStreams2.toByteArrayAndClose(getBlob.getPayload().openStream()), byteSource.read());\n   }\n\n   @Test(timeOut = 5 * 60 * 1000, dependsOnMethods = { \"testCreateContainer\" })\n   public void testCopyBlobIfMatch() throws Exception {\n      ByteSource byteSource = TestUtils.randomByteSource().slice(0, 1024);\n\n      // create blob\n      AzureBlob object = getApi().newBlob();\n      object.getProperties().setName(\"from\");\n      object.setPayload(byteSource.read());\n      String eTag = getApi().putBlob(privateContainer, object);\n      String fakeETag = \"0x8CEB669D794AFE2\";\n\n      URI copySource = view.getSigner().signGetBlob(privateContainer, \"from\").getEndpoint();\n\n      // failure case\n      try {\n         getApi().copyBlob(copySource, privateContainer, \"to-if-match\", CopyBlobOptions.builder().ifMatch(fakeETag).build());\n         failBecauseExceptionWasNotThrown(AzureStorageResponseException.class);\n      } catch (AzureStorageResponseException asre) {\n         assertThat(asre.getResponse().getStatusCode()).as(\"status code\").isEqualTo(412);\n      }\n\n      // success case\n      getApi().copyBlob(copySource, privateContainer, \"to-if-match\", CopyBlobOptions.builder().ifMatch(eTag).build());\n      AzureBlob getBlob = getApi().getBlob(privateContainer, \"to-if-match\");\n      assertEquals(ByteStreams2.toByteArrayAndClose(getBlob.getPayload().openStream()), byteSource.read());\n   }\n\n   @Test(timeOut = 5 * 60 * 1000, dependsOnMethods = { \"testCreateContainer\" })\n   public void testCopyBlobIfNoneMatch() throws Exception {\n      ByteSource byteSource = TestUtils.randomByteSource().slice(0, 1024);\n\n      // create blob\n      AzureBlob object = getApi().newBlob();\n      object.getProperties().setName(\"from\");\n      object.setPayload(byteSource.read());\n      String eTag = getApi().putBlob(privateContainer, object);\n      String fakeETag = \"0x8CEB669D794AFE2\";\n\n      URI copySource = view.getSigner().signGetBlob(privateContainer, \"from\").getEndpoint();\n\n      // failure case\n      try {\n         getApi().copyBlob(copySource, privateContainer, \"to-if-none-match\", CopyBlobOptions.builder().ifNoneMatch(eTag).build());\n         failBecauseExceptionWasNotThrown(AzureStorageResponseException.class);\n      } catch (AzureStorageResponseException asre) {\n         assertThat(asre.getResponse().getStatusCode()).as(\"status code\").isEqualTo(412);\n      }\n\n      // success case\n      getApi().copyBlob(copySource, privateContainer, \"to-if-none-match\", CopyBlobOptions.builder().ifNoneMatch(fakeETag).build());\n      AzureBlob getBlob = getApi().getBlob(privateContainer, \"to-if-none-match\");\n      assertEquals(ByteStreams2.toByteArrayAndClose(getBlob.getPayload().openStream()), byteSource.read());\n   }\n\n   @Test(timeOut = 5 * 60 * 1000, dependsOnMethods = { \"testCreateContainer\" })\n   public void testSetBlobProperties() throws Exception {\n      String blobName = \"blob-name\";\n      ByteSource byteSource = TestUtils.randomByteSource().slice(0, 1024);\n      String contentDisposition = \"attachment; filename=photo.jpg\";\n      String contentEncoding = \"compress\";\n      String contentLanguage = \"en\";\n      String contentType = \"audio/ogg\";\n\n      // create blob\n      AzureBlob object = getApi().newBlob();\n      object.getProperties().setName(blobName);\n      object.setPayload(byteSource.read());\n      getApi().putBlob(privateContainer, object);\n\n      // set properties\n      getApi().setBlobProperties(privateContainer, blobName, ContentMetadataBuilder.create()\n              .contentDisposition(contentDisposition)\n              .contentEncoding(contentEncoding)\n              .contentLanguage(contentLanguage)\n              .contentType(contentType)\n              .build());\n\n      // get properties\n      BlobProperties properties = getApi().getBlobProperties(privateContainer, blobName);\n      ContentMetadata contentMetadata = properties.getContentMetadata();\n      assertThat(contentMetadata.getContentDisposition()).isEqualTo(contentDisposition);\n      assertThat(contentMetadata.getContentEncoding()).isEqualTo(contentEncoding);\n      assertThat(contentMetadata.getContentLanguage()).isEqualTo(contentLanguage);\n      assertThat(contentMetadata.getContentType()).isEqualTo(contentType);\n   }\n\n   @Test(timeOut = 5 * 60 * 1000, dependsOnMethods = { \"testCreateContainer\" })\n   public void testSetBlobTier() throws Exception {\n      String blobName = \"tier-blob-name\";\n      ByteSource byteSource = TestUtils.randomByteSource().slice(0, 1024);\n\n      // create blob\n      AzureBlob object = getApi().newBlob();\n      object.getProperties().setName(blobName);\n      object.setPayload(byteSource.read());\n      getApi().putBlob(privateContainer, object);\n\n      // default\n      BlobProperties properties = getApi().getBlobProperties(privateContainer, blobName);\n      assertThat(properties.getTier()).isEqualTo(AccessTier.HOT);\n\n      // hot\n      getApi().setBlobTier(privateContainer, blobName, AccessTier.HOT);\n      properties = getApi().getBlobProperties(privateContainer, blobName);\n      assertThat(properties.getTier()).isEqualTo(AccessTier.HOT);\n\n      // cool\n      getApi().setBlobTier(privateContainer, blobName, AccessTier.COOL);\n      properties = getApi().getBlobProperties(privateContainer, blobName);\n      assertThat(properties.getTier()).isEqualTo(AccessTier.COOL);\n\n      // archive\n      getApi().setBlobTier(privateContainer, blobName, AccessTier.ARCHIVE);\n      properties = getApi().getBlobProperties(privateContainer, blobName);\n      assertThat(properties.getTier()).isEqualTo(AccessTier.ARCHIVE);\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/test/java/org/jclouds/azureblob/AzureBlobClientTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob;\n\nimport static org.jclouds.azure.storage.options.ListOptions.Builder.maxResults;\nimport static org.jclouds.azureblob.options.CreateContainerOptions.Builder.withPublicAccess;\nimport static org.jclouds.reflect.Reflection2.method;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.EnumSet;\nimport java.util.Map;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.Fallbacks.TrueOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.azure.storage.filters.SharedKeyLiteAuthentication;\nimport org.jclouds.azure.storage.options.ListOptions;\nimport org.jclouds.azureblob.AzureBlobFallbacks.FalseIfContainerAlreadyExists;\nimport org.jclouds.azureblob.domain.AccessTier;\nimport org.jclouds.azureblob.domain.AzureBlob;\nimport org.jclouds.azureblob.domain.ListBlobsInclude;\nimport org.jclouds.azureblob.domain.PublicAccess;\nimport org.jclouds.azureblob.functions.ParseBlobFromHeadersAndHttpContent;\nimport org.jclouds.azureblob.functions.ParseContainerPropertiesFromHeaders;\nimport org.jclouds.azureblob.functions.ParsePublicAccessHeader;\nimport org.jclouds.azureblob.options.CopyBlobOptions;\nimport org.jclouds.azureblob.options.CreateContainerOptions;\nimport org.jclouds.azureblob.options.ListBlobsOptions;\nimport org.jclouds.azureblob.xml.AccountNameEnumerationResultsHandler;\nimport org.jclouds.azureblob.xml.ContainerNameEnumerationResultsHandler;\nimport org.jclouds.blobstore.BlobStoreFallbacks.NullOnContainerNotFound;\nimport org.jclouds.blobstore.BlobStoreFallbacks.NullOnKeyNotFound;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.functions.ParseETagHeader;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.http.functions.ReleasePayloadAndReturn;\nimport org.jclouds.http.functions.ReturnTrueIf2xx;\nimport org.jclouds.http.options.GetOptions;\nimport org.jclouds.io.ContentMetadata;\nimport org.jclouds.io.ContentMetadataBuilder;\nimport org.jclouds.rest.internal.BaseRestAnnotationProcessingTest;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.reflect.Invokable;\n\n@Test(groups = \"unit\", testName = \"AzureBlobClientTest\")\npublic class AzureBlobClientTest extends BaseRestAnnotationProcessingTest<AzureBlobClient> {\n\n   private static AzureBlobClient getAzureBlobClient() {\n      return ContextBuilder\n            .newBuilder(\"azureblob\")\n            .credentials(\"accessKey\", \"secretKey\")\n            .buildApi(AzureBlobClient.class);\n   }\n\n   public void testListContainers() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AzureBlobClient.class, \"listContainers\", ListOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(request, \"GET https://identity.blob.core.windows.net/?comp=list HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"x-ms-version: 2017-11-09\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, AccountNameEnumerationResultsHandler.class);\n      assertFallbackClassEquals(method, null);\n\n   }\n\n   public void testListContainersOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AzureBlobClient.class, \"listContainers\", ListOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(maxResults(1).marker(\"marker\").prefix(\"prefix\")));\n\n      assertRequestLineEquals(request,\n               \"GET https://identity.blob.core.windows.net/?comp=list&maxresults=1&marker=marker&prefix=prefix HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"x-ms-version: 2017-11-09\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, AccountNameEnumerationResultsHandler.class);\n      assertFallbackClassEquals(method, null);\n   }\n\n   public void testCreateContainer() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AzureBlobClient.class, \"createContainer\", String.class,\n               CreateContainerOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"container\"));\n\n      assertRequestLineEquals(request,\n               \"PUT https://identity.blob.core.windows.net/container?restype=container HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"x-ms-version: 2017-11-09\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ReturnTrueIf2xx.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, FalseIfContainerAlreadyExists.class);\n   }\n\n   public void testDeleteContainer() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AzureBlobClient.class, \"deleteContainer\", String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"container\"));\n\n      assertRequestLineEquals(request,\n               \"DELETE https://identity.blob.core.windows.net/container?restype=container HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"x-ms-version: 2017-11-09\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, VoidOnNotFoundOr404.class);\n   }\n\n   public void testCreateContainerOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AzureBlobClient.class, \"createContainer\", String.class,\n               CreateContainerOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"container\", withPublicAccess(PublicAccess.BLOB)\n               .withMetadata(ImmutableMultimap.of(\"foo\", \"bar\"))));\n\n      assertRequestLineEquals(request,\n               \"PUT https://identity.blob.core.windows.net/container?restype=container HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request,\n               \"x-ms-blob-public-access: blob\\n\" +\n               \"x-ms-meta-foo: bar\\n\" +\n               \"x-ms-version: 2017-11-09\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ReturnTrueIf2xx.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, FalseIfContainerAlreadyExists.class);\n   }\n\n   public void testCreateRootContainer() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AzureBlobClient.class, \"createRootContainer\", CreateContainerOptions[].class);\n\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(request, \"PUT https://identity.blob.core.windows.net/$root?restype=container HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"x-ms-version: 2017-11-09\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ReturnTrueIf2xx.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, FalseIfContainerAlreadyExists.class);\n   }\n\n   public void testDeleteRootContainer() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AzureBlobClient.class, \"deleteRootContainer\");\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(request, \"DELETE https://identity.blob.core.windows.net/$root?restype=container HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"x-ms-version: 2017-11-09\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, TrueOnNotFoundOr404.class);\n   }\n\n   public void testCreateRootContainerOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AzureBlobClient.class, \"createRootContainer\", CreateContainerOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(withPublicAccess(PublicAccess.BLOB).withMetadata(\n               ImmutableMultimap.of(\"foo\", \"bar\"))));\n\n      assertRequestLineEquals(request, \"PUT https://identity.blob.core.windows.net/$root?restype=container HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request,\n               \"x-ms-blob-public-access: blob\\n\" +\n               \"x-ms-meta-foo: bar\\n\" +\n               \"x-ms-version: 2017-11-09\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ReturnTrueIf2xx.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, FalseIfContainerAlreadyExists.class);\n   }\n\n   public void testListBlobs() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AzureBlobClient.class, \"listBlobs\", String.class, ListBlobsOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"container\"));\n\n      assertRequestLineEquals(request,\n               \"GET https://identity.blob.core.windows.net/container?restype=container&comp=list HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"x-ms-version: 2017-11-09\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, ContainerNameEnumerationResultsHandler.class);\n      assertFallbackClassEquals(method, null);\n   }\n\n   public void testListBlobsWithOptions() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AzureBlobClient.class, \"listBlobs\", String.class, ListBlobsOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"container\", new ListBlobsOptions().include(EnumSet.allOf(ListBlobsInclude.class))));\n\n      assertRequestLineEquals(request,\n               \"GET https://identity.blob.core.windows.net/container?restype=container&comp=list&include=copy,metadata,snapshots,uncommittedblobs HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"x-ms-version: 2017-11-09\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, ContainerNameEnumerationResultsHandler.class);\n      assertFallbackClassEquals(method, null);\n   }\n\n   public void testListRootBlobs() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AzureBlobClient.class, \"listBlobs\", ListBlobsOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(request,\n               \"GET https://identity.blob.core.windows.net/$root?restype=container&comp=list HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"x-ms-version: 2017-11-09\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ParseSax.class);\n      assertSaxResponseParserClassEquals(method, ContainerNameEnumerationResultsHandler.class);\n      assertFallbackClassEquals(method, null);\n   }\n\n   public void testContainerProperties() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AzureBlobClient.class, \"getContainerProperties\", String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"container\"));\n\n      assertRequestLineEquals(request,\n               \"HEAD https://identity.blob.core.windows.net/container?restype=container HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"x-ms-version: 2017-11-09\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ParseContainerPropertiesFromHeaders.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnContainerNotFound.class);\n   }\n\n   public void testGetPublicAccessForContainer() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AzureBlobClient.class, \"getPublicAccessForContainer\", String.class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"container\"));\n\n      assertRequestLineEquals(request,\n               \"HEAD https://identity.blob.core.windows.net/container?restype=container&comp=acl HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"x-ms-version: 2017-11-09\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ParsePublicAccessHeader.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnContainerNotFound.class);\n   }\n\n   public void testSetPublicAccessForContainer() throws SecurityException, NoSuchMethodException, IOException {\n      setAndVerifyPublicAccessForContainer(PublicAccess.CONTAINER,\n            \"x-ms-blob-public-access: container\\n\");\n      setAndVerifyPublicAccessForContainer(PublicAccess.BLOB,\n            \"x-ms-blob-public-access: blob\\n\");\n      setAndVerifyPublicAccessForContainer(PublicAccess.PRIVATE,\n            \"\");\n   }\n\n   private void setAndVerifyPublicAccessForContainer(PublicAccess access, String expectedHeader) {\n      Invokable<?, ?> method = method(AzureBlobClient.class, \"setPublicAccessForContainer\", String.class, PublicAccess.class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"container\", access));\n\n      assertRequestLineEquals(request,\n               \"PUT https://identity.blob.core.windows.net/container?restype=container&comp=acl HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request,\n               expectedHeader +\n               \"x-ms-version: 2017-11-09\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ParseETagHeader.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n   }\n\n   public void testSetResourceMetadata() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AzureBlobClient.class, \"setResourceMetadata\", String.class, Map.class);\n      GeneratedHttpRequest request = processor.createRequest(method,\n            ImmutableList.<Object> of(\"container\", ImmutableMap.of(\"key\", \"value\")));\n\n      assertRequestLineEquals(request,\n               \"PUT https://identity.blob.core.windows.net/container?restype=container&comp=metadata HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request,\n               \"x-ms-meta-key: value\\n\" +\n               \"x-ms-version: 2017-11-09\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n   }\n\n   public void testPutBlob() throws Exception {\n      Invokable<?, ?> method = method(AzureBlobClient.class, \"putBlob\", String.class, AzureBlob.class);\n      String payload = \"payload\";\n      String cacheControl = \"max-age=3600\";\n      AzureBlob object = getAzureBlobClient().newBlob();\n      object.setPayload(payload);\n      object.getProperties().setName(\"blob\");\n      object.getProperties().getContentMetadata().setCacheControl(cacheControl);\n      object.getProperties().getContentMetadata().setContentLength(7L);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"container\", object));\n\n      assertRequestLineEquals(request, \"PUT https://identity.blob.core.windows.net/container/blob HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request,\n            \"Expect: 100-continue\\n\" +\n            \"x-ms-blob-cache-control: \" + cacheControl + \"\\n\" +\n            \"x-ms-blob-type: BlockBlob\\n\" +\n            \"x-ms-version: 2017-11-09\\n\");\n      assertPayloadEquals(request, payload, \"application/unknown\", false);\n\n      assertResponseParserClassEquals(method, request, ParseETagHeader.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n   }\n\n   public void testGetBlob() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AzureBlobClient.class, \"getBlob\", String.class, String.class, GetOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"container\", \"blob\"));\n\n      assertRequestLineEquals(request, \"GET https://identity.blob.core.windows.net/container/blob HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"x-ms-version: 2017-11-09\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ParseBlobFromHeadersAndHttpContent.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnKeyNotFound.class);\n   }\n\n   public void testSetBlobMetadata() throws SecurityException, NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(AzureBlobClient.class, \"setBlobMetadata\", String.class, String.class, Map.class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"container\", \"blob\", ImmutableMap.of(\"key\", \"value\")));\n\n      assertRequestLineEquals(request,\n               \"PUT https://identity.blob.core.windows.net/container/blob?comp=metadata HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request,\n               \"x-ms-meta-key: value\\n\" +\n               \"x-ms-version: 2017-11-09\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ParseETagHeader.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n   }\n\n   public void testSetBlobProperties() throws Exception {\n      String cacheControl = \"max-age=3600\";\n      ContentMetadata metadata = ContentMetadataBuilder.create()\n            .cacheControl(cacheControl)\n            .build();\n      Invokable<?, ?> method = method(AzureBlobClient.class, \"setBlobProperties\", String.class, String.class, ContentMetadata.class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"container\", \"blob\", metadata));\n\n      assertRequestLineEquals(request,\n               \"PUT https://identity.blob.core.windows.net/container/blob?comp=properties HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request,\n               \"x-ms-blob-cache-control: \" + cacheControl + \"\\n\" +\n               \"x-ms-blob-content-type: application/unknown\\n\" +\n               \"x-ms-version: 2017-11-09\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ParseETagHeader.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n   }\n\n   public void testSetBlobTier() throws Exception {\n      AccessTier tier = AccessTier.COOL;\n      Invokable<?, ?> method = method(AzureBlobClient.class, \"setBlobTier\", String.class, String.class, AccessTier.class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"container\", \"blob\", tier));\n\n      assertRequestLineEquals(request,\n               \"PUT https://identity.blob.core.windows.net/container/blob?comp=tier HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request,\n               \"x-ms-access-tier: \" + tier + \"\\n\" +\n               \"x-ms-version: 2017-11-09\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n   }\n\n   public void testCopyBlob() throws Exception {\n      Invokable<?, ?> method = method(AzureBlobClient.class, \"copyBlob\", URI.class, String.class, String.class, CopyBlobOptions.class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\n               URI.create(\"https://identity.blob.core.windows.net/fromcontainer/fromblob\"), \"tocontainer\", \"toblob\", CopyBlobOptions.NONE));\n\n      assertRequestLineEquals(request,\n               \"PUT https://identity.blob.core.windows.net/tocontainer/toblob HTTP/1.1\");\n      checkFilters(request);\n      assertNonPayloadHeadersEqual(request,\n               \"x-ms-copy-source: https://identity.blob.core.windows.net/fromcontainer/fromblob\\n\" +\n               \"x-ms-version: 2017-11-09\\n\");\n      assertPayloadEquals(request, null, null, false);\n   }\n\n   public void testCopyBlobOverwriteUserMetadata() throws Exception {\n      CopyBlobOptions options = CopyBlobOptions.builder().overrideUserMetadata(ImmutableMap.of(\"foo\", \"bar\")).build();\n      Invokable<?, ?> method = method(AzureBlobClient.class, \"copyBlob\", URI.class, String.class, String.class, CopyBlobOptions.class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\n               URI.create(\"https://identity.blob.core.windows.net/fromcontainer/fromblob\"), \"tocontainer\", \"toblob\", options));\n\n      assertRequestLineEquals(request,\n               \"PUT https://identity.blob.core.windows.net/tocontainer/toblob HTTP/1.1\");\n      checkFilters(request);\n      assertNonPayloadHeadersEqual(request,\n               \"x-ms-copy-source: https://identity.blob.core.windows.net/fromcontainer/fromblob\\n\" +\n               \"x-ms-meta-foo: bar\\n\" +\n               \"x-ms-version: 2017-11-09\\n\");\n      assertPayloadEquals(request, null, null, false);\n   }\n\n   public void testCopyBlobIfModifiedSince() throws Exception {\n      CopyBlobOptions options = CopyBlobOptions.builder().ifModifiedSince(new Date(1000)).build();\n      Invokable<?, ?> method = method(AzureBlobClient.class, \"copyBlob\", URI.class, String.class, String.class, CopyBlobOptions.class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\n               URI.create(\"https://identity.blob.core.windows.net/fromcontainer/fromblob\"), \"tocontainer\", \"toblob\", options));\n\n      assertRequestLineEquals(request,\n               \"PUT https://identity.blob.core.windows.net/tocontainer/toblob HTTP/1.1\");\n      checkFilters(request);\n      assertNonPayloadHeadersEqual(request,\n               \"x-ms-copy-source: https://identity.blob.core.windows.net/fromcontainer/fromblob\\n\" +\n               \"x-ms-source-if-modified-since: Thu, 01 Jan 1970 00:00:01 GMT\\n\" +\n               \"x-ms-version: 2017-11-09\\n\");\n      assertPayloadEquals(request, null, null, false);\n   }\n\n   public void testCopyBlobIfUnmodifiedSince() throws Exception {\n      CopyBlobOptions options = CopyBlobOptions.builder().ifUnmodifiedSince(new Date(1000)).build();\n      Invokable<?, ?> method = method(AzureBlobClient.class, \"copyBlob\", URI.class, String.class, String.class, CopyBlobOptions.class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\n               URI.create(\"https://identity.blob.core.windows.net/fromcontainer/fromblob\"), \"tocontainer\", \"toblob\", options));\n\n      assertRequestLineEquals(request,\n               \"PUT https://identity.blob.core.windows.net/tocontainer/toblob HTTP/1.1\");\n      checkFilters(request);\n      assertNonPayloadHeadersEqual(request,\n               \"x-ms-copy-source: https://identity.blob.core.windows.net/fromcontainer/fromblob\\n\" +\n               \"x-ms-source-if-unmodified-since: Thu, 01 Jan 1970 00:00:01 GMT\\n\" +\n               \"x-ms-version: 2017-11-09\\n\");\n      assertPayloadEquals(request, null, null, false);\n   }\n\n   public void testCopyBlobIfMatch() throws Exception {\n      String eTag = \"0x8CEB669D794AFE2\";\n      CopyBlobOptions options = CopyBlobOptions.builder().ifMatch(eTag).build();\n      Invokable<?, ?> method = method(AzureBlobClient.class, \"copyBlob\", URI.class, String.class, String.class, CopyBlobOptions.class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\n               URI.create(\"https://identity.blob.core.windows.net/fromcontainer/fromblob\"), \"tocontainer\", \"toblob\", options));\n\n      assertRequestLineEquals(request,\n               \"PUT https://identity.blob.core.windows.net/tocontainer/toblob HTTP/1.1\");\n      checkFilters(request);\n      assertNonPayloadHeadersEqual(request,\n               \"x-ms-copy-source: https://identity.blob.core.windows.net/fromcontainer/fromblob\\n\" +\n               \"x-ms-source-if-match: \" + eTag + \"\\n\" +\n               \"x-ms-version: 2017-11-09\\n\");\n      assertPayloadEquals(request, null, null, false);\n   }\n\n   public void testCopyBlobIfNoneMatch() throws Exception {\n      String eTag = \"0x8CEB669D794AFE2\";\n      CopyBlobOptions options = CopyBlobOptions.builder().ifNoneMatch(eTag).build();\n      Invokable<?, ?> method = method(AzureBlobClient.class, \"copyBlob\", URI.class, String.class, String.class, CopyBlobOptions.class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\n               URI.create(\"https://identity.blob.core.windows.net/fromcontainer/fromblob\"), \"tocontainer\", \"toblob\", options));\n\n      assertRequestLineEquals(request,\n               \"PUT https://identity.blob.core.windows.net/tocontainer/toblob HTTP/1.1\");\n      checkFilters(request);\n      assertNonPayloadHeadersEqual(request,\n               \"x-ms-copy-source: https://identity.blob.core.windows.net/fromcontainer/fromblob\\n\" +\n               \"x-ms-source-if-none-match: \" + eTag + \"\\n\" +\n               \"x-ms-version: 2017-11-09\\n\");\n      assertPayloadEquals(request, null, null, false);\n   }\n\n   @Override\n   protected void checkFilters(HttpRequest request) {\n      assertEquals(request.getFilters().size(), 1);\n      assertEquals(request.getFilters().get(0).getClass(), SharedKeyLiteAuthentication.class);\n   }\n\n   @Override\n   public AzureBlobProviderMetadata createProviderMetadata() {\n      return new AzureBlobProviderMetadata();\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/test/java/org/jclouds/azureblob/AzureBlobProviderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob;\n\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"AzureBlobProviderTest\")\npublic class AzureBlobProviderTest extends BaseProviderMetadataTest {\n\n   public AzureBlobProviderTest() {\n      super(new AzureBlobProviderMetadata(), new AzureBlobApiMetadata());\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/test/java/org/jclouds/azureblob/binders/BindAzureBlobMetadataToRequestTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.File;\n\nimport org.jclouds.azureblob.AzureBlobClient;\nimport org.jclouds.azureblob.AzureBlobProviderMetadata;\nimport org.jclouds.azureblob.domain.AzureBlob;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.rest.internal.BaseRestAnnotationProcessingTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\n\n@Test(groups = \"unit\", testName = \"BindAzureBlobMetadataToRequestTest\")\npublic class BindAzureBlobMetadataToRequestTest extends BaseRestAnnotationProcessingTest<AzureBlobClient> {\n\n   @Test\n   public void testPassWithMinimumDetailsAndPayload256MB() {\n      AzureBlob blob = injector.getInstance(AzureBlob.Factory.class).create(null);\n      Payload payload = Payloads.newStringPayload(\"\");\n      payload.getContentMetadata().setContentLength(256 * 1024 * 1024L);\n      blob.setPayload(payload);\n      blob.getProperties().setName(\"foo\");\n\n      HttpRequest request = HttpRequest.builder().method(\"PUT\").endpoint(\"http://localhost\").build();\n      BindAzureBlobMetadataToRequest binder = injector.getInstance(BindAzureBlobMetadataToRequest.class);\n\n      assertEquals(\n            binder.bindToRequest(request, blob),\n            HttpRequest.builder().method(\"PUT\").endpoint(\"http://localhost\")\n                  .addHeader(\"x-ms-blob-type\", \"BlockBlob\").build());\n   }\n\n   @Test\n   public void testExtendedPropertiesBind() {\n      AzureBlob blob = injector.getInstance(AzureBlob.Factory.class).create(null);\n      Payload payload = Payloads.newStringPayload(\"\");\n      payload.getContentMetadata().setContentLength(256 * 1024 * 1024L);\n      blob.setPayload(payload);\n      blob.getProperties().setName(\"foo\");\n      blob.getProperties().setMetadata(ImmutableMap.of(\"foo\", \"bar\"));\n\n      HttpRequest request = HttpRequest.builder().method(\"PUT\").endpoint(\"http://localhost\").build();\n      BindAzureBlobMetadataToRequest binder = injector.getInstance(BindAzureBlobMetadataToRequest.class);\n\n      assertEquals(\n            binder.bindToRequest(request, blob),\n            HttpRequest.builder().method(\"PUT\").endpoint(\"http://localhost\")\n                       .addHeader(\"x-ms-blob-type\", \"BlockBlob\")\n                       .addHeader(\"x-ms-meta-foo\", \"bar\").build());\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testNoContentLengthIsBad() {\n      AzureBlob blob = injector.getInstance(AzureBlob.Factory.class).create(null);\n      Payload payload = Payloads.newStringPayload(\"\");\n      payload.getContentMetadata().setContentLength(null);\n      blob.setPayload(payload);\n      blob.getProperties().setName(\"foo\");\n\n      HttpRequest request = HttpRequest.builder().method(\"PUT\").endpoint(\"http://localhost\").build();\n      BindAzureBlobMetadataToRequest binder = injector.getInstance(BindAzureBlobMetadataToRequest.class);\n      binder.bindToRequest(request, blob);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testNoNameIsBad() {\n      AzureBlob blob = injector.getInstance(AzureBlob.Factory.class).create(null);\n      Payload payload = Payloads.newStringPayload(\"\");\n      payload.getContentMetadata().setContentLength(5368709120000L);\n      blob.setPayload(payload);\n\n      HttpRequest request = HttpRequest.builder().method(\"PUT\").endpoint(\"http://localhost\").build();\n      BindAzureBlobMetadataToRequest binder = injector.getInstance(BindAzureBlobMetadataToRequest.class);\n      binder.bindToRequest(request, blob);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testOver256MBIsBad() {\n      AzureBlob blob = injector.getInstance(AzureBlob.Factory.class).create(null);\n      Payload payload = Payloads.newStringPayload(\"\");\n      payload.getContentMetadata().setContentLength(256 * 1024 * 1024L + 1);\n      blob.setPayload(payload);\n      blob.getProperties().setName(\"foo\");\n\n      HttpRequest request = HttpRequest.builder().method(\"PUT\").endpoint(\"http://localhost\").build();\n      BindAzureBlobMetadataToRequest binder = injector.getInstance(BindAzureBlobMetadataToRequest.class);\n      binder.bindToRequest(request, blob);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testMustBeAzureBlob() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"http://localhost\").build();\n      injector.getInstance(BindAzureBlobMetadataToRequest.class).bindToRequest(request, new File(\"foo\"));\n   }\n\n   @Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class })\n   public void testNullIsBad() {\n      BindAzureBlobMetadataToRequest binder = injector.getInstance(BindAzureBlobMetadataToRequest.class);\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").build();\n      binder.bindToRequest(request, null);\n   }\n\n   @Override\n   protected void checkFilters(HttpRequest request) {\n   }\n\n   @Override\n   public AzureBlobProviderMetadata createProviderMetadata() {\n      return new AzureBlobProviderMetadata();\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/test/java/org/jclouds/azureblob/blobstore/AzureBlobRequestSignerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.blobstore;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.util.Date;\n\nimport org.jclouds.azureblob.AzureBlobClient;\nimport org.jclouds.azureblob.AzureBlobProviderMetadata;\nimport org.jclouds.azureblob.config.AzureBlobHttpApiModule;\nimport org.jclouds.blobstore.BlobRequestSigner;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.Blob.Factory;\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.internal.BaseRestAnnotationProcessingTest;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.hash.HashCode;\nimport com.google.inject.Module;\n\n/**\n * Tests behavior of {@code AzureBlobRequestSigner}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"AzureBlobRequestSignerTest\")\npublic class AzureBlobRequestSignerTest extends BaseRestAnnotationProcessingTest<AzureBlobClient> {\n\n   public AzureBlobRequestSignerTest() {\n      // this is base64 decoded in the signer;\n      credential = \"aaaabbbb\"; \n   }\n   \n   private AzureBlobRequestSigner signer;\n   private Factory blobFactory;\n\n   public void testSignGetBlob() throws ArrayIndexOutOfBoundsException, SecurityException, IllegalArgumentException,\n            NoSuchMethodException, IOException {\n      HttpRequest request = signer.signGetBlob(\"container\", \"name\");\n\n      assertRequestLineEquals(request, \"GET https://identity.blob.core.windows.net/container/name?sv=2017-11-09&se=2008-06-05T16%3A53%3A19Z&sr=b&sp=r&sig=pE9fJqe8oVfYF4DoxcEE7R8p9kbzEkDvP/jot7QuyTo%3D HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Date: Thu, 05 Jun 2008 16:38:19 GMT\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertEquals(request.getFilters().size(), 0);\n   }\n\n   public void testSignRemoveBlob() throws ArrayIndexOutOfBoundsException, SecurityException, IllegalArgumentException,\n            NoSuchMethodException, IOException {\n      HttpRequest request = signer.signRemoveBlob(\"container\", \"name\");\n\n      assertRequestLineEquals(request, \"DELETE https://identity.blob.core.windows.net/container/name?sv=2017-11-09&se=2008-06-05T16%3A53%3A19Z&sr=b&sp=d&sig=BWQi9JrAVgZgiElhBKEEF/%2BRqhUJFeheG8cDkSAGHX4%3D HTTP/1.1\");\n      assertNonPayloadHeadersEqual(request, \"Date: Thu, 05 Jun 2008 16:38:19 GMT\\n\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertEquals(request.getFilters().size(), 0);\n   }\n\n   public void testSignPutBlob() throws ArrayIndexOutOfBoundsException, SecurityException, IllegalArgumentException,\n            NoSuchMethodException, IOException {\n      HashCode hashCode = HashCode.fromBytes(new byte[16]);\n      Blob blob = blobFactory.create(null);\n      blob.getMetadata().setName(\"name\");\n      blob.setPayload(\"\");\n      blob.getPayload().getContentMetadata().setContentLength(2L);\n      blob.getPayload().getContentMetadata().setContentMD5(hashCode);\n      blob.getPayload().getContentMetadata().setContentType(\"text/plain\");\n      blob.getPayload().getContentMetadata().setExpires(new Date(1000));\n\n      HttpRequest request = signer.signPutBlob(\"container\", blob);\n\n      assertRequestLineEquals(request, \"PUT https://identity.blob.core.windows.net/container/name?sv=2017-11-09&se=2008-06-05T16%3A53%3A19Z&sr=b&sp=w&sig=NbnJbaUxRK/VPr5xZy75VCgAG7rpzut2IJEjXDSbT8k%3D HTTP/1.1\");\n      assertNonPayloadHeadersEqual(\n               request,\n               \"Content-Length: 2\\n\" +\n               \"Date: Thu, 05 Jun 2008 16:38:19 GMT\\n\" +\n               \"x-ms-blob-content-type: text/plain\\n\" +\n               \"x-ms-blob-type: BlockBlob\\n\");\n\n      assertEquals(request.getFilters().size(), 0);\n   }\n\n   @BeforeClass\n   protected void setupFactory() throws IOException {\n      super.setupFactory();\n      this.blobFactory = injector.getInstance(Blob.Factory.class);\n      this.signer = (AzureBlobRequestSigner) injector.getInstance(BlobRequestSigner.class);\n   }\n\n   @Override\n   protected void checkFilters(HttpRequest request) {\n   }\n\n   @Override\n   protected Module createModule() {\n      return new TestAzureBlobHttpApiModule();\n   }\n\n      @ConfiguresHttpApi\n   private static final class TestAzureBlobHttpApiModule extends AzureBlobHttpApiModule {\n      @Override\n      protected void configure() {\n         super.configure();\n      }\n\n      @Override\n      protected String provideTimeStamp(@TimeStamp Supplier<String> cache) {\n         return \"Thu, 05 Jun 2008 16:38:19 GMT\";\n      }\n   }\n\n   @Override\n   public AzureBlobProviderMetadata createProviderMetadata() {\n      return new AzureBlobProviderMetadata();\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/test/java/org/jclouds/azureblob/blobstore/AzureBlobStoreTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.blobstore;\n\nimport static org.testng.Assert.assertTrue;\n\nimport org.testng.annotations.Test;\n\nimport java.util.regex.Pattern;\n/**\n * Tests behavior of {@code AzureBlobStore}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"AzureBlobStore\")\npublic class AzureBlobStoreTest {\n    \n    private static final Pattern VALIDATION_PATTERN = Pattern.compile(\"^[a-zA-Z0-9+/=]*$\");\n\n    public void testMakeBlockId() {\n       // how can i achieve something like a junit5 parametrized test in testng?\n       checkBlockIdForPartNumber(0);\n       checkBlockIdForPartNumber(1);\n       checkBlockIdForPartNumber(248);\n       checkBlockIdForPartNumber(504);\n       checkBlockIdForPartNumber(760);\n       checkBlockIdForPartNumber(1016);\n       checkBlockIdForPartNumber(1272);\n       checkBlockIdForPartNumber(4600);\n       checkBlockIdForPartNumber(6654);\n       checkBlockIdForPartNumber(867840);\n       checkBlockIdForPartNumber(868091);\n       checkBlockIdForPartNumber(868096);\n       checkBlockIdForPartNumber(-1);\n       checkBlockIdForPartNumber(-1023);\n   }\n   \n   private void checkBlockIdForPartNumber(int partNumber) {\n       String blockId = AzureBlobStore.makeBlockId(partNumber);\n       assertTrue(VALIDATION_PATTERN.matcher(blockId).find());\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/test/java/org/jclouds/azureblob/blobstore/functions/ListBlobsOptionsToListOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.blobstore.functions;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.azureblob.options.ListBlobsOptions;\nimport org.jclouds.blobstore.options.ListContainerOptions;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class ListBlobsOptionsToListOptions implements\n         Function<ListBlobsOptions[], ListContainerOptions> {\n   public ListContainerOptions apply(ListBlobsOptions[] optionsList) {\n      ListContainerOptions options = new ListContainerOptions();\n      if (optionsList.length != 0) {\n         if (optionsList[0].getDelimiter() == null) {\n            options.recursive();\n         } else if (!optionsList[0].getDelimiter().equals(\"/\")) {\n            throw new IllegalArgumentException(\"only '/' is allowed as a blobstore delimiter\");\n         }\n         if (optionsList[0].getMarker() != null) {\n            options.afterMarker(optionsList[0].getMarker());\n         }\n         if (optionsList[0].getMaxResults() != null) {\n            options.maxResults(optionsList[0].getMaxResults());\n         }\n         if (optionsList[0].getPrefix() != null) {\n            options.inDirectory(optionsList[0].getPrefix());\n         }\n         if (optionsList[0].getIncludeMetadata()) {\n            options.withDetails();\n         }\n      }\n      return options;\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/test/java/org/jclouds/azureblob/blobstore/functions/ResourceToListBlobsResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.blobstore.functions;\n\nimport java.util.SortedSet;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.azureblob.domain.BlobProperties;\nimport org.jclouds.azureblob.domain.ListBlobsResponse;\nimport org.jclouds.azureblob.domain.MutableBlobProperties;\nimport org.jclouds.azureblob.domain.internal.HashSetListBlobsResponse;\nimport org.jclouds.blobstore.domain.BlobMetadata;\nimport org.jclouds.blobstore.domain.PageSet;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.domain.StorageType;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Sets;\n\n@Singleton\npublic class ResourceToListBlobsResponse implements\n         Function<PageSet<? extends StorageMetadata>, ListBlobsResponse> {\n   private final BlobMetadataToBlobProperties blob2ObjectMd;\n\n   @Inject\n   public ResourceToListBlobsResponse(BlobMetadataToBlobProperties blob2ObjectMd) {\n      this.blob2ObjectMd = blob2ObjectMd;\n   }\n\n   public ListBlobsResponse apply(PageSet<? extends StorageMetadata> list) {\n\n      Iterable<BlobProperties> contents = Iterables.transform(Iterables.filter(list,\n               new Predicate<StorageMetadata>() {\n\n                  public boolean apply(StorageMetadata input) {\n                     return input.getType() == StorageType.BLOB;\n                  }\n\n               }), new Function<StorageMetadata, BlobProperties>() {\n\n         public MutableBlobProperties apply(StorageMetadata from) {\n            return blob2ObjectMd.apply((BlobMetadata) from);\n         }\n\n      });\n\n      SortedSet<String> commonPrefixes = Sets.newTreeSet(Iterables.transform(Iterables.filter(list,\n               new Predicate<StorageMetadata>() {\n\n                  public boolean apply(StorageMetadata input) {\n                     return input.getType() == StorageType.RELATIVE_PATH;\n                  }\n\n               }), new Function<StorageMetadata, String>() {\n\n         public String apply(StorageMetadata from) {\n            return from.getName();\n         }\n\n      }));\n      return new HashSetListBlobsResponse(contents, null, null, null, null, list.getNextMarker(),\n               \"/\", commonPrefixes);\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/test/java/org/jclouds/azureblob/blobstore/integration/AzureBlobContainerIntegrationLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.blobstore.integration;\n\nimport org.jclouds.blobstore.integration.internal.BaseContainerIntegrationTest;\nimport org.testng.annotations.Test;\nimport org.testng.SkipException;\n\n@Test(groups = \"live\")\npublic class AzureBlobContainerIntegrationLiveTest extends BaseContainerIntegrationTest {\n   public AzureBlobContainerIntegrationLiveTest() {\n      provider = \"azureblob\";\n   }\n\n   @Override\n   public void testListMarkerAfterLastKey() throws Exception {\n      throw new SkipException(\"cannot specify arbitrary markers\");\n   }\n\n   @Override\n   public void testListContainerWithZeroMaxResults() throws Exception {\n      throw new SkipException(\"Azure requires a positive integer for max results\");\n   }\n\n   @Override\n   public void testListMarkerPrefix() throws Exception {\n      throw new SkipException(\"cannot specify arbitrary markers\");\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/test/java/org/jclouds/azureblob/blobstore/integration/AzureBlobContainerLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.blobstore.integration;\n\nimport org.jclouds.blobstore.integration.internal.BaseContainerLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = { \"live\" })\npublic class AzureBlobContainerLiveTest extends BaseContainerLiveTest {\n   public AzureBlobContainerLiveTest() {\n      provider = \"azureblob\";\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/test/java/org/jclouds/azureblob/blobstore/integration/AzureBlobIntegrationLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.blobstore.integration;\n\nimport java.io.IOException;\nimport java.util.concurrent.ExecutionException;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.collect.ImmutableMap;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.integration.internal.BaseBlobIntegrationTest;\nimport org.jclouds.blobstore.options.CopyOptions;\nimport org.testng.SkipException;\nimport org.testng.annotations.Test;\n\nimport static com.google.common.hash.Hashing.md5;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\n\n@Test(groups = \"live\")\npublic class AzureBlobIntegrationLiveTest extends BaseBlobIntegrationTest {\n   @Override\n   protected long getMinimumMultipartBlobSize() {\n      return view.getBlobStore().getMaximumMultipartPartSize() + 1;\n   }\n\n   public AzureBlobIntegrationLiveTest() {\n      provider = \"azureblob\";\n   }\n\n   // TODO: Azure response has a quoted ETag but request requires unquoted ETag\n   @Override\n   public void testGetIfMatch() throws InterruptedException {\n      throw new SkipException(\"not yet implemented\");\n   }\n\n   public void testCreateBlobWithExpiry() throws InterruptedException {\n      throw new SkipException(\"Expires header unsupported: http://msdn.microsoft.com/en-us/library/windowsazure/dd179404.aspx#Subheading3\");\n   }\n\n   @Override\n   @Test\n   public void testPutObjectStream() throws InterruptedException, IOException, ExecutionException {\n      throw new SkipException(\"Azure requires a Content-Length\");\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testSetBlobAccess() throws Exception {\n      throw new SkipException(\"unsupported in Azure\");\n   }\n\n   @Test(groups = { \"integration\", \"live\" }, expectedExceptions = UnsupportedOperationException.class)\n   public void testPutBlobAccess() throws Exception {\n      super.testPutBlobAccess();\n   }\n\n   @Test(groups = { \"integration\", \"live\" }, expectedExceptions = UnsupportedOperationException.class)\n   public void testPutBlobAccessMultipart() throws Exception {\n      super.testPutBlobAccessMultipart();\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testSigningOfUppercaseMetadata() throws InterruptedException {\n      String containerName = getContainerName();\n      String blobName = \"testSigningOfUppercaseMetadata\";\n\n      Blob blob = view.getBlobStore().blobBuilder(blobName)\n          .userMetadata(ImmutableMap.of(\"B\", \"b\", \"a\", \"a\"))\n          .payload(TEST_STRING).contentType(MediaType.TEXT_PLAIN)\n          .contentMD5(md5().hashString(TEST_STRING, Charsets.UTF_8))\n          .build();\n\n      try {\n         assertNull(view.getBlobStore().blobMetadata(containerName, blobName));\n\n         addBlobToContainer(containerName, blob);\n         assertConsistencyAwareContainerSize(containerName, 1);\n\n         view.getBlobStore().copyBlob(\n             containerName, blobName, containerName, blobName,\n             CopyOptions.builder().userMetadata(ImmutableMap.of(\"B\", \"b\", \"a\", \"a\")).build()\n         );\n\n         Blob newObject = view.getBlobStore().getBlob(containerName, blobName);\n\n         assertNotNull(newObject);\n         assertEquals(newObject.getMetadata().getUserMetadata().get(\"b\"), \"b\");\n         assertEquals(newObject.getMetadata().getUserMetadata().get(\"a\"), \"a\");\n\n      } finally {\n         returnContainer(containerName);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/test/java/org/jclouds/azureblob/blobstore/integration/AzureBlobLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.blobstore.integration;\n\nimport org.jclouds.blobstore.integration.internal.BaseBlobLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = { \"live\" })\npublic class AzureBlobLiveTest extends BaseBlobLiveTest {\n   public AzureBlobLiveTest() {\n      provider = \"azureblob\";\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/test/java/org/jclouds/azureblob/blobstore/integration/AzureBlobServiceIntegrationLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.blobstore.integration;\n\nimport java.util.Set;\n\nimport org.jclouds.blobstore.integration.internal.BaseServiceIntegrationTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"live\")\npublic class AzureBlobServiceIntegrationLiveTest extends BaseServiceIntegrationTest {\n   public AzureBlobServiceIntegrationLiveTest() {\n      provider = \"azureblob\";\n   }\n   @Override\n   protected Set<String> getIso3166Codes() {\n      return ImmutableSet.<String> of(\"US-TX\", \"US-IL\", \"IE-D\", \"SG\", \"NL-NH\", \"HK\");\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/test/java/org/jclouds/azureblob/blobstore/integration/AzureBlobSignerLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.blobstore.integration;\n\nimport org.jclouds.blobstore.integration.internal.BaseBlobSignerLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = { \"live\" })\npublic class AzureBlobSignerLiveTest extends BaseBlobSignerLiveTest {\n   public AzureBlobSignerLiveTest() {\n      provider = \"azureblob\";\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/test/java/org/jclouds/azureblob/config/AzureBlobHttpApiModuleTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.config;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\nimport com.google.common.base.Suppliers;\nimport org.jclouds.domain.Credentials;\nimport org.testng.annotations.DataProvider;\n\n@Test(groups = \"unit\", testName = \"AzureBlobHttpApiModuleTest\") \npublic class AzureBlobHttpApiModuleTest {\n\n   @DataProvider(name = \"auth-sas-tokens\")\n   public static Object[][] tokens() {\n      return new Object[][]{\n         {false, \"sv=2018-03-28&se=2019-02-14T11:12:13Z\"}, \n         {false, \"sv=2018-03-28&se=2019-02-14T11:12:13Z&sp=abc&st=2019-01-20T11:12:13Z\"}, \n         {false, \"u2iAP01ARTewyK/MhOM1d1ASPpjqclkldsdkljfas2kfjkh895ssfslkjpXKfhg==\"}, \n         {false, \"sadf;gjkhflgjkhfdlkfdljghskldjghlfdghw4986754ltjkghdlfkjghst;lyho56[09y7poinh\"}, \n         {false, \"a=apple&b=banana&c=cucumber&d=diet\"}, \n         {false, \"sva=swajak&sta=stancyja&spa=spakoj&sea=mora&sig=podpis\"}, \n         {true, \"sv=2018-03-28&ss=b&srt=sco&sp=r&se=2019-02-13T17:03:09Z&st=2019-02-13T09:03:09Z&spr=https&sig=wNkWK%2GURTjHWhtqG6Q2Gu%2Qu%3FPukW6N4%2FIH4Mr%2F%2FO42M%3D\"}, \n         {true, \"sp=rl&st=2019-02-14T08:50:26Z&se=2019-02-15T08:50:26Z&sv=2018-03-28&sig=Ukow8%2GtpQpAiVZBLcWp1%2RSpFq928MAqzp%2BdrdregaB6%3D&sr=b\"}, \n         {false, \"\"},\n         {true, \"sig=Ukow8%2GtpQpAiVZBLcWp1%2RSpFq928MAqzp%2BdrdregaB6%3D\\u0026sv=2018-03-28\"}\n     };\n   }\n\n   @Test(dataProvider = \"auth-sas-tokens\") \n   void testAuthSasNonSufficientParametersSvSe(boolean expected, String credential){\n      AzureBlobHttpApiModule module = new AzureBlobHttpApiModule();\n      Credentials creds = new Credentials(\"identity\", credential);\n      assertEquals(module.authSAS(Suppliers.ofInstance(creds)), expected);\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/test/java/org/jclouds/azureblob/options/CreateContainerOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.options;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.azure.storage.reference.AzureStorageHeaders;\nimport org.jclouds.azureblob.domain.PublicAccess;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMultimap;\n\n/**\n * Tests behavior of {@code CreateContainerOptions}\n */\n@Test(groups = \"unit\")\npublic class CreateContainerOptionsTest {\n\n   public void testPublicAccess() {\n      CreateContainerOptions options = new CreateContainerOptions().withPublicAccess(PublicAccess.BLOB);\n      assertEquals(ImmutableList.of(\"blob\"), options.buildRequestHeaders().get(\n               \"x-ms-blob-public-access\"));\n   }\n\n   public void testPublicAccessStatic() {\n      CreateContainerOptions options = CreateContainerOptions.Builder.withPublicAccess(PublicAccess.BLOB);\n      assertEquals(ImmutableList.of(\"blob\"), options.buildRequestHeaders().get(\n               \"x-ms-blob-public-access\"));\n   }\n\n   public void testMetadata() {\n      CreateContainerOptions options = new CreateContainerOptions().withMetadata(ImmutableMultimap\n               .of(\"test\", \"foo\"));\n      assertEquals(ImmutableList.of(\"foo\"), options.buildRequestHeaders().get(\n               AzureStorageHeaders.USER_METADATA_PREFIX + \"test\"));\n   }\n\n   public void testMetadataAlreadyPrefixed() {\n      CreateContainerOptions options = new CreateContainerOptions().withMetadata(ImmutableMultimap\n               .of(AzureStorageHeaders.USER_METADATA_PREFIX + \"test\", \"foo\"));\n      assertEquals(ImmutableList.of(\"foo\"), options.buildRequestHeaders().get(\n               AzureStorageHeaders.USER_METADATA_PREFIX + \"test\"));\n   }\n\n   public void testMetadataStatic() {\n      CreateContainerOptions options = CreateContainerOptions.Builder\n               .withMetadata(ImmutableMultimap.of(\"test\", \"foo\"));\n      assertEquals(ImmutableList.of(\"foo\"), options.buildRequestHeaders().get(\n               AzureStorageHeaders.USER_METADATA_PREFIX + \"test\"));\n   }\n\n}\n"
  },
  {
    "path": "providers/azureblob/src/test/java/org/jclouds/azureblob/options/ListBlobsOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.options;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tests behavior of {@code ListBlobsOptions}\n */\n@Test(groups = \"unit\")\npublic class ListBlobsOptionsTest {\n\n   public void testDelimiter() {\n      ListBlobsOptions options = new ListBlobsOptions().delimiter(\"/\");\n      assertEquals(ImmutableList.of(\"/\"), options.buildQueryParameters().get(\"delimiter\"));\n   }\n\n   public void testDelimiterStatic() {\n      ListBlobsOptions options = ListBlobsOptions.Builder.delimiter(\"/\");\n      assertEquals(ImmutableList.of(\"/\"), options.buildQueryParameters().get(\"delimiter\"));\n   }\n\n}\n"
  },
  {
    "path": "providers/azureblob/src/test/java/org/jclouds/azureblob/predicates/validators/ContainerNameValidatorTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.predicates.validators;\n\nimport org.testng.annotations.Test;\n\npublic class ContainerNameValidatorTest {\n\n    @Test\n    public void testNamesValidity() {\n        ContainerNameValidator validator = new ContainerNameValidator();\n\n        validator.validate(\"adasd\");\n\n        validator.validate(\"adasd-ab\");\n\n        validator.validate(\"zzz\");\n        validator.validate(\"abcefghjlkmnop\");\n\n    }\n\n    @Test\n    public void testInvalidNames() {\n\n        ContainerNameValidator validator = new ContainerNameValidator();\n\n        try {\n            //double dash - should fail\n            validator.validate(\"adasd-ab--baba\");\n            throw new RuntimeException(\"to be converted to TestException later\");\n        } catch (IllegalArgumentException e) {\n            // supposed to happen - continue\n        }\n\n        try {\n            // dots - should fail\n            validator.validate(\"abc.zz.la\");\n            throw new RuntimeException(\"to be converted to TestException later\");\n        } catch (IllegalArgumentException e) {\n            // supposed to happen - continue\n        }\n\n        try {\n            // uppercase - should fail\n            validator.validate(\"abcZZla\");\n            throw new RuntimeException(\"to be converted to TestException later\");\n        } catch (IllegalArgumentException e) {\n            // supposed to happen - continue\n        }\n\n        try {\n            validator.validate(\"zz\");\n            throw new RuntimeException(\"to be converted to TestException later\");\n        } catch (IllegalArgumentException e) {\n            // supposed to happen - continue\n        }\n\n        try {\n            // non-ASCII - should fail\n            validator.validate(\"a????\");\n            throw new RuntimeException(\"to be converted to TestException later\");\n        } catch (IllegalArgumentException e) {\n            // supposed to happen - continue\n        }\n\n        try {\n            // starts with dash - should fail\n            validator.validate(\"-adasd\");\n            throw new RuntimeException(\"to be converted to TestException later\");\n        } catch (IllegalArgumentException e) {\n            // supposed to happen - continue\n        }\n\n        try {\n            // ends with dash - should fail\n            validator.validate(\"adasd-\");\n            throw new RuntimeException(\"to be converted to TestException later\");\n        } catch (IllegalArgumentException e) {\n            // supposed to happen - continue\n        }\n\n    }\n\n}\n"
  },
  {
    "path": "providers/azureblob/src/test/java/org/jclouds/azureblob/xml/AccountNameEnumerationResultsHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.xml;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\nimport java.net.URI;\nimport java.util.SortedSet;\n\nimport org.jclouds.azure.storage.domain.BoundedSet;\nimport org.jclouds.azure.storage.domain.internal.BoundedHashSet;\nimport org.jclouds.azureblob.domain.ContainerProperties;\nimport org.jclouds.azureblob.domain.PublicAccess;\nimport org.jclouds.azureblob.domain.internal.ContainerPropertiesImpl;\nimport org.jclouds.date.DateService;\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Maps;\nimport com.google.common.collect.Sets;\n\n/**\n * Tests behavior of {@code AccountNameEnumerationResultsHandler}\n */\n//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"blob.AccountNameEnumerationResultsHandlerTest\")\npublic class AccountNameEnumerationResultsHandlerTest extends BaseHandlerTest {\n\n   private DateService dateService;\n\n   @BeforeTest\n   @Override\n   protected void setUpInjector() {\n      super.setUpInjector();\n      dateService = injector.getInstance(DateService.class);\n      assert dateService != null;\n   }\n\n   public void testApplyInputStream() {\n      InputStream is = getClass().getResourceAsStream(\"/test_list_containers.xml\");\n      SortedSet<ContainerProperties> contents = Sets.newTreeSet();\n      contents.add(new ContainerPropertiesImpl(URI\n               .create(\"http://myaccount.blob.core.windows.net/audio\"), dateService\n               .rfc822DateParse(\"Wed, 13 Aug 2008 20:39:39 GMT\"), \"0x8CACB9BD7C6B1B2\", Maps\n               .<String, String> newHashMap(), PublicAccess.CONTAINER));\n      contents.add(new ContainerPropertiesImpl(URI\n               .create(\"http://myaccount.blob.core.windows.net/images\"), dateService\n               .rfc822DateParse(\"Wed, 14 Aug 2008 20:39:39 GMT\"), \"0x8CACB9BD7C1EEEC\", Maps\n               .<String, String> newHashMap(), PublicAccess.BLOB));\n      contents.add(new ContainerPropertiesImpl(URI\n               .create(\"http://myaccount.blob.core.windows.net/textfiles\"), dateService\n               .rfc822DateParse(\"Wed, 15 Aug 2008 20:39:39 GMT\"), \"0x8CACB9BD7BACAC3\", Maps\n               .<String, String> newHashMap(), PublicAccess.PRIVATE));\n      BoundedSet<ContainerProperties> list = new BoundedHashSet<ContainerProperties>(contents, URI\n               .create(\"http://myaccount.blob.core.windows.net/\"), null, null, 3, \"video\");\n\n      BoundedSet<ContainerProperties> result = factory.create(\n               injector.getInstance(AccountNameEnumerationResultsHandler.class)).parse(is);\n\n      assertEquals(result, list);\n   }\n\n   public void testApplyInputStreamWithOptions() {\n      SortedSet<ContainerProperties> contents = Sets.newTreeSet();\n      contents.add(new ContainerPropertiesImpl(URI\n               .create(\"http://myaccount.blob.core.windows.net/audio\"), dateService\n               .rfc822DateParse(\"Wed, 13 Aug 2008 20:39:39 GMT\"), \"0x8CACB9BD7C6B1B2\", Maps\n               .<String, String> newHashMap(), PublicAccess.CONTAINER));\n      contents.add(new ContainerPropertiesImpl(URI\n               .create(\"http://myaccount.blob.core.windows.net/images\"), dateService\n               .rfc822DateParse(\"Wed, 14 Aug 2008 20:39:39 GMT\"), \"0x8CACB9BD7C1EEEC\", Maps\n               .<String, String> newHashMap(), PublicAccess.BLOB));\n      contents.add(new ContainerPropertiesImpl(URI\n               .create(\"http://myaccount.blob.core.windows.net/textfiles\"), dateService\n               .rfc822DateParse(\"Wed, 15 Aug 2008 20:39:39 GMT\"), \"0x8CACB9BD7BACAC3\", Maps\n               .<String, String> newHashMap(), PublicAccess.PRIVATE));\n      InputStream is = getClass().getResourceAsStream(\"/test_list_containers_options.xml\");\n      BoundedSet<ContainerProperties> list = new BoundedHashSet<ContainerProperties>(contents, URI\n               .create(\"http://myaccount.blob.core.windows.net\"), \"prefix\", \"marker\", 1, \"video\");\n      BoundedSet<ContainerProperties> result = factory.create(\n               injector.getInstance(AccountNameEnumerationResultsHandler.class)).parse(is);\n      assertEquals(result, list);\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/test/java/org/jclouds/azureblob/xml/BlobBlocksResultsHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.xml;\n\nimport org.jclouds.azureblob.domain.BlobBlockProperties;\nimport org.jclouds.azureblob.domain.ListBlobBlocksResponse;\nimport org.jclouds.azureblob.domain.internal.BlobBlockPropertiesImpl;\nimport org.jclouds.azureblob.domain.internal.ListBlobBlocksResponseImpl;\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\nimport java.util.List;\n\nimport com.google.common.collect.Lists;\n\n/**\n * Test XML Parsing of the Blob Block List\n */\n@Test(groups = \"unit\", testName = \"BlobBlocksResultsHandlerTest\")\npublic class BlobBlocksResultsHandlerTest extends BaseHandlerTest {\n\n   @BeforeTest\n   @Override\n   protected void setUpInjector() {\n      super.setUpInjector();\n   }\n\n   public void testGetResult() throws Exception {\n      InputStream is = getClass().getResourceAsStream(\"/test_list_blob_blocks.xml\");\n\n      List<BlobBlockProperties> blocks = Lists.newLinkedList();\n      blocks.add(new BlobBlockPropertiesImpl(\"blockIdA\", 1234, true));\n      blocks.add(new BlobBlockPropertiesImpl(\"blockIdB\", 4321, true));\n      blocks.add(new BlobBlockPropertiesImpl(\"blockIdC\", 5678, false));\n      blocks.add(new BlobBlockPropertiesImpl(\"blockIdD\", 8765, false));\n      ListBlobBlocksResponse expected = new ListBlobBlocksResponseImpl(blocks);\n\n      ListBlobBlocksResponse result = factory.create(\n            injector.getInstance(BlobBlocksResultsHandler.class)).parse(is);\n\n      assertEquals(expected, result);\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/test/java/org/jclouds/azureblob/xml/ContainerNameEnumerationResultsHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azureblob.xml;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\nimport java.net.URI;\nimport java.util.Set;\n\nimport org.jclouds.azureblob.domain.AccessTier;\nimport org.jclouds.azureblob.domain.BlobProperties;\nimport org.jclouds.azureblob.domain.BlobType;\nimport org.jclouds.azureblob.domain.LeaseStatus;\nimport org.jclouds.azureblob.domain.ListBlobsResponse;\nimport org.jclouds.azureblob.domain.internal.BlobPropertiesImpl;\nimport org.jclouds.azureblob.domain.internal.HashSetListBlobsResponse;\nimport org.jclouds.date.DateService;\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Sets;\n\n/**\n * Tests behavior of {@code ContainerNameEnumerationResultsHandler}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"ContainerNameEnumerationResultsHandlerTest\")\npublic class ContainerNameEnumerationResultsHandlerTest extends BaseHandlerTest {\n   private DateService dateService;\n\n   @BeforeTest\n   @Override\n   protected void setUpInjector() {\n      super.setUpInjector();\n      dateService = injector.getInstance(DateService.class);\n      assert dateService != null;\n   }\n\n   public void testApplyInputStream() {\n      InputStream is = getClass().getResourceAsStream(\"/test_list_blobs.xml\");\n      Set<BlobProperties> contents = ImmutableSet.<BlobProperties> of(\n            new BlobPropertiesImpl(BlobType.BLOCK_BLOB, AccessTier.HOT, \"blob1.txt\", \"mycontainer\", URI\n                  .create(\"http://myaccount.blob.core.windows.net/mycontainer/blob1.txt\"), dateService\n                  .rfc822DateParse(\"Thu, 18 Sep 2008 18:41:57 GMT\"), \"0x8CAE7D55D050B8B\", 8,\n                  \"text/plain; charset=UTF-8\", null, null, null, null, LeaseStatus.UNLOCKED, ImmutableMap\n                        .<String, String> of()),\n            new BlobPropertiesImpl(BlobType.BLOCK_BLOB, AccessTier.COOL, \"blob2.txt\", \"mycontainer\", URI\n                  .create(\"http://myaccount.blob.core.windows.net/mycontainer/blob2.txt\"), dateService\n                  .rfc822DateParse(\"Thu, 18 Sep 2008 18:41:57 GMT\"), \"0x8CAE7D55CF6C339\", 14,\n                  \"text/plain; charset=UTF-8\", null, null, null, null, LeaseStatus.UNLOCKED, ImmutableMap\n                        .<String, String> of()),\n            new BlobPropertiesImpl(BlobType.PAGE_BLOB, AccessTier.ARCHIVE, \"newblob1.txt\", \"mycontainer\", URI\n                  .create(\"http://myaccount.blob.core.windows.net/mycontainer/newblob1.txt\"), dateService\n                  .rfc822DateParse(\"Thu, 18 Sep 2008 18:41:57 GMT\"), \"0x8CAE7D55CF6C339\", 25,\n                  \"text/plain; charset=UTF-8\", null, null, null, null, LeaseStatus.UNLOCKED, ImmutableMap\n                        .<String, String> of()));\n\n      ListBlobsResponse list = new HashSetListBlobsResponse(contents,\n            URI.create(\"http://myaccount.blob.core.windows.net/mycontainer\"), \"myfolder/\", null, 4, \"newblob2.txt\",\n            null, ImmutableSet.<String> of(\"myfolder/\"));\n\n      ListBlobsResponse result = factory.create(\n            injector.getInstance(ContainerNameEnumerationResultsHandler.class)).parse(is);\n\n      assertEquals(result, list);\n   }\n\n   public void testOptions() {\n      InputStream is = getClass().getResourceAsStream(\"/test_list_blobs_options.xml\");\n      Set<BlobProperties> contents = ImmutableSet.<BlobProperties> of(new BlobPropertiesImpl(BlobType.BLOCK_BLOB, AccessTier.HOT, \"a\",\n            \"adriancole-blobstore3\", URI.create(\"https://jclouds.blob.core.windows.net/adriancole-blobstore3/a\"),\n            dateService.rfc822DateParse(\"Sat, 30 Jan 2010 17:46:15 GMT\"), \"0x8CC6FEB41736428\", 8,\n            \"application/octet-stream\", null, null, null, null, LeaseStatus.UNLOCKED, ImmutableMap.<String, String> of()));\n\n      ListBlobsResponse list = new HashSetListBlobsResponse(contents,\n            URI.create(\"https://jclouds.blob.core.windows.net/adriancole-blobstore3\"),\n\n            null, null, 1, \"2!68!MDAwMDA2IWFwcGxlcyEwMDAwMjghOTk5OS0xMi0zMVQyMzo1OTo1OS45OTk5OTk5WiE-\", \"/\",\n            Sets.<String> newTreeSet());\n\n      ListBlobsResponse result = factory.create(\n            injector.getInstance(ContainerNameEnumerationResultsHandler.class)).parse(is);\n\n      assertEquals(result, list);\n   }\n}\n"
  },
  {
    "path": "providers/azureblob/src/test/resources/log4j.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE log4j:configuration SYSTEM \"log4j.dtd\">\n\n    <!--\n        For more configuration infromation and examples see the Apache\n        Log4j website: http://logging.apache.org/log4j/\n    -->\n<log4j:configuration xmlns:log4j=\"http://jakarta.apache.org/log4j/\"\n    debug=\"false\">\n\n    <!-- A time/date based rolling appender -->\n    <appender name=\"WIREFILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds-wire.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n\n    <!-- A time/date based rolling appender -->\n    <appender name=\"FILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n\n    <appender name=\"ASYNC\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"FILE\" />\n    </appender>\n\n    <appender name=\"ASYNCWIRE\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"WIREFILE\" />\n    </appender>\n\n    <!-- A time/date based rolling appender -->\n    <appender name=\"BLOBSTOREFILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds-blobstore.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n\n    <appender name=\"ASYNCBLOBSTORE\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"BLOBSTOREFILE\" />\n    </appender>\n    <!-- ================ -->\n    <!-- Limit categories -->\n    <!-- ================ -->\n    <category name=\"jclouds.blobstore\">\n        <priority value=\"TRACE\" />\n        <appender-ref ref=\"ASYNCBLOBSTORE\" />\n    </category>\n\n    <category name=\"org.jclouds\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNC\" />\n    </category>\n\n    <category name=\"jclouds.headers\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNCWIRE\" />\n    </category>\n\n    <category name=\"jclouds.wire\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNCWIRE\" />\n    </category>\n    <!-- ======================= -->\n    <!-- Setup the Root category -->\n    <!-- ======================= -->\n\n    <root>\n        <priority value=\"WARN\" />\n    </root>\n\n</log4j:configuration>\n"
  },
  {
    "path": "providers/azureblob/src/test/resources/test_error.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Error>\n\t<Code>AuthenticationFailed</Code>\n\t<Message>Server failed to authenticate the request. Make sure the value\n\t\tof Authorization header is formed correctly including the signature.\n\t\tRequestId:7859e884-e8b9-4ed0-aa62-ac6963b91bf6\n\t\tTime:2009-09-02T23:32:36.7507749Z</Message>\n\t<AuthenticationErrorDetail>The MAC signature found in the HTTP request\n\t\t'XEv0NqP+zePZxlrHmxy2F6MiyoRD8LIJt1f/Swgzn1U=' is not the same as any\n\t\tcomputed signature. Server used following string to sign: 'GET\n\n\n\t\tWed, 02 Sep 2009 23:32:34 GMT\n\t\t/jclouds/?comp=list'.</AuthenticationErrorDetail>\n</Error>\n"
  },
  {
    "path": "providers/azureblob/src/test/resources/test_list_blob_blocks.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<BlockList>\n    <CommittedBlocks>\n        <Block>\n            <Name>blockIdA</Name>\n            <Size>1234</Size>\n        </Block>\n        <Block>\n            <Name>blockIdB</Name>\n            <Size>4321</Size>\n        </Block>\n    </CommittedBlocks>\n    <UncommittedBlocks>\n        <Block>\n            <Name>blockIdC</Name>\n            <Size>5678</Size>\n        </Block>\n        <Block>\n            <Name>blockIdD</Name>\n            <Size>8765</Size>\n        </Block>\n    </UncommittedBlocks>\n</BlockList>"
  },
  {
    "path": "providers/azureblob/src/test/resources/test_list_blobs.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<EnumerationResults\n    ServiceEndpoint=\"http://myaccount.blob.core.windows.net/\"\n    ContainerName=\"mycontainer\">\n    <MaxResults>4</MaxResults>\n    <Blobs>\n        <Blob>\n            <Name>blob1.txt</Name>\n            <Url>http://myaccount.blob.core.windows.net/mycontainer/blob1.txt\n            </Url>\n            <Last-Modified>Thu, 18 Sep 2008 18:41:57 GMT</Last-Modified>\n            <Etag>0x8CAE7D55D050B8B</Etag>\n            <Content-Length>8</Content-Length>\n            <Content-Type>text/plain; charset=UTF-8</Content-Type>\n            <BlobType>BlockBlob</BlobType>\n            <AccessTier>Hot</AccessTier>\n            <LeaseStatus>unlocked</LeaseStatus>\n            <Content-Encoding />\n            <Content-Language />\n        </Blob>\n        <Blob>\n            <Name>blob2.txt</Name>\n            <Url>http://myaccount.blob.core.windows.net/mycontainer/blob2.txt\n            </Url>\n            <Last-Modified>Thu, 18 Sep 2008 18:41:57 GMT</Last-Modified>\n            <Etag>0x8CAE7D55CF6C339</Etag>\n            <Content-Length>14</Content-Length>\n            <Content-Type>text/plain; charset=UTF-8</Content-Type>\n            <BlobType>BlockBlob</BlobType>\n            <AccessTier>Cool</AccessTier>\n            <LeaseStatus>unlocked</LeaseStatus>\n            <Content-Encoding />\n            <Content-Language />\n        </Blob>\n        <BlobPrefix>\n            <Name>myfolder/</Name>\n        </BlobPrefix>\n        <Blob>\n            <Name>newblob1.txt</Name>\n            <Url>http://myaccount.blob.core.windows.net/mycontainer/newblob1.txt\n            </Url>\n            <Last-Modified>Thu, 18 Sep 2008 18:41:57 GMT</Last-Modified>\n            <Etag>0x8CAE7D55CF6C339</Etag>\n            <Content-Length>25</Content-Length>\n            <Content-Type>text/plain; charset=UTF-8</Content-Type>\n            <BlobType>PageBlob</BlobType>\n            <AccessTier>Archive</AccessTier>\n            <LeaseStatus>unlocked</LeaseStatus>\n            <Content-Encoding />\n            <Content-Language />\n        </Blob>\n    </Blobs>\n    <NextMarker>newblob2.txt</NextMarker>\n</EnumerationResults>\n"
  },
  {
    "path": "providers/azureblob/src/test/resources/test_list_blobs_options.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<EnumerationResults\n    ServiceEndpoint=\"https://jclouds.blob.core.windows.net/\"\n    ContainerName=\"adriancole-blobstore3\">\n    <MaxResults>1</MaxResults>\n    <Delimiter>/</Delimiter>\n    <Blobs>\n        <Blob>\n            <Name>a</Name>\n            <Url>https://jclouds.blob.core.windows.net/adriancole-blobstore3/a</Url>\n            <Properties>\n                <Last-Modified>Sat, 30 Jan 2010 17:46:15 GMT</Last-Modified>\n                <Etag>0x8CC6FEB41736428</Etag>\n                <Content-Length>8</Content-Length>\n                <Content-Type>application/octet-stream</Content-Type>\n                <Content-Encoding />\n                <Content-Language />\n                <Content-MD5 />\n                <Cache-Control />\n                <BlobType>BlockBlob</BlobType>\n                <AccessTier>Hot</AccessTier>\n                <LeaseStatus>unlocked</LeaseStatus>\n            </Properties>\n            <Metadata />\n        </Blob>\n    </Blobs>\n    <NextMarker>2!68!MDAwMDA2IWFwcGxlcyEwMDAwMjghOTk5OS0xMi0zMVQyMzo1OTo1OS45OTk5OTk5WiE-</NextMarker>\n</EnumerationResults>\n"
  },
  {
    "path": "providers/azureblob/src/test/resources/test_list_containers.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<EnumerationResults ServiceEndpoint=\"http://myaccount.blob.core.windows.net\">\n  <MaxResults>3</MaxResults>\n  <Containers>\n    <Container>\n      <Name>audio</Name>\n      <Last-Modified>Wed, 13 Aug 2008 20:39:39 GMT</Last-Modified>\n      <Etag>0x8CACB9BD7C6B1B2</Etag>\n      <PublicAccess>container</PublicAccess>\n    </Container>\n    <Container>\n      <Name>images</Name>\n      <Last-Modified>Wed, 14 Aug 2008 20:39:39 GMT</Last-Modified>\n      <Etag>0x8CACB9BD7C1EEEC</Etag>\n      <PublicAccess>blob</PublicAccess>\n    </Container>\n    <Container>\n      <Name>textfiles</Name>\n      <Last-Modified>Wed, 15 Aug 2008 20:39:39 GMT</Last-Modified>\n      <Etag>0x8CACB9BD7BACAC3</Etag>\n    </Container>\n  </Containers>\n  <NextMarker>video</NextMarker>\n</EnumerationResults>\n"
  },
  {
    "path": "providers/azureblob/src/test/resources/test_list_containers_options.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<EnumerationResults ServiceEndpoint=\"http://myaccount.blob.core.windows.net\">\n  <Prefix>prefix</Prefix>\n  <Marker>marker</Marker>\n  <MaxResults>1</MaxResults>\n  <Containers>\n    <Container>\n      <Name>audio</Name>\n      <Last-Modified>Wed, 13 Aug 2008 20:39:39 GMT</Last-Modified>\n      <Etag>0x8CACB9BD7C6B1B2</Etag>\n      <PublicAccess>container</PublicAccess>\n    </Container>\n    <Container>\n      <Name>images</Name>\n      <Last-Modified>Wed, 14 Aug 2008 20:39:39 GMT</Last-Modified>\n      <Etag>0x8CACB9BD7C1EEEC</Etag>\n      <PublicAccess>blob</PublicAccess>\n    </Container>\n    <Container>\n      <Name>textfiles</Name>\n      <Last-Modified>Wed, 15 Aug 2008 20:39:39 GMT</Last-Modified>\n      <Etag>0x8CACB9BD7BACAC3</Etag>\n    </Container>\n  </Containers>\n  <NextMarker>video</NextMarker>\n</EnumerationResults>\n"
  },
  {
    "path": "providers/azurecompute-arm/README.md",
    "content": "Azure Compute ARM Provider\n==========================\n\nBuild status for azurecompute-arm module:\n[![Build Status](https://jclouds.ci.cloudbees.com/buildStatus/icon?job=jclouds/org.apache.jclouds.provider$azurecompute-arm)](https://jclouds.ci.cloudbees.com/job/jclouds/org.apache.jclouds.provider$azurecompute-arm/)\n\n## Setting Up Test Credentials\n\n### Create a Service Principal\n\nInstall and configure Azure CLI following these [steps](http://azure.microsoft.com/en-us/documentation/articles/xplat-cli/).\n\nUsing the Azure CLI, run the following commands to create a service principal\n\n```bash\n# Enter your Microsoft account credentials when prompted\naz login\n\n# Set current subscription to create a service principal\naz account set --subscription <Subscription-id>\n\n# Create an AD application with your information.\naz ad app create --display-name <name> --password <password> --homepage <home-page> --identifier-uris <identifier-uris>\n\n# For example: az ad app create --display-name \"jcloudsarm\" --password abcd --homepage \"https://jcloudsarm\" --identifier-uris \"https://jcloudsarm\"\n\n# Output will include a value for `Application Id`, which will be used for the live tests\n\n# Create a Service Principal\naz ad sp create --id <Application-id>\n\n# Output will include a value for `Object Id`, to be used in the next step \n```\n\nRun the following commands to assign roles to the service principal\n\n```bash\n# Assign roles for this service principal\naz role assignment create --role Contributor --assignee <ObjectId>\n```\n\nLook up the the tenant Id\n\n```bash\naz account show\n\n# output will be a JSON which will include the `Tenant id`\n```\n\nVerify service principal\n\n```bash\naz login -u <Application-id> -p <password> --service-principal --tenant <Tenant-id>\n```\n\n## Run Live Tests\n\nUse the following to run one live test:\n\n```bash\nmvn -Dtest=<name of the live test> \\\n    -Dtest.azurecompute-arm.identity=\"<Application-id>\" \\\n    -Dtest.azurecompute-arm.credential=\"<password>\" \\\n    -Dtest.azurecompute-arm.endpoint=\"https://management.azure.com/subscriptions/<Subscription-id>\" \\\n    -Dtest.oauth.endpoint=\"https://login.microsoftonline.com/<Tenant-id>/oauth2/token\"\n    integration-test -Plive\n\n```\n\nUse the following to run all the live tests:\n\n```bash\n\nmvn clean verify -Plive \\\n    -Dtest.azurecompute-arm.identity=\"<Application-id>\"\" \\\n    -Dtest.azurecompute-arm.credential=\"<password>\"\" \\\n    -Dtest.azurecompute-arm.endpoint=\"https://management.azure.com/subscriptions/<Subscription-id>\"\" \\\n    -Dtest.oauth.endpoint=https://login.microsoftonline.com/<Tenant-id>/oauth2/token\n\n```\n\n## How to use it\n\nAzure Compute ARM provider works exactly as any other jclouds provider.\nNotice that as Azure supports dozens of locations, operations like listImages can be really time-consuming.\nTo limit the scope of such operations there are some additional properties you may want to use:\n\n```bash\njclouds.azurecompute.arm.publishers\n```\nwhich is by default `Canonical,RedHat`\n\nand\n```bash\njclouds.regions\n```\nwhich is by default `null`. If you want to target only the `north europe` region, you can use\n\n```bash\njclouds.regions=\"northeurope\"\n```\n"
  },
  {
    "path": "providers/azurecompute-arm/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.azurecompute.arm.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "providers/azurecompute-arm/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n\n  <groupId>org.apache.jclouds.provider</groupId>\n  <artifactId>azurecompute-arm</artifactId>\n  <name>jclouds Azure Compute ARM API</name>\n  <description>jclouds components to access an implementation of Azure's ARM Compute Service</description>\n\n  <properties>\n    <test.jclouds.oauth.resource>https://management.azure.com/</test.jclouds.oauth.resource>\n    <test.oauth.endpoint>https://login.microsoftonline.com/FIXME_tenant-id/oauth2/token</test.oauth.endpoint>\n    <test.azurecompute-arm.endpoint>https://management.azure.com/subscriptions/FIXME_subscription-id</test.azurecompute-arm.endpoint>\n    <test.azurecompute-arm.api-version></test.azurecompute-arm.api-version>\n    <test.azurecompute-arm.build-version />\n    <test.azurecompute-arm.identity>app id</test.azurecompute-arm.identity>\n    <test.azurecompute-arm.credential>app password</test.azurecompute-arm.credential>\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <scope>provided</scope>\n      <optional>true</optional>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.value</groupId>\n      <artifactId>auto-value</artifactId>\n      <scope>provided</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>oauth</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-okhttp</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>oauth</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-slf4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-sshj</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n     <groupId>ch.qos.logback</groupId>\n     <artifactId>logback-classic</artifactId>\n     <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.squareup.okhttp3</groupId>\n      <artifactId>mockwebserver</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.github.spotbugs</groupId>\n      <artifactId>spotbugs-annotations</artifactId>\n      <version>3.1.3</version>\n      <scope>provided</scope>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <defaultGoal>clean verify</defaultGoal>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <threadCount>1</threadCount>\n                  <systemPropertyVariables>\n                    <test.azurecompute-arm.endpoint>${test.azurecompute-arm.endpoint}</test.azurecompute-arm.endpoint>\n                    <test.azurecompute-arm.api-version>${test.azurecompute-arm.api-version}</test.azurecompute-arm.api-version>\n                    <test.azurecompute-arm.build-version>${test.azurecompute-arm.build-version}</test.azurecompute-arm.build-version>\n                    <test.azurecompute-arm.identity>${test.azurecompute-arm.identity}</test.azurecompute-arm.identity>\n                    <test.azurecompute-arm.credential>${test.azurecompute-arm.credential}</test.azurecompute-arm.credential>\n                    <test.jclouds.oauth.resource>${test.jclouds.oauth.resource}</test.jclouds.oauth.resource>\n                    <test.oauth.endpoint>${test.oauth.endpoint}</test.oauth.endpoint>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/AzureComputeApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm;\n\nimport java.io.Closeable;\nimport jakarta.ws.rs.PathParam;\n\nimport org.jclouds.azurecompute.arm.domain.ServicePrincipal;\nimport org.jclouds.azurecompute.arm.features.ActivityLogAlertApi;\nimport org.jclouds.azurecompute.arm.features.AlertApi;\nimport org.jclouds.azurecompute.arm.features.AvailabilitySetApi;\nimport org.jclouds.azurecompute.arm.features.DeploymentApi;\nimport org.jclouds.azurecompute.arm.features.DiskApi;\nimport org.jclouds.azurecompute.arm.features.GraphRBACApi;\nimport org.jclouds.azurecompute.arm.features.ImageApi;\nimport org.jclouds.azurecompute.arm.features.JobApi;\nimport org.jclouds.azurecompute.arm.features.LoadBalancerApi;\nimport org.jclouds.azurecompute.arm.features.LocalNetworkGatewayApi;\nimport org.jclouds.azurecompute.arm.features.LocationApi;\nimport org.jclouds.azurecompute.arm.features.MetricAlertApi;\nimport org.jclouds.azurecompute.arm.features.MetricDefinitionsApi;\nimport org.jclouds.azurecompute.arm.features.MetricsApi;\nimport org.jclouds.azurecompute.arm.features.NetworkInterfaceCardApi;\nimport org.jclouds.azurecompute.arm.features.NetworkSecurityGroupApi;\nimport org.jclouds.azurecompute.arm.features.NetworkSecurityRuleApi;\nimport org.jclouds.azurecompute.arm.features.OSImageApi;\nimport org.jclouds.azurecompute.arm.features.PublicIPAddressApi;\nimport org.jclouds.azurecompute.arm.features.ResourceGroupApi;\nimport org.jclouds.azurecompute.arm.features.ResourceProviderApi;\nimport org.jclouds.azurecompute.arm.features.StorageAccountApi;\nimport org.jclouds.azurecompute.arm.features.SubnetApi;\nimport org.jclouds.azurecompute.arm.features.VMSizeApi;\nimport org.jclouds.azurecompute.arm.features.VaultApi;\nimport org.jclouds.azurecompute.arm.features.VirtualMachineApi;\nimport org.jclouds.azurecompute.arm.features.VirtualMachineScaleSetApi;\nimport org.jclouds.azurecompute.arm.features.VirtualNetworkApi;\nimport org.jclouds.azurecompute.arm.features.VirtualNetworkGatewayApi;\nimport org.jclouds.azurecompute.arm.features.VirtualNetworkGatewayConnectionApi;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.rest.annotations.Delegate;\n\nimport com.google.common.base.Supplier;\nimport com.google.inject.Provides;\n\n/**\n * The Azure Resource Manager API is a REST API for managing your services and deployments.\n * <p>\n *\n * @see <a href=\"https://msdn.microsoft.com/en-us/library/azure/dn790568.aspx\" >doc</a>\n */\npublic interface AzureComputeApi extends Closeable {\n   \n   /**\n    * The Azure Resource Manager API includes operations for managing resource groups in your subscription.\n    *\n    * @see <a href=\"https://msdn.microsoft.com/en-us/library/azure/dn790546.aspx\">docs</a>\n    */\n   @Delegate\n   ResourceGroupApi getResourceGroupApi();\n\n   /**\n    * Provides access to the Job tracking API.\n    */\n   @Delegate\n   JobApi getJobApi();\n\n   /**\n    * This Azure Resource Manager API provides all of the locations that are available for resource providers\n    *\n    * @see <a href=\"https://msdn.microsoft.com/en-US/library/azure/dn790540.aspx\">docs</a>\n    */\n   @Delegate\n   LocationApi getLocationApi();\n\n   /**\n    * The Azure Resource Manager API includes operations for managing the storage accounts in your subscription.\n    *\n    * @see <https://msdn.microsoft.com/en-us/library/mt163683.aspx\">docs</a>\n    */\n   @Delegate\n   StorageAccountApi getStorageAccountApi(@PathParam(\"resourceGroup\") String resourceGroup);\n\n   /**\n    * The Subnet API includes operations for managing the subnets in your virtual network.\n    *\n    * @see <a href=\"https://msdn.microsoft.com/en-us/library/azure/mt163621.aspx\">docs</a>\n    */\n   @Delegate\n   SubnetApi getSubnetApi(@PathParam(\"resourcegroup\") String resourcegroup,\n                          @PathParam(\"virtualnetwork\") String virtualnetwork);\n\n   /**\n    * The Virtual Network API includes operations for managing the virtual networks in your subscription.\n    *\n    * @see <a href=\"https://msdn.microsoft.com/en-us/library/azure/mt163661.aspx\">docs</a>\n    */\n   @Delegate\n   VirtualNetworkApi getVirtualNetworkApi(@Nullable @PathParam(\"resourcegroup\") String resourcegroup);\n\n\n   /**\n    * The Network Interface Card API includes operations for managing the NICs in your subscription.\n    *\n    * @see <a href=\"https://msdn.microsoft.com/en-us/library/mt163668.aspx\">docs</a>\n    */\n   @Delegate\n   NetworkInterfaceCardApi getNetworkInterfaceCardApi(@Nullable @PathParam(\"resourcegroup\") String resourcegroup);\n\n   /**\n    * The Public IP Address API includes operations for managing public ID Addresses for NICs in your subscription.\n    *\n    * @see <a href=\"https://msdn.microsoft.com/en-us/library/azure/mt163638.aspx\">docs</a>\n    */\n   @Delegate\n   PublicIPAddressApi getPublicIPAddressApi(@Nullable @PathParam(\"resourcegroup\") String resourcegroup);\n\n\n   /**\n    * The Virtual Machine API includes operations for managing the virtual machines in your subscription.\n    *\n    * @see <a href=\"https://msdn.microsoft.com/en-us/library/azure/mt163630.aspx\">docs</a>\n    */\n   @Delegate\n   VirtualMachineApi getVirtualMachineApi(@Nullable @PathParam(\"resourceGroup\") String resourceGroup);\n\n   /**\n    * The Virtual Machine Scale Set API includes operations for managing the virtual machines in your subscription.\n    *\n    * @see <a href=\"https://msdn.microsoft.com/en-us/library/azure/mt163630.aspx\">docs</a>\n    */\n   @Delegate\n   VirtualMachineScaleSetApi getVirtualMachineScaleSetApi(@PathParam(\"resourceGroup\") String resourceGroup);\n\n   /**\n    * This Azure Resource Manager API lists all available virtual machine sizes for a subscription in a given region\n    *\n    * @see <a href=\"https://msdn.microsoft.com/en-us/library/azure/mt269440.aspx\">docs</a>\n    */\n   @Delegate\n   VMSizeApi getVMSizeApi(@PathParam(\"location\") String location);\n\n   /**\n    * The Azure Resource Manager API gets all the OS images in your subscription.\n    *\n    * @see <a href=\"https://docs.microsoft.com/en-us/rest/api/compute/virtualmachineimages\">docs</a>\n    */\n   @Delegate\n   OSImageApi getOSImageApi(@PathParam(\"location\") String location);\n\n   /**\n    * The Deployment API allows for the management of Azure Resource Manager resources through the use of templates.\n    *\n    * @see <a href=\"https://msdn.microsoft.com/en-us/library/azure/dn790549.aspx\">docs</a>\n    */\n   @Delegate\n   DeploymentApi getDeploymentApi(@PathParam(\"resourcegroup\") String resourceGroup);\n\n   /**\n    * The NetworkSecurityGroup API includes operations for managing network security groups within your subscription.\n    *\n    * @see <a href=\"https://msdn.microsoft.com/en-us/library/azure/mt163615.aspx\">docs</a>\n    */\n   @Delegate\n   NetworkSecurityGroupApi getNetworkSecurityGroupApi(@Nullable @PathParam(\"resourcegroup\") String resourcegroup);\n \n   /**\n    * The NetworkSecurityRule API includes operations for managing network security rules within a network security group.\n    *\n    * @see <a href=\"https://msdn.microsoft.com/en-us/library/azure/mt163580.aspx\">docs</a>\n    */\n   @Delegate\n   NetworkSecurityRuleApi getNetworkSecurityRuleApi(@PathParam(\"resourcegroup\") String resourcegroup,\n                                                    @PathParam(\"networksecuritygroup\") String networksecuritygroup);\n\n   /**\n    * The LoadBalancer API includes operations for managing load balancers\n    * within your subscription.\n    *\n    * @see <a href=\n    *      \"https://msdn.microsoft.com/en-us/library/azure/mt163574.aspx\">docs\n    *      </a>\n    */\n   @Delegate\n   LoadBalancerApi getLoadBalancerApi(@Nullable @PathParam(\"resourcegroup\") String resourcegroup);\n\n   /**\n    * The AvailabilitySet API includes operations for managing availability sets\n    * within your subscription.\n    *\n    * @see <a href=\n    *      \"https://docs.microsoft.com/en-us/rest/api/compute/availabilitysets\">docs\n    *      </a>\n    */\n   @Delegate\n   AvailabilitySetApi getAvailabilitySetApi(@PathParam(\"resourcegroup\") String resourcegroup);\n\n   /**\n    * The Azure Resource Provider API provides information about a resource provider and its supported resource types.\n    *\n    * @see <a href=\"https://msdn.microsoft.com/en-us/library/azure/dn790534.aspx\">docs</a>\n    */\n   @Delegate\n   ResourceProviderApi getResourceProviderApi();\n\n   /**\n    * The ManagedDataDisk API includes operations for managing data disks within your subscription.\n    *\n    * @see <a href=\"https://docs.microsoft.com/en-us/rest/api/manageddisks/disks/disks-rest-api\">docs</a>\n    */\n   @Delegate\n   DiskApi getDiskApi(@PathParam(\"resourcegroup\") String resourcegroup);\n\n   /**\n    * The virtual machine image API includes operations for managing data disks within your subscription.\n    *\n    * @see <a href=\"https://docs.microsoft.com/en-us/rest/api/manageddisks/images/images-rest-api\">docs</a>\n    */\n   @Delegate\n   ImageApi getVirtualMachineImageApi(@PathParam(\"resourcegroup\") String resourcegroup);\n\n   /**\n    * The metrics API includes operations to get insights into entities within your\n    * subscription.\n    *\n    * @see <a href=\"https://docs.microsoft.com/en-us/rest/api/monitor/metrics\">docs</a>\n    */\n   @Delegate\n   MetricsApi getMetricsApi(@PathParam(\"resourceid\") String resourceid);\n\n   /**\n    * The metric definitions API includes operations to get insights available for entities within your\n    * subscription.\n    *\n    * @see <a href=\"https://docs.microsoft.com/en-us/rest/api/monitor/metricdefinitions\">docs</a>\n    */\n   @Delegate\n   MetricDefinitionsApi getMetricsDefinitionsApi(@PathParam(\"resourceid\") String resourceid);\n\n   /**\n    * The Azure Active Directory Graph API provides programmatic access to Azure\n    * AD through REST API endpoints.\n    *\n    * @see <a href=\"https://docs.microsoft.com/en-us/rest/api/graphrbac/\">docs</a>\n    */\n   @Delegate\n   GraphRBACApi getGraphRBACApi();\n   \n   /**\n    * Managing your key vaults as well as the keys, secrets, and certificates within your key vaults can be \n    * accomplished through a REST interface.\n    *\n    * @see <a href=\"https://docs.microsoft.com/en-us/rest/api/keyvault/\">docs</a>\n    */\n   @Delegate\n   VaultApi getVaultApi(@PathParam(\"resourcegroup\") String resourcegroup);\n   \n   /**\n    * Management features for Local Network Gateways.\n    * \n    * @see <a href=\"https://docs.microsoft.com/en-us/rest/api/network-gateway/localnetworkgateways\">docs</a>\n    */\n   @Delegate\n   LocalNetworkGatewayApi getLocalNetworkGatewayApi(@PathParam(\"resourcegroup\") String resourcegroup);\n   \n   /**\n    * Management features for Virtual Network Gateways.\n    * \n    * @see <a href=\"https://docs.microsoft.com/en-us/rest/api/network-gateway/virtualnetworkgateways\">docs</a>\n    */\n   @Delegate\n   VirtualNetworkGatewayApi getVirtualNetworkGatewayApi(@PathParam(\"resourcegroup\") String resourcegroup);\n   \n   /**\n    * Management features for Virtual Network Gateway Connections.\n    * \n    * @see <a href=\"https://docs.microsoft.com/en-us/rest/api/network-gateway/virtualnetworkgatewayconnections\">docs</a>\n    */\n   @Delegate\n   VirtualNetworkGatewayConnectionApi getVirtualNetworkGatewayConnectionApi(@PathParam(\"resourcegroup\") String resourcegroup);\n   \n   /**\n    * Returns the information about the current service principal.\n    */\n   @Provides\n   Supplier<ServicePrincipal> getServicePrincipal();\n   \n\t/**\n\t * The Activity Log Alert API includes operations to get insights available for\n\t * entities within your subscription\n\t *\n\t * @see <a href=\n\t *      \"https://docs.microsoft.com/en-us/rest/api/monitor/activity-log-alerts\">docs</a>\n\t */\n\t@Delegate\n\tActivityLogAlertApi getActivityLogAlertApi(@PathParam(\"resourcegroup\") String resourcegroup);\n\t\n\t/**\n\t * Management features for Alerts.\n\t *\n\t * @see <a href=\n\t *      \"https://docs.microsoft.com/en-us/rest/api/monitor/alertsmanagement/alerts\">docs</a>\n\t */\n\t@Delegate\n\tAlertApi getAlertApi(@PathParam(\"resourceid\") String resourceid);\n\t\n\t/**\n\t * The Metric Alert API includes operations to get insights available for\n\t * entities within your subscription\n\t *\n\t * @see <a href=\n\t *      \"https://docs.microsoft.com/en-us/rest/api/monitor/metric-alerts\">docs</a>\n\t */\n\t@Delegate\n\tMetricAlertApi getMetricAlertApi(@PathParam(\"resourcegroup\") String resourcegroup);\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/AzureComputeProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm;\n\nimport static org.jclouds.Constants.PROPERTY_MAX_RATE_LIMIT_WAIT;\nimport static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL;\nimport static org.jclouds.azurecompute.arm.config.AzureComputeProperties.API_VERSION_PREFIX;\nimport static org.jclouds.azurecompute.arm.config.AzureComputeProperties.DEFAULT_SUBNET_ADDRESS_PREFIX;\nimport static org.jclouds.azurecompute.arm.config.AzureComputeProperties.DEFAULT_VNET_ADDRESS_SPACE_PREFIX;\nimport static org.jclouds.azurecompute.arm.config.AzureComputeProperties.IMAGE_PUBLISHERS;\nimport static org.jclouds.azurecompute.arm.config.AzureComputeProperties.OPERATION_TIMEOUT;\nimport static org.jclouds.compute.config.ComputeServiceProperties.IMAGE_AUTHENTICATE_SUDO;\nimport static org.jclouds.compute.config.ComputeServiceProperties.IMAGE_LOGIN_USER;\nimport static org.jclouds.compute.config.ComputeServiceProperties.POLL_INITIAL_PERIOD;\nimport static org.jclouds.compute.config.ComputeServiceProperties.POLL_MAX_PERIOD;\nimport static org.jclouds.compute.config.ComputeServiceProperties.RESOURCENAME_DELIMITER;\nimport static org.jclouds.compute.config.ComputeServiceProperties.RESOURCENAME_PREFIX;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TEMPLATE;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_TERMINATED;\nimport static org.jclouds.oauth.v2.config.CredentialType.CLIENT_CREDENTIALS_SECRET;\nimport static org.jclouds.oauth.v2.config.OAuthProperties.CREDENTIAL_TYPE;\nimport static org.jclouds.oauth.v2.config.OAuthProperties.RESOURCE;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.azurecompute.arm.domain.Region;\nimport org.jclouds.azurecompute.arm.features.ActivityLogAlertApi;\nimport org.jclouds.azurecompute.arm.features.AlertApi;\nimport org.jclouds.azurecompute.arm.features.AvailabilitySetApi;\nimport org.jclouds.azurecompute.arm.features.DeploymentApi;\nimport org.jclouds.azurecompute.arm.features.DiskApi;\nimport org.jclouds.azurecompute.arm.features.GraphRBACApi;\nimport org.jclouds.azurecompute.arm.features.ImageApi;\nimport org.jclouds.azurecompute.arm.features.LoadBalancerApi;\nimport org.jclouds.azurecompute.arm.features.LocalNetworkGatewayApi;\nimport org.jclouds.azurecompute.arm.features.LocationApi;\nimport org.jclouds.azurecompute.arm.features.MetricAlertApi;\nimport org.jclouds.azurecompute.arm.features.MetricDefinitionsApi;\nimport org.jclouds.azurecompute.arm.features.MetricsApi;\nimport org.jclouds.azurecompute.arm.features.NetworkInterfaceCardApi;\nimport org.jclouds.azurecompute.arm.features.NetworkSecurityGroupApi;\nimport org.jclouds.azurecompute.arm.features.NetworkSecurityRuleApi;\nimport org.jclouds.azurecompute.arm.features.OSImageApi;\nimport org.jclouds.azurecompute.arm.features.PublicIPAddressApi;\nimport org.jclouds.azurecompute.arm.features.ResourceGroupApi;\nimport org.jclouds.azurecompute.arm.features.ResourceProviderApi;\nimport org.jclouds.azurecompute.arm.features.StorageAccountApi;\nimport org.jclouds.azurecompute.arm.features.SubnetApi;\nimport org.jclouds.azurecompute.arm.features.VMSizeApi;\nimport org.jclouds.azurecompute.arm.features.VaultApi;\nimport org.jclouds.azurecompute.arm.features.VirtualMachineApi;\nimport org.jclouds.azurecompute.arm.features.VirtualMachineScaleSetApi;\nimport org.jclouds.azurecompute.arm.features.VirtualNetworkApi;\nimport org.jclouds.azurecompute.arm.features.VirtualNetworkGatewayApi;\nimport org.jclouds.azurecompute.arm.features.VirtualNetworkGatewayConnectionApi;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\n\nimport com.google.auto.service.AutoService;\n\n@AutoService(ProviderMetadata.class)\npublic class AzureComputeProviderMetadata extends BaseProviderMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromProviderMetadata(this);\n   }\n\n   public AzureComputeProviderMetadata() {\n      super(builder());\n   }\n\n   public static Properties defaultProperties() {\n      final Properties properties = AzureManagementApiMetadata.defaultProperties();\n      properties.put(POLL_INITIAL_PERIOD, 1000);\n      properties.put(POLL_MAX_PERIOD, 15000);\n      properties.put(OPERATION_TIMEOUT, 46000000);\n      properties.put(TIMEOUT_NODE_TERMINATED, 60 * 10 * 1000);\n      // Default max wait in rate limit: 5m30s\n      properties.put(PROPERTY_MAX_RATE_LIMIT_WAIT, 330000);\n      properties.put(PROPERTY_SESSION_INTERVAL, 300);\n      properties.put(RESOURCE, \"https://management.azure.com/\");\n      properties.put(CREDENTIAL_TYPE, CLIENT_CREDENTIALS_SECRET.toString());\n      // Set a default Oauth endpoint for Azure, fill in the tenantId based on the value supplied\n      properties.put(\"oauth.endpoint\", \"https://login.microsoft.com/${azurecompute-arm.tenantId}/oauth2/token\");\n      properties.put(DEFAULT_VNET_ADDRESS_SPACE_PREFIX, \"10.0.0.0/16\");\n      properties.put(DEFAULT_SUBNET_ADDRESS_PREFIX, \"10.0.0.0/24\");\n      properties.put(RESOURCENAME_PREFIX, \"jclouds\");\n      properties.put(RESOURCENAME_DELIMITER, \"-\");\n      properties.put(IMAGE_PUBLISHERS, \"Canonical,RedHat\");\n      // Default credentials for all images, Azure doesn't accept root, admin; generate the password on the fly\n      properties.put(IMAGE_LOGIN_USER, \"jclouds\");\n      // Azure allows for passwordless sudo only when using a public key to login to the machine\n      properties.put(IMAGE_AUTHENTICATE_SUDO, \"true\");\n      properties.put(TEMPLATE, \"imageNameMatches=UbuntuServer,osVersionMatches=1[456]\\\\.[01][04](\\\\.[0-9])?-LTS\");\n      // Api versions used in each API\n      properties.put(API_VERSION_PREFIX + DeploymentApi.class.getSimpleName(), \"2016-02-01\");\n      properties.put(API_VERSION_PREFIX + LocationApi.class.getSimpleName(), \"2015-11-01\");\n      properties.put(API_VERSION_PREFIX + NetworkInterfaceCardApi.class.getSimpleName(), \"2017-03-01\");\n      properties.put(API_VERSION_PREFIX + NetworkSecurityGroupApi.class.getSimpleName(), \"2016-03-30\");\n      properties.put(API_VERSION_PREFIX + NetworkSecurityRuleApi.class.getSimpleName(), \"2016-03-30\");\n      properties.put(API_VERSION_PREFIX + OSImageApi.class.getSimpleName(), \"2015-06-15\");\n      properties.put(API_VERSION_PREFIX + PublicIPAddressApi.class.getSimpleName(), \"2018-08-01\");\n      properties.put(API_VERSION_PREFIX + ResourceGroupApi.class.getSimpleName(), \"2015-01-01\");\n      properties.put(API_VERSION_PREFIX + ResourceProviderApi.class.getSimpleName(), \"2015-01-01\");\n      properties.put(API_VERSION_PREFIX + StorageAccountApi.class.getSimpleName(), \"2015-06-15\");\n      properties.put(API_VERSION_PREFIX + SubnetApi.class.getSimpleName(), \"2017-03-01\");\n      properties.put(API_VERSION_PREFIX + VirtualNetworkApi.class.getSimpleName(), \"2015-06-15\");\n      properties.put(API_VERSION_PREFIX + VMSizeApi.class.getSimpleName(), \"2015-06-15\");\n      properties.put(API_VERSION_PREFIX + VirtualMachineApi.class.getSimpleName(), \"2018-06-01\");\n      properties.put(API_VERSION_PREFIX + LoadBalancerApi.class.getSimpleName(), \"2018-08-01\");\n      properties.put(API_VERSION_PREFIX + AvailabilitySetApi.class.getSimpleName(), \"2016-04-30-preview\");\n      properties.put(API_VERSION_PREFIX + DiskApi.class.getSimpleName(), \"2017-03-30\");\n      properties.put(API_VERSION_PREFIX + ImageApi.class.getSimpleName(), \"2016-04-30-preview\");\n      properties.put(API_VERSION_PREFIX + MetricDefinitionsApi.class.getSimpleName(), \"2017-05-01-preview\");\n      properties.put(API_VERSION_PREFIX + MetricsApi.class.getSimpleName(), \"2016-09-01\");\n      properties.put(API_VERSION_PREFIX + VirtualMachineScaleSetApi.class.getSimpleName(), \"2017-03-30\");\n      properties.put(API_VERSION_PREFIX + GraphRBACApi.class.getSimpleName(), \"1.6\");\n      properties.put(API_VERSION_PREFIX + VaultApi.class.getSimpleName(), \"2016-10-01\");\n      properties.put(API_VERSION_PREFIX + LocalNetworkGatewayApi.class.getSimpleName(), \"2018-02-01\");\n      properties.put(API_VERSION_PREFIX + VirtualNetworkGatewayApi.class.getSimpleName(), \"2018-02-01\");\n      properties.put(API_VERSION_PREFIX + VirtualNetworkGatewayConnectionApi.class.getSimpleName(), \"2018-02-01\");\n      properties.put(API_VERSION_PREFIX + ActivityLogAlertApi.class.getSimpleName(), \"2020-10-01\");\n      properties.put(API_VERSION_PREFIX + AlertApi.class.getSimpleName(), \"2019-03-01\");\n      properties.put(API_VERSION_PREFIX + MetricAlertApi.class.getSimpleName(), \"2018-03-01\");\n      \n      return properties;\n   }\n\n   public AzureComputeProviderMetadata(final Builder builder) {\n      super(builder);\n   }\n\n   public static class Builder extends BaseProviderMetadata.Builder {\n\n      protected Builder() {\n         super();\n         id(\"azurecompute-arm\")\n                 .name(\"Azure Resource Management\")\n                 .apiMetadata(new AzureManagementApiMetadata())\n                 .endpoint(\"https://management.azure.com/subscriptions/${azurecompute-arm.subscriptionId}\")\n                 .homepage(URI.create(\"https://www.windowsazure.com/\"))\n                 .console(URI.create(\"https://windows.azure.com/default.aspx\"))\n                 .linkedServices(\"azureblob\")\n                 .iso3166Codes(Region.iso3166Codes())\n                 .defaultProperties(AzureComputeProviderMetadata.defaultProperties());\n      }\n\n      @Override\n      public AzureComputeProviderMetadata build() {\n         return new AzureComputeProviderMetadata(this);\n      }\n\n      @Override\n      public Builder fromProviderMetadata(final ProviderMetadata providerMetadata) {\n         super.fromProviderMetadata(providerMetadata);\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/AzureManagementApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm;\n\nimport static org.jclouds.reflect.Reflection2.typeToken;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.azurecompute.arm.compute.config.AzureComputeServiceContextModule;\nimport org.jclouds.azurecompute.arm.compute.config.AzurePredicatesModule;\nimport org.jclouds.azurecompute.arm.config.AzureComputeHttpApiModule;\nimport org.jclouds.azurecompute.arm.config.AzureComputeParserModule;\nimport org.jclouds.azurecompute.arm.config.AzureComputeRateLimitModule;\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.http.okhttp.config.OkHttpCommandExecutorServiceModule;\nimport org.jclouds.oauth.v2.config.OAuthModule;\nimport org.jclouds.rest.internal.BaseHttpApiMetadata;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n/**\n * Implementation of {@link ApiMetadata} for Microsoft Azure Resource Manager REST API\n */\npublic class AzureManagementApiMetadata extends BaseHttpApiMetadata<AzureComputeApi> {\n\n   @Override\n   public Builder toBuilder() {\n      return new Builder().fromApiMetadata(this);\n   }\n   \n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public AzureManagementApiMetadata() {\n      this(builder());\n   }\n\n   protected AzureManagementApiMetadata(final Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      final Properties properties = BaseHttpApiMetadata.defaultProperties();\n      return properties;\n   }\n\n   public static class Builder extends BaseHttpApiMetadata.Builder<AzureComputeApi, Builder> {\n\n      protected Builder() {\n         super();\n\n         id(\"azurecompute-arm\")\n                 .name(\"Microsoft Azure Resource Manager REST API\")\n                 .identityName(\"Azure Service Principal Application Id\")\n                 .credentialName(\"Azure Service Principal Application Password\")\n                 .endpointName(\"Resource Manager Endpoint ending in your Subscription Id\")\n                 .documentation(URI.create(\"https://msdn.microsoft.com/en-us/library/azure/dn790568.aspx\"))\n                 .defaultProperties(AzureManagementApiMetadata.defaultProperties())\n                 .view(typeToken(ComputeServiceContext.class))\n                 .defaultModules(ImmutableSet.<Class<? extends Module>>builder()\n                         .add(OAuthModule.class)\n                         .add(OkHttpCommandExecutorServiceModule.class)\n                         .add(AzureComputeParserModule.class)\n                         .add(AzureComputeHttpApiModule.class)\n                         .add(AzureComputeServiceContextModule.class)\n                         .add(AzurePredicatesModule.class)\n                         .add(AzureComputeRateLimitModule.class)\n                         .build());\n      }\n\n      @Override\n      public AzureManagementApiMetadata build() {\n         return new AzureManagementApiMetadata(this);\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/compute/AzureComputeService.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.compute;\n\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_RUNNING;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_SUSPENDED;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_TERMINATED;\n\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.Set;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Provider;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Constants;\nimport org.jclouds.azurecompute.arm.compute.domain.ResourceGroupAndName;\nimport org.jclouds.azurecompute.arm.compute.strategy.CleanupResources;\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.compute.callables.RunScriptOnNode;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.TemplateBuilder;\nimport org.jclouds.compute.extensions.ImageExtension;\nimport org.jclouds.compute.extensions.SecurityGroupExtension;\nimport org.jclouds.compute.extensions.internal.DelegatingImageExtension;\nimport org.jclouds.compute.internal.BaseComputeService;\nimport org.jclouds.compute.internal.PersistNodeCredentials;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.compute.strategy.CreateNodesInGroupThenAddToSet;\nimport org.jclouds.compute.strategy.DestroyNodeStrategy;\nimport org.jclouds.compute.strategy.GetImageStrategy;\nimport org.jclouds.compute.strategy.GetNodeMetadataStrategy;\nimport org.jclouds.compute.strategy.InitializeRunScriptOnNodeOrPlaceInBadMap;\nimport org.jclouds.compute.strategy.ListNodesStrategy;\nimport org.jclouds.compute.strategy.RebootNodeStrategy;\nimport org.jclouds.compute.strategy.ResumeNodeStrategy;\nimport org.jclouds.compute.strategy.SuspendNodeStrategy;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.domain.Location;\nimport org.jclouds.scriptbuilder.functions.InitAdminAccess;\n\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.util.concurrent.ListeningExecutorService;\n\n@Singleton\npublic class AzureComputeService extends BaseComputeService {\n   private final CleanupResources cleanupResources;\n\n   @Inject\n   protected AzureComputeService(ComputeServiceContext context, Map<String, Credentials> credentialStore,\n         @Memoized Supplier<Set<? extends Image>> images, @Memoized Supplier<Set<? extends Hardware>> sizes,\n         @Memoized Supplier<Set<? extends Location>> locations, ListNodesStrategy listNodesStrategy,\n         GetImageStrategy getImageStrategy, GetNodeMetadataStrategy getNodeMetadataStrategy,\n         CreateNodesInGroupThenAddToSet runNodesAndAddToSetStrategy, RebootNodeStrategy rebootNodeStrategy,\n         DestroyNodeStrategy destroyNodeStrategy, ResumeNodeStrategy startNodeStrategy,\n         SuspendNodeStrategy stopNodeStrategy, Provider<TemplateBuilder> templateBuilderProvider,\n         @Named(\"DEFAULT\") Provider<TemplateOptions> templateOptionsProvider,\n         @Named(TIMEOUT_NODE_RUNNING) Predicate<AtomicReference<NodeMetadata>> nodeRunning,\n         @Named(TIMEOUT_NODE_TERMINATED) Predicate<AtomicReference<NodeMetadata>> nodeTerminated,\n         @Named(TIMEOUT_NODE_SUSPENDED) Predicate<AtomicReference<NodeMetadata>> nodeSuspended,\n         InitializeRunScriptOnNodeOrPlaceInBadMap.Factory initScriptRunnerFactory,\n         RunScriptOnNode.Factory runScriptOnNodeFactory, InitAdminAccess initAdminAccess,\n         PersistNodeCredentials persistNodeCredentials,\n         @Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor,\n         CleanupResources cleanupResources, Optional<ImageExtension> imageExtension,\n         Optional<SecurityGroupExtension> securityGroupExtension,\n         DelegatingImageExtension.Factory delegatingImageExtension) {\n      super(context, credentialStore, images, sizes, locations, listNodesStrategy, getImageStrategy,\n            getNodeMetadataStrategy, runNodesAndAddToSetStrategy, rebootNodeStrategy, destroyNodeStrategy,\n            startNodeStrategy, stopNodeStrategy, templateBuilderProvider, templateOptionsProvider, nodeRunning,\n            nodeTerminated, nodeSuspended, initScriptRunnerFactory, initAdminAccess, runScriptOnNodeFactory,\n            persistNodeCredentials, userExecutor, imageExtension, securityGroupExtension, delegatingImageExtension);\n      this.cleanupResources = cleanupResources;\n   }\n\n   @Override\n   protected void cleanUpIncidentalResourcesOfDeadNodes(Set<? extends NodeMetadata> deadNodes) {\n      ImmutableMultimap.Builder<String, String> regionGroups = ImmutableMultimap.builder();\n      ImmutableSet.Builder<String> resourceGroups = ImmutableSet.builder();\n\n      for (NodeMetadata deadNode : deadNodes) {\n         String resourceGroupName = ResourceGroupAndName.fromSlashEncoded(deadNode.getId()).resourceGroup();\n         resourceGroups.add(resourceGroupName);\n         \n         if (deadNode.getGroup() != null) {\n            regionGroups.put(resourceGroupName, deadNode.getGroup());\n         }\n\n         try {\n            cleanupResources.cleanupNode(deadNode.getId());\n         } catch (Exception ex) {\n            logger.warn(ex, \"Error cleaning up resources for node %s\", deadNode);\n         }\n      }\n\n      for (Entry<String, String> regionGroup : regionGroups.build().entries()) {\n         cleanupResources.cleanupSecurityGroupIfOrphaned(regionGroup.getKey(), regionGroup.getValue());\n      }\n\n      for (String resourceGroup : resourceGroups.build()) {\n         cleanupResources.deleteResourceGroupIfEmpty(resourceGroup);\n      }\n   }\n   \n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/compute/AzureComputeServiceAdapter.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.compute;\n\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.common.collect.ImmutableList.builder;\nimport static com.google.common.collect.ImmutableList.of;\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static com.google.common.collect.Iterables.transform;\nimport static com.google.common.collect.Lists.newArrayList;\nimport static org.jclouds.azurecompute.arm.compute.domain.LocationAndName.fromSlashEncoded;\nimport static org.jclouds.azurecompute.arm.compute.domain.ResourceGroupAndName.fromResourceGroupAndName;\nimport static org.jclouds.azurecompute.arm.compute.functions.VMImageToImage.createMarketplacePlanIfPresent;\nimport static org.jclouds.azurecompute.arm.config.AzureComputeProperties.IMAGE_PUBLISHERS;\nimport static org.jclouds.azurecompute.arm.domain.IdReference.extractName;\nimport static org.jclouds.azurecompute.arm.domain.IdReference.extractResourceGroup;\nimport static org.jclouds.azurecompute.arm.util.VMImages.isCustom;\nimport static org.jclouds.compute.util.ComputeServiceUtils.metadataAndTagsAsCommaDelimitedValue;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.azurecompute.arm.AzureComputeApi;\nimport org.jclouds.azurecompute.arm.compute.config.AzurePredicatesModule.PublicIpAvailablePredicateFactory;\nimport org.jclouds.azurecompute.arm.compute.domain.ResourceGroupAndName;\nimport org.jclouds.azurecompute.arm.compute.functions.CustomImageToVMImage;\nimport org.jclouds.azurecompute.arm.compute.options.AzureTemplateOptions;\nimport org.jclouds.azurecompute.arm.compute.options.IpOptions;\nimport org.jclouds.azurecompute.arm.compute.strategy.CleanupResources;\nimport org.jclouds.azurecompute.arm.domain.AvailabilitySet;\nimport org.jclouds.azurecompute.arm.domain.CreationData;\nimport org.jclouds.azurecompute.arm.domain.DataDisk;\nimport org.jclouds.azurecompute.arm.domain.HardwareProfile;\nimport org.jclouds.azurecompute.arm.domain.IdReference;\nimport org.jclouds.azurecompute.arm.domain.ImageReference;\nimport org.jclouds.azurecompute.arm.domain.IpConfiguration;\nimport org.jclouds.azurecompute.arm.domain.IpConfigurationProperties;\nimport org.jclouds.azurecompute.arm.domain.Location;\nimport org.jclouds.azurecompute.arm.domain.ManagedDiskParameters;\nimport org.jclouds.azurecompute.arm.domain.NetworkInterfaceCard;\nimport org.jclouds.azurecompute.arm.domain.NetworkInterfaceCardProperties;\nimport org.jclouds.azurecompute.arm.domain.NetworkProfile;\nimport org.jclouds.azurecompute.arm.domain.NetworkProfile.NetworkInterface;\nimport org.jclouds.azurecompute.arm.domain.NetworkProfile.NetworkInterface.NetworkInterfaceProperties;\nimport org.jclouds.azurecompute.arm.domain.OSDisk;\nimport org.jclouds.azurecompute.arm.domain.OSProfile;\nimport org.jclouds.azurecompute.arm.domain.Offer;\nimport org.jclouds.azurecompute.arm.domain.Plan;\nimport org.jclouds.azurecompute.arm.domain.Provisionable;\nimport org.jclouds.azurecompute.arm.domain.ResourceGroup;\nimport org.jclouds.azurecompute.arm.domain.ResourceProviderMetaData;\nimport org.jclouds.azurecompute.arm.domain.SKU;\nimport org.jclouds.azurecompute.arm.domain.StorageAccountType;\nimport org.jclouds.azurecompute.arm.domain.StorageProfile;\nimport org.jclouds.azurecompute.arm.domain.VMHardware;\nimport org.jclouds.azurecompute.arm.domain.VMImage;\nimport org.jclouds.azurecompute.arm.domain.VMSize;\nimport org.jclouds.azurecompute.arm.domain.Version;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachine;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineProperties;\nimport org.jclouds.azurecompute.arm.domain.publicipaddress.PublicIPAddress;\nimport org.jclouds.azurecompute.arm.domain.publicipaddress.PublicIPAddressProperties;\nimport org.jclouds.azurecompute.arm.features.NetworkInterfaceCardApi;\nimport org.jclouds.azurecompute.arm.features.OSImageApi;\nimport org.jclouds.compute.ComputeServiceAdapter;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.location.Region;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Splitter;\nimport com.google.common.base.Strings;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Lists;\n\n/**\n * Defines the connection between the {@link AzureComputeApi} implementation and\n * the jclouds {@link org.jclouds.compute.ComputeService}.\n */\n@Singleton\npublic class AzureComputeServiceAdapter implements ComputeServiceAdapter<VirtualMachine, VMHardware, VMImage, Location> {\n\n   public static final String GROUP_KEY = \"jclouds_group\";\n   public static final String AUTOGENERATED_IP_KEY = \"jclouds-autogenerated\";\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   private final CleanupResources cleanupResources;\n   private final AzureComputeApi api;\n   private final List<String> imagePublishers;\n   private final Supplier<Set<String>> regionIds;\n   private final PublicIpAvailablePredicateFactory publicIpAvailable;\n   private final CustomImageToVMImage customImagetoVmImage;\n   private final GroupNamingConvention namingConvention;\n   private Predicate<Supplier<Provisionable>> resourceAvailable;\n\n   @Inject\n   AzureComputeServiceAdapter(final AzureComputeApi api, @Named(IMAGE_PUBLISHERS) String imagePublishers,\n         CleanupResources cleanupResources, @Region Supplier<Set<String>> regionIds,\n         PublicIpAvailablePredicateFactory publicIpAvailable, CustomImageToVMImage customImagetoVmImage,\n         GroupNamingConvention.Factory namingConvention, Predicate<Supplier<Provisionable>> resourceAvailable) {\n      this.api = api;\n      this.imagePublishers = Splitter.on(',').trimResults().omitEmptyStrings().splitToList(imagePublishers);\n      this.cleanupResources = cleanupResources;\n      this.regionIds = regionIds;\n      this.publicIpAvailable = publicIpAvailable;\n      this.customImagetoVmImage = customImagetoVmImage;\n      this.namingConvention = namingConvention.create();\n      this.resourceAvailable = resourceAvailable;\n   }\n\n   @Override\n   public NodeAndInitialCredentials<VirtualMachine> createNodeWithGroupEncodedIntoName(final String group, final String name, final Template template) {\n      String locationName = template.getLocation().getId();\n      Image image = template.getImage();\n      String hardwareId = fromSlashEncoded(template.getHardware().getId()).name();\n      AzureTemplateOptions templateOptions = template.getOptions().as(AzureTemplateOptions.class);\n      String resourceGroupName = templateOptions.getResourceGroup();\n      \n      IdReference availabilitySet = getAvailabilitySetIdReference(templateOptions.getAvailabilitySet());\n      NetworkProfile networkProfile = createNetworkProfile(createNetworkInterfaceCards(name, locationName,\n            templateOptions));\n      StorageProfile storageProfile = createStorageProfile(image, templateOptions);\n      HardwareProfile hardwareProfile = HardwareProfile.builder().vmSize(hardwareId).build();\n      OSProfile osProfile = createOsProfile(name, template);\n      \n      VirtualMachineProperties virtualMachineProperties = VirtualMachineProperties.builder()\n              .availabilitySet(availabilitySet)\n              .hardwareProfile(hardwareProfile)\n              .storageProfile(storageProfile)\n              .osProfile(osProfile)\n              .networkProfile(networkProfile)\n              .build();\n\n      // Store group apart from the name to be able to identify nodes with\n      // custom names in the configured group\n      templateOptions.getUserMetadata().put(GROUP_KEY, group);\n      Map<String, String> metadataAndTags = metadataAndTagsAsCommaDelimitedValue(templateOptions);\n      Plan plan = createMarketplacePlanIfPresent(image, templateOptions);\n\n      VirtualMachine virtualMachine = api.getVirtualMachineApi(resourceGroupName).createOrUpdate(name, locationName,\n            virtualMachineProperties, metadataAndTags, plan);\n\n      // Safe to pass null credentials here, as jclouds will default populate\n      // the node with the default credentials from the image, or the ones in\n      // the options, if provided.\n      ResourceGroupAndName resourceGroupAndName = fromResourceGroupAndName(resourceGroupName, name);\n      return new NodeAndInitialCredentials<VirtualMachine>(virtualMachine, resourceGroupAndName.slashEncode(), null);\n   }\n\n   @Override\n   public Iterable<VMHardware> listHardwareProfiles() {\n      final List<VMHardware> hwProfiles = Lists.newArrayList();\n      for (Location location : listLocations()) {\n         Iterable<VMSize> vmSizes = api.getVMSizeApi(location.name()).list();\n         for (VMSize vmSize : vmSizes) {\n            VMHardware hwProfile = VMHardware\n                    .create(vmSize.name(), vmSize.numberOfCores(), vmSize.osDiskSizeInMB(),\n                            vmSize.resourceDiskSizeInMB(), vmSize.memoryInMB(), vmSize.maxDataDiskCount(), location.name());\n            hwProfiles.add(hwProfile);\n         }\n      }\n      return hwProfiles;\n   }\n\n   private List<VMImage> getImagesFromPublisher(String publisherName, String location) {\n      List<VMImage> osImagesRef = Lists.newArrayList();\n      OSImageApi osImageApi = api.getOSImageApi(location);\n      Iterable<Offer> offerList = osImageApi.listOffers(publisherName);\n\n      for (Offer offer : offerList) {\n         Iterable<SKU> skuList = osImageApi.listSKUs(publisherName, offer.name());\n\n         for (SKU sku : skuList) {\n            Iterable<Version> versionList = osImageApi.listVersions(publisherName, offer.name(), sku.name());\n            for (Version version : versionList) {\n               Version versionDetails = osImageApi.getVersion(publisherName, offer.name(), sku.name(), version.name());\n               VMImage vmImage = VMImage.azureImage().publisher(publisherName).offer(offer.name()).sku(sku.name())\n                       .version(versionDetails.name()).location(location).versionProperties(versionDetails.properties())\n                       .build();\n               osImagesRef.add(vmImage);\n            }\n         }\n      }\n      return osImagesRef;\n   }\n\n   private List<VMImage> listImagesByLocation(String location) {\n      final List<VMImage> osImages = Lists.newArrayList();\n      for (String publisher : imagePublishers) {\n         osImages.addAll(getImagesFromPublisher(publisher, location));\n      }\n      return osImages;\n   }\n   \n   private List<VMImage> listCustomImagesByResourceGroup(String resourceGroup) {\n      List<org.jclouds.azurecompute.arm.domain.Image> customImgs = api.getVirtualMachineImageApi(resourceGroup).list();\n      return ImmutableList.copyOf(transform(\n            filter(customImgs, new Predicate<org.jclouds.azurecompute.arm.domain.Image>() {\n               @Override\n               public boolean apply(org.jclouds.azurecompute.arm.domain.Image input) {\n                  return regionIds.get().isEmpty() || regionIds.get().contains(input.location());\n               }\n            }), customImagetoVmImage));\n   }\n\n   @Override\n   public Iterable<VMImage> listImages() {\n      final ImmutableList.Builder<VMImage> osImages = ImmutableList.builder();\n      \n      final List<String> availableLocationNames = newArrayList(transform(listLocations(),\n            new Function<Location, String>() {\n               @Override\n               public String apply(Location location) {\n                  return location.name();\n               }\n            }));\n\n      for (String locationName : availableLocationNames) {\n         osImages.addAll(listImagesByLocation(locationName));\n      }\n\n      // We need to look for custom images in all resource groups\n      for (ResourceGroup resourceGroup : api.getResourceGroupApi().list()) {\n         osImages.addAll(listCustomImagesByResourceGroup(resourceGroup.name()));\n      }\n\n      return osImages.build();\n   }\n\n   @Override\n   public VMImage getImage(final String id) {\n      VMImage image = VMImage.decodeFieldsFromUniqueId(id);\n\n      if (image.custom()) {\n         org.jclouds.azurecompute.arm.domain.Image vmImage = api.getVirtualMachineImageApi(image.resourceGroup()).get(\n               image.name());\n         return vmImage == null ? null : customImagetoVmImage.apply(vmImage);\n      }\n\n      String location = image.location();\n      String publisher = image.publisher();\n      String offer = image.offer();\n      String sku = image.sku();\n\n      OSImageApi osImageApi = api.getOSImageApi(location);\n      List<Version> versions = osImageApi.listVersions(publisher, offer, sku);\n      if (!versions.isEmpty()) {\n         Version version = osImageApi.getVersion(publisher, offer, sku, versions.get(0).name());\n         return VMImage.azureImage().publisher(publisher).offer(offer).sku(sku).version(version.name())\n                 .location(location).versionProperties(version.properties()).build();\n      }\n      \n      return null;\n   }\n\n   @Override\n   public Iterable<Location> listLocations() {\n      final Iterable<String> vmLocations = FluentIterable.from(api.getResourceProviderApi().get(\"Microsoft.Compute\"))\n              .filter(new Predicate<ResourceProviderMetaData>() {\n                 @Override\n                 public boolean apply(ResourceProviderMetaData input) {\n                    return input.resourceType().equals(\"virtualMachines\");\n                 }\n              }).transformAndConcat(new Function<ResourceProviderMetaData, Iterable<String>>() {\n                 @Override\n                 public Iterable<String> apply(ResourceProviderMetaData resourceProviderMetaData) {\n                    return resourceProviderMetaData.locations();\n                 }\n              });\n\n      List<Location> locations = FluentIterable.from(api.getLocationApi().list()).filter(new Predicate<Location>() {\n         @Override\n         public boolean apply(Location location) {\n            return Iterables.contains(vmLocations, location.displayName());\n         }\n      }).filter(new Predicate<Location>() {\n         @Override\n         public boolean apply(Location location) {\n            return regionIds.get().isEmpty() ? true : regionIds.get().contains(location.name());\n         }\n      }).toList();\n\n      return locations;\n   }\n\n   @Override\n   public VirtualMachine getNode(final String id) {\n      ResourceGroupAndName resourceGroupAndName = ResourceGroupAndName.fromSlashEncoded(id);\n      return api.getVirtualMachineApi(resourceGroupAndName.resourceGroup()).get(resourceGroupAndName.name());\n   }\n\n   @Override\n   public void destroyNode(final String id) {\n      checkState(cleanupResources.cleanupNode(id), \"server(%s) and its resources still there after deleting!?\", id);\n   }\n\n   @Override\n   public void rebootNode(final String id) {\n      ResourceGroupAndName resourceGroupAndName = ResourceGroupAndName.fromSlashEncoded(id);\n      api.getVirtualMachineApi(resourceGroupAndName.resourceGroup()).restart(resourceGroupAndName.name());\n   }\n\n   @Override\n   public void resumeNode(final String id) {\n      ResourceGroupAndName resourceGroupAndName = ResourceGroupAndName.fromSlashEncoded(id);\n      api.getVirtualMachineApi(resourceGroupAndName.resourceGroup()).start(resourceGroupAndName.name());\n   }\n\n   @Override\n   public void suspendNode(final String id) {\n      ResourceGroupAndName resourceGroupAndName = ResourceGroupAndName.fromSlashEncoded(id);\n      api.getVirtualMachineApi(resourceGroupAndName.resourceGroup()).stop(resourceGroupAndName.name());\n   }\n\n   @Override\n   public Iterable<VirtualMachine> listNodes() {\n      ImmutableList.Builder<VirtualMachine> nodes = builder();\n      if (regionIds.get().isEmpty()) {\n         nodes.addAll(api.getVirtualMachineApi(null).listAll());\n      } else {\n         for (final String location : regionIds.get()) {\n            nodes.addAll(api.getVirtualMachineApi(null).listByLocation(location));\n         }\n      }\n      return nodes.build();\n   }\n\n   @Override\n   public Iterable<VirtualMachine> listNodesByIds(final Iterable<String> ids) {\n      return transform(ids, new Function<String, VirtualMachine>() {\n         @Override\n         public VirtualMachine apply(String input) {\n            return getNode(input);\n         }\n      });\n   }\n\n   private OSProfile createOsProfile(String computerName, Template template) {\n      String defaultLoginUser = template.getImage().getDefaultCredentials().getUser();\n      String adminUsername = MoreObjects.firstNonNull(template.getOptions().getLoginUser(), defaultLoginUser);\n      // Password already generated in CreateResourcesThenCreateNodes (if not set by user)\n      String adminPassword = template.getOptions().getLoginPassword();\n      OSProfile.Builder builder = OSProfile.builder().adminUsername(adminUsername).adminPassword(adminPassword)\n              .computerName(computerName);\n\n      if (!Strings.isNullOrEmpty(template.getOptions().getPublicKey())\n              && OsFamily.WINDOWS != template.getImage().getOperatingSystem().getFamily()) {\n         OSProfile.LinuxConfiguration linuxConfiguration = OSProfile.LinuxConfiguration.create(\"true\",\n                 OSProfile.LinuxConfiguration.SSH.create(of(\n                         OSProfile.LinuxConfiguration.SSH.SSHPublicKey.create(\n                                 String.format(\"/home/%s/.ssh/authorized_keys\", adminUsername),\n                                 template.getOptions().getPublicKey()))));\n         builder.linuxConfiguration(linuxConfiguration);\n      }\n\n      AzureTemplateOptions azureTemplateOptions = template.getOptions().as(AzureTemplateOptions.class);\n\n      if (azureTemplateOptions.getWindowsConfiguration() != null) {\n          builder.windowsConfiguration(azureTemplateOptions.getWindowsConfiguration());\n      }\n\n      if (azureTemplateOptions.getSecrets() != null) {\n          builder.secrets(azureTemplateOptions.getSecrets());\n      }\n\n      if (!Strings.isNullOrEmpty(azureTemplateOptions.getCustomData())) {\n         builder.customData(azureTemplateOptions.getCustomData());\n      }\n\n      return builder.build();\n   }\n\n   private List<NetworkInterfaceCard> createNetworkInterfaceCards(final String nodeName, final String location,\n         AzureTemplateOptions options) {\n      // Prefer a sorted list of NICs with the ones with public IPs first, to\n      // make sure the primary NIC is the public one\n      final String securityGroup = getOnlyElement(options.getGroups(), null);\n      return Lists.transform(publicIpsFirst(options.getIpOptions()), new Function<IpOptions, NetworkInterfaceCard>() {\n         @Override\n         public NetworkInterfaceCard apply(IpOptions input) {\n            return createNetworkInterfaceCard(input, nodeName, location, securityGroup);\n         }\n      });\n   }\n   \n   private NetworkInterfaceCard createNetworkInterfaceCard(IpOptions ipConfig, String nodeName, String location,\n         String securityGroup) {\n      String resourceGroup = extractResourceGroup(ipConfig.subnet());\n      String subnetName = extractName(ipConfig.subnet());\n\n      IpConfigurationProperties.Builder ipProperties = IpConfigurationProperties.builder()\n            .subnet(IdReference.create(ipConfig.subnet()))\n            .privateIPAllocationMethod(ipConfig.address().isPresent() ? \"Static\" : \"Dynamic\")\n            .privateIPAddress(ipConfig.address().orNull());\n\n      configurePublicIP(ipConfig, ipProperties, resourceGroup, location, nodeName);\n\n      String ipName = namingConvention.uniqueNameForGroup(subnetName);\n      final String nicName = namingConvention.uniqueNameForGroup(subnetName);\n\n      IpConfiguration config = IpConfiguration.builder().name(ipName).properties(ipProperties.build()).build();\n\n      NetworkInterfaceCardProperties.Builder nicProperties = NetworkInterfaceCardProperties.builder().ipConfigurations(\n            ImmutableList.of(config));\n\n      if (securityGroup != null) {\n         nicProperties.networkSecurityGroup(IdReference.create(securityGroup));\n      }\n\n      logger.debug(\">> creating nic %s(%s) with security groups (%s)\", nicName, config,\n            securityGroup != null ? securityGroup : \"\");\n\n      final NetworkInterfaceCardApi nicApi = api.getNetworkInterfaceCardApi(resourceGroup);\n      NetworkInterfaceCard nic = nicApi.createOrUpdate(nicName, location, nicProperties.build(),\n            ImmutableMap.of(\"jclouds\", nodeName));\n\n      resourceAvailable.apply(new Supplier<Provisionable>() {\n         @Override\n         public Provisionable get() {\n            NetworkInterfaceCard updated = nicApi.get(nicName);\n            return updated == null ? null : updated.properties();\n         }\n      });\n\n      return nic;\n   }\n   \n   private void configurePublicIP(IpOptions ipConfig, IpConfigurationProperties.Builder ipProperties,\n         String resourceGroup, String location, String nodeName) {\n      if (ipConfig.publicIpId() != null) {\n         logger.debug(\">> configuring public ip: %s\",  extractName(ipConfig.publicIpId()));\n         PublicIPAddress publicIp = api.getPublicIPAddressApi(extractResourceGroup(ipConfig.publicIpId())).get(\n               extractName(ipConfig.publicIpId()));\n         ipProperties.publicIPAddress(IdReference.create(publicIp.id()));\n      } else if (ipConfig.allocateNewPublicIp()) {\n         PublicIPAddress publicIp = createPublicIp(resourceGroup, location, nodeName);\n         ipProperties.publicIPAddress(IdReference.create(publicIp.id()));\n      }\n   }\n   \n   /**\n    * Create the network profile and configure the first NIC as primary.\n    */\n   private NetworkProfile createNetworkProfile(List<NetworkInterfaceCard> nics) {\n      List<NetworkInterface> nicAttachments = new ArrayList<NetworkInterface>(nics.size());\n      for (int i = 0; i < nics.size(); i++) {\n         nicAttachments.add(NetworkInterface.create(nics.get(i).id(), NetworkInterfaceProperties.create(i == 0)));\n      }\n      return NetworkProfile.create(nicAttachments);\n   }\n   \n   private static List<IpOptions> publicIpsFirst(List<IpOptions> ipOptions) {\n      List<IpOptions> sorted = new ArrayList<IpOptions>(ipOptions);\n      Collections.sort(sorted, new Comparator<IpOptions>() {\n         @Override\n         public int compare(IpOptions o1, IpOptions o2) {\n            return o1.allocateNewPublicIp() == o2.allocateNewPublicIp() ? 0 : o1.allocateNewPublicIp() ? -1 : 1;\n         }\n      });\n      return sorted;\n   }\n   \n   private PublicIPAddress createPublicIp(String resourceGroup, String location, String nodeName) {\n      String name = namingConvention.uniqueNameForGroup(nodeName);\n      \n      PublicIPAddressProperties properties = PublicIPAddressProperties.builder()\n            .publicIPAllocationMethod(\"Static\")\n            .idleTimeoutInMinutes(4)\n            .build();\n      \n      logger.debug(\">> allocating new public ip address: %s\", name);\n\n      PublicIPAddress ip = api.getPublicIPAddressApi(resourceGroup).createOrUpdate(name, location,\n            ImmutableMap.of(\"jclouds\", nodeName, AUTOGENERATED_IP_KEY, \"true\"), null, properties);\n\n      checkState(publicIpAvailable.create(resourceGroup).apply(name),\n              \"Public IP was not provisioned in the configured timeout\");\n      \n      return ip;\n   }\n\n   private StorageProfile createStorageProfile(Image image, AzureTemplateOptions templateOptions) {\n      List<DataDisk> dataDisks = templateOptions.getDataDisks();\n      StorageAccountType osDiskStorageType = templateOptions.getOsDiskStorageType();\n      return StorageProfile.create(createImageReference(image), createOSDisk(image, osDiskStorageType), dataDisks);\n   }\n\n   private ImageReference createImageReference(Image image) {\n      return isCustom(image.getId()) ? ImageReference.builder().customImageId(image.getProviderId()).build() : ImageReference\n            .builder().publisher(image.getProviderId()).offer(image.getName()).sku(image.getVersion())\n            .version(\"latest\").build();\n   }\n\n   private OSDisk createOSDisk(Image image, StorageAccountType osDiskStorageType) {\n      OsFamily osFamily = image.getOperatingSystem().getFamily();\n      String osType = osFamily == OsFamily.WINDOWS ? \"Windows\" : \"Linux\";\n      return OSDisk.builder()\n              .osType(osType)\n              .caching(DataDisk.CachingTypes.READ_WRITE.toString())\n              .createOption(CreationData.CreateOptions.FROM_IMAGE.toString())\n              .managedDiskParameters(ManagedDiskParameters.create(null, osDiskStorageType.toString()))\n              .build();\n   }\n   \n   private IdReference getAvailabilitySetIdReference(AvailabilitySet availabilitySet) {\n      return availabilitySet != null ? IdReference.create(availabilitySet.id()) : null;\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/compute/config/AzureComputeServiceContextModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.compute.config;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.azurecompute.arm.compute.AzureComputeService;\nimport org.jclouds.azurecompute.arm.compute.AzureComputeServiceAdapter;\nimport org.jclouds.azurecompute.arm.compute.domain.ResourceGroupAndNameAndIngressRules;\nimport org.jclouds.azurecompute.arm.compute.extensions.AzureComputeImageExtension;\nimport org.jclouds.azurecompute.arm.compute.extensions.AzureComputeSecurityGroupExtension;\nimport org.jclouds.azurecompute.arm.compute.functions.LocationToLocation;\nimport org.jclouds.azurecompute.arm.compute.functions.NetworkSecurityGroupToSecurityGroup;\nimport org.jclouds.azurecompute.arm.compute.functions.NetworkSecurityRuleToIpPermission;\nimport org.jclouds.azurecompute.arm.compute.functions.VMHardwareToHardware;\nimport org.jclouds.azurecompute.arm.compute.functions.VMImageToImage;\nimport org.jclouds.azurecompute.arm.compute.functions.VirtualMachineToNodeMetadata;\nimport org.jclouds.azurecompute.arm.compute.loaders.CreateSecurityGroupIfNeeded;\nimport org.jclouds.azurecompute.arm.compute.loaders.DefaultResourceGroup;\nimport org.jclouds.azurecompute.arm.compute.options.AzureTemplateOptions;\nimport org.jclouds.azurecompute.arm.compute.strategy.CreateResourcesThenCreateNodes;\nimport org.jclouds.azurecompute.arm.domain.Location;\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityGroup;\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityRule;\nimport org.jclouds.azurecompute.arm.domain.ResourceGroup;\nimport org.jclouds.azurecompute.arm.domain.VMHardware;\nimport org.jclouds.azurecompute.arm.domain.VMImage;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachine;\nimport org.jclouds.compute.ComputeService;\nimport org.jclouds.compute.ComputeServiceAdapter;\nimport org.jclouds.compute.config.ComputeServiceAdapterContextModule;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.SecurityGroup;\nimport org.jclouds.compute.extensions.ImageExtension;\nimport org.jclouds.compute.extensions.SecurityGroupExtension;\nimport org.jclouds.compute.functions.NodeAndTemplateOptionsToStatement;\nimport org.jclouds.compute.functions.NodeAndTemplateOptionsToStatementWithoutPublicKey;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.compute.strategy.CreateNodesInGroupThenAddToSet;\nimport org.jclouds.net.domain.IpPermission;\nimport org.jclouds.util.PasswordGenerator;\n\nimport com.google.common.base.Function;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.inject.Provides;\nimport com.google.inject.TypeLiteral;\n\npublic class AzureComputeServiceContextModule extends\n      ComputeServiceAdapterContextModule<VirtualMachine, VMHardware, VMImage, Location> {\n\n   @Override\n   protected void configure() {\n      super.configure();\n\n      bind(new TypeLiteral<ComputeServiceAdapter<VirtualMachine, VMHardware, VMImage, Location>>() {\n      }).to(AzureComputeServiceAdapter.class);\n\n      bind(new TypeLiteral<Function<VMImage, org.jclouds.compute.domain.Image>>() {\n      }).to(VMImageToImage.class);\n      bind(new TypeLiteral<Function<VMHardware, Hardware>>() {\n      }).to(VMHardwareToHardware.class);\n      bind(new TypeLiteral<Function<VirtualMachine, NodeMetadata>>() {\n      }).to(VirtualMachineToNodeMetadata.class);\n      bind(new TypeLiteral<Function<Location, org.jclouds.domain.Location>>() {\n      }).to(LocationToLocation.class);\n      bind(new TypeLiteral<Function<NetworkSecurityGroup, SecurityGroup>>() {\n      }).to(NetworkSecurityGroupToSecurityGroup.class);\n      bind(new TypeLiteral<Function<NetworkSecurityRule, IpPermission>>() {\n      }).to(NetworkSecurityRuleToIpPermission.class);\n      bind(ComputeService.class).to(AzureComputeService.class);\n\n      install(new LocationsFromComputeServiceAdapterModule<VirtualMachine, VMHardware, VMImage, Location>() {\n      });\n\n      bind(TemplateOptions.class).to(AzureTemplateOptions.class);\n      bind(NodeAndTemplateOptionsToStatement.class).to(NodeAndTemplateOptionsToStatementWithoutPublicKey.class);\n      bind(CreateNodesInGroupThenAddToSet.class).to(CreateResourcesThenCreateNodes.class);\n\n      bind(new TypeLiteral<CacheLoader<ResourceGroupAndNameAndIngressRules, String>>() {\n      }).to(CreateSecurityGroupIfNeeded.class);\n      bind(new TypeLiteral<CacheLoader<String, ResourceGroup>>() {\n      }).to(DefaultResourceGroup.class);\n\n      bind(new TypeLiteral<ImageExtension>() {\n      }).to(AzureComputeImageExtension.class);\n      bind(new TypeLiteral<SecurityGroupExtension>() {\n      }).to(AzureComputeSecurityGroupExtension.class);\n   }\n   \n   @Provides\n   @Singleton\n   protected PasswordGenerator.Config providePasswordGenerator() {\n      // Guest passwords must be between 6-72 characters long.\n      // Must contain an upper case character.\n      // Must contain a lower case character.\n      // Must contain a numeric digit.\n      // Must contain a special character. Control characters are not allowed.\n      return new PasswordGenerator()\n            .lower().min(2).max(10)\n            .upper().min(2).max(10)\n            .numbers().min(2).max(10)\n            .symbols().min(2).max(10);\n   }\n\n   @Provides\n   @Singleton\n   protected final LoadingCache<ResourceGroupAndNameAndIngressRules, String> securityGroupMap(\n         CacheLoader<ResourceGroupAndNameAndIngressRules, String> in) {\n      return CacheBuilder.newBuilder().build(in);\n   }\n\n   @Provides\n   @Singleton\n   protected final LoadingCache<String, ResourceGroup> defaultResourceGroup(CacheLoader<String, ResourceGroup> in) {\n      return CacheBuilder.newBuilder().build(in);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/compute/config/AzureNameValidator.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.azurecompute.arm.compute.config;\n\nimport static com.google.common.base.CharMatcher.anyOf;\nimport static com.google.common.base.CharMatcher.inRange;\n\nimport org.jclouds.predicates.Validator;\n\nimport com.google.common.base.CharMatcher;\nimport com.google.inject.Singleton;\n\n/**\n * Validates name for azure entities\n * https://docs.microsoft.com/en-us/azure/architecture/best-practices/naming-conventions\n *\n * @see org.jclouds.predicates.Validator\n */\n@Singleton\npublic class AzureNameValidator extends Validator<String> {\n   private static final int minLength = 2;\n   private static final int maxLength = 63;\n\n   public void validate(String name) {\n\n      if (name == null || name.length() < minLength || name.length() > maxLength)\n         throw exception(name, \"Can't be null or empty. Length must be \" + minLength + \" to \" + maxLength + \" symbols\");\n      if (!Character.isLetterOrDigit(name.charAt(0)))\n         throw exception(name, \"Should start with letter/number\");\n\n      CharMatcher range = getAcceptableRange();\n      if (!range.matchesAllOf(name))\n         throw exception(name,\n               \"Should have lowercase or uppercase ASCII letters, numbers, dashes, underscores and periods\");\n   }\n\n   private CharMatcher getAcceptableRange() {\n      return inRange('a', 'z').or(inRange('A', 'Z')).or(inRange('0', '9')).or(anyOf(\"-_.\"));\n   }\n\n   protected IllegalArgumentException exception(String name, String reason) {\n      return new IllegalArgumentException(String.format(\"Object '%s' doesn't match Azure naming constraints: %s\", name,\n                  reason));\n   }\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/compute/config/AzurePredicatesModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.compute.config;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.azurecompute.arm.config.AzureComputeProperties.OPERATION_TIMEOUT;\nimport static org.jclouds.azurecompute.arm.config.AzureComputeProperties.TIMEOUT_RESOURCE_DELETED;\nimport static org.jclouds.azurecompute.arm.config.AzureComputeProperties.VAULT_CERTIFICATE_DELETE_STATUS;\nimport static org.jclouds.azurecompute.arm.config.AzureComputeProperties.VAULT_CERTIFICATE_OPERATION_STATUS;\nimport static org.jclouds.azurecompute.arm.config.AzureComputeProperties.VAULT_CERTIFICATE_RECOVERABLE_STATUS;\nimport static org.jclouds.azurecompute.arm.config.AzureComputeProperties.VAULT_DELETE_STATUS;\nimport static org.jclouds.azurecompute.arm.config.AzureComputeProperties.VAULT_KEY_DELETED_STATUS;\nimport static org.jclouds.azurecompute.arm.config.AzureComputeProperties.VAULT_KEY_RECOVERABLE_STATUS;\nimport static org.jclouds.azurecompute.arm.config.AzureComputeProperties.VAULT_SECRET_DELETE_STATUS;\nimport static org.jclouds.azurecompute.arm.config.AzureComputeProperties.VAULT_SECRET_RECOVERABLE_STATUS;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_IMAGE_AVAILABLE;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_RUNNING;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_SUSPENDED;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_TERMINATED;\nimport static org.jclouds.util.Predicates2.retry;\n\nimport java.net.URI;\nimport java.util.List;\nimport java.util.concurrent.TimeUnit;\n\nimport org.jclouds.azurecompute.arm.AzureComputeApi;\nimport org.jclouds.azurecompute.arm.domain.Certificate.CertificateBundle;\nimport org.jclouds.azurecompute.arm.domain.Certificate.CertificateOperation;\nimport org.jclouds.azurecompute.arm.domain.Certificate.DeletedCertificateBundle;\nimport org.jclouds.azurecompute.arm.domain.Image;\nimport org.jclouds.azurecompute.arm.domain.Key.DeletedKeyBundle;\nimport org.jclouds.azurecompute.arm.domain.Key.KeyBundle;\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityGroup;\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityRule;\nimport org.jclouds.azurecompute.arm.domain.Provisionable;\nimport org.jclouds.azurecompute.arm.domain.ResourceDefinition;\nimport org.jclouds.azurecompute.arm.domain.Secret.DeletedSecretBundle;\nimport org.jclouds.azurecompute.arm.domain.Secret.SecretBundle;\nimport org.jclouds.azurecompute.arm.domain.Vault;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineInstance;\nimport org.jclouds.azurecompute.arm.domain.VirtualNetwork;\nimport org.jclouds.azurecompute.arm.domain.publicipaddress.PublicIPAddress;\nimport org.jclouds.azurecompute.arm.domain.vpn.VirtualNetworkGateway;\nimport org.jclouds.azurecompute.arm.functions.ParseJobStatus;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.compute.reference.ComputeServiceConstants.PollPeriod;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.Iterables;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Provides;\nimport com.google.inject.name.Named;\n\npublic class AzurePredicatesModule extends AbstractModule {\n   protected void configure() {\n   }\n\n   @Provides\n   @Named(TIMEOUT_NODE_RUNNING)\n   protected VirtualMachineInStatePredicateFactory provideVirtualMachineRunningPredicate(final AzureComputeApi api,\n         final ComputeServiceConstants.Timeouts timeouts, final PollPeriod pollPeriod) {\n      return new VirtualMachineInStatePredicateFactory(api, VirtualMachineInstance.PowerState.RUNNING,\n            timeouts.nodeRunning, pollPeriod.pollInitialPeriod, pollPeriod.pollMaxPeriod);\n   }\n\n   @Provides\n   @Named(TIMEOUT_NODE_TERMINATED)\n   protected Predicate<URI> provideNodeTerminatedPredicate(final AzureComputeApi api,\n         final ComputeServiceConstants.Timeouts timeouts, final PollPeriod pollPeriod) {\n      return retry(new ActionDonePredicate(api), timeouts.nodeTerminated, pollPeriod.pollInitialPeriod,\n            pollPeriod.pollMaxPeriod);\n   }\n\n   @Provides\n   @Named(TIMEOUT_IMAGE_AVAILABLE)\n   protected Predicate<URI> provideImageCapturedPredicate(final AzureComputeApi api,\n         final ComputeServiceConstants.Timeouts timeouts, final PollPeriod pollPeriod) {\n      return retry(new ImageCapturedPredicate(api), timeouts.imageAvailable, pollPeriod.pollInitialPeriod,\n            pollPeriod.pollMaxPeriod);\n   }\n\n   @Provides\n   @Named(TIMEOUT_RESOURCE_DELETED)\n   protected Predicate<URI> provideResourceDeletedPredicate(final AzureComputeApi api,\n         final ComputeServiceConstants.Timeouts timeouts, final PollPeriod pollPeriod) {\n      return retry(new ActionDonePredicate(api), timeouts.nodeTerminated, pollPeriod.pollInitialPeriod,\n            pollPeriod.pollMaxPeriod);\n   }\n\n   @Provides\n   @Named(TIMEOUT_NODE_SUSPENDED)\n   protected VirtualMachineInStatePredicateFactory provideNodeSuspendedPredicate(final AzureComputeApi api,\n         final ComputeServiceConstants.Timeouts timeouts, final PollPeriod pollPeriod) {\n      return new VirtualMachineInStatePredicateFactory(api, VirtualMachineInstance.PowerState.STOPPED,\n            timeouts.nodeTerminated, pollPeriod.pollInitialPeriod, pollPeriod.pollMaxPeriod);\n   }\n\n   @Provides\n   protected PublicIpAvailablePredicateFactory providePublicIpAvailablePredicate(final AzureComputeApi api,\n         Predicate<Supplier<Provisionable>> resourceAvailable) {\n      return new PublicIpAvailablePredicateFactory(api, resourceAvailable);\n   }\n\n   @Provides\n   protected SecurityGroupAvailablePredicateFactory provideSecurityGroupAvailablePredicate(final AzureComputeApi api,\n         Predicate<Supplier<Provisionable>> resourceAvailable) {\n      return new SecurityGroupAvailablePredicateFactory(api, resourceAvailable);\n   }\n\n   @Provides\n   protected SecurityGroupRuleAvailablePredicateFactory provideSecurityGroupRuleAvailablePredicate(final AzureComputeApi api,\n         Predicate<Supplier<Provisionable>> resourceAvailable) {\n      return new SecurityGroupRuleAvailablePredicateFactory(api, resourceAvailable);\n   }\n\n   @Provides\n   protected ImageAvailablePredicateFactory provideImageAvailablePredicate(final AzureComputeApi api,\n         final ComputeServiceConstants.Timeouts timeouts, final PollPeriod pollPeriod) {\n      return new ImageAvailablePredicateFactory(api, retry(new ResourceInStatusPredicate(\"Succeeded\"),\n            timeouts.imageAvailable, pollPeriod.pollInitialPeriod, pollPeriod.pollMaxPeriod));\n   }\n\n   @Provides\n   protected VirtualNetworkGatewayAvailablePredicateFactory provideVirtualNetworkGatewayAvailablePredicate(\n         final AzureComputeApi api, Predicate<Supplier<Provisionable>> resourceAvailable,\n         final ComputeServiceConstants.Timeouts timeouts, final PollPeriod pollPeriod) {\n      // The Azure Virtual Gateways can take up to 45 minutes to be provisioned.\n      // Don't poll too aggressively\n      return new VirtualNetworkGatewayAvailablePredicateFactory(api, retry(new ResourceInStatusPredicate(\"Succeeded\"),\n            45, 1, 2, TimeUnit.MINUTES));\n   }\n\n   @Provides\n   protected Predicate<Supplier<Provisionable>> provideResourceAvailablePredicate(final AzureComputeApi api,\n         @Named(OPERATION_TIMEOUT) Integer operationTimeout, PollPeriod pollPeriod) {\n      return retry(new ResourceInStatusPredicate(\"Succeeded\"), operationTimeout, pollPeriod.pollInitialPeriod,\n            pollPeriod.pollMaxPeriod);\n   }\n\n   @Provides\n   protected NetworkAvailablePredicateFactory provideNetworkAvailablePredicate(final AzureComputeApi api,\n         Predicate<Supplier<Provisionable>> resourceAvailable) {\n      return new NetworkAvailablePredicateFactory(api, resourceAvailable);\n   }\n\n   @VisibleForTesting\n   static class ActionDonePredicate implements Predicate<URI> {\n\n      private final AzureComputeApi api;\n\n      public ActionDonePredicate(final AzureComputeApi api) {\n         this.api = checkNotNull(api, \"api must not be null\");\n      }\n\n      @Override\n      public boolean apply(final URI uri) {\n         checkNotNull(uri, \"uri cannot be null\");\n         return ParseJobStatus.JobStatus.DONE == api.getJobApi().jobStatus(uri)\n               || ParseJobStatus.JobStatus.NO_CONTENT == api.getJobApi().jobStatus(uri);\n      }\n   }\n\n   @VisibleForTesting\n   static class ImageCapturedPredicate implements Predicate<URI> {\n\n      private final AzureComputeApi api;\n\n      public ImageCapturedPredicate(final AzureComputeApi api) {\n         this.api = checkNotNull(api, \"api must not be null\");\n      }\n\n      @Override\n      public boolean apply(final URI uri) {\n         checkNotNull(uri, \"uri cannot be null\");\n         if (api.getJobApi().jobStatus(uri) != ParseJobStatus.JobStatus.DONE) {\n            return false;\n         }\n         List<ResourceDefinition> definitions = api.getJobApi().captureStatus(uri);\n         return definitions != null;\n      }\n   }\n\n   public static class VirtualMachineInStatePredicateFactory {\n\n      private final AzureComputeApi api;\n      private final VirtualMachineInstance.PowerState powerState;\n      private final long timeout;\n      private final long period;\n      private final long maxPeriod;\n\n      VirtualMachineInStatePredicateFactory(final AzureComputeApi api,\n            final VirtualMachineInstance.PowerState powerState, final long timeout, final long period,\n            final long maxPeriod) {\n         this.api = checkNotNull(api, \"api cannot be null\");\n         this.powerState = checkNotNull(powerState, \"powerState cannot be null\");\n         this.timeout = timeout;\n         this.period = period;\n         this.maxPeriod = maxPeriod;\n      }\n\n      public Predicate<String> create(final String azureGroup) {\n         return retry(new Predicate<String>() {\n            @Override\n            public boolean apply(final String name) {\n               checkNotNull(name, \"name cannot be null\");\n               VirtualMachineInstance vmInstance = api.getVirtualMachineApi(azureGroup).getInstanceDetails(name);\n               if (vmInstance == null) {\n                  return false;\n               }\n               return powerState == vmInstance.powerState();\n            }\n         }, timeout, period, maxPeriod);\n      }\n   }\n\n   public static class ResourceInStatusPredicate implements Predicate<Supplier<Provisionable>> {\n      private final String expectedStatus;\n\n      ResourceInStatusPredicate(String expectedStatus) {\n         this.expectedStatus = checkNotNull(expectedStatus, \"expectedStatus cannot be null\");\n      }\n\n      @Override\n      public boolean apply(Supplier<Provisionable> provisionableSupplier) {\n         checkNotNull(provisionableSupplier, \"provisionableSupplier supplier cannot be null\");\n         Provisionable provisionable = provisionableSupplier.get();\n         return provisionable != null && provisionable.provisioningState().equalsIgnoreCase(expectedStatus);\n      }\n   }\n\n   public static class PublicIpAvailablePredicateFactory {\n      private final AzureComputeApi api;\n      private final Predicate<Supplier<Provisionable>> resourceAvailable;\n\n      PublicIpAvailablePredicateFactory(final AzureComputeApi api, Predicate<Supplier<Provisionable>> resourceAvailable) {\n         this.api = checkNotNull(api, \"api cannot be null\");\n         this.resourceAvailable = resourceAvailable;\n      }\n\n      public Predicate<String> create(final String azureGroup) {\n         checkNotNull(azureGroup, \"azureGroup cannot be null\");\n         return new Predicate<String>() {\n            @Override\n            public boolean apply(final String name) {\n               checkNotNull(name, \"name cannot be null\");\n               return resourceAvailable.apply(new Supplier<Provisionable>() {\n                  @Override\n                  public Provisionable get() {\n                     PublicIPAddress publicIp = api.getPublicIPAddressApi(azureGroup).get(name);\n                     return publicIp == null ? null : publicIp.properties();\n                  }\n               });\n            }\n         };\n      }\n   }\n\n   public static class SecurityGroupAvailablePredicateFactory {\n      private final AzureComputeApi api;\n      private final Predicate<Supplier<Provisionable>> resourceAvailable;\n\n      SecurityGroupAvailablePredicateFactory(final AzureComputeApi api,\n            Predicate<Supplier<Provisionable>> resourceAvailable) {\n         this.api = checkNotNull(api, \"api cannot be null\");\n         this.resourceAvailable = resourceAvailable;\n      }\n\n      public Predicate<String> create(final String resourceGroup) {\n         checkNotNull(resourceGroup, \"resourceGroup cannot be null\");\n         return new Predicate<String>() {\n            @Override\n            public boolean apply(final String name) {\n               checkNotNull(name, \"name cannot be null\");\n               return resourceAvailable.apply(new Supplier<Provisionable>() {\n                  @Override\n                  public Provisionable get() {\n                     NetworkSecurityGroup sg = api.getNetworkSecurityGroupApi(resourceGroup).get(name);\n                     return sg == null ? null : sg.properties();\n                  }\n               });\n            }\n         };\n      }\n   }\n\n   public static class SecurityGroupRuleAvailablePredicateFactory {\n      private final AzureComputeApi api;\n      private final Predicate<Supplier<Provisionable>> resourceAvailable;\n\n      SecurityGroupRuleAvailablePredicateFactory(final AzureComputeApi api, Predicate<Supplier<Provisionable>> resourceAvailable) {\n         this.api = checkNotNull(api, \"api cannot be null\");\n         this.resourceAvailable = resourceAvailable;\n      }\n\n      public Predicate<String> create(final String resourceGroup, final String securityGroupName) {\n         checkNotNull(resourceGroup, \"resourceGroup cannot be null\");\n         checkNotNull(securityGroupName, \"securityGroupName cannot be null\");\n         return new Predicate<String>() {\n            @Override\n            public boolean apply(final String name) {\n               checkNotNull(name, \"name cannot be null\");\n               return resourceAvailable.apply(new Supplier<Provisionable>() {\n                  @Override\n                  public Provisionable get() {\n                     NetworkSecurityRule securityRule = api.getNetworkSecurityRuleApi(resourceGroup, securityGroupName).get(name);\n                     return securityRule == null ? null : securityRule.properties();\n                  }\n               });\n            }\n         };\n      }\n   }\n\n   public static class NetworkAvailablePredicateFactory {\n      private final AzureComputeApi api;\n      private final Predicate<Supplier<Provisionable>> resourceAvailable;\n\n      NetworkAvailablePredicateFactory(final AzureComputeApi api, Predicate<Supplier<Provisionable>> resourceAvailable) {\n         this.api = checkNotNull(api, \"api cannot be null\");\n         this.resourceAvailable = resourceAvailable;\n      }\n\n      public Predicate<String> create(final String resourceGroup) {\n         checkNotNull(resourceGroup, \"resourceGroup cannot be null\");\n         return new Predicate<String>() {\n            @Override\n            public boolean apply(final String name) {\n               checkNotNull(name, \"name cannot be null\");\n               return resourceAvailable.apply(new Supplier<Provisionable>() {\n                  @Override\n                  public Provisionable get() {\n                     VirtualNetwork vnet = api.getVirtualNetworkApi(resourceGroup).get(name);\n                     return vnet == null ? null : vnet.properties();\n                  }\n               });\n            }\n         };\n      }\n   }\n\n   public static class ImageAvailablePredicateFactory {\n      private final AzureComputeApi api;\n      private final Predicate<Supplier<Provisionable>> resourceAvailable;\n\n      ImageAvailablePredicateFactory(final AzureComputeApi api, Predicate<Supplier<Provisionable>> resourceAvailable) {\n         this.api = checkNotNull(api, \"api cannot be null\");\n         this.resourceAvailable = resourceAvailable;\n      }\n\n      public Predicate<String> create(final String resourceGroup) {\n         checkNotNull(resourceGroup, \"resourceGroup cannot be null\");\n         return new Predicate<String>() {\n            @Override\n            public boolean apply(final String name) {\n               checkNotNull(name, \"name cannot be null\");\n               return resourceAvailable.apply(new Supplier<Provisionable>() {\n                  @Override\n                  public Provisionable get() {\n                     Image img = api.getVirtualMachineImageApi(resourceGroup).get(name);\n                     return img == null ? null : img.properties();\n                  }\n               });\n            }\n         };\n      }\n   }\n\n   public static class VirtualNetworkGatewayAvailablePredicateFactory {\n      private final AzureComputeApi api;\n      private final Predicate<Supplier<Provisionable>> resourceAvailable;\n\n      VirtualNetworkGatewayAvailablePredicateFactory(final AzureComputeApi api,\n            Predicate<Supplier<Provisionable>> resourceAvailable) {\n         this.api = checkNotNull(api, \"api cannot be null\");\n         this.resourceAvailable = resourceAvailable;\n      }\n\n      public Predicate<String> create(final String resourceGroup) {\n         checkNotNull(resourceGroup, \"resourceGroup cannot be null\");\n         return new Predicate<String>() {\n            @Override\n            public boolean apply(final String name) {\n               checkNotNull(name, \"name cannot be null\");\n               return resourceAvailable.apply(new Supplier<Provisionable>() {\n                  @Override\n                  public Provisionable get() {\n                     VirtualNetworkGateway vng = api.getVirtualNetworkGatewayApi(resourceGroup).get(name);\n                     return vng == null ? null : vng.properties();\n                  }\n               });\n            }\n         };\n      }\n   }\n\n   @Provides\n   @Named(VAULT_DELETE_STATUS)\n   protected VaultPredicates.DeletedVaultStatusPredicateFactory provideDeletedVaultStatusPredicateFactory(\n         final AzureComputeApi api, @Named(OPERATION_TIMEOUT) Integer operationTimeout, final PollPeriod pollPeriod) {\n      return new VaultPredicates.DeletedVaultStatusPredicateFactory(api, operationTimeout.longValue(),\n            pollPeriod.pollInitialPeriod, pollPeriod.pollMaxPeriod);\n   }\n\n   public static class VaultPredicates {\n      public static class DeletedVaultStatusPredicateFactory {\n         private final AzureComputeApi api;\n         private final long operationTimeout;\n         private final long initialPeriod;\n         private final long maxPeriod;\n\n         DeletedVaultStatusPredicateFactory(final AzureComputeApi api, final long operationTimeout,\n               final long initialPeriod, final long maxPeriod) {\n            this.api = checkNotNull(api, \"api cannot be null\");\n            this.operationTimeout = operationTimeout;\n            this.initialPeriod = initialPeriod;\n            this.maxPeriod = maxPeriod;\n         }\n\n         public Predicate<String> create(final String resourceGroup, final boolean shouldBePresent) {\n            checkNotNull(resourceGroup, \"resourceGroup cannot be null\");\n            return retry(new Predicate<String>() {\n               @Override\n               public boolean apply(final String name) {\n                  checkNotNull(name, \"name cannot be null\");\n                  List<Vault.DeletedVault> vaults = api.getVaultApi(resourceGroup).listDeletedVaults();\n                  return shouldBePresent == Iterables.any(vaults, new Predicate<Vault.DeletedVault>() {\n                     @Override\n                     public boolean apply(Vault.DeletedVault input) {\n                        return input.name().equals(name);\n                     }\n                  });\n               }\n            }, operationTimeout, initialPeriod, maxPeriod);\n         }\n      }\n   }\n\n   @Provides\n   @Named(VAULT_KEY_DELETED_STATUS)\n   protected VaultKeyPredicates.DeletedKeyStatusPredicateFactory provideDeletedKeyStatusPredicateFactory(\n         final AzureComputeApi api, @Named(OPERATION_TIMEOUT) Integer operationTimeout, final PollPeriod pollPeriod) {\n      return new VaultKeyPredicates.DeletedKeyStatusPredicateFactory(api, operationTimeout.longValue(),\n            pollPeriod.pollInitialPeriod, pollPeriod.pollMaxPeriod);\n   }\n\n   @Provides\n   @Named(VAULT_KEY_RECOVERABLE_STATUS)\n   protected VaultKeyPredicates.RecoverableKeyStatusPredicateFactory provideRecoverableKeyStatusPredicateFactory(\n         final AzureComputeApi api, @Named(OPERATION_TIMEOUT) Integer operationTimeout, final PollPeriod pollPeriod) {\n      return new VaultKeyPredicates.RecoverableKeyStatusPredicateFactory(api, operationTimeout.longValue(),\n            pollPeriod.pollInitialPeriod, pollPeriod.pollMaxPeriod);\n   }\n\n   public static class VaultKeyPredicates {\n      public static class DeletedKeyStatusPredicateFactory {\n         private final AzureComputeApi api;\n         private final long operationTimeout;\n         private final long initialPeriod;\n         private final long maxPeriod;\n\n         DeletedKeyStatusPredicateFactory(final AzureComputeApi api, final long operationTimeout,\n               final long initialPeriod, final long maxPeriod) {\n            this.api = checkNotNull(api, \"api cannot be null\");\n            this.operationTimeout = operationTimeout;\n            this.initialPeriod = initialPeriod;\n            this.maxPeriod = maxPeriod;\n         }\n\n         public Predicate<String> create(final String resourceGroup, final URI vaultUri, final boolean shouldBePresent) {\n            checkNotNull(resourceGroup, \"resourceGroup cannot be null\");\n            checkNotNull(vaultUri, \"vaultUri cannot be null\");\n            return retry(new Predicate<String>() {\n               @Override\n               public boolean apply(final String name) {\n                  checkNotNull(name, \"name cannot be null\");\n                  DeletedKeyBundle key = api.getVaultApi(resourceGroup).getDeletedKey(vaultUri, name);\n                  return shouldBePresent == (key != null);\n               }\n            }, operationTimeout, initialPeriod, maxPeriod);\n         }\n      }\n\n      public static class RecoverableKeyStatusPredicateFactory {\n         private final AzureComputeApi api;\n         private final long operationTimeout;\n         private final long initialPeriod;\n         private final long maxPeriod;\n\n         RecoverableKeyStatusPredicateFactory(final AzureComputeApi api, final long operationTimeout,\n               final long initialPeriod, final long maxPeriod) {\n            this.api = checkNotNull(api, \"api cannot be null\");\n            this.operationTimeout = operationTimeout;\n            this.initialPeriod = initialPeriod;\n            this.maxPeriod = maxPeriod;\n         }\n\n         public Predicate<String> create(final String resourceGroup, final URI vaultUri, final boolean isRecovered) {\n            checkNotNull(resourceGroup, \"resourceGroup cannot be null\");\n            checkNotNull(vaultUri, \"vaultUri cannot be null\");\n            return retry(new Predicate<String>() {\n               @Override\n               public boolean apply(final String name) {\n                  checkNotNull(name, \"name cannot be null\");\n                  KeyBundle key = api.getVaultApi(resourceGroup).getKey(vaultUri, name);\n                  return key != null ? (isRecovered ? true : key.attributes().recoveryLevel().contains(\"Recoverable\"))\n                        : false;\n               }\n            }, operationTimeout, initialPeriod, maxPeriod);\n         }\n      }\n   }\n\n   @Provides\n   @Named(VAULT_SECRET_DELETE_STATUS)\n   protected VaultSecretPredicates.DeletedSecretStatusPredicateFactory provideDeletedSecretStatusPredicateFactory(\n         final AzureComputeApi api, @Named(OPERATION_TIMEOUT) Integer operationTimeout, final PollPeriod pollPeriod) {\n      return new VaultSecretPredicates.DeletedSecretStatusPredicateFactory(api, operationTimeout.longValue(),\n            pollPeriod.pollInitialPeriod, pollPeriod.pollMaxPeriod);\n   }\n\n   @Provides\n   @Named(VAULT_SECRET_RECOVERABLE_STATUS)\n   protected VaultSecretPredicates.RecoverableSecretStatusPredicateFactory provideRecoverableSecretStatusPredicateFactory(\n         final AzureComputeApi api, @Named(OPERATION_TIMEOUT) Integer operationTimeout, final PollPeriod pollPeriod) {\n      return new VaultSecretPredicates.RecoverableSecretStatusPredicateFactory(api, operationTimeout.longValue(),\n            pollPeriod.pollInitialPeriod, pollPeriod.pollMaxPeriod);\n   }\n\n   public static class VaultSecretPredicates {\n      public static class DeletedSecretStatusPredicateFactory {\n         private final AzureComputeApi api;\n         private final long operationTimeout;\n         private final long initialPeriod;\n         private final long maxPeriod;\n\n         DeletedSecretStatusPredicateFactory(final AzureComputeApi api, final long operationTimeout,\n               final long initialPeriod, final long maxPeriod) {\n            this.api = checkNotNull(api, \"api cannot be null\");\n            this.operationTimeout = operationTimeout;\n            this.initialPeriod = initialPeriod;\n            this.maxPeriod = maxPeriod;\n         }\n\n         public Predicate<String> create(final String resourceGroup, final URI vaultUri, final boolean shouldBePresent) {\n            checkNotNull(resourceGroup, \"resourceGroup cannot be null\");\n            checkNotNull(vaultUri, \"vaultUri cannot be null\");\n            return retry(new Predicate<String>() {\n               @Override\n               public boolean apply(final String name) {\n                  checkNotNull(name, \"name cannot be null\");\n                  DeletedSecretBundle secret = api.getVaultApi(resourceGroup).getDeletedSecret(vaultUri, name);\n                  return shouldBePresent == (secret != null);\n               }\n            }, operationTimeout, initialPeriod, maxPeriod);\n         }\n      }\n\n      public static class RecoverableSecretStatusPredicateFactory {\n         private final AzureComputeApi api;\n         private final long operationTimeout;\n         private final long initialPeriod;\n         private final long maxPeriod;\n\n         RecoverableSecretStatusPredicateFactory(final AzureComputeApi api, final long operationTimeout,\n               final long initialPeriod, final long maxPeriod) {\n            this.api = checkNotNull(api, \"api cannot be null\");\n            this.operationTimeout = operationTimeout;\n            this.initialPeriod = initialPeriod;\n            this.maxPeriod = maxPeriod;\n         }\n\n         public Predicate<String> create(final String resourceGroup, final URI vaultUri, final boolean isRecovered) {\n            checkNotNull(resourceGroup, \"resourceGroup cannot be null\");\n            checkNotNull(vaultUri, \"vaultUri cannot be null\");\n            return retry(new Predicate<String>() {\n               @Override\n               public boolean apply(final String name) {\n                  checkNotNull(name, \"name cannot be null\");\n                  SecretBundle secret = api.getVaultApi(resourceGroup).getSecret(vaultUri, name, null);\n                  return secret != null ? (isRecovered ? true : secret.attributes().recoveryLevel()\n                        .contains(\"Recoverable\")) : false;\n               }\n            }, operationTimeout, initialPeriod, maxPeriod);\n         }\n      }\n   }\n\n   @Provides\n   @Named(VAULT_CERTIFICATE_DELETE_STATUS)\n   protected VaultCertificatePredicates.DeletedCertificateStatusPredicateFactory provideDeletedCertificateStatusPredicateFactory(\n         final AzureComputeApi api, @Named(OPERATION_TIMEOUT) Integer operationTimeout, final PollPeriod pollPeriod) {\n      return new VaultCertificatePredicates.DeletedCertificateStatusPredicateFactory(api, operationTimeout.longValue(),\n            pollPeriod.pollInitialPeriod, pollPeriod.pollMaxPeriod);\n   }\n\n   @Provides\n   @Named(VAULT_CERTIFICATE_RECOVERABLE_STATUS)\n   protected VaultCertificatePredicates.RecoverableCertificateStatusPredicateFactory provideRecoverableCertificateStatusPredicateFactory(\n         final AzureComputeApi api, @Named(OPERATION_TIMEOUT) Integer operationTimeout, final PollPeriod pollPeriod) {\n      return new VaultCertificatePredicates.RecoverableCertificateStatusPredicateFactory(api,\n            operationTimeout.longValue(), pollPeriod.pollInitialPeriod, pollPeriod.pollMaxPeriod);\n   }\n\n   @Provides\n   @Named(VAULT_CERTIFICATE_OPERATION_STATUS)\n   protected VaultCertificatePredicates.CertificateOperationStatusPredicateFactory provideCertificateOperationStatusPredicateFactory(\n         final AzureComputeApi api, @Named(OPERATION_TIMEOUT) Integer operationTimeout, final PollPeriod pollPeriod) {\n      return new VaultCertificatePredicates.CertificateOperationStatusPredicateFactory(api,\n            operationTimeout.longValue(), pollPeriod.pollInitialPeriod, pollPeriod.pollMaxPeriod);\n   }\n\n   public static class VaultCertificatePredicates {\n      public static class DeletedCertificateStatusPredicateFactory {\n         private final AzureComputeApi api;\n         private final long operationTimeout;\n         private final long initialPeriod;\n         private final long maxPeriod;\n\n         DeletedCertificateStatusPredicateFactory(final AzureComputeApi api, final long operationTimeout,\n               final long initialPeriod, final long maxPeriod) {\n            this.api = checkNotNull(api, \"api cannot be null\");\n            this.operationTimeout = operationTimeout;\n            this.initialPeriod = initialPeriod;\n            this.maxPeriod = maxPeriod;\n         }\n\n         public Predicate<String> create(final String resourceGroup, final URI vaultUri, final boolean shouldBePresent) {\n            checkNotNull(resourceGroup, \"resourceGroup cannot be null\");\n            checkNotNull(vaultUri, \"vaultUri cannot be null\");\n            return retry(new Predicate<String>() {\n               @Override\n               public boolean apply(final String name) {\n                  checkNotNull(name, \"name cannot be null\");\n                  DeletedCertificateBundle cert = api.getVaultApi(resourceGroup).getDeletedCertificate(vaultUri, name);\n                  return shouldBePresent == (cert != null);\n               }\n            }, operationTimeout, initialPeriod, maxPeriod);\n         }\n      }\n\n      public static class RecoverableCertificateStatusPredicateFactory {\n         private final AzureComputeApi api;\n         private final long operationTimeout;\n         private final long initialPeriod;\n         private final long maxPeriod;\n\n         RecoverableCertificateStatusPredicateFactory(final AzureComputeApi api, final long operationTimeout,\n               final long initialPeriod, final long maxPeriod) {\n            this.api = checkNotNull(api, \"api cannot be null\");\n            this.operationTimeout = operationTimeout;\n            this.initialPeriod = initialPeriod;\n            this.maxPeriod = maxPeriod;\n         }\n\n         public Predicate<String> create(final String resourceGroup, final URI vaultUri, final boolean isImport) {\n            checkNotNull(resourceGroup, \"resourceGroup cannot be null\");\n            checkNotNull(vaultUri, \"vaultUri cannot be null\");\n            return retry(new Predicate<String>() {\n               @Override\n               public boolean apply(final String name) {\n                  checkNotNull(name, \"name cannot be null\");\n                  CertificateBundle cert = api.getVaultApi(resourceGroup).getCertificate(vaultUri, name, null);\n                  return cert != null ? (isImport ? true : cert.attributes().recoveryLevel().contains(\"Recoverable\"))\n                        : false;\n\n               }\n            }, operationTimeout, initialPeriod, maxPeriod);\n         }\n      }\n\n      public static class CertificateOperationStatusPredicateFactory {\n         private final AzureComputeApi api;\n         private final long operationTimeout;\n         private final long initialPeriod;\n         private final long maxPeriod;\n\n         CertificateOperationStatusPredicateFactory(final AzureComputeApi api, final long operationTimeout,\n               final long initialPeriod, final long maxPeriod) {\n            this.api = checkNotNull(api, \"api cannot be null\");\n            this.operationTimeout = operationTimeout;\n            this.initialPeriod = initialPeriod;\n            this.maxPeriod = maxPeriod;\n         }\n\n         public Predicate<String> create(final String resourceGroup, final URI vaultUri, final boolean isCreate) {\n            checkNotNull(resourceGroup, \"resourceGroup cannot be null\");\n            checkNotNull(vaultUri, \"vaultUri cannot be null\");\n            return retry(new Predicate<String>() {\n               @Override\n               public boolean apply(final String name) {\n                  checkNotNull(name, \"name cannot be null\");\n                  CertificateOperation certOp = api.getVaultApi(resourceGroup).getCertificateOperation(vaultUri, name);\n                  return isCreate ? ((certOp != null) ? !certOp.status().equals(\"inProgress\") : false)\n                        : (certOp == null);\n               }\n            }, operationTimeout, initialPeriod, maxPeriod);\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/compute/domain/LocationAndName.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.compute.domain;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.Iterables;\n\n@AutoValue\npublic abstract class LocationAndName {\n\n   public abstract String location();\n   public abstract String name();\n   \n   protected LocationAndName() {\n      \n   }\n   \n   public static LocationAndName fromSlashEncoded(String id) {\n      Iterable<String> parts = Splitter.on('/').split(checkNotNull(id, \"id\"));\n      checkArgument(Iterables.size(parts) == 2, \"id must be in format location/name\");\n      return new AutoValue_LocationAndName(Iterables.get(parts, 0), Iterables.get(parts, 1));\n   }\n\n   public static LocationAndName fromLocationAndName(String location, String name) {\n      return new AutoValue_LocationAndName(location, name);\n   }\n\n   public String slashEncode() {\n      return location() + \"/\" + name();\n   }\n   \n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/compute/domain/ResourceGroupAndName.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.compute.domain;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.Iterables;\n\n@AutoValue\npublic abstract class ResourceGroupAndName {\n\n   public abstract String resourceGroup();\n   public abstract String name();\n   \n   protected ResourceGroupAndName() {\n      \n   }\n   \n   public static ResourceGroupAndName fromSlashEncoded(String id) {\n      Iterable<String> parts = Splitter.on('/').split(checkNotNull(id, \"id\"));\n      checkArgument(Iterables.size(parts) == 2, \"id must be in format resourcegroup/name\");\n      return new AutoValue_ResourceGroupAndName(Iterables.get(parts, 0), Iterables.get(parts, 1));\n   }\n\n   public static ResourceGroupAndName fromResourceGroupAndName(String resourceGroup, String name) {\n      return new AutoValue_ResourceGroupAndName(resourceGroup, name);\n   }\n\n   public String slashEncode() {\n      return resourceGroup() + \"/\" + name();\n   }\n   \n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/compute/domain/ResourceGroupAndNameAndIngressRules.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.compute.domain;\n\nimport static org.jclouds.azurecompute.arm.compute.domain.ResourceGroupAndName.fromResourceGroupAndName;\n\nimport java.util.Arrays;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.base.Objects;\n\n@AutoValue\npublic abstract class ResourceGroupAndNameAndIngressRules {\n\n   abstract ResourceGroupAndName resourceGroupAndName(); // Intentionally hidden\n   \n   public abstract String location();\n\n   @SuppressWarnings(\"mutable\")\n   public abstract int[] inboundPorts();\n\n   ResourceGroupAndNameAndIngressRules() {\n\n   }\n\n   public static ResourceGroupAndNameAndIngressRules create(String resourceGroup, String location, String name,\n         int[] inboundPorts) {\n      return new AutoValue_ResourceGroupAndNameAndIngressRules(fromResourceGroupAndName(resourceGroup, name), location,\n            Arrays.copyOf(inboundPorts, inboundPorts.length));\n   }\n\n   public String name() {\n      return resourceGroupAndName().name();\n   }\n\n   public String resourceGroup() {\n      return resourceGroupAndName().resourceGroup();\n   }\n\n   // Intentionally delegate equals and hashcode to the fields in the parent\n   // class so that we can search only by region/id in a map\n\n   @Override\n   public final int hashCode() {\n      return Objects.hashCode(resourceGroup(), name());\n   }\n\n   @edu.umd.cs.findbugs.annotations.SuppressFBWarnings(value = \"EQ_UNUSUAL\")\n   @Override\n   public final boolean equals(Object obj) {\n      if (obj == this) {\n         return true;\n      }\n      if (!(obj instanceof ResourceGroupAndName)) {\n         return false;\n      }\n      ResourceGroupAndName that = (ResourceGroupAndName) obj;\n      return Objects.equal(resourceGroup(), that.resourceGroup()) && Objects.equal(name(), that.name());\n   }\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/compute/extensions/AzureComputeImageExtension.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.compute.extensions;\n\nimport static com.google.common.base.Functions.compose;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkState;\nimport static org.jclouds.azurecompute.arm.compute.domain.ResourceGroupAndName.fromSlashEncoded;\nimport static org.jclouds.azurecompute.arm.config.AzureComputeProperties.TIMEOUT_RESOURCE_DELETED;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_SUSPENDED;\n\nimport java.net.URI;\nimport java.util.concurrent.Callable;\n\nimport jakarta.annotation.Resource;\n\nimport org.jclouds.Constants;\nimport org.jclouds.azurecompute.arm.AzureComputeApi;\nimport org.jclouds.azurecompute.arm.compute.config.AzurePredicatesModule.ImageAvailablePredicateFactory;\nimport org.jclouds.azurecompute.arm.compute.config.AzurePredicatesModule.VirtualMachineInStatePredicateFactory;\nimport org.jclouds.azurecompute.arm.compute.domain.ResourceGroupAndName;\nimport org.jclouds.azurecompute.arm.compute.functions.CustomImageToVMImage;\nimport org.jclouds.azurecompute.arm.domain.IdReference;\nimport org.jclouds.azurecompute.arm.domain.ImageProperties;\nimport org.jclouds.azurecompute.arm.domain.VMImage;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachine;\nimport org.jclouds.compute.domain.CloneImageTemplate;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.ImageTemplate;\nimport org.jclouds.compute.domain.ImageTemplateBuilder;\nimport org.jclouds.compute.extensions.ImageExtension;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.inject.Inject;\nimport com.google.inject.name.Named;\n\npublic class AzureComputeImageExtension implements ImageExtension {\n   public static final String CUSTOM_IMAGE_OFFER = \"custom\";\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   private final AzureComputeApi api;\n   private final ListeningExecutorService userExecutor;\n   private final ImageAvailablePredicateFactory imageAvailablePredicate;\n   private final VirtualMachineInStatePredicateFactory nodeSuspendedPredicate;\n   private final Function<VMImage, Image> vmImageToImage;\n   private final Predicate<URI> resourceDeleted;\n   private final CustomImageToVMImage customImagetoVmImage;\n\n   @Inject\n   AzureComputeImageExtension(AzureComputeApi api, ImageAvailablePredicateFactory imageAvailablePredicate,\n         @Named(TIMEOUT_NODE_SUSPENDED) VirtualMachineInStatePredicateFactory nodeSuspendedPredicate,\n         @Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor,\n         Function<VMImage, Image> vmImageToImage, @Named(TIMEOUT_RESOURCE_DELETED) Predicate<URI> resourceDeleted,\n         CustomImageToVMImage customImagetoVmImage) {\n      this.api = api;\n      this.imageAvailablePredicate = imageAvailablePredicate;\n      this.nodeSuspendedPredicate = nodeSuspendedPredicate;\n      this.userExecutor = userExecutor;\n      this.vmImageToImage = vmImageToImage;\n      this.resourceDeleted = resourceDeleted;\n      this.customImagetoVmImage = customImagetoVmImage;\n   }\n\n   @Override\n   public ImageTemplate buildImageTemplateFromNode(String name, String id) {\n      return new ImageTemplateBuilder.CloneImageTemplateBuilder().nodeId(id).name(name.toLowerCase()).build();\n   }\n\n   @Override\n   public ListenableFuture<Image> createImage(ImageTemplate template) {\n      final CloneImageTemplate cloneTemplate = (CloneImageTemplate) template;\n      final ResourceGroupAndName resourceGroupAndName = fromSlashEncoded(cloneTemplate.getSourceNodeId());\n      final String resourceGroupName = resourceGroupAndName.resourceGroup();\n      final String vmName = resourceGroupAndName.name();\n\n      final VirtualMachine vm = api.getVirtualMachineApi(resourceGroupName).get(vmName);\n      final IdReference vmIdRef = IdReference.create(vm.id());\n\n      logger.debug(\">> stopping node %s...\", cloneTemplate.getSourceNodeId());\n      api.getVirtualMachineApi(resourceGroupName).stop(vmName);\n      checkState(nodeSuspendedPredicate.create(resourceGroupName).apply(vmName),\n            \"Node %s was not suspended within the configured time limit\", cloneTemplate.getSourceNodeId());\n\n      return userExecutor.submit(new Callable<Image>() {\n         @Override\n         public Image call() throws Exception {\n            logger.debug(\">> generalizing virtal machine %s...\", vmName);\n\n            api.getVirtualMachineApi(resourceGroupName).generalize(vmName);\n\n            org.jclouds.azurecompute.arm.domain.Image imageFromVM = api.getVirtualMachineImageApi(resourceGroupName)\n                  .createOrUpdate(cloneTemplate.getName(), vm.location(),\n                        ImageProperties.builder().sourceVirtualMachine(vmIdRef).build());\n\n            checkState(imageAvailablePredicate.create(resourceGroupName).apply(imageFromVM.name()),\n                  \"Image for node %s was not created within the configured time limit\", cloneTemplate.getName());\n\n            return compose(vmImageToImage, customImagetoVmImage).apply(imageFromVM);\n         }\n      });\n   }\n\n   @Override\n   public boolean deleteImage(String id) {\n      VMImage image = VMImage.decodeFieldsFromUniqueId(id);\n      checkArgument(image.custom(), \"Only custom images can be deleted\");\n\n      logger.debug(\">> deleting image %s\", id);\n      URI uri = api.getVirtualMachineImageApi(image.resourceGroup()).delete(image.name());\n      return resourceDeleted.apply(uri);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/compute/extensions/AzureComputeSecurityGroupExtension.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.compute.extensions;\n\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.common.base.Predicates.equalTo;\nimport static com.google.common.base.Predicates.notNull;\nimport static com.google.common.collect.Iterables.any;\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.transform;\nimport static org.jclouds.azurecompute.arm.config.AzureComputeProperties.TIMEOUT_RESOURCE_DELETED;\nimport static org.jclouds.azurecompute.arm.domain.IdReference.extractName;\nimport static org.jclouds.azurecompute.arm.domain.IdReference.extractResourceGroup;\n\nimport java.net.URI;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Set;\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\n\nimport org.jclouds.azurecompute.arm.AzureComputeApi;\nimport org.jclouds.azurecompute.arm.compute.config.AzurePredicatesModule.SecurityGroupAvailablePredicateFactory;\nimport org.jclouds.azurecompute.arm.compute.config.AzurePredicatesModule.SecurityGroupRuleAvailablePredicateFactory;\nimport org.jclouds.azurecompute.arm.compute.domain.ResourceGroupAndName;\nimport org.jclouds.azurecompute.arm.domain.NetworkInterfaceCard;\nimport org.jclouds.azurecompute.arm.domain.NetworkProfile.NetworkInterface;\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityGroup;\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityGroupProperties;\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityRule;\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityRuleProperties;\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityRuleProperties.Access;\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityRuleProperties.Direction;\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityRuleProperties.Protocol;\nimport org.jclouds.azurecompute.arm.domain.ResourceGroup;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachine;\nimport org.jclouds.azurecompute.arm.features.NetworkSecurityGroupApi;\nimport org.jclouds.azurecompute.arm.features.NetworkSecurityRuleApi;\nimport org.jclouds.compute.domain.SecurityGroup;\nimport org.jclouds.compute.domain.SecurityGroupBuilder;\nimport org.jclouds.compute.extensions.SecurityGroupExtension;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.domain.Location;\nimport org.jclouds.location.Region;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.net.domain.IpPermission;\nimport org.jclouds.net.domain.IpProtocol;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Objects;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Multimap;\nimport com.google.common.collect.Ordering;\n\npublic class AzureComputeSecurityGroupExtension implements SecurityGroupExtension {\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   private final AzureComputeApi api;\n   private final Function<NetworkSecurityGroup, SecurityGroup> securityGroupConverter;\n   private final SecurityGroupAvailablePredicateFactory securityGroupAvailable;\n   private final SecurityGroupRuleAvailablePredicateFactory securityGroupRuleAvailable;\n   private final Predicate<URI> resourceDeleted;\n   private final LoadingCache<String, ResourceGroup> defaultResourceGroup;\n   private final Supplier<Set<String>> regionIds;\n\n   @Inject\n   AzureComputeSecurityGroupExtension(AzureComputeApi api, Function<NetworkSecurityGroup, SecurityGroup> groupConverter,\n         SecurityGroupAvailablePredicateFactory securityGroupAvailable, SecurityGroupRuleAvailablePredicateFactory securityGroupRuleAvailable,\n         @Named(TIMEOUT_RESOURCE_DELETED) Predicate<URI> resourceDeleted,\n         LoadingCache<String, ResourceGroup> defaultResourceGroup,\n         @Region Supplier<Set<String>> regionIds) {\n      this.api = api;\n      this.securityGroupConverter = groupConverter;\n      this.securityGroupAvailable = securityGroupAvailable;\n      this.securityGroupRuleAvailable = securityGroupRuleAvailable;\n      this.resourceDeleted = resourceDeleted;\n      this.defaultResourceGroup = defaultResourceGroup;\n      this.regionIds = regionIds;\n   }\n\n   @Override\n   public Set<SecurityGroup> listSecurityGroupsInLocation(Location location) {\n      return securityGroupsInLocations(ImmutableSet.of(location.getId()));\n   }\n\n   @Override\n   public Set<SecurityGroup> listSecurityGroups() {\n      return securityGroupsInLocations(regionIds.get());\n   }\n\n   private Set<SecurityGroup> securityGroupsInLocations(final Set<String> locations) {\n      final ImmutableSet<SecurityGroup> allSecurityGroups = ImmutableSet.copyOf(transform(filter(api.getNetworkSecurityGroupApi(null).listAll(), notNull()), securityGroupConverter));\n      return ImmutableSet.copyOf(filter(allSecurityGroups, new Predicate<SecurityGroup>() {\n         @Override\n         public boolean apply(SecurityGroup input) {\n            return input.getLocation() != null && locations.contains(input.getLocation().getId());\n         }\n      }));\n   }\n\n   @Override\n   public Set<SecurityGroup> listSecurityGroupsForNode(String nodeId) {\n      logger.debug(\">> getting security groups for node %s...\", nodeId);\n\n      final ResourceGroupAndName resourceGroupAndName = ResourceGroupAndName.fromSlashEncoded(nodeId);\n\n      VirtualMachine vm = api.getVirtualMachineApi(resourceGroupAndName.resourceGroup()).get(\n            resourceGroupAndName.name());\n      if (vm == null) {\n         throw new IllegalArgumentException(\"Node \" + nodeId + \" was not found\");\n      }\n      List<NetworkInterface> networkInterfaces = vm.properties().networkProfile().networkInterfaces();\n      List<NetworkSecurityGroup> networkGroups = new ArrayList<NetworkSecurityGroup>();\n\n      for (NetworkInterface networkInterfaceCardIdReference : networkInterfaces) {\n         String nicName = extractName(networkInterfaceCardIdReference.id());\n         String nicResourceGroup = extractResourceGroup(networkInterfaceCardIdReference.id());\n         NetworkInterfaceCard card = api.getNetworkInterfaceCardApi(nicResourceGroup).get(nicName);\n         if (card != null && card.properties().networkSecurityGroup() != null) {\n            String secGroupName = card.properties().networkSecurityGroup().name();\n            String sgResourceGroup = card.properties().networkSecurityGroup().resourceGroup();\n            NetworkSecurityGroup group = api.getNetworkSecurityGroupApi(sgResourceGroup).get(secGroupName);\n            networkGroups.add(group);\n         }\n      }\n\n      return ImmutableSet.copyOf(transform(filter(networkGroups, notNull()), securityGroupConverter));\n   }\n\n   @Override\n   public SecurityGroup getSecurityGroupById(String id) {\n      logger.debug(\">> getting security group %s...\", id);\n      final ResourceGroupAndName resourceGroupAndName = ResourceGroupAndName.fromSlashEncoded(id);\n      NetworkSecurityGroup securityGroup = api.getNetworkSecurityGroupApi(resourceGroupAndName.resourceGroup()).get(\n            resourceGroupAndName.name());\n      return securityGroup == null ? null : securityGroupConverter.apply(securityGroup);\n   }\n\n   @Override\n   public SecurityGroup createSecurityGroup(String name, Location location) {\n      ResourceGroup resourceGroup = defaultResourceGroup.getUnchecked(location.getId());\n\n      logger.debug(\">> creating security group %s in %s...\", name, location);\n\n      SecurityGroupBuilder builder = new SecurityGroupBuilder();\n      builder.name(name);\n      builder.location(location);\n      \n      NetworkSecurityGroup sg = api.getNetworkSecurityGroupApi(resourceGroup.name()).createOrUpdate(name,\n            location.getId(), null, NetworkSecurityGroupProperties.builder().build());\n      \n      checkState(securityGroupAvailable.create(resourceGroup.name()).apply(name),\n            \"Security group was not created in the configured timeout\");\n\n      return securityGroupConverter.apply(sg);\n   }\n\n   @Override\n   public boolean removeSecurityGroup(String id) {\n      logger.debug(\">> deleting security group %s...\", id);\n\n      final ResourceGroupAndName resourceGroupAndName = ResourceGroupAndName.fromSlashEncoded(id);\n      URI uri = api.getNetworkSecurityGroupApi(resourceGroupAndName.resourceGroup())\n            .delete(resourceGroupAndName.name());\n\n      // https://docs.microsoft.com/en-us/rest/api/network/virtualnetwork/delete-a-network-security-group\n      if (uri != null) {\n         // 202-Accepted if resource exists and the request is accepted.\n         return resourceDeleted.apply(uri);\n      } else {\n         // 204-No Content if resource does not exist.\n         return false;\n      }\n   }\n\n   @Override\n   public SecurityGroup addIpPermission(IpPermission ipPermission, SecurityGroup group) {\n      return addIpPermission(ipPermission.getIpProtocol(), ipPermission.getFromPort(), ipPermission.getToPort(),\n            ipPermission.getTenantIdGroupNamePairs(), ipPermission.getCidrBlocks(), ipPermission.getGroupIds(), group);\n   }\n\n   @Override\n   public SecurityGroup removeIpPermission(IpPermission ipPermission, SecurityGroup group) {\n      return removeIpPermission(ipPermission.getIpProtocol(), ipPermission.getFromPort(), ipPermission.getToPort(),\n            ipPermission.getTenantIdGroupNamePairs(), ipPermission.getCidrBlocks(), ipPermission.getGroupIds(), group);\n   }\n\n   @Override\n   public SecurityGroup addIpPermission(IpProtocol protocol, int startPort, int endPort,\n         Multimap<String, String> tenantIdGroupNamePairs, Iterable<String> ipRanges, Iterable<String> groupIds,\n         SecurityGroup group) {\n      String portRange = startPort + \"-\" + endPort;\n      String ruleName = \"ingress-\" + protocol.name().toLowerCase() + \"-\" + portRange;\n\n      logger.debug(\">> adding ip permission [%s] to %s...\", ruleName, group.getName());\n\n      // TODO: Support Azure network tags somehow?\n\n      final ResourceGroupAndName resourceGroupAndName = ResourceGroupAndName.fromSlashEncoded(group.getId());\n\n      NetworkSecurityGroupApi groupApi = api.getNetworkSecurityGroupApi(resourceGroupAndName.resourceGroup());\n      NetworkSecurityGroup networkSecurityGroup = groupApi.get(resourceGroupAndName.name());\n\n      if (networkSecurityGroup == null) {\n         throw new IllegalArgumentException(\"Security group \" + group.getName() + \" was not found\");\n      }\n\n      NetworkSecurityRuleApi ruleApi = api.getNetworkSecurityRuleApi(resourceGroupAndName.resourceGroup(), networkSecurityGroup.name());\n      int nextPriority = getRuleStartingPriority(networkSecurityGroup);\n\n      for (String ipRange : ipRanges) {\n         NetworkSecurityRuleProperties properties = NetworkSecurityRuleProperties.builder()\n               .protocol(Protocol.fromValue(protocol.name()))\n               .sourceAddressPrefix(ipRange)\n               .sourcePortRange(\"*\")\n               .destinationAddressPrefix(\"*\")\n               .destinationPortRange(portRange)\n               .direction(Direction.Inbound)\n               .access(Access.Allow)\n               .priority(nextPriority++)\n               .build();\n\n         logger.debug(\">> creating network security rule %s for %s...\", ruleName, ipRange);\n\n         ruleApi.createOrUpdate(ruleName, properties);\n\n         checkState(securityGroupRuleAvailable.create(resourceGroupAndName.resourceGroup(), networkSecurityGroup.name()).apply(ruleName),\n               \"Security group was not updated in the configured timeout\");\n      }\n\n      return getSecurityGroupById(group.getId());\n   }\n\n   @Override\n   public SecurityGroup removeIpPermission(final IpProtocol protocol, int startPort, int endPort,\n         Multimap<String, String> tenantIdGroupNamePairs, final Iterable<String> ipRanges, Iterable<String> groupIds,\n         SecurityGroup group) {\n      final String portRange = startPort + \"-\" + endPort;\n      String ruleName = \"ingress-\" + protocol.name().toLowerCase() + \"-\" + portRange;\n\n      logger.debug(\">> deleting ip permissions matching [%s] from %s...\", ruleName, group.getName());\n\n      final ResourceGroupAndName resourceGroupAndName = ResourceGroupAndName.fromSlashEncoded(group.getId());\n\n      NetworkSecurityGroupApi groupApi = api.getNetworkSecurityGroupApi(resourceGroupAndName.resourceGroup());\n      NetworkSecurityGroup networkSecurityGroup = groupApi.get(resourceGroupAndName.name());\n\n      if (networkSecurityGroup == null) {\n         throw new IllegalArgumentException(\"Security group \" + group.getName() + \" was not found\");\n      }\n\n      NetworkSecurityRuleApi ruleApi = api.getNetworkSecurityRuleApi(resourceGroupAndName.resourceGroup(),\n            networkSecurityGroup.name());\n      Iterable<NetworkSecurityRule> rules = filter(ruleApi.list(), new Predicate<NetworkSecurityRule>() {\n         @Override\n         public boolean apply(NetworkSecurityRule input) {\n            NetworkSecurityRuleProperties props = input.properties();\n            return Objects.equal(portRange, props.destinationPortRange())\n                  && Objects.equal(Protocol.fromValue(protocol.name()), props.protocol())\n                  && Objects.equal(Direction.Inbound, props.direction()) //\n                  && Objects.equal(Access.Allow, props.access())\n                  && any(ipRanges, equalTo(props.sourceAddressPrefix().replace(\"*\", \"0.0.0.0/0\")));\n         }\n      });\n\n      for (NetworkSecurityRule matchingRule : rules) {\n         logger.debug(\">> deleting network security rule %s from %s...\", matchingRule.name(), group.getName());\n         URI uri = ruleApi.delete(matchingRule.name());\n         if (uri != null) {\n            checkState(resourceDeleted.apply(uri), \"Rule %s could not be deleted in the configured timeout\", matchingRule.id());\n         }\n\n      }\n\n      return getSecurityGroupById(group.getId());\n   }\n\n   @Override\n   public boolean supportsTenantIdGroupNamePairs() {\n      return false;\n   }\n\n   @Override\n   public boolean supportsTenantIdGroupIdPairs() {\n      return false;\n   }\n\n   @Override\n   public boolean supportsGroupIds() {\n      return false;\n   }\n\n   @Override\n   public boolean supportsPortRangesForGroups() {\n      return false;\n   }\n\n   @Override\n   public boolean supportsExclusionCidrBlocks() {\n      return false;\n   }\n\n   private int getRuleStartingPriority(NetworkSecurityGroup securityGroup) {\n      List<NetworkSecurityRule> existingRules = securityGroup.properties().securityRules();\n      return existingRules.isEmpty() ? 100 : rulesByPriority().max(existingRules).properties().priority() + 1;\n   }\n\n   private static Ordering<NetworkSecurityRule> rulesByPriority() {\n      return new Ordering<NetworkSecurityRule>() {\n         @Override\n         public int compare(NetworkSecurityRule left, NetworkSecurityRule right) {\n            return left.properties().priority() - right.properties().priority();\n         }\n      };\n   }\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/compute/functions/CustomImageToVMImage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.compute.functions;\n\nimport static org.jclouds.azurecompute.arm.domain.IdReference.extractResourceGroup;\n\nimport org.jclouds.azurecompute.arm.domain.Image;\nimport org.jclouds.azurecompute.arm.domain.VMImage;\n\nimport com.google.common.base.Function;\n\npublic class CustomImageToVMImage implements Function<Image, VMImage> {\n\n   @Override\n   public VMImage apply(Image input) {\n      return VMImage.customImage().resourceGroup(extractResourceGroup(input.id())).customImageId(input.id()).location(input.location()).name(input.name())\n            .offer(input.properties().storageProfile().osDisk().osType()).build();\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/compute/functions/LocationToLocation.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.compute.functions;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.azurecompute.arm.domain.Location;\nimport org.jclouds.azurecompute.arm.domain.Region;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.location.suppliers.all.JustProvider;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableSet;\n\nimport static com.google.common.collect.Iterables.getOnlyElement;\n\n/**\n * Converts an Location into a Location.\n */\n@Singleton\npublic class LocationToLocation implements Function<Location, org.jclouds.domain.Location> {\n\n   private final JustProvider justProvider;\n\n   // allow us to lazy discover the provider of a resource\n   @Inject\n   LocationToLocation(JustProvider justProvider) {\n      this.justProvider = justProvider;\n   }\n\n   @Override\n   public org.jclouds.domain.Location apply(final Location location) {\n      final LocationBuilder builder = new LocationBuilder();\n      builder.id(location.name());\n      builder.description(location.displayName());\n      builder.parent(getOnlyElement(justProvider.get()));\n      builder.scope(LocationScope.REGION);\n      final Region region = Region.byName(location.displayName());\n      if (region != null) {\n         builder.iso3166Codes(ImmutableSet.of(region.iso3166Code()));\n      }\n      return builder.build();\n   }\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/compute/functions/LocationToResourceGroupName.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.compute.functions;\n\nimport static org.jclouds.compute.config.ComputeServiceProperties.RESOURCENAME_DELIMITER;\nimport static org.jclouds.compute.config.ComputeServiceProperties.RESOURCENAME_PREFIX;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\n\nimport com.google.common.base.Function;\n\n/**\n * Returns the name of the resource group for the current location.\n */\npublic class LocationToResourceGroupName implements Function<String, String> {\n\n   private final String prefix;\n   private final char delimiter;\n\n   @Inject\n   LocationToResourceGroupName(@Named(RESOURCENAME_PREFIX) String prefix, @Named(RESOURCENAME_DELIMITER) char delimiter) {\n      this.prefix = prefix;\n      this.delimiter = delimiter;\n   }\n\n   @Override\n   public String apply(String input) {\n      return String.format(\"%s%s%s\", prefix, delimiter, input);\n   }\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/compute/functions/NetworkSecurityGroupToSecurityGroup.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.compute.functions;\n\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.transform;\nimport static org.jclouds.azurecompute.arm.compute.domain.ResourceGroupAndName.fromResourceGroupAndName;\nimport static org.jclouds.azurecompute.arm.compute.functions.NetworkSecurityRuleToIpPermission.InboundRule;\nimport static org.jclouds.azurecompute.arm.compute.functions.VirtualMachineToNodeMetadata.getLocation;\nimport static org.jclouds.azurecompute.arm.domain.IdReference.extractResourceGroup;\n\nimport java.util.Set;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityGroup;\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityRule;\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.domain.SecurityGroup;\nimport org.jclouds.compute.domain.SecurityGroupBuilder;\nimport org.jclouds.domain.Location;\nimport org.jclouds.net.domain.IpPermission;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.inject.Inject;\n\n@Singleton\npublic class NetworkSecurityGroupToSecurityGroup implements Function<NetworkSecurityGroup, SecurityGroup> {\n   private final Function<NetworkSecurityRule, IpPermission> ruleToPermission;\n   private final Supplier<Set<? extends Location>> locations;\n\n   @Inject\n   NetworkSecurityGroupToSecurityGroup(Function<NetworkSecurityRule, IpPermission> ruleToPermission,\n         @Memoized Supplier<Set<? extends Location>> locations) {\n      this.ruleToPermission = ruleToPermission;\n      this.locations = locations;\n   }\n\n   @Override\n   public SecurityGroup apply(NetworkSecurityGroup input) {\n      SecurityGroupBuilder builder = new SecurityGroupBuilder();\n\n      builder.id(fromResourceGroupAndName(extractResourceGroup(input.id()), input.name()).slashEncode());\n      builder.providerId(input.id());\n      builder.name(input.name());\n      builder.location(getLocation(locations, input.location()));\n\n      if (input.properties().securityRules() != null) {\n         // We just support security groups that allow traffic to a set of\n         // targets. We don't support deny rules or origin based rules in the\n         // security group api.\n         builder.ipPermissions(transform(filter(input.properties().securityRules(), InboundRule), ruleToPermission));\n      }\n\n      return builder.build();\n   }\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/compute/functions/NetworkSecurityRuleToIpPermission.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.compute.functions;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityRule;\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityRuleProperties.Access;\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityRuleProperties.Direction;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.net.domain.IpPermission;\nimport org.jclouds.net.domain.IpProtocol;\nimport org.jclouds.net.util.IpPermissions;\nimport org.jclouds.net.util.IpPermissions.PortSelection;\nimport org.jclouds.net.util.IpPermissions.ToSourceSelection;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\n\n@Singleton\npublic class NetworkSecurityRuleToIpPermission implements Function<NetworkSecurityRule, IpPermission> {\n\n   public static final Predicate<NetworkSecurityRule> InboundRule = new Predicate<NetworkSecurityRule>() {\n      @Override\n      public boolean apply(NetworkSecurityRule input) {\n         return Direction.Inbound.equals(input.properties().direction())\n               && Access.Allow.equals(input.properties().access());\n      }\n   };\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   @Override\n   public IpPermission apply(final NetworkSecurityRule rule) {\n      if (!InboundRule.apply(rule)) {\n         logger.warn(\">> ignoring non-inbound network security rule %s...\", rule.name());\n         return null;\n      }\n\n      IpPermission permissions = IpPermissions.permit(IpProtocol.fromValue(rule.properties().protocol().name()));\n\n      String portRange = rule.properties().destinationPortRange();\n      if (!\"*\".equals(portRange)) {\n         String[] range = portRange.split(\"-\"); // One single element if it is a single port\n         permissions = PortSelection.class.cast(permissions).fromPort(Integer.parseInt(range[0]))\n               .to(Integer.parseInt(range[range.length - 1]));\n      }\n\n      if (!\"*\".equals(rule.properties().sourceAddressPrefix())) {\n         permissions = ToSourceSelection.class.cast(permissions).originatingFromCidrBlock(\n               rule.properties().sourceAddressPrefix());\n      }\n\n      return permissions;\n   }\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/compute/functions/TemplateToAvailabilitySet.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.compute.functions;\n\nimport static com.google.common.base.Preconditions.checkArgument;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.azurecompute.arm.AzureComputeApi;\nimport org.jclouds.azurecompute.arm.compute.options.AzureTemplateOptions;\nimport org.jclouds.azurecompute.arm.domain.AvailabilitySet;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class TemplateToAvailabilitySet implements Function<Template, AvailabilitySet> {\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   private final AzureComputeApi api;\n\n   @Inject\n   TemplateToAvailabilitySet(AzureComputeApi api) {\n      this.api = api;\n   }\n\n   @Nullable\n   @Override\n   public AvailabilitySet apply(final Template input) {\n      checkArgument(input.getOptions() instanceof AzureTemplateOptions, \"An AzureTemplateOptions object is required\");\n      AzureTemplateOptions options = input.getOptions().as(AzureTemplateOptions.class);\n\n      AvailabilitySet availabilitySet = null;\n      String location = input.getLocation().getId();\n      String resourceGroup = options.getResourceGroup();\n\n      if (options.getAvailabilitySetName() != null) {\n         availabilitySet = api.getAvailabilitySetApi(resourceGroup).get(options.getAvailabilitySetName());\n\n         checkArgument(availabilitySet != null, \"No availability set with name '%s' was found\", options.getAvailabilitySetName());\n         checkArgument(location.equals(availabilitySet.location()), \"The availability set %s does not belong to location %s\",\n               options.getAvailabilitySetName(), location);\n\n      } else if (options.getAvailabilitySet() != null) {\n         availabilitySet = api.getAvailabilitySetApi(resourceGroup).get(options.getAvailabilitySet().name());\n\n         if (availabilitySet != null) {\n            checkArgument(location.equals(availabilitySet.location()), \"The availability set %s does not belong to location %s\",\n                  options.getAvailabilitySet().name(), location);\n         } else {\n            Map<String, String> tags = new HashMap<String, String>();\n            if (options.getAvailabilitySet().tags() != null) {\n               tags.putAll(options.getAvailabilitySet().tags());\n            }\n            tags.put(\"jclouds\", options.getAvailabilitySet().name());\n\n            logger.debug(\">> creating availability set [%s]\", options.getAvailabilitySet().name());\n\n            availabilitySet = api.getAvailabilitySetApi(resourceGroup).createOrUpdate(\n                  options.getAvailabilitySet().name(), options.getAvailabilitySet().sku(), location, tags,\n                  options.getAvailabilitySet().properties());\n         }\n      }\n\n      return availabilitySet;\n   }\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/compute/functions/VMHardwareToHardware.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.compute.functions;\n\nimport static org.jclouds.azurecompute.arm.compute.domain.LocationAndName.fromLocationAndName;\n\nimport java.util.Set;\n\nimport org.jclouds.azurecompute.arm.domain.VMHardware;\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.HardwareBuilder;\nimport org.jclouds.compute.domain.Processor;\nimport org.jclouds.compute.domain.Volume;\nimport org.jclouds.compute.domain.VolumeBuilder;\nimport org.jclouds.domain.Location;\nimport org.jclouds.location.predicates.LocationPredicates;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.inject.Inject;\n\npublic class VMHardwareToHardware implements Function<VMHardware, Hardware> {\n\n   private final Supplier<Set<? extends Location>> locations;\n\n   @Inject\n   VMHardwareToHardware(@Memoized final Supplier<Set<? extends Location>> locations) {\n      this.locations = locations;\n   }\n\n   @Override\n   public Hardware apply(VMHardware from) {\n      final HardwareBuilder builder = new HardwareBuilder()\n              .name(from.name())\n              .providerId(from.name())\n              .id(fromLocationAndName(from.location(), from.name()).slashEncode())\n              .processors(ImmutableList.of(new Processor(from.numberOfCores(), 2)))\n              .ram(from.memoryInMB())\n              .location(FluentIterable.from(locations.get())\n                      .firstMatch(LocationPredicates.idEquals(from.location()))\n                      .get());\n\n      // No id or providerId from Azure\n      if (from.resourceDiskSizeInMB() != null) {\n         builder.volume(new VolumeBuilder()\n                 .size(Float.valueOf(from.resourceDiskSizeInMB()))\n                 .type(Volume.Type.LOCAL)\n                 .build());\n      }\n      if (from.osDiskSizeInMB() != null) {\n         builder.volume(new VolumeBuilder()\n                 .size(Float.valueOf(from.osDiskSizeInMB()))\n                 .type(Volume.Type.LOCAL)\n                 .build());\n      }\n\n      ImmutableMap.Builder<String, String> metadata = ImmutableMap.builder();\n      metadata.put(\"maxDataDiskCount\", String.valueOf(from.maxDataDiskCount()));\n      builder.userMetadata(metadata.build());\n\n      return builder.build();\n   }\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/compute/functions/VMImageToImage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.compute.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.tryFind;\nimport static java.util.Arrays.asList;\nimport static org.jclouds.location.predicates.LocationPredicates.idEquals;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.azurecompute.arm.compute.extensions.AzureComputeImageExtension;\nimport org.jclouds.azurecompute.arm.compute.options.AzureTemplateOptions;\nimport org.jclouds.azurecompute.arm.domain.Plan;\nimport org.jclouds.azurecompute.arm.domain.VMImage;\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.ImageBuilder;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.domain.Location;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Strings;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.inject.Inject;\n\npublic class VMImageToImage implements Function<VMImage, Image> {\n\n   private static final Map<String, OsFamily> OTHER_OS_MAP = ImmutableMap.<String, OsFamily> builder()\n         .put(\"openlogic\", OsFamily.CENTOS)\n         .put(\"win\", OsFamily.WINDOWS)\n         .put(\"sles\", OsFamily.SUSE)\n         .put(\"oracle-linux\", OsFamily.OEL)\n         .build();\n\n   private final Supplier<Set<? extends org.jclouds.domain.Location>> locations;\n\n   @Inject\n   VMImageToImage(@Memoized Supplier<Set<? extends Location>> locations) {\n      this.locations = locations;\n   }\n\n   @Override\n   public Image apply(final VMImage image) {\n      final ImageBuilder builder = new ImageBuilder();\n      addMarketplacePlanToMetadataIfPresent(builder, image);\n      \n      Location location = FluentIterable.from(locations.get()).firstMatch(idEquals(image.location())).get();\n      \n      if (image.custom()) {\n         builder\n            .id(image.encodeFieldsToUniqueIdCustom())\n            .providerId(image.customImageId())\n            .name(image.name())\n            .location(location)\n            .description(image.group())\n            .status(Image.Status.AVAILABLE)\n            .version(\"latest\");\n      } else {\n         builder\n            .id(image.encodeFieldsToUniqueId())\n            .providerId(image.publisher())\n            .name(image.offer())\n            .location(location)\n            .description(image.sku())\n            .status(Image.Status.AVAILABLE)\n            .version(image.sku());\n      }\n      \n      final OperatingSystem.Builder osBuilder = osFamily().apply(image);\n      builder.operatingSystem(osBuilder.build());\n      \n      return builder.build();\n   }\n   \n   private static void addMarketplacePlanToMetadataIfPresent(ImageBuilder builder, VMImage image) {\n      if (image.versionProperties() != null && image.versionProperties().plan() != null) {\n         // Store the plan information in the metadata so the adapter can\n         // properly configure it when deploying images from the marketplace\n         Plan plan = image.versionProperties().plan();\n         builder.userMetadata(ImmutableMap.of(\"publisher\", plan.publisher(), \"name\", plan.name(), \"product\",\n               plan.product()));\n      }\n   }\n\n   /**\n    * In case that image is offered from Azure Marketplace then it requires to provide \"Plan Information\" (publisher/name/product)\n    * when creating VM from such an image. This method first tries to get this information from image but also allows to\n    * override those values by information passed in Azure template options (@see AzureTemplateOptions).\n    *\n    * In case there is used custom image which was created from Marketplace image then plan information is missing as this image\n    * cannot be referenced in format \"location/publisher/offer/sku\" from which Plan Information is normally parsed.\n    * In this case user can provide plan information (planPublisher/planName/planProduct) in template otherwise VM creation fails with error.\n    * It's allowed to override any of the original \"image\" plan information but only if those were present.\n    *\n    * @param image image\n    * @param templateOptions Azure template options\n    * @return Plan Information (publisher, plan name, product) or null if any of publisher/name/product not defined\n    */\n   @Nullable\n   public static Plan createMarketplacePlanIfPresent(Image image, AzureTemplateOptions templateOptions) {\n      Map<String, String> imageMetadata = image.getUserMetadata();\n\n      String planPublisher = getFirstNonEmptyOrReturnNull(templateOptions.getPlanPublisher(), imageMetadata.get(\"publisher\"));\n      String planName = getFirstNonEmptyOrReturnNull(templateOptions.getPlanName(), imageMetadata.get(\"name\"));\n      String planProduct = getFirstNonEmptyOrReturnNull(templateOptions.getPlanProduct(), imageMetadata.get(\"product\"));\n\n      if (Strings.isNullOrEmpty(planPublisher) || Strings.isNullOrEmpty(planName) || Strings.isNullOrEmpty(planProduct)) {\n         return null;\n      } else {\n         return Plan.create(planPublisher, planName, planProduct);\n      }\n   }\n\n   @Nullable\n   private static String getFirstNonEmptyOrReturnNull(String first, String second)   {\n      if (!Strings.isNullOrEmpty(first))   {\n         return first;\n      } else if (!Strings.isNullOrEmpty(second))   {\n         return second;\n      } else {\n         return null;\n      }\n   }\n\n   public static Function<VMImage, OperatingSystem.Builder> osFamily() {\n      return new Function<VMImage, OperatingSystem.Builder>() {\n         @Override\n         public OperatingSystem.Builder apply(final VMImage image) {\n            final String label = checkNotNull(image.offer(), \"offer\").toLowerCase();\n            OsFamily family = findInStandardFamilies(label).or(findInOtherOSMap(label)).or(OsFamily.UNRECOGNIZED);\n            \n            // Fallback to generic operating system type\n            if (OsFamily.UNRECOGNIZED == family && image.versionProperties() != null\n                  && image.versionProperties().osDiskImage() != null\n                  && image.versionProperties().osDiskImage().operatingSystem() != null) {\n               family = OsFamily.fromValue(image.versionProperties().osDiskImage().operatingSystem().toUpperCase());\n            }\n\n            // only 64bit OS images are supported by Azure ARM\n            return OperatingSystem.builder().family(family).is64Bit(true)\n                  .description(image.custom() ? AzureComputeImageExtension.CUSTOM_IMAGE_OFFER : image.sku())\n                  .version(image.custom() ? \"latest\" : image.sku());\n         }\n      };\n   }\n\n   private static Optional<OsFamily> findInStandardFamilies(final String label) {\n      return tryFind(asList(OsFamily.values()), new Predicate<OsFamily>() {\n         @Override\n         public boolean apply(OsFamily input) {\n            return label.contains(input.value());\n         }\n      });\n   }\n\n   private static Optional<OsFamily> findInOtherOSMap(final String label) {\n      return tryFind(OTHER_OS_MAP.keySet(), new Predicate<String>() {\n         @Override\n         public boolean apply(String input) {\n            return label.contains(input);\n         }\n      }).transform(new Function<String, OsFamily>() {\n         @Override\n         public OsFamily apply(String input) {\n            return OTHER_OS_MAP.get(input);\n         }\n      });\n   }\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/compute/functions/VirtualMachineToNodeMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.compute.functions;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Strings.nullToEmpty;\nimport static com.google.common.collect.Iterables.find;\nimport static org.jclouds.azurecompute.arm.compute.AzureComputeServiceAdapter.GROUP_KEY;\nimport static org.jclouds.azurecompute.arm.compute.domain.LocationAndName.fromLocationAndName;\nimport static org.jclouds.azurecompute.arm.compute.domain.ResourceGroupAndName.fromResourceGroupAndName;\nimport static org.jclouds.azurecompute.arm.domain.IdReference.extractName;\nimport static org.jclouds.azurecompute.arm.domain.IdReference.extractResourceGroup;\nimport static org.jclouds.compute.util.ComputeServiceUtils.addMetadataAndParseTagsFromCommaDelimitedValue;\nimport static org.jclouds.location.predicates.LocationPredicates.idEquals;\n\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\n\nimport org.jclouds.azurecompute.arm.AzureComputeApi;\nimport org.jclouds.azurecompute.arm.compute.domain.LocationAndName;\nimport org.jclouds.azurecompute.arm.compute.functions.VirtualMachineToStatus.StatusAndBackendStatus;\nimport org.jclouds.azurecompute.arm.domain.IdReference;\nimport org.jclouds.azurecompute.arm.domain.IpConfiguration;\nimport org.jclouds.azurecompute.arm.domain.NetworkInterfaceCard;\nimport org.jclouds.azurecompute.arm.domain.NetworkProfile.NetworkInterface;\nimport org.jclouds.azurecompute.arm.domain.StorageProfile;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachine;\nimport org.jclouds.azurecompute.arm.domain.publicipaddress.PublicIPAddress;\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadataBuilder;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.compute.suppliers.ImageCacheSupplier;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.domain.Location;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.Lists;\n\npublic class VirtualMachineToNodeMetadata implements Function<VirtualMachine, NodeMetadata> {\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   private final AzureComputeApi api;\n   private final GroupNamingConvention nodeNamingConvention;\n   private final Supplier<Set<? extends Location>> locations;\n   private final Supplier<Map<String, ? extends Hardware>> hardwares;\n   private final ImageCacheSupplier imageCache;\n   private final VirtualMachineToStatus virtualMachineToStatus;\n\n   @Inject\n   VirtualMachineToNodeMetadata(AzureComputeApi api, GroupNamingConvention.Factory namingConvention,\n         Supplier<Map<String, ? extends Hardware>> hardwares, @Memoized Supplier<Set<? extends Location>> locations,\n         Map<String, Credentials> credentialStore, @Memoized Supplier<Set<? extends Image>> imageCache,\n         VirtualMachineToStatus virtualMachineToStatus) {\n      this.api = api;\n      this.nodeNamingConvention = namingConvention.createWithoutPrefix();\n      this.locations = locations;\n      this.hardwares = hardwares;\n      this.virtualMachineToStatus = virtualMachineToStatus;\n      checkArgument(imageCache instanceof ImageCacheSupplier,\n            \"This provider needs an instance of the ImageCacheSupplier\");\n      this.imageCache = (ImageCacheSupplier) imageCache;\n   }\n\n   @Override\n   public NodeMetadata apply(VirtualMachine virtualMachine) {\n      NodeMetadataBuilder builder = new NodeMetadataBuilder();\n      builder.id(fromResourceGroupAndName(extractResourceGroup(virtualMachine.id()), virtualMachine.name())\n            .slashEncode());\n      builder.providerId(virtualMachine.id());\n      builder.name(virtualMachine.name());\n      builder.hostname(virtualMachine.name());\n\n      StatusAndBackendStatus status = virtualMachineToStatus.apply(virtualMachine);\n      builder.status(status.status());\n      builder.backendStatus(status.backendStatus());\n\n      builder.publicAddresses(getPublicIpAddresses(virtualMachine.properties().networkProfile().networkInterfaces()));\n      builder.privateAddresses(getPrivateIpAddresses(virtualMachine.properties().networkProfile().networkInterfaces()));\n\n      String groupFromMetadata = null;\n      if (virtualMachine.tags() != null) {\n         addMetadataAndParseTagsFromCommaDelimitedValue(builder, virtualMachine.tags());\n         groupFromMetadata = virtualMachine.tags().get(GROUP_KEY);\n      }\n\n      // Try to read the group from the virtual machine tags, and parse the name\n      // if missing\n      builder.group(groupFromMetadata != null ? groupFromMetadata : nodeNamingConvention.extractGroup(virtualMachine\n            .name()));\n\n      String locationName = virtualMachine.location();\n      builder.location(getLocation(locations, locationName));\n\n      Optional<? extends Image> image = findImage(virtualMachine.properties().storageProfile(), locationName);\n      \n      if (image.isPresent()) {\n         builder.imageId(image.get().getId());\n         builder.operatingSystem(image.get().getOperatingSystem());\n      } else {\n         logger.info(\">> image with id %s for virtualmachine %s was not found. \"\n               + \"This might be because the image that was used to create the virtualmachine has a new id.\",\n               virtualMachine.id(), virtualMachine.id());\n      }\n\n      builder.hardware(getHardware(fromLocationAndName(virtualMachine.location(), virtualMachine.properties()\n            .hardwareProfile().vmSize())));\n\n      return builder.build();\n   }\n\n   private Iterable<String> getPrivateIpAddresses(List<NetworkInterface> networkInterfaces) {\n      List<String> privateIpAddresses = Lists.newArrayList();\n      for (NetworkInterface networkInterfaceCardIdReference : networkInterfaces) {\n         NetworkInterfaceCard networkInterfaceCard = getNetworkInterfaceCard(networkInterfaceCardIdReference);\n         if (networkInterfaceCard != null && networkInterfaceCard.properties() != null\n               && networkInterfaceCard.properties().ipConfigurations() != null) {\n            for (IpConfiguration ipConfiguration : networkInterfaceCard.properties().ipConfigurations()) {\n               if (ipConfiguration.properties().privateIPAddress() != null) {\n                  privateIpAddresses.add(ipConfiguration.properties().privateIPAddress());\n               }\n            }\n         }\n      }\n      return privateIpAddresses;\n   }\n\n   private NetworkInterfaceCard getNetworkInterfaceCard(NetworkInterface nic) {\n      return api.getNetworkInterfaceCardApi(extractResourceGroup(nic.id())).get(extractName(nic.id()));\n   }\n\n   private Iterable<String> getPublicIpAddresses(List<NetworkInterface> networkInterfaces) {\n      List<String> publicIpAddresses = Lists.newArrayList();\n      for (NetworkInterface networkInterfaceCardIdReference : networkInterfaces) {\n         NetworkInterfaceCard networkInterfaceCard = getNetworkInterfaceCard(networkInterfaceCardIdReference);\n         if (networkInterfaceCard != null && networkInterfaceCard.properties() != null\n               && networkInterfaceCard.properties().ipConfigurations() != null) {\n            for (IpConfiguration ipConfiguration : networkInterfaceCard.properties().ipConfigurations()) {\n               if (ipConfiguration.properties().publicIPAddress() != null) {\n                  IdReference publicIpId = ipConfiguration.properties().publicIPAddress();\n                  PublicIPAddress publicIp = api.getPublicIPAddressApi(publicIpId.resourceGroup()).get(\n                        publicIpId.name());\n                  if (publicIp != null && publicIp.properties().ipAddress() != null) {\n                     publicIpAddresses.add(publicIp.properties().ipAddress());\n                  }\n               }\n            }\n         }\n      }\n      return publicIpAddresses;\n   }\n\n   protected static Location getLocation(Supplier<Set<? extends Location>> locations, final String locationName) {\n      return find(locations.get(), idEquals(nullToEmpty(locationName)), null);\n   }\n\n   protected Optional<? extends Image> findImage(final StorageProfile storageProfile, String locatioName) {\n      if (storageProfile.imageReference() != null) {\n         String imageId = storageProfile.imageReference().customImageId() != null ?\n               storageProfile.imageReference().encodeFieldsToUniqueIdCustom(locatioName) :\n               storageProfile.imageReference().encodeFieldsToUniqueId(locatioName); \n         return imageCache.get(imageId);\n      } else {\n         logger.warn(\"could not find image for storage profile %s\", storageProfile);\n         return Optional.absent();\n      }\n   }\n\n   protected Hardware getHardware(final LocationAndName hardwareId) {\n      final String slashEncoded = hardwareId.slashEncode();\n      return find(hardwares.get().values(), new Predicate<Hardware>() {\n         @Override\n         public boolean apply(Hardware input) {\n            return input.getId().equals(slashEncoded);\n         }\n      });\n   }\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/compute/functions/VirtualMachineToStatus.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.compute.functions;\n\nimport static com.google.common.collect.Iterables.transform;\nimport static org.jclouds.azurecompute.arm.domain.IdReference.extractResourceGroup;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.azurecompute.arm.AzureComputeApi;\nimport org.jclouds.azurecompute.arm.compute.functions.VirtualMachineToStatus.StatusAndBackendStatus;\nimport org.jclouds.azurecompute.arm.domain.Status;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachine;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineInstance;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineInstance.PowerState;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineProperties;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineProperties.ProvisioningState;\nimport org.jclouds.compute.domain.NodeMetadata;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.base.Function;\nimport com.google.common.base.Functions;\nimport com.google.common.base.Joiner;\nimport com.google.common.collect.ImmutableMap;\n\n@Singleton\npublic class VirtualMachineToStatus implements Function<VirtualMachine, StatusAndBackendStatus> {\n\n   @AutoValue\n   public abstract static class StatusAndBackendStatus {\n      public abstract NodeMetadata.Status status();\n\n      public abstract String backendStatus();\n\n      public static StatusAndBackendStatus create(NodeMetadata.Status status, String backendStatus) {\n         return new AutoValue_VirtualMachineToStatus_StatusAndBackendStatus(status, backendStatus);\n      }\n   }\n\n   // When using the Deployment API to deploy an ARM template, the deployment\n   // goes through stages: Accepted -> Running -> Succeeded.\n   // Only when the deployment has SUCCEEDED is the resource deployed using the\n   // template actually ready.\n   // To get details about the resource(s) deployed via template, one needs to\n   // query the various resources after the deployment has SUCCEEDED.\n   private static final Function<VirtualMachineProperties.ProvisioningState, NodeMetadata.Status> PROVISIONINGSTATE_TO_NODESTATUS = Functions\n         .forMap(\n               ImmutableMap.<VirtualMachineProperties.ProvisioningState, NodeMetadata.Status> builder()\n                     .put(VirtualMachineProperties.ProvisioningState.ACCEPTED, NodeMetadata.Status.PENDING)\n                     .put(VirtualMachineProperties.ProvisioningState.READY, NodeMetadata.Status.PENDING)\n                     .put(VirtualMachineProperties.ProvisioningState.CREATING, NodeMetadata.Status.PENDING)\n                     .put(VirtualMachineProperties.ProvisioningState.RUNNING, NodeMetadata.Status.PENDING)\n                     .put(VirtualMachineProperties.ProvisioningState.UPDATING, NodeMetadata.Status.PENDING)\n                     .put(VirtualMachineProperties.ProvisioningState.DELETED, NodeMetadata.Status.TERMINATED)\n                     .put(VirtualMachineProperties.ProvisioningState.CANCELED, NodeMetadata.Status.TERMINATED)\n                     .put(VirtualMachineProperties.ProvisioningState.FAILED, NodeMetadata.Status.ERROR)\n                     .put(VirtualMachineProperties.ProvisioningState.UNRECOGNIZED, NodeMetadata.Status.UNRECOGNIZED)\n                     .build(), NodeMetadata.Status.UNRECOGNIZED);\n\n   private static final Function<PowerState, NodeMetadata.Status> POWERSTATE_TO_NODESTATUS = Functions.forMap(\n         ImmutableMap.<PowerState, NodeMetadata.Status> builder()\n               .put(PowerState.RUNNING, NodeMetadata.Status.RUNNING)\n               .put(PowerState.STARTING, NodeMetadata.Status.PENDING)\n               .put(PowerState.STOPPED, NodeMetadata.Status.SUSPENDED)\n               .put(PowerState.STOPPING, NodeMetadata.Status.PENDING)\n               .put(PowerState.DEALLOCATED, NodeMetadata.Status.SUSPENDED)\n               .put(PowerState.DEALLOCATING, NodeMetadata.Status.PENDING)\n               .put(PowerState.UNKNOWN, NodeMetadata.Status.UNRECOGNIZED).build(),\n         NodeMetadata.Status.UNRECOGNIZED);\n\n   private final AzureComputeApi api;\n\n   @Inject\n   VirtualMachineToStatus(AzureComputeApi api) {\n      this.api = api;\n   }\n\n   @Override\n   public StatusAndBackendStatus apply(VirtualMachine virtualMachine) {\n      String resourceGroup = extractResourceGroup(virtualMachine.id());\n      ProvisioningState provisioningState = virtualMachine.properties().provisioningState();\n\n      NodeMetadata.Status status = PROVISIONINGSTATE_TO_NODESTATUS.apply(provisioningState);\n      String backendStatus = provisioningState.name();\n\n      if (ProvisioningState.SUCCEEDED.equals(provisioningState)) {\n         // If the provisioning succeeded, we need to query the *real* status of\n         // the VM\n         VirtualMachineInstance instanceDetails = api.getVirtualMachineApi(resourceGroup).getInstanceDetails(\n               virtualMachine.name());\n         if (instanceDetails != null && instanceDetails.powerState() != null) {\n            status = POWERSTATE_TO_NODESTATUS.apply(instanceDetails.powerState());\n            backendStatus = Joiner.on(',').join(transform(instanceDetails.statuses(), new Function<Status, String>() {\n               @Override\n               public String apply(Status input) {\n                  return input.code();\n               }\n            }));\n         } else {\n            status = NodeMetadata.Status.PENDING;\n         }\n      }\n\n      return StatusAndBackendStatus.create(status, backendStatus);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/compute/loaders/CreateSecurityGroupIfNeeded.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.compute.loaders;\n\nimport static com.google.common.base.Preconditions.checkState;\nimport static org.jclouds.compute.util.ComputeServiceUtils.getPortRangesFromList;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.azurecompute.arm.AzureComputeApi;\nimport org.jclouds.azurecompute.arm.compute.config.AzurePredicatesModule.SecurityGroupAvailablePredicateFactory;\nimport org.jclouds.azurecompute.arm.compute.domain.ResourceGroupAndNameAndIngressRules;\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityGroup;\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityGroupProperties;\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityRule;\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityRuleProperties;\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityRuleProperties.Access;\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityRuleProperties.Direction;\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityRuleProperties.Protocol;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.cache.CacheLoader;\n\n@Singleton\npublic class CreateSecurityGroupIfNeeded extends CacheLoader<ResourceGroupAndNameAndIngressRules, String> {\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   private final AzureComputeApi api;\n   private final SecurityGroupAvailablePredicateFactory securityGroupAvailable;\n\n   @Inject\n   CreateSecurityGroupIfNeeded(AzureComputeApi api, SecurityGroupAvailablePredicateFactory securityRuleAvailable) {\n      this.api = api;\n      this.securityGroupAvailable = securityRuleAvailable;\n   }\n\n   @Override\n   public String load(ResourceGroupAndNameAndIngressRules key) throws Exception {\n      return createSecurityGroup(key.location(), key.resourceGroup(), key.name(), key.inboundPorts());\n   }\n\n   private String createSecurityGroup(String location, String resourceGroup, String name, int[] inboundPorts) {\n      logger.debug(\">> creating security group %s in %s...\", name, location);\n\n      Map<Integer, Integer> portRanges = getPortRangesFromList(inboundPorts);\n\n      List<NetworkSecurityRule> rules = new ArrayList<NetworkSecurityRule>();\n\n      int startPriority = 100;\n      for (Map.Entry<Integer, Integer> portRange : portRanges.entrySet()) {\n         String range = portRange.getKey() + \"-\" + portRange.getValue();\n         String ruleName = \"tcp-\" + range;\n\n         NetworkSecurityRuleProperties properties = NetworkSecurityRuleProperties.builder().protocol(Protocol.Tcp) //\n               .sourceAddressPrefix(\"*\") //\n               .sourcePortRange(\"*\") //\n               .destinationAddressPrefix(\"*\") //\n               .destinationPortRange(range) //\n               .direction(Direction.Inbound) //\n               .access(Access.Allow) //\n               .priority(startPriority++) //\n               .build();\n\n         rules.add(NetworkSecurityRule.create(ruleName, null, null, properties));\n      }\n\n      NetworkSecurityGroup securityGroup = api.getNetworkSecurityGroupApi(resourceGroup).createOrUpdate(name, location,\n            null, NetworkSecurityGroupProperties.builder().securityRules(rules).build());\n      \n      checkState(securityGroupAvailable.create(resourceGroup).apply(name),\n            \"Security group was not created in the configured timeout\");\n\n      return securityGroup.id();\n   }\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/compute/loaders/DefaultResourceGroup.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.compute.loaders;\n\nimport java.util.Map;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.azurecompute.arm.AzureComputeApi;\nimport org.jclouds.azurecompute.arm.compute.functions.LocationToResourceGroupName;\nimport org.jclouds.azurecompute.arm.domain.ResourceGroup;\nimport org.jclouds.azurecompute.arm.features.ResourceGroupApi;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.collect.ImmutableMap;\n\n@Singleton\npublic class DefaultResourceGroup extends CacheLoader<String, ResourceGroup> {\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   private final ResourceGroupApi api;\n   private final LocationToResourceGroupName locationToResourceGroupName;\n\n   @Inject\n   DefaultResourceGroup(AzureComputeApi api, LocationToResourceGroupName locationToResourceGroupName) {\n      this.api = api.getResourceGroupApi();\n      this.locationToResourceGroupName = locationToResourceGroupName;\n   }\n\n   @Override\n   public ResourceGroup load(String locationId) throws Exception {\n      String azureGroupName = locationToResourceGroupName.apply(locationId);\n      ResourceGroup resourceGroup = api.get(azureGroupName);\n      if (resourceGroup == null) {\n         logger.debug(\">> creating resource group %s\", azureGroupName);\n         final Map<String, String> tags = ImmutableMap.of(\"description\", \"jclouds default resource group\");\n         resourceGroup = api.create(azureGroupName, locationId, tags);\n      }\n      return resourceGroup;\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/compute/options/AzureTemplateOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.compute.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.List;\n\nimport org.jclouds.azurecompute.arm.domain.AvailabilitySet;\nimport org.jclouds.azurecompute.arm.domain.DataDisk;\nimport org.jclouds.azurecompute.arm.domain.OSProfile.WindowsConfiguration;\nimport org.jclouds.azurecompute.arm.domain.Secrets;\nimport org.jclouds.azurecompute.arm.domain.StorageAccountType;\nimport org.jclouds.compute.options.TemplateOptions;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Azure ARM custom options\n */\npublic class AzureTemplateOptions extends TemplateOptions implements Cloneable {\n\n   private AvailabilitySet availabilitySet;\n   private String availabilitySetName;\n   private List<DataDisk> dataDisks = ImmutableList.of();\n   private String resourceGroup;\n   private List<IpOptions> ipOptions = ImmutableList.of();\n   private WindowsConfiguration windowsConfiguration;\n   private List<Secrets> secrets = ImmutableList.of();\n   private String customData;\n   private StorageAccountType osDiskStorageType = StorageAccountType.STANDARD_LRS;\n   private String planPublisher;\n   private String planName;\n   private String planProduct;\n\n   /**\n    * Sets the availability set where the nodes will be configured. If it does\n    * not exist jclouds will create a new one with the given configuration.\n    */\n   public AzureTemplateOptions availabilitySet(AvailabilitySet availabilitySet) {\n      this.availabilitySet = availabilitySet;\n      return this;\n   }\n\n   /**\n    * Sets the availability set where the nodes will be configured. The\n    * availability set must exist.\n    */\n   public AzureTemplateOptions availabilitySet(String availabilitySetName) {\n      this.availabilitySetName = availabilitySetName;\n      return this;\n   }\n\n   /**\n    * The resource group where the new resources will be created.\n    */\n   public AzureTemplateOptions resourceGroup(String resourceGroup) {\n      this.resourceGroup = resourceGroup;\n      return this;\n   }\n\n   public AzureTemplateOptions dataDisks(Iterable<DataDisk> dataDisks) {\n      for (DataDisk dataDisk : checkNotNull(dataDisks, \"dataDisks\"))\n         checkNotNull(dataDisk, \"all dataDisks must be non-empty\");\n      this.dataDisks = ImmutableList.copyOf(dataDisks);\n      return this;\n   }\n\n   public AzureTemplateOptions dataDisks(DataDisk... dataDisks) {\n      return dataDisks(ImmutableList.copyOf(checkNotNull(dataDisks, \"dataDisks\")));\n   }\n\n   /**\n    * Configure the NICs that will be attached to the created nodes.\n    * <p>\n    * Note that the number of NICs that can be attached depends on the size of\n    * the virtual machine, and that the guest operating system needs to be\n    * prepared to set up all the configured interfaces.\n    * <p>\n    * Depending on the image being used, a cloud-init or bootstrap script might\n    * be needed to make the interface setup.\n    */\n   public AzureTemplateOptions ipOptions(Iterable<IpOptions> ipOptions) {\n      for (IpOptions ipOption : checkNotNull(ipOptions, \"ipOptions\"))\n         checkNotNull(ipOption, \"all ipOptions must be non-empty\");\n      this.ipOptions = ImmutableList.copyOf(ipOptions);\n      return this;\n   }\n\n   /**\n    * @see {@link AzureTemplateOptions#ipOptions(Iterable)\n\n    */\n   public AzureTemplateOptions ipOptions(IpOptions... ipOptions) {\n      return ipOptions(ImmutableList.copyOf(checkNotNull(ipOptions, \"ipOptions\")));\n   }\n\n   /**\n    * Windows configuration parameters\n    *\n    * @see <a\n    *      href=\"https://docs.microsoft.com/en-us/rest/api/compute/virtualmachines/virtualmachines-create-or-update#bk_windowsconfig5\">docs</a>\n    */\n   public AzureTemplateOptions windowsConfiguration(WindowsConfiguration windowsConfiguration) {\n      this.windowsConfiguration = windowsConfiguration;\n      return this;\n   }\n\n   /**\n    * Import certificates in the Windows Certificate Store\n    *\n    * @see <a\n    *      href=\"https://docs.microsoft.com/en-us/rest/api/compute/virtualmachines/virtualmachines-create-or-update#bk_srcvault\">docs</a>\n    */\n   public AzureTemplateOptions secrets(Iterable<? extends Secrets> secrets) {\n      for (Secrets secret : checkNotNull(secrets, \"secrets\"))\n         checkNotNull(secret, \"secrets can not be empty\");\n      this.secrets = ImmutableList.copyOf(secrets);\n      return this;\n   }\n\n   /**\n    * Custom data (for cloud-init) for the Azure ARM API\n    */\n   public AzureTemplateOptions customData(String customData) {\n      this.customData = customData;\n      return this;\n   }\n\n   public AzureTemplateOptions osDiskStorageType(StorageAccountType osDiskStorageType) {\n      this.osDiskStorageType = osDiskStorageType;\n      return this;\n   }\n\n   public AzureTemplateOptions planPublisher(String planPublisher) {\n      this.planPublisher = planPublisher;\n      return this;\n   }\n\n   public AzureTemplateOptions planName(String planName) {\n      this.planName = planName;\n      return this;\n   }\n\n   public AzureTemplateOptions planProduct(String planProduct) {\n      this.planProduct = planProduct;\n      return this;\n   }\n\n   public AvailabilitySet getAvailabilitySet() {\n      return availabilitySet;\n   }\n\n   public String getAvailabilitySetName() {\n      return availabilitySetName;\n   }\n\n   public List<DataDisk> getDataDisks() {\n      return dataDisks;\n   }\n\n   public String getResourceGroup() {\n      return resourceGroup;\n   }\n\n   public List<IpOptions> getIpOptions() {\n      return ipOptions;\n   }\n\n   public WindowsConfiguration getWindowsConfiguration() {\n      return windowsConfiguration;\n   }\n\n   public List<Secrets> getSecrets() {\n      return secrets;\n   }\n\n   public String getCustomData() {\n      return customData;\n   }\n\n   public StorageAccountType getOsDiskStorageType() {\n      return osDiskStorageType;\n   }\n\n   public String getPlanPublisher() {\n      return planPublisher;\n   }\n\n   public String getPlanName() {\n      return planName;\n   }\n\n   public String getPlanProduct() {\n      return planProduct;\n   }\n\n   @Override\n   public AzureTemplateOptions clone() {\n      AzureTemplateOptions options = new AzureTemplateOptions();\n      copyTo(options);\n      return options;\n   }\n\n   @Override\n   public void copyTo(TemplateOptions to) {\n      super.copyTo(to);\n      if (to instanceof AzureTemplateOptions) {\n         AzureTemplateOptions eTo = AzureTemplateOptions.class.cast(to);\n         eTo.availabilitySet(availabilitySet);\n         eTo.availabilitySet(availabilitySetName);\n         eTo.dataDisks(dataDisks);\n         eTo.resourceGroup(resourceGroup);\n         eTo.ipOptions(ipOptions);\n         eTo.windowsConfiguration(windowsConfiguration);\n         eTo.secrets(secrets);\n         eTo.customData(customData);\n         eTo.osDiskStorageType(osDiskStorageType);\n         eTo.planPublisher(planPublisher);\n         eTo.planName(planName);\n         eTo.planProduct(planProduct);\n      }\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o)\n         return true;\n      if (!(o instanceof AzureTemplateOptions))\n         return false;\n      if (!super.equals(o))\n         return false;\n\n      AzureTemplateOptions that = (AzureTemplateOptions) o;\n\n      return Objects.equal(availabilitySetName, that.availabilitySetName)\n            && Objects.equal(resourceGroup, that.resourceGroup) && Objects.equal(availabilitySet, that.availabilitySet)\n            && Objects.equal(dataDisks, that.dataDisks) && Objects.equal(ipOptions, that.ipOptions)\n            && Objects.equal(windowsConfiguration, that.windowsConfiguration) && Objects.equal(secrets, that.secrets)\n            && Objects.equal(this.customData, that.customData)\n            && Objects.equal(this.planPublisher, that.planPublisher)\n            && Objects.equal(this.planName, that.planName)\n            && Objects.equal(this.planProduct, that.planProduct);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(super.hashCode(), availabilitySet, availabilitySetName, dataDisks, resourceGroup,\n            ipOptions, customData, planPublisher, planName, planProduct);\n   }\n\n   @Override\n   public MoreObjects.ToStringHelper string() {\n      MoreObjects.ToStringHelper toString = super.string();\n      if (availabilitySet != null)\n         toString.add(\"availabilitySet\", availabilitySet);\n      if (availabilitySetName != null)\n         toString.add(\"availabilitySetName\", availabilitySetName);\n      if (!dataDisks.isEmpty())\n         toString.add(\"dataDisks\", dataDisks);\n      if (resourceGroup != null)\n         toString.add(\"resourceGroup\", resourceGroup);\n      if (!ipOptions.isEmpty())\n         toString.add(\"ipOptions\", ipOptions);\n      if (windowsConfiguration != null)\n         toString.add(\"windowsConfiguration\", windowsConfiguration);\n      if (!secrets.isEmpty())\n         toString.add(\"secrets\", secrets);\n      if (customData != null)\n         toString.add(\"customData\", customData);\n      if (planPublisher != null)\n         toString.add(\"publisher\", planPublisher);\n      if (planName != null)\n         toString.add(\"planName\", planName);\n      if (planProduct != null)\n         toString.add(\"planProduct\", planProduct);\n      return toString;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see AzureTemplateOptions#availabilitySet(AvailabilitySet)\n       */\n      public static AzureTemplateOptions availabilitySet(AvailabilitySet availabilitySet) {\n         AzureTemplateOptions options = new AzureTemplateOptions();\n         return options.availabilitySet(availabilitySet);\n      }\n\n      /**\n       * @see AzureTemplateOptions#availabilitySet(String)\n       */\n      public static AzureTemplateOptions availabilitySet(String availabilitySetName) {\n         AzureTemplateOptions options = new AzureTemplateOptions();\n         return options.availabilitySet(availabilitySetName);\n      }\n\n      /**\n       * @see AzureTemplateOptions#dataDisks(DataDisk...)\n       */\n      public static AzureTemplateOptions dataDisks(DataDisk... dataDisks) {\n         AzureTemplateOptions options = new AzureTemplateOptions();\n         return options.dataDisks(dataDisks);\n      }\n\n      /**\n       * @see AzureTemplateOptions#dataDisks(Iterable)\n       */\n      public static AzureTemplateOptions dataDisks(Iterable<DataDisk> dataDisks) {\n         AzureTemplateOptions options = new AzureTemplateOptions();\n         return options.dataDisks(dataDisks);\n      }\n\n      /**\n       * @see AzureTemplateOptions#resourceGroup(String)\n       */\n      public static AzureTemplateOptions resourceGroup(String resourceGroup) {\n         AzureTemplateOptions options = new AzureTemplateOptions();\n         return options.resourceGroup(resourceGroup);\n      }\n\n      /**\n       * @see AzureTemplateOptions#ipOptions(IpOptions...)\n       */\n      public static AzureTemplateOptions ipOptions(IpOptions... ipOptions) {\n         AzureTemplateOptions options = new AzureTemplateOptions();\n         return options.ipOptions(ipOptions);\n      }\n\n      /**\n       * @see AzureTemplateOptions#ipOptions(Iterable)\n       */\n      public static AzureTemplateOptions ipOptions(Iterable<IpOptions> ipOptions) {\n         AzureTemplateOptions options = new AzureTemplateOptions();\n         return options.ipOptions(ipOptions);\n      }\n\n      /**\n       * @see AzureTemplateOptions#windowsConfiguration(WindowsConfiguration)\n       */\n      public static AzureTemplateOptions windowsConfiguration(WindowsConfiguration windowsConfiguration) {\n         AzureTemplateOptions options = new AzureTemplateOptions();\n         return options.windowsConfiguration(windowsConfiguration);\n      }\n\n      /**\n       * @see AzureTemplateOptions#secrets(Iterable)\n       */\n      public static AzureTemplateOptions secrets(Iterable<? extends Secrets> secrets) {\n         AzureTemplateOptions options = new AzureTemplateOptions();\n         return options.secrets(secrets);\n      }\n\n      /**\n       * @see AzureTemplateOptions#customData(String)\n       */\n      public static AzureTemplateOptions customData(String customData) {\n         AzureTemplateOptions options = new AzureTemplateOptions();\n         return options.customData(customData);\n      }\n\n      /**\n       * @see AzureTemplateOptions#osDiskStorageType(StorageAccountType)\n       */\n      public static AzureTemplateOptions osDiskStorageType(StorageAccountType osDiskStorageType) {\n         AzureTemplateOptions options = new AzureTemplateOptions();\n         return options.osDiskStorageType(osDiskStorageType);\n      }\n\n      /**\n       * @see AzureTemplateOptions#planPublisher(String)\n       */\n      public static AzureTemplateOptions planPublisher(String planPublisher) {\n         AzureTemplateOptions options = new AzureTemplateOptions();\n         return options.planPublisher(planPublisher);\n      }\n\n      /**\n       * @see AzureTemplateOptions#planName(String)\n       */\n      public static AzureTemplateOptions planName(String planName) {\n         AzureTemplateOptions options = new AzureTemplateOptions();\n         return options.planName(planName);\n      }\n\n      /**\n       * @see AzureTemplateOptions#planProduct(String)\n       */\n      public static AzureTemplateOptions planProduct(String planProduct) {\n         AzureTemplateOptions options = new AzureTemplateOptions();\n         return options.planProduct(planProduct);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/compute/options/IpOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.compute.options;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.base.Optional;\n\n/**\n * Configures the ip addresses to be configured for the created nodes.\n */\n@AutoValue\npublic abstract class IpOptions {\n\n   /**\n    * The subnet where the NIC will be attached.\n    */\n   public abstract String subnet();\n\n   /**\n    * The IP address to be configured, in case of static allocation, or absent\n    * for dynamic assignment.\n    */\n   public abstract Optional<String> address();\n\n   /**\n    * Flag to indicate if a public ip address should be allocated and bound to\n    * this NIC.\n    */\n   public abstract boolean allocateNewPublicIp();\n   \n   /**\n    * ID of the public IP to associate with the NIC.\n    */\n   @Nullable\n   public abstract String publicIpId();\n   \n   IpOptions() {\n      \n   }\n\n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_IpOptions.Builder().address((String) null).allocateNewPublicIp(false);\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder subnet(String subnet);\n      public abstract Builder allocateNewPublicIp(boolean allocatePublicIp);\n      public abstract Builder publicIpId(String publicIpId);\n      \n      abstract Builder address(Optional<String> address);\n      public Builder address(String address) {\n         return address(Optional.fromNullable(address));\n      }\n      \n      public abstract IpOptions build();\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/compute/strategy/CleanupResources.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.compute.strategy;\n\nimport static com.google.common.base.Predicates.not;\nimport static com.google.common.base.Predicates.notNull;\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.transform;\nimport static com.google.common.collect.Maps.filterValues;\nimport static org.jclouds.azurecompute.arm.compute.AzureComputeServiceAdapter.AUTOGENERATED_IP_KEY;\nimport static org.jclouds.azurecompute.arm.config.AzureComputeProperties.TIMEOUT_RESOURCE_DELETED;\nimport static org.jclouds.azurecompute.arm.domain.IdReference.extractName;\nimport static org.jclouds.azurecompute.arm.domain.IdReference.extractResourceGroup;\n\nimport java.net.URI;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.azurecompute.arm.AzureComputeApi;\nimport org.jclouds.azurecompute.arm.compute.domain.ResourceGroupAndName;\nimport org.jclouds.azurecompute.arm.domain.AvailabilitySet;\nimport org.jclouds.azurecompute.arm.domain.DataDisk;\nimport org.jclouds.azurecompute.arm.domain.IdReference;\nimport org.jclouds.azurecompute.arm.domain.IpConfiguration;\nimport org.jclouds.azurecompute.arm.domain.ManagedDiskParameters;\nimport org.jclouds.azurecompute.arm.domain.NetworkInterfaceCard;\nimport org.jclouds.azurecompute.arm.domain.NetworkProfile.NetworkInterface;\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityGroup;\nimport org.jclouds.azurecompute.arm.domain.OSDisk;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachine;\nimport org.jclouds.azurecompute.arm.domain.publicipaddress.PublicIPAddress;\nimport org.jclouds.azurecompute.arm.features.NetworkSecurityGroupApi;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Joiner;\nimport com.google.common.base.Predicate;\n\n@Singleton\npublic class CleanupResources {\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   private final AzureComputeApi api;\n   private final Predicate<URI> resourceDeleted;\n   private final GroupNamingConvention.Factory namingConvention;\n\n   @Inject\n   CleanupResources(AzureComputeApi azureComputeApi, @Named(TIMEOUT_RESOURCE_DELETED) Predicate<URI> resourceDeleted,\n         GroupNamingConvention.Factory namingConvention) {\n      this.api = azureComputeApi;\n      this.resourceDeleted = resourceDeleted;\n      this.namingConvention = namingConvention;\n   }\n\n   public boolean cleanupNode(final String id) {\n      ResourceGroupAndName resourceGroupAndName = ResourceGroupAndName.fromSlashEncoded(id);\n      String resourceGroupName = resourceGroupAndName.resourceGroup();\n\n      VirtualMachine virtualMachine = api.getVirtualMachineApi(resourceGroupName).get(resourceGroupAndName.name());\n      if (virtualMachine == null) {\n         return true;\n      }\n\n      logger.debug(\">> destroying %s ...\", id);\n      boolean vmDeleted = deleteVirtualMachine(resourceGroupName, virtualMachine);\n\n      // We don't delete the network here, as it is global to the resource\n      // group. It will be deleted when the resource group is deleted\n\n      cleanupVirtualMachineNICs(virtualMachine);\n      cleanupManagedDisks(virtualMachine);\n      cleanupAvailabilitySetIfOrphaned(virtualMachine);\n\n      return vmDeleted;\n   }\n\n   public boolean cleanupVirtualMachineNICs(VirtualMachine virtualMachine) {\n      boolean deleted = true;\n      for (NetworkInterface nicRef : virtualMachine.properties().networkProfile().networkInterfaces()) {\n         String nicResourceGroup = extractResourceGroup(nicRef.id());\n         String nicName = extractName(nicRef.id());\n         NetworkInterfaceCard nic = api.getNetworkInterfaceCardApi(nicResourceGroup).get(nicName);\n\n         Iterable<IdReference> publicIps = getPublicIps(nic);\n\n         logger.debug(\">> destroying nic %s...\", nicName);\n         URI nicDeletionURI = api.getNetworkInterfaceCardApi(nicResourceGroup).delete(nicName);\n         deleted &= nicDeletionURI == null || resourceDeleted.apply(nicDeletionURI);\n\n         for (IdReference publicIp : publicIps) {\n            String publicIpResourceGroup = publicIp.resourceGroup();\n            String publicIpName = publicIp.name();\n\n            PublicIPAddress ip = api.getPublicIPAddressApi(publicIpResourceGroup).get(publicIpName);\n            if (ip.tags() != null && Boolean.parseBoolean(ip.tags().get(AUTOGENERATED_IP_KEY))) {\n               logger.debug(\">> deleting public ip %s...\", publicIpName);\n               deleted &= api.getPublicIPAddressApi(publicIpResourceGroup).delete(publicIpName);\n            }\n         }\n      }\n      return deleted;\n   }\n\n   public boolean cleanupManagedDisks(VirtualMachine virtualMachine) {\n      Map<String, URI> deleteJobs = new HashMap<String, URI>();\n\n      OSDisk osDisk = virtualMachine.properties().storageProfile().osDisk();\n      deleteManagedDisk(osDisk.managedDiskParameters(), deleteJobs);\n\n      for (DataDisk dataDisk : virtualMachine.properties().storageProfile().dataDisks()) {\n         deleteManagedDisk(dataDisk.managedDiskParameters(), deleteJobs);\n      }\n\n      Set<String> nonDeletedDisks = filterValues(deleteJobs, not(resourceDeleted)).keySet();\n      if (!nonDeletedDisks.isEmpty()) {\n         logger.warn(\">> could not delete disks: %s\", Joiner.on(',').join(nonDeletedDisks));\n      }\n\n      return nonDeletedDisks.isEmpty();\n   }\n\n   private void deleteManagedDisk(@Nullable ManagedDiskParameters managedDisk, Map<String, URI> deleteJobs) {\n      if (managedDisk != null) {\n         IdReference diskRef = IdReference.create(managedDisk.id());\n         logger.debug(\">> deleting managed disk %s...\", diskRef.name());\n         URI uri = api.getDiskApi(diskRef.resourceGroup()).delete(diskRef.name());\n         if (uri != null) {\n            deleteJobs.put(diskRef.name(), uri);\n         }\n      }\n   }\n\n   public boolean cleanupSecurityGroupIfOrphaned(String resourceGroup, String group) {\n      String name = namingConvention.create().sharedNameForGroup(group);\n      NetworkSecurityGroupApi sgapi = api.getNetworkSecurityGroupApi(resourceGroup);\n\n      boolean deleted = false;\n\n      try {\n         NetworkSecurityGroup securityGroup = sgapi.get(name);\n         if (securityGroup != null) {\n            List<NetworkInterfaceCard> nics = securityGroup.properties().networkInterfaces();\n            if (nics == null || nics.isEmpty()) {\n               logger.debug(\">> deleting orphaned security group %s from %s...\", name, resourceGroup);\n               try {\n                  deleted = resourceDeleted.apply(sgapi.delete(name));\n               } catch (Exception ex) {\n                  logger.warn(ex, \">> error deleting orphaned security group %s from %s...\", name, resourceGroup);\n               }\n            }\n         }\n      } catch (Exception ex) {\n         logger.warn(ex, \"Error deleting security groups for %s and group %s\", resourceGroup, group);\n      }\n\n      return deleted;\n   }\n\n   public boolean cleanupAvailabilitySetIfOrphaned(VirtualMachine virtualMachine) {\n      boolean deleted = true;\n      IdReference availabilitySetRef = virtualMachine.properties().availabilitySet();\n\n      if (availabilitySetRef != null) {\n         String name = availabilitySetRef.name();\n         String resourceGroup = availabilitySetRef.resourceGroup();\n         AvailabilitySet availabilitySet = api.getAvailabilitySetApi(resourceGroup).get(name);\n\n         if (isOrphanedJcloudsAvailabilitySet(availabilitySet)) {\n            logger.debug(\">> deleting orphaned availability set %s from %s...\", name, resourceGroup);\n            URI uri = api.getAvailabilitySetApi(resourceGroup).delete(name);\n            deleted = uri == null || resourceDeleted.apply(uri);\n         }\n      }\n\n      return deleted;\n   }\n\n   public boolean deleteResourceGroupIfEmpty(String group) {\n      boolean deleted = false;\n      if (api.getResourceGroupApi().resources(group).isEmpty()) {\n         logger.debug(\">> the resource group %s is empty. Deleting...\", group);\n         deleted = resourceDeleted.apply(api.getResourceGroupApi().delete(group));\n      }\n      return deleted;\n   }\n\n   private Iterable<IdReference> getPublicIps(NetworkInterfaceCard nic) {\n      return filter(transform(nic.properties().ipConfigurations(), new Function<IpConfiguration, IdReference>() {\n         @Override\n         public IdReference apply(IpConfiguration input) {\n            return input.properties().publicIPAddress();\n         }\n      }), notNull());\n   }\n\n   private static boolean isOrphanedJcloudsAvailabilitySet(AvailabilitySet availabilitySet) {\n      // We check for the presence of the 'jclouds' tag to make sure we only\n      // delete availability sets that were automatically created by jclouds\n      return availabilitySet != null\n            && availabilitySet.tags() != null\n            && availabilitySet.tags().containsKey(\"jclouds\")\n            && (availabilitySet.properties().virtualMachines() == null || availabilitySet.properties()\n                  .virtualMachines().isEmpty());\n   }\n\n   private boolean deleteVirtualMachine(String group, VirtualMachine virtualMachine) {\n      return resourceDeleted.apply(api.getVirtualMachineApi(group).delete(virtualMachine.name()));\n   }\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/compute/strategy/CreateResourcesThenCreateNodes.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.compute.strategy;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static org.jclouds.azurecompute.arm.config.AzureComputeProperties.DEFAULT_SUBNET_ADDRESS_PREFIX;\nimport static org.jclouds.azurecompute.arm.config.AzureComputeProperties.DEFAULT_VNET_ADDRESS_SPACE_PREFIX;\nimport static org.jclouds.azurecompute.arm.domain.IdReference.extractName;\nimport static org.jclouds.azurecompute.arm.domain.IdReference.extractResourceGroup;\nimport static org.jclouds.azurecompute.arm.domain.Subnet.extractVirtualNetwork;\n\nimport java.util.Arrays;\nimport java.util.Map;\nimport java.util.Set;\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Constants;\nimport org.jclouds.azurecompute.arm.AzureComputeApi;\nimport org.jclouds.azurecompute.arm.compute.config.AzurePredicatesModule.NetworkAvailablePredicateFactory;\nimport org.jclouds.azurecompute.arm.compute.domain.ResourceGroupAndName;\nimport org.jclouds.azurecompute.arm.compute.domain.ResourceGroupAndNameAndIngressRules;\nimport org.jclouds.azurecompute.arm.compute.functions.TemplateToAvailabilitySet;\nimport org.jclouds.azurecompute.arm.compute.options.AzureTemplateOptions;\nimport org.jclouds.azurecompute.arm.compute.options.IpOptions;\nimport org.jclouds.azurecompute.arm.domain.AddressSpace;\nimport org.jclouds.azurecompute.arm.domain.AvailabilitySet;\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityGroup;\nimport org.jclouds.azurecompute.arm.domain.ResourceGroup;\nimport org.jclouds.azurecompute.arm.domain.Subnet;\nimport org.jclouds.azurecompute.arm.domain.Subnet.SubnetProperties;\nimport org.jclouds.azurecompute.arm.domain.VirtualNetwork.VirtualNetworkProperties;\nimport org.jclouds.azurecompute.arm.domain.publicipaddress.PublicIPAddress;\nimport org.jclouds.compute.config.CustomizationResponse;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.compute.strategy.CreateNodeWithGroupEncodedIntoName;\nimport org.jclouds.compute.strategy.CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap;\nimport org.jclouds.compute.strategy.ListNodesStrategy;\nimport org.jclouds.compute.strategy.impl.CreateNodesWithGroupEncodedIntoNameThenAddToSet;\nimport org.jclouds.domain.Location;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.util.PasswordGenerator;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Optional;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Multimap;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.ListeningExecutorService;\n\n@Singleton\npublic class CreateResourcesThenCreateNodes extends CreateNodesWithGroupEncodedIntoNameThenAddToSet {\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   private final AzureComputeApi api;\n   private final LoadingCache<ResourceGroupAndNameAndIngressRules, String> securityGroupMap;\n   private final String defaultVnetAddressPrefix;\n   private final String defaultSubnetAddressPrefix;\n   private final TemplateToAvailabilitySet templateToAvailabilitySet;\n   private final PasswordGenerator.Config passwordGenerator;\n   private final NetworkAvailablePredicateFactory networkAvailable;\n\n   @Inject\n   protected CreateResourcesThenCreateNodes(\n         CreateNodeWithGroupEncodedIntoName addNodeWithGroupStrategy,\n         ListNodesStrategy listNodesStrategy,\n         GroupNamingConvention.Factory namingConvention,\n         @Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor,\n         CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap.Factory customizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapFactory,\n         AzureComputeApi api, @Named(DEFAULT_VNET_ADDRESS_SPACE_PREFIX) String defaultVnetAddressPrefix,\n         @Named(DEFAULT_SUBNET_ADDRESS_PREFIX) String defaultSubnetAddressPrefix,\n         LoadingCache<ResourceGroupAndNameAndIngressRules, String> securityGroupMap,\n         TemplateToAvailabilitySet templateToAvailabilitySet, PasswordGenerator.Config passwordGenerator,\n         NetworkAvailablePredicateFactory networkAvailable) {\n      super(addNodeWithGroupStrategy, listNodesStrategy, namingConvention, userExecutor,\n            customizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapFactory);\n      this.api = api;\n      this.securityGroupMap = securityGroupMap;\n      this.defaultVnetAddressPrefix = defaultVnetAddressPrefix;\n      this.defaultSubnetAddressPrefix = defaultSubnetAddressPrefix;\n      this.templateToAvailabilitySet = templateToAvailabilitySet;\n      this.passwordGenerator = passwordGenerator;\n      this.networkAvailable = networkAvailable;\n   }\n\n   @Override\n   public Map<?, ListenableFuture<Void>> execute(String group, int count, Template template,\n         Set<NodeMetadata> goodNodes, Map<NodeMetadata, Exception> badNodes,\n         Multimap<NodeMetadata, CustomizationResponse> customizationResponses) {\n\n      AzureTemplateOptions options = template.getOptions().as(AzureTemplateOptions.class);\n\n      // TODO Generate a private key instead. Also no need to use AUTHENTICATE_SUDO in this case.\n      generatePasswordIfNoneProvided(template);\n      \n      // If there is a script to be run on the node and public key\n      // authentication has been configured, warn users if the private key\n      // is not present\n      if (hasRunScriptWithKeyAuthAndNoPrivateKey(template)) {\n         logger.warn(\">> a runScript was configured but no SSH key has been provided. \"\n               + \"Authentication will delegate to the ssh-agent\");\n      }\n\n      String location = template.getLocation().getId();\n\n      createResourceGroupIfNeeded(group, location, options);\n      \n      normalizeNetworkOptions(options);\n      createDefaultNetworkIfNeeded(group, location, options);\n      \n      configureSecurityGroupForOptions(group, template.getLocation(), options);\n      configureAvailabilitySetForTemplate(template);\n\n      return super.execute(group, count, template, goodNodes, badNodes, customizationResponses);\n   }\n\n   // Azure requires that we pass it the VM password. Need to generate one if not overridden by the user.\n   private void generatePasswordIfNoneProvided(Template template) {\n      TemplateOptions options = template.getOptions();\n      if (options.getLoginPassword() == null) {\n         Optional<String> passwordOptional = template.getImage().getDefaultCredentials().getOptionalPassword();\n         options.overrideLoginPassword(passwordOptional.or(passwordGenerator.generate()));\n      }\n   }\n\n   protected synchronized void createDefaultNetworkIfNeeded(String group, String location, AzureTemplateOptions options) {\n      if (options.getIpOptions().isEmpty()) {\n         String name = namingConvention.create().sharedNameForGroup(group);\n         \n         Subnet subnet = Subnet.builder().name(name)\n               .properties(SubnetProperties.builder().addressPrefix(defaultSubnetAddressPrefix).build()).build();\n         \n         VirtualNetworkProperties properties = VirtualNetworkProperties.builder()\n               .addressSpace(AddressSpace.create(Arrays.asList(defaultVnetAddressPrefix)))\n               .subnets(Arrays.asList(subnet)).build();\n         \n         logger.debug(\">> network options have not been configured. Creating network %s(%s) and subnet %s(%s)\", name,\n               defaultVnetAddressPrefix, name, defaultSubnetAddressPrefix);\n         \n         api.getVirtualNetworkApi(options.getResourceGroup()).createOrUpdate(name, location, null, properties);\n\n         checkState(networkAvailable.create(options.getResourceGroup()).apply(name),\n               \"Network/Subnet was not created in the configured timeout\");\n\n         Subnet createdSubnet = api.getSubnetApi(options.getResourceGroup(), name).get(name);\n\n         options.ipOptions(IpOptions.builder().subnet(createdSubnet.id()).allocateNewPublicIp(true).build());\n      }\n   }\n\n   private static boolean hasRunScriptWithKeyAuthAndNoPrivateKey(Template template) {\n      return template.getOptions().getRunScript() != null && template.getOptions().getPublicKey() != null\n            && !template.getOptions().hasLoginPrivateKeyOption();\n   }\n\n   private void configureSecurityGroupForOptions(String group, Location location, AzureTemplateOptions options) {\n\n      checkArgument(options.getGroups().size() <= 1,\n            \"Only one security group can be configured for each network interface\");\n\n      if (!options.getGroups().isEmpty()) {\n         ResourceGroupAndName securityGroupId = ResourceGroupAndName.fromSlashEncoded(getOnlyElement(options.getGroups()));\n         NetworkSecurityGroup securityGroup = api.getNetworkSecurityGroupApi(securityGroupId.resourceGroup()).get(\n               securityGroupId.name());\n         checkArgument(securityGroup != null, \"Security group %s was not found\", securityGroupId.slashEncode());\n         options.securityGroups(securityGroup.id());\n      } else if (options.getInboundPorts().length > 0) {\n         String name = namingConvention.create().sharedNameForGroup(group);\n         ResourceGroupAndNameAndIngressRules regionAndIdAndIngressRules = ResourceGroupAndNameAndIngressRules.create(\n               options.getResourceGroup(), location.getId(), name, options.getInboundPorts());\n         // this will create if not yet exists.\n         String securityGroupId = securityGroupMap.getUnchecked(regionAndIdAndIngressRules);\n         options.securityGroups(securityGroupId);\n      }\n   }\n   \n   private void configureAvailabilitySetForTemplate(Template template) {\n      AvailabilitySet availabilitySet = templateToAvailabilitySet.apply(template);\n      if (availabilitySet != null) {\n         logger.debug(\">> configuring nodes in availability set [%s]\", availabilitySet.name());\n         template.getOptions().as(AzureTemplateOptions.class).availabilitySet(availabilitySet);\n      }\n   }\n   \n   private void createResourceGroupIfNeeded(String group, String location, AzureTemplateOptions options) {\n      if (options.getResourceGroup() == null) {\n         options.resourceGroup(group);\n      }\n      logger.debug(\">> using resource group [%s]\", options.getResourceGroup());\n      ResourceGroup rg = api.getResourceGroupApi().get(options.getResourceGroup());\n      if (rg == null) {\n         logger.debug(\">> resource group [%s] does not exist. Creating!\", options.getResourceGroup());\n         api.getResourceGroupApi().create(options.getResourceGroup(), location,\n               ImmutableMap.of(\"description\", \"jclouds default resource group\"));\n      }\n   }\n   \n   @VisibleForTesting\n   void normalizeNetworkOptions(AzureTemplateOptions options) {\n      if (!options.getNetworks().isEmpty() && !options.getIpOptions().isEmpty()) {\n         throw new IllegalArgumentException(\"The options.networks and options.ipOptions are exclusive\");\n      }\n      \n      if (!options.getNetworks().isEmpty()) {\n         // The portable interface allows to configure network IDs (subnet IDs),\n         // but we don't know the type of the IP configurations to be applied\n         // when attaching nodes to those networks. We'll assume private IPs\n         // with Dynamic allocation and new public ip address allocated.\n         ImmutableList.Builder<IpOptions> ipOptions = ImmutableList.builder();\n         for (String subnetId : options.getNetworks()) {\n            ipOptions.add(IpOptions.builder().subnet(subnetId).allocateNewPublicIp(true).build());\n         }\n         options.ipOptions(ipOptions.build());\n      }\n      \n      if (!options.getIpOptions().isEmpty()) {\n         // Eagerly validate that all configured subnets exist.\n         for (IpOptions ipConfig : options.getIpOptions()) {\n            if (ipConfig.allocateNewPublicIp() && ipConfig.publicIpId() != null) {\n               throw new IllegalArgumentException(\"The allocateNewPublicIps and publicIpId are exclusive\");\n            }\n            \n            String resourceGroup = extractResourceGroup(ipConfig.subnet());\n            String networkName = extractVirtualNetwork(ipConfig.subnet());\n            String subnetName = extractName(ipConfig.subnet());\n            Subnet subnet = api.getSubnetApi(resourceGroup, networkName).get(subnetName);\n            checkState(subnet != null, \"Configured subnet %s does not exist\", ipConfig.subnet());\n            \n            if (ipConfig.publicIpId() != null) {\n               PublicIPAddress publicIp = api.getPublicIPAddressApi(extractResourceGroup(ipConfig.publicIpId())).get(\n                     extractName(ipConfig.publicIpId()));\n               checkState(publicIp != null, \"Configured public ip %s does not exist\", ipConfig.publicIpId());               \n            }\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/config/AzureComputeHttpApiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.config;\n\nimport static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL;\n\nimport java.net.URI;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicReference;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.azurecompute.arm.AzureComputeApi;\nimport org.jclouds.azurecompute.arm.compute.config.AzureNameValidator;\nimport org.jclouds.azurecompute.arm.config.GraphRBAC.GraphRBACForTenant;\nimport org.jclouds.azurecompute.arm.domain.ServicePrincipal;\nimport org.jclouds.azurecompute.arm.handlers.AzureComputeErrorHandler;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.annotation.ClientError;\nimport org.jclouds.http.annotation.Redirection;\nimport org.jclouds.http.annotation.ServerError;\nimport org.jclouds.location.suppliers.ImplicitLocationSupplier;\nimport org.jclouds.location.suppliers.implicit.FirstRegion;\nimport org.jclouds.oauth.v2.config.OAuthConfigFactory;\nimport org.jclouds.oauth.v2.config.OAuthScopes;\nimport org.jclouds.predicates.Validator;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.config.HttpApiModule;\nimport org.jclouds.rest.suppliers.MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier;\n\nimport com.google.common.base.Supplier;\nimport com.google.inject.Provides;\nimport com.google.inject.Scopes;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.name.Named;\n\n@ConfiguresHttpApi\npublic class AzureComputeHttpApiModule extends HttpApiModule<AzureComputeApi> {\n\n   private static final Pattern OAUTH_TENANT_PATTERN = Pattern\n         .compile(\"https://login.(microsoft(?:online)?.com|chinacloudapi.cn)/([^/]+)/oauth2/token\");\n\n   private static final Pattern CHINA_OAUTH_ENDPOINT_PATTERN = Pattern\n         .compile(\"https://login.chinacloudapi.cn/([^/]+)/oauth2/token\");\n\n   public static final String IS_CHINA_ENDPOINT = \"jclouds.isChinaEndpoint\";\n\n   @Override\n   protected void bindErrorHandlers() {\n      bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(AzureComputeErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(AzureComputeErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(AzureComputeErrorHandler.class);\n   }\n\n   @Override\n   protected void installLocations() {\n      super.installLocations();\n      bind(ImplicitLocationSupplier.class).to(FirstRegion.class).in(Scopes.SINGLETON);\n   }\n\n   @Override\n   protected void configure() {\n      super.configure();\n      bind(OAuthScopes.class).toInstance(OAuthScopes.NoScopes.create());\n      bind(OAuthConfigFactory.class).to(AzureOAuthConfigFactory.class).in(Scopes.SINGLETON);\n      bind(new TypeLiteral<Validator<String>>() {\n      }).to(AzureNameValidator.class).in(Scopes.SINGLETON);\n      bindServiceEndpoints();\n   }\n\n   protected void bindServiceEndpoints() {\n      bind(new TypeLiteral<Supplier<URI>>() {\n      }).annotatedWith(GraphRBAC.class).to(GraphRBACForTenant.class).in(Scopes.SINGLETON);\n   }\n\n   @Provides\n   @Singleton\n   @Tenant\n   protected final String provideTenant(@Named(\"oauth.endpoint\") final String oauthEndpoint) {\n      Matcher m = OAUTH_TENANT_PATTERN.matcher(oauthEndpoint);\n      if (!m.matches()) {\n         throw new IllegalArgumentException(\"Could not parse tenantId from: \" + oauthEndpoint);\n      }\n      return m.group(2);\n   }\n\n   @Provides\n   @Singleton\n   @Named(IS_CHINA_ENDPOINT)\n   protected final boolean isChinaEndpoint(@Named(\"oauth.endpoint\") final String oauthEndpoint) {\n      return CHINA_OAUTH_ENDPOINT_PATTERN.matcher(oauthEndpoint).matches();\n   }\n\n   @Provides\n   @Singleton\n   protected final Supplier<ServicePrincipal> provideServicePrincipal(final AzureComputeApi api,\n         AtomicReference<AuthorizationException> authException, @Named(PROPERTY_SESSION_INTERVAL) long seconds) {\n      // This supplier must be defensive against any auth exception.\n      return MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier.create(authException,\n            new Supplier<ServicePrincipal>() {\n               @Override\n               public ServicePrincipal get() {\n                  return api.getGraphRBACApi().getCurrentServicePrincipal();\n               }\n            }, seconds, TimeUnit.SECONDS);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/config/AzureComputeParserModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.config;\n\nimport org.jclouds.json.config.GsonModule;\n\nimport com.google.inject.AbstractModule;\n\npublic class AzureComputeParserModule extends AbstractModule {\n\n   @Override\n   protected void configure() {\n      bind(GsonModule.DateAdapter.class).to(GsonModule.Iso8601DateAdapter.class);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/config/AzureComputeProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.config;\n\n/**\n * Configuration properties and constants used in Azure Resource Manager\n * connections.\n */\npublic class AzureComputeProperties {\n\n   public static final String OPERATION_TIMEOUT = \"jclouds.azurecompute.arm.operation.timeout\";\n   \n   public static final String IMAGE_PUBLISHERS = \"jclouds.azurecompute.arm.publishers\";\n\n   public static final String TIMEOUT_RESOURCE_DELETED = \"jclouds.azurecompute.arm.timeout.resourcedeleted\";\n\n   public static final String DEFAULT_VNET_ADDRESS_SPACE_PREFIX = \"jclouds.azurecompute.arm.vnet.addressprefix\";\n\n   public static final String DEFAULT_SUBNET_ADDRESS_PREFIX = \"jclouds.azurecompute.arm.subnet.addressprefix\";\n\n   public static final String API_VERSION_PREFIX = \"jclouds.azurecompute.arm.apiversion.\";\n\n   // Predicate constants\n   public static final String VAULT_DELETE_STATUS = \"jclouds.azurecompute.arm.vault.delete_status\";\n   public static final String VAULT_KEY_DELETED_STATUS = \"jclouds.azurecompute.arm.vault.key.delete_status\";\n   public static final String VAULT_KEY_RECOVERABLE_STATUS = \"jclouds.azurecompute.arm.vault.key.recoverable_status\";\n   public static final String VAULT_SECRET_DELETE_STATUS = \"jclouds.azurecompute.arm.vault.secret.delete_status\";\n   public static final String VAULT_SECRET_RECOVERABLE_STATUS = \"jclouds.azurecompute.arm.vault.secret.recoverable_status\";\n   public static final String VAULT_CERTIFICATE_DELETE_STATUS = \"jclouds.azurecompute.arm.vault.certificate.delete_status\";\n   public static final String VAULT_CERTIFICATE_RECOVERABLE_STATUS = \"jclouds.azurecompute.arm.vault.certificate.recoverable_status\";\n   public static final String VAULT_CERTIFICATE_OPERATION_STATUS = \"jclouds.azurecompute.arm.vault.certificate.operation_status\";\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/config/AzureComputeRateLimitModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.config;\n\nimport org.jclouds.azurecompute.arm.handlers.AzureRateLimitRetryHandler;\nimport org.jclouds.http.HttpRetryHandler;\nimport org.jclouds.http.annotation.ClientError;\n\nimport com.google.inject.AbstractModule;\n\npublic class AzureComputeRateLimitModule extends AbstractModule {\n   @Override\n   protected void configure() {\n      bind(HttpRetryHandler.class).annotatedWith(ClientError.class).to(AzureRateLimitRetryHandler.class);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/config/AzureOAuthConfigFactory.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.config;\n\nimport static org.jclouds.azurecompute.arm.config.AzureComputeHttpApiModule.IS_CHINA_ENDPOINT;\nimport static org.jclouds.oauth.v2.config.OAuthProperties.AUDIENCE;\nimport static org.jclouds.oauth.v2.config.OAuthProperties.RESOURCE;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.oauth.v2.config.OAuthConfigFactory;\nimport org.jclouds.oauth.v2.config.OAuthScopes;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\n\nimport com.google.inject.Inject;\nimport com.google.inject.name.Named;\n\npublic class AzureOAuthConfigFactory implements OAuthConfigFactory {\n   private final OAuthScopes scopes;\n\n   @Named(AUDIENCE)\n   @Inject(optional = true)\n   private String audience;\n   \n   @Named(RESOURCE)\n   @Inject(optional = true)\n   private String resource;\n\n   @Named(IS_CHINA_ENDPOINT)\n   @Inject(optional = true)\n   private boolean isChinaEndpoint;\n\n   @Inject\n   AzureOAuthConfigFactory(OAuthScopes scopes) {\n      this.scopes = scopes;\n   }\n\n   @Override\n   public OAuthConfig forRequest(HttpRequest input) {\n      OAuthResource customResource = null;\n      if (input instanceof GeneratedHttpRequest) {\n         GeneratedHttpRequest request = (GeneratedHttpRequest) input;\n         customResource = request.getInvocation().getInvokable().getAnnotation(OAuthResource.class);\n         if (customResource == null) {\n            customResource = request.getInvocation().getInvokable().getDeclaringClass()\n                  .getAnnotation(OAuthResource.class);\n         }\n      }\n      String oauthResource = customResource == null ?\n            resource :\n            (isChinaEndpoint ? customResource.chinaEndpoint() : customResource.value());\n      return OAuthConfig.create(scopes.forRequest(input), audience, oauthResource);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/config/GraphRBAC.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.config;\n\nimport static org.jclouds.azurecompute.arm.config.AzureComputeHttpApiModule.IS_CHINA_ENDPOINT;\n\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\nimport java.net.URI;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Qualifier;\n\nimport com.google.common.base.Supplier;\n\n/**\n * Provides the Graph RBAC API endpoint for the current tenant.\n */\n@Retention(value = RetentionPolicy.RUNTIME)\n@Target(value = {ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})\n@Qualifier\npublic @interface GraphRBAC {\n\n   String STANDARD_ENDPOINT = \"https://graph.windows.net/\";\n   String CHINA_ENDPOINT = \"https://graph.chinacloudapi.cn/\";\n\n   static class GraphRBACForTenant implements Supplier<URI> {\n      private final String tenantId;\n      private final boolean isChinaEndpoint;\n\n      @Inject\n      GraphRBACForTenant(@Tenant String tenantId, @Named(IS_CHINA_ENDPOINT) boolean isChinaEndpoint) {\n         this.tenantId = tenantId;\n         this.isChinaEndpoint = isChinaEndpoint;\n      }\n\n      @Override\n      public URI get() {\n         return URI.create((isChinaEndpoint ? CHINA_ENDPOINT : STANDARD_ENDPOINT) + tenantId);\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/config/OAuthResource.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.config;\n\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\nimport jakarta.inject.Qualifier;\n\n/**\n * Configures a custom OAuth resource for certain APIs and methods.\n */\n@Retention(value = RetentionPolicy.RUNTIME)\n@Target(value = { ElementType.TYPE, ElementType.METHOD })\n@Qualifier\npublic @interface OAuthResource {\n\n   String value();\n\n   String chinaEndpoint();\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/config/Tenant.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.config;\n\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\nimport jakarta.inject.Qualifier;\n\n/**\n * Qualifies an object that describes the current tenant.\n */\n@Retention(value = RetentionPolicy.RUNTIME)\n@Target(value = {ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})\n@Qualifier\npublic @interface Tenant {\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/ActionGroup.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class ActionGroup {\n\t@Nullable\n\tpublic abstract String actionGroupId();\n\n\t@Nullable\n\tpublic abstract Object webhookProperties();\n\n\t@SerializedNames({ \"actionGroupId\", \"webhookProperties\" })\n\tpublic static ActionGroup create(final String actionGroupId, final Object webhookProperties) {\n\t\treturn builder().actionGroupId(actionGroupId).webhookProperties(webhookProperties).build();\n\t}\n\n\tpublic abstract Builder toBuilder();\n\n\tpublic static Builder builder() {\n\t\treturn new AutoValue_ActionGroup.Builder();\n\t}\n\n\t@AutoValue.Builder\n\tpublic abstract static class Builder {\n\t\tpublic abstract Builder actionGroupId(String actionGroupId);\n\n\t\tpublic abstract Builder webhookProperties(Object webhookProperties);\n\n\t\tpublic abstract ActionGroup build();\n\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/ActionStatus.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class ActionStatus {\n\n\tpublic abstract boolean isSuppressed();\n\n\t@SerializedNames({ \"isSuppressed\" })\n\tpublic static ActionStatus create(final boolean isSuppressed) {\n\t\treturn new AutoValue_ActionStatus(isSuppressed);\n\n\t}\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/Actions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\n\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\n@AutoValue\npublic abstract class Actions {\n\n\t@Nullable\n\tpublic abstract List<ActionGroup> actionGroups();\n\n\t@SerializedNames({ \"actionGroups\" })\n\tpublic static Actions create(final List<ActionGroup> actionGroups) {\n\t\treturn new AutoValue_Actions(actionGroups);\n\n\t}\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/ActivityLogAlert.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport java.util.Map;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableMap;\n\n@AutoValue\npublic abstract class ActivityLogAlert {\n\n\t/**\n\t * The id of the resource\n\t */\n\tpublic abstract String id();\n\n\t/**\n\t * The name of the resource\n\t */\n\tpublic abstract String name();\n\n\t/**\n\t * The location of the resource\n\t */\n\tpublic abstract String location();\n\n\t/**\n\t * The type of the resource\n\t */\n\tpublic abstract String type();\n\n\t@Nullable\n\tpublic abstract Map<String, String> tags();\n\n\t@Nullable\n\tpublic abstract ActivityLogAlertProperties properties();\n\n\t@SerializedNames({ \"id\", \"name\", \"location\", \"type\", \"tags\", \"properties\" })\n\tpublic static ActivityLogAlert create(final String id, final String name, final String location,\n\t\t\tfinal String type, final Map<String, String> tags, final ActivityLogAlertProperties properties) {\n\t\treturn builder().id(id).name(name).location(location).type(type).tags(tags).properties(properties).build();\n\t}\n\n\tpublic abstract Builder toBuilder();\n\n\tpublic static Builder builder() {\n\t\treturn new AutoValue_ActivityLogAlert.Builder();\n\t}\n\n\t@AutoValue.Builder\n\tpublic abstract static class Builder {\n\t\tpublic abstract Builder id(String id);\n\n\t\tpublic abstract Builder name(String name);\n\n\t\tpublic abstract Builder location(String location);\n\n\t\tpublic abstract Builder type(String type);\n\n\t\tpublic abstract Builder tags(Map<String, String> tags);\n\n\t\tpublic abstract Builder properties(ActivityLogAlertProperties properties);\n\n\t\tabstract Map<String, String> tags();\n\n\t\tabstract ActivityLogAlert autoBuild();\n\n\t\tpublic ActivityLogAlert build() {\n\t\t\ttags(tags() != null ? ImmutableMap.copyOf(tags()) : null);\n\t\t\treturn autoBuild();\n\t\t}\n\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/ActivityLogAlertProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class ActivityLogAlertProperties {\n\n\t@Nullable\n\tpublic abstract String description();\n\t\n\tpublic abstract boolean enabled();\n\n\t@Nullable\n\tpublic abstract List<String> scopes();\n\n\t@Nullable\n\tpublic abstract AlertRuleAllOfCondition condition();\n\n\t@Nullable\n\tpublic abstract Actions actions();\n\n\t@SerializedNames({ \"description\", \"enabled\", \"scopes\", \"condition\", \"actions\" })\n\tpublic static ActivityLogAlertProperties create(final String description, final boolean enabled,\n\t\t\tfinal List<String> scopes, final AlertRuleAllOfCondition condition, final Actions actions) {\n\t\treturn builder().description(description).enabled(enabled).scopes(scopes).condition(condition).actions(actions)\n\t\t\t\t.build();\n\t}\n\n\tpublic abstract Builder toBuilder();\n\n\tpublic static Builder builder() {\n\t\treturn new AutoValue_ActivityLogAlertProperties.Builder();\n\t}\n\n\t@AutoValue.Builder\n\tpublic abstract static class Builder {\n\t\tpublic abstract Builder description(String description);\n\n\t\tpublic abstract Builder enabled(boolean enabled);\n\n\t\tpublic abstract Builder scopes(List<String> scopes);\n\n\t\tpublic abstract Builder condition(AlertRuleAllOfCondition condition);\n\n\t\tpublic abstract Builder actions(Actions actions);\n\n\t\tpublic abstract ActivityLogAlertProperties build();\n\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/AddressSpace.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport java.util.List;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\n\n@AutoValue\npublic abstract class AddressSpace {\n   public abstract List<String> addressPrefixes();\n\n   @SerializedNames({ \"addressPrefixes\" })\n   public static AddressSpace create(List<String> addressPrefixes) {\n      return new AutoValue_AddressSpace(addressPrefixes == null ? ImmutableList.<String> of()\n            : ImmutableList.copyOf(addressPrefixes));\n   }\n\n   AddressSpace() {\n\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/Alert.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class Alert {\n\n\tpublic abstract String id();\n\n\tpublic abstract String name();\n\n\tpublic abstract String type();\n\n\t@Nullable\n\tpublic abstract AlertProperties properties();\n\n\t@SerializedNames({ \"id\", \"name\", \"type\", \"properties\" })\n\tpublic static Alert create(final String id, final String name, final String type,\n\t\t\tfinal AlertProperties properties) {\n\t\treturn builder().id(id).name(name).type(type).properties(properties).build();\n\t}\n\n\tpublic abstract Builder toBuilder();\n\n\tpublic static Builder builder() {\n\t\treturn new AutoValue_Alert.Builder();\n\t}\n\n\t@AutoValue.Builder\n\tpublic abstract static class Builder {\n\t\tpublic abstract Builder id(String id);\n\n\t\tpublic abstract Builder name(String name);\n\n\t\tpublic abstract Builder type(String type);\n\n\t\tpublic abstract Builder properties(AlertProperties properties);\n\n\t\tpublic abstract Alert build();\n\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/AlertModification.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class AlertModification {\n\n\tpublic abstract String id();\n\n\tpublic abstract String name();\n\n\tpublic abstract String type();\n\n\tpublic abstract AlertModificationProperties properties();\n\n\t@SerializedNames({ \"id\", \"name\", \"type\", \"properties\" })\n\tpublic static AlertModification create(final String id, final String name, final String type,\n\t\t\tAlertModificationProperties properties) {\n\t\treturn builder().id(id).name(name).type(type).properties(properties).build();\n\t}\n\n\tpublic abstract Builder toBuilder();\n\n\tpublic static Builder builder() {\n\t\treturn new AutoValue_AlertModification.Builder();\n\t}\n\n\t@AutoValue.Builder\n\tpublic abstract static class Builder {\n\t\tpublic abstract Builder id(String id);\n\n\t\tpublic abstract Builder name(String name);\n\n\t\tpublic abstract Builder type(String type);\n\n\t\tpublic abstract Builder properties(AlertModificationProperties properties);\n\n\t\tpublic abstract AlertModification build();\n\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/AlertModificationEvent.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class AlertModificationEvent {\n\n\tpublic abstract String AlertCreated();\n\n\tpublic abstract String MonitorConditionChange();\n\n\tpublic abstract String StateChange();\n\n\t@SerializedNames({ \"AlertCreated\", \"MonitorConditionChange\", \"StateChange\" })\n\tpublic static AlertModificationEvent create(final String AlertCreated, final String MonitorConditionChange,\n\t\t\tfinal String StateChange) {\n\t\treturn builder().AlertCreated(AlertCreated).MonitorConditionChange(MonitorConditionChange)\n\t\t\t\t.StateChange(StateChange).build();\n\t}\n\n\tpublic abstract Builder toBuilder();\n\n\tpublic static Builder builder() {\n\t\treturn new AutoValue_AlertModificationEvent.Builder();\n\t}\n\n\t@AutoValue.Builder\n\tpublic abstract static class Builder {\n\t\tpublic abstract Builder AlertCreated(String AlertCreated);\n\n\t\tpublic abstract Builder MonitorConditionChange(String MonitorConditionChange);\n\n\t\tpublic abstract Builder StateChange(String StateChange);\n\n\t\tpublic abstract AlertModificationEvent build();\n\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/AlertModificationItem.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport java.util.Date;\n\nimport org.jclouds.azurecompute.arm.util.GetEnumValue;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class AlertModificationItem {\n\n\tpublic enum AlertModificationEvent {\n\t\tAlertCreated, MonitorConditionChange, StateChange;\n\n\t\tpublic static AlertModificationEvent fromValue(final String text) {\n\t\t\treturn (AlertModificationEvent) GetEnumValue.fromValueOrDefault(text, AlertModificationEvent.AlertCreated);\n\t\t}\n\t}\n\n\tpublic abstract String comments();\n\n\tpublic abstract String description();\n\n\tpublic abstract AlertModificationEvent modificationEvent();\n\n\tpublic abstract Date modifiedAt();\n\n\tpublic abstract String modifiedBy();\n\n\tpublic abstract String newValue();\n\n\tpublic abstract String oldValue();\n\n\t@SerializedNames({ \"comments\", \"description\", \"modificationEvent\", \"modifiedAt\", \"modifiedBy\", \"newValue\",\n\t\t\t\"oldValue\" })\n\tpublic static AlertModificationItem create(final String comments, final String description,\n\t\t\tfinal AlertModificationEvent modificationEvent, final Date modifiedAt, final String modifiedBy,\n\t\t\tfinal String newValue, final String oldValue) {\n\t\treturn builder().comments(comments).description(description).modificationEvent(modificationEvent)\n\t\t\t\t.modifiedAt(modifiedAt).modifiedBy(modifiedBy).newValue(newValue).oldValue(oldValue).build();\n\t}\n\n\tpublic abstract Builder toBuilder();\n\n\tpublic static Builder builder() {\n\t\treturn new AutoValue_AlertModificationItem.Builder();\n\t}\n\n\t@AutoValue.Builder\n\tpublic abstract static class Builder {\n\n\t\tpublic abstract Builder comments(String comments);\n\n\t\tpublic abstract Builder description(String description);\n\n\t\tpublic abstract Builder modificationEvent(AlertModificationEvent modificationEvent);\n\n\t\tpublic abstract Builder modifiedAt(Date modifiedAt);\n\n\t\tpublic abstract Builder modifiedBy(String modifiedBy);\n\n\t\tpublic abstract Builder newValue(String newValue);\n\n\t\tpublic abstract Builder oldValue(String oldValue);\n\n\t\tpublic abstract AlertModificationItem build();\n\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/AlertModificationProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport java.util.List;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class AlertModificationProperties {\n\n\tpublic abstract String alertId();\n\n\tpublic abstract List<AlertModificationItem> modifications();\n\n\t@SerializedNames({ \"alertId\", \"modifications\" })\n\tpublic static AlertModificationProperties create(final String alertId, List<AlertModificationItem> modifications) {\n\t\treturn builder().alertId(alertId).modifications(modifications).build();\n\t}\n\n\tpublic abstract Builder toBuilder();\n\n\tpublic static Builder builder() {\n\t\treturn new AutoValue_AlertModificationProperties.Builder();\n\t}\n\n\t@AutoValue.Builder\n\tpublic abstract static class Builder {\n\t\tpublic abstract Builder alertId(String alertId);\n\n\t\tpublic abstract Builder modifications(List<AlertModificationItem> modifications);\n\n\t\tpublic abstract AlertModificationProperties build();\n\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/AlertProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport org.jclouds.domain.JsonBall;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class AlertProperties {\n\n\t@Nullable\n\tpublic abstract JsonBall context();\n\n\t@Nullable\n\tpublic abstract JsonBall egressConfig();\n\n\t@Nullable\n\tpublic abstract Essentials essentials();\n\n\t@SerializedNames({ \"context\", \"egressConfig\", \"essentials\" })\n\tpublic static AlertProperties create(final JsonBall context, final JsonBall egressConfig, final Essentials essentials) {\n\t\treturn builder().context(context).egressConfig(egressConfig).essentials(essentials).build();\n\t}\n\n\tpublic abstract Builder toBuilder();\n\n\tpublic static Builder builder() {\n\t\treturn new AutoValue_AlertProperties.Builder();\n\t}\n\n\t@AutoValue.Builder\n\tpublic abstract static class Builder {\n\t\tpublic abstract Builder context(JsonBall context);\n\n\t\tpublic abstract Builder egressConfig(JsonBall egressConfig);\n\n\t\tpublic abstract Builder essentials(Essentials essentials);\n\n\t\tpublic abstract AlertProperties build();\n\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/AlertRuleAllOfCondition.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class AlertRuleAllOfCondition {\n\n\t@Nullable\n\tpublic abstract List<AlertRuleAnyOfOrLeafCondition> allOf();\n\n\t@Nullable\n\tpublic abstract String odatatype();\n\n\t@SerializedNames({ \"allOf\", \"odata.type\" })\n\tpublic static AlertRuleAllOfCondition create(final List<AlertRuleAnyOfOrLeafCondition> allOf,\n\t\t\tfinal String odatatype) {\n\t\treturn builder().allOf(allOf).odatatype(odatatype).build();\n\t}\n\n\tpublic abstract Builder toBuilder();\n\n\tpublic static Builder builder() {\n\t\treturn new AutoValue_AlertRuleAllOfCondition.Builder();\n\t}\n\n\t@AutoValue.Builder\n\tpublic abstract static class Builder {\n\t\tpublic abstract Builder allOf(List<AlertRuleAnyOfOrLeafCondition> allOf);\n\n\t\tpublic abstract Builder odatatype(String odatatype);\n\n\t\tpublic abstract AlertRuleAllOfCondition build();\n\n\t}\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/AlertRuleAnyOfOrLeafCondition.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class AlertRuleAnyOfOrLeafCondition {\n\n\t@Nullable\n\tpublic abstract List<AlertRuleLeafCondition> anyOf();\n\n\t@Nullable\n\tpublic abstract List<String> containsAny();\n\n\t@Nullable\n\tpublic abstract String equals();\n\n\t@Nullable\n\tpublic abstract String field();\n\n\t@SerializedNames({ \"anyOf\", \"containsAny\", \"equals\", \"field\" })\n\tpublic static AlertRuleAnyOfOrLeafCondition create(final List<AlertRuleLeafCondition> anyOf,\n\t\t\tfinal List<String> containsAny, final String equals, final String field) {\n\t\treturn builder().anyOf(anyOf).containsAny(containsAny).equals(equals).field(field).build();\n\t}\n\n\tpublic abstract Builder toBuilder();\n\n\tpublic static Builder builder() {\n\t\treturn new AutoValue_AlertRuleAnyOfOrLeafCondition.Builder();\n\t}\n\n\t@AutoValue.Builder\n\tpublic abstract static class Builder {\n\t\tpublic abstract Builder anyOf(List<AlertRuleLeafCondition> anyOf);\n\n\t\tpublic abstract Builder containsAny(List<String> containsAny);\n\n\t\tpublic abstract Builder equals(String equals);\n\n\t\tpublic abstract Builder field(String field);\n\n\t\tpublic abstract AlertRuleAnyOfOrLeafCondition build();\n\n\t}\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/AlertRuleLeafCondition.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class AlertRuleLeafCondition {\n\n\t@Nullable\n\tpublic abstract List<String> containsAny();\n\n\t@Nullable\n\tpublic abstract String field();\n\n\t@Nullable\n\tpublic abstract String equals();\n\n\t@SerializedNames({ \"containsAny\", \"equals\", \"field\" })\n\tpublic static AlertRuleLeafCondition create(final List<String> containsAny, final String equals,\n\t\t\tfinal String field) {\n\t\treturn builder().containsAny(containsAny).equals(equals).field(field).build();\n\t}\n\n\tpublic abstract Builder toBuilder();\n\n\tpublic static Builder builder() {\n\t\treturn new AutoValue_AlertRuleLeafCondition.Builder();\n\t}\n\n\t@AutoValue.Builder\n\tpublic abstract static class Builder {\n\n\t\tpublic abstract Builder containsAny(List<String> containsAny);\n\n\t\tpublic abstract Builder equals(String equals);\n\n\t\tpublic abstract Builder field(String field);\n\n\t\tpublic abstract AlertRuleLeafCondition build();\n\n\t}\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/AlertSummary.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class AlertSummary {\n\n\tpublic abstract String id();\n\n\tpublic abstract String name();\n\n\tpublic abstract String type();\n\n\tpublic abstract AlertSummaryGroup properties();\n\n\t@SerializedNames({ \"id\", \"name\", \"type\", \"properties\" })\n\tpublic static AlertSummary create(final String id, final String name, final String type,\n\t\t\tfinal AlertSummaryGroup properties) {\n\t\treturn builder().id(id).name(name).type(type).properties(properties).build();\n\t}\n\n\tpublic abstract Builder toBuilder();\n\n\tpublic static Builder builder() {\n\t\treturn new AutoValue_AlertSummary.Builder();\n\t}\n\n\t@AutoValue.Builder\n\tpublic abstract static class Builder {\n\t\tpublic abstract Builder id(String id);\n\n\t\tpublic abstract Builder name(String name);\n\n\t\tpublic abstract Builder type(String type);\n\n\t\tpublic abstract Builder properties(AlertSummaryGroup properties);\n\n\t\tpublic abstract AlertSummary build();\n\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/AlertSummaryGroup.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class AlertSummaryGroup {\n\n\tpublic abstract String groupedby();\n\t\n\t@Nullable\n\tpublic abstract Integer smartGroupsCount();\n\n\tpublic abstract int total();\n\n\t@Nullable\n\tpublic abstract List<AlertSummaryGroupItem> values();\n\n\t@SerializedNames({ \"groupedby\", \"smartGroupsCount\", \"total\", \"values\" })\n\tpublic static AlertSummaryGroup create(final String groupedby, final Integer smartGroupsCount, final int total,\n\t\t\tfinal List<AlertSummaryGroupItem> values) {\n\t\treturn builder().groupedby(groupedby).smartGroupsCount(smartGroupsCount).total(total).values(values).build();\n\t}\n\n\tpublic abstract Builder toBuilder();\n\n\tpublic static Builder builder() {\n\t\treturn new AutoValue_AlertSummaryGroup.Builder();\n\t}\n\n\t@AutoValue.Builder\n\tpublic abstract static class Builder {\n\t\tpublic abstract Builder groupedby(String groupedby);\n\n\t\tpublic abstract Builder smartGroupsCount(Integer smartGroupsCount);\n\n\t\tpublic abstract Builder total(int total);\n\n\t\tpublic abstract Builder values(List<AlertSummaryGroupItem> values);\n\n\t\tpublic abstract AlertSummaryGroup build();\n\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/AlertSummaryGroupItem.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class AlertSummaryGroupItem {\n\n\t@Nullable\n\tpublic abstract String groupedby();\n\n\tpublic abstract String name();\n\n\tpublic abstract int count();\n\n\t@SerializedNames({ \"groupedby\", \"name\", \"count\" })\n\tpublic static AlertSummaryGroupItem create(final String groupedby, final String name, final int count) {\n\t\treturn builder().groupedby(groupedby).name(name).count(count).build();\n\t}\n\n\tpublic abstract Builder toBuilder();\n\n\tpublic static Builder builder() {\n\t\treturn new AutoValue_AlertSummaryGroupItem.Builder();\n\t}\n\n\t@AutoValue.Builder\n\tpublic abstract static class Builder {\n\t\tpublic abstract Builder groupedby(String groupedby);\n\n\t\tpublic abstract Builder name(String name);\n\n\t\tpublic abstract Builder count(int count);\n\n\t\tpublic abstract AlertSummaryGroupItem build();\n\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/Availability.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\nimport org.jclouds.json.SerializedNames;\n\n@AutoValue\npublic abstract class Availability {\n\n   public abstract String nameAvailable();\n\n   @SerializedNames({\"nameAvailable\"})\n   public static Availability create(final String nameAvailable) {\n      return new AutoValue_Availability(nameAvailable);\n   }\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/AvailabilitySet.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.azurecompute.arm.domain;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * AvailabilitySet for subscription\n */\n@AutoValue\npublic abstract class AvailabilitySet {\n\n   @AutoValue\n   public abstract static class AvailabilitySetProperties {\n\n      /**\n       * A platform Update Domain Count\n       */\n      public abstract int platformUpdateDomainCount();\n\n      /**\n       * A platform Fault Domain Count\n       */\n      public abstract int platformFaultDomainCount();\n\n      /**\n       * A list of virtual machines in the availability set\n       */\n      @Nullable\n      public abstract List<IdReference> virtualMachines();\n      \n      /**\n       * A list of statuses in the availability set\n       */\n      @Nullable\n      public abstract List<Status> statuses();\n\n      @SerializedNames({ \"platformUpdateDomainCount\", \"platformFaultDomainCount\", \"virtualMachines\", \"statuses\" })\n      public static AvailabilitySetProperties create(final int platformUpdateDomainCount,\n            final int platformFaultDomainCount, List<IdReference> virtualMachines, List<Status> statuses) {\n         return builder().platformUpdateDomainCount(platformUpdateDomainCount)\n               .platformFaultDomainCount(platformFaultDomainCount).virtualMachines(virtualMachines).statuses(statuses)\n               .build();\n      }\n      \n      public abstract Builder toBuilder();\n      \n      public static Builder builder() {\n         return new AutoValue_AvailabilitySet_AvailabilitySetProperties.Builder();\n      }\n      \n      @AutoValue.Builder\n      public abstract static class Builder {\n         public abstract Builder platformUpdateDomainCount(int platformUpdateDomainCount);\n         public abstract Builder platformFaultDomainCount(int platformFaultDomainCount);\n         public abstract Builder virtualMachines(List<IdReference> virtualMachines);\n         public abstract Builder statuses(List<Status> statuses);\n         \n         abstract List<IdReference> virtualMachines();\n         abstract List<Status> statuses();\n         abstract AvailabilitySetProperties autoBuild();\n         \n         public AvailabilitySetProperties build() {\n            virtualMachines(virtualMachines() != null ? ImmutableList.copyOf(virtualMachines()) : null);\n            statuses(statuses() != null ? ImmutableList.copyOf(statuses()) : null);\n            return autoBuild();\n         }\n      }\n   }\n   \n   public static enum AvailabilitySetType {\n      MANAGED(\"Aligned\"),\n      CLASSIC(\"Classic\");\n      \n      private final String value;\n\n      AvailabilitySetType(String value) {\n         this.value = value;\n      }\n\n      public static AvailabilitySetType fromString(String value) {\n         AvailabilitySetType[] items = AvailabilitySetType.values();\n         for (AvailabilitySetType item : items) {\n            if (item.toString().equalsIgnoreCase(value)) {\n               return item;\n            }\n         }\n         throw new IllegalArgumentException(\"Unexpected type: \" + value);\n      }\n\n      @Override\n      public String toString() {\n         return this.value;\n      }\n   }\n   \n   @AutoValue\n   public abstract static class SKU {\n      \n      public abstract AvailabilitySetType type();\n      \n      @SerializedNames({ \"name\" })\n      public static SKU create(final String type) {\n         return create(AvailabilitySetType.fromString(type));\n      }\n      \n      public static SKU create(AvailabilitySetType type) {\n         return new AutoValue_AvailabilitySet_SKU(type);\n      }\n   }\n\n   /**\n    * The id of the availability set\n    */\n   @Nullable\n   public abstract String id();\n\n   /**\n    * The name of the availability set.\n    */\n   @Nullable\n   public abstract String name();\n\n   /**\n    * The type of the availability set.\n    */\n   @Nullable\n   public abstract String type();\n\n   /**\n    * The location of the availability set\n    */\n   @Nullable\n   public abstract String location();\n\n   /**\n    * Specifies the type of the availability set\n    */\n   @Nullable\n   public abstract SKU sku();\n   \n   /**\n    * Specifies the tags of the availability set\n    */\n   @Nullable\n   public abstract Map<String, String> tags();\n   \n   /**\n    * Specifies the properties of the availability set\n    */\n   @Nullable\n   public abstract AvailabilitySetProperties properties();\n\n   @SerializedNames({ \"id\", \"name\", \"type\", \"location\", \"sku\", \"tags\", \"properties\" })\n   public static AvailabilitySet create(final String id, final String name, final String type, final String location,\n         SKU sku, final Map<String, String> tags, AvailabilitySetProperties properties) {\n      return builder().id(id).name(name).type(type).location(location).sku(sku).tags(tags).properties(properties)\n            .build();\n   }\n   \n   public abstract Builder toBuilder();\n   \n   private static Builder builder() {\n      return new AutoValue_AvailabilitySet.Builder();\n   }\n   \n   public static Builder managed() {\n      return builder().managed();\n   }\n   \n   public static Builder classic() {\n      return builder().classic();\n   }\n   \n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder id(String id);\n      public abstract Builder name(String name);\n      public abstract Builder type(String type);\n      public abstract Builder location(String location);\n      public abstract Builder tags(Map<String, String> tags);\n      public abstract Builder properties(AvailabilitySetProperties properties);\n      \n      abstract Builder sku(SKU sku);\n      public Builder managed() {\n         return sku(SKU.create(AvailabilitySetType.MANAGED));\n      }\n      public Builder classic() {\n         return sku(SKU.create(AvailabilitySetType.CLASSIC));\n      }\n      \n      abstract Map<String, String> tags();\n      abstract AvailabilitySet autoBuild();\n      \n      public AvailabilitySet build() {\n         tags(tags() != null ? ImmutableMap.copyOf(tags()) : null);\n         return autoBuild();\n      }\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/BackendAddressPool.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class BackendAddressPool {\n   public abstract String name();\n\n   @Nullable\n   public abstract String id();\n\n   @Nullable\n   public abstract BackendAddressPoolProperties properties();\n\n   @Nullable\n   public abstract String etag();\n\n   @SerializedNames({ \"name\", \"id\", \"properties\", \"etag\" })\n   public static BackendAddressPool create(final String name, final String id,\n         final BackendAddressPoolProperties properties, final String etag) {\n      return new AutoValue_BackendAddressPool(name, id, properties, etag);\n   }\n}\n\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/BackendAddressPoolProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\n\n@AutoValue\npublic abstract class BackendAddressPoolProperties implements Provisionable {\n\n   @Nullable\n   public abstract String provisioningState();\n\n   @Nullable\n   public abstract List<IdReference> backendIPConfigurations();\n\n   @Nullable\n   public abstract List<IdReference> loadBalancingRules();\n\n\n   @SerializedNames({ \"provisioningState\", \"backendIPConfigurations\", \"loadBalancingRules\"})\n   public static BackendAddressPoolProperties create(final String provisioningState,\n         final List<IdReference> backendIPConfigurations, final List<IdReference> loadBalancingRules) {\n      return builder().provisioningState(provisioningState).backendIPConfigurations(backendIPConfigurations).loadBalancingRules(loadBalancingRules).build();\n   }\n   \n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_BackendAddressPoolProperties.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n\n      public abstract Builder provisioningState(String provisioningState);\n\n      public abstract Builder backendIPConfigurations(List<IdReference> backendIPConfigurations);\n\n      public abstract Builder loadBalancingRules(List<IdReference> loadBalancingRules);\n\n      abstract List<IdReference> backendIPConfigurations();\n      abstract List<IdReference> loadBalancingRules();\n      \n      abstract BackendAddressPoolProperties autoBuild();\n      \n      public BackendAddressPoolProperties build() {\n         backendIPConfigurations(backendIPConfigurations() != null ? ImmutableList.copyOf(backendIPConfigurations())\n               : null);\n         loadBalancingRules(loadBalancingRules() != null ? ImmutableList.copyOf(loadBalancingRules()) : null);\n         return autoBuild();\n      }\n   }\n}\n\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/Certificate.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport java.util.Map;\nimport java.util.List;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n\n@AutoValue\npublic abstract class Certificate {\n   @AutoValue\n   public abstract static class CertificateAttributes {\n      @Nullable\n      public abstract Integer created();\n\n      public abstract boolean enabled();\n\n      @Nullable\n      public abstract Integer expiry();\n\n      @Nullable\n      public abstract Integer notBefore();\n\n      @Nullable\n      public abstract String recoveryLevel();\n\n      @Nullable\n      public abstract Integer updated();\n\n      @SerializedNames({\"created\", \"enabled\", \"exp\", \"nbf\", \"recoveryLevel\", \"updated\"})\n      public static CertificateAttributes create(final Integer created,\n                                                 final boolean enabled,\n                                                 final Integer expiry,\n                                                 final Integer notBefore,\n                                                 final String recoveryLevel,\n                                                 final Integer updated) {\n         return new AutoValue_Certificate_CertificateAttributes(created, enabled, expiry, notBefore, recoveryLevel, updated);\n      }\n   }\n\n   @AutoValue\n   public abstract static class IssuerParameters {\n      @Nullable\n      public abstract String certType();\n\n      @Nullable\n      public abstract String name();\n\n      @SerializedNames({\"cty\", \"name\"})\n      public static IssuerParameters create(final String certType,\n                                            final String name) {\n         return new AutoValue_Certificate_IssuerParameters(certType, name);\n      }\n   }\n\n   @AutoValue\n   public abstract static class KeyProperties {\n      @Nullable\n      public abstract Boolean exportable();\n\n      @Nullable\n      public abstract Integer keySize();\n\n      @Nullable\n      public abstract String keyType();\n\n      @Nullable\n      public abstract Boolean reuseKey();\n\n      @SerializedNames({\"exportable\", \"key_size\", \"kty\", \"reuse_key\"})\n      public static KeyProperties create(final boolean exportable,\n                                         final Integer keySize,\n                                         final String keyType,\n                                         final boolean reuseKey) {\n         return new AutoValue_Certificate_KeyProperties(exportable, keySize, keyType, reuseKey);\n      }\n   }\n\n   @AutoValue\n   public abstract static class LifetimeActionTrigger {\n      @Nullable\n      public abstract Integer daysBeforeExpiry();\n\n      @Nullable\n      public abstract Integer lifetimePercentage();\n\n      @SerializedNames({\"days_before_expiry\", \"lifetime_percentage\"})\n      public static LifetimeActionTrigger create(final Integer daysBeforeExpiry,\n                                                 final Integer lifetimePercentage) {\n         return new AutoValue_Certificate_LifetimeActionTrigger(daysBeforeExpiry, lifetimePercentage);\n      }\n   }\n\n   @AutoValue\n   public abstract static class LifetimeActionAction {\n      public abstract String actionType();\n\n      @SerializedNames({\"action_type\"})\n      public static LifetimeActionAction create(final String actionType) {\n         return new AutoValue_Certificate_LifetimeActionAction(actionType);\n      }\n   }\n\n   @AutoValue\n   public abstract static class LifetimeAction {\n      public abstract LifetimeActionAction action();\n\n      public abstract LifetimeActionTrigger trigger();\n\n      @SerializedNames({\"action\", \"trigger\"})\n      public static LifetimeAction create(final LifetimeActionAction action,\n                                          final LifetimeActionTrigger trigger) {\n         return new AutoValue_Certificate_LifetimeAction(action, trigger);\n      }\n   }\n\n   @AutoValue\n   public abstract static class SecretProperties {\n      public abstract String contentType();\n\n      @SerializedNames({\"contentType\"})\n      public static SecretProperties create(final String contentType) {\n         return new AutoValue_Certificate_SecretProperties(contentType);\n      }\n   }\n\n   @AutoValue\n   public abstract static class SubjectAlternativeNames {\n      public abstract List<String> dnsNames();\n\n      public abstract List<String> emails();\n\n      public abstract List<String> upns();\n\n      @SerializedNames({\"dns_names\", \"emails\", \"upns\"})\n      public static SubjectAlternativeNames create(final List<String> dnsNames,\n                                                   final List<String> emails,\n                                                   final List<String> upns) {\n         return new AutoValue_Certificate_SubjectAlternativeNames(\n                 dnsNames != null ? ImmutableList.copyOf(dnsNames) : ImmutableList.<String> of(),\n                 emails != null ? ImmutableList.copyOf(emails) : ImmutableList.<String> of(),\n                 upns != null ? ImmutableList.copyOf(upns) : ImmutableList.<String> of()\n         );\n      }\n   }\n\n   @AutoValue\n   public abstract static class X509CertificateProperties {\n      public abstract List<String> enhancedKeyUsage();\n\n      public abstract List<String> keyUsage();\n\n      @Nullable\n      public abstract SubjectAlternativeNames subjectAltNames();\n\n      @Nullable\n      public abstract String subject();\n\n      @Nullable\n      public abstract Integer validityMonths();\n\n      @SerializedNames({\"ekus\", \"key_usage\", \"sans\", \"subject\", \"validity_months\"})\n      public static X509CertificateProperties create(final List<String> enhancedKeyUsage,\n                                                     final List<String> keyUsage,\n                                                     final SubjectAlternativeNames subjectAltNames,\n                                                     final String subject,\n                                                     final Integer validityMonths) {\n         return new AutoValue_Certificate_X509CertificateProperties(\n                 enhancedKeyUsage != null ? ImmutableList.copyOf(enhancedKeyUsage) : ImmutableList.<String> of(),\n                 keyUsage != null ? ImmutableList.copyOf(keyUsage) : ImmutableList.<String> of(),\n                 subjectAltNames,\n                 subject,\n                 validityMonths\n         );\n      }\n   }\n\n   @AutoValue\n   public abstract static class CertificatePolicy {\n      @Nullable\n      public abstract CertificateAttributes attributes();\n\n      @Nullable\n      public abstract String id();\n\n      @Nullable\n      public abstract IssuerParameters issuer();\n\n      @Nullable\n      public abstract KeyProperties keyProps();\n\n      public abstract List<LifetimeAction> lifetimeActions();\n\n      @Nullable\n      public abstract SecretProperties secretProps();\n\n      @Nullable\n      public abstract X509CertificateProperties x509props();\n\n      @SerializedNames({\"attributes\", \"id\", \"issuer\", \"key_props\", \"lifetime_actions\", \"secret_props\", \"x509_props\"})\n      public static CertificatePolicy create(final CertificateAttributes attributes,\n                                             final String id,\n                                             final IssuerParameters issuer,\n                                             final KeyProperties keyProps,\n                                             final List<LifetimeAction> lifetimeActions,\n                                             final SecretProperties secretProperties,\n                                             final X509CertificateProperties x509Props) {\n         return new AutoValue_Certificate_CertificatePolicy(\n                 attributes,\n                 id,\n                 issuer,\n                 keyProps,\n                 lifetimeActions != null ? ImmutableList.copyOf(lifetimeActions) : ImmutableList.<LifetimeAction>of(),\n                 secretProperties,\n                 x509Props\n         );\n      }\n   }\n\n   @AutoValue\n   public abstract static class CertificateError {\n      @Nullable\n      public abstract String code();\n\n      @Nullable\n      public abstract String message();\n\n      @SerializedNames({\"code\", \"message\"})\n      public static CertificateError create(final String code,\n                                            final String message) {\n         return new AutoValue_Certificate_CertificateError(code, message);\n      }\n   }\n\n   @AutoValue\n   public abstract static class CertificateOperation {\n      @Nullable\n      public abstract Boolean cancellationRequested();\n\n      @Nullable\n      public abstract String csr();\n\n      @Nullable\n      public abstract CertificateError error();\n\n      @Nullable\n      public abstract String id();\n\n      @Nullable\n      public abstract IssuerParameters issuer();\n\n      @Nullable\n      public abstract String requestId();\n\n      @Nullable\n      public abstract String status();\n\n      @Nullable\n      public abstract String statusDetails();\n\n      @Nullable\n      public abstract String target();\n\n      @SerializedNames({\"cancellation_requested\", \"csr\", \"error\", \"id\", \"issuer\", \"request_id\", \"status\", \"status_details\", \"target\"})\n      public static CertificateOperation create(final boolean cancellationRequested,\n                                                final String csr,\n                                                final CertificateError error,\n                                                final String id,\n                                                final IssuerParameters issuer,\n                                                final String requestId,\n                                                final String status,\n                                                final String statusDetails,\n                                                final String target) {\n         return new AutoValue_Certificate_CertificateOperation(\n                 cancellationRequested,\n                 csr,\n                 error,\n                 id,\n                 issuer,\n                 requestId,\n                 status,\n                 statusDetails,\n                 target);\n      }\n   }\n\n   @AutoValue\n   public abstract static class CertificateBundle {\n      @Nullable\n      public abstract CertificateAttributes attributes();\n\n      @Nullable\n      public abstract String certificate();\n\n      @Nullable\n      public abstract String contentType();\n\n      @Nullable\n      public abstract String id();\n\n      @Nullable\n      public abstract String keyId();\n\n      @Nullable\n      public abstract CertificatePolicy policy();\n\n      @Nullable\n      public abstract String secretId();\n\n      @Nullable\n      public abstract Map<String, String> tags();\n\n      @Nullable\n      public abstract String thumbprint();\n\n      @SerializedNames({\"attributes\", \"cer\", \"contentType\", \"id\", \"kid\", \"policy\", \"sid\", \"tags\", \"x5t\"})\n      public static CertificateBundle create(final CertificateAttributes attributes,\n                                             final String certificate,\n                                             final String contentType,\n                                             final String id,\n                                             final String keyId,\n                                             final CertificatePolicy policy,\n                                             final String secretId,\n                                             final Map<String, String> tags,\n                                             final String thumbprint) {\n         return new AutoValue_Certificate_CertificateBundle(attributes,\n                 certificate,\n                 contentType,\n                 id,\n                 keyId,\n                 policy,\n                 secretId,\n                 tags != null ? ImmutableMap.copyOf(tags) : null,\n                 thumbprint\n         );\n      }\n   }\n\n   @AutoValue\n   public abstract static class CertificateIssuer {\n      public abstract String id();\n\n      public abstract String provider();\n\n      @SerializedNames({\"id\", \"provider\"})\n      public static CertificateIssuer create(final String id,\n                                             final String provider) {\n         return new AutoValue_Certificate_CertificateIssuer(id, provider);\n      }\n   }\n\n   @AutoValue\n   public abstract static class IssuerAttributes {\n      @Nullable\n      public abstract Integer created();\n\n      @Nullable\n      public abstract Boolean enabled();\n\n      @Nullable\n      public abstract Integer updated();\n\n      @SerializedNames({\"created\", \"enabled\", \"updated\"})\n      public static IssuerAttributes create(final Integer created,\n                                            final Boolean enabled,\n                                            final Integer updated) {\n         return new AutoValue_Certificate_IssuerAttributes(created, enabled, updated);\n      }\n   }\n\n   @AutoValue\n   public abstract static class IssuerCredentials {\n      @Nullable\n      public abstract String accountId();\n\n      @Nullable\n      public abstract String password();\n\n      @SerializedNames({\"account_id\", \"pwd\"})\n      public static IssuerCredentials create(final String accountId,\n                                             final String password) {\n         return new AutoValue_Certificate_IssuerCredentials(accountId, password);\n      }\n   }\n\n   @AutoValue\n   public abstract static class OrganizationDetails {\n      public abstract List<AdministrationDetails> adminDetails();\n\n      @Nullable\n      public abstract String id();\n\n      @SerializedNames({\"admin_details\", \"id\"})\n      public static OrganizationDetails create(final List<AdministrationDetails> adminDetails,\n                                               final String id) {\n         return new AutoValue_Certificate_OrganizationDetails(\n                 adminDetails != null ? ImmutableList.copyOf(adminDetails) : ImmutableList.<AdministrationDetails> of(),\n                 id\n         );\n      }\n   }\n\n   @AutoValue\n   public abstract static class AdministrationDetails {\n      @Nullable\n      public abstract String email();\n\n      @Nullable\n      public abstract String firstName();\n\n      @Nullable\n      public abstract String lastName();\n\n      @Nullable\n      public abstract String phoneNumber();\n\n      @SerializedNames({\"email\", \"first_name\", \"last_name\", \"phone\"})\n      public static AdministrationDetails create(final String email,\n                                                 final String firstName,\n                                                 final String lastName,\n                                                 final String phoneNumber) {\n         return new AutoValue_Certificate_AdministrationDetails(email, firstName, lastName, phoneNumber);\n      }\n   }\n\n   @AutoValue\n   public abstract static class IssuerBundle {\n      @Nullable\n      public abstract IssuerAttributes attributes();\n\n      @Nullable\n      public abstract IssuerCredentials credentials();\n\n      @Nullable\n      public abstract String id();\n\n      @Nullable\n      public abstract OrganizationDetails organizationDetails();\n\n      @Nullable\n      public abstract String provider();\n\n      @SerializedNames({\"attributes\", \"credentials\", \"id\", \"org_details\", \"provider\"})\n      public static IssuerBundle create(final IssuerAttributes attributes,\n                                        final IssuerCredentials credentials,\n                                        final String id,\n                                        final OrganizationDetails orgDetails,\n                                        final String provider) {\n         return new AutoValue_Certificate_IssuerBundle(attributes, credentials, id, orgDetails, provider);\n      }\n   }\n\n   @AutoValue\n   public abstract static class Contact {\n      @Nullable\n      public abstract String email();\n\n      @Nullable\n      public abstract String name();\n\n      @Nullable\n      public abstract String phone();\n\n      @SerializedNames({\"email\", \"name\", \"phone\"})\n      public static Contact create(final String email,\n                                   final String name,\n                                   final String phone) {\n         return new AutoValue_Certificate_Contact(email, name, phone);\n      }\n   }\n\n   @AutoValue\n   public abstract static class Contacts {\n      public abstract List<Contact> contacts();\n\n      @Nullable\n      public abstract String id();\n\n      @SerializedNames({\"contacts\", \"id\"})\n      public static Contacts create(final List<Contact> contacts,\n                                    final String id) {\n         return new AutoValue_Certificate_Contacts(\n                 contacts != null ? ImmutableList.copyOf(contacts) : ImmutableList.<Contact> of(),\n                 id\n         );\n      }\n   }\n\n   @AutoValue\n   public abstract static class DeletedCertificateBundle {\n      @Nullable\n      public abstract CertificateAttributes attributes();\n\n      @Nullable\n      public abstract String bytes();\n\n      @Nullable\n      public abstract Integer deletedDate();\n\n      @Nullable\n      public abstract String id();\n\n      @Nullable\n      public abstract String keyId();\n\n      @Nullable\n      public abstract String recoveryId();\n\n      @Nullable\n      public abstract Integer scheduledPurgeDate();\n\n      @Nullable\n      public abstract String secredId();\n\n      @Nullable\n      public abstract Map<String, String> tags();\n\n      @Nullable\n      public abstract String thumbprint();\n\n      @SerializedNames({\"attributes\", \"cer\", \"deletedDate\", \"id\", \"kid\", \"recoveryId\", \"scheduledPurgeDate\", \"sid\", \"tags\", \"x5t\"})\n      public static DeletedCertificateBundle create(final CertificateAttributes attributes,\n                                                    final String bytes,\n                                                    final Integer deletedDate,\n                                                    final String id,\n                                                    final String keyId,\n                                                    final String recoveryId,\n                                                    final Integer scheduledPurgeDate,\n                                                    final String secretId,\n                                                    final Map<String, String> tags,\n                                                    final String thumbprint) {\n         return new AutoValue_Certificate_DeletedCertificateBundle(\n                 attributes,\n                 bytes,\n                 deletedDate,\n                 id,\n                 keyId,\n                 recoveryId,\n                 scheduledPurgeDate,\n                 secretId,\n                 tags != null ? ImmutableMap.copyOf(tags) : null,\n                 thumbprint\n         );\n      }\n   }\n\n   @AutoValue\n   public abstract static class DeletedCertificate {\n      @Nullable\n      public abstract CertificateAttributes attributes();\n\n      @Nullable\n      public abstract Integer deletedDate();\n\n      @Nullable\n      public abstract String id();\n\n      @Nullable\n      public abstract String recoveryId();\n\n      @Nullable\n      public abstract Integer scheduledPurgeDate();\n\n      @Nullable\n      public abstract Map<String, String> tags();\n\n      @Nullable\n      public abstract String thumbprint();\n\n      @SerializedNames({\"attributes\", \"deletedDate\", \"id\", \"recoveryId\", \"scheduledPurgeDate\", \"tags\", \"x5t\"})\n      public static DeletedCertificate create(final CertificateAttributes attributes,\n                                              final Integer deletedDate,\n                                              final String id,\n                                              final String recoveryId,\n                                              final Integer scheduledPurgeDate,\n                                              final Map<String, String> tags,\n                                              final String thumbprint) {\n         return new AutoValue_Certificate_DeletedCertificate(\n                 attributes,\n                 deletedDate,\n                 id,\n                 recoveryId,\n                 scheduledPurgeDate,\n                 tags != null ? ImmutableMap.copyOf(tags) : null,\n                 thumbprint\n         );\n      }\n   }\n\n   @Nullable\n   public abstract CertificateAttributes attributes();\n\n   @Nullable\n   public abstract String id();\n\n   @Nullable\n   public abstract Map<String, String> tags();\n\n   @Nullable\n   public abstract String thumbprint();\n\n   @SerializedNames({\"attributes\", \"id\", \"tags\", \"x5t\"})\n   public static Certificate create(final CertificateAttributes attributes,\n                                    final String id,\n                                    final Map<String, String> tags,\n                                    final String thumbprint) {\n      return new AutoValue_Certificate(\n              attributes,\n              id,\n              tags != null ? ImmutableMap.copyOf(tags) : null,\n              thumbprint\n      );\n   }\n\n   Certificate() {\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/ComputeNode.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport org.jclouds.azurecompute.arm.util.GetEnumValue;\n\npublic class ComputeNode {\n   public enum Status {\n      GOOD,\n      BAD,\n      UNRECOGNIZED;\n\n      public static Status fromValue(final String text) {\n         return (Status) GetEnumValue.fromValueOrDefault(text, Status.UNRECOGNIZED);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/CreationData.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport org.jclouds.azurecompute.arm.util.GetEnumValue;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.base.CaseFormat;\n\n@AutoValue\npublic abstract class CreationData {\n\n\n   public enum CreateOptions {\n      EMPTY,\n      FROM_IMAGE,\n      COPY,\n      IMPORT,\n      UNRECOGNIZED;\n\n      public static CreateOptions fromValue(final String text) {\n         return (CreateOptions) GetEnumValue.fromValueOrDefault(text, UNRECOGNIZED);\n      }\n\n      @Override\n      public String toString() {\n         return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name());\n      }\n   }\n   \n   @Nullable\n   public abstract CreateOptions createOption();\n\n   @SerializedNames({ \"createOption\" })\n   public static CreationData create(CreateOptions createOption) {\n      return new AutoValue_CreationData(createOption);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/Criteria.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class Criteria {\n\n\t@Nullable\n\tpublic abstract List<MetricAlertCriteria> allOf();\n\n\t@Nullable\n\tpublic abstract String odatatype();\n\n\t@SerializedNames({ \"allOf\", \"odata.type\" })\n\tpublic static Criteria create(final List<MetricAlertCriteria> allOf,\n\t\t\tfinal String odatatype) {\n\t\treturn builder().allOf(allOf).odatatype(odatatype).build();\n\t}\n\n\tpublic abstract Builder toBuilder();\n\n\tpublic static Builder builder() {\n\t\treturn new AutoValue_Criteria.Builder();\n\t}\n\n\t@AutoValue.Builder\n\tpublic abstract static class Builder {\n\n\t\tpublic abstract Builder allOf(List<MetricAlertCriteria> allOf);\n\n\t\tpublic abstract Builder odatatype(String odatatype);\n\n\t\tpublic abstract Criteria build();\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/DataDisk.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport org.jclouds.azurecompute.arm.util.GetEnumValue;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.base.CaseFormat;\n\n@AutoValue\npublic abstract class DataDisk implements Provisionable {\n\n   public enum DiskCreateOptionTypes {\n      FROM_IMAGE,\n      EMPTY,\n      ATTACH,\n      UNRECOGNIZED;\n\n      public static DiskCreateOptionTypes fromValue(final String text) {\n         return (DiskCreateOptionTypes) GetEnumValue.fromValueOrDefault(text, UNRECOGNIZED);\n      }\n\n      @Override\n      public String toString() {\n         return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name());\n      }\n   }\n   \n   public enum CachingTypes {\n      NONE,\n      READ_ONLY,\n      READ_WRITE,\n      UNRECOGNIZED;\n\n      public static CachingTypes fromValue(final String text) {\n         for (CachingTypes type : CachingTypes.values()) {\n            if (type.toString().equals(text)) {\n               return type;\n            }\n         }\n         return UNRECOGNIZED;\n      }\n\n      @Override\n      public String toString() {\n         return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name());\n      }\n   }\n\n   /**\n    * The name of the data disk\n    */\n   @Nullable public abstract String name();\n\n   /**\n    * The size of the data disk\n    */\n   @Nullable public abstract String diskSizeGB();\n\n   /**\n    * The lun value of the data disk\n    */\n   @Nullable public abstract Integer lun();\n\n   /**\n    * The vhd of the data disk\n    */\n   @Nullable public abstract VHD vhd();\n\n   /**\n    * The source user image virtual hard disk. This virtual hard disk will be\n    * copied before using it to attach to the virtual machine. If SourceImage\n    * is provided, the destination virtual hard disk must not exist.\n    */\n   @Nullable public abstract VHD image();\n\n   /**\n    * The create option of the data disk\n    */\n   public abstract DiskCreateOptionTypes createOption();\n   \n   /**\n    * The caching type. Possible values include: 'None', 'ReadOnly',\n    * 'ReadWrite'.\n    */\n   @Nullable public abstract CachingTypes caching();\n\n   /**\n    * The managed disk parameters.\n    */\n   @Nullable public abstract ManagedDiskParameters managedDiskParameters();\n\n   @Nullable\n   public abstract String provisioningState();\n\n   @SerializedNames({\"name\", \"diskSizeGB\", \"lun\", \"vhd\", \"image\", \"createOption\", \"caching\", \"managedDisk\", \"provisioningState\"})\n   public static DataDisk create(final String name, final String diskSizeGB, final Integer lun,\n                                 final VHD vhd, final VHD image, final String createOption, final String caching, \n                                 final ManagedDiskParameters managedDiskParamenters, final String provisioningState) {\n      final Builder builder = builder();\n      if (caching != null) {\n         builder.caching(CachingTypes.fromValue(caching));\n      }\n      return builder.name(name)\n              .diskSizeGB(diskSizeGB)\n              .lun(lun)\n              .vhd(vhd)\n              .image(image)\n              .createOption(DiskCreateOptionTypes.fromValue(createOption))\n              .managedDiskParameters(managedDiskParamenters)\n              .provisioningState(provisioningState)\n              .build();\n   }\n   \n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_DataDisk.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      \n      public abstract Builder name(String name);\n\n      public abstract Builder diskSizeGB(String diskSizeGB);\n\n      public abstract Builder createOption(DiskCreateOptionTypes createOption);\n\n      public abstract Builder lun(Integer lun);\n\n      public abstract Builder vhd(VHD vhd);\n\n      public abstract Builder image(VHD image);\n\n      public abstract Builder caching(CachingTypes caching);\n\n      public abstract Builder managedDiskParameters(ManagedDiskParameters managedDiskParameters);\n      \n      public abstract Builder provisioningState(String provisioningState);\n\n      public abstract DataDisk build();\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/Deployment.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.azurecompute.arm.util.GetEnumValue;\nimport org.jclouds.domain.JsonBall;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableMap;\n\nimport static com.google.common.collect.ImmutableList.copyOf;\n\n@AutoValue\npublic abstract class Deployment {\n\n   public enum ProvisioningState {\n      ACCEPTED,\n      READY,\n      CANCELED,\n      FAILED,\n      DELETED,\n      SUCCEEDED,\n      RUNNING,\n      UNRECOGNIZED;\n\n      public static ProvisioningState fromValue(final String text) {\n         return (ProvisioningState) GetEnumValue.fromValueOrDefault(text, ProvisioningState.UNRECOGNIZED);\n      }\n   }\n\n   public enum DeploymentMode {\n      INCREMENTAL,\n      COMPLETE,\n      UNRECOGNIZED;\n\n      public static DeploymentMode fromValue(final String text) {\n         return (DeploymentMode) GetEnumValue.fromValueOrDefault(text, DeploymentMode.UNRECOGNIZED);\n      }\n   }\n\n   @AutoValue\n   public abstract static class TypeValue {\n      public abstract String type();\n\n      public abstract String value();\n\n      @SerializedNames({\"type\", \"value\"})\n      public static TypeValue create(final String type, final String value) {\n         return new AutoValue_Deployment_TypeValue(type, value);\n      }\n   }\n\n   @AutoValue\n   public abstract static class ProviderResourceType {\n      @Nullable\n      public abstract String resourceType();\n\n      @Nullable\n      public abstract List<String> locations();\n\n      @Nullable\n      public abstract List<String> apiVersions();\n\n      @Nullable\n      public abstract Map<String, JsonBall> properties();\n\n      @SerializedNames({\"resourceType\", \"locations\", \"apiVersions\", \"properties\"})\n      public static ProviderResourceType create(final String resourceType,\n                                                final List<String> locations,\n                                                final List<String> apiVersions,\n                                                @Nullable final Map<String, JsonBall> properties) {\n         return new AutoValue_Deployment_ProviderResourceType(resourceType,\n                 locations == null ? null : copyOf(locations),\n                 apiVersions == null ? null : copyOf(apiVersions),\n                 properties == null ? ImmutableMap.<String, JsonBall>builder().build() : ImmutableMap.copyOf(properties));\n      }\n   }\n\n   @AutoValue\n   public abstract static class Provider {\n      @Nullable\n      public abstract String id();\n\n      @Nullable\n      public abstract String namespace();\n\n      @Nullable\n      public abstract String registrationState();\n\n      @Nullable\n      public abstract List<ProviderResourceType> resourceTypes();\n\n      @SerializedNames({\"id\", \"namespace\", \"registrationState\", \"resourceTypes\"})\n      public static Provider create(final String id,\n                                    final String namespace,\n                                    final String registrationState,\n                                    final List<ProviderResourceType> resourceTypes) {\n         return new AutoValue_Deployment_Provider(id, namespace, registrationState, resourceTypes == null ? null : copyOf(resourceTypes));\n      }\n   }\n\n   @AutoValue\n   public abstract static class Dependency {\n      @Nullable\n      public abstract List<Dependency> dependencies();\n\n      @Nullable\n      public abstract List<Dependency> dependsOn();\n\n      @Nullable\n      public abstract String id();\n\n      @Nullable\n      public abstract String resourceType();\n\n      @Nullable\n      public abstract String resourceName();\n\n      @SerializedNames({\"dependencies\", \"dependsOn\", \"id\", \"resourceType\", \"resourceName\"})\n      public static Dependency create(final List<Dependency> dependencies,\n                                      final List<Dependency> dependsOn,\n                                      final String id,\n                                      final String resourceType,\n                                      final String resourceName) {\n         return new AutoValue_Deployment_Dependency(dependencies == null ? null : copyOf(dependencies),\n               dependsOn == null ? null : copyOf(dependsOn), id, resourceType, resourceName);\n      }\n   }\n\n   @AutoValue\n   public abstract static class ContentLink {\n      public abstract String uri();\n\n      @Nullable\n      public abstract String contentVersion();\n\n      @SerializedNames({\"uri\", \"contentVersion\"})\n      public static ContentLink create(final String uri, final String contentVersion) {\n         return new AutoValue_Deployment_ContentLink(uri, contentVersion);\n      }\n   }\n\n   @AutoValue\n   public abstract static class DeploymentProperties implements Provisionable {\n      @Nullable\n      public abstract String provisioningState();\n\n      @Nullable\n      public abstract String correlationId();\n\n      @Nullable\n      public abstract String timestamp();\n\n      @Nullable\n      public abstract Map<String, JsonBall> outputs();\n\n      @Nullable\n      public abstract List<Provider> providers();\n\n      @Nullable\n      public abstract List<Dependency> dependencies();\n\n      @Nullable\n      public abstract Map<String, JsonBall> template();\n\n      @Nullable\n      public abstract ContentLink templateLink();\n\n      @Nullable\n      public abstract Map<String, JsonBall> parameters();\n\n      @Nullable\n      public abstract ContentLink parametersLink();\n\n      public abstract String mode();\n\n      // The entries below seem to be dynamic/not documented in the specification\n      @Nullable\n      public abstract String duration();\n\n      @Nullable\n      public abstract List<Map<String, String>> outputResources();\n\n      @SerializedNames({\"provisioningState\", \"correlationId\", \"timestamp\", \"outputs\", \"providers\", \"dependencies\", \"template\", \"templateLink\", \"parameters\", \"parametersLink\", \"mode\", \"duration\", \"outputResources\"})\n      public static DeploymentProperties create(final String provisioningState,\n                                                final String correlationId,\n                                                final String timestamp,\n                                                @Nullable final Map<String, JsonBall> outputs,\n                                                final List<Provider> providers,\n                                                final List<Dependency> dependencies,\n                                                final Map<String, JsonBall> template,\n                                                final ContentLink templateLink,\n                                                final Map<String, JsonBall> parameters,\n                                                final ContentLink parametersLink,\n                                                final String mode,\n                                                final String duration,\n                                                final List<Map<String, String>> outputResources) {\n         return new AutoValue_Deployment_DeploymentProperties(provisioningState,\n                                                              correlationId,\n                                                              timestamp,\n                                                              outputs == null ? ImmutableMap.<String, JsonBall>builder().build() : ImmutableMap.copyOf(outputs),\n                                                              providers == null ? null : copyOf(providers),\n                                                              dependencies == null ? null : copyOf(dependencies),\n                                                              template == null ? ImmutableMap.<String, JsonBall>builder().build() : ImmutableMap.copyOf(template),\n                                                              templateLink,\n                                                              parameters == null ? ImmutableMap.<String, JsonBall>builder().build() : ImmutableMap.copyOf(parameters),\n                                                              parametersLink,\n                                                              mode,\n                                                              duration,\n                                                              outputResources == null ? null : copyOf(outputResources));\n      }\n   }\n\n   /**\n    * The ID associated with the template deployment.\n    */\n   @Nullable\n   public abstract String id();\n\n   /**\n    * The name associated with the template deployment.\n    */\n   public abstract String name();\n\n   /**\n    * Properties of the deployment.\n    */\n   @Nullable\n   public abstract DeploymentProperties properties();\n\n   @SerializedNames({\"id\", \"name\", \"properties\"})\n   public static Deployment create(final String id, final String name, final DeploymentProperties properties) {\n      return new AutoValue_Deployment(id, name, properties);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/DeploymentBody.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\nimport org.jclouds.azurecompute.arm.domain.DeploymentTemplate.Parameters;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\n@AutoValue\npublic abstract class DeploymentBody {\n\n   @Nullable\n   public abstract DeploymentTemplate template();\n\n   @Nullable\n   public abstract String mode();\n\n   @Nullable\n   public abstract Parameters parameters();\n\n   @SerializedNames({\"template\", \"mode\", \"parameters\"})\n   public static DeploymentBody create(final DeploymentTemplate template,\n                                       final String mode,\n                                       final Parameters parameters) {\n      return new AutoValue_DeploymentBody(template, mode, parameters);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/DeploymentProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\nimport org.jclouds.json.SerializedNames;\n\n@AutoValue\npublic abstract class DeploymentProperties {\n\n   public abstract DeploymentBody properties();\n\n   @SerializedNames({\"properties\"})\n   public static DeploymentProperties create(final DeploymentBody properties) {\n      return new AutoValue_DeploymentProperties(properties);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/DeploymentTemplate.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport java.util.List;\nimport java.util.Map;\nimport org.jclouds.json.SerializedNames;\n\n@AutoValue\npublic abstract class DeploymentTemplate {\n\n   //Empty placeholders as we want to generate the empty JSON object\n   @AutoValue\n   public abstract static class Parameters {\n\n      @Nullable\n      public abstract KeyVaultReference publicKeyFromAzureKeyVault();\n\n      public static Parameters create(KeyVaultReference reference)\n      {\n         return new AutoValue_DeploymentTemplate_Parameters(reference);\n      }\n   }\n\n   @AutoValue\n   public abstract static class TemplateParameters {\n\n      @Nullable\n      public abstract TemplateParameterType publicKeyFromAzureKeyVault();\n\n      public static TemplateParameters create(TemplateParameterType publicKeyFromAzureKeyVault)\n      {\n         return new AutoValue_DeploymentTemplate_TemplateParameters(publicKeyFromAzureKeyVault);\n      }\n   }\n\n   public abstract String schema();\n\n   public abstract String contentVersion();\n\n   public abstract TemplateParameters parameters();\n\n   public abstract Map<String, String> variables();\n\n   public abstract List<ResourceDefinition> resources();\n\n   @Nullable\n   public abstract List<?> outputs();\n\n   @SerializedNames({\"$schema\", \"contentVersion\", \"parameters\", \"variables\", \"resources\", \"outputs\"})\n   public static DeploymentTemplate create(final String schema,\n                                           final String contentVersion,\n                                           final TemplateParameters parameters,\n                                           final Map<String, String> variables,\n                                           final List<ResourceDefinition> resources,\n                                           final List<?> outputs) {\n\n      DeploymentTemplate.Builder builder = DeploymentTemplate.builder()\n              .schema(schema)\n              .contentVersion(contentVersion)\n              .parameters(parameters);\n\n      if (variables != null)\n         builder.variables(variables);\n\n      if (resources != null)\n         builder.resources(resources);\n\n      builder.outputs(outputs == null ? null : ImmutableList.copyOf(outputs));\n\n      return builder.build();\n   }\n   \n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_DeploymentTemplate.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder schema(String schema);\n\n      public abstract Builder contentVersion(String type);\n\n      public abstract Builder parameters(TemplateParameters parameters);\n\n      public abstract Builder variables(Map<String, String> variables);\n\n      public abstract Builder resources(List<ResourceDefinition> resources);\n\n      public abstract Builder outputs(List<?> outputs);\n\n      abstract Map<String, String> variables();\n      abstract List<ResourceDefinition> resources();\n\n      abstract DeploymentTemplate autoBuild();\n\n      public DeploymentTemplate build() {\n         variables(variables() != null ? ImmutableMap.copyOf(variables()) : null);\n         resources(resources() != null ? ImmutableList.copyOf(resources()) : null);\n         return autoBuild();\n      }\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/DiagnosticsProfile.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\n@AutoValue\npublic abstract class DiagnosticsProfile {\n\n   @AutoValue\n   public abstract static class BootDiagnostics{\n\n      public abstract boolean enabled();\n\n      @Nullable\n      public abstract String storageUri();\n\n      @SerializedNames({\"enabled\", \"storageUri\"})\n      public static BootDiagnostics create(final boolean enabled, final String storageUri) {\n         return builder()\n                 .enabled(enabled)\n                 .storageUri(storageUri)\n                 .build();\n      }\n      \n      public abstract Builder toBuilder();\n\n      public static Builder builder() {\n         return new AutoValue_DiagnosticsProfile_BootDiagnostics.Builder();\n      }\n      @AutoValue.Builder\n      public abstract static class Builder {\n         public abstract Builder enabled(boolean enabled);\n         public abstract Builder storageUri(String storageUri);\n         public abstract BootDiagnostics build();\n      }\n   }\n\n   public abstract BootDiagnostics bootDiagnostics();\n\n   @SerializedNames({\"bootDiagnostics\"})\n   public static DiagnosticsProfile create(final BootDiagnostics  bootDiagnostics) {\n      return builder().bootDiagnostics(bootDiagnostics).build();\n   }\n   \n   public abstract Builder toBuilder();\n   \n   public static Builder builder() {\n      return new AutoValue_DiagnosticsProfile.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder bootDiagnostics(BootDiagnostics bootDiagnostics);\n      public abstract DiagnosticsProfile build();\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/Disk.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport java.util.Map;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableMap;\n\n@AutoValue\npublic abstract class Disk {\n\n   /**\n    * The id of the disk\n    */\n   @Nullable public abstract String id();\n   \n   /**\n    * The name of the disk\n    */\n   @Nullable public abstract String name();\n\n   /**\n    * The location of the disk\n    */\n   public abstract String location();\n\n   /**\n    * The type of the disk\n    */\n   @Nullable public abstract String type();\n\n   /**\n    * The sku of the disk\n    */\n   @Nullable public abstract SKU sku();\n\n   /**\n    * The managed disk parameters.\n    */\n   public abstract DiskProperties properties();\n   \n   /**\n    * the tags of the disk\n    */\n   @Nullable public abstract Map<String, String> tags();\n\n   @SerializedNames({\"id\", \"name\", \"location\", \"type\", \"sku\", \"properties\", \"tags\"})\n   public static Disk create(final String id, final String name, final String location,\n                             final String type, final SKU sku, \n                             final DiskProperties properties, final Map<String, String> tags) {\n      return builder()\n              .id(id)\n              .name(name)\n              .location(location)\n              .type(type)\n              .sku(sku)\n              .properties(properties)\n              .tags(tags)\n              .build();\n   }\n\n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_Disk.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder id(String id);\n      public abstract Builder name(String name);\n      public abstract Builder location(String location);\n      public abstract Builder type(String type);\n      public abstract Builder sku(SKU sku);\n      public abstract Builder properties(DiskProperties properties);\n      public abstract Builder tags(Map<String, String> tags);\n\n      abstract Map<String, String> tags();\n      abstract Disk autoBuild();\n\n      public Disk build() {\n         tags(tags() != null ? ImmutableMap.copyOf(tags()) : null);\n         return autoBuild();\n      }\n      \n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/DiskProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class DiskProperties implements Provisionable {\n\n   @Nullable\n   public abstract String provisioningState();\n   \n   @Nullable\n   public abstract String timeCreated();\n   \n   @Nullable\n   public abstract String diskState();\n\n   @Nullable\n   public abstract Integer diskSizeGB();\n   \n   @Nullable\n   public abstract Integer lun();\n\n   @Nullable\n   public abstract VHD vhd();\n\n   public abstract CreationData creationData();\n   \n   @SerializedNames({\"provisioningState\", \"timeCreated\", \"diskState\", \"diskSizeGB\", \"lun\", \"vhd\", \"creationData\"})\n   public static DiskProperties create(final String provisioningState, final String timeCreated, final String diskState, final Integer diskSizeGB, final Integer lun, final VHD vhd, final CreationData creationData) {\n      return builder()\n              .provisioningState(provisioningState)\n              .timeCreated(timeCreated)\n              .diskState(diskState)\n              .diskSizeGB(diskSizeGB)\n              .lun(lun)\n              .vhd(vhd)\n              .creationData(creationData)\n              .build();\n   }\n\n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_DiskProperties.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder provisioningState(String provisioningState);\n      public abstract Builder timeCreated(String timeCreated);\n      public abstract Builder diskState(String diskState);\n      public abstract Builder diskSizeGB(Integer diskSizeGB);\n      public abstract Builder lun(Integer lun);\n      public abstract Builder vhd(VHD vhd);\n      public abstract Builder creationData(CreationData creationData);\n      public abstract DiskProperties build();\n\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/DiskSku.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\n@AutoValue\npublic abstract class DiskSku\n{\n    @Nullable\n    public abstract StorageAccountType name();\n\n    @SerializedNames({\"name\"})\n    public static DiskSku create(final StorageAccountType storageAccountType) {\n        return builder()\n                .name(storageAccountType)\n                .build();\n    }\n\n    public abstract Builder toBuilder();\n\n    public static Builder builder() {\n        return new AutoValue_DiskSku.Builder();\n    }\n\n    @AutoValue.Builder\n    public abstract static class Builder {\n        public abstract Builder name(StorageAccountType storageAccountType);\n        public abstract DiskSku build();\n    }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/DnsSettings.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\n@AutoValue\npublic abstract class DnsSettings {\n\n   public abstract String domainNameLabel();\n\n   @Nullable\n   public abstract String fqdn();\n\n   @Nullable\n   public abstract String reverseFqdn();\n\n   @SerializedNames({\"domainNameLabel\", \"fqdn\", \"reverseFqdn\"})\n   public static DnsSettings create(final String domainNameLabel, final String fqdn, final String reverseFqdn) {\n      return builder()\n              .domainNameLabel(domainNameLabel)\n              .fqdn(fqdn)\n              .reverseFqdn(reverseFqdn)\n              .build();\n   }\n   \n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_DnsSettings.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder domainNameLabel(String domainNameLabel);\n\n      public abstract Builder fqdn(String fqdn);\n\n      public abstract Builder reverseFqdn(String reverseFqdn);\n\n      public abstract DnsSettings build();\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/DynamicThresholdFailingPeriods.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class DynamicThresholdFailingPeriods {\n \n\tpublic abstract int minFailingPeriodsToAlert();\n \n\tpublic abstract int numberOfEvaluationPeriods();\n\n\t@SerializedNames({ \"minFailingPeriodsToAlert\", \"numberOfEvaluationPeriods\" })\n\tpublic static DynamicThresholdFailingPeriods create(final int minFailingPeriodsToAlert,\n\t\t\tfinal int numberOfEvaluationPeriods) {\n\t\treturn new AutoValue_DynamicThresholdFailingPeriods(minFailingPeriodsToAlert, numberOfEvaluationPeriods);\n\n\t}\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/Error.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\n\n@AutoValue\npublic abstract class Error {\n\n   public abstract Details details();\n\n   @SerializedNames({ \"error\" })\n   public static Error create(Details details) {\n      return new AutoValue_Error(details);\n   }\n\n   Error() {\n\n   }\n\n   @AutoValue\n   public abstract static class Details {\n      public abstract String code();\n      public abstract String message();\n      public abstract List<Details> details();\n\n      @SerializedNames({ \"code\", \"message\", \"details\" })\n      public static Details create(String code, String message, @Nullable List<Details> details) {\n         return new AutoValue_Error_Details(code, message, details == null ? ImmutableList.<Details> of()\n               : ImmutableList.copyOf(details));\n      }\n\n      Details() {\n\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/Essentials.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport java.util.Date;\n\nimport org.jclouds.azurecompute.arm.util.GetEnumValue;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class Essentials {\n\n\tpublic enum AlertState {\n\t\tNew, Acknowledged, Closed;\n\n\t\tpublic static AlertState fromValue(final String text) {\n\t\t\treturn (AlertState) GetEnumValue.fromValueOrDefault(text, AlertState.New);\n\t\t}\n\t}\n\n\tpublic enum MonitorCondition {\n\t\tFired, Resloved;\n\n\t\tpublic static MonitorCondition fromValue(final String text) {\n\t\t\treturn (MonitorCondition) GetEnumValue.fromValueOrDefault(text, MonitorCondition.Fired);\n\t\t}\n\t}\n\n\t@Nullable\n\tpublic abstract ActionStatus actionStatus();\n\n\t@Nullable\n\tpublic abstract String alertRule();\n\n\t@Nullable\n\tpublic abstract Date lastModifiedDateTime();\n\n\t@Nullable\n\tpublic abstract String lastModifiedUserName();\n\n\t@Nullable\n\tpublic abstract String sourceCreatedId();\n\n\t@Nullable\n\tpublic abstract Date startDateTime();\n\n\t@Nullable\n\tpublic abstract String targetResource();\n\n\t@Nullable\n\tpublic abstract String targetResourceGroup();\n\n\t@Nullable\n\tpublic abstract String targetResourceName();\n\n\t@Nullable\n\tpublic abstract String targetResourceType();\n\n\t@Nullable\n\tpublic abstract AlertState alertState();\n\n\t@Nullable\n\tpublic abstract MonitorCondition monitorCondition();\n\n\t@Nullable\n\tpublic abstract String monitorService();\n\n\t@Nullable\n\tpublic abstract String severity();\n\n\t@Nullable\n\tpublic abstract String signalType();\n\n\t@SerializedNames({ \"actionStatus\", \"alertRule\", \"lastModifiedDateTime\", \"lastModifiedUserName\", \"sourceCreatedId\",\n\t\t\t\"startDateTime\", \"targetResource\", \"targetResourceGroup\", \"targetResourceName\", \"targetResourceType\",\n\t\t\t\"alertState\", \"monitorCondition\", \"monitorService\", \"severity\", \"signalType\" })\n\tpublic static Essentials create(final ActionStatus actionStatus, final String alertRule,\n\t\t\tfinal Date lastModifiedDateTime, final String lastModifiedUserName, final String sourceCreatedId,\n\t\t\tfinal Date startDateTime, final String targetResource, final String targetResourceGroup,\n\t\t\tfinal String targetResourceName, final String targetResourceType, final AlertState alertState,\n\t\t\tfinal MonitorCondition monitorCondition, final String monitorService, final String severity,\n\t\t\tfinal String signalType) {\n\t\treturn new AutoValue_Essentials(actionStatus, alertRule, lastModifiedDateTime, lastModifiedUserName,\n\t\t\t\tsourceCreatedId, startDateTime, targetResource, targetResourceGroup, targetResourceName,\n\t\t\t\ttargetResourceType, alertState, monitorCondition, monitorService, severity, signalType);\n\n\t}\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/Extension.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\nimport org.jclouds.json.SerializedNames;\n\n@AutoValue\npublic abstract class Extension {\n\n   /**\n    * The name reference of the extension profile\n    */\n   public abstract String name();\n\n   /**\n    * The properties reference of the extension profile\n    */\n   public abstract ExtensionProperties properties();\n\n\n   @SerializedNames({\"name\", \"properties\"})\n   public static Extension create(final String name, final ExtensionProperties properties) {\n      return new AutoValue_Extension(name, properties);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/ExtensionProfile.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\nimport org.jclouds.json.SerializedNames;\n\nimport java.util.List;\n\n@AutoValue\npublic abstract class ExtensionProfile {\n\n   /**\n    * The list of extensions of the extension profile\n    */\n   public abstract List<Extension> extensions();\n\n\n   @SerializedNames({\"extensions\"})\n   public static ExtensionProfile create(final List<Extension> extensions) {\n      return new AutoValue_ExtensionProfile(extensions == null ?\n         ImmutableList.<Extension>of() : ImmutableList.copyOf(extensions));\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/ExtensionProfileSettings.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\nimport org.jclouds.json.SerializedNames;\n\nimport java.util.List;\n\n@AutoValue\npublic abstract class ExtensionProfileSettings {\n\n   /**\n    * The fileUris reference of the extension profile settings\n    */\n   public abstract List<String> fileUris();\n\n   /**\n    * The commandToExecute of the extension profile settings\n    */\n   public abstract String commandToExecute();\n\n   @SerializedNames({\"fileUris\", \"commandToExecute\"})\n   public static ExtensionProfileSettings create(final List<String> fileUris, final String commandToExecute) {\n      return new AutoValue_ExtensionProfileSettings(fileUris == null ? ImmutableList.<String>of() : ImmutableList.copyOf(fileUris), commandToExecute);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/ExtensionProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableMap;\nimport org.jclouds.json.SerializedNames;\n\nimport java.util.Map;\n\n@AutoValue\npublic abstract class ExtensionProperties {\n\n   /**\n    * The publisher reference of the extension properties\n    */\n   public abstract String publisher();\n\n   /**\n    * The type reference of the extension properties\n    */\n   public abstract String type();\n\n   /**\n    * The typeHandlerVersion reference of the extension properties\n    */\n   public abstract String typeHandlerVersion();\n\n   /**\n    * The autoUpgradeMinorVersion reference of the extension properties\n    */\n   public abstract Boolean autoUpgradeMinorVersion();\n\n   /**\n    * The ExtensionProfileSettings of the extension properties\n    */\n   public abstract ExtensionProfileSettings settings();\n\n   /**\n    * The list of the protectedSettings of the extension properties\n    */\n   public abstract Map<String, String> protectedSettings();\n\n   @SerializedNames({ \"publisher\", \"type\", \"typeHandlerVersion\",\n      \"autoUpgradeMinorVersion\", \"settings\", \"protectedSettings\"})\n   public static ExtensionProperties create(final String publisher, String type,\n                                            final String typeHandlerVersion,\n                                            final Boolean autoUpgradeMinorVersion,\n                                            final ExtensionProfileSettings settings,\n                                            final Map<String, String> protectedSettings) {\n      return new AutoValue_ExtensionProperties(publisher, type, typeHandlerVersion, autoUpgradeMinorVersion,\n         settings, protectedSettings == null ?\n         ImmutableMap.<String, String>of() : ImmutableMap.copyOf(protectedSettings));\n   }\n}\n\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/FrontendIPConfigurations.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class FrontendIPConfigurations {\n   public abstract String name();\n\n   @Nullable\n   public abstract String id();\n\n   @Nullable\n   public abstract FrontendIPConfigurationsProperties properties();\n\n   @Nullable\n   public abstract String etag();\n\n   @SerializedNames({ \"name\", \"id\", \"properties\", \"etag\" })\n   public static FrontendIPConfigurations create(final String name, final String id,\n         final FrontendIPConfigurationsProperties properties,\n                                             final String etag) {\n      return new AutoValue_FrontendIPConfigurations(name, id,\n                                                properties, etag);\n   }\n}\n\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/FrontendIPConfigurationsProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class FrontendIPConfigurationsProperties {\n\n   @Nullable\n   public abstract IdReference subnet();\n\n   @Nullable\n   public abstract String privateIPAddress();\n\n   @Nullable\n   public abstract String privateIPAllocationMethod();\n\n   @Nullable\n   public abstract IdReference publicIPAddress();\n\n\n   @SerializedNames({ \"subnet\", \"privateIPAddress\", \"privateIPAllocationMethod\", \"publicIPAddress\" })\n   public static FrontendIPConfigurationsProperties create(final IdReference subnet, final String privateIPAddress,\n         final String privateIPAllocationMethod, final IdReference publicIPAddress) {\n      return builder().subnet(subnet).publicIPAddress(publicIPAddress).privateIPAddress(privateIPAddress)\n            .privateIPAllocationMethod(privateIPAllocationMethod).build();\n   }\n   \n   public abstract Builder toBuilder();\n   \n   public static Builder builder() {\n      return new AutoValue_FrontendIPConfigurationsProperties.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder subnet(IdReference subnet);\n\n      public abstract Builder privateIPAddress(String privateIPAddress);\n\n      public abstract Builder privateIPAllocationMethod(String privateIPAllocationMethod);\n\n      public abstract Builder publicIPAddress(IdReference publicIPAddress);\n\n      public abstract FrontendIPConfigurationsProperties build();\n   }\n}\n\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/HardwareProfile.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\n\nimport org.jclouds.json.SerializedNames;\n\n@AutoValue\npublic abstract class HardwareProfile {\n\n   /**\n    * The vm size of the virtual machine.\n    */\n   public abstract String vmSize();\n\n   @SerializedNames({\"vmSize\"})\n   public static HardwareProfile create(final String vmSize) {\n      return builder().vmSize(vmSize).build();\n   }\n   \n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_HardwareProfile.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder vmSize(String vmSize);\n\n      public abstract HardwareProfile build();\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/IdReference.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n// Simple helper class to serialize / deserialize id reference.\n\n@AutoValue\npublic abstract class IdReference {\n   \n   private static final Pattern RESOURCE_GROUP_PATTERN = Pattern.compile(\"^.*/resourceGroups/([^/]+)(/.*)?$\");\n   \n   @Nullable\n   public abstract String id();\n   \n   @Nullable\n   public String resourceGroup() {\n      return extractResourceGroup(id());\n   }\n   \n   @Nullable\n   public String name() {\n      return extractName(id());\n   }\n\n   @SerializedNames({\"id\"})\n   public static IdReference create(final String id) {\n      return new AutoValue_IdReference(id);\n   }\n   \n   /**\n    * Extracts the name from the given URI.\n    */\n   public static String extractName(String uri) {\n      if (uri == null)\n         return null;\n      String noSlashAtEnd = uri.replaceAll(\"/+$\", \"\");\n      return noSlashAtEnd.substring(noSlashAtEnd.lastIndexOf('/') + 1);\n   }\n   \n   /**\n    * Extracts the resource group name from the given URI.\n    */\n   public static String extractResourceGroup(String uri) {\n      if (uri == null)\n         return null;\n      Matcher m = RESOURCE_GROUP_PATTERN.matcher(uri);\n      return m.matches() ? m.group(1) : null;\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/Image.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport java.util.Map;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableMap;\n\n@AutoValue\npublic abstract class Image {\n   \n   /**\n    * The id of the image\n    */\n   @Nullable\n   public abstract String id();\n\n   /**\n    * The name of the image\n    */\n   @Nullable\n   public abstract String name();\n\n   /**\n    * The location of the image\n    */\n   public abstract String location();\n\n   /**\n    * The image properties.\n    */\n   public abstract ImageProperties properties();\n\n   /**\n    * the tags of the image\n    */\n   @Nullable public abstract Map<String, String> tags();\n\n   @SerializedNames({\"id\", \"name\", \"location\", \"properties\", \"tags\"})\n   public static Image create(final String id, final String name, final String location,\n         final ImageProperties properties, final Map<String, String> tags) {\n      return builder().id(id).name(name).location(location).properties(properties).tags(tags).build();\n   }\n\n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_Image.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder id(String id);\n      public abstract Builder name(String name);\n      public abstract Builder location(String location);\n      public abstract Builder properties(ImageProperties properties);\n      public abstract Builder tags(Map<String, String> tags);\n\n      abstract Map<String, String> tags();\n\n      abstract Image autoBuild();\n\n      public Image build() {\n         tags(tags() != null ? ImmutableMap.copyOf(tags()) : null);\n         return autoBuild();\n      }\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/ImageProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class ImageProperties implements Provisionable {\n\n   @Nullable\n   public abstract IdReference sourceVirtualMachine();\n   \n   @Nullable\n   public abstract StorageProfile storageProfile();\n\n   @Nullable\n   public abstract String provisioningState();\n   \n   @SerializedNames({ \"sourceVirtualMachine\", \"storageProfile\", \"provisioningState\"})\n   public static ImageProperties create(final IdReference sourceVirtualMachine, \n                                        final StorageProfile storageProfile,\n                                        final String provisioningState) {\n      return builder()\n              .sourceVirtualMachine(sourceVirtualMachine)\n              .storageProfile(storageProfile)\n              .provisioningState(provisioningState)\n              .build();\n   }\n\n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_ImageProperties.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder sourceVirtualMachine(IdReference sourceVirtualMachine);\n      public abstract Builder storageProfile(StorageProfile storageProfile);\n      public abstract Builder provisioningState(String provisioningState);\n      public abstract ImageProperties build();\n\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/ImageReference.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport static org.jclouds.azurecompute.arm.domain.IdReference.extractName;\nimport static org.jclouds.azurecompute.arm.domain.IdReference.extractResourceGroup;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class ImageReference {\n\n   /**\n    * Specifies the resource identifier of a virtual machine image in your subscription. This element is only used\n    * for virtual machine images, not platform images or marketplace images.\n    */\n   @Nullable\n   public abstract String customImageId();\n\n   /**\n    * The publisher of the image reference.\n    */\n   @Nullable\n   public abstract String publisher();\n\n   /**\n    * The offer of the image reference.\n    */\n   @Nullable\n   public abstract String offer();\n\n   /**\n    * The sku of the image reference.\n    */\n   @Nullable\n   public abstract String sku();\n\n   /**\n    * The version of the image reference.\n    */\n   @Nullable\n   public abstract String version();\n   \n   ImageReference() {\n      \n   }\n\n   @SerializedNames({\"id\", \"publisher\", \"offer\", \"sku\", \"version\"})\n   public static ImageReference create(final String id,\n                                       final String publisher,\n                                       final String offer,\n                                       final String sku,\n                                       final String version) {\n\n      return builder().customImageId(id)\n              .publisher(publisher)\n              .offer(offer)\n              .sku(sku)\n              .version(version)\n              .build();\n   }\n   \n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_ImageReference.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder customImageId(String ids);\n      public abstract Builder publisher(String publisher);\n      public abstract Builder offer(String offer);\n      public abstract Builder sku(String sku);\n      public abstract Builder version(String version);\n\n      public abstract ImageReference build();\n   }\n   \n   public String encodeFieldsToUniqueId(String location) {\n      return VMImage.azureImage().location(location).publisher(publisher()).offer(offer()).sku(sku()).build()\n            .encodeFieldsToUniqueId();\n   }\n\n   public String encodeFieldsToUniqueIdCustom(String location) {\n      return VMImage.customImage().resourceGroup(extractResourceGroup(customImageId())).location(location)\n            .name(extractName(customImageId())).build().encodeFieldsToUniqueIdCustom();\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/InboundNatRule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class InboundNatRule {\n   @Nullable\n   public abstract String name();\n\n   @Nullable\n   public abstract String id();\n\n   @Nullable\n   public abstract InboundNatRuleProperties properties();\n\n   @Nullable\n   public abstract String etag();\n\n   @SerializedNames({ \"name\", \"id\", \"properties\", \"etag\" })\n   public static InboundNatRule create(final String name, final String id, final InboundNatRuleProperties properties,\n         final String etag) {\n      return new AutoValue_InboundNatRule(name, id, properties, etag);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/InboundNatRuleProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport org.jclouds.azurecompute.arm.util.GetEnumValue;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class InboundNatRuleProperties implements Provisionable {\n   public enum Protocol {\n      Tcp(\"Tcp\"), Udp(\"Udp\"), UNRECOGNIZED(\"Unrecognized\");\n\n      private final String label;\n\n      private Protocol(final String label) {\n         this.label = label;\n      }\n\n      public static Protocol fromValue(final String text) {\n         return (Protocol) GetEnumValue.fromValueOrDefault(text, Protocol.UNRECOGNIZED);\n      }\n\n      @Override\n      public String toString() {\n         return label;\n      }\n   }\n\n   @Nullable\n   public abstract IdReference frontendIPConfiguration();\n\n   @Nullable\n   public abstract IdReference backendIPConfiguration();\n\n   public abstract Protocol protocol();\n\n   public abstract int backendPort();\n\n   public abstract int frontendPort();\n\n   @Nullable\n   public abstract Boolean enableFloatingIP();\n\n   @Nullable\n   public abstract Integer idleTimeoutInMinutes();\n\n   @Nullable\n   public abstract String provisioningState();\n\n   @SerializedNames({ \"frontendIPConfiguration\", \"backendIPConfiguration\", \"protocol\", \"frontendPort\", \"backendPort\",\n         \"provisioningState\", \"enableFloatingIP\", \"idleTimeoutInMinutes\" })\n   public static InboundNatRuleProperties create(final IdReference frontendIPConfiguration,\n         final IdReference backendIPConfiguration, final Protocol protocol, final int frontendPort,\n         final int backendPort, final String provisioningState, Boolean enableFloatingIP, Integer idleTimeoutInMinutes) {\n      return builder().frontendIPConfiguration(frontendIPConfiguration).backendIPConfiguration(backendIPConfiguration)\n            .protocol(protocol).frontendPort(frontendPort).backendPort(backendPort)\n            .provisioningState(provisioningState).enableFloatingIP(enableFloatingIP)\n            .idleTimeoutInMinutes(idleTimeoutInMinutes).build();\n   }\n\n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_InboundNatRuleProperties.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n\n      public abstract Builder frontendIPConfiguration(IdReference frontendIPConfiguration);\n\n      public abstract Builder backendIPConfiguration(IdReference backendIPConfiguration);\n\n      public abstract Builder protocol(Protocol protocol);\n\n      public abstract Builder frontendPort(int frontendPort);\n\n      public abstract Builder backendPort(int backendPort);\n\n      public abstract Builder provisioningState(String provisioningState);\n\n      public abstract Builder enableFloatingIP(Boolean enableFloatingIP);\n\n      public abstract Builder idleTimeoutInMinutes(Integer idleTimeoutInMinutes);\n\n      public abstract InboundNatRuleProperties build();\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/IpAddressAvailabilityResult.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport java.util.List;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\n\n@AutoValue\npublic abstract class IpAddressAvailabilityResult {\n   public abstract boolean available();\n\n   public abstract List<String> availableIPAddresses();\n\n   @SerializedNames({ \"available\", \"availableIPAddresses\" })\n   public static IpAddressAvailabilityResult create(final boolean available, final List<String> availableIPAddresses) {\n      return new AutoValue_IpAddressAvailabilityResult(available,\n            availableIPAddresses != null ? ImmutableList.copyOf(availableIPAddresses) : ImmutableList.<String> of());\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/IpAllocationMethod.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport org.jclouds.azurecompute.arm.util.GetEnumValue;\n\npublic enum IpAllocationMethod {\n   \n   Static, Dynamic, Unrecognized;\n\n   public static IpAllocationMethod fromValue(final String text) {\n      return (IpAllocationMethod) GetEnumValue.fromValueOrDefault(text, IpAllocationMethod.Unrecognized);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/IpConfiguration.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.azurecompute.arm.domain;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class IpConfiguration {\n\n   @Nullable\n   public abstract String name();\n\n   @Nullable\n   public abstract String id();\n\n   @Nullable\n   public abstract String etag();\n\n   @Nullable\n   public abstract IpConfigurationProperties properties();\n\n   @SerializedNames({ \"name\", \"id\", \"etag\", \"properties\" })\n   public static IpConfiguration create(final String name, final String id, final String etag,\n         final IpConfigurationProperties properties) {\n      return builder()\n              .name(name)\n              .id(id)\n              .etag(etag)\n              .properties(properties)\n              .build();\n   }\n   \n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_IpConfiguration.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder name(String name);\n      public abstract Builder id(String id);\n      public abstract Builder etag(String etag);\n      public abstract Builder properties(IpConfigurationProperties properties);\n      public abstract IpConfiguration build();\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/IpConfigurationProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\n\n@AutoValue\npublic abstract class IpConfigurationProperties implements Provisionable {\n\n   @Nullable\n   public abstract String provisioningState();\n\n   @Nullable\n   public abstract String privateIPAddress();\n\n   @Nullable\n   public abstract String privateIPAllocationMethod();\n\n   @Nullable\n   public abstract IdReference subnet();\n\n   @Nullable\n   public abstract IdReference publicIPAddress();\n   \n   @Nullable\n   public abstract List<IdReference> loadBalancerBackendAddressPools();\n   \n   @Nullable\n   public abstract List<IdReference> loadBalancerInboundNatRules();\n\n   @Nullable\n   public abstract Boolean primary();\n\n   @SerializedNames({ \"provisioningState\", \"privateIPAddress\", \"privateIPAllocationMethod\", \"subnet\", \"publicIPAddress\",\n         \"loadBalancerBackendAddressPools\", \"loadBalancerInboundNatRules\", \"primary\" })\n   public static IpConfigurationProperties create(final String provisioningState, final String privateIPAddress,\n         final String privateIPAllocationMethod, final IdReference subnet, final IdReference publicIPAddress,\n         List<IdReference> loadBalancerBackendAddressPools, List<IdReference> loadBalancerInboundNatRules,\n         final Boolean primary) {\n\n      return builder()\n              .provisioningState(provisioningState)\n              .privateIPAddress(privateIPAddress)\n              .privateIPAllocationMethod(privateIPAllocationMethod)\n              .subnet(subnet)\n              .publicIPAddress(publicIPAddress)\n              .loadBalancerBackendAddressPools(loadBalancerBackendAddressPools)\n            .loadBalancerInboundNatRules(loadBalancerInboundNatRules).primary(primary)\n              .build();\n   }\n   \n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_IpConfigurationProperties.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder provisioningState(String provisioningState);\n\n      public abstract Builder privateIPAddress(String privateIPAddress);\n\n      public abstract Builder privateIPAllocationMethod(String privateIPAllocationMethod);\n\n      public abstract Builder subnet(IdReference subnet);\n\n      public abstract Builder publicIPAddress(IdReference publicIPAddress);\n\n      public abstract Builder loadBalancerBackendAddressPools(List<IdReference> loadBalancerBackendAddressPools);\n      \n      public abstract Builder loadBalancerInboundNatRules(List<IdReference> loadBalancerInboundNatRules);\n\n      public abstract Builder primary(Boolean primary);\n      \n      abstract List<IdReference> loadBalancerBackendAddressPools();\n      \n      abstract List<IdReference> loadBalancerInboundNatRules();\n      \n      abstract IpConfigurationProperties autoBuild();\n\n      public IpConfigurationProperties build() {\n         loadBalancerBackendAddressPools(loadBalancerBackendAddressPools() != null ? ImmutableList\n               .copyOf(loadBalancerBackendAddressPools()) : null);\n         loadBalancerInboundNatRules(loadBalancerInboundNatRules() != null ? ImmutableList\n               .copyOf(loadBalancerInboundNatRules()) : null);\n         return autoBuild();\n      }\n   }\n}\n\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/Key.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport java.util.Map;\nimport java.util.List;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class Key {\n    @AutoValue\n    public abstract static class JsonWebKey {\n        @Nullable\n        public abstract String crv();\n\n        @Nullable\n        public abstract String d();\n\n        @Nullable\n        public abstract String dp();\n\n        @Nullable\n        public abstract String dq();\n\n        @Nullable\n        public abstract String e();\n\n        @Nullable\n        public abstract String k();\n\n        @Nullable\n        public abstract String keyHsm();\n\n        public abstract List<String> keyOps();\n\n        @Nullable\n        public abstract String kid();\n\n        @Nullable\n        public abstract String kty();\n\n        @Nullable\n        public abstract String n();\n\n        @Nullable\n        public abstract String p();\n\n        @Nullable\n        public abstract String q();\n\n        @Nullable\n        public abstract String qi();\n\n        @Nullable\n        public abstract String x();\n\n        @Nullable\n        public abstract String y();\n\n        @SerializedNames({\"crv\", \"d\", \"dp\", \"dq\", \"e\", \"k\", \"key_hsm\", \"key_ops\", \"kid\", \"kty\", \"n\", \"p\", \"q\", \"qi\", \"x\", \"y\"})\n        public static JsonWebKey create(final String crv, final String d, final String dp, final String dq,\n                                        final String e, final String k, final String keyHsm, final List<String> keyOps,\n                                        final String kid, final String kty, final String n, final String p,\n                                        final String q, final String qi, final String x, final String y) {\n            return new AutoValue_Key_JsonWebKey(\n                    crv, d, dp, dq, e, k, keyHsm,\n                    keyOps != null ? ImmutableList.copyOf(keyOps) : ImmutableList.<String> of(),\n                    kid, kty, n, p, q, qi, x, y);\n        }\n    }\n\n    @AutoValue\n    public abstract static class KeyAttributes {\n        @Nullable\n        public abstract Boolean enabled();\n\n        @Nullable\n        public abstract Integer created();\n\n        @Nullable\n        public abstract Integer expires();\n\n        @Nullable\n        public abstract Integer notBefore();\n\n        @Nullable\n        public abstract String recoveryLevel();\n\n        @Nullable\n        public abstract Integer updated();\n\n        @SerializedNames({\"enabled\", \"created\", \"expires\", \"notBefore\", \"recoveryLevel\", \"updated\"})\n        public static KeyAttributes create(final Boolean enabled,\n                                           final Integer created,\n                                           final Integer expires,\n                                           final Integer notBefore,\n                                           final String recoveryLevel,\n                                           final Integer updated) {\n            return new AutoValue_Key_KeyAttributes(enabled, created, expires, notBefore, recoveryLevel, updated);\n        }\n\n        KeyAttributes() {\n        }\n    }\n\n    @AutoValue\n    public abstract static class KeyBundle {\n        @Nullable\n        public abstract KeyAttributes attributes();\n\n        @Nullable\n        public abstract JsonWebKey key();\n\n        @Nullable\n        public abstract Boolean managed();\n\n        @Nullable\n        public abstract Map<String, String> tags();\n\n        @SerializedNames({\"attributes\", \"key\", \"managed\", \"tags\"})\n        public static KeyBundle create(final KeyAttributes attributes, final JsonWebKey key, final boolean managed, final Map<String, String> tags) {\n            return new AutoValue_Key_KeyBundle(\n                    attributes,\n                    key,\n                    managed,\n                    tags != null ? ImmutableMap.copyOf(tags) : null\n            );\n        }\n    }\n\n    @AutoValue\n    public abstract static class DeletedKeyBundle {\n        @Nullable\n        public abstract KeyAttributes attributes();\n\n        @Nullable\n        public abstract String deletedDate();\n\n        @Nullable\n        public abstract JsonWebKey key();\n\n        @Nullable\n        public abstract Boolean managed();\n\n        @Nullable\n        public abstract String recoveryId();\n\n        @Nullable\n        public abstract String scheduledPurgeDate();\n\n        @Nullable\n        public abstract Map<String, String> tags();\n\n        @SerializedNames({\"attributes\", \"deletedDate\", \"key\", \"managed\", \"recoveryId\", \"scheduledPurgeDate\", \"tags\"})\n        public static DeletedKeyBundle create(final KeyAttributes attributes, final String deletedDate, final JsonWebKey key, final boolean managed, final String recoveryId, final String scheduledPurgeDate, final Map<String, String> tags) {\n            return new AutoValue_Key_DeletedKeyBundle(\n                    attributes,\n                    deletedDate,\n                    key,\n                    managed,\n                    recoveryId,\n                    scheduledPurgeDate,\n                    tags != null ? ImmutableMap.copyOf(tags) : null\n\n            );\n        }\n    }\n\n    @AutoValue\n    public abstract static class KeyOperationResult {\n        @Nullable\n        public abstract String keyId();\n\n        @Nullable\n        public abstract String value();\n\n        @SerializedNames({\"kid\", \"value\"})\n        public static KeyOperationResult create(final String keyId, final String value) {\n            return new AutoValue_Key_KeyOperationResult(\n                    keyId,\n                    value\n            );\n        }\n    }\n\n    @Nullable\n    public abstract String kid();\n\n    public abstract KeyAttributes attributes();\n\n    @Nullable\n    public abstract Boolean managed();\n\n    @Nullable\n    public abstract Map<String, String> tags();\n\n    @SerializedNames({\"kid\", \"attributes\", \"managed\", \"tags\"})\n    public static Key create(final String kid, final KeyAttributes attributes, final boolean managed, final Map<String, String> tags) {\n        return new AutoValue_Key(\n                kid,\n                attributes,\n                managed,\n                tags != null ? ImmutableMap.copyOf(tags) : null\n        );\n    }\n\n    Key() {\n    }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/KeyVaultReference.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\nimport org.jclouds.json.SerializedNames;\n\n// Simple helper class to serialize / deserialize keyvault reference.\n\n@AutoValue\npublic abstract class KeyVaultReference {\n\n   @AutoValue\n   public abstract static class Reference {\n\n      public abstract IdReference keyVault();\n\n      public abstract String secretName();\n\n      @SerializedNames({\"keyVault\", \"secretName\"})\n      public static Reference create(final IdReference keyVault, final String secretName) {\n         return new AutoValue_KeyVaultReference_Reference(keyVault, secretName);\n      }\n   }\n\n   public abstract Reference reference();\n\n   @SerializedNames({\"reference\"})\n   public static KeyVaultReference create(final Reference reference) {\n      return new AutoValue_KeyVaultReference(reference);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/Location.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\nimport org.jclouds.json.SerializedNames;\n\n/**\n * A data center location that is valid for your subscription.\n */\n@AutoValue\npublic abstract class Location {\n   /**\n    * The id of the data center.\n    */\n   public abstract String id();\n\n   /**\n    * The name of the data center location. Ex. {@code West Europe}.\n    */\n   public abstract String name();\n\n   /**\n    * The localized name of the data center location.\n    */\n   public abstract String displayName();\n\n   /**\n    * The longitude of the datacenter\n    */\n   public abstract String longitude();\n\n   /**\n    * The latitude of the datacenter\n    */\n   public abstract String latitude();\n\n   @SerializedNames({\"id\", \"name\", \"displayName\", \"longitude\", \"latitude\"})\n   public static Location create(final String id, final String name, final String displayName, final String longitude,\n           final String latitude) {\n\n      return new AutoValue_Location(id, name, displayName, longitude, latitude);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/ManagedDiskParameters.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class ManagedDiskParameters {\n\n   @Nullable public abstract String id();\n\n   // Might be null in custom images. In that case the API returns it in the OSDisk object.\n   @Nullable public abstract StorageAccountType storageAccountType();\n\n   @SerializedNames({\"id\", \"storageAccountType\"})\n   public static ManagedDiskParameters create(final String id, final String storageAccountType) {\n      return new AutoValue_ManagedDiskParameters(id, StorageAccountType.fromString(storageAccountType));\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/Metric.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\n\n/**\n * A Metric with its values for a resource\n */\n@AutoValue\npublic abstract class Metric {\n\n   public abstract List<MetricData> data();\n\n   public abstract String id();\n\n   @Nullable\n   public abstract MetricName name();\n\n   public abstract String type();\n\n   public abstract String unit();\n\n   @SerializedNames({ \"data\", \"id\", \"name\", \"type\", \"unit\" })\n   public static Metric create(final List<MetricData> data, final String id, final MetricName name, final String type,\n         final String unit) {\n      return new AutoValue_Metric(data == null ? ImmutableList.<MetricData> of() : ImmutableList.copyOf(data), id, name,\n            type, unit);\n   }\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/MetricAlert.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport java.util.Map;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableMap;\n\n@AutoValue\npublic abstract class MetricAlert {\n\n\t/**\n\t * The id of the resource\n\t */\t\n\tpublic abstract String id();\n\n\t/**\n\t * The name of the resource\n\t */\t\n\tpublic abstract String name();\n\n\t/**\n\t * The location of the resource\n\t */\n\tpublic abstract String location();\n\n\t/**\n\t * The type of the resource\n\t */\n\tpublic abstract String type();\n\n\t@Nullable\n\tpublic abstract Map<String, String> tags();\n\n\t@Nullable\n\tpublic abstract MetricAlertProperties properties();\n\n\t@SerializedNames({ \"id\", \"name\", \"location\", \"type\", \"tags\", \"properties\" })\n\tpublic static MetricAlert create(final String id, final String name, final String location,\n\t\t\tfinal String type, final Map<String, String> tags, final MetricAlertProperties properties) {\n\t\treturn builder().id(id).name(name).location(location).type(type).tags(tags).properties(properties).build();\n\t}\n\n\tpublic abstract Builder toBuilder();\n\n\tpublic static Builder builder() {\n\t\treturn new AutoValue_MetricAlert.Builder();\n\t}\n\n\t@AutoValue.Builder\n\tpublic abstract static class Builder {\n\t\tpublic abstract Builder id(String id);\n\n\t\tpublic abstract Builder name(String name);\n\n\t\tpublic abstract Builder location(String location);\n\n\t\tpublic abstract Builder type(String type);\n\n\t\tpublic abstract Builder tags(Map<String, String> tags);\n\n\t\tpublic abstract Builder properties(MetricAlertProperties properties);\n\n\t\tabstract Map<String, String> tags();\n\n\t\tabstract MetricAlert autoBuild();\n\n\t\tpublic MetricAlert build() {\n\t\t\ttags(tags() != null ? ImmutableMap.copyOf(tags()) : null);\n\t\t\treturn autoBuild();\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/MetricAlertAction.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class MetricAlertAction {\n\t@Nullable\n\tpublic abstract String actionGroupId();\n\n\t@Nullable\n\tpublic abstract Object webhookProperties();\n\n\t@SerializedNames({ \"actionGroupId\", \"webhookProperties\" })\n\tpublic static MetricAlertAction create(final String actionGroupId, final Object webhookProperties) {\n\t\treturn new AutoValue_MetricAlertAction(actionGroupId, webhookProperties);\n\n\t}\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/MetricAlertCriteria.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport java.util.List;\n\nimport org.jclouds.azurecompute.arm.util.GetEnumValue;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class MetricAlertCriteria {\n\n\t@Nullable\n\tpublic abstract String criterionType();\n\n\t@Nullable\n\tpublic abstract List<MetricDimension> dimensions();\n\n\t@Nullable\n\tpublic abstract String metricName();\n\n\t@Nullable\n\tpublic abstract String metricNamespace();\n\n\t@Nullable\n\tpublic abstract String name();\n\n\t@Nullable\n\tpublic abstract Operator operator();\n\n\tpublic abstract boolean skipMetricValidation();\n\n\tpublic abstract int threshold();\n\n\t@Nullable\n\tpublic abstract AggregationTypeEnum timeAggregation();\n\n\t@Nullable\n\tpublic abstract DynamicThresholdSensitivity alertSensitivity();\n\n\t@Nullable\n\tpublic abstract DynamicThresholdFailingPeriods failingPeriods();\n\n\t@Nullable\n\tpublic abstract String ignoreDataBefore();\n\n\t@Nullable\n\tpublic abstract String componentId();\n\n\tpublic abstract int failedLocationCount();\n\n\t@Nullable\n\tpublic abstract String webTestId();\n\n\t@SerializedNames({ \"criterionType\", \"dimensions\", \"metricName\", \"metricNamespace\", \"name\", \"operator\",\n\t\t\t\"skipMetricValidation\", \"threshold\", \"timeAggregation\", \"alertSensitivity\", \"failingPeriods\",\n\t\t\t\"ignoreDataBefore\", \"componentId\", \"failedLocationCount\", \"webTestId\" })\n\tpublic static MetricAlertCriteria create(final String criterionType, List<MetricDimension> dimensions,\n\t\t\tfinal String metricName, final String metricNamespace, final String name, final Operator operator,\n\t\t\tfinal boolean skipMetricValidation, final int threshold, final AggregationTypeEnum timeAggregation,\n\t\t\tfinal DynamicThresholdSensitivity alertSensitivity, final DynamicThresholdFailingPeriods failingPeriods,\n\t\t\tfinal String ignoreDataBefore, final String componentId, final int failedLocationCount,\n\t\t\tfinal String webTestId) {\n\t\treturn new AutoValue_MetricAlertCriteria(criterionType, dimensions, metricName, metricNamespace, name, operator,\n\t\t\t\tskipMetricValidation, threshold, timeAggregation, alertSensitivity, failingPeriods, ignoreDataBefore,\n\t\t\t\tcomponentId, failedLocationCount, webTestId);\n\n\t}\n\n\tpublic enum AggregationTypeEnum {\n\t\tAverage, Count, Maximum, Minimum, Total;\n\t\tpublic static AggregationTypeEnum fromValue(final String text) {\n\t\t\treturn (AggregationTypeEnum) GetEnumValue.fromValueOrDefault(text, AggregationTypeEnum.Average);\n\t\t}\n\t}\n\n\tpublic enum Operator {\n\t\tEquals, GreaterThan, GreaterThanOrEqual, LessThan, LessThanOrEqual, GreaterOrLessThan;\n\t\tpublic static Operator fromValue(final String text) {\n\t\t\treturn (Operator) GetEnumValue.fromValueOrDefault(text, Operator.Equals);\n\t\t}\n\t}\n\n\tpublic enum DynamicThresholdSensitivity {\n\t\tHigh, Low, Medium;\n\t\tpublic static DynamicThresholdSensitivity fromValue(final String text) {\n\t\t\treturn (DynamicThresholdSensitivity) GetEnumValue.fromValueOrDefault(text,\n\t\t\t\t\tDynamicThresholdSensitivity.High);\n\t\t}\n\t}\n\n\tpublic enum DynamicThresholdOperator {\n\t\tGreaterOrLessThan, GreaterThan, LessThan;\n\t\tpublic static DynamicThresholdOperator fromValue(final String text) {\n\t\t\treturn (DynamicThresholdOperator) GetEnumValue.fromValueOrDefault(text,\n\t\t\t\t\tDynamicThresholdOperator.GreaterOrLessThan);\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/MetricAlertProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport java.util.Date;\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class MetricAlertProperties {\n\n\t@Nullable\n\tpublic abstract List<MetricAlertAction> actions();\n\n\tpublic abstract boolean autoMitigate();\n\n\t@Nullable\n\tpublic abstract Criteria criteria();\n\n\t@Nullable\n\tpublic abstract String description();\n\n\tpublic abstract boolean enabled();\n\n\t@Nullable\n\tpublic abstract String evaluationFrequency();\n\n\tpublic abstract boolean isMigrated();\n\n\t@Nullable\n\tpublic abstract Date lastUpdatedTime();\n\n\t@Nullable\n\tpublic abstract List<String> scopes();\n\n\tpublic abstract int severity();\n\n\t@Nullable\n\tpublic abstract String targetResourceRegion();\n\n\t@Nullable\n\tpublic abstract String targetResourceType();\n\n\t@Nullable\n\tpublic abstract String windowSize();\n\n\t@SerializedNames({ \"actions\", \"autoMitigate\", \"criteria\", \"description\", \"enabled\", \"evaluationFrequency\",\n\t\t\t\"isMigrated\", \"lastUpdatedTime\", \"scopes\", \"severity\", \"targetResourceRegion\", \"targetResourceType\",\n\t\t\t\"windowSize\" })\n\tpublic static MetricAlertProperties create(final List<MetricAlertAction> actions, final boolean autoMitigate,\n\t\t\tfinal Criteria criteria, final String description, final boolean enabled, final String evaluationFrequency,\n\t\t\tfinal boolean isMigrated, final Date lastUpdatedTime, final List<String> scopes, final int severity,\n\t\t\tfinal String targetResourceRegion, final String targetResourceType, final String windowSize) {\n\t\treturn builder().actions(actions).criteria(criteria).autoMitigate(autoMitigate).description(description)\n\t\t\t\t.enabled(enabled).evaluationFrequency(evaluationFrequency).isMigrated(isMigrated)\n\t\t\t\t.lastUpdatedTime(lastUpdatedTime).scopes(scopes).severity(severity)\n\t\t\t\t.targetResourceRegion(targetResourceRegion).targetResourceType(targetResourceType)\n\t\t\t\t.windowSize(windowSize).build();\n\t}\n\n\tpublic abstract Builder toBuilder();\n\n\tpublic static Builder builder() {\n\t\treturn new AutoValue_MetricAlertProperties.Builder();\n\t}\n\n\t@AutoValue.Builder\n\tpublic abstract static class Builder {\n\n\t\tpublic abstract Builder autoMitigate(boolean autoMitigate);\n\n\t\tpublic abstract Builder description(String description);\n\n\t\tpublic abstract Builder enabled(boolean enabled);\n\n\t\tpublic abstract Builder evaluationFrequency(String evaluationFrequency);\n\n\t\tpublic abstract Builder isMigrated(boolean isMigrated);\n\n\t\tpublic abstract Builder lastUpdatedTime(Date lastUpdatedTime);\n\n\t\tpublic abstract Builder severity(int severity);\n\n\t\tpublic abstract Builder targetResourceRegion(String targetResourceRegion);\n\n\t\tpublic abstract Builder targetResourceType(String targetResourceType);\n\n\t\tpublic abstract Builder windowSize(String windowSize);\n\n\t\tpublic abstract Builder scopes(List<String> scopes);\n\n\t\tpublic abstract Builder actions(List<MetricAlertAction> actions);\n\n\t\tpublic abstract Builder criteria(Criteria criteria);\n\n\t\tpublic abstract MetricAlertProperties build();\n\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/MetricData.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport java.util.Date;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n/**\n *\n */\n@AutoValue\npublic abstract class MetricData\n{\n\n    /**\n     * The timestamp for the metric value in ISO 8601 format.\n     */\n    public abstract Date timeStamp();\n\n    /**\n     * The average value in the time range\n     */\n    @Nullable\n    public abstract Double total();\n\n    /**\n     * The sum of all of the values in the time range.\n     */\n    @Nullable\n    public abstract Double average();\n\n    /**\n     * The least value in the time range.\n     */\n    @Nullable\n    public abstract Double minimum();\n\n    /**\n     * The greatest value in the time range.\n     */\n    @Nullable\n    public abstract Double maximum();\n\n    /**\n     * The number of samples in the time range.\n     */\n    @Nullable\n    public abstract Long count();\n\n    @SerializedNames({\"timeStamp\", \"total\", \"average\", \"minimum\", \"maximum\", \"count\"})\n    public static MetricData create(final Date timeStamp, final Double total, final Double average,\n        final Double minimum, final Double maximum, final Long count)\n    {\n        return new AutoValue_MetricData(timeStamp, total, average, minimum, maximum, count);\n    }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/MetricDefinition.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport java.util.List;\n\nimport org.jclouds.azurecompute.arm.util.GetEnumValue;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\n\n/**\n * A Metric definition for a resource\n */\n@AutoValue\npublic abstract class MetricDefinition {\n\n   public enum AggregationType {\n      None(\"None\"), Average(\"Average\"), Count(\"Count\"), Total(\"Total\"), Minimum(\"Minimum\"), Maximum(\n            \"Maximum\"), UNRECOGNIZED(\"Unrecognized\");\n\n      private final String label;\n\n      AggregationType(String label) {\n         this.label = label;\n      }\n\n      public static AggregationType fromValue(final String text) {\n         return (AggregationType) GetEnumValue.fromValueOrDefault(text, AggregationType.UNRECOGNIZED);\n      }\n\n      @Override\n      public String toString() {\n         return label;\n      }\n   }\n\n   @Nullable\n   public abstract String resourceId();\n\n   public abstract MetricName name();\n\n   @Nullable\n   public abstract Boolean isDimensionRequired();\n\n   public abstract String unit();\n\n   public abstract AggregationType primaryAggregationType();\n\n   public abstract List<MetricDefinition.MetricAvailability> metricAvailabilities();\n\n   public abstract String id();\n\n   @SerializedNames({ \"resourceId\", \"name\", \"isDimensionRequired\", \"unit\", \"primaryAggregationType\",\n         \"metricAvailabilities\", \"id\" })\n   public static MetricDefinition create(final String resourceId, final MetricName name,\n         final Boolean isDimensionRequired, final String unit, final AggregationType primaryAggregationType,\n         List<MetricAvailability> metricAvailabilities, final String id) {\n      return new AutoValue_MetricDefinition(resourceId, name, isDimensionRequired, unit, primaryAggregationType,\n            metricAvailabilities == null ?\n                  ImmutableList.<MetricAvailability> of() :\n                  ImmutableList.copyOf(metricAvailabilities), id);\n   }\n\n   @AutoValue\n   public abstract static class MetricAvailability {\n\n      public abstract String timeGrain();\n\n      public abstract String retention();\n\n      MetricAvailability() {\n\n      }\n\n      @SerializedNames({ \"timeGrain\", \"retention\" })\n      public static MetricDefinition.MetricAvailability create(String timeGrain, String retention) {\n         return new AutoValue_MetricDefinition_MetricAvailability(timeGrain, retention);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/MetricDimension.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class MetricDimension {\n\n\t@Nullable\n\tpublic abstract String name();\n\n\t@Nullable\n\tpublic abstract String operator();\n\n\t@Nullable\n\tpublic abstract List<String> values();\n\n\t@SerializedNames({ \"name\", \"operator\", \"values\" })\n\tpublic static MetricDimension create(final String name, final String operator, final List<String> values) {\n\t\treturn builder().name(name).operator(operator).values(values).build();\n\t}\n\n\tpublic abstract Builder toBuilder();\n\n\tpublic static Builder builder() {\n\t\treturn new AutoValue_MetricDimension.Builder();\n\t}\n\n\t@AutoValue.Builder\n\tpublic abstract static class Builder {\n\n\t\tpublic abstract Builder name(String name);\n\n\t\tpublic abstract Builder operator(String operator);\n\n\t\tpublic abstract Builder values(List<String> values);\n\n\t\tpublic abstract MetricDimension build();\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/MetricName.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n/**\n * A Metric with its values for a resource\n */\n@AutoValue\npublic abstract class MetricName {\n\n   public abstract String value();\n\n   public abstract String localizedValue();\n\n   @SerializedNames({ \"value\", \"localizedValue\" })\n   public static MetricName create(String value, String localizedValue) {\n      return new AutoValue_MetricName(value, localizedValue);\n   }\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/NetworkInterfaceCard.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableMap;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport java.util.Map;\n\n@AutoValue\npublic abstract class NetworkInterfaceCard {\n\n   @Nullable\n   public abstract String name();\n\n   @Nullable\n   public abstract String id();\n\n   @Nullable\n   public abstract String etag();\n\n   @Nullable\n   public abstract String location();\n\n   @Nullable\n   public abstract NetworkInterfaceCardProperties properties();\n\n   @Nullable\n   public abstract Map<String, String> tags();\n\n   @SerializedNames({\"name\", \"id\", \"etag\", \"location\", \"properties\", \"tags\"})\n   public static NetworkInterfaceCard create(final String name,\n                                             final String id,\n                                             final String etag,\n                                             final String location,\n                                             final NetworkInterfaceCardProperties properties,\n                                             final Map<String, String> tags) {\n      return new AutoValue_NetworkInterfaceCard(name, id, etag, location, properties,\n         tags != null ? ImmutableMap.copyOf(tags) : null);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/NetworkInterfaceCardProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\n\n@AutoValue\npublic abstract class NetworkInterfaceCardProperties implements Provisionable {\n\n   @Nullable public abstract String provisioningState();\n   @Nullable public abstract String resourceGuid();\n   @Nullable public abstract Boolean enableIPForwarding();\n   @Nullable public abstract List<IpConfiguration> ipConfigurations();\n   @Nullable public abstract IdReference networkSecurityGroup();\n   @Nullable public abstract IdReference virtualMachine();\n   @Nullable public abstract Boolean primary();\n\n   @SerializedNames({\"provisioningState\", \"resourceGuid\", \"enableIPForwarding\", \"ipConfigurations\",\n         \"networkSecurityGroup\", \"virtualMachine\", \"primary\" })\n   public static NetworkInterfaceCardProperties create(final String provisioningState, final String resourceGuid,\n         final Boolean enableIPForwarding, final List<IpConfiguration> ipConfigurations,\n         final IdReference networkSecurityGroup, final IdReference virtualMachine, final Boolean primary) {\n      NetworkInterfaceCardProperties.Builder builder = NetworkInterfaceCardProperties.builder()\n              .provisioningState(provisioningState)\n              .resourceGuid(resourceGuid)\n              .enableIPForwarding(enableIPForwarding)\n              .ipConfigurations(ipConfigurations == null ? null : ImmutableList.copyOf(ipConfigurations))\n            .networkSecurityGroup(networkSecurityGroup).virtualMachine(virtualMachine).primary(primary);\n\n      return builder.build();\n   }\n\n   NetworkInterfaceCardProperties() {\n\n   }\n\n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_NetworkInterfaceCardProperties.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder provisioningState(String provisioningState);\n      public abstract Builder resourceGuid(String resourceGuid);\n      public abstract Builder enableIPForwarding(Boolean enableIPForwarding);\n      public abstract Builder ipConfigurations(List<IpConfiguration> ipConfigurations);\n      public abstract Builder networkSecurityGroup(IdReference networkSecurityGroup);\n      public abstract Builder virtualMachine(IdReference virtualMachine);\n      public abstract Builder primary(Boolean primary);\n\n\n      abstract List<IpConfiguration> ipConfigurations();\n      abstract NetworkInterfaceCardProperties autoBuild();\n\n      public NetworkInterfaceCardProperties build() {\n         ipConfigurations(ipConfigurations() != null ? ImmutableList.copyOf(ipConfigurations()) : null);\n         return autoBuild();\n      }\n   }\n}\n\n\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/NetworkInterfaceConfiguration.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\n@AutoValue\npublic abstract class NetworkInterfaceConfiguration {\n   /**\n    * The name of the NetworkInterfaceConfiguration\n    */\n   @Nullable\n   public abstract String name();\n\n   /**\n    * The networkConfigurationProperties of the NetworkInterfaceConfiguration\n    */\n   @Nullable\n   public abstract NetworkInterfaceConfigurationProperties networkInterfaceConfigurationProperties();\n\n   @SerializedNames({\"name\", \"properties\"})\n   public static NetworkInterfaceConfiguration create(\n      final String name, NetworkInterfaceConfigurationProperties networkInterfaceConfigurationProperties) {\n\n      return new AutoValue_NetworkInterfaceConfiguration(name, networkInterfaceConfigurationProperties);\n   }\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/NetworkInterfaceConfigurationProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport java.util.List;\n\n\n@AutoValue\npublic abstract class NetworkInterfaceConfigurationProperties {\n    /**\n     * The primary of the NetworkInterfaceConfigurationProperties\n     */\n    @Nullable\n    public abstract Boolean primary();\n\n    /**\n     * The enableAcceleratedNetworking of the NetworkInterfaceConfigurationProperties\n     */\n    @Nullable\n    public abstract Boolean enableAcceleratedNetworking();\n\n    /**\n     * The networkSecurityGroup of the NetworkInterfaceConfigurationProperties\n     */\n    @Nullable\n    public abstract VirtualMachineScaleSetNetworkSecurityGroup networkSecurityGroup();\n\n   /**\n    * The dnsSettings of the NetworkInterfaceConfigurationProperties\n    */\n   @Nullable\n   public abstract VirtualMachineScaleSetDNSSettings dnsSettings();\n\n   /**\n    * The ipConfigurations of the NetworkInterfaceConfigurationProperties\n    */\n   public abstract List<VirtualMachineScaleSetIpConfiguration> ipConfigurations();\n\n\n    @SerializedNames({\"primary\", \"enableAcceleratedNetworking\", \"networkSecurityGroup\", \"dnsSettings\", \"ipConfigurations\"})\n    public static NetworkInterfaceConfigurationProperties create(final Boolean primary,\n                                                               final Boolean enableAcceleratedNetworking,\n                                                               final VirtualMachineScaleSetNetworkSecurityGroup networkSecurityGroup,\n                                                               final VirtualMachineScaleSetDNSSettings dnsSettings,\n                                                               final List<VirtualMachineScaleSetIpConfiguration> ipConfigurations) {\n\n        return new AutoValue_NetworkInterfaceConfigurationProperties(primary, enableAcceleratedNetworking,\n                networkSecurityGroup, dnsSettings, ipConfigurations);\n    }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/NetworkProfile.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport java.util.List;\n\n@AutoValue\npublic abstract class NetworkProfile {\n\n   @AutoValue\n   public abstract static class NetworkInterface {\n      public abstract String id();\n      @Nullable public abstract NetworkInterfaceProperties properties();\n      \n      @AutoValue\n      public abstract static class NetworkInterfaceProperties {\n         public abstract boolean primary();\n         \n         NetworkInterfaceProperties() {\n            \n         }\n         \n         @SerializedNames({\"primary\"})\n         public static NetworkInterfaceProperties create(boolean primary) {\n            return new AutoValue_NetworkProfile_NetworkInterface_NetworkInterfaceProperties(primary);\n         }\n      }\n      \n      NetworkInterface() {\n         \n      }\n      \n      @SerializedNames({\"id\", \"properties\"})\n      public static NetworkInterface create(String id, NetworkInterfaceProperties properties) {\n         return new AutoValue_NetworkProfile_NetworkInterface(id, properties);\n      }\n   }\n   \n   /**\n    * List of network interfaces\n    */\n   public abstract List<NetworkInterface> networkInterfaces();\n\n   @SerializedNames({\"networkInterfaces\"})\n   public static NetworkProfile create(final List<NetworkInterface> networkInterfaces) {\n      return builder().networkInterfaces(networkInterfaces).build();\n   }\n   \n   NetworkProfile() {\n      \n   }\n   \n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_NetworkProfile.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder networkInterfaces(List<NetworkInterface> networkInterfaces);\n\n      abstract List<NetworkInterface> networkInterfaces();\n\n      abstract NetworkProfile autoBuild();\n\n      public NetworkProfile build() {\n         networkInterfaces(networkInterfaces() != null ? ImmutableList.copyOf(networkInterfaces()) : ImmutableList.<NetworkInterface>of());\n         return autoBuild();\n      }\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/NetworkSecurityGroup.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableMap;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport java.util.Map;\n\n@AutoValue\npublic abstract class NetworkSecurityGroup {\n   public abstract String id();\n   public abstract String name();\n\n   @Nullable\n   public abstract String location();\n\n   @Nullable\n   public abstract Map<String, String> tags();\n\n   @Nullable\n   public abstract NetworkSecurityGroupProperties properties();\n\n   @Nullable\n   public abstract String etag();\n\n   @SerializedNames({ \"id\", \"name\", \"location\", \"tags\", \"properties\", \"etag\" })\n   public static NetworkSecurityGroup create(final String id, final String name, final String location,\n         final Map<String, String> tags, final NetworkSecurityGroupProperties properties, final String etag) {\n      return new AutoValue_NetworkSecurityGroup(id, name, location, (tags == null) ? null : ImmutableMap.copyOf(tags),\n            properties, etag);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/NetworkSecurityGroupProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\nimport com.google.common.collect.ImmutableList;\n\nimport java.util.List;\n\n@AutoValue\npublic abstract class NetworkSecurityGroupProperties implements Provisionable {\n\n   @Nullable\n   public abstract List<NetworkSecurityRule> securityRules();\n\n   @Nullable\n   public abstract List<NetworkSecurityRule> defaultSecurityRules();\n\n   @Nullable\n   public abstract List<NetworkInterfaceCard> networkInterfaces();\n\n   @Nullable\n   public abstract List<Subnet> subnets();\n\n   @Nullable\n   public abstract String resourceGuid();\n\n   @Nullable\n   public abstract String provisioningState();\n\n   @SerializedNames({\"securityRules\", \"defaultSecurityRules\", \"networkInterfaces\", \"subnets\", \"resourceGuid\",\n      \"provisioningState\"})\n   public static NetworkSecurityGroupProperties create(final List<NetworkSecurityRule> securityRules,\n                                          final List<NetworkSecurityRule> defaultSecurityRules,\n                                          final List<NetworkInterfaceCard> networkInterfaces,\n                                          final List<Subnet> subnets,\n                                          final String resourceGuid,\n                                          final String provisioningState) {\n      return builder()\n              .securityRules((securityRules == null) ? null : ImmutableList.copyOf(securityRules))\n              .defaultSecurityRules((defaultSecurityRules == null) ? null : ImmutableList.copyOf(defaultSecurityRules))\n              .networkInterfaces((networkInterfaces == null) ? null : ImmutableList.copyOf(networkInterfaces))\n              .subnets((subnets == null) ? null : ImmutableList.copyOf(subnets))\n              .resourceGuid(resourceGuid)\n              .provisioningState(provisioningState)\n              .build();\n   }\n   \n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_NetworkSecurityGroupProperties.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder securityRules(List<NetworkSecurityRule> securityRules);\n\n      public abstract Builder defaultSecurityRules(List<NetworkSecurityRule> securityRules);\n\n      public abstract Builder networkInterfaces(List<NetworkInterfaceCard> networkInterfaces);\n\n      public abstract Builder subnets(List<Subnet> subnets);\n\n      public abstract Builder resourceGuid(String resourceGuid);\n\n      public abstract Builder provisioningState(String provisioningState);\n\n      public abstract NetworkSecurityGroupProperties build();\n   }\n}\n\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/NetworkSecurityRule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\n@AutoValue\npublic abstract class NetworkSecurityRule {\n\n   @Nullable\n   public abstract String name();\n\n   @Nullable\n   public abstract String id();\n\n   @Nullable\n   public abstract String etag();\n\n   @Nullable\n   public abstract NetworkSecurityRuleProperties properties();\n\n   @SerializedNames({\"name\", \"id\", \"etag\", \"properties\"})\n   public static NetworkSecurityRule create(final String name,\n                                            final String id,\n                                            final String etag,\n                                            final NetworkSecurityRuleProperties properties) {\n      return new AutoValue_NetworkSecurityRule(name, id, etag, properties);\n   }\n}\n\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/NetworkSecurityRuleProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport org.jclouds.azurecompute.arm.util.GetEnumValue;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class NetworkSecurityRuleProperties implements Provisionable {\n   public enum Protocol {\n      // * is an allowed value, will handle in\n      Tcp(\"Tcp\"),\n      Udp(\"Udp\"),\n      All(\"*\"),\n      UNRECOGNIZED(\"Unrecognized\");\n\n      private final String label;\n\n      private Protocol(String label) { this.label = label; }\n\n      public static Protocol fromValue(final String text) {\n         if (\"*\".equals(text)) {\n            return All;\n         } else {\n            return (Protocol) GetEnumValue.fromValueOrDefault(text, Protocol.UNRECOGNIZED);\n         }\n      }\n\n      @Override\n      public String toString() {\n         return label;\n      }\n   }\n\n   public enum Access {\n      Allow,\n      Deny,\n      UNRECOGNIZED;\n\n      public static Access fromValue(final String text) {\n         return (Access) GetEnumValue.fromValueOrDefault(text, Access.UNRECOGNIZED);\n      }\n   }\n\n   public enum Direction {\n      Inbound,\n      Outbound,\n      UNRECOGNIZED;\n\n      public static Direction fromValue(final String text) {\n         return (Direction) GetEnumValue.fromValueOrDefault(text, Direction.UNRECOGNIZED);\n      }\n   }\n\n   @Nullable\n   public abstract String description();\n\n   public abstract Protocol protocol();\n\n   @Nullable\n   public abstract String sourcePortRange();\n\n   @Nullable\n   public abstract String destinationPortRange();\n\n   public abstract String sourceAddressPrefix();\n\n   public abstract String destinationAddressPrefix();\n\n   public abstract Access access();\n\n   @Nullable\n   public abstract Integer priority();\n\n   public abstract Direction direction();\n\n   @Nullable\n   public abstract String provisioningState();\n\n   @SerializedNames({ \"description\", \"protocol\", \"sourcePortRange\", \"destinationPortRange\", \"sourceAddressPrefix\", \"destinationAddressPrefix\", \"access\", \"priority\", \"direction\", \"provisioningState\" })\n   public static NetworkSecurityRuleProperties create(final String description,\n                                                      final Protocol protocol,\n                                                      final String sourcePortRange,\n                                                      final String destinationPortRange,\n                                                      final String sourceAddressPrefix,\n                                                      final String destinationAddressPrefix,\n                                                      final Access access,\n                                                      final Integer priority,\n                                                      final Direction direction,\n                                                      final String provisioningState) {\n      return builder()\n              .description(description)\n              .protocol(protocol)\n              .sourcePortRange(sourcePortRange)\n              .destinationPortRange(destinationPortRange)\n              .sourceAddressPrefix(sourceAddressPrefix)\n              .destinationAddressPrefix(destinationAddressPrefix)\n              .access(access)\n              .priority(priority)\n              .direction(direction).provisioningState(provisioningState)\n              .build();\n   }\n   \n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_NetworkSecurityRuleProperties.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder description(String description);\n\n      public abstract Builder protocol(Protocol protocol);\n\n      public abstract Builder sourcePortRange(String sourcePortRange);\n\n      public abstract Builder destinationPortRange(String destinationPortRange);\n\n      public abstract Builder sourceAddressPrefix(String sourceAddressPrefix);\n\n      public abstract Builder destinationAddressPrefix(String sourceAddressPrefix);\n\n      public abstract Builder access(Access access);\n\n      public abstract Builder priority(Integer priority);\n\n      public abstract Builder direction(Direction direction);\n\n      public abstract Builder provisioningState(String provisioningState);\n\n      public abstract NetworkSecurityRuleProperties build();\n   }\n}\n\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/OSDisk.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class OSDisk {\n   /**\n    * The OS type of the os disk\n    */\n   @Nullable\n   public abstract String osType();\n\n   /**\n    * The name of the os disk\n    */\n   @Nullable\n   public abstract String name();\n\n   /**\n    * The vhd of the os disk\n    */\n   @Nullable\n   public abstract VHD vhd();\n\n   /**\n    * The caching mode of the os disk\n    */\n   @Nullable\n   public abstract String caching();\n\n   /**\n    * The create options of the os disk\n    */\n   @Nullable\n   public abstract String createOption();\n\n   /**\n    * The url of the custom image\n    */\n   @Nullable\n   public abstract VHD image();\n\n   /**\n    * The managed disk parameters.\n    */\n   @Nullable public abstract ManagedDiskParameters managedDiskParameters();\n   \n   /**\n    * The storage account type. This field is returned in custom images.\n    */\n   @Nullable public abstract StorageAccountType storageAccountType();\n\n   @SerializedNames({ \"osType\", \"name\", \"vhd\", \"caching\", \"createOption\", \"image\", \"managedDisk\", \"storageAccountType\" })\n   public static OSDisk create(final String osType, final String name, final VHD vhd, final String caching,\n         final String createOption, final VHD image, final ManagedDiskParameters managedDiskParamenters,\n         final String storageAccountType) {\n      return builder().osType(osType).name(name).vhd(vhd).caching(caching).createOption(createOption).image(image)\n            .managedDiskParameters(managedDiskParamenters)\n            .storageAccountType(StorageAccountType.fromString(storageAccountType)).build();\n   }\n\n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_OSDisk.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder osType(String osType);\n      public abstract Builder name(String name);\n      public abstract Builder caching(String caching);\n      public abstract Builder createOption(String createOption);\n      public abstract Builder vhd(VHD vhd);\n      public abstract Builder image(VHD image);\n      public abstract Builder managedDiskParameters(ManagedDiskParameters managedDiskParameters);\n      public abstract Builder storageAccountType(StorageAccountType storageAccountType);\n      public abstract OSDisk build();\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/OSProfile.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport java.util.List;\n\nimport org.jclouds.azurecompute.arm.util.GetEnumValue;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\n\n@AutoValue\npublic abstract class OSProfile {\n\n   @AutoValue\n   public abstract static class LinuxConfiguration {\n\n      @AutoValue\n      public abstract static class SSH {\n\n         @AutoValue\n         public abstract static class SSHPublicKey {\n\n            @Nullable\n            public abstract String path();\n\n            @Nullable\n            public abstract String keyData();\n\n            @SerializedNames({\"path\", \"keyData\"})\n            public static SSHPublicKey create(final String path, final String keyData) {\n\n               return new AutoValue_OSProfile_LinuxConfiguration_SSH_SSHPublicKey(\n                       path, keyData);\n            }\n         }\n\n         /**\n          * The list of public keys and paths\n          */\n         @Nullable\n         public abstract List<SSHPublicKey> publicKeys();\n\n         @SerializedNames({\"publicKeys\"})\n         public static SSH create(final List<SSHPublicKey> publicKeys) {\n\n            return new AutoValue_OSProfile_LinuxConfiguration_SSH(\n                    publicKeys);\n         }\n      }\n\n      /**\n       * The authentication method password or ssh\n       */\n      public abstract String disablePasswordAuthentication();\n\n      /**\n       * ssh keys\n       */\n      @Nullable\n      public abstract SSH ssh();\n\n      @SerializedNames({\"disablePasswordAuthentication\", \"ssh\"})\n      public static LinuxConfiguration create(final String disablePasswordAuthentication,\n                                              final SSH ssh) {\n\n         return new AutoValue_OSProfile_LinuxConfiguration(disablePasswordAuthentication,\n                 ssh);\n      }\n   }\n\n   @AutoValue\n   public abstract static class WindowsConfiguration {\n\n      @AutoValue\n      public abstract static class WinRM {\n          public enum Protocol {\n\n              HTTP(\"http\"),\n              HTTPS(\"https\"),\n              UNRECOGNIZED(\"Unrecognized\");\n\n              private String value;\n\n              Protocol(String value) {\n                 this.value = value;\n              }\n\n              public static Protocol fromValue(String value) {\n                  return (Protocol) GetEnumValue.fromValueOrDefault(value, Protocol.UNRECOGNIZED);\n              }\n\n              @Override\n              public String toString() {\n                 return this.value;\n              }\n           }\n\n          @AutoValue\n          public abstract static class ProtocolListener {\n\n             public abstract Protocol protocol();\n\n             @Nullable\n             public abstract String certificateUrl();\n\n             @SerializedNames({\"protocol\", \"certificateUrl\"})\n             public static ProtocolListener create(final Protocol protocol, final String certificateUrl) {\n\n                return new AutoValue_OSProfile_WindowsConfiguration_WinRM_ProtocolListener(\n                        protocol, certificateUrl);\n             }\n          }\n\n         /**\n          * Map of different settings\n          */\n         public abstract List<ProtocolListener> listeners();\n\n         @SerializedNames({\"listeners\"})\n         public static WinRM create(final List<ProtocolListener> listeners) {\n            return new AutoValue_OSProfile_WindowsConfiguration_WinRM(listeners == null ? ImmutableList.<ProtocolListener>of() : ImmutableList.copyOf(listeners));\n         }\n      }\n\n      @AutoValue\n      public abstract static class AdditionalUnattendContent {\n\n         public abstract String pass();\n\n         public abstract String component();\n\n         public abstract String settingName();\n\n         @Nullable public abstract String content();\n\n         @SerializedNames({\"passName\", \"componentName\", \"settingName\", \"content\"})\n         public static AdditionalUnattendContent create(final String passName, final String componentName,\n                                                        final String settingName,\n                                                        final String content) {\n\n            return new AutoValue_OSProfile_WindowsConfiguration_AdditionalUnattendContent(\n                    passName, componentName, settingName, content);\n         }\n      }\n\n      /**\n       * The provision VM Agent true of false.\n       */\n      public abstract boolean provisionVMAgent();\n\n      /**\n       * winR\n       */\n      @Nullable\n      public abstract WinRM winRM();\n\n      /**\n       * unattend content\n       */\n      @Nullable\n      public abstract List<AdditionalUnattendContent> additionalUnattendContent();\n\n      /**\n       * is automatic updates enabled\n       */\n      public abstract boolean enableAutomaticUpdates();\n\n      @SerializedNames({\"provisionVMAgent\", \"winRM\", \"additionalUnattendContent\", \"enableAutomaticUpdates\"})\n      public static WindowsConfiguration create(final boolean provisionVMAgent, final WinRM winRM,\n                                                final List<AdditionalUnattendContent> additionalUnattendContent,\n                                                final boolean enableAutomaticUpdates) {\n\n         return new AutoValue_OSProfile_WindowsConfiguration(provisionVMAgent, winRM,\n                 additionalUnattendContent, enableAutomaticUpdates);\n      }\n   }\n\n   /**\n    * The computer name of the VM\n    */\n   @Nullable\n   public abstract String computerName();\n\n   /**\n    * The admin username of the VM\n    */\n   @Nullable\n   public abstract String adminUsername();\n\n   /**\n    * The admin password of the VM\n    */\n   @Nullable\n   public abstract String adminPassword();\n\n   /**\n    * The custom data of the VM\n    */\n   @Nullable\n   public abstract String customData();\n\n   /**\n    * The linux configuration of the VM\n    */\n   @Nullable\n   public abstract LinuxConfiguration linuxConfiguration();\n\n   /**\n    * The windows configuration of the VM\n    */\n   @Nullable\n   public abstract WindowsConfiguration windowsConfiguration();\n\n   /**\n    * The Secrets configuration of the VM\n    */\n   @Nullable\n   public abstract List<Secrets> secrets();\n\n   @SerializedNames({\"computerName\", \"adminUsername\", \"adminPassword\", \"customData\", \"linuxConfiguration\",\n           \"windowsConfiguration\", \"secrets\"})\n   public static OSProfile create(final String computerName, final String adminUsername, final String adminPassword,\n                                  final String customData, final LinuxConfiguration linuxConfiguration,\n                                  final WindowsConfiguration windowsConfiguration, final List<Secrets> secrets) {\n      return builder()\n              .computerName(computerName)\n              .adminUsername(adminUsername)\n              .adminPassword(adminPassword)\n              .customData(customData)\n              .linuxConfiguration(linuxConfiguration)\n              .windowsConfiguration(windowsConfiguration)\n              .secrets(secrets)\n              .build();\n   }\n   \n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_OSProfile.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder computerName(String computerName);\n\n      public abstract Builder adminUsername(String adminUsername);\n\n      public abstract Builder adminPassword(String adminPassword);\n\n      public abstract Builder customData(String customData);\n\n      public abstract Builder linuxConfiguration(LinuxConfiguration linuxConfiguration);\n\n      public abstract Builder windowsConfiguration(WindowsConfiguration windowsConfiguration);\n\n      public abstract Builder secrets(List<Secrets> secrets);\n\n      public abstract OSProfile build();\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/Offer.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\n/**\n * Offer\n */\n@AutoValue\npublic abstract class Offer {\n   /**\n    * The location of the Offer\n    */\n   @Nullable\n   public abstract String location();\n\n   /**\n    * The name of the Offer\n    */\n   @Nullable\n   public abstract String name();\n\n   /**\n    * The id of the Offer\n    */\n   @Nullable\n   public abstract String id();\n\n   @SerializedNames({\"location\", \"name\", \"id\"})\n   public static Offer create(final String location, final String name, final String id) {\n\n      return new AutoValue_Offer(location, name, id);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/Plan.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n/**\n * Plan\n */\n@AutoValue\npublic abstract class Plan {\n   /**\n    * The publisher of the Plan\n    */\n   public abstract String publisher();\n   \n   /**\n    * The name of the Plan\n    */\n   public abstract String name();\n   \n   /**\n    * The product of the Plan\n    */\n   public abstract String product();\n   \n   @SerializedNames({\"publisher\", \"name\", \"product\"})\n   public static Plan create(final String publisher, final String name, final String product) {\n      return new AutoValue_Plan(publisher, name, product);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/Probe.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class Probe {\n   @Nullable\n   public abstract String name();\n\n   @Nullable\n   public abstract String id();\n\n   @Nullable\n   public abstract ProbeProperties properties();\n\n   @Nullable\n   public abstract String etag();\n\n   @SerializedNames({ \"name\", \"id\", \"properties\", \"etag\" })\n   public static Probe create(final String name, final String id, final ProbeProperties properties, final String etag) {\n      return new AutoValue_Probe(name, id, properties, etag);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/ProbeProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport org.jclouds.azurecompute.arm.util.GetEnumValue;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class ProbeProperties implements Provisionable {\n   public enum Protocol {\n      Tcp(\"Tcp\"), Http(\"Http\"), UNRECOGNIZED(\"Unrecognized\");\n\n      private final String label;\n\n      private Protocol(final String label) {\n         this.label = label;\n      }\n\n      public static Protocol fromValue(final String text) {\n         return (Protocol) GetEnumValue.fromValueOrDefault(text, Protocol.UNRECOGNIZED);\n      }\n\n      @Override\n      public String toString() {\n         return label;\n      }\n   }\n\n   @Nullable\n   public abstract Protocol protocol();\n\n   public abstract int port();\n\n   @Nullable\n   public abstract String requestPath();\n\n   public abstract int intervalInSeconds();\n\n   public abstract int numberOfProbes();\n\n   @Nullable\n   public abstract String provisioningState();\n\n   @SerializedNames({ \"protocol\", \"port\", \"requestPath\", \"intervalInSeconds\", \"numberOfProbes\", \"provisioningState\" })\n   public static ProbeProperties create(final Protocol protocol, final int port, final String requestPath,\n         final int intervalInSeconds, final int numberOfProbes, final String provisioningState) {\n      return builder().protocol(protocol).port(port).requestPath(requestPath).intervalInSeconds(intervalInSeconds)\n            .numberOfProbes(numberOfProbes).provisioningState(provisioningState).build();\n   }\n   \n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_ProbeProperties.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n\n      public abstract Builder protocol(Protocol protocol);\n\n      public abstract Builder port(int port);\n\n      public abstract Builder requestPath(String requestPath);\n\n      public abstract Builder intervalInSeconds(int intervalInSeconds);\n\n      public abstract Builder numberOfProbes(int numberOfProbes);\n\n      public abstract Builder provisioningState(String provisioningState);\n\n      public abstract ProbeProperties build();\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/Provisionable.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\npublic interface Provisionable {\n   \n   String provisioningState();\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/Publisher.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\n/**\n * Publisher\n */\n@AutoValue\npublic abstract class Publisher {\n\n   /**\n    * The location of the publisher\n    */\n   @Nullable\n   public abstract String location();\n\n   /**\n    * The name of the publisher\n    */\n   @Nullable\n   public abstract String name();\n\n   /**\n    * The id of the publisher\n    */\n   @Nullable\n   public abstract String id();\n\n   @SerializedNames({\"location\", \"name\", \"id\"})\n   public static Publisher create(final String location, final String name, final String id) {\n\n      return new AutoValue_Publisher(location, name, id);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/Region.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport java.util.Arrays;\nimport java.util.Set;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Preconditions;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\n\n/**\n * Regions used in Azure.\n *\n * @see <a href=\"http://azure.microsoft.com/en-us/regions/\">this page</a>\n */\npublic enum Region {\n\n   CENTRAL_US(\"Central US\", \"US-IA\"),\n   EAST_US(\"East US\", \"US-VA\"),\n   EAST_US_2(\"East US 2\", \"US-VA\"),\n   US_GOV_IOWA(\"US Gov Iowa\", \"US-IA\"),\n   US_GOV_VIRGINIA(\"US Gov Virginia\", \"US-VA\"),\n   NORTH_CENTRAL_US(\"North Central US\", \"US-IL\"),\n   SOUTH_CENTRAL_US(\"South Central US\", \"US-TX\"),\n   WEST_CENTRAL_US(\"West Central US\", \"US-WY\"),\n   WEST_US(\"West US\", \"US-CA\"),\n   WEST_US_2(\"West US 2\", \"US-WA\"),\n   NORTH_EUROPE(\"North Europe\", \"IE\"),\n   UK_SOUTH(\"UK South\", \"GB-LND\"),\n   UK_WEST(\"UK West\", \"GB-CRF\"),\n   WEST_EUROPE(\"West Europe\", \"NL\"),\n   EAST_ASIA(\"East Asia\", \"HK\"),\n   SOUTH_EAST_ASIA(\"Southeast Asia\", \"SG\"),\n   KOREA_CENTRAL(\"Korea Central\", \"KR-11\"),\n   KOREA_SOUTH(\"Korea South\", \"KR-26\"),\n   JAPAN_EAST(\"Japan East\", \"JP-11\"),\n   JAPAN_WEST(\"Japan West\", \"JP-27\"),\n   BRAZIL_SOUTH(\"Brazil South\", \"BR\"),\n   AUSTRALIA_EAST(\"Australia East\", \"AU-NSW\"),\n   AUSTRALIA_SOUTH_EAST(\"Australia Southeast\", \"AU-VIC\"),\n   AUSTRALIA_CENTRAL(\"Australia Central\", \"AU-ACT\"), \n   AUSTRALIA_CENTRAL_2(\"Australia Central 2\", \"AU-ACT\"),\n   CENTRAL_INDIA(\"Central India\", \"IN-GA\"),\n   SOUTH_INDIA(\"South India\", \"IN-TN\"),\n   WEST_INDIA(\"West India\", \"IN-MH\"),\n   CHINA_EAST(\"China East\", \"CN-SH\"),\n   CHINA_EAST_2(\"China East 2\", \"CN-SH\"),\n   CHINA_NORTH(\"China North\", \"CN-BJ\"),\n   CHINA_NORTH_2(\"China North 2\", \"CN-BJ\"),\n   CANADA_CENTRAL(\"Canada Central\", \"CA-ON\"),\n   CANADA_EAST(\"Canada East\", \"CA-QC\"),\n   FRANCE_CENTRAL(\"France Central\", \"FR-IDF\"), \n   FRANCE_SOUTH(\"France South\", \"FR-PAC\"),\n   SOUTH_AFRICA_NORTH(\"South Africa North\", \"ZA-GT\"),\n   SOUTH_AFRICA_WEST(\"South Africa West\", \"ZA-WC\"),\n   UAE_NORTH(\"UAE North\", \"AE-DU\");\n\n   private final String name;\n\n   private final String iso3166Code;\n\n   Region(final String name, final String iso3166Code) {\n      this.name = name;\n      this.iso3166Code = iso3166Code;\n   }\n\n   public String getName() {\n      return name;\n   }\n\n   public String iso3166Code() {\n      return iso3166Code;\n   }\n\n   public static Region byName(final String name) {\n      Preconditions.checkNotNull(name);\n\n      for (Region region : values()) {\n         if (name.equals(region.name)) {\n            return region;\n         }\n      }\n      return null;\n   }\n\n   public static Set<String> iso3166Codes() {\n      return ImmutableSet.copyOf(Iterables.transform(Arrays.asList(values()), new Function<Region, String>() {\n\n         @Override\n         public String apply(final Region region) {\n            return region.iso3166Code;\n         }\n      }));\n   }\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/Resource.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport java.util.Map;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableMap;\n\n@AutoValue\npublic abstract class Resource {\n\n   @AutoValue\n   public abstract static class Identity {\n\n      public abstract String principalId();\n      public abstract String tenantId();\n      public abstract String type();\n\n      @SerializedNames({\"principalId\", \"tenantId\", \"type\" })\n      public static Identity create(String principalId, String tenantId, String type) {\n         return new AutoValue_Resource_Identity(principalId, tenantId, type);\n      }\n   }\n   \n   @AutoValue\n   public abstract static class ResourceProperties{\n      @Nullable\n      public abstract String provisioningState();\n\n      @SerializedNames({\"provisioningState\"})\n      public static ResourceProperties create(final String provisioningState) {\n         return new AutoValue_Resource_ResourceProperties(provisioningState);\n      }\n   }\n\n   public abstract String id();\n   public abstract String name();\n   public abstract String type();\n   public abstract String location();\n   @Nullable public abstract Map<String, String> tags();\n   @Nullable public abstract Identity identity();\n   @Nullable public abstract SKU sku();\n   @Nullable public abstract String managedBy();\n   @Nullable public abstract String kind();\n   @Nullable public abstract Plan plan();\n   @Nullable public abstract ResourceProperties properties();\n\n   @SerializedNames({\"id\", \"name\", \"type\", \"location\", \"tags\", \"identity\", \"sku\", \"managedBy\", \"kind\", \"plan\", \"properties\"})\n   public static Resource create(String id, String name, String type, String location, Map<String, String> tags, \n                                 Identity identity, SKU sku, String managedBy, String kind, Plan plan, ResourceProperties properties) {\n      return new AutoValue_Resource(id, name, type, location, tags == null ? null : ImmutableMap.copyOf(tags), \n              identity, sku, managedBy, kind, plan, properties);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/ResourceDefinition.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport java.util.List;\nimport java.util.Map;\n\n@AutoValue\npublic abstract class ResourceDefinition {\n\n    public abstract String name();\n\n    public abstract String type();\n\n    public abstract String location();\n\n    public abstract String apiVersion();\n\n    @Nullable\n    public abstract List<String> dependsOn();\n\n    @Nullable\n    public abstract Map<String, String> tags();\n\n    @Nullable\n    public abstract Object properties();\n\n    @SerializedNames({\"name\", \"type\", \"location\", \"apiVersion\", \"dependsOn\", \"tags\", \"properties\"})\n    public static ResourceDefinition create(final String name,\n                                            final String type,\n                                            final String location,\n                                            final String apiVersion,\n                                            final List<String> dependsOn,\n                                            final Map<String, String> tags,\n                                            final Object properties) {\n        ResourceDefinition.Builder builder = ResourceDefinition.builder()\n                .name(name)\n                .type(type)\n                .location(location)\n                .apiVersion(apiVersion)\n                .properties(properties);\n\n        builder.dependsOn(dependsOn == null ? null : ImmutableList.copyOf(dependsOn));\n\n        builder.tags(tags == null ? null : ImmutableMap.copyOf(tags));\n\n        return  builder.build();\n    }\n    \n    public abstract Builder toBuilder();\n\n    public static Builder builder() {\n        return new AutoValue_ResourceDefinition.Builder();\n    }\n\n    @AutoValue.Builder\n    public abstract static class Builder {\n        public abstract Builder name(String name);\n\n        public abstract Builder type(String type);\n\n        public abstract Builder location(String location);\n\n        public abstract Builder apiVersion(String apiVersion);\n\n        public abstract Builder dependsOn(List<String> dependencies);\n\n        public abstract Builder tags(Map<String, String> tags);\n\n        public abstract Builder properties(Object properties);\n\n        abstract List<String>  dependsOn();\n        abstract Map<String, String>  tags();\n\n        abstract ResourceDefinition autoBuild();\n\n        public ResourceDefinition build() {\n            dependsOn(dependsOn() != null ? ImmutableList.copyOf(dependsOn()) : null);\n            tags(tags() != null ? ImmutableMap.copyOf(tags()) : null);\n            return autoBuild();\n        }\n    }\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/ResourceGroup.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\nimport java.util.Map;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\nimport com.google.common.collect.ImmutableMap;\n\n\n@AutoValue\npublic abstract class ResourceGroup {\n\n   @AutoValue\n   public abstract static class ResourceGroupProperties implements Provisionable {\n      @Nullable\n      public abstract String provisioningState();\n\n      @SerializedNames({\"provisioningState\"})\n      public static ResourceGroupProperties create(final String provisioningState) {\n         return new AutoValue_ResourceGroup_ResourceGroupProperties(provisioningState);\n      }\n   }\n\n   public abstract String id();\n   public abstract String name();\n   public abstract String location();\n\n   @Nullable\n   public abstract Map<String, String> tags();\n   public abstract ResourceGroupProperties properties();\n\n   @SerializedNames({\"id\", \"name\", \"location\", \"tags\", \"properties\"})\n   public static ResourceGroup create(String id, String name, String location, Map<String, String> tags, ResourceGroupProperties properties) {\n      return new AutoValue_ResourceGroup(id, name, location, tags == null ? null : ImmutableMap.copyOf(tags), properties);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/ResourceProviderMetaData.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\n\nimport org.jclouds.json.SerializedNames;\n\nimport java.util.List;\n\n@AutoValue\npublic abstract class ResourceProviderMetaData {\n\n   public abstract String resourceType();\n\n   public abstract List<String> locations();\n\n   public abstract List<String> apiVersions();\n\n   @SerializedNames({\"resourceType\", \"locations\", \"apiVersions\"})\n   public static ResourceProviderMetaData create(final String resourceType, final List<String> locations, final List<String> apiVersions) {\n      ResourceProviderMetaData.Builder builder = ResourceProviderMetaData.builder()\n              .resourceType(resourceType)\n              .locations(locations == null ? ImmutableList.<String>of() : ImmutableList.copyOf(locations))\n              .apiVersions(apiVersions == null ? ImmutableList.<String>of() : ImmutableList.copyOf(apiVersions));\n\n      return builder.build();\n   }\n   \n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_ResourceProviderMetaData.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder resourceType(String resourceType);\n\n      public abstract Builder locations(List<String> locations);\n\n      public abstract Builder apiVersions(List<String> apiVersions);\n\n      abstract List<String> locations();\n\n      abstract List<String> apiVersions();\n\n      abstract ResourceProviderMetaData autoBuild();\n\n      public ResourceProviderMetaData build() {\n         locations(locations() != null ? ImmutableList.copyOf(locations()) : ImmutableList.<String>of());\n         apiVersions(apiVersions() != null ? ImmutableList.copyOf(apiVersions()) : ImmutableList.<String>of());\n         return autoBuild();\n      }\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/SKU.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class SKU {\n   @Nullable\n   public abstract String location();\n   @Nullable\n   public abstract String name();\n   @Nullable\n   public abstract String id();\n   @Nullable\n   public abstract String family();\n   \n   @SerializedNames({\"location\", \"name\", \"id\", \"family\"})\n   public static SKU create(final String location, final String name, final String id, final String family) {\n\n      return new AutoValue_SKU(location, name, id, family);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/Secret.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.common.collect.ImmutableMap;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport java.util.Map;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class Secret {\n\n   @AutoValue\n   public abstract static class SecretAttributes {\n      @Nullable\n      public abstract Boolean enabled();\n\n      @Nullable\n      public abstract Integer created();\n\n      @Nullable\n      public abstract Integer expires();\n\n      @Nullable\n      public abstract Integer notBefore();\n\n      @Nullable\n      public abstract String recoveryLevel();\n\n      @Nullable\n      public abstract Integer updated();\n\n      @SerializedNames({\"enabled\", \"created\", \"expires\", \"notBefore\", \"recoveryLevel\", \"updated\"})\n      public static SecretAttributes create(final Boolean enabled,\n                                            final Integer created,\n                                            final Integer expires,\n                                            final Integer notBefore,\n                                            final String recoveryLevel,\n                                            final Integer updated) {\n         return new AutoValue_Secret_SecretAttributes(enabled, created, expires, notBefore, recoveryLevel, updated);\n      }\n\n      SecretAttributes() {\n      }\n   }\n\n   @AutoValue\n   public abstract static class DeletedSecretBundle {\n      @Nullable\n      public abstract SecretAttributes attributes();\n\n      @Nullable\n      public abstract String contentType();\n\n      @Nullable\n      public abstract String deletedDate();\n\n      @Nullable\n      public abstract String id();\n\n      @Nullable\n      public abstract String kid();\n\n      @Nullable\n      public abstract Boolean managed();\n\n      @Nullable\n      public abstract String recoveryId();\n\n      @Nullable\n      public abstract String scheduledPurgeDate();\n\n      @Nullable\n      public abstract Map<String, String> tags();\n\n      @Nullable\n      public abstract String value();\n\n      @SerializedNames({\"attributes\", \"contentType\", \"deletedDate\", \"id\", \"kid\", \"managed\", \"recoveryId\", \"scheduledPurgeDate\", \"tags\", \"value\"})\n      public static DeletedSecretBundle create(final SecretAttributes attributes,\n                                               final String contentType,\n                                               final String deletedDate,\n                                               final String id,\n                                               final String kid,\n                                               final Boolean managed,\n                                               final String recoveryId,\n                                               final String scheduledPurgeDate,\n                                               final Map<String, String> tags,\n                                               String value) {\n         return new AutoValue_Secret_DeletedSecretBundle(\n                 attributes, contentType, deletedDate,\n                 id, kid, managed, recoveryId, scheduledPurgeDate,\n                 tags != null ? ImmutableMap.copyOf(tags) : null,\n                 value);\n      }\n   }\n\n   @AutoValue\n   public abstract static class SecretBundle {\n      @Nullable\n      public abstract SecretAttributes attributes();\n\n      @Nullable\n      public abstract String contentType();\n\n      @Nullable\n      public abstract String id();\n\n      @Nullable\n      public abstract String kid();\n\n      @Nullable\n      public abstract Boolean managed();\n\n      @Nullable\n      public abstract Map<String, String> tags();\n\n      @Nullable\n      public abstract String value();\n\n      @SerializedNames({\"attributes\", \"contentType\", \"id\", \"kid\", \"managed\", \"tags\", \"value\"})\n      public static SecretBundle create(final SecretAttributes attributes,\n                                        final String contentType,\n                                        final String id,\n                                        final String kid,\n                                        final Boolean managed,\n                                        final Map<String, String> tags,\n                                        String value) {\n         return new AutoValue_Secret_SecretBundle(\n                 attributes, contentType, id,\n                 kid, managed,\n                 tags != null ? ImmutableMap.copyOf(tags) : null,\n                 value);\n      }\n   }\n\n   @Nullable\n   public abstract SecretAttributes attributes();\n\n   @Nullable\n   public abstract String contentType();\n\n   @Nullable\n   public abstract String id();\n\n   @Nullable\n   public abstract Boolean managed();\n\n   @Nullable\n   public abstract Map<String, String> tags();\n\n   @SerializedNames({\"attributes\", \"contentType\", \"id\", \"managed\", \"tags\"})\n   public static Secret create(final SecretAttributes attributes,\n                               final String contentType,\n                               final String id,\n                               final Boolean managed,\n                               final Map<String, String> tags) {\n      return new AutoValue_Secret(\n              attributes,\n              contentType,\n              id,\n              managed,\n              tags != null ? ImmutableMap.copyOf(tags) : null\n      );\n   }\n\n   Secret() {\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/Secrets.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\nimport org.jclouds.json.SerializedNames;\nimport java.util.List;\n\n/**\n * Group of certificates stored in one and the same KeyVault\n */\n@AutoValue\npublic abstract class Secrets {\n\n    @AutoValue\n    public abstract static class SourceVault {\n\n        public abstract String id();\n\n        @SerializedNames({\"id\"})\n        public static SourceVault create(final String id) {\n            return new AutoValue_Secrets_SourceVault(id);\n        }\n    }\n\n    /**\n     * Name of the KeyVault which contains all the certificates\n     */\n    public abstract SourceVault sourceVault();\n\n    /**\n     * List of the certificates\n     */\n    public abstract List<VaultCertificate> vaultCertificates();\n\n    @SerializedNames({\"sourceVault\", \"vaultCertificates\"})\n    public static Secrets create(final SourceVault sourceVault, final List<VaultCertificate> vaultCertificates) {\n       return new AutoValue_Secrets(sourceVault, vaultCertificates);\n    }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/ServicePrincipal.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport java.util.Date;\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\n\n@AutoValue\npublic abstract class ServicePrincipal {\n   \n   @Nullable public abstract String appId();\n   @Nullable public abstract Date deletionTimestamp();\n   @Nullable public abstract String displayName();\n   public abstract String objectId();\n   public abstract String objectType();\n   public abstract List<String> servicePrincipalNames();\n\n   @SerializedNames({ \"appId\", \"deletionTimestamp\", \"displayName\", \"objectId\", \"objectType\", \"servicePrincipalNames\" })\n   public static ServicePrincipal create(String appId, Date deletionTimestamp, String displayName, String objectId,\n         String objectType, List<String> servicePrincipalNames) {\n      List<String> servicePrincipals = servicePrincipalNames != null ? ImmutableList.copyOf(servicePrincipalNames)\n            : ImmutableList.<String> of();\n      return builder().appId(appId).deletionTimestamp(deletionTimestamp).displayName(displayName).objectId(objectId)\n            .objectType(objectType).servicePrincipalNames(servicePrincipals).build();\n   }\n\n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_ServicePrincipal.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      \n      public abstract Builder appId(String appId);\n      public abstract Builder deletionTimestamp(Date deletionTimestamp);\n      public abstract Builder displayName(String displayName);\n      public abstract Builder objectId(String objectId);\n      public abstract Builder objectType(String objectType);\n      public abstract Builder servicePrincipalNames(List<String> servicePrincipalNames);\n\n      public abstract ServicePrincipal build();\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/Status.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport java.util.Date;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class Status {\n\n   @Nullable\n   public abstract String code();\n\n   @Nullable\n   public abstract String level();\n\n   @Nullable\n   public abstract String displayStatus();\n\n   @Nullable\n   public abstract String message();\n\n   @Nullable\n   public abstract Date time();\n\n   @SerializedNames({ \"code\", \"level\", \"displayStatus\", \"message\", \"time\" })\n   public static Status create(final String code, final String level, final String displayStatus, final String message,\n         final Date time) {\n      return new AutoValue_Status(code, level, displayStatus, message, time);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/StorageAccountType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\npublic enum StorageAccountType {\n   /** Enum value Standard HDD. */\n   STANDARD_LRS(\"Standard_LRS\"),\n\n   /** Enum value Standard SSD. */\n   STANDARD_SSD_LRS(\"StandardSSD_LRS\"),\n\n   /** Enum value Premium SSD. */\n   PREMIUM_LRS(\"Premium_LRS\"),\n\n   /** Enum value Ultra SSD (Available only if your subscription is enabled for ultra disks). */\n   ULTRA_SSD_LRS(\"UltraSSD_LRS\");\n\n   /** The actual serialized value for a StorageAccountTypes instance. */\n   private String value;\n\n   StorageAccountType(String value) {\n      this.value = value;\n   }\n\n   public static StorageAccountType fromString(String value) {\n      StorageAccountType[] items = StorageAccountType.values();\n      for (StorageAccountType item : items) {\n         if (item.toString().equalsIgnoreCase(value)) {\n            return item;\n         }\n      }\n      return null;\n   }\n\n   @Override\n   public String toString() {\n      return this.value;\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/StorageProfile.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport java.util.List;\n\n@AutoValue\npublic abstract class StorageProfile {\n\n   /**\n    * The image reference of the storage profile\n    */\n   @Nullable\n   public abstract ImageReference imageReference();\n\n   /**\n    * The image reference of the storage profile\n    */\n   public abstract OSDisk osDisk();\n\n   /**\n    * The list of the data disks of the storage profile\n    */\n   @Nullable\n   public abstract List<DataDisk> dataDisks();\n\n   @SerializedNames({\"imageReference\", \"osDisk\", \"dataDisks\"})\n   public static StorageProfile create(final ImageReference imageReference,\n                                       final OSDisk osDisk, final List<DataDisk> dataDisks) {\n      StorageProfile.Builder builder = StorageProfile.builder()\n              .imageReference(imageReference)\n              .osDisk(osDisk)\n              .dataDisks(dataDisks != null ? ImmutableList.copyOf(dataDisks) : null);\n\n      return builder.build();\n   }\n   \n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_StorageProfile.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder imageReference(ImageReference imageReference);\n\n      public abstract Builder osDisk(OSDisk osDisk);\n\n      public abstract Builder dataDisks(List<DataDisk> dataDisks);\n\n      abstract List<DataDisk> dataDisks();\n\n      abstract StorageProfile autoBuild();\n\n      public StorageProfile build() {\n         dataDisks(dataDisks() != null ? ImmutableList.copyOf(dataDisks()) : null);\n         return autoBuild();\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/StorageService.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\nimport java.util.Date;\nimport java.util.Map;\nimport com.google.common.collect.ImmutableMap;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\nimport org.jclouds.azurecompute.arm.util.GetEnumValue;\n\n@AutoValue\npublic abstract class StorageService {\n\n   public enum AccountType {\n\n      Standard_LRS,\n      Standard_ZRS,\n      Standard_GRS,\n      Standard_RAGRS,\n      Premium_LRS,\n      UNRECOGNIZED;\n\n       public static AccountType fromValue(final String text) {\n           return (AccountType) GetEnumValue.fromValueOrDefault(text, AccountType.UNRECOGNIZED);\n       }\n   }\n\n   public enum RegionStatus {\n\n       Available,\n       Unavailable,\n       UNRECOGNIZED;\n\n       public static RegionStatus fromValue(final String text) {\n           return (RegionStatus) GetEnumValue.fromValueOrDefault(text, RegionStatus.UNRECOGNIZED);\n       }\n\n   }\n\n   public enum Status {\n\n       Creating,\n       Created,\n       Deleting,\n       Deleted,\n       Changing,\n       ResolvingDns,\n       Succeeded,\n       UNRECOGNIZED;\n\n       public static Status fromValue(final String text) {\n           return (Status) GetEnumValue.fromValueOrDefault(text, Status.UNRECOGNIZED);\n       }\n   }\n\n   @AutoValue\n   public abstract static class StorageServiceProperties {\n\n       /**\n        * Specifies whether the account supports locally-redundant storage, geo-redundant storage, zone-redundant\n        * storage, or read access geo-redundant storage.\n        */\n       public abstract AccountType accountType();\n\n       /**\n        * Specifies the time that the storage account was created.\n        */\n       @Nullable\n       public abstract Date creationTime();\n\n       /**\n        * Specifies the endpoints of the storage account.\n        */\n       @Nullable\n       public abstract Map<String, String> primaryEndpoints();\n\n       /**\n       * A primaryLocation for the storage account.\n       */\n      @Nullable\n      public abstract String primaryLocation();\n\n      /**\n       * provisioningState for the storage group\n       */\n      @Nullable\n      public abstract Status provisioningState();\n\n       /**\n        * Specifies the secondary endpoints of the storage account.\n        */\n       @Nullable\n       public abstract Map<String, String> secondaryEndpoints();\n\n      /**\n       * Secondary location for the storage group\n       */\n      @Nullable\n      public abstract String secondaryLocation();\n\n      /**\n       * The status of primary endpoints\n       */\n      @Nullable\n      public abstract RegionStatus statusOfPrimary();\n\n      /**\n       * The secondary status of the storage account.\n       */\n      @Nullable\n      public abstract RegionStatus statusOfSecondary();\n\n\n      @SerializedNames({\"accountType\", \"creationTime\", \"primaryEndpoints\",  \"primaryLocation\",\n              \"provisioningState\", \"secondaryEndpoints\", \"secondaryLocation\", \"statusOfPrimary\", \"statusOfSecondary\"})\n      public static StorageServiceProperties create(final AccountType accountType, final Date creationTime,\n              final Map<String, String> primaryEndpoints, final String primaryLocation, final Status provisioningState,\n              final Map<String, String> secondaryEndpoints, final String secondaryLocation,\n              final RegionStatus statusOfPrimary, final RegionStatus statusOfSecondary) {\n\n         StorageServiceProperties.Builder builder = StorageServiceProperties.builder()\n                 .accountType(accountType)\n                 .creationTime(creationTime)\n                 .primaryLocation(primaryLocation)\n                 .provisioningState(provisioningState)\n                 .secondaryLocation(secondaryLocation)\n                 .statusOfPrimary(statusOfPrimary)\n                 .statusOfSecondary(statusOfSecondary);\n\n\n         builder.primaryEndpoints(primaryEndpoints != null ? ImmutableMap.copyOf(primaryEndpoints) : null);\n         builder.secondaryEndpoints(secondaryEndpoints != null ? ImmutableMap.copyOf(secondaryEndpoints) : null);\n\n         return  builder.build();\n      }\n      \n      public abstract Builder toBuilder();\n      \n      public static Builder builder() {\n         return new AutoValue_StorageService_StorageServiceProperties.Builder();\n      }\n\n      @AutoValue.Builder\n      public abstract static class Builder {\n         public abstract Builder accountType(AccountType accountType);\n         public abstract Builder creationTime(Date creationTime);\n         public abstract Builder primaryEndpoints(Map<String, String> primaryEndpoints);\n         public abstract Builder primaryLocation(String primaryLocation);\n         public abstract Builder provisioningState(Status provisioningState);\n         public abstract Builder secondaryEndpoints(Map<String, String> secondaryEndpoints);\n         public abstract Builder secondaryLocation(String secondaryLocation);\n         public abstract Builder statusOfPrimary(RegionStatus statusOfPrimary);\n         public abstract Builder statusOfSecondary(RegionStatus statusOfSecondary);\n\n         abstract Map<String, String>  primaryEndpoints();\n         abstract Map<String, String>  secondaryEndpoints();\n\n         abstract StorageServiceProperties autoBuild();\n\n         public StorageServiceProperties build() {\n            primaryEndpoints(primaryEndpoints() != null ? ImmutableMap.copyOf(primaryEndpoints()) : null);\n            secondaryEndpoints(secondaryEndpoints() != null ? ImmutableMap.copyOf(secondaryEndpoints()) : null);\n            return autoBuild();\n         }\n      }\n   }\n\n   /**\n    * Specifies the id of the storage account.\n    */\n   @Nullable\n   public abstract String id();\n\n   /**\n    * Specifies the name of the storage account. This name is the DNS prefix name and can be used to access blobs,\n    * queues, and tables in the storage account.\n    */\n   @Nullable\n   public abstract String name();\n\n   /**\n    * Specifies the location of the storage account.\n    */\n   public abstract String location();\n\n   /**\n    * Specifies the tags of the storage account.\n    */\n   @Nullable\n   public abstract Map<String, String> tags();\n\n   /**\n    * Specifies the type of the storage account.\n    */\n   @Nullable\n   public abstract String type();\n\n   /**\n    * Specifies the properties of the storage account.\n    */\n   public abstract StorageServiceProperties storageServiceProperties();\n\n\n   @SerializedNames({\"id\", \"name\", \"location\", \"tags\", \"type\", \"properties\"})\n   public static StorageService create(final String id,  final String name,  final String location,\n                                       final Map<String, String> tags,  final String type,\n                                       final StorageServiceProperties storageServiceProperties) {\n      return new AutoValue_StorageService(id,  name,  location,  tags == null ? null : ImmutableMap.copyOf(tags), type, storageServiceProperties);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/StorageServiceKeys.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\nimport org.jclouds.json.SerializedNames;\n\n@AutoValue\npublic abstract class StorageServiceKeys {\n\n   /**\n    * The primary access key for the storage account.\n    */\n   public abstract String key1();\n\n   /**\n    * The secondary access key for the storage account.\n    */\n   public abstract String key2();\n\n   @SerializedNames({\"key1\", \"key2\"})\n   public static StorageServiceKeys create(final String key1, final String key2) {\n      return new AutoValue_StorageServiceKeys(key1, key2);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/StorageServiceUpdateParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableMap;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\nimport java.util.Map;\n\n@AutoValue\npublic abstract class StorageServiceUpdateParams {\n\n   @AutoValue\n   public abstract static class StorageServiceUpdateProperties {\n\n       /**\n        * Specifies whether the account supports locally-redundant storage, geo-redundant storage, zone-redundant\n        * storage, or read access geo-redundant storage.\n        * Note: This implementation is for version 2015-10-01 and earlier.\n        * For version 2016-01-01 or later, refer to https://msdn.microsoft.com/en-us/library/mt163639.aspx\n        */\n       @Nullable\n       public abstract StorageService.AccountType accountType();\n\n\n      @SerializedNames({\"accountType\"})\n      public static StorageServiceUpdateProperties create(final StorageService.AccountType accountType) {\n\n         return new AutoValue_StorageServiceUpdateParams_StorageServiceUpdateProperties(accountType);\n      }\n   }\n\n   /**\n    * Specifies the tags of the storage account.\n    */\n   @Nullable\n   public abstract Map<String, String> tags();\n\n   /**\n    * Specifies the properties of the storage account.\n    */\n   public abstract StorageServiceUpdateProperties storageServiceProperties();\n\n\n   @SerializedNames({\"tags\", \"properties\"})\n   public static StorageServiceUpdateParams create(final Map<String, String> tags,\n                                                   final StorageServiceUpdateProperties storageServiceProperties) {\n      return new AutoValue_StorageServiceUpdateParams(tags == null ? null : ImmutableMap.copyOf(tags), storageServiceProperties);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/Subnet.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport static com.google.common.collect.ImmutableList.copyOf;\n\nimport java.util.List;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport com.google.common.collect.ImmutableList;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport com.google.auto.value.AutoValue;\nimport org.jclouds.json.SerializedNames;\n\n@AutoValue\npublic abstract class Subnet {\n\n   // To create VPN endpoints, a \"GatewaySubnet\" is required. Azure identifies\n   // such networks by name, and they have to be named exactly \"GatewaySubnet\".\n   public static final String GATEWAY_SUBNET_NAME = \"GatewaySubnet\";\n   \n   private static final Pattern NETWORK_PATTERN = Pattern.compile(\"^.*/virtualNetworks/([^/]+)(/.*)?$\");\n   \n   @AutoValue\n   public abstract static class IpConfiguration {\n\n      public abstract String id();\n\n      @SerializedNames({\"id\"})\n      public static IpConfiguration create(final String id) {\n         return new AutoValue_Subnet_IpConfiguration(id);\n      }\n      \n      IpConfiguration() {\n         \n      }\n   }\n\n   @AutoValue\n   public abstract static class SubnetProperties implements Provisionable {\n\n      @Nullable public abstract String provisioningState();\n      @Nullable public abstract String addressPrefix();\n      @Nullable public abstract List<IpConfiguration> ipConfigurations();\n\n      @SerializedNames({\"provisioningState\", \"addressPrefix\", \"ipConfigurations\"})\n      public static SubnetProperties create(final String provisioningState, final String addressPrefix, final List<IpConfiguration> ipConfigurations) {\n         return builder()\n                 .provisioningState(provisioningState)\n                 .addressPrefix(addressPrefix)\n                 .ipConfigurations(ipConfigurations != null ? copyOf(ipConfigurations) : null)\n                 .build();\n      }\n      \n      SubnetProperties() {\n         \n      }\n      \n      public abstract Builder toBuilder();\n\n      public static Builder builder() {\n         return new AutoValue_Subnet_SubnetProperties.Builder();\n      }\n\n      @AutoValue.Builder\n      public abstract static class Builder {\n         public abstract Builder provisioningState(String provisioningState);\n         public abstract Builder addressPrefix(String addressPrefix);\n         public abstract Builder ipConfigurations(List<IpConfiguration> ipConfigurations);\n\n         abstract List<IpConfiguration> ipConfigurations();\n         abstract SubnetProperties autoBuild();\n\n         public SubnetProperties build() {\n            ipConfigurations(ipConfigurations() != null ? ImmutableList.copyOf(ipConfigurations()) : null);\n            return autoBuild();\n         }\n      }\n   }\n\n   @Nullable public abstract String name();\n   @Nullable public abstract String id();\n   @Nullable public abstract String etag();\n   @Nullable public abstract SubnetProperties properties();\n   \n   @Nullable public String virtualNetwork() {\n      return extractVirtualNetwork(id());\n   }\n   \n   public static String extractVirtualNetwork(String id) {\n      if (id == null)\n         return null;\n      Matcher m = NETWORK_PATTERN.matcher(id);\n      m.matches();\n      return m.group(1);\n   }\n\n   @SerializedNames({\"name\", \"id\", \"etag\", \"properties\"})\n   public static Subnet create(final String name,\n                               final String id,\n                               final String etag,\n                               final SubnetProperties properties) {\n      return builder().name(name).id(id).etag(etag).properties(properties).build();\n   }\n   \n   Subnet() {\n      \n   }\n   \n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_Subnet.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder name(String name);\n      public abstract Builder id(String id);\n      public abstract Builder etag(String etag);\n      public abstract Builder properties(SubnetProperties properties);\n      \n      // Gateway subnets are identified by name\n      public Builder setGatewaySubnet() {\n         return name(GATEWAY_SUBNET_NAME);\n      }\n      \n      public abstract Subnet build();\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/TemplateParameterType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\n// Simple helper class to serialize / deserialize id reference.\n\n@AutoValue\npublic abstract class TemplateParameterType {\n   @Nullable\n   public abstract String type();\n\n   @SerializedNames({\"type\"})\n   public static TemplateParameterType create(final String type) {\n      return new AutoValue_TemplateParameterType(type);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/VHD.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\n\nimport org.jclouds.json.SerializedNames;\n\n@AutoValue\npublic abstract class VHD {\n\n   /**\n    * The uri of the vhd.\n    */\n   public abstract String uri();\n\n   @SerializedNames({\"uri\"})\n   public static VHD create(final String uri) {\n      return builder().uri(uri).build();\n   }\n   \n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_VHD.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder uri(String uri);\n\n      public abstract VHD build();\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/VMDeployment.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport java.util.List;\n\nimport org.jclouds.azurecompute.arm.domain.publicipaddress.PublicIPAddress;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class VMDeployment {\n\n   public abstract String deploymentId();\n   \n   @Nullable\n   public abstract VirtualMachine virtualMachine();\n   \n   @Nullable\n   public abstract List<PublicIPAddress> ipAddressList();\n\n   @Nullable\n   public abstract List<NetworkInterfaceCard> networkInterfaceCards();\n\n   public static VMDeployment create(String deploymentId, VirtualMachine virtualMachine,\n                                     List<PublicIPAddress> ipAddressList,\n                                     List<NetworkInterfaceCard> networkInterfaceCards) {\n      return new AutoValue_VMDeployment(deploymentId, virtualMachine, ipAddressList, networkInterfaceCards);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/VMHardware.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\nimport org.jclouds.json.SerializedNames;\n\n/**\n * A VM Size that is available in a region for a given subscription.\n *\n * @see <a href=\"https://msdn.microsoft.com/en-us/library/azure/mt269440.aspx\" >api</a>\n */\n@AutoValue\npublic abstract class VMHardware {\n\n   /**\n    * The name of the VM size.\n    */\n   public abstract String name();\n\n   /**\n    * The number of cores that are available in the VM size.\n    */\n   public abstract Integer numberOfCores();\n\n   /**\n    * Specifies the size in MB of the OS Disk.\n    */\n   public abstract Integer osDiskSizeInMB();\n\n   /**\n    * The size of the resource disk.\n    */\n   public abstract Integer resourceDiskSizeInMB();\n\n   /**\n    * Specifies the available RAM in MB.\n    */\n   public abstract Integer memoryInMB();\n\n   /**\n    * Specifies the maximum number of data disks that can be attached to the VM size.\n    */\n   public abstract Integer maxDataDiskCount();\n\n   /**\n    * Specifies the location of the HW resource\n    */\n   public abstract String location();\n\n   @SerializedNames({ \"name\", \"numberOfCores\", \"osDiskSizeInMB\", \"resourceDiskSizeInMB\", \"memoryInMB\", \"maxDataDiskCount\", \"location\"})\n   public static VMHardware create(String name, Integer numberOfCores, Integer osDiskSizeInMB, Integer resourceDiskSizeInMB, Integer memoryInMB, Integer maxDataDiskCount, String location) {\n\n      return new AutoValue_VMHardware(name, numberOfCores, osDiskSizeInMB, resourceDiskSizeInMB, memoryInMB, maxDataDiskCount, location);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/VMImage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.azurecompute.arm.util.VMImages.isCustom;\n\nimport org.jclouds.azurecompute.arm.domain.Version.VersionProperties;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class VMImage {\n   /**\n    * The publisher of the image reference.\n    */\n   @Nullable\n   public abstract String publisher();\n\n   /**\n    * The offer of the image reference.\n    */\n   @Nullable\n   public abstract String offer();\n\n   /**\n    * The sku of the image reference.\n    */\n   @Nullable\n   public abstract String sku();\n\n   /**\n    * The version of the image reference.\n    */\n   @Nullable\n   public abstract String version();\n\n   /**\n    * The location from where Image was fetched\n    */\n   @Nullable\n   public abstract String location();\n\n   /**\n    * The group of the custom image\n    */\n   @Nullable\n   public abstract String group();\n\n   /**\n    * The storage of the custom image.\n    */\n   @Nullable\n   public abstract String storage();\n\n   /**\n    * The vhd1 of the custom image\n    */\n   @Nullable\n   public abstract String vhd1();\n\n   /**\n    * The vhd2 of the custom image.\n    */\n   @Nullable\n   public abstract String vhd2();\n\n   /**\n    * The name of the custom image template.\n    */\n   @Nullable\n   public abstract String name();\n   \n   /**\n    * True if custom image\n    */\n   public abstract boolean custom();\n\n   /**\n    * The id of the custom image template.\n    */\n   @Nullable\n   public abstract String customImageId();\n   \n   /**\n    * The resource group for the image in case of custom images.\n    * @return\n    */\n   @Nullable\n   public abstract String resourceGroup();\n\n   /**\n    * Extended version properties.\n    */\n   @Nullable\n   public abstract VersionProperties versionProperties();\n   \n   private static Builder builder() {\n      return new AutoValue_VMImage.Builder();\n   }\n   \n   public static Builder azureImage() {\n      return builder().custom(false);\n   }\n   \n   public static Builder customImage() {\n      return builder().custom(true);\n   }\n   \n   VMImage() {\n      \n   }\n   \n   public abstract Builder toBuilder();\n   \n   @AutoValue.Builder\n   public abstract static class Builder {\n\n      public abstract Builder customImageId(String id);\n      public abstract Builder resourceGroup(String resourceGroup);\n      public abstract Builder publisher(String published);\n      public abstract Builder offer(String offer);\n      public abstract Builder sku(String sku);\n      public abstract Builder version(String version);\n      public abstract Builder location(String location);\n      public abstract Builder group(String group);\n      public abstract Builder storage(String storage);\n      public abstract Builder vhd1(String vhd1);\n      public abstract Builder vhd2(String vhd2);\n      public abstract Builder name(String name);\n      public abstract Builder custom(boolean custom);\n      public abstract Builder versionProperties(VersionProperties versionProperties);\n      \n      public abstract VMImage build();\n   }\n\n   public String encodeFieldsToUniqueId() {\n      return String.format(\"%s/%s/%s/%s\", location(), publisher(), offer(), sku());\n   }\n\n   public String encodeFieldsToUniqueIdCustom() {\n      return String.format(\"%s/%s/%s\", resourceGroup(), location(), name());\n   }\n\n   public static VMImage decodeFieldsFromUniqueId(final String id) {\n      VMImage vmImage;\n      String[] fields = checkNotNull(id, \"id\").split(\"/\");\n      if (isCustom(id)) {\n         /* id fields indexes\n         0: imageReference.resourceGroup\n         1: imageReference.location + \"/\" +\n         2: imageReference.name\n         */\n         vmImage = VMImage.customImage().resourceGroup(fields[0]).location(fields[1]).name(fields[2]).build();\n      } else {\n         /* id fields indexes\n         0: imageReference.location + \"/\" +\n         1: imageReference.publisher + \"/\" +\n         2: imageReference.offer + \"/\" +\n         3: imageReference.sku + \"/\" +\n         */\n         vmImage = VMImage.azureImage().location(fields[0]).publisher(fields[1]).offer(fields[2]).sku(fields[3])\n               .build();\n      }\n      return vmImage;\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/VMSize.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\nimport org.jclouds.json.SerializedNames;\n\n/**\n * A VM Size that is available in a region for a given subscription.\n *\n * @see <a href=\"https://msdn.microsoft.com/en-us/library/azure/mt269440.aspx\" >api</a>\n */\n@AutoValue\npublic abstract class VMSize {\n\n   /**\n    * The name of the VM size.\n    */\n   public abstract String name();\n\n   /**\n    * The number of cores that are available in the VM size.\n    */\n   public abstract Integer numberOfCores();\n\n   /**\n    * Specifies the size in MB of the OS Disk.\n    */\n   public abstract Integer osDiskSizeInMB();\n\n   /**\n    * The size of the resource disk.\n    */\n   public abstract Integer resourceDiskSizeInMB();\n\n   /**\n    * Specifies the available RAM in MB.\n    */\n   public abstract Integer memoryInMB();\n\n   /**\n    * Specifies the maximum number of data disks that can be attached to the VM size.\n    */\n   public abstract Integer maxDataDiskCount();\n\n   @SerializedNames({ \"name\", \"numberOfCores\", \"osDiskSizeInMB\", \"resourceDiskSizeInMB\", \"memoryInMB\", \"maxDataDiskCount\"})\n   public static VMSize create(final String name, final Integer numberOfCores, final Integer osDiskSizeInMB,\n           final Integer resourceDiskSizeInMB, final Integer memoryInMB, final Integer maxDataDiskCount) {\n\n      return new AutoValue_VMSize(name, numberOfCores, osDiskSizeInMB, resourceDiskSizeInMB, memoryInMB, maxDataDiskCount);\n   }\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/Value.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class Value {\n\n   /**\n    * The type of the Value\n    */\n   public abstract String type();\n\n   /**\n    * The name of the Value\n    */\n   public abstract @Nullable String value();\n\n   @SerializedNames({\"type\", \"value\"})\n   public static Value create(final String type, @Nullable final String value) {\n\n      return new AutoValue_Value(type, value);\n   }\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/Vault.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport java.util.Date;\nimport java.util.Map;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableMap;\n\n@AutoValue\npublic abstract class Vault {\n\n   @AutoValue\n   public abstract static class DeletedVault {\n      @Nullable public abstract String id();\n      @Nullable public abstract String name();\n      @Nullable public abstract String type();\n      @Nullable public abstract DeletedVaultProperties properties();\n\n      @SerializedNames({\"id\", \"name\", \"type\", \"properties\"})\n      public static DeletedVault create(final String id, final String name,\n                                        final String type, final DeletedVaultProperties properties) {\n         return new AutoValue_Vault_DeletedVault(id, name, type, properties);\n      }\n   }\n\n   @AutoValue\n   public abstract static class DeletedVaultProperties {\n      @Nullable public abstract Date deletionDate();\n      @Nullable public abstract String location();\n      @Nullable public abstract Date scheduledPurgeDate();\n      @Nullable public abstract Map<String, String> tags();\n      @Nullable public abstract String vaultId();\n\n      @SerializedNames({\"deletionDate\", \"location\", \"scheduledPurgeDate\", \"tags\", \"vaultId\"})\n      public static DeletedVaultProperties create (final Date deletionDate, final String location,\n                                           final Date scheduledPurgeDate, final Map<String, String> tags,\n                                           final String vaultId) {\n         return new AutoValue_Vault_DeletedVaultProperties(\n                 deletionDate,\n                 location,\n                 scheduledPurgeDate,\n                 tags != null ? ImmutableMap.copyOf(tags) : null,\n                 vaultId\n         );\n      }\n   }\n\n   @Nullable public abstract String id();\n   @Nullable public abstract String type();\n   public abstract String location();\n   @Nullable public abstract Map<String, String> tags();\n   @Nullable public abstract String name();\n   public abstract VaultProperties properties();\n\n   @SerializedNames({\"id\", \"name\", \"type\", \"location\", \"properties\", \"tags\"})\n   public static Vault create(final String id, final String name, final String type,\n                              final String location,\n                              final VaultProperties properties, final Map<String, String> tags) {\n      return builder()\n              .id(id)\n              .name(name)\n              .type(type)\n              .location(location)\n              .properties(properties)\n              .tags(tags != null ? ImmutableMap.copyOf(tags) : null)\n              .build();\n   }\n\n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_Vault.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder id(String id);\n      public abstract Builder name(String name);\n      public abstract Builder type(String type);\n      public abstract Builder location(String location);\n      public abstract Builder properties(VaultProperties properties);\n      public abstract Builder tags(Map<String, String> tags);\n\n      abstract Map<String, String> tags();\n      abstract Vault autoBuild();\n\n      public Vault build() {\n         tags(tags() != null ? ImmutableMap.copyOf(tags()) : null);\n         return autoBuild();\n      }\n      \n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/VaultCertificate.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\n/**\n * Certificate stored in a Key Vault\n */\n@AutoValue\npublic abstract class VaultCertificate {\n\n    /**\n     * The URL of the certificate\n     */\n    public abstract String certificateUrl();\n\n    /**\n     * Certificate's store name\n     */\n    @Nullable\n    public abstract String certificateStore();\n\n    @SerializedNames({\"certificateUrl\", \"certificateStore\"})\n    public static VaultCertificate create(final String certificateUrl, final String certificateStore) {\n       return new AutoValue_VaultCertificate(certificateUrl, certificateStore);\n    }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/VaultProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\n\n@AutoValue\npublic abstract class VaultProperties {\n\n   @AutoValue\n   public abstract static class Permissions {\n\n      public abstract List<String> certificates();\n      public abstract List<String> keys();\n      public abstract List<String> secrets();\n      public abstract List<String> storage();\n\n      @SerializedNames({ \"certificates\", \"keys\", \"secrets\", \"storage\"})\n      public static Permissions create(final List<String> certificates, final List<String> keys, final List<String> secrets, final List<String> storage) {\n         return new AutoValue_VaultProperties_Permissions(\n                 certificates != null ? ImmutableList.copyOf(certificates) : ImmutableList.<String> of(),\n                 keys != null ? ImmutableList.copyOf(keys) : ImmutableList.<String> of(),\n                 secrets != null ? ImmutableList.copyOf(secrets) : ImmutableList.<String> of(),\n                 storage != null ? ImmutableList.copyOf(storage) : ImmutableList.<String> of()\n         );\n      }\n\n      Permissions() {\n\n      }\n   }\n   \n   @AutoValue\n   public abstract static class AccessPolicyEntry {\n\n      @Nullable public abstract String applicationId();\n      public abstract String objectId();\n      public abstract String tenantId();\n      @Nullable public abstract Permissions permissions();\n\n      @SerializedNames({\"applicationId\", \"objectId\", \"tenantId\", \"permissions\"})\n      public static AccessPolicyEntry create(final String applicationId, final String objectId, final String tenantId, final Permissions permissions) {\n         return new AutoValue_VaultProperties_AccessPolicyEntry(applicationId, objectId, tenantId, permissions);\n      }\n\n      AccessPolicyEntry() {\n\n      }\n   }\n   \n   @Nullable\n   public abstract String tenantId();\n   @Nullable\n   public abstract URI vaultUri();\n   @Nullable\n   public abstract Boolean enabledForDeployment();\n   @Nullable\n   public abstract Boolean enabledForTemplateDeployment();\n   @Nullable\n   public abstract Boolean enableSoftDelete();\n   @Nullable\n   public abstract String createMode();\n   @Nullable\n   public abstract SKU sku();\n   @Nullable\n   public abstract List<AccessPolicyEntry> accessPolicies();\n\n   @SerializedNames({\"tenantId\", \"vaultUri\", \"enabledForDeployment\", \"enabledForTemplateDeployment\", \"enableSoftDelete\", \"createMode\", \"sku\", \"accessPolicies\" })\n   public static VaultProperties create(final String tenantId, final URI vaultUri, final Boolean enabledForDeployment, final Boolean enabledForTemplateDeployment, final Boolean enableSoftDelete, final String createMode,\n                                        final SKU sku, final List<AccessPolicyEntry> accessPolicies) {\n      return builder()\n              .tenantId(tenantId)\n              .vaultUri(vaultUri)\n              .enabledForDeployment(enabledForDeployment)\n              .enabledForTemplateDeployment(enabledForTemplateDeployment)\n              .enableSoftDelete(enableSoftDelete)\n              .createMode(createMode)\n              .sku(sku)\n              .accessPolicies(accessPolicies)\n              .build();\n   }\n\n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_VaultProperties.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder tenantId(String tenantId);\n      public abstract Builder vaultUri(URI vaultUri);\n      public abstract Builder enabledForDeployment(Boolean enabledForDeployment);\n      public abstract Builder enabledForTemplateDeployment(Boolean enabledForTemplateDeployment);\n      public abstract Builder enableSoftDelete(Boolean enableSoftDelete);\n      public abstract Builder createMode(String createMode);\n      public abstract Builder sku(SKU sku);\n      public abstract Builder accessPolicies(List<AccessPolicyEntry> accessPolicies);\n      \n      abstract List<AccessPolicyEntry> accessPolicies();\n\n      abstract VaultProperties autoBuild();\n\n      public VaultProperties build() {\n         return accessPolicies(accessPolicies() != null ? ImmutableList.copyOf(accessPolicies()) : ImmutableList.<AccessPolicyEntry>of())\n                 .autoBuild();\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/Version.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n/**\n * Version\n */\n@AutoValue\npublic abstract class Version {\n\n   /**\n    * The location of the Version\n    */\n   public abstract String location();\n\n   /**\n    * The name of the Version\n    */\n   public abstract String name();\n\n   /**\n    * The id of the Version\n    */\n   public abstract String id();\n   \n   /**\n    * The plan for the Version if this image is from the marketplace.\n    */\n   @Nullable\n   public abstract VersionProperties properties();\n   \n   Version() {\n      \n   }\n\n   @SerializedNames({\"location\", \"name\", \"id\", \"properties\"})\n   public static Version create(final String location, final String name, final String id,\n         final VersionProperties properties) {\n      return new AutoValue_Version(location, name, id, properties);\n   }\n   \n   @AutoValue\n   public abstract static class VersionProperties {\n      @Nullable public abstract Plan plan();\n      public abstract OSDiskImage osDiskImage();\n      \n      VersionProperties() {\n         \n      }\n      \n      @SerializedNames({\"plan\", \"osDiskImage\"})\n      public static VersionProperties create(Plan plan, OSDiskImage osDiskImage) {\n         return new AutoValue_Version_VersionProperties(plan, osDiskImage);\n      }\n      \n      @AutoValue\n      public abstract static class OSDiskImage {\n         public abstract String operatingSystem();\n         \n         OSDiskImage() {\n            \n         }\n         \n         @SerializedNames({\"operatingSystem\"})\n         public static OSDiskImage create(String operatingSystem) {\n            return new AutoValue_Version_VersionProperties_OSDiskImage(operatingSystem);\n         }\n      }\n   }\n}\n\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/VirtualMachine.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport java.util.Map;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * A virtual machine  that is valid for your subscription.\n */\n@AutoValue\npublic abstract class VirtualMachine {\n\n   /**\n    * The id of the virtual machine.\n    */\n   public abstract String id();\n\n   /**\n    * The name of the virtual machine\n    */\n   public abstract String name();\n\n   /**\n    * The type of the virtual machine .\n    */\n   public abstract String type();\n\n   /**\n    * The localized name of the virtual machine .\n    */\n   public abstract String location();\n\n   /**\n    * Specifies the tags of the vm\n    */\n   @Nullable\n   public abstract Map<String, String> tags();\n\n   /**\n    * Specifies the properties of the vm\n    */\n   public abstract VirtualMachineProperties properties();\n\n   /**\n    * Specifies the plan, for marketplace images\n    */\n   @Nullable\n   public abstract Plan plan();\n\n   @SerializedNames({\"id\", \"name\", \"type\", \"location\", \"tags\", \"properties\", \"plan\"})\n   public static VirtualMachine create(final String id, final String name, final String type, final String location,\n                                       @Nullable final Map<String, String> tags, VirtualMachineProperties properties, @Nullable Plan plan) {\n      return builder().id(id).name(name).type(type).location(location).tags(tags).properties(properties).plan(plan)\n         .build();\n   }\n\n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_VirtualMachine.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n\n      public abstract Builder id(String id);\n      public abstract Builder name(String name);\n      public abstract Builder type(String type);\n      public abstract Builder location(String location);\n      public abstract Builder tags(Map<String, String> tags);\n      public abstract Builder properties(VirtualMachineProperties properties);\n      public abstract Builder plan(Plan plan);\n\n      abstract Map<String, String> tags();\n\n      abstract VirtualMachine autoBuild();\n\n      public VirtualMachine build() {\n         tags(tags() != null ? ImmutableMap.copyOf(tags()) : null);\n         return autoBuild();\n      }\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/VirtualMachineInstance.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.getFirst;\nimport static com.google.common.collect.Iterables.transform;\nimport static org.jclouds.util.Predicates2.startsWith;\n\nimport java.util.List;\n\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineProperties.ProvisioningState;\nimport org.jclouds.azurecompute.arm.util.GetEnumValue;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableList;\n\n/**\n * A virtual machine instance view that is valid for your subscription.\n */\n@AutoValue\npublic abstract class VirtualMachineInstance {\n\n   public static final String PROVISIONING_STATE_PREFIX = \"ProvisioningState/\";\n   public static final String POWER_STATE_PREFIX = \"PowerState/\";\n   \n   /**\n    * @see <a href=\"https://docs.microsoft.com/en-us/java/api/com.microsoft.azure.management.compute._power_state\" />\n    */\n   public enum PowerState {\n      RUNNING,\n      STARTING,\n      STOPPED,\n      STOPPING,\n      DEALLOCATED,\n      DEALLOCATING,\n      UNKNOWN;\n\n      public static PowerState fromValue(final String text) {\n         return (PowerState) GetEnumValue.fromValueOrDefault(text, PowerState.UNKNOWN);\n      }\n   }\n   \n   @Nullable\n   public abstract String platformUpdateDomain();\n\n   @Nullable\n   public abstract String platformFaultDomain();\n\n   @Nullable\n   public abstract List<Status> statuses();\n   \n   public ProvisioningState provisioningState() {\n      return ProvisioningState.fromValue(firstStatus(PROVISIONING_STATE_PREFIX));\n   }\n   \n   public PowerState powerState() {\n      return PowerState.fromValue(firstStatus(POWER_STATE_PREFIX));\n   }\n   \n   private String firstStatus(final String type) {\n      return getFirst(transform(filter(transform(statuses(), new Function<Status, String>() {\n         @Override public String apply(Status input) {\n            return input.code();\n         }\n      }), startsWith(type)), new Function<String, String>() {\n         @Override public String apply(String input) {\n            return input.substring(type.length());\n         }\n      }), null);\n   }\n\n\n   @SerializedNames({\"platformUpdateDomain\", \"platformFaultDomain\", \"statuses\"})\n   public static VirtualMachineInstance create(final String platformUpdateDomain, final String platformFaultDomain,\n                                               final List<Status> statuses) {\n\n      return new AutoValue_VirtualMachineInstance(platformUpdateDomain, platformFaultDomain, statuses == null ? null : ImmutableList.copyOf(statuses));\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/VirtualMachineProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport org.jclouds.azurecompute.arm.util.GetEnumValue;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n/**\n * A virtual machine properties for the virtual machine.\n */\n@AutoValue\npublic abstract class VirtualMachineProperties {\n\n   public enum ProvisioningState {\n      ACCEPTED,\n      CREATING,\n      READY,\n      CANCELED,\n      FAILED,\n      DELETED,\n      SUCCEEDED,\n      RUNNING,\n      UPDATING,\n      UNRECOGNIZED;\n\n      public static ProvisioningState fromValue(final String text) {\n         return (ProvisioningState) GetEnumValue.fromValueOrDefault(text, ProvisioningState.UNRECOGNIZED);\n      }\n   }\n\n   /**\n    * The id of the virtual machine.\n    */\n   @Nullable\n   public abstract String vmId();\n\n   /**\n    * The license type of the virtual machine.\n    */\n   @Nullable\n   public abstract String licenseType();\n\n   /**\n    * The availability set  of the virtual machine\n    */\n   @Nullable\n   public abstract IdReference availabilitySet();\n\n   /**\n    * The hardware Profile of the virtual machine .\n    */\n   @Nullable\n   public abstract HardwareProfile hardwareProfile();\n\n   /**\n    * The Storage Profile of the virtual machine .\n    */\n   @Nullable\n   public abstract StorageProfile storageProfile();\n\n   /**\n    * The OS Profile of the virtual machine .\n    */\n   @Nullable\n   public abstract OSProfile osProfile();\n\n   /**\n    * The network profile of the VM\n    */\n   @Nullable\n   public abstract NetworkProfile networkProfile();\n\n   /**\n    * The diagnostics profile of the VM\n    */\n   @Nullable\n   public abstract DiagnosticsProfile diagnosticsProfile();\n\n   /**\n    * The provisioning state of the VM\n    */\n   @Nullable\n   public abstract ProvisioningState provisioningState();\n\n   @SerializedNames({\"vmId\", \"licenseType\", \"availabilitySet\", \"hardwareProfile\", \"storageProfile\", \"osProfile\",\n           \"networkProfile\", \"diagnosticsProfile\", \"provisioningState\"})\n   public static VirtualMachineProperties create(final String vmId,\n                                                 final String licenseType,\n                                                 final IdReference availabilitySet,\n                                                 final HardwareProfile hardwareProfile,\n                                                 final StorageProfile storageProfile,\n                                                 final OSProfile osProfile,\n                                                 final NetworkProfile networkProfile,\n                                                 final DiagnosticsProfile diagnosticsProfile,\n                                                 final ProvisioningState provisioningState) {\n      return builder()\n              .vmId(vmId)\n              .licenseType(licenseType)\n              .availabilitySet(availabilitySet)\n              .hardwareProfile(hardwareProfile)\n              .storageProfile(storageProfile)\n              .osProfile(osProfile)\n              .networkProfile(networkProfile)\n              .diagnosticsProfile(diagnosticsProfile)\n              .provisioningState(provisioningState)\n              .build();\n   }\n   \n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_VirtualMachineProperties.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder vmId(String vmId);\n\n      public abstract Builder licenseType(String licenseType);\n\n      public abstract Builder availabilitySet(IdReference availabilitySet);\n\n      public abstract Builder hardwareProfile(HardwareProfile hardwareProfile);\n\n      public abstract Builder storageProfile(StorageProfile storageProfile);\n\n      public abstract Builder osProfile(OSProfile osProfile);\n\n      public abstract Builder networkProfile(NetworkProfile networkProfile);\n\n      public abstract Builder diagnosticsProfile(DiagnosticsProfile diagnosticsProfile);\n\n      public abstract Builder provisioningState(ProvisioningState provisioningState);\n\n      public abstract VirtualMachineProperties build();\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/VirtualMachineScaleSet.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableMap;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport java.util.Map;\n\n/**\n * VirtualMachineScaleSet for subscription\n */\n@AutoValue\npublic abstract class VirtualMachineScaleSet {\n\n   /**\n    * The id of the virtual machine scale set\n    */\n   @Nullable\n   public abstract String id();\n\n   /**\n    * The name of the virtual machine scale set\n    */\n   @Nullable\n   public abstract String name();\n\n   /**\n    * The location of the virtual machine scale set\n    */\n   @Nullable\n   public abstract String location();\n\n   /**\n    * Specifies the sku of the virtual machine scale set\n    */\n   public abstract VirtualMachineScaleSetSKU sku();\n\n   /**\n    * Specifies the tags of the virtual machine scale set\n    */\n   @Nullable\n   public abstract Map<String, String> tags();\n\n\n   /**\n    * Specifies the optional plan of the virtual machine scale set (only for market image)\n    */\n   @Nullable\n   public abstract VirtualMachineScaleSetPlan plan();\n\n   /**\n    * Specifies the properties of the availability set\n    */\n   @Nullable\n   public abstract VirtualMachineScaleSetProperties properties();\n\n   @SerializedNames({  \"id\", \"name\", \"location\", \"sku\", \"tags\", \"plan\", \"properties\"})\n   public static VirtualMachineScaleSet create(final String id, final String name, final String location,\n                                               VirtualMachineScaleSetSKU sku, final Map<String, String> tags,\n                                               VirtualMachineScaleSetPlan plan,\n                                               VirtualMachineScaleSetProperties properties) {\n      return builder().id(id).name(name).location(location).sku(sku).tags(tags)\n         .plan(plan).properties(properties)\n         .build();\n   }\n\n   public abstract Builder toBuilder();\n\n   private static Builder builder() {\n      return new AutoValue_VirtualMachineScaleSet.Builder();\n   }\n\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder id(String id);\n      public abstract Builder name(String name);\n      public abstract Builder location(String location);\n      public abstract Builder sku(VirtualMachineScaleSetSKU sku);\n      public abstract Builder tags(Map<String, String> tags);\n      public abstract Builder plan(VirtualMachineScaleSetPlan plan);\n      public abstract Builder properties(VirtualMachineScaleSetProperties properties);\n\n      abstract Map<String, String> tags();\n      abstract VirtualMachineScaleSet autoBuild();\n\n      public VirtualMachineScaleSet build() {\n         tags(tags() != null ? ImmutableMap.copyOf(tags()) : null);\n         return autoBuild();\n      }\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/VirtualMachineScaleSetDNSSettings.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\nimport org.jclouds.json.SerializedNames;\n\nimport java.util.List;\n\n/**\n * VirtualMachineScaleSetDNSSettings\n */\n@AutoValue\npublic abstract class VirtualMachineScaleSetDNSSettings {\n   /**\n    * The list of DNS servers of the Virtual Machine Scale Set DNS Settings\n    */\n   public abstract List<String> dnsServers();\n\n   @SerializedNames({\"dnsServers\"})\n   public static VirtualMachineScaleSetDNSSettings create(final List<String> dnsServers) {\n\n      return new AutoValue_VirtualMachineScaleSetDNSSettings(\n         dnsServers == null ? ImmutableList.<String>of() : ImmutableList.copyOf(dnsServers));\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/VirtualMachineScaleSetIpConfiguration.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\n@AutoValue\npublic abstract class VirtualMachineScaleSetIpConfiguration {\n\n   /**\n    * The name of the Virtual Machine Scale Set Ip Configuration\n    */\n   @Nullable\n   public abstract String name();\n\n   /**\n    * The properties of the Virtual Machine Scale Set Ip Configuration\n    */\n   @Nullable\n   public abstract VirtualMachineScaleSetIpConfigurationProperties properties();\n\n   @SerializedNames({\"name\", \"properties\"})\n   public static VirtualMachineScaleSetIpConfiguration create(\n      final String name,\n      final VirtualMachineScaleSetIpConfigurationProperties properties) {\n      return builder()\n         .name(name)\n         .properties(properties)\n         .build();\n   }\n\n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_VirtualMachineScaleSetIpConfiguration.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder name(String name);\n      public abstract Builder properties(VirtualMachineScaleSetIpConfigurationProperties properties);\n      public abstract VirtualMachineScaleSetIpConfiguration build();\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/VirtualMachineScaleSetIpConfigurationProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport java.util.List;\n\n@AutoValue\npublic abstract class VirtualMachineScaleSetIpConfigurationProperties {\n\n   /**\n    * The public IP address configuration of the Virtual Machine Scale Set Ip Configuration Properties\n    */\n   @Nullable\n   public abstract VirtualMachineScaleSetPublicIPAddressConfiguration publicIPAddressConfiguration();\n\n   /**\n    * The subnet of the Virtual Machine Scale Set Ip Configuration Properties\n    */\n   public abstract Subnet subnet();\n\n   /**\n    * The private IP address version of the Virtual Machine Scale Set Ip Configuration Properties\n    */\n   @Nullable\n   public abstract String privateIPAddressVersion();\n\n   /**\n    * The load balancer backend address pools of the Virtual Machine Scale Set Ip Configuration Properties\n    */\n   public abstract List<IdReference> loadBalancerBackendAddressPools();\n\n   /**\n    * The load balancer inbound nat pools of the Virtual Machine Scale Set Ip Configuration Properties\n    */\n   public abstract List<IdReference> loadBalancerInboundNatPools();\n\n   /**\n    * The application gateway backend address Pools of the Virtual Machine Scale Set Ip Configuration Properties\n    */\n   @Nullable\n   public abstract String applicationGatewayBackendAddressPools();\n\n   @SerializedNames({\"publicIPAddressConfiguration\", \"subnet\", \"privateIPAddressVersion\",\n      \"loadBalancerBackendAddressPools\", \"loadBalancerInboundNatPools\", \"applicationGatewayBackendAddressPools\"})\n   public static VirtualMachineScaleSetIpConfigurationProperties create(\n      final VirtualMachineScaleSetPublicIPAddressConfiguration publicIPAddressConfiguration,\n      final Subnet subnet,\n      final String privateIPAddressVersion,\n      final List<IdReference> loadBalancerBackendAddressPools,\n      final List<IdReference> loadBalancerInboundNatPools,\n      final String applicationGatewayBackendAddressPools)\n\n   {\n      return builder()\n            .publicIPAddressConfiguration(publicIPAddressConfiguration)\n            .subnet(subnet)\n            .privateIPAddressVersion(privateIPAddressVersion)\n            .loadBalancerBackendAddressPools(\n                  loadBalancerBackendAddressPools != null ? ImmutableList.copyOf(loadBalancerBackendAddressPools)\n                        : ImmutableList.<IdReference> of())\n            .loadBalancerInboundNatPools(\n                  loadBalancerInboundNatPools != null ? ImmutableList.copyOf(loadBalancerInboundNatPools)\n                        : ImmutableList.<IdReference> of())\n            .applicationGatewayBackendAddressPools(applicationGatewayBackendAddressPools).build();\n   }\n\n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_VirtualMachineScaleSetIpConfigurationProperties.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder publicIPAddressConfiguration(VirtualMachineScaleSetPublicIPAddressConfiguration publicIPAddressConfiguration);\n      public abstract Builder subnet(Subnet subnet);\n      public abstract Builder loadBalancerBackendAddressPools(List<IdReference> loadBalancerBackendAddressPools);\n      public abstract Builder loadBalancerInboundNatPools(List<IdReference> loadBalancerInboundNatPools);\n      public abstract Builder privateIPAddressVersion(String privateIPAddressVersion);\n      public abstract Builder applicationGatewayBackendAddressPools(String applicationGatewayBackendAddressPools);\n      \n      public abstract VirtualMachineScaleSetIpConfigurationProperties build();\n   }\n}\n\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/VirtualMachineScaleSetNetworkProfile.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\nimport org.jclouds.json.SerializedNames;\n\nimport java.util.List;\n\n@AutoValue\npublic abstract class VirtualMachineScaleSetNetworkProfile {\n\n   /**\n    * The network interface configurations of the Virtual Machine Scale Set Network Profile\n    */\n   public abstract List<NetworkInterfaceConfiguration> networkInterfaceConfigurations();\n\n\n   @SerializedNames({\"networkInterfaceConfigurations\"})\n   public static VirtualMachineScaleSetNetworkProfile create(\n      final List<NetworkInterfaceConfiguration> networkInterfaceConfigurations) {\n         return builder()\n            .networkInterfaceConfigurations(networkInterfaceConfigurations == null ?\n               ImmutableList.<NetworkInterfaceConfiguration>of() : ImmutableList.copyOf(networkInterfaceConfigurations) )\n            .build();\n   }\n\n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_VirtualMachineScaleSetNetworkProfile.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n\n      public abstract Builder networkInterfaceConfigurations(\n         List<NetworkInterfaceConfiguration> networkInterfaceConfigurations);\n\n      public abstract VirtualMachineScaleSetNetworkProfile build();\n\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/VirtualMachineScaleSetNetworkSecurityGroup.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\n/**\n * Virtual Machine Scale Set Network Security Group\n */\n@AutoValue\npublic abstract class VirtualMachineScaleSetNetworkSecurityGroup {\n   /**\n    * The id of the Virtual Machine Scale Set Network Security Group\n    */\n   @Nullable\n   public abstract String id();\n\n   @SerializedNames({\"id\"})\n   public static VirtualMachineScaleSetNetworkSecurityGroup create(final String id) {\n\n      return new AutoValue_VirtualMachineScaleSetNetworkSecurityGroup(id);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/VirtualMachineScaleSetOSProfile.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\nimport org.jclouds.azurecompute.arm.util.GetEnumValue;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport java.util.List;\n\n@AutoValue\npublic abstract class VirtualMachineScaleSetOSProfile {\n\n   @AutoValue\n   public abstract static class LinuxConfiguration {\n\n\n      @AutoValue\n      public abstract static class SSH {\n\n         @AutoValue\n         public abstract static class SSHPublicKey {\n\n            /**\n             * The path for the SSH public key\n             */\n            @Nullable\n            public abstract String path();\n\n            /**\n             * The key data for the SSH public key\n             */\n            @Nullable\n            public abstract String keyData();\n\n            @SerializedNames({\"path\", \"keyData\"})\n            public static SSHPublicKey create(final String path, final String keyData) {\n\n               return new AutoValue_VirtualMachineScaleSetOSProfile_LinuxConfiguration_SSH_SSHPublicKey(\n                  path, keyData);\n            }\n         }\n\n         /**\n          * The list of public keys and paths\n          */\n         @Nullable\n         public abstract List<SSHPublicKey> publicKeys();\n\n         @SerializedNames({\"publicKeys\"})\n         public static SSH create(final List<SSHPublicKey> publicKeys) {\n\n            return new AutoValue_VirtualMachineScaleSetOSProfile_LinuxConfiguration_SSH(\n               publicKeys);\n         }\n      }\n\n      /**\n       * The authentication method password or ssh\n       */\n      public abstract Boolean disablePasswordAuthentication();\n\n      /**\n       * ssh keys\n       */\n      @Nullable\n      public abstract SSH ssh();\n\n      @SerializedNames({\"disablePasswordAuthentication\", \"ssh\"})\n      public static LinuxConfiguration create(final Boolean disablePasswordAuthentication,\n                                              final SSH ssh) {\n\n         return new AutoValue_VirtualMachineScaleSetOSProfile_LinuxConfiguration(disablePasswordAuthentication,\n            ssh);\n      }\n   }\n\n   @AutoValue\n   public abstract static class WindowsConfiguration {\n\n      @AutoValue\n      public abstract static class WinRM {\n         public enum Protocol {\n\n            HTTP(\"http\"),\n            HTTPS(\"https\"),\n            UNRECOGNIZED(\"Unrecognized\");\n\n            private String value;\n\n            Protocol(String value) {\n               this.value = value;\n            }\n\n            public static Protocol fromValue(String value) {\n               return (Protocol) GetEnumValue.fromValueOrDefault(value, Protocol.UNRECOGNIZED);\n            }\n\n            @Override\n            public String toString() {\n               return this.value;\n            }\n         }\n\n         @AutoValue\n         public abstract static class ProtocolListener {\n\n            /**\n             * The protocol for the protcol listener\n             */\n            public abstract Protocol protocol();\n\n            /**\n             * The certificate url or the protcol listener\n             */\n            @Nullable\n            public abstract String certificateUrl();\n\n            @SerializedNames({\"protocol\", \"certificateUrl\"})\n            public static ProtocolListener create(final Protocol protocol, final String certificateUrl) {\n\n               return new AutoValue_VirtualMachineScaleSetOSProfile_WindowsConfiguration_WinRM_ProtocolListener(\n                  protocol, certificateUrl);\n            }\n         }\n\n         /**\n          * Map of different settings\n          */\n         public abstract List<ProtocolListener> listeners();\n\n         @SerializedNames({\"listeners\"})\n         public static WinRM create(final List<ProtocolListener> listeners) {\n            return new AutoValue_VirtualMachineScaleSetOSProfile_WindowsConfiguration_WinRM(listeners == null ? ImmutableList.<ProtocolListener>of() : ImmutableList.copyOf(listeners));\n         }\n      }\n\n      @AutoValue\n      public abstract static class AdditionalUnattendContent {\n\n         public abstract String pass();\n\n         public abstract String component();\n\n         public abstract String settingName();\n\n         public abstract String content();\n\n         @SerializedNames({\"pass\", \"component\", \"settingName\", \"content\"})\n         public static AdditionalUnattendContent create(final String pass, final String component,\n                                                        final String settingName,\n                                                        final String content) {\n\n            return new AutoValue_VirtualMachineScaleSetOSProfile_WindowsConfiguration_AdditionalUnattendContent(\n               pass, component, settingName, content);\n         }\n      }\n\n      /**\n       * The provision VM Agent true of false.\n       */\n      public abstract boolean provisionVMAgent();\n\n      /**\n       * winRM\n       */\n      @Nullable\n      public abstract WinRM winRM();\n\n      /**\n       * unattend content\n       */\n      public abstract List<AdditionalUnattendContent> additionalUnattendContent();\n\n      /**\n       * is automatic updates enabled\n       */\n      public abstract boolean enableAutomaticUpdates();\n\n      @SerializedNames({\"provisionVMAgent\", \"winRM\", \"additionalUnattendContent\", \"enableAutomaticUpdates\"})\n      public static WindowsConfiguration create(final boolean provisionVMAgent, final WinRM winRM,\n                                                final List<AdditionalUnattendContent> additionalUnattendContent,\n                                                final boolean enableAutomaticUpdates) {\n\n         return new AutoValue_VirtualMachineScaleSetOSProfile_WindowsConfiguration(provisionVMAgent, winRM,\n            additionalUnattendContent == null ? ImmutableList.<AdditionalUnattendContent>of() : ImmutableList.copyOf(additionalUnattendContent), enableAutomaticUpdates);\n      }\n   }\n\n   /**\n    * The computer name of the VM\n    */\n   @Nullable\n   public abstract String computerNamePrefix();\n\n   /**\n    * The admin username of the VM\n    */\n   @Nullable\n   public abstract String adminUsername();\n\n   /**\n    * The admin password of the VM\n    */\n   @Nullable\n   public abstract String adminPassword();\n\n   /**\n    * The linux configuration of the VM\n    */\n   @Nullable\n   public abstract LinuxConfiguration linuxConfiguration();\n\n   /**\n    * The windows configuration of the VM\n    */\n   @Nullable\n   public abstract WindowsConfiguration windowsConfiguration();\n\n   /**\n    * The Secrets configuration of the VM\n    */\n   public abstract List<Secrets> secrets();\n\n   @SerializedNames({\"computerNamePrefix\", \"adminUsername\", \"adminPassword\", \"linuxConfiguration\",\n      \"windowsConfiguration\", \"secrets\"})\n   public static VirtualMachineScaleSetOSProfile create(final String computerNamePrefix, final String adminUsername,\n                                                        final String adminPassword, final LinuxConfiguration linuxConfiguration,\n                                                        final WindowsConfiguration windowsConfiguration, final List<Secrets> secrets) {\n      return builder()\n         .computerNamePrefix(computerNamePrefix)\n         .adminUsername(adminUsername)\n         .adminPassword(adminPassword)\n         .linuxConfiguration(linuxConfiguration)\n         .windowsConfiguration(windowsConfiguration)\n         .secrets(secrets != null ? ImmutableList.copyOf(secrets) : ImmutableList.<Secrets> of())\n         .build();\n   }\n\n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_VirtualMachineScaleSetOSProfile.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder computerNamePrefix(String computerNamePrefix);\n      public abstract Builder adminUsername(String adminUsername);\n      public abstract Builder adminPassword(String adminPassword);\n      public abstract Builder linuxConfiguration(LinuxConfiguration linuxConfiguration);\n      public abstract Builder windowsConfiguration(WindowsConfiguration windowsConfiguration);\n      public abstract Builder secrets(List<Secrets> secrets);\n\n      public abstract VirtualMachineScaleSetOSProfile build();\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/VirtualMachineScaleSetPlan.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\n/**\n * SKU\n */\n@AutoValue\npublic abstract class VirtualMachineScaleSetPlan {\n   /**\n    * The name of the Virtual Machine Scale Set Plan\n    */\n   @Nullable\n   public abstract String name();\n\n   /**\n    * The publisher of the Virtual Machine Scale Set Plan\n    */\n   @Nullable\n   public abstract String publisher();\n\n   /**\n    * The product of the Virtual Machine Scale Set Plan\n    */\n   @Nullable\n   public abstract String product();\n\n   @SerializedNames({\"name\", \"publisher\", \"product\"})\n   public static VirtualMachineScaleSetPlan create(final String name, final String publisher, final String product) {\n\n      return new AutoValue_VirtualMachineScaleSetPlan(name, publisher, product);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/VirtualMachineScaleSetProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\nimport org.jclouds.azurecompute.arm.util.GetEnumValue;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\n\n@AutoValue\npublic abstract class VirtualMachineScaleSetProperties {\n\n   public enum ProvisioningState {\n      ACCEPTED,\n      CREATING,\n      READY,\n      CANCELED,\n      FAILED,\n      DELETED,\n      SUCCEEDED,\n      RUNNING,\n      UPDATING,\n      UNRECOGNIZED;\n\n      public static ProvisioningState fromValue(final String text) {\n         return (ProvisioningState) GetEnumValue.fromValueOrDefault(text, ProvisioningState.UNRECOGNIZED);\n      }\n   }\n\n   /**\n    * The singlePlacementGroup of the VirtualMachineScaleSetProperties\n    */\n   @Nullable\n   public abstract Boolean singlePlacementGroup();\n\n   /**\n    * Specifies the over provision of the virtual machine scale set\n    */\n   @Nullable\n   public abstract Boolean overProvision();\n\n   /**\n    * Specifies the upgrade policy of the virtual machine scale set\n    */\n   public abstract VirtualMachineScaleSetUpgradePolicy upgradePolicy();\n\n   /**\n    * Specifies the state of the provision of the virtual machine scale set\n    */\n   @Nullable\n   public abstract ProvisioningState provisioningState();\n\n   /**\n    * Specifies the virtual machine profile of the virtual machine scale set\n    */\n   public abstract VirtualMachineScaleSetVirtualMachineProfile virtualMachineProfile();\n\n   @SerializedNames({\"singlePlacementGroup\", \"overProvision\", \"upgradePolicy\", \"provisioningState\", \"virtualMachineProfile\"})\n   public static VirtualMachineScaleSetProperties create(\n           final Boolean singlePlacementGroup,\n           final Boolean overProvision,\n           final VirtualMachineScaleSetUpgradePolicy upgradePolicy,\n           final ProvisioningState provisioningState,\n           final VirtualMachineScaleSetVirtualMachineProfile virtualMachineProfile) {\n      return builder().singlePlacementGroup(singlePlacementGroup).overProvision(overProvision).\n              upgradePolicy(upgradePolicy).provisioningState(provisioningState).virtualMachineProfile(virtualMachineProfile).build();\n   }\n\n   public abstract Builder toBuilder();\n\n   private static Builder builder() {\n      return new AutoValue_VirtualMachineScaleSetProperties.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder singlePlacementGroup(Boolean singlePlacementGroup);\n\n      public abstract Builder overProvision(Boolean overProvision);\n\n      public abstract Builder upgradePolicy(VirtualMachineScaleSetUpgradePolicy upgradePolicy);\n\n      public abstract Builder provisioningState(ProvisioningState provisioningState);\n\n      public abstract Builder virtualMachineProfile(VirtualMachineScaleSetVirtualMachineProfile virtualMachineProfile);\n\n      public abstract VirtualMachineScaleSetProperties build();\n   }\n}\n\n\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/VirtualMachineScaleSetPublicIPAddressConfiguration.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\nimport org.jclouds.json.SerializedNames;\n\n@AutoValue\npublic abstract class VirtualMachineScaleSetPublicIPAddressConfiguration {\n\n   /**\n    * The name of the Virtual Machine Scale Set Public IP Address Configuration\n    */\n   public abstract String name();\n\n   /**\n    * The properties of the Virtual Machine Scale Set Public IP Address Configuration\n    */\n   public abstract VirtualMachineScaleSetPublicIPAddressProperties properties();\n\n   @SerializedNames({ \"name\",  \"properties\" })\n   public static VirtualMachineScaleSetPublicIPAddressConfiguration create(\n      String name,\n      VirtualMachineScaleSetPublicIPAddressProperties properties) {\n         return builder().name(name).properties(properties).build();\n   }\n\n   VirtualMachineScaleSetPublicIPAddressConfiguration() {\n\n   }\n\n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_VirtualMachineScaleSetPublicIPAddressConfiguration.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder name(String name);\n      public abstract Builder properties(VirtualMachineScaleSetPublicIPAddressProperties properties);\n      public abstract VirtualMachineScaleSetPublicIPAddressConfiguration build();\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/VirtualMachineScaleSetPublicIPAddressProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\n@AutoValue\npublic abstract class VirtualMachineScaleSetPublicIPAddressProperties  {\n\n   /**\n    * The idle timeout (in minutes) of the Virtual Machine Scale Set Public IP Address Configuration\n    */\n   @Nullable\n   public abstract Integer idleTimeoutInMinutes();\n\n\n   @SerializedNames({ \"idleTimeoutInMinutes\" })\n   public static VirtualMachineScaleSetPublicIPAddressProperties create(final Integer idleTimeoutInMinutes) {\n      return builder()\n         .idleTimeoutInMinutes(idleTimeoutInMinutes)\n         .build();\n   }\n\n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_VirtualMachineScaleSetPublicIPAddressProperties.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n\n      public abstract Builder idleTimeoutInMinutes(Integer idleTimeoutInMinutes);\n\n      public abstract VirtualMachineScaleSetPublicIPAddressProperties build();\n   }\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/VirtualMachineScaleSetSKU.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\nimport org.jclouds.json.SerializedNames;\n\n\n@AutoValue\npublic abstract class VirtualMachineScaleSetSKU {\n   /**\n    * The name of the Virtual Machine Scale Set SKU\n    */\n   public abstract String name();\n\n   /**\n    * The tier of the Virtual Machine Scale Set SKU\n    */\n   public abstract String tier();\n\n   /**\n    * The capacity of the Virtual Machine Scale Set SKU\n    */\n   public abstract int capacity();\n\n   @SerializedNames({\"name\", \"tier\", \"capacity\"})\n   public static VirtualMachineScaleSetSKU create(final String name, final String tier, final int capacity) {\n\n      return new AutoValue_VirtualMachineScaleSetSKU(name, tier, capacity);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/VirtualMachineScaleSetUpgradeMode.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport org.jclouds.azurecompute.arm.util.GetEnumValue;\n\n\npublic class VirtualMachineScaleSetUpgradeMode {\n   /**\n    * VirtualMachineScaleSetUpgradeMode\n    * **/\n   public enum Status {\n      Manual,\n      Automatic,\n      Unrecognized;\n\n      public static Status fromValue(final String text) {\n         return (Status) GetEnumValue.fromValueOrDefault(text, Status.Unrecognized);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/VirtualMachineScaleSetUpgradePolicy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\nimport org.jclouds.json.SerializedNames;\n\n\n@AutoValue\npublic abstract class VirtualMachineScaleSetUpgradePolicy {\n   /**\n    * The mode of the Virtual Machine Scale Set Upgrade Policy\n    */\n   public abstract String mode();\n\n   @SerializedNames({\"mode\"})\n   public static VirtualMachineScaleSetUpgradePolicy create(final String mode) {\n\n      return new AutoValue_VirtualMachineScaleSetUpgradePolicy(mode);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/VirtualMachineScaleSetVirtualMachineProfile.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport com.google.auto.value.AutoValue;\nimport org.jclouds.json.SerializedNames;\n\n/**\n * A virtual machine properties for the virtual machine.\n */\n@AutoValue\npublic abstract class VirtualMachineScaleSetVirtualMachineProfile {\n\n   /**\n    * The storage profile of the Virtual Machine Scale Set Virtual Machine Profile.\n    */\n   public abstract StorageProfile storageProfile();\n\n   /**\n    * The OS profile of the Virtual Machine Scale Set Virtual Machine Profile.\n    */\n   public abstract VirtualMachineScaleSetOSProfile osProfile();\n\n   /**\n    * The network profile of the Virtual Machine Scale Set Virtual Machine Profile\n    */\n   public abstract VirtualMachineScaleSetNetworkProfile networkProfile();\n\n   /**\n    * The extension profile of the Virtual Machine Scale Set Virtual Machine Profile .\n    */\n   public abstract ExtensionProfile extensionProfile();\n\n\n\n   @SerializedNames({\"storageProfile\", \"osProfile\", \"networkProfile\", \"extensionProfile\"})\n   public static VirtualMachineScaleSetVirtualMachineProfile create(\n      final StorageProfile storageProfile,\n      final VirtualMachineScaleSetOSProfile osProfile,\n      final VirtualMachineScaleSetNetworkProfile networkProfile,\n      final ExtensionProfile extensionProfile) {\n         return builder()\n            .storageProfile(storageProfile)\n            .osProfile(osProfile)\n            .networkProfile(networkProfile)\n            .extensionProfile(extensionProfile)\n            .build();\n   }\n\n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_VirtualMachineScaleSetVirtualMachineProfile.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n\n      public abstract Builder storageProfile(StorageProfile storageProfile);\n\n      public abstract Builder osProfile(VirtualMachineScaleSetOSProfile osProfile);\n\n      public abstract Builder networkProfile(VirtualMachineScaleSetNetworkProfile networkProfile);\n\n      public abstract Builder extensionProfile(ExtensionProfile extensionProfile);\n\n      public abstract VirtualMachineScaleSetVirtualMachineProfile build();\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/VirtualNetwork.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport static com.google.common.collect.ImmutableList.copyOf;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\n\n@AutoValue\npublic abstract class VirtualNetwork {\n\n   @AutoValue\n   public abstract static class VirtualNetworkProperties implements Provisionable {\n\n      @Nullable\n      public abstract String provisioningState();\n\n      @Nullable\n      public abstract String resourceGuid();\n\n      public abstract AddressSpace addressSpace();\n\n      @Nullable\n      public abstract List<Subnet> subnets();\n\n\n      @SerializedNames({\"provisioningState\", \"resourceGuid\", \"addressSpace\", \"subnets\"})\n      public static VirtualNetworkProperties create(final String provisioningState, final String resourceGuid, final AddressSpace addressSpace, final List<Subnet> subnets) {\n         return builder()\n                 .provisioningState(provisioningState)\n                 .resourceGuid(resourceGuid)\n                 .addressSpace(addressSpace)\n                 .subnets(subnets != null ? copyOf(subnets) : null)\n                 .build();\n      }\n      \n      public abstract Builder toBuilder();\n\n      public static Builder builder() {\n         return new AutoValue_VirtualNetwork_VirtualNetworkProperties.Builder();\n      }\n\n      @AutoValue.Builder\n      public abstract static class Builder {\n         public abstract Builder provisioningState(String provisioningState);\n\n         public abstract Builder resourceGuid(String resourceGuid);\n\n         public abstract Builder addressSpace(AddressSpace addressSpace);\n\n         public abstract Builder subnets(List<Subnet> subnets);\n\n         abstract List<Subnet> subnets();\n\n         abstract VirtualNetworkProperties autoBuild();\n\n         public VirtualNetworkProperties build() {\n            subnets(subnets() != null ? ImmutableList.copyOf(subnets()) : null);\n            return autoBuild();\n         }\n      }\n   }\n\n   @Nullable\n   public abstract String name();\n\n   @Nullable\n   public abstract String id();\n\n   @Nullable\n   public abstract String etag();\n\n   public abstract String location();\n\n   public abstract VirtualNetworkProperties properties();\n\n   @Nullable\n   public abstract Map<String, String> tags();\n\n   @SerializedNames({\"name\", \"id\", \"etag\", \"location\", \"properties\", \"tags\"})\n   public static VirtualNetwork create(final String name,\n                                       final String id,\n                                       final String etag,\n                                       final String location,\n                                       final VirtualNetworkProperties properties,\n                                       final Map<String, String> tags) {\n      return new AutoValue_VirtualNetwork(name, id, etag, location, properties, tags == null ? null : ImmutableMap.copyOf(tags));\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/loadbalancer/LoadBalancer.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain.loadbalancer;\n\nimport java.util.Map;\n\nimport org.jclouds.azurecompute.arm.util.GetEnumValue;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableMap;\n\n@AutoValue\npublic abstract class LoadBalancer {\n   \n   @Nullable public abstract String id();\n   @Nullable public abstract String name();\n   @Nullable public abstract String location();\n   @Nullable public abstract String etag();\n   @Nullable public abstract Map<String, String> tags();\n   @Nullable public abstract LoadBalancerProperties properties();\n\n   @Nullable\n   public abstract SKU sku();\n\n   @SerializedNames({ \"id\", \"name\", \"location\", \"etag\", \"tags\", \"sku\", \"properties\"})\n   public static LoadBalancer create(String id, final String name, final String location, final String etag,\n         final Map<String, String> tags, final SKU sku, final LoadBalancerProperties properties) {\n      return builder().id(id).name(name).location(location).etag(etag).tags(tags).sku(sku).properties(properties).build();\n   }\n   \n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_LoadBalancer.Builder();\n   }\n   \n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder id(String id);\n      public abstract Builder name(String name);\n      public abstract Builder location(String location);\n      public abstract Builder etag(String etag);\n      public abstract Builder tags(Map<String, String> tags);\n      public abstract Builder properties(LoadBalancerProperties properties);\n\n      public abstract Builder sku(SKU sku);\n      \n      abstract Map<String, String> tags();\n\n      abstract LoadBalancer autoBuild();\n      \n      public LoadBalancer build() {\n         tags(tags() != null ? ImmutableMap.copyOf(tags()) : null);\n         return autoBuild();\n      }\n   }\n\n   @AutoValue\n   public abstract static class SKU {\n\n      public enum SKUName {\n         Basic, Standard, Unrecognized;\n\n         public static SKUName fromValue(final String text) {\n            return (SKUName) GetEnumValue.fromValueOrDefault(text, SKUName.Unrecognized);\n         }\n      }\n\n      public abstract SKUName name();\n\n      @SerializedNames({ \"name\" })\n      public static SKU create(final SKUName name) {\n\n         return new AutoValue_LoadBalancer_SKU(name);\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/loadbalancer/LoadBalancerProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain.loadbalancer;\n\nimport java.util.List;\n\nimport org.jclouds.azurecompute.arm.domain.BackendAddressPool;\nimport org.jclouds.azurecompute.arm.domain.FrontendIPConfigurations;\nimport org.jclouds.azurecompute.arm.domain.InboundNatRule;\nimport org.jclouds.azurecompute.arm.domain.Probe;\nimport org.jclouds.azurecompute.arm.domain.Provisionable;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\n\n@AutoValue\npublic abstract class LoadBalancerProperties implements Provisionable {\n\n   @Nullable\n   public abstract List<FrontendIPConfigurations> frontendIPConfigurations();\n\n   @Nullable\n   public abstract List<BackendAddressPool> backendAddressPools();\n\n   @Nullable\n   public abstract List<LoadBalancingRule> loadBalancingRules();\n\n   @Nullable\n   public abstract List<Probe> probes();\n\n   @Nullable\n   public abstract List<InboundNatRule> inboundNatRules();\n\n   @Nullable\n   public abstract String resourceGuid();\n\n   @Nullable\n   public abstract String provisioningState();\n\n   @SerializedNames({ \"frontendIPConfigurations\", \"backendAddressPools\", \"loadBalancingRules\", \"probes\",\n         \"inboundNatRules\", \"resourceGuid\", \"provisioningState\" })\n   public static LoadBalancerProperties create(final List<FrontendIPConfigurations> frontendIPConfigurations,\n         final List<BackendAddressPool> backendAddressPools, final List<LoadBalancingRule> loadBalancingRules,\n         final List<Probe> probes, final List<InboundNatRule> inboundNatRules, final String resourceGuid,\n         final String provisioningState) {\n      return builder().frontendIPConfigurations(frontendIPConfigurations)\n            .backendAddressPools(backendAddressPools == null ? null : ImmutableList.copyOf(backendAddressPools))\n            .loadBalancingRules(loadBalancingRules == null ? null : ImmutableList.copyOf(loadBalancingRules))\n            .probes(probes == null ? null : ImmutableList.copyOf(probes))\n            .inboundNatRules(inboundNatRules == null ? null : ImmutableList.copyOf(inboundNatRules))\n            .resourceGuid(resourceGuid).provisioningState(provisioningState).build();\n   }\n\n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_LoadBalancerProperties.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder frontendIPConfigurations(List<FrontendIPConfigurations> frontendIPConfigurations);\n\n      public abstract Builder backendAddressPools(List<BackendAddressPool> backendAddressPools);\n\n      public abstract Builder loadBalancingRules(List<LoadBalancingRule> networkInterfaces);\n\n      public abstract Builder probes(List<Probe> probes);\n\n      public abstract Builder inboundNatRules(List<InboundNatRule> inboundNatRules);\n\n      public abstract Builder resourceGuid(String resourceGuid);\n\n      public abstract Builder provisioningState(String provisioningState);\n\n      abstract List<FrontendIPConfigurations> frontendIPConfigurations();\n\n      abstract List<BackendAddressPool> backendAddressPools();\n\n      abstract List<LoadBalancingRule> loadBalancingRules();\n\n      abstract List<Probe> probes();\n\n      abstract List<InboundNatRule> inboundNatRules();\n\n      abstract LoadBalancerProperties autoBuild();\n\n      public LoadBalancerProperties build() {\n         frontendIPConfigurations(frontendIPConfigurations() != null ? ImmutableList.copyOf(frontendIPConfigurations())\n               : null);\n         backendAddressPools(backendAddressPools() != null ? ImmutableList.copyOf(backendAddressPools()) : null);\n         loadBalancingRules(loadBalancingRules() != null ? ImmutableList.copyOf(loadBalancingRules()) : null);\n         probes(probes() != null ? ImmutableList.copyOf(probes()) : null);\n         inboundNatRules(inboundNatRules() != null ? ImmutableList.copyOf(inboundNatRules()) : null);\n         return autoBuild();\n      }\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/loadbalancer/LoadBalancingRule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain.loadbalancer;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class LoadBalancingRule {\n   @Nullable\n   public abstract String name();\n\n   @Nullable\n   public abstract String id();\n\n   @Nullable\n   public abstract LoadBalancingRuleProperties properties();\n\n   @Nullable\n   public abstract String etag();\n\n   @SerializedNames({ \"name\", \"id\", \"properties\", \"etag\" })\n   public static LoadBalancingRule create(final String name, final String id,\n         final LoadBalancingRuleProperties properties, final String etag) {\n      return new AutoValue_LoadBalancingRule(name, id, properties, etag);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/loadbalancer/LoadBalancingRuleProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain.loadbalancer;\n\nimport org.jclouds.azurecompute.arm.domain.IdReference;\nimport org.jclouds.azurecompute.arm.util.GetEnumValue;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class LoadBalancingRuleProperties {\n\n   public enum Protocol {\n      Tcp(\"Tcp\"), Udp(\"Udp\"), UNRECOGNIZED(\"Unrecognized\");\n\n      private final String label;\n\n      private Protocol(final String label) {\n         this.label = label;\n      }\n\n      public static Protocol fromValue(final String text) {\n         return (Protocol) GetEnumValue.fromValueOrDefault(text, Protocol.UNRECOGNIZED);\n      }\n\n      @Override\n      public String toString() {\n         return label;\n      }\n   }\n   \n   public enum LoadDistribution {\n      Default(\"Default\"), SourceIp(\"SourceIP\"), SourceIPProtocol(\"SourceIPProtocol\"), UNRECOGNIZED(\"Unrecognized\");\n\n      private final String label;\n\n      private LoadDistribution(final String label) {\n         this.label = label;\n      }\n\n      public static LoadDistribution fromValue(final String text) {\n         return (LoadDistribution) GetEnumValue.fromValueOrDefault(text, LoadDistribution.UNRECOGNIZED);\n      }\n\n      @Override\n      public String toString() {\n         return label;\n      }\n   }\n\n   @Nullable\n   public abstract IdReference frontendIPConfiguration();\n\n   @Nullable\n   public abstract IdReference backendAddressPool();\n\n   public abstract Protocol protocol();\n\n   public abstract int frontendPort();\n\n   public abstract int backendPort();\n\n   @Nullable\n   public abstract IdReference probe();\n\n   @Nullable\n   public abstract Boolean enableFloatingIP();\n\n   @Nullable\n   public abstract Integer idleTimeoutInMinutes();\n\n   @Nullable\n   public abstract LoadDistribution loadDistribution();\n\n   @Nullable\n   public abstract String provisioningState();\n\n   @SerializedNames({ \"frontendIPConfiguration\", \"backendAddressPool\", \"protocol\", \"frontendPort\", \"backendPort\",\n         \"probe\", \"enableFloatingIP\", \"idleTimeoutInMinutes\", \"loadDistribution\", \"provisioningState\" })\n   public static LoadBalancingRuleProperties create(final IdReference frontendIPConfiguration,\n         final IdReference backendAddressPool, final Protocol protocol, final int frontendPort, final int backendPort,\n         final IdReference probe, final Boolean enableFloatingIP, final Integer idleTimeoutInMinutes,\n         final LoadDistribution loadDistribution, final String provisioningState) {\n      return builder().frontendIPConfiguration(frontendIPConfiguration).backendAddressPool(backendAddressPool)\n            .protocol(protocol).frontendPort(frontendPort).backendPort(backendPort).probe(probe)\n            .enableFloatingIP(enableFloatingIP).idleTimeoutInMinutes(idleTimeoutInMinutes)\n            .loadDistribution(loadDistribution).build();\n   }\n   \n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_LoadBalancingRuleProperties.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder frontendIPConfiguration(IdReference frontendIPConfiguration);\n\n      public abstract Builder backendAddressPool(IdReference backendAddressPool);\n\n      public abstract Builder protocol(Protocol protocol);\n\n      public abstract Builder frontendPort(int frontendPort);\n\n      public abstract Builder backendPort(int backendPort);\n\n      public abstract Builder probe(IdReference probe);\n\n      public abstract Builder enableFloatingIP(Boolean enableFloatingIP);\n\n      public abstract Builder idleTimeoutInMinutes(Integer idleTimeoutInMinutes);\n\n      public abstract Builder loadDistribution(LoadDistribution loadDistribution);\n\n      public abstract Builder provisioningState(String provisioningState);\n\n      public abstract LoadBalancingRuleProperties build();\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/publicipaddress/PublicIPAddress.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.azurecompute.arm.domain.publicipaddress;\n\nimport java.util.Map;\n\nimport org.jclouds.azurecompute.arm.util.GetEnumValue;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableMap;\n\n@AutoValue\npublic abstract class PublicIPAddress {\n\n   public abstract String name();\n   public abstract String id();\n   public abstract String etag();\n   public abstract String location();\n   @Nullable public abstract Map<String, String> tags();\n   public abstract PublicIPAddressProperties properties();\n\n   @Nullable\n   public abstract SKU sku();\n\n   @SerializedNames({ \"name\", \"id\", \"etag\", \"location\", \"tags\", \"sku\", \"properties\"})\n   public static PublicIPAddress create(String name, String id, String etag, String location, Map<String, String> tags,\n         SKU sku, PublicIPAddressProperties properties) {\n      return builder().name(name).id(id).etag(etag).location(location).tags(tags).sku(sku).properties(properties).build();\n   }\n   \n   PublicIPAddress() {\n      \n   }\n   \n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_PublicIPAddress.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder name(String name);\n      public abstract Builder id(String id);\n      public abstract Builder etag(String etag);\n      public abstract Builder location(String location);\n      public abstract Builder tags(Map<String, String> tags);\n      public abstract Builder properties(PublicIPAddressProperties properties);\n\n      public abstract Builder sku(SKU sku);\n      \n      abstract Map<String, String> tags();\n      abstract PublicIPAddress autoBuild();\n\n      public PublicIPAddress build() {\n         tags(tags() != null ? ImmutableMap.copyOf(tags()) : null);\n         return autoBuild();\n      }\n   }\n\n   @AutoValue\n   public abstract static class SKU {\n\n      public enum SKUName {\n         Basic, Standard, Unrecognized;\n\n         public static SKUName fromValue(final String text) {\n            return (SKUName) GetEnumValue.fromValueOrDefault(text, SKUName.Unrecognized);\n         }\n      }\n\n      public abstract SKUName name();\n\n      @SerializedNames({ \"name\" })\n      public static SKU create(final SKUName name) {\n\n         return new AutoValue_PublicIPAddress_SKU(name);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/publicipaddress/PublicIPAddressProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain.publicipaddress;\n\nimport org.jclouds.azurecompute.arm.domain.DnsSettings;\nimport org.jclouds.azurecompute.arm.domain.IdReference;\nimport org.jclouds.azurecompute.arm.domain.Provisionable;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class PublicIPAddressProperties implements Provisionable {\n\n   @Nullable // needs to be nullable to create the payload for create request\n   public abstract String provisioningState();\n\n   @Nullable // only set in succeeded provisioningState for Static IP and for Dynamic when attached to a NIC\n   public abstract String ipAddress();\n\n   public abstract String publicIPAllocationMethod();\n\n   @Nullable\n   public abstract Integer idleTimeoutInMinutes();\n\n   @Nullable // only if attached to NIC\n   public abstract IdReference ipConfiguration();\n\n   @Nullable // only if DNS name is set\n   public abstract DnsSettings dnsSettings();\n\n   @SerializedNames({\"provisioningState\", \"ipAddress\", \"publicIPAllocationMethod\", \"idleTimeoutInMinutes\", \"ipConfiguration\", \"dnsSettings\"})\n   public static PublicIPAddressProperties create(final String provisioningState,\n                                                  final String ipAddress,\n                                                  final String publicIPAllocationMethod,\n                                                  final Integer idleTimeoutInMinutes,\n                                                  final IdReference ipConfiguration,\n                                                  final DnsSettings dnsSettings) {\n      return builder()\n              .provisioningState(provisioningState)\n              .ipAddress(ipAddress)\n              .publicIPAllocationMethod(publicIPAllocationMethod)\n              .idleTimeoutInMinutes(idleTimeoutInMinutes)\n              .ipConfiguration(ipConfiguration)\n              .dnsSettings(dnsSettings)\n              .publicIPAllocationMethod(publicIPAllocationMethod)\n              .dnsSettings(dnsSettings)\n              .build();\n   }\n   \n   public abstract Builder toBuilder();\n\n   public static Builder builder() {\n      return new AutoValue_PublicIPAddressProperties.Builder();\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder provisioningState(String provisioningState);\n\n      public abstract Builder ipAddress(String ipAddress);\n\n      public abstract Builder publicIPAllocationMethod(String publicIPAllocationMethod);\n\n      public abstract Builder idleTimeoutInMinutes(Integer idleTimeoutInMinutes);\n\n      public abstract Builder ipConfiguration(IdReference ipConfiguration);\n\n      public abstract Builder dnsSettings(DnsSettings dnsSettings);\n\n      public abstract PublicIPAddressProperties build();\n   }\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/vpn/BGPSettings.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain.vpn;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class BGPSettings {\n   public abstract int asn();\n   public abstract String bgpPeeringAddress();\n   public abstract int peerWeight();\n\n   @SerializedNames({ \"asn\", \"bgpPeeringAddress\", \"peerWeight\" })\n   public static BGPSettings create(int asn, String bgpPeeringAddress, int peerWeight) {\n      return new AutoValue_BGPSettings(asn, bgpPeeringAddress, peerWeight);\n   }\n\n   BGPSettings() {\n\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/vpn/DHGroup.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain.vpn;\n\nimport org.jclouds.azurecompute.arm.util.GetEnumValue;\n\npublic enum DHGroup {\n\n   DHGroup1, DHGroup14, DHGroup2, DHGroup2048, DHGroup24, ECP256, ECP384, None, Unrecognized;\n\n   public static DHGroup fromValue(final String text) {\n      return (DHGroup) GetEnumValue.fromValueOrDefault(text, DHGroup.Unrecognized);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/vpn/IPSecEncryption.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain.vpn;\n\nimport org.jclouds.azurecompute.arm.util.GetEnumValue;\n\npublic enum IPSecEncryption {\n\n   AES128, AES192, AES256, DES, DES3, GCMAES128, GCMAES192, GCMAES256, None, Unrecognized;\n\n   public static IPSecEncryption fromValue(final String text) {\n      return (IPSecEncryption) GetEnumValue.fromValueOrDefault(text, IPSecEncryption.Unrecognized);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/vpn/IPSecIntegrity.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain.vpn;\n\nimport org.jclouds.azurecompute.arm.util.GetEnumValue;\n\npublic enum IPSecIntegrity {\n\n   GCMAES128, GCMAES192, GCMAES256, MD5, SHA1, SHA256, Unrecognized;\n\n   public static IPSecIntegrity fromValue(final String text) {\n      return (IPSecIntegrity) GetEnumValue.fromValueOrDefault(text, IPSecIntegrity.Unrecognized);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/vpn/IPSecPolicy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain.vpn;\n\nimport org.jclouds.azurecompute.arm.domain.AddressSpace;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class IPSecPolicy {\n   @Nullable public abstract String radiusServerAddress();\n   @Nullable public abstract String radiusServerSecret();\n   @Nullable public abstract AddressSpace vpnClientAddressPool();\n   @Nullable public abstract DHGroup dhGroup();\n   @Nullable public abstract IkeEncryption ikeEncryption();\n   @Nullable public abstract IkeIntegrity ikeIntegrity();\n   @Nullable public abstract IPSecEncryption ipsecEncryption();\n   @Nullable public abstract IPSecIntegrity ipsecIntegrity();\n   @Nullable public abstract PFSGroup pfsGroup();\n   @Nullable public abstract Integer saDataSizeKilobytes();\n   @Nullable public abstract Integer saLifeTimeSeconds();\n\n   IPSecPolicy() {\n\n   }\n   \n   @SerializedNames({ \"radiusServerAddress\", \"radiusServerSecret\", \"vpnClientAddressPool\", \"dhGroup\", \"ikeEncryption\",\n         \"ikeIntegrity\", \"ipsecEncryption\", \"ipsecIntegrity\", \"pfsGroup\", \"saDataSizeKilobytes\", \"saLifeTimeSeconds\" })\n   public static IPSecPolicy create(String radiusServerAddress, String radiusServerSecret,\n         AddressSpace vpnClientAddressPool, DHGroup dhGroup, IkeEncryption ikeEncryption, IkeIntegrity ikeIntegrity,\n         IPSecEncryption ipsecEncryption, IPSecIntegrity ipsecIntegrity, PFSGroup pfsGroup,\n         Integer saDataSizeKilobytes, Integer saLifeTimeSeconds) {\n      return builder().radiusServerAddress(radiusServerAddress).radiusServerSecret(radiusServerSecret)\n            .vpnClientAddressPool(vpnClientAddressPool).dhGroup(dhGroup).ikeEncryption(ikeEncryption)\n            .ikeIntegrity(ikeIntegrity).ipsecEncryption(ipsecEncryption).ipsecIntegrity(ipsecIntegrity)\n            .pfsGroup(pfsGroup).saDataSizeKilobytes(saDataSizeKilobytes).saLifeTimeSeconds(saLifeTimeSeconds).build();\n   }\n\n   public static Builder builder() {\n      return new AutoValue_IPSecPolicy.Builder();\n   }\n\n   public abstract Builder toBuilder();\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder radiusServerAddress(String radiusServerAddress);\n      public abstract Builder radiusServerSecret(String radiusServerSecret);\n      public abstract Builder vpnClientAddressPool(AddressSpace vpnClientAddressPool);\n      public abstract Builder dhGroup(DHGroup dhGroup);\n      public abstract Builder ikeEncryption(IkeEncryption ikeEncryption);\n      public abstract Builder ikeIntegrity(IkeIntegrity ikeIntegrity);\n      public abstract Builder ipsecEncryption(IPSecEncryption ipsecEncryption);\n      public abstract Builder ipsecIntegrity(IPSecIntegrity ipsecIntegrity);\n      public abstract Builder pfsGroup(PFSGroup pfsGroup);\n      public abstract Builder saDataSizeKilobytes(Integer saDataSizeKilobytes);\n      public abstract Builder saLifeTimeSeconds(Integer saLifeTimeSeconds);\n\n      public abstract IPSecPolicy build();\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/vpn/IkeEncryption.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain.vpn;\n\nimport org.jclouds.azurecompute.arm.util.GetEnumValue;\n\npublic enum IkeEncryption {\n\n   AES128, AES192, AES256, DES, DES3, GCMAES128, GCMAES256, Unrecognized;\n\n   public static IkeEncryption fromValue(final String text) {\n      return (IkeEncryption) GetEnumValue.fromValueOrDefault(text, IkeEncryption.Unrecognized);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/vpn/IkeIntegrity.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain.vpn;\n\nimport org.jclouds.azurecompute.arm.util.GetEnumValue;\n\npublic enum IkeIntegrity {\n\n   GCMAES128, GCMAES256, MD5, SHA1, SHA256, SHA384, Unrecognized;\n\n   public static IkeIntegrity fromValue(final String text) {\n      return (IkeIntegrity) GetEnumValue.fromValueOrDefault(text, IkeIntegrity.Unrecognized);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/vpn/LocalNetworkGateway.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain.vpn;\n\nimport java.util.Map;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableMap;\n\n@AutoValue\npublic abstract class LocalNetworkGateway {\n\n   @Nullable public abstract String id();\n   public abstract String name();\n   public abstract String location();\n   @Nullable public abstract String type();\n   @Nullable public abstract Map<String, String> tags();\n   @Nullable public abstract String etag();\n   public abstract LocalNetworkGatewayProperties properties();\n\n   LocalNetworkGateway() {\n\n   }\n\n   @SerializedNames({ \"id\", \"name\", \"location\", \"type\", \"tags\", \"etag\", \"properties\" })\n   public static LocalNetworkGateway create(String id, String name, String location, String type,\n         Map<String, String> tags, String etag, LocalNetworkGatewayProperties properties) {\n      return builder(name, location, properties).id(id).type(type).tags(tags).etag(etag).build();\n   }\n\n   public abstract Builder toBuilder();\n\n   public static Builder builder(String name, String location, LocalNetworkGatewayProperties properties) {\n      return new AutoValue_LocalNetworkGateway.Builder().name(name).location(location).properties(properties);\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder id(String id);\n      public abstract Builder name(String name);\n      public abstract Builder location(String location);\n      public abstract Builder type(String type);\n      public abstract Builder tags(Map<String, String> tags);\n      public abstract Builder etag(String etag);\n      public abstract Builder properties(LocalNetworkGatewayProperties properties);\n\n      abstract Map<String, String> tags();\n      abstract LocalNetworkGateway autoBuild();\n\n      public LocalNetworkGateway build() {\n         tags(tags() != null ? ImmutableMap.copyOf(tags()) : null);\n         return autoBuild();\n      }\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/vpn/LocalNetworkGatewayProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain.vpn;\n\nimport org.jclouds.azurecompute.arm.domain.AddressSpace;\nimport org.jclouds.azurecompute.arm.domain.Provisionable;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class LocalNetworkGatewayProperties implements Provisionable {\n   \n   @Nullable public abstract BGPSettings bgpSettings();\n   public abstract String gatewayIpAddress();\n   @Nullable public abstract AddressSpace localNetworkAddressSpace();\n   @Nullable public abstract String provisioningState();\n   @Nullable public abstract String resourceGuid();\n\n   @SerializedNames({ \"bgpSettings\", \"gatewayIpAddress\", \"localNetworkAddressSpace\", \"provisioningState\",\n         \"resourceGuid\" })\n   public static LocalNetworkGatewayProperties create(BGPSettings bgpSettings, String gatewayIpAddress,\n         AddressSpace localNetworkAddressSpace, String provisioningState, String resourceGuid) {\n      return builder(gatewayIpAddress).bgpSettings(bgpSettings).localNetworkAddressSpace(localNetworkAddressSpace)\n            .provisioningState(provisioningState).resourceGuid(resourceGuid).build();\n   }\n\n   LocalNetworkGatewayProperties() {\n\n   }\n\n   public abstract LocalNetworkGatewayProperties.Builder toBuilder();\n\n   public static LocalNetworkGatewayProperties.Builder builder(String gatewayIpAddress) {\n      return new AutoValue_LocalNetworkGatewayProperties.Builder().gatewayIpAddress(gatewayIpAddress);\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder bgpSettings(BGPSettings bgpSettings);\n      public abstract Builder gatewayIpAddress(String gatewayIpAddress);\n      public abstract Builder localNetworkAddressSpace(AddressSpace localNetworkAddressSpace);\n      public abstract Builder provisioningState(String provisioningState);\n      public abstract Builder resourceGuid(String resourceGuid);\n\n      public abstract LocalNetworkGatewayProperties build();\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/vpn/PFSGroup.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain.vpn;\n\nimport org.jclouds.azurecompute.arm.util.GetEnumValue;\n\npublic enum PFSGroup {\n\n   ECP256, ECP384, PFS1, PFS14, PFS2, PFS2048, PFS24, PFSMM, None, Unrecognized;\n\n   public static PFSGroup fromValue(final String text) {\n      return (PFSGroup) GetEnumValue.fromValueOrDefault(text, PFSGroup.Unrecognized);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/vpn/SKU.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain.vpn;\n\nimport org.jclouds.azurecompute.arm.util.GetEnumValue;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class SKU {\n\n   public static enum SKUName {\n      Basic, HighPerformance, Standard, UltraPerformance, VpnGw1, VpnGw2, VpnGw3, Unrecognized;\n\n      public static SKUName fromValue(final String text) {\n         return (SKUName) GetEnumValue.fromValueOrDefault(text, SKUName.Unrecognized);\n      }\n   }\n\n   public static enum SKUTier {\n      Basic, HighPerformance, Standard, UltraPerformance, VpnGw1, VpnGw2, VpnGw3, Unrecognized;\n\n      public static SKUTier fromValue(final String text) {\n         return (SKUTier) GetEnumValue.fromValueOrDefault(text, SKUTier.Unrecognized);\n      }\n   }\n\n   public abstract int capacity();\n   public abstract SKUName name();\n   public abstract SKUTier tier();\n\n   SKU() {\n\n   }\n\n   @SerializedNames({ \"capacity\", \"name\", \"tier\" })\n   public static SKU create(int capacity, SKUName name, SKUTier tier) {\n      return new AutoValue_SKU(capacity, name, tier);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/vpn/TunnelConnectionHealth.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain.vpn;\n\nimport org.jclouds.azurecompute.arm.domain.vpn.VirtualNetworkGatewayConnection.Status;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class TunnelConnectionHealth {\n\n   public abstract Status connectionStatus();\n   public abstract int egressBytesTransferred();\n   public abstract int ingressBytesTransferred();\n   @Nullable public abstract String lastConnectionEstablishedUtcTime();\n   public abstract String tunnel();\n\n   TunnelConnectionHealth() {\n\n   }\n\n   @SerializedNames({ \"connectionStatus\", \"egressBytesTransferred\", \"ingressBytesTransferred\",\n         \"lastConnectionEstablishedUtcTime\", \"tunnel\" })\n   public static TunnelConnectionHealth create(Status connectionStatus, int egressBytesTransferred,\n         int ingressBytesTransferred, String lastConnectionEstablishedUtcTime, String tunnel) {\n      return new AutoValue_TunnelConnectionHealth(connectionStatus, egressBytesTransferred, ingressBytesTransferred,\n            lastConnectionEstablishedUtcTime, tunnel);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/vpn/VPNClientConfiguration.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain.vpn;\n\nimport java.util.List;\n\nimport org.jclouds.azurecompute.arm.domain.AddressSpace;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\n\n@AutoValue\npublic abstract class VPNClientConfiguration {\n   @Nullable public abstract String radiusServerAddress();\n   @Nullable public abstract String radiusServerSecret();\n   @Nullable public abstract AddressSpace vpnClientAddressPool();\n   public abstract List<IPSecPolicy> vpnClientIpsecPolicies();\n   public abstract List<String> vpnClientProtocols();\n   public abstract List<VPNClientRevokedCertificate> vpnClientRevokedCertificates();\n   public abstract List<VPNClientRootCertificate> vpnClientRootCertificates();\n   \n   VPNClientConfiguration() {\n      \n   }\n\n   @SerializedNames({ \"radiusServerAddress\", \"radiusServerSecret\", \"vpnClientAddressPool\", \"vpnClientIpsecPolicies\",\n         \"vpnClientProtocols\", \"vpnClientRevokedCertificates\", \"vpnClientRootCertificates\" })\n   public static VPNClientConfiguration create(String radiusServerAddress, String radiusServerSecret,\n         AddressSpace vpnClientAddressPool, List<IPSecPolicy> vpnClientIpsecPolicies, List<String> vpnClientProtocols,\n         List<VPNClientRevokedCertificate> vpnClientRevokedCertificates,\n         List<VPNClientRootCertificate> vpnClientRootCertificates) {\n      return builder().radiusServerAddress(radiusServerAddress).radiusServerSecret(radiusServerSecret)\n            .vpnClientAddressPool(vpnClientAddressPool).vpnClientIpsecPolicies(vpnClientIpsecPolicies)\n            .vpnClientProtocols(vpnClientProtocols).vpnClientRevokedCertificates(vpnClientRevokedCertificates)\n            .vpnClientRootCertificates(vpnClientRootCertificates).build();\n   }\n   \n   public static Builder builder() {\n      return new AutoValue_VPNClientConfiguration.Builder();\n   }\n   \n   public abstract Builder toBuilder();\n   \n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder radiusServerAddress(String radiusServerAddress);\n      public abstract Builder radiusServerSecret(String radiusServerSecret);\n      public abstract Builder vpnClientAddressPool(AddressSpace vpnClientAddressPool);\n      public abstract Builder vpnClientIpsecPolicies(List<IPSecPolicy> vpnClientIpsecPolicies);\n      public abstract Builder vpnClientProtocols(List<String> vpnClientProtocols);\n      public abstract Builder vpnClientRevokedCertificates(List<VPNClientRevokedCertificate> vpnClientRevokedCertificates);\n      public abstract Builder vpnClientRootCertificates(List<VPNClientRootCertificate> vpnClientRootCertificates);\n      \n      abstract List<IPSecPolicy> vpnClientIpsecPolicies();\n      abstract List<String> vpnClientProtocols();\n      abstract List<VPNClientRevokedCertificate> vpnClientRevokedCertificates();\n      abstract List<VPNClientRootCertificate> vpnClientRootCertificates();\n      abstract VPNClientConfiguration autoBuild();\n      \n      public VPNClientConfiguration build() {\n         vpnClientIpsecPolicies(vpnClientIpsecPolicies() == null ? ImmutableList.<IPSecPolicy> of() : ImmutableList\n               .copyOf(vpnClientIpsecPolicies()));\n         vpnClientProtocols(vpnClientProtocols() == null ? ImmutableList.<String> of() : ImmutableList\n               .copyOf(vpnClientProtocols()));\n         vpnClientRevokedCertificates(vpnClientRevokedCertificates() == null ? ImmutableList\n               .<VPNClientRevokedCertificate> of() : ImmutableList.copyOf(vpnClientRevokedCertificates()));\n         vpnClientRootCertificates(vpnClientRootCertificates() == null ? ImmutableList.<VPNClientRootCertificate> of()\n               : ImmutableList.copyOf(vpnClientRootCertificates()));\n         \n         return autoBuild();\n      }\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/vpn/VPNClientRevokedCertificate.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain.vpn;\n\nimport org.jclouds.azurecompute.arm.domain.Provisionable;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class VPNClientRevokedCertificate {\n   @Nullable public abstract String id();\n   public abstract String name();\n   @Nullable public abstract String etag();\n   public abstract VPNClientRevokedCertificateProperties properties();\n\n   VPNClientRevokedCertificate() {\n\n   }\n\n   @SerializedNames({ \"id\", \"name\", \"etag\", \"properties\" })\n   public static VPNClientRevokedCertificate create(String id, String name, String etag,\n         VPNClientRevokedCertificateProperties properties) {\n      return new AutoValue_VPNClientRevokedCertificate(id, name, etag, properties);\n   }\n\n   @AutoValue\n   public abstract static class VPNClientRevokedCertificateProperties implements Provisionable {\n      public abstract String provisioningState();\n      public abstract String thumbprint();\n\n      VPNClientRevokedCertificateProperties() {\n\n      }\n\n      @SerializedNames({ \"provisioningState\", \"thumbprint\" })\n      public static VPNClientRevokedCertificateProperties create(String provisioningState, String thumbprint) {\n         return new AutoValue_VPNClientRevokedCertificate_VPNClientRevokedCertificateProperties(provisioningState,\n               thumbprint);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/vpn/VPNClientRootCertificate.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain.vpn;\n\nimport org.jclouds.azurecompute.arm.domain.Provisionable;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class VPNClientRootCertificate {\n   @Nullable public abstract String id();\n   public abstract String name();\n   @Nullable public abstract String etag();\n   public abstract VPNClientRootCertificateProperties properties();\n\n   VPNClientRootCertificate() {\n\n   }\n\n   @SerializedNames({ \"id\", \"name\", \"etag\", \"properties\" })\n   public static VPNClientRootCertificate create(String id, String name, String etag,\n         VPNClientRootCertificateProperties properties) {\n      return new AutoValue_VPNClientRootCertificate(id, name, etag, properties);\n   }\n\n   @AutoValue\n   public abstract static class VPNClientRootCertificateProperties implements Provisionable {\n      public abstract String provisioningState();\n      public abstract String publicCertData();\n\n      VPNClientRootCertificateProperties() {\n\n      }\n\n      @SerializedNames({ \"provisioningState\", \"publicCertData\" })\n      public static VPNClientRootCertificateProperties create(String provisioningState, String publicCertData) {\n         return new AutoValue_VPNClientRootCertificate_VPNClientRootCertificateProperties(provisioningState,\n               publicCertData);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/vpn/VPNType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain.vpn;\n\nimport org.jclouds.azurecompute.arm.util.GetEnumValue;\n\npublic enum VPNType {\n   PolicyBased, RouteBased, Unrecognized;\n\n   public static VPNType fromValue(final String text) {\n      return (VPNType) GetEnumValue.fromValueOrDefault(text, VPNType.Unrecognized);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/vpn/VirtualNetworkGateway.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain.vpn;\n\nimport java.util.Map;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableMap;\n\n@AutoValue\npublic abstract class VirtualNetworkGateway {\n\n   @Nullable public abstract String id();\n   public abstract String name();\n   public abstract String location();\n   @Nullable public abstract String type();\n   @Nullable public abstract Map<String, String> tags();\n   @Nullable public abstract String etag();\n   public abstract VirtualNetworkGatewayProperties properties();\n\n   VirtualNetworkGateway() {\n\n   }\n\n   @SerializedNames({ \"id\", \"name\", \"location\", \"type\", \"tags\", \"etag\", \"properties\" })\n   public static VirtualNetworkGateway create(String id, String name, String location, String type,\n         Map<String, String> tags, String etag, VirtualNetworkGatewayProperties properties) {\n      return builder(name, location, properties).id(id).type(type).tags(tags).etag(etag).build();\n   }\n\n   public abstract Builder toBuilder();\n\n   public static Builder builder(String name, String location, VirtualNetworkGatewayProperties properties) {\n      return new AutoValue_VirtualNetworkGateway.Builder().name(name).location(location).properties(properties);\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder id(String id);\n      public abstract Builder name(String name);\n      public abstract Builder location(String location);\n      public abstract Builder type(String type);\n      public abstract Builder tags(Map<String, String> tags);\n      public abstract Builder etag(String etag);\n      public abstract Builder properties(VirtualNetworkGatewayProperties properties);\n\n      abstract Map<String, String> tags();\n      abstract VirtualNetworkGateway autoBuild();\n\n      public VirtualNetworkGateway build() {\n         tags(tags() != null ? ImmutableMap.copyOf(tags()) : null);\n         return autoBuild();\n      }\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/vpn/VirtualNetworkGatewayConnection.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain.vpn;\n\nimport java.util.Map;\n\nimport org.jclouds.azurecompute.arm.util.GetEnumValue;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableMap;\n\n@AutoValue\npublic abstract class VirtualNetworkGatewayConnection {\n   \n   public static enum Status {\n      Connected, Connecting, NotConnected, Unknown;\n\n      public static Status fromValue(final String text) {\n         return (Status) GetEnumValue.fromValueOrDefault(text, Status.Unknown);\n      }\n   }\n\n   public static enum Type {\n      ExpressRoute, IPsec, VPNClient, Vnet2Vnet, Unrecognized;\n\n      public static Type fromValue(final String text) {\n         return (Type) GetEnumValue.fromValueOrDefault(text, Type.Unrecognized);\n      }\n   }\n\n   @Nullable public abstract String id();\n   public abstract String name();\n   public abstract String location();\n   @Nullable public abstract String type();\n   @Nullable public abstract Map<String, String> tags();\n   @Nullable public abstract String etag();\n   public abstract VirtualNetworkGatewayConnectionProperties properties();\n\n   VirtualNetworkGatewayConnection() {\n\n   }\n\n   @SerializedNames({ \"id\", \"name\", \"location\", \"type\", \"tags\", \"etag\", \"properties\" })\n   public static VirtualNetworkGatewayConnection create(String id, String name, String location, String type,\n         Map<String, String> tags, String etag, VirtualNetworkGatewayConnectionProperties properties) {\n      return builder(name, location, properties).id(id).type(type).tags(tags).etag(etag).build();\n   }\n\n   public abstract Builder toBuilder();\n\n   public static Builder builder(String name, String location, VirtualNetworkGatewayConnectionProperties properties) {\n      return new AutoValue_VirtualNetworkGatewayConnection.Builder().name(name).location(location)\n            .properties(properties);\n   }\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder id(String id);\n      public abstract Builder name(String name);\n      public abstract Builder location(String location);\n      public abstract Builder type(String type);\n      public abstract Builder tags(Map<String, String> tags);\n      public abstract Builder etag(String etag);\n      public abstract Builder properties(VirtualNetworkGatewayConnectionProperties properties);\n\n      abstract Map<String, String> tags();\n      abstract VirtualNetworkGatewayConnection autoBuild();\n\n      public VirtualNetworkGatewayConnection build() {\n         tags(tags() != null ? ImmutableMap.copyOf(tags()) : null);\n         return autoBuild();\n      }\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/vpn/VirtualNetworkGatewayConnectionProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain.vpn;\n\nimport java.util.List;\n\nimport org.jclouds.azurecompute.arm.domain.IdReference;\nimport org.jclouds.azurecompute.arm.domain.Provisionable;\nimport org.jclouds.azurecompute.arm.domain.vpn.VirtualNetworkGatewayConnection.Status;\nimport org.jclouds.azurecompute.arm.domain.vpn.VirtualNetworkGatewayConnection.Type;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\n\n@AutoValue\npublic abstract class VirtualNetworkGatewayConnectionProperties implements Provisionable {\n\n   @Nullable public abstract String authorizationKey();\n   @Nullable public abstract Status connectionStatus();\n   public abstract Type connectionType();\n   @Nullable public abstract Integer egressBytesTransferred();\n   @Nullable public abstract Integer ingressBytesTransferred();\n   public abstract boolean enableBGP();\n   public abstract List<IPSecPolicy> ipsecPolicies();\n   @Nullable public abstract IdReference peer();\n   @Nullable public abstract String provisioningState();\n   @Nullable public abstract String resourceGuid();\n   @Nullable public abstract Integer routingWeight();\n   @Nullable public abstract String sharedKey();\n   public abstract List<TunnelConnectionHealth> tunnelConnectionStatus();\n   public abstract boolean usePolicyBasedTrafficSelectors();\n   public abstract IdReference localNetworkGateway2();\n   public abstract IdReference virtualNetworkGateway1();\n   @Nullable public abstract IdReference virtualNetworkGateway2();\n\n   VirtualNetworkGatewayConnectionProperties() {\n\n   }\n   \n   @SerializedNames({ \"authorizationKey\", \"connectionStatus\", \"connectionType\", \"egressBytesTransferred\",\n         \"ingressBytesTransferred\", \"enableBGP\", \"ipsecPolicies\", \"peer\", \"provisioningState\", \"resourceGuid\",\n         \"routingWeight\", \"sharedKey\", \"tunnelConnectionStatus\", \"usePolicyBasedTrafficSelectors\",\n         \"localNetworkGateway2\", \"virtualNetworkGateway1\", \"virtualNetworkGateway2\" })\n   public static VirtualNetworkGatewayConnectionProperties create(String authorizationKey, Status connectionStatus,\n         Type connectionType, Integer egressBytesTransferred, Integer ingressBytesTransferred, boolean enableBGP,\n         List<IPSecPolicy> ipsecPolicies, IdReference peer, String provisioningState, String resourceGuid,\n         Integer routingWeight, String sharedKey, List<TunnelConnectionHealth> tunnelConnectionStatus,\n         boolean usePolicyBasedTrafficSelectors, IdReference localNetworkGateway2, IdReference virtualNetworkGateway1,\n         IdReference virtualNetworkGateway2) {\n      return builder(connectionType, enableBGP, usePolicyBasedTrafficSelectors, localNetworkGateway2,\n            virtualNetworkGateway1).authorizationKey(authorizationKey).connectionStatus(connectionStatus)\n            .egressBytesTransferred(egressBytesTransferred).ingressBytesTransferred(ingressBytesTransferred)\n            .ipsecPolicies(ipsecPolicies).peer(peer).provisioningState(provisioningState).resourceGuid(resourceGuid)\n            .routingWeight(routingWeight).sharedKey(sharedKey).tunnelConnectionStatus(tunnelConnectionStatus)\n            .virtualNetworkGateway2(virtualNetworkGateway2).build();\n   }\n   \n   public static Builder builder(Type connectionType, boolean enableBGP, boolean usePolicyBasedTrafficSelectors,\n         IdReference localNetworkGateway2, IdReference virtualNetworkGateway1) {\n      return new AutoValue_VirtualNetworkGatewayConnectionProperties.Builder().connectionType(connectionType)\n            .enableBGP(enableBGP).usePolicyBasedTrafficSelectors(usePolicyBasedTrafficSelectors)\n            .localNetworkGateway2(localNetworkGateway2).virtualNetworkGateway1(virtualNetworkGateway1)\n            .ipsecPolicies(ImmutableList.<IPSecPolicy> of())\n            .tunnelConnectionStatus(ImmutableList.<TunnelConnectionHealth> of());\n   }\n\n   public abstract Builder toBuilder();\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder authorizationKey(String authorizationKey);\n      public abstract Builder connectionStatus(Status connectionStatus);\n      public abstract Builder connectionType(Type connectionType);\n      public abstract Builder egressBytesTransferred(Integer egressBytesTransferred);\n      public abstract Builder ingressBytesTransferred(Integer ingressBytesTransferred);\n      public abstract Builder enableBGP(boolean enableBGP);\n      public abstract Builder ipsecPolicies(List<IPSecPolicy> ipsecPolicies);\n      public abstract Builder peer(IdReference peer);\n      public abstract Builder provisioningState(String provisioningState);\n      public abstract Builder resourceGuid(String resourceGuid);\n      public abstract Builder routingWeight(Integer routingWeight);\n      public abstract Builder sharedKey(String sharedKey);\n      public abstract Builder tunnelConnectionStatus(List<TunnelConnectionHealth> tunnelConnectionStatus);\n      public abstract Builder usePolicyBasedTrafficSelectors(boolean usePolicyBasedTrafficSelectors);\n      public abstract Builder localNetworkGateway2(IdReference localNetworkGateway2);\n      public abstract Builder virtualNetworkGateway1(IdReference virtualNetworkGateway1);\n      public abstract Builder virtualNetworkGateway2(IdReference virtualNetworkGateway2);\n\n      abstract List<IPSecPolicy> ipsecPolicies();\n      abstract List<TunnelConnectionHealth> tunnelConnectionStatus();\n      abstract VirtualNetworkGatewayConnectionProperties autoBuild();\n\n      public VirtualNetworkGatewayConnectionProperties build() {\n         ipsecPolicies(ipsecPolicies() == null ? ImmutableList.<IPSecPolicy> of() : ImmutableList\n               .copyOf(ipsecPolicies()));\n         tunnelConnectionStatus(tunnelConnectionStatus() == null ? ImmutableList.<TunnelConnectionHealth> of()\n               : ImmutableList.copyOf(tunnelConnectionStatus()));\n         return autoBuild();\n      }\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/vpn/VirtualNetworkGatewayProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain.vpn;\n\nimport java.util.List;\n\nimport org.jclouds.azurecompute.arm.domain.IdReference;\nimport org.jclouds.azurecompute.arm.domain.IpAllocationMethod;\nimport org.jclouds.azurecompute.arm.domain.Provisionable;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\n\n@AutoValue\npublic abstract class VirtualNetworkGatewayProperties implements Provisionable {\n   \n   @Nullable public abstract Boolean activeActive();\n   @Nullable public abstract BGPSettings bgpSettings();\n   public abstract boolean enableBGP();\n   @Nullable public abstract IdReference gatewayDefaultSite();\n   public abstract VirtualNetworkGatewayType gatewayType();\n   public abstract List<IpConfiguration> ipConfigurations();\n   @Nullable public abstract String provisioningState();\n   @Nullable public abstract String resourceGuid();\n   public abstract SKU sku();\n   @Nullable public abstract VPNClientConfiguration vpnClientConfiguration();\n   @Nullable public abstract VPNType vpnType();\n\n   VirtualNetworkGatewayProperties() {\n\n   }\n   \n   @SerializedNames({ \"activeActive\", \"bgpSettings\", \"enableBgp\", \"gatewayDefaultSite\", \"gatewayType\",\n         \"ipConfigurations\", \"provisioningState\", \"resourceGuid\", \"sku\", \"vpnClientConfiguration\", \"vpnType\" })\n   public static VirtualNetworkGatewayProperties create(Boolean activeActive, BGPSettings bgpSettings,\n         boolean enableBGP, IdReference gatewayDefaultSite, VirtualNetworkGatewayType gatewayType,\n         List<IpConfiguration> ipConfigurations, String provisioningState, String resourceGuid, SKU sku,\n         VPNClientConfiguration vpnClientConfiguration, VPNType vpnType) {\n      return builder(enableBGP, gatewayType, sku).activeActive(activeActive).bgpSettings(bgpSettings)\n            .gatewayDefaultSite(gatewayDefaultSite).ipConfigurations(ipConfigurations)\n            .provisioningState(provisioningState).resourceGuid(resourceGuid)\n            .vpnClientConfiguration(vpnClientConfiguration).vpnType(vpnType).build();\n   }\n   \n   public static Builder builder(boolean enableBGP, VirtualNetworkGatewayType virtualNetworkGatewayType, SKU sku) {\n      return new AutoValue_VirtualNetworkGatewayProperties.Builder().enableBGP(enableBGP)\n            .gatewayType(virtualNetworkGatewayType).sku(sku).ipConfigurations(ImmutableList.<IpConfiguration> of());\n   }\n   \n   public abstract Builder toBuilder();\n   \n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder activeActive( Boolean activeActive);\n      public abstract Builder bgpSettings(BGPSettings bgpSettings);\n      public abstract Builder enableBGP(boolean enableBG);\n      public abstract Builder gatewayDefaultSite(IdReference gatewayDefaultSite);\n      public abstract Builder gatewayType(VirtualNetworkGatewayType gatewayType);\n      public abstract Builder ipConfigurations(List<IpConfiguration> ipConfigurations);\n      public abstract Builder provisioningState(String provisioningState);\n      public abstract Builder resourceGuid(String resourceGuid);\n      public abstract Builder sku(SKU sku);\n      public abstract Builder vpnClientConfiguration(VPNClientConfiguration vpnClientConfiguration);\n      public abstract Builder vpnType(VPNType vpnType);\n      \n      abstract List<IpConfiguration> ipConfigurations();\n      abstract VirtualNetworkGatewayProperties autoBuild();\n\n      public VirtualNetworkGatewayProperties build() {\n         ipConfigurations(ipConfigurations() == null ? ImmutableList.<IpConfiguration> of() : ImmutableList\n               .copyOf(ipConfigurations()));\n         return autoBuild();\n      }\n   }\n   \n   @AutoValue\n   public abstract static class IpConfiguration {\n      @Nullable public abstract String id();\n      public abstract String name();\n      @Nullable public abstract String etag();\n      public abstract IpConfigurationProperties properties();\n      \n      IpConfiguration() {\n\n      }\n\n      @SerializedNames({ \"id\", \"name\", \"etag\", \"properties\" })\n      public static IpConfiguration create(String id, String name, String etag, IpConfigurationProperties properties) {\n         return new AutoValue_VirtualNetworkGatewayProperties_IpConfiguration(id, name, etag, properties);\n      }\n      \n      @AutoValue\n      public abstract static class IpConfigurationProperties implements Provisionable {\n         public abstract IpAllocationMethod privateIPAllocationMethod();\n         @Nullable public abstract String provisioningState();\n         @Nullable public abstract IdReference publicIPAddress();\n         @Nullable public abstract IdReference subnet();\n         \n         @SerializedNames({ \"privateIPAllocationMethod\", \"provisioningState\", \"publicIPAddress\", \"subnet\" })\n         public static IpConfigurationProperties create(IpAllocationMethod privateIPAllocationMethod,\n               String provisioningState, IdReference publicIPAddress, IdReference subnet) {\n            return builder(privateIPAllocationMethod).provisioningState(provisioningState)\n                  .publicIPAddress(publicIPAddress).subnet(subnet).build();\n         }\n\n         IpConfigurationProperties() {\n\n         }\n         \n         public static Builder builder(IpAllocationMethod privateIPAllocationMethod) {\n            return new AutoValue_VirtualNetworkGatewayProperties_IpConfiguration_IpConfigurationProperties.Builder()\n                  .privateIPAllocationMethod(privateIPAllocationMethod);\n         }\n         \n         public abstract Builder toBuilder();\n         \n         @AutoValue.Builder\n         public abstract static class Builder {\n            public abstract Builder privateIPAllocationMethod(IpAllocationMethod privateIPAllocationMethod);\n            public abstract Builder provisioningState(String provisioningState);\n            public abstract Builder publicIPAddress(IdReference publicIPAddress);\n            public abstract Builder subnet(IdReference subnet);\n\n            public abstract IpConfigurationProperties build();\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/domain/vpn/VirtualNetworkGatewayType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain.vpn;\n\nimport org.jclouds.azurecompute.arm.util.GetEnumValue;\n\npublic enum VirtualNetworkGatewayType {\n   ExpressRoute, Vpn, Unrecognized;\n\n   public static VirtualNetworkGatewayType fromValue(final String text) {\n      return (VirtualNetworkGatewayType) GetEnumValue.fromValueOrDefault(text,\n            VirtualNetworkGatewayType.Unrecognized);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/exceptions/AzureComputeRateLimitExceededException.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.exceptions;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rest.RateLimitExceededException;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Multimap;\nimport com.google.common.collect.Multimaps;\n\n/**\n * Provides detailed information for rate limit exceptions.\n */\n@Beta\npublic class AzureComputeRateLimitExceededException extends RateLimitExceededException {\n   private static final long serialVersionUID = 1L;\n   private static final String RATE_LIMIT_HEADER_PREFIX = \"x-ms-ratelimit-remaining-\";\n\n   public AzureComputeRateLimitExceededException(HttpResponse response) {\n      super(response.getStatusLine() + \"\\n\" + rateLimitHeaders(response));\n   }\n\n   public AzureComputeRateLimitExceededException(HttpResponse response, Throwable cause) {\n      super(response.getStatusLine() + \"\\n\" + rateLimitHeaders(response), cause);\n   }\n\n   private static Multimap<String, String> rateLimitHeaders(HttpResponse response) {\n      return Multimaps.filterKeys(response.getHeaders(), new Predicate<String>() {\n         @Override\n         public boolean apply(String input) {\n            return input.startsWith(RATE_LIMIT_HEADER_PREFIX);\n         }\n      });\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/features/ActivityLogAlertApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport java.net.URI;\nimport java.util.List;\nimport java.util.Map;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks;\nimport org.jclouds.azurecompute.arm.domain.ActivityLogAlert;\nimport org.jclouds.azurecompute.arm.domain.ActivityLogAlertProperties;\nimport org.jclouds.azurecompute.arm.filters.ApiVersionFilter;\nimport org.jclouds.azurecompute.arm.functions.URIParser;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\n/**\n * The Activity Log Alert API includes operations for managing activity log type\n * alert rules in your subscription.\n *\n * @see <a href=\n *      \"https://docs.microsoft.com/en-us/rest/api/monitor/activity-log-alerts\">docs</a>\n */\n@Path(\"/resourcegroups/{resourcegroup}/providers/Microsoft.Insights/activityLogAlerts\")\n@RequestFilters({ OAuthFilter.class, ApiVersionFilter.class })\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface ActivityLogAlertApi {\n\n\t@Named(\"activitylogalert:get\")\n\t@GET\n\t@Path(\"/{name}\")\n\t@Fallback(Fallbacks.NullOnNotFoundOr404.class)\n\tActivityLogAlert get(@PathParam(\"name\") String name);\n\n\t@Named(\"activitylogalert:list\")\n\t@GET\n\t@SelectJson(\"value\")\n\t@Fallback(Fallbacks.EmptyListOnNotFoundOr404.class)\n\tList<ActivityLogAlert> list();\n\n\t@Named(\"activitylogalert:createOrUpdate\")\n\t@PUT\n\t@MapBinder(BindToJsonPayload.class)\n\t@Path(\"/{activityLogAlertName}\")\n\t@QueryParams(keys = \"validating\", values = \"false\")\n\tActivityLogAlert createOrUpdate(@PathParam(\"activityLogAlertName\") String activityLogAlertName,\n\t\t\t@PayloadParam(\"properties\") ActivityLogAlertProperties properties,\n\t\t\t@PayloadParam(\"tags\") Map<String, String> tags, @PayloadParam(\"location\") String location);\n\n\t@Named(\"activitylogalert:delete\")\n\t@DELETE\n\t@Path(\"/{activityLogAlertName}\")\n\t@ResponseParser(URIParser.class)\n\t@Fallback(Fallbacks.NullOnNotFoundOr404.class)\n\tURI delete(@PathParam(\"activityLogAlertName\") String activityLogAlertName);\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/features/AlertApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport java.util.List;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyListOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.azurecompute.arm.domain.Alert;\nimport org.jclouds.azurecompute.arm.domain.AlertModification;\nimport org.jclouds.azurecompute.arm.domain.AlertSummary;\nimport org.jclouds.azurecompute.arm.filters.ApiVersionFilter;\nimport org.jclouds.azurecompute.arm.options.AlertRequestOptions;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\n/**\n * This Azure Resource Manager API provides all the alerts available for a given\n * resource\n * <p/>\n *\n * @see <a href=\n *      \"https://docs.microsoft.com/en-us/rest/api/monitor/alertsmanagement/alerts\">docs</a>\n */\n@Path(\"/{resourceid}\")\n@RequestFilters({ OAuthFilter.class, ApiVersionFilter.class })\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface AlertApi {\n\t@Named(\"alerts:getAll\")\n\t@Path(\"/providers/Microsoft.AlertsManagement/alerts\")\n\t@GET\n\t@SelectJson(\"value\")\n\t@Fallback(EmptyListOnNotFoundOr404.class)\n\tList<Alert> list(@Nullable AlertRequestOptions... getAllOptions);\n\n\t@Named(\"alerts:getbyid\")\n\t@Path(\"/providers/Microsoft.AlertsManagement/alerts/{alertId}\")\n\t@GET\n\t@Fallback(NullOnNotFoundOr404.class)\n\tAlert get(@PathParam(\"alertId\") String alertId);\n\n\t@Named(\"alerts:changestate\")\n\t@Path(\"/providers/Microsoft.AlertsManagement/alerts/{alertId}/changestate\")\n\t@POST\n\t@Fallback(NullOnNotFoundOr404.class)\n\tAlert changeState(@PathParam(\"alertId\") String alertId, @QueryParam(\"newState\") String newState);\n\n\t@Named(\"alerts:history\")\n\t@Path(\"/providers/Microsoft.AlertsManagement/alerts/{alertId}/history\")\n\t@GET\n\t@Fallback(NullOnNotFoundOr404.class)\n\tAlertModification getHistory(@PathParam(\"alertId\") String alertId);\n\n\t@Named(\"alerts:summary\")\n\t@Path(\"providers/Microsoft.AlertsManagement/alertsSummary\")\n\t@GET\n\t@Fallback(NullOnNotFoundOr404.class)\n\tAlertSummary getSummary(AlertRequestOptions... getSummaryOptions);\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/features/AvailabilitySetApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport java.io.Closeable;\nimport java.net.URI;\nimport java.util.List;\nimport java.util.Map;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyListOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.azurecompute.arm.domain.AvailabilitySet;\nimport org.jclouds.azurecompute.arm.domain.AvailabilitySet.AvailabilitySetProperties;\nimport org.jclouds.azurecompute.arm.domain.AvailabilitySet.SKU;\nimport org.jclouds.azurecompute.arm.filters.ApiVersionFilter;\nimport org.jclouds.azurecompute.arm.functions.URIParser;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\n@Path(\"/resourcegroups/{resourcegroup}/providers/Microsoft.Compute/availabilitySets\")\n@RequestFilters({ OAuthFilter.class, ApiVersionFilter.class })\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface AvailabilitySetApi extends Closeable {\n\n   @Named(\"availabilityset:list\")\n   @GET\n   @SelectJson(\"value\")\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   List<AvailabilitySet> list();\n\n   @Named(\"availabilityset:get\")\n   @Path(\"/{name}\")\n   @GET\n   @Fallback(NullOnNotFoundOr404.class)\n   AvailabilitySet get(@PathParam(\"name\") String name);\n\n   @Named(\"availabilityset:createOrUpdate\")\n   @MapBinder(BindToJsonPayload.class)\n   @Path(\"/{name}\")\n   @PUT\n   AvailabilitySet createOrUpdate(@PathParam(\"name\") String name,\n         @Nullable @PayloadParam(\"sku\") SKU sku,\n         @PayloadParam(\"location\") String location,\n         @Nullable @PayloadParam(\"tags\") Map<String, String> tags,\n         @PayloadParam(\"properties\") AvailabilitySetProperties properties);\n\n   @Named(\"availabilityset:delete\")\n   @Path(\"/{name}\")\n   @DELETE\n   @ResponseParser(URIParser.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   URI delete(@PathParam(\"name\") String name);\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/features/DeploymentApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks;\nimport org.jclouds.Fallbacks.EmptyListOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.azurecompute.arm.domain.Deployment;\nimport org.jclouds.azurecompute.arm.filters.ApiVersionFilter;\nimport org.jclouds.azurecompute.arm.functions.URIParser;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\n\n/**\n * - create deployment\n * - delete deployment\n * - get information about deployment\n */\n@Path(\"/resourcegroups/{resourcegroup}/providers/microsoft.resources/deployments\")\n@RequestFilters({ OAuthFilter.class, ApiVersionFilter.class })\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface DeploymentApi {\n\n   /**\n    * The Create Template Deployment operation starts the process of an ARM Template deployment.\n    * It then returns a Deployment object.\n    */\n   @Named(\"deployment:create\")\n   @Path(\"/{deploymentname}\")\n   @Payload(\"{template}\")\n   @PUT\n   @Produces(MediaType.APPLICATION_JSON)\n   Deployment create(@PathParam(\"deploymentname\") String deploymentname,\n                               @PayloadParam(\"template\") String template);\n\n   /**\n    * Get Deployment Information returns information about the specified deployment.\n    */\n   @Named(\"deployment:get\")\n   @Path(\"/{deploymentname}\")\n   @GET\n   @Fallback(NullOnNotFoundOr404.class)\n   Deployment get(@PathParam(\"deploymentname\") String deploymentname);\n\n   /**\n    * Validate Deployment validates deployment template before deployment\n    */\n   @Named(\"deployment:validate\")\n   @Path(\"/{deploymentname}/validate\")\n   @Payload(\"{template}\")\n   @POST\n   @Produces(MediaType.APPLICATION_JSON)\n   Deployment validate(@PathParam(\"deploymentname\") String deploymentname,\n                                 @PayloadParam(\"template\") String template);\n\n   /**\n    * List all deployments in a resource group\n    */\n   @Named(\"deployment:list\")\n   @GET\n   @SelectJson(\"value\")\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   List<Deployment> list();\n\n   /**\n    * The Delete Template Deployment operation starts the process of an ARM Template removal.\n    */\n   @Named(\"deployment:delete\")\n   @DELETE\n   @ResponseParser(URIParser.class)\n   @Path(\"/{deploymentname}\")\n   @Fallback(Fallbacks.NullOnNotFoundOr404.class)\n   URI delete(@PathParam(\"deploymentname\") String deploymentname);\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/features/DiskApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport java.net.URI;\nimport java.util.List;\nimport java.util.Map;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyListOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.azurecompute.arm.domain.Disk;\nimport org.jclouds.azurecompute.arm.domain.DiskProperties;\nimport org.jclouds.azurecompute.arm.domain.DiskSku;\nimport org.jclouds.azurecompute.arm.filters.ApiVersionFilter;\nimport org.jclouds.azurecompute.arm.functions.URIParser;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\n@Path(\"/resourcegroups/{resourcegroup}/providers/Microsoft.Compute/disks\")\n@RequestFilters({ OAuthFilter.class, ApiVersionFilter.class })\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface DiskApi {\n\n   @Named(\"disk:list\")\n   @SelectJson(\"value\")\n   @GET\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   List<Disk> list();\n\n   @Named(\"disk:create_or_update\")\n   @PUT\n   @MapBinder(BindToJsonPayload.class)\n   @Path(\"/{diskName}\")\n   Disk createOrUpdate(@PathParam(\"diskName\") String diskName,\n                       @PayloadParam(\"location\") String location,\n                       @PayloadParam(\"properties\") DiskProperties properties);\n\n   @Named(\"disk:create_or_update\")\n   @PUT\n   @MapBinder(BindToJsonPayload.class)\n   @Path(\"/{diskName}\")\n   Disk createOrUpdate(@PathParam(\"diskName\") String diskName,\n                       @PayloadParam(\"location\") String location,\n                       @Nullable @PayloadParam(\"tags\") Map<String, String> tags,\n                       @PayloadParam(\"properties\") DiskProperties properties);\n\n   @Named(\"disk:create_or_update\")\n   @PUT\n   @MapBinder(BindToJsonPayload.class)\n   @Path(\"/{diskName}\")\n   Disk createOrUpdate(@PathParam(\"diskName\") String diskName,\n           @PayloadParam(\"location\") String location,\n           @Nullable @PayloadParam(\"tags\") Map<String, String> tags,\n           @PayloadParam(\"properties\") DiskProperties properties,\n           @Nullable @PayloadParam(\"sku\") DiskSku sku);\n\n   @Named(\"disk:get\")\n   @Path(\"/{diskName}\")\n   @GET\n   @Fallback(NullOnNotFoundOr404.class)\n   Disk get(@PathParam(\"diskName\") String diskName);\n\n   @Named(\"disk:delete\")\n   @Path(\"/{diskName}\")\n   @DELETE\n   @ResponseParser(URIParser.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   URI delete(@PathParam(\"diskName\") String diskName);\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/features/GraphRBACApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.azurecompute.arm.config.GraphRBAC;\nimport org.jclouds.azurecompute.arm.config.OAuthResource;\nimport org.jclouds.azurecompute.arm.domain.ServicePrincipal;\nimport org.jclouds.azurecompute.arm.filters.ApiVersionFilter;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.Endpoint;\nimport org.jclouds.rest.annotations.OnlyElement;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\nimport com.google.inject.name.Named;\n\n@RequestFilters({ OAuthFilter.class, ApiVersionFilter.class })\n@Consumes(MediaType.APPLICATION_JSON)\n@Endpoint(GraphRBAC.class)\n@OAuthResource(value = GraphRBAC.STANDARD_ENDPOINT, chinaEndpoint = GraphRBAC.CHINA_ENDPOINT)\npublic interface GraphRBACApi {\n\n   @Named(\"servicePrincipal:get\")\n   @GET\n   @Path(\"/servicePrincipals\")\n   @QueryParams(keys = \"$filter\", values = \"appId eq '{jclouds.identity}'\")\n   @SelectJson(\"value\")\n   @OnlyElement\n   ServicePrincipal getCurrentServicePrincipal();\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/features/ImageApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyListOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.azurecompute.arm.domain.Image;\nimport org.jclouds.azurecompute.arm.domain.ImageProperties;\nimport org.jclouds.azurecompute.arm.filters.ApiVersionFilter;\nimport org.jclouds.azurecompute.arm.functions.URIParser;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\n@Path(\"/resourcegroups/{resourcegroup}/providers/Microsoft.Compute/images\")\n@RequestFilters({ OAuthFilter.class, ApiVersionFilter.class })\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface ImageApi {\n\n   @Named(\"image:list\")\n   @SelectJson(\"value\")\n   @GET\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   List<Image> list();\n\n   @Named(\"image:create_or_update\")\n   @PUT\n   @MapBinder(BindToJsonPayload.class)\n   @Path(\"/{imageName}\")\n   Image createOrUpdate(@PathParam(\"imageName\") String imageName,\n                       @PayloadParam(\"location\") String location,\n                       @PayloadParam(\"properties\") ImageProperties properties);\n\n   @Named(\"image:get\")\n   @Path(\"/{imageName}\")\n   @GET\n   @Fallback(NullOnNotFoundOr404.class)\n   Image get(@PathParam(\"imageName\") String imageName);\n\n   @Named(\"image:delete\")\n   @Path(\"/{imageName}\")\n   @DELETE\n   @ResponseParser(URIParser.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   URI delete(@PathParam(\"imageName\") String imageName);\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/features/JobApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport java.io.Closeable;\nimport java.net.URI;\nimport java.util.List;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks;\nimport org.jclouds.azurecompute.arm.domain.ResourceDefinition;\nimport org.jclouds.azurecompute.arm.functions.ParseJobStatus;\nimport org.jclouds.azurecompute.arm.functions.ParseJobStatus.JobStatus;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.EndpointParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\n\n/**\n * The Azure Resource Manager API checks for job status and progress.\n */\n@RequestFilters(OAuthFilter.class)\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface JobApi extends Closeable {\n   \n   @GET\n   @ResponseParser(ParseJobStatus.class)\n   JobStatus jobStatus(@EndpointParam URI jobURI);\n\n   /**\n    * Get status of captured custom image after capture call\n    */\n   @GET\n   @Fallback(Fallbacks.EmptyListOnNotFoundOr404.class)\n   @SelectJson(\"resources\")\n   List<ResourceDefinition> captureStatus(@EndpointParam URI jobURI);\n\n}\n\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/features/LoadBalancerApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport java.net.URI;\nimport java.util.List;\nimport java.util.Map;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyListOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.azurecompute.arm.domain.loadbalancer.LoadBalancer;\nimport org.jclouds.azurecompute.arm.domain.loadbalancer.LoadBalancer.SKU;\nimport org.jclouds.azurecompute.arm.domain.loadbalancer.LoadBalancerProperties;\nimport org.jclouds.azurecompute.arm.filters.ApiVersionFilter;\nimport org.jclouds.azurecompute.arm.functions.URIParser;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\n/**\n * The Load Balancer API includes operations for managing the load balancers in your subscription.\n *\n * @see <a href=\"https://docs.microsoft.com/en-us/rest/api/load-balancer/loadbalancers\">docs</a>\n */\n@RequestFilters({ OAuthFilter.class, ApiVersionFilter.class })\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface LoadBalancerApi {\n\n   @Named(\"loadbalancer:list\")\n   @GET\n   @Path(\"/resourcegroups/{resourcegroup}/providers/Microsoft.Network/loadBalancers\")\n   @SelectJson(\"value\")\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   List<LoadBalancer> list();\n\n   @Named(\"loadbalancer:listall\")\n   @GET\n   @Path(\"/providers/Microsoft.Network/loadBalancers\")\n   @SelectJson(\"value\")\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   List<LoadBalancer> listAll();\n\n   @Named(\"loadbalancer:get\")\n   @Path(\"/resourcegroups/{resourcegroup}/providers/Microsoft.Network/loadBalancers/{loadbalancername}\")\n   @GET\n   @Fallback(NullOnNotFoundOr404.class)\n   LoadBalancer get(@PathParam(\"loadbalancername\") String lbName);\n\n   @Named(\"loadbalancer:createOrUpdate\")\n   @Path(\"/resourcegroups/{resourcegroup}/providers/Microsoft.Network/loadBalancers/{loadbalancername}\")\n   @PUT\n   @MapBinder(BindToJsonPayload.class)\n   LoadBalancer createOrUpdate(@PathParam(\"loadbalancername\") String lbName, @PayloadParam(\"location\") String location, @Nullable @PayloadParam(\"tags\") Map<String, String> tags, @Nullable @PayloadParam(\"sku\") SKU sku,\n         @PayloadParam(\"properties\") LoadBalancerProperties properties);\n\n   @Named(\"loadbalancer:delete\")\n   @Path(\"/resourcegroups/{resourcegroup}/providers/Microsoft.Network/loadBalancers/{loadbalancername}\")\n   @DELETE\n   @ResponseParser(URIParser.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   URI delete(@PathParam(\"loadbalancername\") String lbName);\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/features/LocalNetworkGatewayApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport java.io.Closeable;\nimport java.net.URI;\nimport java.util.List;\nimport java.util.Map;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyListOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.azurecompute.arm.domain.vpn.LocalNetworkGateway;\nimport org.jclouds.azurecompute.arm.domain.vpn.LocalNetworkGatewayProperties;\nimport org.jclouds.azurecompute.arm.filters.ApiVersionFilter;\nimport org.jclouds.azurecompute.arm.functions.URIParser;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\n@Path(\"/resourcegroups/{resourcegroup}/providers/Microsoft.Network/localNetworkGateways\")\n@RequestFilters({ OAuthFilter.class, ApiVersionFilter.class })\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface LocalNetworkGatewayApi extends Closeable {\n\n   @Named(\"localnetworkgateway:list\")\n   @GET\n   @SelectJson(\"value\")\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   List<LocalNetworkGateway> list();\n\n   @Named(\"localnetworkgateway:get\")\n   @Path(\"/{name}\")\n   @GET\n   @Fallback(NullOnNotFoundOr404.class)\n   LocalNetworkGateway get(@PathParam(\"name\") String name);\n\n   @Named(\"localnetworkgateway:createOrUpdate\")\n   @MapBinder(BindToJsonPayload.class)\n   @Path(\"/{name}\")\n   @PUT\n   LocalNetworkGateway createOrUpdate(@PathParam(\"name\") String name, @PayloadParam(\"location\") String location,\n         @Nullable @PayloadParam(\"tags\") Map<String, String> tags,\n         @PayloadParam(\"properties\") LocalNetworkGatewayProperties properties);\n\n   @Named(\"localnetworkgateway:delete\")\n   @Path(\"/{name}\")\n   @DELETE\n   @ResponseParser(URIParser.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   URI delete(@PathParam(\"name\") String name);\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/features/LocationApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport java.util.List;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyListOnNotFoundOr404;\nimport org.jclouds.azurecompute.arm.domain.Location;\nimport org.jclouds.azurecompute.arm.filters.ApiVersionFilter;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\n/**\n * This Azure Resource Manager API provides all of the locations that are available for resource providers\n * <p/>\n *\n * @see <a href=\"https://msdn.microsoft.com/en-US/library/azure/dn790540.aspx\">docs</a>\n */\n@Path(\"/locations\")\n@RequestFilters({ OAuthFilter.class, ApiVersionFilter.class })\n@Produces(MediaType.APPLICATION_JSON)\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface LocationApi {\n\n   /**\n    * The List Locations operation lists all of the data center locations that are valid for your subscription.\n    */\n   @Named(\"location:list\")\n   @GET\n   @SelectJson(\"value\")\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   List<Location> list();\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/features/MetricAlertApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport java.net.URI;\nimport java.util.List;\nimport java.util.Map;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks;\nimport org.jclouds.azurecompute.arm.domain.MetricAlert;\nimport org.jclouds.azurecompute.arm.domain.MetricAlertProperties;\nimport org.jclouds.azurecompute.arm.filters.ApiVersionFilter;\nimport org.jclouds.azurecompute.arm.functions.URIParser;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\n/**\n * The Metric Alert API includes operations for managing metric type alert rules\n * in your subscription.\n *\n * @see <a href=\n *      \"https://docs.microsoft.com/en-us/rest/api/monitor/metric-alerts\">docs</a>\n */\n@Path(\"/resourcegroups/{resourcegroup}/providers/Microsoft.Insights/metricAlerts\")\n@RequestFilters({ OAuthFilter.class, ApiVersionFilter.class })\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface MetricAlertApi {\n\n\t@Named(\"metricalert:get\")\n\t@GET\n\t@Path(\"/{name}\")\n\t@Fallback(Fallbacks.NullOnNotFoundOr404.class)\n\tMetricAlert get(@PathParam(\"name\") String name);\n\n\t@Named(\"metricalert:list\")\n\t@GET\n\t@SelectJson(\"value\")\n\t@Fallback(Fallbacks.EmptyListOnNotFoundOr404.class)\n\tList<MetricAlert> list();\n\n\t@Named(\"metricalert:createOrUpdate\")\n\t@PUT\n\t@MapBinder(BindToJsonPayload.class)\n\t@Path(\"/{ruleName}\")\n\t@QueryParams(keys = \"validating\", values = \"false\")\n\tMetricAlert createOrUpdate(@PathParam(\"ruleName\") String ruleName,\n\t\t\t@PayloadParam(\"properties\") MetricAlertProperties properties,\n\t\t\t@PayloadParam(\"tags\") Map<String, String> tags, @PayloadParam(\"location\") String location);\n\n\t@Named(\"metricalert:delete\")\n\t@DELETE\n\t@Path(\"/{ruleName}\")\n\t@ResponseParser(URIParser.class)\n\t@Fallback(Fallbacks.NullOnNotFoundOr404.class)\n\tURI delete(@PathParam(\"ruleName\") String ruleName);\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/features/MetricDefinitionsApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport java.util.List;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyListOnNotFoundOr404;\nimport org.jclouds.azurecompute.arm.domain.MetricDefinition;\nimport org.jclouds.azurecompute.arm.filters.ApiVersionFilter;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\n/**\n * This Azure Resource Manager API provides all the metric definitions available for a given resource\n * <p/>\n *\n * @see <a href=\"https://docs.microsoft.com/en-us/rest/api/monitor/metricdefinitions\">docs</a>\n */\n@Path(\"/{resourceid}\")\n@RequestFilters({ OAuthFilter.class, ApiVersionFilter.class })\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface MetricDefinitionsApi {\n   @Named(\"metrics:list\")\n   @Path(\"/providers/microsoft.insights/metricdefinitions\")\n   @GET\n   @SelectJson(\"value\")\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   List<MetricDefinition> list(@Nullable @QueryParam(\"$filter\") String filter);\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/features/MetricsApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport java.util.List;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyListOnNotFoundOr404;\nimport org.jclouds.azurecompute.arm.domain.Metric;\nimport org.jclouds.azurecompute.arm.filters.ApiVersionFilter;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\n/**\n * This Azure Resource Manager API provides all the metric data available for a given resource\n * <p/>\n *\n * @see <a href=\"https://docs.microsoft.com/en-us/rest/api/monitor/metricdefinitions\">docs</a>\n */\n@Path(\"/{resourceid}\")\n@RequestFilters({ OAuthFilter.class, ApiVersionFilter.class })\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface MetricsApi {\n   @Named(\"metrics:list\")\n   @Path(\"/providers/microsoft.insights/metrics\")\n   @GET\n   @SelectJson(\"value\")\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   List<Metric> list(@QueryParam(\"$filter\") String filter);\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/features/NetworkInterfaceCardApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport java.net.URI;\nimport java.util.List;\nimport java.util.Map;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyListOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.azurecompute.arm.domain.NetworkInterfaceCard;\nimport org.jclouds.azurecompute.arm.domain.NetworkInterfaceCardProperties;\nimport org.jclouds.azurecompute.arm.filters.ApiVersionFilter;\nimport org.jclouds.azurecompute.arm.functions.URIParser;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\n@RequestFilters({ OAuthFilter.class, ApiVersionFilter.class })\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface NetworkInterfaceCardApi {\n\n   @Named(\"networkinterfacecard:list\")\n   @Path(\"/resourcegroups/{resourcegroup}/providers/Microsoft.Network/networkInterfaces\")\n   @SelectJson(\"value\")\n   @GET\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   List<NetworkInterfaceCard> list();\n\n   @Named(\"networkinterfacecard:list_all\")\n   @Path(\"/providers/Microsoft.Network/networkInterfaces\")\n   @SelectJson(\"value\")\n   @GET\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   List<NetworkInterfaceCard> listAllInSubscription();\n\n   @Named(\"networkinterfacecard:create_or_update\")\n   @Path(\"/resourcegroups/{resourcegroup}/providers/Microsoft.Network/networkInterfaces/{networkinterfacecardname}\")\n   @MapBinder(BindToJsonPayload.class)\n   @PUT\n   NetworkInterfaceCard createOrUpdate(@PathParam(\"networkinterfacecardname\") String networkinterfacecardname,\n         @PayloadParam(\"location\") String location,\n         @PayloadParam(\"properties\") NetworkInterfaceCardProperties properties,\n         @Nullable @PayloadParam(\"tags\") Map<String, String> tags);\n\n   @Named(\"networkinterfacecard:get\")\n   @Path(\"/resourcegroups/{resourcegroup}/providers/Microsoft.Network/networkInterfaces/{networkinterfacecardname}\")\n   @GET\n   @Fallback(NullOnNotFoundOr404.class)\n   NetworkInterfaceCard get(@PathParam(\"networkinterfacecardname\") String networkinterfacecardname);\n\n   @Named(\"networkinterfacecard:delete\")\n   @Path(\"/resourcegroups/{resourcegroup}/providers/Microsoft.Network/networkInterfaces/{networkinterfacecardname}\")\n   @DELETE\n   @ResponseParser(URIParser.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   URI delete(@PathParam(\"networkinterfacecardname\") String networkinterfacecardname);\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/features/NetworkSecurityGroupApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport java.net.URI;\nimport java.util.List;\nimport java.util.Map;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks;\nimport org.jclouds.Fallbacks.EmptyListOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityGroup;\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityGroupProperties;\nimport org.jclouds.azurecompute.arm.filters.ApiVersionFilter;\nimport org.jclouds.azurecompute.arm.functions.URIParser;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\n/**\n * The Network Security Group API includes operations for managing the network security groups in your subscription.\n *\n * @see <a href=\"https://docs.microsoft.com/en-us/rest/api/virtualnetwork/networksecuritygroups\">docs</a>\n */\n@RequestFilters({ OAuthFilter.class, ApiVersionFilter.class })\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface NetworkSecurityGroupApi {\n\n   @Named(\"networksecuritygroup:list\")\n   @Path(\"/resourcegroups/{resourcegroup}/providers/Microsoft.Network/networkSecurityGroups\")\n   @GET\n   @SelectJson(\"value\")\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   List<NetworkSecurityGroup> list();\n\n   @Named(\"networksecuritygroup:listall\")\n   @GET\n   @Path(\"/providers/Microsoft.Network/networkSecurityGroups\")\n   @SelectJson(\"value\")\n   @Fallback(Fallbacks.EmptyListOnNotFoundOr404.class)\n   List<NetworkSecurityGroup> listAll();\n\n   @Named(\"networksecuritygroup:delete\")\n   @Path(\"/resourcegroups/{resourcegroup}/providers/Microsoft.Network/networkSecurityGroups/{networksecuritygroupname}\")\n   @DELETE\n   @ResponseParser(URIParser.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   URI delete(@PathParam(\"networksecuritygroupname\") String nsgName);\n\n   @Named(\"networksecuritygroup:createOrUpdate\")\n   @Path(\"/resourcegroups/{resourcegroup}/providers/Microsoft.Network/networkSecurityGroups/{networksecuritygroupname}\")\n   @PUT\n   @MapBinder(BindToJsonPayload.class)\n   NetworkSecurityGroup createOrUpdate(@PathParam(\"networksecuritygroupname\") String nsgName,\n         @PayloadParam(\"location\") String location, @Nullable @PayloadParam(\"tags\") Map<String, String> tags,\n         @PayloadParam(\"properties\") NetworkSecurityGroupProperties properties);\n\n   @Named(\"networksecuritygroup:get\")\n   @Path(\"/resourcegroups/{resourcegroup}/providers/Microsoft.Network/networkSecurityGroups/{networksecuritygroupname}\")\n   @GET\n   @Fallback(NullOnNotFoundOr404.class)\n   NetworkSecurityGroup get(@PathParam(\"networksecuritygroupname\") String nsgName);\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/features/NetworkSecurityRuleApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyListOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityRule;\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityRuleProperties;\nimport org.jclouds.azurecompute.arm.filters.ApiVersionFilter;\nimport org.jclouds.azurecompute.arm.functions.URIParser;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\n@Path(\"/resourcegroups/{resourcegroup}/providers/Microsoft.Network/networkSecurityGroups/{networksecuritygroup}\")\n@RequestFilters({ OAuthFilter.class, ApiVersionFilter.class })\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface NetworkSecurityRuleApi {\n\n   @Named(\"networksecurityrule:createOrUpdate\")\n   @Path(\"/securityRules/{networksecurityrulename}\")\n   @PUT\n   @MapBinder(BindToJsonPayload.class)\n   NetworkSecurityRule createOrUpdate(@PathParam(\"networksecurityrulename\") String ruleName,\n                                      @PayloadParam(\"properties\") NetworkSecurityRuleProperties properties);\n\n   @Named(\"networksecurityrule:getDefaultRule\")\n   @Path(\"/defaultSecurityRules/{networksecurityrulename}\")\n   @GET\n   @Fallback(NullOnNotFoundOr404.class)\n   NetworkSecurityRule getDefaultRule(@PathParam(\"networksecurityrulename\") String ruleName);\n\n   @Named(\"networksecurityrule:get\")\n   @Path(\"/securityRules/{networksecurityrulename}\")\n   @GET\n   @Fallback(NullOnNotFoundOr404.class)\n   NetworkSecurityRule get(@PathParam(\"networksecurityrulename\") String ruleName);\n\n   @Named(\"networksecurityrule:delete\")\n   @Path(\"/securityRules/{networksecurityrulename}\")\n   @DELETE\n   @ResponseParser(URIParser.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   URI delete(@PathParam(\"networksecurityrulename\") String ruleName);\n\n   @Named(\"networksecuritygroup:list\")\n   @Path(\"/securityRules\")\n   @GET\n   @SelectJson(\"value\")\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   List<NetworkSecurityRule> list();\n\n   @Named(\"networksecuritygroup:listDefaultRules\")\n   @Path(\"/defaultSecurityRules\")\n   @GET\n   @SelectJson(\"value\")\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   List<NetworkSecurityRule> listDefaultRules();\n}\n\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/features/OSImageApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport java.util.List;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\n\nimport org.jclouds.Fallbacks.EmptyListOnNotFoundOr404;\nimport org.jclouds.azurecompute.arm.domain.Offer;\nimport org.jclouds.azurecompute.arm.domain.Publisher;\nimport org.jclouds.azurecompute.arm.domain.SKU;\nimport org.jclouds.azurecompute.arm.domain.Version;\nimport org.jclouds.azurecompute.arm.filters.ApiVersionFilter;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\n/**\n * The Azure Resource Management API includes operations for managing the OS images in your subscription.\n */\n@Path(\"/providers/Microsoft.Compute/locations/{location}\")\n@RequestFilters({ OAuthFilter.class, ApiVersionFilter.class })\n@Consumes(APPLICATION_JSON)\npublic interface OSImageApi {\n\n   /**\n    * List Publishers in location\n    */\n   @Named(\"publisher:list\")\n   @GET\n   @Path(\"/publishers\")\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   List<Publisher> listPublishers();\n\n   /**\n    * List Offers in publisher\n    */\n   @Named(\"offer:list\")\n   @GET\n   @Path(\"/publishers/{publisher}/artifacttypes/vmimage/offers\")\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   List<Offer> listOffers(@PathParam(\"publisher\") String publisher);\n\n   /**\n    * List SKUs in offer\n    */\n   @Named(\"sku:list\")\n   @GET\n   @Path(\"/publishers/{publisher}/artifacttypes/vmimage/offers/{offer}/skus\")\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   List<SKU> listSKUs(@PathParam(\"publisher\") String publisher, @PathParam(\"offer\") String offer);\n\n   /**\n    * List Versions in SKU\n    */\n   @Named(\"version:list\")\n   @GET\n   @Path(\"/publishers/{publisher}/artifacttypes/vmimage/offers/{offer}/skus/{sku}/versions\")\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   List<Version> listVersions(@PathParam(\"publisher\") String publisher, @PathParam(\"offer\") String offer,\n                          @PathParam(\"sku\") String sku);\n   \n   /**\n    * Get the details of a Version\n    */\n   @Named(\"version:get\")\n   @GET\n   @Path(\"/publishers/{publisher}/artifacttypes/vmimage/offers/{offer}/skus/{sku}/versions/{version}\")\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   Version getVersion(@PathParam(\"publisher\") String publisher, @PathParam(\"offer\") String offer,\n                          @PathParam(\"sku\") String sku, @PathParam(\"version\") String version);\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/features/PublicIPAddressApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport java.util.List;\nimport java.util.Map;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyListOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.azurecompute.arm.domain.publicipaddress.PublicIPAddress;\nimport org.jclouds.azurecompute.arm.domain.publicipaddress.PublicIPAddress.SKU;\nimport org.jclouds.azurecompute.arm.domain.publicipaddress.PublicIPAddressProperties;\nimport org.jclouds.azurecompute.arm.filters.ApiVersionFilter;\nimport org.jclouds.azurecompute.arm.functions.FalseOn204;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\n@RequestFilters({ OAuthFilter.class, ApiVersionFilter.class })\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface PublicIPAddressApi {\n\n   @Named(\"publicipaddress:list\")\n   @Path(\"/resourcegroups/{resourcegroup}/providers/Microsoft.Network/publicIPAddresses\")\n   @SelectJson(\"value\")\n   @GET\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   List<PublicIPAddress> list();\n\n   @Named(\"publicipaddress:list_all\")\n   @Path(\"/providers/Microsoft.Network/publicIPAddresses\")\n   @SelectJson(\"value\")\n   @GET\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   List<PublicIPAddress> listAllInSubscription();\n\n   @Named(\"publicipaddress:create_or_update\")\n   @Path(\"/resourcegroups/{resourcegroup}/providers/Microsoft.Network/publicIPAddresses/{publicipaddressname}\")\n   @MapBinder(BindToJsonPayload.class)\n   @PUT\n   PublicIPAddress createOrUpdate(@PathParam(\"publicipaddressname\") String publicipaddressname,\n         @PayloadParam(\"location\") String location, @Nullable @PayloadParam(\"tags\") Map<String, String> tags,\n         @Nullable @PayloadParam(\"sku\") SKU sku,\n         @PayloadParam(\"properties\") PublicIPAddressProperties properties);\n\n   @Named(\"publicipaddress:get\")\n   @Path(\"/resourcegroups/{resourcegroup}/providers/Microsoft.Network/publicIPAddresses/{publicipaddressname}\")\n   @GET\n   @Fallback(NullOnNotFoundOr404.class)\n   PublicIPAddress get(@PathParam(\"publicipaddressname\") String publicipaddressname);\n\n   @Named(\"publicipaddress:delete\")\n   @Path(\"/resourcegroups/{resourcegroup}/providers/Microsoft.Network/publicIPAddresses/{publicipaddressname}\")\n   @DELETE\n   @ResponseParser(FalseOn204.class)\n   boolean delete(@PathParam(\"publicipaddressname\") String publicipaddressname);\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/features/ResourceGroupApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport java.io.Closeable;\nimport java.net.URI;\nimport java.util.List;\nimport java.util.Map;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyListOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.azurecompute.arm.domain.Resource;\nimport org.jclouds.azurecompute.arm.domain.ResourceGroup;\nimport org.jclouds.azurecompute.arm.filters.ApiVersionFilter;\nimport org.jclouds.azurecompute.arm.functions.URIParser;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PATCH;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\n/**\n * The Azure Resource Manager API includes operations for managing resource groups in your subscription.\n *\n * @see <a href=\"https://msdn.microsoft.com/en-us/library/azure/dn790546.aspx\">docs</a>\n */\n@Path(\"/resourcegroups\")\n@RequestFilters({ OAuthFilter.class, ApiVersionFilter.class })\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface ResourceGroupApi extends Closeable{\n\n   @Named(\"resourcegroup:list\")\n   @SelectJson(\"value\")\n   @GET\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   List<ResourceGroup> list();\n\n   @Named(\"resourcegroup:create\")\n   @PUT\n   @Path(\"/{name}\")\n   @MapBinder(BindToJsonPayload.class)\n   ResourceGroup create(@PathParam(\"name\") String name, @PayloadParam(\"location\") String location, @Nullable @PayloadParam(\"tags\") Map<String, String> tags);\n\n   @Named(\"resourcegroup:get\")\n   @GET\n   @Path(\"/{name}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   ResourceGroup get(@PathParam(\"name\") String name);\n\n   @Named(\"resourcegroup:resources\")\n   @GET\n   @Path(\"/{name}/resources\")\n   @SelectJson(\"value\")\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   List<Resource> resources(@PathParam(\"name\") String name);\n\n   @Named(\"resourcegroup:update\")\n   @PATCH\n   @Path(\"/{name}\")\n   @MapBinder(BindToJsonPayload.class)\n   ResourceGroup update(@PathParam(\"name\") String name, @Nullable @PayloadParam(\"tags\") Map<String, String> tags);\n\n   @Named(\"resourcegroup:delete\")\n   @DELETE\n   @ResponseParser(URIParser.class)\n   @Path(\"/{name}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   URI delete(@PathParam(\"name\") String name);\n}\n\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/features/ResourceProviderApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport java.io.Closeable;\nimport java.util.List;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.azurecompute.arm.domain.ResourceProviderMetaData;\nimport org.jclouds.azurecompute.arm.filters.ApiVersionFilter;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\n/**\n * The Azure Resource Provider API provides information about a resource provider and its supported resource types.\n *\n * @see <a href=\"https://msdn.microsoft.com/en-us/library/azure/dn790534.aspx\">docs</a>\n */\n@Path(\"/providers\")\n\n@RequestFilters({ OAuthFilter.class, ApiVersionFilter.class })\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface ResourceProviderApi extends Closeable {\n\n   @Named(\"providers:get\")\n   @GET\n   @Path(\"/{namespace}\")\n   @SelectJson(\"resourceTypes\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   List<ResourceProviderMetaData> get(@PathParam(\"namespace\") String namespace);\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/features/StorageAccountApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport java.net.URI;\nimport java.util.List;\nimport java.util.Map;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks;\nimport org.jclouds.azurecompute.arm.domain.Availability;\nimport org.jclouds.azurecompute.arm.domain.StorageService;\nimport org.jclouds.azurecompute.arm.domain.StorageServiceKeys;\nimport org.jclouds.azurecompute.arm.domain.StorageServiceUpdateParams;\nimport org.jclouds.azurecompute.arm.filters.ApiVersionFilter;\nimport org.jclouds.azurecompute.arm.functions.FalseOn204;\nimport org.jclouds.azurecompute.arm.functions.URIParser;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PATCH;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\n/**\n * The Azure Resource Management API includes operations for managing the storage accounts in your subscription.\n *\n * @see <a href=\"https://msdn.microsoft.com/en-us/library/mt163683.aspx\">docs</a>\n */\n@Path(\"/\")\n@RequestFilters({ OAuthFilter.class, ApiVersionFilter.class })\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface StorageAccountApi {\n\n   /**\n    * The List Storage Accounts operation lists the storage accounts that are available in the specified subscription\n    * and resource group.\n    * https://msdn.microsoft.com/en-us/library/mt163559.aspx\n    */\n   @Named(\"storageaccount:list\")\n   @Path(\"/resourcegroups/{resourceGroup}/providers/Microsoft.Storage/storageAccounts\")\n   @GET\n   @SelectJson(\"value\")\n   @Fallback(Fallbacks.EmptyListOnNotFoundOr404.class)\n   List<StorageService> list();\n\n   /**\n    * The Create Storage Account asynchronous operation creates a new storage account in Microsoft Azure.\n    * https://msdn.microsoft.com/en-us/library/mt163564.aspx\n    * PUT\n    */\n   @Named(\"storageaccount:create\")\n   @Path(\"/resourcegroups/{resourceGroup}/providers/Microsoft.Storage/storageAccounts/{storageAccountName}\")\n   @ResponseParser(URIParser.class)\n   @MapBinder(BindToJsonPayload.class)\n   @PUT\n   URI create(@PathParam(\"storageAccountName\") String storageAccountName,\n              @PayloadParam(\"location\") String location,\n              @Nullable @PayloadParam(\"tags\") Map<String, String> tags,\n              @PayloadParam(\"properties\") Map<String, String> properties);\n\n   /**\n    * The Check Storage Account Name Availability operation checks to see if the specified storage account name is\n    * available, or if it has already been taken. https://msdn.microsoft.com/en-us/library/mt163642.aspx\n    * POST\n    */\n   @Named(\"CheckStorageAccountNameAvailability\")\n   @POST\n   @Payload(\"%7B\\\"name\\\":\\\"{name}\\\",\\\"type\\\":\\\"Microsoft.Storage/storageAccounts\\\"%7D\")\n   @Path(\"/providers/Microsoft.Storage/checkNameAvailability\")\n   @Produces(MediaType.APPLICATION_JSON)\n   Availability isAvailable(@PayloadParam(\"name\") String storageAccountName);\n\n   /**\n    * The Get Storage Account Properties operation returns system properties for the specified storage account.\n    * https://msdn.microsoft.com/en-us/library/mt163553.aspx\n    */\n   @Named(\"storageaccountproperty:get\")\n   @GET\n   @Path(\"/resourcegroups/{resourceGroup}/providers/Microsoft.Storage/storageAccounts/{storageAccountName}\")\n   @Fallback(Fallbacks.NullOnNotFoundOr404.class)\n   StorageService get(@PathParam(\"storageAccountName\") String storageAccountName);\n\n   /**\n    * The Get Storage Keys operation returns the primary and secondary access keys for the specified storage account.\n    * https://msdn.microsoft.com/en-us/library/mt163589.aspx\n    * POST\n    */\n   @Named(\"storageaccountkey:get\")\n   @POST\n   @Path(\"/resourcegroups/{resourceGroup}/providers/Microsoft.Storage/storageAccounts/{storageAccountName}/listKeys\")\n   @Fallback(Fallbacks.NullOnNotFoundOr404.class)\n   StorageServiceKeys getKeys(@PathParam(\"storageAccountName\") String storageAccountName);\n\n   /**\n    * https://msdn.microsoft.com/en-us/library/mt163567.aspx\n    * POST\n    */\n   @Named(\"RegenerateStorageAccountKeys\")\n   @POST\n   @Payload(\"%7B\\\"keyName\\\":\\\"{keyName}\\\"%7D\")\n   @Path(\"/resourcegroups/{resourceGroup}/providers/Microsoft.Storage/storageAccounts/{storageAccount}/regenerateKey\")\n   @Produces(MediaType.APPLICATION_JSON)\n   StorageServiceKeys regenerateKeys(@PathParam(\"storageAccount\") String storageAccount,\n                                     @PayloadParam(\"keyName\") String keyName);\n\n   /**\n    * The Update Storage Account asynchronous operation updates the label, the description, and enables or disables the\n    * geo-replication status for the specified storage account. https://msdn.microsoft.com/en-us/library/mt163639.aspx\n    * PATCH\n    */\n   @Named(\"storageaccount:update\")\n   @PATCH\n   @MapBinder(BindToJsonPayload.class)\n   @Path(\"/resourcegroups/{resourceGroup}/providers/Microsoft.Storage/storageAccounts/{storageAccountName}\")\n   StorageServiceUpdateParams update(\n           @PathParam(\"storageAccountName\") String storageAccountName,\n           @Nullable @PayloadParam(\"tags\") Map<String, String> tags,\n           @PayloadParam(\"properties\") StorageServiceUpdateParams.StorageServiceUpdateProperties properties);\n\n   /**\n    * https://msdn.microsoft.com/en-us/library/mt163652.aspx\n    * DELETE\n    */\n   @Named(\"storageaccount:delete\")\n   @DELETE\n   @ResponseParser(FalseOn204.class)\n   @Path(\"/resourcegroups/{resourceGroup}/providers/Microsoft.Storage/storageAccounts/{storageAccountName}\")\n   boolean delete(@PathParam(\"storageAccountName\") String storageAccountName);\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/features/SubnetApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport java.util.List;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyListOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.azurecompute.arm.domain.Subnet;\nimport org.jclouds.azurecompute.arm.filters.ApiVersionFilter;\nimport org.jclouds.azurecompute.arm.functions.FalseOn204;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\n@Path(\"/resourcegroups/{resourcegroup}/providers/Microsoft.Network/virtualNetworks/{virtualnetwork}/subnets\")\n\n@RequestFilters({ OAuthFilter.class, ApiVersionFilter.class })\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface SubnetApi {\n\n   @Named(\"subnet:list\")\n   @SelectJson(\"value\")\n   @GET\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   List<Subnet> list();\n\n   @Named(\"subnet:create_or_update\")\n   @Path(\"/{subnetname}\")\n   @MapBinder(BindToJsonPayload.class)\n   @PUT\n   Subnet createOrUpdate(@PathParam(\"subnetname\") String name,\n                               @PayloadParam(\"properties\") Subnet.SubnetProperties properties);\n\n   @Named(\"subnet:get\")\n   @Path(\"/{subnetname}\")\n   @GET\n   @Fallback(NullOnNotFoundOr404.class)\n   Subnet get(@PathParam(\"subnetname\") String subnetname);\n\n   @Named(\"subnet:delete\")\n   @Path(\"/{subnetname}\")\n   @DELETE\n   @ResponseParser(FalseOn204.class)\n   boolean delete(@PathParam(\"subnetname\") String subnetname);\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/features/VMSizeApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport java.util.List;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyListOnNotFoundOr404;\nimport org.jclouds.azurecompute.arm.domain.VMSize;\nimport org.jclouds.azurecompute.arm.filters.ApiVersionFilter;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\n@Path(\"/providers/Microsoft.Compute/locations/{location}/vmSizes\")\n@RequestFilters({ OAuthFilter.class, ApiVersionFilter.class })\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface VMSizeApi {\n\n   @Named(\"vmSizes:list\")\n   @GET\n   @SelectJson(\"value\")\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   List<VMSize> list();\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/features/VaultApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport java.net.URI;\nimport java.util.List;\nimport java.util.Map;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyListOnNotFoundOr404;\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.azurecompute.arm.config.OAuthResource;\nimport org.jclouds.azurecompute.arm.domain.Certificate;\nimport org.jclouds.azurecompute.arm.domain.Certificate.CertificateAttributes;\nimport org.jclouds.azurecompute.arm.domain.Certificate.CertificateBundle;\nimport org.jclouds.azurecompute.arm.domain.Certificate.CertificateIssuer;\nimport org.jclouds.azurecompute.arm.domain.Certificate.CertificateOperation;\nimport org.jclouds.azurecompute.arm.domain.Certificate.CertificatePolicy;\nimport org.jclouds.azurecompute.arm.domain.Certificate.Contact;\nimport org.jclouds.azurecompute.arm.domain.Certificate.Contacts;\nimport org.jclouds.azurecompute.arm.domain.Certificate.DeletedCertificate;\nimport org.jclouds.azurecompute.arm.domain.Certificate.DeletedCertificateBundle;\nimport org.jclouds.azurecompute.arm.domain.Certificate.IssuerAttributes;\nimport org.jclouds.azurecompute.arm.domain.Certificate.IssuerBundle;\nimport org.jclouds.azurecompute.arm.domain.Certificate.IssuerCredentials;\nimport org.jclouds.azurecompute.arm.domain.Certificate.IssuerParameters;\nimport org.jclouds.azurecompute.arm.domain.Certificate.KeyProperties;\nimport org.jclouds.azurecompute.arm.domain.Certificate.LifetimeAction;\nimport org.jclouds.azurecompute.arm.domain.Certificate.OrganizationDetails;\nimport org.jclouds.azurecompute.arm.domain.Certificate.SecretProperties;\nimport org.jclouds.azurecompute.arm.domain.Certificate.X509CertificateProperties;\nimport org.jclouds.azurecompute.arm.domain.Key;\nimport org.jclouds.azurecompute.arm.domain.Key.DeletedKeyBundle;\nimport org.jclouds.azurecompute.arm.domain.Key.JsonWebKey;\nimport org.jclouds.azurecompute.arm.domain.Key.KeyAttributes;\nimport org.jclouds.azurecompute.arm.domain.Key.KeyBundle;\nimport org.jclouds.azurecompute.arm.domain.Key.KeyOperationResult;\nimport org.jclouds.azurecompute.arm.domain.Secret;\nimport org.jclouds.azurecompute.arm.domain.Secret.DeletedSecretBundle;\nimport org.jclouds.azurecompute.arm.domain.Secret.SecretAttributes;\nimport org.jclouds.azurecompute.arm.domain.Secret.SecretBundle;\nimport org.jclouds.azurecompute.arm.domain.Vault;\nimport org.jclouds.azurecompute.arm.domain.Vault.DeletedVault;\nimport org.jclouds.azurecompute.arm.domain.VaultProperties;\nimport org.jclouds.azurecompute.arm.filters.ApiVersionFilter;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.EndpointParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PATCH;\nimport org.jclouds.rest.annotations.ParamParser;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport com.google.common.base.Function;\n\n@RequestFilters({ OAuthFilter.class, ApiVersionFilter.class })\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface VaultApi {\n\n   String VAULT_API_STANDARD_ENDPOINT = \"https://vault.azure.net\";\n   String VAULT_API_CHINA_ENDPOINT = \"https://vault.azure.cn\";\n\n   static class PrependSlashOrEmptyString implements Function<Object, String> {\n      public String apply(Object from) {\n         if ((from == null) || (from.toString().length() == 0)) {\n            return \"\";\n         } else {\n            return \"/\" + from.toString();\n         }\n      }\n   }\n\n   // Vault operations\n   @Named(\"vault:list\")\n   @SelectJson(\"value\")\n   @GET\n   @Path(\"/resourcegroups/{resourcegroup}/providers/Microsoft.KeyVault/vaults\")\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   List<Vault> listVaults();\n\n   @Named(\"vault:create_or_update\")\n   @PUT\n   @MapBinder(BindToJsonPayload.class)\n   @Path(\"/resourcegroups/{resourcegroup}/providers/Microsoft.KeyVault/vaults/{vaultName}\")\n   Vault createOrUpdateVault(@PathParam(\"vaultName\") String vaultName, @PayloadParam(\"location\") String location,\n         @PayloadParam(\"properties\") VaultProperties properties, @Nullable @PayloadParam(\"tags\") Map<String, String> tags);\n\n   @Named(\"vault:get\")\n   @Path(\"/resourcegroups/{resourcegroup}/providers/Microsoft.KeyVault/vaults/{vaultName}\")\n   @GET\n   @Fallback(NullOnNotFoundOr404.class)\n   Vault getVault(@PathParam(\"vaultName\") String vaultName);\n\n   @Named(\"vault:delete\")\n   @Path(\"/resourcegroups/{resourcegroup}/providers/Microsoft.KeyVault/vaults/{vaultName}\")\n   @DELETE\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean deleteVault(@PathParam(\"vaultName\") String vaultName);\n\n   @Named(\"vault:list_deleted_vaults\")\n   @Path(\"/providers/Microsoft.KeyVault/deletedVaults\")\n   @GET\n   @SelectJson(\"value\")\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   List<DeletedVault> listDeletedVaults();\n\n   @Named(\"vault:get_deleted\")\n   @GET\n   @Path(\"/providers/Microsoft.KeyVault/locations/{location}/deletedVaults/{vaultName}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   DeletedVault getDeletedVault(@PathParam(\"location\") String location, @PathParam(\"vaultName\") String vaultName);\n\n   @Named(\"vault:purge\")\n   @POST\n   @Fallback(FalseOnNotFoundOr404.class)\n   @Path(\"/providers/Microsoft.KeyVault/locations/{location}/deletedVaults/{vaultName}/purge\")\n   boolean purgeVault(@PathParam(\"location\") String location, @PathParam(\"vaultName\") String vaultName);\n\n   // Key operations\n   @Named(\"key:list\")\n   @SelectJson(\"value\")\n   @GET\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   @Path(\"/keys\")\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   List<Key> listKeys(@EndpointParam URI keyVaultUri);\n\n   @Named(\"key:create\")\n   @POST\n   @MapBinder(BindToJsonPayload.class)\n   @Path(\"/keys/{keyName}/create\")\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   KeyBundle createKey(@EndpointParam URI vaultBaseUrl, @PathParam(\"keyName\") String keyName,\n         @Nullable @PayloadParam(\"attributes\") KeyAttributes attributes,\n         @Nullable @PayloadParam(\"crv\") String curveName, @Nullable @PayloadParam(\"key_ops\") List<String> keyOps,\n         @PayloadParam(\"key_size\") int keySize, @PayloadParam(\"kty\") String keyType,\n         @Nullable @PayloadParam(\"tags\") Map<String, String> tags);\n\n   @Named(\"key:import\")\n   @PUT\n   @MapBinder(BindToJsonPayload.class)\n   @Path(\"/keys/{keyName}\")\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   KeyBundle importKey(@EndpointParam URI vaultBaseUrl, @PathParam(\"keyName\") String keyName,\n         @PayloadParam(\"Hsm\") boolean hsm, @Nullable @PayloadParam(\"attributes\") KeyAttributes attributes,\n         @Nullable @PayloadParam(\"key\") JsonWebKey key, @Nullable @PayloadParam(\"tags\") Map<String, String> tags);\n\n   @Named(\"key:get\")\n   @GET\n   @Path(\"/keys/{keyName}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   KeyBundle getKey(@EndpointParam URI vaultBaseUrl, @PathParam(\"keyName\") String keyName);\n\n   @Named(\"key:delete\")\n   @DELETE\n   @Path(\"/keys/{keyName}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   DeletedKeyBundle deleteKey(@EndpointParam URI vaultBaseUrl, @PathParam(\"keyName\") String keyName);\n\n   @Named(\"key:get_versions\")\n   @GET\n   @SelectJson(\"value\")\n   @Path(\"/keys/{keyName}/versions\")\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   List<Key> getKeyVersions(@EndpointParam URI vaultBaseUrl, @PathParam(\"keyName\") String keyName);\n\n   @Named(\"key:update\")\n   @PATCH\n   @MapBinder(BindToJsonPayload.class)\n   @Path(\"/keys/{keyName}{keyVersion}\")\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   KeyBundle updateKey(@EndpointParam URI vaultBaseUrl,\n                       @PathParam(\"keyName\") String keyName,\n                       @Nullable @PathParam(\"keyVersion\") @ParamParser(PrependSlashOrEmptyString.class) String keyVersion,\n                       @Nullable @PayloadParam(\"attributes\") KeyAttributes attributes,\n                       @Nullable @PayloadParam(\"key_ops\") List<String> keyOps,\n                       @Nullable @PayloadParam(\"tags\") Map<String, String> tags);\n\n   @Named(\"key:backup\")\n   @POST\n   @SelectJson(\"value\")\n   @Path(\"/keys/{keyName}/backup\")\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   String backupKey(@EndpointParam URI vaultBaseUrl, @PathParam(\"keyName\") String keyName);\n\n   @Named(\"key:restore\")\n   @POST\n   @MapBinder(BindToJsonPayload.class)\n   @Path(\"/keys/restore\")\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   KeyBundle restoreKey(@EndpointParam URI vaultBaseUrl, @PayloadParam(\"value\") String keyInfo);\n\n   // Soft-delete key operations\n   @Named(\"key:list_deleted\")\n   @GET\n   @SelectJson(\"value\")\n   @Path(\"/deletedkeys\")\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   List<DeletedKeyBundle> listDeletedKeys(@EndpointParam URI vaultBaseUrl);\n\n   @Named(\"key:get_deleted\")\n   @GET\n   @Path(\"/deletedkeys/{keyName}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   DeletedKeyBundle getDeletedKey(@EndpointParam URI vaultBaseUrl, @PathParam(\"keyName\") String keyName);\n\n   @Named(\"key:recover_deleted\")\n   @POST\n   @Path(\"/deletedkeys/{keyName}/recover\")\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   KeyBundle recoverDeletedKey(@EndpointParam URI vaultBaseUrl, @PathParam(\"keyName\") String keyName);\n\n   @Named(\"key:purge_deleted\")\n   @DELETE\n   @Path(\"/deletedkeys/{keyName}\")\n   @Fallback(FalseOnNotFoundOr404.class)\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   boolean purgeDeletedKey(@EndpointParam URI vaultBaseUrl, @PathParam(\"keyName\") String keyName);\n\n   // Key cryptographic operations\n   @Named(\"key:crypto_encrypt\")\n   @POST\n   @Path(\"/keys/{keyName}{keyVersion}/encrypt\")\n   @MapBinder(BindToJsonPayload.class)\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   KeyOperationResult encrypt(@EndpointParam URI vaultBaseUrl,\n                              @PathParam(\"keyName\") String keyName,\n                              @Nullable @PathParam(\"keyVersion\") @ParamParser(PrependSlashOrEmptyString.class) String keyVersion,\n                              @PayloadParam(\"alg\") String algorithm,\n                              @PayloadParam(\"value\") String value);\n\n   @Named(\"key:crypto_decrypt\")\n   @POST\n   @Path(\"/keys/{keyName}{keyVersion}/decrypt\")\n   @MapBinder(BindToJsonPayload.class)\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   KeyOperationResult decrypt(@EndpointParam URI vaultBaseUrl,\n                              @PathParam(\"keyName\") String keyName,\n                              @Nullable @PathParam(\"keyVersion\") @ParamParser(PrependSlashOrEmptyString.class) String keyVersion,\n                              @PayloadParam(\"alg\") String algorithm,\n                              @PayloadParam(\"value\") String value);\n\n   @Named(\"key:crypto_sign\")\n   @POST\n   @Path(\"/keys/{keyName}{keyVersion}/sign\")\n   @MapBinder(BindToJsonPayload.class)\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   KeyOperationResult sign(@EndpointParam URI vaultBaseUrl,\n                           @PathParam(\"keyName\") String keyName,\n                           @Nullable @PathParam(\"keyVersion\") @ParamParser(PrependSlashOrEmptyString.class) String keyVersion,\n                           @PayloadParam(\"alg\") String algorithm,\n                           @PayloadParam(\"value\") String value);\n\n   @Named(\"key:crypto_verify\")\n   @POST\n   @Path(\"/keys/{keyName}{keyVersion}/verify\")\n   @MapBinder(BindToJsonPayload.class)\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   boolean verify(@EndpointParam URI vaultBaseUrl,\n                  @PathParam(\"keyName\") String keyName,\n                  @Nullable @PathParam(\"keyVersion\")  @ParamParser(PrependSlashOrEmptyString.class) String keyVersion,\n                  @PayloadParam(\"alg\") String algorithm,\n                  @PayloadParam(\"digest\") String digest,\n                  @PayloadParam(\"value\") String value);\n\n   @Named(\"key:crypto_wrap\")\n   @POST\n   @Path(\"/keys/{keyName}{keyVersion}/wrapkey\")\n   @MapBinder(BindToJsonPayload.class)\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   KeyOperationResult wrap(@EndpointParam URI vaultBaseUrl,\n                           @PathParam(\"keyName\") String keyName,\n                           @Nullable @PathParam(\"keyVersion\") @ParamParser(PrependSlashOrEmptyString.class) String keyVersion,\n                           @PayloadParam(\"alg\") String algorithm,\n                           @PayloadParam(\"value\") String value);\n\n   @Named(\"key:crypto_unwrap\")\n   @POST\n   @Path(\"/keys/{keyName}{keyVersion}/unwrapkey\")\n   @MapBinder(BindToJsonPayload.class)\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   KeyOperationResult unwrap(@EndpointParam URI vaultBaseUrl,\n                             @PathParam(\"keyName\") String keyName,\n                             @Nullable @PathParam(\"keyVersion\") @ParamParser(PrependSlashOrEmptyString.class) String keyVersion,\n                             @PayloadParam(\"alg\") String algorithm,\n                             @PayloadParam(\"value\") String value);\n\n   // Secret operations\n   @Named(\"secret:list\")\n   @SelectJson(\"value\")\n   @GET\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   @Path(\"/secrets\")\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   List<Secret> listSecrets(@EndpointParam URI keyVaultUri);\n\n   @Named(\"secret:set\")\n   @PUT\n   @MapBinder(BindToJsonPayload.class)\n   @Path(\"/secrets/{secretName}\")\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   SecretBundle setSecret(@EndpointParam URI keyVaultUri, @PathParam(\"secretName\") String secretName,\n         @Nullable @PayloadParam(\"attributes\") SecretAttributes attributes,\n         @Nullable @PayloadParam(\"contentType\") String contentType,\n         @Nullable @PayloadParam(\"tags\") Map<String, String> tags, @PayloadParam(\"value\") String value);\n\n   @Named(\"secret:get\")\n   @GET\n   @Path(\"/secrets/{secretName}{secretVersion}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   SecretBundle getSecret(@EndpointParam URI vaultBaseUrl,\n                          @PathParam(\"secretName\") String secretName,\n                          @Nullable @PathParam(\"secretVersion\") @ParamParser(PrependSlashOrEmptyString.class) String secretVersion);\n\n   @Named(\"secret:delete\")\n   @DELETE\n   @Path(\"/secrets/{secretName}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   DeletedSecretBundle deleteSecret(@EndpointParam URI vaultBaseUrl, @PathParam(\"secretName\") String secretName);\n\n   @Named(\"secret:get_versions\")\n   @GET\n   @SelectJson(\"value\")\n   @Path(\"/secrets/{secretName}/versions\")\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   List<Secret> getSecretVersions(@EndpointParam URI vaultBaseUrl, @PathParam(\"secretName\") String secretName);\n\n   @Named(\"secret:update\")\n   @PATCH\n   @MapBinder(BindToJsonPayload.class)\n   @Path(\"/secrets/{secretName}{secretVersion}\")\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   SecretBundle updateSecret(@EndpointParam URI vaultBaseUrl,\n                             @PathParam(\"secretName\") String secretName,\n                             @Nullable @PathParam(\"secretVersion\") @ParamParser(PrependSlashOrEmptyString.class) String secretVersion,\n                             @Nullable @PayloadParam(\"attributes\") SecretAttributes attributes,\n                             @Nullable @PayloadParam(\"contentType\") String contentType,\n                             @Nullable @PayloadParam(\"tags\") Map<String, String> tags);\n\n   @Named(\"secret:backup\")\n   @POST\n   @SelectJson(\"value\")\n   @Path(\"/secrets/{secretName}/backup\")\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   String backupSecret(@EndpointParam URI vaultBaseUrl, @PathParam(\"secretName\") String secretName);\n\n   @Named(\"secret:restore\")\n   @POST\n   @MapBinder(BindToJsonPayload.class)\n   @Path(\"/secrets/restore\")\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   SecretBundle restoreSecret(@EndpointParam URI vaultBaseUrl, @PayloadParam(\"value\") String secretInfo);\n\n   // Soft-delete secret operations\n   @Named(\"secret:list_deleted\")\n   @GET\n   @SelectJson(\"value\")\n   @Path(\"/deletedsecrets\")\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   List<DeletedSecretBundle> listDeletedSecrets(@EndpointParam URI vaultBaseUrl);\n\n   @Named(\"secret:get_deleted\")\n   @GET\n   @Path(\"/deletedsecrets/{secretName}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   DeletedSecretBundle getDeletedSecret(@EndpointParam URI vaultBaseUrl, @PathParam(\"secretName\") String secretName);\n\n   @Named(\"secret:recover_deleted\")\n   @POST\n   @Path(\"/deletedsecrets/{secretName}/recover\")\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   SecretBundle recoverDeletedSecret(@EndpointParam URI vaultBaseUrl, @PathParam(\"secretName\") String secretName);\n\n   @Named(\"secret:purge_deleted\")\n   @DELETE\n   @Path(\"/deletedsecrets/{secretName}\")\n   @Fallback(FalseOnNotFoundOr404.class)\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   boolean purgeDeletedSecret(@EndpointParam URI vaultBaseUrl, @PathParam(\"secretName\") String secretName);\n\n   // Certificate operations\n   @Named(\"certificate:create\")\n   @POST\n   @MapBinder(BindToJsonPayload.class)\n   @Path(\"/certificates/{certificateName}/create\")\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   CertificateOperation createCertificate(@EndpointParam URI vaultBaseUrl,\n         @PathParam(\"certificateName\") String certificateName,\n         @Nullable @PayloadParam(\"attributes\") CertificateAttributes attributes,\n         @Nullable @PayloadParam(\"policy\") CertificatePolicy policy,\n         @Nullable @PayloadParam(\"tags\") Map<String, String> tags);\n\n   @Named(\"certificate:get\")\n   @GET\n   @Path(\"/certificates/{certificateName}{certificateVersion}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   CertificateBundle getCertificate(@EndpointParam URI vaultBaseUrl,\n                                    @PathParam(\"certificateName\") String certificateName,\n                                    @Nullable @PathParam(\"certificateVersion\") @ParamParser(PrependSlashOrEmptyString.class) String certificateVersion);\n\n   @Named(\"certificate:delete\")\n   @DELETE\n   @Path(\"/certificates/{certificateName}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   DeletedCertificateBundle deleteCertificate(@EndpointParam URI vaultBaseUrl,\n         @PathParam(\"certificateName\") String certificateName);\n\n   @Named(\"certificate:list\")\n   @GET\n   @SelectJson(\"value\")\n   @Path(\"/certificates\")\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   List<Certificate> getCertificates(@EndpointParam URI vaultBaseUrl);\n\n   @Named(\"certificate:list_deleted\")\n   @GET\n   @SelectJson(\"value\")\n   @Path(\"/deletedcertificates\")\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   List<DeletedCertificate> getDeletedCertificates(@EndpointParam URI vaultBaseUrl);\n\n   @Named(\"certificate:get_deleted\")\n   @GET\n   @Path(\"/deletedcertificates/{certificateName}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   DeletedCertificateBundle getDeletedCertificate(@EndpointParam URI vaultBaseUrl,\n         @PathParam(\"certificateName\") String certificateName);\n\n   @Named(\"certificate:recover_deleted\")\n   @POST\n   @Path(\"/deletedcertificates/{certificateName}/recover\")\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   CertificateBundle recoverDeletedCertificate(@EndpointParam URI vaultBaseUrl,\n         @PathParam(\"certificateName\") String certificateName);\n\n   @Named(\"certificate:purge_deleted\")\n   @DELETE\n   @Path(\"/deletedcertificates/{certificateName}\")\n   @Fallback(FalseOnNotFoundOr404.class)\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   boolean purgeDeletedCertificate(@EndpointParam URI vaultBaseUrl, @PathParam(\"certificateName\") String certificateName);\n\n   @Named(\"certificate:get_versions\")\n   @GET\n   @SelectJson(\"value\")\n   @Path(\"/certificates/{certificateName}/versions\")\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   List<Certificate> getCertificateVersions(@EndpointParam URI vaultBaseUrl,\n         @PathParam(\"certificateName\") String certificateName);\n\n   @Named(\"certificate:update\")\n   @PATCH\n   @MapBinder(BindToJsonPayload.class)\n   @Path(\"/certificates/{certificateName}{certificateVersion}\")\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   CertificateBundle updateCertificate(@EndpointParam URI vaultBaseUrl,\n                                       @PathParam(\"certificateName\") String certificateName,\n                                       @Nullable @PathParam(\"certificateVersion\") @ParamParser(PrependSlashOrEmptyString.class) String certificateVersion,\n                                       @Nullable @PayloadParam(\"attributes\") CertificateAttributes attributes,\n                                       @Nullable @PayloadParam(\"policy\") CertificatePolicy policy,\n                                       @Nullable @PayloadParam(\"tags\") Map<String, String> tags);\n\n   @Named(\"certificate:import\")\n   @POST\n   @MapBinder(BindToJsonPayload.class)\n   @Path(\"/certificates/{certificateName}/import\")\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   CertificateBundle importCertificate(@EndpointParam URI vaultBaseUrl,\n         @PathParam(\"certificateName\") String certificateName,\n         @Nullable @PayloadParam(\"attributes\") CertificateAttributes attributes,\n         @Nullable @PayloadParam(\"policy\") CertificatePolicy policy, @Nullable @PayloadParam(\"pwd\") String password,\n         @Nullable @PayloadParam(\"tags\") Map<String, String> tags, @PayloadParam(\"value\") String value);\n\n   @Named(\"certificate:merge\")\n   @POST\n   @MapBinder(BindToJsonPayload.class)\n   @Path(\"/certificates/{certificateName}/pending/merge\")\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   CertificateBundle mergeCertificate(@EndpointParam URI vaultBaseUrl,\n         @PathParam(\"certificateName\") String certificateName,\n         @Nullable @PayloadParam(\"attributes\") CertificateAttributes attributes,\n         @Nullable @PayloadParam(\"tags\") Map<String, String> tags, @PayloadParam(\"x5c\") List<String> value);\n\n   @Named(\"certificate:get_operation\")\n   @GET\n   @Path(\"/certificates/{certificateName}/pending\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   CertificateOperation getCertificateOperation(@EndpointParam URI vaultBaseUrl,\n         @PathParam(\"certificateName\") String certificateName);\n\n   @Named(\"certificate:update_operation\")\n   @PATCH\n   @Path(\"/certificates/{certificateName}/pending\")\n   @MapBinder(BindToJsonPayload.class)\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   CertificateOperation updateCertificateOperation(@EndpointParam URI vaultBaseUrl,\n         @PathParam(\"certificateName\") String certificateName,\n         @PayloadParam(\"cancellation_requested\") boolean cancellationRequested);\n\n   @Named(\"certificate:delete_operation\")\n   @DELETE\n   @Path(\"/certificates/{certificateName}/pending\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   CertificateOperation deleteCertificateOperation(@EndpointParam URI vaultBaseUrl,\n         @PathParam(\"certificateName\") String certificateName);\n\n   @Named(\"certificate:set_issuer\")\n   @PUT\n   @Path(\"/certificates/issuers/{issuerName}\")\n   @MapBinder(BindToJsonPayload.class)\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   IssuerBundle setCertificateIssuer(@EndpointParam URI vaultBaseUrl, @PathParam(\"issuerName\") String issuerName,\n         @Nullable @PayloadParam(\"attributes\") IssuerAttributes attributes,\n         @Nullable @PayloadParam(\"credentials\") IssuerCredentials credentials,\n         @Nullable @PayloadParam(\"org_details\") OrganizationDetails orgDetails,\n         @PayloadParam(\"provider\") String provider);\n\n   @Named(\"certificate:get_issuers\")\n   @GET\n   @SelectJson(\"value\")\n   @Path(\"/certificates/issuers\")\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   List<CertificateIssuer> getCertificateIssuers(@EndpointParam URI vaultBaseUrl);\n\n   @Named(\"certificate:get_issuer\")\n   @GET\n   @Path(\"/certificates/issuers/{issuerName}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   IssuerBundle getCertificateIssuer(@EndpointParam URI vaultBaseUrl, @PathParam(\"issuerName\") String issuerName);\n\n   @Named(\"certificate:update_issuer\")\n   @PATCH\n   @Path(\"/certificates/issuers/{issuerName}\")\n   @MapBinder(BindToJsonPayload.class)\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   IssuerBundle updateCertificateIssuer(@EndpointParam URI vaultBaseUrl, @PathParam(\"issuerName\") String issuerName,\n         @Nullable @PayloadParam(\"attributes\") IssuerAttributes attributes,\n         @Nullable @PayloadParam(\"credentials\") IssuerCredentials credentials,\n         @Nullable @PayloadParam(\"org_details\") OrganizationDetails orgDetails,\n         @PayloadParam(\"provider\") String provider);\n\n   @Named(\"certificate:delete_issuer\")\n   @DELETE\n   @Path(\"/certificates/issuers/{issuerName}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   IssuerBundle deleteCertificateIssuer(@EndpointParam URI vaultBaseUrl, @PathParam(\"issuerName\") String issuerName);\n\n   @Named(\"certificate:get_contacts\")\n   @GET\n   @Path(\"/certificates/contacts\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   Contacts getCertificateContacts(@EndpointParam URI vaultBaseUrl);\n\n   @Named(\"certificate:set_contacts\")\n   @PUT\n   @Path(\"/certificates/contacts\")\n   @MapBinder(BindToJsonPayload.class)\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   Contacts setCertificateContacts(@EndpointParam URI vaultBaseUrl, @PayloadParam(\"contacts\") List<Contact> contacts);\n\n   @Named(\"certificate:delete_contacts\")\n   @DELETE\n   @Path(\"/certificates/contacts\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   Contacts deleteCertificateContacts(@EndpointParam URI vaultBaseUrl);\n\n   @Named(\"certificate:get_policy\")\n   @GET\n   @Path(\"/certificates/{certificateName}/policy\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   CertificatePolicy getCertificatePolicy(@EndpointParam URI vaultBaseUrl,\n         @PathParam(\"certificateName\") String certificateName);\n\n   @Named(\"certificate:update_policy\")\n   @PATCH\n   @MapBinder(BindToJsonPayload.class)\n   @Path(\"/certificates/{certificateName}/policy\")\n   @OAuthResource(value = VAULT_API_STANDARD_ENDPOINT, chinaEndpoint = VAULT_API_CHINA_ENDPOINT)\n   CertificatePolicy updateCertificatePolicy(@EndpointParam URI vaultBaseUrl,\n         @PathParam(\"certificateName\") String certificateName,\n         @Nullable @PayloadParam(\"attributes\") CertificateAttributes attributes,\n         @Nullable @PayloadParam(\"issuer\") IssuerParameters issuer,\n         @Nullable @PayloadParam(\"key_props\") KeyProperties keyProps,\n         @Nullable @PayloadParam(\"lifetime_actions\") List<LifetimeAction> lifetimeActions,\n         @Nullable @PayloadParam(\"secret_props\") SecretProperties secretProps,\n         @Nullable @PayloadParam(\"x509_props\") X509CertificateProperties x509Props);\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/features/VirtualMachineApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport java.net.URI;\nimport java.util.List;\nimport java.util.Map;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks;\nimport org.jclouds.azurecompute.arm.domain.Plan;\nimport org.jclouds.azurecompute.arm.domain.VMSize;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachine;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineInstance;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineProperties;\nimport org.jclouds.azurecompute.arm.filters.ApiVersionFilter;\nimport org.jclouds.azurecompute.arm.functions.URIParser;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\n/**\n * The Virtual Machine API includes operations for managing the virtual machines in your subscription.\n *\n * @see <a href=\"https://docs.microsoft.com/en-us/rest/api/compute/virtualmachines\">docs</a>\n */\n@RequestFilters({ OAuthFilter.class, ApiVersionFilter.class })\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface VirtualMachineApi {\n\n   @Named(\"GetVirtualMachine\")\n   @GET\n   @Path(\"/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/virtualMachines/{name}\")\n   @Fallback(Fallbacks.NullOnNotFoundOr404.class)\n   VirtualMachine get(@PathParam(\"name\") String name);\n\n   /**\n    * Get information about the model view and instance view of a virtual machine\n    */\n   @Named(\"GetVirtualMachineInstance\")\n   @GET\n   @Path(\"/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/virtualMachines/{name}/instanceView\")\n   @Fallback(Fallbacks.NullOnNotFoundOr404.class)\n   VirtualMachineInstance getInstanceDetails(@PathParam(\"name\") String name);\n\n   @Named(\"CreateOrUpdateVirtualMachine\")\n   @PUT\n   @MapBinder(BindToJsonPayload.class)\n   @Path(\"/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/virtualMachines/{vmname}\")\n   @QueryParams(keys = \"validating\", values = \"false\")\n   VirtualMachine createOrUpdate(@PathParam(\"vmname\") String vmname, @PayloadParam(\"location\") String location,\n         @PayloadParam(\"properties\") VirtualMachineProperties properties,\n         @PayloadParam(\"tags\") Map<String, String> tags, @Nullable @PayloadParam(\"plan\") Plan plan);\n\n   @Named(\"ListVirtualMachines\")\n   @GET\n   @Path(\"/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/virtualMachines\")\n   @SelectJson(\"value\")\n   @Fallback(Fallbacks.EmptyListOnNotFoundOr404.class)\n   List<VirtualMachine> list();\n\n   @Named(\"ListVirtualMachinesAll\")\n   @GET\n   @Path(\"/providers/Microsoft.Compute/virtualMachines\")\n   @SelectJson(\"value\")\n   @Fallback(Fallbacks.EmptyListOnNotFoundOr404.class)\n   List<VirtualMachine> listAll();\n\n   @Named(\"ListVirtualMachinesByLocation\")\n   @GET\n   @Path(\"/providers/Microsoft.Compute/locations/{location}/virtualMachines\")\n   @SelectJson(\"value\")\n   @Fallback(Fallbacks.EmptyListOnNotFoundOr404.class)\n   List<VirtualMachine> listByLocation(@PathParam(\"location\") String location);\n\n   @Named(\"ListAvailableSizes\")\n   @GET\n   @SelectJson(\"value\")\n   @Path(\"/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/virtualMachines/{name}/vmSizes\")\n   @Fallback(Fallbacks.EmptyListOnNotFoundOr404.class)\n   List<VMSize> listAvailableSizes(@PathParam(\"name\") String name);\n\n   @Named(\"DeleteVirtualMachine\")\n   @DELETE\n   @Path(\"/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/virtualMachines/{name}\")\n   @ResponseParser(URIParser.class)\n   @Fallback(Fallbacks.NullOnNotFoundOr404.class)\n   URI delete(@PathParam(\"name\") String name);\n\n   @Named(\"RestartVirtualMachine\")\n   @POST\n   @Path(\"/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/virtualMachines/{name}/restart\")\n   void restart(@PathParam(\"name\") String name);\n\n   @Named(\"StartVirtualMachine\")\n   @POST\n   @Path(\"/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/virtualMachines/{name}/start\")\n   void start(@PathParam(\"name\") String name);\n\n   @Named(\"StopVirtualMachine\")\n   @POST\n   @Path(\"/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/virtualMachines/{name}/powerOff\")\n   void stop(@PathParam(\"name\") String name);\n\n   @Named(\"DeallocateVirtualMachine\")\n   @POST\n   @Path(\"/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/virtualMachines/{name}/deallocate\")\n   void deallocate(@PathParam(\"name\") String name);\n\n   @Named(\"generalize\")\n   @POST\n   @Path(\"/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/virtualMachines/{name}/generalize\")\n   void generalize(@PathParam(\"name\") String name);\n\n   /**\n    * Capture the virtual machine image\n    * destinationContainerName: the name of the folder created under the \"system\" container in the storage account\n    * Folder structure: Microsoft.Computer > Images > destinationContainerName\n    * Within the folder, there will be 1 page blob for the osDisk vhd and 1 block blob for the vmTemplate json file\n    */\n   @Named(\"capture\")\n   @POST\n   @Payload(\"%7B\\\"vhdPrefix\\\":\\\"{vhdPrefix}\\\",\\\"destinationContainerName\\\":\\\"{destinationContainerName}\\\",\\\"overwriteVhds\\\":\\\"true\\\"%7D\")\n   @Path(\"/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/virtualMachines/{name}/capture\")\n   @ResponseParser(URIParser.class)\n   @Fallback(Fallbacks.NullOnNotFoundOr404.class)\n   @Produces(MediaType.APPLICATION_JSON)\n   URI capture(@PathParam(\"name\") String name, @PayloadParam(\"vhdPrefix\") String vhdPrefix,\n         @PayloadParam(\"destinationContainerName\") String destinationContainerName);\n\n}\n\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/features/VirtualMachineScaleSetApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport org.jclouds.Fallbacks.EmptyListOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineScaleSet;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineScaleSetProperties;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineScaleSetSKU;\nimport org.jclouds.azurecompute.arm.filters.ApiVersionFilter;\nimport org.jclouds.azurecompute.arm.functions.URIParser;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\nimport java.io.Closeable;\nimport java.net.URI;\nimport java.util.List;\nimport java.util.Map;\n\n/**\n * The Virtual Machine Scale Set API includes operations for managing the virtual machines in your subscription.\n *\n * @see <a href=\"https://docs.microsoft.com/en-us/rest/api/virtualmachinescalesets/\">docs</a>\n */\n@Path(\"/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/VirtualMachineScaleSets\")\n@RequestFilters({OAuthFilter.class, ApiVersionFilter.class})\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface VirtualMachineScaleSetApi extends Closeable {\n\n   @Named(\"virtualmachinescaleset:list\")\n   @GET\n   @SelectJson(\"value\")\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   List<VirtualMachineScaleSet> list();\n\n   @Named(\"virtualmachinescaleset:get\")\n   @Path(\"/{name}\")\n   @GET\n   @Fallback(NullOnNotFoundOr404.class)\n   VirtualMachineScaleSet get(@PathParam(\"name\") String name);\n\n   @Named(\"virtualmachinescaleset:createOrUpdate\")\n   @MapBinder(BindToJsonPayload.class)\n   @Path(\"/{name}\")\n   @PUT\n   VirtualMachineScaleSet createOrUpdate(@PathParam(\"name\") String name,\n                                         @PayloadParam(\"location\") String location,\n                                         @PayloadParam(\"sku\") VirtualMachineScaleSetSKU sku,\n                                         @Nullable @PayloadParam(\"tags\") Map<String, String> tags,\n                                         @PayloadParam(\"properties\") VirtualMachineScaleSetProperties properties);\n\n   @Named(\"virtualmachinescaleset:delete\")\n   @Path(\"/{name}\")\n   @DELETE\n   @ResponseParser(URIParser.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   URI delete(@PathParam(\"name\") String name);\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/features/VirtualNetworkApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport java.util.List;\nimport java.util.Map;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyListOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.azurecompute.arm.domain.IpAddressAvailabilityResult;\nimport org.jclouds.azurecompute.arm.domain.VirtualNetwork;\nimport org.jclouds.azurecompute.arm.filters.ApiVersionFilter;\nimport org.jclouds.azurecompute.arm.functions.FalseOn204;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\n/**\n * The Virtual Networks API includes operations for managing Azure virtual networks in your subscription.\n *\n * @see <a href=\"https://docs.microsoft.com/en-us/rest/api/virtualnetwork/virtualnetworks\">docs</a>\n */\n@Path(\"\")\n@RequestFilters({ OAuthFilter.class, ApiVersionFilter.class })\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface VirtualNetworkApi {\n\n   @Named(\"virtualnetwork:list\")\n   @Path(\"/resourcegroups/{resourcegroup}/providers/Microsoft.Network/virtualNetworks\")\n   @SelectJson(\"value\")\n   @GET\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   List<VirtualNetwork> list();\n\n   @Named(\"loadbalancer:listall\")\n   @GET\n   @Path(\"/providers/Microsoft.Network/virtualNetworks\")\n   @SelectJson(\"value\")\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   List<VirtualNetwork> listAll();\n\n   @Named(\"virtualnetwork:create_or_update\")\n   @Path(\"/resourcegroups/{resourcegroup}/providers/Microsoft.Network/virtualNetworks/{virtualnetworkname}\")\n   @MapBinder(BindToJsonPayload.class)\n   @PUT\n   VirtualNetwork createOrUpdate(@PathParam(\"virtualnetworkname\") String virtualnetworkname, @PayloadParam(\"location\") String location, @Nullable @PayloadParam(\"tags\") Map<String, String> tags,\n         @PayloadParam(\"properties\") VirtualNetwork.VirtualNetworkProperties properties);\n\n   @Named(\"virtualnetwork:get\")\n   @Path(\"/resourcegroups/{resourcegroup}/providers/Microsoft.Network/virtualNetworks/{virtualnetworkname}\")\n   @GET\n   @Fallback(NullOnNotFoundOr404.class)\n   VirtualNetwork get(@PathParam(\"virtualnetworkname\") String virtualnetworkname);\n\n   @Named(\"virtualnetwork:delete\")\n   @Path(\"/resourcegroups/{resourcegroup}/providers/Microsoft.Network/virtualNetworks/{virtualnetworkname}\")\n   @DELETE\n   @ResponseParser(FalseOn204.class)\n   boolean delete(@PathParam(\"virtualnetworkname\") String virtualnetworkname);\n\n   @Named(\"virtualnetwork:check_ip_address_availability\")\n   @Path(\"/resourcegroups/{resourcegroup}/providers/Microsoft.Network/virtualNetworks/{virtualnetworkname}/CheckIPAddressAvailability\")\n   @GET\n   IpAddressAvailabilityResult checkIPAddressAvailability(@PathParam(\"virtualnetworkname\") String virtualnetworkname, @QueryParam(\"ipAddress\") String ipAddress);\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/features/VirtualNetworkGatewayApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport java.io.Closeable;\nimport java.net.URI;\nimport java.util.List;\nimport java.util.Map;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyListOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.azurecompute.arm.domain.vpn.VirtualNetworkGateway;\nimport org.jclouds.azurecompute.arm.domain.vpn.VirtualNetworkGatewayProperties;\nimport org.jclouds.azurecompute.arm.filters.ApiVersionFilter;\nimport org.jclouds.azurecompute.arm.functions.URIParser;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\n@Path(\"/resourcegroups/{resourcegroup}/providers/Microsoft.Network/virtualNetworkGateways\")\n@RequestFilters({ OAuthFilter.class, ApiVersionFilter.class })\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface VirtualNetworkGatewayApi extends Closeable {\n\n   @Named(\"virtualnetworkgateway:list\")\n   @GET\n   @SelectJson(\"value\")\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   List<VirtualNetworkGateway> list();\n\n   @Named(\"virtualnetworkgateway:get\")\n   @Path(\"/{name}\")\n   @GET\n   @Fallback(NullOnNotFoundOr404.class)\n   VirtualNetworkGateway get(@PathParam(\"name\") String name);\n\n   @Named(\"virtualnetworkgateway:createOrUpdate\")\n   @MapBinder(BindToJsonPayload.class)\n   @Path(\"/{name}\")\n   @PUT\n   VirtualNetworkGateway createOrUpdate(@PathParam(\"name\") String name, @PayloadParam(\"location\") String location,\n         @Nullable @PayloadParam(\"tags\") Map<String, String> tags,\n         @PayloadParam(\"properties\") VirtualNetworkGatewayProperties properties);\n\n   @Named(\"virtualnetworkgateway:delete\")\n   @Path(\"/{name}\")\n   @DELETE\n   @ResponseParser(URIParser.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   URI delete(@PathParam(\"name\") String name);\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/features/VirtualNetworkGatewayConnectionApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport java.io.Closeable;\nimport java.net.URI;\nimport java.util.List;\nimport java.util.Map;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyListOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.azurecompute.arm.domain.vpn.VirtualNetworkGatewayConnection;\nimport org.jclouds.azurecompute.arm.domain.vpn.VirtualNetworkGatewayConnectionProperties;\nimport org.jclouds.azurecompute.arm.filters.ApiVersionFilter;\nimport org.jclouds.azurecompute.arm.functions.URIParser;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\n@Path(\"/resourcegroups/{resourcegroup}/providers/Microsoft.Network/connections\")\n@RequestFilters({ OAuthFilter.class, ApiVersionFilter.class })\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface VirtualNetworkGatewayConnectionApi extends Closeable {\n\n   @Named(\"virtualnetworkgatewayconnection:list\")\n   @GET\n   @SelectJson(\"value\")\n   @Fallback(EmptyListOnNotFoundOr404.class)\n   List<VirtualNetworkGatewayConnection> list();\n\n   @Named(\"virtualnetworkgatewayconnection:get\")\n   @Path(\"/{name}\")\n   @GET\n   @Fallback(NullOnNotFoundOr404.class)\n   VirtualNetworkGatewayConnection get(@PathParam(\"name\") String name);\n   \n   @Named(\"virtualnetworkgatewayconnection:getSharedKey\")\n   @Path(\"/{name}/sharedkey\")\n   @GET\n   @Fallback(NullOnNotFoundOr404.class)\n   String getSharedKey(@PathParam(\"name\") String name);\n\n   @Named(\"virtualnetworkgatewayconnection:createOrUpdate\")\n   @MapBinder(BindToJsonPayload.class)\n   @Path(\"/{name}\")\n   @PUT\n   VirtualNetworkGatewayConnection createOrUpdate(@PathParam(\"name\") String name,\n         @PayloadParam(\"location\") String location, @Nullable @PayloadParam(\"tags\") Map<String, String> tags,\n         @PayloadParam(\"properties\") VirtualNetworkGatewayConnectionProperties properties);\n\n   @Named(\"virtualnetworkgatewayconnection:delete\")\n   @Path(\"/{name}\")\n   @DELETE\n   @ResponseParser(URIParser.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   URI delete(@PathParam(\"name\") String name);\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/filters/ApiVersionFilter.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.filters;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static org.jclouds.azurecompute.arm.config.AzureComputeProperties.API_VERSION_PREFIX;\nimport static org.jclouds.util.Maps2.transformKeys;\nimport static org.jclouds.util.Predicates2.startsWith;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpRequestFilter;\nimport org.jclouds.rest.config.InvocationConfig;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.reflect.Invokable;\n\n/**\n * Allow users to customize the api versions for each method call.\n * <p>\n * In Azure ARM, each method may have its own api version. This filter allows to\n * configure the versions of each method, so there is no need to change the code\n * when Azure deprecates old versions.\n */\npublic class ApiVersionFilter implements HttpRequestFilter {\n\n   private final InvocationConfig config;\n   private final Map<String, String> versions;\n\n   @Inject\n   ApiVersionFilter(InvocationConfig config, Function<Predicate<String>, Map<String, String>> filterStringsBoundByName) {\n      this.config = config;\n      this.versions = versions(filterStringsBoundByName);\n   }\n\n   @Override\n   public HttpRequest filter(HttpRequest request) throws HttpException {\n      checkArgument(request instanceof GeneratedHttpRequest,\n            \"This filter can only be applied to GeneratedHttpRequest objects\");\n      GeneratedHttpRequest generatedRequest = (GeneratedHttpRequest) request;\n\n      // Look if there is a custom api version for the current method\n      String commandName = config.getCommandName(generatedRequest.getInvocation());\n      String customApiVersion = versions.get(commandName);\n\n      if (customApiVersion == null) {\n         // No custom config for the specific method. Let's look for custom\n         // config for the class\n         Invokable<?, ?> invoked = generatedRequest.getInvocation().getInvokable();\n         String className = invoked.getOwnerType().getRawType().getSimpleName();\n         customApiVersion = versions.get(className);\n      }\n\n      if (customApiVersion != null) {\n         return request.toBuilder().replaceQueryParam(\"api-version\", customApiVersion).build();\n      }\n\n      return request;\n   }\n\n   private static Map<String, String> versions(Function<Predicate<String>, Map<String, String>> filterStringsBoundByName) {\n      Map<String, String> stringBoundWithApiVersionPrefix = filterStringsBoundByName\n            .apply(startsWith(API_VERSION_PREFIX));\n      return transformKeys(stringBoundWithApiVersionPrefix, new Function<String, String>() {\n         public String apply(String input) {\n            return input.replaceFirst(API_VERSION_PREFIX, \"\");\n         }\n      });\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/functions/FalseOn204.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.functions;\nimport com.google.common.base.Function;\nimport org.jclouds.http.HttpResponse;\n\nimport jakarta.inject.Singleton;\n\nimport static org.jclouds.http.HttpUtils.releasePayload;\n/**\n * Parses an http response code from http responser\n */\n@Singleton\npublic class FalseOn204 implements Function<HttpResponse, Boolean> {\n   public Boolean apply(final HttpResponse from) {\n      releasePayload(from);\n      final int statusCode = from.getStatusCode();\n      if (statusCode == 200 || statusCode == 202) {\n         return true;\n      }\n      if (statusCode == 204) {\n         return false;\n      }\n      throw new IllegalStateException(\"not expected response from: \" + from);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/functions/ParseJobStatus.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.functions;\nimport com.google.common.base.Function;\nimport org.jclouds.azurecompute.arm.util.GetEnumValue;\nimport org.jclouds.http.HttpResponse;\n\nimport jakarta.inject.Singleton;\n/**\n * Parses job status from http response\n */\n@Singleton\npublic class ParseJobStatus implements Function<HttpResponse, ParseJobStatus.JobStatus> {\n   public enum JobStatus {\n\n      DONE,\n      IN_PROGRESS,\n      FAILED,\n      NO_CONTENT,\n      UNRECOGNIZED;\n\n      public static JobStatus fromValue(final String text) {\n         return (JobStatus) GetEnumValue.fromValueOrDefault(text, JobStatus.UNRECOGNIZED);\n      }\n   }\n   public JobStatus apply(final HttpResponse from) {\n      if (from.getStatusCode() == 202 ){\n         return JobStatus.IN_PROGRESS;\n      } else if (from.getStatusCode() == 204) {\n         return JobStatus.NO_CONTENT;\n      } else if (from.getStatusCode() == 200 ){\n         return JobStatus.DONE;\n      } else {\n         return JobStatus.FAILED;\n      }\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/functions/StatusCodeParser.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.functions;\nimport com.google.common.base.Function;\nimport org.jclouds.http.HttpResponse;\n\nimport jakarta.inject.Singleton;\n\nimport static org.jclouds.http.HttpUtils.releasePayload;\n\n/**\n * Parses an http response code from http responser\n */\n@Singleton\npublic class StatusCodeParser implements Function<HttpResponse, String> {\n   public String apply(final HttpResponse from) {\n      releasePayload(from);\n      final String statusCode = Integer.toString(from.getStatusCode());\n      if (statusCode != null) {\n         return statusCode;\n      }\n      throw new IllegalStateException(\"did not receive RequestId in: \" + from);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/functions/URIParser.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.functions;\nimport java.net.URI;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpResponse;\n\nimport com.google.common.base.Function;\n/**\n * Parses job status from http response\n */\n@Singleton\npublic class URIParser implements Function<HttpResponse, URI> {\n   public URI apply(final HttpResponse from) {\n      String locationUri;\n      if (from.getStatusCode() == 202 && (locationUri = from.getFirstHeaderOrNull(\"Location\")) != null){\n         return URI.create(locationUri);\n\n      } else if (from.getStatusCode() == 200 || from.getStatusCode() == 204){\n         return null;\n      }\n      throw new IllegalStateException(\"did not receive expected response code and header in: \" + from);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/handlers/AzureComputeErrorHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.handlers;\n\nimport static org.jclouds.azurecompute.arm.handlers.AzureRateLimitRetryHandler.isRateLimitError;\n\nimport java.io.IOException;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.azurecompute.arm.exceptions.AzureComputeRateLimitExceededException;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.jclouds.util.Closeables2;\nimport org.jclouds.util.Strings2;\n\n/**\n * This will parse and set an appropriate exception on the command object.\n */\n@Singleton\npublic class AzureComputeErrorHandler implements HttpErrorHandler {\n\n   @Override\n   public void handleError(final HttpCommand command, final HttpResponse response) {\n      // It is important to always read fully and close streams\n      // For 429 errors the response body might have already been consumed as\n      // some errors report information in the response body that needs to be\n      // handled by the retry handlers.\n      String message = parseMessage(response);\n      Exception exception = message == null\n              ? new HttpResponseException(command, response)\n              : new HttpResponseException(command, response, message);\n      try {\n         message = message == null\n                 ? String.format(\"%s -> %s\", command.getCurrentRequest().getRequestLine(), response.getStatusLine())\n                 : message;\n         switch (response.getStatusCode()) {\n            case 400:\n               if (message.contains(\"unauthorized_client\")) {\n                  exception = new AuthorizationException(message, exception);\n               }\n               else {\n                  exception = new IllegalArgumentException(message, exception);\n               }\n               break;\n            case 401:\n            case 403:\n               exception = new AuthorizationException(message, exception);\n               break;\n\n            case 404:\n               if (!command.getCurrentRequest().getMethod().equals(\"DELETE\")) {\n                  exception = new ResourceNotFoundException(message, exception);\n               }\n               break;\n            case 409:\n               exception = new IllegalStateException(message, exception);\n               break;\n            case 429:\n               if (isRateLimitError(response)) {\n                  exception = new AzureComputeRateLimitExceededException(response, exception);\n               } else {\n                  exception = new IllegalStateException(message, exception);\n               }\n               break;\n            default:\n         }\n      } finally {\n         Closeables2.closeQuietly(response.getPayload());\n         command.setException(exception);\n      }\n   }\n\n   public String parseMessage(final HttpResponse response) {\n      if (response.getPayload() == null) {\n         return null;\n      }\n      try {\n         return Strings2.toStringAndClose(response.getPayload().openStream());\n      } catch (IOException e) {\n         throw new RuntimeException(e);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/handlers/AzureRateLimitRetryHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.handlers;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.handlers.RateLimitRetryHandler;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Optional;\nimport com.google.common.net.HttpHeaders;\n\n/**\n * Handles 429 Too Many Requests responses.\n * <p>\n * The Azure ARM provider also returns this 429 HTTP status code for some errors\n * when resources are busy or in a state where they cannot be modified. In this\n * case this handler delegates to the {@link AzureRetryableErrorHandler} to\n * determine if the requests can be retried.\n */\n@Beta\n@Singleton\npublic class AzureRateLimitRetryHandler extends RateLimitRetryHandler {\n\n   private final AzureRetryableErrorHandler retryableErrorHandler;\n\n   @Inject\n   AzureRateLimitRetryHandler(AzureRetryableErrorHandler retryableErrorHandler) {\n      this.retryableErrorHandler = retryableErrorHandler;\n   }\n\n   @Override\n   protected boolean delayRequestUntilAllowed(HttpCommand command, HttpResponse response) {\n      if (!isRateLimitError(response)) {\n         return retryableErrorHandler.shouldRetryRequest(command, response);\n      }\n      return super.delayRequestUntilAllowed(command, response);\n   }\n\n   @Override\n   protected Optional<Long> millisToNextAvailableRequest(HttpCommand command, HttpResponse response) {\n      String secondsToNextAvailableRequest = response.getFirstHeaderOrNull(HttpHeaders.RETRY_AFTER);\n      return secondsToNextAvailableRequest != null ? Optional.of(Long.parseLong(secondsToNextAvailableRequest) * 1000)\n            : Optional.<Long> absent();\n   }\n\n   public static boolean isRateLimitError(HttpResponse response) {\n      return response.getFirstHeaderOrNull(HttpHeaders.RETRY_AFTER) != null;\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/handlers/AzureRetryableErrorHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.handlers;\n\nimport static org.jclouds.azurecompute.arm.handlers.AzureRateLimitRetryHandler.isRateLimitError;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.azurecompute.arm.domain.Error;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.http.handlers.BackoffLimitedRetryHandler;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.annotations.Beta;\n\n/**\n * This handles failed responses that return a <code>RetryableError</code>.\n * <p>\n * In order to determine if the error is retryable, the response body must be\n * read, so this handler will have to buffer the response payload in memory so\n * the response body can be read again in subsequent steps of the response\n * processing flow.\n */\n@Singleton\n@Beta\npublic class AzureRetryableErrorHandler extends BackoffLimitedRetryHandler {\n\n   private static final String RETRYABLE_ERROR_CODE = \"RetryableError\";\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n   private final ParseJson<Error> parseError;\n\n   @Inject\n   AzureRetryableErrorHandler(ParseJson<Error> parseError) {\n      this.parseError = parseError;\n   }\n\n   @Override\n   public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) {\n      // Only consider retryable errors and discard rate limit ones\n      if (response.getStatusCode() != 429 || isRateLimitError(response)) {\n         return false;\n      }\n\n      try {\n         // Note that this will consume the response body. At this point,\n         // subsequent retry handlers or error handlers will not be able to read\n         // again the payload, but that should only be attempted when the\n         // command is not retryable and an exception should be thrown.\n         Error error = parseError.apply(response);\n         logger.debug(\"processing error: %s\", error);\n\n         boolean isRetryable = RETRYABLE_ERROR_CODE.equals(error.details().code());\n         return isRetryable ? super.shouldRetryRequest(command, response) : false;\n      } catch (Exception ex) {\n         // If we can't parse the error, just assume it is not a retryable error\n         logger.warn(\"could not parse error. Request won't be retried: %s\", ex.getMessage());\n         return false;\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/options/AlertRequestOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.options;\n\nimport static com.google.common.base.Preconditions.checkState;\n\nimport static org.jclouds.azurecompute.arm.reference.AlertQueryParams.TARGET_RESOURCE;\nimport static org.jclouds.azurecompute.arm.reference.AlertQueryParams.TARGET_RESOURCE_GROUP;\nimport static org.jclouds.azurecompute.arm.reference.AlertQueryParams.TARGET_RESOURCE_TYPE;\nimport static org.jclouds.azurecompute.arm.reference.AlertQueryParams.MONITOR_SERVICE;\nimport static org.jclouds.azurecompute.arm.reference.AlertQueryParams.MONITOR_CONDITION;\nimport static org.jclouds.azurecompute.arm.reference.AlertQueryParams.SERVERITY;\nimport static org.jclouds.azurecompute.arm.reference.AlertQueryParams.ALERT_RULE;\nimport static org.jclouds.azurecompute.arm.reference.AlertQueryParams.ALERT_STATE;\nimport static org.jclouds.azurecompute.arm.reference.AlertQueryParams.SMART_GROUP_ID;\nimport static org.jclouds.azurecompute.arm.reference.AlertQueryParams.INCLUDE_CONTEXT;\nimport static org.jclouds.azurecompute.arm.reference.AlertQueryParams.INCLUDE_EGRESS_CONFIG;\nimport static org.jclouds.azurecompute.arm.reference.AlertQueryParams.PAGE_COUNT;\nimport static org.jclouds.azurecompute.arm.reference.AlertQueryParams.SORT_BY;\nimport static org.jclouds.azurecompute.arm.reference.AlertQueryParams.SORT_ORDER;\n\nimport static org.jclouds.azurecompute.arm.reference.AlertQueryParams.SELECT;\nimport static org.jclouds.azurecompute.arm.reference.AlertQueryParams.TIME_RANGE;\nimport static org.jclouds.azurecompute.arm.reference.AlertQueryParams.CUSTOM_TIME_RANGE;\nimport static org.jclouds.azurecompute.arm.reference.AlertQueryParams.GROUP_BY;\nimport static org.jclouds.azurecompute.arm.reference.AlertQueryParams.INCLUDE_SMART_GROUPS_COUNT;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\npublic class AlertRequestOptions extends BaseHttpRequestOptions {\n\n\tpublic static final AlertRequestOptions NONE = new AlertRequestOptions();\n\n\tpublic AlertRequestOptions withTargetResource(String targetResource) {\n\t\tcheckState(!queryParameters.containsKey(TARGET_RESOURCE), \"Can't have duplicate parameter of targetResource\");\n\t\tqueryParameters.put(TARGET_RESOURCE, targetResource);\n\t\treturn this;\n\t}\n\n\tpublic AlertRequestOptions withTargetResourceGroup(String targetResourceGroup) {\n\t\tcheckState(!queryParameters.containsKey(TARGET_RESOURCE_GROUP),\n\t\t\t\t\"Can't have duplicate parameter of targetResourceGroup\");\n\t\tqueryParameters.put(TARGET_RESOURCE_GROUP, targetResourceGroup);\n\t\treturn this;\n\t}\n\n\tpublic AlertRequestOptions withTargetResourceType(String targetResourceType) {\n\t\tcheckState(!queryParameters.containsKey(TARGET_RESOURCE_TYPE),\n\t\t\t\t\"Can't have duplicate parameter of targetResourceType\");\n\t\tqueryParameters.put(TARGET_RESOURCE_TYPE, targetResourceType);\n\t\treturn this;\n\t}\n\n\tpublic AlertRequestOptions withMonitorService(String monitorService) {\n\t\tcheckState(!queryParameters.containsKey(MONITOR_SERVICE), \"Can't have duplicate parameter of monitorService\");\n\t\tqueryParameters.put(MONITOR_SERVICE, monitorService);\n\t\treturn this;\n\t}\n\n\tpublic AlertRequestOptions withMonitorCondition(String monitorCondition) {\n\t\tcheckState(!queryParameters.containsKey(MONITOR_CONDITION),\n\t\t\t\t\"Can't have duplicate parameter of monitorCondition\");\n\t\tqueryParameters.put(MONITOR_CONDITION, monitorCondition);\n\t\treturn this;\n\t}\n\n\tpublic AlertRequestOptions withSeverity(String severity) {\n\t\tcheckState(!queryParameters.containsKey(SERVERITY), \"Can't have duplicate parameter of severity\");\n\t\tqueryParameters.put(SERVERITY, severity);\n\t\treturn this;\n\t}\n\n\tpublic AlertRequestOptions withAlertState(String alertState) {\n\t\tcheckState(!queryParameters.containsKey(ALERT_STATE), \"Can't have duplicate parameter of alertState\");\n\t\tqueryParameters.put(ALERT_STATE, alertState);\n\t\treturn this;\n\t}\n\n\tpublic AlertRequestOptions withAlertRule(String alertRule) {\n\t\tcheckState(!queryParameters.containsKey(ALERT_RULE), \"Can't have duplicate parameter of alertRule\");\n\t\tqueryParameters.put(ALERT_RULE, alertRule);\n\t\treturn this;\n\t}\n\n\tpublic AlertRequestOptions withSmartGroupId(String smartGroupId) {\n\t\tcheckState(!queryParameters.containsKey(SMART_GROUP_ID), \"Can't have duplicate parameter of smartGroupId\");\n\t\tqueryParameters.put(SMART_GROUP_ID, smartGroupId);\n\t\treturn this;\n\t}\n\n\tpublic AlertRequestOptions withIncludeContext(boolean includeContext) {\n\t\tcheckState(!queryParameters.containsKey(INCLUDE_CONTEXT), \"Can't have duplicate parameter of includeContext\");\n\t\tqueryParameters.put(INCLUDE_CONTEXT, String.valueOf(includeContext));\n\t\treturn this;\n\t}\n\n\tpublic AlertRequestOptions withIncludeEgressConfig(boolean includeEgressConfig) {\n\t\tcheckState(!queryParameters.containsKey(INCLUDE_EGRESS_CONFIG),\n\t\t\t\t\"Can't have duplicate parameter of includeEgressConfig\");\n\t\tqueryParameters.put(INCLUDE_EGRESS_CONFIG, String.valueOf(includeEgressConfig));\n\t\treturn this;\n\t}\n\n\tpublic AlertRequestOptions withPageCount(int pageCount) {\n\t\tcheckState(!queryParameters.containsKey(PAGE_COUNT), \"Can't have duplicate parameter of pageCount\");\n\t\tqueryParameters.put(PAGE_COUNT, String.valueOf(pageCount));\n\t\treturn this;\n\t}\n\n\tpublic AlertRequestOptions withSortBy(String sortBy) {\n\t\tcheckState(!queryParameters.containsKey(SORT_BY), \"Can't have duplicate parameter of sortBy\");\n\t\tqueryParameters.put(SORT_BY, sortBy);\n\t\treturn this;\n\t}\n\n\tpublic AlertRequestOptions withSortOrder(String sortOrder) {\n\t\tcheckState(!queryParameters.containsKey(SORT_ORDER), \"Can't have duplicate parameter of sortOrder\");\n\t\tqueryParameters.put(SORT_ORDER, sortOrder);\n\t\treturn this;\n\t}\n\n\tpublic AlertRequestOptions withSelect(String select) {\n\t\tcheckState(!queryParameters.containsKey(SELECT), \"Can't have duplicate parameter of select\");\n\t\tqueryParameters.put(SELECT, select);\n\t\treturn this;\n\t}\n\n\tpublic AlertRequestOptions withTimeRange(String timeRange) {\n\t\tcheckState(!queryParameters.containsKey(TIME_RANGE), \"Can't have duplicate parameter of timeRange\");\n\t\tqueryParameters.put(TIME_RANGE, timeRange);\n\t\treturn this;\n\t}\n\n\tpublic AlertRequestOptions withCustomTimeRange(String customTimeRange) {\n\t\tcheckState(!queryParameters.containsKey(CUSTOM_TIME_RANGE),\n\t\t\t\t\"Can't have duplicate parameter of customTimeRange\");\n\t\tqueryParameters.put(CUSTOM_TIME_RANGE, customTimeRange);\n\t\treturn this;\n\t}\n\n\tpublic AlertRequestOptions withGroupBy(String groupby) {\n\t\tcheckState(!queryParameters.containsKey(GROUP_BY), \"Can't have duplicate parameter of groupby\");\n\t\tqueryParameters.put(GROUP_BY, groupby);\n\t\treturn this;\n\t}\n\n\tpublic AlertRequestOptions withIncludeSmartGroupsCount(boolean includeSmartGroupsCount) {\n\t\tcheckState(!queryParameters.containsKey(INCLUDE_SMART_GROUPS_COUNT),\n\t\t\t\t\"Can't have duplicate parameter of includeSmartGroupsCount\");\n\t\tqueryParameters.put(INCLUDE_SMART_GROUPS_COUNT, String.valueOf(includeSmartGroupsCount));\n\t\treturn this;\n\t}\n\n\t/*\n\t * This method is intended for testing\n\t */\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (this == o)\n\t\t\treturn true;\n\t\tif (o == null || getClass() != o.getClass())\n\t\t\treturn false;\n\n\t\tAlertRequestOptions options = (AlertRequestOptions) o;\n\n\t\treturn buildQueryParameters().equals(options.buildQueryParameters());\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn buildQueryParameters().hashCode();\n\t}\n\n\tpublic static class Builder {\n\n\t\tpublic static AlertRequestOptions targetResource(String targetResource) {\n\t\t\treturn new AlertRequestOptions().withTargetResource(targetResource);\n\t\t}\n\n\t\tpublic static AlertRequestOptions targetResourceGroup(String targetResourceGroup) {\n\t\t\treturn new AlertRequestOptions().withTargetResourceGroup(targetResourceGroup);\n\t\t}\n\n\t\tpublic static AlertRequestOptions targetResourceGroupType(String targetResourceGroupType) {\n\t\t\treturn new AlertRequestOptions().withTargetResourceType(targetResourceGroupType);\n\t\t}\n\n\t\tpublic static AlertRequestOptions monitorService(String monitorService) {\n\t\t\treturn new AlertRequestOptions().withMonitorService(monitorService);\n\t\t}\n\n\t\tpublic static AlertRequestOptions monitorCondition(String monitorCondition) {\n\t\t\treturn new AlertRequestOptions().withMonitorCondition(monitorCondition);\n\t\t}\n\n\t\tpublic static AlertRequestOptions severity(String severity) {\n\t\t\treturn new AlertRequestOptions().withSeverity(severity);\n\t\t}\n\n\t\tpublic static AlertRequestOptions alertState(String alertState) {\n\t\t\treturn new AlertRequestOptions().withAlertState(alertState);\n\t\t}\n\n\t\tpublic static AlertRequestOptions alertRule(String alertRule) {\n\t\t\treturn new AlertRequestOptions().withAlertRule(alertRule);\n\t\t}\n\n\t\tpublic static AlertRequestOptions smartGroupId(String smartGroupId) {\n\t\t\treturn new AlertRequestOptions().withSmartGroupId(smartGroupId);\n\t\t}\n\n\t\tpublic static AlertRequestOptions includeContext(boolean includeContext) {\n\t\t\treturn new AlertRequestOptions().withIncludeContext(includeContext);\n\t\t}\n\n\t\tpublic static AlertRequestOptions includeEgressConfig(boolean includeEgressConfig) {\n\t\t\treturn new AlertRequestOptions().withIncludeEgressConfig(includeEgressConfig);\n\t\t}\n\n\t\tpublic static AlertRequestOptions pageCount(int pageCount) {\n\t\t\treturn new AlertRequestOptions().withPageCount(pageCount);\n\t\t}\n\n\t\tpublic static AlertRequestOptions sortBy(String sortBy) {\n\t\t\treturn new AlertRequestOptions().withSortBy(sortBy);\n\t\t}\n\n\t\tpublic static AlertRequestOptions sortOrder(String sortOrder) {\n\t\t\treturn new AlertRequestOptions().withSortOrder(sortOrder);\n\t\t}\n\n\t\tpublic static AlertRequestOptions select(String select) {\n\t\t\treturn new AlertRequestOptions().withSelect(select);\n\t\t}\n\n\t\tpublic static AlertRequestOptions timeRange(String timeRange) {\n\t\t\treturn new AlertRequestOptions().withTimeRange(timeRange);\n\t\t}\n\n\t\tpublic static AlertRequestOptions customTimeRange(String customTimeRange) {\n\t\t\treturn new AlertRequestOptions().withCustomTimeRange(customTimeRange);\n\t\t}\n\n\t\tpublic static AlertRequestOptions groupBy(String groupBy) {\n\t\t\treturn new AlertRequestOptions().withGroupBy(groupBy);\n\t\t}\n\n\t\tpublic static AlertRequestOptions includeSmartGroupsCount(boolean includeSmartGroupsCount) {\n\t\t\treturn new AlertRequestOptions().withIncludeSmartGroupsCount(includeSmartGroupsCount);\n\t\t}\n\n\t}\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/reference/AlertQueryParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.reference;\n\npublic final class AlertQueryParams {\n\n\tpublic static final String TARGET_RESOURCE = \"targetResource\";\n\tpublic static final String TARGET_RESOURCE_GROUP = \"targetResourceGroup\";\n\tpublic static final String TARGET_RESOURCE_TYPE = \"targetResourceGroupType\";\n\tpublic static final String MONITOR_SERVICE = \"monitorService\";\n\tpublic static final String MONITOR_CONDITION = \"monitorCondition\";\n\tpublic static final String SERVERITY = \"severity\";\n\tpublic static final String ALERT_STATE = \"alertState\";\n\tpublic static final String ALERT_RULE = \"alertRule\";\n\tpublic static final String SMART_GROUP_ID = \"smartGroupId\";\n\tpublic static final String INCLUDE_SMART_GROUPS_COUNT = \"includeSmartGroupsCount\";\n\tpublic static final String INCLUDE_CONTEXT = \"includeContext\";\n\tpublic static final String INCLUDE_EGRESS_CONFIG = \"includeEgressConfig\";\n\tpublic static final String PAGE_COUNT = \"pageCount\";\n\tpublic static final String SORT_BY = \"sortBy\";\n\tpublic static final String SORT_ORDER = \"sortOrder\";\n\tpublic static final String SELECT = \"select\";\n\tpublic static final String TIME_RANGE = \"timeRange\";\n\tpublic static final String CUSTOM_TIME_RANGE = \"customTimeRange\";\n\tpublic static final String GROUP_BY = \"groupby\";\n\n\tprivate AlertQueryParams() {\n\t\tthrow new AssertionError(\"intentionally unimplemented\");\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/util/GetEnumValue.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.util;\n\nimport java.util.EnumSet;\n\npublic class GetEnumValue {\n\n   public static <T extends Enum<T>> Enum<T> fromValueOrDefault(String text, Enum<T> defaultValue) {\n      if (text != null) {\n         EnumSet<T> elements = EnumSet.allOf(defaultValue.getDeclaringClass());\n         for (Enum<T> element : elements) {\n            if (text.equalsIgnoreCase(element.name())) {\n               return element;\n            }\n         }\n      }\n      return defaultValue;\n   }\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/main/java/org/jclouds/azurecompute/arm/util/VMImages.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.util;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\npublic class VMImages {\n\n   public static boolean isCustom(String imageId) {\n      return checkNotNull(imageId, \"id\").split(\"/\").length == 3;\n   }\n  \n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/AzureComputeProviderMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm;\n\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"AzureManagementProviderMetadataTest\")\npublic class AzureComputeProviderMetadataTest extends BaseProviderMetadataTest {\n\n   public AzureComputeProviderMetadataTest() {\n      super(new AzureComputeProviderMetadata(), new AzureManagementApiMetadata());\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/compute/AzureComputeServiceLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.compute;\n\nimport static com.google.common.collect.ImmutableSet.copyOf;\nimport static com.google.common.collect.Iterables.transform;\nimport static org.jclouds.azurecompute.arm.compute.options.AzureTemplateOptions.Builder.resourceGroup;\nimport static org.jclouds.azurecompute.arm.config.AzureComputeProperties.TIMEOUT_RESOURCE_DELETED;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport org.jclouds.azurecompute.arm.AzureComputeApi;\nimport org.jclouds.azurecompute.arm.AzureComputeProviderMetadata;\nimport org.jclouds.azurecompute.arm.internal.AzureLiveTestUtils;\nimport org.jclouds.compute.domain.ComputeMetadata;\nimport org.jclouds.compute.domain.ComputeType;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.domain.TemplateBuilder;\nimport org.jclouds.compute.internal.BaseComputeServiceLiveTest;\nimport org.jclouds.logging.config.LoggingModule;\nimport org.jclouds.logging.slf4j.config.SLF4JLoggingModule;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.scriptbuilder.domain.Statement;\nimport org.jclouds.scriptbuilder.domain.Statements;\nimport org.jclouds.scriptbuilder.statements.java.InstallJDK;\nimport org.jclouds.scriptbuilder.statements.login.AdminAccess;\nimport org.jclouds.sshj.config.SshjSshClientModule;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.inject.Key;\nimport com.google.inject.Module;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.name.Names;\n\n/**\n * Live tests for the {@link org.jclouds.compute.ComputeService} integration.\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"AzureComputeServiceLiveTest\")\npublic class AzureComputeServiceLiveTest extends BaseComputeServiceLiveTest {\n   \n   private Predicate<URI> resourceDeleted;\n   private String resourceGroupName;\n\n   public AzureComputeServiceLiveTest() {\n      provider = \"azurecompute-arm\";\n      resourceGroupName = getClass().getSimpleName().toLowerCase();\n   }\n\n   @Override\n   public void initializeContext() {\n      super.initializeContext();\n      resourceDeleted = context.utils().injector().getInstance(Key.get(new TypeLiteral<Predicate<URI>>() {\n      }, Names.named(TIMEOUT_RESOURCE_DELETED)));\n   }\n\n   // Base method performs Iterables.elementsEqual which is case sensitive.\n   // Azure API can return values in different cases so we'll perform a custom validation\n   @Override\n   @Test(dependsOnMethods = \"testSuspendResume\")\n   public void testListNodesByIds() {\n      final Set<String> nodeIds = copyOf(transform(nodes, new Function<NodeMetadata, String>() {\n\n         @Override\n         public String apply(NodeMetadata from) {\n            return from.getId();\n         }\n\n      }));\n\n      final Set<? extends ComputeMetadata> listedNodes = client.listNodesByIds(nodeIds);\n\n      assertEquals(listedNodes.size(), nodes.size());\n\n      for (ComputeMetadata listedNode : listedNodes) {\n         assert listedNode.getProviderId() != null : listedNode;\n         assert listedNode.getLocation() != null : listedNode;\n         assertEquals(listedNode.getType(), ComputeType.NODE);\n         assert nodeIds.contains(listedNode.getId());\n      }\n   }\n\n   @Override\n   @AfterClass(groups = \"live\", alwaysRun = true)\n   protected void tearDownContext() {\n      try {\n         URI uri = view.unwrapApi(AzureComputeApi.class).getResourceGroupApi().delete(resourceGroupName);\n         if (uri != null) {\n            assertTrue(resourceDeleted.apply(uri),\n                  String.format(\"Resource %s was not terminated in the configured timeout\", uri));\n         }\n      } finally {\n         super.tearDownContext();\n      }\n   }\n\n   @Override\n   protected LoggingModule getLoggingModule() {\n      return new SLF4JLoggingModule();\n   }\n\n   @Override\n   protected Module getSshModule() {\n      return new SshjSshClientModule();\n   }\n\n   @Override\n   protected ProviderMetadata createProviderMetadata() {\n      return AzureComputeProviderMetadata.builder().build();\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties properties = super.setupProperties();\n      AzureLiveTestUtils.defaultProperties(properties);\n      setIfTestSystemPropertyPresent(properties, \"oauth.endpoint\");\n      return properties;\n   }\n\n   @Override\n   protected TemplateBuilder templateBuilder() {\n      return super.templateBuilder().options(\n            resourceGroup(resourceGroupName).authorizePublicKey(keyPair.get(\"public\")).overrideLoginPrivateKey(\n                  keyPair.get(\"private\")));\n   }\n\n   @Override\n   protected Template addRunScriptToTemplate(Template template) {\n      template.getOptions().runScript(\n            Statements.newStatementList(new Statement[] { AdminAccess.standard(), Statements.exec(\"sleep 50\"),\n                  InstallJDK.fromOpenJDK() }));\n      return template;\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/compute/AzureTemplateBuilderLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.compute;\n\nimport static org.jclouds.compute.util.ComputeServiceUtils.getCores;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport org.jclouds.azurecompute.arm.AzureComputeProviderMetadata;\nimport org.jclouds.azurecompute.arm.domain.Region;\nimport org.jclouds.azurecompute.arm.internal.AzureLiveTestUtils;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.internal.BaseTemplateBuilderLiveTest;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.sshj.config.SshjSshClientModule;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Module;\n\n@Test(groups = \"live\", testName = \"AzureTemplateBuilderLiveTest\")\npublic class AzureTemplateBuilderLiveTest extends BaseTemplateBuilderLiveTest {\n\n   public AzureTemplateBuilderLiveTest() {\n      provider = \"azurecompute-arm\";\n   }\n\n   @Override\n   protected Module getSshModule() {\n      return new SshjSshClientModule();\n   }\n\n   @Override\n   protected ProviderMetadata createProviderMetadata() {\n      return AzureComputeProviderMetadata.builder().build();\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties properties = super.setupProperties();\n      AzureLiveTestUtils.defaultProperties(properties);\n      setIfTestSystemPropertyPresent(properties, \"oauth.endpoint\");\n      return properties;\n   }\n\n   @Override\n   @Test\n   public void testDefaultTemplateBuilder() throws IOException {\n      Template defaultTemplate = view.getComputeService().templateBuilder().build();\n      assertTrue(defaultTemplate.getImage().getOperatingSystem().getVersion().matches(\"1[456]\\\\.[01][04](\\\\.[0-9])?-LTS\"),\n            \"Version mismatch, expected dd.dd(.d)?-LTS, found: \"\n                  + defaultTemplate.getImage().getOperatingSystem().getVersion());\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true);\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.UBUNTU);\n      assertEquals(getCores(defaultTemplate.getHardware()), 1.0d);\n   }\n\n   @Override\n   protected Set<String> getIso3166Codes() {\n      return Region.iso3166Codes();\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/compute/extensions/AzureComputeImageExtensionLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.compute.extensions;\n\nimport static org.jclouds.azurecompute.arm.compute.options.AzureTemplateOptions.Builder.resourceGroup;\nimport static org.jclouds.azurecompute.arm.config.AzureComputeProperties.TIMEOUT_RESOURCE_DELETED;\nimport static org.jclouds.compute.options.RunScriptOptions.Builder.wrapInInitScript;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.Map;\nimport java.util.Properties;\n\nimport org.jclouds.azurecompute.arm.AzureComputeApi;\nimport org.jclouds.azurecompute.arm.AzureComputeProviderMetadata;\nimport org.jclouds.azurecompute.arm.internal.AzureLiveTestUtils;\nimport org.jclouds.compute.ComputeTestUtils;\nimport org.jclouds.compute.domain.ExecResponse;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.TemplateBuilder;\nimport org.jclouds.compute.extensions.internal.BaseImageExtensionLiveTest;\nimport org.jclouds.domain.Location;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.sshj.config.SshjSshClientModule;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.inject.Key;\nimport com.google.inject.Module;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.name.Names;\n\n/**\n * Live tests for the {@link org.jclouds.compute.extensions.ImageExtension}\n * integration.\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"AzureComputeImageExtensionLiveTest\")\npublic class AzureComputeImageExtensionLiveTest extends BaseImageExtensionLiveTest {\n\n   private Predicate<URI> resourceDeleted;\n   private String resourceGroupName;\n   \n   public AzureComputeImageExtensionLiveTest() {\n      provider = \"azurecompute-arm\";\n      resourceGroupName = getClass().getSimpleName().toLowerCase();\n   }\n   \n   @BeforeClass(groups = { \"integration\", \"live\" })\n   public void setupContext() {\n      super.setupContext();\n      resourceDeleted = context.utils().injector().getInstance(Key.get(new TypeLiteral<Predicate<URI>>() {\n      }, Names.named(TIMEOUT_RESOURCE_DELETED)));\n      createResourceGroup(resourceGroupName);\n   }\n   \n   @AfterClass(groups = { \"integration\", \"live\" })\n   @Override\n   protected void tearDownContext() {\n      try {\n         URI uri = view.unwrapApi(AzureComputeApi.class).getResourceGroupApi().delete(resourceGroupName);\n         if (uri != null) {\n            assertTrue(resourceDeleted.apply(uri),\n                  String.format(\"Resource %s was not terminated in the configured timeout\", uri));\n         }\n      } finally {\n         super.tearDownContext();\n      }\n   }\n\n   @Override\n   protected void prepareNodeBeforeCreatingImage(NodeMetadata node) {\n      // Don't wrap in the init-script, since the comand will clear the user\n      // config, and jclouds won't be able to execute more than one command\n      // (won't be able to poll for the execution status of the command when\n      // running with the init-script)\n      ExecResponse result = view.getComputeService().runScriptOnNode(node.getId(), \"waagent -deprovision+user -force\",\n            wrapInInitScript(false));\n      assertEquals(result.getExitStatus(), 0);\n   }\n\n   @Override\n   protected Module getSshModule() {\n      return new SshjSshClientModule();\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties properties = super.setupProperties();\n      AzureLiveTestUtils.defaultProperties(properties);\n      setIfTestSystemPropertyPresent(properties, \"oauth.endpoint\");\n      return properties;\n   }\n\n   @Override\n   protected ProviderMetadata createProviderMetadata() {\n      return AzureComputeProviderMetadata.builder().build();\n   }\n\n   @Override\n   public TemplateBuilder getNodeTemplate() {\n      Map<String, String> keyPair = ComputeTestUtils.setupKeyPair();\n      return super.getNodeTemplate().options(\n            resourceGroup(resourceGroupName).authorizePublicKey(keyPair.get(\"public\")).overrideLoginPrivateKey(\n                  keyPair.get(\"private\")));\n   }\n\n   private void createResourceGroup(String name) {\n      Location location = getNodeTemplate().build().getLocation();\n      view.unwrapApi(AzureComputeApi.class).getResourceGroupApi().create(name, location.getId(), null);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/compute/extensions/AzureComputeSecurityGroupExtensionLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.compute.extensions;\n\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static org.jclouds.azurecompute.arm.compute.options.AzureTemplateOptions.Builder.resourceGroup;\nimport static org.jclouds.azurecompute.arm.config.AzureComputeProperties.TIMEOUT_RESOURCE_DELETED;\nimport static org.jclouds.compute.predicates.NodePredicates.inGroup;\nimport static org.jclouds.net.domain.IpProtocol.TCP;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.Properties;\nimport java.util.Set;\nimport java.util.concurrent.ExecutionException;\n\nimport org.jclouds.azurecompute.arm.AzureComputeApi;\nimport org.jclouds.azurecompute.arm.AzureComputeProviderMetadata;\nimport org.jclouds.azurecompute.arm.compute.options.AzureTemplateOptions;\nimport org.jclouds.azurecompute.arm.internal.AzureLiveTestUtils;\nimport org.jclouds.compute.ComputeService;\nimport org.jclouds.compute.RunNodesException;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.SecurityGroup;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.extensions.SecurityGroupExtension;\nimport org.jclouds.compute.extensions.internal.BaseSecurityGroupExtensionLiveTest;\nimport org.jclouds.domain.Location;\nimport org.jclouds.net.domain.IpPermission;\nimport org.jclouds.net.util.IpPermissions;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.inject.Key;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.name.Names;\n\n/**\n * Live test for AzureCompute\n * {@link org.jclouds.compute.extensions.SecurityGroupExtension} implementation.\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"AzureComputeSecurityGroupExtensionLiveTest\")\npublic class AzureComputeSecurityGroupExtensionLiveTest extends BaseSecurityGroupExtensionLiveTest {\n\n   private Predicate<URI> resourceDeleted;\n   private String resourceGroupName;\n\n   public AzureComputeSecurityGroupExtensionLiveTest() {\n      provider = \"azurecompute-arm\";\n      resourceGroupName = \"sgelivetest\";\n   }\n\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   public void setupContext() {\n      super.setupContext();\n      resourceDeleted = context.utils().injector().getInstance(Key.get(new TypeLiteral<Predicate<URI>>() {\n      }, Names.named(TIMEOUT_RESOURCE_DELETED)));\n      createResourceGroup(resourceGroupName);\n   }\n\n   @Test(groups = { \"integration\", \"live\" }, singleThreaded = true, dependsOnMethods = \"testAddIpPermissionsFromSpec\")\n   public void testAddIpPermissionForAnyProtocol() {\n      ComputeService computeService = view.getComputeService();\n      Optional<SecurityGroupExtension> securityGroupExtension = computeService.getSecurityGroupExtension();\n      assertTrue(securityGroupExtension.isPresent(), \"security group extension was not present\");\n\n      SecurityGroup group = securityGroupExtension.get().getSecurityGroupById(groupId);\n      assertNotNull(group, \"No security group was found with id: \" + groupId);\n\n      IpPermission openAll = IpPermissions.permitAnyProtocol();\n      SecurityGroup allOpenSecurityGroup = securityGroupExtension.get().addIpPermission(openAll, group);\n\n      assertTrue(allOpenSecurityGroup.getIpPermissions().contains(openAll));\n   }\n\n   @Test(groups = { \"integration\", \"live\" }, dependsOnMethods = \"testCreateSecurityGroup\")\n   public void testCreateNodeWithSecurityGroup() throws RunNodesException, InterruptedException, ExecutionException {\n      ComputeService computeService = view.getComputeService();\n      Optional<SecurityGroupExtension> securityGroupExtension = computeService.getSecurityGroupExtension();\n      assertTrue(securityGroupExtension.isPresent(), \"security group extension was not present\");\n\n      NodeMetadata node = getOnlyElement(computeService.createNodesInGroup(nodeGroup, 1,\n            options().securityGroups(groupId)));\n\n      try {\n         Set<SecurityGroup> groups = securityGroupExtension.get().listSecurityGroupsForNode(node.getId());\n         assertEquals(groups.size(), 1, \"node has \" + groups.size() + \" groups\");\n         assertEquals(getOnlyElement(groups).getId(), groupId);\n      } finally {\n         computeService.destroyNodesMatching(inGroup(node.getGroup()));\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" }, dependsOnMethods = \"testCreateSecurityGroup\")\n   public void testCreateNodeWithInboundPorts() throws RunNodesException, InterruptedException, ExecutionException {\n      ComputeService computeService = view.getComputeService();\n      Optional<SecurityGroupExtension> securityGroupExtension = computeService.getSecurityGroupExtension();\n      assertTrue(securityGroupExtension.isPresent(), \"security group extension was not present\");\n\n      NodeMetadata node = getOnlyElement(computeService.createNodesInGroup(nodeGroup, 1,\n            options().inboundPorts(22, 23, 24, 8000)));\n\n      try {\n         Set<SecurityGroup> groups = securityGroupExtension.get().listSecurityGroupsForNode(node.getId());\n         assertEquals(groups.size(), 1, \"node has \" + groups.size() + \" groups\");\n\n         SecurityGroup group = getOnlyElement(groups);\n         assertEquals(group.getIpPermissions().size(), 2);\n         assertTrue(group.getIpPermissions().contains(IpPermissions.permit(TCP).fromPort(22).to(24)));\n         assertTrue(group.getIpPermissions().contains(IpPermissions.permit(TCP).port(8000)));\n      } finally {\n         computeService.destroyNodesMatching(inGroup(node.getGroup()));\n      }\n   }\n\n   @AfterClass(groups = { \"integration\", \"live\" })\n   @Override\n   protected void tearDownContext() {\n      try {\n         URI uri = view.unwrapApi(AzureComputeApi.class).getResourceGroupApi().delete(resourceGroupName);\n         if (uri != null) {\n            assertTrue(resourceDeleted.apply(uri),\n                  String.format(\"Resource %s was not terminated in the configured timeout\", uri));\n         }\n      } finally {\n         super.tearDownContext();\n      }\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties properties = super.setupProperties();\n      AzureLiveTestUtils.defaultProperties(properties);\n      setIfTestSystemPropertyPresent(properties, \"oauth.endpoint\");\n      return properties;\n   }\n\n   @Override\n   protected ProviderMetadata createProviderMetadata() {\n      return AzureComputeProviderMetadata.builder().build();\n   }\n   \n   private AzureTemplateOptions options() {\n      return resourceGroup(resourceGroupName);\n   }\n   \n   @Override\n   public Template getNodeTemplate() {\n      return view.getComputeService().templateBuilder().options(options()).build();\n   }\n\n   private void createResourceGroup(String name) {\n      Location location = getNodeTemplate().getLocation();\n      view.unwrapApi(AzureComputeApi.class).getResourceGroupApi().create(name, location.getId(), null);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/compute/functions/VirtualMachineToStatusTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.compute.functions;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Collections;\n\nimport org.jclouds.azurecompute.arm.AzureComputeApi;\nimport org.jclouds.azurecompute.arm.domain.Status;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachine;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineInstance;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineInstance.PowerState;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineProperties;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineProperties.ProvisioningState;\nimport org.jclouds.azurecompute.arm.features.VirtualMachineApi;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"VirtualMachineToStatusTest\")\npublic class VirtualMachineToStatusTest {\n\n   @Test\n   public void testError() {\n      assertStatus(ProvisioningState.FAILED, null, NodeMetadata.Status.ERROR);\n   }\n\n   @Test\n   public void testUnrecognized() {\n      assertStatus(ProvisioningState.UNRECOGNIZED, null, NodeMetadata.Status.UNRECOGNIZED);\n      assertStatus(ProvisioningState.SUCCEEDED, PowerState.UNKNOWN, NodeMetadata.Status.UNRECOGNIZED);\n   }\n\n   @Test\n   public void testTerminated() {\n      assertStatus(ProvisioningState.DELETED, null, NodeMetadata.Status.TERMINATED);\n      assertStatus(ProvisioningState.CANCELED, null, NodeMetadata.Status.TERMINATED);\n   }\n\n   @Test\n   public void testPending() {\n      assertStatus(ProvisioningState.ACCEPTED, null, NodeMetadata.Status.PENDING);\n      assertStatus(ProvisioningState.READY, null, NodeMetadata.Status.PENDING);\n      assertStatus(ProvisioningState.CREATING, null, NodeMetadata.Status.PENDING);\n      assertStatus(ProvisioningState.RUNNING, null, NodeMetadata.Status.PENDING);\n      assertStatus(ProvisioningState.UPDATING, null, NodeMetadata.Status.PENDING);\n\n      assertStatus(ProvisioningState.SUCCEEDED, PowerState.STARTING, NodeMetadata.Status.PENDING);\n      assertStatus(ProvisioningState.SUCCEEDED, PowerState.STOPPING, NodeMetadata.Status.PENDING);\n      assertStatus(ProvisioningState.SUCCEEDED, PowerState.DEALLOCATING, NodeMetadata.Status.PENDING);\n   }\n\n   @Test\n   public void testSuspended() {\n      assertStatus(ProvisioningState.SUCCEEDED, PowerState.STOPPED, NodeMetadata.Status.SUSPENDED);\n      assertStatus(ProvisioningState.SUCCEEDED, PowerState.DEALLOCATED, NodeMetadata.Status.SUSPENDED);\n   }\n\n   @Test\n   public void testRunning() {\n      assertStatus(ProvisioningState.SUCCEEDED, PowerState.RUNNING, NodeMetadata.Status.RUNNING);\n   }\n\n   @Test\n   public void testPendingWhenInstanceNotFound() {\n      AzureComputeApi api = createMock(AzureComputeApi.class);\n      VirtualMachineApi vmApi = createMock(VirtualMachineApi.class);\n      VirtualMachine vm = createMock(VirtualMachine.class);\n      VirtualMachineProperties props = createMock(VirtualMachineProperties.class);\n\n      expect(vm.id()).andReturn(\"/resourceGroups/test/virtualMachines/vm\");\n      expect(vm.properties()).andReturn(props);\n      expect(vm.name()).andReturn(\"vm\");\n      expect(props.provisioningState()).andReturn(ProvisioningState.SUCCEEDED);\n      expect(api.getVirtualMachineApi(\"test\")).andReturn(vmApi);\n      expect(vmApi.getInstanceDetails(\"vm\")).andReturn(null);\n      replay(props, vm, vmApi, api);\n\n      assertEquals(new VirtualMachineToStatus(api).apply(vm).status(), NodeMetadata.Status.PENDING);\n\n      verify(props, vm, vmApi, api);\n   }\n\n   @Test\n   public void testPendingWhenInstanceHasNoPowerState() {\n      AzureComputeApi api = createMock(AzureComputeApi.class);\n      VirtualMachineApi vmApi = createMock(VirtualMachineApi.class);\n      VirtualMachine vm = createMock(VirtualMachine.class);\n      VirtualMachineProperties props = createMock(VirtualMachineProperties.class);\n      VirtualMachineInstance instance = createMock(VirtualMachineInstance.class);\n\n      expect(vm.id()).andReturn(\"/resourceGroups/test/virtualMachines/vm\");\n      expect(vm.properties()).andReturn(props);\n      expect(vm.name()).andReturn(\"vm\");\n      expect(props.provisioningState()).andReturn(ProvisioningState.SUCCEEDED);\n      expect(api.getVirtualMachineApi(\"test\")).andReturn(vmApi);\n      expect(vmApi.getInstanceDetails(\"vm\")).andReturn(instance);\n      expect(instance.powerState()).andReturn(null);\n      replay(props, vm, vmApi, api, instance);\n\n      assertEquals(new VirtualMachineToStatus(api).apply(vm).status(), NodeMetadata.Status.PENDING);\n\n      verify(props, vm, vmApi, api, instance);\n   }\n\n   private void assertStatus(ProvisioningState provisioningState, PowerState powerState, NodeMetadata.Status expected) {\n      VirtualMachine vm = createMock(VirtualMachine.class);\n      VirtualMachineProperties props = createMock(VirtualMachineProperties.class);\n\n      expect(vm.id()).andReturn(\"/resourceGroups/test/virtualMachines/vm\");\n      expect(vm.properties()).andReturn(props);\n      expect(props.provisioningState()).andReturn(provisioningState);\n\n      AzureComputeApi api = null;\n      VirtualMachineApi vmApi = null;\n      VirtualMachineInstance instance = null;\n\n      if (powerState != null) {\n         api = createMock(AzureComputeApi.class);\n         vmApi = createMock(VirtualMachineApi.class);\n         instance = createMock(VirtualMachineInstance.class);\n\n         expect(vm.name()).andReturn(\"vm\");\n\n         expect(api.getVirtualMachineApi(\"test\")).andReturn(vmApi);\n         expect(vmApi.getInstanceDetails(\"vm\")).andReturn(instance);\n         expect(instance.powerState()).andReturn(powerState).times(2);\n         expect(instance.statuses()).andReturn(Collections.<Status> emptyList());\n         replay(instance, vmApi, api);\n      }\n      replay(props, vm);\n\n      assertEquals(new VirtualMachineToStatus(api).apply(vm).status(), expected);\n\n      verify(props, vm);\n      if (powerState != null) {\n         verify(instance, vmApi, api);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/compute/strategy/CreateResourcesThenCreateNodesTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.compute.strategy;\n\nimport static org.easymock.EasyMock.anyObject;\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.azurecompute.arm.AzureComputeApi;\nimport org.jclouds.azurecompute.arm.compute.options.AzureTemplateOptions;\nimport org.jclouds.azurecompute.arm.compute.options.IpOptions;\nimport org.jclouds.azurecompute.arm.domain.Subnet;\nimport org.jclouds.azurecompute.arm.domain.publicipaddress.PublicIPAddress;\nimport org.jclouds.azurecompute.arm.domain.publicipaddress.PublicIPAddressProperties;\nimport org.jclouds.azurecompute.arm.features.PublicIPAddressApi;\nimport org.jclouds.azurecompute.arm.features.SubnetApi;\nimport org.jclouds.util.PasswordGenerator;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"CreateResourcesThenCreateNodesTest\")\npublic class CreateResourcesThenCreateNodesTest {\n\n   @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = \"The options.networks and options.ipOptions are exclusive\")\n   public void testNormalizeNetworkOptionsWithConflictingConfig() {\n      AzureTemplateOptions options = new AzureTemplateOptions();\n      options.ipOptions(IpOptions.builder().subnet(netResource(\"/virtualNetworks/vn/subnets/foo\")).build());\n      options.networks(netResource(\"/virtualNetworks/vn/subnets/bar\"));\n      strategy(null).normalizeNetworkOptions(options);\n   }\n   \n   @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = \"The allocateNewPublicIps and publicIpId are exclusive\")\n   public void testNormalizeNetworkOptionsExclusivePublicIps() {\n      AzureTemplateOptions options = new AzureTemplateOptions();\n      options.ipOptions(IpOptions.builder().subnet(netResource(\"/virtualNetworks/vn/subnets/foo\"))\n            .allocateNewPublicIp(true).publicIpId(netResource(\"/publicIPAddresses/pub\")).build());\n      strategy(null).normalizeNetworkOptions(options);\n   }\n\n   public void testPortableNetworkOptions() {\n      AzureComputeApi api = createMock(AzureComputeApi.class);\n      SubnetApi subnetApi = createMock(SubnetApi.class);\n\n      expect(api.getSubnetApi(anyObject(String.class), anyObject(String.class))).andReturn(subnetApi).times(2);\n      expect(subnetApi.get(anyObject(String.class))).andReturn(Subnet.builder().build()).times(2);\n      replay(api, subnetApi);\n\n      AzureTemplateOptions options = new AzureTemplateOptions();\n      options.networks(netResource(\"/virtualNetworks/vn/subnets/foo\"), netResource(\"/virtualNetworks/vn/subnets/bar\"));\n      strategy(api).normalizeNetworkOptions(options);\n\n      assertEquals(options.getIpOptions(), ImmutableList.of(\n              IpOptions.builder().subnet(netResource(\"/virtualNetworks/vn/subnets/foo\")).allocateNewPublicIp(true).build(), \n              IpOptions.builder().subnet(netResource(\"/virtualNetworks/vn/subnets/bar\")).allocateNewPublicIp(true).build())\n      );\n\n      // Verify that the code has validated that the subnets exist\n      verify(api, subnetApi);\n   }\n\n   public void testProviderSpecificNetworkOptions() {\n      AzureComputeApi api = createMock(AzureComputeApi.class);\n      SubnetApi subnetApi = createMock(SubnetApi.class);\n      PublicIPAddressApi publicIpApi = createMock(PublicIPAddressApi.class);\n\n      expect(api.getSubnetApi(anyObject(String.class), anyObject(String.class))).andReturn(subnetApi).times(2);\n      expect(api.getPublicIPAddressApi(anyObject(String.class))).andReturn(publicIpApi);\n      expect(subnetApi.get(anyObject(String.class))).andReturn(Subnet.builder().build()).times(2);\n      expect(publicIpApi.get(anyObject(String.class))).andReturn(mockAddress());\n      replay(api, subnetApi, publicIpApi);\n\n      IpOptions publicOpts = IpOptions.builder().subnet(netResource(\"/virtualNetworks/vn/subnets/foo\"))\n            .publicIpId(netResource(\"/publicIPAddresses/pub\")).address(\"10.0.0.2\").build();\n      IpOptions privateOpts = IpOptions.builder().subnet(netResource(\"/virtualNetworks/vn/subnets/bar\")).build();\n\n      AzureTemplateOptions options = new AzureTemplateOptions();\n      options.ipOptions(publicOpts, privateOpts);\n      strategy(api).normalizeNetworkOptions(options);\n\n      assertEquals(options.getIpOptions(), ImmutableList.of(publicOpts, privateOpts));\n\n      // Verify that the code has validated that the subnets exist\n      verify(api, subnetApi, publicIpApi);\n   }\n\n   private static CreateResourcesThenCreateNodes strategy(AzureComputeApi api) {\n      return new CreateResourcesThenCreateNodes(null, null, null, null, null, api, null, null, null, null,\n            new PasswordGenerator().lower(), null); \n   }\n\n   private static String netResource(String resource) {\n      return \"/subscriptions/subs/resourceGroups/rg/providers/Microsoft.Network\" + resource;\n   }\n\n   private static PublicIPAddress mockAddress() {\n      return PublicIPAddress.builder().name(\"name\").id(\"id\").etag(\"etag\").location(\"location\")\n            .properties(PublicIPAddressProperties.builder().publicIPAllocationMethod(\"Dynamic\").build()).build();\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/config/AzureNameValidatorTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.config;\n\nimport org.jclouds.azurecompute.arm.compute.config.AzureNameValidator;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Strings;\n\n@Test(groups = \"unit\", testName = \"AzureNameValidatorTest\")\npublic class AzureNameValidatorTest {\n\n   AzureNameValidator validator = new AzureNameValidator();\n\n   @Test\n   public void testNamesValidity() {\n      validator.validate(\"7sdaiDD00-_.rrr\");\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testEmptyName() {\n      validator.validate(\"\");\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testNullName() {\n      validator.validate(null);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testNameTooShort() {\n      validator.validate(\"x\");\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testNameTooLong() {\n      validator.validate(Strings.repeat(\"x\", 64));\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testInvalidStartingCharacterInName() {\n      validator.validate(\"_whatever\");\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testInvalidCharactersInName() {\n      validator.validate(\"is/not/ok/\");\n   }\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/config/IsChinaEndpointTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.config;\n\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"IsChinaEndpointTest\")\npublic class IsChinaEndpointTest {\n\n   @Test\n   public void testIsChinaEndpoint() {\n      AzureComputeHttpApiModule module = new AzureComputeHttpApiModule();\n\n      assertTrue(module.isChinaEndpoint(\"https://login.chinacloudapi.cn/tenantId/oauth2/token\"));\n      assertFalse(module.isChinaEndpoint(\"http://login.chinacloudapi.cn/tenantId/oauth2/token\"));\n      assertFalse(module.isChinaEndpoint(\"https://login.chinacloudapi.cn/otherpaths/not/oauth\"));\n      assertFalse(module.isChinaEndpoint(\"https://login.microsoftonline.com/tenantId/oauth2/token\"));\n      assertFalse(module.isChinaEndpoint(\"https://login.microsoft.com/otherpaths/not/oauth\"));\n   }\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/config/ParseTenantIdTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.config;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.fail;\n\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ParseTenantIdTest\")\npublic class ParseTenantIdTest {\n\n   @Test\n   public void testParseTenantId() {\n      AzureComputeHttpApiModule module = new AzureComputeHttpApiModule();\n\n      assertEquals(module.provideTenant(\"https://login.microsoftonline.com/tenantId/oauth2/token\"), \"tenantId\");\n      assertEquals(module.provideTenant(\"https://login.microsoft.com/tenant2/oauth2/token\"), \"tenant2\");\n      assertEquals(module.provideTenant(\"https://login.chinacloudapi.cn/tenantId/oauth2/token\"), \"tenantId\");\n      assertEquals(module.provideTenant(\"https://login.chinacloudapi.cn/tenant2/oauth2/token\"), \"tenant2\");\n\n      assertInvalid(module, \"https://login.microsoftonline.com/a/b/c/oauth2/token\");\n      assertInvalid(module, \"https://login.microsoft.com/a/b/c/oauth2/token\");\n      assertInvalid(module, \"https://login.microsoftonline.com//oauth2/token\");\n      assertInvalid(module, \"https://login.microsoft.com//oauth2/token\");\n      assertInvalid(module, \"https://login.chinacloudapi.cn/a/b/c/oauth2/token\");\n      assertInvalid(module, \"https://login.chinacloudapi.cn//oauth2/token\");\n   }\n\n   private static void assertInvalid(AzureComputeHttpApiModule module, String endpoint) {\n      try {\n         module.provideTenant(endpoint);\n         fail(\"Expected an IllegalArgumentException for endpoint: \" + endpoint);\n      } catch (IllegalArgumentException ex) {\n         assertEquals(ex.getMessage(), \"Could not parse tenantId from: \" + endpoint);\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/domain/IdReferenceTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport static org.jclouds.azurecompute.arm.domain.IdReference.extractName;\nimport static org.jclouds.azurecompute.arm.domain.IdReference.extractResourceGroup;\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"IdReferenceTest\")\npublic class IdReferenceTest {\n\n   @Test\n   public void testExtractResourceGroup() {\n      assertEquals(extractResourceGroup(null), null);\n      assertEquals(extractResourceGroup(\"\"), null);\n      assertEquals(\n            extractResourceGroup(\"/subscriptions/subscription/resourceGroups/jclouds-northeurope/providers/Microsoft.Compute/virtualMachines/resources-8c5\"),\n            \"jclouds-northeurope\");\n      assertEquals(extractResourceGroup(\"/subscriptions/subscription/resourceGroups/jclouds-west\"), \"jclouds-west\");\n      assertEquals(extractResourceGroup(\"/resourceGroups/jclouds-west2\"), \"jclouds-west2\");\n      assertEquals(\n            extractResourceGroup(\"/resourceGroups/jclouds-northeurope2/providers/Microsoft.Compute/virtualMachines/resources-8c5\"),\n            \"jclouds-northeurope2\");\n      assertEquals(extractResourceGroup(\"resourceGroups/jclouds-west2\"), null);\n      assertEquals(\n            extractResourceGroup(\"resourceGroups/jclouds-northeurope2/providers/Microsoft.Compute/virtualMachines/resources-8c5\"),\n            null);\n      assertEquals(\n            extractResourceGroup(\"/subscriptions/subscription/providers/Microsoft.Compute/virtualMachines/resources-8c5\"),\n            null);\n      assertEquals(\n            extractResourceGroup(\"/subscriptions/subscription/resourceGroups//jclouds-northeurope/providers/Microsoft.Compute/virtualMachines/resources-8c5\"),\n            null);\n   }\n\n   @Test\n   public void testExtractName() {\n      assertEquals(extractName(null), null);\n      assertEquals(extractName(\"\"), \"\");\n      assertEquals(extractName(\"foo\"), \"foo\");\n      assertEquals(extractName(\"/foo/bar\"), \"bar\");\n      assertEquals(extractName(\"/foo/bar/\"), \"bar\");\n      assertEquals(extractName(\"/foo/bar////\"), \"bar\");\n      assertEquals(extractName(\"/foo///bar////\"), \"bar\");\n      assertEquals(extractName(\"////bar\"), \"bar\");\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/domain/SubnetTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.domain;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.fail;\n\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"SubnetTest\")\npublic class SubnetTest {\n\n   @Test\n   public void testExtractVirtualNetwork() {\n\n      assertEquals(Subnet.builder().build().virtualNetwork(), null);\n      assertEquals(\n            Subnet.builder()\n                  .id(\"/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/virtualNetworks/vn/subnets/subnet\")\n                  .build().virtualNetwork(), \"vn\");\n      assertInvalidId(\"/subscriptions/subscription/resourceGroups/rg/providers/Microsoft.Network/virtualNetworks\");\n      assertInvalidId(\"virtualNetworks/vn\");\n   }\n\n   private static void assertInvalidId(String id) {\n      try {\n         Subnet.builder().id(id).build().virtualNetwork();\n         fail(\"The given ID \" + id + \"should not match a valid virtual network\");\n      } catch (IllegalStateException ex) {\n         // Expected\n      }\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/ActivityLogAlertApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\nimport org.checkerframework.checker.nullness.qual.Nullable;\nimport org.jclouds.azurecompute.arm.domain.ActivityLogAlert;\nimport org.jclouds.azurecompute.arm.domain.ActivityLogAlertProperties;\nimport org.jclouds.azurecompute.arm.domain.AlertRuleAllOfCondition;\nimport org.jclouds.azurecompute.arm.domain.AlertRuleAnyOfOrLeafCondition;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiLiveTest;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\n\n@Test(groups = \"live\", testName = \"ActivityLogAlertApiLiveTest\", singleThreaded = true)\npublic class ActivityLogAlertApiLiveTest extends BaseAzureComputeApiLiveTest {\n\n\tprivate String alertRuleName;\n\tprivate String subscriptionid;\n\tprivate final String GLOBAL = \"Global\";\n\n\t@BeforeClass\n\t@Override\n\tpublic void setup() {\n\t\tsuper.setup();\n\t\tsubscriptionid = getSubscriptionId();\n\t\tcreateTestResourceGroup();\n\t\talertRuleName = String.format(\"vn-%s-%s\", this.getClass().getSimpleName().toLowerCase(),\n\t\t\t\tSystem.getProperty(\"user.name\"));\n\n\t}\t \n\n\tprivate ActivityLogAlertApi api() {\n\t\treturn api.getActivityLogAlertApi(resourceGroupName);\n\t}\n\n\t@Test\n\tpublic void testCreate() {\n\t\tActivityLogAlert activityAlert = api().createOrUpdate(alertRuleName, properties(),\n\t\t\t\tImmutableMap.of(\"createdBy\", \"jclouds\"), GLOBAL);\n\t\tassertTrue(!activityAlert.type().isEmpty());\n\t}\n\n\t@Test(dependsOnMethods = \"testCreate\")\n\tpublic void testGet() {\n\t\tfinal ActivityLogAlert activityLogAlertRule = api().get(alertRuleName);\n\t\tassertTrue(!activityLogAlertRule.name().isEmpty());\n\t}\n\n\t@Test(dependsOnMethods = \"testCreate\")\n\tpublic void testList() {\n\t\tList<ActivityLogAlert> list = api().list();\n\t\tfinal ActivityLogAlert activityLogAlertRule = api().get(alertRuleName);\n\t\tboolean alertRulePresent = Iterables.any(list, new Predicate<ActivityLogAlert>() {\n\t\t\t@Override\n\t\t\tpublic boolean apply(@Nullable ActivityLogAlert input) {\n\t\t\t\treturn input.name().equals(activityLogAlertRule.name());\n\t\t\t}\n\t\t});\n\n\t\tassertTrue(alertRulePresent);\n\t}\n\n\t@Test(dependsOnMethods = \"testList\", alwaysRun = true)\n\tpublic void testDelete() throws Exception {\n\t\tURI uri = api().delete(alertRuleName);\n\t\tassertResourceDeleted(uri);\n\t}\n\n\tpublic ActivityLogAlertProperties properties() {\n\t\treturn ActivityLogAlertProperties.create(\"LiveTest\", true,\n\t\t\t\tArrays.asList(\"/subscriptions/\" + subscriptionid + \"/resourceGroups/\" + resourceGroupName), condition(),\n\t\t\t\tnull);\n\n\t}\n\n\tpublic AlertRuleAllOfCondition condition() {\n\t\tfinal List<AlertRuleAnyOfOrLeafCondition> list1 = new ArrayList<>();\n\t\tfinal AlertRuleAnyOfOrLeafCondition alertRuleAnyOfOrLeafCondition0 = AlertRuleAnyOfOrLeafCondition.create(null,\n\t\t\t\tnull, \"Administrative\", \"category\");\n\t\tfinal AlertRuleAnyOfOrLeafCondition alertRuleAnyOfOrLeafCondition1 = AlertRuleAnyOfOrLeafCondition.create(null,\n\t\t\t\tnull, \"Microsoft.Compute/virtualMachines\", \"resourceType\");\n\t\tlist1.add(alertRuleAnyOfOrLeafCondition0);\n\t\tlist1.add(alertRuleAnyOfOrLeafCondition1);\n\t\tfinal AlertRuleAllOfCondition condtion = AlertRuleAllOfCondition.create(list1, null);\n\t\treturn condtion;\n\t}\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/ActivityLogAlertApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport static com.google.common.collect.Iterables.isEmpty;\nimport static org.junit.Assert.assertNotNull;\nimport static org.junit.Assert.assertNull;\nimport static org.junit.Assert.assertTrue;\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.azurecompute.arm.domain.ActionGroup;\nimport org.jclouds.azurecompute.arm.domain.Actions;\nimport org.jclouds.azurecompute.arm.domain.ActivityLogAlert;\nimport org.jclouds.azurecompute.arm.domain.ActivityLogAlertProperties;\nimport org.jclouds.azurecompute.arm.domain.AlertRuleAllOfCondition;\nimport org.jclouds.azurecompute.arm.domain.AlertRuleAnyOfOrLeafCondition;\nimport org.jclouds.azurecompute.arm.domain.AlertRuleLeafCondition;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiMockTest;\nimport org.testng.annotations.Test;\n\nimport okhttp3.mockwebserver.MockResponse;\n\n@Test(groups = \"unit\", testName = \"ActivityLogAlertApiMockTest\", singleThreaded = true)\npublic class ActivityLogAlertApiMockTest extends BaseAzureComputeApiMockTest {\n\n\tpublic void testList() throws InterruptedException {\n\t\tserver.enqueue(jsonResponse(\"/activitylogalertresourcegroup.json\"));\n\t\tfinal ActivityLogAlertApi activityLogAlertApi = api.getActivityLogAlertApi(\"myResourceGroup\");\n\t\tassertEquals(activityLogAlertApi.list(), getActivityLogRuleList());\n\t\tassertSent(server, \"GET\",\n\t\t\t\t\"/subscriptions/SUBSCRIPTIONID/resourcegroups/myResourceGroup/providers/Microsoft.Insights/activityLogAlerts?api-version=2020-10-01\");\n\t}\n\n\tprivate List<ActivityLogAlert> getActivityLogRuleList() {\n\t\tList<ActivityLogAlert> activityLogAlertRules = new ArrayList<ActivityLogAlert>();\n\t\tactivityLogAlertRules.add(ActivityLogAlert.create(\n\t\t\t\t\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/microsoft.insights/activityLogAlerts/myActivityLog\",\n\t\t\t\t\"myActivityLog\", \"Global\", \"Microsoft.Insights/ActivityLogAlerts\", tags(),\n\t\t\t\tmyActivityLogAlertProperties()));\n\t\tactivityLogAlertRules.add(ActivityLogAlert.create(\n\t\t\t\t\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/microsoft.insights/activityLogAlerts/simpleActivityLog\",\n\t\t\t\t\"simpleActivityLog\", \"Global\", \"Microsoft.Insights/ActivityLogAlerts\", null,\n\t\t\t\tsampleActivityLogAlertProperties()));\n\t\treturn activityLogAlertRules;\n\t}\n\n\tpublic ActivityLogAlertProperties myActivityLogAlertProperties() {\n\t\treturn ActivityLogAlertProperties.create(\"\", false, scope0(), condition0(), actions());\n\t}\n\n\tpublic ActivityLogAlertProperties sampleActivityLogAlertProperties() {\n\t\treturn ActivityLogAlertProperties.create(\"\", true, scope1(), condition1(), actions());\n\n\t}\n\n\tpublic void testListEmpty() throws Exception {\n\t\tserver.enqueue(new MockResponse().setResponseCode(404));\n\t\tfinal ActivityLogAlertApi activityApi = api.getActivityLogAlertApi(\"groupname\");\n\t\tList<ActivityLogAlert> list = activityApi.list();\n\t\tassertTrue(isEmpty(list));\n\t\tassertSent(server, \"GET\",\n\t\t\t\t\"/subscriptions/SUBSCRIPTIONID/resourcegroups/groupname/providers/Microsoft.Insights/activityLogAlerts?api-version=2020-10-01\");\n\t}\n\n\tpublic void testGet() throws InterruptedException {\n\t\tserver.enqueue(jsonResponse(\"/activitylogalertget.json\"));\n\t\tfinal ActivityLogAlertApi activityApi = api.getActivityLogAlertApi(\"myResourceGroup\");\n\t\tActivityLogAlert alert = activityApi.get(\"myActivityLogAlert\");\n\t\tassertEquals(alert.location(), \"Global\");\n\t\tassertSent(server, \"GET\",\n\t\t\t\t\"/subscriptions/SUBSCRIPTIONID/resourcegroups/myResourceGroup/providers/Microsoft.Insights/activityLogAlerts/myActivityLogAlert?api-version=2020-10-01\");\n\t}\n\t\n\tpublic void testGetReturns404() throws InterruptedException {\n\t\tserver.enqueue(response404());\n\t\tfinal ActivityLogAlertApi activityApi = api.getActivityLogAlertApi(\"myResourceGroup\");\n\t\tActivityLogAlert alert = activityApi.get(\"myActivityLogAlert\");\n\t\tassertNull(alert);\n\t\tassertSent(server, \"GET\",\n\t\t\t\t\"/subscriptions/SUBSCRIPTIONID/resourcegroups/myResourceGroup/providers/Microsoft.Insights/activityLogAlerts/myActivityLogAlert?api-version=2020-10-01\");\n\t}\n\n\tpublic void testDelete() throws Exception {\n\t\tserver.enqueue(response202WithHeader());\n\t\tfinal ActivityLogAlertApi activityApi = api.getActivityLogAlertApi(\"myResourceGroup\");\n\t\tURI uri = activityApi.delete(\"myActivityLogAlert\");\n\t\tassertEquals(server.getRequestCount(), 1);\n\t\tassertNotNull(uri);\n\t\tassertSent(server, \"DELETE\",\n\t\t\t\t\"/subscriptions/SUBSCRIPTIONID/resourcegroups/myResourceGroup/providers/Microsoft.Insights/activityLogAlerts/myActivityLogAlert?api-version=2020-10-01\");\n\t}\n\n\tpublic void testDeleteReturns404() throws Exception {\n\t\tserver.enqueue(response404());\n\t\tfinal ActivityLogAlertApi activityApi = api.getActivityLogAlertApi(\"myResourceGroup\");\n\t\tURI uri = activityApi.delete(\"myActivityLogAlert\");\n\t\tassertEquals(server.getRequestCount(), 1);\n\t\tassertNull(uri);\n\t\tassertSent(server, \"DELETE\",\n\t\t\t\t\"/subscriptions/SUBSCRIPTIONID/resourcegroups/myResourceGroup/providers/Microsoft.Insights/activityLogAlerts/myActivityLogAlert?api-version=2020-10-01\");\n\t}\n\n\tpublic Map<String, String> tags() {\n\t\tMap<String, String> tags = new HashMap<>();\n\t\ttags.put(\"key1\", \"value1\");\n\t\ttags.put(\"key2\", \"value2\");\n\t\treturn tags;\n\t}\n\n\tpublic List<String> scope0() {\n\t\tList<String> list = new ArrayList<String>();\n\t\tlist.add(\n\t\t\t\t\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM\");\n\t\treturn list;\n\t}\n\n\tpublic List<String> scope1() {\n\t\tList<String> list = new ArrayList<String>();\n\t\tlist.add(\n\t\t\t\t\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/simpleVM\");\n\n\t\treturn list;\n\t}\n\n\tpublic AlertRuleAllOfCondition condition0() {\n\t\tfinal List<AlertRuleAnyOfOrLeafCondition> list1 = new ArrayList<>();\n\t\tfinal AlertRuleAnyOfOrLeafCondition alertRuleAnyOfOrLeafCondition = AlertRuleAnyOfOrLeafCondition.create(null,\n\t\t\t\tnull, \"ServiceHealth\", \"category\");\n\t\tlist1.add(alertRuleAnyOfOrLeafCondition);\n\t\tfinal AlertRuleAllOfCondition condtion = AlertRuleAllOfCondition.create(list1, \"\");\n\t\treturn condtion;\n\t}\n\n\tpublic AlertRuleAllOfCondition condition1() {\n\t\tfinal List<AlertRuleAnyOfOrLeafCondition> list1 = new ArrayList<>();\n\t\tfinal AlertRuleAnyOfOrLeafCondition alertRuleAnyOfOrLeafCondition0 = AlertRuleAnyOfOrLeafCondition.create(null,\n\t\t\t\tnull, \"Administrative\", \"category\");\n\t\tfinal AlertRuleAnyOfOrLeafCondition alertRuleAnyOfOrLeafCondition1 = AlertRuleAnyOfOrLeafCondition.create(null,\n\t\t\t\tnull, \"Microsoft.Compute/virtualMachines/write\", \"operationName\");\n\t\tlist1.add(alertRuleAnyOfOrLeafCondition0);\n\t\tlist1.add(alertRuleAnyOfOrLeafCondition1);\n\t\tfinal AlertRuleAllOfCondition condtion = AlertRuleAllOfCondition.create(list1, null);\n\t\treturn condtion;\n\t}\n\n\tpublic List<AlertRuleAnyOfOrLeafCondition> allOf() {\n\t\tList<AlertRuleAnyOfOrLeafCondition> list = new ArrayList<>();\n\t\tlist.add(anyOfOrLeafCondition());\n\t\treturn list;\n\t}\n\n\tpublic AlertRuleAnyOfOrLeafCondition anyOfOrLeafCondition() {\n\t\tAlertRuleAnyOfOrLeafCondition alertRule = AlertRuleAnyOfOrLeafCondition.create(leafCondition(), null, null,\n\t\t\t\tnull);\n\t\treturn alertRule;\n\t}\n\n\tpublic List<AlertRuleLeafCondition> leafCondition() {\n\t\tfinal List<AlertRuleLeafCondition> list = new ArrayList<>();\n\t\tfinal AlertRuleLeafCondition alertRuleLeafCondition = AlertRuleLeafCondition.create(null, \"ServiceHealth\",\n\t\t\t\t\"category\");\n\t\tlist.add(alertRuleLeafCondition);\n\t\treturn list;\n\t}\n\n\tpublic Actions actions() {\n\t\tList<ActionGroup> list = new ArrayList<>();\n\t\tActionGroup actionGroup = ActionGroup.create(\n\t\t\t\t\"/subscriptions/SUBSCRIPTIONID/resourcegroups/myResourceGroup/providers/microsoft.insights/actiongroups/myAction\",\n\t\t\t\tnull);\n\t\tlist.add(actionGroup);\n\t\tActions action = Actions.create(list);\n\t\treturn action;\n\t}\n\n\tpublic void testCreate() throws Exception {\n\t\tserver.enqueue(jsonResponse(\"/activitylogalertcreate.json\"));\n\t\tfinal ActivityLogAlertApi activityApi = api.getActivityLogAlertApi(\"myResourceGroup\");\n\t\tActivityLogAlert activityAlert = activityApi.createOrUpdate(\"myActivityLogAlertRule\",\n\t\t\t\tmyActivityLogAlertProperties(), new HashMap<>(), \"Global\");\n\t\tfinal ActivityLogAlert expected = ActivityLogAlert.create(\n\t\t\t\t\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/microsoft.insights/activityLogAlerts/myActivityLogAlertRule\",\n\t\t\t\t\"myActivityLogAlertRule\", \"Global\", \"Microsoft.Insights/ActivityLogAlerts\", tags(),\n\t\t\t\tmyActivityLogAlertProperties());\n\t\tassertEquals(activityAlert.id(), expected.id());\n\t\tassertSent(server, \"PUT\",\n\t\t\t\t\"/subscriptions/SUBSCRIPTIONID/resourcegroups/myResourceGroup/providers/Microsoft.Insights/activityLogAlerts/myActivityLogAlertRule?validating=false&api-version=2020-10-01\");\n\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/AlertApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.List;\n\nimport org.jclouds.azurecompute.arm.domain.Alert;\nimport org.jclouds.azurecompute.arm.domain.AlertModification;\nimport org.jclouds.azurecompute.arm.domain.AlertSummary;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiLiveTest;\nimport org.jclouds.azurecompute.arm.options.AlertRequestOptions;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"AlertApiLiveTest\", singleThreaded = true)\npublic class AlertApiLiveTest extends BaseAzureComputeApiLiveTest {\n\n\tprivate String alertId;\n\n\tprivate AlertApi alertApi() {\n\t\treturn api.getAlertApi(\"\");\n\t}\n\n\t@Test\n\tpublic void testList() {\n\t\tAlertRequestOptions pageCount = AlertRequestOptions.Builder.pageCount(1);\n\t\tList<Alert> result = alertApi().list(pageCount);\n\t\tSystem.out.println(result.size());\n\t\tassertNotNull(result);\n\t\tassertTrue(result.size() > 0);\n\t\tfinal String id = result.get(0).id();\n\t\talertId = id.substring(id.lastIndexOf(\"/\") + 1);\n\t}\n\n\t@Test(dependsOnMethods = \"testList\")\n\tpublic void testGetById() {\n\t\tAlert alert = alertApi().get(alertId);\n\t\tassertNotNull(alert);\n\t}\n\n\t@Test(dependsOnMethods = \"testList\")\n\tpublic void testGetHistory() {\n\t\tAlertModification history = alertApi().getHistory(alertId);\n\t\tassertNotNull(history);\n\t}\n\n\t@Test(dependsOnMethods = \"testList\")\n\tpublic void testGetSummary() {\n\t\tAlertRequestOptions groupByOption = AlertRequestOptions.Builder.groupBy(\"severity\");\n\t\tAlertSummary summary = alertApi().getSummary(groupByOption);\n\t\tassertNotNull(summary);\n\t}\n\n\t@Test(dependsOnMethods = \"testList\")\n\tpublic void testAlertChangeState() {\n\t\tAlert alert = alertApi().changeState(alertId, \"Closed\");\n\t\tassertNotNull(alert);\n\t\tassertEquals(\"Closed\", alertApi().get(alertId).properties().essentials().alertState().name());\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/AlertApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport static org.junit.Assert.assertNotNull;\nimport static org.junit.Assert.assertNull;\nimport static org.junit.Assert.assertTrue;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.List;\n\nimport org.jclouds.azurecompute.arm.domain.Alert;\nimport org.jclouds.azurecompute.arm.domain.AlertModification;\nimport org.jclouds.azurecompute.arm.domain.AlertSummary;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiMockTest;\nimport org.jclouds.azurecompute.arm.options.AlertRequestOptions;\nimport org.testng.annotations.Test;\n\nimport static com.google.common.collect.Iterables.isEmpty;\nimport okhttp3.mockwebserver.MockResponse;\n\n@Test(groups = \"unit\", testName = \"AlertApiMockTest\", singleThreaded = true)\npublic class AlertApiMockTest extends BaseAzureComputeApiMockTest {\n\n\tpublic void testGetById() throws InterruptedException {\n\t\tserver.enqueue(jsonResponse(\"/alertsgetbyid.json\"));\n\t\tfinal AlertApi alertApi = api.getAlertApi(\"resourceGroups/myResourceGroup\");\n\t\tAlert alert = alertApi.get(\"60c4d62b-xxxx-46d8-0000-b6dd8c4a769e\");\n\t\tfinal String alertName = alert.name();\n\t\tassertEquals(alertName, \"SampleAlert\");\n\t\tassertSent(server, \"GET\",\n\t\t\t\t\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.AlertsManagement/alerts/60c4d62b-xxxx-46d8-0000-b6dd8c4a769e?api-version=2019-03-01\");\n\t}\n\n\tpublic void testGetByIdEmpty() throws Exception {\n\t\tserver.enqueue(new MockResponse().setResponseCode(404));\n\t\tfinal AlertApi alertApi = api.getAlertApi(\"resourceGroups/myResourceGroup\");\n\t\tAlert alert = alertApi.get(\"60c4d62b-xxxx-46d8-0000-b6dd8c4a769e\");\n\t\tassertNull(alert);\n\t\tassertSent(server, \"GET\",\n\t\t\t\t\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.AlertsManagement/alerts/60c4d62b-xxxx-46d8-0000-b6dd8c4a769e?api-version=2019-03-01\");\n\t}\n\n\tpublic void testGetHistory() throws InterruptedException {\n\t\tserver.enqueue(jsonResponse(\"/alertgethistory.json\"));\n\t\tfinal AlertApi alertApi = api.getAlertApi(\"resourceGroups/myResourceGroup\");\n\t\tAlertModification history = alertApi.getHistory(\"d9db1f27-ce08-4c6d-8ab6-c0a8fbd8bf64\");\n\t\tfinal String type = history.type();\n\t\tassertEquals(type, \"Microsoft.AlertsManagement/alerts\");\n\t\tassertSent(server, \"GET\",\n\t\t\t\t\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.AlertsManagement/alerts/d9db1f27-ce08-4c6d-8ab6-c0a8fbd8bf64/history?api-version=2019-03-01\");\n\t}\n\n\tpublic void testGetHistoryEmpty() throws Exception {\n\t\tserver.enqueue(new MockResponse().setResponseCode(404));\n\t\tfinal AlertApi alertApi = api.getAlertApi(\"resourceGroups/myResourceGroup\");\n\t\tAlertModification history = alertApi.getHistory(\"d9db1f27-ce08-4c6d-8ab6-c0a8fbd8bf64\");\n\t\tassertNull(history);\n\t\tassertSent(server, \"GET\",\n\t\t\t\t\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.AlertsManagement/alerts/d9db1f27-ce08-4c6d-8ab6-c0a8fbd8bf64/history?api-version=2019-03-01\");\n\t}\n\n\tpublic void testGetSummary() throws InterruptedException {\n\t\tserver.enqueue(jsonResponse(\"/alertgetsummary.json\"));\n\t\tfinal AlertApi alertApi = api.getAlertApi(\"resourceGroups/myResourceGroup\");\n\t\tAlertRequestOptions groupByOption = AlertRequestOptions.Builder.groupBy(\"severity\");\n\t\tAlertSummary summary = alertApi.getSummary(groupByOption);\n\t\tfinal String alertName = summary.name();\n\t\tassertEquals(alertName, \"current\");\n\t\tassertSent(server, \"GET\",\n\t\t\t\t\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.AlertsManagement/alertsSummary?groupby=severity&api-version=2019-03-01\");\n\t}\n\n\tpublic void testGetSummaryEmpty() throws Exception {\n\t\tserver.enqueue(new MockResponse().setResponseCode(404));\n\t\tfinal AlertApi alertApi = api.getAlertApi(\"resourceGroups/myResourceGroup\");\n\t\tAlertRequestOptions groupByOption = AlertRequestOptions.Builder.groupBy(\"severity\");\n\t\tAlertSummary summary = alertApi.getSummary(groupByOption);\n\t\tassertNull(summary);\n\t\tassertSent(server, \"GET\",\n\t\t\t\t\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.AlertsManagement/alertsSummary?groupby=severity&api-version=2019-03-01\");\n\t}\n\n\tpublic void testGetAll() throws InterruptedException {\n\t\tserver.enqueue(jsonResponse(\"/alertgetall.json\"));\n\t\tfinal AlertApi alertApi = api.getAlertApi(\"resourceGroups/myResourceGroup\");\n\t\tList<Alert> list = alertApi.list();\n\t\tassertEquals(list.get(0).name(), \"HostPoolAlert\");\n\t\tassertSent(server, \"GET\",\n\t\t\t\t\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.AlertsManagement/alerts?api-version=2019-03-01\");\n\t}\n\n\tpublic void testGetAllEmpty() throws Exception {\n\t\tserver.enqueue(new MockResponse().setResponseCode(404));\n\t\tfinal AlertApi alertApi = api.getAlertApi(\"resourceGroups/myResourceGroup\");\n\t\tList<Alert> list = alertApi.list();\n\t\tassertTrue(isEmpty(list));\n\t\tassertSent(server, \"GET\",\n\t\t\t\t\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.AlertsManagement/alerts?api-version=2019-03-01\");\n\t}\n\n\tpublic void testAlertChangeState() throws InterruptedException {\n\t\tserver.enqueue(jsonResponse(\"/alertchangestate.json\"));\n\t\tfinal AlertApi alertApi = api.getAlertApi(\"resourceGroups/myResourceGroup\");\n\t\tAlert alert = alertApi.changeState(\"650d5726-xxxx-4e8c-0000-504d577da210\", \"Closed\");\n\t\tassertNotNull(alert);\n\t\tassertSent(server, \"POST\",\n\t\t\t\t\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.AlertsManagement/alerts/650d5726-xxxx-4e8c-0000-504d577da210/changestate?newState=Closed&api-version=2019-03-01\");\n\t}\n\t\n\tpublic void testAlertChangeStateReturns404() throws InterruptedException {\n\t\tserver.enqueue(response404());\n\t\tfinal AlertApi alertApi = api.getAlertApi(\"resourceGroups/myResourceGroup\");\n\t\tAlert alert = alertApi.changeState(\"650d5726-xxxx-4e8c-0000-504d577da210\", \"Closed\");\n\t\tassertNull(alert);\n\t\tassertSent(server, \"POST\",\n\t\t\t\t\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.AlertsManagement/alerts/650d5726-xxxx-4e8c-0000-504d577da210/changestate?newState=Closed&api-version=2019-03-01\");\n\t\t\n\t}\t\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/AvailabilitySetApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport static com.google.common.collect.Iterables.any;\nimport static org.jclouds.azurecompute.arm.domain.AvailabilitySet.AvailabilitySetType.MANAGED;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.UUID;\n\nimport org.jclouds.azurecompute.arm.domain.AvailabilitySet;\nimport org.jclouds.azurecompute.arm.domain.AvailabilitySet.AvailabilitySetProperties;\nimport org.jclouds.azurecompute.arm.domain.AvailabilitySet.SKU;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiLiveTest;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableMap;\n\n@Test(groups = \"live\", testName = \"AvailabilitySetApiLiveTest\", singleThreaded = true)\npublic class AvailabilitySetApiLiveTest extends BaseAzureComputeApiLiveTest {\n\n   private String asName;\n\n   @BeforeClass\n   @Override\n   public void setup() {\n      super.setup();\n      createTestResourceGroup();\n      asName = \"jclouds-\" + RAND;\n   }\n\n   @Test\n   public void deleteAvailabilitySetDoesNotExist() {\n      assertNull(api().delete(UUID.randomUUID().toString()));\n   }\n\n   @Test\n   public void createAvailabilitySet() {\n      AvailabilitySetProperties props = AvailabilitySetProperties.builder().platformUpdateDomainCount(2)\n            .platformFaultDomainCount(3).build();\n      AvailabilitySet as = api().createOrUpdate(asName, SKU.create(MANAGED), LOCATION, null, props);\n\n      assertNotNull(as);\n      assertEquals(as.name(), asName);\n      \n      assertNotNull(as.sku());\n      assertEquals(as.sku().type(), MANAGED);\n   }\n\n   @Test(dependsOnMethods = \"createAvailabilitySet\")\n   public void getAvailabilitySet() {\n      assertNotNull(api().get(asName));\n   }\n   \n   @Test(dependsOnMethods = \"createAvailabilitySet\")\n   public void listAvailabilitySet() {\n      assertTrue(any(api().list(), new Predicate<AvailabilitySet>() {\n         @Override\n         public boolean apply(AvailabilitySet input) {\n            return asName.equals(input.name());\n         }\n      }));\n   }\n   \n   @Test(dependsOnMethods = \"createAvailabilitySet\")\n   public void updateAvailabilitySet() {\n      AvailabilitySet as = api().get(asName);\n      as = api().createOrUpdate(asName, SKU.create(MANAGED), LOCATION, ImmutableMap.of(\"foo\", \"bar\"), as.properties());\n\n      assertNotNull(as);\n      assertTrue(as.tags().containsKey(\"foo\"));\n      assertEquals(as.tags().get(\"foo\"), \"bar\");\n   }\n   \n   @Test(dependsOnMethods = { \"getAvailabilitySet\", \"listAvailabilitySet\", \"updateAvailabilitySet\" })\n   public void deleteAvailabilitySet() {\n      URI uri = api().delete(asName);\n      assertResourceDeleted(uri);\n   }\n\n   private AvailabilitySetApi api() {\n      return api.getAvailabilitySetApi(resourceGroupName);\n   }\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/AvailabilitySetApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport static com.google.common.collect.Iterables.isEmpty;\nimport static org.jclouds.azurecompute.arm.domain.AvailabilitySet.AvailabilitySetType.MANAGED;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport org.jclouds.azurecompute.arm.domain.AvailabilitySet;\nimport org.jclouds.azurecompute.arm.domain.AvailabilitySet.AvailabilitySetProperties;\nimport org.jclouds.azurecompute.arm.domain.AvailabilitySet.SKU;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiMockTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"AvailabilitySetApiMockTest\", singleThreaded = true)\npublic class AvailabilitySetApiMockTest extends BaseAzureComputeApiMockTest {\n\n   private final String subscriptionid = \"SUBSCRIPTIONID\";\n   private final String resourcegroup = \"myresourcegroup\";\n   private final String asName = \"myas\";\n   private final String apiVersion = \"api-version=2016-04-30-preview\";\n\n   public void createAvailabilitySet() throws InterruptedException {\n\n      server.enqueue(jsonResponse(\"/availabilitysetcreate.json\").setResponseCode(200));\n\n      AvailabilitySetApi asApi = api.getAvailabilitySetApi(resourcegroup);\n\n      AvailabilitySetProperties props = AvailabilitySetProperties.builder().platformUpdateDomainCount(2)\n            .platformFaultDomainCount(3).build();\n      AvailabilitySet as = asApi.createOrUpdate(asName, SKU.create(MANAGED), \"westeurope\", null, props);\n\n      String path = String.format(\n            \"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Compute/availabilitySets/%s?%s\", subscriptionid,\n            resourcegroup, asName, apiVersion);\n      String json = \"{\\\"location\\\":\\\"westeurope\\\",\\\"properties\\\":{\\\"platformUpdateDomainCount\\\":2,\\\"platformFaultDomainCount\\\":3},\\\"sku\\\":{\\\"name\\\":\\\"Aligned\\\"}}\";\n      assertSent(server, \"PUT\", path, json);\n\n      assertEquals(as.name(), asName);\n      assertEquals(as.properties().platformUpdateDomainCount(), 2);\n      assertEquals(as.properties().platformFaultDomainCount(), 3);\n   }\n\n   public void getAvailabilitySet() throws InterruptedException {\n\n      server.enqueue(jsonResponse(\"/availabilitysetget.json\").setResponseCode(200));\n\n      AvailabilitySetApi asApi = api.getAvailabilitySetApi(resourcegroup);\n\n      AvailabilitySet as = asApi.get(asName);\n\n      String path = String.format(\n            \"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Compute/availabilitySets/%s?%s\", subscriptionid,\n            resourcegroup, asName, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertEquals(as.name(), asName);\n   }\n\n   public void getAvailabilitySet404() throws InterruptedException {\n      server.enqueue(response404());\n\n      AvailabilitySetApi asApi = api.getAvailabilitySetApi(resourcegroup);\n\n      AvailabilitySet as = asApi.get(asName);\n\n      String path = String.format(\n            \"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Compute/availabilitySets/%s?%s\", subscriptionid,\n            resourcegroup, asName, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertNull(as);\n   }\n\n   public void listAvailabilitySets() throws InterruptedException {\n\n      server.enqueue(jsonResponse(\"/availabilitysetlist.json\").setResponseCode(200));\n\n      AvailabilitySetApi asApi = api.getAvailabilitySetApi(resourcegroup);\n\n      List<AvailabilitySet> asList = asApi.list();\n\n      String path = String.format(\n            \"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Compute/availabilitySets?%s\", subscriptionid,\n            resourcegroup, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertTrue(asList.size() > 0);\n   }\n\n   public void listAvailabilitySets404() throws InterruptedException {\n      server.enqueue(response404());\n\n      AvailabilitySetApi asApi = api.getAvailabilitySetApi(resourcegroup);\n\n      List<AvailabilitySet> asList = asApi.list();\n\n      String path = String.format(\n            \"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Compute/availabilitySets?%s\", subscriptionid,\n            resourcegroup, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertTrue(isEmpty(asList));\n   }\n\n   public void deleteAvailabilitySet() throws InterruptedException {\n\n      server.enqueue(response202WithHeader());\n\n      AvailabilitySetApi asApi = api.getAvailabilitySetApi(resourcegroup);\n\n      URI uri = asApi.delete(asName);\n      assertNotNull(uri);\n\n      String path = String.format(\n            \"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Compute/availabilitySets/%s?%s\", subscriptionid,\n            resourcegroup, asName, apiVersion);\n      assertSent(server, \"DELETE\", path);\n   }\n\n   public void deleteAvailabilitySetDoesNotExist() throws InterruptedException {\n\n      server.enqueue(response204());\n\n      AvailabilitySetApi asApi = api.getAvailabilitySetApi(resourcegroup);\n\n      URI uri = asApi.delete(asName);\n      assertNull(uri);\n\n      String path = String.format(\n            \"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Compute/availabilitySets/%s?%s\", subscriptionid,\n            resourcegroup, asName, apiVersion);\n      assertSent(server, \"DELETE\", path);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/DeploymentApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport org.jclouds.azurecompute.arm.domain.Deployment;\nimport org.jclouds.azurecompute.arm.domain.Deployment.ProvisioningState;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiLiveTest;\nimport org.jclouds.util.Predicates2;\nimport org.testng.Assert;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.net.UrlEscapers;\n\n@Test(groups = \"live\", testName = \"DeploymentApiLiveTest\", singleThreaded = true)\npublic class DeploymentApiLiveTest extends BaseAzureComputeApiLiveTest {\n\n   private String deploymentName;\n   private String properties;\n   private String badProperties;\n\n   @BeforeClass\n   @Override\n   public void setup() {\n      super.setup();\n      createTestResourceGroup();\n      deploymentName = \"jc\" + System.currentTimeMillis();\n      String storageAccountName = String.format(\"st%s%s\", System.getProperty(\"user.name\"), RAND);\n\n      String rawtemplate = \"{\\\"$schema\\\":\\\"https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#\\\",\\\"contentVersion\\\":\\\"1.0.0.0\\\",\\\"parameters\\\":{\\\"newStorageAccountName\\\":{\\\"type\\\":\\\"string\\\",\\\"metadata\\\":{\\\"description\\\":\\\"Name of the Storage Account\\\"}},\\\"storageAccountType\\\":{\\\"type\\\":\\\"string\\\",\\\"defaultValue\\\":\\\"Standard_LRS\\\",\\\"allowedValues\\\":[\\\"Standard_LRS\\\",\\\"Standard_GRS\\\",\\\"Standard_ZRS\\\"],\\\"metadata\\\":{\\\"description\\\":\\\"Storage Account type\\\"}},\\\"location\\\":{\\\"type\\\":\\\"string\\\",\\\"allowedValues\\\":[\\\"East US\\\",\\\"West US\\\",\\\"West Europe\\\",\\\"East Asia\\\",\\\"Southeast Asia\\\"],\\\"metadata\\\":{\\\"description\\\":\\\"Location of storage account\\\"}}},\\\"resources\\\":[{\\\"type\\\":\\\"Microsoft.Storage/storageAccounts\\\",\\\"name\\\":\\\"[parameters('newStorageAccountName')]\\\",\\\"apiVersion\\\":\\\"2015-05-01-preview\\\",\\\"location\\\":\\\"[parameters('location')]\\\",\\\"properties\\\":{\\\"accountType\\\":\\\"[parameters('storageAccountType')]\\\"}}]}\";\n      String rawparameters = \"{\\\"newStorageAccountName\\\":{\\\"value\\\":\\\"\" + storageAccountName + \"\\\"},\\\"storageAccountType\\\":{\\\"value\\\":\\\"Standard_LRS\\\"},\\\"location\\\":{\\\"value\\\":\\\"West US\\\"}}\";\n      String rawbadParameters = \"{\\\"newStorageAccountName\\\":{\\\"value\\\":\\\"\" + storageAccountName + \"\\\"},\\\"storageAccountType\\\":{\\\"value\\\":\\\"Standard_LRS\\\"},\\\"location\\\":{\\\"value\\\":\\\"West\\\"}}\";\n\n      properties = getPutBody(rawtemplate, \"Incremental\", rawparameters);\n      badProperties = getPutBody(rawtemplate, \"Incremental\", rawbadParameters);\n   }\n\n   private String getPutBody(String template, String mode, String parameters) {\n      String body = \"{ \" +\n              \"\\\"properties\\\" : \" +\n              \"  { \" +\n              \"    \\\"template\\\" : \" + template + \", \" +\n              \"    \\\"mode\\\" : \\\"\" + mode + \"\\\", \" +\n              \"    \\\"parameters\\\" : \" + parameters + \" \" +\n              \"  } \" +\n              \"}\";\n      return body;\n   }\n\n   @Test\n   public void testValidate(){\n      Deployment deploymentInvalid = null;\n      try {\n         deploymentInvalid = api().validate(deploymentName + \"invalid\", badProperties);\n      } catch (Exception ex) {\n         assertTrue(ex.getClass() == java.lang.IllegalArgumentException.class);\n      }\n      assertNull(deploymentInvalid);\n\n      Deployment deploymentValid = null;\n      try {\n         deploymentValid = api().validate(deploymentName + \"valid\", properties);\n      } catch (Exception ex) {\n         assertTrue(ex.getClass() == java.lang.IllegalArgumentException.class);\n      }\n      assertNotNull(deploymentValid);\n   }\n   \n   @Test(dependsOnMethods = \"testValidate\")\n   public void testCreate() {\n      String deploymentTemplate = UrlEscapers.urlFormParameterEscaper().escape(properties);\n\n      Deployment deploymentValid = api().validate(deploymentName, deploymentTemplate);\n      assertNotNull(deploymentValid);\n\n      Deployment deployment = api().create(deploymentName, deploymentTemplate);\n      assertNotNull(deployment);\n\n      //Poll until resource is ready to be used\n      boolean jobDone = Predicates2.retry(new Predicate<String>() {\n         @Override\n         public boolean apply(String name) {\n            Deployment dp = api().get(deploymentName);\n            ProvisioningState state = ProvisioningState.fromValue(dp.properties().provisioningState());\n            if (state == ProvisioningState.FAILED) Assert.fail();\n            return state == ProvisioningState.SUCCEEDED;\n         }\n      }, 60 * 20 * 1000).apply(deploymentName);\n      assertTrue(jobDone, \"create operation did not complete in the configured timeout\");\n\n      Deployment dp = api().get(deploymentName);\n      ProvisioningState state = ProvisioningState.fromValue(dp.properties().provisioningState());\n      assertTrue(state == ProvisioningState.SUCCEEDED);\n   }\n\n\n   @Test(dependsOnMethods = \"testCreate\")\n   public void testGetDeployment() {\n      Deployment deployment = api().get(deploymentName);\n      assertNotNull(deployment);\n      ProvisioningState state = ProvisioningState.fromValue(deployment.properties().provisioningState());\n      assertTrue(state == ProvisioningState.SUCCEEDED);\n   }\n\n   @Test(dependsOnMethods = \"testCreate\")\n   public void testListDeployments() {\n      List<Deployment> deployments = api().list();\n      assertTrue(deployments.size() > 0);\n      boolean deploymentFound = false;\n      for (Deployment d : deployments) {\n\n         if (d.name().equals(deploymentName)) {\n            deploymentFound = true;\n            break;\n         }\n      }\n      assertTrue(deploymentFound);\n   }\n\n   @Test(dependsOnMethods = {\"testGetDeployment\", \"testListDeployments\"})\n   public void testDelete() throws Exception {\n      List<Deployment> deployments = api().list();\n      for (Deployment d : deployments) {\n         if (d.name().contains(\"jc\")) {\n            URI uri = api().delete(d.name());\n            assertResourceDeleted(uri);\n         }\n      }\n   }\n\n   private DeploymentApi api() {\n      return api.getDeploymentApi(resourceGroupName);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/DeploymentApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport okhttp3.mockwebserver.MockResponse;\n\nimport org.jclouds.azurecompute.arm.domain.Deployment;\nimport org.jclouds.azurecompute.arm.domain.Deployment.ProvisioningState;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiMockTest;\nimport org.testng.annotations.Test;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.Assert.assertEquals;\n\n@Test(groups = \"unit\", testName = \"DeploymentApiMockTest\", singleThreaded = true)\npublic class DeploymentApiMockTest extends BaseAzureComputeApiMockTest {\n\n   private String subscriptionId = \"SUBSCRIPTIONID\";\n   private String resourceGroup = \"resourceGroup\";\n   private String deploymentName = \"jcdep1458344383064\";\n   private String resourceName = \"jcres1458344383064\";\n\n   private String getPutBody(String template, String mode, String parameters) {\n      String body = \"{ \" +\n              \"\\\"properties\\\" : \" +\n              \"  { \" +\n              \"    \\\"template\\\" : \" + template + \", \" +\n              \"    \\\"mode\\\" : \\\"\" + mode + \"\\\", \" +\n              \"    \\\"parameters\\\" : \" + parameters + \" \" +\n              \"  } \" +\n              \"}\";\n      return body;\n   }\n\n   @Test\n   public void testCreateDeployment() throws Exception {\n      final DeploymentApi deploymentApi = api.getDeploymentApi(resourceGroup);\n\n      // check if deployment accepted\n      server.enqueue(jsonResponse(\"/createdeploymentaccepted.json\"));\n      String template = \"{\\\"$schema\\\":\\\"https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#\\\",\\\"contentVersion\\\":\\\"1.0.0.0\\\",\\\"parameters\\\":{\\\"newStorageAccountName\\\":{\\\"type\\\":\\\"string\\\",\\\"metadata\\\":{\\\"description\\\":\\\"Name of the Storage Account\\\"}},\\\"storageAccountType\\\":{\\\"type\\\":\\\"string\\\",\\\"defaultValue\\\":\\\"Standard_LRS\\\",\\\"allowedValues\\\":[\\\"Standard_LRS\\\",\\\"Standard_GRS\\\",\\\"Standard_ZRS\\\"],\\\"metadata\\\":{\\\"description\\\":\\\"Storage Account type\\\"}},\\\"location\\\":{\\\"type\\\":\\\"string\\\",\\\"allowedValues\\\":[\\\"East US\\\",\\\"West US\\\",\\\"West Europe\\\",\\\"East Asia\\\",\\\"Southeast Asia\\\"],\\\"metadata\\\":{\\\"description\\\":\\\"Location of storage account\\\"}}},\\\"resources\\\":[{\\\"type\\\":\\\"Microsoft.Storage/storageAccounts\\\",\\\"name\\\":\\\"[parameters('newStorageAccountName')]\\\",\\\"apiVersion\\\":\\\"2015-05-01-preview\\\",\\\"location\\\":\\\"[parameters('location')]\\\",\\\"properties\\\":{\\\"accountType\\\":\\\"[parameters('storageAccountType')]\\\"}}]}\";\n      String parameters = \"{\\\"newStorageAccountName\\\":{\\\"value\\\":\\\"\" + resourceName + \"\\\"},\\\"storageAccountType\\\":{\\\"value\\\":\\\"Standard_LRS\\\"},\\\"location\\\":{\\\"value\\\":\\\"West US\\\"}}\";\n      String properties = getPutBody(template, \"Incremental\", parameters);\n      Deployment deployment = deploymentApi.create(deploymentName, properties);\n      assertTrue(deployment != null);\n      assertEquals(ProvisioningState.fromValue(deployment.properties().provisioningState()), ProvisioningState.ACCEPTED);\n\n      // check if deployment succeeded\n      server.enqueue(jsonResponse(\"/createdeploymentsucceeded.json\"));\n      deployment = deploymentApi.create(deploymentName, properties);\n      assertTrue(deployment != null);\n      assertEquals(ProvisioningState.fromValue(deployment.properties().provisioningState()), ProvisioningState.SUCCEEDED);\n      assertSent(server, \"PUT\", \"/subscriptions/\" + subscriptionId + \"/resourcegroups/\" + resourceGroup +\n              \"/providers/microsoft.resources/deployments/\" + deploymentName + \"?api-version=2016-02-01\", properties);\n   }\n\n   @Test\n   public void testGetDeployment() throws Exception {\n      final DeploymentApi deploymentApi = api.getDeploymentApi(resourceGroup);\n\n      // check if deployment succeeded\n      server.enqueue(jsonResponse(\"/createdeploymentsucceeded.json\"));\n      Deployment deployment = deploymentApi.get(deploymentName);\n      assertTrue(deployment != null);\n      assertEquals(ProvisioningState.fromValue(deployment.properties().provisioningState()), ProvisioningState.SUCCEEDED);\n      assertSent(server, \"GET\", \"/subscriptions/\" + subscriptionId + \"/resourcegroups/\" + resourceGroup +\n              \"/providers/microsoft.resources/deployments/\" + deploymentName + \"?api-version=2016-02-01\");\n   }\n\n   @Test\n   public void testGetDeploymentEmpty() throws Exception {\n      final DeploymentApi deploymentApi = api.getDeploymentApi(resourceGroup);\n\n      server.enqueue(new MockResponse().setResponseCode(404));\n\n      Deployment deployment = deploymentApi.get(deploymentName);\n      assertNull(deployment);\n\n      assertSent(server, \"GET\", \"/subscriptions/\" + subscriptionId + \"/resourcegroups/\" + resourceGroup +\n              \"/providers/microsoft.resources/deployments/\" + deploymentName + \"?api-version=2016-02-01\");\n   }\n\n   @Test\n   public void testListDeployment() throws Exception {\n      final DeploymentApi deploymentApi = api.getDeploymentApi(resourceGroup);\n\n      // check if deployment succeeded\n      server.enqueue(jsonResponse(\"/listdeployments.json\"));\n      List<Deployment> deployments = deploymentApi.list();\n      assertTrue(deployments.size() > 0);\n\n      assertSent(server, \"GET\", \"/subscriptions/\" + subscriptionId + \"/resourcegroups/\" + resourceGroup +\n              \"/providers/microsoft.resources/deployments?api-version=2016-02-01\");\n\n   }\n\n   @Test\n   public void testListDeploymentEmpty() throws Exception {\n      final DeploymentApi deploymentApi = api.getDeploymentApi(resourceGroup);\n\n      server.enqueue(new MockResponse().setResponseCode(404));\n\n      List<Deployment> deployments = deploymentApi.list();\n      assertTrue(deployments.size() == 0);\n\n      assertSent(server, \"GET\", \"/subscriptions/\" + subscriptionId + \"/resourcegroups/\" + resourceGroup +\n              \"/providers/microsoft.resources/deployments?api-version=2016-02-01\");\n\n   }\n\n   @Test\n   public void testDeleteDeployment() throws InterruptedException {\n      final DeploymentApi deploymentApi = api.getDeploymentApi(resourceGroup);\n\n      server.enqueue(response202WithHeader());\n\n      URI uri = deploymentApi.delete(deploymentName);\n      assertNotNull(uri);\n\n      assertSent(server, \"DELETE\", \"/subscriptions/\" + subscriptionId + \"/resourcegroups/\" + resourceGroup +\n              \"/providers/microsoft.resources/deployments/\" + deploymentName + \"?api-version=2016-02-01\");\n   }\n\n   @Test\n   public void testDeleteDeploymentReturns404() throws InterruptedException {\n      final DeploymentApi deploymentApi = api.getDeploymentApi(resourceGroup);\n\n      server.enqueue(response404());\n\n      URI uri = deploymentApi.delete(deploymentName);\n      assertNull(uri);\n\n      assertSent(server, \"DELETE\", \"/subscriptions/\" + subscriptionId + \"/resourcegroups/\" + resourceGroup +\n              \"/providers/microsoft.resources/deployments/\" + deploymentName + \"?api-version=2016-02-01\");\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/DiskApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport java.net.URI;\nimport java.util.List;\nimport java.util.UUID;\n\nimport org.jclouds.azurecompute.arm.domain.CreationData;\nimport org.jclouds.azurecompute.arm.domain.Disk;\nimport org.jclouds.azurecompute.arm.domain.DiskProperties;\nimport org.jclouds.azurecompute.arm.domain.DiskSku;\nimport org.jclouds.azurecompute.arm.domain.Provisionable;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiLiveTest;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\n\nimport static org.jclouds.azurecompute.arm.domain.StorageAccountType.PREMIUM_LRS;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\n@Test(groups = \"live\", testName = \"DiskApiLiveTest\", singleThreaded = true)\npublic class DiskApiLiveTest extends BaseAzureComputeApiLiveTest {\n\n   public static final String JCLOUDS_DISK_PREFIX = \"jclouds-\";\n   private String diskName;\n\n   @BeforeClass\n   @Override\n   public void setup() {\n      super.setup();\n      createTestResourceGroup();\n      diskName = JCLOUDS_DISK_PREFIX + RAND;\n   }\n\n   @Test\n   public void deleteDiskResourceDoesNotExist() {\n      assertNull(api().delete(JCLOUDS_DISK_PREFIX + UUID.randomUUID()));\n   }\n\n   @Test\n   public void createDisk() {\n      DiskProperties properties = DiskProperties.builder().creationData(CreationData.create(CreationData.CreateOptions.EMPTY)).diskSizeGB(2).build();\n      DiskSku sku = DiskSku.builder().name(PREMIUM_LRS).build();\n      Disk dataDisk = api().createOrUpdate(diskName, LOCATION, ImmutableMap.of(\"exampleTag\", \"jclouds-test-tag\"), properties, sku);\n      assertTrue(waitUntilAvailable(diskName), \"creation operation did not complete in the configured timeout\");\n      assertTrue(dataDisk.properties().diskSizeGB() == 2);\n      assertTrue(dataDisk.tags().containsValue(\"jclouds-test-tag\"));\n   }\n\n   @Test(dependsOnMethods = \"createDisk\")\n   public void getDisk() {\n      Disk dataDisk = api().get(diskName);\n      assertNotNull(dataDisk.name());\n      assertTrue(dataDisk.properties().diskSizeGB() == 2);\n   }\n\n   @Test(dependsOnMethods = \"createDisk\")\n   public void listDisks() {\n      List<Disk> dataDisks = api().list();\n      assertTrue(dataDisks.size() > 0);\n      final Disk dataDisk = api().get(diskName);\n\n      assertTrue(Iterables.any(dataDisks, new Predicate<Disk>() {\n         @Override\n         public boolean apply(Disk input) {\n            return dataDisk.equals(input);\n         }\n      }));\n   }\n\n   @Test(dependsOnMethods = {\"listDisks\", \"getDisk\"}, alwaysRun = true)\n   public void deleteDisk() {\n      URI uri = api().delete(diskName);\n      assertNotNull(uri);\n   }\n\n   private DiskApi api() {\n      return api.getDiskApi(resourceGroupName);\n   }\n\n   private boolean waitUntilAvailable(final String name) {\n      return resourceAvailable.apply(new Supplier<Provisionable>() {\n         @Override public Provisionable get() {\n            Disk disk = api().get(name);\n            return disk == null ? null : disk.properties();\n         }\n      });\n   }\n   \n}\n\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/DiskApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport com.google.common.collect.ImmutableMap;\nimport org.jclouds.azurecompute.arm.domain.CreationData;\nimport org.jclouds.azurecompute.arm.domain.Disk;\nimport org.jclouds.azurecompute.arm.domain.DiskProperties;\nimport org.jclouds.azurecompute.arm.domain.DiskSku;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiMockTest;\nimport org.testng.Assert;\nimport org.testng.annotations.Test;\n\nimport static com.google.common.collect.Iterables.isEmpty;\nimport static org.jclouds.azurecompute.arm.domain.StorageAccountType.PREMIUM_LRS;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\n\n@Test(groups = \"unit\", testName = \"DiskApiMockTest\", singleThreaded = true)\npublic class DiskApiMockTest extends BaseAzureComputeApiMockTest {\n\n   private final String subscriptionid = \"SUBSCRIPTIONID\";\n   private final String resourcegroup = \"myresourcegroup\";\n   private final String diskName = \"myDisk\";\n   private final String apiVersion = \"api-version=2017-03-30\";\n\n   public void createDisk() throws InterruptedException {\n\n      server.enqueue(jsonResponse(\"/creatediskresponse.json\").setResponseCode(200));\n\n      final DiskApi diskApi = api.getDiskApi(resourcegroup);\n\n      DiskProperties properties = DiskProperties.builder().diskSizeGB(2).creationData(CreationData.create(CreationData.CreateOptions.EMPTY)).build();\n\n      Disk dataDisk = diskApi.createOrUpdate(diskName, \"westus\", properties);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Compute/disks/%s?%s\", subscriptionid, resourcegroup, diskName, apiVersion);\n      String json = \"{\\\"location\\\":\\\"westus\\\",\\\"properties\\\":{\\\"diskSizeGB\\\":2,\\\"creationData\\\":{\\\"createOption\\\":\\\"Empty\\\"}}}\";\n      assertSent(server, \"PUT\", path, json);\n\n      assertEquals(dataDisk.properties().provisioningState(), \"Updating\");\n      assertTrue(dataDisk.properties().diskSizeGB() == 2);\n   }\n\n   public void createDiskWithTags() throws InterruptedException {\n\n      server.enqueue(jsonResponse(\"/creatediskwithtagsresponse.json\").setResponseCode(200));\n\n      final DiskApi diskApi = api.getDiskApi(resourcegroup);\n\n      DiskProperties properties = DiskProperties.builder().diskSizeGB(2).creationData(CreationData.create(CreationData.CreateOptions.EMPTY)).build();\n\n      Disk dataDisk = diskApi.createOrUpdate(diskName, \"westus\", ImmutableMap.of(\"exampleTag\", \"jclouds-test-tag\"), properties);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Compute/disks/%s?%s\", subscriptionid, resourcegroup, diskName, apiVersion);\n      String json = \"{\\\"location\\\":\\\"westus\\\",\\\"tags\\\":{\\\"exampleTag\\\":\\\"jclouds-test-tag\\\"},\\\"properties\\\":{\\\"diskSizeGB\\\":2,\\\"creationData\\\":{\\\"createOption\\\":\\\"Empty\\\"}}}\";\n      assertSent(server, \"PUT\", path, json);\n\n      assertEquals(dataDisk.properties().provisioningState(), \"Updating\");\n      assertTrue(dataDisk.properties().diskSizeGB() == 2);\n      assertTrue(dataDisk.tags().containsValue(\"jclouds-test-tag\"));\n   }\n\n   public void createDiskWithTagsAndSku() throws InterruptedException {\n\n      server.enqueue(jsonResponse(\"/creatediskwithtagsandskuresponse.json\").setResponseCode(200));\n\n      final DiskApi diskApi = api.getDiskApi(resourcegroup);\n\n      DiskProperties properties = DiskProperties.builder().diskSizeGB(2).creationData(CreationData.create(CreationData.CreateOptions.EMPTY)).build();\n\n      DiskSku sku = DiskSku.builder().name(PREMIUM_LRS).build();\n\n      Disk dataDisk = diskApi.createOrUpdate(diskName, \"westus\", ImmutableMap.of(\"exampleTag\", \"jclouds-test-tag\"), properties, sku);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Compute/disks/%s?%s\", subscriptionid, resourcegroup, diskName, apiVersion);\n      String json = \"{\\\"location\\\":\\\"westus\\\",\\\"tags\\\":{\\\"exampleTag\\\":\\\"jclouds-test-tag\\\"},\\\"properties\\\":{\\\"diskSizeGB\\\":2,\\\"creationData\\\":{\\\"createOption\\\":\\\"Empty\\\"}},\\\"sku\\\":{\\\"name\\\":\\\"Premium_LRS\\\"}}\";\n      assertSent(server, \"PUT\", path, json);\n\n      assertEquals(dataDisk.properties().provisioningState(), \"Updating\");\n      assertTrue(dataDisk.properties().diskSizeGB() == 2);\n      assertTrue(dataDisk.tags().containsValue(\"jclouds-test-tag\"));\n   }\n\n   public void getDisk() throws InterruptedException {\n\n      server.enqueue(jsonResponse(\"/getdisk.json\").setResponseCode(200));\n\n      final DiskApi diskApi = api.getDiskApi(resourcegroup);\n\n      Disk dataDisk = diskApi.get(diskName);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Compute/disks/%s?%s\", subscriptionid, resourcegroup, diskName, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertEquals(dataDisk.name(), diskName);\n      assertTrue(dataDisk.properties().diskSizeGB() == 2);\n   }\n\n   public void getDiskReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      final DiskApi diskApi = api.getDiskApi(resourcegroup);\n\n      Disk dataDisk = diskApi.get(diskName);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Compute/disks/%s?%s\", subscriptionid, resourcegroup, diskName, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertNull(dataDisk);\n   }\n\n   public void listDisks() throws InterruptedException {\n\n      server.enqueue(jsonResponse(\"/listdisks.json\").setResponseCode(200));\n\n      final DiskApi diskApi = api.getDiskApi(resourcegroup);\n\n      List<Disk> dataDisks = diskApi.list();\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Compute/disks?%s\", subscriptionid, resourcegroup, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertTrue(dataDisks.size() > 0);\n   }\n\n   public void listDisksReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      final DiskApi diskApi = api.getDiskApi(resourcegroup);\n\n      List<Disk> dataDisks = diskApi.list();\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Compute/disks?%s\", subscriptionid, resourcegroup, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertTrue(isEmpty(dataDisks));\n   }\n\n   public void deleteDisk() throws InterruptedException {\n\n      server.enqueue(response202WithHeader());\n\n      final DiskApi diskApi = api.getDiskApi(resourcegroup);\n\n      URI uri = diskApi.delete(diskName);\n      Assert.assertNotNull(uri);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Compute/disks/%s?%s\", subscriptionid, resourcegroup, diskName, apiVersion);\n      assertSent(server, \"DELETE\", path);\n   }\n\n   public void deleteDiskResourceDoesNotExist() throws InterruptedException {\n\n      server.enqueue(response204());\n\n      final DiskApi diskApi = api.getDiskApi(resourcegroup);\n\n      URI uri = diskApi.delete(diskName);\n      assertNull(uri);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Compute/disks/%s?%s\", subscriptionid, resourcegroup, diskName, apiVersion);\n      assertSent(server, \"DELETE\", path);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/GraphRBACApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.azurecompute.arm.domain.ServicePrincipal;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"GraphRBACApiLiveTest\", singleThreaded = true)\npublic class GraphRBACApiLiveTest extends BaseAzureComputeApiLiveTest {\n\n   @Test\n   public void testGetCurrentServicePrincipalSupplier() {\n      ServicePrincipal currentUser = api.getServicePrincipal().get();\n      assertEquals(currentUser.appId(), identity);\n   }\n\n   @Test\n   public void testGetCurrentServicePrincipal() {\n      ServicePrincipal currentUser = api.getGraphRBACApi().getCurrentServicePrincipal();\n      assertEquals(currentUser.appId(), identity);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/GraphRBACApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\n\nimport org.jclouds.azurecompute.arm.domain.ServicePrincipal;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiMockTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"GraphRBACApiMockTest\", singleThreaded = true)\npublic class GraphRBACApiMockTest extends BaseAzureComputeApiMockTest {\n\n   public void testGetCurrentServicePrincipal() throws IOException, InterruptedException {\n      server.enqueue(jsonResponse(\"/serviceprincipals.json\"));\n\n      ServicePrincipal sp = api.getGraphRBACApi().getCurrentServicePrincipal();\n\n      assertEquals(sp.appId(), \"applicationId\");\n      assertSent(server, \"GET\", \"/graphrbac/tenant-id/servicePrincipals?$filter=appId%20eq%20%27mock%27&api-version=1.6\");\n   }\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/ImageApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.any;\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static org.jclouds.azurecompute.arm.config.AzureComputeProperties.TIMEOUT_RESOURCE_DELETED;\nimport static org.jclouds.compute.predicates.NodePredicates.inGroup;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\nimport static org.jclouds.azurecompute.arm.compute.options.AzureTemplateOptions.Builder.resourceGroup;\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.azurecompute.arm.AzureComputeApi;\nimport org.jclouds.azurecompute.arm.domain.IdReference;\nimport org.jclouds.azurecompute.arm.domain.Image;\nimport org.jclouds.azurecompute.arm.domain.ImageProperties;\nimport org.jclouds.azurecompute.arm.internal.AzureLiveTestUtils;\nimport org.jclouds.compute.RunNodesException;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.internal.BaseComputeServiceContextLiveTest;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.inject.Key;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.name.Names;\n\n// We extend the BaseComputeServiceContextLiveTest to create nodes using the abstraction, which is much easier\n@Test(groups = \"live\", singleThreaded = true, testName = \"ImageApiLiveTest\")\npublic class ImageApiLiveTest extends BaseComputeServiceContextLiveTest {\n\n   private static final String imageName = \"imageFromRest\";\n\n   private Predicate<URI> resourceDeleted;\n   private AzureComputeApi api;\n\n   private String location;\n   private ImageApi imageApi;\n   private Image image;\n\n   private String group;\n\n   public ImageApiLiveTest() {\n      provider = \"azurecompute-arm\";\n      group = getClass().getSimpleName().toLowerCase();\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties properties = super.setupProperties();\n      AzureLiveTestUtils.defaultProperties(properties);\n      checkNotNull(setIfTestSystemPropertyPresent(properties, \"oauth.endpoint\"), \"test.oauth.endpoint\");\n      return properties;\n   }\n\n   @Override\n   protected void initializeContext() {\n      super.initializeContext();\n      resourceDeleted = context.utils().injector().getInstance(Key.get(new TypeLiteral<Predicate<URI>>() {\n      }, Names.named(TIMEOUT_RESOURCE_DELETED)));\n      api = view.unwrapApi(AzureComputeApi.class);\n   }\n\n   @Override\n   @BeforeClass\n   public void setupContext() {\n      super.setupContext();\n      // Use the resource name conventions used in the abstraction\n      location = view.getComputeService().templateBuilder().build().getLocation().getId();\n      view.unwrapApi(AzureComputeApi.class).getResourceGroupApi().create(group, location, null);\n      imageApi = api.getVirtualMachineImageApi(group);\n   }\n\n   @Override\n   @AfterClass(alwaysRun = true)\n   protected void tearDownContext() {\n      try {\n         view.getComputeService().destroyNodesMatching(inGroup(group));\n      } finally {\n         try {\n            URI uri = api.getResourceGroupApi().delete(group);\n            assertResourceDeleted(uri);\n         } finally {\n            super.tearDownContext();\n         }\n      }\n   }\n\n   @Test\n   public void testDeleteImageDoesNotExist() {\n      assertNull(imageApi.delete(\"notAnImage\"));\n   }\n\n   @Test\n   public void testCreateImage() throws RunNodesException {\n      NodeMetadata node = getOnlyElement(view.getComputeService().createNodesInGroup(group, 1, resourceGroup(group)));\n      IdReference vmIdRef = IdReference.create(node.getProviderId());\n      view.getComputeService().suspendNode(node.getId());\n\n      api.getVirtualMachineApi(group).generalize(node.getName());\n\n      image = imageApi.createOrUpdate(imageName, location, ImageProperties.builder()\n            .sourceVirtualMachine(vmIdRef).build());\n      assertNotNull(image);\n   }\n\n   @Test(dependsOnMethods = \"testCreateImage\")\n   public void testListImages() {\n      // Check that the image we've just created exists\n      assertTrue(any(imageApi.list(), new Predicate<Image>() {\n         @Override\n         public boolean apply(Image input) {\n            return image.name().equals(input.name());\n         }\n      }));\n   }\n\n   @Test(dependsOnMethods = \"testCreateImage\")\n   public void testGetImage() {\n      assertNotNull(imageApi.get(imageName));\n   }\n\n   @Test(dependsOnMethods = { \"testCreateImage\", \"testListImages\", \"testGetImage\" }, alwaysRun = true)\n   public void deleteImage() {\n      assertResourceDeleted(imageApi.delete(imageName));\n   }\n\n   private void assertResourceDeleted(final URI uri) {\n      if (uri != null) {\n         assertTrue(resourceDeleted.apply(uri),\n               String.format(\"Resource %s was not deleted in the configured timeout\", uri));\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/ImageApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport static com.google.common.collect.Iterables.isEmpty;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport org.jclouds.azurecompute.arm.domain.DataDisk;\nimport org.jclouds.azurecompute.arm.domain.IdReference;\nimport org.jclouds.azurecompute.arm.domain.Image;\nimport org.jclouds.azurecompute.arm.domain.ImageProperties;\nimport org.jclouds.azurecompute.arm.domain.OSDisk;\nimport org.jclouds.azurecompute.arm.domain.StorageProfile;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiMockTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"ImageApiMockTest\", singleThreaded = true)\npublic class ImageApiMockTest extends BaseAzureComputeApiMockTest {\n   private static final String subscriptionid = \"SUBSCRIPTIONID\";\n   private static final String resourcegroup = \"myresourcegroup\";\n   private static final String apiVersion = \"api-version=2016-04-30-preview\";\n   private static final String imageName = \"testVirtualMachineImage\";\n   private static final String location = \"canadaeast\";\n   \n   private static final String PATH = String\n         .format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Compute/images/%s?%s\", subscriptionid,\n               resourcegroup, imageName, apiVersion);\n\n   public void createVirtualMachineImage() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/virtualmachineimagecreate.json\"));\n\n      ImageApi imageApi = api.getVirtualMachineImageApi(resourcegroup);\n      Image result = imageApi.createOrUpdate(imageName, location, newVirtualMachineImage().properties());\n      \n      assertSent(server, \"PUT\", PATH, \"{\\\"location\\\":\\\"\" + location + \"\\\",\"\n            + \"\\\"properties\\\":{\\\"sourceVirtualMachine\\\":{\\\"id\\\":\\\"vmId\\\"},\"\n            + \"\\\"storageProfile\\\":{\\\"osDisk\\\":{\\\"osType\\\":\\\"Linux\\\",\\\"name\\\":\\\"Ubuntu\\\"},\\\"dataDisks\\\":[]},\"\n            + \"\\\"provisioningState\\\":\\\"Succeeded\\\"}}\");\n\n      assertEquals(result.name(), imageName);\n      assertEquals(result.location(), location);\n   }\n\n   public void getVirtualMachineImage() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/virtualmachineimageget.json\"));\n\n      ImageApi imageApi = api.getVirtualMachineImageApi(resourcegroup);\n      Image result = imageApi.get(imageName);\n\n      assertSent(server, \"GET\", PATH);\n\n      assertEquals(result.name(), imageName);\n      assertEquals(result.location(), location);\n      assertNotNull(result.properties().sourceVirtualMachine());\n      assertNotNull(result.properties().storageProfile());\n   }\n\n   public void getVirtualMachineImageReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      final ImageApi imageApi = api.getVirtualMachineImageApi(resourcegroup);\n      Image result = imageApi.get(imageName);\n\n      assertSent(server, \"GET\", PATH);\n      \n      assertNull(result);\n   }\n\n   public void listVirtualMachineImages() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/virtualmachineimagelist.json\"));\n\n      final ImageApi imageApi = api.getVirtualMachineImageApi(resourcegroup);\n      List<Image> result = imageApi.list();\n\n      assertSent(server, \"GET\", String\n            .format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Compute/images?%s\", subscriptionid,\n                  resourcegroup, apiVersion));\n\n      assertNotNull(result);\n      assertTrue(result.size() > 0);\n   }\n\n   public void listVirtualMachineImagesReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      final ImageApi imageApi = api.getVirtualMachineImageApi(resourcegroup);\n      List<Image> result = imageApi.list();\n\n      assertSent(server, \"GET\", String\n            .format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Compute/images?%s\", subscriptionid,\n                  resourcegroup, apiVersion));\n\n      assertTrue(isEmpty(result));\n   }\n\n   public void deleteVirtualMachineImage() throws InterruptedException {\n      server.enqueue(response202WithHeader());\n\n      final ImageApi imageApi = api.getVirtualMachineImageApi(resourcegroup);\n      URI uri = imageApi.delete(imageName);\n\n      assertSent(server, \"DELETE\", PATH);\n\n      assertNotNull(uri);\n      assertTrue(uri.toString().contains(\"api-version\"));\n      assertTrue(uri.toString().contains(\"operationresults\"));\n   }\n\n   public void deleteVirtualMachineImageDoesNotExist() throws InterruptedException {\n      server.enqueue(response404());\n\n      final ImageApi imageApi = api.getVirtualMachineImageApi(resourcegroup);\n      URI uri = imageApi.delete(imageName);\n      assertNull(uri);\n\n      assertSent(server, \"DELETE\", PATH);\n   }\n\n   private Image newVirtualMachineImage() {\n      return Image\n            .builder()\n            .name(imageName)\n            .location(location)\n            .properties(\n                  ImageProperties\n                        .builder()\n                        .sourceVirtualMachine(IdReference.create(\"vmId\"))\n                        .storageProfile(\n                              StorageProfile.create(null, OSDisk.builder().osType(\"Linux\").name(\"Ubuntu\").build(),\n                                    ImmutableList.<DataDisk> of())).provisioningState(\"Succeeded\").build()).build();\n      \n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/JobApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport java.io.IOException;\nimport java.net.URI;\nimport java.util.List;\n\nimport org.jclouds.azurecompute.arm.domain.ResourceDefinition;\nimport org.jclouds.azurecompute.arm.functions.ParseJobStatus.JobStatus;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiMockTest;\nimport org.testng.annotations.Test;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\n@Test(groups = \"unit\", testName = \"JobApiMockTest\", singleThreaded = true)\npublic class JobApiMockTest extends BaseAzureComputeApiMockTest {\n\n   final String requestUrl = \"/operationresults/eyJqb2JJZCI6IlJFU09VUkNFR1JPVVBERUxFVElPTkpPQi1SVEVTVC1DRU5UUkFMVVMiLCJqb2JMb2NhdGlvbiI6ImNlbnRyYWx1cyJ9?api-version=2014-04-01\";\n\n   public void testGetJobStatus() throws IOException, InterruptedException {\n      server.enqueue(response200());\n\n      JobStatus status = api.getJobApi().jobStatus(URI.create(requestUrl));\n\n      assertEquals(status, JobStatus.DONE);\n\n      assertSent(server, \"GET\", requestUrl);\n   }\n\n   public void testGetJobStatusInProgress() throws InterruptedException {\n      server.enqueue(response202WithHeader());\n\n      JobStatus status = api.getJobApi().jobStatus(URI.create(requestUrl));\n\n      assertEquals(status, JobStatus.IN_PROGRESS);\n\n      assertSent(server, \"GET\", requestUrl);\n   }\n\n   public void testGetJobStatusNoContent() throws InterruptedException {\n      server.enqueue(response204());\n\n      JobStatus status = api.getJobApi().jobStatus(URI.create(requestUrl));\n\n      assertEquals(status, JobStatus.NO_CONTENT);\n\n      assertSent(server, \"GET\", requestUrl);\n   }\n\n   public void testGetJobStatusFailed() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/resourcegroup.json\").setStatus(\"HTTP/1.1 208 Error\"));\n\n      JobStatus status = api.getJobApi().jobStatus(URI.create(requestUrl));\n\n      assertEquals(status, JobStatus.FAILED);\n\n      assertSent(server, \"GET\", requestUrl);\n   }\n\n   public void testCaptureJobStatus() throws IOException, InterruptedException {\n      server.enqueue(jsonResponse(\"/resourceDefinition.json\").setResponseCode(200));\n\n      List<ResourceDefinition> resourceDefinitionsList = api.getJobApi().captureStatus(URI.create(requestUrl));\n\n      assertTrue(resourceDefinitionsList.size() > 0);\n\n      assertSent(server, \"GET\", requestUrl);\n   }\n\n   public void testCaptureJobStatusFailed() throws InterruptedException {\n      server.enqueue(response404());\n\n      List<ResourceDefinition> resourceDefinitionsList = api.getJobApi().captureStatus(URI.create(requestUrl));\n\n      assertEquals(resourceDefinitionsList.size(), 0);\n\n      assertSent(server, \"GET\", requestUrl);\n   }\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/LoadBalancerApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.common.collect.Iterables.any;\nimport static com.google.common.collect.Iterables.transform;\nimport static com.google.common.collect.Lists.newArrayList;\nimport static org.jclouds.azurecompute.arm.compute.options.AzureTemplateOptions.Builder.availabilitySet;\nimport static org.jclouds.azurecompute.arm.config.AzureComputeProperties.TIMEOUT_RESOURCE_DELETED;\nimport static org.jclouds.azurecompute.arm.domain.IdReference.extractName;\nimport static org.jclouds.azurecompute.arm.domain.InboundNatRuleProperties.Protocol.Tcp;\nimport static org.jclouds.azurecompute.arm.domain.loadbalancer.LoadBalancer.SKU.SKUName.Basic;\nimport static org.jclouds.azurecompute.arm.domain.loadbalancer.LoadBalancer.SKU.SKUName.Standard;\nimport static org.jclouds.compute.predicates.NodePredicates.inGroup;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport org.jclouds.azurecompute.arm.AzureComputeApi;\nimport org.jclouds.azurecompute.arm.compute.config.AzurePredicatesModule.PublicIpAvailablePredicateFactory;\nimport org.jclouds.azurecompute.arm.compute.domain.ResourceGroupAndName;\nimport org.jclouds.azurecompute.arm.domain.AvailabilitySet;\nimport org.jclouds.azurecompute.arm.domain.AvailabilitySet.AvailabilitySetProperties;\nimport org.jclouds.azurecompute.arm.domain.BackendAddressPool;\nimport org.jclouds.azurecompute.arm.domain.BackendAddressPoolProperties;\nimport org.jclouds.azurecompute.arm.domain.FrontendIPConfigurations;\nimport org.jclouds.azurecompute.arm.domain.FrontendIPConfigurationsProperties;\nimport org.jclouds.azurecompute.arm.domain.IdReference;\nimport org.jclouds.azurecompute.arm.domain.InboundNatRule;\nimport org.jclouds.azurecompute.arm.domain.InboundNatRuleProperties;\nimport org.jclouds.azurecompute.arm.domain.IpConfiguration;\nimport org.jclouds.azurecompute.arm.domain.IpConfigurationProperties;\nimport org.jclouds.azurecompute.arm.domain.NetworkInterfaceCard;\nimport org.jclouds.azurecompute.arm.domain.NetworkInterfaceCardProperties;\nimport org.jclouds.azurecompute.arm.domain.Probe;\nimport org.jclouds.azurecompute.arm.domain.ProbeProperties;\nimport org.jclouds.azurecompute.arm.domain.Provisionable;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachine;\nimport org.jclouds.azurecompute.arm.domain.loadbalancer.LoadBalancer;\nimport org.jclouds.azurecompute.arm.domain.loadbalancer.LoadBalancerProperties;\nimport org.jclouds.azurecompute.arm.domain.loadbalancer.LoadBalancingRule;\nimport org.jclouds.azurecompute.arm.domain.loadbalancer.LoadBalancingRuleProperties;\nimport org.jclouds.azurecompute.arm.domain.loadbalancer.LoadBalancingRuleProperties.Protocol;\nimport org.jclouds.azurecompute.arm.domain.publicipaddress.PublicIPAddress;\nimport org.jclouds.azurecompute.arm.domain.publicipaddress.PublicIPAddressProperties;\nimport org.jclouds.azurecompute.arm.internal.AzureLiveTestUtils;\nimport org.jclouds.compute.RunNodesException;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.internal.BaseComputeServiceContextLiveTest;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.inject.Key;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.name.Names;\n\n// We extend the BaseComputeServiceContextLiveTest to create nodes using the abstraction, which is much easier\n@Test(groups = \"live\", singleThreaded = true)\npublic class LoadBalancerApiLiveTest extends BaseComputeServiceContextLiveTest {\n\n   private static final String lbName = String.format(\"lb-%s-%s\", LoadBalancerApiLiveTest.class.getSimpleName()\n         .toLowerCase(), System.getProperty(\"user.name\"));\n\n   private static final String lbStandardName = lbName + \"Standard\";\n\n   private Predicate<URI> resourceDeleted;\n   private PublicIpAvailablePredicateFactory publicIpAvailable;\n   private Predicate<Supplier<Provisionable>> resourceAvailable;\n   private AzureComputeApi api;\n\n   private String location;\n   private LoadBalancerApi lbApi;\n   private NetworkInterfaceCardApi nicApi;\n\n   private LoadBalancer lb;\n   private String group;\n   private List<String> nicNames;\n\n   public LoadBalancerApiLiveTest() {\n      provider = \"azurecompute-arm\";\n      group = getClass().getSimpleName().toLowerCase();\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties properties = super.setupProperties();\n      AzureLiveTestUtils.defaultProperties(properties);\n      checkNotNull(setIfTestSystemPropertyPresent(properties, \"oauth.endpoint\"), \"test.oauth.endpoint\");\n      return properties;\n   }\n\n   @Override\n   protected void initializeContext() {\n      super.initializeContext();\n      resourceDeleted = context.utils().injector().getInstance(Key.get(new TypeLiteral<Predicate<URI>>() {\n      }, Names.named(TIMEOUT_RESOURCE_DELETED)));\n      publicIpAvailable = context.utils().injector().getInstance(PublicIpAvailablePredicateFactory.class);\n      resourceAvailable = context.utils().injector()\n            .getInstance(Key.get(new TypeLiteral<Predicate<Supplier<Provisionable>>>() {\n            }));\n      api = view.unwrapApi(AzureComputeApi.class);\n   }\n\n   @Override\n   @BeforeClass\n   public void setupContext() {\n      super.setupContext();\n      // Use the resource name conventions used in the abstraction so the nodes\n      // can see the load balancer\n      location = view.getComputeService().templateBuilder().build().getLocation().getId();\n      view.unwrapApi(AzureComputeApi.class).getResourceGroupApi().create(group, location, null);\n      lbApi = api.getLoadBalancerApi(group);\n      nicApi = api.getNetworkInterfaceCardApi(group);\n   }\n\n   @Override\n   @AfterClass(alwaysRun = true)\n   protected void tearDownContext() {\n      try {\n         view.getComputeService().destroyNodesMatching(inGroup(group));\n      } finally {\n         try {\n            URI uri = api.getResourceGroupApi().delete(group);\n            assertResourceDeleted(uri);\n         } finally {\n            super.tearDownContext();\n         }\n      }\n   }\n\n   @Test\n   public void testDeleteLoadBalancerDoesNotExist() {\n      URI uri = lbApi.delete(lbName);\n      assertNull(uri);\n   }\n\n   @Test(dependsOnMethods = \"testDeleteLoadBalancerDoesNotExist\")\n   public void testCreateLoadBalancerStandard() {\n      LoadBalancer createLB = newLoadBalancer(lbStandardName, location);\n\n      PublicIPAddress publicIP = createPublicIPAddress(\"Ip4LoadBalancerStandard\",\n            PublicIPAddress.SKU.create(PublicIPAddress.SKU.SKUName.Standard));\n      FrontendIPConfigurationsProperties frontendProps = FrontendIPConfigurationsProperties.builder()\n            .publicIPAddress(IdReference.create(publicIP.id())).build();\n      FrontendIPConfigurations frontendIps = FrontendIPConfigurations.create(\"ipConfigs\", null, frontendProps, null);\n      LoadBalancerProperties props = LoadBalancerProperties.builder()\n            .frontendIPConfigurations(ImmutableList.of(frontendIps)).build();\n\n      lb = lbApi.createOrUpdate(lbStandardName, createLB.location(), createLB.tags(), LoadBalancer.SKU.create(Standard),\n            props);\n      assertNotNull(lb);\n      assertEquals(lb.name(), lbStandardName);\n      assertEquals(lb.sku().name(), Standard);\n   }\n\n   @Test(dependsOnMethods = \"testDeleteLoadBalancerDoesNotExist\")\n   public void testCreateLoadBalancer() {\n      LoadBalancer createLB = newLoadBalancer(lbName, location);\n\n      PublicIPAddress publicIP = createPublicIPAddress(\"Ip4LoadBalancer\",\n            PublicIPAddress.SKU.create(PublicIPAddress.SKU.SKUName.Basic));\n      FrontendIPConfigurationsProperties frontendProps = FrontendIPConfigurationsProperties.builder()\n            .publicIPAddress(IdReference.create(publicIP.id())).build();\n      FrontendIPConfigurations frontendIps = FrontendIPConfigurations.create(\"ipConfigs\", null, frontendProps, null);\n      LoadBalancerProperties props = LoadBalancerProperties.builder()\n            .frontendIPConfigurations(ImmutableList.of(frontendIps)).build();\n\n      lb = lbApi.createOrUpdate(lbName, createLB.location(), createLB.tags(), null, props);\n      assertNotNull(lb);\n      assertEquals(lb.name(), lbName);\n      assertEquals(lb.sku().name(), Basic);\n   }\n\n   @Test(dependsOnMethods = \"testCreateLoadBalancer\")\n   public void testListLoadBalancers() {\n      List<LoadBalancer> result = lbApi.list();\n\n      // Verify we have something\n      assertNotNull(result);\n      assertTrue(result.size() > 0);\n\n      // Check that the load balancer matches the one we originally passed in\n      assertTrue(any(result, new Predicate<LoadBalancer>() {\n         @Override\n         public boolean apply(LoadBalancer input) {\n            return lb.name().equals(input.name());\n         }\n      }));\n   }\n\n   @Test(dependsOnMethods = \"testCreateLoadBalancer\")\n   public void testListAllLoadBalancers() {\n      List<LoadBalancer> result = lbApi.listAll();\n\n      // Verify we have something\n      assertNotNull(result);\n      assertTrue(result.size() > 0);\n\n      // Check that the load balancer matches the one we originally passed in\n      assertTrue(any(result, new Predicate<LoadBalancer>() {\n         @Override\n         public boolean apply(LoadBalancer input) {\n            return lb.name().equals(input.name());\n         }\n      }));\n   }\n\n   @Test(dependsOnMethods = \"testCreateLoadBalancer\")\n   public void testGetLoadBalancer() {\n      lb = lbApi.get(lbName);\n      assertNotNull(lb);\n   }\n\n   @Test(dependsOnMethods = \"testGetLoadBalancer\")\n   public void testAddProbe() {\n      ProbeProperties probeProps = ProbeProperties.builder().protocol(ProbeProperties.Protocol.Http).port(80)\n            .requestPath(\"/\").intervalInSeconds(5).numberOfProbes(2).build();\n\n      Probe probe = Probe.create(\"probetest\", null, probeProps, null);\n      LoadBalancerProperties props = lb.properties().toBuilder().probes(ImmutableList.of(probe)).build();\n\n      lb = updateLoadBalancer(lbName, props);\n\n      assertEquals(lb.properties().probes().size(), 1);\n      assertEquals(lb.properties().probes().get(0).name(), probe.name());\n   }\n\n   @Test(dependsOnMethods = \"testGetLoadBalancer\")\n   public void testAddBackendPool() throws Exception {\n      List<IdReference> rules = newArrayList(transform(lb.properties().loadBalancingRules(), ToIdReference));\n      BackendAddressPool pool = BackendAddressPool.create(\"backpools\", null, BackendAddressPoolProperties.builder()\n            .loadBalancingRules(rules).build(), null);\n\n      LoadBalancerProperties props = lb.properties().toBuilder().backendAddressPools(ImmutableList.of(pool)).build();\n\n      lb = updateLoadBalancer(lbName, props);\n\n      assertEquals(lb.properties().backendAddressPools().size(), 1);\n      assertEquals(lb.properties().backendAddressPools().get(0).name(), pool.name());\n   }\n\n   @Test(dependsOnMethods = { \"testAddProbe\", \"testAddBackendPool\" })\n   public void testAddLoadBalancingRule() {\n      IdReference frontendIp = IdReference.create(lb.properties().frontendIPConfigurations().get(0).id());\n      IdReference probe = IdReference.create(lb.properties().probes().get(0).id());\n      IdReference backendPool = IdReference.create(lb.properties().backendAddressPools().get(0).id());\n\n      LoadBalancingRuleProperties ruleProperties = LoadBalancingRuleProperties.builder()\n            .frontendIPConfiguration(frontendIp).backendAddressPool(backendPool).frontendPort(80).backendPort(80)\n            .protocol(Protocol.Tcp).probe(probe).build();\n\n      LoadBalancingRule rule = LoadBalancingRule.create(\"lbRule1\", null, ruleProperties, null);\n      LoadBalancerProperties props = lb.properties().toBuilder().loadBalancingRules(ImmutableList.of(rule)).build();\n\n      lb = updateLoadBalancer(lbName, props);\n\n      assertEquals(lb.properties().loadBalancingRules().size(), 1);\n      assertEquals(lb.properties().loadBalancingRules().get(0).name(), rule.name());\n   }\n\n   @Test(dependsOnMethods = { \"testAddBackendPool\", \"testAddProbe\", \"testAddLoadBalancingRule\" })\n   public void testAttachNodesToBackendPool() throws Exception {\n      nicNames = createVirtualMachinesInGroupAndGetNicRefs(group, 2);\n\n      // Add the first IP of each node to the pool\n      List<NetworkInterfaceCard> attachedNics = new ArrayList<NetworkInterfaceCard>();\n      BackendAddressPool targetPool = lb.properties().backendAddressPools().get(0);\n      for (String nicName : nicNames) {\n         attachedNics.add(attachNicToBackendPool(nicName, targetPool));\n      }\n\n      // Refresh the LB after having attached NICs to the pool\n      lb = lbApi.get(lbName);\n      List<BackendAddressPool> pools = lb.properties().backendAddressPools();\n      assertEquals(pools.size(), 1);\n\n      List<IdReference> backendIps = pools.get(0).properties().backendIPConfigurations();\n      assertEquals(backendIps.size(), attachedNics.size());\n      assertTrue(backendIps.containsAll(newArrayList(transform(attachedNics, ToFirstIpReference))));\n   }\n\n   @Test(dependsOnMethods = \"testAttachNodesToBackendPool\")\n   public void testAddInboundNatRule() {\n      IdReference frontendIp = IdReference.create(lb.properties().frontendIPConfigurations().get(0).id());\n\n      InboundNatRuleProperties natProps = InboundNatRuleProperties.builder().frontendIPConfiguration(frontendIp)\n            .frontendPort(5679).backendPort(56710).protocol(Tcp).build();\n\n      InboundNatRule natRule = InboundNatRule.create(\"inboundnat\", null, natProps, null);\n      LoadBalancerProperties props = lb.properties().toBuilder().inboundNatRules(ImmutableList.of(natRule)).build();\n\n      lb = updateLoadBalancer(lbName, props);\n\n      assertEquals(lb.properties().inboundNatRules().size(), 1);\n      assertEquals(lb.properties().inboundNatRules().get(0).name(), natRule.name());\n\n      InboundNatRule createdRule = lb.properties().inboundNatRules().get(0);\n      NetworkInterfaceCard updatedNic = attachNicToNatRule(nicNames.get(0), createdRule);\n      List<IdReference> natRulesInNic = updatedNic.properties().ipConfigurations().get(0).properties()\n            .loadBalancerInboundNatRules();\n\n      assertEquals(natRulesInNic.size(), 1);\n      assertEquals(natRulesInNic.get(0), IdReference.create(createdRule.id()));\n\n      // Refresh the LB after having attached NICs to the pool\n      lb = lbApi.get(lbName);\n\n      IdReference backendIpRef = IdReference.create(updatedNic.properties().ipConfigurations().get(0).id());\n      assertEquals(lb.properties().inboundNatRules().size(), 1);\n      assertEquals(lb.properties().inboundNatRules().get(0).properties().backendIPConfiguration(), backendIpRef);\n\n   }\n\n   @Test(dependsOnMethods = { \"testCreateLoadBalancer\", \"testListLoadBalancers\", \"testListAllLoadBalancers\", \"testGetLoadBalancer\", \"testAddProbe\",\n         \"testAddLoadBalancingRule\", \"testAddBackendPool\", \"testAttachNodesToBackendPool\", \"testAddInboundNatRule\" }, alwaysRun = true)\n   public void deleteLoadBalancer() {\n      URI uri = lbApi.delete(lbName);\n      assertResourceDeleted(uri);\n   }\n\n   private PublicIPAddress createPublicIPAddress(final String publicIpAddressName, final PublicIPAddress.SKU sku) {\n      final PublicIPAddressApi ipApi = view.unwrapApi(AzureComputeApi.class).getPublicIPAddressApi(group);\n      PublicIPAddress publicIPAddress = ipApi.get(publicIpAddressName);\n\n      if (publicIPAddress == null) {\n         final Map<String, String> tags = ImmutableMap.of(\"testkey\", \"testvalue\");\n         PublicIPAddressProperties properties = PublicIPAddressProperties.builder().publicIPAllocationMethod(\"Static\")\n               .idleTimeoutInMinutes(4).build();\n         publicIPAddress = ipApi.createOrUpdate(publicIpAddressName, location, tags, sku, properties);\n\n         checkState(publicIpAvailable.create(group).apply(publicIpAddressName),\n               \"Public IP was not provisioned in the configured timeout\");\n      }\n\n      return publicIPAddress;\n   }\n\n   private LoadBalancer newLoadBalancer(final String lbName, final String locationName) {\n      FrontendIPConfigurationsProperties frontendIPConfigurationsProperties = FrontendIPConfigurationsProperties\n            .builder().build();\n      FrontendIPConfigurations frontendIPConfigurations = FrontendIPConfigurations.create(\"ipConfigs\", null,\n            frontendIPConfigurationsProperties, null);\n      return LoadBalancer\n            .builder()\n            .name(lbName)\n            .location(locationName)\n            .properties(\n                  LoadBalancerProperties.builder().frontendIPConfigurations(ImmutableList.of(frontendIPConfigurations))\n                        .build()).build();\n   }\n\n   private void assertResourceDeleted(final URI uri) {\n      if (uri != null) {\n         assertTrue(resourceDeleted.apply(uri),\n               String.format(\"Resource %s was not terminated in the configured timeout\", uri));\n      }\n   }\n\n   private List<String> createVirtualMachinesInGroupAndGetNicRefs(final String group, final int count)\n         throws RunNodesException {\n\n      // To add multiple nodes in a LB they must belong to the same availability\n      // set\n      AvailabilitySetProperties props = AvailabilitySetProperties.builder().platformUpdateDomainCount(count)\n            .platformFaultDomainCount(count).build();\n      AvailabilitySet as = AvailabilitySet.managed().name(group).properties(props).build();\n\n      Set<? extends NodeMetadata> nodes = view.getComputeService().createNodesInGroup(group, count,\n            availabilitySet(as).resourceGroup(this.group));\n\n      List<String> nicNames = new ArrayList<String>();\n      for (NodeMetadata node : nodes) {\n         ResourceGroupAndName resourceGroupAndName = ResourceGroupAndName.fromSlashEncoded(node.getId());\n         VirtualMachine vm = api.getVirtualMachineApi(resourceGroupAndName.resourceGroup()).get(\n               resourceGroupAndName.name());\n\n         String nicName = extractName(vm.properties().networkProfile().networkInterfaces().get(0).id());\n         nicNames.add(nicName);\n      }\n\n      return nicNames;\n   }\n\n   private NetworkInterfaceCard attachNicToBackendPool(final String nicName, BackendAddressPool pool) {\n      List<IdReference> poolRefs = ImmutableList.of(IdReference.create(pool.id()));\n\n      // Assume we are attaching the first IP to the Load Balancer\n      NetworkInterfaceCard nic = nicApi.get(nicName);\n\n      IpConfigurationProperties ipProps = nic.properties().ipConfigurations().get(0).properties().toBuilder()\n            .loadBalancerBackendAddressPools(poolRefs).build();\n      List<IpConfiguration> ips = ImmutableList.of(nic.properties().ipConfigurations().get(0).toBuilder()\n            .properties(ipProps).build());\n\n      NetworkInterfaceCardProperties nicProps = nic.properties().toBuilder().ipConfigurations(ips).build();\n\n      nicApi.createOrUpdate(nicName, location, nicProps, null);\n\n      resourceAvailable.apply(new Supplier<Provisionable>() {\n         @Override\n         public Provisionable get() {\n            NetworkInterfaceCard updated = nicApi.get(nicName);\n            return updated == null ? null : updated.properties();\n         }\n      });\n\n      return nicApi.get(nicName);\n   }\n\n   private NetworkInterfaceCard attachNicToNatRule(final String nicName, InboundNatRule rule) {\n      List<IdReference> natRuleRefs = ImmutableList.of(IdReference.create(rule.id()));\n\n      // Assume we are attaching the first IP to the NAT rule\n      NetworkInterfaceCard nic = nicApi.get(nicName);\n\n      IpConfigurationProperties ipProps = nic.properties().ipConfigurations().get(0).properties().toBuilder()\n            .loadBalancerInboundNatRules(natRuleRefs).build();\n      List<IpConfiguration> ips = ImmutableList.of(nic.properties().ipConfigurations().get(0).toBuilder()\n            .properties(ipProps).build());\n\n      NetworkInterfaceCardProperties nicProps = nic.properties().toBuilder().ipConfigurations(ips).build();\n\n      nicApi.createOrUpdate(nicName, location, nicProps, null);\n\n      resourceAvailable.apply(new Supplier<Provisionable>() {\n         @Override\n         public Provisionable get() {\n            NetworkInterfaceCard updated = nicApi.get(nicName);\n            return updated == null ? null : updated.properties();\n         }\n      });\n\n      return nicApi.get(nicName);\n   }\n\n   private LoadBalancer updateLoadBalancer(final String name, LoadBalancerProperties props) {\n      lbApi.createOrUpdate(name, location, null, null, props);\n      resourceAvailable.apply(new Supplier<Provisionable>() {\n         @Override\n         public Provisionable get() {\n            LoadBalancer updated = lbApi.get(name);\n            return updated == null ? null : updated.properties();\n         }\n      });\n      return lbApi.get(name);\n   }\n\n   private static final Function<LoadBalancingRule, IdReference> ToIdReference = new Function<LoadBalancingRule, IdReference>() {\n      @Override\n      public IdReference apply(LoadBalancingRule input) {\n         return IdReference.create(input.id());\n      }\n   };\n\n   private static final Function<NetworkInterfaceCard, IdReference> ToFirstIpReference = new Function<NetworkInterfaceCard, IdReference>() {\n      @Override\n      public IdReference apply(NetworkInterfaceCard input) {\n         return IdReference.create(input.properties().ipConfigurations().get(0).id());\n      }\n   };\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/LoadBalancerApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport static com.google.common.collect.Iterables.isEmpty;\nimport static org.jclouds.azurecompute.arm.config.AzureComputeProperties.API_VERSION_PREFIX;\nimport static org.jclouds.azurecompute.arm.domain.loadbalancer.LoadBalancer.SKU.SKUName.Basic;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport org.jclouds.azurecompute.arm.AzureComputeProviderMetadata;\nimport org.jclouds.azurecompute.arm.domain.FrontendIPConfigurations;\nimport org.jclouds.azurecompute.arm.domain.FrontendIPConfigurationsProperties;\nimport org.jclouds.azurecompute.arm.domain.loadbalancer.LoadBalancer;\nimport org.jclouds.azurecompute.arm.domain.loadbalancer.LoadBalancerProperties;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiMockTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"LoadBalancerApiMockTest\", singleThreaded = true)\npublic class LoadBalancerApiMockTest extends BaseAzureComputeApiMockTest {\n   private final String subscriptionid = \"SUBSCRIPTIONID\";\n   private final String resourcegroup = \"myresourcegroup\";\n   private final String apiVersion = \"api-version=\" + AzureComputeProviderMetadata.defaultProperties()\n         .getProperty(API_VERSION_PREFIX + LoadBalancerApi.class.getSimpleName());\n   private final String lbName = \"testLoadBalancer\";\n\n   public void createLoadBalancer() throws InterruptedException {\n      LoadBalancer nsg = newLoadBalancer();\n\n      server.enqueue(jsonResponse(\"/loadbalancercreate.json\").setResponseCode(200));\n      final LoadBalancerApi loadBalancerApi = api.getLoadBalancerApi(resourcegroup);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/loadBalancers/%s?%s\",\n            subscriptionid, resourcegroup, lbName, apiVersion);\n      \n      String json = \"{\\\"location\\\":\\\"westeurope\\\",\\\"properties\\\":{\\\"frontendIPConfigurations\\\":[{\\\"name\\\":\\\"ipConfigs\"\n            + \"\\\",\\\"properties\\\":{}}]} }\";\n      \n      LoadBalancer result = loadBalancerApi.createOrUpdate(lbName, \"westeurope\", null, null, nsg.properties());\n      assertSent(server, \"PUT\", path, json);\n\n      assertEquals(result.name(), lbName);\n      assertEquals(result.location(), \"westeurope\");\n      assertEquals(result.sku().name(), Basic);\n   }\n\n   public void getLoadBalancer() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/loadbalancerget.json\").setResponseCode(200));\n\n      final LoadBalancerApi nsgApi = api.getLoadBalancerApi(resourcegroup);\n      LoadBalancer result = nsgApi.get(lbName);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/loadBalancers/%s?%s\",\n            subscriptionid, resourcegroup, lbName, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertEquals(result.name(), lbName);\n      assertEquals(result.location(), \"westeurope\");\n      assertEquals(result.properties().loadBalancingRules().size(), 1);\n      assertEquals(result.properties().loadBalancingRules().get(0).name(), \"lbRule1\");\n      assertEquals(result.sku().name(), Basic);\n   }\n\n   public void getLoadBalancerReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      final LoadBalancerApi nsgApi = api.getLoadBalancerApi(resourcegroup);\n      LoadBalancer result = nsgApi.get(lbName);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/loadBalancers/%s?%s\",\n            subscriptionid, resourcegroup, lbName, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertNull(result);\n   }\n\n   public void listLoadBalancers() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/loadbalancerlist.json\").setResponseCode(200));\n\n      final LoadBalancerApi nsgApi = api.getLoadBalancerApi(resourcegroup);\n      List<LoadBalancer> result = nsgApi.list();\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/loadBalancers?%s\",\n            subscriptionid, resourcegroup, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertNotNull(result);\n      assertTrue(result.size() > 0);\n   }\n\n   public void listAllLoadBalancers() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/loadbalancerlistall.json\").setResponseCode(200));\n\n      final LoadBalancerApi nsgApi = api.getLoadBalancerApi(resourcegroup);\n      List<LoadBalancer> result = nsgApi.listAll();\n\n      String path = String.format(\"/subscriptions/%s/providers/Microsoft.Network/loadBalancers?%s\", subscriptionid, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertNotNull(result);\n      assertTrue(result.size() > 0);\n   }\n\n   public void listLoadBalancersReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      final LoadBalancerApi nsgApi = api.getLoadBalancerApi(resourcegroup);\n      List<LoadBalancer> result = nsgApi.list();\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/loadBalancers?%s\",\n            subscriptionid, resourcegroup, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertTrue(isEmpty(result));\n   }\n\n   public void deleteLoadBalancer() throws InterruptedException {\n      server.enqueue(response202WithHeader());\n\n      final LoadBalancerApi nsgApi = api.getLoadBalancerApi(resourcegroup);\n      URI uri = nsgApi.delete(lbName);\n\n      assertEquals(server.getRequestCount(), 1);\n      assertNotNull(uri);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/loadBalancers/%s?%s\",\n            subscriptionid, resourcegroup, lbName, apiVersion);\n      assertSent(server, \"DELETE\", path);\n\n      assertTrue(uri.toString().contains(\"api-version\"));\n      assertTrue(uri.toString().contains(\"operationresults\"));\n   }\n\n   public void deleteLoadBalancerDoesNotExist() throws InterruptedException {\n      server.enqueue(response404());\n\n      final LoadBalancerApi nsgApi = api.getLoadBalancerApi(resourcegroup);\n      URI uri = nsgApi.delete(lbName);\n      assertNull(uri);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/loadBalancers/%s?%s\",\n            subscriptionid, resourcegroup, lbName, apiVersion);\n      assertSent(server, \"DELETE\", path);\n   }\n   \n   private LoadBalancer newLoadBalancer() {\n      FrontendIPConfigurationsProperties frontendIPConfigurationsProperties = FrontendIPConfigurationsProperties\n            .builder().build();\n      FrontendIPConfigurations frontendIPConfigurations = FrontendIPConfigurations.create(\"ipConfigs\", null,\n            frontendIPConfigurationsProperties, null);\n      return LoadBalancer\n            .builder()\n            .name(lbName)\n            .location(\"westus\")\n            .properties(\n                  LoadBalancerProperties.builder().frontendIPConfigurations(ImmutableList.of(frontendIPConfigurations))\n                        .build()).build();\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/LocalNetworkGatewayApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport static com.google.common.collect.Iterables.any;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\n\nimport org.jclouds.azurecompute.arm.domain.AddressSpace;\nimport org.jclouds.azurecompute.arm.domain.Provisionable;\nimport org.jclouds.azurecompute.arm.domain.vpn.LocalNetworkGateway;\nimport org.jclouds.azurecompute.arm.domain.vpn.LocalNetworkGatewayProperties;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiLiveTest;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\n\n@Test(groups = \"live\", testName = \"LocalNetworkGatewayApiLiveTest\", singleThreaded = true)\npublic class LocalNetworkGatewayApiLiveTest extends BaseAzureComputeApiLiveTest {\n\n   private String name;\n\n   @BeforeClass\n   @Override\n   public void setup() {\n      super.setup();\n      createTestResourceGroup();\n      name = \"jclouds-\" + RAND;\n   }\n\n   @Test\n   public void createLocalNetworkGateway() {\n      AddressSpace localAddresses = AddressSpace.create(ImmutableList.of(\"192.168.0.0/24\"));\n      LocalNetworkGatewayProperties props = LocalNetworkGatewayProperties.builder(\"1.2.3.4\")\n            .localNetworkAddressSpace(localAddresses).build();\n\n      LocalNetworkGateway gw = api().createOrUpdate(name, LOCATION, null, props);\n\n      assertNotNull(gw);\n      assertEquals(gw.name(), name);\n      assertNotNull(gw.properties());\n      assertNotNull(gw.properties().gatewayIpAddress());\n      assertEquals(gw.properties().gatewayIpAddress(), \"1.2.3.4\");\n      assertNotNull(gw.properties().localNetworkAddressSpace());\n      assertTrue(gw.properties().localNetworkAddressSpace().addressPrefixes().contains(\"192.168.0.0/24\"));\n   }\n\n   @Test(dependsOnMethods = \"createLocalNetworkGateway\")\n   public void getLocalNetworkGateway() {\n      assertNotNull(api().get(name));\n   }\n\n   @Test(dependsOnMethods = \"createLocalNetworkGateway\")\n   public void listLocalNetworkGateways() {\n      assertTrue(any(api().list(), new Predicate<LocalNetworkGateway>() {\n         @Override\n         public boolean apply(LocalNetworkGateway input) {\n            return name.equals(input.name());\n         }\n      }));\n   }\n\n   @Test(dependsOnMethods = \"createLocalNetworkGateway\")\n   public void updateLocalNetworkGateway() {\n      // Make sure the resource is fully provisioned before modifying it\n      waitUntilAvailable(name);\n      \n      LocalNetworkGateway gw = api().get(name);\n      AddressSpace localAddresses = AddressSpace.create(ImmutableList.of(\"192.168.0.0/24\", \"192.168.1.0/24\"));\n      gw = api().createOrUpdate(name, LOCATION, ImmutableMap.of(\"foo\", \"bar\"),\n            gw.properties().toBuilder().localNetworkAddressSpace(localAddresses).build());\n\n      assertNotNull(gw);\n      assertTrue(gw.tags().containsKey(\"foo\"));\n      assertEquals(gw.tags().get(\"foo\"), \"bar\");\n      assertTrue(gw.properties().localNetworkAddressSpace().addressPrefixes().contains(\"192.168.0.0/24\"));\n      assertTrue(gw.properties().localNetworkAddressSpace().addressPrefixes().contains(\"192.168.1.0/24\"));\n   }\n\n   @Test(dependsOnMethods = { \"getLocalNetworkGateway\", \"listLocalNetworkGateways\", \"updateLocalNetworkGateway\" })\n   public void deleteLocalNetworkGateway() {\n      // Make sure the resource is fully provisioned before deleting it\n      waitUntilAvailable(name);\n      URI uri = api().delete(name);\n      assertResourceDeleted(uri);\n   }\n\n   private LocalNetworkGatewayApi api() {\n      return api.getLocalNetworkGatewayApi(resourceGroupName);\n   }\n\n   private void waitUntilAvailable(final String name) {\n      assertTrue(resourceAvailable.apply(new Supplier<Provisionable>() {\n         @Override\n         public Provisionable get() {\n            LocalNetworkGateway gw = api().get(name);\n            return gw == null ? null : gw.properties();\n         }\n      }));\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/LocalNetworkGatewayApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport static com.google.common.collect.Iterables.isEmpty;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport org.jclouds.azurecompute.arm.domain.AddressSpace;\nimport org.jclouds.azurecompute.arm.domain.vpn.LocalNetworkGateway;\nimport org.jclouds.azurecompute.arm.domain.vpn.LocalNetworkGatewayProperties;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiMockTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"LocalNetworkGatewayApiMockTest\", singleThreaded = true)\npublic class LocalNetworkGatewayApiMockTest extends BaseAzureComputeApiMockTest {\n\n   private final String subscriptionid = \"SUBSCRIPTIONID\";\n   private final String resourcegroup = \"myresourcegroup\";\n   private final String name = \"mylocalgw\";\n   private final String apiVersion = \"api-version=2018-02-01\";\n\n   public void createOrUpdateLocalNetworkGateway() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/localnetworkgatewaycreate.json\").setResponseCode(200));\n      LocalNetworkGatewayApi gwapi = api.getLocalNetworkGatewayApi(resourcegroup);\n\n      AddressSpace localAddresses = AddressSpace.create(ImmutableList.of(\"192.168.0.0/24\"));\n      LocalNetworkGatewayProperties props = LocalNetworkGatewayProperties.builder(\"1.2.3.4\")\n            .localNetworkAddressSpace(localAddresses).build();\n      LocalNetworkGateway gw = gwapi.createOrUpdate(name, \"westeurope\", null, props);\n\n      String path = String.format(\n            \"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/localNetworkGateways/%s?%s\",\n            subscriptionid, resourcegroup, name, apiVersion);\n      String json = \"{\\\"location\\\":\\\"westeurope\\\",\\\"properties\\\":{\\\"gatewayIpAddress\\\":\\\"1.2.3.4\\\",\\\"localNetworkAddressSpace\\\":{\\\"addressPrefixes\\\":[\\\"192.168.0.0/24\\\"]}}}\";\n      assertSent(server, \"PUT\", path, json);\n\n      assertEquals(gw.name(), name);\n      assertNotNull(gw.properties());\n      assertNotNull(gw.properties().gatewayIpAddress());\n      assertEquals(gw.properties().gatewayIpAddress(), \"1.2.3.4\");\n      assertNotNull(gw.properties().localNetworkAddressSpace());\n      assertTrue(gw.properties().localNetworkAddressSpace().addressPrefixes().contains(\"192.168.0.0/24\"));\n   }\n\n   public void getLocalNetworkGateway() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/localnetworkgatewayget.json\").setResponseCode(200));\n      LocalNetworkGatewayApi gwapi = api.getLocalNetworkGatewayApi(resourcegroup);\n\n      LocalNetworkGateway gw = gwapi.get(name);\n\n      String path = String.format(\n            \"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/localNetworkGateways/%s?%s\",\n            subscriptionid, resourcegroup, name, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertEquals(gw.name(), name);\n   }\n\n   public void getLocalNetworkGatewayReturns404() throws InterruptedException {\n      server.enqueue(response404());\n      LocalNetworkGatewayApi gwapi = api.getLocalNetworkGatewayApi(resourcegroup);\n\n      LocalNetworkGateway gw = gwapi.get(name);\n\n      String path = String.format(\n            \"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/localNetworkGateways/%s?%s\",\n            subscriptionid, resourcegroup, name, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertNull(gw);\n   }\n\n   public void listLocalNetworkGateways() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/localnetworkgatewaylist.json\").setResponseCode(200));\n      LocalNetworkGatewayApi gwapi = api.getLocalNetworkGatewayApi(resourcegroup);\n\n      List<LocalNetworkGateway> gws = gwapi.list();\n\n      String path = String.format(\n            \"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/localNetworkGateways?%s\",\n            subscriptionid, resourcegroup,  apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertTrue(gws.size() > 0);\n   }\n\n   public void listLocalNetworkGatewaysReturns404() throws InterruptedException {\n      server.enqueue(response404());\n      LocalNetworkGatewayApi gwapi = api.getLocalNetworkGatewayApi(resourcegroup);\n\n      List<LocalNetworkGateway> gws = gwapi.list();\n\n      String path = String.format(\n            \"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/localNetworkGateways?%s\",\n            subscriptionid, resourcegroup,  apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertTrue(isEmpty(gws));\n   }\n\n   public void deleteLocalNetworkGateway() throws InterruptedException {\n      server.enqueue(response202WithHeader());\n      LocalNetworkGatewayApi gwapi = api.getLocalNetworkGatewayApi(resourcegroup);\n\n      URI uri = gwapi.delete(name);\n      assertNotNull(uri);\n\n      String path = String.format(\n            \"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/localNetworkGateways/%s?%s\",\n            subscriptionid, resourcegroup, name, apiVersion);\n      assertSent(server, \"DELETE\", path);\n   }\n\n   public void deleteLocalNetworkGatewayDoesNotExist() throws InterruptedException {\n      server.enqueue(response204());\n      LocalNetworkGatewayApi gwapi = api.getLocalNetworkGatewayApi(resourcegroup);\n\n      URI uri = gwapi.delete(name);\n      assertNull(uri);\n\n      String path = String.format(\n            \"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/localNetworkGateways/%s?%s\",\n            subscriptionid, resourcegroup, name, apiVersion);\n      assertSent(server, \"DELETE\", path);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/LocationApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport java.util.List;\n\nimport org.jclouds.azurecompute.arm.domain.Location;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiLiveTest;\nimport org.testng.annotations.Test;\n\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\n@Test(groups = \"live\", testName = \"LocationApiLiveTest\")\npublic class LocationApiLiveTest extends BaseAzureComputeApiLiveTest {\n\n   @Test\n   public void testList() {\n      List<Location> locations = api().list();\n      assertTrue(!locations.isEmpty());\n      for (Location location : locations) {\n         checkLocation(location);\n      }\n   }\n\n   private LocationApi api() {\n      return api.getLocationApi();\n   }\n\n   private void checkLocation(final Location location) {\n      assertNotNull(location.name(), \"Name cannot be null for a Location.\");\n      assertNotNull(location.displayName(), \"DisplayName cannot be null for: \" + location.name());\n      assertNotNull(location.id(), \"Id cannot be null for: \" + location.name());\n      assertNotNull(location.latitude(), \"Latitude cannot be null for: \" + location.name());\n      assertNotNull(location.longitude(), \"Longitude cannot be null for: \" + location.name());\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/LocationApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport com.google.common.collect.ImmutableList;\n\nimport okhttp3.mockwebserver.MockResponse;\n\nimport org.jclouds.azurecompute.arm.domain.Location;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiMockTest;\nimport org.testng.annotations.Test;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\n@Test(groups = \"unit\", testName = \"LocationApiMockTest\", singleThreaded = true)\npublic class LocationApiMockTest extends BaseAzureComputeApiMockTest {\n\n   public void testList() throws Exception {\n      server.enqueue(jsonResponse(\"/locations.json\"));\n      final LocationApi locationAPI = api.getLocationApi();\n      assertEquals(locationAPI.list(), ImmutableList.of(\n              Location.create(\"/subscriptions/SUBSCRIPTIONID/locations/eastasia\",\n                      \"eastasia\", \"East Asia\", \"114.188\", \"22.267\")\n      ));\n      assertSent(server, \"GET\", \"/subscriptions/SUBSCRIPTIONID/locations?api-version=2015-11-01\");\n   }\n\n   public void testEmptyList() throws Exception {\n      server.enqueue(new MockResponse().setResponseCode(404));\n\n      final LocationApi locationAPI = api.getLocationApi();\n\n      assertTrue(locationAPI.list().isEmpty());\n\n      assertSent(server, \"GET\", \"/subscriptions/SUBSCRIPTIONID/locations?api-version=2015-11-01\");\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/MetricAlertApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\nimport org.checkerframework.checker.nullness.qual.Nullable;\nimport org.jclouds.azurecompute.arm.domain.Criteria;\nimport org.jclouds.azurecompute.arm.domain.MetricAlert;\nimport org.jclouds.azurecompute.arm.domain.MetricAlertCriteria;\nimport org.jclouds.azurecompute.arm.domain.MetricAlertCriteria.Operator;\nimport org.jclouds.azurecompute.arm.domain.MetricAlertProperties;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiLiveTest;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\n\n@Test(groups = \"live\", testName = \"MetricAlertApiLiveTest\", singleThreaded = true)\npublic class MetricAlertApiLiveTest extends BaseAzureComputeApiLiveTest {\n\n\tprivate String alertRuleName;\n\tprivate String subscriptionid;\n\tprivate final String GLOBAL = \"Global\";\n\n\t@BeforeClass\n\t@Override\n\tpublic void setup() {\n\t\tsuper.setup();\n\t\tsubscriptionid = getSubscriptionId();\n\t\tcreateTestResourceGroup();\n\t\talertRuleName = String.format(\"vn-%s-%s\", this.getClass().getSimpleName().toLowerCase(),\n\t\t\t\tSystem.getProperty(\"user.name\"));\n\t}\n\n\tprivate MetricAlertApi api() {\n\t\treturn api.getMetricAlertApi(resourceGroupName);\n\t}\n\n\t@Test\n\tpublic void testCreate() {\n\t\tMetricAlert metricAlert = api().createOrUpdate(alertRuleName, getMetricAlertProperties(),\n\t\t\t\tImmutableMap.of(\"createdBy\", \"jclouds\"), GLOBAL);\n\t\tassertTrue(!metricAlert.type().isEmpty());\n\t}\n\t\n\t@Test(dependsOnMethods = \"testCreate\")\n\tpublic void testGet() {\n\t\tfinal MetricAlert rule = api().get(alertRuleName);\n\t\tassertTrue(!rule.name().isEmpty());\n\t}\n\n\t@Test(dependsOnMethods = \"testCreate\")\n\tpublic void testList() {\n\t\tList<MetricAlert> list = api().list();\n\t\tfinal MetricAlert rule = api().get(alertRuleName);\n\t\tboolean alertRulePresent = Iterables.any(list, new Predicate<MetricAlert>() {\n\t\t\t@Override\n\t\t\tpublic boolean apply(@Nullable MetricAlert input) {\n\t\t\t\treturn input.name().equals(rule.name());\n\t\t\t}\n\t\t});\n\t\tassertTrue(alertRulePresent);\n\t}\n\t\n\t@Test(dependsOnMethods = \"testList\", alwaysRun = true)\n\tpublic void testDelete() throws Exception {\n\t\tURI uri = api().delete(alertRuleName);\n\t\tassertResourceDeleted(uri);\n\t}\n\n\tpublic MetricAlertProperties getMetricAlertProperties() {\n\t\tfinal List<MetricAlertCriteria> lstMetricAlertCriteria = new ArrayList<>();\n\t\tlstMetricAlertCriteria.add(MetricAlertCriteria.create(\"StaticThresholdCriterion\", null, \"CPU Credits Consumed\",\n\t\t\t\t\"Microsoft.Compute/virtualMachines\", \"Metric1\", Operator.GreaterThan, false, 0,\n\t\t\t\tMetricAlertCriteria.AggregationTypeEnum.Average, null, null, null, null, 0, null));\n\t\tfinal Criteria criteria = Criteria.create(lstMetricAlertCriteria,\n\t\t\t\t\"Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria\");\n\t\treturn MetricAlertProperties.create(Collections.emptyList(), true, criteria, \"\", true, \"PT5M\", false, null,\n\t\t\t\tArrays.asList(\"/subscriptions/\" + subscriptionid + \"/resourceGroups/\" + resourceGroupName), 3, \"eastus\",\n\t\t\t\t\"Microsoft.Compute/virtualMachines\", \"PT5M\");\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/MetricAlertApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport static org.junit.Assert.assertNotNull;\nimport static org.junit.Assert.assertNull;\nimport static org.junit.Assert.assertTrue;\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.azurecompute.arm.domain.Criteria;\nimport org.jclouds.azurecompute.arm.domain.MetricAlert;\nimport org.jclouds.azurecompute.arm.domain.MetricAlertAction;\nimport org.jclouds.azurecompute.arm.domain.MetricAlertCriteria;\nimport org.jclouds.azurecompute.arm.domain.MetricAlertCriteria.Operator;\nimport org.jclouds.azurecompute.arm.domain.MetricAlertProperties;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiMockTest;\nimport org.testng.annotations.Test;\n\nimport okhttp3.mockwebserver.MockResponse;\n\n@Test(groups = \"unit\", testName = \"MetricAlertApiMockTest\", singleThreaded = true)\npublic class MetricAlertApiMockTest extends BaseAzureComputeApiMockTest {\n\n\tpublic void testList() throws InterruptedException {\n\t\tserver.enqueue(jsonResponse(\"/metricalertgetbyresource.json\"));\n\t\tfinal MetricAlertApi metricAlertApi = api.getMetricAlertApi(\"myResourceGroup\");\n\t\tList<MetricAlert> list = metricAlertApi.list();\n\t\tassertEquals(list, getMetricAlertRuleList());\n\t\tassertSent(server, \"GET\",\n\t\t\t\t\"/subscriptions/SUBSCRIPTIONID/resourcegroups/myResourceGroup/providers/Microsoft.Insights/metricAlerts?api-version=2018-03-01\");\n\t}\n\n\tprivate List<MetricAlert> getMetricAlertRuleList() {\n\t\tList<MetricAlert> metricAlertRules = new ArrayList<MetricAlert>();\n\t\tmetricAlertRules.add(MetricAlert.create(\n\t\t\t\t\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/microsoft.insights/metricalerts/MetricAlert1\",\n\t\t\t\t\"MetricAlert1\", \"global\", \"Microsoft.Insights/metricAlerts\", Collections.emptyMap(),\n\t\t\t\tmyMetricAlertProperties0()));\n\t\tmetricAlertRules.add(MetricAlert.create(\n\t\t\t\t\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/microsoft.insights/metricalerts/MetricAlert2\",\n\t\t\t\t\"MetricAlert2\", \"global\", \"Microsoft.Insights/metricAlerts\", Collections.emptyMap(),\n\t\t\t\tmyMetricAlertProperties1()));\n\t\treturn metricAlertRules;\n\t}\n\n\tpublic MetricAlertProperties myMetricAlertProperties0() {\n\t\treturn MetricAlertProperties.create(Collections.emptyList(), true, criteria0(\"Available Memory Bytes\"),\n\t\t\t\t\"MetricAlert1\", true, \"PT1M\", false, null, scope0(), 0, \"eastus\", \"Microsoft.Compute/virtualMachines\",\n\t\t\t\t\"PT1M\");\n\t}\n\n\tpublic MetricAlertProperties myMetricAlertProperties1() {\n\t\treturn MetricAlertProperties.create(actions(), true, criteria1(\"Percentage CPU\"), \"\", false, \"PT1M\", false,\n\t\t\t\tnull, scope1(), 3, \"eastus\", \"Microsoft.Compute/virtualMachines\", \"PT5M\");\n\t}\n\n\tpublic List<String> scope0() {\n\t\tList<String> list = new ArrayList<String>();\n\t\tlist.add(\n\t\t\t\t\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/LinuxVM\");\n\t\tlist.add(\n\t\t\t\t\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/CentOSVM\");\n\t\treturn list;\n\t}\n\n\tpublic List<String> scope1() {\n\t\tList<String> list = new ArrayList<String>();\n\t\tlist.add(\n\t\t\t\t\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/LinuxVM\");\n\t\treturn list;\n\t}\n\n\tpublic Criteria criteria0(String metricName) {\n\t\tList<MetricAlertCriteria> lstMetricAlertCriteria = new ArrayList<>();\n\t\tlstMetricAlertCriteria.add(MetricAlertCriteria.create(\"StaticThresholdCriterion\", null, metricName,\n\t\t\t\t\"Microsoft.Compute/virtualMachines\", \"criteria1\", Operator.GreaterThan, false, 0,\n\t\t\t\tMetricAlertCriteria.AggregationTypeEnum.Total, null, null, null, null, 0, null));\n\t\tfinal Criteria criteria = Criteria.create(lstMetricAlertCriteria,\n\t\t\t\t\"Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria\");\n\t\treturn criteria;\n\t}\n\n\tpublic Criteria criteria1(String metricName) {\n\t\tList<MetricAlertCriteria> lstMetricAlertCriteria = new ArrayList<>();\n\t\tlstMetricAlertCriteria.add(MetricAlertCriteria.create(\"StaticThresholdCriterion\", null, metricName,\n\t\t\t\t\"Microsoft.Compute/virtualMachines\", \"criteria1\", Operator.GreaterThan, false, 0,\n\t\t\t\tMetricAlertCriteria.AggregationTypeEnum.Average, null, null, null, null, 0, null));\n\t\tfinal Criteria criteria = Criteria.create(lstMetricAlertCriteria,\n\t\t\t\t\"Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria\");\n\t\treturn criteria;\n\t}\n\n\tpublic List<MetricAlertAction> actions() {\n\t\tList<MetricAlertAction> list = new ArrayList<>();\n\t\tMetricAlertAction actionGroup = MetricAlertAction.create(\n\t\t\t\t\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/microsoft.insights/actionGroups/metricaction\",\n\t\t\t\tnull);\n\t\tlist.add(actionGroup);\n\t\treturn list;\n\t}\n\n\tpublic void testListEmpty() throws Exception {\n\t\tserver.enqueue(new MockResponse().setResponseCode(404));\n\t\tfinal MetricAlertApi metricAlertApi = api.getMetricAlertApi(\"myResourceGroup\");\n\t\tList<MetricAlert> list = metricAlertApi.list();\n\t\tassertTrue(list.isEmpty());\n\t\tassertSent(server, \"GET\",\n\t\t\t\t\"/subscriptions/SUBSCRIPTIONID/resourcegroups/myResourceGroup/providers/Microsoft.Insights/metricAlerts?api-version=2018-03-01\");\n\t}\n\n\tpublic void testGet() throws InterruptedException {\n\t\tserver.enqueue(jsonResponse(\"/metricalertget.json\"));\n\t\tfinal MetricAlertApi metricAlerApi = api.getMetricAlertApi(\"myResourceGroup\");\n\t\tMetricAlert actual = metricAlerApi.get(\"MetricAlertTest\");\n\n\t\tMetricAlert expected = MetricAlert.create(\n\t\t\t\t\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Insights/metricalerts/MetricAlertTest\",\n\t\t\t\t\"MetricAlertTest\", \"global\", \"Microsoft.Insights/metricAlerts\", tags(), getMetricAlertProperties());\n\n\t\tassertEquals(expected, actual);\n\t\tassertSent(server, \"GET\",\n\t\t\t\t\"/subscriptions/SUBSCRIPTIONID/resourcegroups/myResourceGroup/providers/Microsoft.Insights/metricAlerts/MetricAlertTest?api-version=2018-03-01\");\n\t}\n\n\tpublic Map<String, String> tags() {\n\t\tMap<String, String> tags = new HashMap<>();\n\t\ttags.put(\"createdBy\", \"jclouds\");\n\t\treturn tags;\n\t}\n\n\tpublic MetricAlertProperties getMetricAlertProperties() {\n\t\tfinal List<MetricAlertAction> actionList = new ArrayList<>();\n\t\tfinal MetricAlertAction action = MetricAlertAction.create(\n\t\t\t\t\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/microsoft.insights/actiongroups/actionemail\",\n\t\t\t\tnull);\n\t\tactionList.add(action);\n\t\tfinal List<MetricAlertCriteria> lstMetricAlertCriteria = new ArrayList<>();\n\t\tlstMetricAlertCriteria.add(MetricAlertCriteria.create(\"StaticThresholdCriterion\", null, \"CPU Credits Consumed\",\n\t\t\t\t\"Microsoft.Compute/virtualMachines\", \"Metric1\", Operator.GreaterThan, false, 0,\n\t\t\t\tMetricAlertCriteria.AggregationTypeEnum.Average, null, null, null, null, 0, null));\n\t\tfinal Criteria criteria = Criteria.create(lstMetricAlertCriteria,\n\t\t\t\t\"Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria\");\n\t\treturn MetricAlertProperties.create(actionList, true, criteria, \"\", false, \"PT5M\", false, null, scope1(), 3,\n\t\t\t\t\"eastus\", \"Microsoft.Compute/virtualMachines\", \"PT5M\");\n\t}\n\n\tpublic void testGetReturns404() throws InterruptedException {\n\t\tserver.enqueue(response404());\n\t\tfinal MetricAlertApi metricAlerApi = api.getMetricAlertApi(\"myResourceGroup\");\n\t\tMetricAlert alert = metricAlerApi.get(\"MetricAlertTest\");\n\t\tassertNull(alert);\n\t\tassertSent(server, \"GET\",\n\t\t\t\t\"/subscriptions/SUBSCRIPTIONID/resourcegroups/myResourceGroup/providers/Microsoft.Insights/metricAlerts/MetricAlertTest?api-version=2018-03-01\");\n\t}\n\n\tpublic void testDelete() throws Exception {\n\t\tserver.enqueue(response202WithHeader());\n\t\tfinal MetricAlertApi metricAlerApi = api.getMetricAlertApi(\"myResourceGroup\");\n\t\tURI uri = metricAlerApi.delete(\"MetricAlertTest\");\n\t\tassertEquals(server.getRequestCount(), 1);\n\t\tassertNotNull(uri);\n\t\tassertSent(server, \"DELETE\",\n\t\t\t\t\"/subscriptions/SUBSCRIPTIONID/resourcegroups/myResourceGroup/providers/Microsoft.Insights/metricAlerts/MetricAlertTest?api-version=2018-03-01\");\n\t}\n\n\tpublic void testDeleteReturns404() throws Exception {\n\t\tserver.enqueue(response404());\n\t\tfinal MetricAlertApi metricAlerApi = api.getMetricAlertApi(\"myResourceGroup\");\n\t\tURI uri = metricAlerApi.delete(\"MetricAlertTest\");\n\t\tassertEquals(server.getRequestCount(), 1);\n\t\tassertNull(uri);\n\t\tassertSent(server, \"DELETE\",\n\t\t\t\t\"/subscriptions/SUBSCRIPTIONID/resourcegroups/myResourceGroup/providers/Microsoft.Insights/metricAlerts/MetricAlertTest?api-version=2018-03-01\");\n\t}\n\n\tpublic void testCreate() throws Exception {\n\t\tserver.enqueue(jsonResponse(\"/metricalertcreateorupdate.json\"));\n\t\tfinal MetricAlertApi metricAlertApi = api.getMetricAlertApi(\"myResourceGroup\");\n\t\tMetricAlert alertRule = metricAlertApi.createOrUpdate(\"MetricAlertTest\", getMetricAlertProperties(), tags(),\n\t\t\t\t\"global\");\n\n\t\tMetricAlert expected = MetricAlert.create(\n\t\t\t\t\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Insights/metricalerts/MetricAlertTest\",\n\t\t\t\t\"MetricAlertTest\", \"global\", \"Microsoft.Insights/metricAlerts\", tags(), getMetricAlertProperties());\n\n\t\tassertEquals(alertRule, expected);\n\t\tassertSent(server, \"PUT\",\n\t\t\t\t\"/subscriptions/SUBSCRIPTIONID/resourcegroups/myResourceGroup/providers/Microsoft.Insights/metricAlerts/MetricAlertTest?validating=false&api-version=2018-03-01\");\n\t}\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/MetricDefinitionsApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static org.jclouds.azurecompute.arm.compute.options.AzureTemplateOptions.Builder.resourceGroup;\nimport static org.jclouds.azurecompute.arm.config.AzureComputeProperties.TIMEOUT_RESOURCE_DELETED;\nimport static org.jclouds.compute.predicates.NodePredicates.inGroup;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.Assert.fail;\n\nimport java.net.URI;\nimport java.util.List;\nimport java.util.Properties;\n\nimport org.jclouds.azurecompute.arm.AzureComputeApi;\nimport org.jclouds.azurecompute.arm.domain.IdReference;\nimport org.jclouds.azurecompute.arm.domain.MetricDefinition;\nimport org.jclouds.azurecompute.arm.internal.AzureLiveTestUtils;\nimport org.jclouds.compute.RunNodesException;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.internal.BaseComputeServiceContextLiveTest;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.inject.Key;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.name.Names;\n\n@Test(groups = \"live\", singleThreaded = true)\npublic class MetricDefinitionsApiLiveTest extends BaseComputeServiceContextLiveTest {\n\n   private Predicate<URI> resourceDeleted;\n   private AzureComputeApi api;\n\n   private String location;\n   private MetricDefinitionsApi metricDefinitionsApi;\n\n   private String group;\n\n   public MetricDefinitionsApiLiveTest() {\n      provider = \"azurecompute-arm\";\n      group = getClass().getSimpleName().toLowerCase();\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties properties = super.setupProperties();\n      AzureLiveTestUtils.defaultProperties(properties);\n      checkNotNull(setIfTestSystemPropertyPresent(properties, \"oauth.endpoint\"), \"test.oauth.endpoint\");\n      return properties;\n   }\n\n   @Override\n   protected void initializeContext() {\n      super.initializeContext();\n      resourceDeleted = context.utils().injector().getInstance(Key.get(new TypeLiteral<Predicate<URI>>() {\n      }, Names.named(TIMEOUT_RESOURCE_DELETED)));\n      api = view.unwrapApi(AzureComputeApi.class);\n   }\n\n   @Override\n   @BeforeClass\n   public void setupContext() {\n      super.setupContext();\n      NodeMetadata node = null;\n      try {\n         node = getOnlyElement(view.getComputeService().createNodesInGroup(group, 1, resourceGroup(group)));\n      } catch (RunNodesException e) {\n         fail();\n      }\n      String resourceId = String.format(\"/resourceGroups/%s/providers/Microsoft.Compute/virtualMachines/%s\",\n            IdReference.extractResourceGroup(node.getProviderId()), IdReference.extractName(node.getProviderId()));\n\n      location = view.getComputeService().templateBuilder().build().getLocation().getId();\n      view.unwrapApi(AzureComputeApi.class).getResourceGroupApi().create(group, location, null);\n      metricDefinitionsApi = api.getMetricsDefinitionsApi(resourceId);\n   }\n\n   @Override\n   @AfterClass(alwaysRun = true)\n   protected void tearDownContext() {\n      try {\n         view.getComputeService().destroyNodesMatching(inGroup(group));\n      } finally {\n         try {\n            URI uri = api.getResourceGroupApi().delete(group);\n            assertResourceDeleted(uri);\n         } finally {\n            super.tearDownContext();\n         }\n      }\n   }\n\n   public void listVirtualMachineMetricDefinitions() {\n      List<MetricDefinition> result = metricDefinitionsApi.list(\"name.value eq 'Percentage CPU'\");\n\n      // verify we have something\n      assertNotNull(result);\n      assertTrue(result.size() > 1);\n      assertEquals(result.get(0).name().value(), \"Percentage CPU\");\n   }\n\n   private void assertResourceDeleted(final URI uri) {\n      if (uri != null) {\n         assertTrue(resourceDeleted.apply(uri),\n               String.format(\"Resource %s was not deleted in the configured timeout\", uri));\n      }\n   }\n\n}\n\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/MetricDefinitionsApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport okhttp3.mockwebserver.MockResponse;\n\nimport org.jclouds.azurecompute.arm.domain.MetricDefinition;\nimport org.jclouds.azurecompute.arm.domain.MetricName;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiMockTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"MetricDefinitionsApiMockTest\", singleThreaded = true)\npublic class MetricDefinitionsApiMockTest extends BaseAzureComputeApiMockTest {\n\n   private final String resourceId = \"resourceGroups/myresourceGroup/providers/Microsoft.Compute/virtualMachines/myvm\";\n   private final String filter = \"(name.value eq 'Percentage CPU')\";\n\n   public void testList() throws Exception {\n      server.enqueue(jsonResponse(\"/metricdefinitions.json\"));\n      final MetricDefinitionsApi metricDefinitionsApi = api.getMetricsDefinitionsApi(resourceId);\n      assertEquals(metricDefinitionsApi.list(filter), ImmutableList.of(MetricDefinition.create(\n            \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myresourcegroup/providers/Microsoft\"\n                  + \".Compute/virtualMachines/myvm\", MetricName.create(\"Percentage CPU\", \"Percentage CPU\"),\n            Boolean.FALSE, \"Percent\", MetricDefinition.AggregationType.Average,\n            ImmutableList.<MetricDefinition.MetricAvailability> of(\n                  MetricDefinition.MetricAvailability.create(\"PT1M\", \"P30D\"),\n                  MetricDefinition.MetricAvailability.create(\"PT1H\", \"P30D\")),\n            \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myresourcegroup/providers\"\n                  + \"/Microsoft.Compute/virtualMachines/myvm/providers/microsoft\"\n                  + \".insights/metricdefinitions/Percentage \" + \"CPU\")));\n      assertSent(server, \"GET\", \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myresourceGroup/providers/Microsoft\"\n            + \".Compute/virtualMachines/myvm/providers/microsoft.insights/metricdefinitions?$filter=%28name\"\n            + \".value%20eq%20%27Percentage%20CPU%27%29&api-version=2017-05-01-preview\");\n   }\n\n   public void testEmptyList() throws Exception {\n      server.enqueue(new MockResponse().setResponseCode(404));\n\n      final MetricDefinitionsApi metricDefinitionsApi = api.getMetricsDefinitionsApi(resourceId);\n\n      assertTrue(metricDefinitionsApi.list(filter).isEmpty());\n\n      assertSent(server, \"GET\", \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myresourceGroup/providers/Microsoft\"\n            + \".Compute/virtualMachines/myvm/providers/microsoft.insights/metricdefinitions?$filter=%28name\"\n            + \".value%20eq%20%27Percentage%20CPU%27%29&api-version=2017-05-01-preview\");\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/MetricsApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static org.jclouds.azurecompute.arm.compute.options.AzureTemplateOptions.Builder.resourceGroup;\nimport static org.jclouds.azurecompute.arm.config.AzureComputeProperties.TIMEOUT_RESOURCE_DELETED;\nimport static org.jclouds.compute.predicates.NodePredicates.inGroup;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.Assert.fail;\n\nimport java.net.URI;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Properties;\n\nimport org.jclouds.azurecompute.arm.AzureComputeApi;\nimport org.jclouds.azurecompute.arm.domain.IdReference;\nimport org.jclouds.azurecompute.arm.domain.Metric;\nimport org.jclouds.azurecompute.arm.internal.AzureLiveTestUtils;\nimport org.jclouds.compute.RunNodesException;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.internal.BaseComputeServiceContextLiveTest;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.inject.Key;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.name.Names;\n\n@Test(groups = \"live\", singleThreaded = true)\npublic class MetricsApiLiveTest extends BaseComputeServiceContextLiveTest {\n\n   private Predicate<URI> resourceDeleted;\n   private AzureComputeApi api;\n\n   private String location;\n   private MetricsApi metricsApi;\n\n   private String group;\n\n   private String startTime;\n   private SimpleDateFormat dateFormat;\n\n   public MetricsApiLiveTest() {\n      provider = \"azurecompute-arm\";\n      group = getClass().getSimpleName().toLowerCase();\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties properties = super.setupProperties();\n      AzureLiveTestUtils.defaultProperties(properties);\n      checkNotNull(setIfTestSystemPropertyPresent(properties, \"oauth.endpoint\"), \"test.oauth.endpoint\");\n      return properties;\n   }\n\n   @Override\n   protected void initializeContext() {\n      super.initializeContext();\n      resourceDeleted = context.utils().injector().getInstance(Key.get(new TypeLiteral<Predicate<URI>>() {\n      }, Names.named(TIMEOUT_RESOURCE_DELETED)));\n      api = view.unwrapApi(AzureComputeApi.class);\n   }\n\n   @Override\n   @BeforeClass\n   public void setupContext() {\n      super.setupContext();\n\n      dateFormat = new SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ss'Z'\");\n      startTime = dateFormat.format(new Date());\n\n      NodeMetadata node = null;\n      try {\n         node = getOnlyElement(view.getComputeService().createNodesInGroup(group, 1, resourceGroup(group)));\n      } catch (RunNodesException e) {\n         fail();\n      }\n      String resourceId = String.format(\"/resourceGroups/%s/providers/Microsoft.Compute/virtualMachines/%s\",\n            IdReference.extractResourceGroup(node.getProviderId()), IdReference.extractName(node.getProviderId()));\n\n      location = view.getComputeService().templateBuilder().build().getLocation().getId();\n      view.unwrapApi(AzureComputeApi.class).getResourceGroupApi().create(group, location, null);\n      metricsApi = api.getMetricsApi(resourceId);\n   }\n\n   @Override\n   @AfterClass(alwaysRun = true)\n   protected void tearDownContext() {\n      try {\n         view.getComputeService().destroyNodesMatching(inGroup(group));\n      } finally {\n         try {\n            URI uri = api.getResourceGroupApi().delete(group);\n            assertResourceDeleted(uri);\n         } finally {\n            super.tearDownContext();\n         }\n      }\n   }\n\n   public void listVirtualMachineMetrics() throws RunNodesException {\n      List<Metric> result = metricsApi\n            .list(\"(name.value eq 'Percentage CPU') and startTime eq \" + startTime + \" and endTime eq \" + dateFormat\n                  .format(new Date()) + \" and timeGrain eq duration'PT1M'\");\n\n      // verify we have something\n      assertNotNull(result);\n      assertEquals(result.size(), 1);\n      assertEquals(result.get(0).name().value(), \"Percentage CPU\");\n      assertTrue(result.get(0).data().size() > 1);\n   }\n\n   private void assertResourceDeleted(final URI uri) {\n      if (uri != null) {\n         assertTrue(resourceDeleted.apply(uri),\n               String.format(\"Resource %s was not deleted in the configured timeout\", uri));\n      }\n   }\n\n}\n\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/MetricsApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Date;\n\nimport okhttp3.mockwebserver.MockResponse;\n\nimport org.jclouds.azurecompute.arm.domain.Metric;\nimport org.jclouds.azurecompute.arm.domain.MetricData;\nimport org.jclouds.azurecompute.arm.domain.MetricName;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiMockTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"MetricsApiMockTest\", singleThreaded = true)\npublic class MetricsApiMockTest extends BaseAzureComputeApiMockTest {\n\n   private final String resourceId = \"resourceGroups/myresourceGroup/providers/Microsoft.Compute/virtualMachines/myvm\";\n   private final String filter = \"(name.value eq 'Percentage CPU') and startTime eq 2017-06-01T11:14:00Z and \"\n         + \"endTime eq 2017-06-01T11:23:00Z and timeGrain eq duration'PT1M'\";\n\n   public void testList() throws Exception {\n      server.enqueue(jsonResponse(\"/metrics.json\"));\n      final MetricsApi metricsApi = api.getMetricsApi(resourceId);\n      Date timestamp = dateService.iso8601DateOrSecondsDateParse(\"2017-06-01T11:14:00Z\");\n      assertEquals(metricsApi.list(filter), ImmutableList.of(Metric.create(\n            ImmutableList.of(MetricData.create(timestamp, null, Double.valueOf(0.295), null, null, null)),\n            \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myresourcegroup/providers\"\n                  + \"/Microsoft.Compute/virtualMachines/myvm/providers/Microsoft.Insights/metrics/Percentage CPU\",\n            MetricName.create(\"Percentage CPU\", \"Percentage CPU\"), \"Microsoft.Insights/metrics\", \"Percent\")));\n      assertSent(server, \"GET\", \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myresourceGroup/providers/Microsoft\"\n            + \".Compute/virtualMachines/myvm/providers/microsoft.insights/metrics?$filter=%28name\"\n            + \".value%20eq%20%27Percentage%20CPU%27%29%20and%20startTime%20eq%202017-06-01T11%3A14%3A00Z%20and\"\n            + \"%20endTime%20eq%202017-06-01T11%3A23%3A00Z%20and%20timeGrain%20eq%20duration%27PT1M%27&api-version\"\n            + \"=2016-09-01\");\n   }\n\n   public void testEmptyList() throws Exception {\n      server.enqueue(new MockResponse().setResponseCode(404));\n\n      final MetricsApi metricsAPI = api.getMetricsApi(resourceId);\n\n      assertTrue(metricsAPI.list(filter).isEmpty());\n\n      assertSent(server, \"GET\", \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myresourceGroup/providers/Microsoft\"\n            + \".Compute/virtualMachines/myvm/providers/microsoft.insights/metrics?$filter=%28name\"\n            + \".value%20eq%20%27Percentage%20CPU%27%29%20and%20startTime%20eq%202017-06-01T11%3A14%3A00Z%20and\"\n            + \"%20endTime%20eq%202017-06-01T11%3A23%3A00Z%20and%20timeGrain%20eq%20duration%27PT1M%27&api-version\"\n            + \"=2016-09-01\");\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/NetworkInterfaceCardApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport static java.lang.Boolean.TRUE;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.azurecompute.arm.domain.IdReference;\nimport org.jclouds.azurecompute.arm.domain.IpConfiguration;\nimport org.jclouds.azurecompute.arm.domain.IpConfigurationProperties;\nimport org.jclouds.azurecompute.arm.domain.NetworkInterfaceCard;\nimport org.jclouds.azurecompute.arm.domain.NetworkInterfaceCardProperties;\nimport org.jclouds.azurecompute.arm.domain.Subnet;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiLiveTest;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\n\n@Test(groups = \"live\", singleThreaded = true)\npublic class NetworkInterfaceCardApiLiveTest extends BaseAzureComputeApiLiveTest {\n\n   private String subnetId;\n   private String nicName;\n\n   @BeforeClass\n   @Override\n   public void setup() {\n      super.setup();\n      createTestResourceGroup();\n      String virtualNetworkName = String.format(\"vn-%s-%s\", this.getClass().getSimpleName().toLowerCase(), System.getProperty(\"user.name\"));\n      nicName = String.format(\"nic-%s-%s\", this.getClass().getSimpleName().toLowerCase(), System.getProperty(\"user.name\"));\n      String subnetName = String.format(\"s-%s-%s\", this.getClass().getSimpleName().toLowerCase(), System.getProperty(\"user.name\"));\n\n      //Subnets belong to a virtual network so that needs to be created first\n      assertNotNull(createDefaultVirtualNetwork(resourceGroupName, virtualNetworkName, \"10.2.0.0/16\", LOCATION));\n\n      //Subnet needs to be up & running before NIC can be created\n      Subnet subnet = createDefaultSubnet(resourceGroupName, subnetName, virtualNetworkName, \"10.2.0.0/23\");\n      assertNotNull(subnet);\n      assertNotNull(subnet.id());\n      subnetId = subnet.id();\n   }\n\n   @Test\n   public void createNetworkInterfaceCard() {\n      //Create properties object\n      final NetworkInterfaceCardProperties networkInterfaceCardProperties = NetworkInterfaceCardProperties.builder()\n            .ipConfigurations(Arrays.asList(IpConfiguration.builder().name(\"myipconfig\")\n                        .properties(IpConfigurationProperties.builder().privateIPAllocationMethod(\"Dynamic\").primary\n                                    (TRUE)\n                                      .subnet(IdReference.create(subnetId)).build()\n                              ).build()\n                      )).build();\n\n      final Map<String, String> tags = ImmutableMap.of(\"jclouds\", \"livetest\");\n      NetworkInterfaceCard nic = api().createOrUpdate(nicName, LOCATION, networkInterfaceCardProperties, tags);\n\n      assertEquals(nic.name(), nicName);\n      assertEquals(nic.location(), LOCATION);\n      assertTrue(nic.properties().ipConfigurations().size() > 0);\n      assertEquals(nic.properties().ipConfigurations().get(0).name(), \"myipconfig\");\n      assertEquals(nic.properties().ipConfigurations().get(0).properties().privateIPAllocationMethod(), \"Dynamic\");\n      assertTrue(nic.properties().ipConfigurations().get(0).properties().primary());\n      assertEquals(nic.properties().ipConfigurations().get(0).properties().subnet().id(), subnetId);\n      assertEquals(nic.tags().get(\"jclouds\"), \"livetest\");\n   }\n\n   @Test(dependsOnMethods = \"createNetworkInterfaceCard\")\n   public void getNetworkInterfaceCard() {\n      NetworkInterfaceCard nic = api().get(nicName);\n\n      assertEquals(nic.name(), nicName);\n      assertEquals(nic.location(), LOCATION);\n      assertTrue(nic.properties().ipConfigurations().size() > 0);\n      assertEquals(nic.properties().ipConfigurations().get(0).name(), \"myipconfig\");\n      assertEquals(nic.properties().ipConfigurations().get(0).properties().privateIPAllocationMethod(), \"Dynamic\");\n      assertEquals(nic.properties().ipConfigurations().get(0).properties().subnet().id(), subnetId);\n   }\n\n   @Test(dependsOnMethods = \"createNetworkInterfaceCard\")\n   public void listNetworkInterfaceCards() {\n      List<NetworkInterfaceCard> nicList = api().list();\n      assertTrue(nicList.contains(api().get(nicName)));\n   }\n\n   @Test(dependsOnMethods = \"createNetworkInterfaceCard\")\n   public void listAllNetworkInterfaceCardsInSubscription() {\n      List<NetworkInterfaceCard> nicList = api.getNetworkInterfaceCardApi(null).listAllInSubscription();\n      assertTrue(nicList.contains(api().get(nicName)));\n   }\n\n   @Test(dependsOnMethods = { \"listNetworkInterfaceCards\", \"listAllNetworkInterfaceCardsInSubscription\",\n         \"getNetworkInterfaceCard\" })\n   public void deleteNetworkInterfaceCard() {\n      URI uri = api().delete(nicName);\n      assertResourceDeleted(uri);\n   }\n\n   private NetworkInterfaceCardApi api() {\n      return api.getNetworkInterfaceCardApi(resourceGroupName);\n   }\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/NetworkInterfaceCardApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.Map;\n\nimport okhttp3.mockwebserver.MockResponse;\n\nimport org.jclouds.azurecompute.arm.domain.IdReference;\nimport org.jclouds.azurecompute.arm.domain.IpConfiguration;\nimport org.jclouds.azurecompute.arm.domain.IpConfigurationProperties;\nimport org.jclouds.azurecompute.arm.domain.NetworkInterfaceCard;\nimport org.jclouds.azurecompute.arm.domain.NetworkInterfaceCardProperties;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiMockTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\n\n@Test(groups = \"unit\", testName = \"NetworkInterfaceCardApiMockTest\", singleThreaded = true)\npublic class NetworkInterfaceCardApiMockTest extends BaseAzureComputeApiMockTest {\n\n   private final String subscriptionid = \"SUBSCRIPTIONID\";\n   private final String resourcegroup = \"myresourcegroup\";\n   private final String apiVersion = \"api-version=2017-03-01\";\n   private final String location = \"northeurope\";\n   private final String nicName = \"myNic\";\n\n   public void getNetworkInterfaceCard() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/getnetworkinterfacecard.json\"));\n\n      final NetworkInterfaceCardApi nicApi = api.getNetworkInterfaceCardApi(resourcegroup);\n      NetworkInterfaceCard nic = nicApi.get(nicName);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/networkInterfaces/%s?%s\", subscriptionid, resourcegroup, nicName, apiVersion);\n      assertSent(server, \"GET\", path);\n      assertNotNull(nic);\n      assertEquals(nic.name(), nicName);\n      assertTrue(nic.properties().primary());\n      assertEquals(nic.properties().ipConfigurations().get(0).name(), \"myip1\");\n      assertTrue(nic.properties().ipConfigurations().get(0).properties().primary());\n      assertEquals(nic.tags().get(\"mycustomtag\"), \"foobar\");\n   }\n\n   public void getNetworkInterfaceCardEmpty() throws Exception {\n      server.enqueue(new MockResponse().setResponseCode(404));\n\n      final NetworkInterfaceCardApi nicApi = api.getNetworkInterfaceCardApi(resourcegroup);\n\n      assertNull(nicApi.get(nicName));\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/networkInterfaces/%s?%s\", subscriptionid, resourcegroup, nicName, apiVersion);\n      assertSent(server, \"GET\", path);\n   }\n\n   public void listNetworkInterfaceCards() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/listnetworkinterfaces.json\"));\n\n      final NetworkInterfaceCardApi nicApi = api.getNetworkInterfaceCardApi(resourcegroup);\n      List<NetworkInterfaceCard> nicList = nicApi.list();\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/networkInterfaces?%s\", subscriptionid, resourcegroup, apiVersion);\n\n      assertSent(server, \"GET\", path);\n      assertTrue(nicList.size() == 2);\n      assertTrue(nicList.get(0).properties().ipConfigurations().size() > 0);\n      assertEquals(nicList.get(0).properties().ipConfigurations().get(0).properties().privateIPAllocationMethod(), \"Dynamic\");\n      assertTrue(nicList.get(1).properties().ipConfigurations().size() > 0);\n      assertEquals(nicList.get(1).properties().ipConfigurations().get(0).properties().privateIPAllocationMethod(), \"Static\");\n   }\n\n   public void listAllNetworkInterfaceCardsInSubscription() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/listallnetworkinterfaces.json\"));\n\n      final NetworkInterfaceCardApi nicApi = api.getNetworkInterfaceCardApi(null);\n      List<NetworkInterfaceCard> nicList = nicApi.listAllInSubscription();\n      String path = String\n            .format(\"/subscriptions/%s/providers/Microsoft.Network/networkInterfaces?%s\", subscriptionid, apiVersion);\n\n      assertSent(server, \"GET\", path);\n      assertTrue(nicList.size() == 3);\n      assertTrue(nicList.get(0).properties().ipConfigurations().size() > 0);\n      assertEquals(nicList.get(0).properties().ipConfigurations().get(0).properties().privateIPAllocationMethod(),\n            \"Dynamic\");\n      assertTrue(nicList.get(1).properties().ipConfigurations().size() > 0);\n      assertEquals(nicList.get(1).properties().ipConfigurations().get(0).properties().privateIPAllocationMethod(),\n            \"Static\");\n      assertTrue(nicList.get(2).properties().ipConfigurations().size() > 0);\n      assertNotEquals(IdReference.extractResourceGroup(nicList.get(2).id()), resourcegroup);\n      assertEquals(nicList.get(2).properties().ipConfigurations().get(0).properties().privateIPAllocationMethod(),\n            \"Static\");\n   }\n\n   public void listAllNetworkInterfaceCardsInSubscriptionEmpty() throws Exception {\n      server.enqueue(new MockResponse().setResponseCode(404));\n\n      final NetworkInterfaceCardApi nicApi = api.getNetworkInterfaceCardApi(null);\n\n      assertTrue(nicApi.listAllInSubscription().isEmpty());\n      String path = String\n            .format(\"/subscriptions/%s/providers/Microsoft.Network/networkInterfaces?%s\", subscriptionid, apiVersion);\n\n      assertSent(server, \"GET\", path);\n   }\n\n   public void listNetworkInterfaceCardsEmpty() throws Exception {\n      server.enqueue(new MockResponse().setResponseCode(404));\n\n      final NetworkInterfaceCardApi nicApi = api.getNetworkInterfaceCardApi(resourcegroup);\n\n      assertTrue(nicApi.list().isEmpty());\n      String path = String\n            .format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/networkInterfaces?%s\",\n                  subscriptionid, resourcegroup, apiVersion);\n\n      assertSent(server, \"GET\", path);\n   }\n\n   public void createNetworkInterfaceCard() throws InterruptedException {\n\n      server.enqueue(jsonResponse(\"/createnetworkinterfacecard.json\").setStatus(\"HTTP/1.1 201 Created\"));\n\n      final NetworkInterfaceCardApi nicApi = api.getNetworkInterfaceCardApi(resourcegroup);\n\n\n      final String SubnetID = \"/subscriptions/\" + subscriptionid + \"/resourceGroups/azurearmtesting/providers/Microsoft.Network/virtualNetworks/myvirtualnetwork/subnets/mysubnet\";\n      //Create properties object\n      final NetworkInterfaceCardProperties networkInterfaceCardProperties = NetworkInterfaceCardProperties\n            .create(null, null, null, Arrays.asList(IpConfiguration.create(\"myipconfig\", null, null,\n                  IpConfigurationProperties\n                        .create(null, null, \"Dynamic\", IdReference.create(SubnetID), null, null, null, Boolean.TRUE))),\n                  null, null, Boolean.TRUE);\n\n      final Map<String, String> tags = ImmutableMap.of(\"mycustomtag\", \"foobar\");\n\n      NetworkInterfaceCard nic = nicApi.createOrUpdate(nicName, location, networkInterfaceCardProperties, tags);\n\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/networkInterfaces/%s?%s\", subscriptionid, resourcegroup, nicName, apiVersion);\n      String json = String.format(\n            \"{\\\"location\\\":\\\"northeurope\\\",\\\"properties\\\":{\\\"ipConfigurations\\\":[{\\\"name\\\":\\\"myipconfig\\\",\"\n                  + \"\\\"properties\\\":{\\\"privateIPAllocationMethod\\\":\\\"Dynamic\\\",\"\n                  + \"\\\"subnet\\\":{\\\"id\\\":\\\"/subscriptions/SUBSCRIPTIONID/resourceGroups/azurearmtesting/providers\"\n                  + \"/Microsoft\" + \".Network/virtualNetworks/myvirtualnetwork/subnets/mysubnet\\\"},\\\"primary\\\":true}}],\"\n                  + \"\\\"primary\\\":true},\" + \"\\\"tags\\\":{\\\"mycustomtag\\\":\\\"foobar\\\"}}\");\n      assertSent(server, \"PUT\", path, json);\n      assertEquals(nic.tags().get(\"mycustomtag\"), \"foobar\");\n   }\n\n   public void deleteNetworkInterfaceCard() throws InterruptedException {\n\n      server.enqueue(response202WithHeader());\n\n      final NetworkInterfaceCardApi nicApi = api.getNetworkInterfaceCardApi(resourcegroup);\n\n      nicApi.delete(nicName);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/networkInterfaces/%s?%s\", subscriptionid, resourcegroup, nicName, apiVersion);\n      assertSent(server, \"DELETE\", path);\n\n   }\n\n   public void deleteNetworkInterfaceCardResourceDoesNotExist() throws InterruptedException {\n\n      server.enqueue(response404());\n\n      final NetworkInterfaceCardApi nicApi = api.getNetworkInterfaceCardApi(resourcegroup);\n\n      nicApi.delete(nicName);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/networkInterfaces/%s?%s\", subscriptionid, resourcegroup, nicName, apiVersion);\n      assertSent(server, \"DELETE\", path);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/NetworkSecurityGroupApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityGroup;\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityRule;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiLiveTest;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true)\npublic class NetworkSecurityGroupApiLiveTest extends BaseAzureComputeApiLiveTest {\n\n   private static String nsgName = \"testNetworkSecurityGroup\";\n\n   @BeforeClass\n   @Override\n   public void setup() {\n      super.setup();\n      createTestResourceGroup();\n      nsgName = String.format(\"nsg-%s-%s\", this.getClass().getSimpleName().toLowerCase(), System.getProperty(\"user.name\"));\n   }\n\n   @Test\n   public void deleteNetworkSecurityGroupDoesNotExist() {\n      URI uri = api().delete(nsgName);\n      assertNull(uri);\n   }\n\n   @Test(dependsOnMethods = \"deleteNetworkSecurityGroupDoesNotExist\")\n   public void createNetworkSecurityGroup() {\n      final NetworkSecurityGroup nsg = newNetworkSecurityGroup(nsgName, LOCATION);\n      assertNotNull(nsg);\n\n      NetworkSecurityGroup result = api().createOrUpdate(nsgName,\n                                                  nsg.location(),\n                                                  nsg.tags(),\n                                                  nsg.properties());\n      assertNotNull(result);\n   }\n\n   @Test(dependsOnMethods = \"createNetworkSecurityGroup\")\n   public void listNetworkSecurityGroups() {\n      List<NetworkSecurityGroup> result = api().list();\n\n      // verify we have something\n      assertNotNull(result);\n      assertEquals(result.size(), 1);\n\n      // check that the network security group matches the one we originally passed in\n      NetworkSecurityGroup original = newNetworkSecurityGroup(nsgName, LOCATION);\n      NetworkSecurityGroup nsg = result.get(0);\n      assertEquals(original.name(), nsg.name());\n      assertEquals(original.location(), nsg.location());\n      assertEquals(original.tags(), nsg.tags());\n\n      // check the network security rule in the group\n      assertEquals(nsg.properties().securityRules().size(), 1);\n      NetworkSecurityRule originalRule = original.properties().securityRules().get(0);\n      NetworkSecurityRule nsgRule = nsg.properties().securityRules().get(0);\n      assertEquals(originalRule.name(), nsgRule.name());\n      assertTrue(originalRule.properties().equals(nsgRule.properties()));\n   }\n\n   @Test(dependsOnMethods = \"createNetworkSecurityGroup\")\n   public void listAllNetworkSecurityGroups() {\n      List<NetworkSecurityGroup> result = api().listAll();\n\n      // verify we have at least the original created SG. We could retrieve here any other SGs in different RGs\n      assertNotNull(result);\n      assertTrue(result.size() > 1);\n\n      NetworkSecurityGroup original = newNetworkSecurityGroup(nsgName, LOCATION);\n      boolean found = false;\n      for (NetworkSecurityGroup networkSecurityGroup : result) {\n         if (networkSecurityGroup.name().equalsIgnoreCase(original.name())) {\n            assertEquals(original.name(), networkSecurityGroup.name());\n            assertEquals(original.location(), networkSecurityGroup.location());\n            assertEquals(original.tags(), networkSecurityGroup.tags());\n\n            // check the network security rule in the group\n            assertEquals(networkSecurityGroup.properties().securityRules().size(), 1);\n            NetworkSecurityRule originalRule = original.properties().securityRules().get(0);\n            NetworkSecurityRule nsgRule = networkSecurityGroup.properties().securityRules().get(0);\n            assertEquals(originalRule.name(), nsgRule.name());\n            assertTrue(originalRule.properties().equals(nsgRule.properties()));\n            found = true;\n            break;\n         }\n      }\n\n      assertTrue(found, \"NSG created in test was not found in subscription\");\n   }\n\n   @Test(dependsOnMethods = { \"listNetworkSecurityGroups\", \"listAllNetworkSecurityGroups\", \"getNetworkSecurityGroup\" }, alwaysRun = true)\n   public void deleteNetworkSecurityGroup() {\n      URI uri = api().delete(nsgName);\n      assertResourceDeleted(uri);\n   }\n\n   @Test(dependsOnMethods = \"createNetworkSecurityGroup\")\n   public void getNetworkSecurityGroup() {\n      NetworkSecurityGroup nsg = api().get(nsgName);\n      assertNotNull(nsg);\n      assertNotNull(nsg.etag());\n      assertEquals(nsg.name(), nsgName);\n   }\n\n   private NetworkSecurityGroupApi api() {\n      return api.getNetworkSecurityGroupApi(resourceGroupName);\n   }\n\n}\n\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/NetworkSecurityGroupApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport static com.google.common.collect.Iterables.isEmpty;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityGroup;\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityGroupProperties;\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityRule;\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityRuleProperties;\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityRuleProperties.Protocol;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiMockTest;\nimport org.testng.annotations.Test;\n\nimport com.google.gson.Gson;\n\n@Test(groups = \"unit\", testName = \"NetworkSecurityGroupApiMockTest\", singleThreaded = true)\npublic class NetworkSecurityGroupApiMockTest extends BaseAzureComputeApiMockTest {\n   private final String subscriptionid = \"SUBSCRIPTIONID\";\n   private final String resourcegroup = \"myresourcegroup\";\n   private final String apiVersion = \"api-version=2016-03-30\";\n   private static String DEFAULT_NSG_NAME = \"testNetworkSecurityGroup\";\n\n   private NetworkSecurityGroup createGroup() {\n      NetworkSecurityRule rule = NetworkSecurityRule.create(\"denyallout\", null, null,\n              NetworkSecurityRuleProperties.builder()\n                      .description(\"deny all out\")\n                      .protocol(Protocol.Tcp)\n                      .sourcePortRange(\"*\")\n                      .destinationPortRange(\"*\")\n                      .sourceAddressPrefix(\"*\")\n                      .destinationAddressPrefix(\"*\")\n                      .access(NetworkSecurityRuleProperties.Access.Deny)\n                      .priority(4095)\n                      .direction(NetworkSecurityRuleProperties.Direction.Outbound)\n                      .provisioningState(\"Succeeded\")\n                      .build());\n      ArrayList<NetworkSecurityRule> ruleList = new ArrayList<NetworkSecurityRule>();\n      ruleList.add(rule);\n      NetworkSecurityGroup nsg = NetworkSecurityGroup.create(\"id\", \"samplensg\", \"westus\", null,\n              NetworkSecurityGroupProperties.builder()\n                      .securityRules(ruleList)\n                      .build(),\n              null);\n      return nsg;\n   }\n\n   public void createNetworkSecurityGroup() throws InterruptedException {\n      NetworkSecurityGroup nsg = createGroup();\n\n      server.enqueue(jsonResponse(\"/networksecuritygroupcreate.json\").setResponseCode(200));\n      final NetworkSecurityGroupApi nsgApi = api.getNetworkSecurityGroupApi(resourcegroup);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/networkSecurityGroups/%s?%s\", subscriptionid, resourcegroup, DEFAULT_NSG_NAME, apiVersion);\n      String json = String.format(\"{\\\"location\\\":\\\"%s\\\",\\\"properties\\\":%s}\", \"westus\", new Gson().toJson(nsg.properties()));\n      NetworkSecurityGroup result = nsgApi.createOrUpdate(DEFAULT_NSG_NAME, \"westus\", null, nsg.properties());\n      assertSent(server, \"PUT\", path, json);\n\n      assertEquals(result.name(), DEFAULT_NSG_NAME);\n      assertEquals(result.location(), \"westus\");\n      assertEquals(result.properties().securityRules().size(), 1);\n      assertEquals(result.properties().securityRules().get(0).properties().protocol(), Protocol.Tcp);\n   }\n\n   public void getNetworkSecurityGroup() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/networksecuritygroupget.json\").setResponseCode(200));\n\n      final NetworkSecurityGroupApi nsgApi = api.getNetworkSecurityGroupApi(resourcegroup);\n      NetworkSecurityGroup result = nsgApi.get(DEFAULT_NSG_NAME);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/networkSecurityGroups/%s?%s\", subscriptionid, resourcegroup, DEFAULT_NSG_NAME, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertEquals(result.name(), DEFAULT_NSG_NAME);\n      assertEquals(result.location(), \"westus\");\n      assertEquals(result.properties().securityRules().size(), 1);\n      assertEquals(result.properties().securityRules().get(0).properties().protocol(), Protocol.Tcp);\n   }\n\n   public void getNetworkSecurityGroupReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      final NetworkSecurityGroupApi nsgApi = api.getNetworkSecurityGroupApi(resourcegroup);\n      NetworkSecurityGroup result = nsgApi.get(DEFAULT_NSG_NAME);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/networkSecurityGroups/%s?%s\", subscriptionid, resourcegroup, DEFAULT_NSG_NAME, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertNull(result);\n   }\n\n   public void listNetworkSecurityGroups() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/networksecuritygrouplist.json\").setResponseCode(200));\n\n      final NetworkSecurityGroupApi nsgApi = api.getNetworkSecurityGroupApi(resourcegroup);\n      List<NetworkSecurityGroup> result = nsgApi.list();\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/networkSecurityGroups?%s\", subscriptionid, resourcegroup, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertNotNull(result);\n      assertTrue(result.size() > 0);\n   }\n\n   public void listAllNetworkSecurityGroups() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/networksecuritygrouplistall.json\").setResponseCode(200));\n\n      final NetworkSecurityGroupApi nsgApi = api.getNetworkSecurityGroupApi(resourcegroup);\n      List<NetworkSecurityGroup> result = nsgApi.listAll();\n\n      String path = String.format(\"/subscriptions/%s/providers/Microsoft.Network/networkSecurityGroups?%s\", subscriptionid, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertNotNull(result);\n      assertEquals(result.size(), 2);\n   }\n\n   public void listNetworkSecurityGroupsReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      final NetworkSecurityGroupApi nsgApi = api.getNetworkSecurityGroupApi(resourcegroup);\n      List<NetworkSecurityGroup> result = nsgApi.list();\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/networkSecurityGroups?%s\", subscriptionid, resourcegroup, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertTrue(isEmpty(result));\n   }\n\n   public void deleteNetworkSecurityGroup() throws InterruptedException {\n      server.enqueue(response202WithHeader());\n\n      final NetworkSecurityGroupApi nsgApi = api.getNetworkSecurityGroupApi(resourcegroup);\n      URI uri = nsgApi.delete(DEFAULT_NSG_NAME);\n\n      assertEquals(server.getRequestCount(), 1);\n      assertNotNull(uri);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/networkSecurityGroups/%s?%s\", subscriptionid, resourcegroup, DEFAULT_NSG_NAME, apiVersion);\n      assertSent(server, \"DELETE\", path);\n\n      assertTrue(uri.toString().contains(\"api-version\"));\n      assertTrue(uri.toString().contains(\"operationresults\"));\n   }\n\n   public void deleteNetworkSecurityGroupDoesNotExist() throws InterruptedException {\n      server.enqueue(response404());\n\n      final NetworkSecurityGroupApi nsgApi = api.getNetworkSecurityGroupApi(resourcegroup);\n      URI uri = nsgApi.delete(DEFAULT_NSG_NAME);\n      assertNull(uri);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/networkSecurityGroups/%s?%s\", subscriptionid, resourcegroup, DEFAULT_NSG_NAME, apiVersion);\n      assertSent(server, \"DELETE\", path);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/NetworkSecurityRuleApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityGroup;\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityRule;\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityRuleProperties;\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityRuleProperties.Access;\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityRuleProperties.Direction;\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityRuleProperties.Protocol;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiLiveTest;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Iterables;\n\n@Test(groups = \"live\", singleThreaded = true)\npublic class NetworkSecurityRuleApiLiveTest extends BaseAzureComputeApiLiveTest {\n\n   private static String UNKNOWN_RULE_NAME = \"ruledoesntexist\";\n   private String nsgName;\n\n   @BeforeClass\n   @Override\n   public void setup() {\n      super.setup();\n      createTestResourceGroup();\n      nsgName = String.format(\"nsg-%s-%s\", this.getClass().getSimpleName().toLowerCase(), System.getProperty(\"user.name\"));\n\n      // a network security group is needed\n      final NetworkSecurityGroup nsg = newNetworkSecurityGroup(nsgName, LOCATION);\n      assertNotNull(api.getNetworkSecurityGroupApi(resourceGroupName).createOrUpdate(nsgName,\n              nsg.location(),\n              nsg.tags(),\n              nsg.properties()));\n   }\n\n   @Test\n   public void deleteNetworkSecurityRuleDoesNotExist() {\n      URI uri = api().delete(UNKNOWN_RULE_NAME);\n      assertNull(uri);\n   }\n\n   @Test(dependsOnMethods = \"deleteNetworkSecurityRuleDoesNotExist\")\n   public void createNetworkSecurityRule() {\n      final NetworkSecurityRule rule = createRule();\n      assertNotNull(rule);\n\n      final NetworkSecurityRuleApi ruleApi = api.getNetworkSecurityRuleApi(resourceGroupName, nsgName);\n      NetworkSecurityRule result = ruleApi.createOrUpdate(rule.name(), rule.properties());\n      assertNotNull(result);\n      assertEquals(result.name(), rule.name());\n   }\n\n   @Test(dependsOnMethods = \"createNetworkSecurityRule\")\n   public void getNetworkSecurityRule() {\n      final NetworkSecurityRule rule = createRule();\n      assertNotNull(rule);\n\n      NetworkSecurityRule result = api().get(rule.name());\n      assertNotNull(result);\n      assertNotNull(result.etag());\n      assertEquals(result.name(), rule.name());\n   }\n\n   @Test(dependsOnMethods = \"createNetworkSecurityRule\")\n   public void getNetworkSecurityDefaultRule() {\n      String defaultRuleName = \"AllowVnetInBound\";\n\n      NetworkSecurityRule result = api().getDefaultRule(defaultRuleName);\n\n      assertNotNull(result);\n      assertNotNull(result.etag());\n      assertEquals(result.name(), defaultRuleName);\n   }\n\n   @Test(dependsOnMethods = \"createNetworkSecurityRule\")\n   public void listNetworkSecurityRules() {\n      final NetworkSecurityRule rule = createRule();\n      assertNotNull(rule);\n\n      List<NetworkSecurityRule> result = api().list();\n\n      assertNotNull(result);\n      assertEquals(result.size(), 2);\n\n      boolean rulePresent = Iterables.any(result, new Predicate<NetworkSecurityRule>() {\n         public boolean apply(NetworkSecurityRule input) {\n            return input.name().equals(rule.name());\n         }\n      });\n\n      assertTrue(rulePresent);\n   }\n\n   @Test(dependsOnMethods = \"createNetworkSecurityRule\")\n   public void listDefaultSecurityRules() {\n      List<NetworkSecurityRule> result = api().listDefaultRules();\n      assertNotNull(result);\n      assertTrue(result.size() > 0);\n   }\n\n   @Test(dependsOnMethods = {\"listNetworkSecurityRules\", \"listDefaultSecurityRules\", \"getNetworkSecurityRule\"})\n   public void deleteNetworkSecurityRule() {\n      final NetworkSecurityRule rule = createRule();\n      assertNotNull(rule);\n\n      URI uri = api().delete(rule.name());\n      assertResourceDeleted(uri);\n   }\n\n   private NetworkSecurityRule createRule() {\n      NetworkSecurityRule rule = NetworkSecurityRule.create(\"allowalludpin\", null, null,\n              NetworkSecurityRuleProperties.builder()\n                      .description(\"allow all udp in\")\n                      .protocol(Protocol.Udp)\n                      .sourcePortRange(\"*\")\n                      .destinationPortRange(\"*\")\n                      .sourceAddressPrefix(\"*\")\n                      .destinationAddressPrefix(\"*\")\n                      .access(Access.Allow)\n                      .priority(4094)\n                      .direction(Direction.Inbound)\n                      .build());\n      return rule;\n   }\n\n   private NetworkSecurityRuleApi api() {\n      return api.getNetworkSecurityRuleApi(resourceGroupName, nsgName);\n   }\n\n}\n\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/NetworkSecurityRuleApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport com.google.gson.Gson;\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityRule;\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityRuleProperties;\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityRuleProperties.Protocol;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiMockTest;\nimport org.testng.annotations.Test;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport static com.google.common.collect.Iterables.isEmpty;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.Assert.assertNotNull;\n\n\n@Test(groups = \"unit\", testName = \"NetworkSecurityRuleApiMockTest\", singleThreaded = true)\npublic class NetworkSecurityRuleApiMockTest extends BaseAzureComputeApiMockTest {\n   private final String subscriptionid = \"SUBSCRIPTIONID\";\n   private final String resourcegroup = \"myresourcegroup\";\n   private final String apiVersion = \"api-version=2016-03-30\";\n   private static String DEFAULT_NSG_NAME = \"testNetworkSecurityGroup\";\n\n   private NetworkSecurityRule createRule() {\n      NetworkSecurityRule rule = NetworkSecurityRule.create(\"allowalludpin\", null, null,\n              NetworkSecurityRuleProperties.builder()\n                      .description(\"allow all udp in\")\n                      .protocol(Protocol.Udp)\n                      .sourcePortRange(\"*\")\n                      .destinationPortRange(\"*\")\n                      .sourceAddressPrefix(\"*\")\n                      .destinationAddressPrefix(\"*\")\n                      .access(NetworkSecurityRuleProperties.Access.Allow)\n                      .priority(4094)\n                      .direction(NetworkSecurityRuleProperties.Direction.Inbound)\n                      .provisioningState(\"Succeeded\")\n                      .build());\n      return rule;\n   }\n\n   public void createNetworkSecurityRule() throws InterruptedException {\n      NetworkSecurityRule rule = createRule();\n\n      server.enqueue(jsonResponse(\"/networksecurityrulecreate.json\").setResponseCode(200));\n      final NetworkSecurityRuleApi ruleApi = api.getNetworkSecurityRuleApi(resourcegroup, DEFAULT_NSG_NAME);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/networkSecurityGroups/%s/securityRules/%s?%s\", subscriptionid, resourcegroup, DEFAULT_NSG_NAME, rule.name(), apiVersion);\n      NetworkSecurityRule result = ruleApi.createOrUpdate(rule.name(), rule.properties());\n      String json = String.format(\"{\\\"properties\\\":%s}\", new Gson().toJson(rule.properties()));\n\n      assertSent(server, \"PUT\", path, json);\n\n      assertNotNull(result);\n      assertEquals(result.name(), rule.name());\n   }\n\n   public void getNetworkSecurityRule() throws InterruptedException {\n      NetworkSecurityRule rule = createRule();\n\n      server.enqueue(jsonResponse(\"/networksecurityruleget.json\").setResponseCode(200));\n      final NetworkSecurityRuleApi ruleApi = api.getNetworkSecurityRuleApi(resourcegroup, DEFAULT_NSG_NAME);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/networkSecurityGroups/%s/securityRules/%s?%s\", subscriptionid, resourcegroup, DEFAULT_NSG_NAME, rule.name(), apiVersion);\n      NetworkSecurityRule result = ruleApi.get(rule.name());\n      assertSent(server, \"GET\", path);\n\n      assertEquals(result.name(), rule.name());\n   }\n\n   public void getNetworkSecurityRuleReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      String missingRuleName = \"ruleismissing\";\n      final NetworkSecurityRuleApi ruleApi = api.getNetworkSecurityRuleApi(resourcegroup, DEFAULT_NSG_NAME);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/networkSecurityGroups/%s/securityRules/%s?%s\", subscriptionid, resourcegroup, DEFAULT_NSG_NAME, missingRuleName, apiVersion);\n      NetworkSecurityRule result = ruleApi.get(missingRuleName);\n      assertSent(server, \"GET\", path);\n\n      assertNull(result);\n   }\n\n   public void getNetworkSecurityDefaultRule() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/networksecurityrulegetdefault.json\").setResponseCode(200));\n      final NetworkSecurityRuleApi ruleApi = api.getNetworkSecurityRuleApi(resourcegroup, DEFAULT_NSG_NAME);\n      String ruleName = \"AllowVnetInBound\";\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/networkSecurityGroups/%s/defaultSecurityRules/%s?%s\", subscriptionid, resourcegroup, DEFAULT_NSG_NAME, ruleName, apiVersion);\n      NetworkSecurityRule result = ruleApi.getDefaultRule(ruleName);\n      assertSent(server, \"GET\", path);\n\n      assertNotNull(result);\n      assertEquals(result.name(), ruleName);\n   }\n\n   public void getNetworkSecurityDefaultRuleReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      String missingRuleName = \"ruleismissing\";\n      final NetworkSecurityRuleApi ruleApi = api.getNetworkSecurityRuleApi(resourcegroup, DEFAULT_NSG_NAME);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/networkSecurityGroups/%s/defaultSecurityRules/%s?%s\", subscriptionid, resourcegroup, DEFAULT_NSG_NAME, missingRuleName, apiVersion);\n      NetworkSecurityRule result = ruleApi.getDefaultRule(missingRuleName);\n      assertSent(server, \"GET\", path);\n\n      assertNull(result);\n   }\n\n   public void listNetworkSecurityRules() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/networksecurityrulelist.json\").setResponseCode(200));\n\n      final NetworkSecurityRuleApi ruleApi = api.getNetworkSecurityRuleApi(resourcegroup, DEFAULT_NSG_NAME);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/networkSecurityGroups/%s/securityRules?%s\", subscriptionid, resourcegroup, DEFAULT_NSG_NAME, apiVersion);\n      List<NetworkSecurityRule> result = ruleApi.list();\n      assertSent(server, \"GET\", path);\n\n      assertNotNull(result);\n      assertTrue(result.size() > 0);\n   }\n\n   public void listNetworkSecurityRulesReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      final NetworkSecurityRuleApi ruleApi = api.getNetworkSecurityRuleApi(resourcegroup, DEFAULT_NSG_NAME);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/networkSecurityGroups/%s/securityRules?%s\", subscriptionid, resourcegroup, DEFAULT_NSG_NAME, apiVersion);\n      List<NetworkSecurityRule> result = ruleApi.list();\n      assertSent(server, \"GET\", path);\n\n      assertTrue(isEmpty(result));\n   }\n\n   public void listNetworkSecurityDefaultRules() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/networksecurityrulelistdefault.json\").setResponseCode(200));\n\n      final NetworkSecurityRuleApi ruleApi = api.getNetworkSecurityRuleApi(resourcegroup, DEFAULT_NSG_NAME);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/networkSecurityGroups/%s/defaultSecurityRules?%s\", subscriptionid, resourcegroup, DEFAULT_NSG_NAME, apiVersion);\n      List<NetworkSecurityRule> result = ruleApi.listDefaultRules();\n      assertSent(server, \"GET\", path);\n\n      assertNotNull(result);\n      assertTrue(result.size() > 0);\n   }\n\n   public void listNetworkSecurityDefaultRulesReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      final NetworkSecurityRuleApi ruleApi = api.getNetworkSecurityRuleApi(resourcegroup, DEFAULT_NSG_NAME);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/networkSecurityGroups/%s/defaultSecurityRules?%s\", subscriptionid, resourcegroup, DEFAULT_NSG_NAME, apiVersion);\n      List<NetworkSecurityRule> result = ruleApi.listDefaultRules();\n      assertSent(server, \"GET\", path);\n\n      assertTrue(isEmpty(result));\n   }\n\n   public void deleteNetworkSecurityRule() throws InterruptedException {\n      server.enqueue(response202WithHeader());\n\n      NetworkSecurityRule rule = createRule();\n\n      final NetworkSecurityRuleApi ruleApi = api.getNetworkSecurityRuleApi(resourcegroup, DEFAULT_NSG_NAME);\n      URI uri = ruleApi.delete(rule.name());\n\n      assertEquals(server.getRequestCount(), 1);\n      assertNotNull(uri);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/networkSecurityGroups/%s/securityRules/%s?%s\", subscriptionid, resourcegroup, DEFAULT_NSG_NAME, rule.name(), apiVersion);\n      assertSent(server, \"DELETE\", path);\n\n      assertTrue(uri.toString().contains(\"api-version\"));\n      assertTrue(uri.toString().contains(\"operationresults\"));\n   }\n\n   public void deleteNetworkSecurityRuleDoesNotExist() throws InterruptedException {\n      server.enqueue(response404());\n\n      final NetworkSecurityRuleApi ruleApi = api.getNetworkSecurityRuleApi(resourcegroup, DEFAULT_NSG_NAME);\n      String dummyname = \"dummyrulename\";\n      URI uri = ruleApi.delete(dummyname);\n      assertNull(uri);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/networkSecurityGroups/%s/securityRules/%s?%s\", subscriptionid, resourcegroup, DEFAULT_NSG_NAME, dummyname, apiVersion);\n      assertSent(server, \"DELETE\", path);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/OSImageApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport java.util.List;\n\nimport org.jclouds.azurecompute.arm.domain.Offer;\nimport org.jclouds.azurecompute.arm.domain.Publisher;\nimport org.jclouds.azurecompute.arm.domain.SKU;\nimport org.jclouds.azurecompute.arm.domain.Version;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiLiveTest;\nimport org.testng.annotations.Test;\n\nimport static org.testng.Assert.assertTrue;\n\n@Test(groups = \"live\", testName = \"OSImageApiLiveTest\")\npublic class OSImageApiLiveTest extends BaseAzureComputeApiLiveTest {\n\n   @Test\n   public void testPublisher() {\n      List<Publisher> publishers = api().listPublishers();\n      assertTrue(publishers.size() > 0);\n   }\n\n   @Test\n   public void testList() {\n      List<Offer> offerList = api().listOffers(\"MicrosoftWindowsServer\");\n      assertTrue(offerList.size() > 0);\n\n      List<SKU> skuList = api().listSKUs(\"MicrosoftWindowsServer\", offerList.get(0).name());\n      assertTrue(skuList.size() > 0);\n\n      List<Version> versionList = api().listVersions(\"MicrosoftWindowsServer\", offerList.get(0).name(), skuList.get(0).name());\n\n      assertTrue(versionList.size() > 0);\n   }\n\n   @Test\n   public void testListCanonicalUbuntu() {\n      Iterable<Offer> offerList = api().listOffers(\"canonical\");\n      int total = 0;\n\n      for (Offer offer : offerList) {\n         Iterable<SKU> skuList = api().listSKUs(\"canonical\", offer.name());\n         for (SKU sku : skuList) {\n            List<Version> versionList = api().listVersions(\"canonical\", offer.name(), sku.name());\n            total += versionList.size();\n         }\n      }\n      assertTrue(total > 0);\n   }\n\n   private OSImageApi api() {\n      return api.getOSImageApi(\"eastus\");\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/OSImageApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport static com.google.common.collect.Iterables.isEmpty;\nimport static com.google.common.collect.Iterables.size;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.List;\n\nimport org.jclouds.azurecompute.arm.domain.Offer;\nimport org.jclouds.azurecompute.arm.domain.Publisher;\nimport org.jclouds.azurecompute.arm.domain.SKU;\nimport org.jclouds.azurecompute.arm.domain.Version;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiMockTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"OSImageApiMockTest\", singleThreaded = true)\npublic class OSImageApiMockTest extends BaseAzureComputeApiMockTest {\n\n   private final String subscriptionid = \"SUBSCRIPTIONID\";\n   private final String apiversion = \"?api-version=2015-06-15\";\n   private final String location = \"eastus\";\n   private final String publisher = \"MicrosoftWindowsServer\";\n   private final String offer = \"WindowsServer\";\n   private final String sku = \"2008-R2-SP1\";\n\n   final String requestUrl = \"/subscriptions/\" + subscriptionid + \"/providers/Microsoft.Compute/locations/\" + location + \"/publishers\";\n\n   public void testPublishers() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/publishers.json\"));\n\n      List<Publisher> publishers = api.getOSImageApi(location).listPublishers();\n\n      assertEquals(size(publishers), 2);\n\n      assertSent(server, \"GET\", requestUrl + apiversion);\n   }\n   public void testPublishersEmtpy() throws InterruptedException {\n      server.enqueue(response404());\n\n      List<Publisher> publishers = api.getOSImageApi(location).listPublishers();\n\n      assertTrue(isEmpty(publishers));\n\n      assertSent(server, \"GET\", requestUrl + apiversion);\n   }\n\n   public void testOffers() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/offers.json\"));\n\n      List<Offer> offers = api.getOSImageApi(location).listOffers(publisher);\n\n      assertEquals(size(offers), 1);\n\n      assertSent(server, \"GET\", requestUrl + \"/\" + publisher + \"/artifacttypes/vmimage/offers\" + apiversion);\n   }\n   public void testOffersEmtpy() throws InterruptedException {\n      server.enqueue(response404());\n\n      List<Offer> offers = api.getOSImageApi(location).listOffers(publisher);\n\n      assertTrue(isEmpty(offers));\n\n      assertSent(server, \"GET\", requestUrl + \"/\" + publisher + \"/artifacttypes/vmimage/offers\" + apiversion);\n   }\n\n   public void testSkus() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/skus.json\"));\n\n      List<SKU> skus = api.getOSImageApi(location).listSKUs(publisher, offer);\n\n      assertEquals(size(skus), 2);\n\n      assertSent(server, \"GET\", requestUrl + \"/\" + publisher + \"/artifacttypes/vmimage/offers/\" + offer + \"/skus\" + apiversion);\n   }\n\n   public void testSkusEmtpy() throws InterruptedException {\n      server.enqueue(response404());\n\n      List<SKU> skus = api.getOSImageApi(location).listSKUs(publisher, offer);\n\n      assertTrue(isEmpty(skus));\n\n      assertSent(server, \"GET\", requestUrl + \"/\" + publisher + \"/artifacttypes/vmimage/offers/\" + offer + \"/skus\" + apiversion);\n   }\n\n   public void testVersions() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/versions.json\"));\n\n      List<Version> versions = api.getOSImageApi(location).listVersions(publisher, offer, sku);\n\n      assertEquals(size(versions), 2);\n\n      assertSent(server, \"GET\", requestUrl + \"/\" + publisher + \"/artifacttypes/vmimage/offers/\" + offer + \"/skus/\" + sku + \"/versions\" + apiversion);\n   }\n   public void testVersionsEmtpy() throws InterruptedException {\n      server.enqueue(response404());\n\n      List<Version> versions = api.getOSImageApi(location).listVersions(publisher, offer, sku);\n\n      assertTrue(isEmpty(versions));\n\n      assertSent(server, \"GET\", requestUrl + \"/\" + publisher + \"/artifacttypes/vmimage/offers/\" + offer + \"/skus/\" + sku + \"/versions\" + apiversion);\n   }\n\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/PublicIPAddressApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport static org.jclouds.azurecompute.arm.domain.publicipaddress.PublicIPAddress.SKU.SKUName.Basic;\nimport static org.jclouds.azurecompute.arm.domain.publicipaddress.PublicIPAddress.SKU.SKUName.Standard;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.azurecompute.arm.domain.publicipaddress.PublicIPAddress;\nimport org.jclouds.azurecompute.arm.domain.publicipaddress.PublicIPAddress.SKU;\nimport org.jclouds.azurecompute.arm.domain.publicipaddress.PublicIPAddressProperties;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiLiveTest;\nimport org.jclouds.util.Predicates2;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableMap;\n\n@Test(groups = \"live\", singleThreaded = true)\npublic class PublicIPAddressApiLiveTest extends BaseAzureComputeApiLiveTest {\n\n   private final String publicIpAddressName = \"myipaddress\";\n   private final String publicIpAddressNameStandard = \"myipaddressStandard\";\n   private String subscriptionid;\n\n   @BeforeClass\n   @Override\n   public void setup() {\n      super.setup();\n      createTestResourceGroup();\n      subscriptionid = getSubscriptionId();\n   }\n\n   @Test(groups = \"live\")\n   public void deletePublicIPAddressResourceDoesNotExist() {\n      final PublicIPAddressApi ipApi = api.getPublicIPAddressApi(resourceGroupName);\n      boolean status = ipApi.delete(publicIpAddressName);\n      assertFalse(status);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"deletePublicIPAddressResourceDoesNotExist\")\n   public void createPublicIPAddress() {\n\n      final PublicIPAddressApi ipApi = api.getPublicIPAddressApi(resourceGroupName);\n\n      final Map<String, String> tags = ImmutableMap.of(\"testkey\", \"testvalue\");\n\n      PublicIPAddressProperties properties =\n              PublicIPAddressProperties.builder()\n                  .publicIPAllocationMethod(\"Static\")\n                  .idleTimeoutInMinutes(4)\n                  .build();\n\n      PublicIPAddress ip = ipApi.createOrUpdate(publicIpAddressName, LOCATION, tags, null, properties);\n\n      assertNotNull(ip);\n      assertEquals(ip.name(), publicIpAddressName);\n      assertEquals(ip.location(), LOCATION);\n      assertEquals(ip.id(), String.format(\"/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/publicIPAddresses/%s\", subscriptionid, resourceGroupName, publicIpAddressName));\n      assertEquals(ip.tags().get(\"testkey\"), \"testvalue\");\n      assertNotNull(ip.properties());\n      assertEquals(ip.properties().provisioningState(), \"Updating\");\n      assertNull(ip.properties().ipAddress()); // as we don't get IP address until Succeeded state\n      assertEquals(ip.properties().publicIPAllocationMethod(), \"Static\");\n      assertEquals(ip.properties().idleTimeoutInMinutes().intValue(), 4);\n      assertEquals(ip.sku().name(), Basic);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"deletePublicIPAddressResourceDoesNotExist\")\n   public void createPublicIPAddressStandard() {\n      final PublicIPAddressApi ipApi = api.getPublicIPAddressApi(resourceGroupName);\n\n      final Map<String, String> tags = ImmutableMap.of(\"testkey\", \"testvalue\");\n\n      PublicIPAddressProperties properties = PublicIPAddressProperties.builder().publicIPAllocationMethod(\"Static\")\n            .idleTimeoutInMinutes(4).build();\n\n      PublicIPAddress ip = ipApi\n            .createOrUpdate(publicIpAddressNameStandard, LOCATION, tags, SKU.create(Standard), properties);\n\n      assertNotNull(ip);\n      assertEquals(ip.name(), publicIpAddressNameStandard);\n      assertEquals(ip.location(), LOCATION);\n      assertEquals(ip.id(),\n            String.format(\"/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/publicIPAddresses/%s\",\n                  subscriptionid, resourceGroupName, publicIpAddressNameStandard));\n      assertEquals(ip.tags().get(\"testkey\"), \"testvalue\");\n      assertNotNull(ip.properties());\n      assertEquals(ip.properties().provisioningState(), \"Updating\");\n      assertNull(ip.properties().ipAddress()); // as we don't get IP address until Succeeded state\n      assertEquals(ip.properties().publicIPAllocationMethod(), \"Static\");\n      assertEquals(ip.properties().idleTimeoutInMinutes().intValue(), 4);\n      assertEquals(ip.sku().name(), Standard);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"createPublicIPAddress\")\n   public void getPublicIPAddress() {\n\n      final PublicIPAddressApi ipApi = api.getPublicIPAddressApi(resourceGroupName);\n\n      //Poll until resource is ready to be used\n      boolean jobDone = Predicates2.retry(new Predicate<String>() {\n         @Override public boolean apply(String name) {\n            return ipApi.get(name).properties().provisioningState().equals(\"Succeeded\");\n         }\n      }, 10 * 1000).apply(publicIpAddressName);\n      assertTrue(jobDone, \"get operation did not complete in the configured timeout\");\n\n      PublicIPAddress ip = ipApi.get(publicIpAddressName);\n      assertNotNull(ip);\n      assertEquals(ip.name(), publicIpAddressName);\n      assertEquals(ip.location(), LOCATION);\n      assertEquals(ip.id(), String.format(\"/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Network/publicIPAddresses/%s\", subscriptionid, resourceGroupName, publicIpAddressName));\n      assertEquals(ip.tags().get(\"testkey\"), \"testvalue\");\n      assertNotNull(ip.properties());\n      assertEquals(ip.properties().provisioningState(), \"Succeeded\");\n      assertNotNull(ip.properties().ipAddress()); // by this time we should have IP address already\n      assertEquals(ip.properties().publicIPAllocationMethod(), \"Static\");\n      assertEquals(ip.properties().idleTimeoutInMinutes().intValue(), 4);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"createPublicIPAddress\")\n   public void listPublicIPAddresses() {\n\n      final PublicIPAddressApi ipApi = api.getPublicIPAddressApi(resourceGroupName);\n\n      List<PublicIPAddress> ipList = ipApi.list();\n\n      assertTrue(ipList.size() > 0);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"createPublicIPAddress\")\n   public void listAllPublicIPAddressesInSubscription() {\n\n      final PublicIPAddressApi ipApi = api.getPublicIPAddressApi(null);\n\n      List<PublicIPAddress> ipList = ipApi.listAllInSubscription();\n\n      assertTrue(ipList.size() > 0);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = { \"listPublicIPAddresses\", \"listAllPublicIPAddressesInSubscription\",\n         \"getPublicIPAddress\" }, alwaysRun = true)\n   public void deletePublicIPAddress() {\n      final PublicIPAddressApi ipApi = api.getPublicIPAddressApi(resourceGroupName);\n      boolean status = ipApi.delete(publicIpAddressName);\n      assertTrue(status);\n   }\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/PublicIPAddressApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport static org.jclouds.azurecompute.arm.config.AzureComputeProperties.API_VERSION_PREFIX;\nimport static org.jclouds.azurecompute.arm.domain.publicipaddress.PublicIPAddress.SKU.SKUName.Basic;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport okhttp3.mockwebserver.MockResponse;\n\nimport org.jclouds.azurecompute.arm.AzureComputeProviderMetadata;\nimport org.jclouds.azurecompute.arm.domain.DnsSettings;\nimport org.jclouds.azurecompute.arm.domain.publicipaddress.PublicIPAddress;\nimport org.jclouds.azurecompute.arm.domain.publicipaddress.PublicIPAddress.SKU;\nimport org.jclouds.azurecompute.arm.domain.publicipaddress.PublicIPAddressProperties;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiMockTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\n\n\n@Test(groups = \"unit\", testName = \"PublicIPAddressApiMockTest\", singleThreaded = true)\npublic class PublicIPAddressApiMockTest extends BaseAzureComputeApiMockTest {\n\n   private final String subscriptionid = \"SUBSCRIPTIONID\";\n   private final String resourcegroup = \"myresourcegroup\";\n   private final String apiVersion = \"api-version=\" + AzureComputeProviderMetadata.defaultProperties()\n         .getProperty(API_VERSION_PREFIX + LoadBalancerApi.class.getSimpleName());\n   private final String location = \"northeurope\";\n   private final String publicIpName = \"mypublicaddress\";\n\n   public void getPublicIPAddressInfo() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/PublicIPAddressGetInfo.json\"));\n\n      final PublicIPAddressApi ipApi = api.getPublicIPAddressApi(resourcegroup);\n      PublicIPAddress ip = ipApi.get(publicIpName);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/publicIPAddresses/%s?%s\", subscriptionid, resourcegroup, publicIpName, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertNotNull(ip);\n      assertEquals(ip.name(), \"mypublicaddress\");\n      assertEquals(ip.location(), \"northeurope\");\n      assertEquals(ip.id(), \"/subscriptions/fakeb2f5-4710-4e93-bdf4-419edbde2178/resourceGroups/myresourcegroup/providers/Microsoft.Network/publicIPAddresses/mypublicaddress\");\n      assertEquals(ip.tags().get(\"testkey\"), \"testvalue\");\n      assertNotNull(ip.properties());\n      assertEquals(ip.properties().provisioningState(), \"Succeeded\");\n      assertEquals(ip.properties().ipAddress(), \"12.123.12.123\");\n      assertEquals(ip.properties().publicIPAllocationMethod(), \"Static\");\n      assertEquals(ip.properties().idleTimeoutInMinutes().intValue(), 4);\n      assertNotNull(ip.properties().dnsSettings());\n      assertEquals(ip.properties().dnsSettings().domainNameLabel(), \"foobar\");\n      assertEquals(ip.properties().dnsSettings().fqdn(), \"foobar.northeurope.cloudapp.azure.com\");\n      assertNotNull(ip.properties().ipConfiguration());\n      assertEquals(ip.properties().ipConfiguration().id(), \"/subscriptions/fakeb2f5-4710-4e93-bdf4-419edbde2178/resourceGroups/myresourcegroup/providers/Microsoft.Network/networkInterfaces/myNic/ipConfigurations/myip1\");\n      assertEquals(ip.sku().name(), Basic);\n   }\n\n   public void getPublicIPAddressInfoEmpty() throws Exception {\n      server.enqueue(new MockResponse().setResponseCode(404));\n\n      final PublicIPAddressApi ipApi = api.getPublicIPAddressApi(resourcegroup);\n      PublicIPAddress ip = ipApi.get(publicIpName);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/publicIPAddresses/%s?%s\", subscriptionid, resourcegroup, publicIpName, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertNull(ip);\n   }\n\n   public void listPublicIPAddresses() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/PublicIPAddressList.json\"));\n\n      final PublicIPAddressApi ipApi = api.getPublicIPAddressApi(resourcegroup);\n      List<PublicIPAddress> ipList = ipApi.list();\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/publicIPAddresses?%s\", subscriptionid, resourcegroup, apiVersion);\n      assertSent(server, \"GET\", path);\n      assertEquals(ipList.size(), 4);\n   }\n\n   public void listPublicIPAddressesEmpty() throws InterruptedException {\n      server.enqueue(new MockResponse().setResponseCode(404));\n\n      final PublicIPAddressApi ipApi = api.getPublicIPAddressApi(resourcegroup);\n      List<PublicIPAddress> ipList = ipApi.list();\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/publicIPAddresses?%s\", subscriptionid, resourcegroup, apiVersion);\n      assertSent(server, \"GET\", path);\n      assertEquals(ipList.size(), 0);\n   }\n\n   public void listAllPublicIPAddressesInSubscription() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/PublicIPAddressListAll.json\"));\n\n      final PublicIPAddressApi ipApi = api.getPublicIPAddressApi(null);\n      List<PublicIPAddress> ipList = ipApi.listAllInSubscription();\n\n      String path = String\n            .format(\"/subscriptions/%s/providers/Microsoft.Network/publicIPAddresses?%s\", subscriptionid, apiVersion);\n      assertSent(server, \"GET\", path);\n      assertEquals(ipList.size(), 5);\n   }\n\n   public void listAllPublicIPAddressesInSubscriptionEmpty() throws InterruptedException {\n      server.enqueue(new MockResponse().setResponseCode(404));\n\n      final PublicIPAddressApi ipApi = api.getPublicIPAddressApi(null);\n      List<PublicIPAddress> ipList = ipApi.listAllInSubscription();\n\n      String path = String\n            .format(\"/subscriptions/%s/providers/Microsoft.Network/publicIPAddresses?%s\", subscriptionid, apiVersion);\n      assertSent(server, \"GET\", path);\n      assertEquals(ipList.size(), 0);\n   }\n\n   public void createPublicIPAddress() throws InterruptedException {\n\n      server.enqueue(jsonResponse(\"/PublicIPAddressCreate.json\").setStatus(\"HTTP/1.1 201 Created\"));\n\n      final PublicIPAddressApi ipApi = api.getPublicIPAddressApi(resourcegroup);\n\n      final Map<String, String> tags = ImmutableMap.of(\"testkey\", \"testvalue\");\n\n      PublicIPAddressProperties properties = PublicIPAddressProperties.create(null, null, \"Static\", 4, null,\n              DnsSettings.create(\"foobar\", \"foobar.northeurope.cloudapp.azure.com\", null));\n\n      PublicIPAddress ip = ipApi.createOrUpdate(publicIpName, location, tags, SKU.create(Basic), properties);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/publicIPAddresses/%s?%s\", subscriptionid, resourcegroup, publicIpName, apiVersion);\n      String json = String.format(\"{ \\\"location\\\": \\\"%s\\\", \\\"tags\\\": { \\\"testkey\\\": \\\"testvalue\\\" }, \\\"properties\\\": \"\n            + \"{ \\\"publicIPAllocationMethod\\\": \\\"Static\\\", \\\"idleTimeoutInMinutes\\\": 4, \\\"dnsSettings\\\": { \"\n            + \"\\\"domainNameLabel\\\": \\\"foobar\\\", \\\"fqdn\\\": \\\"foobar.northeurope.cloudapp.azure.com\\\" } }, \\\"sku\\\": {\\\"name\\\": \\\"Basic\\\" } }\", location);\n      assertSent(server, \"PUT\", path, json);\n\n      assertNotNull(ip);\n      assertEquals(ip.name(), \"mypublicaddress\");\n      assertEquals(ip.location(), \"northeurope\");\n      assertEquals(ip.id(), \"/subscriptions/fakeb2f5-4710-4e93-bdf4-419edbde2178/resourceGroups/myresourcegroup/providers/Microsoft.Network/publicIPAddresses/mypublicaddress\");\n      assertEquals(ip.tags().get(\"testkey\"), \"testvalue\");\n      assertNotNull(ip.properties());\n      assertEquals(ip.properties().provisioningState(), \"Updating\");\n      assertNull(ip.properties().ipAddress()); // as we don't get IP address until Succeeded state\n      assertEquals(ip.properties().publicIPAllocationMethod(), \"Static\");\n      assertEquals(ip.properties().idleTimeoutInMinutes().intValue(), 4);\n      assertNotNull(ip.properties().dnsSettings());\n      assertEquals(ip.properties().dnsSettings().domainNameLabel(), \"foobar\");\n      assertEquals(ip.properties().dnsSettings().fqdn(), \"foobar.northeurope.cloudapp.azure.com\");\n      assertEquals(ip.sku().name(), Basic);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void createPublicIPAddressDnsRecordInUse() throws IllegalArgumentException, InterruptedException {\n\n      server.enqueue(jsonResponse(\"/PublicIPAddressCreateDnsRecordInUse.json\").setStatus(\"HTTP/1.1 400 Bad Request\"));\n\n      final PublicIPAddressApi ipApi = api.getPublicIPAddressApi(resourcegroup);\n\n      final Map<String, String> tags = ImmutableMap.of(\"testkey\", \"testvalue\");\n\n      PublicIPAddressProperties properties = PublicIPAddressProperties.create(null, null, \"Static\", 4, null,\n              DnsSettings.create(\"foobar\", \"foobar.northeurope.cloudapp.azure.com\", null));\n\n      ipApi.createOrUpdate(publicIpName, location, tags, null, properties);\n   }\n\n   public void deletePublicIPAddress() throws InterruptedException {\n\n      server.enqueue(response202());\n\n      final PublicIPAddressApi ipApi = api.getPublicIPAddressApi(resourcegroup);\n      boolean status = ipApi.delete(publicIpName);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/publicIPAddresses/%s?%s\", subscriptionid, resourcegroup, publicIpName, apiVersion);\n      assertSent(server, \"DELETE\", path);\n\n      assertTrue(status);\n   }\n\n   public void deletePublicIPAddressResourceDoesNotExist() throws InterruptedException {\n\n      server.enqueue(response204());\n\n      final PublicIPAddressApi ipApi = api.getPublicIPAddressApi(resourcegroup);\n      boolean status = ipApi.delete(publicIpName);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/publicIPAddresses/%s?%s\", subscriptionid, resourcegroup, publicIpName, apiVersion);\n      assertSent(server, \"DELETE\", path);\n\n      assertFalse(status);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/ResourceGroupApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport org.jclouds.azurecompute.arm.domain.Resource;\nimport org.jclouds.azurecompute.arm.domain.ResourceGroup;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiLiveTest;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\n@Test(groups = \"live\", testName = \"ResourceGroupApiLiveTest\")\npublic class ResourceGroupApiLiveTest extends BaseAzureComputeApiLiveTest {\n\n   private static final String RESOURCE_GROUP_NAME = \"jcloudstest\";\n\n   private ResourceGroupApi api() {\n      return api.getResourceGroupApi();\n   }\n\n   @Test(dependsOnMethods = \"testCreate\")\n   public void testResources() {\n      List<Resource> resources = api().resources(RESOURCE_GROUP_NAME);\n      assertTrue(resources.isEmpty());\n      for (Resource resource : resources) {\n         assertNotNull(resource);\n      }\n   }\n   \n   @Test(dependsOnMethods = \"testCreate\")\n   public void testList() {\n      final List<ResourceGroup> resourceGroups = api().list();\n\n      assertTrue(resourceGroups.size() > 0);\n\n      assertTrue(Iterables.any(resourceGroups, new Predicate<ResourceGroup>() {\n\n         @Override\n         public boolean apply(final ResourceGroup group) {\n            return RESOURCE_GROUP_NAME.equals(group.name());\n         }\n      }));\n   }\n\n   @Test(dependsOnMethods = \"testCreate\")\n   public void testRead() {\n      final ResourceGroup resourceGroup = api().get(RESOURCE_GROUP_NAME);\n      assertNotNull(resourceGroup);\n      assertEquals(resourceGroup.name(), RESOURCE_GROUP_NAME);\n      assertEquals(resourceGroup.location(), LOCATION);\n   }\n\n   public void testCreate() {\n      final ResourceGroup resourceGroup = api().create(RESOURCE_GROUP_NAME, LOCATION, null);\n      assertEquals(resourceGroup.name(), RESOURCE_GROUP_NAME);\n      assertEquals(resourceGroup.location(), LOCATION);\n      assertNull(resourceGroup.tags());\n      assertTrue(resourceGroup.id().contains(RESOURCE_GROUP_NAME));\n      assertEquals(resourceGroup.properties().provisioningState(), \"Succeeded\");\n   }\n\n   @Test(dependsOnMethods = \"testCreate\")\n   public void testUpdateWithEmptyTag() {\n      ImmutableMap<String, String> tags = ImmutableMap.<String, String>builder().build();\n\n      final ResourceGroup resourceGroup = api().update(RESOURCE_GROUP_NAME, tags);\n\n      assertEquals(resourceGroup.tags().size(), 0);\n      assertEquals(resourceGroup.properties().provisioningState(), \"Succeeded\");\n   }\n\n   @Test(dependsOnMethods = \"testCreate\")\n   public void testUpdateWithTag() {\n      ImmutableMap<String, String> tags = ImmutableMap.<String, String>builder().put(\"test1\", \"value1\").build();\n\n      final ResourceGroup resourceGroup = api().update(RESOURCE_GROUP_NAME, tags);\n\n      assertEquals(resourceGroup.tags().size(), 1);\n      assertEquals(resourceGroup.properties().provisioningState(), \"Succeeded\");\n   }\n\n   @AfterClass(alwaysRun = true)\n   public void testDelete() throws Exception {\n      URI uri =  api().delete(RESOURCE_GROUP_NAME);\n      assertResourceDeleted(uri);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/ResourceGroupApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport org.jclouds.azurecompute.arm.domain.Resource;\nimport org.jclouds.azurecompute.arm.domain.ResourceGroup;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiMockTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\n\nimport static com.google.common.collect.Iterables.isEmpty;\nimport static com.google.common.collect.Iterables.size;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\n@Test(groups = \"unit\", testName = \"ResourceGroupApiMockTest\", singleThreaded = true)\npublic class ResourceGroupApiMockTest extends BaseAzureComputeApiMockTest {\n\n   final String subscriptionid = \"SUBSCRIPTIONID\";\n   final String requestUrl = \"/subscriptions/\" + subscriptionid + \"/resourcegroups\";\n   final String version = \"?api-version=2015-01-01\";\n\n   public void testListResourceGroups() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/resourcegroups.json\"));\n\n      List<ResourceGroup> resourceGroups = api.getResourceGroupApi().list();\n\n      assertEquals(size(resourceGroups), 2);\n\n      assertSent(server, \"GET\", requestUrl + version);\n   }\n\n   public void testListResourceGroupsReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      List<ResourceGroup> resourceGroups = api.getResourceGroupApi().list();\n\n      assertTrue(isEmpty(resourceGroups));\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", requestUrl + version);\n   }\n\n   public void testCreateResourceGroup() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/resourcegroup.json\").setStatus(\"HTTP/1.1 201 Created\"));\n\n      ImmutableMap<String, String> tags = ImmutableMap.<String, String>builder().put(\"tagname1\", \"tagvalue1\").build();\n\n      ResourceGroup resourceGroup = api.getResourceGroupApi().create(\"jcloudstest\", \"West US\", tags);\n\n      assertEquals(resourceGroup.name(), \"jcloudstest\");\n      assertEquals(resourceGroup.location(), \"westus\");\n      assertEquals(resourceGroup.tags().size(), 1);\n      assertTrue(resourceGroup.id().contains(\"jcloudstest\"));\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"PUT\", requestUrl + \"/jcloudstest\" + version, String.format(\"{\\\"location\\\":\\\"%s\\\", \\\"tags\\\":{\\\"tagname1\\\":\\\"tagvalue1\\\"}}\", \"West US\"));\n   }\n\n   public void testCreateResourceGroupWithNoTag() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/resourcegroup.json\").setStatus(\"HTTP/1.1 201 Created\"));\n\n      ResourceGroup resourceGroup = api.getResourceGroupApi().create(\"jcloudstest\", \"West US\", null);\n\n      assertEquals(resourceGroup.name(), \"jcloudstest\");\n      assertEquals(resourceGroup.location(), \"westus\");\n      assertTrue(resourceGroup.id().contains(\"jcloudstest\"));\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"PUT\", requestUrl + \"/jcloudstest\" + version, String.format(\"{\\\"location\\\":\\\"%s\\\"}\", \"West US\"));\n   }\n\n   public void testGetResourceGroup() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/resourcegroup.json\"));\n\n      ResourceGroup resourceGroup = api.getResourceGroupApi().get(\"jcloudstest\");\n\n      assertEquals(resourceGroup.name(), \"jcloudstest\");\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", requestUrl + \"/jcloudstest\" + version);\n   }\n\n   public void testGetResourceGroupReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      ResourceGroup resourceGroup = api.getResourceGroupApi().get(\"jcloudstest\");\n\n      assertNull(resourceGroup);\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", requestUrl + \"/jcloudstest\" + version);\n   }\n\n   public void testUpdateResourceGroupTags() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/resourcegroupupdated.json\"));\n\n      ImmutableMap<String, String> tags = ImmutableMap.<String, String>builder().build();\n\n      ResourceGroup resourceGroup = api.getResourceGroupApi().update(\"jcloudstest\", tags);\n\n\n      assertEquals(resourceGroup.tags().size(), 0);\n      assertEquals(resourceGroup.properties().provisioningState(), \"Succeeded\");\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"PATCH\", requestUrl + \"/jcloudstest\" + version, \"{\\\"tags\\\":{}}\");\n   }\n\n   public void testDeleteResourceGroup() throws InterruptedException {\n      server.enqueue(response202WithHeader());\n\n      URI uri = api.getResourceGroupApi().delete(\"jcloudstest\");\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"DELETE\", requestUrl + \"/jcloudstest\" + version);\n      assertNotNull(uri);\n\n      assertTrue(uri.toString().contains(\"api-version\"));\n      assertTrue(uri.toString().contains(\"operationresults\"));\n   }\n\n   public void testDeleteResourceGroupReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      URI uri = api.getResourceGroupApi().delete(\"jcloudstest\");\n      assertNull(uri);\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"DELETE\", requestUrl + \"/jcloudstest\" + version);\n   }\n\n   public void testListResourceGroupResources() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/resourcegroup-resources.json\"));\n\n      List<Resource> resources = api.getResourceGroupApi().resources(\"jcloudstest\");\n\n      assertEquals(size(resources), 6);\n\n      assertSent(server, \"GET\", requestUrl + \"/jcloudstest/resources\" + version);\n   }\n\n   public void testListResourceGroupResourcesReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      List<Resource> resources = api.getResourceGroupApi().resources(\"jcloudstest\");\n\n      assertTrue(isEmpty(resources));\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", requestUrl + \"/jcloudstest/resources\" + version);\n   }\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/ResourceProviderAPIMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport org.jclouds.azurecompute.arm.domain.ResourceProviderMetaData;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiMockTest;\nimport org.testng.annotations.Test;\n\nimport java.util.List;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\n@Test(groups = \"unit\", testName = \"NetworkInterfaceCardApiMockTest\", singleThreaded = true)\npublic class ResourceProviderAPIMockTest extends BaseAzureComputeApiMockTest {\n\n   final String apiVersion = \"2015-01-01\";\n   final String resource = \"Microsoft.Compute\";\n\n   public void getPublicIPAddressInfo() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/getresourceprovidermetadata.json\"));\n\n      final ResourceProviderApi resourceProviderApi = api.getResourceProviderApi();\n\n      List<ResourceProviderMetaData> metaDatas = resourceProviderApi.get(resource);\n\n      String path = String.format(\"/subscriptions/SUBSCRIPTIONID/providers/%s?api-version=%s\", resource, apiVersion);\n\n      assertSent(server, \"GET\", path);\n      assertTrue(metaDatas.size() > 0);\n      ResourceProviderMetaData md = metaDatas.get(0);\n\n      assertEquals(md.resourceType(), \"availabilitySets\");\n      assertEquals(md.locations().get(0), \"East US\");\n      assertEquals(md.apiVersions().get(0), \"2016-03-30\");\n   }\n\n   public void getPublicIPAddressInfoEmpty() throws InterruptedException {\n      server.enqueue(response404());\n\n      final ResourceProviderApi resourceProviderApi = api.getResourceProviderApi();\n\n      List<ResourceProviderMetaData> metaDatas = resourceProviderApi.get(resource);\n\n      String path = String.format(\"/subscriptions/SUBSCRIPTIONID/providers/%s?api-version=%s\", resource, apiVersion);\n\n      assertSent(server, \"GET\", path);\n      assertNull(metaDatas);\n   }\n}\n\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/ResourceProviderApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport java.util.List;\n\nimport org.jclouds.azurecompute.arm.domain.ResourceProviderMetaData;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Iterables;\n\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\n@Test(groups = \"live\", testName = \"ResourceProviderApiLiveTest\")\npublic class ResourceProviderApiLiveTest extends BaseAzureComputeApiLiveTest {\n\n   private final String PROVIDER = \"Microsoft.Compute\";\n   private final String VM_RESOURCE_TYPE = \"virtualMachines\";\n\n   private ResourceProviderApi api() {\n      return api.getResourceProviderApi();\n   }\n\n   @Test\n   public void testGetComputeProviderMetadata() {\n\n      List<ResourceProviderMetaData> resourceProviderMetaDatas = api().get(PROVIDER);\n\n      assertNotNull(resourceProviderMetaDatas);\n\n      assertTrue(Iterables.any(resourceProviderMetaDatas, new Predicate<ResourceProviderMetaData>() {\n         @Override\n         public boolean apply(final ResourceProviderMetaData providerMetaData) {\n            return providerMetaData.resourceType().equals(VM_RESOURCE_TYPE);\n         }\n      }));\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/StorageAccountApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport org.jclouds.azurecompute.arm.domain.StorageService;\nimport org.jclouds.azurecompute.arm.domain.StorageServiceKeys;\nimport org.jclouds.azurecompute.arm.domain.StorageServiceUpdateParams;\nimport org.jclouds.azurecompute.arm.functions.ParseJobStatus;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiLiveTest;\nimport org.jclouds.util.Predicates2;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableMap;\n\n@Test(groups = \"live\", testName = \"StorageAccountApiLiveTest\")\npublic class StorageAccountApiLiveTest extends BaseAzureComputeApiLiveTest {\n\n   private static final String NAME = String.format(\"%3.24s\",\n           RAND + StorageAccountApiLiveTest.class.getSimpleName().toLowerCase());\n\n   @BeforeClass\n   @Override\n   public void setup() {\n      super.setup();\n      createTestResourceGroup();\n   }\n\n   @Test(dependsOnMethods = \"testCreate\")\n   public void testList() {\n      List<StorageService> storages = api().list();\n      assertTrue(storages.size() > 0);\n      for (StorageService storage : storages) {\n         check(storage);\n      }\n   }\n\n   @Test()\n   public void testIsAvailable() {\n      assertTrue(api().isAvailable(NAME).nameAvailable().equals(\"true\"));\n   }\n\n   @Test(dependsOnMethods = \"testIsAvailable\")\n   public void testCreate() {\n      URI uri = api().create(NAME, LOCATION, ImmutableMap.of(\"property_name\",\n              \"property_value\"), ImmutableMap.of(\"accountType\", StorageService.AccountType.Standard_LRS.toString()));\n      if (uri != null){\n         assertTrue(uri.toString().contains(\"api-version\"));\n\n         boolean jobDone = Predicates2.retry(new Predicate<URI>() {\n            @Override public boolean apply(URI uri) {\n               return ParseJobStatus.JobStatus.DONE == api.getJobApi().jobStatus(uri);\n            }\n         }, 60 * 1 * 1000 /* 1 minute timeout */).apply(uri);\n         assertTrue(jobDone, \"create operation did not complete in the configured timeout\");\n      }\n      final StorageService service = api().get(NAME);\n      assertNotNull(service);\n      assertEquals(service.location(), LOCATION);\n      assertNotNull(service.storageServiceProperties().creationTime());\n   }\n\n   @Test(dependsOnMethods = \"testCreate\")\n   public void testGet() {\n      final StorageService service = api().get(NAME);\n      assertNotNull(service);\n      assertEquals(service.name(), NAME);\n      assertEquals(service.storageServiceProperties().primaryLocation(), LOCATION);\n      assertEquals(service.storageServiceProperties().accountType(), StorageService.AccountType.Standard_LRS);\n   }\n\n   @Test(dependsOnMethods = \"testCreate\")\n   public void testGetKeys() {\n      final StorageServiceKeys keys = api().getKeys(NAME);\n      assertNotNull(keys);\n      assertNotNull(keys.key1());\n      assertNotNull(keys.key2());\n   }\n\n   @Test(dependsOnMethods = \"testCreate\")\n   public void testRegenerateKeys() {\n      StorageServiceKeys keys = api().regenerateKeys(NAME, \"key1\");\n      assertFalse(keys.key1().isEmpty());\n      assertFalse(keys.key2().isEmpty());\n   }\n\n   @Test(dependsOnMethods = \"testCreate\")\n   public void testUpdateTags() {\n      StorageServiceUpdateParams.StorageServiceUpdateProperties props =\n              StorageServiceUpdateParams.StorageServiceUpdateProperties.create(null);\n      final StorageServiceUpdateParams params = api().update(NAME,\n              ImmutableMap.of(\"another_property_name\", \"another_property_value\"), props);\n      assertTrue(params.tags().containsKey(\"another_property_name\"));\n      assertNull(params.storageServiceProperties().accountType());\n   }\n\n   @Test(dependsOnMethods = {\"testCreate\", \"testGet\"})\n   public void testUpdateAccountType() {\n      StorageServiceUpdateParams.StorageServiceUpdateProperties props =\n              StorageServiceUpdateParams.StorageServiceUpdateProperties.create(StorageService.AccountType.Standard_GRS);\n      final StorageServiceUpdateParams params = api().update(NAME,\n              null, props);\n      assertNull(params.tags());\n      assertEquals(params.storageServiceProperties().accountType(), StorageService.AccountType.Standard_GRS);\n   }\n\n   private void check(final StorageService storage) {\n      assertNotNull(storage.id());\n      assertNotNull(storage.name());\n      assertNotNull(storage.storageServiceProperties());\n      assertNotNull(storage.storageServiceProperties().accountType());\n      assertFalse(storage.storageServiceProperties().primaryEndpoints().isEmpty());\n      assertNotNull(storage.storageServiceProperties().creationTime());\n   }\n\n   private StorageAccountApi api() {\n      return api.getStorageAccountApi(resourceGroupName);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/StorageAccountApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\n\nimport okhttp3.mockwebserver.MockResponse;\n\nimport org.jclouds.azurecompute.arm.domain.StorageService;\nimport org.jclouds.azurecompute.arm.domain.Availability;\nimport org.jclouds.azurecompute.arm.domain.StorageServiceKeys;\nimport org.jclouds.azurecompute.arm.domain.StorageServiceUpdateParams;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiMockTest;\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.testng.annotations.Test;\n\nimport java.net.MalformedURLException;\nimport java.net.URI;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport static com.google.common.collect.Iterables.isEmpty;\n\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertFalse;\n\n\n@Test(groups = \"unit\", testName = \"StorageAccountApiMockTest\", singleThreaded = true)\npublic class StorageAccountApiMockTest extends BaseAzureComputeApiMockTest {\n\n   private String subsriptionId = \"SUBSCRIPTIONID\";\n   private String resourceGroup = \"resourceGroup\";\n\n   public void testList() throws Exception {\n      server.enqueue(jsonResponse(\"/storageAccounts.json\"));\n\n      final StorageAccountApi storageAPI = api.getStorageAccountApi(resourceGroup);\n\n      List<StorageService> list = storageAPI.list();\n      assertEquals(list, expected());\n\n      assertSent(server, \"GET\", \"/subscriptions/\" + subsriptionId +\n              \"/resourcegroups/resourceGroup/providers/Microsoft.Storage/storageAccounts?api-version=2015-06-15\");\n   }\n\n   public void testListReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      final StorageAccountApi storageAPI = api.getStorageAccountApi(resourceGroup);\n\n      List<StorageService> list = storageAPI.list();\n\n      assertTrue(isEmpty(list));\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/subscriptions/\" + subsriptionId +\n              \"/resourcegroups/resourceGroup/providers/Microsoft.Storage/storageAccounts?api-version=2015-06-15\");\n   }\n\n   public void testCreate() throws Exception {\n      final StorageAccountApi storageAPI = api.getStorageAccountApi(resourceGroup);\n\n      server.enqueue(response202WithHeader());\n\n      URI uri = storageAPI.create(\"name-of-storage-account\", \"westus\",\n              ImmutableMap.of(\"property_name\", \"property_value\"),\n              ImmutableMap.of(\"accountType\", StorageService.AccountType.Premium_LRS.toString()));\n      assertNotNull(uri);\n\n      assertSent(server, \"PUT\", \"/subscriptions/\" + subsriptionId +\n              \"/resourcegroups/resourceGroup/providers/Microsoft.Storage/\" +\n              \"storageAccounts/name-of-storage-account?api-version=2015-06-15\", String.format(\"{\\\"location\\\":\\\"westus\\\",\\\"tags\\\":{\\\"property_name\\\":\\\"property_value\\\"},\\\"properties\\\":{\\\"accountType\\\":\\\"Premium_LRS\\\"}}\"));\n   }\n\n   public void testCreateWithNullTag() throws Exception {\n      final StorageAccountApi storageAPI = api.getStorageAccountApi(resourceGroup);\n\n      server.enqueue(response202WithHeader());\n\n      URI uri = storageAPI.create(\"name-of-storage-account\", \"westus\",\n              null,\n              ImmutableMap.of(\"accountType\", StorageService.AccountType.Premium_LRS.toString()));\n      assertNotNull(uri);\n\n      assertSent(server, \"PUT\", \"/subscriptions/\" + subsriptionId +\n              \"/resourcegroups/resourceGroup/providers/Microsoft.Storage/\" +\n              \"storageAccounts/name-of-storage-account?api-version=2015-06-15\", String.format(\"{\\\"location\\\":\\\"westus\\\",\\\"properties\\\":{\\\"accountType\\\":\\\"Premium_LRS\\\"}}\"));\n   }\n\n   public void testIsAvailable() throws Exception {\n      server.enqueue(jsonResponse(\"/isavailablestorageservice.json\"));\n\n      final StorageAccountApi storageAPI = api.getStorageAccountApi(resourceGroup);\n\n      assertEquals(storageAPI.isAvailable(\"TESTSTORAGE\"),\n              Availability.create(\"true\"));\n\n      assertSent(server, \"POST\", \"/subscriptions/\" + subsriptionId +\n              \"/providers/Microsoft.Storage/checkNameAvailability?api-version=2015-06-15\", String.format(\"{\\\"name\\\":\\\"TESTSTORAGE\\\",\\\"type\\\":\\\"Microsoft.Storage/storageAccounts\\\"}\"));\n   }\n\n   public void testGet() throws Exception {\n      server.enqueue(jsonResponse(\"/storageservices.json\"));\n\n      final StorageAccountApi storageAPI = api.getStorageAccountApi(resourceGroup);\n\n      assertEquals(storageAPI.get(\"TESTSTORAGE\"), expected().get(0));\n\n      assertSent(server, \"GET\", \"/subscriptions/\" + subsriptionId + \"/resourcegroups/\" + resourceGroup +\n              \"/providers/Microsoft.Storage/storageAccounts/TESTSTORAGE?api-version=2015-06-15\");\n   }\n\n   public void testNullGet() throws Exception {\n      server.enqueue(new MockResponse().setResponseCode(404));\n\n      final StorageAccountApi storageAPI = api.getStorageAccountApi(resourceGroup);\n\n      assertNull(storageAPI.get(\"TESTSTORAGE\"));\n\n      assertSent(server, \"GET\", \"/subscriptions/\" + subsriptionId + \"/resourcegroups/\" + resourceGroup +\n              \"/providers/Microsoft.Storage/storageAccounts/TESTSTORAGE?api-version=2015-06-15\");\n   }\n\n   public void testGetKeys() throws Exception {\n      server.enqueue(jsonResponse(\"/storageaccountkeys.json\"));\n\n      final StorageAccountApi storageAPI = api.getStorageAccountApi(resourceGroup);\n\n      assertEquals(storageAPI.getKeys(\"TESTSTORAGE\"), StorageServiceKeys.create(\n              \"bndO7lydwDkMo4Y0mFvmfLyi2f9aZY7bwfAVWoJWv4mOVK6E9c/exLnFsSm/NMWgifLCfxC/c6QBTbdEvWUA7w==\",\n              \"/jMLLT3kKqY4K+cUtJTbh7pCBdvG9EMKJxUvaJJAf6W6aUiZe1A1ulXHcibrqRVA2RJE0oUeXQGXLYJ2l85L7A==\"));\n\n      assertSent(server, \"POST\", \"/subscriptions/\" + subsriptionId + \"/resourcegroups/\" + resourceGroup +\n              \"/providers/Microsoft.Storage/storageAccounts/TESTSTORAGE/listKeys?api-version=2015-06-15\");\n   }\n\n   public void testNullGetKeys() throws Exception {\n      server.enqueue(new MockResponse().setResponseCode(404));\n\n      final StorageAccountApi storageAPI = api.getStorageAccountApi(resourceGroup);\n\n      assertNull(storageAPI.getKeys(\"TESTSTORAGE\"));\n\n      assertSent(server, \"POST\", \"/subscriptions/\" + subsriptionId + \"/resourcegroups/\" + resourceGroup +\n              \"/providers/Microsoft.Storage/storageAccounts/TESTSTORAGE/listKeys?api-version=2015-06-15\");\n   }\n\n   public void testRegenerateKeys() throws Exception {\n      server.enqueue(jsonResponse(\"/storageaccountkeys.json\"));\n\n      final StorageAccountApi storageAPI = api.getStorageAccountApi(resourceGroup);\n\n      assertEquals(storageAPI.regenerateKeys(\"TESTSTORAGE\", \"key1\"), StorageServiceKeys.create(\n              \"bndO7lydwDkMo4Y0mFvmfLyi2f9aZY7bwfAVWoJWv4mOVK6E9c/exLnFsSm/NMWgifLCfxC/c6QBTbdEvWUA7w==\",\n              \"/jMLLT3kKqY4K+cUtJTbh7pCBdvG9EMKJxUvaJJAf6W6aUiZe1A1ulXHcibrqRVA2RJE0oUeXQGXLYJ2l85L7A==\"));\n\n      assertSent(server, \"POST\", \"/subscriptions/\" + subsriptionId + \"/resourcegroups/\" + resourceGroup +\n              \"/providers/Microsoft.Storage/storageAccounts/TESTSTORAGE/regenerateKey?api-version=2015-06-15\", String.format(\"{\\\"keyName\\\":\\\"key1\\\"}\"));\n   }\n\n   public void testUpdate() throws Exception {\n      server.enqueue(jsonResponse(\"/storageaccountupdate.json\"));\n\n      final StorageAccountApi storageAPI = api.getStorageAccountApi(resourceGroup);\n\n      StorageServiceUpdateParams.StorageServiceUpdateProperties props =\n      StorageServiceUpdateParams.StorageServiceUpdateProperties.create(StorageService.AccountType.Standard_LRS);\n\n      final StorageServiceUpdateParams params = storageAPI.update(\"TESTSTORAGE\",\n              ImmutableMap.of(\"another_property_name\", \"another_property_value\"), props);\n\n      assertTrue(params.tags().containsKey(\"another_property_name\"));\n\n      assertSent(server, \"PATCH\", \"/subscriptions/\" + subsriptionId + \"/resourcegroups/\" + resourceGroup +\n         \"/providers/Microsoft.Storage/storageAccounts/TESTSTORAGE?api-version=2015-06-15\", String.format(\"{\\\"properties\\\":{ \\\"accountType\\\": \\\"Standard_LRS\\\" },\\\"tags\\\":{\\\"another_property_name\\\":\\\"another_property_value\\\"}}\"));\n   }\n\n   public void testUpdateWithNullTagAndNullProperty() throws Exception {\n      server.enqueue(jsonResponse(\"/storageaccountupdate.json\"));\n\n      final StorageAccountApi storageAPI = api.getStorageAccountApi(resourceGroup);\n\n      StorageServiceUpdateParams.StorageServiceUpdateProperties props =\n              StorageServiceUpdateParams.StorageServiceUpdateProperties.create(null);\n\n      final StorageServiceUpdateParams params = storageAPI.update(\"TESTSTORAGE\", null, props);\n\n      assertTrue(params.tags().containsKey(\"another_property_name\"));\n\n      assertSent(server, \"PATCH\", \"/subscriptions/\" + subsriptionId + \"/resourcegroups/\" + resourceGroup +\n              \"/providers/Microsoft.Storage/storageAccounts/TESTSTORAGE?api-version=2015-06-15\", String.format(\"{\\\"properties\\\":{}}\"));\n   }\n\n   public void testDelete() throws Exception {\n      server.enqueue(new MockResponse().setResponseCode(200));\n\n      final StorageAccountApi storageAPI = api.getStorageAccountApi(resourceGroup);\n\n      boolean status = storageAPI.delete(\"TESTSTORAGE\");\n      assertTrue(status);\n\n      assertSent(server, \"DELETE\", \"/subscriptions/\" + subsriptionId + \"/resourcegroups/\" + resourceGroup +\n              \"/providers/Microsoft.Storage/storageAccounts/TESTSTORAGE?api-version=2015-06-15\");\n   }\n\n   public void testDelete204() throws Exception {\n\n      server.enqueue(new MockResponse().setResponseCode(204));\n\n      final StorageAccountApi storageAPI = api.getStorageAccountApi(resourceGroup);\n\n      boolean status = storageAPI.delete(\"TESTSTORAGE\");\n      assertFalse(status);\n\n      assertSent(server, \"DELETE\", \"/subscriptions/\" + subsriptionId + \"/resourcegroups/\" + resourceGroup +\n              \"/providers/Microsoft.Storage/storageAccounts/TESTSTORAGE?api-version=2015-06-15\");\n   }\n\n   private List<StorageService> expected() throws MalformedURLException {\n      DateService DATE_SERVICE = new SimpleDateFormatDateService();\n      Map<String, String> endpoints = new HashMap<String, String>();\n      endpoints.put(\"blob\", \"https://TESTSTORAGE.blob.core.windows.net/\");\n      endpoints.put(\"file\", \"https://TESTSTORAGE.file.core.windows.net/\");\n      endpoints.put(\"queue\", \"https://TESTSTORAGE.queue.core.windows.net/\");\n      endpoints.put(\"table\", \"https://TESTSTORAGE.table.core.windows.net/\");\n      Map<String, String> secondaryEndpoints = new HashMap<String, String>();\n      secondaryEndpoints.put(\"blob\", \"https://TESTSTORAGE-secondary.blob.core.windows.net/\");\n      secondaryEndpoints.put(\"queue\", \"https://TESTSTORAGE-secondary.queue.core.windows.net/\");\n      secondaryEndpoints.put(\"table\", \"https://TESTSTORAGE-secondary.table.core.windows.net/\");\n      Map<String, String> endpoints2 = new HashMap<String, String>();\n      endpoints2.put(\"blob\", \"https://TESTSTORAGE2.blob.core.windows.net/\");\n      endpoints2.put(\"file\", \"https://TESTSTORAGE2.file.core.windows.net/\");\n      endpoints2.put(\"queue\", \"https://TESTSTORAGE2.queue.core.windows.net/\");\n      endpoints2.put(\"table\", \"https://TESTSTORAGE2.table.core.windows.net/\");\n      Map<String, String> secondaryEndpoints2 = new HashMap<String, String>();\n      secondaryEndpoints2.put(\"blob\", \"https://TESTSTORAGE2-secondary.blob.core.windows.net/\");\n      secondaryEndpoints2.put(\"queue\", \"https://TESTSTORAGE2-secondary.queue.core.windows.net/\");\n      secondaryEndpoints2.put(\"table\", \"https://TESTSTORAGE2-secondary.table.core.windows.net/\");\n      Map<String, String> endpoints3 = new HashMap<String, String>();\n      endpoints3.put(\"blob\", \"https://TESTSTORAGE3.blob.core.windows.net/\");\n      endpoints3.put(\"file\", \"https://TESTSTORAGE3.file.core.windows.net/\");\n      endpoints3.put(\"queue\", \"https://TESTSTORAGE3.queue.core.windows.net/\");\n      endpoints3.put(\"table\", \"https://TESTSTORAGE3.table.core.windows.net/\");\n      Map<String, String> secondaryEndpoints3 = new HashMap<String, String>();\n      secondaryEndpoints3.put(\"blob\", \"https://TESTSTORAGE3-secondary.blob.core.windows.net/\");\n      secondaryEndpoints3.put(\"queue\", \"https://TESTSTORAGE3-secondary.queue.core.windows.net/\");\n      secondaryEndpoints3.put(\"table\", \"https://TESTSTORAGE3-secondary.table.core.windows.net/\");\n\n\n      String location = \"westus\";\n      String secondaryLocation = \"eastus\";\n      final StorageService.StorageServiceProperties props = StorageService.StorageServiceProperties.create(\n              StorageService.AccountType.Standard_RAGRS,\n              DATE_SERVICE.iso8601DateOrSecondsDateParse(\"2016-02-24T13:04:45.0890883Z\"),\n              endpoints,\n              location,\n              StorageService.Status.Succeeded, secondaryEndpoints, secondaryLocation,\n              StorageService.RegionStatus.Available,\n              StorageService.RegionStatus.Available);\n      final StorageService.StorageServiceProperties props2 = StorageService.StorageServiceProperties.create(\n              StorageService.AccountType.Standard_RAGRS,\n              DATE_SERVICE.iso8601DateOrSecondsDateParse(\"2016-02-24T13:11:43.8265672Z\"),\n              endpoints2, location,\n              StorageService.Status.Succeeded, secondaryEndpoints2, secondaryLocation,\n              StorageService.RegionStatus.Available,\n              StorageService.RegionStatus.Available);\n      final StorageService.StorageServiceProperties props3 = StorageService.StorageServiceProperties.create(\n              StorageService.AccountType.Standard_RAGRS,\n              DATE_SERVICE.iso8601DateOrSecondsDateParse(\"2016-02-24T14:12:59.5223315Z\"),\n              endpoints3, location,\n              StorageService.Status.Succeeded, secondaryEndpoints3, secondaryLocation,\n              StorageService.RegionStatus.Available,\n              StorageService.RegionStatus.Available);\n\n      final Map<String, String> tags = ImmutableMap.of(\n              \"key1\", \"value1\",\n              \"key2\", \"value2\");\n\n      return ImmutableList.of(StorageService.create(\n              \"/subscriptions/SUBSCRIPTIONID/resourceGroups/resourceGroup/\" +\n                      \"providers/Microsoft.Storage/storageAccounts/TESTSTORAGE\",\n              \"TESTSTORAGE\", location, tags, \"Microsoft.Storage/storageAccounts\", props),\n              StorageService.create(\n                      \"/subscriptions/SUBSCRIPTIONID/resourceGroups/resourceGroup/\" +\n                              \"providers/Microsoft.Storage/storageAccounts/TESTSTORAGE2\",\n                      \"TESTSTORAGE2\", location, tags, \"Microsoft.Storage/storageAccounts\", props2),\n              StorageService.create(\n                      \"/subscriptions/SUBSCRIPTIONID/resourceGroups/resourceGroup/\" +\n                              \"providers/Microsoft.Storage/storageAccounts/TESTSTORAGE3\",\n                      \"TESTSTORAGE3\", location, tags, \"Microsoft.Storage/storageAccounts\", props3));\n   }\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/SubnetApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.List;\n\nimport org.jclouds.azurecompute.arm.domain.Subnet;\nimport org.jclouds.azurecompute.arm.domain.VirtualNetwork;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiLiveTest;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true)\npublic class SubnetApiLiveTest extends BaseAzureComputeApiLiveTest {\n\n   private String virtualNetworkName;\n   private String subnetName;\n\n   @BeforeClass\n   @Override\n   public void setup() {\n      super.setup();\n      createTestResourceGroup();\n      virtualNetworkName = String.format(\"vn-%s-%s\", this.getClass().getSimpleName().toLowerCase(),\n            System.getProperty(\"user.name\"));\n      subnetName = \"jclouds-\" + RAND;\n\n      // Subnets belong to a virtual network so that needs to be created first\n      // VN will be deleted when resource group is deleted\n      VirtualNetwork vn = createDefaultVirtualNetwork(resourceGroupName, virtualNetworkName, \"10.2.0.0/16\", LOCATION);\n      assertNotNull(vn);\n   }\n\n   @Test\n   public void deleteSubnetResourceDoesNotExist() {\n      assertFalse(api().delete(subnetName));\n   }\n\n   @Test(dependsOnMethods = \"deleteSubnetResourceDoesNotExist\")\n   public void createSubnet() {\n      //Create properties object\n      //addressPrefix must match Virtual network address space!\n      Subnet.SubnetProperties properties = Subnet.SubnetProperties.builder().addressPrefix(\"10.2.0.0/23\").build();\n\n      Subnet subnet = api().createOrUpdate(subnetName, properties);\n\n      assertEquals(subnet.name(), subnetName);\n      assertEquals(subnet.properties().addressPrefix(), \"10.2.0.0/23\");\n   }\n\n   @Test(dependsOnMethods = \"createSubnet\")\n   public void getSubnet() {\n      Subnet subnet = api().get(subnetName);\n      assertNotNull(subnet.name());\n      assertNotNull(subnet.properties().addressPrefix());\n   }\n\n   @Test(dependsOnMethods = \"createSubnet\")\n   public void listSubnets() {\n      List<Subnet> subnets = api().list();\n      assertTrue(subnets.size() > 0);\n   }\n\n   @Test(dependsOnMethods = {\"listSubnets\", \"getSubnet\"}, alwaysRun = true)\n   public void deleteSubnet() {\n      boolean status = api().delete(subnetName);\n      assertTrue(status);\n   }\n\n   private SubnetApi api() {\n      return api.getSubnetApi(resourceGroupName, virtualNetworkName);\n   }\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/SubnetApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport static com.google.common.collect.Iterables.isEmpty;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.List;\n\nimport org.jclouds.azurecompute.arm.domain.Subnet;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiMockTest;\nimport org.testng.annotations.Test;\n\n\n@Test(groups = \"unit\", testName = \"SubnetApiMockTest\", singleThreaded = true)\npublic class SubnetApiMockTest extends BaseAzureComputeApiMockTest {\n\n   private final String subscriptionid = \"SUBSCRIPTIONID\";\n   private final String resourcegroup = \"myresourcegroup\";\n   private final String virtualNetwork = \"myvirtualnetwork\";\n   private final String subnetName = \"mysubnet\";\n   private final String apiVersion = \"api-version=2017-03-01\";\n\n   public void createSubnet() throws InterruptedException {\n\n      server.enqueue(jsonResponse(\"/createsubnetresponse.json\").setResponseCode(200));\n\n      final SubnetApi subnetApi = api.getSubnetApi(resourcegroup, virtualNetwork);\n\n      Subnet.SubnetProperties properties = Subnet.SubnetProperties.builder().addressPrefix(\"10.2.0.0/24\").build();\n\n      Subnet subnet = subnetApi.createOrUpdate(subnetName, properties);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/virtualNetworks/%s/subnets/%s?%s\", subscriptionid, resourcegroup, virtualNetwork, subnetName, apiVersion);\n      String json = \"{ \\\"properties\\\":{\\\"addressPrefix\\\":\\\"10.2.0.0/24\\\"}}\";\n      assertSent(server, \"PUT\", path, json);\n\n      assertEquals(subnet.name(), subnetName);\n      assertEquals(subnet.properties().addressPrefix(), \"10.2.0.0/24\");\n   }\n\n   public void getSubnet() throws InterruptedException {\n\n      server.enqueue(jsonResponse(\"/getonesubnet.json\").setResponseCode(200));\n\n      final SubnetApi subnetApi = api.getSubnetApi(resourcegroup, virtualNetwork);\n\n      Subnet subnet = subnetApi.get(subnetName);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/virtualNetworks/%s/subnets/%s?%s\", subscriptionid, resourcegroup, virtualNetwork, subnetName, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertEquals(subnet.name(), subnetName);\n      assertEquals(subnet.properties().addressPrefix(), \"10.2.0.0/24\");\n   }\n\n   public void getSubnetReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      final SubnetApi subnetApi = api.getSubnetApi(resourcegroup, virtualNetwork);\n\n      Subnet subnet = subnetApi.get(subnetName);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/virtualNetworks/%s/subnets/%s?%s\", subscriptionid, resourcegroup, virtualNetwork, subnetName, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertNull(subnet);\n   }\n\n   public void listSubnets() throws InterruptedException {\n\n      server.enqueue(jsonResponse(\"/listsubnetswithinvirtualnetwork.json\").setResponseCode(200));\n\n      final SubnetApi subnetApi = api.getSubnetApi(resourcegroup, virtualNetwork);\n\n      List<Subnet> subnets = subnetApi.list();\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/virtualNetworks/%s/subnets?%s\", subscriptionid, resourcegroup, virtualNetwork, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertTrue(subnets.size() > 0);\n   }\n\n   public void listSubnetsReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      final SubnetApi subnetApi = api.getSubnetApi(resourcegroup, virtualNetwork);\n\n      List<Subnet> subnets = subnetApi.list();\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/virtualNetworks/%s/subnets?%s\", subscriptionid, resourcegroup, virtualNetwork, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertTrue(isEmpty(subnets));\n   }\n\n   public void deleteSubnet() throws InterruptedException {\n\n      server.enqueue(response202());\n\n      final SubnetApi subnetApi = api.getSubnetApi(resourcegroup, virtualNetwork);\n\n      boolean status = subnetApi.delete(subnetName);\n      assertTrue(status);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/virtualNetworks/%s/subnets/%s?%s\", subscriptionid, resourcegroup, virtualNetwork, subnetName, apiVersion);\n      assertSent(server, \"DELETE\", path);\n   }\n\n   public void deleteSubnetResourceDoesNotExist() throws InterruptedException {\n\n      server.enqueue(response204());\n\n      final SubnetApi subnetApi = api.getSubnetApi(resourcegroup, virtualNetwork);\n\n      boolean status = subnetApi.delete(subnetName);\n      assertFalse(status);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/virtualNetworks/%s/subnets/%s?%s\", subscriptionid, resourcegroup, virtualNetwork, subnetName, apiVersion);\n      assertSent(server, \"DELETE\", path);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/VMSizeApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport org.jclouds.azurecompute.arm.domain.VMSize;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiLiveTest;\nimport org.testng.annotations.Test;\n\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\n@Test(groups = \"live\", testName = \"VMSizeApiLiveTest\")\npublic class VMSizeApiLiveTest extends BaseAzureComputeApiLiveTest {\n\n   @Test\n   public void testList() {\n      for (VMSize vmSize : api().list()) {\n         assertNotNull(vmSize.name());\n      }\n      assertTrue(api().list().size() > 0);\n   }\n\n   private VMSizeApi api() {\n      return api.getVMSizeApi(LOCATION);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/VMSizeApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport okhttp3.mockwebserver.MockResponse;\n\nimport org.jclouds.azurecompute.arm.domain.VMSize;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiMockTest;\nimport org.testng.annotations.Test;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.List;\n\n@Test(groups = \"unit\", testName = \"VMSizeApiMockTest\", singleThreaded = true)\npublic class VMSizeApiMockTest extends BaseAzureComputeApiMockTest {\n\n   public void testList() throws Exception {\n      server.enqueue(jsonResponse(\"/vmsizes.json\"));\n      final VMSizeApi vmSizeAPI = api.getVMSizeApi(\"westeurope\");\n      List<VMSize> vmSizes = vmSizeAPI.list();\n\n      assertNotNull(vmSizes);\n      assertEquals(vmSizes.size(), 3);\n      assertEquals(\n              vmSizes.get(0),\n              VMSize.create(\"Standard_A0\", 1, 1047552, 20480, 768, 1));\n\n\n      assertSent(server, \"GET\", \"/subscriptions/SUBSCRIPTIONID/providers/Microsoft.Compute/locations/westeurope/vmSizes?api-version=2015-06-15\");\n   }\n\n   public void testEmptyList() throws Exception {\n      server.enqueue(new MockResponse().setResponseCode(404));\n\n      final VMSizeApi vmSizeAPI = api.getVMSizeApi(\"location\");\n\n      assertTrue(vmSizeAPI.list().isEmpty());\n\n      assertSent(server, \"GET\", \"/subscriptions/SUBSCRIPTIONID/providers/Microsoft.Compute/locations/location/vmSizes?api-version=2015-06-15\");\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/VaultApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport java.net.URI;\nimport java.util.Map;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.ArrayList;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.FluentIterable;\nimport org.jclouds.azurecompute.arm.domain.Certificate;\nimport org.jclouds.azurecompute.arm.domain.Certificate.Contact;\nimport org.jclouds.azurecompute.arm.domain.Certificate.Contacts;\nimport org.jclouds.azurecompute.arm.domain.Certificate.AdministrationDetails;\nimport org.jclouds.azurecompute.arm.domain.Certificate.CertificateIssuer;\nimport org.jclouds.azurecompute.arm.domain.Certificate.CertificateBundle;\nimport org.jclouds.azurecompute.arm.domain.Certificate.CertificateOperation;\nimport org.jclouds.azurecompute.arm.domain.Certificate.CertificatePolicy;\nimport org.jclouds.azurecompute.arm.domain.Certificate.DeletedCertificate;\nimport org.jclouds.azurecompute.arm.domain.Certificate.DeletedCertificateBundle;\nimport org.jclouds.azurecompute.arm.domain.Certificate.OrganizationDetails;\nimport org.jclouds.azurecompute.arm.domain.Certificate.IssuerBundle;\nimport org.jclouds.azurecompute.arm.domain.Certificate.IssuerCredentials;\nimport org.jclouds.azurecompute.arm.domain.Certificate.IssuerParameters;\nimport org.jclouds.azurecompute.arm.domain.Certificate.KeyProperties;\nimport org.jclouds.azurecompute.arm.domain.Certificate.SecretProperties;\nimport org.jclouds.azurecompute.arm.domain.Certificate.X509CertificateProperties;\nimport org.jclouds.azurecompute.arm.domain.Secret;\nimport org.jclouds.azurecompute.arm.domain.Secret.SecretBundle;\nimport org.jclouds.azurecompute.arm.domain.Secret.SecretAttributes;\nimport org.jclouds.azurecompute.arm.domain.Secret.DeletedSecretBundle;\nimport org.jclouds.azurecompute.arm.domain.Key;\nimport org.jclouds.azurecompute.arm.domain.Key.JsonWebKey;\nimport org.jclouds.azurecompute.arm.domain.Key.KeyBundle;\nimport org.jclouds.azurecompute.arm.domain.Key.KeyAttributes;\nimport org.jclouds.azurecompute.arm.domain.Key.DeletedKeyBundle;\nimport org.jclouds.azurecompute.arm.domain.Key.KeyOperationResult;\nimport org.jclouds.azurecompute.arm.domain.SKU;\nimport org.jclouds.azurecompute.arm.domain.Vault;\nimport org.jclouds.azurecompute.arm.domain.Vault.DeletedVault;\nimport org.jclouds.azurecompute.arm.domain.VaultProperties;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiLiveTest;\nimport org.testng.SkipException;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\nimport static com.google.common.base.Preconditions.checkState;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.AssertJUnit.assertNull;\n\n@Test(groups = \"live\", testName = \"VaultApiLiveTest\")\npublic class VaultApiLiveTest extends BaseAzureComputeApiLiveTest {\n   private String vaultName;\n   private URI vaultUri = null;\n   private static String KEY_NAME = \"myKey\";\n   private static String IMPORT_KEY_NAME = \"myImportKey\";\n   private static String RECOVERABLE_KEY_NAME = \"myRecoverableKey\";\n   private static String SECRET_NAME = \"mySecret\";\n   private static String RECOVERABLE_SECRET_NAME = \"myRecoverableSecret\";\n   private static String CERTIFICATE_NAME = \"myCertificate\";\n   private static String TEMP_CERTIFICATE_NAME = \"myTempCertificate\";\n   private static String RECOVERABLE_CERTIFICATE_NAME = \"myRecoverableCertificate\";\n   private static String IMPORTABLE_CERTIFICATE_NAME = \"myImportableCertificate\";\n   private String importableCertificatePem = stringFromResource(\"/vaultimportablecert.txt\");\n   private String sampleSecret = stringFromResource(\"/vaultsamplesecret.txt\");\n   private static String cryptoText = \"R29sZCUyNTIxJTJCR29sZCUyNTIxJTJCR2\" +\n           \"9sZCUyQmZyb20lMkJ0aGUlMkJBbWVyaWNhbiUyQlJpdmVyJTI1MjE\";\n   private static String cryptoAlgorithm = \"RSA-OAEP\";\n   private static String hashToSign = \"FvabKT6qGwpml59iHUJ72DZ4XyJcJ8bgpgFA4_8JFmM\";\n   private static String signatureAlgorithm = \"RS256\";\n   private static String contentEncryptionKey = \"YxzoHR65aFwD2_IOiZ5rD08jMSALA1y7b_yYW0G3hyI\";\n\n   @BeforeClass\n   @Override\n   public void setup() {\n      super.setup();\n      createTestResourceGroup();\n      vaultName = String.format(\"kv%s\", this.getClass().getSimpleName().toLowerCase());\n   }\n\n   @AfterClass(alwaysRun = true)\n   public void forceVaultRemoval() {\n      // see if the vault has been deleted or not\n      Vault vault = api().getVault(vaultName);\n      if (vault != null) {\n         if ((vault.properties().enableSoftDelete() != null) && vault.properties().enableSoftDelete()) {\n            api().deleteVault(vaultName);\n            checkState(deletedVaultStatus.create(resourceGroupName, true).apply(vaultName),\n                    \"vault was not deleted before timeout\");\n         } else {\n            return;\n         }\n      }\n\n      DeletedVault deletedVault = api().getDeletedVault(LOCATION, vaultName);\n      if (deletedVault != null) {\n         api().purgeVault(LOCATION, vaultName);\n         checkState(deletedVaultStatus.create(resourceGroupName, false).apply(vaultName),\n                 \"vault was not purged before timeout\");\n      }\n   }\n\n   @Test\n   public void testCreate() {\n      String objectId = api.getServicePrincipal().get().objectId();\n      Vault vault = api().createOrUpdateVault(vaultName, LOCATION, VaultProperties.builder()\n              .tenantId(tenantId)\n              .sku(SKU.create(LOCATION, \"standard\", null, \"A\"))\n              .accessPolicies(ImmutableList.of(VaultProperties.AccessPolicyEntry.create(null, objectId, tenantId,\n                      VaultProperties.Permissions.create(\n                              ImmutableList.of( // certificates\n                                      \"Get\",\n                                      \"List\",\n                                      \"Update\",\n                                      \"Create\",\n                                      \"Import\",\n                                      \"Delete\",\n                                      \"ManageContacts\",\n                                      \"ManageIssuers\",\n                                      \"GetIssuers\",\n                                      \"ListIssuers\",\n                                      \"SetIssuers\",\n                                      \"DeleteIssuers\",\n                                      \"Purge\",\n                                      \"Recover\"\n                              ),\n                              ImmutableList.of( // keys\n                                      \"Get\",\n                                      \"List\",\n                                      \"Update\",\n                                      \"Create\",\n                                      \"Import\",\n                                      \"Delete\",\n                                      \"Recover\",\n                                      \"Backup\",\n                                      \"Restore\",\n                                      \"Purge\",\n                                      \"Encrypt\",\n                                      \"Decrypt\",\n                                      \"Sign\",\n                                      \"Verify\",\n                                      \"WrapKey\",\n                                      \"UnwrapKey\"\n                              ),\n                              ImmutableList.of( // secrets\n                                      \"Get\",\n                                      \"List\",\n                                      \"Set\",\n                                      \"Delete\",\n                                      \"Recover\",\n                                      \"Backup\",\n                                      \"Restore\",\n                                      \"Purge\"\n                              ),\n                              ImmutableList.<String>of()\n                      ))))\n              .build(),\n              null);\n      vaultUri = vault.properties().vaultUri();\n      assertTrue(!vault.name().isEmpty());\n   }\n\n   @Test(dependsOnMethods = \"testCreate\")\n   public void testGet() {\n      Vault vaultFound = api().getVault(vaultName);\n      assertNotNull(vaultFound);\n   }\n\n   @Test(dependsOnMethods = \"testCreate\")\n   public void testList() {\n      for (Vault vault : api().listVaults()) {\n         assertTrue(!vault.name().isEmpty());\n      }\n   }\n\n   @Test(dependsOnMethods = {\"testDeleteKey\", \"testDeleteSecret\"})\n   public void testUpdateVaultToSoftDelete() {\n      Vault v = api().getVault(vaultName);\n      assertNotNull(v);\n      VaultProperties newProps = VaultProperties.create(v.properties().tenantId(),\n              v.properties().vaultUri(),\n              v.properties().enabledForDeployment(),\n              v.properties().enabledForTemplateDeployment(),\n              true,\n              v.properties().createMode(),\n              v.properties().sku(),\n              v.properties().accessPolicies());\n      Vault updatedVault = api().createOrUpdateVault(vaultName, LOCATION, newProps, null);\n      assertNotNull(updatedVault);\n      updatedVault = api().getVault(vaultName);\n      assertTrue(updatedVault.properties().enableSoftDelete());\n   }\n\n   @Test(dependsOnMethods = {\"testPurgeDeletedKey\", \"testPurgeDeletedSecret\"})\n   public void testDelete() {\n      boolean result =  api().deleteVault(vaultName);\n      assertTrue(result);\n      checkState(deletedVaultStatus.create(resourceGroupName, true).apply(vaultName),\n              \"vault was not deleted before timeout\");\n   }\n\n   @Test(dependsOnMethods = \"testDelete\")\n   public void testGetDeleted() {\n      DeletedVault dv = api().getDeletedVault(LOCATION, vaultName);\n      assertNotNull(dv);\n   }\n\n   @Test(dependsOnMethods = \"testDelete\")\n   public void testListDeleted() {\n      for (DeletedVault vault : api().listDeletedVaults()) {\n         assertNotNull(vault.name());\n      }\n   }\n\n   @Test(dependsOnMethods = {\"testGetDeleted\", \"testListDeleted\"})\n   public void testPurgeDeletedVault() {\n      api().purgeVault(LOCATION, vaultName);\n      checkState(deletedVaultStatus.create(resourceGroupName, true).apply(vaultName),\n              \"vault was not purged before timeout\");\n\n   }\n\n   @Test(dependsOnMethods = \"testGet\")\n   public void testCreateKey() {\n      KeyAttributes keyAttr = KeyAttributes.create(true, 0, null, null, null, null);\n      KeyBundle keyBundle = api().createKey(vaultUri,\n              KEY_NAME,\n              keyAttr,\n              null,\n              null,\n              2048,\n              \"RSA\",\n              null\n      );\n      assertNotNull(keyBundle);\n   }\n\n   @Test(dependsOnMethods = \"testCreateKey\")\n   public void testImportKey() {\n      KeyAttributes keyAttr = KeyAttributes.create(true, null, null, null, null, null);\n      List<String> keyOps = new ArrayList<String>();\n      keyOps.add(\"encrypt\");\n      JsonWebKey keyInfo = JsonWebKey.create(\n              null,\n              \"DjU54mYvHpICXHjc5-JiFqiH8NkUgOG8LL4kwt3DeBp9bP0-5hSJH8vmzwJkeGG9L79EWG4b_bfxgYdeNX7cFFagmW\" +\n                      \"PRFrlxbd64VRYFawZHRJt-2cbzMVI6DL8EK4bu5Ux5qTiV44Jw19hoD9nDzCTfPzSTSGrKD3iLPdnREYaIGDVxcjB\" +\n                      \"v3Tx6rrv3Z2lhHHKhEHb0RRjATcjAVKV9NZhMajJ4l9pqJ3A4IQrCBl95ux6Xm1oXP0i6aR78cjchsCpcMXdP3WMs\" +\n                      \"vHgTlsZT0RZLFHrvkiNHlPiil4G2_eHkwvT__CrcbO6SmI_zCtMmypuHJqcr-Xb7GPJoa64WoQ\",\n              \"DB9nGuHplY_7Xv5a5UCs5YgxkWPtJFfbIZ1Zr-XHCCY09JIWReOGQG226OhjwixKtOK_OqmAKtMKM9OmKviJRHNbD\" +\n                      \"hbTxumN3u7cL8dftjXpSryiEQlPmWyW94MneI2WNIrvh4wruQuDt8EztgOiDFxwcnUgey8iend7WmZnE7E\",\n              \"O-bSTUQ4N_UuQezgkF3TDrnBraO67leDGwRbfiE_U0ghQvqh5DA0QSPVzlWDZc9KUitvj8vxsR9o1PW9GS0an17GJ\" +\n                      \"EYuetLnkShKK3NWOhBBX6d1yP9rVdH6JhgIJEy_g0Suz7TAFiFc8i7JF8u4QJ05C8bZAMhOLotqftQeVOM\",\n              \"AQAB\",\n              null,\n              null,\n              keyOps,\n              null,\n              \"RSA\",\n              \"33TqqLR3eeUmDtHS89qF3p4MP7Wfqt2Zjj3lZjLjjCGDvwr9cJNlNDiuKboODgUiT4ZdPWbOiMAfDcDzlOxA04DDnEF\" +\n                      \"GAf-kDQiNSe2ZtqC7bnIc8-KSG_qOGQIVaay4Ucr6ovDkykO5Hxn7OU7sJp9TP9H0JH8zMQA6YzijYH9LsupTerrY\" +\n                      \"3U6zyihVEDXXOv08vBHk50BMFJbE9iwFwnxCsU5-UZUZYw87Uu0n4LPFS9BT8tUIvAfnRXIEWCha3KbFWmdZQZlyr\" +\n                      \"Fw0buUEf0YN3_Q0auBkdbDR_ES2PbgKTJdkjc_rEeM0TxvOUf7HuUNOhrtAVEN1D5uuxE1WSw\",\n              \"8K33pX90XX6PZGiv26wZm7tfvqlqWFT03nUMvOAytqdxhO2HysiPn4W58OaJd1tY4372Qpiv6enmUeI4MidCie-s-d0\" +\n                      \"_B6A0xfhU5EeeaDN0xDOOl8yN-kaaVj9b4HDR3c91OAwKpDJQIeJVZtxoijxl-SRx3u7Vs_7meeSpOfE\",\n              \"7a5KnUs1pTo72A-JquJvIz4Eu794Yh3ftTk_Et-83aE_FVc6Nk-EhfnwYSNpVmM6UKdrAoy5gsCvZPxrq-eR9pEwU8M\" +\n                      \"5UOlki03vWY_nqDBpJSIqwPvGHUB16zvggsPQUyQBfnN3N8XlDi12n88ltvWwEhn1LQOwMUALEfka9_s\",\n              \"InfGmkb2jNkPGuNiZ-mU0-ZrOgLza_fLL9ErZ35jUPhGFzdGxJNobklvsNoTd-E2GAU41YkJh24bncMLvJVYxHHA5iF\" +\n                      \"7FBWx1SvpEyKVhhnIcuXGD7N5PbNZzEdmr9C6I7cPVkWO-sUV7zfFukexIcANmsd_oBBGKRoYzP5Tti4\",\n              null,\n              null\n      );\n      KeyBundle importedKey = api().importKey(vaultUri, IMPORT_KEY_NAME, false, keyAttr, keyInfo, null);\n      assertNotNull(importedKey);\n   }\n\n   @Test(dependsOnMethods = \"testCreateKey\")\n   public void testListKeys() {\n      for (Key key : api().listKeys(vaultUri)) {\n         assertNotNull(key);   \n      }\n   }\n\n   @Test(dependsOnMethods = \"testListKeys\")\n   public void testGetKey() {\n      KeyBundle keyBundle = api().getKey(vaultUri, KEY_NAME);\n      assertNotNull(keyBundle);\n   }\n\n   @Test(dependsOnMethods = \"testGetKey\")\n   public void testUpdateKey() {\n      Map<String, String> tags = new HashMap<String, String>();\n      tags.put(\"purpose\", \"testing\");\n      KeyBundle updatedKey = api().updateKey(vaultUri, KEY_NAME, \"\", null, null, tags);\n      assertNotNull(updatedKey.tags());\n      assertEquals(updatedKey.tags().size(), 1);\n   }\n\n   @Test(dependsOnMethods = \"testUpdateKey\")\n   public void testListKeyVersions() {\n      // List key versions\n      List<Key> keys = api().getKeyVersions(vaultUri, KEY_NAME);\n      assertNotNull(keys);\n      assertTrue(keys.size() > 1);\n   }\n\n   @Test(dependsOnMethods = \"testListKeyVersions\")\n   public void testUpdateKeyWithVersion() {\n      List<Key> keys = api().getKeyVersions(vaultUri, KEY_NAME);\n      assertNotNull(keys);\n      assertTrue(keys.size() > 1);\n\n      // get key version to operate on\n      Key key = keys.get(1);\n      assertNotNull(key);\n      final String version = key.kid().substring(key.kid().lastIndexOf(\"/\") + 1).trim();\n\n      Map<String, String> tags = new HashMap<String, String>();\n      tags.put(\"purpose\", \"testing again\");\n      KeyBundle updatedKey = api().updateKey(vaultUri, KEY_NAME, version, null, null, tags);\n      assertNotNull(updatedKey);\n\n      FluentIterable<Key> iKeys = FluentIterable.from(api().getKeyVersions(vaultUri, KEY_NAME));\n      assertTrue(iKeys.anyMatch(new Predicate<Key>() {\n         @Override public boolean apply(Key input) {\n            return input.kid().contains(version);\n         }\n      }));\n\n      assertEquals(tags, updatedKey.tags());\n   }\n\n   @Test(dependsOnMethods = \"testUpdateKeyWithVersion\")\n   public void testBackupRestoreKey() {\n      KeyBundle originalKey = api().getKey(vaultUri, KEY_NAME);\n      assertNotNull(originalKey);\n\n      String backupKey = api().backupKey(vaultUri, KEY_NAME);\n      assertNotNull(backupKey);\n\n      DeletedKeyBundle dkb = api().deleteKey(vaultUri, KEY_NAME);\n      assertNotNull(dkb);\n\n      KeyBundle restoredKey = api().restoreKey(vaultUri, backupKey);\n      assertNotNull(restoredKey);\n\n      KeyBundle verifyKey = api().getKey(vaultUri, KEY_NAME);\n      assertNotNull(verifyKey);\n\n      assertEquals(verifyKey, originalKey);\n   }\n\n   @Test(dependsOnMethods = \"testBackupRestoreKey\")\n   public void testDeleteKey() {\n      DeletedKeyBundle dkb = api().deleteKey(vaultUri, KEY_NAME);\n      assertNotNull(dkb);\n   }\n\n   @Test(dependsOnMethods = \"testUpdateVaultToSoftDelete\")\n   public void testCreateRecoverableKey() {\n      KeyAttributes keyAttr = KeyAttributes.create(true, null, null, null, null, null);\n      KeyBundle keyBundle = api().createKey(vaultUri, RECOVERABLE_KEY_NAME,\n              keyAttr,\n              null,\n              null,\n              2048,\n              \"RSA\",\n              null\n      );\n      assertNotNull(keyBundle);\n      checkState(recoverableKeyStatus.create(resourceGroupName, vaultUri, false).apply(RECOVERABLE_KEY_NAME),\n              \"key was not created before timeout\");\n   }\n\n   @Test(dependsOnMethods = \"testCreateRecoverableKey\")\n   public void testDeleteRecoverableKey() {\n      DeletedKeyBundle dkb = api().deleteKey(vaultUri, RECOVERABLE_KEY_NAME);\n      assertNotNull(dkb.deletedDate());\n      assertNotNull(dkb.recoveryId());\n      checkState(deletedKeyStatus.create(resourceGroupName, vaultUri, true).apply(RECOVERABLE_KEY_NAME),\n              \"key was not deleted before timeout\");\n   }\n\n   @Test(dependsOnMethods = \"testDeleteRecoverableKey\")\n   public void testListDeletedKeys() {\n      for (DeletedKeyBundle key : api().listDeletedKeys(vaultUri)) {\n         assertNotNull(key.deletedDate());\n      }\n   }\n\n   @Test(dependsOnMethods = \"testListDeletedKeys\")\n   public void testGetDeletedKey() {\n      DeletedKeyBundle key = api().getDeletedKey(vaultUri, RECOVERABLE_KEY_NAME);\n      assertNotNull(key.deletedDate());\n   }\n\n   @Test(dependsOnMethods = {\"testDeleteRecoverableKey\", \"testGetDeletedKey\"})\n   public void testRecoverDeletedKey() {\n      api().recoverDeletedKey(vaultUri, RECOVERABLE_KEY_NAME);\n      checkState(recoverableKeyStatus.create(resourceGroupName, vaultUri, true).apply(RECOVERABLE_KEY_NAME),\n              \"key was not recovered before timeout\");\n   }\n\n   @Test(dependsOnMethods = \"testRecoverDeletedKey\")\n   public void testPurgeDeletedKey() {\n      // delete the key\n      api().deleteKey(vaultUri, RECOVERABLE_KEY_NAME);\n      checkState(deletedKeyStatus.create(resourceGroupName, vaultUri, true).apply(RECOVERABLE_KEY_NAME),\n              \"key was not deleted before timeout\");\n\n      // purge the key and verify that it is no longer listed as deleted\n      api().purgeDeletedKey(vaultUri, RECOVERABLE_KEY_NAME);\n      checkState(deletedKeyStatus.create(resourceGroupName, vaultUri, false).apply(RECOVERABLE_KEY_NAME),\n              \"key was not purged before timeout\");\n   }\n\n   @Test(dependsOnMethods = \"testCreateKey\")\n   public void testEncryptDecrypt() {\n      // Encrypt some text\n      KeyOperationResult encryptResult = api().encrypt(vaultUri,\n              KEY_NAME,\n              \"\",\n              cryptoAlgorithm,\n              cryptoText\n      );\n      assertNotNull(encryptResult);\n      assertTrue(encryptResult.value().length() > cryptoText.length());\n\n      // Decrypt the encrypted text\n      KeyOperationResult decryptResult = api().decrypt(vaultUri,\n              KEY_NAME,\n              \"\",\n              cryptoAlgorithm,\n              encryptResult.value()\n      );\n      assertNotNull(decryptResult);\n      assertTrue(decryptResult.value().equals(cryptoText));\n   }\n\n   @Test(dependsOnMethods = \"testCreateKey\")\n   public void testSignVerify() {\n      // Sign a hash\n      KeyOperationResult signResult = api().sign(vaultUri,\n              KEY_NAME,\n              \"\",\n              signatureAlgorithm,\n              hashToSign\n      );\n      assertNotNull(signResult);\n      assertTrue(!signResult.value().isEmpty());\n\n      // Verify the signature\n      boolean verifyResult = api().verify(vaultUri,\n              KEY_NAME,\n              \"\",\n              signatureAlgorithm,\n              hashToSign,\n              signResult.value()\n      );\n      assertTrue(verifyResult);\n   }\n\n   @Test(dependsOnMethods = \"testCreateKey\")\n   public void testWrapUnwrapKey() {\n      // Wrap a 256bit symmetric key\n      KeyOperationResult wrapResult = api().wrap(vaultUri,\n              KEY_NAME,\n              \"\",\n              cryptoAlgorithm,\n              contentEncryptionKey\n      );\n      assertNotNull(wrapResult);\n      assertTrue(!wrapResult.value().isEmpty());\n\n      // Unwrap symmetric key\n      KeyOperationResult unwrapResult = api().unwrap(vaultUri,\n              KEY_NAME,\n              \"\",\n              cryptoAlgorithm,\n              wrapResult.value()\n      );\n      assertNotNull(unwrapResult);\n      assertTrue(unwrapResult.value().equals(contentEncryptionKey));\n   }\n\n   @Test(dependsOnMethods = \"testBackupRestoreKey\")\n   public void testSetSecret() {\n      SecretAttributes attributes = SecretAttributes.create(true, null, null, null, null, null);\n      SecretBundle secretBundle = api().setSecret(vaultUri,\n              SECRET_NAME,\n              attributes,\n              \"testSecretKey\",\n              null,\n              sampleSecret\n      );\n      assertNotNull(secretBundle);\n   }\n\n   @Test(dependsOnMethods = \"testSetSecret\")\n   public void testGetSecret() {\n      SecretBundle secret = api().getSecret(vaultUri, SECRET_NAME, null);\n      assertNotNull(secret);\n   }\n\n   @Test(dependsOnMethods = \"testSetSecret\")\n   public void testGetSecrets() {\n      for (Secret secret : api().listSecrets(vaultUri)) {\n         assertNotNull(secret);\n      }\n   }\n\n   @Test(dependsOnMethods = {\"testBackupRestoreSecret\"})\n   public void testDeleteSecret() {\n      DeletedSecretBundle dsb = api().deleteSecret(vaultUri, SECRET_NAME);\n      assertNotNull(dsb);\n   }\n\n   @Test(dependsOnMethods = \"testGetSecret\")\n   public void testUpdateSecret() {\n      Map<String, String> tags = new HashMap<String, String>();\n      tags.put(\"purpose\", \"testing\");\n      SecretBundle updatedSecret = api().updateSecret(vaultUri, SECRET_NAME, \"\", null, null, tags);\n      assertNotNull(updatedSecret.tags());\n      assertEquals(updatedSecret.tags().size(), 1);\n   }\n\n   @Test(dependsOnMethods = \"testUpdateSecret\")\n   public void testListSecretVersions() {\n      // Create a second version of the secret\n      SecretAttributes attributes = SecretAttributes.create(true, null, null, null, null, null);\n      api().setSecret(vaultUri,\n              SECRET_NAME,\n              attributes,\n              \"aNewSecretKey\",\n              null,\n              \"-----BEGIN DSA PRIVATE KEY-----\\n\" +\n                      \"MIIBvAIBAAKBgQDvgcVEyeU5gfw69xY2n1zHWGp/Z8O573SiWIcy29rW382W6jvn\\n\" +\n                      \"X5rF/LX8AscwRhf2pUTEy64ECkd08eRgEjRIKdGSaTZpBXxM25TPb2fF9k1/ObXd\\n\" +\n                      \"SkNOQNlwoCHdyQlvwdkVRohJoBX9u371owXObwLiBR1V597p3PdGNYD3DQIVAPtD\\n\" +\n                      \"dHQQaHCYMxAIXRsaCmOZfsjdAoGBANVOovY4XqS48hvi/RzcCMbRbuHMFBXh/lEM\\n\" +\n                      \"FmBdZ5sczpi1S3KpEjnBPQfOTzspTlEm5y6cHbkQjh1qT1tMdPAAr5aHYVLCTR+v\\n\" +\n                      \"CSSALXP48YiZrJcgdyfhbyr5h/Su2QuwX2DvYrR9d88fYHU4O0njEyMd8UFwQ6Uy\\n\" +\n                      \"qez/catgAoGAJ2AbSklFUXYvehmCVO6XVo3bgO++C3GMycJY3HHTTFQNAb3LJkeO\\n\" +\n                      \"fa2ZCSqWbd85M00Lt0VEkqlb0EkjDvAgL0R78IJUmvb3FH1RiUofP/yK3g1/3I/l\\n\" +\n                      \"jUa1fXXn2jSFYcyzGaDnC2U/B55g9G7hXsXJuldwATfDnLtqCdNPoWcCFQDx5K/k\\n\" +\n                      \"Ub4xHF/4Tau8wDAkxHeJiw==\\n\" +\n                      \"-----END DSA PRIVATE KEY-----\"\n      );\n\n      // List secret versions\n      List<Secret> secrets = api().getSecretVersions(vaultUri, SECRET_NAME);\n      assertNotNull(secrets);\n      assertEquals(secrets.size(), 2);\n   }\n\n   @Test(dependsOnMethods = \"testListSecretVersions\")\n   public void testUpdateSecretWithVersion() {\n      List<Secret> secrets = api().getSecretVersions(vaultUri, SECRET_NAME);\n      assertNotNull(secrets);\n      assertEquals(secrets.size(), 2);\n\n      // get secret version to operate on\n      Secret secret = secrets.get(1);\n      assertNotNull(secret);\n      String version = secret.id().substring(secret.id().lastIndexOf(\"/\") + 1).trim();\n\n      Map<String, String> tags = new HashMap<String, String>();\n      tags.put(\"purpose\", \"testing again\");\n      SecretBundle updatedSecret = api().updateSecret(vaultUri, SECRET_NAME, version, null, null, tags);\n      assertNotNull(updatedSecret);\n\n      secrets = api().getSecretVersions(vaultUri, SECRET_NAME);\n      assertNotNull(secrets);\n      boolean found = false;\n      for (Secret s : secrets) {\n         if (s.id().contains(version)) {\n            secret = s;\n            found = true;\n            break;\n         }\n      }\n      assertTrue(found);\n      assertEquals(tags, secret.tags());\n   }\n\n   @Test(dependsOnMethods = \"testUpdateSecretWithVersion\")\n   public void testBackupRestoreSecret() {\n      SecretBundle originalSecret = api().getSecret(vaultUri, SECRET_NAME, null);\n      assertNotNull(originalSecret);\n\n      String backupSecret = api().backupSecret(vaultUri, SECRET_NAME);\n      assertNotNull(backupSecret);\n\n      DeletedSecretBundle dsb = api().deleteSecret(vaultUri, SECRET_NAME);\n      assertNotNull(dsb);\n\n      SecretBundle restoredSecret = api().restoreSecret(vaultUri, backupSecret);\n      assertNotNull(restoredSecret);\n\n      SecretBundle verifySecret = api().getSecret(vaultUri, SECRET_NAME, null);\n      assertNotNull(verifySecret);\n\n      assertEquals(verifySecret, originalSecret);\n   }\n\n   @Test(dependsOnMethods = \"testUpdateVaultToSoftDelete\")\n   public void testCreateRecoverableSecret() {\n      SecretAttributes attributes = SecretAttributes.create(true, null, null, null, null, null);\n      SecretBundle secretBundle = api().setSecret(vaultUri,\n              RECOVERABLE_SECRET_NAME,\n              attributes,\n              \"aNewSecretKey\",\n              null,\n              \"-----BEGIN DSA PRIVATE KEY-----\\n\" +\n                      \"MIIBvAIBAAKBgQDvgcVEyeU5gfw69xY2n1zHWGp/Z8O573SiWIcy29rW382W6jvn\\n\" +\n                      \"X5rF/LX8AscwRhf2pUTEy64ECkd08eRgEjRIKdGSaTZpBXxM25TPb2fF9k1/ObXd\\n\" +\n                      \"SkNOQNlwoCHdyQlvwdkVRohJoBX9u371owXObwLiBR1V597p3PdGNYD3DQIVAPtD\\n\" +\n                      \"dHQQaHCYMxAIXRsaCmOZfsjdAoGBANVOovY4XqS48hvi/RzcCMbRbuHMFBXh/lEM\\n\" +\n                      \"FmBdZ5sczpi1S3KpEjnBPQfOTzspTlEm5y6cHbkQjh1qT1tMdPAAr5aHYVLCTR+v\\n\" +\n                      \"CSSALXP48YiZrJcgdyfhbyr5h/Su2QuwX2DvYrR9d88fYHU4O0njEyMd8UFwQ6Uy\\n\" +\n                      \"qez/catgAoGAJ2AbSklFUXYvehmCVO6XVo3bgO++C3GMycJY3HHTTFQNAb3LJkeO\\n\" +\n                      \"fa2ZCSqWbd85M00Lt0VEkqlb0EkjDvAgL0R78IJUmvb3FH1RiUofP/yK3g1/3I/l\\n\" +\n                      \"jUa1fXXn2jSFYcyzGaDnC2U/B55g9G7hXsXJuldwATfDnLtqCdNPoWcCFQDx5K/k\\n\" +\n                      \"Ub4xHF/4Tau8wDAkxHeJiw==\\n\" +\n                      \"-----END DSA PRIVATE KEY-----\"\n      );\n      assertNotNull(secretBundle);\n      checkState(recoverableSecretStatus.create(resourceGroupName, vaultUri, false).apply(RECOVERABLE_SECRET_NAME),\n              \"secret was not created before timeout\");\n   }\n\n   @Test(dependsOnMethods = \"testCreateRecoverableSecret\")\n   public void testDeleteRecoverableSecret() {\n      DeletedSecretBundle dsb = api().deleteSecret(vaultUri, RECOVERABLE_SECRET_NAME);\n      assertNotNull(dsb.deletedDate());\n      assertNotNull(dsb.recoveryId());\n      checkState(deletedSecretStatus.create(resourceGroupName, vaultUri, true).apply(RECOVERABLE_SECRET_NAME),\n              \"secret was not deleted before timeout\");\n   }\n\n   @Test(dependsOnMethods = \"testDeleteRecoverableSecret\")\n   public void testListDeletedSecrets() {\n      for (DeletedSecretBundle secret : api().listDeletedSecrets(vaultUri)) {\n         assertNotNull(secret.deletedDate());\n      }\n   }\n\n   @Test(dependsOnMethods = \"testListDeletedSecrets\")\n   public void testGetDeletedSecret() {\n      DeletedSecretBundle dsb = api().getDeletedSecret(vaultUri, RECOVERABLE_SECRET_NAME);\n      assertNotNull(dsb.deletedDate());\n   }\n\n   @Test(dependsOnMethods = {\"testDeleteRecoverableSecret\", \"testGetDeletedSecret\"})\n   public void testRecoverDeletedSecret() {\n      api().recoverDeletedSecret(vaultUri, RECOVERABLE_SECRET_NAME);\n      checkState(recoverableSecretStatus.create(resourceGroupName, vaultUri, true).apply(RECOVERABLE_SECRET_NAME),\n              \"secret was not created before timeout\");\n   }\n\n   @Test(dependsOnMethods = \"testRecoverDeletedSecret\")\n   public void testPurgeDeletedSecret() {\n      // delete the secret\n      api().deleteSecret(vaultUri, RECOVERABLE_SECRET_NAME);\n      checkState(deletedSecretStatus.create(resourceGroupName, vaultUri, true).apply(RECOVERABLE_SECRET_NAME),\n              \"secret was not deleted before timeout\");\n\n      // purge the secret and verify that it is no longer listed as deleted\n      api().purgeDeletedSecret(vaultUri, RECOVERABLE_SECRET_NAME);\n      checkState(deletedSecretStatus.create(resourceGroupName, vaultUri, false).apply(RECOVERABLE_SECRET_NAME),\n              \"secret was not purged before timeout\");\n   }\n\n   @Test(dependsOnMethods = \"testGet\")\n   public void testCreateCertificate() {\n      CertificatePolicy policy = Certificate.CertificatePolicy.create(null,\n              CERTIFICATE_NAME,\n              IssuerParameters.create(null, \"Self\"),\n              KeyProperties.create(false, 2048, \"RSA\", false),\n              null,\n              null,\n              X509CertificateProperties.create(null, null, null, \"CN=mycertificate.foobar.com\", 12)\n      );\n      assertNotNull(policy);\n\n      CertificateOperation certOp = api().createCertificate(vaultUri,\n              CERTIFICATE_NAME,\n              null,\n              policy,\n              null\n      );\n      assertNotNull(certOp);\n   }\n\n   @Test(dependsOnMethods = \"testCreateCertificate\")\n   public void testImportCertificate() {\n      String certPem = importableCertificatePem;\n      CertificateBundle certBundle = api().importCertificate(\n              vaultUri,\n              IMPORTABLE_CERTIFICATE_NAME,\n              null,\n              CertificatePolicy.create(\n                      null,\n                      null,\n                      null,\n                      null,\n                      null,\n                      SecretProperties.create(\"application/x-pem-file\"),\n                      null\n              ),\n              null,\n              null,\n              certPem);\n      assertNotNull(certBundle);\n   }\n\n   @Test(dependsOnMethods = \"testImportCertificate\")\n   public void testMergeCertificate() {\n      /* XXX - Merging certificates is used in the case where a CSR is generated\n       * within the Azure Key Vault and then signed by an external entity.\n       * Since this requires an offline process outside the scope of automated\n       * tests, this test is currently not implemented.\n       */\n      throw new SkipException(\"merging certificates requires an external entity, skipping\");\n   }\n\n   @Test(dependsOnMethods = \"testGetCertificateOperation\")\n   public void testGetCertificate() {\n      CertificateBundle certBundle = api().getCertificate(vaultUri, \"myCertificate\", null);\n      assertNotNull(certBundle);\n   }\n\n   @Test(dependsOnMethods = \"testGetCertificateOperation\")\n   public void testListCertificates() {\n      List<Certificate> certs = api().getCertificates(vaultUri);\n      assertTrue(!certs.isEmpty());\n      for (Certificate cert : certs) {\n         assertNotNull(cert.id());\n      }\n   }\n\n   @Test(dependsOnMethods = \"testGetCertificateOperation\")\n   public void testListCertificateVersions() {\n      List<Certificate> certs = api().getCertificateVersions(vaultUri, CERTIFICATE_NAME);\n      assertNotNull(certs);\n      assertEquals(certs.size(), 1);\n   }\n\n   @Test(dependsOnMethods = \"testGetCertificatePolicy\")\n   public void testUpdateCertificate() {\n      Map<String, String> tags = new HashMap<String, String>();\n      tags.put(\"selfsigned\", \"true\");\n      CertificatePolicy policy = api().getCertificatePolicy(\n              vaultUri,\n              CERTIFICATE_NAME\n      );\n      assertNotNull(policy);\n      CertificateBundle certBundle = api().updateCertificate(\n              vaultUri,\n              CERTIFICATE_NAME,\n              \"\",\n              null,\n              policy,\n              tags\n      );\n      assertNotNull(certBundle);\n      assertEquals(certBundle.tags().size(), 1);\n   }\n\n   @Test(dependsOnMethods = \"testUpdateCertificate\")\n   public void testUpdateCertificateVersion() {\n      // create a new version of the certificate\n      /*\n       * XXX -- update using version complains about needing policy (required input), yet\n       * passing in the same policy results in the error:\n       *\n       * Policy cannot be updated with a specific version of a certificate\n       *\n       * Will uncomment/fix once this issue is resolved.\n       *\n       */\n      throw new SkipException(\"bug in requirements for function\");\n   }\n\n   @Test(dependsOnMethods = {\"testDeleteCertificateOperation\", \"testDeleteCertificateIssuer\",\n                             \"testDeleteCertificateContacts\", \"testUpdateCertificatePolicy\"})\n   public void testDeleteCertificate() {\n      DeletedCertificateBundle dcb = api().deleteCertificate(\n              vaultUri,\n              CERTIFICATE_NAME\n      );\n      assertNotNull(dcb);\n   }\n\n   @Test(dependsOnMethods = \"testCreateCertificate\")\n   public void testGetCertificateOperation() {\n      CertificateOperation certOp = api().getCertificateOperation(vaultUri, CERTIFICATE_NAME);\n      assertNotNull(certOp);\n      checkState(certificateOperationStatus.create(resourceGroupName, vaultUri, true).apply(CERTIFICATE_NAME),\n              \"certificate was not created before timeout\");\n   }\n\n   @Test(dependsOnMethods = \"testDeleteCertificateContacts\")\n   public void testUpdateCertificateOperation() {\n      CertificatePolicy policy = Certificate.CertificatePolicy.create(null,\n              TEMP_CERTIFICATE_NAME,\n              IssuerParameters.create(null, \"Self\"),\n              KeyProperties.create(false, 4096, \"RSA\", false),\n              null,\n              null,\n              X509CertificateProperties.create(null, null, null, \"CN=mytempcertificate.foobar.com\", 12)\n      );\n      assertNotNull(policy);\n      CertificateOperation certOp = api().createCertificate(vaultUri,\n              TEMP_CERTIFICATE_NAME,\n              null,\n              policy,\n              null\n      );\n      assertNotNull(certOp);\n\n      certOp = api().updateCertificateOperation(vaultUri, TEMP_CERTIFICATE_NAME, true);\n      assertNotNull(certOp);\n      assertTrue(certOp.cancellationRequested());\n   }\n\n   @Test(dependsOnMethods = \"testUpdateCertificateOperation\")\n   public void testDeleteCertificateOperation() {\n      CertificateOperation certOp = api().deleteCertificateOperation(vaultUri, TEMP_CERTIFICATE_NAME);\n      assertNotNull(certOp);\n      checkState(certificateOperationStatus.create(resourceGroupName, vaultUri, false).apply(TEMP_CERTIFICATE_NAME),\n              \"certificate was not deleted before timeout\");\n   }\n\n   @Test(dependsOnMethods = \"testGetCertificate\")\n   public void testSetCertificateIssuer() {\n      AdministrationDetails adminDetail = AdministrationDetails.create(\n              \"adminguy@certsforme.com\",\n              \"Admin\",\n              \"Guy\",\n              \"867-5309\"\n      );\n      List<AdministrationDetails> adminDetails = new ArrayList<AdministrationDetails>();\n      adminDetails.add(adminDetail);\n      OrganizationDetails orgDetails = OrganizationDetails.create(\n              adminDetails,\n              null\n      );\n      IssuerBundle issuer = api().setCertificateIssuer(\n              vaultUri,\n              \"globalsign01\",\n              null,\n              IssuerCredentials.create(\"imauser\", \"This1sMyPa55wurD!\"),\n              orgDetails,\n              \"GlobalSign\"\n      );\n      assertNotNull(issuer);\n   }\n\n   @Test(dependsOnMethods = \"testSetCertificateIssuer\")\n   public void testGetCertificateIssuers() {\n      List<CertificateIssuer> issuers = api().getCertificateIssuers(vaultUri);\n      assertNotNull(issuers);\n      assertTrue(issuers.size() > 0);\n   }\n\n   @Test(dependsOnMethods = \"testSetCertificateIssuer\")\n   public void testGetCertificateIssuer() {\n      IssuerBundle issuer = api().getCertificateIssuer(vaultUri, \"globalsign01\");\n      assertNotNull(issuer);\n      assertEquals(issuer.provider(), \"GlobalSign\");\n   }\n\n   @Test(dependsOnMethods = \"testGetCertificateIssuer\")\n   public void testUpdateCertificateIssuer() {\n      AdministrationDetails adminDetail = AdministrationDetails.create(\n              \"adminguy@certsforme.com\",\n              \"Admin\",\n              \"Guy\",\n              \"867-5309\"\n      );\n      List<AdministrationDetails> adminDetails = new ArrayList<AdministrationDetails>();\n      adminDetails.add(adminDetail);\n      OrganizationDetails orgDetails = OrganizationDetails.create(\n              adminDetails,\n              null\n      );\n      IssuerBundle issuer = api().updateCertificateIssuer(\n              vaultUri,\n              \"globalsign01\",\n              null,\n              IssuerCredentials.create(\"imauser\", \"CanHa5P455wuRd!\"),\n              orgDetails,\n              \"GlobalSign\"\n      );\n      assertNotNull(issuer);\n   }\n\n   @Test(dependsOnMethods = \"testUpdateCertificateIssuer\")\n   public void testDeleteCertificateIssuer() {\n      IssuerBundle issuer = api().deleteCertificateIssuer(vaultUri, \"globalsign01\");\n      assertNotNull(issuer);\n\n      issuer = api().getCertificateIssuer(vaultUri, \"globalsign01\");\n      assertEquals(issuer, null);\n   }\n\n   @Test(dependsOnMethods = \"testDeleteCertificateIssuer\")\n   public void testSetCertificateContacts() {\n      List<Contact> contactsIn = new ArrayList<Contact>();\n      contactsIn.add(Contact.create(\"foo@bar.com\", \"Foo bar\", \"867-5309\"));\n      Contacts contacts = api().setCertificateContacts(vaultUri, contactsIn);\n      assertNotNull(contacts);\n   }\n   @Test(dependsOnMethods = \"testSetCertificateContacts\")\n   public void testGetCertificateContacts() {\n      Contacts contacts = api().getCertificateContacts(vaultUri);\n      assertNotNull(contacts.id());\n      assertEquals(contacts.contacts().size(), 1);\n   }\n\n   @Test(dependsOnMethods = \"testGetCertificateContacts\")\n   public void testDeleteCertificateContacts() {\n      Contacts contacts = api().deleteCertificateContacts(vaultUri);\n      assertNotNull(contacts.id());\n\n      contacts = api().getCertificateContacts(vaultUri);\n      assertNull(contacts);\n   }\n\n   @Test(dependsOnMethods = \"testCreateCertificate\")\n   public void testGetCertificatePolicy() {\n      CertificatePolicy policy = api().getCertificatePolicy(vaultUri, CERTIFICATE_NAME);\n      assertNotNull(policy);\n   }\n\n   @Test(dependsOnMethods = \"testUpdateCertificate\")\n   public void testUpdateCertificatePolicy() {\n      CertificatePolicy policy = api().updateCertificatePolicy(\n              vaultUri,\n              CERTIFICATE_NAME,\n              null,\n              null,\n              KeyProperties.create(true, 3072, \"RSA\", false),\n              null,\n              null,\n              null\n      );\n      assertNotNull(policy);\n      assertTrue(policy.keyProps().exportable());\n   }\n\n   @Test(dependsOnMethods = \"testUpdateVaultToSoftDelete\")\n   public void testImportRecoverableCertificate() {\n      String certPem = importableCertificatePem;\n      CertificateBundle certBundle = api().importCertificate(\n              vaultUri,\n              RECOVERABLE_CERTIFICATE_NAME,\n              null,\n              CertificatePolicy.create(\n                      null,\n                      null,\n                      null,\n                      null,\n                      null,\n                      SecretProperties.create(\"application/x-pem-file\"),\n                      null\n              ),\n              null,\n              null,\n              certPem);\n      checkState(recoverableCertificateStatus.create(resourceGroupName, vaultUri, true).apply(RECOVERABLE_CERTIFICATE_NAME),\n              \"certificate was not imported before timeout\");\n\n      certBundle = api().getCertificate(vaultUri, RECOVERABLE_CERTIFICATE_NAME, null);\n      assertNotNull(certBundle);\n      assertTrue(certBundle.attributes().recoveryLevel().contains(\"Recoverable\"));\n   }\n\n   @Test(dependsOnMethods = \"testImportRecoverableCertificate\")\n   public void testDeleteRecoverableCertificate() {\n      DeletedCertificateBundle dcb = api().deleteCertificate(vaultUri, RECOVERABLE_CERTIFICATE_NAME);\n      assertNotNull(dcb.deletedDate());\n      assertNotNull(dcb.recoveryId());\n      checkState(deletedCertificateStatus.create(resourceGroupName, vaultUri, true).apply(RECOVERABLE_CERTIFICATE_NAME),\n              \"certificate was not deleted before timeout\");\n   }\n\n   @Test(dependsOnMethods = \"testDeleteRecoverableCertificate\")\n   public void testListDeletedCertificates() {\n      for (DeletedCertificate dc : api().getDeletedCertificates(vaultUri)) {\n         assertNotNull(dc.deletedDate());\n      }\n   }\n\n   @Test(dependsOnMethods = \"testListDeletedCertificates\")\n   public void testGetDeletedCertificate() {\n      DeletedCertificateBundle dcb = api().getDeletedCertificate(vaultUri, RECOVERABLE_CERTIFICATE_NAME);\n      assertNotNull(dcb.deletedDate());\n   }\n\n   @Test(dependsOnMethods = \"testGetDeletedCertificate\")\n   public void testRecoverDeletedCertificate() {\n      CertificateBundle dcb = api().recoverDeletedCertificate(vaultUri, RECOVERABLE_CERTIFICATE_NAME);\n      assertNotNull(dcb);\n      checkState(recoverableCertificateStatus.create(resourceGroupName, vaultUri, false).apply(RECOVERABLE_CERTIFICATE_NAME),\n              \"certificate was not recovered before timeout\");\n   }\n\n   @Test(dependsOnMethods = \"testRecoverDeletedCertificate\")\n   public void testPurgeDeletedCertificate() {\n      // delete the certificate\n      api().deleteCertificate(vaultUri, RECOVERABLE_CERTIFICATE_NAME);\n      checkState(deletedCertificateStatus.create(resourceGroupName, vaultUri, true).apply(RECOVERABLE_CERTIFICATE_NAME),\n              \"certificate was not deleted before timeout\");\n\n      // purge the certificate and verify that it is no longer listed as deleted\n      api().purgeDeletedCertificate(vaultUri, RECOVERABLE_CERTIFICATE_NAME);\n      checkState(deletedCertificateStatus.create(resourceGroupName, vaultUri, false).apply(RECOVERABLE_CERTIFICATE_NAME),\n              \"certificate was not purged before timeout\");\n   }\n\n   private VaultApi api() {\n      return api.getVaultApi(resourceGroupName);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/VaultApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.net.URI;\nimport java.net.URISyntaxException;\n\nimport java.util.List;\nimport java.util.Map;\nimport java.util.HashMap;\nimport java.util.Arrays;\nimport java.util.ArrayList;\n\nimport org.jclouds.azurecompute.arm.domain.Certificate;\nimport org.jclouds.azurecompute.arm.domain.Certificate.AdministrationDetails;\nimport org.jclouds.azurecompute.arm.domain.Certificate.CertificateAttributes;\nimport org.jclouds.azurecompute.arm.domain.Certificate.CertificateBundle;\nimport org.jclouds.azurecompute.arm.domain.Certificate.CertificateIssuer;\nimport org.jclouds.azurecompute.arm.domain.Certificate.CertificateOperation;\nimport org.jclouds.azurecompute.arm.domain.Certificate.CertificatePolicy;\nimport org.jclouds.azurecompute.arm.domain.Certificate.Contact;\nimport org.jclouds.azurecompute.arm.domain.Certificate.Contacts;\nimport org.jclouds.azurecompute.arm.domain.Certificate.DeletedCertificate;\nimport org.jclouds.azurecompute.arm.domain.Certificate.DeletedCertificateBundle;\nimport org.jclouds.azurecompute.arm.domain.Certificate.IssuerBundle;\nimport org.jclouds.azurecompute.arm.domain.Certificate.IssuerCredentials;\nimport org.jclouds.azurecompute.arm.domain.Certificate.IssuerParameters;\nimport org.jclouds.azurecompute.arm.domain.Certificate.KeyProperties;\nimport org.jclouds.azurecompute.arm.domain.Certificate.OrganizationDetails;\nimport org.jclouds.azurecompute.arm.domain.Certificate.SecretProperties;\nimport org.jclouds.azurecompute.arm.domain.Certificate.X509CertificateProperties;\nimport org.jclouds.azurecompute.arm.domain.Key;\nimport org.jclouds.azurecompute.arm.domain.Key.DeletedKeyBundle;\nimport org.jclouds.azurecompute.arm.domain.Key.JsonWebKey;\nimport org.jclouds.azurecompute.arm.domain.Key.KeyAttributes;\nimport org.jclouds.azurecompute.arm.domain.Key.KeyBundle;\nimport org.jclouds.azurecompute.arm.domain.Key.KeyOperationResult;\nimport org.jclouds.azurecompute.arm.domain.SKU;\nimport org.jclouds.azurecompute.arm.domain.Secret;\nimport org.jclouds.azurecompute.arm.domain.Secret.DeletedSecretBundle;\nimport org.jclouds.azurecompute.arm.domain.Secret.SecretAttributes;\nimport org.jclouds.azurecompute.arm.domain.Secret.SecretBundle;\nimport org.jclouds.azurecompute.arm.domain.Vault;\nimport org.jclouds.azurecompute.arm.domain.Vault.DeletedVault;\nimport org.jclouds.azurecompute.arm.domain.VaultProperties;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiMockTest;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.testng.SkipException;\nimport org.testng.annotations.BeforeMethod;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n\n@Test(groups = \"unit\", testName = \"VaultApiMockTest\", singleThreaded = true)\npublic class VaultApiMockTest extends BaseAzureComputeApiMockTest {\n   private final String subscriptionId = \"SUBSCRIPTIONID\";\n   private final String resourceGroup = \"myresourcegroup\";\n   private final String tenantId = \"myTenantId\";\n   private final String identityObjId = \"myIdentityObjectId\";\n   private final String vaultName = \"kvvaultapimocktest\";\n   private final String apiVersion = \"api-version=2016-10-01\";\n   private final String location = \"westeurope\";\n   private URI vaultUri;\n\n   private static String KEY_NAME = \"myKey\";\n   private static String IMPORT_KEY_NAME = \"myImportKey\";\n   private static String RECOVERABLE_KEY_NAME = \"myRecoverableKey\";\n   private static String SECRET_NAME = \"mySecret\";\n   private static String RECOVERABLE_SECRET_NAME = \"myRecoverableSecret\";\n   private static String CERTIFICATE_NAME = \"myCertificate\";\n   private static String RECOVERABLE_CERTIFICATE_NAME = \"myRecoverableCertificate\";\n   private static String CERTIFICATE_ISSUER_NAME = \"globalsign01\";\n   private String IMPORTABLE_CERTIFICATE_PEM = stringFromResource(\"/vaultimportablecert.txt\");\n   private String sampleSecret = stringFromResource(\"/vaultsamplesecret.txt\");\n   private String keyBackup = stringFromResource(\"/vaultkeybackup.txt\");\n   private String secretBackup = stringFromResource(\"/vaultsecretbackup.txt\");\n   private String[] mergeX5C = {\n           stringFromResource(\"/vaultmergex5c-1.txt\"),\n           stringFromResource(\"/vaultmergex5c-2.txt\"),\n           stringFromResource(\"/vaultmergex5c-3.txt\")\n   };\n   private static String cryptoText = \"R29sZCUyNTIxJTJCR29sZCUyNTIxJTJCR2\" +\n           \"9sZCUyQmZyb20lMkJ0aGUlMkJBbWVyaWNhbiUyQlJpdmVyJTI1MjE\";\n   private static String cryptoAlgorithm = \"RSA-OAEP\";\n   private static String hashToSign = \"FvabKT6qGwpml59iHUJ72DZ4XyJcJ8bgpgFA4_8JFmM\";\n   private static String signatureAlgorithm = \"RS256\";\n   private static String contentEncryptionKey = \"YxzoHR65aFwD2_IOiZ5rD08jMSALA1y7b_yYW0G3hyI\";\n   private static String keyDecryptData = \"0_S8pyjjnGRlcbDa-Lt0jYjMXpXrf9Fat3elx-fSO\" +\n           \"g3dj6mYgEEs6kt79OMD4MFmVyOt6umeWAfdDIkNVnqb5fgyWceveh9wN-37jc5CFgG2PF3XI\" +\n           \"A6RII-HF2BkBcVa9KcAX3_di4KQE70PXgHf-dlz_RgLOJILeG50wzFeBFCLsjEEPp3itmoai\" +\n           \"E6vfDidCRm5At8Vjka0G-N_afwkIijfQZLT0VaXvL39cIJE2QN3HJPZM8YPUlkFlYnY4GIRy\" +\n           \"RWSBpK_KYuVufzUGtDi6Sh8pUa67ppa7DHVZlixlmnVqI3Oeg6XUvMqbFFqVSrcNbRQDwVGL\" +\n           \"3cUtK-KB1PfKg\";\n   private static String keySignedData = \"uO0r4P1cB-fKsDZ8cj5ahiNw8Tdsudt5zLCeEKOt29\" +\n           \"LAlPDpeGx9Q1SOFNaR7JlRYVelxsohdzvydwX8ao6MLnqlpdEj0Xt5Aadp-kN84AXW238gab\" +\n           \"S1AUyiWILCmdsBFeRU4wTRSxz2qGS_0ztHkaNln32P_9GJC72ZRlgZoVA4C_fowZolUoCWGj\" +\n           \"4V7fAzcSoiNYipWP0HkFe3xmuz-cSQg3CCAs-MclHHfMeSagLJZZQ9bpl5LIr-Ik89bNtqEq\" +\n           \"yP7Jb_fCgHajAx2lUFcRZhSIKuCfrLPMl6wzejQ2rQXX-ixEkDa73dYaPIrVW4IL3iC0Ufxn\" +\n           \"fxYffHJ7QCRw\";\n   private static String keyWrappedData = \"1jcTlu3KJNDBYydhaH9POWOo0tAPGkpsZVizCkHpC\" +\n           \"3g_9Kg91Q3HKK-rfZynn5W5nVPM-SVFHA3JTankcXX8gx8GycwUh4pMoyil_DV35m2QjyuiT\" +\n           \"ln83OJXw-nMvRXyKdVfF7nyRcs256kW7gthAOsYUVBrfFS7DFFxsXqLNREsA8j85IqIXIm8p\" +\n           \"AB3C9uvl1I7SQhLvrwZZXXqjeCWMfseVJwWgsQFyyqH2P0f3-xnngV7cvik2k3Elrk3G_2Cu\" +\n           \"JCozIIrANg9zG9Z8DrwSNNm9YooxWkSu0ZeDLOJ0bMdhcPGGm5OvKz3oZqX-39yv5klNlCRb\" +\n           \"r0q7gqmI0x25w\";\n\n   @BeforeMethod\n   public void start() throws IOException, URISyntaxException {\n      super.start();\n      vaultUri = server.url(\"\").uri();\n   }\n\n   public void createVault() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultcreate.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      Vault vault = vaultApi.createOrUpdateVault(vaultName, location, VaultProperties.builder()\n              .tenantId(this.tenantId)\n              .sku(SKU.create(location, \"standard\", null, \"A\"))\n              .accessPolicies(ImmutableList.of(VaultProperties.AccessPolicyEntry.create(null, this.identityObjId, this.tenantId,\n                      VaultProperties.Permissions.create(\n                              ImmutableList.of( // certificates\n                                      \"Get\",\n                                      \"List\",\n                                      \"Update\",\n                                      \"Create\",\n                                      \"Import\",\n                                      \"Delete\",\n                                      \"ManageContacts\",\n                                      \"ManageIssuers\",\n                                      \"GetIssuers\",\n                                      \"ListIssuers\",\n                                      \"SetIssuers\",\n                                      \"DeleteIssuers\",\n                                      \"Purge\",\n                                      \"Recover\"\n                              ),\n                              ImmutableList.of( // keys\n                                      \"Get\",\n                                      \"List\",\n                                      \"Update\",\n                                      \"Create\",\n                                      \"Import\",\n                                      \"Delete\",\n                                      \"Recover\",\n                                      \"Backup\",\n                                      \"Restore\",\n                                      \"Purge\",\n                                      \"Encrypt\",\n                                      \"Decrypt\",\n                                      \"Sign\",\n                                      \"Verify\",\n                                      \"WrapKey\",\n                                      \"UnwrapKey\"\n                              ),\n                              ImmutableList.of( // secrets\n                                      \"Get\",\n                                      \"List\",\n                                      \"Set\",\n                                      \"Delete\",\n                                      \"Recover\",\n                                      \"Backup\",\n                                      \"Restore\",\n                                      \"Purge\"\n                              ),\n                              ImmutableList.<String>of()\n                      ))))\n              .build(),\n              null);\n\n      String path = String.format(\n              \"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.KeyVault/vaults/%s?%s\",\n              subscriptionId, resourceGroup, vaultName, apiVersion\n      );\n      assertSent(server, \"PUT\", path, stringFromResource(\"/vaultcreaterequestbody.json\"));\n\n      assertNotNull(vault);\n      assertNotNull(vault.properties().vaultUri());\n      assertTrue(!vault.name().isEmpty());\n   }\n\n   public void listVaults() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultlist.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      List<Vault> vaults = vaultApi.listVaults();\n\n      String path = String.format(\n              \"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.KeyVault/vaults?%s\",\n              subscriptionId, resourceGroup, apiVersion\n      );\n      assertSent(server, \"GET\", path);\n\n      assertNotNull(vaults);\n      assertTrue(vaults.size() > 0);\n      assertTrue(!vaults.get(0).name().isEmpty());\n   }\n\n   public void listVaultsReturns404() throws InterruptedException {\n      server.enqueue(response404());\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      List<Vault> vaults = vaultApi.listVaults();\n\n      String path = String.format(\n              \"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.KeyVault/vaults?%s\",\n              subscriptionId, resourceGroup, apiVersion\n      );\n      assertSent(server, \"GET\", path);\n\n      assertTrue(vaults.isEmpty());\n   }\n\n   public void getVault() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultget.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      Vault vault = vaultApi.getVault(vaultName);\n\n      String path = String.format(\n              \"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.KeyVault/vaults/%s?%s\",\n              subscriptionId, resourceGroup, vaultName, apiVersion\n      );\n      assertSent(server, \"GET\", path);\n\n      assertNotNull(vault);\n      assertTrue(!vault.name().isEmpty());\n   }\n\n   public void getVaultReturns404() throws InterruptedException {\n      server.enqueue(response404());\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      Vault vault = vaultApi.getVault(vaultName);\n\n      String path = String.format(\n              \"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.KeyVault/vaults/%s?%s\",\n              subscriptionId, resourceGroup, vaultName, apiVersion\n      );\n      assertSent(server, \"GET\", path);\n\n      assertNull(vault);\n   }\n\n   public void deleteVault() throws InterruptedException {\n      server.enqueue(response200());\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      boolean status = vaultApi.deleteVault(vaultName);\n\n      String path = String.format(\n              \"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.KeyVault/vaults/%s?%s\",\n              subscriptionId, resourceGroup, vaultName, apiVersion\n      );\n      assertSent(server, \"DELETE\", path);\n\n      assertTrue(status);\n   }\n\n   public void deleteVaultReturns404() throws InterruptedException {\n      server.enqueue(response404());\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      boolean status = vaultApi.deleteVault(vaultName);\n\n      String path = String.format(\n              \"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.KeyVault/vaults/%s?%s\",\n              subscriptionId, resourceGroup, vaultName, apiVersion\n      );\n      assertSent(server, \"DELETE\", path);\n\n      assertFalse(status);\n   }\n\n   public void purgeDeletedVault() throws InterruptedException {\n      server.enqueue(response200());\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      boolean status = vaultApi.purgeVault(location, vaultName);\n\n      String path = String.format(\n              \"/subscriptions/%s/providers/Microsoft.KeyVault/locations/%s/deletedVaults/%s/purge?%s\",\n              subscriptionId, location, vaultName, apiVersion\n      );\n      assertSent(server, \"POST\", path);\n\n      assertTrue(status);\n   }\n\n   public void purgeDeletedVaultReturns404() throws InterruptedException {\n      server.enqueue(response404());\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      boolean status = vaultApi.purgeVault(location, vaultName);\n\n      String path = String.format(\n              \"/subscriptions/%s/providers/Microsoft.KeyVault/locations/%s/deletedVaults/%s/purge?%s\",\n              subscriptionId, location, vaultName, apiVersion\n      );\n      assertSent(server, \"POST\", path);\n\n      assertFalse(status);\n   }\n\n   public void listDeletedVaults() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultlistdeleted.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      List<DeletedVault> vaults = vaultApi.listDeletedVaults();\n\n      String path = String.format(\n              \"/subscriptions/%s/providers/Microsoft.KeyVault/deletedVaults?%s\",\n              subscriptionId, apiVersion\n      );\n      assertSent(server, \"GET\", path);\n\n      assertNotNull(vaults);\n      assertTrue(vaults.size() > 0);\n   }\n\n   public void listDeletedVaultsReturns404() throws InterruptedException {\n      server.enqueue(response404());\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      List<DeletedVault> vaults = vaultApi.listDeletedVaults();\n\n      String path = String.format(\n              \"/subscriptions/%s/providers/Microsoft.KeyVault/deletedVaults?%s\",\n              subscriptionId, apiVersion\n      );\n      assertSent(server, \"GET\", path);\n\n      assertTrue(vaults.isEmpty());\n   }\n\n   public void getDeletedVault() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultgetdeleted.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      DeletedVault vault = vaultApi.getDeletedVault(location, vaultName);\n\n      String path = String.format(\n              \"/subscriptions/%s/providers/Microsoft.KeyVault/locations/%s/deletedVaults/%s?%s\",\n              subscriptionId, location, vaultName, apiVersion\n      );\n      assertSent(server, \"GET\", path);\n\n      assertNotNull(vault);\n      assertTrue(!vault.name().isEmpty());\n      assertTrue(!vault.properties().deletionDate().toString().isEmpty());\n   }\n\n   public void getDeletedVaultReturns404() throws InterruptedException {\n      server.enqueue(response404());\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      DeletedVault vault = vaultApi.getDeletedVault(location, vaultName);\n\n      String path = String.format(\n              \"/subscriptions/%s/providers/Microsoft.KeyVault/locations/%s/deletedVaults/%s?%s\",\n              subscriptionId, location, vaultName, apiVersion\n      );\n      assertSent(server, \"GET\", path);\n\n      assertNull(vault);\n   }\n\n\n   // Key mock tests\n   public void listKeys() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultlistkeys.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      List<Key> keys = vaultApi.listKeys(vaultUri);\n\n      String path = String.format(\"/keys?%s\", apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertNotNull(keys);\n      assertTrue(keys.size() > 0);\n   }\n\n   public void listKeysReturns404() throws InterruptedException {\n      server.enqueue(response404());\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      List<Key> keys = vaultApi.listKeys(vaultUri);\n\n      String path = String.format(\"/keys?%s\", apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertTrue(keys.isEmpty());\n   }\n\n   public void createKey() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultcreatekey.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      KeyAttributes keyAttr = KeyAttributes.create(true, null, null, null, null, null);\n      KeyBundle keyBundle = vaultApi.createKey(vaultUri,\n              KEY_NAME,\n              keyAttr,\n              null,\n              null,\n              2048,\n              \"RSA\",\n              null\n      );\n\n      String path = String.format(\"/keys/%s/create?%s\", KEY_NAME, apiVersion);\n      assertSent(server, \"POST\", path, stringFromResource(\"/vaultcreatekeyrequestbody.json\"));\n\n      assertNotNull(keyBundle);\n      assertNotNull(keyBundle.attributes().created());\n   }\n\n   public void importKey() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultcreatekey.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      KeyAttributes keyAttr = KeyAttributes.create(true, null, null, null, null, null);\n      List<String> keyOps = new ArrayList<String>();\n      keyOps.add(\"encrypt\");\n      JsonWebKey keyInfo = JsonWebKey.create(\n              null,\n              \"DjU54mYvHpICXHjc5-JiFqiH8NkUgOG8LL4kwt3DeBp9bP0-5hSJH8vmzwJkeGG9L79EWG4b_bfxgYdeNX7cFFagmW\" +\n                      \"PRFrlxbd64VRYFawZHRJt-2cbzMVI6DL8EK4bu5Ux5qTiV44Jw19hoD9nDzCTfPzSTSGrKD3iLPdnREYaIGDVxcjB\" +\n                      \"v3Tx6rrv3Z2lhHHKhEHb0RRjATcjAVKV9NZhMajJ4l9pqJ3A4IQrCBl95ux6Xm1oXP0i6aR78cjchsCpcMXdP3WMs\" +\n                      \"vHgTlsZT0RZLFHrvkiNHlPiil4G2_eHkwvT__CrcbO6SmI_zCtMmypuHJqcr-Xb7GPJoa64WoQ\",\n              \"DB9nGuHplY_7Xv5a5UCs5YgxkWPtJFfbIZ1Zr-XHCCY09JIWReOGQG226OhjwixKtOK_OqmAKtMKM9OmKviJRHNbD\" +\n                      \"hbTxumN3u7cL8dftjXpSryiEQlPmWyW94MneI2WNIrvh4wruQuDt8EztgOiDFxwcnUgey8iend7WmZnE7E\",\n              \"O-bSTUQ4N_UuQezgkF3TDrnBraO67leDGwRbfiE_U0ghQvqh5DA0QSPVzlWDZc9KUitvj8vxsR9o1PW9GS0an17GJ\" +\n                      \"EYuetLnkShKK3NWOhBBX6d1yP9rVdH6JhgIJEy_g0Suz7TAFiFc8i7JF8u4QJ05C8bZAMhOLotqftQeVOM\",\n              \"AQAB\",\n              null,\n              null,\n              keyOps,\n              null,\n              \"RSA\",\n              \"33TqqLR3eeUmDtHS89qF3p4MP7Wfqt2Zjj3lZjLjjCGDvwr9cJNlNDiuKboODgUiT4ZdPWbOiMAfDcDzlOxA04DDnEF\" +\n                      \"GAf-kDQiNSe2ZtqC7bnIc8-KSG_qOGQIVaay4Ucr6ovDkykO5Hxn7OU7sJp9TP9H0JH8zMQA6YzijYH9LsupTerrY\" +\n                      \"3U6zyihVEDXXOv08vBHk50BMFJbE9iwFwnxCsU5-UZUZYw87Uu0n4LPFS9BT8tUIvAfnRXIEWCha3KbFWmdZQZlyr\" +\n                      \"Fw0buUEf0YN3_Q0auBkdbDR_ES2PbgKTJdkjc_rEeM0TxvOUf7HuUNOhrtAVEN1D5uuxE1WSw\",\n              \"8K33pX90XX6PZGiv26wZm7tfvqlqWFT03nUMvOAytqdxhO2HysiPn4W58OaJd1tY4372Qpiv6enmUeI4MidCie-s-d0\" +\n                      \"_B6A0xfhU5EeeaDN0xDOOl8yN-kaaVj9b4HDR3c91OAwKpDJQIeJVZtxoijxl-SRx3u7Vs_7meeSpOfE\",\n              \"7a5KnUs1pTo72A-JquJvIz4Eu794Yh3ftTk_Et-83aE_FVc6Nk-EhfnwYSNpVmM6UKdrAoy5gsCvZPxrq-eR9pEwU8M\" +\n                      \"5UOlki03vWY_nqDBpJSIqwPvGHUB16zvggsPQUyQBfnN3N8XlDi12n88ltvWwEhn1LQOwMUALEfka9_s\",\n              \"InfGmkb2jNkPGuNiZ-mU0-ZrOgLza_fLL9ErZ35jUPhGFzdGxJNobklvsNoTd-E2GAU41YkJh24bncMLvJVYxHHA5iF\" +\n                      \"7FBWx1SvpEyKVhhnIcuXGD7N5PbNZzEdmr9C6I7cPVkWO-sUV7zfFukexIcANmsd_oBBGKRoYzP5Tti4\",\n              null,\n              null\n      );\n      KeyBundle importedKey = vaultApi.importKey(vaultUri, IMPORT_KEY_NAME, false, keyAttr, keyInfo, null);\n\n      String path = String.format(\"/keys/%s?%s\", IMPORT_KEY_NAME, apiVersion);\n      assertSent(server, \"PUT\", path, stringFromResource(\"/vaultimportkeyrequestbody.json\"));\n\n      assertNotNull(importedKey);\n      assertNotNull(importedKey.attributes().created());\n   }\n\n   public void getKey() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultgetkey.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      KeyBundle key = vaultApi.getKey(vaultUri, KEY_NAME);\n\n      String path = String.format(\"/keys/%s?%s\", KEY_NAME, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertNotNull(key);\n      assertNotNull(key.attributes().created());\n   }\n\n   public void getKeyReturns404() throws InterruptedException {\n      server.enqueue(response404());\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      KeyBundle key = vaultApi.getKey(vaultUri, KEY_NAME);\n\n      String path = String.format(\"/keys/%s?%s\", KEY_NAME, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertNull(key);\n   }\n\n   public void deleteKey() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultdeletekey.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      DeletedKeyBundle key = vaultApi.deleteKey(vaultUri, KEY_NAME);\n\n      String path = String.format(\"/keys/%s?%s\", KEY_NAME, apiVersion);\n      assertSent(server, \"DELETE\", path);\n\n      assertNotNull(key);\n      assertNotNull(key.attributes().created());\n   }\n\n   public void deleteKeyReturns404() throws InterruptedException {\n      server.enqueue(response404());\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      DeletedKeyBundle key = vaultApi.deleteKey(vaultUri, KEY_NAME);\n\n      String path = String.format(\"/keys/%s?%s\", KEY_NAME, apiVersion);\n      assertSent(server, \"DELETE\", path);\n\n      assertNull(key);\n   }\n\n   public void getKeyVersions() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultgetkeyversions.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      List<Key> keys = vaultApi.getKeyVersions(vaultUri, KEY_NAME);\n\n      String path = String.format(\"/keys/%s/versions?%s\", KEY_NAME, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertNotNull(keys);\n      assertTrue(keys.size() > 0);\n      assertNotNull(keys.get(0).attributes().created());\n   }\n\n   public void getKeyVersionsReturns404() throws InterruptedException {\n      server.enqueue(response404());\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      List<Key> keys = vaultApi.getKeyVersions(vaultUri, KEY_NAME);\n\n      String path = String.format(\"/keys/%s/versions?%s\", KEY_NAME, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertTrue(keys.isEmpty());\n   }\n\n   public void updateKey() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultupdatekey.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      Map<String, String> tags = new HashMap<String, String>();\n      tags.put(\"purpose\", \"testing\");\n      KeyBundle updatedKey = vaultApi.updateKey(vaultUri, KEY_NAME, null, null, null, tags);\n\n      String path = String.format(\"/keys/%s?%s\", KEY_NAME, apiVersion);\n      assertSent(server, \"PATCH\", path, stringFromResource(\"/vaultupdatekeyrequestbody.json\"));\n\n      assertNotNull(updatedKey);\n      assertNotNull(updatedKey.attributes().created());\n   }\n\n   public void updateKeyWithVersion() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultupdatekeywithversion.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      String keyVersion = \"bd6566ec707e4ad89f4ab9577d9d0bef\";\n      Map<String, String> tags = new HashMap<String, String>();\n      tags.put(\"purpose\", \"testing\");\n      KeyBundle updatedKey = vaultApi.updateKey(vaultUri, KEY_NAME, keyVersion, null, null, tags);\n\n      String path = String.format(\"/keys/%s/%s?%s\", KEY_NAME, keyVersion, apiVersion);\n      assertSent(server, \"PATCH\", path, stringFromResource(\"/vaultupdatekeyrequestbody.json\"));\n\n      assertNotNull(updatedKey);\n      assertNotNull(updatedKey.attributes().created());\n   }\n\n   public void backupKey() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultbackupkey.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      String keyBackup = vaultApi.backupKey(vaultUri, KEY_NAME);\n\n      String path = String.format(\"/keys/%s/backup?%s\", KEY_NAME, apiVersion);\n      assertSent(server, \"POST\", path);\n\n      assertNotNull(keyBackup);\n      assertTrue(keyBackup.length() > 0);\n   }\n\n   public void restoreKey() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultrestorekey.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      KeyBundle restoredKey = vaultApi.restoreKey(vaultUri, keyBackup);\n\n      String path = String.format(\"/keys/restore?%s\", apiVersion);\n      assertSent(server, \"POST\", path, stringFromResource(\"/vaultrestorekeyrequestbody.json\"));\n\n      assertNotNull(restoredKey);\n      assertNotNull(restoredKey.attributes().created());\n   }\n\n   public void listDeletedKeys() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultlistdeletedkeys.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      List<DeletedKeyBundle> keys = vaultApi.listDeletedKeys(vaultUri);\n\n      String path = String.format(\"/deletedkeys?%s\", apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertNotNull(keys);\n      assertTrue(keys.size() > 0);\n   }\n\n   public void listDeletedKeysReturns404() throws InterruptedException {\n      server.enqueue(response404());\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      List<DeletedKeyBundle> keys = vaultApi.listDeletedKeys(vaultUri);\n\n      String path = String.format(\"/deletedkeys?%s\", apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertTrue(keys.isEmpty());\n   }\n\n   public void getDeletedKey() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultgetdeletedkey.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      DeletedKeyBundle key = vaultApi.getDeletedKey(vaultUri, RECOVERABLE_KEY_NAME);\n\n      String path = String.format(\"/deletedkeys/%s?%s\", RECOVERABLE_KEY_NAME, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertNotNull(key);\n      assertTrue(!key.deletedDate().isEmpty());\n   }\n\n   public void getDeletedKeyReturns404() throws InterruptedException {\n      server.enqueue(response404());\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      DeletedKeyBundle key = vaultApi.getDeletedKey(vaultUri, RECOVERABLE_KEY_NAME);\n\n      String path = String.format(\"/deletedkeys/%s?%s\", RECOVERABLE_KEY_NAME, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertNull(key);\n   }\n\n   public void recoverDeletedKey() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultrecoverdeletedkey.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      KeyBundle key = vaultApi.recoverDeletedKey(vaultUri, RECOVERABLE_KEY_NAME);\n\n      String path = String.format(\"/deletedkeys/%s/recover?%s\", RECOVERABLE_KEY_NAME, apiVersion);\n      assertSent(server, \"POST\", path);\n\n      assertNotNull(key);\n      assertNotNull(key.attributes().created());\n   }\n\n   public void purgeDeletedKey() throws InterruptedException {\n      server.enqueue(response200());\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      boolean status = vaultApi.purgeDeletedKey(vaultUri, RECOVERABLE_KEY_NAME);\n\n      String path = String.format(\"/deletedkeys/%s?%s\", RECOVERABLE_KEY_NAME, apiVersion);\n      assertSent(server, \"DELETE\", path);\n\n      assertTrue(status);\n   }\n\n   public void purgeDeletedKeyReturns404() throws InterruptedException {\n      server.enqueue(response404());\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      boolean status = vaultApi.purgeDeletedKey(vaultUri, RECOVERABLE_KEY_NAME);\n\n      String path = String.format(\"/deletedkeys/%s?%s\", RECOVERABLE_KEY_NAME, apiVersion);\n      assertSent(server, \"DELETE\", path);\n\n      assertFalse(status);\n   }\n\n   public void encrypt() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultkeyencrypt.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      KeyOperationResult encryptResult = vaultApi.encrypt(vaultUri,\n              KEY_NAME,\n              null,\n              cryptoAlgorithm,\n              cryptoText\n      );\n\n      String path = String.format(\"/keys/%s/encrypt?%s\", KEY_NAME, apiVersion);\n      assertSent(server, \"POST\", path, stringFromResource(\"/vaultkeyencryptrequestbody.json\"));\n\n      assertNotNull(encryptResult);\n      assertTrue(!encryptResult.value().isEmpty());\n   }\n\n   public void decrypt() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultkeydecrypt.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      KeyOperationResult decryptResult = vaultApi.decrypt(vaultUri,\n              KEY_NAME,\n              null,\n              cryptoAlgorithm,\n              keyDecryptData\n      );\n\n      String path = String.format(\"/keys/%s/decrypt?%s\", KEY_NAME, apiVersion);\n      assertSent(server, \"POST\", path, stringFromResource(\"/vaultkeydecryptrequestbody.json\"));\n\n      assertNotNull(decryptResult);\n      assertTrue(!decryptResult.value().isEmpty());\n   }\n\n   public void sign() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultkeysign.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      KeyOperationResult signResult = vaultApi.sign(vaultUri,\n              KEY_NAME,\n              null,\n              signatureAlgorithm,\n              hashToSign\n      );\n\n      String path = String.format(\"/keys/%s/sign?%s\", KEY_NAME, apiVersion);\n      assertSent(server, \"POST\", path, stringFromResource(\"/vaultkeysignrequestbody.json\"));\n\n      assertNotNull(signResult);\n      assertTrue(!signResult.value().isEmpty());\n   }\n\n   public void verify() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultkeyverify.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      boolean verifyResult = vaultApi.verify(vaultUri,\n              KEY_NAME,\n              null,\n              signatureAlgorithm,\n              hashToSign,\n              keySignedData\n      );\n\n      String path = String.format(\"/keys/%s/verify?%s\", KEY_NAME, apiVersion);\n      assertSent(server, \"POST\", path, stringFromResource(\"/vaultkeyverifyrequestbody.json\"));\n\n      assertTrue(verifyResult);\n   }\n\n   public void wrap() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultkeywrap.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      KeyOperationResult wrapResult = vaultApi.wrap(vaultUri,\n              KEY_NAME,\n              null,\n              cryptoAlgorithm,\n              contentEncryptionKey\n      );\n\n      String path = String.format(\"/keys/%s/wrapkey?%s\", KEY_NAME, apiVersion);\n      assertSent(server, \"POST\", path, stringFromResource(\"/vaultkeywraprequestbody.json\"));\n\n      assertNotNull(wrapResult);\n      assertTrue(!wrapResult.value().isEmpty());\n   }\n\n   public void unwrap() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultkeyunwrap.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      KeyOperationResult unwrapResult = vaultApi.unwrap(vaultUri,\n              KEY_NAME,\n              null,\n              cryptoAlgorithm,\n              keyWrappedData\n      );\n\n      String path = String.format(\"/keys/%s/unwrapkey?%s\", KEY_NAME, apiVersion);\n      assertSent(server, \"POST\", path, stringFromResource(\"/vaultkeyunwraprequestbody.json\"));\n\n      assertNotNull(unwrapResult);\n      assertTrue(!unwrapResult.value().isEmpty());\n   }\n\n   // Secret mock tests\n   public void listSecrets() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultlistsecrets.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      List<Secret> secrets = vaultApi.listSecrets(vaultUri);\n\n      String path = String.format(\"/secrets?%s\", apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertNotNull(secrets);\n      assertTrue(secrets.size() > 0);\n   }\n\n   public void listSecretsReturns404() throws InterruptedException {\n      server.enqueue(response404());\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      List<Secret> secrets = vaultApi.listSecrets(vaultUri);\n\n      String path = String.format(\"/secrets?%s\", apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertTrue(secrets.isEmpty());\n   }\n\n   public void setSecret() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultsetsecret.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      SecretAttributes attributes = SecretAttributes.create(true, null, null, null, null, null);\n      SecretBundle secretBundle = vaultApi.setSecret(vaultUri,\n              SECRET_NAME,\n              attributes,\n              \"testSecretKey\",\n              null,\n              sampleSecret\n      );\n\n      String path = String.format(\"/secrets/%s?%s\", SECRET_NAME, apiVersion);\n      assertSent(server, \"PUT\", path, stringFromResource(\"/vaultsetsecretrequestbody.json\"));\n\n      assertNotNull(secretBundle);\n      assertTrue(!secretBundle.id().isEmpty());\n   }\n\n   public void getSecret() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultgetsecret.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      SecretBundle secret = vaultApi.getSecret(vaultUri, SECRET_NAME, null);\n\n      String path = String.format(\"/secrets/%s?%s\", SECRET_NAME, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertNotNull(secret);\n      assertNotNull(secret.attributes().created());\n   }\n\n   public void getSecretReturns404() throws InterruptedException {\n      server.enqueue(response404());\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      SecretBundle secret = vaultApi.getSecret(vaultUri, SECRET_NAME, null);\n\n      String path = String.format(\"/secrets/%s?%s\", SECRET_NAME, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertNull(secret);\n   }\n\n   public void deleteSecret() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultdeletesecret.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      DeletedSecretBundle secret = vaultApi.deleteSecret(vaultUri, SECRET_NAME);\n\n      String path = String.format(\"/secrets/%s?%s\", SECRET_NAME, apiVersion);\n      assertSent(server, \"DELETE\", path);\n\n      assertNotNull(secret);\n      assertNotNull(secret.attributes().created());\n   }\n\n   public void deleteSecretReturns404() throws InterruptedException {\n      server.enqueue(response404());\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      DeletedSecretBundle secret = vaultApi.deleteSecret(vaultUri, SECRET_NAME);\n\n      String path = String.format(\"/secrets/%s?%s\", SECRET_NAME, apiVersion);\n      assertSent(server, \"DELETE\", path);\n\n      assertNull(secret);\n   }\n\n   public void getSecretVersions() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultgetsecretversions.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      List<Secret> secrets = vaultApi.getSecretVersions(vaultUri, SECRET_NAME);\n\n      String path = String.format(\"/secrets/%s/versions?%s\", SECRET_NAME, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertNotNull(secrets);\n      assertTrue(secrets.size() > 0);\n      assertNotNull(secrets.get(0).attributes().created());\n   }\n\n   public void getSecretVersionsReturns404() throws InterruptedException {\n      server.enqueue(response404());\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      List<Secret> secrets = vaultApi.getSecretVersions(vaultUri, SECRET_NAME);\n\n      String path = String.format(\"/secrets/%s/versions?%s\", SECRET_NAME, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertTrue(secrets.isEmpty());\n   }\n\n   public void updateSecret() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultupdatekey.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      Map<String, String> tags = new HashMap<String, String>();\n      tags.put(\"purpose\", \"testing\");\n      SecretBundle updatedSecret = vaultApi.updateSecret(vaultUri, SECRET_NAME, null, null, null, tags);\n\n      String path = String.format(\"/secrets/%s?%s\", SECRET_NAME, apiVersion);\n      assertSent(server, \"PATCH\", path, stringFromResource(\"/vaultupdatesecretrequestbody.json\"));\n\n      assertNotNull(updatedSecret);\n      assertNotNull(updatedSecret.attributes().created());\n   }\n\n   public void updateSecretWithVersion() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultupdatesecretwithversion.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      String secretVersion = \"b936ececbc674f3bb1367ae50d28ada0\";\n      Map<String, String> tags = new HashMap<String, String>();\n      tags.put(\"purpose\", \"testing again\");\n      SecretBundle updatedSecret = vaultApi.updateSecret(vaultUri, SECRET_NAME,  secretVersion, null, null, tags);\n\n      String path = String.format(\"/secrets/%s/%s?%s\", SECRET_NAME, secretVersion, apiVersion);\n      assertSent(server, \"PATCH\", path, stringFromResource(\"/vaultupdatesecretwithversionrequestbody.json\"));\n\n      assertNotNull(updatedSecret);\n      assertNotNull(updatedSecret.attributes().created());\n   }\n\n   public void backupSecret() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultbackupsecret.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      String secretBackup = vaultApi.backupSecret(vaultUri, SECRET_NAME);\n\n      String path = String.format(\"/secrets/%s/backup?%s\", SECRET_NAME, apiVersion);\n      assertSent(server, \"POST\", path);\n\n      assertNotNull(secretBackup);\n      assertTrue(secretBackup.length() > 0);\n   }\n\n   public void restoreSecret() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultrestoresecret.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      SecretBundle restoredSecret = vaultApi.restoreSecret(vaultUri, secretBackup);\n\n      String path = String.format(\"/secrets/restore?%s\", apiVersion);\n      assertSent(server, \"POST\", path, stringFromResource(\"/vaultrestoresecretrequestbody.json\"));\n\n      assertNotNull(restoredSecret);\n      assertNotNull(restoredSecret.attributes().created());\n   }\n\n   public void listDeletedSecrets() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultlistdeletedsecrets.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      List<DeletedSecretBundle> secrets = vaultApi.listDeletedSecrets(vaultUri);\n\n      String path = String.format(\"/deletedsecrets?%s\", apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertNotNull(secrets);\n      assertTrue(secrets.size() > 0);\n   }\n\n   public void listDeletedSecretsReturns404() throws InterruptedException {\n      server.enqueue(response404());\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      List<DeletedSecretBundle> secrets = vaultApi.listDeletedSecrets(vaultUri);\n\n      String path = String.format(\"/deletedsecrets?%s\", apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertTrue(secrets.isEmpty());\n   }\n\n   public void getDeletedSecret() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultgetdeletedsecret.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      DeletedSecretBundle secret = vaultApi.getDeletedSecret(vaultUri, RECOVERABLE_SECRET_NAME);\n\n      String path = String.format(\"/deletedsecrets/%s?%s\", RECOVERABLE_SECRET_NAME, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertNotNull(secret);\n      assertTrue(!secret.deletedDate().isEmpty());\n   }\n\n   public void getDeletedSecretReturns404() throws InterruptedException {\n      server.enqueue(response404());\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      DeletedSecretBundle secret = vaultApi.getDeletedSecret(vaultUri, RECOVERABLE_SECRET_NAME);\n\n      String path = String.format(\"/deletedsecrets/%s?%s\", RECOVERABLE_SECRET_NAME, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertNull(secret);\n   }\n\n   public void recoverDeletedSecret() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultrecoverdeletedsecret.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      SecretBundle secret = vaultApi.recoverDeletedSecret(vaultUri, RECOVERABLE_SECRET_NAME);\n\n      String path = String.format(\"/deletedsecrets/%s/recover?%s\", RECOVERABLE_SECRET_NAME, apiVersion);\n      assertSent(server, \"POST\", path);\n\n      assertNotNull(secret);\n      assertNotNull(secret.attributes().created());\n   }\n\n   public void purgeDeletedSecret() throws InterruptedException {\n      server.enqueue(response200());\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      boolean status = vaultApi.purgeDeletedSecret(vaultUri, RECOVERABLE_SECRET_NAME);\n\n      String path = String.format(\"/deletedsecrets/%s?%s\", RECOVERABLE_SECRET_NAME, apiVersion);\n      assertSent(server, \"DELETE\", path);\n\n      assertTrue(status);\n   }\n\n   public void purgeDeletedSecretReturns404() throws InterruptedException {\n      server.enqueue(response404());\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      boolean status = vaultApi.purgeDeletedSecret(vaultUri, RECOVERABLE_SECRET_NAME);\n\n      String path = String.format(\"/deletedsecrets/%s?%s\", RECOVERABLE_SECRET_NAME, apiVersion);\n      assertSent(server, \"DELETE\", path);\n\n      assertFalse(status);\n   }\n\n   public void createCertificate() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultcreatecertificate.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      CertificatePolicy policy = CertificatePolicy.create(null,\n              CERTIFICATE_NAME,\n              IssuerParameters.create(null, \"Self\"),\n              KeyProperties.create(false, 2048, \"RSA\", false),\n              null,\n              null,\n              X509CertificateProperties.create(null, null, null, \"CN=mycertificate.foobar.com\", 12)\n      );\n      CertificateOperation certOp = vaultApi.createCertificate(vaultUri,\n              CERTIFICATE_NAME,\n              null,\n              policy,\n              null\n      );\n\n      String path = String.format(\"/certificates/%s/create?%s\", CERTIFICATE_NAME, apiVersion);\n      assertSent(server, \"POST\", path, stringFromResource(\"/vaultcreatecertificaterequestbody.json\"));\n\n      assertNotNull(certOp);\n      assertTrue(!certOp.id().isEmpty());\n   }\n\n   public void getCertificate() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultgetcertificate.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      CertificateBundle cert = vaultApi.getCertificate(vaultUri, CERTIFICATE_NAME, null);\n\n      String path = String.format(\"/certificates/%s?%s\", CERTIFICATE_NAME, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertNotNull(cert);\n      assertTrue(!cert.id().isEmpty());\n   }\n\n   public void getCertificateReturns404() throws InterruptedException {\n      server.enqueue(response404());\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      CertificateBundle cert = vaultApi.getCertificate(vaultUri, CERTIFICATE_NAME, null);\n\n      String path = String.format(\"/certificates/%s?%s\", CERTIFICATE_NAME, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertNull(cert);\n   }\n\n   public void deleteCertificate() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultdeletecertificate.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      DeletedCertificateBundle cert = vaultApi.deleteCertificate(vaultUri, CERTIFICATE_NAME);\n\n      String path = String.format(\"/certificates/%s?%s\", CERTIFICATE_NAME, apiVersion);\n      assertSent(server, \"DELETE\", path);\n\n      assertNotNull(cert);\n      assertTrue(!cert.id().isEmpty());\n   }\n\n   public void deleteCertificateReturns404() throws InterruptedException {\n      server.enqueue(response404());\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      DeletedCertificateBundle cert = vaultApi.deleteCertificate(vaultUri, CERTIFICATE_NAME);\n\n      String path = String.format(\"/certificates/%s?%s\", CERTIFICATE_NAME, apiVersion);\n      assertSent(server, \"DELETE\", path);\n\n      assertNull(cert);\n   }\n\n   public void listCertificates() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultlistcertificates.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      List<Certificate> certs = vaultApi.getCertificates(vaultUri);\n\n      String path = String.format(\"/certificates?%s\", apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertNotNull(certs);\n      assertTrue(certs.size() > 0);\n   }\n\n   public void listCertificatesReturns404() throws InterruptedException {\n      server.enqueue(response404());\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      List<Certificate> certs = vaultApi.getCertificates(vaultUri);\n\n      String path = String.format(\"/certificates?%s\", apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertTrue(certs.isEmpty());\n   }\n\n   public void listDeletedCertificates() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultlistdeletedcertificates.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      List<DeletedCertificate> certs = vaultApi.getDeletedCertificates(vaultUri);\n\n      String path = String.format(\"/deletedcertificates?%s\", apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertNotNull(certs);\n      assertTrue(certs.size() > 0);\n   }\n\n   public void listDeletedCertificatesReturns404() throws InterruptedException {\n      server.enqueue(response404());\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      List<DeletedCertificate> certs = vaultApi.getDeletedCertificates(vaultUri);\n\n      String path = String.format(\"/deletedcertificates?%s\", apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertTrue(certs.isEmpty());\n   }\n\n   public void getDeletedCertificate() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultgetdeletedcertificate.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      DeletedCertificateBundle cert = vaultApi.getDeletedCertificate(vaultUri, RECOVERABLE_CERTIFICATE_NAME);\n\n      String path = String.format(\"/deletedcertificates/%s?%s\", RECOVERABLE_CERTIFICATE_NAME, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertNotNull(cert);\n      assertTrue(!cert.id().isEmpty());\n   }\n\n   public void getDeletedCertificateReturns404() throws InterruptedException {\n      server.enqueue(response404());\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      DeletedCertificateBundle cert = vaultApi.getDeletedCertificate(vaultUri, RECOVERABLE_CERTIFICATE_NAME);\n\n      String path = String.format(\"/deletedcertificates/%s?%s\", RECOVERABLE_CERTIFICATE_NAME, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertNull(cert);\n   }\n\n   public void recoverDeletedCertificate() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultrecoverdeletedcertificate.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      CertificateBundle cert = vaultApi.recoverDeletedCertificate(vaultUri, RECOVERABLE_CERTIFICATE_NAME);\n\n      String path = String.format(\"/deletedcertificates/%s/recover?%s\", RECOVERABLE_CERTIFICATE_NAME, apiVersion);\n      assertSent(server, \"POST\", path);\n\n      assertNotNull(cert);\n      assertTrue(!cert.id().isEmpty());\n   }\n\n   public void purgeDeletedCertificate() throws InterruptedException {\n      server.enqueue(response200());\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      boolean status = vaultApi.purgeDeletedCertificate(vaultUri, RECOVERABLE_CERTIFICATE_NAME);\n\n      String path = String.format(\"/deletedcertificates/%s?%s\", RECOVERABLE_CERTIFICATE_NAME, apiVersion);\n      assertSent(server, \"DELETE\", path);\n\n      assertTrue(status);\n   }\n\n   public void purgeDeletedCertificateReturns404() throws InterruptedException {\n      server.enqueue(response404());\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      boolean status = vaultApi.purgeDeletedCertificate(vaultUri, RECOVERABLE_CERTIFICATE_NAME);\n\n      String path = String.format(\"/deletedcertificates/%s?%s\", RECOVERABLE_CERTIFICATE_NAME, apiVersion);\n      assertSent(server, \"DELETE\", path);\n\n      assertFalse(status);\n   }\n\n   public void listCertificateVersions() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultlistcertificateversions.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      List<Certificate> certs = vaultApi.getCertificateVersions(vaultUri, CERTIFICATE_NAME);\n\n      String path = String.format(\"/certificates/%s/versions?%s\", CERTIFICATE_NAME, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertNotNull(certs);\n      assertTrue(certs.size() > 0);\n   }\n\n   public void listCertificateVersionsReturns404() throws InterruptedException {\n      server.enqueue(response404());\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      List<Certificate> certs = vaultApi.getCertificateVersions(vaultUri, CERTIFICATE_NAME);\n\n      String path = String.format(\"/certificates/%s/versions?%s\", CERTIFICATE_NAME, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertTrue(certs.isEmpty());\n   }\n\n   public void updateCertificate() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultupdatecertificate.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      Map<String, String> tags = new HashMap<String, String>();\n      tags.put(\"selfsigned\", \"true\");\n      CertificatePolicy policy = CertificatePolicy.create(null,\n              CERTIFICATE_NAME,\n              IssuerParameters.create(null, \"Self\"),\n              KeyProperties.create(false, 2048, \"RSA\", false),\n              null,\n              null,\n              X509CertificateProperties.create(null, null, null, \"CN=mycertificate.foobar.com\", 12)\n      );\n      CertificateBundle certBundle = vaultApi.updateCertificate(\n              vaultUri,\n              CERTIFICATE_NAME,\n              null,\n              null,\n              policy,\n              tags\n      );\n\n      String path = String.format(\"/certificates/%s?%s\", CERTIFICATE_NAME, apiVersion);\n      assertSent(server, \"PATCH\", path, stringFromResource(\"/vaultupdatecertificaterequestbody.json\"));\n\n      assertNotNull(certBundle);\n      assertTrue(!certBundle.id().isEmpty());\n   }\n\n   public void updateCertificateVersion() {\n      // Update the specific version of a certificate\n\n        /*\n         * XXX -- update using version complains about needing policy (required input), yet\n         * passing in the same policy results in the error:\n         *\n         * Policy cannot be updated with a specific version of a certificate\n         *\n         * Will uncomment/fix once this issue is resolved.\n         *\n         */\n      throw new SkipException(\"azure bug - update using version complains about needing policy\");\n   }\n\n   public void importCertificate() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultimportcertificate.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      String certPem = IMPORTABLE_CERTIFICATE_PEM;\n      CertificateBundle certBundle = null;\n      try {\n         certBundle = vaultApi.importCertificate(\n                 vaultUri,\n                 RECOVERABLE_CERTIFICATE_NAME,\n                 null,\n                 CertificatePolicy.create(\n                         null,\n                         null,\n                         null,\n                         null,\n                         null,\n                         SecretProperties.create(\"application/x-pem-file\"),\n                         null\n                 ),\n                 null,\n                 null,\n                 certPem);\n      } catch (ResourceNotFoundException rnf) {\n         assertNotNull(rnf);\n      }\n\n      String path = String.format(\"/certificates/%s/import?%s\", RECOVERABLE_CERTIFICATE_NAME, apiVersion);\n      assertSent(server, \"POST\", path, stringFromResource(\"/vaultimportcertificaterequestbody.json\"));\n\n      assertNotNull(certBundle);\n      assertTrue(!certBundle.id().isEmpty());\n   }\n\n   public void mergeCertificate() throws InterruptedException {\n      // Merging a certificate is for when a CSR is signed by an external CA\n      server.enqueue(jsonResponse(\"/vaultmergecertificate.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      CertificateAttributes attributes = CertificateAttributes.create(null, true, null, null, null, null);\n      CertificateBundle certBundle = vaultApi.mergeCertificate(\n              vaultUri,\n              CERTIFICATE_NAME,\n              attributes,\n              null,\n              Arrays.asList(mergeX5C)\n      );\n\n      String path = String.format(\"/certificates/%s/pending/merge?%s\", CERTIFICATE_NAME, apiVersion);\n      assertSent(server, \"POST\", path, stringFromResource(\"/vaultmergecertificaterequestbody.json\"));\n\n      assertNotNull(certBundle);\n      assertTrue(!certBundle.attributes().created().toString().isEmpty());\n   }\n\n   public void getCertificateOperation() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultgetcertificateoperation.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      CertificateOperation certOp = vaultApi.getCertificateOperation(vaultUri, CERTIFICATE_NAME);\n\n      String path = String.format(\"/certificates/%s/pending?%s\", CERTIFICATE_NAME, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertNotNull(certOp);\n      assertTrue(!certOp.id().isEmpty());\n   }\n\n   public void getCertificateOperationReturns404() throws InterruptedException {\n      server.enqueue(response404());\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      CertificateOperation certOp = vaultApi.getCertificateOperation(vaultUri, CERTIFICATE_NAME);\n\n      String path = String.format(\"/certificates/%s/pending?%s\", CERTIFICATE_NAME, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertNull(certOp);\n   }\n\n   public void updateCertificateOperation() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultupdatecertificateoperation.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      CertificateOperation certOp = vaultApi.updateCertificateOperation(vaultUri, CERTIFICATE_NAME, true);\n\n      String path = String.format(\"/certificates/%s/pending?%s\", CERTIFICATE_NAME, apiVersion);\n      assertSent(server, \"PATCH\", path, stringFromResource(\"/vaultupdatecertificateoperationrequestbody.json\"));\n\n      assertNotNull(certOp);\n      assertTrue(!certOp.id().isEmpty());\n   }\n\n   public void deleteCertificateOperation() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultdeletecertificateoperation.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      CertificateOperation certOp = vaultApi.deleteCertificateOperation(vaultUri, CERTIFICATE_NAME);\n\n      String path = String.format(\"/certificates/%s/pending?%s\", CERTIFICATE_NAME, apiVersion);\n      assertSent(server, \"DELETE\", path);\n\n      assertNotNull(certOp);\n      assertTrue(!certOp.id().isEmpty());\n   }\n\n   public void deleteCertificateOperationReturns404() throws InterruptedException {\n      server.enqueue(response404());\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      CertificateOperation certOp = vaultApi.deleteCertificateOperation(vaultUri, CERTIFICATE_NAME);\n\n      String path = String.format(\"/certificates/%s/pending?%s\", CERTIFICATE_NAME, apiVersion);\n      assertSent(server, \"DELETE\", path);\n\n      assertNull(certOp);\n   }\n\n   public void setCertificateIssuer() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultsetcertificateissuer.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      AdministrationDetails adminDetail = AdministrationDetails.create(\n              \"adminguy@certsforme.com\",\n              \"Admin\",\n              \"Guy\",\n              \"867-5309\"\n      );\n      List<AdministrationDetails> adminDetails = new ArrayList<AdministrationDetails>();\n      adminDetails.add(adminDetail);\n      OrganizationDetails orgDetails = OrganizationDetails.create(\n              adminDetails,\n              null\n      );\n      IssuerBundle issuer = null;\n      try {\n         issuer = vaultApi.setCertificateIssuer(\n                 vaultUri,\n                 CERTIFICATE_ISSUER_NAME,\n                 null,\n                 IssuerCredentials.create(\"imauser\", \"This1sMyPa55wurD!\"),\n                 orgDetails,\n                 \"GlobalSign\"\n         );\n      } catch (ResourceNotFoundException rnf) {\n         assertNotNull(rnf);\n      }\n\n      String path = String.format(\"/certificates/issuers/%s?%s\", CERTIFICATE_ISSUER_NAME, apiVersion);\n      assertSent(server, \"PUT\", path, stringFromResource(\"/vaultsetcertificateissuerrequestbody.json\"));\n\n      assertNotNull(issuer);\n      assertTrue(!issuer.id().isEmpty());\n   }\n\n   public void listCertificateIssuers() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultlistcertificateissuers.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      List<CertificateIssuer> issuers = vaultApi.getCertificateIssuers(vaultUri);\n\n      String path = String.format(\"/certificates/issuers?%s\", apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertNotNull(issuers);\n      assertTrue(issuers.size() > 0);\n   }\n\n   public void listCertificateIssuersReturns404() throws InterruptedException {\n      server.enqueue(response404());\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      List<CertificateIssuer> issuers = vaultApi.getCertificateIssuers(vaultUri);\n\n      String path = String.format(\"/certificates/issuers?%s\", apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertTrue(issuers.isEmpty());\n   }\n\n   public void getCertificateIssuer() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultgetcertificateissuer.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      IssuerBundle issuer = vaultApi.getCertificateIssuer(vaultUri, CERTIFICATE_ISSUER_NAME);\n\n      String path = String.format(\"/certificates/issuers/%s?%s\", CERTIFICATE_ISSUER_NAME, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertNotNull(issuer);\n      assertTrue(!issuer.id().isEmpty());\n   }\n\n   public void getCertificateIssuerReturns404() throws InterruptedException {\n      server.enqueue(response404());\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      IssuerBundle issuer = vaultApi.getCertificateIssuer(vaultUri, CERTIFICATE_ISSUER_NAME);\n\n      String path = String.format(\"/certificates/issuers/%s?%s\", CERTIFICATE_ISSUER_NAME, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertNull(issuer);\n   }\n\n   public void updateCertificateIssuer() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultupdatecertificateissuer.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      AdministrationDetails adminDetail = AdministrationDetails.create(\n              \"adminguy@certsforme.com\",\n              \"Admin\",\n              \"Guy\",\n              \"867-5309\"\n      );\n      List<AdministrationDetails> adminDetails = new ArrayList<AdministrationDetails>();\n      adminDetails.add(adminDetail);\n      OrganizationDetails orgDetails = OrganizationDetails.create(\n              adminDetails,\n              null\n      );\n      IssuerBundle issuer = vaultApi.updateCertificateIssuer(\n              vaultUri,\n              \"globalsign01\",\n              null,\n              IssuerCredentials.create(\"imauser\", \"CanHa5P455wuRd!\"),\n              orgDetails,\n              \"GlobalSign\"\n      );\n\n      String path = String.format(\"/certificates/issuers/%s?%s\", CERTIFICATE_ISSUER_NAME, apiVersion);\n      assertSent(server, \"PATCH\", path, stringFromResource(\"/vaultupdatecertificateissuerrequestbody.json\"));\n\n      assertNotNull(issuer);\n      assertTrue(!issuer.id().isEmpty());\n   }\n\n   public void deleteCertificateIssuer() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultdeletecertificateissuer.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      IssuerBundle issuer = vaultApi.deleteCertificateIssuer(vaultUri, CERTIFICATE_ISSUER_NAME);\n\n      String path = String.format(\"/certificates/issuers/%s?%s\", CERTIFICATE_ISSUER_NAME, apiVersion);\n      assertSent(server, \"DELETE\", path);\n\n      assertNotNull(issuer);\n      assertTrue(!issuer.id().isEmpty());\n   }\n\n   public void deleteCertificateIssuerReturns404() throws InterruptedException {\n      server.enqueue(response404());\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      IssuerBundle issuer = vaultApi.deleteCertificateIssuer(vaultUri, CERTIFICATE_ISSUER_NAME);\n\n      String path = String.format(\"/certificates/issuers/%s?%s\", CERTIFICATE_ISSUER_NAME, apiVersion);\n      assertSent(server, \"DELETE\", path);\n\n      assertNull(issuer);\n   }\n\n   public void getCertificateContacts() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultgetcertificatecontacts.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      Contacts contacts = vaultApi.getCertificateContacts(vaultUri);\n\n      String path = String.format(\"/certificates/contacts?%s\", apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertNotNull(contacts);\n      assertTrue(!contacts.id().isEmpty());\n      assertTrue(contacts.contacts().size() > 0);\n   }\n\n   public void getCertificateContactsReturns404() throws InterruptedException {\n      server.enqueue(response404());\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      IssuerBundle issuer = null;\n      try {\n         issuer = vaultApi.getCertificateIssuer(vaultUri, CERTIFICATE_ISSUER_NAME);\n      } catch (ResourceNotFoundException rnf) {\n         assertNotNull(rnf);\n      }\n\n      String path = String.format(\"/certificates/issuers/%s?%s\", CERTIFICATE_ISSUER_NAME, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertNull(issuer);\n   }\n\n   public void setCertificateContacts() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultsetcertificatecontacts.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      List<Contact> contactsIn = new ArrayList<Contact>();\n      contactsIn.add(Contact.create(\"foo@bar.com\", \"Foo bar\", \"867-5309\"));\n      Contacts contacts = vaultApi.setCertificateContacts(vaultUri, contactsIn);\n\n      String path = String.format(\"/certificates/contacts?%s\", apiVersion);\n      assertSent(server, \"PUT\", path, stringFromResource(\"/vaultsetcertificatecontactsrequestbody.json\"));\n\n      assertNotNull(contacts);\n      assertTrue(!contacts.id().isEmpty());\n      assertTrue(contacts.contacts().size() > 0);\n   }\n\n   public void deleteCertificateContacts() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultdeletecertificatecontacts.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      Contacts contacts = vaultApi.deleteCertificateContacts(vaultUri);\n\n      String path = String.format(\"/certificates/contacts?%s\", apiVersion);\n      assertSent(server, \"DELETE\", path);\n\n      assertNotNull(contacts);\n      assertTrue(!contacts.id().isEmpty());\n      assertTrue(contacts.contacts().size() > 0);\n   }\n\n   public void deleteCertificateContactsReturns404() throws InterruptedException {\n      server.enqueue(response404());\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      Contacts contacts = vaultApi.deleteCertificateContacts(vaultUri);\n\n      String path = String.format(\"/certificates/contacts?%s\", apiVersion);\n      assertSent(server, \"DELETE\", path);\n\n      assertNull(contacts);\n   }\n\n   public void getCertificatePolicy() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultgetcertificatepolicy.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      CertificatePolicy policy = vaultApi.getCertificatePolicy(vaultUri, CERTIFICATE_NAME);\n\n      String path = String.format(\"/certificates/%s/policy?%s\", CERTIFICATE_NAME, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertNotNull(policy);\n      assertTrue(!policy.id().isEmpty());\n   }\n\n   public void getCertificatePolicyReturns404() throws InterruptedException {\n      server.enqueue(response404());\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      CertificatePolicy policy = vaultApi.getCertificatePolicy(vaultUri, CERTIFICATE_NAME);\n\n      String path = String.format(\"/certificates/%s/policy?%s\", CERTIFICATE_NAME, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertNull(policy);\n   }\n\n   public void updateCertificatePolicy() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/vaultupdatecertificatepolicy.json\").setResponseCode(200));\n      final VaultApi vaultApi = api.getVaultApi(resourceGroup);\n      CertificatePolicy policy = vaultApi.updateCertificatePolicy(\n              vaultUri,\n              CERTIFICATE_NAME,\n              null,\n              null,\n              KeyProperties.create(true, 3072, \"RSA\", false),\n              null,\n              null,\n              null\n      );\n\n      String path = String.format(\"/certificates/%s/policy?%s\", CERTIFICATE_NAME, apiVersion);\n      assertSent(server, \"PATCH\", path, stringFromResource(\"/vaultupdatecertificatepolicyrequestbody.json\"));\n\n      assertNotNull(policy);\n      assertTrue(!policy.id().isEmpty());\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/VirtualMachineApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.jclouds.util.Predicates2.retry;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.util.Strings.isNullOrEmpty;\n\nimport java.net.URI;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.azurecompute.arm.domain.DataDisk;\nimport org.jclouds.azurecompute.arm.domain.HardwareProfile;\nimport org.jclouds.azurecompute.arm.domain.IdReference;\nimport org.jclouds.azurecompute.arm.domain.ImageReference;\nimport org.jclouds.azurecompute.arm.domain.IpConfiguration;\nimport org.jclouds.azurecompute.arm.domain.IpConfigurationProperties;\nimport org.jclouds.azurecompute.arm.domain.ManagedDiskParameters;\nimport org.jclouds.azurecompute.arm.domain.NetworkInterfaceCard;\nimport org.jclouds.azurecompute.arm.domain.NetworkInterfaceCardProperties;\nimport org.jclouds.azurecompute.arm.domain.NetworkProfile;\nimport org.jclouds.azurecompute.arm.domain.NetworkProfile.NetworkInterface;\nimport org.jclouds.azurecompute.arm.domain.NetworkProfile.NetworkInterface.NetworkInterfaceProperties;\nimport org.jclouds.azurecompute.arm.domain.OSDisk;\nimport org.jclouds.azurecompute.arm.domain.OSProfile;\nimport org.jclouds.azurecompute.arm.domain.OSProfile.WindowsConfiguration.WinRM.Protocol;\nimport org.jclouds.azurecompute.arm.domain.OSProfile.WindowsConfiguration.WinRM.ProtocolListener;\nimport org.jclouds.azurecompute.arm.domain.ResourceDefinition;\nimport org.jclouds.azurecompute.arm.domain.Secrets;\nimport org.jclouds.azurecompute.arm.domain.StorageAccountType;\nimport org.jclouds.azurecompute.arm.domain.StorageProfile;\nimport org.jclouds.azurecompute.arm.domain.StorageService;\nimport org.jclouds.azurecompute.arm.domain.Subnet;\nimport org.jclouds.azurecompute.arm.domain.VHD;\nimport org.jclouds.azurecompute.arm.domain.VMSize;\nimport org.jclouds.azurecompute.arm.domain.VaultCertificate;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachine;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineInstance;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineInstance.PowerState;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineProperties;\nimport org.jclouds.azurecompute.arm.functions.ParseJobStatus;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiLiveTest;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.beust.jcommander.internal.Lists;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\n\n@Test(groups = \"live\", testName = \"VirtualMachineApiLiveTest\")\npublic class VirtualMachineApiLiveTest extends BaseAzureComputeApiLiveTest {\n\n   private String subscriptionid;\n   private String vmName;\n   private String nicName;\n   private String virtualNetworkName;\n   private String subnetId;\n\n   @BeforeClass\n   @Override\n   public void setup() {\n      super.setup();\n      subscriptionid = getSubscriptionId();\n\n      createTestResourceGroup();\n\n      virtualNetworkName = String.format(\"vn-%s-%s\", this.getClass().getSimpleName().toLowerCase(), System.getProperty(\"user.name\"));\n\n      // Subnets belong to a virtual network so that needs to be created first\n      assertNotNull(createDefaultVirtualNetwork(resourceGroupName, virtualNetworkName, \"10.2.0.0/16\", LOCATION));\n\n      //Subnet needs to be up & running before NIC can be created\n      String subnetName = String.format(\"s-%s-%s\", this.getClass().getSimpleName().toLowerCase(), System.getProperty(\"user.name\"));\n      Subnet subnet = createDefaultSubnet(resourceGroupName, subnetName, virtualNetworkName, \"10.2.0.0/23\");\n      assertNotNull(subnet);\n      assertNotNull(subnet.id());\n      subnetId = subnet.id();\n\n      NetworkInterfaceCard nic = createNetworkInterfaceCard(resourceGroupName, \"jc-nic-\" + RAND, LOCATION, \"ipConfig-\" + RAND);\n      assertNotNull(nic);\n      nicName = nic.name();\n\n      vmName = String.format(\"%3.24s\", System.getProperty(\"user.name\") + RAND + this.getClass().getSimpleName()).toLowerCase().substring(0, 15);\n   }\n\n   @Test\n   public void testCreate() {\n      VirtualMachine vm = api().createOrUpdate(vmName, LOCATION, getProperties(nicName, null),\n            Collections.<String, String> emptyMap(), null);\n      assertTrue(!vm.name().isEmpty());\n      waitUntilReady(vmName);\n   }\n\n   @Test(dependsOnMethods = \"testCreate\")\n   public void testGet() {\n      VirtualMachine vm = api().get(vmName);\n      assertTrue(!vm.name().isEmpty());\n   }\n\n   @Test(dependsOnMethods = \"testCreate\")\n   public void testGetInstanceView() {\n      VirtualMachineInstance vmi = api().getInstanceDetails(vmName);\n      assertTrue(!vmi.statuses().isEmpty());\n   }\n\n   @Test(dependsOnMethods = \"testGet\")\n   public void testStart() {\n      api().start(vmName);\n      assertTrue(stateReached(vmName, PowerState.RUNNING), \"start operation did not complete in the configured timeout\");\n   }\n\n   @Test(dependsOnMethods = \"testStart\")\n   public void testUpdate() {\n      VirtualMachine vm = api().get(vmName);\n      VirtualMachineProperties oldProperties = vm.properties();\n      StorageProfile oldStorageProfile = oldProperties.storageProfile();\n      \n      DataDisk newDataDisk = DataDisk.builder()\n              .name(vmName + \"new-data-disk\")\n              .diskSizeGB(\"1\")\n              .lun(1)\n              .createOption(DataDisk.DiskCreateOptionTypes.EMPTY)\n              .build();\n      List<DataDisk> oldDataDisks = oldStorageProfile.dataDisks();\n      assertEquals(oldDataDisks.size(), 1);\n\n      ImmutableList<DataDisk> newDataDisks = ImmutableList.<DataDisk> builder().addAll(oldDataDisks).add(newDataDisk).build();\n      StorageProfile newStorageProfile = oldStorageProfile.toBuilder().dataDisks(newDataDisks).build();\n      VirtualMachineProperties newProperties = oldProperties.toBuilder().storageProfile(newStorageProfile).build();\n\n      VirtualMachine newVm = vm.toBuilder().properties(newProperties).build();\n      vm = api().createOrUpdate(vmName, newVm.location(), newVm.properties(), newVm.tags(), newVm.plan());\n\n      assertEquals(vm.properties().storageProfile().dataDisks().size(), oldDataDisks.size() + 1);\n   }\n\n   @Test(dependsOnMethods = \"testRestart\")\n   public void testStop() {\n      api().stop(vmName);\n      assertTrue(stateReached(vmName, PowerState.STOPPED), \"stop operation did not complete in the configured timeout\");\n   }\n\n   @Test(dependsOnMethods = \"testUpdate\")\n   public void testDeallocate() {\n      api().deallocate(vmName);\n      assertTrue(stateReached(vmName, PowerState.DEALLOCATED),\n            \"deallocate operation did not complete in the configured timeout\");\n   }\n\n   @Test(dependsOnMethods = \"testDeallocate\")\n   public void testRestart() {\n      api().start(vmName);\n      assertTrue(stateReached(vmName, PowerState.RUNNING), \"start operation did not complete in the configured timeout\");\n      api().restart(vmName);\n      assertTrue(stateReached(vmName, PowerState.RUNNING), \"restart operation did not complete in the configured timeout\");\n   }\n\n   @Test(dependsOnMethods = \"testCreate\")\n   public void testList() {\n      List<VirtualMachine> list = api().list();\n      final VirtualMachine vm = api().get(vmName);\n\n      boolean vmPresent = Iterables.any(list, new Predicate<VirtualMachine>() {\n         public boolean apply(VirtualMachine input) {\n            return input.name().equals(vm.name());\n         }\n      });\n\n      assertTrue(vmPresent);\n   }\n\n   @Test(dependsOnMethods = \"testCreate\")\n   public void testListAll() {\n      List<VirtualMachine> list = api.getVirtualMachineApi(null).listAll();\n      final VirtualMachine vm = api().get(vmName);\n\n      boolean vmPresent = Iterables.any(list, new Predicate<VirtualMachine>() {\n         public boolean apply(VirtualMachine input) {\n            return input.name().equals(vm.name());\n         }\n      });\n\n      assertTrue(vmPresent);\n   }\n\n   @Test(dependsOnMethods = \"testCreate\")\n   public void testListByLocation() {\n      List<VirtualMachine> list = api.getVirtualMachineApi(null).listByLocation(LOCATION);\n      final VirtualMachine vm = api().get(vmName);\n\n      boolean vmPresent = Iterables.any(list, new Predicate<VirtualMachine>() {\n         public boolean apply(VirtualMachine input) {\n            return input.name().equals(vm.name());\n         }\n      });\n      assertTrue(vmPresent);\n\n      boolean vmsInOtherLocations = Iterables.any(list, new Predicate<VirtualMachine>() {\n         public boolean apply(VirtualMachine input) {\n            return !input.location().equals(LOCATION);\n         }\n      });\n      assertFalse(vmsInOtherLocations);\n\n   }\n\n   @Test(dependsOnMethods = \"testCreate\")\n   public void testListAvailableSizes() {\n      List<VMSize> vmSizes = api().listAvailableSizes(vmName);\n\n      assertNotNull(vmSizes);\n      assertFalse(vmSizes.isEmpty());\n   }\n\n   @Test(dependsOnMethods = \"testRestart\")\n   public void testGeneralize() throws IllegalStateException {\n      api().stop(vmName);\n      assertTrue(stateReached(vmName, PowerState.STOPPED), \"restart operation did not complete in the configured timeout\");\n      api().generalize(vmName);\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Test\n   public void testCapture() throws IllegalStateException {\n      // Capture is only allowed for Blob based VMs, so let's create one VM for this test\n      NetworkInterfaceCard nic = createNetworkInterfaceCard(resourceGroupName, \"capture-nic-\" + RAND, LOCATION, \"ipConfig-\" + RAND);\n      StorageService storageService = createStorageService(resourceGroupName, \"capture\" + RAND, LOCATION);\n      String blob = storageService.storageServiceProperties().primaryEndpoints().get(\"blob\");\n      \n      String captureVmName = \"capture-\" + RAND;\n      api().createOrUpdate(captureVmName, LOCATION, getProperties(nic.name(), blob),\n            Collections.<String, String> emptyMap(), null);\n      waitUntilReady(captureVmName);\n      \n      api().stop(captureVmName);\n      assertTrue(stateReached(captureVmName, PowerState.STOPPED),\n            \"restart operation did not complete in the configured timeout\");\n      api().generalize(captureVmName);\n      \n      URI uri = api().capture(captureVmName, captureVmName, captureVmName);\n      assertNotNull(uri);\n      \n      if (imageAvailablePredicate.apply(uri)) {\n         List<ResourceDefinition> definitions = api.getJobApi().captureStatus(uri);\n         if (definitions != null) {\n            for (ResourceDefinition definition : definitions) {\n               Map<String, String> properties = (Map<String, String>) definition.properties();\n               Object storageObject = properties.get(\"storageProfile\");\n               Map<String, String> properties2 = (Map<String, String>) storageObject;\n               Object osDiskObject = properties2.get(\"osDisk\");\n               Map<String, String> osProperties = (Map<String, String>) osDiskObject;\n               assertNotNull(osProperties.get(\"name\"));\n            }\n         }\n      }\n   }\n\n   @Test(dependsOnMethods = \"testGeneralize\", alwaysRun = true)\n   public void testDelete() throws Exception {\n      URI uri = api().delete(vmName);\n      assertResourceDeleted(uri);\n   }\n\n   private VirtualMachineApi api() {\n      return api.getVirtualMachineApi(resourceGroupName);\n   }\n\n   private VirtualMachineProperties getProperties(String nic, String blob) {\n\n      HardwareProfile hwProf = HardwareProfile.create(\"Standard_D1_v2\");\n      ImageReference imgRef = ImageReference.builder().publisher(\"MicrosoftWindowsServer\")\n              .offer(\"WindowsServer\").sku(\"2008-R2-SP1\").version(\"latest\").build();\n      \n      DataDisk.Builder dataDisk = DataDisk.builder().name(\"data\").diskSizeGB(\"100\").lun(0).createOption(DataDisk.DiskCreateOptionTypes.EMPTY);\n      \n      OSDisk.Builder osDisk = OSDisk.builder()\n              .name(\"os\")\n              .osType(\"Windows\")\n              .caching(DataDisk.CachingTypes.READ_WRITE.toString())\n              .createOption(\"FromImage\");\n      \n      if (blob == null) {\n         osDisk.managedDiskParameters(ManagedDiskParameters.create(null, StorageAccountType.STANDARD_LRS.toString()));\n      } else {\n         osDisk.vhd(VHD.create(blob + \"vhds/\" + vmName + \".vhd\"));\n         dataDisk.vhd(VHD.create(blob + \"vhds/\" + vmName + \"data.vhd\"));\n      }\n\n      StorageProfile storageProfile = StorageProfile.create(imgRef, osDisk.build(), ImmutableList.of(dataDisk.build()));\n\n      List<Secrets> secrets = null;\n      OSProfile.WindowsConfiguration.WinRM winRm = null;\n      if (!isNullOrEmpty(vaultResourceGroup) && !isNullOrEmpty(vaultName) && !isNullOrEmpty(vaultCertificateUrl)) {\n          List<ProtocolListener> listeners = Lists.newArrayList();\n\n          listeners.add(OSProfile.WindowsConfiguration.WinRM.ProtocolListener.create(Protocol.HTTPS, vaultCertificateUrl));\n          listeners.add(OSProfile.WindowsConfiguration.WinRM.ProtocolListener.create(Protocol.HTTP, null));\n\n          winRm = OSProfile.WindowsConfiguration.WinRM.create(listeners);\n          VaultCertificate vaultCertificate = VaultCertificate.create(vaultCertificateUrl, vaultName);\n          secrets = ImmutableList.of(Secrets.create(Secrets.SourceVault.create(String.format(\"%s/providers/Microsoft.KeyVault/vaults/%s\",\n                            api.getResourceGroupApi().get(vaultResourceGroup).id(), vaultName)),\n                    ImmutableList.of(vaultCertificate)));\n      }\n      OSProfile.WindowsConfiguration windowsConfig = OSProfile.WindowsConfiguration.create(true, winRm, null, true);\n      OSProfile osProfile = OSProfile.create(vmName, \"azureuser\", \"RFe3&432dg\", null, null, windowsConfig, secrets);\n      NetworkInterface networkInterface =\n            NetworkInterface.create(\"/subscriptions/\" + subscriptionid +\n                      \"/resourceGroups/\" + resourceGroupName + \"/providers/Microsoft.Network/networkInterfaces/\"\n                      + nic, NetworkInterfaceProperties.create(true));\n      List<NetworkInterface> networkInterfaces = new ArrayList<NetworkInterface>();\n      networkInterfaces.add(networkInterface);\n      NetworkProfile networkProfile = NetworkProfile.create(networkInterfaces);\n      VirtualMachineProperties properties = VirtualMachineProperties.create(null,\n              null, null, hwProf, storageProfile, osProfile, networkProfile, null, VirtualMachineProperties.ProvisioningState.CREATING);\n      return properties;\n   }\n\n   private NetworkInterfaceCard createNetworkInterfaceCard(final String resourceGroupName, String networkInterfaceCardName, String locationName, String ipConfigurationName) {\n      //Create properties object\n      final NetworkInterfaceCardProperties networkInterfaceCardProperties = NetworkInterfaceCardProperties\n            .builder().ipConfigurations(Arrays.asList(IpConfiguration.create(ipConfigurationName, null, null,\n                  IpConfigurationProperties\n                        .create(null, null, \"Dynamic\", IdReference.create(subnetId), null, null, null, Boolean.TRUE))))\n            .build();\n\n      final Map<String, String> tags = ImmutableMap.of(\"jclouds\", \"livetest\");\n      return api.getNetworkInterfaceCardApi(resourceGroupName).createOrUpdate(networkInterfaceCardName, locationName, networkInterfaceCardProperties, tags);\n   }\n   \n   private StorageService createStorageService(final String resourceGroupName, final String storageServiceName,\n         final String location) {\n      URI uri = api.getStorageAccountApi(resourceGroupName).create(storageServiceName, location,\n            ImmutableMap.of(\"property_name\", \"property_value\"),\n            ImmutableMap.of(\"accountType\", StorageService.AccountType.Standard_LRS.toString()));\n      if (uri != null) {\n         assertTrue(uri.toString().contains(\"api-version\"));\n\n         boolean jobDone = retry(new Predicate<URI>() {\n            @Override\n            public boolean apply(final URI uri) {\n               return ParseJobStatus.JobStatus.DONE == api.getJobApi().jobStatus(uri);\n            }\n         }, 60 * 1 * 1000 /* 1 minute timeout */).apply(uri);\n         assertTrue(jobDone, \"create operation did not complete in the configured timeout\");\n      }\n      return api.getStorageAccountApi(resourceGroupName).get(storageServiceName);\n   }\n\n   private boolean waitForState(String name, final PowerState state) {\n      return api().getInstanceDetails(name).powerState().equals(state);\n   }\n   \n   private void waitUntilReady(String vmName) {\n      boolean ready = retry(new Predicate<String>() {\n         @Override\n         public boolean apply(String name) {\n            return !api().get(name).properties().provisioningState().equals(VirtualMachineProperties.ProvisioningState.CREATING);\n         }\n      }, 60 * 20 * 1000).apply(vmName);\n      assertTrue(ready, \"createOrUpdate operation did not complete in the configured timeout\");\n\n      VirtualMachineProperties.ProvisioningState status = api().get(vmName).properties().provisioningState();\n      // Cannot be creating anymore. Should be succeeded or running but not failed.\n      assertThat(status).isNotEqualTo(VirtualMachineProperties.ProvisioningState.CREATING);\n      assertThat(status).isNotEqualTo(VirtualMachineProperties.ProvisioningState.FAILED);\n   }\n\n   private boolean stateReached(String vmName, final PowerState state) {\n      return retry(new Predicate<String>() {\n         @Override\n         public boolean apply(String name) {\n            return waitForState(name, state);\n         }\n      }, 60 * 4 * 1000).apply(vmName);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/VirtualMachineApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport static com.google.common.collect.Iterables.isEmpty;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.text.DateFormat;\nimport java.text.SimpleDateFormat;\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.List;\n\nimport okhttp3.mockwebserver.MockResponse;\n\nimport org.jclouds.azurecompute.arm.domain.DataDisk;\nimport org.jclouds.azurecompute.arm.domain.DiagnosticsProfile;\nimport org.jclouds.azurecompute.arm.domain.HardwareProfile;\nimport org.jclouds.azurecompute.arm.domain.IdReference;\nimport org.jclouds.azurecompute.arm.domain.ImageReference;\nimport org.jclouds.azurecompute.arm.domain.ManagedDiskParameters;\nimport org.jclouds.azurecompute.arm.domain.NetworkProfile;\nimport org.jclouds.azurecompute.arm.domain.NetworkProfile.NetworkInterface;\nimport org.jclouds.azurecompute.arm.domain.OSDisk;\nimport org.jclouds.azurecompute.arm.domain.OSProfile;\nimport org.jclouds.azurecompute.arm.domain.OSProfile.LinuxConfiguration;\nimport org.jclouds.azurecompute.arm.domain.OSProfile.WindowsConfiguration.AdditionalUnattendContent;\nimport org.jclouds.azurecompute.arm.domain.OSProfile.WindowsConfiguration.WinRM.Protocol;\nimport org.jclouds.azurecompute.arm.domain.Plan;\nimport org.jclouds.azurecompute.arm.domain.Secrets;\nimport org.jclouds.azurecompute.arm.domain.Secrets.SourceVault;\nimport org.jclouds.azurecompute.arm.domain.Status;\nimport org.jclouds.azurecompute.arm.domain.StorageProfile;\nimport org.jclouds.azurecompute.arm.domain.VHD;\nimport org.jclouds.azurecompute.arm.domain.VMSize;\nimport org.jclouds.azurecompute.arm.domain.VaultCertificate;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachine;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineInstance;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineProperties;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiMockTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\n\n@Test(groups = \"unit\", testName = \"VirtualMachineApiMockTest\", singleThreaded = true)\npublic class VirtualMachineApiMockTest extends BaseAzureComputeApiMockTest {\n\n   public void testGet() throws Exception {\n      server.enqueue(jsonResponse(\"/virtualmachine.json\"));\n      final VirtualMachineApi vmAPI = api.getVirtualMachineApi(\"groupname\");\n      assertEquals(vmAPI.get(\"windowsmachine\"),\n            getVM(Plan.create(\"thinkboxsoftware\", \"deadline-slave-7-2\", \"deadline7-2\")));\n      assertSent(server, \"GET\", \"/subscriptions/SUBSCRIPTIONID/resourceGroups/groupname/providers/Microsoft.Compute\"\n            + \"/virtualMachines/windowsmachine?api-version=2018-06-01\");\n   }\n\n   public void testGetEmpty() throws Exception {\n      server.enqueue(new MockResponse().setResponseCode(404));\n      final VirtualMachineApi vmAPI = api.getVirtualMachineApi(\"groupname\");\n      assertNull(vmAPI.get(\"windowsmachine\"));\n      assertSent(server, \"GET\", \"/subscriptions/SUBSCRIPTIONID/resourceGroups/groupname/providers/Microsoft.Compute\"\n            + \"/virtualMachines/windowsmachine?api-version=2018-06-01\");\n   }\n\n   public void testGetInstanceDetails() throws Exception {\n      server.enqueue(jsonResponse(\"/virtualmachineInstance.json\"));\n      final VirtualMachineApi vmAPI = api.getVirtualMachineApi(\"groupname\");\n      VirtualMachineInstance actual = vmAPI.getInstanceDetails(\"windowsmachine\");\n      VirtualMachineInstance expected = getVMInstance();\n\n      assertEquals(actual.statuses().get(0).code(), expected.statuses().get(0).code());\n      assertEquals(actual.statuses().get(0).displayStatus(), expected.statuses().get(0).displayStatus());\n      assertEquals(actual.statuses().get(0).level(), expected.statuses().get(0).level());\n      // assertEquals(actual.statuses().get(0).time().toString(),\n      // expected.statuses().get(0).time().toString());\n      assertSent(server, \"GET\", \"/subscriptions/SUBSCRIPTIONID/resourceGroups/groupname/providers/Microsoft.Compute\"\n            + \"/virtualMachines/windowsmachine/instanceView?api-version=2018-06-01\");\n   }\n\n   public void testGetInstanceDetailsEmpty() throws Exception {\n      server.enqueue(new MockResponse().setResponseCode(404));\n      final VirtualMachineApi vmAPI = api.getVirtualMachineApi(\"groupname\");\n      assertNull(vmAPI.getInstanceDetails(\"windowsmachine\"));\n      assertSent(server, \"GET\", \"/subscriptions/SUBSCRIPTIONID/resourceGroups/groupname/providers/Microsoft.Compute\"\n            + \"/virtualMachines/windowsmachine/instanceView?api-version=2018-06-01\");\n   }\n\n   public void testList() throws Exception {\n      server.enqueue(jsonResponse(\"/virtualmachinesinresourcegroup.json\"));\n      final VirtualMachineApi vmAPI = api.getVirtualMachineApi(\"groupname\");\n      assertEquals(vmAPI.list(), getVMList());\n      assertSent(server, \"GET\", \"/subscriptions/SUBSCRIPTIONID/resourceGroups/groupname/providers/Microsoft.Compute\"\n            + \"/virtualMachines?api-version=2018-06-01\");\n   }\n\n   public void testListEmpty() throws Exception {\n      server.enqueue(new MockResponse().setResponseCode(404));\n      final VirtualMachineApi vmAPI = api.getVirtualMachineApi(\"groupname\");\n      assertTrue(isEmpty(vmAPI.list()));\n      assertSent(server, \"GET\", \"/subscriptions/SUBSCRIPTIONID/resourceGroups/groupname/providers/Microsoft.Compute\"\n            + \"/virtualMachines?api-version=2018-06-01\");\n   }\n\n   public void testListAll() throws Exception {\n      server.enqueue(jsonResponse(\"/virtualmachinesinsubscription.json\"));\n      final VirtualMachineApi vmAPI = api.getVirtualMachineApi(null);\n      assertEquals(vmAPI.listAll(), getVMListAll());\n      assertSent(server, \"GET\",\n            \"/subscriptions/SUBSCRIPTIONID/providers/Microsoft.Compute/virtualMachines?api-version=2018-06-01\");\n   }\n\n   public void testListByLocation() throws Exception {\n      server.enqueue(jsonResponse(\"/virtualmachinesinlocation.json\"));\n      final VirtualMachineApi vmAPI = api.getVirtualMachineApi(null);\n      assertEquals(vmAPI.listByLocation(\"testlocation\"), getVMListByLocation()); // TODO bylocation\n      assertSent(server, \"GET\", \"/subscriptions/SUBSCRIPTIONID/providers/Microsoft.Compute/locations/testlocation\"\n            + \"/virtualMachines?api-version=2018-06-01\");\n   }\n\n   public void testListAvailableSizes() throws Exception {\n      server.enqueue(jsonResponse(\"/virtualmachineavailablesizes.json\"));\n      final VirtualMachineApi vmAPI = api.getVirtualMachineApi(\"groupname\");\n      assertEquals(vmAPI.listAvailableSizes(\"windowsmachine\"), ImmutableList.of(VMSize.create(\"Standard_A0\", 1,\n            1047552, 20480, 768, 1), VMSize.create(\"Standard_A1\", 1,\n            1047552, 71680, 1792, 2)));\n      assertSent(server, \"GET\", \"/subscriptions/SUBSCRIPTIONID/resourceGroups/groupname/providers/Microsoft.Compute\"\n            + \"/virtualMachines/windowsmachine/vmSizes?api-version=2018-06-01\");\n   }\n\n   public void testCreateWithPlan() throws Exception {\n      server.enqueue(jsonResponse(\"/createvirtualmachineresponse.json\"));\n      Plan plan = Plan.create(\"thinkboxsoftware\", \"deadline-slave-7-2\", \"deadline7-2\");\n      final VirtualMachineApi vmAPI = api.getVirtualMachineApi(\"groupname\");\n      VirtualMachine vm = vmAPI\n            .createOrUpdate(\"windowsmachine\", \"westus\", getVMWithManagedDisksProperties(), ImmutableMap.of(\"foo\", \"bar\"), plan);\n      assertEquals(vm, getVM(plan));\n      assertSent(\n            server,\n            \"PUT\",\n            \"/subscriptions/SUBSCRIPTIONID/resourceGroups/groupname/providers/Microsoft.Compute\"\n                  + \"/virtualMachines/windowsmachine?validating=false&api-version=2018-06-01\",\n            \"{\\\"location\\\":\\\"westus\\\",\\\"properties\\\":\"\n                  + \"{\\\"vmId\\\":\\\"27ee085b-d707-xxxx-yyyy-2370e2eb1cc1\\\",\\\"licenseType\\\":\\\"Windows_Server\\\",\"\n                  + \"\\\"availabilitySet\\\":{\\\"id\\\":\\\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/availabilitySets/myAVSet\\\"},\"\n                  + \"\\\"hardwareProfile\\\":{\\\"vmSize\\\":\\\"Standard_D1\\\"},\"\n                  + \"\\\"storageProfile\\\":{\\\"imageReference\\\":{\\\"id\\\":\\\"/subscriptions/SUBSCRIPTIONID/providers/Microsoft.Compute/locations/westus/publishers/MicrosoftWindowsServerEssentials/artifactype/vmimage/offers/OFFER/skus/OFFER/versions/latest\\\",\"\n                  + \"\\\"publisher\\\":\\\"publisher\\\",\\\"offer\\\":\\\"OFFER\\\",\\\"sku\\\":\\\"sku\\\",\\\"version\\\":\\\"ver\\\"},\"\n                  + \"\\\"osDisk\\\":{\\\"osType\\\":\\\"Windows\\\",\\\"name\\\":\\\"windowsmachine\\\",\"\n                  + \"\\\"caching\\\":\\\"ReadWrite\\\",\\\"createOption\\\":\\\"FromImage\\\",\"\n                  + \"\\\"managedDisk\\\":{\\\"id\\\":\\\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/osDisk\\\",\\\"storageAccountType\\\":\\\"Standard_LRS\\\"}},\"\n                  + \"\\\"dataDisks\\\":[{\\\"name\\\":\\\"mydatadisk1\\\",\\\"diskSizeGB\\\":\\\"1\\\",\\\"lun\\\":0,\\\"createOption\\\":\\\"Empty\\\",\\\"caching\\\":\\\"ReadWrite\\\",\\\"managedDisk\\\":{\\\"id\\\":\\\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/osDisk\\\",\\\"storageAccountType\\\":\\\"Standard_LRS\\\"}}]},\"\n                  + \"\\\"osProfile\\\":{\\\"computerName\\\":\\\"windowsmachine\\\",\\\"adminUsername\\\":\\\"azureuser\\\",\\\"adminPassword\\\":\\\"password\\\",\\\"customData\\\":\\\"\\\",\\\"windowsConfiguration\\\":{\\\"provisionVMAgent\\\":false,\"\n                  + \"\\\"winRM\\\":{\\\"listeners\\\":[{\\\"protocol\\\":\\\"https\\\",\\\"certificateUrl\\\":\\\"url-to-certificate\\\"}]},\\\"additionalUnattendContent\\\":[{\\\"passName\\\":\\\"oobesystem\\\",\\\"componentName\\\":\\\"Microsoft-Windows-Shell-Setup\\\",\\\"settingName\\\":\\\"FirstLogonCommands\\\",\\\"content\\\":\\\"<XML unattend content>\\\"}],\"\n                  + \"\\\"enableAutomaticUpdates\\\":true},\"\n                  + \"\\\"secrets\\\":[{\\\"sourceVault\\\":{\\\"id\\\":\\\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myresourcegroup1/providers/Microsoft.KeyVault/vaults/myvault1\\\"},\\\"vaultCertificates\\\":[{\\\"certificateUrl\\\":\\\"https://myvault1.vault.azure.net/secrets/SECRETNAME/SECRETVERSION\\\",\\\"certificateStore\\\":\\\"CERTIFICATESTORENAME\\\"}]}]},\"\n                  + \"\\\"networkProfile\\\":{\\\"networkInterfaces\\\":[{\\\"id\\\":\\\"/subscriptions/SUBSCRIPTIONID/resourceGroups/groupname/providers/Microsoft.Network/networkInterfaces/windowsmachine167\\\"}]},\"\n                  + \"\\\"diagnosticsProfile\\\":{\\\"bootDiagnostics\\\":{\\\"enabled\\\":true,\\\"storageUri\\\":\\\"https://groupname2760.blob.core.windows.net/\\\"}},\\\"provisioningState\\\":\\\"CREATING\\\"},\"\n                  + \"\\\"tags\\\":{\\\"foo\\\":\\\"bar\\\"},\"\n                  + \"\\\"plan\\\":{\\\"name\\\":\\\"deadline-slave-7-2\\\",\\\"publisher\\\":\\\"thinkboxsoftware\\\",\\\"product\\\":\\\"deadline7-2\\\"}}\");\n   }\n\n   // See https://docs.microsoft.com/en-us/rest/api/compute/virtualmachines/virtualmachines-create-or-update\n   // for where part of the example json response comes from. Unfortunately examples in the microsoft docs\n   // are not valid json (e.g. missing commas, illegal quotes). Therefore this example merges the original \n   // real-world example (presumably taken from the jclouds wire log), and snippets from the microsoft docs.\n   public void testCreate() throws Exception {\n      server.enqueue(jsonResponse(\"/createvirtualmachineresponse.json\"));\n\n      final VirtualMachineApi vmAPI = api.getVirtualMachineApi(\"groupname\");\n      VirtualMachine vm = vmAPI.createOrUpdate(\"windowsmachine\", \"westus\", getVMWithManagedDisksProperties(), ImmutableMap.of(\"foo\", \"bar\"), null);\n      assertEquals(vm, getVM());\n      assertSent(\n            server,\n            \"PUT\",\n            \"/subscriptions/SUBSCRIPTIONID/resourceGroups/groupname/providers/Microsoft.Compute\"\n                  + \"/virtualMachines/windowsmachine?validating=false&api-version=2018-06-01\",\n            \"{\\\"location\\\":\\\"westus\\\",\\\"properties\\\":\"\n                  + \"{\\\"vmId\\\":\\\"27ee085b-d707-xxxx-yyyy-2370e2eb1cc1\\\",\\\"licenseType\\\":\\\"Windows_Server\\\",\"\n                  + \"\\\"availabilitySet\\\":{\\\"id\\\":\\\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/availabilitySets/myAVSet\\\"},\"\n                  + \"\\\"hardwareProfile\\\":{\\\"vmSize\\\":\\\"Standard_D1\\\"},\"\n                  + \"\\\"storageProfile\\\":{\\\"imageReference\\\":{\\\"id\\\":\\\"/subscriptions/SUBSCRIPTIONID/providers/Microsoft.Compute/locations/westus/publishers/MicrosoftWindowsServerEssentials/artifactype/vmimage/offers/OFFER/skus/OFFER/versions/latest\\\",\"\n                  + \"\\\"publisher\\\":\\\"publisher\\\",\\\"offer\\\":\\\"OFFER\\\",\\\"sku\\\":\\\"sku\\\",\\\"version\\\":\\\"ver\\\"},\"\n                  + \"\\\"osDisk\\\":{\\\"osType\\\":\\\"Windows\\\",\\\"name\\\":\\\"windowsmachine\\\",\"\n                  + \"\\\"caching\\\":\\\"ReadWrite\\\",\\\"createOption\\\":\\\"FromImage\\\",\"\n                  + \"\\\"managedDisk\\\":{\\\"id\\\":\\\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/osDisk\\\",\\\"storageAccountType\\\":\\\"Standard_LRS\\\"}},\"\n                  + \"\\\"dataDisks\\\":[{\\\"name\\\":\\\"mydatadisk1\\\",\\\"diskSizeGB\\\":\\\"1\\\",\\\"lun\\\":0,\\\"createOption\\\":\\\"Empty\\\",\\\"caching\\\":\\\"ReadWrite\\\",\\\"managedDisk\\\":{\\\"id\\\":\\\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/osDisk\\\",\\\"storageAccountType\\\":\\\"Standard_LRS\\\"}}]},\"\n                  + \"\\\"osProfile\\\":{\\\"computerName\\\":\\\"windowsmachine\\\",\\\"adminUsername\\\":\\\"azureuser\\\",\\\"adminPassword\\\":\\\"password\\\",\\\"customData\\\":\\\"\\\",\\\"windowsConfiguration\\\":{\\\"provisionVMAgent\\\":false,\"\n                  + \"\\\"winRM\\\":{\\\"listeners\\\":[{\\\"protocol\\\":\\\"https\\\",\\\"certificateUrl\\\":\\\"url-to-certificate\\\"}]},\\\"additionalUnattendContent\\\":[{\\\"passName\\\":\\\"oobesystem\\\",\\\"componentName\\\":\\\"Microsoft-Windows-Shell-Setup\\\",\\\"settingName\\\":\\\"FirstLogonCommands\\\",\\\"content\\\":\\\"<XML unattend content>\\\"}],\"\n                  + \"\\\"enableAutomaticUpdates\\\":true},\"\n                  + \"\\\"secrets\\\":[{\\\"sourceVault\\\":{\\\"id\\\":\\\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myresourcegroup1/providers/Microsoft.KeyVault/vaults/myvault1\\\"},\\\"vaultCertificates\\\":[{\\\"certificateUrl\\\":\\\"https://myvault1.vault.azure.net/secrets/SECRETNAME/SECRETVERSION\\\",\\\"certificateStore\\\":\\\"CERTIFICATESTORENAME\\\"}]}]},\"\n                  + \"\\\"networkProfile\\\":{\\\"networkInterfaces\\\":[{\\\"id\\\":\\\"/subscriptions/SUBSCRIPTIONID/resourceGroups/groupname/providers/Microsoft.Network/networkInterfaces/windowsmachine167\\\"}]},\"\n                  + \"\\\"diagnosticsProfile\\\":{\\\"bootDiagnostics\\\":{\\\"enabled\\\":true,\\\"storageUri\\\":\\\"https://groupname2760.blob.core.windows.net/\\\"}},\\\"provisioningState\\\":\\\"CREATING\\\"},\"\n                  + \"\\\"tags\\\":{\\\"foo\\\":\\\"bar\\\"}}\");\n   }\n\n   public void testDeleteReturns404() throws Exception {\n      server.enqueue(response404());\n\n      final VirtualMachineApi vmAPI = api.getVirtualMachineApi(\"groupname\");\n\n      URI uri = vmAPI.delete(\"windowsmachine\");\n\n      assertEquals(server.getRequestCount(), 1);\n      assertNull(uri);\n\n      assertSent(server, \"DELETE\", \"/subscriptions/SUBSCRIPTIONID/resourceGroups/groupname/providers/Microsoft.Compute\"\n            + \"/virtualMachines/windowsmachine?api-version=2018-06-01\");\n   }\n\n   public void testDelete() throws Exception {\n      server.enqueue(response202WithHeader());\n\n      final VirtualMachineApi vmAPI = api.getVirtualMachineApi(\"groupname\");\n\n      URI uri = vmAPI.delete(\"windowsmachine\");\n\n      assertEquals(server.getRequestCount(), 1);\n      assertNotNull(uri);\n\n      assertSent(server, \"DELETE\", \"/subscriptions/SUBSCRIPTIONID/resourceGroups/groupname/providers/Microsoft.Compute\"\n            + \"/virtualMachines/windowsmachine?api-version=2018-06-01\");\n   }\n\n   public void testStart() throws Exception {\n      server.enqueue(response202WithHeader());\n\n      final VirtualMachineApi vmAPI = api.getVirtualMachineApi(\"groupname\");\n\n      vmAPI.start(\"windowsmachine\");\n\n      assertSent(server, \"POST\", \"/subscriptions/SUBSCRIPTIONID/resourceGroups/groupname/providers/Microsoft.Compute\"\n            + \"/virtualMachines/windowsmachine/start?api-version=2018-06-01\");\n   }\n\n   public void testRestart() throws Exception {\n      server.enqueue(response202WithHeader());\n\n      final VirtualMachineApi vmAPI = api.getVirtualMachineApi(\"groupname\");\n\n      vmAPI.restart(\"windowsmachine\");\n\n      assertSent(server, \"POST\", \"/subscriptions/SUBSCRIPTIONID/resourceGroups/groupname/providers/Microsoft.Compute\"\n            + \"/virtualMachines/windowsmachine/restart?api-version=2018-06-01\");\n   }\n\n   public void testStop() throws Exception {\n      server.enqueue(response202WithHeader());\n\n      final VirtualMachineApi vmAPI = api.getVirtualMachineApi(\"groupname\");\n\n      vmAPI.stop(\"windowsmachine\");\n\n      assertSent(server, \"POST\", \"/subscriptions/SUBSCRIPTIONID/resourceGroups/groupname/providers/Microsoft.Compute\"\n            + \"/virtualMachines/windowsmachine/powerOff?api-version=2018-06-01\");\n   }\n\n   public void testDeallocate() throws Exception {\n      server.enqueue(response202WithHeader());\n\n      final VirtualMachineApi vmAPI = api.getVirtualMachineApi(\"groupname\");\n\n      vmAPI.deallocate(\"windowsmachine\");\n\n      assertSent(server, \"POST\", \"/subscriptions/SUBSCRIPTIONID/resourceGroups/groupname/providers/Microsoft.Compute\"\n            + \"/virtualMachines/windowsmachine/deallocate?api-version=2018-06-01\");\n   }\n\n   public void testGeneralize() throws Exception {\n      server.enqueue(new MockResponse().setResponseCode(200));\n      final VirtualMachineApi vmAPI = api.getVirtualMachineApi(\"groupname\");\n      vmAPI.generalize(\"vm\"); // IllegalStateException if failed\n      assertSent(server, \"POST\", \"/subscriptions/SUBSCRIPTIONID/resourceGroups/groupname/providers/Microsoft.Compute\"\n            + \"/virtualMachines/vm/generalize?api-version=2018-06-01\");\n   }\n\n   public void testCapture() throws Exception {\n      server.enqueue(response202WithHeader());\n\n      final VirtualMachineApi vmAPI = api.getVirtualMachineApi(\"groupname\");\n      URI uri = vmAPI.capture(\"vm\", \"prefix\", \"container\");\n      assertNotNull(uri);\n      assertSent(server, \"POST\", \"/subscriptions/SUBSCRIPTIONID/resourceGroups/groupname/providers/Microsoft.Compute\"\n            + \"/virtualMachines/vm/capture?api-version=2018-06-01\",\n            \"{\\\"vhdPrefix\\\":\\\"prefix\\\",\\\"destinationContainerName\\\":\\\"container\\\",\\\"overwriteVhds\\\":\\\"true\\\"}\");\n   }\n\n   public void testCapture404() throws Exception {\n      server.enqueue(response404());\n\n      final VirtualMachineApi vmAPI = api.getVirtualMachineApi(\"groupname\");\n      URI uri = vmAPI.capture(\"vm\", \"prefix\", \"container\");\n      assertNull(uri);\n      assertSent(server, \"POST\", \"/subscriptions/SUBSCRIPTIONID/resourceGroups/groupname/providers/Microsoft.Compute\"\n            + \"/virtualMachines/vm/capture?api-version=2018-06-01\",\n            \"{\\\"vhdPrefix\\\":\\\"prefix\\\",\\\"destinationContainerName\\\":\\\"container\\\",\\\"overwriteVhds\\\":\\\"true\\\"}\");\n   }\n\n   private VirtualMachineProperties getVMWithBlobDisksProperties() {\n      String licenseType = \"Windows_Server\";\n      IdReference availabilitySet = IdReference.create(\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/availabilitySets/myAVSet\");\n      HardwareProfile hwProf = HardwareProfile.create(\"Standard_D1\");\n      ImageReference imgRef = ImageReference.builder().publisher(\"publisher\").offer(\"OFFER\").sku(\"sku\").version(\"ver\")\n            .customImageId(\"/subscriptions/SUBSCRIPTIONID/providers/Microsoft.Compute/locations/westus/publishers/MicrosoftWindowsServerEssentials/artifactype/vmimage/offers/OFFER/skus/OFFER/versions/latest\")\n            .build();\n      VHD vhd = VHD.create(\"https://groupname2760.blob.core.windows.net/vhds/windowsmachine201624102936.vhd\");\n      List<DataDisk> dataDisks = ImmutableList.of(\n            DataDisk.create(\"mydatadisk1\", \"1\", 0, VHD.create(\"http://mystorage1.blob.core.windows.net/vhds/mydatadisk1.vhd\"),\n                  null, \"Empty\", null, null, null));\n      ManagedDiskParameters managedDiskParameters = ManagedDiskParameters.create(\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/osDisk\",\n            \"Standard_LRS\");\n      OSDisk osDisk = OSDisk.create(\"Windows\", \"windowsmachine\", vhd, \"ReadWrite\", \"FromImage\", null, managedDiskParameters, null);\n      StorageProfile storageProfile = StorageProfile.create(imgRef, osDisk, dataDisks);\n      LinuxConfiguration linuxConfig = null;\n      OSProfile.WindowsConfiguration.WinRM winrm = OSProfile.WindowsConfiguration.WinRM.create(\n            ImmutableList.of(\n                  OSProfile.WindowsConfiguration.WinRM.ProtocolListener.create(Protocol.HTTPS, \"url-to-certificate\")));\n      List<AdditionalUnattendContent> additionalUnattendContent = ImmutableList.of(\n            AdditionalUnattendContent.create(\"oobesystem\", \"Microsoft-Windows-Shell-Setup\", \"FirstLogonCommands\", \"<XML unattend content>\"));\n      OSProfile.WindowsConfiguration windowsConfig = OSProfile.WindowsConfiguration.create(false, winrm, additionalUnattendContent, true);\n      List<Secrets> secrets =  ImmutableList.of(\n            Secrets.create(SourceVault.create(\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myresourcegroup1/providers/Microsoft.KeyVault/vaults/myvault1\"),\n                  ImmutableList.of(VaultCertificate.create(\"https://myvault1.vault.azure.net/secrets/SECRETNAME/SECRETVERSION\", \"CERTIFICATESTORENAME\"))));\n      OSProfile osProfile = OSProfile.create(\"windowsmachine\", \"azureuser\", \"password\", \"\", linuxConfig, windowsConfig, secrets);\n      NetworkInterface networkInterface = NetworkInterface.create(\"/subscriptions/SUBSCRIPTIONID\"\n            + \"/resourceGroups/groupname/providers/Microsoft.Network/networkInterfaces/\" + \"windowsmachine167\", null);\n      List<NetworkInterface> networkInterfaces = new ArrayList<NetworkInterface>();\n      networkInterfaces.add(networkInterface);\n      NetworkProfile networkProfile = NetworkProfile.create(networkInterfaces);\n      DiagnosticsProfile.BootDiagnostics bootDiagnostics = DiagnosticsProfile.BootDiagnostics.create(true,\n            \"https://groupname2760.blob.core.windows.net/\");\n      DiagnosticsProfile diagnosticsProfile = DiagnosticsProfile.create(bootDiagnostics);\n      VirtualMachineProperties properties = VirtualMachineProperties.create(\"27ee085b-d707-xxxx-yyyy-2370e2eb1cc1\",\n            licenseType, availabilitySet, hwProf, storageProfile, osProfile, networkProfile, diagnosticsProfile,\n            VirtualMachineProperties.ProvisioningState.CREATING);\n      return properties;\n   }\n\n   private VirtualMachineProperties getVMWithManagedDisksProperties() {\n      String licenseType = \"Windows_Server\";\n      IdReference availabilitySet = IdReference.create(\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/availabilitySets/myAVSet\");\n      HardwareProfile hwProf = HardwareProfile.create(\"Standard_D1\");\n      ImageReference imgRef = ImageReference.builder().publisher(\"publisher\").offer(\"OFFER\").sku(\"sku\").version(\"ver\")\n            .customImageId(\"/subscriptions/SUBSCRIPTIONID/providers/Microsoft.Compute/locations/westus/publishers/MicrosoftWindowsServerEssentials/artifactype/vmimage/offers/OFFER/skus/OFFER/versions/latest\")\n            .build();\n      ManagedDiskParameters managedDiskParameters = ManagedDiskParameters.create(\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/osDisk\",\n            \"Standard_LRS\");\n      List<DataDisk> dataDisks = ImmutableList.of(\n              DataDisk.builder().name(\"mydatadisk1\").diskSizeGB(\"1\").lun(0).managedDiskParameters(managedDiskParameters).createOption(DataDisk.DiskCreateOptionTypes.EMPTY).caching(DataDisk.CachingTypes.READ_WRITE).build());\n      OSDisk osDisk = OSDisk.builder().osType(\"Windows\").name(\"windowsmachine\").caching(\"ReadWrite\").createOption(\"FromImage\").managedDiskParameters(managedDiskParameters).build();\n      StorageProfile storageProfile = StorageProfile.create(imgRef, osDisk, dataDisks);\n      LinuxConfiguration linuxConfig = null;\n      OSProfile.WindowsConfiguration.WinRM winrm = OSProfile.WindowsConfiguration.WinRM.create(\n            ImmutableList.of(\n                  OSProfile.WindowsConfiguration.WinRM.ProtocolListener.create(Protocol.HTTPS, \"url-to-certificate\")));\n      List<AdditionalUnattendContent> additionalUnattendContent = ImmutableList.of(\n            AdditionalUnattendContent.create(\"oobesystem\", \"Microsoft-Windows-Shell-Setup\", \"FirstLogonCommands\", \"<XML unattend content>\"));\n      OSProfile.WindowsConfiguration windowsConfig = OSProfile.WindowsConfiguration.create(false, winrm, additionalUnattendContent, true);\n      List<Secrets> secrets =  ImmutableList.of(\n            Secrets.create(SourceVault.create(\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myresourcegroup1/providers/Microsoft.KeyVault/vaults/myvault1\"), \n                  ImmutableList.of(VaultCertificate.create(\"https://myvault1.vault.azure.net/secrets/SECRETNAME/SECRETVERSION\", \"CERTIFICATESTORENAME\"))));\n      OSProfile osProfile = OSProfile.create(\"windowsmachine\", \"azureuser\", \"password\", \"\", linuxConfig, windowsConfig, secrets);\n      NetworkInterface networkInterface = NetworkInterface.create(\"/subscriptions/SUBSCRIPTIONID\"\n            + \"/resourceGroups/groupname/providers/Microsoft.Network/networkInterfaces/\" + \"windowsmachine167\", null);\n      List<NetworkInterface> networkInterfaces = new ArrayList<NetworkInterface>();\n      networkInterfaces.add(networkInterface);\n      NetworkProfile networkProfile = NetworkProfile.create(networkInterfaces);\n      DiagnosticsProfile.BootDiagnostics bootDiagnostics = DiagnosticsProfile.BootDiagnostics.create(true,\n            \"https://groupname2760.blob.core.windows.net/\");\n      DiagnosticsProfile diagnosticsProfile = DiagnosticsProfile.create(bootDiagnostics);\n      VirtualMachineProperties properties = VirtualMachineProperties.create(\"27ee085b-d707-xxxx-yyyy-2370e2eb1cc1\",\n            licenseType, availabilitySet, hwProf, storageProfile, osProfile, networkProfile, diagnosticsProfile,\n            VirtualMachineProperties.ProvisioningState.CREATING);\n      return properties;\n   }\n\n   private VirtualMachine getVM() {\n      VirtualMachineProperties properties = getVMWithManagedDisksProperties();\n      VirtualMachine machine = VirtualMachine.create(\"/subscriptions/SUBSCRIPTIONID/\" + \"\"\n            + \"resourceGroups/groupname/providers/Microsoft.Compute/virtualMachines/windowsmachine\", \"windowsmachine\",\n            \"Microsoft.Compute/virtualMachines\", \"westus\", ImmutableMap.of(\"foo\", \"bar\"), properties,\n            Plan.create(\"thinkboxsoftware\", \"deadline-slave-7-2\", \"deadline7-2\"));\n      return machine;\n   }\n   \n   private VirtualMachine getVM(Plan plan) {\n      VirtualMachineProperties properties = getVMWithManagedDisksProperties();\n      VirtualMachine machine = VirtualMachine.create(\"/subscriptions/SUBSCRIPTIONID/\" + \"\"\n            + \"resourceGroups/groupname/providers/Microsoft.Compute/virtualMachines/windowsmachine\", \"windowsmachine\",\n            \"Microsoft.Compute/virtualMachines\", \"westus\", ImmutableMap.of(\"foo\", \"bar\"), properties, plan);\n      return machine;\n   }\n\n   private VirtualMachineInstance getVMInstance() {\n      List<Status> statuses = new ArrayList<Status>();\n      String testDate = \"Wed May 04 01:38:52 PDT 2016\";\n      DateFormat formatter = new SimpleDateFormat(\"EEE MMM dd HH:mm:ss z yyyy\");\n      Date date = null;\n      try {\n         date = formatter.parse(testDate);\n      } catch (Exception e) {\n         e.printStackTrace();\n      }\n      Status vmStatus = Status.create(\n            \"ProvisioningState/succeeded\", \"Info\", \"Provisioning succeeded\", null, date);\n      statuses.add(vmStatus);\n      Status vmStatus1 = Status.create(\n            \"PowerState/running\", \"Info\", \"VM running\", null, null);\n      statuses.add(vmStatus1);\n\n      VirtualMachineInstance machineInstance = VirtualMachineInstance\n            .create(null, null, ImmutableList.copyOf(statuses));\n      return machineInstance;\n   }\n\n   private List<VirtualMachine> getVMList() {\n      List<VirtualMachine> list = new ArrayList<VirtualMachine>();\n      VirtualMachineProperties propertiesWithManagedDisks = getVMWithManagedDisksProperties();\n      VirtualMachine machineWithManagedDisks = VirtualMachine.create(\"/subscriptions/SUBSCRIPTIONID/\" + \"\"\n            + \"resourceGroups/groupname/providers/Microsoft.Compute/virtualMachines/windowsmachine\", \"windowsmachine\",\n            \"Microsoft.Compute/virtualMachines\", \"westus\", null, propertiesWithManagedDisks, null);\n      list.add(machineWithManagedDisks);\n      VirtualMachineProperties propertiesWithBlobDisks = getVMWithBlobDisksProperties();\n      VirtualMachine machineWithBlobDisks = VirtualMachine.create(\"/subscriptions/SUBSCRIPTIONID/\" + \"\"\n                      + \"resourceGroups/groupname/providers/Microsoft.Compute/virtualMachines/windowsmachine\", \"windowsmachine\",\n              \"Microsoft.Compute/virtualMachines\", \"westus\", null, propertiesWithBlobDisks, null);\n      list.add(machineWithBlobDisks);\n      return list;\n   }\n\n   private List<VirtualMachine> getVMListAll() {\n      List<VirtualMachine> list = new ArrayList<VirtualMachine>();\n      VirtualMachineProperties propertiesWithManagedDisks = getVMWithManagedDisksProperties();\n      VirtualMachine machineWithManagedDisks = VirtualMachine.create(\"/subscriptions/SUBSCRIPTIONID/\" + \"\"\n                  + \"resourceGroups/groupname/providers/Microsoft.Compute/virtualMachines/windowsmachine\",\n            \"windowsmachine\",\n            \"Microsoft.Compute/virtualMachines\", \"westus\", null, propertiesWithManagedDisks, null);\n      list.add(machineWithManagedDisks);\n      VirtualMachineProperties propertiesWithBlobDisks = getVMWithBlobDisksProperties();\n      VirtualMachine machineWithBlobDisks = VirtualMachine.create(\"/subscriptions/SUBSCRIPTIONID/\" + \"\"\n                  + \"resourceGroups/groupname/providers/Microsoft.Compute/virtualMachines/windowsmachine\",\n            \"windowsmachine\",\n            \"Microsoft.Compute/virtualMachines\", \"westus\", null, propertiesWithBlobDisks, null);\n      list.add(machineWithBlobDisks);\n      VirtualMachine machineInDifferentResourceGroup = VirtualMachine.create(\"/subscriptions/SUBSCRIPTIONID/\" + \"\"\n                  + \"resourceGroups/otherresourcegroup/providers/Microsoft.Compute/virtualMachines/windowsmachine\",\n            \"windowsmachine\", \"Microsoft.Compute/virtualMachines\", \"westus\", null, propertiesWithBlobDisks, null);\n      list.add(machineInDifferentResourceGroup);\n      VirtualMachine machineInDifferentLocation = VirtualMachine.create(\"/subscriptions/SUBSCRIPTIONID/\" + \"\"\n                  + \"resourceGroups/groupname/providers/Microsoft.Compute/virtualMachines/windowsmachine\",\n            \"windowsmachine\",\n            \"Microsoft.Compute/virtualMachines\", \"eastus\", null, propertiesWithBlobDisks, null);\n      list.add(machineInDifferentLocation);\n      return list;\n   }\n\n   private List<VirtualMachine> getVMListByLocation() {\n      List<VirtualMachine> list = new ArrayList<VirtualMachine>();\n      VirtualMachineProperties propertiesWithManagedDisks = getVMWithManagedDisksProperties();\n      VirtualMachine machineWithManagedDisks = VirtualMachine.create(\"/subscriptions/SUBSCRIPTIONID/\" + \"\"\n                  + \"resourceGroups/groupname/providers/Microsoft.Compute/virtualMachines/windowsmachine\",\n            \"windowsmachine\",\n            \"Microsoft.Compute/virtualMachines\", \"westus\", null, propertiesWithManagedDisks, null);\n      list.add(machineWithManagedDisks);\n      VirtualMachineProperties propertiesWithBlobDisks = getVMWithBlobDisksProperties();\n      VirtualMachine machineWithBlobDisks = VirtualMachine.create(\"/subscriptions/SUBSCRIPTIONID/\" + \"\"\n                  + \"resourceGroups/groupname/providers/Microsoft.Compute/virtualMachines/windowsmachine\",\n            \"windowsmachine\",\n            \"Microsoft.Compute/virtualMachines\", \"westus\", null, propertiesWithBlobDisks, null);\n      list.add(machineWithBlobDisks);\n      VirtualMachine machineInDifferentResourceGroup = VirtualMachine.create(\"/subscriptions/SUBSCRIPTIONID/\" + \"\"\n                  + \"resourceGroups/otherresourcegroup/providers/Microsoft.Compute/virtualMachines/windowsmachine\",\n            \"windowsmachine\", \"Microsoft.Compute/virtualMachines\", \"westus\", null, propertiesWithBlobDisks, null);\n      list.add(machineInDifferentResourceGroup);\n      return list;\n   }\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/VirtualMachineScaleSetApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.azurecompute.arm.domain.Extension;\nimport org.jclouds.azurecompute.arm.domain.ExtensionProfile;\nimport org.jclouds.azurecompute.arm.domain.ExtensionProfileSettings;\nimport org.jclouds.azurecompute.arm.domain.ExtensionProperties;\nimport org.jclouds.azurecompute.arm.domain.IdReference;\nimport org.jclouds.azurecompute.arm.domain.ImageReference;\nimport org.jclouds.azurecompute.arm.domain.IpConfiguration;\nimport org.jclouds.azurecompute.arm.domain.IpConfigurationProperties;\nimport org.jclouds.azurecompute.arm.domain.ManagedDiskParameters;\nimport org.jclouds.azurecompute.arm.domain.NetworkInterfaceCard;\nimport org.jclouds.azurecompute.arm.domain.NetworkInterfaceCardProperties;\nimport org.jclouds.azurecompute.arm.domain.NetworkInterfaceConfiguration;\nimport org.jclouds.azurecompute.arm.domain.NetworkInterfaceConfigurationProperties;\nimport org.jclouds.azurecompute.arm.domain.NetworkProfile;\nimport org.jclouds.azurecompute.arm.domain.OSDisk;\nimport org.jclouds.azurecompute.arm.domain.StorageProfile;\nimport org.jclouds.azurecompute.arm.domain.Subnet;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineScaleSet;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineScaleSetDNSSettings;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineScaleSetIpConfiguration;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineScaleSetIpConfigurationProperties;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineScaleSetNetworkProfile;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineScaleSetNetworkSecurityGroup;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineScaleSetOSProfile;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineScaleSetProperties;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineScaleSetPublicIPAddressConfiguration;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineScaleSetPublicIPAddressProperties;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineScaleSetSKU;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineScaleSetUpgradePolicy;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineScaleSetVirtualMachineProfile;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiLiveTest;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\n\n@Test(groups = \"live\", testName = \"VirtualMachineScaleSetApiLiveTest\")\npublic class VirtualMachineScaleSetApiLiveTest extends BaseAzureComputeApiLiveTest {\n\n   private String subscriptionid;\n   private String vmssName;\n   private String virtualNetworkName;\n   private String subnetId;\n   private Subnet subnet;\n\n   @BeforeClass\n   @Override\n   public void setup() {\n      super.setup();\n      subscriptionid = getSubscriptionId();\n\n      createTestResourceGroup();  //BASE: Creates a random resource group using the properties location\n\n      virtualNetworkName = String.format(\"vn-%s-%s\", this.getClass().getSimpleName().toLowerCase(), System.getProperty(\"user.name\"));\n\n      // Subnets belong to a virtual network so that needs to be created first\n      assertNotNull(createDefaultVirtualNetwork(resourceGroupName, virtualNetworkName, \"10.2.0.0/16\", LOCATION));\n\n      //Subnet needs to be up & running before NIC can be created\n      String subnetName = String.format(\"s-%s-%s\", this.getClass().getSimpleName().toLowerCase(), System.getProperty(\"user.name\"));\n      this.subnet = createDefaultSubnet(resourceGroupName, subnetName, virtualNetworkName, \"10.2.0.0/23\");\n      assertNotNull(subnet);\n      assertNotNull(subnet.id());\n      this.subnetId = subnet.id();\n\n\n      vmssName = String.format(\"%3.24s\", System.getProperty(\"user.name\") + RAND + this.getClass().getSimpleName()).toLowerCase().substring(0, 15);\n   }\n\n   private VirtualMachineScaleSetApi api() {\n      return api.getVirtualMachineScaleSetApi(resourceGroupName);\n   }\n\n   @Test\n   public void testCreate() {\n      VirtualMachineScaleSet vmss = api().createOrUpdate(vmssName, LOCATIONDESCRIPTION, getSKU(),\n         Collections.<String, String>emptyMap(), getProperties());\n      assertTrue(!vmss.name().isEmpty());\n//      waitUntilReady(vmssName);\n   }\n\n   @Test(dependsOnMethods = \"testCreate\")\n   public void testList() throws InterruptedException {\n      final VirtualMachineScaleSetApi vmssAPI = api.getVirtualMachineScaleSetApi(resourceGroupName);\n      assertEquals(vmssAPI.list().size(), 1);\n   }\n\n   @Test(dependsOnMethods = \"testList\")\n   public void testGet()  {\n      final VirtualMachineScaleSetApi vmssAPI = api.getVirtualMachineScaleSetApi(resourceGroupName);\n      assertEquals(vmssAPI.get(vmssName).name(), vmssName);\n   }\n\n   @Test(dependsOnMethods = \"testGet\", alwaysRun = true)\n   public void testDelete() throws Exception {\n      final VirtualMachineScaleSetApi vmssAPI = api.getVirtualMachineScaleSetApi(resourceGroupName);\n      URI uri = vmssAPI.delete(vmssName);\n      assertResourceDeleted(uri);\n   }\n\n   protected void assertResourceDeleted(URI uri) {\n      if (uri != null) {\n         assertTrue(resourceDeleted.apply(uri),\n                 String.format(\"Resource %s was not terminated in the configured timeout\", uri));\n      }\n   }\n\n\n   /**\n    * Create a standard SKU\n    *\n    * @return VirtualMachineScaleSetSKU\n    */\n   public VirtualMachineScaleSetSKU getSKU() {\n      return VirtualMachineScaleSetSKU.create(\"Standard_A1\", \"Standard\", 10);\n   }\n\n   private VirtualMachineScaleSetUpgradePolicy getUpgradePolicy() {\n      return VirtualMachineScaleSetUpgradePolicy.create(\"Manual\");\n   }\n\n   private StorageProfile getLinuxStorageProfile_Default() {\n      return StorageProfile.create(getLinuxImageReference(), getLinuxOSDisk(), null);\n   }\n\n   private ManagedDiskParameters getManagedDiskParameters() {\n      return ManagedDiskParameters.create(null, \"Standard_LRS\");\n   }\n\n   private OSDisk getLinuxOSDisk() {\n      return OSDisk.create(\"Linux\", null, null, null, \"FromImage\",\n         null, getManagedDiskParameters(), null);\n   }\n\n   private ImageReference getLinuxImageReference() {\n      return ImageReference.create(null, \"Canonical\", \"UbuntuServer\",\n         \"16.04-LTS\", \"latest\");\n   }\n\n   private VirtualMachineScaleSetOSProfile getOSProfile() {\n      VirtualMachineScaleSetOSProfile.LinuxConfiguration linuxConfiguration =\n         VirtualMachineScaleSetOSProfile.LinuxConfiguration.create(false, null);\n      VirtualMachineScaleSetOSProfile.WindowsConfiguration windowsConfiguration = null;\n\n      return VirtualMachineScaleSetOSProfile.create(vmssName, \"jclouds\", \"jClouds1!\",\n         linuxConfiguration, windowsConfiguration, null);\n   }\n\n\n   private VirtualMachineScaleSetNetworkProfile getNetworkProfile() {\n      NetworkInterfaceCard nic = createNetworkInterfaceCard(resourceGroupName, \"jc-nic-\" + RAND, LOCATION, \"ipConfig-\" + RAND);\n      assertNotNull(nic);\n      NetworkProfile.NetworkInterface.create(nic.id(), NetworkProfile.NetworkInterface.NetworkInterfaceProperties.create(true));\n\n      List<NetworkInterfaceConfiguration> networkInterfaceConfigurations = new ArrayList<NetworkInterfaceConfiguration>();\n      List<VirtualMachineScaleSetIpConfiguration> virtualMachineScaleSetIpConfigurations = new ArrayList<VirtualMachineScaleSetIpConfiguration>();\n\n\n      VirtualMachineScaleSetPublicIPAddressConfiguration publicIPAddressConfiguration =\n         VirtualMachineScaleSetPublicIPAddressConfiguration.create(\"pub1\", VirtualMachineScaleSetPublicIPAddressProperties.create(15));\n\n\n      VirtualMachineScaleSetIpConfigurationProperties virtualMachineScaleSetIpConfigurationProperties =\n         VirtualMachineScaleSetIpConfigurationProperties.create(publicIPAddressConfiguration,\n            this.subnet, \"IPv4\", null,\n            null, null);\n\n      VirtualMachineScaleSetIpConfiguration virtualMachineScaleSetIpConfiguration =\n         VirtualMachineScaleSetIpConfiguration.create(\"ipconfig1\", virtualMachineScaleSetIpConfigurationProperties);\n\n      virtualMachineScaleSetIpConfigurations.add(virtualMachineScaleSetIpConfiguration);\n\n      VirtualMachineScaleSetNetworkSecurityGroup networkSecurityGroup = null;\n\n      ArrayList<String> dnsList = new ArrayList<String>();\n      dnsList.add(\"8.8.8.8\");\n      VirtualMachineScaleSetDNSSettings dnsSettings =  VirtualMachineScaleSetDNSSettings.create(dnsList);\n\n      NetworkInterfaceConfigurationProperties networkInterfaceConfigurationProperties =\n         NetworkInterfaceConfigurationProperties.create(true, false, networkSecurityGroup, dnsSettings, virtualMachineScaleSetIpConfigurations);\n      NetworkInterfaceConfiguration networkInterfaceConfiguration = NetworkInterfaceConfiguration.create(\"nicconfig1\", networkInterfaceConfigurationProperties);\n      networkInterfaceConfigurations.add(networkInterfaceConfiguration);\n\n      return VirtualMachineScaleSetNetworkProfile.create(networkInterfaceConfigurations);\n   }\n\n\n   private ExtensionProfile getExtensionProfile() {\n      List<Extension> extensions = new ArrayList<Extension>();\n\n      List<String> uris = new ArrayList<String>();\n      uris.add(\"https://mystorage1.blob.core.windows.net/winvmextekfacnt/SampleCmd_1.cmd\");\n      ExtensionProfileSettings extensionProfileSettings = ExtensionProfileSettings.create(uris, \"SampleCmd_1.cmd\");\n\n      Map<String, String> protectedSettings = new HashMap<String, String>();\n      protectedSettings.put(\"StorageAccountKey\", \"jclouds-accountkey\");\n\n      ExtensionProperties extensionProperties = ExtensionProperties.create(\"Microsoft.compute\", \"CustomScriptExtension\",\n         \"1.1\", false, extensionProfileSettings,\n         protectedSettings);\n\n      Extension extension = Extension.create(\"extensionName\", extensionProperties);\n      extensions.add(extension);\n\n      return ExtensionProfile.create(extensions);\n   }\n\n\n   private VirtualMachineScaleSetVirtualMachineProfile getVirtualMachineProfile() {\n      return VirtualMachineScaleSetVirtualMachineProfile.create(getLinuxStorageProfile_Default(), getOSProfile(), getNetworkProfile(), getExtensionProfile());\n   }\n\n   public VirtualMachineScaleSetProperties getProperties() {\n\n      return VirtualMachineScaleSetProperties.create(null, null, getUpgradePolicy(), null, getVirtualMachineProfile());\n   }\n\n   private NetworkInterfaceCard createNetworkInterfaceCard(final String resourceGroupName, String networkInterfaceCardName, String locationName, String ipConfigurationName) {\n      //Create properties object\n      final NetworkInterfaceCardProperties networkInterfaceCardProperties = NetworkInterfaceCardProperties\n         .builder().ipConfigurations(Arrays.asList(IpConfiguration.create(ipConfigurationName, null, null,\n                  IpConfigurationProperties\n                        .create(null, null, \"Dynamic\", IdReference.create(subnetId), null, null, null, null)))).build();\n\n      final Map<String, String> tags = ImmutableMap.of(\"jclouds\", \"livetest\");\n      return api.getNetworkInterfaceCardApi(resourceGroupName).createOrUpdate(networkInterfaceCardName, locationName, networkInterfaceCardProperties, tags);\n   }\n\n   public String getSubscriptionid() {\n      return subscriptionid;\n   }\n\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/VirtualMachineScaleSetApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport static com.google.common.collect.Iterables.isEmpty;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.azurecompute.arm.domain.DataDisk;\nimport org.jclouds.azurecompute.arm.domain.Extension;\nimport org.jclouds.azurecompute.arm.domain.ExtensionProfile;\nimport org.jclouds.azurecompute.arm.domain.ExtensionProfileSettings;\nimport org.jclouds.azurecompute.arm.domain.ExtensionProperties;\nimport org.jclouds.azurecompute.arm.domain.IdReference;\nimport org.jclouds.azurecompute.arm.domain.ImageReference;\nimport org.jclouds.azurecompute.arm.domain.ManagedDiskParameters;\nimport org.jclouds.azurecompute.arm.domain.NetworkInterfaceCard;\nimport org.jclouds.azurecompute.arm.domain.NetworkInterfaceCardProperties;\nimport org.jclouds.azurecompute.arm.domain.NetworkInterfaceConfiguration;\nimport org.jclouds.azurecompute.arm.domain.NetworkInterfaceConfigurationProperties;\nimport org.jclouds.azurecompute.arm.domain.NetworkProfile;\nimport org.jclouds.azurecompute.arm.domain.OSDisk;\nimport org.jclouds.azurecompute.arm.domain.Secrets;\nimport org.jclouds.azurecompute.arm.domain.StorageProfile;\nimport org.jclouds.azurecompute.arm.domain.Subnet;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineScaleSet;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineScaleSetDNSSettings;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineScaleSetIpConfiguration;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineScaleSetIpConfigurationProperties;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineScaleSetNetworkProfile;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineScaleSetOSProfile;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineScaleSetProperties;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineScaleSetPublicIPAddressConfiguration;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineScaleSetPublicIPAddressProperties;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineScaleSetSKU;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineScaleSetUpgradePolicy;\nimport org.jclouds.azurecompute.arm.domain.VirtualMachineScaleSetVirtualMachineProfile;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiMockTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\n\n\n@Test(groups = \"unit\", testName = \"VirtualMachineScaleSetAPIMockTest\", singleThreaded = true)\npublic class VirtualMachineScaleSetApiMockTest extends BaseAzureComputeApiMockTest {\n\n   private final String resourcegroup = \"myresourcegroup\";\n   private final String vmssname = \"jclouds-vmssname\";\n\n   public void testGet() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/virtualmachinescalesetget.json\").setResponseCode(200));\n      final VirtualMachineScaleSetApi vmssAPI = api.getVirtualMachineScaleSetApi(resourcegroup);\n      assertEquals(vmssAPI.get(vmssname).name(), vmssname);\n      assertSent(server,\n              \"GET\", \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myresourcegroup/\" +\n                      \"providers/Microsoft.Compute\"\n            + \"/VirtualMachineScaleSets/jclouds-vmssname?api-version=2017-03-30\");\n   }\n\n   public void testGetWhen404() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/virtualmachinescalesetgetwhen404.json\").setResponseCode(404));\n      final VirtualMachineScaleSetApi vmssAPI = api.getVirtualMachineScaleSetApi(resourcegroup);\n      VirtualMachineScaleSet vmss = vmssAPI.get(vmssname + 1);\n      assertSent(server,\n              \"GET\",\n              \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myresourcegroup/providers/\" +\n                      \"Microsoft.Compute/VirtualMachineScaleSets/\" +\n                      vmssname + \"1?api-version=2017-03-30\");\n      assertNull(vmss);\n   }\n\n   public void testCreateOrUpdate() throws InterruptedException {\n      server.enqueue(\n              jsonResponse(\n                      \"/virtualmachinescalesetresponsecreateorupdate.json\").setResponseCode(200));\n      final VirtualMachineScaleSetApi vmssAPI = api.getVirtualMachineScaleSetApi(resourcegroup);\n      VirtualMachineScaleSet vmss = CreateOrUpdateVMSS(vmssAPI);\n\n      assertNotNull(vmss);\n      assertSent(server,\n              \"PUT\",\n              \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myresourcegroup/providers/\" +\n                      \"Microsoft.Compute\"\n                      + \"/VirtualMachineScaleSets/\" + vmssname + \"?api-version=2017-03-30\",\n              \"{\\n\" +\n                      \"  \\\"location\\\": \\\"eastus\\\",\\n\" +\n                      \"  \\\"sku\\\": {\\n\" +\n                      \"    \\\"name\\\": \\\"Standard_A1\\\",\\n\" +\n                      \"    \\\"tier\\\": \\\"Standard\\\",\\n\" +\n                      \"    \\\"capacity\\\": 10\\n\" +\n                      \"  },\\n\" +\n                      \"  \\\"properties\\\": {\\n\" +\n                      \"    \\\"singlePlacementGroup\\\": true,\\n\" +\n                      \"    \\\"overProvision\\\": true,\\n\" +\n                      \"    \\\"upgradePolicy\\\": {\\n\" +\n                      \"      \\\"mode\\\": \\\"Manual\\\"\\n\" +\n                      \"    },\\n\" +\n                      \"    \\\"virtualMachineProfile\\\": {\\n\" +\n                      \"      \\\"storageProfile\\\": {\\n\" +\n                      \"        \\\"imageReference\\\": {\\n\" +\n                      \"          \\\"publisher\\\": \\\"Canonical\\\",\\n\" +\n                      \"          \\\"offer\\\": \\\"UbuntuServer\\\",\\n\" +\n                      \"          \\\"sku\\\": \\\"16.04-LTS\\\",\\n\" +\n                      \"          \\\"version\\\": \\\"latest\\\"\\n\" +\n                      \"        },\\n\" +\n                      \"        \\\"osDisk\\\": {\\n\" +\n                      \"          \\\"osType\\\": \\\"Windows\\\",\\n\" +\n                      \"          \\\"createOption\\\": \\\"FromImage\\\",\\n\" +\n                      \"          \\\"managedDisk\\\": {\\n\" +\n                      \"            \\\"storageAccountType\\\": \\\"Standard_LRS\\\"\\n\" +\n                      \"          }\\n\" +\n                      \"        },\\n\" +\n                      \"        \\\"dataDisks\\\": [{\\n\" +\n                      \"          \\\"diskSizeGB\\\": \\\"10\\\",\\n\" +\n                      \"          \\\"lun\\\": 1,\\n\" +\n                      \"          \\\"createOption\\\": \\\"Unrecognized\\\",\\n\" +\n                      \"          \\\"caching\\\": \\\"None\\\",\\n\" +\n                      \"          \\\"managedDisk\\\": {\\n\" +\n                      \"            \\\"storageAccountType\\\": \\\"Standard_LRS\\\"\\n\" +\n                      \"          }\\n\" +\n                      \"        }\\n\" +\n                      \"        ]\\n\" +\n                      \"      },\\n\" +\n                      \"      \\\"osProfile\\\": {\\n\" +\n                      \"        \\\"computerNamePrefix\\\": \\\"jclouds-vmssname\\\",\\n\" +\n                      \"        \\\"adminUsername\\\": \\\"admin\\\",\\n\" +\n                      \"        \\\"adminPassword\\\": \\\"password\\\",\\n\" +\n                      \"        \\\"linuxConfiguration\\\": {\\n\" +\n                      \"          \\\"disablePasswordAuthentication\\\": false\\n\" +\n                      \"        },\\n\" +\n                      \"        \\\"secrets\\\": []\\n\" +\n                      \"      },\\n\" +\n                      \"      \\\"networkProfile\\\": {\\n\" +\n                      \"        \\\"networkInterfaceConfigurations\\\": [{\\n\" +\n                      \"          \\\"name\\\": \\\"nicconfig1\\\",\\n\" +\n                      \"          \\\"properties\\\": {\\n\" +\n                      \"            \\\"primary\\\": true,\\n\" +\n                      \"            \\\"enableAcceleratedNetworking\\\": false,\\n\" +\n                      \"            \\\"dnsSettings\\\": {\\n\" +\n                      \"              \\\"dnsServers\\\": [\\\"8.8.8.8\\\"]\\n\" +\n                      \"            },\\n\" +\n                      \"            \\\"ipConfigurations\\\": [{\\n\" +\n                      \"              \\\"name\\\": \\\"ipconfig1\\\",\\n\" +\n                      \"              \\\"properties\\\": {\\n\" +\n                      \"                \\\"publicIPAddressConfiguration\\\": {\\n\" +\n                      \"                  \\\"name\\\": \\\"pub1\\\",\\n\" +\n                      \"                  \\\"properties\\\": {\\n\" +\n                      \"                    \\\"idleTimeoutInMinutes\\\": 15\\n\" +\n                      \"                  }\\n\" +\n                      \"                },\\n\" +\n                      \"                \\\"subnet\\\": {\\n\" +\n                      \"                  \\\"name\\\": \\\"virtualNetworkName\\\",\\n\" +\n                      \"                  \\\"id\\\": \\\"/subscriptions/xxxxx-xxxx-xxxx-xxxx-xxxxxx/resourceGroups/\" +\n                      \"jcloud-eastus/providers/Microsoft.Network/virtualNetworks/\" +\n                      \"jclouds-eastus-virtualNetworkName/subnets/jclouds-eastus-subnet\\\",\\n\" +\n                      \"                  \\\"properties\\\": {}\\n\" +\n                      \"                },\\n\" +\n                      \"                \\\"privateIPAddressVersion\\\": \\\"IPv4\\\",\\n\" +\n                      \"                \\\"loadBalancerBackendAddressPools\\\": [],\\n\" +\n                      \"                \\\"loadBalancerInboundNatPools\\\": []\\n\" +\n                      \"              }\\n\" +\n                      \"            }\\n\" +\n                      \"            ]\\n\" +\n                      \"          }\\n\" +\n                      \"        }\\n\" +\n                      \"        ]\\n\" +\n                      \"      },\\n\" +\n                      \"      \\\"extensionProfile\\\": {\\n\" +\n                      \"        \\\"extensions\\\": [{\\n\" +\n                      \"          \\\"name\\\": \\\"extensionName\\\",\\n\" +\n                      \"          \\\"properties\\\": {\\n\" +\n                      \"            \\\"publisher\\\": \\\"Microsoft.compute\\\",\\n\" +\n                      \"            \\\"type\\\": \\\"CustomScriptExtension\\\",\\n\" +\n                      \"            \\\"typeHandlerVersion\\\": \\\"1.1\\\",\\n\" +\n                      \"            \\\"autoUpgradeMinorVersion\\\": false,\\n\" +\n                      \"            \\\"settings\\\": {\\n\" +\n                      \"              \\\"fileUris\\\": [\\\"https://mystorage1.blob.core.windows.net/winvmextekfacnt/\" +\n                      \"SampleCmd_1.cmd\\\"],\\n\" +\n                      \"              \\\"commandToExecute\\\": \\\"SampleCmd_1.cmd\\\"\\n\" +\n                      \"            },\\n\" +\n                      \"            \\\"protectedSettings\\\": {\\n\" +\n                      \"              \\\"StorageAccountKey\\\": \\\"jclouds-accountkey\\\"\\n\" +\n                      \"            }\\n\" +\n                      \"          }\\n\" +\n                      \"        }\\n\" +\n                      \"        ]\\n\" +\n                      \"      }\\n\" +\n                      \"    }\\n\" +\n                      \"  }\\n\" +\n                      \"}\\n\"\n              );\n   }\n\n   private VirtualMachineScaleSet CreateOrUpdateVMSS(VirtualMachineScaleSetApi vmssAPI) {\n      return vmssAPI.createOrUpdate(\n              vmssname,\n              \"eastus\",\n              VirtualMachineScaleSetSKU.create(\n                      \"Standard_A1\",\n                      \"Standard\",\n                      10),\n              null,\n              VirtualMachineScaleSetProperties.create(\n                      true,\n                      true,\n                      VirtualMachineScaleSetUpgradePolicy.create(\"Manual\"),\n                      null,\n                      VirtualMachineScaleSetVirtualMachineProfile.create(\n                              StorageProfile.create(\n                                      ImageReference.create(\n                                              null,\n                                              \"Canonical\",\n                                              \"UbuntuServer\",\n                                              \"16.04-LTS\",\n                                              \"latest\"),\n                                      OSDisk.create(\n                                              \"Windows\",\n                                              null,\n                                              null,\n                                              null,\n                                              \"FromImage\",\n                                              null,\n                                              ManagedDiskParameters.create(\n                                                      null,\n                                                      \"Standard_LRS\"),\n                                              null),\n                                      Arrays.asList(DataDisk.create(\n                                              null,\n                                              \"10\",\n                                              1,\n                                              null,\n                                              null,\n                                              \"FromImage\",\n                                              \"None\",\n                                              ManagedDiskParameters.create(\n                                                      null,\n                                                      \"Standard_LRS\"),\n                                              null))),\n                              VirtualMachineScaleSetOSProfile.create(\n                                      \"jclouds-vmssname\",\n                                      \"admin\",\n                                      \"password\",\n                                      VirtualMachineScaleSetOSProfile.LinuxConfiguration.create(\n                                              false,\n                                              null),\n                                      null,\n                                      new ArrayList<Secrets>()),\n                              getNetworkProfile(),\n                              getExtensionProfile()\n\n                      )\n              ));\n   }\n\n\n   private VirtualMachineScaleSetNetworkProfile getNetworkProfile() {\n      NetworkInterfaceCard nic =\n              createNetworkInterfaceCard(\n                      \"jc-nic-\" + 123,\n                      \"eastus\");\n      NetworkProfile.NetworkInterface.create(\n              nic.id(),\n              NetworkProfile.NetworkInterface.NetworkInterfaceProperties.create(true));\n\n      List<NetworkInterfaceConfiguration> networkInterfaceConfigurations =\n              new ArrayList<NetworkInterfaceConfiguration>();\n      List<VirtualMachineScaleSetIpConfiguration> virtualMachineScaleSetIpConfigurations =\n              new ArrayList<VirtualMachineScaleSetIpConfiguration>();\n\n\n      VirtualMachineScaleSetPublicIPAddressConfiguration publicIPAddressConfiguration =\n              VirtualMachineScaleSetPublicIPAddressConfiguration.create(\n                      \"pub1\",\n                      VirtualMachineScaleSetPublicIPAddressProperties.create(15));\n\n\n      VirtualMachineScaleSetIpConfigurationProperties virtualMachineScaleSetIpConfigurationProperties =\n              VirtualMachineScaleSetIpConfigurationProperties.create(\n                      publicIPAddressConfiguration,\n                      createDefaultSubnet(\n                              \"virtualNetworkName\"\n                      ),\n                      \"IPv4\",\n                      null,\n                      null,\n                      null);\n\n      VirtualMachineScaleSetIpConfiguration virtualMachineScaleSetIpConfiguration =\n              VirtualMachineScaleSetIpConfiguration.create(\n                      \"ipconfig1\",\n                      virtualMachineScaleSetIpConfigurationProperties);\n\n      virtualMachineScaleSetIpConfigurations.add(virtualMachineScaleSetIpConfiguration);\n\n      ArrayList<String> dnsList = new ArrayList<String>();\n      dnsList.add(\"8.8.8.8\");\n      VirtualMachineScaleSetDNSSettings dnsSettings =  VirtualMachineScaleSetDNSSettings.create(dnsList);\n\n      NetworkInterfaceConfigurationProperties networkInterfaceConfigurationProperties =\n              NetworkInterfaceConfigurationProperties.create(\n                      true,\n                      false,\n                      null,\n                      dnsSettings,\n                      virtualMachineScaleSetIpConfigurations);\n      NetworkInterfaceConfiguration networkInterfaceConfiguration =\n              NetworkInterfaceConfiguration.create(\n                      \"nicconfig1\",\n                      networkInterfaceConfigurationProperties);\n      networkInterfaceConfigurations.add(networkInterfaceConfiguration);\n\n      return VirtualMachineScaleSetNetworkProfile.create(networkInterfaceConfigurations);\n   }\n\n\n   private NetworkInterfaceCard createNetworkInterfaceCard(\n           String networkInterfaceCardName, String locationName) {\n      //Create properties object\n      NetworkInterfaceCardProperties networkInterfaceCardProperties =\n              NetworkInterfaceCardProperties.create(\n                      null,\n                      null,\n                      false,\n                      null,\n                      IdReference.create(\n                              \"/subscriptions/xxxxx-xxxx-xxxx-xxxx-xxxxxx/resourceGroups/\" +\n                                      \"jcloud-eastus/providers/\" +\n                                      \"Microsoft.Network/virtualNetworks/\" + \"jclouds-eastus-virtualNetworkName\"\n                                    + \"/subnets/\" + \"jclouds-eastus-subnet\"), null, Boolean.TRUE\n              );\n\n      Map<String, String> tags = ImmutableMap.of(\"jclouds\", \"livetest\");\n      return NetworkInterfaceCard.create(\n              networkInterfaceCardName,\n              \"\",\n              null,\n              locationName,\n              networkInterfaceCardProperties, tags);\n   }\n\n   protected Subnet createDefaultSubnet(final String subnetName) {\n      Subnet.SubnetProperties properties = Subnet.SubnetProperties.create(\n              null,\n              null,\n              null);\n      return Subnet.create(\n              subnetName,\n              \"/subscriptions/xxxxx-xxxx-xxxx-xxxx-xxxxxx/resourceGroups/jcloud-eastus/providers/\" +\n                      \"Microsoft.Network/virtualNetworks/jclouds-eastus-virtualNetworkName/subnets/\" +\n                      \"jclouds-eastus-subnet\",\n              null,\n              properties);\n   }\n\n   private ExtensionProfile getExtensionProfile() {\n      List<Extension> extensions = new ArrayList<Extension>();\n\n      List<String> uris = new ArrayList<String>();\n      uris.add(\"https://mystorage1.blob.core.windows.net/winvmextekfacnt/SampleCmd_1.cmd\");\n\n      Map<String, String> protectedSettings = new HashMap<String, String>();\n      protectedSettings.put(\"StorageAccountKey\", \"jclouds-accountkey\");\n\n      Extension extension = Extension.create(\n              \"extensionName\",\n              ExtensionProperties.create(\n                      \"Microsoft.compute\",\n                      \"CustomScriptExtension\",\n                      \"1.1\",\n                      false,\n                      ExtensionProfileSettings.create(\n                              uris,\n                              \"SampleCmd_1.cmd\"),\n                      protectedSettings));\n      extensions.add(extension);\n\n      return ExtensionProfile.create(extensions);\n   }\n\n   public void testList() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/virtualmachinescalesetlist.json\").setResponseCode(200));\n      final VirtualMachineScaleSetApi vmssAPI = api.getVirtualMachineScaleSetApi(resourcegroup);\n      assertEquals(vmssAPI.list().size(), 1);\n      assertSent(server,\n              \"GET\",\n              \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myresourcegroup/providers/\" +\n                      \"Microsoft.Compute\"\n              + \"/VirtualMachineScaleSets?api-version=2017-03-30\");\n   }\n\n   public void testListWhen404() throws InterruptedException {\n      server.enqueue(\n              jsonResponse(\"/virtualmachinescalesetlistwhen404.json\").setResponseCode(404));\n      final VirtualMachineScaleSetApi vmssAPI = api.getVirtualMachineScaleSetApi(\n              resourcegroup + \"1\");\n      List<VirtualMachineScaleSet> vmssList = vmssAPI.list();\n      assertSent(server,\n              \"GET\",\n              \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myresourcegroup1/providers/\" +\n                      \"Microsoft.Compute\"\n              + \"/VirtualMachineScaleSets?api-version=2017-03-30\");\n      assertTrue(isEmpty(vmssList));\n   }\n\n\n   public void testDeleteWhen404() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/virtualmachinescalesetlist.json\").setResponseCode(404));\n      final VirtualMachineScaleSetApi vmssAPI = api.getVirtualMachineScaleSetApi(resourcegroup);\n      assertNull(vmssAPI.delete(vmssname));\n      assertSent(server,\n              \"DELETE\",\n              \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myresourcegroup/providers/\" +\n                      \"Microsoft.Compute\"\n              + \"/VirtualMachineScaleSets/\" + vmssname + \"?api-version=2017-03-30\");\n\n   }\n\n   public void testDelete() throws InterruptedException {\n      server.enqueue(response202WithHeader());\n      final VirtualMachineScaleSetApi vmssAPI = api.getVirtualMachineScaleSetApi(resourcegroup);\n      assertNotNull(vmssAPI.delete(vmssname));\n      assertSent(server,\n              \"DELETE\",\n              \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myresourcegroup/providers/\" +\n                      \"Microsoft.Compute\"\n              + \"/VirtualMachineScaleSets/jclouds-vmssname?api-version=2017-03-30\");\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/VirtualNetworkApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport static com.google.common.collect.Iterables.any;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.Arrays;\nimport java.util.List;\n\nimport org.jclouds.azurecompute.arm.domain.AddressSpace;\nimport org.jclouds.azurecompute.arm.domain.FrontendIPConfigurations;\nimport org.jclouds.azurecompute.arm.domain.FrontendIPConfigurationsProperties;\nimport org.jclouds.azurecompute.arm.domain.IdReference;\nimport org.jclouds.azurecompute.arm.domain.IpAddressAvailabilityResult;\nimport org.jclouds.azurecompute.arm.domain.Subnet;\nimport org.jclouds.azurecompute.arm.domain.Subnet.SubnetProperties;\nimport org.jclouds.azurecompute.arm.domain.VirtualNetwork;\nimport org.jclouds.azurecompute.arm.domain.loadbalancer.LoadBalancer;\nimport org.jclouds.azurecompute.arm.domain.loadbalancer.LoadBalancerProperties;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiLiveTest;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"live\", singleThreaded = true)\npublic class VirtualNetworkApiLiveTest extends BaseAzureComputeApiLiveTest {\n\n   private static final String TEST_VIRTUALNETWORK_ADDRESS_PREFIX = \"10.20.0.0/16\";\n   private static final String TEST_IP_ADDRESS_AVAILABLE = \"10.20.0.15\";\n   private static final String TEST_IP_ADDRESS_USED_IN_PROVIDER = \"10.20.0.7\";\n\n   private String virtualNetworkName;\n   private VirtualNetwork vn;\n\n   @BeforeClass\n   @Override\n   public void setup() {\n      super.setup();\n      createTestResourceGroup();\n      virtualNetworkName = String.format(\"vn-%s-%s\", this.getClass().getSimpleName().toLowerCase(), System.getProperty(\"user.name\"));\n   }\n\n   @Test\n   public void deleteVirtualNetworkResourceDoesNotExist() {\n      boolean status = api().delete(virtualNetworkName);\n      assertFalse(status);\n   }\n\n   @Test(dependsOnMethods = \"deleteVirtualNetworkResourceDoesNotExist\")\n   public void createVirtualNetwork() {\n\n      Subnet subnet = Subnet.builder().name(\"subnetName\")\n            .properties(SubnetProperties.builder().addressPrefix(TEST_VIRTUALNETWORK_ADDRESS_PREFIX).build()).build();\n\n      final VirtualNetwork.VirtualNetworkProperties virtualNetworkProperties = VirtualNetwork.VirtualNetworkProperties\n            .builder().subnets(ImmutableList.<Subnet> of(subnet))\n            .addressSpace(AddressSpace.create(Arrays.asList(TEST_VIRTUALNETWORK_ADDRESS_PREFIX))).build();\n\n      vn = api().createOrUpdate(virtualNetworkName, LOCATION, null, virtualNetworkProperties);\n\n      networkAvailablePredicate.create(resourceGroupName).apply(virtualNetworkName);\n\n      assertEquals(vn.name(), virtualNetworkName);\n      assertEquals(vn.location(), LOCATION);\n   }\n\n   @Test(dependsOnMethods = \"createVirtualNetwork\")\n   public void getVirtualNetwork() {\n      VirtualNetwork vn = api().get(virtualNetworkName);\n\n      assertNotNull(vn.name());\n      assertNotNull(vn.location());\n      assertNotNull(vn.properties().addressSpace().addressPrefixes());\n   }\n\n   @Test(dependsOnMethods = \"createVirtualNetwork\")\n   public void listVirtualNetworks() {\n      List<VirtualNetwork> vnList = api().list();\n\n      assertNotNull(vnList);\n      assertTrue(vnList.size() > 0);\n\n      assertTrue(any(vnList, new Predicate<VirtualNetwork>() {\n         @Override\n         public boolean apply(VirtualNetwork input) {\n            return vn.name().equals(input.name());\n         }\n      }));\n   }\n\n   @Test(dependsOnMethods = \"createVirtualNetwork\")\n   public void listAllVirtualNetworks() {\n      List<VirtualNetwork> vnList = api.getVirtualNetworkApi(null).listAll();\n\n      assertNotNull(vnList);\n      assertTrue(vnList.size() > 0);\n\n      assertTrue(any(vnList, new Predicate<VirtualNetwork>() {\n         @Override\n         public boolean apply(VirtualNetwork input) {\n            return vn.name().equals(input.name());\n         }\n      }));\n   }\n\n   @Test(dependsOnMethods = \"getVirtualNetwork\")\n   public void checkIpAvailability() {\n      final IpAddressAvailabilityResult checkResultAvailable = api()\n            .checkIPAddressAvailability(virtualNetworkName, TEST_IP_ADDRESS_AVAILABLE);\n      assertTrue(checkResultAvailable.available());\n      assertTrue(checkResultAvailable.availableIPAddresses().isEmpty());\n\n      LoadBalancer lbCreated = createLoadBalancerWithPrivateIP(TEST_IP_ADDRESS_USED_IN_PROVIDER);\n\n      final IpAddressAvailabilityResult checkResultUnavailable = api()\n            .checkIPAddressAvailability(virtualNetworkName, TEST_IP_ADDRESS_USED_IN_PROVIDER);\n      assertFalse(checkResultUnavailable.available());\n      assertFalse(checkResultUnavailable.availableIPAddresses().isEmpty());\n\n      deleteLoadBalancer(lbCreated);\n   }\n\n   @Test(dependsOnMethods = { \"listVirtualNetworks\", \"listAllVirtualNetworks\", \"getVirtualNetwork\", \"checkIpAvailability\" }, alwaysRun = true)\n   public void deleteVirtualNetwork() {\n      boolean status = api().delete(virtualNetworkName);\n      assertTrue(status);\n   }\n\n   private VirtualNetworkApi api() {\n      return api.getVirtualNetworkApi(resourceGroupName);\n   }\n\n   private LoadBalancerApi lbApi() {\n      return api.getLoadBalancerApi(resourceGroupName);\n   }\n\n   private LoadBalancer createLoadBalancerWithPrivateIP(final String ipAddress) {\n\n      FrontendIPConfigurationsProperties frontendProps = FrontendIPConfigurationsProperties.builder()\n            .privateIPAddress(ipAddress).privateIPAllocationMethod(\"Static\")\n            .subnet(IdReference.create(api().get(virtualNetworkName).properties().subnets().get(0).id())).build();\n      FrontendIPConfigurations frontendIps = FrontendIPConfigurations.create(\"ipConfigs\", null, frontendProps, null);\n      LoadBalancerProperties props = LoadBalancerProperties.builder()\n            .frontendIPConfigurations(ImmutableList.of(frontendIps)).build();\n\n      LoadBalancer lbCreated = lbApi().createOrUpdate(\"lbName\", LOCATION, null, null, props);\n      assertNotNull(lbCreated);\n      return lbCreated;\n   }\n\n   private void deleteLoadBalancer(LoadBalancer lbCreated) {\n      URI lbDeletedURI = lbApi().delete(lbCreated.name());\n      assertResourceDeleted(lbDeletedURI);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/VirtualNetworkApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport static com.google.common.collect.Iterables.isEmpty;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Arrays;\nimport java.util.List;\n\nimport org.jclouds.azurecompute.arm.domain.AddressSpace;\nimport org.jclouds.azurecompute.arm.domain.IpAddressAvailabilityResult;\nimport org.jclouds.azurecompute.arm.domain.VirtualNetwork;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiMockTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"VirtualNetworkApiMockTest\", singleThreaded = true)\npublic class VirtualNetworkApiMockTest extends BaseAzureComputeApiMockTest {\n\n   private final String subscriptionid = \"SUBSCRIPTIONID\";\n   private final String resourcegroup = \"myresourcegroup\";\n   private final String virtualNetwork = \"mockvirtualnetwork\";\n   private final String apiVersion = \"api-version=2015-06-15\";\n   private final String location = \"westeurope\";\n   private final String ipAvailable = \"10.20.0.7\";\n   private final String ipNotAvailable = \"10.20.0.3\";\n\n   public void getVirtualNetwork() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/virtualnetwork.json\"));\n\n      final VirtualNetworkApi vnApi = api.getVirtualNetworkApi(resourcegroup);\n      VirtualNetwork vn = vnApi.get(virtualNetwork);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/virtualNetworks/%s?%s\", subscriptionid, resourcegroup, virtualNetwork, apiVersion);\n      assertSent(server, \"GET\", path);\n      assertEquals(vn.name(), \"mockvirtualnetwork\");\n      assertEquals(vn.properties().resourceGuid(), \"1568c76a-73a4-4a60-8dfb-53b823197ccb\");\n      assertEquals(vn.properties().addressSpace().addressPrefixes().get(0), \"10.2.0.0/16\");\n      assertEquals(vn.tags().get(\"tagkey\"), \"tagvalue\");\n   }\n\n   public void checkIpNotAvailable() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/ipnotavailable.json\"));\n\n      final VirtualNetworkApi vnApi = api.getVirtualNetworkApi(resourcegroup);\n      IpAddressAvailabilityResult checkResult = vnApi.checkIPAddressAvailability(virtualNetwork, ipNotAvailable);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft\"\n                  + \".Network/virtualNetworks/%s/CheckIPAddressAvailability?ipAddress=%s&%s\", subscriptionid,\n            resourcegroup,\n            virtualNetwork, ipNotAvailable, apiVersion);\n      assertSent(server, \"GET\", path);\n      assertFalse(checkResult.available());\n      assertFalse(checkResult.availableIPAddresses().isEmpty());\n   }\n\n   public void getVirtualNetworkReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      final VirtualNetworkApi vnApi = api.getVirtualNetworkApi(resourcegroup);\n      VirtualNetwork vn = vnApi.get(virtualNetwork);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/virtualNetworks/%s?%s\", subscriptionid, resourcegroup, virtualNetwork, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertNull(vn);\n   }\n\n   public void listVirtualNetworks() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/listvirtualnetworks.json\"));\n\n      final VirtualNetworkApi vnApi = api.getVirtualNetworkApi(resourcegroup);\n      List<VirtualNetwork> vnList = vnApi.list();\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/virtualNetworks?%s\", subscriptionid, resourcegroup, apiVersion);\n\n      assertSent(server, \"GET\", path);\n      assertEquals(vnList.size(), 3);\n   }\n\n   public void listAllVirtualNetworks() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/listvirtualnetworksall.json\"));\n\n      final VirtualNetworkApi vnApi = api.getVirtualNetworkApi(null);\n      List<VirtualNetwork> vnList = vnApi.listAll();\n      String path = String.format(\"/subscriptions/%s/providers/Microsoft.Network/virtualNetworks?%s\", subscriptionid, apiVersion);\n\n      assertSent(server, \"GET\", path);\n      assertEquals(vnList.size(), 4);\n   }\n\n   public void listVirtualNetworkReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      final VirtualNetworkApi vnApi = api.getVirtualNetworkApi(resourcegroup);\n      List<VirtualNetwork> vnList = vnApi.list();\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/virtualNetworks?%s\", subscriptionid, resourcegroup, apiVersion);\n\n      assertSent(server, \"GET\", path);\n\n      assertTrue(isEmpty(vnList));\n   }\n\n   public void createVirtualNetwork() throws InterruptedException {\n\n      server.enqueue(jsonResponse(\"/createvirtualnetwork.json\").setStatus(\"HTTP/1.1 201 Created\"));\n\n      final VirtualNetworkApi vnApi = api.getVirtualNetworkApi(resourcegroup);\n\n      final VirtualNetwork.VirtualNetworkProperties virtualNetworkProperties =\n              VirtualNetwork.VirtualNetworkProperties.create(null, null,\n                      AddressSpace.create(Arrays.asList(\"10.2.0.0/16\")), null);\n\n\n      vnApi.createOrUpdate(virtualNetwork, location, null, virtualNetworkProperties);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/virtualNetworks/%s?%s\", subscriptionid, resourcegroup, virtualNetwork, apiVersion);\n      String json = String.format(\"{\\\"location\\\":\\\"%s\\\",\\\"properties\\\":{\\\"addressSpace\\\":{\\\"addressPrefixes\\\":[\\\"%s\\\"]}}}\", location, \"10.2.0.0/16\");\n      assertSent(server, \"PUT\", path, json);\n   }\n\n   public void deleteVirtualNetwork() throws InterruptedException {\n\n      server.enqueue(response202());\n\n      final VirtualNetworkApi vnApi = api.getVirtualNetworkApi(resourcegroup);\n\n      boolean status = vnApi.delete(virtualNetwork);\n      assertTrue(status);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/virtualNetworks/%s?%s\", subscriptionid, resourcegroup, virtualNetwork, apiVersion);\n      assertSent(server, \"DELETE\", path);\n\n   }\n\n   public void deleteVirtualNetworkResourceDoesNotExist() throws InterruptedException {\n\n      server.enqueue(response204());\n\n      final VirtualNetworkApi vnApi = api.getVirtualNetworkApi(resourcegroup);\n\n      boolean status = vnApi.delete(virtualNetwork);\n      assertFalse(status);\n\n      String path = String.format(\"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/virtualNetworks/%s?%s\", subscriptionid, resourcegroup, virtualNetwork, apiVersion);\n      assertSent(server, \"DELETE\", path);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/VirtualNetworkGatewayApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport static com.google.common.collect.Iterables.any;\nimport static java.util.Collections.singletonList;\nimport static java.util.logging.Logger.getAnonymousLogger;\nimport static org.jclouds.azurecompute.arm.domain.vpn.VirtualNetworkGatewayType.Vpn;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.Collections;\n\nimport org.jclouds.azurecompute.arm.domain.IdReference;\nimport org.jclouds.azurecompute.arm.domain.IpAllocationMethod;\nimport org.jclouds.azurecompute.arm.domain.Subnet;\nimport org.jclouds.azurecompute.arm.domain.VirtualNetwork;\nimport org.jclouds.azurecompute.arm.domain.publicipaddress.PublicIPAddress;\nimport org.jclouds.azurecompute.arm.domain.publicipaddress.PublicIPAddressProperties;\nimport org.jclouds.azurecompute.arm.domain.vpn.SKU;\nimport org.jclouds.azurecompute.arm.domain.vpn.SKU.SKUName;\nimport org.jclouds.azurecompute.arm.domain.vpn.SKU.SKUTier;\nimport org.jclouds.azurecompute.arm.domain.vpn.VPNType;\nimport org.jclouds.azurecompute.arm.domain.vpn.VirtualNetworkGateway;\nimport org.jclouds.azurecompute.arm.domain.vpn.VirtualNetworkGatewayProperties;\nimport org.jclouds.azurecompute.arm.domain.vpn.VirtualNetworkGatewayProperties.IpConfiguration;\nimport org.jclouds.azurecompute.arm.domain.vpn.VirtualNetworkGatewayProperties.IpConfiguration.IpConfigurationProperties;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiLiveTest;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableMap;\n\n@Test(groups = \"live\", testName = \"VirtualNetworkGatewayApiLiveTest\", singleThreaded = true)\npublic class VirtualNetworkGatewayApiLiveTest extends BaseAzureComputeApiLiveTest {\n\n   private String name;\n   private String subnetId;\n   private PublicIPAddress publicIp;\n   private Predicate<String> virtualNetworkGatewayAvailable;\n\n   @BeforeClass\n   @Override\n   public void setup() {\n      super.setup();\n      createTestResourceGroup();\n      name = \"jclouds-\" + RAND;\n      virtualNetworkGatewayAvailable = virtualNetworkGatewayStatus.create(resourceGroupName);\n\n      VirtualNetwork vnet = createDefaultVirtualNetwork(resourceGroupName, name + \"-net\", \"10.2.0.0/16\", LOCATION);\n      Subnet subnet = createDefaultSubnet(resourceGroupName, Subnet.GATEWAY_SUBNET_NAME, vnet.name(), \"10.2.0.0/23\");\n      subnetId = subnet.id();\n\n      PublicIPAddressProperties props = PublicIPAddressProperties.builder()\n            .publicIPAllocationMethod(IpAllocationMethod.Dynamic.name()).idleTimeoutInMinutes(4).build();\n      publicIp = api.getPublicIPAddressApi(resourceGroupName).createOrUpdate(name + \"-publicip\", LOCATION,\n            Collections.<String, String> emptyMap(), null, props);\n   }\n\n   @Test\n   public void createVirtualNetworkGateway() {\n      IpConfigurationProperties ipprops = IpConfigurationProperties.builder(IpAllocationMethod.Dynamic)\n            .subnet(IdReference.create(subnetId)).publicIPAddress(IdReference.create(publicIp.id())).build();\n      IpConfiguration ipconf = IpConfiguration.create(null, name + \"-ipconf\", null, ipprops);\n\n      VirtualNetworkGatewayProperties props = VirtualNetworkGatewayProperties\n            .builder(false, Vpn, SKU.create(1, SKUName.Basic, SKUTier.Basic)).vpnType(VPNType.PolicyBased)\n            .ipConfigurations(singletonList(ipconf)).build();\n\n      getAnonymousLogger().info(String.format(\"Creating virtual network gateway %s. This may take a while...\", name));\n      VirtualNetworkGateway gw = api().createOrUpdate(name, LOCATION, null, props);\n\n      assertNotNull(gw);\n      assertEquals(gw.name(), name);\n      assertNotNull(gw.properties());\n   }\n\n   @Test(dependsOnMethods = \"createVirtualNetworkGateway\")\n   public void getVirtualNetworkGateway() {\n      assertNotNull(api().get(name));\n   }\n\n   @Test(dependsOnMethods = \"createVirtualNetworkGateway\")\n   public void listVirtualNetworkGateways() {\n      assertTrue(any(api().list(), new Predicate<VirtualNetworkGateway>() {\n         @Override\n         public boolean apply(VirtualNetworkGateway input) {\n            return name.equals(input.name());\n         }\n      }));\n   }\n\n   @Test(dependsOnMethods = \"createVirtualNetworkGateway\")\n   public void updateVirtualNetworkGateway() {\n      // Make sure the resource is fully provisioned before modifying it\n      assertTrue(virtualNetworkGatewayAvailable.apply(name));\n\n      VirtualNetworkGateway gw = api().get(name);\n      gw = api().createOrUpdate(name, LOCATION, ImmutableMap.of(\"foo\", \"bar\"), gw.properties());\n\n      assertNotNull(gw);\n      assertTrue(gw.tags().containsKey(\"foo\"));\n      assertEquals(gw.tags().get(\"foo\"), \"bar\");\n   }\n\n   @Test(dependsOnMethods = { \"getVirtualNetworkGateway\", \"listVirtualNetworkGateways\", \"updateVirtualNetworkGateway\" })\n   public void deleteVirtualNetworkGateway() {\n      // Make sure the resource is fully provisioned before deleting it\n      assertTrue(virtualNetworkGatewayAvailable.apply(name));\n      URI uri = api().delete(name);\n      assertResourceDeleted(uri);\n   }\n\n   private VirtualNetworkGatewayApi api() {\n      return api.getVirtualNetworkGatewayApi(resourceGroupName);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/VirtualNetworkGatewayApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport static com.google.common.collect.Iterables.isEmpty;\nimport static java.util.Collections.singletonList;\nimport static org.jclouds.azurecompute.arm.domain.vpn.VirtualNetworkGatewayType.Vpn;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport org.jclouds.azurecompute.arm.domain.IdReference;\nimport org.jclouds.azurecompute.arm.domain.IpAllocationMethod;\nimport org.jclouds.azurecompute.arm.domain.vpn.SKU;\nimport org.jclouds.azurecompute.arm.domain.vpn.SKU.SKUName;\nimport org.jclouds.azurecompute.arm.domain.vpn.SKU.SKUTier;\nimport org.jclouds.azurecompute.arm.domain.vpn.VPNType;\nimport org.jclouds.azurecompute.arm.domain.vpn.VirtualNetworkGateway;\nimport org.jclouds.azurecompute.arm.domain.vpn.VirtualNetworkGatewayProperties;\nimport org.jclouds.azurecompute.arm.domain.vpn.VirtualNetworkGatewayProperties.IpConfiguration;\nimport org.jclouds.azurecompute.arm.domain.vpn.VirtualNetworkGatewayProperties.IpConfiguration.IpConfigurationProperties;\nimport org.jclouds.azurecompute.arm.domain.vpn.VirtualNetworkGatewayType;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiMockTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"VirtualNetworkGatewayApiMockTest\", singleThreaded = true)\npublic class VirtualNetworkGatewayApiMockTest extends BaseAzureComputeApiMockTest {\n\n   private final String subscriptionid = \"SUBSCRIPTIONID\";\n   private final String resourcegroup = \"myresourcegroup\";\n   private final String name = \"myvirtualgw\";\n   private final String apiVersion = \"api-version=2018-02-01\";\n\n   private static final String SUBNET_ID = \"/subscriptions/SUBSCRIPTIONID/resourceGroups/rg-virtualnetworkgatewayapilivetest-nacx/providers/Microsoft.Network/virtualNetworks/myvirtualgw-net/subnets/GatewaySubnet\";\n   private static final String PUBLIC_IP = \"/subscriptions/SUBSCRIPTIONID/resourceGroups/rg-virtualnetworkgatewayapilivetest-nacx/providers/Microsoft.Network/publicIPAddresses/myvirtualgw-publicip\";\n\n   public void createOrUpdateVirtualNetworkGateway() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/virtualnetworkgatewaycreate.json\").setResponseCode(200));\n      VirtualNetworkGatewayApi gwapi = api.getVirtualNetworkGatewayApi(resourcegroup);\n\n      IpConfigurationProperties ipprops = IpConfigurationProperties.builder(IpAllocationMethod.Dynamic)\n            .subnet(IdReference.create(SUBNET_ID)).publicIPAddress(IdReference.create(PUBLIC_IP)).build();\n      IpConfiguration ipconf = IpConfiguration.create(null, name + \"-ipconf\", null, ipprops);\n\n      VirtualNetworkGatewayProperties props = VirtualNetworkGatewayProperties\n            .builder(false, Vpn, SKU.create(1, SKUName.Basic, SKUTier.Basic)).vpnType(VPNType.PolicyBased)\n            .ipConfigurations(singletonList(ipconf)).build();\n\n      VirtualNetworkGateway gw = gwapi.createOrUpdate(name, \"westeurope\", null, props);\n\n      String path = String.format(\n            \"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/virtualNetworkGateways/%s?%s\",\n            subscriptionid, resourcegroup, name, apiVersion);\n      String json = \"{\\\"location\\\":\\\"westeurope\\\",\\\"properties\\\":{\\\"enableBgp\\\":false,\\\"gatewayType\\\":\\\"Vpn\\\",\\\"ipConfigurations\\\":[{\\\"name\\\":\\\"myvirtualgw-ipconf\\\",\\\"properties\\\":{\\\"privateIPAllocationMethod\\\":\\\"Dynamic\\\",\\\"publicIPAddress\\\":{\\\"id\\\":\\\"/subscriptions/SUBSCRIPTIONID/resourceGroups/rg-virtualnetworkgatewayapilivetest-nacx/providers/Microsoft.Network/publicIPAddresses/myvirtualgw-publicip\\\"},\\\"subnet\\\":{\\\"id\\\":\\\"/subscriptions/SUBSCRIPTIONID/resourceGroups/rg-virtualnetworkgatewayapilivetest-nacx/providers/Microsoft.Network/virtualNetworks/myvirtualgw-net/subnets/GatewaySubnet\\\"}}}],\\\"sku\\\":{\\\"capacity\\\":1,\\\"name\\\":\\\"Basic\\\",\\\"tier\\\":\\\"Basic\\\"},\\\"vpnType\\\":\\\"PolicyBased\\\"}}\";\n      assertSent(server, \"PUT\", path, json);\n\n      assertEquals(gw.name(), name);\n      assertNotNull(gw.properties());\n      assertEquals(gw.properties().gatewayType(), VirtualNetworkGatewayType.Vpn);\n   }\n\n   public void getVirtualNetworkGateway() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/virtualnetworkgatewayget.json\").setResponseCode(200));\n      VirtualNetworkGatewayApi gwapi = api.getVirtualNetworkGatewayApi(resourcegroup);\n\n      VirtualNetworkGateway gw = gwapi.get(name);\n\n      String path = String.format(\n            \"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/virtualNetworkGateways/%s?%s\",\n            subscriptionid, resourcegroup, name, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertEquals(gw.name(), name);\n   }\n\n   public void getVirtualNetworkGatewayReturns404() throws InterruptedException {\n      server.enqueue(response404());\n      VirtualNetworkGatewayApi gwapi = api.getVirtualNetworkGatewayApi(resourcegroup);\n\n      VirtualNetworkGateway gw = gwapi.get(name);\n\n      String path = String.format(\n            \"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/virtualNetworkGateways/%s?%s\",\n            subscriptionid, resourcegroup, name, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertNull(gw);\n   }\n\n   public void listVirtualNetworkGateways() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/virtualnetworkgatewaylist.json\").setResponseCode(200));\n      VirtualNetworkGatewayApi gwapi = api.getVirtualNetworkGatewayApi(resourcegroup);\n\n      List<VirtualNetworkGateway> gws = gwapi.list();\n\n      String path = String.format(\n            \"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/virtualNetworkGateways?%s\",\n            subscriptionid, resourcegroup, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertTrue(gws.size() > 0);\n   }\n\n   public void listVirtualNetworkGatewaysReturns404() throws InterruptedException {\n      server.enqueue(response404());\n      VirtualNetworkGatewayApi gwapi = api.getVirtualNetworkGatewayApi(resourcegroup);\n\n      List<VirtualNetworkGateway> gws = gwapi.list();\n\n      String path = String.format(\n            \"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/virtualNetworkGateways?%s\",\n            subscriptionid, resourcegroup, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertTrue(isEmpty(gws));\n   }\n\n   public void deleteVirtualNetworkGateway() throws InterruptedException {\n      server.enqueue(response202WithHeader());\n      VirtualNetworkGatewayApi gwapi = api.getVirtualNetworkGatewayApi(resourcegroup);\n\n      URI uri = gwapi.delete(name);\n      assertNotNull(uri);\n\n      String path = String.format(\n            \"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/virtualNetworkGateways/%s?%s\",\n            subscriptionid, resourcegroup, name, apiVersion);\n      assertSent(server, \"DELETE\", path);\n   }\n\n   public void deleteVirtualNetworkGatewayDoesNotExist() throws InterruptedException {\n      server.enqueue(response204());\n      VirtualNetworkGatewayApi gwapi = api.getVirtualNetworkGatewayApi(resourcegroup);\n\n      URI uri = gwapi.delete(name);\n      assertNull(uri);\n\n      String path = String.format(\n            \"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/virtualNetworkGateways/%s?%s\",\n            subscriptionid, resourcegroup, name, apiVersion);\n      assertSent(server, \"DELETE\", path);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/VirtualNetworkGatewayConnectionApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport static com.google.common.collect.Iterables.any;\nimport static java.util.Collections.singletonList;\nimport static java.util.logging.Logger.getAnonymousLogger;\nimport static org.jclouds.azurecompute.arm.domain.vpn.VirtualNetworkGatewayConnection.Type.IPsec;\nimport static org.jclouds.azurecompute.arm.domain.vpn.VirtualNetworkGatewayType.Vpn;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.Collections;\n\nimport org.jclouds.azurecompute.arm.domain.AddressSpace;\nimport org.jclouds.azurecompute.arm.domain.IdReference;\nimport org.jclouds.azurecompute.arm.domain.IpAllocationMethod;\nimport org.jclouds.azurecompute.arm.domain.Provisionable;\nimport org.jclouds.azurecompute.arm.domain.Subnet;\nimport org.jclouds.azurecompute.arm.domain.VirtualNetwork;\nimport org.jclouds.azurecompute.arm.domain.publicipaddress.PublicIPAddress;\nimport org.jclouds.azurecompute.arm.domain.publicipaddress.PublicIPAddressProperties;\nimport org.jclouds.azurecompute.arm.domain.vpn.LocalNetworkGateway;\nimport org.jclouds.azurecompute.arm.domain.vpn.LocalNetworkGatewayProperties;\nimport org.jclouds.azurecompute.arm.domain.vpn.SKU;\nimport org.jclouds.azurecompute.arm.domain.vpn.SKU.SKUName;\nimport org.jclouds.azurecompute.arm.domain.vpn.SKU.SKUTier;\nimport org.jclouds.azurecompute.arm.domain.vpn.VPNType;\nimport org.jclouds.azurecompute.arm.domain.vpn.VirtualNetworkGateway;\nimport org.jclouds.azurecompute.arm.domain.vpn.VirtualNetworkGatewayConnection;\nimport org.jclouds.azurecompute.arm.domain.vpn.VirtualNetworkGatewayConnectionProperties;\nimport org.jclouds.azurecompute.arm.domain.vpn.VirtualNetworkGatewayProperties;\nimport org.jclouds.azurecompute.arm.domain.vpn.VirtualNetworkGatewayProperties.IpConfiguration;\nimport org.jclouds.azurecompute.arm.domain.vpn.VirtualNetworkGatewayProperties.IpConfiguration.IpConfigurationProperties;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiLiveTest;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\n\n@Test(groups = \"live\", testName = \"VirtualNetworkGatewayConnectionApiLiveTest\", singleThreaded = true)\npublic class VirtualNetworkGatewayConnectionApiLiveTest extends BaseAzureComputeApiLiveTest {\n\n   private String name;\n   private LocalNetworkGateway localGateway;\n   private VirtualNetworkGateway virtualGateway;\n\n   @BeforeClass\n   @Override\n   public void setup() {\n      super.setup();\n      createTestResourceGroup();\n      name = \"jclouds-\" + RAND;\n      setupLocalGateway();\n      setupVirtualGateway();\n   }\n\n   private void setupLocalGateway() {\n      AddressSpace localAddresses = AddressSpace.create(ImmutableList.of(\"192.168.0.0/24\"));\n      LocalNetworkGatewayProperties props = LocalNetworkGatewayProperties.builder(\"1.2.3.4\")\n            .localNetworkAddressSpace(localAddresses).build();\n\n      final LocalNetworkGatewayApi lgwApi = api.getLocalNetworkGatewayApi(resourceGroupName);\n      localGateway = lgwApi.createOrUpdate(name + \"-lgw\", LOCATION, null, props);\n\n      assertTrue(resourceAvailable.apply(new Supplier<Provisionable>() {\n         @Override\n         public Provisionable get() {\n            LocalNetworkGateway gw = lgwApi.get(localGateway.name());\n            return gw == null ? null : gw.properties();\n         }\n      }));\n   }\n\n   private void setupVirtualGateway() {\n      VirtualNetwork vnet = createDefaultVirtualNetwork(resourceGroupName, name + \"-net\", \"10.2.0.0/16\", LOCATION);\n      Subnet subnet = createDefaultSubnet(resourceGroupName, Subnet.GATEWAY_SUBNET_NAME, vnet.name(), \"10.2.0.0/23\");\n\n      PublicIPAddressProperties props = PublicIPAddressProperties.builder()\n            .publicIPAllocationMethod(IpAllocationMethod.Dynamic.name()).idleTimeoutInMinutes(4).build();\n      PublicIPAddress publicIp = api.getPublicIPAddressApi(resourceGroupName).createOrUpdate(name + \"-publicip\",\n            LOCATION, Collections.<String, String> emptyMap(), null, props);\n\n      IpConfigurationProperties ipprops = IpConfigurationProperties.builder(IpAllocationMethod.Dynamic)\n            .subnet(IdReference.create(subnet.id())).publicIPAddress(IdReference.create(publicIp.id())).build();\n      IpConfiguration ipconf = IpConfiguration.create(null, name + \"-ipconf\", null, ipprops);\n\n      VirtualNetworkGatewayProperties gwProps = VirtualNetworkGatewayProperties\n            .builder(false, Vpn, SKU.create(1, SKUName.Basic, SKUTier.Basic)).vpnType(VPNType.PolicyBased)\n            .ipConfigurations(singletonList(ipconf)).build();\n\n      getAnonymousLogger().info(\n            String.format(\"Creating virtual network gateway %s-vgw. This may take a while...\", name));\n      virtualGateway = api.getVirtualNetworkGatewayApi(resourceGroupName).createOrUpdate(name + \"-vgw\", LOCATION, null,\n            gwProps);\n      assertTrue(virtualNetworkGatewayStatus.create(resourceGroupName).apply(virtualGateway.name()));\n   }\n\n   @Test\n   public void createVirtualNetworkGatewayConnection() {\n      VirtualNetworkGatewayConnectionProperties props = VirtualNetworkGatewayConnectionProperties\n            .builder(IPsec, false, false, IdReference.create(localGateway.id()),\n                  IdReference.create(virtualGateway.id())).sharedKey(\"jcl0uds\").build();\n\n      VirtualNetworkGatewayConnection conn = api().createOrUpdate(name, LOCATION, null, props);\n\n      assertNotNull(conn);\n      assertEquals(conn.name(), name);\n      assertNotNull(conn.properties());\n   }\n\n   @Test(dependsOnMethods = \"createVirtualNetworkGatewayConnection\")\n   public void getVirtualNetworkGatewayConnection() {\n      assertNotNull(api().get(name));\n   }\n\n   @Test(dependsOnMethods = \"createVirtualNetworkGatewayConnection\")\n   public void listVirtualNetworkGatewayConnections() {\n      assertTrue(any(api().list(), new Predicate<VirtualNetworkGatewayConnection>() {\n         @Override\n         public boolean apply(VirtualNetworkGatewayConnection input) {\n            return name.equals(input.name());\n         }\n      }));\n   }\n\n   @Test(dependsOnMethods = \"createVirtualNetworkGatewayConnection\")\n   public void updateVirtualNetworkGatewayConnection() {\n      // Make sure the resource is fully provisioned before modifying it\n      waitUntilAvailable(name);\n\n      VirtualNetworkGatewayConnection conn = api().get(name);\n      conn = api().createOrUpdate(name, LOCATION, ImmutableMap.of(\"foo\", \"bar\"), conn.properties());\n\n      assertNotNull(conn);\n      assertTrue(conn.tags().containsKey(\"foo\"));\n      assertEquals(conn.tags().get(\"foo\"), \"bar\");\n   }\n\n   @Test(dependsOnMethods = { \"getVirtualNetworkGatewayConnection\", \"listVirtualNetworkGatewayConnections\",\n         \"updateVirtualNetworkGatewayConnection\" })\n   public void deleteVirtualNetworkGatewayConnection() {\n      // Make sure the resource is fully provisioned before deleting it\n      waitUntilAvailable(name);\n      URI uri = api().delete(name);\n      assertResourceDeleted(uri);\n   }\n\n   private void waitUntilAvailable(final String name) {\n      assertTrue(resourceAvailable.apply(new Supplier<Provisionable>() {\n         @Override\n         public Provisionable get() {\n            VirtualNetworkGatewayConnection gw = api().get(name);\n            return gw == null ? null : gw.properties();\n         }\n      }));\n   }\n\n   private VirtualNetworkGatewayConnectionApi api() {\n      return api.getVirtualNetworkGatewayConnectionApi(resourceGroupName);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/features/VirtualNetworkGatewayConnectionApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.features;\n\nimport static com.google.common.collect.Iterables.isEmpty;\nimport static org.jclouds.azurecompute.arm.domain.vpn.VirtualNetworkGatewayConnection.Type.IPsec;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport org.jclouds.azurecompute.arm.domain.IdReference;\nimport org.jclouds.azurecompute.arm.domain.vpn.VirtualNetworkGatewayConnection;\nimport org.jclouds.azurecompute.arm.domain.vpn.VirtualNetworkGatewayConnection.Type;\nimport org.jclouds.azurecompute.arm.domain.vpn.VirtualNetworkGatewayConnectionProperties;\nimport org.jclouds.azurecompute.arm.internal.BaseAzureComputeApiMockTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"VirtualNetworkGatewayConnectionApiMockTest\", singleThreaded = true)\npublic class VirtualNetworkGatewayConnectionApiMockTest extends BaseAzureComputeApiMockTest {\n\n   private final String subscriptionid = \"SUBSCRIPTIONID\";\n   private final String resourcegroup = \"myresourcegroup\";\n   private final String name = \"myconn\";\n   private final String apiVersion = \"api-version=2018-02-01\";\n\n   private static final String LG_ID = \"/subscriptions/SUBSCRIPTIONID/resourceGroups/rg-virtualnetworkgatewayconnectionapilivetest-nacx/providers/Microsoft.Network/localNetworkGateways/jclouds-827-lgw\";\n   private static final String VG_ID = \"/subscriptions/SUBSCRIPTIONID/resourceGroups/rg-virtualnetworkgatewayconnectionapilivetest-nacx/providers/Microsoft.Network/virtualNetworkGateways/jclouds-827-vgw\";\n\n   public void createOrUpdateVirtualNetworkGateway() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/connectioncreate.json\").setResponseCode(200));\n      VirtualNetworkGatewayConnectionApi connapi = api.getVirtualNetworkGatewayConnectionApi(resourcegroup);\n\n      VirtualNetworkGatewayConnectionProperties props = VirtualNetworkGatewayConnectionProperties\n            .builder(IPsec, false, false, IdReference.create(LG_ID), IdReference.create(VG_ID)).sharedKey(\"jcl0uds\")\n            .build();\n\n      VirtualNetworkGatewayConnection conn = connapi.createOrUpdate(name, \"westeurope\", null, props);\n\n      String path = String.format(\n            \"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/connections/%s?%s\",\n            subscriptionid, resourcegroup, name, apiVersion);\n      String json = \"{\\\"location\\\":\\\"westeurope\\\",\\\"properties\\\":{\\\"connectionType\\\":\\\"IPsec\\\",\\\"enableBGP\\\":false,\\\"ipsecPolicies\\\":[],\\\"sharedKey\\\":\\\"jcl0uds\\\",\\\"tunnelConnectionStatus\\\":[],\\\"usePolicyBasedTrafficSelectors\\\":false,\\\"localNetworkGateway2\\\":{\\\"id\\\":\\\"/subscriptions/SUBSCRIPTIONID/resourceGroups/rg-virtualnetworkgatewayconnectionapilivetest-nacx/providers/Microsoft.Network/localNetworkGateways/jclouds-827-lgw\\\"},\\\"virtualNetworkGateway1\\\":{\\\"id\\\":\\\"/subscriptions/SUBSCRIPTIONID/resourceGroups/rg-virtualnetworkgatewayconnectionapilivetest-nacx/providers/Microsoft.Network/virtualNetworkGateways/jclouds-827-vgw\\\"}}}\";\n      assertSent(server, \"PUT\", path, json);\n\n      assertEquals(conn.name(), name);\n      assertNotNull(conn.properties());\n      assertEquals(conn.properties().connectionType(), Type.IPsec);\n   }\n\n   public void getVirtualNetworkGateway() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/connectionget.json\").setResponseCode(200));\n      VirtualNetworkGatewayConnectionApi connapi = api.getVirtualNetworkGatewayConnectionApi(resourcegroup);\n\n      VirtualNetworkGatewayConnection conn = connapi.get(name);\n\n      String path = String.format(\n            \"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/connections/%s?%s\",\n            subscriptionid, resourcegroup, name, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertEquals(conn.name(), name);\n   }\n\n   public void getVirtualNetworkGatewayReturns404() throws InterruptedException {\n      server.enqueue(response404());\n      VirtualNetworkGatewayConnectionApi connapi = api.getVirtualNetworkGatewayConnectionApi(resourcegroup);\n\n      VirtualNetworkGatewayConnection conn = connapi.get(name);\n\n      String path = String.format(\n            \"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/connections/%s?%s\",\n            subscriptionid, resourcegroup, name, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertNull(conn);\n   }\n\n   public void listVirtualNetworkGateways() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/connectionlist.json\").setResponseCode(200));\n      VirtualNetworkGatewayConnectionApi connapi = api.getVirtualNetworkGatewayConnectionApi(resourcegroup);\n\n      List<VirtualNetworkGatewayConnection> conns = connapi.list();\n\n      String path = String.format(\n            \"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/connections?%s\",\n            subscriptionid, resourcegroup, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertTrue(conns.size() > 0);\n   }\n\n   public void listVirtualNetworkGatewaysReturns404() throws InterruptedException {\n      server.enqueue(response404());\n      VirtualNetworkGatewayConnectionApi connapi = api.getVirtualNetworkGatewayConnectionApi(resourcegroup);\n\n      List<VirtualNetworkGatewayConnection> conns = connapi.list();\n\n      String path = String.format(\n            \"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/connections?%s\",\n            subscriptionid, resourcegroup, apiVersion);\n      assertSent(server, \"GET\", path);\n\n      assertTrue(isEmpty(conns));\n   }\n\n   public void deleteVirtualNetworkGateway() throws InterruptedException {\n      server.enqueue(response202WithHeader());\n      VirtualNetworkGatewayConnectionApi connapi = api.getVirtualNetworkGatewayConnectionApi(resourcegroup);\n\n      URI uri = connapi.delete(name);\n      assertNotNull(uri);\n\n      String path = String.format(\n            \"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/connections/%s?%s\",\n            subscriptionid, resourcegroup, name, apiVersion);\n      assertSent(server, \"DELETE\", path);\n   }\n\n   public void deleteVirtualNetworkGatewayDoesNotExist() throws InterruptedException {\n      server.enqueue(response204());\n      VirtualNetworkGatewayConnectionApi connapi = api.getVirtualNetworkGatewayConnectionApi(resourcegroup);\n\n      URI uri = connapi.delete(name);\n      assertNull(uri);\n\n      String path = String.format(\n            \"/subscriptions/%s/resourcegroups/%s/providers/Microsoft.Network/connections/%s?%s\",\n            subscriptionid, resourcegroup, name, apiVersion);\n      assertSent(server, \"DELETE\", path);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/filters/ApiVersionFilterTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.filters;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.jclouds.azurecompute.arm.config.AzureComputeProperties.API_VERSION_PREFIX;\nimport static org.jclouds.reflect.Reflection2.method;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Properties;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.internal.FilterStringsBoundToInjectorByName;\nimport org.jclouds.reflect.Invocation;\nimport org.jclouds.rest.config.InvocationConfig;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.BeforeMethod;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport com.google.inject.name.Names;\n\n@Test(groups = \"unit\", testName = \"ApiVersionFilterTest\", singleThreaded = true)\npublic class ApiVersionFilterTest {\n\n   public interface VersionedApi {\n      HttpResponse noName();\n\n      @Named(\"named:get\")\n      HttpResponse named();\n   }\n\n   private Invocation noName;\n   private Invocation named;\n   private InvocationConfig config;\n\n   @BeforeMethod\n   public void setup() {\n      noName = Invocation.create(method(VersionedApi.class, \"noName\"), ImmutableList.of());\n      named = Invocation.create(method(VersionedApi.class, \"named\"), ImmutableList.of());\n\n      config = createMock(InvocationConfig.class);\n      expect(config.getCommandName(noName)).andReturn(\"VersionedApi.noName\");\n      expect(config.getCommandName(named)).andReturn(\"named:get\");\n      replay(config);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testFailIfNoGeneratedHttpRequest() {\n      ApiVersionFilter filter = new ApiVersionFilter(config, filterStringsBoundToInjectorByName(new Properties()));\n      filter.filter(HttpRequest.builder().method(\"GET\").endpoint(\"http://localhost\").build());\n   }\n\n   @Test\n   public void testOverrideMethodVersion() {\n      Properties props = new Properties();\n      props.setProperty(API_VERSION_PREFIX + \"named:get\", \"namedversion\");\n      props.setProperty(API_VERSION_PREFIX + \"VersionedApi.noName\", \"noNameversion\");\n      ApiVersionFilter filter = new ApiVersionFilter(config, filterStringsBoundToInjectorByName(props));\n\n      HttpRequest request = GeneratedHttpRequest.builder().method(\"GET\").endpoint(\"http://localhost\")\n            .invocation(noName).addQueryParam(\"api-version\", \"original\", \"original2\").build();\n      HttpRequest filtered = filter.filter(request);\n      assertEquals(filtered.getEndpoint().getQuery(), \"api-version=noNameversion\");\n\n      request = GeneratedHttpRequest.builder().method(\"GET\").endpoint(\"http://localhost\").invocation(named)\n            .addQueryParam(\"api-version\", \"original\", \"original2\").build();\n      filtered = filter.filter(request);\n      assertEquals(filtered.getEndpoint().getQuery(), \"api-version=namedversion\");\n   }\n\n   @Test\n   public void testFallbackToClassName() {\n      Properties props = new Properties();\n      props.setProperty(API_VERSION_PREFIX + \"VersionedApi\", \"classversion\");\n      ApiVersionFilter filter = new ApiVersionFilter(config, filterStringsBoundToInjectorByName(props));\n\n      HttpRequest request = GeneratedHttpRequest.builder().method(\"GET\").endpoint(\"http://localhost\")\n            .invocation(noName).addQueryParam(\"api-version\", \"original\", \"original2\").build();\n      HttpRequest filtered = filter.filter(request);\n      assertEquals(filtered.getEndpoint().getQuery(), \"api-version=classversion\");\n\n      request = GeneratedHttpRequest.builder().method(\"GET\").endpoint(\"http://localhost\").invocation(named)\n            .addQueryParam(\"api-version\", \"original\", \"original2\").build();\n      filtered = filter.filter(request);\n      assertEquals(filtered.getEndpoint().getQuery(), \"api-version=classversion\");\n   }\n\n   @Test\n   public void testNothingChangesIfNoCustomVersion() {\n      ApiVersionFilter filter = new ApiVersionFilter(config, filterStringsBoundToInjectorByName(new Properties()));\n\n      HttpRequest request = GeneratedHttpRequest.builder().method(\"GET\").endpoint(\"http://localhost\").invocation(named)\n            .addQueryParam(\"api-version\", \"foo\").build();\n      HttpRequest filtered = filter.filter(request);\n      assertEquals(filtered.getEndpoint().getQuery(), \"api-version=foo\");\n   }\n\n   private FilterStringsBoundToInjectorByName filterStringsBoundToInjectorByName(final Properties props) {\n      Injector injector = Guice.createInjector(new AbstractModule() {\n         protected void configure() {\n            Names.bindProperties(binder(), props);\n         }\n      });\n      return new FilterStringsBoundToInjectorByName(injector);\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/functions/URIParserTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.functions;\n\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.net.URI;\n\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.Test;\nimport com.google.common.collect.Multimap;\nimport com.google.common.collect.LinkedHashMultimap;\n\n@Test(groups = \"unit\", testName = \"URIParserTest\")\npublic class URIParserTest {\n\n   public void testApply() {\n      URIParser parser = new URIParser();\n      Multimap<String, String> headers = LinkedHashMultimap.<String, String>create();\n\n      URI uri = parser.apply(HttpResponse.builder().statusCode(200).build());\n      assertNull(uri);\n\n      try {\n         uri = parser.apply(HttpResponse.builder().statusCode(202).build());\n      } catch (IllegalStateException ex) {\n         assertNotNull(ex);\n      }\n\n      headers.put(\"Location\", \"https://someuri\");\n\n      uri = parser.apply(HttpResponse.builder().statusCode(202).headers(headers).build());\n      assertNotNull(uri);\n\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/handlers/AzureRetryableErrorHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.handlers;\n\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpRetryHandler;\nimport org.jclouds.json.config.GsonModule;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.net.HttpHeaders;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\", testName = \"AzureRetryableErrorHandlerTest\")\npublic class AzureRetryableErrorHandlerTest {\n\n   private HttpRetryHandler handler;\n\n   @BeforeClass\n   public void setup() {\n      // Initialize an injector with just the Json features to get all\n      // serialization stuff\n      Injector injector = Guice.createInjector(new GsonModule());\n      handler = injector.getInstance(AzureRetryableErrorHandler.class);\n   }\n\n   @Test\n   public void testDoesNotRetryWhenNot429() {\n      HttpCommand command = new HttpCommand(HttpRequest.builder().method(\"GET\").endpoint(\"http://localhost\").build());\n      HttpResponse response = HttpResponse.builder().statusCode(400).build();\n\n      assertFalse(handler.shouldRetryRequest(command, response));\n   }\n\n   @Test\n   public void testDoesNotRetryWhenRateLimitError() {\n      HttpCommand command = new HttpCommand(HttpRequest.builder().method(\"GET\").endpoint(\"http://localhost\").build());\n      HttpResponse response = HttpResponse.builder().statusCode(429).addHeader(HttpHeaders.RETRY_AFTER, \"15\").build();\n\n      assertFalse(handler.shouldRetryRequest(command, response));\n   }\n\n   @Test\n   public void testDoesNotRetryWhenCannotParseError() {\n      HttpCommand command = new HttpCommand(HttpRequest.builder().method(\"GET\").endpoint(\"http://localhost\").build());\n      HttpResponse response = HttpResponse.builder().statusCode(429).payload(\"foo\").build();\n\n      assertFalse(handler.shouldRetryRequest(command, response));\n   }\n\n   @Test\n   public void testDoesNotRetryWhenErrorNotRetryable() {\n      String nonRetryable = \"{\\\"error\\\":{\\\"code\\\":\\\"ReferencedResourceNotProvisioned\\\",\\\"message\\\":\\\"Not provisioned\\\"}}\";\n      HttpCommand command = new HttpCommand(HttpRequest.builder().method(\"GET\").endpoint(\"http://localhost\").build());\n      HttpResponse response = HttpResponse.builder().statusCode(429).payload(nonRetryable).build();\n\n      assertFalse(handler.shouldRetryRequest(command, response));\n   }\n\n   @Test\n   public void testRetriesWhenRetryableError() {\n      String retryable = \"{\\\"error\\\":{\\\"code\\\":\\\"RetryableError\\\",\\\"message\\\":\\\"Resource busy\\\"}}\";\n      HttpCommand command = new HttpCommand(HttpRequest.builder().method(\"GET\").endpoint(\"http://localhost\").build());\n      HttpResponse response = HttpResponse.builder().statusCode(429).payload(retryable).build();\n\n      assertTrue(handler.shouldRetryRequest(command, response));\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/internal/AzureLiveTestUtils.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.internal;\n\nimport static org.jclouds.azurecompute.arm.config.AzureComputeProperties.IMAGE_PUBLISHERS;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_RUNNING;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_SUSPENDED;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_TERMINATED;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_PORT_OPEN;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_SCRIPT_COMPLETE;\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_REGIONS;\nimport static org.jclouds.oauth.v2.config.CredentialType.CLIENT_CREDENTIALS_SECRET;\nimport static org.jclouds.oauth.v2.config.OAuthProperties.CREDENTIAL_TYPE;\n\nimport java.util.Properties;\nimport java.util.concurrent.TimeUnit;\n\npublic class AzureLiveTestUtils {\n\n   public static Properties defaultProperties(Properties properties) {\n      properties = properties == null ? new Properties() : properties;\n      properties.put(CREDENTIAL_TYPE, CLIENT_CREDENTIALS_SECRET.toString());\n      properties.put(PROPERTY_REGIONS, \"westeurope\");\n      properties.put(IMAGE_PUBLISHERS, \"Canonical\");\n\n      String defaultTimeout = String.valueOf(TimeUnit.MILLISECONDS.convert(60, TimeUnit.MINUTES));\n      properties.setProperty(TIMEOUT_SCRIPT_COMPLETE, defaultTimeout);\n      properties.setProperty(TIMEOUT_NODE_RUNNING, defaultTimeout);\n      properties.setProperty(TIMEOUT_PORT_OPEN, defaultTimeout);\n      properties.setProperty(TIMEOUT_NODE_TERMINATED, defaultTimeout);\n      properties.setProperty(TIMEOUT_NODE_SUSPENDED, defaultTimeout);\n\n      return properties;\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/internal/BaseAzureComputeApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.azurecompute.arm.config.AzureComputeProperties.TIMEOUT_RESOURCE_DELETED;\nimport static org.jclouds.azurecompute.arm.config.AzureComputeProperties.VAULT_CERTIFICATE_DELETE_STATUS;\nimport static org.jclouds.azurecompute.arm.config.AzureComputeProperties.VAULT_CERTIFICATE_OPERATION_STATUS;\nimport static org.jclouds.azurecompute.arm.config.AzureComputeProperties.VAULT_CERTIFICATE_RECOVERABLE_STATUS;\nimport static org.jclouds.azurecompute.arm.config.AzureComputeProperties.VAULT_DELETE_STATUS;\nimport static org.jclouds.azurecompute.arm.config.AzureComputeProperties.VAULT_KEY_DELETED_STATUS;\nimport static org.jclouds.azurecompute.arm.config.AzureComputeProperties.VAULT_KEY_RECOVERABLE_STATUS;\nimport static org.jclouds.azurecompute.arm.config.AzureComputeProperties.VAULT_SECRET_DELETE_STATUS;\nimport static org.jclouds.azurecompute.arm.config.AzureComputeProperties.VAULT_SECRET_RECOVERABLE_STATUS;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_IMAGE_AVAILABLE;\nimport static org.jclouds.oauth.v2.config.OAuthProperties.RESOURCE;\nimport static org.jclouds.util.Predicates2.retry;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.net.URI;\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.Properties;\nimport java.util.Random;\n\nimport org.jclouds.apis.BaseApiLiveTest;\nimport org.jclouds.azurecompute.arm.AzureComputeApi;\nimport org.jclouds.azurecompute.arm.compute.config.AzurePredicatesModule.NetworkAvailablePredicateFactory;\nimport org.jclouds.azurecompute.arm.compute.config.AzurePredicatesModule.PublicIpAvailablePredicateFactory;\nimport org.jclouds.azurecompute.arm.compute.config.AzurePredicatesModule.VaultCertificatePredicates.CertificateOperationStatusPredicateFactory;\nimport org.jclouds.azurecompute.arm.compute.config.AzurePredicatesModule.VaultCertificatePredicates.DeletedCertificateStatusPredicateFactory;\nimport org.jclouds.azurecompute.arm.compute.config.AzurePredicatesModule.VaultCertificatePredicates.RecoverableCertificateStatusPredicateFactory;\nimport org.jclouds.azurecompute.arm.compute.config.AzurePredicatesModule.VaultKeyPredicates.DeletedKeyStatusPredicateFactory;\nimport org.jclouds.azurecompute.arm.compute.config.AzurePredicatesModule.VaultKeyPredicates.RecoverableKeyStatusPredicateFactory;\nimport org.jclouds.azurecompute.arm.compute.config.AzurePredicatesModule.VaultPredicates.DeletedVaultStatusPredicateFactory;\nimport org.jclouds.azurecompute.arm.compute.config.AzurePredicatesModule.VaultSecretPredicates.DeletedSecretStatusPredicateFactory;\nimport org.jclouds.azurecompute.arm.compute.config.AzurePredicatesModule.VaultSecretPredicates.RecoverableSecretStatusPredicateFactory;\nimport org.jclouds.azurecompute.arm.compute.config.AzurePredicatesModule.VirtualNetworkGatewayAvailablePredicateFactory;\nimport org.jclouds.azurecompute.arm.config.Tenant;\nimport org.jclouds.azurecompute.arm.domain.AddressSpace;\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityGroup;\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityGroupProperties;\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityRule;\nimport org.jclouds.azurecompute.arm.domain.NetworkSecurityRuleProperties;\nimport org.jclouds.azurecompute.arm.domain.Provisionable;\nimport org.jclouds.azurecompute.arm.domain.ResourceGroup;\nimport org.jclouds.azurecompute.arm.domain.Subnet;\nimport org.jclouds.azurecompute.arm.domain.VirtualNetwork;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Throwables;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Lists;\nimport com.google.common.io.Resources;\nimport com.google.inject.Injector;\nimport com.google.inject.Key;\nimport com.google.inject.Module;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.name.Names;\n\npublic class BaseAzureComputeApiLiveTest extends BaseApiLiveTest<AzureComputeApi> {\n\n   protected static final int RAND = new Random().nextInt(999);\n   public static final String LOCATION = \"westeurope\";\n   public static final String LOCATIONDESCRIPTION = \"West Europe\";\n   public static final String DEFAULT_VIRTUALNETWORK_ADDRESS_PREFIX = \"10.2.0.0/16\";\n   \n   protected Predicate<URI> imageAvailablePredicate;\n   protected Predicate<URI> resourceDeleted;\n   protected PublicIpAvailablePredicateFactory publicIpAvailable;\n   protected VirtualNetworkGatewayAvailablePredicateFactory virtualNetworkGatewayStatus;\n   protected Predicate<Supplier<Provisionable>> resourceAvailable;\n   protected DeletedVaultStatusPredicateFactory deletedVaultStatus;\n   protected DeletedKeyStatusPredicateFactory deletedKeyStatus;\n   protected RecoverableKeyStatusPredicateFactory recoverableKeyStatus;\n   protected DeletedSecretStatusPredicateFactory deletedSecretStatus;\n   protected RecoverableSecretStatusPredicateFactory recoverableSecretStatus;\n   protected DeletedCertificateStatusPredicateFactory deletedCertificateStatus;\n   protected RecoverableCertificateStatusPredicateFactory recoverableCertificateStatus;\n   protected CertificateOperationStatusPredicateFactory certificateOperationStatus;\n   protected NetworkAvailablePredicateFactory networkAvailablePredicate;\n\n   protected String resourceGroupName;\n   \n   protected String vaultResourceGroup;\n   protected String vaultName;\n   protected String vaultCertificateUrl;\n   protected String tenantId;\n\n   public BaseAzureComputeApiLiveTest() {\n      provider = \"azurecompute-arm\";\n   }\n   \n   @Override\n   @AfterClass(groups = \"live\")\n   protected void tearDown() {\n      try {\n         if (resourceGroupName != null) {\n            deleteResourceGroup(resourceGroupName);\n         }\n      } finally {\n         super.tearDown();\n      }\n   }\n\n   @BeforeClass\n   @Override\n   public void setup() {\n      super.setup();\n\n      // Providing system properties for specifying the required Azure KeyVault configurations for Live tests\n      // They have to be externally provided, because azurecompute-arm doesn't support creating KeyVaults yet\n      //\n      // TODO Replace the used configurations once full KeyVault implementation is added to azurecompute-arm\n      vaultResourceGroup = System.getProperty(\"test.azurecompute-arm.vault.resource.group\");\n      vaultName = System.getProperty(\"test.azurecompute-arm.vault.name\");\n      vaultCertificateUrl = System.getProperty(\"test.azurecompute-arm.vault.certificate.url\");\n   }\n\n   @Override protected AzureComputeApi create(Properties props, Iterable<Module> modules) {\n      Injector injector = newBuilder().modules(modules).overrides(props).buildInjector();\n      imageAvailablePredicate = injector.getInstance(Key.get(new TypeLiteral<Predicate<URI>>() {\n      }, Names.named(TIMEOUT_IMAGE_AVAILABLE)));\n      resourceDeleted = injector.getInstance(Key.get(new TypeLiteral<Predicate<URI>>() {\n      }, Names.named(TIMEOUT_RESOURCE_DELETED)));\n      publicIpAvailable = injector.getInstance(PublicIpAvailablePredicateFactory.class);\n      virtualNetworkGatewayStatus = injector.getInstance(VirtualNetworkGatewayAvailablePredicateFactory.class);\n      resourceAvailable = injector.getInstance(Key.get(new TypeLiteral<Predicate<Supplier<Provisionable>>>() {\n      }));\n      deletedVaultStatus = injector.getInstance(Key.get(DeletedVaultStatusPredicateFactory.class, Names.named(VAULT_DELETE_STATUS)));\n      deletedKeyStatus = injector.getInstance(Key.get(DeletedKeyStatusPredicateFactory.class, Names.named(VAULT_KEY_DELETED_STATUS)));\n      recoverableKeyStatus = injector.getInstance(Key.get(RecoverableKeyStatusPredicateFactory.class, Names.named(VAULT_KEY_RECOVERABLE_STATUS)));\n      deletedSecretStatus = injector.getInstance(Key.get(DeletedSecretStatusPredicateFactory.class, Names.named(VAULT_SECRET_DELETE_STATUS)));\n      recoverableSecretStatus = injector.getInstance(Key.get(RecoverableSecretStatusPredicateFactory.class, Names.named(VAULT_SECRET_RECOVERABLE_STATUS)));\n      deletedCertificateStatus = injector.getInstance(Key.get(DeletedCertificateStatusPredicateFactory.class, Names.named(VAULT_CERTIFICATE_DELETE_STATUS)));\n      recoverableCertificateStatus = injector.getInstance(Key.get(RecoverableCertificateStatusPredicateFactory.class, Names.named(VAULT_CERTIFICATE_RECOVERABLE_STATUS)));\n      certificateOperationStatus = injector.getInstance(Key.get(CertificateOperationStatusPredicateFactory.class, Names.named(VAULT_CERTIFICATE_OPERATION_STATUS)));\n      networkAvailablePredicate = injector.getInstance(NetworkAvailablePredicateFactory.class);\n\n      tenantId = injector.getInstance(Key.get(String.class, Tenant.class));\n      return injector.getInstance(AzureComputeApi.class);\n   }\n\n   @Override protected Properties setupProperties() {\n      Properties properties = super.setupProperties();\n      // for oauth\n      AzureLiveTestUtils.defaultProperties(properties);\n      checkNotNull(setIfTestSystemPropertyPresent(properties, \"oauth.endpoint\"), \"test.oauth.endpoint\");\n      setIfTestSystemPropertyPresent(properties, RESOURCE);\n      return properties;\n   }\n   \n   protected void assertResourceDeleted(URI uri) {\n      if (uri != null) {\n         assertTrue(resourceDeleted.apply(uri),\n               String.format(\"Resource %s was not terminated in the configured timeout\", uri));\n      }\n   }\n\n   protected VirtualNetwork createDefaultVirtualNetwork(final String resourceGroupName, final String virtualNetworkName, final String virtualnetworkAddressPrefix, final String location) {\n      final VirtualNetwork.VirtualNetworkProperties virtualNetworkProperties =\n              VirtualNetwork.VirtualNetworkProperties.create(null, null,\n                      AddressSpace.create(Arrays.asList(virtualnetworkAddressPrefix)), null);\n      VirtualNetwork virtualNetwork = api.getVirtualNetworkApi(resourceGroupName).createOrUpdate(virtualNetworkName, location, null, virtualNetworkProperties);\n      retry(new Predicate<String>() {\n         @Override\n         public boolean apply(final String name) {\n            VirtualNetwork virtualNetwork = api.getVirtualNetworkApi(resourceGroupName).get(name);\n            return virtualNetwork.properties().provisioningState().equals(\"Succeeded\");\n         }\n      }, 60 * 4 * 1000).apply(virtualNetwork.name());\n      return virtualNetwork;\n   }\n\n   protected Subnet createDefaultSubnet(final String resourceGroupName, final String subnetName, final String virtualNetworkName, final String subnetAddressSpace) {\n      Subnet.SubnetProperties  properties = Subnet.SubnetProperties.builder().addressPrefix(subnetAddressSpace).build();\n      Subnet subnet = api.getSubnetApi(resourceGroupName, virtualNetworkName).createOrUpdate(subnetName, properties);\n      retry(new Predicate<String>() {\n         @Override\n         public boolean apply(final String name) {\n            Subnet subnet = api.getSubnetApi(resourceGroupName, virtualNetworkName).get(name);\n            return subnet.properties().provisioningState().equals(\"Succeeded\");\n         }\n      }, 60 * 4 * 1000).apply(subnet.name());\n      return subnet;\n   }\n\n   protected void createTestResourceGroup() {\n      String name = String.format(\"rg-%s-%s\", this.getClass().getSimpleName().toLowerCase(),\n            System.getProperty(\"user.name\"));\n      ResourceGroup rg = api.getResourceGroupApi().create(name, LOCATION, ImmutableMap.<String, String> of());\n      assertNotNull(rg);\n      resourceGroupName = rg.name();\n   }\n\n   protected void deleteResourceGroup(final String resourceGroupName) {\n      URI uri = api.getResourceGroupApi().delete(resourceGroupName);\n      assertResourceDeleted(uri);\n   }\n\n   protected NetworkSecurityGroup newNetworkSecurityGroup(String nsgName, String locationName) {\n      NetworkSecurityRule rule = NetworkSecurityRule.create(\"denyallout\", null, null,\n              NetworkSecurityRuleProperties.builder()\n                      .description(\"deny all out\")\n                      .protocol(NetworkSecurityRuleProperties.Protocol.Tcp)\n                      .sourcePortRange(\"*\")\n                      .destinationPortRange(\"*\")\n                      .sourceAddressPrefix(\"*\")\n                      .destinationAddressPrefix(\"*\")\n                      .access(NetworkSecurityRuleProperties.Access.Deny)\n                      .priority(4095)\n                      .direction(NetworkSecurityRuleProperties.Direction.Outbound)\n                      .build());\n      List<NetworkSecurityRule> ruleList = Lists.newArrayList();\n      ruleList.add(rule);\n      NetworkSecurityGroup nsg = NetworkSecurityGroup.create(\"id\", nsgName, locationName, null,\n              NetworkSecurityGroupProperties.builder()\n                      .securityRules(ruleList)\n                      .build(),\n              null);\n      return nsg;\n   }\n\n   protected String getSubscriptionId() {\n      String subscriptionId = endpoint.substring(endpoint.lastIndexOf(\"/\") + 1);\n      assertNotNull(subscriptionId);\n      return subscriptionId;\n   }\n\n   protected String stringFromResource(String resourceName) {\n      try {\n         return Resources.toString(getClass().getResource(resourceName), Charsets.UTF_8);\n      } catch (IOException e) {\n         throw Throwables.propagate(e);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/java/org/jclouds/azurecompute/arm/internal/BaseAzureComputeApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.azurecompute.arm.internal;\n\nimport static com.google.common.base.Predicates.not;\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.util.concurrent.MoreExecutors.newDirectExecutorService;\nimport static org.assertj.core.util.Sets.newHashSet;\nimport static org.jclouds.oauth.v2.config.CredentialType.BEARER_TOKEN_CREDENTIALS;\nimport static org.jclouds.oauth.v2.config.OAuthProperties.CREDENTIAL_TYPE;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\nimport okhttp3.mockwebserver.RecordedRequest;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.azurecompute.arm.AzureComputeApi;\nimport org.jclouds.azurecompute.arm.AzureComputeProviderMetadata;\nimport org.jclouds.azurecompute.arm.AzureManagementApiMetadata;\nimport org.jclouds.azurecompute.arm.config.AzureComputeHttpApiModule;\nimport org.jclouds.azurecompute.arm.config.GraphRBAC;\nimport org.jclouds.concurrent.config.ExecutorServiceModule;\nimport org.jclouds.date.DateService;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.rest.ApiContext;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.testng.annotations.AfterMethod;\nimport org.testng.annotations.BeforeMethod;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.base.Predicates;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.base.Throwables;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.io.Resources;\nimport com.google.gson.JsonParser;\nimport com.google.inject.Module;\nimport com.google.inject.TypeLiteral;\n\n\npublic class BaseAzureComputeApiMockTest {\n\n   private static final String MOCK_BEARER_TOKEN = \"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik1uQ19WWmNBVGZNNXBPWWlKSE1iYTlnb0VLWSIsImtpZCI6Ik1uQ19WWmNBVGZNNXBPWWlKSE1iYTlnb0VLWSJ9\";\n   private static final String DEFAULT_ENDPOINT = new AzureComputeProviderMetadata().getEndpoint();\n\n   protected MockWebServer server;\n   protected AzureComputeApi api;\n   protected ApiContext<AzureComputeApi> context;\n   protected DateService dateService;\n\n   // So that we can ignore formatting.\n   private final JsonParser parser = new JsonParser();\n\n   @BeforeMethod\n   public void start() throws IOException, URISyntaxException {\n      server = new MockWebServer();\n      server.start();\n      \n      context = ContextBuilder.newBuilder(testProviderMetadata())\n              .credentials(\"mock\", MOCK_BEARER_TOKEN)\n              .endpoint(server.url(\"/\").toString() + \"subscriptions/SUBSCRIPTIONID\")\n              .modules(setupModules())\n              .overrides(setupProperties())\n              .build();\n      api = context.getApi();\n      dateService = context.utils().injector().getInstance(DateService.class);\n   }\n   \n   protected ProviderMetadata testProviderMetadata() {\n      // Omit the default HTTP API modules to allow overriding\n      Set<Class<? extends Module>> defaultModules = newHashSet(filter(\n            new AzureManagementApiMetadata().getDefaultModules(),\n            not(Predicates.<Class<? extends Module>> equalTo(AzureComputeHttpApiModule.class))));\n      return AzureComputeProviderMetadata.builder()\n            .apiMetadata(AzureManagementApiMetadata.builder().defaultModules(defaultModules).build()).build();\n   }\n\n   protected Properties setupProperties() {\n      Properties properties = new Properties();\n      properties.put(CREDENTIAL_TYPE, BEARER_TOKEN_CREDENTIALS.toString());\n      properties.put(\"oauth.endpoint\", \"https://login.microsoftonline.com/tenant-id/oauth2/token\");\n      return properties;\n   }\n\n   protected Set<Module> setupModules() {\n      ImmutableSet.Builder<Module> modules = ImmutableSet.builder();\n      modules.add(new ExecutorServiceModule(newDirectExecutorService()));\n      // Override the default HTTP module to accomodate custom bindings for the\n      // hardcoded endpoints such as the Graph RBAC API one.\n      modules.add(new TestAzureComputeHttpApiModule(server));\n      return modules.build();\n   }\n   \n   @AfterMethod(alwaysRun = true)\n   public void stop() throws IOException {\n      server.shutdown();\n      api.close();\n   }\n\n   protected String url(String path) {\n      return server.url(path).toString();\n   }\n\n   protected MockResponse jsonResponse(String resource) {\n      return new MockResponse().addHeader(\"Content-Type\", \"application/json\").setBody(stringFromResource(resource));\n   }\n\n   protected MockResponse response404() {\n      return new MockResponse().setStatus(\"HTTP/1.1 404 Not Found\");\n   }\n\n   protected MockResponse response200() {\n      return new MockResponse().setStatus(\"HTTP/1.1 200 OK\");\n   }\n\n   protected MockResponse response202() {\n      return new MockResponse().setStatus(\"HTTP/1.1 202 Accepted\");\n   }\n\n   protected MockResponse response204() {\n      return new MockResponse().setStatus(\"HTTP/1.1 204 No Content\");\n   }\n\n   protected MockResponse response202WithHeader() {\n      return new MockResponse()\n            .setStatus(\"HTTP/1.1 202 Accepted\")\n            .addHeader(\n                  \"Location\",\n                  \"https://management.azure.com/subscriptions/SUBSCRIPTIONID/operationresults/eyJqb2JJZCI6IlJFU09VUkNFR1JPVVBERUxFVElPTkpPQi1SVEVTVC1DRU5UUkFMVVMiLCJqb2JMb2NhdGlvbiI6ImNlbnRyYWx1cyJ9?api-version=2014-04-01\");\n   }\n\n   protected MockResponse response200WithHeader() {\n      return new MockResponse()\n              .setStatus(\"HTTP/1.1 200 O\")\n              .addHeader(\"Location\", \"https://management.azure.com/subscriptions/SUBSCRIPTIONID/operationresults/eyJqb2JJZCI6IlJFU09VUkNFR1JPVVBERUxFVElPTkpPQi1SVEVTVC1DRU5UUkFMVVMiLCJqb2JMb2NhdGlvbiI6ImNlbnRyYWx1cyJ9?api-version=2014-04-01\");\n   }\n\n   protected String stringFromResource(String resourceName) {\n      try {\n         String rsrc = Resources.toString(getClass().getResource(resourceName), Charsets.UTF_8);\n         if (rsrc.contains(DEFAULT_ENDPOINT)) {\n            rsrc = rsrc.replace(DEFAULT_ENDPOINT, url(\"\"));\n         }\n         return rsrc;\n      } catch (IOException e) {\n         throw Throwables.propagate(e);\n      }\n   }\n\n   protected RecordedRequest assertSent(MockWebServer server, String method, String path) throws InterruptedException {\n      RecordedRequest request = server.takeRequest();\n      assertEquals(request.getMethod(), method);\n      assertEquals(request.getPath(), path);\n      assertEquals(request.getHeader(\"Accept\"), \"application/json\");\n      assertEquals(request.getHeader(\"Authorization\"), \"Bearer \" + MOCK_BEARER_TOKEN);\n      return request;\n   }\n\n   protected RecordedRequest assertSent(MockWebServer server, String method, String path, String json)\n         throws InterruptedException {\n      RecordedRequest request = assertSent(server, method, path);\n      assertEquals(request.getHeader(\"Content-Type\"), \"application/json\");\n      assertEquals(parser.parse(request.getBody().readUtf8()), parser.parse(json));\n      return request;\n   }\n   \n   @ConfiguresHttpApi\n   private static class TestAzureComputeHttpApiModule extends AzureComputeHttpApiModule {\n      private final MockWebServer server;\n      \n      public TestAzureComputeHttpApiModule(MockWebServer server) {\n         this.server = server;\n      }\n\n      @Override\n      protected void bindServiceEndpoints() {\n         // Override the hardcoded service URIs to allow mocking service endpoints\n         bind(new TypeLiteral<Supplier<URI>>() {\n         }).annotatedWith(GraphRBAC.class).toInstance(\n               Suppliers.ofInstance(URI.create(server.url(\"/graphrbac\").toString() + \"/tenant-id\")));\n      }\n   }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/PublicIPAddressCreate.json",
    "content": "{\n  \"name\": \"mypublicaddress\",\n  \"id\": \"/subscriptions/fakeb2f5-4710-4e93-bdf4-419edbde2178/resourceGroups/myresourcegroup/providers/Microsoft.Network/publicIPAddresses/mypublicaddress\",\n  \"etag\": \"W/\\\"f0bdaf62-456b-4338-8f65-05417b1a55e9\\\"\",\n  \"type\": \"Microsoft.Network/publicIPAddresses\",\n  \"location\": \"northeurope\",\n  \"tags\": {\n    \"testkey\": \"testvalue\"\n  },\n  \"properties\": {\n    \"provisioningState\": \"Updating\",\n    \"resourceGuid\": \"ebe3f160-2484-447a-8980-c587b214b16f\",\n    \"publicIPAllocationMethod\": \"Static\",\n    \"idleTimeoutInMinutes\": 4,\n    \"dnsSettings\": {\n      \"domainNameLabel\": \"foobar\",\n      \"fqdn\": \"foobar.northeurope.cloudapp.azure.com\"\n    }\n  },\n  \"sku\": {\n    \"name\": \"Basic\"\n  }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/PublicIPAddressCreateDnsRecordInUse.json",
    "content": "{\n  \"error\": {\n    \"code\": \"DnsRecordInUse\",\n    \"message\": \"DNS record foobar.northeurope.cloudapp.azure.com is already used by another public IP.\",\n    \"details\": []\n  }\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/PublicIPAddressGetInfo.json",
    "content": "{\n  \"name\": \"mypublicaddress\",\n  \"id\": \"/subscriptions/fakeb2f5-4710-4e93-bdf4-419edbde2178/resourceGroups/myresourcegroup/providers/Microsoft.Network/publicIPAddresses/mypublicaddress\",\n  \"etag\": \"W/\\\"0b020646-202f-4ac6-b1a7-f9645db7c371\\\"\",\n  \"type\": \"Microsoft.Network/publicIPAddresses\",\n  \"location\": \"northeurope\",\n  \"tags\": {\n    \"testkey\": \"testvalue\"\n  },\n  \"properties\": {\n    \"provisioningState\": \"Succeeded\",\n    \"resourceGuid\": \"eb0da01e-2a30-4e84-b7a4-0ce9dde019f5\",\n    \"ipAddress\": \"12.123.12.123\",\n    \"publicIPAllocationMethod\": \"Static\",\n    \"idleTimeoutInMinutes\": 4,\n    \"dnsSettings\": {\n      \"domainNameLabel\": \"foobar\",\n      \"fqdn\": \"foobar.northeurope.cloudapp.azure.com\"\n    },\n    \"ipConfiguration\": {\n      \"id\": \"/subscriptions/fakeb2f5-4710-4e93-bdf4-419edbde2178/resourceGroups/myresourcegroup/providers/Microsoft.Network/networkInterfaces/myNic/ipConfigurations/myip1\"\n    }\n  },\n  \"sku\": {\n    \"name\": \"Basic\"\n  }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/PublicIPAddressList.json",
    "content": "{\n  \"value\": [\n    {\n      \"name\": \"my2ndpublicaddress\",\n      \"id\": \"/subscriptions/fakeb2f5-4710-4e93-bdf4-419edbde2178/resourceGroups/myresourcegroup/providers/Microsoft.Network/publicIPAddresses/my2ndpublicaddress\",\n      \"etag\": \"W/\\\"b83fa879-46ee-48a9-8120-26572449788f\\\"\",\n      \"type\": \"Microsoft.Network/publicIPAddresses\",\n      \"location\": \"northeurope\",\n      \"tags\": {\n        \"testkey\": \"testvalue\"\n      },\n      \"properties\": {\n        \"provisioningState\": \"Succeeded\",\n        \"resourceGuid\": \"ebe3f160-2484-447a-8980-c587b214b16f\",\n        \"publicIPAllocationMethod\": \"Dynamic\",\n        \"idleTimeoutInMinutes\": 4,\n        \"dnsSettings\": {\n          \"domainNameLabel\": \"foobar123\",\n          \"fqdn\": \"foobar123.northeurope.cloudapp.azure.com\"\n        }\n      }\n    },\n    {\n      \"name\": \"my3rdpublicaddress\",\n      \"id\": \"/subscriptions/fakeb2f5-4710-4e93-bdf4-419edbde2178/resourceGroups/myresourcegroup/providers/Microsoft.Network/publicIPAddresses/my3rdpublicaddress\",\n      \"etag\": \"W/\\\"17d2cf9a-7aa8-4c53-a5b8-ebc2ccb7bf93\\\"\",\n      \"type\": \"Microsoft.Network/publicIPAddresses\",\n      \"location\": \"northeurope\",\n      \"tags\": {\n        \"testkey\": \"testvalue\"\n      },\n      \"properties\": {\n        \"provisioningState\": \"Succeeded\",\n        \"resourceGuid\": \"e1107240-79c5-4829-ba16-f7a00c2763df\",\n        \"ipAddress\": \"12.12.123.123\",\n        \"publicIPAllocationMethod\": \"Static\",\n        \"idleTimeoutInMinutes\": 4\n      }\n    },\n    {\n      \"name\": \"my4thpublicaddress\",\n      \"id\": \"/subscriptions/fakeb2f5-4710-4e93-bdf4-419edbde2178/resourceGroups/myresourcegroup/providers/Microsoft.Network/publicIPAddresses/my4thpublicaddress\",\n      \"etag\": \"W/\\\"c32275e9-e1fc-465a-a5de-728c1359e123\\\"\",\n      \"type\": \"Microsoft.Network/publicIPAddresses\",\n      \"location\": \"northeurope\",\n      \"tags\": {\n        \"testkey\": \"testvalue\"\n      },\n      \"properties\": {\n        \"provisioningState\": \"Succeeded\",\n        \"resourceGuid\": \"dbde9a83-8c1a-43f4-8d81-0fa469703e8a\",\n        \"ipAddress\": \"12.12.123.124\",\n        \"publicIPAllocationMethod\": \"Static\",\n        \"idleTimeoutInMinutes\": 4\n      }\n    },\n    {\n      \"name\": \"mypublicaddress\",\n      \"id\": \"/subscriptions/fakeb2f5-4710-4e93-bdf4-419edbde2178/resourceGroups/myresourcegroup/providers/Microsoft.Network/publicIPAddresses/mypublicaddress\",\n      \"etag\": \"W/\\\"0b020646-202f-4ac6-b1a7-f9645db7c371\\\"\",\n      \"type\": \"Microsoft.Network/publicIPAddresses\",\n      \"location\": \"northeurope\",\n      \"tags\": {},\n      \"properties\": {\n        \"provisioningState\": \"Succeeded\",\n        \"resourceGuid\": \"eb0da01e-2a30-4e84-b7a4-0ce9dde019f5\",\n        \"ipAddress\": \"12.123.12.125\",\n        \"publicIPAllocationMethod\": \"Static\",\n        \"idleTimeoutInMinutes\": 4,\n        \"dnsSettings\": {\n          \"domainNameLabel\": \"foobar\",\n          \"fqdn\": \"foobar.northeurope.cloudapp.azure.com\"\n        },\n        \"ipConfiguration\": {\n          \"id\": \"/subscriptions/fakeb2f5-4710-4e93-bdf4-419edbde2178/resourceGroups/myresourcegroup/providers/Microsoft.Network/networkInterfaces/myNic/ipConfigurations/myip1\"\n        }\n      }\n    }\n  ]\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/PublicIPAddressListAll.json",
    "content": "{\n  \"value\": [\n    {\n      \"name\": \"my2ndpublicaddress\",\n      \"id\": \"/subscriptions/fakeb2f5-4710-4e93-bdf4-419edbde2178/resourceGroups/myresourcegroup/providers/Microsoft.Network/publicIPAddresses/my2ndpublicaddress\",\n      \"etag\": \"W/\\\"b83fa879-46ee-48a9-8120-26572449788f\\\"\",\n      \"type\": \"Microsoft.Network/publicIPAddresses\",\n      \"location\": \"northeurope\",\n      \"tags\": {\n        \"testkey\": \"testvalue\"\n      },\n      \"properties\": {\n        \"provisioningState\": \"Succeeded\",\n        \"resourceGuid\": \"ebe3f160-2484-447a-8980-c587b214b16f\",\n        \"publicIPAllocationMethod\": \"Dynamic\",\n        \"idleTimeoutInMinutes\": 4,\n        \"dnsSettings\": {\n          \"domainNameLabel\": \"foobar123\",\n          \"fqdn\": \"foobar123.northeurope.cloudapp.azure.com\"\n        }\n      }\n    },\n    {\n      \"name\": \"my3rdpublicaddress\",\n      \"id\": \"/subscriptions/fakeb2f5-4710-4e93-bdf4-419edbde2178/resourceGroups/myresourcegroup/providers/Microsoft.Network/publicIPAddresses/my3rdpublicaddress\",\n      \"etag\": \"W/\\\"17d2cf9a-7aa8-4c53-a5b8-ebc2ccb7bf93\\\"\",\n      \"type\": \"Microsoft.Network/publicIPAddresses\",\n      \"location\": \"northeurope\",\n      \"tags\": {\n        \"testkey\": \"testvalue\"\n      },\n      \"properties\": {\n        \"provisioningState\": \"Succeeded\",\n        \"resourceGuid\": \"e1107240-79c5-4829-ba16-f7a00c2763df\",\n        \"ipAddress\": \"12.12.123.123\",\n        \"publicIPAllocationMethod\": \"Static\",\n        \"idleTimeoutInMinutes\": 4\n      }\n    },\n    {\n      \"name\": \"my4thpublicaddress\",\n      \"id\": \"/subscriptions/fakeb2f5-4710-4e93-bdf4-419edbde2178/resourceGroups/myresourcegroup/providers/Microsoft.Network/publicIPAddresses/my4thpublicaddress\",\n      \"etag\": \"W/\\\"c32275e9-e1fc-465a-a5de-728c1359e123\\\"\",\n      \"type\": \"Microsoft.Network/publicIPAddresses\",\n      \"location\": \"northeurope\",\n      \"tags\": {\n        \"testkey\": \"testvalue\"\n      },\n      \"properties\": {\n        \"provisioningState\": \"Succeeded\",\n        \"resourceGuid\": \"dbde9a83-8c1a-43f4-8d81-0fa469703e8a\",\n        \"ipAddress\": \"12.12.123.124\",\n        \"publicIPAllocationMethod\": \"Static\",\n        \"idleTimeoutInMinutes\": 4\n      }\n    },\n    {\n      \"name\": \"mypublicaddress\",\n      \"id\": \"/subscriptions/fakeb2f5-4710-4e93-bdf4-419edbde2178/resourceGroups/myresourcegroup/providers/Microsoft.Network/publicIPAddresses/mypublicaddress\",\n      \"etag\": \"W/\\\"0b020646-202f-4ac6-b1a7-f9645db7c371\\\"\",\n      \"type\": \"Microsoft.Network/publicIPAddresses\",\n      \"location\": \"northeurope\",\n      \"tags\": {},\n      \"properties\": {\n        \"provisioningState\": \"Succeeded\",\n        \"resourceGuid\": \"eb0da01e-2a30-4e84-b7a4-0ce9dde019f5\",\n        \"ipAddress\": \"12.123.12.125\",\n        \"publicIPAllocationMethod\": \"Static\",\n        \"idleTimeoutInMinutes\": 4,\n        \"dnsSettings\": {\n          \"domainNameLabel\": \"foobar\",\n          \"fqdn\": \"foobar.northeurope.cloudapp.azure.com\"\n        },\n        \"ipConfiguration\": {\n          \"id\": \"/subscriptions/fakeb2f5-4710-4e93-bdf4-419edbde2178/resourceGroups/myresourcegroup/providers/Microsoft.Network/networkInterfaces/myNic/ipConfigurations/myip1\"\n        }\n      }\n    },\n    {\n      \"name\": \"mypublicaddressinanotherResourceGroup\",\n      \"id\": \"/subscriptions/fakeb2f5-4710-4e93-bdf4-419edbde2178/resourceGroups/anotherresourcegroup/providers/Microsoft.Network/publicIPAddresses/mypublicaddress\",\n      \"etag\": \"W/\\\"0b020646-202f-4ac6-b1a7-f9645db7c371\\\"\",\n      \"type\": \"Microsoft.Network/publicIPAddresses\",\n      \"location\": \"northeurope\",\n      \"tags\": {},\n      \"properties\": {\n        \"provisioningState\": \"Succeeded\",\n        \"resourceGuid\": \"eb0da01e-2a30-4e84-b7a4-0ce9dde019f5\",\n        \"ipAddress\": \"12.123.12.126\",\n        \"publicIPAllocationMethod\": \"Static\",\n        \"idleTimeoutInMinutes\": 4,\n        \"dnsSettings\": {\n          \"domainNameLabel\": \"foobar\",\n          \"fqdn\": \"foobarotherrg.northeurope.cloudapp.azure.com\"\n        },\n        \"ipConfiguration\": {\n          \"id\": \"/subscriptions/fakeb2f5-4710-4e93-bdf4-419edbde2178/resourceGroups/anotherresourcegroup/providers/Microsoft.Network/networkInterfaces/myNic/ipConfigurations/myip2\"\n        }\n      }\n    }\n  ]\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/activitylogalertcreate.json",
    "content": "{\n\t\"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/microsoft.insights/activityLogAlerts/myActivityLogAlertRule\",\n\t\"type\": \"Microsoft.Insights/ActivityLogAlerts\",\n\t\"name\": \"myActivityLogAlertRule\",\n\t\"location\": \"Global\",\n\t\"properties\": {\n\t\t\"scopes\": [\n\t\t\t\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/VM\"\n\t\t],\n\t\t\"condition\": {\n\t\t\t\"allOf\": [\n\t\t\t\t{\n\t\t\t\t\t\"field\": \"category\",\n\t\t\t\t\t\"equals\": \"ServiceHealth\",\n\t\t\t\t\t\"containsAny\": null,\n\t\t\t\t\t\"odata.type\": null\n\t\t\t\t}\n\t\t\t],\n\t\t\t\"odata.type\": \"\"\n\t\t},\n\t\t\"actions\": {\n\t\t\t\"actionGroups\": [\n\t\t\t\t{\n\t\t\t\t\t\"actionGroupId\": \"/subscriptions/SUBSCRIPTIONID/resourcegroups/myResourceGroup/providers/microsoft.insights/actiongroups/myAction\",\n\t\t\t\t\t\"webhookProperties\": null\n\t\t\t\t}\n\t\t\t]\n\t\t},\n\t\t\"enabled\": false,\n\t\t\"description\": \"\"\n\t},\n\t\"identity\": null\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/activitylogalertget.json",
    "content": "{\n\t\"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/microsoft.insights/activityLogAlerts/myActivityLogAlert\",\n\t\"type\": \"Microsoft.Insights/ActivityLogAlerts\",\n\t\"name\": \"myActivityLogAlert\",\n\t\"location\": \"Global\",\n\t\"kind\": null,\n\t\"tags\": {\n\t\t\"key1\": \"Test\",\n\t\t\"key2\": \"Testing\"\n\t},\n\t\"properties\": {\n\t\t\"scopes\": [\n\t\t\t\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/VM\"\n\t\t],\n\t\t\"condition\": {\n\t\t\t\"allOf\": [\n\t\t\t\t{\n\t\t\t\t\t\"field\": \"category\",\n\t\t\t\t\t\"equals\": \"Administrative\",\n\t\t\t\t\t\"containsAny\": null,\n\t\t\t\t\t\"odata.type\": null\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t\"field\": \"operationName\",\n\t\t\t\t\t\"equals\": \"Microsoft.Compute/virtualMachines/write\",\n\t\t\t\t\t\"containsAny\": null,\n\t\t\t\t\t\"odata.type\": null\n\t\t\t\t}\n\t\t\t],\n\t\t\t\"odata.type\": null\n\t\t},\n\t\t\"actions\": {\n\t\t\t\"actionGroups\": [\n\t\t\t\t{\n\t\t\t\t\t\"actionGroupId\": \"/subscriptions/SUBSCRIPTIONID/resourcegroups/armdemo/providers/microsoft.insights/actiongroups/actions\",\n\t\t\t\t\t\"webhookProperties\": {\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t]\n\t\t},\n\t\t\"enabled\": true,\n\t\t\"description\": \"test\"\n\t},\n\t\"identity\": null\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/activitylogalertresourcegroup.json",
    "content": "{\n\t\"value\": [\n\t\t{\n\t\t\t\"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/microsoft.insights/activityLogAlerts/myActivityLog\",\n\t\t\t\"type\": \"Microsoft.Insights/ActivityLogAlerts\",\n\t\t\t\"name\": \"myActivityLog\",\n\t\t\t\"location\": \"Global\",\n\t\t\t\"kind\": null,\n\t\t\t\"tags\": {\n\t\t\t\t\"key1\": \"value1\",\n\t\t\t\t\"key2\": \"value2\"\n\t\t\t},\n\t\t\t\"properties\": {\n\t\t\t\t\"scopes\": [\n\t\t\t\t\t\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM\"\n\t\t\t\t],\n\t\t\t\t\"condition\": {\n\t\t\t\t\t\"allOf\": [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\"field\": \"category\",\n\t\t\t\t\t\t\t\"equals\": \"ServiceHealth\",\n\t\t\t\t\t\t\t\"containsAny\": null\t\t\t\t\t\t\t\n\t\t\t\t\t\t} \n\t\t\t\t\t],\n\t\t\t\t\t\"odata.type\": \"\"\n\t\t\t\t},\n\t\t\t\t\"actions\": {\n\t\t\t\t\t\"actionGroups\": [\n\t\t\t\t\t \t{\n            \t\t\t  \"actionGroupId\": \"/subscriptions/SUBSCRIPTIONID/resourcegroups/myResourceGroup/providers/microsoft.insights/actiongroups/myAction\",\n              \t\t\t  \"webhookProperties\": null\n            \t\t\t}\n\t\t\t\t\t]\n\t\t\t\t},\n\t\t\t\t\"enabled\": false,\n\t\t\t\t\"description\": \"\"\n\t\t\t},\n\t\t\t\"identity\": null\n\t\t},\n\t\t{\n\t\t\t\"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/microsoft.insights/activityLogAlerts/simpleActivityLog\",\n\t\t\t\"type\": \"Microsoft.Insights/ActivityLogAlerts\",\n\t\t\t\"name\": \"simpleActivityLog\",\n\t\t\t\"location\": \"Global\",\n\t\t\t\"kind\": null,\t\t\t\n\t\t\t\"properties\": {\n\t\t\t\t\"scopes\": [\n\t\t\t\t\t\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/simpleVM\"\n\t\t\t\t],\n\t\t\t\t\"condition\": {\n\t\t\t\t\t\"allOf\": [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\"field\": \"category\",\n\t\t\t\t\t\t\t\"equals\": \"Administrative\",\n\t\t\t\t\t\t\t\"containsAny\": null\t\t\t\t\t\t\t\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\"field\": \"operationName\",\n\t\t\t\t\t\t\t\"equals\": \"Microsoft.Compute/virtualMachines/write\",\n\t\t\t\t\t\t\t\"containsAny\": null\t\t\t\t\t\t\t\n\t\t\t\t\t\t}\n\t\t\t\t\t],\n\t\t\t\t\t\"odata.type\": null\n\t\t\t\t},\n\t\t\t\t\"actions\": {\n\t\t\t\t\t\"actionGroups\": [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\"actionGroupId\": \"/subscriptions/SUBSCRIPTIONID/resourcegroups/myResourceGroup/providers/microsoft.insights/actiongroups/myAction\",\n\t\t\t\t\t\t\t\"webhookProperties\": null\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t}\n\t\t\t\t\t]\n\t\t\t\t},\n\t\t\t\t\"enabled\": true,\n\t\t\t\t\"description\": \"\"\n\t\t\t},\n\t\t\t\"identity\": null\n\t\t}\n\t]\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/alertchangestate.json",
    "content": "{\n\t\"properties\": {\n\t\t\"essentials\": {\n\t\t\t\"severity\": \"Sev4\",\n\t\t\t\"signalType\": \"Log\",\n\t\t\t\"alertState\": \"Closed\",\n\t\t\t\"monitorCondition\": \"Fired\",\n\t\t\t\"monitorService\": \"ActivityLog Administrative\",\n\t\t\t\"targetResource\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/microsoft.desktopvirtualization/hostpools/test\",\n\t\t\t\"targetResourceName\": \"test\",\n\t\t\t\"targetResourceGroup\": \"simple-vm\",\n\t\t\t\"targetResourceType\": \"microsoft.desktopvirtualization/hostpools\",\n\t\t\t\"sourceCreatedId\": \"e9bac899-9b62-4a4c-bdf0-03d0b36de44d_b19412575e566c1d66904f19b7bd652c\",\n\t\t\t\"smartGroupId\": \"5578c276-b1ac-449c-99e2-7890fa1ff59b\",\n\t\t\t\"alertRule\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/microsoft.insights/activityLogAlerts/HostPoolAlert\",\n\t\t\t\"startDateTime\": \"2021-12-16T11:18:24.7655495Z\",\n\t\t\t\"lastModifiedDateTime\": \"2021-12-17T05:57:33.8879323Z\",\n\t\t\t\"lastModifiedUserName\": \"abc@xyz.com\",\n\t\t\t\"actionStatus\": {\n\t\t\t\t\"isSuppressed\": false\n\t\t\t},\n\t\t\t\"description\": \"\"\n\t\t}\t\t\n\t},\n\t\"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/microsoft.desktopvirtualization/hostpools/test/providers/Microsoft.AlertsManagement/alerts/650d5726-xxxx-4e8c-0000-504d577da210\",\n\t\"type\": \"Microsoft.AlertsManagement/alerts\",\n\t\"name\": \"HostPoolAlert\"\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/alertgetall.json",
    "content": "{\n\t\"value\": [\n\t\t{\n\t\t\t\"properties\": {\n\t\t\t\t\"essentials\": {\n\t\t\t\t\t\"alertRule\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/microsoft.insights/activityLogAlerts/HostPoolAlert\",\n\t\t\t\t\t\"alertState\": \"New\",\n\t\t\t\t\t\"severity\": \"Sev4\",\n\t\t\t\t\t\"signalType\": \"Log\",\n\t\t\t\t\t\"monitorCondition\": \"Fired\",\n\t\t\t\t\t\"monitorService\": \"ActivityLog Administrative\",\n\t\t\t\t\t\"targetResource\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/microsoft.desktopvirtualization/hostpools/test\",\n\t\t\t\t\t\"targetResourceName\": \"test\",\n\t\t\t\t\t\"targetResourceGroup\": \"tidal-vm\",\n\t\t\t\t\t\"targetResourceType\": \"microsoft.desktopvirtualization/hostpools\",\n\t\t\t\t\t\"sourceCreatedId\": \"e9bac899-9b62-4a4c-bdf0-03d0b36de44d_b19412575e566c1d66904f19b7bd652c\",\n\t\t\t\t\t\"smartGroupId\": \"5578c276-b1ac-449c-99e2-7890fa1ff59b\",\n\t\t\t\t\t\"startDateTime\": \"2021-12-16T11:18:24.7655495Z\",\n\t\t\t\t\t\"lastModifiedDateTime\": \"2021-12-16T11:18:24.7655495Z\",\n\t\t\t\t\t\"lastModifiedUserName\": \"System\",\n\t\t\t\t\t\"actionStatus\": {\n\t\t\t\t\t\t\"isSuppressed\": false\n\t\t\t\t\t},\n\t\t\t\t\t\"description\": \"\"\n\t\t\t\t}\n\t\t\t},\n\t\t\t\"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/microsoft.desktopvirtualization/hostpools/test/providers/Microsoft.AlertsManagement/alerts/650d5726-44d5-4e8c-a7b4-504d577da210\",\n\t\t\t\"type\": \"Microsoft.AlertsManagement/alerts\",\n\t\t\t\"name\": \"HostPoolAlert\"\n\t\t}\n\t]\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/alertgethistory.json",
    "content": "{\n\t\"properties\": {\n\t\t\"alertId\": \"d9db1f27-ce08-4c6d-8ab6-c0a8fbd8bf64\",\n\t\t\"modifications\": [\n\t\t\t{\n\t\t\t\t\"modificationEvent\": \"AlertCreated\",\n\t\t\t\t\"oldValue\": \"\",\n\t\t\t\t\"newValue\": \"\",\n\t\t\t\t\"modifiedAt\": \"2021-12-15T18:01:42.4020003Z\",\n\t\t\t\t\"modifiedBy\": \"System\",\n\t\t\t\t\"comments\": \"\",\n\t\t\t\t\"description\": \"Alert fired\"\n\t\t\t}\n\t\t]\n\t},\n\t\"id\": \"/subscriptions/SUBSCRIPTIONID/resourcegroups/myResourceGroup/providers/microsoft.compute/virtualmachines/mac/providers/Microsoft.AlertsManagement/alerts/d9db1f27-ce08-4c6d-8ab6-c0a8fbd8bf64/history/default\",\n\t\"type\": \"Microsoft.AlertsManagement/alerts\",\n\t\"name\": \"myRule\"\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/alertgetsummary.json",
    "content": "{\n\t\"properties\": {\n\t\t\"groupedby\": \"severity\",\n\t\t\"total\": 1,\n\t\t\"values\": [\n\t\t\t{\n\t\t\t\t\"name\": \"Sev0\",\n\t\t\t\t\"count\": 0\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"name\": \"Sev1\",\n\t\t\t\t\"count\": 0\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"name\": \"Sev2\",\n\t\t\t\t\"count\": 0\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"name\": \"Sev3\",\n\t\t\t\t\"count\": 0\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"name\": \"Sev4\",\n\t\t\t\t\"count\": 1\n\t\t\t}\n\t\t]\n\t},\n\t\"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/microsoft.desktopvirtualization/hostpools/test/providers/Microsoft.AlertsManagement/alertsSummary/current\",\n\t\"type\": \"Microsoft.AlertsManagement/alertsSummary\",\n\t\"name\": \"current\"\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/alertsgetbyid.json",
    "content": "{\n  \"properties\": {\n    \"essentials\": {\n      \"severity\": \"Sev4\",\n      \"signalType\": \"Log\",\n      \"alertState\": \"Acknowledged\",\n      \"monitorCondition\": \"Fired\",\n      \"monitorService\": \"ActivityLog Administrative\",\n      \"targetResource\": \"/subscriptions/SUBSCRIPTIONID/resourcegroups/myResourceGroup/providers/microsoft.compute/virtualmachines/mac\",\n      \"targetResourceName\": \"mac\",\n      \"targetResourceGroup\": \"myResourceGroup\",\n      \"targetResourceType\": \"microsoft.compute/virtualmachines\",\n      \"sourceCreatedId\": \"4f4f8514-8dcc-483d-bfd4-90142a63fe06_952656992461616e11c062eeaaed472d\",\n      \"smartGroupId\": \"54ebf82c-b522-4520-b582-6c6382477b6a\",\n      \"smartGroupingReason\": \"Similar to other alerts in the group\",\n      \"alertRule\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/microsoft.insights/activityLogAlerts/SampleAlert\",\n      \"startDateTime\": \"2021-12-15T04:21:17.7200826Z\",\n      \"lastModifiedDateTime\": \"2021-12-15T04:23:20.9184138Z\",\n      \"lastModifiedUserName\": \"abc@xyz.com\",\n      \"actionStatus\": {\n        \"isSuppressed\": false\n      },\n      \"description\": \"\"\n    } \n  },\n  \"id\": \"/subscriptions/SUBSCRIPTIONID/resourcegroups/myResourceGroup/providers/microsoft.compute/virtualmachines/mac/providers/Microsoft.AlertsManagement/alerts/60c4d62b-xxxx-46d8-0000-b6dd8c4a769e\",\n  \"type\": \"Microsoft.AlertsManagement/alerts\",\n  \"name\": \"SampleAlert\"\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/availabilitysetcreate.json",
    "content": "{\n  \"properties\": {\n    \"platformUpdateDomainCount\": 2,\n    \"platformFaultDomainCount\": 3\n  },\n  \"type\": \"Microsoft.Compute/availabilitySets\",\n  \"location\": \"westeurope\",\n  \"tags\": {},\n  \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myresourcegroup/providers/Microsoft.Compute/availabilitySets/myas\",\n  \"name\": \"myas\"\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/availabilitysetget.json",
    "content": "{\n  \"properties\": {\n    \"platformUpdateDomainCount\": 2,\n    \"platformFaultDomainCount\": 3,\n    \"virtualMachines\": []\n  },\n  \"type\": \"Microsoft.Compute/availabilitySets\",\n  \"location\": \"westeurope\",\n  \"tags\": {},\n  \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myresourcegroup/providers/Microsoft.Compute/availabilitySets/myas\",\n  \"name\": \"myas\"\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/availabilitysetlist.json",
    "content": "{\n  \"value\": [\n    {\n      \"properties\": {\n        \"platformUpdateDomainCount\": 2,\n        \"platformFaultDomainCount\": 3,\n        \"virtualMachines\": []\n      },\n      \"type\": \"Microsoft.Compute/availabilitySets\",\n      \"location\": \"westeurope\",\n      \"tags\": {},\n      \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myresourcegroup/providers/Microsoft.Compute/availabilitySets/myas\",\n      \"name\": \"myas\"\n    }\n  ]\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/connectioncreate.json",
    "content": "{\n      \"name\": \"myconn\",\n      \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/rg-virtualnetworkgatewayconnectionapilivetest-nacx/providers/Microsoft.Network/connections/myconn\",\n      \"etag\": \"W/\\\"e6f08058-3815-4498-858b-0fe750e086c8\\\"\",\n      \"type\": \"Microsoft.Network/connections\",\n      \"location\": \"westeurope\",\n      \"properties\": {\n        \"provisioningState\": \"Updating\",\n        \"resourceGuid\": \"1c7fc4e8-5d48-476b-b951-38279aec7d63\",\n        \"virtualNetworkGateway1\": {\n          \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/rg-virtualnetworkgatewayconnectionapilivetest-nacx/providers/Microsoft.Network/virtualNetworkGateways/jclouds-827-vgw\"\n        },\n        \"localNetworkGateway2\": {\n          \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/rg-virtualnetworkgatewayconnectionapilivetest-nacx/providers/Microsoft.Network/localNetworkGateways/jclouds-827-lgw\"\n        },\n        \"connectionType\": \"IPsec\",\n        \"routingWeight\": 0,\n        \"sharedKey\": \"jcl0uds\",\n        \"enableBgp\": false,\n        \"usePolicyBasedTrafficSelectors\": false,\n        \"ipsecPolicies\": [],\n        \"ingressBytesTransferred\": 0,\n        \"egressBytesTransferred\": 0,\n        \"tunnelConnectionStatus\": []\n      }\n    }"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/connectionget.json",
    "content": "{\n    \"name\": \"myconn\",\n    \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/rg-virtualnetworkgatewayconnectionapilivetest-nacx/providers/Microsoft.Network/connections/myconn\",\n    \"etag\": \"W/\\\"e6f08058-3815-4498-858b-0fe750e086c8\\\"\",\n    \"type\": \"Microsoft.Network/connections\",\n    \"location\": \"westeurope\",\n    \"properties\": {\n      \"provisioningState\": \"Updating\",\n      \"resourceGuid\": \"1c7fc4e8-5d48-476b-b951-38279aec7d63\",\n      \"virtualNetworkGateway1\": {\n        \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/rg-virtualnetworkgatewayconnectionapilivetest-nacx/providers/Microsoft.Network/virtualNetworkGateways/jclouds-827-vgw\"\n      },\n      \"localNetworkGateway2\": {\n        \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/rg-virtualnetworkgatewayconnectionapilivetest-nacx/providers/Microsoft.Network/localNetworkGateways/jclouds-827-lgw\"\n      },\n      \"connectionType\": \"IPsec\",\n      \"routingWeight\": 0,\n      \"sharedKey\": \"jcl0uds\",\n      \"enableBgp\": false,\n      \"usePolicyBasedTrafficSelectors\": false,\n      \"ipsecPolicies\": [],\n      \"ingressBytesTransferred\": 0,\n      \"egressBytesTransferred\": 0,\n      \"tunnelConnectionStatus\": []\n    }\n  }"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/connectionlist.json",
    "content": "{\n    \"value\": [\n      {\n        \"name\": \"myconn\",\n        \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/rg-virtualnetworkgatewayconnectionapilivetest-nacx/providers/Microsoft.Network/connections/myconn\",\n        \"etag\": \"W/\\\"e6f08058-3815-4498-858b-0fe750e086c8\\\"\",\n        \"type\": \"Microsoft.Network/connections\",\n        \"location\": \"westeurope\",\n        \"properties\": {\n          \"provisioningState\": \"Updating\",\n          \"resourceGuid\": \"1c7fc4e8-5d48-476b-b951-38279aec7d63\",\n          \"virtualNetworkGateway1\": {\n            \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/rg-virtualnetworkgatewayconnectionapilivetest-nacx/providers/Microsoft.Network/virtualNetworkGateways/jclouds-827-vgw\"\n          },\n          \"localNetworkGateway2\": {\n            \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/rg-virtualnetworkgatewayconnectionapilivetest-nacx/providers/Microsoft.Network/localNetworkGateways/jclouds-827-lgw\"\n          },\n          \"connectionType\": \"IPsec\",\n          \"routingWeight\": 0,\n          \"enableBgp\": false,\n          \"usePolicyBasedTrafficSelectors\": false,\n          \"ipsecPolicies\": [],\n          \"ingressBytesTransferred\": 0,\n          \"egressBytesTransferred\": 0,\n          \"tunnelConnectionStatus\": []\n        }\n      }\n    ]\n  }"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/createdeploymentaccepted.json",
    "content": "{\n  \"id\": \"/subscriptions/04f7ec88-8e28-41ed-8537-5e17766001f5/resourceGroups/jims216group/providers/Microsoft.Resources/deployments/jcdep1458344383064\",\n  \"name\": \"jcdep1458344383064\",\n  \"properties\": {\n    \"parameters\": {\n      \"newStorageAccountName\": {\n        \"type\": \"String\",\n        \"value\": \"jcres1458344383064\"\n      },\n      \"storageAccountType\": {\n        \"type\": \"String\",\n        \"value\": \"Standard_LRS\"\n      },\n      \"location\": {\n        \"type\": \"String\",\n        \"value\": \"West US\"\n      }\n    },\n    \"mode\": \"Incremental\",\n    \"provisioningState\": \"Accepted\",\n    \"timestamp\": \"2016-03-18T23:39:47.3048037Z\",\n    \"duration\": \"PT2.4433028S\",\n    \"correlationId\": \"8dee9711-8632-4948-9fe6-368bb75e6438\",\n    \"providers\": [{\n      \"namespace\": \"Microsoft.Storage\",\n      \"resourceTypes\": [{\n        \"resourceType\": \"storageAccounts\",\n        \"locations\": [\"westus\"]\n      }]\n    }],\n    \"dependencies\": []\n  }\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/createdeploymentsucceeded.json",
    "content": "{\n  \"id\": \"/subscriptions/04f7ec88-8e28-41ed-8537-5e17766001f5/resourceGroups/jims216group/providers/Microsoft.Resources/deployments/jcdep1458344383064\",\n  \"name\": \"jcdep1458344383064\",\n  \"properties\": {\n    \"parameters\": {\n      \"newStorageAccountName\": {\n        \"type\": \"String\",\n        \"value\": \"jcres1458344383064\"\n      },\n      \"storageAccountType\": {\n        \"type\": \"String\",\n        \"value\": \"Standard_LRS\"\n      },\n      \"location\": {\n        \"type\": \"String\",\n        \"value\": \"West US\"\n      }\n    },\n    \"mode\": \"Incremental\",\n    \"provisioningState\": \"Succeeded\",\n    \"timestamp\": \"2016-03-18T23:40:25.1856907Z\",\n    \"duration\": \"PT40.3241898S\",\n    \"correlationId\": \"8dee9711-8632-4948-9fe6-368bb75e6438\",\n    \"providers\": [{\n      \"namespace\": \"Microsoft.Storage\",\n      \"resourceTypes\": [{\n        \"resourceType\": \"storageAccounts\",\n        \"locations\": [\"westus\"]\n      }]\n    }],\n    \"dependencies\": [],\n    \"outputResources\": [{\n      \"id\": \"Microsoft.Storage/storageAccounts/jcres1458344383064\"\n    }]\n  }\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/creatediskresponse.json",
    "content": "{\n  \"properties\": {\n    \"creationData\": {\n      \"createOption\": \"Empty\"\n    },\n    \"diskSizeGB\": 2,\n    \"provisioningState\": \"Updating\",\n    \"isArmResource\": true\n  },\n  \"location\": \"westeurope\"\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/creatediskwithtagsandskuresponse.json",
    "content": "{\n  \"properties\": {\n    \"creationData\": {\n      \"createOption\": \"Empty\"\n    },\n    \"diskSizeGB\": 2,\n    \"provisioningState\": \"Updating\",\n    \"isArmResource\": true\n  },\n  \"tags\": {\n    \"exampleTag\": \"jclouds-test-tag\"\n  },\n  \"sku\": {\n    \"name\": \"Premium_LRS\"\n  },\n  \"location\": \"westeurope\"\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/creatediskwithtagsresponse.json",
    "content": "{\n  \"properties\": {\n    \"creationData\": {\n      \"createOption\": \"Empty\"\n    },\n    \"diskSizeGB\": 2,\n    \"provisioningState\": \"Updating\",\n    \"isArmResource\": true\n  },\n  \"tags\": {\n    \"exampleTag\": \"jclouds-test-tag\"\n  },\n  \"location\": \"westeurope\"\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/createnetworkinterfacecard.json",
    "content": "{\n  \"name\": \"myusualvm607\",\n  \"id\": \"/subscriptions/bd81406c-6028-4037-9f03-9a3af4ff725d/resourceGroups/abiquo-eastus/providers/Microsoft.Network/networkInterfaces/myusualvm607\",\n  \"etag\": \"W/\\\"01f72f0f-a12f-426a-bf9a-25d09be49cee\\\"\",\n  \"location\": \"eastus\",\n  \"tags\": {\n    \"mycustomtag\": \"foobar\"\n  },\n  \"properties\": {\n    \"provisioningState\": \"Succeeded\",\n    \"resourceGuid\": \"40a46008-5368-4e9f-ba39-a87b76ea047d\",\n    \"ipConfigurations\": [\n      {\n        \"name\": \"ipconfig1\",\n        \"id\": \"/subscriptions/bd81406c-6028-4037-9f03-9a3af4ff725d/resourceGroups/abiquo-eastus/providers/Microsoft.Network/networkInterfaces/myusualvm607/ipConfigurations/ipconfig1\",\n        \"etag\": \"W/\\\"01f72f0f-a12f-426a-bf9a-25d09be49cee\\\"\",\n        \"properties\": {\n          \"provisioningState\": \"Succeeded\",\n          \"privateIPAddress\": \"192.168.0.4\",\n          \"privateIPAllocationMethod\": \"Dynamic\",\n          \"publicIPAddress\": {\n            \"id\": \"/subscriptions/bd81406c-6028-4037-9f03-9a3af4ff725d/resourceGroups/abiquo-eastus/providers/Microsoft.Network/publicIPAddresses/myusualvm-ip\"\n          },\n          \"subnet\": {\n            \"id\": \"/subscriptions/bd81406c-6028-4037-9f03-9a3af4ff725d/resourceGroups/abiquo-eastus/providers/Microsoft.Network/virtualNetworks/abqvnet-bf0tuznt0x/subnets/abqsubnet-reauuik6qx\"\n          },\n          \"primary\": true,\n          \"privateIPAddressVersion\": \"IPv4\",\n          \"isInUseWithService\": false\n        }\n      }\n    ],\n    \"dnsSettings\": {\n      \"dnsServers\": [],\n      \"appliedDnsServers\": [],\n      \"internalDomainNameSuffix\": \"zqh4yoheybzejmruwtgyl2semg.bx.internal.cloudapp.net\"\n    },\n    \"macAddress\": \"00-0D-3A-17-A4-C9\",\n    \"enableAcceleratedNetworking\": false,\n    \"enableIPForwarding\": false,\n    \"networkSecurityGroup\": {\n      \"id\": \"/subscriptions/bd81406c-6028-4037-9f03-9a3af4ff725d/resourceGroups/abiquo-eastus/providers/Microsoft.Network/networkSecurityGroups/myusualvm-nsg\"\n    },\n    \"primary\": true,\n    \"virtualMachine\": {\n      \"id\": \"/subscriptions/bd81406c-6028-4037-9f03-9a3af4ff725d/resourceGroups/abiquo-eastus/providers/Microsoft.Compute/virtualMachines/myusualvm\"\n    }\n  },\n  \"type\": \"Microsoft.Network/networkInterfaces\"\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/createsubnet.json",
    "content": "{\n  \"properties\":{\n    \"addressPrefix\":\"10.2.0.0/24\"\n  }\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/createsubnetresponse.json",
    "content": "{\n  \"name\": \"mysubnet\",\n  \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/azurearmtesting/providers/Microsoft.Network/virtualNetworks/myvirtualnetwork/subnets/mysubnet\",\n  \"etag\": \"W/\\\"b68ab7a3-38d5-4690-a978-20149a6a0994\\\"\",\n  \"properties\": {\n    \"provisioningState\": \"Succeeded\",\n    \"addressPrefix\": \"10.2.0.0/24\",\n    \"ipConfigurations\": [\n      {\n        \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/azurearmtesting/providers/Microsoft.Network/networkInterfaces/myNic/ipConfigurations/myip1\"\n      }\n    ]\n  }\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/createvirtualmachineresponse.json",
    "content": "{\n  \"properties\": {\n    \"vmId\": \"27ee085b-d707-xxxx-yyyy-2370e2eb1cc1\",\n    \"licenseType\": \"Windows_Server\",\n    \"availabilitySet\": {\n      \"id\":\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/availabilitySets/myAVSet\"\n    },\n    \"hardwareProfile\": {\n      \"vmSize\": \"Standard_D1\"\n    },\n    \"storageProfile\": {\n      \"imageReference\": {\n        \"publisher\": \"publisher\",\n        \"offer\": \"OFFER\",\n        \"sku\": \"sku\",\n        \"version\": \"ver\",\n        \"id\": \"/subscriptions/SUBSCRIPTIONID/providers/Microsoft.Compute/locations/westus/publishers/MicrosoftWindowsServerEssentials/artifactype/vmimage/offers/OFFER/skus/OFFER/versions/latest\"\n      },\n      \"osDisk\": {\n        \"osType\": \"Windows\",\n        \"name\": \"windowsmachine\",\n        \"createOption\": \"FromImage\",\n        \"managedDisk\": {\n          \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/osDisk\",\n          \"storageAccountType\": \"Standard_LRS\"\n        },\n        \"caching\": \"ReadWrite\"\n      },\n      \"dataDisks\":[\n        {\n          \"name\":\"mydatadisk1\",\n          \"diskSizeGB\":\"1\",\n          \"lun\": 0,\n          \"managedDisk\": {\n            \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/osDisk\",\n            \"storageAccountType\": \"Standard_LRS\"\n          },\n          \"caching\": \"ReadWrite\",\n          \"createOption\":\"Empty\"\n        }\n      ]\n    },\n    \"osProfile\": {\n      \"computerName\": \"windowsmachine\",\n      \"adminUsername\": \"azureuser\",\n      \"adminPassword\": \"password\",\n      \"customData\": \"\",\n      \"windowsConfiguration\": {\n        \"provisionVMAgent\": false,\n        \"enableAutomaticUpdates\": true,\n        \"winRM\": {    \n          \"listeners\": [\n            {    \n              \"protocol\": \"https\",    \n              \"certificateUrl\": \"url-to-certificate\"    \n            }\n          ]\n        },    \n        \"additionalUnattendContent\": [\n          {      \n            \"passName\":\"oobesystem\",    \n            \"componentName\":\"Microsoft-Windows-Shell-Setup\",    \n            \"settingName\":\"FirstLogonCommands\",    \n            \"content\":\"<XML unattend content>\"    \n          }\n        ]\n      },\n      \"secrets\":[\n        {     \n          \"sourceVault\": {\n             \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myresourcegroup1/providers/Microsoft.KeyVault/vaults/myvault1\"     \n           },\n           \"vaultCertificates\": [\n             {\n               \"certificateUrl\": \"https://myvault1.vault.azure.net/secrets/SECRETNAME/SECRETVERSION\",\n               \"certificateStore\": \"CERTIFICATESTORENAME\"\n             }\n           ]\n         }\n       ]\n    },\n    \"networkProfile\": {\n      \"networkInterfaces\":[\n        {\n          \"id\":\"/subscriptions/SUBSCRIPTIONID/resourceGroups/groupname/providers/Microsoft.Network/networkInterfaces/windowsmachine167\"\n        }\n      ]\n    },\n    \"diagnosticsProfile\": {\n      \"bootDiagnostics\": {\n        \"enabled\": true,\n        \"storageUri\": \"https://groupname2760.blob.core.windows.net/\"\n      }\n    },\n    \"provisioningState\": \"Creating\"\n  },\n  \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/groupname/providers/Microsoft.Compute/virtualMachines/windowsmachine\",\n  \"name\": \"windowsmachine\",\n  \"type\": \"Microsoft.Compute/virtualMachines\",\n  \"location\": \"westus\",\n  \"tags\": {\n    \"foo\": \"bar\"\n  },\n  \"plan\": {\n    \"name\": \"deadline-slave-7-2\",\n    \"publisher\": \"thinkboxsoftware\",\n    \"product\": \"deadline7-2\"\n  }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/createvirtualnetwork.json",
    "content": "{\n  \"name\": \"mockvirtualnetwork\",\n  \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/azurearmtesting/providers/Microsoft.Network/virtualNetworks/mockvirtualnetwork\",\n  \"etag\": \"W/\\\"bb0f3bf7-381e-424b-8e00-8f813c61956c\\\"\",\n  \"type\": \"Microsoft.Network/virtualNetworks\",\n  \"location\": \"westeurope\",\n  \"tags\": {\n    \"key\": \"value\"\n  },\n  \"properties\": {\n    \"provisioningState\": \"Updating\",\n    \"resourceGuid\": \"5192bdb3-f6ed-44ad-bf4c-059cff905791\",\n    \"addressSpace\": {\n      \"addressPrefixes\": [\n        \"10.2.0.0/16\"\n      ]\n    },\n    \"subnets\": []\n  }\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/getdisk.json",
    "content": "{\n  \"sku\": {\n    \"name\": \"Standard_LRS\",\n    \"tier\": \"Standard\"\n  },\n  \"properties\": {\n    \"creationData\": {\n      \"createOption\": \"Empty\"\n    },\n    \"diskSizeGB\": 2,\n    \"timeCreated\": \"2017-03-01T09:38:18.5808215+00:00\",\n    \"provisioningState\": \"Succeeded\",\n    \"diskState\": \"Unattached\"\n  },\n  \"type\": \"Microsoft.Compute/disks\",\n  \"location\": \"westeurope\",\n  \"id\": \"/subscriptions/610bba05-d7a7-4567-96af-48ecbd09453b/resourceGroups/rg-diskapilivetest-andrea/providers/Microsoft.Compute/disks/myDisk\",\n  \"name\": \"myDisk\"\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/getnetworkinterfacecard.json",
    "content": "{\n  \"name\": \"myNic\",\n  \"id\": \"/subscriptions/12345678-2749-4e68-9dcf-123456789abc/resourceGroups/azurearmtesting/providers/Microsoft.Network/networkInterfaces/myNic\",\n  \"etag\": \"W/\\\"3dff0c55-a7a7-434f-837b-0cad946b755f\\\"\",\n  \"type\": \"Microsoft.Network/networkInterfaces\",\n  \"location\": \"northeurope\",\n  \"tags\": {\n    \"mycustomtag\": \"foobar\"\n  },\n  \"properties\": {\n    \"provisioningState\": \"Succeeded\",\n    \"resourceGuid\": \"f3465472-536f-49e7-9e9c-fa91b971a618\",\n    \"ipConfigurations\": [\n      {\n        \"name\": \"myip1\",\n        \"id\": \"/subscriptions/12345678-2749-4e68-9dcf-123456789abc/resourceGroups/azurearmtesting/providers/Microsoft.Network/networkInterfaces/myNic/ipConfigurations/myip1\",\n        \"etag\": \"W/\\\"3dff0c55-a7a7-434f-837b-0cad946b755f\\\"\",\n        \"properties\": {\n          \"provisioningState\": \"Succeeded\",\n          \"privateIPAddress\": \"10.2.0.4\",\n          \"privateIPAllocationMethod\": \"Dynamic\",\n          \"subnet\": {\n            \"id\": \"/subscriptions/12345678-2749-4e68-9dcf-123456789abc/resourceGroups/azurearmtesting/providers/Microsoft.Network/virtualNetworks/myvirtualnetwork/subnets/mysubnet\"\n          },\n          \"primary\": true\n        }\n      }\n    ],\n    \"primary\": true,\n    \"dnsSettings\": {\n      \"dnsServers\": [],\n      \"appliedDnsServers\": []\n    },\n    \"enableIPForwarding\": false\n  }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/getonesubnet.json",
    "content": "{\n  \"name\": \"mysubnet\",\n  \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/azurearmtesting/providers/Microsoft.Network/virtualNetworks/myvirtualnetwork/subnets/mysubnet\",\n  \"etag\": \"W/\\\"bc7e1d77-eec0-4b91-ae80-afc33cf3c867\\\"\",\n  \"properties\": {\n    \"provisioningState\": \"Succeeded\",\n    \"addressPrefix\": \"10.2.0.0/24\",\n    \"ipConfigurations\": [\n      {\n        \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/azurearmtesting/providers/Microsoft.Network/networkInterfaces/myNic/ipConfigurations/myip1\"\n      }\n    ]\n  }\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/getresourceprovidermetadata.json",
    "content": "{\n  \"id\": \"/subscriptions/SUBSCRIPTIONID/providers/Microsoft.Compute\",\n  \"namespace\": \"Microsoft.Compute\",\n  \"authorization\": {\n    \"applicationId\": \"12312312-1212-1212-1212-121212121212\",\n    \"roleDefinitionId\": \"34534534-272e-4238-8723-123423452224\"\n  },\n  \"resourceTypes\": [\n    {\n      \"resourceType\": \"availabilitySets\",\n      \"locations\": [\n        \"East US\",\n        \"East US 2\",\n        \"West US\",\n        \"Central US\",\n        \"North Central US\",\n        \"South Central US\",\n        \"North Europe\",\n        \"West Europe\",\n        \"East Asia\",\n        \"Southeast Asia\",\n        \"Japan East\",\n        \"Japan West\",\n        \"Brazil South\"\n      ],\n      \"apiVersions\": [\n        \"2016-03-30\",\n        \"2015-06-15\",\n        \"2015-05-01-preview\"\n      ],\n      \"capabilities\": \"CrossResourceGroupResourceMove, CrossSubscriptionResourceMove\"\n    },\n    {\n      \"resourceType\": \"virtualMachines\",\n      \"locations\": [\n        \"East US\",\n        \"East US 2\",\n        \"West US\",\n        \"Central US\",\n        \"North Central US\",\n        \"South Central US\",\n        \"North Europe\",\n        \"West Europe\",\n        \"East Asia\",\n        \"Southeast Asia\",\n        \"Japan East\",\n        \"Japan West\",\n        \"Brazil South\"\n      ],\n      \"apiVersions\": [\n        \"2016-03-30\",\n        \"2015-06-15\",\n        \"2015-05-01-preview\"\n      ],\n      \"capabilities\": \"CrossResourceGroupResourceMove, CrossSubscriptionResourceMove\"\n    },\n    {\n      \"resourceType\": \"virtualMachines/extensions\",\n      \"locations\": [\n        \"East US\",\n        \"East US 2\",\n        \"West US\",\n        \"Central US\",\n        \"North Central US\",\n        \"South Central US\",\n        \"North Europe\",\n        \"West Europe\",\n        \"East Asia\",\n        \"Southeast Asia\",\n        \"Japan East\",\n        \"Japan West\",\n        \"Brazil South\"\n      ],\n      \"apiVersions\": [\n        \"2016-03-30\",\n        \"2015-06-15\",\n        \"2015-05-01-preview\"\n      ],\n      \"capabilities\": \"CrossResourceGroupResourceMove, CrossSubscriptionResourceMove\"\n    },\n    {\n      \"resourceType\": \"virtualMachines/diagnosticSettings\",\n      \"locations\": [\n        \"East US\",\n        \"East US 2\",\n        \"West US\",\n        \"Central US\",\n        \"North Central US\",\n        \"South Central US\",\n        \"North Europe\",\n        \"West Europe\",\n        \"East Asia\",\n        \"Southeast Asia\",\n        \"Japan East\",\n        \"Japan West\",\n        \"Brazil South\"\n      ],\n      \"apiVersions\": [\n        \"2014-04-01\"\n      ]\n    },\n    {\n      \"resourceType\": \"virtualMachines/metricDefinitions\",\n      \"locations\": [\n        \"East US\",\n        \"East US 2\",\n        \"West US\",\n        \"Central US\",\n        \"North Central US\",\n        \"South Central US\",\n        \"North Europe\",\n        \"West Europe\",\n        \"East Asia\",\n        \"Southeast Asia\",\n        \"Japan East\",\n        \"Japan West\",\n        \"Brazil South\"\n      ],\n      \"apiVersions\": [\n        \"2014-04-01\"\n      ]\n    },\n    {\n      \"resourceType\": \"virtualMachineScaleSets\",\n      \"locations\": [\n        \"East US\",\n        \"East US 2\",\n        \"West US\",\n        \"Central US\",\n        \"North Central US\",\n        \"South Central US\",\n        \"North Europe\",\n        \"West Europe\",\n        \"East Asia\",\n        \"Southeast Asia\",\n        \"Japan East\",\n        \"Japan West\",\n        \"Brazil South\"\n      ],\n      \"apiVersions\": [\n        \"2016-03-30\",\n        \"2015-06-15\",\n        \"2015-05-01-preview\"\n      ],\n      \"capabilities\": \"None\"\n    },\n    {\n      \"resourceType\": \"virtualMachineScaleSets/extensions\",\n      \"locations\": [\n        \"East US\",\n        \"East US 2\",\n        \"West US\",\n        \"Central US\",\n        \"North Central US\",\n        \"South Central US\",\n        \"North Europe\",\n        \"West Europe\",\n        \"East Asia\",\n        \"Southeast Asia\",\n        \"Japan East\",\n        \"Japan West\",\n        \"Brazil South\"\n      ],\n      \"apiVersions\": [\n        \"2016-03-30\",\n        \"2015-06-15\",\n        \"2015-05-01-preview\"\n      ],\n      \"capabilities\": \"CrossResourceGroupResourceMove, CrossSubscriptionResourceMove\"\n    },\n    {\n      \"resourceType\": \"virtualMachineScaleSets/virtualMachines\",\n      \"locations\": [\n        \"East US\",\n        \"East US 2\",\n        \"West US\",\n        \"Central US\",\n        \"North Central US\",\n        \"South Central US\",\n        \"North Europe\",\n        \"West Europe\",\n        \"East Asia\",\n        \"Southeast Asia\",\n        \"Japan East\",\n        \"Japan West\",\n        \"Brazil South\"\n      ],\n      \"apiVersions\": [\n        \"2016-03-30\",\n        \"2015-06-15\",\n        \"2015-05-01-preview\"\n      ]\n    },\n    {\n      \"resourceType\": \"virtualMachineScaleSets/networkInterfaces\",\n      \"locations\": [\n        \"East US\",\n        \"East US 2\",\n        \"West US\",\n        \"Central US\",\n        \"North Central US\",\n        \"South Central US\",\n        \"North Europe\",\n        \"West Europe\",\n        \"East Asia\",\n        \"Southeast Asia\",\n        \"Japan East\",\n        \"Japan West\",\n        \"Brazil South\"\n      ],\n      \"apiVersions\": [\n        \"2016-03-30\",\n        \"2015-06-15\",\n        \"2015-05-01-preview\"\n      ]\n    },\n    {\n      \"resourceType\": \"virtualMachineScaleSets/virtualMachines/networkInterfaces\",\n      \"locations\": [\n        \"East US\",\n        \"East US 2\",\n        \"West US\",\n        \"Central US\",\n        \"North Central US\",\n        \"South Central US\",\n        \"North Europe\",\n        \"West Europe\",\n        \"East Asia\",\n        \"Southeast Asia\",\n        \"Japan East\",\n        \"Japan West\",\n        \"Brazil South\"\n      ],\n      \"apiVersions\": [\n        \"2016-03-30\",\n        \"2015-06-15\",\n        \"2015-05-01-preview\"\n      ]\n    },\n    {\n      \"resourceType\": \"locations\",\n      \"locations\": [],\n      \"apiVersions\": [\n        \"2016-03-30\",\n        \"2015-06-15\",\n        \"2015-05-01-preview\"\n      ]\n    },\n    {\n      \"resourceType\": \"locations/operations\",\n      \"locations\": [\n        \"East US\",\n        \"East US 2\",\n        \"West US\",\n        \"Central US\",\n        \"North Central US\",\n        \"South Central US\",\n        \"North Europe\",\n        \"West Europe\",\n        \"East Asia\",\n        \"Southeast Asia\",\n        \"Japan East\",\n        \"Japan West\",\n        \"Brazil South\"\n      ],\n      \"apiVersions\": [\n        \"2016-03-30\",\n        \"2015-06-15\",\n        \"2015-05-01-preview\"\n      ]\n    },\n    {\n      \"resourceType\": \"locations/vmSizes\",\n      \"locations\": [\n        \"East US\",\n        \"East US 2\",\n        \"West US\",\n        \"Central US\",\n        \"North Central US\",\n        \"South Central US\",\n        \"North Europe\",\n        \"West Europe\",\n        \"East Asia\",\n        \"Southeast Asia\",\n        \"Japan East\",\n        \"Japan West\",\n        \"Brazil South\"\n      ],\n      \"apiVersions\": [\n        \"2016-03-30\",\n        \"2015-06-15\",\n        \"2015-05-01-preview\"\n      ]\n    },\n    {\n      \"resourceType\": \"locations/usages\",\n      \"locations\": [\n        \"East US\",\n        \"East US 2\",\n        \"West US\",\n        \"Central US\",\n        \"North Central US\",\n        \"South Central US\",\n        \"North Europe\",\n        \"West Europe\",\n        \"East Asia\",\n        \"Southeast Asia\",\n        \"Japan East\",\n        \"Japan West\",\n        \"Brazil South\"\n      ],\n      \"apiVersions\": [\n        \"2016-03-30\",\n        \"2015-06-15\",\n        \"2015-05-01-preview\"\n      ]\n    },\n    {\n      \"resourceType\": \"locations/publishers\",\n      \"locations\": [\n        \"East US\",\n        \"East US 2\",\n        \"West US\",\n        \"Central US\",\n        \"North Central US\",\n        \"South Central US\",\n        \"North Europe\",\n        \"West Europe\",\n        \"East Asia\",\n        \"Southeast Asia\",\n        \"Japan East\",\n        \"Japan West\",\n        \"Brazil South\"\n      ],\n      \"apiVersions\": [\n        \"2016-03-30\",\n        \"2015-06-15\",\n        \"2015-05-01-preview\"\n      ]\n    },\n    {\n      \"resourceType\": \"operations\",\n      \"locations\": [\n        \"East US\",\n        \"East US 2\",\n        \"West US\",\n        \"Central US\",\n        \"North Central US\",\n        \"South Central US\",\n        \"North Europe\",\n        \"West Europe\",\n        \"East Asia\",\n        \"Southeast Asia\",\n        \"Japan East\",\n        \"Japan West\",\n        \"Brazil South\"\n      ],\n      \"apiVersions\": [\n        \"2016-03-30\",\n        \"2015-06-15\",\n        \"2015-05-01-preview\"\n      ]\n    }\n  ],\n  \"registrationState\": \"Registered\"\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/getvault.json",
    "content": "{\n  \"id\": \"/subscriptions/012e832d-7b27-4c30-9f21-22cdd9159d12/resourceGroups/rg-vaultapilivetest-andrea/providers/Microsoft.KeyVault/vaults/vaultapilivetest-andrea\",\n  \"name\": \"vaultapilivetest-andrea\",\n  \"type\": \"Microsoft.KeyVault/vaults\",\n  \"location\": \"westeurope\",\n  \"tags\": {},\n  \"properties\": {\n    \"sku\": {\n      \"family\": \"A\",\n      \"name\": \"Standard\"\n    },\n    \"tenantId\": \"ba85e8cd-8c83-486e-a7e3-0d7666169d34\",\n    \"accessPolicies\": [\n      {\n        \"tenantId\": \"ba85e8cd-8c83-486e-a7e3-0d7666169d34\",\n        \"objectId\": \"b025a8c0-d7fa-42fd-8e62-d988a3f12791\",\n        \"permissions\": {\n          \"keys\": [\n            \"Get\",\n            \"List\",\n            \"Update\",\n            \"Create\",\n            \"Import\",\n            \"Delete\",\n            \"Recover\",\n            \"Backup\",\n            \"Restore\"\n          ],\n          \"secrets\": [\n            \"Get\",\n            \"List\",\n            \"Set\",\n            \"Delete\",\n            \"Recover\",\n            \"Backup\",\n            \"Restore\"\n          ],\n          \"certificates\": [\n            \"Get\",\n            \"List\",\n            \"Update\",\n            \"Create\",\n            \"Import\",\n            \"Delete\",\n            \"ManageContacts\",\n            \"ManageIssuers\",\n            \"GetIssuers\",\n            \"ListIssuers\",\n            \"SetIssuers\",\n            \"DeleteIssuers\"\n          ]\n        }\n      }\n    ],\n    \"enabledForDeployment\": false,\n    \"enabledForDiskEncryption\": false,\n    \"enabledForTemplateDeployment\": false,\n    \"vaultUri\": \"https://vaultapilivetest-andrea.vault.azure.net/\"\n  }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/image.json",
    "content": "{\n  \"location\": \"West US\",\n  \"tags\": {\n    \"key\": \"value\"\n  },\n  \"properties\": {\n    \"sourceVirtualMachine\": {\n      \"id\": \"/subscriptions/{subscriptionId}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/myVM\"\n    },\n    \"storageProfile\": {\n      \"osDisk\": {\n        \"osType\": \"Windows\",\n        \"blobUri\": \"https://mystorageaccount.blob.core.windows.net/osimages/osimage.vhd\",\n        \"snapshot\": {\n          \"id\": \"subscriptions/{subscriptionId}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/snapshots/mySnapshot1\"\n        },\n        \"managedDisk\": {\n          \"id\": \"subscriptions/{subscriptionId}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/myManagedDisk1\"\n        },\n        \"osState\": \"generalized\",\n        \"hostCaching\": \"ReadWrite\",\n        \"storageAccountType\": \"Standard_LRS\",\n        \"diskSizeGB\": 20\n      },\n      \"dataDisks\": [\n        {\n          \"lun\": \"1\",\n          \"blobUri\": \"https://mystorageaccount.blob.core.windows.net/dataimages/dataimage.vhd\",\n          \"snapshot\": {\n            \"id\": \"subscriptions/{subscriptionId}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/snapshots/mySnapshot2\"\n          },\n          \"managedDisk\": {\n            \"id\": \"subscriptions/{subscriptionId}/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/myManagedDisk2\"\n          },\n          \"hostCaching\": \"ReadWrite\",\n          \"storageAccountType\": \"Standard_LRS\",\n          \"diskSizeInGB\": 20\n        }\n      ]\n    },\n    \"provisioningState\": \"creating\"\n  }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/ipnotavailable.json",
    "content": "{\n  \"available\": false,\n  \"availableIPAddresses\": [\n    \"20.20.0.4\",\n    \"20.20.0.5\",\n    \"20.20.0.6\",\n    \"20.20.0.8\",\n    \"20.20.0.9\"\n  ]\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/isavailablestorageservice.json",
    "content": "{\n  \"nameAvailable\": true\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/listallnetworkinterfaces.json",
    "content": "{\n  \"value\": [\n    {\n      \"name\": \"AnotherNIC\",\n      \"id\": \"/subscriptions/12345678-2749-4e68-9dcf-123456789abc/resourceGroups/azurearmtesting/providers/Microsoft.Network/networkInterfaces/AnotherNIC\",\n      \"etag\": \"W/\\\"e4ed4253-64b6-4184-bfaa-554f470d20c5\\\"\",\n      \"type\": \"Microsoft.Network/networkInterfaces\",\n      \"location\": \"northeurope\",\n      \"properties\": {\n        \"provisioningState\": \"Succeeded\",\n        \"resourceGuid\": \"7fcf6704-21c5-4983-bd9f-017e0873f22f\",\n        \"ipConfigurations\": [\n          {\n            \"name\": \"ipconfig1\",\n            \"id\": \"/subscriptions/12345678-2749-4e68-9dcf-123456789abc/resourceGroups/azurearmtesting/providers/Microsoft.Network/networkInterfaces/AnotherNIC/ipConfigurations/ipconfig1\",\n            \"etag\": \"W/\\\"e4ed4253-64b6-4184-bfaa-554f470d20c5\\\"\",\n            \"properties\": {\n              \"provisioningState\": \"Succeeded\",\n              \"privateIPAddress\": \"10.2.1.4\",\n              \"privateIPAllocationMethod\": \"Dynamic\",\n              \"subnet\": {\n                \"id\": \"/subscriptions/12345678-2749-4e68-9dcf-123456789abc/resourceGroups/armlivetesting/providers/Microsoft.Network/virtualNetworks/jclouds-virtual-network-live-test/subnets/anothersubnet\"\n              },\n              \"primary\": true\n            }\n          }\n        ],\n        \"dnsSettings\": {\n          \"dnsServers\": [],\n          \"appliedDnsServers\": []\n        },\n        \"enableIPForwarding\": false\n      }\n    },\n    {\n      \"name\": \"MyNic\",\n      \"id\": \"/subscriptions/12345678-2749-4e68-9dcf-123456789abc/resourceGroups/azurearmtesting/providers/Microsoft.Network/networkInterfaces/MyNic\",\n      \"etag\": \"W/\\\"a37d25ff-3f62-4ee2-a111-f355beb5ff69\\\"\",\n      \"type\": \"Microsoft.Network/networkInterfaces\",\n      \"location\": \"northeurope\",\n      \"properties\": {\n        \"provisioningState\": \"Succeeded\",\n        \"resourceGuid\": \"35908409-a081-4411-86a9-51f9ea99321f\",\n        \"ipConfigurations\": [\n          {\n            \"name\": \"ipconfig1\",\n            \"id\": \"/subscriptions/12345678-2749-4e68-9dcf-123456789abc/resourceGroups/azurearmtesting/providers/Microsoft.Network/networkInterfaces/MyNic/ipConfigurations/ipconfig1\",\n            \"etag\": \"W/\\\"a37d25ff-3f62-4ee2-a111-f355beb5ff69\\\"\",\n            \"properties\": {\n              \"provisioningState\": \"Succeeded\",\n              \"privateIPAddress\": \"10.2.0.100\",\n              \"privateIPAllocationMethod\": \"Static\",\n              \"subnet\": {\n                \"id\": \"/subscriptions/12345678-2749-4e68-9dcf-123456789abc/resourceGroups/armlivetesting/providers/Microsoft.Network/virtualNetworks/jclouds-virtual-network-live-test/subnets/default\"\n              },\n              \"primary\": true\n            }\n          }\n        ],\n        \"dnsSettings\": {\n          \"dnsServers\": [],\n          \"appliedDnsServers\": []\n        },\n        \"enableIPForwarding\": false\n      }\n    },\n    {\n      \"name\": \"MyNicInAnotherRG\",\n      \"id\": \"/subscriptions/12345678-2749-4e68-9dcf-123456789abc/resourceGroups/otherazurearmtesting/providers/Microsoft.Network/networkInterfaces/MyNic\",\n      \"etag\": \"W/\\\"a37d25ff-3f62-4ee2-a111-f355beb5ff69\\\"\",\n      \"type\": \"Microsoft.Network/networkInterfaces\",\n      \"location\": \"northeurope\",\n      \"properties\": {\n        \"provisioningState\": \"Succeeded\",\n        \"resourceGuid\": \"35908409-a081-4411-86a9-51f9ea99321f\",\n        \"ipConfigurations\": [\n          {\n            \"name\": \"ipconfig1\",\n            \"id\": \"/subscriptions/12345678-2749-4e68-9dcf-123456789abc/resourceGroups/otherazurearmtesting/providers/Microsoft.Network/networkInterfaces/MyNic/ipConfigurations/ipconfig1\",\n            \"etag\": \"W/\\\"a37d25ff-3f62-4ee2-a111-f355beb5ff69\\\"\",\n            \"properties\": {\n              \"provisioningState\": \"Succeeded\",\n              \"privateIPAddress\": \"10.2.0.101\",\n              \"privateIPAllocationMethod\": \"Static\",\n              \"subnet\": {\n                \"id\": \"/subscriptions/12345678-2749-4e68-9dcf-123456789abc/resourceGroups/otherazurearmtesting/providers/Microsoft.Network/virtualNetworks/jclouds-virtual-network-live-test/subnets/default\"\n              },\n              \"primary\": true\n            }\n          }\n        ],\n        \"dnsSettings\": {\n          \"dnsServers\": [],\n          \"appliedDnsServers\": []\n        },\n        \"enableIPForwarding\": false\n      }\n    }\n  ]\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/listdeployments.json",
    "content": "{\n  \"value\": [\n    {\n      \"id\": \"/subscriptions/123abc12-1234-1234-1234-12345345234/resourceGroups/resourceGroup/providers/Microsoft.Resources/deployments/jcdep1458344383064\",\n      \"name\": \"jcdep1458344383064\",\n      \"properties\": {\n        \"parameters\": {},\n        \"mode\": \"Incremental\",\n        \"provisioningState\": \"Running\",\n        \"timestamp\": \"2016-04-26T11:48:11.1807222Z\",\n        \"duration\": \"PT0.950828S\",\n        \"correlationId\": \"f7876e0f-22ec-413c-a79e-0a718b4789a2\",\n        \"providers\": [\n          {\n            \"namespace\": \"Microsoft.Storage\",\n            \"resourceTypes\": [\n              {\n                \"resourceType\": \"storageAccounts\",\n                \"locations\": [\n                  \"northeurope\"\n                ]\n              }\n            ]\n          },\n          {\n            \"namespace\": \"Microsoft.Network\",\n            \"resourceTypes\": [\n              {\n                \"resourceType\": \"virtualNetworks\",\n                \"locations\": [\n                  \"northeurope\"\n                ]\n              },\n              {\n                \"resourceType\": \"publicIPAddresses\",\n                \"locations\": [\n                  \"northeurope\"\n                ]\n              },\n              {\n                \"resourceType\": \"networkInterfaces\",\n                \"locations\": [\n                  \"northeurope\"\n                ]\n              }\n            ]\n          },\n          {\n            \"namespace\": \"Microsoft.Compute\",\n            \"resourceTypes\": [\n              {\n                \"resourceType\": \"virtualMachines\",\n                \"locations\": [\n                  \"northeurope\"\n                ]\n              }\n            ]\n          }\n        ],\n        \"dependencies\": [\n          {\n            \"dependsOn\": [\n              {\n                \"id\": \"/subscriptions/123abc12-1234-1234-1234-12345345234/resourceGroups/resourceGroup/providers/Microsoft.Network/publicIPAddresses/jc1461584629971publicip\",\n                \"resourceType\": \"Microsoft.Network/publicIPAddresses\",\n                \"resourceName\": \"jc1461584629971publicip\"\n              },\n              {\n                \"id\": \"/subscriptions/123abc12-1234-1234-1234-12345345234/resourceGroups/resourceGroup/providers/Microsoft.Network/virtualNetworks/jc1461584629971virtualnetwork\",\n                \"resourceType\": \"Microsoft.Network/virtualNetworks\",\n                \"resourceName\": \"jc1461584629971virtualnetwork\"\n              }\n            ],\n            \"id\": \"/subscriptions/123abc12-1234-1234-1234-12345345234/resourceGroups/resourceGroup/providers/Microsoft.Network/networkInterfaces/jc1461584629971nic\",\n            \"resourceType\": \"Microsoft.Network/networkInterfaces\",\n            \"resourceName\": \"jc1461584629971nic\"\n          },\n          {\n            \"dependsOn\": [\n              {\n                \"id\": \"/subscriptions/123abc12-1234-1234-1234-12345345234/resourceGroups/resourceGroup/providers/Microsoft.Storage/storageAccounts/jc1461584629971storage\",\n                \"resourceType\": \"Microsoft.Storage/storageAccounts\",\n                \"resourceName\": \"jc1461584629971storage\"\n              },\n              {\n                \"id\": \"/subscriptions/123abc12-1234-1234-1234-12345345234/resourceGroups/resourceGroup/providers/Microsoft.Network/networkInterfaces/jc1461584629971nic\",\n                \"resourceType\": \"Microsoft.Network/networkInterfaces\",\n                \"resourceName\": \"jc1461584629971nic\"\n              }\n            ],\n            \"id\": \"/subscriptions/123abc12-1234-1234-1234-12345345234/resourceGroups/resourceGroup/providers/Microsoft.Compute/virtualMachines/jc1461584629971VirtualMachine\",\n            \"resourceType\": \"Microsoft.Compute/virtualMachines\",\n            \"resourceName\": \"jc1461584629971VirtualMachine\"\n          }\n        ]\n      }\n    }\n  ]\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/listdisks.json",
    "content": "{\n  \"value\": [\n    {\n      \"sku\": {\n        \"name\": \"Standard_LRS\",\n        \"tier\": \"Standard\"\n      },\n      \"properties\": {\n        \"creationData\": {\n          \"createOption\": \"Empty\"\n        },\n        \"diskSizeGB\": 2,\n        \"timeCreated\": \"2017-03-01T09:48:27.4526118+00:00\",\n        \"provisioningState\": \"Succeeded\",\n        \"diskState\": \"Unattached\"\n      },\n      \"type\": \"Microsoft.Compute/disks\",\n      \"location\": \"westeurope\",\n      \"id\": \"/subscriptions/610bba05-d7a7-4567-96af-48ecbd09453b/resourceGroups/rg-diskapilivetest-andrea/providers/Microsoft.Compute/disks/jclouds-646\",\n      \"name\": \"jclouds-646\"\n    }\n  ]\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/listnetworkinterfaces.json",
    "content": "{\n  \"value\": [\n    {\n      \"name\": \"AnotherNIC\",\n      \"id\": \"/subscriptions/12345678-2749-4e68-9dcf-123456789abc/resourceGroups/azurearmtesting/providers/Microsoft.Network/networkInterfaces/AnotherNIC\",\n      \"etag\": \"W/\\\"e4ed4253-64b6-4184-bfaa-554f470d20c5\\\"\",\n      \"type\": \"Microsoft.Network/networkInterfaces\",\n      \"location\": \"northeurope\",\n      \"properties\": {\n        \"provisioningState\": \"Succeeded\",\n        \"resourceGuid\": \"7fcf6704-21c5-4983-bd9f-017e0873f22f\",\n        \"ipConfigurations\": [\n          {\n            \"name\": \"ipconfig1\",\n            \"id\": \"/subscriptions/12345678-2749-4e68-9dcf-123456789abc/resourceGroups/azurearmtesting/providers/Microsoft.Network/networkInterfaces/AnotherNIC/ipConfigurations/ipconfig1\",\n            \"etag\": \"W/\\\"e4ed4253-64b6-4184-bfaa-554f470d20c5\\\"\",\n            \"properties\": {\n              \"provisioningState\": \"Succeeded\",\n              \"privateIPAddress\": \"10.2.1.4\",\n              \"privateIPAllocationMethod\": \"Dynamic\",\n              \"subnet\": {\n                \"id\": \"/subscriptions/12345678-2749-4e68-9dcf-123456789abc/resourceGroups/armlivetesting/providers/Microsoft.Network/virtualNetworks/jclouds-virtual-network-live-test/subnets/anothersubnet\"\n              },\n              \"primary\": true\n            }\n          }\n        ],\n        \"dnsSettings\": {\n          \"dnsServers\": [],\n          \"appliedDnsServers\": []\n        },\n        \"enableIPForwarding\": false\n      }\n    },\n    {\n      \"name\": \"MyNic\",\n      \"id\": \"/subscriptions/12345678-2749-4e68-9dcf-123456789abc/resourceGroups/azurearmtesting/providers/Microsoft.Network/networkInterfaces/MyNic\",\n      \"etag\": \"W/\\\"a37d25ff-3f62-4ee2-a111-f355beb5ff69\\\"\",\n      \"type\": \"Microsoft.Network/networkInterfaces\",\n      \"location\": \"northeurope\",\n      \"properties\": {\n        \"provisioningState\": \"Succeeded\",\n        \"resourceGuid\": \"35908409-a081-4411-86a9-51f9ea99321f\",\n        \"ipConfigurations\": [\n          {\n            \"name\": \"ipconfig1\",\n            \"id\": \"/subscriptions/12345678-2749-4e68-9dcf-123456789abc/resourceGroups/azurearmtesting/providers/Microsoft.Network/networkInterfaces/MyNic/ipConfigurations/ipconfig1\",\n            \"etag\": \"W/\\\"a37d25ff-3f62-4ee2-a111-f355beb5ff69\\\"\",\n            \"properties\": {\n              \"provisioningState\": \"Succeeded\",\n              \"privateIPAddress\": \"10.2.0.100\",\n              \"privateIPAllocationMethod\": \"Static\",\n              \"subnet\": {\n                \"id\": \"/subscriptions/12345678-2749-4e68-9dcf-123456789abc/resourceGroups/armlivetesting/providers/Microsoft.Network/virtualNetworks/jclouds-virtual-network-live-test/subnets/default\"\n              },\n              \"primary\": true\n            }\n          }\n        ],\n        \"dnsSettings\": {\n          \"dnsServers\": [],\n          \"appliedDnsServers\": []\n        },\n        \"enableIPForwarding\": false\n      }\n    }\n  ]\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/listsubnetswithinvirtualnetwork.json",
    "content": "{\n  \"value\": [\n    {\n      \"name\": \"mysubnet\",\n      \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/azurearmtesting/providers/Microsoft.Network/virtualNetworks/myvirtualnetwork/subnets/mysubnet\",\n      \"etag\": \"W/\\\"bc7e1d77-eec0-4b91-ae80-afc33cf3c867\\\"\",\n      \"properties\": {\n        \"provisioningState\": \"Succeeded\",\n        \"addressPrefix\": \"10.2.0.0/24\",\n        \"ipConfigurations\": [\n          {\n            \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/azurearmtesting/providers/Microsoft.Network/networkInterfaces/myNic/ipConfigurations/myip1\"\n          }\n        ]\n      }\n    }\n  ]\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/listvirtualnetworks.json",
    "content": "{\n  \"value\": [\n    {\n      \"name\": \"mockvirtualnetwork\",\n      \"id\": \"/subscriptions/6b6748c8-3e69-4e27-9b71-df97a81c0bbc/resourceGroups/azurearmtesting/providers/Microsoft.Network/virtualNetworks/mockvirtualnetwork\",\n      \"etag\": \"W/\\\"0dcd223f-670c-49ca-abe7-5978d127c131\\\"\",\n      \"type\": \"Microsoft.Network/virtualNetworks\",\n      \"location\": \"westeurope\",\n      \"tags\": {\n        \"key\": \"value\"\n      },\n      \"properties\": {\n        \"provisioningState\": \"Succeeded\",\n        \"resourceGuid\": \"1568c76a-73a4-4a60-8dfb-53b823197ccb\",\n        \"addressSpace\": {\n          \"addressPrefixes\": [\n            \"10.2.0.0/16\"\n          ]\n        },\n        \"subnets\": []\n      }\n    },\n    {\n      \"name\": \"anothervirtualnetworks\",\n      \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/azurearmtesting/providers/Microsoft.Network/virtualNetworks/anothervirtualnetworks\",\n      \"etag\": \"W/\\\"7604d8fe-f3b8-4fd4-ae52-ab503cc29097\\\"\",\n      \"type\": \"Microsoft.Network/virtualNetworks\",\n      \"location\": \"westeurope\",\n      \"tags\": {\n        \"key\": \"value\"\n      },\n      \"properties\": {\n        \"provisioningState\": \"Succeeded\",\n        \"resourceGuid\": \"5192bdb3-f6ed-44ad-bf4c-059cff905791\",\n        \"addressSpace\": {\n          \"addressPrefixes\": [\n            \"10.2.0.0/16\"\n          ]\n        },\n        \"subnets\": []\n      }\n    },\n    {\n      \"name\": \"myvirtualnetwork\",\n      \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/azurearmtesting/providers/Microsoft.Network/virtualNetworks/myvirtualnetwork\",\n      \"etag\": \"W/\\\"bc7e1d77-eec0-4b91-ae80-afc33cf3c867\\\"\",\n      \"type\": \"Microsoft.Network/virtualNetworks\",\n      \"location\": \"westeurope\",\n      \"tags\": {\n        \"key\": \"value\"\n      },\n      \"properties\": {\n        \"provisioningState\": \"Succeeded\",\n        \"resourceGuid\": \"8da85637-833c-4445-a681-81ca3fb90044\",\n        \"addressSpace\": {\n          \"addressPrefixes\": [\n            \"10.2.0.0/16\"\n          ]\n        },\n        \"subnets\": [\n          {\n            \"name\": \"mysubnet\",\n            \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/azurearmtesting/providers/Microsoft.Network/virtualNetworks/myvirtualnetwork/subnets/mysubnet\",\n            \"etag\": \"W/\\\"bc7e1d77-eec0-4b91-ae80-afc33cf3c867\\\"\",\n            \"properties\": {\n              \"provisioningState\": \"Succeeded\",\n              \"addressPrefix\": \"10.2.0.0/24\",\n              \"ipConfigurations\": [\n                {\n                  \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/azurearmtesting/providers/Microsoft.Network/networkInterfaces/myNic/ipConfigurations/myip1\"\n                }\n              ]\n            }\n          }\n        ]\n      }\n    }\n  ]\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/listvirtualnetworksall.json",
    "content": "{\n  \"value\": [\n    {\n      \"name\": \"mockvirtualnetwork\",\n      \"id\": \"/subscriptions/6b6748c8-3e69-4e27-9b71-df97a81c0bbc/resourceGroups/azurearmtesting/providers/Microsoft.Network/virtualNetworks/mockvirtualnetwork\",\n      \"etag\": \"W/\\\"0dcd223f-670c-49ca-abe7-5978d127c131\\\"\",\n      \"type\": \"Microsoft.Network/virtualNetworks\",\n      \"location\": \"westeurope\",\n      \"tags\": {\n        \"key\": \"value\"\n      },\n      \"properties\": {\n        \"provisioningState\": \"Succeeded\",\n        \"resourceGuid\": \"1568c76a-73a4-4a60-8dfb-53b823197ccb\",\n        \"addressSpace\": {\n          \"addressPrefixes\": [\n            \"10.2.0.0/16\"\n          ]\n        },\n        \"subnets\": []\n      }\n    },\n    {\n      \"name\": \"anothervirtualnetworks\",\n      \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/azurearmtesting/providers/Microsoft.Network/virtualNetworks/anothervirtualnetworks\",\n      \"etag\": \"W/\\\"7604d8fe-f3b8-4fd4-ae52-ab503cc29097\\\"\",\n      \"type\": \"Microsoft.Network/virtualNetworks\",\n      \"location\": \"westeurope\",\n      \"tags\": {\n        \"key\": \"value\"\n      },\n      \"properties\": {\n        \"provisioningState\": \"Succeeded\",\n        \"resourceGuid\": \"5192bdb3-f6ed-44ad-bf4c-059cff905791\",\n        \"addressSpace\": {\n          \"addressPrefixes\": [\n            \"10.2.0.0/16\"\n          ]\n        },\n        \"subnets\": []\n      }\n    },\n    {\n      \"name\": \"myvirtualnetwork\",\n      \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/azurearmtesting/providers/Microsoft.Network/virtualNetworks/myvirtualnetwork\",\n      \"etag\": \"W/\\\"bc7e1d77-eec0-4b91-ae80-afc33cf3c867\\\"\",\n      \"type\": \"Microsoft.Network/virtualNetworks\",\n      \"location\": \"westeurope\",\n      \"tags\": {\n        \"key\": \"value\"\n      },\n      \"properties\": {\n        \"provisioningState\": \"Succeeded\",\n        \"resourceGuid\": \"8da85637-833c-4445-a681-81ca3fb90044\",\n        \"addressSpace\": {\n          \"addressPrefixes\": [\n            \"10.2.0.0/16\"\n          ]\n        },\n        \"subnets\": [\n          {\n            \"name\": \"mysubnet\",\n            \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/azurearmtesting/providers/Microsoft.Network/virtualNetworks/myvirtualnetwork/subnets/mysubnet\",\n            \"etag\": \"W/\\\"bc7e1d77-eec0-4b91-ae80-afc33cf3c867\\\"\",\n            \"properties\": {\n              \"provisioningState\": \"Succeeded\",\n              \"addressPrefix\": \"10.2.0.0/24\",\n              \"ipConfigurations\": [\n                {\n                  \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/azurearmtesting/providers/Microsoft.Network/networkInterfaces/myNic/ipConfigurations/myip1\"\n                }\n              ]\n            }\n          }\n        ]\n      }\n    },\n    {\n      \"name\": \"mockvirtualnetworkextra\",\n      \"id\": \"/subscriptions/6b6748c8-3e69-4e27-9b71-df97a81c0bbc/resourceGroups/other-rg/providers/Microsoft.Network/virtualNetworks/mockvirtualnetwork\",\n      \"etag\": \"W/\\\"0dcd223f-670c-49ca-abe7-5978d127c131\\\"\",\n      \"type\": \"Microsoft.Network/virtualNetworks\",\n      \"location\": \"westeurope\",\n      \"tags\": {\n        \"key\": \"value\"\n      },\n      \"properties\": {\n        \"provisioningState\": \"Succeeded\",\n        \"resourceGuid\": \"1568c76a-73a4-4a60-8dfb-53b823197ccb\",\n        \"addressSpace\": {\n          \"addressPrefixes\": [\n            \"10.2.0.0/16\"\n          ]\n        },\n        \"subnets\": []\n      }\n    }\n  ]\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/loadbalancercreate.json",
    "content": "{\n  \"name\": \"testLoadBalancer\",\n  \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/rg-loadbalancerapilivetest-nacx/providers/Microsoft.Network/loadBalancers/testLoadBalancer\",\n  \"etag\": \"W/\\\"406af4e7-b24b-4c00-b42f-b3c4399bf61d\\\"\",\n  \"type\": \"Microsoft.Network/loadBalancers\",\n  \"location\": \"westeurope\",\n  \"sku\": {\n    \"name\": \"Basic\"\n  },\n  \"properties\": {\n    \"provisioningState\": \"Succeeded\",\n    \"resourceGuid\": \"112b7e75-f287-4789-9f6a-9a55a6fbe47c\",\n    \"frontendIPConfigurations\": [\n      {\n        \"name\": \"ipConfigs\",\n        \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/rg-loadbalancerapilivetest-nacx/providers/Microsoft.Network/loadBalancers/testLoadBalancer/frontendIPConfigurations/ipConfigs\",\n        \"etag\": \"W/\\\"406af4e7-b24b-4c00-b42f-b3c4399bf61d\\\"\",\n        \"properties\": {\n          \"provisioningState\": \"Succeeded\",\n          \"privateIPAllocationMethod\": \"Dynamic\"\n        }\n      }\n    ],\n    \"backendAddressPools\": [],\n    \"loadBalancingRules\": [],\n    \"probes\": [],\n    \"inboundNatRules\": [],\n    \"outboundNatRules\": [],\n    \"inboundNatPools\": []\n  }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/loadbalancerget.json",
    "content": "{\n  \"name\": \"testLoadBalancer\",\n  \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/rg-loadbalancerapilivetest-nacx/providers/Microsoft.Network/loadBalancers/testLoadBalancer\",\n  \"etag\": \"W/\\\"b2cfb60e-4ada-4546-a336-dd71e574ead6\\\"\",\n  \"type\": \"Microsoft.Network/loadBalancers\",\n  \"location\": \"westeurope\",\n  \"sku\": {\n    \"name\": \"Basic\"\n  },\n  \"properties\": {\n    \"provisioningState\": \"Succeeded\",\n    \"resourceGuid\": \"0d53b121-95cc-47b5-bbc6-0391f5991028\",\n    \"frontendIPConfigurations\": [\n      {\n        \"name\": \"ipConfigs\",\n        \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/rg-loadbalancerapilivetest-nacx/providers/Microsoft.Network/loadBalancers/testLoadBalancer/frontendIPConfigurations/ipConfigs\",\n        \"etag\": \"W/\\\"b2cfb60e-4ada-4546-a336-dd71e574ead6\\\"\",\n        \"properties\": {\n          \"provisioningState\": \"Succeeded\",\n          \"privateIPAllocationMethod\": \"Dynamic\",\n          \"publicIPAddress\": {\n            \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/rg-loadbalancerapilivetest-nacx/providers/Microsoft.Network/publicIPAddresses/Ip4LoadBalancer\"\n          },\n          \"loadBalancingRules\": [\n            {\n              \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/rg-loadbalancerapilivetest-nacx/providers/Microsoft.Network/loadBalancers/testLoadBalancer/loadBalancingRules/lbRule1\"\n            }\n          ]\n        }\n      }\n    ],\n    \"backendAddressPools\": [],\n    \"loadBalancingRules\": [\n      {\n        \"name\": \"lbRule1\",\n        \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/rg-loadbalancerapilivetest-nacx/providers/Microsoft.Network/loadBalancers/testLoadBalancer/loadBalancingRules/lbRule1\",\n        \"etag\": \"W/\\\"b2cfb60e-4ada-4546-a336-dd71e574ead6\\\"\",\n        \"properties\": {\n          \"provisioningState\": \"Succeeded\",\n          \"frontendIPConfiguration\": {\n            \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/rg-loadbalancerapilivetest-nacx/providers/Microsoft.Network/loadBalancers/testLoadBalancer/frontendIPConfigurations/ipConfigs\"\n          },\n          \"frontendPort\": 80,\n          \"backendPort\": 80,\n          \"enableFloatingIP\": false,\n          \"idleTimeoutInMinutes\": 4,\n          \"protocol\": \"Tcp\",\n          \"loadDistribution\": \"Default\"\n        }\n      }\n    ],\n    \"probes\": [],\n    \"inboundNatRules\": [],\n    \"outboundNatRules\": [],\n    \"inboundNatPools\": []\n  }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/loadbalancerlist.json",
    "content": "{\n  \"value\": [\n    {\n      \"name\": \"testLoadBalancer\",\n      \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/rg-loadbalancerapilivetest-nacx/providers/Microsoft.Network/loadBalancers/testLoadBalancer\",\n      \"etag\": \"W/\\\"1107154b-8717-486b-80c1-af99ec62897b\\\"\",\n      \"type\": \"Microsoft.Network/loadBalancers\",\n      \"location\": \"westeurope\",\n      \"properties\": {\n        \"provisioningState\": \"Succeeded\",\n        \"resourceGuid\": \"383708b3-8d4e-474c-8908-9c4e311ac0bf\",\n        \"frontendIPConfigurations\": [\n          {\n            \"name\": \"ipConfigs\",\n            \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/rg-loadbalancerapilivetest-nacx/providers/Microsoft.Network/loadBalancers/testLoadBalancer/frontendIPConfigurations/ipConfigs\",\n            \"etag\": \"W/\\\"1107154b-8717-486b-80c1-af99ec62897b\\\"\",\n            \"properties\": {\n              \"provisioningState\": \"Succeeded\",\n              \"privateIPAllocationMethod\": \"Dynamic\",\n              \"publicIPAddress\": {\n                \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/rg-loadbalancerapilivetest-nacx/providers/Microsoft.Network/publicIPAddresses/Ip4LoadBalancer\"\n              }\n            }\n          }\n        ],\n        \"backendAddressPools\": [],\n        \"loadBalancingRules\": [],\n        \"probes\": [],\n        \"inboundNatRules\": [],\n        \"outboundNatRules\": [],\n        \"inboundNatPools\": []\n      }\n    }\n  ]\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/loadbalancerlistall.json",
    "content": "{\n  \"value\": [\n    {\n      \"name\": \"testLoadBalancer\",\n      \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/rg-loadbalancerapilivetest-nacx/providers/Microsoft.Network/loadBalancers/testLoadBalancer\",\n      \"etag\": \"W/\\\"1107154b-8717-486b-80c1-af99ec62897b\\\"\",\n      \"type\": \"Microsoft.Network/loadBalancers\",\n      \"location\": \"westeurope\",\n      \"properties\": {\n        \"provisioningState\": \"Succeeded\",\n        \"resourceGuid\": \"383708b3-8d4e-474c-8908-9c4e311ac0bf\",\n        \"frontendIPConfigurations\": [\n          {\n            \"name\": \"ipConfigs\",\n            \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/rg-loadbalancerapilivetest-nacx/providers/Microsoft.Network/loadBalancers/testLoadBalancer/frontendIPConfigurations/ipConfigs\",\n            \"etag\": \"W/\\\"1107154b-8717-486b-80c1-af99ec62897b\\\"\",\n            \"properties\": {\n              \"provisioningState\": \"Succeeded\",\n              \"privateIPAllocationMethod\": \"Dynamic\",\n              \"publicIPAddress\": {\n                \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/rg-loadbalancerapilivetest-nacx/providers/Microsoft.Network/publicIPAddresses/Ip4LoadBalancer\"\n              }\n            }\n          }\n        ],\n        \"backendAddressPools\": [],\n        \"loadBalancingRules\": [],\n        \"probes\": [],\n        \"inboundNatRules\": [],\n        \"outboundNatRules\": [],\n        \"inboundNatPools\": []\n      }\n    },\n    {\n      \"name\": \"testLoadBalancer\",\n      \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/other-rg/providers/Microsoft.Network/loadBalancers/testLoadBalancer\",\n      \"etag\": \"W/\\\"1107154b-8717-486b-80c1-af99ec62897b\\\"\",\n      \"type\": \"Microsoft.Network/loadBalancers\",\n      \"location\": \"westeurope\",\n      \"properties\": {\n        \"provisioningState\": \"Succeeded\",\n        \"resourceGuid\": \"383708b3-8d4e-474c-8908-9c4e311ac0bf\",\n        \"frontendIPConfigurations\": [\n          {\n            \"name\": \"ipConfigs\",\n            \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/other-rg/providers/Microsoft.Network/loadBalancers/testLoadBalancer/frontendIPConfigurations/ipConfigs\",\n            \"etag\": \"W/\\\"1107154b-8717-486b-80c1-af99ec62897b\\\"\",\n            \"properties\": {\n              \"provisioningState\": \"Succeeded\",\n              \"privateIPAllocationMethod\": \"Dynamic\",\n              \"publicIPAddress\": {\n                \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/other-rg/providers/Microsoft.Network/publicIPAddresses/Ip4LoadBalancer\"\n              }\n            }\n          }\n        ],\n        \"backendAddressPools\": [],\n        \"loadBalancingRules\": [],\n        \"probes\": [],\n        \"inboundNatRules\": [],\n        \"outboundNatRules\": [],\n        \"inboundNatPools\": []\n      }\n    }\n  ]\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/localnetworkgatewaycreate.json",
    "content": "{\n  \"name\": \"mylocalgw\",\n  \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myresourcegroup/providers/Microsoft.Network/localNetworkGateways/mylocalgw\",\n  \"etag\": \"W/\\\"e76a6517-260a-4424-811b-b4d518109424\\\"\",\n  \"type\": \"Microsoft.Network/localNetworkGateways\",\n  \"location\": \"westeurope\",\n  \"properties\": {\n    \"provisioningState\": \"Updating\",\n    \"resourceGuid\": \"cd00ef09-fec6-4d6e-aa15-77cf06d14915\",\n    \"localNetworkAddressSpace\": {\n      \"addressPrefixes\": [\n        \"192.168.0.0/24\"\n      ]\n    },\n    \"gatewayIpAddress\": \"1.2.3.4\"\n  }\n}\n\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/localnetworkgatewayget.json",
    "content": "{\n  \"name\": \"mylocalgw\",\n  \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myresourcegroup/providers/Microsoft.Network/localNetworkGateways/mylocalgw\",\n  \"etag\": \"W/\\\"e76a6517-260a-4424-811b-b4d518109424\\\"\",\n  \"type\": \"Microsoft.Network/localNetworkGateways\",\n  \"location\": \"westeurope\",\n  \"properties\": {\n    \"provisioningState\": \"Updating\",\n    \"resourceGuid\": \"cd00ef09-fec6-4d6e-aa15-77cf06d14915\",\n    \"localNetworkAddressSpace\": {\n      \"addressPrefixes\": [\n        \"192.168.0.0/24\"\n      ]\n    },\n    \"gatewayIpAddress\": \"1.2.3.4\"\n  }\n}\n\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/localnetworkgatewaylist.json",
    "content": "{\n  \"value\": [\n    {\n      \"name\": \"mylocalgw\",\n      \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myresourcegroup/providers/Microsoft.Network/localNetworkGateways/mylocalgw\",\n      \"etag\": \"W/\\\"e76a6517-260a-4424-811b-b4d518109424\\\"\",\n      \"type\": \"Microsoft.Network/localNetworkGateways\",\n      \"location\": \"westeurope\",\n      \"properties\": {\n        \"provisioningState\": \"Updating\",\n        \"resourceGuid\": \"cd00ef09-fec6-4d6e-aa15-77cf06d14915\",\n        \"localNetworkAddressSpace\": {\n          \"addressPrefixes\": [\n            \"192.168.0.0/24\"\n          ]\n        },\n        \"gatewayIpAddress\": \"1.2.3.4\"\n      }\n    }\n  ]\n}\n\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/locations.json",
    "content": "{\"value\": [\n  {\n    \"id\":\"/subscriptions/SUBSCRIPTIONID/locations/eastasia\",\n    \"name\":\"eastasia\",\n    \"displayName\":\"East Asia\",\n    \"longitude\":\"114.188\",\n    \"latitude\":\"22.267\"\n  }\n  ]\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/logback-test.xml",
    "content": "<?xml version=\"1.0\"?>\n<configuration scan=\"false\">\n    <appender name=\"FILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds.log</file>\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n    <appender name=\"WIREFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds-wire.log</file>\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n    <appender name=\"COMPUTEFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds-compute.log</file>\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <logger name=\"org.jclouds\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"FILE\" />\n    </logger>\n    <logger name=\"jclouds.compute\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"COMPUTEFILE\" />\n    </logger>\n    <logger name=\"jclouds.wire\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n    <logger name=\"jclouds.headers\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n\n    <root>\n        <level value=\"INFO\" />\n    </root>\n</configuration>\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/metricalertcreateorupdate.json",
    "content": "{\n  \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Insights/metricalerts/MetricAlertTest\",\n  \"name\": \"MetricAlertTest\",\n  \"type\": \"Microsoft.Insights/metricAlerts\",\n  \"location\": \"global\",\n  \"tags\": {\n    \"createdBy\": \"jclouds\"\n  },\n  \"properties\": {\n    \"description\": \"\",\n    \"severity\": 3,\n    \"enabled\": false,\n    \"scopes\": [\n      \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/LinuxVM\"\n    ],\n    \"evaluationFrequency\": \"PT5M\",\n    \"windowSize\": \"PT5M\",\n    \"criteria\": {\n      \"allOf\": [\n        {\n          \"threshold\": 0,\n          \"name\": \"Metric1\",\n          \"metricNamespace\": \"Microsoft.Compute/virtualMachines\",\n          \"metricName\": \"CPU Credits Consumed\",\n          \"operator\": \"GreaterThan\",\n          \"timeAggregation\": \"Average\",\n          \"criterionType\": \"StaticThresholdCriterion\"\n        }\n      ],\n      \"odata.type\": \"Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria\"\n    },\n    \"autoMitigate\": true,\n    \"targetResourceRegion\": \"eastus\",\n    \"targetResourceType\":\"Microsoft.Compute/virtualMachines\",\n    \"actions\": [\n      {\n        \"actionGroupId\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/microsoft.insights/actiongroups/actionemail\",\n        \"webHookProperties\": {}\n      }\n    ]\n  }\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/metricalertget.json",
    "content": "{\n  \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Insights/metricalerts/MetricAlertTest\",\n  \"name\": \"MetricAlertTest\",\n  \"type\": \"Microsoft.Insights/metricAlerts\",\n  \"location\": \"global\",\n  \"tags\": {\n    \"createdBy\": \"jclouds\"\n  },\n  \"properties\": {\n    \"description\": \"\",\n    \"severity\": 3,\n    \"enabled\": false,\n    \"scopes\": [\n      \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/LinuxVM\"\n    ],\n    \"evaluationFrequency\": \"PT5M\",\n    \"windowSize\": \"PT5M\",\n    \"criteria\": {\n      \"allOf\": [\n        {\n          \"threshold\": 0,\n          \"name\": \"Metric1\",\n          \"metricNamespace\": \"Microsoft.Compute/virtualMachines\",\n          \"metricName\": \"CPU Credits Consumed\",\n          \"operator\": \"GreaterThan\",\n          \"timeAggregation\": \"Average\",\n          \"criterionType\": \"StaticThresholdCriterion\"\n        }\n      ],\n      \"odata.type\": \"Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria\"\n    },\n    \"autoMitigate\": true,\n    \"targetResourceRegion\": \"eastus\",\n    \"targetResourceType\":\"Microsoft.Compute/virtualMachines\",\n    \"actions\": [\n      {\n        \"actionGroupId\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/microsoft.insights/actiongroups/actionemail\",\n        \"webHookProperties\": {}\n      }\n    ]\n  }\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/metricalertgetbyresource.json",
    "content": "{\n  \"value\": [\n    {\n      \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/microsoft.insights/metricalerts/MetricAlert1\",\n      \"name\": \"MetricAlert1\",\n      \"type\": \"Microsoft.Insights/metricAlerts\",\n      \"location\": \"global\",\n      \"tags\": {},\n      \"properties\": {\n        \"description\": \"MetricAlert1\",\n        \"severity\": 0,\n        \"enabled\": true,\n        \"scopes\": [\n          \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/LinuxVM\",\n          \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/CentOSVM\"\n        ],\n        \"evaluationFrequency\": \"PT1M\",\n        \"windowSize\": \"PT1M\",\n        \"criteria\": {\n          \"allOf\": [\n            {\n              \"threshold\": 0,\n              \"name\": \"criteria1\",\n              \"metricNamespace\": \"Microsoft.Compute/virtualMachines\",\n              \"metricName\": \"Available Memory Bytes\",\n              \"operator\": \"GreaterThan\",\n              \"timeAggregation\": \"Total\",\n              \"criterionType\": \"StaticThresholdCriterion\"\n            }\n          ],\n          \"odata.type\": \"Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria\"\n        },\n        \"autoMitigate\": true,\n        \"targetResourceType\": \"Microsoft.Compute/virtualMachines\",\n        \"targetResourceRegion\": \"eastus\",\n        \"actions\": []\n      }\n    },\n    {\n      \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/microsoft.insights/metricalerts/MetricAlert2\",\n      \"name\": \"MetricAlert2\",\n      \"type\": \"Microsoft.Insights/metricAlerts\",\n      \"location\": \"global\",\n      \"tags\": {},\n      \"properties\": {\n        \"description\": \"\",\n        \"severity\": 3,\n        \"enabled\": false,\n        \"scopes\": [\n          \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/virtualMachines/LinuxVM\"\n        ],\n        \"evaluationFrequency\": \"PT1M\",\n        \"windowSize\": \"PT5M\",\n        \"criteria\": {\n          \"allOf\": [\n            {\n              \"threshold\": 0,\n              \"name\": \"criteria1\",\n              \"metricNamespace\": \"Microsoft.Compute/virtualMachines\",\n              \"metricName\": \"Percentage CPU\",\n              \"operator\": \"GreaterThan\",\n              \"timeAggregation\": \"Average\",\n              \"criterionType\": \"StaticThresholdCriterion\"\n            }\n          ],\n          \"odata.type\": \"Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria\"\n        },\n        \"autoMitigate\": true,\n        \"targetResourceType\": \"Microsoft.Compute/virtualMachines\",\n        \"targetResourceRegion\": \"eastus\",\n  \t\t\"actions\": [\n          {\n            \"actionGroupId\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/microsoft.insights/actionGroups/metricaction\",\n            \"webHookProperties\": {}\n          }\n        ]\n      }\n    }      \n  ]\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/metricdefinitions.json",
    "content": "{\n  \"value\": [\n    {\n      \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myresourcegroup/providers/Microsoft.Compute/virtualMachines/myvm/providers/microsoft.insights/metricdefinitions/Percentage CPU\",\n      \"resourceId\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myresourcegroup/providers/Microsoft.Compute/virtualMachines/myvm\",\n      \"name\": {\n        \"value\": \"Percentage CPU\",\n        \"localizedValue\": \"Percentage CPU\"\n      },\n      \"isDimensionRequired\": false,\n      \"unit\": \"Percent\",\n      \"primaryAggregationType\": \"Average\",\n      \"metricAvailabilities\": [\n        {\n          \"timeGrain\": \"PT1M\",\n          \"retention\": \"P30D\"\n        },\n        {\n          \"timeGrain\": \"PT1H\",\n          \"retention\": \"P30D\"\n        }\n      ]\n    }\n  ]\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/metrics.json",
    "content": "{\n  \"value\": [\n    {\n      \"data\": [\n        {\n          \"timeStamp\": \"2017-06-01T11:14:00Z\",\n          \"average\": 0.295\n        }\n      ],\n      \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myresourcegroup/providers/Microsoft.Compute/virtualMachines/myvm/providers/Microsoft.Insights/metrics/Percentage CPU\",\n      \"name\": {\n        \"value\": \"Percentage CPU\",\n        \"localizedValue\": \"Percentage CPU\"\n      },\n      \"type\": \"Microsoft.Insights/metrics\",\n      \"unit\": \"Percent\"\n    }\n  ]\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/networksecuritygroupcreate.json",
    "content": "{\n  \"name\": \"testNetworkSecurityGroup\",\n  \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/jims947groupjclouds/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup\",\n  \"etag\": \"W/\\\"1883271c-c55b-4f5b-a95a-b7415833e0ae\\\"\",\n  \"type\": \"Microsoft.Network/networkSecurityGroups\",\n  \"location\": \"westus\",\n  \"properties\": {\n    \"provisioningState\": \"Updating\",\n    \"resourceGuid\": \"028cb30d-f97f-4dbe-9fea-705da1f383ca\",\n    \"securityRules\": [{\n      \"name\": \"denyallout\",\n      \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/jims947groupjclouds/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/securityRules/denyallout\",\n      \"etag\": \"W/\\\"1883271c-c55b-4f5b-a95a-b7415833e0ae\\\"\",\n      \"properties\": {\n        \"provisioningState\": \"Updating\",\n        \"description\": \"deny all out\",\n        \"protocol\": \"Tcp\",\n        \"sourcePortRange\": \"*\",\n        \"destinationPortRange\": \"*\",\n        \"sourceAddressPrefix\": \"*\",\n        \"destinationAddressPrefix\": \"*\",\n        \"access\": \"Deny\",\n        \"priority\": 4095,\n        \"direction\": \"Outbound\"\n      }\n    }],\n    \"defaultSecurityRules\": [{\n      \"name\": \"AllowVnetInBound\",\n      \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/jims947groupjclouds/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/defaultSecurityRules/AllowVnetInBound\",\n      \"etag\": \"W/\\\"1883271c-c55b-4f5b-a95a-b7415833e0ae\\\"\",\n      \"properties\": {\n        \"provisioningState\": \"Updating\",\n        \"description\": \"Allow inbound traffic from all VMs in VNET\",\n        \"protocol\": \"*\",\n        \"sourcePortRange\": \"*\",\n        \"destinationPortRange\": \"*\",\n        \"sourceAddressPrefix\": \"VirtualNetwork\",\n        \"destinationAddressPrefix\": \"VirtualNetwork\",\n        \"access\": \"Allow\",\n        \"priority\": 65000,\n        \"direction\": \"Inbound\"\n      }\n    }, {\n      \"name\": \"AllowAzureLoadBalancerInBound\",\n      \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/jims947groupjclouds/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/defaultSecurityRules/AllowAzureLoadBalancerInBound\",\n      \"etag\": \"W/\\\"1883271c-c55b-4f5b-a95a-b7415833e0ae\\\"\",\n      \"properties\": {\n        \"provisioningState\": \"Updating\",\n        \"description\": \"Allow inbound traffic from azure load balancer\",\n        \"protocol\": \"*\",\n        \"sourcePortRange\": \"*\",\n        \"destinationPortRange\": \"*\",\n        \"sourceAddressPrefix\": \"AzureLoadBalancer\",\n        \"destinationAddressPrefix\": \"*\",\n        \"access\": \"Allow\",\n        \"priority\": 65001,\n        \"direction\": \"Inbound\"\n      }\n    }, {\n      \"name\": \"DenyAllInBound\",\n      \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/jims947groupjclouds/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/defaultSecurityRules/DenyAllInBound\",\n      \"etag\": \"W/\\\"1883271c-c55b-4f5b-a95a-b7415833e0ae\\\"\",\n      \"properties\": {\n        \"provisioningState\": \"Updating\",\n        \"description\": \"Deny all inbound traffic\",\n        \"protocol\": \"*\",\n        \"sourcePortRange\": \"*\",\n        \"destinationPortRange\": \"*\",\n        \"sourceAddressPrefix\": \"*\",\n        \"destinationAddressPrefix\": \"*\",\n        \"access\": \"Deny\",\n        \"priority\": 65500,\n        \"direction\": \"Inbound\"\n      }\n    }, {\n      \"name\": \"AllowVnetOutBound\",\n      \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/jims947groupjclouds/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/defaultSecurityRules/AllowVnetOutBound\",\n      \"etag\": \"W/\\\"1883271c-c55b-4f5b-a95a-b7415833e0ae\\\"\",\n      \"properties\": {\n        \"provisioningState\": \"Updating\",\n        \"description\": \"Allow outbound traffic from all VMs to all VMs in VNET\",\n        \"protocol\": \"*\",\n        \"sourcePortRange\": \"*\",\n        \"destinationPortRange\": \"*\",\n        \"sourceAddressPrefix\": \"VirtualNetwork\",\n        \"destinationAddressPrefix\": \"VirtualNetwork\",\n        \"access\": \"Allow\",\n        \"priority\": 65000,\n        \"direction\": \"Outbound\"\n      }\n    }, {\n      \"name\": \"AllowInternetOutBound\",\n      \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/jims947groupjclouds/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/defaultSecurityRules/AllowInternetOutBound\",\n      \"etag\": \"W/\\\"1883271c-c55b-4f5b-a95a-b7415833e0ae\\\"\",\n      \"properties\": {\n        \"provisioningState\": \"Updating\",\n        \"description\": \"Allow outbound traffic from all VMs to Internet\",\n        \"protocol\": \"*\",\n        \"sourcePortRange\": \"*\",\n        \"destinationPortRange\": \"*\",\n        \"sourceAddressPrefix\": \"*\",\n        \"destinationAddressPrefix\": \"Internet\",\n        \"access\": \"Allow\",\n        \"priority\": 65001,\n        \"direction\": \"Outbound\"\n      }\n    }, {\n      \"name\": \"DenyAllOutBound\",\n      \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/jims947groupjclouds/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/defaultSecurityRules/DenyAllOutBound\",\n      \"etag\": \"W/\\\"1883271c-c55b-4f5b-a95a-b7415833e0ae\\\"\",\n      \"properties\": {\n        \"provisioningState\": \"Updating\",\n        \"description\": \"Deny all outbound traffic\",\n        \"protocol\": \"*\",\n        \"sourcePortRange\": \"*\",\n        \"destinationPortRange\": \"*\",\n        \"sourceAddressPrefix\": \"*\",\n        \"destinationAddressPrefix\": \"*\",\n        \"access\": \"Deny\",\n        \"priority\": 65500,\n        \"direction\": \"Outbound\"\n      }\n    }]\n  }\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/networksecuritygroupget.json",
    "content": "{\n  \"name\": \"testNetworkSecurityGroup\",\n  \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/jims947groupjclouds/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup\",\n  \"etag\": \"W/\\\"14e288e4-5d9b-48cf-89c4-b532b59d71de\\\"\",\n  \"type\": \"Microsoft.Network/networkSecurityGroups\",\n  \"location\": \"westus\",\n  \"properties\": {\n    \"provisioningState\": \"Succeeded\",\n    \"resourceGuid\": \"028cb30d-f97f-4dbe-9fea-705da1f383ca\",\n    \"securityRules\": [{\n      \"name\": \"denyallout\",\n      \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/jims947groupjclouds/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/securityRules/denyallout\",\n      \"etag\": \"W/\\\"14e288e4-5d9b-48cf-89c4-b532b59d71de\\\"\",\n      \"properties\": {\n        \"provisioningState\": \"Succeeded\",\n        \"description\": \"deny all out\",\n        \"protocol\": \"Tcp\",\n        \"sourcePortRange\": \"*\",\n        \"destinationPortRange\": \"*\",\n        \"sourceAddressPrefix\": \"*\",\n        \"destinationAddressPrefix\": \"*\",\n        \"access\": \"Deny\",\n        \"priority\": 4095,\n        \"direction\": \"Outbound\"\n      }\n    }],\n    \"defaultSecurityRules\": [{\n      \"name\": \"AllowVnetInBound\",\n      \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/jims947groupjclouds/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/defaultSecurityRules/AllowVnetInBound\",\n      \"etag\": \"W/\\\"14e288e4-5d9b-48cf-89c4-b532b59d71de\\\"\",\n      \"properties\": {\n        \"provisioningState\": \"Succeeded\",\n        \"description\": \"Allow inbound traffic from all VMs in VNET\",\n        \"protocol\": \"*\",\n        \"sourcePortRange\": \"*\",\n        \"destinationPortRange\": \"*\",\n        \"sourceAddressPrefix\": \"VirtualNetwork\",\n        \"destinationAddressPrefix\": \"VirtualNetwork\",\n        \"access\": \"Allow\",\n        \"priority\": 65000,\n        \"direction\": \"Inbound\"\n      }\n    }, {\n      \"name\": \"AllowAzureLoadBalancerInBound\",\n      \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/jims947groupjclouds/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/defaultSecurityRules/AllowAzureLoadBalancerInBound\",\n      \"etag\": \"W/\\\"14e288e4-5d9b-48cf-89c4-b532b59d71de\\\"\",\n      \"properties\": {\n        \"provisioningState\": \"Succeeded\",\n        \"description\": \"Allow inbound traffic from azure load balancer\",\n        \"protocol\": \"*\",\n        \"sourcePortRange\": \"*\",\n        \"destinationPortRange\": \"*\",\n        \"sourceAddressPrefix\": \"AzureLoadBalancer\",\n        \"destinationAddressPrefix\": \"*\",\n        \"access\": \"Allow\",\n        \"priority\": 65001,\n        \"direction\": \"Inbound\"\n      }\n    }, {\n      \"name\": \"DenyAllInBound\",\n      \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/jims947groupjclouds/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/defaultSecurityRules/DenyAllInBound\",\n      \"etag\": \"W/\\\"14e288e4-5d9b-48cf-89c4-b532b59d71de\\\"\",\n      \"properties\": {\n        \"provisioningState\": \"Succeeded\",\n        \"description\": \"Deny all inbound traffic\",\n        \"protocol\": \"*\",\n        \"sourcePortRange\": \"*\",\n        \"destinationPortRange\": \"*\",\n        \"sourceAddressPrefix\": \"*\",\n        \"destinationAddressPrefix\": \"*\",\n        \"access\": \"Deny\",\n        \"priority\": 65500,\n        \"direction\": \"Inbound\"\n      }\n    }, {\n      \"name\": \"AllowVnetOutBound\",\n      \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/jims947groupjclouds/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/defaultSecurityRules/AllowVnetOutBound\",\n      \"etag\": \"W/\\\"14e288e4-5d9b-48cf-89c4-b532b59d71de\\\"\",\n      \"properties\": {\n        \"provisioningState\": \"Succeeded\",\n        \"description\": \"Allow outbound traffic from all VMs to all VMs in VNET\",\n        \"protocol\": \"*\",\n        \"sourcePortRange\": \"*\",\n        \"destinationPortRange\": \"*\",\n        \"sourceAddressPrefix\": \"VirtualNetwork\",\n        \"destinationAddressPrefix\": \"VirtualNetwork\",\n        \"access\": \"Allow\",\n        \"priority\": 65000,\n        \"direction\": \"Outbound\"\n      }\n    }, {\n      \"name\": \"AllowInternetOutBound\",\n      \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/jims947groupjclouds/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/defaultSecurityRules/AllowInternetOutBound\",\n      \"etag\": \"W/\\\"14e288e4-5d9b-48cf-89c4-b532b59d71de\\\"\",\n      \"properties\": {\n        \"provisioningState\": \"Succeeded\",\n        \"description\": \"Allow outbound traffic from all VMs to Internet\",\n        \"protocol\": \"*\",\n        \"sourcePortRange\": \"*\",\n        \"destinationPortRange\": \"*\",\n        \"sourceAddressPrefix\": \"*\",\n        \"destinationAddressPrefix\": \"Internet\",\n        \"access\": \"Allow\",\n        \"priority\": 65001,\n        \"direction\": \"Outbound\"\n      }\n    }, {\n      \"name\": \"DenyAllOutBound\",\n      \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/jims947groupjclouds/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/defaultSecurityRules/DenyAllOutBound\",\n      \"etag\": \"W/\\\"14e288e4-5d9b-48cf-89c4-b532b59d71de\\\"\",\n      \"properties\": {\n        \"provisioningState\": \"Succeeded\",\n        \"description\": \"Deny all outbound traffic\",\n        \"protocol\": \"*\",\n        \"sourcePortRange\": \"*\",\n        \"destinationPortRange\": \"*\",\n        \"sourceAddressPrefix\": \"*\",\n        \"destinationAddressPrefix\": \"*\",\n        \"access\": \"Deny\",\n        \"priority\": 65500,\n        \"direction\": \"Outbound\"\n      }\n    }]\n  }\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/networksecuritygrouplist.json",
    "content": "{\n  \"value\": [{\n    \"name\": \"testNetworkSecurityGroup\",\n    \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/jims947groupjclouds/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup\",\n    \"etag\": \"W/\\\"14e288e4-5d9b-48cf-89c4-b532b59d71de\\\"\",\n    \"type\": \"Microsoft.Network/networkSecurityGroups\",\n    \"location\": \"westus\",\n    \"properties\": {\n      \"provisioningState\": \"Succeeded\",\n      \"resourceGuid\": \"028cb30d-f97f-4dbe-9fea-705da1f383ca\",\n      \"securityRules\": [{\n        \"name\": \"denyallout\",\n        \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/jims947groupjclouds/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/securityRules/denyallout\",\n        \"etag\": \"W/\\\"14e288e4-5d9b-48cf-89c4-b532b59d71de\\\"\",\n        \"properties\": {\n          \"provisioningState\": \"Succeeded\",\n          \"description\": \"deny all out\",\n          \"protocol\": \"Tcp\",\n          \"sourcePortRange\": \"*\",\n          \"destinationPortRange\": \"*\",\n          \"sourceAddressPrefix\": \"*\",\n          \"destinationAddressPrefix\": \"*\",\n          \"access\": \"Deny\",\n          \"priority\": 4095,\n          \"direction\": \"Outbound\"\n        }\n      }],\n      \"defaultSecurityRules\": [{\n        \"name\": \"AllowVnetInBound\",\n        \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/jims947groupjclouds/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/defaultSecurityRules/AllowVnetInBound\",\n        \"etag\": \"W/\\\"14e288e4-5d9b-48cf-89c4-b532b59d71de\\\"\",\n        \"properties\": {\n          \"provisioningState\": \"Succeeded\",\n          \"description\": \"Allow inbound traffic from all VMs in VNET\",\n          \"protocol\": \"*\",\n          \"sourcePortRange\": \"*\",\n          \"destinationPortRange\": \"*\",\n          \"sourceAddressPrefix\": \"VirtualNetwork\",\n          \"destinationAddressPrefix\": \"VirtualNetwork\",\n          \"access\": \"Allow\",\n          \"priority\": 65000,\n          \"direction\": \"Inbound\"\n        }\n      }, {\n        \"name\": \"AllowAzureLoadBalancerInBound\",\n        \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/jims947groupjclouds/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/defaultSecurityRules/AllowAzureLoadBalancerInBound\",\n        \"etag\": \"W/\\\"14e288e4-5d9b-48cf-89c4-b532b59d71de\\\"\",\n        \"properties\": {\n          \"provisioningState\": \"Succeeded\",\n          \"description\": \"Allow inbound traffic from azure load balancer\",\n          \"protocol\": \"*\",\n          \"sourcePortRange\": \"*\",\n          \"destinationPortRange\": \"*\",\n          \"sourceAddressPrefix\": \"AzureLoadBalancer\",\n          \"destinationAddressPrefix\": \"*\",\n          \"access\": \"Allow\",\n          \"priority\": 65001,\n          \"direction\": \"Inbound\"\n        }\n      }, {\n        \"name\": \"DenyAllInBound\",\n        \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/jims947groupjclouds/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/defaultSecurityRules/DenyAllInBound\",\n        \"etag\": \"W/\\\"14e288e4-5d9b-48cf-89c4-b532b59d71de\\\"\",\n        \"properties\": {\n          \"provisioningState\": \"Succeeded\",\n          \"description\": \"Deny all inbound traffic\",\n          \"protocol\": \"*\",\n          \"sourcePortRange\": \"*\",\n          \"destinationPortRange\": \"*\",\n          \"sourceAddressPrefix\": \"*\",\n          \"destinationAddressPrefix\": \"*\",\n          \"access\": \"Deny\",\n          \"priority\": 65500,\n          \"direction\": \"Inbound\"\n        }\n      }, {\n        \"name\": \"AllowVnetOutBound\",\n        \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/jims947groupjclouds/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/defaultSecurityRules/AllowVnetOutBound\",\n        \"etag\": \"W/\\\"14e288e4-5d9b-48cf-89c4-b532b59d71de\\\"\",\n        \"properties\": {\n          \"provisioningState\": \"Succeeded\",\n          \"description\": \"Allow outbound traffic from all VMs to all VMs in VNET\",\n          \"protocol\": \"*\",\n          \"sourcePortRange\": \"*\",\n          \"destinationPortRange\": \"*\",\n          \"sourceAddressPrefix\": \"VirtualNetwork\",\n          \"destinationAddressPrefix\": \"VirtualNetwork\",\n          \"access\": \"Allow\",\n          \"priority\": 65000,\n          \"direction\": \"Outbound\"\n        }\n      }, {\n        \"name\": \"AllowInternetOutBound\",\n        \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/jims947groupjclouds/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/defaultSecurityRules/AllowInternetOutBound\",\n        \"etag\": \"W/\\\"14e288e4-5d9b-48cf-89c4-b532b59d71de\\\"\",\n        \"properties\": {\n          \"provisioningState\": \"Succeeded\",\n          \"description\": \"Allow outbound traffic from all VMs to Internet\",\n          \"protocol\": \"*\",\n          \"sourcePortRange\": \"*\",\n          \"destinationPortRange\": \"*\",\n          \"sourceAddressPrefix\": \"*\",\n          \"destinationAddressPrefix\": \"Internet\",\n          \"access\": \"Allow\",\n          \"priority\": 65001,\n          \"direction\": \"Outbound\"\n        }\n      }, {\n        \"name\": \"DenyAllOutBound\",\n        \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/jims947groupjclouds/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/defaultSecurityRules/DenyAllOutBound\",\n        \"etag\": \"W/\\\"14e288e4-5d9b-48cf-89c4-b532b59d71de\\\"\",\n        \"properties\": {\n          \"provisioningState\": \"Succeeded\",\n          \"description\": \"Deny all outbound traffic\",\n          \"protocol\": \"*\",\n          \"sourcePortRange\": \"*\",\n          \"destinationPortRange\": \"*\",\n          \"sourceAddressPrefix\": \"*\",\n          \"destinationAddressPrefix\": \"*\",\n          \"access\": \"Deny\",\n          \"priority\": 65500,\n          \"direction\": \"Outbound\"\n        }\n      }]\n    }\n  }]\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/networksecuritygrouplistall.json",
    "content": "{\n  \"value\": [{\n    \"name\": \"testNetworkSecurityGroup\",\n    \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/otherRG/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup\",\n    \"etag\": \"W/\\\"14e288e4-5d9b-48cf-89c4-b532b59d71de\\\"\",\n    \"type\": \"Microsoft.Network/networkSecurityGroups\",\n    \"location\": \"westus\",\n    \"properties\": {\n      \"provisioningState\": \"Succeeded\",\n      \"resourceGuid\": \"028cb30d-f97f-4dbe-9fea-705da1f383ca\",\n      \"securityRules\": [{\n        \"name\": \"denyallout\",\n        \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/otherRG/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/securityRules/denyallout\",\n        \"etag\": \"W/\\\"14e288e4-5d9b-48cf-89c4-b532b59d71de\\\"\",\n        \"properties\": {\n          \"provisioningState\": \"Succeeded\",\n          \"description\": \"deny all out\",\n          \"protocol\": \"Tcp\",\n          \"sourcePortRange\": \"*\",\n          \"destinationPortRange\": \"*\",\n          \"sourceAddressPrefix\": \"*\",\n          \"destinationAddressPrefix\": \"*\",\n          \"access\": \"Deny\",\n          \"priority\": 4095,\n          \"direction\": \"Outbound\"\n        }\n      }],\n      \"defaultSecurityRules\": [{\n        \"name\": \"AllowVnetInBound\",\n        \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/otherRG/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/defaultSecurityRules/AllowVnetInBound\",\n        \"etag\": \"W/\\\"14e288e4-5d9b-48cf-89c4-b532b59d71de\\\"\",\n        \"properties\": {\n          \"provisioningState\": \"Succeeded\",\n          \"description\": \"Allow inbound traffic from all VMs in VNET\",\n          \"protocol\": \"*\",\n          \"sourcePortRange\": \"*\",\n          \"destinationPortRange\": \"*\",\n          \"sourceAddressPrefix\": \"VirtualNetwork\",\n          \"destinationAddressPrefix\": \"VirtualNetwork\",\n          \"access\": \"Allow\",\n          \"priority\": 65000,\n          \"direction\": \"Inbound\"\n        }\n      }, {\n        \"name\": \"AllowAzureLoadBalancerInBound\",\n        \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/otherRG/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/defaultSecurityRules/AllowAzureLoadBalancerInBound\",\n        \"etag\": \"W/\\\"14e288e4-5d9b-48cf-89c4-b532b59d71de\\\"\",\n        \"properties\": {\n          \"provisioningState\": \"Succeeded\",\n          \"description\": \"Allow inbound traffic from azure load balancer\",\n          \"protocol\": \"*\",\n          \"sourcePortRange\": \"*\",\n          \"destinationPortRange\": \"*\",\n          \"sourceAddressPrefix\": \"AzureLoadBalancer\",\n          \"destinationAddressPrefix\": \"*\",\n          \"access\": \"Allow\",\n          \"priority\": 65001,\n          \"direction\": \"Inbound\"\n        }\n      }, {\n        \"name\": \"DenyAllInBound\",\n        \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/otherRG/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/defaultSecurityRules/DenyAllInBound\",\n        \"etag\": \"W/\\\"14e288e4-5d9b-48cf-89c4-b532b59d71de\\\"\",\n        \"properties\": {\n          \"provisioningState\": \"Succeeded\",\n          \"description\": \"Deny all inbound traffic\",\n          \"protocol\": \"*\",\n          \"sourcePortRange\": \"*\",\n          \"destinationPortRange\": \"*\",\n          \"sourceAddressPrefix\": \"*\",\n          \"destinationAddressPrefix\": \"*\",\n          \"access\": \"Deny\",\n          \"priority\": 65500,\n          \"direction\": \"Inbound\"\n        }\n      }, {\n        \"name\": \"AllowVnetOutBound\",\n        \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/otherRG/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/defaultSecurityRules/AllowVnetOutBound\",\n        \"etag\": \"W/\\\"14e288e4-5d9b-48cf-89c4-b532b59d71de\\\"\",\n        \"properties\": {\n          \"provisioningState\": \"Succeeded\",\n          \"description\": \"Allow outbound traffic from all VMs to all VMs in VNET\",\n          \"protocol\": \"*\",\n          \"sourcePortRange\": \"*\",\n          \"destinationPortRange\": \"*\",\n          \"sourceAddressPrefix\": \"VirtualNetwork\",\n          \"destinationAddressPrefix\": \"VirtualNetwork\",\n          \"access\": \"Allow\",\n          \"priority\": 65000,\n          \"direction\": \"Outbound\"\n        }\n      }, {\n        \"name\": \"AllowInternetOutBound\",\n        \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/otherRG/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/defaultSecurityRules/AllowInternetOutBound\",\n        \"etag\": \"W/\\\"14e288e4-5d9b-48cf-89c4-b532b59d71de\\\"\",\n        \"properties\": {\n          \"provisioningState\": \"Succeeded\",\n          \"description\": \"Allow outbound traffic from all VMs to Internet\",\n          \"protocol\": \"*\",\n          \"sourcePortRange\": \"*\",\n          \"destinationPortRange\": \"*\",\n          \"sourceAddressPrefix\": \"*\",\n          \"destinationAddressPrefix\": \"Internet\",\n          \"access\": \"Allow\",\n          \"priority\": 65001,\n          \"direction\": \"Outbound\"\n        }\n      }, {\n        \"name\": \"DenyAllOutBound\",\n        \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/otherRG/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/defaultSecurityRules/DenyAllOutBound\",\n        \"etag\": \"W/\\\"14e288e4-5d9b-48cf-89c4-b532b59d71de\\\"\",\n        \"properties\": {\n          \"provisioningState\": \"Succeeded\",\n          \"description\": \"Deny all outbound traffic\",\n          \"protocol\": \"*\",\n          \"sourcePortRange\": \"*\",\n          \"destinationPortRange\": \"*\",\n          \"sourceAddressPrefix\": \"*\",\n          \"destinationAddressPrefix\": \"*\",\n          \"access\": \"Deny\",\n          \"priority\": 65500,\n          \"direction\": \"Outbound\"\n        }\n      }]\n    }\n  },\n    {\n      \"name\": \"testNetworkSecurityGroup\",\n      \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/jims947groupjclouds/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup\",\n      \"etag\": \"W/\\\"14e288e4-5d9b-48cf-89c4-b532b59d71de\\\"\",\n      \"type\": \"Microsoft.Network/networkSecurityGroups\",\n      \"location\": \"westus\",\n      \"properties\": {\n        \"provisioningState\": \"Succeeded\",\n        \"resourceGuid\": \"028cb30d-f97f-4dbe-9fea-705da1f383ca\",\n        \"securityRules\": [{\n          \"name\": \"denyallout\",\n          \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/jims947groupjclouds/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/securityRules/denyallout\",\n          \"etag\": \"W/\\\"14e288e4-5d9b-48cf-89c4-b532b59d71de\\\"\",\n          \"properties\": {\n            \"provisioningState\": \"Succeeded\",\n            \"description\": \"deny all out\",\n            \"protocol\": \"Tcp\",\n            \"sourcePortRange\": \"*\",\n            \"destinationPortRange\": \"*\",\n            \"sourceAddressPrefix\": \"*\",\n            \"destinationAddressPrefix\": \"*\",\n            \"access\": \"Deny\",\n            \"priority\": 4095,\n            \"direction\": \"Outbound\"\n          }\n        }],\n        \"defaultSecurityRules\": [{\n          \"name\": \"AllowVnetInBound\",\n          \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/jims947groupjclouds/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/defaultSecurityRules/AllowVnetInBound\",\n          \"etag\": \"W/\\\"14e288e4-5d9b-48cf-89c4-b532b59d71de\\\"\",\n          \"properties\": {\n            \"provisioningState\": \"Succeeded\",\n            \"description\": \"Allow inbound traffic from all VMs in VNET\",\n            \"protocol\": \"*\",\n            \"sourcePortRange\": \"*\",\n            \"destinationPortRange\": \"*\",\n            \"sourceAddressPrefix\": \"VirtualNetwork\",\n            \"destinationAddressPrefix\": \"VirtualNetwork\",\n            \"access\": \"Allow\",\n            \"priority\": 65000,\n            \"direction\": \"Inbound\"\n          }\n        }, {\n          \"name\": \"AllowAzureLoadBalancerInBound\",\n          \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/jims947groupjclouds/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/defaultSecurityRules/AllowAzureLoadBalancerInBound\",\n          \"etag\": \"W/\\\"14e288e4-5d9b-48cf-89c4-b532b59d71de\\\"\",\n          \"properties\": {\n            \"provisioningState\": \"Succeeded\",\n            \"description\": \"Allow inbound traffic from azure load balancer\",\n            \"protocol\": \"*\",\n            \"sourcePortRange\": \"*\",\n            \"destinationPortRange\": \"*\",\n            \"sourceAddressPrefix\": \"AzureLoadBalancer\",\n            \"destinationAddressPrefix\": \"*\",\n            \"access\": \"Allow\",\n            \"priority\": 65001,\n            \"direction\": \"Inbound\"\n          }\n        }, {\n          \"name\": \"DenyAllInBound\",\n          \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/jims947groupjclouds/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/defaultSecurityRules/DenyAllInBound\",\n          \"etag\": \"W/\\\"14e288e4-5d9b-48cf-89c4-b532b59d71de\\\"\",\n          \"properties\": {\n            \"provisioningState\": \"Succeeded\",\n            \"description\": \"Deny all inbound traffic\",\n            \"protocol\": \"*\",\n            \"sourcePortRange\": \"*\",\n            \"destinationPortRange\": \"*\",\n            \"sourceAddressPrefix\": \"*\",\n            \"destinationAddressPrefix\": \"*\",\n            \"access\": \"Deny\",\n            \"priority\": 65500,\n            \"direction\": \"Inbound\"\n          }\n        }, {\n          \"name\": \"AllowVnetOutBound\",\n          \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/jims947groupjclouds/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/defaultSecurityRules/AllowVnetOutBound\",\n          \"etag\": \"W/\\\"14e288e4-5d9b-48cf-89c4-b532b59d71de\\\"\",\n          \"properties\": {\n            \"provisioningState\": \"Succeeded\",\n            \"description\": \"Allow outbound traffic from all VMs to all VMs in VNET\",\n            \"protocol\": \"*\",\n            \"sourcePortRange\": \"*\",\n            \"destinationPortRange\": \"*\",\n            \"sourceAddressPrefix\": \"VirtualNetwork\",\n            \"destinationAddressPrefix\": \"VirtualNetwork\",\n            \"access\": \"Allow\",\n            \"priority\": 65000,\n            \"direction\": \"Outbound\"\n          }\n        }, {\n          \"name\": \"AllowInternetOutBound\",\n          \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/jims947groupjclouds/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/defaultSecurityRules/AllowInternetOutBound\",\n          \"etag\": \"W/\\\"14e288e4-5d9b-48cf-89c4-b532b59d71de\\\"\",\n          \"properties\": {\n            \"provisioningState\": \"Succeeded\",\n            \"description\": \"Allow outbound traffic from all VMs to Internet\",\n            \"protocol\": \"*\",\n            \"sourcePortRange\": \"*\",\n            \"destinationPortRange\": \"*\",\n            \"sourceAddressPrefix\": \"*\",\n            \"destinationAddressPrefix\": \"Internet\",\n            \"access\": \"Allow\",\n            \"priority\": 65001,\n            \"direction\": \"Outbound\"\n          }\n        }, {\n          \"name\": \"DenyAllOutBound\",\n          \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/jims947groupjclouds/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/defaultSecurityRules/DenyAllOutBound\",\n          \"etag\": \"W/\\\"14e288e4-5d9b-48cf-89c4-b532b59d71de\\\"\",\n          \"properties\": {\n            \"provisioningState\": \"Succeeded\",\n            \"description\": \"Deny all outbound traffic\",\n            \"protocol\": \"*\",\n            \"sourcePortRange\": \"*\",\n            \"destinationPortRange\": \"*\",\n            \"sourceAddressPrefix\": \"*\",\n            \"destinationAddressPrefix\": \"*\",\n            \"access\": \"Deny\",\n            \"priority\": 65500,\n            \"direction\": \"Outbound\"\n          }\n        }]\n      }\n    }]\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/networksecurityrulecreate.json",
    "content": "{\n  \"name\": \"allowalludpin\",\n  \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/jims859groupjclouds/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/securityRules/allowalludpin\",\n  \"etag\": \"W/\\\"d9b6cda9-3873-445d-bc70-cd9c13f87ba7\\\"\",\n  \"properties\": {\n    \"provisioningState\": \"Updating\",\n    \"description\": \"allow all udp in\",\n    \"protocol\": \"Udp\",\n    \"sourcePortRange\": \"*\",\n    \"destinationPortRange\": \"*\",\n    \"sourceAddressPrefix\": \"*\",\n    \"destinationAddressPrefix\": \"*\",\n    \"access\": \"Allow\",\n    \"priority\": 4094,\n    \"direction\": \"Inbound\",\n    \"provisioningState\": \"Succeeded\"\n  }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/networksecurityruleget.json",
    "content": "{\n  \"name\": \"allowalludpin\",\n  \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/jims859groupjclouds/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/securityRules/allowalludpin\",\n  \"etag\": \"W/\\\"d9b6cda9-3873-445d-bc70-cd9c13f87ba7\\\"\",\n  \"properties\": {\n    \"provisioningState\": \"Updating\",\n    \"description\": \"allow all udp in\",\n    \"protocol\": \"Udp\",\n    \"sourcePortRange\": \"*\",\n    \"destinationPortRange\": \"*\",\n    \"sourceAddressPrefix\": \"*\",\n    \"destinationAddressPrefix\": \"*\",\n    \"access\": \"Allow\",\n    \"priority\": 4094,\n    \"direction\": \"Inbound\"\n  }\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/networksecurityrulegetdefault.json",
    "content": "{\n  \"name\": \"AllowVnetInBound\",\n  \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/jims741groupjclouds/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/defaultSecurityRules/AllowVnetInBound\",\n  \"etag\": \"W/\\\"23efab91-398a-4984-a9a7-281af38f6538\\\"\",\n  \"properties\": {\n    \"provisioningState\": \"Succeeded\",\n    \"description\": \"Allow inbound traffic from all VMs in VNET\",\n    \"protocol\": \"*\",\n    \"sourcePortRange\": \"*\",\n    \"destinationPortRange\": \"*\",\n    \"sourceAddressPrefix\": \"VirtualNetwork\",\n    \"destinationAddressPrefix\": \"VirtualNetwork\",\n    \"access\": \"Allow\",\n    \"priority\": 65000,\n    \"direction\": \"Inbound\"\n  }\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/networksecurityrulelist.json",
    "content": "{\n  \"value\": [{\n    \"name\": \"denyallout\",\n    \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/jims859groupjclouds/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/securityRules/denyallout\",\n    \"etag\": \"W/\\\"409ae6c7-fbe1-4bc4-aadb-c1d8330844d2\\\"\",\n    \"properties\": {\n      \"provisioningState\": \"Succeeded\",\n      \"description\": \"deny all out\",\n      \"protocol\": \"Tcp\",\n      \"sourcePortRange\": \"*\",\n      \"destinationPortRange\": \"*\",\n      \"sourceAddressPrefix\": \"*\",\n      \"destinationAddressPrefix\": \"*\",\n      \"access\": \"Deny\",\n      \"priority\": 4095,\n      \"direction\": \"Outbound\"\n    }\n  }, {\n    \"name\": \"allowalludpin\",\n    \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/jims859groupjclouds/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/securityRules/allowalludpin\",\n    \"etag\": \"W/\\\"409ae6c7-fbe1-4bc4-aadb-c1d8330844d2\\\"\",\n    \"properties\": {\n      \"provisioningState\": \"Succeeded\",\n      \"description\": \"allow all udp in\",\n      \"protocol\": \"Udp\",\n      \"sourcePortRange\": \"*\",\n      \"destinationPortRange\": \"*\",\n      \"sourceAddressPrefix\": \"*\",\n      \"destinationAddressPrefix\": \"*\",\n      \"access\": \"Allow\",\n      \"priority\": 4094,\n      \"direction\": \"Inbound\"\n    }\n  }]\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/networksecurityrulelistdefault.json",
    "content": "{\n  \"value\": [{\n    \"name\": \"AllowVnetInBound\",\n    \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/jims859groupjclouds/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/defaultSecurityRules/AllowVnetInBound\",\n    \"etag\": \"W/\\\"409ae6c7-fbe1-4bc4-aadb-c1d8330844d2\\\"\",\n    \"properties\": {\n      \"provisioningState\": \"Succeeded\",\n      \"description\": \"Allow inbound traffic from all VMs in VNET\",\n      \"protocol\": \"*\",\n      \"sourcePortRange\": \"*\",\n      \"destinationPortRange\": \"*\",\n      \"sourceAddressPrefix\": \"VirtualNetwork\",\n      \"destinationAddressPrefix\": \"VirtualNetwork\",\n      \"access\": \"Allow\",\n      \"priority\": 65000,\n      \"direction\": \"Inbound\"\n    }\n  }, {\n    \"name\": \"AllowAzureLoadBalancerInBound\",\n    \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/jims859groupjclouds/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/defaultSecurityRules/AllowAzureLoadBalancerInBound\",\n    \"etag\": \"W/\\\"409ae6c7-fbe1-4bc4-aadb-c1d8330844d2\\\"\",\n    \"properties\": {\n      \"provisioningState\": \"Succeeded\",\n      \"description\": \"Allow inbound traffic from azure load balancer\",\n      \"protocol\": \"*\",\n      \"sourcePortRange\": \"*\",\n      \"destinationPortRange\": \"*\",\n      \"sourceAddressPrefix\": \"AzureLoadBalancer\",\n      \"destinationAddressPrefix\": \"*\",\n      \"access\": \"Allow\",\n      \"priority\": 65001,\n      \"direction\": \"Inbound\"\n    }\n  }, {\n    \"name\": \"DenyAllInBound\",\n    \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/jims859groupjclouds/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/defaultSecurityRules/DenyAllInBound\",\n    \"etag\": \"W/\\\"409ae6c7-fbe1-4bc4-aadb-c1d8330844d2\\\"\",\n    \"properties\": {\n      \"provisioningState\": \"Succeeded\",\n      \"description\": \"Deny all inbound traffic\",\n      \"protocol\": \"*\",\n      \"sourcePortRange\": \"*\",\n      \"destinationPortRange\": \"*\",\n      \"sourceAddressPrefix\": \"*\",\n      \"destinationAddressPrefix\": \"*\",\n      \"access\": \"Deny\",\n      \"priority\": 65500,\n      \"direction\": \"Inbound\"\n    }\n  }, {\n    \"name\": \"AllowVnetOutBound\",\n    \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/jims859groupjclouds/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/defaultSecurityRules/AllowVnetOutBound\",\n    \"etag\": \"W/\\\"409ae6c7-fbe1-4bc4-aadb-c1d8330844d2\\\"\",\n    \"properties\": {\n      \"provisioningState\": \"Succeeded\",\n      \"description\": \"Allow outbound traffic from all VMs to all VMs in VNET\",\n      \"protocol\": \"*\",\n      \"sourcePortRange\": \"*\",\n      \"destinationPortRange\": \"*\",\n      \"sourceAddressPrefix\": \"VirtualNetwork\",\n      \"destinationAddressPrefix\": \"VirtualNetwork\",\n      \"access\": \"Allow\",\n      \"priority\": 65000,\n      \"direction\": \"Outbound\"\n    }\n  }, {\n    \"name\": \"AllowInternetOutBound\",\n    \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/jims859groupjclouds/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/defaultSecurityRules/AllowInternetOutBound\",\n    \"etag\": \"W/\\\"409ae6c7-fbe1-4bc4-aadb-c1d8330844d2\\\"\",\n    \"properties\": {\n      \"provisioningState\": \"Succeeded\",\n      \"description\": \"Allow outbound traffic from all VMs to Internet\",\n      \"protocol\": \"*\",\n      \"sourcePortRange\": \"*\",\n      \"destinationPortRange\": \"*\",\n      \"sourceAddressPrefix\": \"*\",\n      \"destinationAddressPrefix\": \"Internet\",\n      \"access\": \"Allow\",\n      \"priority\": 65001,\n      \"direction\": \"Outbound\"\n    }\n  }, {\n    \"name\": \"DenyAllOutBound\",\n    \"id\": \"/subscriptions/e43b3d9c-f839-48a8-b0fb-691aee6f1e4d/resourceGroups/jims859groupjclouds/providers/Microsoft.Network/networkSecurityGroups/testNetworkSecurityGroup/defaultSecurityRules/DenyAllOutBound\",\n    \"etag\": \"W/\\\"409ae6c7-fbe1-4bc4-aadb-c1d8330844d2\\\"\",\n    \"properties\": {\n      \"provisioningState\": \"Succeeded\",\n      \"description\": \"Deny all outbound traffic\",\n      \"protocol\": \"*\",\n      \"sourcePortRange\": \"*\",\n      \"destinationPortRange\": \"*\",\n      \"sourceAddressPrefix\": \"*\",\n      \"destinationAddressPrefix\": \"*\",\n      \"access\": \"Deny\",\n      \"priority\": 65500,\n      \"direction\": \"Outbound\"\n    }\n  }]\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/offers.json",
    "content": "[\n  {\n    \"location\": \"eastus\",\n    \"name\": \"WindowsServer\",\n    \"id\": \"/Subscriptions/c36d97d3-3fea-4561-aa2d-e61168908c5b/Providers/Microsoft.Compute/Locations/eastus/Publishers/MicrosoftWindowsServer/ArtifactTypes/VMImage/Offers/WindowsServer\"\n  }\n]"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/publishers.json",
    "content": "[\n  {\n    \"location\": \"eastus\",\n    \"name\": \"MicrosoftVisualStudio\",\n    \"id\": \"/Subscriptions/c36d97d3-3fea-4561-aa2d-e61168908c5b/Providers/Microsoft.Compute/Locations/eastus/Publishers/MicrosoftVisualStudio\"\n  },\n  {\n    \"location\": \"eastus\",\n    \"name\": \"MicrosoftWindowsServer\",\n    \"id\": \"/Subscriptions/c36d97d3-3fea-4561-aa2d-e61168908c5b/Providers/Microsoft.Compute/Locations/eastus/Publishers/MicrosoftWindowsServer\"\n  }\n]"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/resourceDefinition.json",
    "content": "{\n  \"resources\": [\n    {\n      \"name\": \"[parameters('vnName')]\",\n      \"type\": \"Microsoft.Compute/virtualMachines\",\n      \"location\": \"westeurope\",\n      \"apiVersion\": \"2015-06-15\",\n      \"properties\": {\n        \"hardwareProfile\": {\n          \"vmSize\": \"[paramters('vmSize')]\"\n        },\n        \"storageProfile\": {\n          \"osDisk\": {\n            \"osType\":\"Windows\",\n            \"name\":\"testmachine-osDisk.539c38a7-642c-43cc-a20b-89b0f3e56afe.vhd\"\n          }\n        },\n        \"provisioningState\": \"0.0\"\n      }\n    }\n  ]\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/resourcegroup-resources.json",
    "content": "{\n  \"value\": [\n    {\n      \"id\": \"/subscriptions/610bba05-d7a7-4567-96af-48ecbd09453b/resourceGroups/test/providers/Microsoft.Compute/virtualMachines/test\",\n      \"name\": \"test\",\n      \"type\": \"Microsoft.Compute/virtualMachines\",\n      \"location\": \"northeurope\"\n    },\n    {\n      \"id\": \"/subscriptions/610bba05-d7a7-4567-96af-48ecbd09453b/resourceGroups/test/providers/Microsoft.Network/networkInterfaces/test641\",\n      \"name\": \"test641\",\n      \"type\": \"Microsoft.Network/networkInterfaces\",\n      \"location\": \"northeurope\"\n    },\n    {\n      \"id\": \"/subscriptions/610bba05-d7a7-4567-96af-48ecbd09453b/resourceGroups/test/providers/Microsoft.Network/networkSecurityGroups/test-nsg\",\n      \"name\": \"test-nsg\",\n      \"type\": \"Microsoft.Network/networkSecurityGroups\",\n      \"location\": \"northeurope\"\n    },\n    {\n      \"id\": \"/subscriptions/610bba05-d7a7-4567-96af-48ecbd09453b/resourceGroups/test/providers/Microsoft.Network/publicIPAddresses/test-ip\",\n      \"name\": \"test-ip\",\n      \"type\": \"Microsoft.Network/publicIPAddresses\",\n      \"location\": \"northeurope\"\n    },\n    {\n      \"id\": \"/subscriptions/610bba05-d7a7-4567-96af-48ecbd09453b/resourceGroups/test/providers/Microsoft.Network/virtualNetworks/test-vnet\",\n      \"name\": \"test-vnet\",\n      \"type\": \"Microsoft.Network/virtualNetworks\",\n      \"location\": \"northeurope\"\n    },\n    {\n      \"id\": \"/subscriptions/610bba05-d7a7-4567-96af-48ecbd09453b/resourceGroups/test/providers/Microsoft.Storage/storageAccounts/testjclo\",\n      \"name\": \"testjclo\",\n      \"type\": \"Microsoft.Storage/storageAccounts\",\n      \"sku\": {\n        \"name\": \"Premium_LRS\",\n        \"tier\": \"Premium\"\n      },\n      \"kind\": \"Storage\",\n      \"location\": \"northeurope\",\n      \"tags\": {}\n    }\n  ]\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/resourcegroup.json",
    "content": "{\n  \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/jcloudstest\",\n  \"name\": \"jcloudstest\",\n  \"location\": \"westus\",\n  \"tags\": {\n    \"tagname1\": \"tagvalue1\"\n  },\n  \"properties\": {\n    \"provisioningState\": \"Succeeded\"\n  }\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/resourcegroups.json",
    "content": "{\n   \"value\": [\n      {\n         \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/test1\",\n         \"name\": \"test1\",\n         \"location\": \"westus\",\n         \"properties\": {\n            \"provisioningState\": \"Succeeded\"\n         }\n      },\n      {\n         \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/test2\",\n         \"name\": \"test2\",\n         \"location\": \"eastus\",\n         \"properties\": {\n            \"provisioningState\": \"Succeeded\"\n         }\n      }\n   ],\n   \"nextLink\": \"https://management.azure.com/subscriptions/SUBSCRIPTIONID/resourceGroups?api-version=2015-11-01&%24top=2&%24skiptoken=eyJuZXh0UGFydGl0aW9uS2V5IjoiMSE4IVJVTkJNalEtIiwibmV4dFJvd0tleSI6IjEhNjghTURSR04wVkRPRGc0UlRJNE5ERkZSRGcxTXpjMVJURTNOelkyTURBeFJqVmZRVTVRVWtsRFJWUkZVMVF0VjBWVFZGVlQifQ%3d%3d\"\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/resourcegroupupdated.json",
    "content": "{\n  \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/jcloudstest\",\n  \"name\": \"jcloudstest\",\n  \"location\": \"westus\",\n  \"tags\": {},\n  \"properties\": {\n    \"provisioningState\": \"Succeeded\"\n  }\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/serviceprincipals.json",
    "content": "{\n  \"odata.metadata\": \"https://graph.windows.net/tenantId/$metadata#directoryObjects/Microsoft.DirectoryServices.ServicePrincipal\",\n  \"value\": [\n    {\n      \"odata.type\": \"Microsoft.DirectoryServices.ServicePrincipal\",\n      \"objectType\": \"ServicePrincipal\",\n      \"objectId\": \"objectId\",\n      \"deletionTimestamp\": null,\n      \"accountEnabled\": true,\n      \"addIns\": [],\n      \"alternativeNames\": [],\n      \"appDisplayName\": \"jclouds\",\n      \"appId\": \"applicationId\",\n      \"appOwnerTenantId\": \"tenantId\",\n      \"appRoleAssignmentRequired\": false,\n      \"appRoles\": [],\n      \"displayName\": \"jclouds\",\n      \"errorUrl\": null,\n      \"homepage\": \"https://jclouds.apache.org\",\n      \"keyCredentials\": [],\n      \"logoutUrl\": null,\n      \"oauth2Permissions\": [\n        {\n          \"adminConsentDescription\": \"Allow the application to access jclouds on behalf of the signed-in user.\",\n          \"adminConsentDisplayName\": \"Access jclouds\",\n          \"id\": \"id\",\n          \"isEnabled\": true,\n          \"type\": \"User\",\n          \"userConsentDescription\": \"Allow the application to access jclouds on your behalf.\",\n          \"userConsentDisplayName\": \"Access jclouds\",\n          \"value\": \"user_impersonation\"\n        }\n      ],\n      \"passwordCredentials\": [],\n      \"preferredTokenSigningKeyThumbprint\": null,\n      \"publisherName\": \"Default Directory\",\n      \"replyUrls\": [\n        \"https://jclouds.apache.org\"\n      ],\n      \"samlMetadataUrl\": null,\n      \"servicePrincipalNames\": [\n        \"https://jclouds.onmicrosoft.com/jcloudsid\",\n        \"applicationId\"\n      ],\n      \"servicePrincipalType\": \"Application\",\n      \"tags\": [\n        \"WindowsAzureActiveDirectoryIntegratedApp\"\n      ],\n      \"tokenEncryptionKeyId\": null\n    }\n  ]\n}\n\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/skus.json",
    "content": "[\n  {\n    \"location\": \"eastus\",\n    \"name\": \"2008-R2-SP1\",\n    \"id\": \"/Subscriptions/c36d97d3-3fea-4561-aa2d-e61168908c5b/Providers/Microsoft.Compute/Locations/eastus/Publishers/MicrosoftWindowsServer/ArtifactTypes/VMImage/Offers/WindowsServer/Skus/2008-R2-SP1\"\n  },\n  {\n    \"location\": \"eastus\",\n    \"name\": \"2012-Datacenter\",\n    \"id\": \"/Subscriptions/c36d97d3-3fea-4561-aa2d-e61168908c5b/Providers/Microsoft.Compute/Locations/eastus/Publishers/MicrosoftWindowsServer/ArtifactTypes/VMImage/Offers/WindowsServer/Skus/2012-Datacenter\"\n  }\n]"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/storageAccounts.json",
    "content": "{\n  \"value\": [{\n    \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/resourceGroup/providers/Microsoft.Storage/storageAccounts/TESTSTORAGE\",\n    \"location\": \"westus\",\n    \"name\": \"TESTSTORAGE\",\n    \"properties\": {\n      \"accountType\": \"Standard_RAGRS\",\n      \"creationTime\": \"2016-02-24T13:04:45.0890883Z\",\n      \"primaryEndpoints\": {\n        \"blob\": \"https://TESTSTORAGE.blob.core.windows.net/\",\n        \"file\": \"https://TESTSTORAGE.file.core.windows.net/\",\n        \"queue\": \"https://TESTSTORAGE.queue.core.windows.net/\",\n        \"table\": \"https://TESTSTORAGE.table.core.windows.net/\"\n      },\n      \"primaryLocation\": \"westus\",\n      \"provisioningState\": \"Succeeded\",\n      \"secondaryEndpoints\": {\n        \"blob\": \"https://TESTSTORAGE-secondary.blob.core.windows.net/\",\n        \"queue\": \"https://TESTSTORAGE-secondary.queue.core.windows.net/\",\n        \"table\": \"https://TESTSTORAGE-secondary.table.core.windows.net/\"\n      },\n      \"secondaryLocation\": \"eastus\",\n      \"statusOfPrimary\": \"available\",\n      \"statusOfSecondary\": \"available\"\n    },\n    \"tags\": {\n      \"key1\": \"value1\",\n      \"key2\": \"value2\"\n    },\n    \"type\": \"Microsoft.Storage/storageAccounts\"\n  }, {\n    \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/resourceGroup/providers/Microsoft.Storage/storageAccounts/TESTSTORAGE2\",\n    \"location\": \"westus\",\n    \"name\": \"TESTSTORAGE2\",\n    \"properties\": {\n      \"accountType\": \"Standard_RAGRS\",\n      \"creationTime\": \"2016-02-24T13:11:43.8265672Z\",\n      \"primaryEndpoints\": {\n        \"blob\": \"https://TESTSTORAGE2.blob.core.windows.net/\",\n        \"file\": \"https://TESTSTORAGE2.file.core.windows.net/\",\n        \"queue\": \"https://TESTSTORAGE2.queue.core.windows.net/\",\n        \"table\": \"https://TESTSTORAGE2.table.core.windows.net/\"\n      },\n      \"primaryLocation\": \"westus\",\n      \"provisioningState\": \"Succeeded\",\n      \"secondaryEndpoints\": {\n        \"blob\": \"https://TESTSTORAGE2-secondary.blob.core.windows.net/\",\n        \"queue\": \"https://TESTSTORAGE2-secondary.queue.core.windows.net/\",\n        \"table\": \"https://TESTSTORAGE2-secondary.table.core.windows.net/\"\n      },\n      \"secondaryLocation\": \"eastus\",\n      \"statusOfPrimary\": \"available\",\n      \"statusOfSecondary\": \"available\"\n    },\n    \"tags\": {\n      \"key1\": \"value1\",\n      \"key2\": \"value2\"\n    },\n    \"type\": \"Microsoft.Storage/storageAccounts\"\n  }, {\n    \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/resourceGroup/providers/Microsoft.Storage/storageAccounts/TESTSTORAGE3\",\n    \"location\": \"westus\",\n    \"name\": \"TESTSTORAGE3\",\n    \"properties\": {\n      \"accountType\": \"Standard_RAGRS\",\n      \"creationTime\": \"2016-02-24T14:12:59.5223315Z\",\n      \"primaryEndpoints\": {\n        \"blob\": \"https://TESTSTORAGE3.blob.core.windows.net/\",\n        \"file\": \"https://TESTSTORAGE3.file.core.windows.net/\",\n        \"queue\": \"https://TESTSTORAGE3.queue.core.windows.net/\",\n        \"table\": \"https://TESTSTORAGE3.table.core.windows.net/\"\n      },\n      \"primaryLocation\": \"westus\",\n      \"provisioningState\": \"Succeeded\",\n      \"secondaryEndpoints\": {\n        \"blob\": \"https://TESTSTORAGE3-secondary.blob.core.windows.net/\",\n        \"queue\": \"https://TESTSTORAGE3-secondary.queue.core.windows.net/\",\n        \"table\": \"https://TESTSTORAGE3-secondary.table.core.windows.net/\"\n      },\n      \"secondaryLocation\": \"eastus\",\n      \"statusOfPrimary\": \"available\",\n      \"statusOfSecondary\": \"available\"\n    },\n    \"tags\": {\n      \"key1\": \"value1\",\n      \"key2\": \"value2\"\n    },\n    \"type\": \"Microsoft.Storage/storageAccounts\"\n  }]\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/storageCreateResponse.json",
    "content": "{\n  \"location\": \"westus\",\n  \"tags\": {\n    \"property_name\": \"property_value\"\n  },\n  \"properties\": {\n    \"accountType\": \"Premium_LRS\"\n  }\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/storageaccountkeys.json",
    "content": "{\n  \"key1\": \"bndO7lydwDkMo4Y0mFvmfLyi2f9aZY7bwfAVWoJWv4mOVK6E9c/exLnFsSm/NMWgifLCfxC/c6QBTbdEvWUA7w==\",\n  \"key2\": \"/jMLLT3kKqY4K+cUtJTbh7pCBdvG9EMKJxUvaJJAf6W6aUiZe1A1ulXHcibrqRVA2RJE0oUeXQGXLYJ2l85L7A==\"\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/storageaccountupdate.json",
    "content": "{\n  \"properties\": {\n  },\n  \"tags\": {\n    \"another_property_name\": \"another_property_value\"\n  }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/storageservices.json",
    "content": "{\n   \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/resourceGroup/providers/Microsoft.Storage/storageAccounts/TESTSTORAGE\",\n   \"location\": \"westus\",\n   \"name\": \"TESTSTORAGE\",\n   \"properties\": {\n      \"accountType\": \"Standard_RAGRS\",\n      \"creationTime\": \"2016-02-24T13:04:45.0890883Z\",\n      \"primaryEndpoints\": {\n         \"blob\": \"https://TESTSTORAGE.blob.core.windows.net/\",\n         \"file\": \"https://TESTSTORAGE.file.core.windows.net/\",\n         \"queue\": \"https://TESTSTORAGE.queue.core.windows.net/\",\n         \"table\": \"https://TESTSTORAGE.table.core.windows.net/\"\n      },\n      \"primaryLocation\": \"westus\",\n      \"provisioningState\": \"Succeeded\",\n      \"secondaryEndpoints\": {\n         \"blob\": \"https://TESTSTORAGE-secondary.blob.core.windows.net/\",\n         \"queue\": \"https://TESTSTORAGE-secondary.queue.core.windows.net/\",\n         \"table\": \"https://TESTSTORAGE-secondary.table.core.windows.net/\"\n      },\n      \"secondaryLocation\": \"eastus\",\n      \"statusOfPrimary\": \"available\",\n      \"statusOfSecondary\": \"available\"\n   },\n   \"tags\": {\n      \"key1\": \"value1\",\n      \"key2\": \"value2\"\n   },\n   \"type\": \"Microsoft.Storage/storageAccounts\"\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultbackupkey.json",
    "content": "{\n\t\"value\": \"JkF6dXJlS2V5VmF1bHRLZXlCYWNrdXBWMS5taWNyb3NvZnQuY29tZXlKcmFXUWlPaUppTTJJd1pqZ3dZeTB5Wkdaa0xUUmlPVGt0T0RVeE1TMWpZVGRrTTJKbFlURTVNMkVpTENKaGJHY2lPaUpTVTBFdFQwRkZVQ0lzSW1WdVl5STZJa0V4TWpoRFFrTXRTRk15TlRZaWZRLnVWeGFLX3g3V1kyMzhLTEY0TDNVOXJEYUlWdnpwaEt6ckY3WGtqcVhkOGwzaVMwMXdfdncwLUFpS3JocEVoY3NGaHVkMHREaFV2eXBNS2cyN1UxZlZNRkZoRExxVmxwUk5vdTZnSVZKVThSa3N6anZmU3phaS1hYS0zSzFacHU3eENBazJXTW1iZzJMSXB5bWI0T29HZ3B0NXA3dk16RW9fN1ZjRTRKTXhUckVQV0xOY1plQXRKUkxlVFkza3YyUHZCTHQ4cGN3MmhNWUYtQ1hpd1UtcGt3R0s5QUMxUVFwZzBFWEZXZnpGZkNwVkg0UUpZQ1dyckd5MXhUMlpWbERPdGZHcG9zSkZ2cDBfSWR0X2ZnY2lxeVZ4Ym1Ccnk4eGJ4blRXcVdySm1KOExmMldzRXdMcXNvZ3pQUzZlRFJqU29YRlBCd1lqal9ENFVhcDNqTGlCQS5DOEV1cFF1aUNSOU12YVBabGVKSTN3LkQwT01pTHBHd1pVVW5GdDI0OFJYUjNycS1KcVFqeTJSUzZnTFBUMkM1SVFyOHVTZmpoaUI1cTRoQV9TN2NMQTVnWXo4VVZpWTRRNEQ3eTdSU2JxemhRTUNPa1QxclBNUkxtZjYzbC03ckNBaHhHNWNwVzFCZVlma2FBaTFMUGxwZ1RnYi1EN2h2NjFNQzhCcXMtU0t1eTEyN2tfSXV5d0hMelFtXzQ5WTNBQ0xJSGlDQlhYZTlSTWJKSEhuY21nMTc1WGlGY2RuRlhKTnRKb1B6MWZWZWlrRFBkb2x2Z3pYSkFHYTROcDI2SDhJVGRTanRpOWUtWVNUTllTUEs0ZXlwRFRNcFlYcTJZNUJIYjNTNnYzMHZCNWhCdHkxdy1jXy1iQ3pUQ3VHNzA4WnZneHB5V3VXU3prZ2g1VVF4Y0F5djdaUk5fZk1VVEVQdXMxTmRKaEt1N1Vna3FxdWU1c0ZPVm1mS3ZTaXdlN21QZldUajA2N1JpTXVWY29JLTU0eUhLU3NRTXcyZjRteTR4eDk1QlloUmlXOE9HMS1ISzdkN2Z0TGRYbHRKMDR2WjFDUmFOTjlQdldUOWhNR25DUlFRYTMwamlWNDd1Mm9oTnZGRDJNLUlQT25pb1ZYbWNPeGQ2eXluaUpxQzBodWNuMWo3ZnRlTFpNbVlLMDJEOTZNZzZ1aEZnU2ZWVDFDRDdVeUtISk9tamIwX3FtNXBLZ24xWGkxZVhlSWsxMnNpeTBqMDlBNkJDTW9JM3NIdEZaeWxaTmY1SDlTMmRzcEhZN0JvTWt5eUZqOWJjMEFWY1F4Umpjc2YyMEE1cHd4TWlLZ2tRSUlIT3RkbEpGUHQxWUVrQ0Yxc182LTlSenpGbVI2OW5LaUZJdVYwS1BWRjVOT05RYmc1Vm5qcnhhNFEweFhVcE1Ecmsxa2ZQZ0lSRG5LQ1dUMEtlbWkzSVctdS1EMzBHNXJUZ1RvYjdDNkdLd3NYeHpCXy1scWdEb2RqUk9LdVhISFdjMzZlZ3ZwbWNRdDNRaHFkYUt5UEVRTWNUbHdSWGw1VE9yangwWHloZENpZ2hWSk95XzVMVGxLUkpXdVh6dHZ0Z3lIaGhGVi1CdS02UFBKeDFSSTF6NmV0Q2xSNGd3WnlYU3p4c0cwem9tSjlKVTJqczBrQVBmWlFVc1FQZ0FZZFlvTEFkTV93a0l1eXVrNks1RmVTZ2FQbFJiRXEtNmZzdnhCVXM1STRwcm9BYnZDR0c2RXc1YXRDVU8ycTh2V3VrcFBZNG5DVzdseDkxZWI2QVVQRjdhMFUyQzh2SjRJU3VuSGdpaURvX19YaDlTZDk3ZDNZNnFUemZhd1A5eUIwTERKZDZIeDQ4QWNWd1ZYQWdNeVo1Vm1YWWtVTjgxTFVxNzNLY21lRGV6R2hlelpBVmp3cEVXQzZKdzdRMUJfM2luMlA0SzB2bGVXa3ROWjFaV2ltd20yRDNkTjNYdWc2Rkh3MWdjZ0RyaEc1OXd4ZEVTVU40eXFwY2hZQWZSZnlLc0R0NkdpOFRZWThiSGI4eXFCWUxITEpQd2p4UzY3dTc1QVRZTGNKU2lTQXk1cEtPSzRSUGhDMzRVWjR4Wi1mZEFVUGdHNmJIcHd1eHdOWVhYM3dnZzR4LUN4X0s1bERGWTJfenhUdG91c0tGSXZ3N3BDNkRkT215N0JPQkRyRzhUMkVKYmJHQW41QzJxZXNCRHNQMlh0U3RwZno2MXF5QWlpeVFzWVF1UWR0Ums2MWVfaWlDZldaYlBhVTZPYnRYemJrblVCM3lwcHpybnZiQlB3S2RuY2RVVHU2Q2hldzduc1gzRkR3TGdPSnNld0xjb1BwSndSWGl2QnY1Z1pNT2NFLVB3VUc4WmVLWjQzUDMweW9UenJWWnkzUmgtQW80ZVVyR3k0QXFja0UwbUx1ald0d1JUQnpEbFBwWE9aWHV4dTkwTENOdVJXQ0RBYnRfajdKd1hCbkZjSlVTYTJVUkM5VHdWaTNZWW01aURrSnRZR2s4ZkFILVU4b0xIT2dRb2Itb0o1eTdwQjNrM3pnNmpLWC04T0wtbWlLWkw3a1JPYUlOVzNtWEZHSmhIdmR0cHNaaFNVV29FaU9ZbkdNT1NwSFpSdkJtYVRlVDRHNTFLWlB5bHV3aEx2bXNNVTFjZlpYVzE0SnlXZlpYbUk3YWRrQ1cyRTBDZGE4Si0tbGtLQ0pxVUVtdW5WZmhndVRaakRxVF8xSy14ZF9ldkk3TV9mZVNfX3ppZFJncDFiV2NrTl9EZ0NZSjkyNHpSV3h4bVE1MU5NSF9pcVZiS2FFOXhSOXZ5cFNRLS0xV0tONWZFWHh2NFdYa29sbkRTYUp2VWhaYmE1bGFSbXUzT19sQnZMU2VRbEM3eDQ5MWJTbGhmdXpWV2gxOUpzdGRtYkF6Y0dZQk1ZYXpwMDRMclc0cW5ZTVNYWHFQU2VJcWpWMVBzTHg1WTUzR2JxbnY0TktRMEJubnhjRVZHZzVPZGl5ZlB6UTRMZUlPZzZhTzBxUy05eUVqTHFZdGY3dDVWRnZaN1RDWTRDWlI4dlRoT0Z0cURvSHYyVWo0eUJaODFuYU41OFF1aXMtb01iampETTM1OV9WMy1OUWhvTk9vSllpZXFiYW9fSTRlUzVNclAxZXNEYzNvck5BWEptV1M4MDB3SG9maGRjUE9vYmt6dzNjUmhQN19wYjduZGtWZjEwUmVJZEktcnAwTjJiOGk4bEppRG1Xb1otR291bkdkbGZoSVlqdUpROUczRHhMNXcyRWIxRDlXMlBnTlZON3FSRk1fM29Dc045MWs1YnJjNWJUUWdBMTZ4TTg4NlNXb0ttaGViYjdEb2ZSU3NQV1RTRno2Y1JjTzcyTUZNSkQxUDY2T2otcVlfUGU3cElhZ3IyVl9QVFNQclBsb2MyYjBlRmt6bTZROGhlRUdpZVlZcnd0SGFTUVVoWmlyN1N4aW5IVmxTblBYVkpDUzZmcWRKbnBaeHhOdzVaZ2JiWGJobDRwU0tLOGY5b0FDdTNvTk1XUGdWaVRpVjRSS09WalM0QXF1bjB5T2ljRkRoVzVOZEExZWItakhfN2V2RGxaNmNnemZ5bkNfdjFpbzFucDAyTEs2WG9jNURIZEhUMzlqZDkzQUdvZmtkT1c1LWx0clUycW0wMzYxVDA3WTAtSG5ZeHNDQW96VGs1M25zQmdTMkRQWklYaWpiRVpIVHc2OWJINTZPX2J1R0ZBYUdNMUNySV9RLUJoWW9QWHpINHFuMXMyZ3RlcUNaOUtKMGZlMy1lVnE1ZGZkNVRmR2pfUzNCWl9QZnlPYUtIR1pBdk1mcS12cTdhdU52UjN2YnRMTjJkZHhLVTZoQkNpRkcwbmtWZ3JMNVVBbzZ2em5fTXZBdC0zYktaRXhXSDB3WGtjM05rc1U2YnBpMkQyVnFVeV9RUE9TVUlsTktRUDVwX3ExMERheXFleWdwdlZYNWJsMGVwWDd4ZGxURmN3Z3lZUGxpc2h4VnlZX2ZydTV0QlRCX3hjZWgzMXFTeEZjTUNMYnFLMUpIZm5LVjltUVJZNUZDRURibllwQVNTeDBJVkxRVFpqNjBSN3MyVTVqTk0tZzFzXzc2RlNSSDlZS2VEc1FXcUpZNkVxNjJxaHBUNjBDOTFhMGhRRGdIdW5xTU5lSl96azFDbGZZZmJwSWdDaHZFd01YX3VOS1FMRmNDdWVjWG1mS0Fxb1ZfczRLTXJlbVJqMDMzNDQwWUZxS2FiZWhjVDVpYWhDSnRkZnZxSXUwc3pDRnNmY09INGtyRndYTmlXYV9VY09aY3FHc0Fxbjh6eWFfZVRSV3BUanNFelYzY0tjU3F1aHBtQUU2SWpnQ1NFTGw3SmxsZVdteFdzM214NnFJYmJlakhNLV9ndUZ4QmQxc2FJMUZVWFlQYWJsMXFybzJNZDhPSWtGeUR0WmJad3Zla1JoTU9lWFBJWFNKRGFuVkR1S0h3akRCbEktSWgxd2R4TndqN2tBVW5fSm5rM1BZQzVKM2MxTm80Q3hxdW9ocm1nZGJTUEdqNXBzZWNWRDRGaFh2VDVvNUxtRDdVcEVVT3lFemtjVFJNeHNQTTMxVFprRVlnOHktX3V0VTFJLVQxN3NLOGo3dGxnVTFfTm9kQW1TUHM4WmdHaFRhRXA1SVRRZXNFNXN4NFl4TnZBVXpHTklPUGNzSExfTi15WnA4OGN5dlhyV1g4TXdBZEhwYTFNX19Xd09DOS1KempvRVYyejJ3YWNyTk83bUxiQWNydVFoSzBQMXBrRmpsbENzUHdqSkdwWGN4dldtaEdrMDE0cjA1dWtjRkp0LS05bGw1WFFvQkdwWU1GWGY1Q0l1SG9HaUF0cGJvRDlRd2NhN0ZiNkU5MFRqSVhUMkJ4cmhKR1lXY0dWajAzNlFja2I2WVJpOVZiRWxweXBmbkxscEdvWDcxVndVTWJnY1RvMHlORElWLTNtMEM2VlVndmtxS0ljT2RnYi1SX0VPdkVSVHNhODQzVHA0Z3JlM1pnRzlTNVI3UE1GdE40ZUY3NkJZbzdFYm5IcGttdTJkdlg1aDdQdnF0R216cnp0QVozZ1ZWUUcyNFVVNHRDN0VmaHdkLXR1MkNWcU5QTVRROFhSaUxlM3JKMjJuRktEdFNXSXVHcFRoV0hqNGJ1Uy0xRFlkNHBxV1hNUjBtUDNLNkYxbFJ2SUlUSnhlNEhjeVhvaVJtaktJQjVvbFJFZEFsR2ZhY0taY1FmcDhvVUlmM0liNEJnSDVQU1VHSGFMWFhjSDZaN3RPU1pERzZCVmJsZTVvT1VMdkd1SzVUaUQtaVh1bWFSMjk3TFB3SHl0dEZDQ1BjN0txdGZhbEJPTy15dUJacmRtRlVtN3ljMkdpRWtnWnNuVlFzcHl3NHZmU2hWb3VCTGdsbHJuU05NN1l1NWoxM2hTOEFkblBmWGNOQ0xsVkFleTVVeVVuTWlpcmR5ek90Yk9TekI1dHRGcDFpR1AtaElfSmtvUHdvT0RIZUJlbzQ0cXhkekZvUVBWbUFGNS10RzN4QWFqU0FUNGVyNXNLVlZ3dmsxWmZUQlJxYXhQWTdHd3RaWmxpa3hYcThpTC0wdm5mNEtINktnT09uUGtoajM2VmhCeXp1c1BrNkYyUUdQdjNXdlRxX3VMalgxV2V4UWVmS0JjYUtrOTF4R1Nxakl0YXVZQTZGWWpNd3Jmc0NPelNwOGV0VjNQc0NhWEt4dHJyWGxHd1dEOV9EeFhKVmprNDMyc3UyR0pEaVk3aVNfOGl6XzBlQWQxakxOQ09YcFN4SzlFYjdvY2RjS3pTX05JVktqMTZFYWxDa1Z1MGI3OXZfLU0tY055NUwyc0lUZHpGRmZEOVZDdjVRdk5hbFFzTU1Fc2VoRm5JXzAtMW1fRXFNMUtFdTVlWGtZa3JwMThoWXU3RFpCbXg4dDZhTXY0Q0tpVk9kVDhhUVFmeXhwZ3BSSS1jUGdBNHVxVzk0U2dRZ0RURWhmeGVxbzg5WEd1MXBaOTRndHliOXEzVHd3VDZTeWNYRW5vSlExck9EaEhqV0gzRUJyUjZRSVR3d1VqRUFjRHdDZmFPREJ0OWlUeHJjZk0tem5mekx3elZkUjVBakVNd3RSTVZUOEpzd3JYeHI5bXlWMU52cGtZeFdFUlpvbTItcW1DWm1vRWZWdG13d1Axa2g2d1U0a1VGNWo4Q1psOWdUck5NVk9Ra1pzbkxuWDRKVnhpc2k5WENBVWRkLXE3NlZpemNFNGpFYzVmamd6ZzdsdF9IZldWUXpIVWZaR1NXVUg5OGZEd0k3N0otSmh2dlJMMF9uQkpvZDZlYUxVNjRpODgzSDFrODdpTXFXcTl6ZVNrcFpmRGhpZVhvb1Brc1YyRUROZG5pSkt4dHZvcU8zLU53bTdoVTNDZXNEMjZ0STB3dHhEZk1MdkQ3Y2VZMTVRZXNOdTJqSmRTdGE1bmNtZVNMMmNVVWZkUmJyWmhRYmV3VFFtMTh6UWlXSTN5d09jWXhadm9SNXpXc3ctQmIwT29XRWVwbFJQNzR1S3RXTVZVQUlpYTdHcVN0aGxFT2tXcllFMUNLT2ExajB5dU85Q0czTk1jSmdHYnlOMXJUYmR5azBfQXlEUV9JT1NEQUp3TVg0UkZadkNSdjRNWU01U1hPYVhWWVRwa0t0bEdFWXlUaEQyT3liU2ZLNjJhTnNTQUJDc29MWm1Pb1pYeWlwT2swT0F1Rkw1djh6S0hzMkJENVBkTGNRc3B0d0pyUlFPZ3NtS3JRU1dJNFJrTDJwVzJ4VEtfdkJibC1LcnpEcGdJUHZwaUFENUJYS2FEbzlvU3BKRWZQbEw4VTBLX1k4Z00taGtqUmYyZzBzRFdJeVUxYV9raUdzY21UYl9oNlRiYTg5aVQ3cjg3RVhUTlhwMmI2TnNmdDI3QlMxdy1qc0RPSVZtdlNfNThTbVVDXzAwdmxjVENBcUhaM1ItWnE0dFdHdkY4UkE3UnVabDBDYXVvY3hXTFNBV0NEbkVCUXM0X2wyUmowek04NFBXeVhRN0loZlRDVU12X1gzZmwwYVJJN18wYTd2c1BYLXRILThBSTBPRzVRb2tUZm1scXhFWTNhSjRxUTlOTERJN0t1TExpWGE1clZ0WjFVelJLNHRWTUNKaUJPQzRGZ3BiRDRkT1VEWFRQWVUyenRMN3F2dy1pbGxYNTc1WlNyUzVCMGVQSXFUdFl6NWZoX2pXeUtiR2x2U1RlbHpSNFdueVBxa01CaUNWQmd0dkZGS09nZV9vclpEM25CNVVuVHBTd0NGWVFkLTZwVDRKeEdNTDF4RWloWk9tTTdSV1BaaHpFNWVfRGczdzZ5UVlSbUhabV9hb3lrNGh5Tld6OW01Q3hleVlIRjc0N2c5a3NpOHpJN3hycTVLWHVHeFhxMXNIWEtvV21jNTVySV9LeGpTb3Y1bTlLYkVNNGZOMW4tMFVORmF3cDM2Vkk2WGQ3enAwa2pZeXVJY2J1TTZqMkdNUEJIeXZWbmFEYzIzMkVwWWVTdnhOUUJZUW1NR1hDNUNoWm1KQzN5T0ZXV09OQy11SkZjbVY4eENuXzE2LTkzS3JCT1U1eVVYaUZRQlV3M0hzTU5BRnNrdllwWjBncTNwZ1dWNTBOMXRRcDZjclFTTXBNNFppOTdVUU10TlhZLWNPZHpsNHl2Q05mM1ExN013U2Z5MFlrN2F6bVpIalNhclZaajZHbTdadjdFRHRpT0lYNTlDNEJRVGpkTDZONUZJLXROZElxOVlJODB6N3pvRXZpOHE4czY0UmsxZm5TY3NWbkpNOEFKTVVHV1Vkay12REYyTzR0QjNQQllKZXdheUkyNjRHSWJRSElJeDB2Z0pkVkhLYnFmZE56bzZwQnVHaldCUWVkczhWakJxdnA5b3BERnRhamx5X2lkY0p5ZGFtbFNfN0RCekdGaS1SLUNYSmxqVTgtdllvekVJM3h2SkxzamViN3ZtRFNpNml0a3BEaVZwX0hDSUhzQTM5MkhhZzZjN0VSbWJ3cEk0MkZaOUVUYzVReVRoc2ExZkVYaEw3aG5mR2N4b0RpdlJSc2dFdXdndEZTb2N4T0U0Y0o5UjUzeFNTYWRYcUFqSS1NSWdGWDNXRGhjcWlNemRBRm1SQVRnLW9tc1NMN0ZoZ2NmNk5WUUtpaVZVMEJZRUNPQjh2YTVFZVlnd0gwOGZfeTdNUF9Fb0xOZHBQN2IxMWFoSkR3cDRsN3FhaXNWcDZzX0ZoMi03OVN2a3o4RGU5azVNT25WVjQzOEVVUzJGUGMwb2RfQkpxWng2bVNaSFE1MFdpSTYwV2hSTnEtMy1DQWJ3ODVrSVBPTXlCdjlvNXNIVEVVU1EyQjVFSm1HOV9rZFVxTkF6aXE5cWNWbGJ4RHFHc0hsaFJ5QmlZdi1jQjd6NlVack1ZaWNwT3VaYzVNbUFseGxoY0t3cHl2R2RuX0hkRS1RT0dvekNHdUF1M3UwbjU5Um5qWDRCWm1hdTFWeXhJeWkxdkYydXNKUFZub3RoU0NxUlY0U1RNTWljZDhrNm9zU1BIWTZLUmRrRVN1SnRoZjlxWWctVFQ0MVp0M3RYVUE4bUhfWWxNTEU1NnVpWWlJMlZCT2FNbFktMlQ4My1MUHcwTEpnQ2k3RElvZ3BOTnFWRE14ZVVDTWdpX2pKMnotMEYta0pWdUtNMTJMT0YwSENWQmJUeWJ0cFlGVHB2eXFVSU02d1dzanp1WjNGdUh3c3hyVnRqWWZFUHJfaVhtM2FQazBHSEdFVUFLMG1YTUozN3Y1Zm1GZmhwcTJ6aFRyLXJYR29sYVU1NHlBVkZrV2pLbkJYTWdxb0pCLWZMbHh0WFlvMllHbzdHUDFDMkFVRkUzTWFiOW5zSTlacmhGYV8yN0RXMHVDeTBsV09QQ2JCNTRPRUpIdTR2MGdSaTZCeERDUU5NUS1NNFZQUGdfQUVyOWV2aEFnQlRseUZtbFdDX1A0Vm1ONzJmYV9sdjBnSldsZERGQWdpOHFaaGhRUHdoamdUekRvR2ZqNzRDOFZiZE5KbXgyMm5DSW5fQVhiUi1PV0hsM200TnVVeEdZblVZcDNKczRoTF84UVFqNFJlWHppajVnSWJVYXhTTWx4UTFhRmVLLVVJaXFuQVJDcC12TW1TNm16V3N6TGJRUzVEN0RXSnl5N2JuRmtFLVljblYzTlJCTEFaei1ndU5DX1Z1bkpwVGxuSVJ5bzIzaERIZkNQeDROM0lLVWMyTWlxUDdTNW1vT09HMjZUb0Y3LUJBZktzT2ttMl84UGNudU51VWhmRWpxYzN3VUlZU2c1TmlyZzlUSVlOQks1YVNhSEFjS1AwcXdENW0tMkt0T2lEMkJ0RmhrelJPdm9fUnF6SnAtR21kajFwdFRyQlIwcy1KdU9rY1lud3VJcW9RRFBhVy16WDJXTzRjX3pDMDR2YlZjcDRGdXFoZzhaTVNiQWFkQldQWFZlNENGU1A1R2RfVkJvVFU5V3RLRkdEOXViLVNLQkNfbXRZcVVfRDN6SUpxTFJmUm5mT1JoT2RoemdJNVFpMlAxTVlISjdFenF6NHhNSzlzZVU5OEdtZkM5cUwteEZhRW9RTlVCajBUaHp1dVUwNkxUbENYZXh0OWNtVXRhYnVFZGwzQXE5RnhQVXJwRWxwWGhoLTQ1N2gzQk1Bal94Nmk1a0RBUV85X1EzZVEtay05Y3dPQmRrRUcwNk5xX0NhNFFyNUFTRTZvcXVEazBVMHBjcERHa2ltTUM1MVZ5N1lzNWlqQk42cTFKVzNzYU8yN1ZUV19LSC01YWFQQUw1ZmVBZ2lXeW56T0l5V3pEX1BwWm40SHNGaFNwU1RKcVViYXI3amZIRERNaUN6bUhybFVJQWF3QW10blhsS0drWF9RMDhjeEN0Ni1YMDlCd0poQk5JMDJkTXpWZDFPQzhPVUo1VFEtX28zTzgwZmNIeml6UDhENk1GS1R1SDFfcjgwczlBX1IybVRObGdFaTY4T19fdFVqZUdQNWZqd0JlbWJjSGc1aEREdDBDaVBMZmZMUm1iQ1dtT2JJR0xMNFlLazNrWEh3ejQ3MlpjZFRCZndGT0dDT1BzUXcyc1hMcDhtNE5TeWpIeTlTSzN6a2tNdHE2cVJ5YWQ0dHpnaTVoTmJJLWpYRUdLWmZGWWFDSkxXQUJGbzljSU5hb2VhU2lFbTdXeDNkWEV3R0QtNmZQU0JVRzVLVl84QTZmU1R2WVVkMU5QSmRuSkgyY1lUOTFIekk2cjAwQUpOcFg4NWtfbG8yZlJKVkNSUE1UVkVZb1JqSWtBUURQVDdDMlI1Y1pxcDhneURod2JGc1pzUlhTWGp3RkgxOU1Kd2lsaHFNNnQzNW1FU3o2Zy1aeldMQzJrNDZBSkd2eTUzajJwYzQwbTVXRGpxdVBzQjh6RUt6bGlobHpFbWtTdzlIT2VJNjJPM050RDFBQTVSTnFNYkdVeVhUN09KWEFIRWZrOV8wOHRkOUJoMkhQaUVxOVVZSERsWW10WjdUbjkxV3NpelZYNEZxeFpzMjR4OE9XQ2VJTm9PZFRDZHFocGNxRVQ4aldYYmZvX0Z2Mkl0UEljMndSSWVqekZ4X2h2bjBVbVc3UTRFSWRTdnNJelI1ZnQ4ZHJzUUZHN3ZQZTRfQlhCOEw0cmtQY2JGUGVWU29XejdvcnhxWWc5bGJlWEVRR2s3dzN3OG9FTU1rZ0VPVnk1eVdvREFQY2xldTk3VmVKdFJlRUkzclBKNE9jUFh2bnRVUG4zSDFsSjBnUzQxT1dwckVMRWFWTl9ocVpsaXdkRUpJTXAtNTdydGN5SVk4N19McU1rUEFDVkJtX2dtZ2V4MVZkTlhkYzU1OUlvWVljd0NDUlBERWVpRXVSLWcxMWtTRHFJZ3lRaHE1OWRDSmpRN2JCSTV5andfMG5PNkpYRjU5eWRWcURfU1ZEb2xkazNpa09VcEYwUTRrZkZKYlYxY29wQl9DRFJKM3pXRE5ScENhVEZxbEVGc3dMWEtRSFliTUwyOThKR3dIWW5FX0N0dWtrU1Q0YU9kbnBkcGVfTGhhLWJvUVQwQ2RKMUhhZHJOb21uWlhER3VxckZQcWVBRGkyOTJHZzRLZGxEV2MwVkh1RGtrSGREYkRtaWd2RXhhVjVEQlFhd05zcFJxaUhIa0R0cDFZRmVlT2FwdTRFM3o2WkhkYzFNUWpFRWlGYjczSmNNQVVTMGlwS1VLV0NhS1B3ZE51dU95ZUF0Q0o0dnpicmczTFdSaWJaVjRzc0pqZElRYjZneFpMOHZteTUtMUFiZ0czekpJSUNvSElJM3ZqWWxEVXk1UVRqMkhoaEp3TnFYR1hxTmNaM1ptMGRoMlRzSTJseHZEVDVVRlBzeG9ab2F6dXZIUW1uSjR0ZXlma1hNalNFMEgyRGF0YVhiS1pndGJTaEY3Q0tpYjRwdXN1SHpyMFllOTI1MDdPaHk5Rzg2WENSUWxkb2xlVkhVMEczWUVhQ1AxeWhjRG9qbmg4ZVBFSlFwdFhpRGxBU3hXSFFiY1FNOUE5dWs3ZmNRVEFLZ1hsYTdjR3JFamwwODJENWtWWmhROTV2dVpXTEtDN2lqZlE3dGVnX09WOHNzel9pSGxlSHpiV1o3SGhWaGM2YmZLMW9GUGdCS0dESmlmTk1fZ040QkVQRjFSaTR0ajh3cGdLbzIyaWpieG5faXhac2pUUDU4TTRmSXEyWmFweWFSVkpoQ3NKTkRWWlFabnRKTGVsVVNVWmxrZktPOURfdjNXcVZwZ2RhbngxVHZ5M1BCUWhlU1RzVXE3Yk0xdXJhMEdEbXN4dFZVdnBncW5HTWtuNHRoZUlNRm1ndWJoTmlXUFd2ZlJNNUpDM2hBVjJXb28zRGpvS1lISkVrMFA1MnBqOUVuVEVXZWlTcWZHcklqUndjZml2RXFRNHk2ZkRfSFZaSUx2RzhxMl9IemoyWXVPVHN1dWFPNExnZkZCeUNXN29kemZNejJDeDVVeHdXUEZPYm9LcF9INVdUUTFfRTFDQjB4bHIxRGVFSElwS0ZLUVowakZIQ0IwWGtsLUc0OE9tYTRXS1dZcW5JSV9LaGdBRkY5Y0NUQ1dQZlNwTUtGWS1MRXN3R18xN2hxOEswYXNoTzZZbFR1TkNNczlpZEdCRnZyZEd6THhoUGVldDI1bVlPSDRLZUs3WkZPeUh5RnY3YWVSVmlESkQ2dW8zbHV4TXM5UV9NTkF4WnZ5SUZhMG4yQ0V3eUwxVTlQcGhhNm9UMW4zZHFsbDhSVFVLaGZDZXRQZWtaQVJfT20ybDhRMWFVY0tHV2RaN3d2Xzd5SXVCWEpHbTdieDgwVnpxTDYxMVN3OE5FdFh1cVprLUVkRGlvMEx0SU1kNDZ3MWpTQ0l6QTFueUdtSklrTjktZWF3czlkNy1Uc3FUcHpQQTV5WS1KRkl3c2NXcEozcE5ma1d5RDFKaDV2cldvcEE4THRJaWJNdHlEU2ZnZ1FZckNvQWNWSmdGcmRzUWJ4Z2x5UXpablVNVEZKV2IwYjZnWnRqNHh4cndlb3lEV25zMmRlMWVqMDV5QUl1c3E4MVZXTU5fc0pDZG5NOGpOUWxSMzhPcnhXaVU3SDBVT3N2ejZPTG1WMmUwSzN6RmRKbUItWVk0eDdmd3hGaDVMREQ2Y2VteDA3UndQSzhxSzJGem5VNmx1eEVrTkpIRHNKSDZmdENxb19BaGgxQ2I2a0tmUGhkc1BYSTZxUlJIM2psOGJKMkVDRkhiVHpDTHUtM2RVQTJjQXo0amd3Ynpfd2ZQZWItNG9wR0xTVHpMVU5RYVhibkFaLTkwZnpNTmM2SUY5MFNVeHRXY190bFFPUzhxclBvcFVRSF9ObV9wR0sxT0VmRkg0U2J3SVFVY2xrQnZQUXh1VEs2TS1QZFh2QVFpQUZTWlEyTVVlSmZkRk56LXNyaTJUWV9yY01KQU02cTVOVEdPMS1INEV4SEZVTmRZYUt5RWkyNEJ2Z1pRTEtBREtBLV9uRElqNE93ME4zOGFnZ0ZFX0VIUDZ3bXNPWXFXQ09VLVlSb2dyT2VXREhlenBwaGIxeklPVVF0SmxHdHhlREZEdTRmNjc2bVUtM2hhcmlBRzNtV2ZYUUJ3RDB3dzhnc2ZZWXNkdUduUWpEdUgwZjlYRGZlVHhHbi02T0RxVG9mcHFGMl82ZVZOM0pUR3hieXFLMkpWVGo3YU04Mi1WMVJ3RG1iZV85N05uM0lfSzZGbmpCclJzZEowNklJcF9vdW5aUVVVT1pEbXdyRXZKN0dxWXRYYktubnlYTVdYcHI4UmRaUjItVWphWXBFNDZjRmRFM0ZhTTk0ZnRDS3Ezd1BTMXZFbU1KVnUzLUZSTVMtc3VKZDZCTlFPWUEzTjU4VHF6c1NIWEk4Nm1FOXA4dW5zazZMSHN1OXFxMHVMS1UwS2xDTTZWZFd1b0pfMy1yMk1ELVZHc2VoWFZ0VzdwTmE3SzF4bWVDcjVnNEFXX0tWaGJLMy1nWUY1RWNQd3JLR2ttNktYMkx0emZOSWZtcEhHN2djaFFGbm9KeEZwclZQejR2b1lwbDRTUTlKaHhCOXFJbUhWVll6WTI1dm1UdnpZd3FDRnUxYnZDN0VrTE9fNzZTemc2OUdLeHc5QThlSmFucHBydDVjMzE0YjB5Z1FVSUtXdWV2YVJXcFVhTEI0Ml9wSXJBcWQxV1VZSk5idy04MzZoM1QxZkdhR1pqUDduX1BHRDlpVzB5TUlXMHBGdmdfTXVoajN1N1ZHUTZ2aEEzZEo2MHB2ZEZIOWUzVmNMdktFcC1hYXl3ZUdlaHBKTVJiUkc1amhOaC1DODdOMzZNUzBaWVIwX1F2YjQ0ZnVyekVoRXdRcUN0M1k2a2xSb05tS2x5LW9rZmtRTWgxWG9xc1dLMUJxSTEyZjl4N1ZOSnFPV0VxWkRNYlNPcmlCb1g4a3prY0VaWHh0YUpDeEVFZkhxZWZkcldiN3RLWldvaXFiei1mSUVCazk2N0s4OHJSQ3V5TnhRR1BXcnNuTEtrTnNVdnhKOWhzckdNZFVoendUX2d2OV9iUllGVXN6ZXdweHA2QXdJNEpac041Z1RScWRvRkhaZnVUb3FIZ1NlODQ4TFUtelRJV245Y3ROWUtWb1Z4VWNEdzBiZHdSdXRUdmk0R2RvY0JiMTlqRXRzeWR5Y1VyclZWVXY1UTc3UjVRVi1tSFFtSTZ1VmRGR0JHUUdiM0Nkakw2YUNRTG5GVEl3U25LalN0N0pSLXAtb3Q4WFFvNDVRR1dGZEJSMkZXT2FmZGZkSkJ4Qno5MExmZjJrczZ4bXhfVmx2b3ptV0JFMi1zV2hLbXFONVRrZ1JnMXNNWFhZTWpBUEsxMENoR2doanVLLWxydndvOWYuYVFLYzIzRDR0TUlkZUhoVklVQ3FqZw\"\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultbackupsecret.json",
    "content": "{\n\t\"value\": \"KUF6dXJlS2V5VmF1bHRTZWNyZXRCYWNrdXBWMS5taWNyb3NvZnQuY29tZXlKcmFXUWlPaUppTTJJd1pqZ3dZeTB5Wkdaa0xUUmlPVGt0T0RVeE1TMWpZVGRrTTJKbFlURTVNMkVpTENKaGJHY2lPaUpTVTBFdFQwRkZVQ0lzSW1WdVl5STZJa0V4TWpoRFFrTXRTRk15TlRZaWZRLlFLelA2anZVR0Y5X1M3UU8tRkZDTHIyNGp0RXJuandkQThNZUtsSGE1MmhvS01rNjdiOHQyckZhNTJ6dGR2and1d1I3VWh4RldRLUpuOHk3YlJiNlYtcTlUYl9iV3E5clplUlhpUy1jdUhPak9ONHB1bHd1cVVmQkJOU2V3NlJGUXpOUzRrQks3RmxQSGZpQVRRaUUtLTc1cnZIM0dMTEdDd25KTkxIUDNTR0FtWlR1dXo0bTN6X1owR3RsZUU5XzFZT3pqczU1UmJFNEdOTC0tWDhDWnlRWmVFNGdGRXZ2WmFrYkRXTk5hOWd6SnBUNlNOTm5tcGtpMFZocGxaNGdzWmNmR29xQktZNF8wTS1WTmpIbkZ5QUlySXdsSTNjZkIzWUVCbHJ3X1A1QXhQVFFvNDJNa1pETmNKYjFwaGh0c1phaTNLcWRxT0E0ZEVWNVZWQ1VNZy5fTkN5eTNJSS1VV1VtWDB4UXhTVnNRLjJkbEFpUEpSa3NlenNVTEZocTE3ZmdCWm11XzBBaU5GUWkyTU8zMnlVanpEMjMxQlY0bHhwU21ZMmI1bGdsTXlYQzNtYy1PT2VmcVNseXdqMlcwTllOYzJKOUg4MzFHc0VCdXZ1SS1BWEQ3dzdocGRNTG5VaG5DQ0RUQTJYY0ZTZ2lXTWMzMFFISHUzRi1KcDh2VGU1QUk5R1ljelEzSFVPRjJOREpjRERoLU9CNFFJRlZWMS0zWEJkeS1uOWR5MjlSY0FwNEo4WHRPMjZxN2dJa3BDT1JxMTVuOXZHd3ViVlZhdGhfMlZwM3p1ZEJPX3k5SlFTVVYxMW1jZFVIQXNCVGxFMU5xYkZaU0lfX093NTl6ZktGRTVTMnZrYWl6a1RFbXFVQi1EcTVnMnMxQ05PcUdUNk1wQWNiSEtUNTNSajNZN2RlOFlBckZIMlNSZF9udUV6Q09PMnAxeFpFUjh4c2RIRjlDM1Nnc3ZRQzIzX3BfeDBIR1RfbWY5V3B4amZOWF9Bd1E5NWNLZ0JOdU1ENEZ1TTdWTmpKc1JaSGtvM2tNTlJ5N3BybkhhaVd5aHRiVV9ic0w3X3FRa1JGNEl3eGFzUlh6M3RtZzYyT2tCWl82MEMyRE11Q0pIZWtqSnI5SGJDeGp6Z1lGMjVmRDhDTk00YmNaRV9ma1Z4Y2lVVklWU2lvemREX3owTFBMY09paVp6dTNIWGIxekplZkJsVXduc1NBT0RZa2lWbjJPMjFOMHpkRGwwMjNPSnJTdWQycWo1UkEtVTlsVWRxU0w1QUltN1ZaMTFSVzh5clpkWXc4NFJTejVySldRSm1sVW54RzJHb3lMMTFaQkJacXY5bEJ5Wnd3SDN6ZGNDZWFRQWM0LVZJWjQ5NzBfTC1tT2paNUFwdXI4UERHVDIydkNKdEw1cVVaNGJabThBeXQ0NDFEX2o2cG16NzRUWWlIU210ZnlJcnNvRTMzbG9QM0xGdTFKMklXLXJTdk9HUElveEx1ai1ZMkNKMENYTk1lR0UyQVNhOEY5RmY3enhVLVRkbVZneWpfYi1EY05XUmVJZUMyTEF4OV9EWDY0QlRJV0pNSFc3a2plbjRkem9kajMzbjM1aFU0UUVmRVM0a2pmUUtMVENrYnRlWXliVUlQWmhaa3BDRzRpTVBQSVpTRVdqU2RMckl6NlRYN3FJZHFHcE1UYk9zeld3eWc2dzI1WTd4aDFvelY2RjJEOFpKR3FiZjhQZTVDRWtIcE5LeC1kNExUTzNsOWZlZVd6RFRwTzRnTWpBZ1RNdHBqdXRqT2xhSEYyN1JLaVNGWU82eFNQY0ZVb3JGMlZKRERlQUxZSk9Pb0JOMkhpalJ1Y0R5bWR3NUtzNHBZTmZvV3dCeHVnbjBPenJoNVFIS2Q3dWpoUll1XzhkLWd2RVNKQzNJY3JZWFI1aFhxaUp5WGVNMGtULWlnRUFQRFVmSXE0cjJiRW5iZ0RhdUZrN2syekZzXzZzeGZ4Ty1TNEp0alp2UkJia0lnZm1WdVB5OXZTQy02QUl0aEctMW5OUE9PNG1oak9ON2EzVUdzQVpvREg0T1RFczA3ajJMQ092VGdqX05PN1pJcEt6LWhyU0daSXdCdjlRdHJ5NjY4US1kTUpRZzAzRi1UXzZlX1htc1BWRWt1RWdaSzdnS092STNzdjk4Y0VVODFiVEZfNjQ3cmE5bjN6NHdnbmZwVE1lWEhMQ1JWeGpKbHJURmxJcW9wbkdZeHlQdm5iVXBzb3A2NktHbVAtTEpTeERjNlJJckpuQ2drbjN1OGN0c25NZWxuWHZSeGZFdFRsNnkyendUV3ZSdnVEcVR1UFphQXdNVmllbTdaaXZqNTdMYjNHT3RUcjBxQXNrMC15dHN2TkpmY19tYTEydVlUWll1b2RCM2ZoVFBITjFaclFoQzdiWDVHdXFDUFFDQXFuenJjT0lESDIweTFlZHAxam1ZdTFyZThPaG9yMDRiVWhLa2stcUVVdEVsZTFqYzFTckNuWkEyMlRZMFNVYkxkVm1hb2dyaUJfckpackVaM0tneGFaSjNnZ3FQd2NhSW0wNUVoMDQwYUpUa20xOWdzRzVCNEExQ2dDWHRMOGhUMFl4TmNneW9tT0dnRzd2Q2FzdW43WGhtdjJZLWROWVNrZzRZbzlfdkktWWlmZEp2MnhJVWY3eGFvS1RRRzY4NkNzaE0zTkVubFRWb1FjaWxjaXllaHc3RkpiMnYyTDFNV0tlamRWM2dPNjIyVjZ3QXV4MW9GdXJhdWZORzh2cnkyS2NwczFOUzBWeFJObU9mNDFkbFRhSkljUmFJM2tSbUg5UkpTakJZcnA1Y1ZzZWh5WGVaQXpnU2JzUlg0eGp6LURJSGVPa1dRS05HMlZvTnloZ3BZS05FVnlNN2dkdFBWTUo3TmlkVE9PM3BaYTBMeV9GaUhHLXc0dkUwTTR0X1ZpOFhvRzBFbWhJcjBWdmRvN0RGUXVUbmdoblRGVnpreEtyRlJSZzRMWkhCNzR2Z1BycTVTNGxTV2hlZGRfekRad2JVeUxJY1NXWmk3QzlpWDctczNHeGp2UjNGekxJT3NuSXUxVHpaQ3B4a0d4ZGkzU1VyS1c0NGlTaDM3eGNmaEpsNDVDcTQ5N1pQQmo1eVA0UmYwazVTS3djM1JvOUJoUXN0aUdzVk5qMlIzcmpHTHZfOEwtUHNxOG1IYTZKZHVvaEtRbEVQT1hYNzZ5aDdab05KUUZhemRNRWV3eVJNOGQ3eUZIcFc0M3RTZTA4Mi1BUmRjcW55OXFZRmJLMFJfV3dNTDlOQkFpNWxjQldUSms2ZHJXN1RPRmJ2eDFyZ0p5cUcza2w4TEdwRExheFNfaFhXZVRxSy1YS3pVRk9zNjA4WEp6U2NhVE1xay1QTVZIdkN5c3Vjci1mOFN3SF9wdks0bTNQYWprcGVOMjl3dmVZdUp1X1ZKZHlPNE9yY043cnRYVXR3VWNSblBzNUNXYWF0N1RfUWhnZ1VTdHBZczBJTlVuNXU2Rm5oNGVsUUxTTEhvdWZDdE9RekpDV0VVd3N2TWdkdkc2cEUzU2FZU244OFd6YzdMbGctZEVMeERLQXE1dmI1bXFleXAyem9hZFhJa20wWks5amlwdnBZdmQyRlFnNE50NF9nOUo3WTRoeVp3TjFWdXlqQ2YyUkFpMzJXZlNid1B4ZmdVdjhVVkktcUlKWjc5TjNQOTFnWnB4X2xxdF9aNFB0bzIwTTZqamw0MGkwUXRwMUdaRU5hbHoxN00zbFRBUl81WkY5Ql81dTIwN1FGbGh3UDYzbFRNMF8td1lCOVBzV2VtdGJUTEZYZmJFU0t6VGVzckVzQWwzQkVDMFotSndhMno3cEc3VHhvQWhON21hWDdKajVjbWtzdmJjVk05MENSNTVwbmtwOUM0Tm1BRWM2amw1dXRBSGlGOEdaV1A1V2lGVFFwVTBpYktXLUVycEMyblVvRVBmbFRPbVowM2lzaFNLbnZTSUFUQjBMSW95S1lhYm9tcU5NWkZhWDV5OWVjTGtFdmlmYS04dW8zRzNYSWFhQWk3TE5YRXpqQm9iZWlVSzBFeGJxaGd0VzNvbE85V1o1MGxqOWw5UXpGV3FWOGRiUThOeTdkdzRnT2wzNl93ZVNrbHJ3b19VVDA0Sm9Oc0IzOWFrUnJaWkdzaXJuamR1T0F4RWZaaXRLdHdTdkpZSzRtV0huSk5uRENMVlo2cVpzVG50NThjVjQ2cFY3T1FxckNpVnlQREU3Y1N0RW5neXhEbzRZdlpibDNrNndkaGxYOXAwZXNaOUdXbHNxcXlGVUJCc19QbVN2UUd6djZ3bDlWSnk4WnNKYmpIdlkwclZOUFJnN2FYTjlNOElsVWpia3B6RmdqY0VPZVVrZ1M5UFp5RURLYUw5U2NjeFJFbjI1OUR3MDFJZFJPS2U5Mnp3U1hSQUJlbVhBcVRaSGZPd1Z2VDBUS2JnWkwxcE5vb242NWRMR0hKZ2dYWmt6SjVHT3dvbFRkYkEwczVkaXRQZllxU3ZwQmpmVHpfQTZhTWl3bmFnamlET0QzT2doeTQxc1Q2UDdTWTFxanpfWkxjZ1puc1djWDlkOWc4TkpzZ1had184d2dUY3hRdW1TM3oxVTYxX2dlbndBNzNPaEs5MWl5YW90Z2ZySWNzOWxodm1taEcwRC1KX3lkQUxfdXNROWc0dHRlN1ptN0hMZDZOb1pCYnJFTkZ0ODRmejdJbjJxMXItM1lsYk9kMm1xRXIxZUdZMmtCTlh1eFc0XzlVZVFOZER5UHZPRFR0Ni1mR3FuMF9sd2dYOXJldUxsRzY1UjFKY29yMnczWmZBLWU3SEN3Y2tCTTBEcmhjZmwxdmhtcVY4WXpMcHBxUUhPa1F2YUpMNHE2ZG1ZS0thZmhGbXcxVk1qSnp5UWswUVNzazFWUGdzUmpta3l0YmpjZjRoenJNdVRMU0VQTGZVWGVPOEYzbEdLNE03bWlhblRPQ0xXSmRNWnc5dFlKSHVTQ0g3SjhZOUVwNS1XWTRBeUZlaFJfaDVSNHVYdlBPUmUzSzZQcWJibHlaMEJuclpCcDZnTUNvNVcwZkd5ZEdiQ1N6dzUzVndsY3FEWnJlb0p0Rk5pZFNzdTBtLUFub1g0SWxsSFFnYVB4SnlLYWRPSWpvalNKMnZTTTZCYXRkci1pR3VTbDJSZmswLXkyX3FFeDZRakNOQWFXaWNvM2RsS3VIY0h6TU13YzVXT1J4bzdweXdWYmtOUmpoOUVPZlkxSW51Tk11SjdfYWt2T0V5MGpMVXlCc04zR0hrTzlEUExFLTk2bVlIMWd6R19IbGQ5aVRpOWcxZTB5WjdBVkNEQzBoaVRZMXB5V0pVanpGVE91clJaYW5qOWl5MWdjcFdpeFVPN2xiWjl2aHFhdHg0VUh4VFRneS1IbUcydmRTYjhJbGl2bHNqLXVpM3dxUjBYeVNXRDFVYmVJUFVIZk15bTR2bXkzdkIyWEJKMEJnTF80bkx2VWQ2MEpFdXI1Z0ZOSUUtR0RSY0JwSkdPZXN4b1lyQktYU1I2QUd1UG84b2ptemFudUFIaF83OTI5OWg2aDdtN3JRZ0NxYzJ0Wjg1dU9YVHNzZzRYSW1kVjdCN3ZrcHRlUmt5WjZEQ1RFYW5GRmNvWEJzSThYMVFZeFFDRzgtdzltYlppTHNiRGN6bVV5Z3RiRkNQUXludjByclNiRzFUUWtmZnk4UGVfT0tRYkxSdWJNNG55dmZxWG81X21FcXA0T1dzMlJSMDhiSE9YTWpDU0FlYUwyaC1RRjg2MmRrLUNpV05ZSVVuUHhTYWkyWTEzeGVqVklwYkI1YkZzaVUzTWJmY2pyNnduRUVuMmhzWGx1aGpWVXFtUzNIOEZwZDFkS0pSa1lzM2NWZWRHTEhaRFZRM0hTWHlBWk1FbXNzX01kTUlGMFZhUjU0WTU3QXhhcnR5QUFmZy1OWWtkNVhtVkxPQWJnRFdCMzdrbEVPVEZCYXV4SGg4dXJjVk9neVF6Z1RNcTIwTWpEUzhzaDlZLUNHNUxSRHJiYVlRU2ZoR0VSYVFYcFpuVEdWX20tcDFpWU1zMEMzRFBJanMxSWIxZVR4X0lJbTFPRlBGOWcwWVJsbXFCdkx2bGtGeExqM0t2SGxQVEUwaUYyZ1JaMmN4NUMtckJGZ0dXaU1hRUQzdjcxTW0xQlFJeklaY1lfUUI5V3FsWEVaSmJWZHNZc0FmNm93eW9XckpVQUszTEswclRPaEdNS2VaUzlzUGxvZWU4T0x2OTluc2wxRUM0Z3F2MHJqdk9JQ0pVR0kwb1R1dXV5enhSbU41cHJtX2VycHNLbkM3QmRXV3VaLXRab0g0c2ZDeExiYVppeW8tQU1xdVRhMzB0ckFOV21rSUtuTHFubFRvcXJXZ1JiQjF3Q0hlVjA4WXR1ak9sQUdKc0dHRTRLVjc0X2QwSXZ2NXA3RUxQZlJJcU51cGVLdlpTZ0pxU19tQmU0eG5wTFZsWDhmaHRIOE9aSUxKQ25ZQUt5VHZyNGFoZG9jd0NrOE9JX0xVOG5wQ1Rpc1VFdEo1MXpON2dqUEs2eGhCazZ1YnNNeE9oalhNSjhUd01sWHZvMjcwSXdYV08wVm1lN3pGbnp2S3dnWjV0UlB4c1hwTjlySDBlLUxIZU9uNHIzWWtHeHlpRDFrMkUyM0s4ay02RmxhM2JwMV9DQktfdkM0VUhBU3NqQnJjd21kOHVvYzdJTDRsQmRfeldQbEtyUXp6bmxyZVlMV2w3S1RmdG5ELXF0STlLMlFpWm9Ib3E4anZSYUJTTjZqUTk3RXhEb0E5dUk1LVRFc21UYlpCV3pGemdoOS1mbXBKZmQ1R3VNUXVhblJDN2VPbzh4bkJrVnI2UVVnZjVhYzV6Um0zc1ZBaktBVDJ5djc0dTNyOEJjUEJMcTBsc1gwTUpza3FlNEZhN193NXB5Q0Y4dS1RbVFkN2dmeUdPSW1OdTgySGJPSk5yMHg4Vm9NZU9uUExsVUhyY2cxNk43czY5ekU3SEM2UExpcHJobHdmY2JvMXlaZDZYVUxYNGI5MXJ4ME5SU0VpYURISGV1QS1LNWFQb1F6VVZiSFJ0cExvdHpwTEFTZkhwMWFhSEoyakRQUElfcVllbzkwWjVrR3RiV2plSTBYVDlzMy1TMk5pcW16Z2Q5WEMxNEJaUTM0UWpNdksyNUpJYXpqWW5FdGQzYUFYRWFZNU9CdGZ5R2NIcV96UmRaZlVQdDdDNk1LTFdRbnpzTXNWZHJ4cnpCcWRMMVV0NzlIQnZ5M3RlWDZ0RmJuYjR2ZkgxY3NZUl82a041T205VndHelRZYWNGM1dDTkNuOHljMk13N1Y4b25ZOXFLU0VLS1hRYk5KYlB1cEJsT29qLV9tV1drTkdmSy1TUHJoRmFGNF9LaDFTd25TelBydHRVVU9WMXg4ejNmUVFXZml5eVllcGd0VHVGSEZheHE0YXNCUjRQVndfUnBJN3c4QTNiSGR5ODQteWprZU0wU0k4WE5CdkRmVThRXzA2aVZjWkg1UWhwU2VENVpZNWotcDNzN3c4X2MtRXo3RHRZaHgyQzducWU2OFNVYmt3dmd4d2RUOFhaYzcySTJwSUFwYklPTzN0SEFIVmpvVHdVX3dsSHctSVZKbzZfSlBvRE5JbEdZcHdDZ21oMV9rb2FCLXFvMGdQd0UyeG1sRmdNeVVCd3lfWHNEdVRUcVJfT3pYVHBQbWdhTWNZMXJldEgzVjBDZ3BHaTBqYVZoN2NJSUpoVWNRcXRIVHl6S1hDTWVMRVBXYzJuVV9oXzB5U0tTanJMUmR1cHpkMTZ6V2sxdTRzdDRDak9CR1AxbloxVU14X3lGQ3ZsVVlESGY5OHhBelJNbUg0c1YxMnVMYmlCS2l0eTEwSG83X2N6T0htQ09LeE1oaFlhRmVrS19veUU3X3pWbTRjUzhHbEJiMUo2UVZMeHpGMXlORnlqeHdITEtnNURXUzN1T0JfSGpNdHlMOHh4WXhNR2FjNTh1X2g5ZEM5QThtVGJ5bEF6Wll6eTUtU3pvSVJYZHhVOGtBN1c0QzFWYmI1VGgyVHZmemF1Vk1mNVg0SWc1WTU4NzMtd3oxNVpHZW5xU3JreFVqU0tVUWVlZkI2eEg1aGtKeWs1cDZWY1JJNzF6SkVEVEU2LWZHSGsxTlNRd2QtS2tTaWlwMjI2d0JCOHZSVWdGQ1VZcy1EZC10TXF1aDdKZjlaRTU5amNzR0ZkTDJhamFRcjc4Z21VZEFVYS1HRHpQeHp3YkM0b1FKS29ObkNEZGc5WV94S3NHeEtDWnRVT1VjM0Z4MlptZFpfM292ZGExaHdyVDZpYVJLM0MxZnh0ZVpheE9IWkNvdW5MeU8wZUkzZ1Nnd2dkVERxODZ3TzY2U3pHdGRxYmo0bGZrT3NkRUYtUDNhQU1yOGNuclh3b2NOdGVpaVJ0YnVqLXhfNlVQUk5hWHJCV0lHRk1Mc2x3b1VlRXE1ZUpuOUhSYmdvd25vU3psOUdDWWdtdnRsb1ZIVHFVLXpNWk9TcmxPejA2aU1ZZjBjakliUDJtdHUyWHlDS3dkRnFsZHJqUWs3VmNUUEJkczluRjR2Z3lmOU1nSFVTeVpHTHFubHNtdG5ER1p4VTN0UmR1eXZfTFRLcDgxYVVQVVprb0EtTkMzdEFncHdQbUtodzVnY3M4U19aSC16VVNFd1BjLVR6NGtJSzhrSFVxQ2ZFY0pfMmhpX2RTWHRKbFB3TG9EeU95R1hTWkp5ZGIzb2hjblk3Z3RneGpQaU82Vmlwd1NZMXRVVUV1YmFKbHkzTGFwRjN0cXlEZXBBdHMxc2JDdzNSSm1HcE92WjlfaTk5SXZ6WjY1WDZPSDB1YUpDTWl6bFpzdGQwZ1FRMXl2ZTNQRDRaVHZPdzlMMm9Na0ZDQlFvQzBUalU5b0tPTHNpdlAzbTZOWjROLVpiaWFaNTIxbWU1ZjBWV1loRkN3RENxajRyUDZ5WmloOXVPTW5rWnNhZ3BtS0RlaVV6d1RpaENKdlRkZnBfbG1GQ3cyc0Jyd0lIVWJfdkxWY1RWNDd4NVNwSnhuS2dpWHpZUG8weElnYnY1bmZGWTJvM1NBWkZpSlNlNEJQbmFsX2FQLUFnNDdWM2h5NmNzT0xCM3l0VlNCRDdlNjFpU1VGWVhBUmZJVEVXa0VRaHBIWWJyRTlvemdldzdOLU5HaXdtWndOUy04SUFSbmRFS0tXSXRXb01fMllXVmYxS1ZoME8xQ2wwR0ZDV2NCNzFDLWxMazVJbkpKUm5Wd2dPQ1M2YUFKaEM2T2pIVVYydTR3TTdndFI1c1Y2Snk1NUxQcjFUbVpZQXAyVFNSMG0zUWMyN0ZKRnhxaFU2R20tZGtVNXZKbGtnSjUwY2xTUVVGcVl4Z0pDX1hSdWVpOXNzdkNmbnZVOW1ZSEFQZTU2Q2dXNWFiVGhSOEJCcTc2aTlxUjBlRVV4eFVWUUtCemFhVlB3TmVqaFRVYnpWcHZnNGlqSFRocFBlRzdDZ3hwQ00zT0pCaHFnS2k3RzVTeHFHYjdNVEhoclp2Q3I2WHZtZGdFc3NxWW9RdUQyYUQ4TlhjdVU0Mm1NVGwyZS1sY2pwU1E5R29hdlRHSjFCeFp2YWlYZzRNS1FGUjBjRDQzYkxsaXo2Y2NCeEEwZnJTU2dqbUhRNERxdHhjYkFiNFlPTDFlYkFQNFNSQnJwa3hGQW5fc1l6ci1aR0F0R0l3R1JfUHRRbjVLQ05yaXBueDRITVBmS2UtTHg4MzBIWFNxVGV5c0hRbGtuRlRSeFdwLXdNcUxPMlFhTHJnMlUzdnBDekloRmh4dG1tWnpPSE8zZmY2YTAySk9BaDVDek9GcG9oTDFXakl5a1RMd0dNMDZMQ25uNmhGeDVOZEhmVTlqaTdKNGZuT2RkcVh2ZnZ4TDhSN0wtM1d6SThIUVI4TkRHRzl6ZGtHZDUyQVlkNTBqUTZPN29qNUdkZldGMDdQTVY3WWFETjhGc1YwT19wZDM5bFpiUnM0SlV1Y0xWMzBXNGpqVGdselZGeXBaZEFxQXU0d2pWTVd5T1I0X1RSMnh6YW0wemx0ZXc1bm01TUk4NTlZYVhCVE95bkV5T18yRndDR2hzdmxQR2t5SHZuc050NFVya3pjRGswX0JaYUlYYWFNbUhxMUJQUWdiR0d6bUxNV0FXcFY0OUszdnBkN250WHFBZEVyN25VUnVpS2RSckVTYnpEUnAxclh2NExOMUdGNXRnRUFCZFhwYTVQVG9nVDM3cHUwb1BNNW5FZXFDeklRbmtjemMzUVk5SEZwY1J6bWFmbV9fSngxRFd0ak5qR1J0cVM4aHVUcVNKOG5ORl90ZXZsV2dwOU5uZU9KSUZwZkVMMnhYMTc2dnkyQ1FONTBFRzZZWmM4dXZreHFNUmk3OFNjdENEeXQ0WS5Sc3FFM1dad19XclIxRmtQc1RtWW1B\"\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultcreate.json",
    "content": "{\n  \"id\": \"/subscriptions/3fee811e-11bf-4b5c-9c62-a2f28b517724/resourceGroups/rg-vaultapilivetest-jims/providers/Microsoft.KeyVault/vaults/kvvaultapilivetest\",\n  \"name\": \"kvvaultapilivetest\",\n  \"type\": \"Microsoft.KeyVault/vaults\",\n  \"location\": \"westeurope\",\n  \"tags\": {},\n  \"properties\": {\n    \"sku\": {\n      \"family\": \"A\",\n      \"name\": \"standard\"\n    },\n    \"tenantId\": \"72f988bf-86f1-41af-91ab-2d7cd011db47\",\n    \"accessPolicies\": [{\n      \"tenantId\": \"72f988bf-86f1-41af-91ab-2d7cd011db47\",\n      \"objectId\": \"5a7f4cb9-ce9d-4b31-87ce-f61083c4b0ea\",\n      \"permissions\": {\n        \"certificates\": [\"Get\", \"List\", \"Update\", \"Create\", \"Import\", \"Delete\", \"ManageContacts\", \"ManageIssuers\", \"GetIssuers\", \"ListIssuers\", \"SetIssuers\", \"DeleteIssuers\", \"Purge\", \"Recover\"],\n        \"keys\": [\"Get\", \"List\", \"Update\", \"Create\", \"Import\", \"Delete\", \"Recover\", \"Backup\", \"Restore\", \"Purge\"],\n        \"secrets\": [\"Get\", \"List\", \"Set\", \"Delete\", \"Recover\", \"Backup\", \"Restore\", \"Purge\"],\n        \"storage\": []\n      }\n    }],\n    \"enabledForDeployment\": false,\n    \"vaultUri\": \"https://kvvaultapilivetest.vault.azure.net\"\n  }\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultcreatecertificate.json",
    "content": "{\n\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/certificates/myCertificate/pending\",\n\t\"issuer\": {\n\t\t\"name\": \"Self\"\n\t},\n\t\"csr\": \"MIICszCCAZsCAQAwIzEhMB8GA1UEAxMYbXljZXJ0aWZpY2F0ZS5mb29iYXIuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArrIwtQO60BI1vUkS/Vx0TQ5dBLjWBFfQFUHABJoKXCeloLrHWrWnhaxyj5jvEVGYF5OLBNeHd6PR43bmHKnzq3vhQXUA1sKBRxAJavSM9a+MKBpN39aKvSnqRNdnETE8kwNteIpbmDVMe18UnGtyhRbMKqJ73HpGyyRdiD8nTS9F65SCRQlKALNz0Vi3z52Loo6kRoZPAfcRkDAbbg7JxIuMEEcbrBR0dScR0m2OucYtR3PQ7PUQMXSsLwZmGAu1e/KuqjTNC6XpxRpWSTHf3kS1Q4LjNXde8sk1/5Xovzo/MlVQ7L2tt4pVK79ZkeePbL9ZSKsTc3Thi7G+o8pCewIDAQABoEswSQYJKoZIhvcNAQkOMTwwOjAOBgNVHQ8BAf8EBAMCBaAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMAkGA1UdEwQCMAAwDQYJKoZIhvcNAQELBQADggEBABoDgWVU0DqfhKsujIa4gUHyZKvRWhms0reqb4Ld9GkF4O6TV+TxibBUZRW3SSVvA+po8G7aX+E+si0BfQiwM1PutcK0f5WuYMiEkQ6xaiDhIblrouCYRCTiYmmt2+8iuKAtDNqgqMJjViGXUKcGQgz7UTEJY/LLlgxW2kDyfEJOhGls40AT7tuXAjZ6QPLT9vAdQ8B0L0JNzJ6lJcDe7KattWonjQ4cLZ7xvY0SwUyvabui1UkOFze/EEkLwnJjigvfWkzhoJS7j0Cp3nI08c5zd/rQGq1XNVb9plnjtQP0kwNVQdHVeTug9rqZCyuS3jqwa1prrXkZJyufMmuNSV0=\",\n\t\"cancellation_requested\": false,\n\t\"status\": \"inProgress\",\n\t\"status_details\": \"Pending certificate created. Certificate request is in progress. This may take some time based on the issuer provider. Please check again later.\",\n\t\"request_id\": \"550fcfd2c33440aea6cd354658f91ddb\"\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultcreatecertificaterequestbody.json",
    "content": "{\n\t\"policy\": {\n\t\t\"id\": \"myCertificate\",\n\t\t\"issuer\": {\n\t\t\t\"name\": \"Self\"\n\t\t},\n\t\t\"key_props\": {\n\t\t\t\"exportable\": false,\n\t\t\t\"key_size\": 2048,\n\t\t\t\"kty\": \"RSA\",\n\t\t\t\"reuse_key\": false\n\t\t},\n\t\t\"lifetime_actions\": [],\n\t\t\"x509_props\": {\n\t\t\t\"ekus\": [],\n\t\t\t\"key_usage\": [],\n\t\t\t\"subject\": \"CN\\u003dmycertificate.foobar.com\",\n\t\t\t\"validity_months\": 12\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultcreatekey.json",
    "content": "{\n  \"key\": {\n    \"kid\": \"https://kvvaultapilivetest.vault.azure.net/keys/myKey/f5cfaa4b90a34710a646af83636a5c1b\",\n    \"kty\": \"RSA\",\n    \"key_ops\": [\"encrypt\", \"decrypt\", \"sign\", \"verify\", \"wrapKey\", \"unwrapKey\"],\n    \"n\": \"zattdXaoaTAnEDPv38dpgkLSuVp56_7TNczuyBGy3GOF62LgLEId1i7You5R4SGAXJDVDWBVAFIcbw3ppgbn-DgCf4QbAWWREQUOvPNhFvm78Ey6tewofP5jyrCDeSBkjlXC5lRgd8XtVXv0JvNtOU_GbTLMVAGOwPE-0nZWXaD__nkO90AS_2D1tDywcZ7vKix9WjkjYTmY1CEw06-vsQJSYSaaL2M5MmE-S21sgoGZUv7a0jHxDR2rEX3okFoW0sjynz6yxCZtYUmUyDMpWdTIaqKu9ZhfxZPtb6T9E8yAStvma0M5xc70gfOj1LJRK8mMhLmB4lh0POj-2a4fBw\",\n    \"e\": \"AQAB\"\n  },\n  \"attributes\": {\n    \"enabled\": true,\n    \"created\": 1509314506,\n    \"updated\": 1509314506,\n    \"recoveryLevel\": \"Purgeable\"\n  }\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultcreatekeyrequestbody.json",
    "content": "{\n  \"attributes\": {\n    \"enabled\": true\n  },\n  \"key_size\": 2048,\n  \"kty\": \"RSA\"\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultcreaterequestbody.json",
    "content": "{\n  \"location\": \"westeurope\",\n  \"properties\": {\n    \"tenantId\": \"myTenantId\",\n    \"sku\": {\n      \"location\": \"westeurope\",\n      \"name\": \"standard\",\n      \"family\": \"A\"\n    },\n    \"accessPolicies\": [{\n      \"objectId\": \"myIdentityObjectId\",\n      \"tenantId\": \"myTenantId\",\n      \"permissions\": {\n        \"certificates\": [\"Get\", \"List\", \"Update\", \"Create\", \"Import\", \"Delete\", \"ManageContacts\", \"ManageIssuers\", \"GetIssuers\", \"ListIssuers\", \"SetIssuers\", \"DeleteIssuers\", \"Purge\", \"Recover\"],\n        \"keys\": [\"Get\", \"List\", \"Update\", \"Create\", \"Import\", \"Delete\", \"Recover\", \"Backup\", \"Restore\", \"Purge\", \"Encrypt\", \"Decrypt\", \"Sign\", \"Verify\", \"WrapKey\", \"UnwrapKey\"],\n        \"secrets\": [\"Get\", \"List\", \"Set\", \"Delete\", \"Recover\", \"Backup\", \"Restore\", \"Purge\"],\n        \"storage\": []\n      }\n    }]\n  }\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultdeletecertificate.json",
    "content": "{\n\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/certificates/myCertificate/b73ba4610dc24dca946f76933f6590dd\",\n\t\"kid\": \"https://kvvaultapilivetest.vault.azure.net/keys/myCertificate/b73ba4610dc24dca946f76933f6590dd\",\n\t\"sid\": \"https://kvvaultapilivetest.vault.azure.net/secrets/myCertificate/b73ba4610dc24dca946f76933f6590dd\",\n\t\"x5t\": \"K7HXO6YIK6xwCX8W1InUKsJV9Rk\",\n\t\"cer\": \"MIIDTDCCAjSgAwIBAgIQVA+XomvgS56ybBWv2MnacjANBgkqhkiG9w0BAQsFADAjMSEwHwYDVQQDExhteWNlcnRpZmljYXRlLmZvb2Jhci5jb20wHhcNMTcxMDMwMDY0NDI3WhcNMTgxMDMwMDY1NDI3WjAjMSEwHwYDVQQDExhteWNlcnRpZmljYXRlLmZvb2Jhci5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCusjC1A7rQEjW9SRL9XHRNDl0EuNYEV9AVQcAEmgpcJ6WgusdataeFrHKPmO8RUZgXk4sE14d3o9HjduYcqfOre+FBdQDWwoFHEAlq9Iz1r4woGk3f1oq9KepE12cRMTyTA214iluYNUx7XxSca3KFFswqonvcekbLJF2IPydNL0XrlIJFCUoAs3PRWLfPnYuijqRGhk8B9xGQMBtuDsnEi4wQRxusFHR1JxHSbY65xi1Hc9Ds9RAxdKwvBmYYC7V78q6qNM0LpenFGlZJMd/eRLVDguM1d17yyTX/lei/Oj8yVVDsva23ilUrv1mR549sv1lIqxNzdOGLsb6jykJ7AgMBAAGjfDB6MA4GA1UdDwEB/wQEAwIFoDAJBgNVHRMEAjAAMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAfBgNVHSMEGDAWgBRnlX51KtyJ/m/V8I/3il4cAW/HOzAdBgNVHQ4EFgQUZ5V+dSrcif5v1fCP94peHAFvxzswDQYJKoZIhvcNAQELBQADggEBAAbSFuMRMbXyH80iA/jU7vuUCYe0Ra/wTTB1qVHTBuqQ/W8RI01mdqI9+GAPOTyN94XPPYVpSz9ZQ3P0/dhgcsahW5bZQkC0CcUSE5R7JUOKI5Up6n8zZM/unHlC6ZcEpNA/scObPKhQXdZayxgf2/p30bii4CiyS7ADEH92xMnzo1Eu9Dckxh1MRDypfxMY9YIzggksiY78BxoNsRDyxNjeRHVUxAIJ3n9TUv+WG31r7rMOIs6ZPsWc96AzUHHAZREVTEh2kiKKIenbMXn1tCpF6/GJKGfp7rt5ObUoQAlnn7kgAceteKZHEMgRZ4c4EQq+yqBw3hJrz4dOabJcmcU=\",\n\t\"attributes\": {\n\t\t\"enabled\": true,\n\t\t\"nbf\": 1509345867,\n\t\t\"exp\": 1540882467,\n\t\t\"created\": 1509346467,\n\t\t\"updated\": 1509346472,\n\t\t\"recoveryLevel\": \"Purgeable\"\n\t},\n\t\"tags\": {\n\t\t\"selfsigned\": \"true\"\n\t},\n\t\"policy\": {\n\t\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/certificates/myCertificate/policy\",\n\t\t\"key_props\": {\n\t\t\t\"exportable\": true,\n\t\t\t\"kty\": \"RSA\",\n\t\t\t\"key_size\": 3072,\n\t\t\t\"reuse_key\": false\n\t\t},\n\t\t\"secret_props\": {\n\t\t\t\"contentType\": \"application/x-pkcs12\"\n\t\t},\n\t\t\"x509_props\": {\n\t\t\t\"subject\": \"CN=mycertificate.foobar.com\",\n\t\t\t\"ekus\": [\"1.3.6.1.5.5.7.3.1\", \"1.3.6.1.5.5.7.3.2\"],\n\t\t\t\"key_usage\": [\"digitalSignature\", \"keyEncipherment\"],\n\t\t\t\"validity_months\": 12,\n\t\t\t\"basic_constraints\": {\n\t\t\t\t\"ca\": false\n\t\t\t}\n\t\t},\n\t\t\"lifetime_actions\": [{\n\t\t\t\"trigger\": {\n\t\t\t\t\"lifetime_percentage\": 80\n\t\t\t},\n\t\t\t\"action\": {\n\t\t\t\t\"action_type\": \"AutoRenew\"\n\t\t\t}\n\t\t}],\n\t\t\"issuer\": {\n\t\t\t\"name\": \"Self\"\n\t\t},\n\t\t\"attributes\": {\n\t\t\t\"enabled\": true,\n\t\t\t\"created\": 1509346452,\n\t\t\t\"updated\": 1509346474\n\t\t}\n\t},\n\t\"pending\": {\n\t\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/certificates/myCertificate/pending\"\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultdeletecertificatecontacts.json",
    "content": "{\n\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/certificates/contacts\",\n\t\"contacts\": [{\n\t\t\"email\": \"foo@bar.com\",\n\t\t\"name\": \"Foo bar\",\n\t\t\"phone\": \"867-5309\"\n\t}]\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultdeletecertificateissuer.json",
    "content": "{\n\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/certificates/issuers/globalsign01\",\n\t\"provider\": \"GlobalSign\",\n\t\"credentials\": {\n\t\t\"account_id\": \"imauser\"\n\t},\n\t\"org_details\": {\n\t\t\"zip\": 0,\n\t\t\"admin_details\": [{\n\t\t\t\"first_name\": \"Admin\",\n\t\t\t\"last_name\": \"Guy\",\n\t\t\t\"email\": \"adminguy@certsforme.com\",\n\t\t\t\"phone\": \"867-5309\"\n\t\t}]\n\t},\n\t\"attributes\": {\n\t\t\"enabled\": true,\n\t\t\"created\": 1509346474,\n\t\t\"updated\": 1509346479\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultdeletecertificateoperation.json",
    "content": "{\n\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/certificates/myTempCertificate/pending\",\n\t\"issuer\": {\n\t\t\"name\": \"Self\"\n\t},\n\t\"csr\": \"MIIEtzCCAp8CAQAwJzElMCMGA1UEAxMcbXl0ZW1wY2VydGlmaWNhdGUuZm9vYmFyLmNvbTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMmt2TbL1ndbSggTwx2l3k/ZUzt0IGO/FMB/oqpmc5izy2KGi0/uSoEdFA9cSqfctL3FGx2J1cFVTz287cvLB8HB3A4svAoPnKsZmKpXuYbF4fK2wQGXm/iNk+JVq1KL0lfoqW2g52lHDM85XURMn8YCkAGIKeTlOVyEn7EMBuBumcJbszj0g56Ij+VKmxoua/Ja4ONmIGsKdyZRBEuvFQ1GTnJUvCWHwyo1pT0M5EY/VL9ikc283DSvpQcfvNelQgQfWCpTRX1Q7nTUHk14DD4d/Y6OdbjcVuqE0Jdqdw6MXfU2zrkPo/nZBf5GHsUChiaxzVeEafPjWKvqVDzhEYXpmMB5SDAELaQtV6PoX+kxcjAO4K//BQtwneHHVF/Sh+7ke3nNUlSf4Mjn541wS7LdkBDOlTnKdYu+DhfbdkRD4E9LPiDduWDWHZs051uFBecR93JaZmX2b376RORQygDkBRga/MNENoEEnsz4zmoMYCGspZhRXEC9Uts1hzYEtwM1hyLqJlfadX/sct20N4JkhDkM8NG2V43R8jcnKFmzjfv6Yc1tuiQ1GQpYNFPJWh+fakAZkt7IwYsvy1CQg92Yvi3ne9zRTBn00enDpBTWaGCZ84gYYaT7Yfyo7/WRTjinYt6R0+u8l0AmZb0xkgxEACIQoyrg+oWQZI4YrneRAgMBAAGgSzBJBgkqhkiG9w0BCQ4xPDA6MA4GA1UdDwEB/wQEAwIFoDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwCQYDVR0TBAIwADANBgkqhkiG9w0BAQsFAAOCAgEAr8RMKLLpGG31Mq4Dor6Tf11AoiHCLH33MUqblF1VfDiw0++qBZ1dgm0D+uzQph/bZ6jKe/PUWpS1bErfaOt3iaVNOHom8jP/U3kZiYWvc/YHetU03prm1Qb+izNZA97NNeZRsuCXMAkNAHQnXa/rz/zG6BmGXFigh55wglX6aB8PnfKZb7N6RCct8BsKSV8uPpxXzRWPKrv7TA2RKfMifUD/Dzt7FSDuYJ8FGkvQNX012RXb2DqHp8tbZgUSj7iXdoZMZ1jfwlh6P61yhfItbF4SYvtBd9PTWIxP6SkCfDjJ7f0/ofwoV2DvAiwfH7URdQIMC+B8dPCqbjya3Ku+B2fWXXhdG7gJqa1zRY066QTIsHwfwd3WbeLQxCcBUEQUG0u23gj9fDX81fvKsgHtN9Nod5wXsdLtjjpHpJQJlDanII4H3fvDxAOlqSnxxEhjL9uA3YXUERMGGjExXA5kCOqKrdfGT5x4yosuNutylvF8YYn8r+mvMgegtVl8XmKnyP+uESSE2krVVmnSM2gveq7ILxBvanq70LmQVeYQB4AlLtUsxPUPIPiOryDI39KrlqWKdl3/oC7Gx+WbVzXxs37NEwt/tx8E+r1Nq/jRFxP0QlyyUdjpiPXjUpuCdn4y6erpCuahbMP+CZNCNgeEh1v2pNljuaGCIB+VA2Fz/oU=\",\n\t\"cancellation_requested\": true,\n\t\"status\": \"inProgress\",\n\t\"status_details\": \"Pending certificate created. Certificate request is in progress. This may take some time based on the issuer provider. Please check again later.\",\n\t\"request_id\": \"32051e4e4ac947c5b9ad1b6737bee7c0\"\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultdeletekey.json",
    "content": "{\n\t\"key\": {\n\t\t\"kid\": \"https://kvvaultapilivetest.vault.azure.net/keys/myKey/1374543b3de34500a97d075991ee3893\",\n\t\t\"kty\": \"RSA\",\n\t\t\"key_ops\": [\"encrypt\", \"decrypt\", \"sign\", \"verify\", \"wrapKey\", \"unwrapKey\"],\n\t\t\"n\": \"tY2pzXPfU7NFYCWvZB1gJNAetkgJ7Qi75lTVOzVns9KjFFo6e_F9GSETZbAYl5oMwfLtdqQqT5fxzWDk0sYlz09HXvCCoYmbzobd3gJ6-WLAqhtCbBikr5HAIlCzy_UqKT--WhEw8AT_EJFBPIY9xNktqnaNZuRBmjmXinzT02qUmBZRsAdJmaYfG9IZSmToOkb54OytI5TreWN0JvceoQ3GSeFLMC5PUmXP6HmZliOzBBHWnXNq3H7a3qfWV3rxT2QpbrIuz18ZqOVp7o5868kN8knKytVcqEzmdiQUdabkqbrwuh-z_IEre9AqTfw6OjUUmLjs4lyKcpWLYFh8KJuML1ub-8u0VgNGwczUZ7aAld1iwGMsoMmQfMRDOnv-9pqtY-y40ZWpBGXpzFV-IvtKHnqQk_vWqowpE8xwx7yZ74z9XNgS9TmkVpcC-ONbEfNE1sez0Zf-RZ9eOm_7WSxxH6OJYtJI7wotBXYoy1bJaqo7mgHs1IUOFhSE-Evj\",\n\t\t\"e\": \"AQAB\"\n\t},\n\t\"attributes\": {\n\t\t\"enabled\": true,\n\t\t\"created\": 1509335925,\n\t\t\"updated\": 1509335925,\n\t\t\"recoveryLevel\": \"Purgeable\"\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultdeletesecret.json",
    "content": "{\n\t\"contentType\": \"aNewSecretKey\",\n\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/secrets/mySecret/8c418537cbc948539ea2ac12c0bfcfb4\",\n\t\"attributes\": {\n\t\t\"enabled\": true,\n\t\t\"created\": 1509335944,\n\t\t\"updated\": 1509335944,\n\t\t\"recoveryLevel\": \"Purgeable\"\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultget.json",
    "content": "{\n  \"id\": \"/subscriptions/3fee811e-11bf-4b5c-9c62-a2f28b517724/resourceGroups/rg-vaultapilivetest-jims/providers/Microsoft.KeyVault/vaults/kvvaultapilivetest\",\n  \"name\": \"kvvaultapilivetest\",\n  \"type\": \"Microsoft.KeyVault/vaults\",\n  \"location\": \"westeurope\",\n  \"tags\": {},\n  \"properties\": {\n    \"sku\": {\n      \"family\": \"A\",\n      \"name\": \"standard\"\n    },\n    \"tenantId\": \"72f988bf-86f1-41af-91ab-2d7cd011db47\",\n    \"accessPolicies\": [{\n      \"tenantId\": \"72f988bf-86f1-41af-91ab-2d7cd011db47\",\n      \"objectId\": \"5a7f4cb9-ce9d-4b31-87ce-f61083c4b0ea\",\n      \"permissions\": {\n        \"certificates\": [\"Get\", \"List\", \"Update\", \"Create\", \"Import\", \"Delete\", \"ManageContacts\", \"ManageIssuers\", \"GetIssuers\", \"ListIssuers\", \"SetIssuers\", \"DeleteIssuers\", \"Purge\", \"Recover\"],\n        \"keys\": [\"Get\", \"List\", \"Update\", \"Create\", \"Import\", \"Delete\", \"Recover\", \"Backup\", \"Restore\", \"Purge\"],\n        \"secrets\": [\"Get\", \"List\", \"Set\", \"Delete\", \"Recover\", \"Backup\", \"Restore\", \"Purge\"],\n        \"storage\": []\n      }\n    }],\n    \"enabledForDeployment\": false,\n    \"vaultUri\": \"https://kvvaultapilivetest.vault.azure.net/\"\n  }\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultgetcertificate.json",
    "content": "{\n\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/certificates/myCertificate/b73ba4610dc24dca946f76933f6590dd\",\n\t\"kid\": \"https://kvvaultapilivetest.vault.azure.net/keys/myCertificate/b73ba4610dc24dca946f76933f6590dd\",\n\t\"sid\": \"https://kvvaultapilivetest.vault.azure.net/secrets/myCertificate/b73ba4610dc24dca946f76933f6590dd\",\n\t\"x5t\": \"K7HXO6YIK6xwCX8W1InUKsJV9Rk\",\n\t\"cer\": \"MIIDTDCCAjSgAwIBAgIQVA+XomvgS56ybBWv2MnacjANBgkqhkiG9w0BAQsFADAjMSEwHwYDVQQDExhteWNlcnRpZmljYXRlLmZvb2Jhci5jb20wHhcNMTcxMDMwMDY0NDI3WhcNMTgxMDMwMDY1NDI3WjAjMSEwHwYDVQQDExhteWNlcnRpZmljYXRlLmZvb2Jhci5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCusjC1A7rQEjW9SRL9XHRNDl0EuNYEV9AVQcAEmgpcJ6WgusdataeFrHKPmO8RUZgXk4sE14d3o9HjduYcqfOre+FBdQDWwoFHEAlq9Iz1r4woGk3f1oq9KepE12cRMTyTA214iluYNUx7XxSca3KFFswqonvcekbLJF2IPydNL0XrlIJFCUoAs3PRWLfPnYuijqRGhk8B9xGQMBtuDsnEi4wQRxusFHR1JxHSbY65xi1Hc9Ds9RAxdKwvBmYYC7V78q6qNM0LpenFGlZJMd/eRLVDguM1d17yyTX/lei/Oj8yVVDsva23ilUrv1mR549sv1lIqxNzdOGLsb6jykJ7AgMBAAGjfDB6MA4GA1UdDwEB/wQEAwIFoDAJBgNVHRMEAjAAMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAfBgNVHSMEGDAWgBRnlX51KtyJ/m/V8I/3il4cAW/HOzAdBgNVHQ4EFgQUZ5V+dSrcif5v1fCP94peHAFvxzswDQYJKoZIhvcNAQELBQADggEBAAbSFuMRMbXyH80iA/jU7vuUCYe0Ra/wTTB1qVHTBuqQ/W8RI01mdqI9+GAPOTyN94XPPYVpSz9ZQ3P0/dhgcsahW5bZQkC0CcUSE5R7JUOKI5Up6n8zZM/unHlC6ZcEpNA/scObPKhQXdZayxgf2/p30bii4CiyS7ADEH92xMnzo1Eu9Dckxh1MRDypfxMY9YIzggksiY78BxoNsRDyxNjeRHVUxAIJ3n9TUv+WG31r7rMOIs6ZPsWc96AzUHHAZREVTEh2kiKKIenbMXn1tCpF6/GJKGfp7rt5ObUoQAlnn7kgAceteKZHEMgRZ4c4EQq+yqBw3hJrz4dOabJcmcU=\",\n\t\"attributes\": {\n\t\t\"enabled\": true,\n\t\t\"nbf\": 1509345867,\n\t\t\"exp\": 1540882467,\n\t\t\"created\": 1509346467,\n\t\t\"updated\": 1509346467,\n\t\t\"recoveryLevel\": \"Purgeable\"\n\t},\n\t\"policy\": {\n\t\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/certificates/myCertificate/policy\",\n\t\t\"key_props\": {\n\t\t\t\"exportable\": false,\n\t\t\t\"kty\": \"RSA\",\n\t\t\t\"key_size\": 2048,\n\t\t\t\"reuse_key\": false\n\t\t},\n\t\t\"secret_props\": {\n\t\t\t\"contentType\": \"application/x-pkcs12\"\n\t\t},\n\t\t\"x509_props\": {\n\t\t\t\"subject\": \"CN=mycertificate.foobar.com\",\n\t\t\t\"ekus\": [\"1.3.6.1.5.5.7.3.1\", \"1.3.6.1.5.5.7.3.2\"],\n\t\t\t\"key_usage\": [\"digitalSignature\", \"keyEncipherment\"],\n\t\t\t\"validity_months\": 12,\n\t\t\t\"basic_constraints\": {\n\t\t\t\t\"ca\": false\n\t\t\t}\n\t\t},\n\t\t\"lifetime_actions\": [{\n\t\t\t\"trigger\": {\n\t\t\t\t\"lifetime_percentage\": 80\n\t\t\t},\n\t\t\t\"action\": {\n\t\t\t\t\"action_type\": \"AutoRenew\"\n\t\t\t}\n\t\t}],\n\t\t\"issuer\": {\n\t\t\t\"name\": \"Self\"\n\t\t},\n\t\t\"attributes\": {\n\t\t\t\"enabled\": true,\n\t\t\t\"created\": 1509346452,\n\t\t\t\"updated\": 1509346452\n\t\t}\n\t},\n\t\"pending\": {\n\t\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/certificates/myCertificate/pending\"\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultgetcertificatecontacts.json",
    "content": "{\n\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/certificates/contacts\",\n\t\"contacts\": [{\n\t\t\"email\": \"foo@bar.com\",\n\t\t\"name\": \"Foo bar\",\n\t\t\"phone\": \"867-5309\"\n\t}]\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultgetcertificateissuer.json",
    "content": "{\n\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/certificates/issuers/globalsign01\",\n\t\"provider\": \"GlobalSign\",\n\t\"credentials\": {\n\t\t\"account_id\": \"imauser\"\n\t},\n\t\"org_details\": {\n\t\t\"zip\": 0,\n\t\t\"admin_details\": [{\n\t\t\t\"first_name\": \"Admin\",\n\t\t\t\"last_name\": \"Guy\",\n\t\t\t\"email\": \"adminguy@certsforme.com\",\n\t\t\t\"phone\": \"867-5309\"\n\t\t}]\n\t},\n\t\"attributes\": {\n\t\t\"enabled\": true,\n\t\t\"created\": 1509346474,\n\t\t\"updated\": 1509346474\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultgetcertificateoperation.json",
    "content": "{\n\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/certificates/myCertificate/pending\",\n\t\"issuer\": {\n\t\t\"name\": \"Self\"\n\t},\n\t\"csr\": \"MIICszCCAZsCAQAwIzEhMB8GA1UEAxMYbXljZXJ0aWZpY2F0ZS5mb29iYXIuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArrIwtQO60BI1vUkS/Vx0TQ5dBLjWBFfQFUHABJoKXCeloLrHWrWnhaxyj5jvEVGYF5OLBNeHd6PR43bmHKnzq3vhQXUA1sKBRxAJavSM9a+MKBpN39aKvSnqRNdnETE8kwNteIpbmDVMe18UnGtyhRbMKqJ73HpGyyRdiD8nTS9F65SCRQlKALNz0Vi3z52Loo6kRoZPAfcRkDAbbg7JxIuMEEcbrBR0dScR0m2OucYtR3PQ7PUQMXSsLwZmGAu1e/KuqjTNC6XpxRpWSTHf3kS1Q4LjNXde8sk1/5Xovzo/MlVQ7L2tt4pVK79ZkeePbL9ZSKsTc3Thi7G+o8pCewIDAQABoEswSQYJKoZIhvcNAQkOMTwwOjAOBgNVHQ8BAf8EBAMCBaAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMAkGA1UdEwQCMAAwDQYJKoZIhvcNAQELBQADggEBABoDgWVU0DqfhKsujIa4gUHyZKvRWhms0reqb4Ld9GkF4O6TV+TxibBUZRW3SSVvA+po8G7aX+E+si0BfQiwM1PutcK0f5WuYMiEkQ6xaiDhIblrouCYRCTiYmmt2+8iuKAtDNqgqMJjViGXUKcGQgz7UTEJY/LLlgxW2kDyfEJOhGls40AT7tuXAjZ6QPLT9vAdQ8B0L0JNzJ6lJcDe7KattWonjQ4cLZ7xvY0SwUyvabui1UkOFze/EEkLwnJjigvfWkzhoJS7j0Cp3nI08c5zd/rQGq1XNVb9plnjtQP0kwNVQdHVeTug9rqZCyuS3jqwa1prrXkZJyufMmuNSV0=\",\n\t\"cancellation_requested\": false,\n\t\"status\": \"inProgress\",\n\t\"status_details\": \"Pending certificate created. Certificate request is in progress. This may take some time based on the issuer provider. Please check again later.\",\n\t\"request_id\": \"550fcfd2c33440aea6cd354658f91ddb\"\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultgetcertificatepolicy.json",
    "content": "{\n\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/certificates/myCertificate/policy\",\n\t\"key_props\": {\n\t\t\"exportable\": false,\n\t\t\"kty\": \"RSA\",\n\t\t\"key_size\": 2048,\n\t\t\"reuse_key\": false\n\t},\n\t\"secret_props\": {\n\t\t\"contentType\": \"application/x-pkcs12\"\n\t},\n\t\"x509_props\": {\n\t\t\"subject\": \"CN=mycertificate.foobar.com\",\n\t\t\"ekus\": [\"1.3.6.1.5.5.7.3.1\", \"1.3.6.1.5.5.7.3.2\"],\n\t\t\"key_usage\": [\"digitalSignature\", \"keyEncipherment\"],\n\t\t\"validity_months\": 12,\n\t\t\"basic_constraints\": {\n\t\t\t\"ca\": false\n\t\t}\n\t},\n\t\"lifetime_actions\": [{\n\t\t\"trigger\": {\n\t\t\t\"lifetime_percentage\": 80\n\t\t},\n\t\t\"action\": {\n\t\t\t\"action_type\": \"AutoRenew\"\n\t\t}\n\t}],\n\t\"issuer\": {\n\t\t\"name\": \"Self\"\n\t},\n\t\"attributes\": {\n\t\t\"enabled\": true,\n\t\t\"created\": 1509346452,\n\t\t\"updated\": 1509346452\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultgetdeleted.json",
    "content": "{\n  \"id\": \"/subscriptions/3fee811e-11bf-4b5c-9c62-a2f28b517724/providers/Microsoft.KeyVault/locations/westeurope/deletedVaults/kvvaultapilivetest\",\n  \"name\": \"kvvaultapilivetest\",\n  \"type\": \"Microsoft.KeyVault/deletedVaults\",\n  \"properties\": {\n    \"vaultId\": \"/subscriptions/3fee811e-11bf-4b5c-9c62-a2f28b517724/resourceGroups/rg-vaultapilivetest-jims/providers/Microsoft.KeyVault/vaults/kvvaultapilivetest\",\n    \"location\": \"westeurope\",\n    \"tags\": {},\n    \"deletionDate\": \"2017-10-29T22:06:02Z\",\n    \"scheduledPurgeDate\": \"2018-01-27T22:06:02Z\"\n  }\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultgetdeletedcertificate.json",
    "content": "{\n\t\"recoveryId\": \"https://kvvaultapilivetest.vault.azure.net/deletedcertificates/myRecoverableCertificate\",\n\t\"deletedDate\": 1509346545,\n\t\"scheduledPurgeDate\": 1517122545,\n\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/certificates/myRecoverableCertificate/42f1b607074a4531b4f14fb4447d4346\",\n\t\"kid\": \"https://kvvaultapilivetest.vault.azure.net/keys/myRecoverableCertificate/42f1b607074a4531b4f14fb4447d4346\",\n\t\"sid\": \"https://kvvaultapilivetest.vault.azure.net/secrets/myRecoverableCertificate/42f1b607074a4531b4f14fb4447d4346\",\n\t\"x5t\": \"-qEnW6P9TdfOOXzbNQNS5ZKveRo\",\n\t\"cer\": \"MIIFNDCCAxygAwIBAgICQ0MwDQYJKoZIhvcNAQELBQAwVjELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlmb3JuaWExDzANBgNVBAoMBkZvb2JhcjEhMB8GA1UEAwwYRm9vYmFyIEludGVybWVkaWF0ZSBDQSAxMB4XDTE3MTAyODIyNTIxNFoXDTE4MTEwNzIyNTIxNFowUTELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlmb3JuaWExDzANBgNVBAoMBkZvb2JhcjEcMBoGA1UEAwwTdGVzdHNpdGUuZm9vYmFyLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKKlPGmdiqKloSbUri9gvo2lyS0x2axSpeTfgIxI4Qnqhq8wMkih+SuO8+2rzIUd3S9nYqVww6yy+qHiJLXi3DKVYM/jgJnF+PlUoXxulD1abN8kX+TCKuHeAfTSIjM6WSgimGqW3hoB6bYHsaUFaAIg5FYbg5/IpbEMnD2yjU4M/nHVbxRwPqHGYdYfSqGDeHYjDb8GdA/+N0JDEoMVflTQKrDzq9R0lwOg+kICem1D+kww9ajyTu/7QdE8oOhAzuqFIVkCyZwpkrs576ng34mP04vpGcBs8YiKODydtFl2p5labXr5la0LVpLJL6rUkM3EhWOhQ0s+fCGtfrlmFRMCAwEAAaOCAQ8wggELMAkGA1UdEwQCMAAwEQYJYIZIAYb4QgEBBAQDAgZAMDMGCWCGSAGG+EIBDQQmFiRPcGVuU1NMIEdlbmVyYXRlZCBTZXJ2ZXIgQ2VydGlmaWNhdGUwHQYDVR0OBBYEFNPsyKBhnCjL7pVBLRYK3jaoZ8PfMHIGA1UdIwRrMGmAFAf9rGqvLeJheBNJOHBKTG3Oz32PoU2kSzBJMQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEPMA0GA1UECgwGRm9vYmFyMRQwEgYDVQQDDAtGb29iYXIgUm9vdIICQkIwDgYDVR0PAQH/BAQDAgWgMBMGA1UdJQQMMAoGCCsGAQUFBwMBMA0GCSqGSIb3DQEBCwUAA4ICAQA4sFKv4JDZ0+CVjcHL9bkTpk5I2L45xXk3d7GrhBpGveyy8vlb/g7P0qyAVo0UnB+eRTtwk6GTsJdzz4FBem+FDq8ZO/N51Rn4ZJQbDg24eGErK4rpbOo5OQgKKhTKjjBYwsAsIOkJ1TKQDQ3++Kqw3cWh/vlCWoxGPSMOeU/Iro34IWzSeEREMamYo5kIYq2ERCcVSoTcYB87cTYMU+ORyQSEx/OncDuAKm45ub92By5NpeFVMk+8ibifgzbNJHVnaZUVg8ScdM1A4Db6WAL0SUsYIawrnQ+TENs+6Ekls+wu8G5FAmbtOEV0WOafGvdcnELn5IPXlkvLbiRx5EChG+nF3XrLgn3dBQwP2cGrI/IPRm1XfaaBAkMSkf6St5TX3C40g1CGcNSVoKBYBB2Di+hPXwTHImGggR1JF34ljHCokMoPxmr7lP9pam0dhP/SSpIwxfsvDJylBgUEqTr3tsVDIDfMtJjudK7A7H1HMoqEiqlzRvJIEZ1koOxANFcQ1f9am2PPUNFvfK9IbLQlV8d4k1w6xBAeOVke79lJI9pTTCSVb+PTDniEL79JXjmjQUoKE4zo1u41d+wLu3dEGM27GI7BdLYt6bRsolZvrbey7Nn4c0t4ug4B4GTd1SLLVJns/IRLBrNr1anBJ7u9WFruBUEWwtdxAwSoXdtIIQ==\",\n\t\"attributes\": {\n\t\t\"enabled\": true,\n\t\t\"nbf\": 1509231134,\n\t\t\"exp\": 1541631134,\n\t\t\"created\": 1509346510,\n\t\t\"updated\": 1509346510,\n\t\t\"recoveryLevel\": \"Recoverable+Purgeable\"\n\t},\n\t\"policy\": {\n\t\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/certificates/myRecoverableCertificate/policy\",\n\t\t\"key_props\": {\n\t\t\t\"exportable\": true,\n\t\t\t\"kty\": \"RSA\",\n\t\t\t\"key_size\": 2048,\n\t\t\t\"reuse_key\": false\n\t\t},\n\t\t\"secret_props\": {\n\t\t\t\"contentType\": \"application/x-pem-file\"\n\t\t},\n\t\t\"x509_props\": {\n\t\t\t\"subject\": \"CN=testsite.foobar.com, O=Foobar, S=California, C=US\",\n\t\t\t\"ekus\": [\"1.3.6.1.5.5.7.3.1\"],\n\t\t\t\"key_usage\": [\"digitalSignature\", \"keyEncipherment\"],\n\t\t\t\"validity_months\": 13,\n\t\t\t\"basic_constraints\": {\n\t\t\t\t\"ca\": false\n\t\t\t}\n\t\t},\n\t\t\"lifetime_actions\": [{\n\t\t\t\"trigger\": {\n\t\t\t\t\"lifetime_percentage\": 80\n\t\t\t},\n\t\t\t\"action\": {\n\t\t\t\t\"action_type\": \"EmailContacts\"\n\t\t\t}\n\t\t}],\n\t\t\"issuer\": {\n\t\t\t\"name\": \"Unknown\"\n\t\t},\n\t\t\"attributes\": {\n\t\t\t\"enabled\": true,\n\t\t\t\"created\": 1509346510,\n\t\t\t\"updated\": 1509346510\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultgetdeletedkey.json",
    "content": "{\n\t\"recoveryId\": \"https://kvvaultapilivetest.vault.azure.net/deletedkeys/myRecoverableKey\",\n\t\"deletedDate\": 1509335960,\n\t\"scheduledPurgeDate\": 1517111960,\n\t\"key\": {\n\t\t\"kid\": \"https://kvvaultapilivetest.vault.azure.net/keys/myRecoverableKey/274f6c69b94b41359a5932226425eb43\",\n\t\t\"kty\": \"RSA\",\n\t\t\"key_ops\": [\"encrypt\", \"decrypt\", \"sign\", \"verify\", \"wrapKey\", \"unwrapKey\"],\n\t\t\"n\": \"urhKlXbEGvYetOSH-GLytvSJ5djS0-5SKBtFOlJ2885PE0s_ZbnkRURDm2fImv_RV763HKSUQbEolQNs8I99N-3uCkrDStVZ6MPii9-0U6lrEkX7LrMRNYCfPAaSSZhSjCbsyqX9Y-N_A5Jz9uHNuXvpjQ9N7ojUK7fqqhnJKcJ6l6YsGOhGCD3uei4SL5GzbSAn2auIK51lj77UXjBZaudnNWTiKaCbTAmSmEe13DOJkg82_7Y1eWea3NJn4T2nY8WqRJCp4hzBsPBmFXjE1lgFWcSjm_afiSb0mCUP7v7tSOLR3xUBv9WgMO7p4_ce_--A9ZWP418Uqq0COcHAWQ\",\n\t\t\"e\": \"AQAB\"\n\t},\n\t\"attributes\": {\n\t\t\"enabled\": true,\n\t\t\"created\": 1509335950,\n\t\t\"updated\": 1509335950,\n\t\t\"recoveryLevel\": \"Recoverable+Purgeable\"\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultgetdeletedsecret.json",
    "content": "{\n\t\"recoveryId\": \"https://kvvaultapilivetest.vault.azure.net/deletedsecrets/myRecoverableSecret\",\n\t\"deletedDate\": 1509335980,\n\t\"scheduledPurgeDate\": 1517111980,\n\t\"contentType\": \"aNewSecretKey\",\n\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/secrets/myRecoverableSecret/d7194ca6b0214d0ba382353109cd7e58\",\n\t\"attributes\": {\n\t\t\"enabled\": true,\n\t\t\"created\": 1509335958,\n\t\t\"updated\": 1509335958,\n\t\t\"recoveryLevel\": \"Recoverable+Purgeable\"\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultgetkey.json",
    "content": "{\n\t\"key\": {\n\t\t\"kid\": \"https://kvvaultapilivetest.vault.azure.net/keys/myKey/bd6566ec707e4ad89f4ab9577d9d0bef\",\n\t\t\"kty\": \"RSA\",\n\t\t\"key_ops\": [\"encrypt\", \"decrypt\", \"sign\", \"verify\", \"wrapKey\", \"unwrapKey\"],\n\t\t\"n\": \"2ZWsir4hwVxFTQXfWN7Vy1zA33jg1kxUMHmkmEFtVjGDByzmMfEXpnPziNCtYppBtpNT4AJEVQ60aIgSLNrUYBMoeiI2HCf2NM0NTdwYp7wq5tImtbGDASdDXQ1v3Bv3hXGh3CVmN2VLRf0OmoXnZUG_2UZZ05iPXOY6lNFfq8L81v0ZCMiXwFvNVhZ_fzppzhnwuHQf-X6Lnvrd1ocFqF8IFjV3663eumAfZmBLPP6tmiAZYW3G68_G0I2CHLtTPFX05aN51Jn42RITgcs63HFMT_iVW5556YR0BwtqkCXIUgTD714Fipz7EKGqhHsqND7YUSKpiRVQhfoZEckAkQ\",\n\t\t\"e\": \"AQAB\"\n\t},\n\t\"attributes\": {\n\t\t\"enabled\": true,\n\t\t\"created\": 1509335902,\n\t\t\"updated\": 1509335902,\n\t\t\"recoveryLevel\": \"Purgeable\"\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultgetkeyversions.json",
    "content": "{\n\t\"value\": [{\n\t\t\"kid\": \"https://kvvaultapilivetest.vault.azure.net/keys/myKey/1374543b3de34500a97d075991ee3893\",\n\t\t\"attributes\": {\n\t\t\t\"enabled\": true,\n\t\t\t\"created\": 1509335925,\n\t\t\t\"updated\": 1509335925,\n\t\t\t\"recoveryLevel\": \"Purgeable\"\n\t\t}\n\t}, {\n\t\t\"kid\": \"https://kvvaultapilivetest.vault.azure.net/keys/myKey/bd6566ec707e4ad89f4ab9577d9d0bef\",\n\t\t\"attributes\": {\n\t\t\t\"enabled\": true,\n\t\t\t\"created\": 1509335902,\n\t\t\t\"updated\": 1509335923,\n\t\t\t\"recoveryLevel\": \"Purgeable\"\n\t\t},\n\t\t\"tags\": {\n\t\t\t\"purpose\": \"testing\"\n\t\t}\n\t}],\n\t\"nextLink\": null\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultgetsecret.json",
    "content": "{\n\t\"value\": \"-----BEGIN RSA PRIVATE KEY-----\\\\nMIIEogIBAAKCAQEAvZiOgV6b4EmGiasBskXYnTaRyWzBHBGnWB11BzFN3FGigfWx\\\\nVvjI7Ox1SHTx+vGsnjbqQPvIP4JnPEsNcWLyHa6tNAcnj/M7BuyIwdD5+Hvs6kOe\\\\nPuSOJUf8dRjPMUpr6rcUcBmmOwTnKOH4rdpb6jXNnuCIHP+lgXCeRWveZ62TjEB+\\\\n9aB8W8UHH854FGebiUd/aY0tpCFC7wkWz3KbgmjmY2vSe2U98Yj4+l/IWydIZ7ON\\\\nLicteEEIGbNM0o2QSYhQBCJSw5RixDpPlrUUB094qgqUOyW0k8PvjibGxxTh0LYy\\\\nWqWydPF0XaqFRQ6v36UvEiVGwzVsLwsJL/QVtQIDAQABAoIBAEJ6790lE3s9zNMR\\\\nB3M/UoktzUjXvY7eEdOv4I05GJgcd+MiB6D7c1jAQQ+7Ee5wN5rynolSwBCk5RYb\\\\nKweLLmKCEXGg4Jp1K0luPzXW1Q/wRE6Qjzh2Y/FmoHtey6f49IZE1AHKvKMNQRDw\\\\ny4YKfxhM7WC8Un34lkwg9R5aiI3JkOG9/yNkOGrJfQnGUKt+AOAdu6fNYsRLWAPo\\\\nG3vWSNIgwaG5WL5cKd1gacbGBlc6tLB7+LrZuNrqln5ibTtN6QJvRF9KfOrMSvxy\\\\nL/xiHRpyzec/jrxJxAIIwFHiw2jbLdxNqDaVPFA6X1Cks4fvY40KymOS8Ecmkgx4\\\\nC6/ZqLECgYEA38rL8zmbJRRWgrxSoROucaN/9DyvE8Hd97s1zf3I0LIF+GI3JdcN\\\\nDV5O5VDIgQ7QZ55lOaTqJ0f2fOQZF1UbTU1gBUHVF6j1nv6Xic3OV+ZmhTMbt0Op\\\\nWxPaKup6dkNEAe/Xg0p308r8xw/psh4/gjL1ICHwycjUlz9FQz8FLGsCgYEA2OHc\\\\n/F4vAdK04U4w6AyivuJdIsDAks1ikl+3TqgzyesPg+DpKVNSy6DhraDFKdRqWhbK\\\\nDqigTud8TVk9kmyF3WIb1BDf4IrxlTK08s6Jf25QA/lBlwIst3rejqWwRBY2fJp4\\\\nO8hU31xNLd8nZq8tKYaP+yvyI6fSC+9ZIgyATl8CgYBtTlYzZG2cvMRMcsNBHaXU\\\\np3E1z/YLhmNuPqhXBp/xHyK/YOliuBkN8IREiSKFtsCf+8OhViVwLjv8YETJGq6N\\\\nIT/HEZKNTd86W0uU6UrhsA1e/cmJx6iObbHfyEssPEqZT5ZJ8DN65Oh2KhWRBCks\\\\n5MrJeQps5ITBowunfr5+JQKBgBln09goPD9tbEzcOPRlzoanw5s3kxdfQcW9up5X\\\\nK8HibC3ZodZ6cT9zOBx7sbzlqhOlicPP0v+LNE9nPcQyPDgjrvjXhTIrdIMyrmmm\\\\n8gpgZLUidKF42r4fgYSaOhyvsXBFNAJkxDRp/ox6EIaBzLuJjMIycqnklcFaJ0nK\\\\nxxjnAoGAU/3jRok74Yn0MY183UCXICf/WxVYzwEi3cyRWVh6gAo2ExNye97rau/B\\\\nY2woAcVxEN9h1HNirq8Z2AwrZKd/BcBnvulZqECeH5zBQ0W56ADX72r+lzOAxTJa\\\\nU1AIlNCIkfsQ5CpIoYsVoNEM8P+GyS8B9kaEmk/FVKldRTKJqkI=\\\\n-----END RSA PRIVATE KEY-----\\\\n\",\n\t\"contentType\": \"testSecretKey\",\n\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/secrets/mySecret/b936ececbc674f3bb1367ae50d28ada0\",\n\t\"attributes\": {\n\t\t\"enabled\": true,\n\t\t\"created\": 1509335932,\n\t\t\"updated\": 1509335932,\n\t\t\"recoveryLevel\": \"Purgeable\"\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultgetsecretversions.json",
    "content": "{\n\t\"value\": [{\n\t\t\"contentType\": \"aNewSecretKey\",\n\t\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/secrets/mySecret/8c418537cbc948539ea2ac12c0bfcfb4\",\n\t\t\"attributes\": {\n\t\t\t\"enabled\": true,\n\t\t\t\"created\": 1509335944,\n\t\t\t\"updated\": 1509335944,\n\t\t\t\"recoveryLevel\": \"Purgeable\"\n\t\t}\n\t}, {\n\t\t\"contentType\": \"testSecretKey\",\n\t\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/secrets/mySecret/b936ececbc674f3bb1367ae50d28ada0\",\n\t\t\"attributes\": {\n\t\t\t\"enabled\": true,\n\t\t\t\"created\": 1509335932,\n\t\t\t\"updated\": 1509335934,\n\t\t\t\"recoveryLevel\": \"Purgeable\"\n\t\t},\n\t\t\"tags\": {\n\t\t\t\"purpose\": \"testing\"\n\t\t}\n\t}],\n\t\"nextLink\": null\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultimportablecert.txt",
    "content": "-----BEGIN PRIVATE KEY-----\nMIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCipTxpnYqipaEm\n1K4vYL6NpcktMdmsUqXk34CMSOEJ6oavMDJIofkrjvPtq8yFHd0vZ2KlcMOssvqh\n4iS14twylWDP44CZxfj5VKF8bpQ9WmzfJF/kwirh3gH00iIzOlkoIphqlt4aAem2\nB7GlBWgCIORWG4OfyKWxDJw9so1ODP5x1W8UcD6hxmHWH0qhg3h2Iw2/BnQP/jdC\nQxKDFX5U0Cqw86vUdJcDoPpCAnptQ/pMMPWo8k7v+0HRPKDoQM7qhSFZAsmcKZK7\nOe+p4N+Jj9OL6RnAbPGIijg8nbRZdqeZWm16+ZWtC1aSyS+q1JDNxIVjoUNLPnwh\nrX65ZhUTAgMBAAECggEAQWLiXadbM7YYik7YU+21zaZHsWaoFtIHJXMA7+Tgq6bg\nTI+4t2B+lpda00LM7vspj8QlcVNbJxOxFOGgVosEcUWCbTEN40Qmqr3uSeL+r4ep\n2y95abLxoGorKSxNWYDslOkLk1Zhpdz9AxQmw6vfu3NTuJZJHTSCACKMsXUVv7lv\ngMzyaZQ5JC+NFjLv/AK1moq4AqkjwQYzwXou2jbzJ9aoSS+hGSijGwmJbYBe1tev\n3PZVa708PTUF/U0Iw2FaEIg7BrkUxILic6THRBE/Lak+nBG7dlmQhL/3gEukTojr\niMMtYhCEv0mhKGa7AycIGk31ySbAtV7/KXMEvgMROQKBgQDOrv9f9skNdanV5YyU\nOoOzfc8LOFUlTMyDS5Ioh5PWD0YqzELcBbcbsMmVwRBlChDiJcwDG7Ro4DCSLG9I\nG4vo0JHDxyKJpWLq07E8MRzL3804K0XKKP/AFS4u0P8LMVAny7OK2c58NvFXmDqu\nRV+k3S65AVQNaie0uUZ7IoXfvwKBgQDJdDm6hOJtKuZiZP7k23k1rcBGc0mPkd0w\n8yUooWNZGBjPpwzX7ELqYFnK+6Wy8qOJSEYVjzov7ArSmbmhq09bej9uLP0fWYcm\nO6C7FMw++Gkz+MF5s7EGcUQI36wGWIlGuNyHTVNqOgBhCYBulhtQVj0CImuV5XHg\nHMv3YppfrQKBgB3jNnClGjvFCRMyR5rjv0nEZp1DvyROr8BIvFD6EgnBWa80rHJu\nrSTm8q+iJIHH69sYBiFo7zS/PqbUoB74RMoc5wc9k6P984jrpdSDcZuVuHJn54at\nWRZoua3xcQAoWGP40/S/PFnABDRbghjTVVpc1bXRGFt8P1Ol+ygxPNS3AoGACRbq\nZ+UJBl3yKSxfZ9oTPP3K+CLJheXR8hx2Z7/oaKOysuPZq4BogIS6aHM0Rb+260HM\nj7p3qKPg1SHEg2vkV79LT2BOR3TVqT71gJtun8S7knG94QzfhufjZvcYnuytvPgo\nUx6FDfzx+W7hUZwKPXS2qfr9mbTRj4gdF9tmFb0CgYBTT/j/J4pHnUUVTMROhHTb\n4HlyZLvfaT5TSHa+W+WyqtYNvsR1yUrQ+bErjBiSg8lFZjVUiGlUeWtysMBUttdr\nuulnqRnPp3QFmwNdu+6gIfJmz0R8QZfkBc57X/9wDLmEb6nN8PnysQ8zvRDTE1ga\n8MCiq3A3u1HM0+JN+v0c2g==\n-----END PRIVATE KEY-----\n-----BEGIN CERTIFICATE-----\nMIIFNDCCAxygAwIBAgICQ0MwDQYJKoZIhvcNAQELBQAwVjELMAkGA1UEBhMCVVMx\nEzARBgNVBAgMCkNhbGlmb3JuaWExDzANBgNVBAoMBkZvb2JhcjEhMB8GA1UEAwwY\nRm9vYmFyIEludGVybWVkaWF0ZSBDQSAxMB4XDTE3MTAyODIyNTIxNFoXDTE4MTEw\nNzIyNTIxNFowUTELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlmb3JuaWExDzAN\nBgNVBAoMBkZvb2JhcjEcMBoGA1UEAwwTdGVzdHNpdGUuZm9vYmFyLmNvbTCCASIw\nDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKKlPGmdiqKloSbUri9gvo2lyS0x\n2axSpeTfgIxI4Qnqhq8wMkih+SuO8+2rzIUd3S9nYqVww6yy+qHiJLXi3DKVYM/j\ngJnF+PlUoXxulD1abN8kX+TCKuHeAfTSIjM6WSgimGqW3hoB6bYHsaUFaAIg5FYb\ng5/IpbEMnD2yjU4M/nHVbxRwPqHGYdYfSqGDeHYjDb8GdA/+N0JDEoMVflTQKrDz\nq9R0lwOg+kICem1D+kww9ajyTu/7QdE8oOhAzuqFIVkCyZwpkrs576ng34mP04vp\nGcBs8YiKODydtFl2p5labXr5la0LVpLJL6rUkM3EhWOhQ0s+fCGtfrlmFRMCAwEA\nAaOCAQ8wggELMAkGA1UdEwQCMAAwEQYJYIZIAYb4QgEBBAQDAgZAMDMGCWCGSAGG\n+EIBDQQmFiRPcGVuU1NMIEdlbmVyYXRlZCBTZXJ2ZXIgQ2VydGlmaWNhdGUwHQYD\nVR0OBBYEFNPsyKBhnCjL7pVBLRYK3jaoZ8PfMHIGA1UdIwRrMGmAFAf9rGqvLeJh\neBNJOHBKTG3Oz32PoU2kSzBJMQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZv\ncm5pYTEPMA0GA1UECgwGRm9vYmFyMRQwEgYDVQQDDAtGb29iYXIgUm9vdIICQkIw\nDgYDVR0PAQH/BAQDAgWgMBMGA1UdJQQMMAoGCCsGAQUFBwMBMA0GCSqGSIb3DQEB\nCwUAA4ICAQA4sFKv4JDZ0+CVjcHL9bkTpk5I2L45xXk3d7GrhBpGveyy8vlb/g7P\n0qyAVo0UnB+eRTtwk6GTsJdzz4FBem+FDq8ZO/N51Rn4ZJQbDg24eGErK4rpbOo5\nOQgKKhTKjjBYwsAsIOkJ1TKQDQ3++Kqw3cWh/vlCWoxGPSMOeU/Iro34IWzSeERE\nMamYo5kIYq2ERCcVSoTcYB87cTYMU+ORyQSEx/OncDuAKm45ub92By5NpeFVMk+8\nibifgzbNJHVnaZUVg8ScdM1A4Db6WAL0SUsYIawrnQ+TENs+6Ekls+wu8G5FAmbt\nOEV0WOafGvdcnELn5IPXlkvLbiRx5EChG+nF3XrLgn3dBQwP2cGrI/IPRm1XfaaB\nAkMSkf6St5TX3C40g1CGcNSVoKBYBB2Di+hPXwTHImGggR1JF34ljHCokMoPxmr7\nlP9pam0dhP/SSpIwxfsvDJylBgUEqTr3tsVDIDfMtJjudK7A7H1HMoqEiqlzRvJI\nEZ1koOxANFcQ1f9am2PPUNFvfK9IbLQlV8d4k1w6xBAeOVke79lJI9pTTCSVb+PT\nDniEL79JXjmjQUoKE4zo1u41d+wLu3dEGM27GI7BdLYt6bRsolZvrbey7Nn4c0t4\nug4B4GTd1SLLVJns/IRLBrNr1anBJ7u9WFruBUEWwtdxAwSoXdtIIQ==\n-----END CERTIFICATE-----"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultimportcertificate.json",
    "content": "{\n\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/certificates/myImportableCertificate/f69168f2963e4ac7b68622b2bb2f80d3\",\n\t\"kid\": \"https://kvvaultapilivetest.vault.azure.net/keys/myImportableCertificate/f69168f2963e4ac7b68622b2bb2f80d3\",\n\t\"sid\": \"https://kvvaultapilivetest.vault.azure.net/secrets/myImportableCertificate/f69168f2963e4ac7b68622b2bb2f80d3\",\n\t\"x5t\": \"-qEnW6P9TdfOOXzbNQNS5ZKveRo\",\n\t\"cer\": \"MIIFNDCCAxygAwIBAgICQ0MwDQYJKoZIhvcNAQELBQAwVjELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlmb3JuaWExDzANBgNVBAoMBkZvb2JhcjEhMB8GA1UEAwwYRm9vYmFyIEludGVybWVkaWF0ZSBDQSAxMB4XDTE3MTAyODIyNTIxNFoXDTE4MTEwNzIyNTIxNFowUTELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlmb3JuaWExDzANBgNVBAoMBkZvb2JhcjEcMBoGA1UEAwwTdGVzdHNpdGUuZm9vYmFyLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKKlPGmdiqKloSbUri9gvo2lyS0x2axSpeTfgIxI4Qnqhq8wMkih+SuO8+2rzIUd3S9nYqVww6yy+qHiJLXi3DKVYM/jgJnF+PlUoXxulD1abN8kX+TCKuHeAfTSIjM6WSgimGqW3hoB6bYHsaUFaAIg5FYbg5/IpbEMnD2yjU4M/nHVbxRwPqHGYdYfSqGDeHYjDb8GdA/+N0JDEoMVflTQKrDzq9R0lwOg+kICem1D+kww9ajyTu/7QdE8oOhAzuqFIVkCyZwpkrs576ng34mP04vpGcBs8YiKODydtFl2p5labXr5la0LVpLJL6rUkM3EhWOhQ0s+fCGtfrlmFRMCAwEAAaOCAQ8wggELMAkGA1UdEwQCMAAwEQYJYIZIAYb4QgEBBAQDAgZAMDMGCWCGSAGG+EIBDQQmFiRPcGVuU1NMIEdlbmVyYXRlZCBTZXJ2ZXIgQ2VydGlmaWNhdGUwHQYDVR0OBBYEFNPsyKBhnCjL7pVBLRYK3jaoZ8PfMHIGA1UdIwRrMGmAFAf9rGqvLeJheBNJOHBKTG3Oz32PoU2kSzBJMQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEPMA0GA1UECgwGRm9vYmFyMRQwEgYDVQQDDAtGb29iYXIgUm9vdIICQkIwDgYDVR0PAQH/BAQDAgWgMBMGA1UdJQQMMAoGCCsGAQUFBwMBMA0GCSqGSIb3DQEBCwUAA4ICAQA4sFKv4JDZ0+CVjcHL9bkTpk5I2L45xXk3d7GrhBpGveyy8vlb/g7P0qyAVo0UnB+eRTtwk6GTsJdzz4FBem+FDq8ZO/N51Rn4ZJQbDg24eGErK4rpbOo5OQgKKhTKjjBYwsAsIOkJ1TKQDQ3++Kqw3cWh/vlCWoxGPSMOeU/Iro34IWzSeEREMamYo5kIYq2ERCcVSoTcYB87cTYMU+ORyQSEx/OncDuAKm45ub92By5NpeFVMk+8ibifgzbNJHVnaZUVg8ScdM1A4Db6WAL0SUsYIawrnQ+TENs+6Ekls+wu8G5FAmbtOEV0WOafGvdcnELn5IPXlkvLbiRx5EChG+nF3XrLgn3dBQwP2cGrI/IPRm1XfaaBAkMSkf6St5TX3C40g1CGcNSVoKBYBB2Di+hPXwTHImGggR1JF34ljHCokMoPxmr7lP9pam0dhP/SSpIwxfsvDJylBgUEqTr3tsVDIDfMtJjudK7A7H1HMoqEiqlzRvJIEZ1koOxANFcQ1f9am2PPUNFvfK9IbLQlV8d4k1w6xBAeOVke79lJI9pTTCSVb+PTDniEL79JXjmjQUoKE4zo1u41d+wLu3dEGM27GI7BdLYt6bRsolZvrbey7Nn4c0t4ug4B4GTd1SLLVJns/IRLBrNr1anBJ7u9WFruBUEWwtdxAwSoXdtIIQ==\",\n\t\"attributes\": {\n\t\t\"enabled\": true,\n\t\t\"nbf\": 1509231134,\n\t\t\"exp\": 1541631134,\n\t\t\"created\": 1509346469,\n\t\t\"updated\": 1509346469,\n\t\t\"recoveryLevel\": \"Purgeable\"\n\t},\n\t\"policy\": {\n\t\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/certificates/myImportableCertificate/policy\",\n\t\t\"key_props\": {\n\t\t\t\"exportable\": true,\n\t\t\t\"kty\": \"RSA\",\n\t\t\t\"key_size\": 2048,\n\t\t\t\"reuse_key\": false\n\t\t},\n\t\t\"secret_props\": {\n\t\t\t\"contentType\": \"application/x-pem-file\"\n\t\t},\n\t\t\"x509_props\": {\n\t\t\t\"subject\": \"CN=testsite.foobar.com, O=Foobar, S=California, C=US\",\n\t\t\t\"ekus\": [\"1.3.6.1.5.5.7.3.1\"],\n\t\t\t\"key_usage\": [\"digitalSignature\", \"keyEncipherment\"],\n\t\t\t\"validity_months\": 13,\n\t\t\t\"basic_constraints\": {\n\t\t\t\t\"ca\": false\n\t\t\t}\n\t\t},\n\t\t\"lifetime_actions\": [{\n\t\t\t\"trigger\": {\n\t\t\t\t\"lifetime_percentage\": 80\n\t\t\t},\n\t\t\t\"action\": {\n\t\t\t\t\"action_type\": \"EmailContacts\"\n\t\t\t}\n\t\t}],\n\t\t\"issuer\": {\n\t\t\t\"name\": \"Unknown\"\n\t\t},\n\t\t\"attributes\": {\n\t\t\t\"enabled\": true,\n\t\t\t\"created\": 1509346469,\n\t\t\t\"updated\": 1509346469\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultimportcertificaterequestbody.json",
    "content": "{\n\t\"policy\": {\n\t\t\"lifetime_actions\": [],\n\t\t\"secret_props\": {\n\t\t\t\"contentType\": \"application/x-pem-file\"\n\t\t}\n\t},\n\t\"value\": \"-----BEGIN PRIVATE KEY-----\\nMIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCipTxpnYqipaEm\\n1K4vYL6NpcktMdmsUqXk34CMSOEJ6oavMDJIofkrjvPtq8yFHd0vZ2KlcMOssvqh\\n4iS14twylWDP44CZxfj5VKF8bpQ9WmzfJF/kwirh3gH00iIzOlkoIphqlt4aAem2\\nB7GlBWgCIORWG4OfyKWxDJw9so1ODP5x1W8UcD6hxmHWH0qhg3h2Iw2/BnQP/jdC\\nQxKDFX5U0Cqw86vUdJcDoPpCAnptQ/pMMPWo8k7v+0HRPKDoQM7qhSFZAsmcKZK7\\nOe+p4N+Jj9OL6RnAbPGIijg8nbRZdqeZWm16+ZWtC1aSyS+q1JDNxIVjoUNLPnwh\\nrX65ZhUTAgMBAAECggEAQWLiXadbM7YYik7YU+21zaZHsWaoFtIHJXMA7+Tgq6bg\\nTI+4t2B+lpda00LM7vspj8QlcVNbJxOxFOGgVosEcUWCbTEN40Qmqr3uSeL+r4ep\\n2y95abLxoGorKSxNWYDslOkLk1Zhpdz9AxQmw6vfu3NTuJZJHTSCACKMsXUVv7lv\\ngMzyaZQ5JC+NFjLv/AK1moq4AqkjwQYzwXou2jbzJ9aoSS+hGSijGwmJbYBe1tev\\n3PZVa708PTUF/U0Iw2FaEIg7BrkUxILic6THRBE/Lak+nBG7dlmQhL/3gEukTojr\\niMMtYhCEv0mhKGa7AycIGk31ySbAtV7/KXMEvgMROQKBgQDOrv9f9skNdanV5YyU\\nOoOzfc8LOFUlTMyDS5Ioh5PWD0YqzELcBbcbsMmVwRBlChDiJcwDG7Ro4DCSLG9I\\nG4vo0JHDxyKJpWLq07E8MRzL3804K0XKKP/AFS4u0P8LMVAny7OK2c58NvFXmDqu\\nRV+k3S65AVQNaie0uUZ7IoXfvwKBgQDJdDm6hOJtKuZiZP7k23k1rcBGc0mPkd0w\\n8yUooWNZGBjPpwzX7ELqYFnK+6Wy8qOJSEYVjzov7ArSmbmhq09bej9uLP0fWYcm\\nO6C7FMw++Gkz+MF5s7EGcUQI36wGWIlGuNyHTVNqOgBhCYBulhtQVj0CImuV5XHg\\nHMv3YppfrQKBgB3jNnClGjvFCRMyR5rjv0nEZp1DvyROr8BIvFD6EgnBWa80rHJu\\nrSTm8q+iJIHH69sYBiFo7zS/PqbUoB74RMoc5wc9k6P984jrpdSDcZuVuHJn54at\\nWRZoua3xcQAoWGP40/S/PFnABDRbghjTVVpc1bXRGFt8P1Ol+ygxPNS3AoGACRbq\\nZ+UJBl3yKSxfZ9oTPP3K+CLJheXR8hx2Z7/oaKOysuPZq4BogIS6aHM0Rb+260HM\\nj7p3qKPg1SHEg2vkV79LT2BOR3TVqT71gJtun8S7knG94QzfhufjZvcYnuytvPgo\\nUx6FDfzx+W7hUZwKPXS2qfr9mbTRj4gdF9tmFb0CgYBTT/j/J4pHnUUVTMROhHTb\\n4HlyZLvfaT5TSHa+W+WyqtYNvsR1yUrQ+bErjBiSg8lFZjVUiGlUeWtysMBUttdr\\nuulnqRnPp3QFmwNdu+6gIfJmz0R8QZfkBc57X/9wDLmEb6nN8PnysQ8zvRDTE1ga\\n8MCiq3A3u1HM0+JN+v0c2g\\u003d\\u003d\\n-----END PRIVATE KEY-----\\n-----BEGIN CERTIFICATE-----\\nMIIFNDCCAxygAwIBAgICQ0MwDQYJKoZIhvcNAQELBQAwVjELMAkGA1UEBhMCVVMx\\nEzARBgNVBAgMCkNhbGlmb3JuaWExDzANBgNVBAoMBkZvb2JhcjEhMB8GA1UEAwwY\\nRm9vYmFyIEludGVybWVkaWF0ZSBDQSAxMB4XDTE3MTAyODIyNTIxNFoXDTE4MTEw\\nNzIyNTIxNFowUTELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlmb3JuaWExDzAN\\nBgNVBAoMBkZvb2JhcjEcMBoGA1UEAwwTdGVzdHNpdGUuZm9vYmFyLmNvbTCCASIw\\nDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKKlPGmdiqKloSbUri9gvo2lyS0x\\n2axSpeTfgIxI4Qnqhq8wMkih+SuO8+2rzIUd3S9nYqVww6yy+qHiJLXi3DKVYM/j\\ngJnF+PlUoXxulD1abN8kX+TCKuHeAfTSIjM6WSgimGqW3hoB6bYHsaUFaAIg5FYb\\ng5/IpbEMnD2yjU4M/nHVbxRwPqHGYdYfSqGDeHYjDb8GdA/+N0JDEoMVflTQKrDz\\nq9R0lwOg+kICem1D+kww9ajyTu/7QdE8oOhAzuqFIVkCyZwpkrs576ng34mP04vp\\nGcBs8YiKODydtFl2p5labXr5la0LVpLJL6rUkM3EhWOhQ0s+fCGtfrlmFRMCAwEA\\nAaOCAQ8wggELMAkGA1UdEwQCMAAwEQYJYIZIAYb4QgEBBAQDAgZAMDMGCWCGSAGG\\n+EIBDQQmFiRPcGVuU1NMIEdlbmVyYXRlZCBTZXJ2ZXIgQ2VydGlmaWNhdGUwHQYD\\nVR0OBBYEFNPsyKBhnCjL7pVBLRYK3jaoZ8PfMHIGA1UdIwRrMGmAFAf9rGqvLeJh\\neBNJOHBKTG3Oz32PoU2kSzBJMQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZv\\ncm5pYTEPMA0GA1UECgwGRm9vYmFyMRQwEgYDVQQDDAtGb29iYXIgUm9vdIICQkIw\\nDgYDVR0PAQH/BAQDAgWgMBMGA1UdJQQMMAoGCCsGAQUFBwMBMA0GCSqGSIb3DQEB\\nCwUAA4ICAQA4sFKv4JDZ0+CVjcHL9bkTpk5I2L45xXk3d7GrhBpGveyy8vlb/g7P\\n0qyAVo0UnB+eRTtwk6GTsJdzz4FBem+FDq8ZO/N51Rn4ZJQbDg24eGErK4rpbOo5\\nOQgKKhTKjjBYwsAsIOkJ1TKQDQ3++Kqw3cWh/vlCWoxGPSMOeU/Iro34IWzSeERE\\nMamYo5kIYq2ERCcVSoTcYB87cTYMU+ORyQSEx/OncDuAKm45ub92By5NpeFVMk+8\\nibifgzbNJHVnaZUVg8ScdM1A4Db6WAL0SUsYIawrnQ+TENs+6Ekls+wu8G5FAmbt\\nOEV0WOafGvdcnELn5IPXlkvLbiRx5EChG+nF3XrLgn3dBQwP2cGrI/IPRm1XfaaB\\nAkMSkf6St5TX3C40g1CGcNSVoKBYBB2Di+hPXwTHImGggR1JF34ljHCokMoPxmr7\\nlP9pam0dhP/SSpIwxfsvDJylBgUEqTr3tsVDIDfMtJjudK7A7H1HMoqEiqlzRvJI\\nEZ1koOxANFcQ1f9am2PPUNFvfK9IbLQlV8d4k1w6xBAeOVke79lJI9pTTCSVb+PT\\nDniEL79JXjmjQUoKE4zo1u41d+wLu3dEGM27GI7BdLYt6bRsolZvrbey7Nn4c0t4\\nug4B4GTd1SLLVJns/IRLBrNr1anBJ7u9WFruBUEWwtdxAwSoXdtIIQ\\u003d\\u003d\\n-----END CERTIFICATE-----\"\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultimportkeyrequestbody.json",
    "content": "{\n  \"Hsm\": false,\n  \"attributes\": {\n    \"enabled\": true\n  },\n  \"key\": {\n    \"d\": \"DjU54mYvHpICXHjc5-JiFqiH8NkUgOG8LL4kwt3DeBp9bP0-5hSJH8vmzwJkeGG9L79EWG4b_bfxgYdeNX7cFFagmWPRFrlxbd64VRYFawZHRJt-2cbzMVI6DL8EK4bu5Ux5qTiV44Jw19hoD9nDzCTfPzSTSGrKD3iLPdnREYaIGDVxcjBv3Tx6rrv3Z2lhHHKhEHb0RRjATcjAVKV9NZhMajJ4l9pqJ3A4IQrCBl95ux6Xm1oXP0i6aR78cjchsCpcMXdP3WMsvHgTlsZT0RZLFHrvkiNHlPiil4G2_eHkwvT__CrcbO6SmI_zCtMmypuHJqcr-Xb7GPJoa64WoQ\",\n    \"dp\": \"DB9nGuHplY_7Xv5a5UCs5YgxkWPtJFfbIZ1Zr-XHCCY09JIWReOGQG226OhjwixKtOK_OqmAKtMKM9OmKviJRHNbDhbTxumN3u7cL8dftjXpSryiEQlPmWyW94MneI2WNIrvh4wruQuDt8EztgOiDFxwcnUgey8iend7WmZnE7E\",\n    \"dq\": \"O-bSTUQ4N_UuQezgkF3TDrnBraO67leDGwRbfiE_U0ghQvqh5DA0QSPVzlWDZc9KUitvj8vxsR9o1PW9GS0an17GJEYuetLnkShKK3NWOhBBX6d1yP9rVdH6JhgIJEy_g0Suz7TAFiFc8i7JF8u4QJ05C8bZAMhOLotqftQeVOM\",\n    \"e\": \"AQAB\",\n    \"key_ops\": [\"encrypt\"],\n    \"kty\": \"RSA\",\n    \"n\": \"33TqqLR3eeUmDtHS89qF3p4MP7Wfqt2Zjj3lZjLjjCGDvwr9cJNlNDiuKboODgUiT4ZdPWbOiMAfDcDzlOxA04DDnEFGAf-kDQiNSe2ZtqC7bnIc8-KSG_qOGQIVaay4Ucr6ovDkykO5Hxn7OU7sJp9TP9H0JH8zMQA6YzijYH9LsupTerrY3U6zyihVEDXXOv08vBHk50BMFJbE9iwFwnxCsU5-UZUZYw87Uu0n4LPFS9BT8tUIvAfnRXIEWCha3KbFWmdZQZlyrFw0buUEf0YN3_Q0auBkdbDR_ES2PbgKTJdkjc_rEeM0TxvOUf7HuUNOhrtAVEN1D5uuxE1WSw\",\n    \"p\": \"8K33pX90XX6PZGiv26wZm7tfvqlqWFT03nUMvOAytqdxhO2HysiPn4W58OaJd1tY4372Qpiv6enmUeI4MidCie-s-d0_B6A0xfhU5EeeaDN0xDOOl8yN-kaaVj9b4HDR3c91OAwKpDJQIeJVZtxoijxl-SRx3u7Vs_7meeSpOfE\",\n    \"q\": \"7a5KnUs1pTo72A-JquJvIz4Eu794Yh3ftTk_Et-83aE_FVc6Nk-EhfnwYSNpVmM6UKdrAoy5gsCvZPxrq-eR9pEwU8M5UOlki03vWY_nqDBpJSIqwPvGHUB16zvggsPQUyQBfnN3N8XlDi12n88ltvWwEhn1LQOwMUALEfka9_s\",\n    \"qi\": \"InfGmkb2jNkPGuNiZ-mU0-ZrOgLza_fLL9ErZ35jUPhGFzdGxJNobklvsNoTd-E2GAU41YkJh24bncMLvJVYxHHA5iF7FBWx1SvpEyKVhhnIcuXGD7N5PbNZzEdmr9C6I7cPVkWO-sUV7zfFukexIcANmsd_oBBGKRoYzP5Tti4\"\n  }\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultkeybackup.txt",
    "content": "JkF6dXJlS2V5VmF1bHRLZXlCYWNrdXBWMS5taWNyb3NvZnQuY29tZXlKcmFXUWlPaUppTTJJd1pqZ3dZeTB5Wkdaa0xUUmlPVGt0T0RVeE1TMWpZVGRrTTJKbFlURTVNMkVpTENKaGJHY2lPaUpTVTBFdFQwRkZVQ0lzSW1WdVl5STZJa0V4TWpoRFFrTXRTRk15TlRZaWZRLk9tXzl6QnhwTEw5a3NCVmNfR1JLUHR5akZ6R1JGV3BBWFVvVm91dmdNQXNEcFo2UUp1QUloRzZJWFB4ZHBOUDNlbEZFc19Ld3RpMlBhRXNEQWM4TEVQVHZvVzlSRmlROHZTY3JiWHlKcFNROXJSS1V5NlQ2SWo3UEpDV3Z6alp5ZlNYbklPNjRYMUtzRThFZWNKRDdudDRhN2tfZkpiSkw4a3paWnhXWFZLZnZwZEQ4c3dobFdOLVhMU0RsWDFORmlYQk5ILVRoU1BDbkNMOHc4RjlpV0o0LWFxeXozc0ozRDAzb3JzTHdKczFBTF9LN1c4eUlUNlprb3Azc20zeGlBb2pYZl92WDdOLXhQMUtKMU1tRlFnQVpaMmNpQWdJc2UzVDdoWFhsa0RaNGJqSXpYa2ZocGg1YlNuUEkzQU5kbDRUaXZkdVlxM0lCdlZrQ0hpWnY0US5pLXNxb3lQVVNHdlM2SVdUdld0MzBRLkR5N0U0cE9vanU3bzlMQ2dkcVYwd1c2MGxkOWRaU0tPN0wxWXhid1RMQzd3Z0piSmhlNno5b3VWN0FFMnBMLXFFMUhLclI3Nk9TVTJ3c1FBMFZuTDhlR1RnVFk0TWJOaklzSERraGFSUWN4bGRjOHpGWEVxNzNOWlhPWE5vaWJ2QVhUcm9oX3JnS0plNVFYWE1MSFJ6T2lVWEtqVEU3ak11Qm0zejNMRm1mQ1pQb0xWTnpNT09mdmFwQTh5XzNEUFk1OUdxOUFzWlZsakNpTWoxUlVrQV9QQTBwREUwRU8xd25pV0dIb0t1R3h2N2hLb18wcFVMMWRPalZrNFA1ZmRWRmtGOENVemVvSDNja29xbUxMRmktQ0Nra2E5Q1JZcUE5ekZFckJsZGYzQTlIOVNuazdiUkNhb3c5Tk0tdXFBbkF1OWF6U3JBbnZZZ1NUT0VFUjFvX01Yc1Bqc1loTHp0NFZoTGx4RjlQNDROSU1ZTjEwWVZBYlVIQ0FaREZZejl5d3l2YWJPSXF1bjUzc25DZTBYVjBaWndabFNmSktJUkNsMk9zU29vVEt2OWx6U2kwOVFlUTRxb1NCMFdXSThobjFGd1pYV0RhdHNSNFFxOTB4RXB1bFVyWV9mOWI3cnNSem9jYmF6c0cxek50a0t5bjNVY29fR00yRjJDclFybi1uRVlXMkZRcVpkMlpHT2Nnbk52NFVyWmMxRjB5MUpTdXgxS29qdHBkZDgzR2JPd2s5dmVlSGs2NXlCdmtMTUYtcGtUWGdFS0lZeVN5ZUM4ekdndVZJOHhrX2VndXhQVlhCVVBMWk0xTHJ3U1VDc2JhaGR3WnRZZDN0R1dZVjZsSzhyT1UtQjhlWllvRTd0QUF2RkZxNEJ1R0U1TXRsdHFSRVpkcHlkOWFkTDRVRkttZ05YcTlvNWVqdWJuSmV2RWhRQmhVRXpRLUdCZ3RudVgtSlNTYjBDVllxV3p0NVU2dzJpcVNwZzBNMnQ4WG5OQXN5WTlvYXVBbVhuUGhMZ3lYYWpaSE1TS2FqNjIwOHdrZVA5ME1CSkt1anBfSFhJaEttSW1TOXVwLVY1NXBHRXdMQnhfYlU3TFpwYnhIcm14R3VOTE9pNXhJUGt3QkpTdXFZRlNSMWdaUU5lb1ZHUncwTW5TQW5HYnJ3eE92NFVjVlpUUjhkVTI1Y0NTOHpENjNwQ0ZUdm5CNllyN0pwcGhYekd3SFZYeTM2TkJPdWVuQ2NYQUR2QXNXS2M5a1RQeTlEalVFRFVQd0QydUpZQmhqaV9RR2taYjhfQnNwdURUbWM1Z0Y3TkdsV2NPRTBqZmFwUi1CSlJhUXJENFhxeU95NTRsTUxCZlNSTFBIN0w4VnMyUTVvc0FfVHlPYUoxa3B6dG5iLUhyNTdSQ1E4UWNsRnd5eVRfakpLaXFQRFEyWFlrZ2NjMmdkZlAtS29GNHFHSl9HRERMN3NVaThKeWRnOFNBdDBoRGdUOTh4Zk1URTlQc0twTU9FQUkwWF9KRWdsRTFwRmNxbVFkT2NOU2Z0VUxRaEFPVWd6Qlgxb1UtYTdiX2gtX0l5RVgyb0htZDdaNUJJRV80b0ZEYWVMaXh6ck9BWFdTTzVFZ3B4U0pYUXZ2ZEVZUV9mNHhPVFU3SExmUWkyNEthdGNUTWJJczlBVU1UY1NvVUhIY0RLWVhZbTl3SWR0RXR3MG5mbFp5YVJMYkx4cVJNTzd0X1ZLbnJ6OGVOZ2dJWENBVno4dmJmXzk1VWdVNGJUTzZDLU9BbHJqbUZNbVNzaEpwY0VhRjAwaGx3MnZud2s2QWlCRTlWUzdOYmJFb0JVZmtuaWJFeVJ5NHp2MmZtMWxhRkJnYmUzWV9QVEtHQTlVOGJlNGJsb2lkQmlVOGwxUS1qT3oxeFRNVFUybkpnYkJ6b0xzWEtadEw0d0ZDTnlNVFN3N1pyX3c0aDJjUzU4UHZsVWlYalRhcGpNdTJzYWJtdVJnVXROTjFlWVdxZjBRSEVFdGoydE5nd25TaHNBOHBRWkZKaXp6Rlc2VXpKRXdPbnN4S25tcjFEQktnZ1hsZFFtdmlxWHU5aE00MzdWcUJIeVA2SFZ1dUdiOEUtTlM5WlBPekJWMEFrcTM2QXVJcWNIMXUwTm1NT0laaXR1WVhFNXp3UGlVczJxSmMzQ1BHbVdZQ3d6THNibF9YRkx1dU5udXlIa2VGN1cwOGtxNjhBU2FBMTVic3BQMDU1a2UyMlRVbzNqVl9PeHRUY205OUdBcktGOE82elBjTlQyQ0xNdjkwZ3I1SEx0MVg1WjF4WFNTTVczZ0NRVEs0TmFtNUsyTzFUNXdoTWtPdnhYYmdkb3Jwc245amhGb25aaC00VG5RczJiUmMxVTM1Q1BudmRVM0s1dUVOTzNxZGVxV28zR20xeFRMaUdJSUhsNkdpX0dFdnlqWjdEQzRjeVhlYkI5enRiMklLQXZLVFhyQkF0aXd2bWF4U2FzNFRXVUc5Qy1RYUxLZnpRdDZwVm82NU8wLUZHQ3VLSU1Fc1I4bm9lM19jVVVJNzRiYl9sTVFWdnNyOW9KamJtS1RrWVBhREViQWZCd0FLdGw2dzdWUER4bGt6UmFZVTdPVENsdmFhMTVZQ1hJSzQ2V2hkd2QxMDNoR0x5UjltWlFSdmcyLWhfN0tESzNSVWRzcjNtTlBEYmpCcU16U202MldDNnZTclBVdENKTks2UG1ZWjhfT3A4bXp0U0xUbDBLWlN4dWt5U3d1Y2hfQXZLcGdqa3ktQmVfS0JXNTdka05TT2JlWmZKZElRT0xkSVcwZExqd1BWeTdENEhPS3FyWE1JRGdIdkRIR25zWFBZb0VRZG9wX05BOFZfTW03bWp1blhtZWoxVDI4cTN5VTcxRDEzVUxhdXNwVnNQVHBTcEVDX19mS2ZVSUF2dnI3RmszN19uSFU2QXowSndhNklSU19mTUZHamRuSDI5RXBUcTZGRDdaY1hPZzMxSGdNMHNtNUZlUnkxaHFqUUdIOTRwd2JpUktfWXhQaWVzZHd3cUh2TE1MZE02SU1CU0tuZlVfdTV0bkJISEV6NzZvQ0dHSEJmM0ZnTzFkX1hZZGhtVDZIR2FRUmZhV0s5QTVRNkpUbHBaWUpkOHc2eVlLSDVvNktFR01TWXRKbDFhM29KQ1A2Q0o5Wmh0R0ZWcHlQYlk3M1BkenozR2xvdFlqOE8zYzgtT3BxTm0xaEc2MU1IeEFnNkJYZHgxeFBqZ1RuTVRHbUtTYUplV0d6OWdHc2JDWm52RmlwSExjbHJQVHczVVR0NThOdmpkcGJtOGV1VVdxUDM3RVZzMFFoVHZkNzdmc1duZTgzZlpsYkh5SHF1Y3gwWEtBRmNlMURZNlM5Vlc1Ulp4akU4bHJHemxpVXplTGtsS19wVG91d191MXBVWktLV25jTzJ5RzlrZ3dOT0pkazZiWVlPb1dCRGhVNHU3TFVZR2tETENFaVJrSGRIeVBQbjJBeGNXTGhQYml5cUZ2RWRtNUNMMzMtaHN0OHFRNC1QYldfQV85QVFLZ2hoLXJfUUE2Wjlzd3F4QWJFeWI5R294TUFPenAzMlBoaVhpOHRxTC1qQ1ZqSEFnRTdqYm1jRVBVQVh4QlZFUXNLRGd0MFFRM2RscG0xSUd0OU9fMzNwWEIwUmt1bUxYT3pnWjYzYzNGNVp4ZlRyTGtZZ2MxM0p5dXdjb0Nxa0VxS2RxY0F1N3RFODUtSnkxZnpNTHQzLW9wXzBOWUdqallIZTQxU2drdDZjWjdnQXRFeHlDek5YRjBZcG10WFlralI2UTF0dnFIczhRWU9GaTF4RFZBb01pUjBMczFjRGFRcm5WMEhVZ05QeFJSdUlaYld3dWc1OE9QYnNvUDZYdHRhVGo5RU9yRlJEbUR3OVhiSjhxWEV6YkQ5ZXcxUjVsWGVPZWZZcjVnQVlIU1k0X2lTMXR2Qzg0QkY3RGtYUjVDVUxWZXNkTDBwckh6RFA5MHZfRC1oemJSUDVBNFJMM0RLNmFGN3Z6dFktRlRJSnM0bTNKZ3NyVUp4WkV4NjFMQjRIdGJKM2RTMUYxTjJ2YTJPc2VBSWZ0dkhESWFyV21tbjhBZy12T1JhTW1kWC1pT2YtajI2dWlYV3VvTkNPV085NnM3ZWsyUzRoQ1psN0lPNzVzQThkZGprbDNtaFhrSmEtaVBZZk9Nb3pKWDV5WEREX1E2WDg2YzNvZThLZEdVODJCbGluNXRycjRUdlVXcHBEYVZoYzJ6MENyclN4dko2ZjBIb2ZrYVVNTW9seVlpWW1rSEdpVWNzdmRNbDhMS1MxVEZoWVZiVW9xNUVyYWhKdW0yTjlqdk9DOGd0Ty0yempNR2NjbkEwUzhqbTR2SFVTRDV4MGtkWFotY0NrZ01HSWM2LW1LaHU1YVRpTTFWX01mN3dteTlrdHZITVRqVUM1d0kwU3JMU1F2RnNWZUZHamthLW1qajlsUEkzMFhORmRLajRTR3A5T2pmclRyYnhfeV91emZ5b3NudGVvRHF0RURmVmFSSFhVOF9pQncwWEdZUDBIaGloR3VlczdrdTZJVlE5aTVjVTBNSTRKR01vR0xJRUJKUG1NckxmamJMdkdVWTgzOWUwc0s5NFNBVHJseXo1YzYyeUloTC1xdEdIeTJBMmxxRUhnVnNvQjF0M0J5bDhwME1OSWJId1ZaUlkxcFBDdFBJVmctYWJCZ1ZVSGZneC1FSDVhVlR3QUZGekw5YjBhVUF5eEhnam1XVTlkYjJTMGJ2S3lKaTh2UXJuOWVnYkt4QWM4OEw1NDNsY1dUU1BIOUQ2Zmk5Z19hY0JUUXF5VUt6S3JxYmJUUGxMNWxQdGdfazFhd3ZLNmhNUDZfR0FLUi15a3JzTlcwVUZHaFI0WDNkTE5DNnFUdGdNaXFnYThKN1dVSjdMZUtaRTV1dzlzQlVRemJSdUxjUDFSMnEwQ29DSHdRYWJIRGhPUkdNMkFyMF9HbmIxZVotRXNNSXJHcWcxQkY5T2FMMTdZWE9RWXRhZXBhUEZGcXI5TS1FTHpEWEtYWlBFU1RVZGZqU1g0RllvMFk5cXNTUGdnTjlhajNnMWxfYVNoclA2SVdxZjJrRWoxTjNIMWVaZVUzQjZrWHBCUFV4VXV0LXk3MkU4Q3l6czJtUDgyQjRvNW9GOUVncldIZXF6WGw5XzQyVDFYNlB0Y0l2TGZ2d2hzd2FTVzlGamxVbC1hczVQbUtxSlRtUzl3bE9CdHZybDh1YWdIT1psMW1zZ3Ezd0hWTGVxMmRQclc4UmRjZXJwSTNySGVDZGVzZGJUb3pnS3FuTVhSSVNmZWtvQThLRTkzWFRDOXl1SkM2NmdMcTNJbkJnZ2NUMFp3X0pmWldvN2tmb2dyd2dMRTYwTm9uamxvMERGWFlCRDlKcDd6VGFDRGFGLUZRbHZ5MFdGb1YzRlh2dDllMDdJajBTN0c3THZ0OXVOaW1sbnYyazZOUUJxemlLT01zSjVRQ0pYOEFsbnMwNk9rZG9aVmIzV3Q5MjRQcFM4U0N5R3JnYWVPb24xTHhiMXp2QkIyZDQ5cGJ4a1ZMQnZjcnpFZkYzbExSOU9NdThGNERjS1VHcnBiMjUtNHFQQXVIZXJCcEVEWVBDY3p1RWJaQktZakZQSlozejhKNk45S2l6MktaQTQ0Z3ZKVE42QW5rcThnXzRJMWRBNzRtME9QMEcxd3dtd1pQQU10VXJqYmJ2TVNtbHVjb0FibXhSbDNPd2hFbGRoVFVwdi1iQ3d6ZHVqYnNPMVBsYWI5am1LQUZZaFloU0RZR0FoOTRRRVJ1dkd2VTJnQzlzRmYxTGFTM0Zaa24tRXIxWmgyallpc3BwMlFFd1FBdFlDcmMwaUptMlYwOF95RTVheEVJSnlpZzBhVnFZQ1FiN05GS2diX19LRF9uMi1yN2YwX2RIOFgxeUdJcXpiNzNGbHRCU05RRG1oUU1TdVlVYjlMbHFlREhuNVFtZ3JpQW02d3kwR25QMmE2X2k2TGZWejhMckUxVm94d253V1h4SDlSeDVuTUdpREFvRGxaVlIzVzd1cW1BZ0lMaGFvNldXb0xuYVZSU0pRUTFybTY2R2dCTENUa1QwcE9kS0Vpelc4TlpwXy00Q0tWSHB4ZUpRVFBodXo1cXBmalM4Xzh2M3Nkb0lHNko5RkxwMUludnlmTnFIM0djZ0sxbWZZbWZPUW42cXUybU4yckpiMDg2Y3U2cU5VZnpRcXJqQVpwckdpQ2pCU3Z5T3JwdnZCdGQxVHBQTXFMZEZxbmtGeC1GSTdYWDJocUtoRGFyX2R6QldTWXFPSE9adG50d0hocGNWVExLeXdqQTl0MmxGWTFuNFJtR1l1SHlKdlhVeFZvc05BU19nd1EzM015U25lTk40am5aTWFCNFMyM2lNV0Y0UktSaUlSXzAtTV9Nc1kwbDZmbUxOekZFbFJrUE1LcWFsOHFmbUo3VDkxU2IxdkJFQl9WX052dGxlVzd2VnlaSXBpbV8xUHJ3MC1oMXBMcXVXVDFodll4SWNtbHllSldIUy1NQURnaVdWbnlFOVJBOHpXWFI3TWR2V2s0U2MtaGV0U29LUk1YbmxCM0F2cFc1bEVYN2g0aTJEcVNfLTI0RGdMS09iNWlfVTMwZHNxcWJCdTFMUkNiX2p5dHJhUUlwMEJOczhEMFFXQmFzYlZDbTdNTkM2WlpESlZLMFlBQWkyZnktM3RPSjA3dFF2OFRQelNiaHZETDh6UHdqTmVCSURMWjlvTmdlZFNJYk5sRWdZS3RKZHh6emJEOVp2UmNKSzNYUTBYVHY5bGc0V19HVGJYSUx1bF9fa1owcGZ2RjV6N1Rlc21obV9hRFY2MzNYTEJzWG1wNHJqWUdKUE4tdWxkNW11YkZoWnFWRjJaRHpOTFI5czNKSXNkeHZubnl5QVpiR3dfVjI3eFVKQ19WbktXTzN4bVhGdW5lV0dVSkNFZFpWR2FyZkQ3MHgzc1JIeHJzM29jSEQyQ1JhcnFpM19SOHlndWM4NzlveEJuU29FbXJJTkd5dWkxbXkyRHdnOFYyaGNrcVZKSjhBakxONjNJaGZBR0FTNEU4QWpQODdBczlPX0ZUcnVESWhtOHBEOGpFbUpQTFlTV0hNbkl5WDV6VXEwa3p0NE1QMkNpdzF0Z1pXMGtvRGtHVFhMX1hTV2JCX2ZmVG1lWDN0cDVYU0M0YUh3X3BzUV9oNE44Y2NkS3ItWE1jYXo2aTJ0U3k0Ymh6U2lwWXdqcGx6S3hTYU5wdVpmcURWUHlEVXpfSE9OSHVvV0ZVSEw5alhpTEVuR2JFYW5HZ2VlRXN0cEFDcGMyS2JNN0NhSWpDdUtubmpxVy1EZWoxWGNMY3Y5LU1EVFVraGZwTGhMV3ZOWUZKV19UZ1F3eHhEbllTdEwxYTNZVGRfMjJuQ3dJUm5SekY1Y19YTU5KM0JleDh5c3F6ZTJyN1Q4b1hUcFhvY2ozQ2sxaGgzdEh0dHhCOEIyYUh0UlRUanIzRFltamc1RllTOENLNl9mOThkX1QyS2FHYkViZFd4eDhyTDdEZ3JKTGdqeC1Ba05ma0pCR3prY1JaRnBFX1VHVnNhMW1nZlNwOC00QTVaM1Bfdzhuc1RsdzhsaUZ1MUpxcTR2S2ZyQmNUWTI2UEptdEdkZWQ5N21KQnN1aFhyWW5uZW5qamg5bEZYZ3g1TmYyOFFKNHdoV2w5eTFnSS0wNHF5ZEdfem5CbVJ0MkY1Q0FNbXdMQ0hpZV83LUNZVzNDTkJNWlRPcV80VUpaWndxcTUzNkJYdWtmNHZNZ2ZJSENnT1JfczcxUTRleGRmWWZ2ZTU5ZEp3WEc4ZHRMa2xxdXM5SlM4dlgzSnFHdHpLOUhWYjhlVkdmVWpNNXVnU3J6RWJCRFQ2SE1vLWhqVFpNbzBrbjAtY2hTV0hpVV81X2xRanlmdDZMYkxWZFZEbkxlLXFhczlhUi05YXZDZGk2Wmt1SmxuNVJPbXI1XzVpam54Y0haam1ZU3ZXdU9xX0tZT1JxLTMwRXhMdldTM29YbjNQc0lzOTNWTGktU1hHSEpXamJ6YXVlWDFySWlsMGZFLVY4ektpMU5aLXVVWjJJQnVHdjllVWtYeXJyVl9EWmZxUE94RlpMT1NqYWZuWWxSNEt0dE9WMHJVeURaUExob2h6bkZHdG9jRjAwV29xOVB6b1dCT3VJNjNjeE1YNVZGSnpmYTdTdTZ4Vk1FRExLVEZZRzh0bGVDdUpLSHpTV2hpR0FaY1djU3NvLU1VNnQ3LUJMVEQwWHEzVklNZU5qQzdQcmU2TjU3YkZheWpqaVVTdTBrOEh1SjBhWGZnNDlOZ2M5S1AxWHp5bjA3M3p4NWd4dEVQYTFhSFVFVEROMkVWakc2SDZMdE50VnNqNGVWRVVzTzZ1VTZTWk1hOHhfX1ZPUEM0WEgzVGRYVFMwTl9KZUw4OENyWmZSMmt3VDh2RWdSUHNVLUc1MU9fQnBXcnVzRndXMElRWXBZTnUwLVVmUjB3VDBlUUFsdHpCbDQ5VkZ6SkVMeHhsTXlKc3ByVUNmMHp1cUNUaVg4d0VUNEc5YWtZZzZKWlV5SVptSUk2RmNycy1sWTBPWlVYSW5IS3pqY0w0WnRVbHhZTTFFUENXVXBibWw4SXN2SlpBN1FELUtWOEJVeFdTXzdUOHRLOWtfbUpGT2pTdVhZUTNjTFVDVktyVkRwU3RZZ3JUREdiUlR5bk9EX3QxU2dwbHczMFFUS01mTXNyZkJweWQ1VEpkSGg2eVdSNFFwUlJnWnVaWGR6STRfWVFUMXIzT3NnWDBWM1NaMUZQN2hSNF9NQnFQSkVTenpZc2pQWVdkTzdzaE55Tl8yaXJDLVNxbG81UkJaNVZvZ2VNZDNaVmhhZEQzcnF0UjJmVHZNZm1aYUtuN0piT2FoUUFJYjY3a3NVUHZHQU9rRC1kNS1VRDV0N2JTU0xkd2xXel9aUjFLakxES0xaTE1WSEtTRk40ejhOUGhIcjc3d21GSDZ0ZEw4X0dEaWh3YnVGTEdmbHl3VmRuWi1uenFQcXNhaTU5MGU4SnBfOVQ3dGtMczZQUHBwclFGSGFVRnFtSTAyYUNvaFJDMGRhTEZDY0JrTXA4blkxeFRlamJyZm1yLVpNcmNLMGQtUmM3bWtpVTY3bUpBRTJSQ3BFZ0Y1dUNiT0xoTlNxMXh5SEZHa0llUE92RkFYMWFGQjNwa1VCN0Q4OWxoUkF1ZGd1bW9JWkRCd0dzdVBSRGZPUlR1T3hZakZhaWozZzVyenZHdEVlanB0SVJDbVhNZXhhMVFnYlpQOWJabWh4a0k1SXdHNHJDS0pvZ3NBWnFhYmZUSmUwY18xQTdLYjIzNkEzSHRSMFhJMWRIbVotM2c4cXBwVG9Eb0JPYTZ2RW5vU3NkOFNsX1g1Z0JlZFdmWXZwYzd3X1pfdXJGUXlac3BBbDJrS0N5N2w2U19BUkZqR0dvSnVNWVFicElIbjZGbkJCcjhsTGlyMExZUDVTQlJfM3NaSHNyb3UwamxyLWNMejRZSlpUYzBZcnBGNnRETHA3NFJ0bWM3cDk5aHhNRVE1UG40S1VGNlZJcWt2R2JocjJjdlgzb1d1bk52S0tOcmdXaDYtYzBONFNDTjBkMklveVZfbktzNG4wR2tQcmtDS1ExSGJMbUg1N2ZSTGdqSzFFaEtydGp1SUx3dXFRM0pCeUhISlpOdEdsbV9nZkt5bzZsQ2IyQ2xacElxR2Y0X3ozcVVyMmZVQXhMdWxtRFRMZzh6Z0RlTEViVVdUTXYxTWRUc0pSb0NTZGJiS1NvQ3k2UE1YZUwycllBR2tHT1VYMnVPaDVnRlVkZkdzRVg3enVHamtadnhra2J3VHpTSFlibkMxNHlaRXZsbS1qRkhWS0JjUFdJemJKSnFoUl8zdFVNZ2xRc0xrZzQ2WHFlLUREblVTYUMxbzZ0NnNXOE5CbGR3aGdnOU9JUXhlT2NacVhTanY4TW84SkdrUWlBMnp2WUVWNmJpa09MS3BTbXQyRnNWVE5BSVBQNm1nazE2NG5JaVZXSTN3dlljZ0pCb1ZxeEpCdXJVY2NVNksyVmc1MkU1cnVQc09rNVZwTlphR0ZCb3NYNnU1bjhBM2RfR0laV3VhTUxsZnZnVkdxN21nbFowaFBlM3F3WHI5QndCNm5VV1lJdU1ycFVxUDFQanBmck9OZ3BSOHprQlJ1T0R5R040XzJzRHloMDFWUWRxOGF6OUY4a1gwRU9RaHZ2ZUJKcmtqTTRENGJ5dFVSeVR5RHJRX0hYTExFYUw4UjBPMm9MOGNPeUtSa3F6b1ZGc0NjUC1jMzB1UHFnV2E0T0NzYXhnYUxkTUJveTFKdkFENVF3SWp5dHd2QzR6THNpSXljd3JqeEZaZnVlUnBNRVZLOTR4WVRvNkhlWGQxX0VweFBYMkhiMFFBb0VVVS1zWkFCQVBFZG1OQi1XMEtoUnNpMmJSZi12b3JVZzhJbS1remxCZmxaQ19zUU1RckcwZjR0VE9qTlR0QnlHWUt2dXRqQWJuTjhMQlFSN2JmT0tzM1BvQktQc3pTWDNWMUhtTTUyNnd0X1ZmcDk4d1lFZUNOc3RwcTl1YTRKUlcxRWNGTTRJNnY2aXBXQ3Q5b1V3dVVsTkhUOHNhR2NaUVptRzdZTTRUTDNYVVJITHdaZnNzeUFma2dHejZ0Qm84RWp2MlhNVlZta0ZlRGQ4REl5QXNSUEVHRzZFYUowXzdYajRxNWttR2lUOEJBNE9jMm5pS0M3eVJCVE5CNnhMSldPaXRHcHM0a3ZSX3JfVTl2VUQwMTZ6U19PVlgzLTBqLWNwNzYyWjRicHhNeUswbmNzbFc0M1diUFhRajh2N1libjR1bmtPOU5lc0ZkMC1YWlRvU0J0ZlBTeDk2dGVMM0t4YXEwOFBzV1U5NzhDTVdrUlZHXzZnZWtWWGI0SDdrQUo1M0RoTlpFTW1yM0hSM0lsampIM1YySDRvVGlmeW82ZWdiMHZQX1VEQVNFZGVCUkNYT3JuLUJhTUxzaWhGZE8wVjFxNmNwS2FLVlBkTHgtOTRlelRSRWdtcEpjYjNvSXZoa21RRzJhZ3pZejFEMy1lX0FRU3ladE03TUx6NmY3Ni1HYkkyMy05S0JtVnBVQjJOTnU1aS1xZl8tN3ExQ3JVTFNxNE04aGJsN2E2OUt1UW1RZ0xtQUJZVzlwX3J0ZGFGUzJTRTNGZ0ZPWk1GYnB3MEo3SzRDbXd1VURXb0tyejlGZXAwRDktdkR5NEtpQmdnZWlZTHY3ZFJPVEMwblV2WWlMX00ydXlHbXZtMGJDc29ZMXB3VFNjcDl0aUJZVTZuYW9Ub21ua09qWXZ3T0ZHN3h5R1ZSMF9yT2o3aHpWbzlfbDY3ZE4xaHRFcXZud1BTRno0dXNEcE5UOEFnR3VDVXlMVW5NVVc3ZjNDUFVlOGlqWk5PTm14NEpBT2ZZY1E4dXh3SVRPaExqSEU2alFJOVVFSGNnRmJsMUtrVFJJSDFveGhNSDI3ajJTaUNkS2VrUWVZX3J6cllHTWNmTWF0NTFrdXVzT2pMWDZvbnZWVzBEc1ZXS1FnaUt1OVI1QW8tQkFUTXhxMGJUMWl1X2FaZGNLNkxlZHVwTnVqRXJzSHpNTzF3eGRRcWtMcDVvN2M0ajlQLU5xTTJWWGpnQm93OWJrUmxYdWd2a3Z4WV9tNU1fMm1oeWF1amdtdHg1bXNPR0pIUl9OckY1djZiUGk2aWZkU2o5emhuWGV4MDFEb1B1VmRHeXJkaGN3N25FRjZrczV2N1pOT2ZvRFZuemxCbUpsQVA1eHFjX21SQjI0ZmdWQW5JTzNXMTFSX0V2ZF9UbWxXd085a1cyemFxbi1OeURLUGxtOWp0aXdSSExYRmR1Snc2d2MtdVhJYXdxZFNkZVJkSUV2TWhYX2ExSFhNTG9RYk5VZnpHYk0xSi1aUVBNNWRfbkJPMGN3S0xyRUhlX1ZiT1R4UmZuUU1UVEw1ZnlrcmJGZkgwWUdPYl90aVlqWGJ3QWRsUmtFcFVuSmRWemtCY0tPZUxHMF9ydkRXdmJKX3E4QTFkeFpONm9PSlFvOHRjV0IyVTIyMFNmWjNoNmhUdC12dVBPelltdG1WMDZQb1ZSQTQ5c0JxRWJhNUVKU0pRSGRkVEQyZERDVnRBSV9XNFFFNF9QRGFhQ2kyZFVsN09pZnZJS09TMnJVeVRRckJ2eG1LSnN2Rm9yM2hjOEQ1a3UxMEFQcnlUQmdtOFFTbXJma0xlZGNHUEk0YzlxLW53QnRPM1l0cXExTmhnaHU1WFBxc3h4RXZiMkpOekdXME1DeFJGSGI1bzZLbFg4cExjLWZzUFV1V05lWlV0MnQ3R3ppd1dDc2QtTno2VW1Hb1JicU52SmNKeE56VjUtdnotNWJpUzN5UWkwVlJSczl4elhmN05jYURrQlR1N090Q28wVDFUYWQ3bVE1WTVVREN6UXJGVkR4YS05Q1JubDczLUFvZXp2SUtSWUtYWDZLam5RUjZpNmRJOWNBN2pKRFFFT0thMGY3UHFXcU5tYktMalhSY25ocXZJNW56UU5pYUh5bkUzTXpMb3VOMzEwQ2wtM2d5VFloci1ya3c1UE15VHY4enZpYWtMbER5Vm93dTF4OHMzcmdlSDFUbFp5U0JRUDRIcDBBWFYxelZQQUhNbFU0R1dZdXNOSk0tWk1uSGxBdW5RSVd1WF9pRmxVbmFqMWhyR3pfUFJ3dzRVajF5aVZOLW1UR2laSUdadXRDQXRYeGZUd1hwOE5Lc1pwNThYU2QyeTNfTE4xc2QwZDMydEI3Z20xRE1ybHpqQmFybkdBQ3pEQVo4LXpwUDhhVzh5cXFDQ25GdHdiU1hGOUtiNkVEZzRPckNqZmlpTlZXQTZHSFE2TDlPTnZvemozOXpvaU1nOTdDc2dLY2tZTnUxTXo3NWhtSG14NjdudzZLdFBrcnBBRTFmVDBzeDlYdUtWczhUWEdlUFdvVHREMGRDOUVTRjRsV3RPMnpoV3NsTzhHaWVkQnhjTDVUOTNmWGFwR05sbG12d2lIVWx3S29TSFVnS2JwVWp6MU9WenBGM0l0TGNzVnpoRXlRQXJKakp4THoyNkFGSzVaTE5NUGc0Z2V4ZlRtMmI3YTNkX0g0LUhvMlY0THE4WDVMN1ZBZzh2b1dXY0tfZnBfbERHLWp2STduQzFOYzd0UmkyWnkwU05zY2FKbVQyeE1pZ1ZZM1ZYaGJyRG9iQXJvbjZBZkJlZjRibE9PMHNVTFdWMVRobzVMMmc3TEs1alc1am41bjRYSDkzNEYydTNPazhwT211T25HOWwzZDVySy1zWVpYQ3g3NENqVDJmN3BjZ3FiQ2F3cExBMmx2T1VqOVFublRiaVpkQzc5LXF4YVpZWXRUOVc4dEFVQllpQllJTUY3UFl4ME1KaFVWUFBWM1NMR0syTkJURTF2bWM2c1RFZ2l3ODltcTRPakJLZ3hUTTNNa2paRGJzMm1OVktqUjhHODBYYjlKX3VMOWYzRzI1c1RBemdVcDB5ZEItaHR3OGFwRDlmRkhSZzhYSEdDZTVmSHNGTDNpejJvb0d0RTRkeHZSQ1ZDLW5lY3FtRG1KMS1jMEZkVDE4djRWX2ZZcGc3QXpNQzNYT2xQLXNiOE5KS2d6RUZOZldseUtHWXhaRkt6R0RhZnBBYjdEYUloWVpmU2Faa3Ftbnh4eHpDbGVrSTk2T2ZnZElsbkgtUEd6dW5Nb2FvcElxN0lPek1rZGVPazBpUFF6VmtDUGxxc0M0LXZ1enFJODZvLTQxbHZGVmhpU20yeEozRHJWQzBXbGpVUjlPVVZ0R2JoNEF3Zm8tb3hMdVFLMW1Ma2pqLW1yNkQ3d3ktNDBrcmdOV1ZLeEpET0Z4UEhnOVBQc09xQlBvbWpwUXpkNUowYWg1RmdvNk9uODJlVmVRZzdHRzkwUjZZbVBSR2dFVFVQUWl0XzRHZGE0U0xnTVZDSktZdGZvZHY2WWQwZ2pSZzJEVW5qZUtOVUp3c1RjSEhyYWs3MXNRaVNfVmRtekZsSm1CNjVhYjFlSE9VQ2I4SmtYalF1XzR3UmZXdnhuc1VmcExWd1VMMGNmNi1YWmp1RVpIUF9PaGlGWDlzWldTSjBLS1RfVFI4RzFTbWpFcTZUbXhKa1E1RHRnV014OWNwTjJSRlNwcWFyU1V0STJtUWNIM191U0tERjNuY1lhWDl0Vk55ZGpEOFloUkdwWHVQdk4wWHZyejBKTklHLVBWeVlqUUJPdXNvOF9GeV9yX0ctSmVhdVNxMFRpVUhEUVM0Yl96ZDlfQWxMM2wySzZJdzAyQkVhWEhwb2Jpd3pFeEdFeU4weWFVMDRVNjliUEl5TGxIcy1sVVpnMTl5Z3hOR2pzdkxDaktqQ2gzdlhxdDRsMnlZZmFnY0RHSzdWcXpUYzhDWG5wZ1p1bnR3LnRTWm9BN2tNdGItRVJtRWs3d2MyT2c"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultkeydecrypt.json",
    "content": "{\n\t\"kid\": \"https://kvvaultapilivetest.vault.azure.net/keys/myKey/003a927b194f4f6a9070ebdbdce57c59\",\n\t\"value\": \"R29sZCUyNTIxJTJCR29sZCUyNTIxJTJCR29sZCUyQmZyb20lMkJ0aGUlMkJBbWVyaWNhbiUyQlJpdmVyJTI1MjE\"\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultkeydecryptrequestbody.json",
    "content": "{\n\t\"alg\": \"RSA-OAEP\",\n\t\"value\": \"0_S8pyjjnGRlcbDa-Lt0jYjMXpXrf9Fat3elx-fSOg3dj6mYgEEs6kt79OMD4MFmVyOt6umeWAfdDIkNVnqb5fgyWceveh9wN-37jc5CFgG2PF3XIA6RII-HF2BkBcVa9KcAX3_di4KQE70PXgHf-dlz_RgLOJILeG50wzFeBFCLsjEEPp3itmoaiE6vfDidCRm5At8Vjka0G-N_afwkIijfQZLT0VaXvL39cIJE2QN3HJPZM8YPUlkFlYnY4GIRyRWSBpK_KYuVufzUGtDi6Sh8pUa67ppa7DHVZlixlmnVqI3Oeg6XUvMqbFFqVSrcNbRQDwVGL3cUtK-KB1PfKg\"\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultkeyencrypt.json",
    "content": "{\n\t\"kid\": \"https://kvvaultapilivetest.vault.azure.net/keys/myKey/003a927b194f4f6a9070ebdbdce57c59\",\n\t\"value\": \"0_S8pyjjnGRlcbDa-Lt0jYjMXpXrf9Fat3elx-fSOg3dj6mYgEEs6kt79OMD4MFmVyOt6umeWAfdDIkNVnqb5fgyWceveh9wN-37jc5CFgG2PF3XIA6RII-HF2BkBcVa9KcAX3_di4KQE70PXgHf-dlz_RgLOJILeG50wzFeBFCLsjEEPp3itmoaiE6vfDidCRm5At8Vjka0G-N_afwkIijfQZLT0VaXvL39cIJE2QN3HJPZM8YPUlkFlYnY4GIRyRWSBpK_KYuVufzUGtDi6Sh8pUa67ppa7DHVZlixlmnVqI3Oeg6XUvMqbFFqVSrcNbRQDwVGL3cUtK-KB1PfKg\"\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultkeyencryptrequestbody.json",
    "content": "{\n\t\"alg\": \"RSA-OAEP\",\n\t\"value\": \"R29sZCUyNTIxJTJCR29sZCUyNTIxJTJCR29sZCUyQmZyb20lMkJ0aGUlMkJBbWVyaWNhbiUyQlJpdmVyJTI1MjE\"\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultkeysign.json",
    "content": "{\n\t\"kid\": \"https://kvvaultapilivetest.vault.azure.net/keys/myKey/003a927b194f4f6a9070ebdbdce57c59\",\n\t\"value\": \"uO0r4P1cB-fKsDZ8cj5ahiNw8Tdsudt5zLCeEKOt29LAlPDpeGx9Q1SOFNaR7JlRYVelxsohdzvydwX8ao6MLnqlpdEj0Xt5Aadp-kN84AXW238gabS1AUyiWILCmdsBFeRU4wTRSxz2qGS_0ztHkaNln32P_9GJC72ZRlgZoVA4C_fowZolUoCWGj4V7fAzcSoiNYipWP0HkFe3xmuz-cSQg3CCAs-MclHHfMeSagLJZZQ9bpl5LIr-Ik89bNtqEqyP7Jb_fCgHajAx2lUFcRZhSIKuCfrLPMl6wzejQ2rQXX-ixEkDa73dYaPIrVW4IL3iC0UfxnfxYffHJ7QCRw\"\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultkeysignrequestbody.json",
    "content": "{\n\t\"alg\": \"RS256\",\n\t\"value\": \"FvabKT6qGwpml59iHUJ72DZ4XyJcJ8bgpgFA4_8JFmM\"\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultkeyunwrap.json",
    "content": "{\n\t\"kid\": \"https://kvvaultapilivetest.vault.azure.net/keys/myKey/003a927b194f4f6a9070ebdbdce57c59\",\n\t\"value\": \"YxzoHR65aFwD2_IOiZ5rD08jMSALA1y7b_yYW0G3hyI\"\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultkeyunwraprequestbody.json",
    "content": "{\n\t\"alg\": \"RSA-OAEP\",\n\t\"value\": \"1jcTlu3KJNDBYydhaH9POWOo0tAPGkpsZVizCkHpC3g_9Kg91Q3HKK-rfZynn5W5nVPM-SVFHA3JTankcXX8gx8GycwUh4pMoyil_DV35m2QjyuiTln83OJXw-nMvRXyKdVfF7nyRcs256kW7gthAOsYUVBrfFS7DFFxsXqLNREsA8j85IqIXIm8pAB3C9uvl1I7SQhLvrwZZXXqjeCWMfseVJwWgsQFyyqH2P0f3-xnngV7cvik2k3Elrk3G_2CuJCozIIrANg9zG9Z8DrwSNNm9YooxWkSu0ZeDLOJ0bMdhcPGGm5OvKz3oZqX-39yv5klNlCRbr0q7gqmI0x25w\"\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultkeyverify.json",
    "content": "{\n\t\"value\": true\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultkeyverifyrequestbody.json",
    "content": "{\n\t\"alg\": \"RS256\",\n\t\"digest\": \"FvabKT6qGwpml59iHUJ72DZ4XyJcJ8bgpgFA4_8JFmM\",\n\t\"value\": \"FvabKT6qGwpml59iHUJ72DZ4XyJcJ8bgpgFA4_8JFmM\",\"value\":\"uO0r4P1cB-fKsDZ8cj5ahiNw8Tdsudt5zLCeEKOt29LAlPDpeGx9Q1SOFNaR7JlRYVelxsohdzvydwX8ao6MLnqlpdEj0Xt5Aadp-kN84AXW238gabS1AUyiWILCmdsBFeRU4wTRSxz2qGS_0ztHkaNln32P_9GJC72ZRlgZoVA4C_fowZolUoCWGj4V7fAzcSoiNYipWP0HkFe3xmuz-cSQg3CCAs-MclHHfMeSagLJZZQ9bpl5LIr-Ik89bNtqEqyP7Jb_fCgHajAx2lUFcRZhSIKuCfrLPMl6wzejQ2rQXX-ixEkDa73dYaPIrVW4IL3iC0UfxnfxYffHJ7QCRw\"\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultkeywrap.json",
    "content": "{\n\t\"kid\": \"https://kvvaultapilivetest.vault.azure.net/keys/myKey/003a927b194f4f6a9070ebdbdce57c59\",\n\t\"value\": \"1jcTlu3KJNDBYydhaH9POWOo0tAPGkpsZVizCkHpC3g_9Kg91Q3HKK-rfZynn5W5nVPM-SVFHA3JTankcXX8gx8GycwUh4pMoyil_DV35m2QjyuiTln83OJXw-nMvRXyKdVfF7nyRcs256kW7gthAOsYUVBrfFS7DFFxsXqLNREsA8j85IqIXIm8pAB3C9uvl1I7SQhLvrwZZXXqjeCWMfseVJwWgsQFyyqH2P0f3-xnngV7cvik2k3Elrk3G_2CuJCozIIrANg9zG9Z8DrwSNNm9YooxWkSu0ZeDLOJ0bMdhcPGGm5OvKz3oZqX-39yv5klNlCRbr0q7gqmI0x25w\"\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultkeywraprequestbody.json",
    "content": "{\n\t\"alg\": \"RSA-OAEP\",\n\t\"value\": \"YxzoHR65aFwD2_IOiZ5rD08jMSALA1y7b_yYW0G3hyI\"\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultlist.json",
    "content": "{\n  \"value\": [{\n    \"id\": \"/subscriptions/3fee811e-11bf-4b5c-9c62-a2f28b517724/resourceGroups/rg-vaultapilivetest-jims/providers/Microsoft.KeyVault/vaults/kvvaultapilivetest\",\n    \"name\": \"kvvaultapilivetest\",\n    \"type\": \"Microsoft.KeyVault/vaults\",\n    \"location\": \"westeurope\",\n    \"tags\": {},\n    \"properties\": {\n      \"sku\": {\n        \"family\": \"A\",\n        \"name\": \"standard\"\n      },\n      \"tenantId\": \"72f988bf-86f1-41af-91ab-2d7cd011db47\",\n      \"accessPolicies\": [{\n        \"tenantId\": \"72f988bf-86f1-41af-91ab-2d7cd011db47\",\n        \"objectId\": \"5a7f4cb9-ce9d-4b31-87ce-f61083c4b0ea\",\n        \"permissions\": {\n          \"certificates\": [\"Get\", \"List\", \"Update\", \"Create\", \"Import\", \"Delete\", \"ManageContacts\", \"ManageIssuers\", \"GetIssuers\", \"ListIssuers\", \"SetIssuers\", \"DeleteIssuers\", \"Purge\", \"Recover\"],\n          \"keys\": [\"Get\", \"List\", \"Update\", \"Create\", \"Import\", \"Delete\", \"Recover\", \"Backup\", \"Restore\", \"Purge\"],\n          \"secrets\": [\"Get\", \"List\", \"Set\", \"Delete\", \"Recover\", \"Backup\", \"Restore\", \"Purge\"],\n          \"storage\": []\n        }\n      }],\n      \"enabledForDeployment\": false,\n      \"vaultUri\": \"https://kvvaultapilivetest.vault.azure.net/\"\n    }\n  }],\n  \"nextLink\": \"https://management.azure.com/subscriptions/3fee811e-11bf-4b5c-9c62-a2f28b517724/resourcegroups/rg-vaultapilivetest-jims/providers/Microsoft.KeyVault/vaults?api-version=2016-10-01&$skiptoken=a3Z2YXVsdGFwaWxpdmV0ZXN0\"\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultlistcertificateissuers.json",
    "content": "{\n\t\"value\": [{\n\t\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/certificates/issuers/globalsign01\",\n\t\t\"provider\": \"GlobalSign\"\n\t}],\n\t\"nextLink\": null\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultlistcertificates.json",
    "content": "{\n\t\"value\": [{\n\t\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/certificates/myCertificate\",\n\t\t\"x5t\": \"K7HXO6YIK6xwCX8W1InUKsJV9Rk\",\n\t\t\"attributes\": {\n\t\t\t\"enabled\": true,\n\t\t\t\"nbf\": 1509345867,\n\t\t\t\"exp\": 1540882467,\n\t\t\t\"created\": 1509346467,\n\t\t\t\"updated\": 1509346472\n\t\t},\n\t\t\"tags\": {\n\t\t\t\"selfsigned\": \"true\"\n\t\t}\n\t}, {\n\t\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/certificates/myImportableCertificate\",\n\t\t\"x5t\": \"-qEnW6P9TdfOOXzbNQNS5ZKveRo\",\n\t\t\"attributes\": {\n\t\t\t\"enabled\": true,\n\t\t\t\"nbf\": 1509231134,\n\t\t\t\"exp\": 1541631134,\n\t\t\t\"created\": 1509346469,\n\t\t\t\"updated\": 1509346469\n\t\t}\n\t}],\n\t\"nextLink\": null\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultlistcertificateversions.json",
    "content": "{\n\t\"value\": [{\n\t\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/certificates/myCertificate/b73ba4610dc24dca946f76933f6590dd\",\n\t\t\"x5t\": \"K7HXO6YIK6xwCX8W1InUKsJV9Rk\",\n\t\t\"attributes\": {\n\t\t\t\"enabled\": true,\n\t\t\t\"nbf\": 1509345867,\n\t\t\t\"exp\": 1540882467,\n\t\t\t\"created\": 1509346467,\n\t\t\t\"updated\": 1509346472\n\t\t},\n\t\t\"tags\": {\n\t\t\t\"selfsigned\": \"true\"\n\t\t}\n\t}],\n\t\"nextLink\": null\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultlistdeleted.json",
    "content": "{\n\t\"value\": [{\n\t\t\"id\": \"/subscriptions/3fee811e-11bf-4b5c-9c62-a2f28b517724/providers/Microsoft.KeyVault/locations/westeurope/deletedVaults/kvvaultapilivetest\",\n\t\t\"name\": \"kvvaultapilivetest\",\n\t\t\"type\": \"Microsoft.KeyVault/deletedVaults\",\n\t\t\"properties\": {\n\t\t\t\"vaultId\": \"/subscriptions/3fee811e-11bf-4b5c-9c62-a2f28b517724/resourceGroups/rg-vaultapilivetest-jims/providers/Microsoft.KeyVault/vaults/kvvaultapilivetest\",\n\t\t\t\"location\": \"westeurope\",\n\t\t\t\"tags\": {},\n\t\t\t\"deletionDate\": \"2017-10-29T22:06:02Z\",\n\t\t\t\"scheduledPurgeDate\": \"2018-01-27T22:06:02Z\"\n\t\t}\n\t}],\n\t\"nextLink\": \"https://management.azure.com/subscriptions/3fee811e-11bf-4b5c-9c62-a2f28b517724/providers/Microsoft.KeyVault/deletedVaults?api-version=2016-10-01&%24skiptoken=HY1db4IwGEb%2fS7PsrpQyUCQxiwts0QkMbDHxjo8Xh%2bUrtLgN438f8fJJzjnPDbXwq%2fZVKyRybujoHZjH4%2fDLQw76VqqXDiFN2qZnaKBVWjqNA2h51xA5ZjIfql5VXSvJSwlgUwqY0qzEZmbleJUvDJwapWFnFl0uDZP0Q3etChgk8at86GRXKu0T%2fpJ0rBUpoAYFxWPI17Sv8HUm5%2fja0OkCUx3r9PlJivmxE9CuuUiOcbJjMY%2ffmZfwA1%2bFe17z0t1Sn50t%2fyLM4LKZgknogZubPkvsQOzeQrdwQ49PMRNT4J3cSN9akfCNaDp9%2bOzh%2fERsg%2b73fw%3d%3d\"\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultlistdeletedcertificates.json",
    "content": "{\n\t\"value\": [{\n\t\t\"recoveryId\": \"https://kvvaultapilivetest.vault.azure.net/deletedcertificates/myRecoverableCertificate\",\n\t\t\"deletedDate\": 1509346545,\n\t\t\"scheduledPurgeDate\": 1517122545,\n\t\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/certificates/myRecoverableCertificate\",\n\t\t\"x5t\": \"-qEnW6P9TdfOOXzbNQNS5ZKveRo\",\n\t\t\"attributes\": {\n\t\t\t\"enabled\": true,\n\t\t\t\"nbf\": 1509231134,\n\t\t\t\"exp\": 1541631134,\n\t\t\t\"created\": 1509346510,\n\t\t\t\"updated\": 1509346510,\n\t\t\t\"recoveryLevel\": \"Recoverable+Purgeable\"\n\t\t}\n\t}],\n\t\"nextLink\": null\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultlistdeletedkeys.json",
    "content": "{\n\t\"value\": [{\n\t\t\"recoveryId\": \"https://kvvaultapilivetest.vault.azure.net/deletedkeys/myRecoverableKey\",\n\t\t\"deletedDate\": 1509335960,\n\t\t\"scheduledPurgeDate\": 1517111960,\n\t\t\"kid\": \"https://kvvaultapilivetest.vault.azure.net/keys/myRecoverableKey\",\n\t\t\"attributes\": {\n\t\t\t\"enabled\": true,\n\t\t\t\"created\": 1509335950,\n\t\t\t\"updated\": 1509335950,\n\t\t\t\"recoveryLevel\": \"Recoverable+Purgeable\"\n\t\t}\n\t}],\n\t\"nextLink\": null\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultlistdeletedsecrets.json",
    "content": "{\n\t\"value\": [{\n\t\t\"recoveryId\": \"https://kvvaultapilivetest.vault.azure.net/deletedsecrets/myRecoverableSecret\",\n\t\t\"deletedDate\": 1509335980,\n\t\t\"scheduledPurgeDate\": 1517111980,\n\t\t\"contentType\": \"aNewSecretKey\",\n\t\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/secrets/myRecoverableSecret\",\n\t\t\"attributes\": {\n\t\t\t\"enabled\": true,\n\t\t\t\"created\": 1509335958,\n\t\t\t\"updated\": 1509335958,\n\t\t\t\"recoveryLevel\": \"Recoverable+Purgeable\"\n\t\t}\n\t}],\n\t\"nextLink\": null\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultlistkeys.json",
    "content": "{\n  \"value\": [{\n    \"kid\": \"https://kvvaultapilivetest.vault.azure.net/keys/myCertificate\",\n    \"attributes\": {\n      \"enabled\": true,\n      \"nbf\": 1509313915,\n      \"exp\": 1540850515,\n      \"created\": 1509314515,\n      \"updated\": 1509314515,\n      \"recoveryLevel\": \"Purgeable\"\n    },\n    \"managed\": true\n  }, {\n    \"kid\": \"https://kvvaultapilivetest.vault.azure.net/keys/myImportableCertificate\",\n    \"attributes\": {\n      \"enabled\": true,\n      \"nbf\": 1509231134,\n      \"exp\": 1541631134,\n      \"created\": 1509314521,\n      \"updated\": 1509314521,\n      \"recoveryLevel\": \"Purgeable\"\n    },\n    \"managed\": true\n  }, {\n    \"kid\": \"https://kvvaultapilivetest.vault.azure.net/keys/myImportKey\",\n    \"attributes\": {\n      \"enabled\": true,\n      \"created\": 1509314522,\n      \"updated\": 1509314522,\n      \"recoveryLevel\": \"Purgeable\"\n    }\n  }, {\n    \"kid\": \"https://kvvaultapilivetest.vault.azure.net/keys/myKey\",\n    \"attributes\": {\n      \"enabled\": true,\n      \"created\": 1509314506,\n      \"updated\": 1509314506,\n      \"recoveryLevel\": \"Purgeable\"\n    }\n  }],\n  \"nextLink\": null\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultlistsecrets.json",
    "content": "{\n\t\"value\": [{\n\t\t\"contentType\": \"application/x-pkcs12\",\n\t\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/secrets/myCertificate\",\n\t\t\"managed\": true,\n\t\t\"attributes\": {\n\t\t\t\"enabled\": true,\n\t\t\t\"nbf\": 1509335314,\n\t\t\t\"exp\": 1540871914,\n\t\t\t\"created\": 1509335914,\n\t\t\t\"updated\": 1509335920,\n\t\t\t\"recoveryLevel\": \"Purgeable\"\n\t\t},\n\t\t\"tags\": {\n\t\t\t\"selfsigned\": \"true\"\n\t\t}\n\t}, {\n\t\t\"contentType\": \"application/x-pem-file\",\n\t\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/secrets/myImportableCertificate\",\n\t\t\"managed\": true,\n\t\t\"attributes\": {\n\t\t\t\"enabled\": true,\n\t\t\t\"nbf\": 1509231134,\n\t\t\t\"exp\": 1541631134,\n\t\t\t\"created\": 1509335917,\n\t\t\t\"updated\": 1509335917,\n\t\t\t\"recoveryLevel\": \"Purgeable\"\n\t\t}\n\t}, {\n\t\t\"contentType\": \"testSecretKey\",\n\t\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/secrets/mySecret\",\n\t\t\"attributes\": {\n\t\t\t\"enabled\": true,\n\t\t\t\"created\": 1509335932,\n\t\t\t\"updated\": 1509335932,\n\t\t\t\"recoveryLevel\": \"Purgeable\"\n\t\t}\n\t}],\n\t\"nextLink\": null\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultmergecertificate.json",
    "content": "{\n  \"id\": \"https://jimskv1.vault.azure.net/certificates/jmskv1cert6/d8f385d3741b4b1cba9c002299e892dd\",\n  \"kid\": \"https://jimskv1.vault.azure.net/keys/jmskv1cert6/d8f385d3741b4b1cba9c002299e892dd\",\n  \"sid\": \"https://jimskv1.vault.azure.net/secrets/jmskv1cert6/d8f385d3741b4b1cba9c002299e892dd\",\n  \"x5t\": \"SQix1jyV9XeF2Q8MCecpUr0etk4\",\n  \"cer\": \"MIIEQTCCAikCAhABMA0GCSqGSIb3DQEBCwUAMF4xCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQKDA1BQ01FIFRlc3QgTHRkMSIwIAYDVQQDDBlBQ01FIFRlc3QgSW50ZXJtZWRpYXRlIENBMB4XDTE3MTEyODIzMDkxMVoXDTE4MTIwODIzMDkxMVowbjELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAkNBMRIwEAYDVQQHEwlBbGxlZ2hhbnkxDTALBgNVBAoTBEFDTUUxFDASBgNVBAsTC0VuZ2luZWVyaW5nMRkwFwYDVQQDExBBQ01FIEZvb2JhciBDZXJ0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwE0Gu/rJlbkqL0ynSbkCdrM+XP4dis/QNPz819ybXXpIX8HfkmAxrpLmfWh36KlflFYgpuV/J5lnJKlRmPWWOFjizAhq0dBijJUdLf6+QuImDjijd/nkO5SeQApZ4D50imTJL81vs2vwAfcCLwdlf7MNrMIfBsyjRSJh/Phjqib6kcYWcz6I6yTfkcsXcUB1JgR8KnQdVy0gYDu1MacHu2VYuS35HpPcQyXRqR1Ky9qh16+OhheRJw03ghEiPMcKbWS5NRgw/l/itoST2Qd6BzJTHUkJaXHNSO9fNF/fAccqECp0ZfaCSrfZs47EcjCv+N7bvrqfFl4BhB77tb7ZAQIDAQABMA0GCSqGSIb3DQEBCwUAA4ICAQCbpjL5XGC3T6gWU8sxCbS0VBmgamyvSHA8jLkWUXQfPirGFwgdGN7394mYViVU0qe6ZqmnhlhqZ1h6VbkBMVwzp3KlRhuoz/fXlW+TFvEC8Q3F+7oUdHn8w3EMyjKA5EbLzRIYXBizdbfEn8eJynjyWEdOaJpMmy9au/oFSqpmZDcxWW2SKq4j+Pqjhr+Ig4BmTVvwR6iEERPYQI4pv0OxRa7xA6Hb8NF02TyDzV7k02kN9PL/QO2dh9f3U0YY5XlV1HQzQ/BmavudPT1MiuH0CVSlCHE/JetXdJdWZA4HRiwXJn+5K8MgE5i1hjjXN/dLuaY8vItJzyrgxGRtRZoJA8t7B3QJjDECmey2m0K0qjYu7l1jAVFBWaqDdJQLmnKxViuz0MF4uFqgveW6CZEMcdqwZQ2cmZPlmcjneT0veBBh5qCdFNFM9pYDn0wqt5ruK+vqHkqJdMToBPNaBfGX10ADlB8rKW24eve+2c0iVmorJuTPdOqm2L9NKGpf2scvZZU4n/khkGKihrSOLygeLZ6SQc74cRL35FmzJqqKKpZtG9/a91dkJDz2XUiTO5TialaOU9+A1+Xrzj8LGG9JnB0KizF5dOd5mbZTROr3VCexRxyTrtZLpeJK+lYQLkDQ5ixWnd2sikym4hy3+NZ1g6nE+GQpqSALB4YnsFgUdg==\",\n  \"attributes\": {\n    \"enabled\": true,\n    \"nbf\": 1511910551,\n    \"exp\": 1544310551,\n    \"created\": 1511911458,\n    \"updated\": 1511911458,\n    \"recoveryLevel\": \"Purgeable\"\n  },\n  \"policy\": {\n    \"id\": \"https://jimskv1.vault.azure.net/certificates/jmskv1cert6/policy\",\n    \"key_props\": {\n      \"exportable\": true,\n      \"kty\": \"RSA\",\n      \"key_size\": 2048,\n      \"reuse_key\": true\n    },\n    \"secret_props\": {\n      \"contentType\": \"application/x-pem-file\"\n    },\n    \"x509_props\": {\n      \"subject\": \"C=US, ST=CA, L=Alleghany, O=ACME, OU=Engineering, CN=ACME Foobar Cert\",\n      \"sans\": {\n        \"emails\": [],\n        \"dns_names\": [],\n        \"upns\": []\n      },\n      \"ekus\": [\n        \"1.3.6.1.5.5.7.3.1\"\n      ],\n      \"key_usage\": [\n        \"cRLSign\",\n        \"dataEncipherment\",\n        \"digitalSignature\",\n        \"keyAgreement\",\n        \"keyCertSign\",\n        \"keyEncipherment\"\n      ],\n      \"validity_months\": 24,\n      \"basic_constraints\": {\n        \"ca\": false\n      }\n    },\n    \"lifetime_actions\": [],\n    \"issuer\": {\n      \"name\": \"Unknown\"\n    },\n    \"attributes\": {\n      \"enabled\": true,\n      \"created\": 1511910301,\n      \"updated\": 1511910301\n    }\n  },\n  \"pending\": {\n    \"id\": \"https://jimskv1.vault.azure.net/certificates/jmskv1cert6/pending\"\n  }\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultmergecertificaterequestbody.json",
    "content": "{\n    \"attributes\": {\n        \"enabled\": true\n    },\n    \"x5c\": [\n        \"MIIFljCCA36gAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwVjELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAoMDUFDTUUgVGVzdCBMdGQxGjAYBgNVBAMMEUFDTUUgVGVzdCBSb290IENBMB4XDTE3MTEyODIwMDA1NVoXDTI3MTEyNjIwMDA1NVowXjELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAoMDUFDTUUgVGVzdCBMdGQxIjAgBgNVBAMMGUFDTUUgVGVzdCBJbnRlcm1lZGlhdGUgQ0EwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDU1CRXpOEOzNxom8xwA3kYb4kmc3JX8cSuWZKoaPm8KvhsgYOkH+1z4dt2OC/FtSaWJuMZrSTJs/lFmdyE1yuyRBhyqwCK3ZnFxCG10NXiHgj+uHK8ajNJQDitFuz4yLwgp6R91UhuCPPMAKL3eDwC/PPqnT6/D/EPG7eotlokUrpNrhTdz5YYH4VhXwM3VKkIdtSkPQTMftZ0Rbzd0u4sJlsF+RtXVY7/zzg2st0d2vEddpaOENFQfYT7D8C9VsKqo13sClQGoKoPa20a1Yvh65bK2P0SDzhbIu2xQCeis+wC/h0ZZrwCW5/ivCFo4DILk9269LaN4xqpnwJz9QrNFxwglktZm2j7gm4K9BH5a437E6xMvo7WXYwt+0305lLN4khL2ZhagFrvEYG6SLgJwZRWTAE8IsOC9Oyrq0CgpX+KpGkGMpokrgH8aWVCSgQxsUCPJYaBwMgAWepuf3Rx54cUV66vYb7z2NlSvV7JNvtNdXFFjddOfdoQC0QIVOJM1sOgUN/9negFRUtspudB397h+ncvnLnlrg+QaTZNjfCvP4YV+t0eMmlyhBpxIKxPnP0vQCVH9JfpJeZxpY9hFwbxfKcsNLhYHC/22ntbr1UMiIV1HDN8o1gQb6KwyPnS4SVggnf+WPqO4xhXCtwqSDQSAuVe9t03xAs1SGvt8wIDAQABo2YwZDAdBgNVHQ4EFgQURR0ZtFNyLfu1x57+yYiybG149JQwHwYDVR0jBBgwFoAUSCW8FQ+iFqE5L3zx0+2Onc3d1vYwEgYDVR0TAQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAYYwDQYJKoZIhvcNAQELBQADggIBAMo/VnCd/ndvOfBrI29QhBcwaHEgiC9QUA9u63EhAFGHaThtSd8dFnJLhOQaS2+rYC1nUhkZa03ImceTQpWsGpXOm/sFIAWojzgxqTEopCP5OUxVu6FuJMOGaUvaupGLIJSrUpzpn31NJxThOANEtd0sbMK5fk7sYXLlLNeCOfLu/dytit5jfDsUERJQGTi2YmzIYgFli0ECdswgxAb3b1klKvqOcXZI4K6WkCl5L/wjEP5XygnfyXJ6nMTSLpxuD7dRpqyitmauavfscGpLwYMArx+5gn2jwlq4TIDWdaKi86Oz8VAg+X0C5qBcAdx6k8pFUSjeD2kvykNbEdxBtkD4dgUn5UDmqB2IfW5UiL04cDBaxijDLbsYvjOE+wiXbESxnZf9bQXdeFSemARIWmE6to0uOmdp+snetB88Nw8EQ6faL9aKGBYPI3+KDy1IdMtyU50dMj7BSogZeBHh+6B/1qqlp3VGm5/PBaoyZJLRgx7VQNYFcPjUk0iLaBK7bqJ1CFkr5YX3/Ypjty4u1BD1LxEG2u60Q6PpLgBGGxqXDH6KpNkH2Z9mdagLL+HfZDf73m+J2PD0puLzVVcvzwPRf3nJyyh7ALnG9gd5gl8ksy6uHBizAOmzO0Ize7B8/1he1dSxZQ7wnHIuZ9HSvTvVHv8ST2l7XkKGaB0+BBHR\",\n        \"MIIFkjCCA3qgAwIBAgIJANPuNc8d4n46MA0GCSqGSIb3DQEBCwUAMFYxCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQKDA1BQ01FIFRlc3QgTHRkMRowGAYDVQQDDBFBQ01FIFRlc3QgUm9vdCBDQTAeFw0xNzExMjgxOTU3MDJaFw0zNzExMjMxOTU3MDJaMFYxCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQKDA1BQ01FIFRlc3QgTHRkMRowGAYDVQQDDBFBQ01FIFRlc3QgUm9vdCBDQTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAOP2me/TzHq4fGve9X2fdDXQFayCq4XZ/mijLkerAPoka3T7lNfO4FI0jvnPNbrf6KZ2YolwiQ04OnFekder5WoVuoQFKZMLCFulHK/+GpyJPdE0fRRrbIsnSRiTvX7fvarHilQKu1B5vKyn6SLzNbvA8+zKJuCiA+ghIxiIKTI3wenzp/uuaWS9+qUXISINJnitgNxD9FnV3CSvAbuzTWfoWDNjS4q7BqUsY6sHCLCmds8kd2ah/CLOmraC7diwA5okE6CCSNzMI7fSzAztRx4BmYW9EgZjwacoWPUp+lGM9ZxRhPcD/euk91Qks10h04EkUXV2HpSVwtNYoSuFBADlNYw7mmn+UpzvG7wBUusDbjhDWG22i5IyOBRuuiUGYgDzleo7v7b9W8ocn5/q4cgEryed7LRxspP7wa614DcHz/6Rmg7CD1dH7zo96EyDl4tlyFB37XQzDtdvs0tU9ahQxFMVj+wcNEnVf7IBv93ukv5YA0sgcfmanLu5fiRBT+hw2ADb4OWNFhR+ZnuTpAtsc27bbjrJ6h6cwYnUFLdYiOVTTFYZjVKLlIhfpB1gNhzZFeiYwZBeU8bvmhD3xASApNyJL93PqTJYHxVYv9rfW5hcGkAJz+0gEBXSDEuKekm0vEujdMDMo9Atkv6HR3oeQttd3mRL81PfcxAqQbC1AgMBAAGjYzBhMB0GA1UdDgQWBBRIJbwVD6IWoTkvfPHT7Y6dzd3W9jAfBgNVHSMEGDAWgBRIJbwVD6IWoTkvfPHT7Y6dzd3W9jAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBhjANBgkqhkiG9w0BAQsFAAOCAgEAlLFwOq4VgtDEJ6vpWn21GfweuB2Saz8DYoDBrvcXLGImArfp9n0baeXqa9qqR8Tu12ZF2dEkvQsFnZ6gzobmctw3k4c+Oz0pJ5/iFUTotkqhFf8/RcZCwEk0pcEyAqlQ2LehMyB5UvFhSg54uucj4Ofp1CSjQ59GSe7u9LvHO0cEOdN7jQS9OaAnP03WYktDFTupxD+7xyQsIKePilCKVYgOAlJPKMAaaYcSGMGljUOizLVNYPLaFermcOzdaoyHz6btjq56febLQ2c0VSrL1C2+qOaVbJz0oQSEwt6meADvO8rcP/ZNK9T0kmDxbQzqpKZ31bt/d0iRBygGaFy2vYgybwo3iPGqPTInv2FaTRvWnHP/NlbdNKFwd876hMM+8m9PcNRcIeM+yFwD0aCJtfqorxdN2nNEioP5X08yVnexO9ywkDcAXQTj4RV9TyGlzZRc+1JM1LkhIgLvI6OAOxmrnXnHW08Vzo3yhK72NtnDukU4UcCAHOao6Vq+MJu2Ngb11WBlZulObcEoccxhpx929xIeOj67ZSLOEopP7z+fesjgABc4HQVQQ0v37eiYvVT3Bzz+TklfL/gEVLAk6AqLcFizs9vND2bTrGDgE8AWEX77lBsLGg92ofPXeXZsHsh43m2fRjAnroXQVsziQ0zJgHcA7OmLlB8mkb8fl3E=\",\n        \"MIIEQTCCAikCAhABMA0GCSqGSIb3DQEBCwUAMF4xCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQKDA1BQ01FIFRlc3QgTHRkMSIwIAYDVQQDDBlBQ01FIFRlc3QgSW50ZXJtZWRpYXRlIENBMB4XDTE3MTEyODIzMDkxMVoXDTE4MTIwODIzMDkxMVowbjELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAkNBMRIwEAYDVQQHEwlBbGxlZ2hhbnkxDTALBgNVBAoTBEFDTUUxFDASBgNVBAsTC0VuZ2luZWVyaW5nMRkwFwYDVQQDExBBQ01FIEZvb2JhciBDZXJ0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwE0Gu/rJlbkqL0ynSbkCdrM+XP4dis/QNPz819ybXXpIX8HfkmAxrpLmfWh36KlflFYgpuV/J5lnJKlRmPWWOFjizAhq0dBijJUdLf6+QuImDjijd/nkO5SeQApZ4D50imTJL81vs2vwAfcCLwdlf7MNrMIfBsyjRSJh/Phjqib6kcYWcz6I6yTfkcsXcUB1JgR8KnQdVy0gYDu1MacHu2VYuS35HpPcQyXRqR1Ky9qh16+OhheRJw03ghEiPMcKbWS5NRgw/l/itoST2Qd6BzJTHUkJaXHNSO9fNF/fAccqECp0ZfaCSrfZs47EcjCv+N7bvrqfFl4BhB77tb7ZAQIDAQABMA0GCSqGSIb3DQEBCwUAA4ICAQCbpjL5XGC3T6gWU8sxCbS0VBmgamyvSHA8jLkWUXQfPirGFwgdGN7394mYViVU0qe6ZqmnhlhqZ1h6VbkBMVwzp3KlRhuoz/fXlW+TFvEC8Q3F+7oUdHn8w3EMyjKA5EbLzRIYXBizdbfEn8eJynjyWEdOaJpMmy9au/oFSqpmZDcxWW2SKq4j+Pqjhr+Ig4BmTVvwR6iEERPYQI4pv0OxRa7xA6Hb8NF02TyDzV7k02kN9PL/QO2dh9f3U0YY5XlV1HQzQ/BmavudPT1MiuH0CVSlCHE/JetXdJdWZA4HRiwXJn+5K8MgE5i1hjjXN/dLuaY8vItJzyrgxGRtRZoJA8t7B3QJjDECmey2m0K0qjYu7l1jAVFBWaqDdJQLmnKxViuz0MF4uFqgveW6CZEMcdqwZQ2cmZPlmcjneT0veBBh5qCdFNFM9pYDn0wqt5ruK+vqHkqJdMToBPNaBfGX10ADlB8rKW24eve+2c0iVmorJuTPdOqm2L9NKGpf2scvZZU4n/khkGKihrSOLygeLZ6SQc74cRL35FmzJqqKKpZtG9/a91dkJDz2XUiTO5TialaOU9+A1+Xrzj8LGG9JnB0KizF5dOd5mbZTROr3VCexRxyTrtZLpeJK+lYQLkDQ5ixWnd2sikym4hy3+NZ1g6nE+GQpqSALB4YnsFgUdg==\"\n    ]\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultmergex5c-1.txt",
    "content": "MIIFljCCA36gAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwVjELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAoMDUFDTUUgVGVzdCBMdGQxGjAYBgNVBAMMEUFDTUUgVGVzdCBSb290IENBMB4XDTE3MTEyODIwMDA1NVoXDTI3MTEyNjIwMDA1NVowXjELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAoMDUFDTUUgVGVzdCBMdGQxIjAgBgNVBAMMGUFDTUUgVGVzdCBJbnRlcm1lZGlhdGUgQ0EwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDU1CRXpOEOzNxom8xwA3kYb4kmc3JX8cSuWZKoaPm8KvhsgYOkH+1z4dt2OC/FtSaWJuMZrSTJs/lFmdyE1yuyRBhyqwCK3ZnFxCG10NXiHgj+uHK8ajNJQDitFuz4yLwgp6R91UhuCPPMAKL3eDwC/PPqnT6/D/EPG7eotlokUrpNrhTdz5YYH4VhXwM3VKkIdtSkPQTMftZ0Rbzd0u4sJlsF+RtXVY7/zzg2st0d2vEddpaOENFQfYT7D8C9VsKqo13sClQGoKoPa20a1Yvh65bK2P0SDzhbIu2xQCeis+wC/h0ZZrwCW5/ivCFo4DILk9269LaN4xqpnwJz9QrNFxwglktZm2j7gm4K9BH5a437E6xMvo7WXYwt+0305lLN4khL2ZhagFrvEYG6SLgJwZRWTAE8IsOC9Oyrq0CgpX+KpGkGMpokrgH8aWVCSgQxsUCPJYaBwMgAWepuf3Rx54cUV66vYb7z2NlSvV7JNvtNdXFFjddOfdoQC0QIVOJM1sOgUN/9negFRUtspudB397h+ncvnLnlrg+QaTZNjfCvP4YV+t0eMmlyhBpxIKxPnP0vQCVH9JfpJeZxpY9hFwbxfKcsNLhYHC/22ntbr1UMiIV1HDN8o1gQb6KwyPnS4SVggnf+WPqO4xhXCtwqSDQSAuVe9t03xAs1SGvt8wIDAQABo2YwZDAdBgNVHQ4EFgQURR0ZtFNyLfu1x57+yYiybG149JQwHwYDVR0jBBgwFoAUSCW8FQ+iFqE5L3zx0+2Onc3d1vYwEgYDVR0TAQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAYYwDQYJKoZIhvcNAQELBQADggIBAMo/VnCd/ndvOfBrI29QhBcwaHEgiC9QUA9u63EhAFGHaThtSd8dFnJLhOQaS2+rYC1nUhkZa03ImceTQpWsGpXOm/sFIAWojzgxqTEopCP5OUxVu6FuJMOGaUvaupGLIJSrUpzpn31NJxThOANEtd0sbMK5fk7sYXLlLNeCOfLu/dytit5jfDsUERJQGTi2YmzIYgFli0ECdswgxAb3b1klKvqOcXZI4K6WkCl5L/wjEP5XygnfyXJ6nMTSLpxuD7dRpqyitmauavfscGpLwYMArx+5gn2jwlq4TIDWdaKi86Oz8VAg+X0C5qBcAdx6k8pFUSjeD2kvykNbEdxBtkD4dgUn5UDmqB2IfW5UiL04cDBaxijDLbsYvjOE+wiXbESxnZf9bQXdeFSemARIWmE6to0uOmdp+snetB88Nw8EQ6faL9aKGBYPI3+KDy1IdMtyU50dMj7BSogZeBHh+6B/1qqlp3VGm5/PBaoyZJLRgx7VQNYFcPjUk0iLaBK7bqJ1CFkr5YX3/Ypjty4u1BD1LxEG2u60Q6PpLgBGGxqXDH6KpNkH2Z9mdagLL+HfZDf73m+J2PD0puLzVVcvzwPRf3nJyyh7ALnG9gd5gl8ksy6uHBizAOmzO0Ize7B8/1he1dSxZQ7wnHIuZ9HSvTvVHv8ST2l7XkKGaB0+BBHR"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultmergex5c-2.txt",
    "content": "MIIFkjCCA3qgAwIBAgIJANPuNc8d4n46MA0GCSqGSIb3DQEBCwUAMFYxCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQKDA1BQ01FIFRlc3QgTHRkMRowGAYDVQQDDBFBQ01FIFRlc3QgUm9vdCBDQTAeFw0xNzExMjgxOTU3MDJaFw0zNzExMjMxOTU3MDJaMFYxCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQKDA1BQ01FIFRlc3QgTHRkMRowGAYDVQQDDBFBQ01FIFRlc3QgUm9vdCBDQTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAOP2me/TzHq4fGve9X2fdDXQFayCq4XZ/mijLkerAPoka3T7lNfO4FI0jvnPNbrf6KZ2YolwiQ04OnFekder5WoVuoQFKZMLCFulHK/+GpyJPdE0fRRrbIsnSRiTvX7fvarHilQKu1B5vKyn6SLzNbvA8+zKJuCiA+ghIxiIKTI3wenzp/uuaWS9+qUXISINJnitgNxD9FnV3CSvAbuzTWfoWDNjS4q7BqUsY6sHCLCmds8kd2ah/CLOmraC7diwA5okE6CCSNzMI7fSzAztRx4BmYW9EgZjwacoWPUp+lGM9ZxRhPcD/euk91Qks10h04EkUXV2HpSVwtNYoSuFBADlNYw7mmn+UpzvG7wBUusDbjhDWG22i5IyOBRuuiUGYgDzleo7v7b9W8ocn5/q4cgEryed7LRxspP7wa614DcHz/6Rmg7CD1dH7zo96EyDl4tlyFB37XQzDtdvs0tU9ahQxFMVj+wcNEnVf7IBv93ukv5YA0sgcfmanLu5fiRBT+hw2ADb4OWNFhR+ZnuTpAtsc27bbjrJ6h6cwYnUFLdYiOVTTFYZjVKLlIhfpB1gNhzZFeiYwZBeU8bvmhD3xASApNyJL93PqTJYHxVYv9rfW5hcGkAJz+0gEBXSDEuKekm0vEujdMDMo9Atkv6HR3oeQttd3mRL81PfcxAqQbC1AgMBAAGjYzBhMB0GA1UdDgQWBBRIJbwVD6IWoTkvfPHT7Y6dzd3W9jAfBgNVHSMEGDAWgBRIJbwVD6IWoTkvfPHT7Y6dzd3W9jAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBhjANBgkqhkiG9w0BAQsFAAOCAgEAlLFwOq4VgtDEJ6vpWn21GfweuB2Saz8DYoDBrvcXLGImArfp9n0baeXqa9qqR8Tu12ZF2dEkvQsFnZ6gzobmctw3k4c+Oz0pJ5/iFUTotkqhFf8/RcZCwEk0pcEyAqlQ2LehMyB5UvFhSg54uucj4Ofp1CSjQ59GSe7u9LvHO0cEOdN7jQS9OaAnP03WYktDFTupxD+7xyQsIKePilCKVYgOAlJPKMAaaYcSGMGljUOizLVNYPLaFermcOzdaoyHz6btjq56febLQ2c0VSrL1C2+qOaVbJz0oQSEwt6meADvO8rcP/ZNK9T0kmDxbQzqpKZ31bt/d0iRBygGaFy2vYgybwo3iPGqPTInv2FaTRvWnHP/NlbdNKFwd876hMM+8m9PcNRcIeM+yFwD0aCJtfqorxdN2nNEioP5X08yVnexO9ywkDcAXQTj4RV9TyGlzZRc+1JM1LkhIgLvI6OAOxmrnXnHW08Vzo3yhK72NtnDukU4UcCAHOao6Vq+MJu2Ngb11WBlZulObcEoccxhpx929xIeOj67ZSLOEopP7z+fesjgABc4HQVQQ0v37eiYvVT3Bzz+TklfL/gEVLAk6AqLcFizs9vND2bTrGDgE8AWEX77lBsLGg92ofPXeXZsHsh43m2fRjAnroXQVsziQ0zJgHcA7OmLlB8mkb8fl3E="
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultmergex5c-3.txt",
    "content": "MIIEQTCCAikCAhABMA0GCSqGSIb3DQEBCwUAMF4xCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQKDA1BQ01FIFRlc3QgTHRkMSIwIAYDVQQDDBlBQ01FIFRlc3QgSW50ZXJtZWRpYXRlIENBMB4XDTE3MTEyODIzMDkxMVoXDTE4MTIwODIzMDkxMVowbjELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAkNBMRIwEAYDVQQHEwlBbGxlZ2hhbnkxDTALBgNVBAoTBEFDTUUxFDASBgNVBAsTC0VuZ2luZWVyaW5nMRkwFwYDVQQDExBBQ01FIEZvb2JhciBDZXJ0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwE0Gu/rJlbkqL0ynSbkCdrM+XP4dis/QNPz819ybXXpIX8HfkmAxrpLmfWh36KlflFYgpuV/J5lnJKlRmPWWOFjizAhq0dBijJUdLf6+QuImDjijd/nkO5SeQApZ4D50imTJL81vs2vwAfcCLwdlf7MNrMIfBsyjRSJh/Phjqib6kcYWcz6I6yTfkcsXcUB1JgR8KnQdVy0gYDu1MacHu2VYuS35HpPcQyXRqR1Ky9qh16+OhheRJw03ghEiPMcKbWS5NRgw/l/itoST2Qd6BzJTHUkJaXHNSO9fNF/fAccqECp0ZfaCSrfZs47EcjCv+N7bvrqfFl4BhB77tb7ZAQIDAQABMA0GCSqGSIb3DQEBCwUAA4ICAQCbpjL5XGC3T6gWU8sxCbS0VBmgamyvSHA8jLkWUXQfPirGFwgdGN7394mYViVU0qe6ZqmnhlhqZ1h6VbkBMVwzp3KlRhuoz/fXlW+TFvEC8Q3F+7oUdHn8w3EMyjKA5EbLzRIYXBizdbfEn8eJynjyWEdOaJpMmy9au/oFSqpmZDcxWW2SKq4j+Pqjhr+Ig4BmTVvwR6iEERPYQI4pv0OxRa7xA6Hb8NF02TyDzV7k02kN9PL/QO2dh9f3U0YY5XlV1HQzQ/BmavudPT1MiuH0CVSlCHE/JetXdJdWZA4HRiwXJn+5K8MgE5i1hjjXN/dLuaY8vItJzyrgxGRtRZoJA8t7B3QJjDECmey2m0K0qjYu7l1jAVFBWaqDdJQLmnKxViuz0MF4uFqgveW6CZEMcdqwZQ2cmZPlmcjneT0veBBh5qCdFNFM9pYDn0wqt5ruK+vqHkqJdMToBPNaBfGX10ADlB8rKW24eve+2c0iVmorJuTPdOqm2L9NKGpf2scvZZU4n/khkGKihrSOLygeLZ6SQc74cRL35FmzJqqKKpZtG9/a91dkJDz2XUiTO5TialaOU9+A1+Xrzj8LGG9JnB0KizF5dOd5mbZTROr3VCexRxyTrtZLpeJK+lYQLkDQ5ixWnd2sikym4hy3+NZ1g6nE+GQpqSALB4YnsFgUdg=="
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultrecoverdeletedcertificate.json",
    "content": "{\n\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/certificates/myRecoverableCertificate/42f1b607074a4531b4f14fb4447d4346\",\n\t\"kid\": \"https://kvvaultapilivetest.vault.azure.net/keys/myRecoverableCertificate/42f1b607074a4531b4f14fb4447d4346\",\n\t\"sid\": \"https://kvvaultapilivetest.vault.azure.net/secrets/myRecoverableCertificate/42f1b607074a4531b4f14fb4447d4346\",\n\t\"x5t\": \"-qEnW6P9TdfOOXzbNQNS5ZKveRo\",\n\t\"cer\": \"MIIFNDCCAxygAwIBAgICQ0MwDQYJKoZIhvcNAQELBQAwVjELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlmb3JuaWExDzANBgNVBAoMBkZvb2JhcjEhMB8GA1UEAwwYRm9vYmFyIEludGVybWVkaWF0ZSBDQSAxMB4XDTE3MTAyODIyNTIxNFoXDTE4MTEwNzIyNTIxNFowUTELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlmb3JuaWExDzANBgNVBAoMBkZvb2JhcjEcMBoGA1UEAwwTdGVzdHNpdGUuZm9vYmFyLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKKlPGmdiqKloSbUri9gvo2lyS0x2axSpeTfgIxI4Qnqhq8wMkih+SuO8+2rzIUd3S9nYqVww6yy+qHiJLXi3DKVYM/jgJnF+PlUoXxulD1abN8kX+TCKuHeAfTSIjM6WSgimGqW3hoB6bYHsaUFaAIg5FYbg5/IpbEMnD2yjU4M/nHVbxRwPqHGYdYfSqGDeHYjDb8GdA/+N0JDEoMVflTQKrDzq9R0lwOg+kICem1D+kww9ajyTu/7QdE8oOhAzuqFIVkCyZwpkrs576ng34mP04vpGcBs8YiKODydtFl2p5labXr5la0LVpLJL6rUkM3EhWOhQ0s+fCGtfrlmFRMCAwEAAaOCAQ8wggELMAkGA1UdEwQCMAAwEQYJYIZIAYb4QgEBBAQDAgZAMDMGCWCGSAGG+EIBDQQmFiRPcGVuU1NMIEdlbmVyYXRlZCBTZXJ2ZXIgQ2VydGlmaWNhdGUwHQYDVR0OBBYEFNPsyKBhnCjL7pVBLRYK3jaoZ8PfMHIGA1UdIwRrMGmAFAf9rGqvLeJheBNJOHBKTG3Oz32PoU2kSzBJMQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEPMA0GA1UECgwGRm9vYmFyMRQwEgYDVQQDDAtGb29iYXIgUm9vdIICQkIwDgYDVR0PAQH/BAQDAgWgMBMGA1UdJQQMMAoGCCsGAQUFBwMBMA0GCSqGSIb3DQEBCwUAA4ICAQA4sFKv4JDZ0+CVjcHL9bkTpk5I2L45xXk3d7GrhBpGveyy8vlb/g7P0qyAVo0UnB+eRTtwk6GTsJdzz4FBem+FDq8ZO/N51Rn4ZJQbDg24eGErK4rpbOo5OQgKKhTKjjBYwsAsIOkJ1TKQDQ3++Kqw3cWh/vlCWoxGPSMOeU/Iro34IWzSeEREMamYo5kIYq2ERCcVSoTcYB87cTYMU+ORyQSEx/OncDuAKm45ub92By5NpeFVMk+8ibifgzbNJHVnaZUVg8ScdM1A4Db6WAL0SUsYIawrnQ+TENs+6Ekls+wu8G5FAmbtOEV0WOafGvdcnELn5IPXlkvLbiRx5EChG+nF3XrLgn3dBQwP2cGrI/IPRm1XfaaBAkMSkf6St5TX3C40g1CGcNSVoKBYBB2Di+hPXwTHImGggR1JF34ljHCokMoPxmr7lP9pam0dhP/SSpIwxfsvDJylBgUEqTr3tsVDIDfMtJjudK7A7H1HMoqEiqlzRvJIEZ1koOxANFcQ1f9am2PPUNFvfK9IbLQlV8d4k1w6xBAeOVke79lJI9pTTCSVb+PTDniEL79JXjmjQUoKE4zo1u41d+wLu3dEGM27GI7BdLYt6bRsolZvrbey7Nn4c0t4ug4B4GTd1SLLVJns/IRLBrNr1anBJ7u9WFruBUEWwtdxAwSoXdtIIQ==\",\n\t\"attributes\": {\n\t\t\"enabled\": true,\n\t\t\"nbf\": 1509231134,\n\t\t\"exp\": 1541631134,\n\t\t\"created\": 1509346510,\n\t\t\"updated\": 1509346510,\n\t\t\"recoveryLevel\": \"Recoverable+Purgeable\"\n\t},\n\t\"policy\": {\n\t\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/certificates/myRecoverableCertificate/policy\",\n\t\t\"key_props\": {\n\t\t\t\"exportable\": true,\n\t\t\t\"kty\": \"RSA\",\n\t\t\t\"key_size\": 2048,\n\t\t\t\"reuse_key\": false\n\t\t},\n\t\t\"secret_props\": {\n\t\t\t\"contentType\": \"application/x-pem-file\"\n\t\t},\n\t\t\"x509_props\": {\n\t\t\t\"subject\": \"CN=testsite.foobar.com, O=Foobar, S=California, C=US\",\n\t\t\t\"ekus\": [\"1.3.6.1.5.5.7.3.1\"],\n\t\t\t\"key_usage\": [\"digitalSignature\", \"keyEncipherment\"],\n\t\t\t\"validity_months\": 13,\n\t\t\t\"basic_constraints\": {\n\t\t\t\t\"ca\": false\n\t\t\t}\n\t\t},\n\t\t\"lifetime_actions\": [{\n\t\t\t\"trigger\": {\n\t\t\t\t\"lifetime_percentage\": 80\n\t\t\t},\n\t\t\t\"action\": {\n\t\t\t\t\"action_type\": \"EmailContacts\"\n\t\t\t}\n\t\t}],\n\t\t\"issuer\": {\n\t\t\t\"name\": \"Unknown\"\n\t\t},\n\t\t\"attributes\": {\n\t\t\t\"enabled\": true,\n\t\t\t\"created\": 1509346510,\n\t\t\t\"updated\": 1509346510\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultrecoverdeletedkey.json",
    "content": "{\n\t\"key\": {\n\t\t\"kid\": \"https://kvvaultapilivetest.vault.azure.net/keys/myRecoverableKey/274f6c69b94b41359a5932226425eb43\",\n\t\t\"kty\": \"RSA\",\n\t\t\"key_ops\": [\"encrypt\", \"decrypt\", \"sign\", \"verify\", \"wrapKey\", \"unwrapKey\"],\n\t\t\"n\": \"urhKlXbEGvYetOSH-GLytvSJ5djS0-5SKBtFOlJ2885PE0s_ZbnkRURDm2fImv_RV763HKSUQbEolQNs8I99N-3uCkrDStVZ6MPii9-0U6lrEkX7LrMRNYCfPAaSSZhSjCbsyqX9Y-N_A5Jz9uHNuXvpjQ9N7ojUK7fqqhnJKcJ6l6YsGOhGCD3uei4SL5GzbSAn2auIK51lj77UXjBZaudnNWTiKaCbTAmSmEe13DOJkg82_7Y1eWea3NJn4T2nY8WqRJCp4hzBsPBmFXjE1lgFWcSjm_afiSb0mCUP7v7tSOLR3xUBv9WgMO7p4_ce_--A9ZWP418Uqq0COcHAWQ\",\n\t\t\"e\": \"AQAB\"\n\t},\n\t\"attributes\": {\n\t\t\"enabled\": true,\n\t\t\"created\": 1509335950,\n\t\t\"updated\": 1509335950,\n\t\t\"recoveryLevel\": \"Recoverable+Purgeable\"\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultrecoverdeletedsecret.json",
    "content": "{\n\t\"contentType\": \"aNewSecretKey\",\n\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/secrets/myRecoverableSecret/d7194ca6b0214d0ba382353109cd7e58\",\n\t\"attributes\": {\n\t\t\"enabled\": true,\n\t\t\"created\": 1509335958,\n\t\t\"updated\": 1509335958,\n\t\t\"recoveryLevel\": \"Recoverable+Purgeable\"\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultrestorekey.json",
    "content": "{\n\t\"key\": {\n\t\t\"kid\": \"https://kvvaultapilivetest.vault.azure.net/keys/myKey/1374543b3de34500a97d075991ee3893\",\n\t\t\"kty\": \"RSA\",\n\t\t\"key_ops\": [\"encrypt\", \"decrypt\", \"sign\", \"verify\", \"wrapKey\", \"unwrapKey\"],\n\t\t\"n\": \"tY2pzXPfU7NFYCWvZB1gJNAetkgJ7Qi75lTVOzVns9KjFFo6e_F9GSETZbAYl5oMwfLtdqQqT5fxzWDk0sYlz09HXvCCoYmbzobd3gJ6-WLAqhtCbBikr5HAIlCzy_UqKT--WhEw8AT_EJFBPIY9xNktqnaNZuRBmjmXinzT02qUmBZRsAdJmaYfG9IZSmToOkb54OytI5TreWN0JvceoQ3GSeFLMC5PUmXP6HmZliOzBBHWnXNq3H7a3qfWV3rxT2QpbrIuz18ZqOVp7o5868kN8knKytVcqEzmdiQUdabkqbrwuh-z_IEre9AqTfw6OjUUmLjs4lyKcpWLYFh8KJuML1ub-8u0VgNGwczUZ7aAld1iwGMsoMmQfMRDOnv-9pqtY-y40ZWpBGXpzFV-IvtKHnqQk_vWqowpE8xwx7yZ74z9XNgS9TmkVpcC-ONbEfNE1sez0Zf-RZ9eOm_7WSxxH6OJYtJI7wotBXYoy1bJaqo7mgHs1IUOFhSE-Evj\",\n\t\t\"e\": \"AQAB\"\n\t},\n\t\"attributes\": {\n\t\t\"enabled\": true,\n\t\t\"created\": 1509335925,\n\t\t\"updated\": 1509335925,\n\t\t\"recoveryLevel\": \"Purgeable\"\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultrestorekeyrequestbody.json",
    "content": "{\n  \"value\": \"JkF6dXJlS2V5VmF1bHRLZXlCYWNrdXBWMS5taWNyb3NvZnQuY29tZXlKcmFXUWlPaUppTTJJd1pqZ3dZeTB5Wkdaa0xUUmlPVGt0T0RVeE1TMWpZVGRrTTJKbFlURTVNMkVpTENKaGJHY2lPaUpTVTBFdFQwRkZVQ0lzSW1WdVl5STZJa0V4TWpoRFFrTXRTRk15TlRZaWZRLk9tXzl6QnhwTEw5a3NCVmNfR1JLUHR5akZ6R1JGV3BBWFVvVm91dmdNQXNEcFo2UUp1QUloRzZJWFB4ZHBOUDNlbEZFc19Ld3RpMlBhRXNEQWM4TEVQVHZvVzlSRmlROHZTY3JiWHlKcFNROXJSS1V5NlQ2SWo3UEpDV3Z6alp5ZlNYbklPNjRYMUtzRThFZWNKRDdudDRhN2tfZkpiSkw4a3paWnhXWFZLZnZwZEQ4c3dobFdOLVhMU0RsWDFORmlYQk5ILVRoU1BDbkNMOHc4RjlpV0o0LWFxeXozc0ozRDAzb3JzTHdKczFBTF9LN1c4eUlUNlprb3Azc20zeGlBb2pYZl92WDdOLXhQMUtKMU1tRlFnQVpaMmNpQWdJc2UzVDdoWFhsa0RaNGJqSXpYa2ZocGg1YlNuUEkzQU5kbDRUaXZkdVlxM0lCdlZrQ0hpWnY0US5pLXNxb3lQVVNHdlM2SVdUdld0MzBRLkR5N0U0cE9vanU3bzlMQ2dkcVYwd1c2MGxkOWRaU0tPN0wxWXhid1RMQzd3Z0piSmhlNno5b3VWN0FFMnBMLXFFMUhLclI3Nk9TVTJ3c1FBMFZuTDhlR1RnVFk0TWJOaklzSERraGFSUWN4bGRjOHpGWEVxNzNOWlhPWE5vaWJ2QVhUcm9oX3JnS0plNVFYWE1MSFJ6T2lVWEtqVEU3ak11Qm0zejNMRm1mQ1pQb0xWTnpNT09mdmFwQTh5XzNEUFk1OUdxOUFzWlZsakNpTWoxUlVrQV9QQTBwREUwRU8xd25pV0dIb0t1R3h2N2hLb18wcFVMMWRPalZrNFA1ZmRWRmtGOENVemVvSDNja29xbUxMRmktQ0Nra2E5Q1JZcUE5ekZFckJsZGYzQTlIOVNuazdiUkNhb3c5Tk0tdXFBbkF1OWF6U3JBbnZZZ1NUT0VFUjFvX01Yc1Bqc1loTHp0NFZoTGx4RjlQNDROSU1ZTjEwWVZBYlVIQ0FaREZZejl5d3l2YWJPSXF1bjUzc25DZTBYVjBaWndabFNmSktJUkNsMk9zU29vVEt2OWx6U2kwOVFlUTRxb1NCMFdXSThobjFGd1pYV0RhdHNSNFFxOTB4RXB1bFVyWV9mOWI3cnNSem9jYmF6c0cxek50a0t5bjNVY29fR00yRjJDclFybi1uRVlXMkZRcVpkMlpHT2Nnbk52NFVyWmMxRjB5MUpTdXgxS29qdHBkZDgzR2JPd2s5dmVlSGs2NXlCdmtMTUYtcGtUWGdFS0lZeVN5ZUM4ekdndVZJOHhrX2VndXhQVlhCVVBMWk0xTHJ3U1VDc2JhaGR3WnRZZDN0R1dZVjZsSzhyT1UtQjhlWllvRTd0QUF2RkZxNEJ1R0U1TXRsdHFSRVpkcHlkOWFkTDRVRkttZ05YcTlvNWVqdWJuSmV2RWhRQmhVRXpRLUdCZ3RudVgtSlNTYjBDVllxV3p0NVU2dzJpcVNwZzBNMnQ4WG5OQXN5WTlvYXVBbVhuUGhMZ3lYYWpaSE1TS2FqNjIwOHdrZVA5ME1CSkt1anBfSFhJaEttSW1TOXVwLVY1NXBHRXdMQnhfYlU3TFpwYnhIcm14R3VOTE9pNXhJUGt3QkpTdXFZRlNSMWdaUU5lb1ZHUncwTW5TQW5HYnJ3eE92NFVjVlpUUjhkVTI1Y0NTOHpENjNwQ0ZUdm5CNllyN0pwcGhYekd3SFZYeTM2TkJPdWVuQ2NYQUR2QXNXS2M5a1RQeTlEalVFRFVQd0QydUpZQmhqaV9RR2taYjhfQnNwdURUbWM1Z0Y3TkdsV2NPRTBqZmFwUi1CSlJhUXJENFhxeU95NTRsTUxCZlNSTFBIN0w4VnMyUTVvc0FfVHlPYUoxa3B6dG5iLUhyNTdSQ1E4UWNsRnd5eVRfakpLaXFQRFEyWFlrZ2NjMmdkZlAtS29GNHFHSl9HRERMN3NVaThKeWRnOFNBdDBoRGdUOTh4Zk1URTlQc0twTU9FQUkwWF9KRWdsRTFwRmNxbVFkT2NOU2Z0VUxRaEFPVWd6Qlgxb1UtYTdiX2gtX0l5RVgyb0htZDdaNUJJRV80b0ZEYWVMaXh6ck9BWFdTTzVFZ3B4U0pYUXZ2ZEVZUV9mNHhPVFU3SExmUWkyNEthdGNUTWJJczlBVU1UY1NvVUhIY0RLWVhZbTl3SWR0RXR3MG5mbFp5YVJMYkx4cVJNTzd0X1ZLbnJ6OGVOZ2dJWENBVno4dmJmXzk1VWdVNGJUTzZDLU9BbHJqbUZNbVNzaEpwY0VhRjAwaGx3MnZud2s2QWlCRTlWUzdOYmJFb0JVZmtuaWJFeVJ5NHp2MmZtMWxhRkJnYmUzWV9QVEtHQTlVOGJlNGJsb2lkQmlVOGwxUS1qT3oxeFRNVFUybkpnYkJ6b0xzWEtadEw0d0ZDTnlNVFN3N1pyX3c0aDJjUzU4UHZsVWlYalRhcGpNdTJzYWJtdVJnVXROTjFlWVdxZjBRSEVFdGoydE5nd25TaHNBOHBRWkZKaXp6Rlc2VXpKRXdPbnN4S25tcjFEQktnZ1hsZFFtdmlxWHU5aE00MzdWcUJIeVA2SFZ1dUdiOEUtTlM5WlBPekJWMEFrcTM2QXVJcWNIMXUwTm1NT0laaXR1WVhFNXp3UGlVczJxSmMzQ1BHbVdZQ3d6THNibF9YRkx1dU5udXlIa2VGN1cwOGtxNjhBU2FBMTVic3BQMDU1a2UyMlRVbzNqVl9PeHRUY205OUdBcktGOE82elBjTlQyQ0xNdjkwZ3I1SEx0MVg1WjF4WFNTTVczZ0NRVEs0TmFtNUsyTzFUNXdoTWtPdnhYYmdkb3Jwc245amhGb25aaC00VG5RczJiUmMxVTM1Q1BudmRVM0s1dUVOTzNxZGVxV28zR20xeFRMaUdJSUhsNkdpX0dFdnlqWjdEQzRjeVhlYkI5enRiMklLQXZLVFhyQkF0aXd2bWF4U2FzNFRXVUc5Qy1RYUxLZnpRdDZwVm82NU8wLUZHQ3VLSU1Fc1I4bm9lM19jVVVJNzRiYl9sTVFWdnNyOW9KamJtS1RrWVBhREViQWZCd0FLdGw2dzdWUER4bGt6UmFZVTdPVENsdmFhMTVZQ1hJSzQ2V2hkd2QxMDNoR0x5UjltWlFSdmcyLWhfN0tESzNSVWRzcjNtTlBEYmpCcU16U202MldDNnZTclBVdENKTks2UG1ZWjhfT3A4bXp0U0xUbDBLWlN4dWt5U3d1Y2hfQXZLcGdqa3ktQmVfS0JXNTdka05TT2JlWmZKZElRT0xkSVcwZExqd1BWeTdENEhPS3FyWE1JRGdIdkRIR25zWFBZb0VRZG9wX05BOFZfTW03bWp1blhtZWoxVDI4cTN5VTcxRDEzVUxhdXNwVnNQVHBTcEVDX19mS2ZVSUF2dnI3RmszN19uSFU2QXowSndhNklSU19mTUZHamRuSDI5RXBUcTZGRDdaY1hPZzMxSGdNMHNtNUZlUnkxaHFqUUdIOTRwd2JpUktfWXhQaWVzZHd3cUh2TE1MZE02SU1CU0tuZlVfdTV0bkJISEV6NzZvQ0dHSEJmM0ZnTzFkX1hZZGhtVDZIR2FRUmZhV0s5QTVRNkpUbHBaWUpkOHc2eVlLSDVvNktFR01TWXRKbDFhM29KQ1A2Q0o5Wmh0R0ZWcHlQYlk3M1BkenozR2xvdFlqOE8zYzgtT3BxTm0xaEc2MU1IeEFnNkJYZHgxeFBqZ1RuTVRHbUtTYUplV0d6OWdHc2JDWm52RmlwSExjbHJQVHczVVR0NThOdmpkcGJtOGV1VVdxUDM3RVZzMFFoVHZkNzdmc1duZTgzZlpsYkh5SHF1Y3gwWEtBRmNlMURZNlM5Vlc1Ulp4akU4bHJHemxpVXplTGtsS19wVG91d191MXBVWktLV25jTzJ5RzlrZ3dOT0pkazZiWVlPb1dCRGhVNHU3TFVZR2tETENFaVJrSGRIeVBQbjJBeGNXTGhQYml5cUZ2RWRtNUNMMzMtaHN0OHFRNC1QYldfQV85QVFLZ2hoLXJfUUE2Wjlzd3F4QWJFeWI5R294TUFPenAzMlBoaVhpOHRxTC1qQ1ZqSEFnRTdqYm1jRVBVQVh4QlZFUXNLRGd0MFFRM2RscG0xSUd0OU9fMzNwWEIwUmt1bUxYT3pnWjYzYzNGNVp4ZlRyTGtZZ2MxM0p5dXdjb0Nxa0VxS2RxY0F1N3RFODUtSnkxZnpNTHQzLW9wXzBOWUdqallIZTQxU2drdDZjWjdnQXRFeHlDek5YRjBZcG10WFlralI2UTF0dnFIczhRWU9GaTF4RFZBb01pUjBMczFjRGFRcm5WMEhVZ05QeFJSdUlaYld3dWc1OE9QYnNvUDZYdHRhVGo5RU9yRlJEbUR3OVhiSjhxWEV6YkQ5ZXcxUjVsWGVPZWZZcjVnQVlIU1k0X2lTMXR2Qzg0QkY3RGtYUjVDVUxWZXNkTDBwckh6RFA5MHZfRC1oemJSUDVBNFJMM0RLNmFGN3Z6dFktRlRJSnM0bTNKZ3NyVUp4WkV4NjFMQjRIdGJKM2RTMUYxTjJ2YTJPc2VBSWZ0dkhESWFyV21tbjhBZy12T1JhTW1kWC1pT2YtajI2dWlYV3VvTkNPV085NnM3ZWsyUzRoQ1psN0lPNzVzQThkZGprbDNtaFhrSmEtaVBZZk9Nb3pKWDV5WEREX1E2WDg2YzNvZThLZEdVODJCbGluNXRycjRUdlVXcHBEYVZoYzJ6MENyclN4dko2ZjBIb2ZrYVVNTW9seVlpWW1rSEdpVWNzdmRNbDhMS1MxVEZoWVZiVW9xNUVyYWhKdW0yTjlqdk9DOGd0Ty0yempNR2NjbkEwUzhqbTR2SFVTRDV4MGtkWFotY0NrZ01HSWM2LW1LaHU1YVRpTTFWX01mN3dteTlrdHZITVRqVUM1d0kwU3JMU1F2RnNWZUZHamthLW1qajlsUEkzMFhORmRLajRTR3A5T2pmclRyYnhfeV91emZ5b3NudGVvRHF0RURmVmFSSFhVOF9pQncwWEdZUDBIaGloR3VlczdrdTZJVlE5aTVjVTBNSTRKR01vR0xJRUJKUG1NckxmamJMdkdVWTgzOWUwc0s5NFNBVHJseXo1YzYyeUloTC1xdEdIeTJBMmxxRUhnVnNvQjF0M0J5bDhwME1OSWJId1ZaUlkxcFBDdFBJVmctYWJCZ1ZVSGZneC1FSDVhVlR3QUZGekw5YjBhVUF5eEhnam1XVTlkYjJTMGJ2S3lKaTh2UXJuOWVnYkt4QWM4OEw1NDNsY1dUU1BIOUQ2Zmk5Z19hY0JUUXF5VUt6S3JxYmJUUGxMNWxQdGdfazFhd3ZLNmhNUDZfR0FLUi15a3JzTlcwVUZHaFI0WDNkTE5DNnFUdGdNaXFnYThKN1dVSjdMZUtaRTV1dzlzQlVRemJSdUxjUDFSMnEwQ29DSHdRYWJIRGhPUkdNMkFyMF9HbmIxZVotRXNNSXJHcWcxQkY5T2FMMTdZWE9RWXRhZXBhUEZGcXI5TS1FTHpEWEtYWlBFU1RVZGZqU1g0RllvMFk5cXNTUGdnTjlhajNnMWxfYVNoclA2SVdxZjJrRWoxTjNIMWVaZVUzQjZrWHBCUFV4VXV0LXk3MkU4Q3l6czJtUDgyQjRvNW9GOUVncldIZXF6WGw5XzQyVDFYNlB0Y0l2TGZ2d2hzd2FTVzlGamxVbC1hczVQbUtxSlRtUzl3bE9CdHZybDh1YWdIT1psMW1zZ3Ezd0hWTGVxMmRQclc4UmRjZXJwSTNySGVDZGVzZGJUb3pnS3FuTVhSSVNmZWtvQThLRTkzWFRDOXl1SkM2NmdMcTNJbkJnZ2NUMFp3X0pmWldvN2tmb2dyd2dMRTYwTm9uamxvMERGWFlCRDlKcDd6VGFDRGFGLUZRbHZ5MFdGb1YzRlh2dDllMDdJajBTN0c3THZ0OXVOaW1sbnYyazZOUUJxemlLT01zSjVRQ0pYOEFsbnMwNk9rZG9aVmIzV3Q5MjRQcFM4U0N5R3JnYWVPb24xTHhiMXp2QkIyZDQ5cGJ4a1ZMQnZjcnpFZkYzbExSOU9NdThGNERjS1VHcnBiMjUtNHFQQXVIZXJCcEVEWVBDY3p1RWJaQktZakZQSlozejhKNk45S2l6MktaQTQ0Z3ZKVE42QW5rcThnXzRJMWRBNzRtME9QMEcxd3dtd1pQQU10VXJqYmJ2TVNtbHVjb0FibXhSbDNPd2hFbGRoVFVwdi1iQ3d6ZHVqYnNPMVBsYWI5am1LQUZZaFloU0RZR0FoOTRRRVJ1dkd2VTJnQzlzRmYxTGFTM0Zaa24tRXIxWmgyallpc3BwMlFFd1FBdFlDcmMwaUptMlYwOF95RTVheEVJSnlpZzBhVnFZQ1FiN05GS2diX19LRF9uMi1yN2YwX2RIOFgxeUdJcXpiNzNGbHRCU05RRG1oUU1TdVlVYjlMbHFlREhuNVFtZ3JpQW02d3kwR25QMmE2X2k2TGZWejhMckUxVm94d253V1h4SDlSeDVuTUdpREFvRGxaVlIzVzd1cW1BZ0lMaGFvNldXb0xuYVZSU0pRUTFybTY2R2dCTENUa1QwcE9kS0Vpelc4TlpwXy00Q0tWSHB4ZUpRVFBodXo1cXBmalM4Xzh2M3Nkb0lHNko5RkxwMUludnlmTnFIM0djZ0sxbWZZbWZPUW42cXUybU4yckpiMDg2Y3U2cU5VZnpRcXJqQVpwckdpQ2pCU3Z5T3JwdnZCdGQxVHBQTXFMZEZxbmtGeC1GSTdYWDJocUtoRGFyX2R6QldTWXFPSE9adG50d0hocGNWVExLeXdqQTl0MmxGWTFuNFJtR1l1SHlKdlhVeFZvc05BU19nd1EzM015U25lTk40am5aTWFCNFMyM2lNV0Y0UktSaUlSXzAtTV9Nc1kwbDZmbUxOekZFbFJrUE1LcWFsOHFmbUo3VDkxU2IxdkJFQl9WX052dGxlVzd2VnlaSXBpbV8xUHJ3MC1oMXBMcXVXVDFodll4SWNtbHllSldIUy1NQURnaVdWbnlFOVJBOHpXWFI3TWR2V2s0U2MtaGV0U29LUk1YbmxCM0F2cFc1bEVYN2g0aTJEcVNfLTI0RGdMS09iNWlfVTMwZHNxcWJCdTFMUkNiX2p5dHJhUUlwMEJOczhEMFFXQmFzYlZDbTdNTkM2WlpESlZLMFlBQWkyZnktM3RPSjA3dFF2OFRQelNiaHZETDh6UHdqTmVCSURMWjlvTmdlZFNJYk5sRWdZS3RKZHh6emJEOVp2UmNKSzNYUTBYVHY5bGc0V19HVGJYSUx1bF9fa1owcGZ2RjV6N1Rlc21obV9hRFY2MzNYTEJzWG1wNHJqWUdKUE4tdWxkNW11YkZoWnFWRjJaRHpOTFI5czNKSXNkeHZubnl5QVpiR3dfVjI3eFVKQ19WbktXTzN4bVhGdW5lV0dVSkNFZFpWR2FyZkQ3MHgzc1JIeHJzM29jSEQyQ1JhcnFpM19SOHlndWM4NzlveEJuU29FbXJJTkd5dWkxbXkyRHdnOFYyaGNrcVZKSjhBakxONjNJaGZBR0FTNEU4QWpQODdBczlPX0ZUcnVESWhtOHBEOGpFbUpQTFlTV0hNbkl5WDV6VXEwa3p0NE1QMkNpdzF0Z1pXMGtvRGtHVFhMX1hTV2JCX2ZmVG1lWDN0cDVYU0M0YUh3X3BzUV9oNE44Y2NkS3ItWE1jYXo2aTJ0U3k0Ymh6U2lwWXdqcGx6S3hTYU5wdVpmcURWUHlEVXpfSE9OSHVvV0ZVSEw5alhpTEVuR2JFYW5HZ2VlRXN0cEFDcGMyS2JNN0NhSWpDdUtubmpxVy1EZWoxWGNMY3Y5LU1EVFVraGZwTGhMV3ZOWUZKV19UZ1F3eHhEbllTdEwxYTNZVGRfMjJuQ3dJUm5SekY1Y19YTU5KM0JleDh5c3F6ZTJyN1Q4b1hUcFhvY2ozQ2sxaGgzdEh0dHhCOEIyYUh0UlRUanIzRFltamc1RllTOENLNl9mOThkX1QyS2FHYkViZFd4eDhyTDdEZ3JKTGdqeC1Ba05ma0pCR3prY1JaRnBFX1VHVnNhMW1nZlNwOC00QTVaM1Bfdzhuc1RsdzhsaUZ1MUpxcTR2S2ZyQmNUWTI2UEptdEdkZWQ5N21KQnN1aFhyWW5uZW5qamg5bEZYZ3g1TmYyOFFKNHdoV2w5eTFnSS0wNHF5ZEdfem5CbVJ0MkY1Q0FNbXdMQ0hpZV83LUNZVzNDTkJNWlRPcV80VUpaWndxcTUzNkJYdWtmNHZNZ2ZJSENnT1JfczcxUTRleGRmWWZ2ZTU5ZEp3WEc4ZHRMa2xxdXM5SlM4dlgzSnFHdHpLOUhWYjhlVkdmVWpNNXVnU3J6RWJCRFQ2SE1vLWhqVFpNbzBrbjAtY2hTV0hpVV81X2xRanlmdDZMYkxWZFZEbkxlLXFhczlhUi05YXZDZGk2Wmt1SmxuNVJPbXI1XzVpam54Y0haam1ZU3ZXdU9xX0tZT1JxLTMwRXhMdldTM29YbjNQc0lzOTNWTGktU1hHSEpXamJ6YXVlWDFySWlsMGZFLVY4ektpMU5aLXVVWjJJQnVHdjllVWtYeXJyVl9EWmZxUE94RlpMT1NqYWZuWWxSNEt0dE9WMHJVeURaUExob2h6bkZHdG9jRjAwV29xOVB6b1dCT3VJNjNjeE1YNVZGSnpmYTdTdTZ4Vk1FRExLVEZZRzh0bGVDdUpLSHpTV2hpR0FaY1djU3NvLU1VNnQ3LUJMVEQwWHEzVklNZU5qQzdQcmU2TjU3YkZheWpqaVVTdTBrOEh1SjBhWGZnNDlOZ2M5S1AxWHp5bjA3M3p4NWd4dEVQYTFhSFVFVEROMkVWakc2SDZMdE50VnNqNGVWRVVzTzZ1VTZTWk1hOHhfX1ZPUEM0WEgzVGRYVFMwTl9KZUw4OENyWmZSMmt3VDh2RWdSUHNVLUc1MU9fQnBXcnVzRndXMElRWXBZTnUwLVVmUjB3VDBlUUFsdHpCbDQ5VkZ6SkVMeHhsTXlKc3ByVUNmMHp1cUNUaVg4d0VUNEc5YWtZZzZKWlV5SVptSUk2RmNycy1sWTBPWlVYSW5IS3pqY0w0WnRVbHhZTTFFUENXVXBibWw4SXN2SlpBN1FELUtWOEJVeFdTXzdUOHRLOWtfbUpGT2pTdVhZUTNjTFVDVktyVkRwU3RZZ3JUREdiUlR5bk9EX3QxU2dwbHczMFFUS01mTXNyZkJweWQ1VEpkSGg2eVdSNFFwUlJnWnVaWGR6STRfWVFUMXIzT3NnWDBWM1NaMUZQN2hSNF9NQnFQSkVTenpZc2pQWVdkTzdzaE55Tl8yaXJDLVNxbG81UkJaNVZvZ2VNZDNaVmhhZEQzcnF0UjJmVHZNZm1aYUtuN0piT2FoUUFJYjY3a3NVUHZHQU9rRC1kNS1VRDV0N2JTU0xkd2xXel9aUjFLakxES0xaTE1WSEtTRk40ejhOUGhIcjc3d21GSDZ0ZEw4X0dEaWh3YnVGTEdmbHl3VmRuWi1uenFQcXNhaTU5MGU4SnBfOVQ3dGtMczZQUHBwclFGSGFVRnFtSTAyYUNvaFJDMGRhTEZDY0JrTXA4blkxeFRlamJyZm1yLVpNcmNLMGQtUmM3bWtpVTY3bUpBRTJSQ3BFZ0Y1dUNiT0xoTlNxMXh5SEZHa0llUE92RkFYMWFGQjNwa1VCN0Q4OWxoUkF1ZGd1bW9JWkRCd0dzdVBSRGZPUlR1T3hZakZhaWozZzVyenZHdEVlanB0SVJDbVhNZXhhMVFnYlpQOWJabWh4a0k1SXdHNHJDS0pvZ3NBWnFhYmZUSmUwY18xQTdLYjIzNkEzSHRSMFhJMWRIbVotM2c4cXBwVG9Eb0JPYTZ2RW5vU3NkOFNsX1g1Z0JlZFdmWXZwYzd3X1pfdXJGUXlac3BBbDJrS0N5N2w2U19BUkZqR0dvSnVNWVFicElIbjZGbkJCcjhsTGlyMExZUDVTQlJfM3NaSHNyb3UwamxyLWNMejRZSlpUYzBZcnBGNnRETHA3NFJ0bWM3cDk5aHhNRVE1UG40S1VGNlZJcWt2R2JocjJjdlgzb1d1bk52S0tOcmdXaDYtYzBONFNDTjBkMklveVZfbktzNG4wR2tQcmtDS1ExSGJMbUg1N2ZSTGdqSzFFaEtydGp1SUx3dXFRM0pCeUhISlpOdEdsbV9nZkt5bzZsQ2IyQ2xacElxR2Y0X3ozcVVyMmZVQXhMdWxtRFRMZzh6Z0RlTEViVVdUTXYxTWRUc0pSb0NTZGJiS1NvQ3k2UE1YZUwycllBR2tHT1VYMnVPaDVnRlVkZkdzRVg3enVHamtadnhra2J3VHpTSFlibkMxNHlaRXZsbS1qRkhWS0JjUFdJemJKSnFoUl8zdFVNZ2xRc0xrZzQ2WHFlLUREblVTYUMxbzZ0NnNXOE5CbGR3aGdnOU9JUXhlT2NacVhTanY4TW84SkdrUWlBMnp2WUVWNmJpa09MS3BTbXQyRnNWVE5BSVBQNm1nazE2NG5JaVZXSTN3dlljZ0pCb1ZxeEpCdXJVY2NVNksyVmc1MkU1cnVQc09rNVZwTlphR0ZCb3NYNnU1bjhBM2RfR0laV3VhTUxsZnZnVkdxN21nbFowaFBlM3F3WHI5QndCNm5VV1lJdU1ycFVxUDFQanBmck9OZ3BSOHprQlJ1T0R5R040XzJzRHloMDFWUWRxOGF6OUY4a1gwRU9RaHZ2ZUJKcmtqTTRENGJ5dFVSeVR5RHJRX0hYTExFYUw4UjBPMm9MOGNPeUtSa3F6b1ZGc0NjUC1jMzB1UHFnV2E0T0NzYXhnYUxkTUJveTFKdkFENVF3SWp5dHd2QzR6THNpSXljd3JqeEZaZnVlUnBNRVZLOTR4WVRvNkhlWGQxX0VweFBYMkhiMFFBb0VVVS1zWkFCQVBFZG1OQi1XMEtoUnNpMmJSZi12b3JVZzhJbS1remxCZmxaQ19zUU1RckcwZjR0VE9qTlR0QnlHWUt2dXRqQWJuTjhMQlFSN2JmT0tzM1BvQktQc3pTWDNWMUhtTTUyNnd0X1ZmcDk4d1lFZUNOc3RwcTl1YTRKUlcxRWNGTTRJNnY2aXBXQ3Q5b1V3dVVsTkhUOHNhR2NaUVptRzdZTTRUTDNYVVJITHdaZnNzeUFma2dHejZ0Qm84RWp2MlhNVlZta0ZlRGQ4REl5QXNSUEVHRzZFYUowXzdYajRxNWttR2lUOEJBNE9jMm5pS0M3eVJCVE5CNnhMSldPaXRHcHM0a3ZSX3JfVTl2VUQwMTZ6U19PVlgzLTBqLWNwNzYyWjRicHhNeUswbmNzbFc0M1diUFhRajh2N1libjR1bmtPOU5lc0ZkMC1YWlRvU0J0ZlBTeDk2dGVMM0t4YXEwOFBzV1U5NzhDTVdrUlZHXzZnZWtWWGI0SDdrQUo1M0RoTlpFTW1yM0hSM0lsampIM1YySDRvVGlmeW82ZWdiMHZQX1VEQVNFZGVCUkNYT3JuLUJhTUxzaWhGZE8wVjFxNmNwS2FLVlBkTHgtOTRlelRSRWdtcEpjYjNvSXZoa21RRzJhZ3pZejFEMy1lX0FRU3ladE03TUx6NmY3Ni1HYkkyMy05S0JtVnBVQjJOTnU1aS1xZl8tN3ExQ3JVTFNxNE04aGJsN2E2OUt1UW1RZ0xtQUJZVzlwX3J0ZGFGUzJTRTNGZ0ZPWk1GYnB3MEo3SzRDbXd1VURXb0tyejlGZXAwRDktdkR5NEtpQmdnZWlZTHY3ZFJPVEMwblV2WWlMX00ydXlHbXZtMGJDc29ZMXB3VFNjcDl0aUJZVTZuYW9Ub21ua09qWXZ3T0ZHN3h5R1ZSMF9yT2o3aHpWbzlfbDY3ZE4xaHRFcXZud1BTRno0dXNEcE5UOEFnR3VDVXlMVW5NVVc3ZjNDUFVlOGlqWk5PTm14NEpBT2ZZY1E4dXh3SVRPaExqSEU2alFJOVVFSGNnRmJsMUtrVFJJSDFveGhNSDI3ajJTaUNkS2VrUWVZX3J6cllHTWNmTWF0NTFrdXVzT2pMWDZvbnZWVzBEc1ZXS1FnaUt1OVI1QW8tQkFUTXhxMGJUMWl1X2FaZGNLNkxlZHVwTnVqRXJzSHpNTzF3eGRRcWtMcDVvN2M0ajlQLU5xTTJWWGpnQm93OWJrUmxYdWd2a3Z4WV9tNU1fMm1oeWF1amdtdHg1bXNPR0pIUl9OckY1djZiUGk2aWZkU2o5emhuWGV4MDFEb1B1VmRHeXJkaGN3N25FRjZrczV2N1pOT2ZvRFZuemxCbUpsQVA1eHFjX21SQjI0ZmdWQW5JTzNXMTFSX0V2ZF9UbWxXd085a1cyemFxbi1OeURLUGxtOWp0aXdSSExYRmR1Snc2d2MtdVhJYXdxZFNkZVJkSUV2TWhYX2ExSFhNTG9RYk5VZnpHYk0xSi1aUVBNNWRfbkJPMGN3S0xyRUhlX1ZiT1R4UmZuUU1UVEw1ZnlrcmJGZkgwWUdPYl90aVlqWGJ3QWRsUmtFcFVuSmRWemtCY0tPZUxHMF9ydkRXdmJKX3E4QTFkeFpONm9PSlFvOHRjV0IyVTIyMFNmWjNoNmhUdC12dVBPelltdG1WMDZQb1ZSQTQ5c0JxRWJhNUVKU0pRSGRkVEQyZERDVnRBSV9XNFFFNF9QRGFhQ2kyZFVsN09pZnZJS09TMnJVeVRRckJ2eG1LSnN2Rm9yM2hjOEQ1a3UxMEFQcnlUQmdtOFFTbXJma0xlZGNHUEk0YzlxLW53QnRPM1l0cXExTmhnaHU1WFBxc3h4RXZiMkpOekdXME1DeFJGSGI1bzZLbFg4cExjLWZzUFV1V05lWlV0MnQ3R3ppd1dDc2QtTno2VW1Hb1JicU52SmNKeE56VjUtdnotNWJpUzN5UWkwVlJSczl4elhmN05jYURrQlR1N090Q28wVDFUYWQ3bVE1WTVVREN6UXJGVkR4YS05Q1JubDczLUFvZXp2SUtSWUtYWDZLam5RUjZpNmRJOWNBN2pKRFFFT0thMGY3UHFXcU5tYktMalhSY25ocXZJNW56UU5pYUh5bkUzTXpMb3VOMzEwQ2wtM2d5VFloci1ya3c1UE15VHY4enZpYWtMbER5Vm93dTF4OHMzcmdlSDFUbFp5U0JRUDRIcDBBWFYxelZQQUhNbFU0R1dZdXNOSk0tWk1uSGxBdW5RSVd1WF9pRmxVbmFqMWhyR3pfUFJ3dzRVajF5aVZOLW1UR2laSUdadXRDQXRYeGZUd1hwOE5Lc1pwNThYU2QyeTNfTE4xc2QwZDMydEI3Z20xRE1ybHpqQmFybkdBQ3pEQVo4LXpwUDhhVzh5cXFDQ25GdHdiU1hGOUtiNkVEZzRPckNqZmlpTlZXQTZHSFE2TDlPTnZvemozOXpvaU1nOTdDc2dLY2tZTnUxTXo3NWhtSG14NjdudzZLdFBrcnBBRTFmVDBzeDlYdUtWczhUWEdlUFdvVHREMGRDOUVTRjRsV3RPMnpoV3NsTzhHaWVkQnhjTDVUOTNmWGFwR05sbG12d2lIVWx3S29TSFVnS2JwVWp6MU9WenBGM0l0TGNzVnpoRXlRQXJKakp4THoyNkFGSzVaTE5NUGc0Z2V4ZlRtMmI3YTNkX0g0LUhvMlY0THE4WDVMN1ZBZzh2b1dXY0tfZnBfbERHLWp2STduQzFOYzd0UmkyWnkwU05zY2FKbVQyeE1pZ1ZZM1ZYaGJyRG9iQXJvbjZBZkJlZjRibE9PMHNVTFdWMVRobzVMMmc3TEs1alc1am41bjRYSDkzNEYydTNPazhwT211T25HOWwzZDVySy1zWVpYQ3g3NENqVDJmN3BjZ3FiQ2F3cExBMmx2T1VqOVFublRiaVpkQzc5LXF4YVpZWXRUOVc4dEFVQllpQllJTUY3UFl4ME1KaFVWUFBWM1NMR0syTkJURTF2bWM2c1RFZ2l3ODltcTRPakJLZ3hUTTNNa2paRGJzMm1OVktqUjhHODBYYjlKX3VMOWYzRzI1c1RBemdVcDB5ZEItaHR3OGFwRDlmRkhSZzhYSEdDZTVmSHNGTDNpejJvb0d0RTRkeHZSQ1ZDLW5lY3FtRG1KMS1jMEZkVDE4djRWX2ZZcGc3QXpNQzNYT2xQLXNiOE5KS2d6RUZOZldseUtHWXhaRkt6R0RhZnBBYjdEYUloWVpmU2Faa3Ftbnh4eHpDbGVrSTk2T2ZnZElsbkgtUEd6dW5Nb2FvcElxN0lPek1rZGVPazBpUFF6VmtDUGxxc0M0LXZ1enFJODZvLTQxbHZGVmhpU20yeEozRHJWQzBXbGpVUjlPVVZ0R2JoNEF3Zm8tb3hMdVFLMW1Ma2pqLW1yNkQ3d3ktNDBrcmdOV1ZLeEpET0Z4UEhnOVBQc09xQlBvbWpwUXpkNUowYWg1RmdvNk9uODJlVmVRZzdHRzkwUjZZbVBSR2dFVFVQUWl0XzRHZGE0U0xnTVZDSktZdGZvZHY2WWQwZ2pSZzJEVW5qZUtOVUp3c1RjSEhyYWs3MXNRaVNfVmRtekZsSm1CNjVhYjFlSE9VQ2I4SmtYalF1XzR3UmZXdnhuc1VmcExWd1VMMGNmNi1YWmp1RVpIUF9PaGlGWDlzWldTSjBLS1RfVFI4RzFTbWpFcTZUbXhKa1E1RHRnV014OWNwTjJSRlNwcWFyU1V0STJtUWNIM191U0tERjNuY1lhWDl0Vk55ZGpEOFloUkdwWHVQdk4wWHZyejBKTklHLVBWeVlqUUJPdXNvOF9GeV9yX0ctSmVhdVNxMFRpVUhEUVM0Yl96ZDlfQWxMM2wySzZJdzAyQkVhWEhwb2Jpd3pFeEdFeU4weWFVMDRVNjliUEl5TGxIcy1sVVpnMTl5Z3hOR2pzdkxDaktqQ2gzdlhxdDRsMnlZZmFnY0RHSzdWcXpUYzhDWG5wZ1p1bnR3LnRTWm9BN2tNdGItRVJtRWs3d2MyT2c\"\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultrestoresecret.json",
    "content": "{\n\t\"contentType\": \"aNewSecretKey\",\n\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/secrets/mySecret/8c418537cbc948539ea2ac12c0bfcfb4\",\n\t\"attributes\": {\n\t\t\"enabled\": true,\n\t\t\"created\": 1509335944,\n\t\t\"updated\": 1509335944,\n\t\t\"recoveryLevel\": \"Purgeable\"\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultrestoresecretrequestbody.json",
    "content": "{\n    \"value\": \"KUF6dXJlS2V5VmF1bHRTZWNyZXRCYWNrdXBWMS5taWNyb3NvZnQuY29tZXlKcmFXUWlPaUppTTJJd1pqZ3dZeTB5Wkdaa0xUUmlPVGt0T0RVeE1TMWpZVGRrTTJKbFlURTVNMkVpTENKaGJHY2lPaUpTVTBFdFQwRkZVQ0lzSW1WdVl5STZJa0V4TWpoRFFrTXRTRk15TlRZaWZRLlFLelA2anZVR0Y5X1M3UU8tRkZDTHIyNGp0RXJuandkQThNZUtsSGE1MmhvS01rNjdiOHQyckZhNTJ6dGR2and1d1I3VWh4RldRLUpuOHk3YlJiNlYtcTlUYl9iV3E5clplUlhpUy1jdUhPak9ONHB1bHd1cVVmQkJOU2V3NlJGUXpOUzRrQks3RmxQSGZpQVRRaUUtLTc1cnZIM0dMTEdDd25KTkxIUDNTR0FtWlR1dXo0bTN6X1owR3RsZUU5XzFZT3pqczU1UmJFNEdOTC0tWDhDWnlRWmVFNGdGRXZ2WmFrYkRXTk5hOWd6SnBUNlNOTm5tcGtpMFZocGxaNGdzWmNmR29xQktZNF8wTS1WTmpIbkZ5QUlySXdsSTNjZkIzWUVCbHJ3X1A1QXhQVFFvNDJNa1pETmNKYjFwaGh0c1phaTNLcWRxT0E0ZEVWNVZWQ1VNZy5fTkN5eTNJSS1VV1VtWDB4UXhTVnNRLjJkbEFpUEpSa3NlenNVTEZocTE3ZmdCWm11XzBBaU5GUWkyTU8zMnlVanpEMjMxQlY0bHhwU21ZMmI1bGdsTXlYQzNtYy1PT2VmcVNseXdqMlcwTllOYzJKOUg4MzFHc0VCdXZ1SS1BWEQ3dzdocGRNTG5VaG5DQ0RUQTJYY0ZTZ2lXTWMzMFFISHUzRi1KcDh2VGU1QUk5R1ljelEzSFVPRjJOREpjRERoLU9CNFFJRlZWMS0zWEJkeS1uOWR5MjlSY0FwNEo4WHRPMjZxN2dJa3BDT1JxMTVuOXZHd3ViVlZhdGhfMlZwM3p1ZEJPX3k5SlFTVVYxMW1jZFVIQXNCVGxFMU5xYkZaU0lfX093NTl6ZktGRTVTMnZrYWl6a1RFbXFVQi1EcTVnMnMxQ05PcUdUNk1wQWNiSEtUNTNSajNZN2RlOFlBckZIMlNSZF9udUV6Q09PMnAxeFpFUjh4c2RIRjlDM1Nnc3ZRQzIzX3BfeDBIR1RfbWY5V3B4amZOWF9Bd1E5NWNLZ0JOdU1ENEZ1TTdWTmpKc1JaSGtvM2tNTlJ5N3BybkhhaVd5aHRiVV9ic0w3X3FRa1JGNEl3eGFzUlh6M3RtZzYyT2tCWl82MEMyRE11Q0pIZWtqSnI5SGJDeGp6Z1lGMjVmRDhDTk00YmNaRV9ma1Z4Y2lVVklWU2lvemREX3owTFBMY09paVp6dTNIWGIxekplZkJsVXduc1NBT0RZa2lWbjJPMjFOMHpkRGwwMjNPSnJTdWQycWo1UkEtVTlsVWRxU0w1QUltN1ZaMTFSVzh5clpkWXc4NFJTejVySldRSm1sVW54RzJHb3lMMTFaQkJacXY5bEJ5Wnd3SDN6ZGNDZWFRQWM0LVZJWjQ5NzBfTC1tT2paNUFwdXI4UERHVDIydkNKdEw1cVVaNGJabThBeXQ0NDFEX2o2cG16NzRUWWlIU210ZnlJcnNvRTMzbG9QM0xGdTFKMklXLXJTdk9HUElveEx1ai1ZMkNKMENYTk1lR0UyQVNhOEY5RmY3enhVLVRkbVZneWpfYi1EY05XUmVJZUMyTEF4OV9EWDY0QlRJV0pNSFc3a2plbjRkem9kajMzbjM1aFU0UUVmRVM0a2pmUUtMVENrYnRlWXliVUlQWmhaa3BDRzRpTVBQSVpTRVdqU2RMckl6NlRYN3FJZHFHcE1UYk9zeld3eWc2dzI1WTd4aDFvelY2RjJEOFpKR3FiZjhQZTVDRWtIcE5LeC1kNExUTzNsOWZlZVd6RFRwTzRnTWpBZ1RNdHBqdXRqT2xhSEYyN1JLaVNGWU82eFNQY0ZVb3JGMlZKRERlQUxZSk9Pb0JOMkhpalJ1Y0R5bWR3NUtzNHBZTmZvV3dCeHVnbjBPenJoNVFIS2Q3dWpoUll1XzhkLWd2RVNKQzNJY3JZWFI1aFhxaUp5WGVNMGtULWlnRUFQRFVmSXE0cjJiRW5iZ0RhdUZrN2syekZzXzZzeGZ4Ty1TNEp0alp2UkJia0lnZm1WdVB5OXZTQy02QUl0aEctMW5OUE9PNG1oak9ON2EzVUdzQVpvREg0T1RFczA3ajJMQ092VGdqX05PN1pJcEt6LWhyU0daSXdCdjlRdHJ5NjY4US1kTUpRZzAzRi1UXzZlX1htc1BWRWt1RWdaSzdnS092STNzdjk4Y0VVODFiVEZfNjQ3cmE5bjN6NHdnbmZwVE1lWEhMQ1JWeGpKbHJURmxJcW9wbkdZeHlQdm5iVXBzb3A2NktHbVAtTEpTeERjNlJJckpuQ2drbjN1OGN0c25NZWxuWHZSeGZFdFRsNnkyendUV3ZSdnVEcVR1UFphQXdNVmllbTdaaXZqNTdMYjNHT3RUcjBxQXNrMC15dHN2TkpmY19tYTEydVlUWll1b2RCM2ZoVFBITjFaclFoQzdiWDVHdXFDUFFDQXFuenJjT0lESDIweTFlZHAxam1ZdTFyZThPaG9yMDRiVWhLa2stcUVVdEVsZTFqYzFTckNuWkEyMlRZMFNVYkxkVm1hb2dyaUJfckpackVaM0tneGFaSjNnZ3FQd2NhSW0wNUVoMDQwYUpUa20xOWdzRzVCNEExQ2dDWHRMOGhUMFl4TmNneW9tT0dnRzd2Q2FzdW43WGhtdjJZLWROWVNrZzRZbzlfdkktWWlmZEp2MnhJVWY3eGFvS1RRRzY4NkNzaE0zTkVubFRWb1FjaWxjaXllaHc3RkpiMnYyTDFNV0tlamRWM2dPNjIyVjZ3QXV4MW9GdXJhdWZORzh2cnkyS2NwczFOUzBWeFJObU9mNDFkbFRhSkljUmFJM2tSbUg5UkpTakJZcnA1Y1ZzZWh5WGVaQXpnU2JzUlg0eGp6LURJSGVPa1dRS05HMlZvTnloZ3BZS05FVnlNN2dkdFBWTUo3TmlkVE9PM3BaYTBMeV9GaUhHLXc0dkUwTTR0X1ZpOFhvRzBFbWhJcjBWdmRvN0RGUXVUbmdoblRGVnpreEtyRlJSZzRMWkhCNzR2Z1BycTVTNGxTV2hlZGRfekRad2JVeUxJY1NXWmk3QzlpWDctczNHeGp2UjNGekxJT3NuSXUxVHpaQ3B4a0d4ZGkzU1VyS1c0NGlTaDM3eGNmaEpsNDVDcTQ5N1pQQmo1eVA0UmYwazVTS3djM1JvOUJoUXN0aUdzVk5qMlIzcmpHTHZfOEwtUHNxOG1IYTZKZHVvaEtRbEVQT1hYNzZ5aDdab05KUUZhemRNRWV3eVJNOGQ3eUZIcFc0M3RTZTA4Mi1BUmRjcW55OXFZRmJLMFJfV3dNTDlOQkFpNWxjQldUSms2ZHJXN1RPRmJ2eDFyZ0p5cUcza2w4TEdwRExheFNfaFhXZVRxSy1YS3pVRk9zNjA4WEp6U2NhVE1xay1QTVZIdkN5c3Vjci1mOFN3SF9wdks0bTNQYWprcGVOMjl3dmVZdUp1X1ZKZHlPNE9yY043cnRYVXR3VWNSblBzNUNXYWF0N1RfUWhnZ1VTdHBZczBJTlVuNXU2Rm5oNGVsUUxTTEhvdWZDdE9RekpDV0VVd3N2TWdkdkc2cEUzU2FZU244OFd6YzdMbGctZEVMeERLQXE1dmI1bXFleXAyem9hZFhJa20wWks5amlwdnBZdmQyRlFnNE50NF9nOUo3WTRoeVp3TjFWdXlqQ2YyUkFpMzJXZlNid1B4ZmdVdjhVVkktcUlKWjc5TjNQOTFnWnB4X2xxdF9aNFB0bzIwTTZqamw0MGkwUXRwMUdaRU5hbHoxN00zbFRBUl81WkY5Ql81dTIwN1FGbGh3UDYzbFRNMF8td1lCOVBzV2VtdGJUTEZYZmJFU0t6VGVzckVzQWwzQkVDMFotSndhMno3cEc3VHhvQWhON21hWDdKajVjbWtzdmJjVk05MENSNTVwbmtwOUM0Tm1BRWM2amw1dXRBSGlGOEdaV1A1V2lGVFFwVTBpYktXLUVycEMyblVvRVBmbFRPbVowM2lzaFNLbnZTSUFUQjBMSW95S1lhYm9tcU5NWkZhWDV5OWVjTGtFdmlmYS04dW8zRzNYSWFhQWk3TE5YRXpqQm9iZWlVSzBFeGJxaGd0VzNvbE85V1o1MGxqOWw5UXpGV3FWOGRiUThOeTdkdzRnT2wzNl93ZVNrbHJ3b19VVDA0Sm9Oc0IzOWFrUnJaWkdzaXJuamR1T0F4RWZaaXRLdHdTdkpZSzRtV0huSk5uRENMVlo2cVpzVG50NThjVjQ2cFY3T1FxckNpVnlQREU3Y1N0RW5neXhEbzRZdlpibDNrNndkaGxYOXAwZXNaOUdXbHNxcXlGVUJCc19QbVN2UUd6djZ3bDlWSnk4WnNKYmpIdlkwclZOUFJnN2FYTjlNOElsVWpia3B6RmdqY0VPZVVrZ1M5UFp5RURLYUw5U2NjeFJFbjI1OUR3MDFJZFJPS2U5Mnp3U1hSQUJlbVhBcVRaSGZPd1Z2VDBUS2JnWkwxcE5vb242NWRMR0hKZ2dYWmt6SjVHT3dvbFRkYkEwczVkaXRQZllxU3ZwQmpmVHpfQTZhTWl3bmFnamlET0QzT2doeTQxc1Q2UDdTWTFxanpfWkxjZ1puc1djWDlkOWc4TkpzZ1had184d2dUY3hRdW1TM3oxVTYxX2dlbndBNzNPaEs5MWl5YW90Z2ZySWNzOWxodm1taEcwRC1KX3lkQUxfdXNROWc0dHRlN1ptN0hMZDZOb1pCYnJFTkZ0ODRmejdJbjJxMXItM1lsYk9kMm1xRXIxZUdZMmtCTlh1eFc0XzlVZVFOZER5UHZPRFR0Ni1mR3FuMF9sd2dYOXJldUxsRzY1UjFKY29yMnczWmZBLWU3SEN3Y2tCTTBEcmhjZmwxdmhtcVY4WXpMcHBxUUhPa1F2YUpMNHE2ZG1ZS0thZmhGbXcxVk1qSnp5UWswUVNzazFWUGdzUmpta3l0YmpjZjRoenJNdVRMU0VQTGZVWGVPOEYzbEdLNE03bWlhblRPQ0xXSmRNWnc5dFlKSHVTQ0g3SjhZOUVwNS1XWTRBeUZlaFJfaDVSNHVYdlBPUmUzSzZQcWJibHlaMEJuclpCcDZnTUNvNVcwZkd5ZEdiQ1N6dzUzVndsY3FEWnJlb0p0Rk5pZFNzdTBtLUFub1g0SWxsSFFnYVB4SnlLYWRPSWpvalNKMnZTTTZCYXRkci1pR3VTbDJSZmswLXkyX3FFeDZRakNOQWFXaWNvM2RsS3VIY0h6TU13YzVXT1J4bzdweXdWYmtOUmpoOUVPZlkxSW51Tk11SjdfYWt2T0V5MGpMVXlCc04zR0hrTzlEUExFLTk2bVlIMWd6R19IbGQ5aVRpOWcxZTB5WjdBVkNEQzBoaVRZMXB5V0pVanpGVE91clJaYW5qOWl5MWdjcFdpeFVPN2xiWjl2aHFhdHg0VUh4VFRneS1IbUcydmRTYjhJbGl2bHNqLXVpM3dxUjBYeVNXRDFVYmVJUFVIZk15bTR2bXkzdkIyWEJKMEJnTF80bkx2VWQ2MEpFdXI1Z0ZOSUUtR0RSY0JwSkdPZXN4b1lyQktYU1I2QUd1UG84b2ptemFudUFIaF83OTI5OWg2aDdtN3JRZ0NxYzJ0Wjg1dU9YVHNzZzRYSW1kVjdCN3ZrcHRlUmt5WjZEQ1RFYW5GRmNvWEJzSThYMVFZeFFDRzgtdzltYlppTHNiRGN6bVV5Z3RiRkNQUXludjByclNiRzFUUWtmZnk4UGVfT0tRYkxSdWJNNG55dmZxWG81X21FcXA0T1dzMlJSMDhiSE9YTWpDU0FlYUwyaC1RRjg2MmRrLUNpV05ZSVVuUHhTYWkyWTEzeGVqVklwYkI1YkZzaVUzTWJmY2pyNnduRUVuMmhzWGx1aGpWVXFtUzNIOEZwZDFkS0pSa1lzM2NWZWRHTEhaRFZRM0hTWHlBWk1FbXNzX01kTUlGMFZhUjU0WTU3QXhhcnR5QUFmZy1OWWtkNVhtVkxPQWJnRFdCMzdrbEVPVEZCYXV4SGg4dXJjVk9neVF6Z1RNcTIwTWpEUzhzaDlZLUNHNUxSRHJiYVlRU2ZoR0VSYVFYcFpuVEdWX20tcDFpWU1zMEMzRFBJanMxSWIxZVR4X0lJbTFPRlBGOWcwWVJsbXFCdkx2bGtGeExqM0t2SGxQVEUwaUYyZ1JaMmN4NUMtckJGZ0dXaU1hRUQzdjcxTW0xQlFJeklaY1lfUUI5V3FsWEVaSmJWZHNZc0FmNm93eW9XckpVQUszTEswclRPaEdNS2VaUzlzUGxvZWU4T0x2OTluc2wxRUM0Z3F2MHJqdk9JQ0pVR0kwb1R1dXV5enhSbU41cHJtX2VycHNLbkM3QmRXV3VaLXRab0g0c2ZDeExiYVppeW8tQU1xdVRhMzB0ckFOV21rSUtuTHFubFRvcXJXZ1JiQjF3Q0hlVjA4WXR1ak9sQUdKc0dHRTRLVjc0X2QwSXZ2NXA3RUxQZlJJcU51cGVLdlpTZ0pxU19tQmU0eG5wTFZsWDhmaHRIOE9aSUxKQ25ZQUt5VHZyNGFoZG9jd0NrOE9JX0xVOG5wQ1Rpc1VFdEo1MXpON2dqUEs2eGhCazZ1YnNNeE9oalhNSjhUd01sWHZvMjcwSXdYV08wVm1lN3pGbnp2S3dnWjV0UlB4c1hwTjlySDBlLUxIZU9uNHIzWWtHeHlpRDFrMkUyM0s4ay02RmxhM2JwMV9DQktfdkM0VUhBU3NqQnJjd21kOHVvYzdJTDRsQmRfeldQbEtyUXp6bmxyZVlMV2w3S1RmdG5ELXF0STlLMlFpWm9Ib3E4anZSYUJTTjZqUTk3RXhEb0E5dUk1LVRFc21UYlpCV3pGemdoOS1mbXBKZmQ1R3VNUXVhblJDN2VPbzh4bkJrVnI2UVVnZjVhYzV6Um0zc1ZBaktBVDJ5djc0dTNyOEJjUEJMcTBsc1gwTUpza3FlNEZhN193NXB5Q0Y4dS1RbVFkN2dmeUdPSW1OdTgySGJPSk5yMHg4Vm9NZU9uUExsVUhyY2cxNk43czY5ekU3SEM2UExpcHJobHdmY2JvMXlaZDZYVUxYNGI5MXJ4ME5SU0VpYURISGV1QS1LNWFQb1F6VVZiSFJ0cExvdHpwTEFTZkhwMWFhSEoyakRQUElfcVllbzkwWjVrR3RiV2plSTBYVDlzMy1TMk5pcW16Z2Q5WEMxNEJaUTM0UWpNdksyNUpJYXpqWW5FdGQzYUFYRWFZNU9CdGZ5R2NIcV96UmRaZlVQdDdDNk1LTFdRbnpzTXNWZHJ4cnpCcWRMMVV0NzlIQnZ5M3RlWDZ0RmJuYjR2ZkgxY3NZUl82a041T205VndHelRZYWNGM1dDTkNuOHljMk13N1Y4b25ZOXFLU0VLS1hRYk5KYlB1cEJsT29qLV9tV1drTkdmSy1TUHJoRmFGNF9LaDFTd25TelBydHRVVU9WMXg4ejNmUVFXZml5eVllcGd0VHVGSEZheHE0YXNCUjRQVndfUnBJN3c4QTNiSGR5ODQteWprZU0wU0k4WE5CdkRmVThRXzA2aVZjWkg1UWhwU2VENVpZNWotcDNzN3c4X2MtRXo3RHRZaHgyQzducWU2OFNVYmt3dmd4d2RUOFhaYzcySTJwSUFwYklPTzN0SEFIVmpvVHdVX3dsSHctSVZKbzZfSlBvRE5JbEdZcHdDZ21oMV9rb2FCLXFvMGdQd0UyeG1sRmdNeVVCd3lfWHNEdVRUcVJfT3pYVHBQbWdhTWNZMXJldEgzVjBDZ3BHaTBqYVZoN2NJSUpoVWNRcXRIVHl6S1hDTWVMRVBXYzJuVV9oXzB5U0tTanJMUmR1cHpkMTZ6V2sxdTRzdDRDak9CR1AxbloxVU14X3lGQ3ZsVVlESGY5OHhBelJNbUg0c1YxMnVMYmlCS2l0eTEwSG83X2N6T0htQ09LeE1oaFlhRmVrS19veUU3X3pWbTRjUzhHbEJiMUo2UVZMeHpGMXlORnlqeHdITEtnNURXUzN1T0JfSGpNdHlMOHh4WXhNR2FjNTh1X2g5ZEM5QThtVGJ5bEF6Wll6eTUtU3pvSVJYZHhVOGtBN1c0QzFWYmI1VGgyVHZmemF1Vk1mNVg0SWc1WTU4NzMtd3oxNVpHZW5xU3JreFVqU0tVUWVlZkI2eEg1aGtKeWs1cDZWY1JJNzF6SkVEVEU2LWZHSGsxTlNRd2QtS2tTaWlwMjI2d0JCOHZSVWdGQ1VZcy1EZC10TXF1aDdKZjlaRTU5amNzR0ZkTDJhamFRcjc4Z21VZEFVYS1HRHpQeHp3YkM0b1FKS29ObkNEZGc5WV94S3NHeEtDWnRVT1VjM0Z4MlptZFpfM292ZGExaHdyVDZpYVJLM0MxZnh0ZVpheE9IWkNvdW5MeU8wZUkzZ1Nnd2dkVERxODZ3TzY2U3pHdGRxYmo0bGZrT3NkRUYtUDNhQU1yOGNuclh3b2NOdGVpaVJ0YnVqLXhfNlVQUk5hWHJCV0lHRk1Mc2x3b1VlRXE1ZUpuOUhSYmdvd25vU3psOUdDWWdtdnRsb1ZIVHFVLXpNWk9TcmxPejA2aU1ZZjBjakliUDJtdHUyWHlDS3dkRnFsZHJqUWs3VmNUUEJkczluRjR2Z3lmOU1nSFVTeVpHTHFubHNtdG5ER1p4VTN0UmR1eXZfTFRLcDgxYVVQVVprb0EtTkMzdEFncHdQbUtodzVnY3M4U19aSC16VVNFd1BjLVR6NGtJSzhrSFVxQ2ZFY0pfMmhpX2RTWHRKbFB3TG9EeU95R1hTWkp5ZGIzb2hjblk3Z3RneGpQaU82Vmlwd1NZMXRVVUV1YmFKbHkzTGFwRjN0cXlEZXBBdHMxc2JDdzNSSm1HcE92WjlfaTk5SXZ6WjY1WDZPSDB1YUpDTWl6bFpzdGQwZ1FRMXl2ZTNQRDRaVHZPdzlMMm9Na0ZDQlFvQzBUalU5b0tPTHNpdlAzbTZOWjROLVpiaWFaNTIxbWU1ZjBWV1loRkN3RENxajRyUDZ5WmloOXVPTW5rWnNhZ3BtS0RlaVV6d1RpaENKdlRkZnBfbG1GQ3cyc0Jyd0lIVWJfdkxWY1RWNDd4NVNwSnhuS2dpWHpZUG8weElnYnY1bmZGWTJvM1NBWkZpSlNlNEJQbmFsX2FQLUFnNDdWM2h5NmNzT0xCM3l0VlNCRDdlNjFpU1VGWVhBUmZJVEVXa0VRaHBIWWJyRTlvemdldzdOLU5HaXdtWndOUy04SUFSbmRFS0tXSXRXb01fMllXVmYxS1ZoME8xQ2wwR0ZDV2NCNzFDLWxMazVJbkpKUm5Wd2dPQ1M2YUFKaEM2T2pIVVYydTR3TTdndFI1c1Y2Snk1NUxQcjFUbVpZQXAyVFNSMG0zUWMyN0ZKRnhxaFU2R20tZGtVNXZKbGtnSjUwY2xTUVVGcVl4Z0pDX1hSdWVpOXNzdkNmbnZVOW1ZSEFQZTU2Q2dXNWFiVGhSOEJCcTc2aTlxUjBlRVV4eFVWUUtCemFhVlB3TmVqaFRVYnpWcHZnNGlqSFRocFBlRzdDZ3hwQ00zT0pCaHFnS2k3RzVTeHFHYjdNVEhoclp2Q3I2WHZtZGdFc3NxWW9RdUQyYUQ4TlhjdVU0Mm1NVGwyZS1sY2pwU1E5R29hdlRHSjFCeFp2YWlYZzRNS1FGUjBjRDQzYkxsaXo2Y2NCeEEwZnJTU2dqbUhRNERxdHhjYkFiNFlPTDFlYkFQNFNSQnJwa3hGQW5fc1l6ci1aR0F0R0l3R1JfUHRRbjVLQ05yaXBueDRITVBmS2UtTHg4MzBIWFNxVGV5c0hRbGtuRlRSeFdwLXdNcUxPMlFhTHJnMlUzdnBDekloRmh4dG1tWnpPSE8zZmY2YTAySk9BaDVDek9GcG9oTDFXakl5a1RMd0dNMDZMQ25uNmhGeDVOZEhmVTlqaTdKNGZuT2RkcVh2ZnZ4TDhSN0wtM1d6SThIUVI4TkRHRzl6ZGtHZDUyQVlkNTBqUTZPN29qNUdkZldGMDdQTVY3WWFETjhGc1YwT19wZDM5bFpiUnM0SlV1Y0xWMzBXNGpqVGdselZGeXBaZEFxQXU0d2pWTVd5T1I0X1RSMnh6YW0wemx0ZXc1bm01TUk4NTlZYVhCVE95bkV5T18yRndDR2hzdmxQR2t5SHZuc050NFVya3pjRGswX0JaYUlYYWFNbUhxMUJQUWdiR0d6bUxNV0FXcFY0OUszdnBkN250WHFBZEVyN25VUnVpS2RSckVTYnpEUnAxclh2NExOMUdGNXRnRUFCZFhwYTVQVG9nVDM3cHUwb1BNNW5FZXFDeklRbmtjemMzUVk5SEZwY1J6bWFmbV9fSngxRFd0ak5qR1J0cVM4aHVUcVNKOG5ORl90ZXZsV2dwOU5uZU9KSUZwZkVMMnhYMTc2dnkyQ1FONTBFRzZZWmM4dXZreHFNUmk3OFNjdENEeXQ0WS5Sc3FFM1dad19XclIxRmtQc1RtWW1B\"\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultsamplesecret.txt",
    "content": "-----BEGIN RSA PRIVATE KEY-----\nMIIEogIBAAKCAQEAvZiOgV6b4EmGiasBskXYnTaRyWzBHBGnWB11BzFN3FGigfWx\nVvjI7Ox1SHTx+vGsnjbqQPvIP4JnPEsNcWLyHa6tNAcnj/M7BuyIwdD5+Hvs6kOe\nPuSOJUf8dRjPMUpr6rcUcBmmOwTnKOH4rdpb6jXNnuCIHP+lgXCeRWveZ62TjEB+\n9aB8W8UHH854FGebiUd/aY0tpCFC7wkWz3KbgmjmY2vSe2U98Yj4+l/IWydIZ7ON\nLicteEEIGbNM0o2QSYhQBCJSw5RixDpPlrUUB094qgqUOyW0k8PvjibGxxTh0LYy\nWqWydPF0XaqFRQ6v36UvEiVGwzVsLwsJL/QVtQIDAQABAoIBAEJ6790lE3s9zNMR\nB3M/UoktzUjXvY7eEdOv4I05GJgcd+MiB6D7c1jAQQ+7Ee5wN5rynolSwBCk5RYb\nKweLLmKCEXGg4Jp1K0luPzXW1Q/wRE6Qjzh2Y/FmoHtey6f49IZE1AHKvKMNQRDw\ny4YKfxhM7WC8Un34lkwg9R5aiI3JkOG9/yNkOGrJfQnGUKt+AOAdu6fNYsRLWAPo\nG3vWSNIgwaG5WL5cKd1gacbGBlc6tLB7+LrZuNrqln5ibTtN6QJvRF9KfOrMSvxy\nL/xiHRpyzec/jrxJxAIIwFHiw2jbLdxNqDaVPFA6X1Cks4fvY40KymOS8Ecmkgx4\nC6/ZqLECgYEA38rL8zmbJRRWgrxSoROucaN/9DyvE8Hd97s1zf3I0LIF+GI3JdcN\nDV5O5VDIgQ7QZ55lOaTqJ0f2fOQZF1UbTU1gBUHVF6j1nv6Xic3OV+ZmhTMbt0Op\nWxPaKup6dkNEAe/Xg0p308r8xw/psh4/gjL1ICHwycjUlz9FQz8FLGsCgYEA2OHc\n/F4vAdK04U4w6AyivuJdIsDAks1ikl+3TqgzyesPg+DpKVNSy6DhraDFKdRqWhbK\nDqigTud8TVk9kmyF3WIb1BDf4IrxlTK08s6Jf25QA/lBlwIst3rejqWwRBY2fJp4\nO8hU31xNLd8nZq8tKYaP+yvyI6fSC+9ZIgyATl8CgYBtTlYzZG2cvMRMcsNBHaXU\np3E1z/YLhmNuPqhXBp/xHyK/YOliuBkN8IREiSKFtsCf+8OhViVwLjv8YETJGq6N\nIT/HEZKNTd86W0uU6UrhsA1e/cmJx6iObbHfyEssPEqZT5ZJ8DN65Oh2KhWRBCks\n5MrJeQps5ITBowunfr5+JQKBgBln09goPD9tbEzcOPRlzoanw5s3kxdfQcW9up5X\nK8HibC3ZodZ6cT9zOBx7sbzlqhOlicPP0v+LNE9nPcQyPDgjrvjXhTIrdIMyrmmm\n8gpgZLUidKF42r4fgYSaOhyvsXBFNAJkxDRp/ox6EIaBzLuJjMIycqnklcFaJ0nK\nxxjnAoGAU/3jRok74Yn0MY183UCXICf/WxVYzwEi3cyRWVh6gAo2ExNye97rau/B\nY2woAcVxEN9h1HNirq8Z2AwrZKd/BcBnvulZqECeH5zBQ0W56ADX72r+lzOAxTJa\nU1AIlNCIkfsQ5CpIoYsVoNEM8P+GyS8B9kaEmk/FVKldRTKJqkI=\n-----END RSA PRIVATE KEY-----"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultsecretbackup.txt",
    "content": "KUF6dXJlS2V5VmF1bHRTZWNyZXRCYWNrdXBWMS5taWNyb3NvZnQuY29tZXlKcmFXUWlPaUppTTJJd1pqZ3dZeTB5Wkdaa0xUUmlPVGt0T0RVeE1TMWpZVGRrTTJKbFlURTVNMkVpTENKaGJHY2lPaUpTVTBFdFQwRkZVQ0lzSW1WdVl5STZJa0V4TWpoRFFrTXRTRk15TlRZaWZRLlFLelA2anZVR0Y5X1M3UU8tRkZDTHIyNGp0RXJuandkQThNZUtsSGE1MmhvS01rNjdiOHQyckZhNTJ6dGR2and1d1I3VWh4RldRLUpuOHk3YlJiNlYtcTlUYl9iV3E5clplUlhpUy1jdUhPak9ONHB1bHd1cVVmQkJOU2V3NlJGUXpOUzRrQks3RmxQSGZpQVRRaUUtLTc1cnZIM0dMTEdDd25KTkxIUDNTR0FtWlR1dXo0bTN6X1owR3RsZUU5XzFZT3pqczU1UmJFNEdOTC0tWDhDWnlRWmVFNGdGRXZ2WmFrYkRXTk5hOWd6SnBUNlNOTm5tcGtpMFZocGxaNGdzWmNmR29xQktZNF8wTS1WTmpIbkZ5QUlySXdsSTNjZkIzWUVCbHJ3X1A1QXhQVFFvNDJNa1pETmNKYjFwaGh0c1phaTNLcWRxT0E0ZEVWNVZWQ1VNZy5fTkN5eTNJSS1VV1VtWDB4UXhTVnNRLjJkbEFpUEpSa3NlenNVTEZocTE3ZmdCWm11XzBBaU5GUWkyTU8zMnlVanpEMjMxQlY0bHhwU21ZMmI1bGdsTXlYQzNtYy1PT2VmcVNseXdqMlcwTllOYzJKOUg4MzFHc0VCdXZ1SS1BWEQ3dzdocGRNTG5VaG5DQ0RUQTJYY0ZTZ2lXTWMzMFFISHUzRi1KcDh2VGU1QUk5R1ljelEzSFVPRjJOREpjRERoLU9CNFFJRlZWMS0zWEJkeS1uOWR5MjlSY0FwNEo4WHRPMjZxN2dJa3BDT1JxMTVuOXZHd3ViVlZhdGhfMlZwM3p1ZEJPX3k5SlFTVVYxMW1jZFVIQXNCVGxFMU5xYkZaU0lfX093NTl6ZktGRTVTMnZrYWl6a1RFbXFVQi1EcTVnMnMxQ05PcUdUNk1wQWNiSEtUNTNSajNZN2RlOFlBckZIMlNSZF9udUV6Q09PMnAxeFpFUjh4c2RIRjlDM1Nnc3ZRQzIzX3BfeDBIR1RfbWY5V3B4amZOWF9Bd1E5NWNLZ0JOdU1ENEZ1TTdWTmpKc1JaSGtvM2tNTlJ5N3BybkhhaVd5aHRiVV9ic0w3X3FRa1JGNEl3eGFzUlh6M3RtZzYyT2tCWl82MEMyRE11Q0pIZWtqSnI5SGJDeGp6Z1lGMjVmRDhDTk00YmNaRV9ma1Z4Y2lVVklWU2lvemREX3owTFBMY09paVp6dTNIWGIxekplZkJsVXduc1NBT0RZa2lWbjJPMjFOMHpkRGwwMjNPSnJTdWQycWo1UkEtVTlsVWRxU0w1QUltN1ZaMTFSVzh5clpkWXc4NFJTejVySldRSm1sVW54RzJHb3lMMTFaQkJacXY5bEJ5Wnd3SDN6ZGNDZWFRQWM0LVZJWjQ5NzBfTC1tT2paNUFwdXI4UERHVDIydkNKdEw1cVVaNGJabThBeXQ0NDFEX2o2cG16NzRUWWlIU210ZnlJcnNvRTMzbG9QM0xGdTFKMklXLXJTdk9HUElveEx1ai1ZMkNKMENYTk1lR0UyQVNhOEY5RmY3enhVLVRkbVZneWpfYi1EY05XUmVJZUMyTEF4OV9EWDY0QlRJV0pNSFc3a2plbjRkem9kajMzbjM1aFU0UUVmRVM0a2pmUUtMVENrYnRlWXliVUlQWmhaa3BDRzRpTVBQSVpTRVdqU2RMckl6NlRYN3FJZHFHcE1UYk9zeld3eWc2dzI1WTd4aDFvelY2RjJEOFpKR3FiZjhQZTVDRWtIcE5LeC1kNExUTzNsOWZlZVd6RFRwTzRnTWpBZ1RNdHBqdXRqT2xhSEYyN1JLaVNGWU82eFNQY0ZVb3JGMlZKRERlQUxZSk9Pb0JOMkhpalJ1Y0R5bWR3NUtzNHBZTmZvV3dCeHVnbjBPenJoNVFIS2Q3dWpoUll1XzhkLWd2RVNKQzNJY3JZWFI1aFhxaUp5WGVNMGtULWlnRUFQRFVmSXE0cjJiRW5iZ0RhdUZrN2syekZzXzZzeGZ4Ty1TNEp0alp2UkJia0lnZm1WdVB5OXZTQy02QUl0aEctMW5OUE9PNG1oak9ON2EzVUdzQVpvREg0T1RFczA3ajJMQ092VGdqX05PN1pJcEt6LWhyU0daSXdCdjlRdHJ5NjY4US1kTUpRZzAzRi1UXzZlX1htc1BWRWt1RWdaSzdnS092STNzdjk4Y0VVODFiVEZfNjQ3cmE5bjN6NHdnbmZwVE1lWEhMQ1JWeGpKbHJURmxJcW9wbkdZeHlQdm5iVXBzb3A2NktHbVAtTEpTeERjNlJJckpuQ2drbjN1OGN0c25NZWxuWHZSeGZFdFRsNnkyendUV3ZSdnVEcVR1UFphQXdNVmllbTdaaXZqNTdMYjNHT3RUcjBxQXNrMC15dHN2TkpmY19tYTEydVlUWll1b2RCM2ZoVFBITjFaclFoQzdiWDVHdXFDUFFDQXFuenJjT0lESDIweTFlZHAxam1ZdTFyZThPaG9yMDRiVWhLa2stcUVVdEVsZTFqYzFTckNuWkEyMlRZMFNVYkxkVm1hb2dyaUJfckpackVaM0tneGFaSjNnZ3FQd2NhSW0wNUVoMDQwYUpUa20xOWdzRzVCNEExQ2dDWHRMOGhUMFl4TmNneW9tT0dnRzd2Q2FzdW43WGhtdjJZLWROWVNrZzRZbzlfdkktWWlmZEp2MnhJVWY3eGFvS1RRRzY4NkNzaE0zTkVubFRWb1FjaWxjaXllaHc3RkpiMnYyTDFNV0tlamRWM2dPNjIyVjZ3QXV4MW9GdXJhdWZORzh2cnkyS2NwczFOUzBWeFJObU9mNDFkbFRhSkljUmFJM2tSbUg5UkpTakJZcnA1Y1ZzZWh5WGVaQXpnU2JzUlg0eGp6LURJSGVPa1dRS05HMlZvTnloZ3BZS05FVnlNN2dkdFBWTUo3TmlkVE9PM3BaYTBMeV9GaUhHLXc0dkUwTTR0X1ZpOFhvRzBFbWhJcjBWdmRvN0RGUXVUbmdoblRGVnpreEtyRlJSZzRMWkhCNzR2Z1BycTVTNGxTV2hlZGRfekRad2JVeUxJY1NXWmk3QzlpWDctczNHeGp2UjNGekxJT3NuSXUxVHpaQ3B4a0d4ZGkzU1VyS1c0NGlTaDM3eGNmaEpsNDVDcTQ5N1pQQmo1eVA0UmYwazVTS3djM1JvOUJoUXN0aUdzVk5qMlIzcmpHTHZfOEwtUHNxOG1IYTZKZHVvaEtRbEVQT1hYNzZ5aDdab05KUUZhemRNRWV3eVJNOGQ3eUZIcFc0M3RTZTA4Mi1BUmRjcW55OXFZRmJLMFJfV3dNTDlOQkFpNWxjQldUSms2ZHJXN1RPRmJ2eDFyZ0p5cUcza2w4TEdwRExheFNfaFhXZVRxSy1YS3pVRk9zNjA4WEp6U2NhVE1xay1QTVZIdkN5c3Vjci1mOFN3SF9wdks0bTNQYWprcGVOMjl3dmVZdUp1X1ZKZHlPNE9yY043cnRYVXR3VWNSblBzNUNXYWF0N1RfUWhnZ1VTdHBZczBJTlVuNXU2Rm5oNGVsUUxTTEhvdWZDdE9RekpDV0VVd3N2TWdkdkc2cEUzU2FZU244OFd6YzdMbGctZEVMeERLQXE1dmI1bXFleXAyem9hZFhJa20wWks5amlwdnBZdmQyRlFnNE50NF9nOUo3WTRoeVp3TjFWdXlqQ2YyUkFpMzJXZlNid1B4ZmdVdjhVVkktcUlKWjc5TjNQOTFnWnB4X2xxdF9aNFB0bzIwTTZqamw0MGkwUXRwMUdaRU5hbHoxN00zbFRBUl81WkY5Ql81dTIwN1FGbGh3UDYzbFRNMF8td1lCOVBzV2VtdGJUTEZYZmJFU0t6VGVzckVzQWwzQkVDMFotSndhMno3cEc3VHhvQWhON21hWDdKajVjbWtzdmJjVk05MENSNTVwbmtwOUM0Tm1BRWM2amw1dXRBSGlGOEdaV1A1V2lGVFFwVTBpYktXLUVycEMyblVvRVBmbFRPbVowM2lzaFNLbnZTSUFUQjBMSW95S1lhYm9tcU5NWkZhWDV5OWVjTGtFdmlmYS04dW8zRzNYSWFhQWk3TE5YRXpqQm9iZWlVSzBFeGJxaGd0VzNvbE85V1o1MGxqOWw5UXpGV3FWOGRiUThOeTdkdzRnT2wzNl93ZVNrbHJ3b19VVDA0Sm9Oc0IzOWFrUnJaWkdzaXJuamR1T0F4RWZaaXRLdHdTdkpZSzRtV0huSk5uRENMVlo2cVpzVG50NThjVjQ2cFY3T1FxckNpVnlQREU3Y1N0RW5neXhEbzRZdlpibDNrNndkaGxYOXAwZXNaOUdXbHNxcXlGVUJCc19QbVN2UUd6djZ3bDlWSnk4WnNKYmpIdlkwclZOUFJnN2FYTjlNOElsVWpia3B6RmdqY0VPZVVrZ1M5UFp5RURLYUw5U2NjeFJFbjI1OUR3MDFJZFJPS2U5Mnp3U1hSQUJlbVhBcVRaSGZPd1Z2VDBUS2JnWkwxcE5vb242NWRMR0hKZ2dYWmt6SjVHT3dvbFRkYkEwczVkaXRQZllxU3ZwQmpmVHpfQTZhTWl3bmFnamlET0QzT2doeTQxc1Q2UDdTWTFxanpfWkxjZ1puc1djWDlkOWc4TkpzZ1had184d2dUY3hRdW1TM3oxVTYxX2dlbndBNzNPaEs5MWl5YW90Z2ZySWNzOWxodm1taEcwRC1KX3lkQUxfdXNROWc0dHRlN1ptN0hMZDZOb1pCYnJFTkZ0ODRmejdJbjJxMXItM1lsYk9kMm1xRXIxZUdZMmtCTlh1eFc0XzlVZVFOZER5UHZPRFR0Ni1mR3FuMF9sd2dYOXJldUxsRzY1UjFKY29yMnczWmZBLWU3SEN3Y2tCTTBEcmhjZmwxdmhtcVY4WXpMcHBxUUhPa1F2YUpMNHE2ZG1ZS0thZmhGbXcxVk1qSnp5UWswUVNzazFWUGdzUmpta3l0YmpjZjRoenJNdVRMU0VQTGZVWGVPOEYzbEdLNE03bWlhblRPQ0xXSmRNWnc5dFlKSHVTQ0g3SjhZOUVwNS1XWTRBeUZlaFJfaDVSNHVYdlBPUmUzSzZQcWJibHlaMEJuclpCcDZnTUNvNVcwZkd5ZEdiQ1N6dzUzVndsY3FEWnJlb0p0Rk5pZFNzdTBtLUFub1g0SWxsSFFnYVB4SnlLYWRPSWpvalNKMnZTTTZCYXRkci1pR3VTbDJSZmswLXkyX3FFeDZRakNOQWFXaWNvM2RsS3VIY0h6TU13YzVXT1J4bzdweXdWYmtOUmpoOUVPZlkxSW51Tk11SjdfYWt2T0V5MGpMVXlCc04zR0hrTzlEUExFLTk2bVlIMWd6R19IbGQ5aVRpOWcxZTB5WjdBVkNEQzBoaVRZMXB5V0pVanpGVE91clJaYW5qOWl5MWdjcFdpeFVPN2xiWjl2aHFhdHg0VUh4VFRneS1IbUcydmRTYjhJbGl2bHNqLXVpM3dxUjBYeVNXRDFVYmVJUFVIZk15bTR2bXkzdkIyWEJKMEJnTF80bkx2VWQ2MEpFdXI1Z0ZOSUUtR0RSY0JwSkdPZXN4b1lyQktYU1I2QUd1UG84b2ptemFudUFIaF83OTI5OWg2aDdtN3JRZ0NxYzJ0Wjg1dU9YVHNzZzRYSW1kVjdCN3ZrcHRlUmt5WjZEQ1RFYW5GRmNvWEJzSThYMVFZeFFDRzgtdzltYlppTHNiRGN6bVV5Z3RiRkNQUXludjByclNiRzFUUWtmZnk4UGVfT0tRYkxSdWJNNG55dmZxWG81X21FcXA0T1dzMlJSMDhiSE9YTWpDU0FlYUwyaC1RRjg2MmRrLUNpV05ZSVVuUHhTYWkyWTEzeGVqVklwYkI1YkZzaVUzTWJmY2pyNnduRUVuMmhzWGx1aGpWVXFtUzNIOEZwZDFkS0pSa1lzM2NWZWRHTEhaRFZRM0hTWHlBWk1FbXNzX01kTUlGMFZhUjU0WTU3QXhhcnR5QUFmZy1OWWtkNVhtVkxPQWJnRFdCMzdrbEVPVEZCYXV4SGg4dXJjVk9neVF6Z1RNcTIwTWpEUzhzaDlZLUNHNUxSRHJiYVlRU2ZoR0VSYVFYcFpuVEdWX20tcDFpWU1zMEMzRFBJanMxSWIxZVR4X0lJbTFPRlBGOWcwWVJsbXFCdkx2bGtGeExqM0t2SGxQVEUwaUYyZ1JaMmN4NUMtckJGZ0dXaU1hRUQzdjcxTW0xQlFJeklaY1lfUUI5V3FsWEVaSmJWZHNZc0FmNm93eW9XckpVQUszTEswclRPaEdNS2VaUzlzUGxvZWU4T0x2OTluc2wxRUM0Z3F2MHJqdk9JQ0pVR0kwb1R1dXV5enhSbU41cHJtX2VycHNLbkM3QmRXV3VaLXRab0g0c2ZDeExiYVppeW8tQU1xdVRhMzB0ckFOV21rSUtuTHFubFRvcXJXZ1JiQjF3Q0hlVjA4WXR1ak9sQUdKc0dHRTRLVjc0X2QwSXZ2NXA3RUxQZlJJcU51cGVLdlpTZ0pxU19tQmU0eG5wTFZsWDhmaHRIOE9aSUxKQ25ZQUt5VHZyNGFoZG9jd0NrOE9JX0xVOG5wQ1Rpc1VFdEo1MXpON2dqUEs2eGhCazZ1YnNNeE9oalhNSjhUd01sWHZvMjcwSXdYV08wVm1lN3pGbnp2S3dnWjV0UlB4c1hwTjlySDBlLUxIZU9uNHIzWWtHeHlpRDFrMkUyM0s4ay02RmxhM2JwMV9DQktfdkM0VUhBU3NqQnJjd21kOHVvYzdJTDRsQmRfeldQbEtyUXp6bmxyZVlMV2w3S1RmdG5ELXF0STlLMlFpWm9Ib3E4anZSYUJTTjZqUTk3RXhEb0E5dUk1LVRFc21UYlpCV3pGemdoOS1mbXBKZmQ1R3VNUXVhblJDN2VPbzh4bkJrVnI2UVVnZjVhYzV6Um0zc1ZBaktBVDJ5djc0dTNyOEJjUEJMcTBsc1gwTUpza3FlNEZhN193NXB5Q0Y4dS1RbVFkN2dmeUdPSW1OdTgySGJPSk5yMHg4Vm9NZU9uUExsVUhyY2cxNk43czY5ekU3SEM2UExpcHJobHdmY2JvMXlaZDZYVUxYNGI5MXJ4ME5SU0VpYURISGV1QS1LNWFQb1F6VVZiSFJ0cExvdHpwTEFTZkhwMWFhSEoyakRQUElfcVllbzkwWjVrR3RiV2plSTBYVDlzMy1TMk5pcW16Z2Q5WEMxNEJaUTM0UWpNdksyNUpJYXpqWW5FdGQzYUFYRWFZNU9CdGZ5R2NIcV96UmRaZlVQdDdDNk1LTFdRbnpzTXNWZHJ4cnpCcWRMMVV0NzlIQnZ5M3RlWDZ0RmJuYjR2ZkgxY3NZUl82a041T205VndHelRZYWNGM1dDTkNuOHljMk13N1Y4b25ZOXFLU0VLS1hRYk5KYlB1cEJsT29qLV9tV1drTkdmSy1TUHJoRmFGNF9LaDFTd25TelBydHRVVU9WMXg4ejNmUVFXZml5eVllcGd0VHVGSEZheHE0YXNCUjRQVndfUnBJN3c4QTNiSGR5ODQteWprZU0wU0k4WE5CdkRmVThRXzA2aVZjWkg1UWhwU2VENVpZNWotcDNzN3c4X2MtRXo3RHRZaHgyQzducWU2OFNVYmt3dmd4d2RUOFhaYzcySTJwSUFwYklPTzN0SEFIVmpvVHdVX3dsSHctSVZKbzZfSlBvRE5JbEdZcHdDZ21oMV9rb2FCLXFvMGdQd0UyeG1sRmdNeVVCd3lfWHNEdVRUcVJfT3pYVHBQbWdhTWNZMXJldEgzVjBDZ3BHaTBqYVZoN2NJSUpoVWNRcXRIVHl6S1hDTWVMRVBXYzJuVV9oXzB5U0tTanJMUmR1cHpkMTZ6V2sxdTRzdDRDak9CR1AxbloxVU14X3lGQ3ZsVVlESGY5OHhBelJNbUg0c1YxMnVMYmlCS2l0eTEwSG83X2N6T0htQ09LeE1oaFlhRmVrS19veUU3X3pWbTRjUzhHbEJiMUo2UVZMeHpGMXlORnlqeHdITEtnNURXUzN1T0JfSGpNdHlMOHh4WXhNR2FjNTh1X2g5ZEM5QThtVGJ5bEF6Wll6eTUtU3pvSVJYZHhVOGtBN1c0QzFWYmI1VGgyVHZmemF1Vk1mNVg0SWc1WTU4NzMtd3oxNVpHZW5xU3JreFVqU0tVUWVlZkI2eEg1aGtKeWs1cDZWY1JJNzF6SkVEVEU2LWZHSGsxTlNRd2QtS2tTaWlwMjI2d0JCOHZSVWdGQ1VZcy1EZC10TXF1aDdKZjlaRTU5amNzR0ZkTDJhamFRcjc4Z21VZEFVYS1HRHpQeHp3YkM0b1FKS29ObkNEZGc5WV94S3NHeEtDWnRVT1VjM0Z4MlptZFpfM292ZGExaHdyVDZpYVJLM0MxZnh0ZVpheE9IWkNvdW5MeU8wZUkzZ1Nnd2dkVERxODZ3TzY2U3pHdGRxYmo0bGZrT3NkRUYtUDNhQU1yOGNuclh3b2NOdGVpaVJ0YnVqLXhfNlVQUk5hWHJCV0lHRk1Mc2x3b1VlRXE1ZUpuOUhSYmdvd25vU3psOUdDWWdtdnRsb1ZIVHFVLXpNWk9TcmxPejA2aU1ZZjBjakliUDJtdHUyWHlDS3dkRnFsZHJqUWs3VmNUUEJkczluRjR2Z3lmOU1nSFVTeVpHTHFubHNtdG5ER1p4VTN0UmR1eXZfTFRLcDgxYVVQVVprb0EtTkMzdEFncHdQbUtodzVnY3M4U19aSC16VVNFd1BjLVR6NGtJSzhrSFVxQ2ZFY0pfMmhpX2RTWHRKbFB3TG9EeU95R1hTWkp5ZGIzb2hjblk3Z3RneGpQaU82Vmlwd1NZMXRVVUV1YmFKbHkzTGFwRjN0cXlEZXBBdHMxc2JDdzNSSm1HcE92WjlfaTk5SXZ6WjY1WDZPSDB1YUpDTWl6bFpzdGQwZ1FRMXl2ZTNQRDRaVHZPdzlMMm9Na0ZDQlFvQzBUalU5b0tPTHNpdlAzbTZOWjROLVpiaWFaNTIxbWU1ZjBWV1loRkN3RENxajRyUDZ5WmloOXVPTW5rWnNhZ3BtS0RlaVV6d1RpaENKdlRkZnBfbG1GQ3cyc0Jyd0lIVWJfdkxWY1RWNDd4NVNwSnhuS2dpWHpZUG8weElnYnY1bmZGWTJvM1NBWkZpSlNlNEJQbmFsX2FQLUFnNDdWM2h5NmNzT0xCM3l0VlNCRDdlNjFpU1VGWVhBUmZJVEVXa0VRaHBIWWJyRTlvemdldzdOLU5HaXdtWndOUy04SUFSbmRFS0tXSXRXb01fMllXVmYxS1ZoME8xQ2wwR0ZDV2NCNzFDLWxMazVJbkpKUm5Wd2dPQ1M2YUFKaEM2T2pIVVYydTR3TTdndFI1c1Y2Snk1NUxQcjFUbVpZQXAyVFNSMG0zUWMyN0ZKRnhxaFU2R20tZGtVNXZKbGtnSjUwY2xTUVVGcVl4Z0pDX1hSdWVpOXNzdkNmbnZVOW1ZSEFQZTU2Q2dXNWFiVGhSOEJCcTc2aTlxUjBlRVV4eFVWUUtCemFhVlB3TmVqaFRVYnpWcHZnNGlqSFRocFBlRzdDZ3hwQ00zT0pCaHFnS2k3RzVTeHFHYjdNVEhoclp2Q3I2WHZtZGdFc3NxWW9RdUQyYUQ4TlhjdVU0Mm1NVGwyZS1sY2pwU1E5R29hdlRHSjFCeFp2YWlYZzRNS1FGUjBjRDQzYkxsaXo2Y2NCeEEwZnJTU2dqbUhRNERxdHhjYkFiNFlPTDFlYkFQNFNSQnJwa3hGQW5fc1l6ci1aR0F0R0l3R1JfUHRRbjVLQ05yaXBueDRITVBmS2UtTHg4MzBIWFNxVGV5c0hRbGtuRlRSeFdwLXdNcUxPMlFhTHJnMlUzdnBDekloRmh4dG1tWnpPSE8zZmY2YTAySk9BaDVDek9GcG9oTDFXakl5a1RMd0dNMDZMQ25uNmhGeDVOZEhmVTlqaTdKNGZuT2RkcVh2ZnZ4TDhSN0wtM1d6SThIUVI4TkRHRzl6ZGtHZDUyQVlkNTBqUTZPN29qNUdkZldGMDdQTVY3WWFETjhGc1YwT19wZDM5bFpiUnM0SlV1Y0xWMzBXNGpqVGdselZGeXBaZEFxQXU0d2pWTVd5T1I0X1RSMnh6YW0wemx0ZXc1bm01TUk4NTlZYVhCVE95bkV5T18yRndDR2hzdmxQR2t5SHZuc050NFVya3pjRGswX0JaYUlYYWFNbUhxMUJQUWdiR0d6bUxNV0FXcFY0OUszdnBkN250WHFBZEVyN25VUnVpS2RSckVTYnpEUnAxclh2NExOMUdGNXRnRUFCZFhwYTVQVG9nVDM3cHUwb1BNNW5FZXFDeklRbmtjemMzUVk5SEZwY1J6bWFmbV9fSngxRFd0ak5qR1J0cVM4aHVUcVNKOG5ORl90ZXZsV2dwOU5uZU9KSUZwZkVMMnhYMTc2dnkyQ1FONTBFRzZZWmM4dXZreHFNUmk3OFNjdENEeXQ0WS5Sc3FFM1dad19XclIxRmtQc1RtWW1B"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultsetcertificatecontacts.json",
    "content": "{\n\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/certificates/contacts\",\n\t\"contacts\": [{\n\t\t\"email\": \"foo@bar.com\",\n\t\t\"name\": \"Foo bar\",\n\t\t\"phone\": \"867-5309\"\n\t}]\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultsetcertificatecontactsrequestbody.json",
    "content": "{\n\t\"contacts\": [{\n\t\t\"email\": \"foo@bar.com\",\n\t\t\"name\": \"Foo bar\",\n\t\t\"phone\": \"867-5309\"\n\t}]\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultsetcertificateissuer.json",
    "content": "{\n\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/certificates/issuers/globalsign01\",\n\t\"provider\": \"GlobalSign\",\n\t\"credentials\": {\n\t\t\"account_id\": \"imauser\"\n\t},\n\t\"org_details\": {\n\t\t\"zip\": 0,\n\t\t\"admin_details\": [{\n\t\t\t\"first_name\": \"Admin\",\n\t\t\t\"last_name\": \"Guy\",\n\t\t\t\"email\": \"adminguy@certsforme.com\",\n\t\t\t\"phone\": \"867-5309\"\n\t\t}]\n\t},\n\t\"attributes\": {\n\t\t\"enabled\": true,\n\t\t\"created\": 1509346474,\n\t\t\"updated\": 1509346474\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultsetcertificateissuerrequestbody.json",
    "content": "{\n\t\"credentials\": {\n\t\t\"account_id\": \"imauser\",\n\t\t\"pwd\": \"This1sMyPa55wurD!\"\n\t},\n\t\"org_details\": {\n\t\t\"admin_details\": [{\n\t\t\t\"email\": \"adminguy@certsforme.com\",\n\t\t\t\"first_name\": \"Admin\",\n\t\t\t\"last_name\": \"Guy\",\n\t\t\t\"phone\": \"867-5309\"\n\t\t}]\n\t},\n\t\"provider\": \"GlobalSign\"\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultsetsecret.json",
    "content": "{\n\t\"value\": \"-----BEGIN RSA PRIVATE KEY-----\\\\nMIIEogIBAAKCAQEAvZiOgV6b4EmGiasBskXYnTaRyWzBHBGnWB11BzFN3FGigfWx\\\\nVvjI7Ox1SHTx+vGsnjbqQPvIP4JnPEsNcWLyHa6tNAcnj/M7BuyIwdD5+Hvs6kOe\\\\nPuSOJUf8dRjPMUpr6rcUcBmmOwTnKOH4rdpb6jXNnuCIHP+lgXCeRWveZ62TjEB+\\\\n9aB8W8UHH854FGebiUd/aY0tpCFC7wkWz3KbgmjmY2vSe2U98Yj4+l/IWydIZ7ON\\\\nLicteEEIGbNM0o2QSYhQBCJSw5RixDpPlrUUB094qgqUOyW0k8PvjibGxxTh0LYy\\\\nWqWydPF0XaqFRQ6v36UvEiVGwzVsLwsJL/QVtQIDAQABAoIBAEJ6790lE3s9zNMR\\\\nB3M/UoktzUjXvY7eEdOv4I05GJgcd+MiB6D7c1jAQQ+7Ee5wN5rynolSwBCk5RYb\\\\nKweLLmKCEXGg4Jp1K0luPzXW1Q/wRE6Qjzh2Y/FmoHtey6f49IZE1AHKvKMNQRDw\\\\ny4YKfxhM7WC8Un34lkwg9R5aiI3JkOG9/yNkOGrJfQnGUKt+AOAdu6fNYsRLWAPo\\\\nG3vWSNIgwaG5WL5cKd1gacbGBlc6tLB7+LrZuNrqln5ibTtN6QJvRF9KfOrMSvxy\\\\nL/xiHRpyzec/jrxJxAIIwFHiw2jbLdxNqDaVPFA6X1Cks4fvY40KymOS8Ecmkgx4\\\\nC6/ZqLECgYEA38rL8zmbJRRWgrxSoROucaN/9DyvE8Hd97s1zf3I0LIF+GI3JdcN\\\\nDV5O5VDIgQ7QZ55lOaTqJ0f2fOQZF1UbTU1gBUHVF6j1nv6Xic3OV+ZmhTMbt0Op\\\\nWxPaKup6dkNEAe/Xg0p308r8xw/psh4/gjL1ICHwycjUlz9FQz8FLGsCgYEA2OHc\\\\n/F4vAdK04U4w6AyivuJdIsDAks1ikl+3TqgzyesPg+DpKVNSy6DhraDFKdRqWhbK\\\\nDqigTud8TVk9kmyF3WIb1BDf4IrxlTK08s6Jf25QA/lBlwIst3rejqWwRBY2fJp4\\\\nO8hU31xNLd8nZq8tKYaP+yvyI6fSC+9ZIgyATl8CgYBtTlYzZG2cvMRMcsNBHaXU\\\\np3E1z/YLhmNuPqhXBp/xHyK/YOliuBkN8IREiSKFtsCf+8OhViVwLjv8YETJGq6N\\\\nIT/HEZKNTd86W0uU6UrhsA1e/cmJx6iObbHfyEssPEqZT5ZJ8DN65Oh2KhWRBCks\\\\n5MrJeQps5ITBowunfr5+JQKBgBln09goPD9tbEzcOPRlzoanw5s3kxdfQcW9up5X\\\\nK8HibC3ZodZ6cT9zOBx7sbzlqhOlicPP0v+LNE9nPcQyPDgjrvjXhTIrdIMyrmmm\\\\n8gpgZLUidKF42r4fgYSaOhyvsXBFNAJkxDRp/ox6EIaBzLuJjMIycqnklcFaJ0nK\\\\nxxjnAoGAU/3jRok74Yn0MY183UCXICf/WxVYzwEi3cyRWVh6gAo2ExNye97rau/B\\\\nY2woAcVxEN9h1HNirq8Z2AwrZKd/BcBnvulZqECeH5zBQ0W56ADX72r+lzOAxTJa\\\\nU1AIlNCIkfsQ5CpIoYsVoNEM8P+GyS8B9kaEmk/FVKldRTKJqkI=\\\\n-----END RSA PRIVATE KEY-----\\\\n\",\n\t\"contentType\": \"testSecretKey\",\n\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/secrets/mySecret/b936ececbc674f3bb1367ae50d28ada0\",\n\t\"attributes\": {\n\t\t\"enabled\": true,\n\t\t\"created\": 1509335932,\n\t\t\"updated\": 1509335932,\n\t\t\"recoveryLevel\": \"Purgeable\"\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultsetsecretrequestbody.json",
    "content": "{\n\t\"attributes\": {\n\t\t\"enabled\": true\n\t},\n\t\"contentType\": \"testSecretKey\",\n\t\"value\": \"-----BEGIN RSA PRIVATE KEY-----\\nMIIEogIBAAKCAQEAvZiOgV6b4EmGiasBskXYnTaRyWzBHBGnWB11BzFN3FGigfWx\\nVvjI7Ox1SHTx+vGsnjbqQPvIP4JnPEsNcWLyHa6tNAcnj/M7BuyIwdD5+Hvs6kOe\\nPuSOJUf8dRjPMUpr6rcUcBmmOwTnKOH4rdpb6jXNnuCIHP+lgXCeRWveZ62TjEB+\\n9aB8W8UHH854FGebiUd/aY0tpCFC7wkWz3KbgmjmY2vSe2U98Yj4+l/IWydIZ7ON\\nLicteEEIGbNM0o2QSYhQBCJSw5RixDpPlrUUB094qgqUOyW0k8PvjibGxxTh0LYy\\nWqWydPF0XaqFRQ6v36UvEiVGwzVsLwsJL/QVtQIDAQABAoIBAEJ6790lE3s9zNMR\\nB3M/UoktzUjXvY7eEdOv4I05GJgcd+MiB6D7c1jAQQ+7Ee5wN5rynolSwBCk5RYb\\nKweLLmKCEXGg4Jp1K0luPzXW1Q/wRE6Qjzh2Y/FmoHtey6f49IZE1AHKvKMNQRDw\\ny4YKfxhM7WC8Un34lkwg9R5aiI3JkOG9/yNkOGrJfQnGUKt+AOAdu6fNYsRLWAPo\\nG3vWSNIgwaG5WL5cKd1gacbGBlc6tLB7+LrZuNrqln5ibTtN6QJvRF9KfOrMSvxy\\nL/xiHRpyzec/jrxJxAIIwFHiw2jbLdxNqDaVPFA6X1Cks4fvY40KymOS8Ecmkgx4\\nC6/ZqLECgYEA38rL8zmbJRRWgrxSoROucaN/9DyvE8Hd97s1zf3I0LIF+GI3JdcN\\nDV5O5VDIgQ7QZ55lOaTqJ0f2fOQZF1UbTU1gBUHVF6j1nv6Xic3OV+ZmhTMbt0Op\\nWxPaKup6dkNEAe/Xg0p308r8xw/psh4/gjL1ICHwycjUlz9FQz8FLGsCgYEA2OHc\\n/F4vAdK04U4w6AyivuJdIsDAks1ikl+3TqgzyesPg+DpKVNSy6DhraDFKdRqWhbK\\nDqigTud8TVk9kmyF3WIb1BDf4IrxlTK08s6Jf25QA/lBlwIst3rejqWwRBY2fJp4\\nO8hU31xNLd8nZq8tKYaP+yvyI6fSC+9ZIgyATl8CgYBtTlYzZG2cvMRMcsNBHaXU\\np3E1z/YLhmNuPqhXBp/xHyK/YOliuBkN8IREiSKFtsCf+8OhViVwLjv8YETJGq6N\\nIT/HEZKNTd86W0uU6UrhsA1e/cmJx6iObbHfyEssPEqZT5ZJ8DN65Oh2KhWRBCks\\n5MrJeQps5ITBowunfr5+JQKBgBln09goPD9tbEzcOPRlzoanw5s3kxdfQcW9up5X\\nK8HibC3ZodZ6cT9zOBx7sbzlqhOlicPP0v+LNE9nPcQyPDgjrvjXhTIrdIMyrmmm\\n8gpgZLUidKF42r4fgYSaOhyvsXBFNAJkxDRp/ox6EIaBzLuJjMIycqnklcFaJ0nK\\nxxjnAoGAU/3jRok74Yn0MY183UCXICf/WxVYzwEi3cyRWVh6gAo2ExNye97rau/B\\nY2woAcVxEN9h1HNirq8Z2AwrZKd/BcBnvulZqECeH5zBQ0W56ADX72r+lzOAxTJa\\nU1AIlNCIkfsQ5CpIoYsVoNEM8P+GyS8B9kaEmk/FVKldRTKJqkI\\u003d\\n-----END RSA PRIVATE KEY-----\"\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultupdatecertificate.json",
    "content": "{\n\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/certificates/myCertificate/b73ba4610dc24dca946f76933f6590dd\",\n\t\"kid\": \"https://kvvaultapilivetest.vault.azure.net/keys/myCertificate/b73ba4610dc24dca946f76933f6590dd\",\n\t\"sid\": \"https://kvvaultapilivetest.vault.azure.net/secrets/myCertificate/b73ba4610dc24dca946f76933f6590dd\",\n\t\"x5t\": \"K7HXO6YIK6xwCX8W1InUKsJV9Rk\",\n\t\"cer\": \"MIIDTDCCAjSgAwIBAgIQVA+XomvgS56ybBWv2MnacjANBgkqhkiG9w0BAQsFADAjMSEwHwYDVQQDExhteWNlcnRpZmljYXRlLmZvb2Jhci5jb20wHhcNMTcxMDMwMDY0NDI3WhcNMTgxMDMwMDY1NDI3WjAjMSEwHwYDVQQDExhteWNlcnRpZmljYXRlLmZvb2Jhci5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCusjC1A7rQEjW9SRL9XHRNDl0EuNYEV9AVQcAEmgpcJ6WgusdataeFrHKPmO8RUZgXk4sE14d3o9HjduYcqfOre+FBdQDWwoFHEAlq9Iz1r4woGk3f1oq9KepE12cRMTyTA214iluYNUx7XxSca3KFFswqonvcekbLJF2IPydNL0XrlIJFCUoAs3PRWLfPnYuijqRGhk8B9xGQMBtuDsnEi4wQRxusFHR1JxHSbY65xi1Hc9Ds9RAxdKwvBmYYC7V78q6qNM0LpenFGlZJMd/eRLVDguM1d17yyTX/lei/Oj8yVVDsva23ilUrv1mR549sv1lIqxNzdOGLsb6jykJ7AgMBAAGjfDB6MA4GA1UdDwEB/wQEAwIFoDAJBgNVHRMEAjAAMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAfBgNVHSMEGDAWgBRnlX51KtyJ/m/V8I/3il4cAW/HOzAdBgNVHQ4EFgQUZ5V+dSrcif5v1fCP94peHAFvxzswDQYJKoZIhvcNAQELBQADggEBAAbSFuMRMbXyH80iA/jU7vuUCYe0Ra/wTTB1qVHTBuqQ/W8RI01mdqI9+GAPOTyN94XPPYVpSz9ZQ3P0/dhgcsahW5bZQkC0CcUSE5R7JUOKI5Up6n8zZM/unHlC6ZcEpNA/scObPKhQXdZayxgf2/p30bii4CiyS7ADEH92xMnzo1Eu9Dckxh1MRDypfxMY9YIzggksiY78BxoNsRDyxNjeRHVUxAIJ3n9TUv+WG31r7rMOIs6ZPsWc96AzUHHAZREVTEh2kiKKIenbMXn1tCpF6/GJKGfp7rt5ObUoQAlnn7kgAceteKZHEMgRZ4c4EQq+yqBw3hJrz4dOabJcmcU=\",\n\t\"attributes\": {\n\t\t\"enabled\": true,\n\t\t\"nbf\": 1509345867,\n\t\t\"exp\": 1540882467,\n\t\t\"created\": 1509346467,\n\t\t\"updated\": 1509346472,\n\t\t\"recoveryLevel\": \"Purgeable\"\n\t},\n\t\"tags\": {\n\t\t\"selfsigned\": \"true\"\n\t},\n\t\"policy\": {\n\t\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/certificates/myCertificate/policy\",\n\t\t\"key_props\": {\n\t\t\t\"exportable\": false,\n\t\t\t\"kty\": \"RSA\",\n\t\t\t\"key_size\": 2048,\n\t\t\t\"reuse_key\": false\n\t\t},\n\t\t\"secret_props\": {\n\t\t\t\"contentType\": \"application/x-pkcs12\"\n\t\t},\n\t\t\"x509_props\": {\n\t\t\t\"subject\": \"CN=mycertificate.foobar.com\",\n\t\t\t\"ekus\": [\"1.3.6.1.5.5.7.3.1\", \"1.3.6.1.5.5.7.3.2\"],\n\t\t\t\"key_usage\": [\"digitalSignature\", \"keyEncipherment\"],\n\t\t\t\"validity_months\": 12,\n\t\t\t\"basic_constraints\": {\n\t\t\t\t\"ca\": false\n\t\t\t}\n\t\t},\n\t\t\"lifetime_actions\": [{\n\t\t\t\"trigger\": {\n\t\t\t\t\"lifetime_percentage\": 80\n\t\t\t},\n\t\t\t\"action\": {\n\t\t\t\t\"action_type\": \"AutoRenew\"\n\t\t\t}\n\t\t}],\n\t\t\"issuer\": {\n\t\t\t\"name\": \"Self\"\n\t\t},\n\t\t\"attributes\": {\n\t\t\t\"enabled\": true,\n\t\t\t\"created\": 1509346452,\n\t\t\t\"updated\": 1509346472\n\t\t}\n\t},\n\t\"pending\": {\n\t\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/certificates/myCertificate/pending\"\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultupdatecertificateissuer.json",
    "content": "{\n\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/certificates/issuers/globalsign01\",\n\t\"provider\": \"GlobalSign\",\n\t\"credentials\": {\n\t\t\"account_id\": \"imauser\"\n\t},\n\t\"org_details\": {\n\t\t\"zip\": 0,\n\t\t\"admin_details\": [{\n\t\t\t\"first_name\": \"Admin\",\n\t\t\t\"last_name\": \"Guy\",\n\t\t\t\"email\": \"adminguy@certsforme.com\",\n\t\t\t\"phone\": \"867-5309\"\n\t\t}]\n\t},\n\t\"attributes\": {\n\t\t\"enabled\": true,\n\t\t\"created\": 1509346474,\n\t\t\"updated\": 1509346654\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultupdatecertificateissuerrequestbody.json",
    "content": "{\n\t\"credentials\": {\n\t\t\"account_id\": \"imauser\",\n\t\t\"pwd\": \"CanHa5P455wuRd!\"\n\t},\n\t\"org_details\": {\n\t\t\"admin_details\": [{\n\t\t\t\"email\": \"adminguy@certsforme.com\",\n\t\t\t\"first_name\": \"Admin\",\n\t\t\t\"last_name\": \"Guy\",\n\t\t\t\"phone\": \"867-5309\"\n\t\t}]\n\t},\n\t\"provider\": \"GlobalSign\"\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultupdatecertificateoperation.json",
    "content": "{\n\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/certificates/myTempCertificate/pending\",\n\t\"issuer\": {\n\t\t\"name\": \"Self\"\n\t},\n\t\"csr\": \"MIIEtzCCAp8CAQAwJzElMCMGA1UEAxMcbXl0ZW1wY2VydGlmaWNhdGUuZm9vYmFyLmNvbTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMmt2TbL1ndbSggTwx2l3k/ZUzt0IGO/FMB/oqpmc5izy2KGi0/uSoEdFA9cSqfctL3FGx2J1cFVTz287cvLB8HB3A4svAoPnKsZmKpXuYbF4fK2wQGXm/iNk+JVq1KL0lfoqW2g52lHDM85XURMn8YCkAGIKeTlOVyEn7EMBuBumcJbszj0g56Ij+VKmxoua/Ja4ONmIGsKdyZRBEuvFQ1GTnJUvCWHwyo1pT0M5EY/VL9ikc283DSvpQcfvNelQgQfWCpTRX1Q7nTUHk14DD4d/Y6OdbjcVuqE0Jdqdw6MXfU2zrkPo/nZBf5GHsUChiaxzVeEafPjWKvqVDzhEYXpmMB5SDAELaQtV6PoX+kxcjAO4K//BQtwneHHVF/Sh+7ke3nNUlSf4Mjn541wS7LdkBDOlTnKdYu+DhfbdkRD4E9LPiDduWDWHZs051uFBecR93JaZmX2b376RORQygDkBRga/MNENoEEnsz4zmoMYCGspZhRXEC9Uts1hzYEtwM1hyLqJlfadX/sct20N4JkhDkM8NG2V43R8jcnKFmzjfv6Yc1tuiQ1GQpYNFPJWh+fakAZkt7IwYsvy1CQg92Yvi3ne9zRTBn00enDpBTWaGCZ84gYYaT7Yfyo7/WRTjinYt6R0+u8l0AmZb0xkgxEACIQoyrg+oWQZI4YrneRAgMBAAGgSzBJBgkqhkiG9w0BCQ4xPDA6MA4GA1UdDwEB/wQEAwIFoDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwCQYDVR0TBAIwADANBgkqhkiG9w0BAQsFAAOCAgEAr8RMKLLpGG31Mq4Dor6Tf11AoiHCLH33MUqblF1VfDiw0++qBZ1dgm0D+uzQph/bZ6jKe/PUWpS1bErfaOt3iaVNOHom8jP/U3kZiYWvc/YHetU03prm1Qb+izNZA97NNeZRsuCXMAkNAHQnXa/rz/zG6BmGXFigh55wglX6aB8PnfKZb7N6RCct8BsKSV8uPpxXzRWPKrv7TA2RKfMifUD/Dzt7FSDuYJ8FGkvQNX012RXb2DqHp8tbZgUSj7iXdoZMZ1jfwlh6P61yhfItbF4SYvtBd9PTWIxP6SkCfDjJ7f0/ofwoV2DvAiwfH7URdQIMC+B8dPCqbjya3Ku+B2fWXXhdG7gJqa1zRY066QTIsHwfwd3WbeLQxCcBUEQUG0u23gj9fDX81fvKsgHtN9Nod5wXsdLtjjpHpJQJlDanII4H3fvDxAOlqSnxxEhjL9uA3YXUERMGGjExXA5kCOqKrdfGT5x4yosuNutylvF8YYn8r+mvMgegtVl8XmKnyP+uESSE2krVVmnSM2gveq7ILxBvanq70LmQVeYQB4AlLtUsxPUPIPiOryDI39KrlqWKdl3/oC7Gx+WbVzXxs37NEwt/tx8E+r1Nq/jRFxP0QlyyUdjpiPXjUpuCdn4y6erpCuahbMP+CZNCNgeEh1v2pNljuaGCIB+VA2Fz/oU=\",\n\t\"cancellation_requested\": true,\n\t\"status\": \"inProgress\",\n\t\"status_details\": \"Pending certificate created. Certificate request is in progress. This may take some time based on the issuer provider. Please check again later.\",\n\t\"request_id\": \"32051e4e4ac947c5b9ad1b6737bee7c0\"\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultupdatecertificateoperationrequestbody.json",
    "content": "{\n    \"cancellation_requested\": true\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultupdatecertificatepolicy.json",
    "content": "{\n\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/certificates/myCertificate/policy\",\n\t\"key_props\": {\n\t\t\"exportable\": false,\n\t\t\"kty\": \"RSA\",\n\t\t\"key_size\": 2048,\n\t\t\"reuse_key\": false\n\t},\n\t\"secret_props\": {\n\t\t\"contentType\": \"application/x-pkcs12\"\n\t},\n\t\"x509_props\": {\n\t\t\"subject\": \"CN=mycertificate.foobar.com\",\n\t\t\"ekus\": [\"1.3.6.1.5.5.7.3.1\", \"1.3.6.1.5.5.7.3.2\"],\n\t\t\"key_usage\": [\"digitalSignature\", \"keyEncipherment\"],\n\t\t\"validity_months\": 12,\n\t\t\"basic_constraints\": {\n\t\t\t\"ca\": false\n\t\t}\n\t},\n\t\"lifetime_actions\": [{\n\t\t\"trigger\": {\n\t\t\t\"lifetime_percentage\": 80\n\t\t},\n\t\t\"action\": {\n\t\t\t\"action_type\": \"AutoRenew\"\n\t\t}\n\t}],\n\t\"issuer\": {\n\t\t\"name\": \"Self\"\n\t},\n\t\"attributes\": {\n\t\t\"enabled\": true,\n\t\t\"created\": 1509346452,\n\t\t\"updated\": 1509346452\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultupdatecertificatepolicyrequestbody.json",
    "content": "{\n\t\"key_props\": {\n\t\t\"exportable\": true,\n\t\t\"key_size\": 3072,\n\t\t\"kty\": \"RSA\",\n\t\t\"reuse_key\": false\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultupdatecertificaterequestbody.json",
    "content": "{\"policy\":{\"id\":\"myCertificate\",\"issuer\":{\"name\":\"Self\"},\"key_props\":{\"exportable\":false,\"key_size\":2048,\"kty\":\"RSA\",\"reuse_key\":false},\"lifetime_actions\":[],\"x509_props\":{\"ekus\":[],\"key_usage\":[],\"subject\":\"CN=mycertificate.foobar.com\",\"validity_months\":12}},\"tags\":{\"selfsigned\":\"true\"}}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultupdatekey.json",
    "content": "{\n\t\"key\": {\n\t\t\"kid\": \"https://kvvaultapilivetest.vault.azure.net/keys/myKey/bd6566ec707e4ad89f4ab9577d9d0bef\",\n\t\t\"kty\": \"RSA\",\n\t\t\"key_ops\": [\"encrypt\", \"decrypt\", \"sign\", \"verify\", \"wrapKey\", \"unwrapKey\"],\n\t\t\"n\": \"2ZWsir4hwVxFTQXfWN7Vy1zA33jg1kxUMHmkmEFtVjGDByzmMfEXpnPziNCtYppBtpNT4AJEVQ60aIgSLNrUYBMoeiI2HCf2NM0NTdwYp7wq5tImtbGDASdDXQ1v3Bv3hXGh3CVmN2VLRf0OmoXnZUG_2UZZ05iPXOY6lNFfq8L81v0ZCMiXwFvNVhZ_fzppzhnwuHQf-X6Lnvrd1ocFqF8IFjV3663eumAfZmBLPP6tmiAZYW3G68_G0I2CHLtTPFX05aN51Jn42RITgcs63HFMT_iVW5556YR0BwtqkCXIUgTD714Fipz7EKGqhHsqND7YUSKpiRVQhfoZEckAkQ\",\n\t\t\"e\": \"AQAB\"\n\t},\n\t\"attributes\": {\n\t\t\"enabled\": true,\n\t\t\"created\": 1509335902,\n\t\t\"updated\": 1509335923,\n\t\t\"recoveryLevel\": \"Purgeable\"\n\t},\n\t\"tags\": {\n\t\t\"purpose\": \"testing\"\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultupdatekeyrequestbody.json",
    "content": "{\n  \"tags\": {\n    \"purpose\": \"testing\"\n  }\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultupdatekeywithversion.json",
    "content": "{\n\t\"key\": {\n\t\t\"kid\": \"https://kvvaultapilivetest.vault.azure.net/keys/myKey/bd6566ec707e4ad89f4ab9577d9d0bef\",\n\t\t\"kty\": \"RSA\",\n\t\t\"key_ops\": [\"encrypt\", \"decrypt\", \"sign\", \"verify\", \"wrapKey\", \"unwrapKey\"],\n\t\t\"n\": \"2ZWsir4hwVxFTQXfWN7Vy1zA33jg1kxUMHmkmEFtVjGDByzmMfEXpnPziNCtYppBtpNT4AJEVQ60aIgSLNrUYBMoeiI2HCf2NM0NTdwYp7wq5tImtbGDASdDXQ1v3Bv3hXGh3CVmN2VLRf0OmoXnZUG_2UZZ05iPXOY6lNFfq8L81v0ZCMiXwFvNVhZ_fzppzhnwuHQf-X6Lnvrd1ocFqF8IFjV3663eumAfZmBLPP6tmiAZYW3G68_G0I2CHLtTPFX05aN51Jn42RITgcs63HFMT_iVW5556YR0BwtqkCXIUgTD714Fipz7EKGqhHsqND7YUSKpiRVQhfoZEckAkQ\",\n\t\t\"e\": \"AQAB\"\n\t},\n\t\"attributes\": {\n\t\t\"enabled\": true,\n\t\t\"created\": 1509335902,\n\t\t\"updated\": 1509335927,\n\t\t\"recoveryLevel\": \"Purgeable\"\n\t},\n\t\"tags\": {\n\t\t\"purpose\": \"testing again\"\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultupdatesecret.json",
    "content": "{\n\t\"contentType\": \"testSecretKey\",\n\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/secrets/mySecret/b936ececbc674f3bb1367ae50d28ada0\",\n\t\"attributes\": {\n\t\t\"enabled\": true,\n\t\t\"created\": 1509335932,\n\t\t\"updated\": 1509335934,\n\t\t\"recoveryLevel\": \"Purgeable\"\n\t},\n\t\"tags\": {\n\t\t\"purpose\": \"testing\"\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultupdatesecretrequestbody.json",
    "content": "{\n\t\"tags\": {\n\t\t\"purpose\": \"testing\"\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultupdatesecretwithversion.json",
    "content": "{\n\t\"contentType\": \"testSecretKey\",\n\t\"id\": \"https://kvvaultapilivetest.vault.azure.net/secrets/mySecret/b936ececbc674f3bb1367ae50d28ada0\",\n\t\"attributes\": {\n\t\t\"enabled\": true,\n\t\t\"created\": 1509335932,\n\t\t\"updated\": 1509335946,\n\t\t\"recoveryLevel\": \"Purgeable\"\n\t},\n\t\"tags\": {\n\t\t\"purpose\": \"testing again\"\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vaultupdatesecretwithversionrequestbody.json",
    "content": "{\n\t\"tags\": {\n\t\t\"purpose\": \"testing again\"\n\t}\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/versions.json",
    "content": "[\n  {\n    \"location\": \"eastus\",\n    \"name\": \"2.0.20151120\",\n    \"id\": \"/Subscriptions/c36d97d3-3fea-4561-aa2d-e61168908c5b/Providers/Microsoft.Compute/Locations/eastus/Publishers/MicrosoftWindowsServer/ArtifactTypes/VMImage/Offers/WindowsServer/Skus/2008-R2-SP1/Versions/2.0.20151120\"\n  },\n  {\n    \"location\": \"eastus\",\n    \"name\": \"2.0.20151214\",\n    \"id\": \"/Subscriptions/c36d97d3-3fea-4561-aa2d-e61168908c5b/Providers/Microsoft.Compute/Locations/eastus/Publishers/MicrosoftWindowsServer/ArtifactTypes/VMImage/Offers/WindowsServer/Skus/2008-R2-SP1/Versions/2.0.20151214\"\n  }\n]"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/virtualmachine.json",
    "content": "{\n  \"properties\": {\n    \"vmId\": \"27ee085b-d707-xxxx-yyyy-2370e2eb1cc1\",\n    \"licenseType\": \"Windows_Server\",    \n    \"availabilitySet\":{    \n      \"id\":\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/availabilitySets/myAVSet\"\n    },\n    \"hardwareProfile\": {\n      \"vmSize\": \"Standard_D1\"\n    },\n    \"storageProfile\": {\n      \"imageReference\": {\n        \"publisher\": \"publisher\",\n        \"offer\": \"OFFER\",\n        \"sku\": \"sku\",\n        \"version\": \"ver\",\n        \"id\": \"/subscriptions/SUBSCRIPTIONID/providers/Microsoft.Compute/locations/westus/publishers/MicrosoftWindowsServerEssentials/artifactype/vmimage/offers/OFFER/skus/OFFER/versions/latest\"\n      },\n      \"osDisk\": {\n        \"osType\": \"Windows\",\n        \"name\": \"windowsmachine\",\n        \"createOption\": \"FromImage\",\n        \"managedDisk\": {\n          \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/osDisk\",\n          \"storageAccountType\": \"Standard_LRS\"\n        },\n        \"caching\": \"ReadWrite\"\n      },\n      \"dataDisks\":[\n        {\n          \"name\":\"mydatadisk1\",\n          \"diskSizeGB\":\"1\",\n          \"lun\": 0,\n          \"createOption\":\"Empty\",\n          \"managedDisk\": {\n            \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/osDisk\",\n            \"storageAccountType\": \"Standard_LRS\"\n          },\n          \"caching\": \"ReadWrite\"\n        }\n      ]\n    },\n    \"osProfile\": {\n      \"computerName\": \"windowsmachine\",\n      \"adminUsername\": \"azureuser\",\n      \"adminPassword\":\"password\",\n      \"customData\":\"\",\n      \"windowsConfiguration\": {\n        \"provisionVMAgent\": false,\n        \"enableAutomaticUpdates\": true,\n        \"winRM\": {\n           \"listeners\":[{\n             \"protocol\": \"https\",\n             \"certificateUrl\": \"url-to-certificate\"\n           }]\n        },\n        \"additionalUnattendContent\":[\n          {\n            \"passName\":\"oobesystem\",    \n            \"componentName\":\"Microsoft-Windows-Shell-Setup\",\n            \"settingName\":\"FirstLogonCommands\",\n            \"content\":\"<XML unattend content>\"\n          }\n        ]\n      },\n      \"secrets\":[\n        {     \n          \"sourceVault\": {     \n             \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myresourcegroup1/providers/Microsoft.KeyVault/vaults/myvault1\"     \n           },     \n           \"vaultCertificates\": [\n             {     \n               \"certificateUrl\": \"https://myvault1.vault.azure.net/secrets/SECRETNAME/SECRETVERSION\",     \n               \"certificateStore\": \"CERTIFICATESTORENAME\"     \n             }\n           ]     \n         }\n       ]\n    },\n    \"networkProfile\": {\n      \"networkInterfaces\":[\n        {\n          \"id\":\"/subscriptions/SUBSCRIPTIONID/resourceGroups/groupname/providers/Microsoft.Network/networkInterfaces/windowsmachine167\"\n        }\n      ]\n    },\n    \"diagnosticsProfile\": {\n      \"bootDiagnostics\": {\n        \"enabled\": true,\n        \"storageUri\": \"https://groupname2760.blob.core.windows.net/\"\n      }\n    },\n    \"provisioningState\": \"Creating\"\n  },\n  \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/groupname/providers/Microsoft.Compute/virtualMachines/windowsmachine\",\n  \"name\": \"windowsmachine\",\n  \"type\": \"Microsoft.Compute/virtualMachines\",\n  \"location\": \"westus\",\n  \"tags\": {\n    \"foo\": \"bar\"\n  },\n  \"plan\": {\n    \"name\": \"deadline-slave-7-2\",\n    \"publisher\": \"thinkboxsoftware\",\n    \"product\": \"deadline7-2\"\n  }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/virtualmachineInstance.json",
    "content": "{\n  \"vmAgent\": {\n    \"vmAgentVersion\": \"2.7.1198.766\",\n    \"statuses\": [\n      {\n        \"code\": \"ProvisioningState/succeeded\",\n        \"level\": \"Info\",\n        \"displayStatus\": \"Ready\",\n        \"message\": \"GuestAgent is running and accepting new configurations.\",\n        \"time\": \"2016-05-04T08:42:15+00:00\"\n      }\n    ]\n  },\n  \"disks\": [\n    {\n      \"name\": \"windowsmachine\",\n      \"statuses\": [\n        {\n          \"code\": \"ProvisioningState/succeeded\",\n          \"level\": \"Info\",\n          \"displayStatus\": \"Provisioning succeeded\",\n          \"time\": \"2016-05-04T08:31:45.2525129+00:00\"\n        }\n      ]\n    }\n  ],\n  \"statuses\": [\n    {\n      \"code\": \"ProvisioningState/succeeded\",\n      \"level\": \"Info\",\n      \"displayStatus\": \"Provisioning succeeded\",\n      \"time\": \"2016-05-04T08:38:52.4310433+00:00\"\n    },\n    {\n      \"code\": \"PowerState/running\",\n      \"level\": \"Info\",\n      \"displayStatus\": \"VM running\"\n    }\n  ]\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/virtualmachineavailablesizes.json",
    "content": "{\n  \"value\": [\n    {\n      \"name\": \"Standard_A0\",\n      \"numberOfCores\": 1,\n      \"osDiskSizeInMB\": 1047552,\n      \"resourceDiskSizeInMB\": 20480,\n      \"memoryInMB\": 768,\n      \"maxDataDiskCount\": 1\n    },\n    {\n      \"name\": \"Standard_A1\",\n      \"numberOfCores\": 1,\n      \"osDiskSizeInMB\": 1047552,\n      \"resourceDiskSizeInMB\": 71680,\n      \"memoryInMB\": 1792,\n      \"maxDataDiskCount\": 2\n    }\n  ]\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/virtualmachineimagecreate.json",
    "content": "{\n  \"type\": \"Microsoft.Compute/images\",\n  \"location\": \"canadaeast\",\n  \"id\": \"/subscriptions/bd81406c-6028-4037-9f03-9a3af4ff725d/resourceGroups/jcloudstest-canadaeast/providers/Microsoft.Compute/images/testVirtualMachineImage\",\n  \"name\": \"testVirtualMachineImage\",\n  \"properties\": {\n    \"sourceVirtualMachine\": {\n      \"id\": \"/subscriptions/bd81406c-6028-4037-9f03-9a3af4ff725d/resourceGroups/jcloudstest-canadaeast/providers/Microsoft.Compute/virtualMachines/vm2image\"\n    },\n    \"storageProfile\": {\n      \"osDisk\": {\n        \"osType\": \"Linux\",\n        \"osState\": \"Generalized\",\n        \"blobUri\": \"https://jcloudstestcanadaeast982.blob.core.windows.net/vhds/vm2image20170315140332.vhd\",\n        \"caching\": \"ReadWrite\"\n      },\n      \"dataDisks\": []\n    },\n    \"provisioningState\": \"Succeeded\"\n  }\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/virtualmachineimageget.json",
    "content": "{\n  \"type\": \"Microsoft.Compute/images\",\n  \"location\": \"canadaeast\",\n  \"id\": \"/subscriptions/bd81406c-6028-4037-9f03-9a3af4ff725d/resourceGroups/jcloudstest-canadaeast/providers/Microsoft.Compute/images/testVirtualMachineImage\",\n  \"name\": \"testVirtualMachineImage\",\n  \"properties\": {\n    \"sourceVirtualMachine\": {\n      \"id\": \"/subscriptions/bd81406c-6028-4037-9f03-9a3af4ff725d/resourceGroups/jcloudstest-canadaeast/providers/Microsoft.Compute/virtualMachines/vm2image\"\n    },\n    \"storageProfile\": {\n      \"osDisk\": {\n        \"osType\": \"Linux\",\n        \"osState\": \"Generalized\",\n        \"blobUri\": \"https://jcloudstestcanadaeast982.blob.core.windows.net/vhds/vm2image20170315140332.vhd\",\n        \"caching\": \"ReadWrite\"\n      },\n      \"dataDisks\": []\n    },\n    \"provisioningState\": \"Succeeded\"\n  }\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/virtualmachineimagelist.json",
    "content": "{\n  \"value\": [\n    {\n      \"type\": \"Microsoft.Compute/images\",\n      \"location\": \"canadaeast\",\n      \"id\": \"/subscriptions/bd81406c-6028-4037-9f03-9a3af4ff725d/resourceGroups/jcloudstest-canadaeast/providers/Microsoft.Compute/images/imageFromRest\",\n      \"name\": \"testVirtualMachineImage\",\n      \"properties\": {\n        \"sourceVirtualMachine\": {\n          \"id\": \"/subscriptions/bd81406c-6028-4037-9f03-9a3af4ff725d/resourceGroups/jcloudstest-canadaeast/providers/Microsoft.Compute/virtualMachines/vm2image\"\n        },\n        \"storageProfile\": {\n          \"osDisk\": {\n            \"osType\": \"Linux\",\n            \"osState\": \"Generalized\",\n            \"blobUri\": \"https://jcloudstestcanadaeast982.blob.core.windows.net/vhds/vm2image20170315140332.vhd\",\n            \"caching\": \"ReadWrite\"\n          },\n          \"dataDisks\": []\n        },\n        \"provisioningState\": \"Succeeded\"\n      }\n    }\n  ]\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/virtualmachinescalesetget.json",
    "content": "{\n  \"sku\": {\n    \"name\": \"Standard_A1\",\n    \"tier\": \"Standard\",\n    \"capacity\": 4\n  },\n  \"properties\": {\n    \"singlePlacementGroup\": true,\n    \"upgradePolicy\": {\n      \"mode\": \"Manual\"\n    },\n    \"virtualMachineProfile\": {\n      \"osProfile\": {\n        \"computerNamePrefix\": \"vmmsprefix\",\n        \"adminUsername\": \"jclouds\",\n        \"linuxConfiguration\": {\n          \"disablePasswordAuthentication\": false\n        },\n        \"secrets\": []\n      },\n      \"storageProfile\": {\n        \"osDisk\": {\n          \"createOption\": \"FromImage\",\n          \"caching\": \"None\",\n          \"managedDisk\": {\n            \"storageAccountType\": \"Standard_LRS\"\n          }\n        },\n        \"imageReference\": {\n          \"publisher\": \"Canonical\",\n          \"offer\": \"UbuntuServer\",\n          \"sku\": \"16.04-LTS\",\n          \"version\": \"latest\"\n        }\n      },\n      \"networkProfile\": {\"networkInterfaceConfigurations\":[{\"name\":\"nicconfig1\",\"properties\":{\"primary\":true,\"enableAcceleratedNetworking\":false,\"dnsSettings\":{\"dnsServers\":[\"8.8.8.8\"]},\"ipConfigurations\":[{\"name\":\"ipconfig1\",\"properties\":{\"publicIPAddressConfiguration\":{\"name\":\"pub1\",\"properties\":{\"idleTimeoutInMinutes\":15}},\"subnet\":{\"id\":\"/subscriptions/xxxxx-xxxx-xxxx-xxxx-xxxxxx/resourceGroups/jcloud-eastus/providers/Microsoft.Network/virtualNetworks/jclouds-eastus-virtualNetworkName/subnets/jclouds-eastus-subnet\"},\"privateIPAddressVersion\":\"IPv4\"}}]}}]},\n      \"extensionProfile\": {\n        \"extensions\": [\n          {\n            \"properties\": {\n              \"publisher\": \"Microsoft.compute\",\n              \"type\": \"CustomScriptExtension\",\n              \"typeHandlerVersion\": \"1.1\",\n              \"autoUpgradeMinorVersion\": false,\n              \"settings\": {\"fileUris\":[\"https://mystorage1.blob.core.windows.net/winvmextekfacnt/SampleCmd_1.cmd\"],\"commandToExecute\":\"SampleCmd_1.cmd\"}\n            },\n            \"name\": \"extensionName\"\n          }\n        ]\n      }\n    },\n    \"provisioningState\": \"Creating\",\n    \"overprovision\": true,\n    \"uniqueId\": \"xxxxx-xxxx-xxxx-xxxx-xxxxxx\"\n  },\n  \"type\": \"Microsoft.Compute/virtualMachineScaleSets\",\n  \"location\": \"eastus\",\n  \"tags\": {\n    \"test\": \"test\"\n  },\n  \"id\": \"/subscriptions/xxxxx-xxxx-xxxx-xxxx-xxxxxx/resourceGroups/jcloud-eastus/providers/Microsoft.Compute/virtualMachineScaleSets/jclouds-vmssname\",\n  \"name\": \"jclouds-vmssname\"\n}\n\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/virtualmachinescalesetgetwhen404.json",
    "content": "{\n  \"error\": {\n    \"code\": \"ResourceNotFound\",\n    \"message\": \"The Resource 'Microsoft.Compute/virtualMachineScaleSets/jclouds-vmssname1' under resource group 'jcloud-eastus' was not found.\"\n  }\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/virtualmachinescalesetlist.json",
    "content": "{\n  \"value\": [{\n    \"sku\": {\n      \"name\": \"Standard_A1\",\n      \"tier\": \"Standard\",\n      \"capacity\": 4\n    },\n    \"properties\": {\n      \"singlePlacementGroup\": true,\n      \"upgradePolicy\": {\n        \"mode\": \"Manual\",\n        \"automaticOSUpgrade\": false\n      },\n      \"virtualMachineProfile\": {\n        \"osProfile\": {\n          \"computerNamePrefix\": \"vmmsprefix\",\n          \"adminUsername\": \"jclouds\",\n          \"linuxConfiguration\": {\n            \"disablePasswordAuthentication\": false\n          },\n          \"secrets\": []\n        },\n        \"storageProfile\": {\n          \"osDisk\": {\n            \"createOption\": \"FromImage\",\n            \"caching\": \"None\",\n            \"managedDisk\": {\n              \"storageAccountType\": \"Standard_LRS\"\n            }\n          },\n          \"imageReference\": {\n            \"publisher\": \"Canonical\",\n            \"offer\": \"UbuntuServer\",\n            \"sku\": \"16.04-LTS\",\n            \"version\": \"latest\"\n          }\n        },\n        \"networkProfile\": {\n          \"networkInterfaceConfigurations\": [{\n            \"name\": \"nicconfig1\",\n            \"properties\": {\n              \"primary\": true,\n              \"enableAcceleratedNetworking\": false,\n              \"dnsSettings\": {\n                \"dnsServers\": [\"8.8.8.8\"]\n              },\n              \"ipConfigurations\": [{\n                \"name\": \"ipconfig1\",\n                \"properties\": {\n                  \"publicIPAddressConfiguration\": {\n                    \"name\": \"pub1\",\n                    \"properties\": {\n                      \"idleTimeoutInMinutes\": 15\n                    }\n                  },\n                  \"subnet\": {\n                    \"id\": \"/subscriptions/xxxxx-xxxx-xxxx-xxxx-xxxxxx/resourceGroups/jcloud-eastus/providers/Microsoft.Network/virtualNetworks/jclouds-eastus-virtualNetworkName/subnets/jclouds-eastus-subnet\"\n                  },\n                  \"privateIPAddressVersion\": \"IPv4\"\n                }\n              }]\n            }\n          }]\n        },\n        \"extensionProfile\": {\n          \"extensions\": [{\n            \"properties\": {\n              \"publisher\": \"Microsoft.compute\",\n              \"type\": \"CustomScriptExtension\",\n              \"typeHandlerVersion\": \"1.1\",\n              \"autoUpgradeMinorVersion\": false,\n              \"settings\": {\n                \"fileUris\": [\"https://mystorage1.blob.core.windows.net/winvmextekfacnt/SampleCmd_1.cmd\"],\n                \"commandToExecute\": \"SampleCmd_1.cmd\"\n              }\n            },\n            \"name\": \"extensionName\"\n          }]\n        }\n      },\n      \"provisioningState\": \"Failed\",\n      \"overprovision\": true,\n      \"uniqueId\": \"xxxxx-xxxx-xxxx-xxxx-xxxxxx\"\n    },\n    \"type\": \"Microsoft.Compute/virtualMachineScaleSets\",\n    \"location\": \"eastus\",\n    \"tags\": {\n      \"test\": \"test\"\n    },\n    \"id\": \"/subscriptions/xxxxx-xxxx-xxxx-xxxx-xxxxxx/resourceGroups/jcloud-eastus/providers/Microsoft.Compute/virtualMachineScaleSets/jclouds-vmssname\",\n    \"name\": \"jclouds-vmssname\"\n  }]\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/virtualmachinescalesetlistwhen404.json",
    "content": "{\n  \"error\": {\n    \"code\": \"ResourceGroupNotFound\",\n    \"message\": \"Resource group 'jcloud-eastus1' could not be found.\"\n  }\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/virtualmachinescalesetresponsecreateorupdate.json",
    "content": "{\n  \"location\": \"eastus\",\n  \"sku\": {\n    \"name\": \"Standard_A1\",\n    \"tier\": \"Standard\",\n    \"capacity\": 10\n  },\n  \"properties\": {\n    \"singlePlacementGroup\": true,\n    \"overProvision\": true,\n    \"upgradePolicy\": {\n      \"mode\": \"Manual\"\n    },\n    \"virtualMachineProfile\": {\n      \"storageProfile\": {\n        \"imageReference\": {\n          \"publisher\": \"Canonical\",\n          \"offer\": \"UbuntuServer\",\n          \"sku\": \"16.04-LTS\",\n          \"version\": \"latest\"\n        },\n        \"osDisk\": {\n          \"osType\": \"Windows\",\n          \"createOption\": \"FromImage\",\n          \"managedDisk\": {\n            \"storageAccountType\": \"Standard_LRS\"\n          }\n        },\n        \"dataDisks\": [{\n          \"diskSizeGB\": \"10\",\n          \"lun\": 1,\n          \"createOption\": \"Unrecognized\",\n          \"caching\": \"None\",\n          \"managedDisk\": {\n            \"storageAccountType\": \"Standard_LRS\"\n          }\n        }\n        ]\n      },\n      \"osProfile\": {\n        \"computerNamePrefix\": \"jclouds-vmssname\",\n        \"adminUsername\": \"jclouds\",\n        \"adminPassword\": \"jClouds1!\",\n        \"linuxConfiguration\": {\n          \"disablePasswordAuthentication\": \"False\"\n        },\n        \"secrets\": []\n      },\n      \"networkProfile\": {\n        \"networkInterfaceConfigurations\": [{\n          \"name\": \"nicconfig1\",\n          \"properties\": {\n            \"primary\": true,\n            \"enableAcceleratedNetworking\": false,\n            \"dnsSettings\": {\n              \"dnsServers\": [\"8.8.8.8\"]\n            },\n            \"ipConfigurations\": [{\n              \"name\": \"ipconfig1\",\n              \"properties\": {\n                \"publicIPAddressConfiguration\": {\n                  \"name\": \"pub1\",\n                  \"properties\": {\n                    \"idleTimeoutInMinutes\": 15\n                  }\n                },\n                \"subnet\": {\n                  \"name\": \"virtualNetworkName\",\n                  \"id\": \"/subscriptions/xxxxx-xxxx-xxxx-xxxx-xxxxxx/resourceGroups/jcloud-eastus/providers/Microsoft.Network/virtualNetworks/jclouds-eastus-virtualNetworkName/subnets/jclouds-eastus-subnet\",\n                  \"properties\": {}\n                },\n                \"privateIPAddressVersion\": \"IPv4\",\n                \"loadBalancerBackendAddressPools\": [],\n                \"loadBalancerInboundNatPools\": []\n              }\n            }\n            ]\n          }\n        }\n        ]\n      },\n      \"extensionProfile\": {\n        \"extensions\": [{\n          \"name\": \"extensionName\",\n          \"properties\": {\n            \"publisher\": \"Microsoft.compute\",\n            \"type\": \"CustomScriptExtension\",\n            \"typeHandlerVersion\": \"1.1\",\n            \"autoUpgradeMinorVersion\": false,\n            \"settings\": {\n              \"fileUris\": [\"https://mystorage1.blob.core.windows.net/winvmextekfacnt/SampleCmd_1.cmd\"],\n              \"commandToExecute\": \"SampleCmd_1.cmd\"\n            },\n            \"protectedSettings\": {\n              \"StorageAccountKey\": \"jclouds-accountkey\"\n            }\n          }\n        }\n        ]\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/virtualmachinesinlocation.json",
    "content": "{\n  \"value\": [\n    {\n      \"properties\": {\n        \"vmId\": \"27ee085b-d707-xxxx-yyyy-2370e2eb1cc1\",\n        \"licenseType\": \"Windows_Server\",    \n        \"availabilitySet\":{    \n          \"id\":\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/availabilitySets/myAVSet\"\n        },    \n        \"hardwareProfile\": {\n          \"vmSize\": \"Standard_D1\"\n        },\n        \"storageProfile\": {\n          \"imageReference\": {\n            \"publisher\": \"publisher\",\n            \"offer\": \"OFFER\",\n            \"sku\": \"sku\",\n            \"version\": \"ver\",\n            \"id\": \"/subscriptions/SUBSCRIPTIONID/providers/Microsoft.Compute/locations/westus/publishers/MicrosoftWindowsServerEssentials/artifactype/vmimage/offers/OFFER/skus/OFFER/versions/latest\"\n          },\n          \"osDisk\": {\n            \"osType\": \"Windows\",\n            \"name\": \"windowsmachine\",\n            \"createOption\": \"FromImage\",\n            \"managedDisk\": {\n              \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/osDisk\",\n              \"storageAccountType\": \"Standard_LRS\" \n            },\n            \"caching\": \"ReadWrite\"\n          },\n          \"dataDisks\":[\n            {\n              \"name\":\"mydatadisk1\",\n              \"diskSizeGB\":\"1\",\n              \"lun\": 0,\n              \"createOption\":\"Empty\",\n              \"caching\":\"ReadWrite\",\n              \"managedDisk\": {\n                \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/osDisk\",\n                \"storageAccountType\": \"Standard_LRS\"\n              }\n            }\n          ]    \n        },\n        \"osProfile\": {\n          \"computerName\": \"windowsmachine\",\n          \"adminUsername\": \"azureuser\",\n          \"adminPassword\":\"password\",\n          \"customData\":\"\",\n          \"windowsConfiguration\": {\n            \"provisionVMAgent\": false,\n            \"enableAutomaticUpdates\": true,\n            \"winRM\": {\n               \"listeners\":[{\n                 \"protocol\": \"https\",\n                 \"certificateUrl\": \"url-to-certificate\"\n               }]\n            },    \n            \"additionalUnattendContent\":[\n              {\n                \"passName\":\"oobesystem\",    \n                \"componentName\":\"Microsoft-Windows-Shell-Setup\",\n                \"settingName\":\"FirstLogonCommands\",\n                \"content\":\"<XML unattend content>\"\n              }\n            ]\n          },\n          \"secrets\":[\n            {\n              \"sourceVault\": {\n                 \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myresourcegroup1/providers/Microsoft.KeyVault/vaults/myvault1\"     \n               },\n               \"vaultCertificates\": [\n                 {\n                   \"certificateUrl\": \"https://myvault1.vault.azure.net/secrets/SECRETNAME/SECRETVERSION\",\n                   \"certificateStore\": \"CERTIFICATESTORENAME\"\n                 }\n               ]\n             }\n           ]\n        },\n        \"networkProfile\": {\n          \"networkInterfaces\": [\n            {\n              \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/groupname/providers/Microsoft.Network/networkInterfaces/windowsmachine167\"\n            }\n          ]\n        },\n        \"diagnosticsProfile\": {\n          \"bootDiagnostics\": {\n            \"enabled\": true,\n            \"storageUri\": \"https://groupname2760.blob.core.windows.net/\"\n          }\n        },\n        \"provisioningState\": \"Creating\"\n      },\n      \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/groupname/providers/Microsoft.Compute/virtualMachines/windowsmachine\",\n      \"name\": \"windowsmachine\",\n      \"type\": \"Microsoft.Compute/virtualMachines\",\n      \"location\": \"westus\"\n    },\n    {\n      \"properties\": {\n        \"vmId\": \"27ee085b-d707-xxxx-yyyy-2370e2eb1cc1\",\n        \"licenseType\": \"Windows_Server\",\n        \"availabilitySet\":{\n          \"id\":\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/availabilitySets/myAVSet\"\n        },\n        \"hardwareProfile\": {\n          \"vmSize\": \"Standard_D1\"\n        },\n        \"storageProfile\": {\n          \"imageReference\": {\n            \"publisher\": \"publisher\",\n            \"offer\": \"OFFER\",\n            \"sku\": \"sku\",\n            \"version\": \"ver\",\n            \"id\": \"/subscriptions/SUBSCRIPTIONID/providers/Microsoft.Compute/locations/westus/publishers/MicrosoftWindowsServerEssentials/artifactype/vmimage/offers/OFFER/skus/OFFER/versions/latest\"\n          },\n          \"osDisk\": {\n            \"osType\": \"Windows\",\n            \"name\": \"windowsmachine\",\n            \"createOption\": \"FromImage\",\n            \"managedDisk\": {\n              \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/osDisk\",\n              \"storageAccountType\": \"Standard_LRS\"\n            },\n            \"vhd\": {\n              \"uri\": \"https://groupname2760.blob.core.windows.net/vhds/windowsmachine201624102936.vhd\"\n            },\n            \"caching\": \"ReadWrite\"\n          },\n          \"dataDisks\":[\n            {\n              \"name\":\"mydatadisk1\",\n              \"diskSizeGB\":\"1\",\n              \"lun\": 0,\n              \"vhd\": {\n                \"uri\" : \"http://mystorage1.blob.core.windows.net/vhds/mydatadisk1.vhd\"\n              },\n              \"createOption\":\"Empty\"\n            }\n          ]\n        },\n        \"osProfile\": {\n          \"computerName\": \"windowsmachine\",\n          \"adminUsername\": \"azureuser\",\n          \"adminPassword\":\"password\",\n          \"customData\":\"\",\n          \"windowsConfiguration\": {\n            \"provisionVMAgent\": false,\n            \"enableAutomaticUpdates\": true,\n            \"winRM\": {\n              \"listeners\":[{\n                \"protocol\": \"https\",\n                \"certificateUrl\": \"url-to-certificate\"\n              }]\n            },\n            \"additionalUnattendContent\":[\n              {\n                \"passName\":\"oobesystem\",\n                \"componentName\":\"Microsoft-Windows-Shell-Setup\",\n                \"settingName\":\"FirstLogonCommands\",\n                \"content\":\"<XML unattend content>\"\n              }\n            ]\n          },\n          \"secrets\":[\n            {\n              \"sourceVault\": {\n                \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myresourcegroup1/providers/Microsoft.KeyVault/vaults/myvault1\"\n              },\n              \"vaultCertificates\": [\n                {\n                  \"certificateUrl\": \"https://myvault1.vault.azure.net/secrets/SECRETNAME/SECRETVERSION\",\n                  \"certificateStore\": \"CERTIFICATESTORENAME\"\n                }\n              ]\n            }\n          ]\n        },\n        \"networkProfile\": {\n          \"networkInterfaces\": [\n            {\n              \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/groupname/providers/Microsoft.Network/networkInterfaces/windowsmachine167\"\n            }\n          ]\n        },\n        \"diagnosticsProfile\": {\n          \"bootDiagnostics\": {\n            \"enabled\": true,\n            \"storageUri\": \"https://groupname2760.blob.core.windows.net/\"\n          }\n        },\n        \"provisioningState\": \"Creating\"\n      },\n      \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/groupname/providers/Microsoft.Compute/virtualMachines/windowsmachine\",\n      \"name\": \"windowsmachine\",\n      \"type\": \"Microsoft.Compute/virtualMachines\",\n      \"location\": \"westus\"\n    },\n    {\n      \"properties\": {\n        \"vmId\": \"27ee085b-d707-xxxx-yyyy-2370e2eb1cc1\",\n        \"licenseType\": \"Windows_Server\",\n        \"availabilitySet\":{\n          \"id\":\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/availabilitySets/myAVSet\"\n        },\n        \"hardwareProfile\": {\n          \"vmSize\": \"Standard_D1\"\n        },\n        \"storageProfile\": {\n          \"imageReference\": {\n            \"publisher\": \"publisher\",\n            \"offer\": \"OFFER\",\n            \"sku\": \"sku\",\n            \"version\": \"ver\",\n            \"id\": \"/subscriptions/SUBSCRIPTIONID/providers/Microsoft.Compute/locations/westus/publishers/MicrosoftWindowsServerEssentials/artifactype/vmimage/offers/OFFER/skus/OFFER/versions/latest\"\n          },\n          \"osDisk\": {\n            \"osType\": \"Windows\",\n            \"name\": \"windowsmachine\",\n            \"createOption\": \"FromImage\",\n            \"managedDisk\": {\n              \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/osDisk\",\n              \"storageAccountType\": \"Standard_LRS\"\n            },\n            \"vhd\": {\n              \"uri\": \"https://groupname2760.blob.core.windows.net/vhds/windowsmachine201624102936.vhd\"\n            },\n            \"caching\": \"ReadWrite\"\n          },\n          \"dataDisks\":[\n            {\n              \"name\":\"mydatadisk1\",\n              \"diskSizeGB\":\"1\",\n              \"lun\": 0,\n              \"vhd\": {\n                \"uri\" : \"http://mystorage1.blob.core.windows.net/vhds/mydatadisk1.vhd\"\n              },\n              \"createOption\":\"Empty\"\n            }\n          ]\n        },\n        \"osProfile\": {\n          \"computerName\": \"windowsmachine\",\n          \"adminUsername\": \"azureuser\",\n          \"adminPassword\":\"password\",\n          \"customData\":\"\",\n          \"windowsConfiguration\": {\n            \"provisionVMAgent\": false,\n            \"enableAutomaticUpdates\": true,\n            \"winRM\": {\n              \"listeners\":[{\n                \"protocol\": \"https\",\n                \"certificateUrl\": \"url-to-certificate\"\n              }]\n            },\n            \"additionalUnattendContent\":[\n              {\n                \"passName\":\"oobesystem\",\n                \"componentName\":\"Microsoft-Windows-Shell-Setup\",\n                \"settingName\":\"FirstLogonCommands\",\n                \"content\":\"<XML unattend content>\"\n              }\n            ]\n          },\n          \"secrets\":[\n            {\n              \"sourceVault\": {\n                \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myresourcegroup1/providers/Microsoft.KeyVault/vaults/myvault1\"\n              },\n              \"vaultCertificates\": [\n                {\n                  \"certificateUrl\": \"https://myvault1.vault.azure.net/secrets/SECRETNAME/SECRETVERSION\",\n                  \"certificateStore\": \"CERTIFICATESTORENAME\"\n                }\n              ]\n            }\n          ]\n        },\n        \"networkProfile\": {\n          \"networkInterfaces\": [\n            {\n              \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/groupname/providers/Microsoft.Network/networkInterfaces/windowsmachine167\"\n            }\n          ]\n        },\n        \"diagnosticsProfile\": {\n          \"bootDiagnostics\": {\n            \"enabled\": true,\n            \"storageUri\": \"https://groupname2760.blob.core.windows.net/\"\n          }\n        },\n        \"provisioningState\": \"Creating\"\n      },\n      \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/otherresourcegroup/providers/Microsoft.Compute/virtualMachines/windowsmachine\",\n      \"name\": \"windowsmachine\",\n      \"type\": \"Microsoft.Compute/virtualMachines\",\n      \"location\": \"westus\"\n    }\n  ]\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/virtualmachinesinresourcegroup.json",
    "content": "{\n  \"value\": [\n    {\n      \"properties\": {\n        \"vmId\": \"27ee085b-d707-xxxx-yyyy-2370e2eb1cc1\",\n        \"licenseType\": \"Windows_Server\",    \n        \"availabilitySet\":{    \n          \"id\":\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/availabilitySets/myAVSet\"\n        },    \n        \"hardwareProfile\": {\n          \"vmSize\": \"Standard_D1\"\n        },\n        \"storageProfile\": {\n          \"imageReference\": {\n            \"publisher\": \"publisher\",\n            \"offer\": \"OFFER\",\n            \"sku\": \"sku\",\n            \"version\": \"ver\",\n            \"id\": \"/subscriptions/SUBSCRIPTIONID/providers/Microsoft.Compute/locations/westus/publishers/MicrosoftWindowsServerEssentials/artifactype/vmimage/offers/OFFER/skus/OFFER/versions/latest\"\n          },\n          \"osDisk\": {\n            \"osType\": \"Windows\",\n            \"name\": \"windowsmachine\",\n            \"createOption\": \"FromImage\",\n            \"managedDisk\": {\n              \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/osDisk\",\n              \"storageAccountType\": \"Standard_LRS\" \n            },\n            \"caching\": \"ReadWrite\"\n          },\n          \"dataDisks\":[\n            {\n              \"name\":\"mydatadisk1\",\n              \"diskSizeGB\":\"1\",\n              \"lun\": 0,\n              \"createOption\":\"Empty\",\n              \"caching\":\"ReadWrite\",\n              \"managedDisk\": {\n                \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/osDisk\",\n                \"storageAccountType\": \"Standard_LRS\"\n              }\n            }\n          ]    \n        },\n        \"osProfile\": {\n          \"computerName\": \"windowsmachine\",\n          \"adminUsername\": \"azureuser\",\n          \"adminPassword\":\"password\",\n          \"customData\":\"\",\n          \"windowsConfiguration\": {\n            \"provisionVMAgent\": false,\n            \"enableAutomaticUpdates\": true,\n            \"winRM\": {\n               \"listeners\":[{\n                 \"protocol\": \"https\",\n                 \"certificateUrl\": \"url-to-certificate\"\n               }]\n            },    \n            \"additionalUnattendContent\":[\n              {\n                \"passName\":\"oobesystem\",    \n                \"componentName\":\"Microsoft-Windows-Shell-Setup\",\n                \"settingName\":\"FirstLogonCommands\",\n                \"content\":\"<XML unattend content>\"\n              }\n            ]\n          },\n          \"secrets\":[\n            {\n              \"sourceVault\": {\n                 \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myresourcegroup1/providers/Microsoft.KeyVault/vaults/myvault1\"     \n               },\n               \"vaultCertificates\": [\n                 {\n                   \"certificateUrl\": \"https://myvault1.vault.azure.net/secrets/SECRETNAME/SECRETVERSION\",\n                   \"certificateStore\": \"CERTIFICATESTORENAME\"\n                 }\n               ]\n             }\n           ]\n        },\n        \"networkProfile\": {\n          \"networkInterfaces\": [\n            {\n              \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/groupname/providers/Microsoft.Network/networkInterfaces/windowsmachine167\"\n            }\n          ]\n        },\n        \"diagnosticsProfile\": {\n          \"bootDiagnostics\": {\n            \"enabled\": true,\n            \"storageUri\": \"https://groupname2760.blob.core.windows.net/\"\n          }\n        },\n        \"provisioningState\": \"Creating\"\n      },\n      \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/groupname/providers/Microsoft.Compute/virtualMachines/windowsmachine\",\n      \"name\": \"windowsmachine\",\n      \"type\": \"Microsoft.Compute/virtualMachines\",\n      \"location\": \"westus\"\n    },\n    {\n      \"properties\": {\n        \"vmId\": \"27ee085b-d707-xxxx-yyyy-2370e2eb1cc1\",\n        \"licenseType\": \"Windows_Server\",\n        \"availabilitySet\":{\n          \"id\":\"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/availabilitySets/myAVSet\"\n        },\n        \"hardwareProfile\": {\n          \"vmSize\": \"Standard_D1\"\n        },\n        \"storageProfile\": {\n          \"imageReference\": {\n            \"publisher\": \"publisher\",\n            \"offer\": \"OFFER\",\n            \"sku\": \"sku\",\n            \"version\": \"ver\",\n            \"id\": \"/subscriptions/SUBSCRIPTIONID/providers/Microsoft.Compute/locations/westus/publishers/MicrosoftWindowsServerEssentials/artifactype/vmimage/offers/OFFER/skus/OFFER/versions/latest\"\n          },\n          \"osDisk\": {\n            \"osType\": \"Windows\",\n            \"name\": \"windowsmachine\",\n            \"createOption\": \"FromImage\",\n            \"managedDisk\": {\n              \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/osDisk\",\n              \"storageAccountType\": \"Standard_LRS\"\n            },\n            \"vhd\": {\n              \"uri\": \"https://groupname2760.blob.core.windows.net/vhds/windowsmachine201624102936.vhd\"\n            },\n            \"caching\": \"ReadWrite\"\n          },\n          \"dataDisks\":[\n            {\n              \"name\":\"mydatadisk1\",\n              \"diskSizeGB\":\"1\",\n              \"lun\": 0,\n              \"vhd\": {\n                \"uri\" : \"http://mystorage1.blob.core.windows.net/vhds/mydatadisk1.vhd\"\n              },\n              \"createOption\":\"Empty\"\n            }\n          ]\n        },\n        \"osProfile\": {\n          \"computerName\": \"windowsmachine\",\n          \"adminUsername\": \"azureuser\",\n          \"adminPassword\":\"password\",\n          \"customData\":\"\",\n          \"windowsConfiguration\": {\n            \"provisionVMAgent\": false,\n            \"enableAutomaticUpdates\": true,\n            \"winRM\": {\n              \"listeners\":[{\n                \"protocol\": \"https\",\n                \"certificateUrl\": \"url-to-certificate\"\n              }]\n            },\n            \"additionalUnattendContent\":[\n              {\n                \"passName\":\"oobesystem\",\n                \"componentName\":\"Microsoft-Windows-Shell-Setup\",\n                \"settingName\":\"FirstLogonCommands\",\n                \"content\":\"<XML unattend content>\"\n              }\n            ]\n          },\n          \"secrets\":[\n            {\n              \"sourceVault\": {\n                \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myresourcegroup1/providers/Microsoft.KeyVault/vaults/myvault1\"\n              },\n              \"vaultCertificates\": [\n                {\n                  \"certificateUrl\": \"https://myvault1.vault.azure.net/secrets/SECRETNAME/SECRETVERSION\",\n                  \"certificateStore\": \"CERTIFICATESTORENAME\"\n                }\n              ]\n            }\n          ]\n        },\n        \"networkProfile\": {\n          \"networkInterfaces\": [\n            {\n              \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/groupname/providers/Microsoft.Network/networkInterfaces/windowsmachine167\"\n            }\n          ]\n        },\n        \"diagnosticsProfile\": {\n          \"bootDiagnostics\": {\n            \"enabled\": true,\n            \"storageUri\": \"https://groupname2760.blob.core.windows.net/\"\n          }\n        },\n        \"provisioningState\": \"Creating\"\n      },\n      \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/groupname/providers/Microsoft.Compute/virtualMachines/windowsmachine\",\n      \"name\": \"windowsmachine\",\n      \"type\": \"Microsoft.Compute/virtualMachines\",\n      \"location\": \"westus\"\n    }\n  ]\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/virtualmachinesinsubscription.json",
    "content": "{\n  \"value\": [\n    {\n      \"properties\": {\n        \"vmId\": \"27ee085b-d707-xxxx-yyyy-2370e2eb1cc1\",\n        \"licenseType\": \"Windows_Server\",\n        \"availabilitySet\": {\n          \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/availabilitySets/myAVSet\"\n        },\n        \"hardwareProfile\": {\n          \"vmSize\": \"Standard_D1\"\n        },\n        \"storageProfile\": {\n          \"imageReference\": {\n            \"publisher\": \"publisher\",\n            \"offer\": \"OFFER\",\n            \"sku\": \"sku\",\n            \"version\": \"ver\",\n            \"id\": \"/subscriptions/SUBSCRIPTIONID/providers/Microsoft.Compute/locations/westus/publishers/MicrosoftWindowsServerEssentials/artifactype/vmimage/offers/OFFER/skus/OFFER/versions/latest\"\n          },\n          \"osDisk\": {\n            \"osType\": \"Windows\",\n            \"name\": \"windowsmachine\",\n            \"createOption\": \"FromImage\",\n            \"managedDisk\": {\n              \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/osDisk\",\n              \"storageAccountType\": \"Standard_LRS\"\n            },\n            \"caching\": \"ReadWrite\"\n          },\n          \"dataDisks\": [\n            {\n              \"name\": \"mydatadisk1\",\n              \"diskSizeGB\": \"1\",\n              \"lun\": 0,\n              \"createOption\": \"Empty\",\n              \"caching\": \"ReadWrite\",\n              \"managedDisk\": {\n                \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/osDisk\",\n                \"storageAccountType\": \"Standard_LRS\"\n              }\n            }\n          ]\n        },\n        \"osProfile\": {\n          \"computerName\": \"windowsmachine\",\n          \"adminUsername\": \"azureuser\",\n          \"adminPassword\": \"password\",\n          \"customData\": \"\",\n          \"windowsConfiguration\": {\n            \"provisionVMAgent\": false,\n            \"enableAutomaticUpdates\": true,\n            \"winRM\": {\n              \"listeners\": [\n                {\n                  \"protocol\": \"https\",\n                  \"certificateUrl\": \"url-to-certificate\"\n                }\n              ]\n            },\n            \"additionalUnattendContent\": [\n              {\n                \"passName\": \"oobesystem\",\n                \"componentName\": \"Microsoft-Windows-Shell-Setup\",\n                \"settingName\": \"FirstLogonCommands\",\n                \"content\": \"<XML unattend content>\"\n              }\n            ]\n          },\n          \"secrets\": [\n            {\n              \"sourceVault\": {\n                \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myresourcegroup1/providers/Microsoft.KeyVault/vaults/myvault1\"\n              },\n              \"vaultCertificates\": [\n                {\n                  \"certificateUrl\": \"https://myvault1.vault.azure.net/secrets/SECRETNAME/SECRETVERSION\",\n                  \"certificateStore\": \"CERTIFICATESTORENAME\"\n                }\n              ]\n            }\n          ]\n        },\n        \"networkProfile\": {\n          \"networkInterfaces\": [\n            {\n              \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/groupname/providers/Microsoft.Network/networkInterfaces/windowsmachine167\"\n            }\n          ]\n        },\n        \"diagnosticsProfile\": {\n          \"bootDiagnostics\": {\n            \"enabled\": true,\n            \"storageUri\": \"https://groupname2760.blob.core.windows.net/\"\n          }\n        },\n        \"provisioningState\": \"Creating\"\n      },\n      \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/groupname/providers/Microsoft.Compute/virtualMachines/windowsmachine\",\n      \"name\": \"windowsmachine\",\n      \"type\": \"Microsoft.Compute/virtualMachines\",\n      \"location\": \"westus\"\n    },\n    {\n      \"properties\": {\n        \"vmId\": \"27ee085b-d707-xxxx-yyyy-2370e2eb1cc1\",\n        \"licenseType\": \"Windows_Server\",\n        \"availabilitySet\": {\n          \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/availabilitySets/myAVSet\"\n        },\n        \"hardwareProfile\": {\n          \"vmSize\": \"Standard_D1\"\n        },\n        \"storageProfile\": {\n          \"imageReference\": {\n            \"publisher\": \"publisher\",\n            \"offer\": \"OFFER\",\n            \"sku\": \"sku\",\n            \"version\": \"ver\",\n            \"id\": \"/subscriptions/SUBSCRIPTIONID/providers/Microsoft.Compute/locations/westus/publishers/MicrosoftWindowsServerEssentials/artifactype/vmimage/offers/OFFER/skus/OFFER/versions/latest\"\n          },\n          \"osDisk\": {\n            \"osType\": \"Windows\",\n            \"name\": \"windowsmachine\",\n            \"createOption\": \"FromImage\",\n            \"managedDisk\": {\n              \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/osDisk\",\n              \"storageAccountType\": \"Standard_LRS\"\n            },\n            \"vhd\": {\n              \"uri\": \"https://groupname2760.blob.core.windows.net/vhds/windowsmachine201624102936.vhd\"\n            },\n            \"caching\": \"ReadWrite\"\n          },\n          \"dataDisks\": [\n            {\n              \"name\": \"mydatadisk1\",\n              \"diskSizeGB\": \"1\",\n              \"lun\": 0,\n              \"vhd\": {\n                \"uri\": \"http://mystorage1.blob.core.windows.net/vhds/mydatadisk1.vhd\"\n              },\n              \"createOption\": \"Empty\"\n            }\n          ]\n        },\n        \"osProfile\": {\n          \"computerName\": \"windowsmachine\",\n          \"adminUsername\": \"azureuser\",\n          \"adminPassword\": \"password\",\n          \"customData\": \"\",\n          \"windowsConfiguration\": {\n            \"provisionVMAgent\": false,\n            \"enableAutomaticUpdates\": true,\n            \"winRM\": {\n              \"listeners\": [\n                {\n                  \"protocol\": \"https\",\n                  \"certificateUrl\": \"url-to-certificate\"\n                }\n              ]\n            },\n            \"additionalUnattendContent\": [\n              {\n                \"passName\": \"oobesystem\",\n                \"componentName\": \"Microsoft-Windows-Shell-Setup\",\n                \"settingName\": \"FirstLogonCommands\",\n                \"content\": \"<XML unattend content>\"\n              }\n            ]\n          },\n          \"secrets\": [\n            {\n              \"sourceVault\": {\n                \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myresourcegroup1/providers/Microsoft.KeyVault/vaults/myvault1\"\n              },\n              \"vaultCertificates\": [\n                {\n                  \"certificateUrl\": \"https://myvault1.vault.azure.net/secrets/SECRETNAME/SECRETVERSION\",\n                  \"certificateStore\": \"CERTIFICATESTORENAME\"\n                }\n              ]\n            }\n          ]\n        },\n        \"networkProfile\": {\n          \"networkInterfaces\": [\n            {\n              \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/groupname/providers/Microsoft.Network/networkInterfaces/windowsmachine167\"\n            }\n          ]\n        },\n        \"diagnosticsProfile\": {\n          \"bootDiagnostics\": {\n            \"enabled\": true,\n            \"storageUri\": \"https://groupname2760.blob.core.windows.net/\"\n          }\n        },\n        \"provisioningState\": \"Creating\"\n      },\n      \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/groupname/providers/Microsoft.Compute/virtualMachines/windowsmachine\",\n      \"name\": \"windowsmachine\",\n      \"type\": \"Microsoft.Compute/virtualMachines\",\n      \"location\": \"westus\"\n    },\n    {\n      \"properties\": {\n        \"vmId\": \"27ee085b-d707-xxxx-yyyy-2370e2eb1cc1\",\n        \"licenseType\": \"Windows_Server\",\n        \"availabilitySet\": {\n          \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/availabilitySets/myAVSet\"\n        },\n        \"hardwareProfile\": {\n          \"vmSize\": \"Standard_D1\"\n        },\n        \"storageProfile\": {\n          \"imageReference\": {\n            \"publisher\": \"publisher\",\n            \"offer\": \"OFFER\",\n            \"sku\": \"sku\",\n            \"version\": \"ver\",\n            \"id\": \"/subscriptions/SUBSCRIPTIONID/providers/Microsoft.Compute/locations/westus/publishers/MicrosoftWindowsServerEssentials/artifactype/vmimage/offers/OFFER/skus/OFFER/versions/latest\"\n          },\n          \"osDisk\": {\n            \"osType\": \"Windows\",\n            \"name\": \"windowsmachine\",\n            \"createOption\": \"FromImage\",\n            \"managedDisk\": {\n              \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/osDisk\",\n              \"storageAccountType\": \"Standard_LRS\"\n            },\n            \"vhd\": {\n              \"uri\": \"https://groupname2760.blob.core.windows.net/vhds/windowsmachine201624102936.vhd\"\n            },\n            \"caching\": \"ReadWrite\"\n          },\n          \"dataDisks\": [\n            {\n              \"name\": \"mydatadisk1\",\n              \"diskSizeGB\": \"1\",\n              \"lun\": 0,\n              \"vhd\": {\n                \"uri\": \"http://mystorage1.blob.core.windows.net/vhds/mydatadisk1.vhd\"\n              },\n              \"createOption\": \"Empty\"\n            }\n          ]\n        },\n        \"osProfile\": {\n          \"computerName\": \"windowsmachine\",\n          \"adminUsername\": \"azureuser\",\n          \"adminPassword\": \"password\",\n          \"customData\": \"\",\n          \"windowsConfiguration\": {\n            \"provisionVMAgent\": false,\n            \"enableAutomaticUpdates\": true,\n            \"winRM\": {\n              \"listeners\": [\n                {\n                  \"protocol\": \"https\",\n                  \"certificateUrl\": \"url-to-certificate\"\n                }\n              ]\n            },\n            \"additionalUnattendContent\": [\n              {\n                \"passName\": \"oobesystem\",\n                \"componentName\": \"Microsoft-Windows-Shell-Setup\",\n                \"settingName\": \"FirstLogonCommands\",\n                \"content\": \"<XML unattend content>\"\n              }\n            ]\n          },\n          \"secrets\": [\n            {\n              \"sourceVault\": {\n                \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myresourcegroup1/providers/Microsoft.KeyVault/vaults/myvault1\"\n              },\n              \"vaultCertificates\": [\n                {\n                  \"certificateUrl\": \"https://myvault1.vault.azure.net/secrets/SECRETNAME/SECRETVERSION\",\n                  \"certificateStore\": \"CERTIFICATESTORENAME\"\n                }\n              ]\n            }\n          ]\n        },\n        \"networkProfile\": {\n          \"networkInterfaces\": [\n            {\n              \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/groupname/providers/Microsoft.Network/networkInterfaces/windowsmachine167\"\n            }\n          ]\n        },\n        \"diagnosticsProfile\": {\n          \"bootDiagnostics\": {\n            \"enabled\": true,\n            \"storageUri\": \"https://groupname2760.blob.core.windows.net/\"\n          }\n        },\n        \"provisioningState\": \"Creating\"\n      },\n      \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/otherresourcegroup/providers/Microsoft.Compute/virtualMachines/windowsmachine\",\n      \"name\": \"windowsmachine\",\n      \"type\": \"Microsoft.Compute/virtualMachines\",\n      \"location\": \"westus\"\n    },\n    {\n      \"properties\": {\n        \"vmId\": \"27ee085b-d707-xxxx-yyyy-2370e2eb1cc1\",\n        \"licenseType\": \"Windows_Server\",\n        \"availabilitySet\": {\n          \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/availabilitySets/myAVSet\"\n        },\n        \"hardwareProfile\": {\n          \"vmSize\": \"Standard_D1\"\n        },\n        \"storageProfile\": {\n          \"imageReference\": {\n            \"publisher\": \"publisher\",\n            \"offer\": \"OFFER\",\n            \"sku\": \"sku\",\n            \"version\": \"ver\",\n            \"id\": \"/subscriptions/SUBSCRIPTIONID/providers/Microsoft.Compute/locations/westus/publishers/MicrosoftWindowsServerEssentials/artifactype/vmimage/offers/OFFER/skus/OFFER/versions/latest\"\n          },\n          \"osDisk\": {\n            \"osType\": \"Windows\",\n            \"name\": \"windowsmachine\",\n            \"createOption\": \"FromImage\",\n            \"managedDisk\": {\n              \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myResourceGroup/providers/Microsoft.Compute/disks/osDisk\",\n              \"storageAccountType\": \"Standard_LRS\"\n            },\n            \"vhd\": {\n              \"uri\": \"https://groupname2760.blob.core.windows.net/vhds/windowsmachine201624102936.vhd\"\n            },\n            \"caching\": \"ReadWrite\"\n          },\n          \"dataDisks\": [\n            {\n              \"name\": \"mydatadisk1\",\n              \"diskSizeGB\": \"1\",\n              \"lun\": 0,\n              \"vhd\": {\n                \"uri\": \"http://mystorage1.blob.core.windows.net/vhds/mydatadisk1.vhd\"\n              },\n              \"createOption\": \"Empty\"\n            }\n          ]\n        },\n        \"osProfile\": {\n          \"computerName\": \"windowsmachine\",\n          \"adminUsername\": \"azureuser\",\n          \"adminPassword\": \"password\",\n          \"customData\": \"\",\n          \"windowsConfiguration\": {\n            \"provisionVMAgent\": false,\n            \"enableAutomaticUpdates\": true,\n            \"winRM\": {\n              \"listeners\": [\n                {\n                  \"protocol\": \"https\",\n                  \"certificateUrl\": \"url-to-certificate\"\n                }\n              ]\n            },\n            \"additionalUnattendContent\": [\n              {\n                \"passName\": \"oobesystem\",\n                \"componentName\": \"Microsoft-Windows-Shell-Setup\",\n                \"settingName\": \"FirstLogonCommands\",\n                \"content\": \"<XML unattend content>\"\n              }\n            ]\n          },\n          \"secrets\": [\n            {\n              \"sourceVault\": {\n                \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/myresourcegroup1/providers/Microsoft.KeyVault/vaults/myvault1\"\n              },\n              \"vaultCertificates\": [\n                {\n                  \"certificateUrl\": \"https://myvault1.vault.azure.net/secrets/SECRETNAME/SECRETVERSION\",\n                  \"certificateStore\": \"CERTIFICATESTORENAME\"\n                }\n              ]\n            }\n          ]\n        },\n        \"networkProfile\": {\n          \"networkInterfaces\": [\n            {\n              \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/groupname/providers/Microsoft.Network/networkInterfaces/windowsmachine167\"\n            }\n          ]\n        },\n        \"diagnosticsProfile\": {\n          \"bootDiagnostics\": {\n            \"enabled\": true,\n            \"storageUri\": \"https://groupname2760.blob.core.windows.net/\"\n          }\n        },\n        \"provisioningState\": \"Creating\"\n      },\n      \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/groupname/providers/Microsoft.Compute/virtualMachines/windowsmachine\",\n      \"name\": \"windowsmachine\",\n      \"type\": \"Microsoft.Compute/virtualMachines\",\n      \"location\": \"eastus\"\n    }\n  ]\n}\n"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/virtualnetwork.json",
    "content": "{\n    \"name\": \"mockvirtualnetwork\",\n    \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/azurearmtesting/providers/Microsoft.Network/virtualNetworks/mockvirtualnetwork\",\n    \"etag\": \"W/\\\"0dcd223f-670c-49ca-abe7-5978d127c131\\\"\",\n    \"type\": \"Microsoft.Network/virtualNetworks\",\n    \"location\": \"northeurope\",\n    \"tags\": {\n      \"tagkey\": \"tagvalue\"\n    },\n    \"properties\": {\n      \"provisioningState\": \"Succeeded\",\n      \"resourceGuid\": \"1568c76a-73a4-4a60-8dfb-53b823197ccb\",\n      \"addressSpace\": {\n        \"addressPrefixes\": [\n          \"10.2.0.0/16\"\n        ]\n      },\n      \"subnets\": []\n    }\n }"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/virtualnetworkgatewaycreate.json",
    "content": "{\n  \"name\": \"myvirtualgw\",\n  \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/rg-virtualnetworkgatewayapilivetest-nacx/providers/Microsoft.Network/virtualNetworkGateways/myvirtualgw\",\n  \"etag\": \"W/\\\"7d15735c-35b4-4e22-a281-d7d54c6fdecf\\\"\",\n  \"type\": \"Microsoft.Network/virtualNetworkGateways\",\n  \"location\": \"westeurope\",\n  \"properties\": {\n    \"provisioningState\": \"Updating\",\n    \"resourceGuid\": \"36998db6-e664-4683-ad8d-9afb2e23b1d8\",\n    \"ipConfigurations\": [\n      {\n        \"name\": \"myvirtualgw-ipconf\",\n        \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/rg-virtualnetworkgatewayapilivetest-nacx/providers/Microsoft.Network/virtualNetworkGateways/myvirtualgw/ipConfigurations/myvirtualgw-ipconf\",\n        \"etag\": \"W/\\\"7d15735c-35b4-4e22-a281-d7d54c6fdecf\\\"\",\n        \"properties\": {\n          \"provisioningState\": \"Updating\",\n          \"privateIPAllocationMethod\": \"Dynamic\",\n          \"publicIPAddress\": {\n            \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/rg-virtualnetworkgatewayapilivetest-nacx/providers/Microsoft.Network/publicIPAddresses/myvirtualgw-publicip\"\n          },\n          \"subnet\": {\n            \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/rg-virtualnetworkgatewayapilivetest-nacx/providers/Microsoft.Network/virtualNetworks/myvirtualgw-net/subnets/GatewaySubnet\"\n          }\n        }\n      }\n    ],\n    \"sku\": {\n      \"name\": \"Basic\",\n      \"tier\": \"Basic\",\n      \"capacity\": 2\n    },\n    \"gatewayType\": \"Vpn\",\n    \"vpnType\": \"PolicyBased\",\n    \"enableBgp\": false,\n    \"activeActive\": false,\n    \"vpnClientConfiguration\": {\n      \"vpnClientProtocols\": [\n        \"SSTP\"\n      ],\n      \"vpnClientRootCertificates\": [],\n      \"vpnClientRevokedCertificates\": [],\n      \"vpnClientIpsecPolicies\": []\n    }\n  }\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/virtualnetworkgatewayget.json",
    "content": "{\n  \"name\": \"myvirtualgw\",\n  \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/rg-virtualnetworkgatewayapilivetest-nacx/providers/Microsoft.Network/virtualNetworkGateways/myvirtualgw\",\n  \"etag\": \"W/\\\"7d15735c-35b4-4e22-a281-d7d54c6fdecf\\\"\",\n  \"type\": \"Microsoft.Network/virtualNetworkGateways\",\n  \"location\": \"westeurope\",\n  \"properties\": {\n    \"provisioningState\": \"Updating\",\n    \"resourceGuid\": \"36998db6-e664-4683-ad8d-9afb2e23b1d8\",\n    \"ipConfigurations\": [\n      {\n        \"name\": \"myvirtualgw-ipconf\",\n        \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/rg-virtualnetworkgatewayapilivetest-nacx/providers/Microsoft.Network/virtualNetworkGateways/myvirtualgw/ipConfigurations/myvirtualgw-ipconf\",\n        \"etag\": \"W/\\\"7d15735c-35b4-4e22-a281-d7d54c6fdecf\\\"\",\n        \"properties\": {\n          \"provisioningState\": \"Updating\",\n          \"privateIPAllocationMethod\": \"Dynamic\",\n          \"publicIPAddress\": {\n            \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/rg-virtualnetworkgatewayapilivetest-nacx/providers/Microsoft.Network/publicIPAddresses/myvirtualgw-publicip\"\n          },\n          \"subnet\": {\n            \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/rg-virtualnetworkgatewayapilivetest-nacx/providers/Microsoft.Network/virtualNetworks/myvirtualgw-net/subnets/GatewaySubnet\"\n          }\n        }\n      }\n    ],\n    \"sku\": {\n      \"name\": \"Basic\",\n      \"tier\": \"Basic\",\n      \"capacity\": 2\n    },\n    \"gatewayType\": \"Vpn\",\n    \"vpnType\": \"PolicyBased\",\n    \"enableBgp\": false,\n    \"activeActive\": false\n  }\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/virtualnetworkgatewaylist.json",
    "content": "{\n  \"value\": [\n    {\n      \"name\": \"myvirtualgw\",\n      \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/rg-virtualnetworkgatewayapilivetest-nacx/providers/Microsoft.Network/virtualNetworkGateways/myvirtualgw\",\n      \"etag\": \"W/\\\"7d15735c-35b4-4e22-a281-d7d54c6fdecf\\\"\",\n      \"type\": \"Microsoft.Network/virtualNetworkGateways\",\n      \"location\": \"westeurope\",\n      \"properties\": {\n        \"provisioningState\": \"Updating\",\n        \"resourceGuid\": \"36998db6-e664-4683-ad8d-9afb2e23b1d8\",\n        \"ipConfigurations\": [\n          {\n            \"name\": \"myvirtualgw-ipconf\",\n            \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/rg-virtualnetworkgatewayapilivetest-nacx/providers/Microsoft.Network/virtualNetworkGateways/myvirtualgw/ipConfigurations/myvirtualgw-ipconf\",\n            \"etag\": \"W/\\\"7d15735c-35b4-4e22-a281-d7d54c6fdecf\\\"\",\n            \"properties\": {\n              \"provisioningState\": \"Updating\",\n              \"privateIPAllocationMethod\": \"Dynamic\",\n              \"publicIPAddress\": {\n                \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/rg-virtualnetworkgatewayapilivetest-nacx/providers/Microsoft.Network/publicIPAddresses/myvirtualgw-publicip\"\n              },\n              \"subnet\": {\n                \"id\": \"/subscriptions/SUBSCRIPTIONID/resourceGroups/rg-virtualnetworkgatewayapilivetest-nacx/providers/Microsoft.Network/virtualNetworks/myvirtualgw-net/subnets/GatewaySubnet\"\n              }\n            }\n          }\n        ],\n        \"sku\": {\n          \"name\": \"Basic\",\n          \"tier\": \"Basic\",\n          \"capacity\": 2\n        },\n        \"gatewayType\": \"Vpn\",\n        \"vpnType\": \"PolicyBased\",\n        \"enableBgp\": false,\n        \"activeActive\": false,\n        \"vpnClientConfiguration\": {\n          \"vpnClientProtocols\": [\n            \"SSTP\"\n          ],\n          \"vpnClientRootCertificates\": [],\n          \"vpnClientRevokedCertificates\": [],\n          \"vpnClientIpsecPolicies\": []\n        }\n      }\n    }\n  ]\n}"
  },
  {
    "path": "providers/azurecompute-arm/src/test/resources/vmsizes.json",
    "content": "{\n  \"value\": [\n    {\n      \"name\": \"Standard_A0\",\n      \"numberOfCores\": 1,\n      \"osDiskSizeInMB\": 1047552,\n      \"resourceDiskSizeInMB\": 20480,\n      \"memoryInMB\": 768,\n      \"maxDataDiskCount\": 1\n    },\n    {\n      \"name\": \"Standard_A1\",\n      \"numberOfCores\": 1,\n      \"osDiskSizeInMB\": 1047552,\n      \"resourceDiskSizeInMB\": 71680,\n      \"memoryInMB\": 1792,\n      \"maxDataDiskCount\": 2\n    },\n    {\n      \"name\": \"Standard_A2\",\n      \"numberOfCores\": 2,\n      \"osDiskSizeInMB\": 1047552,\n      \"resourceDiskSizeInMB\": 138240,\n      \"memoryInMB\": 3584,\n      \"maxDataDiskCount\": 4\n    }\n  ]\n}"
  },
  {
    "path": "providers/b2/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.b2.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "providers/b2/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://maven.apache.org/POM/4.0.0\"\n         xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n\n  <groupId>org.apache.jclouds.provider</groupId>\n  <artifactId>b2</artifactId>\n  <name>Apache jclouds B2 API</name>\n  <description>BlobStore binding to the Backblaze B2 API</description>\n\n  <properties>\n    <test.b2.identity>FIXME_IDENTITY</test.b2.identity>\n    <test.b2.credential>FIXME_CREDENTIAL</test.b2.credential>\n    <test.b2.build-version />\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-blobstore</artifactId>\n      <version>${project.version}</version>\n      <type>jar</type>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-blobstore</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-log4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.logging.log4j</groupId>\n      <artifactId>log4j-core</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.value</groupId>\n      <artifactId>auto-value</artifactId>\n      <scope>provided</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.squareup.okhttp3</groupId>\n      <artifactId>mockwebserver</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.assertj</groupId>\n      <artifactId>assertj-core</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <groups>live</groups>\n                  <systemPropertyVariables>\n                    <jclouds.blobstore.httpstream.url>${jclouds.blobstore.httpstream.url}</jclouds.blobstore.httpstream.url>\n                    <jclouds.blobstore.httpstream.md5>${jclouds.blobstore.httpstream.md5}</jclouds.blobstore.httpstream.md5>\n                    <test.b2.endpoint>${test.b2.endpoint}</test.b2.endpoint>\n                    <test.b2.api-version>${test.b2.api-version}</test.b2.api-version>\n                    <test.b2.build-version>${test.b2.build-version}</test.b2.build-version>\n                    <test.b2.identity>${test.b2.identity}</test.b2.identity>\n                    <test.b2.credential>${test.b2.credential}</test.b2.credential>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n</project>\n"
  },
  {
    "path": "providers/b2/src/main/java/org/jclouds/b2/B2Api.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2;\n\nimport java.io.Closeable;\n\nimport org.jclouds.b2.features.AuthorizationApi;\nimport org.jclouds.b2.features.BucketApi;\nimport org.jclouds.b2.features.MultipartApi;\nimport org.jclouds.b2.features.ObjectApi;\nimport org.jclouds.rest.annotations.Delegate;\n\n/** Provides access to Backblaze B2 resources via their REST API. */\npublic interface B2Api extends Closeable {\n   @Delegate\n   AuthorizationApi getAuthorizationApi();\n\n   @Delegate\n   BucketApi getBucketApi();\n\n   @Delegate\n   ObjectApi getObjectApi();\n\n   @Delegate\n   MultipartApi getMultipartApi();\n}\n"
  },
  {
    "path": "providers/b2/src/main/java/org/jclouds/b2/B2ApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2;\n\nimport static org.jclouds.reflect.Reflection2.typeToken;\n\nimport java.net.URI;\nimport java.util.Properties;\nimport java.util.concurrent.TimeUnit;\n\nimport org.jclouds.Constants;\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.blobstore.BlobStoreContext;\nimport org.jclouds.blobstore.reference.BlobStoreConstants;\nimport org.jclouds.b2.blobstore.config.B2BlobStoreContextModule;\nimport org.jclouds.b2.config.B2HttpApiModule;\nimport org.jclouds.rest.internal.BaseHttpApiMetadata;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\npublic final class B2ApiMetadata extends BaseHttpApiMetadata {\n   @Override\n   public Builder toBuilder() {\n      return new Builder().fromApiMetadata(this);\n   }\n\n   public B2ApiMetadata() {\n      this(new Builder());\n   }\n\n   protected B2ApiMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = BaseHttpApiMetadata.defaultProperties();\n      properties.setProperty(BlobStoreConstants.PROPERTY_USER_METADATA_PREFIX, \"X-Bz-Info-\");\n      properties.setProperty(Constants.PROPERTY_SESSION_INTERVAL, String.valueOf(TimeUnit.HOURS.toSeconds(1)));\n      properties.setProperty(Constants.PROPERTY_IDEMPOTENT_METHODS, \"DELETE,GET,HEAD,OPTIONS,POST,PUT\");\n      properties.setProperty(Constants.PROPERTY_RETRY_DELAY_START, String.valueOf(TimeUnit.SECONDS.toMillis(1)));\n      return properties;\n   }\n\n   public static class Builder extends BaseHttpApiMetadata.Builder<B2Api, Builder> {\n\n      protected Builder() {\n         super(B2Api.class);\n         id(\"b2\")\n                 .name(\"Backblaze B2 API\")\n                 .identityName(\"Account Id\")\n                 .credentialName(\"Application Key\")\n                 .documentation(URI.create(\"https://www.backblaze.com/b2/docs/\"))\n                 .defaultEndpoint(\"https://api.backblazeb2.com/\")\n                 .defaultProperties(B2ApiMetadata.defaultProperties())\n                 .view(typeToken(BlobStoreContext.class))\n                 .defaultModules(ImmutableSet.<Class<? extends Module>>of(\n                         B2HttpApiModule.class,\n                         B2BlobStoreContextModule.class));\n      }\n\n      @Override\n      public B2ApiMetadata build() {\n         return new B2ApiMetadata(this);\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n\n      @Override\n      public Builder fromApiMetadata(ApiMetadata in) {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "providers/b2/src/main/java/org/jclouds/b2/B2ProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2;\n\nimport java.util.Properties;\n\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\n\nimport com.google.auto.service.AutoService;\n\n@AutoService(ProviderMetadata.class)\npublic final class B2ProviderMetadata extends BaseProviderMetadata {\n   @Override\n   public Builder toBuilder() {\n      return new Builder().fromProviderMetadata(this);\n   }\n\n   public B2ProviderMetadata() {\n      this(new Builder());\n   }\n\n   protected B2ProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = B2ApiMetadata.defaultProperties();\n      return properties;\n   }\n\n   public static class Builder extends BaseProviderMetadata.Builder {\n\n      protected Builder() {\n         id(\"b2\")\n                 .name(\"Backblaze B2\")\n                 .apiMetadata(new B2ApiMetadata())\n                 .endpoint(\"https://api.backblazeb2.com/\")\n                 .defaultProperties(B2ProviderMetadata.defaultProperties());\n      }\n\n      @Override\n      public B2ProviderMetadata build() {\n         return new B2ProviderMetadata(this);\n      }\n\n      @Override\n      public Builder fromProviderMetadata(ProviderMetadata in) {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "providers/b2/src/main/java/org/jclouds/b2/B2ResponseException.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2;\n\nimport org.jclouds.b2.domain.B2Error;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\n\nimport com.google.common.base.Preconditions;\nimport org.jclouds.javax.annotation.Nullable;\n\npublic final class B2ResponseException extends HttpResponseException {\n   private final transient B2Error error;\n\n   public B2ResponseException(HttpCommand command, HttpResponse response, B2Error error) {\n      super(\"request \" + command.getCurrentRequest().getRequestLine() + \" failed with code \" + response.getStatusCode()\n            + \", error: \" + Preconditions.checkNotNull(error, \"error\").toString(), command, response);\n      this.error = error;\n   }\n\n   @Nullable\n   public B2Error getError() {\n      return error;\n   }\n}\n"
  },
  {
    "path": "providers/b2/src/main/java/org/jclouds/b2/binders/UploadFileBinder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2.binders;\n\nimport java.util.Map;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.b2.domain.UploadUrlResponse;\nimport org.jclouds.b2.reference.B2Headers;\nimport org.jclouds.rest.MapBinder;\n\nimport com.google.common.net.HttpHeaders;\nimport com.google.common.net.PercentEscaper;\n\npublic final class UploadFileBinder implements MapBinder {\n   private static final PercentEscaper escaper = new PercentEscaper(\"._-/~!$'()*;=:@\", false);\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      UploadUrlResponse uploadUrl = (UploadUrlResponse) postParams.get(\"uploadUrl\");\n      String fileName = (String) postParams.get(\"fileName\");\n      String contentSha1 = (String) postParams.get(\"contentSha1\");\n      if (contentSha1 == null) {\n         contentSha1 = \"do_not_verify\";\n      }\n      Map<String, String> fileInfo = (Map<String, String>) postParams.get(\"fileInfo\");\n      HttpRequest.Builder builder = request.toBuilder()\n            .endpoint(uploadUrl.uploadUrl())\n            .replaceHeader(HttpHeaders.AUTHORIZATION, uploadUrl.authorizationToken())\n            .replaceHeader(B2Headers.CONTENT_SHA1, contentSha1)\n            .replaceHeader(B2Headers.FILE_NAME, escaper.escape(fileName));\n      for (Map.Entry<String, String> entry : fileInfo.entrySet()) {\n         builder.replaceHeader(B2Headers.FILE_INFO_PREFIX + entry.getKey(), escaper.escape(entry.getValue()));\n      }\n      return (R) builder.build();\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      throw new UnsupportedOperationException();\n   }\n}\n"
  },
  {
    "path": "providers/b2/src/main/java/org/jclouds/b2/binders/UploadPartBinder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2.binders;\n\nimport java.util.Map;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.b2.domain.GetUploadPartResponse;\nimport org.jclouds.b2.reference.B2Headers;\nimport org.jclouds.rest.MapBinder;\n\nimport com.google.common.net.HttpHeaders;\n\npublic final class UploadPartBinder implements MapBinder {\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      GetUploadPartResponse uploadUrl = (GetUploadPartResponse) postParams.get(\"response\");\n      String contentSha1 = (String) postParams.get(\"contentSha1\");\n      if (contentSha1 == null) {\n         contentSha1 = \"do_not_verify\";\n      }\n      return (R) request.toBuilder()\n            .endpoint(uploadUrl.uploadUrl())\n            .replaceHeader(HttpHeaders.AUTHORIZATION, uploadUrl.authorizationToken())\n            .replaceHeader(B2Headers.CONTENT_SHA1, contentSha1)\n            .build();\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      throw new UnsupportedOperationException();\n   }\n}\n"
  },
  {
    "path": "providers/b2/src/main/java/org/jclouds/b2/blobstore/B2BlobStore.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2.blobstore;\n\nimport java.io.UnsupportedEncodingException;\nimport java.net.URI;\nimport java.net.URLEncoder;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.TimeUnit;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.b2.B2Api;\nimport org.jclouds.b2.B2ResponseException;\nimport org.jclouds.b2.domain.Action;\nimport org.jclouds.b2.domain.Authorization;\nimport org.jclouds.b2.domain.B2Object;\nimport org.jclouds.b2.domain.B2ObjectList;\nimport org.jclouds.b2.domain.Bucket;\nimport org.jclouds.b2.domain.BucketList;\nimport org.jclouds.b2.domain.BucketType;\nimport org.jclouds.b2.domain.GetUploadPartResponse;\nimport org.jclouds.b2.domain.ListPartsResponse;\nimport org.jclouds.b2.domain.ListUnfinishedLargeFilesResponse;\nimport org.jclouds.b2.domain.MultipartUploadResponse;\nimport org.jclouds.b2.domain.UploadFileResponse;\nimport org.jclouds.b2.domain.UploadUrlResponse;\nimport org.jclouds.b2.domain.UploadPartResponse;\nimport org.jclouds.blobstore.BlobStoreContext;\nimport org.jclouds.blobstore.ContainerNotFoundException;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.BlobAccess;\nimport org.jclouds.blobstore.domain.BlobMetadata;\nimport org.jclouds.blobstore.domain.ContainerAccess;\nimport org.jclouds.blobstore.domain.MultipartPart;\nimport org.jclouds.blobstore.domain.MultipartUpload;\nimport org.jclouds.blobstore.domain.MutableBlobMetadata;\nimport org.jclouds.blobstore.domain.PageSet;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.domain.StorageType;\nimport org.jclouds.blobstore.domain.Tier;\nimport org.jclouds.blobstore.domain.internal.BlobImpl;\nimport org.jclouds.blobstore.domain.internal.BlobMetadataImpl;\nimport org.jclouds.blobstore.domain.internal.MutableBlobMetadataImpl;\nimport org.jclouds.blobstore.domain.internal.PageSetImpl;\nimport org.jclouds.blobstore.domain.internal.StorageMetadataImpl;\nimport org.jclouds.blobstore.functions.BlobToHttpGetOptions;\nimport org.jclouds.blobstore.internal.BaseBlobStore;\nimport org.jclouds.blobstore.options.CreateContainerOptions;\nimport org.jclouds.blobstore.options.GetOptions;\nimport org.jclouds.blobstore.options.ListContainerOptions;\nimport org.jclouds.blobstore.options.PutOptions;\nimport org.jclouds.blobstore.util.BlobUtils;\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.domain.Location;\nimport org.jclouds.io.ContentMetadata;\nimport org.jclouds.io.ContentMetadataBuilder;\nimport org.jclouds.io.MutableContentMetadata;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.PayloadSlicer;\nimport org.jclouds.io.payloads.BaseMutableContentMetadata;\n\nimport com.google.common.base.Preconditions;\nimport com.google.common.base.Strings;\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.net.HttpHeaders;\nimport com.google.common.util.concurrent.UncheckedExecutionException;\n\npublic final class B2BlobStore extends BaseBlobStore {\n   private final B2Api api;\n   private final BlobToHttpGetOptions blob2ObjectGetOptions;\n   private final LoadingCache<String, Bucket> bucketNameToBucket;\n   private final Supplier<Authorization> auth;\n\n   @Inject\n   B2BlobStore(BlobStoreContext context, BlobUtils blobUtils, Supplier<Location> defaultLocation,\n            @Memoized Supplier<Set<? extends Location>> locations, PayloadSlicer slicer, final B2Api api,\n            BlobToHttpGetOptions blob2ObjectGetOptions, @Memoized Supplier<Authorization> auth) {\n      super(context, blobUtils, defaultLocation, locations, slicer);\n      this.api = api;\n      this.blob2ObjectGetOptions = blob2ObjectGetOptions;\n      this.auth = auth;\n      this.bucketNameToBucket = CacheBuilder.newBuilder()\n            .expireAfterWrite(5, TimeUnit.MINUTES)\n            .build(new CacheLoader<String, Bucket>() {\n               @Override\n               public Bucket load(String bucketName) {\n                  BucketList list = api.getBucketApi().listBuckets();\n                  for (Bucket bucket : list.buckets()) {\n                     if (bucket.bucketName().equals(bucketName)) {\n                        return bucket;\n                     }\n                  }\n                  throw new ContainerNotFoundException(bucketName, null);\n               }\n            });\n   }\n\n   @Override\n   public PageSet<? extends StorageMetadata> list() {\n      ImmutableList.Builder<StorageMetadata> builder = ImmutableList.builder();\n      BucketList list = api.getBucketApi().listBuckets();\n      for (Bucket bucket : list.buckets()) {\n         builder.add(new StorageMetadataImpl(StorageType.CONTAINER, null, bucket.bucketName(), defaultLocation.get(), null, null, null, null, ImmutableMap.<String, String>of(), null, Tier.STANDARD));\n      }\n      return new PageSetImpl<StorageMetadata>(builder.build(), null);\n   }\n\n   @Override\n   public boolean containerExists(String container) {\n      BucketList list = api.getBucketApi().listBuckets();\n      for (Bucket bucket : list.buckets()) {\n         if (bucket.bucketName().equals(container)) {\n            return true;\n         }\n      }\n      return false;\n   }\n\n   @Override\n   public boolean createContainerInLocation(Location location, String container) {\n      return createContainerInLocation(location, container, CreateContainerOptions.NONE);\n   }\n\n   @Override\n   public boolean createContainerInLocation(Location location, String container, CreateContainerOptions options) {\n      BucketType bucketType = options.isPublicRead() ? BucketType.ALL_PUBLIC : BucketType.ALL_PRIVATE;\n      try {\n         Bucket bucket = api.getBucketApi().createBucket(container, bucketType);\n         bucketNameToBucket.put(container, bucket);\n      } catch (B2ResponseException bre) {\n         if (bre.getError().code().equals(\"duplicate_bucket_name\")) {\n            return false;\n         }\n         throw bre;\n      }\n      return true;\n   }\n\n   @Override\n   public ContainerAccess getContainerAccess(String container) {\n      Bucket bucket = getBucket(container);\n      return bucket.bucketType() == BucketType.ALL_PUBLIC ? ContainerAccess.PUBLIC_READ : ContainerAccess.PRIVATE;\n   }\n\n   @Override\n   public void setContainerAccess(String container, ContainerAccess access) {\n      Bucket bucket = getBucket(container);\n\n      BucketType bucketType = access == ContainerAccess.PUBLIC_READ ? BucketType.ALL_PUBLIC : BucketType.ALL_PRIVATE;\n      bucket = api.getBucketApi().updateBucket(bucket.bucketId(), bucketType);\n      bucketNameToBucket.put(container, bucket);\n   }\n\n   @Override\n   public PageSet<? extends StorageMetadata> list(String container) {\n      return list(container, ListContainerOptions.NONE);\n   }\n\n   @Override\n   public PageSet<? extends StorageMetadata> list(String container, ListContainerOptions options) {\n      Preconditions.checkArgument(options.getDir() == null, \"B2 does not support directories\");\n      String delimiter = null;\n      if (!options.isRecursive()) {\n         delimiter = \"/\";\n      }\n      if (options.getDelimiter() != null) {\n         delimiter = options.getDelimiter();\n      }\n\n      Bucket bucket = getBucket(container);\n\n      ImmutableList.Builder<StorageMetadata> builder = ImmutableList.builder();\n      B2ObjectList list = api.getObjectApi().listFileNames(bucket.bucketId(), options.getMarker(), options.getMaxResults(), options.getPrefix(), Strings.emptyToNull(delimiter));\n      for (B2ObjectList.Entry entry : list.files()) {\n         if (entry.action() == Action.FOLDER) {\n            builder.add(new StorageMetadataImpl(StorageType.RELATIVE_PATH, null, entry.fileName(), null, null, null, null, entry.uploadTimestamp(), ImmutableMap.<String, String>of(), null, Tier.STANDARD));\n         } else if (options.isDetailed()) {\n            BlobMetadata metadata = blobMetadata(container, entry.fileName());\n            if (metadata != null) {\n               builder.add(metadata);\n            }\n         } else {\n            Map<String, String> userMetadata = ImmutableMap.of();\n            ContentMetadata metadata = ContentMetadataBuilder.create()\n                  .contentLength(entry.contentLength())\n                  .build();\n            builder.add(new BlobMetadataImpl(null, entry.fileName(), null, null, null, null, entry.uploadTimestamp(), userMetadata, null, container, metadata, entry.contentLength()));\n         }\n      }\n      return new PageSetImpl<StorageMetadata>(builder.build(), list.nextFileName());\n   }\n\n   @Override\n   public boolean blobExists(String container, String name) {\n      return blobMetadata(container, name) != null;\n   }\n\n   @Override\n   public String putBlob(String container, Blob blob) {\n      return putBlob(container, blob, PutOptions.NONE);\n   }\n\n   @Override\n   public String putBlob(String container, Blob blob, PutOptions options) {\n      if (options.getBlobAccess() != BlobAccess.PRIVATE) {\n         throw new UnsupportedOperationException(\"B2 only supports private access blobs\");\n      }\n\n      long contentLength = Preconditions.checkNotNull(blob.getMetadata().getContentMetadata().getContentLength(),\n            \"must provide content-length to use multi-part upload\");\n      if (options.isMultipart() && contentLength >= auth.get().recommendedPartSize()) {\n         return putMultipartBlob(container, blob, options);\n      } else {\n         String name = blob.getMetadata().getName();\n\n         // B2 versions all files so we store the original fileId to delete it after the upload succeeds\n         String oldFileId = getFileId(container, name);\n\n         Bucket bucket = getBucket(container);\n         UploadUrlResponse uploadUrl = api.getObjectApi().getUploadUrl(bucket.bucketId());\n         UploadFileResponse uploadFile = api.getObjectApi().uploadFile(uploadUrl, name, null, blob.getMetadata().getUserMetadata(), blob.getPayload());\n\n         if (oldFileId != null) {\n            api.getObjectApi().deleteFileVersion(name, oldFileId);\n         }\n\n         return uploadFile.contentSha1();  // B2 does not support ETag, fake it with SHA-1\n      }\n   }\n\n   @Override\n   public BlobMetadata blobMetadata(String container, String name) {\n      String fileId = getFileId(container, name);\n      if (fileId == null) {\n         return null;\n      }\n\n      B2Object b2Object = api.getObjectApi().getFileInfo(fileId);\n      if (b2Object == null) {\n         return null;\n      }\n\n      return toBlobMetadata(container, b2Object);\n   }\n\n   @Override\n   public Blob getBlob(String container, String name, GetOptions options) {\n      if (options.getIfMatch() != null ||\n            options.getIfNoneMatch() != null ||\n            options.getIfModifiedSince() != null ||\n            options.getIfUnmodifiedSince() != null) {\n         throw new UnsupportedOperationException(\"B2 does not support conditional get\");\n      }\n\n      B2Object b2Object = api.getObjectApi().downloadFileByName(container, name, blob2ObjectGetOptions.apply(options));\n      if (b2Object == null) {\n         return null;\n      }\n\n      MutableBlobMetadata metadata = toBlobMetadata(container, b2Object);\n      Blob blob = new BlobImpl(metadata);\n      blob.setPayload(b2Object.payload());\n      if (b2Object.contentRange() != null) {\n         blob.getAllHeaders().put(HttpHeaders.CONTENT_RANGE, b2Object.contentRange());\n      }\n      return blob;\n   }\n\n   @Override\n   public void removeBlob(String container, String name) {\n      String fileId = getFileId(container, name);\n      if (fileId == null) {\n         return;\n      }\n\n      api.getObjectApi().deleteFileVersion(name, fileId);\n   }\n\n   @Override\n   public BlobAccess getBlobAccess(String container, String name) {\n      return BlobAccess.PRIVATE;\n   }\n\n   @Override\n   public void setBlobAccess(String container, String name, BlobAccess access) {\n      throw new UnsupportedOperationException(\"B2 does not support object access control\");\n   }\n\n   @Override\n   public void deleteContainer(String container) {\n      // Explicitly abort multi-part uploads which B2 requires to delete a bucket but other providers do not.\n      try {\n         for (MultipartUpload upload : listMultipartUploads(container)) {\n            abortMultipartUpload(upload);\n         }\n      } catch (ContainerNotFoundException cnfe) {\n         // ignore\n      }\n\n      super.deleteContainer(container);\n   }\n\n   @Override\n   protected boolean deleteAndVerifyContainerGone(String container) {\n      Bucket bucket = getBucket(container);\n      try {\n         api.getBucketApi().deleteBucket(bucket.bucketId());\n      } catch (B2ResponseException bre) {\n         if (bre.getError().code().equals(\"cannot_delete_non_empty_bucket\")) {\n            return false;\n         }\n         throw bre;\n      }\n      return true;\n   }\n\n   @Override\n   public MultipartUpload initiateMultipartUpload(String container, BlobMetadata blobMetadata, PutOptions options) {\n      Bucket bucket = getBucket(container);\n      MultipartUploadResponse response = api.getMultipartApi().startLargeFile(bucket.bucketId(), blobMetadata.getName(), blobMetadata.getContentMetadata().getContentType(), blobMetadata.getUserMetadata());\n      return MultipartUpload.create(container, blobMetadata.getName(), response.fileId(), blobMetadata, options);\n   }\n\n   @Override\n   public void abortMultipartUpload(MultipartUpload mpu) {\n      api.getMultipartApi().cancelLargeFile(mpu.id());\n   }\n\n   @Override\n   public String completeMultipartUpload(MultipartUpload mpu, List<MultipartPart> parts) {\n      ImmutableList.Builder<String> sha1 = ImmutableList.builder();\n      for (MultipartPart part : parts) {\n         sha1.add(part.partETag());\n      }\n      B2Object b2Object = api.getMultipartApi().finishLargeFile(mpu.id(), sha1.build());\n      return b2Object.contentSha1();  // this is always \"none\"\n   }\n\n   @Override\n   public MultipartPart uploadMultipartPart(MultipartUpload mpu, int partNumber, Payload payload) {\n      GetUploadPartResponse getUploadPart = api.getMultipartApi().getUploadPartUrl(mpu.id());\n      UploadPartResponse uploadPart = api.getMultipartApi().uploadPart(getUploadPart, partNumber, null, payload);\n\n      Date lastModified = null;  // B2 does not return Last-Modified\n      String contentSha1 = uploadPart.contentSha1();\n      if (contentSha1.startsWith(\"unverified:\")) {\n          contentSha1 = contentSha1.substring(\"unverified:\".length());\n      }\n      return MultipartPart.create(uploadPart.partNumber(), uploadPart.contentLength(), contentSha1, lastModified);\n   }\n\n   @Override\n   public List<MultipartPart> listMultipartUpload(MultipartUpload mpu) {\n      ListPartsResponse response = api.getMultipartApi().listParts(mpu.id(), null, null);\n      ImmutableList.Builder<MultipartPart> parts = ImmutableList.builder();\n      for (ListPartsResponse.Entry entry : response.parts()) {\n         parts.add(MultipartPart.create(entry.partNumber(), entry.contentLength(), entry.contentSha1(), entry.uploadTimestamp()));\n      }\n      return parts.build();\n   }\n\n   @Override\n   public List<MultipartUpload> listMultipartUploads(String container) {\n      ImmutableList.Builder<MultipartUpload> builder = ImmutableList.builder();\n      Bucket bucket = getBucket(container);\n\n      String marker = null;\n      while (true) {\n         ListUnfinishedLargeFilesResponse response = api.getMultipartApi().listUnfinishedLargeFiles(bucket.bucketId(), marker, null);\n         for (ListUnfinishedLargeFilesResponse.Entry entry : response.files()) {\n            builder.add(MultipartUpload.create(container, entry.fileName(), entry.fileId(), null, null));\n         }\n\n         if (response.nextFileId() == null || response.files().isEmpty()) {\n            break;\n         }\n      }\n\n      return builder.build();\n   }\n\n   @Override\n   public long getMinimumMultipartPartSize() {\n      return auth.get().absoluteMinimumPartSize();\n   }\n\n   @Override\n   public long getMaximumMultipartPartSize() {\n      return 5L * 1024L * 1024L * 1024L;\n   }\n\n   @Override\n   public int getMaximumNumberOfParts() {\n      return 10 * 1000;\n   }\n\n   private Bucket getBucket(String container) {\n      Bucket bucket;\n      try {\n         bucket = bucketNameToBucket.getUnchecked(container);\n      } catch (UncheckedExecutionException uee) {\n         if (uee.getCause() instanceof ContainerNotFoundException) {\n            throw (ContainerNotFoundException) uee.getCause();\n         }\n         throw uee;\n      }\n      return bucket;\n   }\n\n   private String getFileId(String container, String name) {\n      Bucket bucket = getBucket(container);\n      B2ObjectList list = api.getObjectApi().listFileNames(bucket.bucketId(), name, 1);\n      if (list.files().isEmpty()) {\n         return null;\n      }\n\n      B2ObjectList.Entry entry = list.files().get(0);\n      if (!entry.fileName().equals(name)) {\n         return null;\n      }\n\n      return entry.fileId();\n   }\n\n   private MutableBlobMetadata toBlobMetadata(String container, B2Object b2Object) {\n      MutableBlobMetadata metadata = new MutableBlobMetadataImpl();\n      metadata.setContainer(container);\n      metadata.setETag(b2Object.contentSha1());  // B2 does not support ETag, fake it with SHA-1\n      metadata.setLastModified(b2Object.uploadTimestamp());\n      metadata.setName(b2Object.fileName());\n      metadata.setSize(b2Object.contentLength());\n      MutableContentMetadata contentMetadata = new BaseMutableContentMetadata();\n      contentMetadata.setContentLength(b2Object.contentLength());\n      contentMetadata.setContentType(b2Object.contentType());\n      metadata.setContentMetadata(contentMetadata);\n      metadata.setUserMetadata(b2Object.fileInfo());\n      metadata.setTier(Tier.STANDARD);\n      try {\n         metadata.setPublicUri(URI.create(auth.get().downloadUrl() + \"/file/\" + container + \"/\" +\n               URLEncoder.encode(b2Object.fileName(), \"UTF-8\")));\n      } catch (UnsupportedEncodingException uee) {\n         throw new RuntimeException(uee);\n      }\n      return metadata;\n   }\n}\n"
  },
  {
    "path": "providers/b2/src/main/java/org/jclouds/b2/blobstore/config/B2BlobStoreContextModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2.blobstore.config;\n\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.attr.ConsistencyModel;\nimport org.jclouds.b2.blobstore.B2BlobStore;\n\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Scopes;\n\npublic final class B2BlobStoreContextModule extends AbstractModule {\n   @Override\n   protected void configure() {\n      bind(ConsistencyModel.class).toInstance(ConsistencyModel.EVENTUAL);\n      bind(BlobStore.class).to(B2BlobStore.class).in(Scopes.SINGLETON);\n   }\n}\n"
  },
  {
    "path": "providers/b2/src/main/java/org/jclouds/b2/config/B2HttpApiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2.config;\n\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Constants;\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.b2.B2Api;\nimport org.jclouds.b2.domain.Authorization;\nimport org.jclouds.b2.filters.B2RetryHandler;\nimport org.jclouds.b2.filters.RequestAuthorization;\nimport org.jclouds.b2.handlers.ParseB2ErrorFromJsonContent;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpRetryHandler;\nimport org.jclouds.http.annotation.ClientError;\nimport org.jclouds.http.annotation.Redirection;\nimport org.jclouds.http.annotation.ServerError;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.config.HttpApiModule;\nimport org.jclouds.rest.suppliers.MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier;\n\nimport com.google.common.base.Supplier;\nimport com.google.inject.Provides;\nimport com.google.inject.Scopes;\n\n/** Configures the mappings. Installs the Object and Parser modules. */\n@ConfiguresHttpApi\npublic final class B2HttpApiModule extends HttpApiModule<B2Api> {\n   @Override\n   protected void configure() {\n      super.configure();\n      bind(RequestAuthorization.class).in(Scopes.SINGLETON);\n   }\n\n   @Override\n   protected void bindErrorHandlers() {\n      bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(ParseB2ErrorFromJsonContent.class);\n      bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(ParseB2ErrorFromJsonContent.class);\n      bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(ParseB2ErrorFromJsonContent.class);\n   }\n\n   @Override\n   protected void bindRetryHandlers() {\n      bind(HttpRetryHandler.class).annotatedWith(ServerError.class).to(B2RetryHandler.class);\n   }\n\n   @Provides\n   @Singleton\n   static Supplier<Authorization> provideAuthorizationSupplier(final B2Api b2Api) {\n      return new Supplier<Authorization>() {\n            @Override\n            public Authorization get() {\n               return b2Api.getAuthorizationApi().authorizeAccount();\n            }\n         };\n   }\n\n   @Provides\n   @Singleton\n   @Memoized\n   static Supplier<Authorization> provideAuthorizationCache(\n         AtomicReference<AuthorizationException> authException,\n         @Named(Constants.PROPERTY_SESSION_INTERVAL) long seconds,\n         Supplier<Authorization>  uncached) {\n      return MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier.create(\n            authException, uncached, seconds, TimeUnit.SECONDS);\n   }\n}\n"
  },
  {
    "path": "providers/b2/src/main/java/org/jclouds/b2/domain/Action.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2.domain;\n\nimport com.google.common.base.CaseFormat;\n\npublic enum Action {\n   START,\n   FOLDER,\n   UPLOAD,\n   HIDE;\n\n   public static Action fromValue(String symbol) {\n      return Action.valueOf(CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, symbol));\n   }\n\n   @Override\n   public String toString() {\n      return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, name());\n   }\n}\n"
  },
  {
    "path": "providers/b2/src/main/java/org/jclouds/b2/domain/Authorization.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2.domain;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class Authorization {\n   public abstract String accountId();\n   public abstract String apiUrl();\n   public abstract String authorizationToken();\n   public abstract String downloadUrl();\n   public abstract long absoluteMinimumPartSize();\n   public abstract long recommendedPartSize();\n\n   @SerializedNames({\"accountId\", \"apiUrl\", \"authorizationToken\", \"downloadUrl\", \"absoluteMinimumPartSize\", \"recommendedPartSize\"})\n   public static Authorization create(String accountId, String apiUrl, String authorizationToken, String downloadUrl, long absoluteMinimumPartSize, long recommendedPartSize) {\n      return new AutoValue_Authorization(accountId, apiUrl, authorizationToken, downloadUrl, absoluteMinimumPartSize, recommendedPartSize);\n   }\n}\n"
  },
  {
    "path": "providers/b2/src/main/java/org/jclouds/b2/domain/B2Error.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2.domain;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class B2Error {\n   public abstract String code();\n   public abstract String message();\n   public abstract int status();\n\n   @SerializedNames({ \"code\", \"message\", \"status\" })\n   public static B2Error create(String code, String message, int status) {\n      return new AutoValue_B2Error(code, message, status);\n   }\n}\n"
  },
  {
    "path": "providers/b2/src/main/java/org/jclouds/b2/domain/B2Object.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2.domain;\n\nimport java.util.Date;\nimport java.util.Map;\n\nimport org.jclouds.io.Payload;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableMap;\n\n@AutoValue\npublic abstract class B2Object {\n   public abstract String fileId();\n   public abstract String fileName();\n   @Nullable public abstract String contentSha1();\n   @Nullable public abstract Map<String, String> fileInfo();\n   @Nullable public abstract Payload payload();\n   @Nullable public abstract Date uploadTimestamp();\n   @Nullable public abstract Action action();\n   @Nullable public abstract String accountId();\n   @Nullable public abstract String bucketId();\n   @Nullable public abstract Long contentLength();\n   @Nullable public abstract String contentType();\n   @Nullable public abstract String contentRange();\n\n   @SerializedNames({\"fileId\", \"fileName\", \"accountId\", \"bucketId\", \"contentLength\", \"contentSha1\", \"contentType\", \"fileInfo\", \"action\", \"uploadTimestamp\", \"contentRange\", \"payload\"})\n   public static B2Object create(String fileId, String fileName, @Nullable String accountId, @Nullable String bucketId, @Nullable Long contentLength, @Nullable String contentSha1, @Nullable String contentType, @Nullable Map<String, String> fileInfo, @Nullable Action action, @Nullable Long uploadTimestamp, @Nullable String contentRange, @Nullable Payload payload) {\n      if (fileInfo != null) {\n         fileInfo = ImmutableMap.copyOf(fileInfo);\n      }\n      Date date = uploadTimestamp == null ? null : new Date(uploadTimestamp);\n      return new AutoValue_B2Object(fileId, fileName, contentSha1, fileInfo, payload, date, action, accountId, bucketId, contentLength, contentType, contentRange);\n   }\n}\n"
  },
  {
    "path": "providers/b2/src/main/java/org/jclouds/b2/domain/B2ObjectList.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2.domain;\n\nimport java.util.Date;\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\n\n@AutoValue\npublic abstract class B2ObjectList {\n   public abstract List<Entry> files();\n   @Nullable public abstract String nextFileId();\n   @Nullable public abstract String nextFileName();\n\n   @SerializedNames({\"files\", \"nextFileId\", \"nextFileName\"})\n   public static B2ObjectList create(List<Entry> files, @Nullable String nextFileId, @Nullable String nextFileName) {\n      return new AutoValue_B2ObjectList(ImmutableList.copyOf(files), nextFileId, nextFileName);\n   }\n\n   @AutoValue\n   public abstract static class Entry {\n      public abstract Action action();\n      public abstract String accountId();\n      public abstract String bucketId();\n      @Nullable public abstract String fileId();\n      public abstract String fileName();\n      public abstract long contentLength();\n      @Deprecated\n      public long size() {\n         return contentLength();\n      }\n      public abstract Date uploadTimestamp();\n\n      @SerializedNames({\"action\", \"accountId\", \"bucketId\", \"fileId\", \"fileName\", \"contentLength\", \"uploadTimestamp\"})\n      public static Entry create(Action action, String accountId, String bucketId, @Nullable String fileId, String fileName, long contentLength, long uploadTimestamp) {\n         return new AutoValue_B2ObjectList_Entry(action, accountId, bucketId, fileId, fileName, contentLength, new Date(uploadTimestamp));\n      }\n   }\n}\n"
  },
  {
    "path": "providers/b2/src/main/java/org/jclouds/b2/domain/Bucket.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2.domain;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class Bucket {\n   public abstract String bucketId();\n   public abstract String accountId();\n   public abstract String bucketName();\n   public abstract BucketType bucketType();\n\n   @SerializedNames({\"bucketId\", \"accountId\", \"bucketName\", \"bucketType\"})\n   public static Bucket create(String bucketId, String accountId, String bucketName, BucketType bucketType) {\n      return new AutoValue_Bucket(bucketId, accountId, bucketName, bucketType);\n   }\n}\n"
  },
  {
    "path": "providers/b2/src/main/java/org/jclouds/b2/domain/BucketList.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2.domain;\n\nimport java.util.List;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\n\n@AutoValue\npublic abstract class BucketList {\n   public abstract List<Bucket> buckets();\n\n   @SerializedNames({\"buckets\"})\n   public static BucketList create(List<Bucket> buckets) {\n      return new AutoValue_BucketList(ImmutableList.copyOf(buckets));\n   }\n}\n"
  },
  {
    "path": "providers/b2/src/main/java/org/jclouds/b2/domain/BucketType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2.domain;\n\nimport com.google.common.base.CaseFormat;\n\npublic enum BucketType {\n   ALL_PUBLIC,\n   ALL_PRIVATE,\n   SNAPSHOT;\n\n   public static BucketType fromValue(String symbol) {\n      return BucketType.valueOf(CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, symbol));\n   }\n\n   @Override\n   public String toString() {\n      return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, name());\n   }\n}\n"
  },
  {
    "path": "providers/b2/src/main/java/org/jclouds/b2/domain/DeleteFileResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2.domain;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class DeleteFileResponse {\n   public abstract String fileName();\n   public abstract String fileId();\n\n   @SerializedNames({\"fileName\", \"fileId\"})\n   public static DeleteFileResponse create(String fileName, String fileId) {\n      return new AutoValue_DeleteFileResponse(fileName, fileId);\n   }\n}\n"
  },
  {
    "path": "providers/b2/src/main/java/org/jclouds/b2/domain/GetUploadPartResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2.domain;\n\nimport java.net.URI;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class GetUploadPartResponse {\n   public abstract String fileId();\n   public abstract URI uploadUrl();\n   public abstract String authorizationToken();\n\n   @SerializedNames({\"fileId\", \"uploadUrl\", \"authorizationToken\"})\n   public static GetUploadPartResponse create(String fileId, URI uploadUrl, String authorizationToken) {\n      return new AutoValue_GetUploadPartResponse(fileId, uploadUrl, authorizationToken);\n   }\n}\n"
  },
  {
    "path": "providers/b2/src/main/java/org/jclouds/b2/domain/HideFileResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2.domain;\n\nimport java.util.Date;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class HideFileResponse {\n   /** Always \"hide\". */\n   public abstract Action action();\n   public abstract String accountId();\n   public abstract String bucketId();\n   public abstract String fileId();\n   public abstract String fileName();\n   public abstract Date uploadTimestamp();\n\n   @SerializedNames({\"action\", \"accountId\", \"bucketId\", \"fileId\", \"fileName\", \"uploadTimestamp\"})\n   public static HideFileResponse create(Action action, String accountId, String bucketId, String fileId, String fileName, long uploadTimestamp) {\n      return new AutoValue_HideFileResponse(action, accountId, bucketId, fileId, fileName, new Date(uploadTimestamp));\n   }\n}\n"
  },
  {
    "path": "providers/b2/src/main/java/org/jclouds/b2/domain/ListPartsResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2.domain;\n\nimport java.util.Date;\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\n\n@AutoValue\npublic abstract class ListPartsResponse {\n   @Nullable public abstract Integer nextPartNumber();\n   public abstract List<Entry> parts();\n\n   @SerializedNames({\"nextPartNumber\", \"parts\"})\n   public static ListPartsResponse create(@Nullable Integer nextPartNumber, List<Entry> parts) {\n      return new AutoValue_ListPartsResponse(nextPartNumber, ImmutableList.copyOf(parts));\n   }\n\n   @AutoValue\n   public abstract static class Entry {\n      public abstract long contentLength();\n      public abstract String contentSha1();\n      public abstract String fileId();\n      public abstract int partNumber();\n      public abstract Date uploadTimestamp();\n\n      @SerializedNames({\"contentLength\", \"contentSha1\", \"fileId\", \"partNumber\", \"uploadTimestamp\"})\n      public static Entry create(long contentLength, String contentSha1, String fileId, int partNumber, long uploadTimestamp) {\n         return new AutoValue_ListPartsResponse_Entry(contentLength, contentSha1, fileId, partNumber, new Date(uploadTimestamp));\n      }\n   }\n}\n"
  },
  {
    "path": "providers/b2/src/main/java/org/jclouds/b2/domain/ListUnfinishedLargeFilesResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2.domain;\n\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\n\n@AutoValue\npublic abstract class ListUnfinishedLargeFilesResponse {\n   @Nullable public abstract String nextFileId();\n   public abstract List<Entry> files();\n\n   @SerializedNames({\"nextFileId\", \"files\"})\n   public static ListUnfinishedLargeFilesResponse create(@Nullable String nextFileId, List<Entry> files) {\n      return new AutoValue_ListUnfinishedLargeFilesResponse(nextFileId, ImmutableList.copyOf(files));\n   }\n\n   @AutoValue\n   public abstract static class Entry {\n      public abstract String accountId();\n      /** Always \"upload\". */\n      public abstract Action action();\n      public abstract String bucketId();\n      /** Always null. */\n      @Nullable public abstract Long contentLength();\n      /** Always null. */\n      @Nullable public abstract String contentSha1();\n      public abstract String contentType();\n      public abstract String fileId();\n      public abstract Map<String, String> fileInfo();\n      public abstract String fileName();\n      public abstract Date uploadTimestamp();\n\n      @SerializedNames({\"accountId\", \"action\", \"bucketId\", \"contentLength\", \"contentSha1\", \"contentType\", \"fileId\", \"fileInfo\", \"fileName\", \"uploadTimestamp\"})\n      public static Entry create(String accountId, Action action, String bucketId, @Nullable Long contentLength, @Nullable String contentSha1, String contentType, String fileId, Map<String, String> fileInfo, String fileName, long uploadTimestamp) {\n         return new AutoValue_ListUnfinishedLargeFilesResponse_Entry(accountId, action, bucketId, contentLength, contentSha1, contentType, fileId, ImmutableMap.copyOf(fileInfo), fileName, new Date(uploadTimestamp));\n      }\n   }\n}\n"
  },
  {
    "path": "providers/b2/src/main/java/org/jclouds/b2/domain/MultipartUploadResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2.domain;\n\nimport java.util.Date;\nimport java.util.Map;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableMap;\n\n@AutoValue\npublic abstract class MultipartUploadResponse {\n   /** Always \"upload\". */\n   public abstract Action action();\n   public abstract String accountId();\n   public abstract String bucketId();\n   public abstract String contentType();\n   public abstract String fileId();\n   public abstract Map<String, String> fileInfo();\n   public abstract String fileName();\n   public abstract Date uploadTimestamp();\n\n   @SerializedNames({\"action\", \"accountId\", \"bucketId\", \"contentType\", \"fileId\", \"fileInfo\", \"fileName\", \"uploadTimestamp\"})\n   public static MultipartUploadResponse create(Action action, String accountId, String bucketId, String contentType, String fileId, Map<String, String> fileInfo, String fileName, long uploadTimestamp) {\n      return new AutoValue_MultipartUploadResponse(action, accountId, bucketId, contentType, fileId, ImmutableMap.copyOf(fileInfo), fileName, new Date(uploadTimestamp));\n   }\n}\n"
  },
  {
    "path": "providers/b2/src/main/java/org/jclouds/b2/domain/UploadFileResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2.domain;\n\nimport java.util.Map;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableMap;\n\n@AutoValue\npublic abstract class UploadFileResponse {\n   public abstract String fileId();\n   public abstract String fileName();\n   public abstract String accountId();\n   public abstract String bucketId();\n   public abstract long contentLength();\n   public abstract String contentSha1();\n   public abstract String contentType();\n   public abstract Map<String, String> fileInfo();\n\n   @SerializedNames({\"fileId\", \"fileName\", \"accountId\", \"bucketId\", \"contentLength\", \"contentSha1\", \"contentType\", \"fileInfo\"})\n   public static UploadFileResponse create(String fileId, String fileName, String accountId, String bucketId, long contentLength, String contentSha1, String contentType, Map<String, String> fileInfo) {\n      return new AutoValue_UploadFileResponse(fileId, fileName, accountId, bucketId, contentLength, contentSha1, contentType, ImmutableMap.copyOf(fileInfo));\n   }\n}\n"
  },
  {
    "path": "providers/b2/src/main/java/org/jclouds/b2/domain/UploadPartResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2.domain;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class UploadPartResponse {\n   public abstract long contentLength();\n   public abstract String contentSha1();\n   public abstract String fileId();\n   public abstract int partNumber();\n\n   @SerializedNames({\"contentLength\", \"contentSha1\", \"fileId\", \"partNumber\"})\n   public static UploadPartResponse create(long contentLength, String contentSha1, String fileId, int partNumber) {\n      return new AutoValue_UploadPartResponse(contentLength, contentSha1, fileId, partNumber);\n   }\n}\n"
  },
  {
    "path": "providers/b2/src/main/java/org/jclouds/b2/domain/UploadUrlResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2.domain;\n\nimport java.net.URI;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class UploadUrlResponse {\n   public abstract String bucketId();\n   public abstract URI uploadUrl();\n   public abstract String authorizationToken();\n\n   @SerializedNames({\"bucketId\", \"uploadUrl\", \"authorizationToken\"})\n   public static UploadUrlResponse create(String bucketId, URI uploadUrl, String authorizationToken) {\n      return new AutoValue_UploadUrlResponse(bucketId, uploadUrl, authorizationToken);\n   }\n}\n"
  },
  {
    "path": "providers/b2/src/main/java/org/jclouds/b2/features/AuthorizationApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\n\nimport org.jclouds.http.filters.BasicAuthentication;\nimport org.jclouds.b2.domain.Authorization;\nimport org.jclouds.rest.annotations.RequestFilters;\n\npublic interface AuthorizationApi {\n   @Named(\"b2_authorize_account\")\n   @GET\n   @Path(\"/b2api/v2/b2_authorize_account\")\n   @RequestFilters(BasicAuthentication.class)\n   @Consumes(APPLICATION_JSON)\n   Authorization authorizeAccount();\n}\n"
  },
  {
    "path": "providers/b2/src/main/java/org/jclouds/b2/features/BucketApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport static org.jclouds.blobstore.attr.BlobScopes.CONTAINER;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.Produces;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.blobstore.attr.BlobScope;\nimport org.jclouds.b2.domain.Bucket;\nimport org.jclouds.b2.domain.BucketList;\nimport org.jclouds.b2.domain.BucketType;\nimport org.jclouds.b2.filters.RequestAuthorization;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.PayloadParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\n@RequestFilters(RequestAuthorization.class)\n@BlobScope(CONTAINER)\n@Consumes(APPLICATION_JSON)\n@Produces(APPLICATION_JSON)\npublic interface BucketApi {\n   @Named(\"b2_create_bucket\")\n   @POST\n   @Path(\"/b2api/v2/b2_create_bucket\")\n   @MapBinder(BindToJsonPayload.class)\n   @PayloadParams(keys = {\"accountId\"}, values = {\"{jclouds.identity}\"})\n   Bucket createBucket(@PayloadParam(\"bucketName\") String bucketName, @PayloadParam(\"bucketType\") BucketType bucketType);\n\n   @Named(\"b2_delete_bucket\")\n   @POST\n   @Path(\"/b2api/v2/b2_delete_bucket\")\n   @MapBinder(BindToJsonPayload.class)\n   @PayloadParams(keys = {\"accountId\"}, values = {\"{jclouds.identity}\"})\n   @Fallback(NullOnNotFoundOr404.class)\n   Bucket deleteBucket(@PayloadParam(\"bucketId\") String bucketId);\n\n   @Named(\"b2_update_bucket\")\n   @POST\n   @Path(\"/b2api/v2/b2_update_bucket\")\n   @MapBinder(BindToJsonPayload.class)\n   @PayloadParams(keys = {\"accountId\"}, values = {\"{jclouds.identity}\"})\n   Bucket updateBucket(@PayloadParam(\"bucketId\") String bucketId, @PayloadParam(\"bucketType\") BucketType bucketType);\n\n   @Named(\"b2_list_buckets\")\n   @POST\n   @Path(\"/b2api/v2/b2_list_buckets\")\n   @MapBinder(BindToJsonPayload.class)\n   @PayloadParams(keys = {\"accountId\"}, values = {\"{jclouds.identity}\"})\n   BucketList listBuckets();\n}\n"
  },
  {
    "path": "providers/b2/src/main/java/org/jclouds/b2/features/MultipartApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport static org.jclouds.blobstore.attr.BlobScopes.CONTAINER;\n\nimport java.util.Collection;\nimport java.util.Map;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.HeaderParam;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.Produces;\n\nimport org.jclouds.blobstore.attr.BlobScope;\nimport org.jclouds.io.Payload;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.b2.binders.UploadPartBinder;\nimport org.jclouds.b2.domain.B2Object;\nimport org.jclouds.b2.domain.GetUploadPartResponse;\nimport org.jclouds.b2.domain.ListPartsResponse;\nimport org.jclouds.b2.domain.ListUnfinishedLargeFilesResponse;\nimport org.jclouds.b2.domain.MultipartUploadResponse;\nimport org.jclouds.b2.domain.UploadPartResponse;\nimport org.jclouds.b2.filters.RequestAuthorization;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\n@BlobScope(CONTAINER)\n@Consumes(APPLICATION_JSON)\npublic interface MultipartApi {\n   @Named(\"b2_start_large_file\")\n   @POST\n   @Path(\"/b2api/v2/b2_start_large_file\")\n   @RequestFilters(RequestAuthorization.class)\n   @MapBinder(BindToJsonPayload.class)\n   @Produces(APPLICATION_JSON)\n   MultipartUploadResponse startLargeFile(@PayloadParam(\"bucketId\") String bucketId, @PayloadParam(\"fileName\") String fileName, @PayloadParam(\"contentType\") String contentType, @PayloadParam(\"fileInfo\") Map<String, String> fileInfo);\n\n   @Named(\"b2_cancel_large_file\")\n   @POST\n   @Path(\"/b2api/v2/b2_cancel_large_file\")\n   @RequestFilters(RequestAuthorization.class)\n   @MapBinder(BindToJsonPayload.class)\n   @Produces(APPLICATION_JSON)\n   B2Object cancelLargeFile(@PayloadParam(\"fileId\") String fileId);\n\n   @Named(\"b2_finish_large_file\")\n   @POST\n   @Path(\"/b2api/v2/b2_finish_large_file\")\n   @RequestFilters(RequestAuthorization.class)\n   @MapBinder(BindToJsonPayload.class)\n   @Produces(APPLICATION_JSON)\n   B2Object finishLargeFile(@PayloadParam(\"fileId\") String fileId, @PayloadParam(\"partSha1Array\") Collection<String> contentSha1List);\n\n   @Named(\"b2_get_upload_part_url\")\n   @POST\n   @Path(\"/b2api/v2/b2_get_upload_part_url\")\n   @RequestFilters(RequestAuthorization.class)\n   @MapBinder(BindToJsonPayload.class)\n   @Produces(APPLICATION_JSON)\n   GetUploadPartResponse getUploadPartUrl(@PayloadParam(\"fileId\") String fileId);\n\n   @Named(\"b2_upload_part\")\n   @POST\n   @MapBinder(UploadPartBinder.class)\n   UploadPartResponse uploadPart(@PayloadParam(\"response\") GetUploadPartResponse response, @HeaderParam(\"X-Bz-Part-Number\") int partNumber, @Nullable @PayloadParam(\"contentSha1\") String sha1, @PayloadParam(\"payload\") Payload payload);\n\n   @Named(\"b2_list_parts\")\n   @POST\n   @Path(\"/b2api/v2/b2_list_parts\")\n   @RequestFilters(RequestAuthorization.class)\n   @MapBinder(BindToJsonPayload.class)\n   @Produces(APPLICATION_JSON)\n   ListPartsResponse listParts(@PayloadParam(\"fileId\") String fileId, @PayloadParam(\"startPartNumber\") @Nullable Integer startPartNumber, @PayloadParam(\"maxPartCount\") @Nullable Integer maxPartCount);\n\n   @Named(\"b2_list_unfinished_large_files\")\n   @POST\n   @Path(\"/b2api/v2/b2_list_unfinished_large_files\")\n   @RequestFilters(RequestAuthorization.class)\n   @MapBinder(BindToJsonPayload.class)\n   @Produces(APPLICATION_JSON)\n   ListUnfinishedLargeFilesResponse listUnfinishedLargeFiles(@PayloadParam(\"bucketId\") String bucketId, @PayloadParam(\"startFileId\") @Nullable String startFileId, @PayloadParam(\"maxFileCount\") @Nullable Integer maxFileCount);\n}\n"
  },
  {
    "path": "providers/b2/src/main/java/org/jclouds/b2/features/ObjectApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport static org.jclouds.blobstore.attr.BlobScopes.CONTAINER;\n\nimport java.util.Map;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.QueryParam;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.blobstore.attr.BlobScope;\nimport org.jclouds.http.options.GetOptions;\nimport org.jclouds.io.Payload;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.b2.binders.UploadFileBinder;\nimport org.jclouds.b2.domain.B2Object;\nimport org.jclouds.b2.domain.B2ObjectList;\nimport org.jclouds.b2.domain.DeleteFileResponse;\nimport org.jclouds.b2.domain.HideFileResponse;\nimport org.jclouds.b2.domain.UploadFileResponse;\nimport org.jclouds.b2.domain.UploadUrlResponse;\nimport org.jclouds.b2.filters.RequestAuthorization;\nimport org.jclouds.b2.filters.RequestAuthorizationDownload;\nimport org.jclouds.b2.functions.ParseB2ObjectFromResponse;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\n@BlobScope(CONTAINER)\npublic interface ObjectApi {\n   @Named(\"b2_get_upload_url\")\n   @POST\n   @Path(\"/b2api/v2/b2_get_upload_url\")\n   @RequestFilters(RequestAuthorization.class)\n   @MapBinder(BindToJsonPayload.class)\n   @Consumes(APPLICATION_JSON)\n   @Produces(APPLICATION_JSON)\n   UploadUrlResponse getUploadUrl(@PayloadParam(\"bucketId\") String bucketId);\n\n   @Named(\"b2_upload_file\")\n   @POST\n   @MapBinder(UploadFileBinder.class)\n   @Consumes(APPLICATION_JSON)\n   UploadFileResponse uploadFile(@PayloadParam(\"uploadUrl\") UploadUrlResponse uploadUrl, @PayloadParam(\"fileName\") String fileName, @Nullable @PayloadParam(\"contentSha1\") String contentSha1, @PayloadParam(\"fileInfo\") Map<String, String> fileInfo, Payload payload);\n\n   @Named(\"b2_delete_file_version\")\n   @POST\n   @Path(\"/b2api/v2/b2_delete_file_version\")\n   @MapBinder(BindToJsonPayload.class)\n   @RequestFilters(RequestAuthorization.class)\n   @Consumes(APPLICATION_JSON)\n   @Produces(APPLICATION_JSON)\n   DeleteFileResponse deleteFileVersion(@PayloadParam(\"fileName\") String fileName, @PayloadParam(\"fileId\") String fileId);\n\n   @Named(\"b2_get_file_info\")\n   @POST\n   @Path(\"/b2api/v2/b2_get_file_info\")\n   @MapBinder(BindToJsonPayload.class)\n   @RequestFilters(RequestAuthorization.class)\n   @Consumes(APPLICATION_JSON)\n   @Produces(APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   B2Object getFileInfo(@PayloadParam(\"fileId\") String fileId);\n\n   @Named(\"b2_download_file_by_id\")\n   @GET\n   @Path(\"/b2api/v2/b2_download_file_by_id\")\n   @RequestFilters(RequestAuthorizationDownload.class)\n   @ResponseParser(ParseB2ObjectFromResponse.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   B2Object downloadFileById(@QueryParam(\"fileId\") String fileId);\n\n   @Named(\"b2_download_file_by_id\")\n   @GET\n   @Path(\"/b2api/v2/b2_download_file_by_id\")\n   @RequestFilters(RequestAuthorizationDownload.class)\n   @ResponseParser(ParseB2ObjectFromResponse.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   B2Object downloadFileById(@QueryParam(\"fileId\") String fileId, GetOptions options);\n\n   @Named(\"b2_download_file_by_name\")\n   @GET\n   @Path(\"/file/{bucketName}/{fileName}\")\n   @RequestFilters(RequestAuthorizationDownload.class)\n   @ResponseParser(ParseB2ObjectFromResponse.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   B2Object downloadFileByName(@PathParam(\"bucketName\") String bucketName, @PathParam(\"fileName\") String fileName);\n\n   @Named(\"b2_download_file_by_name\")\n   @GET\n   @Path(\"/file/{bucketName}/{fileName}\")\n   @RequestFilters(RequestAuthorizationDownload.class)\n   @ResponseParser(ParseB2ObjectFromResponse.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   B2Object downloadFileByName(@PathParam(\"bucketName\") String bucketName, @PathParam(\"fileName\") String fileName, GetOptions options);\n\n   @Deprecated\n   @Named(\"b2_list_file_names\")\n   @GET\n   @Path(\"/b2api/v2/b2_list_file_names\")\n   @MapBinder(BindToJsonPayload.class)\n   @RequestFilters(RequestAuthorization.class)\n   @Consumes(APPLICATION_JSON)\n   @Produces(APPLICATION_JSON)\n   B2ObjectList listFileNames(@PayloadParam(\"bucketId\") String bucketId, @PayloadParam(\"startFileName\") @Nullable String startFileName, @PayloadParam(\"maxFileCount\") @Nullable Integer maxFileCount);\n\n   @Named(\"b2_list_file_names\")\n   @GET\n   @Path(\"/b2api/v2/b2_list_file_names\")\n   @MapBinder(BindToJsonPayload.class)\n   @RequestFilters(RequestAuthorization.class)\n   @Consumes(APPLICATION_JSON)\n   @Produces(APPLICATION_JSON)\n   B2ObjectList listFileNames(@PayloadParam(\"bucketId\") String bucketId, @PayloadParam(\"startFileName\") @Nullable String startFileName, @PayloadParam(\"maxFileCount\") @Nullable Integer maxFileCount, @PayloadParam(\"prefix\") @Nullable String prefix, @Nullable @PayloadParam(\"delimiter\") String delimiter);\n\n   @Deprecated\n   @Named(\"b2_list_file_versions\")\n   @GET\n   @Path(\"/b2api/v2/b2_list_file_versions\")\n   @MapBinder(BindToJsonPayload.class)\n   @RequestFilters(RequestAuthorization.class)\n   @Consumes(APPLICATION_JSON)\n   @Produces(APPLICATION_JSON)\n   B2ObjectList listFileVersions(@PayloadParam(\"bucketId\") String bucketId, @PayloadParam(\"startFileId\") @Nullable String startFileId, @PayloadParam(\"startFileName\") @Nullable String startFileName, @PayloadParam(\"maxFileCount\") @Nullable Integer maxFileCount);\n\n   @Named(\"b2_list_file_versions\")\n   @GET\n   @Path(\"/b2api/v2/b2_list_file_versions\")\n   @MapBinder(BindToJsonPayload.class)\n   @RequestFilters(RequestAuthorization.class)\n   @Consumes(APPLICATION_JSON)\n   @Produces(APPLICATION_JSON)\n   B2ObjectList listFileVersions(@PayloadParam(\"bucketId\") String bucketId, @PayloadParam(\"startFileId\") @Nullable String startFileId, @PayloadParam(\"startFileName\") @Nullable String startFileName, @PayloadParam(\"maxFileCount\") @Nullable Integer maxFileCount, @PayloadParam(\"prefix\") @Nullable String prefix, @PayloadParam(\"delimiter\") @Nullable String delimiter);\n\n   @Named(\"b2_hide_file\")\n   @POST\n   @Path(\"/b2api/v2/b2_hide_file\")\n   @MapBinder(BindToJsonPayload.class)\n   @RequestFilters(RequestAuthorization.class)\n   @Consumes(APPLICATION_JSON)\n   @Produces(APPLICATION_JSON)\n   HideFileResponse hideFile(@PayloadParam(\"bucketId\") String bucketId, @PayloadParam(\"fileName\") String fileName);\n}\n"
  },
  {
    "path": "providers/b2/src/main/java/org/jclouds/b2/filters/B2RetryHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2.filters;\n\nimport static org.jclouds.http.HttpUtils.closeClientButKeepContentStream;\nimport static org.jclouds.http.HttpUtils.releasePayload;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\n\nimport org.jclouds.b2.B2Api;\nimport org.jclouds.b2.domain.GetUploadPartResponse;\nimport org.jclouds.b2.domain.UploadUrlResponse;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpRequestFilter;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.handlers.BackoffLimitedRetryHandler;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.net.HttpHeaders;\nimport com.google.inject.Singleton;\n\n@Singleton\npublic final class B2RetryHandler extends BackoffLimitedRetryHandler implements HttpRequestFilter {\n   private final B2Api api;\n\n   @Resource\n   private Logger logger = Logger.NULL;\n\n   @Inject\n   B2RetryHandler(B2Api api) {\n      this.api = api;\n   }\n\n   @Override\n   public HttpRequest filter(HttpRequest request) throws HttpException {\n      HttpRequest.Builder<?> builder = request.toBuilder();\n\n      // B2 requires retrying on a different storage node for uploads\n      String path = request.getEndpoint().getPath();\n      if (path.startsWith(\"/b2api/v2/b2_upload_file\")) {\n         String bucketId = path.split(\"/\")[4];\n         UploadUrlResponse uploadUrl = api.getObjectApi().getUploadUrl(bucketId);\n         builder.endpoint(uploadUrl.uploadUrl())\n               .replaceHeader(HttpHeaders.AUTHORIZATION, uploadUrl.authorizationToken());\n      } else if (path.startsWith(\"/b2api/v2/b2_upload_part\")) {\n         String fileId = path.split(\"/\")[4];\n         GetUploadPartResponse uploadUrl = api.getMultipartApi().getUploadPartUrl(fileId);\n         builder.endpoint(uploadUrl.uploadUrl())\n               .replaceHeader(HttpHeaders.AUTHORIZATION, uploadUrl.authorizationToken());\n      }\n\n      return builder.build();\n   }\n\n   @Override\n   public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) {\n      boolean retry = false;\n      try {\n         byte[] data = closeClientButKeepContentStream(response);\n         switch (response.getStatusCode()) {\n         case 500:\n         case 503:\n            retry = super.shouldRetryRequest(command, response);\n            break;\n         default:\n            break;\n         }\n      } finally {\n         releasePayload(response);\n      }\n      return retry;\n   }\n}\n"
  },
  {
    "path": "providers/b2/src/main/java/org/jclouds/b2/filters/RequestAuthorization.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2.filters;\n\nimport java.net.URI;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpRequestFilter;\nimport org.jclouds.b2.domain.Authorization;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.net.HttpHeaders;\n\n@Singleton\npublic final class RequestAuthorization implements HttpRequestFilter {\n   private final Supplier<Authorization> auth;\n\n   @Inject\n   RequestAuthorization(@Memoized Supplier<Authorization> auth) {\n      this.auth = auth;\n   }\n\n   @Override\n   public HttpRequest filter(HttpRequest request) throws HttpException {\n      Authorization auth = this.auth.get();\n\n      // Replace with API URL\n      URI endpoint = request.getEndpoint();\n      endpoint = URI.create(auth.apiUrl() +\n            (endpoint.getPort() == -1 ? \"\" : \":\" + endpoint.getPort()) +\n            endpoint.getPath() +\n            (endpoint.getQuery() == null ? \"\" : \"?\" + endpoint.getQuery()));\n\n      String updatedRequestBody = request.getPayload().getRawContent().toString().replaceAll(\"\\\"accountId\\\":.?\\\".*\\\"\", \"\\\"accountId\\\":\\\"\" + auth.accountId() + \"\\\"\");\n      request = request.toBuilder()\n            .endpoint(endpoint)\n            .replaceHeader(HttpHeaders.AUTHORIZATION, auth.authorizationToken())\n            .payload(updatedRequestBody)\n            .build();\n      return request;\n   }\n}\n"
  },
  {
    "path": "providers/b2/src/main/java/org/jclouds/b2/filters/RequestAuthorizationDownload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2.filters;\n\nimport java.net.URI;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpRequestFilter;\nimport org.jclouds.b2.domain.Authorization;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.net.HttpHeaders;\n\n@Singleton\npublic final class RequestAuthorizationDownload implements HttpRequestFilter {\n   private final Supplier<Authorization> auth;\n\n   @Inject\n   RequestAuthorizationDownload(@Memoized Supplier<Authorization> auth) {\n      this.auth = auth;\n   }\n\n   @Override\n   public HttpRequest filter(HttpRequest request) throws HttpException {\n      Authorization auth = this.auth.get();\n\n      // Replace with download URL\n      URI endpoint = request.getEndpoint();\n      endpoint = URI.create(auth.downloadUrl() +\n            (endpoint.getPort() == -1 ? \"\" : \":\" + endpoint.getPort()) +\n            endpoint.getRawPath() +\n            (endpoint.getQuery() == null ? \"\" : \"?\" + endpoint.getQuery()));\n\n      request = request.toBuilder()\n            .endpoint(endpoint)\n            .replaceHeader(HttpHeaders.AUTHORIZATION, auth.authorizationToken())\n            .build();\n      return request;\n   }\n}\n"
  },
  {
    "path": "providers/b2/src/main/java/org/jclouds/b2/functions/ParseB2ObjectFromResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2.functions;\n\nimport java.io.UnsupportedEncodingException;\nimport java.net.URLDecoder;\nimport java.util.Date;\nimport java.util.Map;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.io.MutableContentMetadata;\nimport org.jclouds.io.Payload;\nimport org.jclouds.b2.domain.B2Object;\nimport org.jclouds.b2.reference.B2Headers;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Throwables;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.net.HttpHeaders;\n\npublic final class ParseB2ObjectFromResponse implements Function<HttpResponse, B2Object> {\n   @Override\n   public B2Object apply(HttpResponse from) {\n      Payload payload = from.getPayload();\n      MutableContentMetadata contentMeta = payload.getContentMetadata();\n\n      String fileId = from.getFirstHeaderOrNull(B2Headers.FILE_ID);\n      String fileName;\n      try {\n         fileName = URLDecoder.decode(from.getFirstHeaderOrNull(B2Headers.FILE_NAME), \"UTF-8\");\n      } catch (UnsupportedEncodingException uee) {\n         throw Throwables.propagate(uee);\n      }\n      String contentSha1 = from.getFirstHeaderOrNull(B2Headers.CONTENT_SHA1);\n      ImmutableMap.Builder<String, String> fileInfo = ImmutableMap.builder();\n      for (Map.Entry<String, String> entry : from.getHeaders().entries()) {\n         if (entry.getKey().regionMatches(true, 0, B2Headers.FILE_INFO_PREFIX, 0, B2Headers.FILE_INFO_PREFIX.length())) {\n            String value;\n            try {\n               value = URLDecoder.decode(entry.getValue(), \"UTF-8\");\n            } catch (UnsupportedEncodingException uee) {\n               throw Throwables.propagate(uee);\n            }\n            fileInfo.put(entry.getKey().substring(B2Headers.FILE_INFO_PREFIX.length()), value);\n         }\n      }\n      Date uploadTimestamp = new Date(Long.parseLong(from.getFirstHeaderOrNull(B2Headers.UPLOAD_TIMESTAMP)));\n      String contentRange = from.getFirstHeaderOrNull(HttpHeaders.CONTENT_RANGE);\n\n      return B2Object.create(fileId, fileName, null, null, contentMeta.getContentLength(), contentSha1, contentMeta.getContentType(), fileInfo.build(), null, uploadTimestamp.getTime(), contentRange, payload);\n   }\n}\n"
  },
  {
    "path": "providers/b2/src/main/java/org/jclouds/b2/handlers/ParseB2ErrorFromJsonContent.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2.handlers;\n\nimport org.jclouds.blobstore.ContainerNotFoundException;\nimport org.jclouds.blobstore.KeyNotFoundException;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\nimport org.jclouds.b2.B2ResponseException;\nimport org.jclouds.b2.domain.B2Error;\nimport org.jclouds.rest.ResourceNotFoundException;\n\nimport com.google.inject.Inject;\nimport com.google.inject.TypeLiteral;\n\npublic final class ParseB2ErrorFromJsonContent extends ParseJson<B2Error> implements HttpErrorHandler {\n   @Inject\n   ParseB2ErrorFromJsonContent(Json json) {\n      super(json, TypeLiteral.get(B2Error.class));\n   }\n\n   private static Exception refineException(B2Error error, Exception exception) {\n      if (\"bad_bucket_id\".equals(error.code())) {\n         return new ContainerNotFoundException(exception);\n      } else if (\"bad_json\".equals(error.code())) {\n         return new IllegalArgumentException(error.message(), exception);\n      } else if (\"bad_request\".equals(error.code())) {\n         return new IllegalArgumentException(error.message(), exception);\n      } else if (\"file_not_present\".equals(error.code())) {\n         return new KeyNotFoundException(exception);\n      } else if (\"not_found\".equals(error.code())) {\n         return new ResourceNotFoundException(error.message(), exception);\n      } else {\n         return exception;\n      }\n   }\n\n   @Override\n   public void handleError(HttpCommand command, HttpResponse response) {\n      B2Error error = this.apply(response);\n      Exception exception = refineException(error, new B2ResponseException(command, response, error));\n      command.setException(exception);\n   }\n}\n"
  },
  {
    "path": "providers/b2/src/main/java/org/jclouds/b2/reference/B2Headers.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2.reference;\n\npublic final class B2Headers {\n   public static final String CONTENT_SHA1 = \"X-Bz-Content-Sha1\";\n   public static final String FILE_ID = \"X-Bz-File-Id\";\n   public static final String FILE_NAME = \"X-Bz-File-Name\";\n   public static final String UPLOAD_TIMESTAMP = \"X-Bz-Upload-Timestamp\";\n   /**\n    * Recommended user metadata for last-modified.  The value should be a base 10 number which represents a UTC time\n    * when the original source file was last modified. It is a base 10 number of milliseconds since midnight, January\n    * 1, 1970 UTC.\n    */\n   public static final String LAST_MODIFIED = \"X-Bz-Info-src_last_modified_millis\";\n\n   public static final String FILE_INFO_PREFIX = \"X-Bz-Info-\";\n\n   private B2Headers() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "providers/b2/src/test/java/org/jclouds/b2/B2ProviderMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2;\n\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"B2ProviderMetadataTest\")\npublic final class B2ProviderMetadataTest extends BaseProviderMetadataTest {\n   public B2ProviderMetadataTest() {\n      super(new B2ProviderMetadata(), new B2ApiMetadata());\n   }\n}\n"
  },
  {
    "path": "providers/b2/src/test/java/org/jclouds/b2/blobstore/integration/B2BlobIntegrationLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2.blobstore.integration;\n\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown;\n\nimport java.io.IOException;\nimport java.util.concurrent.ExecutionException;\n\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.BlobMetadata;\nimport org.jclouds.blobstore.domain.BlobBuilder.PayloadBlobBuilder;\nimport org.jclouds.blobstore.domain.Tier;\nimport org.jclouds.blobstore.integration.internal.BaseBlobIntegrationTest;\nimport org.testng.SkipException;\nimport org.testng.annotations.Test;\n\n@Test(groups = { \"live\", \"blobstorelive\" })\npublic final class B2BlobIntegrationLiveTest extends BaseBlobIntegrationTest {\n   public B2BlobIntegrationLiveTest() throws IOException {\n      provider = \"b2\";\n   }\n\n   @Override\n   protected long getMinimumMultipartBlobSize() {\n      return view.getBlobStore().getMinimumMultipartPartSize() + 1;\n   }\n\n   @Override\n   protected void addContentMetadata(PayloadBlobBuilder blobBuilder) {\n      blobBuilder.contentType(\"text/csv\");\n      // B2 does not support the following:\n      //blobBuilder.contentDisposition(\"attachment; filename=photo.jpg\");\n      //blobBuilder.contentEncoding(\"gzip\");\n      //blobBuilder.contentLanguage(\"en\");\n   }\n\n   @Override\n   protected void checkContentMetadata(Blob blob) {\n      checkContentType(blob, \"text/csv\");\n      // B2 does not support the following:\n      //checkContentDisposition(blob, \"attachment; filename=photo.jpg\");\n      //checkContentEncoding(blob, \"gzip\");\n      //checkContentLanguage(blob, \"en\");\n   }\n\n   @Override\n   protected void checkMD5(BlobMetadata metadata) throws IOException {\n      // B2 does not support Content-MD5\n   }\n\n   @Override\n   public void testCopyBlobReplaceMetadata() throws Exception {\n      try {\n         super.testCopyBlobReplaceMetadata();\n         failBecauseExceptionWasNotThrown(IllegalArgumentException.class);\n      } catch (IllegalArgumentException iae) {\n         throw new SkipException(\"B2 does not support the Cache-Control header\", iae);\n      }\n   }\n\n   @Override\n   public void testPutObjectStream() throws InterruptedException, IOException, ExecutionException {\n      throw new SkipException(\"B2 requires a Content-Length\");\n   }\n\n   @Override\n   public void testPutIncorrectContentMD5ByteSource() throws InterruptedException, IOException {\n      try {\n         super.testPutIncorrectContentMD5ByteSource();\n         failBecauseExceptionWasNotThrown(AssertionError.class);\n      } catch (AssertionError ae) {\n         throw new SkipException(\"B2 does not enforce Content-MD5\", ae);\n      }\n   }\n\n   @Override\n   public void testPutIncorrectContentMD5InputStream() throws InterruptedException, IOException {\n      try {\n         super.testPutIncorrectContentMD5InputStream();\n         failBecauseExceptionWasNotThrown(AssertionError.class);\n      } catch (AssertionError ae) {\n         throw new SkipException(\"B2 does not enforce Content-MD5\", ae);\n      }\n   }\n\n   @Override\n   public void testCreateBlobWithExpiry() throws InterruptedException {\n      try {\n         super.testCreateBlobWithExpiry();\n         failBecauseExceptionWasNotThrown(IllegalArgumentException.class);\n      } catch (IllegalArgumentException iae) {\n         throw new SkipException(\"B2 does not allow Expires header\", iae);\n      }\n   }\n\n   @Override\n   public void testSetBlobAccess() throws Exception {\n      try {\n         super.testSetBlobAccess();\n         failBecauseExceptionWasNotThrown(UnsupportedOperationException.class);\n      } catch (UnsupportedOperationException uoe) {\n         throw new SkipException(\"not supported on B2\", uoe);\n      }\n   }\n\n   @Override\n   public void testPutBlobAccess() throws Exception {\n      try {\n         super.testPutBlobAccess();\n         failBecauseExceptionWasNotThrown(UnsupportedOperationException.class);\n      } catch (UnsupportedOperationException uoe) {\n         throw new SkipException(\"not supported on B2\", uoe);\n      }\n   }\n\n   @Override\n   public void testPutBlobAccessMultipart() throws Exception {\n      try {\n         super.testPutBlobAccessMultipart();\n         failBecauseExceptionWasNotThrown(UnsupportedOperationException.class);\n      } catch (UnsupportedOperationException uoe) {\n         throw new SkipException(\"not supported on B2\", uoe);\n      }\n   }\n\n   @Override\n   public void testGetIfModifiedSince() throws InterruptedException {\n      try {\n         super.testGetIfModifiedSince();\n         failBecauseExceptionWasNotThrown(UnsupportedOperationException.class);\n      } catch (UnsupportedOperationException uoe) {\n         throw new SkipException(\"not supported on B2\", uoe);\n      }\n   }\n\n   @Override\n   public void testGetIfUnmodifiedSince() throws InterruptedException {\n      try {\n         super.testGetIfUnmodifiedSince();\n         failBecauseExceptionWasNotThrown(UnsupportedOperationException.class);\n      } catch (UnsupportedOperationException uoe) {\n         throw new SkipException(\"not supported on B2\", uoe);\n      }\n   }\n\n   @Override\n   public void testGetIfMatch() throws InterruptedException {\n      try {\n         super.testGetIfMatch();\n         failBecauseExceptionWasNotThrown(UnsupportedOperationException.class);\n      } catch (UnsupportedOperationException uoe) {\n         throw new SkipException(\"not supported on B2\", uoe);\n      }\n   }\n\n   @Override\n   public void testGetIfNoneMatch() throws InterruptedException {\n      try {\n         super.testGetIfNoneMatch();\n         failBecauseExceptionWasNotThrown(UnsupportedOperationException.class);\n      } catch (UnsupportedOperationException uoe) {\n         throw new SkipException(\"not supported on B2\", uoe);\n      }\n   }\n\n   @Override\n   public void testGetRangeOutOfRange() throws InterruptedException, IOException {\n      try {\n         super.testGetRangeOutOfRange();\n         failBecauseExceptionWasNotThrown(AssertionError.class);\n      } catch (AssertionError ae) {\n         throw new SkipException(\"B2 does not error on invalid ranges\", ae);\n      }\n   }\n\n   @Override\n   public void testMultipartUploadSinglePart() throws Exception {\n      try {\n         super.testMultipartUploadSinglePart();\n         failBecauseExceptionWasNotThrown(IllegalArgumentException.class);\n      } catch (IllegalArgumentException iae) {\n         throw new SkipException(\"B2 requires at least two parts\", iae);\n      }\n   }\n\n   @Override\n   protected void checkTier(BlobMetadata metadata, Tier expected) {\n      // B2 maps all tiers to STANDARD\n      assertThat(metadata.getTier()).isEqualTo(Tier.STANDARD);\n   }\n}\n"
  },
  {
    "path": "providers/b2/src/test/java/org/jclouds/b2/blobstore/integration/B2BlobLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2.blobstore.integration;\n\nimport static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown;\n\nimport org.jclouds.blobstore.integration.internal.BaseBlobLiveTest;\n\nimport org.testng.SkipException;\nimport org.testng.annotations.Optional;\nimport org.testng.annotations.Test;\n\n@Test(groups = { \"live\" })\npublic final class B2BlobLiveTest extends BaseBlobLiveTest {\n   public B2BlobLiveTest() {\n      provider = \"b2\";\n   }\n\n   @Override\n   public void testCopyUrl(@Optional String httpStreamUrl, @Optional String httpStreamMD5) throws Exception {\n      try {\n         super.testCopyUrl(httpStreamUrl, httpStreamMD5);\n         failBecauseExceptionWasNotThrown(IllegalArgumentException.class);\n      } catch (IllegalArgumentException iae) {\n         throw new SkipException(\"B2 requires repeatable payloads to calculate SHA1 hash\", iae);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/b2/src/test/java/org/jclouds/b2/blobstore/integration/B2BlobSignerLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2.blobstore.integration;\n\nimport static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown;\n\nimport java.io.IOException;\n\nimport org.jclouds.blobstore.integration.internal.BaseBlobSignerLiveTest;\nimport org.testng.SkipException;\nimport org.testng.annotations.Test;\n\n@Test(groups = { \"live\" })\npublic final class B2BlobSignerLiveTest extends BaseBlobSignerLiveTest {\n   public B2BlobSignerLiveTest() {\n      provider = \"b2\";\n   }\n\n   @Test\n   public void testSignGetUrl() throws Exception {\n      try {\n         super.testSignGetUrl();\n         failBecauseExceptionWasNotThrown(UnsupportedOperationException.class);\n      } catch (UnsupportedOperationException uoe) {\n         throw new SkipException(\"unsupported by B2\", uoe);\n      }\n   }\n\n   @Test\n   public void testSignGetUrlOptions() throws Exception {\n      try {\n         super.testSignGetUrlOptions();\n         failBecauseExceptionWasNotThrown(UnsupportedOperationException.class);\n      } catch (UnsupportedOperationException uoe) {\n         throw new SkipException(\"unsupported by B2\", uoe);\n      }\n   }\n\n   @Test\n   public void testSignGetUrlWithTime() throws InterruptedException, IOException {\n      try {\n         super.testSignGetUrlWithTime();\n         failBecauseExceptionWasNotThrown(UnsupportedOperationException.class);\n      } catch (UnsupportedOperationException uoe) {\n         throw new SkipException(\"unsupported by B2\", uoe);\n      }\n   }\n\n   @Test\n   public void testSignGetUrlWithTimeExpired() throws InterruptedException, IOException {\n      try {\n         super.testSignGetUrlWithTimeExpired();\n         failBecauseExceptionWasNotThrown(UnsupportedOperationException.class);\n      } catch (UnsupportedOperationException uoe) {\n         throw new SkipException(\"unsupported by B2\", uoe);\n      }\n   }\n\n   @Test\n   public void testSignPutUrl() throws Exception {\n      try {\n         super.testSignPutUrl();\n         failBecauseExceptionWasNotThrown(UnsupportedOperationException.class);\n      } catch (UnsupportedOperationException uoe) {\n         throw new SkipException(\"unsupported by B2\", uoe);\n      }\n   }\n\n   @Test\n   public void testSignPutUrlWithTime() throws Exception {\n      try {\n         super.testSignPutUrlWithTime();\n         failBecauseExceptionWasNotThrown(UnsupportedOperationException.class);\n      } catch (UnsupportedOperationException uoe) {\n         throw new SkipException(\"unsupported by B2\", uoe);\n      }\n   }\n\n   @Test\n   public void testSignPutUrlWithTimeExpired() throws Exception {\n      try {\n         super.testSignPutUrlWithTimeExpired();\n         failBecauseExceptionWasNotThrown(UnsupportedOperationException.class);\n      } catch (UnsupportedOperationException uoe) {\n         throw new SkipException(\"unsupported by B2\", uoe);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/b2/src/test/java/org/jclouds/b2/blobstore/integration/B2ContainerIntegrationLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2.blobstore.integration;\n\nimport static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown;\n\nimport java.io.IOException;\n\nimport org.jclouds.blobstore.domain.BlobMetadata;\nimport org.jclouds.blobstore.integration.internal.BaseContainerIntegrationTest;\nimport org.testng.SkipException;\nimport org.testng.annotations.DataProvider;\n\nimport com.google.common.collect.ImmutableSet;\n\npublic final class B2ContainerIntegrationLiveTest extends BaseContainerIntegrationTest {\n   public B2ContainerIntegrationLiveTest() {\n      provider = \"b2\";\n   }\n\n   @Override\n   public void testListMarkerAfterLastKey() throws Exception {\n      try {\n         super.testListMarkerAfterLastKey();\n         failBecauseExceptionWasNotThrown(AssertionError.class);\n      } catch (AssertionError ae) {\n         throw new SkipException(\"B2 uses the marker as the current key, not the next key\", ae);\n      }\n   }\n\n   @Override\n   public void testListContainerWithZeroMaxResults() throws Exception {\n      try {\n         super.testListContainerWithZeroMaxResults();\n         failBecauseExceptionWasNotThrown(AssertionError.class);\n      } catch (AssertionError ae) {\n         throw new SkipException(\"B2 does not enforce zero max results\", ae);\n      }\n   }\n\n   @Override\n   public void testDirectory() throws InterruptedException {\n      throw new SkipException(\"B2 does not support directories\");\n   }\n\n   @Override\n   public void testSetContainerAccess() throws Exception {\n      try {\n         super.testSetContainerAccess();\n         failBecauseExceptionWasNotThrown(UnsupportedOperationException.class);\n      } catch (UnsupportedOperationException uoe) {\n         throw new SkipException(\"Test uses blob signer which B2 does not support\", uoe);\n      }\n   }\n\n   @Override\n   protected void checkMD5(BlobMetadata metadata) throws IOException {\n      // B2 does not support Content-MD5\n   }\n\n   // B2 does not support \" \" file name\n   @DataProvider\n   @Override\n   public Object[][] getBlobsToEscape() {\n      ImmutableSet<String> testNames = ImmutableSet.of(\"%20\", \"%20 \", \" %20\");\n      Object[][] result = new Object[1][1];\n      result[0][0] = testNames;\n      return result;\n   }\n}\n"
  },
  {
    "path": "providers/b2/src/test/java/org/jclouds/b2/blobstore/integration/B2ContainerLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2.blobstore.integration;\n\nimport org.jclouds.blobstore.integration.internal.BaseContainerLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = { \"live\" })\npublic final class B2ContainerLiveTest extends BaseContainerLiveTest {\n   public B2ContainerLiveTest() {\n      provider = \"b2\";\n   }\n}\n"
  },
  {
    "path": "providers/b2/src/test/java/org/jclouds/b2/features/B2TestUtils.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2.features;\n\nimport static org.assertj.core.api.Assertions.assertThat;\n\nimport java.io.IOException;\nimport java.net.URL;\nimport java.util.Set;\nimport java.util.Properties;\n\nimport okhttp3.mockwebserver.MockWebServer;\nimport okhttp3.mockwebserver.RecordedRequest;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.concurrent.config.ExecutorServiceModule;\nimport org.jclouds.b2.B2Api;\nimport org.jclouds.util.Strings2;\n\nimport com.google.common.base.Throwables;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.util.concurrent.MoreExecutors;\nimport com.google.gson.JsonElement;\nimport com.google.gson.JsonParser;\nimport com.google.inject.Module;\n\n\nfinal class B2TestUtils {\n   static B2Api api(String uri, String provider, Properties overrides) {\n       Set<Module> modules = ImmutableSet.<Module> of(\n             new ExecutorServiceModule(MoreExecutors.newDirectExecutorService()));\n\n      return ContextBuilder.newBuilder(provider)\n            .credentials(\"ACCOUNT_ID\", \"APPLICATION_KEY\")\n            .endpoint(uri)\n            .overrides(overrides)\n            .modules(modules)\n            .buildApi(B2Api.class);\n   }\n\n   static B2Api api(String uri, String provider) {\n      return api(uri, provider, new Properties());\n   }\n\n   static MockWebServer createMockWebServer() throws IOException {\n      MockWebServer server = new MockWebServer();\n      server.start();\n      URL url = server.url(\"\").url();\n      return server;\n   }\n\n   static void assertAuthentication(MockWebServer server) {\n      assertThat(server.getRequestCount()).isGreaterThanOrEqualTo(1);\n      try {\n         assertThat(server.takeRequest().getRequestLine()).isEqualTo(\"GET /b2api/v2/b2_authorize_account HTTP/1.1\");\n      } catch (InterruptedException e) {\n         throw Throwables.propagate(e);\n      }\n   }\n\n   /**\n    * Ensures the request has a json header for the proper REST methods.\n    *\n    * @param request\n    * @param method\n    *           The request method (such as GET).\n    * @param path\n    *           The path requested for this REST call.\n    * @see RecordedRequest\n    */\n   static void assertRequest(RecordedRequest request, String method, String path) {\n      assertThat(request.getMethod()).isEqualTo(method);\n      assertThat(request.getPath()).isEqualTo(path);\n   }\n\n   /**\n    * Ensures the request is json and has the same contents as the resource\n    * file provided.\n    *\n    * @param request\n    * @param method\n    *           The request method (such as GET).\n    * @param resourceLocation\n    *           The location of the resource file. Contents will be compared to\n    *           the request body as JSON.\n    * @see RecordedRequest\n    */\n   static void assertRequest(RecordedRequest request, String method, String path, String resourceLocation) {\n      assertRequest(request, method, path);\n      assertContentTypeIsJson(request);\n      JsonParser parser = new JsonParser();\n      JsonElement requestJson;\n      try {\n         requestJson = parser.parse(request.getBody().readUtf8());\n      } catch (Exception e) {\n         throw Throwables.propagate(e);\n      }\n      JsonElement resourceJson = parser.parse(stringFromResource(resourceLocation));\n      assertThat(requestJson).isEqualTo(resourceJson);\n   }\n\n   /**\n    * Ensures the request has a json header.\n    *\n    * @param request\n    * @see RecordedRequest\n    */\n   private static void assertContentTypeIsJson(RecordedRequest request) {\n      assertThat(request.getHeaders().values(\"Content-Type\")).contains(\"application/unknown\");\n   }\n\n   /**\n    * Get a string from a resource\n    *\n    * @param resourceName\n    *           The name of the resource.\n    * @return The content of the resource\n    */\n   static String stringFromResource(String resourceName) {\n      try {\n         return Strings2.toStringAndClose(BucketApiMockTest.class.getResourceAsStream(resourceName));\n      } catch (IOException e) {\n         throw Throwables.propagate(e);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/b2/src/test/java/org/jclouds/b2/features/BucketApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2.features;\n\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown;\n\nimport java.util.Random;\n\nimport org.jclouds.b2.domain.Bucket;\nimport org.jclouds.b2.domain.BucketList;\nimport org.jclouds.b2.domain.BucketType;\nimport org.jclouds.b2.internal.BaseB2ApiLiveTest;\nimport org.testng.annotations.Test;\n\npublic final class BucketApiLiveTest extends BaseB2ApiLiveTest {\n   private static final String BUCKET_NAME = \"jcloudstestbucket\" + new Random().nextInt(Integer.MAX_VALUE);\n\n   @Test(groups = \"live\")\n   public void testCreateBucket() {\n      BucketApi bucketApi = api.getBucketApi();\n\n      Bucket response = bucketApi.createBucket(BUCKET_NAME, BucketType.ALL_PRIVATE);\n      try {\n         assertThat(response.bucketName()).isEqualTo(BUCKET_NAME);\n         assertThat(response.bucketType()).isEqualTo(BucketType.ALL_PRIVATE);\n      } finally {\n         response = bucketApi.deleteBucket(response.bucketId());\n         assertThat(response.bucketName()).isEqualTo(BUCKET_NAME);\n         assertThat(response.bucketType()).isEqualTo(BucketType.ALL_PRIVATE);\n      }\n   }\n\n   @Test(groups = \"live\")\n   public void testDeleteAlreadyDeletedBucket() {\n      BucketApi bucketApi = api.getBucketApi();\n\n      Bucket response = bucketApi.createBucket(BUCKET_NAME, BucketType.ALL_PRIVATE);\n      response = bucketApi.deleteBucket(response.bucketId());\n\n      response = bucketApi.deleteBucket(response.bucketId());\n      assertThat(response).isNull();\n   }\n\n   @Test(groups = \"live\")\n   public void testDeleteInvalidBucketId() {\n      BucketApi bucketApi = api.getBucketApi();\n\n      try {\n         bucketApi.deleteBucket(\"4a48fe8875c6214145260818\");\n         failBecauseExceptionWasNotThrown(IllegalArgumentException.class);\n      } catch (IllegalArgumentException iae) {\n         assertThat(iae.getMessage()).isEqualTo(\"bucketId not valid for account\");\n      }\n   }\n\n   @Test(groups = \"live\")\n   public void testUpdateBucket() {\n      BucketApi bucketApi = api.getBucketApi();\n\n      Bucket response = bucketApi.createBucket(BUCKET_NAME, BucketType.ALL_PRIVATE);\n      try {\n         response = bucketApi.updateBucket(response.bucketId(), BucketType.ALL_PUBLIC);\n         assertThat(response.bucketName()).isEqualTo(BUCKET_NAME);\n         assertThat(response.bucketType()).isEqualTo(BucketType.ALL_PUBLIC);\n      } finally {\n         response = bucketApi.deleteBucket(response.bucketId());\n         assertThat(response.bucketName()).isEqualTo(BUCKET_NAME);\n      }\n   }\n\n   @Test(groups = \"live\")\n   public void testListBuckets() {\n      BucketApi bucketApi = api.getBucketApi();\n\n      Bucket response = bucketApi.createBucket(BUCKET_NAME, BucketType.ALL_PRIVATE);\n      try {\n         boolean found = false;\n         BucketList buckets = bucketApi.listBuckets();\n         for (Bucket bucket : buckets.buckets()) {\n            if (bucket.bucketName().equals(BUCKET_NAME)) {\n               assertThat(response.bucketType()).isEqualTo(BucketType.ALL_PRIVATE);\n               found = true;\n            }\n         }\n         assertThat(found).isTrue();\n      } finally {\n         response = bucketApi.deleteBucket(response.bucketId());\n         assertThat(response.bucketName()).isEqualTo(BUCKET_NAME);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/b2/src/test/java/org/jclouds/b2/features/BucketApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2.features;\n\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.jclouds.b2.features.B2TestUtils.api;\nimport static org.jclouds.b2.features.B2TestUtils.assertAuthentication;\nimport static org.jclouds.b2.features.B2TestUtils.assertRequest;\nimport static org.jclouds.b2.features.B2TestUtils.createMockWebServer;\nimport static org.jclouds.b2.features.B2TestUtils.stringFromResource;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\n\nimport org.jclouds.b2.domain.Bucket;\nimport org.jclouds.b2.domain.BucketList;\nimport org.jclouds.b2.domain.BucketType;\nimport org.testng.annotations.Test;\n\n\n@Test(groups = \"unit\", testName = \"BucketApiMockTest\")\npublic final class BucketApiMockTest {\n   public void testCreateBucket() throws Exception {\n      MockWebServer server = createMockWebServer();\n      server.enqueue(new MockResponse().setBody(stringFromResource(\"/authorize_account_response.json\")));\n      server.enqueue(new MockResponse().setBody(stringFromResource(\"/bucket.json\")));\n\n      try {\n         BucketApi api = api(server.url(\"/\").toString(), \"b2\").getBucketApi();\n         Bucket response = api.createBucket(\"any_name_you_pick\", BucketType.ALL_PRIVATE);\n         assertThat(response.bucketId()).isEqualTo(\"4a48fe8875c6214145260818\");\n         assertThat(response.bucketName()).isEqualTo(\"any_name_you_pick\");\n         assertThat(response.bucketType()).isEqualTo(BucketType.ALL_PRIVATE);\n\n         assertThat(server.getRequestCount()).isEqualTo(2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"POST\", \"/b2api/v2/b2_create_bucket\", \"/create_bucket_request.json\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testDeleteBucket() throws Exception {\n      MockWebServer server = createMockWebServer();\n      server.enqueue(new MockResponse().setBody(stringFromResource(\"/authorize_account_response.json\")));\n      server.enqueue(new MockResponse().setBody(stringFromResource(\"/bucket.json\")));\n\n      try {\n         BucketApi api = api(server.url(\"/\").toString(), \"b2\").getBucketApi();\n         Bucket response = api.deleteBucket(\"4a48fe8875c6214145260818\");\n         assertThat(response.bucketId()).isEqualTo(\"4a48fe8875c6214145260818\");\n         assertThat(response.bucketName()).isEqualTo(\"any_name_you_pick\");\n         assertThat(response.bucketType()).isEqualTo(BucketType.ALL_PRIVATE);\n\n         assertThat(server.getRequestCount()).isEqualTo(2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"POST\", \"/b2api/v2/b2_delete_bucket\", \"/delete_bucket_request.json\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testDeleteAlreadyDeletedBucket() throws Exception {\n      MockWebServer server = createMockWebServer();\n      server.enqueue(new MockResponse().setBody(stringFromResource(\"/authorize_account_response.json\")));\n      server.enqueue(new MockResponse().setResponseCode(400).setBody(stringFromResource(\"/delete_bucket_already_deleted_response.json\")));\n\n      try {\n         BucketApi api = api(server.url(\"/\").toString(), \"b2\").getBucketApi();\n         Bucket response = api.deleteBucket(\"4a48fe8875c6214145260818\");\n         assertThat(response).isNull();\n\n         assertThat(server.getRequestCount()).isEqualTo(2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"POST\", \"/b2api/v2/b2_delete_bucket\", \"/delete_bucket_request.json\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testUpdateBucket() throws Exception {\n      MockWebServer server = createMockWebServer();\n      server.enqueue(new MockResponse().setBody(stringFromResource(\"/authorize_account_response.json\")));\n      server.enqueue(new MockResponse().setBody(stringFromResource(\"/bucket.json\")));\n\n      try {\n         BucketApi api = api(server.url(\"/\").toString(), \"b2\").getBucketApi();\n         Bucket response = api.updateBucket(\"4a48fe8875c6214145260818\", BucketType.ALL_PRIVATE);\n         assertThat(response.bucketId()).isEqualTo(\"4a48fe8875c6214145260818\");\n         assertThat(response.bucketName()).isEqualTo(\"any_name_you_pick\");\n         assertThat(response.bucketType()).isEqualTo(BucketType.ALL_PRIVATE);\n\n         assertThat(server.getRequestCount()).isEqualTo(2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"POST\", \"/b2api/v2/b2_update_bucket\", \"/update_bucket_request.json\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testListBuckets() throws Exception {\n      MockWebServer server = createMockWebServer();\n      server.enqueue(new MockResponse().setBody(stringFromResource(\"/authorize_account_response.json\")));\n      server.enqueue(new MockResponse().setBody(stringFromResource(\"/list_buckets_response.json\")));\n\n      try {\n         BucketApi api = api(server.url(\"/\").toString(), \"b2\").getBucketApi();\n         BucketList response = api.listBuckets();\n\n         assertThat(response.buckets()).hasSize(3);\n\n         assertThat(response.buckets().get(0).bucketName()).isEqualTo(\"Kitten Videos\");\n         assertThat(response.buckets().get(0).bucketType()).isEqualTo(BucketType.ALL_PRIVATE);\n\n         assertThat(response.buckets().get(1).bucketName()).isEqualTo(\"Puppy Videos\");\n         assertThat(response.buckets().get(1).bucketType()).isEqualTo(BucketType.ALL_PUBLIC);\n\n         assertThat(response.buckets().get(2).bucketName()).isEqualTo(\"Vacation Pictures\");\n         assertThat(response.buckets().get(2).bucketType()).isEqualTo(BucketType.ALL_PRIVATE);\n\n         assertThat(server.getRequestCount()).isEqualTo(2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"POST\", \"/b2api/v2/b2_list_buckets\", \"/list_buckets_request.json\");\n      } finally {\n         server.shutdown();\n      }\n   }\n}\n"
  },
  {
    "path": "providers/b2/src/test/java/org/jclouds/b2/features/MultipartApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2.features;\n\nimport static org.assertj.core.api.Assertions.assertThat;\n\nimport java.util.Map;\nimport java.util.Random;\n\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.b2.domain.Action;\nimport org.jclouds.b2.domain.B2Object;\nimport org.jclouds.b2.domain.Bucket;\nimport org.jclouds.b2.domain.BucketType;\nimport org.jclouds.b2.domain.GetUploadPartResponse;\nimport org.jclouds.b2.domain.ListPartsResponse;\nimport org.jclouds.b2.domain.ListUnfinishedLargeFilesResponse;\nimport org.jclouds.b2.domain.MultipartUploadResponse;\nimport org.jclouds.b2.internal.BaseB2ApiLiveTest;\nimport org.jclouds.utils.TestUtils;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.hash.Hashing;\nimport com.google.common.io.ByteSource;\n\npublic final class MultipartApiLiveTest extends BaseB2ApiLiveTest {\n   private static final Random random = new Random();\n\n   @Test(groups = \"live\")\n   public void testCancelMultipart() throws Exception {\n      BucketApi bucketApi = api.getBucketApi();\n      MultipartApi multipartApi = api.getMultipartApi();\n\n      String fileName = \"file-name\";\n      String contentType = \"text/plain\";\n      Map<String, String> fileInfo = ImmutableMap.of(\"author\", \"unknown\");\n\n      Bucket bucket = bucketApi.createBucket(getBucketName(), BucketType.ALL_PRIVATE);\n      try {\n         MultipartUploadResponse response = multipartApi.startLargeFile(bucket.bucketId(), fileName, contentType, fileInfo);\n         multipartApi.cancelLargeFile(response.fileId());\n      } finally {\n         bucketApi.deleteBucket(bucket.bucketId());\n      }\n   }\n\n   @Test(groups = \"live\")\n   public void testFinishMultipart() throws Exception {\n      BucketApi bucketApi = api.getBucketApi();\n      ObjectApi objectApi = api.getObjectApi();\n      MultipartApi multipartApi = api.getMultipartApi();\n\n      String fileName = \"file-name\";\n      String contentType = \"text/plain\";\n      Map<String, String> fileInfo = ImmutableMap.of(\"author\", \"unknown\");\n\n      Bucket bucket = bucketApi.createBucket(getBucketName(), BucketType.ALL_PRIVATE);\n      MultipartUploadResponse response = null;\n      B2Object b2Object = null;\n      try {\n         response = multipartApi.startLargeFile(bucket.bucketId(), fileName, contentType, fileInfo);\n\n         ByteSource part1 = TestUtils.randomByteSource().slice(0, 100 * 1024 * 1024);\n         String hash1 = part1.hash(Hashing.sha1()).toString();\n         Payload payload1 = Payloads.newByteSourcePayload(part1);\n         payload1.getContentMetadata().setContentLength(part1.size());\n         GetUploadPartResponse uploadUrl = multipartApi.getUploadPartUrl(response.fileId());\n         multipartApi.uploadPart(uploadUrl, 1, hash1, payload1);\n\n         ByteSource part2 = TestUtils.randomByteSource().slice(0, 1);\n         String hash2 = part2.hash(Hashing.sha1()).toString();\n         Payload payload2 = Payloads.newByteSourcePayload(part2);\n         payload2.getContentMetadata().setContentLength(part2.size());\n         uploadUrl = multipartApi.getUploadPartUrl(response.fileId());\n         multipartApi.uploadPart(uploadUrl, 2, hash2, payload2);\n\n         b2Object = multipartApi.finishLargeFile(response.fileId(), ImmutableList.of(hash1, hash2));\n         response = null;\n\n         assertThat(b2Object.fileName()).isEqualTo(fileName);\n         assertThat(b2Object.fileInfo()).isEqualTo(fileInfo);\n         assertThat(b2Object.uploadTimestamp()).isAfterYear(2015);\n         assertThat(b2Object.action()).isEqualTo(Action.UPLOAD);\n         assertThat(b2Object.bucketId()).isEqualTo(bucket.bucketId());\n         assertThat(b2Object.contentLength()).isEqualTo(100 * 1024 * 1024 + 1);\n         assertThat(b2Object.contentType()).isEqualTo(contentType);\n      } finally {\n         if (b2Object != null) {\n            objectApi.deleteFileVersion(fileName, b2Object.fileId());\n         }\n         if (response != null) {\n            multipartApi.cancelLargeFile(response.fileId());\n         }\n         bucketApi.deleteBucket(bucket.bucketId());\n      }\n   }\n\n   @Test(groups = \"live\")\n   public void testListParts() throws Exception {\n      BucketApi bucketApi = api.getBucketApi();\n      ObjectApi objectApi = api.getObjectApi();\n      MultipartApi multipartApi = api.getMultipartApi();\n\n      String fileName = \"file-name\";\n      String contentType = \"text/plain\";\n      Map<String, String> fileInfo = ImmutableMap.of(\"author\", \"unknown\");\n\n      Bucket bucket = bucketApi.createBucket(getBucketName(), BucketType.ALL_PRIVATE);\n      MultipartUploadResponse response = null;\n      B2Object b2Object = null;\n      try {\n         response = multipartApi.startLargeFile(bucket.bucketId(), fileName, contentType, fileInfo);\n\n         ListPartsResponse listParts = multipartApi.listParts(response.fileId(), 1, 1000);\n         assertThat(listParts.parts()).hasSize(0);\n\n         long contentLength = 1024 * 1024;\n         ByteSource part = TestUtils.randomByteSource().slice(0, contentLength);\n         String hash = part.hash(Hashing.sha1()).toString();\n         Payload payload = Payloads.newByteSourcePayload(part);\n         payload.getContentMetadata().setContentLength(contentLength);\n         GetUploadPartResponse uploadUrl = multipartApi.getUploadPartUrl(response.fileId());\n         multipartApi.uploadPart(uploadUrl, 1, hash, payload);\n\n         listParts = multipartApi.listParts(response.fileId(), 1, 1000);\n         assertThat(listParts.parts()).hasSize(1);\n\n         ListPartsResponse.Entry entry = listParts.parts().get(0);\n         assertThat(entry.contentLength()).isEqualTo(contentLength);\n         assertThat(entry.contentSha1()).isEqualTo(hash);\n         assertThat(entry.partNumber()).isEqualTo(1);\n      } finally {\n         if (response != null) {\n            multipartApi.cancelLargeFile(response.fileId());\n         }\n         bucketApi.deleteBucket(bucket.bucketId());\n      }\n   }\n\n   @Test(groups = \"live\")\n   public void testListUnfinishedLargeFiles() throws Exception {\n      BucketApi bucketApi = api.getBucketApi();\n      ObjectApi objectApi = api.getObjectApi();\n      MultipartApi multipartApi = api.getMultipartApi();\n\n      String fileName = \"file-name\";\n      String contentType = \"text/plain\";\n      Map<String, String> fileInfo = ImmutableMap.of(\"author\", \"unknown\");\n\n      Bucket bucket = bucketApi.createBucket(getBucketName(), BucketType.ALL_PRIVATE);\n      MultipartUploadResponse response = null;\n      B2Object b2Object = null;\n      try {\n         ListUnfinishedLargeFilesResponse unfinishedLargeFiles = multipartApi.listUnfinishedLargeFiles(bucket.bucketId(), null, null);\n         assertThat(unfinishedLargeFiles.files()).hasSize(0);\n\n         response = multipartApi.startLargeFile(bucket.bucketId(), fileName, contentType, fileInfo);\n\n         unfinishedLargeFiles = multipartApi.listUnfinishedLargeFiles(bucket.bucketId(), null, null);\n         assertThat(unfinishedLargeFiles.files()).hasSize(1);\n\n         ListUnfinishedLargeFilesResponse.Entry entry = unfinishedLargeFiles.files().get(0);\n         assertThat(entry.contentType()).isEqualTo(contentType);\n         assertThat(entry.fileInfo()).isEqualTo(fileInfo);\n         assertThat(entry.fileName()).isEqualTo(fileName);\n      } finally {\n         if (response != null) {\n            multipartApi.cancelLargeFile(response.fileId());\n         }\n         bucketApi.deleteBucket(bucket.bucketId());\n      }\n   }\n\n   private static String getBucketName() {\n      return \"jcloudstestbucket-\" + random.nextInt(Integer.MAX_VALUE);\n   }\n}\n"
  },
  {
    "path": "providers/b2/src/test/java/org/jclouds/b2/features/MultipartApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2.features;\n\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.jclouds.b2.features.B2TestUtils.api;\nimport static org.jclouds.b2.features.B2TestUtils.assertAuthentication;\nimport static org.jclouds.b2.features.B2TestUtils.assertRequest;\nimport static org.jclouds.b2.features.B2TestUtils.createMockWebServer;\nimport static org.jclouds.b2.features.B2TestUtils.stringFromResource;\n\nimport java.net.URI;\nimport java.util.Collection;\nimport java.util.Date;\nimport java.util.Map;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\n\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.b2.domain.Action;\nimport org.jclouds.b2.domain.B2Object;\nimport org.jclouds.b2.domain.GetUploadPartResponse;\nimport org.jclouds.b2.domain.ListPartsResponse;\nimport org.jclouds.b2.domain.ListUnfinishedLargeFilesResponse;\nimport org.jclouds.b2.domain.MultipartUploadResponse;\nimport org.jclouds.b2.domain.UploadPartResponse;\nimport org.jclouds.utils.TestUtils;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\n\n\n@Test(groups = \"unit\", testName = \"MultipartApiMockTest\")\npublic final class MultipartApiMockTest {\n   private static final String ACCOUNT_ID = \"YOUR_ACCOUNT_ID\";\n   private static final String AUTHORIZATION_TOKEN = \"3_20160409004829_42b8f80ba60fb4323dcaad98_ec81302316fccc2260201cbf17813247f312cf3b_000_uplg\";\n   private static final String BUCKET_NAME = \"BUCKET_NAME\";\n   private static final String BUCKET_ID = \"e73ede9c9c8412db49f60715\";\n   private static final String CONTENT_TYPE = \"b2/x-auto\";\n   private static final String FILE_ID = \"4_za71f544e781e6891531b001a_f200ec353a2184825_d20160409_m004829_c000_v0001016_t0028\";\n   private static final Map<String, String> FILE_INFO = ImmutableMap.of(\"author\", \"unknown\");\n   private static final String FILE_NAME = \"bigfile.dat\";\n   private static final String SHA1 = \"062685a84ab248d2488f02f6b01b948de2514ad8\";\n   private static final Date UPLOAD_TIMESTAMP = new Date(1460162909000L);\n\n   public void testStartLargeFile() throws Exception {\n      MockWebServer server = createMockWebServer();\n      server.enqueue(new MockResponse().setBody(stringFromResource(\"/authorize_account_response.json\")));\n      server.enqueue(new MockResponse().setBody(stringFromResource(\"/start_large_file_response.json\")));\n\n      try {\n         MultipartApi api = api(server.url(\"/\").toString(), \"b2\").getMultipartApi();\n         MultipartUploadResponse response = api.startLargeFile(BUCKET_ID, FILE_NAME, CONTENT_TYPE, FILE_INFO);\n         assertThat(response.accountId()).isEqualTo(ACCOUNT_ID);\n         assertThat(response.bucketId()).isEqualTo(BUCKET_ID);\n         assertThat(response.contentType()).isEqualTo(CONTENT_TYPE);\n         assertThat(response.fileId()).isEqualTo(FILE_ID);\n         assertThat(response.fileInfo()).isEqualTo(FILE_INFO);\n         assertThat(response.fileName()).isEqualTo(FILE_NAME);\n         assertThat(response.uploadTimestamp()).isEqualTo(UPLOAD_TIMESTAMP);\n\n         assertThat(server.getRequestCount()).isEqualTo(2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"POST\", \"/b2api/v2/b2_start_large_file\", \"/start_large_file_request.json\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testCancelLargeFile() throws Exception {\n      MockWebServer server = createMockWebServer();\n      server.enqueue(new MockResponse().setBody(stringFromResource(\"/authorize_account_response.json\")));\n      server.enqueue(new MockResponse().setBody(stringFromResource(\"/cancel_large_file_response.json\")));\n\n      try {\n         MultipartApi api = api(server.url(\"/\").toString(), \"b2\").getMultipartApi();\n         B2Object response = api.cancelLargeFile(FILE_ID);\n         assertThat(response.accountId()).isEqualTo(ACCOUNT_ID);\n         assertThat(response.bucketId()).isEqualTo(BUCKET_ID);\n         assertThat(response.fileId()).isEqualTo(FILE_ID);\n         assertThat(response.fileName()).isEqualTo(FILE_NAME);\n\n         assertThat(server.getRequestCount()).isEqualTo(2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"POST\", \"/b2api/v2/b2_cancel_large_file\", \"/cancel_large_file_request.json\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testFinishLargeFile() throws Exception {\n      MockWebServer server = createMockWebServer();\n      server.enqueue(new MockResponse().setBody(stringFromResource(\"/authorize_account_response.json\")));\n      server.enqueue(new MockResponse().setBody(stringFromResource(\"/finish_large_file_response.json\")));\n      Collection<String> sha1 = ImmutableList.of(\n            \"0000000000000000000000000000000000000000\",\n            \"ffffffffffffffffffffffffffffffffffffffff\");\n\n      try {\n         MultipartApi api = api(server.url(\"/\").toString(), \"b2\").getMultipartApi();\n         B2Object response = api.finishLargeFile(FILE_ID, sha1);\n         assertThat(response.accountId()).isEqualTo(ACCOUNT_ID);\n         assertThat(response.action()).isEqualTo(Action.UPLOAD);\n         assertThat(response.bucketId()).isEqualTo(BUCKET_ID);\n         assertThat(response.contentLength()).isEqualTo(208158542);\n         assertThat(response.contentSha1()).isEqualTo(\"none\");\n         assertThat(response.contentType()).isEqualTo(CONTENT_TYPE);\n         assertThat(response.fileId()).isEqualTo(FILE_ID);\n         assertThat(response.fileInfo()).isEqualTo(FILE_INFO);\n         assertThat(response.fileName()).isEqualTo(FILE_NAME);\n         assertThat(response.uploadTimestamp()).isEqualTo(UPLOAD_TIMESTAMP);\n\n         assertThat(server.getRequestCount()).isEqualTo(2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"POST\", \"/b2api/v2/b2_finish_large_file\", \"/finish_large_file_request.json\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGetUploadPartUrl() throws Exception {\n      MockWebServer server = createMockWebServer();\n      server.enqueue(new MockResponse().setBody(stringFromResource(\"/authorize_account_response.json\")));\n      server.enqueue(new MockResponse().setBody(stringFromResource(\"/get_upload_part_url_response.json\")));\n\n      try {\n         MultipartApi api = api(server.url(\"/\").toString(), \"b2\").getMultipartApi();\n         GetUploadPartResponse response = api.getUploadPartUrl(FILE_ID);\n         assertThat(response.authorizationToken()).isEqualTo(AUTHORIZATION_TOKEN);\n         assertThat(response.fileId()).isEqualTo(FILE_ID);\n         assertThat(response.uploadUrl()).isEqualTo(URI.create(\"https://pod-000-1016-09.backblaze.com/b2api/v2/b2_upload_part/4_ze73ede9c9c8412db49f60715_f100b4e93fbae6252_d20150824_m224353_c900_v8881000_t0001/0037\"));\n\n         assertThat(server.getRequestCount()).isEqualTo(2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"POST\", \"/b2api/v2/b2_get_upload_part_url\", \"/get_upload_part_url_request.json\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testUploadPart() throws Exception {\n      MockWebServer server = createMockWebServer();\n      server.enqueue(new MockResponse().setBody(stringFromResource(\"/upload_part_response.json\")));\n\n      try {\n         MultipartApi api = api(server.url(\"/\").toString(), \"b2\").getMultipartApi();\n         GetUploadPartResponse uploadPart = GetUploadPartResponse.create(FILE_ID, server.url(\"/b2api/v2/b2_upload_part/4a48fe8875c6214145260818/c001_v0001007_t0042\").uri(), AUTHORIZATION_TOKEN);\n         long contentLength = 100 * 1000 * 1000;\n         Payload payload = Payloads.newByteSourcePayload(TestUtils.randomByteSource().slice(0, contentLength));\n         payload.getContentMetadata().setContentLength(contentLength);\n         UploadPartResponse response = api.uploadPart(uploadPart, 1, SHA1, payload);\n         assertThat(response.contentLength()).isEqualTo(contentLength);\n         assertThat(response.contentSha1()).isEqualTo(SHA1);\n         assertThat(response.fileId()).isEqualTo(FILE_ID);\n         assertThat(response.partNumber()).isEqualTo(1);\n\n         assertThat(server.getRequestCount()).isEqualTo(1);\n         assertRequest(server.takeRequest(), \"POST\", \"/b2api/v2/b2_upload_part/4a48fe8875c6214145260818/c001_v0001007_t0042\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testListParts() throws Exception {\n      MockWebServer server = createMockWebServer();\n      server.enqueue(new MockResponse().setBody(stringFromResource(\"/authorize_account_response.json\")));\n      server.enqueue(new MockResponse().setBody(stringFromResource(\"/list_parts_response.json\")));\n\n      try {\n         MultipartApi api = api(server.url(\"/\").toString(), \"b2\").getMultipartApi();\n         ListPartsResponse response = api.listParts(FILE_ID, 1, 1000);\n         assertThat(response.nextPartNumber()).isNull();\n         assertThat(response.parts()).hasSize(3);\n\n         ListPartsResponse.Entry entry = response.parts().get(0);\n         assertThat(entry.contentLength()).isEqualTo(100000000);\n         assertThat(entry.contentSha1()).isEqualTo(\"062685a84ab248d2488f02f6b01b948de2514ad8\");\n         assertThat(entry.fileId()).isEqualTo(\"4_ze73ede9c9c8412db49f60715_f100b4e93fbae6252_d20150824_m224353_c900_v8881000_t0001\");\n         assertThat(entry.partNumber()).isEqualTo(1);\n         assertThat(entry.uploadTimestamp()).isEqualTo(new Date(1462212185000L));\n\n         entry = response.parts().get(1);\n         assertThat(entry.contentLength()).isEqualTo(100000000);\n         assertThat(entry.contentSha1()).isEqualTo(\"cf634751c3d9f6a15344f23cbf13f3fc9542addf\");\n         assertThat(entry.fileId()).isEqualTo(\"4_ze73ede9c9c8412db49f60715_f100b4e93fbae6252_d20150824_m224353_c900_v8881000_t0001\");\n         assertThat(entry.partNumber()).isEqualTo(2);\n         assertThat(entry.uploadTimestamp()).isEqualTo(new Date(1462212296000L));\n\n         entry = response.parts().get(2);\n         assertThat(entry.contentLength()).isEqualTo(8158554);\n         assertThat(entry.contentSha1()).isEqualTo(\"00ad164147cbbd60aedb2b04ff66b0f74f962753\");\n         assertThat(entry.fileId()).isEqualTo(\"4_ze73ede9c9c8412db49f60715_f100b4e93fbae6252_d20150824_m224353_c900_v8881000_t0001\");\n         assertThat(entry.partNumber()).isEqualTo(3);\n         assertThat(entry.uploadTimestamp()).isEqualTo(new Date(1462212327000L));\n\n         assertThat(server.getRequestCount()).isEqualTo(2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"POST\", \"/b2api/v2/b2_list_parts\", \"/list_parts_request.json\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testListUnfinishedLargeFiles() throws Exception {\n      MockWebServer server = createMockWebServer();\n      server.enqueue(new MockResponse().setBody(stringFromResource(\"/authorize_account_response.json\")));\n      server.enqueue(new MockResponse().setBody(stringFromResource(\"/list_unfinished_large_files_response.json\")));\n\n      try {\n         MultipartApi api = api(server.url(\"/\").toString(), \"b2\").getMultipartApi();\n         ListUnfinishedLargeFilesResponse response = api.listUnfinishedLargeFiles(BUCKET_ID, FILE_ID, 1000);\n         assertThat(response.nextFileId()).isNull();\n         assertThat(response.files()).hasSize(1);\n\n         ListUnfinishedLargeFilesResponse.Entry entry = response.files().get(0);\n         assertThat(entry.accountId()).isEqualTo(ACCOUNT_ID);\n         assertThat(entry.bucketId()).isEqualTo(BUCKET_ID);\n         assertThat(entry.contentType()).isEqualTo(\"application/octet-stream\");\n         assertThat(entry.fileId()).isEqualTo(\"4_ze73ede9c9c8412db49f60715_f100b4e93fbae6252_d20150824_m224353_c900_v8881000_t0001\");\n         assertThat(entry.fileInfo()).isEqualTo(FILE_INFO);\n         assertThat(entry.fileName()).isEqualTo(FILE_NAME);\n         assertThat(entry.uploadTimestamp()).isEqualTo(new Date(1462212184000L));\n\n         assertThat(server.getRequestCount()).isEqualTo(2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"POST\", \"/b2api/v2/b2_list_unfinished_large_files\", \"/list_unfinished_large_files_request.json\");\n      } finally {\n         server.shutdown();\n      }\n   }\n}\n"
  },
  {
    "path": "providers/b2/src/test/java/org/jclouds/b2/features/ObjectApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2.features;\n\nimport static org.assertj.core.api.Assertions.assertThat;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.Map;\nimport java.util.Random;\n\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.b2.domain.Action;\nimport org.jclouds.b2.domain.B2Object;\nimport org.jclouds.b2.domain.B2ObjectList;\nimport org.jclouds.b2.domain.Bucket;\nimport org.jclouds.b2.domain.BucketType;\nimport org.jclouds.b2.domain.HideFileResponse;\nimport org.jclouds.b2.domain.UploadFileResponse;\nimport org.jclouds.b2.domain.UploadUrlResponse;\nimport org.jclouds.b2.internal.BaseB2ApiLiveTest;\nimport org.jclouds.util.Closeables2;\nimport org.jclouds.utils.TestUtils;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.hash.Hashing;\nimport com.google.common.io.ByteSource;\n\npublic final class ObjectApiLiveTest extends BaseB2ApiLiveTest {\n   private static final Random random = new Random();\n\n   @Test(groups = \"live\")\n   public void testGetFileInfo() throws Exception {\n      BucketApi bucketApi = api.getBucketApi();\n      ObjectApi objectApi = api.getObjectApi();\n\n      ByteSource byteSource = TestUtils.randomByteSource().slice(0, 1024);\n      Payload payload = Payloads.newByteSourcePayload(byteSource);\n      payload.getContentMetadata().setContentLength(byteSource.size());\n      String fileName = \"file-name\";\n      String contentSha1 = byteSource.hash(Hashing.sha1()).toString();\n      String contentType = \"text/plain\";\n      payload.getContentMetadata().setContentType(contentType);\n      Map<String, String> fileInfo = ImmutableMap.of(\"author\", \"unknown\");\n\n      Bucket response = bucketApi.createBucket(getBucketName(), BucketType.ALL_PRIVATE);\n      UploadFileResponse uploadFile = null;\n      try {\n         UploadUrlResponse uploadUrl = objectApi.getUploadUrl(response.bucketId());\n\n         uploadFile = objectApi.uploadFile(uploadUrl, fileName, contentSha1, fileInfo, payload);\n\n         B2Object b2Object = objectApi.getFileInfo(uploadFile.fileId());\n         assertThat(b2Object.fileId()).isEqualTo(uploadFile.fileId());\n         assertThat(b2Object.fileName()).isEqualTo(fileName);\n         assertThat(b2Object.accountId()).isEqualTo(response.accountId());\n         assertThat(b2Object.bucketId()).isEqualTo(response.bucketId());\n         assertThat(b2Object.contentLength()).isEqualTo(byteSource.size());\n         assertThat(b2Object.contentSha1()).isEqualTo(contentSha1);\n         assertThat(b2Object.contentType()).isEqualTo(contentType);\n         assertThat(b2Object.fileInfo()).isEqualTo(fileInfo);\n         assertThat(b2Object.action()).isEqualTo(Action.UPLOAD);\n         assertThat(b2Object.uploadTimestamp()).isAfterYear(2015);\n         assertThat(b2Object.payload()).isNull();\n      } finally {\n         if (uploadFile != null) {\n            objectApi.deleteFileVersion(uploadFile.fileName(), uploadFile.fileId());\n         }\n         bucketApi.deleteBucket(response.bucketId());\n      }\n   }\n\n   @Test(groups = \"live\")\n   public void testDownloadFileById() throws Exception {\n      BucketApi bucketApi = api.getBucketApi();\n      ObjectApi objectApi = api.getObjectApi();\n\n      ByteSource byteSource = TestUtils.randomByteSource().slice(0, 1024);\n      Payload payload = Payloads.newByteSourcePayload(byteSource);\n      payload.getContentMetadata().setContentLength(byteSource.size());\n      String fileName = \"file-name\";\n      String contentSha1 = byteSource.hash(Hashing.sha1()).toString();\n      String contentType = \"text/plain\";\n      payload.getContentMetadata().setContentType(contentType);\n      Map<String, String> fileInfo = ImmutableMap.of(\"author\", \"unknown\");\n\n      Bucket response = bucketApi.createBucket(getBucketName(), BucketType.ALL_PRIVATE);\n      UploadFileResponse uploadFile = null;\n      try {\n         UploadUrlResponse uploadUrl = objectApi.getUploadUrl(response.bucketId());\n\n         uploadFile = objectApi.uploadFile(uploadUrl, fileName, contentSha1, fileInfo, payload);\n\n         B2Object b2Object = objectApi.downloadFileById(uploadFile.fileId());\n         payload = b2Object.payload();\n         assertThat(b2Object.fileName()).isEqualTo(fileName);\n         assertThat(b2Object.contentSha1()).isEqualTo(contentSha1);\n         assertThat(b2Object.fileInfo()).isEqualTo(fileInfo);\n         assertThat(b2Object.uploadTimestamp()).isAfterYear(2015);\n         assertThat(payload.getContentMetadata().getContentType()).isEqualTo(contentType);\n\n         InputStream actual = null;\n         InputStream expected = null;\n         try {\n            actual = payload.openStream();\n            expected = byteSource.openStream();\n            assertThat(actual).hasContentEqualTo(expected);\n         } finally {\n            Closeables2.closeQuietly(expected);\n            Closeables2.closeQuietly(actual);\n         }\n      } finally {\n         if (uploadFile != null) {\n            objectApi.deleteFileVersion(uploadFile.fileName(), uploadFile.fileId());\n         }\n         bucketApi.deleteBucket(response.bucketId());\n      }\n   }\n\n   @Test(groups = \"live\")\n   public void testDownloadFileByName() throws Exception {\n      BucketApi bucketApi = api.getBucketApi();\n      ObjectApi objectApi = api.getObjectApi();\n\n      String bucketName = getBucketName();\n      ByteSource byteSource = TestUtils.randomByteSource().slice(0, 1024);\n      Payload payload = Payloads.newByteSourcePayload(byteSource);\n      payload.getContentMetadata().setContentLength(byteSource.size());\n      String fileName = \"file name\";  // intentionally using spaces in file name\n      String contentSha1 = byteSource.hash(Hashing.sha1()).toString();\n      String contentType = \"text/plain\";\n      payload.getContentMetadata().setContentType(contentType);\n      Map<String, String> fileInfo = ImmutableMap.of(\"author\", \"unknown\");\n\n      Bucket response = bucketApi.createBucket(bucketName, BucketType.ALL_PRIVATE);\n      UploadFileResponse uploadFile = null;\n      try {\n         UploadUrlResponse uploadUrl = objectApi.getUploadUrl(response.bucketId());\n\n         uploadFile = objectApi.uploadFile(uploadUrl, fileName, contentSha1, fileInfo, payload);\n\n         B2Object b2Object = objectApi.downloadFileByName(bucketName, fileName);\n         payload = b2Object.payload();\n         assertThat(b2Object.fileName()).isEqualTo(fileName);\n         assertThat(b2Object.contentSha1()).isEqualTo(contentSha1);\n         assertThat(b2Object.fileInfo()).isEqualTo(fileInfo);\n         assertThat(b2Object.uploadTimestamp()).isAfterYear(2015);\n         assertThat(payload.getContentMetadata().getContentType()).isEqualTo(contentType);\n\n         InputStream actual = null;\n         InputStream expected = null;\n         try {\n            actual = payload.openStream();\n            expected = byteSource.openStream();\n            assertThat(actual).hasContentEqualTo(expected);\n         } finally {\n            Closeables2.closeQuietly(expected);\n            Closeables2.closeQuietly(actual);\n         }\n      } finally {\n         if (uploadFile != null) {\n            objectApi.deleteFileVersion(uploadFile.fileName(), uploadFile.fileId());\n         }\n         bucketApi.deleteBucket(response.bucketId());\n      }\n   }\n\n   @Test(groups = \"live\")\n   public void testListFileNames() throws Exception {\n      BucketApi bucketApi = api.getBucketApi();\n      ObjectApi objectApi = api.getObjectApi();\n\n      Bucket response = bucketApi.createBucket(getBucketName(), BucketType.ALL_PRIVATE);\n      int numFiles = 3;\n      ImmutableList.Builder<UploadFileResponse> uploadFiles = ImmutableList.builder();\n      try {\n         for (int i = 0; i < numFiles; ++i) {\n            uploadFiles.add(createFile(objectApi, response.bucketId(), \"file\" + i));\n         }\n\n         B2ObjectList list = objectApi.listFileNames(response.bucketId(), null, null, null, null);\n         assertThat(list.files()).hasSize(numFiles);\n      } finally {\n         for (UploadFileResponse uploadFile : uploadFiles.build()) {\n            objectApi.deleteFileVersion(uploadFile.fileName(), uploadFile.fileId());\n         }\n         bucketApi.deleteBucket(response.bucketId());\n      }\n   }\n\n   @Test(groups = \"live\")\n   public void testListFileVersions() throws Exception {\n      BucketApi bucketApi = api.getBucketApi();\n      ObjectApi objectApi = api.getObjectApi();\n\n      Bucket response = bucketApi.createBucket(getBucketName(), BucketType.ALL_PRIVATE);\n      int numFiles = 3;\n      ImmutableList.Builder<UploadFileResponse> uploadFiles = ImmutableList.builder();\n      try {\n         for (int i = 0; i < numFiles; ++i) {\n            uploadFiles.add(createFile(objectApi, response.bucketId(), \"file\"));\n         }\n\n         B2ObjectList list = objectApi.listFileNames(response.bucketId(), null, null, null, null);\n         assertThat(list.files()).hasSize(1);\n\n         list = objectApi.listFileVersions(response.bucketId(), null, null, null, null, null);\n         assertThat(list.files()).hasSize(numFiles);\n      } finally {\n         for (UploadFileResponse uploadFile : uploadFiles.build()) {\n            objectApi.deleteFileVersion(uploadFile.fileName(), uploadFile.fileId());\n         }\n         bucketApi.deleteBucket(response.bucketId());\n      }\n   }\n\n   @Test(groups = \"live\")\n   public void testHideFile() throws Exception {\n      BucketApi bucketApi = api.getBucketApi();\n      ObjectApi objectApi = api.getObjectApi();\n      String fileName = \"file-name\";\n\n      Bucket response = bucketApi.createBucket(getBucketName(), BucketType.ALL_PRIVATE);\n      UploadFileResponse uploadFile = null;\n      HideFileResponse hideFile = null;\n      try {\n         uploadFile = createFile(objectApi, response.bucketId(), fileName);\n\n         B2ObjectList list = objectApi.listFileNames(response.bucketId(), null, null, null, null);\n         assertThat(list.files()).hasSize(1);\n\n         hideFile = objectApi.hideFile(response.bucketId(), fileName);\n\n         list = objectApi.listFileNames(response.bucketId(), null, null, null, null);\n         assertThat(list.files()).isEmpty();\n\n         list = objectApi.listFileVersions(response.bucketId(), null, null, null, null, null);\n         assertThat(list.files()).hasSize(2);\n      } finally {\n         if (hideFile != null) {\n            objectApi.deleteFileVersion(hideFile.fileName(), hideFile.fileId());\n         }\n         if (uploadFile != null) {\n            objectApi.deleteFileVersion(uploadFile.fileName(), uploadFile.fileId());\n         }\n         bucketApi.deleteBucket(response.bucketId());\n      }\n   }\n\n   private static String getBucketName() {\n      return \"jcloudstestbucket-\" + random.nextInt(Integer.MAX_VALUE);\n   }\n\n   private static UploadFileResponse createFile(ObjectApi objectApi, String bucketId, String fileName) throws IOException {\n      ByteSource byteSource = TestUtils.randomByteSource().slice(0, 1024);\n      Payload payload = Payloads.newByteSourcePayload(byteSource);\n      payload.getContentMetadata().setContentLength(byteSource.size());\n      String contentSha1 = byteSource.hash(Hashing.sha1()).toString();\n      String contentType = \"text/plain\";\n      payload.getContentMetadata().setContentType(contentType);\n      Map<String, String> fileInfo = ImmutableMap.of(\"author\", \"unknown\");\n\n      UploadUrlResponse uploadUrl = objectApi.getUploadUrl(bucketId);\n\n      return objectApi.uploadFile(uploadUrl, fileName, contentSha1, fileInfo, payload);\n   }\n}\n"
  },
  {
    "path": "providers/b2/src/test/java/org/jclouds/b2/features/ObjectApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2.features;\n\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown;\nimport static org.jclouds.b2.features.B2TestUtils.api;\nimport static org.jclouds.b2.features.B2TestUtils.assertAuthentication;\nimport static org.jclouds.b2.features.B2TestUtils.assertRequest;\nimport static org.jclouds.b2.features.B2TestUtils.createMockWebServer;\nimport static org.jclouds.b2.features.B2TestUtils.stringFromResource;\n\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.Map;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\nimport okhttp3.mockwebserver.RecordedRequest;\n\nimport org.jclouds.blobstore.ContainerNotFoundException;\nimport org.jclouds.blobstore.KeyNotFoundException;\nimport org.jclouds.http.options.GetOptions;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.b2.domain.Action;\nimport org.jclouds.b2.domain.B2Object;\nimport org.jclouds.b2.domain.B2ObjectList;\nimport org.jclouds.b2.domain.DeleteFileResponse;\nimport org.jclouds.b2.domain.HideFileResponse;\nimport org.jclouds.b2.domain.UploadFileResponse;\nimport org.jclouds.b2.domain.UploadUrlResponse;\nimport org.jclouds.b2.reference.B2Headers;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.net.HttpHeaders;\n\n\n@Test(groups = \"unit\", testName = \"ObjectApiMockTest\")\npublic final class ObjectApiMockTest {\n   private static final String BUCKET_NAME = \"BUCKET_NAME\";\n   private static final String BUCKET_ID = \"4a48fe8875c6214145260818\";\n   private static final String FILE_ID = \"4_h4a48fe8875c6214145260818_f000000000000472a_d20140104_m032022_c001_v0000123_t0104\";\n   private static final String FILE_NAME = \"typing_test.txt\";\n   private static final String CONTENT_TYPE = \"text/plain\";\n   private static final String SHA1 = \"bae5ed658ab3546aee12f23f36392f35dba1ebdd\";\n   private static final String PAYLOAD = \"The quick brown fox jumped over the lazy dog.\\n\";\n   private static final Map<String, String> FILE_INFO = ImmutableMap.of(\"author\", \"unknown\");\n\n   public void testGetUploadUrl() throws Exception {\n      MockWebServer server = createMockWebServer();\n      server.enqueue(new MockResponse().setBody(stringFromResource(\"/authorize_account_response.json\")));\n      server.enqueue(new MockResponse().setBody(stringFromResource(\"/get_upload_url_response.json\")));\n\n      try {\n         ObjectApi api = api(server.url(\"/\").toString(), \"b2\").getObjectApi();\n         UploadUrlResponse response = api.getUploadUrl(BUCKET_ID);\n         assertThat(response.bucketId()).isEqualTo(BUCKET_ID);\n         assertThat(response.uploadUrl()).isEqualTo(URI.create(\"https://pod-000-1005-03.backblaze.com/b2api/v2/b2_upload_file?cvt=c001_v0001005_t0027&bucket=4a48fe8875c6214145260818\"));\n         assertThat(response.authorizationToken()).isEqualTo(\"2_20151009170037_f504a0f39a0f4e657337e624_9754dde94359bd7b8f1445c8f4cc1a231a33f714_upld\");\n\n         assertThat(server.getRequestCount()).isEqualTo(2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"POST\", \"/b2api/v2/b2_get_upload_url\", \"/get_upload_url_request.json\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGetUploadUrlDeletedBucket() throws Exception {\n      MockWebServer server = createMockWebServer();\n      server.enqueue(new MockResponse().setBody(stringFromResource(\"/authorize_account_response.json\")));\n      server.enqueue(new MockResponse().setResponseCode(400).setBody(stringFromResource(\"/get_upload_url_deleted_bucket_response.json\")));\n\n      try {\n         ObjectApi api = api(server.url(\"/\").toString(), \"b2\").getObjectApi();\n         try {\n            api.getUploadUrl(BUCKET_ID);\n            failBecauseExceptionWasNotThrown(ContainerNotFoundException.class);\n         } catch (ContainerNotFoundException cnfe) {\n            // expected\n         }\n\n         assertThat(server.getRequestCount()).isEqualTo(2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"POST\", \"/b2api/v2/b2_get_upload_url\", \"/get_upload_url_request.json\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testUploadFile() throws Exception {\n      MockWebServer server = createMockWebServer();\n      server.enqueue(new MockResponse().setBody(stringFromResource(\"/upload_file_response.json\")));\n\n      try {\n         ObjectApi api = api(server.url(\"/\").toString(), \"b2\").getObjectApi();\n         String accountId = \"d522aa47a10f\";\n\n         UploadUrlResponse uploadUrl = UploadUrlResponse.create(BUCKET_ID, server.url(\"/b2api/v2/b2_upload_file/4a48fe8875c6214145260818/c001_v0001007_t0042\").uri(), \"FAKE-AUTHORIZATION-TOKEN\");\n         Payload payload = Payloads.newStringPayload(PAYLOAD);\n         payload.getContentMetadata().setContentType(CONTENT_TYPE);\n         UploadFileResponse response = api.uploadFile(uploadUrl, FILE_NAME, SHA1, FILE_INFO, payload);\n\n         assertThat(response.fileId()).isEqualTo(FILE_ID);\n         assertThat(response.fileName()).isEqualTo(FILE_NAME);\n         assertThat(response.accountId()).isEqualTo(accountId);\n         assertThat(response.bucketId()).isEqualTo(BUCKET_ID);\n         assertThat(response.contentLength()).isEqualTo(PAYLOAD.length());\n         assertThat(response.contentSha1()).isEqualTo(SHA1);\n         assertThat(response.contentType()).isEqualTo(CONTENT_TYPE);\n         assertThat(response.fileInfo()).isEqualTo(FILE_INFO);\n\n         assertThat(server.getRequestCount()).isEqualTo(1);\n         assertRequest(server.takeRequest(), \"POST\", \"/b2api/v2/b2_upload_file/4a48fe8875c6214145260818/c001_v0001007_t0042\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testDeleteFileVersion() throws Exception {\n      MockWebServer server = createMockWebServer();\n      server.enqueue(new MockResponse().setBody(stringFromResource(\"/authorize_account_response.json\")));\n      server.enqueue(new MockResponse().setBody(stringFromResource(\"/delete_object_response.json\")));\n\n      try {\n         ObjectApi api = api(server.url(\"/\").toString(), \"b2\").getObjectApi();\n         DeleteFileResponse response = api.deleteFileVersion(FILE_NAME, FILE_ID);\n         assertThat(response.fileName()).isEqualTo(FILE_NAME);\n         assertThat(response.fileId()).isEqualTo(FILE_ID);\n\n         assertThat(server.getRequestCount()).isEqualTo(2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"POST\", \"/b2api/v2/b2_delete_file_version\", \"/delete_object_request.json\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testDeleteAlreadyDeletedFileVersion() throws Exception {\n      MockWebServer server = createMockWebServer();\n      server.enqueue(new MockResponse().setBody(stringFromResource(\"/authorize_account_response.json\")));\n      server.enqueue(new MockResponse().setResponseCode(400).setBody(stringFromResource(\"/delete_file_version_already_deleted_response.json\")));\n\n      try {\n         ObjectApi api = api(server.url(\"/\").toString(), \"b2\").getObjectApi();\n         try {\n            api.deleteFileVersion(FILE_NAME, FILE_ID);\n            failBecauseExceptionWasNotThrown(KeyNotFoundException.class);\n         } catch (KeyNotFoundException knfe) {\n            // expected\n         }\n\n         assertThat(server.getRequestCount()).isEqualTo(2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"POST\", \"/b2api/v2/b2_delete_file_version\", \"/delete_object_request.json\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGetFileInfo() throws Exception {\n      MockWebServer server = createMockWebServer();\n      server.enqueue(new MockResponse().setBody(stringFromResource(\"/authorize_account_response.json\")));\n      server.enqueue(new MockResponse().setBody(stringFromResource(\"/get_file_info_response.json\")));\n\n      try {\n         ObjectApi api = api(server.url(\"/\").toString(), \"b2\").getObjectApi();\n         B2Object b2Object = api.getFileInfo(\"4_ze73ede9c9c8412db49f60715_f100b4e93fbae6252_d20150824_m224353_c900_v8881000_t0001\");\n         assertThat(b2Object.fileId()).isEqualTo(\"4_ze73ede9c9c8412db49f60715_f100b4e93fbae6252_d20150824_m224353_c900_v8881000_t0001\");\n         assertThat(b2Object.fileName()).isEqualTo(\"akitty.jpg\");\n         assertThat(b2Object.accountId()).isEqualTo(\"7eecc42b9675\");\n         assertThat(b2Object.bucketId()).isEqualTo(\"e73ede9c9c8412db49f60715\");\n         assertThat(b2Object.contentLength()).isEqualTo(122573);\n         assertThat(b2Object.contentSha1()).isEqualTo(\"a01a21253a07fb08a354acd30f3a6f32abb76821\");\n         assertThat(b2Object.contentType()).isEqualTo(\"image/jpeg\");\n         assertThat(b2Object.fileInfo()).isEqualTo(ImmutableMap.<String, String>of());\n         assertThat(b2Object.action()).isEqualTo(Action.UPLOAD);\n         assertThat(b2Object.uploadTimestamp()).isAfterYear(2014);\n         assertThat(b2Object.payload()).isNull();\n\n         assertThat(server.getRequestCount()).isEqualTo(2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"POST\", \"/b2api/v2/b2_get_file_info\", \"/get_file_info_request.json\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGetFileInfoDeletedFileVersion() throws Exception {\n      MockWebServer server = createMockWebServer();\n      server.enqueue(new MockResponse().setBody(stringFromResource(\"/authorize_account_response.json\")));\n      server.enqueue(new MockResponse().setResponseCode(404).setBody(stringFromResource(\"/get_file_info_deleted_file_response.json\")));\n\n      try {\n         ObjectApi api = api(server.url(\"/\").toString(), \"b2\").getObjectApi();\n         B2Object b2Object = api.getFileInfo(\"4_ze73ede9c9c8412db49f60715_f100b4e93fbae6252_d20150824_m224353_c900_v8881000_t0001\");\n         assertThat(b2Object).isNull();\n\n         assertThat(server.getRequestCount()).isEqualTo(2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"POST\", \"/b2api/v2/b2_get_file_info\", \"/get_file_info_request.json\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testDownloadFileById() throws Exception {\n      MockWebServer server = createMockWebServer();\n      server.enqueue(new MockResponse().setBody(stringFromResource(\"/authorize_account_response.json\")));\n\n      server.enqueue(new MockResponse()\n            .addHeader(HttpHeaders.CONTENT_TYPE, CONTENT_TYPE)\n            .addHeader(B2Headers.FILE_ID, FILE_ID)\n            .addHeader(B2Headers.FILE_NAME, FILE_NAME)\n            .addHeader(B2Headers.CONTENT_SHA1, SHA1)\n            .addHeader(B2Headers.UPLOAD_TIMESTAMP, String.valueOf(1500000000000L))\n            .addHeader(B2Headers.FILE_INFO_PREFIX + FILE_INFO.entrySet().iterator().next().getKey(), FILE_INFO.entrySet().iterator().next().getValue())\n            .setBody(PAYLOAD));\n\n      try {\n         ObjectApi api = api(server.url(\"/\").toString(), \"b2\").getObjectApi();\n\n         B2Object b2Object = api.downloadFileById(FILE_ID);\n\n         assertThat(b2Object.fileId()).isEqualTo(FILE_ID);\n         assertThat(b2Object.fileName()).isEqualTo(FILE_NAME);\n         assertThat(b2Object.contentSha1()).isEqualTo(SHA1);\n         assertThat(b2Object.fileInfo()).isEqualTo(FILE_INFO);\n         assertThat(b2Object.uploadTimestamp()).isAfterYear(2015);\n         assertThat(b2Object.payload().getContentMetadata().getContentLength()).isEqualTo(PAYLOAD.length());\n         assertThat(b2Object.payload().getContentMetadata().getContentType()).isEqualTo(CONTENT_TYPE);\n\n         assertThat(server.getRequestCount()).isEqualTo(2);\n\n         RecordedRequest request = server.takeRequest();\n         assertThat(request.getMethod()).isEqualTo(\"GET\");\n         assertThat(request.getPath()).isEqualTo(\"/b2api/v2/b2_authorize_account\");\n\n         request = server.takeRequest();\n         assertThat(request.getMethod()).isEqualTo(\"GET\");\n         assertThat(request.getPath()).isEqualTo(\"/b2api/v2/b2_download_file_by_id?fileId=4_h4a48fe8875c6214145260818_f000000000000472a_d20140104_m032022_c001_v0000123_t0104\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testDownloadFileByIdOptions() throws Exception {\n      MockWebServer server = createMockWebServer();\n      server.enqueue(new MockResponse().setBody(stringFromResource(\"/authorize_account_response.json\")));\n\n      server.enqueue(new MockResponse()\n            .addHeader(HttpHeaders.CONTENT_TYPE, CONTENT_TYPE)\n            .addHeader(B2Headers.FILE_ID, FILE_ID)\n            .addHeader(B2Headers.FILE_NAME, FILE_NAME)\n            .addHeader(B2Headers.CONTENT_SHA1, SHA1)\n            .addHeader(B2Headers.UPLOAD_TIMESTAMP, String.valueOf(1500000000000L))\n            .addHeader(B2Headers.FILE_INFO_PREFIX + FILE_INFO.entrySet().iterator().next().getKey(), FILE_INFO.entrySet().iterator().next().getValue())\n            .setBody(PAYLOAD));\n\n      try {\n         ObjectApi api = api(server.url(\"/\").toString(), \"b2\").getObjectApi();\n\n         B2Object b2Object = api.downloadFileById(FILE_ID, new GetOptions().range(42, 69));\n\n         assertThat(server.getRequestCount()).isEqualTo(2);\n\n         RecordedRequest request = server.takeRequest();\n         assertThat(request.getMethod()).isEqualTo(\"GET\");\n         assertThat(request.getPath()).isEqualTo(\"/b2api/v2/b2_authorize_account\");\n\n         request = server.takeRequest();\n         assertThat(request.getMethod()).isEqualTo(\"GET\");\n         assertThat(request.getPath()).isEqualTo(\"/b2api/v2/b2_download_file_by_id?fileId=4_h4a48fe8875c6214145260818_f000000000000472a_d20140104_m032022_c001_v0000123_t0104\");\n         assertThat(request.getHeaders().values(\"Range\")).contains(\"bytes=42-69\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testDownloadFileByName() throws Exception {\n      MockWebServer server = createMockWebServer();\n      server.enqueue(new MockResponse().setBody(stringFromResource(\"/authorize_account_response.json\")));\n\n      server.enqueue(new MockResponse()\n            .addHeader(HttpHeaders.CONTENT_TYPE, CONTENT_TYPE)\n            .addHeader(B2Headers.FILE_ID, FILE_ID)\n            .addHeader(B2Headers.FILE_NAME, FILE_NAME)\n            .addHeader(B2Headers.CONTENT_SHA1, SHA1)\n            .addHeader(B2Headers.UPLOAD_TIMESTAMP, String.valueOf(1500000000000L))\n            .addHeader(B2Headers.FILE_INFO_PREFIX + FILE_INFO.entrySet().iterator().next().getKey(), FILE_INFO.entrySet().iterator().next().getValue())\n            .setBody(PAYLOAD));\n\n      try {\n         ObjectApi api = api(server.url(\"/\").toString(), \"b2\").getObjectApi();\n\n         B2Object b2Object = api.downloadFileByName(BUCKET_NAME, FILE_NAME);\n\n         assertThat(b2Object.fileId()).isEqualTo(FILE_ID);\n         assertThat(b2Object.fileName()).isEqualTo(FILE_NAME);\n         assertThat(b2Object.contentSha1()).isEqualTo(SHA1);\n         assertThat(b2Object.fileInfo()).isEqualTo(FILE_INFO);\n         assertThat(b2Object.uploadTimestamp()).isAfterYear(2015);\n         assertThat(b2Object.payload().getContentMetadata().getContentLength()).isEqualTo(PAYLOAD.length());\n         assertThat(b2Object.payload().getContentMetadata().getContentType()).isEqualTo(CONTENT_TYPE);\n\n         assertThat(server.getRequestCount()).isEqualTo(2);\n\n         RecordedRequest request = server.takeRequest();\n         assertThat(request.getMethod()).isEqualTo(\"GET\");\n         assertThat(request.getPath()).isEqualTo(\"/b2api/v2/b2_authorize_account\");\n\n         request = server.takeRequest();\n         assertThat(request.getMethod()).isEqualTo(\"GET\");\n         assertThat(request.getPath()).isEqualTo(\"/file/BUCKET_NAME/typing_test.txt\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testListFileNames() throws Exception {\n      MockWebServer server = createMockWebServer();\n      server.enqueue(new MockResponse().setBody(stringFromResource(\"/authorize_account_response.json\")));\n      server.enqueue(new MockResponse().setBody(stringFromResource(\"/list_file_names_response.json\")));\n\n      try {\n         ObjectApi api = api(server.url(\"/\").toString(), \"b2\").getObjectApi();\n         String accountId = \"d522aa47a10f\";\n\n         B2ObjectList list = api.listFileNames(BUCKET_ID, null, null, null, null);\n\n         assertThat(list.nextFileName()).isNull();\n         assertThat(list.files()).hasSize(2);\n\n         B2ObjectList.Entry object = list.files().get(0);\n         assertThat(object.action()).isEqualTo(Action.UPLOAD);\n         assertThat(object.fileId()).isEqualTo(\"4_z27c88f1d182b150646ff0b16_f1004ba650fe24e6b_d20150809_m012853_c100_v0009990_t0000\");\n         assertThat(object.fileName()).isEqualTo(\"files/hello.txt\");\n         assertThat(object.size()).isEqualTo(6);\n         assertThat(object.uploadTimestamp()).isEqualTo(new Date(1439083733000L));\n\n         object = list.files().get(1);\n         assertThat(object.action()).isEqualTo(Action.UPLOAD);\n         assertThat(object.fileId()).isEqualTo(\"4_z27c88f1d182b150646ff0b16_f1004ba650fe24e6c_d20150809_m012854_c100_v0009990_t0000\");\n         assertThat(object.fileName()).isEqualTo(\"files/world.txt\");\n         assertThat(object.size()).isEqualTo(6);\n         assertThat(object.uploadTimestamp()).isEqualTo(new Date(1439083734000L));\n\n         assertThat(server.getRequestCount()).isEqualTo(2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"POST\", \"/b2api/v2/b2_list_file_names\", \"/list_file_names_request.json\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testListFileVersions() throws Exception {\n      MockWebServer server = createMockWebServer();\n      server.enqueue(new MockResponse().setBody(stringFromResource(\"/authorize_account_response.json\")));\n      server.enqueue(new MockResponse().setBody(stringFromResource(\"/list_file_versions_response.json\")));\n\n      try {\n         ObjectApi api = api(server.url(\"/\").toString(), \"b2\").getObjectApi();\n         String accountId = \"d522aa47a10f\";\n\n         B2ObjectList list = api.listFileVersions(BUCKET_ID, null, null, null, null, null);\n\n         assertThat(list.nextFileId()).isEqualTo(\"4_z27c88f1d182b150646ff0b16_f100920ddab886247_d20150809_m232316_c100_v0009990_t0003\");\n         assertThat(list.nextFileName()).isEqualTo(\"files/world.txt\");\n         assertThat(list.files()).hasSize(3);\n\n         B2ObjectList.Entry object = list.files().get(0);\n         assertThat(object.action()).isEqualTo(Action.UPLOAD);\n         assertThat(object.fileId()).isEqualTo(\"4_z27c88f1d182b150646ff0b16_f100920ddab886245_d20150809_m232316_c100_v0009990_t0003\");\n         assertThat(object.fileName()).isEqualTo(\"files/hello.txt\");\n         assertThat(object.size()).isEqualTo(6);\n         assertThat(object.uploadTimestamp()).isEqualTo(new Date(1439162596000L));\n\n         object = list.files().get(1);\n         assertThat(object.action()).isEqualTo(Action.HIDE);\n         assertThat(object.fileId()).isEqualTo(\"4_z27c88f1d182b150646ff0b16_f100920ddab886247_d20150809_m232323_c100_v0009990_t0005\");\n         assertThat(object.fileName()).isEqualTo(\"files/world.txt\");\n         assertThat(object.size()).isEqualTo(0);\n         assertThat(object.uploadTimestamp()).isEqualTo(new Date(1439162603000L));\n\n         object = list.files().get(2);\n         assertThat(object.action()).isEqualTo(Action.UPLOAD);\n         assertThat(object.fileId()).isEqualTo(\"4_z27c88f1d182b150646ff0b16_f100920ddab886246_d20150809_m232316_c100_v0009990_t0003\");\n         assertThat(object.fileName()).isEqualTo(\"files/world.txt\");\n         assertThat(object.size()).isEqualTo(6);\n         assertThat(object.uploadTimestamp()).isEqualTo(new Date(1439162596000L));\n\n         assertThat(server.getRequestCount()).isEqualTo(2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"POST\", \"/b2api/v2/b2_list_file_versions\", \"/list_file_versions_request.json\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testHideFile() throws Exception {\n      MockWebServer server = createMockWebServer();\n      server.enqueue(new MockResponse().setBody(stringFromResource(\"/authorize_account_response.json\")));\n      server.enqueue(new MockResponse().setBody(stringFromResource(\"/hide_file_response.json\")));\n\n      try {\n         ObjectApi api = api(server.url(\"/\").toString(), \"b2\").getObjectApi();\n         String accountId = \"d522aa47a10f\";\n\n         HideFileResponse response = api.hideFile(BUCKET_ID, FILE_NAME);\n         assertThat(response.action()).isEqualTo(Action.HIDE);\n         assertThat(response.fileId()).isEqualTo(\"4_h4a48fe8875c6214145260818_f000000000000472a_d20140104_m032022_c001_v0000123_t0104\");\n         assertThat(response.fileName()).isEqualTo(FILE_NAME);\n         assertThat(response.uploadTimestamp()).isEqualTo(new Date(1437815673000L));\n\n         assertThat(server.getRequestCount()).isEqualTo(2);\n         assertAuthentication(server);\n         assertRequest(server.takeRequest(), \"POST\", \"/b2api/v2/b2_hide_file\", \"/hide_file_request.json\");\n      } finally {\n         server.shutdown();\n      }\n   }\n}\n"
  },
  {
    "path": "providers/b2/src/test/java/org/jclouds/b2/internal/BaseB2ApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.b2.internal;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.apis.BaseApiLiveTest;\nimport org.jclouds.b2.B2Api;\nimport org.jclouds.b2.B2ApiMetadata;\n\npublic class BaseB2ApiLiveTest extends BaseApiLiveTest<B2Api> {\n   protected BaseB2ApiLiveTest() {\n      provider = \"b2\";\n   }\n\n   @Override\n   protected ApiMetadata createApiMetadata() {\n      return new B2ApiMetadata();\n   }\n}\n"
  },
  {
    "path": "providers/b2/src/test/resources/authorize_account_response.json",
    "content": "{\n    \"absoluteMinimumPartSize\": 5000000,\n    \"accountId\": \"YOUR_ACCOUNT_ID\",\n    \"apiUrl\": \"http://localhost\",\n    \"authorizationToken\": \"2_20150807002553_443e98bf57f978fa58c284f8_24d25d99772e3ba927778b39c9b0198f412d2163_acct\",\n    \"downloadUrl\": \"http://localhost\",\n    \"recommendedPartSize\": 100000000\n}\n"
  },
  {
    "path": "providers/b2/src/test/resources/bucket.json",
    "content": "{\n    \"bucketId\" : \"4a48fe8875c6214145260818\",\n    \"accountId\" : \"010203040506\",\n    \"bucketName\" : \"any_name_you_pick\",\n    \"bucketType\" : \"allPrivate\"\n}\n"
  },
  {
    "path": "providers/b2/src/test/resources/cancel_large_file_request.json",
    "content": "{\n    \"fileId\": \"4_za71f544e781e6891531b001a_f200ec353a2184825_d20160409_m004829_c000_v0001016_t0028\"\n}\n"
  },
  {
    "path": "providers/b2/src/test/resources/cancel_large_file_response.json",
    "content": "{\n    \"accountId\": \"YOUR_ACCOUNT_ID\",\n    \"bucketId\": \"e73ede9c9c8412db49f60715\",\n    \"fileId\": \"4_za71f544e781e6891531b001a_f200ec353a2184825_d20160409_m004829_c000_v0001016_t0028\",\n    \"fileName\": \"bigfile.dat\"\n}\n"
  },
  {
    "path": "providers/b2/src/test/resources/create_bucket_request.json",
    "content": "{\n    \"accountId\": \"YOUR_ACCOUNT_ID\",\n    \"bucketName\": \"any_name_you_pick\",\n    \"bucketType\": \"allPrivate\"\n}\n"
  },
  {
    "path": "providers/b2/src/test/resources/delete_bucket_already_deleted_response.json",
    "content": "{\n   \"status\" : 400,\n   \"code\" : \"bad_bucket_id\",\n   \"message\" : \"Bucket id 4a48fe8875c6214145260818 does not exist\"\n}\n"
  },
  {
    "path": "providers/b2/src/test/resources/delete_bucket_request.json",
    "content": "{\n    \"accountId\": \"YOUR_ACCOUNT_ID\",\n    \"bucketId\": \"4a48fe8875c6214145260818\"\n}\n"
  },
  {
    "path": "providers/b2/src/test/resources/delete_file_version_already_deleted_response.json",
    "content": "{\n   \"status\" : 400,\n   \"code\" : \"file_not_present\",\n   \"message\" : \"File not present: file-name 4_za7acecf18b053f3258580715_f1036e7f957cafbe1_d20160609_m045216_c001_v0001011_t0035\"\n}\n"
  },
  {
    "path": "providers/b2/src/test/resources/delete_object_request.json",
    "content": "{\n    \"fileName\": \"typing_test.txt\",\n    \"fileId\": \"4_h4a48fe8875c6214145260818_f000000000000472a_d20140104_m032022_c001_v0000123_t0104\"\n}\n"
  },
  {
    "path": "providers/b2/src/test/resources/delete_object_response.json",
    "content": "{\n    \"fileId\" : \"4_h4a48fe8875c6214145260818_f000000000000472a_d20140104_m032022_c001_v0000123_t0104\",\n    \"fileName\" : \"typing_test.txt\"\n}\n"
  },
  {
    "path": "providers/b2/src/test/resources/finish_large_file_request.json",
    "content": "{\n    \"partSha1Array\": [\n        \"0000000000000000000000000000000000000000\",\n        \"ffffffffffffffffffffffffffffffffffffffff\"\n    ],\n    \"fileId\": \"4_za71f544e781e6891531b001a_f200ec353a2184825_d20160409_m004829_c000_v0001016_t0028\"\n}\n"
  },
  {
    "path": "providers/b2/src/test/resources/finish_large_file_response.json",
    "content": "{\n    \"accountId\": \"YOUR_ACCOUNT_ID\",\n    \"action\": \"upload\",\n    \"bucketId\": \"e73ede9c9c8412db49f60715\",\n    \"contentLength\": 208158542,\n    \"contentSha1\": \"none\",\n    \"contentType\": \"b2/x-auto\",\n    \"fileId\": \"4_za71f544e781e6891531b001a_f200ec353a2184825_d20160409_m004829_c000_v0001016_t0028\",\n    \"fileInfo\": {\n        \"author\": \"unknown\"\n    },\n    \"fileName\": \"bigfile.dat\",\n    \"uploadTimestamp\": 1460162909000\n}\n"
  },
  {
    "path": "providers/b2/src/test/resources/get_file_info_deleted_file_response.json",
    "content": "{\n   \"status\" : 404,\n   \"code\" : \"not_found\",\n   \"message\" : \"file_state_deleted\"\n}\n"
  },
  {
    "path": "providers/b2/src/test/resources/get_file_info_request.json",
    "content": "{\n    \"fileId\": \"4_ze73ede9c9c8412db49f60715_f100b4e93fbae6252_d20150824_m224353_c900_v8881000_t0001\"\n}\n"
  },
  {
    "path": "providers/b2/src/test/resources/get_file_info_response.json",
    "content": "{\n    \"accountId\": \"7eecc42b9675\",\n    \"bucketId\": \"e73ede9c9c8412db49f60715\",\n    \"contentLength\": 122573,\n    \"contentSha1\": \"a01a21253a07fb08a354acd30f3a6f32abb76821\",\n    \"contentType\": \"image/jpeg\",\n    \"fileId\": \"4_ze73ede9c9c8412db49f60715_f100b4e93fbae6252_d20150824_m224353_c900_v8881000_t0001\",\n    \"fileInfo\": {},\n    \"fileName\": \"akitty.jpg\",\n    \"action\": \"upload\",\n    \"uploadTimestamp\": 1439083733000\n}\n"
  },
  {
    "path": "providers/b2/src/test/resources/get_upload_part_url_request.json",
    "content": "{\n    \"fileId\": \"4_za71f544e781e6891531b001a_f200ec353a2184825_d20160409_m004829_c000_v0001016_t0028\"\n}\n"
  },
  {
    "path": "providers/b2/src/test/resources/get_upload_part_url_response.json",
    "content": "{\n    \"authorizationToken\": \"3_20160409004829_42b8f80ba60fb4323dcaad98_ec81302316fccc2260201cbf17813247f312cf3b_000_uplg\",\n    \"fileId\": \"4_za71f544e781e6891531b001a_f200ec353a2184825_d20160409_m004829_c000_v0001016_t0028\",\n    \"uploadUrl\": \"https://pod-000-1016-09.backblaze.com/b2api/v2/b2_upload_part/4_ze73ede9c9c8412db49f60715_f100b4e93fbae6252_d20150824_m224353_c900_v8881000_t0001/0037\"\n}\n"
  },
  {
    "path": "providers/b2/src/test/resources/get_upload_url_deleted_bucket_response.json",
    "content": "{\n   \"status\" : 400,\n   \"code\" : \"bad_bucket_id\",\n   \"message\" : \"Bucket b7ecac119bd53f3258580715 does not exist\"\n}\n"
  },
  {
    "path": "providers/b2/src/test/resources/get_upload_url_request.json",
    "content": "{\n    \"bucketId\" : \"4a48fe8875c6214145260818\"\n}\n"
  },
  {
    "path": "providers/b2/src/test/resources/get_upload_url_response.json",
    "content": "{\n    \"bucketId\" : \"4a48fe8875c6214145260818\",\n    \"uploadUrl\" : \"https://pod-000-1005-03.backblaze.com/b2api/v2/b2_upload_file?cvt=c001_v0001005_t0027&bucket=4a48fe8875c6214145260818\",\n    \"authorizationToken\" : \"2_20151009170037_f504a0f39a0f4e657337e624_9754dde94359bd7b8f1445c8f4cc1a231a33f714_upld\"\n}\n"
  },
  {
    "path": "providers/b2/src/test/resources/hide_file_request.json",
    "content": "{\n    \"bucketId\": \"4a48fe8875c6214145260818\",\n    \"fileName\": \"typing_test.txt\"\n}\n"
  },
  {
    "path": "providers/b2/src/test/resources/hide_file_response.json",
    "content": "{\n    \"action\" : \"hide\",\n    \"accountId\" : \"d522aa47a10f\",\n    \"bucketId\" : \"4a48fe8875c6214145260818\",\n    \"fileId\" : \"4_h4a48fe8875c6214145260818_f000000000000472a_d20140104_m032022_c001_v0000123_t0104\",\n    \"fileName\" : \"typing_test.txt\",\n    \"uploadTimestamp\" : 1437815673000\n}\n"
  },
  {
    "path": "providers/b2/src/test/resources/list_buckets_request.json",
    "content": "{\n    \"accountId\": \"YOUR_ACCOUNT_ID\"\n}\n"
  },
  {
    "path": "providers/b2/src/test/resources/list_buckets_response.json",
    "content": "{\n    \"buckets\": [\n    {\n        \"bucketId\": \"4a48fe8875c6214145260818\",\n        \"accountId\": \"30f20426f0b1\",\n        \"bucketName\" : \"Kitten Videos\",\n        \"bucketType\": \"allPrivate\"\n    },\n    {\n        \"bucketId\" : \"5b232e8875c6214145260818\",\n        \"accountId\": \"30f20426f0b1\",\n        \"bucketName\": \"Puppy Videos\",\n        \"bucketType\": \"allPublic\"\n    },\n    {\n        \"bucketId\": \"87ba238875c6214145260818\",\n        \"accountId\": \"30f20426f0b1\",\n        \"bucketName\": \"Vacation Pictures\",\n        \"bucketType\" : \"allPrivate\"\n    } ]\n}\n"
  },
  {
    "path": "providers/b2/src/test/resources/list_file_names_request.json",
    "content": "{\n    \"bucketId\": \"4a48fe8875c6214145260818\"\n}\n"
  },
  {
    "path": "providers/b2/src/test/resources/list_file_names_response.json",
    "content": "{\n    \"files\": [\n        {\n            \"action\": \"upload\",\n            \"accountId\" : \"d522aa47a10f\",\n            \"bucketId\" : \"4a48fe8875c6214145260818\",\n            \"fileId\": \"4_z27c88f1d182b150646ff0b16_f1004ba650fe24e6b_d20150809_m012853_c100_v0009990_t0000\",\n            \"fileName\": \"files/hello.txt\",\n            \"contentLength\": 6,\n            \"uploadTimestamp\": 1439083733000\n        },\n        {\n            \"action\": \"upload\",\n            \"accountId\" : \"d522aa47a10f\",\n            \"bucketId\" : \"4a48fe8875c6214145260818\",\n            \"fileId\": \"4_z27c88f1d182b150646ff0b16_f1004ba650fe24e6c_d20150809_m012854_c100_v0009990_t0000\",\n            \"fileName\": \"files/world.txt\",\n            \"contentLength\": 6,\n            \"uploadTimestamp\": 1439083734000\n        }\n    ],\n    \"nextFileName\": null\n}\n"
  },
  {
    "path": "providers/b2/src/test/resources/list_file_versions_request.json",
    "content": "{\n   \"bucketId\": \"4a48fe8875c6214145260818\"\n}\n"
  },
  {
    "path": "providers/b2/src/test/resources/list_file_versions_response.json",
    "content": "{\n    \"files\": [\n        {\n            \"action\": \"upload\",\n            \"accountId\" : \"d522aa47a10f\",\n            \"bucketId\" : \"4a48fe8875c6214145260818\",\n            \"fileId\": \"4_z27c88f1d182b150646ff0b16_f100920ddab886245_d20150809_m232316_c100_v0009990_t0003\",\n            \"fileName\": \"files/hello.txt\",\n            \"contentLength\": 6,\n            \"uploadTimestamp\": 1439162596000\n        },\n        {\n            \"action\": \"hide\",\n            \"accountId\" : \"d522aa47a10f\",\n            \"bucketId\" : \"4a48fe8875c6214145260818\",\n            \"fileId\": \"4_z27c88f1d182b150646ff0b16_f100920ddab886247_d20150809_m232323_c100_v0009990_t0005\",\n            \"fileName\": \"files/world.txt\",\n            \"contentLength\": 0,\n            \"uploadTimestamp\": 1439162603000\n        },\n        {\n            \"action\": \"upload\",\n            \"accountId\" : \"d522aa47a10f\",\n            \"bucketId\" : \"4a48fe8875c6214145260818\",\n            \"fileId\": \"4_z27c88f1d182b150646ff0b16_f100920ddab886246_d20150809_m232316_c100_v0009990_t0003\",\n            \"fileName\": \"files/world.txt\",\n            \"contentLength\": 6,\n            \"uploadTimestamp\": 1439162596000\n        }\n    ],\n    \"nextFileId\": \"4_z27c88f1d182b150646ff0b16_f100920ddab886247_d20150809_m232316_c100_v0009990_t0003\",\n    \"nextFileName\": \"files/world.txt\"\n}\n"
  },
  {
    "path": "providers/b2/src/test/resources/list_parts_request.json",
    "content": "{\n    \"fileId\": \"4_za71f544e781e6891531b001a_f200ec353a2184825_d20160409_m004829_c000_v0001016_t0028\",\n    \"startPartNumber\": 1,\n    \"maxPartCount\": 1000\n}\n"
  },
  {
    "path": "providers/b2/src/test/resources/list_parts_response.json",
    "content": "{\n    \"nextPartNumber\": null,\n    \"parts\": [\n        {\n            \"contentLength\": 100000000,\n            \"contentSha1\": \"062685a84ab248d2488f02f6b01b948de2514ad8\",\n            \"fileId\": \"4_ze73ede9c9c8412db49f60715_f100b4e93fbae6252_d20150824_m224353_c900_v8881000_t0001\",\n            \"partNumber\": 1,\n            \"uploadTimestamp\": 1462212185000\n        },\n        {\n            \"contentLength\": 100000000,\n            \"contentSha1\": \"cf634751c3d9f6a15344f23cbf13f3fc9542addf\",\n            \"fileId\": \"4_ze73ede9c9c8412db49f60715_f100b4e93fbae6252_d20150824_m224353_c900_v8881000_t0001\",\n            \"partNumber\": 2,\n            \"uploadTimestamp\": 1462212296000\n        },\n        {\n            \"contentLength\": 8158554,\n            \"contentSha1\": \"00ad164147cbbd60aedb2b04ff66b0f74f962753\",\n            \"fileId\": \"4_ze73ede9c9c8412db49f60715_f100b4e93fbae6252_d20150824_m224353_c900_v8881000_t0001\",\n            \"partNumber\": 3,\n            \"uploadTimestamp\": 1462212327000\n        }\n    ]\n}\n"
  },
  {
    "path": "providers/b2/src/test/resources/list_unfinished_large_files_request.json",
    "content": "{\n    \"bucketId\": \"e73ede9c9c8412db49f60715\",\n    \"startFileId\": \"4_za71f544e781e6891531b001a_f200ec353a2184825_d20160409_m004829_c000_v0001016_t0028\",\n    \"maxFileCount\": 1000\n}\n"
  },
  {
    "path": "providers/b2/src/test/resources/list_unfinished_large_files_response.json",
    "content": "{\n    \"action\": \"upload\",\n    \"files\": [\n        {\n            \"accountId\": \"YOUR_ACCOUNT_ID\",\n            \"action\": \"upload\",\n            \"bucketId\": \"e73ede9c9c8412db49f60715\",\n            \"contentType\": \"application/octet-stream\",\n            \"fileId\": \"4_ze73ede9c9c8412db49f60715_f100b4e93fbae6252_d20150824_m224353_c900_v8881000_t0001\",\n            \"fileInfo\": {\n                \"author\": \"unknown\"\n            },\n            \"fileName\": \"bigfile.dat\",\n            \"uploadTimestamp\": 1462212184000\n        }\n    ],\n    \"nextFileId\": null\n}\n"
  },
  {
    "path": "providers/b2/src/test/resources/log4j.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE log4j:configuration SYSTEM \"log4j.dtd\">\n\n    <!--\n        For more configuration infromation and examples see the Apache\n        Log4j website: http://logging.apache.org/log4j/\n    -->\n<log4j:configuration xmlns:log4j=\"http://jakarta.apache.org/log4j/\"\n    debug=\"false\">\n\n    <!-- A time/date based rolling appender -->\n    <appender name=\"WIREFILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds-wire.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n\n    <!-- A time/date based rolling appender -->\n    <appender name=\"FILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n    <!-- A time/date based rolling appender -->\n    <appender name=\"BLOBSTOREFILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds-blobstore.log\" />\n        <param name=\"Append\" value=\"true\" />\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n        <param name=\"Threshold\" value=\"TRACE\" />\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n        </layout>\n    </appender>\n\n    <appender name=\"ASYNC\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"FILE\" />\n    </appender>\n\n    <appender name=\"ASYNCWIRE\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"WIREFILE\" />\n    </appender>\n\n    <appender name=\"ASYNCBLOBSTORE\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"BLOBSTOREFILE\" />\n    </appender>\n    <!-- ================ -->\n    <!-- Limit categories -->\n    <!-- ================ -->\n\n    <category name=\"org.jclouds\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNC\" />\n    </category>\n\n    <category name=\"jclouds.headers\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNCWIRE\" />\n    </category>\n    <category name=\"jclouds.wire\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNCWIRE\" />\n    </category>\n    <category name=\"jclouds.blobstore\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNCBLOBSTORE\" />\n    </category>\n    <!-- ======================= -->\n    <!-- Setup the Root category -->\n    <!-- ======================= -->\n\n    <root>\n        <priority value=\"WARN\" />\n    </root>\n\n</log4j:configuration>\n"
  },
  {
    "path": "providers/b2/src/test/resources/start_large_file_request.json",
    "content": "{\n    \"fileName\": \"bigfile.dat\",\n    \"bucketId\": \"e73ede9c9c8412db49f60715\",\n    \"contentType\": \"b2/x-auto\",\n    \"fileInfo\": {\n        \"author\": \"unknown\"\n    }\n}\n"
  },
  {
    "path": "providers/b2/src/test/resources/start_large_file_response.json",
    "content": "{\n    \"action\": \"upload\",\n    \"accountId\": \"YOUR_ACCOUNT_ID\",\n    \"bucketId\": \"e73ede9c9c8412db49f60715\",\n    \"contentLength\": null,\n    \"contentSha1\": null,\n    \"contentType\": \"b2/x-auto\",\n    \"fileId\": \"4_za71f544e781e6891531b001a_f200ec353a2184825_d20160409_m004829_c000_v0001016_t0028\",\n    \"fileInfo\": {\n        \"author\": \"unknown\"\n    },\n    \"fileName\": \"bigfile.dat\",\n    \"uploadTimestamp\": 1460162909000\n}\n"
  },
  {
    "path": "providers/b2/src/test/resources/update_bucket_request.json",
    "content": "{\n    \"accountId\": \"YOUR_ACCOUNT_ID\",\n    \"bucketId\": \"4a48fe8875c6214145260818\",\n    \"bucketType\": \"allPrivate\"\n}\n"
  },
  {
    "path": "providers/b2/src/test/resources/upload_file_response.json",
    "content": "{\n    \"fileId\" : \"4_h4a48fe8875c6214145260818_f000000000000472a_d20140104_m032022_c001_v0000123_t0104\",\n    \"fileName\" : \"typing_test.txt\",\n    \"accountId\" : \"d522aa47a10f\",\n    \"bucketId\" : \"4a48fe8875c6214145260818\",\n    \"contentLength\" : 46,\n    \"contentSha1\" : \"bae5ed658ab3546aee12f23f36392f35dba1ebdd\",\n    \"contentType\" : \"text/plain\",\n    \"uploadTimestamp\" : 0,\n    \"fileInfo\" : {\n        \"author\" : \"unknown\"\n    }\n}\n"
  },
  {
    "path": "providers/b2/src/test/resources/upload_part_response.json",
    "content": "{\n    \"contentLength\": 100000000,\n    \"contentSha1\": \"062685a84ab248d2488f02f6b01b948de2514ad8\",\n    \"fileId\": \"4_za71f544e781e6891531b001a_f200ec353a2184825_d20160409_m004829_c000_v0001016_t0028\",\n    \"partNumber\": 1\n}\n"
  },
  {
    "path": "providers/digitalocean2/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.digitalocean2.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "providers/digitalocean2/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n  xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n\n  <groupId>org.apache.jclouds.provider</groupId>\n  <artifactId>digitalocean2</artifactId>\n  <name>jclouds DigitalOcean v2 API Provider</name>\n  <description>jclouds provider for Digital Ocean v2 Compute API</description>\n\n  <properties>\n    <test.digitalocean2.endpoint>https://api.digitalocean.com/v2/</test.digitalocean2.endpoint>\n    <test.digitalocean2.api-version>2</test.digitalocean2.api-version>\n    <test.digitalocean2.identity>FIXME</test.digitalocean2.identity>\n    <test.digitalocean2.credential>FIXME</test.digitalocean2.credential>\n    <test.digitalocean2.template>osFamily=UBUNTU,os64Bit=true,osVersionMatches=16.*</test.digitalocean2.template>\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>oauth</artifactId>\n      <version>${project.version}</version>\n      <type>jar</type>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>oauth</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-slf4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-sshj</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>ch.qos.logback</groupId>\n      <artifactId>logback-classic</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.squareup.okhttp3</groupId>\n      <artifactId>mockwebserver</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.value</groupId>\n      <artifactId>auto-value</artifactId>\n      <scope>provided</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <scope>provided</scope>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.digitalocean2.endpoint>${test.digitalocean2.endpoint}</test.digitalocean2.endpoint>\n                    <test.digitalocean2.api-version>${test.digitalocean2.api-version}</test.digitalocean2.api-version>\n                    <test.digitalocean2.build-version>${test.digitalocean2.build-version}</test.digitalocean2.build-version>\n                    <test.digitalocean2.identity>${test.digitalocean2.identity}</test.digitalocean2.identity>\n                    <test.digitalocean2.credential>${test.digitalocean2.credential}</test.digitalocean2.credential>\n                    <test.digitalocean2.template>${test.digitalocean2.template}</test.digitalocean2.template>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n</project>\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/DigitalOcean2Api.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2;\n\nimport java.io.Closeable;\n\nimport org.jclouds.digitalocean2.features.ActionApi;\nimport org.jclouds.digitalocean2.features.DropletApi;\nimport org.jclouds.digitalocean2.features.ImageApi;\nimport org.jclouds.digitalocean2.features.KeyApi;\nimport org.jclouds.digitalocean2.features.RegionApi;\nimport org.jclouds.digitalocean2.features.SizeApi;\nimport org.jclouds.rest.annotations.Delegate;\n\nimport com.google.common.annotations.Beta;\n\n/**\n * Provides access to DigitalOcean.\n */\n@Beta\npublic interface DigitalOcean2Api extends Closeable {\n\n   /**\n    * Provides access to Droplet features\n    */\n   @Delegate\n   DropletApi dropletApi();\n\n   /**\n    * Provides access to SSH Key features\n    */\n   @Delegate\n   KeyApi keyApi();\n\n   /**\n    * Provides access to Images\n    */\n   @Delegate\n   ImageApi imageApi();\n\n   /**\n    * Provides access to Actions\n    */\n   @Delegate\n   ActionApi actionApi();\n\n   /**\n    * Provides access to Sizes\n    */\n   @Delegate\n   SizeApi sizeApi();\n\n   /**\n    * Provides access to Regions\n    */\n   @Delegate\n   RegionApi regionApi();\n\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/DigitalOcean2ApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2;\n\nimport static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL;\nimport static org.jclouds.compute.config.ComputeServiceProperties.POLL_INITIAL_PERIOD;\nimport static org.jclouds.compute.config.ComputeServiceProperties.POLL_MAX_PERIOD;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TEMPLATE;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_RUNNING;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_SUSPENDED;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_TERMINATED;\nimport static org.jclouds.oauth.v2.config.CredentialType.BEARER_TOKEN_CREDENTIALS;\nimport static org.jclouds.oauth.v2.config.OAuthProperties.AUDIENCE;\nimport static org.jclouds.oauth.v2.config.OAuthProperties.CREDENTIAL_TYPE;\nimport static org.jclouds.oauth.v2.config.OAuthProperties.JWS_ALG;\nimport static org.jclouds.reflect.Reflection2.typeToken;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.digitalocean2.compute.config.DigitalOcean2ComputeServiceContextModule;\nimport org.jclouds.digitalocean2.config.DigitalOcean2HttpApiModule;\nimport org.jclouds.digitalocean2.config.DigitalOceanParserModule;\nimport org.jclouds.oauth.v2.config.OAuthModule;\nimport org.jclouds.rest.internal.BaseHttpApiMetadata;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n/**\n * Implementation of {@link ApiMetadata} for DigitalOcean v2 API\n */\npublic class DigitalOcean2ApiMetadata extends BaseHttpApiMetadata<DigitalOcean2Api> {\n\n   @Override\n   public Builder toBuilder() {\n      return new Builder().fromApiMetadata(this);\n   }\n\n   public DigitalOcean2ApiMetadata() {\n      this(new Builder());\n   }\n\n   protected DigitalOcean2ApiMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = BaseHttpApiMetadata.defaultProperties();\n      properties.put(\"oauth.endpoint\", \"https://cloud.digitalocean.com/v1/oauth/token\");\n      properties.put(JWS_ALG, \"RS256\");\n      properties.put(AUDIENCE, \"https://cloud.digitalocean.com/v1/oauth/token\");\n      properties.put(CREDENTIAL_TYPE, BEARER_TOKEN_CREDENTIALS.toString());\n      properties.put(PROPERTY_SESSION_INTERVAL, 3600);\n      properties.put(TEMPLATE, \"osFamily=UBUNTU,os64Bit=true,osVersionMatches=16.*\");\n      properties.put(POLL_INITIAL_PERIOD, 5000);\n      properties.put(POLL_MAX_PERIOD, 20000);\n      // Node operations in DigitalOcean can be quite slow. Use a 5 minutes\n      // timeout by default\n      properties.put(TIMEOUT_NODE_RUNNING, 300000);\n      properties.put(TIMEOUT_NODE_SUSPENDED, 300000);\n      properties.put(TIMEOUT_NODE_TERMINATED, 300000);\n      return properties;\n   }\n\n   public static class Builder extends BaseHttpApiMetadata.Builder<DigitalOcean2Api, Builder> {\n\n      protected Builder() {\n         id(\"digitalocean2\")\n                 .name(\"Digital Ocean v2 API\")\n                 .identityName(\"Not used for OAuth\")\n                 .credentialName(\"Must be oauth2 Bearer Token\")\n                 .documentation(URI.create(\"https://developers.digitalocean.com/v2/\"))\n                 .defaultEndpoint(\"https://api.digitalocean.com/v2\")\n                 .defaultProperties(DigitalOcean2ApiMetadata.defaultProperties())\n                 .view(typeToken(ComputeServiceContext.class))\n                 .defaultModules(ImmutableSet.<Class<? extends Module>>builder()\n                       .add(DigitalOcean2HttpApiModule.class)\n                       .add(OAuthModule.class)\n                       .add(DigitalOceanParserModule.class)\n                       .add(DigitalOcean2ComputeServiceContextModule.class)\n                       .build());\n      }\n\n      @Override\n      public DigitalOcean2ApiMetadata build() {\n         return new DigitalOcean2ApiMetadata(this);\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/DigitalOcean2ProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\n\nimport com.google.auto.service.AutoService;\n\n/**\n * Implementation of {@link org.jclouds.providers.ProviderMetadata} for DigitalOcean.\n */\n@AutoService(ProviderMetadata.class)\npublic class DigitalOcean2ProviderMetadata extends BaseProviderMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromProviderMetadata(this);\n   }\n\n   public DigitalOcean2ProviderMetadata() {\n      super(builder());\n   }\n\n   public DigitalOcean2ProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = DigitalOcean2ApiMetadata.defaultProperties();\n      return properties;\n   }\n\n   public static class Builder extends BaseProviderMetadata.Builder {\n\n      protected Builder() {\n         id(\"digitalocean2\")\n            .name(\"DigitalOcean Compute Services\")\n            .apiMetadata(new DigitalOcean2ApiMetadata())\n            .homepage(URI.create(\"https://www.digitalocean.com/\"))\n            .console(URI.create(\"https://cloud.digitalocean.com/\"))\n            .endpoint(\"https://api.digitalocean.com/v2\")\n            .defaultProperties(DigitalOcean2ProviderMetadata.defaultProperties());\n      }\n\n      @Override\n      public DigitalOcean2ProviderMetadata build() {\n         return new DigitalOcean2ProviderMetadata(this);\n      }\n\n      @Override\n      public Builder fromProviderMetadata(ProviderMetadata in) {\n         super.fromProviderMetadata(in);\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/compute/DigitalOcean2ComputeServiceAdapter.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.compute;\n\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.common.base.Predicates.notNull;\nimport static com.google.common.collect.Iterables.concat;\nimport static com.google.common.collect.Iterables.contains;\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.transform;\nimport static com.google.common.collect.Sets.newHashSet;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_RUNNING;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_SUSPENDED;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_TERMINATED;\n\nimport java.util.List;\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\n\nimport org.jclouds.compute.ComputeServiceAdapter;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.digitalocean2.DigitalOcean2Api;\nimport org.jclouds.digitalocean2.compute.internal.ImageInRegion;\nimport org.jclouds.digitalocean2.compute.options.DigitalOcean2TemplateOptions;\nimport org.jclouds.digitalocean2.domain.Droplet;\nimport org.jclouds.digitalocean2.domain.DropletCreate;\nimport org.jclouds.digitalocean2.domain.Image;\nimport org.jclouds.digitalocean2.domain.Region;\nimport org.jclouds.digitalocean2.domain.Size;\nimport org.jclouds.digitalocean2.domain.options.CreateDropletOptions;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.primitives.Ints;\n\n/**\n * Implementation of the Compute Service for the DigitalOcean API.\n */\npublic class DigitalOcean2ComputeServiceAdapter implements ComputeServiceAdapter<Droplet, Size, ImageInRegion, Region> {\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   private final DigitalOcean2Api api;\n   private final Predicate<Integer> nodeRunningPredicate;\n   private final Predicate<Integer> nodeStoppedPredicate;\n   private final Predicate<Integer> nodeTerminatedPredicate;\n\n   @Inject DigitalOcean2ComputeServiceAdapter(DigitalOcean2Api api,\n         @Named(TIMEOUT_NODE_RUNNING) Predicate<Integer> nodeRunningPredicate,\n         @Named(TIMEOUT_NODE_SUSPENDED) Predicate<Integer> nodeStoppedPredicate,\n         @Named(TIMEOUT_NODE_TERMINATED) Predicate<Integer> nodeTerminatedPredicate) {\n      this.api = api;\n      this.nodeRunningPredicate = nodeRunningPredicate;\n      this.nodeStoppedPredicate = nodeStoppedPredicate;\n      this.nodeTerminatedPredicate = nodeTerminatedPredicate;\n   }\n\n   private void setUserDataIfSupported(Template template, CreateDropletOptions.Builder options, String userData) {\n      @SuppressWarnings(\"unchecked\")\n      List<String> regionFeatures = (List<String>) template.getLocation().getMetadata().get(\"features\");\n      if (regionFeatures.contains(\"metadata\")) {\n         options.userData(userData);\n      } else {\n         logger.debug(\">> region %s does not support metadata, ignoring provided user data\", template.getLocation()\n               .getId());\n      }\n   }\n\n   @Override\n   public NodeAndInitialCredentials<Droplet> createNodeWithGroupEncodedIntoName(String group, final String name,\n         Template template) {\n      DigitalOcean2TemplateOptions templateOptions = template.getOptions().as(DigitalOcean2TemplateOptions.class);\n      CreateDropletOptions.Builder options = CreateDropletOptions.builder();\n\n      // DigitalOcean specific options\n      options.privateNetworking(templateOptions.getPrivateNetworking());\n      options.backupsEnabled(templateOptions.getBackupsEnabled());\n      if (!templateOptions.getSshKeyIds().isEmpty()) {\n         options.addSshKeyIds(templateOptions.getSshKeyIds());\n      }\n\n      // In DigitalOcean, user_data is a SINGLE string, NOT a map!\n      // Encoding tags or anything else than user_data in here breaks their functionality.\n      if (null != templateOptions.getUserData()) {\n         setUserDataIfSupported(template, options, new String(templateOptions.getUserData()));\n      } else if (null != templateOptions.getUserMetadata().get(\"user_data\")) {\n         // Backwards compatible variant, getting userData from userMetaData map.\n         setUserDataIfSupported(template, options, templateOptions.getUserMetadata().get(\"user_data\"));\n      }\n\n      DropletCreate dropletCreated = api.dropletApi().create(name,\n            template.getLocation().getId(),\n            template.getHardware().getProviderId(),\n            template.getImage().getProviderId(),\n            options.build());\n\n      // We have to actively wait until the droplet has been provisioned until\n      // we can build the entire Droplet object we want to return\n      nodeRunningPredicate.apply(dropletCreated.droplet().id());\n      Droplet droplet = api.dropletApi().get(dropletCreated.droplet().id());\n\n      LoginCredentials defaultCredentials = LoginCredentials.builder().user(\"root\")\n            .privateKey(templateOptions.getLoginPrivateKey()).build();\n\n      return new NodeAndInitialCredentials<Droplet>(droplet, String.valueOf(droplet.id()), defaultCredentials);\n   }\n\n   @Override\n   public Iterable<ImageInRegion> listImages() {\n      // Images can claim to be available in a region that is currently marked as \"unavailable\". We shouldn't return\n      // the images scoped to those regions.\n      final Set<String> availableRegionsIds = newHashSet(transform(listLocations(), new Function<Region, String>() {\n         @Override\n         public String apply(Region input) {\n            return input.slug();\n         }\n      }));\n\n      // Public images re globally available, but non-public ones can only be available in certain regions.\n      // For these kind of images, return one instance of an ImageInRegion for each region where the image is\n      // available. This way we can properly scope global and concrete images so they can be properly looked up.\n      return concat(filter(api.imageApi().list().concat().transform(new Function<Image, Iterable<ImageInRegion>>() {\n         @Override\n         public Iterable<ImageInRegion> apply(final Image image) {\n            return transform(image.regions(), new Function<String, ImageInRegion>() {\n               @Override\n               public ImageInRegion apply(String region) {\n                  return availableRegionsIds.contains(region) ? ImageInRegion.create(image, region) : null;\n               }\n            });\n         }\n      }), notNull()));\n   }\n\n   @Override\n   public Iterable<Size> listHardwareProfiles() {\n      return filter(api.sizeApi().list().concat(), new Predicate<Size>() {\n         @Override\n         public boolean apply(Size size) {\n            return size.available();\n         }\n      });\n   }\n\n   @Override\n   public Iterable<Region> listLocations() {\n      // DigitalOcean lists regions that are unavailable for droplet creation\n      return filter(api.regionApi().list().concat(), new Predicate<Region>() {\n         @Override\n         public boolean apply(Region region) {\n            return region.available();\n         }\n      });\n   }\n\n   @Override\n   public Iterable<Droplet> listNodes() {\n      return api.dropletApi().list().concat();\n   }\n\n   @Override\n   public Iterable<Droplet> listNodesByIds(final Iterable<String> ids) {\n      return filter(listNodes(), new Predicate<Droplet>() {\n         @Override\n         public boolean apply(Droplet droplet) {\n            return contains(ids, String.valueOf(droplet.id()));\n         }\n      });\n   }\n\n   @Override\n   public ImageInRegion getImage(String id) {\n      String region = ImageInRegion.extractRegion(id);\n      String imageId = ImageInRegion.extractImageId(id);\n      // The id of the image can be an id or a slug. Use the corresponding method of the API depending on what is\n      // provided. If it can be parsed as a number, use the method to get by ID. Otherwise, get by slug.\n      Integer numericId = Ints.tryParse(imageId);\n      Image image = numericId == null ? api.imageApi().get(imageId) : api.imageApi().get(numericId);\n      return image == null ? null : ImageInRegion.create(image, region);\n   }\n\n   @Override\n   public Droplet getNode(String id) {\n      return api.dropletApi().get(Integer.parseInt(id));\n   }\n\n   @Override\n   public void destroyNode(String id) {\n      // We have to wait here, as the api does not properly populate the state\n      // but fails if there is a pending event\n      int dropletId = Integer.parseInt(id);\n      api.dropletApi().delete(dropletId);\n      checkState(nodeTerminatedPredicate.apply(dropletId), \"node was not destroyed in the configured timeout\");\n   }\n\n   @Override\n   public void rebootNode(String id) {\n      // We have to wait here, as the api does not properly populate the state\n      // but fails if there is a pending event\n      int dropletId = Integer.parseInt(id);\n      api.dropletApi().reboot(dropletId);\n      checkState(nodeRunningPredicate.apply(dropletId), \"node did not restart in the configured timeout\");\n   }\n\n   @Override\n   public void resumeNode(String id) {\n      // We have to wait here, as the api does not properly populate the state\n      // but fails if there is a pending event\n      int dropletId = Integer.parseInt(id);\n      api.dropletApi().powerOn(dropletId);\n      checkState(nodeRunningPredicate.apply(dropletId), \"node did not started in the configured timeout\");\n   }\n\n   @Override\n   public void suspendNode(String id) {\n      // We have to wait here, as the api does not properly populate the state\n      // but fails if there is a pending event\n      int dropletId = Integer.parseInt(id);\n      api.dropletApi().powerOff(dropletId);\n      checkState(nodeStoppedPredicate.apply(dropletId), \"node did not stop in the configured timeout\");\n   }\n\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/compute/config/DigitalOcean2ComputeServiceContextModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.compute.config;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_IMAGE_AVAILABLE;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_RUNNING;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_SUSPENDED;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_TERMINATED;\nimport static org.jclouds.util.Predicates2.retry;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.ComputeServiceAdapter;\nimport org.jclouds.compute.config.ComputeServiceAdapterContextModule;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadata.Status;\nimport org.jclouds.compute.extensions.ImageExtension;\nimport org.jclouds.compute.functions.NodeAndTemplateOptionsToStatement;\nimport org.jclouds.compute.functions.NodeAndTemplateOptionsToStatementWithoutPublicKey;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.compute.reference.ComputeServiceConstants.PollPeriod;\nimport org.jclouds.compute.reference.ComputeServiceConstants.Timeouts;\nimport org.jclouds.compute.strategy.CreateNodesInGroupThenAddToSet;\nimport org.jclouds.digitalocean2.DigitalOcean2Api;\nimport org.jclouds.digitalocean2.compute.DigitalOcean2ComputeServiceAdapter;\nimport org.jclouds.digitalocean2.compute.extensions.DigitalOcean2ImageExtension;\nimport org.jclouds.digitalocean2.compute.functions.DropletStatusToStatus;\nimport org.jclouds.digitalocean2.compute.functions.DropletToNodeMetadata;\nimport org.jclouds.digitalocean2.compute.functions.ImageInRegionToImage;\nimport org.jclouds.digitalocean2.compute.functions.RegionToLocation;\nimport org.jclouds.digitalocean2.compute.functions.SizeToHardware;\nimport org.jclouds.digitalocean2.compute.internal.ImageInRegion;\nimport org.jclouds.digitalocean2.compute.options.DigitalOcean2TemplateOptions;\nimport org.jclouds.digitalocean2.compute.strategy.CreateKeyPairsThenCreateNodes;\nimport org.jclouds.digitalocean2.domain.Action;\nimport org.jclouds.digitalocean2.domain.Droplet;\nimport org.jclouds.digitalocean2.domain.Region;\nimport org.jclouds.digitalocean2.domain.Size;\nimport org.jclouds.domain.Location;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.inject.Provides;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.name.Named;\n\n/**\n * Configures the compute service classes for the DigitalOcean API.\n */\npublic class DigitalOcean2ComputeServiceContextModule extends\n      ComputeServiceAdapterContextModule<Droplet, Size, ImageInRegion, Region> {\n\n   @Override\n   protected void configure() {\n      super.configure();\n\n      bind(new TypeLiteral<ComputeServiceAdapter<Droplet, Size, ImageInRegion, Region>>() {\n      }).to(DigitalOcean2ComputeServiceAdapter.class);\n\n      bind(new TypeLiteral<Function<Droplet, NodeMetadata>>() {\n      }).to(DropletToNodeMetadata.class);\n      bind(new TypeLiteral<Function<ImageInRegion, Image>>() {\n      }).to(ImageInRegionToImage.class);\n      bind(new TypeLiteral<Function<Region, Location>>() {\n      }).to(RegionToLocation.class);\n      bind(new TypeLiteral<Function<Size, Hardware>>() {\n      }).to(SizeToHardware.class);\n      bind(new TypeLiteral<Function<Droplet.Status, Status>>() {\n      }).to(DropletStatusToStatus.class);\n\n      install(new LocationsFromComputeServiceAdapterModule<Droplet, Size, ImageInRegion, Region>() {\n      });\n\n      bind(CreateNodesInGroupThenAddToSet.class).to(CreateKeyPairsThenCreateNodes.class);\n      bind(TemplateOptions.class).to(DigitalOcean2TemplateOptions.class);\n      bind(NodeAndTemplateOptionsToStatement.class).to(NodeAndTemplateOptionsToStatementWithoutPublicKey.class);\n\n      bind(new TypeLiteral<ImageExtension>() {\n      }).to(DigitalOcean2ImageExtension.class);\n   }\n\n   @Provides\n   @Named(TIMEOUT_NODE_RUNNING)\n   protected Predicate<Integer> provideDropletRunningPredicate(final DigitalOcean2Api api, Timeouts timeouts,\n         PollPeriod pollPeriod) {\n      return retry(new DropletInStatusPredicate(api, Droplet.Status.ACTIVE), timeouts.nodeRunning,\n            pollPeriod.pollInitialPeriod, pollPeriod.pollMaxPeriod);\n   }\n\n   @Provides\n   @Named(TIMEOUT_NODE_SUSPENDED)\n   protected Predicate<Integer> provideDropletSuspendedPredicate(final DigitalOcean2Api api, Timeouts timeouts,\n         PollPeriod pollPeriod) {\n      return retry(new DropletInStatusPredicate(api, Droplet.Status.OFF), timeouts.nodeSuspended,\n            pollPeriod.pollInitialPeriod, pollPeriod.pollMaxPeriod);\n   }\n\n   @Provides\n   @Named(TIMEOUT_NODE_TERMINATED)\n   protected Predicate<Integer> provideDropletTerminatedPredicate(final DigitalOcean2Api api, Timeouts timeouts,\n         PollPeriod pollPeriod) {\n      return retry(new DropletTerminatedPredicate(api), timeouts.nodeTerminated, pollPeriod.pollInitialPeriod,\n            pollPeriod.pollMaxPeriod);\n   }\n\n   @Provides\n   @Named(TIMEOUT_IMAGE_AVAILABLE)\n   protected Predicate<Long> provideImageAvailablePredicate(final DigitalOcean2Api api, Timeouts timeouts,\n         PollPeriod pollPeriod) {\n      return retry(new ActionDonePredicate(api), timeouts.imageAvailable, pollPeriod.pollInitialPeriod,\n            pollPeriod.pollMaxPeriod);\n   }\n\n   @Provides\n   @Singleton\n   protected Predicate<Region> provideRegionAvailablePredicate(final DigitalOcean2Api api, Timeouts timeouts,\n         PollPeriod pollPeriod) {\n      return retry(new RegionAvailablePredicate(), timeouts.imageAvailable, pollPeriod.pollInitialPeriod,\n            pollPeriod.pollMaxPeriod);\n   }\n\n   @Provides\n   protected Predicate<Long> provideActionCompletedPredicate(final DigitalOcean2Api api, Timeouts timeouts,\n         PollPeriod pollPeriod) {\n      return retry(new ActionDonePredicate(api), timeouts.imageAvailable, pollPeriod.pollInitialPeriod,\n            pollPeriod.pollMaxPeriod);\n   }\n\n   @VisibleForTesting\n   static class ActionDonePredicate implements Predicate<Long> {\n\n      private final DigitalOcean2Api api;\n\n      public ActionDonePredicate(DigitalOcean2Api api) {\n         this.api = checkNotNull(api, \"api must not be null\");\n      }\n\n      @Override\n      public boolean apply(Long input) {\n         checkNotNull(input, \"action id cannot be null\");\n         Action current = api.actionApi().get(input);\n         switch (current.status()) {\n            case COMPLETED:\n               return true;\n            case IN_PROGRESS:\n               return false;\n            case ERRORED:\n            default:\n               throw new IllegalStateException(\"Resource is in invalid status: \" + current.status().name());\n         }\n      }\n\n   }\n\n   @VisibleForTesting\n   static class DropletTerminatedPredicate implements Predicate<Integer> {\n\n      private final DigitalOcean2Api api;\n\n      public DropletTerminatedPredicate(DigitalOcean2Api api) {\n         this.api = checkNotNull(api, \"api must not be null\");\n      }\n\n      @Override\n      public boolean apply(Integer input) {\n         checkNotNull(input, \"droplet id\");\n         Droplet droplet = api.dropletApi().get(input);\n         return droplet == null;\n      }\n   }\n   \n   @VisibleForTesting\n   static class DropletInStatusPredicate implements Predicate<Integer> {\n\n      private final DigitalOcean2Api api;\n      private final Droplet.Status status;\n\n      public DropletInStatusPredicate(DigitalOcean2Api api, Droplet.Status status) {\n         this.api = checkNotNull(api, \"api must not be null\");\n         this.status = checkNotNull(status, \"status must not be null\");\n      }\n\n      @Override\n      public boolean apply(Integer input) {\n         checkNotNull(input, \"droplet id\");\n         Droplet droplet = api.dropletApi().get(input);\n         return droplet != null && status == droplet.status();\n      }\n   }\n\n   @VisibleForTesting\n   static class RegionAvailablePredicate implements Predicate<Region> {\n      @Override\n      public boolean apply(Region input) {\n         return input.available();\n      }\n\n   }\n\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/compute/extensions/DigitalOcean2ImageExtension.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.compute.extensions;\n\nimport static com.google.common.base.Preconditions.checkState;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_IMAGE_AVAILABLE;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_RUNNING;\n\nimport java.util.NoSuchElementException;\nimport java.util.concurrent.Callable;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Constants;\nimport org.jclouds.compute.domain.CloneImageTemplate;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.ImageTemplate;\nimport org.jclouds.compute.domain.ImageTemplateBuilder;\nimport org.jclouds.compute.extensions.ImageExtension;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.digitalocean2.DigitalOcean2Api;\nimport org.jclouds.digitalocean2.compute.internal.ImageInRegion;\nimport org.jclouds.digitalocean2.domain.Action;\nimport org.jclouds.digitalocean2.domain.Droplet;\nimport org.jclouds.digitalocean2.domain.Droplet.Status;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.primitives.Ints;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.common.util.concurrent.UncheckedTimeoutException;\n\n/**\n * The {@link org.jclouds.compute.extensions.ImageExtension} implementation for the DigitalOcean provider.\n */\n@Singleton\npublic class DigitalOcean2ImageExtension implements ImageExtension {\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   private final DigitalOcean2Api api;\n   private final Predicate<Long> imageAvailablePredicate;\n   private final Predicate<Integer> nodeRunningPredicate;\n   private final Function<ImageInRegion, Image> imageTransformer;\n   private final ListeningExecutorService userExecutor;\n\n   @Inject DigitalOcean2ImageExtension(DigitalOcean2Api api,\n         @Named(TIMEOUT_IMAGE_AVAILABLE) Predicate<Long> imageAvailablePredicate,\n         @Named(TIMEOUT_NODE_RUNNING) Predicate<Integer> nodeRunningPredicate,\n         Function<ImageInRegion, Image> imageTransformer,\n         @Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor) {\n      this.api = api;\n      this.imageAvailablePredicate = imageAvailablePredicate;\n      this.nodeRunningPredicate = nodeRunningPredicate;\n      this.imageTransformer = imageTransformer;\n      this.userExecutor = userExecutor;\n   }\n\n   @Override\n   public ImageTemplate buildImageTemplateFromNode(String name, String id) {\n      Droplet droplet = api.dropletApi().get(Integer.parseInt(id));\n\n      if (droplet == null) {\n         throw new NoSuchElementException(\"Cannot find droplet with id: \" + id);\n      }\n\n      return new ImageTemplateBuilder.CloneImageTemplateBuilder().nodeId(id).name(name).build();\n   }\n\n   @Override\n   public ListenableFuture<Image> createImage(ImageTemplate template) {\n      checkState(template instanceof CloneImageTemplate, \"DigitalOcean only supports creating images through cloning.\");\n      final CloneImageTemplate cloneTemplate = (CloneImageTemplate) template;\n      int dropletId = Integer.parseInt(cloneTemplate.getSourceNodeId());\n\n      // Droplet needs to be active\n      final Droplet droplet = api.dropletApi().get(dropletId);\n      if (droplet.status() != Status.ACTIVE) {\n         api.dropletApi().powerOn(dropletId);\n         checkState(nodeRunningPredicate.apply(dropletId), \"node was not powered on in the configured timeout\");\n      }\n\n      final Action snapshotEvent = api.dropletApi().snapshot(Integer.parseInt(cloneTemplate.getSourceNodeId()),\n            cloneTemplate.getName());\n\n      logger.info(\">> registered new Image, waiting for it to become available\");\n\n      return userExecutor.submit(new Callable<Image>() {\n         @Override\n         public Image call() throws Exception {\n            if (imageAvailablePredicate.apply(snapshotEvent.id())) {\n               org.jclouds.digitalocean2.domain.Image snapshot = api.imageApi().list().concat()\n                     .firstMatch(new Predicate<org.jclouds.digitalocean2.domain.Image>() {\n                        @Override\n                        public boolean apply(org.jclouds.digitalocean2.domain.Image input) {\n                           return input.name().equals(cloneTemplate.getName());\n                        }\n                     }).get();\n\n               return imageTransformer.apply(ImageInRegion.create(snapshot, droplet.region().slug()));\n            }\n\n            throw new UncheckedTimeoutException(\"Image was not created within the time limit: \"\n                  + cloneTemplate.getName());\n         }\n      });\n   }\n\n   @Override\n   public boolean deleteImage(String id) {\n      String imageId = ImageInRegion.extractImageId(id);\n      Integer numericId = Ints.tryParse(imageId); // User images don't have a slug, so we expect a numeric id here\n\n      if (numericId != null) {\n         try {\n            logger.debug(\">> deleting image %s...\", id);\n            api.imageApi().delete(numericId);\n            return true;\n         } catch (Exception ex) {\n            logger.error(ex, \">> error deleting image %s\", id);\n         }\n      } else {\n         logger.warn(\">> image %s is not a user image and cannot be deleted\", id);\n      }\n\n      return false;\n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/compute/functions/DropletStatusToStatus.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.compute.functions;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.domain.NodeMetadata.Status;\nimport org.jclouds.digitalocean2.domain.Droplet;\nimport com.google.common.base.Function;\nimport com.google.common.base.Functions;\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Transforms an {@link org.jclouds.compute.domain.NodeMetadata.Status} to the jclouds portable model.\n */\n@Singleton\npublic class DropletStatusToStatus implements Function<Droplet.Status, Status> {\n\n   private static final Function<Droplet.Status, Status> toPortableStatus = Functions.forMap(\n         ImmutableMap.<Droplet.Status, Status> builder()\n               .put(Droplet.Status.NEW, Status.PENDING)\n               .put(Droplet.Status.ACTIVE, Status.RUNNING)\n               .put(Droplet.Status.ARCHIVE, Status.TERMINATED)\n               .put(Droplet.Status.OFF, Status.SUSPENDED)\n               .build(), \n         Status.UNRECOGNIZED);\n\n   @Override\n   public Status apply(final Droplet.Status input) {\n      return toPortableStatus.apply(input);\n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/compute/functions/DropletToNodeMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.compute.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.find;\nimport static org.jclouds.digitalocean2.compute.internal.ImageInRegion.encodeId;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadata.Status;\nimport org.jclouds.compute.domain.NodeMetadataBuilder;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.digitalocean2.compute.internal.ImageInRegion;\nimport org.jclouds.digitalocean2.domain.Droplet;\nimport org.jclouds.digitalocean2.domain.Networks;\nimport org.jclouds.digitalocean2.domain.Region;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.Iterables;\n\n/**\n * Transforms an {@link Droplet} to the jclouds portable model.\n */\n@Singleton\npublic class DropletToNodeMetadata implements Function<Droplet, NodeMetadata> {\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   private final Supplier<Map<String, ? extends Image>> images;\n   private final Supplier<Map<String, ? extends Hardware>> hardwares;\n   private final Supplier<Set<? extends Location>> locations;\n   private final Function<Droplet.Status, Status> toPortableStatus;\n   private final GroupNamingConvention groupNamingConvention;\n   private final Map<String, Credentials> credentialStore;\n\n   @Inject\n   DropletToNodeMetadata(Supplier<Map<String, ? extends Image>> images,\n         Supplier<Map<String, ? extends Hardware>> hardwares, @Memoized Supplier<Set<? extends Location>> locations,\n         Function<Droplet.Status, Status> toPortableStatus, GroupNamingConvention.Factory groupNamingConvention,\n         Map<String, Credentials> credentialStore) {\n      this.images = checkNotNull(images, \"images cannot be null\");\n      this.hardwares = checkNotNull(hardwares, \"hardwares cannot be null\");\n      this.locations = checkNotNull(locations, \"locations cannot be null\");\n      this.toPortableStatus = checkNotNull(toPortableStatus, \"toPortableStatus cannot be null\");\n      this.groupNamingConvention = checkNotNull(groupNamingConvention, \"groupNamingConvention cannot be null\")\n            .createWithoutPrefix();\n      this.credentialStore = checkNotNull(credentialStore, \"credentialStore cannot be null\");\n   }\n\n   @Override\n   public NodeMetadata apply(Droplet input) {\n      NodeMetadataBuilder builder = new NodeMetadataBuilder();\n      builder.ids(String.valueOf(input.id()));\n      builder.name(input.name());\n      builder.hostname(input.name());\n      builder.group(groupNamingConvention.extractGroup(input.name()));\n\n      builder.hardware(getHardware(input.sizeSlug()));\n      builder.location(getLocation(input.region()));\n\n      Optional<? extends Image> image = findImage(input.image(), input.region().slug());\n      if (image.isPresent()) {\n         builder.imageId(image.get().getId());\n         builder.operatingSystem(image.get().getOperatingSystem());\n      } else {\n         logger.info(\">> image with id %s for droplet %s was not found. \"\n               + \"This might be because the image that was used to create the droplet has a new id.\",\n               input.image().id(), input.id());\n      }\n\n      builder.status(toPortableStatus.apply(input.status()));\n      builder.backendStatus(input.status().name());\n\n      if (!input.getPublicAddresses().isEmpty()) {\n         builder.publicAddresses(FluentIterable\n                     .from(input.getPublicAddresses())\n                     .transform(new Function<Networks.Address, String>() {\n                        @Override\n                        public String apply(final Networks.Address input) {\n                           return input.ip();\n                        }\n                     })\n         );\n      }\n\n      if (!input.getPrivateAddresses().isEmpty()) {\n         builder.privateAddresses(FluentIterable\n               .from(input.getPrivateAddresses())\n               .transform(new Function<Networks.Address, String>() {\n                  @Override\n                  public String apply(final Networks.Address input) {\n                     return input.ip();\n                  }\n               })\n         );\n      }\n\n      // DigitalOcean does not provide a way to get the credentials.\n      // Try to return them from the credential store\n      Credentials credentials = credentialStore.get(\"node#\" + input.id());\n      if (credentials instanceof LoginCredentials) {\n         builder.credentials(LoginCredentials.class.cast(credentials));\n      }\n\n      return builder.build();\n   }\n\n   protected Optional<? extends Image> findImage(org.jclouds.digitalocean2.domain.Image image, String region) {\n      return Optional.fromNullable(images.get().get(encodeId(ImageInRegion.create(image, region))));\n   }\n\n   protected Hardware getHardware(final String slug) {\n      return Iterables.find(hardwares.get().values(), new Predicate<Hardware>() {\n         @Override\n         public boolean apply(Hardware input) {\n            return input.getId().equals(slug);\n         }\n      });\n   }\n\n   protected Location getLocation(final Region region) {\n      return find(locations.get(), new Predicate<Location>() {\n         @Override\n         public boolean apply(Location location) {\n            return region != null && region.slug().equals(location.getId());\n         }\n      }, null);\n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/compute/functions/ImageInRegionToImage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.compute.functions;\n\nimport static com.google.common.collect.Iterables.find;\nimport static org.jclouds.compute.domain.OperatingSystem.builder;\nimport static org.jclouds.digitalocean2.compute.internal.ImageInRegion.encodeId;\n\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.Image.Status;\nimport org.jclouds.compute.domain.ImageBuilder;\nimport org.jclouds.digitalocean2.compute.internal.ImageInRegion;\nimport org.jclouds.digitalocean2.domain.OperatingSystem;\nimport org.jclouds.domain.Location;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Transforms an {@link ImageInRegion} to the jclouds portable model.\n */\n@Singleton\npublic class ImageInRegionToImage implements Function<ImageInRegion, Image> {\n\n   private final Supplier<Set<? extends Location>> locations;\n\n   @Inject ImageInRegionToImage(@Memoized Supplier<Set<? extends Location>> locations) {\n      this.locations = locations;\n   }\n\n   @Override\n   public Image apply(final ImageInRegion input) {\n      String description = input.image().distribution() + \" \" + input.image().name();\n      ImageBuilder builder = new ImageBuilder();\n      // Private images don't have a slug\n      builder.id(encodeId(input));\n      builder.providerId(String.valueOf(input.image().id()));\n      builder.name(input.image().name());\n      builder.description(description);\n      builder.status(Status.AVAILABLE);\n      builder.location(getLocation(input.region()));\n\n      OperatingSystem os = OperatingSystem.create(input.image().name(), input.image().distribution());\n\n      builder.operatingSystem(builder()\n            .name(os.distribution().value())\n            .family(os.distribution().osFamily())\n            .description(description)\n            .arch(os.arch())\n            .version(os.version())\n            .is64Bit(os.is64bit())\n            .build());\n\n      ImmutableMap.Builder<String, String> metadata = ImmutableMap.builder();\n      metadata.put(\"publicImage\", String.valueOf(input.image().isPublic()));\n      builder.userMetadata(metadata.build());\n\n      return builder.build();\n   }\n\n   protected Location getLocation(final String region) {\n      return find(locations.get(), new Predicate<Location>() {\n         @Override\n         public boolean apply(Location location) {\n            return region.equals(location.getId());\n         }\n      });\n   }\n\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/compute/functions/RegionToLocation.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.compute.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.getOnlyElement;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.digitalocean2.domain.Region;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.location.suppliers.all.JustProvider;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Transforms an {@link Region} to the jclouds portable model.\n */\n@Singleton\npublic class RegionToLocation implements Function<Region, Location> {\n\n   private final JustProvider justProvider;\n\n   @Inject\n   RegionToLocation(JustProvider justProvider) {\n      this.justProvider = checkNotNull(justProvider, \"justProvider cannot be null\");\n   }\n\n   @Override\n   public Location apply(Region input) {\n      LocationBuilder builder = new LocationBuilder();\n      builder.id(input.slug());\n      builder.description(input.name());\n      builder.scope(LocationScope.REGION);\n      builder.parent(getOnlyElement(justProvider.get()));\n      builder.iso3166Codes(ImmutableSet.<String> of());\n      builder.metadata(ImmutableMap.<String, Object> of(\"available\", input.available(), \"features\", input.features()));\n      return builder.build();\n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/compute/functions/SizeToHardware.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.compute.functions;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.HardwareBuilder;\nimport org.jclouds.compute.domain.Processor;\nimport org.jclouds.compute.domain.Volume.Type;\nimport org.jclouds.compute.domain.VolumeBuilder;\nimport org.jclouds.digitalocean2.domain.Size;\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Transforms an {@link Size} to the jclouds portable model.\n */\n@Singleton\npublic class SizeToHardware implements Function<Size, Hardware> {\n\n   @Override\n   public Hardware apply(Size input) {\n      HardwareBuilder builder = new HardwareBuilder();\n      builder.id(input.slug());\n      builder.providerId(input.slug());\n      builder.name(input.slug());\n      builder.ram(input.memory());\n      // No cpu speed from DigitalOcean API, so assume more cores == faster\n      builder.processor(new Processor(input.vcpus(), input.vcpus()));\n\n      builder.volume(new VolumeBuilder() \n            .size(Float.valueOf(input.disk()))\n            .type(Type.LOCAL) \n            .build());\n\n      ImmutableMap.Builder<String, String> metadata = ImmutableMap.builder();\n      metadata.put(\"costPerHour\", String.valueOf(input.priceHourly()));\n      metadata.put(\"costPerMonth\", String.valueOf(input.priceMonthly()));\n      builder.userMetadata(metadata.build());\n\n      return builder.build();\n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/compute/internal/ImageInRegion.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.compute.internal;\n\nimport org.jclouds.digitalocean2.domain.Image;\n\nimport com.google.auto.value.AutoValue;\n\n/**\n * Scopes an image to a particular region.\n */\n@AutoValue\npublic abstract class ImageInRegion {\n\n   public abstract Image image();\n   public abstract String region();\n\n   public static ImageInRegion create(Image image, String region) {\n      return new AutoValue_ImageInRegion(image, region);\n   }\n\n   public static String encodeId(ImageInRegion imageInRegion) {\n      // Private images don't have a slug\n      return String.format(\"%s/%s\", imageInRegion.region(), slugOrId(imageInRegion.image()));\n   }\n\n   public static String extractRegion(String imageId) {\n      return imageId.substring(0, imageId.indexOf('/'));\n   }\n\n   public static String extractImageId(String imageId) {\n      return imageId.substring(imageId.indexOf('/') + 1);\n   }\n\n   private static String slugOrId(Image image) {\n      return image.slug() != null ? image.slug() : String.valueOf(image.id());\n   }\n\n   ImageInRegion() { }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/compute/options/DigitalOcean2TemplateOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.compute.options;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Arrays;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.compute.options.TemplateOptions;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Custom options for the DigitalOcean API.\n */\npublic class DigitalOcean2TemplateOptions extends TemplateOptions implements Cloneable {\n\n   private Set<Integer> sshKeyIds = ImmutableSet.of();\n   private boolean privateNetworking = false;\n   private boolean backupsEnabled = false;\n   private boolean autoCreateKeyPair = true;\n   private byte[] userData;\n\n   /**\n    * Enables a private network interface if the region supports private networking.\n    */\n   public DigitalOcean2TemplateOptions privateNetworking(boolean privateNetworking) {\n      this.privateNetworking = privateNetworking;\n      return this;\n   }\n\n   /**\n    * Enabled backups for the droplet.\n    */\n   public DigitalOcean2TemplateOptions backupsEnabled(boolean backupsEnabled) {\n      this.backupsEnabled = backupsEnabled;\n      return this;\n   }\n\n   /**\n    * Sets the ssh key ids to be added to the droplet.\n    */\n   public DigitalOcean2TemplateOptions sshKeyIds(Iterable<Integer> sshKeyIds) {\n      this.sshKeyIds = ImmutableSet.copyOf(checkNotNull(sshKeyIds, \"sshKeyIds cannot be null\"));\n      return this;\n   }\n\n   /**\n    * Sets whether an SSH key pair should be created automatically.\n    */\n   public DigitalOcean2TemplateOptions autoCreateKeyPair(boolean autoCreateKeyPair) {\n      this.autoCreateKeyPair = autoCreateKeyPair;\n      return this;\n   }\n\n   /**\n    * Sets the userData member.\n    */\n   public DigitalOcean2TemplateOptions userData(byte[] userData) {\n      this.userData = userData;\n      return this;\n   }\n   \n   /**\n    * @deprecated Key value metadata is not supported in DigitalOcean. Use\n    *             {@link #userData(byte[])} instead.\n    */\n   @Deprecated\n   @Override\n   public TemplateOptions userMetadata(Map<String, String> userMetadata) {\n      return super.userMetadata(userMetadata);\n   }\n\n   /**\n    * @deprecated Key value metadata is not supported in DigitalOcean. Use\n    *             {@link #userData(byte[])} instead.\n    */\n   @Deprecated\n   @Override\n   public TemplateOptions userMetadata(String key, String value) {\n      return super.userMetadata(key, value);\n   }\n\n   /**\n    * @deprecated Key value metadata is not supported in DigitalOcean. User data\n    *             can be retrieved with {@link #getUserData()}.\n    */\n   @Deprecated\n   @Override\n   public Map<String, String> getUserMetadata() {\n      return super.getUserMetadata();\n   }\n\n   public Set<Integer> getSshKeyIds() {\n      return sshKeyIds;\n   }\n\n   public boolean getPrivateNetworking() {\n      return privateNetworking;\n   }\n\n   public boolean getBackupsEnabled() {\n      return backupsEnabled;\n   }\n\n   public boolean getAutoCreateKeyPair() {\n      return autoCreateKeyPair;\n   }\n\n   public byte[] getUserData() {\n      return userData;\n   }\n\n   @Override\n   public DigitalOcean2TemplateOptions clone() {\n      DigitalOcean2TemplateOptions options = new DigitalOcean2TemplateOptions();\n      copyTo(options);\n      return options;\n   }\n\n   @Override\n   public void copyTo(TemplateOptions to) {\n      super.copyTo(to);\n      if (to instanceof DigitalOcean2TemplateOptions) {\n         DigitalOcean2TemplateOptions eTo = DigitalOcean2TemplateOptions.class.cast(to);\n         eTo.privateNetworking(privateNetworking);\n         eTo.backupsEnabled(backupsEnabled);\n         eTo.autoCreateKeyPair(autoCreateKeyPair);\n         eTo.sshKeyIds(sshKeyIds);\n         if (null != getUserData()) {\n            eTo.userData(getUserData());\n         }\n      }\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(super.hashCode(), backupsEnabled, privateNetworking, autoCreateKeyPair, sshKeyIds,\n            Arrays.hashCode(userData));\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) {\n         return true;\n      }\n      if (!super.equals(obj)) {\n         return false;\n      }\n      if (getClass() != obj.getClass()) {\n         return false;\n      }\n      DigitalOcean2TemplateOptions other = (DigitalOcean2TemplateOptions) obj;\n      return super.equals(other) && equal(this.backupsEnabled, other.backupsEnabled)\n            && equal(this.privateNetworking, other.privateNetworking)\n            && equal(this.autoCreateKeyPair, other.autoCreateKeyPair) && equal(this.sshKeyIds, other.sshKeyIds)\n            && Arrays.equals(this.userData, other.userData);\n   }\n\n   @Override\n   public ToStringHelper string() {\n      ToStringHelper toString = super.string().omitNullValues();\n      toString.add(\"privateNetworking\", privateNetworking);\n      toString.add(\"backupsEnabled\", backupsEnabled);\n      if (!sshKeyIds.isEmpty()) {\n         toString.add(\"sshKeyIds\", sshKeyIds);\n      }\n      toString.add(\"autoCreateKeyPair\", autoCreateKeyPair);\n      toString.add(\"userData\", userData);\n      return toString;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see DigitalOcean2TemplateOptions#privateNetworking\n       */\n      public static DigitalOcean2TemplateOptions privateNetworking(boolean privateNetworking) {\n         DigitalOcean2TemplateOptions options = new DigitalOcean2TemplateOptions();\n         return options.privateNetworking(privateNetworking);\n      }\n\n      /**\n       * @see DigitalOcean2TemplateOptions#backupsEnabled\n       */\n      public static DigitalOcean2TemplateOptions backupsEnabled(boolean backupsEnabled) {\n         DigitalOcean2TemplateOptions options = new DigitalOcean2TemplateOptions();\n         return options.backupsEnabled(backupsEnabled);\n      }\n\n      /**\n       * @see DigitalOcean2TemplateOptions#sshKeyIds\n       */\n      public static DigitalOcean2TemplateOptions sshKeyIds(Iterable<Integer> sshKeyIds) {\n         DigitalOcean2TemplateOptions options = new DigitalOcean2TemplateOptions();\n         return options.sshKeyIds(sshKeyIds);\n      }\n\n      /**\n       * @see DigitalOcean2TemplateOptions#autoCreateKeyPair\n       */\n      public static DigitalOcean2TemplateOptions autoCreateKeyPair(boolean autoCreateKeyPair) {\n         DigitalOcean2TemplateOptions options = new DigitalOcean2TemplateOptions();\n         return options.autoCreateKeyPair(autoCreateKeyPair);\n      }\n\n      /**\n       * @see DigitalOcean2TemplateOptions#userData\n       */\n      public static DigitalOcean2TemplateOptions userData(byte[] userData) {\n         DigitalOcean2TemplateOptions options = new DigitalOcean2TemplateOptions();\n         return options.userData(userData);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/compute/strategy/CreateKeyPairsThenCreateNodes.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.compute.strategy;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.security.PublicKey;\nimport java.security.interfaces.DSAPublicKey;\nimport java.security.interfaces.ECPublicKey;\nimport java.security.interfaces.RSAPublicKey;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Constants;\nimport org.jclouds.compute.config.CustomizationResponse;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.compute.strategy.CreateNodeWithGroupEncodedIntoName;\nimport org.jclouds.compute.strategy.CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap;\nimport org.jclouds.compute.strategy.ListNodesStrategy;\nimport org.jclouds.compute.strategy.impl.CreateNodesWithGroupEncodedIntoNameThenAddToSet;\nimport org.jclouds.digitalocean2.DigitalOcean2Api;\nimport org.jclouds.digitalocean2.compute.options.DigitalOcean2TemplateOptions;\nimport org.jclouds.digitalocean2.domain.Key;\nimport org.jclouds.digitalocean2.ssh.DSAKeys;\nimport org.jclouds.digitalocean2.ssh.ECDSAKeys;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.ssh.SshKeyPairGenerator;\nimport org.jclouds.ssh.SshKeys;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Strings;\nimport com.google.common.collect.Multimap;\nimport com.google.common.collect.Sets;\nimport com.google.common.util.concurrent.FutureCallback;\nimport com.google.common.util.concurrent.Futures;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.ListeningExecutorService;\n\n@Singleton\npublic class CreateKeyPairsThenCreateNodes extends CreateNodesWithGroupEncodedIntoNameThenAddToSet {\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   private final DigitalOcean2Api api;\n   private final SshKeyPairGenerator keyGenerator;\n   private final Function<String, PublicKey> sshKeyToPublicKey;\n\n   @Inject\n   protected CreateKeyPairsThenCreateNodes(\n         CreateNodeWithGroupEncodedIntoName addNodeWithGroupStrategy,\n         ListNodesStrategy listNodesStrategy,\n         GroupNamingConvention.Factory namingConvention,\n         @Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor,\n         CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap.Factory customizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapFactory,\n         DigitalOcean2Api api, SshKeyPairGenerator keyGenerator, Function<String, PublicKey> sshKeyToPublicKey) {\n      super(addNodeWithGroupStrategy, listNodesStrategy, namingConvention, userExecutor,\n            customizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapFactory);\n      this.api = checkNotNull(api, \"api cannot be null\");\n      this.keyGenerator = checkNotNull(keyGenerator, \"keyGenerator cannot be null\");\n      checkNotNull(userExecutor, \"userExecutor cannot be null\");\n      this.sshKeyToPublicKey = checkNotNull(sshKeyToPublicKey, \"sshKeyToPublicKey cannot be null\");\n   }\n\n   @Override\n   public Map<?, ListenableFuture<Void>> execute(String group, int count, Template template,\n         Set<NodeMetadata> goodNodes, Map<NodeMetadata, Exception> badNodes,\n         Multimap<NodeMetadata, CustomizationResponse> customizationResponses) {\n\n      DigitalOcean2TemplateOptions options = template.getOptions().as(DigitalOcean2TemplateOptions.class);\n      Set<Integer> generatedSshKeyIds = Sets.newHashSet();\n\n      // If no key has been configured and the auto-create option is set, then generate a key pair\n      if (options.getSshKeyIds().isEmpty() && options.getAutoCreateKeyPair()\n            && Strings.isNullOrEmpty(options.getPublicKey())) {\n         generateKeyPairAndAddKeyToSet(options, generatedSshKeyIds, group);\n      }\n\n      // If there is a script to run in the node, make sure a private key has\n      // been configured so jclouds will be able to access the node\n      if (options.getRunScript() != null && Strings.isNullOrEmpty(options.getLoginPrivateKey())) {\n         logger.warn(\">> A runScript has been configured but no SSH key has been provided.\"\n               + \" Authentication will delegate to the ssh-agent\");\n      }\n\n      // If there is a key configured, then make sure there is a key pair for it\n      if (!Strings.isNullOrEmpty(options.getPublicKey())) {\n         createKeyPairForPublicKeyInOptionsAndAddToSet(options, generatedSshKeyIds);\n      }\n\n      // Set all keys (the provided and the auto-generated) in the options object so the\n      // DigitalOceanComputeServiceAdapter adds them all\n      options.sshKeyIds(Sets.union(generatedSshKeyIds, options.getSshKeyIds()));\n\n      Map<?, ListenableFuture<Void>> responses = super.execute(group, count, template, goodNodes, badNodes,\n            customizationResponses);\n\n      // Key pairs in DigitalOcean are only required to create the Droplets. They aren't used anymore so it is better\n      // to delete the auto-generated key pairs at this point where we know exactly which ones have been\n      // auto-generated by jclouds.\n      registerAutoGeneratedKeyPairCleanupCallbacks(responses, generatedSshKeyIds);\n\n      return responses;\n   }\n\n   private void createKeyPairForPublicKeyInOptionsAndAddToSet(DigitalOcean2TemplateOptions options,\n         Set<Integer> generatedSshKeyIds) {\n      logger.debug(\">> checking if the key pair already exists...\");\n\n      PublicKey userKey = sshKeyToPublicKey.apply(options.getPublicKey());\n      String userFingerprint = computeFingerprint(userKey);\n      Key key = api.keyApi().get(userFingerprint);  \n\n      if (key == null) {\n         logger.debug(\">> key pair not found. creating a new one...\");\n\n         Key newKey = api.keyApi().create(userFingerprint, options.getPublicKey());\n\n         generatedSshKeyIds.add(newKey.id());\n         logger.debug(\">> key pair created! %s\", newKey);\n      } else {\n         logger.debug(\">> key pair found! %s\", key);\n         generatedSshKeyIds.add(key.id());\n      }\n   }\n\n   private void generateKeyPairAndAddKeyToSet(DigitalOcean2TemplateOptions options, Set<Integer> generatedSshKeyIds, String prefix) {\n      logger.debug(\">> creating default keypair for node...\");\n\n      Map<String, String> defaultKeys = keyGenerator.get();\n\n      Key defaultKey = api.keyApi().create(prefix + \"-\" + System.getProperty(\"user.name\"), defaultKeys.get(\"public\"));\n      generatedSshKeyIds.add(defaultKey.id());\n\n      logger.debug(\">> keypair created! %s\", defaultKey);\n\n      // If a private key has not been explicitly set, configure the auto-generated one\n      if (Strings.isNullOrEmpty(options.getLoginPrivateKey())) {\n         options.overrideLoginPrivateKey(defaultKeys.get(\"private\"));\n      }\n   }\n\n   private void registerAutoGeneratedKeyPairCleanupCallbacks(Map<?, ListenableFuture<Void>> responses,\n         final Set<Integer> generatedSshKeyIds) {\n      // The Futures.allAsList fails immediately if some of the futures fail. The Futures.successfulAsList, however,\n      // returns a list containing the results or 'null' for those futures that failed. We want to wait for all them\n      // (even if they fail), so better use the latter form.\n      ListenableFuture<List<Void>> aggregatedResponses = Futures.successfulAsList(responses.values());\n\n      // Key pairs must be cleaned up after all futures completed (even if some failed).\n      Futures.addCallback(aggregatedResponses, new FutureCallback<List<Void>>() {\n         @Override\n         public void onSuccess(List<Void> result) {\n            cleanupAutoGeneratedKeyPairs(generatedSshKeyIds);\n         }\n\n         @Override\n         public void onFailure(Throwable t) {\n            cleanupAutoGeneratedKeyPairs(generatedSshKeyIds);\n         }\n\n         private void cleanupAutoGeneratedKeyPairs(Set<Integer> generatedSshKeyIds) {\n            logger.debug(\">> cleaning up auto-generated key pairs...\");\n            for (Integer sshKeyId : generatedSshKeyIds) {\n               try {\n                  api.keyApi().delete(sshKeyId);\n               } catch (Exception ex) {\n                  logger.warn(\">> could not delete key pair %s: %s\", sshKeyId, ex.getMessage());\n               }\n            }\n         }\n\n      }, userExecutor);\n   }\n   \n   private static String computeFingerprint(PublicKey key) {\n      if (key instanceof RSAPublicKey) {\n         RSAPublicKey rsaKey = (RSAPublicKey) key;\n         return SshKeys.fingerprint(rsaKey.getPublicExponent(), rsaKey.getModulus());\n      } else if (key instanceof DSAPublicKey) {\n         DSAPublicKey dsaKey = (DSAPublicKey) key;\n         return DSAKeys.fingerprint(dsaKey.getParams().getP(), dsaKey.getParams().getQ(), dsaKey.getParams().getG(),\n               dsaKey.getY());\n      } else if (key instanceof ECPublicKey) {\n         ECPublicKey ecdsaKey = (ECPublicKey) key;\n         return ECDSAKeys.fingerprint(ecdsaKey);\n      } else {\n         throw new IllegalArgumentException(\"Only RSA and DSA keys are supported\");\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/config/DigitalOcean2HttpApiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.config;\n\nimport java.net.URI;\n\nimport org.jclouds.digitalocean2.DigitalOcean2Api;\nimport org.jclouds.digitalocean2.domain.options.ImageListOptions;\nimport org.jclouds.digitalocean2.domain.options.ListOptions;\nimport org.jclouds.digitalocean2.functions.LinkToImageListOptions;\nimport org.jclouds.digitalocean2.functions.LinkToListOptions;\nimport org.jclouds.digitalocean2.handlers.DigitalOcean2ErrorHandler;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.annotation.ClientError;\nimport org.jclouds.http.annotation.Redirection;\nimport org.jclouds.http.annotation.ServerError;\nimport org.jclouds.oauth.v2.config.OAuthScopes;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.config.HttpApiModule;\n\nimport com.google.common.base.Function;\nimport com.google.inject.TypeLiteral;\n\n@ConfiguresHttpApi\npublic class DigitalOcean2HttpApiModule extends HttpApiModule<DigitalOcean2Api> {\n\n   @Override\n   protected void bindErrorHandlers() {\n      bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(DigitalOcean2ErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(DigitalOcean2ErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(DigitalOcean2ErrorHandler.class);\n   }\n\n   @Override\n   protected void configure() {\n      super.configure();\n      bind(OAuthScopes.class).toInstance(OAuthScopes.ReadOrWriteScopes.create(\"read\", \"read write\"));\n      bind(new TypeLiteral<Function<URI, ListOptions>>() {\n      }).to(LinkToListOptions.class);\n      bind(new TypeLiteral<Function<URI, ImageListOptions>>() {\n      }).to(LinkToImageListOptions.class);\n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/config/DigitalOcean2RateLimitModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.config;\n\nimport org.jclouds.digitalocean2.handlers.DigitalOcean2RateLimitRetryHandler;\nimport org.jclouds.http.HttpRetryHandler;\nimport org.jclouds.http.annotation.ClientError;\n\nimport com.google.inject.AbstractModule;\n\npublic class DigitalOcean2RateLimitModule extends AbstractModule {\n   @Override\n   protected void configure() {\n      bind(HttpRetryHandler.class).annotatedWith(ClientError.class).to(DigitalOcean2RateLimitRetryHandler.class);\n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/config/DigitalOceanParserModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.config;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Throwables.propagate;\nimport static com.google.common.collect.Iterables.get;\nimport static com.google.common.collect.Iterables.size;\nimport static com.google.inject.Scopes.SINGLETON;\n\nimport java.io.IOException;\nimport java.lang.reflect.Type;\nimport java.security.KeyFactory;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.PublicKey;\nimport java.security.interfaces.DSAPublicKey;\nimport java.security.interfaces.RSAPublicKey;\nimport java.security.spec.DSAPublicKeySpec;\nimport java.security.spec.ECPublicKeySpec;\nimport java.security.spec.InvalidKeySpecException;\nimport java.security.spec.RSAPublicKeySpec;\nimport java.util.Map;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.digitalocean2.ssh.DSAKeys;\nimport org.jclouds.digitalocean2.ssh.ECDSAKeys;\nimport org.jclouds.json.config.GsonModule.DateAdapter;\nimport org.jclouds.json.config.GsonModule.Iso8601DateAdapter;\nimport org.jclouds.ssh.SshKeys;\nimport com.google.common.base.Function;\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.gson.TypeAdapter;\nimport com.google.gson.stream.JsonReader;\nimport com.google.gson.stream.JsonWriter;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Provides;\n\n/**\n * Custom parser bindings.\n */\npublic class DigitalOceanParserModule extends AbstractModule {\n\n   @Override\n   protected void configure() {\n      bind(DateAdapter.class).to(Iso8601DateAdapter.class).in(SINGLETON);\n   }\n\n   @Singleton\n   public static class SshPublicKeyAdapter extends TypeAdapter<PublicKey> {\n\n      private final Function<PublicKey, String> publicKeyToSshKey;\n      private final Function<String, PublicKey> sshKeyToPublicKey;\n\n      @Inject\n      public SshPublicKeyAdapter(Function<PublicKey, String> publicKeyToSshKey,\n            Function<String, PublicKey> sshKeyToPublicKey) {\n         this.publicKeyToSshKey = checkNotNull(publicKeyToSshKey, \"publicKeyToSshKey cannot be null\");\n         this.sshKeyToPublicKey = checkNotNull(sshKeyToPublicKey, \"sshKeyToPublicKey cannot be null\");\n      }\n\n      @Override\n      public void write(JsonWriter out, PublicKey value) throws IOException {\n         out.value(publicKeyToSshKey.apply(value));\n      }\n\n      @Override\n      public PublicKey read(JsonReader in) throws IOException {\n         return sshKeyToPublicKey.apply(in.nextString().trim());\n      }\n   }\n\n   @Provides\n   @Singleton\n   public Function<PublicKey, String> publicKeyToSshKey() {\n      return new Function<PublicKey, String>() {\n         @Override\n         public String apply(PublicKey input) {\n            if (input instanceof RSAPublicKey) {\n               return SshKeys.encodeAsOpenSSH((RSAPublicKey) input);\n            } else if (input instanceof DSAPublicKey) {\n               return DSAKeys.encodeAsOpenSSH((DSAPublicKey) input);\n            } else {\n               throw new IllegalArgumentException(\"Only RSA and DSA keys are supported\");\n            }\n         }\n      };\n   }\n\n   @Provides\n   @Singleton\n   public Function<String, PublicKey> sshKeyToPublicKey() {\n      return new Function<String, PublicKey>() {\n         @Override\n         public PublicKey apply(String input) {\n            Iterable<String> parts = Splitter.on(' ').split(input);\n            checkArgument(size(parts) >= 2, \"bad format, should be: [ssh-rsa|ssh-dss] AAAAB3...\");\n            String type = get(parts, 0);\n\n            try {\n               if (\"ssh-rsa\".equals(type)) {\n                  RSAPublicKeySpec spec = SshKeys.publicKeySpecFromOpenSSH(input);\n                  return KeyFactory.getInstance(\"RSA\").generatePublic(spec);\n               } else if (\"ssh-dss\".equals(type)) {\n                  DSAPublicKeySpec spec = DSAKeys.publicKeySpecFromOpenSSH(input);\n                  return KeyFactory.getInstance(\"DSA\").generatePublic(spec);\n               } else if (type.startsWith(\"ecdsa-sha2-\")) {\n                  ECPublicKeySpec spec = ECDSAKeys.publicKeySpecFromOpenSSH(input);\n                  return KeyFactory.getInstance(\"EC\").generatePublic(spec);\n               } else {\n                  throw new IllegalArgumentException(\"bad format, jclouds supports ssh-rsa, ssh-dss, ecdsa-sha2-nistp[256|384|521]\");\n               }\n            } catch (InvalidKeySpecException ex) {\n               throw propagate(ex);\n            } catch (NoSuchAlgorithmException ex) {\n               throw propagate(ex);\n            }\n         }\n      };\n   }\n\n   @Provides\n   @Singleton\n   public Map<Type, Object> provideCustomAdapterBindings(SshPublicKeyAdapter sshPublicKeyAdapter) {\n      return ImmutableMap.<Type, Object> of(PublicKey.class, sshPublicKeyAdapter);\n   }\n\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/domain/Action.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.digitalocean2.domain;\n\nimport static com.google.common.base.Preconditions.checkArgument;\n\nimport java.util.Date;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.base.CaseFormat;\nimport com.google.common.base.Enums;\nimport com.google.common.base.Joiner;\nimport com.google.common.base.Optional;\n\n@AutoValue\npublic abstract class Action {\n   \n   public enum Status {\n      COMPLETED, IN_PROGRESS, ERRORED;\n\n      Status() {}\n\n      public static Status fromValue(String value) {\n         Optional<Status> status = Enums.getIfPresent(Status.class, value.toUpperCase());\n         if (!status.isPresent()) {\n            String upperCamelValue = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_UNDERSCORE, value.toLowerCase());\n            status = Enums.getIfPresent(Status.class, upperCamelValue);\n         }\n         checkArgument(status.isPresent(), \"Expected one of %s but was\", Joiner.on(',').join(Status.values()), value);\n         return status.get();\n      }\n   }\n\n   public abstract long id();\n   public abstract Status status();\n   public abstract String type();\n   public abstract Date startedAt();\n   @Nullable public abstract Date completedAt();\n   public abstract long resourceId();\n   public abstract String resourceType();\n   @Nullable public abstract Region region();\n   @Nullable public abstract String regionSlug();\n\n   @SerializedNames({ \"id\", \"status\", \"type\", \"started_at\", \"completed_at\", \"resource_id\", \"resource_type\",\n      \"region\", \"region_slug\" })\n   public static Action create(long id, Status status, String type, Date startedAt, Date completedAt, long resourceId,\n         String resourceType, Region region, String regionSlug) {\n      return new AutoValue_Action(id, status, type, startedAt, completedAt, resourceId, resourceType, region,\n            regionSlug);\n   }\n\n   Action() {}\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/domain/Backup.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.digitalocean2.domain;\n\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class Backup {\n   public abstract int id();\n   public abstract String name();\n   public abstract String distribution();\n   @Nullable public abstract String slug();\n   public abstract boolean isPublic();\n   public abstract List<String> regions();\n   public abstract int minDiskSize();\n\n   @SerializedNames({ \"id\", \"name\", \"distribution\", \"slug\", \"public\", \"regions\", \"min_disk_size\" })\n   public static Backup create(int id, String name, String distribution, String slug, boolean isPublic,\n         List<String> regions, int minDiskSize) {\n      return new AutoValue_Backup(id, name, distribution, slug, isPublic, regions, minDiskSize);\n   }\n\n   Backup() {}\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/domain/Distribution.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.tryFind;\nimport static java.util.Arrays.asList;\n\nimport java.util.List;\n\nimport org.jclouds.compute.domain.OsFamily;\nimport com.google.common.base.Predicate;\n\n/**\n * DigitalOcean image distributions.\n */\npublic enum Distribution {\n   ARCHLINUX(OsFamily.ARCH, \"Arch Linux\"), \n   CENTOS(OsFamily.CENTOS, \"CentOS\"), \n   DEBIAN(OsFamily.DEBIAN, \"Debian\"), \n   FEDORA(OsFamily.FEDORA, \"Fedora\"), \n   UBUNTU(OsFamily.UBUNTU, \"Ubuntu\"), \n   UNRECOGNIZED(OsFamily.UNRECOGNIZED, \"\"); \n\n   private static final List<Distribution> values = asList(Distribution.values());\n\n   private final OsFamily osFamily;\n   private final String value;\n\n   private Distribution(OsFamily osFamily, String value) {\n      this.osFamily = checkNotNull(osFamily, \"osFamily cannot be null\");\n      this.value = checkNotNull(value, \"value cannot be null\");\n   }\n\n   public OsFamily osFamily() {\n      return this.osFamily;\n   }\n   \n   public String value() {\n      return this.value;\n   }\n\n   public static Distribution fromValue(String value) {\n      return tryFind(values, hasValue(value)).or(UNRECOGNIZED);\n   }\n\n   private static Predicate<Distribution> hasValue(final String value) {\n      return new Predicate<Distribution>() {\n         @Override\n         public boolean apply(Distribution input) {\n            return input.value.equalsIgnoreCase(value);\n         }\n      };\n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/domain/Droplet.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.domain;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.collect.ImmutableList.copyOf;\nimport static com.google.common.collect.Iterables.concat;\n\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.base.Enums;\nimport com.google.common.base.Joiner;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableList;\n\n@AutoValue\npublic abstract class Droplet {\n   \n   public enum Status {\n      NEW, ACTIVE, ARCHIVE, OFF;\n\n      public static Status fromValue(String value) {\n         Optional<Status> status = Enums.getIfPresent(Status.class, value.toUpperCase());\n         checkArgument(status.isPresent(), \"Expected one of %s but was %s\", Joiner.on(',').join(Status.values()), value);\n         return status.get();\n      }\n   }\n   \n   public abstract int id();\n   public abstract String name();\n   public abstract int memory();\n   public abstract int vcpus();\n   public abstract int disk();\n   public abstract boolean locked();\n   public abstract Date createdAt();\n   public abstract Status status();\n   public abstract List<Integer> backupsIds();\n   public abstract List<Integer> snapshotIds();\n   public abstract List<String> features();\n   @Nullable public abstract Region region();\n   @Nullable public abstract Image image();\n   @Nullable public abstract Size size();\n   public abstract String sizeSlug();\n   @Nullable  public abstract Networks networks();\n   @Nullable public abstract Kernel kernel();\n\n   @SerializedNames({ \"id\", \"name\", \"memory\", \"vcpus\", \"disk\", \"locked\", \"created_at\", \"status\", \"backup_ids\",\n         \"snapshot_ids\", \"features\", \"region\", \"image\", \"size\", \"size_slug\", \"networks\", \"kernel\" })\n   public static Droplet create(int id, String name, int memory, int vcpus, int disk, boolean locked, Date createdAt,\n         Status status, List<Integer> backupIds, List<Integer> snapshotIds, List<String> features, Region region,\n         Image image, Size size, String sizeSlug, Networks network, Kernel kernel) {\n      return new AutoValue_Droplet(id, name, memory, vcpus, disk, locked, createdAt, status, \n            backupIds == null ? ImmutableList.<Integer> of() : copyOf(backupIds),\n            snapshotIds == null ? ImmutableList.<Integer> of() : copyOf(snapshotIds), copyOf(features), region, image,\n            size, sizeSlug, network, kernel);\n   }\n\n   public Set<Networks.Address> getPublicAddresses() {\n      return FluentIterable.from(concat(networks().ipv4(), networks().ipv6()))\n            .filter(Networks.Predicates.publicNetworks())\n            .toSet();\n   }\n\n   public Set<Networks.Address> getPrivateAddresses() {\n      return FluentIterable.from(concat(networks().ipv4(), networks().ipv6()))\n            .filter(Networks.Predicates.privateNetworks())\n            .toSet();\n   }\n\n   Droplet() {}\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/domain/DropletCreate.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.domain;\n\nimport static com.google.common.collect.ImmutableList.copyOf;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class DropletCreate {\n   public abstract Droplet droplet();\n   public abstract Links links();\n\n   @AutoValue\n   public abstract static class Links {\n      \n      @AutoValue\n      public abstract static class ActionLink {\n         public abstract long id();\n         public abstract String rel();\n         public abstract URI href();\n         \n         @SerializedNames({\"id\", \"rel\", \"href\"})\n         public static ActionLink create(long id, String rel, URI href) {\n            return new AutoValue_DropletCreate_Links_ActionLink(id, rel, href);\n         }\n         \n         ActionLink() {}\n      }\n      \n      public abstract List<ActionLink> actions();\n\n      @SerializedNames({ \"actions\" })\n      public static Links create(List<ActionLink> actions) {\n         return new AutoValue_DropletCreate_Links(copyOf(actions));\n      }\n\n      Links() {}\n   }\n\n   @SerializedNames({ \"droplet\", \"links\" })\n   public static DropletCreate create(Droplet droplet, Links links) {\n      return new AutoValue_DropletCreate(droplet, links);\n   }\n\n   DropletCreate() {}\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/domain/Image.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.domain;\n\nimport static com.google.common.collect.ImmutableList.copyOf;\n\nimport java.util.Date;\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class Image {\n\n   public abstract int id();\n   public abstract String name();\n   public abstract String type();\n   public abstract String distribution();\n   @Nullable public abstract String slug();\n   public abstract boolean isPublic();\n   public abstract List<String> regions();\n   public abstract Date createdAt();\n   public abstract float minDiskSize();\n   public abstract float sizeGBs();\n\n   @SerializedNames({ \"id\", \"name\", \"type\", \"distribution\", \"slug\", \"public\", \"regions\", \"created_at\", \"min_disk_size\",\n         \"size_gigabytes\" })\n   public static Image create(int id, String name, String type, String distribution, String slug, boolean isPublic,\n         List<String> regions, Date createdAt, float minDiskSize, float sizeGBs) {\n      return new AutoValue_Image(id, name, type, distribution, slug, isPublic, copyOf(regions), createdAt, minDiskSize,\n            sizeGBs);\n   }\n\n   Image() {}\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/domain/Kernel.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.domain;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class Kernel {\n   public abstract int id();\n   public abstract String name();\n   public abstract String version();\n\n   @SerializedNames({ \"id\", \"name\", \"version\" })\n   public static Kernel create(int id, String name, String version) {\n      return new AutoValue_Kernel(id, name, version);\n   }\n\n   Kernel() {}\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/domain/Key.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.domain;\n\nimport java.security.PublicKey;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class Key {\n\n   public abstract int id();\n   public abstract String name();\n   public abstract String fingerprint();\n   public abstract PublicKey publicKey();\n\n   @SerializedNames({ \"id\", \"name\", \"fingerprint\", \"public_key\" })\n   public static Key create(int id, String name, String fingerprint, PublicKey publicKey) {\n      return new AutoValue_Key(id, name, fingerprint, publicKey);\n   }\n\n   Key() {}\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/domain/Networks.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.domain;\n\nimport static com.google.common.collect.ImmutableList.copyOf;\n\nimport java.util.List;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.base.Predicate;\n\n@AutoValue\npublic abstract class Networks {\n   \n   @AutoValue\n   public abstract static class Address {\n      public abstract String ip();\n      public abstract String netmask();\n      public abstract String gateway();\n      public abstract String type();\n\n      @SerializedNames({ \"ip_address\", \"netmask\", \"gateway\", \"type\"})\n      public static Address create(String ip, String netmask, String gateway, String type) {\n         return new AutoValue_Networks_Address(ip, netmask, gateway, type);\n      }\n      \n      Address() {}\n   }\n   \n   public abstract List<Address> ipv4();\n   public abstract List<Address> ipv6();\n   \n   @SerializedNames({ \"v4\", \"v6\" })\n   public static Networks create(List<Address> ipv4, List<Address> ipv6) {\n      return new AutoValue_Networks(copyOf(ipv4), copyOf(ipv6));\n   }\n   \n   Networks() {}\n\n   public static class Predicates {\n      \n      public static Predicate<Address> publicNetworks() {\n         return new Predicate<Address>() {\n            @Override\n            public boolean apply(Address network) {\n               return network.type().equals(\"public\");\n            }\n         };\n      }\n      \n      public static Predicate<Address> privateNetworks() {\n         return new Predicate<Address>() {\n            @Override\n            public boolean apply(Address network) {\n               return network.type().equals(\"private\");\n            }\n         };\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/domain/OperatingSystem.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.domain;\n\nimport static com.google.common.base.Strings.nullToEmpty;\nimport static java.util.regex.Pattern.compile;\n\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport com.google.auto.value.AutoValue;\n\n/**\n * The operating system of an image.\n * <p>\n * This class parses the <code>name</code> string (e.g. \"Ubuntu 12.10 x64\") of the images and properly sets each field\n * to the right value.\n */\n@AutoValue\npublic abstract class OperatingSystem {\n   \n   // Parse something like \"12.10 x64\" or \"Ubuntu 12.10.1 x64\" and matches the version and architecture\n   private static final Pattern VERSION_PATTERN = compile(\"(?:[a-zA-Z\\\\s]*\\\\s+)?(\\\\d+(?:\\\\.?\\\\d+)*)?(?:\\\\s*(x\\\\d{2}))?.*\");\n   private static final String IS_64_BIT = \"x64\";\n\n   public abstract Distribution distribution();\n   public abstract String version();\n   public abstract String arch();\n\n   public static OperatingSystem create(String name, String distribution) {\n      return new AutoValue_OperatingSystem(Distribution.fromValue(distribution), match(VERSION_PATTERN, name, 1),\n            match(VERSION_PATTERN, name, 2));\n   }\n\n   public boolean is64bit() {\n      return IS_64_BIT.equals(arch());\n   }\n   \n   OperatingSystem() {}\n\n   private static String match(final Pattern pattern, final String input, int group) {\n      Matcher m = pattern.matcher(input);\n      return m.find() ? nullToEmpty(m.group(group)) : \"\";\n   }\n\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/domain/Region.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.digitalocean2.domain;\n\nimport java.util.List;\n\nimport org.jclouds.json.SerializedNames;\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class Region {\n   public abstract String slug();\n   public abstract String name();\n   public abstract List<String> sizes();\n   public abstract boolean available();\n   public abstract List<String> features();\n\n   @SerializedNames({ \"slug\", \"name\", \"sizes\", \"available\", \"features\" })\n   public static Region create(String slug, String name, List<String> sizes, boolean available, List<String> features) {\n      return new AutoValue_Region(slug, name, sizes, available, features);\n   }\n\n   Region() {}\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/domain/Size.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.digitalocean2.domain;\n\nimport java.util.List;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class Size {\n   public abstract String slug();\n   public abstract boolean available();\n   public abstract float transfer();\n   public abstract float priceMonthly();\n   public abstract float priceHourly();\n   public abstract int memory();\n   public abstract int vcpus();\n   public abstract int disk();\n   public abstract List<String> regions();\n\n   @SerializedNames({ \"slug\", \"available\", \"transfer\", \"price_monthly\", \"price_hourly\", \"memory\", \"vcpus\", \"disk\",\n         \"regions\" })\n   public static Size create(String slug, boolean available, float transfer, float priceMonthly, float priceHourly,\n         int memory, int vcpus, int disk, List<String> regions) {\n      return new AutoValue_Size(slug, available, transfer, priceMonthly, priceHourly, memory, vcpus, disk, regions);\n   }\n\n   Size() {}\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/domain/Snapshot.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.digitalocean2.domain;\n\nimport java.util.Date;\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class Snapshot {\n   public abstract int id();\n   public abstract String name();\n   public abstract String type();\n   public abstract String distribution();\n   @Nullable public abstract String slug();\n   public abstract boolean isPublic();\n   public abstract List<String> regions();\n   public abstract int minDiskSize();\n   public abstract Date createdAt();\n\n   @SerializedNames({ \"id\", \"name\", \"type\", \"distribution\", \"slug\", \"public\", \"regions\", \"min_disk_size\", \"created_at\"})\n   public static Snapshot create(int id, String name, String type, String distribution, String slug, boolean isPublic,\n         List<String> regions, int minDiskSize, Date createdAt) {\n      return new AutoValue_Snapshot(id, name, type, distribution, slug, isPublic, regions, minDiskSize, createdAt);\n   }\n   \n   Snapshot() {}\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/domain/internal/PaginatedCollection.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.domain.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.net.URI;\nimport java.util.Iterator;\nimport java.util.List;\n\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Base class for all collections that return paginated results.\n */\npublic abstract class PaginatedCollection<T> extends IterableWithMarker<T> {\n\n   @AutoValue\n   public abstract static class Meta {\n      public abstract long total();\n\n      @SerializedNames({ \"total\" })\n      public static Meta create(long total) {\n         return new AutoValue_PaginatedCollection_Meta(total);\n      }\n\n      Meta() { }\n   }\n\n   @AutoValue\n   public abstract static class Links {\n\n      @AutoValue\n      public abstract static class Pages {\n         @Nullable public abstract URI first();\n         @Nullable public abstract URI prev();\n         @Nullable public abstract URI next();\n         @Nullable public abstract URI last();\n\n         @SerializedNames({ \"first\", \"prev\", \"next\", \"last\" })\n         public static Pages create(URI first, URI prev, URI next, URI last) {\n            return new AutoValue_PaginatedCollection_Links_Pages(first, prev, next, last);\n         }\n\n         Pages() { }\n      }\n\n      @Nullable public abstract Pages pages();\n\n      @SerializedNames({ \"pages\" })\n      public static Links create(Pages pages) {\n         return new AutoValue_PaginatedCollection_Links(pages);\n      }\n\n      Links() { }\n   }\n\n   private final List<T> items;\n   private final Meta meta;\n   private final Links links;\n\n   protected PaginatedCollection(List<T> items, Meta meta, Links links) {\n      this.items = ImmutableList.copyOf(checkNotNull(items, \"items cannot be null\"));\n      this.meta = checkNotNull(meta, \"meta cannot be null\");\n      this.links = checkNotNull(links, \"links cannot be null\");\n   }\n\n   public List<T> items() {\n      return items;\n   }\n\n   public Meta meta() {\n      return meta;\n   }\n\n   public Links links() {\n      return links;\n   }\n\n   @Override public Iterator<T> iterator() {\n      return items.iterator();\n   }\n\n   @Override public Optional<Object> nextMarker() {\n      if (links.pages() == null) {\n         return Optional.absent();\n      }\n      return Optional.fromNullable((Object) links.pages().next());\n   }\n\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/domain/options/CreateDropletOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.domain.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\nimport org.jclouds.rest.MapBinder;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Options to customize droplet creation.\n */\npublic class CreateDropletOptions implements MapBinder {\n\n   @Inject private BindToJsonPayload jsonBinder;\n\n   private final Set<Integer> sshKeys;\n   private final boolean backupsEnabled;\n   private final boolean ipv6Enabled;\n   private final boolean privateNetworking;\n   private final String userData;\n\n   private CreateDropletOptions(Set<Integer> sshKeys, boolean backupsEnabled, boolean ipv6Enabled,\n         boolean privateNetworking, @Nullable String userData) {\n      this.sshKeys = sshKeys;\n      this.backupsEnabled = backupsEnabled;\n      this.ipv6Enabled = ipv6Enabled;\n      this.privateNetworking = privateNetworking;\n      this.userData = userData;\n   }\n\n   @AutoValue\n   abstract static class DropletRequest {\n      abstract String name();\n      abstract String region();\n      abstract String size();\n      abstract String image();\n      abstract Set<Integer> sshKeys();\n      abstract Boolean backups();\n      abstract Boolean ipv6();\n      abstract Boolean privateNetworking();\n      @Nullable abstract String userData();\n      \n      @SerializedNames({\"name\", \"region\", \"size\", \"image\", \"ssh_keys\", \"backups\", \"ipv6\", \"private_networking\", \"user_data\"})\n      static DropletRequest create(String name, String region, String size, String image, Set<Integer> sshKeys,\n            Boolean backups, Boolean ipv6, Boolean privateNetworking, String userData) {\n         return new AutoValue_CreateDropletOptions_DropletRequest(name, region, size, image, sshKeys, backups, ipv6,\n               privateNetworking, userData);\n      }\n      \n      DropletRequest() {}\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      DropletRequest droplet = DropletRequest.create(checkNotNull(postParams.get(\"name\"), \"name parameter not present\").toString(),\n            checkNotNull(postParams.get(\"region\"), \"region parameter not present\").toString(),\n            checkNotNull(postParams.get(\"size\"), \"size parameter not present\").toString(),\n            checkNotNull(postParams.get(\"image\"), \"image parameter not present\").toString(),\n            sshKeys, backupsEnabled, ipv6Enabled, privateNetworking, userData);\n\n      return bindToRequest(request, droplet);\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      return jsonBinder.bindToRequest(request, input);\n   }\n\n   public Set<Integer> getSshKeys() {\n      return sshKeys;\n   }\n\n   public Boolean getPrivateNetworking() {\n      return privateNetworking;\n   }\n\n   public Boolean getBackupsEnabled() {\n      return backupsEnabled;\n   }\n\n   public boolean isIpv6Enabled() {\n      return ipv6Enabled;\n   }\n\n   public String getUserData() {\n      return userData;\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n      private ImmutableSet.Builder<Integer> sshKeyIds = ImmutableSet.builder();\n      private boolean backupsEnabled;\n      private boolean ipv6Enabled;\n      private boolean privateNetworking;\n      private String userData;\n\n      /**\n       * Adds a set of ssh key ids to be added to the droplet.\n       */\n      public Builder addSshKeyIds(Iterable<Integer> sshKeyIds) {\n         this.sshKeyIds.addAll(sshKeyIds);\n         return this;\n      }\n\n      /**\n       * Adds an ssh key id to be added to the droplet.\n       */\n      public Builder addSshKeyId(int sshKeyId) {\n         this.sshKeyIds.add(sshKeyId);\n         return this;\n      }\n\n      /**\n       * Enables a private network interface if the region supports private\n       * networking.\n       */\n      public Builder privateNetworking(boolean privateNetworking) {\n         this.privateNetworking = privateNetworking;\n         return this;\n      }\n\n      /**\n       * Enabled backups for the droplet.\n       */\n      public Builder backupsEnabled(boolean backupsEnabled) {\n         this.backupsEnabled = backupsEnabled;\n         return this;\n      }\n\n      /**\n       * Sets the user data for the droplet.\n       */\n      public Builder userData(String userData) {\n         this.userData = userData;\n         return this;\n      }\n\n      /**\n       * Enables/disables IPv6 for the droplet.\n       */\n      public Builder ipv6Enabled(boolean ipv6Enabled) {\n         this.ipv6Enabled = ipv6Enabled;\n         return this;\n      }\n\n      public CreateDropletOptions build() {\n         return new CreateDropletOptions(sshKeyIds.build(), backupsEnabled, ipv6Enabled, privateNetworking, userData);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/domain/options/ImageListOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.domain.options;\n\n/**\n * Custom options to filter the list of images.\n */\npublic class ImageListOptions extends ListOptions {\n   public static final String TYPE_PARAM = \"type\";\n   public static final String PRIVATE_PARAM = \"private\";\n   \n   /**\n    * Configures the type of the images to be retrieved.\n    */\n   public ImageListOptions type(String type) {\n      queryParameters.put(TYPE_PARAM, type);\n      return this;\n   }\n   \n   /**\n    * Get the images of the current user.\n    */\n   public ImageListOptions privateImages(boolean privateImages) {\n      queryParameters.put(PRIVATE_PARAM, String.valueOf(privateImages));\n      return this;\n   }\n   \n   @Override public ImageListOptions perPage(int perPage) {\n      super.perPage(perPage);\n      return this;\n   }\n\n   @Override public ImageListOptions page(int page) {\n      super.page(page);\n      return this;\n   }\n   \n   public static final class Builder {\n      \n      /**\n       * @see {@link ImageListOptions#type(String)}\n       */\n      public static ImageListOptions type(String type) {\n         return new ImageListOptions().type(type);\n      }\n      \n      /**\n       * @see {@link ImageListOptions#privateImages(boolean)}\n       */\n      public static ImageListOptions privateImages(boolean privateImages) {\n         return new ImageListOptions().privateImages(privateImages);\n      }\n      /**\n       * @see {@link ImageListOptions#page(int)}\n       */\n      public static ImageListOptions page(int page) {\n         return new ImageListOptions().page(page);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/domain/options/ListOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.domain.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\n/**\n * Options to customize how paginated lists are returned.\n */\npublic class ListOptions extends BaseHttpRequestOptions {\n   public static final String PAGE_PARAM = \"page\";\n   public static final String PER_PAGE_PARAM = \"per_page\";\n   \n   /**\n    * Configures the number of entries to return in each page.\n    */\n   public ListOptions perPage(int perPage) {\n      queryParameters.put(PER_PAGE_PARAM, String.valueOf(perPage));\n      return this;\n   }\n   \n   /**\n    * Configures the number of the page to be returned.\n    */\n   public ListOptions page(int page) {\n      queryParameters.put(PAGE_PARAM, String.valueOf(page));\n      return this;\n   }\n   \n   public static final class Builder {\n      \n      /**\n       * @see {@link ListOptions#perPage(int)}\n       */\n      public static ListOptions perPage(int perPage) {\n         return new ListOptions().perPage(perPage);\n      }\n      \n      /**\n       * @see {@link ListOptions#page(int)}\n       */\n      public static ListOptions page(int page) {\n         return new ListOptions().page(page);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/exceptions/DigitalOcean2RateLimitExceededException.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.exceptions;\n\nimport static org.jclouds.digitalocean2.handlers.DigitalOcean2RateLimitRetryHandler.millisUntilNextAvailableRequest;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rest.RateLimitExceededException;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Multimap;\nimport com.google.common.collect.Multimaps;\n\n/**\n * Provides detailed information for rate limit exceptions.\n */\n@Beta\npublic class DigitalOcean2RateLimitExceededException extends RateLimitExceededException {\n   private static final long serialVersionUID = 1L;\n   private static final String RATE_LIMIT_HEADER_PREFIX = \"RateLimit-\";\n\n   private Integer totalRequestsPerHour;\n   private Integer remainingRequests;\n   private Long timeToNextAvailableRequest;\n\n   public DigitalOcean2RateLimitExceededException(HttpResponse response) {\n      super(response.getStatusLine() + \"\\n\" + rateLimitHeaders(response));\n      parseRateLimitInfo(response);\n   }\n\n   public DigitalOcean2RateLimitExceededException(HttpResponse response, Throwable cause) {\n      super(response.getStatusLine() + \"\\n\" + rateLimitHeaders(response), cause);\n      parseRateLimitInfo(response);\n   }\n\n   public Integer totalRequestsPerHour() {\n      return totalRequestsPerHour;\n   }\n\n   public Integer remainingRequests() {\n      return remainingRequests;\n   }\n\n   public Long timeToNextAvailableRequest() {\n      return timeToNextAvailableRequest;\n   }\n\n   private void parseRateLimitInfo(HttpResponse response) {\n      String limit = response.getFirstHeaderOrNull(\"RateLimit-Limit\");\n      String remaining = response.getFirstHeaderOrNull(\"RateLimit-Remaining\");\n      String reset = response.getFirstHeaderOrNull(\"RateLimit-Reset\");\n\n      totalRequestsPerHour = limit == null ? null : Integer.valueOf(limit);\n      remainingRequests = remaining == null ? null : Integer.valueOf(remaining);\n      timeToNextAvailableRequest = reset == null ? null : millisUntilNextAvailableRequest(Long.parseLong(reset));\n   }\n\n   private static Multimap<String, String> rateLimitHeaders(HttpResponse response) {\n      return Multimaps.filterKeys(response.getHeaders(), new Predicate<String>() {\n         @Override\n         public boolean apply(String input) {\n            return input.startsWith(RATE_LIMIT_HEADER_PREFIX);\n         }\n      });\n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/features/ActionApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.features;\n\nimport java.beans.ConstructorProperties;\nimport java.io.Closeable;\nimport java.net.URI;\nimport java.util.List;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyIterableWithMarkerOnNotFoundOr404;\nimport org.jclouds.Fallbacks.EmptyPagedIterableOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.PagedIterable;\nimport org.jclouds.digitalocean2.DigitalOcean2Api;\nimport org.jclouds.digitalocean2.domain.Action;\nimport org.jclouds.digitalocean2.domain.internal.PaginatedCollection;\nimport org.jclouds.digitalocean2.domain.options.ListOptions;\nimport org.jclouds.digitalocean2.functions.BaseToPagedIterable;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.Json;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.Transform;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.inject.TypeLiteral;\n\n/**\n * Provides access to Actions via the REST API.\n *\n * @see <a href=\"https://developers.digitalocean.com/v2/#actions\"/>\n * @see ActionApi\n */\n@Path(\"/actions\")\n@RequestFilters(OAuthFilter.class)\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface ActionApi extends Closeable {\n\n   @Named(\"action:list\")\n   @GET\n   @ResponseParser(ParseActions.class)\n   @Transform(ParseActions.ToPagedIterable.class)\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   PagedIterable<Action> list();\n   \n   @Named(\"action:list\")\n   @GET\n   @ResponseParser(ParseActions.class)\n   @Fallback(EmptyIterableWithMarkerOnNotFoundOr404.class)\n   IterableWithMarker<Action> list(ListOptions options);\n   \n   static final class ParseActions extends ParseJson<ParseActions.Actions> {\n      @Inject ParseActions(Json json) {\n         super(json, TypeLiteral.get(Actions.class));\n      }\n\n      private static class Actions extends PaginatedCollection<Action> {\n         @ConstructorProperties({ \"actions\", \"meta\", \"links\" })\n         public Actions(List<Action> items, Meta meta, Links links) {\n            super(items, meta, links);\n         }\n      }\n\n      private static class ToPagedIterable extends BaseToPagedIterable<Action, ListOptions> {\n         @Inject ToPagedIterable(DigitalOcean2Api api, Function<URI, ListOptions> linkToOptions) {\n            super(api, linkToOptions);\n         }\n\n         @Override\n         protected IterableWithMarker<Action> fetchPageUsingOptions(ListOptions options, Optional<Object> arg0) {\n            return api.actionApi().list(options);\n         }\n      }\n   }\n\n   @Named(\"action:get\")\n   @GET\n   @SelectJson(\"action\")\n   @Path(\"/{id}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Action get(@PathParam(\"id\") long id);\n   \n}\n\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/features/DropletApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.features;\n\nimport java.beans.ConstructorProperties;\nimport java.io.Closeable;\nimport java.net.URI;\nimport java.util.List;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyIterableWithMarkerOnNotFoundOr404;\nimport org.jclouds.Fallbacks.EmptyPagedIterableOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.PagedIterable;\nimport org.jclouds.digitalocean2.DigitalOcean2Api;\nimport org.jclouds.digitalocean2.domain.Action;\nimport org.jclouds.digitalocean2.domain.Backup;\nimport org.jclouds.digitalocean2.domain.Droplet;\nimport org.jclouds.digitalocean2.domain.DropletCreate;\nimport org.jclouds.digitalocean2.domain.Kernel;\nimport org.jclouds.digitalocean2.domain.Snapshot;\nimport org.jclouds.digitalocean2.domain.internal.PaginatedCollection;\nimport org.jclouds.digitalocean2.domain.options.CreateDropletOptions;\nimport org.jclouds.digitalocean2.domain.options.ListOptions;\nimport org.jclouds.digitalocean2.functions.BaseToPagedIterable;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.Json;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.Transform;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.inject.TypeLiteral;\n\n/**\n * Provides access to Droplets via their REST API.\n *\n * @see <a href=\"https://developers.digitalocean.com/v2/#droplets\"/>\n * @see DropletApi\n */\n@Path(\"/droplets\")\n@RequestFilters(OAuthFilter.class)\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface DropletApi extends Closeable {\n\n   @Named(\"droplet:list\")\n   @GET\n   @ResponseParser(ParseDroplets.class)\n   @Transform(ParseDroplets.ToPagedIterable.class)\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   PagedIterable<Droplet> list();\n\n   @Named(\"droplet:list\")\n   @GET\n   @ResponseParser(ParseDroplets.class)\n   @Fallback(EmptyIterableWithMarkerOnNotFoundOr404.class)\n   IterableWithMarker<Droplet> list(ListOptions options);\n\n   static final class ParseDroplets extends ParseJson<ParseDroplets.Droplets> {\n      @Inject ParseDroplets(Json json) {\n         super(json, TypeLiteral.get(Droplets.class));\n      }\n\n      private static class Droplets extends PaginatedCollection<Droplet> {\n         @ConstructorProperties({ \"droplets\", \"meta\", \"links\" })\n         public Droplets(List<Droplet> items, Meta meta, Links links) {\n            super(items, meta, links);\n         }\n      }\n\n      private static class ToPagedIterable extends BaseToPagedIterable<Droplet, ListOptions> {\n         @Inject ToPagedIterable(DigitalOcean2Api api, Function<URI, ListOptions> linkToOptions) {\n            super(api, linkToOptions);\n         }\n\n         @Override\n         protected IterableWithMarker<Droplet> fetchPageUsingOptions(ListOptions options, Optional<Object> arg0) {\n            return api.dropletApi().list(options);\n         }\n      }\n   }\n\n   @Named(\"droplet:listkernels\")\n   @GET\n   @Path(\"/{id}/kernels\")\n   @ResponseParser(ParseKernels.class)\n   @Transform(ParseKernels.ToPagedIterable.class)\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   PagedIterable<Kernel> listKernels(@PathParam(\"id\") int id);\n\n   @Named(\"droplet:listkernels\")\n   @GET\n   @Path(\"/{id}/kernels\")\n   @ResponseParser(ParseKernels.class)\n   @Fallback(EmptyIterableWithMarkerOnNotFoundOr404.class)\n   IterableWithMarker<Kernel> listKernels(@PathParam(\"id\") int id, ListOptions options);\n\n   static final class ParseKernels extends ParseJson<ParseKernels.Kernels> {\n      @Inject ParseKernels(Json json) {\n         super(json, TypeLiteral.get(Kernels.class));\n      }\n\n      private static class Kernels extends PaginatedCollection<Kernel> {\n         @ConstructorProperties({ \"kernels\", \"meta\", \"links\" })\n         public Kernels(List<Kernel> items, Meta meta, Links links) {\n            super(items, meta, links);\n         }\n      }\n\n      private static class ToPagedIterable extends BaseToPagedIterable<Kernel, ListOptions> {\n         @Inject ToPagedIterable(DigitalOcean2Api api, Function<URI, ListOptions> linkToOptions) {\n            super(api, linkToOptions);\n         }\n\n         @Override\n         protected IterableWithMarker<Kernel> fetchPageUsingOptions(ListOptions options, Optional<Object> arg0) {\n            return api.dropletApi().listKernels((Integer) arg0.get(), options);\n         }\n      }\n   }\n\n   @Named(\"droplet:listsnapshots\")\n   @GET\n   @Path(\"/{id}/snapshots\")\n   @ResponseParser(ParseSnapshots.class)\n   @Transform(ParseSnapshots.ToPagedIterable.class)\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   PagedIterable<Snapshot> listSnapshots(@PathParam(\"id\") int id);\n\n   @Named(\"droplet:listsnapshots\")\n   @GET\n   @Path(\"/{id}/snapshots\")\n   @ResponseParser(ParseSnapshots.class)\n   @Fallback(EmptyIterableWithMarkerOnNotFoundOr404.class)\n   IterableWithMarker<Snapshot> listSnapshots(@PathParam(\"id\") int id, ListOptions options);\n\n   static final class ParseSnapshots extends ParseJson<ParseSnapshots.Snapshots> {\n      @Inject ParseSnapshots(Json json) {\n         super(json, TypeLiteral.get(Snapshots.class));\n      }\n\n      private static class Snapshots extends PaginatedCollection<Snapshot> {\n         @ConstructorProperties({ \"snapshots\", \"meta\", \"links\" })\n         public Snapshots(List<Snapshot> items, Meta meta, Links links) {\n            super(items, meta, links);\n         }\n      }\n\n      private static class ToPagedIterable extends BaseToPagedIterable<Snapshot, ListOptions> {\n         @Inject ToPagedIterable(DigitalOcean2Api api, Function<URI, ListOptions> linkToOptions) {\n            super(api, linkToOptions);\n         }\n\n         @Override\n         protected IterableWithMarker<Snapshot> fetchPageUsingOptions(ListOptions options, Optional<Object> arg0) {\n            return api.dropletApi().listSnapshots((Integer) arg0.get(), options);\n         }\n      }\n   }\n\n   @Named(\"droplet:listbackups\")\n   @GET\n   @Path(\"/{id}/backups\")\n   @ResponseParser(ParseBackups.class)\n   @Transform(ParseBackups.ToPagedIterable.class)\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   PagedIterable<Backup> listBackups(@PathParam(\"id\") int id);\n\n   @Named(\"droplet:listbackups\")\n   @GET\n   @Path(\"/{id}/backups\")\n   @ResponseParser(ParseBackups.class)\n   @Fallback(EmptyIterableWithMarkerOnNotFoundOr404.class)\n   IterableWithMarker<Backup> listBackups(@PathParam(\"id\") int id, ListOptions options);\n\n   static final class ParseBackups extends ParseJson<ParseBackups.Backups> {\n      @Inject ParseBackups(Json json) {\n         super(json, TypeLiteral.get(Backups.class));\n      }\n\n      private static class Backups extends PaginatedCollection<Backup> {\n         @ConstructorProperties({ \"backups\", \"meta\", \"links\" })\n         public Backups(List<Backup> items, Meta meta, Links links) {\n            super(items, meta, links);\n         }\n      }\n\n      private static class ToPagedIterable extends BaseToPagedIterable<Backup, ListOptions> {\n         @Inject ToPagedIterable(DigitalOcean2Api api, Function<URI, ListOptions> linkToOptions) {\n            super(api, linkToOptions);\n         }\n\n         @Override\n         protected IterableWithMarker<Backup> fetchPageUsingOptions(ListOptions options, Optional<Object> arg0) {\n            return api.dropletApi().listBackups((Integer) arg0.get(), options);\n         }\n      }\n   }\n\n   @Named(\"droplet:actions\")\n   @GET\n   @Path(\"/{id}/actions\")\n   @ResponseParser(ParseDropletActions.class)\n   @Transform(ParseDropletActions.ToPagedIterable.class)\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   PagedIterable<Action> listActions(@PathParam(\"id\") int id);\n\n   @Named(\"droplet:actions\")\n   @GET\n   @Path(\"/{id}/actions\")\n   @ResponseParser(ParseDropletActions.class)\n   @Fallback(EmptyIterableWithMarkerOnNotFoundOr404.class)\n   IterableWithMarker<Action> listActions(@PathParam(\"id\") int id, ListOptions options);\n\n   static final class ParseDropletActions extends ParseJson<ParseDropletActions.DropletActions> {\n      @Inject ParseDropletActions(Json json) {\n         super(json, TypeLiteral.get(DropletActions.class));\n      }\n\n      private static class DropletActions extends PaginatedCollection<Action> {\n         @ConstructorProperties({ \"actions\", \"meta\", \"links\" })\n         public DropletActions(List<Action> items, Meta meta, Links links) {\n            super(items, meta, links);\n         }\n      }\n\n      private static class ToPagedIterable extends BaseToPagedIterable<Action, ListOptions> {\n         @Inject ToPagedIterable(DigitalOcean2Api api, Function<URI, ListOptions> linkToOptions) {\n            super(api, linkToOptions);\n         }\n\n         @Override\n         protected IterableWithMarker<Action> fetchPageUsingOptions(ListOptions options, Optional<Object> arg0) {\n            return api.dropletApi().listActions((Integer) arg0.get(), options);\n         }\n      }\n   }\n\n   @Named(\"droplet:create\")\n   @POST\n   @Produces(MediaType.APPLICATION_JSON)\n   @MapBinder(BindToJsonPayload.class)\n   DropletCreate create(@PayloadParam(\"name\") String name, @PayloadParam(\"region\") String region,\n         @PayloadParam(\"size\") String size, @PayloadParam(\"image\") String image);\n\n   @Named(\"droplet:create\")\n   @POST\n   @Produces(MediaType.APPLICATION_JSON)\n   @MapBinder(CreateDropletOptions.class)\n   DropletCreate create(@PayloadParam(\"name\") String name, @PayloadParam(\"region\") String region,\n         @PayloadParam(\"size\") String size, @PayloadParam(\"image\") String image, CreateDropletOptions options);\n\n   @Named(\"droplet:get\")\n   @GET\n   @SelectJson(\"droplet\")\n   @Path(\"/{id}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Droplet get(@PathParam(\"id\") int id);\n\n   @Named(\"droplet:delete\")\n   @DELETE\n   @Path(\"/{id}\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void delete(@PathParam(\"id\") int id);\n\n   @Named(\"droplet:reboot\")\n   @POST\n   @Produces(MediaType.APPLICATION_JSON)\n   @SelectJson(\"action\")\n   @Path(\"/{id}/actions\")\n   @Payload(\"{\\\"type\\\":\\\"reboot\\\"}\")\n   Action reboot(@PathParam(\"id\") int id);\n\n   @Named(\"droplet:powercycle\")\n   @POST\n   @Produces(MediaType.APPLICATION_JSON)\n   @SelectJson(\"action\")\n   @Path(\"/{id}/actions\")\n   @Payload(\"{\\\"type\\\":\\\"power_cycle\\\"}\")\n   Action powerCycle(@PathParam(\"id\") int id);\n\n   @Named(\"droplet:shutdown\")\n   @POST\n   @Produces(MediaType.APPLICATION_JSON)\n   @SelectJson(\"action\")\n   @Path(\"/{id}/actions\")\n   @Payload(\"{\\\"type\\\":\\\"shutdown\\\"}\")\n   Action shutdown(@PathParam(\"id\") int id);\n\n   @Named(\"droplet:poweroff\")\n   @POST\n   @Produces(MediaType.APPLICATION_JSON)\n   @SelectJson(\"action\")\n   @Path(\"/{id}/actions\")\n   @Payload(\"{\\\"type\\\":\\\"power_off\\\"}\")\n   Action powerOff(@PathParam(\"id\") int id);\n\n   @Named(\"droplet:poweron\")\n   @POST\n   @Produces(MediaType.APPLICATION_JSON)\n   @SelectJson(\"action\")\n   @Path(\"/{id}/actions\")\n   @Payload(\"{\\\"type\\\":\\\"power_on\\\"}\")\n   Action powerOn(@PathParam(\"id\") int id);\n\n   @Named(\"droplet:snapshot\")\n   @POST\n   @Produces(MediaType.APPLICATION_JSON)\n   @SelectJson(\"action\")\n   @Path(\"/{id}/actions\")\n   @Payload(\"%7B\\\"type\\\":\\\"snapshot\\\",\\\"name\\\":\\\"{name}\\\"%7D\")\n   Action snapshot(@PathParam(\"id\") int id, @PayloadParam(\"name\") String name);\n\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/features/ImageApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.features;\n\nimport java.beans.ConstructorProperties;\nimport java.io.Closeable;\nimport java.net.URI;\nimport java.util.List;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyIterableWithMarkerOnNotFoundOr404;\nimport org.jclouds.Fallbacks.EmptyPagedIterableOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.PagedIterable;\nimport org.jclouds.digitalocean2.DigitalOcean2Api;\nimport org.jclouds.digitalocean2.domain.Image;\nimport org.jclouds.digitalocean2.domain.internal.PaginatedCollection;\nimport org.jclouds.digitalocean2.domain.options.ImageListOptions;\nimport org.jclouds.digitalocean2.functions.BaseToPagedIterable;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.Json;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.Transform;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.inject.TypeLiteral;\n\n/**\n * Provides access to Images via the REST API.\n *\n * @see <a href=\"https://developers.digitalocean.com/v2/#images\"/>\n * @see ImageApi\n */\n@Path(\"/images\")\n@RequestFilters(OAuthFilter.class)\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface ImageApi extends Closeable {\n\n   @Named(\"image:list\")\n   @GET\n   @ResponseParser(ParseImages.class)\n   @Transform(ParseImages.ToPagedIterable.class)\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   PagedIterable<Image> list();\n   \n   @Named(\"image:list\")\n   @GET\n   @ResponseParser(ParseImages.class)\n   @Fallback(EmptyIterableWithMarkerOnNotFoundOr404.class)\n   IterableWithMarker<Image> list(ImageListOptions options);\n   \n   static final class ParseImages extends ParseJson<ParseImages.Images> {\n      @Inject ParseImages(Json json) {\n         super(json, TypeLiteral.get(Images.class));\n      }\n\n      private static class Images extends PaginatedCollection<Image> {\n         @ConstructorProperties({ \"images\", \"meta\", \"links\" })\n         public Images(List<Image> items, Meta meta, Links links) {\n            super(items, meta, links);\n         }\n      }\n\n      private static class ToPagedIterable extends BaseToPagedIterable<Image, ImageListOptions> {\n         @Inject ToPagedIterable(DigitalOcean2Api api, Function<URI, ImageListOptions> linkToOptions) {\n            super(api, linkToOptions);\n         }\n\n         @Override\n         protected IterableWithMarker<Image> fetchPageUsingOptions(ImageListOptions options, Optional<Object> arg0) {\n            return api.imageApi().list(options);\n         }\n      }\n   }\n\n   @Named(\"image:get\")\n   @GET\n   @SelectJson(\"image\")\n   @Path(\"/{id}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Image get(@PathParam(\"id\") int id);\n\n   @Named(\"image:get\")\n   @GET\n   @SelectJson(\"image\")\n   @Path(\"/{slug}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Image get(@PathParam(\"slug\") String slug);\n\n   @Named(\"image:delete\")\n   @DELETE\n   @Path(\"/{id}\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void delete(@PathParam(\"id\") int id);\n\n   //TODO: Add delete and create\n\n}\n\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/features/KeyApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.features;\n\nimport java.beans.ConstructorProperties;\nimport java.io.Closeable;\nimport java.net.URI;\nimport java.util.List;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyIterableWithMarkerOnNotFoundOr404;\nimport org.jclouds.Fallbacks.EmptyPagedIterableOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.PagedIterable;\nimport org.jclouds.digitalocean2.DigitalOcean2Api;\nimport org.jclouds.digitalocean2.domain.Key;\nimport org.jclouds.digitalocean2.domain.internal.PaginatedCollection;\nimport org.jclouds.digitalocean2.domain.options.ListOptions;\nimport org.jclouds.digitalocean2.functions.BaseToPagedIterable;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.Json;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.Transform;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.inject.TypeLiteral;\n\n/**\n * Provides access to Keys via the REST API.\n *\n * @see <a href=\"https://developers.digitalocean.com/v2/#keys\"/>\n * @see KeyApi\n */\n@Path(\"/account/keys\")\n@RequestFilters(OAuthFilter.class)\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface KeyApi extends Closeable {\n\n   @Named(\"key:list\")\n   @GET\n   @ResponseParser(ParseKeys.class)\n   @Transform(ParseKeys.ToPagedIterable.class)\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   PagedIterable<Key> list();\n\n   @Named(\"key:list\")\n   @GET\n   @ResponseParser(ParseKeys.class)\n   @Fallback(EmptyIterableWithMarkerOnNotFoundOr404.class)\n   IterableWithMarker<Key> list(ListOptions options);\n   \n   static final class ParseKeys extends ParseJson<ParseKeys.Keys> {\n      @Inject ParseKeys(Json json) {\n         super(json, TypeLiteral.get(Keys.class));\n      }\n\n      private static class Keys extends PaginatedCollection<Key> {\n         @ConstructorProperties({ \"ssh_keys\", \"meta\", \"links\" })\n         public Keys(List<Key> items, Meta meta, Links links) {\n            super(items, meta, links);\n         }\n      }\n\n      private static class ToPagedIterable extends BaseToPagedIterable<Key, ListOptions> {\n         @Inject ToPagedIterable(DigitalOcean2Api api, Function<URI, ListOptions> linkToOptions) {\n            super(api, linkToOptions);\n         }\n\n         @Override\n         protected IterableWithMarker<Key> fetchPageUsingOptions(ListOptions options, Optional<Object> arg0) {\n            return api.keyApi().list(options);\n         }\n      }\n   }\n\n   @Named(\"key:create\")\n   @POST\n   @Produces(MediaType.APPLICATION_JSON)\n   @SelectJson(\"ssh_key\")\n   @MapBinder(BindToJsonPayload.class)\n   Key create(@PayloadParam(\"name\") String name, @PayloadParam(\"public_key\") String key);\n\n   @Named(\"key:get\")\n   @GET\n   @SelectJson(\"ssh_key\")\n   @Path(\"/{id}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Key get(@PathParam(\"id\") int id);\n\n   @Named(\"key:get\")\n   @GET\n   @SelectJson(\"ssh_key\")\n   @Path(\"/{fingerprint}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Key get(@PathParam(\"fingerprint\") String fingerprint);\n\n   @Named(\"key:update\")\n   @PUT\n   @Produces(MediaType.APPLICATION_JSON)\n   @SelectJson(\"ssh_key\")\n   @Path(\"/{id}\")\n   @MapBinder(BindToJsonPayload.class)\n   Key update(@PathParam(\"id\") int id, @PayloadParam(\"name\") String name);\n\n   @Named(\"key:update\")\n   @PUT\n   @Produces(MediaType.APPLICATION_JSON)\n   @SelectJson(\"ssh_key\")\n   @Path(\"/{fingerprint}\")\n   @MapBinder(BindToJsonPayload.class)\n   Key update(@PathParam(\"fingerprint\") String fingerprint, @PayloadParam(\"name\") String name);\n\n   @Named(\"key:delete\")\n   @DELETE\n   @Path(\"/{id}\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void delete(@PathParam(\"id\") int id);\n\n   @Named(\"key:delete\")\n   @DELETE\n   @Path(\"/{fingerprint}\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void delete(@PathParam(\"fingerprint\") String fingerprint);\n\n}\n\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/features/RegionApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.features;\n\nimport java.beans.ConstructorProperties;\nimport java.io.Closeable;\nimport java.net.URI;\nimport java.util.List;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyIterableWithMarkerOnNotFoundOr404;\nimport org.jclouds.Fallbacks.EmptyPagedIterableOnNotFoundOr404;\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.PagedIterable;\nimport org.jclouds.digitalocean2.DigitalOcean2Api;\nimport org.jclouds.digitalocean2.domain.Region;\nimport org.jclouds.digitalocean2.domain.internal.PaginatedCollection;\nimport org.jclouds.digitalocean2.domain.options.ListOptions;\nimport org.jclouds.digitalocean2.functions.BaseToPagedIterable;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.Transform;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.inject.TypeLiteral;\n\n/**\n * Provides access to Regions via the REST API.\n */\n@Path(\"/regions\")\n@RequestFilters(OAuthFilter.class)\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface RegionApi extends Closeable {\n\n   /**\n    * Get the list of all regions.\n    * \n    * @return The (paginated) list of all regions.\n    */\n   @Named(\"region:list\")\n   @GET\n   @ResponseParser(ParseRegions.class)\n   @Transform(ParseRegions.ToPagedIterable.class)\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   PagedIterable<Region> list();\n\n   /**\n    * Get a single page of the region list.\n    * \n    * @param options The options to configure the page to get and the size of the page.\n    * @return The page with the requested regions.\n    */\n   @Named(\"region:list\")\n   @GET\n   @ResponseParser(ParseRegions.class)\n   @Fallback(EmptyIterableWithMarkerOnNotFoundOr404.class)\n   IterableWithMarker<Region> list(ListOptions options);\n\n   static final class ParseRegions extends ParseJson<ParseRegions.Regions> {\n      @Inject ParseRegions(Json json) {\n         super(json, TypeLiteral.get(Regions.class));\n      }\n\n      private static class Regions extends PaginatedCollection<Region> {\n         @ConstructorProperties({ \"regions\", \"meta\", \"links\" })\n         public Regions(List<Region> items, Meta meta, Links links) {\n            super(items, meta, links);\n         }\n      }\n\n      static class ToPagedIterable extends BaseToPagedIterable<Region, ListOptions> {\n         @Inject ToPagedIterable(DigitalOcean2Api api, Function<URI, ListOptions> linkToOptions) {\n            super(api, linkToOptions);\n         }\n\n         @Override\n         protected IterableWithMarker<Region> fetchPageUsingOptions(ListOptions options, Optional<Object> arg0) {\n            return api.regionApi().list(options);\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/features/SizeApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.features;\n\nimport java.beans.ConstructorProperties;\nimport java.io.Closeable;\nimport java.net.URI;\nimport java.util.List;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptyIterableWithMarkerOnNotFoundOr404;\nimport org.jclouds.Fallbacks.EmptyPagedIterableOnNotFoundOr404;\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.PagedIterable;\nimport org.jclouds.digitalocean2.DigitalOcean2Api;\nimport org.jclouds.digitalocean2.domain.Size;\nimport org.jclouds.digitalocean2.domain.internal.PaginatedCollection;\nimport org.jclouds.digitalocean2.domain.options.ListOptions;\nimport org.jclouds.digitalocean2.functions.BaseToPagedIterable;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.Transform;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.inject.TypeLiteral;\n\n/**\n * Provides access to Sizes via the REST API.\n *\n * @see <a href=\"https://developers.digitalocean.com/v2/#sizes\"/>\n * @see org.jclouds.digitalocean2.features.SizeApi\n */\n@Path(\"/sizes\")\n@RequestFilters(OAuthFilter.class)\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface SizeApi extends Closeable {\n\n   @Named(\"size:list\")\n   @GET\n   @ResponseParser(ParseSizes.class)\n   @Transform(ParseSizes.ToPagedIterable.class)\n   @Fallback(EmptyPagedIterableOnNotFoundOr404.class)\n   PagedIterable<Size> list();\n\n   @Named(\"size:list\")\n   @GET\n   @ResponseParser(ParseSizes.class)\n   @Fallback(EmptyIterableWithMarkerOnNotFoundOr404.class)\n   IterableWithMarker<Size> list(ListOptions options);\n\n   static final class ParseSizes extends ParseJson<ParseSizes.Sizes> {\n      @Inject ParseSizes(Json json) {\n         super(json, TypeLiteral.get(Sizes.class));\n      }\n\n      private static class Sizes extends PaginatedCollection<Size> {\n         @ConstructorProperties({ \"sizes\", \"meta\", \"links\" })\n         public Sizes(List<Size> items, Meta meta, Links links) {\n            super(items, meta, links);\n         }\n      }\n\n      private static class ToPagedIterable extends BaseToPagedIterable<Size, ListOptions> {\n         @Inject ToPagedIterable(DigitalOcean2Api api, Function<URI, ListOptions> linkToOptions) {\n            super(api, linkToOptions);\n         }\n\n         @Override\n         protected IterableWithMarker<Size> fetchPageUsingOptions(ListOptions options, Optional<Object> arg0) {\n            return api.sizeApi().list(options);\n         }\n      }\n   }\n}\n\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/functions/BaseToPagedIterable.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.functions;\n\nimport java.net.URI;\n\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.internal.Arg0ToPagedIterable;\nimport org.jclouds.digitalocean2.DigitalOcean2Api;\nimport org.jclouds.digitalocean2.domain.options.ListOptions;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\n\n/**\n * Base class to implement the functions that build the\n * <code>PagedIterable</code>. Subclasses just need to override the\n * {@link #fetchPageUsingOptions(ListOptions, Optional)} to invoke the right API\n * method with the given options parameter to get the next page.\n */\npublic abstract class BaseToPagedIterable<T, O extends ListOptions> extends\n      Arg0ToPagedIterable<T, BaseToPagedIterable<T, O>> {\n   private final Function<URI, O> linkToOptions;\n   protected final DigitalOcean2Api api;\n\n   protected BaseToPagedIterable(DigitalOcean2Api api, Function<URI, O> linkToOptions) {\n      this.api = api;\n      this.linkToOptions = linkToOptions;\n   }\n\n   protected abstract IterableWithMarker<T> fetchPageUsingOptions(O options, Optional<Object> arg0);\n\n   @Override protected Function<Object, IterableWithMarker<T>> markerToNextForArg0(final Optional<Object> arg0) {\n      return new Function<Object, IterableWithMarker<T>>() {\n         @Override\n         public IterableWithMarker<T> apply(Object input) {\n            O nextOptions = linkToOptions.apply(URI.class.cast(input));\n            return fetchPageUsingOptions(nextOptions, arg0);\n         }\n      };\n   }\n\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/functions/LinkToImageListOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.digitalocean2.domain.options.ImageListOptions.PRIVATE_PARAM;\nimport static org.jclouds.digitalocean2.domain.options.ImageListOptions.TYPE_PARAM;\nimport static org.jclouds.digitalocean2.domain.options.ListOptions.PAGE_PARAM;\nimport static org.jclouds.digitalocean2.domain.options.ListOptions.PER_PAGE_PARAM;\nimport static org.jclouds.digitalocean2.functions.LinkToListOptions.getFirstOrNull;\nimport static org.jclouds.http.utils.Queries.queryParser;\n\nimport java.net.URI;\n\nimport org.jclouds.digitalocean2.domain.options.ImageListOptions;\nimport org.jclouds.digitalocean2.domain.options.ListOptions;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.Multimap;\n\n/**\n * Transforms a link returned by the API into a {@link ListOptions} that can be\n * used to perform a request to get another page of a paginated list.\n */\npublic class LinkToImageListOptions implements Function<URI, ImageListOptions> {\n\n   @Override public ImageListOptions apply(URI input) {\n      checkNotNull(input, \"input cannot be null\");\n\n      Multimap<String, String> queryParams = queryParser().apply(input.getQuery());\n      String nextPage = getFirstOrNull(PAGE_PARAM, queryParams);\n      String nextPerPage = getFirstOrNull(PER_PAGE_PARAM, queryParams);\n      String nextType = getFirstOrNull(TYPE_PARAM, queryParams);\n      String nextPrivate = getFirstOrNull(PRIVATE_PARAM, queryParams);\n\n      ImageListOptions options = new ImageListOptions();\n      if (nextPage != null) {\n         options.page(Integer.parseInt(nextPage));\n      }\n      if (nextPerPage != null) {\n         options.perPage(Integer.parseInt(nextPerPage));\n      }\n      if (nextType != null) {\n         options.type(nextType);\n      }\n      if (nextPrivate != null) {\n         options.privateImages(Boolean.parseBoolean(nextPrivate));\n      }\n\n      return options;\n   }\n\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/functions/LinkToListOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Strings.emptyToNull;\nimport static com.google.common.collect.Iterables.getFirst;\nimport static org.jclouds.digitalocean2.domain.options.ListOptions.PAGE_PARAM;\nimport static org.jclouds.digitalocean2.domain.options.ListOptions.PER_PAGE_PARAM;\nimport static org.jclouds.http.utils.Queries.queryParser;\n\nimport java.net.URI;\n\nimport org.jclouds.digitalocean2.domain.options.ListOptions;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.Multimap;\n\n/**\n * Transforms a link returned by the API into a {@link ListOptions} that can be\n * used to perform a request to get another page of a paginated list.\n */\npublic class LinkToListOptions implements Function<URI, ListOptions> {\n\n   @Override public ListOptions apply(URI input) {\n      checkNotNull(input, \"input cannot be null\");\n\n      Multimap<String, String> queryParams = queryParser().apply(input.getQuery());\n      String nextPage = getFirstOrNull(PAGE_PARAM, queryParams);\n      String nextPerPage = getFirstOrNull(PER_PAGE_PARAM, queryParams);\n\n      ListOptions options = new ListOptions();\n      if (nextPage != null) {\n         options.page(Integer.parseInt(nextPage));\n      }\n      if (nextPerPage != null) {\n         options.perPage(Integer.parseInt(nextPerPage));\n      }\n\n      return options;\n   }\n\n   public static String getFirstOrNull(String key, Multimap<String, String> params) {\n      return params.containsKey(key) ? emptyToNull(getFirst(params.get(key), null)) : null;\n   }\n\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/handlers/DigitalOcean2ErrorHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.handlers;\n\nimport static org.jclouds.http.HttpUtils.closeClientButKeepContentStream;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.digitalocean2.exceptions.DigitalOcean2RateLimitExceededException;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.InsufficientResourcesException;\nimport org.jclouds.rest.ResourceNotFoundException;\n\n/**\n * This will parse and set an appropriate exception on the command object.\n */\n@Singleton\npublic class DigitalOcean2ErrorHandler implements HttpErrorHandler {\n\n   public void handleError(HttpCommand command, HttpResponse response) {\n      // it is important to always read fully and close streams\n      byte[] data = closeClientButKeepContentStream(response);\n      String message = data != null ? new String(data) : null;\n\n      Exception exception = message != null ? new HttpResponseException(command, response, message)\n            : new HttpResponseException(command, response);\n      message = message != null ? message : String.format(\"%s -> %s\", command.getCurrentRequest().getRequestLine(),\n            response.getStatusLine());\n      switch (response.getStatusCode()) {\n         case 400:\n            break;\n         case 401:\n         case 403:\n            if (message.contains(\"droplet limit\")) {\n               exception = new InsufficientResourcesException(message, exception);\n            } else {\n               exception = new AuthorizationException(message, exception);\n            }\n            break;\n         case 404:\n            if (!command.getCurrentRequest().getMethod().equals(\"DELETE\")) {\n               exception = new ResourceNotFoundException(message, exception);\n            }\n            break;\n         case 409:\n            exception = new IllegalStateException(message, exception);\n            break;\n         case 429:\n            exception = new DigitalOcean2RateLimitExceededException(response, exception);\n            break;\n      }\n      command.setException(exception);\n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/handlers/DigitalOcean2RateLimitRetryHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.handlers;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.handlers.RateLimitRetryHandler;\n\nimport com.google.common.base.Optional;\n\n@Singleton\npublic class DigitalOcean2RateLimitRetryHandler extends RateLimitRetryHandler {\n\n   @Override\n   protected Optional<Long> millisToNextAvailableRequest(HttpCommand command, HttpResponse response) {\n      // The header is the Unix epoch time when the next request can be done\n      String epochForNextAvailableRequest = response.getFirstHeaderOrNull(\"RateLimit-Reset\");\n      if (epochForNextAvailableRequest == null) {\n         return Optional.absent();\n      }\n      return Optional.of(millisUntilNextAvailableRequest(Long.parseLong(epochForNextAvailableRequest)));\n   }\n\n   public static long millisUntilNextAvailableRequest(long epochForNextAvailableRequest) {\n      return (epochForNextAvailableRequest * 1000) - System.currentTimeMillis();\n   }\n\n   \n}\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/ssh/DSAKeys.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.ssh;\n\nimport static com.google.common.base.Joiner.on;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Splitter.fixedLength;\nimport static com.google.common.base.Throwables.propagate;\nimport static com.google.common.collect.Iterables.get;\nimport static com.google.common.collect.Iterables.size;\nimport static com.google.common.io.BaseEncoding.base16;\nimport static com.google.common.io.BaseEncoding.base64;\nimport static org.jclouds.util.Strings2.toStringAndClose;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.math.BigInteger;\nimport java.security.interfaces.DSAParams;\nimport java.security.interfaces.DSAPublicKey;\nimport java.security.spec.DSAPublicKeySpec;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.base.Splitter;\nimport com.google.common.hash.HashCode;\nimport com.google.common.hash.Hashing;\nimport com.google.common.io.ByteSource;\nimport com.google.common.io.ByteStreams;\n\n/**\n * Utility methods to work with DSA SSH keys.\n * <p>\n * Methods in this class should be moved to the {@link org.jclouds.ssh.SshKeys} class.\n * \n * \n * @see org.jclouds.ssh.SshKeys\n */\npublic class DSAKeys {\n\n   public static String encodeAsOpenSSH(DSAPublicKey key) {\n      DSAParams params = key.getParams();\n      byte[] keyBlob = keyBlob(params.getP(), params.getQ(), params.getG(), key.getY());\n      return \"ssh-dss \" + base64().encode(keyBlob);\n   }\n\n   /**\n    * Executes {@link org.jclouds.crypto.Pems#publicKeySpecFromOpenSSH(com.google.common.io.InputSupplier)} on the\n    * string which was OpenSSH Base64 Encoded {@code id_rsa.pub}\n    * \n    * @param idRsaPub formatted {@code ssh-dss AAAAB3NzaC1yc2EAAAADAQABAAAB...}\n    * @see org.jclouds.crypto.Pems#publicKeySpecFromOpenSSH(com.google.common.io.InputSupplier)\n    */\n   public static DSAPublicKeySpec publicKeySpecFromOpenSSH(String idDsaPub) {\n      try {\n         return publicKeySpecFromOpenSSH(ByteSource.wrap(idDsaPub.getBytes(Charsets.UTF_8)));\n      } catch (IOException e) {\n         throw propagate(e);\n      }\n   }\n\n   /**\n    * Returns {@link java.security.spec.DSAPublicKeySpec} which was OpenSSH Base64 Encoded {@code id_rsa.pub}\n    *\n    * @param supplier the input stream factory, formatted {@code ssh-dss AAAAB3NzaC1yc2EAAAADAQABAAAB...}\n    *\n    * @return the {@link java.security.spec.DSAPublicKeySpec} which was OpenSSH Base64 Encoded {@code id_rsa.pub}\n    * @throws java.io.IOException if an I/O error occurs\n    */\n   public static DSAPublicKeySpec publicKeySpecFromOpenSSH(ByteSource supplier) throws IOException {\n      InputStream stream = supplier.openStream();\n      Iterable<String> parts = Splitter.on(' ').split(toStringAndClose(stream).trim());\n      checkArgument(size(parts) >= 2 && \"ssh-dss\".equals(get(parts, 0)), \"bad format, should be: ssh-dss AAAAB3...\");\n      stream = new ByteArrayInputStream(base64().decode(get(parts, 1)));\n      String marker = new String(readLengthFirst(stream));\n      checkArgument(\"ssh-dss\".equals(marker), \"looking for marker ssh-dss but got %s\", marker);\n      BigInteger p = new BigInteger(readLengthFirst(stream));\n      BigInteger q = new BigInteger(readLengthFirst(stream));\n      BigInteger g = new BigInteger(readLengthFirst(stream));\n      BigInteger y = new BigInteger(readLengthFirst(stream));\n      return new DSAPublicKeySpec(y, p, q, g);\n   }\n\n   /**\n    * @param publicKeyOpenSSH RSA public key in OpenSSH format\n    * @return fingerprint ex. {@code 2b:a9:62:95:5b:8b:1d:61:e0:92:f7:03:10:e9:db:d9}\n    */\n   public static String fingerprintPublicKey(String publicKeyOpenSSH) {\n      DSAPublicKeySpec publicKeySpec = publicKeySpecFromOpenSSH(publicKeyOpenSSH);\n      return fingerprint(publicKeySpec.getP(), publicKeySpec.getQ(), publicKeySpec.getG(), publicKeySpec.getY());\n   }\n\n   /**\n    * Create a fingerprint per the following <a href=\"http://tools.ietf.org/html/draft-friedl-secsh-fingerprint-00\"\n    * >spec</a>\n    * \n    * @return hex fingerprint ex. {@code 2b:a9:62:95:5b:8b:1d:61:e0:92:f7:03:10:e9:db:d9}\n    */\n   public static String fingerprint(BigInteger p, BigInteger q, BigInteger g, BigInteger y) {\n      byte[] keyBlob = keyBlob(p, q, g, y);\n      return hexColonDelimited(Hashing.md5().hashBytes(keyBlob));\n   }\n\n   /**\n    * @see org.jclouds.ssh.SshKeys\n    */\n   private static String hexColonDelimited(HashCode hc) {\n      return on(':').join(fixedLength(2).split(base16().lowerCase().encode(hc.asBytes())));\n   }\n\n   /**\n    * @see org.jclouds.ssh.SshKeys\n    */\n   private static byte[] keyBlob(BigInteger p, BigInteger q, BigInteger g, BigInteger y) {\n      try {\n         ByteArrayOutputStream out = new ByteArrayOutputStream();\n         writeLengthFirst(\"ssh-dss\".getBytes(), out);\n         writeLengthFirst(p.toByteArray(), out);\n         writeLengthFirst(q.toByteArray(), out);\n         writeLengthFirst(g.toByteArray(), out);\n         writeLengthFirst(y.toByteArray(), out);\n         return out.toByteArray();\n      } catch (IOException e) {\n         throw propagate(e);\n      }\n   }\n\n   /**\n    * @see org.jclouds.ssh.SshKeys\n    */\n   // http://www.ietf.org/rfc/rfc4253.txt\n   private static byte[] readLengthFirst(InputStream in) throws IOException {\n      int byte1 = in.read();\n      int byte2 = in.read();\n      int byte3 = in.read();\n      int byte4 = in.read();\n      int length = (byte1 << 24) + (byte2 << 16) + (byte3 << 8) + (byte4 << 0);\n      byte[] val = new byte[length];\n      ByteStreams.readFully(in, val);\n      return val;\n   }\n\n   /**\n    * @see org.jclouds.ssh.SshKeys\n    */\n   // http://www.ietf.org/rfc/rfc4253.txt\n   private static void writeLengthFirst(byte[] array, ByteArrayOutputStream out) throws IOException {\n      out.write(array.length >>> 24 & 0xFF);\n      out.write(array.length >>> 16 & 0xFF);\n      out.write(array.length >>> 8 & 0xFF);\n      out.write(array.length >>> 0 & 0xFF);\n      if (array.length == 1 && array[0] == (byte) 0x00) {\n         out.write(new byte[0]);\n      } else {\n         out.write(array);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/main/java/org/jclouds/digitalocean2/ssh/ECDSAKeys.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.ssh;\n\nimport static com.google.common.base.Joiner.on;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Splitter.fixedLength;\nimport static com.google.common.base.Throwables.propagate;\nimport static com.google.common.collect.Iterables.get;\nimport static com.google.common.collect.Iterables.size;\nimport static com.google.common.io.BaseEncoding.base16;\nimport static com.google.common.io.BaseEncoding.base64;\nimport static org.jclouds.util.Strings2.toStringAndClose;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.math.BigInteger;\nimport java.security.KeyFactory;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.interfaces.ECPublicKey;\nimport java.security.spec.ECFieldFp;\nimport java.security.spec.ECParameterSpec;\nimport java.security.spec.ECPoint;\nimport java.security.spec.ECPublicKeySpec;\nimport java.security.spec.EllipticCurve;\nimport java.security.spec.InvalidKeySpecException;\nimport java.util.Map;\nimport java.util.TreeMap;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.base.Splitter;\nimport com.google.common.hash.HashCode;\nimport com.google.common.hash.Hashing;\nimport com.google.common.io.ByteSource;\nimport com.google.common.io.ByteStreams;\n\n/**\n * Utility methods to work with ECDSA Elliptic Curve DSA keys.\n * <p>\n * Methods in this class should be moved to the {@link org.jclouds.ssh.SshKeys} class.\n * \n * @see org.jclouds.ssh.SshKeys\n */\npublic class ECDSAKeys {\n   public static final String ECDSA_SHA2_PREFIX = \"ecdsa-sha2-\";\n\n   private static final String NISTP256 = \"nistp256\";\n   private static final String NISTP384 = \"nistp384\";\n   private static final String NISTP521 = \"nistp521\";\n\n   private static final Map<String, ECParameterSpec> CURVES = new TreeMap<String, ECParameterSpec>();\n   static {\n      CURVES.put(NISTP256, EllipticCurves.nistp256);\n      CURVES.put(NISTP384, EllipticCurves.nistp384);\n      CURVES.put(NISTP521, EllipticCurves.nistp521);\n   }\n\n   private static final Map<Integer, String> CURVE_SIZES = new TreeMap<Integer, String>();\n   static {\n      CURVE_SIZES.put(256, NISTP256);\n      CURVE_SIZES.put(384, NISTP384);\n      CURVE_SIZES.put(521, NISTP521);\n   }\n\n   public static String encodeAsOpenSSH(ECPublicKey key) {\n\n      String curveName = null;\n      try {\n         curveName = getCurveName(key.getParams());\n      } catch (IOException e) {\n         propagate(e);\n      }\n\n      String keyFormat = ECDSA_SHA2_PREFIX + curveName;\n\n      byte[] keyBlob = keyBlob(key);\n      return keyFormat + \" \" + base64().encode(keyBlob);\n   }\n\n   /**\n    * Executes {@link org.jclouds.crypto.Pems#publicKeySpecFromOpenSSH(com.google.common.io.InputSupplier)} on the\n    * string which was OpenSSH Base64 Encoded {@code id_rsa.pub}\n    * \n    * @param idRsaPub formatted {@code ssh-dss AAAAB3NzaC1yc2EAAAADAQABAAAB...}\n    * @see org.jclouds.crypto.Pems#publicKeySpecFromOpenSSH(com.google.common.io.InputSupplier)\n    */\n   public static ECPublicKeySpec publicKeySpecFromOpenSSH(String ecDsaPub) {\n      try {\n         return publicKeySpecFromOpenSSH(ByteSource.wrap(ecDsaPub.getBytes(Charsets.UTF_8)));\n      } catch (IOException e) {\n         throw propagate(e);\n      }\n   }\n\n   /**\n    * Returns {@link java.security.spec.DSAPublicKeySpec} which was OpenSSH Base64 Encoded {@code id_rsa.pub}\n    *\n    * @param supplier the input stream factory, formatted {@code ssh-dss AAAAB3NzaC1yc2EAAAADAQABAAAB...}\n    *\n    * @return the {@link java.security.spec.DSAPublicKeySpec} which was OpenSSH Base64 Encoded {@code id_rsa.pub}\n    * @throws java.io.IOException if an I/O error occurs\n    */\n   public static ECPublicKeySpec publicKeySpecFromOpenSSH(ByteSource supplier) throws IOException {\n      InputStream stream = supplier.openStream();\n      Iterable<String> parts = Splitter.on(' ').split(toStringAndClose(stream).trim());\n      String signatureFormat = get(parts, 0);\n      checkArgument(size(parts) >= 2 && signatureFormat.startsWith(ECDSA_SHA2_PREFIX), \"bad format, should be: ecdsa-sha2-xxx AAAAB3...\");\n\n      String curveName = signatureFormat.substring(ECDSA_SHA2_PREFIX.length());\n      if (!CURVES.containsKey(curveName)) {\n         throw new IOException(\"Unsupported curve: \" + curveName);\n      }\n      ECParameterSpec spec = CURVES.get(curveName);\n      stream = new ByteArrayInputStream(base64().decode(get(parts, 1)));\n      readLengthFirst(stream);  // ignore return value\n      String curveMarker = new String(readLengthFirst(stream));\n      checkArgument(curveName.equals(curveMarker), \"looking for marker %s but got %s\", curveName, curveMarker);\n\n      ECPoint ecPoint = decodeECPoint(readLengthFirst(stream), spec.getCurve());\n\n      return new ECPublicKeySpec(ecPoint, spec);\n   }\n\n   /**\n    * @param publicKeyOpenSSH RSA public key in OpenSSH format\n    * @return fingerprint ex. {@code 2b:a9:62:95:5b:8b:1d:61:e0:92:f7:03:10:e9:db:d9}\n    */\n   public static String fingerprintPublicKey(String publicKeyOpenSSH) throws IOException {\n      ECPublicKeySpec publicKeySpec = publicKeySpecFromOpenSSH(publicKeyOpenSSH);\n      String fingerprint = null;\n      try {\n         ECPublicKey pk = (ECPublicKey) KeyFactory.getInstance(\"EC\").generatePublic(publicKeySpec);\n         fingerprint = fingerprint(pk);\n      } catch (InvalidKeySpecException e) {\n         e.printStackTrace();\n      } catch (NoSuchAlgorithmException e) {\n         e.printStackTrace();\n      }\n      return fingerprint;\n   }\n\n   /**\n    * Create a fingerprint per the following <a href=\"http://tools.ietf.org/html/draft-friedl-secsh-fingerprint-00\"\n    * >spec</a>\n    * \n    * @return hex fingerprint ex. {@code 2b:a9:62:95:5b:8b:1d:61:e0:92:f7:03:10:e9:db:d9}\n    */\n   public static String fingerprint(ECPublicKey publicKey) {\n      byte[] keyBlob = keyBlob(publicKey);\n      return hexColonDelimited(Hashing.md5().hashBytes(keyBlob));\n   }\n\n   /**\n    * @see org.jclouds.ssh.SshKeys\n    */\n   private static String hexColonDelimited(HashCode hc) {\n      return on(':').join(fixedLength(2).split(base16().lowerCase().encode(hc.asBytes())));\n   }\n\n   private static byte[] keyBlob(ECPublicKey key) {\n      try {\n         String curveName = getCurveName(key.getParams());\n         ByteArrayOutputStream out = new ByteArrayOutputStream();\n         writeLengthFirst((ECDSA_SHA2_PREFIX + curveName).getBytes(), out);\n         writeLengthFirst(curveName.getBytes(), out);\n         writeLengthFirst(encodeECPoint(key.getW(), key.getParams().getCurve()), out);\n         return out.toByteArray();\n      } catch (IOException e) {\n         throw propagate(e);\n      }\n   }\n\n   /**\n    * @see org.jclouds.ssh.SshKeys\n    */\n   // http://www.ietf.org/rfc/rfc4253.txt\n   private static byte[] readLengthFirst(InputStream in) throws IOException {\n      int byte1 = in.read();\n      int byte2 = in.read();\n      int byte3 = in.read();\n      int byte4 = in.read();\n      int length = (byte1 << 24) + (byte2 << 16) + (byte3 << 8) + (byte4 << 0);\n      byte[] val = new byte[length];\n      ByteStreams.readFully(in, val);\n      return val;\n   }\n\n   /**\n    * @see org.jclouds.ssh.SshKeys\n    */\n   // http://www.ietf.org/rfc/rfc4253.txt\n   private static void writeLengthFirst(byte[] array, ByteArrayOutputStream out) throws IOException {\n      out.write(array.length >>> 24 & 0xFF);\n      out.write(array.length >>> 16 & 0xFF);\n      out.write(array.length >>> 8 & 0xFF);\n      out.write(array.length >>> 0 & 0xFF);\n      if (array.length == 1 && array[0] == (byte) 0x00) {\n         out.write(new byte[0]);\n      } else {\n         out.write(array);\n      }\n   }\n\n   private static String getCurveName(ECParameterSpec params) throws IOException {\n      int fieldSize = getCurveSize(params);\n      String curveName = CURVE_SIZES.get(fieldSize);\n      if (curveName == null) {\n         throw new IOException(\"Unsupported curve field size: \" + fieldSize);\n      }\n      return curveName;\n   }\n\n   private static int getCurveSize(ECParameterSpec params) {\n      return params.getCurve().getField().getFieldSize();\n   }\n\n   /**\n    * Encode EllipticCurvePoint to an OctetString\n    */\n   public static byte[] encodeECPoint(ECPoint group, EllipticCurve curve)\n   {\n      // M has len 2 ceil(log_2(q)/8) + 1 ?\n      int elementSize = (curve.getField().getFieldSize() + 7) / 8;\n      byte[] M = new byte[2 * elementSize + 1];\n\n      // Uncompressed format\n      M[0] = 0x04;\n\n      {\n         byte[] affineX = removeLeadingZeroes(group.getAffineX().toByteArray());\n         System.arraycopy(affineX, 0, M, 1 + elementSize - affineX.length, affineX.length);\n      }\n\n      {\n         byte[] affineY = removeLeadingZeroes(group.getAffineY().toByteArray());\n         System.arraycopy(affineY, 0, M, 1 + elementSize + elementSize - affineY.length,\n               affineY.length);\n      }\n\n      return M;\n   }\n\n   private static byte[] removeLeadingZeroes(byte[] input) {\n      if (input[0] != 0x00) {\n         return input;\n      }\n\n      int pos = 1;\n      while (pos < input.length - 1 && input[pos] == 0x00) {\n         pos++;\n      }\n\n      byte[] output = new byte[input.length - pos];\n      System.arraycopy(input, pos, output, 0, output.length);\n      return output;\n   }\n\n   /**\n    * Decode an OctetString to EllipticCurvePoint according to SECG 2.3.4\n    */\n   public static ECPoint decodeECPoint(byte[] M, EllipticCurve curve) {\n      if (M.length == 0) {\n         return null;\n      }\n\n      // M has len 2 ceil(log_2(q)/8) + 1 ?\n      int elementSize = (curve.getField().getFieldSize() + 7) / 8;\n      if (M.length != 2 * elementSize + 1) {\n         return null;\n      }\n\n      // step 3.2\n      if (M[0] != 0x04) {\n         return null;\n      }\n\n      // Step 3.3\n      byte[] xp = new byte[elementSize];\n      System.arraycopy(M, 1, xp, 0, elementSize);\n\n      // Step 3.4\n      byte[] yp = new byte[elementSize];\n      System.arraycopy(M, 1 + elementSize, yp, 0, elementSize);\n\n      ECPoint P = new ECPoint(new BigInteger(1, xp), new BigInteger(1, yp));\n\n      // TODO check point 3.5\n\n      // Step 3.6\n      return P;\n   }\n\n   public static class EllipticCurves {\n      public static final ECParameterSpec nistp256 = new ECParameterSpec(\n            new EllipticCurve(\n                  new ECFieldFp(new BigInteger(\"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF\", 16)),\n                  new BigInteger(\"FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC\", 16),\n                  new BigInteger(\"5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b\", 16)),\n            new ECPoint(new BigInteger(\"6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296\", 16),\n                  new BigInteger(\"4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5\", 16)),\n            new BigInteger(\"FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551\", 16),\n            1);\n\n      public static final ECParameterSpec nistp384 = new ECParameterSpec(\n            new EllipticCurve(\n                  new ECFieldFp(new BigInteger(\"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFF\", 16)),\n                  new BigInteger(\"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFC\", 16),\n                  new BigInteger(\"B3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141120314088F5013875AC656398D8A2ED19D2A85C8EDD3EC2AEF\", 16)),\n            new ECPoint(new BigInteger(\"AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7\", 16),\n                  new BigInteger(\"3617DE4A96262C6F5D9E98BF9292DC29F8F41DBD289A147CE9DA3113B5F0B8C00A60B1CE1D7E819D7A431D7C90EA0E5F\", 16)),\n            new BigInteger(\"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973\", 16),\n            1);\n\n      public static final ECParameterSpec nistp521 = new ECParameterSpec(\n            new EllipticCurve(\n                  new ECFieldFp(new BigInteger(\"01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF\", 16)),\n                  new BigInteger(\"01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC\", 16),\n                  new BigInteger(\"0051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00\", 16)\n            ),\n            new ECPoint(new BigInteger(\"00C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66\", 16),\n                  new BigInteger(\"011839296A789A3BC0045C8A5FB42C7D1BD998F54449579B446817AFBD17273E662C97EE72995EF42640C550B9013FAD0761353C7086A272C24088BE94769FD16650\", 16)\n            ),\n            new BigInteger(\"01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409\", 16),\n            1);\n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/java/org/jclouds/digitalocean2/DigitalOcean2ProviderMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2;\n\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"DigitalOcean2ProviderMetadataTest\")\npublic class DigitalOcean2ProviderMetadataTest extends BaseProviderMetadataTest {\n\n   public DigitalOcean2ProviderMetadataTest() {\n      super(new DigitalOcean2ProviderMetadata(), new DigitalOcean2ApiMetadata());\n   }\n\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/java/org/jclouds/digitalocean2/compute/DigitalOcean2ComputeServiceLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.compute;\n\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.internal.BaseComputeServiceLiveTest;\nimport org.jclouds.digitalocean2.config.DigitalOcean2RateLimitModule;\nimport org.jclouds.sshj.config.SshjSshClientModule;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n/**\n * Live tests for the {@link org.jclouds.compute.ComputeService} integration.\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"DigitalOcean2ComputeServiceLiveTest\")\npublic class DigitalOcean2ComputeServiceLiveTest extends BaseComputeServiceLiveTest {\n\n   public DigitalOcean2ComputeServiceLiveTest() {\n      provider = \"digitalocean2\";\n   }\n\n   @Override\n   protected Module getSshModule() {\n      return new SshjSshClientModule();\n   }\n\n   @Override\n   protected Iterable<Module> setupModules() {\n      return ImmutableSet.<Module> builder().addAll(super.setupModules()).add(new DigitalOcean2RateLimitModule())\n            .build();\n   }\n\n   @Override\n   public void testOptionToNotBlock() throws Exception {\n      // DigitalOcean ComputeService implementation has to block until the node\n      // is provisioned, to be able to return it.\n   }\n\n   @Override\n   protected void checkTagsInNodeEquals(NodeMetadata node, ImmutableSet<String> tags) {\n      // We do not support tags yet.\n   }\n\n   @Override\n   protected void checkUserMetadataContains(NodeMetadata node, ImmutableMap<String, String> userMetadata) {\n      // The DigitalOcean API does not support user metadata.\n   }\n\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/java/org/jclouds/digitalocean2/compute/DigitalOcean2TemplateBuilderLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.compute;\n\nimport static org.jclouds.compute.util.ComputeServiceUtils.getCores;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.internal.BaseTemplateBuilderLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"live\", testName = \"DigitalOcean2TemplateBuilderLiveTest\")\npublic class DigitalOcean2TemplateBuilderLiveTest extends BaseTemplateBuilderLiveTest {\n\n   public DigitalOcean2TemplateBuilderLiveTest() {\n      provider = \"digitalocean2\";\n   }\n\n   @Test\n   @Override\n   public void testDefaultTemplateBuilder() throws IOException {\n      Template defaultTemplate = view.getComputeService().templateBuilder().build();\n      assert defaultTemplate.getImage().getOperatingSystem().getVersion().startsWith(\"16.\") : defaultTemplate\n            .getImage().getOperatingSystem().getVersion();\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true);\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.UBUNTU);\n      assertEquals(getCores(defaultTemplate.getHardware()), 1.0d);\n   }\n\n   @Override\n   protected Set<String> getIso3166Codes() {\n      return ImmutableSet.<String> of();\n   }\n\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/java/org/jclouds/digitalocean2/compute/config/ActionDonePredicateTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.compute.config;\n\nimport static org.easymock.EasyMock.anyInt;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.Assert.fail;\n\nimport java.util.Date;\n\nimport org.easymock.EasyMock;\nimport org.jclouds.digitalocean2.DigitalOcean2Api;\nimport org.jclouds.digitalocean2.compute.config.DigitalOcean2ComputeServiceContextModule.ActionDonePredicate;\nimport org.jclouds.digitalocean2.domain.Action;\nimport org.jclouds.digitalocean2.features.ActionApi;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ActionDonePredicateTest\")\npublic class ActionDonePredicateTest {\n\n   public void testActionStatusOk() {\n      ActionApi actionApi = EasyMock.createMock(ActionApi.class);\n      DigitalOcean2Api api = EasyMock.createMock(DigitalOcean2Api.class);\n\n      expect(actionApi.get(1)).andReturn(action(Action.Status.COMPLETED));\n      expect(actionApi.get(2)).andReturn(action(Action.Status.IN_PROGRESS));\n      expect(api.actionApi()).andReturn(actionApi).times(2);\n      replay(actionApi, api);\n\n      ActionDonePredicate predicate = new ActionDonePredicate(api);\n      assertTrue(predicate.apply(1L));\n      assertFalse(predicate.apply(2L));\n   }\n\n   public void testActionStatusError() {\n      ActionApi actionApi = EasyMock.createMock(ActionApi.class);\n      DigitalOcean2Api api = EasyMock.createMock(DigitalOcean2Api.class);\n\n      expect(actionApi.get(anyInt())).andReturn(action(Action.Status.ERRORED));\n      expect(api.actionApi()).andReturn(actionApi);\n      replay(actionApi, api);\n\n      ActionDonePredicate predicate = new ActionDonePredicate(api);\n\n      try {\n         predicate.apply(1L);\n         fail(\"Method should have thrown an IllegalStateException\");\n      } catch (IllegalStateException ex) {\n         assertEquals(ex.getMessage(), \"Resource is in invalid status: ERRORED\");\n      }\n   }\n\n   private static Action action(Action.Status status) {\n      return Action.create(1, status, \"foo\", new Date(), new Date(), 1, \"\", null, \"\");\n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/java/org/jclouds/digitalocean2/compute/config/DropletInStatusPredicateTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.compute.config;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Date;\n\nimport org.easymock.EasyMock;\nimport org.jclouds.digitalocean2.DigitalOcean2Api;\nimport org.jclouds.digitalocean2.compute.config.DigitalOcean2ComputeServiceContextModule.DropletInStatusPredicate;\nimport org.jclouds.digitalocean2.domain.Droplet;\nimport org.jclouds.digitalocean2.domain.Droplet.Status;\nimport org.jclouds.digitalocean2.features.DropletApi;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"DropletInStatusPredicateTest\")\npublic class DropletInStatusPredicateTest {\n\n   public void testDropletSuspended() {\n      DropletApi dropletApi = EasyMock.createMock(DropletApi.class);\n      DigitalOcean2Api api = EasyMock.createMock(DigitalOcean2Api.class);\n\n      expect(dropletApi.get(1)).andReturn(mockDroplet(Status.ACTIVE));\n      expect(dropletApi.get(2)).andReturn(mockDroplet(Status.OFF));\n      expect(api.dropletApi()).andReturn(dropletApi).times(2);\n      replay(dropletApi, api);\n\n      DropletInStatusPredicate predicate = new DropletInStatusPredicate(api, Status.OFF);\n      assertFalse(predicate.apply(1));\n      assertTrue(predicate.apply(2));\n   }\n\n   private static Droplet mockDroplet(Status status) {\n      return Droplet.create(1, \"foo\", 1024, 1, 20, false, new Date(), status,\n            ImmutableList.<Integer> of(), ImmutableList.<Integer> of(), ImmutableList.<String> of(), null, null, null,\n            \"\", null, null);\n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/java/org/jclouds/digitalocean2/compute/config/DropletTerminatedPredicateTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.compute.config;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Date;\n\nimport org.easymock.EasyMock;\nimport org.jclouds.digitalocean2.DigitalOcean2Api;\nimport org.jclouds.digitalocean2.compute.config.DigitalOcean2ComputeServiceContextModule.DropletTerminatedPredicate;\nimport org.jclouds.digitalocean2.domain.Droplet;\nimport org.jclouds.digitalocean2.features.DropletApi;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"DropletTerminatedPredicateTest\")\npublic class DropletTerminatedPredicateTest {\n\n   public void testDropletTerminated() {\n      DropletApi dropletApi = EasyMock.createMock(DropletApi.class);\n      DigitalOcean2Api api = EasyMock.createMock(DigitalOcean2Api.class);\n\n      expect(dropletApi.get(1)).andReturn(mockDroplet());\n      expect(dropletApi.get(2)).andReturn(null);\n      expect(api.dropletApi()).andReturn(dropletApi).times(2);\n      replay(dropletApi, api);\n\n      DropletTerminatedPredicate predicate = new DropletTerminatedPredicate(api);\n      assertFalse(predicate.apply(1));\n      assertTrue(predicate.apply(2));\n   }\n\n   private static Droplet mockDroplet() {\n      return Droplet.create(1, \"foo\", 1024, 1, 20, false, new Date(), Droplet.Status.ACTIVE,\n            ImmutableList.<Integer> of(), ImmutableList.<Integer> of(), ImmutableList.<String> of(), null, null, null,\n            \"\", null, null);\n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/java/org/jclouds/digitalocean2/compute/extensions/DigitalOcean2ImageExtensionLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.compute.extensions;\n\nimport org.jclouds.compute.extensions.internal.BaseImageExtensionLiveTest;\nimport org.jclouds.sshj.config.SshjSshClientModule;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Module;\n\n/**\n * Live tests for the {@link org.jclouds.compute.extensions.ImageExtension} integration.\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"DigitalOcean2ImageExtensionLiveTest\")\npublic class DigitalOcean2ImageExtensionLiveTest extends BaseImageExtensionLiveTest {\n\n   public DigitalOcean2ImageExtensionLiveTest() {\n      provider = \"digitalocean2\";\n   }\n\n   @Override\n   protected Module getSshModule() {\n      return new SshjSshClientModule();\n   }\n\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/java/org/jclouds/digitalocean2/compute/functions/DropletStatusToStatusTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.compute.functions;\n\nimport static org.jclouds.compute.domain.NodeMetadata.Status.UNRECOGNIZED;\nimport static org.testng.Assert.assertNotEquals;\n\nimport org.jclouds.digitalocean2.domain.Droplet.Status;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"DropletStatusToStatusTest\")\npublic class DropletStatusToStatusTest {\n\n   @Test\n   public void testAllStatesHaveMapping() {\n      DropletStatusToStatus function = new DropletStatusToStatus();\n      for (Status status : Status.values()) {\n         assertNotEquals(function.apply(status), UNRECOGNIZED);\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/java/org/jclouds/digitalocean2/compute/functions/DropletToNodeMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.compute.functions;\n\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static org.jclouds.compute.domain.Image.Status.AVAILABLE;\nimport static org.jclouds.compute.domain.NodeMetadata.Status.RUNNING;\nimport static org.jclouds.digitalocean2.domain.Droplet.Status.ACTIVE;\nimport static org.testng.Assert.assertEquals;\n\nimport java.text.ParseException;\nimport java.util.Date;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.HardwareBuilder;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.ImageBuilder;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadataBuilder;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.Processor;\nimport org.jclouds.compute.domain.Volume.Type;\nimport org.jclouds.compute.domain.VolumeBuilder;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.digitalocean2.domain.Droplet;\nimport org.jclouds.digitalocean2.domain.Networks;\nimport org.jclouds.digitalocean2.domain.Networks.Address;\nimport org.jclouds.digitalocean2.domain.Region;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.domain.LoginCredentials;\nimport org.testng.annotations.BeforeMethod;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Maps;\nimport com.google.inject.Guice;\n\n@Test(groups = \"unit\", testName = \"DropletToNodeMetadataTest\")\npublic class DropletToNodeMetadataTest {\n\n   private org.jclouds.digitalocean2.domain.Image image;\n   \n   private Region region;\n   \n   private Set<Hardware> hardwares;\n\n   private Set<Image> images;\n\n   private Set<Location> locations;\n\n   private LoginCredentials credentials;\n\n   private DropletToNodeMetadata function;\n\n   @BeforeMethod\n   public void setup() {\n      image = org.jclouds.digitalocean2.domain.Image.create(1, \"14.04 x64\",\n            \"distribution\", \"Ubuntu\", \"ubuntu-1404-x86\", true, ImmutableList.of(\"sfo1\"), new Date(), 20, 20);\n      region = Region.create(\"sfo1\", \"San Francisco 1\", ImmutableList.of(\"2gb\"), true, ImmutableList.<String> of());\n      \n      images = ImmutableSet.of(new ImageBuilder()\n            .id(\"sfo1/ubuntu-1404-x86\")\n            .providerId(\"1\")\n            .name(\"mock image\")\n            .status(AVAILABLE)\n            .operatingSystem(\n                  OperatingSystem.builder().name(\"Ubuntu 14.04 x86_64\").description(\"Ubuntu\").family(OsFamily.UBUNTU)\n                        .version(\"10.04\").arch(\"x86_64\").is64Bit(true).build()).build());\n\n      hardwares = ImmutableSet.of(new HardwareBuilder().id(\"2gb\").providerId(\"2gb\").name(\"mock hardware\")\n            .processor(new Processor(1.0, 1.0)).ram(2048)\n            .volume(new VolumeBuilder().size(20f).type(Type.LOCAL).build()).build());\n\n      locations = ImmutableSet.of(new LocationBuilder()\n            .id(\"sfo1\")\n            .description(\"sfo1/San Francisco 1\")\n            .scope(LocationScope.REGION)\n            .parent(\n                  new LocationBuilder().id(\"0\").description(\"mock parent location\").scope(LocationScope.PROVIDER)\n                        .build()).build());\n\n      credentials = LoginCredentials.builder().user(\"foo\").password(\"bar\").build();\n\n      function = createNodeParser(hardwares, images, locations, ImmutableMap.of(\"node#1\", (Credentials) credentials));\n   }\n\n   @Test\n   public void testConvertDroplet() throws ParseException {\n      Droplet droplet = Droplet.create(\n            1,\n            \"mock-droplet\",\n            1,\n            1,\n            1,\n            false,\n            new Date(),\n            Droplet.Status.ACTIVE,\n            ImmutableList.<Integer> of(),\n            ImmutableList.<Integer> of(),\n            ImmutableList.<String> of(),\n            region,\n            image,\n            null,\n            \"2gb\",\n            Networks.create(\n                  ImmutableList.of(Address.create(\"84.45.69.3\", \"255.255.255.0\", \"84.45.69.1\", \"public\"),\n                        Address.create(\"192.168.2.5\", \"255.255.255.0\", \"192.168.2.1\", \"private\")),\n                  ImmutableList.<Networks.Address> of()), null);\n\n      NodeMetadata expected = new NodeMetadataBuilder().ids(\"1\").hardware(getOnlyElement(hardwares))\n            .imageId(\"sfo1/ubuntu-1404-x86\").status(RUNNING).location(getOnlyElement(locations)).name(\"mock-droplet\")\n            .hostname(\"mock-droplet\").group(\"mock\").credentials(credentials)\n            .publicAddresses(ImmutableSet.of(\"84.45.69.3\")).privateAddresses(ImmutableSet.of(\"192.168.2.5\"))\n            .providerId(\"1\").backendStatus(ACTIVE.name()).operatingSystem(getOnlyElement(images).getOperatingSystem())\n            .build();\n\n      NodeMetadata actual = function.apply(droplet);\n      assertNodeEquals(actual, expected);\n   }\n\n   @Test\n   public void testConvertDropletOldImage() throws ParseException {\n      // Use an image id that is not in the list of images\n      org.jclouds.digitalocean2.domain.Image image = org.jclouds.digitalocean2.domain.Image.create(2, \"14.04 x64\",\n            \"distribution\", \"Ubuntu\", \"ubuntu2-1404-x86\", true, ImmutableList.of(\"sfo1\"), new Date(), 20, 20);\n      \n      Droplet droplet = Droplet.create(\n            1,\n            \"mock-droplet\",\n            1,\n            1,\n            1,\n            false,\n            new Date(),\n            Droplet.Status.ACTIVE,\n            ImmutableList.<Integer> of(),\n            ImmutableList.<Integer> of(),\n            ImmutableList.<String> of(),\n            region,\n            image,\n            null,\n            \"2gb\",\n            Networks.create(\n                  ImmutableList.of(Address.create(\"84.45.69.3\", \"255.255.255.0\", \"84.45.69.1\", \"public\"),\n                        Address.create(\"192.168.2.5\", \"255.255.255.0\", \"192.168.2.1\", \"private\")),\n                  ImmutableList.<Networks.Address> of()), null);\n\n      NodeMetadata expected = new NodeMetadataBuilder().ids(\"1\").hardware(getOnlyElement(hardwares)).imageId(null)\n            .status(RUNNING).location(getOnlyElement(locations)).name(\"mock-droplet\").hostname(\"mock-droplet\")\n            .group(\"mock\").credentials(credentials).publicAddresses(ImmutableSet.of(\"84.45.69.3\"))\n            .privateAddresses(ImmutableSet.of(\"192.168.2.5\")).providerId(\"1\").backendStatus(ACTIVE.name())\n            .operatingSystem(null).build();\n\n      NodeMetadata actual = function.apply(droplet);\n      assertNodeEquals(actual, expected);\n   }\n\n   private static void assertNodeEquals(NodeMetadata actual, NodeMetadata expected) {\n      assertEquals(actual, expected);\n      // NodeMetadata equals method does not use all fields in equals. It assumes that same ids in same locations\n      // determine the equivalence\n      assertEquals(actual.getStatus(), expected.getStatus());\n      assertEquals(actual.getBackendStatus(), expected.getBackendStatus());\n      assertEquals(actual.getLoginPort(), expected.getLoginPort());\n      assertEquals(actual.getPublicAddresses(), expected.getPublicAddresses());\n      assertEquals(actual.getPrivateAddresses(), expected.getPrivateAddresses());\n      assertEquals(actual.getCredentials(), expected.getCredentials());\n      assertEquals(actual.getGroup(), expected.getGroup());\n      assertEquals(actual.getImageId(), expected.getImageId());\n      assertEquals(actual.getHardware(), expected.getHardware());\n      assertEquals(actual.getOperatingSystem(), expected.getOperatingSystem());\n      assertEquals(actual.getHostname(), expected.getHostname());\n   }\n\n   private DropletToNodeMetadata createNodeParser(final Set<Hardware> hardware, final Set<Image> images,\n         final Set<Location> locations, Map<String, Credentials> credentialStore) {\n      Supplier<Set<? extends Location>> locationSupplier = new Supplier<Set<? extends Location>>() {\n         @Override\n         public Set<? extends Location> get() {\n            return locations;\n         }\n      };\n\n      Supplier<Map<String, ? extends Hardware>> hardwareSupplier = new Supplier<Map<String, ? extends Hardware>>() {\n         @Override\n         public Map<String, ? extends Hardware> get() {\n            return Maps.uniqueIndex(hardware, new Function<Hardware, String>() {\n               @Override\n               public String apply(Hardware input) {\n                  return input.getId();\n               }\n            });\n         }\n      };\n\n      Supplier<Map<String, ? extends Image>> imageSupplier = new Supplier<Map<String, ? extends Image>>() {\n         @Override\n         public Map<String, ? extends Image> get() {\n            return Maps.uniqueIndex(images, new Function<Image, String>() {\n               @Override\n               public String apply(Image input) {\n                  return input.getId();\n               }\n            });\n         }\n      };\n\n      GroupNamingConvention.Factory namingConvention = Guice.createInjector().getInstance(GroupNamingConvention.Factory.class);\n\n      return new DropletToNodeMetadata(imageSupplier, hardwareSupplier, locationSupplier, new DropletStatusToStatus(),\n            namingConvention, credentialStore);\n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/java/org/jclouds/digitalocean2/compute/functions/ImageInRegionToImageTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.compute.functions;\n\nimport static org.jclouds.compute.domain.Image.Status.AVAILABLE;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Date;\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.ImageBuilder;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.digitalocean2.compute.internal.ImageInRegion;\nimport org.jclouds.digitalocean2.domain.Image;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.testng.annotations.BeforeMethod;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\n\n@Test(groups = \"unit\", testName = \"ImageToImageTest\")\npublic class ImageInRegionToImageTest {\n\n   private Set<Location> locations;\n\n   private ImageInRegionToImage function;\n\n   @BeforeMethod\n   public void setup() {\n      locations = ImmutableSet.of(\n            new LocationBuilder()\n                  .id(\"sfo1\")\n                  .description(\"sfo1/San Francisco 1\")\n                  .scope(LocationScope.REGION)\n                  .parent(\n                        new LocationBuilder().id(\"0\").description(\"mock parent location\").scope(LocationScope.PROVIDER)\n                              .build()).build(),\n            new LocationBuilder()\n                  .id(\"lon1\")\n                  .description(\"lon1/London 1\")\n                  .scope(LocationScope.REGION)\n                  .parent(\n                        new LocationBuilder().id(\"0\").description(\"mock parent location\").scope(LocationScope.PROVIDER)\n                              .build()).build());\n\n      function = new ImageInRegionToImage(new Supplier<Set<? extends Location>>() {\n         @Override\n         public Set<? extends Location> get() {\n            return locations;\n         }\n      });\n   }\n\n   @Test\n   public void testConvertImage() {\n      Image image = Image.create(1, \"14.04 x64\", \"distribution\", \"Ubuntu\", \"ubuntu-1404-x86\", true,\n            ImmutableList.of(\"sfo1\", \"lon1\"), new Date(), 20, 20);\n      org.jclouds.compute.domain.Image expected = new ImageBuilder()\n            .id(\"lon1/ubuntu-1404-x86\") // Location scoped images have the location encoded in the id\n            .providerId(\"1\")\n            .name(\"14.04 x64\")\n            .description(\"Ubuntu 14.04 x64\")\n            .status(AVAILABLE)\n            .operatingSystem(\n                  OperatingSystem.builder().name(\"Ubuntu\").description(\"Ubuntu 14.04 x64\").family(OsFamily.UBUNTU)\n                        .version(\"14.04\").arch(\"x64\").is64Bit(true).build())\n            .location(Iterables.get(locations, 1))\n            .userMetadata(ImmutableMap.of(\"publicImage\", \"true\")).build();\n\n      org.jclouds.compute.domain.Image result = function.apply(ImageInRegion.create(image, \"lon1\"));\n      assertEquals(result, expected);\n      assertEquals(result.getDescription(), expected.getDescription());\n      assertEquals(result.getOperatingSystem(), expected.getOperatingSystem());\n      assertEquals(result.getStatus(), expected.getStatus());\n      assertEquals(result.getLocation(), Iterables.get(locations, 1));\n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/java/org/jclouds/digitalocean2/compute/functions/RegionToLocationTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.compute.functions;\n\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\n\nimport org.jclouds.digitalocean2.DigitalOcean2ProviderMetadata;\nimport org.jclouds.digitalocean2.domain.Region;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.location.suppliers.all.JustProvider;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\", testName = \"RegionToLocationTest\")\npublic class RegionToLocationTest {\n\n   @Test\n   public void testConvertRegion() {\n      DigitalOcean2ProviderMetadata metadata = new DigitalOcean2ProviderMetadata();\n      JustProvider locationsSupplier = new JustProvider(metadata.getId(), Suppliers.<URI> ofInstance(URI\n            .create(metadata.getEndpoint())), ImmutableSet.<String> of());\n\n      Region region = Region.create(\"reg1\", \"Region1\", ImmutableList.<String> of(), true,\n            ImmutableList.<String> of(\"virtio\", \"metadata\"));\n      Location expected = new LocationBuilder().id(\"reg1\").description(\"reg1/Region 1\")\n            .parent(getOnlyElement(locationsSupplier.get())).scope(LocationScope.REGION).build();\n\n      Location location = new RegionToLocation(locationsSupplier).apply(region);\n\n      assertEquals(location, expected);\n      assertEquals(location.getMetadata().get(\"available\"), true);\n      assertEquals(location.getMetadata().get(\"features\"), ImmutableList.of(\"virtio\", \"metadata\"));\n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/java/org/jclouds/digitalocean2/compute/functions/SizeToHardwareTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.compute.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.HardwareBuilder;\nimport org.jclouds.compute.domain.Processor;\nimport org.jclouds.compute.domain.Volume.Type;\nimport org.jclouds.compute.domain.VolumeBuilder;\nimport org.jclouds.digitalocean2.domain.Size;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Unit tests for the {@link SizeToHardware} class.\n */\n@Test(groups = \"unit\", testName = \"SizeToHardwareTest\")\npublic class SizeToHardwareTest {\n\n   @Test\n   public void testConvertSize() {\n      Size size = Size.create(\"2gb\", true, 1.0f, 10f, 0.05f, 2048, 1, 20, ImmutableList.<String> of());\n      Hardware expected = new HardwareBuilder().id(\"2gb\").providerId(\"2gb\").name(\"2gb\")\n            .processor(new Processor(1.0, 1.0)).ram(2048)\n            .volume(new VolumeBuilder().size(20f).type(Type.LOCAL).build())\n            .userMetadata(ImmutableMap.of(\"costPerHour\", \"0.05\", \"costPerMonth\", \"10\")).build();\n\n      SizeToHardware function = new SizeToHardware();\n      assertEquals(function.apply(size), expected);\n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/java/org/jclouds/digitalocean2/compute/options/DigitalOcean2TemplateOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.compute.options;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\", testName = \"DigitalOcean2TemplateOptionsTest\")\npublic class DigitalOcean2TemplateOptionsTest {\n\n   @Test\n   public void testSShKeyIds() {\n      TemplateOptions options = new DigitalOcean2TemplateOptions().sshKeyIds(ImmutableSet.of(1, 2, 3));\n      assertEquals(options.as(DigitalOcean2TemplateOptions.class).getSshKeyIds(), ImmutableSet.of(1, 2, 3));\n   }\n\n   @Test\n   public void testPrivateNetworking() {\n      TemplateOptions options = new DigitalOcean2TemplateOptions().privateNetworking(true);\n      assertEquals(options.as(DigitalOcean2TemplateOptions.class).getPrivateNetworking(), true);\n   }\n\n   @Test\n   public void testBackupsEnabled() {\n      TemplateOptions options = new DigitalOcean2TemplateOptions().backupsEnabled(true);\n      assertEquals(options.as(DigitalOcean2TemplateOptions.class).getBackupsEnabled(), true);\n   }\n\n   @Test\n   public void testAutoCreateKeyPair() {\n      TemplateOptions options = new DigitalOcean2TemplateOptions().autoCreateKeyPair(false);\n      assertEquals(options.as(DigitalOcean2TemplateOptions.class).getAutoCreateKeyPair(), false);\n   }\n\n   @Test\n   public void testUserData() {\n      byte[] userData = \"Lorem ipsum\".getBytes();\n      TemplateOptions options = new DigitalOcean2TemplateOptions().userData(userData);\n      assertEquals(options.as(DigitalOcean2TemplateOptions.class).getUserData(), userData);\n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/java/org/jclouds/digitalocean2/domain/OperatingSystemTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.domain;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"OperatingSystemTest\")\npublic class OperatingSystemTest {\n\n   public void testParseStandard64bit() {\n      OperatingSystem os = OperatingSystem.create(\"12.10 x64\", \"Ubuntu\");\n\n      assertEquals(os.distribution(), Distribution.UBUNTU);\n      assertEquals(os.version(), \"12.10\");\n      assertEquals(os.arch(), \"x64\");\n      assertTrue(os.is64bit());\n   }\n\n   public void testLongVersionStandard64bit() {\n      OperatingSystem os = OperatingSystem.create(\"12.10.1 x64\", \"Ubuntu\");\n\n      assertEquals(os.distribution(), Distribution.UBUNTU);\n      assertEquals(os.version(), \"12.10.1\");\n      assertEquals(os.arch(), \"x64\");\n      assertTrue(os.is64bit());\n   }\n\n   public void testParseStandard64bitWithPrefix() {\n      OperatingSystem os = OperatingSystem.create(\"Arch Linux 12.10 x64 Desktop\", \"Arch Linux\");\n\n      assertEquals(os.distribution(), Distribution.ARCHLINUX);\n      assertEquals(os.version(), \"12.10\");\n      assertEquals(os.arch(), \"x64\");\n      assertTrue(os.is64bit());\n   }\n\n   public void testParseStandard() {\n      OperatingSystem os = OperatingSystem.create(\"12.10 x32\", \"Ubuntu\");\n\n      assertEquals(os.distribution(), Distribution.UBUNTU);\n      assertEquals(os.version(), \"12.10\");\n      assertEquals(os.arch(), \"x32\");\n      assertFalse(os.is64bit());\n\n      os = OperatingSystem.create(\"6.5 x64\", \"CentOS\");\n\n      assertEquals(os.distribution(), Distribution.CENTOS);\n      assertEquals(os.version(), \"6.5\");\n      assertEquals(os.arch(), \"x64\");\n      assertTrue(os.is64bit());\n\n      os = OperatingSystem.create(\"6.5 x64\", \"Centos\");\n\n      assertEquals(os.distribution(), Distribution.CENTOS);\n      assertEquals(os.version(), \"6.5\");\n      assertEquals(os.arch(), \"x64\");\n      assertTrue(os.is64bit());\n   }\n\n   public void testParseNoArch() {\n      OperatingSystem os = OperatingSystem.create(\"12.10\", \"Ubuntu\");\n\n      assertEquals(os.distribution(), Distribution.UBUNTU);\n      assertEquals(os.version(), \"12.10\");\n      assertEquals(os.arch(), \"\");\n      assertFalse(os.is64bit());\n   }\n\n   public void testParseNoVersion() {\n      OperatingSystem os = OperatingSystem.create(\"x64\", \"Ubuntu\");\n\n      assertEquals(os.distribution(), Distribution.UBUNTU);\n      assertEquals(os.version(), \"\");\n      assertEquals(os.arch(), \"x64\");\n      assertTrue(os.is64bit());\n   }\n\n   public void testParseUnknownDistribution() {\n      OperatingSystem os = OperatingSystem.create(\"12.04 x64\", \"Foo\");\n\n      assertEquals(os.distribution(), Distribution.UNRECOGNIZED);\n      assertEquals(os.version(), \"12.04\");\n      assertEquals(os.arch(), \"x64\");\n      assertTrue(os.is64bit());\n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/java/org/jclouds/digitalocean2/exceptions/RateLimitExceptionMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.exceptions;\n\nimport static org.jclouds.Constants.PROPERTY_MAX_RETRIES;\nimport static org.jclouds.digitalocean2.handlers.DigitalOcean2RateLimitRetryHandler.millisUntilNextAvailableRequest;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.Assert.fail;\n\nimport java.util.Properties;\n\nimport okhttp3.mockwebserver.MockResponse;\n\nimport org.jclouds.digitalocean2.internal.BaseDigitalOcean2ApiMockTest;\nimport org.testng.annotations.Test;\n\n\n@Test(groups = \"unit\", testName = \"RateLimitExceptionMockTest\", singleThreaded = true)\npublic class RateLimitExceptionMockTest extends BaseDigitalOcean2ApiMockTest {\n\n   @Override\n   protected Properties overrides() {\n      Properties overrides = super.overrides();\n      overrides.put(PROPERTY_MAX_RETRIES, \"0\"); // Do not retry\n      return overrides;\n   }\n\n   public void testRateLimitExceptionIsThrown() throws InterruptedException {\n      long reset = (System.currentTimeMillis() / 1000) + 3600; // Epoch for one\n                                                               // hour from now\n      long millisToReset = millisUntilNextAvailableRequest(reset);\n\n      server.enqueue(new MockResponse().setResponseCode(429).addHeader(\"RateLimit-Limit\", \"5000\")\n            .addHeader(\"RateLimit-Remaining\", \"1235\").addHeader(\"RateLimit-Reset\", String.valueOf(reset)));\n\n      try {\n         api.keyApi().list();\n         fail(\"Expected a DigitalOcean2RateLimitExceededException to be thrown\");\n      } catch (DigitalOcean2RateLimitExceededException ex) {\n         assertEquals(ex.totalRequestsPerHour().intValue(), 5000);\n         assertEquals(ex.remainingRequests().intValue(), 1235);\n         // Can't verify with millisecond precision. Use an interval to have a\n         // consistent test.\n         assertTrue(ex.timeToNextAvailableRequest() < millisToReset\n               && ex.timeToNextAvailableRequest() > millisToReset - 1800000);\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/java/org/jclouds/digitalocean2/features/ActionApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.features;\n\nimport static org.jclouds.digitalocean2.domain.options.ImageListOptions.Builder.page;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.util.Strings.isNullOrEmpty;\n\nimport java.util.concurrent.atomic.AtomicInteger;\n\nimport org.jclouds.digitalocean2.domain.Action;\nimport org.jclouds.digitalocean2.internal.BaseDigitalOcean2ApiLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\n\n@Test(groups = \"live\", testName = \"ActionApiLiveTest\")\npublic class ActionApiLiveTest extends BaseDigitalOcean2ApiLiveTest {\n\n   public void testListActions() {\n      final AtomicInteger found = new AtomicInteger(0);\n      // DigitalOcean return 25 records per page by default. Inspect at most 2 pages\n      assertTrue(api().list().concat().limit(50).allMatch(new Predicate<Action>() {\n         @Override\n         public boolean apply(Action input) {\n            found.incrementAndGet();\n            return !isNullOrEmpty(input.type());\n         }\n      }), \"All actions must have the 'type' field populated\");\n      assertTrue(found.get() > 0, \"Expected some actions to be returned\");\n   }\n   \n   public void testListActionsOnePage() {\n      final AtomicInteger found = new AtomicInteger(0);\n      assertTrue(api().list(page(1).perPage(5)).allMatch(new Predicate<Action>() {\n         @Override\n         public boolean apply(Action input) {\n            found.incrementAndGet();\n            return !isNullOrEmpty(input.type());\n         }\n      }), \"All actions must have the 'type' field populated\");\n      assertTrue(found.get() > 0, \"Expected some actions to be returned\");\n   }\n   \n   public void testGetAction() {\n      Optional<Action> first = api().list().concat().first();\n      assertTrue(first.isPresent(), \"At least one action was expected to exist\");\n      assertNotNull(api().get(first.get().id()));\n   }\n   \n   private ActionApi api() {\n      return api.actionApi();\n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/java/org/jclouds/digitalocean2/features/ActionApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.features;\n\nimport static com.google.common.collect.Iterables.isEmpty;\nimport static com.google.common.collect.Iterables.size;\nimport static org.jclouds.digitalocean2.domain.options.ListOptions.Builder.page;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Map;\n\nimport org.jclouds.digitalocean2.domain.Action;\nimport org.jclouds.digitalocean2.internal.BaseDigitalOcean2ApiMockTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.reflect.TypeToken;\n\n@Test(groups = \"unit\", testName = \"ActionApiMockTest\", singleThreaded = true)\npublic class ActionApiMockTest extends BaseDigitalOcean2ApiMockTest {\n\n   public void testListActions() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/actions-first.json\"));\n      server.enqueue(jsonResponse(\"/actions-last.json\"));\n\n      Iterable<Action> actions = api.actionApi().list().concat();\n\n      assertEquals(size(actions), 8); // Force the PagedIterable to advance\n      assertEquals(server.getRequestCount(), 2);\n\n      assertSent(server, \"GET\", \"/actions\");\n      assertSent(server, \"GET\", \"/actions?page=2&per_page=5\");\n   }\n\n   public void testListActionsReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      Iterable<Action> actions = api.actionApi().list().concat();\n\n      assertTrue(isEmpty(actions));\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/actions\");\n   }\n\n   public void testListActionsWithOptions() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/actions-first.json\"));\n\n      Iterable<Action> actions = api.actionApi().list(page(1).perPage(5));\n\n      assertEquals(size(actions), 5);\n      assertEquals(server.getRequestCount(), 1);\n\n      assertSent(server, \"GET\", \"/actions?page=1&per_page=5\");\n   }\n\n   public void testListActionsWithOptionsReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      Iterable<Action> actions = api.actionApi().list(page(1).perPage(5));\n\n      assertTrue(isEmpty(actions));\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/actions?page=1&per_page=5\");\n   }\n   \n   public void testGetAction() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/action.json\"));\n\n      Action action = api.actionApi().get(1);\n\n      assertEquals(action, actionFromResource(\"/action.json\"));\n      \n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/actions/1\");\n   }\n\n   public void testGetActionReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      Action action = api.actionApi().get(1);\n\n      assertNull(action);\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/actions/1\");\n   }\n   \n   private Action actionFromResource(String resource) {\n      return onlyObjectFromResource(resource, new TypeToken<Map<String, Action>>() {\n         private static final long serialVersionUID = 1L;\n      }); \n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/java/org/jclouds/digitalocean2/features/DropletApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.features;\n\nimport static java.util.logging.Logger.getAnonymousLogger;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.digitalocean2.domain.Action;\nimport org.jclouds.digitalocean2.domain.Backup;\nimport org.jclouds.digitalocean2.domain.Droplet;\nimport org.jclouds.digitalocean2.domain.DropletCreate;\nimport org.jclouds.digitalocean2.domain.Image;\nimport org.jclouds.digitalocean2.domain.Kernel;\nimport org.jclouds.digitalocean2.domain.Key;\nimport org.jclouds.digitalocean2.domain.Region;\nimport org.jclouds.digitalocean2.domain.Size;\nimport org.jclouds.digitalocean2.domain.Snapshot;\nimport org.jclouds.digitalocean2.domain.options.CreateDropletOptions;\nimport org.jclouds.digitalocean2.internal.BaseDigitalOcean2ApiLiveTest;\nimport org.jclouds.ssh.SshKeys;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.FluentIterable;\n\n@Test(groups = \"live\", testName = \"DropletApiLiveTest\")\npublic class DropletApiLiveTest extends BaseDigitalOcean2ApiLiveTest {\n\n   private Region region;\n   private Size size;\n   private Image image;\n   private Key key;\n   private int dropletId = -1;\n   \n   @BeforeClass\n   public void setupDroplet() {\n      region = firstAvailableRegion();\n      image = ubuntuImageInRegion(region);\n      size = cheapestSizeInRegionForImage(region, image);\n      \n      Map<String, String> keyPair = SshKeys.generate();\n      key = api.keyApi().create(prefix + \"-droplet-livetest\", keyPair.get(\"public\"));\n   }\n   \n   @AfterClass(alwaysRun = true)\n   public void tearDown() {\n      if (key != null) {\n         api.keyApi().delete(key.id());\n      }\n   }\n   \n   public void testCreate() {\n      DropletCreate dropletCreate = api().create(prefix + \"-droplet-livetest\", region.slug(), size.slug(), image.slug(),\n            CreateDropletOptions.builder().backupsEnabled(true).addSshKeyId(key.id()).build());\n      dropletId = dropletCreate.droplet().id();\n      assertNodeRunning(dropletId);\n      Droplet droplet = api().get(dropletId);\n      assertNotNull(droplet, \"Droplet should not be null\");\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testCreate\")\n   public void testListDroplets() {\n      assertTrue(api().list().concat().anyMatch(new Predicate<Droplet>() {\n         @Override\n         public boolean apply(Droplet input) {\n            return input.id() == dropletId;\n         }\n      }), \"The created droplet must be in the list\");\n   }\n\n   @Test(dependsOnMethods = \"testCreate\")\n   public void testListKernels() {\n      Iterable<Kernel> kernels = api().listKernels(dropletId).concat();\n      assertTrue(kernels.iterator().hasNext());\n   }\n   \n   @Test(dependsOnMethods = \"testListKernels\")\n   public void testPowerOff() {\n      api().powerOff(dropletId);\n      assertNodeStopped(dropletId);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testPowerOff\")\n   public void testPowerOn() {\n      api().powerOn(dropletId);\n      assertNodeRunning(dropletId);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testPowerOn\")\n   public void testSnapshots() {\n      Action action = api().snapshot(dropletId, prefix + dropletId + \"-snapshot\");\n      assertActionCompleted(action.id());\n      \n      List<Snapshot> snapshots = api().listSnapshots(dropletId).concat().toList();\n      assertEquals(snapshots.size(), 1, \"Must contain 1 snapshot\");\n      \n      for (Snapshot snapshot : snapshots) {\n         try {\n            api.imageApi().delete(snapshot.id());\n         } catch (Exception ex) {\n            getAnonymousLogger().warning(\"Could not delete snapshot: \" + snapshot.id());\n         }\n      }\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testSnapshots\")\n   public void testBackups() {\n      Iterable<Backup> backups = api().listBackups(dropletId).concat();\n      // Backups are automatically taken by DO on a weekly basis, so we can't guarantee\n      // there will be any backup available. Just check that the call succeeds\n      assertNotNull(backups);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testSnapshots\")\n   public void testListActions() {\n      FluentIterable<Action> actions = api().listActions(dropletId).concat();\n      assertTrue(actions.anyMatch(new Predicate<Action>() {\n         @Override\n         public boolean apply(Action input) {\n            return \"snapshot\".equals(input.type());\n         }\n      }));\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testSnapshots\")\n   public void testReboot() {\n      Action action = api().reboot(dropletId);\n      assertActionCompleted(action.id());\n      assertNodeRunning(dropletId);\n   }\n   \n   @Test(groups = \"live\", dependsOnMethods = \"testReboot\")\n   public void testPowerCycle() {\n      Action action = api().powerCycle(dropletId);\n      assertActionCompleted(action.id());\n      assertNodeRunning(dropletId);\n   }\n   \n   @Test(groups = \"live\", dependsOnMethods = \"testPowerCycle\")\n   public void testShutdown() {\n      Action action = api().shutdown(dropletId);\n      assertActionCompleted(action.id());\n      // The shutdown action can fail if the shutdown command fails in the guest OS\n      // We can not guarantee that a graceful shutdown action will en up in the droplet\n      // being in OFF state\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testShutdown\", alwaysRun = true)\n   public void testDelete() throws InterruptedException {\n      if (dropletId != -1) {\n         api().delete(dropletId);\n         assertNodeTerminated(dropletId);\n         assertNull(api().get(dropletId));\n      }\n   }\n   \n   private DropletApi api() {\n      return api.dropletApi();\n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/java/org/jclouds/digitalocean2/features/DropletApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.features;\n\nimport static com.google.common.collect.Iterables.isEmpty;\nimport static com.google.common.collect.Iterables.size;\nimport static org.jclouds.digitalocean2.domain.options.ListOptions.Builder.page;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Map;\n\nimport org.jclouds.digitalocean2.domain.Action;\nimport org.jclouds.digitalocean2.domain.Backup;\nimport org.jclouds.digitalocean2.domain.Droplet;\nimport org.jclouds.digitalocean2.domain.DropletCreate;\nimport org.jclouds.digitalocean2.domain.Kernel;\nimport org.jclouds.digitalocean2.domain.Snapshot;\nimport org.jclouds.digitalocean2.domain.options.CreateDropletOptions;\nimport org.jclouds.digitalocean2.internal.BaseDigitalOcean2ApiMockTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.reflect.TypeToken;\n\n@Test(groups = \"unit\", testName = \"DropletApiMockTest\", singleThreaded = true)\npublic class DropletApiMockTest extends BaseDigitalOcean2ApiMockTest {\n\n   public void testListDroplets() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/droplets-first.json\"));\n      server.enqueue(jsonResponse(\"/droplets-last.json\"));\n\n      Iterable<Droplet> droplets = api.dropletApi().list().concat();\n\n      assertEquals(size(droplets), 2); // Force the PagedIterable to advance\n      assertEquals(server.getRequestCount(), 2);\n\n      assertSent(server, \"GET\", \"/droplets\");\n      assertSent(server, \"GET\", \"/droplets?page=2&per_page=1\");\n   }\n\n   public void testListDropletsReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      Iterable<Droplet> droplets = api.dropletApi().list().concat();\n\n      assertTrue(isEmpty(droplets));\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/droplets\");\n   }\n\n   public void testListDropletsWithOptions() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/droplets-first.json\"));\n\n      Iterable<Droplet> droplets = api.dropletApi().list(page(1).perPage(20));\n\n      assertEquals(size(droplets), 1);\n      assertEquals(server.getRequestCount(), 1);\n\n      assertSent(server, \"GET\", \"/droplets?page=1&per_page=20\");\n   }\n\n   public void testListDropletsWithOptionsReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      Iterable<Droplet> droplets = api.dropletApi().list(page(1).perPage(20));\n\n      assertTrue(isEmpty(droplets));\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/droplets?page=1&per_page=20\");\n   }\n   \n   public void testGetDroplet() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/droplet.json\"));\n\n      Droplet droplet = api.dropletApi().get(1);\n\n      assertEquals(droplet, dropletFromResource(\"/droplet.json\"));\n      \n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/droplets/1\");\n   }\n\n   public void testGetDropletReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      Droplet droplet = api.dropletApi().get(1);\n\n      assertNull(droplet);\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/droplets/1\");\n   }\n   \n   public void testCreateDroplet() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/droplet-create-res.json\"));\n\n      DropletCreate droplet = api.dropletApi().create(\"digitalocean2-s-d5e\", \"sfo1\", \"512mb\", \"6374124\", CreateDropletOptions.builder().addSshKeyId(421192).build());\n\n      assertEquals(droplet, objectFromResource(\"/droplet-create-res.json\", DropletCreate.class));\n      \n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"POST\", \"/droplets\", stringFromResource(\"/droplet-create-req.json\"));\n   }\n   \n   public void testListKernels() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/kernels-first.json\"));\n      server.enqueue(jsonResponse(\"/kernels-last.json\"));\n\n      Iterable<Kernel> kernels = api.dropletApi().listKernels(5425561).concat();\n\n      assertEquals(size(kernels), 10); // Force the PagedIterable to advance\n      assertEquals(server.getRequestCount(), 2);\n\n      assertSent(server, \"GET\", \"/droplets/5425561/kernels\");\n      assertSent(server, \"GET\", \"/droplets/5425561/kernels?page=2\");\n   }\n\n   public void testListKernelsReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      Iterable<Kernel> kernels = api.dropletApi().listKernels(5425561).concat();\n\n      assertTrue(isEmpty(kernels));\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/droplets/5425561/kernels\");\n   }\n   \n   public void testListKernelsWithOptions() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/kernels-first.json\"));\n\n      Iterable<Kernel> kernels = api.dropletApi().listKernels(5425561, page(1).perPage(20));\n\n      assertEquals(size(kernels), 5);\n      assertEquals(server.getRequestCount(), 1);\n\n      assertSent(server, \"GET\", \"/droplets/5425561/kernels?page=1&per_page=20\");\n   }\n\n   public void testListKernelsWithOptionsReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      Iterable<Kernel> kernels = api.dropletApi().listKernels(5425561, page(1).perPage(20));\n\n      assertTrue(isEmpty(kernels));\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/droplets/5425561/kernels?page=1&per_page=20\");\n   }\n   \n   public void testListActions() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/actions-first.json\"));\n      server.enqueue(jsonResponse(\"/actions-last.json\"));\n\n      Iterable<Action> actions = api.dropletApi().listActions(1).concat();\n\n      assertEquals(size(actions), 8); // Force the PagedIterable to advance\n      assertEquals(server.getRequestCount(), 2);\n\n      assertSent(server, \"GET\", \"/droplets/1/actions\");\n      assertSent(server, \"GET\", \"/droplets/1/actions?page=2&per_page=5\");\n   }\n\n   public void testListActionsReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      Iterable<Action> actions = api.dropletApi().listActions(1).concat();\n\n      assertTrue(isEmpty(actions));\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/droplets/1/actions\");\n   }\n\n   public void testListActionsWithOptions() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/actions-first.json\"));\n\n      Iterable<Action> actions = api.dropletApi().listActions(1, page(1).perPage(5));\n\n      assertEquals(size(actions), 5);\n      assertEquals(server.getRequestCount(), 1);\n\n      assertSent(server, \"GET\", \"/droplets/1/actions?page=1&per_page=5\");\n   }\n\n   public void testListActionsWithOptionsReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      Iterable<Action> actions = api.dropletApi().listActions(1, page(1).perPage(5));\n\n      assertTrue(isEmpty(actions));\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/droplets/1/actions?page=1&per_page=5\");\n   }\n   \n   public void testListBackups() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/backups-first.json\"));\n      server.enqueue(jsonResponse(\"/backups-last.json\"));\n\n      Iterable<Backup> backups = api.dropletApi().listBackups(5425561).concat();\n\n      assertEquals(size(backups), 2); // Force the PagedIterable to advance\n      assertEquals(server.getRequestCount(), 2);\n\n      assertSent(server, \"GET\", \"/droplets/5425561/backups\");\n      assertSent(server, \"GET\", \"/droplets/5425561/backups?page=2\");\n   }\n\n   public void testListBackupsReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      Iterable<Backup> backups = api.dropletApi().listBackups(5425561).concat();\n\n      assertTrue(isEmpty(backups));\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/droplets/5425561/backups\");\n   }\n   \n   public void testListBackupsWithOptions() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/backups-first.json\"));\n\n      Iterable<Backup> backups = api.dropletApi().listBackups(5425561, page(1).perPage(20));\n\n      assertEquals(size(backups), 1);\n      assertEquals(server.getRequestCount(), 1);\n\n      assertSent(server, \"GET\", \"/droplets/5425561/backups?page=1&per_page=20\");\n   }\n\n   public void testListBackupsWithOptionsReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      Iterable<Backup> backups = api.dropletApi().listBackups(5425561, page(1).perPage(20));\n\n      assertTrue(isEmpty(backups));\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/droplets/5425561/backups?page=1&per_page=20\");\n   }\n   \n   public void testListSnapshots() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/snapshots-first.json\"));\n      server.enqueue(jsonResponse(\"/snapshots-last.json\"));\n\n      Iterable<Snapshot> snapshots = api.dropletApi().listSnapshots(5425561).concat();\n\n      assertEquals(size(snapshots), 2); // Force the PagedIterable to advance\n      assertEquals(server.getRequestCount(), 2);\n\n      assertSent(server, \"GET\", \"/droplets/5425561/snapshots\");\n      assertSent(server, \"GET\", \"/droplets/5425561/snapshots?page=2\");\n   }\n\n   public void testListSnapshotsReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      Iterable<Snapshot> snapshots = api.dropletApi().listSnapshots(5425561).concat();\n\n      assertTrue(isEmpty(snapshots));\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/droplets/5425561/snapshots\");\n   }\n   \n   public void testListSnapshotsWithOptions() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/snapshots-first.json\"));\n\n      Iterable<Snapshot> snapshots = api.dropletApi().listSnapshots(5425561, page(1).perPage(20));\n\n      assertEquals(size(snapshots), 1);\n      assertEquals(server.getRequestCount(), 1);\n\n      assertSent(server, \"GET\", \"/droplets/5425561/snapshots?page=1&per_page=20\");\n   }\n\n   public void testListSnapshotsWithOptionsReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      Iterable<Snapshot> snapshots = api.dropletApi().listSnapshots(5425561, page(1).perPage(20));\n\n      assertTrue(isEmpty(snapshots));\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/droplets/5425561/snapshots?page=1&per_page=20\");\n   }\n   \n   public void testDeleteDroplet() throws InterruptedException {\n      server.enqueue(response204());\n\n      api.dropletApi().delete(1);\n      \n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"DELETE\", \"/droplets/1\");\n   }\n\n   public void testDeleteDropletReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      api.dropletApi().delete(1);\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"DELETE\", \"/droplets/1\");\n   }\n   \n   public void testPowerCycleDroplet() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/power-cycle.json\"));\n\n      Action action = api.dropletApi().powerCycle(1);\n      \n      assertEquals(action, actionFromResource(\"/power-cycle.json\"));\n      \n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"POST\", \"/droplets/1/actions\", \"{\\\"type\\\":\\\"power_cycle\\\"}\");\n   }\n   \n   public void testPowerOn() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/power-on.json\"));\n\n      Action action = api.dropletApi().powerOn(1);\n      \n      assertEquals(action, actionFromResource(\"/power-on.json\"));\n      \n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"POST\", \"/droplets/1/actions\", \"{\\\"type\\\":\\\"power_on\\\"}\");\n   }\n   \n   public void testPowerOff() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/power-off.json\"));\n\n      Action action = api.dropletApi().powerOff(1);\n      \n      assertEquals(action, actionFromResource(\"/power-off.json\"));\n      \n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"POST\", \"/droplets/1/actions\", \"{\\\"type\\\":\\\"power_off\\\"}\");\n   }\n   \n   public void testReboot() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/reboot.json\"));\n\n      Action action = api.dropletApi().reboot(1);\n      \n      assertEquals(action, actionFromResource(\"/reboot.json\"));\n      \n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"POST\", \"/droplets/1/actions\", \"{\\\"type\\\":\\\"reboot\\\"}\");\n   }\n   \n   public void testShutdown() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/shutdown.json\"));\n\n      Action action = api.dropletApi().shutdown(1);\n      \n      assertEquals(action, actionFromResource(\"/shutdown.json\"));\n      \n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"POST\", \"/droplets/1/actions\", \"{\\\"type\\\":\\\"shutdown\\\"}\");\n   }\n   \n   public void testSnapshot() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/snapshot.json\"));\n\n      Action action = api.dropletApi().snapshot(1, \"foo\");\n      \n      assertEquals(action, actionFromResource(\"/snapshot.json\"));\n      \n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"POST\", \"/droplets/1/actions\", \"{\\\"type\\\":\\\"snapshot\\\",\\\"name\\\":\\\"foo\\\"}\");\n   }\n   \n   private Droplet dropletFromResource(String resource) {\n      return onlyObjectFromResource(resource, new TypeToken<Map<String, Droplet>>() {\n         private static final long serialVersionUID = 1L;\n      }); \n   }\n   \n   private Action actionFromResource(String resource) {\n      return onlyObjectFromResource(resource, new TypeToken<Map<String, Action>>() {\n         private static final long serialVersionUID = 1L;\n      }); \n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/java/org/jclouds/digitalocean2/features/ImageApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.features;\n\nimport static org.jclouds.digitalocean2.domain.options.ImageListOptions.Builder.page;\nimport static org.jclouds.digitalocean2.domain.options.ImageListOptions.Builder.type;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.util.Strings.isNullOrEmpty;\n\nimport java.util.concurrent.atomic.AtomicInteger;\n\nimport org.jclouds.digitalocean2.domain.Image;\nimport org.jclouds.digitalocean2.internal.BaseDigitalOcean2ApiLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\n\n@Test(groups = \"live\", testName = \"ImageApiLiveTest\")\npublic class ImageApiLiveTest extends BaseDigitalOcean2ApiLiveTest {\n\n   public void testListImages() {\n      final AtomicInteger found = new AtomicInteger(0);\n      // DigitalOcean return 25 records per page by default. Inspect at most 2 pages\n      assertTrue(api().list().concat().limit(50).allMatch(new Predicate<Image>() {\n         @Override\n         public boolean apply(Image input) {\n            found.incrementAndGet();\n            return !isNullOrEmpty(input.name());\n         }\n      }), \"All images must have the 'name' field populated\");\n      assertTrue(found.get() > 0, \"Expected some images to be returned\");\n   }\n   \n   public void testListImagesOnePage() {\n      final AtomicInteger found = new AtomicInteger(0);\n      assertTrue(api().list(page(1).perPage(5)).allMatch(new Predicate<Image>() {\n         @Override\n         public boolean apply(Image input) {\n            found.incrementAndGet();\n            return !isNullOrEmpty(input.name());\n         }\n      }), \"All images must have the 'name' field populated\");\n      assertTrue(found.get() > 0, \"Expected some images to be returned\");\n   }\n   \n   public void testListImagesByType() {\n      final AtomicInteger found = new AtomicInteger(0);\n      assertTrue(api().list(type(\"distribution\").perPage(5)).allMatch(new Predicate<Image>() {\n         @Override\n         public boolean apply(Image input) {\n            found.incrementAndGet();\n            return !isNullOrEmpty(input.distribution());\n         }\n      }), \"All images must have the 'distribution' field populated\");\n      assertTrue(found.get() > 0, \"Expected some images to be returned\");\n   }\n   \n   public void testGetImage() {\n      Optional<Image> first = api().list().concat().first();\n      assertTrue(first.isPresent(), \"At least one image was expected to exist\");\n      assertNotNull(api().get(first.get().id()));\n   }\n   \n   public void testGetImageBySlug() {\n      Optional<Image> first = api().list().concat().firstMatch(new Predicate<Image>() {\n         @Override\n         public boolean apply(Image input) {\n            return !isNullOrEmpty(input.slug());\n         }\n      });\n      \n      assertTrue(first.isPresent(), \"At least one image with the 'slug' field set was expected to exist\");\n      assertNotNull(api().get(first.get().slug()));\n   }\n   \n   // TODO: Delete live test once the create/transfer operations are implemented\n   \n   private ImageApi api() {\n      return api.imageApi();\n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/java/org/jclouds/digitalocean2/features/ImageApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.features;\n\nimport static com.google.common.collect.Iterables.isEmpty;\nimport static com.google.common.collect.Iterables.size;\nimport static org.jclouds.digitalocean2.domain.options.ImageListOptions.Builder.page;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Map;\n\nimport org.jclouds.digitalocean2.domain.Image;\nimport org.jclouds.digitalocean2.internal.BaseDigitalOcean2ApiMockTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.reflect.TypeToken;\n\n@Test(groups = \"unit\", testName = \"ImageApiMockTest\", singleThreaded = true)\npublic class ImageApiMockTest extends BaseDigitalOcean2ApiMockTest {\n\n   public void testListImages() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/images-first.json\"));\n      server.enqueue(jsonResponse(\"/images-last.json\"));\n\n      Iterable<Image> images = api.imageApi().list().concat();\n\n      assertEquals(size(images), 10); // Force the PagedIterable to advance\n      assertEquals(server.getRequestCount(), 2);\n\n      assertSent(server, \"GET\", \"/images\");\n      assertSent(server, \"GET\", \"/images?page=2&per_page=5&type=distribution\");\n   }\n\n   public void testListImagesReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      Iterable<Image> images = api.imageApi().list().concat();\n\n      assertTrue(isEmpty(images));\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/images\");\n   }\n\n   public void testListImagesWithOptions() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/images-first.json\"));\n\n      Iterable<Image> images = api.imageApi().list(page(1).perPage(5).type(\"distribution\"));\n\n      assertEquals(size(images), 5);\n      assertEquals(server.getRequestCount(), 1);\n\n      assertSent(server, \"GET\", \"/images?page=1&per_page=5&type=distribution\");\n   }\n\n   public void testListImagesWithOptionsReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      Iterable<Image> images = api.imageApi().list(page(1).perPage(5).type(\"distribution\"));\n\n      assertTrue(isEmpty(images));\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/images?page=1&per_page=5&type=distribution\");\n   }\n   \n   public void testGetImage() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/image.json\"));\n\n      Image image = api.imageApi().get(1);\n\n      assertEquals(image, imageFromResource(\"/image.json\"));\n      \n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/images/1\");\n   }\n\n   public void testGetImageReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      Image image = api.imageApi().get(1);\n\n      assertNull(image);\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/images/1\");\n   }\n   \n   public void testGetImageUsingSlug() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/image.json\"));\n\n      Image image = api.imageApi().get(\"foo\");\n\n      assertEquals(image, imageFromResource(\"/image.json\"));\n      \n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/images/foo\");\n   }\n\n   public void testGetImageUsingSlugReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      Image image = api.imageApi().get(\"foo\");\n\n      assertNull(image);\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/images/foo\");\n   }\n   \n   public void testDeleteImage() throws InterruptedException {\n      server.enqueue(response204());\n\n      api.imageApi().delete(1);\n      \n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"DELETE\", \"/images/1\");\n   }\n\n   public void testDeleteImageReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      api.imageApi().delete(1);\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"DELETE\", \"/images/1\");\n   }\n   \n   private Image imageFromResource(String resource) {\n      return onlyObjectFromResource(resource, new TypeToken<Map<String, Image>>() {\n         private static final long serialVersionUID = 1L;\n      }); \n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/java/org/jclouds/digitalocean2/features/KeyApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.features;\n\nimport static org.jclouds.digitalocean2.domain.options.ListOptions.Builder.page;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\n\nimport org.jclouds.digitalocean2.domain.Key;\nimport org.jclouds.digitalocean2.internal.BaseDigitalOcean2ApiLiveTest;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.base.Throwables;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.io.Resources;\n\n@Test(groups = \"live\", testName = \"KeyApiLiveTest\")\npublic class KeyApiLiveTest extends BaseDigitalOcean2ApiLiveTest {\n\n   private Key dsa;\n   private Key ecdsa;\n\n   public void testCreateKey() {\n      dsa = api().create(\"jclouds-test-dsa\", loadKey(\"/ssh-dsa.pub\"));\n      ecdsa = api().create(\"jclouds-test-ecdsa\", loadKey(\"/ssh-ecdsa.pub\"));\n      \n      assertEquals(dsa.name(), \"jclouds-test-dsa\");\n      assertEquals(ecdsa.name(), \"jclouds-test-ecdsa\");\n   }\n   \n   @Test(dependsOnMethods = \"testCreateKey\")\n   public void testListKeys() {\n      FluentIterable<Key> keys = api().list().concat();\n      assertTrue(keys.size() >= 2, \"At least the two created keys must exist\");\n   }\n   \n   @Test(dependsOnMethods = \"testCreateKey\")\n   public void testListKeysOnePAge() {\n      FluentIterable<Key> keys = api().list(page(1));\n      assertTrue(keys.size() >= 2, \"At least the two created keys must exist\");\n   }\n\n   @Test(dependsOnMethods = \"testCreateKey\")\n   public void testGetKey() {\n      assertEquals(api().get(dsa.id()).fingerprint(), dsa.fingerprint());\n      assertEquals(api().get(ecdsa.fingerprint()).id(), ecdsa.id());\n   }\n   \n   @Test(dependsOnMethods = \"testCreateKey\")\n   public void testUpdateKey() {\n      api().update(dsa.id(), \"jclouds-test-dsa-updated\");\n      assertEquals(api().get(dsa.id()).name(), \"jclouds-test-dsa-updated\");\n   }\n\n   @AfterClass(alwaysRun = true)\n   public void testDeleteKey() {\n      if (dsa != null) {\n         api().delete(dsa.id());\n         FluentIterable<Key> keys = api().list().concat();\n         assertFalse(keys.contains(dsa), \"dsa key must not be present in list\");\n      }\n      if (ecdsa != null) {\n         api().delete(ecdsa.fingerprint());\n         FluentIterable<Key>  keys = api().list().concat();\n         assertFalse(keys.contains(ecdsa), \"dsa key must not be present in list\");\n      }\n   }\n   \n   private String loadKey(String resourceName) {\n      try {\n         return Resources.toString(getClass().getResource(resourceName), Charsets.UTF_8);\n      } catch (IOException e) {\n         throw Throwables.propagate(e);\n      }\n   }\n\n   private KeyApi api() {\n      return api.keyApi();\n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/java/org/jclouds/digitalocean2/features/KeyApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.features;\n\nimport static com.google.common.collect.Iterables.isEmpty;\nimport static com.google.common.collect.Iterables.size;\nimport static org.jclouds.digitalocean2.domain.options.ListOptions.Builder.page;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Map;\n\nimport org.jclouds.digitalocean2.domain.Key;\nimport org.jclouds.digitalocean2.internal.BaseDigitalOcean2ApiMockTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.reflect.TypeToken;\n\n@Test(groups = \"unit\", testName = \"KeyApiMockTest\", singleThreaded = true)\npublic class KeyApiMockTest extends BaseDigitalOcean2ApiMockTest {\n\n   public void testListKeys() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/keys-first.json\"));\n      server.enqueue(jsonResponse(\"/keys-last.json\"));\n\n      Iterable<Key> keys = api.keyApi().list().concat();\n\n      assertEquals(size(keys), 7); // Force the PagedIterable to advance\n      assertEquals(server.getRequestCount(), 2);\n\n      assertSent(server, \"GET\", \"/account/keys\");\n      assertSent(server, \"GET\", \"/account/keys?page=2&per_page=5\");\n   }\n\n   public void testListKeysReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      Iterable<Key> keys = api.keyApi().list().concat();\n\n      assertTrue(isEmpty(keys));\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/account/keys\");\n   }\n\n   public void testListKeysWithOptions() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/keys-first.json\"));\n\n      Iterable<Key> keys = api.keyApi().list(page(1).perPage(5));\n\n      assertEquals(size(keys), 5);\n      assertEquals(server.getRequestCount(), 1);\n\n      assertSent(server, \"GET\", \"/account/keys?page=1&per_page=5\");\n   }\n\n   public void testListKeysWithOptionsReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      Iterable<Key> keys = api.keyApi().list(page(1).perPage(5));\n\n      assertTrue(isEmpty(keys));\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/account/keys?page=1&per_page=5\");\n   }\n   \n   public void testCreateKey() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/key.json\").setStatus(\"HTTP/1.1 201 Created\"));\n      \n      String dsa = stringFromResource(\"/ssh-dsa.pub\");\n      \n      Key key = api.keyApi().create(\"foo\", dsa);\n      \n      assertEquals(key, keyFromResource(\"/key.json\"));\n      \n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"POST\", \"/account/keys\", String.format(\"{\\\"name\\\":\\\"foo\\\", \\\"public_key\\\":\\\"%s\\\"}\", dsa));\n   }\n   \n   public void testGetKey() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/key.json\"));\n\n      Key key = api.keyApi().get(1);\n\n      assertEquals(key, keyFromResource(\"/key.json\"));\n      \n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/account/keys/1\");\n   }\n\n   public void testGetKeyReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      Key key = api.keyApi().get(1);\n\n      assertNull(key);\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/account/keys/1\");\n   }\n   \n   public void testGetKeyUsingFingerprint() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/key.json\"));\n\n      Key key = api.keyApi().get(\"1a:cc:9b:88:c8:4f:b8:77:96:15:d2:0c:95:86:ff:90\");\n\n      assertEquals(key, keyFromResource(\"/key.json\"));\n      \n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/account/keys/1a:cc:9b:88:c8:4f:b8:77:96:15:d2:0c:95:86:ff:90\");\n   }\n\n   public void testGetKeyUsingFingerprintReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      Key key = api.keyApi().get(\"1a:cc:9b:88:c8:4f:b8:77:96:15:d2:0c:95:86:ff:90\");\n\n      assertNull(key);\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/account/keys/1a:cc:9b:88:c8:4f:b8:77:96:15:d2:0c:95:86:ff:90\");\n   }\n   \n   public void testUpdateKey() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/key.json\"));\n\n      Key key = api.keyApi().update(1, \"foo\");\n\n      assertEquals(key, keyFromResource(\"/key.json\"));\n      \n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"PUT\", \"/account/keys/1\", \"{\\\"name\\\":\\\"foo\\\"}\");\n   }\n   \n   public void testUpdateKeyUsingFingerprint() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/key.json\"));\n\n      Key key = api.keyApi().update(\"1a:cc:9b:88:c8:4f:b8:77:96:15:d2:0c:95:86:ff:90\", \"foo\");\n\n      assertEquals(key, keyFromResource(\"/key.json\"));\n      \n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"PUT\", \"/account/keys/1a:cc:9b:88:c8:4f:b8:77:96:15:d2:0c:95:86:ff:90\", \"{\\\"name\\\":\\\"foo\\\"}\");\n   }\n   \n   public void testDeleteKey() throws InterruptedException {\n      server.enqueue(response204());\n\n      api.keyApi().delete(1);\n      \n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"DELETE\", \"/account/keys/1\");\n   }\n\n   public void testDeleteKeyReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      api.keyApi().delete(1);\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"DELETE\", \"/account/keys/1\");\n   }\n   \n   public void testDeleteKeyUsingFingerprint() throws InterruptedException {\n      server.enqueue(response204());\n\n      api.keyApi().delete(\"1a:cc:9b:88:c8:4f:b8:77:96:15:d2:0c:95:86:ff:90\");\n      \n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"DELETE\", \"/account/keys/1a:cc:9b:88:c8:4f:b8:77:96:15:d2:0c:95:86:ff:90\");\n   }\n\n   public void testDeleteKeyUsingfingerprintReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      api.keyApi().delete(\"1a:cc:9b:88:c8:4f:b8:77:96:15:d2:0c:95:86:ff:90\");\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"DELETE\", \"/account/keys/1a:cc:9b:88:c8:4f:b8:77:96:15:d2:0c:95:86:ff:90\");\n   }\n   \n   private Key keyFromResource(String resource) {\n      return onlyObjectFromResource(resource, new TypeToken<Map<String, Key>>() {\n         private static final long serialVersionUID = 1L;\n      }); \n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/java/org/jclouds/digitalocean2/features/RegionApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.features;\n\nimport static org.testng.Assert.assertTrue;\nimport static org.jclouds.digitalocean2.domain.options.ListOptions.Builder.page;\n\nimport java.util.concurrent.atomic.AtomicInteger;\n\nimport org.jclouds.digitalocean2.domain.Region;\nimport org.jclouds.digitalocean2.internal.BaseDigitalOcean2ApiLiveTest;\nimport org.testng.annotations.Test;\nimport org.testng.util.Strings;\n\nimport com.google.common.base.Predicate;\n\n@Test(groups = \"live\", testName = \"RegionApiLiveTest\")\npublic class RegionApiLiveTest extends BaseDigitalOcean2ApiLiveTest {\n   \n   public void testListRegions() {\n      final AtomicInteger found = new AtomicInteger(0);\n      // DigitalOcean return 25 records per page by default. Inspect at most 2 pages\n      assertTrue(api().list().concat().limit(50).allMatch(new Predicate<Region>() {\n         @Override\n         public boolean apply(Region input) {\n            found.incrementAndGet();\n            return !Strings.isNullOrEmpty(input.slug());\n         }\n      }), \"All regions must have the 'slug' field populated\");\n      assertTrue(found.get() > 0, \"Expected some regions to be returned\");\n   }\n   \n   public void testListRegionsOnePage() {\n      final AtomicInteger found = new AtomicInteger(0);\n      assertTrue(api().list(page(1)).allMatch(new Predicate<Region>() {\n         @Override\n         public boolean apply(Region input) {\n            found.incrementAndGet();\n            return !Strings.isNullOrEmpty(input.slug());\n         }\n      }), \"All regions must have the 'slug' field populated\");\n      assertTrue(found.get() > 0, \"Expected some regions to be returned\");\n   }\n   \n   private RegionApi api() {\n      return api.regionApi();\n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/java/org/jclouds/digitalocean2/features/RegionApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.features;\n\nimport static com.google.common.collect.Iterables.isEmpty;\nimport static com.google.common.collect.Iterables.size;\nimport static org.jclouds.digitalocean2.domain.options.ListOptions.Builder.page;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.digitalocean2.domain.Region;\nimport org.jclouds.digitalocean2.internal.BaseDigitalOcean2ApiMockTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"RegionApiMockTest\", singleThreaded = true)\npublic class RegionApiMockTest extends BaseDigitalOcean2ApiMockTest {\n\n   public void testListRegions() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/regions-first.json\"));\n      server.enqueue(jsonResponse(\"/regions-last.json\"));\n\n      Iterable<Region> regions = api.regionApi().list().concat();\n\n      assertEquals(size(regions), 10); // Force the PagedIterable to advance\n      assertEquals(server.getRequestCount(), 2);\n\n      assertSent(server, \"GET\", \"/regions\");\n      assertSent(server, \"GET\", \"/regions?page=2&per_page=5\");\n   }\n\n   public void testListRegionsReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      Iterable<Region> regions = api.regionApi().list().concat();\n\n      assertTrue(isEmpty(regions));\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/regions\");\n   }\n\n   public void testListRegionsWithOptions() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/regions-first.json\"));\n\n      Iterable<Region> regions = api.regionApi().list(page(1).perPage(5));\n\n      assertEquals(size(regions), 5);\n      assertEquals(server.getRequestCount(), 1);\n\n      assertSent(server, \"GET\", \"/regions?page=1&per_page=5\");\n   }\n\n   public void testListRegionsWithOptionsReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      Iterable<Region> regions = api.regionApi().list(page(1).perPage(5));\n\n      assertTrue(isEmpty(regions));\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/regions?page=1&per_page=5\");\n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/java/org/jclouds/digitalocean2/features/SizeApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.features;\n\nimport static org.jclouds.digitalocean2.domain.options.ListOptions.Builder.page;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.concurrent.atomic.AtomicInteger;\n\nimport org.jclouds.digitalocean2.domain.Size;\nimport org.jclouds.digitalocean2.internal.BaseDigitalOcean2ApiLiveTest;\nimport org.testng.annotations.Test;\nimport org.testng.util.Strings;\n\nimport com.google.common.base.Predicate;\n\n@Test(groups = \"live\", testName = \"SizeApiLiveTest\")\npublic class SizeApiLiveTest extends BaseDigitalOcean2ApiLiveTest {\n   \n   public void testListSizes() {\n      final AtomicInteger found = new AtomicInteger(0);\n      // DigitalOcean return 25 records per page by default. Inspect at most 2 pages\n      assertTrue(api().list().concat().limit(50).allMatch(new Predicate<Size>() {\n         @Override\n         public boolean apply(Size input) {\n            found.incrementAndGet();\n            return !Strings.isNullOrEmpty(input.slug());\n         }\n      }), \"All sizes must have the 'slug' field populated\");\n      assertTrue(found.get() > 0, \"Expected some sizes to be returned\");\n   }\n   \n   public void testListSizesOnePage() {\n      final AtomicInteger found = new AtomicInteger(0);\n      assertTrue(api().list(page(1)).allMatch(new Predicate<Size>() {\n         @Override\n         public boolean apply(Size input) {\n            found.incrementAndGet();\n            return !Strings.isNullOrEmpty(input.slug());\n         }\n      }), \"All sizes must have the 'slug' field populated\");\n      assertTrue(found.get() > 0, \"Expected some sizes to be returned\");\n   }\n   \n   private SizeApi api() {\n      return api.sizeApi();\n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/java/org/jclouds/digitalocean2/features/SizeApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.features;\n\nimport static com.google.common.collect.Iterables.isEmpty;\nimport static com.google.common.collect.Iterables.size;\nimport static org.jclouds.digitalocean2.domain.options.ListOptions.Builder.page;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.digitalocean2.domain.Size;\nimport org.jclouds.digitalocean2.internal.BaseDigitalOcean2ApiMockTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"SizeApiMockTest\", singleThreaded = true)\npublic class SizeApiMockTest extends BaseDigitalOcean2ApiMockTest {\n\n   public void testListSizes() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/sizes-first.json\"));\n      server.enqueue(jsonResponse(\"/sizes-last.json\"));\n\n      Iterable<Size> sizes = api.sizeApi().list().concat();\n\n      assertEquals(size(sizes), 9); // Force the PagedIterable to advance\n      assertEquals(server.getRequestCount(), 2);\n\n      assertSent(server, \"GET\", \"/sizes\");\n      assertSent(server, \"GET\", \"/sizes?page=2&per_page=5\");\n   }\n\n   public void testListSizesReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      Iterable<Size> sizes = api.sizeApi().list().concat();\n\n      assertTrue(isEmpty(sizes));\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/sizes\");\n   }\n\n   public void testListSizesWithOptions() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/sizes-first.json\"));\n\n      Iterable<Size> sizes = api.sizeApi().list(page(1).perPage(5));\n\n      assertEquals(size(sizes), 5);\n      assertEquals(server.getRequestCount(), 1);\n\n      assertSent(server, \"GET\", \"/sizes?page=1&per_page=5\");\n   }\n\n   public void testListSizesWithOptionsReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      Iterable<Size> sizes = api.sizeApi().list(page(1).perPage(5));\n\n      assertTrue(isEmpty(sizes));\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/sizes?page=1&per_page=5\");\n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/java/org/jclouds/digitalocean2/functions/LinkToImageListOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.functions;\n\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static org.jclouds.digitalocean2.domain.options.ImageListOptions.PRIVATE_PARAM;\nimport static org.jclouds.digitalocean2.domain.options.ImageListOptions.TYPE_PARAM;\nimport static org.jclouds.digitalocean2.domain.options.ListOptions.PAGE_PARAM;\nimport static org.jclouds.digitalocean2.domain.options.ListOptions.PER_PAGE_PARAM;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.net.URI;\n\nimport org.jclouds.digitalocean2.domain.options.ImageListOptions;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Multimap;\n\n@Test(groups = \"unit\", testName = \"LinkToImageListOptionsTest\")\npublic class LinkToImageListOptionsTest {\n\n   public void testNoOptions() {\n      LinkToImageListOptions function = new LinkToImageListOptions();\n\n      ImageListOptions options = function.apply(URI.create(\"https://api.digitalocean.com/v2/images\"));\n      assertNotNull(options);\n\n      Multimap<String, String> params = options.buildQueryParameters();\n      assertFalse(params.containsKey(PAGE_PARAM));\n      assertFalse(params.containsKey(PER_PAGE_PARAM));\n      assertFalse(params.containsKey(TYPE_PARAM));\n      assertFalse(params.containsKey(PRIVATE_PARAM));\n   }\n\n   public void testWithOptions() {\n      LinkToImageListOptions function = new LinkToImageListOptions();\n\n      ImageListOptions options = function.apply(URI\n            .create(\"https://api.digitalocean.com/v2/images?page=1&per_page=5&type=distribution&private=true\"));\n      assertNotNull(options);\n\n      Multimap<String, String> params = options.buildQueryParameters();\n      assertEquals(getOnlyElement(params.get(PAGE_PARAM)), \"1\");\n      assertEquals(getOnlyElement(params.get(PER_PAGE_PARAM)), \"5\");\n      assertEquals(getOnlyElement(params.get(TYPE_PARAM)), \"distribution\");\n      assertEquals(getOnlyElement(params.get(PRIVATE_PARAM)), \"true\");\n   }\n\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/java/org/jclouds/digitalocean2/functions/LinkToListOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.functions;\n\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static org.jclouds.digitalocean2.domain.options.ListOptions.PAGE_PARAM;\nimport static org.jclouds.digitalocean2.domain.options.ListOptions.PER_PAGE_PARAM;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.net.URI;\n\nimport org.jclouds.digitalocean2.domain.options.ListOptions;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Multimap;\n\n@Test(groups = \"unit\", testName = \"LinkToListOptionsTest\")\npublic class LinkToListOptionsTest {\n\n   public void testNoOptions() {\n      LinkToListOptions function = new LinkToListOptions();\n\n      ListOptions options = function.apply(URI.create(\"https://api.digitalocean.com/v2/actions\"));\n      assertNotNull(options);\n\n      Multimap<String, String> params = options.buildQueryParameters();\n      assertFalse(params.containsKey(PAGE_PARAM));\n      assertFalse(params.containsKey(PER_PAGE_PARAM));\n   }\n\n   public void testWithOptions() {\n      LinkToListOptions function = new LinkToListOptions();\n\n      ListOptions options = function.apply(URI.create(\"https://api.digitalocean.com/v2/actions?page=2&per_page=5\"));\n      assertNotNull(options);\n\n      Multimap<String, String> params = options.buildQueryParameters();\n      assertEquals(getOnlyElement(params.get(PAGE_PARAM)), \"2\");\n      assertEquals(getOnlyElement(params.get(PER_PAGE_PARAM)), \"5\");\n   }\n\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/java/org/jclouds/digitalocean2/internal/BaseDigitalOcean2ApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.internal;\n\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_RUNNING;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_SUSPENDED;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_TERMINATED;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.util.Strings.isNullOrEmpty;\n\nimport java.util.Properties;\nimport java.util.concurrent.TimeUnit;\n\nimport org.jclouds.apis.BaseApiLiveTest;\nimport org.jclouds.compute.config.ComputeServiceProperties;\nimport org.jclouds.digitalocean2.DigitalOcean2Api;\nimport org.jclouds.digitalocean2.config.DigitalOcean2RateLimitModule;\nimport org.jclouds.digitalocean2.domain.Image;\nimport org.jclouds.digitalocean2.domain.Region;\nimport org.jclouds.digitalocean2.domain.Size;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ComparisonChain;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Ordering;\nimport com.google.inject.Injector;\nimport com.google.inject.Key;\nimport com.google.inject.Module;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.name.Names;\n\npublic class BaseDigitalOcean2ApiLiveTest extends BaseApiLiveTest<DigitalOcean2Api> {\n\n   private Predicate<Long> actionCompleted;\n   private Predicate<Integer> nodeTerminated;\n   private Predicate<Integer> nodeStopped;\n   private Predicate<Integer> nodeRunning;\n\n   public BaseDigitalOcean2ApiLiveTest() {\n      provider = \"digitalocean2\";\n   }\n\n   @Override protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      props.put(ComputeServiceProperties.POLL_INITIAL_PERIOD, 1000);\n      props.put(ComputeServiceProperties.POLL_MAX_PERIOD, 10000);\n      props.put(ComputeServiceProperties.TIMEOUT_IMAGE_AVAILABLE, TimeUnit.MINUTES.toMillis(45));\n      return props;\n   }\n\n   @Override protected DigitalOcean2Api create(Properties props, Iterable<Module> modules) {\n      Injector injector = newBuilder().modules(modules).overrides(props).buildInjector();\n      actionCompleted = injector.getInstance(Key.get(new TypeLiteral<Predicate<Long>>(){}));\n      nodeTerminated = injector.getInstance(Key.get(new TypeLiteral<Predicate<Integer>>(){},\n            Names.named(TIMEOUT_NODE_TERMINATED)));\n      nodeStopped = injector.getInstance(Key.get(new TypeLiteral<Predicate<Integer>>(){},\n            Names.named(TIMEOUT_NODE_SUSPENDED)));\n      nodeRunning = injector.getInstance(Key.get(new TypeLiteral<Predicate<Integer>>(){},\n            Names.named(TIMEOUT_NODE_RUNNING)));\n      return injector.getInstance(DigitalOcean2Api.class);\n   }\n\n   @Override protected Iterable<Module> setupModules() {\n      return ImmutableSet.<Module> builder().addAll(super.setupModules()).add(new DigitalOcean2RateLimitModule())\n            .build();\n   }\n\n   protected void assertActionCompleted(long actionId) {\n      assertTrue(actionCompleted.apply(actionId), String.format(\"Action %s did not complete in the configured timeout\", actionId));\n   }\n\n   protected void assertNodeStopped(int dropletId) {\n      assertTrue(nodeStopped.apply(dropletId), String.format(\"Droplet %s did not stop in the configured timeout\", dropletId));\n   }\n\n   protected void assertNodeRunning(int dropletId) {\n      assertTrue(nodeRunning.apply(dropletId), String.format(\"Droplet %s did not start in the configured timeout\", dropletId));\n   }\n\n   protected void assertNodeTerminated(int dropletId) {\n      assertTrue(nodeTerminated.apply(dropletId), String.format(\"Droplet %s was not terminated in the configured timeout\", dropletId));\n   }\n   \n   protected Region firstAvailableRegion() {\n      return api.regionApi().list().concat().firstMatch(new Predicate<Region>() {\n         @Override\n         public boolean apply(Region input) {\n            return input.available();\n         }\n      }).get();\n   }\n   \n   protected Size cheapestSizeInRegionForImage(final Region region, final Image image) {\n      return sizesByPrice().min(api.sizeApi().list().concat().filter(new Predicate<Size>() {\n         @Override\n         public boolean apply(Size input) {\n            return input.available() && input.regions().contains(region.slug()) && input.disk() >= image.minDiskSize();\n         }\n      }));\n   }\n   \n   protected Image ubuntuImageInRegion(final Region region) {\n      return api.imageApi().list().concat().firstMatch(new Predicate<Image>() {\n         @Override\n         public boolean apply(Image input) {\n            return \"Ubuntu\".equalsIgnoreCase(input.distribution()) && !isNullOrEmpty(input.slug())\n                  && input.regions().contains(region.slug());\n         }\n      }).get();\n   }\n   \n   protected static Ordering<Size> sizesByPrice() {\n      return new Ordering<Size>() {\n         @Override\n         public int compare(Size left, Size right) {\n            return ComparisonChain.start()\n                  .compare(left.priceHourly(), right.priceHourly())\n                  .compare(left.priceMonthly(), right.priceMonthly())\n                  .result();\n         }\n      };\n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/java/org/jclouds/digitalocean2/internal/BaseDigitalOcean2ApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.internal;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static com.google.common.util.concurrent.MoreExecutors.newDirectExecutorService;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\nimport okhttp3.mockwebserver.RecordedRequest;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.concurrent.config.ExecutorServiceModule;\nimport org.jclouds.digitalocean2.DigitalOcean2Api;\nimport org.jclouds.digitalocean2.DigitalOcean2ProviderMetadata;\nimport org.jclouds.json.Json;\nimport org.jclouds.rest.ApiContext;\nimport org.testng.annotations.AfterMethod;\nimport org.testng.annotations.BeforeMethod;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.base.Throwables;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.io.Resources;\nimport com.google.common.reflect.TypeToken;\nimport com.google.gson.JsonParser;\nimport com.google.inject.Module;\n\n\npublic class BaseDigitalOcean2ApiMockTest {\n   \n   private static final String MOCK_BEARER_TOKEN = \"c5401990f0c24135e8d6b5d260603fc71696d4738da9aa04a720229a01a2521d\";\n   private static final String DEFAULT_ENDPOINT = new DigitalOcean2ProviderMetadata().getEndpoint();\n   \n   private final Set<Module> modules = ImmutableSet.<Module> of(new ExecutorServiceModule(newDirectExecutorService()));\n   \n   protected MockWebServer server;\n   protected DigitalOcean2Api api;\n   private Json json;\n   \n   // So that we can ignore formatting.\n   private final JsonParser parser = new JsonParser();\n   \n   @BeforeMethod\n   public void start() throws IOException {\n      server = new MockWebServer();\n      server.start();\n      ApiContext<DigitalOcean2Api> ctx = ContextBuilder.newBuilder(\"digitalocean2\")\n            .credentials(\"\", MOCK_BEARER_TOKEN)\n            .endpoint(url(\"\"))\n            .modules(modules)\n            .overrides(overrides())\n            .build();\n      json = ctx.utils().injector().getInstance(Json.class);\n      api = ctx.getApi();\n   }\n\n   @AfterMethod(alwaysRun = true)\n   public void stop() throws IOException {\n      server.shutdown();\n      api.close();\n   }\n   \n   protected Properties overrides() {\n      return new Properties();\n   }\n\n   protected String url(String path) {\n      return server.url(path).toString();\n   }\n\n   protected MockResponse jsonResponse(String resource) {\n      return new MockResponse().addHeader(\"Content-Type\", \"application/json\").setBody(stringFromResource(resource));\n   }\n\n   protected MockResponse response404() {\n      return new MockResponse().setStatus(\"HTTP/1.1 404 Not Found\");\n   }\n   \n   protected MockResponse response204() {\n      return new MockResponse().setStatus(\"HTTP/1.1 204 No Content\");\n   }\n\n   protected String stringFromResource(String resourceName) {\n      try {\n         return Resources.toString(getClass().getResource(resourceName), Charsets.UTF_8)\n               .replace(DEFAULT_ENDPOINT, url(\"\"));\n      } catch (IOException e) {\n         throw Throwables.propagate(e);\n      }\n   }\n   \n   protected <T> T onlyObjectFromResource(String resourceName, TypeToken<Map<String, T>> type) {\n      // Assume JSON objects passed here will be in the form: { \"entity\": { ... } }\n      String text = stringFromResource(resourceName);\n      Map<String, T> object = json.fromJson(text, type.getType());\n      checkArgument(!object.isEmpty(), \"The given json does not contain any object: %s\", text);\n      checkArgument(object.keySet().size() == 1, \"The given json does not contain more than one object: %s\", text);\n      return object.get(getOnlyElement(object.keySet()));\n   }\n   \n   protected <T> T objectFromResource(String resourceName, Class<T> type) {\n      String text = stringFromResource(resourceName);\n      return json.fromJson(text, type);\n   }\n\n   protected RecordedRequest assertSent(MockWebServer server, String method, String path) throws InterruptedException {\n      RecordedRequest request = server.takeRequest();\n      assertEquals(request.getMethod(), method);\n      assertEquals(request.getPath(), path);\n      assertEquals(request.getHeader(\"Accept\"), \"application/json\");\n      assertEquals(request.getHeader(\"Authorization\"), \"Bearer \" + MOCK_BEARER_TOKEN);\n      return request;\n   }\n\n   protected RecordedRequest assertSent(MockWebServer server, String method, String path, String json)\n         throws InterruptedException {\n      RecordedRequest request = assertSent(server, method, path);\n      assertEquals(request.getHeader(\"Content-Type\"), \"application/json\");\n      assertEquals(parser.parse(request.getBody().readUtf8()), parser.parse(json));\n      return request;\n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/java/org/jclouds/digitalocean2/ssh/DSAKeysTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.ssh;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.security.KeyFactory;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.interfaces.DSAPublicKey;\nimport java.security.spec.DSAPublicKeySpec;\nimport java.security.spec.InvalidKeySpecException;\n\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.Test;\n\n/**\n * Unit tests for the {@link DSAKeys} class.\n */\n@Test(groups = \"unit\", testName = \"DSAKeysTest\")\npublic class DSAKeysTest {\n\n   private static final String expectedFingerPrint = \"2a:54:bb:8e:ba:44:96:c8:6c:9c:40:34:3c:4d:38:e4\";\n\n   @Test\n   public void testCanReadRsaAndCompareFingerprintOnPublicRSAKey() throws IOException {\n      String dsa = Strings2.toStringAndClose(getClass().getResourceAsStream(\"/ssh-dsa.pub\"));\n      String fingerPrint = DSAKeys.fingerprintPublicKey(dsa);\n      assertEquals(fingerPrint, expectedFingerPrint);\n   }\n\n   @Test\n   public void testEncodeAsOpenSSH() throws IOException, InvalidKeySpecException, NoSuchAlgorithmException {\n      String dsa = Strings2.toStringAndClose(getClass().getResourceAsStream(\"/ssh-dsa.pub\"));\n      DSAPublicKeySpec spec = DSAKeys.publicKeySpecFromOpenSSH(dsa);\n      DSAPublicKey key = (DSAPublicKey) KeyFactory.getInstance(\"DSA\").generatePublic(spec);\n\n      assertEquals(DSAKeys.encodeAsOpenSSH(key), dsa);\n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/java/org/jclouds/digitalocean2/ssh/ECDSAKeysTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.digitalocean2.ssh;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.security.KeyFactory;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.interfaces.ECPublicKey;\nimport java.security.spec.ECPublicKeySpec;\nimport java.security.spec.InvalidKeySpecException;\n\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.Test;\n\n/**\n * Unit tests for the {@link ECDSAKeysTest} class.\n */\n@Test(groups = \"unit\", testName = \"ECDSAKeysTest\")\npublic class ECDSAKeysTest {\n\n   private static final String expectedFingerPrint = \"0e:9f:aa:cc:3e:79:5d:1e:f9:19:58:08:dc:c4:5e:1c\";\n\n   @Test\n   public void testCanReadRsaAndCompareFingerprintOnPublicECDSAKey() throws IOException {\n      String ecdsa = Strings2.toStringAndClose(getClass().getResourceAsStream(\"/ssh-ecdsa.pub\"));\n      String fingerPrint = ECDSAKeys.fingerprintPublicKey(ecdsa);\n      assertEquals(fingerPrint, expectedFingerPrint);\n   }\n\n   @Test\n   public void testEncodeAsOpenSSH() throws IOException, InvalidKeySpecException, NoSuchAlgorithmException {\n      String ecdsa = Strings2.toStringAndClose(getClass().getResourceAsStream(\"/ssh-ecdsa.pub\"));\n      ECPublicKeySpec spec = ECDSAKeys.publicKeySpecFromOpenSSH(ecdsa);\n      ECPublicKey key = (ECPublicKey) KeyFactory.getInstance(\"EC\").generatePublic(spec);\n\n      assertTrue(ecdsa.startsWith(ECDSAKeys.encodeAsOpenSSH(key)));\n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/resources/action.json",
    "content": "{\n    \"action\": {\n         \"region\" : {\n            \"name\" : \"New York 1\",\n            \"available\" : true,\n            \"slug\" : \"nyc1\",\n            \"features\" : [\n               \"virtio\",\n               \"backups\",\n               \"metadata\"\n            ],\n            \"sizes\" : [\n               \"512mb\",\n               \"8gb\",\n               \"16gb\",\n               \"32gb\",\n               \"48gb\",\n               \"64gb\",\n               \"1gb\",\n               \"2gb\",\n               \"4gb\"\n            ]\n         },\n         \"started_at\" : \"2015-05-19T15:17:55Z\",\n         \"status\" : \"completed\",\n         \"resource_type\" : \"droplet\",\n         \"resource_id\" : 5347489,\n         \"region_slug\" : \"nyc1\",\n         \"id\" : 50900149,\n         \"completed_at\" : \"2015-05-19T15:18:01Z\",\n         \"type\" : \"destroy\"\n      }\n}"
  },
  {
    "path": "providers/digitalocean2/src/test/resources/actions-first.json",
    "content": "{\n   \"actions\" : [\n      {\n         \"region\" : {\n            \"name\" : \"New York 1\",\n            \"available\" : true,\n            \"slug\" : \"nyc1\",\n            \"features\" : [\n               \"virtio\",\n               \"backups\",\n               \"metadata\"\n            ],\n            \"sizes\" : [\n               \"512mb\",\n               \"8gb\",\n               \"16gb\",\n               \"32gb\",\n               \"48gb\",\n               \"64gb\",\n               \"1gb\",\n               \"2gb\",\n               \"4gb\"\n            ]\n         },\n         \"started_at\" : \"2015-05-19T15:17:55Z\",\n         \"status\" : \"completed\",\n         \"resource_type\" : \"droplet\",\n         \"resource_id\" : 5347489,\n         \"region_slug\" : \"nyc1\",\n         \"id\" : 50900149,\n         \"completed_at\" : \"2015-05-19T15:18:01Z\",\n         \"type\" : \"destroy\"\n      },\n      {\n         \"started_at\" : \"2015-05-19T15:07:55Z\",\n         \"region\" : {\n            \"sizes\" : [\n               \"512mb\",\n               \"8gb\",\n               \"16gb\",\n               \"32gb\",\n               \"48gb\",\n               \"64gb\",\n               \"1gb\",\n               \"2gb\",\n               \"4gb\"\n            ],\n            \"features\" : [\n               \"virtio\",\n               \"backups\",\n               \"metadata\"\n            ],\n            \"available\" : true,\n            \"slug\" : \"nyc1\",\n            \"name\" : \"New York 1\"\n         },\n         \"status\" : \"completed\",\n         \"resource_type\" : \"droplet\",\n         \"region_slug\" : \"nyc1\",\n         \"id\" : 50899364,\n         \"resource_id\" : 5346565,\n         \"completed_at\" : \"2015-05-19T15:08:04Z\",\n         \"type\" : \"destroy\"\n      },\n      {\n         \"completed_at\" : \"2015-05-19T13:39:59Z\",\n         \"type\" : \"create\",\n         \"region\" : {\n            \"name\" : \"New York 1\",\n            \"sizes\" : [\n               \"512mb\",\n               \"8gb\",\n               \"16gb\",\n               \"32gb\",\n               \"48gb\",\n               \"64gb\",\n               \"1gb\",\n               \"2gb\",\n               \"4gb\"\n            ],\n            \"features\" : [\n               \"virtio\",\n               \"backups\",\n               \"metadata\"\n            ],\n            \"available\" : true,\n            \"slug\" : \"nyc1\"\n         },\n         \"started_at\" : \"2015-05-19T13:39:12Z\",\n         \"resource_type\" : \"droplet\",\n         \"status\" : \"completed\",\n         \"resource_id\" : 5347489,\n         \"region_slug\" : \"nyc1\",\n         \"id\" : 50892713\n      },\n      {\n         \"resource_id\" : 5346565,\n         \"region_slug\" : \"nyc1\",\n         \"id\" : 50888077,\n         \"status\" : \"completed\",\n         \"resource_type\" : \"droplet\",\n         \"region\" : {\n            \"name\" : \"New York 1\",\n            \"features\" : [\n               \"virtio\",\n               \"backups\",\n               \"metadata\"\n            ],\n            \"available\" : true,\n            \"slug\" : \"nyc1\",\n            \"sizes\" : [\n               \"512mb\",\n               \"8gb\",\n               \"16gb\",\n               \"32gb\",\n               \"48gb\",\n               \"64gb\",\n               \"1gb\",\n               \"2gb\",\n               \"4gb\"\n            ]\n         },\n         \"started_at\" : \"2015-05-19T12:37:23Z\",\n         \"type\" : \"create\",\n         \"completed_at\" : \"2015-05-19T12:38:13Z\"\n      },\n      {\n         \"completed_at\" : \"2015-05-19T11:33:00Z\",\n         \"type\" : \"destroy\",\n         \"status\" : \"completed\",\n         \"resource_type\" : \"droplet\",\n         \"started_at\" : \"2015-05-19T11:32:55Z\",\n         \"region\" : {\n            \"available\" : true,\n            \"features\" : [\n               \"virtio\",\n               \"backups\",\n               \"metadata\"\n            ],\n            \"slug\" : \"nyc1\",\n            \"sizes\" : [\n               \"512mb\",\n               \"8gb\",\n               \"16gb\",\n               \"32gb\",\n               \"48gb\",\n               \"64gb\",\n               \"1gb\",\n               \"2gb\",\n               \"4gb\"\n            ],\n            \"name\" : \"New York 1\"\n         },\n         \"region_slug\" : \"nyc1\",\n         \"id\" : 50884032,\n         \"resource_id\" : 5344505\n      }\n   ],\n   \"links\" : {\n      \"pages\" : {\n         \"last\" : \"https://api.digitalocean.com/v2/actions?page=2&per_page=5\",\n         \"next\" : \"https://api.digitalocean.com/v2/actions?page=2&per_page=5\"\n      }\n   },\n   \"meta\" : {\n      \"total\" : 8\n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/resources/actions-last.json",
    "content": "{\n   \"meta\" : {\n      \"total\" : 8\n   },\n   \"links\" : {\n      \"pages\" : {\n         \"first\" : \"https://api.digitalocean.com/v2/actions?page=1&per_page=5\",\n         \"prev\" : \"https://api.digitalocean.com/v2/actions?page=1&per_page=5\"\n      }\n   },\n   \"actions\" : [\n      {\n         \"region\" : {\n            \"sizes\" : [\n               \"512mb\",\n               \"8gb\",\n               \"16gb\",\n               \"32gb\",\n               \"48gb\",\n               \"64gb\",\n               \"1gb\",\n               \"2gb\",\n               \"4gb\"\n            ],\n            \"available\" : true,\n            \"features\" : [\n               \"virtio\",\n               \"backups\",\n               \"metadata\"\n            ],\n            \"slug\" : \"nyc1\",\n            \"name\" : \"New York 1\"\n         },\n         \"started_at\" : \"2014-01-18T22:39:08Z\",\n         \"type\" : \"create\",\n         \"resource_type\" : \"droplet\",\n         \"id\" : 14115951,\n         \"completed_at\" : \"2014-01-18T22:41:14Z\",\n         \"region_slug\" : \"nyc1\",\n         \"resource_id\" : 1010699,\n         \"status\" : \"completed\"\n      },\n      {\n         \"started_at\" : \"2014-01-18T22:39:06Z\",\n         \"type\" : \"create\",\n         \"resource_type\" : \"droplet\",\n         \"region\" : {\n            \"sizes\" : [\n               \"512mb\",\n               \"8gb\",\n               \"16gb\",\n               \"32gb\",\n               \"48gb\",\n               \"64gb\",\n               \"1gb\",\n               \"2gb\",\n               \"4gb\"\n            ],\n            \"slug\" : \"nyc1\",\n            \"name\" : \"New York 1\",\n            \"features\" : [\n               \"virtio\",\n               \"backups\",\n               \"metadata\"\n            ],\n            \"available\" : true\n         },\n         \"resource_id\" : 1010697,\n         \"region_slug\" : \"nyc1\",\n         \"status\" : \"completed\",\n         \"id\" : 14115948,\n         \"completed_at\" : \"2014-01-18T22:40:43Z\"\n      },\n      {\n         \"region_slug\" : \"nyc1\",\n         \"resource_id\" : 1010698,\n         \"status\" : \"completed\",\n         \"id\" : 14115949,\n         \"completed_at\" : \"2014-01-18T22:44:08Z\",\n         \"type\" : \"create\",\n         \"started_at\" : \"2014-01-18T22:39:06Z\",\n         \"resource_type\" : \"droplet\",\n         \"region\" : {\n            \"sizes\" : [\n               \"512mb\",\n               \"8gb\",\n               \"16gb\",\n               \"32gb\",\n               \"48gb\",\n               \"64gb\",\n               \"1gb\",\n               \"2gb\",\n               \"4gb\"\n            ],\n            \"slug\" : \"nyc1\",\n            \"name\" : \"New York 1\",\n            \"available\" : true,\n            \"features\" : [\n               \"virtio\",\n               \"backups\",\n               \"metadata\"\n            ]\n         }\n      }\n   ]\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/resources/backups-first.json",
    "content": "{\n  \"backups\": [\n    {\n      \"id\": 7622989,\n      \"name\": \"example.com 2014-11-14\",\n      \"distribution\": \"Ubuntu\",\n      \"slug\": null,\n      \"public\": false,\n      \"regions\": [\n        \"nyc3\"\n      ],\n      \"created_at\": \"2014-11-14T16:07:38Z\",\n      \"type\": \"snapshot\",\n      \"min_disk_size\": 20\n    }\n  ],\n  \"links\" : {\n      \"pages\" : {\n         \"last\" : \"https://api.digitalocean.com/v2/droplets/3067509/backups?page=2\",\n         \"next\" : \"https://api.digitalocean.com/v2/droplets/3067509/backups?page=2\"\n      }\n  },\n  \"meta\": {\n    \"total\": 2\n  }\n}"
  },
  {
    "path": "providers/digitalocean2/src/test/resources/backups-last.json",
    "content": "{\n  \"backups\": [\n    {\n      \"id\": 76229890,\n      \"name\": \"example.com 2014-11-14\",\n      \"distribution\": \"Ubuntu\",\n      \"slug\": null,\n      \"public\": false,\n      \"regions\": [\n        \"nyc3\"\n      ],\n      \"created_at\": \"2014-11-14T16:07:38Z\",\n      \"type\": \"snapshot\",\n      \"min_disk_size\": 20\n    }\n  ],\n  \"links\" : {\n      \"pages\" : {\n         \"first\" : \"https://api.digitalocean.com/v2/droplets/3067509/backups?page=1\",\n         \"prev\" : \"https://api.digitalocean.com/v2/droplets/3067509/backups?page=1\"\n      }\n  },\n  \"meta\": {\n    \"total\": 2\n  }\n}"
  },
  {
    "path": "providers/digitalocean2/src/test/resources/droplet-create-req.json",
    "content": "{\n    \"name\": \"digitalocean2-s-d5e\",\n    \"region\": \"sfo1\",\n    \"size\": \"512mb\",\n    \"image\": \"6374124\",\n    \"ssh_keys\": [\n        421192\n    ],\n    \"backups\": false,\n    \"ipv6\": false,\n    \"private_networking\": false\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/resources/droplet-create-res.json",
    "content": "{\n    \"droplet\": {\n        \"id\": 2987224,\n        \"name\": \"digitalocean2-s-d5e\",\n        \"memory\": 512,\n        \"vcpus\": 1,\n        \"disk\": 20,\n        \"locked\": true,\n        \"status\": \"new\",\n        \"kernel\": {\n            \"id\": 70,\n            \"name\": \"Ubuntu 10.04 x64 vmlinuz-2.6.32-41-server\",\n            \"version\": \"2.6.32-41-server\"\n        },\n        \"created_at\": \"2014-10-27T19:33:34Z\",\n        \"features\": [\n            \"virtio\"\n        ],\n        \"backup_ids\": [],\n        \"snapshot_ids\": [],\n        \"image\": {},\n        \"size_slug\": \"512mb\",\n        \"networks\": {},\n        \"region\": {}\n    },\n    \"links\": {\n        \"actions\": [\n            {\n                \"id\": 2512718872,\n                \"rel\": \"create\",\n                \"href\": \"https://api.digitalocean.com/v2/actions/2512718872\"\n            }\n        ]\n    }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/resources/droplet.json",
    "content": "{\n   \"droplet\" :\n      {\n         \"created_at\" : \"2015-05-25T15:50:48Z\",\n         \"region\" : {\n            \"name\" : \"New York 1\",\n            \"sizes\" : [\n               \"32gb\",\n               \"16gb\",\n               \"2gb\",\n               \"1gb\",\n               \"4gb\",\n               \"8gb\",\n               \"512mb\",\n               \"64gb\",\n               \"48gb\"\n            ],\n            \"slug\" : \"nyc1\",\n            \"features\" : [\n               \"virtio\",\n               \"backups\",\n               \"metadata\"\n            ],\n            \"available\" : true\n         },\n         \"id\" : 5425561,\n         \"disk\" : 20,\n         \"networks\" : {\n            \"v6\" : [],\n            \"v4\" : [\n               {\n                  \"type\" : \"public\",\n                  \"ip_address\" : \"162.243.167.46\",\n                  \"netmask\" : \"255.255.255.0\",\n                  \"gateway\" : \"162.243.167.1\"\n               }\n            ]\n         },\n         \"backup_ids\" : [],\n         \"image\" : {\n            \"slug\" : \"ubuntu-14-10-x32\",\n            \"public\" : true,\n            \"created_at\" : \"2015-01-08T18:41:22Z\",\n            \"distribution\" : \"Ubuntu\",\n            \"id\" : 9801951,\n            \"type\" : \"snapshot\",\n            \"regions\" : [\n               \"nyc1\",\n               \"ams1\",\n               \"sfo1\",\n               \"nyc2\",\n               \"ams2\",\n               \"sgp1\",\n               \"lon1\",\n               \"nyc3\",\n               \"ams3\",\n               \"fra1\"\n            ],\n            \"name\" : \"14.10 x32\",\n            \"min_disk_size\" : 20\n         },\n         \"vcpus\" : 1,\n         \"next_backup_window\" : {\n            \"end\" : \"2015-06-01T23:00:00Z\",\n            \"start\" : \"2015-06-01T00:00:00Z\"\n         },\n         \"locked\" : false,\n         \"snapshot_ids\" : [],\n         \"kernel\" : {\n            \"name\" : \"Ubuntu 14.10 x32 vmlinuz-3.16.0-28-generic\",\n            \"id\" : 2926,\n            \"version\" : \"3.16.0-28-generic\"\n         },\n         \"status\" : \"active\",\n         \"features\" : [\n            \"backups\",\n            \"virtio\"\n         ],\n         \"size\" : {\n            \"price_hourly\" : 0.00744,\n            \"slug\" : \"512mb\",\n            \"disk\" : 20,\n            \"available\" : true,\n            \"transfer\" : 1,\n            \"price_monthly\" : 5,\n            \"regions\" : [\n               \"nyc1\",\n               \"sgp1\",\n               \"ams1\",\n               \"sfo1\",\n               \"nyc2\",\n               \"lon1\",\n               \"nyc3\",\n               \"ams3\",\n               \"ams2\",\n               \"fra1\"\n            ],\n            \"memory\" : 512,\n            \"vcpus\" : 1\n         },\n         \"name\" : \"test1\",\n         \"size_slug\" : \"512mb\",\n         \"memory\" : 512\n    }\n}"
  },
  {
    "path": "providers/digitalocean2/src/test/resources/droplets-first.json",
    "content": "{\n   \"links\" : {\n      \"pages\" : {\n         \"next\" : \"https://api.digitalocean.com/v2/droplets/5425561?page=2&per_page=1\",\n         \"last\" : \"https://api.digitalocean.com/v2/droplets/5425561?page=2&per_page=1\"\n      }\n   },\n   \"meta\" : {\n      \"total\" : 2\n   },\n   \"droplets\" : [\n      {\n         \"created_at\" : \"2015-05-25T15:50:48Z\",\n         \"region\" : {\n            \"name\" : \"New York 1\",\n            \"sizes\" : [\n               \"32gb\",\n               \"16gb\",\n               \"2gb\",\n               \"1gb\",\n               \"4gb\",\n               \"8gb\",\n               \"512mb\",\n               \"64gb\",\n               \"48gb\"\n            ],\n            \"slug\" : \"nyc1\",\n            \"features\" : [\n               \"virtio\",\n               \"backups\",\n               \"metadata\"\n            ],\n            \"available\" : true\n         },\n         \"id\" : 5425561,\n         \"disk\" : 20,\n         \"networks\" : {\n            \"v6\" : [],\n            \"v4\" : [\n               {\n                  \"type\" : \"public\",\n                  \"ip_address\" : \"162.243.167.46\",\n                  \"netmask\" : \"255.255.255.0\",\n                  \"gateway\" : \"162.243.167.1\"\n               }\n            ]\n         },\n         \"backup_ids\" : [],\n         \"image\" : {\n            \"slug\" : \"ubuntu-14-10-x32\",\n            \"public\" : true,\n            \"created_at\" : \"2015-01-08T18:41:22Z\",\n            \"distribution\" : \"Ubuntu\",\n            \"id\" : 9801951,\n            \"type\" : \"snapshot\",\n            \"regions\" : [\n               \"nyc1\",\n               \"ams1\",\n               \"sfo1\",\n               \"nyc2\",\n               \"ams2\",\n               \"sgp1\",\n               \"lon1\",\n               \"nyc3\",\n               \"ams3\",\n               \"fra1\"\n            ],\n            \"name\" : \"14.10 x32\",\n            \"min_disk_size\" : 20\n         },\n         \"vcpus\" : 1,\n         \"next_backup_window\" : {\n            \"end\" : \"2015-06-01T23:00:00Z\",\n            \"start\" : \"2015-06-01T00:00:00Z\"\n         },\n         \"locked\" : false,\n         \"snapshot_ids\" : [],\n         \"kernel\" : {\n            \"name\" : \"Ubuntu 14.10 x32 vmlinuz-3.16.0-28-generic\",\n            \"id\" : 2926,\n            \"version\" : \"3.16.0-28-generic\"\n         },\n         \"status\" : \"active\",\n         \"features\" : [\n            \"backups\",\n            \"virtio\"\n         ],\n         \"size\" : {\n            \"price_hourly\" : 0.00744,\n            \"slug\" : \"512mb\",\n            \"disk\" : 20,\n            \"available\" : true,\n            \"transfer\" : 1,\n            \"price_monthly\" : 5,\n            \"regions\" : [\n               \"nyc1\",\n               \"sgp1\",\n               \"ams1\",\n               \"sfo1\",\n               \"nyc2\",\n               \"lon1\",\n               \"nyc3\",\n               \"ams3\",\n               \"ams2\",\n               \"fra1\"\n            ],\n            \"memory\" : 512,\n            \"vcpus\" : 1\n         },\n         \"name\" : \"test1\",\n         \"size_slug\" : \"512mb\",\n         \"memory\" : 512\n      }\n   ]\n}"
  },
  {
    "path": "providers/digitalocean2/src/test/resources/droplets-last.json",
    "content": "{\n   \"links\" : {\n      \"pages\" : {\n         \"first\" : \"https://api.digitalocean.com/v2/droplets/5425561?page=2&per_page=1\",\n         \"prev\" : \"https://api.digitalocean.com/v2/droplets/5425561?page=2&per_page=1\"\n      }\n   },\n   \"meta\" : {\n      \"total\" : 2\n   },\n   \"droplets\" : [\n      {\n         \"created_at\" : \"2015-05-25T15:50:48Z\",\n         \"region\" : {\n            \"name\" : \"New York 1\",\n            \"sizes\" : [\n               \"32gb\",\n               \"16gb\",\n               \"2gb\",\n               \"1gb\",\n               \"4gb\",\n               \"8gb\",\n               \"512mb\",\n               \"64gb\",\n               \"48gb\"\n            ],\n            \"slug\" : \"nyc1\",\n            \"features\" : [\n               \"virtio\",\n               \"backups\",\n               \"metadata\"\n            ],\n            \"available\" : true\n         },\n         \"id\" : 5425561,\n         \"disk\" : 20,\n         \"networks\" : {\n            \"v6\" : [],\n            \"v4\" : [\n               {\n                  \"type\" : \"public\",\n                  \"ip_address\" : \"162.243.167.46\",\n                  \"netmask\" : \"255.255.255.0\",\n                  \"gateway\" : \"162.243.167.1\"\n               }\n            ]\n         },\n         \"backup_ids\" : [],\n         \"image\" : {\n            \"slug\" : \"ubuntu-14-10-x32\",\n            \"public\" : true,\n            \"created_at\" : \"2015-01-08T18:41:22Z\",\n            \"distribution\" : \"Ubuntu\",\n            \"id\" : 9801951,\n            \"type\" : \"snapshot\",\n            \"regions\" : [\n               \"nyc1\",\n               \"ams1\",\n               \"sfo1\",\n               \"nyc2\",\n               \"ams2\",\n               \"sgp1\",\n               \"lon1\",\n               \"nyc3\",\n               \"ams3\",\n               \"fra1\"\n            ],\n            \"name\" : \"14.10 x32\",\n            \"min_disk_size\" : 20\n         },\n         \"vcpus\" : 1,\n         \"next_backup_window\" : {\n            \"end\" : \"2015-06-01T23:00:00Z\",\n            \"start\" : \"2015-06-01T00:00:00Z\"\n         },\n         \"locked\" : false,\n         \"snapshot_ids\" : [],\n         \"kernel\" : {\n            \"name\" : \"Ubuntu 14.10 x32 vmlinuz-3.16.0-28-generic\",\n            \"id\" : 2926,\n            \"version\" : \"3.16.0-28-generic\"\n         },\n         \"status\" : \"active\",\n         \"features\" : [\n            \"backups\",\n            \"virtio\"\n         ],\n         \"size\" : {\n            \"price_hourly\" : 0.00744,\n            \"slug\" : \"512mb\",\n            \"disk\" : 20,\n            \"available\" : true,\n            \"transfer\" : 1,\n            \"price_monthly\" : 5,\n            \"regions\" : [\n               \"nyc1\",\n               \"sgp1\",\n               \"ams1\",\n               \"sfo1\",\n               \"nyc2\",\n               \"lon1\",\n               \"nyc3\",\n               \"ams3\",\n               \"ams2\",\n               \"fra1\"\n            ],\n            \"memory\" : 512,\n            \"vcpus\" : 1\n         },\n         \"name\" : \"test1\",\n         \"size_slug\" : \"512mb\",\n         \"memory\" : 512\n      }\n   ]\n}"
  },
  {
    "path": "providers/digitalocean2/src/test/resources/image.json",
    "content": "{\n   \"image\" : {\n         \"type\" : \"snapshot\",\n         \"id\" : 11732785,\n         \"name\" : \"Maintenance Mode\",\n         \"min_disk_size\" : 20,\n         \"distribution\" : \"Debian\",\n         \"created_at\" : \"2015-05-05T21:21:25Z\",\n         \"regions\" : [\n            \"nyc1\",\n            \"ams1\",\n            \"sfo1\",\n            \"nyc2\",\n            \"ams2\",\n            \"sgp1\",\n            \"lon1\",\n            \"nyc3\",\n            \"ams3\",\n            \"fra1\"\n         ],\n         \"slug\" : null,\n         \"public\" : true\n    }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/resources/images-first.json",
    "content": "{\n   \"meta\" : {\n      \"total\" : 54\n   },\n   \"links\" : {\n      \"pages\" : {\n         \"next\" : \"https://api.digitalocean.com/v2/images?page=2&per_page=5&type=distribution\",\n         \"last\" : \"https://api.digitalocean.com/v2/images?page=11&per_page=5&type=distribution\"\n      }\n   },\n   \"images\" : [\n      {\n         \"type\" : \"snapshot\",\n         \"id\" : 11732785,\n         \"name\" : \"Maintenance Mode\",\n         \"min_disk_size\" : 20,\n         \"distribution\" : \"Debian\",\n         \"created_at\" : \"2015-05-05T21:21:25Z\",\n         \"regions\" : [\n            \"nyc1\",\n            \"ams1\",\n            \"sfo1\",\n            \"nyc2\",\n            \"ams2\",\n            \"sgp1\",\n            \"lon1\",\n            \"nyc3\",\n            \"ams3\",\n            \"fra1\"\n         ],\n         \"slug\" : null,\n         \"public\" : true\n      },\n      {\n         \"type\" : \"snapshot\",\n         \"id\" : 11833262,\n         \"distribution\" : \"CoreOS\",\n         \"created_at\" : \"2015-05-12T17:41:36Z\",\n         \"regions\" : [\n            \"nyc1\",\n            \"sfo1\",\n            \"ams2\",\n            \"sgp1\",\n            \"lon1\",\n            \"nyc3\",\n            \"ams3\",\n            \"fra1\"\n         ],\n         \"public\" : true,\n         \"slug\" : \"coreos-stable\",\n         \"name\" : \"647.0.0 (stable)\",\n         \"min_disk_size\" : 20\n      },\n      {\n         \"min_disk_size\" : 20,\n         \"name\" : \"668.3.0 (beta)\",\n         \"created_at\" : \"2015-05-18T18:14:12Z\",\n         \"public\" : true,\n         \"regions\" : [\n            \"nyc1\",\n            \"sfo1\",\n            \"ams2\",\n            \"sgp1\",\n            \"lon1\",\n            \"nyc3\",\n            \"ams3\",\n            \"fra1\"\n         ],\n         \"slug\" : \"coreos-beta\",\n         \"distribution\" : \"CoreOS\",\n         \"id\" : 11919888,\n         \"type\" : \"snapshot\"\n      },\n      {\n         \"type\" : \"snapshot\",\n         \"id\" : 11919908,\n         \"distribution\" : \"CoreOS\",\n         \"created_at\" : \"2015-05-18T18:20:08Z\",\n         \"public\" : true,\n         \"regions\" : [\n            \"nyc1\",\n            \"sfo1\",\n            \"ams2\",\n            \"sgp1\",\n            \"lon1\",\n            \"nyc3\",\n            \"ams3\",\n            \"fra1\"\n         ],\n         \"slug\" : \"coreos-alpha\",\n         \"name\" : \"681.0.0 (alpha)\",\n         \"min_disk_size\" : 20\n      },\n      {\n         \"min_disk_size\" : 30,\n         \"name\" : \"vum-easter-move\",\n         \"slug\" : null,\n         \"regions\" : [\n            \"ams1\"\n         ],\n         \"public\" : true,\n         \"created_at\" : \"2015-04-10T07:31:20Z\",\n         \"distribution\" : \"Debian\",\n         \"id\" : 11385199,\n         \"type\" : \"snapshot\"\n      }\n   ]\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/resources/images-last.json",
    "content": "{\n   \"meta\" : {\n      \"total\" : 54\n   },\n   \"links\" : {\n      \"pages\" : {\n         \"prev\" : \"https://api.digitalocean.com/v2/images?page=1&per_page=5&type=distribution\",\n         \"first\" : \"https://api.digitalocean.com/v2/images?page=1&per_page=5&type=distribution\"\n      }\n   },\n   \"images\" : [\n      {\n         \"distribution\" : \"Fedora\",\n         \"min_disk_size\" : 20,\n         \"id\" : 6370882,\n         \"regions\" : [\n            \"nyc1\",\n            \"ams1\",\n            \"sfo1\",\n            \"nyc2\",\n            \"ams2\",\n            \"sgp1\",\n            \"lon1\",\n            \"nyc3\",\n            \"ams3\",\n            \"fra1\"\n         ],\n         \"name\" : \"20 x64\",\n         \"type\" : \"snapshot\",\n         \"slug\" : \"fedora-20-x64\",\n         \"public\" : true,\n         \"created_at\" : \"2014-09-26T15:29:01Z\"\n      },\n      {\n         \"name\" : \"20 x32\",\n         \"type\" : \"snapshot\",\n         \"distribution\" : \"Fedora\",\n         \"regions\" : [\n            \"nyc1\",\n            \"ams1\",\n            \"sfo1\",\n            \"nyc2\",\n            \"ams2\",\n            \"sgp1\",\n            \"lon1\",\n            \"nyc3\",\n            \"ams3\",\n            \"fra1\"\n         ],\n         \"id\" : 6370885,\n         \"min_disk_size\" : 20,\n         \"created_at\" : \"2014-09-26T15:29:18Z\",\n         \"public\" : true,\n         \"slug\" : \"fedora-20-x32\"\n      },\n      {\n         \"created_at\" : \"2014-09-26T16:40:18Z\",\n         \"slug\" : \"centos-5-8-x64\",\n         \"public\" : true,\n         \"type\" : \"snapshot\",\n         \"name\" : \"5.10 x64\",\n         \"regions\" : [\n            \"nyc1\",\n            \"ams1\",\n            \"sfo1\",\n            \"nyc2\",\n            \"ams2\",\n            \"sgp1\",\n            \"lon1\",\n            \"nyc3\",\n            \"ams3\",\n            \"fra1\"\n         ],\n         \"min_disk_size\" : 20,\n         \"id\" : 6372321,\n         \"distribution\" : \"CentOS\"\n      },\n      {\n         \"public\" : true,\n         \"slug\" : \"centos-5-8-x32\",\n         \"created_at\" : \"2014-09-26T16:45:29Z\",\n         \"id\" : 6372425,\n         \"min_disk_size\" : 20,\n         \"regions\" : [\n            \"nyc1\",\n            \"ams1\",\n            \"sfo1\",\n            \"nyc2\",\n            \"ams2\",\n            \"sgp1\",\n            \"lon1\",\n            \"nyc3\",\n            \"ams3\",\n            \"fra1\"\n         ],\n         \"distribution\" : \"CentOS\",\n         \"type\" : \"snapshot\",\n         \"name\" : \"5.10 x32\"\n      },\n      {\n         \"created_at\" : \"2014-09-26T16:56:00Z\",\n         \"public\" : true,\n         \"slug\" : \"debian-6-0-x64\",\n         \"type\" : \"snapshot\",\n         \"name\" : \"6.0 x64\",\n         \"regions\" : [\n            \"nyc1\",\n            \"ams1\",\n            \"sfo1\",\n            \"nyc2\",\n            \"ams2\",\n            \"sgp1\",\n            \"lon1\",\n            \"nyc3\",\n            \"ams3\",\n            \"fra1\"\n         ],\n         \"min_disk_size\" : 20,\n         \"id\" : 6372581,\n         \"distribution\" : \"Debian\"\n      }\n   ]\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/resources/kernels-first.json",
    "content": "{\n   \"links\" : {\n      \"pages\" : {\n         \"next\" : \"https://api.digitalocean.com/v2/droplets/5425561/kernels?page=2\",\n         \"last\" : \"https://api.digitalocean.com/v2/droplets/5425561/kernels?page=2\"\n      }\n   },\n   \"meta\" : {\n      \"total\" : 10\n   },\n   \"kernels\" : [\n      {\n         \"id\" : 231,\n         \"version\" : \"3.8.0-25-generic\",\n         \"name\" : \"DO-recovery-static-fsck\"\n      },\n      {\n         \"name\" : \"Ubuntu 10.04 x32 vmlinuz-2.6.32-41-generic-pae\",\n         \"version\" : \"2.6.32-41-generic-pae\",\n         \"id\" : 61\n      },\n      {\n         \"name\" : \"Ubuntu 10.04 x32 vmlinuz-2.6.32-56-generic-pae\",\n         \"id\" : 946,\n         \"version\" : \"2.6.32-56-generic-pae\"\n      },\n      {\n         \"name\" : \"Ubuntu 10.04 x32 vmlinuz-2.6.32-57-generic-pae\",\n         \"id\" : 987,\n         \"version\" : \"2.6.32-57-generic-pae\"\n      },\n      {\n         \"name\" : \"Ubuntu 10.04 x32 vmlinuz-2.6.32-58-generic-pae\",\n         \"id\" : 1269,\n         \"version\" : \"2.6.32-58-generic-pae\"\n      }\n   ]\n}"
  },
  {
    "path": "providers/digitalocean2/src/test/resources/kernels-last.json",
    "content": "{\n   \"links\" : {\n      \"pages\" : {\n         \"first\" : \"https://api.digitalocean.com/v2/droplets/5425561/kernels?page=2\",\n         \"prev\" : \"https://api.digitalocean.com/v2/droplets/5425561/kernels?page=2\"\n      }\n   },\n   \"meta\" : {\n      \"total\" : 10\n   },\n   \"kernels\" : [\n      {\n         \"id\" : 2311,\n         \"version\" : \"3.8.0-25-generic\",\n         \"name\" : \"DO-recovery-static-fsck\"\n      },\n      {\n         \"name\" : \"Ubuntu 10.04 x32 vmlinuz-2.6.32-41-generic-pae\",\n         \"version\" : \"2.6.32-41-generic-pae\",\n         \"id\" : 6111\n      },\n      {\n         \"name\" : \"Ubuntu 10.04 x32 vmlinuz-2.6.32-56-generic-pae\",\n         \"id\" : 94611,\n         \"version\" : \"2.6.32-56-generic-pae\"\n      },\n      {\n         \"name\" : \"Ubuntu 10.04 x32 vmlinuz-2.6.32-57-generic-pae\",\n         \"id\" : 98711,\n         \"version\" : \"2.6.32-57-generic-pae\"\n      },\n      {\n         \"name\" : \"Ubuntu 10.04 x32 vmlinuz-2.6.32-58-generic-pae\",\n         \"id\" : 1269,\n         \"version\" : \"2.6.32-58-generic-pae\"\n      }\n   ]\n}"
  },
  {
    "path": "providers/digitalocean2/src/test/resources/key.json",
    "content": "{\n   \"ssh_key\" : {\n     \"id\" : 767051,\n     \"name\" : \"ubuntu-1204-64bit-338\",\n     \"public_key\" : \"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCIshoBsRRK73Kwq9zlKauwNWClpaR99TpAxjtP5DcL3EMCTCDepaNPMHhPYO1rogRyjZrc2nsJ1ImCbZ3eEGFjspyhIyPk1NbYkAFsoSV7eBtqy1V7ddZ8t1ZsDexigAA5GnXZSWL4O0oVyZpBTrkzhZ49lbWUq8ch3Hhulvml1BR4nTx92ZcYIFFr1S7NEtua9xhKvRvUcSmgL/0A8deOBgkc85y5ADcEIt+nrlrOtIOW/agX0VPXNFjRxYW7MCkRGoDObOYEaT/mj7PyKk0kimmemxAH5wd6aOI4C82TmHjQmXTwXZgpVlrsdbxomOGDDGNSy7HoQLI/xMRvEf+9\",\n     \"fingerprint\" : \"1a:cc:9b:88:c8:4f:b8:77:96:15:d2:0c:95:86:ff:90\"\n    }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/resources/keys-first.json",
    "content": "{\n   \"meta\" : {\n      \"total\" : 17\n   },\n   \"ssh_keys\" : [\n      {\n         \"id\" : 767051,\n         \"name\" : \"ubuntu-1204-64bit-338\",\n         \"public_key\" : \"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCIshoBsRRK73Kwq9zlKauwNWClpaR99TpAxjtP5DcL3EMCTCDepaNPMHhPYO1rogRyjZrc2nsJ1ImCbZ3eEGFjspyhIyPk1NbYkAFsoSV7eBtqy1V7ddZ8t1ZsDexigAA5GnXZSWL4O0oVyZpBTrkzhZ49lbWUq8ch3Hhulvml1BR4nTx92ZcYIFFr1S7NEtua9xhKvRvUcSmgL/0A8deOBgkc85y5ADcEIt+nrlrOtIOW/agX0VPXNFjRxYW7MCkRGoDObOYEaT/mj7PyKk0kimmemxAH5wd6aOI4C82TmHjQmXTwXZgpVlrsdbxomOGDDGNSy7HoQLI/xMRvEf+9\",\n         \"fingerprint\" : \"1a:cc:9b:88:c8:4f:b8:77:96:15:d2:0c:95:86:ff:90\"\n      },\n      {\n         \"id\" : 767067,\n         \"name\" : \"ubuntu-1204-64bit-ea4\",\n         \"public_key\" : \"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCdkjezVub0t+lSNSQYbO+Kcd/SoOJBCYgETqroI+ysHpPjRRNTYp3XSqSB0O3snnXM1GRfjPFatYFBUO9ajsb8cq0pzDPEIh3+cn+ZEoQ5WPg8OpaU6zVt2fPZNwqE2FCWEr2naH2yj2qV7Wzd1T9xYRfFdQ19YU1HuUhs16zvF6cO4BJH0YX2HLtZkxtOHonSbBx78/hBoV1NgSKlzlHVj9rhqmJO0fcEBeia4y/6G/65n8Z3hrM3zwyoN/eBKV7ngeJ70VU8tcP/QK9anB6hx4lOOSnWro2j3GKDwjSADL2vbOGl4OS6kM2y+6I04A6UAUkMu7KWCSr1Zf0zC45N\",\n         \"fingerprint\" : \"8f:81:51:d2:91:09:25:8f:c2:9c:b2:c3:6f:67:55:77\"\n      },\n      {\n         \"name\" : \"ubuntu-1204-64bit-jdk8-850\",\n         \"id\" : 767363,\n         \"public_key\" : \"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQD0zjvxYEyNYsVd7lfYXJxLON98OTgdMizD14XYCHwhVdJkS5ht9h+6dpiWbgatVgb/xyB63N2EeW+yZvQGlohWFytd1HvX7C8LFVtS/h4nrFJxtEYc2QXRl+WRRys6ekxYy6cwf/WV8nQPitUIPQru7vKR8bRpMPDBh+2Va/k7ApLd83AM9UYwXgCxDC7wlL/ttdJCV40buwPVvbOot97+qFPyg600/s6MGMX5448VifeBEEZG/qjzHj4SSGpQn+12O0dFLpYxOruzLLBpu2QxwvIqj1Nsm2ij6seMh0J8a5rQPl3ssPYrDCi8QGhL2NyzDSmT/9tYMLOlhBj7x3zN\",\n         \"fingerprint\" : \"1c:17:a2:c2:00:42:89:63:23:79:01:d7:b8:e6:a6:b4\"\n      },\n      {\n         \"name\" : \"ubuntu-1204-64bit-jdk8-ead\",\n         \"id\" : 767375,\n         \"public_key\" : \"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCTMLrMCDSPF3BBeDjzSIYtVi8ACkxrvG4VT58sI+XjpeE9c3KGekqXqeTKZFwLxRllgbox8j610ABvcdAstBBSooSYmuDjT2nFotiTcw+5iHUe4A8BHG3HSlqXfuPlBCZ9bE4MdDBTPXqaDjiuvUqWdjpUihZeX2W2OtznDXDMFtn846Df0hD2V7ixHqVVQRXgflSfIoajEY5MlVG/Iuh3cjPpoJZ/IN/FcQnHjNe1FdJM8fC7kF+yY8sEE+u10KlfR1Y9WTdJSIiz5QDdlR4RTPXYyb9wyctD/sxCJ3xAgfZOG7Ey8eZF0+0MSbxkUGQll/xLuaP2aA5owIfMkEoj\",\n         \"fingerprint\" : \"a1:4d:20:c8:25:ce:2f:fa:43:8d:21:6f:65:77:c9:c4\"\n      },\n      {\n         \"public_key\" : \"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCj9vCuDlTrQd+9WqlsQxWLg7VO2oVwq960CyW9C7rEro07wPGDdiOQornhyy7KiSL0mqYzFT5j0vTICSYeiGXIO/4SFPekz7vRN1yjO2GKaPokl/eYnbt1ABqB41jL0YX4ySwTm11O8A5yqWMouyxiGlSr13p61S2LTim5r5Z2C+4dKWHduloxnyCJJsh/56ZquS/ERgcrZusis9ybIP3aP+5DbXmyokGU83qGuNqSjZXaWc7MGFRTZzzzR9dQsbMvTgPwpyFXtSruIC+u7ca8oJ0b7+9WCAj2g/GXzbv/dsiJyJkEOtx6k1NN8n02PmL3o50vM1GGAjBFUN65JghD\",\n         \"name\" : \"ubuntu-1204-64bit-jdk8-ce2\",\n         \"id\" : 767390,\n         \"fingerprint\" : \"7f:bc:1c:af:e5:51:b6:1b:f0:bd:93:de:60:1a:e9:25\"\n      }\n   ],\n   \"links\" : {\n      \"pages\" : {\n         \"next\" : \"https://api.digitalocean.com/v2/account/keys?page=2&per_page=5\",\n         \"last\" : \"https://api.digitalocean.com/v2/account/keys?page=2&per_page=5\"\n      }\n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/resources/keys-last.json",
    "content": "{\n   \"meta\" : {\n      \"total\" : 7\n   },\n   \"ssh_keys\" : [\n      {\n         \"fingerprint\" : \"a1:df:a0:64:e4:36:10:6b:de:8d:e6:65:55:17:8f:31\",\n         \"public_key\" : \"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCHcVV1Rb5+/sCDF0eZ9Hw8vrHF+HYxptZRaNmnWsjzjeupeIiFgq6W1gRrDKB6pjA1t8R0b1xlcfb0361B5fRuwkeQTr2ALior6cipTgUUHT4UKcZMah7n09/YMPj2I7vzxjdX07PyB1z4OkL7FT3zBrsDTaR+ZngeFAVG59WmCj6vD2EqoZ2PeiEKETZOvQnZ3MEGiU5sYX9odIh5mjO5Jg1Q7oLjFzBbmMQ0oo/gkte8nBybHlD20iq1kzvmoSV4ECbTIa48yr8cgsX0d4M29YV9v2WCBfqaSRTRGVhfsalu9sgeSTHZ7F68g1wEkPXOzE3ZCUlZsKpskiYmCcTP\",\n         \"name\" : \"ubuntu-1204-64bit-jdk8-77a\",\n         \"id\" : 799690\n      },\n      {\n         \"name\" : \"ubuntu-1204-64bit-jdk8-a14\",\n         \"public_key\" : \"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCeU4rK0wlk8YOOAWd9GURgJzOlgNkLEarq/y9RMXKq1zUW9Jf5J4UuztZm6HsSpAbiBfwL/QYBsFEhfDUZiW0B5p6CL0cR93vgUhGVgoi+v5Nl3KDEgMDryja48CdmzkCB3KoX4aRGRkahx6chrFByM5laEyGJETnDl0s4VyxZH07FGgQYqdWj8jg99stIvZ8Ktzlq5RMXPYePEA03vzzc5JrTEtdhuiy/wjxY8piq1j40uch6JEfcEzfPdkWY7LZt5KlOtrYoVFVmu+Mp3QSknhZPyMMZW5GOEtcr1IGtOEBCL3gJWz0E/H4e4Itt+3L2bNpNfHJmISJRXsNanuyn\",\n         \"fingerprint\" : \"f3:34:8d:dc:26:31:90:2b:55:f0:d4:77:d4:17:1e:f2\",\n         \"id\" : 802469\n      }\n   ],\n   \"links\" : {\n      \"pages\" : {\n         \"first\" : \"https://api.digitalocean.com/v2/account/keys?page=1&per_page=5\",\n         \"prev\" : \"https://api.digitalocean.com/v2/account/keys?page=1&per_page=5\"\n      }\n   }\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/resources/logback-test.xml",
    "content": "<?xml version=\"1.0\"?>\n<configuration scan=\"false\">\n    <appender name=\"FILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds.log</file>\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n    <appender name=\"WIREFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds-wire.log</file>\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n    <appender name=\"COMPUTEFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/jclouds-compute.log</file>\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <logger name=\"org.jclouds\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"FILE\" />\n    </logger>\n    <logger name=\"jclouds.compute\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"COMPUTEFILE\" />\n    </logger>\n    <logger name=\"jclouds.wire\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n    <logger name=\"jclouds.headers\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n    \n    <root>\n        <level value=\"INFO\" />\n    </root>\n</configuration>"
  },
  {
    "path": "providers/digitalocean2/src/test/resources/power-cycle.json",
    "content": "{\n    \"action\": {\n         \"region\" : {\n            \"name\" : \"New York 1\",\n            \"available\" : true,\n            \"slug\" : \"nyc1\",\n            \"features\" : [\n               \"virtio\",\n               \"backups\",\n               \"metadata\"\n            ],\n            \"sizes\" : [\n               \"512mb\",\n               \"8gb\",\n               \"16gb\",\n               \"32gb\",\n               \"48gb\",\n               \"64gb\",\n               \"1gb\",\n               \"2gb\",\n               \"4gb\"\n            ]\n         },\n         \"started_at\" : \"2015-05-19T15:17:55Z\",\n         \"status\" : \"in-progress\",\n         \"resource_type\" : \"droplet\",\n         \"resource_id\" : 5347489,\n         \"region_slug\" : \"nyc1\",\n         \"id\" : 50900149,\n         \"completed_at\" : \"2015-05-19T15:18:01Z\",\n         \"type\" : \"power_cycle\"\n      }\n}"
  },
  {
    "path": "providers/digitalocean2/src/test/resources/power-off.json",
    "content": "{\n    \"action\": {\n         \"region\" : {\n            \"name\" : \"New York 1\",\n            \"available\" : true,\n            \"slug\" : \"nyc1\",\n            \"features\" : [\n               \"virtio\",\n               \"backups\",\n               \"metadata\"\n            ],\n            \"sizes\" : [\n               \"512mb\",\n               \"8gb\",\n               \"16gb\",\n               \"32gb\",\n               \"48gb\",\n               \"64gb\",\n               \"1gb\",\n               \"2gb\",\n               \"4gb\"\n            ]\n         },\n         \"started_at\" : \"2015-05-19T15:17:55Z\",\n         \"status\" : \"in-progress\",\n         \"resource_type\" : \"droplet\",\n         \"resource_id\" : 5347489,\n         \"region_slug\" : \"nyc1\",\n         \"id\" : 50900149,\n         \"completed_at\" : \"2015-05-19T15:18:01Z\",\n         \"type\" : \"power_off\"\n      }\n}"
  },
  {
    "path": "providers/digitalocean2/src/test/resources/power-on.json",
    "content": "{\n    \"action\": {\n         \"region\" : {\n            \"name\" : \"New York 1\",\n            \"available\" : true,\n            \"slug\" : \"nyc1\",\n            \"features\" : [\n               \"virtio\",\n               \"backups\",\n               \"metadata\"\n            ],\n            \"sizes\" : [\n               \"512mb\",\n               \"8gb\",\n               \"16gb\",\n               \"32gb\",\n               \"48gb\",\n               \"64gb\",\n               \"1gb\",\n               \"2gb\",\n               \"4gb\"\n            ]\n         },\n         \"started_at\" : \"2015-05-19T15:17:55Z\",\n         \"status\" : \"in-progress\",\n         \"resource_type\" : \"droplet\",\n         \"resource_id\" : 5347489,\n         \"region_slug\" : \"nyc1\",\n         \"id\" : 50900149,\n         \"completed_at\" : \"2015-05-19T15:18:01Z\",\n         \"type\" : \"power_on\"\n      }\n}"
  },
  {
    "path": "providers/digitalocean2/src/test/resources/reboot.json",
    "content": "{\n    \"action\": {\n         \"region\" : {\n            \"name\" : \"New York 1\",\n            \"available\" : true,\n            \"slug\" : \"nyc1\",\n            \"features\" : [\n               \"virtio\",\n               \"backups\",\n               \"metadata\"\n            ],\n            \"sizes\" : [\n               \"512mb\",\n               \"8gb\",\n               \"16gb\",\n               \"32gb\",\n               \"48gb\",\n               \"64gb\",\n               \"1gb\",\n               \"2gb\",\n               \"4gb\"\n            ]\n         },\n         \"started_at\" : \"2015-05-19T15:17:55Z\",\n         \"status\" : \"in-progress\",\n         \"resource_type\" : \"droplet\",\n         \"resource_id\" : 5347489,\n         \"region_slug\" : \"nyc1\",\n         \"id\" : 50900149,\n         \"completed_at\" : \"2015-05-19T15:18:01Z\",\n         \"type\" : \"reboot\"\n      }\n}"
  },
  {
    "path": "providers/digitalocean2/src/test/resources/regions-first.json",
    "content": "{\n   \"links\" : {\n      \"pages\" : {\n         \"next\" : \"https://api.digitalocean.com/v2/regions?page=2&per_page=5\",\n         \"last\" : \"https://api.digitalocean.com/v2/regions?page=2&per_page=5\"\n      }\n   },\n   \"meta\" : {\n      \"total\" : 10\n   },\n   \"regions\" : [\n      {\n         \"sizes\" : [\n            \"32gb\",\n            \"16gb\",\n            \"2gb\",\n            \"1gb\",\n            \"4gb\",\n            \"8gb\",\n            \"512mb\",\n            \"64gb\",\n            \"48gb\"\n         ],\n         \"name\" : \"New York 1\",\n         \"slug\" : \"nyc1\",\n         \"features\" : [\n            \"virtio\",\n            \"backups\",\n            \"metadata\"\n         ],\n         \"available\" : true\n      },\n      {\n         \"slug\" : \"ams1\",\n         \"name\" : \"Amsterdam 1\",\n         \"available\" : false,\n         \"features\" : [\n            \"virtio\",\n            \"backups\"\n         ],\n         \"sizes\" : []\n      },\n      {\n         \"sizes\" : [\n            \"32gb\",\n            \"16gb\",\n            \"2gb\",\n            \"1gb\",\n            \"4gb\",\n            \"8gb\",\n            \"512mb\",\n            \"64gb\",\n            \"48gb\"\n         ],\n         \"name\" : \"San Francisco 1\",\n         \"slug\" : \"sfo1\",\n         \"features\" : [\n            \"virtio\",\n            \"private_networking\",\n            \"backups\",\n            \"ipv6\",\n            \"metadata\"\n         ],\n         \"available\" : true\n      },\n      {\n         \"sizes\" : [\n            \"32gb\",\n            \"16gb\",\n            \"2gb\",\n            \"1gb\",\n            \"4gb\",\n            \"8gb\",\n            \"512mb\",\n            \"64gb\",\n            \"48gb\"\n         ],\n         \"available\" : true,\n         \"features\" : [\n            \"virtio\",\n            \"private_networking\",\n            \"backups\"\n         ],\n         \"name\" : \"New York 2\",\n         \"slug\" : \"nyc2\"\n      },\n      {\n         \"features\" : [\n            \"virtio\",\n            \"private_networking\",\n            \"backups\",\n            \"ipv6\",\n            \"metadata\"\n         ],\n         \"available\" : true,\n         \"slug\" : \"ams2\",\n         \"name\" : \"Amsterdam 2\",\n         \"sizes\" : [\n            \"32gb\",\n            \"16gb\",\n            \"2gb\",\n            \"1gb\",\n            \"4gb\",\n            \"8gb\",\n            \"512mb\",\n            \"64gb\",\n            \"48gb\"\n         ]\n      }\n   ]\n}"
  },
  {
    "path": "providers/digitalocean2/src/test/resources/regions-last.json",
    "content": "{\n   \"links\" : {\n      \"pages\" : {\n         \"first\" : \"https://api.digitalocean.com/v2/regions?page=1&per_page=5\",\n         \"prev\" : \"https://api.digitalocean.com/v2/regions?page=1&per_page=5\"\n      }\n   },\n   \"meta\" : {\n      \"total\" : 10\n   },\n   \"regions\" : [\n      {\n         \"available\" : true,\n         \"features\" : [\n            \"virtio\",\n            \"private_networking\",\n            \"backups\",\n            \"ipv6\",\n            \"metadata\"\n         ],\n         \"name\" : \"Singapore 1\",\n         \"sizes\" : [\n            \"32gb\",\n            \"16gb\",\n            \"2gb\",\n            \"1gb\",\n            \"4gb\",\n            \"8gb\",\n            \"512mb\",\n            \"64gb\",\n            \"48gb\"\n         ],\n         \"slug\" : \"sgp1\"\n      },\n      {\n         \"available\" : true,\n         \"features\" : [\n            \"virtio\",\n            \"private_networking\",\n            \"backups\",\n            \"ipv6\",\n            \"metadata\"\n         ],\n         \"name\" : \"London 1\",\n         \"sizes\" : [\n            \"32gb\",\n            \"16gb\",\n            \"2gb\",\n            \"1gb\",\n            \"4gb\",\n            \"8gb\",\n            \"512mb\",\n            \"64gb\",\n            \"48gb\"\n         ],\n         \"slug\" : \"lon1\"\n      },\n      {\n         \"sizes\" : [\n            \"32gb\",\n            \"16gb\",\n            \"2gb\",\n            \"1gb\",\n            \"4gb\",\n            \"8gb\",\n            \"512mb\",\n            \"64gb\",\n            \"48gb\"\n         ],\n         \"name\" : \"New York 3\",\n         \"features\" : [\n            \"virtio\",\n            \"private_networking\",\n            \"backups\",\n            \"ipv6\",\n            \"metadata\"\n         ],\n         \"available\" : true,\n         \"slug\" : \"nyc3\"\n      },\n      {\n         \"available\" : true,\n         \"features\" : [\n            \"virtio\",\n            \"private_networking\",\n            \"backups\",\n            \"ipv6\",\n            \"metadata\"\n         ],\n         \"name\" : \"Amsterdam 3\",\n         \"sizes\" : [\n            \"32gb\",\n            \"16gb\",\n            \"2gb\",\n            \"1gb\",\n            \"4gb\",\n            \"8gb\",\n            \"512mb\",\n            \"64gb\",\n            \"48gb\"\n         ],\n         \"slug\" : \"ams3\"\n      },\n      {\n         \"available\" : true,\n         \"features\" : [\n            \"virtio\",\n            \"private_networking\",\n            \"backups\",\n            \"ipv6\",\n            \"metadata\"\n         ],\n         \"name\" : \"Frankfurt 1\",\n         \"sizes\" : [\n            \"32gb\",\n            \"16gb\",\n            \"2gb\",\n            \"1gb\",\n            \"4gb\",\n            \"8gb\",\n            \"512mb\",\n            \"64gb\",\n            \"48gb\"\n         ],\n         \"slug\" : \"fra1\"\n      }\n   ]\n}"
  },
  {
    "path": "providers/digitalocean2/src/test/resources/shutdown.json",
    "content": "{\n    \"action\": {\n         \"region\" : {\n            \"name\" : \"New York 1\",\n            \"available\" : true,\n            \"slug\" : \"nyc1\",\n            \"features\" : [\n               \"virtio\",\n               \"backups\",\n               \"metadata\"\n            ],\n            \"sizes\" : [\n               \"512mb\",\n               \"8gb\",\n               \"16gb\",\n               \"32gb\",\n               \"48gb\",\n               \"64gb\",\n               \"1gb\",\n               \"2gb\",\n               \"4gb\"\n            ]\n         },\n         \"started_at\" : \"2015-05-19T15:17:55Z\",\n         \"status\" : \"in-progress\",\n         \"resource_type\" : \"droplet\",\n         \"resource_id\" : 5347489,\n         \"region_slug\" : \"nyc1\",\n         \"id\" : 50900149,\n         \"completed_at\" : \"2015-05-19T15:18:01Z\",\n         \"type\" : \"shutdown\"\n      }\n}"
  },
  {
    "path": "providers/digitalocean2/src/test/resources/sizes-first.json",
    "content": "{\n   \"links\" : {\n      \"pages\" : {\n         \"next\" : \"https://api.digitalocean.com/v2/sizes?page=2&per_page=5\",\n         \"last\" : \"https://api.digitalocean.com/v2/sizes?page=2&per_page=5\"\n      }\n   },\n   \"meta\" : {\n      \"total\" : 9\n   },\n   \"sizes\" : [\n      {\n         \"vcpus\" : 1,\n         \"disk\" : 20,\n         \"price_monthly\" : 5,\n         \"regions\" : [\n            \"nyc1\",\n            \"sgp1\",\n            \"ams1\",\n            \"sfo1\",\n            \"nyc2\",\n            \"lon1\",\n            \"nyc3\",\n            \"ams3\",\n            \"ams2\",\n            \"fra1\"\n         ],\n         \"price_hourly\" : 0.00744,\n         \"transfer\" : 1,\n         \"available\" : true,\n         \"slug\" : \"512mb\",\n         \"memory\" : 512\n      },\n      {\n         \"vcpus\" : 1,\n         \"disk\" : 30,\n         \"price_monthly\" : 10,\n         \"regions\" : [\n            \"nyc2\",\n            \"sgp1\",\n            \"ams1\",\n            \"sfo1\",\n            \"lon1\",\n            \"nyc3\",\n            \"ams3\",\n            \"nyc1\",\n            \"ams2\",\n            \"fra1\"\n         ],\n         \"price_hourly\" : 0.01488,\n         \"transfer\" : 2,\n         \"slug\" : \"1gb\",\n         \"available\" : true,\n         \"memory\" : 1024\n      },\n      {\n         \"price_hourly\" : 0.02976,\n         \"regions\" : [\n            \"nyc2\",\n            \"sfo1\",\n            \"ams1\",\n            \"sgp1\",\n            \"lon1\",\n            \"nyc3\",\n            \"ams3\",\n            \"nyc1\",\n            \"ams2\",\n            \"fra1\"\n         ],\n         \"transfer\" : 3,\n         \"available\" : true,\n         \"slug\" : \"2gb\",\n         \"memory\" : 2048,\n         \"vcpus\" : 2,\n         \"disk\" : 40,\n         \"price_monthly\" : 20\n      },\n      {\n         \"transfer\" : 4,\n         \"price_hourly\" : 0.05952,\n         \"regions\" : [\n            \"nyc2\",\n            \"ams1\",\n            \"sgp1\",\n            \"lon1\",\n            \"nyc3\",\n            \"ams3\",\n            \"nyc1\",\n            \"ams2\",\n            \"sfo1\",\n            \"fra1\"\n         ],\n         \"memory\" : 4096,\n         \"slug\" : \"4gb\",\n         \"available\" : true,\n         \"disk\" : 60,\n         \"vcpus\" : 2,\n         \"price_monthly\" : 40\n      },\n      {\n         \"available\" : true,\n         \"slug\" : \"8gb\",\n         \"memory\" : 8192,\n         \"regions\" : [\n            \"nyc2\",\n            \"sgp1\",\n            \"ams1\",\n            \"nyc1\",\n            \"lon1\",\n            \"nyc3\",\n            \"ams3\",\n            \"ams2\",\n            \"sfo1\",\n            \"fra1\"\n         ],\n         \"price_hourly\" : 0.11905,\n         \"transfer\" : 5,\n         \"price_monthly\" : 80,\n         \"vcpus\" : 4,\n         \"disk\" : 80\n      }\n   ]\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/resources/sizes-last.json",
    "content": "{\n   \"meta\" : {\n      \"total\" : 9\n   },\n   \"links\" : {\n      \"pages\" : {\n         \"prev\" : \"https://api.digitalocean.com/v2/sizes?page=1&per_page=5\",\n         \"first\" : \"https://api.digitalocean.com/v2/sizes?page=1&per_page=5\"\n      }\n   },\n   \"sizes\" : [\n      {\n         \"regions\" : [\n            \"sgp1\",\n            \"nyc1\",\n            \"nyc3\",\n            \"lon1\",\n            \"nyc2\",\n            \"ams1\",\n            \"ams3\",\n            \"ams2\",\n            \"sfo1\",\n            \"fra1\"\n         ],\n         \"transfer\" : 6,\n         \"price_monthly\" : 160,\n         \"available\" : true,\n         \"vcpus\" : 8,\n         \"disk\" : 160,\n         \"slug\" : \"16gb\",\n         \"memory\" : 16384,\n         \"price_hourly\" : 0.2381\n      },\n      {\n         \"price_hourly\" : 0.47619,\n         \"price_monthly\" : 320,\n         \"available\" : true,\n         \"transfer\" : 7,\n         \"regions\" : [\n            \"nyc2\",\n            \"sgp1\",\n            \"nyc1\",\n            \"lon1\",\n            \"ams3\",\n            \"nyc3\",\n            \"ams2\",\n            \"sfo1\",\n            \"fra1\"\n         ],\n         \"memory\" : 32768,\n         \"slug\" : \"32gb\",\n         \"disk\" : 320,\n         \"vcpus\" : 12\n      },\n      {\n         \"price_monthly\" : 480,\n         \"available\" : true,\n         \"transfer\" : 8,\n         \"regions\" : [\n            \"sgp1\",\n            \"nyc1\",\n            \"lon1\",\n            \"nyc2\",\n            \"ams3\",\n            \"nyc3\",\n            \"ams2\",\n            \"sfo1\",\n            \"fra1\"\n         ],\n         \"memory\" : 49152,\n         \"slug\" : \"48gb\",\n         \"disk\" : 480,\n         \"vcpus\" : 16,\n         \"price_hourly\" : 0.71429\n      },\n      {\n         \"price_hourly\" : 0.95238,\n         \"price_monthly\" : 640,\n         \"available\" : true,\n         \"transfer\" : 9,\n         \"regions\" : [\n            \"sgp1\",\n            \"nyc1\",\n            \"nyc2\",\n            \"lon1\",\n            \"ams3\",\n            \"nyc3\",\n            \"ams2\",\n            \"sfo1\",\n            \"fra1\"\n         ],\n         \"memory\" : 65536,\n         \"slug\" : \"64gb\",\n         \"disk\" : 640,\n         \"vcpus\" : 20\n      }\n   ]\n}\n"
  },
  {
    "path": "providers/digitalocean2/src/test/resources/snapshot.json",
    "content": "{\n    \"action\": {\n         \"region\" : {\n            \"name\" : \"New York 1\",\n            \"available\" : true,\n            \"slug\" : \"nyc1\",\n            \"features\" : [\n               \"virtio\",\n               \"backups\",\n               \"metadata\"\n            ],\n            \"sizes\" : [\n               \"512mb\",\n               \"8gb\",\n               \"16gb\",\n               \"32gb\",\n               \"48gb\",\n               \"64gb\",\n               \"1gb\",\n               \"2gb\",\n               \"4gb\"\n            ]\n         },\n         \"started_at\" : \"2015-05-19T15:17:55Z\",\n         \"status\" : \"in-progress\",\n         \"resource_type\" : \"droplet\",\n         \"resource_id\" : 5347489,\n         \"region_slug\" : \"nyc1\",\n         \"id\" : 50900149,\n         \"completed_at\" : \"2015-05-19T15:18:01Z\",\n         \"type\" : \"snapshot\"\n      }\n}"
  },
  {
    "path": "providers/digitalocean2/src/test/resources/snapshots-first.json",
    "content": "{\n  \"snapshots\": [\n    {\n      \"id\": 7938206,\n      \"name\": \"nginx-fresh\",\n      \"distribution\": \"Ubuntu\",\n      \"slug\": null,\n      \"public\": false,\n      \"regions\": [\n        \"nyc3\",\n        \"nyc3\"\n      ],\n      \"created_at\": \"2014-11-14T16:37:34Z\",\n      \"type\": \"snapshot\",\n      \"min_disk_size\": 20\n    }\n  ],\n  \"links\": {\n      \"pages\" : {\n         \"last\" : \"https://api.digitalocean.com/v2/droplets/3067509/snapshots?page=2\",\n         \"next\" : \"https://api.digitalocean.com/v2/droplets/3067509/snapshots?page=2\"\n      }\n  },\n  \"meta\": {\n    \"total\": 2\n  }\n}"
  },
  {
    "path": "providers/digitalocean2/src/test/resources/snapshots-last.json",
    "content": "{\n  \"snapshots\": [\n    {\n      \"id\": 7938206,\n      \"name\": \"nginx-fresh\",\n      \"distribution\": \"Ubuntu\",\n      \"slug\": null,\n      \"public\": false,\n      \"regions\": [\n        \"nyc3\",\n        \"nyc3\"\n      ],\n      \"created_at\": \"2014-11-14T16:37:34Z\",\n      \"type\": \"snapshot\",\n      \"min_disk_size\": 20\n    }\n  ],\n  \"links\": {\n      \"pages\" : {\n         \"first\" : \"https://api.digitalocean.com/v2/droplets/3067509/snapshots?page=1\",\n         \"prev\" : \"https://api.digitalocean.com/v2/droplets/3067509/snapshots?page=1\"\n      }\n  },\n  \"meta\": {\n    \"total\": 2\n  }\n}"
  },
  {
    "path": "providers/digitalocean2/src/test/resources/ssh-dsa.pub",
    "content": "ssh-dss AAAAB3NzaC1kc3MAAACBAK5uLwicCrFEpaVKBzkWxC7RQn+smg5ZQb5keh9RQKo8AszFTol5npgUAr0JWmqKIHv7nof0HndO86x9iIqNjq3vrz9CIVcFfZM7poKBJZ27Hv3v0fmSKfAc6eGdx8eM9UkZe1gzcLXK8UP2HaeY1Y4LlaHXS5tPi/dXooFVgiA7AAAAFQCQl6LZo/VYB9VgPEZzOmsmQevnswAAAIBCNKGsVP5eZ+IJklXheUyzyuL75i04OOtEGW6MO5TymKMwTZlU9r4ukuwxty+T9Ot2LqlNRnLSPQUjb0vplasZ8Ix45JOpRbuSvPovryn7rvS7//klu9hIkFAAQ/AZfGTw+696EjFBg4F5tN6MGMA6KrTQVLXeuYcZeRXwE5t5lwAAAIEAl2xYh098bozJUANQ82DiZznjHc5FW76Xm1apEqsZtVRFuh3V9nc7QNcBekhmHp5Z0sHthXCm1XqnFbkRCdFlX02NpgtNs7OcKpaJP47N8C+C/Yrf8qK/Wt3fExrL2ZLX5XD2tiotugSkwZJMW5Bv0mtjrNt0Q7P45rZjNNTag2c="
  },
  {
    "path": "providers/digitalocean2/src/test/resources/ssh-ecdsa.pub",
    "content": "ecdsa-sha2-nistp521 AAAAE2VjZHNhLXNoYTItbmlzdHA1MjEAAAAIbmlzdHA1MjEAAACFBACeO2+Ci8Aw76SDF1FJyrwAp2fUhNeIgkP7G2x0SvF/yvZarOkZbCg1MAav3JobuqYZEA4GbLnoT2UK9OBAenucTgHXhEX91mQaFWe3pKqroealb7Vc059za+h6b6IfzONNhyXGpCVYlh6tUdq8y1nhGjMzIsUrma+hA1+ERJGFfGDLgA==\n"
  },
  {
    "path": "providers/digitalocean2/src/test/resources/token.json",
    "content": ""
  },
  {
    "path": "providers/dynect/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.dynect.v3.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "providers/dynect/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.provider</groupId>\n  <artifactId>dynect</artifactId>\n  <name>jclouds dynect api</name>\n  <description>jclouds components for DynECT Managed DNS</description>\n\n  <properties>\n    <test.dynect.endpoint>https://api2.dynect.net/REST</test.dynect.endpoint>\n    <test.dynect.api-version>3.3.8</test.dynect.api-version>\n    <test.dynect.build-version />\n    <test.dynect.identity />\n    <test.dynect.credential />\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.squareup.okhttp3</groupId>\n      <artifactId>mockwebserver</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-slf4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>ch.qos.logback</groupId>\n      <artifactId>logback-classic</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n  \n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <!-- TODO: remove when multiple jobs/session are supported -->\n                  <threadCount>1</threadCount>\n                  <systemPropertyVariables>\n                    <test.dynect.endpoint>${test.dynect.endpoint}</test.dynect.endpoint>\n                    <test.dynect.api-version>${test.dynect.api-version}</test.dynect.api-version>\n                    <test.dynect.build-version>${test.dynect.build-version}</test.dynect.build-version>\n                    <test.dynect.identity>${test.dynect.identity}</test.dynect.identity>\n                    <test.dynect.credential>${test.dynect.credential}</test.dynect.credential>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/DynECTApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.io.Closeable;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.dynect.v3.domain.Job;\nimport org.jclouds.dynect.v3.features.GeoRegionGroupApi;\nimport org.jclouds.dynect.v3.features.GeoServiceApi;\nimport org.jclouds.dynect.v3.features.RecordApi;\nimport org.jclouds.dynect.v3.features.SessionApi;\nimport org.jclouds.dynect.v3.features.ZoneApi;\nimport org.jclouds.dynect.v3.filters.AlwaysAddContentType;\nimport org.jclouds.dynect.v3.filters.SessionManager;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.rest.annotations.Delegate;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.Headers;\nimport org.jclouds.rest.annotations.RequestFilters;\n\n/**\n * Provides access to DynECT Managed DNS through the API2 api\n * <p/>\n * \n * @see <a href=\"https://manage.dynect.net/help/docs/api2/rest/\" />\n */\npublic interface DynECTApi extends Closeable {\n   /**\n    * returns the current status of a job.\n    * \n    * @param jobId\n    *           The ID of the job\n    * @return null, if not found\n    */\n   @Named(\"GetJob\")\n   @GET\n   @Path(\"/Job/{jobId}\")\n   @RequestFilters({ AlwaysAddContentType.class, SessionManager.class })\n   @Headers(keys = \"API-Version\", values = \"{jclouds.api-version}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Consumes(APPLICATION_JSON)\n   @Nullable\n   Job getJob(@PathParam(\"jobId\") long jobId);\n\n   /**\n    * Provides access to Session features.\n    */\n   @Delegate\n   SessionApi getSessionApi();\n\n   /**\n    * Provides access to Zone features.\n    */\n   @Delegate\n   ZoneApi getZoneApi();\n\n   /**\n    * Provides access to Record features\n    */\n   @Delegate\n   RecordApi getRecordApiForZone(@PathParam(\"zone\") String zone);\n\n   /**\n    * Provides access to Geo features.\n    */\n   @Delegate\n   GeoServiceApi getGeoServiceApi();\n\n   /**\n    * Provides access to Geo region group features\n    */\n   @Delegate\n   GeoRegionGroupApi getGeoRegionGroupApiForService(@PathParam(\"serviceName\") String serviceName);\n}\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/DynECTApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.dynect.v3.config.DynECTParserModule;\nimport org.jclouds.dynect.v3.config.DynECTHttpApiModule;\nimport org.jclouds.rest.internal.BaseHttpApiMetadata;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n/**\n * Implementation of {@link ApiMetadata} for DynECT 1.0 API\n */\npublic class DynECTApiMetadata extends BaseHttpApiMetadata<DynECTApi> {\n   \n   @Override\n   public Builder toBuilder() {\n      return new Builder().fromApiMetadata(this);\n   }\n\n   public DynECTApiMetadata() {\n      this(new Builder());\n   }\n\n   protected DynECTApiMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = BaseHttpApiMetadata.defaultProperties();\n      return properties;\n   }\n\n   public static class Builder extends BaseHttpApiMetadata.Builder<DynECTApi, Builder> {\n\n      protected Builder() {\n          id(\"dynect\")\n         .name(\"DynECT API2\")\n         .identityName(\"${customer}:${userName}\")\n         .credentialName(\"${password}\")\n         .documentation(URI.create(\"https://manage.dynect.net/help/docs/api2/rest/\"))\n         .version(\"3.3.8\")\n         .defaultEndpoint(\"https://api2.dynect.net/REST\")\n         .defaultProperties(DynECTApiMetadata.defaultProperties())\n         .defaultModules(ImmutableSet.<Class<? extends Module>>builder()\n                                     .add(DynECTParserModule.class)\n                                     .add(DynECTHttpApiModule.class).build());\n      }\n      \n      @Override\n      public DynECTApiMetadata build() {\n         return new DynECTApiMetadata(this);\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/DynECTExceptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3;\n\n/**\n * Exceptions likely to be encountered when using {@link DynECTApi}\n */\npublic final class DynECTExceptions {\n   private DynECTExceptions() {\n      throw new AssertionError(\"intentionally not implemented\");\n   }\n\n   /**\n    * You must wait until another job is finished before attempting this command\n    * again\n    */\n   public static class JobStillRunningException extends IllegalStateException {\n      private static final long serialVersionUID = 1L;\n\n      public JobStillRunningException(String message, Throwable cause) {\n         super(message, cause);\n      }\n   }\n\n   /**\n    * The Zone or other resource already exists\n    */\n   public static class TargetExistsException extends IllegalStateException {\n      private static final long serialVersionUID = 1L;\n\n      public TargetExistsException(String message, Throwable cause) {\n         super(message, cause);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/DynECTFallbacks.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3;\n\nimport static com.google.common.base.Predicates.equalTo;\nimport static com.google.common.base.Throwables.propagate;\nimport static org.jclouds.http.HttpUtils.returnValueOnCodeOrNull;\n\nimport org.jclouds.Fallback;\n\npublic final class DynECTFallbacks {\n   private DynECTFallbacks() {\n   }\n\n   public static class FalseOn400 implements Fallback<Boolean> {\n      @Override\n      public Boolean createOrPropagate(Throwable t) throws Exception {\n         if (returnValueOnCodeOrNull(t, false, equalTo(400)) != null)\n            return false;\n         throw propagate(t);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/DynECTProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3;\n\nimport static org.jclouds.Constants.PROPERTY_MAX_REDIRECTS;\nimport static org.jclouds.Constants.PROPERTY_RETRY_DELAY_START;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\n\nimport com.google.auto.service.AutoService;\n\n/**\n * Implementation of {@link ProviderMetadata} for DynECT Managed DNS.\n */\n@AutoService(ProviderMetadata.class)\npublic class DynECTProviderMetadata extends BaseProviderMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromProviderMetadata(this);\n   }\n\n   public DynECTProviderMetadata() {\n      super(builder());\n   }\n\n   public DynECTProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = new Properties();\n      // job polling occurs via redirect loop and can take a while\n      properties.setProperty(PROPERTY_MAX_REDIRECTS, \"100\");\n      properties.setProperty(PROPERTY_RETRY_DELAY_START, \"200\");\n      return properties;\n   }\n\n   public static class Builder extends BaseProviderMetadata.Builder {\n\n      protected Builder() {\n         id(\"dynect\")\n         .name(\"DynECT Managed DNS\")\n         .apiMetadata(new DynECTApiMetadata())\n         .homepage(URI.create(\"http://dyn.com/dns/dynect-managed-dns/\"))\n         .console(URI.create(\"https://manage.dynect.net\"))\n         .iso3166Codes(\"US-CA\", \"US-VA\")\n         .endpoint(\"https://api2.dynect.net/REST\")\n         .defaultProperties(DynECTProviderMetadata.defaultProperties());\n      }\n\n      @Override\n      public DynECTProviderMetadata build() {\n         return new DynECTProviderMetadata(this);\n      }\n\n      @Override\n      public Builder fromProviderMetadata(ProviderMetadata in) {\n         super.fromProviderMetadata(in);\n         return this;\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/binders/CreateRecordBinder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.binders;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.http.Uris.uriBuilder;\n\nimport java.net.URI;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.dynect.v3.domain.CreateRecord;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.json.Json;\nimport org.jclouds.rest.Binder;\n\nimport com.google.common.collect.ImmutableMap;\n\npublic class CreateRecordBinder implements Binder {\n   private final Json json;\n\n   @Inject\n   CreateRecordBinder(Json json) {\n      this.json = checkNotNull(json, \"json\");\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object arg) {\n      CreateRecord<?> in = CreateRecord.class.cast(checkNotNull(arg, \"record to create\"));\n      URI path = uriBuilder(request.getEndpoint())\n                  .build(ImmutableMap.<String, Object> builder()\n                                     .put(\"type\", in.getType())\n                                     .put(\"fqdn\", in.getFQDN()).build());\n      return (R) request.toBuilder()\n                        .endpoint(path)\n                        .payload(json.toJson(ImmutableMap.of(\"rdata\", in.getRData(), \"ttl\", in.getTTL()))).build();\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/binders/RecordIdBinder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.binders;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.http.Uris.uriBuilder;\n\nimport java.net.URI;\n\nimport org.jclouds.dynect.v3.domain.RecordId;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\nimport com.google.common.collect.ImmutableMap;\n\npublic class RecordIdBinder implements Binder {\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object recordId) {\n      RecordId valueToAppend = RecordId.class.cast(checkNotNull(recordId, \"recordId\"));\n      URI path = uriBuilder(request.getEndpoint()).appendPath(\"/{type}Record/{zone}/{fqdn}/{id}\").build(\n            ImmutableMap.<String, Object> builder()\n                        .put(\"type\", valueToAppend.getType())\n                        .put(\"zone\", valueToAppend.getZone())\n                        .put(\"fqdn\", valueToAppend.getFQDN())\n                        .put(\"id\", valueToAppend.getId()).build());\n      return (R) request.toBuilder().endpoint(path).build();\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/config/DynECTHttpApiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.config;\n\nimport static org.jclouds.Constants.PROPERTY_IDEMPOTENT_METHODS;\nimport static org.jclouds.Constants.PROPERTY_OUTPUT_SOCKET_BUFFER_SIZE;\nimport static org.jclouds.Constants.PROPERTY_USER_AGENT;\nimport static org.jclouds.http.HttpUtils.closeClientButKeepContentStream;\nimport static org.jclouds.rest.config.BinderUtils.bindHttpApi;\n\nimport java.io.IOException;\nimport java.net.HttpURLConnection;\nimport java.net.Proxy;\nimport java.net.URI;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\nimport javax.net.ssl.HostnameVerifier;\nimport javax.net.ssl.SSLContext;\n\nimport org.jclouds.concurrent.SingleThreaded;\nimport org.jclouds.dynect.v3.DynECTApi;\nimport org.jclouds.dynect.v3.features.SessionApi;\nimport org.jclouds.dynect.v3.filters.SessionManager;\nimport org.jclouds.dynect.v3.handlers.DynECTErrorHandler;\nimport org.jclouds.dynect.v3.handlers.GetJobRedirectionRetryHandler;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpRetryHandler;\nimport org.jclouds.http.HttpUtils;\nimport org.jclouds.http.IOExceptionRetryHandler;\nimport org.jclouds.http.annotation.ClientError;\nimport org.jclouds.http.annotation.Redirection;\nimport org.jclouds.http.annotation.ServerError;\nimport org.jclouds.http.handlers.DelegatingErrorHandler;\nimport org.jclouds.http.handlers.DelegatingRetryHandler;\nimport org.jclouds.http.handlers.RedirectionRetryHandler;\nimport org.jclouds.http.internal.HttpWire;\nimport org.jclouds.http.internal.JavaUrlHttpCommandExecutorService;\nimport org.jclouds.io.ContentMetadataCodec;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.config.HttpApiModule;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\n\n/**\n * Configures the DynECT connection.\n */\n@ConfiguresHttpApi\n// only one job at a time or error \"This session already has a job running\"\n@SingleThreaded\npublic class DynECTHttpApiModule extends HttpApiModule<DynECTApi> {\n\n   public DynECTHttpApiModule() {\n   }\n\n   @Override\n   protected void bindErrorHandlers() {\n      bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(DynECTErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(DynECTErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(DynECTErrorHandler.class);\n   }\n\n   @Override\n   protected void bindRetryHandlers() {\n      bind(HttpRetryHandler.class).annotatedWith(ClientError.class).to(SessionManager.class);\n   }\n\n   @Override\n   protected void configure() {\n      // binding explicitly ensures singleton despite multiple linked bindings\n      bind(SessionManager.class);\n      bind(RedirectionRetryHandler.class).to(GetJobRedirectionRetryHandler.class);\n      super.configure();\n      // for authentication filters\n      bindHttpApi(binder(), SessionApi.class);\n      bind(JavaUrlHttpCommandExecutorService.class).to(SillyRabbit200sAreForSuccess.class);\n   }\n\n   // dynect returns the following as a 200.\n   // {\"status\": \"failure\", \"data\": {}, \"job_id\": 274509427, \"msgs\":\n   // [{\"INFO\": \"token: This session already has a job running\", \"SOURCE\":\n   // \"API-B\", \"ERR_CD\": \"OPERATION_FAILED\", \"LVL\": \"ERROR\"}]}\n   @Singleton\n   private static class SillyRabbit200sAreForSuccess extends JavaUrlHttpCommandExecutorService {\n\n      @Inject\n      private SillyRabbit200sAreForSuccess(HttpUtils utils, ContentMetadataCodec contentMetadataCodec,\n            DelegatingRetryHandler retryHandler, IOExceptionRetryHandler ioRetryHandler,\n            DelegatingErrorHandler errorHandler, HttpWire wire, @Named(\"untrusted\") HostnameVerifier verifier,\n            @Named(\"untrusted\") Supplier<SSLContext> untrustedSSLContextProvider, Function<URI, Proxy> proxyForURI,\n            @Named(PROPERTY_IDEMPOTENT_METHODS) String idempotentMethods,\n            @Named(PROPERTY_OUTPUT_SOCKET_BUFFER_SIZE) int outputSocketBufferSize,\n            @Named(PROPERTY_USER_AGENT) String userAgent)\n            throws SecurityException, NoSuchFieldException {\n         super(utils, contentMetadataCodec, retryHandler, ioRetryHandler, errorHandler, wire, verifier,\n               untrustedSSLContextProvider, proxyForURI, idempotentMethods, outputSocketBufferSize, userAgent);\n      }\n\n      /**\n       * synchronized to prevent multiple callers from overlapping requests on the same session\n       */\n      @Override\n      protected synchronized HttpResponse invoke(HttpURLConnection connection) throws IOException, InterruptedException {\n         HttpResponse response = super.invoke(connection);\n         if (response.getStatusCode() == 200) {\n            byte[] data = closeClientButKeepContentStream(response);\n            String message = data != null ? new String(data, Charsets.UTF_8) : null;\n            if (message != null && !message.startsWith(\"{\\\"status\\\": \\\"success\\\"\")) {\n               response = response.toBuilder().statusCode(400).build();\n            }\n         }\n         return response;\n      }\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/config/DynECTParserModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.config;\n\nimport java.lang.reflect.Type;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.dynect.v3.domain.GeoService;\nimport org.jclouds.dynect.v3.domain.Node;\nimport org.jclouds.dynect.v3.domain.RecordSet;\nimport org.jclouds.dynect.v3.domain.RecordSet.Value;\nimport org.jclouds.dynect.v3.domain.RecordSet.Value.Builder;\nimport org.jclouds.dynect.v3.domain.GeoRegionGroup;\nimport org.jclouds.dynect.v3.domain.SessionCredentials;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.gson.JsonDeserializationContext;\nimport com.google.gson.JsonDeserializer;\nimport com.google.gson.JsonElement;\nimport com.google.gson.JsonObject;\nimport com.google.gson.JsonParseException;\nimport com.google.gson.JsonSerializationContext;\nimport com.google.gson.JsonSerializer;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Provides;\n\npublic class DynECTParserModule extends AbstractModule {\n\n   @Override\n   protected void configure() {\n   }\n\n   @Provides\n   @Singleton\n   public final Map<Type, Object> provideCustomAdapterBindings() {\n      return new ImmutableMap.Builder<Type, Object>()\n            .put(SessionCredentials.class, new SessionCredentialsTypeAdapter())\n            .put(GeoRegionGroup.class, new GeoRegionGroupTypeAdapter())\n            .put(GeoService.class, new GeoServiceTypeAdapter()).build();\n   }\n\n   private static class SessionCredentialsTypeAdapter implements JsonSerializer<SessionCredentials> {\n      public JsonElement serialize(SessionCredentials src, Type typeOfSrc, JsonSerializationContext context) {\n         JsonObject metadataObject = new JsonObject();\n         metadataObject.addProperty(\"customer_name\", src.getCustomerName());\n         metadataObject.addProperty(\"user_name\", src.getUserName());\n         metadataObject.addProperty(\"password\", src.getPassword());\n         return metadataObject;\n      }\n   }\n\n   private static class GeoRegionGroupTypeAdapter implements JsonDeserializer<GeoRegionGroup> {\n\n      @Override\n      public GeoRegionGroup deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)\n            throws JsonParseException {\n         CreepyGeoRegionGroup creepyGeoRegionGroup = context.deserialize(json, CreepyGeoRegionGroup.class);\n         GeoRegionGroup.Builder builder = GeoRegionGroup.builder();\n         builder.name(creepyGeoRegionGroup.name);\n         builder.serviceName(creepyGeoRegionGroup.service_name);\n         builder.countries(creepyGeoRegionGroup.countries);\n         ImmutableList.Builder<RecordSet> rsets = ImmutableList.builder();\n         for (Entry<String, List<Map<String, Object>>> entry : creepyGeoRegionGroup.rdata.entrySet()) {\n            if (entry.getValue().isEmpty())\n               continue;\n            // ex. spf_rdata -> SPF\n            String type = entry.getKey().substring(0, entry.getKey().indexOf('_')).toUpperCase();\n            // ex. dhcid_ttl\n            int ttl = creepyGeoRegionGroup.ttl.get(type.toLowerCase() + \"_ttl\");\n            RecordSet.Builder rset = RecordSet.builder();\n            rset.type(type);\n            rset.ttl(ttl);\n\n            // weight is only present for a couple record types\n            List<Integer> weights = creepyGeoRegionGroup.weight.get(type.toLowerCase() + \"_weight\");\n            if (weights == null)\n               weights = ImmutableList.of();\n\n            List<String> labels = creepyGeoRegionGroup.label.get(type.toLowerCase() + \"_label\");\n            for (int i = 0; i < entry.getValue().size(); i++) {\n               Builder elementBuilder = Value.builder().rdata(entry.getValue().get(i));\n               // chance of index out of bounds\n               if (i < labels.size())\n                  elementBuilder.label(labels.get(i));\n               if (i < weights.size())\n                  elementBuilder.weight(weights.get(i));\n               rset.add(elementBuilder.build());\n            }\n            rsets.add(rset.build());\n         }\n         builder.recordSets(rsets.build());\n         return builder.build();\n      }\n   }\n\n   private static class CreepyGeoRegionGroup {\n      String name;\n      // aaaa_weight\n      Map<String, List<Integer>> weight;\n      List<String> countries;\n      String service_name;\n      // spf_rdata\n      Map<String, List<Map<String, Object>>> rdata;\n      // a_label\n      Map<String, List<String>> label;\n      // dhcid_ttl\n      Map<String, Integer> ttl;\n   }\n   \n\n   private static class GeoServiceTypeAdapter implements JsonDeserializer<GeoService> {\n\n      @Override\n      public GeoService deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)\n            throws JsonParseException {\n         CreepyGeoService creepyGeoService = context.deserialize(json, CreepyGeoService.class);\n         GeoService.Builder builder = GeoService.builder();\n         builder.name(creepyGeoService.name);\n         builder.active(\"Y\".equals(creepyGeoService.active));\n         builder.ttl(creepyGeoService.ttl);\n         builder.nodes(creepyGeoService.nodes);\n         builder.groups(creepyGeoService.groups);\n         return builder.build();\n      }\n   }\n\n   private static class CreepyGeoService {\n      String name;\n      String active;  // creepy part\n      int ttl;\n      List<Node> nodes;\n      List<GeoRegionGroup> groups;\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/domain/CreatePrimaryZone.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.dynect.v3.domain.Zone.SerialStyle;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Objects;\n\npublic final class CreatePrimaryZone {\n   // persisted via path param\n   private final transient String fqdn;\n   @Named(\"rname\")\n   private final String contact;\n   @Named(\"serial_style\")\n   private final SerialStyle serialStyle;\n   @Named(\"ttl\")\n   private final int defaultTTL;\n\n   private CreatePrimaryZone(String fqdn, String contact, SerialStyle serialStyle, int defaultTTL) {\n      this.fqdn = checkNotNull(fqdn, \"fqdn\");\n      this.contact = checkNotNull(contact, \"contact for %s\", fqdn);\n      this.defaultTTL = defaultTTL;\n      this.serialStyle = checkNotNull(serialStyle, \"serialStyle for %s\", fqdn);\n   }\n\n   /**\n    * The fqdn of the zone to create\n    */\n   public String getFQDN() {\n      return fqdn;\n   }\n\n   /**\n    * The administrative contact or {@code rname} for the {@code SOA} record.\n    */\n   public String getContact() {\n      return contact;\n   }\n\n   /**\n    * Default TTL (in seconds) for records in the zone.  Defaults to 3600.\n    */\n   public int getDefaultTTL() {\n      return defaultTTL;\n   }\n\n   /**\n    * The style of the zone's serial. Defaults to {@link SerialStyle#INCREMENT}.\n    */\n   public SerialStyle getSerialStyle() {\n      return serialStyle;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(fqdn, contact);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      CreatePrimaryZone that = CreatePrimaryZone.class.cast(obj);\n      return equal(this.fqdn, that.fqdn) && equal(this.contact, that.contact);\n   }\n\n   @Override\n   public String toString() {\n      return toStringHelper(this).omitNullValues().add(\"fqdn\", fqdn).add(\"contact\", contact)\n            .add(\"defaultTTL\", defaultTTL).add(\"serialStyle\", serialStyle).toString();\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().from(this);\n   }\n\n   public static final class Builder {\n      private String fqdn;\n      private String contact;\n      private int defaultTTL = 3600;\n      private SerialStyle serialStyle = SerialStyle.INCREMENT;\n\n      /**\n       * @see CreatePrimaryZone#getFQDN()\n       */\n      public Builder fqdn(String fqdn) {\n         this.fqdn = fqdn;\n         return this;\n      }\n\n      /**\n       * @see CreatePrimaryZone#getContact()\n       */\n      public Builder contact(String contact) {\n         this.contact = contact;\n         return this;\n      }\n\n      /**\n       * @see CreatePrimaryZone#getDefaultTTL()\n       */\n      public Builder defaultTTL(int defaultTTL) {\n         this.defaultTTL = defaultTTL;\n         return this;\n      }\n\n      /**\n       * @see CreatePrimaryZone#getSerialStyle()\n       */\n      public Builder serialStyle(SerialStyle serialStyle) {\n         this.serialStyle = serialStyle;\n         return this;\n      }\n\n      public CreatePrimaryZone build() {\n         return new CreatePrimaryZone(fqdn, contact, serialStyle, defaultTTL);\n      }\n\n      public Builder from(CreatePrimaryZone in) {\n         return this.fqdn(in.fqdn).contact(in.contact).serialStyle(in.serialStyle).defaultTTL(in.defaultTTL);\n      }\n   }\n\n   public static final class ToFQDN implements Function<Object, String> {\n      public String apply(Object in) {\n         return CreatePrimaryZone.class.cast(in).getFQDN();\n      }\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/domain/CreateRecord.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\n\nimport com.google.common.base.Objects;\n\npublic class CreateRecord<D extends Map<String, Object>> {\n\n   private final String fqdn;\n   private final String type;\n   private final int ttl;\n   private final D rdata;\n\n   private CreateRecord(String fqdn, String type, int ttl, D rdata) {\n      this.fqdn = checkNotNull(fqdn, \"fqdn\");\n      this.type = checkNotNull(type, \"type of %s\", fqdn);\n      checkArgument(ttl >= 0, \"ttl of %s must be unsigned\", fqdn);\n      this.ttl = ttl;\n      this.rdata = checkNotNull(rdata, \"rdata of %s\", fqdn);\n   }\n\n   /**\n    * @see RecordId#getFQDN()\n    */\n   public String getFQDN() {\n      return fqdn;\n   }\n\n   /**\n    * @see RecordId#getType()\n    */\n   public String getType() {\n      return type;\n   }\n\n   /**\n    * zero for zone default\n    * \n    * @see Record#getTTL()\n    */\n   public int getTTL() {\n      return ttl;\n   }\n\n   /**\n    * @see Record#getRData()\n    */\n   public D getRData() {\n      return rdata;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || !(obj instanceof CreateRecord))\n         return false;\n      CreateRecord<?> that = CreateRecord.class.cast(obj);\n      return equal(this.fqdn, that.fqdn) && equal(this.type, that.type) && equal(this.ttl, that.ttl)\n            && equal(this.rdata, that.rdata);\n   }\n\n   @Override\n   public String toString() {\n      return toStringHelper(this).add(\"fqdn\", fqdn).add(\"type\", type).add(\"ttl\", ttl).add(\"rdata\", rdata).toString();\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(fqdn, type, ttl, rdata);\n   }\n\n   public static <D extends Map<String, Object>> Builder<D> builder() {\n      return new Builder<D>();\n   }\n\n   public Builder<D> toBuilder() {\n      return new Builder<D>().from(this);\n   }\n\n   public static class Builder<D extends Map<String, Object>> {\n      protected String fqdn;\n      protected String type;\n      // default of zone is implied when ttl is set to zero\n      protected int ttl = 0;\n      protected D rdata;\n\n      /**\n       * @see CreateRecord#getFQDN()\n       */\n      public Builder<D> fqdn(String fqdn) {\n         this.fqdn = fqdn;\n         return this;\n      }\n\n      /**\n       * @see CreateRecord#getType()\n       */\n      public Builder<D> type(String type) {\n         this.type = type;\n         return this;\n      }\n\n      /**\n       * @see CreateRecord#getTTL()\n       */\n      public Builder<D> ttl(int ttl) {\n         this.ttl = ttl;\n         return this;\n      }\n\n      /**\n       * @see CreateRecord#getRData()\n       */\n      public Builder<D> rdata(D rdata) {\n         this.rdata = rdata;\n         return this;\n      }\n\n      public CreateRecord<D> build() {\n         return new CreateRecord<D>(fqdn, type, ttl, rdata);\n      }\n\n      public <Y extends D> Builder<D> from(CreateRecord<Y> in) {\n         return fqdn(in.fqdn).type(in.type).ttl(in.ttl).rdata(in.rdata);\n      }\n\n      public <Y extends D> Builder<D> from(Record<Y> in) {\n         return fqdn(in.getFQDN()).type(in.getType()).ttl(in.getTTL()).rdata(in.getRData());\n      }\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/domain/GeoRegionGroup.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.List;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableList;\n\npublic class GeoRegionGroup {\n\n   private final Optional<String> serviceName;\n   private final String name;\n   private final List<String> countries;\n   private final List<RecordSet> recordSets;\n\n   private GeoRegionGroup(Optional<String> serviceName, String name, List<String> countries, List<RecordSet> recordSets) {\n      this.serviceName = checkNotNull(serviceName, \"serviceName\");\n      this.name = checkNotNull(name, \"name\");\n      this.countries = checkNotNull(countries, \"countries of %s/%s\", serviceName, name);\n      this.recordSets = checkNotNull(recordSets, \"recordSets of %s\", name);\n   }\n\n   /**\n    * Name of the Geo Service. Absent, if a member of {@link GeoService}\n    */\n   public Optional<String> getServiceName() {\n      return serviceName;\n   }\n\n   /**\n    * Name of the Region Group\n    */\n   public String getName() {\n      return name;\n   }\n\n   /**\n    * A list of ISO-3166 two letter codes to represent the names of countries\n    * and their subdivisions or one of the predefined groups.\n    */\n   public List<String> getCountries() {\n      return countries;\n   }\n\n   /**\n    * record sets assigned to this region group.\n    */\n   public List<RecordSet> getRecordSets() {\n      return recordSets;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(serviceName, name, countries, recordSets);\n   }\n\n   /**\n    * permits equals comparisons with subtypes\n    */\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || !(obj instanceof GeoRegionGroup))\n         return false;\n      GeoRegionGroup that = GeoRegionGroup.class.cast(obj);\n      return equal(this.serviceName, that.serviceName) && equal(this.name, that.name)\n            && equal(this.countries, that.countries) && equal(this.recordSets, that.recordSets);\n   }\n\n   @Override\n   public String toString() {\n      return toStringHelper(this).add(\"serviceName\", serviceName.orNull()).add(\"name\", name)\n            .add(\"countries\", countries).add(\"recordSets\", recordSets).toString();\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().from(this);\n   }\n\n   public static class Builder {\n\n      private Optional<String> serviceName = Optional.absent();\n      private String name;\n      private ImmutableList.Builder<String> countries = ImmutableList.builder();\n      private ImmutableList.Builder<RecordSet> recordSets = ImmutableList.builder();\n\n      /**\n       * @see GeoRegionGroup#getServiceName()\n       */\n      public Builder serviceName(String serviceName) {\n         this.serviceName = Optional.fromNullable(serviceName);\n         return this;\n      }\n\n      /**\n       * @see GeoRegionGroup#getName()\n       */\n      public Builder name(String name) {\n         this.name = name;\n         return this;\n      }\n\n      /**\n       * @see GeoRegionGroup#getCountries()\n       */\n      public Builder addCountry(String country) {\n         this.countries.add(country);\n         return this;\n      }\n\n      /**\n       * replaces current record sets\n       * \n       * @see GeoRegionGroup#getCountries()\n       */\n      public Builder countries(Iterable<String> countries) {\n         this.countries = ImmutableList.<String> builder().addAll(countries);\n         return this;\n      }\n\n      /**\n       * @see GeoRegionGroup#getCountries()\n       */\n      public Builder addAllCountries(Iterable<String> countries) {\n         this.countries.addAll(countries);\n         return this;\n      }\n\n      /**\n       * @see GeoRegionGroup#getRecordSets()\n       */\n      public Builder addRecordSet(RecordSet recordSet) {\n         this.recordSets.add(recordSet);\n         return this;\n      }\n\n      /**\n       * replaces current record sets\n       * \n       * @see GeoRegionGroup#getRecordSets()\n       */\n      public Builder recordSets(Iterable<RecordSet> recordSets) {\n         this.recordSets = ImmutableList.<RecordSet> builder().addAll(recordSets);\n         return this;\n      }\n\n      /**\n       * @see GeoRegionGroup#getRecordSets()\n       */\n      public Builder addAllRecordSets(Iterable<RecordSet> recordSets) {\n         this.recordSets.addAll(recordSets);\n         return this;\n      }\n\n      public GeoRegionGroup build() {\n         return new GeoRegionGroup(serviceName, name, countries.build(), recordSets.build());\n      }\n\n      public Builder from(GeoRegionGroup in) {\n         return serviceName(in.serviceName.orNull()).name(in.name).countries(in.countries).recordSets(in.recordSets);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/domain/GeoService.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.List;\n\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ImmutableList;\n\npublic class GeoService {\n\n   private final String name;\n   private final boolean active;\n   private final int ttl;\n   private final List<Node> nodes;\n   private final List<GeoRegionGroup> groups;\n\n   private GeoService(String name, boolean active, int ttl, List<Node> nodes, List<GeoRegionGroup> groups) {\n      this.name = checkNotNull(name, \"name\");\n      this.active = active;\n      this.ttl = ttl;\n      this.nodes = checkNotNull(nodes, \"nodes of %s\", name);\n      this.groups = checkNotNull(groups, \"groups of %s\", name);\n   }\n\n   public String getName() {\n      return name;\n   }\n\n   public boolean isActive() {\n      return active;\n   }\n\n   public int getTTL() {\n      return ttl;\n   }\n\n   public List<Node> getNodes() {\n      return nodes;\n   }\n\n   public List<GeoRegionGroup> getGroups() {\n      return groups;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(active, name, nodes, groups);\n   }\n\n   /**\n    * permits equals comparisons with subtypes\n    */\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || !(obj instanceof GeoService))\n         return false;\n      GeoService that = GeoService.class.cast(obj);\n      return equal(this.active, that.active) && equal(this.name, that.name) && equal(this.ttl, that.ttl)\n            && equal(this.nodes, that.nodes) && equal(this.groups, that.groups);\n   }\n\n   @Override\n   public String toString() {\n      return toStringHelper(this).add(\"active\", active).add(\"name\", name).add(\"ttl\", ttl).add(\"nodes\", nodes).add(\"groups\", groups)\n            .toString();\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().from(this);\n   }\n\n   public static class Builder {\n\n      private String name;\n      private boolean active;\n      protected int ttl = -1;\n      private ImmutableList.Builder<Node> nodes = ImmutableList.builder();\n      private ImmutableList.Builder<GeoRegionGroup> groups = ImmutableList.builder();\n\n      /**\n       * @see GeoService#getName()\n       */\n      public Builder name(String name) {\n         this.name = name;\n         return this;\n      }\n\n      /**\n       * @see GeoService#isActive()\n       */\n      public Builder active(boolean active) {\n         this.active = active;\n         return this;\n      }\n\n      /**\n       * @see Builder#getTTL()\n       */\n      public Builder ttl(int ttl) {\n         this.ttl = ttl;\n         return this;\n      }\n\n      /**\n       * @see GeoService#getNodes()\n       */\n      public Builder addNode(Node node) {\n         this.nodes.add(node);\n         return this;\n      }\n\n      /**\n       * replaces current region groups\n       * \n       * @see GeoService#getNodes()\n       */\n      public Builder nodes(Iterable<Node> nodes) {\n         this.nodes = ImmutableList.<Node> builder().addAll(nodes);\n         return this;\n      }\n\n      /**\n       * @see GeoService#getNodes()\n       */\n      public Builder addAllNodes(Iterable<Node> nodes) {\n         this.nodes.addAll(nodes);\n         return this;\n      }\n\n      /**\n       * @see GeoService#getGroups()\n       */\n      public Builder addGroup(GeoRegionGroup group) {\n         this.groups.add(group);\n         return this;\n      }\n\n      /**\n       * replaces current region groups\n       * \n       * @see GeoService#getGroups()\n       */\n      public Builder groups(Iterable<GeoRegionGroup> groups) {\n         this.groups = ImmutableList.<GeoRegionGroup> builder().addAll(groups);\n         return this;\n      }\n\n      /**\n       * @see GeoService#getGroups()\n       */\n      public Builder addAllGroups(Iterable<GeoRegionGroup> groups) {\n         this.groups.addAll(groups);\n         return this;\n      }\n\n      public GeoService build() {\n         return new GeoService(name, active, ttl, nodes.build(), groups.build());\n      }\n\n      public Builder from(GeoService in) {\n         return name(in.name).active(in.active).ttl(in.ttl).nodes(in.nodes).groups(in.groups);\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/domain/Job.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Named;\n\nimport com.google.common.base.Objects;\n\npublic final class Job {\n\n   @Named(\"job_id\")\n   private final long id;\n   private final Status status;\n\n   @ConstructorProperties({ \"job_id\", \"status\" })\n   private Job(long id, Status status) {\n      this.id = id;\n      this.status = checkNotNull(status, \"status for %s\", id);\n   }\n\n   /**\n    * The ID of the job.\n    */\n   public long getId() {\n      return id;\n   }\n\n   /**\n    * The current status of the job.\n    */\n   public Status getStatus() {\n      return status;\n   }\n\n   public enum Status {\n      SUCCESS, FAILURE, UNRECOGNIZED;\n\n      public static Status fromValue(String status) {\n         try {\n            return valueOf(checkNotNull(status, \"status\").toUpperCase());\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      Job that = Job.class.cast(obj);\n      return equal(this.id, that.id);\n   }\n\n   @Override\n   public String toString() {\n      return toStringHelper(this).add(\"id\", id).add(\"status\", status).toString();\n   }\n\n   public static Job success(long id) {\n      return new Job(id, Status.SUCCESS);\n   }\n\n   public static Job failure(long id) {\n      return new Job(id, Status.FAILURE);\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/domain/Node.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\npublic class Node {\n\n   public static Node create(String zone, String fqdn) {\n      return new Node(zone, fqdn);\n   }\n\n   private final String zone;\n   private final String fqdn;\n\n   @ConstructorProperties({ \"zone\", \"fqdn\" })\n   protected Node(String zone, String fqdn) {\n      this.fqdn = checkNotNull(fqdn, \"fqdn\");\n      this.zone = checkNotNull(zone, \"zone for %s\", fqdn);\n   }\n\n   /**\n    * Name of the zone\n    */\n   public String getZone() {\n      return zone;\n   }\n\n   /**\n    * Fully qualified domain name of a node in the zone\n    */\n   public String getFQDN() {\n      return fqdn;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(zone, fqdn);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      Node that = Node.class.cast(obj);\n      return Objects.equal(this.zone, that.zone) && Objects.equal(this.fqdn, that.fqdn);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(\"\").add(\"zone\", zone).add(\"fqdn\", fqdn).toString();\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/domain/Record.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.domain;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Map;\n\nimport jakarta.inject.Named;\n\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\npublic class Record<D extends Map<String, Object>> extends RecordId {\n\n   private final int ttl;\n   @Named(\"rdata\")\n   private final D rdata;\n\n   @ConstructorProperties({ \"zone\", \"fqdn\", \"record_type\", \"record_id\", \"ttl\", \"rdata\" })\n   protected Record(String zone, String fqdn, String type, long id, int ttl, D rdata) {\n      super(zone, fqdn, type, id);\n      checkArgument(ttl >= 0, \"ttl of %s must be unsigned\", fqdn);\n      this.ttl = ttl;\n      this.rdata = checkNotNull(rdata, \"rdata of %s\", id);\n   }\n\n   /**\n    * The current ttl of the record or zero if default for the zone\n    */\n   public int getTTL() {\n      return ttl;\n   }\n\n   /**\n    * RData defining the record; corresponds to binary master format. Only\n    * simple data types such as String or Integer are values.\n    */\n   public D getRData() {\n      return rdata;\n   }\n\n   @Override\n   protected ToStringHelper string() {\n      return super.string().add(\"ttl\", ttl).add(\"rdata\", rdata);\n   }\n\n   public static <D extends Map<String, Object>> Builder<D, ?> builder() {\n      return new ConcreteBuilder<D>();\n   }\n\n   public Builder<D, ?> toBuilder() {\n      return new ConcreteBuilder<D>().from(this);\n   }\n\n   public abstract static class Builder<D extends Map<String, Object>, B extends Builder<D, B>> extends RecordId.Builder<B> {\n\n      protected int ttl = -1;\n      protected D rdata;\n\n      /**\n       * @see Record#getTTL()\n       */\n      public B ttl(int ttl) {\n         this.ttl = ttl;\n         return self();\n      }\n\n      /**\n       * @see Record#getRData()\n       */\n      public B rdata(D rdata) {\n         this.rdata = rdata;\n         return self();\n      }\n\n      public Record<D> build() {\n         return new Record<D>(zone, fqdn, type, id, ttl, rdata);\n      }\n\n      @Override\n      public B from(RecordId in) {\n         if (in instanceof Record) {\n            @SuppressWarnings(\"unchecked\")\n            Record<D> record = Record.class.cast(in);\n            ttl(record.ttl).rdata(record.rdata);\n         }\n         return super.from(in);\n      }\n   }\n\n   private static class ConcreteBuilder<D extends Map<String, Object>> extends Builder<D, ConcreteBuilder<D>> {\n      protected ConcreteBuilder<D> self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/domain/RecordId.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\npublic class RecordId extends Node {\n\n   private final long id;\n   private final String type;\n\n   @ConstructorProperties({\"zone\", \"fqdn\", \"record_type\", \"record_id\" })\n   RecordId(String zone, String fqdn, String type, long id) {\n      super(zone, fqdn);\n      this.id = id;\n      this.type = checkNotNull(type, \"type of %s\", id);\n   }\n\n   /**\n    * The RRType of the record\n    */\n   public String getType() {\n      return type;\n   }\n\n   /**\n    * The record id\n    */\n   public long getId() {\n      return id;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(getZone(), getFQDN(), type, id);\n   }\n\n   /**\n    * permits equals comparisons with subtypes\n    */\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || !(obj instanceof RecordId))\n         return false;\n      RecordId that = RecordId.class.cast(obj);\n      return super.equals(obj) && equal(this.type, that.type) && equal(this.id, that.id);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   protected ToStringHelper string() {\n      return toStringHelper(this).add(\"zone\", getZone()).add(\"fqdn\", getFQDN()).add(\"type\", type).add(\"id\", id);\n   }\n\n   public static Builder<?> recordIdBuilder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().from(this);\n   }\n\n   public abstract static class Builder<B extends Builder<B>>  {\n      protected abstract B self();\n\n      protected String zone;\n      protected String fqdn;\n      protected String type;\n      protected long id;\n\n      /**\n       * @see Node#getZone()\n       */\n      public B zone(String zone) {\n         this.zone = zone;\n         return self();\n      }\n\n      /**\n       * @see Node#getFQDN()\n       */\n      public B fqdn(String fqdn) {\n         this.fqdn = fqdn;\n         return self();\n      }\n\n      /**\n       * @see RecordId#getType()\n       */\n      public B type(String type) {\n         this.type = type;\n         return self();\n      }\n\n      /**\n       * @see RecordId#getId()\n       */\n      public B id(long id) {\n         this.id = id;\n         return self();\n      }\n\n      public RecordId build() {\n         return new RecordId(zone, fqdn, type, id);\n      }\n\n      public B from(RecordId in) {\n         return zone(in.getZone()).fqdn(in.getFQDN()).type(in.type).id(in.id);\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/domain/RecordSet.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.dynect.v3.domain.RecordSet.Value;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ForwardingList;\nimport com.google.common.collect.ImmutableList;\n\n/**\n * A set of records which shared the same name, type, and ttl\n */\npublic class RecordSet extends ForwardingList<Value> {\n\n   private final String type;\n   private final int ttl;\n   private final transient List<Value> values;\n\n   private RecordSet(String type, int ttl, List<Value> values) {\n      this.type = checkNotNull(type, \"type\");\n      this.ttl = ttl;\n      checkArgument(ttl >= 0, \"ttl must be >=0\");\n      this.values = checkNotNull(values, \"values\");\n   }\n\n   /**\n    * @see Record#getType()\n    */\n   public String getType() {\n      return type;\n   }\n\n   /**\n    * @see Record#getTTL()\n    */\n   public int getTTL() {\n      return ttl;\n   }\n\n   public static class Value {\n      private final Optional<String> label;\n      private final Optional<Integer> weight;\n      private final Map<String, Object> rdata;\n\n      private Value(Optional<String> label, Optional<Integer> weight, Map<String, Object> rdata) {\n         this.label = checkNotNull(label, \"label\");\n         this.weight = checkNotNull(weight, \"weight\");\n         this.rdata = checkNotNull(rdata, \"rdata\");\n      }\n\n      /**\n       * The label of the value.\n       */\n      public Optional<String> getLabel() {\n         return label;\n      }\n\n      /**\n       * The relative weight of the value.\n       */\n      public Optional<Integer> getWeight() {\n         return weight;\n      }\n\n      /**\n       * @see Record#getRData()\n       */\n      public Map<String, Object> getRData() {\n         return rdata;\n      }\n\n      @Override\n      public int hashCode() {\n         return Objects.hashCode(label, weight, rdata);\n      }\n\n      @Override\n      public boolean equals(Object obj) {\n         if (this == obj)\n            return true;\n         if (obj == null || getClass() != obj.getClass())\n            return false;\n         Value that = Value.class.cast(obj);\n         return equal(this.label, that.label) && equal(this.weight, that.weight) && equal(this.rdata, that.rdata);\n      }\n\n      @Override\n      public String toString() {\n         return toStringHelper(\"\").omitNullValues().add(\"label\", label.orNull()).add(\"weight\", weight.orNull())\n               .add(\"rdata\", rdata).toString();\n      }\n\n      public static Builder builder() {\n         return new Builder();\n      }\n\n      public Builder toBuilder() {\n         return new Builder().from(this);\n      }\n\n      public static final class Builder {\n         private Optional<String> label = Optional.absent();\n         private Optional<Integer> weight = Optional.absent();\n         private Map<String, Object> rdata;\n\n         /**\n          * @see Value#getLabel()\n          */\n         public Builder label(String label) {\n            this.label = Optional.fromNullable(label);\n            return this;\n         }\n\n         /**\n          * @see Value#getWeight()\n          */\n         public Builder weight(Integer weight) {\n            this.weight = Optional.fromNullable(weight);\n            return this;\n         }\n\n         /**\n          * @see Record#getRData()\n          */\n         public Builder rdata(Map<String, Object> rdata) {\n            this.rdata = rdata;\n            return this;\n         }\n\n         public Value build() {\n            return new Value(label, weight, rdata);\n         }\n\n         public Builder from(Value in) {\n            return label(in.label.orNull()).weight(in.weight.orNull()).rdata(in.rdata);\n         }\n      }\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(type, ttl, values);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      RecordSet that = RecordSet.class.cast(obj);\n      return equal(this.type, that.type) && equal(this.ttl, that.ttl) && equal(this.values, that.values);\n   }\n\n   @Override\n   public String toString() {\n      return toStringHelper(\"\").omitNullValues().add(\"type\", type).add(\"ttl\", ttl).add(\"values\", values).toString();\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return new Builder().from(this);\n   }\n\n   public static final class Builder {\n      private String type;\n      private int ttl = -1;\n      private ImmutableList.Builder<Value> values = ImmutableList.builder();\n\n      /**\n       * @see RecordSet#getType()\n       */\n      public Builder type(String type) {\n         this.type = type;\n         return this;\n      }\n\n      /**\n       * @see RecordSet#getTTL()\n       */\n      public Builder ttl(int ttl) {\n         this.ttl = ttl;\n         return this;\n      }\n\n      /**\n       * @see RecordSet#iterator()\n       */\n      public Builder add(Value value) {\n         this.values.add(value);\n         return this;\n      }\n\n      /**\n       * replaces current values\n       * \n       * @see RecordSet#iterator()\n       */\n      public Builder values(Iterable<Value> values) {\n         this.values = ImmutableList.<Value> builder().addAll(values);\n         return this;\n      }\n\n      /**\n       * @see RecordSet#iterator()\n       */\n      public Builder addAll(Iterable<Value> values) {\n         this.values.addAll(values);\n         return this;\n      }\n\n      public RecordSet build() {\n         return new RecordSet(type, ttl, values.build());\n      }\n\n      public Builder from(RecordSet in) {\n         return type(in.type).ttl(in.ttl).values(in.values);\n      }\n   }\n\n   @Override\n   protected List<Value> delegate() {\n      return values;\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/domain/SOARecord.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.dynect.v3.domain.Zone.SerialStyle;\nimport org.jclouds.dynect.v3.domain.rdata.SOAData;\n\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Start of Authority per RFC 1035\n */\npublic final class SOARecord extends Record<SOAData> {\n\n   @Named(\"serial_style\")\n   private final SerialStyle serialStyle;\n\n   @ConstructorProperties({ \"zone\", \"fqdn\", \"record_type\", \"record_id\", \"ttl\", \"rdata\", \"serial_style\" })\n   private SOARecord(String zone, String fqdn, String type, long id, int ttl, SOAData rdata, SerialStyle serialStyle) {\n      super(zone, fqdn, type, id, ttl, rdata);\n      this.serialStyle = checkNotNull(serialStyle, \"serialStyle of %s\", id);\n   }\n\n   /**\n    * @see Zone#getSerialStyle\n    */\n   public SerialStyle getSerialStyle() {\n      return serialStyle;\n   }\n\n   @Override\n   protected ToStringHelper string() {\n      return super.string().add(\"serialStyle\", serialStyle);\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().from(this);\n   }\n\n   public static final class Builder extends Record.Builder<SOAData, Builder> {\n\n      private SerialStyle serialStyle;\n\n      /**\n       * @see Zone#getSerialStyle()\n       */\n      public Builder serialStyle(SerialStyle serialStyle) {\n         this.serialStyle = serialStyle;\n         return this;\n      }\n\n      public SOARecord build() {\n         return new SOARecord(zone, fqdn, type, id, ttl, rdata, serialStyle);\n      }\n\n      @Override\n      public Builder from(RecordId in) {\n         if (in instanceof SOARecord) {\n            SOARecord record = SOARecord.class.cast(in);\n            serialStyle(record.serialStyle);\n         }\n         return super.from(in);\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n   }   \n}\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/domain/Session.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\npublic final class Session {\n\n   public static Session forTokenAndVersion(String token, String version) {\n      return new Session(token, version);\n   }\n   \n   private final String token;\n   private final String version;\n\n   @ConstructorProperties({\"token\", \"version\"})\n   private Session(String token, String version) {\n      this.token = checkNotNull(token, \"token\");\n      this.version = checkNotNull(version, \"version for %s\", token);\n   }\n\n   /**\n    * The authentication token\n    */\n   public String getToken() {\n      return token;\n   }\n\n   /**\n    * The current version of the server\n    */\n   public String getVersion() {\n      return version;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(token, version);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      Session other = Session.class.cast(obj);\n      return Objects.equal(this.token, other.token) && Objects.equal(this.version, other.version);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).add(\"token\", token).add(\"version\", version).toString();\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/domain/SessionCredentials.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.domain.Credentials;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\n/**\n * Session credentials for API authentication.\n * \n * @see <a href= \"https://manage.dynect.net/help/docs/api2/rest/\" />\n */\npublic final class SessionCredentials extends Credentials {\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().from(this);\n   }\n\n   public static final class Builder extends Credentials.Builder<SessionCredentials> {\n      private String customerName;\n      private String userName;\n      private String password;\n\n      /**\n       * @see SessionCredentials#getCustomerName()\n       */\n      public Builder customerName(String customerName) {\n         this.customerName = customerName;\n         return this;\n      }\n\n      @Override\n      public Builder identity(String identity) {\n         return userName(identity);\n      }\n\n      @Override\n      public Builder credential(String credential) {\n         return password(credential);\n      }\n\n      /**\n       * @see SessionCredentials#getUserName()\n       */\n      public Builder userName(String userName) {\n         this.userName = userName;\n         return this;\n      }\n\n      /**\n       * @see SessionCredentials#getPassword()\n       */\n      public Builder password(String password) {\n         this.password = password;\n         return this;\n      }\n\n      public SessionCredentials build() {\n         return new SessionCredentials(customerName, userName, password);\n      }\n\n      public Builder from(SessionCredentials in) {\n         return this.userName(in.identity).password(in.credential).customerName(in.customerName);\n      }\n   }\n\n   @Named(\"customer_name\")\n   private final String customerName;\n   @Named(\"user_name\")\n   private final String userName;\n   private final String password;\n\n   @ConstructorProperties({ \"customer_name\", \"user_name\", \"password\" })\n   private SessionCredentials(String customerName, String userName, String password) {\n      super(checkNotNull(userName, \"userName\"), checkNotNull(password, \"password for %s\", userName));\n      this.userName = userName;\n      this.password = password;\n      this.customerName = checkNotNull(customerName, \"customerName for %s\", userName);\n   }\n\n   /**\n    * UserName ID that identifies the temporary credentials.\n    */\n   public String getUserName() {\n      return userName;\n   }\n\n   /**\n    * The Secret Access Key to sign requests.\n    */\n   public String getPassword() {\n      return password;\n   }\n\n   /**\n    * The security token that users must pass to the service API to use the\n    * temporary credentials.\n    */\n   public String getCustomerName() {\n      return customerName;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(customerName, userName, password);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      SessionCredentials other = SessionCredentials.class.cast(obj);\n      return Objects.equal(this.userName, other.userName) && Objects.equal(this.password, other.password)\n            && Objects.equal(this.customerName, other.customerName);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).add(\"userName\", identity).add(\"customerName\", customerName).toString();\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/domain/Zone.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport jakarta.inject.Named;\n\nimport com.google.common.base.CaseFormat;\nimport com.google.common.base.Objects;\n\npublic final class Zone {\n\n   private final String fqdn;\n   @Named(\"zone_type\")\n   private final Type type;\n   private final int serial;\n   @Named(\"serial_style\")\n   private final SerialStyle serialStyle;\n\n   public static enum Type {\n      PRIMARY, SECONDARY;\n\n      @Override\n      public String toString() {\n         return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name());\n      }\n\n      public static Type fromValue(String type) {\n         return valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, checkNotNull(type, \"type\")));\n      }\n\n   }\n\n   public static enum SerialStyle {\n      /**\n       * Serials are incremented by 1 on every change\n       */\n      INCREMENT,\n      /**\n       * Serials will be the UNIX timestamp at the time of the publish\n       */\n      EPOCH,\n      /**\n       * Serials will be in the form of YYYYMMDDxx where xx is incremented by\n       * one for each change during that particular day\n       */\n      DAY,\n      /**\n       * Serials will be in the form of YYMMDDHHMM\n       */\n      MINUTE,\n\n      UNRECOGNIZED;\n\n      @Override\n      public String toString() {\n         return name().toLowerCase();\n      }\n\n      public static SerialStyle fromValue(String serialStyle) {\n         try {\n            return valueOf(checkNotNull(serialStyle, \"serialStyle\").toUpperCase());\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n\n   }\n\n   @ConstructorProperties({ \"zone\", \"zone_type\", \"serial\", \"serial_style\" })\n   private Zone(String fqdn, Type type, int serial, SerialStyle serialStyle) {\n      this.fqdn = checkNotNull(fqdn, \"fqdn\");\n      this.type = checkNotNull(type, \"type for %s\", fqdn);\n      this.serial = serial;\n      this.serialStyle = checkNotNull(serialStyle, \"serialStyle for %s\", fqdn);\n   }\n\n   /**\n    * The fqdn of the requested zone\n    */\n   public String getFQDN() {\n      return fqdn;\n   }\n\n   /**\n    * A unique string that identifies the request to create the hosted zone.\n    */\n   public Type getType() {\n      return type;\n   }\n\n   /**\n    * The current serial number of the zone\n    */\n   public int getSerial() {\n      return serial;\n   }\n\n   /**\n    * The style of the zone's serial\n    */\n   public SerialStyle getSerialStyle() {\n      return serialStyle;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(fqdn, type);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      Zone that = Zone.class.cast(obj);\n      return equal(this.fqdn, that.fqdn) && equal(this.type, that.type);\n   }\n\n   @Override\n   public String toString() {\n      return toStringHelper(this).omitNullValues().add(\"fqdn\", fqdn).add(\"type\", type).add(\"serial\", serial)\n            .add(\"serialStyle\", serialStyle).toString();\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().from(this);\n   }\n\n   public static final class Builder {\n      private String fqdn;\n      private Type type;\n      private int serial;\n      private SerialStyle serialStyle;\n\n      /**\n       * @see Zone#getFQDN()\n       */\n      public Builder fqdn(String fqdn) {\n         this.fqdn = fqdn;\n         return this;\n      }\n\n      /**\n       * @see Zone#getType()\n       */\n      public Builder type(Type type) {\n         this.type = type;\n         return this;\n      }\n\n      /**\n       * @see Zone#getSerial()\n       */\n      public Builder serial(int serial) {\n         this.serial = serial;\n         return this;\n      }\n\n      /**\n       * @see Zone#getSerialStyle()\n       */\n      public Builder serialStyle(SerialStyle serialStyle) {\n         this.serialStyle = serialStyle;\n         return this;\n      }\n\n      public Zone build() {\n         return new Zone(fqdn, type, serial, serialStyle);\n      }\n\n      public Builder from(Zone in) {\n         return this.fqdn(in.fqdn).type(in.type).serial(in.serial).serialStyle(in.serialStyle);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/domain/rdata/AAAAData.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.domain.rdata;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Map;\n\nimport com.google.common.collect.ForwardingMap;\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Corresponds to the binary representation of the {@code AAAA} (Address) RData\n * \n * <h4>Example</h4>\n * \n * <pre>\n * import static org.jclouds.dynect.v3.domain.rdata.NSData.aaaa;\n * ...\n * NSData rdata = aaaa(\"1234:ab00:ff00::6b14:abcd\");\n * </pre>\n * \n * @see <aaaa href=\"http://www.ietf.org/rfc/rfc3596.txt\">RFC 3596</aaaa>\n */\npublic class AAAAData extends ForwardingMap<String, Object> {\n   private final String address;\n\n   @ConstructorProperties(\"address\")\n   private AAAAData(String address) {\n      this.address = checkNotNull(address, \"address\");\n      this.delegate = ImmutableMap.<String, Object> of(\"address\", address);\n   }\n\n   /**\n    * a 128 bit IPv6 address\n    */\n   public String getAddress() {\n      return address;\n   }\n\n   private final transient ImmutableMap<String, Object> delegate;\n\n   protected Map<String, Object> delegate() {\n      return delegate;\n   }\n\n   public static AAAAData aaaa(String address) {\n      return builder().address(address).build();\n   }\n\n   public static AAAAData.Builder builder() {\n      return new Builder();\n   }\n\n   public AAAAData.Builder toBuilder() {\n      return builder().from(this);\n   }\n\n   public static final class Builder {\n      private String address;\n\n      /**\n       * @see AAAAData#getAddress()\n       */\n      public AAAAData.Builder address(String address) {\n         this.address = address;\n         return this;\n      }\n\n      public AAAAData build() {\n         return new AAAAData(address);\n      }\n\n      public AAAAData.Builder from(AAAAData in) {\n         return this.address(in.getAddress());\n      }\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/domain/rdata/AData.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.domain.rdata;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Map;\n\nimport com.google.common.collect.ForwardingMap;\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Corresponds to the binary representation of the {@code A} (Address) RData\n * \n * <h4>Example</h4>\n * \n * <pre>\n * import static org.jclouds.dynect.v3.domain.rdata.NSData.a;\n * ...\n * NSData rdata = a(\"ptr.foo.com.\");\n * </pre>\n * \n * @see <a href=\"http://www.ietf.org/rfc/rfc1035.txt\">RFC 1035</a>\n */\npublic class AData extends ForwardingMap<String, Object> {\n\n   private final String address;\n\n   @ConstructorProperties(\"address\")\n   private AData(String address) {\n      this.address = checkNotNull(address, \"address\");\n      this.delegate = ImmutableMap.<String, Object> of(\"address\", checkNotNull(address, \"address\"));\n   }\n\n   /**\n    * a 32-bit internet address\n    */\n   public String getAddress() {\n      return address;\n   }\n\n   private final transient ImmutableMap<String, Object> delegate;\n\n   protected Map<String, Object> delegate() {\n      return delegate;\n   }\n\n   public static AData a(String address) {\n      return builder().address(address).build();\n   }\n\n   public static AData.Builder builder() {\n      return new Builder();\n   }\n\n   public AData.Builder toBuilder() {\n      return builder().from(this);\n   }\n\n   public static final class Builder {\n      private String address;\n\n      /**\n       * @see AData#getAddress()\n       */\n      public AData.Builder address(String address) {\n         this.address = address;\n         return this;\n      }\n\n      public AData build() {\n         return new AData(address);\n      }\n\n      public AData.Builder from(AData in) {\n         return this.address(in.getAddress());\n      }\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/domain/rdata/CNAMEData.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.domain.rdata;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Map;\n\nimport com.google.common.collect.ForwardingMap;\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Corresponds to the binary representation of the {@code CNAME} (Canonical Name) RData\n * \n * <h4>Example</h4>\n * \n * <pre>\n * import static org.jclouds.dynect.v3.domain.rdata.NSData.cname;\n * ...\n * NSData rdata = cname(\"cname.foo.com.\");\n * </pre>\n * \n * @see <a href=\"http://www.ietf.org/rfc/rfc1035.txt\">RFC 1035</a>\n */\npublic class CNAMEData extends ForwardingMap<String, Object> {\n\n   private final String cname;\n\n   @ConstructorProperties(\"cname\")\n   private CNAMEData(String cname) {\n      this.cname = checkNotNull(cname, \"cname\");\n      this.delegate = ImmutableMap.<String, Object> of(\"cname\", cname);\n   }\n\n   /**\n    * domain-name which specifies the canonical or primary name for the owner.\n    * The owner name is an alias.\n    */\n   public String getCname() {\n      return cname;\n   }\n\n   private final transient ImmutableMap<String, Object> delegate;\n\n   protected Map<String, Object> delegate() {\n      return delegate;\n   }\n\n   public static CNAMEData cname(String cname) {\n      return builder().cname(cname).build();\n   }\n\n   public static CNAMEData.Builder builder() {\n      return new Builder();\n   }\n\n   public CNAMEData.Builder toBuilder() {\n      return builder().from(this);\n   }\n\n   public static final class Builder {\n      private String cname;\n\n      /**\n       * @see CNAMEData#getCname()\n       */\n      public CNAMEData.Builder cname(String cname) {\n         this.cname = cname;\n         return this;\n      }\n\n      public CNAMEData build() {\n         return new CNAMEData(cname);\n      }\n\n      public CNAMEData.Builder from(CNAMEData in) {\n         return this.cname(in.getCname());\n      }\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/domain/rdata/MXData.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.domain.rdata;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Map;\n\nimport com.google.common.collect.ForwardingMap;\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Corresponds to the binary representation of the {@code MX} (Mail Exchange)\n * RData\n * \n * <h4>Example</h4>\n * \n * <pre>\n * import static org.jclouds.dynect.v3.domain.rdata.MXData.mx;\n * ...\n * MXData rdata = mx(1, \"mail.jclouds.org\");\n * </pre>\n * \n * @see <a href=\"http://www.ietf.org/rfc/rfc1035.txt\">RFC 1035</a>\n */\npublic class MXData extends ForwardingMap<String, Object> {\n\n   private final int preference;\n   private final String exchange;\n\n   @ConstructorProperties({ \"preference\", \"exchange\" })\n   private MXData(int preference, String exchange) {\n      checkArgument(preference >= 0, \"preference of %s must be unsigned\", exchange);\n      this.preference = preference;\n      this.exchange = checkNotNull(exchange, \"exchange\");\n      this.delegate = ImmutableMap.<String, Object> builder().put(\"preference\", preference).put(\"exchange\", exchange)\n            .build();\n   }\n\n   /**\n    * specifies the preference given to this RR among others at the same owner.\n    * Lower values are preferred.\n    */\n   public int getPreference() {\n      return preference;\n   }\n\n   /**\n    * domain-name which specifies a host willing to act as a mail exchange for\n    * the owner name.\n    */\n   public String getExchange() {\n      return exchange;\n   }\n\n   private final transient ImmutableMap<String, Object> delegate;\n\n   protected Map<String, Object> delegate() {\n      return delegate;\n   }\n\n   public static MXData mx(int preference, String exchange) {\n      return builder().preference(preference).exchange(exchange).build();\n   }\n\n   public static MXData.Builder builder() {\n      return new Builder();\n   }\n\n   public MXData.Builder toBuilder() {\n      return builder().from(this);\n   }\n\n   public static final class Builder {\n      private int preference = -1;\n      private String exchange;\n\n      /**\n       * @see MXData#getPreference()\n       */\n      public MXData.Builder preference(int preference) {\n         this.preference = preference;\n         return this;\n      }\n\n      /**\n       * @see MXData#getExchange()\n       */\n      public MXData.Builder exchange(String exchange) {\n         this.exchange = exchange;\n         return this;\n      }\n\n      public MXData build() {\n         return new MXData(preference, exchange);\n      }\n\n      public MXData.Builder from(MXData in) {\n         return this.preference(in.getPreference()).exchange(in.getExchange());\n      }\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/domain/rdata/NSData.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.domain.rdata;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Map;\n\nimport com.google.common.collect.ForwardingMap;\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Corresponds to the binary representation of the {@code NS} (Name Server) RData\n * \n * <h4>Example</h4>\n * \n * <pre>\n * import static org.jclouds.dynect.v3.domain.rdata.NSData.ns;\n * ...\n * NSData rdata = ns(\"ns.foo.com.\");\n * </pre>\n * \n * @see <a href=\"http://www.ietf.org/rfc/rfc1035.txt\">RFC 1035</a>\n */\npublic class NSData extends ForwardingMap<String, Object> {\n\n   private final String nsdname;\n\n   @ConstructorProperties(\"nsdname\")\n   private NSData(String nsdname) {\n      this.nsdname = checkNotNull(nsdname, \"nsdname\");\n      this.delegate = ImmutableMap.<String, Object> of(\"nsdname\", nsdname);\n   }\n\n   /**\n    * domain-name which specifies a host which should be authoritative for the\n    * specified class and domain.\n    */\n   public String getNsdname() {\n      return nsdname;\n   }\n\n   private final transient ImmutableMap<String, Object> delegate;\n\n   protected Map<String, Object> delegate() {\n      return delegate;\n   }\n\n   public static NSData ns(String nsdname) {\n      return builder().nsdname(nsdname).build();\n   }\n\n   public static NSData.Builder builder() {\n      return new Builder();\n   }\n\n   public NSData.Builder toBuilder() {\n      return builder().from(this);\n   }\n\n   public static final class Builder {\n      private String nsdname;\n\n      /**\n       * @see NSData#getNsdname()\n       */\n      public NSData.Builder nsdname(String nsdname) {\n         this.nsdname = nsdname;\n         return this;\n      }\n\n      public NSData build() {\n         return new NSData(nsdname);\n      }\n\n      public NSData.Builder from(NSData in) {\n         return this.nsdname(in.getNsdname());\n      }\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/domain/rdata/PTRData.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.domain.rdata;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Map;\n\nimport com.google.common.collect.ForwardingMap;\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Corresponds to the binary representation of the {@code PTR} (Pointer) RData\n * \n * <h4>Example</h4>\n * \n * <pre>\n * import static org.jclouds.dynect.v3.domain.rdata.NSData.ptr;\n * ...\n * NSData rdata = ptr(\"ptr.foo.com.\");\n * </pre>\n * \n * @see <a href=\"http://www.ietf.org/rfc/rfc1035.txt\">RFC 1035</a>\n */\npublic class PTRData extends ForwardingMap<String, Object> {\n\n   private final String ptrdname;\n\n   @ConstructorProperties(\"ptrdname\")\n   private PTRData(String ptrdname) {\n      this.ptrdname = checkNotNull(ptrdname, \"ptrdname\");\n      this.delegate = ImmutableMap.<String, Object> of(\"ptrdname\", ptrdname);\n   }\n\n   /**\n    * domain-name which points to some location in the domain name space.\n    */\n   public String getPtrdname() {\n      return ptrdname;\n   }\n\n   private final transient ImmutableMap<String, Object> delegate;\n\n   protected Map<String, Object> delegate() {\n      return delegate;\n   }\n\n   public static PTRData ptr(String ptrdname) {\n      return builder().ptrdname(ptrdname).build();\n   }\n\n   public static PTRData.Builder builder() {\n      return new Builder();\n   }\n\n   public PTRData.Builder toBuilder() {\n      return builder().from(this);\n   }\n\n   public static final class Builder {\n      private String ptrdname;\n\n      /**\n       * @see PTRData#getPtrdname()\n       */\n      public PTRData.Builder ptrdname(String ptrdname) {\n         this.ptrdname = ptrdname;\n         return this;\n      }\n\n      public PTRData build() {\n         return new PTRData(ptrdname);\n      }\n\n      public PTRData.Builder from(PTRData in) {\n         return this.ptrdname(in.getPtrdname());\n      }\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/domain/rdata/SOAData.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.domain.rdata;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Map;\n\nimport com.google.common.collect.ForwardingMap;\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Corresponds to the binary representation of the {@code SOA} (Start of Authority) RData\n * \n * <h4>Example</h4>\n * \n * <pre>\n * SOAData rdata = SOAData.builder()\n *                        .rname(&quot;foo.com.&quot;)\n *                        .mname(&quot;admin.foo.com.&quot;)\n *                        .serial(1)\n *                        .refresh(3600)\n *                        .retry(600)\n *                        .expire(604800)\n *                        .minimum(60).build()\n * </pre>\n * \n * @see <a href=\"http://www.ietf.org/rfc/rfc1035.txt\">RFC 1035</a>\n */\npublic class SOAData extends ForwardingMap<String, Object> {\n   private final String mname;\n   private final String rname;\n   private final int serial;\n   private final int refresh;\n   private final int retry;\n   private final int expire;\n   private final int minimum;\n\n   @ConstructorProperties({ \"mname\", \"rname\", \"serial\", \"refresh\", \"retry\", \"expire\", \"minimum\" })\n   private SOAData(String mname, String rname, int serial, int refresh, int retry,\n         int expire, int minimum) {\n      this.mname = checkNotNull(mname, \"mname\");\n      this.rname = checkNotNull(rname, \"rname of %s\", mname);\n      checkArgument(serial >= 0, \"serial of %s must be unsigned\", mname);\n      this.serial = serial;\n      checkArgument(refresh >= 0, \"refresh of %s must be unsigned\", mname);\n      this.refresh = refresh;\n      checkArgument(retry >= 0, \"retry of %s must be unsigned\", mname);\n      this.retry = retry;\n      checkArgument(expire >= 0, \"expire of %s must be unsigned\", mname);\n      this.expire = expire;\n      checkArgument(minimum >= 0, \"minimum of %s must be unsigned\", mname);\n      this.minimum = minimum;\n      this.delegate = ImmutableMap.<String, Object> builder()\n            .put(\"mname\", checkNotNull(mname, \"mname\"))\n            .put(\"rname\", checkNotNull(rname, \"rname of %s\", mname))\n            .put(\"serial\", serial)\n            .put(\"refresh\", refresh)\n            .put(\"retry\", retry)\n            .put(\"expire\", expire)\n            .put(\"minimum\", minimum)\n            .build();\n   }\n\n   /**\n    * domain-name of the name server that was the original or primary source of\n    * data for this zone\n    */\n   public String getMname() {\n      return mname;\n   }\n\n   /**\n    * domain-name which specifies the mailbox of the person responsible for this\n    * zone.\n    */\n   public String getRname() {\n      return rname;\n   }\n\n   /**\n    * version number of the original copy of the zone.\n    */\n   public int getSerial() {\n      return serial;\n   }\n\n   /**\n    * time interval before the zone should be refreshed\n    */\n   public int getRefresh() {\n      return refresh;\n   }\n\n   /**\n    * time interval that should elapse before a failed refresh should be retried\n    */\n   public int getRetry() {\n      return retry;\n   }\n\n   /**\n    * time value that specifies the upper limit on the time interval that can\n    * elapse before the zone is no longer authoritative.\n    */\n   public int getExpire() {\n      return expire;\n   }\n\n   /**\n    * minimum TTL field that should be exported with any RR from this zone.\n    */\n   public int getMinimum() {\n      return minimum;\n   }\n\n   private final transient ImmutableMap<String, Object> delegate;\n\n   protected Map<String, Object> delegate() {\n      return delegate;\n   }\n\n   public static SOAData.Builder builder() {\n      return new Builder();\n   }\n\n   public SOAData.Builder toBuilder() {\n      return builder().from(this);\n   }\n\n   public static final class Builder {\n      private String mname;\n      private String rname;\n      private int serial = -1;\n      private int refresh = -1;\n      private int retry = -1;\n      private int expire = -1;\n      private int minimum = -1;\n\n      /**\n       * @see SOAData#getMname()\n       */\n      public SOAData.Builder mname(String mname) {\n         this.mname = mname;\n         return this;\n      }\n\n      /**\n       * @see SOAData#getRname()\n       */\n      public SOAData.Builder rname(String rname) {\n         this.rname = rname;\n         return this;\n      }\n\n      /**\n       * @see SOAData#getSerial()\n       */\n      public SOAData.Builder serial(int serial) {\n         this.serial = serial;\n         return this;\n      }\n\n      /**\n       * @see SOAData#getRefresh()\n       */\n      public SOAData.Builder refresh(int refresh) {\n         this.refresh = refresh;\n         return this;\n      }\n\n      /**\n       * @see SOAData#getRetry()\n       */\n      public SOAData.Builder retry(int retry) {\n         this.retry = retry;\n         return this;\n      }\n\n      /**\n       * @see SOAData#getExpire()\n       */\n      public SOAData.Builder expire(int expire) {\n         this.expire = expire;\n         return this;\n      }\n\n      /**\n       * @see SOAData#getMinimum()\n       */\n      public SOAData.Builder minimum(int minimum) {\n         this.minimum = minimum;\n         return this;\n      }\n\n      public SOAData build() {\n         return new SOAData(mname, rname, serial, refresh, retry, expire, minimum);\n      }\n\n      public SOAData.Builder from(SOAData in) {\n         return this.mname(in.getMname()).rname(in.getRname()).serial(in.getSerial()).refresh(in.getRefresh())\n               .expire(in.getExpire()).minimum(in.getMinimum());\n      }\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/domain/rdata/SPFData.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.domain.rdata;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Map;\n\nimport com.google.common.collect.ForwardingMap;\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Corresponds to the binary representation of the {@code SPF} (Sender Policy\n * Framework) RData\n * \n * <h4>Example</h4>\n * \n * <pre>\n * import static denominator.model.rdata.SPFData.spf;\n * ...\n * SPFData rdata = spf(\"v=spf1 +mx a:colo.example.com/28 -all\");\n * </pre>\n * \n * @see <a href=\"http://tools.ietf.org/html/rfc4408#section-3.1.1\">RFC 4408</a>\n */\npublic class SPFData extends ForwardingMap<String, Object> {\n\n   public static SPFData create(String txtdata) {\n      return new SPFData(txtdata);\n   }\n\n   private final String txtdata;\n\n   @ConstructorProperties(\"txtdata\")\n   private SPFData(String txtdata) {\n      this.txtdata = checkNotNull(txtdata, \"txtdata\");\n      this.delegate = ImmutableMap.<String, Object> of(\"txtdata\", txtdata);\n   }\n\n   /**\n    * One or more character-strings.\n    */\n   public String getTxtdata() {\n      return txtdata;\n   }\n\n   // transient to avoid serializing by default, for example in json\n   private final transient ImmutableMap<String, Object> delegate;\n\n   @Override\n   protected Map<String, Object> delegate() {\n      return delegate;\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/domain/rdata/SRVData.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.domain.rdata;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Map;\n\nimport com.google.common.collect.ForwardingMap;\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Corresponds to the binary representation of the {@code SRV} (Service) RData\n * \n * <h4>Example</h4>\n * \n * <pre>\n * SRVData rdata = SRVData.builder()\n *                        .priority(0)\n *                        .weight(1)\n *                        .port(80)\n *                        .target(&quot;www.foo.com.&quot;).build()\n * </pre>\n * \n * @see <a href=\"http://www.ietf.org/rfc/rfc2782.txt\">RFC 2782</a>\n */\npublic class SRVData extends ForwardingMap<String, Object> {\n   private final int priority;\n   private final int weight;\n   private final int port;\n   private final String target;\n   \n   @ConstructorProperties({ \"priority\", \"weight\", \"port\", \"target\" })\n   private SRVData(int priority, int weight, int port, String target) {\n      checkArgument(priority <= 0xFFFF, \"priority must be 0-65535\");\n      this.priority = priority;\n      checkArgument(weight <= 0xFFFF, \"weight must be 0-65535\");\n      this.weight = weight;\n      checkArgument(port <= 0xFFFF, \"port must be 0-65535\");\n      this.port = port;\n      this.target = checkNotNull(target, \"target\");\n      this.delegate = ImmutableMap.<String, Object> builder()\n            .put(\"priority\", priority)\n            .put(\"weight\", weight)\n            .put(\"port\", port)\n            .put(\"target\", target)\n            .build();\n   }\n\n   /**\n    * The priority of this target host. A client MUST attempt to contact the\n    * target host with the lowest-numbered priority it can reach; target hosts\n    * with the same priority SHOULD be tried in an order defined by the weight\n    * field.\n    */\n   public int getPriority() {\n      return priority;\n   }\n\n   /**\n    * The weight field specifies a relative weight for entries with the same\n    * priority. Larger weights SHOULD be given a proportionately higher\n    * probability of being selected.\n    */\n   public int getWeight() {\n      return weight;\n   }\n\n   /**\n    * The port on this target host of this service.\n    */\n   public int getPort() {\n      return port;\n   }\n\n   /**\n    * The domain name of the target host. There MUST be one or more address\n    * records for this name, the name MUST NOT be an alias.\n    */\n   public String getTarget() {\n      return target;\n   }\n\n   private final transient ImmutableMap<String, Object> delegate;\n\n   protected Map<String, Object> delegate() {\n      return delegate;\n   }\n\n   public static SRVData.Builder builder() {\n      return new Builder();\n   }\n\n   public SRVData.Builder toBuilder() {\n      return builder().from(this);\n   }\n\n   public static final class Builder {\n      private int priority = -1;\n      private int weight = -1;\n      private int port = -1;\n      private String target;\n\n      /**\n       * @see SRVData#getPriority()\n       */\n      public SRVData.Builder priority(int priority) {\n         this.priority = priority;\n         return this;\n      }\n\n      /**\n       * @see SRVData#getWeight()\n       */\n      public SRVData.Builder weight(int weight) {\n         this.weight = weight;\n         return this;\n      }\n\n      /**\n       * @see SRVData#getPort()\n       */\n      public SRVData.Builder port(int port) {\n         this.port = port;\n         return this;\n      }\n\n      /**\n       * @see SRVData#getTarget()\n       */\n      public SRVData.Builder target(String target) {\n         this.target = target;\n         return this;\n      }\n\n      public SRVData build() {\n         return new SRVData(priority, weight, port, target);\n      }\n\n      public SRVData.Builder from(SRVData in) {\n         return this.priority(in.getPriority()).weight(in.getWeight()).port(in.getPort()).target(in.getTarget());\n      }\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/domain/rdata/SSHFPData.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.domain.rdata;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Map;\n\nimport com.google.common.collect.ForwardingMap;\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Corresponds to the binary representation of the {@code SSHFP} (SSH\n * Fingerprint) RData\n * \n * <h4>Example</h4>\n * \n * <pre>\n * SSHFPData rdata = SSHFPData.builder().algorithm(2).fptype(1).fingerprint(&quot;123456789abcdef67890123456789abcdef67890&quot;)\n *       .build();\n * // or shortcut\n * SSHFPData rdata = SSHFPData.createDSA(&quot;123456789abcdef67890123456789abcdef67890&quot;);\n * </pre>\n * \n * @see <a href=\"http://www.rfc-editor.org/rfc/rfc4255.txt\">RFC 4255</a>\n */\npublic class SSHFPData extends ForwardingMap<String, Object> {\n\n   /**\n    * @param fingerprint\n    *           {@code DSA} {@code SHA-1} fingerprint\n    */\n   public static SSHFPData createDSA(String fingerprint) {\n      return builder().algorithm(2).fptype(1).fingerprint(fingerprint).build();\n   }\n\n   /**\n    * @param fingerprint\n    *           {@code RSA} {@code SHA-1} fingerprint\n    */\n   public static SSHFPData createRSA(String fingerprint) {\n      return builder().algorithm(1).fptype(1).fingerprint(fingerprint).build();\n   }\n\n   private final int algorithm;\n   private final int fptype;\n   private final String fingerprint;\n\n   @ConstructorProperties({ \"algorithm\", \"fptype\", \"fingerprint\" })\n   private SSHFPData(int algorithm, int fptype, String fingerprint) {\n      checkArgument(algorithm >= 0, \"algorithm of %s must be unsigned\", fingerprint);\n      this.algorithm = algorithm;\n      checkArgument(fptype >= 0, \"fptype of %s must be unsigned\", fingerprint);\n      this.fptype = fptype;\n      this.fingerprint = checkNotNull(fingerprint, \"fingerprint\");\n      this.delegate = ImmutableMap.<String, Object> builder()\n            .put(\"algorithm\", algorithm)\n            .put(\"fptype\", fptype)\n            .put(\"fingerprint\", fingerprint).build();\n   }\n\n   /**\n    * This algorithm number octet describes the algorithm of the public key.\n    * \n    * @return most often {@code 1} for {@code RSA} or {@code 2} for {@code DSA}.\n    */\n   public int getAlgorithm() {\n      return algorithm;\n   }\n\n   /**\n    * The fingerprint fptype octet describes the message-digest algorithm used\n    * to calculate the fingerprint of the public key.\n    * \n    * @return most often {@code 1} for {@code SHA-1}\n    */\n   public int getType() {\n      return fptype;\n   }\n\n   /**\n    * The fingerprint calculated over the public key blob.\n    */\n   public String getFingerprint() {\n      return fingerprint;\n   }\n\n   public static final class Builder {\n      private int algorithm;\n      private int fptype;\n      private String fingerprint;\n\n      /**\n       * @see SSHFPData#getAlgorithm()\n       */\n      public SSHFPData.Builder algorithm(int algorithm) {\n         this.algorithm = algorithm;\n         return this;\n      }\n\n      /**\n       * @see SSHFPData#getType()\n       */\n      public SSHFPData.Builder fptype(int fptype) {\n         this.fptype = fptype;\n         return this;\n      }\n\n      /**\n       * @see SSHFPData#getFingerprint()\n       */\n      public SSHFPData.Builder fingerprint(String fingerprint) {\n         this.fingerprint = fingerprint;\n         return this;\n      }\n\n      public SSHFPData build() {\n         return new SSHFPData(algorithm, fptype, fingerprint);\n      }\n   }\n\n   public static SSHFPData.Builder builder() {\n      return new Builder();\n   }\n\n   // transient to avoid serializing by default, for example in json\n   private final transient ImmutableMap<String, Object> delegate;\n\n   @Override\n   protected Map<String, Object> delegate() {\n      return delegate;\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/domain/rdata/TXTData.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.domain.rdata;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Map;\n\nimport com.google.common.collect.ForwardingMap;\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Corresponds to the binary representation of the {@code TXT} (Text) RData\n * \n * <h4>Example</h4>\n * \n * <pre>\n * import static org.jclouds.dynect.v3.domain.rdata.NSData.txt;\n * ...\n * NSData rdata = txt(\"=spf1 ip4:1.1.1.1/24 ip4:2.2.2.2/24 -all\");\n * </pre>\n * \n * @see <a href=\"http://www.ietf.org/rfc/rfc1035.txt\">RFC 1035</a>\n */\npublic class TXTData extends ForwardingMap<String, Object> {\n\n   private final String txtdata;\n\n   @ConstructorProperties(\"txtdata\")\n   private TXTData(String txtdata) {\n      this.txtdata = checkNotNull(txtdata, \"txtdata\");\n      this.delegate = ImmutableMap.<String, Object> of(\"txtdata\", txtdata);\n   }\n\n   /**\n    * One or more character-strings.\n    */\n   public String getTxtdata() {\n      return txtdata;\n   }\n\n   private final transient ImmutableMap<String, Object> delegate;\n\n   protected Map<String, Object> delegate() {\n      return delegate;\n   }\n\n   public static TXTData txt(String txtdata) {\n      return builder().txtdata(txtdata).build();\n   }\n\n   public static TXTData.Builder builder() {\n      return new Builder();\n   }\n\n   public TXTData.Builder toBuilder() {\n      return builder().from(this);\n   }\n\n   public static final class Builder {\n      private String txtdata;\n\n      /**\n       * @see TXTData#getTxtdata()\n       */\n      public TXTData.Builder txtdata(String txtdata) {\n         this.txtdata = txtdata;\n         return this;\n      }\n\n      public TXTData build() {\n         return new TXTData(txtdata);\n      }\n\n      public TXTData.Builder from(TXTData in) {\n         return this.txtdata(in.getTxtdata());\n      }\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/features/GeoRegionGroupApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.dynect.v3.DynECTExceptions.JobStillRunningException;\nimport org.jclouds.dynect.v3.domain.GeoRegionGroup;\nimport org.jclouds.dynect.v3.filters.AlwaysAddContentType;\nimport org.jclouds.dynect.v3.filters.SessionManager;\nimport org.jclouds.dynect.v3.functions.ExtractLastPathComponent;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.Headers;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.Transform;\n\nimport com.google.common.collect.FluentIterable;\n\n/**\n * @see <a\n *      href=\"https://manage.dynect.net/help/docs/api2/rest/resources/Geo.html\"\n *      />\n */\n@Headers(keys = \"API-Version\", values = \"{jclouds.api-version}\")\n@Path(\"/GeoRegionGroup/{serviceName}\")\n@RequestFilters({ AlwaysAddContentType.class, SessionManager.class })\npublic interface GeoRegionGroupApi {\n    /**\n     * Lists all geo region group names.\n     * \n     * @throws JobStillRunningException\n     *            if a different job in the session is still running\n     */\n    @Named(\"ListGeoRegionGroupNames\")\n    @GET\n    @SelectJson(\"data\")\n    @Transform(ExtractLastPathComponent.class)\n    FluentIterable<String> list() throws JobStillRunningException;\n\n    /**\n     * Retrieves information about the specified geo region group\n     * \n     * @param groupName\n     *           name of the group to get information about. ex\n     *           {@code api-prod}\n     * @return null if not found\n     * @throws JobStillRunningException\n     *            if a different job in the session is still running\n     */\n    @Named(\"GetGeoRegionGroup\")\n    @GET\n    @Path(\"/{groupName}\")\n    @SelectJson(\"data\")\n    @Fallback(NullOnNotFoundOr404.class)\n    @Nullable\n    GeoRegionGroup get(@PathParam(\"groupName\") String groupName) throws JobStillRunningException;\n}\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/features/GeoServiceApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.dynect.v3.DynECTExceptions.JobStillRunningException;\nimport org.jclouds.dynect.v3.domain.GeoService;\nimport org.jclouds.dynect.v3.filters.AlwaysAddContentType;\nimport org.jclouds.dynect.v3.filters.SessionManager;\nimport org.jclouds.dynect.v3.functions.ExtractLastPathComponent;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.Headers;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.Transform;\n\nimport com.google.common.collect.FluentIterable;\n\n/**\n * @see <a\n *      href=\"https://manage.dynect.net/help/docs/api2/rest/resources/Geo.html\"\n *      />\n */\n@Headers(keys = \"API-Version\", values = \"{jclouds.api-version}\")\n@Path(\"/Geo\")\n@RequestFilters({ AlwaysAddContentType.class, SessionManager.class })\npublic interface GeoServiceApi {\n    /**\n     * Lists all geo service names.\n     * \n     * @throws JobStillRunningException\n     *            if a different job in the session is still running\n     */\n    @Named(\"ListGeoServiceNames\")\n    @GET\n    @SelectJson(\"data\")\n    @Transform(ExtractLastPathComponent.class)\n    FluentIterable<String> list() throws JobStillRunningException;\n\n    /**\n     * Retrieves information about the specified geo service.\n     * \n     * @param serviceName\n     *           name of the service to get information about. ex\n     *           {@code api-prod}\n     * @return null if not found\n     * @throws JobStillRunningException\n     *            if a different job in the session is still running\n     */\n    @Named(\"GetGeoService\")\n    @GET\n    @Path(\"/{serviceName}\")\n    @SelectJson(\"data\")\n    @Fallback(NullOnNotFoundOr404.class)\n    @Nullable\n    GeoService get(@PathParam(\"serviceName\") String serviceName) throws JobStillRunningException;\n}\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/features/RecordApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.util.Map;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\n\nimport org.jclouds.Fallbacks.EmptyFluentIterableOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.dynect.v3.DynECTExceptions.JobStillRunningException;\nimport org.jclouds.dynect.v3.binders.CreateRecordBinder;\nimport org.jclouds.dynect.v3.binders.RecordIdBinder;\nimport org.jclouds.dynect.v3.domain.CreateRecord;\nimport org.jclouds.dynect.v3.domain.Job;\nimport org.jclouds.dynect.v3.domain.Record;\nimport org.jclouds.dynect.v3.domain.RecordId;\nimport org.jclouds.dynect.v3.domain.SOARecord;\nimport org.jclouds.dynect.v3.domain.rdata.AAAAData;\nimport org.jclouds.dynect.v3.domain.rdata.AData;\nimport org.jclouds.dynect.v3.domain.rdata.CNAMEData;\nimport org.jclouds.dynect.v3.domain.rdata.MXData;\nimport org.jclouds.dynect.v3.domain.rdata.NSData;\nimport org.jclouds.dynect.v3.domain.rdata.PTRData;\nimport org.jclouds.dynect.v3.domain.rdata.SPFData;\nimport org.jclouds.dynect.v3.domain.rdata.SRVData;\nimport org.jclouds.dynect.v3.domain.rdata.SSHFPData;\nimport org.jclouds.dynect.v3.domain.rdata.TXTData;\nimport org.jclouds.dynect.v3.filters.AlwaysAddContentType;\nimport org.jclouds.dynect.v3.filters.SessionManager;\nimport org.jclouds.dynect.v3.functions.ToRecordIds;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.Headers;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\n\nimport com.google.common.collect.FluentIterable;\n\n@Headers(keys = \"API-Version\", values = \"{jclouds.api-version}\")\n@RequestFilters({ AlwaysAddContentType.class, SessionManager.class })\npublic interface RecordApi {\n   /**\n    * Retrieves a list of resource record ids for all records of any type in the\n    * given zone.\n    * \n    * @throws JobStillRunningException\n    *            if a different job in the session is still running\n    */\n   @Named(\"GetAllRecord\")\n   @GET\n   @Path(\"/AllRecord/{zone}\")\n   @ResponseParser(ToRecordIds.class)\n   FluentIterable<RecordId> list() throws JobStillRunningException;\n\n   /**\n    * Retrieves a list of resource record ids for all records of the fqdn in the\n    * given zone\n    * \n    * @throws JobStillRunningException\n    *            if a different job in the session is still running\n    */\n   @Named(\"GetRecord\")\n   @GET\n   @Path(\"/AllRecord/{zone}/{fqdn}\")\n   @ResponseParser(ToRecordIds.class)\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<RecordId> listByFQDN(@PathParam(\"fqdn\") String fqdn) throws JobStillRunningException;\n\n   /**\n    * Retrieves a list of resource record ids for all records of the fqdn and\n    * type in the given zone\n    * \n    * @throws JobStillRunningException\n    *            if a different job in the session is still running\n    */\n   @Named(\"GetRecord\")\n   @GET\n   @Path(\"/{type}Record/{zone}/{fqdn}\")\n   @ResponseParser(ToRecordIds.class)\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<RecordId> listByFQDNAndType(@PathParam(\"fqdn\") String fqdn, @PathParam(\"type\") String type)\n         throws JobStillRunningException;\n\n   /**\n    * Schedules addition of a new record into the current session. Calling\n    * {@link ZoneApi#publish(String)} will publish the zone, creating the\n    * record.\n    * \n    * @param newRecord\n    *           record to create\n    * @return job relating to the scheduled creation.\n    * @throws JobStillRunningException\n    *            if a different job in the session is still running\n    */\n   @Named(\"CreateRecord\")\n   @POST\n   @Path(\"/{type}Record/{zone}/{fqdn}\")\n   @Consumes(APPLICATION_JSON)\n   @Produces(APPLICATION_JSON)\n   Job scheduleCreate(@BinderParam(CreateRecordBinder.class) CreateRecord<?> newRecord) throws JobStillRunningException;\n\n   /**\n    * Schedules deletion of a record into the current session. Calling\n    * {@link ZoneApi#publish(String)} will publish the changes, deleting the\n    * record.\n    * \n    * @param recordId\n    *           record to delete\n    * @return job relating to the scheduled deletion or null, if the record\n    *         never existed.\n    * @throws JobStillRunningException\n    *            if a different job in the session is still running\n    */\n   @Nullable\n   @Named(\"DeleteRecord\")\n   @DELETE\n   @Fallback(NullOnNotFoundOr404.class)\n   @Consumes(APPLICATION_JSON)\n   Job scheduleDelete(@BinderParam(RecordIdBinder.class) RecordId recordId) throws JobStillRunningException;\n\n   /**\n    * retrieves a resource record without regard to type\n    * \n    * @return null if not found\n    * @throws JobStillRunningException\n    *            if a different job in the session is still running\n    */\n   @Named(\"GetRecord\")\n   @GET\n   @SelectJson(\"data\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Record<? extends Map<String, Object>> get(@BinderParam(RecordIdBinder.class) RecordId recordId)\n         throws JobStillRunningException;\n\n   /**\n    * Gets the {@link AAAARecord} or null if not present.\n    * \n    * @param fqdn\n    *           {@link RecordId#getFQDN()}\n    * @param recordId\n    *           {@link RecordId#getId()}\n    * @return null if not found\n    * @throws JobStillRunningException\n    *            if a different job in the session is still running\n    */\n   @Named(\"GetAAAARecord\")\n   @GET\n   @Path(\"/AAAARecord/{zone}/{fqdn}/{id}\")\n   @SelectJson(\"data\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Record<AAAAData> getAAAA(@PathParam(\"fqdn\") String fqdn, @PathParam(\"id\") long recordId)\n         throws JobStillRunningException;\n\n   /**\n    * Gets the {@link ARecord} or null if not present.\n    * \n    * @param fqdn\n    *           {@link RecordId#getFQDN()}\n    * @param recordId\n    *           {@link RecordId#getId()}\n    * @return null if not found\n    * @throws JobStillRunningException\n    *            if a different job in the session is still running\n    */\n   @Named(\"GetARecord\")\n   @GET\n   @Path(\"/ARecord/{zone}/{fqdn}/{id}\")\n   @SelectJson(\"data\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Record<AData> getA(@PathParam(\"fqdn\") String fqdn, @PathParam(\"id\") long recordId) throws JobStillRunningException;\n\n   /**\n    * Gets the {@link CNAMERecord} or null if not present.\n    * \n    * @param fqdn\n    *           {@link RecordId#getFQDN()}\n    * @param recordId\n    *           {@link RecordId#getId()}\n    * @return null if not found\n    * @throws JobStillRunningException\n    *            if a different job in the session is still running\n    */\n   @Named(\"GetCNAMERecord\")\n   @GET\n   @Path(\"/CNAMERecord/{zone}/{fqdn}/{id}\")\n   @SelectJson(\"data\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Record<CNAMEData> getCNAME(@PathParam(\"fqdn\") String fqdn, @PathParam(\"id\") long recordId)\n         throws JobStillRunningException;\n\n   /**\n    * Gets the {@link MXRecord} or null if not present.\n    * \n    * @param fqdn\n    *           {@link RecordId#getFQDN()}\n    * @param recordId\n    *           {@link RecordId#getId()}\n    * @return null if not found\n    * @throws JobStillRunningException\n    *            if a different job in the session is still running\n    */\n   @Named(\"GetMXRecord\")\n   @GET\n   @Path(\"/MXRecord/{zone}/{fqdn}/{id}\")\n   @SelectJson(\"data\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Record<MXData> getMX(@PathParam(\"fqdn\") String fqdn, @PathParam(\"id\") long recordId) throws JobStillRunningException;\n\n   /**\n    * Gets the {@link NSRecord} or null if not present.\n    * \n    * @param fqdn\n    *           {@link RecordId#getFQDN()}\n    * @param recordId\n    *           {@link RecordId#getId()}\n    * @return null if not found\n    * @throws JobStillRunningException\n    *            if a different job in the session is still running\n    */\n   @Named(\"GetNSRecord\")\n   @GET\n   @Path(\"/NSRecord/{zone}/{fqdn}/{id}\")\n   @SelectJson(\"data\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Record<NSData> getNS(@PathParam(\"fqdn\") String fqdn, @PathParam(\"id\") long recordId) throws JobStillRunningException;\n\n   /**\n    * Gets the {@link PTRRecord} or null if not present.\n    * \n    * @param fqdn\n    *           {@link RecordId#getFQDN()}\n    * @param recordId\n    *           {@link RecordId#getId()}\n    * @return null if not found\n    * @throws JobStillRunningException\n    *            if a different job in the session is still running\n    */\n   @Named(\"GetPTRRecord\")\n   @GET\n   @Path(\"/PTRRecord/{zone}/{fqdn}/{id}\")\n   @SelectJson(\"data\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Record<PTRData> getPTR(@PathParam(\"fqdn\") String fqdn, @PathParam(\"id\") long recordId)\n         throws JobStillRunningException;\n\n   /**\n    * Gets the {@link SOARecord} or null if not present.\n    * \n    * @param fqdn\n    *           {@link RecordId#getFQDN()}\n    * @param recordId\n    *           {@link RecordId#getId()}\n    * @return null if not found\n    * @throws JobStillRunningException\n    *            if a different job in the session is still running\n    */\n   @Named(\"GetSOARecord\")\n   @GET\n   @Path(\"/SOARecord/{zone}/{fqdn}/{id}\")\n   @SelectJson(\"data\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   SOARecord getSOA(@PathParam(\"fqdn\") String fqdn, @PathParam(\"id\") long recordId) throws JobStillRunningException;\n\n   /**\n    * Gets the {@link SPFRecord} or null if not present.\n    * \n    * @param fqdn\n    *           {@link RecordId#getFQDN()}\n    * @param recordId\n    *           {@link RecordId#getId()}\n    * @return null if not found\n    * @throws JobStillRunningException\n    *            if a different job in the session is still running\n    */\n   @Named(\"GetSPFRecord\")\n   @GET\n   @Path(\"/SPFRecord/{zone}/{fqdn}/{id}\")\n   @SelectJson(\"data\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Record<SPFData> getSPF(@PathParam(\"fqdn\") String fqdn, @PathParam(\"id\") long recordId)\n         throws JobStillRunningException;\n\n   /**\n    * Gets the {@link SRVRecord} or null if not present.\n    * \n    * @param fqdn\n    *           {@link RecordId#getFQDN()}\n    * @param recordId\n    *           {@link RecordId#getId()}\n    * @return null if not found\n    * @throws JobStillRunningException\n    *            if a different job in the session is still running\n    */\n   @Named(\"GetSRVRecord\")\n   @GET\n   @Path(\"/SRVRecord/{zone}/{fqdn}/{id}\")\n   @SelectJson(\"data\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Record<SRVData> getSRV(@PathParam(\"fqdn\") String fqdn, @PathParam(\"id\") long recordId)\n         throws JobStillRunningException;\n\n   /**\n    * Gets the {@link SSHFPRecord} or null if not present.\n    * \n    * @param fqdn\n    *           {@link RecordId#getFQDN()}\n    * @param recordId\n    *           {@link RecordId#getId()}\n    * @return null if not found\n    * @throws JobStillRunningException\n    *            if a different job in the session is still running\n    */\n   @Named(\"GetSSHFPRecord\")\n   @GET\n   @Path(\"/SSHFPRecord/{zone}/{fqdn}/{id}\")\n   @SelectJson(\"data\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Record<SSHFPData> getSSHFP(@PathParam(\"fqdn\") String fqdn, @PathParam(\"id\") long recordId)\n         throws JobStillRunningException;\n\n   /**\n    * Gets the {@link TXTRecord} or null if not present.\n    * \n    * @param fqdn\n    *           {@link RecordId#getFQDN()}\n    * @param recordId\n    *           {@link RecordId#getId()}\n    * @return null if not found\n    * @throws JobStillRunningException\n    *            if a different job in the session is still running\n    */\n   @Named(\"GetTXTRecord\")\n   @GET\n   @Path(\"/TXTRecord/{zone}/{fqdn}/{id}\")\n   @SelectJson(\"data\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Record<TXTData> getTXT(@PathParam(\"fqdn\") String fqdn, @PathParam(\"id\") long recordId)\n         throws JobStillRunningException;\n}\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/features/SessionApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.HeaderParam;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\n\nimport org.jclouds.dynect.v3.DynECTFallbacks.FalseOn400;\nimport org.jclouds.dynect.v3.domain.Session;\nimport org.jclouds.dynect.v3.domain.SessionCredentials;\nimport org.jclouds.dynect.v3.filters.AlwaysAddContentType;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.Headers;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\n/**\n * @see <a\n *      href=\"https://manage.dynect.net/help/docs/api2/rest/resources/Session.html\"\n *      />\n */\n@Headers(keys = \"API-Version\", values = \"{jclouds.api-version}\")\n@Path(\"/Session\")\n@RequestFilters(AlwaysAddContentType.class)\npublic interface SessionApi {\n\n   @Named(\"POST:Session\")\n   @POST\n   @SelectJson(\"data\")\n   Session login(@BinderParam(BindToJsonPayload.class) SessionCredentials credentials);\n\n   @Named(\"GET:Session\")\n   @GET\n   @Fallback(FalseOn400.class)\n   boolean isValid(@HeaderParam(\"Auth-Token\") String token);\n\n   @Named(\"DELETE:Session\")\n   @DELETE\n   void logout(@HeaderParam(\"Auth-Token\") String token);\n}\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/features/ZoneApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.dynect.v3.DynECTExceptions.JobStillRunningException;\nimport org.jclouds.dynect.v3.DynECTExceptions.TargetExistsException;\nimport org.jclouds.dynect.v3.domain.CreatePrimaryZone;\nimport org.jclouds.dynect.v3.domain.CreatePrimaryZone.ToFQDN;\nimport org.jclouds.dynect.v3.domain.Job;\nimport org.jclouds.dynect.v3.domain.Zone;\nimport org.jclouds.dynect.v3.filters.AlwaysAddContentType;\nimport org.jclouds.dynect.v3.filters.SessionManager;\nimport org.jclouds.dynect.v3.functions.ExtractLastPathComponent;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.Headers;\nimport org.jclouds.rest.annotations.ParamParser;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.Transform;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport com.google.common.collect.FluentIterable;\n\n@Headers(keys = \"API-Version\", values = \"{jclouds.api-version}\")\n@RequestFilters({ AlwaysAddContentType.class, SessionManager.class })\npublic interface ZoneApi {\n   /**\n    * Lists all zone ids.\n    * \n    * @throws JobStillRunningException\n    *            if a different job in the session is still running\n    */\n   @Named(\"ListZones\")\n   @GET\n   @Path(\"/Zone\")\n   @SelectJson(\"data\")\n   @Transform(ExtractLastPathComponent.class)\n   FluentIterable<String> list() throws JobStillRunningException;\n\n   /**\n    * Schedules addition of a new primary zone into the current session. Calling\n    * {@link ZoneApi#publish(String)} will publish the zone, creating the zone.\n    * \n    * @param zone\n    *           required parameters to create the zone.\n    * @return job relating to the scheduled creation.\n    * @throws JobStillRunningException\n    *            if a different job in the session is still running\n    * @throws TargetExistsException\n    *            if the same fqdn exists\n    */\n   @Named(\"CreatePrimaryZone\")\n   @POST\n   @Path(\"/Zone/{fqdn}\")\n   @Consumes(APPLICATION_JSON)\n   Job scheduleCreate(\n         @PathParam(\"fqdn\") @ParamParser(ToFQDN.class) @BinderParam(BindToJsonPayload.class) CreatePrimaryZone createZone)\n         throws JobStillRunningException, TargetExistsException;\n\n   /**\n    * Schedules addition of a new primary zone with one hour default TTL and\n    * {@link SerialStyle#INCREMENT} into the current session. Calling\n    * {@link ZoneApi#publish(String)} will publish the zone, creating the zone.\n    * \n    * @param fqdn\n    *           fqdn of the zone to create {@ex. jclouds.org}\n    * @param contact\n    *           email address of the contact\n    * @return job relating to the scheduled creation.\n    * @throws JobStillRunningException\n    *            if a different job in the session is still running\n    * @throws TargetExistsException\n    *            if the same fqdn exists\n    */\n   @Named(\"CreatePrimaryZone\")\n   @POST\n   @Produces(APPLICATION_JSON)\n   @Payload(\"%7B\\\"rname\\\":\\\"{contact}\\\",\\\"serial_style\\\":\\\"increment\\\",\\\"ttl\\\":3600%7D\")\n   @Path(\"/Zone/{fqdn}\")\n   @Consumes(APPLICATION_JSON)\n   Job scheduleCreateWithContact(@PathParam(\"fqdn\") String fqdn, @PayloadParam(\"contact\") String contact)\n         throws JobStillRunningException, TargetExistsException;\n\n   /**\n    * Retrieves information about the specified zone.\n    * \n    * @param fqdn\n    *           fqdn of the zone to get information about. ex\n    *           {@code jclouds.org}\n    * @return null if not found\n    * @throws JobStillRunningException\n    *            if a different job in the session is still running\n    */\n   @Named(\"GetZone\")\n   @GET\n   @Path(\"/Zone/{fqdn}\")\n   @SelectJson(\"data\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Zone get(@PathParam(\"fqdn\") String fqdn) throws JobStillRunningException;\n\n   /**\n    * Deletes the zone. No need to call @link ZoneApi#publish(String)}.\n    * \n    * @param fqdn\n    *           zone to delete\n    * @return job relating to the scheduled deletion or null, if the zone never\n    *         existed.\n    * @throws JobStillRunningException\n    *            if a different job in the session is still running\n    */\n   @Named(\"DeleteZone\")\n   @DELETE\n   @Path(\"/Zone/{fqdn}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Consumes(APPLICATION_JSON)\n   @Nullable\n   Job delete(@PathParam(\"fqdn\") String fqdn) throws JobStillRunningException;\n\n   /**\n    * Deletes changes to the specified zone that have been created during the\n    * current session but not yet published to the zone.\n    * \n    * @param fqdn\n    *           fqdn of the zone to delete changes from ex {@code jclouds.org}\n    * @throws JobStillRunningException\n    *            if a different job in the session is still running\n    */\n   @Named(\"DeleteZoneChanges\")\n   @DELETE\n   @Path(\"/ZoneChanges/{fqdn}\")\n   @Consumes(APPLICATION_JSON)\n   Job deleteChanges(@PathParam(\"fqdn\") String fqdn) throws JobStillRunningException;\n\n   /**\n    * Publishes the current zone\n    * \n    * @param fqdn\n    *           fqdn of the zone to publish. ex {@code jclouds.org}\n    * @throws JobStillRunningException\n    *            if a different job in the session is still running\n    * @throws ResourceNotFoundException\n    *            if the zone doesn't exist\n    */\n   @Named(\"PublishZone\")\n   @PUT\n   @Path(\"/Zone/{fqdn}\")\n   @Produces(APPLICATION_JSON)\n   @Payload(\"{\\\"publish\\\":true}\")\n   @SelectJson(\"data\")\n   Zone publish(@PathParam(\"fqdn\") String fqdn) throws JobStillRunningException, ResourceNotFoundException;\n\n   /**\n    * freezes the specified zone.\n    * \n    * @param fqdn\n    *           fqdn of the zone to freeze ex {@code jclouds.org}\n    * @throws JobStillRunningException\n    *            if a different job in the session is still running\n    */\n   @Named(\"FreezeZone\")\n   @PUT\n   @Path(\"/Zone/{fqdn}\")\n   @Produces(APPLICATION_JSON)\n   @Payload(\"{\\\"freeze\\\":true}\")\n   @Consumes(APPLICATION_JSON)\n   Job freeze(@PathParam(\"fqdn\") String fqdn) throws JobStillRunningException;\n\n   /**\n    * thaws the specified zone.\n    * \n    * @param fqdn\n    *           fqdn of the zone to thaw ex {@code jclouds.org}\n    * @throws JobStillRunningException\n    *            if a different job in the session is still running\n    */\n   @Named(\"ThawZone\")\n   @PUT\n   @Path(\"/Zone/{fqdn}\")\n   @Produces(APPLICATION_JSON)\n   @Payload(\"{\\\"thaw\\\":true}\")\n   @Consumes(APPLICATION_JSON)\n   Job thaw(@PathParam(\"fqdn\") String fqdn) throws JobStillRunningException;\n}\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/filters/AlwaysAddContentType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.filters;\n\nimport static com.google.common.net.HttpHeaders.CONTENT_TYPE;\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\nimport static org.jclouds.http.HttpRequest.NON_PAYLOAD_METHODS;\n\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpRequestFilter;\n\n/**\n * \n * DynECT requires Content-Type even on GET requests.\n */\npublic final class AlwaysAddContentType implements HttpRequestFilter {\n   @Override\n   public HttpRequest filter(HttpRequest request) throws HttpException {\n      if (NON_PAYLOAD_METHODS.contains(request.getMethod()))\n         return request.toBuilder().replaceHeader(CONTENT_TYPE, APPLICATION_JSON).build();\n      return request;\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/filters/SessionManager.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.filters;\n\nimport static org.jclouds.http.HttpUtils.closeClientButKeepContentStream;\nimport static org.jclouds.http.HttpUtils.releasePayload;\n\nimport jakarta.annotation.PreDestroy;\nimport jakarta.annotation.Resource;\n\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.dynect.v3.domain.Session;\nimport org.jclouds.dynect.v3.domain.SessionCredentials;\nimport org.jclouds.dynect.v3.features.SessionApi;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpRequest.Builder;\nimport org.jclouds.http.HttpRequestFilter;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.handlers.BackoffLimitedRetryHandler;\nimport org.jclouds.location.Provider;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.inject.Inject;\nimport com.google.inject.Singleton;\n\n/**\n * \n * This class manages session interactions, including grabbing latest from the\n * cache, and invalidating upon 401 If the credentials supplied in the\n * authentication header are invalid, or if the token has expired, the server\n * returns HTTP response code 401. After the token expires, you must log in\n * again to obtain a new token.\n */\n@Singleton\npublic final class SessionManager extends BackoffLimitedRetryHandler implements HttpRequestFilter {\n\n   @Resource\n   private Logger logger = Logger.NULL;\n\n   private final Supplier<Credentials> creds;\n   private final SessionApi sessionApi;\n   private final LoadingCache<Credentials, Session> sessionCache;\n\n   @Inject\n   SessionManager(@Provider Supplier<Credentials> creds, SessionApi sessionApi) {\n      this(creds, buildCache(sessionApi), sessionApi);\n   }\n\n   SessionManager(@Provider Supplier<Credentials> creds, LoadingCache<Credentials, Session> sessionCache,\n         SessionApi sessionApi) {\n      this.creds = creds;\n      this.sessionCache = sessionCache;\n      this.sessionApi = sessionApi;\n   }\n\n   static LoadingCache<Credentials, Session> buildCache(final SessionApi sessionApi) {\n      return CacheBuilder.newBuilder().build(new CacheLoader<Credentials, Session>() {\n         public Session load(Credentials key) {\n            return sessionApi.login(convert(key));\n         }\n      });\n   }\n\n   static SessionCredentials convert(Credentials key) {\n      if (key instanceof SessionCredentials)\n         return SessionCredentials.class.cast(key);\n      return SessionCredentials.builder().customerName(key.identity.substring(0, key.identity.indexOf(':')))\n            .userName(key.identity.substring(key.identity.indexOf(':') + 1)).password(key.credential).build();\n   }\n\n   @Override\n   public HttpRequest filter(HttpRequest request) throws HttpException {\n      Session session = sessionCache.getUnchecked(creds.get());\n      Builder<?> builder = request.toBuilder();\n      builder.replaceHeader(\"Auth-Token\", session.getToken());\n      return builder.build();\n   }\n\n   private static final String IP_MISMATCH = \"IP address does not match current session\";\n\n   @Override\n   public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) {\n      boolean retry = false; // default\n      try {\n         byte[] data = closeClientButKeepContentStream(response);\n         String message = data != null ? new String(data) : null;\n         if (response.getStatusCode() == 401 || (message != null && message.indexOf(IP_MISMATCH) != -1)) {\n            logger.debug(\"invalidating session\");\n            sessionCache.invalidateAll();\n            retry = super.shouldRetryRequest(command, response);\n         }\n         return retry;\n      } finally {\n         releasePayload(response);\n      }\n   }\n\n   /**\n    * it is important that we close any sessions on close to help the server not\n    * become overloaded.\n    */\n   @PreDestroy\n   public void logoutOnClose() {\n      for (Session s : sessionCache.asMap().values()) {\n         try {\n            sessionApi.logout(s.getToken());\n         } catch (Exception e) {\n            logger.error(e, \"error logging out session %s\", s);\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/functions/ExtractLastPathComponent.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.functions;\n\nimport static com.google.common.base.Preconditions.checkState;\n\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.FluentIterable;\n\n/**\n * Zones, Geo Services, and Geo region groups come back encoded in REST paths, such as\n * {@code /REST/Geo/srv-global/}\n */\npublic final class ExtractLastPathComponent implements Function<FluentIterable<String>, FluentIterable<String>> {\n   public FluentIterable<String> apply(FluentIterable<String> in) {\n      return in.transform(ExtractNameInPath.INSTANCE);\n   }\n\n   static enum ExtractNameInPath implements Function<String, String> {\n      INSTANCE;\n      public static final Pattern DEFAULT_PATTERN = Pattern.compile(\"/REST.*/([^/]+)/?$\");\n\n      public String apply(String in) {\n         Matcher matcher = DEFAULT_PATTERN.matcher(in);\n         checkState(matcher.find() && matcher.groupCount() == 1, \"%s didn't match %s\", in, DEFAULT_PATTERN);\n         return matcher.group(1);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/functions/ToRecordIds.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static org.jclouds.dynect.v3.domain.RecordId.recordIdBuilder;\n\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport org.jclouds.dynect.v3.domain.RecordId;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseFirstJsonValueNamed;\nimport org.jclouds.json.internal.GsonWrapper;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.FluentIterable;\nimport com.google.inject.Inject;\nimport com.google.inject.TypeLiteral;\n\n/**\n * Records come back encoded in REST paths, such as\n * {@code /REST/NSRecord/adrianc.zone.dynecttest.jclouds.org/adrianc.zone.dynecttest.jclouds.org/50976583}\n */\npublic final class ToRecordIds implements Function<HttpResponse, FluentIterable<RecordId>> {\n   private final ParseFirstJsonValueNamed<FluentIterable<String>> parser;\n\n   @Inject\n   public ToRecordIds(GsonWrapper gsonView) {\n      this.parser = new ParseFirstJsonValueNamed<FluentIterable<String>>(checkNotNull(gsonView, \"gsonView\"),\n            new TypeLiteral<FluentIterable<String>>() {\n            }, \"data\");\n   }\n\n   public FluentIterable<RecordId> apply(HttpResponse response) {\n      checkNotNull(response, \"response\");\n      return parser.apply(response).transform(ParsePath.INSTANCE);\n   }\n\n   static enum ParsePath implements Function<String, RecordId> {\n      INSTANCE;\n      public static final Pattern DEFAULT_PATTERN = Pattern.compile(\"/REST/([a-zA-Z]+)Record/(.*)/(.*)/([0-9]+)\");\n\n      public RecordId apply(String in) {\n         Matcher matcher = DEFAULT_PATTERN.matcher(in);\n         checkState(matcher.find() && matcher.groupCount() == 4, \"%s didn't match %s\", in, DEFAULT_PATTERN);\n         return recordIdBuilder().type(matcher.group(1)).zone(matcher.group(2)).fqdn(matcher.group(3))\n               .id(Long.parseLong(matcher.group(4))).build();\n      }\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/handlers/DynECTErrorHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.handlers;\n\nimport static org.jclouds.http.HttpUtils.closeClientButKeepContentStream;\nimport static org.jclouds.http.HttpUtils.releasePayload;\n\nimport org.jclouds.dynect.v3.DynECTExceptions.TargetExistsException;\nimport org.jclouds.dynect.v3.DynECTExceptions.JobStillRunningException;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\n\npublic class DynECTErrorHandler implements HttpErrorHandler {\n   private static final String JOB_STILL_RUNNING = \"This session already has a job running\";\n   private static final String OPERATION_BLOCKED = \"Operation blocked by current task\";\n   private static final String TARGET_EXISTS = \"Name already exists\";\n   \n   public void handleError(HttpCommand command, HttpResponse response) {\n      Exception exception = new HttpResponseException(command, response);\n      try {\n         byte[] data = closeClientButKeepContentStream(response);\n         String message = data != null ? new String(data) : null;\n         if (message != null) {\n            exception = new HttpResponseException(command, response, message);\n            if (message.indexOf(JOB_STILL_RUNNING) != -1)\n               exception = new JobStillRunningException(JOB_STILL_RUNNING, exception);\n            else if (message.indexOf(OPERATION_BLOCKED) != -1)\n               exception = new JobStillRunningException(OPERATION_BLOCKED, exception);\n            else if (message.indexOf(TARGET_EXISTS) != -1)\n               exception = new TargetExistsException(TARGET_EXISTS, exception);\n         } else {\n            exception = new HttpResponseException(command, response);\n         }\n      } finally {\n         releasePayload(response);\n         command.setException(exception);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/handlers/GetJobRedirectionRetryHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.handlers;\nimport static com.google.common.net.HttpHeaders.LOCATION;\nimport static jakarta.ws.rs.HttpMethod.GET;\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.handlers.BackoffLimitedRetryHandler;\nimport org.jclouds.http.handlers.RedirectionRetryHandler;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\n\n/**\n * if the redirection URL is a Job, do not replay the original request; just get\n * the job.\n */\n@Singleton\npublic class GetJobRedirectionRetryHandler extends RedirectionRetryHandler {\n   \n   private final Payload emptyPayload;\n\n   @Inject\n   protected GetJobRedirectionRetryHandler(BackoffLimitedRetryHandler backoffHandler) {\n      super(backoffHandler);\n      this.emptyPayload = Payloads.newPayload(new byte[]{});\n      this.emptyPayload.getContentMetadata().setContentType(APPLICATION_JSON);     \n   }\n\n   @Override\n   public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) {\n      String location = response.getFirstHeaderOrNull(LOCATION);\n      if (location != null && location.indexOf(\"Job\") != -1) {\n         HttpRequest getRequest = command.getCurrentRequest().toBuilder()\n                                                             .method(GET)\n                                                             .payload((Payload) null).build();\n         command.setCurrentRequest(getRequest);\n      }\n      return super.shouldRetryRequest(command, response);\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/loaders/LoginUserInOrgWithPassword.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.loaders;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.dynect.v3.domain.Session;\nimport org.jclouds.dynect.v3.domain.SessionCredentials;\nimport org.jclouds.dynect.v3.features.SessionApi;\n\nimport com.google.common.cache.CacheLoader;\n\n@Singleton\npublic class LoginUserInOrgWithPassword extends CacheLoader<SessionCredentials, Session> {\n   private final SessionApi api;\n\n   @Inject\n   LoginUserInOrgWithPassword(SessionApi api) {\n      this.api = api;\n   }\n\n   @Override\n   public Session load(SessionCredentials input) {\n      return api.login(input);\n   }\n\n   @Override\n   public String toString() {\n      return \"loginUserInOrgWithPassword()\";\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/main/java/org/jclouds/dynect/v3/predicates/RecordPredicates.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.dynect.v3.domain.RecordId;\n\nimport com.google.common.base.Predicate;\n\n/**\n * Predicates handy when working with Records\n */\npublic class RecordPredicates {\n\n   /**\n    * matches type of the given record\n    * \n    * @param type\n    * @return predicate that matches type\n    */\n   public static <R extends RecordId> Predicate<R> typeEquals(final String type) {\n      checkNotNull(type, \"type must be defined\");\n\n      return new Predicate<R>() {\n         @Override\n         public boolean apply(R record) {\n            return type.equals(record.getType());\n         }\n\n         @Override\n         public String toString() {\n            return \"typeEquals(\" + type + \")\";\n         }\n      };\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/test/java/org/jclouds/dynect/v3/DynECTProviderMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3;\n\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"DynECTProviderMetadataTest\")\npublic class DynECTProviderMetadataTest extends BaseProviderMetadataTest {\n   public DynECTProviderMetadataTest() {\n      super(new DynECTProviderMetadata(), new DynECTApiMetadata());\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/test/java/org/jclouds/dynect/v3/DynectApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3;\n\nimport static com.google.common.util.concurrent.MoreExecutors.newDirectExecutorService;\nimport static jakarta.ws.rs.core.Response.Status.OK;\nimport static org.jclouds.Constants.PROPERTY_MAX_RETRIES;\n\nimport java.io.IOException;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.concurrent.config.ExecutorServiceModule;\nimport org.jclouds.dynect.v3.DynECTExceptions.JobStillRunningException;\nimport org.jclouds.dynect.v3.DynECTExceptions.TargetExistsException;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n\n@Test(singleThreaded = true)\npublic class DynectApiMockTest {\n   \n   private static final Set<Module> modules = ImmutableSet.<Module> of(\n         new ExecutorServiceModule(newDirectExecutorService()));\n\n   static DynECTApi mockDynectApi(String uri) {\n      Properties overrides = new Properties();\n      overrides.setProperty(PROPERTY_MAX_RETRIES, \"1\");\n      return ContextBuilder.newBuilder(\"dynect\")\n                           .credentials(\"jclouds:joe\", \"letmein\")\n                           .endpoint(uri)\n                           .overrides(overrides)\n                           .modules(modules)\n                           .buildApi(DynECTApi.class);\n   }\n\n   String session = \"{\\\"status\\\": \\\"success\\\", \\\"data\\\": {\\\"token\\\": \\\"FFFFFFFFFF\\\", \\\"version\\\": \\\"3.3.8\\\"}, \\\"job_id\\\": 254417252, \\\"msgs\\\": [{\\\"INFO\\\": \\\"login: Login successful\\\", \\\"SOURCE\\\": \\\"BLL\\\", \\\"ERR_CD\\\": null, \\\"LVL\\\": \\\"INFO\\\"}]}\";\n\n   String running = \"{\\\"status\\\": \\\"running\\\", \\\"data\\\": {}, \\\"job_id\\\": 274509427, \\\"msgs\\\": [{\\\"INFO\\\": \\\"token: This session already has a job running\\\", \\\"SOURCE\\\": \\\"API-B\\\", \\\"ERR_CD\\\": \\\"OPERATION_FAILED\\\", \\\"LVL\\\": \\\"ERROR\\\"}]}\";\n\n   @Test(expectedExceptions = JobStillRunningException.class, expectedExceptionsMessageRegExp = \"This session already has a job running\")\n   public void test200OnFailureThrowsExceptionWithoutRetryWhenJobRunning() throws IOException, InterruptedException {\n      MockWebServer server = new MockWebServer();\n      server.enqueue(new MockResponse().setResponseCode(OK.getStatusCode()).setBody(session));\n      server.enqueue(new MockResponse().setResponseCode(OK.getStatusCode()).setBody(running));\n      server.start();\n\n      DynECTApi api = mockDynectApi(server.url(\"/\").toString());\n\n      try {\n         api.getZoneApi().list();\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   String taskBlocking = \"[{\\\"status\\\": \\\"failure\\\", \\\"data\\\": {}, \\\"job_id\\\": 275545493, \\\"msgs\\\": [{\\\"INFO\\\": \\\"zone: Operation blocked by current task\\\", \\\"SOURCE\\\": \\\"BLL\\\", \\\"ERR_CD\\\": \\\"ILLEGAL_OPERATION\\\", \\\"LVL\\\": \\\"ERROR\\\"}, {\\\"INFO\\\": \\\"task_name: ProvisionZone\\\", \\\"SOURCE\\\": \\\"BLL\\\", \\\"ERR_CD\\\": null, \\\"LVL\\\": \\\"INFO\\\"}, {\\\"INFO\\\": \\\"task_id: 39120953\\\", \\\"SOURCE\\\": \\\"BLL\\\", \\\"ERR_CD\\\": null, \\\"LVL\\\": \\\"INFO\\\"}]}]\";\n\n   @Test(expectedExceptions = JobStillRunningException.class, expectedExceptionsMessageRegExp = \"Operation blocked by current task\")\n   public void test200OnFailureThrowsExceptionWithoutRetryWhenOperationBlocked() throws IOException,\n         InterruptedException {\n      MockWebServer server = new MockWebServer();\n      server.enqueue(new MockResponse().setResponseCode(OK.getStatusCode()).setBody(session));\n      server.enqueue(new MockResponse().setResponseCode(OK.getStatusCode()).setBody(taskBlocking));\n      server.start();\n\n      DynECTApi api = mockDynectApi(server.url(\"/\").toString());\n\n      try {\n         api.getZoneApi().list();\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   String targetExists = \"[{\\\"status\\\": \\\"failure\\\", \\\"data\\\": {}, \\\"job_id\\\": 275533917, \\\"msgs\\\": [{\\\"INFO\\\": \\\"name: Name already exists\\\", \\\"SOURCE\\\": \\\"BLL\\\", \\\"ERR_CD\\\": \\\"TARGET_EXISTS\\\", \\\"LVL\\\": \\\"ERROR\\\"}, {\\\"INFO\\\": \\\"create: You already have this zone.\\\", \\\"SOURCE\\\": \\\"BLL\\\", \\\"ERR_CD\\\": null, \\\"LVL\\\": \\\"INFO\\\"}]}]\";\n\n   @Test(expectedExceptions = TargetExistsException.class, expectedExceptionsMessageRegExp = \"Name already exists\")\n   public void test200OnFailureThrowsExceptionWithoutRetryOnNameExists() throws IOException, InterruptedException {\n      MockWebServer server = new MockWebServer();\n      server.enqueue(new MockResponse().setResponseCode(OK.getStatusCode()).setBody(session));\n      server.enqueue(new MockResponse().setResponseCode(OK.getStatusCode()).setBody(targetExists));\n      server.start();\n\n      DynECTApi api = mockDynectApi(server.url(\"/\").toString());\n\n      try {\n         api.getZoneApi().list();\n      } finally {\n         server.shutdown();\n      }\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/test/java/org/jclouds/dynect/v3/features/GeoRegionGroupApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.features;\n\nimport static com.google.common.net.HttpHeaders.CONTENT_TYPE;\nimport static jakarta.ws.rs.HttpMethod.GET;\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\nimport static jakarta.ws.rs.core.Response.Status.OK;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.dynect.v3.DynECTApi;\nimport org.jclouds.dynect.v3.internal.BaseDynECTApiExpectTest;\nimport org.jclouds.dynect.v3.parse.ListGeoRegionGroupsResponseTest;\nimport org.jclouds.dynect.v3.parse.GetGeoRegionGroupResponseTest;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"GeoRegionGroupApiExpectTest\")\npublic class GeoRegionGroupApiExpectTest extends BaseDynECTApiExpectTest {\n\n   HttpRequest list = HttpRequest.builder().method(GET).endpoint(\"https://api2.dynect.net/REST/GeoRegionGroup/srv\")\n         .addHeader(\"API-Version\", \"3.3.8\").addHeader(CONTENT_TYPE, APPLICATION_JSON)\n         .addHeader(\"Auth-Token\", authToken).build();\n\n   HttpResponse listResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/list_geo_regiongroups.json\", APPLICATION_JSON)).build();\n\n   public void testListWhenResponseIs2xx() {\n      DynECTApi success = requestsSendResponses(createSession, createSessionResponse, list, listResponse);\n      assertEquals(success.getGeoRegionGroupApiForService(\"srv\").list().toString(),\n            new ListGeoRegionGroupsResponseTest().expected().toString());\n   }\n\n   HttpRequest get = HttpRequest.builder().method(GET)\n         .endpoint(\"https://api2.dynect.net/REST/GeoRegionGroup/srv/Everywhere%20Else\")\n         .addHeader(\"API-Version\", \"3.3.8\").addHeader(CONTENT_TYPE, APPLICATION_JSON)\n         .addHeader(\"Auth-Token\", authToken).build();\n\n   HttpResponse getResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/get_geo_regiongroup.json\", APPLICATION_JSON)).build();\n\n   public void testGetWhenResponseIs2xx() {\n      DynECTApi success = requestsSendResponses(createSession, createSessionResponse, get, getResponse);\n      assertEquals(success.getGeoRegionGroupApiForService(\"srv\").get(\"Everywhere Else\").toString(),\n            new GetGeoRegionGroupResponseTest().expected().toString());\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/test/java/org/jclouds/dynect/v3/features/GeoRegionGroupApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.features;\n\nimport static java.util.logging.Logger.getAnonymousLogger;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.dynect.v3.domain.RecordSet;\nimport org.jclouds.dynect.v3.domain.RecordSet.Value;\nimport org.jclouds.dynect.v3.domain.GeoRegionGroup;\nimport org.jclouds.dynect.v3.internal.BaseDynECTApiLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"GeoRegionGroupApiLiveTest\")\npublic class GeoRegionGroupApiLiveTest extends BaseDynECTApiLiveTest {\n\n   @Test\n   protected void testListAndGetGeoRegionGroups() {\n      for (String service : geoApi().list()) {\n         GeoRegionGroupApi api = api(service);\n         ImmutableList<String> groups = api.list().toList();\n         getAnonymousLogger().info(\"geo service: \" + service + \" group count: \" + groups.size());\n         for (String group : groups) {\n            GeoRegionGroup groupDetail = api.get(group);\n            assertNotNull(groupDetail.getServiceName().get(), \"ServiceName cannot be null \" + groupDetail);\n            checkGeoRegionGroup(groupDetail);\n         }\n      }\n   }\n\n   static void checkGeoRegionGroup(GeoRegionGroup group) {\n      assertNotNull(group.getName(), \"Name cannot be null \" + group);\n      assertTrue(!group.getCountries().isEmpty(), \"countries must be assigned \" + group);\n      assertTrue(!group.getRecordSets().isEmpty(), \"RecordSets must be assigned \" + group);\n      for (RecordSet recordSet : group.getRecordSets())\n         checkRecordSet(recordSet);\n   }\n\n   static void checkRecordSet(RecordSet rset) {\n      assertNotNull(rset.getType(), \"Type cannot be null \" + rset);\n      assertTrue(rset.getTTL() >= 0, \"TTL cannot be negative \" + rset);\n      for (Value value : rset)\n         checkValue(value);\n   }\n\n   static void checkValue(Value value) {\n      assertNotNull(value.getLabel(), \"Label cannot be null \" + value);\n      assertNotNull(value.getWeight(), \"Weight cannot be null \" + value);\n      assertTrue(!value.getRData().isEmpty(), \"RData entries should be present: \" + value);\n   }\n\n   protected GeoRegionGroupApi api(String serviceName) {\n      return api.getGeoRegionGroupApiForService(serviceName);\n   }\n\n   protected GeoServiceApi geoApi() {\n      return api.getGeoServiceApi();\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/test/java/org/jclouds/dynect/v3/features/GeoServiceApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.features;\n\nimport static com.google.common.net.HttpHeaders.CONTENT_TYPE;\nimport static jakarta.ws.rs.HttpMethod.GET;\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\nimport static jakarta.ws.rs.core.Response.Status.OK;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.dynect.v3.DynECTApi;\nimport org.jclouds.dynect.v3.internal.BaseDynECTApiExpectTest;\nimport org.jclouds.dynect.v3.parse.GetGeoServiceResponseTest;\nimport org.jclouds.dynect.v3.parse.ListGeoServicesResponseTest;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"GeoServiceApiExpectTest\")\npublic class GeoServiceApiExpectTest extends BaseDynECTApiExpectTest {\n\n   HttpRequest list = HttpRequest.builder().method(GET).endpoint(\"https://api2.dynect.net/REST/Geo\")\n         .addHeader(\"API-Version\", \"3.3.8\").addHeader(CONTENT_TYPE, APPLICATION_JSON)\n         .addHeader(\"Auth-Token\", authToken).build();\n\n   HttpResponse listResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/list_geo_services.json\", APPLICATION_JSON)).build();\n\n   public void testListWhenResponseIs2xx() {\n      DynECTApi success = requestsSendResponses(createSession, createSessionResponse, list, listResponse);\n      assertEquals(success.getGeoServiceApi().list().toString(), new ListGeoServicesResponseTest().expected()\n            .toString());\n   }\n\n   HttpRequest get = HttpRequest.builder().method(GET).endpoint(\"https://api2.dynect.net/REST/Geo/srv\")\n         .addHeader(\"API-Version\", \"3.3.8\").addHeader(CONTENT_TYPE, APPLICATION_JSON)\n         .addHeader(\"Auth-Token\", authToken).build();\n\n   HttpResponse getResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/get_geo_service.json\", APPLICATION_JSON)).build();\n\n   public void testGetWhenResponseIs2xx() {\n      DynECTApi success = requestsSendResponses(createSession, createSessionResponse, get, getResponse);\n      assertEquals(success.getGeoServiceApi().get(\"srv\").toString(), new GetGeoServiceResponseTest().expected()\n            .toString());\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/test/java/org/jclouds/dynect/v3/features/GeoServiceApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.features;\n\nimport static java.util.logging.Logger.getAnonymousLogger;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.dynect.v3.domain.GeoService;\nimport org.jclouds.dynect.v3.domain.GeoRegionGroup;\nimport org.jclouds.dynect.v3.internal.BaseDynECTApiLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"GeoServiceApiLiveTest\")\npublic class GeoServiceApiLiveTest extends BaseDynECTApiLiveTest {\n\n   @Test\n   protected void testListAndGetGeoServices() {\n      ImmutableList<String> geos = api().list().toList();\n      getAnonymousLogger().info(\"geo services: \" + geos.size());\n      for (String fqdn : geos) {\n         GeoService geo = api().get(fqdn);\n         checkGeoService(geo);\n      }\n   }\n\n   static void checkGeoService(GeoService service) {\n      assertNotNull(service.getName(), \"Name cannot be null \" + service);\n      assertTrue(service.getTTL() >= 0, \"TTL cannot be negative \" + service);\n      assertTrue(!service.getNodes().isEmpty(), \"Nodes must be assigned \" + service);\n      assertTrue(!service.getGroups().isEmpty(), \"Groups must be assigned \" + service);\n      for (GeoRegionGroup group : service.getGroups())\n         GeoRegionGroupApiLiveTest.checkGeoRegionGroup(group);\n   }\n\n   protected GeoServiceApi api() {\n      return api.getGeoServiceApi();\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/test/java/org/jclouds/dynect/v3/features/RecordApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.features;\nimport static com.google.common.net.HttpHeaders.ACCEPT;\nimport static com.google.common.net.HttpHeaders.CONTENT_TYPE;\nimport static jakarta.ws.rs.HttpMethod.DELETE;\nimport static jakarta.ws.rs.HttpMethod.GET;\nimport static jakarta.ws.rs.HttpMethod.POST;\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\nimport static jakarta.ws.rs.core.Response.Status.OK;\nimport static org.jclouds.dynect.v3.domain.RecordId.recordIdBuilder;\nimport static org.jclouds.dynect.v3.domain.rdata.AData.a;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.dynect.v3.DynECTApi;\nimport org.jclouds.dynect.v3.domain.CreateRecord;\nimport org.jclouds.dynect.v3.domain.Job;\nimport org.jclouds.dynect.v3.domain.RecordId;\nimport org.jclouds.dynect.v3.domain.rdata.AData;\nimport org.jclouds.dynect.v3.internal.BaseDynECTApiExpectTest;\nimport org.jclouds.dynect.v3.parse.GetAAAARecordResponseTest;\nimport org.jclouds.dynect.v3.parse.GetARecordResponseTest;\nimport org.jclouds.dynect.v3.parse.GetCNAMERecordResponseTest;\nimport org.jclouds.dynect.v3.parse.GetMXRecordResponseTest;\nimport org.jclouds.dynect.v3.parse.GetNSRecordResponseTest;\nimport org.jclouds.dynect.v3.parse.GetPTRRecordResponseTest;\nimport org.jclouds.dynect.v3.parse.GetRecordResponseTest;\nimport org.jclouds.dynect.v3.parse.GetSOARecordResponseTest;\nimport org.jclouds.dynect.v3.parse.GetSPFRecordResponseTest;\nimport org.jclouds.dynect.v3.parse.GetSRVRecordResponseTest;\nimport org.jclouds.dynect.v3.parse.GetSSHFPRecordResponseTest;\nimport org.jclouds.dynect.v3.parse.GetTXTRecordResponseTest;\nimport org.jclouds.dynect.v3.parse.ListRecordsResponseTest;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"RecordApiExpectTest\")\npublic class RecordApiExpectTest extends BaseDynECTApiExpectTest {\n   HttpRequest getSOA = HttpRequest.builder().method(GET)\n                                   .endpoint(\"https://api2.dynect.net/REST/SOARecord/jclouds.org/jclouds.org/50976579\")\n                                   .addHeader(\"API-Version\", \"3.3.8\")\n                                   .addHeader(CONTENT_TYPE, APPLICATION_JSON)\n                                   .addHeader(\"Auth-Token\", authToken).build();   \n\n   HttpResponse soaResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/get_record_soa.json\", APPLICATION_JSON)).build();\n\n   RecordId soaId = recordIdBuilder()\n                            .zone(\"jclouds.org\")\n                            .fqdn(\"jclouds.org\")\n                            .type(\"SOA\")\n                            .id(50976579L).build();\n\n   public void testGetWhenResponseIs2xx() {\n      DynECTApi success = requestsSendResponses(createSession, createSessionResponse, getSOA, soaResponse);\n      assertEquals(success.getRecordApiForZone(\"jclouds.org\").get(soaId).toString(),\n                   new GetRecordResponseTest().expected().toString());\n   }\n\n   public void testGetWhenResponseIs404() {\n      DynECTApi fail = requestsSendResponses(createSession, createSessionResponse, getSOA, notFound);\n      assertNull(fail.getRecordApiForZone(\"jclouds.org\").get(soaId));\n   }\n\n   HttpRequest getAAAA = HttpRequest.builder().method(GET)\n         .endpoint(\"https://api2.dynect.net/REST/AAAARecord/jclouds.org/jclouds.org/50976579\")\n         .addHeader(\"API-Version\", \"3.3.8\")\n         .addHeader(CONTENT_TYPE, APPLICATION_JSON)\n         .addHeader(\"Auth-Token\", authToken).build();\n   \n   HttpResponse aaaaResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/get_record_aaaa.json\", APPLICATION_JSON)).build();\n\n   RecordId aaaaId = recordIdBuilder()\n        .zone(\"jclouds.org\")\n        .fqdn(\"jclouds.org\")\n        .type(\"AAAA\")\n        .id(50976579L).build();\n\n   public void testGetAAAAWhenResponseIs2xx() {\n      DynECTApi success = requestsSendResponses(createSession, createSessionResponse, getAAAA, aaaaResponse);\n      assertEquals(success.getRecordApiForZone(\"jclouds.org\").getAAAA(aaaaId.getFQDN(), aaaaId.getId()).toString(),\n                   new GetAAAARecordResponseTest().expected().toString());\n   }\n\n   public void testGetAAAAWhenResponseIs404() {\n      DynECTApi fail = requestsSendResponses(createSession, createSessionResponse, getAAAA, notFound);\n      assertNull(fail.getRecordApiForZone(\"jclouds.org\").getAAAA(aaaaId.getFQDN(), aaaaId.getId()));\n   }\n\n   HttpRequest getA = HttpRequest.builder().method(GET)\n         .endpoint(\"https://api2.dynect.net/REST/ARecord/jclouds.org/jclouds.org/50976579\")\n         .addHeader(\"API-Version\", \"3.3.8\")\n         .addHeader(CONTENT_TYPE, APPLICATION_JSON)\n         .addHeader(\"Auth-Token\", authToken).build();   \n   \n   HttpResponse aResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/get_record_a.json\", APPLICATION_JSON)).build();\n\n   RecordId aId = recordIdBuilder()\n        .zone(\"jclouds.org\")\n        .fqdn(\"jclouds.org\")\n        .type(\"A\")\n        .id(50976579L).build();\n\n   public void testGetAWhenResponseIs2xx() {\n      DynECTApi success = requestsSendResponses(createSession, createSessionResponse, getA, aResponse);\n      assertEquals(success.getRecordApiForZone(\"jclouds.org\").getA(aId.getFQDN(), aId.getId()).toString(),\n                   new GetARecordResponseTest().expected().toString());\n   }\n\n   public void testGetAWhenResponseIs404() {\n      DynECTApi fail = requestsSendResponses(createSession, createSessionResponse, getA, notFound);\n      assertNull(fail.getRecordApiForZone(\"jclouds.org\").getA(aId.getFQDN(), aId.getId()));\n   }\n\n   HttpRequest getCNAME = HttpRequest.builder().method(GET)\n         .endpoint(\"https://api2.dynect.net/REST/CNAMERecord/jclouds.org/jclouds.org/50976579\")\n         .addHeader(\"API-Version\", \"3.3.8\")\n         .addHeader(CONTENT_TYPE, APPLICATION_JSON)\n         .addHeader(\"Auth-Token\", authToken).build();   \n   \n   HttpResponse cnameResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/get_record_cname.json\", APPLICATION_JSON)).build();\n\n   RecordId cnameId = recordIdBuilder()\n        .zone(\"jclouds.org\")\n        .fqdn(\"jclouds.org\")\n        .type(\"CNAME\")\n        .id(50976579L).build();\n\n   public void testGetCNAMEWhenResponseIs2xx() {\n      DynECTApi success = requestsSendResponses(createSession, createSessionResponse, getCNAME, cnameResponse);\n      assertEquals(success.getRecordApiForZone(\"jclouds.org\").getCNAME(cnameId.getFQDN(), cnameId.getId()).toString(),\n                   new GetCNAMERecordResponseTest().expected().toString());\n   }\n\n   public void testGetCNAMEWhenResponseIs404() {\n      DynECTApi fail = requestsSendResponses(createSession, createSessionResponse, getCNAME, notFound);\n      assertNull(fail.getRecordApiForZone(\"jclouds.org\").getCNAME(cnameId.getFQDN(), cnameId.getId()));\n   }\n\n   HttpRequest getMX = HttpRequest.builder().method(GET)\n         .endpoint(\"https://api2.dynect.net/REST/MXRecord/jclouds.org/jclouds.org/50976579\")\n         .addHeader(\"API-Version\", \"3.3.8\")\n         .addHeader(CONTENT_TYPE, APPLICATION_JSON)\n         .addHeader(\"Auth-Token\", authToken).build();   \n   \n   HttpResponse mxResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/get_record_mx.json\", APPLICATION_JSON)).build();\n\n   RecordId mxId = recordIdBuilder()\n        .zone(\"jclouds.org\")\n        .fqdn(\"jclouds.org\")\n        .type(\"MX\")\n        .id(50976579L).build();\n\n   public void testGetMXWhenResponseIs2xx() {\n      DynECTApi success = requestsSendResponses(createSession, createSessionResponse, getMX, mxResponse);\n      assertEquals(success.getRecordApiForZone(\"jclouds.org\").getMX(mxId.getFQDN(), mxId.getId()).toString(),\n                   new GetMXRecordResponseTest().expected().toString());\n   }\n\n   public void testGetMXWhenResponseIs404() {\n      DynECTApi fail = requestsSendResponses(createSession, createSessionResponse, getMX, notFound);\n      assertNull(fail.getRecordApiForZone(\"jclouds.org\").getMX(mxId.getFQDN(), mxId.getId()));\n   }\n\n   HttpRequest getNS = HttpRequest.builder().method(GET)\n         .endpoint(\"https://api2.dynect.net/REST/NSRecord/jclouds.org/jclouds.org/50976579\")\n         .addHeader(\"API-Version\", \"3.3.8\")\n         .addHeader(CONTENT_TYPE, APPLICATION_JSON)\n         .addHeader(\"Auth-Token\", authToken).build();   \n   \n   HttpResponse nsResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/get_record_ns.json\", APPLICATION_JSON)).build();\n\n   RecordId nsId = recordIdBuilder()\n        .zone(\"jclouds.org\")\n        .fqdn(\"jclouds.org\")\n        .type(\"NS\")\n        .id(50976579L).build();\n\n   public void testGetNSWhenResponseIs2xx() {\n      DynECTApi success = requestsSendResponses(createSession, createSessionResponse, getNS, nsResponse);\n      assertEquals(success.getRecordApiForZone(\"jclouds.org\").getNS(nsId.getFQDN(), nsId.getId()).toString(),\n                   new GetNSRecordResponseTest().expected().toString());\n   }\n\n   public void testGetNSWhenResponseIs404() {\n      DynECTApi fail = requestsSendResponses(createSession, createSessionResponse, getNS, notFound);\n      assertNull(fail.getRecordApiForZone(\"jclouds.org\").getNS(nsId.getFQDN(), nsId.getId()));\n   }\n\n   HttpRequest getPTR = HttpRequest.builder().method(GET)\n         .endpoint(\"https://api2.dynect.net/REST/PTRRecord/jclouds.org/jclouds.org/50976579\")\n         .addHeader(\"API-Version\", \"3.3.8\")\n         .addHeader(CONTENT_TYPE, APPLICATION_JSON)\n         .addHeader(\"Auth-Token\", authToken).build();   \n   \n   HttpResponse ptrResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/get_record_ptr.json\", APPLICATION_JSON)).build();\n\n   RecordId ptrId = recordIdBuilder()\n        .zone(\"jclouds.org\")\n        .fqdn(\"jclouds.org\")\n        .type(\"PTR\")\n        .id(50976579L).build();\n\n   public void testGetPTRWhenResponseIs2xx() {\n      DynECTApi success = requestsSendResponses(createSession, createSessionResponse, getPTR, ptrResponse);\n      assertEquals(success.getRecordApiForZone(\"jclouds.org\").getPTR(ptrId.getFQDN(), ptrId.getId()).toString(),\n                   new GetPTRRecordResponseTest().expected().toString());\n   }\n\n   public void testGetPTRWhenResponseIs404() {\n      DynECTApi fail = requestsSendResponses(createSession, createSessionResponse, getPTR, notFound);\n      assertNull(fail.getRecordApiForZone(\"jclouds.org\").getPTR(ptrId.getFQDN(), ptrId.getId()));\n   }\n\n   public void testGetSOAWhenResponseIs2xx() {\n      DynECTApi success = requestsSendResponses(createSession, createSessionResponse, getSOA, soaResponse);\n      assertEquals(success.getRecordApiForZone(\"jclouds.org\").getSOA(soaId.getFQDN(), soaId.getId()).toString(),\n                   new GetSOARecordResponseTest().expected().toString());\n   }\n\n   public void testGetSOAWhenResponseIs404() {\n      DynECTApi fail = requestsSendResponses(createSession, createSessionResponse, getSOA, notFound);\n      assertNull(fail.getRecordApiForZone(\"jclouds.org\").getSOA(soaId.getFQDN(), soaId.getId()));\n   }\n\n   HttpRequest getSPF = HttpRequest.builder().method(GET)\n         .endpoint(\"https://api2.dynect.net/REST/SPFRecord/jclouds.org/jclouds.org/50976579\")\n         .addHeader(\"API-Version\", \"3.3.8\")\n         .addHeader(CONTENT_TYPE, APPLICATION_JSON)\n         .addHeader(\"Auth-Token\", authToken).build();   \n   \n   HttpResponse spfResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/get_record_spf.json\", APPLICATION_JSON)).build();\n\n   RecordId spfId = recordIdBuilder()\n        .zone(\"jclouds.org\")\n        .fqdn(\"jclouds.org\")\n        .type(\"SPF\")\n        .id(50976579L).build();\n\n   public void testGetSPFWhenResponseIs2xx() {\n      DynECTApi success = requestsSendResponses(createSession, createSessionResponse, getSPF, spfResponse);\n      assertEquals(success.getRecordApiForZone(\"jclouds.org\").getSPF(spfId.getFQDN(), spfId.getId()).toString(),\n                   new GetSPFRecordResponseTest().expected().toString());\n   }\n\n   HttpRequest getSRV = HttpRequest.builder().method(GET)\n         .endpoint(\"https://api2.dynect.net/REST/SRVRecord/jclouds.org/jclouds.org/50976579\")\n         .addHeader(\"API-Version\", \"3.3.8\")\n         .addHeader(CONTENT_TYPE, APPLICATION_JSON)\n         .addHeader(\"Auth-Token\", authToken).build();   \n   \n   HttpResponse srvResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/get_record_srv.json\", APPLICATION_JSON)).build();\n\n   RecordId srvId = recordIdBuilder()\n        .zone(\"jclouds.org\")\n        .fqdn(\"jclouds.org\")\n        .type(\"SRV\")\n        .id(50976579L).build();\n\n   public void testGetSRVWhenResponseIs2xx() {\n      DynECTApi success = requestsSendResponses(createSession, createSessionResponse, getSRV, srvResponse);\n      assertEquals(success.getRecordApiForZone(\"jclouds.org\").getSRV(srvId.getFQDN(), srvId.getId()).toString(),\n                   new GetSRVRecordResponseTest().expected().toString());\n   }\n\n   HttpRequest getSSHFP = HttpRequest.builder().method(GET)\n         .endpoint(\"https://api2.dynect.net/REST/SSHFPRecord/jclouds.org/jclouds.org/50976579\")\n         .addHeader(\"API-Version\", \"3.3.8\")\n         .addHeader(CONTENT_TYPE, APPLICATION_JSON)\n         .addHeader(\"Auth-Token\", authToken).build();   \n   \n   HttpResponse sshfpResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/get_record_sshfp.json\", APPLICATION_JSON)).build();\n\n   RecordId sshfpId = recordIdBuilder()\n        .zone(\"jclouds.org\")\n        .fqdn(\"jclouds.org\")\n        .type(\"SSHFP\")\n        .id(50976579L).build();\n\n   public void testGetSSHFPWhenResponseIs2xx() {\n      DynECTApi success = requestsSendResponses(createSession, createSessionResponse, getSSHFP, sshfpResponse);\n      assertEquals(success.getRecordApiForZone(\"jclouds.org\").getSSHFP(sshfpId.getFQDN(), sshfpId.getId()).toString(),\n                   new GetSSHFPRecordResponseTest().expected().toString());\n   }\n\n   HttpRequest getTXT = HttpRequest.builder().method(GET)\n         .endpoint(\"https://api2.dynect.net/REST/TXTRecord/jclouds.org/jclouds.org/50976579\")\n         .addHeader(\"API-Version\", \"3.3.8\")\n         .addHeader(CONTENT_TYPE, APPLICATION_JSON)\n         .addHeader(\"Auth-Token\", authToken).build();   \n   \n   HttpResponse txtResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/get_record_txt.json\", APPLICATION_JSON)).build();\n\n   RecordId txtId = recordIdBuilder()\n        .zone(\"jclouds.org\")\n        .fqdn(\"jclouds.org\")\n        .type(\"TXT\")\n        .id(50976579L).build();\n\n   public void testGetTXTWhenResponseIs2xx() {\n      DynECTApi success = requestsSendResponses(createSession, createSessionResponse, getTXT, txtResponse);\n      assertEquals(success.getRecordApiForZone(\"jclouds.org\").getTXT(txtId.getFQDN(), txtId.getId()).toString(),\n                   new GetTXTRecordResponseTest().expected().toString());\n   }\n\n   public void testGetTXTWhenResponseIs404() {\n      DynECTApi fail = requestsSendResponses(createSession, createSessionResponse, getTXT, notFound);\n      assertNull(fail.getRecordApiForZone(\"jclouds.org\").getTXT(txtId.getFQDN(), txtId.getId()));\n   }\n\n   HttpRequest list = HttpRequest.builder().method(GET)\n                                 .endpoint(\"https://api2.dynect.net/REST/AllRecord/jclouds.org\")\n                                 .addHeader(\"API-Version\", \"3.3.8\")\n                                 .addHeader(CONTENT_TYPE, APPLICATION_JSON)\n                                 .addHeader(\"Auth-Token\", authToken).build();   \n\n   HttpResponse listResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/list_records.json\", APPLICATION_JSON)).build();\n\n   public void testListWhenResponseIs2xx() {\n      DynECTApi success = requestsSendResponses(createSession, createSessionResponse, list, listResponse);\n      assertEquals(success.getRecordApiForZone(\"jclouds.org\").list().toString(),\n                   new ListRecordsResponseTest().expected().toString());\n   }\n\n   HttpRequest listByFQDN = HttpRequest.builder().method(GET)\n         .endpoint(\"https://api2.dynect.net/REST/AllRecord/jclouds.org/www.foo.com\")\n         .addHeader(\"API-Version\", \"3.3.8\")\n         .addHeader(CONTENT_TYPE, APPLICATION_JSON)\n         .addHeader(\"Auth-Token\", authToken).build();   \n\n   public void testListByFQDNWhenResponseIs2xx() {\n      DynECTApi success = requestsSendResponses(createSession, createSessionResponse, listByFQDN, listResponse);\n      assertEquals(success.getRecordApiForZone(\"jclouds.org\").listByFQDN(\"www.foo.com\").toString(),\n      new ListRecordsResponseTest().expected().toString());\n   }\n   \n   public void testListByFQDNWhenResponseIs404() {\n      DynECTApi fail = requestsSendResponses(createSession, createSessionResponse, listByFQDN, notFound);\n      assertTrue(fail.getRecordApiForZone(\"jclouds.org\").listByFQDN(\"www.foo.com\").isEmpty());\n   }\n\n   HttpRequest listByFQDNAndType = HttpRequest.builder().method(GET)\n                                              .endpoint(\"https://api2.dynect.net/REST/ARecord/jclouds.org/www.foo.com\")\n                                              .addHeader(\"API-Version\", \"3.3.8\")\n                                              .addHeader(CONTENT_TYPE, APPLICATION_JSON)\n                                              .addHeader(\"Auth-Token\", authToken).build();   \n\n   public void testListByFQDNAndTypeWhenResponseIs2xx() {\n      DynECTApi success = requestsSendResponses(createSession, createSessionResponse, listByFQDNAndType, listResponse);\n      assertEquals(success.getRecordApiForZone(\"jclouds.org\").listByFQDNAndType(\"www.foo.com\", \"A\").toString(),\n            new ListRecordsResponseTest().expected().toString());\n   }\n   \n   public void testListByFQDNAndTypeWhenResponseIs404() {\n       DynECTApi fail = requestsSendResponses(createSession, createSessionResponse, listByFQDNAndType, notFound);\n       assertTrue(fail.getRecordApiForZone(\"jclouds.org\").listByFQDNAndType(\"www.foo.com\", \"A\").isEmpty());\n    }\n\n   HttpRequest create = HttpRequest.builder().method(POST)\n         .endpoint(\"https://api2.dynect.net/REST/ARecord/jclouds.org/www.jclouds.org\")\n         .addHeader(\"API-Version\", \"3.3.8\")\n         .addHeader(ACCEPT, APPLICATION_JSON)\n         .addHeader(\"Auth-Token\", authToken)\n         .payload(stringPayload(\"{\\\"rdata\\\":{\\\"address\\\":\\\"1.1.1.1\\\"},\\\"ttl\\\":86400}\"))\n         .build();   \n\n   HttpResponse createResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/new_record.json\", APPLICATION_JSON)).build();\n\n   public void testCreateWhenResponseIs2xx() {\n      DynECTApi success = requestsSendResponses(createSession, createSessionResponse, create, createResponse);\n      CreateRecord<AData> record = CreateRecord.<AData> builder()\n                                               .fqdn(\"www.jclouds.org\")\n                                               .type(\"A\")\n                                               .ttl(86400)\n                                               .rdata(a(\"1.1.1.1\"))\n                                               .build();\n      assertEquals(success.getRecordApiForZone(\"jclouds.org\").scheduleCreate(record), Job.success(285372440L));\n   }\n\n   HttpRequest delete = HttpRequest.builder().method(DELETE)\n                                             .endpoint(\"https://api2.dynect.net/REST/ARecord/jclouds.org/www.jclouds.org/285372440\")\n                                             .addHeader(\"API-Version\", \"3.3.8\")\n                                             .addHeader(ACCEPT, APPLICATION_JSON)\n                                             .addHeader(CONTENT_TYPE, APPLICATION_JSON)\n                                             .addHeader(\"Auth-Token\", authToken).build();  \n\n   HttpResponse deleteResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/delete_record.json\", APPLICATION_JSON)).build();\n\n   RecordId id = recordIdBuilder()\n                     .zone(\"jclouds.org\")\n                     .fqdn(\"www.jclouds.org\")\n                     .type(\"A\")\n                     .id(285372440L)\n                     .build();\n\n   public void testDeleteWhenResponseIs2xx() {\n      DynECTApi success = requestsSendResponses(createSession, createSessionResponse, delete, deleteResponse);\n\n      assertEquals(success.getRecordApiForZone(\"jclouds.org\").scheduleDelete(id), Job.success(285372457L));\n   }\n\n   public void testDeleteWhenResponseIs404() {\n      DynECTApi fail = requestsSendResponses(createSession, createSessionResponse, delete, notFound);\n      assertNull(fail.getRecordApiForZone(\"jclouds.org\").scheduleDelete(id));\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/test/java/org/jclouds/dynect/v3/features/RecordApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.features;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static java.util.logging.Logger.getAnonymousLogger;\nimport static org.jclouds.dynect.v3.domain.rdata.AData.a;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Map;\n\nimport org.jclouds.JcloudsVersion;\nimport org.jclouds.dynect.v3.DynECTExceptions.JobStillRunningException;\nimport org.jclouds.dynect.v3.domain.CreateRecord;\nimport org.jclouds.dynect.v3.domain.Job;\nimport org.jclouds.dynect.v3.domain.Job.Status;\nimport org.jclouds.dynect.v3.domain.Record;\nimport org.jclouds.dynect.v3.domain.RecordId;\nimport org.jclouds.dynect.v3.domain.SOARecord;\nimport org.jclouds.dynect.v3.domain.Zone;\nimport org.jclouds.dynect.v3.domain.rdata.AAAAData;\nimport org.jclouds.dynect.v3.domain.rdata.AData;\nimport org.jclouds.dynect.v3.domain.rdata.CNAMEData;\nimport org.jclouds.dynect.v3.domain.rdata.MXData;\nimport org.jclouds.dynect.v3.domain.rdata.NSData;\nimport org.jclouds.dynect.v3.domain.rdata.PTRData;\nimport org.jclouds.dynect.v3.domain.rdata.SOAData;\nimport org.jclouds.dynect.v3.domain.rdata.SPFData;\nimport org.jclouds.dynect.v3.domain.rdata.SRVData;\nimport org.jclouds.dynect.v3.domain.rdata.SSHFPData;\nimport org.jclouds.dynect.v3.domain.rdata.TXTData;\nimport org.jclouds.dynect.v3.internal.BaseDynECTApiLiveTest;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"RecordApiLiveTest\")\npublic class RecordApiLiveTest extends BaseDynECTApiLiveTest {\n\n   private void checkRecordId(RecordId record) {\n      assertTrue(record.getId() > 0, \"Id cannot be zero for RecordId: \" + record);\n      checkNotNull(record.getType(), \"Type cannot be null for RecordId: %s\", record);\n      checkNotNull(record.getFQDN(), \"FQDN cannot be null for RecordId: %s\", record);\n      checkNotNull(record.getZone(), \"Zone cannot be null for RecordId: %s\", record);\n   }\n\n   private void checkRecord(Record<? extends Map<String, Object>> record) {\n      checkRecordId(record);\n      assertTrue(!record.getRData().isEmpty(), \"RData entries should be present for cannot be zero for Record: \"\n            + record);\n   }\n\n   @Test\n   protected void testListAndGetRecords() {\n      for (String zone : zoneApi().list()) {\n         RecordApi api = api(zone);\n         ImmutableList<RecordId> records = api.list().toList();\n         getAnonymousLogger().info(\"zone: \" + zone + \" record count: \" + records.size());\n\n         for (RecordId recordId : records) {\n            Record<? extends Map<String, Object>> record;\n            if (\"AAAA\".equals(recordId.getType())) {\n               record = checkAAAARecord(api.getAAAA(recordId.getFQDN(), recordId.getId()));\n            } else if (\"A\".equals(recordId.getType())) {\n               record = checkARecord(api.getA(recordId.getFQDN(), recordId.getId()));\n            } else if (\"CNAME\".equals(recordId.getType())) {\n               record = checkCNAMERecord(api.getCNAME(recordId.getFQDN(), recordId.getId()));\n            } else if (\"MX\".equals(recordId.getType())) {\n               record = checkMXRecord(api.getMX(recordId.getFQDN(), recordId.getId()));\n            } else if (\"NS\".equals(recordId.getType())) {\n               record = checkNSRecord(api.getNS(recordId.getFQDN(), recordId.getId()));\n            } else if (\"PTR\".equals(recordId.getType())) {\n               record = checkPTRRecord(api.getPTR(recordId.getFQDN(), recordId.getId()));\n            } else if (\"SOA\".equals(recordId.getType())) {\n               record = checkSOARecord(api.getSOA(recordId.getFQDN(), recordId.getId()));\n            } else if (\"SPF\".equals(recordId.getType())) {\n               record = checkSPFRecord(api.getSPF(recordId.getFQDN(), recordId.getId()));\n            } else if (\"SRV\".equals(recordId.getType())) {\n               record = checkSRVRecord(api.getSRV(recordId.getFQDN(), recordId.getId()));\n            } else if (\"SSHFP\".equals(recordId.getType())) {\n               record = checkSSHFPRecord(api.getSSHFP(recordId.getFQDN(), recordId.getId()));\n            } else if (\"TXT\".equals(recordId.getType())) {\n               record = checkTXTRecord(api.getTXT(recordId.getFQDN(), recordId.getId()));\n            } else {\n               record = api.get(recordId);\n            }\n            assertEquals(record, recordId);\n            checkRecord(record);\n         }\n      }\n   }\n\n   private Record<AAAAData> checkAAAARecord(Record<AAAAData> record) {\n      AAAAData rdata = record.getRData();\n      checkNotNull(rdata.getAddress(), \"rdata.address cannot be null for AAAARecord: %s\", record);\n      return record;\n   }\n\n   private Record<AData> checkARecord(Record<AData> record) {\n      AData rdata = record.getRData();\n      checkNotNull(rdata.getAddress(), \"rdata.address cannot be null for ARecord: %s\", record);\n      return record;\n   }\n\n   private Record<CNAMEData> checkCNAMERecord(Record<CNAMEData> record) {\n      CNAMEData rdata = record.getRData();\n      checkNotNull(rdata.getCname(), \"rdata.cname cannot be null for CNAMERecord: %s\", record);\n      return record;\n   }\n\n   private Record<MXData> checkMXRecord(Record<MXData> record) {\n      MXData rdata = record.getRData();\n      checkNotNull(rdata.getExchange(), \"rdata.exchange cannot be null for MXRecord: %s\", record);\n      return record;\n   }\n\n   private Record<NSData> checkNSRecord(Record<NSData> record) {\n      NSData rdata = record.getRData();\n      checkNotNull(rdata.getNsdname(), \"rdata.nsdname cannot be null for NSRecord: %s\", record);\n      return record;\n   }\n\n   private Record<PTRData> checkPTRRecord(Record<PTRData> record) {\n      PTRData rdata = record.getRData();\n      checkNotNull(rdata.getPtrdname(), \"rdata.ptrdname cannot be null for PTRRecord: %s\", record);\n      return record;\n   }\n\n   private SOARecord checkSOARecord(SOARecord record) {\n      checkNotNull(record.getSerialStyle(), \"SerialStyle cannot be null for SOARecord: %s\", record);\n      SOAData rdata = record.getRData();\n      checkNotNull(rdata.getMname(), \"rdata.mname cannot be null for SOARecord: %s\", record);\n      checkNotNull(rdata.getRname(), \"rdata.rname cannot be null for SOARecord: %s\", record);\n      return record;\n   }\n\n   private Record<SPFData> checkSPFRecord(Record<SPFData> record) {\n      SPFData rdata = record.getRData();\n      checkNotNull(rdata.getTxtdata(), \"rdata.txtdata cannot be null for SPFRecord: %s\", record);\n      return record;\n   }\n\n   private Record<SRVData> checkSRVRecord(Record<SRVData> record) {\n      SRVData rdata = record.getRData();\n      checkNotNull(rdata.getTarget(), \"rdata.target cannot be null for SRVRecord: %s\", record);\n      return record;\n   }\n\n   private Record<SSHFPData> checkSSHFPRecord(Record<SSHFPData> record) {\n      SSHFPData rdata = record.getRData();\n      checkNotNull(rdata.getFingerprint(), \"rdata.fingerprint cannot be null for SSHFPRecord: %s\", record);\n      return record;\n   }\n\n   private Record<TXTData> checkTXTRecord(Record<TXTData> record) {\n      TXTData rdata = record.getRData();\n      checkNotNull(rdata.getTxtdata(), \"rdata.txtdata cannot be null for TXTRecord: %s\", record);\n      return record;\n   }\n\n   String zoneFQDN = System.getProperty(\"user.name\").replace('.', '-') + \".record.dynecttest.jclouds.org\";\n   String contact = JcloudsVersion.get() + \".jclouds.org\";\n\n   private void createZone() {\n      Job job = zoneApi().scheduleCreateWithContact(zoneFQDN, contact);\n      checkNotNull(job, \"unable to create zone %s\", zoneFQDN);\n      getAnonymousLogger().info(\"created zone: \" + job);\n      assertEquals(job.getStatus(), Status.SUCCESS);\n      assertEquals(api.getJob(job.getId()), job);\n      Zone zone = zoneApi().publish(zoneFQDN);\n      checkNotNull(zone, \"unable to publish zone %s\", zoneFQDN);\n      getAnonymousLogger().info(\"published zone: \" + zone);\n   }\n\n   String fqdn = \"www.\" + zoneFQDN;\n   CreateRecord<AData> record = CreateRecord.<AData> builder()\n                                            .fqdn(\"www.\" + zoneFQDN)\n                                            .type(\"A\")\n                                            .ttl(86400)\n                                            .rdata(a(\"1.1.1.1\"))\n                                            .build();\n\n   public void testCreateRecord() {\n      createZone();\n\n      Job job = null;\n      while (true) {\n         try {\n            job = api(zoneFQDN).scheduleCreate(record);\n            break;\n         } catch (JobStillRunningException e) {\n            continue;\n         }\n      }\n\n      checkNotNull(job, \"unable to create record %s\", record);\n      getAnonymousLogger().info(\"created record: \" + job);\n      assertEquals(job.getStatus(), Status.SUCCESS);\n      assertEquals(api.getJob(job.getId()), job);\n      zoneApi().publish(zoneFQDN);\n   }\n\n   RecordId id;\n\n   @Test(dependsOnMethods = \"testCreateRecord\")\n   public void testListByFQDNAndType() {\n      id = api(zoneFQDN).listByFQDNAndType(record.getFQDN(), record.getType()).toList().get(0);\n      getAnonymousLogger().info(id.toString());\n      Record<? extends Map<String, Object>> newRecord = api(zoneFQDN).get(id);\n      assertEquals(newRecord.getFQDN(), record.getFQDN());\n      assertEquals(newRecord.getType(), record.getType());\n      assertEquals(newRecord.getTTL(), record.getTTL());\n      assertEquals(newRecord.getRData(), record.getRData());\n      checkRecord(newRecord);\n   }\n\n   @Test(dependsOnMethods = \"testCreateRecord\")\n   public void testListByFQDN() {\n      id = api(zoneFQDN).listByFQDN(record.getFQDN()).toList().get(0);\n      getAnonymousLogger().info(id.toString());\n      Record<? extends Map<String, Object>> newRecord = api(zoneFQDN).get(id);\n      assertEquals(newRecord.getFQDN(), record.getFQDN());\n      assertEquals(newRecord.getType(), record.getType());\n      assertEquals(newRecord.getTTL(), record.getTTL());\n      assertEquals(newRecord.getRData(), record.getRData());\n      checkRecord(newRecord);\n   }\n\n   @Test(dependsOnMethods = { \"testListByFQDNAndType\", \"testListByFQDN\" })\n   public void testDeleteRecord() {\n      Job job = api(zoneFQDN).scheduleDelete(id);\n      checkNotNull(job, \"unable to delete record %s\", id);\n      getAnonymousLogger().info(\"deleted record: \" + job);\n      assertEquals(job.getStatus(), Status.SUCCESS);\n      assertEquals(api.getJob(job.getId()), job);\n      zoneApi().publish(zoneFQDN);\n   }\n\n   protected RecordApi api(String zoneFQDN) {\n      return api.getRecordApiForZone(zoneFQDN);\n   }\n\n   protected ZoneApi zoneApi() {\n      return api.getZoneApi();\n   }\n\n   @Override\n   @AfterClass(groups = \"live\", alwaysRun = true)\n   protected void tearDown() {\n      zoneApi().delete(zoneFQDN);\n      super.tearDown();\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/test/java/org/jclouds/dynect/v3/features/SessionApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.features;\nimport static com.google.common.net.HttpHeaders.CONTENT_TYPE;\nimport static jakarta.ws.rs.HttpMethod.DELETE;\nimport static jakarta.ws.rs.HttpMethod.GET;\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\nimport static jakarta.ws.rs.core.Response.Status.OK;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.dynect.v3.DynECTApi;\nimport org.jclouds.dynect.v3.domain.SessionCredentials;\nimport org.jclouds.dynect.v3.internal.BaseDynECTApiExpectTest;\nimport org.jclouds.dynect.v3.parse.CreateSessionResponseTest;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.Test;\n@Test(groups = \"unit\", testName = \"SessionApiExpectTest\")\npublic class SessionApiExpectTest extends BaseDynECTApiExpectTest {\n\n   public void testCreateWhenResponseIs2xx() {\n      DynECTApi apiCreatesSession = requestSendsResponse(createSession, createSessionResponse);\n      assertEquals(apiCreatesSession.getSessionApi().login(SessionCredentials.builder()\n                                                                         .customerName(\"jclouds\")\n                                                                         .userName(\"joe\")\n                                                                         .password(\"letmein\").build()).toString(),\n                   new CreateSessionResponseTest().expected().toString());\n   }\n\n   HttpRequest isValid = HttpRequest.builder().method(GET)\n                                    .endpoint(\"https://api2.dynect.net/REST/Session\")\n                                    .addHeader(\"API-Version\", \"3.3.8\")\n                                    .addHeader(CONTENT_TYPE, APPLICATION_JSON)\n                                    .addHeader(\"Auth-Token\", authToken).build();\n\n   HttpResponse validResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/session_valid.json\", APPLICATION_JSON)).build();\n\n   HttpResponse invalidResponse = HttpResponse.builder().statusCode(400)\n         .payload(payloadFromResourceWithContentType(\"/session_invalid.json\", APPLICATION_JSON)).build();\n\n   public void testSessionValid() {\n      DynECTApi apiWhenValid = requestSendsResponse(isValid, validResponse);\n      assertTrue(apiWhenValid.getSessionApi().isValid(authToken));\n   }\n\n   public void testSessionInvalid() {\n      DynECTApi apiWhenInvalid = requestSendsResponse(isValid, invalidResponse);\n      assertFalse(apiWhenInvalid.getSessionApi().isValid(authToken));\n   }\n\n   HttpRequest logout = HttpRequest.builder().method(DELETE)\n                                   .endpoint(\"https://api2.dynect.net/REST/Session\")\n                                   .addHeader(\"API-Version\", \"3.3.8\")\n                                   .addHeader(CONTENT_TYPE, APPLICATION_JSON)\n                                   .addHeader(\"Auth-Token\", authToken).build();\n\n   HttpResponse logoutResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/logout.json\", APPLICATION_JSON)).build();\n\n   public void testLogout() {\n      DynECTApi apiWhenLogoutSuccess = requestSendsResponse(logout, logoutResponse);\n      apiWhenLogoutSuccess.getSessionApi().logout(authToken);\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/test/java/org/jclouds/dynect/v3/features/SessionApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.features;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.dynect.v3.domain.Session;\nimport org.jclouds.dynect.v3.domain.SessionCredentials;\nimport org.jclouds.dynect.v3.internal.BaseDynECTApiLiveTest;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"SessionApiLiveTest\")\npublic class SessionApiLiveTest extends BaseDynECTApiLiveTest {\n\n   private Session session;\n\n   private void checkSession(Session zone) {\n      checkNotNull(zone.getToken(), \"Token cannot be null for a Session.\");\n      checkNotNull(zone.getVersion(),  \"Version cannot be null for a Session.\");\n   }\n\n   @Test\n   protected void testCreateSession() {\n      SessionCredentials credentials = SessionCredentials.builder()\n                                                         .customerName(identity.substring(0, identity.indexOf(':')))\n                                                         .userName(identity.substring(identity.indexOf(':') + 1))\n                                                         .password(credential).build();\n      session = api().login(credentials);\n      checkSession(session);\n   }\n\n   protected SessionApi api() {\n      return api.getSessionApi();\n   }\n   \n   @AfterClass(groups = { \"integration\", \"live\" })\n   @Override\n   protected void tearDown() {\n      if (session != null)\n         api().logout(session.getToken());\n      super.tearDown();\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/test/java/org/jclouds/dynect/v3/features/ZoneApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.features;\nimport static com.google.common.net.HttpHeaders.ACCEPT;\nimport static com.google.common.net.HttpHeaders.CONTENT_TYPE;\nimport static jakarta.ws.rs.HttpMethod.DELETE;\nimport static jakarta.ws.rs.HttpMethod.GET;\nimport static jakarta.ws.rs.HttpMethod.POST;\nimport static jakarta.ws.rs.HttpMethod.PUT;\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\nimport static jakarta.ws.rs.core.Response.Status.OK;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\n\nimport org.jclouds.dynect.v3.DynECTApi;\nimport org.jclouds.dynect.v3.domain.CreatePrimaryZone;\nimport org.jclouds.dynect.v3.domain.Job;\nimport org.jclouds.dynect.v3.internal.BaseDynECTApiExpectTest;\nimport org.jclouds.dynect.v3.parse.DeleteZoneChangesResponseTest;\nimport org.jclouds.dynect.v3.parse.DeleteZoneResponseTest;\nimport org.jclouds.dynect.v3.parse.GetZoneResponseTest;\nimport org.jclouds.dynect.v3.parse.ListZonesResponseTest;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.Test;\n@Test(groups = \"unit\", testName = \"ZoneApiExpectTest\")\npublic class ZoneApiExpectTest extends BaseDynECTApiExpectTest {\n   HttpRequest get = HttpRequest.builder().method(GET)\n                                .endpoint(\"https://api2.dynect.net/REST/Zone/jclouds.org\")\n                                .addHeader(\"API-Version\", \"3.3.8\")\n                                .addHeader(CONTENT_TYPE, APPLICATION_JSON)\n                                .addHeader(\"Auth-Token\", authToken).build();\n\n   HttpResponse getResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/get_zone.json\", APPLICATION_JSON)).build();\n\n   public void testGetWhenResponseIs2xx() {\n      DynECTApi success = requestsSendResponses(createSession, createSessionResponse, get, getResponse);\n      assertEquals(success.getZoneApi().get(\"jclouds.org\").toString(),\n                   new GetZoneResponseTest().expected().toString());\n   }\n\n   HttpRequest create = HttpRequest.builder().method(POST)\n         .endpoint(\"https://api2.dynect.net/REST/Zone/jclouds.org\")\n         .addHeader(\"API-Version\", \"3.3.8\")\n         .addHeader(ACCEPT, APPLICATION_JSON)\n         .addHeader(\"Auth-Token\", authToken)\n         .payload(stringPayload(\"{\\\"rname\\\":\\\"jimmy@jclouds.org\\\",\\\"serial_style\\\":\\\"increment\\\",\\\"ttl\\\":3600}\"))\n         .build();   \n\n   HttpResponse createResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/new_zone.json\", APPLICATION_JSON)).build();\n\n   public void testCreateWhenResponseIs2xx() {\n      DynECTApi success = requestsSendResponses(createSession, createSessionResponse, create, createResponse);\n      assertEquals(success.getZoneApi().scheduleCreate(CreatePrimaryZone.builder()\n                                                                        .fqdn(\"jclouds.org\")\n                                                                        .contact(\"jimmy@jclouds.org\")\n                                                                        .build()), Job.success(285351593L));\n   }\n\n   public void testCreateWithContactWhenResponseIs2xx() {\n      DynECTApi success = requestsSendResponses(createSession, createSessionResponse, create, createResponse);\n      assertEquals(success.getZoneApi().scheduleCreateWithContact(\"jclouds.org\", \"jimmy@jclouds.org\"), Job.success(285351593L));\n   }\n\n   public void testGetWhenResponseIs404() {\n      DynECTApi fail = requestsSendResponses(createSession, createSessionResponse, get, notFound);\n      assertNull(fail.getZoneApi().get(\"jclouds.org\"));\n   }\n\n   HttpRequest list = HttpRequest.builder().method(GET)\n                                 .endpoint(\"https://api2.dynect.net/REST/Zone\")\n                                 .addHeader(\"API-Version\", \"3.3.8\")\n                                 .addHeader(CONTENT_TYPE, APPLICATION_JSON)\n                                 .addHeader(\"Auth-Token\", authToken).build();  \n\n   HttpResponse listResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/list_zones.json\", APPLICATION_JSON)).build();\n\n   public void testListWhenResponseIs2xx() {\n      DynECTApi success = requestsSendResponses(createSession, createSessionResponse, list, listResponse);\n      assertEquals(success.getZoneApi().list().toString(),\n                   new ListZonesResponseTest().expected().toString());\n   }\n\n   HttpRequest deleteChanges = HttpRequest.builder().method(DELETE)\n                                          .endpoint(\"https://api2.dynect.net/REST/ZoneChanges/jclouds.org\")\n                                          .addHeader(\"API-Version\", \"3.3.8\")\n                                          .addHeader(ACCEPT, APPLICATION_JSON)\n                                          .addHeader(CONTENT_TYPE, APPLICATION_JSON)\n                                          .addHeader(\"Auth-Token\", authToken).build();\n\n   HttpResponse deleteChangesResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/delete_zone_changes.json\", APPLICATION_JSON)).build();\n\n   public void testDeleteChangesWhenResponseIs2xx() {\n      DynECTApi success = requestsSendResponses(createSession, createSessionResponse, deleteChanges, deleteChangesResponse);\n      assertEquals(success.getZoneApi().deleteChanges(\"jclouds.org\").toString(),\n                   new DeleteZoneChangesResponseTest().expected().toString());\n   }\n\n   HttpRequest delete = HttpRequest.builder().method(DELETE)\n                                   .endpoint(\"https://api2.dynect.net/REST/Zone/jclouds.org\")\n                                   .addHeader(\"API-Version\", \"3.3.8\")\n                                   .addHeader(ACCEPT, APPLICATION_JSON)\n                                   .addHeader(CONTENT_TYPE, APPLICATION_JSON)\n                                   .addHeader(\"Auth-Token\", authToken).build();\n\n   HttpResponse deleteResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/delete_zone.json\", APPLICATION_JSON)).build();\n\n   public void testDeleteWhenResponseIs2xx() {\n      DynECTApi success = requestsSendResponses(createSession, createSessionResponse, delete, deleteResponse);\n      assertEquals(success.getZoneApi().delete(\"jclouds.org\").toString(),\n                   new DeleteZoneResponseTest().expected().toString());\n   }\n\n   public void testDeleteWhenResponseIs404() {\n      DynECTApi fail = requestsSendResponses(createSession, createSessionResponse, delete, notFound);\n      assertNull(fail.getZoneApi().delete(\"jclouds.org\"));\n   }\n\n   HttpRequest publish = HttpRequest.builder().method(PUT)\n         .endpoint(\"https://api2.dynect.net/REST/Zone/jclouds.org\")\n         .addHeader(\"API-Version\", \"3.3.8\")\n         .addHeader(\"Auth-Token\", authToken)\n         .payload(stringPayload(\"{\\\"publish\\\":true}\"))\n         .build();   \n\n   public void testPublishWhenResponseIs2xx() {\n      DynECTApi success = requestsSendResponses(createSession, createSessionResponse, publish, getResponse);\n      assertEquals(success.getZoneApi().publish(\"jclouds.org\").toString(),\n                   new GetZoneResponseTest().expected().toString());\n   }\n\n   HttpRequest freeze = HttpRequest.builder().method(PUT)\n         .endpoint(\"https://api2.dynect.net/REST/Zone/jclouds.org\")\n         .addHeader(\"API-Version\", \"3.3.8\")\n         .addHeader(ACCEPT, APPLICATION_JSON)\n         .addHeader(\"Auth-Token\", authToken)\n         .payload(stringPayload(\"{\\\"freeze\\\":true}\"))\n         .build();   \n\n   public void testFreezeWhenResponseIs2xx() {\n      DynECTApi success = requestsSendResponses(createSession, createSessionResponse, freeze, deleteResponse);\n      assertEquals(success.getZoneApi().freeze(\"jclouds.org\").toString(),\n                   new DeleteZoneResponseTest().expected().toString());\n   }\n\n   HttpRequest thaw = HttpRequest.builder().method(PUT)\n         .endpoint(\"https://api2.dynect.net/REST/Zone/jclouds.org\")\n         .addHeader(\"API-Version\", \"3.3.8\")\n         .addHeader(ACCEPT, APPLICATION_JSON)\n         .addHeader(\"Auth-Token\", authToken)\n         .payload(stringPayload(\"{\\\"thaw\\\":true}\"))\n         .build();   \n\n   public void testThawWhenResponseIs2xx() {\n      DynECTApi success = requestsSendResponses(createSession, createSessionResponse, thaw, deleteResponse);\n      assertEquals(success.getZoneApi().thaw(\"jclouds.org\").toString(),\n                   new DeleteZoneResponseTest().expected().toString());\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/test/java/org/jclouds/dynect/v3/features/ZoneApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.features;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static java.util.logging.Logger.getAnonymousLogger;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\n\nimport org.jclouds.JcloudsVersion;\nimport org.jclouds.dynect.v3.domain.Job;\nimport org.jclouds.dynect.v3.domain.Job.Status;\nimport org.jclouds.dynect.v3.domain.Zone;\nimport org.jclouds.dynect.v3.internal.BaseDynECTApiLiveTest;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"ZoneApiLiveTest\")\npublic class ZoneApiLiveTest extends BaseDynECTApiLiveTest {\n\n   private void checkZone(Zone zone) {\n      checkNotNull(zone.getFQDN(), \"FQDN cannot be null for a Zone: %s\", zone);\n   }\n\n   @Test\n   protected void testListAndGetZones() {\n      ImmutableList<String> zones = api().list().toList();\n      getAnonymousLogger().info(\"zones: \" + zones.size());\n\n      for (String fqdn : zones) {\n         Zone zone = api().get(fqdn);\n         checkNotNull(zone, \"zone was null for Zone: %s\", fqdn);\n         checkZone(zone);\n      }\n   }\n\n   @Test\n   public void testGetZoneWhenNotFound() {\n      assertNull(api().get(\"AAAAAAAAAAAAAAAA.foo.com\"));\n   }\n\n   @Test\n   public void testDeleteZoneWhenNotFound() {\n      assertNull(api().delete(\"AAAAAAAAAAAAAAAA.foo.com\"));\n   }\n\n   String fqdn = System.getProperty(\"user.name\").replace('.', '-') + \".zone.dynecttest.jclouds.org\";\n   String contact = JcloudsVersion.get() + \".jclouds.org\";\n\n   @Test\n   public void testCreateZone() {\n      Job job = api().scheduleCreateWithContact(fqdn, contact);\n      checkNotNull(job, \"unable to create zone %s\", fqdn);\n      getAnonymousLogger().info(\"created zone: \" + job);\n      assertEquals(job.getStatus(), Status.SUCCESS);\n      assertEquals(api.getJob(job.getId()), job);\n   }\n\n   @Test(dependsOnMethods = \"testCreateZone\")\n   public void testPublishZone() {\n      Zone zone = api().publish(fqdn);\n      checkNotNull(zone, \"unable to publish zone %s\", fqdn);\n      getAnonymousLogger().info(\"published zone: \" + zone);\n      checkZone(zone);\n   }\n\n   @Test(dependsOnMethods = \"testPublishZone\")\n   public void testFreezeZone() {\n      Job job = api().freeze(fqdn);\n      assertEquals(job.getStatus(), Status.SUCCESS);\n      assertEquals(api.getJob(job.getId()), job);\n      // TODO: determine how to prove it is frozen\n   }\n\n   @Test(dependsOnMethods = \"testFreezeZone\")\n   public void testThawZone() {\n      Job job = api().thaw(fqdn);\n      assertEquals(job.getStatus(), Status.SUCCESS);\n      assertEquals(api.getJob(job.getId()), job);\n      // TODO: determine how to prove it is thawed\n   }\n\n   @Test(dependsOnMethods = \"testThawZone\")\n   public void testDeleteZoneChanges() {\n      Job job = api().deleteChanges(fqdn);\n      assertEquals(job.getStatus(), Status.SUCCESS);\n      assertEquals(api.getJob(job.getId()), job);\n   }\n\n   @Test(dependsOnMethods = \"testDeleteZoneChanges\")\n   public void testDeleteZone() {\n      Job job = api().delete(fqdn);\n      assertEquals(job.getStatus(), Status.SUCCESS);\n      assertEquals(api.getJob(job.getId()), job);\n      assertNull(api().get(fqdn), \"job \" + job + \" didn't delete zone\" + fqdn);\n   }\n\n   protected ZoneApi api() {\n      return api.getZoneApi();\n   }\n\n   @Override\n   @AfterClass(groups = \"live\", alwaysRun = true)\n   protected void tearDown() {\n      api().delete(fqdn);\n      super.tearDown();\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/test/java/org/jclouds/dynect/v3/filters/SessionManagerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.filters;\n\nimport static com.google.common.io.Resources.getResource;\nimport static jakarta.ws.rs.core.Response.Status.BAD_REQUEST;\nimport static jakarta.ws.rs.core.Response.Status.FORBIDDEN;\nimport static jakarta.ws.rs.core.Response.Status.UNAUTHORIZED;\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.expectLastCall;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertSame;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\n\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.dynect.v3.domain.Session;\nimport org.jclouds.dynect.v3.domain.SessionCredentials;\nimport org.jclouds.dynect.v3.features.SessionApi;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.LoadingCache;\n@Test(groups = \"unit\", testName = \"SessionManagerTest\")\npublic class SessionManagerTest {\n   SessionCredentials creds = SessionCredentials.builder()\n                                                .customerName(\"customer\")\n                                                .userName(\"robbie\")\n                                                .password(\"password\").build();\n\n   Session session = Session.forTokenAndVersion(\"token\", \"version\");\n\n   public void testAlreadySessionCredentials() {\n      assertSame(SessionManager.convert(creds), creds);\n   }\n\n   public void testConvertCredentialsParsesCustomer() {\n      assertEquals(SessionManager.convert(new Credentials(\"customer:robbie\", \"password\")), creds);\n   }\n\n   public void testCacheLoadLogsIn() {\n      SessionApi sessionApi = createMock(SessionApi.class);\n      expect(sessionApi.login(creds)).andReturn(session);\n      replay(sessionApi);\n\n      assertSame(SessionManager.buildCache(sessionApi).getUnchecked(creds), session);\n\n      verify(sessionApi);\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Test\n   public void testUnauthorizedShouldInvalidateSessionAndRetry() {\n      HttpCommand command = createMock(HttpCommand.class);\n      Supplier<Credentials> creds = createMock(Supplier.class);\n      LoadingCache<Credentials, Session> sessionCache = createMock(LoadingCache.class);\n      SessionApi sessionApi = createMock(SessionApi.class);\n\n      sessionCache.invalidateAll();\n      expectLastCall();\n      expect(command.incrementFailureCount()).andReturn(1);\n      expect(command.isReplayable()).andReturn(true);\n      expect(command.getFailureCount()).andReturn(1).atLeastOnce();\n\n      replay(creds, sessionCache, sessionApi, command);\n\n      HttpResponse response = HttpResponse.builder().statusCode(UNAUTHORIZED.getStatusCode()).build();\n\n      SessionManager retry = new SessionManager(creds, sessionCache, sessionApi);\n\n      assertTrue(retry.shouldRetryRequest(command, response));\n\n      verify(creds, sessionCache, sessionApi, command);\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Test\n   public void testIPMismatchShouldInvalidateSessionAndRetry() throws IOException {\n      HttpCommand command = createMock(HttpCommand.class);\n      Supplier<Credentials> creds = createMock(Supplier.class);\n      LoadingCache<Credentials, Session> sessionCache = createMock(LoadingCache.class);\n      SessionApi sessionApi = createMock(SessionApi.class);\n\n      sessionCache.invalidateAll();\n      expectLastCall();\n      expect(command.incrementFailureCount()).andReturn(1);\n      expect(command.isReplayable()).andReturn(true);\n      expect(command.getFailureCount()).andReturn(1).atLeastOnce();\n\n      replay(creds, sessionCache, sessionApi, command);\n\n      HttpResponse response = HttpResponse.builder()\n                                          .statusCode(BAD_REQUEST.getStatusCode())\n                                          .payload(getResource(\"ip_mismatch.json\").openStream())\n                                          .build();\n\n      SessionManager retry = new SessionManager(creds, sessionCache, sessionApi);\n\n      assertTrue(retry.shouldRetryRequest(command, response));\n\n      verify(creds, sessionCache, sessionApi, command);\n   }\n\n   @SuppressWarnings(\"unchecked\")\n   @Test\n   public void testForbiddenShouldNotInvalidateSessionOrRetry() {\n      HttpCommand command = createMock(HttpCommand.class);\n      Supplier<Credentials> creds = createMock(Supplier.class);\n      LoadingCache<Credentials, Session> sessionCache = createMock(LoadingCache.class);\n      SessionApi sessionApi = createMock(SessionApi.class);\n\n      replay(creds, sessionCache, sessionApi, command);\n\n      HttpResponse response = HttpResponse.builder().statusCode(FORBIDDEN.getStatusCode()).build();\n\n      SessionManager retry = new SessionManager(creds, sessionCache, sessionApi);\n\n      assertFalse(retry.shouldRetryRequest(command, response));\n\n      verify(creds, sessionCache, sessionApi, command);\n   }\n\n}\n"
  },
  {
    "path": "providers/dynect/src/test/java/org/jclouds/dynect/v3/functions/ExtractLastPathComponentTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.dynect.v3.functions.ExtractLastPathComponent.ExtractNameInPath;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\")\npublic class ExtractLastPathComponentTest {\n   ExtractLastPathComponent fn = new ExtractLastPathComponent();\n\n   public void testExtractNameInPath() {\n      assertEquals(ExtractNameInPath.INSTANCE.apply(\"/REST/Zone/jclouds.org/\"), \"jclouds.org\");\n   }\n\n   public void testExtractLastPathComponent() {\n      assertEquals(fn.apply(FluentIterable.from(ImmutableSet.of(\"/REST/Zone/jclouds.org/\"))).toSet(),\n            ImmutableSet.of(\"jclouds.org\"));\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/test/java/org/jclouds/dynect/v3/functions/ToRecordIdsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.functions;\n\nimport static org.jclouds.dynect.v3.domain.RecordId.recordIdBuilder;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.dynect.v3.domain.RecordId;\nimport org.jclouds.dynect.v3.functions.ToRecordIds.ParsePath;\nimport org.jclouds.json.internal.GsonWrapper;\nimport org.testng.annotations.Test;\n\nimport com.google.gson.Gson;\n\n@Test(groups = \"unit\")\npublic class ToRecordIdsTest {\n   ToRecordIds fn = new ToRecordIds(new GsonWrapper(new Gson()));\n   RecordId recordId = recordIdBuilder()\n                               .id(50976583)\n                               .type(\"NS\")\n                               .zone(\"adrianc.zone.dynecttest.jclouds.org\")\n                               .fqdn(\"adrianc.zone.dynecttest.jclouds.org\")\n                               .build();\n\n   public void testParsePath() {\n      assertEquals(\n            ParsePath.INSTANCE\n                  .apply(\"/REST/NSRecord/adrianc.zone.dynecttest.jclouds.org/adrianc.zone.dynecttest.jclouds.org/50976583\"),\n            recordId);\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/test/java/org/jclouds/dynect/v3/handlers/GetJobRedirectionRetryHandlerExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.handlers;\nimport static com.google.common.net.HttpHeaders.ACCEPT;\nimport static com.google.common.net.HttpHeaders.CONTENT_TYPE;\nimport static com.google.common.net.HttpHeaders.LOCATION;\nimport static jakarta.ws.rs.HttpMethod.GET;\nimport static jakarta.ws.rs.HttpMethod.PUT;\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\nimport static jakarta.ws.rs.core.Response.Status.TEMPORARY_REDIRECT;\n\nimport org.jclouds.dynect.v3.DynECTApi;\nimport org.jclouds.dynect.v3.internal.BaseDynECTApiExpectTest;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"GetJobRedirectionRetryHandlerExpectTest\")\npublic class GetJobRedirectionRetryHandlerExpectTest extends BaseDynECTApiExpectTest {\n\n   public void testRedirectOnJobLocationSwitchesToGETAndNoPayload() {\n\n      HttpRequest thaw = HttpRequest.builder().method(PUT)\n                                    .endpoint(\"https://api2.dynect.net/REST/Zone/jclouds.org\")\n                                    .addHeader(\"API-Version\", \"3.3.8\")\n                                    .addHeader(ACCEPT, APPLICATION_JSON)\n                                    .addHeader(\"Auth-Token\", authToken)\n                                    .payload(stringPayload(\"{\\\"thaw\\\":true}\"))\n                                    .build();\n\n      HttpResponse redirectResponse = HttpResponse.builder() \n                                                  .statusCode(TEMPORARY_REDIRECT.getStatusCode())\n                                                  .addHeader(LOCATION, \"https://api2.dynect.net/REST/Job/1234\")\n                                                  .build();\n\n      HttpRequest job = HttpRequest.builder().method(GET)\n                                   .endpoint(\"https://api2.dynect.net/REST/Job/1234\")\n                                   .addHeader(\"API-Version\", \"3.3.8\")\n                                   .addHeader(ACCEPT, APPLICATION_JSON)\n                                   .addHeader(CONTENT_TYPE, APPLICATION_JSON)\n                                   .addHeader(\"Auth-Token\", authToken).build();\n\n      HttpResponse success = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResourceWithContentType(\"/delete_zone.json\", APPLICATION_JSON)).build();\n\n      DynECTApi apiThatRedirects = requestsSendResponses(createSession, createSessionResponse, thaw, redirectResponse,\n            job, success);\n      \n      apiThatRedirects.getZoneApi().thaw(\"jclouds.org\");\n\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/test/java/org/jclouds/dynect/v3/internal/BaseDynECTApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.internal;\n\nimport org.jclouds.dynect.v3.DynECTApi;\n\n/**\n * Base class for writing DynECT Expect tests\n */\npublic class BaseDynECTApiExpectTest extends BaseDynECTExpectTest<DynECTApi> {\n\n}\n"
  },
  {
    "path": "providers/dynect/src/test/java/org/jclouds/dynect/v3/internal/BaseDynECTApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.internal;\n\nimport org.jclouds.apis.BaseApiLiveTest;\nimport org.jclouds.dynect.v3.DynECTApi;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\")\npublic class BaseDynECTApiLiveTest extends BaseApiLiveTest<DynECTApi> {\n   public BaseDynECTApiLiveTest() {\n      provider = \"dynect\";\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/test/java/org/jclouds/dynect/v3/internal/BaseDynECTExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.internal;\nimport static jakarta.ws.rs.HttpMethod.POST;\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\nimport static jakarta.ws.rs.core.Response.Status.NOT_FOUND;\nimport static jakarta.ws.rs.core.Response.Status.OK;\n\nimport org.jclouds.dynect.v3.config.DynECTHttpApiModule;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.config.SSLModule;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.internal.BaseRestApiExpectTest;\n\nimport com.google.inject.Module;\n\n/**\n * Base class for writing DynECT Expect tests\n */\npublic class BaseDynECTExpectTest<T> extends BaseRestApiExpectTest<T> {\n   public BaseDynECTExpectTest() {\n      provider = \"dynect\";\n      identity = \"jclouds:joe\";\n      credential = \"letmein\";\n   }\n\n   @Override\n   protected Module createModule() {\n      return new TestDynECTHttpApiModule();\n   }\n\n   @ConfiguresHttpApi\n   private static final class TestDynECTHttpApiModule extends DynECTHttpApiModule {\n      @Override\n      protected void configure() {\n         install(new SSLModule());\n         super.configure();\n      }\n   }\n\n   public static Payload stringPayload(String json) {\n      Payload p = Payloads.newPayload(json);\n      p.getContentMetadata().setContentType(APPLICATION_JSON);\n      return p;\n   }\n\n   @Override\n   protected HttpRequestComparisonType compareHttpRequestAsType(HttpRequest input) {\n      return HttpRequestComparisonType.JSON;\n   }\n\n   protected String authToken = \"FFFFFFFFFF\";\n\n   protected HttpRequest createSession = HttpRequest.builder()\n         .method(POST)\n         .endpoint(\"https://api2.dynect.net/REST/Session\")\n         .addHeader(\"API-Version\", \"3.3.8\")\n         .payload(\n               payloadFromStringWithContentType(\n                     \"{\\\"customer_name\\\":\\\"jclouds\\\",\\\"user_name\\\":\\\"joe\\\",\\\"password\\\":\\\"letmein\\\"}\", APPLICATION_JSON))\n         .build();\n\n   protected HttpResponse createSessionResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/create_session.json\", APPLICATION_JSON)).build();\n\n   protected HttpResponse notFound = HttpResponse.builder().statusCode(NOT_FOUND.getStatusCode()).build();\n}\n"
  },
  {
    "path": "providers/dynect/src/test/java/org/jclouds/dynect/v3/internal/BaseDynECTParseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.internal;\n\nimport org.jclouds.dynect.v3.config.DynECTParserModule;\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.json.config.GsonModule;\n\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\npublic abstract class BaseDynECTParseTest<T> extends BaseItemParserTest<T> {\n\n   @Override\n   protected Injector injector() {\n      return Guice.createInjector(new GsonModule(), new DynECTParserModule());\n   }\n\n}\n"
  },
  {
    "path": "providers/dynect/src/test/java/org/jclouds/dynect/v3/parse/CreateSessionResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.parse;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.dynect.v3.domain.Session;\nimport org.jclouds.dynect.v3.internal.BaseDynECTParseTest;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class CreateSessionResponseTest extends BaseDynECTParseTest<Session> {\n\n   @Override\n   public String resource() {\n      return \"/create_session.json\";\n   }\n\n   @Override\n   @SelectJson(\"data\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Session expected() {\n      return Session.forTokenAndVersion(\"FFFFFFFFFF\", \"3.3.8\");\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/test/java/org/jclouds/dynect/v3/parse/DeleteZoneChangesResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.parse;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.dynect.v3.domain.Job;\nimport org.jclouds.dynect.v3.internal.BaseDynECTParseTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class DeleteZoneChangesResponseTest extends BaseDynECTParseTest<Job> {\n\n   @Override\n   public String resource() {\n      return \"/delete_zone_changes.json\";\n   }\n\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Job expected() {\n      return Job.success(275625520L);\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/test/java/org/jclouds/dynect/v3/parse/DeleteZoneResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.parse;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.dynect.v3.domain.Job;\nimport org.jclouds.dynect.v3.internal.BaseDynECTParseTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class DeleteZoneResponseTest extends BaseDynECTParseTest<Job> {\n\n   @Override\n   public String resource() {\n      return \"/delete_zone.json\";\n   }\n\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Job expected() {\n      return Job.success(262989027L);\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/test/java/org/jclouds/dynect/v3/parse/GetAAAARecordResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.parse;\nimport static org.jclouds.dynect.v3.domain.rdata.AAAAData.aaaa;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.dynect.v3.domain.Record;\nimport org.jclouds.dynect.v3.domain.rdata.AAAAData;\nimport org.jclouds.dynect.v3.internal.BaseDynECTParseTest;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class GetAAAARecordResponseTest extends BaseDynECTParseTest<Record<AAAAData>> {\n\n   @Override\n   public String resource() {\n      return \"/get_record_aaaa.json\";\n   }\n\n   @Override\n   @SelectJson(\"data\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Record<AAAAData> expected() {\n      return Record.<AAAAData> builder()\n                   .zone(\"egg.org\")\n                   .fqdn(\"egg.org\")\n                   .type(\"AAAA\")\n                   .id(50959331)\n                   .ttl(86400)\n                   .rdata(aaaa(\"2406:bbbb:ff00::6b14:aaaa\"))\n                   .build();\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/test/java/org/jclouds/dynect/v3/parse/GetARecordResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.parse;\nimport static org.jclouds.dynect.v3.domain.rdata.AData.a;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.dynect.v3.domain.Record;\nimport org.jclouds.dynect.v3.domain.rdata.AData;\nimport org.jclouds.dynect.v3.internal.BaseDynECTParseTest;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class GetARecordResponseTest extends BaseDynECTParseTest<Record<AData>> {\n\n   @Override\n   public String resource() {\n      return \"/get_record_a.json\";\n   }\n\n   @Override\n   @SelectJson(\"data\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Record<AData> expected() {\n      return Record.<AData> builder()\n                   .zone(\"egg.org\")\n                   .fqdn(\"egg.org\")\n                   .type(\"A\")\n                   .id(50959331)\n                   .ttl(86400)\n                   .rdata(a(\"1.1.1.1\"))\n                   .build();\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/test/java/org/jclouds/dynect/v3/parse/GetCNAMERecordResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.parse;\nimport static org.jclouds.dynect.v3.domain.rdata.CNAMEData.cname;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.dynect.v3.domain.Record;\nimport org.jclouds.dynect.v3.domain.rdata.CNAMEData;\nimport org.jclouds.dynect.v3.internal.BaseDynECTParseTest;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class GetCNAMERecordResponseTest extends BaseDynECTParseTest<Record<CNAMEData>> {\n\n   @Override\n   public String resource() {\n      return \"/get_record_cname.json\";\n   }\n\n   @Override\n   @SelectJson(\"data\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Record<CNAMEData> expected() {\n      return Record.<CNAMEData> builder()\n                   .zone(\"egg.org\")\n                   .fqdn(\"egg.org\")\n                   .type(\"CNAME\")\n                   .id(50959331)\n                   .ttl(86400)\n                   .rdata(cname(\"prod-LB-359594650.us-east-1.elb.amazonaws.com.\"))\n                   .build();\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/test/java/org/jclouds/dynect/v3/parse/GetGeoRegionGroupResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.parse;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.dynect.v3.domain.RecordSet;\nimport org.jclouds.dynect.v3.domain.RecordSet.Value;\nimport org.jclouds.dynect.v3.domain.GeoRegionGroup;\nimport org.jclouds.dynect.v3.internal.BaseDynECTParseTest;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\n\n@Test(groups = \"unit\")\npublic class GetGeoRegionGroupResponseTest extends BaseDynECTParseTest<GeoRegionGroup> {\n\n   @Override\n   public String resource() {\n      return \"/get_geo_regiongroup.json\";\n   }\n\n   @Override\n   @SelectJson(\"data\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public GeoRegionGroup expected() {\n      return GeoRegionGroup\n            .builder()\n            .name(\"Everywhere Else\")\n            .countries(ImmutableList.of(\"11\", \"16\", \"12\", \"17\", \"15\", \"14\"))\n            .serviceName(\"CCS\")\n            .addRecordSet(\n                  RecordSet\n                        .builder()\n                        .ttl(0)\n                        .type(\"CNAME\")\n                        .add(Value\n                              .builder()\n                              .rdata(\n                                    ImmutableMap.<String, Object> builder()\n                                          .put(\"cname\", \"srv-938089264.us-east-1.elb.amazonaws.com.\").build()).build())\n                        .build()).build();\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/test/java/org/jclouds/dynect/v3/parse/GetGeoServiceResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.parse;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.dynect.v3.domain.GeoService;\nimport org.jclouds.dynect.v3.domain.Node;\nimport org.jclouds.dynect.v3.domain.RecordSet;\nimport org.jclouds.dynect.v3.domain.GeoRegionGroup;\nimport org.jclouds.dynect.v3.domain.RecordSet.Value;\nimport org.jclouds.dynect.v3.internal.BaseDynECTParseTest;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\n\n@Test(groups = \"unit\")\npublic class GetGeoServiceResponseTest extends BaseDynECTParseTest<GeoService> {\n\n   @Override\n   public String resource() {\n      return \"/get_geo_service.json\";\n   }\n\n   @Override\n   @SelectJson(\"data\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public GeoService expected() {\n      return GeoService\n            .builder()\n            .name(\"CCS\")\n            .active(true)\n            .ttl(30)\n            .addNode(Node.create(\"jclouds.org\", \"srv.jclouds.org\"))\n            .addGroup(\n                  GeoRegionGroup\n                        .builder()\n                        .name(\"Everywhere Else\")\n                        .countries(ImmutableList.of(\"11\", \"16\", \"12\", \"17\", \"15\", \"14\"))\n                        .addRecordSet(\n                              RecordSet\n                                    .builder()\n                                    .ttl(0)\n                                    .type(\"CNAME\")\n                                    .add(Value\n                                          .builder()\n                                          .rdata(\n                                                ImmutableMap.<String, Object> builder()\n                                                      .put(\"cname\", \"srv-000000001.us-east-1.elb.amazonaws.com.\")\n                                                      .build()).build()).build()).build())\n            .addGroup(\n                  GeoRegionGroup\n                        .builder()\n                        .name(\"Europe\")\n                        .countries(ImmutableList.of(\"13\"))\n                        .addRecordSet(\n                              RecordSet\n                                    .builder()\n                                    .ttl(0)\n                                    .type(\"CNAME\")\n                                    .add(Value\n                                          .builder()\n                                          .rdata(\n                                                ImmutableMap.<String, Object> builder()\n                                                      .put(\"cname\", \"srv-000000001.eu-west-1.elb.amazonaws.com.\")\n                                                      .build()).build()).build()).build())\n            .addGroup(\n                  GeoRegionGroup\n                        .builder()\n                        .name(\"Fallback\")\n                        .countries(ImmutableList.of(\"@!\", \"@@\"))\n                        .addRecordSet(\n                              RecordSet\n                                    .builder()\n                                    .ttl(0)\n                                    .type(\"CNAME\")\n                                    .add(Value\n                                          .builder()\n                                          .rdata(\n                                                ImmutableMap.<String, Object> builder()\n                                                      .put(\"cname\", \"srv-000000002.us-east-1.elb.amazonaws.com.\")\n                                                      .build()).build()).build()).build()).build();\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/test/java/org/jclouds/dynect/v3/parse/GetMXRecordResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.parse;\nimport static org.jclouds.dynect.v3.domain.rdata.MXData.mx;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.dynect.v3.domain.Record;\nimport org.jclouds.dynect.v3.domain.rdata.MXData;\nimport org.jclouds.dynect.v3.internal.BaseDynECTParseTest;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class GetMXRecordResponseTest extends BaseDynECTParseTest<Record<MXData>> {\n\n   @Override\n   public String resource() {\n      return \"/get_record_mx.json\";\n   }\n\n   @Override\n   @SelectJson(\"data\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Record<MXData> expected() {\n      return Record.<MXData> builder()\n                   .zone(\"egg.org\")\n                   .fqdn(\"egg.org\")\n                   .type(\"MX\")\n                   .id(50959331)\n                   .ttl(86400)\n                   .rdata(mx(10, \"mail.egg.org.\"))\n                   .build();\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/test/java/org/jclouds/dynect/v3/parse/GetNSRecordResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.parse;\nimport static org.jclouds.dynect.v3.domain.rdata.NSData.ns;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.dynect.v3.domain.Record;\nimport org.jclouds.dynect.v3.domain.rdata.NSData;\nimport org.jclouds.dynect.v3.internal.BaseDynECTParseTest;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class GetNSRecordResponseTest extends BaseDynECTParseTest<Record<NSData>> {\n\n   @Override\n   public String resource() {\n      return \"/get_record_ns.json\";\n   }\n\n   @Override\n   @SelectJson(\"data\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Record<NSData> expected() {\n      return Record.<NSData> builder()\n                   .zone(\"egg.org\")\n                   .fqdn(\"egg.org\")\n                   .type(\"NS\")\n                   .id(50959331)\n                   .ttl(86400)\n                   .rdata(ns(\"ns4.p28.dynect.net.\"))\n                   .build();\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/test/java/org/jclouds/dynect/v3/parse/GetPTRRecordResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.parse;\nimport static org.jclouds.dynect.v3.domain.rdata.PTRData.ptr;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.dynect.v3.domain.Record;\nimport org.jclouds.dynect.v3.domain.rdata.PTRData;\nimport org.jclouds.dynect.v3.internal.BaseDynECTParseTest;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class GetPTRRecordResponseTest extends BaseDynECTParseTest<Record<PTRData>> {\n\n   @Override\n   public String resource() {\n      return \"/get_record_ptr.json\";\n   }\n\n   @Override\n   @SelectJson(\"data\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Record<PTRData> expected() {\n      return Record.<PTRData> builder()\n                   .zone(\"egg.org\")\n                   .fqdn(\"1.2.3.0.0.0.0.0.0.0.0.0.0.0.0.0.d.9.2.1.4.0.0.7.0.c.6.8.0.0.a.2.ip6.arpa\")\n                   .type(\"PTR\")\n                   .id(50959331)\n                   .ttl(86400)\n                   .rdata(ptr(\"egg.org.\"))\n                   .build();\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/test/java/org/jclouds/dynect/v3/parse/GetRecordResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.parse;\n\nimport java.util.Map;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.dynect.v3.domain.Record;\nimport org.jclouds.dynect.v3.internal.BaseDynECTParseTest;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\n\n@Test(groups = \"unit\")\npublic class GetRecordResponseTest extends BaseDynECTParseTest<Record<Map<String, Object>>> {\n\n   @Override\n   public String resource() {\n      return \"/get_record_soa.json\";\n   }\n\n   @Override\n   @SelectJson(\"data\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Record<Map<String, Object>> expected() {\n      return Record.<Map<String, Object>> builder()\n                   .zone(\"adrianc.zone.dynecttest.jclouds.org\")\n                   .fqdn(\"adrianc.zone.dynecttest.jclouds.org\")\n                   .type(\"SOA\")\n                   .id(50976579L)\n                   .ttl(3600)\n                   // TODO: default parse to unsigned\n                   .rdata(ImmutableMap.<String, Object> builder()\n                                      .put(\"rname\", \"1\\\\.5\\\\.7-SNAPSHOT@jclouds.org.\")\n                                      .put(\"retry\", 600.0)\n                                      .put(\"mname\", \"ns1.p28.dynect.net.\")\n                                      .put(\"minimum\", 60.0)\n                                      .put(\"refresh\", 3600.0)\n                                      .put(\"expire\", 604800.0)\n                                      .put(\"serial\", 1.0).build()).build();\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/test/java/org/jclouds/dynect/v3/parse/GetSOARecordResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.parse;\n\nimport static org.jclouds.dynect.v3.domain.Zone.SerialStyle.INCREMENT;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.dynect.v3.domain.SOARecord;\nimport org.jclouds.dynect.v3.domain.rdata.SOAData;\nimport org.jclouds.dynect.v3.internal.BaseDynECTParseTest;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class GetSOARecordResponseTest extends BaseDynECTParseTest<SOARecord> {\n\n   @Override\n   public String resource() {\n      return \"/get_record_soa.json\";\n   }\n\n   @Override\n   @SelectJson(\"data\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public SOARecord expected() {\n      return SOARecord.builder()\n                      .zone(\"adrianc.zone.dynecttest.jclouds.org\")\n                      .fqdn(\"adrianc.zone.dynecttest.jclouds.org\")\n                      .type(\"SOA\")\n                      .id(50976579L)\n                      .ttl(3600)\n                      .serialStyle(INCREMENT)\n                      .rdata(SOAData.builder()\n                                    .rname(\"1\\\\.5\\\\.7-SNAPSHOT@jclouds.org.\")\n                                    .retry(600)\n                                    .mname(\"ns1.p28.dynect.net.\")\n                                    .minimum(60)\n                                    .refresh(3600)\n                                    .expire(604800)\n                                    .serial(1).build()).build();\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/test/java/org/jclouds/dynect/v3/parse/GetSPFRecordResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.parse;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.dynect.v3.domain.Record;\nimport org.jclouds.dynect.v3.domain.rdata.SPFData;\nimport org.jclouds.dynect.v3.internal.BaseDynECTParseTest;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class GetSPFRecordResponseTest extends BaseDynECTParseTest<Record<SPFData>> {\n\n   @Override\n   public String resource() {\n      return \"/get_record_spf.json\";\n   }\n\n   @Override\n   @SelectJson(\"data\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Record<SPFData> expected() {\n      return Record.<SPFData> builder()\n                   .zone(\"adrianc.zone.dynecttest.jclouds.org\")\n                   .fqdn(\"_http._tcp.www.jclouds.org.\")\n                   .type(\"SPF\")\n                   .id(50976579L)\n                   .ttl(3600)\n                   .rdata(SPFData.create(\"v=spf1 a -all\")).build();\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/test/java/org/jclouds/dynect/v3/parse/GetSRVRecordResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.parse;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.dynect.v3.domain.Record;\nimport org.jclouds.dynect.v3.domain.rdata.SRVData;\nimport org.jclouds.dynect.v3.internal.BaseDynECTParseTest;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class GetSRVRecordResponseTest extends BaseDynECTParseTest<Record<SRVData>> {\n\n   @Override\n   public String resource() {\n      return \"/get_record_srv.json\";\n   }\n\n   @Override\n   @SelectJson(\"data\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Record<SRVData> expected() {\n      return Record.<SRVData> builder()\n                   .zone(\"adrianc.zone.dynecttest.jclouds.org\")\n                   .fqdn(\"_http._tcp.www.jclouds.org.\")\n                   .type(\"SRV\")\n                   .id(50976579L)\n                   .ttl(3600)\n                   .rdata(SRVData.builder()\n                                 .priority(0)\n                                 .weight(2)\n                                 .port(80)\n                                 .target(\"www.jclouds.org.\").build()).build();\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/test/java/org/jclouds/dynect/v3/parse/GetSSHFPRecordResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.parse;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.dynect.v3.domain.Record;\nimport org.jclouds.dynect.v3.domain.rdata.SSHFPData;\nimport org.jclouds.dynect.v3.internal.BaseDynECTParseTest;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class GetSSHFPRecordResponseTest extends BaseDynECTParseTest<Record<SSHFPData>> {\n\n    @Override\n    public String resource() {\n        return \"/get_record_sshfp.json\";\n    }\n\n    @Override\n    @SelectJson(\"data\")\n    @Consumes(MediaType.APPLICATION_JSON)\n    public Record<SSHFPData> expected() {\n        return Record.<SSHFPData> builder().zone(\"adrianc.zone.dynecttest.jclouds.org\")\n                .fqdn(\"_http._tcp.www.jclouds.org.\").type(\"SSHFP\").id(50976579L).ttl(3600)\n                .rdata(SSHFPData.builder().algorithm(2).fptype(1).fingerprint(\"190E37C5B5DB9A1C455E648A41AF3CC83F99F102\").build()).build();\n    }\n}\n"
  },
  {
    "path": "providers/dynect/src/test/java/org/jclouds/dynect/v3/parse/GetTXTRecordResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.parse;\nimport static org.jclouds.dynect.v3.domain.rdata.TXTData.txt;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.dynect.v3.domain.Record;\nimport org.jclouds.dynect.v3.domain.rdata.TXTData;\nimport org.jclouds.dynect.v3.internal.BaseDynECTParseTest;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class GetTXTRecordResponseTest extends BaseDynECTParseTest<Record<TXTData>> {\n\n   @Override\n   public String resource() {\n      return \"/get_record_txt.json\";\n   }\n\n   @Override\n   @SelectJson(\"data\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Record<TXTData> expected() {\n      return Record.<TXTData> builder()\n                   .zone(\"egg.org\")\n                   .fqdn(\"sm._domainkey.email.egg.org\")\n                   .type(\"TXT\")\n                   .id(50959331)\n                   .ttl(86400)\n                   .rdata(txt(\"k=rsa\\\\; p=4KAtUdsUGRtjPHE1rsyFYs8XVzvdke8pXnoo+80Kj5b6C37rnyCmZ0w1R5LY==\"))\n                   .build();\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/test/java/org/jclouds/dynect/v3/parse/GetZoneResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.parse;\n\nimport static org.jclouds.dynect.v3.domain.Zone.SerialStyle.INCREMENT;\nimport static org.jclouds.dynect.v3.domain.Zone.Type.PRIMARY;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.dynect.v3.domain.Zone;\nimport org.jclouds.dynect.v3.internal.BaseDynECTParseTest;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class GetZoneResponseTest extends BaseDynECTParseTest<Zone> {\n\n   @Override\n   public String resource() {\n      return \"/get_zone.json\";\n   }\n\n   @Override\n   @SelectJson(\"data\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Zone expected() {\n      return Zone.builder().type(PRIMARY).serialStyle(INCREMENT).serial(5).fqdn(\"jclouds.org\").build();\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/test/java/org/jclouds/dynect/v3/parse/ListGeoRegionGroupsResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.parse;\n\nimport static com.google.common.base.Functions.compose;\n\nimport org.jclouds.dynect.v3.functions.ExtractLastPathComponent;\nimport org.jclouds.dynect.v3.internal.BaseDynECTParseTest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\")\npublic class ListGeoRegionGroupsResponseTest extends BaseDynECTParseTest<FluentIterable<String>> {\n\n   @Override\n   public String resource() {\n      return \"/list_geo_regiongroups.json\";\n   }\n\n   @Override\n   @SelectJson(\"data\")\n   public FluentIterable<String> expected() {\n      return FluentIterable.from(ImmutableSet.of(\"Everywhere Else\", \"Europe\", \"Fallback\"));\n   }\n\n   // TODO: currently our parsing of annotations on expected() ignores\n   // @Transform\n   @Override\n   protected Function<HttpResponse, FluentIterable<String>> parser(Injector i) {\n      return compose(new ExtractLastPathComponent(), super.parser(i));\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/test/java/org/jclouds/dynect/v3/parse/ListGeoServicesResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.parse;\n\nimport static com.google.common.base.Functions.compose;\n\nimport org.jclouds.dynect.v3.functions.ExtractLastPathComponent;\nimport org.jclouds.dynect.v3.internal.BaseDynECTParseTest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\")\npublic class ListGeoServicesResponseTest extends BaseDynECTParseTest<FluentIterable<String>> {\n\n   @Override\n   public String resource() {\n      return \"/list_geo_services.json\";\n   }\n\n   @Override\n   @SelectJson(\"data\")\n   public FluentIterable<String> expected() {\n      return FluentIterable.from(ImmutableSet.of(\"srv\", \"srv-log\"));\n   }\n\n   // TODO: currently our parsing of annotations on expected() ignores\n   // @Transform\n   @Override\n   protected Function<HttpResponse, FluentIterable<String>> parser(Injector i) {\n      return compose(new ExtractLastPathComponent(), super.parser(i));\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/test/java/org/jclouds/dynect/v3/parse/ListRecordsResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.parse;\n\nimport static org.jclouds.dynect.v3.domain.RecordId.recordIdBuilder;\n\nimport org.jclouds.dynect.v3.domain.RecordId;\nimport org.jclouds.dynect.v3.domain.RecordId.Builder;\nimport org.jclouds.dynect.v3.functions.ToRecordIds;\nimport org.jclouds.dynect.v3.internal.BaseDynECTParseTest;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\")\npublic class ListRecordsResponseTest extends BaseDynECTParseTest<FluentIterable<RecordId>> {\n\n   @Override\n   public String resource() {\n      return \"/list_records.json\";\n   }\n\n   @Override\n   @ResponseParser(ToRecordIds.class)\n   public FluentIterable<RecordId> expected() {\n      Builder<?> builder = recordIdBuilder()\n                                   .zone(\"adrianc.zone.dynecttest.jclouds.org\")\n                                   .fqdn(\"adrianc.zone.dynecttest.jclouds.org\");\n      return FluentIterable.from(ImmutableSet.<RecordId> builder()\n                                             .add(builder.type(\"SOA\").id(50976579L).build())\n                                             .add(builder.type(\"NS\").id(50976580L).build())\n                                             .add(builder.type(\"NS\").id(50976581L).build())\n                                             .add(builder.type(\"NS\").id(50976582L).build())\n                                             .add(builder.type(\"NS\").id(50976583L).build())\n                                             .build());\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/test/java/org/jclouds/dynect/v3/parse/ListZonesResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.parse;\n\nimport static com.google.common.base.Functions.compose;\n\nimport org.jclouds.dynect.v3.functions.ExtractLastPathComponent;\nimport org.jclouds.dynect.v3.internal.BaseDynECTParseTest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\")\npublic class ListZonesResponseTest extends BaseDynECTParseTest<FluentIterable<String>> {\n\n   @Override\n   public String resource() {\n      return \"/list_zones.json\";\n   }\n\n   @Override\n   @SelectJson(\"data\")\n   public FluentIterable<String> expected() {\n      return FluentIterable.from(ImmutableSet.of(\"0.0.0.0.d.6.e.0.0.a.2.ip6.arpa\", \"126.12.44.in-addr.arpa\", \"jclouds.org\"));\n   }\n\n   // TODO: currently our parsing of annotations on expected() ignores @Transform\n   @Override\n   protected Function<HttpResponse, FluentIterable<String>> parser(Injector i) {\n      return compose(new ExtractLastPathComponent(), super.parser(i));\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/test/java/org/jclouds/dynect/v3/predicates/RecordPredicatesTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.dynect.v3.predicates;\n\nimport static org.jclouds.dynect.v3.domain.RecordId.recordIdBuilder;\nimport static org.jclouds.dynect.v3.predicates.RecordPredicates.typeEquals;\n\nimport org.jclouds.dynect.v3.domain.RecordId;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class RecordPredicatesTest {\n   RecordId recordId = recordIdBuilder()\n                               .zone(\"adrianc.zone.dynecttest.jclouds.org\")\n                               .fqdn(\"adrianc.zone.dynecttest.jclouds.org\")\n                               .type(\"SOA\")\n                               .id(50976579L).build();\n\n   @Test\n   public void testTypeEqualsWhenEqual() {\n      assert typeEquals(\"SOA\").apply(recordId);\n   }\n\n   @Test\n   public void testTypeEqualsWhenNotEqual() {\n      assert !typeEquals(\"NS\").apply(recordId);\n   }\n}\n"
  },
  {
    "path": "providers/dynect/src/test/resources/create_session.json",
    "content": "{\"status\": \"success\", \"data\": {\"token\": \"FFFFFFFFFF\", \"version\": \"3.3.8\"}, \"job_id\": 254417252, \"msgs\": [{\"INFO\": \"login: Login successful\", \"SOURCE\": \"BLL\", \"ERR_CD\": null, \"LVL\": \"INFO\"}]}"
  },
  {
    "path": "providers/dynect/src/test/resources/delete_record.json",
    "content": "{\"status\": \"success\", \"data\": {}, \"job_id\": 285372457, \"msgs\": [{\"INFO\": \"delete: Record will be deleted on zone publish\", \"SOURCE\": \"BLL\", \"ERR_CD\": null, \"LVL\": \"INFO\"}, {\"INFO\": \"remove_node: www.adriancole.zone.dynecttest.jclouds.org removed from tree.\", \"SOURCE\": \"BLL\", \"ERR_CD\": null, \"LVL\": \"INFO\"}]}"
  },
  {
    "path": "providers/dynect/src/test/resources/delete_zone.json",
    "content": "{\"status\": \"success\", \"data\": {}, \"job_id\": 262989027, \"msgs\": [{\"INFO\": \"remove: Zone removed\", \"SOURCE\": \"BLL\", \"ERR_CD\": null, \"LVL\": \"INFO\"}]}"
  },
  {
    "path": "providers/dynect/src/test/resources/delete_zone_changes.json",
    "content": "{\"status\": \"success\", \"data\": {}, \"job_id\": 275625520, \"msgs\": [{\"INFO\": \"discard: 0 zone changes discarded\", \"SOURCE\": \"BLL\", \"ERR_CD\": null, \"LVL\": \"INFO\"}]}"
  },
  {
    "path": "providers/dynect/src/test/resources/get_geo_regiongroup.json",
    "content": "{\n    \"status\": \"success\",\n    \"data\": {\n        \"name\": \"Everywhere Else\",\n        \"weight\": {\n            \"aaaa_weight\": [],\n            \"a_weight\": [],\n            \"cname_weight\": []\n        },\n        \"countries\": [\"11\", \"16\", \"12\", \"17\", \"15\", \"14\"],\n        \"service_name\": \"CCS\",\n        \"rdata\": {\n            \"spf_rdata\": [],\n            \"px_rdata\": [],\n            \"srv_rdata\": [],\n            \"txt_rdata\": [],\n            \"soa_rdata\": [],\n            \"rp_rdata\": [],\n            \"ipseckey_rdata\": [],\n            \"dhcid_rdata\": [],\n            \"kx_rdata\": [],\n            \"key_rdata\": [],\n            \"aaaa_rdata\": [],\n            \"mx_rdata\": [],\n            \"dnskey_rdata\": [],\n            \"naptr_rdata\": [],\n            \"a_rdata\": [],\n            \"cname_rdata\": [{\n                    \"cname\": \"srv-938089264.us-east-1.elb.amazonaws.com.\"\n                }\n            ],\n            \"cert_rdata\": [],\n            \"nsap_rdata\": [],\n            \"ptr_rdata\": [],\n            \"ds_rdata\": [],\n            \"sshfp_rdata\": [],\n            \"dname_rdata\": [],\n            \"ns_rdata\": [],\n            \"loc_rdata\": []\n        },\n        \"label\": {\n            \"a_label\": [],\n            \"key_label\": [],\n            \"ptr_label\": [],\n            \"srv_label\": [],\n            \"txt_label\": [],\n            \"spf_label\": [],\n            \"mx_label\": [],\n            \"rp_label\": [],\n            \"sshfp_label\": [],\n            \"dnskey_label\": [],\n            \"aaaa_label\": [],\n            \"dhcid_label\": [],\n            \"nsap_label\": [],\n            \"loc_label\": [],\n            \"px_label\": [],\n            \"cname_label\": [],\n            \"cert_label\": []\n        },\n        \"ttl\": {\n            \"dhcid_ttl\": 0,\n            \"key_ttl\": 0,\n            \"ptr_ttl\": 0,\n            \"srv_ttl\": 0,\n            \"mx_ttl\": 0,\n            \"aaaa_ttl\": 0,\n            \"rp_ttl\": 0,\n            \"loc_ttl\": 0,\n            \"dnskey_ttl\": 0,\n            \"cname_ttl\": 0,\n            \"cert_ttl\": 0,\n            \"nsap_ttl\": 0,\n            \"a_ttl\": 0,\n            \"px_ttl\": 0,\n            \"sshfp_ttl\": 0,\n            \"spf_ttl\": 0,\n            \"txt_ttl\": 0\n        },\n        \"serve_count\": {\n            \"a_serve_count\": \"\",\n            \"aaaa_serve_count\": \"\"\n        }\n    },\n    \"job_id\": 321503845,\n    \"msgs\": [{\n            \"INFO\": \"detail_region_groups: Here is your group\",\n            \"SOURCE\": \"BLL\",\n            \"ERR_CD\": null,\n            \"LVL\": \"INFO\"\n        }\n    ]\n}\n"
  },
  {
    "path": "providers/dynect/src/test/resources/get_geo_service.json",
    "content": "{\n    \"status\": \"success\",\n    \"data\": {\n        \"active\": \"Y\",\n        \"nodes\": [{\n                \"fqdn\": \"srv.jclouds.org\",\n                \"zone\": \"jclouds.org\"\n            }\n        ],\n        \"name\": \"CCS\",\n        \"groups\": [{\n                \"name\": \"Everywhere Else\",\n                \"weight\": {\n                    \"aaaa_weight\": [],\n                    \"a_weight\": [],\n                    \"cname_weight\": []\n                },\n                \"countries\": [\"11\", \"16\", \"12\", \"17\", \"15\", \"14\"],\n                \"rdata\": {\n                    \"spf_rdata\": [],\n                    \"px_rdata\": [],\n                    \"srv_rdata\": [],\n                    \"txt_rdata\": [],\n                    \"soa_rdata\": [],\n                    \"rp_rdata\": [],\n                    \"ipseckey_rdata\": [],\n                    \"dhcid_rdata\": [],\n                    \"kx_rdata\": [],\n                    \"key_rdata\": [],\n                    \"aaaa_rdata\": [],\n                    \"mx_rdata\": [],\n                    \"dnskey_rdata\": [],\n                    \"naptr_rdata\": [],\n                    \"a_rdata\": [],\n                    \"cname_rdata\": [{\n                            \"cname\": \"srv-000000001.us-east-1.elb.amazonaws.com.\"\n                        }\n                    ],\n                    \"cert_rdata\": [],\n                    \"nsap_rdata\": [],\n                    \"ptr_rdata\": [],\n                    \"ds_rdata\": [],\n                    \"sshfp_rdata\": [],\n                    \"dname_rdata\": [],\n                    \"ns_rdata\": [],\n                    \"loc_rdata\": []\n                },\n                \"label\": {\n                    \"a_label\": [],\n                    \"key_label\": [],\n                    \"ptr_label\": [],\n                    \"srv_label\": [],\n                    \"txt_label\": [],\n                    \"spf_label\": [],\n                    \"mx_label\": [],\n                    \"rp_label\": [],\n                    \"sshfp_label\": [],\n                    \"dnskey_label\": [],\n                    \"aaaa_label\": [],\n                    \"dhcid_label\": [],\n                    \"nsap_label\": [],\n                    \"loc_label\": [],\n                    \"px_label\": [],\n                    \"cname_label\": [],\n                    \"cert_label\": []\n                },\n                \"ttl\": {\n                    \"dhcid_ttl\": 0,\n                    \"key_ttl\": 0,\n                    \"ptr_ttl\": 0,\n                    \"srv_ttl\": 0,\n                    \"mx_ttl\": 0,\n                    \"aaaa_ttl\": 0,\n                    \"rp_ttl\": 0,\n                    \"loc_ttl\": 0,\n                    \"dnskey_ttl\": 0,\n                    \"cname_ttl\": 0,\n                    \"cert_ttl\": 0,\n                    \"nsap_ttl\": 0,\n                    \"a_ttl\": 0,\n                    \"px_ttl\": 0,\n                    \"sshfp_ttl\": 0,\n                    \"spf_ttl\": 0,\n                    \"txt_ttl\": 0\n                },\n                \"serve_count\": {\n                    \"a_serve_count\": \"\",\n                    \"aaaa_serve_count\": \"\"\n                }\n            }, {\n                \"name\": \"Europe\",\n                \"weight\": {\n                    \"aaaa_weight\": [],\n                    \"a_weight\": [],\n                    \"cname_weight\": []\n                },\n                \"countries\": [\"13\"],\n                \"rdata\": {\n                    \"spf_rdata\": [],\n                    \"px_rdata\": [],\n                    \"srv_rdata\": [],\n                    \"txt_rdata\": [],\n                    \"soa_rdata\": [],\n                    \"rp_rdata\": [],\n                    \"ipseckey_rdata\": [],\n                    \"dhcid_rdata\": [],\n                    \"kx_rdata\": [],\n                    \"key_rdata\": [],\n                    \"aaaa_rdata\": [],\n                    \"mx_rdata\": [],\n                    \"dnskey_rdata\": [],\n                    \"naptr_rdata\": [],\n                    \"a_rdata\": [],\n                    \"cname_rdata\": [{\n                            \"cname\": \"srv-000000001.eu-west-1.elb.amazonaws.com.\"\n                        }\n                    ],\n                    \"cert_rdata\": [],\n                    \"nsap_rdata\": [],\n                    \"ptr_rdata\": [],\n                    \"ds_rdata\": [],\n                    \"sshfp_rdata\": [],\n                    \"dname_rdata\": [],\n                    \"ns_rdata\": [],\n                    \"loc_rdata\": []\n                },\n                \"label\": {\n                    \"a_label\": [],\n                    \"key_label\": [],\n                    \"ptr_label\": [],\n                    \"srv_label\": [],\n                    \"txt_label\": [],\n                    \"spf_label\": [],\n                    \"mx_label\": [],\n                    \"rp_label\": [],\n                    \"sshfp_label\": [],\n                    \"dnskey_label\": [],\n                    \"aaaa_label\": [],\n                    \"dhcid_label\": [],\n                    \"nsap_label\": [],\n                    \"loc_label\": [],\n                    \"px_label\": [],\n                    \"cname_label\": [],\n                    \"cert_label\": []\n                },\n                \"ttl\": {\n                    \"dhcid_ttl\": 0,\n                    \"key_ttl\": 0,\n                    \"ptr_ttl\": 0,\n                    \"srv_ttl\": 0,\n                    \"mx_ttl\": 0,\n                    \"aaaa_ttl\": 0,\n                    \"rp_ttl\": 0,\n                    \"loc_ttl\": 0,\n                    \"dnskey_ttl\": 0,\n                    \"cname_ttl\": 0,\n                    \"cert_ttl\": 0,\n                    \"nsap_ttl\": 0,\n                    \"a_ttl\": 0,\n                    \"px_ttl\": 0,\n                    \"sshfp_ttl\": 0,\n                    \"spf_ttl\": 0,\n                    \"txt_ttl\": 0\n                },\n                \"serve_count\": {\n                    \"a_serve_count\": \"\",\n                    \"aaaa_serve_count\": \"\"\n                }\n            }, {\n                \"name\": \"Fallback\",\n                \"weight\": {\n                    \"aaaa_weight\": [],\n                    \"a_weight\": [],\n                    \"cname_weight\": []\n                },\n                \"countries\": [\"@!\", \"@@\"],\n                \"rdata\": {\n                    \"spf_rdata\": [],\n                    \"px_rdata\": [],\n                    \"srv_rdata\": [],\n                    \"txt_rdata\": [],\n                    \"soa_rdata\": [],\n                    \"rp_rdata\": [],\n                    \"ipseckey_rdata\": [],\n                    \"dhcid_rdata\": [],\n                    \"kx_rdata\": [],\n                    \"key_rdata\": [],\n                    \"aaaa_rdata\": [],\n                    \"mx_rdata\": [],\n                    \"dnskey_rdata\": [],\n                    \"naptr_rdata\": [],\n                    \"a_rdata\": [],\n                    \"cname_rdata\": [{\n                            \"cname\": \"srv-000000002.us-east-1.elb.amazonaws.com.\"\n                        }\n                    ],\n                    \"cert_rdata\": [],\n                    \"nsap_rdata\": [],\n                    \"ptr_rdata\": [],\n                    \"ds_rdata\": [],\n                    \"sshfp_rdata\": [],\n                    \"dname_rdata\": [],\n                    \"ns_rdata\": [],\n                    \"loc_rdata\": []\n                },\n                \"label\": {\n                    \"a_label\": [],\n                    \"key_label\": [],\n                    \"ptr_label\": [],\n                    \"srv_label\": [],\n                    \"txt_label\": [],\n                    \"spf_label\": [],\n                    \"mx_label\": [],\n                    \"rp_label\": [],\n                    \"sshfp_label\": [],\n                    \"dnskey_label\": [],\n                    \"aaaa_label\": [],\n                    \"dhcid_label\": [],\n                    \"nsap_label\": [],\n                    \"loc_label\": [],\n                    \"px_label\": [],\n                    \"cname_label\": [],\n                    \"cert_label\": []\n                },\n                \"ttl\": {\n                    \"dhcid_ttl\": 0,\n                    \"key_ttl\": 0,\n                    \"ptr_ttl\": 0,\n                    \"srv_ttl\": 0,\n                    \"mx_ttl\": 0,\n                    \"aaaa_ttl\": 0,\n                    \"rp_ttl\": 0,\n                    \"loc_ttl\": 0,\n                    \"dnskey_ttl\": 0,\n                    \"cname_ttl\": 0,\n                    \"cert_ttl\": 0,\n                    \"nsap_ttl\": 0,\n                    \"a_ttl\": 0,\n                    \"px_ttl\": 0,\n                    \"sshfp_ttl\": 0,\n                    \"spf_ttl\": 0,\n                    \"txt_ttl\": 0\n                },\n                \"serve_count\": {\n                    \"a_serve_count\": \"\",\n                    \"aaaa_serve_count\": \"\"\n                }\n            }\n        ],\n        \"ttl\": 30\n    },\n    \"job_id\": 321488519,\n    \"msgs\": [{\n            \"INFO\": \"detail: Here is your service\",\n            \"SOURCE\": \"BLL\",\n            \"ERR_CD\": null,\n            \"LVL\": \"INFO\"\n        }\n    ]\n}\n"
  },
  {
    "path": "providers/dynect/src/test/resources/get_record_a.json",
    "content": "{\"status\": \"success\", \"data\": {\"zone\": \"egg.org\", \"ttl\": 86400, \"fqdn\": \"egg.org\", \"record_type\": \"A\", \"rdata\": {\"address\": \"1.1.1.1\"}, \"record_id\": 50959331}, \"job_id\": 274279510, \"msgs\": [{\"INFO\": \"get: Found the record\", \"SOURCE\": \"API-B\", \"ERR_CD\": null, \"LVL\": \"INFO\"}]}"
  },
  {
    "path": "providers/dynect/src/test/resources/get_record_aaaa.json",
    "content": "{\"status\": \"success\", \"data\": {\"zone\": \"egg.org\", \"ttl\": 86400, \"fqdn\": \"egg.org\", \"record_type\": \"AAAA\", \"rdata\": {\"address\": \"2406:bbbb:ff00::6b14:aaaa\"}, \"record_id\": 50959331}, \"job_id\": 274279510, \"msgs\": [{\"INFO\": \"get: Found the record\", \"SOURCE\": \"API-B\", \"ERR_CD\": null, \"LVL\": \"INFO\"}]}"
  },
  {
    "path": "providers/dynect/src/test/resources/get_record_cname.json",
    "content": "{\"status\": \"success\", \"data\": {\"zone\": \"egg.org\", \"ttl\": 86400, \"fqdn\": \"egg.org\", \"record_type\": \"CNAME\", \"rdata\": {\"cname\": \"prod-LB-359594650.us-east-1.elb.amazonaws.com.\"}, \"record_id\": 50959331}, \"job_id\": 274279510, \"msgs\": [{\"INFO\": \"get: Found the record\", \"SOURCE\": \"API-B\", \"ERR_CD\": null, \"LVL\": \"INFO\"}]}"
  },
  {
    "path": "providers/dynect/src/test/resources/get_record_mx.json",
    "content": "{\"status\": \"success\", \"data\": {\"zone\": \"egg.org\", \"ttl\": 86400, \"fqdn\": \"egg.org\", \"record_type\": \"MX\", \"rdata\": {\"preference\": 10, \"exchange\": \"mail.egg.org.\"}, \"record_id\": 50959331}, \"job_id\": 274279510, \"msgs\": [{\"INFO\": \"get: Found the record\", \"SOURCE\": \"API-B\", \"ERR_CD\": null, \"LVL\": \"INFO\"}]}"
  },
  {
    "path": "providers/dynect/src/test/resources/get_record_ns.json",
    "content": "{\"status\": \"success\", \"data\": {\"zone\": \"egg.org\", \"ttl\": 86400, \"fqdn\": \"egg.org\", \"record_type\": \"NS\", \"rdata\": {\"nsdname\": \"ns4.p28.dynect.net.\"}, \"record_id\": 50959331}, \"job_id\": 274279510, \"msgs\": [{\"INFO\": \"get: Found the record\", \"SOURCE\": \"API-B\", \"ERR_CD\": null, \"LVL\": \"INFO\"}]}"
  },
  {
    "path": "providers/dynect/src/test/resources/get_record_ptr.json",
    "content": "{\"status\": \"success\", \"data\": {\"zone\": \"egg.org\", \"ttl\": 86400, \"fqdn\": \"1.2.3.0.0.0.0.0.0.0.0.0.0.0.0.0.d.9.2.1.4.0.0.7.0.c.6.8.0.0.a.2.ip6.arpa\", \"record_type\": \"PTR\", \"rdata\": {\"ptrdname\": \"egg.org.\"}, \"record_id\": 50959331}, \"job_id\": 274279510, \"msgs\": [{\"INFO\": \"get: Found the record\", \"SOURCE\": \"API-B\", \"ERR_CD\": null, \"LVL\": \"INFO\"}]}"
  },
  {
    "path": "providers/dynect/src/test/resources/get_record_soa.json",
    "content": "{\"status\": \"success\", \"data\": {\"zone\": \"adrianc.zone.dynecttest.jclouds.org\", \"ttl\": 3600, \"fqdn\": \"adrianc.zone.dynecttest.jclouds.org\", \"record_type\": \"SOA\", \"rdata\": {\"rname\": \"1\\\\.5\\\\.7-SNAPSHOT@jclouds.org.\", \"retry\": 600, \"mname\": \"ns1.p28.dynect.net.\", \"minimum\": 60, \"refresh\": 3600, \"expire\": 604800, \"serial\": 1}, \"record_id\": 50976579, \"serial_style\": \"increment\"}, \"job_id\": 273523378, \"msgs\": [{\"INFO\": \"get: Found the record\", \"SOURCE\": \"API-B\", \"ERR_CD\": null, \"LVL\": \"INFO\"}]}"
  },
  {
    "path": "providers/dynect/src/test/resources/get_record_spf.json",
    "content": "{\"status\": \"success\", \"data\": {\"zone\": \"adrianc.zone.dynecttest.jclouds.org\", \"ttl\": 3600, \"fqdn\": \"_http._tcp.www.jclouds.org.\", \"record_type\": \"SPF\", \"rdata\": {\"txtdata\": \"v=spf1 a -all\"}, \"record_id\": 50976579}, \"job_id\": 273523378, \"msgs\": [{\"INFO\": \"get: Found the record\", \"SOURCE\": \"API-B\", \"ERR_CD\": null, \"LVL\": \"INFO\"}]}"
  },
  {
    "path": "providers/dynect/src/test/resources/get_record_srv.json",
    "content": "{\"status\": \"success\", \"data\": {\"zone\": \"adrianc.zone.dynecttest.jclouds.org\", \"ttl\": 3600, \"fqdn\": \"_http._tcp.www.jclouds.org.\", \"record_type\": \"SRV\", \"rdata\": {\"priority\": 0, \"weight\": 2, \"port\": 80, \"target\": \"www.jclouds.org.\"}, \"record_id\": 50976579}, \"job_id\": 273523378, \"msgs\": [{\"INFO\": \"get: Found the record\", \"SOURCE\": \"API-B\", \"ERR_CD\": null, \"LVL\": \"INFO\"}]}"
  },
  {
    "path": "providers/dynect/src/test/resources/get_record_sshfp.json",
    "content": "{\"status\": \"success\", \"data\": {\"zone\": \"adrianc.zone.dynecttest.jclouds.org\", \"ttl\": 3600, \"fqdn\": \"_http._tcp.www.jclouds.org.\", \"record_type\": \"SSHFP\", \"rdata\": {\"fptype\": 1, \"algorithm\": 2, \"fingerprint\": \"190E37C5B5DB9A1C455E648A41AF3CC83F99F102\"}, \"record_id\": 50976579}, \"job_id\": 273523378, \"msgs\": [{\"INFO\": \"get: Found the record\", \"SOURCE\": \"API-B\", \"ERR_CD\": null, \"LVL\": \"INFO\"}]}"
  },
  {
    "path": "providers/dynect/src/test/resources/get_record_txt.json",
    "content": "{\"status\": \"success\", \"data\": {\"zone\": \"egg.org\", \"ttl\": 86400, \"fqdn\": \"sm._domainkey.email.egg.org\", \"record_type\": \"TXT\", \"rdata\": {\"txtdata\": \"k=rsa\\\\; p=4KAtUdsUGRtjPHE1rsyFYs8XVzvdke8pXnoo+80Kj5b6C37rnyCmZ0w1R5LY==\"}, \"record_id\": 50959331}, \"job_id\": 274279510, \"msgs\": [{\"INFO\": \"get: Found the record\", \"SOURCE\": \"API-B\", \"ERR_CD\": null, \"LVL\": \"INFO\"}]}"
  },
  {
    "path": "providers/dynect/src/test/resources/get_zone.json",
    "content": "{\"status\": \"success\", \"data\": {\"zone_type\": \"Primary\", \"serial_style\": \"increment\", \"serial\": 5, \"zone\": \"jclouds.org\"}, \"job_id\": 260737493, \"msgs\": [{\"INFO\": \"get: Your zone, jclouds.org\", \"SOURCE\": \"BLL\", \"ERR_CD\": null, \"LVL\": \"INFO\"}]}"
  },
  {
    "path": "providers/dynect/src/test/resources/ip_mismatch.json",
    "content": "{\n    \"status\": \"failure\",\n    \"data\": {},\n    \"job_id\": 305900967,\n    \"msgs\": [{\n            \"INFO\": \"login: IP address does not match current session\",\n            \"SOURCE\": \"BLL\",\n            \"ERR_CD\": \"INVALID_DATA\",\n            \"LVL\": \"ERROR\"\n        }, {\n            \"INFO\": \"login: There was a problem with your credentials\",\n            \"SOURCE\": \"BLL\",\n            \"ERR_CD\": null,\n            \"LVL\": \"INFO\"\n        }\n    ]\n}\n"
  },
  {
    "path": "providers/dynect/src/test/resources/list_geo_regiongroups.json",
    "content": "{\n    \"status\": \"success\",\n    \"data\": [\"/REST/GeoRegionGroup/srv/Everywhere Else\", \"/REST/GeoRegionGroup/srv/Europe\", \"/REST/GeoRegionGroup/srv/Fallback\"],\n    \"job_id\": 321503402,\n    \"msgs\": [{\n            \"INFO\": \"get_region_groups: Here are your groups\",\n            \"SOURCE\": \"BLL\",\n            \"ERR_CD\": null,\n            \"LVL\": \"INFO\"\n        }\n    ]\n}\n"
  },
  {
    "path": "providers/dynect/src/test/resources/list_geo_services.json",
    "content": "{\n    \"status\": \"success\",\n    \"data\": [\"/REST/Geo/srv/\", \"/REST/Geo/srv-log/\"],\n    \"job_id\": 321483166,\n    \"msgs\": [{\n            \"INFO\": \"GET: Found 2 services\",\n            \"SOURCE\": \"BLL\",\n            \"ERR_CD\": null,\n            \"LVL\": \"INFO\"\n        }\n    ]\n}\n"
  },
  {
    "path": "providers/dynect/src/test/resources/list_records.json",
    "content": "{\"status\": \"success\", \"data\": [\"/REST/SOARecord/adrianc.zone.dynecttest.jclouds.org/adrianc.zone.dynecttest.jclouds.org/50976579\", \"/REST/NSRecord/adrianc.zone.dynecttest.jclouds.org/adrianc.zone.dynecttest.jclouds.org/50976580\", \"/REST/NSRecord/adrianc.zone.dynecttest.jclouds.org/adrianc.zone.dynecttest.jclouds.org/50976581\", \"/REST/NSRecord/adrianc.zone.dynecttest.jclouds.org/adrianc.zone.dynecttest.jclouds.org/50976582\", \"/REST/NSRecord/adrianc.zone.dynecttest.jclouds.org/adrianc.zone.dynecttest.jclouds.org/50976583\"], \"job_id\": 273523368, \"msgs\": [{\"INFO\": \"get_tree: Here is your zone tree\", \"SOURCE\": \"BLL\", \"ERR_CD\": null, \"LVL\": \"INFO\"}]}"
  },
  {
    "path": "providers/dynect/src/test/resources/list_zones.json",
    "content": "{\"status\": \"success\", \"data\": [\"/REST/Zone/0.0.0.0.d.6.e.0.0.a.2.ip6.arpa/\", \"/REST/Zone/126.12.44.in-addr.arpa/\", \"/REST/Zone/jclouds.org/\"], \"job_id\": 260657587, \"msgs\": [{\"INFO\": \"get: Your 3 zones\", \"SOURCE\": \"BLL\", \"ERR_CD\": null, \"LVL\": \"INFO\"}]}"
  },
  {
    "path": "providers/dynect/src/test/resources/logback.xml",
    "content": "<?xml version=\"1.0\"?>\n<configuration scan=\"false\">\n    <appender name=\"FILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <appender name=\"WIREFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds-wire.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n    \n    <root>\n        <level value=\"warn\" />\n    </root>\n\n    <logger name=\"org.jclouds\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"FILE\" />\n    </logger>\n\n    <logger name=\"jclouds.wire\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n\n    <logger name=\"jclouds.headers\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n\n</configuration>\n"
  },
  {
    "path": "providers/dynect/src/test/resources/logout.json",
    "content": "{\"status\": \"success\", \"data\": {}, \"job_id\": 254506373, \"msgs\": [{\"INFO\": \"logout: Logout successful\", \"SOURCE\": \"BLL\", \"ERR_CD\": null, \"LVL\": \"INFO\"}]}"
  },
  {
    "path": "providers/dynect/src/test/resources/new_record.json",
    "content": "{\"status\": \"success\", \"data\": {\"zone\": \"adriancole.zone.dynecttest.jclouds.org\", \"ttl\": 86400, \"fqdn\": \"www.adriancole.zone.dynecttest.jclouds.org\", \"record_type\": \"A\", \"rdata\": {\"address\": \"1.1.1.1\"}, \"record_id\": 0}, \"job_id\": 285372440, \"msgs\": [{\"INFO\": \"add: Record added\", \"SOURCE\": \"BLL\", \"ERR_CD\": null, \"LVL\": \"INFO\"}]}"
  },
  {
    "path": "providers/dynect/src/test/resources/new_zone.json",
    "content": "{\"status\": \"success\", \"data\": {\"zone_type\": \"Primary\", \"serial_style\": \"increment\", \"serial\": 0, \"zone\": \"adriancole.zone.dynecttest.jclouds.org\"}, \"job_id\": 285351593, \"msgs\": [{\"INFO\": \"create: New zone adriancole.zone.dynecttest.jclouds.org created.  Publish it to put it on our server.\", \"SOURCE\": \"BLL\", \"ERR_CD\": null, \"LVL\": \"INFO\"}, {\"INFO\": \"setup: If you plan to provide your own secondary DNS for the zone, allow notify requests from these IP addresses on your nameserver: 204.13.249.66, 208.78.68.66, 2600:2001:0:1::66, 2600:2003:0:1::66\", \"SOURCE\": \"BLL\", \"ERR_CD\": null, \"LVL\": \"INFO\"}]}"
  },
  {
    "path": "providers/dynect/src/test/resources/session_invalid.json",
    "content": "{\"status\": \"failure\", \"data\": {}, \"job_id\": 254505048, \"msgs\": [{\"INFO\": \"login: Bad or expired credentials\", \"SOURCE\": \"BLL\", \"ERR_CD\": \"INVALID_DATA\", \"LVL\": \"ERROR\"}, {\"INFO\": \"login: There was a problem with your credentials\", \"SOURCE\": \"BLL\", \"ERR_CD\": null, \"LVL\": \"INFO\"}]}"
  },
  {
    "path": "providers/dynect/src/test/resources/session_valid.json",
    "content": "{\"status\": \"success\", \"data\": {}, \"job_id\": 254504748, \"msgs\": [{\"INFO\": \"isalive: User session is still active\", \"SOURCE\": \"BLL\", \"ERR_CD\": null, \"LVL\": \"INFO\"}]}"
  },
  {
    "path": "providers/elastichosts-ams-e/README.txt",
    "content": "#\n# The jclouds provider for ElasticHosts' Amsterdam ElasticStack  (http://www.elastichosts.com/).\n#\n# Expects the jclouds elasticstack API to be present on your application's classpath.\n#\n\n"
  },
  {
    "path": "providers/elastichosts-ams-e/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.elastichosts.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "providers/elastichosts-ams-e/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.provider</groupId>\n  <artifactId>elastichosts-ams-e</artifactId>\n  <name>jclouds ElasticHosts Amsterdam provider</name>\n  <description>ElasticHosts implementation targeted to Amsterdam</description>\n\n  <properties>\n    <test.elastichosts-ams-e.endpoint>https://api-ams-e.elastichosts.com</test.elastichosts-ams-e.endpoint>\n    <test.elastichosts-ams-e.api-version>2.0</test.elastichosts-ams-e.api-version>\n    <test.elastichosts-ams-e.build-version />\n    <test.elastichosts-ams-e.identity>FIXME_IDENTITY</test.elastichosts-ams-e.identity>\n    <test.elastichosts-ams-e.credential>FIXME_CREDENTIAL</test.elastichosts-ams-e.credential>\n    <test.elastichosts-ams-e.template />\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>elasticstack</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>elasticstack</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-log4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-sshj</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.elastichosts-ams-e.endpoint>${test.elastichosts-ams-e.endpoint}</test.elastichosts-ams-e.endpoint>\n                    <test.elastichosts-ams-e.api-version>${test.elastichosts-ams-e.api-version}</test.elastichosts-ams-e.api-version>\n                    <test.elastichosts-ams-e.build-version>${test.elastichosts-ams-e.build-version}</test.elastichosts-ams-e.build-version>\n                    <test.elastichosts-ams-e.identity>${test.elastichosts-ams-e.identity}</test.elastichosts-ams-e.identity>\n                    <test.elastichosts-ams-e.credential>${test.elastichosts-ams-e.credential}</test.elastichosts-ams-e.credential>\n                    <test.elastichosts-ams-e.template>${test.elastichosts-ams-e.template}</test.elastichosts-ams-e.template>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n</project>\n\n"
  },
  {
    "path": "providers/elastichosts-ams-e/src/main/java/org/jclouds/elastichosts/ElasticHostsAmsterdamMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts;\n\nimport static org.jclouds.compute.config.ComputeServiceProperties.TEMPLATE;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.elasticstack.ElasticStackApiMetadata;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\n\nimport com.google.auto.service.AutoService;\n\n/**\n * Implementation of {@link ProviderMetadata} for ElasticHosts Amsterdam.\n */\n@AutoService(ProviderMetadata.class)\npublic class ElasticHostsAmsterdamMetadata extends BaseProviderMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromProviderMetadata(this);\n   }\n\n   public ElasticHostsAmsterdamMetadata() {\n      super(builder());\n   }\n\n   public ElasticHostsAmsterdamMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = new Properties();\n      properties.setProperty(TEMPLATE, \"osFamily=UBUNTU,osVersionMatches=1[01234].[01][04].[0-9]*,os64Bit=true\");\n      return properties;\n   }\n\n   public static class Builder\n         extends\n         BaseProviderMetadata.Builder {\n\n      protected Builder() {\n         id(\"elastichosts-ams-e\")\n         .name(\"ElasticHosts Amsterdam\")\n         .apiMetadata(new ElasticStackApiMetadata().toBuilder().version(\"2.0\").build())\n         .homepage(URI.create(\"https://ams-e.elastichosts.com\"))\n         .console(URI.create(\"https://ams-e.elastichosts.com/accounts\"))\n         .iso3166Codes(\"NL-NH\")\n         .endpoint(\"https://api-ams-e.elastichosts.com\")\n         .defaultProperties(ElasticHostsAmsterdamMetadata.defaultProperties());\n      }\n\n      @Override\n      public ElasticHostsAmsterdamMetadata build() {\n         return new ElasticHostsAmsterdamMetadata(this);\n      }\n\n      @Override\n      public Builder fromProviderMetadata(\n            ProviderMetadata in) {\n         super.fromProviderMetadata(in);\n         return this;\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/elastichosts-ams-e/src/test/java/org/jclouds/elastichosts/ElasticHostsAmsterdamApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts;\n\nimport org.jclouds.elasticstack.ElasticStackApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"ElasticHostsAmsterdamApiLiveTest\")\npublic class ElasticHostsAmsterdamApiLiveTest extends ElasticStackApiLiveTest {\n   public ElasticHostsAmsterdamApiLiveTest() {\n      provider = \"elastichosts-ams-e\";\n   }\n}\n"
  },
  {
    "path": "providers/elastichosts-ams-e/src/test/java/org/jclouds/elastichosts/ElasticHostsAmsterdamProviderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts;\n\nimport org.jclouds.elasticstack.ElasticStackApiMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ElasticHostsAmsterdamProviderTest\")\npublic class ElasticHostsAmsterdamProviderTest extends BaseProviderMetadataTest {\n\n   public ElasticHostsAmsterdamProviderTest() {\n      super(new ElasticHostsAmsterdamMetadata(), new ElasticStackApiMetadata());\n   }\n}\n"
  },
  {
    "path": "providers/elastichosts-ams-e/src/test/java/org/jclouds/elastichosts/compute/ElasticHostsAmsterdamComputeServiceLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts.compute;\n\nimport org.jclouds.elasticstack.compute.ElasticStackComputeServiceLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"ElasticHostsAmsterdamComputeServiceLiveTest\")\npublic class ElasticHostsAmsterdamComputeServiceLiveTest extends ElasticStackComputeServiceLiveTest {\n\n   public ElasticHostsAmsterdamComputeServiceLiveTest() {\n      provider = \"elastichosts-ams-e\";\n      group = \"elastichosts\";\n   }\n\n}\n"
  },
  {
    "path": "providers/elastichosts-ams-e/src/test/java/org/jclouds/elastichosts/compute/ElasticHostsAmsterdamTemplateBuilderLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts.compute;\n\nimport static org.jclouds.compute.util.ComputeServiceUtils.getCores;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.internal.BaseTemplateBuilderLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"live\", testName = \"ElasticHostsAmsterdamTemplateBuilderLiveTest\")\npublic class ElasticHostsAmsterdamTemplateBuilderLiveTest extends BaseTemplateBuilderLiveTest {\n\n   public ElasticHostsAmsterdamTemplateBuilderLiveTest() {\n      provider = \"elastichosts-ams-e\";\n   }\n\n   @Override\n   public void testDefaultTemplateBuilder() throws IOException {\n      Template defaultTemplate = view.getComputeService().templateBuilder().build();\n      assertTrue(defaultTemplate.getImage().getOperatingSystem().getVersion().matches(\"1[01234].[01][04].[0-9]*\"));\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true);\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.UBUNTU);\n      assertEquals(getCores(defaultTemplate.getHardware()), 1.0d);\n   }\n\n   @Override\n   protected Set<String> getIso3166Codes() {\n      return ImmutableSet.<String> of(\"NL-NH\");\n   }\n}\n"
  },
  {
    "path": "providers/elastichosts-dal-a/README.txt",
    "content": "#\n# The jclouds provider for ElasticHosts' Dallas ElasticStack  (http://www.elastichosts.com/).\n#\n# Expects the jclouds elasticstack API to be present on your application's classpath.\n#\n\n"
  },
  {
    "path": "providers/elastichosts-dal-a/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.elastichosts.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "providers/elastichosts-dal-a/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.provider</groupId>\n  <artifactId>elastichosts-dal-a</artifactId>\n  <name>jclouds ElasticHosts Dallas provider</name>\n  <description>ElasticHosts implementation targeted to Dallas</description>\n\n  <properties>\n    <test.elastichosts-dal-a.endpoint>https://api-dal-a.elastichosts.com</test.elastichosts-dal-a.endpoint>\n    <test.elastichosts-dal-a.api-version>2.0</test.elastichosts-dal-a.api-version>\n    <test.elastichosts-dal-a.build-version />\n    <test.elastichosts-dal-a.identity>FIXME_IDENTITY</test.elastichosts-dal-a.identity>\n    <test.elastichosts-dal-a.credential>FIXME_CREDENTIAL</test.elastichosts-dal-a.credential>\n    <test.elastichosts-dal-a.template />\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>elasticstack</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>elasticstack</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-log4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-sshj</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.elastichosts-dal-a.endpoint>${test.elastichosts-dal-a.endpoint}</test.elastichosts-dal-a.endpoint>\n                    <test.elastichosts-dal-a.api-version>${test.elastichosts-dal-a.api-version}</test.elastichosts-dal-a.api-version>\n                    <test.elastichosts-dal-a.build-version>${test.elastichosts-dal-a.build-version}</test.elastichosts-dal-a.build-version>\n                    <test.elastichosts-dal-a.identity>${test.elastichosts-dal-a.identity}</test.elastichosts-dal-a.identity>\n                    <test.elastichosts-dal-a.credential>${test.elastichosts-dal-a.credential}</test.elastichosts-dal-a.credential>\n                    <test.elastichosts-dal-a.template>${test.elastichosts-dal-a.template}</test.elastichosts-dal-a.template>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n</project>\n\n"
  },
  {
    "path": "providers/elastichosts-dal-a/src/main/java/org/jclouds/elastichosts/ElasticHostsDallasMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts;\n\nimport static org.jclouds.compute.config.ComputeServiceProperties.TEMPLATE;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.elasticstack.ElasticStackApiMetadata;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\n\nimport com.google.auto.service.AutoService;\n\n/**\n * Implementation of {@link ProviderMetadata} for ElasticHosts Dallas.\n */\n@AutoService(ProviderMetadata.class)\npublic class ElasticHostsDallasMetadata extends BaseProviderMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromProviderMetadata(this);\n   }\n\n   public ElasticHostsDallasMetadata() {\n      super(builder());\n   }\n\n   public ElasticHostsDallasMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = new Properties();\n      properties.setProperty(TEMPLATE, \"osFamily=UBUNTU,osVersionMatches=1[01234].[01][04],os64Bit=true\");\n      return properties;\n   }\n\n   public static class Builder extends BaseProviderMetadata.Builder {\n\n      protected Builder() {\n         id(\"elastichosts-dal-a\").name(\"ElasticHosts Dallas\")\n               .apiMetadata(new ElasticStackApiMetadata().toBuilder().version(\"2.0\").build())\n               .homepage(URI.create(\"https://dal-a.elastichosts.com\"))\n               .console(URI.create(\"https://dal-a.elastichosts.com/accounts\")).iso3166Codes(\"US-TX\")\n               .endpoint(\"https://api-dal-a.elastichosts.com\")\n               .defaultProperties(ElasticHostsDallasMetadata.defaultProperties());\n      }\n\n      @Override\n      public ElasticHostsDallasMetadata build() {\n         return new ElasticHostsDallasMetadata(this);\n      }\n\n      @Override\n      public Builder fromProviderMetadata(ProviderMetadata in) {\n         super.fromProviderMetadata(in);\n         return this;\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/elastichosts-dal-a/src/test/java/org/jclouds/elastichosts/ElasticHostsDallasApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts;\n\nimport org.jclouds.elasticstack.ElasticStackApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"ElasticHostsDallasApiLiveTest\")\npublic class ElasticHostsDallasApiLiveTest extends ElasticStackApiLiveTest {\n   public ElasticHostsDallasApiLiveTest() {\n      provider = \"elastichosts-dal-a\";\n   }\n}\n"
  },
  {
    "path": "providers/elastichosts-dal-a/src/test/java/org/jclouds/elastichosts/ElasticHostsDallasProviderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts;\n\nimport org.jclouds.elasticstack.ElasticStackApiMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ElasticHostsDallasProviderTest\")\npublic class ElasticHostsDallasProviderTest extends BaseProviderMetadataTest {\n\n   public ElasticHostsDallasProviderTest() {\n      super(new ElasticHostsDallasMetadata(), new ElasticStackApiMetadata());\n   }\n}\n"
  },
  {
    "path": "providers/elastichosts-dal-a/src/test/java/org/jclouds/elastichosts/compute/ElasticHostsDallasComputeServiceLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts.compute;\n\nimport org.jclouds.elasticstack.compute.ElasticStackComputeServiceLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"ElasticHostsDallasComputeServiceLiveTest\")\npublic class ElasticHostsDallasComputeServiceLiveTest extends ElasticStackComputeServiceLiveTest {\n\n   public ElasticHostsDallasComputeServiceLiveTest() {\n      provider = \"elastichosts-dal-a\";\n      group = \"elastichosts\";\n   }\n\n}\n"
  },
  {
    "path": "providers/elastichosts-dal-a/src/test/java/org/jclouds/elastichosts/compute/ElasticHostsDallasTemplateBuilderLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts.compute;\n\nimport static org.jclouds.compute.util.ComputeServiceUtils.getCores;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.internal.BaseTemplateBuilderLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"live\", testName = \"ElasticHostsDallasTemplateBuilderLiveTest\")\npublic class ElasticHostsDallasTemplateBuilderLiveTest extends BaseTemplateBuilderLiveTest {\n\n   public ElasticHostsDallasTemplateBuilderLiveTest() {\n      provider = \"elastichosts-dal-a\";\n   }\n\n   @Override\n   public void testDefaultTemplateBuilder() throws IOException {\n      Template defaultTemplate = view.getComputeService().templateBuilder().build();\n      assertTrue(defaultTemplate.getImage().getOperatingSystem().getVersion().matches(\"1[01234].[01][04]\"));\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true);\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.UBUNTU);\n      assertEquals(getCores(defaultTemplate.getHardware()), 1.0d);\n   }\n\n   @Override\n   protected Set<String> getIso3166Codes() {\n      return ImmutableSet.<String> of(\"US-TX\");\n   }\n}\n"
  },
  {
    "path": "providers/elastichosts-hkg-e/README.txt",
    "content": "#\n# The jclouds provider for ElasticHosts' Hong Kong ElasticStack  (http://www.elastichosts.com/).\n#\n# Expects the jclouds elasticstack API to be present on your application's classpath.\n#"
  },
  {
    "path": "providers/elastichosts-hkg-e/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.elastichosts.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "providers/elastichosts-hkg-e/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.provider</groupId>\n  <artifactId>elastichosts-hkg-e</artifactId>\n  <name>jclouds ElasticHosts Hong Kong provider</name>\n  <description>ElasticHosts implementation targeted to Hong Kong</description>\n\n  <properties>\n    <test.elastichosts-hkg-e.endpoint>https://api-hkg-e.elastichosts.com</test.elastichosts-hkg-e.endpoint>\n    <test.elastichosts-hkg-e.api-version>2.0</test.elastichosts-hkg-e.api-version>\n    <test.elastichosts-hkg-e.build-version />\n    <test.elastichosts-hkg-e.identity>FIXME_IDENTITY</test.elastichosts-hkg-e.identity>\n    <test.elastichosts-hkg-e.credential>FIXME_CREDENTIAL</test.elastichosts-hkg-e.credential>\n    <test.elastichosts-hkg-e.template />\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>elasticstack</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>elasticstack</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-log4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-sshj</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.elastichosts-hkg-e.endpoint>${test.elastichosts-hkg-e.endpoint}</test.elastichosts-hkg-e.endpoint>\n                    <test.elastichosts-hkg-e.api-version>${test.elastichosts-hkg-e.api-version}</test.elastichosts-hkg-e.api-version>\n                    <test.elastichosts-hkg-e.build-version>${test.elastichosts-hkg-e.build-version}</test.elastichosts-hkg-e.build-version>\n                    <test.elastichosts-hkg-e.identity>${test.elastichosts-hkg-e.identity}</test.elastichosts-hkg-e.identity>\n                    <test.elastichosts-hkg-e.credential>${test.elastichosts-hkg-e.credential}</test.elastichosts-hkg-e.credential>\n                    <test.elastichosts-hkg-e.template>${test.elastichosts-hkg-e.template}</test.elastichosts-hkg-e.template>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n</project>\n\n"
  },
  {
    "path": "providers/elastichosts-hkg-e/src/main/java/org/jclouds/elastichosts/ElasticHostsHongKongProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts;\n\nimport static org.jclouds.compute.config.ComputeServiceProperties.TEMPLATE;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.elasticstack.ElasticStackApiMetadata;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\n\nimport com.google.auto.service.AutoService;\n\n/**\n * Implementation of {@link ProviderMetadata} for ElasticHosts Hong Kong.\n */\n@AutoService(ProviderMetadata.class)\npublic class ElasticHostsHongKongProviderMetadata extends BaseProviderMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromProviderMetadata(this);\n   }\n\n   public ElasticHostsHongKongProviderMetadata() {\n      super(builder());\n   }\n\n   public ElasticHostsHongKongProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = new Properties();\n      properties.setProperty(TEMPLATE, \"osFamily=UBUNTU,osVersionMatches=1[01234].[01][04].[0-9]*,os64Bit=true\");\n      return properties;\n   }\n\n   public static class Builder\n         extends\n         BaseProviderMetadata.Builder {\n\n      protected Builder() {\n         id(\"elastichosts-hkg-e\")\n         .name(\"ElasticHosts Hong Kong\")\n         .apiMetadata(new ElasticStackApiMetadata().toBuilder().version(\"2.0\").build())\n         .homepage(URI.create(\"https://hkg-e.elastichosts.com\"))\n         .console(URI.create(\"https://hkg-e.elastichosts.com/accounts\"))\n         .iso3166Codes(\"HK\")\n         .endpoint(\"https://api-hkg-e.elastichosts.com\")\n         .defaultProperties(ElasticHostsHongKongProviderMetadata.defaultProperties());\n      }\n\n      @Override\n      public ElasticHostsHongKongProviderMetadata build() {\n         return new ElasticHostsHongKongProviderMetadata(this);\n      }\n\n      @Override\n      public Builder fromProviderMetadata(\n            ProviderMetadata in) {\n         super.fromProviderMetadata(in);\n         return this;\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/elastichosts-hkg-e/src/test/java/org/jclouds/elastichosts/ElasticHostsHongKongApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts;\n\nimport org.jclouds.elasticstack.ElasticStackApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"ElasticHostsHongKongApiLiveTest\")\npublic class ElasticHostsHongKongApiLiveTest extends ElasticStackApiLiveTest {\n   public ElasticHostsHongKongApiLiveTest() {\n      provider = \"elastichosts-hkg-e\";\n   }\n}\n"
  },
  {
    "path": "providers/elastichosts-hkg-e/src/test/java/org/jclouds/elastichosts/ElasticHostsHongKongProviderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts;\n\nimport org.jclouds.elasticstack.ElasticStackApiMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ElasticHostsHongKongProviderTest\")\npublic class ElasticHostsHongKongProviderTest extends BaseProviderMetadataTest {\n\n   public ElasticHostsHongKongProviderTest() {\n      super(new ElasticHostsHongKongProviderMetadata(), new ElasticStackApiMetadata());\n   }\n}\n"
  },
  {
    "path": "providers/elastichosts-hkg-e/src/test/java/org/jclouds/elastichosts/compute/ElasticHostsHongKongComputeServiceLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts.compute;\n\nimport org.jclouds.elasticstack.compute.ElasticStackComputeServiceLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"ElasticHostsHongKongComputeServiceLiveTest\")\npublic class ElasticHostsHongKongComputeServiceLiveTest extends ElasticStackComputeServiceLiveTest {\n\n   public ElasticHostsHongKongComputeServiceLiveTest() {\n      provider = \"elastichosts-hkg-e\";\n      group = \"elastichosts\";\n   }\n\n}\n"
  },
  {
    "path": "providers/elastichosts-hkg-e/src/test/java/org/jclouds/elastichosts/compute/ElasticHostsHongKongTemplateBuilderLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts.compute;\n\nimport static org.jclouds.compute.util.ComputeServiceUtils.getCores;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.internal.BaseTemplateBuilderLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"live\", testName = \"ElasticHostsHongKongTemplateBuilderLiveTest\")\npublic class ElasticHostsHongKongTemplateBuilderLiveTest extends BaseTemplateBuilderLiveTest {\n\n   public ElasticHostsHongKongTemplateBuilderLiveTest() {\n      provider = \"elastichosts-hkg-e\";\n   }\n\n   @Override\n   public void testDefaultTemplateBuilder() throws IOException {\n      Template defaultTemplate = view.getComputeService().templateBuilder().build();\n      assertTrue(defaultTemplate.getImage().getOperatingSystem().getVersion().matches(\"1[01234].[01][04].[0-9]*\"));\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true);\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.UBUNTU);\n      assertEquals(getCores(defaultTemplate.getHardware()), 1.0d);\n   }\n\n   @Override\n   protected Set<String> getIso3166Codes() {\n      return ImmutableSet.of(\"HK\");\n   }\n}\n"
  },
  {
    "path": "providers/elastichosts-lax-p/README.txt",
    "content": "#\n# The jclouds provider for ElasticHosts' Peer1 Los Angeles ElasticStack  (http://www.elastichosts.com/).\n#\n# Expects the jclouds elasticstack API to be present on your application's classpath.\n#\n# TODO: Implementation status.\n# TODO: Supported features.\n# TODO: Usage example.\n"
  },
  {
    "path": "providers/elastichosts-lax-p/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.elastichosts.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "providers/elastichosts-lax-p/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.provider</groupId>\n  <artifactId>elastichosts-lax-p</artifactId>\n  <name>jclouds ElasticHosts Peer1 Los Angeles provider</name>\n  <description>ElasticHosts implementation targeted to Peer1 Toronto</description>\n\n  <properties>\n    <test.elastichosts-lax-p.endpoint>https://api-lax-p.elastichosts.com</test.elastichosts-lax-p.endpoint>\n    <test.elastichosts-lax-p.api-version>2.0</test.elastichosts-lax-p.api-version>\n    <test.elastichosts-lax-p.build-version />\n    <test.elastichosts-lax-p.identity>FIXME_IDENTITY</test.elastichosts-lax-p.identity>\n    <test.elastichosts-lax-p.credential>FIXME_CREDENTIAL</test.elastichosts-lax-p.credential>\n    <test.elastichosts-lax-p.template />\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>elasticstack</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>elasticstack</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-log4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-sshj</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.elastichosts-lax-p.endpoint>${test.elastichosts-lax-p.endpoint}</test.elastichosts-lax-p.endpoint>\n                    <test.elastichosts-lax-p.api-version>${test.elastichosts-lax-p.api-version}</test.elastichosts-lax-p.api-version>\n                    <test.elastichosts-lax-p.build-version>${test.elastichosts-lax-p.build-version}</test.elastichosts-lax-p.build-version>\n                    <test.elastichosts-lax-p.identity>${test.elastichosts-lax-p.identity}</test.elastichosts-lax-p.identity>\n                    <test.elastichosts-lax-p.credential>${test.elastichosts-lax-p.credential}</test.elastichosts-lax-p.credential>\n                    <test.elastichosts-lax-p.template>${test.elastichosts-lax-p.template}</test.elastichosts-lax-p.template>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n\n"
  },
  {
    "path": "providers/elastichosts-lax-p/src/main/java/org/jclouds/elastichosts/ElasticHostsPeer1LosAngelesProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts;\n\nimport static org.jclouds.compute.config.ComputeServiceProperties.TEMPLATE;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.elasticstack.ElasticStackApiMetadata;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\n\nimport com.google.auto.service.AutoService;\n\n/**\n * Implementation of {@link ProviderMetadata} for ElasticHosts LA Peer1.\n */\n@AutoService(ProviderMetadata.class)\npublic class ElasticHostsPeer1LosAngelesProviderMetadata extends BaseProviderMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromProviderMetadata(this);\n   }\n\n   public ElasticHostsPeer1LosAngelesProviderMetadata() {\n      super(builder());\n   }\n\n   public ElasticHostsPeer1LosAngelesProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = new Properties();\n      properties.setProperty(TEMPLATE, \"osFamily=UBUNTU,osVersionMatches=1[01234].[01][04].[0-9]*,os64Bit=true\");\n      return properties;\n   }\n\n   public static class Builder\n         extends\n         BaseProviderMetadata.Builder {\n\n      protected Builder() {\n         id(\"elastichosts-lax-p\")\n         .name(\"ElasticHosts Los Angeles Peer 1\")\n         .apiMetadata(new ElasticStackApiMetadata().toBuilder().version(\"2.0\").build())\n         .homepage(URI.create(\"https://lax-p.elastichosts.com\"))\n         .console(URI.create(\"https://lax-p.elastichosts.com/accounts\"))\n         .iso3166Codes(\"US-CA\")\n         .endpoint(\"https://api-lax-p.elastichosts.com\")\n         .defaultProperties(ElasticHostsPeer1LosAngelesProviderMetadata.defaultProperties());\n      }\n\n      @Override\n      public ElasticHostsPeer1LosAngelesProviderMetadata build() {\n         return new ElasticHostsPeer1LosAngelesProviderMetadata(this);\n      }\n\n      @Override\n      public Builder fromProviderMetadata(\n            ProviderMetadata in) {\n         super.fromProviderMetadata(in);\n         return this;\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/elastichosts-lax-p/src/test/java/org/jclouds/elastichosts/ElasticHostsPeer1LosAngelesApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts;\n\nimport org.jclouds.elasticstack.ElasticStackApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"ElasticHostsPeer1LosAngelesApiLiveTest\")\npublic class ElasticHostsPeer1LosAngelesApiLiveTest extends ElasticStackApiLiveTest {\n   public ElasticHostsPeer1LosAngelesApiLiveTest() {\n      provider = \"elastichosts-lax-p\";\n   }\n   \n}\n"
  },
  {
    "path": "providers/elastichosts-lax-p/src/test/java/org/jclouds/elastichosts/ElasticHostsPeer1LosAngelesProviderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts;\n\nimport org.jclouds.elasticstack.ElasticStackApiMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ElasticHostsPeer1LosAngelesProviderTest\")\npublic class ElasticHostsPeer1LosAngelesProviderTest extends BaseProviderMetadataTest {\n\n   public ElasticHostsPeer1LosAngelesProviderTest() {\n      super(new ElasticHostsPeer1LosAngelesProviderMetadata(), new ElasticStackApiMetadata());\n   }\n}\n"
  },
  {
    "path": "providers/elastichosts-lax-p/src/test/java/org/jclouds/elastichosts/compute/ElasticHostsPeer1LosAngelesComputeServiceLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts.compute;\n\nimport org.jclouds.elasticstack.compute.ElasticStackComputeServiceLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"ElasticHostsPeer1LosAngelesComputeServiceLiveTest\")\npublic class ElasticHostsPeer1LosAngelesComputeServiceLiveTest extends ElasticStackComputeServiceLiveTest {\n\n   public ElasticHostsPeer1LosAngelesComputeServiceLiveTest() {\n      provider = \"elastichosts-lax-p\";\n      group = \"elastichosts\";\n   }\n\n}\n"
  },
  {
    "path": "providers/elastichosts-lax-p/src/test/java/org/jclouds/elastichosts/compute/ElasticHostsPeer1LosAngelesTemplateBuilderLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts.compute;\n\nimport static org.jclouds.compute.util.ComputeServiceUtils.getCores;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.internal.BaseTemplateBuilderLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"live\")\npublic class ElasticHostsPeer1LosAngelesTemplateBuilderLiveTest extends BaseTemplateBuilderLiveTest {\n\n   public ElasticHostsPeer1LosAngelesTemplateBuilderLiveTest() {\n      provider = \"elastichosts-lax-p\";\n   }\n\n   @Override\n   public void testDefaultTemplateBuilder() throws IOException {\n      Template defaultTemplate = view.getComputeService().templateBuilder().build();\n      assertTrue(defaultTemplate.getImage().getOperatingSystem().getVersion().matches(\"1[01234].[01][04].[0-9]*\"));\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true);\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.UBUNTU);\n      assertEquals(getCores(defaultTemplate.getHardware()), 1.0d);\n   }\n\n   @Override\n   protected Set<String> getIso3166Codes() {\n      return ImmutableSet.of(\"US-CA\");\n   }\n}\n"
  },
  {
    "path": "providers/elastichosts-lon-b/README.txt",
    "content": "#\n# The jclouds provider for ElasticHosts' Peer1 London ElasticStack  (http://www.elastichosts.com/).\n#\n# Expects the jclouds elasticstack API to be present on your application's classpath.\n#\n# TODO: Implementation status.\n# TODO: Supported features.\n# TODO: Usage example.\n"
  },
  {
    "path": "providers/elastichosts-lon-b/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.elastichosts.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "providers/elastichosts-lon-b/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.provider</groupId>\n  <artifactId>elastichosts-lon-b</artifactId>\n  <name>jclouds ElasticHosts BlueSquare London provider</name>\n  <description>ElasticHosts implementation targeted to BlueSquare London</description>\n\n  <properties>\n    <test.elastichosts-lon-b.endpoint>https://api-lon-b.elastichosts.com</test.elastichosts-lon-b.endpoint>\n    <test.elastichosts-lon-b.api-version>2.0</test.elastichosts-lon-b.api-version>\n    <test.elastichosts-lon-b.build-version />\n    <test.elastichosts-lon-b.identity>FIXME_IDENTITY</test.elastichosts-lon-b.identity>\n    <test.elastichosts-lon-b.credential>FIXME_CREDENTIAL</test.elastichosts-lon-b.credential>\n    <test.elastichosts-lon-b.template />\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>elasticstack</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>elasticstack</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-log4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-sshj</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.elastichosts-lon-b.endpoint>${test.elastichosts-lon-b.endpoint}</test.elastichosts-lon-b.endpoint>\n                    <test.elastichosts-lon-b.api-version>${test.elastichosts-lon-b.api-version}</test.elastichosts-lon-b.api-version>\n                    <test.elastichosts-lon-b.build-version>${test.elastichosts-lon-b.build-version}</test.elastichosts-lon-b.build-version>\n                    <test.elastichosts-lon-b.identity>${test.elastichosts-lon-b.identity}</test.elastichosts-lon-b.identity>\n                    <test.elastichosts-lon-b.credential>${test.elastichosts-lon-b.credential}</test.elastichosts-lon-b.credential>\n                    <test.elastichosts-lon-b.template>${test.elastichosts-lon-b.template}</test.elastichosts-lon-b.template>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n\n</project>\n\n"
  },
  {
    "path": "providers/elastichosts-lon-b/src/main/java/org/jclouds/elastichosts/ElasticHostsBlueSquareLondonProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts;\n\nimport static org.jclouds.compute.config.ComputeServiceProperties.TEMPLATE;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.elasticstack.ElasticStackApiMetadata;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\n\nimport com.google.auto.service.AutoService;\n\n/**\n * Implementation of {@link ProviderMetadata} for ElasticHosts London BlueSquare.\n */\n@AutoService(ProviderMetadata.class)\npublic class ElasticHostsBlueSquareLondonProviderMetadata extends BaseProviderMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromProviderMetadata(this);\n   }\n\n   public ElasticHostsBlueSquareLondonProviderMetadata() {\n      super(builder());\n   }\n\n   public ElasticHostsBlueSquareLondonProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = new Properties();\n      properties.setProperty(TEMPLATE, \"osFamily=UBUNTU,osVersionMatches=1[01234].[01][04].[0-9]*,os64Bit=true\");\n      return properties;\n   }\n\n   public static class Builder\n         extends\n         BaseProviderMetadata.Builder {\n\n      protected Builder() {\n         id(\"elastichosts-lon-b\")\n         .name(\"ElasticHosts Los Angeles BlueSquare\")\n         .apiMetadata(new ElasticStackApiMetadata().toBuilder().version(\"2.0\").build())\n         .homepage(URI.create(\"https://lon-b.elastichosts.com\"))\n         .console(URI.create(\"https://lon-b.elastichosts.com/accounts\"))\n         .iso3166Codes(\"GB-LND\")\n         .endpoint(\"https://api-lon-b.elastichosts.com\")\n         .defaultProperties(ElasticHostsBlueSquareLondonProviderMetadata.defaultProperties());\n      }\n\n      @Override\n      public ElasticHostsBlueSquareLondonProviderMetadata build() {\n         return new ElasticHostsBlueSquareLondonProviderMetadata(this);\n      }\n\n      @Override\n      public Builder fromProviderMetadata(\n            ProviderMetadata in) {\n         super.fromProviderMetadata(in);\n         return this;\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/elastichosts-lon-b/src/test/java/org/jclouds/elastichosts/ElasticHostsBlueSquareLondonApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts;\n\nimport org.jclouds.elasticstack.ElasticStackApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"ElasticHostsBlueSquareLondonApiLiveTest\")\npublic class ElasticHostsBlueSquareLondonApiLiveTest extends ElasticStackApiLiveTest {\n   public ElasticHostsBlueSquareLondonApiLiveTest() {\n      provider = \"elastichosts-lon-b\";\n   }\n}\n"
  },
  {
    "path": "providers/elastichosts-lon-b/src/test/java/org/jclouds/elastichosts/ElasticHostsBlueSquareLondonProviderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts;\n\nimport org.jclouds.elasticstack.ElasticStackApiMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ElasticHostsBlueSquareLondonProviderTest\")\npublic class ElasticHostsBlueSquareLondonProviderTest extends BaseProviderMetadataTest {\n\n   public ElasticHostsBlueSquareLondonProviderTest() {\n      super(new ElasticHostsBlueSquareLondonProviderMetadata(), new ElasticStackApiMetadata());\n   }\n}\n"
  },
  {
    "path": "providers/elastichosts-lon-b/src/test/java/org/jclouds/elastichosts/compute/ElasticHostsBlueSquareLondonComputeServiceLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts.compute;\n\nimport org.jclouds.elasticstack.compute.ElasticStackComputeServiceLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"ElasticHostsBlueSquareLondonComputeServiceLiveTest\")\npublic class ElasticHostsBlueSquareLondonComputeServiceLiveTest extends ElasticStackComputeServiceLiveTest {\n\n   public ElasticHostsBlueSquareLondonComputeServiceLiveTest() {\n      provider = \"elastichosts-lon-b\";\n      group = \"elastichosts\";\n   }\n\n}\n"
  },
  {
    "path": "providers/elastichosts-lon-b/src/test/java/org/jclouds/elastichosts/compute/ElasticHostsBlueSquareLondonTemplateBuilderLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts.compute;\n\nimport static org.jclouds.compute.util.ComputeServiceUtils.getCores;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.internal.BaseTemplateBuilderLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"live\")\npublic class ElasticHostsBlueSquareLondonTemplateBuilderLiveTest extends BaseTemplateBuilderLiveTest {\n\n   public ElasticHostsBlueSquareLondonTemplateBuilderLiveTest() {\n      provider = \"elastichosts-lon-b\";\n   }\n\n   @Override\n   public void testDefaultTemplateBuilder() throws IOException {\n      Template defaultTemplate = view.getComputeService().templateBuilder().build();\n      assertTrue(defaultTemplate.getImage().getOperatingSystem().getVersion().matches(\"1[01234].[01][04].[0-9]*\"));\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true);\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.UBUNTU);\n      assertEquals(getCores(defaultTemplate.getHardware()), 1.0d);\n   }\n\n   @Override\n   protected Set<String> getIso3166Codes() {\n      return ImmutableSet.<String> of(\"GB-LND\");\n   }\n}\n"
  },
  {
    "path": "providers/elastichosts-lon-p/README.txt",
    "content": "#\n# The jclouds provider for ElasticHosts' BlueSquare London ElasticStack  (http://www.elastichosts.com/).\n#\n# Expects the jclouds elasticstack API to be present on your application's classpath.\n#\n# TODO: Implementation status.\n# TODO: Supported features.\n# TODO: Usage example.\n"
  },
  {
    "path": "providers/elastichosts-lon-p/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.elastichosts.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "providers/elastichosts-lon-p/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.provider</groupId>\n  <artifactId>elastichosts-lon-p</artifactId>\n  <name>jclouds ElasticHosts Peer1 London provider</name>\n  <description>ElasticHosts implementation targeted to Peer1 London</description>\n\n  <properties>\n    <test.elastichosts-lon-p.endpoint>https://api-lon-p.elastichosts.com</test.elastichosts-lon-p.endpoint>\n    <test.elastichosts-lon-p.api-version>2.0</test.elastichosts-lon-p.api-version>\n    <test.elastichosts-lon-p.build-version />\n    <test.elastichosts-lon-p.identity>FIXME_IDENTITY</test.elastichosts-lon-p.identity>\n    <test.elastichosts-lon-p.credential>FIXME_CREDENTIAL</test.elastichosts-lon-p.credential>\n    <test.elastichosts-lon-p.template />\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>elasticstack</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>elasticstack</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-log4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-sshj</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.elastichosts-lon-p.endpoint>${test.elastichosts-lon-p.endpoint}</test.elastichosts-lon-p.endpoint>\n                    <test.elastichosts-lon-p.api-version>${test.elastichosts-lon-p.api-version}</test.elastichosts-lon-p.api-version>\n                    <test.elastichosts-lon-p.build-version>${test.elastichosts-lon-p.build-version}</test.elastichosts-lon-p.build-version>\n                    <test.elastichosts-lon-p.identity>${test.elastichosts-lon-p.identity}</test.elastichosts-lon-p.identity>\n                    <test.elastichosts-lon-p.credential>${test.elastichosts-lon-p.credential}</test.elastichosts-lon-p.credential>\n                    <test.elastichosts-lon-p.template>${test.elastichosts-lon-p.template}</test.elastichosts-lon-p.template>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n\n</project>\n\n"
  },
  {
    "path": "providers/elastichosts-lon-p/src/main/java/org/jclouds/elastichosts/ElasticHostsPeer1LondonProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts;\n\nimport static org.jclouds.compute.config.ComputeServiceProperties.TEMPLATE;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.elasticstack.ElasticStackApiMetadata;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\n\nimport com.google.auto.service.AutoService;\n\n/**\n * Implementation of {@link ProviderMetadata} for ElasticHosts London Peer 1.\n */\n@AutoService(ProviderMetadata.class)\npublic class ElasticHostsPeer1LondonProviderMetadata extends BaseProviderMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromProviderMetadata(this);\n   }\n\n   public ElasticHostsPeer1LondonProviderMetadata() {\n      super(builder());\n   }\n\n   public ElasticHostsPeer1LondonProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = new Properties();\n      properties.setProperty(TEMPLATE, \"osFamily=UBUNTU,osVersionMatches=1[01234].[01][04].[0-9]*,os64Bit=true\");\n      return properties;\n   }\n\n   public static class Builder\n         extends\n         BaseProviderMetadata.Builder {\n\n      protected Builder() {\n         id(\"elastichosts-lon-p\")\n         .name(\"ElasticHosts London Peer 1\")\n         .apiMetadata(new ElasticStackApiMetadata().toBuilder().version(\"2.0\").build())\n         .homepage(URI.create(\"https://lon-p.elastichosts.com\"))\n         .console(URI.create(\"https://lon-p.elastichosts.com/accounts\"))\n         .iso3166Codes(\"GB-LND\")\n         .endpoint(\"https://api-lon-p.elastichosts.com\")\n         .defaultProperties(ElasticHostsPeer1LondonProviderMetadata.defaultProperties());\n      }\n\n      @Override\n      public ElasticHostsPeer1LondonProviderMetadata build() {\n         return new ElasticHostsPeer1LondonProviderMetadata(this);\n      }\n\n      @Override\n      public Builder fromProviderMetadata(\n            ProviderMetadata in) {\n         super.fromProviderMetadata(in);\n         return this;\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/elastichosts-lon-p/src/test/java/org/jclouds/elastichosts/ElasticHostsPeer1LondonApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts;\n\nimport org.jclouds.elasticstack.ElasticStackApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"ElasticHostsPeer1LondonApiLiveTest\")\npublic class ElasticHostsPeer1LondonApiLiveTest extends ElasticStackApiLiveTest {\n   public ElasticHostsPeer1LondonApiLiveTest() {\n      provider = \"elastichosts-lon-p\";\n   }\n}\n"
  },
  {
    "path": "providers/elastichosts-lon-p/src/test/java/org/jclouds/elastichosts/ElasticHostsPeer1LondonProviderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts;\n\nimport org.jclouds.elasticstack.ElasticStackApiMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ElasticHostsPeer1LondonProviderTest\")\npublic class ElasticHostsPeer1LondonProviderTest extends BaseProviderMetadataTest {\n\n   public ElasticHostsPeer1LondonProviderTest() {\n      super(new ElasticHostsPeer1LondonProviderMetadata(), new ElasticStackApiMetadata());\n   }\n}\n"
  },
  {
    "path": "providers/elastichosts-lon-p/src/test/java/org/jclouds/elastichosts/compute/ElasticHostsPeer1LondonComputeServiceLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts.compute;\n\nimport org.jclouds.elasticstack.compute.ElasticStackComputeServiceLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"ElasticHostsPeer1LondonComputeServiceLiveTest\")\npublic class ElasticHostsPeer1LondonComputeServiceLiveTest extends ElasticStackComputeServiceLiveTest {\n\n   public ElasticHostsPeer1LondonComputeServiceLiveTest() {\n      provider = \"elastichosts-lon-p\";\n      group = \"elastichosts\";\n   }\n\n}\n"
  },
  {
    "path": "providers/elastichosts-lon-p/src/test/java/org/jclouds/elastichosts/compute/ElasticHostsPeer1LondonTemplateBuilderLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts.compute;\n\nimport static org.jclouds.compute.util.ComputeServiceUtils.getCores;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.internal.BaseTemplateBuilderLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"live\")\npublic class ElasticHostsPeer1LondonTemplateBuilderLiveTest extends BaseTemplateBuilderLiveTest {\n\n   public ElasticHostsPeer1LondonTemplateBuilderLiveTest() {\n      provider = \"elastichosts-lon-p\";\n   }\n\n   @Override\n   public void testDefaultTemplateBuilder() throws IOException {\n      Template defaultTemplate = view.getComputeService().templateBuilder().build();\n      assertTrue(defaultTemplate.getImage().getOperatingSystem().getVersion().matches(\"1[01234].[01][04].[0-9]*\"));\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true);\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.UBUNTU);\n      assertEquals(getCores(defaultTemplate.getHardware()), 1.0d);\n   }\n\n   @Override\n   protected Set<String> getIso3166Codes() {\n      return ImmutableSet.of(\"GB-LND\");\n   }\n}\n"
  },
  {
    "path": "providers/elastichosts-mmi-a/README.txt",
    "content": "#\n# The jclouds provider for ElasticHosts' Miami ElasticStack  (http://www.elastichosts.com/).\n#\n# Expects the jclouds elasticstack API to be present on your application's classpath.\n#\n\n"
  },
  {
    "path": "providers/elastichosts-mmi-a/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.elastichosts.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "providers/elastichosts-mmi-a/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.provider</groupId>\n  <artifactId>elastichosts-mmi-a</artifactId>\n  <name>jclouds ElasticHosts Miami provider</name>\n  <description>ElasticHosts implementation targeted to Miami</description>\n\n  <properties>\n    <test.elastichosts-mmi-a.endpoint>https://api-mmi-a.elastichosts.com</test.elastichosts-mmi-a.endpoint>\n    <test.elastichosts-mmi-a.api-version>2.0</test.elastichosts-mmi-a.api-version>\n    <test.elastichosts-mmi-a.build-version />\n    <test.elastichosts-mmi-a.identity>FIXME_IDENTITY</test.elastichosts-mmi-a.identity>\n    <test.elastichosts-mmi-a.credential>FIXME_CREDENTIAL</test.elastichosts-mmi-a.credential>\n    <test.elastichosts-mmi-a.template />\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>elasticstack</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>elasticstack</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-log4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-sshj</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.elastichosts-mmi-a.endpoint>${test.elastichosts-mmi-a.endpoint}</test.elastichosts-mmi-a.endpoint>\n                    <test.elastichosts-mmi-a.api-version>${test.elastichosts-mmi-a.api-version}</test.elastichosts-mmi-a.api-version>\n                    <test.elastichosts-mmi-a.build-version>${test.elastichosts-mmi-a.build-version}</test.elastichosts-mmi-a.build-version>\n                    <test.elastichosts-mmi-a.identity>${test.elastichosts-mmi-a.identity}</test.elastichosts-mmi-a.identity>\n                    <test.elastichosts-mmi-a.credential>${test.elastichosts-mmi-a.credential}</test.elastichosts-mmi-a.credential>\n                    <test.elastichosts-mmi-a.template>${test.elastichosts-mmi-a.template}</test.elastichosts-mmi-a.template>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n</project>\n\n"
  },
  {
    "path": "providers/elastichosts-mmi-a/src/main/java/org/jclouds/elastichosts/ElasticHostsMiamiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts;\n\nimport static org.jclouds.compute.config.ComputeServiceProperties.TEMPLATE;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.elasticstack.ElasticStackApiMetadata;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\n\nimport com.google.auto.service.AutoService;\n\n/**\n * Implementation of {@link ProviderMetadata} for ElasticHosts Miami.\n */\n@AutoService(ProviderMetadata.class)\npublic class ElasticHostsMiamiMetadata extends BaseProviderMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromProviderMetadata(this);\n   }\n\n   public ElasticHostsMiamiMetadata() {\n      super(builder());\n   }\n\n   public ElasticHostsMiamiMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = new Properties();\n      properties.setProperty(TEMPLATE, \"osFamily=UBUNTU,osVersionMatches=1[01234].[01][04],os64Bit=true\");\n      return properties;\n   }\n\n   public static class Builder extends BaseProviderMetadata.Builder {\n\n      protected Builder() {\n         id(\"elastichosts-mmi-a\").name(\"ElasticHosts Miami\")\n               .apiMetadata(new ElasticStackApiMetadata().toBuilder().version(\"2.0\").build())\n               .homepage(URI.create(\"https://mmi-a.elastichosts.com\"))\n               .console(URI.create(\"https://mmi-a.elastichosts.com/accounts\"))\n               .iso3166Codes(\"US-FL\")\n               .endpoint(\"https://api-mmi-a.elastichosts.com\")\n               .defaultProperties(ElasticHostsMiamiMetadata.defaultProperties());\n      }\n\n      @Override\n      public ElasticHostsMiamiMetadata build() {\n         return new ElasticHostsMiamiMetadata(this);\n      }\n\n      @Override\n      public Builder fromProviderMetadata(ProviderMetadata in) {\n         super.fromProviderMetadata(in);\n         return this;\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/elastichosts-mmi-a/src/test/java/org/jclouds/elastichosts/ElasticHostsMiamiApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts;\n\nimport org.jclouds.elasticstack.ElasticStackApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"ElasticHostsMiamiApiLiveTest\")\npublic class ElasticHostsMiamiApiLiveTest extends ElasticStackApiLiveTest {\n   public ElasticHostsMiamiApiLiveTest() {\n      provider = \"elastichosts-mmi-a\";\n   }\n}\n"
  },
  {
    "path": "providers/elastichosts-mmi-a/src/test/java/org/jclouds/elastichosts/ElasticHostsMiamiProviderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts;\n\nimport org.jclouds.elasticstack.ElasticStackApiMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ElasticHostsMiamiProviderTest\")\npublic class ElasticHostsMiamiProviderTest extends BaseProviderMetadataTest {\n\n   public ElasticHostsMiamiProviderTest() {\n      super(new ElasticHostsMiamiMetadata(), new ElasticStackApiMetadata());\n   }\n}\n"
  },
  {
    "path": "providers/elastichosts-mmi-a/src/test/java/org/jclouds/elastichosts/compute/ElasticHostsMiamiComputeServiceLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts.compute;\n\nimport org.jclouds.elasticstack.compute.ElasticStackComputeServiceLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"ElasticHostsMiamiComputeServiceLiveTest\")\npublic class ElasticHostsMiamiComputeServiceLiveTest extends ElasticStackComputeServiceLiveTest {\n\n   public ElasticHostsMiamiComputeServiceLiveTest() {\n      provider = \"elastichosts-mmi-a\";\n      group = \"elastichosts\";\n   }\n\n}\n"
  },
  {
    "path": "providers/elastichosts-mmi-a/src/test/java/org/jclouds/elastichosts/compute/ElasticHostsMiamiTemplateBuilderLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts.compute;\n\nimport static org.jclouds.compute.util.ComputeServiceUtils.getCores;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.internal.BaseTemplateBuilderLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"live\", testName = \"ElasticHostsMiamiTemplateBuilderLiveTest\")\npublic class ElasticHostsMiamiTemplateBuilderLiveTest extends BaseTemplateBuilderLiveTest {\n\n   public ElasticHostsMiamiTemplateBuilderLiveTest() {\n      provider = \"elastichosts-mmi-a\";\n   }\n\n   @Override\n   public void testDefaultTemplateBuilder() throws IOException {\n      Template defaultTemplate = view.getComputeService().templateBuilder().build();\n      assertTrue(defaultTemplate.getImage().getOperatingSystem().getVersion().matches(\"1[01234].[01][04]\"));\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true);\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.UBUNTU);\n      assertEquals(getCores(defaultTemplate.getHardware()), 1.0d);\n   }\n\n   @Override\n   protected Set<String> getIso3166Codes() {\n      return ImmutableSet.<String> of(\"US-FL\");\n   }\n}\n"
  },
  {
    "path": "providers/elastichosts-sat-p/README.txt",
    "content": "#\n# The jclouds provider for ElasticHosts' Peer1 San Antonio ElasticStack  (http://www.elastichosts.com/).\n#\n# Expects the jclouds elasticstack API to be present on your application's classpath.\n#\n# TODO: Implementation status.\n# TODO: Supported features.\n# TODO: Usage example.\n"
  },
  {
    "path": "providers/elastichosts-sat-p/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.elastichosts.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "providers/elastichosts-sat-p/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.provider</groupId>\n  <artifactId>elastichosts-sat-p</artifactId>\n  <name>jclouds ElasticHosts Peer1 San Antonio provider</name>\n  <description>ElasticHosts implementation targeted to Peer1 San Antonio</description>\n\n  <properties>\n    <test.elastichosts-sat-p.endpoint>https://api-sat-p.elastichosts.com</test.elastichosts-sat-p.endpoint>\n    <test.elastichosts-sat-p.api-version>2.0</test.elastichosts-sat-p.api-version>\n    <test.elastichosts-sat-p.build-version />\n    <test.elastichosts-sat-p.identity>FIXME_IDENTITY</test.elastichosts-sat-p.identity>\n    <test.elastichosts-sat-p.credential>FIXME_CREDENTIAL</test.elastichosts-sat-p.credential>\n    <test.elastichosts-sat-p.template />\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>elasticstack</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>elasticstack</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-log4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-sshj</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.elastichosts-sat-p.endpoint>${test.elastichosts-sat-p.endpoint}</test.elastichosts-sat-p.endpoint>\n                    <test.elastichosts-sat-p.api-version>${test.elastichosts-sat-p.api-version}</test.elastichosts-sat-p.api-version>\n                    <test.elastichosts-sat-p.build-version>${test.elastichosts-sat-p.build-version}</test.elastichosts-sat-p.build-version>\n                    <test.elastichosts-sat-p.identity>${test.elastichosts-sat-p.identity}</test.elastichosts-sat-p.identity>\n                    <test.elastichosts-sat-p.credential>${test.elastichosts-sat-p.credential}</test.elastichosts-sat-p.credential>\n                    <test.elastichosts-sat-p.template>${test.elastichosts-sat-p.template}</test.elastichosts-sat-p.template>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n\n"
  },
  {
    "path": "providers/elastichosts-sat-p/src/main/java/org/jclouds/elastichosts/ElasticHostsPeer1SanAntonioProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts;\n\nimport static org.jclouds.compute.config.ComputeServiceProperties.TEMPLATE;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.elasticstack.ElasticStackApiMetadata;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\n\nimport com.google.auto.service.AutoService;\n\n/**\n * Implementation of {@link ProviderMetadata} for ElasticHosts San Antonio Peer 1.\n */\n@AutoService(ProviderMetadata.class)\npublic class ElasticHostsPeer1SanAntonioProviderMetadata extends BaseProviderMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromProviderMetadata(this);\n   }\n\n   public ElasticHostsPeer1SanAntonioProviderMetadata() {\n      super(builder());\n   }\n\n   public ElasticHostsPeer1SanAntonioProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = new Properties();\n      properties.setProperty(TEMPLATE, \"osFamily=UBUNTU,osVersionMatches=1[01234].[01][04].[0-9]*,os64Bit=true\");\n      return properties;\n   }\n\n   public static class Builder extends BaseProviderMetadata.Builder {\n\n      protected Builder() {\n         id(\"elastichosts-sat-p\")\n         .name(\"ElasticHosts San Antonio Peer 1\")\n         .apiMetadata(new ElasticStackApiMetadata().toBuilder().version(\"2.0\").build())\n         .homepage(URI.create(\"https://sat-p.elastichosts.com\"))\n         .console(URI.create(\"https://sat-p.elastichosts.com/accounts\"))\n         .iso3166Codes(\"US-TX\")\n         .endpoint(\"https://api-sat-p.elastichosts.com\")\n         .defaultProperties(ElasticHostsPeer1SanAntonioProviderMetadata.defaultProperties());\n      }\n\n      @Override\n      public ElasticHostsPeer1SanAntonioProviderMetadata build() {\n         return new ElasticHostsPeer1SanAntonioProviderMetadata(this);\n      }\n\n      @Override\n      public Builder fromProviderMetadata(ProviderMetadata in) {\n         super.fromProviderMetadata(in);\n         return this;\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/elastichosts-sat-p/src/test/java/org/jclouds/elastichosts/ElasticHostsPeer1SanAntonioApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts;\n\nimport org.jclouds.elasticstack.ElasticStackApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"ElasticHostsPeer1SanAntonioApiLiveTest\")\npublic class ElasticHostsPeer1SanAntonioApiLiveTest extends ElasticStackApiLiveTest {\n   public ElasticHostsPeer1SanAntonioApiLiveTest() {\n      provider = \"elastichosts-sat-p\";\n   }\n}\n"
  },
  {
    "path": "providers/elastichosts-sat-p/src/test/java/org/jclouds/elastichosts/ElasticHostsPeer1SanAntonioProviderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts;\n\nimport org.jclouds.elasticstack.ElasticStackApiMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ElasticHostsPeer1SanAntonioProviderTest\")\npublic class ElasticHostsPeer1SanAntonioProviderTest extends BaseProviderMetadataTest {\n\n   public ElasticHostsPeer1SanAntonioProviderTest() {\n      super(new ElasticHostsPeer1SanAntonioProviderMetadata(), new ElasticStackApiMetadata());\n   }\n}\n"
  },
  {
    "path": "providers/elastichosts-sat-p/src/test/java/org/jclouds/elastichosts/compute/ElasticHostsPeer1SanAntonioComputeServiceLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts.compute;\n\nimport org.jclouds.elasticstack.compute.ElasticStackComputeServiceLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"ElasticHostsPeer1SanAntonioComputeServiceLiveTest\")\npublic class ElasticHostsPeer1SanAntonioComputeServiceLiveTest extends ElasticStackComputeServiceLiveTest {\n\n   public ElasticHostsPeer1SanAntonioComputeServiceLiveTest() {\n      provider = \"elastichosts-sat-p\";\n      group = \"elastichosts\";\n   }\n\n}\n"
  },
  {
    "path": "providers/elastichosts-sat-p/src/test/java/org/jclouds/elastichosts/compute/ElasticHostsPeer1SanAntonioTemplateBuilderLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts.compute;\n\nimport static org.jclouds.compute.util.ComputeServiceUtils.getCores;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.internal.BaseTemplateBuilderLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"live\")\npublic class ElasticHostsPeer1SanAntonioTemplateBuilderLiveTest extends BaseTemplateBuilderLiveTest {\n\n   public ElasticHostsPeer1SanAntonioTemplateBuilderLiveTest() {\n      provider = \"elastichosts-sat-p\";\n   }\n\n   @Override\n   public void testDefaultTemplateBuilder() throws IOException {\n      Template defaultTemplate = view.getComputeService().templateBuilder().build();\n      assertTrue(defaultTemplate.getImage().getOperatingSystem().getVersion().matches(\"1[01234].[01][04].[0-9]*\"));\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true);\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.UBUNTU);\n      assertEquals(getCores(defaultTemplate.getHardware()), 1.0d);\n   }\n\n   @Override\n   protected Set<String> getIso3166Codes() {\n      return ImmutableSet.of(\"US-TX\");\n   }\n}\n"
  },
  {
    "path": "providers/elastichosts-sjc-c/README.txt",
    "content": "#\n# The jclouds provider for ElasticHosts' San Jose ElasticStack  (http://www.elastichosts.com/).\n#\n# Expects the jclouds elasticstack API to be present on your application's classpath.\n#"
  },
  {
    "path": "providers/elastichosts-sjc-c/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.elastichosts.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "providers/elastichosts-sjc-c/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.provider</groupId>\n  <artifactId>elastichosts-sjc-c</artifactId>\n  <name>jclouds ElasticHosts San Jose provider</name>\n  <description>ElasticHosts implementation targeted to San Jose</description>\n\n  <properties>\n    <test.elastichosts-sjc-c.endpoint>https://api-sjc-c.elastichosts.com</test.elastichosts-sjc-c.endpoint>\n    <test.elastichosts-sjc-c.api-version>2.0</test.elastichosts-sjc-c.api-version>\n    <test.elastichosts-sjc-c.build-version />\n    <test.elastichosts-sjc-c.identity>FIXME_IDENTITY</test.elastichosts-sjc-c.identity>\n    <test.elastichosts-sjc-c.credential>FIXME_CREDENTIAL</test.elastichosts-sjc-c.credential>\n    <test.elastichosts-sjc-c.template />\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>elasticstack</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>elasticstack</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-log4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-sshj</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.elastichosts-sjc-c.endpoint>${test.elastichosts-sjc-c.endpoint}</test.elastichosts-sjc-c.endpoint>\n                    <test.elastichosts-sjc-c.api-version>${test.elastichosts-sjc-c.api-version}</test.elastichosts-sjc-c.api-version>\n                    <test.elastichosts-sjc-c.build-version>${test.elastichosts-sjc-c.build-version}</test.elastichosts-sjc-c.build-version>\n                    <test.elastichosts-sjc-c.identity>${test.elastichosts-sjc-c.identity}</test.elastichosts-sjc-c.identity>\n                    <test.elastichosts-sjc-c.credential>${test.elastichosts-sjc-c.credential}</test.elastichosts-sjc-c.credential>\n                    <test.elastichosts-sjc-c.template>${test.elastichosts-sjc-c.template}</test.elastichosts-sjc-c.template>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n</project>\n\n"
  },
  {
    "path": "providers/elastichosts-sjc-c/src/main/java/org/jclouds/elastichosts/ElasticHostsSanJoseProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts;\n\nimport static org.jclouds.compute.config.ComputeServiceProperties.TEMPLATE;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.elasticstack.ElasticStackApiMetadata;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\n\nimport com.google.auto.service.AutoService;\n\n/**\n * Implementation of {@link ProviderMetadata} for ElasticHosts San Jose.\n */\n@AutoService(ProviderMetadata.class)\npublic class ElasticHostsSanJoseProviderMetadata extends BaseProviderMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromProviderMetadata(this);\n   }\n\n   public ElasticHostsSanJoseProviderMetadata() {\n      super(builder());\n   }\n\n   public ElasticHostsSanJoseProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = new Properties();\n      properties.setProperty(TEMPLATE, \"osFamily=UBUNTU,osVersionMatches=1[01234].[01][04].[0-9]*,os64Bit=true\");\n      return properties;\n   }\n\n   public static class Builder extends BaseProviderMetadata.Builder {\n\n      protected Builder() {\n         id(\"elastichosts-sjc-c\")\n         .name(\"ElasticHosts San Jose\")\n         .apiMetadata(new ElasticStackApiMetadata().toBuilder().version(\"2.0\").build())\n         .homepage(URI.create(\"https://sjc-c.elastichosts.com\"))\n         .console(URI.create(\"https://sjc-c.elastichosts.com/accounts\"))\n         .iso3166Codes(\"US-CA\")\n         .endpoint(\"https://api-sjc-c.elastichosts.com\")\n         .defaultProperties(ElasticHostsSanJoseProviderMetadata.defaultProperties());\n      }\n\n      @Override\n      public ElasticHostsSanJoseProviderMetadata build() {\n         return new ElasticHostsSanJoseProviderMetadata(this);\n      }\n\n      @Override\n      public Builder fromProviderMetadata(ProviderMetadata in) {\n         super.fromProviderMetadata(in);\n         return this;\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/elastichosts-sjc-c/src/test/java/org/jclouds/elastichosts/ElasticHostsSanJoseApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts;\n\nimport org.jclouds.elasticstack.ElasticStackApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"ElasticHostsSanJoseApiLiveTest\")\npublic class ElasticHostsSanJoseApiLiveTest extends ElasticStackApiLiveTest {\n   public ElasticHostsSanJoseApiLiveTest() {\n      provider = \"elastichosts-sjc-c\";\n   }\n}\n"
  },
  {
    "path": "providers/elastichosts-sjc-c/src/test/java/org/jclouds/elastichosts/ElasticHostsSanJoseProviderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts;\n\nimport org.jclouds.elasticstack.ElasticStackApiMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ElasticHostsSanJoseProviderTest\")\npublic class ElasticHostsSanJoseProviderTest extends BaseProviderMetadataTest {\n\n   public ElasticHostsSanJoseProviderTest() {\n      super(new ElasticHostsSanJoseProviderMetadata(), new ElasticStackApiMetadata());\n   }\n}\n"
  },
  {
    "path": "providers/elastichosts-sjc-c/src/test/java/org/jclouds/elastichosts/compute/ElasticHostsSanJoseComputeServiceLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts.compute;\n\nimport org.jclouds.elasticstack.compute.ElasticStackComputeServiceLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"ElasticHostsSanJoseComputeServiceLiveTest\")\npublic class ElasticHostsSanJoseComputeServiceLiveTest extends ElasticStackComputeServiceLiveTest {\n\n   public ElasticHostsSanJoseComputeServiceLiveTest() {\n      provider = \"elastichosts-sjc-c\";\n      group = \"elastichosts\";\n   }\n\n}\n"
  },
  {
    "path": "providers/elastichosts-sjc-c/src/test/java/org/jclouds/elastichosts/compute/ElasticHostsSanJoseTemplateBuilderLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts.compute;\n\nimport static org.jclouds.compute.util.ComputeServiceUtils.getCores;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.internal.BaseTemplateBuilderLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"live\", testName = \"ElasticHostsSanJoseTemplateBuilderLiveTest\")\npublic class ElasticHostsSanJoseTemplateBuilderLiveTest extends BaseTemplateBuilderLiveTest {\n\n   public ElasticHostsSanJoseTemplateBuilderLiveTest() {\n      provider = \"elastichosts-sjc-c\";\n   }\n\n   @Override\n   public void testDefaultTemplateBuilder() throws IOException {\n      Template defaultTemplate = view.getComputeService().templateBuilder().build();\n      assertTrue(defaultTemplate.getImage().getOperatingSystem().getVersion().matches(\"1[01234].[01][04].[0-9]*\"));\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true);\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.UBUNTU);\n      assertEquals(getCores(defaultTemplate.getHardware()), 1.0d);\n   }\n\n   @Override\n   protected Set<String> getIso3166Codes() {\n      return ImmutableSet.<String> of(\"US-CA\");\n   }\n}\n"
  },
  {
    "path": "providers/elastichosts-syd-v/README.txt",
    "content": "#\n# The jclouds provider for ElasticHosts' Sydney ElasticStack  (http://www.elastichosts.com/).\n#\n# Expects the jclouds elasticstack API to be present on your application's classpath.\n#"
  },
  {
    "path": "providers/elastichosts-syd-v/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.elastichosts.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "providers/elastichosts-syd-v/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.provider</groupId>\n  <artifactId>elastichosts-syd-v</artifactId>\n  <name>jclouds ElasticHosts Sydney provider</name>\n  <description>ElasticHosts implementation targeted to Sydney</description>\n\n  <properties>\n    <test.elastichosts-syd-v.endpoint>https://api-syd-v.elastichosts.com</test.elastichosts-syd-v.endpoint>\n    <test.elastichosts-syd-v.api-version>2.0</test.elastichosts-syd-v.api-version>\n    <test.elastichosts-syd-v.build-version />\n    <test.elastichosts-syd-v.identity>FIXME_IDENTITY</test.elastichosts-syd-v.identity>\n    <test.elastichosts-syd-v.credential>FIXME_CREDENTIAL</test.elastichosts-syd-v.credential>\n    <test.elastichosts-syd-v.template />\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>elasticstack</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>elasticstack</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-log4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-sshj</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.elastichosts-syd-v.endpoint>${test.elastichosts-syd-v.endpoint}</test.elastichosts-syd-v.endpoint>\n                    <test.elastichosts-syd-v.api-version>${test.elastichosts-syd-v.api-version}</test.elastichosts-syd-v.api-version>\n                    <test.elastichosts-syd-v.build-version>${test.elastichosts-syd-v.build-version}</test.elastichosts-syd-v.build-version>\n                    <test.elastichosts-syd-v.identity>${test.elastichosts-syd-v.identity}</test.elastichosts-syd-v.identity>\n                    <test.elastichosts-syd-v.credential>${test.elastichosts-syd-v.credential}</test.elastichosts-syd-v.credential>\n                    <test.elastichosts-syd-v.template>${test.elastichosts-syd-v.template}</test.elastichosts-syd-v.template>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n</project>\n\n"
  },
  {
    "path": "providers/elastichosts-syd-v/src/main/java/org/jclouds/elastichosts/ElasticHostsSydneyProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts;\n\nimport static org.jclouds.compute.config.ComputeServiceProperties.TEMPLATE;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.elasticstack.ElasticStackApiMetadata;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\n\nimport com.google.auto.service.AutoService;\n\n/**\n * Implementation of {@link ProviderMetadata} for ElasticHosts Sydney.\n */\n@AutoService(ProviderMetadata.class)\npublic class ElasticHostsSydneyProviderMetadata extends BaseProviderMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromProviderMetadata(this);\n   }\n\n   public ElasticHostsSydneyProviderMetadata() {\n      super(builder());\n   }\n\n   public ElasticHostsSydneyProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = new Properties();\n      properties.setProperty(TEMPLATE, \"osFamily=UBUNTU,osVersionMatches=1[01234].[01][04].[0-9]*,os64Bit=true\");\n      return properties;\n   }\n\n   public static class Builder extends BaseProviderMetadata.Builder {\n\n      protected Builder() {\n         id(\"elastichosts-syd-v\")\n         .name(\"ElasticHosts Sydney\")\n         .apiMetadata(new ElasticStackApiMetadata().toBuilder().version(\"2.0\").build())\n         .homepage(URI.create(\"https://syd-v.elastichosts.com\"))\n         .console(URI.create(\"https://syd-v.elastichosts.com/accounts\"))\n         .iso3166Codes(\"AU-NSW\")\n         .endpoint(\"https://api-syd-v.elastichosts.com\")\n         .defaultProperties(ElasticHostsSydneyProviderMetadata.defaultProperties());\n      }\n\n      @Override\n      public ElasticHostsSydneyProviderMetadata build() {\n         return new ElasticHostsSydneyProviderMetadata(this);\n      }\n\n      @Override\n      public Builder fromProviderMetadata(ProviderMetadata in) {\n         super.fromProviderMetadata(in);\n         return this;\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/elastichosts-syd-v/src/test/java/org/jclouds/elastichosts/ElasticHostsSydneyApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts;\n\nimport org.jclouds.elasticstack.ElasticStackApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"ElasticHostsSydneyApiLiveTest\")\npublic class ElasticHostsSydneyApiLiveTest extends ElasticStackApiLiveTest {\n   public ElasticHostsSydneyApiLiveTest() {\n      provider = \"elastichosts-syd-v\";\n   }\n}\n"
  },
  {
    "path": "providers/elastichosts-syd-v/src/test/java/org/jclouds/elastichosts/ElasticHostsSydneyProviderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts;\n\nimport org.jclouds.elasticstack.ElasticStackApiMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ElasticHostsSydneyProviderTest\")\npublic class ElasticHostsSydneyProviderTest extends BaseProviderMetadataTest {\n\n   public ElasticHostsSydneyProviderTest() {\n      super(new ElasticHostsSydneyProviderMetadata(), new ElasticStackApiMetadata());\n   }\n}\n"
  },
  {
    "path": "providers/elastichosts-syd-v/src/test/java/org/jclouds/elastichosts/compute/ElasticHostsSydneyComputeServiceLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts.compute;\n\nimport org.jclouds.elasticstack.compute.ElasticStackComputeServiceLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"ElasticHostsSydneyComputeServiceLiveTest\")\npublic class ElasticHostsSydneyComputeServiceLiveTest extends ElasticStackComputeServiceLiveTest {\n\n   public ElasticHostsSydneyComputeServiceLiveTest() {\n      provider = \"elastichosts-syd-v\";\n      group = \"elastichosts\";\n   }\n\n}\n"
  },
  {
    "path": "providers/elastichosts-syd-v/src/test/java/org/jclouds/elastichosts/compute/ElasticHostsSydneyTemplateBuilderLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts.compute;\n\nimport static org.jclouds.compute.util.ComputeServiceUtils.getCores;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.internal.BaseTemplateBuilderLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"live\", testName = \"ElasticHostsSydneyTemplateBuilderLiveTest\")\npublic class ElasticHostsSydneyTemplateBuilderLiveTest extends BaseTemplateBuilderLiveTest {\n\n   public ElasticHostsSydneyTemplateBuilderLiveTest() {\n      provider = \"elastichosts-syd-v\";\n   }\n\n   @Override\n   public void testDefaultTemplateBuilder() throws IOException {\n      Template defaultTemplate = view.getComputeService().templateBuilder().build();\n      assertTrue(defaultTemplate.getImage().getOperatingSystem().getVersion().matches(\"1[01234].[01][04].[0-9]*\"));\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true);\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.UBUNTU);\n      assertEquals(getCores(defaultTemplate.getHardware()), 1.0d);\n   }\n\n   @Override\n   protected Set<String> getIso3166Codes() {\n      return ImmutableSet.<String> of(\"AU-NSW\");\n   }\n}\n"
  },
  {
    "path": "providers/elastichosts-tor-p/README.txt",
    "content": "#\n# The jclouds provider for ElasticHosts' Peer1 Toronto ElasticStack  (http://www.elastichosts.com/).\n#\n# Expects the jclouds elasticstack API to be present on your application's classpath.\n#\n# TODO: Implementation status.\n# TODO: Supported features.\n# TODO: Usage example.\n"
  },
  {
    "path": "providers/elastichosts-tor-p/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.elastichosts.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "providers/elastichosts-tor-p/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.provider</groupId>\n  <artifactId>elastichosts-tor-p</artifactId>\n  <name>jclouds ElasticHosts Peer1 Toronto provider</name>\n  <description>ElasticHosts implementation targeted to Peer1 Toronto</description>\n\n  <properties>\n    <test.elastichosts-tor-p.endpoint>https://api-tor-p.elastichosts.com</test.elastichosts-tor-p.endpoint>\n    <test.elastichosts-tor-p.api-version>2.0</test.elastichosts-tor-p.api-version>\n    <test.elastichosts-tor-p.build-version />\n    <test.elastichosts-tor-p.identity>FIXME_IDENTITY</test.elastichosts-tor-p.identity>\n    <test.elastichosts-tor-p.credential>FIXME_CREDENTIAL</test.elastichosts-tor-p.credential>\n    <test.elastichosts-tor-p.template />\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>elasticstack</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>elasticstack</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-log4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-sshj</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.elastichosts-tor-p.endpoint>${test.elastichosts-tor-p.endpoint}</test.elastichosts-tor-p.endpoint>\n                    <test.elastichosts-tor-p.api-version>${test.elastichosts-tor-p.api-version}</test.elastichosts-tor-p.api-version>\n                    <test.elastichosts-tor-p.build-version>${test.elastichosts-tor-p.build-version}</test.elastichosts-tor-p.build-version>\n                    <test.elastichosts-tor-p.identity>${test.elastichosts-tor-p.identity}</test.elastichosts-tor-p.identity>\n                    <test.elastichosts-tor-p.credential>${test.elastichosts-tor-p.credential}</test.elastichosts-tor-p.credential>\n                    <test.elastichosts-tor-p.template>${test.elastichosts-tor-p.template}</test.elastichosts-tor-p.template>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n\n"
  },
  {
    "path": "providers/elastichosts-tor-p/src/main/java/org/jclouds/elastichosts/ElasticHostsPeer1TorontoProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts;\n\nimport static org.jclouds.compute.config.ComputeServiceProperties.TEMPLATE;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.elasticstack.ElasticStackApiMetadata;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\n\nimport com.google.auto.service.AutoService;\n\n/**\n * Implementation of {@link ProviderMetadata} for ElasticHosts Toronto Peer 1.\n */\n@AutoService(ProviderMetadata.class)\npublic class ElasticHostsPeer1TorontoProviderMetadata extends BaseProviderMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromProviderMetadata(this);\n   }\n\n   public ElasticHostsPeer1TorontoProviderMetadata() {\n      super(builder());\n   }\n\n   public ElasticHostsPeer1TorontoProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = new Properties();\n      properties.setProperty(TEMPLATE, \"osFamily=UBUNTU,osVersionMatches=1[01234].[01][04].[0-9]*,os64Bit=true\");\n      return properties;\n   }\n\n   public static class Builder extends BaseProviderMetadata.Builder {\n\n      protected Builder() {\n         id(\"elastichosts-tor-p\")\n         .name(\"ElasticHosts Toronto Peer 1\")\n         .apiMetadata(new ElasticStackApiMetadata().toBuilder().version(\"2.0\").build())\n         .homepage(URI.create(\"https://tor-p.elastichosts.com\"))\n         .console(URI.create(\"https://tor-p.elastichosts.com/accounts\"))\n         .iso3166Codes(\"CA-ON\")\n         .endpoint(\"https://api-tor-p.elastichosts.com\")\n         .defaultProperties(ElasticHostsPeer1TorontoProviderMetadata.defaultProperties());\n      }\n\n      @Override\n      public ElasticHostsPeer1TorontoProviderMetadata build() {\n         return new ElasticHostsPeer1TorontoProviderMetadata(this);\n      }\n\n      @Override\n      public Builder fromProviderMetadata(\n            ProviderMetadata in) {\n         super.fromProviderMetadata(in);\n         return this;\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/elastichosts-tor-p/src/test/java/org/jclouds/elastichosts/ElasticHostsPeer1TorontoApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts;\n\nimport org.jclouds.elasticstack.ElasticStackApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"ElasticHostsPeer1TorontoApiLiveTest\")\npublic class ElasticHostsPeer1TorontoApiLiveTest extends ElasticStackApiLiveTest {\n   public ElasticHostsPeer1TorontoApiLiveTest() {\n      provider = \"elastichosts-tor-p\";\n   }\n}\n"
  },
  {
    "path": "providers/elastichosts-tor-p/src/test/java/org/jclouds/elastichosts/ElasticHostsPeer1TorontoProviderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts;\n\nimport org.jclouds.elasticstack.ElasticStackApiMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ElasticHostsPeer1TorontoProviderTest\")\npublic class ElasticHostsPeer1TorontoProviderTest extends BaseProviderMetadataTest {\n\n   public ElasticHostsPeer1TorontoProviderTest() {\n      super(new ElasticHostsPeer1TorontoProviderMetadata(), new ElasticStackApiMetadata());\n   }\n}\n"
  },
  {
    "path": "providers/elastichosts-tor-p/src/test/java/org/jclouds/elastichosts/compute/ElasticHostsPeer1TorontoComputeServiceLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts.compute;\n\nimport org.jclouds.elasticstack.compute.ElasticStackComputeServiceLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"ElasticHostsPeer1TorontoComputeServiceLiveTest\")\npublic class ElasticHostsPeer1TorontoComputeServiceLiveTest extends ElasticStackComputeServiceLiveTest {\n\n   public ElasticHostsPeer1TorontoComputeServiceLiveTest() {\n      provider = \"elastichosts-tor-p\";\n      group = \"elastichosts\";\n   }\n\n}\n"
  },
  {
    "path": "providers/elastichosts-tor-p/src/test/java/org/jclouds/elastichosts/compute/ElasticHostsPeer1TorontoTemplateBuilderLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.elastichosts.compute;\n\nimport static org.jclouds.compute.util.ComputeServiceUtils.getCores;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.internal.BaseTemplateBuilderLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"live\")\npublic class ElasticHostsPeer1TorontoTemplateBuilderLiveTest extends BaseTemplateBuilderLiveTest {\n\n   public ElasticHostsPeer1TorontoTemplateBuilderLiveTest() {\n      provider = \"elastichosts-tor-p\";\n   }\n\n   @Override\n   public void testDefaultTemplateBuilder() throws IOException {\n      Template defaultTemplate = view.getComputeService().templateBuilder().build();\n      assertTrue(defaultTemplate.getImage().getOperatingSystem().getVersion().matches(\"1[01234].[01][04].[0-9]*\"));\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true);\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.UBUNTU);\n      assertEquals(getCores(defaultTemplate.getHardware()), 1.0d);\n   }\n\n   @Override\n   protected Set<String> getIso3166Codes() {\n      return ImmutableSet.<String> of(\"CA-ON\");\n   }\n}\n"
  },
  {
    "path": "providers/glesys/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.glesys.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "providers/glesys/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.provider</groupId>\n  <artifactId>glesys</artifactId>\n  <name>jclouds GleSYS core</name>\n  <description>jclouds components to access GleSYS</description>\n\n  <properties>\n    <test.glesys.endpoint>https://api.glesys.com</test.glesys.endpoint>\n    <test.glesys.api-version>1</test.glesys.api-version>\n    <test.glesys.build-version>3.5.0</test.glesys.build-version>\n    <test.glesys.identity>FIXME_IDENTITY</test.glesys.identity>\n    <test.glesys.credential>FIXME_CREDENTIAL</test.glesys.credential>\n    <test.glesys.template>osFamily=UBUNTU,osVersionMatches=1[012].[01][04],os64Bit=true,minRam=768</test.glesys.template>\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-log4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-sshj</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.glesys.endpoint>${test.glesys.endpoint}</test.glesys.endpoint>\n                    <test.glesys.api-version>${test.glesys.api-version}</test.glesys.api-version>\n                    <test.glesys.build-version>${test.glesys.build-version}</test.glesys.build-version>\n                    <test.glesys.identity>${test.glesys.identity}</test.glesys.identity>\n                    <test.glesys.credential>${test.glesys.credential}</test.glesys.credential>\n                    <test.glesys.template>${test.glesys.template}</test.glesys.template>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/GleSYSApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys;\n\nimport java.io.Closeable;\n\nimport org.jclouds.glesys.features.ArchiveApi;\nimport org.jclouds.glesys.features.DomainApi;\nimport org.jclouds.glesys.features.EmailAccountApi;\nimport org.jclouds.glesys.features.IpApi;\nimport org.jclouds.glesys.features.ServerApi;\nimport org.jclouds.rest.annotations.Delegate;\n\n/**\n * Provides synchronous access to GleSYS.\n * <p/>\n * \n * @see <a href=\"https://customer.glesys.com/api.php\" />\n */\npublic interface GleSYSApi extends Closeable {\n\n   /**\n    * Provides synchronous access to Server features.\n    */\n   @Delegate\n   ServerApi getServerApi();\n\n   /**\n    * Provides synchronous access to Ip Address features.\n    */\n   @Delegate\n   IpApi getIpApi();\n\n   /**\n    * Provides synchronous access to Archive features.\n    */\n   @Delegate\n   ArchiveApi getArchiveApi();\n\n   /**\n    * Provides synchronous access to DNS features.\n    */\n   @Delegate\n   DomainApi getDomainApi();\n\n   /**\n    * Provides synchronous access to E-Mail features.\n    */\n   @Delegate\n   EmailAccountApi getEmailAccountApi();\n\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/GleSYSApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys;\n\nimport static org.jclouds.reflect.Reflection2.typeToken;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.glesys.compute.config.GleSYSComputeServiceContextModule;\nimport org.jclouds.glesys.config.GleSYSHttpApiModule;\nimport org.jclouds.rest.internal.BaseHttpApiMetadata;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n/**\n * Implementation of {@link ApiMetadata} for  API\n */\npublic class GleSYSApiMetadata extends BaseHttpApiMetadata {\n\n   @Override\n   public Builder toBuilder() {\n      return new Builder().fromApiMetadata(this);\n   }\n\n   public GleSYSApiMetadata() {\n      this(new Builder());\n   }\n\n   protected GleSYSApiMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = BaseHttpApiMetadata.defaultProperties();\n      properties.setProperty(\"jclouds.ssh.max-retries\", \"5\");\n      properties.setProperty(\"jclouds.ssh.retry-auth\", \"true\");\n      return properties;\n   }\n\n   public static class Builder extends BaseHttpApiMetadata.Builder<GleSYSApi, Builder> {\n\n      @SuppressWarnings(\"deprecation\")\n      protected Builder() {\n         id(\"glesys\")\n         .name(\"GleSYS API\")\n         .identityName(\"Username\")\n         .credentialName(\"API Key\")\n         .documentation(URI.create(\"https://customer.glesys.com/api.php\"))\n         .version(\"1\")\n         .buildVersion(\"3.5.0\")\n         .defaultEndpoint(\"https://api.glesys.com\")\n         .defaultProperties(GleSYSApiMetadata.defaultProperties())\n         .view(typeToken(ComputeServiceContext.class))\n         .defaultModules(ImmutableSet.<Class<? extends Module>>of(GleSYSComputeServiceContextModule.class, GleSYSHttpApiModule.class));\n      }\n\n      @Override\n      public GleSYSApiMetadata build() {\n         return new GleSYSApiMetadata(this);\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/GleSYSProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys;\n\nimport static org.jclouds.compute.config.ComputeServiceProperties.TEMPLATE;\nimport static org.jclouds.location.reference.LocationConstants.ISO3166_CODES;\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_ZONE;\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_ZONES;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\n\nimport com.google.auto.service.AutoService;\n\n/**\n * Implementation of {@link ProviderMetadata} for GleSYS.\n */\n@AutoService(ProviderMetadata.class)\npublic class GleSYSProviderMetadata extends BaseProviderMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromProviderMetadata(this);\n   }\n\n   public GleSYSProviderMetadata() {\n      super(builder());\n   }\n\n   public GleSYSProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = new Properties();\n      properties.setProperty(PROPERTY_ZONES, \"Amsterdam,Falkenberg,New York City,Stockholm\");\n      properties.setProperty(PROPERTY_ZONE + \".Amsterdam.\" + ISO3166_CODES, \"NL-NH\");\n      properties.setProperty(PROPERTY_ZONE + \".Falkenberg.\" + ISO3166_CODES, \"SE-N\");\n      properties.setProperty(PROPERTY_ZONE + \".New York City.\" + ISO3166_CODES, \"US-NY\");\n      properties.setProperty(PROPERTY_ZONE + \".Stockholm.\" + ISO3166_CODES, \"SE-AB\");\n      properties.setProperty(TEMPLATE, \"osFamily=UBUNTU,osVersionMatches=1[012].[01][04],os64Bit=true,minRam=768\");\n      return properties;\n   }\n\n   public static class Builder extends BaseProviderMetadata.Builder {\n\n      protected Builder() {\n         id(\"glesys\")\n         .name(\"GleSYS\")\n         .apiMetadata(new GleSYSApiMetadata())\n         .homepage(URI.create(\"http://www.glesys.com\"))\n         .console(URI.create(\"https://customer.glesys.com/cloud.php\"))\n         .iso3166Codes(\"NL-NH\", \"SE-N\", \"US-NY\", \"SE-AB\")\n         .endpoint(\"https://api.glesys.com\")\n         .defaultProperties(GleSYSProviderMetadata.defaultProperties());\n      }\n\n      @Override\n      public GleSYSProviderMetadata build() {\n         return new GleSYSProviderMetadata(this);\n      }\n\n      @Override\n      public Builder fromProviderMetadata(ProviderMetadata in) {\n         super.fromProviderMetadata(in);\n         return this;\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/compute/GleSYSComputeServiceAdapter.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.compute;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.contains;\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.find;\nimport static com.google.common.io.BaseEncoding.base16;\nimport static org.jclouds.compute.util.ComputeServiceUtils.metadataAndTagsAsCommaDelimitedValue;\nimport static org.jclouds.util.Predicates2.retry;\n\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.Set;\nimport java.util.UUID;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Constants;\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.ComputeServiceAdapter;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.HardwareBuilder;\nimport org.jclouds.compute.domain.Processor;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.domain.Volume;\nimport org.jclouds.compute.domain.internal.VolumeImpl;\nimport org.jclouds.compute.predicates.ImagePredicates;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.compute.reference.ComputeServiceConstants.Timeouts;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.glesys.GleSYSApi;\nimport org.jclouds.glesys.compute.options.GleSYSTemplateOptions;\nimport org.jclouds.glesys.domain.AllowedArgumentsForCreateServer;\nimport org.jclouds.glesys.domain.OSTemplate;\nimport org.jclouds.glesys.domain.Server;\nimport org.jclouds.glesys.domain.ServerDetails;\nimport org.jclouds.glesys.domain.ServerSpec;\nimport org.jclouds.glesys.options.CreateServerOptions;\nimport org.jclouds.glesys.options.DestroyServerOptions;\nimport org.jclouds.location.predicates.LocationPredicates;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Joiner;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.util.concurrent.ListeningExecutorService;\n\n/**\n * defines the connection between the {@link GleSYSApi} implementation and\n * the jclouds {@link ComputeService}\n */\n@Singleton\npublic class GleSYSComputeServiceAdapter implements ComputeServiceAdapter<ServerDetails, Hardware, OSTemplate, String> {\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   private final GleSYSApi api;\n   private final ListeningExecutorService userExecutor;\n   private final Timeouts timeouts;\n   private final Supplier<Set<? extends Location>> locations;\n\n   @Inject\n   public GleSYSComputeServiceAdapter(GleSYSApi api,\n         @Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor, Timeouts timeouts,\n         @Memoized Supplier<Set<? extends Location>> locations) {\n      this.api = checkNotNull(api, \"api\");\n      this.userExecutor = checkNotNull(userExecutor, \"userExecutor\");\n      this.timeouts = checkNotNull(timeouts, \"timeouts\");\n      this.locations = checkNotNull(locations, \"locations\");\n   }\n\n   @Override\n   public NodeAndInitialCredentials<ServerDetails> createNodeWithGroupEncodedIntoName(String group, String name,\n         Template template) {\n      checkNotNull(template, \"template was null\");\n      checkNotNull(template.getOptions(), \"template options was null\");\n      checkArgument(template.getOptions().getClass().isAssignableFrom(GleSYSTemplateOptions.class),\n            \"options class %s should have been assignable from GleSYSTemplateOptions\", template.getOptions().getClass());\n\n      GleSYSTemplateOptions templateOptions = template.getOptions().as(GleSYSTemplateOptions.class);\n\n      CreateServerOptions createServerOptions = new CreateServerOptions();\n      createServerOptions.ip(templateOptions.getIp());\n      template.getOptions().userMetadata(ComputeServiceConstants.NODE_GROUP_KEY, group);\n\n      Map<String, String> md = metadataAndTagsAsCommaDelimitedValue(template.getOptions());\n      if (!md.isEmpty()) {\n         String description = Joiner.on('\\n').withKeyValueSeparator(\"=\").join(md);\n         // TODO: get glesys to stop stripping out equals and commas!\n         createServerOptions.description(base16().lowerCase().encode(description.getBytes(UTF_8)));\n      }\n      ServerSpec.Builder<?> builder = ServerSpec.builder();\n      builder.datacenter(template.getLocation().getId());\n      builder.templateName(template.getImage().getId());\n      builder.platform(template.getHardware().getHypervisor());\n      builder.memorySizeMB(template.getHardware().getRam());\n      builder.diskSizeGB(Math.round(template.getHardware().getVolumes().get(0).getSize()));\n      builder.cpuCores((int) template.getHardware().getProcessors().get(0).getCores());\n      builder.transferGB(templateOptions.getTransferGB());\n      ServerSpec spec = builder.build();\n\n\n      // use random root password unless one was provided via template options\n      String password = templateOptions.hasRootPassword() ? templateOptions.getRootPassword() : getRandomPassword();\n\n      logger.debug(\">> creating new Server spec(%s) name(%s) options(%s)\", spec, name, createServerOptions);\n      ServerDetails result = api.getServerApi().createWithHostnameAndRootPassword(spec, name, password,\n            createServerOptions);\n      logger.trace(\"<< server(%s)\", result.getId());\n\n      return new NodeAndInitialCredentials<ServerDetails>(result, result.getId() + \"\", LoginCredentials.builder()\n            .password(password).build());\n   }\n\n   /**\n    * @return a generated random password string\n    */\n   private String getRandomPassword() {\n      return UUID.randomUUID().toString().replace(\"-\", \"\");\n   }\n\n   @Override\n   public Iterable<Hardware> listHardwareProfiles() {\n      Set<? extends Location> locationsSet = locations.get();\n      ImmutableSet.Builder<Hardware> hardwareToReturn = ImmutableSet.builder();\n\n      // do this loop after dupes are filtered, else OOM\n      Set<OSTemplate> images = listImages();\n\n      for (Entry<String, AllowedArgumentsForCreateServer> platformToArgs : api.getServerApi()\n            .getAllowedArgumentsForCreateByPlatform().entrySet())\n         for (String datacenter : platformToArgs.getValue().getDataCenters())\n            for (int diskSizeGB : platformToArgs.getValue().getDiskSizesInGB().getAllowedUnits())\n               for (int cpuCores : platformToArgs.getValue().getCpuCoreOptions().getAllowedUnits())\n                  for (int memorySizeMB : platformToArgs.getValue().getMemorySizesInMB().getAllowedUnits()) {\n                     ImmutableSet.Builder<String> templatesSupportedBuilder = ImmutableSet.builder();\n                     for (OSTemplate template : images) {\n                        if (template.getPlatform().equals(platformToArgs.getKey())\n                              && diskSizeGB >= template.getMinDiskSize() && memorySizeMB >= template.getMinMemSize())\n                           templatesSupportedBuilder.add(template.getName());\n                     }\n                     ImmutableSet<String> templatesSupported = templatesSupportedBuilder.build();\n                     if (!templatesSupported.isEmpty())\n                        hardwareToReturn.add(new HardwareBuilder()\n                              .ids(String.format(\n                                    \"datacenter(%s)platform(%s)cpuCores(%d)memorySizeMB(%d)diskSizeGB(%d)\", datacenter,\n                                    platformToArgs.getKey(), cpuCores, memorySizeMB, diskSizeGB)).ram(memorySizeMB)\n                              .processors(ImmutableList.of(new Processor(cpuCores, 1.0)))\n                              .volumes(ImmutableList.<Volume> of(new VolumeImpl((float) diskSizeGB, true, true)))\n                              .hypervisor(platformToArgs.getKey())\n                              .location(find(locationsSet, LocationPredicates.idEquals(datacenter)))\n                              .supportsImage(ImagePredicates.idIn(templatesSupported)).build());\n                  }\n\n      return hardwareToReturn.build();\n   }\n\n   @Override\n   public Set<OSTemplate> listImages() {\n      return api.getServerApi().listTemplates().toSet();\n   }\n\n   // cheat until we have a getTemplate command\n   @Override\n   public OSTemplate getImage(final String id) {\n      return find(listImages(), new Predicate<OSTemplate>() {\n\n         @Override\n         public boolean apply(OSTemplate input) {\n            return input.getName().equals(id);\n         }\n\n      }, null);\n   }\n\n   @Override\n   public Iterable<ServerDetails> listNodes() {\n      return api.getServerApi().list().transform(new Function<Server, ServerDetails>() {\n         public ServerDetails apply(Server from) {\n            return api.getServerApi().get(from.getId());\n         }\n      });\n   }\n\n   @Override\n   public Iterable<ServerDetails> listNodesByIds(final Iterable<String> ids) {\n      return filter(listNodes(), new Predicate<ServerDetails>() {\n\n            @Override\n            public boolean apply(ServerDetails server) {\n               return contains(ids, server.getId());\n            }\n         });\n   }\n\n   @Override\n   public Set<String> listLocations() {\n      return FluentIterable.from(api.getServerApi().getAllowedArgumentsForCreateByPlatform().values())\n            .transformAndConcat(new Function<AllowedArgumentsForCreateServer, Set<String>>() {\n               @Override\n               public Set<String> apply(AllowedArgumentsForCreateServer arg0) {\n                  return arg0.getDataCenters();\n               }\n            }).toSet();\n   }\n\n   @Override\n   public ServerDetails getNode(String id) {\n      return api.getServerApi().get(id);\n   }\n\n   @Override\n   public void destroyNode(String id) {\n      retry(new Predicate<String>() {\n         public boolean apply(String arg0) {\n            try {\n               api.getServerApi().destroy(arg0, DestroyServerOptions.Builder.discardIp());\n               return true;\n            } catch (IllegalStateException e) {\n               return false;\n            }\n         }\n      }, timeouts.nodeTerminated).apply(id);\n   }\n\n   @Override\n   public void rebootNode(String id) {\n      api.getServerApi().reboot(id);\n   }\n\n   @Override\n   public void resumeNode(String id) {\n      api.getServerApi().start(id);\n   }\n\n   @Override\n   public void suspendNode(String id) {\n      api.getServerApi().stop(id);\n   }\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/compute/config/GleSYSComputeServiceContextModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.compute.config;\n\nimport org.jclouds.compute.ComputeServiceAdapter;\nimport org.jclouds.compute.config.ComputeServiceAdapterContextModule;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.OsFamilyVersion64Bit;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.domain.Location;\nimport org.jclouds.functions.IdentityFunction;\nimport org.jclouds.glesys.compute.GleSYSComputeServiceAdapter;\nimport org.jclouds.glesys.compute.functions.DatacenterToLocation;\nimport org.jclouds.glesys.compute.functions.OSTemplateToImage;\nimport org.jclouds.glesys.compute.functions.ParseOsFamilyVersion64BitFromImageName;\nimport org.jclouds.glesys.compute.functions.ServerDetailsToNodeMetadata;\nimport org.jclouds.glesys.compute.options.GleSYSTemplateOptions;\nimport org.jclouds.glesys.domain.OSTemplate;\nimport org.jclouds.glesys.domain.ServerDetails;\n\nimport com.google.common.base.Function;\nimport com.google.inject.TypeLiteral;\n\npublic class GleSYSComputeServiceContextModule extends\n         ComputeServiceAdapterContextModule<ServerDetails, Hardware, OSTemplate, String> {\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   protected void configure() {\n      super.configure();\n      bind(new TypeLiteral<ComputeServiceAdapter<ServerDetails, Hardware, OSTemplate, String>>() {\n      }).to(GleSYSComputeServiceAdapter.class);\n      bind(new TypeLiteral<Function<ServerDetails, NodeMetadata>>() {\n      }).to(ServerDetailsToNodeMetadata.class);\n      bind(new TypeLiteral<Function<OSTemplate, org.jclouds.compute.domain.Image>>() {\n      }).to(OSTemplateToImage.class);\n      bind(new TypeLiteral<Function<Hardware, Hardware>>() {\n      }).to(Class.class.cast(IdentityFunction.class));\n      bind(new TypeLiteral<Function<String, Location>>() {\n      }).to(DatacenterToLocation.class);\n      bind(new TypeLiteral<Function<String, OsFamilyVersion64Bit>>() {\n      }).to(ParseOsFamilyVersion64BitFromImageName.class);\n      bind(TemplateOptions.class).to(GleSYSTemplateOptions.class);\n      install(new LocationsFromComputeServiceAdapterModule<ServerDetails, Hardware, OSTemplate, String>(){});\n   }\n\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/compute/functions/DatacenterToLocation.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.compute.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.location.suppliers.all.JustProvider;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.Iterables;\n\n/**\n * Converts an ServerSpec into a Location.\n */\npublic class DatacenterToLocation implements Function<String, Location> {\n   private final JustProvider provider;\n\n   // allow us to lazy discover the provider of a resource\n   @Inject\n   public DatacenterToLocation(JustProvider provider) {\n      this.provider = checkNotNull(provider, \"provider\");\n   }\n\n   @Override\n   public Location apply(String datacenter) {\n      return new LocationBuilder().scope(LocationScope.ZONE).description(datacenter).id(datacenter)\n      // TODO: iso3166Codes\n               .parent(Iterables.getOnlyElement(provider.get())).build();\n   }\n\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/compute/functions/OSTemplateToImage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.compute.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.Image.Status;\nimport org.jclouds.compute.domain.ImageBuilder;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.OperatingSystem.Builder;\nimport org.jclouds.compute.domain.OsFamilyVersion64Bit;\nimport org.jclouds.glesys.domain.OSTemplate;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class OSTemplateToImage implements Function<OSTemplate, Image> {\n   private final Function<String, OsFamilyVersion64Bit> osParser;\n\n   @Inject\n   public OSTemplateToImage(Function<String, OsFamilyVersion64Bit> osParser) {\n      this.osParser = osParser;\n   }\n\n   @Override\n   public Image apply(OSTemplate template) {\n      checkNotNull(template, \"template\");\n      OsFamilyVersion64Bit parsed = osParser.apply(template.getName());\n      Builder builder = OperatingSystem.builder();\n      builder.name(template.getName()).description(template.getName()).is64Bit(parsed.is64Bit).version(parsed.version)\n               .family(parsed.family);\n      return new ImageBuilder().ids(template.getName()).name(template.getName()).description(template.getName())\n            .operatingSystem(builder.build()).status(Status.AVAILABLE).build();\n   }\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/compute/functions/ParseOsFamilyVersion64BitFromImageName.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.compute.functions;\n\nimport static com.google.common.base.Predicates.containsPattern;\n\nimport java.util.Map;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.OsFamilyVersion64Bit;\nimport org.jclouds.compute.util.ComputeServiceUtils;\n\nimport com.google.common.base.Function;\n\n/**\n * Defaults to version null and 64bit, if the operating system is unrecognized\n * and the pattern \"32bit\" isn't in the string.\n */\n@Singleton\npublic class ParseOsFamilyVersion64BitFromImageName implements Function<String, OsFamilyVersion64Bit> {\n   private final Map<OsFamily, Map<String, String>> osVersionMap;\n\n   @Inject\n   public ParseOsFamilyVersion64BitFromImageName(Map<OsFamily, Map<String, String>> osVersionMap) {\n      this.osVersionMap = osVersionMap;\n   }\n\n   // ex Debian 6.0 64-bit\n   // ex. Ubuntu 10.04 LTS 32-bit\n   public static final Pattern OSFAMILY_VERSION = Pattern\n         .compile(\"([^ ]+).*[ -]([0-9.]+)( LTS)?( [36][24]-bit)?( x[68][46])?$\");\n   public static final Pattern OSFAMILY = Pattern.compile(\"([^ ]+).*$\");\n\n   @Override\n   public OsFamilyVersion64Bit apply(String input) {\n      boolean is64Bit = containsPattern(\"64\").apply(input);\n      String version = \"\";\n\n      if (input.indexOf(\"Windows\") != -1) {\n         Matcher matcher = Pattern.compile(\".*(20[01][0-9] R[1-9]).*\").matcher(input);\n         if (matcher.find()) {\n            version = matcher.group(1);\n         } else {\n            matcher = Pattern.compile(\".*(20[01][0-9]).*\").matcher(input);\n            if (matcher.find())\n               version = matcher.group(1);\n         }\n         return new OsFamilyVersion64Bit(OsFamily.WINDOWS, osVersionMap.get(OsFamily.WINDOWS).get(version), is64Bit);\n      }\n      Matcher osFamilyVersionMatcher = OSFAMILY_VERSION.matcher(input);\n      if (osFamilyVersionMatcher.find()) {\n         OsFamily fam = OsFamily.fromValue(osFamilyVersionMatcher.group(1).toLowerCase());\n         if (fam == OsFamily.UNRECOGNIZED ) {\n            return new OsFamilyVersion64Bit(OsFamily.UNRECOGNIZED, version, is64Bit);\n         }\n         return new OsFamilyVersion64Bit(fam, ComputeServiceUtils.parseVersionOrReturnEmptyString(fam,\n               osFamilyVersionMatcher.group(2), osVersionMap), is64Bit);\n      } else {\n         Matcher osFamilyMatcher = OSFAMILY.matcher(input);\n         OsFamily fam = OsFamily.UNRECOGNIZED;\n         if (osFamilyMatcher.find()) {\n            fam = OsFamily.fromValue(osFamilyMatcher.group(1).toLowerCase());\n         }\n         return new OsFamilyVersion64Bit(fam, version, is64Bit);\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/compute/functions/ServerDetailsToNodeMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.compute.functions;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.common.base.Strings.isNullOrEmpty;\nimport static com.google.common.io.BaseEncoding.base16;\nimport static org.jclouds.compute.util.ComputeServiceUtils.addMetadataAndParseTagsFromCommaDelimitedValue;\nimport static org.jclouds.compute.util.ComputeServiceUtils.groupFromMapOrName;\nimport static org.jclouds.location.predicates.LocationPredicates.idEquals;\n\nimport java.util.Map;\nimport java.util.NoSuchElementException;\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.domain.HardwareBuilder;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadata.Status;\nimport org.jclouds.compute.domain.NodeMetadataBuilder;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.Processor;\nimport org.jclouds.compute.domain.Volume;\nimport org.jclouds.compute.domain.internal.VolumeImpl;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.domain.Location;\nimport org.jclouds.glesys.domain.Ip;\nimport org.jclouds.glesys.domain.ServerDetails;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.util.InetAddresses2.IsPrivateIPAddress;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Predicates;\nimport com.google.common.base.Splitter;\nimport com.google.common.base.Strings;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\n\n@Singleton\npublic class ServerDetailsToNodeMetadata implements Function<ServerDetails, NodeMetadata> {\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n   public static final Map<ServerDetails.State, Status> serverStateToNodeStatus = ImmutableMap\n         .<ServerDetails.State, Status> builder().put(ServerDetails.State.STOPPED, Status.SUSPENDED)\n         .put(ServerDetails.State.LOCKED, Status.PENDING)\n         .put(ServerDetails.State.RUNNING, Status.RUNNING)\n         .put(ServerDetails.State.UNRECOGNIZED, Status.UNRECOGNIZED).build();\n\n   protected final Supplier<Set<? extends Image>> images;\n   protected final Supplier<Set<? extends Location>> locations;\n   protected final GroupNamingConvention nodeNamingConvention;\n\n   private static class FindImageForServer implements Predicate<Image> {\n      private final ServerDetails instance;\n\n      private FindImageForServer(ServerDetails instance) {\n         this.instance = instance;\n      }\n\n      @Override\n      public boolean apply(Image input) {\n         return input.getProviderId().equals(instance.getTemplateName());\n      }\n   }\n\n   @Inject\n   ServerDetailsToNodeMetadata(@Memoized Supplier<Set<? extends Location>> locations,\n         @Memoized Supplier<Set<? extends Image>> images, GroupNamingConvention.Factory namingConvention) {\n      this.nodeNamingConvention = checkNotNull(namingConvention, \"namingConvention\").createWithoutPrefix();\n      this.locations = checkNotNull(locations, \"locations\");\n      this.images = checkNotNull(images, \"images\");\n   }\n\n   @Override\n   public NodeMetadata apply(ServerDetails from) {\n      NodeMetadataBuilder builder = new NodeMetadataBuilder();\n      builder.ids(from.getId() + \"\");\n      builder.name(from.getHostname());\n      builder.hostname(from.getHostname());\n      Location location = FluentIterable.from(locations.get()).firstMatch(idEquals(from.getDatacenter())).orNull();\n      checkState(location != null, \"no location matched ServerDetails %s\", from);\n\n      Map<String, String> metadataMap;\n\n      // TODO: get glesys to stop stripping out equals and commas!\n      if (!isNullOrEmpty(from.getDescription()) && from.getDescription().matches(\"^[0-9A-Fa-f]+$\")) {\n         String decoded = new String(base16().lowerCase().decode(from.getDescription()), UTF_8);\n         metadataMap = Splitter.on('\\n').withKeyValueSeparator(\"=\").split(decoded);\n         addMetadataAndParseTagsFromCommaDelimitedValue(builder, metadataMap);\n      } else {\n         metadataMap = ImmutableMap.of();\n      }\n      builder.group(groupFromMapOrName(metadataMap, from.getHostname(), nodeNamingConvention));\n      builder.imageId(from.getTemplateName() + \"\");\n      builder.operatingSystem(parseOperatingSystem(from));\n      builder.hardware(new HardwareBuilder().ids(from.getId() + \"\").ram(from.getMemorySizeMB())\n            .processors(ImmutableList.of(new Processor(from.getCpuCores(), 1.0)))\n            .volumes(ImmutableList.<Volume> of(new VolumeImpl((float) from.getDiskSizeGB(), true, true)))\n            .hypervisor(from.getPlatform()).build());\n      builder.status(serverStateToNodeStatus.get(from.getState()));\n      Iterable<String> addresses = Iterables.filter(Iterables.transform(from.getIps(), new Function<Ip, String>() {\n\n         @Override\n         public String apply(Ip arg0) {\n            return Strings.emptyToNull(arg0.getIp());\n         }\n\n      }), Predicates.notNull());\n      builder.publicAddresses(Iterables.filter(addresses, Predicates.not(IsPrivateIPAddress.INSTANCE)));\n      builder.privateAddresses(Iterables.filter(addresses, IsPrivateIPAddress.INSTANCE));\n      return builder.build();\n   }\n\n   protected OperatingSystem parseOperatingSystem(ServerDetails from) {\n      try {\n         return Iterables.find(images.get(), new FindImageForServer(from)).getOperatingSystem();\n      } catch (NoSuchElementException e) {\n         logger.debug(\"could not find a matching image for server %s\", from);\n      }\n      return null;\n   }\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/compute/functions/ServerSpecToHardware.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.compute.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.location.predicates.LocationPredicates.idEquals;\n\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.HardwareBuilder;\nimport org.jclouds.compute.domain.Processor;\nimport org.jclouds.compute.domain.Volume;\nimport org.jclouds.compute.domain.internal.VolumeImpl;\nimport org.jclouds.compute.predicates.ImagePredicates;\nimport org.jclouds.domain.Location;\nimport org.jclouds.glesys.domain.ServerSpec;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableList;\n\n@Singleton\npublic class ServerSpecToHardware implements Function<ServerSpec, Hardware> {\n\n   private final Supplier<Set<? extends Location>> locations;\n\n   @Inject\n   ServerSpecToHardware(@Memoized Supplier<Set<? extends Location>> locations) {\n      this.locations = checkNotNull(locations, \"locations\");\n   }\n\n   @Override\n   public Hardware apply(ServerSpec spec) {\n      Location location = FluentIterable.from(locations.get()).firstMatch(idEquals(spec.getDatacenter())).orNull();\n      assert location != null : String.format(\"no location matched ServerSpec %s\", spec);\n      return new HardwareBuilder().ids(spec.toString()).ram(spec.getMemorySizeMB()).processors(\n               ImmutableList.of(new Processor(spec.getCpuCores(), 1.0))).volumes(\n               ImmutableList.<Volume> of(new VolumeImpl((float) spec.getDiskSizeGB(), true, true))).hypervisor(\n               spec.getPlatform()).location(location).supportsImage(\n               ImagePredicates.idEquals(spec.getTemplateName())).build();\n   }\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/compute/options/GleSYSTemplateOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.compute.options;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\n\nimport org.jclouds.compute.options.TemplateOptions;\n\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.net.InetAddresses;\n\n/**\n * Contains options supported by the\n * {@link ComputeService#createNodesInGroup(String, int, TemplateOptions)} and\n * {@link ComputeService#createNodesInGroup(String, int, TemplateOptions)}\n * operations on the <em>glesys</em> provider.\n * \n * <h2>Usage</h2> The recommended way to instantiate a\n * {@link GleSYSTemplateOptions} object is to statically import\n * {@code GleSYSTemplateOptions.*} and invoke a static creation method followed\n * by an instance mutator (if needed):\n * <p>\n * \n * <pre>\n * import static org.jclouds.compute.options.GleSYSTemplateOptions.Builder.*;\n * ComputeService api = // get connection\n * templateBuilder.options(rootPassword(\"caQu5rou\"));\n * Set&lt;? extends NodeMetadata&gt; set = api.createNodesInGroup(tag, 2, templateBuilder.build());\n * </pre>\n */\npublic class GleSYSTemplateOptions extends TemplateOptions implements Cloneable {\n\n   /**\n    * The IP address to assign to the new node instance. If set to \"\n    * <code>any</code>\" the node will be automatically assigned a free IP\n    * address.\n    */\n   protected String ip = \"any\";\n   /**\n    * The password to set for the root user on the created server instance. If\n    * left unspecified, a random password will be assigned.\n    */\n   protected String rootPassword = null;\n\n   /** The monthly data transfer limit (in GB) for the server. */\n   protected int transferGB = 50;\n\n   @Override\n   public GleSYSTemplateOptions clone() {\n      GleSYSTemplateOptions options = new GleSYSTemplateOptions();\n      copyTo(options);\n      return options;\n   }\n\n   @Override\n   public void copyTo(TemplateOptions to) {\n      super.copyTo(to);\n      if (to instanceof GleSYSTemplateOptions) {\n         GleSYSTemplateOptions copy = GleSYSTemplateOptions.class.cast(to);\n         copy.ip(ip);\n         copy.rootPassword(rootPassword);\n         copy.transferGB(transferGB);\n      }\n   }\n\n   /**\n    * Sets the IP address to assign to the new server instance. If set to \"\n    * <code>any</code>\" the server will be automatically assigned a free IP\n    * address.\n    * \n    * @see ServerApi#createWithHostnameAndRootPassword\n    * @see InetAddresses#isInetAddress\n    */\n   public GleSYSTemplateOptions ip(String ip) {\n      checkNotNull(ip);\n      checkArgument(\"any\".equals(ip) || InetAddresses.isInetAddress(ip), \"ip %s is not valid\", ip);      \n      this.ip = ip;\n      return this;\n   }\n\n   /**\n    * @return the IP address to assign to the new server instance.\n    */\n   public String getIp() {\n      return ip;\n   }\n\n   /**\n    * Sets the password for the root user on the created server instance. If\n    * left unspecified, a random password will be assigned.\n    * \n    * @see ServerApi#createWithHostnameAndRootPassword\n    */\n   public GleSYSTemplateOptions rootPassword(String rootPassword) {\n      checkNotNull(rootPassword, \"root password cannot be null\");\n      this.rootPassword = rootPassword;\n      return this;\n   }\n\n   /**\n    * @return the password set for the root user or <code>null</code> if none is\n    *         set (and a random password will be assigned).\n    */\n   public String getRootPassword() {\n      return rootPassword;\n   }\n\n   /**\n    * @return <code>true</code> if a root password has been specified.\n    */\n   public boolean hasRootPassword() {\n      return rootPassword != null;\n   }\n\n   /**\n    * Sets the monthly data transfer limit (in GB) for the server.\n    * \n    * @see ServerSpec#getTransferGB()\n    */\n   public GleSYSTemplateOptions transferGB(int transferGB) {\n      checkArgument(transferGB >= 0, \"transferGB value must be >= 0\", transferGB);\n      this.transferGB = transferGB;\n      return this;\n   }\n\n   /**\n    * @return the monthly data transfer limit (in GB) for the server.\n    */\n   public int getTransferGB() {\n      return transferGB;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see GleSYSTemplateOptions#ip\n       */\n      public static GleSYSTemplateOptions ip(String ip) {\n         GleSYSTemplateOptions options = new GleSYSTemplateOptions();\n         return GleSYSTemplateOptions.class.cast(options.ip(ip));\n      }\n\n      /**\n       * @see GleSYSTemplateOptions#rootPassword\n       */\n      public static GleSYSTemplateOptions rootPassword(String rootPassword) {\n         GleSYSTemplateOptions options = new GleSYSTemplateOptions();\n         return GleSYSTemplateOptions.class.cast(options.rootPassword(rootPassword));\n      }\n\n      /**\n       * @see GleSYSTemplateOptions#transferGB\n       */\n      public static GleSYSTemplateOptions transferGB(int transferGB) {\n         GleSYSTemplateOptions options = new GleSYSTemplateOptions();\n         return GleSYSTemplateOptions.class.cast(options.transferGB(transferGB));\n      }\n\n      // methods that only facilitate returning the correct object type\n\n      /**\n       * @see TemplateOptions#inboundPorts(int...)\n       */\n      public static GleSYSTemplateOptions inboundPorts(int... ports) {\n         GleSYSTemplateOptions options = new GleSYSTemplateOptions();\n         return GleSYSTemplateOptions.class.cast(options.inboundPorts(ports));\n      }\n\n      /**\n       * @see TemplateOptions#blockOnPort(int, int)\n       */\n      public static GleSYSTemplateOptions blockOnPort(int port, int seconds) {\n         GleSYSTemplateOptions options = new GleSYSTemplateOptions();\n         return GleSYSTemplateOptions.class.cast(options.blockOnPort(port, seconds));\n      }\n\n      /**\n       * @see TemplateOptions#userMetadata(Map)\n       */\n      public static GleSYSTemplateOptions userMetadata(Map<String, String> userMetadata) {\n         GleSYSTemplateOptions options = new GleSYSTemplateOptions();\n         return GleSYSTemplateOptions.class.cast(options.userMetadata(userMetadata));\n      }\n\n      /**\n       * @see TemplateOptions#userMetadata(String, String)\n       */\n      public static GleSYSTemplateOptions userMetadata(String key, String value) {\n         GleSYSTemplateOptions options = new GleSYSTemplateOptions();\n         return GleSYSTemplateOptions.class.cast(options.userMetadata(key, value));\n      }\n\n      /**\n       * @see TemplateOptions#nodeNames(Iterable)\n       */\n      public static GleSYSTemplateOptions nodeNames(Iterable<String> nodeNames) {\n         GleSYSTemplateOptions options = new GleSYSTemplateOptions();\n         return GleSYSTemplateOptions.class.cast(options.nodeNames(nodeNames));\n      }\n\n      /**\n       * @see TemplateOptions#networks(Iterable)\n       */\n      public static GleSYSTemplateOptions networks(Iterable<String> networks) {\n         GleSYSTemplateOptions options = new GleSYSTemplateOptions();\n         return GleSYSTemplateOptions.class.cast(options.networks(networks));\n      }\n   }\n\n   // methods that only facilitate returning the correct object type\n\n   /**\n    * @see TemplateOptions#blockOnPort(int, int)\n    */\n   @Override\n   public GleSYSTemplateOptions blockOnPort(int port, int seconds) {\n      return GleSYSTemplateOptions.class.cast(super.blockOnPort(port, seconds));\n   }\n\n   /**\n    * @see TemplateOptions#inboundPorts(int...)\n    */\n   @Override\n   public GleSYSTemplateOptions inboundPorts(int... ports) {\n      return GleSYSTemplateOptions.class.cast(super.inboundPorts(ports));\n   }\n\n   /**\n    * @see TemplateOptions#authorizePublicKey(String)\n    */\n   @Override\n   public GleSYSTemplateOptions authorizePublicKey(String publicKey) {\n      return GleSYSTemplateOptions.class.cast(super.authorizePublicKey(publicKey));\n   }\n\n   /**\n    * @see TemplateOptions#installPrivateKey(String)\n    */\n   @Override\n   public GleSYSTemplateOptions installPrivateKey(String privateKey) {\n      return GleSYSTemplateOptions.class.cast(super.installPrivateKey(privateKey));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public GleSYSTemplateOptions userMetadata(Map<String, String> userMetadata) {\n      return GleSYSTemplateOptions.class.cast(super.userMetadata(userMetadata));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public GleSYSTemplateOptions userMetadata(String key, String value) {\n      return GleSYSTemplateOptions.class.cast(super.userMetadata(key, value));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public GleSYSTemplateOptions nodeNames(Iterable<String> nodeNames) {\n      return GleSYSTemplateOptions.class.cast(super.nodeNames(nodeNames));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public GleSYSTemplateOptions networks(Iterable<String> networks) {\n      return GleSYSTemplateOptions.class.cast(super.networks(networks));\n   }\n\n   @Override\n   public ToStringHelper string() {\n      ToStringHelper stringHelper = super.string();\n\n      stringHelper.add(\"transferGB\", this.transferGB);\n      stringHelper.add(\"ip\", this.ip);\n      if (this.hasRootPassword()) {\n         stringHelper.add(\"rootPasswordPresent\", true);\n      }\n\n      return stringHelper;\n   }\n\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/config/GleSYSHttpApiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.config;\n\nimport org.jclouds.glesys.GleSYSApi;\nimport org.jclouds.glesys.handlers.GleSYSErrorHandler;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpRetryHandler;\nimport org.jclouds.http.annotation.ClientError;\nimport org.jclouds.http.annotation.Redirection;\nimport org.jclouds.http.annotation.ServerError;\nimport org.jclouds.http.handlers.BackoffLimitedRetryHandler;\nimport org.jclouds.location.suppliers.ImplicitLocationSupplier;\nimport org.jclouds.location.suppliers.implicit.OnlyLocationOrFirstZone;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.config.HttpApiModule;\n\nimport com.google.inject.Scopes;\n\n/**\n * Configures the GleSYS connection.\n */\n@ConfiguresHttpApi\npublic class GleSYSHttpApiModule extends HttpApiModule<GleSYSApi> {\n\n   @Override\n   protected void configure() {\n      install(new GleSYSParserModule());\n      super.configure();\n   }\n\n   @Override\n   protected void bindErrorHandlers() {\n      bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(GleSYSErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(GleSYSErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(GleSYSErrorHandler.class);\n   }\n\n   @Override\n   protected void bindRetryHandlers() {\n      bind(HttpRetryHandler.class).annotatedWith(ClientError.class).to(BackoffLimitedRetryHandler.class);\n   }\n   \n   @Override\n   protected void installLocations() {\n      super.installLocations();\n      bind(ImplicitLocationSupplier.class).to(OnlyLocationOrFirstZone.class).in(Scopes.SINGLETON);\n   }\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/config/GleSYSParserModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.config;\n\nimport java.lang.reflect.Type;\nimport java.util.Map;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.glesys.domain.GleSYSBoolean;\nimport org.jclouds.glesys.domain.Server;\nimport org.jclouds.glesys.functions.internal.GleSYSTypeAdapters;\nimport org.jclouds.json.config.GsonModule.DateAdapter;\nimport org.jclouds.json.config.GsonModule.Iso8601DateAdapter;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Provides;\n\npublic class GleSYSParserModule extends AbstractModule {\n\n   @Provides\n   @Singleton\n   public final Map<Type, Object> provideCustomAdapterBindings() {\n      return ImmutableMap.<Type, Object>of(Server.State.class, new GleSYSTypeAdapters.ServerStateAdapter(),\n                                           GleSYSBoolean.class, new GleSYSTypeAdapters.GleSYSBooleanAdapter());\n   }\n\n   @Override\n   protected void configure() {\n      bind(DateAdapter.class).to(Iso8601DateAdapter.class);\n   }\n\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/domain/AllowedArguments.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Set;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Represents the allowed arguments for a certain server resource type (such as\n * disksize, memorysize, cpucores, and transfer).\n * <p/>\n * This is a composite type consisting of both the set of allowed units for the\n * resource type as well as the cost per unit.\n * \n * @see AllowedArgumentsForCreateServer\n */\npublic class AllowedArguments {\n\tpublic static Builder builder() {\n\t\treturn new Builder();\n\t}\n\n\tpublic Builder toBuilder() {\n\t\treturn new Builder().fromAllowedArgument(this);\n\t}\n\n\tpublic static class Builder {\n\n\t\tprotected Cost costPerUnit;\n\t\tprotected Set<Integer> allowedUnits;\n\n\t\t/**\n\t\t * @see AllowedArguments#getCostPerUnit()\n\t\t */\n\t\tpublic Builder costPerUnit(Cost costPerUnit) {\n\t\t\tthis.costPerUnit = costPerUnit;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * @see AllowedArguments#getAllowedUnits()\n\t\t */\n\t\tpublic Builder allowedUnits(Set<Integer> allowedUnits) {\n\t\t\tthis.allowedUnits = ImmutableSet.copyOf(checkNotNull(allowedUnits,\n\t\t\t\t\t\"allowedUnits\"));\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic Builder allowedUnits(Integer... allowedUnits) {\n\t\t\treturn allowedUnits(ImmutableSet.copyOf(allowedUnits));\n\t\t}\n\n\t\tpublic AllowedArguments build() {\n\t\t\treturn new AllowedArguments(this.costPerUnit, this.allowedUnits);\n\t\t}\n\n\t\tpublic Builder fromAllowedArgument(AllowedArguments in) {\n\t\t\treturn this.costPerUnit(in.getCostPerUnit()).allowedUnits(\n\t\t\t\t\tin.getAllowedUnits());\n\t\t}\n\t}\n\n\tprivate final Cost costPerUnit;\n\tprivate final Set<Integer> allowedUnits;\n\n\t@ConstructorProperties({ \"costperunit\", \"units\" })\n\tprotected AllowedArguments(Cost costPerUnit, Set<Integer> units) {\n\t\tthis.costPerUnit = checkNotNull(costPerUnit, \"costPerUnit\");\n\t\tthis.allowedUnits = ImmutableSet.copyOf(checkNotNull(units,\n\t\t\t\t\"allowedUnits\"));\n\t}\n\n\t/**\n\t * @return the cost per unit.\n\t */\n\tpublic Cost getCostPerUnit() {\n\t\treturn this.costPerUnit;\n\t}\n\n\t/**\n\t * @return the set of allowed units for the resource type.\n\t */\n\tpublic Set<Integer> getAllowedUnits() {\n\t\treturn this.allowedUnits;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hashCode(this.costPerUnit, this.allowedUnits);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) {\n\t\t\treturn true;\n\t\t}\n\t\tif ((obj == null) || (getClass() != obj.getClass())) {\n\t\t\treturn false;\n\t\t}\n\t\tAllowedArguments that = AllowedArguments.class.cast(obj);\n\t\treturn Objects.equal(this.costPerUnit, that.costPerUnit)\n\t\t\t\t&& Objects.equal(this.allowedUnits, that.allowedUnits);\n\t}\n\n\tprotected ToStringHelper string() {\n\t\treturn MoreObjects.toStringHelper(\"\").add(\"costPerUnit\", this.costPerUnit)\n\t\t\t\t.add(\"allowedUnits\", this.allowedUnits);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn string().toString();\n\t}\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/domain/AllowedArgumentsForCreateServer.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Set;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Sets the allowed arguments for some of the functions in this module such as disksize, cpucores etc.\n *\n * @see <a href=\"https://customer.glesys.com/api.php?a=doc#server_allowedarguments\" />\n */\npublic class AllowedArgumentsForCreateServer {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return new Builder().fromAllowedArgumentsForCreateServer(this);\n   }\n\n   public static class Builder {\n      protected AllowedArguments diskSizes;\n      protected AllowedArguments memorySizes;\n      protected AllowedArguments cpuCores;\n      protected Set<String> templates = ImmutableSet.of();\n      protected AllowedArguments transfers;\n      protected Set<String> dataCenters = ImmutableSet.of();\n\n      /**\n       * @see AllowedArgumentsForCreateServer#getDiskSizesInGB()\n       */\n      public Builder diskSizes(AllowedArguments diskSizes) {\n         this.diskSizes = checkNotNull(diskSizes, \"diskSizesInGB\");\n         return this;\n      }\n\n\n      /**\n       * @see AllowedArgumentsForCreateServer#getMemorySizesInMB()\n       */\n      public Builder memorySizes(AllowedArguments memorySizes) {\n         this.memorySizes = checkNotNull(memorySizes, \"memorySizesInMB\");\n         return this;\n      }\n\n\n      /**\n       * @see AllowedArgumentsForCreateServer#getCpuCoreOptions()\n       */\n      public Builder cpuCores(AllowedArguments cpuCores) {\n         this.cpuCores = checkNotNull(cpuCores, \"cpuCoreOptions\");\n         return this;\n      }\n\n\n      /**\n       * @see AllowedArgumentsForCreateServer#getTemplateNames()\n       */\n      public Builder templates(Set<String> templates) {\n         this.templates = ImmutableSet.copyOf(checkNotNull(templates, \"templateNames\"));\n         return this;\n      }\n\n      public Builder templates(String... in) {\n         return templates(ImmutableSet.copyOf(in));\n      }\n\n      /**\n       * @see AllowedArgumentsForCreateServer#getTransfersInGB()\n       */\n      public Builder transfers(AllowedArguments transfers) {\n         this.transfers = checkNotNull(transfers, \"transfersInGB\");\n         return this;\n      }\n\n      /**\n       * @see AllowedArgumentsForCreateServer#getDataCenters()\n       */\n      public Builder dataCenters(Set<String> dataCenters) {\n         this.dataCenters = ImmutableSet.copyOf(checkNotNull(dataCenters, \"dataCenters\"));\n         return this;\n      }\n\n      public Builder dataCenters(String... in) {\n         return dataCenters(ImmutableSet.copyOf(in));\n      }\n\n      public AllowedArgumentsForCreateServer build() {\n         return new AllowedArgumentsForCreateServer(diskSizes, memorySizes, cpuCores, templates, transfers, dataCenters);\n      }\n\n      public Builder fromAllowedArgumentsForCreateServer(AllowedArgumentsForCreateServer in) {\n         return this\n               .diskSizes(in.getDiskSizesInGB())\n               .memorySizes(in.getMemorySizesInMB())\n               .cpuCores(in.getCpuCoreOptions())\n               .templates(in.getTemplateNames())\n               .transfers(in.getTransfersInGB())\n               .dataCenters(in.getDataCenters());\n      }\n   }\n\n   private final AllowedArguments diskSizesInGB;\n   private final AllowedArguments memorySizesInMB;\n   private final AllowedArguments cpuCoreOptions;\n   private final Set<String> templateNames;\n   private final AllowedArguments transfersInGB;\n   private final Set<String> dataCenters;\n\n   @ConstructorProperties({\n         \"disksize\", \"memorysize\", \"cpucores\", \"template\", \"transfer\", \"datacenter\"\n   })\n   protected AllowedArgumentsForCreateServer(AllowedArguments diskSizesInGB, AllowedArguments memorySizesInMB, AllowedArguments cpuCoreOptions, Set<String> templateNames, AllowedArguments transfersInGB, Set<String> dataCenters) {\n      this.diskSizesInGB = checkNotNull(diskSizesInGB, \"diskSizesInGB\");\n      this.memorySizesInMB = checkNotNull(memorySizesInMB, \"memorySizesInMB\");\n      this.cpuCoreOptions = checkNotNull(cpuCoreOptions, \"cpuCoreOptions\");\n      this.templateNames = ImmutableSet.copyOf(checkNotNull(templateNames, \"templateNames\"));\n      this.transfersInGB = checkNotNull(transfersInGB, \"transfersInGB\");\n      this.dataCenters = ImmutableSet.copyOf(checkNotNull(dataCenters, \"dataCenters\"));\n   }\n\n   /**\n    * @return a list of disk sizes, in GB, that can be used for creating servers on this platform\n    * @see org.jclouds.glesys.domain.OSTemplate#getMinDiskSize()\n    */\n   public AllowedArguments getDiskSizesInGB() {\n      return this.diskSizesInGB;\n   }\n\n   /**\n    * @return a list of memory sizes, in MB, that can be used for creating servers on this platform\n    * @see org.jclouds.glesys.domain.OSTemplate#getMinMemSize()\n    */\n   public AllowedArguments getMemorySizesInMB() {\n      return this.memorySizesInMB;\n   }\n\n   /**\n    * @return a list of which core counts can be used for creating servers on this platform\n    */\n   public AllowedArguments getCpuCoreOptions() {\n      return this.cpuCoreOptions;\n   }\n\n   /**\n    * @return a list of template names available for creating servers on this platform\n    * @see org.jclouds.glesys.domain.OSTemplate#getName()\n    */\n   public Set<String> getTemplateNames() {\n      return this.templateNames;\n   }\n\n   /**\n    * @return the list of transfer settings available for creating servers on this platform\n    */\n   public AllowedArguments getTransfersInGB() {\n      return this.transfersInGB;\n   }\n\n   /**\n    * @return the list of datacenters available that support creating servers on this platform\n    */\n   public Set<String> getDataCenters() {\n      return this.dataCenters;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(diskSizesInGB, memorySizesInMB, cpuCoreOptions, templateNames, transfersInGB, dataCenters);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      AllowedArgumentsForCreateServer that = AllowedArgumentsForCreateServer.class.cast(obj);\n      return Objects.equal(this.diskSizesInGB, that.diskSizesInGB)\n            && Objects.equal(this.memorySizesInMB, that.memorySizesInMB)\n            && Objects.equal(this.cpuCoreOptions, that.cpuCoreOptions)\n            && Objects.equal(this.templateNames, that.templateNames)\n            && Objects.equal(this.transfersInGB, that.transfersInGB)\n            && Objects.equal(this.dataCenters, that.dataCenters);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(\"\").add(\"diskSizesInGB\", diskSizesInGB).add(\"memorySizesInMB\", memorySizesInMB)\n            .add(\"cpuCoreOptions\", cpuCoreOptions).add(\"templateNames\", templateNames)\n            .add(\"transfersInGB\", transfersInGB).add(\"dataCenters\", dataCenters);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/domain/Archive.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Information about an archive\n *\n * @see <a href= \"https://customer.glesys.com/api.php?a=doc#archive_list\" />\n */\npublic class Archive {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromArchive(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String username;\n      protected String totalSize;\n      protected String freeSize;\n      protected boolean locked;\n\n      /**\n       * @see Archive#getUsername()\n       */\n      public T username(String username) {\n         this.username = checkNotNull(username, \"username\");\n         return self();\n      }\n\n      /**\n       * @see Archive#getTotalSize()\n       */\n      public T totalSize(String totalSize) {\n         this.totalSize = checkNotNull(totalSize, \"totalSize\");\n         return self();\n      }\n\n      /**\n       * @see Archive#getFreeSize()\n       */\n      public T freeSize(String freeSize) {\n         this.freeSize = checkNotNull(freeSize, \"freeSize\");\n         return self();\n      }\n\n      /**\n       * @see Archive#isLocked()\n       */\n      public T locked(boolean locked) {\n         this.locked = locked;\n         return self();\n      }\n\n      public Archive build() {\n         return new Archive(username, totalSize, freeSize, new GleSYSBoolean(locked));\n      }\n\n      public T fromArchive(Archive in) {\n         return this\n               .username(in.getUsername())\n               .totalSize(in.getTotalSize())\n               .freeSize(in.getFreeSize())\n               .locked(in.isLocked());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String username;\n   private final String totalSize;\n   private final String freeSize;\n   private final boolean locked;\n\n   @ConstructorProperties({\n         \"username\", \"sizetotal\", \"sizefree\", \"locked\"\n   })\n   protected Archive(String username, String totalSize, String freeSize, GleSYSBoolean locked) {\n      this.username = checkNotNull(username, \"username\");\n      this.totalSize = checkNotNull(totalSize, \"totalSize\");\n      this.freeSize = checkNotNull(freeSize, \"freeSize\");\n      this.locked = checkNotNull(locked, \"locked\").getValue();\n   }\n\n   /**\n    * @return the name (username) of the archive\n    */\n   public String getUsername() {\n      return this.username;\n   }\n\n   /**\n    * @return the total size of the archive, ex. \"10 GB\"\n    */\n   public String getTotalSize() {\n      return this.totalSize;\n   }\n\n   /**\n    * @return the free space left of the archive\n    */\n   public String getFreeSize() {\n      return this.freeSize;\n   }\n\n   /**\n    * @return true if the archive is locked\n    */\n   public boolean isLocked() {\n      return this.locked;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(username, totalSize, freeSize, locked);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Archive that = Archive.class.cast(obj);\n      return Objects.equal(this.username, that.username)\n            && Objects.equal(this.totalSize, that.totalSize)\n            && Objects.equal(this.freeSize, that.freeSize)\n            && Objects.equal(this.locked, that.locked);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(\"\")\n            .add(\"username\", username).add(\"totalSize\", totalSize).add(\"freeSize\", freeSize).add(\"locked\", locked);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/domain/ArchiveAllowedArguments.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.List;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableList;\n\n/**\n * The allowed arguments for archive manipulation, such as archivesize\n *\n * @see <a href= \"https://customer.glesys.com/api.php?a=doc#archive_allowedarguments\" />\n */\npublic class ArchiveAllowedArguments {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromArchiveAllowedArguments(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected List<Integer> archiveSizes = ImmutableList.of();\n\n      /**\n       * @see ArchiveAllowedArguments#getSizes()\n       */\n      public T archiveSizes(List<Integer> archiveSizes) {\n         this.archiveSizes = ImmutableList.copyOf(checkNotNull(archiveSizes, \"archiveSizes\"));\n         return self();\n      }\n\n      public T archiveSizes(Integer... in) {\n         return archiveSizes(ImmutableList.copyOf(in));\n      }\n\n      public ArchiveAllowedArguments build() {\n         return new ArchiveAllowedArguments(archiveSizes);\n      }\n\n      public T fromArchiveAllowedArguments(ArchiveAllowedArguments in) {\n         return this.archiveSizes(in.getSizes());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final List<Integer> archiveSizes;\n\n   @ConstructorProperties({\n         \"archivesize\"\n   })\n   protected ArchiveAllowedArguments(List<Integer> archiveSizes) {\n      this.archiveSizes = ImmutableList.copyOf(checkNotNull(archiveSizes, \"archiveSizes\"));\n   }\n\n   /**\n    * @return the list of allowed archive sizes, in GB\n    */\n   public List<Integer> getSizes() {\n      return this.archiveSizes;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(archiveSizes);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      ArchiveAllowedArguments that = ArchiveAllowedArguments.class.cast(obj);\n      return Objects.equal(this.archiveSizes, that.archiveSizes);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(\"\")\n            .add(\"archiveSizes\", archiveSizes);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/domain/Console.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Connection information to connect to a server with VNC.\n *\n * @see <a href=\"https://customer.glesys.com/api.php?a=doc#server_console\" />\n */\npublic class Console {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromConsole(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String host;\n      protected int port;\n      protected String protocol;\n      protected String password;\n\n      /**\n       * @see Console#getHost()\n       */\n      public T host(String host) {\n         this.host = checkNotNull(host, \"host\");\n         return self();\n      }\n\n      /**\n       * @see Console#getPort()\n       */\n      public T port(int port) {\n         this.port = port;\n         return self();\n      }\n\n      /**\n       * @see Console#getProtocol()\n       */\n      public T protocol(String protocol) {\n         this.protocol = checkNotNull(protocol, \"protocol\");\n         return self();\n      }\n\n      /**\n       * @see Console#getPassword()\n       */\n      public T password(String password) {\n         this.password = checkNotNull(password, \"password\");\n         return self();\n      }\n\n      public Console build() {\n         return new Console(host, port, protocol, password);\n      }\n\n      public T fromConsole(Console in) {\n         return this.host(in.getHost()).port(in.getPort()).protocol(in.getProtocol()).password(in.getPassword());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String host;\n   private final int port;\n   private final String protocol;\n   private final String password;\n\n   @ConstructorProperties({\n         \"host\", \"port\", \"protocol\", \"password\"\n   })\n   protected Console(String host, int port, String protocol, String password) {\n      this.host = checkNotNull(host, \"host\");\n      this.port = port;\n      this.protocol = checkNotNull(protocol, \"protocol\");\n      this.password = checkNotNull(password, \"password\");\n   }\n\n   /**\n    * @return the host name to use to connect to the server\n    */\n   public String getHost() {\n      return this.host;\n   }\n\n   /**\n    * @return the port to use to connect to the server\n    */\n   public int getPort() {\n      return this.port;\n   }\n\n   /**\n    * @return the protocol to use to connect to the server\n    */\n   public String getProtocol() {\n      return this.protocol;\n   }\n\n   /**\n    * @return the password to use to connect to the server\n    */\n   public String getPassword() {\n      return this.password;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(host, port, protocol);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Console that = Console.class.cast(obj);\n      return Objects.equal(this.host, that.host)\n            && Objects.equal(this.port, that.port)\n            && Objects.equal(this.protocol, that.protocol);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(\"\").add(\"host\", host).add(\"port\", port).add(\"protocol\", protocol)\n            .add(\"password\", password);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/domain/Cost.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * The Cost class contains information about the cost of a server\n *\n * @see ServerDetails\n */\npublic class Cost {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromCost(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected double amount;\n      protected String currency;\n      protected String timePeriod;\n\n      /**\n       * @see Cost#getAmount()\n       */\n      public T amount(double amount) {\n         this.amount = amount;\n         return self();\n      }\n\n      /**\n       * @see Cost#getCurrency()\n       */\n      public T currency(String currency) {\n         this.currency = checkNotNull(currency, \"currency\");\n         return self();\n      }\n\n      /**\n       * @see Cost#getTimePeriod()\n       */\n      public T timePeriod(String timePeriod) {\n         this.timePeriod = checkNotNull(timePeriod, \"timePeriod\");\n         return self();\n      }\n\n      public Cost build() {\n         return new Cost(amount, currency, timePeriod);\n      }\n\n      public T fromCost(Cost in) {\n         return this.amount(in.getAmount()).currency(in.getCurrency()).timePeriod(in.getTimePeriod());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final double amount;\n   private final String currency;\n   private final String timePeriod;\n\n   @ConstructorProperties({\n         \"amount\", \"currency\", \"timeperiod\"\n   })\n   protected Cost(double amount, String currency, String timePeriod) {\n      this.amount = amount;\n      this.currency = checkNotNull(currency, \"currency\");\n      this.timePeriod = checkNotNull(timePeriod, \"timePeriod\");\n   }\n\n   /**\n    * @return the numeric cost in #currency / #timePeriod\n    */\n   public double getAmount() {\n      return this.amount;\n   }\n\n   /**\n    * @return the currency unit, e.g. \"EUR\" for Euro\n    */\n   public String getCurrency() {\n      return this.currency;\n   }\n\n   /**\n    * @return the time period for which this cost charged, e.g. \"month\"\n    */\n   public String getTimePeriod() {\n      return this.timePeriod;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(amount, currency, timePeriod);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Cost that = Cost.class.cast(obj);\n      return Objects.equal(this.amount, that.amount)\n            && Objects.equal(this.currency, that.currency)\n            && Objects.equal(this.timePeriod, that.timePeriod);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(\"\")\n            .add(\"amount\", amount).add(\"currency\", currency).add(\"timePeriod\", timePeriod);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/domain/Domain.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Domain data for a Glesys account.\n *\n * @see <a href= \"https://customer.glesys.com/api.php?a=doc#domain_list\" />\n */\npublic class Domain {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromDomain(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String domainName;\n      protected Date createTime;\n      protected int recordCount;\n      protected boolean useGlesysNameServer;\n      protected String primaryNameServer;\n      protected String responsiblePerson;\n      protected int ttl;\n      protected int refresh;\n      protected int retry;\n      protected int expire;\n      protected int minimum;\n\n      /**\n       * @see Domain#getName()\n       */\n      public T domainName(String domainName) {\n         this.domainName = checkNotNull(domainName, \"domainName\");\n         return self();\n      }\n\n      /**\n       * @see Domain#getCreateTime()\n       */\n      public T createTime(Date createTime) {\n         this.createTime = createTime;\n         return self();\n      }\n\n      /**\n       * @see Domain#getRecordCount()\n       */\n      public T recordCount(int recordCount) {\n         this.recordCount = recordCount;\n         return self();\n      }\n\n      /**\n       * @see Domain#isUseGlesysNameServer()\n       */\n      public T useGlesysNameServer(boolean useGlesysNameServer) {\n         this.useGlesysNameServer = useGlesysNameServer;\n         return self();\n      }\n\n      /**\n       * @see Domain#getPrimaryNameServer()\n       */\n      public T primaryNameServer(String primaryNameServer) {\n         this.primaryNameServer = primaryNameServer;\n         return self();\n      }\n\n      /**\n       * @see Domain#getResponsiblePerson()\n       */\n      public T responsiblePerson(String responsiblePerson) {\n         this.responsiblePerson = responsiblePerson;\n         return self();\n      }\n\n      /**\n       * @see Domain#getTtl()\n       */\n      public T ttl(int ttl) {\n         this.ttl = ttl;\n         return self();\n      }\n\n      /**\n       * @see Domain#getRefresh()\n       */\n      public T refresh(int refresh) {\n         this.refresh = refresh;\n         return self();\n      }\n\n      /**\n       * @see Domain#getRetry()\n       */\n      public T retry(int retry) {\n         this.retry = retry;\n         return self();\n      }\n\n      /**\n       * @see Domain#getExpire()\n       */\n      public T expire(int expire) {\n         this.expire = expire;\n         return self();\n      }\n\n      /**\n       * @see Domain#getMinimum()\n       */\n      public T minimum(int minimum) {\n         this.minimum = minimum;\n         return self();\n      }\n\n      public Domain build() {\n         return new Domain(domainName, createTime, recordCount, new GleSYSBoolean(useGlesysNameServer), primaryNameServer, responsiblePerson, ttl, refresh, retry, expire, minimum);\n      }\n\n      public T fromDomain(Domain in) {\n         return this.domainName(in.getName())\n               .createTime(in.getCreateTime())\n               .recordCount(in.getRecordCount())\n               .useGlesysNameServer(in.isUseGlesysNameServer())\n               .primaryNameServer(in.getPrimaryNameServer())\n               .responsiblePerson(in.getResponsiblePerson())\n               .ttl(in.getTtl())\n               .refresh(in.getRefresh())\n               .retry(in.getRetry())\n               .expire(in.getExpire());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String domainName;\n   private final Date createTime;\n   private final int recordCount;\n   private final boolean useGlesysNameServer;\n   private final String primaryNameServer;\n   private final String responsiblePerson;\n   private final int ttl;\n   private final int refresh;\n   private final int retry;\n   private final int expire;\n   private final int minimum;\n\n   @ConstructorProperties({\n         \"domainname\", \"createtime\", \"recordcount\", \"usingglesysnameserver\", \"primarynameserver\", \"responsibleperson\",\n         \"ttl\", \"refresh\", \"retry\", \"expire\", \"minimum\"\n   })\n   protected Domain(String domainName, @Nullable Date createTime, int recordCount, GleSYSBoolean useGlesysNameServer,\n                    @Nullable String primaryNameServer, @Nullable String responsiblePerson,\n                    int ttl, int refresh, int retry, int expire, int minimum) {\n      this.domainName = checkNotNull(domainName, \"domainName\");\n      this.createTime = createTime;\n      this.recordCount = recordCount;\n      this.useGlesysNameServer = checkNotNull(useGlesysNameServer, \"useGlesysNameServer\").getValue();\n      this.primaryNameServer = primaryNameServer;\n      this.responsiblePerson = responsiblePerson;\n      this.ttl = ttl;\n      this.refresh = refresh;\n      this.retry = retry;\n      this.expire = expire;\n      this.minimum = minimum;\n   }\n\n   /**\n    * @return the domain name, ex. \"jclouds.org\"\n    */\n   public String getName() {\n      return this.domainName;\n   }\n\n   /**\n    * @return the date the domain was registered with GleSYS\n    */\n   public Date getCreateTime() {\n      return this.createTime;\n   }\n\n   /**\n    * @return the number of DNS records for this domain\n    */\n   public int getRecordCount() {\n      return this.recordCount;\n   }\n\n   /**\n    * @return true if a GleSYS nameserver holds the records\n    */\n   public boolean isUseGlesysNameServer() {\n      return this.useGlesysNameServer;\n   }\n\n   @Nullable\n   public String getPrimaryNameServer() {\n      return primaryNameServer;\n   }\n\n   /**\n    * The E-mail address of the person responsible for this domain (reformatted with '.' at end).\n    */\n   @Nullable\n   public String getResponsiblePerson() {\n      return responsiblePerson;\n   }\n\n   /**\n    * TTL (time to live). The number of seconds a domain name is cached locally before expiration and return to authoritative nameServers for updates\n    */\n   public int getTtl() {\n      return ttl;\n   }\n\n   /**\n    * The number of seconds between update requests from secondary and slave name servers\n    */\n   public int getRefresh() {\n      return refresh;\n   }\n\n\n   /**\n    * The number of seconds the secondary/slave will wait before retrying when the last attempt failed\n    */\n   public int getRetry() {\n      return retry;\n   }\n\n   /**\n    * The number of seconds a master or slave will wait before considering the data stale if it cannot reach the primary name server\n    */\n   public int getExpire() {\n      return expire;\n   }\n\n   /**\n    * The minimum/default TTL if the domain does not specify ttl\n    *\n    * @see #getTtl()\n    */\n   public int getMinimum() {\n      return minimum;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(domainName);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Domain that = Domain.class.cast(obj);\n      return Objects.equal(this.domainName, that.domainName);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(\"\")\n            .add(\"domainName\", domainName).add(\"createTime\", createTime).add(\"recordCount\", recordCount).add(\"useGlesysNameServer\", useGlesysNameServer);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/domain/DomainRecord.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * DNS record data.\n *\n * @see <a href= \"https://customer.glesys.com/api.php?a=doc#domain_list_records\" />\n */\npublic class DomainRecord {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromDomainRecord(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String id;\n      protected String domainname;\n      protected String host;\n      protected String type;\n      protected String data;\n      protected int ttl;\n\n      /**\n       * @see DomainRecord#getId()\n       */\n      public T id(String id) {\n         this.id = checkNotNull(id, \"id\");\n         return self();\n      }\n\n      /**\n       * @see DomainRecord#getname()\n       */\n      public T domainname(String domainname) {\n         this.domainname = checkNotNull(domainname, \"domainname\");\n         return self();\n      }\n\n      /**\n       * @see DomainRecord#getHost()\n       */\n      public T host(String host) {\n         this.host = checkNotNull(host, \"host\");\n         return self();\n      }\n\n      /**\n       * @see DomainRecord#getType()\n       */\n      public T type(String type) {\n         this.type = checkNotNull(type, \"type\");\n         return self();\n      }\n\n      /**\n       * @see DomainRecord#getData()\n       */\n      public T data(String data) {\n         this.data = checkNotNull(data, \"data\");\n         return self();\n      }\n\n      /**\n       * @see DomainRecord#getTtl()\n       */\n      public T ttl(int ttl) {\n         this.ttl = ttl;\n         return self();\n      }\n\n      public DomainRecord build() {\n         return new DomainRecord(id, domainname, host, type, data, ttl);\n      }\n\n      public T fromDomainRecord(DomainRecord in) {\n         return this.id(in.getId())\n               .domainname(in.getname())\n               .host(in.getHost())\n               .type(in.getType())\n               .data(in.getData())\n               .ttl(in.getTtl());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final String domainname;\n   private final String host;\n   private final String type;\n   private final String data;\n   private final int ttl;\n\n   @ConstructorProperties({\n         \"recordid\", \"domainname\", \"host\", \"type\", \"data\", \"ttl\"\n   })\n   protected DomainRecord(@Nullable String id, String domainname, String host, String type, @Nullable String data, int ttl) {\n      this.id = id;\n      this.domainname = checkNotNull(domainname, \"domainname\");\n      this.host = checkNotNull(host, \"host\");\n      this.type = checkNotNull(type, \"type\");\n      this.data = data;\n      this.ttl = ttl;\n   }\n\n   /**\n    * @return the id of the record used to modify it via the API\n    * @see org.jclouds.glesys.features.DomainApi\n    */\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * @return the zone content of the record\n    */\n   public String getname() {\n      return this.domainname;\n   }\n\n   /**\n    * @return the host content of the record\n    */\n   public String getHost() {\n      return this.host;\n   }\n\n   /**\n    * @return the type of the record, ex. \"A\"\n    */\n   public String getType() {\n      return this.type;\n   }\n\n   /**\n    * @return the data content of the record\n    */\n   @Nullable\n   public String getData() {\n      return this.data;\n   }\n\n   /**\n    * @return the TTL/Time-to-live for the record\n    */\n   public int getTtl() {\n      return this.ttl;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      DomainRecord that = DomainRecord.class.cast(obj);\n      return Objects.equal(this.id, that.id);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(\"\")\n            .add(\"id\", id).add(\"domainname\", domainname).add(\"host\", host).add(\"type\", type).add(\"data\", data)\n            .add(\"ttl\", ttl);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/domain/EmailAccount.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Detailed information on an Email Account\n *\n * @see <a href=\"https://customer.glesys.com/api.php?a=doc#email_list\" />\n */\npublic class EmailAccount {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromEmailAccount(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String account;\n      protected EmailQuota quota;\n      protected int antispamLevel;\n      protected boolean antiVirus;\n      protected boolean autoRespond;\n      protected String autoRespondMessage;\n      protected boolean autoRespondSaveEmail;\n      protected Date created;\n      protected Date modified;\n\n      /**\n       * @see EmailAccount#getAccount()\n       */\n      public T account(String account) {\n         this.account = checkNotNull(account, \"account\");\n         return self();\n      }\n\n      /**\n       * @see EmailAccount#getQuota()\n       */\n      public T quota(EmailQuota quota) {\n         this.quota = checkNotNull(quota, \"quota\");\n         return self();\n      }\n\n      /**\n       * @see EmailAccount#getAntispamLevel()\n       */\n      public T antispamLevel(int antispamLevel) {\n         this.antispamLevel = antispamLevel;\n         return self();\n      }\n\n      /**\n       * @see EmailAccount#isAntiVirus()\n       */\n      public T antiVirus(boolean antiVirus) {\n         this.antiVirus = antiVirus;\n         return self();\n      }\n\n      /**\n       * @see EmailAccount#isAutoRespond()\n       */\n      public T autoRespond(boolean autoRespond) {\n         this.autoRespond = autoRespond;\n         return self();\n      }\n\n      /**\n       * @see EmailAccount#getAutoRespondMessage()\n       */\n      public T autoRespondMessage(String autoRespondMessage) {\n         this.autoRespondMessage = checkNotNull(autoRespondMessage, \"autoRespondMessage\");\n         return self();\n      }\n\n      /**\n       * @see EmailAccount#isAutoRespondSaveEmail()\n       */\n      public T autoRespondSaveEmail(boolean autoRespondSaveEmail) {\n         this.autoRespondSaveEmail = autoRespondSaveEmail;\n         return self();\n      }\n\n      /**\n       * @see EmailAccount#getCreated()\n       */\n      public T created(Date created) {\n         this.created = checkNotNull(created, \"created\");\n         return self();\n      }\n\n      /**\n       * @see EmailAccount#getModified()\n       */\n      public T modified(Date modified) {\n         this.modified = checkNotNull(modified, \"modified\");\n         return self();\n      }\n\n      public EmailAccount build() {\n         return new EmailAccount(account, quota, antispamLevel, new GleSYSBoolean(antiVirus), new GleSYSBoolean(autoRespond), autoRespondMessage, new GleSYSBoolean(autoRespondSaveEmail), created, modified);\n      }\n\n      public T fromEmailAccount(EmailAccount in) {\n         return this.account(in.getAccount())\n               .quota(in.getQuota())\n               .antispamLevel(in.getAntispamLevel())\n               .antiVirus(in.isAntiVirus())\n               .autoRespond(in.isAutoRespond())\n               .autoRespondMessage(in.getAutoRespondMessage())\n               .autoRespondSaveEmail(in.isAutoRespondSaveEmail())\n               .created(in.getCreated())\n               .modified(in.getModified());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String account;\n   private final EmailQuota quota;\n   private final int antispamLevel;\n   private final boolean antiVirus;\n   private final boolean autoRespond;\n   private final String autoRespondMessage;\n   private final boolean autoRespondSaveEmail;\n   private final Date created;\n   private final Date modified;\n\n   @ConstructorProperties({\n         \"emailaccount\", \"quota\", \"antispamlevel\", \"antivirus\", \"autorespond\", \"autorespondmessage\", \"autorespondsaveemail\", \"created\", \"modified\"\n   })\n   protected EmailAccount(String account, EmailQuota quota, int antispamLevel,\n                          GleSYSBoolean antiVirus, GleSYSBoolean autoRespond, @Nullable String autoRespondMessage,\n                          GleSYSBoolean autoRespondSaveEmail, Date created, @Nullable Date modified) {\n      this.account = checkNotNull(account, \"account\");\n      this.quota = checkNotNull(quota, \"quota\");\n      this.antispamLevel = antispamLevel;\n      this.antiVirus = checkNotNull(antiVirus, \"antiVirus\").getValue();\n      this.autoRespond = checkNotNull(autoRespond, \"autoRespond\").getValue();\n      this.autoRespondMessage = autoRespondMessage;\n      this.autoRespondSaveEmail = checkNotNull(autoRespondSaveEmail, \"autoRespondSaveEmail\").getValue();\n      this.created = checkNotNull(created, \"created\");\n      this.modified = modified;\n   }\n\n   /**\n    * @return the e-mail address for this e-mail account\n    */\n   public String getAccount() {\n      return this.account;\n   }\n\n   /**\n    * @return the quota for this e-mail account\n    */\n   public EmailQuota getQuota() {\n      return this.quota;\n   }\n\n   /**\n    * @return the antispam level of the e-mail account\n    */\n   public int getAntispamLevel() {\n      return this.antispamLevel;\n   }\n\n   /**\n    * @return true if antivirus is enabled for this e-mail account\n    */\n   public boolean isAntiVirus() {\n      return this.antiVirus;\n   }\n\n   /**\n    * @return true if auto-respond is enabled for this e-mail account\n    */\n   public boolean isAutoRespond() {\n      return this.autoRespond;\n   }\n   /**\n    * @return the auto-respond message for this e-mail account\n    */\n   @Nullable\n   public String getAutoRespondMessage() {\n      return this.autoRespondMessage;\n   }\n\n   /**\n    * @return true if saving is enabled for auto-respond e-mails\n    */\n   public boolean isAutoRespondSaveEmail() {\n      return this.autoRespondSaveEmail;\n   }\n\n   /**\n    * @return when this account was created\n    */\n   public Date getCreated() {\n      return this.created;\n   }\n\n   /**\n    * @return when this account was last modified\n    */\n   @Nullable\n   public Date getModified() {\n      return this.modified;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(account);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      EmailAccount that = EmailAccount.class.cast(obj);\n      return Objects.equal(this.account, that.account);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(\"\")\n            .add(\"account\", account).add(\"quota\", quota).add(\"antispamLevel\", antispamLevel).add(\"antiVirus\", antiVirus).add(\"autoRespond\", autoRespond).add(\"autoRespondMessage\", autoRespondMessage).add(\"autoRespondSaveEmail\", autoRespondSaveEmail).add(\"created\", created).add(\"modified\", modified);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/domain/EmailAlias.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Detailed information on an Email Account\n *\n * @see <a href=\"https://customer.glesys.com/api.php?a=doc#email_list\" />\n */\npublic class EmailAlias {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromEmailAlias(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String alias;\n      protected String forwardTo;\n\n      /**\n       * @see org.jclouds.glesys.domain.EmailAlias#getAlias()\n       */\n      public T alias(String alias) {\n         this.alias = checkNotNull(alias, \"alias\");\n         return self();\n      }\n\n      /**\n       * @see EmailAlias#getForwardTo()\n       */\n      public T forwardTo(String forwardTo) {\n         this.forwardTo = checkNotNull(forwardTo, \"forwardTo\");\n         return self();\n      }\n\n      public EmailAlias build() {\n         return new EmailAlias(alias, forwardTo);\n      }\n\n      public T fromEmailAlias(EmailAlias in) {\n         return this.alias(in.getAlias()).forwardTo(in.getForwardTo());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String alias;\n   private final String forwardTo;\n\n   @ConstructorProperties({\n         \"emailalias\", \"goto\"\n   })\n   protected EmailAlias(String alias, String forwardTo) {\n      this.alias = checkNotNull(alias, \"alias\");\n      this.forwardTo = checkNotNull(forwardTo, \"forwardTo\");\n   }\n\n   /**\n    * @return the e-mail address being forwarded\n    */\n   public String getAlias() {\n      return this.alias;\n   }\n\n   /**\n    * @return the e-mail address this address forwards to\n    */\n   public String getForwardTo() {\n      return this.forwardTo;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(alias);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      EmailAlias that = EmailAlias.class.cast(obj);\n      return Objects.equal(this.alias, that.alias);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(\"\")\n            .add(\"alias\", alias).add(\"forwardTo\", forwardTo);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/domain/EmailOverview.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Set;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Structure containing all information about e-mail addresses for a GleSYS account\n *\n * @see <a href=\"https://customer.glesys.com/api.php?a=doc#email_overview\" />\n */\n//TODO: find a better name for this class\n@Beta\npublic class EmailOverview {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromEmailOverview(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected EmailOverviewSummary summary;\n      protected Set<EmailOverviewDomain> domains = ImmutableSet.of();\n\n      /**\n       * @see EmailOverview#getSummary()\n       */\n      public T summary(EmailOverviewSummary summary) {\n         this.summary = checkNotNull(summary, \"summary\");\n         return self();\n      }\n\n      /**\n       * @see EmailOverview#gets()\n       */\n      public T domains(Set<EmailOverviewDomain> domains) {\n         this.domains = ImmutableSet.copyOf(checkNotNull(domains, \"domains\"));\n         return self();\n      }\n\n      public T domains(EmailOverviewDomain... in) {\n         return domains(ImmutableSet.copyOf(in));\n      }\n\n      public EmailOverview build() {\n         return new EmailOverview(summary, domains);\n      }\n\n      public T fromEmailOverview(EmailOverview in) {\n         return this.summary(in.getSummary()).domains(in.gets());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final EmailOverviewSummary summary;\n   private final Set<EmailOverviewDomain> domains;\n\n   @ConstructorProperties({\n         \"summary\", \"domains\"\n   })\n   protected EmailOverview(EmailOverviewSummary summary, Set<EmailOverviewDomain> domains) {\n      this.summary = checkNotNull(summary, \"summary\");\n      this.domains = ImmutableSet.copyOf(checkNotNull(domains, \"domains\"));\n   }\n\n   /**\n    * @return summary information about the account\n    */\n   public EmailOverviewSummary getSummary() {\n      return this.summary;\n   }\n\n   /**\n    * @return the set of detailed information about the e-mail addresses and aliases for each domain\n    */\n   public Set<EmailOverviewDomain> gets() {\n      return this.domains;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(summary, domains);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      EmailOverview that = EmailOverview.class.cast(obj);\n      return Objects.equal(this.summary, that.summary)\n            && Objects.equal(this.domains, that.domains);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(\"\")\n            .add(\"summary\", summary).add(\"domains\", domains);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/domain/EmailOverviewDomain.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Detailed information about e-mail settings for a single domain\n *\n * @see <a href=\"https://customer.glesys.com/api.php?a=doc#email_overview\" />\n */\n@Beta\npublic class EmailOverviewDomain {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromEmailOverviewDomain(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String domain;\n      protected int accounts;\n      protected int aliases;\n\n      /**\n       * @see EmailOverviewDomain#get()\n       */\n      public T domain(String domain) {\n         this.domain = checkNotNull(domain, \"domain\");\n         return self();\n      }\n\n      /**\n       * @see EmailOverviewDomain#getAccounts()\n       */\n      public T accounts(int accounts) {\n         this.accounts = accounts;\n         return self();\n      }\n\n      /**\n       * @see EmailOverviewDomain#getAliases()\n       */\n      public T aliases(int aliases) {\n         this.aliases = aliases;\n         return self();\n      }\n\n      public EmailOverviewDomain build() {\n         return new EmailOverviewDomain(domain, accounts, aliases);\n      }\n\n      public T fromEmailOverviewDomain(EmailOverviewDomain in) {\n         return this.domain(in.get()).accounts(in.getAccounts()).aliases(in.getAliases());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String domain;\n   private final int accounts;\n   private final int aliases;\n\n   @ConstructorProperties({\n         \"domainname\", \"accounts\", \"aliases\"\n   })\n   protected EmailOverviewDomain(String domain, int accounts, int aliases) {\n      this.domain = checkNotNull(domain, \"domain\");\n      this.accounts = accounts;\n      this.aliases = aliases;\n   }\n\n   /** @return the domain name */\n   public String get() {\n      return this.domain;\n   }\n\n   /** @return the number of e-mail accounts in the domain */\n   public int getAccounts() {\n      return this.accounts;\n   }\n\n   /** @return the number of e-mail aliases in the domain */\n   public int getAliases() {\n      return this.aliases;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(domain);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      EmailOverviewDomain that = EmailOverviewDomain.class.cast(obj);\n      return Objects.equal(this.domain, that.domain);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(\"\").add(\"domain\", domain).add(\"accounts\", accounts).add(\"aliases\", aliases);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/domain/EmailOverviewSummary.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Summary information of e-mail settings and limits for a GleSYS account\n *\n * @see <a href=\"https://customer.glesys.com/api.php?a=doc#email_overview\" />\n */\n//TODO: find a better name for this class\n@Beta\npublic class EmailOverviewSummary {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromEmailOverviewSummary(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected int accounts;\n      protected int maxAccounts;\n      protected int aliases;\n      protected int maxAliases;\n\n      /**\n       * @see EmailOverviewSummary#getAccounts()\n       */\n      public T accounts(int accounts) {\n         this.accounts = accounts;\n         return self();\n      }\n\n      /**\n       * @see EmailOverviewSummary#getMaxAccounts()\n       */\n      public T maxAccounts(int maxAccounts) {\n         this.maxAccounts = maxAccounts;\n         return self();\n      }\n\n      /**\n       * @see EmailOverviewSummary#getAliases()\n       */\n      public T aliases(int aliases) {\n         this.aliases = aliases;\n         return self();\n      }\n\n      /**\n       * @see EmailOverviewSummary#getMaxAliases()\n       */\n      public T maxAliases(int maxAliases) {\n         this.maxAliases = maxAliases;\n         return self();\n      }\n\n      public EmailOverviewSummary build() {\n         return new EmailOverviewSummary(accounts, maxAccounts, aliases, maxAliases);\n      }\n\n      public T fromEmailOverviewSummary(EmailOverviewSummary in) {\n         return this.accounts(in.getAccounts())\n               .maxAccounts(in.getMaxAccounts())\n               .aliases(in.getAliases())\n               .maxAliases(in.getMaxAliases());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final int accounts;\n   private final int maxAccounts;\n   private final int aliases;\n   private final int maxAliases;\n\n   @ConstructorProperties({\n         \"accounts\", \"maxaccounts\", \"aliases\", \"maxaliases\"\n   })\n   protected EmailOverviewSummary(int accounts, int maxAccounts, int aliases, int maxAliases) {\n      this.accounts = accounts;\n      this.maxAccounts = maxAccounts;\n      this.aliases = aliases;\n      this.maxAliases = maxAliases;\n   }\n\n   /**\n    * @return the number of e-mail accounts\n    */\n   public int getAccounts() {\n      return this.accounts;\n   }\n\n   /**\n    * @return the maximum number of e-mail accounts\n    */\n   public int getMaxAccounts() {\n      return this.maxAccounts;\n   }\n\n   /**\n    * @return the number of e-mail aliases\n    */\n   public int getAliases() {\n      return this.aliases;\n   }\n\n   /**\n    * @return the maximum number of e-mail aliases\n    */\n   public int getMaxAliases() {\n      return this.maxAliases;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(accounts, maxAccounts, aliases, maxAliases);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      EmailOverviewSummary that = EmailOverviewSummary.class.cast(obj);\n      return Objects.equal(this.accounts, that.accounts)\n            && Objects.equal(this.maxAccounts, that.maxAccounts)\n            && Objects.equal(this.aliases, that.aliases)\n            && Objects.equal(this.maxAliases, that.maxAliases);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(\"\")\n            .add(\"accounts\", accounts).add(\"maxAccounts\", maxAccounts).add(\"aliases\", aliases).add(\"maxAliases\", maxAliases);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/domain/EmailQuota.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Information on an Email Account Quota size\n *\n * @see <a href=\"https://customer.glesys.com/api.php?a=doc#email_list\" />\n */\npublic class EmailQuota {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromEmailAccount(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected int max;\n      protected String unit;\n\n      /**\n       * @see EmailQuota#getMax()\n       */\n      public T max(int max) {\n         this.max = max;\n         return self();\n      }\n\n      /**\n       * @see EmailQuota#getUnit()\n       */\n      public T unit(String unit) {\n         this.unit = checkNotNull(unit, \"unit\");\n         return self();\n      }\n\n      public EmailQuota build() {\n         return new EmailQuota(max, unit);\n      }\n\n      public T fromEmailAccount(EmailQuota in) {\n         return this.max(in.getMax()).unit(in.getUnit());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final int max;\n   private final String unit;\n\n   @ConstructorProperties({\n         \"max\", \"unit\"\n   })\n   protected EmailQuota(int max, String unit) {\n      this.max = max;\n      this.unit = unit;\n   }\n\n   /**\n    * @return the maximum size of the mailbox (in units)\n    * @see #getUnit\n    */\n   public int getMax() {\n      return this.max;\n   }\n\n   /**\n    * @return the quota for this e-mail account\n    */\n   public String getUnit() {\n      return this.unit;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(max, unit);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      EmailQuota that = EmailQuota.class.cast(obj);\n      return Objects.equal(this.max, that.max) && Objects.equal(this.unit, that.unit);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(\"\").add(\"max\", max).add(\"unit\", unit);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/domain/GleSYSBoolean.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.domain;\n\n/**\n * Wrapping booleans for the time being (gson won't allow TypeAdapter&lt;Boolean&gt;)\n */\npublic class GleSYSBoolean {\n   public static final GleSYSBoolean TRUE = new GleSYSBoolean(true);\n   public static final GleSYSBoolean FALSE = new GleSYSBoolean(false);\n\n   private boolean value;\n\n   public GleSYSBoolean(boolean value) {\n      this.value = value;\n   }\n\n   public boolean getValue() {\n      return value;\n   }\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/domain/Ip.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Represents an ip address used by a server.\n *\n * @see Server\n * @see ServerDetails\n */\npublic class Ip {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromIp(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String ip;\n      protected int version;\n      protected double cost;\n      protected String currency;\n\n      /**\n       * @see Ip#getIp()\n       */\n      public T ip(String ip) {\n         this.ip = checkNotNull(ip, \"ip\");\n         return self();\n      }\n\n      /**\n       * @see Ip#getVersion()\n       */\n      protected T version(int version) {\n         this.version = version;\n         return self();\n      }\n\n      /**\n       * @see Ip#getVersion()\n       */\n      public T version4() {\n         return version(4);\n      }\n\n      /**\n       * @see Ip#getVersion()\n       */\n      public T version6() {\n         return version(6);\n      }\n\n      /**\n       * @see Ip#getCost()\n       */\n      public T cost(double cost) {\n         this.cost = cost;\n         return self();\n      }\n\n      /**\n       * @see Ip#getCurrency()\n       */\n      public T currency(String currency) {\n         this.currency = currency;\n         return self();\n      }\n\n      public Ip build() {\n         return new Ip(ip, version, cost, currency);\n      }\n\n      public T fromIp(Ip in) {\n         return this.ip(in.getIp()).version(in.getVersion()).cost(in.getCost());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String ip;\n   private final int version;\n   private final double cost;\n   private final String currency;\n\n   @ConstructorProperties({\n         \"ipaddress\", \"version\", \"cost\", \"currency\"\n   })\n   protected Ip(String ip, int version, double cost, String currency) {\n      this.ip = checkNotNull(ip, \"ip\");\n      this.version = version;\n      this.cost = cost;\n      this.currency = checkNotNull(currency, \"currency\");\n   }\n\n   /**\n    * @return the IP version, ex. 4\n    */\n   public String getIp() {\n      return this.ip;\n   }\n\n   /**\n    * @return the ip address of the new server\n    */\n   public int getVersion() {\n      return this.version;\n   }\n\n   /**\n    * @return the cost of the ip address allocated to the new server\n    * @see #getCurrency()\n    */\n   public double getCost() {\n      return this.cost;\n   }\n\n   /**\n    * @return the currency of the cost\n    * @see #getCost() \n    */\n   public String getCurrency() {\n      return currency;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(ip, version, cost);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Ip that = Ip.class.cast(obj);\n      return Objects.equal(this.ip, that.ip)\n            && Objects.equal(this.version, that.version)\n            && Objects.equal(this.cost, that.cost)\n            && Objects.equal(this.currency, that.currency);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(\"\")\n            .add(\"ip\", ip).add(\"version\", version).add(\"cost\", cost).add(\"currency\", currency);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/domain/IpDetails.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Represents detailed information about an IP address.\n */\npublic class IpDetails {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromIpDetails(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String datacenter;\n      protected int ipversion;\n      protected String ptr;\n      protected String platform;\n      protected String address;\n      protected String netmask;\n      protected String broadcast;\n      protected String gateway;\n      protected List<String> nameServers = ImmutableList.of();\n      protected String serverId;\n      protected Cost cost;\n      protected boolean reserved;\n\n      /**\n       * @see IpDetails#getDatacenter()\n       */\n      public T datacenter(String datacenter) {\n         this.datacenter = checkNotNull(datacenter, \"datacenter\");\n         return self();\n      }\n\n      protected T version(int ipversion) {\n         this.ipversion = ipversion;\n         return self();\n      }\n\n      /*\n      * @see IpDetails#getVersion()\n      */\n      public T version4() {\n         return version(4);\n      }\n\n      /*\n      * @see IpDetails#getVersion()\n      */\n      public T version6() {\n         return version(6);\n      }\n\n      /**\n       * @see IpDetails#getPtr()\n       */\n      public T ptr(String ptr) {\n         this.ptr = checkNotNull(ptr, \"ptr\");\n         return self();\n      }\n\n      /**\n       * @see IpDetails#getPlatform()\n       */\n      public T platform(String platform) {\n         this.platform = checkNotNull(platform, \"platform\");\n         return self();\n      }\n\n      /**\n       * @see IpDetails#getAddress()\n       */\n      public T address(String address) {\n         this.address = address;\n         return self();\n      }\n\n      /**\n       * @see IpDetails#getNetmask()\n       */\n      public T netmask(String netmask) {\n         this.netmask = netmask;\n         return self();\n      }\n\n      /**\n       * @see IpDetails#getBroadcast()\n       */\n      public T broadcast(String broadcast) {\n         this.broadcast = broadcast;\n         return self();\n      }\n\n      /**\n       * @see IpDetails#getGateway()\n       */\n      public T gateway(String gateway) {\n         this.gateway = gateway;\n         return self();\n      }\n\n      /**\n       * @see IpDetails#getNameServers()\n       */\n      public T nameServers(List<String> nameservers) {\n         this.nameServers = ImmutableList.copyOf(checkNotNull(nameservers, \"nameServers\"));\n         return self();\n      }\n\n      public T nameServers(String... in) {\n         return nameServers(ImmutableList.copyOf(in));\n      }\n\n      /**\n       * @see IpDetails#getServerId()\n       */\n      public T serverId(String serverId) {\n         this.serverId = serverId;\n         return self();\n      }\n\n      /**\n       * @see IpDetails#getCost()\n       */\n      public T cost(Cost cost) {\n         this.cost = cost;\n         return self();\n      }\n\n      /**\n       * @see IpDetails#isReserved()\n       */\n      public T reserved(boolean reserved) {\n         this.reserved = reserved;\n         return self();\n      }\n\n      public IpDetails build() {\n         return new IpDetails(datacenter, ipversion, ptr, platform, address, netmask, broadcast, gateway, nameServers,\n               serverId, cost, new GleSYSBoolean(reserved));\n      }\n\n      public T fromIpDetails(IpDetails in) {\n         return this.datacenter(in.getDatacenter())\n               .version(in.getVersion())\n               .ptr(in.getPtr())\n               .platform(in.getPlatform())\n               .address(in.getAddress())\n               .netmask(in.getNetmask())\n               .broadcast(in.getBroadcast())\n               .gateway(in.getGateway())\n               .nameServers(in.getNameServers())\n               .serverId(in.getServerId())\n               .cost(in.getCost())\n               .reserved(in.isReserved());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String datacenter;\n   private final int version;\n   private final String ptr;\n   private final String platform;\n   private final String address;\n   private final String netmask;\n   private final String broadcast;\n   private final String gateway;\n   private final List<String> nameServers;\n   private final String serverId;\n   private final Cost cost;\n   private final boolean reserved;\n\n   @ConstructorProperties({\n         \"datacenter\", \"ipversion\", \"ptr\", \"platform\", \"ipaddress\", \"netmask\", \"broadcast\", \"gateway\", \"nameservers\",\n         \"serverid\", \"cost\", \"reserved\"\n   })\n   protected IpDetails(String datacenter, int version, String ptr, String platform, String address,\n                       @Nullable String netmask, @Nullable String broadcast, @Nullable String gateway,\n                       List<String> nameServers, @Nullable String serverId, Cost cost, GleSYSBoolean reserved) {\n      this.datacenter = checkNotNull(datacenter, \"datacenter\");\n      this.version = version;\n      this.ptr = checkNotNull(ptr, \"ptr\");\n      this.platform = checkNotNull(platform, \"platform\");\n      this.address = address;\n      this.netmask = netmask;\n      this.broadcast = broadcast;\n      this.gateway = gateway;\n      this.nameServers = ImmutableList.copyOf(nameServers);\n      this.serverId = serverId;\n      this.cost = checkNotNull(cost, \"cost\");\n      this.reserved = checkNotNull(reserved, \"reserved\").getValue();\n   }\n\n   public String getDatacenter() {\n      return this.datacenter;\n   }\n\n   /**\n    * @return the IP version, ex. 4\n    */\n   public int getVersion() {\n      return this.version;\n   }\n\n   public String getPtr() {\n      return this.ptr;\n   }\n\n   public String getPlatform() {\n      return this.platform;\n   }\n\n   public String getAddress() {\n      return this.address;\n   }\n\n   @Nullable\n   public String getNetmask() {\n      return this.netmask;\n   }\n\n   @Nullable\n   public String getBroadcast() {\n      return this.broadcast;\n   }\n\n   @Nullable\n   public String getGateway() {\n      return this.gateway;\n   }\n\n   public List<String> getNameServers() {\n      return this.nameServers;\n   }\n\n   @Nullable\n   public String getServerId() {\n      return serverId;\n   }\n\n   public Cost getCost() {\n      return cost;\n   }\n\n   public boolean isReserved() {\n      return reserved;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(datacenter, version, ptr, platform, address, netmask, broadcast, gateway, nameServers,\n            serverId, cost, reserved);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      IpDetails that = IpDetails.class.cast(obj);\n      return Objects.equal(this.datacenter, that.datacenter)\n            && Objects.equal(this.version, that.version)\n            && Objects.equal(this.ptr, that.ptr)\n            && Objects.equal(this.platform, that.platform)\n            && Objects.equal(this.address, that.address)\n            && Objects.equal(this.netmask, that.netmask)\n            && Objects.equal(this.broadcast, that.broadcast)\n            && Objects.equal(this.gateway, that.gateway)\n            && Objects.equal(this.nameServers, that.nameServers)\n            && Objects.equal(this.serverId, that.serverId)\n            && Objects.equal(this.cost, that.cost)\n            && Objects.equal(this.reserved, that.reserved);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(\"\")\n            .add(\"datacenter\", datacenter).add(\"ipversion\", version).add(\"ptr\", ptr).add(\"platform\", platform)\n            .add(\"address\", address).add(\"netmask\", netmask).add(\"broadcast\", broadcast).add(\"gateway\", gateway)\n            .add(\"nameServers\", nameServers).add(\"serverId\", serverId).add(\"cost\", cost).add(\"reserved\", reserved);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/domain/OSTemplate.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Operating system template\n *\n * @see <a href= \"https://customer.glesys.com/api.php?a=doc#server_templates\" />\n */\npublic class OSTemplate {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromOSTemplate(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String name;\n      protected int minDiskSize;\n      protected int minMemSize;\n      protected String os;\n      protected String platform;\n\n      /**\n       * @see OSTemplate#getName()\n       */\n      public T name(String name) {\n         this.name = checkNotNull(name, \"name\");\n         return self();\n      }\n\n      /**\n       * @see OSTemplate#getMinDiskSize()\n       */\n      public T minDiskSize(int minDiskSize) {\n         this.minDiskSize = minDiskSize;\n         return self();\n      }\n\n      /**\n       * @see OSTemplate#getMinMemSize()\n       */\n      public T minMemSize(int minMemSize) {\n         this.minMemSize = minMemSize;\n         return self();\n      }\n\n      /**\n       * @see OSTemplate#getOs()\n       */\n      public T os(String os) {\n         this.os = checkNotNull(os, \"os\");\n         return self();\n      }\n\n      /**\n       * @see OSTemplate#getPlatform()\n       */\n      public T platform(String platform) {\n         this.platform = checkNotNull(platform, \"platform\");\n         return self();\n      }\n\n      public OSTemplate build() {\n         return new OSTemplate(name, minDiskSize, minMemSize, os, platform);\n      }\n\n      public T fromOSTemplate(OSTemplate in) {\n         return this.name(in.getName())\n               .minDiskSize(in.getMinDiskSize())\n               .minMemSize(in.getMinMemSize())\n               .os(in.getOs())\n               .platform(in.getPlatform());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String name;\n   private final int minDiskSize;\n   private final int minMemSize;\n   private final String os;\n   private final String platform;\n\n   @ConstructorProperties({\n         \"name\", \"minimumdisksize\", \"minimummemorysize\", \"operatingsystem\", \"platform\"\n   })\n   protected OSTemplate(String name, int minDiskSize, int minMemSize, String os, String platform) {\n      this.name = checkNotNull(name, \"name\");\n      this.minDiskSize = minDiskSize;\n      this.minMemSize = minMemSize;\n      this.os = checkNotNull(os, \"os\");\n      this.platform = checkNotNull(platform, \"platform\");\n   }\n\n   /**\n    */\n   public String getName() {\n      return this.name;\n   }\n\n   /**\n    * @return the minimum allowed disk size in GB\n    * @see org.jclouds.glesys.domain.AllowedArgumentsForCreateServer#getDiskSizesInGB()\n    */\n   public int getMinDiskSize() {\n      return this.minDiskSize;\n   }\n\n   /**\n    * @return the minimum allowed memory size in MB\n    * @see org.jclouds.glesys.domain.AllowedArgumentsForCreateServer#getMemorySizesInMB()\n    */\n   public int getMinMemSize() {\n      return this.minMemSize;\n   }\n\n   /**\n    * @return the name of the operating system type ex. \"linux\"\n    */\n   public String getOs() {\n      return this.os;\n   }\n\n   /**\n    * @return the name of the platform this template is available in, ex. \"Xen\"\n    */\n   public String getPlatform() {\n      return this.platform;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(name, platform);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      OSTemplate that = OSTemplate.class.cast(obj);\n      return Objects.equal(this.name, that.name)\n            && Objects.equal(this.platform, that.platform);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(\"\")\n            .add(\"name\", name).add(\"minDiskSize\", minDiskSize).add(\"minMemSize\", minMemSize).add(\"os\", os).add(\"platform\", platform);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/domain/ResourceStatus.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Detailed information on usage\n *\n * @see ServerStatus\n */\npublic class ResourceStatus {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromResourceUsage(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected double usage;\n      protected double max;\n      protected String unit;\n\n      /**\n       * @see ResourceStatus#getUsage()\n       */\n      public T usage(double usage) {\n         this.usage = usage;\n         return self();\n      }\n\n      /**\n       * @see ResourceStatus#getMax()\n       */\n      public T max(double max) {\n         this.max = max;\n         return self();\n      }\n\n      /**\n       * @see ResourceStatus#getUnit()\n       */\n      public T unit(String unit) {\n         this.unit = checkNotNull(unit, \"unit\");\n         return self();\n      }\n\n      public ResourceStatus build() {\n         return new ResourceStatus(usage, max, unit);\n      }\n\n      public T fromResourceUsage(ResourceStatus in) {\n         return this.usage(in.getUsage()).max(in.getMax()).unit(in.getUnit());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final double usage;\n   private final double max;\n   private final String unit;\n\n   @ConstructorProperties({\n         \"usage\", \"max\", \"unit\"\n   })\n   protected ResourceStatus(double usage, double max, String unit) {\n      this.usage = usage;\n      this.max = max;\n      this.unit = checkNotNull(unit, \"unit\");\n   }\n\n   /**\n    * @return the usage in #unit\n    */\n   public double getUsage() {\n      return this.usage;\n   }\n\n   /**\n    * @return the max usage in #unit\n    */\n   public double getMax() {\n      return this.max;\n   }\n\n   /**\n    * @return the unit used\n    */\n   public String getUnit() {\n      return this.unit;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(usage, max, unit);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      ResourceStatus that = ResourceStatus.class.cast(obj);\n      return Objects.equal(this.usage, that.usage)\n            && Objects.equal(this.max, that.max)\n            && Objects.equal(this.unit, that.unit);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(\"\").add(\"usage\", usage).add(\"max\", max).add(\"unit\", unit);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/domain/ResourceUsage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Set;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Detailed information on usage\n *\n * @see ResourceUsageInfo\n * @see ResourceUsageValue\n */\npublic class ResourceUsage {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromResourceUsages(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected ResourceUsageInfo info;\n      protected Set<ResourceUsageValue> values = ImmutableSet.of();\n\n      /**\n       * @see ResourceUsage#getInfo()\n       */\n      public T info(ResourceUsageInfo info) {\n         this.info = checkNotNull(info, \"info\");\n         return self();\n      }\n\n      /**\n       * @see ResourceUsage#getValues()\n       */\n      public T values(Set<ResourceUsageValue> values) {\n         this.values = ImmutableSet.copyOf(checkNotNull(values, \"values\"));\n         return self();\n      }\n\n      /**\n       * @see ResourceUsage#getValues()\n       */\n      public T values(ResourceUsageValue... in) {\n         return values(ImmutableSet.copyOf(in));\n      }\n\n      public ResourceUsage build() {\n         return new ResourceUsage(info, values);\n      }\n\n      public T fromResourceUsages(ResourceUsage in) {\n         return this\n               .info(in.getInfo())\n               .values(in.getValues());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final ResourceUsageInfo info;\n   private final Set<ResourceUsageValue> values;\n\n   @ConstructorProperties({\n         \"info\", \"values\"\n   })\n   protected ResourceUsage(ResourceUsageInfo info, Set<ResourceUsageValue> values) {\n      this.info = checkNotNull(info, \"info\");\n      this.values = ImmutableSet.copyOf(checkNotNull(values, \"values\"));\n   }\n\n   public ResourceUsageInfo getInfo() {\n      return this.info;\n   }\n\n   public Set<ResourceUsageValue> getValues() {\n      return this.values;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(info, values);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      ResourceUsage that = ResourceUsage.class.cast(obj);\n      return Objects.equal(this.info, that.info)\n            && Objects.equal(this.values, that.values);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(\"\")\n            .add(\"info\", info).add(\"values\", values);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/domain/ResourceUsageInfo.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Detailed information on usage\n *\n * @see ServerStatus\n */\npublic class ResourceUsageInfo {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromResourceUsageInfo(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>>  {\n      protected abstract T self();\n\n      protected String resource;\n      protected String resolution;\n      protected String unit;\n\n      /**\n       * @see ResourceUsageInfo#getResource()\n       */\n      public T resource(String resource) {\n         this.resource = checkNotNull(resource, \"resource\");\n         return self();\n      }\n\n      /**\n       * @see ResourceUsageInfo#getResolution()\n       */\n      public T resolution(String resolution) {\n         this.resolution = checkNotNull(resolution, \"resolution\");\n         return self();\n      }\n\n      /**\n       * @see ResourceUsageInfo#getUnit()\n       */\n      public T unit(String unit) {\n         this.unit = checkNotNull(unit, \"unit\");\n         return self();\n      }\n\n      public ResourceUsageInfo build() {\n         return new ResourceUsageInfo(resource, resolution, unit);\n      }\n\n      public T fromResourceUsageInfo(ResourceUsageInfo in) {\n         return this\n               .resource(in.getResource())\n               .resolution(in.getResolution())\n               .unit(in.getUnit());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String resource;\n   private final String resolution;\n   private final String unit;\n\n   @ConstructorProperties({\n         \"type\", \"resolution\", \"unit\"\n   })\n   protected ResourceUsageInfo(String resource, String resolution, String unit) {\n      this.resource = checkNotNull(resource, \"resource\");\n      this.resolution = checkNotNull(resolution, \"resolution\");\n      this.unit = checkNotNull(unit, \"unit\");\n   }\n\n   public String getResource() {\n      return this.resource;\n   }\n\n   public String getResolution() {\n      return this.resolution;\n   }\n\n   public String getUnit() {\n      return this.unit;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(resource, resolution, unit);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      ResourceUsageInfo that = ResourceUsageInfo.class.cast(obj);\n      return Objects.equal(this.resource, that.resource)\n            && Objects.equal(this.resolution, that.resolution)\n            && Objects.equal(this.unit, that.unit);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(\"\")\n            .add(\"resource\", resource).add(\"resolution\", resolution).add(\"unit\", unit);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/domain/ResourceUsageValue.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Detailed information on usage\n *\n * @see org.jclouds.glesys.domain.ServerStatus\n */\npublic class ResourceUsageValue {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromResourceUsage(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected double value;\n      protected Date timestamp;\n\n\n      /**\n       * @see ResourceUsageValue#getValue()\n       */\n      public T value(double value) {\n         this.value = value;\n         return self();\n      }\n\n      /**\n       * @see ResourceUsageValue#getTimestamp()\n       */\n      public T timestamp(Date timestamp) {\n         this.timestamp = checkNotNull(timestamp, \"timestamp\");\n         return self();\n      }\n\n      public ResourceUsageValue build() {\n         return new ResourceUsageValue(value, timestamp);\n      }\n\n      public T fromResourceUsage(ResourceUsageValue in) {\n         return this\n               .value(in.getValue())\n               .timestamp(in.getTimestamp());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final double value;\n   private final Date timestamp;\n\n   @ConstructorProperties({\n         \"value\", \"timestamp\"\n   })\n   protected ResourceUsageValue(double value, Date timestamp) {\n      this.value = value;\n      this.timestamp = checkNotNull(timestamp, \"timestamp\");\n   }\n\n   public double getValue() {\n      return this.value;\n   }\n\n   public Date getTimestamp() {\n      return this.timestamp;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(value, timestamp);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      ResourceUsageValue that = ResourceUsageValue.class.cast(obj);\n      return Objects.equal(this.value, that.value)\n            && Objects.equal(this.timestamp, that.timestamp);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(\"\").add(\"value\", value).add(\"timestamp\", timestamp);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/domain/Server.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport com.google.common.base.CaseFormat;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Listing of a server.\n *\n * @see <a href= \"https://customer.glesys.com/api.php?a=doc#server_list\" />\n */\npublic class Server {\n\n   /**\n    */\n   public static enum State {\n\n      RUNNING, LOCKED, STOPPED, UNRECOGNIZED;\n\n      public String value() {\n         return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name());\n      }\n\n      @Override\n      public String toString() {\n         return value();\n      }\n\n      public static State fromValue(String state) {\n         try {\n            return valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, checkNotNull(state, \"state\")));\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n   }\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromServer(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String id;\n      protected String hostname;\n      protected String datacenter;\n      protected String platform;\n\n      /**\n       * @see Server#getId()\n       */\n      public T id(String id) {\n         this.id = checkNotNull(id, \"id\");\n         return self();\n      }\n\n      /**\n       * @see Server#getHostname()\n       */\n      public T hostname(String hostname) {\n         this.hostname = checkNotNull(hostname, \"hostname\");\n         return self();\n      }\n\n      /**\n       * @see Server#getDatacenter()\n       */\n      public T datacenter(String datacenter) {\n         this.datacenter = checkNotNull(datacenter, \"datacenter\");\n         return self();\n      }\n\n      /**\n       * @see Server#getPlatform()\n       */\n      public T platform(String platform) {\n         this.platform = checkNotNull(platform, \"platform\");\n         return self();\n      }\n\n      public Server build() {\n         return new Server(id, hostname, datacenter, platform);\n      }\n\n      public T fromServer(Server in) {\n         return this.id(in.getId()).hostname(in.getHostname()).datacenter(in.getDatacenter()).platform(in.getPlatform());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String id;\n   private final String hostname;\n   private final String datacenter;\n   private final String platform;\n\n   @ConstructorProperties({\n         \"serverid\", \"hostname\", \"datacenter\", \"platform\"\n   })\n   protected Server(String id, String hostname, String datacenter, String platform) {\n      this.id = checkNotNull(id, \"id\");\n      this.hostname = checkNotNull(hostname, \"hostname\");\n      this.datacenter = checkNotNull(datacenter, \"datacenter\");\n      this.platform = checkNotNull(platform, \"platform\");\n   }\n\n   /**\n    * @return the generated id of the server\n    */\n   public String getId() {\n      return this.id;\n   }\n\n   /**\n    * @return the hostname of the server\n    */\n   public String getHostname() {\n      return this.hostname;\n   }\n\n   /**\n    * @return platform running the server (ex. {@code OpenVZ})\n    */\n   public String getDatacenter() {\n      return this.datacenter;\n   }\n\n   /**\n    * @return the datacenter the server exists in (ex. {@code Falkenberg})\n    */\n   public String getPlatform() {\n      return this.platform;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Server that = Server.class.cast(obj);\n      return Objects.equal(this.id, that.id);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(\"\").add(\"id\", id).add(\"hostname\", hostname).add(\"datacenter\", datacenter)\n            .add(\"platform\", platform);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/domain/ServerDetails.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Detailed information about a server such as cpuCores, hardware configuration\n * (cpu, memory and disk), ip addresses, cost, transfer, os and more.\n *\n * @see <a href= \"https://customer.glesys.com/api.php?a=doc#server_details\" />\n */\npublic class ServerDetails extends Server {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromServerDetails(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> extends Server.Builder<T> {\n      protected Server.State state;\n      protected String description;\n      protected String templateName;\n      protected int cpuCores;\n      protected int memorySizeMB;\n      protected int diskSizeGB;\n      protected int transferGB;\n      protected Cost cost;\n      protected Set<Ip> ips = ImmutableSet.of();\n\n      /**\n       * @see ServerDetails#getState()\n       */\n      public T state(Server.State state) {\n         this.state = checkNotNull(state, \"state\");\n         return self();\n      }\n\n      /**\n       * @see ServerDetails#getDescription()\n       */\n      public T description(String description) {\n         this.description = checkNotNull(description, \"description\");\n         return self();\n      }\n\n      /**\n       * @see ServerDetails#getTemplateName()\n       */\n      public T templateName(String templateName) {\n         this.templateName = checkNotNull(templateName, \"templateName\");\n         return self();\n      }\n\n      /**\n       * @see ServerDetails#getCpuCores()\n       */\n      public T cpuCores(int cpuCores) {\n         this.cpuCores = cpuCores;\n         return self();\n      }\n\n      /**\n       * @see ServerDetails#getMemorySizeMB()\n       */\n      public T memorySizeMB(int memorySizeMB) {\n         this.memorySizeMB = memorySizeMB;\n         return self();\n      }\n\n      /**\n       * @see ServerDetails#getDiskSizeGB()\n       */\n      public T diskSizeGB(int diskSizeGB) {\n         this.diskSizeGB = diskSizeGB;\n         return self();\n      }\n\n      /**\n       * @see ServerDetails#getTransferGB()\n       */\n      public T transferGB(int transferGB) {\n         this.transferGB = transferGB;\n         return self();\n      }\n\n      /**\n       * @see ServerDetails#getCost()\n       */\n      public T cost(Cost cost) {\n         this.cost = checkNotNull(cost, \"cost\");\n         return self();\n      }\n\n      /**\n       * @see ServerDetails#getIps()\n       */\n      public T ips(Set<Ip> ips) {\n         this.ips = ImmutableSet.copyOf(checkNotNull(ips, \"ips\"));\n         return self();\n      }\n\n      public T ips(Ip... in) {\n         return ips(ImmutableSet.copyOf(in));\n      }\n\n      public ServerDetails build() {\n         return new ServerDetails(id, hostname, datacenter, platform, state, description, templateName, cpuCores, memorySizeMB, diskSizeGB, transferGB, cost, ips);\n      }\n\n      public T fromServerDetails(ServerDetails in) {\n         return super.fromServer(in)\n               .state(in.getState())\n               .description(in.getDescription())\n               .templateName(in.getTemplateName())\n               .cpuCores(in.getCpuCores())\n               .memorySizeMB(in.getMemorySizeMB())\n               .diskSizeGB(in.getDiskSizeGB())\n               .transferGB(in.getTransferGB())\n               .cost(in.getCost())\n               .ips(in.getIps());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final Server.State state;\n   private final String description;\n   private final String templateName;\n   private final int cpuCores;\n   private final int memorySizeMB;\n   private final int diskSizeGB;\n   private final int transferGB;\n   private final Cost cost;\n   private final Set<Ip> ips;\n\n   @ConstructorProperties({\n         \"serverid\", \"hostname\", \"datacenter\", \"platform\", \"state\", \"description\", \"templatename\", \"cpucores\",\n         \"memorysize\", \"disksize\", \"transfer\", \"cost\", \"iplist\"\n   })\n   protected ServerDetails(String id, String hostname, String datacenter, String platform, @Nullable Server.State state,\n                           @Nullable String description, String templateName, int cpuCores, int memorySizeMB,\n                           int diskSizeGB, int transferGB, Cost cost, @Nullable Set<Ip> ips) {\n      super(id, hostname, datacenter, platform);\n      this.state = state;\n      this.description = description;\n      this.templateName = checkNotNull(templateName, \"templateName\");\n      this.cpuCores = cpuCores;\n      this.memorySizeMB = memorySizeMB;\n      this.diskSizeGB = diskSizeGB;\n      this.transferGB = transferGB;\n      this.cost = checkNotNull(cost, \"cost\");\n      this.ips = ips == null ? ImmutableSet.<Ip>of() : ImmutableSet.copyOf(checkNotNull(ips, \"ips\"));\n   }\n\n   /**\n    * @return the state of the server (e.g. \"running\")\n    */\n   public Server.State getState() {\n      return this.state;\n   }\n\n   /**\n    * @return the user-specified description of the server\n    */\n   public String getDescription() {\n      return this.description;\n   }\n\n   /**\n    * @return the name of the template used to create the server\n    */\n   public String getTemplateName() {\n      return this.templateName;\n   }\n\n   /**\n    * @return number of cores on the server\n    */\n   public int getCpuCores() {\n      return this.cpuCores;\n   }\n\n   /**\n    * @return the memory of the server in MB\n    */\n   public int getMemorySizeMB() {\n      return this.memorySizeMB;\n   }\n\n   /**\n    * @return the disk of the server in GB\n    */\n   public int getDiskSizeGB() {\n      return this.diskSizeGB;\n   }\n\n   /**\n    * @return the transfer of the server\n    */\n   public int getTransferGB() {\n      return this.transferGB;\n   }\n\n   /**\n    * @return details of the cost of the server\n    */\n   public Cost getCost() {\n      return this.cost;\n   }\n\n   /**\n    * @return the ip addresses assigned to the server\n    */\n   public Set<Ip> getIps() {\n      return this.ips;\n   }\n\n   protected ToStringHelper string() {\n      return super.string().add(\"state\", state).add(\"description\", description).add(\"templateName\", templateName)\n            .add(\"cpuCores\", cpuCores).add(\"memorySizeMB\", memorySizeMB).add(\"diskSizeGB\", diskSizeGB)\n            .add(\"transferGB\", transferGB).add(\"cost\", cost).add(\"ips\", ips);\n   }\n\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/domain/ServerLimit.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Detailed information about an OpenVZ server's limits\n *\n * @see <a href= \"https://customer.glesys.com/api.php?a=doc#server_limits\" />\n */\npublic class ServerLimit {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromServerLimit(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected long held;\n      protected long maxHeld;\n      protected long barrier;\n      protected long limit;\n      protected long failCount;\n\n      /**\n       * @see ServerLimit#getHeld()\n       */\n      public T held(long held) {\n         this.held = held;\n         return self();\n      }\n\n      /**\n       * @see ServerLimit#getMaxHeld()\n       */\n      public T maxHeld(long maxHeld) {\n         this.maxHeld = maxHeld;\n         return self();\n      }\n\n      /**\n       * @see ServerLimit#getBarrier()\n       */\n      public T barrier(long barrier) {\n         this.barrier = barrier;\n         return self();\n      }\n\n      /**\n       * @see ServerLimit#getLimit()\n       */\n      public T limit(long limit) {\n         this.limit = limit;\n         return self();\n      }\n\n      /**\n       * @see ServerLimit#getFailCount()\n       */\n      public T failCount(long failCount) {\n         this.failCount = failCount;\n         return self();\n      }\n\n      public ServerLimit build() {\n         return new ServerLimit(held, maxHeld, barrier, limit, failCount);\n      }\n\n      public T fromServerLimit(ServerLimit in) {\n         return this.held(in.getHeld())\n               .maxHeld(in.getMaxHeld())\n               .barrier(in.getBarrier())\n               .limit(in.getLimit())\n               .failCount(in.getFailCount());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final long held;\n   private final long maxHeld;\n   private final long barrier;\n   private final long limit;\n   private final long failCount;\n\n   @ConstructorProperties({\n         \"held\", \"maxHeld\", \"barrier\", \"limit\", \"failCount\"\n   })\n   protected ServerLimit(long held, long maxHeld, long barrier, long limit, long failCount) {\n      this.held = held;\n      this.maxHeld = maxHeld;\n      this.barrier = barrier;\n      this.limit = limit;\n      this.failCount = failCount;\n   }\n\n   public long getHeld() {\n      return this.held;\n   }\n\n   public long getMaxHeld() {\n      return this.maxHeld;\n   }\n\n   public long getBarrier() {\n      return this.barrier;\n   }\n\n   public long getLimit() {\n      return this.limit;\n   }\n\n   public long getFailCount() {\n      return this.failCount;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(held, maxHeld, barrier, limit, failCount);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      ServerLimit that = ServerLimit.class.cast(obj);\n      return Objects.equal(this.held, that.held)\n            && Objects.equal(this.maxHeld, that.maxHeld)\n            && Objects.equal(this.barrier, that.barrier)\n            && Objects.equal(this.limit, that.limit)\n            && Objects.equal(this.failCount, that.failCount);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(\"\").add(\"held\", held).add(\"maxHeld\", maxHeld).add(\"barrier\", barrier)\n            .add(\"limit\", limit).add(\"failCount\", failCount);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/domain/ServerSpec.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Class ServerSpec\n */\npublic class ServerSpec {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromServerSpec(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected String platform;\n      protected String datacenter;\n      protected int memorySizeMB;\n      protected int diskSizeGB;\n      protected String templateName;\n      protected int cpuCores;\n      protected int transferGB;\n\n      /**\n       * @see ServerSpec#getPlatform()\n       */\n      public T platform(String platform) {\n         this.platform = checkNotNull(platform, \"platform\");\n         return self();\n      }\n\n      /**\n       * @see ServerSpec#getDatacenter()\n       */\n      public T datacenter(String datacenter) {\n         this.datacenter = checkNotNull(datacenter, \"datacenter\");\n         return self();\n      }\n\n      /**\n       * @see ServerSpec#getMemorySizeMB()\n       */\n      public T memorySizeMB(int memorySizeMB) {\n         this.memorySizeMB = memorySizeMB;\n         return self();\n      }\n\n      /**\n       * @see ServerSpec#getDiskSizeGB()\n       */\n      public T diskSizeGB(int diskSizeGB) {\n         this.diskSizeGB = diskSizeGB;\n         return self();\n      }\n\n      /**\n       * @see ServerSpec#getTemplateName()\n       */\n      public T templateName(String templateName) {\n         this.templateName = checkNotNull(templateName, \"templateName\");\n         return self();\n      }\n\n      /**\n       * @see ServerSpec#getCpuCores()\n       */\n      public T cpuCores(int cpuCores) {\n         this.cpuCores = cpuCores;\n         return self();\n      }\n\n      /**\n       * @see ServerSpec#getTransferGB()\n       */\n      public T transferGB(int transferGB) {\n         this.transferGB = transferGB;\n         return self();\n      }\n\n      public ServerSpec build() {\n         return new ServerSpec(platform, datacenter, memorySizeMB, diskSizeGB, templateName, cpuCores, transferGB);\n      }\n\n      public T fromServerSpec(ServerSpec in) {\n         return this.platform(in.getPlatform())\n               .datacenter(in.getDatacenter())\n               .memorySizeMB(in.getMemorySizeMB())\n               .diskSizeGB(in.getDiskSizeGB())\n               .templateName(in.getTemplateName())\n               .cpuCores(in.getCpuCores())\n               .transferGB(in.getTransferGB());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String platform;\n   private final String datacenter;\n   private final int memorySizeMB;\n   private final int diskSizeGB;\n   private final String templateName;\n   private final int cpuCores;\n   private final int transferGB;\n\n   @ConstructorProperties({\n         \"platform\", \"datacenter\", \"memorySizeMB\", \"diskSizeGB\", \"templateName\", \"cpuCores\", \"transferGB\"\n   })\n   protected ServerSpec(String platform, String datacenter, int memorySizeMB, int diskSizeGB, String templateName, int cpuCores, int transferGB) {\n      this.platform = checkNotNull(platform, \"platform\");\n      this.datacenter = checkNotNull(datacenter, \"datacenter\");\n      this.memorySizeMB = memorySizeMB;\n      this.diskSizeGB = diskSizeGB;\n      this.templateName = checkNotNull(templateName, \"templateName\");\n      this.cpuCores = cpuCores;\n      this.transferGB = transferGB;\n   }\n\n   /**\n    * @return the data center to create the new server in\n    */\n   public String getPlatform() {\n      return this.platform;\n   }\n\n   /**\n    * @return the platform to use (i.e. \"Xen\" or \"OpenVZ\")\n    */\n   public String getDatacenter() {\n      return this.datacenter;\n   }\n\n   /**\n    * @return the os template to use to create the new server\n    */\n   public int getMemorySizeMB() {\n      return this.memorySizeMB;\n   }\n\n   /**\n    * @return the amount of disk space, in GB, to allocate\n    */\n   public int getDiskSizeGB() {\n      return this.diskSizeGB;\n   }\n\n   /**\n    * @return the memory, in MB, to allocate\n    */\n   public String getTemplateName() {\n      return this.templateName;\n   }\n\n   /**\n    * @return the number of CPU cores to allocate\n    */\n   public int getCpuCores() {\n      return this.cpuCores;\n   }\n\n   /**\n    * @return bandwidth of in GB\n    */\n   public int getTransferGB() {\n      return this.transferGB;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(platform, datacenter, memorySizeMB, diskSizeGB, templateName, cpuCores, transferGB);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      ServerSpec that = ServerSpec.class.cast(obj);\n      return Objects.equal(this.platform, that.platform)\n            && Objects.equal(this.datacenter, that.datacenter)\n            && Objects.equal(this.memorySizeMB, that.memorySizeMB)\n            && Objects.equal(this.diskSizeGB, that.diskSizeGB)\n            && Objects.equal(this.templateName, that.templateName)\n            && Objects.equal(this.cpuCores, that.cpuCores)\n            && Objects.equal(this.transferGB, that.transferGB);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(\"\").add(\"platform\", platform).add(\"datacenter\", datacenter)\n            .add(\"memorySizeMB\", memorySizeMB).add(\"diskSizeGB\", diskSizeGB).add(\"templateName\", templateName)\n            .add(\"cpuCores\", cpuCores).add(\"transferGB\", transferGB);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/domain/ServerStatus.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Detailed information server status including hardware usage (cpu, memory and disk), bandwidth and up-time.\n *\n * @see <a href= \"https://customer.glesys.com/api.php?a=doc#server_status\" />\n */\npublic class ServerStatus {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromServerStatus(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected Server.State state;\n      protected ResourceStatus cpu;\n      protected ResourceStatus memory;\n      protected ResourceStatus disk;\n      protected ServerUptime uptime;\n\n      /**\n       * @see ServerStatus#getState()\n       */\n      public T state(Server.State state) {\n         this.state = checkNotNull(state, \"state\");\n         return self();\n      }\n\n      /**\n       * @see ServerStatus#getCpu()\n       */\n      public T cpu(ResourceStatus cpu) {\n         this.cpu = checkNotNull(cpu, \"cpu\");\n         return self();\n      }\n\n      /**\n       * @see ServerStatus#getMemory()\n       */\n      public T memory(ResourceStatus memory) {\n         this.memory = checkNotNull(memory, \"memory\");\n         return self();\n      }\n\n      /**\n       * @see ServerStatus#getDisk()\n       */\n      public T disk(ResourceStatus disk) {\n         this.disk = checkNotNull(disk, \"disk\");\n         return self();\n      }\n\n      /**\n       * @see ServerStatus#getUptime()\n       */\n      public T uptime(ServerUptime uptime) {\n         this.uptime = checkNotNull(uptime, \"uptime\");\n         return self();\n      }\n\n      public ServerStatus build() {\n         return new ServerStatus(state, cpu, memory, disk, uptime);\n      }\n\n      public T fromServerStatus(ServerStatus in) {\n         return this.state(in.getState()).cpu(in.getCpu()).memory(in.getMemory()).disk(in.getDisk()).uptime(in.getUptime());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final Server.State state;\n   private final ResourceStatus cpu;\n   private final ResourceStatus memory;\n   private final ResourceStatus disk;\n   private final ServerUptime uptime;\n\n   @ConstructorProperties({\n         \"state\", \"cpu\", \"memory\", \"disk\", \"uptime\"\n   })\n   protected ServerStatus(Server.State state, @Nullable ResourceStatus cpu, @Nullable ResourceStatus memory,\n                          @Nullable ResourceStatus disk, @Nullable ServerUptime uptime) {\n      this.state = checkNotNull(state, \"state\");\n      this.cpu = cpu;\n      this.memory = memory;\n      this.disk = disk;\n      this.uptime = uptime;\n   }\n\n   /**\n    * @return the state of the server (e.g. \"running\")\n    */\n   @Nullable\n   public Server.State getState() {\n      return this.state;\n   }\n\n   /**\n    * @return CPU usage information\n    */\n   @Nullable\n   public ResourceStatus getCpu() {\n      return this.cpu;\n   }\n\n   /**\n    * @return details of memory usage and limits\n    */\n   @Nullable\n   public ResourceStatus getMemory() {\n      return this.memory;\n   }\n\n   /**\n    * @return details of disk usage and limits\n    */\n   @Nullable\n   public ResourceStatus getDisk() {\n      return this.disk;\n   }\n\n   /**\n    * @return the uptime of the server\n    */\n   @Nullable\n   public ServerUptime getUptime() {\n      return this.uptime;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(state, cpu, memory, disk, uptime);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      ServerStatus that = ServerStatus.class.cast(obj);\n      return Objects.equal(this.state, that.state)\n            && Objects.equal(this.cpu, that.cpu)\n            && Objects.equal(this.memory, that.memory)\n            && Objects.equal(this.disk, that.disk)\n            && Objects.equal(this.uptime, that.uptime);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(\"\")\n            .add(\"state\", state).add(\"cpu\", cpu).add(\"memory\", memory).add(\"disk\", disk).add(\"uptime\", uptime);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/domain/ServerUptime.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Represents an 'uptime' duration of server in a Glesys cloud\n *\n * @see ServerStatus\n */\npublic class ServerUptime {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromServerUptime(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected long current;\n      protected String unit;\n\n      /**\n       * @see ServerUptime#getCurrent()\n       */\n      public T current(long current) {\n         this.current = current;\n         return self();\n      }\n\n      /**\n       * @see ServerUptime#getUnit()\n       */\n      public T unit(String unit) {\n         this.unit = checkNotNull(unit, \"unit\");\n         return self();\n      }\n\n      public ServerUptime build() {\n         return new ServerUptime(current, unit);\n      }\n\n      public T fromServerUptime(ServerUptime in) {\n         return this.current(in.getCurrent()).unit(in.getUnit());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final long current;\n   private final String unit;\n\n   @ConstructorProperties({\n         \"current\", \"unit\"\n   })\n   protected ServerUptime(long current, String unit) {\n      this.current = current;\n      this.unit = checkNotNull(unit, \"unit\");\n   }\n\n   /**\n    * @return the time the server has been up in #getUnit()\n    */\n   public long getCurrent() {\n      return this.current;\n   }\n\n   /**\n    * @return the unit used for #getCurrent()\n    */\n   public String getUnit() {\n      return this.unit;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(current, unit);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      ServerUptime that = ServerUptime.class.cast(obj);\n      return Objects.equal(this.current, that.current) && Objects.equal(this.unit, that.unit);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(\"\").add(\"current\", current).add(\"unit\", unit);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/features/ArchiveApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.FormParam;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks;\nimport org.jclouds.glesys.domain.Archive;\nimport org.jclouds.glesys.domain.ArchiveAllowedArguments;\nimport org.jclouds.http.filters.BasicAuthentication;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\nimport com.google.common.collect.FluentIterable;\n\n/**\n * Provides synchronous access to Archive requests.\n * <p/>\n *\n * @see <a href=\"https://github.com/GleSYS/API/wiki/API-Documentation\" />\n */\n@RequestFilters(BasicAuthentication.class)\npublic interface ArchiveApi {\n\n   /**\n    * Lists all active disks on this account.\n    */\n   @Named(\"archive:list\")\n   @POST\n   @Path(\"/archive/list/format/json\")\n   @SelectJson(\"archives\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(Fallbacks.EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<Archive> list();\n\n   /**\n    * Get detailed information about an archive volume.\n    *\n    * @param username the username associated with the archive\n    * @return the archive information or null if not found\n    */\n   @Named(\"archive:details\")\n   @POST\n   @Path(\"/archive/details/format/json\")\n   @SelectJson(\"details\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(Fallbacks.NullOnNotFoundOr404.class)\n   Archive get(@FormParam(\"username\") String username);\n\n   /**\n    * Create a new backup volume.\n    *\n    * @param username the archive username, this must be prefixed by Glesys account name (in lower case) and an\n    *                 underscore, ex. \"c100005_archive1\"\n    * @param password the new password\n    * @param size     the new size required in GB\n    */\n   @Named(\"archive:create\")\n   @POST\n   @Path(\"/archive/create/format/json\")\n   @SelectJson(\"details\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   Archive createWithCredentialsAndSize(@FormParam(\"username\") String username, @FormParam(\"password\") String password,\n                                        @FormParam(\"size\")int size);\n\n   /**\n    * Delete an archive volume. All files on the volume\n    *\n    * @param username the username associated with the archive\n    */\n   @Named(\"archive:delete\")\n   @POST\n   @Path(\"/archive/delete/format/json\")\n   void delete(@FormParam(\"username\") String username);\n\n   /**\n    * Resize an archive volume. It is only possible to upgrade the size of the disk. Downgrading is currently not\n    * supported. If you need to downgrade, please create a new volume and transfer all data to the new volume.\n    * Then delete the old volume.\n    *\n    * @param username the username associated with the archive\n    * @param size     the new size required, see #getAllowedArguments for valid values\n    */\n   @Named(\"archive:resize\")\n   @POST\n   @Path(\"/archive/resize/format/json\")\n   @SelectJson(\"details\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   Archive resize(@FormParam(\"username\") String username, @FormParam(\"size\") int size);\n\n   /**\n    * Change the password for an archive user.\n    *\n    * @param username the archive username\n    * @param password the new password\n    */\n   @Named(\"archive:changepassword\")\n   @POST\n   @Path(\"/archive/changepassword/format/json\")\n   @SelectJson(\"details\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   Archive changePassword(@FormParam(\"username\") String username, @FormParam(\"password\") String password);\n\n   /**\n    * Lists the allowed arguments for some of the functions in this module such as archive size.\n    */\n   @Named(\"archive:allowedarguments\")\n   @GET\n   @Path(\"/archive/allowedarguments/format/json\")\n   @SelectJson(\"argumentslist\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(Fallbacks.NullOnNotFoundOr404.class)\n   ArchiveAllowedArguments getAllowedArguments();\n\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/features/DomainApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.features;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.FormParam;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks;\nimport org.jclouds.glesys.domain.Domain;\nimport org.jclouds.glesys.domain.DomainRecord;\nimport org.jclouds.glesys.options.AddDomainOptions;\nimport org.jclouds.glesys.options.AddRecordOptions;\nimport org.jclouds.glesys.options.DomainOptions;\nimport org.jclouds.glesys.options.UpdateRecordOptions;\nimport org.jclouds.http.filters.BasicAuthentication;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\nimport com.google.common.collect.FluentIterable;\n\n/**\n * Provides synchronous access to Domain requests.\n * <p/>\n *\n * @see <a href=\"https://github.com/GleSYS/API/wiki/API-Documentation\" />\n */\n@RequestFilters(BasicAuthentication.class)\npublic interface DomainApi {\n\n   /**\n    * Get a list of all domains for this account.\n    *\n    * @return an account's associated domain objects.\n    */\n   @Named(\"domain:list\")\n   @POST\n   @Path(\"/domain/list/format/json\")\n   @SelectJson(\"domains\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(Fallbacks.EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<Domain> list();\n\n   /**\n    * Get a specific domain.\n    *\n    * @return the requested domain object.\n    */\n   @Named(\"domain:details\")\n   @POST\n   @Path(\"/domain/details/format/json\")\n   @SelectJson(\"domain\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(Fallbacks.NullOnNotFoundOr404.class)\n   Domain get(@FormParam(\"domainname\") String name);\n\n   /**\n    * Add a domain to the Glesys dns-system\n    *\n    * @param name  the name of the domain to add.\n    * @param options optional parameters\n    * @return information about the added domain\n    */\n   @Named(\"domain:add\")\n   @POST\n   @Path(\"/domain/add/format/json\")\n   @SelectJson(\"domain\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   Domain create(@FormParam(\"domainname\") String name, AddDomainOptions... options);\n\n   /**\n    * Update a domain to the Glesys dns-system\n    *\n    * @param domain  the name of the domain to add.\n    * @param options optional parameters\n    * @return information about the modified domain\n    */\n   @Named(\"domain:edit\")\n   @POST\n   @Path(\"/domain/edit/format/json\")\n   @SelectJson(\"domain\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   Domain update(@FormParam(\"domainname\") String domain, DomainOptions options);\n\n   /**\n    * Remove a domain to the Glesys dns-system\n    *\n    * @param domain the name of the domain to remove\n    */\n   @Named(\"domain:delete\")\n   @POST\n   @Path(\"/domain/delete/format/json\")\n   void delete(@FormParam(\"domainname\") String domain);\n\n   /**\n    * Retrieve the DNS records for a given domain\n    *\n    * @param domain the name of the domain to retrieve records for\n    */\n   @Named(\"domain:listrecords\")\n   @POST\n   @Path(\"/domain/listrecords/format/json\")\n   @SelectJson(\"records\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   Set<DomainRecord> listRecords(@FormParam(\"domainname\") String domain);\n\n   /**\n    * Add a DNS Record\n    *\n    * @param domain  the domain to add the record to\n    * @param options optional settings for the record\n    */\n   @Named(\"domain:addrecord\")\n   @POST\n   @Path(\"/domain/addrecord/format/json\")\n   @SelectJson(\"record\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   DomainRecord createRecord(@FormParam(\"domainname\") String domain, @FormParam(\"host\") String host,\n                                               @FormParam(\"type\") String type, @FormParam(\"data\") String data,\n                                               AddRecordOptions... options);\n\n   /**\n    * Modify a specific DNS Record\n    *\n    * @param recordId the id for the record to edit\n    * @param options  the settings to change\n    * @see #listRecords to retrieve the necessary ids\n    */\n   @Named(\"domain:updaterecord\")\n   @POST\n   @Path(\"/domain/updaterecord/format/json\")\n   @SelectJson(\"record\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   DomainRecord updateRecord(@FormParam(\"recordid\") String recordId, UpdateRecordOptions options);\n\n   /**\n    * Delete a DNS record\n    *\n    * @param recordId the id for the record to delete\n    * @see #listRecords to retrieve the necessary ids\n    */\n   @Named(\"domain:deleterecord\")\n   @POST\n   @Path(\"/domain/deleterecord/format/json\")\n   void deleteRecord(@FormParam(\"recordid\") String recordId);\n\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/features/EmailAccountApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.FormParam;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks;\nimport org.jclouds.glesys.domain.EmailAccount;\nimport org.jclouds.glesys.domain.EmailAlias;\nimport org.jclouds.glesys.domain.EmailOverview;\nimport org.jclouds.glesys.options.CreateAccountOptions;\nimport org.jclouds.glesys.options.UpdateAccountOptions;\nimport org.jclouds.http.filters.BasicAuthentication;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\nimport com.google.common.collect.FluentIterable;\n\n/**\n * Provides synchronous access to E-Mail requests.\n * <p/>\n *\n * @see <a href=\"https://github.com/GleSYS/API/wiki/API-Documentation\" />\n */\n@RequestFilters(BasicAuthentication.class)\npublic interface EmailAccountApi {\n\n   /**\n    * Get a summary of e-mail accounts associated with this Glesys account\n    *\n    * @return the relevant summary data\n    */\n   @Named(\"email:overview\")\n   @POST\n   @Path(\"/email/overview/format/json\")\n   @SelectJson(\"overview\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(Fallbacks.NullOnNotFoundOr404.class)\n   EmailOverview getOverview();\n\n   /**\n    * Get the set of detailed information about e-mail accounts\n    *\n    * @return the relevant set of details\n    */\n   @Named(\"email:list:accounts\")\n   @POST\n   @Path(\"/email/list/format/json\")\n   @SelectJson(\"emailaccounts\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(Fallbacks.EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<EmailAccount> listDomain(@FormParam(\"domainname\") String domain);\n\n   /**\n    * Get the set of details about e-mail aliases\n    *\n    * @return the relevant set of details\n    */\n   @Named(\"email:list:aliases\")\n   @POST\n   @Path(\"/email/list/format/json\")\n   @SelectJson(\"emailaliases\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(Fallbacks.EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<EmailAlias> listAliasesInDomain(@FormParam(\"domainname\") String domain);\n\n   /**\n    * Create a new e-mail account\n    *\n    * @param accountAddress the e-mail address to use (the domain should already exist)\n    * @param password       the password to use for the mailbox\n    * @param options        optional parameters\n    * @see DomainApi#create\n    */\n   @Named(\"email:createaccount\")\n   @POST\n   @Consumes(MediaType.APPLICATION_JSON)\n   @SelectJson(\"emailaccount\")\n   @Path(\"/email/createaccount/format/json\")\n   EmailAccount createWithPassword(@FormParam(\"emailaccount\") String accountAddress, @FormParam(\"password\") String password, CreateAccountOptions... options);\n\n   /**\n    * Create an e-mail alias for an e-mail account\n    *\n    * @param aliasAddress   the address to use for the alias  (the domain should already exist)\n    * @param toEmailAddress the existing e-mail account address the alias should forward to\n    * @see DomainApi#create\n    */\n   @Named(\"email:createalias\")\n   @POST\n   @Consumes(MediaType.APPLICATION_JSON)\n   @SelectJson(\"alias\")\n   @Path(\"/email/createalias/format/json\")\n   EmailAlias createAlias(@FormParam(\"emailalias\") String aliasAddress, @FormParam(\"goto\") String toEmailAddress);\n\n   /**\n    * Adjust an e-mail account's settings\n    *\n    * @param accountAddress the existing e-mail account address\n    * @param options        optional parameters\n    */\n   @Named(\"email:editaccount\")\n   @POST\n   @Consumes(MediaType.APPLICATION_JSON)\n   @SelectJson(\"emailaccount\")\n   @Path(\"/email/editaccount/format/json\")\n   EmailAccount update(@FormParam(\"emailaccount\") String accountAddress, UpdateAccountOptions... options);\n\n   /**\n    * Adjust (re-target) an e-mail alias\n    *\n    * @param aliasAddress   the existing alias e-mail address\n    * @param toEmailAddress the existing e-mail account address the alias should forward to\n    */\n   @Named(\"email:editalias\")\n   @POST\n   @Consumes(MediaType.APPLICATION_JSON)\n   @SelectJson(\"alias\")\n   @Path(\"/email/editalias/format/json\")\n   EmailAlias updateAlias(@FormParam(\"emailalias\") String aliasAddress, @FormParam(\"goto\") String toEmailAddress);\n\n   /**\n    * Delete an e-mail account or alias\n    *\n    * @param accountAddress the existing alias e-mail account or alias address\n    */\n   @Named(\"email:delete\")\n   @POST\n   @Path(\"/email/delete/format/json\")\n   @Fallback(Fallbacks.TrueOnNotFoundOr404.class)\n   boolean delete(@FormParam(\"email\") String accountAddress);\n\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/features/IpApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.FormParam;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks;\nimport org.jclouds.glesys.domain.IpDetails;\nimport org.jclouds.glesys.options.ListIpOptions;\nimport org.jclouds.http.filters.BasicAuthentication;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.FormParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\n\nimport com.google.common.collect.FluentIterable;\n\n/**\n * Provides synchronous access to IP Addresses.\n * <p/>\n *\n * @see <a href=\"https://github.com/GleSYS/API/wiki/API-Documentation\" />\n */\n@RequestFilters(BasicAuthentication.class)\npublic interface IpApi {\n   /**\n    * Get a set of all IP addresses that are available and not used on any account or server.\n    *\n    * @param ipVersion  4 or 6, for IPV4 or IPV6, respectively\n    * @param datacenter the datacenter\n    * @param platform   the platform\n    * @return a set of free IP addresses\n    */\n   @Named(\"ip:listfree\")\n   @GET\n   @Path(\"/ip/listfree/ipversion/{ipversion}/datacenter/{datacenter}/platform/{platform}/format/json\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @SelectJson(\"ipaddresses\")\n   @Fallback(Fallbacks.EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<String> listFree(@PathParam(\"ipversion\") int ipVersion,\n                                   @PathParam(\"datacenter\") String datacenter,\n                                   @PathParam(\"platform\") String platform);\n\n   /**\n    * Take a free IP address and add it to this account. You can list free IP addresses with the function listFree().\n    * Once your free IP on this account you can add it to a server with the add() function.\n    *\n    * @param ipAddress the IP address to be add to this account (reserve)\n    */\n   @Named(\"ip:take\")\n   @POST\n   @Path(\"/ip/take/format/json\")\n   @SelectJson(\"details\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   IpDetails take(@FormParam(\"ipaddress\") String ipAddress);\n\n   /**\n    * Return an unused IP address to the pool of free ips. If the IP address is allocated to a server,\n    * it must first be removed by calling remove(ipAddress) before it can be released.\n    *\n    * @param ipAddress the IP address to be released\n    */\n   @Named(\"ip:release\")\n   @POST\n   @Path(\"/ip/release/format/json\")\n   @SelectJson(\"details\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   IpDetails release(@FormParam(\"ipaddress\") String ipAddress);\n\n   /**\n    * Get IP addresses associated with your account (reserved, assigned to servers, etc)\n    *\n    * @param options options to filter the results (by IPV4/6, serverId, etc)\n    * @return the set of IP addresses\n    */\n   @Named(\"ip:listown\")\n   @GET\n   @Path(\"/ip/listown/format/json\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @SelectJson(\"iplist\")\n   @Fallback(Fallbacks.EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<IpDetails> list(ListIpOptions... options);\n\n   /**\n    * Get details about the given IP address such as gateway and netmask. Different details are available\n    * on different platforms.\n    *\n    * @param ipAddress the ip address\n    * @return details about the given IP address\n    */\n   @Named(\"ip:details\")\n   @GET\n   @Path(\"/ip/details/ipaddress/{ipaddress}/format/json\")\n   @SelectJson(\"details\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(Fallbacks.NullOnNotFoundOr404.class)\n   IpDetails get(@PathParam(\"ipaddress\") String ipAddress);\n\n   /**\n    * Add an IP address to an server. The IP has to be free, but reserved to this account. You are able to list such addresses\n    * with listOwn() and reserve an address for this account by using take(). To find free ips you can use ip/listfree\n    * ip to an Xen-server you have to configure the server yourself, unless the ip was added during the c\n    * server (server/create). You can get detailed information such as gateway and netmask using the ip\n    *\n    * @param ipAddress the IP address to remove\n    * @param serverId  the server to add the IP address to\n    */\n   @Named(\"ip:add\")\n   @POST\n   @Path(\"/ip/add/format/json\")\n   @SelectJson(\"details\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   IpDetails addToServer(@FormParam(\"ipaddress\") String ipAddress,\n                         @FormParam(\"serverid\") String serverId);\n\n   /**\n    * Remove an IP address from a server. This does not release it back to GleSYS pool of free ips. The address will be\n    * kept on the account so that you can use it for other servers or the same server at a later time. To completely remove\n    * the IP address from this account, use removeFromServerAndRelease to do so\n    *\n    * @param ipAddress the IP address to remove\n    * @param serverId  the server to remove the IP address from\n    * @see #removeFromServerAndRelease\n    */\n   @Named(\"ip:remove\")\n   @POST\n   @Path(\"/ip/remove/format/json\")\n   @SelectJson(\"details\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   IpDetails removeFromServer(@FormParam(\"ipaddress\") String ipAddress,\n                              @FormParam(\"serverid\") String serverId);\n\n   /**\n    * Remove an IP address from a server and release it back to GleSYS pool of free ips.\n    *\n    * @param ipAddress the IP address to remove\n    * @param serverId  the server to remove the IP address from\n    * @see #removeFromServer\n    */\n   @Named(\"ip:remove:release\")\n   @POST\n   @FormParams(keys = \"release\", values = \"true\")\n   @Path(\"/ip/remove/format/json\")\n   @SelectJson(\"details\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   IpDetails removeFromServerAndRelease(@FormParam(\"ipaddress\") String ipAddress,\n                                        @FormParam(\"serverid\") String serverId);\n\n   /**\n    * Sets PTR data for an IP. Use ip/listown or ip/details to get current PTR data\n    */\n   @Named(\"ip:setptr\")\n   @POST\n   @Path(\"/ip/setptr/format/json\")\n   @SelectJson(\"details\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   IpDetails setPtr(@FormParam(\"ipaddress\") String ipAddress,\n                    @FormParam(\"data\") String ptr);\n\n   /**\n    * Resets PTR data for an IP back to the default value\n    */\n   @Named(\"ip:resetptr\")\n   @POST\n   @Path(\"/ip/resetptr/format/json\")\n   @SelectJson(\"details\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   IpDetails resetPtr(@FormParam(\"ipaddress\") String ipAddress);\n\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/features/ServerApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.features;\n\nimport java.util.Map;\nimport java.util.SortedMap;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.FormParam;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks;\nimport org.jclouds.glesys.domain.AllowedArgumentsForCreateServer;\nimport org.jclouds.glesys.domain.Console;\nimport org.jclouds.glesys.domain.OSTemplate;\nimport org.jclouds.glesys.domain.ResourceUsage;\nimport org.jclouds.glesys.domain.Server;\nimport org.jclouds.glesys.domain.ServerDetails;\nimport org.jclouds.glesys.domain.ServerLimit;\nimport org.jclouds.glesys.domain.ServerSpec;\nimport org.jclouds.glesys.domain.ServerStatus;\nimport org.jclouds.glesys.functions.ParseTemplatesFromHttpResponse;\nimport org.jclouds.glesys.options.CloneServerOptions;\nimport org.jclouds.glesys.options.CreateServerOptions;\nimport org.jclouds.glesys.options.DestroyServerOptions;\nimport org.jclouds.glesys.options.ServerStatusOptions;\nimport org.jclouds.glesys.options.UpdateServerOptions;\nimport org.jclouds.http.filters.BasicAuthentication;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.FormParams;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\n\nimport com.google.common.collect.FluentIterable;\n\n/**\n * Provides synchronous access to Server.\n * <p/>\n *\n * @see <a href=\"https://github.com/GleSYS/API/wiki/API-Documentation\" />\n */\n@RequestFilters(BasicAuthentication.class)\npublic interface ServerApi {\n\n   /**\n    * Get a list of all servers on this account.\n    *\n    * @return an account's associated server objects.\n    */\n   @Named(\"server:list\")\n   @POST\n   @Path(\"/server/list/format/json\")\n   @SelectJson(\"servers\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(Fallbacks.EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<Server> list();\n\n   /**\n    * Get detailed information about a server such as hostname, hardware\n    * configuration (cpu, memory and disk), ip addresses, cost, transfer, os and\n    * more.\n    *\n    * @param id id of the server\n    * @return server or null if not found\n    */\n   @Named(\"server:details\")\n   @POST\n   @Path(\"/server/details/format/json\")\n   @SelectJson(\"server\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @FormParams(keys = \"includestate\", values = \"true\")\n   @Fallback(Fallbacks.NullOnNotFoundOr404.class)\n   ServerDetails get(@FormParam(\"serverid\") String id);\n\n   /**\n    * Get detailed information about a server status including up-time and\n    * hardware usage (cpu, disk, memory and bandwidth)\n    *\n    * @param id      id of the server\n    * @param options optional parameters\n    * @return the status of the server or null if not found\n    */\n   @Named(\"server:status\")\n   @POST\n   @Path(\"/server/status/format/json\")\n   @SelectJson(\"server\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(Fallbacks.NullOnNotFoundOr404.class)\n   ServerStatus getStatus(@FormParam(\"serverid\") String id, ServerStatusOptions... options);\n\n   /**\n    * Get detailed information about a server's limits (for OpenVZ only).\n    * <p/>\n    *\n    * @param id id of the server\n    * @return the requested information about the server or null if not found\n    */\n   @Named(\"server:limits\")\n   @POST\n   @Path(\"/server/limits/format/json\")\n   @SelectJson(\"limits\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(Fallbacks.NullOnNotFoundOr404.class)\n   SortedMap<String, ServerLimit> getLimits(@FormParam(\"serverid\") String id);\n\n   /**\n    * Get information about how to connect to a server via VNC\n    *\n    * @param id id of the server\n    * @return the requested information about the server or null if not found\n    */\n   @Named(\"server:console\")\n   @POST\n   @Path(\"/server/console/format/json\")\n   @SelectJson(\"console\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @Fallback(Fallbacks.NullOnNotFoundOr404.class)\n   Console getConsole(@FormParam(\"serverid\") String id);\n\n   /**\n    * Get information about the OS templates available\n    *\n    * @return the set of information about each template\n    */\n   @Named(\"server:allowedarguments\")\n   @GET\n   @Path(\"/server/allowedarguments/format/json\")\n   @SelectJson(\"argumentslist\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   Map<String, AllowedArgumentsForCreateServer> getAllowedArgumentsForCreateByPlatform();\n\n   /**\n    * Get information about valid arguments to #createServer for each platform\n    *\n    * @return a map of argument lists, keyed on platform\n    */\n   @Named(\"server:templates\")\n   @GET\n   @Path(\"/server/templates/format/json\")\n   @ResponseParser(ParseTemplatesFromHttpResponse.class)\n   @Fallback(Fallbacks.EmptyFluentIterableOnNotFoundOr404.class)\n   @Consumes(MediaType.APPLICATION_JSON)\n   FluentIterable<OSTemplate> listTemplates();\n\n   /**\n    * Reset the fail count for a server limit (for OpenVZ only).\n    *\n    * @param id   id of the server\n    * @param type the type of limit to reset\n    */\n   @Named(\"server:resetlimit\")\n   @POST\n   @Path(\"/server/resetlimit/format/json\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   SortedMap<String, ServerLimit> resetLimit(@FormParam(\"serverid\") String id,\n                                             @FormParam(\"type\") String type);\n\n   /**\n    * Reboot a server\n    *\n    * @param id id of the server\n    */\n   @Named(\"server:reboot\")\n   @POST\n   @SelectJson(\"server\")\n   @Path(\"/server/reboot/format/json\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   ServerDetails reboot(@FormParam(\"serverid\") String id);\n\n   /**\n    * Start a server\n    *\n    * @param id id of the server\n    */\n   @Named(\"server:start\")\n   @POST\n   @SelectJson(\"server\")\n   @Path(\"/server/start/format/json\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   ServerDetails start(@FormParam(\"serverid\") String id);\n\n   /**\n    * Stop a server\n    *\n    * @param id id of the server\n    */\n   @Named(\"server:stop\")\n   @POST\n   @SelectJson(\"server\")\n   @Path(\"/server/stop/format/json\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   ServerDetails stop(@FormParam(\"serverid\") String id);\n\n   /**\n    * hard stop a server\n    *\n    * @param id id of the server\n    */\n   @Named(\"server:stop:hard\")\n   @POST\n   @SelectJson(\"server\")\n   @Path(\"/server/stop/format/json\")\n   @FormParams(keys = \"type\", values = \"hard\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   ServerDetails hardStop(@FormParam(\"serverid\") String id);\n\n   /**\n    * Create a new server\n    *\n    * @param hostname     the host name of the new server\n    * @param rootPassword the root password to use\n    * @param options      optional settings ex. description\n    */\n   @Named(\"server:create\")\n   @POST\n   @SelectJson(\"server\")\n   @Path(\"/server/create/format/json\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   @MapBinder(CreateServerOptions.class)\n   ServerDetails createWithHostnameAndRootPassword(ServerSpec serverSpec,\n                                                   @PayloadParam(\"hostname\") String hostname, @PayloadParam(\"rootpassword\") String rootPassword,\n                                                   CreateServerOptions... options);\n\n   /**\n    * Clone a server\n    *\n    * @param serverid the serverId of the server to clone\n    * @param hostname the new host name of the cloned server\n    * @param options  the settings to change\n    */\n   @Named(\"server:clone\")\n   @POST\n   @Path(\"/server/clone/format/json\")\n   @SelectJson(\"server\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   ServerDetails clone(@FormParam(\"serverid\") String serverid,\n                       @FormParam(\"hostname\") String hostname, CloneServerOptions... options);\n\n   /**\n    * Update the configuration of a server\n    *\n    * @param serverid the serverId of the server to edit\n    * @param options  the settings to change\n    */\n   @Named(\"server:edit\")\n   @POST\n   @Path(\"/server/edit/format/json\")\n   @SelectJson(\"server\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   ServerDetails update(@FormParam(\"serverid\") String serverid, UpdateServerOptions options);\n\n   /**\n    * Destroy a server\n    *\n    * @param id     the id of the server\n    * @param keepIp if DestroyServerOptions.keepIp(true) the servers ip will be retained for use in your GleSYS account\n    */\n   @Named(\"server:destroy\")\n   @POST\n   @Path(\"/server/destroy/format/json\")\n   void destroy(@FormParam(\"serverid\") String id, DestroyServerOptions keepIp);\n\n   /**\n    * Reset the root password of a server\n    *\n    * @param id       the id of the server\n    * @param password the new password to use\n    */\n   @Named(\"server:resetpassword\")\n   @POST\n   @Path(\"/server/resetpassword/format/json\")\n   @SelectJson(\"server\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   ServerDetails resetPassword(@FormParam(\"serverid\") String id, @FormParam(\"rootpassword\") String password);\n\n   /**\n    * Return resource usage over time for server\n    *\n    * @param id       the id of the server\n    * @param resource the name of the resource to retrieve usage information for (e.g. \"cpuusage\")\n    * @param resolution the time-period to extract data for (one of \"minute\", \"hour\" or \"day)\n    */\n   @Named(\"server:resourceusage\")\n   @POST\n   @Path(\"/server/resourceusage/format/json\")\n   @SelectJson(\"usage\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   ResourceUsage getResourceUsage(@FormParam(\"serverid\") String id, @FormParam(\"resource\") String resource,\n                                  @FormParam(\"resolution\") String resolution);\n\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/functions/ParseTemplatesFromHttpResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.glesys.domain.OSTemplate;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseFirstJsonValueNamed;\nimport org.jclouds.json.internal.GsonWrapper;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.Iterables;\nimport com.google.inject.Inject;\nimport com.google.inject.TypeLiteral;\n\n@Singleton\npublic class ParseTemplatesFromHttpResponse implements Function<HttpResponse, FluentIterable<OSTemplate>> {\n   private final ParseFirstJsonValueNamed<Map<String, Set<OSTemplate>>> parser;\n\n   @Inject\n   public ParseTemplatesFromHttpResponse(GsonWrapper gsonView) {\n      this.parser = new ParseFirstJsonValueNamed<Map<String, Set<OSTemplate>>>(checkNotNull(gsonView,\n               \"gsonView\"), new TypeLiteral<Map<String, Set<OSTemplate>>>() {\n      }, \"templates\");\n   }\n\n   public FluentIterable<OSTemplate> apply(HttpResponse response) {\n      checkNotNull(response, \"response\");\n      Map<String, Set<OSTemplate>> toParse = parser.apply(response);\n      checkNotNull(toParse, \"parsed result from %s\", response);\n      return FluentIterable.from(Iterables.concat(toParse.values()));\n   }\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/functions/internal/GleSYSTypeAdapters.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.functions.internal;\n\nimport java.io.IOException;\n\nimport org.jclouds.glesys.domain.GleSYSBoolean;\nimport org.jclouds.glesys.domain.Server;\n\nimport com.google.common.base.Objects;\nimport com.google.gson.TypeAdapter;\nimport com.google.gson.stream.JsonReader;\nimport com.google.gson.stream.JsonToken;\nimport com.google.gson.stream.JsonWriter;\n\npublic class GleSYSTypeAdapters {\n\n   public static class ServerStateAdapter extends TypeAdapter<Server.State> {\n      @Override\n      public void write(JsonWriter writer, Server.State value) throws IOException {\n         writer.value(value.value());\n      }\n\n      @Override\n      public Server.State read(JsonReader reader) throws IOException {\n         if (reader.peek() == JsonToken.NULL) {\n            reader.nextNull();\n            return Server.State.UNRECOGNIZED;\n         }\n         return Server.State.fromValue(reader.nextString());\n      }\n   }\n\n   public static class GleSYSBooleanAdapter extends TypeAdapter<GleSYSBoolean> {\n\n      @Override\n      public void write(JsonWriter writer, GleSYSBoolean value) throws IOException {\n         writer.value(value.getValue() ? \"yes\" : \"no\");\n      }\n\n      @Override\n      public GleSYSBoolean read(JsonReader in) throws IOException {\n         if (in.peek() == JsonToken.BOOLEAN) {\n            return new GleSYSBoolean(in.nextBoolean());\n         } else if (in.peek() == JsonToken.NULL) {\n            return GleSYSBoolean.FALSE;\n         } else {\n            return new GleSYSBoolean(Objects.equal(in.nextString(), \"yes\"));\n         }\n      }\n\n   }\n\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/handlers/GleSYSErrorHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.handlers;\n\nimport java.io.IOException;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.jclouds.util.Closeables2;\nimport org.jclouds.util.Strings2;\n\nimport com.google.common.base.Throwables;\n\n/**\n * This will parse and set an appropriate exception on the command object.\n */\n@Singleton\npublic class GleSYSErrorHandler implements HttpErrorHandler {\n\n   public void handleError(HttpCommand command, HttpResponse response) {\n      // it is important to always read fully and close streams\n      String message = parseMessage(response);\n      Exception exception = message != null ? new HttpResponseException(command, response, message)\n            : new HttpResponseException(command, response);\n      try {\n         message = message != null ? message : String.format(\"%s -> %s\", command.getCurrentRequest().getRequestLine(),\n               response.getStatusLine());\n         switch (response.getStatusCode()) {\n         case 401:\n         case 403:\n            exception = new AuthorizationException(message, exception);\n            break;\n         case 400:\n            if (message.indexOf(\"not find\") != -1) {\n               exception = new ResourceNotFoundException(message, exception);\n            }\n            break;\n         case 404:\n            if (message.indexOf(\"Not supported\") != -1) {\n               exception = new UnsupportedOperationException(message, exception);\n            } else {\n               exception = new ResourceNotFoundException(message, exception);\n            }\n            break;\n         case 500:\n            if (message.indexOf(\"Locked\") != -1) {\n               exception = new IllegalStateException(message, exception);\n            }\n            break;\n         }\n      } finally {\n         Closeables2.closeQuietly(response.getPayload());\n         command.setException(exception);\n      }\n   }\n\n   public String parseMessage(HttpResponse response) {\n      if (response.getPayload() == null)\n         return null;\n      try {\n         return Strings2.toStringAndClose(response.getPayload().openStream());\n      } catch (IOException e) {\n         throw new RuntimeException(e);\n      } finally {\n         try {\n            response.getPayload().getInput().close();\n         } catch (IOException e) {\n            Throwables.propagate(e);\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/options/AddDomainOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.options;\n\n\npublic class AddDomainOptions extends DomainOptions {\n   public static class Builder {\n      /**\n       * @see AddDomainOptions#primaryNameServer\n       */\n      public static AddDomainOptions primaryNameServer(String primaryNameServer) {\n         return AddDomainOptions.class.cast(new AddDomainOptions().primaryNameServer(primaryNameServer));\n      }\n\n      /**\n       * @see AddDomainOptions#responsiblePerson\n       */\n      public static AddDomainOptions responsiblePerson(String responsiblePerson) {\n         return AddDomainOptions.class.cast(new AddDomainOptions().responsiblePerson(responsiblePerson));\n      }\n\n      /**\n       * @see AddDomainOptions#ttl\n       */\n      public static AddDomainOptions ttl(int ttl) {\n         return AddDomainOptions.class.cast(new AddDomainOptions().ttl(ttl));\n      }\n\n      /**\n       * @see AddDomainOptions#refresh\n       */\n      public static AddDomainOptions refresh(int refresh) {\n         return AddDomainOptions.class.cast(new AddDomainOptions().refresh(refresh));\n      }\n\n      /**\n       * @see AddDomainOptions#retry\n       */\n      public static AddDomainOptions retry(int retry) {\n         return AddDomainOptions.class.cast(new AddDomainOptions().retry(retry));\n      }\n\n      /**\n       * @see AddDomainOptions#expire\n       */\n      public static AddDomainOptions expire(int expire) {\n         return AddDomainOptions.class.cast(new AddDomainOptions().expire(expire));\n      }\n\n      /**\n       * @see AddDomainOptions#minimum\n       */\n      public static AddDomainOptions minimum(int minimum) {\n         return AddDomainOptions.class.cast(new AddDomainOptions().minimum(minimum));\n      }\n\n      /**\n       * @see AddDomainOptions#minimalRecords\n       */\n      public static AddDomainOptions minimalRecords() {\n         return AddDomainOptions.class.cast(new AddDomainOptions().minimalRecords());\n      }\n   }\n\n   /**\n    * Ensure only NS and SOA records will be created by default, when this option is not used a number of default records will be created on the domain.\n    */\n   public DomainOptions minimalRecords() {\n      formParameters.put(\"createrecords\", Boolean.FALSE.toString());\n      return this;\n   }\n\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/options/AddRecordOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\npublic class AddRecordOptions extends BaseHttpRequestOptions {\n\n   public static class Builder {\n      /**\n       * @see AddRecordOptions#ttl\n       */\n      public static AddRecordOptions ttl(int ttl) {\n         AddRecordOptions options = new AddRecordOptions();\n         return options.ttl(ttl);\n      }\n   }\n\n   /** Configure TTL/Time-to-live for record */\n   public AddRecordOptions ttl(int ttl) {\n      formParameters.put(\"ttl\", Integer.toString(ttl));\n      return this;\n   }\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/options/CloneServerOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.options;\n\npublic class CloneServerOptions extends UpdateServerOptions {\n   public static class Builder {\n      /**\n       * @see org.jclouds.glesys.options.CloneServerOptions#diskSizeGB\n       */\n      public static CloneServerOptions diskSizeGB(int diskSizeGB) {\n         return CloneServerOptions.class.cast(new CloneServerOptions().diskSizeGB(diskSizeGB));\n      }\n\n      /**\n       * @see org.jclouds.glesys.options.CloneServerOptions#memorySizeMB\n       */\n      public static CloneServerOptions memorySizeMB(int memorySizeMB) {\n         return CloneServerOptions.class.cast(new CloneServerOptions().memorySizeMB(memorySizeMB));\n      }\n\n      /**\n       * @see org.jclouds.glesys.options.CloneServerOptions#cpuCores\n       */\n      public static CloneServerOptions cpucores(int cpucores) {\n         return CloneServerOptions.class.cast(new CloneServerOptions().cpuCores(cpucores));\n      }\n\n      /**\n       * @see org.jclouds.glesys.options.CloneServerOptions#transferGB\n       */\n      public static CloneServerOptions transferGB(int transferGB) {\n         return CloneServerOptions.class.cast(new CloneServerOptions().transferGB(transferGB));\n      }\n\n      /**\n       * @see org.jclouds.glesys.options.UpdateServerOptions#description\n       */\n      public static CloneServerOptions description(String description) {\n         return CloneServerOptions.class.cast(new CloneServerOptions().description(description));\n      }\n\n      /**\n       * @see org.jclouds.glesys.options.CloneServerOptions#dataCenter\n       */\n      public static CloneServerOptions dataCenter(String dataCenter) {\n         return new CloneServerOptions().dataCenter(dataCenter);\n      }\n   }\n\n   /**\n    * Configure which datacenter to create the clone in\n    */\n   public CloneServerOptions dataCenter(String dataCenter) {\n      formParameters.put(\"datacenter\", dataCenter);\n      return this;\n   }\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/options/CreateAccountOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\n/**\n * @see <a href=\"https://customer.glesys.com/api.php?a=doc#email_createaccount\" />\n */\npublic class CreateAccountOptions extends BaseHttpRequestOptions {\n   public static class Builder {\n      /**\n       * @see CreateAccountOptions#antispamLevel\n       */\n      public static CreateAccountOptions antispamLevel(int antispamLevel) {\n         return new CreateAccountOptions().antispamLevel(antispamLevel);\n      }\n\n      /**\n       * @see CreateAccountOptions#antiVirus\n       */\n      public static CreateAccountOptions antiVirus(boolean antiVirus) {\n         return new CreateAccountOptions().antiVirus(antiVirus);\n      }\n\n      /**\n       * @see CreateAccountOptions#autorespond\n       */\n      public static CreateAccountOptions autorespond(boolean autorespond) {\n         return new CreateAccountOptions().autorespond(autorespond);\n      }\n\n      /**\n       * @see CreateAccountOptions#autorespondSaveEmail\n       */\n      public static CreateAccountOptions autorespondSaveEmail(boolean autorespondSaveEmail) {\n         return new CreateAccountOptions().autorespondSaveEmail(autorespondSaveEmail);\n      }\n\n      /**\n       * @see CreateAccountOptions#autorespondMessage\n       */\n      public static CreateAccountOptions autorespondMessage(String autorespondMessage) {\n         return new CreateAccountOptions().autorespondMessage(autorespondMessage);\n      }\n   }\n\n   /** Configure the antispam level of the account */\n   public CreateAccountOptions antispamLevel(int antispamLevel) {\n      formParameters.put(\"antispamlevel\", Integer.toString(antispamLevel));\n      return this;\n   }\n\n   /** Enable or disable virus checking */\n   public CreateAccountOptions antiVirus(boolean antiVirus) {\n      formParameters.put(\"antivirus\", Boolean.toString(antiVirus));\n      return this;\n   }\n\n   /** Enable or disable auto-respond */\n   public CreateAccountOptions autorespond(boolean autorespond) {\n      formParameters.put(\"autorespond\", Boolean.toString(autorespond));\n      return this;\n   }\n\n   /** Enable or disable saving of auto-respond e-mails */\n   public CreateAccountOptions autorespondSaveEmail(boolean autorespondSaveEmail) {\n      formParameters.put(\"autorespondsaveemail\", Boolean.toString(autorespondSaveEmail));\n      return this;\n   }\n\n   /** Configure the auto-respond message */\n   public CreateAccountOptions autorespondMessage(String autorespondMessage) {\n      formParameters.put(\"autorespondmessage\", autorespondMessage);\n      return this;\n   }\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/options/CreateServerOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.options;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Predicates.instanceOf;\nimport static com.google.common.collect.Iterables.find;\n\nimport java.util.Map;\n\nimport org.jclouds.glesys.domain.ServerSpec;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.io.payloads.UrlEncodedFormPayload;\nimport org.jclouds.rest.MapBinder;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\n\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ImmutableMultimap;\n\npublic class CreateServerOptions implements MapBinder {\n\n   private String ip;\n   private String description;\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      checkArgument(checkNotNull(request, \"request\") instanceof GeneratedHttpRequest,\n            \"this binder is only valid for GeneratedHttpRequests!\");\n      GeneratedHttpRequest gRequest = (GeneratedHttpRequest) request;\n      ImmutableMultimap.Builder<String, String> formParams = ImmutableMultimap.builder();\n      for (Map.Entry<String, Object> entry : postParams.entrySet())\n         formParams.put(entry.getKey(), (String) entry.getValue());\n      ServerSpec serverSpec = ServerSpec.class.cast(find(gRequest.getInvocation().getArgs(),\n            instanceOf(ServerSpec.class)));\n      formParams.put(\"datacenter\", serverSpec.getDatacenter());\n      formParams.put(\"platform\", serverSpec.getPlatform());\n      formParams.put(\"templatename\", serverSpec.getTemplateName());\n      formParams.put(\"disksize\", serverSpec.getDiskSizeGB() + \"\");\n      formParams.put(\"memorysize\", serverSpec.getMemorySizeMB() + \"\");\n      formParams.put(\"cpucores\", serverSpec.getCpuCores() + \"\");\n      formParams.put(\"transfer\", serverSpec.getTransferGB() + \"\");\n      if (ip != null)\n         formParams.put(\"ip\", ip);\n      if (description != null)\n         formParams.put(\"description\", description);\n\n      request.setPayload(new UrlEncodedFormPayload(formParams.build()));\n      return request;\n   }\n\n   public static class Builder {\n      /**\n       * @see CreateServerOptions#description\n       */\n      public static CreateServerOptions description(String primaryNameServer) {\n         CreateServerOptions options = new CreateServerOptions();\n         return options.description(primaryNameServer);\n      }\n\n      /**\n       * @see CreateServerOptions#ip\n       */\n      public static CreateServerOptions ip(String ip) {\n         CreateServerOptions options = new CreateServerOptions();\n         return options.ip(ip);\n      }\n   }\n\n   /**\n    * @param description\n    *           the description of the server\n    */\n   public CreateServerOptions description(String description) {\n      this.description = description;\n      return this;\n   }\n\n   /**\n    * @param ip\n    *           the ip address to assign to the server\n    */\n   public CreateServerOptions ip(String ip) {\n      this.ip = ip;\n      return this;\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      throw new IllegalArgumentException();\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(ip, description);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (obj == null)\n         return false;\n      if (!(obj instanceof CreateServerOptions))\n         return false;\n      CreateServerOptions that = CreateServerOptions.class.cast(obj);\n      return equal(this.ip, that.ip) && equal(this.description, that.description);\n   }\n\n   @Override\n   public String toString() {\n      return toStringHelper(\"\").add(\"ip\", ip).add(\"description\", description).toString();\n   }\n\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/options/DestroyServerOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\npublic class DestroyServerOptions extends BaseHttpRequestOptions {\n   public static class Builder {\n      /**\n       * Discard the server's ip on destroy\n       */\n      public static DestroyServerOptions keepIp() {\n         return new DestroyServerOptions().keepIp(true);\n      }\n\n      /**\n       * Discard the server's ip on destroy\n       */\n      public static DestroyServerOptions discardIp() {\n         return new DestroyServerOptions().keepIp(false);\n      }\n\n   }\n\n   /**\n    * Determines whether to keep the server's ip attached to your account when destroying a server\n    *\n    * @param keepIp if true, keep the ip address\n    */\n   public DestroyServerOptions keepIp(boolean keepIp) {\n      formParameters.put(\"keepip\", Boolean.toString(keepIp));\n      return this;\n   }\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/options/DomainOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\npublic class DomainOptions extends BaseHttpRequestOptions {\n   public static class Builder {\n      /**\n       * @see DomainOptions#primaryNameServer\n       */\n      public static DomainOptions primaryNameServer(String primaryNameServer) {\n         DomainOptions options = new DomainOptions();\n         return options.primaryNameServer(primaryNameServer);\n      }\n\n      /**\n       * @see DomainOptions#responsiblePerson\n       */\n      public static DomainOptions responsiblePerson(String responsiblePerson) {\n         DomainOptions options = new DomainOptions();\n         return options.responsiblePerson(responsiblePerson);\n      }\n\n      /**\n       * @see DomainOptions#ttl\n       */\n      public static DomainOptions ttl(int ttl) {\n         DomainOptions options = new DomainOptions();\n         return options.ttl(ttl);\n      }\n\n      /**\n       * @see DomainOptions#refresh\n       */\n      public static DomainOptions refresh(int refresh) {\n         DomainOptions options = new DomainOptions();\n         return options.refresh(refresh);\n      }\n\n      /**\n       * @see DomainOptions#retry\n       */\n      public static DomainOptions retry(int retry) {\n         DomainOptions options = new DomainOptions();\n         return options.retry(retry);\n      }\n\n      /**\n       * @see DomainOptions#expire\n       */\n      public static DomainOptions expire(int expire) {\n         DomainOptions options = new DomainOptions();\n         return options.expire(expire);\n      }\n\n      /**\n       * @see DomainOptions#minimum\n       */\n      public static DomainOptions minimum(int minimum) {\n         DomainOptions options = new DomainOptions();\n         return options.minimum(minimum);\n      }\n   }\n\n   /**\n    *  Configure the primary DNS server for this domain.\n    */\n   public DomainOptions primaryNameServer(String primaryNameServer) {\n      formParameters.put(\"primarynameserver\", primaryNameServer);\n      return this;\n   }\n\n   /**\n    *  Configure the E-mail address of the person responsible for this domain (usually attached to MX records).\n    */\n   public DomainOptions responsiblePerson(String responsiblePerson) {\n      responsiblePerson = responsiblePerson.replaceAll(\"@\", \".\");\n      if (!responsiblePerson.endsWith(\".\")) {\n         responsiblePerson = responsiblePerson + \".\";\n      }\n      formParameters.put(\"responsibleperson\", responsiblePerson);\n      return this;\n   }\n\n   /**\n    * TTL (time to live). The number of seconds a domain name is cached locally before expiration and return to authoritative nameservers for updates\n    */\n   public DomainOptions ttl(int ttl) {\n      formParameters.put(\"ttl\", Integer.toString(ttl));\n      return this;\n   }\n\n   /**\n    * Configure the number of seconds between update requests from secondary and slave name servers\n    */\n   public DomainOptions refresh(int refresh) {\n      formParameters.put(\"refresh\", Integer.toString(refresh));\n      return this;\n   }\n\n   /**\n    * Configure the number of seconds the secondary/slave will wait before retrying when the last attempt failed\n    */\n   public DomainOptions retry(int retry) {\n      formParameters.put(\"retry\", Integer.toString(retry));\n      return this;\n   }\n\n   /**\n    * Configure the number of seconds a master or slave will wait before considering the data stale if it cannot reach the primary name server\n    */\n   public DomainOptions expire(int expire) {\n      formParameters.put(\"expire\", Integer.toString(expire));\n      return this;\n   }\n\n   /**\n    * Configure the minimum/default TTL if the domain does not specify ttl\n    * \n    * @see #ttl\n    */\n   public DomainOptions minimum(int minimum) {\n      formParameters.put(\"minimum\", Integer.toString(minimum));\n      return this;\n   }\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/options/ListIpOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\npublic class ListIpOptions extends BaseHttpRequestOptions {\n\n   public static class Builder {\n      /**\n       * @see org.jclouds.glesys.options.ListIpOptions#used\n       */\n      public static ListIpOptions used(boolean used) {\n         return new ListIpOptions().used(used);\n      }\n\n      /**\n       * @see org.jclouds.glesys.options.ListIpOptions#serverId\n       */\n      public static ListIpOptions serverId(String serverId) {\n         return new ListIpOptions().serverId(serverId);\n      }\n\n      /**\n       * @see org.jclouds.glesys.options.ListIpOptions#ipVersion\n       */\n      public static ListIpOptions ipVersion(int ipVersion) {\n         return new ListIpOptions().ipVersion(ipVersion);\n      }\n\n      /**\n       * @see org.jclouds.glesys.options.ListIpOptions#datacenter\n       */\n      public static ListIpOptions datacenter(String datacenter) {\n         return new ListIpOptions().datacenter(datacenter);\n      }\n\n      /**\n       * @see org.jclouds.glesys.options.ListIpOptions#platform\n       */\n      public static ListIpOptions platform(String platform) {\n         return new ListIpOptions().platform(platform);\n      }\n\n   }\n\n   /**\n    * Retrieve only IPs that are in use\n    */\n   public ListIpOptions used(boolean used) {\n      formParameters.put(\"used\", Boolean.toString(used));\n      return this;\n   }\n\n   /**\n    * Retrieve only IP assigned to the specified server\n    */\n   public ListIpOptions serverId(String serverId) {\n      formParameters.put(\"serverid\", serverId);\n      return this;\n   }\n\n   /**\n    * Retrieve only IPs of the requested version\n    */\n   public ListIpOptions ipVersion(int ipVersion) {\n      formParameters.put(\"ipversion\", Integer.toString(ipVersion));\n      return this;\n   }\n\n   /**\n    * Retrieve only IPs served in the specified datacenter\n    */\n   public ListIpOptions datacenter(String datacenter) {\n      formParameters.put(\"datacenter\", datacenter);\n      return this;\n   }\n\n   /**\n    * Retrieve only IPs served on the specified platform\n    */\n   public ListIpOptions platform(String platform) {\n      formParameters.put(\"platform\", platform);\n      return this;\n   }\n\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/options/ServerStatusOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\npublic class ServerStatusOptions extends BaseHttpRequestOptions {\n\n   public enum StatusTypes {\n      STATE, CPU, MEMORY, DISK, BANDWIDTH, UPTIME;\n   }\n\n   public static class Builder {\n      /**\n       * @see org.jclouds.glesys.options.ServerStatusOptions#statusType\n       */\n      public static ServerStatusOptions state() {\n         ServerStatusOptions options = new ServerStatusOptions();\n         return options.statusType(StatusTypes.STATE);\n      }\n\n      /**\n       * @see org.jclouds.glesys.options.ServerStatusOptions#statusType\n       */\n      public static ServerStatusOptions cpu() {\n         ServerStatusOptions options = new ServerStatusOptions();\n         return options.statusType(StatusTypes.CPU);\n      }\n\n      /**\n       * @see org.jclouds.glesys.options.ServerStatusOptions#statusType\n       */\n      public static ServerStatusOptions memory() {\n         ServerStatusOptions options = new ServerStatusOptions();\n         return options.statusType(StatusTypes.MEMORY);\n      }\n\n      /**\n       * @see org.jclouds.glesys.options.ServerStatusOptions#statusType\n       */\n      public static ServerStatusOptions disk() {\n         ServerStatusOptions options = new ServerStatusOptions();\n         return options.statusType(StatusTypes.DISK);\n      }\n\n      /**\n       * @see org.jclouds.glesys.options.ServerStatusOptions#statusType\n       */\n      public static ServerStatusOptions bandwidth() {\n         ServerStatusOptions options = new ServerStatusOptions();\n         return options.statusType(StatusTypes.BANDWIDTH);\n      }\n   }\n\n   /**\n    * Select the given type of information form the server\n    */\n   public ServerStatusOptions statusType(StatusTypes type) {\n      formParameters.put(\"statustype\", type.name().toLowerCase());\n      return this;\n   }\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/options/UpdateAccountOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.options;\n\n\n/**\n * @see <a href=\"https://customer.glesys.com/api.php?a=doc#email_editaccount\" />\n */\npublic class UpdateAccountOptions extends CreateAccountOptions {\n\n   public static class Builder {\n      /**\n       * @see org.jclouds.glesys.options.UpdateAccountOptions#antispamLevel\n       */\n      public static UpdateAccountOptions antispamLevel(int antispamLevel) {\n         return UpdateAccountOptions.class.cast(new UpdateAccountOptions().antispamLevel(antispamLevel));\n      }\n\n      /**\n       * @see org.jclouds.glesys.options.UpdateAccountOptions#antiVirus\n       */\n      public static UpdateAccountOptions antiVirus(boolean antiVirus) {\n         return UpdateAccountOptions.class.cast(new UpdateAccountOptions().antiVirus(antiVirus));\n      }\n\n      /**\n       * @see org.jclouds.glesys.options.UpdateAccountOptions#autorespond\n       */\n      public static UpdateAccountOptions autorespond(boolean autorespond) {\n         return UpdateAccountOptions.class.cast(new UpdateAccountOptions().autorespond(autorespond));\n      }\n\n      /**\n       * @see org.jclouds.glesys.options.UpdateAccountOptions#autorespondSaveEmail\n       */\n      public static UpdateAccountOptions autorespondSaveEmail(boolean autorespondSaveEmail) {\n         return UpdateAccountOptions.class.cast(new UpdateAccountOptions().autorespondSaveEmail(autorespondSaveEmail));\n      }\n\n      /**\n       * @see org.jclouds.glesys.options.UpdateAccountOptions#autorespondMessage\n       */\n      public static UpdateAccountOptions autorespondMessage(String autorespondMessage) {\n         return UpdateAccountOptions.class.cast(new UpdateAccountOptions().autorespondMessage(autorespondMessage));\n      }\n\n      /**\n       * @see org.jclouds.glesys.options.UpdateAccountOptions#password\n       */\n      public static UpdateAccountOptions password(String password) {\n         return new UpdateAccountOptions().password(password);\n      }\n   }\n\n   /** Reset the password for this account */\n   public UpdateAccountOptions password(String password) {\n      formParameters.put(\"password\", password);\n      return this;\n   }\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/options/UpdateRecordOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.options;\n\npublic class UpdateRecordOptions extends AddRecordOptions {\n\n   public static class Builder {\n      /**\n       * @see UpdateRecordOptions#host\n       */\n      public static UpdateRecordOptions host(String host) {\n         return new UpdateRecordOptions().host(host);\n      }\n\n      /**\n       * @see UpdateRecordOptions#type\n       */\n      public static UpdateRecordOptions type(String type) {\n         return new UpdateRecordOptions().type(type);\n      }\n\n      /**\n       * @see UpdateRecordOptions#data\n       */\n      public static UpdateRecordOptions data(String data) {\n         return new UpdateRecordOptions().data(data);\n      }\n\n      /**\n       * @see UpdateRecordOptions#ttl\n       */\n      public static UpdateRecordOptions ttl(int ttl) {\n         return UpdateRecordOptions.class.cast(new UpdateRecordOptions().ttl(ttl));\n      }\n   }\n\n\n   /** Configure the hostname attached to this record */\n   public UpdateRecordOptions host(String host) {\n      formParameters.put(\"host\", host);\n      return this;\n   }\n\n   /** Configure the type of record, ex. \"A\", \"CNAME\" or \"MX\"  */\n   public UpdateRecordOptions type(String type) {\n      formParameters.put(\"type\", type);\n      return this;\n   }\n\n   /** Set the content of this record (depending on type, for an \"A\" record this would be an ip address) */\n   public UpdateRecordOptions data(String data) {\n      formParameters.put(\"data\", data);\n      return this;\n   }\n\n   @Override\n   public UpdateRecordOptions ttl(int ttl) {\n      return UpdateRecordOptions.class.cast(super.ttl(ttl));\n   }\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/options/UpdateServerOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\npublic class UpdateServerOptions extends BaseHttpRequestOptions {\n\n   public static class Builder {\n      /**\n       * @see org.jclouds.glesys.options.UpdateServerOptions#diskSizeGB\n       */\n      public static UpdateServerOptions disksizeGB(int disksizeGB) {\n         return new UpdateServerOptions().diskSizeGB(disksizeGB);\n      }\n      \n      /**\n       * @see org.jclouds.glesys.options.UpdateServerOptions#memorySizeMB\n       */\n      public static UpdateServerOptions memorysizeMB(int memorysizeMB) {\n         return new UpdateServerOptions().memorySizeMB(memorysizeMB);\n      }\n\n      /**\n       * @see org.jclouds.glesys.options.UpdateServerOptions#cpuCores\n       */\n      public static UpdateServerOptions cpucores(int cpucores) {\n         UpdateServerOptions options = new UpdateServerOptions();\n         return options.cpuCores(cpucores);\n      }\n\n      /**\n       * @see org.jclouds.glesys.options.UpdateServerOptions#transferGB\n       */\n      public static UpdateServerOptions transferGB(int transferGB) {\n         return new UpdateServerOptions().transferGB(transferGB);\n      }\n      \n      /**\n       * @see org.jclouds.glesys.options.UpdateServerOptions#hostname\n       */\n      public static UpdateServerOptions hostname(String hostname) {\n         UpdateServerOptions options = new UpdateServerOptions();\n         return options.hostname(hostname);\n      }\n\n      /**\n       * @see org.jclouds.glesys.options.UpdateServerOptions#description\n       */\n      public static UpdateServerOptions description(String description) {\n         UpdateServerOptions options = new UpdateServerOptions();\n         return options.description(description);\n      }\n   }\n\n   /** Configure the size of the disk, in GB, of the server */\n   public UpdateServerOptions diskSizeGB(int diskSizeGB) {\n      formParameters.put(\"disksize\", Integer.toString(diskSizeGB));\n      return this;\n   }\n\n   /** Configure the amount of RAM, in MB, allocated to the server */\n   public UpdateServerOptions memorySizeMB(int memorySizeMB) {\n      formParameters.put(\"memorysize\", Integer.toString(memorySizeMB));\n      return this;\n   }\n\n   /** Configure the number of CPU cores allocated to the server */\n   public UpdateServerOptions cpuCores(int cpucores) {\n      formParameters.put(\"cpucores\", Integer.toString(cpucores));\n      return this;\n   }\n\n   /** Configure the transfer setting for the server */\n   public UpdateServerOptions transferGB(int transferGB) {\n      formParameters.put(\"transfer\", Integer.toString(transferGB));\n      return this;\n   }\n\n   /** Configure the host name of the server (must be unique within the GleSYS account) */\n   public UpdateServerOptions hostname(String hostname) {\n      formParameters.put(\"hostname\", hostname);\n      return this;\n   }\n\n   /** Configure the description of the server */\n   public UpdateServerOptions description(String description) {\n      formParameters.put(\"description\", description);\n      return this;\n   }\n\n}\n"
  },
  {
    "path": "providers/glesys/src/main/java/org/jclouds/glesys/reference/GleSYSConstants.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.reference;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport org.jclouds.compute.domain.ComputeMetadata;\n\n/**\n * Configuration properties and constants in GleSYS connections.\n */\npublic final class GleSYSConstants {\n\n   public static final Pattern JCLOUDS_ID_TO_PLATFORM = Pattern.compile(\"([a-zA-Z]+) .*\");\n   \n   public static String getPlatform(ComputeMetadata jcloudsObject) {\n      checkNotNull(jcloudsObject, \"jcloudsObject\");\n      Matcher matcher = JCLOUDS_ID_TO_PLATFORM.matcher(jcloudsObject.getId());\n      if (!matcher.matches()) {\n         throw new IllegalArgumentException(jcloudsObject.getId() + \" not a GleSYS platform-based id!\");\n      }\n      return matcher.group(1);\n   }\n\n   private GleSYSConstants() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "providers/glesys/src/test/java/org/jclouds/glesys/GleSYSApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys;\n\nimport java.io.IOException;\nimport java.util.concurrent.ExecutionException;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.rest.internal.BaseRestAnnotationProcessingTest;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code GleSYSApi}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"GleSYSApiTest\")\npublic class GleSYSApiTest extends BaseRestAnnotationProcessingTest<GleSYSApi> {\n   private GleSYSApi syncApi;\n\n   @Override\n   public ProviderMetadata createProviderMetadata() {\n      return new GleSYSProviderMetadata();\n   }\n   \n   public void testSync() throws SecurityException, NoSuchMethodException, InterruptedException, ExecutionException {\n      assert syncApi.getServerApi() != null;\n      assert syncApi.getIpApi() != null;\n      assert syncApi.getDomainApi() != null;\n      assert syncApi.getArchiveApi() != null;\n   }\n\n   @BeforeClass\n   @Override\n   protected void setupFactory() throws IOException {\n      super.setupFactory();\n      syncApi = injector.getInstance(GleSYSApi.class);\n   }\n\n   @Override\n   protected void checkFilters(HttpRequest request) {\n\n   }\n}\n"
  },
  {
    "path": "providers/glesys/src/test/java/org/jclouds/glesys/GleSYSErrorHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.reportMatcher;\nimport static org.easymock.EasyMock.verify;\n\nimport java.net.URI;\n\nimport org.easymock.IArgumentMatcher;\nimport org.jclouds.glesys.handlers.GleSYSErrorHandler;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Guice;\n\n@Test(groups = { \"unit\" })\npublic class GleSYSErrorHandlerTest {\n\n   @Test\n   public void test401MakesAuthorizationException() {\n      assertCodeMakes(\"GET\", URI.create(\"https://api.glesys.com/foo\"), 401, \"\", \"Unauthorized\",\n            AuthorizationException.class);\n   }\n   @Test\n   public void test500LockedMakesIllegalStateException() {\n      assertCodeMakes(\n            \"POST\",\n            URI.create(\"https://api.glesys.com/server/destroy/format/json\"),\n            500,\n            \"\",\n            \"{\\\"response\\\":{\\\"status\\\":{\\\"code\\\":606,\\\"timestamp\\\":\\\"2012-02-14T15:48:39+01:00\\\",\\\"text\\\":\\\"Server Locked\\\"},\\\"debug\\\":{\\\"input\\\":{\\\"serverid\\\":\\\"xm3270596\\\",\\\"keepip\\\":\\\"0\\\"}}}}\",\n            IllegalStateException.class);\n   }\n\n   @Test\n   public void test400MakesResourceNotFoundExceptionOnCouldNotFind() {\n      assertCodeMakes(\n            \"POST\",\n            URI.create(\"https://api.glesys.com/domain/delete/format/json\"),\n            400,\n            \"\",\n            \"{\\\"response\\\":{\\\"status\\\":{\\\"code\\\":400,\\\"timestamp\\\":\\\"2012-02-10T12:07:56+01:00\\\",\\\"text\\\":\\\"Could not find server with this id on this account.\\n\\\"},\\\"debug\\\":{\\\"input\\\":{\\\"domainname\\\":\\\"email-test.jclouds.org\\\"}}}}\",\n            ResourceNotFoundException.class);\n   }\n   \n   @Test\n   public void test404MakesResourceNotFoundException() {\n      assertCodeMakes(\"GET\", URI.create(\"https://api.glesys.com/foo\"), 404, \"\", \"Not Found\",\n            ResourceNotFoundException.class);\n   }\n\n   private void assertCodeMakes(String method, URI uri, int statusCode, String message, String content,\n         Class<? extends Exception> expected) {\n      assertCodeMakes(method, uri, statusCode, message, \"text/xml\", content, expected);\n   }\n\n   private void assertCodeMakes(String method, URI uri, int statusCode, String message, String contentType,\n         String content, Class<? extends Exception> expected) {\n\n      GleSYSErrorHandler function = Guice.createInjector().getInstance(GleSYSErrorHandler.class);\n\n      HttpCommand command = createMock(HttpCommand.class);\n      HttpRequest request = HttpRequest.builder().method(method).endpoint(uri).build();\n      HttpResponse response = HttpResponse.builder().statusCode(statusCode).message(message).payload(content).build();\n      response.getPayload().getContentMetadata().setContentType(contentType);\n\n      expect(command.getCurrentRequest()).andReturn(request).atLeastOnce();\n      command.setException(classEq(expected));\n\n      replay(command);\n\n      function.handleError(command, response);\n\n      verify(command);\n   }\n\n   public static Exception classEq(final Class<? extends Exception> in) {\n      reportMatcher(new IArgumentMatcher() {\n\n         @Override\n         public void appendTo(StringBuffer buffer) {\n            buffer.append(\"classEq(\");\n            buffer.append(in);\n            buffer.append(\")\");\n         }\n\n         @Override\n         public boolean matches(Object arg) {\n            return arg.getClass() == in;\n         }\n\n      });\n      return null;\n   }\n\n}\n"
  },
  {
    "path": "providers/glesys/src/test/java/org/jclouds/glesys/GleSYSProviderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys;\n\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"GleSYSProviderTest\")\npublic class GleSYSProviderTest extends BaseProviderMetadataTest {\n\n   public GleSYSProviderTest() {\n      super(new GleSYSProviderMetadata(), new GleSYSApiMetadata());\n   }\n}\n"
  },
  {
    "path": "providers/glesys/src/test/java/org/jclouds/glesys/compute/GleSYSComputeServiceAdapterExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.compute;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.glesys.compute.internal.BaseGleSYSComputeServiceExpectTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Iterables;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"GleSYSComputeServiceAdapterExpectTest\")\npublic class GleSYSComputeServiceAdapterExpectTest extends BaseGleSYSComputeServiceExpectTest {\n\n   @Test\n   public void testListImages() {\n\n      GleSYSComputeServiceAdapter adapter = injectorForKnownArgumentsAndConstantPassword().getInstance(GleSYSComputeServiceAdapter.class);\n\n      assertEquals(Iterables.size(adapter.listImages()), 34);\n\n   }\n\n   \n   //TODO: most importantly createServer and listHardwareProfiles tests\n}\n"
  },
  {
    "path": "providers/glesys/src/test/java/org/jclouds/glesys/compute/GleSYSComputeServiceLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.compute;\n\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.internal.BaseComputeServiceLiveTest;\nimport org.jclouds.sshj.config.SshjSshClientModule;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.inject.Module;\n\n/**\n * \n * TODO: enable this\n */\n@Test(groups = \"live\", enabled = true, singleThreaded = true)\npublic class GleSYSComputeServiceLiveTest extends BaseComputeServiceLiveTest {\n\n   public GleSYSComputeServiceLiveTest() {\n      provider = \"glesys\";\n      // ensure hyphens work\n      group = \"gle-sys\";\n   }\n\n   @Override\n   protected Module getSshModule() {\n      return new SshjSshClientModule();\n   }\n\n   // GleSYS does not support metadata\n   @Override\n   protected void checkUserMetadataContains(NodeMetadata node, ImmutableMap<String, String> userMetadata) {\n   }\n}\n"
  },
  {
    "path": "providers/glesys/src/test/java/org/jclouds/glesys/compute/GleSYSExperimentExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.compute;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.glesys.compute.internal.BaseGleSYSComputeServiceExpectTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"GleSYSExperimentLiveTest\")\npublic class GleSYSExperimentExpectTest extends BaseGleSYSComputeServiceExpectTest {\n\n   @Test\n   public void testAndExperiment() {\n      ComputeServiceContext context = null;\n      try {\n\n         context = computeContextForKnownArgumentsAndConstantPassword();\n\n         assertEquals(context.getComputeService().listAssignableLocations().size(), 4);\n\n      } finally {\n         if (context != null)\n            context.close();\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/glesys/src/test/java/org/jclouds/glesys/compute/GleSYSExperimentLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.compute;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.compute.internal.BaseComputeServiceContextLiveTest;\nimport org.jclouds.glesys.GleSYSProviderMetadata;\nimport org.jclouds.util.Closeables2;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"GleSYSExperimentLiveTest\")\npublic class GleSYSExperimentLiveTest extends BaseComputeServiceContextLiveTest {\n\n   public GleSYSExperimentLiveTest() {\n      provider = \"glesys\";\n   }\n\n   @Test\n   public void testAndExperiment() {\n      ComputeServiceContext context = null;\n      try {\n\n         context = ContextBuilder\n               .newBuilder(new GleSYSProviderMetadata())\n               .overrides(setupProperties())\n               .modules(setupModules()).build(ComputeServiceContext.class);\n\n         assertEquals(context.getComputeService().listAssignableLocations().size(), 4);\n\n      } finally {\n         Closeables2.closeQuietly(context);\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/glesys/src/test/java/org/jclouds/glesys/compute/GleSYSTemplateBuilderLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.compute;\n\nimport static org.jclouds.compute.util.ComputeServiceUtils.getCores;\nimport static org.jclouds.compute.util.ComputeServiceUtils.getSpace;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.domain.Volume;\nimport org.jclouds.compute.internal.BaseTemplateBuilderLiveTest;\nimport org.jclouds.glesys.compute.options.GleSYSTemplateOptions;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"live\", testName = \"GleSYSTemplateBuilderLiveTest\")\npublic class GleSYSTemplateBuilderLiveTest extends BaseTemplateBuilderLiveTest {\n\n   public GleSYSTemplateBuilderLiveTest() {\n      provider = \"glesys\";\n   }\n\n   @Test\n   public void testDefaultTemplateBuilder() throws IOException {\n      Template defaultTemplate = view.getComputeService().templateBuilder().build();\n      assertEquals(defaultTemplate.getImage().getId(), \"Ubuntu 12.04 x64\");\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().getVersion(), \"12.04\");\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true);\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.UBUNTU);\n      assertEquals(getCores(defaultTemplate.getHardware()), 1.0d);\n      assertEquals(defaultTemplate.getHardware().getRam(), 768);\n      assertEquals(defaultTemplate.getHardware().getHypervisor(), \"Xen\");\n      assertEquals(getSpace(defaultTemplate.getHardware()), 5.0d);\n      assertEquals(defaultTemplate.getHardware().getVolumes().get(0).getType(), Volume.Type.LOCAL);\n      // test that we bound the correct templateoptions in guice\n      assertEquals(defaultTemplate.getOptions().getClass(), GleSYSTemplateOptions.class);\n   }\n\n   @Override\n   protected Set<String> getIso3166Codes() {\n      return ImmutableSet.of(\"NL-NH\", \"SE-N\", \"US-NY\", \"SE-AB\");\n   }\n}\n"
  },
  {
    "path": "providers/glesys/src/test/java/org/jclouds/glesys/compute/functions/ParseOsFamilyVersion64BitFromImageNameTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.compute.functions;\n\nimport static com.google.common.collect.Iterables.transform;\nimport static com.google.common.collect.Lists.newArrayList;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\nimport org.jclouds.compute.config.BaseComputeServiceContextModule;\nimport org.jclouds.compute.domain.OsFamilyVersion64Bit;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.json.Json;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.json.internal.GsonWrapper;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.DataProvider;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.gson.Gson;\nimport com.google.inject.Guice;\nimport com.google.inject.TypeLiteral;\n\n@Test(groups = \"unit\", testName = \"ParseOsFamilyVersion64BitFromImageNameTest\")\npublic class ParseOsFamilyVersion64BitFromImageNameTest {\n   Json json = new GsonWrapper(new Gson());\n\n   //TODO: update osmatches corresponding with server_templates.json, this may imply an update to ComputeServiceConstants and/or OsFamily\n   @DataProvider(name = \"data\")\n   public Object[][] createData() throws IOException {\n      InputStream is = ParseOsFamilyVersion64BitFromImageNameTest.class.getResourceAsStream(\"/osmatches.json\");\n      Map<String, OsFamilyVersion64Bit> values = json.fromJson(Strings2.toStringAndClose(is),\n            new TypeLiteral<Map<String, OsFamilyVersion64Bit>>() {\n            }.getType());\n\n      return newArrayList(\n            transform(values.entrySet(), new Function<Map.Entry<String, OsFamilyVersion64Bit>, Object[]>() {\n\n               @Override\n               public Object[] apply(Entry<String, OsFamilyVersion64Bit> input) {\n                  return new Object[] { input.getKey(), input.getValue() };\n               }\n\n            })).toArray(new Object[][] {});\n   }\n\n   ParseOsFamilyVersion64BitFromImageName parser = new ParseOsFamilyVersion64BitFromImageName(new BaseComputeServiceContextModule() {\n      }.provideOsVersionMap(new ComputeServiceConstants.ReferenceData(), Guice.createInjector(new GsonModule())\n            .getInstance(Json.class)));\n\n   @Test(dataProvider = \"data\")\n   public void test(String input, OsFamilyVersion64Bit expected) {\n      assertEquals(parser.apply(input), expected);\n   }\n}\n"
  },
  {
    "path": "providers/glesys/src/test/java/org/jclouds/glesys/compute/functions/ServerDetailsToNodeMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.compute.functions;\n\nimport static org.jclouds.io.Payloads.newUrlEncodedFormPayload;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport org.jclouds.compute.domain.HardwareBuilder;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadata.Status;\nimport org.jclouds.compute.domain.NodeMetadataBuilder;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.Processor;\nimport org.jclouds.compute.domain.Volume;\nimport org.jclouds.compute.domain.internal.VolumeImpl;\nimport org.jclouds.glesys.compute.internal.BaseGleSYSComputeServiceExpectTest;\nimport org.jclouds.glesys.features.ServerApiExpectTest;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * TODO\n */\n@Test(groups = \"unit\", testName = \"ServerDetailsToNodeMetadataTest\")\npublic class ServerDetailsToNodeMetadataTest extends BaseGleSYSComputeServiceExpectTest {\n\n   @Test\n   public void testServerDetailsRequest() {\n\n      ServerDetailsToNodeMetadata toTest = injectorForKnownArgumentsAndConstantPassword(\n            ImmutableMap\n                  .<HttpRequest, HttpResponse> builder()\n                  .put(HttpRequest\n                        .builder()\n                        .method(\"POST\")\n                        .endpoint(\"https://api.glesys.com/server/details/format/json\")\n                        .addHeader(\"Accept\", \"application/json\")\n                        .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                        .payload(\n                              newUrlEncodedFormPayload(ImmutableMultimap.<String, String> builder()\n                                    .put(\"serverid\", \"xm3276891\").build())).build(),\n                        HttpResponse\n                              .builder()\n                              .statusCode(200)\n                              .payload(payloadFromResource(\"/server_details.json\"))\n                              .build()).build()\n\n      ).getInstance(ServerDetailsToNodeMetadata.class);\n\n      NodeMetadata actual = toTest.apply(ServerApiExpectTest.expectedServerDetails());\n      assertNotNull(actual);\n\n      assertEquals(\n            actual.toString(),\n            new NodeMetadataBuilder()\n                  .ids(\"vz1840356\")\n                  .name(\"glesys-s\")\n                  .hostname(\"glesys-s\")\n                  .group(\"glesys\")\n                  .imageId(\"Ubuntu 10.04 LTS 32-bit\")\n                  .operatingSystem(\n                        OperatingSystem.builder().name(\"Ubuntu 10.04 LTS 32-bit\").family(OsFamily.UBUNTU).version(\"10.04\")\n                              .is64Bit(false).description(\"Ubuntu 10.04 LTS 32-bit\").build())\n                  .publicAddresses(ImmutableSet.of(\"31.192.231.254\"))\n                  .hardware(\n                        new HardwareBuilder().ids(\"vz1840356\").ram(512)\n                              .processors(ImmutableList.of(new Processor(1, 1.0)))\n                              .volumes(ImmutableList.<Volume> of(new VolumeImpl(5f, true, true))).hypervisor(\"OpenVZ\")\n                              .build()).status(Status.RUNNING).build().toString());\n   }\n}\n"
  },
  {
    "path": "providers/glesys/src/test/java/org/jclouds/glesys/compute/functions/ServerSpecToHardwareTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.compute.functions;\n\nimport org.jclouds.glesys.compute.internal.BaseGleSYSComputeServiceExpectTest;\nimport org.testng.annotations.Test;\n\n/**\n * TODO\n */\n@Test(groups = \"unit\")\npublic class ServerSpecToHardwareTest extends BaseGleSYSComputeServiceExpectTest {\n\n   @Test\n   public void testHardwareRequest() {\n      \n      injectorForKnownArgumentsAndConstantPassword().getInstance(ServerSpecToHardware.class);\n\n   }\n\n\n}\n"
  },
  {
    "path": "providers/glesys/src/test/java/org/jclouds/glesys/compute/internal/BaseGleSYSComputeServiceExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.compute.internal;\n\nimport java.util.Map;\nimport java.util.Properties;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.compute.ComputeService;\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.glesys.GleSYSApiMetadata;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rest.internal.BaseRestApiExpectTest;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.inject.Injector;\nimport com.google.inject.Module;\n\n/**\n * Base class for writing GleSYS Expect tests for ComputeService operations\n */\npublic abstract class BaseGleSYSComputeServiceExpectTest extends BaseRestApiExpectTest<ComputeService> {\n\n   public BaseGleSYSComputeServiceExpectTest() {\n      provider = \"glesys\";\n   }\n\n   @Override\n   protected ApiMetadata createApiMetadata() {\n      return new GleSYSApiMetadata();\n   }\n\n   @Override\n   public ComputeService createClient(Function<HttpRequest, HttpResponse> fn, Module module, Properties props) {\n      return createInjector(fn, module, props).getInstance(ComputeService.class);\n   }\n\n   protected Injector injectorForKnownArgumentsAndConstantPassword() {\n      return injectorForKnownArgumentsAndConstantPassword(ImmutableMap.<HttpRequest, HttpResponse> of());\n   }\n\n   protected Injector injectorForKnownArgumentsAndConstantPassword(Map<HttpRequest, HttpResponse> requestsResponses) {\n      return computeContextForKnownArgumentsAndConstantPassword(requestsResponses).utils().injector();\n   }\n\n   protected ComputeServiceContext computeContextForKnownArgumentsAndConstantPassword(\n         Map<HttpRequest, HttpResponse> requestsResponses) {\n      return requestsSendResponses(\n            ImmutableMap\n                  .<HttpRequest, HttpResponse> builder()\n                  .put(HttpRequest\n                        .builder()\n                        .method(\"GET\")\n                        .endpoint(\"https://api.glesys.com/server/templates/format/json\")\n                        .addHeader(\"Accept\", \"application/json\")\n                        .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\").build(),\n                        HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/server_templates.json\"))\n                              .build())\n                  .put(HttpRequest\n                        .builder()\n                        .method(\"GET\")\n                        .endpoint(\"https://api.glesys.com/server/allowedarguments/format/json\")\n                        .addHeader(\"Accept\", \"application/json\")\n                        .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\").build(),\n                        HttpResponse.builder().statusCode(204)\n                              .payload(payloadFromResource(\"/server_allowed_arguments.json\")).build())\n                  .putAll(requestsResponses).build()).getContext();\n   }\n\n   protected ComputeServiceContext computeContextForKnownArgumentsAndConstantPassword() {\n      return computeContextForKnownArgumentsAndConstantPassword(ImmutableMap.<HttpRequest, HttpResponse> of());\n   }\n}\n"
  },
  {
    "path": "providers/glesys/src/test/java/org/jclouds/glesys/compute/options/GleSYSTemplateOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.compute.options;\n\nimport static org.jclouds.glesys.compute.options.GleSYSTemplateOptions.Builder.ip;\nimport static org.jclouds.glesys.compute.options.GleSYSTemplateOptions.Builder.rootPassword;\nimport static org.jclouds.glesys.compute.options.GleSYSTemplateOptions.Builder.transferGB;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.testng.annotations.Test;\n\n/**\n * Tests possible uses of {@code GleSYSTemplateOptions} and {@code\n * GleSYSTemplateOptions.Builder.*}.\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"GleSYSTemplateOptionsTest\")\npublic class GleSYSTemplateOptionsTest {\n   @Test\n   public void testAs() {\n      TemplateOptions options = new GleSYSTemplateOptions();\n      assertEquals(options.as(GleSYSTemplateOptions.class), options);\n   }\n\n   @Test\n   public void testDefaultip() {\n      TemplateOptions options = new GleSYSTemplateOptions();\n      assertEquals(options.as(GleSYSTemplateOptions.class).getIp(), \"any\");\n   }\n\n   @Test\n   public void testip() {\n      TemplateOptions options = new GleSYSTemplateOptions().ip(\"1.1.1.1\");\n      assertEquals(options.as(GleSYSTemplateOptions.class).getIp(), \"1.1.1.1\");\n   }\n\n   @Test\n   public void testipStatic() {\n      TemplateOptions options = ip(\"1.1.1.1\");\n      assertEquals(options.as(GleSYSTemplateOptions.class).getIp(), \"1.1.1.1\");\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testNullIpThrowsNPE() {\n      new GleSYSTemplateOptions().ip(null);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testInvalidIpThrowsIllegalArgument() {\n      new GleSYSTemplateOptions().ip(\"1.1.1\");\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testipIsInvalidThrowsIllegalArgument() {\n      new GleSYSTemplateOptions().ip(\"foo\");\n   }\n\n   @Test\n   public void testDefaultRootPassword() {\n      TemplateOptions options = new GleSYSTemplateOptions();\n      assertEquals(options.as(GleSYSTemplateOptions.class).getRootPassword(), null);\n   }\n\n   @Test\n   public void testRootPassword() {\n      TemplateOptions options = new GleSYSTemplateOptions().rootPassword(\"secret\");\n      assertEquals(options.as(GleSYSTemplateOptions.class).getRootPassword(), \"secret\");\n   }   \n\n   @Test\n   public void testRootPasswordStatic() {\n      TemplateOptions options = rootPassword(\"secret\");\n      assertEquals(options.as(GleSYSTemplateOptions.class).getRootPassword(), \"secret\");\n   }   \n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testNullRootPasswordThrowsNPE() {\n      new GleSYSTemplateOptions().rootPassword(null);\n   }   \n\n   @Test\n   public void testDefaultTranferGB() {\n      TemplateOptions options = new GleSYSTemplateOptions();\n      assertEquals(options.as(GleSYSTemplateOptions.class).getTransferGB(), 50);\n   }\n\n   @Test\n   public void testTransferGB() {\n      TemplateOptions options = new GleSYSTemplateOptions().transferGB(75);\n      assertEquals(options.as(GleSYSTemplateOptions.class).getTransferGB(), 75);\n   }   \n\n   @Test\n   public void testTransferGBStatic() {\n      TemplateOptions options = transferGB(75);\n      assertEquals(options.as(GleSYSTemplateOptions.class).getTransferGB(), 75);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testNegativeTransferGBThrowsException() {\n      new GleSYSTemplateOptions().transferGB(-1);\n   }\n   \n   @Test\n   public void testClone() {\n      GleSYSTemplateOptions clone = transferGB(75).rootPassword(\"root\").ip(\"1.1.1.1\").clone();\n      assertEquals(clone.getTransferGB(), 75);\n      assertEquals(clone.getRootPassword(), \"root\");\n      assertEquals(clone.getIp(), \"1.1.1.1\");\n   }\n}\n"
  },
  {
    "path": "providers/glesys/src/test/java/org/jclouds/glesys/features/ArchiveApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\n\nimport org.jclouds.glesys.domain.Archive;\nimport org.jclouds.glesys.domain.ArchiveAllowedArguments;\nimport org.jclouds.glesys.internal.BaseGleSYSApiExpectTest;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests parsing of {@code ArchiveApi}\n */\n@Test(groups = \"unit\", testName = \"ArchiveApiExpectTest\")\npublic class ArchiveApiExpectTest extends BaseGleSYSApiExpectTest {\n\n   public void testListArchivesWhenReponseIs2xx() throws Exception {\n      ArchiveApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/archive/list/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\").build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/archive_list.json\")).build())\n            .getArchiveApi();\n\n      Set<Archive> expected = ImmutableSet.of(\n            Archive.builder().username(\"xxxxx_test1\").freeSize(\"20 GB\").totalSize(\"30 GB\").locked(false).build());\n\n      assertEquals(api.list().toSet(), expected);\n   }\n\n   public void testListArchivesWhenResponseIs4xxReturnsEmpty() {\n      ArchiveApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/archive/list/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\").build(),\n            HttpResponse.builder().statusCode(404).build()).getArchiveApi();\n\n      assertTrue(api.list().isEmpty());\n   }\n\n   public void testArchiveDetailsWhenResponseIs2xx() throws Exception {\n      ArchiveApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/archive/details/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"username\", \"xxxxxx_test1\").build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/archive_details.json\")).build())\n            .getArchiveApi();\n\n      assertEquals(api.get(\"xxxxxx_test1\"), detailsInArchiveDetails());\n   }\n\n   private Archive detailsInArchiveDetails() {\n      return Archive.builder().username(\"xxxxxx_test1\").freeSize(\"30 GB\").totalSize(\"30 GB\").locked(false).build();\n   }\n\n   public void testArchiveDetailsWhenResponseIs4xxReturnsNull() {\n      ArchiveApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/archive/details/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"username\", \"xxxxxx_test1\").build(),\n            HttpResponse.builder().statusCode(404).build())\n            .getArchiveApi();\n      assertNull(api.get(\"xxxxxx_test1\"));\n   }\n\n   public void testCreateArchiveWhenResponseIs2xx() throws Exception {\n      ArchiveApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/archive/create/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParams(ImmutableMultimap.<String, String>builder()\n                             .put(\"username\", \"xxxxxx_test1\")\n                             .put(\"password\", \"somepass\")\n                             .put(\"size\", \"5\").build()).build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/archive_details.json\")).build()).getArchiveApi();\n      assertEquals(api.createWithCredentialsAndSize(\"xxxxxx_test1\", \"somepass\", 5), detailsInArchiveDetails());\n   }\n\n   public void testDeleteArchiveWhenResponseIs2xx() throws Exception {\n      ArchiveApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/archive/delete/format/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"username\", \"xxxxxx_test1\").build(),\n            HttpResponse.builder().statusCode(200).build()).getArchiveApi();\n\n      api.delete(\"xxxxxx_test1\");\n   }\n\n   @Test(expectedExceptions = {HttpResponseException.class})\n   public void testDeleteArchiveWhenResponseIs4xxThrows() throws Exception {\n      ArchiveApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/archive/delete/format/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"username\", \"xxxxxx_test1\").build(),\n            HttpResponse.builder().statusCode(402).build()).getArchiveApi();\n      api.delete(\"xxxxxx_test1\");\n   }\n\n   public void testResizeArchiveWhenResponseIs2xx() throws Exception {\n      ArchiveApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/archive/resize/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"username\", \"username1\")\n                       .addFormParam(\"size\", \"5\").build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/archive_details.json\")).build()).getArchiveApi();\n\n      assertEquals(api.resize(\"username1\", 5), detailsInArchiveDetails());\n   }\n\n   @Test(expectedExceptions = {ResourceNotFoundException.class})\n   public void testResizeArchiveWhenResponseIs4xxThrows() throws Exception {\n      ArchiveApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/archive/resize/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"username\", \"username1\")\n                       .addFormParam(\"size\", \"5\").build(),\n            HttpResponse.builder().statusCode(404).build()).getArchiveApi();\n\n      api.resize(\"username1\", 5);\n   }\n\n   public void testChangeArchivePasswordWhenResponseIs2xx() throws Exception {\n      ArchiveApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\")\n                       .endpoint(\"https://api.glesys.com/archive/changepassword/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"username\", \"username\")\n                       .addFormParam(\"password\", \"newpass\").build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/archive_details.json\")).build()).getArchiveApi();\n      \n      assertEquals(api.changePassword(\"username\", \"newpass\"), detailsInArchiveDetails());\n   }\n\n   @Test(expectedExceptions = {ResourceNotFoundException.class})\n   public void testChangeArchivePasswordWhenResponseIs4xxThrows() throws Exception {\n      ArchiveApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\")\n                  .endpoint(\"https://api.glesys.com/archive/changepassword/format/json\")\n                  .addHeader(\"Accept\", \"application/json\")\n                  .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                  .addFormParam(\"username\", \"username\")\n                  .addFormParam(\"password\", \"newpass\").build(),\n            HttpResponse.builder().statusCode(404).build()).getArchiveApi();\n\n      api.changePassword(\"username\", \"newpass\");\n   }\n\n   public void testGetArchiveAllowedArgumentsWhenResponseIs2xx() throws Exception {\n      ArchiveApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"GET\")\n                  .endpoint(\"https://api.glesys.com/archive/allowedarguments/format/json\")\n                  .addHeader(\"Accept\", \"application/json\")\n                  .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\").build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/archive_allowed_arguments.json\")).build()).getArchiveApi();\n      ArchiveAllowedArguments expected = ArchiveAllowedArguments.builder().archiveSizes(10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 125, 150, 175, 200, 225, 250, 275, 300, 325, 350, 375, 400, 425, 450, 475, 500, 550, 600, 650, 700, 750, 800, 850, 900, 950, 1000).build();\n\n      assertEquals(api.getAllowedArguments(), expected);\n   }\n\n   public void testGetArchiveAllowedArguments4xxWhenResponseIs2xx() throws Exception {\n      ArchiveApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"GET\")\n                  .endpoint(\"https://api.glesys.com/archive/allowedarguments/format/json\")\n                  .addHeader(\"Accept\", \"application/json\")\n                  .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\").build(),\n            HttpResponse.builder().statusCode(404).build()).getArchiveApi();\n\n      assertNull(api.getAllowedArguments());\n   }\n}\n"
  },
  {
    "path": "providers/glesys/src/test/java/org/jclouds/glesys/features/ArchiveApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.features;\n\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static org.jclouds.util.Predicates2.retry;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.glesys.domain.Archive;\nimport org.jclouds.glesys.domain.ArchiveAllowedArguments;\nimport org.jclouds.glesys.internal.BaseGleSYSApiLiveTest;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\n\n/**\n * Tests behavior of {@code ArchiveApi}\n */\n@Test(groups = \"live\", testName = \"ArchiveApiLiveTest\", singleThreaded = true)\npublic class ArchiveApiLiveTest extends BaseGleSYSApiLiveTest {\n\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   public void setup() {\n      super.setup();\n\n      archiveApi = api.getArchiveApi();\n      archiveUser = identity.toLowerCase() + \"_test9\";\n      archiveCounter = retry(new Predicate<Integer>() {\n         public boolean apply(Integer value) {\n            return archiveApi.list().size() == value.intValue();\n         }\n      }, 30, 1, SECONDS);\n   }\n\n   @AfterClass(groups = { \"integration\", \"live\" })\n   protected void tearDown() {\n      int before = archiveApi.list().size();\n      archiveApi.delete(archiveUser);\n      assertTrue(archiveCounter.apply(before - 1));\n\n      super.tearDown();\n   }\n\n   private ArchiveApi archiveApi;\n   private String archiveUser;\n   private Predicate<Integer> archiveCounter;\n\n   @Test\n   public void testAllowedArguments() throws Exception {\n      ArchiveAllowedArguments args = archiveApi.getAllowedArguments();\n      assertNotNull(args);\n      assertNotNull(args.getSizes());\n      assertTrue(!args.getSizes().isEmpty());\n\n      for (int size : args.getSizes()) {\n         assertTrue(size > 0);\n      }\n   }\n\n   @Test\n   public void testCreateArchive() throws Exception {\n      try {\n         archiveApi.delete(archiveUser);\n      } catch (Exception ex) {\n      }\n\n      int before = archiveApi.list().size();\n\n      archiveApi.createWithCredentialsAndSize(archiveUser, \"password\", 10);\n\n      assertTrue(archiveCounter.apply(before + 1));\n   }\n\n   @Test(dependsOnMethods = \"testCreateArchive\")\n   public void testArchiveDetails() throws Exception {\n      Archive details = archiveApi.get(archiveUser);\n      assertEquals(details.getUsername(), archiveUser);\n   }\n\n   @Test(dependsOnMethods = \"testCreateArchive\")\n   public void testChangePassword() throws Exception {\n      archiveApi.changePassword(archiveUser, \"newpassword\");\n      // TODO assert something useful!\n   }\n\n   @Test(dependsOnMethods = \"testCreateArchive\")\n   public void testResizeArchive() throws Exception {\n      archiveApi.resize(archiveUser, 20);\n\n      assertTrue(retry(new Predicate<String>() {\n         public boolean apply(String value) {\n            return archiveApi.get(archiveUser) != null && value.equals(archiveApi.get(archiveUser).getTotalSize());\n         }\n      }, 30, 1, SECONDS).apply(\"20 GB\"));\n   }\n\n}\n"
  },
  {
    "path": "providers/glesys/src/test/java/org/jclouds/glesys/features/DomainApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.glesys.domain.Domain;\nimport org.jclouds.glesys.domain.DomainRecord;\nimport org.jclouds.glesys.internal.BaseGleSYSApiExpectTest;\nimport org.jclouds.glesys.options.AddDomainOptions;\nimport org.jclouds.glesys.options.DomainOptions;\nimport org.jclouds.glesys.options.UpdateRecordOptions;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\n\n/**\n * Tests annotation parsing of {@code DomainApi}\n */\n@Test(groups = \"unit\", testName = \"DomainApiExpectTest\")\npublic class DomainApiExpectTest extends BaseGleSYSApiExpectTest {\n   \n   public void testListDomainsWhenResponseIs2xx() throws Exception {\n      DomainApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/domain/list/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\").build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/domain_list.json\")).build()).getDomainApi();\n\n      Domain expected =\n            Domain.builder().domainName(\"testglesys.jclouds.org\").createTime(dateService.iso8601SecondsDateParse(\"2012-01-31T12:19:03+01:00\")).build();\n\n      Domain actual = Iterables.getOnlyElement(api.list());\n      assertEquals(expected.getName(), actual.getName());\n      assertEquals(expected.getCreateTime(), actual.getCreateTime());\n   }\n\n   public void testListDomainsWhenResponseIs4xxReturnsEmpty() throws Exception {\n      DomainApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/domain/list/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\").build(),\n            HttpResponse.builder().statusCode(404).build()).getDomainApi();\n\n      assertTrue(api.list().isEmpty());\n   }\n\n   public void testListDomainRecordsWhenResponseIs2xx() throws Exception {\n      DomainApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/domain/listrecords/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"domainname\", \"testglesys.jclouds.org\").build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/domain_list_records.json\")).build()).getDomainApi();\n\n      Set<DomainRecord> expected = ImmutableSet.of(\n            DomainRecord.builder().id(\"224538\").domainname(\"testglesys.jclouds.org\").host(\"@\").type(\"NS\").data(\"ns1.namesystem.se.\").ttl(3600).build(),\n            DomainRecord.builder().id(\"224539\").domainname(\"testglesys.jclouds.org\").host(\"@\").type(\"NS\").data(\"ns2.namesystem.se.\").ttl(3600).build(),\n            DomainRecord.builder().id(\"224540\").domainname(\"testglesys.jclouds.org\").host(\"@\").type(\"NS\").data(\"ns3.namesystem.se.\").ttl(3600).build(),\n            DomainRecord.builder().id(\"224541\").domainname(\"testglesys.jclouds.org\").host(\"@\").type(\"A\").data(\"127.0.0.1\").ttl(3600).build(),\n            DomainRecord.builder().id(\"224542\").domainname(\"testglesys.jclouds.org\").host(\"www\").type(\"A\").data(\"127.0.0.1\").ttl(3600).build(),\n            DomainRecord.builder().id(\"224543\").domainname(\"testglesys.jclouds.org\").host(\"mail\").type(\"A\").data(\"79.99.4.40\").ttl(3600).build(),\n            DomainRecord.builder().id(\"224544\").domainname(\"testglesys.jclouds.org\").host(\"@\").type(\"MX\").data(\"10 mx01.glesys.se.\").ttl(3600).build(),\n            DomainRecord.builder().id(\"224545\").domainname(\"testglesys.jclouds.org\").host(\"@\").type(\"MX\").data(\"20 mx02.glesys.se.\").ttl(3600).build(),\n            DomainRecord.builder().id(\"224546\").domainname(\"testglesys.jclouds.org\").host(\"@\").type(\"TXT\").data(\"v=spf1 include:spf.glesys.se -all\").ttl(3600).build()\n      );\n\n      Set<DomainRecord> actual = api.listRecords(\"testglesys.jclouds.org\");\n\n      assertEquals(actual, expected);\n\n      for (DomainRecord result : actual) {\n         for (DomainRecord expect : expected) {\n            if (result.equals(expect)) {\n               assertEquals(result.toString(), expect.toString(), \"Deep comparison using toString() failed!\");\n            }\n         }\n      }\n   }\n\n   public void testListDomainRecordsWhenResponseIs4xxReturnsEmpty() throws Exception {\n      DomainApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/domain/list/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\").build(),\n            HttpResponse.builder().statusCode(404).build()).getDomainApi();\n\n      assertTrue(api.list().isEmpty());\n   }\n\n   public void testAddDomainRecordsWhenResponseIs2xx() throws Exception {\n      DomainApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/domain/addrecord/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"domainname\", \"jclouds.org\")\n                       .addFormParam(\"host\", \"jclouds.org\")\n                       .addFormParam(\"type\", \"A\")\n                       .addFormParam(\"data\", \"\").build(),\n            HttpResponse.builder().statusCode(200)\n                  .payload(payloadFromResourceWithContentType(\"/domain_record.json\", MediaType.APPLICATION_JSON)).build())\n            .getDomainApi();\n\n      assertEquals(api.createRecord(\"jclouds.org\", \"jclouds.org\", \"A\", \"\"), recordInDomainRecord());\n   }\n\n   protected DomainRecord recordInDomainRecord() {\n      return DomainRecord.builder().id(\"256151\").domainname(\"cl13016-domain.jclouds.org\").host(\"test\").type(\"A\").data(\"127.0.0.1\").ttl(3600).build();\n   }\n\n   @Test(expectedExceptions = ResourceNotFoundException.class)\n   public void testAddDomainRecordsWhenResponseIs4xx() throws Exception {\n      DomainApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/domain/addrecord/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"domainname\", \"jclouds.org\")\n                       .addFormParam(\"host\", \"jclouds.org\")\n                       .addFormParam(\"type\", \"A\")\n                       .addFormParam(\"data\", \"\").build(),\n            HttpResponse.builder().statusCode(404).build()).getDomainApi();\n\n      api.createRecord(\"jclouds.org\", \"jclouds.org\", \"A\", \"\");\n   }\n\n   public void testUpdateDomainRecordsWhenResponseIs2xx() throws Exception {\n      DomainApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/domain/updaterecord/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"recordid\", \"256151\")\n                       .addFormParam(\"host\", \"somehost\")\n                       .addFormParam(\"ttl\", \"1800\").build(),\n            HttpResponse.builder().statusCode(200)\n                  .payload(payloadFromResourceWithContentType(\"/domain_record.json\", MediaType.APPLICATION_JSON)).build())\n            .getDomainApi();\n\n      assertEquals(api.updateRecord(\"256151\", UpdateRecordOptions.Builder.host(\"somehost\").ttl(1800)), recordInDomainRecord());\n   }\n\n   @Test(expectedExceptions = ResourceNotFoundException.class)\n   public void testUpdateDomainRecordsWhenResponseIs4xx() throws Exception {\n      DomainApi api = requestSendsResponse(\n               HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/domain/updaterecord/format/json\")\n                          .addHeader(\"Accept\", \"application/json\")\n                          .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                          .addFormParam(\"recordid\", \"256151\")\n                          .addFormParam(\"host\", \"somehost\")\n                          .addFormParam(\"ttl\", \"1800\").build(),\n            HttpResponse.builder().statusCode(404).build()).getDomainApi();\n\n      api.updateRecord(\"256151\", UpdateRecordOptions.Builder.host(\"somehost\").ttl(1800));\n   }\n\n   public void testDeleteDomainRecordsWhenResponseIs2xx() throws Exception {\n      DomainApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/domain/deleterecord/format/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"recordid\", \"256151\").build(),\n            HttpResponse.builder().statusCode(200)\n                  .payload(payloadFromResourceWithContentType(\"/domain_record.json\", MediaType.APPLICATION_JSON)).build())\n            .getDomainApi();\n\n      api.deleteRecord(\"256151\");\n   }\n\n   @Test(expectedExceptions = ResourceNotFoundException.class)\n   public void testDeleteDomainRecordsWhenResponseIs4xx() throws Exception {\n      DomainApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/domain/deleterecord/format/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"recordid\", \"256151\").build(),\n            HttpResponse.builder().statusCode(404).build()).getDomainApi();\n\n      api.deleteRecord(\"256151\");\n   }\n\n   public void testGetDomainWhenResponseIs2xx() throws Exception {\n      DomainApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/domain/details/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"domainname\", \"cl66666_x\").build(),\n            HttpResponse.builder().statusCode(200)\n                  .payload(payloadFromResourceWithContentType(\"/domain_details.json\", MediaType.APPLICATION_JSON)).build())\n            .getDomainApi();\n\n      assertEquals(api.get(\"cl66666_x\"), domainInDomainDetails());\n   }\n\n\n   public void testGetDomainWhenResponseIs4xx() throws Exception {\n      DomainApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/domain/details/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"domainname\", \"cl66666_x\").build(),\n            HttpResponse.builder().statusCode(404).build())\n            .getDomainApi();\n\n      assertNull(api.get(\"cl66666_x\"));\n   }\n\n   protected Domain domainInDomainDetails() {\n      return Domain.builder().domainName(\"cl13016-domain.jclouds.org\").createTime(dateService.iso8601SecondsDateParse(\"2012-06-24T11:52:49+02:00\")).recordCount(9).build();\n   }\n\n   public void testAddDomainWhenResponseIs2xx() throws Exception {\n      DomainApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/domain/add/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"domainname\", \"cl66666_x\").build(),\n            HttpResponse.builder().statusCode(200)\n                  .payload(payloadFromResourceWithContentType(\"/domain_details.json\", MediaType.APPLICATION_JSON)).build())\n            .getDomainApi();\n\n      assertEquals(api.create(\"cl66666_x\"), domainInDomainDetails());\n   }\n\n   public void testAddDomainWithOptsWhenResponseIs2xx() throws Exception {\n      DomainApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/domain/add/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"domainname\", \"cl66666_x\")\n                       .addFormParam(\"primarynameserver\", \"ns1.somewhere.x\")\n                       .addFormParam(\"expire\", \"1\")\n                       .addFormParam(\"minimum\", \"1\")\n                       .addFormParam(\"refresh\", \"1\")\n                       .addFormParam(\"responsibleperson\", \"Tester.\")\n                       .addFormParam(\"retry\", \"1\")\n                       .addFormParam(\"ttl\", \"1\").build(),\n            HttpResponse.builder().statusCode(200)\n                  .payload(payloadFromResourceWithContentType(\"/domain_details.json\", MediaType.APPLICATION_JSON)).build())\n            .getDomainApi();\n      AddDomainOptions options = (AddDomainOptions) AddDomainOptions.Builder.primaryNameServer(\"ns1.somewhere.x\")\n            .expire(1).minimum(1).refresh(1).responsiblePerson(\"Tester\").retry(1).ttl(1);\n\n      assertEquals(api.create(\"cl66666_x\", options), domainInDomainDetails());\n   }\n\n   public void testUpdateDomainWhenResponseIs2xx() throws Exception {\n      DomainApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/domain/edit/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"domainname\", \"x\")\n                       .addFormParam(\"expire\", \"1\").build(),\n            HttpResponse.builder().statusCode(200)\n                  .payload(payloadFromResourceWithContentType(\"/domain_details.json\", MediaType.APPLICATION_JSON)).build())\n            .getDomainApi();\n\n      assertEquals(api.update(\"x\", DomainOptions.Builder.expire(1)), domainInDomainDetails());\n   }\n\n   @Test(expectedExceptions = {ResourceNotFoundException.class})\n   public void testUpdateDomainWhenResponseIs4xxThrows() throws Exception {\n      DomainApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/domain/edit/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"domainname\", \"x\")\n                       .addFormParam(\"expire\", \"1\").build(),\n            HttpResponse.builder().statusCode(404).build()).getDomainApi();\n\n      api.update(\"x\", DomainOptions.Builder.expire(1));\n   }\n\n   public void testDeleteDomainWhenResponseIs2xx() throws Exception {\n      DomainApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/domain/delete/format/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"domainname\", \"x\").build(),\n            HttpResponse.builder().statusCode(200).build()).getDomainApi();\n\n      api.delete(\"x\");\n   }\n\n   @Test(expectedExceptions = {ResourceNotFoundException.class})\n   public void testDeleteDomainWhenResponseIs4xxThrows() throws Exception {\n      DomainApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/domain/delete/format/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"domainname\", \"x\").build(),\n            HttpResponse.builder().statusCode(404).build()).getDomainApi();\n\n      api.delete(\"x\");\n   }\n}\n"
  },
  {
    "path": "providers/glesys/src/test/java/org/jclouds/glesys/features/DomainApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.features;\n\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static org.jclouds.util.Predicates2.retry;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\n\nimport org.jclouds.glesys.domain.Domain;\nimport org.jclouds.glesys.domain.DomainRecord;\nimport org.jclouds.glesys.internal.BaseGleSYSApiLiveTest;\nimport org.jclouds.glesys.options.DomainOptions;\nimport org.jclouds.glesys.options.UpdateRecordOptions;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\n\n/**\n * Tests behavior of {@code DomainApi}\n */\n@Test(groups = \"live\", testName = \"DomainApiLiveTest\", singleThreaded = true)\npublic class DomainApiLiveTest extends BaseGleSYSApiLiveTest {\n   public String testDomain;\n\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   public void setup() {\n      super.setup();\n      testDomain =  identity.toLowerCase() + \"-domain.jclouds.org\";\n      domainApi = api.getDomainApi();\n      domainCounter = retry(new Predicate<Integer>() {\n         public boolean apply(Integer value) {\n            return domainApi.list().size() == value.intValue();\n         }\n      }, 30, 1, SECONDS);\n      recordCounter = retry(new Predicate<Integer>() {\n         public boolean apply(Integer value) {\n            return domainApi.listRecords(testDomain).size() == value.intValue();\n         }\n      }, 30, 1, SECONDS);\n\n      try {\n         domainApi.delete(testDomain);\n      } catch (Exception ex) {\n      }\n      \n      createDomain(testDomain);\n   }\n\n   @AfterClass(groups = { \"integration\", \"live\" })\n   public void tearDown() {\n      int before = domainApi.list().size();\n      domainApi.delete(testDomain);\n      assertTrue(domainCounter.apply(before - 1));\n   \n      super.tearDown();\n   }\n\n   private DomainApi domainApi;\n   private Predicate<Integer> domainCounter;\n   private Predicate<Integer> recordCounter;\n\n   @Test\n   public void testGetDomain() throws Exception {\n      Domain domain = domainApi.get(testDomain);\n      assertNotNull(domain);\n      assertEquals(domain.getName(), testDomain);\n      assertNotNull(domain.getCreateTime());\n   }\n   \n   @Test\n   public void testUpdateDomain() throws Exception {\n      domainApi.update(testDomain, DomainOptions.Builder.responsiblePerson(\"another-tester.jclouds.org.\"));\n      Domain domain = domainApi.get(testDomain);\n      assertEquals(domain.getResponsiblePerson(), \"another-tester.jclouds.org.\");\n   }\n\n   @Test\n   public void testCreateRecord() throws Exception {\n      int before = domainApi.listRecords(testDomain).size();\n\n      domainApi.createRecord(testDomain, \"test\", \"A\", \"127.0.0.1\");\n\n      assertTrue(recordCounter.apply(before + 1));\n\n      for (DomainRecord record : domainApi.listRecords(testDomain)) {\n         if (\"test\".equals(record.getHost())) {\n            assertEquals(record.getType(), \"A\");\n            assertEquals(record.getData(), \"127.0.0.1\");\n         }\n      }\n   }\n\n   @Test\n   public void testUpdateRecord() throws Exception {\n      int before = domainApi.listRecords(testDomain).size();\n\n      domainApi.createRecord(testDomain, \"testeditbefore\", \"A\", \"127.0.0.1\");\n\n      assertTrue(recordCounter.apply(before + 1));\n\n      String recordId = null;\n      for (DomainRecord record : domainApi.listRecords(testDomain)) {\n         if (\"testeditbefore\".equals(record.getHost())) {\n            assertEquals(record.getType(), \"A\");\n            assertEquals(record.getData(), \"127.0.0.1\");\n            recordId = record.getId();\n         }\n      }\n\n      assertNotNull(recordId);\n\n      domainApi.updateRecord(recordId, UpdateRecordOptions.Builder.host(\"testeditafter\"));\n\n      boolean found = false;\n      for (DomainRecord record : domainApi.listRecords(testDomain)) {\n         if (recordId.equals(record.getId())) {\n            assertEquals(record.getHost(), \"testeditafter\");\n            assertEquals(record.getType(), \"A\");\n            assertEquals(record.getData(), \"127.0.0.1\");\n            found = true;\n         }\n      }\n      assertTrue(found);\n   }\n\n   @Test\n   public void testDeleteRecord() throws Exception {\n      Set<DomainRecord> domainRecords = domainApi.listRecords(testDomain);\n\n      int before = domainRecords.size();\n      \n      domainApi.deleteRecord(domainRecords.iterator().next().getId());\n\n      assertTrue(recordCounter.apply(before - 1));\n   }\n}\n"
  },
  {
    "path": "providers/glesys/src/test/java/org/jclouds/glesys/features/EmailAccountApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.glesys.domain.EmailAccount;\nimport org.jclouds.glesys.domain.EmailAlias;\nimport org.jclouds.glesys.domain.EmailOverview;\nimport org.jclouds.glesys.domain.EmailOverviewDomain;\nimport org.jclouds.glesys.domain.EmailOverviewSummary;\nimport org.jclouds.glesys.domain.EmailQuota;\nimport org.jclouds.glesys.internal.BaseGleSYSApiExpectTest;\nimport org.jclouds.glesys.options.UpdateAccountOptions;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\n\n/**\n * Tests annotation parsing of {@code EmailAccountApi}\n */\n@Test(groups = \"unit\", testName = \"EmailAccountApiExpectTest\")\npublic class EmailAccountApiExpectTest extends BaseGleSYSApiExpectTest {\n\n   public void testListWhenResponseIs2xx() throws Exception {\n      EmailAccountApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/email/list/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"domainname\", \"cl13016.test.jclouds.org\").build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/email_list.json\")).build()).getEmailAccountApi();\n\n      EmailAccount.Builder<?> builder = EmailAccount.builder().quota(EmailQuota.builder().max(200).unit(\"MB\").build()).antispamLevel(3).antiVirus(true).autoRespond(false).autoRespondSaveEmail(true);\n      Set<EmailAccount> expected =\n            ImmutableSet.of(\n                  builder.account(\"test1@cl13016.test.jclouds.org\").antispamLevel(3)\n                        .created(dateService.iso8601SecondsDateParse(\"2012-06-24T11:53:45+02:00\")).build(),\n                  builder.account(\"test@cl13016.test.jclouds.org\").antispamLevel(3)\n                        .created(dateService.iso8601SecondsDateParse(\"2012-06-21T11:26:09+02:00\"))\n                        .modified(dateService.iso8601SecondsDateParse(\"2012-06-24T11:53:48+02:00\")).build()\n            );\n\n      Set<EmailAccount> actual = api.listDomain(\"cl13016.test.jclouds.org\").toSet();\n      assertEquals(actual, expected);\n      assertEquals(Iterables.get(actual, 0).toString(), Iterables.get(expected, 0).toString());\n   }\n\n   public void testListWhenResponseIs404IsEmpty() throws Exception {\n      EmailAccountApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/email/list/format/json\")\n                  .addHeader(\"Accept\", \"application/json\")\n                  .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                  .addFormParam(\"domainname\", \"test\").build(),\n            HttpResponse.builder().statusCode(404).build()).getEmailAccountApi();\n\n      assertTrue(api.listDomain(\"test\").isEmpty());\n   }\n\n   public void testListAliasesWhenResponseIs2xx() throws Exception {\n      EmailAccountApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/email/list/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"domainname\", \"cl13016.test.jclouds.org\").build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/email_list.json\")).build()).getEmailAccountApi();\n\n      EmailAlias expected = EmailAlias.builder().alias(\"test2@cl13016.test.jclouds.org\").forwardTo(\"test2@cl13016.test.jclouds.org\").build();\n      EmailAlias actual = Iterables.getOnlyElement(api.listAliasesInDomain(\"cl13016.test.jclouds.org\"));\n      assertEquals(actual, expected);\n   }\n\n   public void testListAliasesWhenResponseIs404IsEmpty() throws Exception {\n      EmailAccountApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/email/list/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"domainname\", \"test\").build(),\n            HttpResponse.builder().statusCode(404).build()).getEmailAccountApi();\n\n      assertTrue(api.listAliasesInDomain(\"test\").isEmpty());\n   }\n\n   public void testOverviewWhenResponseIs2xx() throws Exception {\n      EmailAccountApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/email/overview/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\").build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/email_overview.json\")).build()).getEmailAccountApi();\n\n      EmailOverviewSummary summary = EmailOverviewSummary.builder().accounts(2).maxAccounts(50).aliases(1).maxAliases(1000).build();\n      EmailOverviewDomain domain = EmailOverviewDomain.builder().domain(\"cl13016.test.jclouds.org\").accounts(2).aliases(0).build();\n      EmailOverview expected = EmailOverview.builder().summary(summary).domains(domain).build();\n\n      assertEquals(api.getOverview(), expected);\n   }\n\n   public void testOverviewWhenResponseIs404ReturnsNull() throws Exception {\n      EmailAccountApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/email/overview/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\").build(),\n            HttpResponse.builder().statusCode(404).build()).getEmailAccountApi();\n\n      assertNull(api.getOverview());\n   }\n\n   public void testCreateAccountWhenResponseIs2xx() throws Exception {\n      EmailAccountApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/email/createaccount/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"emailaccount\", \"test@jclouds.org\")\n                       .addFormParam(\"password\", \"newpass\").build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResourceWithContentType(\"/email_details.json\", MediaType.APPLICATION_JSON)).build())\n            .getEmailAccountApi();\n\n      assertEquals(api.createWithPassword(\"test@jclouds.org\", \"newpass\").toString(), getEmailAccountInDetails().toString());\n   }\n\n   public void testUpdateAccountWhenResponseIs2xx() throws Exception {\n      EmailAccountApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/email/editaccount/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"emailaccount\", \"test@jclouds.org\")\n                       .addFormParam(\"password\", \"anotherpass\").build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResourceWithContentType(\"/email_details.json\", MediaType.APPLICATION_JSON)).build())\n            .getEmailAccountApi();\n\n      assertEquals(api.update(\"test@jclouds.org\", UpdateAccountOptions.Builder.password(\"anotherpass\")).toString(), getEmailAccountInDetails().toString());\n   }\n\n   @Test(expectedExceptions = ResourceNotFoundException.class)\n   public void testUpdateAccountWhenResponseIs4xx() throws Exception {\n      EmailAccountApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/email/editaccount/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"emailaccount\", \"test@jclouds.org\")\n                       .addFormParam(\"password\", \"anotherpass\").build(),\n            HttpResponse.builder().statusCode(404).build())\n            .getEmailAccountApi();\n\n      assertEquals(api.update(\"test@jclouds.org\", UpdateAccountOptions.Builder.password(\"anotherpass\")).toString(), getEmailAccountInDetails().toString());\n   }\n\n   private EmailAccount getEmailAccountInDetails() {\n      return EmailAccount.builder().account(\"test@CL13016.jclouds.org\")\n            .antispamLevel(3)\n            .antiVirus(true)\n            .autoRespondSaveEmail(true)\n            .created(dateService.iso8601SecondsDateParse(\"2012-06-20T12:01:01+02:00\"))\n            .quota(EmailQuota.builder().max(200).unit(\"MB\").build()).build();\n   }\n\n   @Test(expectedExceptions = {ResourceNotFoundException.class})\n   public void testCreateAccountWhenResponseIs4xxThrows() throws Exception {\n      EmailAccountApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/email/createaccount/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"emailaccount\", \"test@jclouds.org\")\n                       .addFormParam(\"password\", \"newpass\").build(),\n            HttpResponse.builder().statusCode(404).build()).getEmailAccountApi();\n\n      api.createWithPassword(\"test@jclouds.org\", \"newpass\");\n   }\n\n   public void testCreateAliasWhenResponseIs2xx() throws Exception {\n      EmailAccountApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/email/createalias/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"emailalias\", \"test2@jclouds.org\")\n                       .addFormParam(\"goto\", \"test@jclouds.org\").build(),\n            HttpResponse.builder().statusCode(200).build()).getEmailAccountApi();\n\n      api.createAlias(\"test2@jclouds.org\", \"test@jclouds.org\");\n   }\n\n   @Test(expectedExceptions = {AuthorizationException.class})\n   public void testCreateAliasWhenResponseIs4xxThrows() throws Exception {\n      EmailAccountApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/email/createalias/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"emailalias\", \"test2@jclouds.org\")\n                       .addFormParam(\"goto\", \"test@jclouds.org\").build(),\n            HttpResponse.builder().statusCode(401).build()).getEmailAccountApi();\n\n      api.createAlias(\"test2@jclouds.org\", \"test@jclouds.org\");\n   }\n\n   public void testUpdateAliasWhenResponseIs2xx() throws Exception {\n      EmailAccountApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/email/editalias/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"emailalias\", \"test2@jclouds.org\")\n                       .addFormParam(\"goto\", \"test@jclouds.org\").build(),\n            HttpResponse.builder().statusCode(200).build()).getEmailAccountApi();\n\n      api.updateAlias(\"test2@jclouds.org\", \"test@jclouds.org\");\n   }\n\n   @Test(expectedExceptions = {ResourceNotFoundException.class})\n   public void testUpdateAliasWhenResponseIs4xxThrows() throws Exception {\n      EmailAccountApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/email/editalias/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"emailalias\", \"test2@jclouds.org\")\n                       .addFormParam(\"goto\", \"test@jclouds.org\").build(),\n            HttpResponse.builder().statusCode(404).build()).getEmailAccountApi();\n\n      api.updateAlias(\"test2@jclouds.org\", \"test@jclouds.org\");\n   }\n\n   public void testDeleteWhenResponseIs2xx() throws Exception {\n      EmailAccountApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/email/delete/format/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"email\", \"test2@jclouds.org\").build(),\n            HttpResponse.builder().statusCode(200).build()).getEmailAccountApi();\n\n      api.delete(\"test2@jclouds.org\");\n   }\n\n   public void testDeleteWhenResponseIs4xxOk() throws Exception {\n      EmailAccountApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/email/delete/format/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"email\", \"test2@jclouds.org\").build(),\n            HttpResponse.builder().statusCode(404).build()).getEmailAccountApi();\n\n      api.delete(\"test2@jclouds.org\");\n   }\n}\n"
  },
  {
    "path": "providers/glesys/src/test/java/org/jclouds/glesys/features/EmailAccountApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.features;\n\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static org.jclouds.util.Predicates2.retry;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.glesys.domain.EmailAccount;\nimport org.jclouds.glesys.domain.EmailAlias;\nimport org.jclouds.glesys.domain.EmailOverview;\nimport org.jclouds.glesys.domain.EmailOverviewDomain;\nimport org.jclouds.glesys.internal.BaseGleSYSApiLiveTest;\nimport org.jclouds.glesys.options.CreateAccountOptions;\nimport org.jclouds.glesys.options.UpdateAccountOptions;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.Iterables;\n\n/**\n * Tests behavior of {@code EmailAccountApi}\n */\n@Test(groups = \"live\", testName = \"EmailAccountApiLiveTest\", singleThreaded = true)\npublic class EmailAccountApiLiveTest extends BaseGleSYSApiLiveTest {\n   public EmailAccountApiLiveTest() {\n      hostName = hostName + \"-email\";\n   }\n\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   @Override\n   public void setup() {\n      super.setup();\n      testDomain = hostName + \".test.jclouds.org\";\n      emailAccountApi = api.getEmailAccountApi();\n      deleteAll();\n\n      createDomain(testDomain);\n\n      emailAccountCounter = retry(new Predicate<Integer>() {\n         public boolean apply(Integer value) {\n            return emailAccountApi.listDomain(testDomain).size() == value.intValue();\n         }\n      }, 180, 5, SECONDS);\n\n      assertTrue(emailAccountCounter.apply(0));\n\n   }\n\n   @AfterClass(groups = { \"integration\", \"live\" })\n   @Override\n   public void tearDown() {\n      deleteAll();\n      super.tearDown();\n   }\n\n   private void deleteAll() {\n      emailAccountApi.delete(\"test@\" + testDomain);\n      emailAccountApi.delete(\"test1@\" + testDomain);\n   }\n\n   private EmailAccountApi emailAccountApi;\n   private String testDomain;\n   private Predicate<Integer> emailAccountCounter;\n\n   @Test\n   public void testCreateEmail() {\n      emailAccountApi.createWithPassword(\"test@\" + testDomain, \"password\", CreateAccountOptions.Builder.antiVirus(true)\n               .autorespond(true).autorespondMessage(\"out of office\"));\n\n      assertTrue(emailAccountCounter.apply(1));\n\n      emailAccountApi.createWithPassword(\"test1@\" + testDomain, \"password\");\n\n      assertTrue(emailAccountCounter.apply(2));\n   }\n\n   @Test(dependsOnMethods = \"testCreateEmail\")\n   public void testAliases() {\n      assertTrue(emailAccountApi.listAliasesInDomain(testDomain).isEmpty());\n\n      EmailAlias alias = emailAccountApi.createAlias(\"test2@\" + testDomain, \"test@\" + testDomain);\n      assertEquals(alias.getAlias(), \"test2@\" + testDomain);\n      assertEquals(alias.getForwardTo(), \"test@\" + testDomain);\n\n      EmailAlias aliasFromList = Iterables.getOnlyElement(emailAccountApi.listAliasesInDomain(testDomain));\n      assertEquals(aliasFromList, alias);\n\n      EmailOverview overview = emailAccountApi.getOverview();\n      assertEquals(1, overview.getSummary().getAliases());\n\n      alias = emailAccountApi.updateAlias(\"test2@\" + testDomain, \"test1@\" + testDomain);\n      overview = emailAccountApi.getOverview();\n      assertEquals(1, overview.getSummary().getAliases());\n\n      aliasFromList = Iterables.getOnlyElement(emailAccountApi.listAliasesInDomain(testDomain));\n      assertEquals(aliasFromList, alias);\n\n      emailAccountApi.delete(\"test2@\" + testDomain);\n      overview = emailAccountApi.getOverview();\n      assertEquals(0, overview.getSummary().getAliases());\n   }\n\n   @Test(dependsOnMethods = \"testCreateEmail\")\n   public void testOverview() throws Exception {\n      EmailOverview overview = emailAccountApi.getOverview();\n      assertNotNull(overview.getSummary());\n      assertTrue(overview.getSummary().getAccounts() > 0);\n      assertTrue(overview.getSummary().getAliases() > -1);\n      assertTrue(overview.getSummary().getMaxAccounts() > 0);\n      assertTrue(overview.getSummary().getMaxAliases() > 0);\n      assertNotNull(overview.gets());\n      assertFalse(overview.gets().isEmpty());\n\n      EmailOverviewDomain domain = EmailOverviewDomain.builder().domain(testDomain).accounts(1).build();\n      assertTrue(overview.gets().contains(domain));\n   }\n\n   @Test(dependsOnMethods = \"testCreateEmail\")\n   public void testListAccounts() throws Exception {\n      FluentIterable<EmailAccount> accounts = emailAccountApi.listDomain(testDomain);\n      assertTrue(accounts.size() >= 1);\n   }\n\n   @Test(dependsOnMethods = \"testCreateEmail\")\n   public void testUpdateAccount() throws Exception {\n      FluentIterable<EmailAccount> accounts = emailAccountApi.listDomain(testDomain);\n      for (EmailAccount account : accounts) {\n         if (account.getAccount().equals(\"test@\" + testDomain)) {\n            assertTrue(account.isAntiVirus());\n         }\n      }\n\n      emailAccountApi.update(\"test@\" + testDomain, UpdateAccountOptions.Builder.antiVirus(false));\n\n      accounts = emailAccountApi.listDomain(testDomain);\n      for (EmailAccount account : accounts) {\n         if (account.getAccount().equals(\"test@\" + testDomain)) {\n            assertFalse(account.isAntiVirus());\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "providers/glesys/src/test/java/org/jclouds/glesys/features/IpApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.glesys.domain.Cost;\nimport org.jclouds.glesys.domain.IpDetails;\nimport org.jclouds.glesys.internal.BaseGleSYSApiExpectTest;\nimport org.jclouds.glesys.parse.ParseIpAddressFromResponseTest;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Allows us to test a api via its side effects.\n */\n@Test(groups = \"unit\", testName = \"IpApiExpectTest\")\npublic class IpApiExpectTest extends BaseGleSYSApiExpectTest {\n\n   public void testListIpsWhenResponseIs2xx() {\n      IpApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"GET\").endpoint(\"https://api.glesys.com/ip/listown/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\").build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/ip_list_own.json\")).build())\n            .getIpApi();\n\n      IpDetails.Builder<?> builder = IpDetails.builder().datacenter(\"Falkenberg\").version4().reserved(true)\n            .platform(\"OpenVZ\")\n            .nameServers(\"79.99.4.100\", \"79.99.4.101\")\n            .cost(Cost.builder().amount(2.0).currency(\"EUR\").timePeriod(\"month\").build());\n\n      assertEquals(api.list().toString(), ImmutableSet.of(\n            builder.ptr(\"31-192-230-68-static.serverhotell.net.\").address(\"31.192.230.68\").serverId(null).build(),\n            builder.ptr(\"31-192-231-148-static.serverhotell.net.\").address(\"31.192.231.148\").serverId(\"vz1609110\").build()).toString());\n   }\n\n   public void testListIpsWhenResponseIs4xxReturnsEmpty() {\n      IpApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"GET\").endpoint(\"https://api.glesys.com/ip/listown/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\").build(),\n            HttpResponse.builder().statusCode(404).build()).getIpApi();\n\n      assertTrue(api.list().isEmpty());\n   }\n\n   public void testGetIpDetailsWhenResponseIs2xx() {\n      IpApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"GET\").endpoint(\"https://api.glesys.com/ip/details/ipaddress/31.192.227.113/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\").build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/ip_get_details.json\")).build())\n            .getIpApi();\n\n      assertEquals(api.get(\"31.192.227.113\"), getIpInIpDetails());\n   }\n\n   protected IpDetails getIpInIpDetails() {\n      return IpDetails.builder().datacenter(\"Falkenberg\").version4()\n            .platform(\"OpenVZ\").ptr(\"31-192-227-113-static.serverhotell.net.\")\n            .nameServers(\"79.99.4.100\", \"79.99.4.101\")\n            .address(\"31.192.227.113\")\n            .cost(Cost.builder().amount(2.0).currency(\"EUR\").timePeriod(\"month\").build()).build();\n   }\n\n   public void testGetIpDetailsWhenResponseIs4xxReturnsNull() {\n\n      IpApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"GET\").endpoint(\"https://api.glesys.com/ip/details/ipaddress/31.192.227.37/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\").build(),\n            HttpResponse.builder().statusCode(404).build()).getIpApi();\n\n      assertEquals(api.get(\"31.192.227.37\"), null);\n   }\n\n   public void testTakeWhenResponseIs2xx() {\n      IpApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/ip/take/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"ipaddress\", \"46.21.105.186\").build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/ip_take.json\")).build())\n            .getIpApi();\n\n      api.take(\"46.21.105.186\");\n   }\n\n   @Test(expectedExceptions = HttpResponseException.class)\n   public void testTakeWhenResponseIs4xxThrowsResponseException() {\n      IpApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/ip/take/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"ipaddress\", \"46.21.105.186\").build(),\n            HttpResponse.builder().statusCode(400).build()).getIpApi();\n      api.take(\"46.21.105.186\");\n   }\n\n   public void testReleaseWhenResponseIs2xx() {\n      IpApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/ip/release/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"ipaddress\", \"46.21.105.186\").build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/ip_release.json\")).build())\n            .getIpApi();\n\n      api.release(\"46.21.105.186\");\n   }\n\n   @Test(expectedExceptions = ResourceNotFoundException.class)\n   public void testReleaseWhenResponseIs4xxThrowsResponseException() {\n      IpApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/ip/release/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"ipaddress\", \"46.21.105.186\").build(),\n            HttpResponse.builder().statusCode(404).build())\n            .getIpApi();\n\n      api.release(\"46.21.105.186\");\n   }\n\n   public void testListFreeWhenResponseIs2xx() {\n      IpApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"GET\").endpoint(\"https://api.glesys.com/ip/listfree/ipversion/4/datacenter/Falkenberg/platform/OpenVZ/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\").build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/ip_list_free.json\")).build())\n            .getIpApi();\n\n      assertEquals(api.listFree(4, \"Falkenberg\", \"OpenVZ\").toSet(), ParseIpAddressFromResponseTest.EXPECTED_IPS);\n   }\n\n   public void testListFreeWhenResponseIs404ReturnsEmptySet() {\n      IpApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"GET\").endpoint(\"https://api.glesys.com/ip/listfree/ipversion/6/datacenter/Falkenberg/platform/OpenVZ/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\").build(),\n            HttpResponse.builder().statusCode(404).build())\n            .getIpApi();\n\n      assertEquals(api.listFree(6, \"Falkenberg\", \"OpenVZ\").toSet(), ImmutableSet.of());\n   }\n\n   public void testAddWhenResponseIs2xx() {\n      IpApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/ip/add/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"ipaddress\", \"31.192.227.37\")\n                       .addFormParam(\"serverid\", \"vz1946889\").build(),\n            HttpResponse.builder().statusCode(200).build())\n            .getIpApi();\n\n      api.addToServer(\"31.192.227.37\", \"vz1946889\");\n   }\n\n   @Test(expectedExceptions = AuthorizationException.class)\n   public void testAddWhenResponseIs4xxThrowsHttpException() {\n      IpApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/ip/add/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"ipaddress\", \"31.192.227.37\")\n                       .addFormParam(\"serverid\", \"vz1946889\").build(),\n            HttpResponse.builder().statusCode(401).build())\n            .getIpApi();\n      api.addToServer(\"31.192.227.37\", \"vz1946889\");\n   }\n\n   public void testRemoveWhenResponseIs2xx() {\n      IpApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/ip/remove/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"ipaddress\", \"31.192.227.37\")\n                       .addFormParam(\"serverid\", \"vz1946889\").build(),\n            HttpResponse.builder().statusCode(200).build())\n            .getIpApi();\n\n      api.removeFromServer(\"31.192.227.37\", \"vz1946889\");\n   }\n\n   @Test(expectedExceptions = HttpResponseException.class)\n   public void testRemoveWhenResponseIs4xxThrowsHttpException() {\n      IpApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/ip/remove/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"ipaddress\", \"31.192.227.37\")\n                       .addFormParam(\"serverid\", \"vz1946889\").build(),\n            HttpResponse.builder().statusCode(400).build())\n            .getIpApi();\n\n      api.removeFromServer(\"31.192.227.37\", \"vz1946889\");\n   }\n\n   public void testRemoveAndReleaseWhenResponseIs2xx() {\n      IpApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/ip/remove/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"release\", \"true\")\n                       .addFormParam(\"ipaddress\", \"31.192.227.37\")\n                       .addFormParam(\"serverid\", \"vz1946889\").build(),\n            HttpResponse.builder().statusCode(200).build())\n            .getIpApi();\n\n      api.removeFromServerAndRelease(\"31.192.227.37\", \"vz1946889\");\n   }\n\n   @Test(expectedExceptions = HttpResponseException.class)\n   public void testRemoveAndReleaseWhenResponseIs4xxThrowsHttpException() {\n      IpApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/ip/remove/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"release\", \"true\")\n                       .addFormParam(\"ipaddress\", \"31.192.227.37\")\n                       .addFormParam(\"serverid\", \"vz1946889\").build(),\n            HttpResponse.builder().statusCode(400).build())\n            .getIpApi();\n\n      api.removeFromServerAndRelease(\"31.192.227.37\", \"vz1946889\");\n   }\n\n   public void testSetPrtWhenResponseIs2xx() {\n      IpApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/ip/setptr/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"ipaddress\", \"31.192.227.37\")\n                       .addFormParam(\"data\", \"sommeptr.\").build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResourceWithContentType(\"/ip_get_details.json\", MediaType.APPLICATION_JSON)).build())\n            .getIpApi();\n\n      assertEquals(api.setPtr(\"31.192.227.37\", \"sommeptr.\"), getIpInIpDetails());\n   }\n\n   @Test(expectedExceptions = ResourceNotFoundException.class)\n   public void testSetPtrWhenResponseIs4xxThrowsHttpException() {\n      IpApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/ip/setptr/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"ipaddress\", \"31.192.227.37\")\n                       .addFormParam(\"data\", \"sommeptr.\").build(),\n            HttpResponse.builder().statusCode(404).build())\n            .getIpApi();\n\n      api.setPtr(\"31.192.227.37\", \"sommeptr.\");\n   }\n\n   public void testResetPrtWhenResponseIs2xx() {\n      IpApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/ip/resetptr/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"ipaddress\", \"31.192.227.37\").build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResourceWithContentType(\"/ip_get_details.json\", MediaType.APPLICATION_JSON)).build())\n            .getIpApi();\n\n      assertEquals(api.resetPtr(\"31.192.227.37\"), getIpInIpDetails());\n   }\n\n   @Test(expectedExceptions = AuthorizationException.class)\n   public void testResetPtrWhenResponseIs4xxThrowsHttpException() {\n      IpApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/ip/resetptr/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"ipaddress\", \"31.192.227.37\").build(),\n            HttpResponse.builder().statusCode(401).build())\n            .getIpApi();\n\n      api.resetPtr(\"31.192.227.37\");\n   }\n}\n"
  },
  {
    "path": "providers/glesys/src/test/java/org/jclouds/glesys/features/IpApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\n\nimport org.jclouds.glesys.domain.IpDetails;\nimport org.jclouds.glesys.internal.BaseGleSYSApiWithAServerLiveTest;\nimport org.jclouds.glesys.options.ListIpOptions;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Sets;\n\n/**\n * Tests behavior of {@code IpApi}\n */\n@Test(groups = \"live\", testName = \"IpApiLiveTest\", singleThreaded = true)\npublic class IpApiLiveTest extends BaseGleSYSApiWithAServerLiveTest {\n   public IpApiLiveTest() {\n      hostName = hostName + \"-ip\";\n   }\n\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   @Override\n   public void setup() {\n      super.setup();\n      ipApi = api.getIpApi();\n   }\n\n   @AfterClass(groups = { \"integration\", \"live\" })\n   @Override\n   public void tearDown() {\n      if (reservedIp != null) {\n         ipApi.release(reservedIp.getAddress());\n      }\n      super.tearDown();\n   }\n\n   private IpApi ipApi;\n   private IpDetails reservedIp;\n\n   @Test\n   public void testListFree() throws Exception {\n      FluentIterable<String> freeIps = ipApi.listFree(4, \"Falkenberg\", \"Xen\");\n      assertFalse(freeIps.isEmpty());\n   }\n\n   @Test\n   public void reserveIp() throws Exception {\n      FluentIterable<String> openVzIps = ipApi.listFree(4, \"Falkenberg\", \"OpenVZ\");\n      assertFalse(openVzIps.isEmpty());\n      reservedIp = ipApi.take(Iterables.get(openVzIps, 0));\n      assertTrue(reservedIp.isReserved());\n      checkOpenVZDefailsInFalkenberg(reservedIp);\n   }\n\n   @Test(dependsOnMethods = \"reserveIp\")\n   public void reserveAndReleaseIp() throws Exception {\n      IpDetails details = ipApi.release(reservedIp.getAddress());\n      assertEquals(details.getAddress(), reservedIp.getAddress());\n      assertFalse(details.isReserved());\n\n      // reserve an address again!\n      reserveIp();\n   }\n\n   @Test(dependsOnMethods = \"reserveIp\")\n   public void testList() throws Exception {\n      FluentIterable<IpDetails> ownIps = ipApi.list();\n      assertTrue(ownIps.contains(reservedIp));\n      ownIps = ipApi.list(ListIpOptions.Builder.datacenter(reservedIp.getDatacenter()));\n      assertTrue(ownIps.contains(reservedIp));\n      ownIps = ipApi.list(ListIpOptions.Builder.platform(reservedIp.getPlatform()));\n      assertTrue(ownIps.contains(reservedIp));\n      ownIps = ipApi.list(ListIpOptions.Builder.ipVersion(reservedIp.getVersion()));\n      assertTrue(ownIps.contains(reservedIp));\n\n      ownIps = ipApi.list(ListIpOptions.Builder.datacenter(reservedIp.getDatacenter()),\n               ListIpOptions.Builder.platform(reservedIp.getPlatform()),\n               ListIpOptions.Builder.ipVersion(reservedIp.getVersion()));\n      assertTrue(ownIps.contains(reservedIp));\n\n      ownIps = ipApi.list(ListIpOptions.Builder.serverId(\"xmthisisnotaserverid\"));\n      assertTrue(ownIps.isEmpty());\n   }\n\n   private void checkOpenVZDefailsInFalkenberg(IpDetails ipDetails) {\n      assertEquals(ipDetails.getDatacenter(), \"Falkenberg\");\n      assertEquals(ipDetails.getPlatform(), \"OpenVZ\");\n      assertEquals(ipDetails.getVersion(), 4);\n      assertFalse(ipDetails.getPtr().isEmpty());\n      // broadcast, gateway and netmask are null for OpenVZ\n      assertFalse(ipDetails.getNameServers().isEmpty());\n   }\n\n   @Test\n   public void testGetOpenVZDetails() throws Exception {\n      FluentIterable<String> openVzIps = ipApi.listFree(4, \"Falkenberg\", \"OpenVZ\");\n      assertFalse(openVzIps.isEmpty());\n      String openVzIp = openVzIps.iterator().next();\n      IpDetails ipDetails = ipApi.get(openVzIp);\n      checkOpenVZDefailsInFalkenberg(ipDetails);\n      assertEquals(ipDetails.getAddress(), openVzIp);\n   }\n\n   @Test\n   public void testGetXenDetails() throws Exception {\n      FluentIterable<String> xenVzIps = ipApi.listFree(4, \"Falkenberg\", \"Xen\");\n      assertFalse(xenVzIps.isEmpty());\n      String xenIp = xenVzIps.iterator().next();\n      IpDetails ipDetails = ipApi.get(xenIp);\n      assertEquals(ipDetails.getDatacenter(), \"Falkenberg\");\n      assertEquals(ipDetails.getPlatform(), \"Xen\");\n      assertEquals(ipDetails.getVersion(), 4);\n      assertEquals(ipDetails.getAddress(), xenIp);\n      assertFalse(ipDetails.getPtr().isEmpty());\n      assertNotNull(ipDetails.getBroadcast());\n      assertNotNull(ipDetails.getGateway());\n      assertNotNull(ipDetails.getNetmask());\n      assertFalse(ipDetails.getNameServers().isEmpty());\n   }\n\n   @Test(dependsOnMethods = \"reserveIp\")\n   public void testPtrSetReset() throws Exception {\n      IpDetails original = reservedIp;\n\n      IpDetails modified = ipApi.setPtr(reservedIp.getAddress(), \"wibble.\");\n      IpDetails modified2 = ipApi.get(reservedIp.getAddress());\n\n      assertEquals(modified.getPtr(), \"wibble.\");\n      assertEquals(modified2, modified);\n\n      reservedIp = ipApi.resetPtr(reservedIp.getAddress());\n\n      assertEquals(reservedIp, original);\n   }\n\n   @Test(dependsOnMethods = \"reserveIp\")\n   public void testAddRemove() throws Exception {\n      IpDetails added = ipApi.addToServer(reservedIp.getAddress(), serverId);\n\n      assertEquals(added.getAddress(), reservedIp.getAddress());\n      assertEquals(added.getPtr(), reservedIp.getPtr());\n      assertEquals(added.getServerId(), serverId);\n\n      IpDetails again = ipApi.get(reservedIp.getAddress());\n      assertEquals(again, added);\n\n      IpDetails removed = ipApi.removeFromServer(reservedIp.getAddress(), serverId);\n      assertEquals(removed, added.toBuilder().serverId(null).build());\n\n      assertEquals(removed, reservedIp);\n\n      Set<String> openVzIps = Sets.newHashSet(ipApi.listFree(4, \"Falkenberg\", \"OpenVZ\"));\n      openVzIps.remove(reservedIp.getAddress());\n      assertFalse(openVzIps.isEmpty());\n\n      added = ipApi.addToServer(reservedIp.getAddress(), serverId);\n\n      assertEquals(added.getServerId(), serverId);\n\n      removed = ipApi.removeFromServerAndRelease(reservedIp.getAddress(), serverId);\n\n      assertNull(removed.getServerId());\n      assertFalse(removed.isReserved());\n\n      // reserve an address again!\n      reserveIp();\n   }\n}\n"
  },
  {
    "path": "providers/glesys/src/test/java/org/jclouds/glesys/features/ServerApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Map;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.glesys.domain.AllowedArguments;\nimport org.jclouds.glesys.domain.AllowedArgumentsForCreateServer;\nimport org.jclouds.glesys.domain.Console;\nimport org.jclouds.glesys.domain.Cost;\nimport org.jclouds.glesys.domain.Ip;\nimport org.jclouds.glesys.domain.OSTemplate;\nimport org.jclouds.glesys.domain.ResourceStatus;\nimport org.jclouds.glesys.domain.ResourceUsage;\nimport org.jclouds.glesys.domain.ResourceUsageInfo;\nimport org.jclouds.glesys.domain.ResourceUsageValue;\nimport org.jclouds.glesys.domain.Server;\nimport org.jclouds.glesys.domain.ServerDetails;\nimport org.jclouds.glesys.domain.ServerSpec;\nimport org.jclouds.glesys.domain.ServerStatus;\nimport org.jclouds.glesys.domain.ServerUptime;\nimport org.jclouds.glesys.internal.BaseGleSYSApiExpectTest;\nimport org.jclouds.glesys.options.CloneServerOptions;\nimport org.jclouds.glesys.options.CreateServerOptions;\nimport org.jclouds.glesys.options.DestroyServerOptions;\nimport org.jclouds.glesys.options.UpdateServerOptions;\nimport org.jclouds.glesys.options.ServerStatusOptions;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Maps;\n\n/**\n * Tests annotation parsing of {@code ServerApi}\n */\n@Test(groups = \"unit\", testName = \"ServerApiTest\")\npublic class ServerApiExpectTest extends BaseGleSYSApiExpectTest {\n\n   public void testListServersWhenResponseIs2xx() throws Exception {\n      ServerApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/server/list/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\").build(),\n            HttpResponse.builder().statusCode(204).payload(payloadFromResource(\"/server_list.json\")).build()).getServerApi();\n      Server expected = Server.builder().id(\"vz1541880\").hostname(\"mammamia\").datacenter(\"Falkenberg\").platform(\"OpenVZ\").build();\n\n      assertEquals(api.list().toSet(), ImmutableSet.<Server>of(expected));\n   }\n\n   public void testListServersWhenReponseIs404IsEmpty() {\n      ServerApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/server/list/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\").build(),\n            HttpResponse.builder().statusCode(404).build()).getServerApi();\n\n      assertTrue(api.list().isEmpty());\n   }\n\n   public void testGetAllowedArgumentsWhenResponseIs2xx() throws Exception {\n      ServerApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"GET\").endpoint(\"https://api.glesys.com/server/allowedarguments/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\").build(),\n            HttpResponse.builder().statusCode(204).payload(payloadFromResource(\"/server_allowed_arguments.json\")).build()).getServerApi();\n\n      Map<String, AllowedArgumentsForCreateServer> expected = Maps.newLinkedHashMap();\n      AllowedArguments openvzAllowedMemorySizes = AllowedArguments.builder().allowedUnits(128, 256, 512, 768, 1024, 1536, 2048, 2560, 3072, 3584, 4096, 5120, 6144, 7168, 8192, 9216, 10240, 11264, 12288, 14336, 16384).costPerUnit(Cost.builder().amount(0.09).currency(\"SEK\").timePeriod(\"month\").build()).build();\n      AllowedArguments openvzAllowedDiskSizes = AllowedArguments.builder().allowedUnits(5, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 120, 140, 150).costPerUnit(Cost.builder().amount(2.2).currency(\"SEK\").timePeriod(\"month\").build()).build();\n      AllowedArguments openvzAllowedCpuCores = AllowedArguments.builder().allowedUnits(1, 2, 3, 4, 5, 6, 7, 8).costPerUnit(Cost.builder().amount(30).currency(\"SEK\").timePeriod(\"month\").build()).build();\n      AllowedArguments openvzAllowedTransfers = AllowedArguments.builder().allowedUnits(50, 100, 250, 500, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000).costPerUnit(Cost.builder().amount(0.2).currency(\"SEK\").timePeriod(\"month\").build()).build();\n      AllowedArgumentsForCreateServer openvz = AllowedArgumentsForCreateServer.builder()\n            .dataCenters(\"Amsterdam\", \"Falkenberg\", \"New York City\", \"Stockholm\")\n            .memorySizes(openvzAllowedMemorySizes)\n            .diskSizes(openvzAllowedDiskSizes)\n            .cpuCores(openvzAllowedCpuCores)\n            .templates(\"Centos 5\", \"Centos 5 64-bit\", \"Centos 6 32-bit\", \"Centos 6 64-bit\", \"Debian 5.0 32-bit\",\n                    \"Debian 5.0 64-bit\", \"Debian 6.0 32-bit\", \"Debian 6.0 64-bit\", \"Fedora Core 11\", \"Fedora Core 11 64-bit\",\n                    \"Gentoo\", \"Gentoo 64-bit\", \"Scientific Linux 6\", \"Scientific Linux 6 64-bit\", \"Slackware 12\",\n                    \"Ubuntu 10.04 LTS 32-bit\", \"Ubuntu 10.04 LTS 64-bit\", \"Ubuntu 11.04 64-bit\", \"Ubuntu 12.04 LTS 32-bit\",\n                    \"Ubuntu 12.04 LTS 64-bit\")\n            .transfers(openvzAllowedTransfers)\n            .build();\n      \n      AllowedArguments xenAllowedMemorySizes = AllowedArguments.builder().allowedUnits(512, 768, 1024, 1536, 2048, 2560, 3072, 3584, 4096, 5120, 6144, 7168, 8192, 9216, 10240, 11264, 12288, 14336, 16384).costPerUnit(Cost.builder().amount(0.09).currency(\"SEK\").timePeriod(\"month\").build()).build();\n      AllowedArguments xenAllowedDiskSizes = AllowedArguments.builder().allowedUnits(5, 10, 20, 30, 40, 50, 80, 100, 120, 140, 150, 160, 160, 200, 250, 300).costPerUnit(Cost.builder().amount(2.2).currency(\"SEK\").timePeriod(\"month\").build()).build();\n      AllowedArguments xenAllowedCpuCores = AllowedArguments.builder().allowedUnits(1, 2, 3, 4, 5, 6, 7, 8).costPerUnit(Cost.builder().amount(30).currency(\"SEK\").timePeriod(\"month\").build()).build();\n      AllowedArguments xenAllowedTransfers = AllowedArguments.builder().allowedUnits(50, 100, 250, 500, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000).costPerUnit(Cost.builder().amount(0.2).currency(\"SEK\").timePeriod(\"month\").build()).build();      \n      AllowedArgumentsForCreateServer xen = AllowedArgumentsForCreateServer.builder()\n            .memorySizes(xenAllowedMemorySizes)\n            .diskSizes(xenAllowedDiskSizes)\n            .cpuCores(xenAllowedCpuCores)\n            \n            \n            .templates(\"CentOS 5.5 x64\", \"CentOS 5.5 x86\", \"Centos 6 x64\", \"Centos 6 x86\", \n            \t\t\"Debian-6 x64\", \"Debian 5.0.1 x64\", \"FreeBSD 8.2\", \"FreeBSD 9.0\", \n            \t\t\"Gentoo 10.1 x64\", \"OpenSUSE 11.4 64-bit\", \"Ubuntu 8.04 x64\", \n            \t\t\"Ubuntu 10.04 LTS 64-bit\", \"Ubuntu 10.10 x64\", \"Ubuntu 11.04 x64\", \n            \t\t\"Ubuntu 12.04 x64\", \"Ubuntu 12.04 x86\", \"Windows Server 2008 R2 x64 std\", \n            \t\t\"Windows Server 2008 R2 x64 web\", \"Windows Server 2008 x64 web\")\n            .transfers(xenAllowedTransfers)\n            .dataCenters(\"Falkenberg\")\n            .build();\n      expected.put(\"Xen\", xen);\n      expected.put(\"OpenVZ\", openvz);\n      assertEquals(api.getAllowedArgumentsForCreateByPlatform(), expected);\n   }\n\n   public void testGetTemplatesWhenResponseIs2xx() throws Exception {\n      ServerApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"GET\").endpoint(\"https://api.glesys.com/server/templates/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\").build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/server_templates.json\")).build()).getServerApi();\n\n      ImmutableSet.Builder<OSTemplate> expectedBuilder = ImmutableSet.builder();\n\n      for (String name : new String[]{\"Centos 5\", \"Centos 5 64-bit\", \"Centos 6 32-bit\", \"Centos 6 64-bit\",\n            \"Debian 5.0 32-bit\", \"Debian 5.0 64-bit\", \"Debian 6.0 32-bit\", \"Debian 6.0 64-bit\", \"Fedora Core 11\",\n            \"Fedora Core 11 64-bit\", \"Gentoo\", \"Gentoo 64-bit\", \"Scientific Linux 6\", \"Scientific Linux 6 64-bit\",\n            \"Slackware 12\", \"Ubuntu 10.04 LTS 32-bit\", \"Ubuntu 10.04 LTS 64-bit\", \"Ubuntu 11.04 64-bit\"}) {\n         expectedBuilder.add(OSTemplate.builder().name(name).minDiskSize(5).minMemSize(128).os(\"linux\").platform(\"OpenVZ\").build());\n      }\n\n      for (String name : new String[]{\"CentOS 5.5 x64\", \"CentOS 5.5 x86\", \"Centos 6 x64\", \"Centos 6 x86\",\n            \"Debian-6 x64\", \"Debian 5.0.1 x64\", \"FreeBSD 8.2\", \"Gentoo 10.1 x64\", \"Ubuntu 8.04 x64\",\n            \"Ubuntu 10.04 LTS 64-bit\", \"Ubuntu 10.10 x64\", \"Ubuntu 11.04 x64\"}) {\n         expectedBuilder.add(OSTemplate.builder().name(name).minDiskSize(5).minMemSize(512)\n               .os(name.startsWith(\"FreeBSD\") ? \"freebsd\" : \"linux\").platform(\"Xen\").build());\n      }\n      for (String name : new String[]{\"Windows Server 2008 R2 x64 std\", \"Windows Server 2008 R2 x64 web\",\n            \"Windows Server 2008 x64 web\", \"Windows Server 2008 x86 web\"}) {\n         expectedBuilder.add(OSTemplate.builder().name(name).minDiskSize(20).minMemSize(1024).os(\"windows\").platform(\"Xen\").build());\n      }\n\n      assertEquals(api.listTemplates().toSet(), expectedBuilder.build());\n   }\n\n   public void testGetServerDetailsWhenResponseIs2xx() throws Exception {\n      ServerApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/server/details/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"includestate\", \"true\")\n                       .addFormParam(\"serverid\", \"xm3276891\").build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/server_details.json\")).build()).getServerApi();\n\n      ServerDetails actual = api.get(\"xm3276891\");\n      assertEquals(actual.toString(), expectedServerDetails().toString());\n   }\n\n   public static ServerDetails expectedServerDetails() {\n      Ip ip = Ip.builder().version4().ip(\"31.192.231.254\").version4().cost(2.0).currency(\"EUR\").build();\n      Cost cost = Cost.builder().amount(10.22).currency(\"EUR\").timePeriod(\"month\").build();\n      return ServerDetails.builder().id(\"vz1840356\").transferGB(50).hostname(\"glesys-s\").cpuCores(1).memorySizeMB(512)\n            .diskSizeGB(5).datacenter(\"Falkenberg\").description(\"glesys-s-6dd\").platform(\"OpenVZ\")\n            .templateName(\"Ubuntu 10.04 LTS 32-bit\").state(Server.State.RUNNING).cost(cost).ips(ip).build();\n   }\n\n   @Test\n   public void testServerDetailsWhenResponseIs4xxReturnsNull() throws Exception {\n      ServerApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/server/details/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"includestate\", \"true\")\n                       .addFormParam(\"serverid\", \"xm3276891\").build(),\n            HttpResponse.builder().statusCode(404).build()).getServerApi();\n\n      assertNull(api.get(\"xm3276891\"));\n   }\n\n   @Test\n   public void testCreateServerWhenResponseIs2xx() throws Exception {\n      ServerApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/server/create/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"hostname\", \"jclouds-test\")\n                       .addFormParam(\"rootpassword\", \"password\")\n                       .addFormParam(\"datacenter\", \"Falkenberg\")\n                       .addFormParam(\"platform\", \"OpenVZ\")\n                       .addFormParam(\"templatename\", \"Ubuntu 32-bit\")\n                       .addFormParam(\"disksize\", \"5\")\n                       .addFormParam(\"memorysize\", \"512\")\n                       .addFormParam(\"cpucores\", \"1\")\n                       .addFormParam(\"transfer\", \"50\").build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/server_noip.json\")).build()).getServerApi();\n\n      Cost cost = Cost.builder().amount(6.38).currency(\"EUR\").timePeriod(\"month\").build();\n      ServerDetails expected = ServerDetails.builder().id(\"vz1541880\").hostname(\"mammamia\").datacenter(\"Falkenberg\").platform(\"OpenVZ\")\n            .templateName(\"Ubuntu 11.04 64-bit\").description(\"description\").cpuCores(1).memorySizeMB(128).diskSizeGB(5).transferGB(50).cost(cost).build();\n\n      assertEquals(\n            api.createWithHostnameAndRootPassword(\n                  ServerSpec.builder().datacenter(\"Falkenberg\").platform(\"OpenVZ\").templateName(\"Ubuntu 32-bit\")\n                        .diskSizeGB(5).memorySizeMB(512).cpuCores(1).transferGB(50).build(), \"jclouds-test\", \"password\").toString(),\n            expected.toString());\n   }\n\n   public void testCreateServerWithOptsWhenResponseIs2xx() throws Exception {\n      ServerApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/server/create/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"hostname\", \"jclouds-test\")\n                       .addFormParam(\"rootpassword\", \"password\")\n                       .addFormParam(\"datacenter\", \"Falkenberg\")\n                       .addFormParam(\"platform\", \"OpenVZ\")\n                       .addFormParam(\"templatename\", \"Ubuntu 32-bit\")\n                       .addFormParam(\"disksize\", \"5\")\n                       .addFormParam(\"memorysize\", \"512\")\n                       .addFormParam(\"cpucores\", \"1\")\n                       .addFormParam(\"transfer\", \"50\")\n                       .addFormParam(\"ip\", \"10.0.0.1\")\n                       .addFormParam(\"description\", \"Description-of-server\").build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/server_details.json\")).build()).getServerApi();\n\n      CreateServerOptions options = CreateServerOptions.Builder.description(\"Description-of-server\").ip(\"10.0.0.1\");\n\n\n      assertEquals(api.createWithHostnameAndRootPassword(ServerSpec.builder().datacenter(\"Falkenberg\")\n            .platform(\"OpenVZ\").templateName(\"Ubuntu 32-bit\").diskSizeGB(5).memorySizeMB(512).cpuCores(1).transferGB(50)\n            .build(), \"jclouds-test\", \"password\", options), expectedServerDetails());\n   }\n\n   @Test\n   public void testUpdateServerWhenResponseIs2xx() throws Exception {\n      ServerApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/server/edit/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"serverid\", \"xm3276891\")\n                       .addFormParam(\"description\", \"this is a different description!\")\n                       .addFormParam(\"hostname\", \"new-hostname\").build(),\n            HttpResponse.builder().statusCode(206).build()).getServerApi();\n\n      api.update(\"xm3276891\", UpdateServerOptions.Builder.description(\"this is a different description!\").hostname(\"new-hostname\"));\n   }\n\n   @Test\n   public void testUpdateServerWithOptsWhenResponseIs2xx() throws Exception {\n      ServerApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/server/edit/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"serverid\", \"xm3276891\")\n                       .addFormParam(\"description\", \"Description-of-server\")\n                       .addFormParam(\"disksize\", \"1\")\n                       .addFormParam(\"memorysize\", \"512\")\n                       .addFormParam(\"cpucores\", \"1\")\n                       .addFormParam(\"hostname\", \"jclouds-test\").build(),\n            HttpResponse.builder().statusCode(200).build()).getServerApi();\n\n      UpdateServerOptions options =\n            UpdateServerOptions.Builder.description(\"Description-of-server\").diskSizeGB(1).memorySizeMB(512).cpuCores(1).hostname(\"jclouds-test\");\n\n      api.update(\"xm3276891\", options);\n   }\n\n   @Test\n   public void testCloneServerWhenResponseIs2xx() throws Exception {\n      ServerApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/server/clone/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"serverid\", \"xm3276891\")\n                       .addFormParam(\"hostname\", \"hostname1\").build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/server_details.json\")).build()).getServerApi();\n\n      assertEquals(api.clone(\"xm3276891\", \"hostname1\"), expectedServerDetails());\n   }\n\n   @Test\n   public void testCloneServerWithOptsWhenResponseIs2xx() throws Exception {\n      ServerApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/server/clone/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"serverid\", \"xm3276891\")\n                       .addFormParam(\"hostname\", \"hostname1\")\n                       .addFormParam(\"description\", \"Description-of-server\")\n                       .addFormParam(\"disksize\", \"1\")\n                       .addFormParam(\"memorysize\", \"512\")\n                       .addFormParam(\"cpucores\", \"1\").build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/server_details.json\")).build()).getServerApi();\n      CloneServerOptions options = (CloneServerOptions) CloneServerOptions.Builder.description(\"Description-of-server\").diskSizeGB(1).memorySizeMB(512).cpuCores(1);\n\n      assertEquals(api.clone(\"xm3276891\", \"hostname1\", options), expectedServerDetails());\n   }\n\n   @Test(expectedExceptions = {ResourceNotFoundException.class})\n   public void testCloneServerWhenResponseIs4xx() throws Exception {\n      ServerApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/server/clone/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"serverid\", \"xm3276891\")\n                       .addFormParam(\"hostname\", \"hostname1\").build(),\n            HttpResponse.builder().statusCode(404).build()).getServerApi();\n\n      api.clone(\"xm3276891\", \"hostname1\");\n   }\n\n   public void testGetServerStatusWhenResponseIs2xx() throws Exception {\n      ServerApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/server/status/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"serverid\", \"xm3276891\").build(),\n            HttpResponse.builder().statusCode(206).payload(payloadFromResource(\"/server_status.json\")).build())\n            .getServerApi();\n\n      assertEquals(api.getStatus(\"xm3276891\"), expectedServerStatus());\n   }\n\n   public void testGetServerStatusWithOptsWhenResponseIs2xx() throws Exception {\n      ServerApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/server/status/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"serverid\", \"server321\")\n                       .addFormParam(\"statustype\", \"state\").build(),\n            HttpResponse.builder().statusCode(206).payload(payloadFromResource(\"/server_status.json\")).build())\n            .getServerApi();\n\n      assertEquals(api.getStatus(\"server321\", ServerStatusOptions.Builder.state()), expectedServerStatus());\n   }\n\n   public void testGetServerStatusWhenResponseIs4xx() throws Exception {\n      ServerApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/server/status/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"serverid\", \"server321\")\n                       .addFormParam(\"statustype\", \"state\").build(),\n            HttpResponse.builder().statusCode(404).build())\n            .getServerApi();\n\n      assertNull(api.getStatus(\"server321\", ServerStatusOptions.Builder.state()));\n   }\n\n   public void testGetServerLimitsWhenResponseIs2xx() throws Exception {\n      ServerApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/server/limits/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"serverid\", \"server321\").build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/server_limits.json\")).build())\n            .getServerApi();\n\n      api.getLimits(\"server321\");\n   }\n\n   public void testGetConsoleWhenResponseIs2xx() throws Exception {\n      ServerApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/server/console/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"serverid\", \"server322\").build(),\n            HttpResponse.builder().statusCode(200).payload(payloadFromResource(\"/server_console.json\")).build())\n            .getServerApi();\n\n      Console expected = Console.builder().host(\"79.99.2.147\").port(59478).password(\"1476897311\").protocol(\"vnc\").build();\n\n      assertEquals(api.getConsole(\"server322\"), expected);\n   }\n\n   public void testGetConsoleWhenResponseIs4xx() throws Exception {\n      ServerApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/server/console/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"serverid\", \"server322\").build(),\n            HttpResponse.builder().statusCode(404).build())\n            .getServerApi();\n\n      assertNull(api.getConsole(\"server322\"));\n   }\n\n   public void testStartServerWhenResponseIs2xx() throws Exception {\n      ServerApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/server/start/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"serverid\", \"server777\").build(),\n            HttpResponse.builder().statusCode(200).build())\n            .getServerApi();\n\n      api.start(\"server777\");\n   }\n\n   @Test(expectedExceptions = {AuthorizationException.class})\n   public void testStartServerWhenResponseIs4xx() throws Exception {\n      ServerApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/server/start/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"serverid\", \"server777\").build(),\n            HttpResponse.builder().statusCode(401).build())\n            .getServerApi();\n\n      api.start(\"server777\");\n   }\n\n   public void testStopServerWhenResponseIs2xx() throws Exception {\n      ServerApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/server/stop/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"serverid\", \"server777\").build(),\n            HttpResponse.builder().statusCode(200).build())\n            .getServerApi();\n\n      api.stop(\"server777\");\n   }\n\n   public void testHardStopServerWhenResponseIs2xx() throws Exception {\n      ServerApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/server/stop/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"type\", \"hard\")\n                       .addFormParam(\"serverid\", \"server777\").build(),\n            HttpResponse.builder().statusCode(200).build())\n            .getServerApi();\n\n      api.hardStop(\"server777\");\n   }\n\n   @Test(expectedExceptions = {AuthorizationException.class})\n   public void testStopServerWhenResponseIs4xx() throws Exception {\n      ServerApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/server/stop/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"serverid\", \"server777\").build(),\n            HttpResponse.builder().statusCode(401).build())\n            .getServerApi();\n\n      api.stop(\"server777\");\n   }\n\n   public void testRebootServerWhenResponseIs2xx() throws Exception {\n      ServerApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/server/reboot/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"serverid\", \"server777\").build(),\n            HttpResponse.builder().statusCode(200).build())\n            .getServerApi();\n\n      api.reboot(\"server777\");\n   }\n\n   @Test(expectedExceptions = {AuthorizationException.class})\n   public void testRebootServerWhenResponseIs4xx() throws Exception {\n      ServerApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/server/reboot/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"serverid\", \"server777\").build(),\n            HttpResponse.builder().statusCode(401).build())\n            .getServerApi();\n\n      api.reboot(\"server777\");\n   }\n\n   public void testDestroyServerWhenResponseIs2xx() throws Exception {\n      ServerApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/server/destroy/format/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"serverid\", \"server777\")\n                       .addFormParam(\"keepip\", \"true\").build(),\n            HttpResponse.builder().statusCode(200).build())\n            .getServerApi();\n\n      api.destroy(\"server777\", DestroyServerOptions.Builder.keepIp());\n   }\n\n   @Test(expectedExceptions = {AuthorizationException.class})\n   public void testDestroyServerWhenResponseIs4xx() throws Exception {\n      ServerApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/server/destroy/format/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"serverid\", \"server777\")\n                       .addFormParam(\"keepip\", \"false\").build(),\n            HttpResponse.builder().statusCode(401).build())\n            .getServerApi();\n\n      api.destroy(\"server777\", DestroyServerOptions.Builder.discardIp());\n   }\n\n   public void testResourceUsageWhenResponseIs2xx() throws Exception {\n      ServerApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/server/resourceusage/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"serverid\", \"server777\")\n                       .addFormParam(\"resource\", \"diskioread\")\n                       .addFormParam(\"resolution\", \"minute\").build(),\n            HttpResponse.builder().statusCode(200)\n                  .payload(payloadFromResourceWithContentType(\"/server_resource_usage.json\", MediaType.APPLICATION_JSON))\n                  .build())\n            .getServerApi();\n\n      ResourceUsage expected = ResourceUsage.builder().info(\n            ResourceUsageInfo.builder().resolution(\"minute\").resource(\"diskioread\").unit(\"KB\").build())\n            .values(\n                  ResourceUsageValue.builder().value(0.0).timestamp(dateService.iso8601SecondsDateParse(\"2012-06-24T14:21:07+02:00\")).build(),\n                  ResourceUsageValue.builder().value(5.1).timestamp(dateService.iso8601SecondsDateParse(\"2012-06-24T14:22:05+02:00\")).build(),\n                  ResourceUsageValue.builder().value(0.0).timestamp(dateService.iso8601SecondsDateParse(\"2012-06-24T14:23:05+02:00\")).build(),\n                  ResourceUsageValue.builder().value(10.0).timestamp(dateService.iso8601SecondsDateParse(\"2012-06-24T14:24:08+02:00\")).build(),\n                  ResourceUsageValue.builder().value(0.0).timestamp(dateService.iso8601SecondsDateParse(\"2012-06-24T14:25:12+02:00\")).build(),\n                  ResourceUsageValue.builder().value(0.0).timestamp(dateService.iso8601SecondsDateParse(\"2012-06-24T14:26:07+02:00\")).build(),\n                  ResourceUsageValue.builder().value(0.0).timestamp(dateService.iso8601SecondsDateParse(\"2012-06-24T14:27:12+02:00\")).build(),\n                  ResourceUsageValue.builder().value(0.0).timestamp(dateService.iso8601SecondsDateParse(\"2012-06-24T14:28:05+02:00\")).build()\n            ).build();\n      assertEquals(api.getResourceUsage(\"server777\", \"diskioread\", \"minute\").toString(), expected.toString());\n   }\n\n   @Test(expectedExceptions = {AuthorizationException.class})\n   public void testResouceUsageWhenResponseIs4xx() throws Exception {\n      ServerApi api = requestSendsResponse(\n            HttpRequest.builder().method(\"POST\").endpoint(\"https://api.glesys.com/server/resourceusage/format/json\")\n                       .addHeader(\"Accept\", \"application/json\")\n                       .addHeader(\"Authorization\", \"Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\")\n                       .addFormParam(\"serverid\", \"server777\")\n                       .addFormParam(\"resource\", \"diskioread\")\n                       .addFormParam(\"resolution\", \"minute\").build(),\n            HttpResponse.builder().statusCode(401).build())\n            .getServerApi();\n\n      api.getResourceUsage(\"server777\", \"diskioread\", \"minute\");\n   }\n\n   private ServerStatus expectedServerStatus() {\n      ResourceStatus cpu = ResourceStatus.builder().unit(\"cores\").max(1.0).usage(0.0).build();\n      ResourceStatus disk = ResourceStatus.builder().unit(\"MB\").usage(0.0).max(5120).build();\n      ResourceStatus memory = ResourceStatus.builder().unit(\"MB\").usage(2.0).max(512).build();\n      ServerUptime uptime = ServerUptime.builder().current(21).unit(\"seconds\").build();\n      return ServerStatus.builder().state(Server.State.RUNNING).uptime(uptime).\n            cpu(cpu).disk(disk).memory(memory).build();\n   }\n\n}\n"
  },
  {
    "path": "providers/glesys/src/test/java/org/jclouds/glesys/features/ServerApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.features;\n\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static org.jclouds.util.Predicates2.retry;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Map;\n\nimport org.jclouds.glesys.domain.AllowedArgumentsForCreateServer;\nimport org.jclouds.glesys.domain.Console;\nimport org.jclouds.glesys.domain.OSTemplate;\nimport org.jclouds.glesys.domain.ResourceStatus;\nimport org.jclouds.glesys.domain.ResourceUsage;\nimport org.jclouds.glesys.domain.Server;\nimport org.jclouds.glesys.domain.Server.State;\nimport org.jclouds.glesys.domain.ServerDetails;\nimport org.jclouds.glesys.domain.ServerLimit;\nimport org.jclouds.glesys.domain.ServerStatus;\nimport org.jclouds.glesys.internal.BaseGleSYSApiWithAServerLiveTest;\nimport org.jclouds.glesys.options.CloneServerOptions;\nimport org.jclouds.glesys.options.DestroyServerOptions;\nimport org.jclouds.glesys.options.ServerStatusOptions;\nimport org.jclouds.glesys.options.UpdateServerOptions;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.BeforeMethod;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.FluentIterable;\n\n/**\n * Tests behavior of {@code ServerApi}\n */\n@Test(groups = \"live\", testName = \"ServerApiLiveTest\", singleThreaded = true)\npublic class ServerApiLiveTest extends BaseGleSYSApiWithAServerLiveTest {\n   public static final String testHostName2 = \"jclouds-test2\";\n\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   @Override\n   public void setup() {\n      hostName = hostName + \"-server\";\n      super.setup();\n      serverApi = api.getServerApi();\n   }\n\n   @AfterClass(groups = { \"integration\", \"live\" })\n   @Override\n   public void tearDown() {\n      if (testServerId2 != null) {\n         serverApi.destroy(testServerId2, DestroyServerOptions.Builder.discardIp());\n      }\n      super.tearDown();\n   }\n\n   private ServerApi serverApi;\n   private String testServerId2;\n\n   @BeforeMethod\n   public void makeSureServerIsRunning() throws Exception {\n      serverStatusChecker.apply(Server.State.RUNNING);\n   }\n\n   @Test\n   public void testAllowedArguments() throws Exception {\n      Map<String, AllowedArgumentsForCreateServer> templates = serverApi.getAllowedArgumentsForCreateByPlatform();\n\n      assertTrue(templates.containsKey(\"OpenVZ\"));\n      assertTrue(templates.containsKey(\"Xen\"));\n\n      checkAllowedArguments(templates.get(\"OpenVZ\"));\n      checkAllowedArguments(templates.get(\"Xen\"));\n   }\n\n   private void checkAllowedArguments(AllowedArgumentsForCreateServer t) {\n      assertNotNull(t);\n\n      assert !t.getDataCenters().isEmpty() : t;\n      assert !t.getCpuCoreOptions().getAllowedUnits().isEmpty() : t;\n      assert !t.getDiskSizesInGB().getAllowedUnits().isEmpty() : t;\n      assert !t.getMemorySizesInMB().getAllowedUnits().isEmpty() : t;\n      assert !t.getTemplateNames().isEmpty() : t;\n      assert !t.getTransfersInGB().getAllowedUnits().isEmpty() : t;\n      assert !t.getTransfersInGB().getAllowedUnits().isEmpty() : t;\n   }\n\n   public void testListTemplates() throws Exception {\n      FluentIterable<OSTemplate> oSTemplates = serverApi.listTemplates();\n\n      for (OSTemplate oSTemplate : oSTemplates) {\n         checkTemplate(oSTemplate);\n      }\n   }\n\n   private void checkTemplate(OSTemplate t) {\n      assertNotNull(t);\n      assertNotNull(t.getName());\n      assertNotNull(t.getOs());\n\n      assertNotNull(t.getPlatform());\n      assert t.getMinDiskSize() > 0 : t;\n      assert t.getMinMemSize() > 0 : t;\n    }\n\n   public void testListServers() throws Exception {\n      FluentIterable<Server> response = serverApi.list();\n      assertNotNull(response);\n      assertTrue(!response.isEmpty());\n\n      for (Server server : response) {\n         ServerDetails newDetails = serverApi.get(server.getId());\n         assertEquals(newDetails.getId(), server.getId());\n         assertEquals(newDetails.getHostname(), server.getHostname());\n         assertEquals(newDetails.getPlatform(), server.getPlatform());\n         assertEquals(newDetails.getDatacenter(), server.getDatacenter());\n         checkServer(newDetails);\n      }\n   }\n\n   public void testServerDetails() throws Exception {\n      ServerDetails details = serverApi.get(serverId);\n      checkServer(details);\n      assertEquals(\"Ubuntu 10.04 LTS 32-bit\", details.getTemplateName());\n      assertEquals(\"Falkenberg\", details.getDatacenter());\n      assertEquals(\"OpenVZ\", details.getPlatform());\n      assertEquals(5, details.getDiskSizeGB());\n      assertEquals(512, details.getMemorySizeMB());\n      assertEquals(1, details.getCpuCores());\n      assertEquals(50, details.getTransferGB());\n   }\n\n   public void testServerStatus() throws Exception {\n      ServerStatus newStatus = serverApi.getStatus(serverId);\n      checkStatus(newStatus);\n   }\n\n   public void testUpdateServer() throws Exception {\n      ServerDetails edited = serverApi.update(serverId, UpdateServerOptions.Builder.description(\"this is a different description!\"));\n      assertEquals(edited.getDescription(), \"this is a different description!\");\n\n      edited = serverApi.update(serverId, UpdateServerOptions.Builder.description(\"another description!\").hostname(\"host-name1\"));\n      assertEquals(edited.getDescription(), \"another description!\");\n      assertEquals(edited.getHostname(), \"host-name1\");\n\n      edited = serverApi.resetPassword(serverId, \"anotherpass\");\n      assertEquals(edited.getHostname(), \"host-name1\");\n\n      edited = serverApi.update(serverId, UpdateServerOptions.Builder.hostname(hostName));\n      assertEquals(edited.getHostname(), hostName);\n   }\n\n   @Test\n   public void testRebootServer() throws Exception {\n      assertTrue(serverStatusChecker.apply(Server.State.RUNNING));\n\n      serverApi.reboot(serverId);\n\n      assertTrue(serverStatusChecker.apply(Server.State.RUNNING));\n   }\n\n   @Test\n   public void testStopAndStartServer() throws Exception {\n      assertTrue(serverStatusChecker.apply(Server.State.RUNNING));\n\n      serverApi.stop(serverId);\n\n      assertTrue(serverStatusChecker.apply(Server.State.STOPPED));\n\n      serverApi.start(serverId);\n\n      assertTrue(serverStatusChecker.apply(Server.State.RUNNING));\n   }\n\n   public void testServerLimits() throws Exception {\n      Map<String, ServerLimit> limits = serverApi.getLimits(serverId);\n      assertNotNull(limits);\n      for (Map.Entry<String, ServerLimit> entry : limits.entrySet()) {\n         assertNotNull(entry.getKey());\n         assertNotNull(entry.getValue());\n         ServerLimit limit = entry.getValue();\n         assertTrue(limit.getBarrier() >= 0);\n         assertEquals(0, limit.getFailCount());\n         assertTrue(limit.getHeld() >= 0);\n         assertTrue(limit.getLimit() > 0);\n         assertTrue(limit.getMaxHeld() >= 0);\n      }\n   }\n\n   public void testResourceUsage() throws Exception {\n      // test server has only been in existence for less than a minute - check all servers\n      for (Server server : serverApi.list()) {\n         try {\n            ResourceUsage usage = serverApi.getResourceUsage(server.getId(), \"diskioread\", \"minute\");\n            assertEquals(usage.getInfo().getResource(), \"diskioread\");\n            assertEquals(usage.getInfo().getResolution(), \"minute\");\n         } catch (UnsupportedOperationException e) {\n\n         }\n         try {\n            ResourceUsage usage = serverApi.getResourceUsage(server.getId(), \"cpuusage\", \"minute\");\n            assertEquals(usage.getInfo().getResource(), \"cpuusage\");\n            assertEquals(usage.getInfo().getResolution(), \"minute\");\n         } catch (UnsupportedOperationException e) {\n\n         }\n      }\n   }\n\n   public void testConsole() throws Exception {\n      Console console = serverApi.getConsole(serverId);\n      assertNotNull(console);\n      assertNotNull(console.getHost());\n      assertTrue(console.getPort() > 0 && console.getPort() < 65537);\n      assertNotNull(console.getPassword());\n   }\n\n   // takes a few minutes and requires an extra server (used 1 already)\n   @Test(enabled = false)\n   public void testCloneServer() throws Exception {\n      ServerDetails testServer2 = serverApi.clone(serverId, testHostName2, CloneServerOptions.Builder.cpucores(1));\n\n      assertNotNull(testServer2.getId());\n      assertEquals(testServer2.getHostname(), \"jclouds-test2\");\n      assertTrue(testServer2.getIps().isEmpty());\n\n      testServerId2 = testServer2.getId();\n\n      Predicate<State> cloneChecker = statusChecker(serverApi, testServerId2);\n      assertTrue(cloneChecker.apply(Server.State.STOPPED));\n\n      serverApi.start(testServer2.getId());\n\n      // TODO ServerStatus==STOPPED suggests the previous call to start should have worked\n      cloneChecker = retry(new Predicate<Server.State>() {\n         public boolean apply(Server.State value) {\n            ServerStatus status = serverApi.getStatus(testServerId2, ServerStatusOptions.Builder.state());\n            if (status.getState() == value) {\n               return true;\n            }\n            serverApi.start(testServerId2);\n            return false;\n         }\n      }, 600, 30, SECONDS);\n\n      assertTrue(cloneChecker.apply(Server.State.RUNNING));\n   }\n\n   private void checkServer(ServerDetails server) {\n      // description can be null\n      assert server.getCpuCores() > 0 : server;\n      assert server.getDiskSizeGB() > 0 : server;\n      assert server.getMemorySizeMB() > 0 : server;\n      assert server.getCost() != null;\n      assert server.getTransferGB() > 0 : server;\n\n      assertNotNull(server.getTemplateName());\n      assertNotNull(server.getIps());\n   }\n\n   private void checkStatus(ServerStatus status) {\n      assertNotNull(status.getState());\n      assertNotNull(status.getUptime());\n\n\n      for (ResourceStatus usage : new ResourceStatus[] { status.getCpu(), status.getDisk(), status.getMemory() }) {\n         assertNotNull(usage);\n         assert usage.getMax() >= 0.0 : status;\n         assert usage.getUsage() >= 0.0 : status;\n\n         assertNotNull(usage.getUnit());\n      }\n\n      assertNotNull(status.getUptime());\n      assert status.getUptime().getCurrent() > 0 : status;\n      assertNotNull(status.getUptime().getUnit());\n   }\n}\n"
  },
  {
    "path": "providers/glesys/src/test/java/org/jclouds/glesys/internal/BaseGleSYSApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.internal;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.glesys.GleSYSApi;\nimport org.jclouds.rest.internal.BaseRestApiExpectTest;\n\n/**\n * Configures a glesys api expect test - provides a dateService\n */\npublic class BaseGleSYSApiExpectTest extends BaseRestApiExpectTest<GleSYSApi> {\n   protected DateService dateService = new SimpleDateFormatDateService();\n\n   public BaseGleSYSApiExpectTest() {\n      provider = \"glesys\";\n   }\n}\n"
  },
  {
    "path": "providers/glesys/src/test/java/org/jclouds/glesys/internal/BaseGleSYSApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.internal;\n\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static org.jclouds.util.Predicates2.retry;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.apis.BaseApiLiveTest;\nimport org.jclouds.glesys.GleSYSApi;\nimport org.jclouds.glesys.features.DomainApi;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\n\n/**\n * Tests behavior of {@code GleSYSApi}\n */\n@Test(groups = \"live\")\npublic class BaseGleSYSApiLiveTest extends BaseApiLiveTest<GleSYSApi> {\n   protected String hostName = System.getProperty(\"user.name\").replace('.', '-').toLowerCase();\n\n   public BaseGleSYSApiLiveTest() {\n      provider = \"glesys\";\n   }\n\n   protected void createDomain(String domain) {\n      final DomainApi domainApi = api.getDomainApi();\n      int before = domainApi.list().size();\n      domainApi.create(domain);\n\n      Predicate<Integer> result = retry(new Predicate<Integer>() {\n         public boolean apply(Integer value) {\n            return domainApi.list().size() == value.intValue();\n         }\n      }, 30, 1, SECONDS);\n\n      assertTrue(result.apply(before + 1));\n   }\n\n}\n"
  },
  {
    "path": "providers/glesys/src/test/java/org/jclouds/glesys/internal/BaseGleSYSApiWithAServerLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.internal;\n\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static org.jclouds.util.Predicates2.retry;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.UUID;\nimport java.util.concurrent.TimeUnit;\n\nimport org.jclouds.glesys.domain.Server;\nimport org.jclouds.glesys.domain.Server.State;\nimport org.jclouds.glesys.domain.ServerDetails;\nimport org.jclouds.glesys.domain.ServerSpec;\nimport org.jclouds.glesys.domain.ServerStatus;\nimport org.jclouds.glesys.features.DomainApi;\nimport org.jclouds.glesys.features.ServerApi;\nimport org.jclouds.glesys.options.DestroyServerOptions;\nimport org.jclouds.glesys.options.ServerStatusOptions;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\n\n/**\n * Tests behavior of {@code GleSYSApi}\n */\n@Test(groups = \"live\", singleThreaded = true)\npublic class BaseGleSYSApiWithAServerLiveTest extends BaseGleSYSApiLiveTest {\n   protected String serverId;\n   protected Predicate<State> serverStatusChecker;\n\n   public BaseGleSYSApiWithAServerLiveTest() {\n      provider = \"glesys\";\n   }\n\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   @Override\n   public void setup() {\n      assertNull(serverId, \"This method should be called EXACTLY once per run\");\n      super.setup();\n      serverStatusChecker = createServer(hostName);\n   }\n\n   @AfterClass(groups = { \"integration\", \"live\" })\n   @Override\n   public void tearDown() {\n      api.getServerApi().destroy(serverId, DestroyServerOptions.Builder.discardIp());\n      super.tearDown();\n   }\n\n   protected void createDomain(String domain) {\n      final DomainApi domainApi = api.getDomainApi();\n      int before = domainApi.list().size();\n      domainApi.create(domain);\n      Predicate<Integer> result = retry(new Predicate<Integer>() {\n         public boolean apply(Integer value) {\n            return domainApi.list().size() == value.intValue();\n         }\n      }, 30, 1, SECONDS);\n      assertTrue(result.apply(before + 1));\n   }\n\n   protected Predicate<State> createServer(String hostName) {\n      final ServerApi serverApi = api.getServerApi();\n\n      ServerDetails testServer = serverApi.createWithHostnameAndRootPassword(\n            ServerSpec.builder().datacenter(\"Falkenberg\").platform(\"OpenVZ\").templateName(\"Ubuntu 10.04 LTS 32-bit\")\n                  .diskSizeGB(5).memorySizeMB(512).cpuCores(1).transferGB(50).build(), hostName, UUID.randomUUID()\n                  .toString().replace(\"-\", \"\"));\n\n      assertNotNull(testServer.getId());\n      assertEquals(testServer.getHostname(), hostName);\n      assertFalse(testServer.getIps().isEmpty());\n\n      Predicate<State> statusChecker = statusChecker(serverApi, testServer.getId());\n      assertTrue(statusChecker.apply(Server.State.RUNNING));\n      serverId = testServer.getId();\n      return statusChecker;\n   }\n\n   protected Predicate<State> statusChecker(final ServerApi api, final String serverId) {\n     return retry(new Predicate<Server.State>() {\n\n         public boolean apply(Server.State value) {\n            ServerStatus status = api.getStatus(serverId, ServerStatusOptions.Builder.state());\n            return status.getState() == value;\n         }\n\n      }, 300, 10, TimeUnit.SECONDS);\n   }\n}\n"
  },
  {
    "path": "providers/glesys/src/test/java/org/jclouds/glesys/parse/ParseFullIpDetailsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.parse;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.glesys.config.GleSYSParserModule;\nimport org.jclouds.glesys.domain.Cost;\nimport org.jclouds.glesys.domain.IpDetails;\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.rest.annotations.SelectJson;\n\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\npublic class ParseFullIpDetailsTest extends BaseItemParserTest<IpDetails> {\n\n   @Override\n   protected String resource() {\n      return \"/ip_get_details_xen.json\";\n   }\n\n   @Override\n   @SelectJson(\"details\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public IpDetails expected() {\n      return IpDetails.builder().datacenter(\"Falkenberg\").version4()\n            .address(\"109.74.10.13\")\n            .platform(\"Xen\").ptr(\"109-74-10-13-static.serverhotell.net.\").netmask(\"255.255.254.0\").broadcast(\"109.74.11.255\")\n            .gateway(\"109.74.10.1\").nameServers(\"79.99.4.100\", \"79.99.4.101\")\n            .cost(Cost.builder().amount(2.0).currency(\"EUR\").timePeriod(\"month\").build()).build();\n   }\n\n   protected Injector injector() {\n      return Guice.createInjector(new GleSYSParserModule(), new GsonModule());\n   }\n   \n}\n"
  },
  {
    "path": "providers/glesys/src/test/java/org/jclouds/glesys/parse/ParseIpAddressFromResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.glesys.parse;\n\nimport java.util.Set;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.glesys.config.GleSYSParserModule;\nimport org.jclouds.json.BaseSetParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\", testName = \"ParseIpAddressFromResponseTest\")\npublic class ParseIpAddressFromResponseTest extends BaseSetParserTest<String> {\n   public static final Set<String> EXPECTED_IPS = ImmutableSet.of(\"109.74.10.13\", \"109.74.10.50\", \"109.74.10.109\", \"109.74.10.125\",\n         \"109.74.10.131\", \"109.74.10.148\", \"109.74.10.171\", \"109.74.10.173\", \"109.74.10.191\", \"109.74.10.215\",\n         \"109.74.10.216\", \"109.74.10.219\", \"109.74.10.223\", \"109.74.10.224\", \"109.74.10.236\", \"109.74.10.249\",\n         \"109.74.11.49\", \"109.74.11.58\", \"109.74.11.62\", \"109.74.11.63\", \"109.74.11.73\", \"109.74.11.76\",\n         \"109.74.11.86\", \"109.74.11.98\", \"109.74.11.118\", \"109.74.11.124\", \"109.74.11.131\", \"109.74.11.137\",\n         \"109.74.11.146\", \"109.74.11.157\", \"109.74.11.159\", \"109.74.11.173\", \"109.74.11.178\", \"109.74.11.187\",\n         \"109.74.11.190\", \"109.74.11.205\", \"109.74.11.213\", \"109.74.11.234\", \"109.74.11.236\", \"109.74.11.241\",\n         \"109.74.11.243\", \"109.74.11.246\", \"109.74.11.247\");\n   \n   @Override\n   public String resource() {\n      return \"/ip_list_free.json\";\n   }\n\n   @Override\n   @SelectJson(\"ipaddresses\")\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Set<String> expected() {\n      return EXPECTED_IPS;\n   }\n\n   protected Injector injector() {\n      return Guice.createInjector(new GleSYSParserModule(), new GsonModule());\n   }\n}\n"
  },
  {
    "path": "providers/glesys/src/test/resources/archive_allowed_arguments.json",
    "content": "{\"response\":{\"status\":{\"code\":\"200\",\"text\":\"OK\"},\"argumentslist\":{\"archivesize\":[\"10\",\"20\",\"30\",\"40\",\"50\",\"60\",\"70\",\"80\",\"90\",\"100\",\"125\",\"150\",\"175\",\"200\",\"225\",\"250\",\"275\",\"300\",\"325\",\"350\",\"375\",\"400\",\"425\",\"450\",\"475\",\"500\",\"550\",\"600\",\"650\",\"700\",\"750\",\"800\",\"850\",\"900\",\"950\",\"1000\"]},\"debug\":{\"input\":[]}}}"
  },
  {
    "path": "providers/glesys/src/test/resources/archive_details.json",
    "content": "{\"response\":{\"status\":{\"code\":\"200\",\"text\":\"OK\"},\"details\":{\"username\":\"xxxxxx_test1\",\"sizetotal\":\"30 GB\",\"sizefree\":\"30 GB\",\"locked\":false},\"debug\":{\"input\":{\"username\":\"xxxxxx_test1\"}}}}"
  },
  {
    "path": "providers/glesys/src/test/resources/archive_list.json",
    "content": "{\"response\":{\"status\":{\"code\":\"200\",\"text\":\"OK\"},\"archives\":[{\"username\":\"xxxxx_test1\",\"sizetotal\":\"30 GB\",\"sizefree\":\"20 GB\",\"locked\":false}],\"debug\":{\"input\":[]}}}"
  },
  {
    "path": "providers/glesys/src/test/resources/domain_details.json",
    "content": "{\"response\":{\"status\":{\"code\":200,\"timestamp\":\"2012-06-24T11:52:49+02:00\",\"text\":\"Domain added\"},\"domain\":{\"domainname\":\"cl13016-domain.jclouds.org\",\"createtime\":\"2012-06-24T11:52:49+02:00\",\"recordcount\":9,\"usingglesysnameserver\":\"no\"},\"debug\":{\"input\":{\"domainname\":\"cl13016-domain.jclouds.org\"}}}}"
  },
  {
    "path": "providers/glesys/src/test/resources/domain_list.json",
    "content": "{\"response\":{\"status\":{\"code\":200,\"text\":\"OK\"},\"domains\":[{\"domainname\":\"testglesys.jclouds.org\",\"createtime\":\"2012-01-31T12:19:03+01:00\",\"recordcount\":9,\"usingglesysnameserver\":\"no\"}],\"debug\":{\"input\":[]}}}"
  },
  {
    "path": "providers/glesys/src/test/resources/domain_list_records.json",
    "content": "{\"response\":{\"status\":{\"code\":200,\"text\":\"OK\"},\"records\":[{\"recordid\":224546,\"domainname\":\"testglesys.jclouds.org\",\"host\":\"@\",\"type\":\"TXT\",\"data\":\"v=spf1 include:spf.glesys.se -all\",\"ttl\":3600},{\"recordid\":224545,\"domainname\":\"testglesys.jclouds.org\",\"host\":\"@\",\"type\":\"MX\",\"data\":\"20 mx02.glesys.se.\",\"ttl\":3600},{\"recordid\":224543,\"domainname\":\"testglesys.jclouds.org\",\"host\":\"mail\",\"type\":\"A\",\"data\":\"79.99.4.40\",\"ttl\":3600},{\"recordid\":224544,\"domainname\":\"testglesys.jclouds.org\",\"host\":\"@\",\"type\":\"MX\",\"data\":\"10 mx01.glesys.se.\",\"ttl\":3600},{\"recordid\":224542,\"domainname\":\"testglesys.jclouds.org\",\"host\":\"www\",\"type\":\"A\",\"data\":\"127.0.0.1\",\"ttl\":3600},{\"recordid\":224541,\"domainname\":\"testglesys.jclouds.org\",\"host\":\"@\",\"type\":\"A\",\"data\":\"127.0.0.1\",\"ttl\":3600},{\"recordid\":224540,\"domainname\":\"testglesys.jclouds.org\",\"host\":\"@\",\"type\":\"NS\",\"data\":\"ns3.namesystem.se.\",\"ttl\":3600},{\"recordid\":224539,\"domainname\":\"testglesys.jclouds.org\",\"host\":\"@\",\"type\":\"NS\",\"data\":\"ns2.namesystem.se.\",\"ttl\":3600},{\"recordid\":224538,\"domainname\":\"testglesys.jclouds.org\",\"host\":\"@\",\"type\":\"NS\",\"data\":\"ns1.namesystem.se.\",\"ttl\":3600}],\"debug\":{\"input\":{\"domainname\":\"testglesys.jclouds.org\"}}}}"
  },
  {
    "path": "providers/glesys/src/test/resources/domain_record.json",
    "content": "{\"response\":{\"status\":{\"code\":200,\"timestamp\":\"2012-06-24T11:52:51+02:00\",\"text\":\"Record added.\"},\"record\":{\"recordid\":256151,\"domainname\":\"cl13016-domain.jclouds.org\",\"host\":\"test\",\"type\":\"A\",\"data\":\"127.0.0.1\",\"ttl\":3600},\"debug\":{\"input\":{\"domainname\":\"cl13016-domain.jclouds.org\",\"type\":\"A\",\"host\":\"test\",\"data\":\"127.0.0.1\"}}}}"
  },
  {
    "path": "providers/glesys/src/test/resources/email_details.json",
    "content": "{\"response\":{\"status\":{\"code\":200,\"timestamp\":\"2012-06-20T12:01:01+02:00\",\"text\":\"Account created\"},\"emailaccount\":{\"emailaccount\":\"test@CL13016.jclouds.org\",\"quota\":{\"max\":200,\"unit\":\"MB\"},\"antispamlevel\":3,\"antivirus\":\"yes\",\"autorespond\":\"no\",\"autorespondmessage\":null,\"autorespondsaveemail\":\"yes\",\"created\":\"2012-06-20T12:01:01+02:00\",\"modified\":null},\"debug\":{\"input\":{\"emailaccount\":\"test@CLXXXX.jclouds.org\",\"password\":\"password\",\"antivirus\":\"1\",\"autorespond\":\"1\",\"autorespondmessage\":\"out of office\"}}}}\n"
  },
  {
    "path": "providers/glesys/src/test/resources/email_list.json",
    "content": "{\"response\":{\n    \"status\":{\"code\":200,\"timestamp\":\"2012-06-24T11:53:55+02:00\",\"text\":\"OK\"},\n    \"list\":{\n        \"emailaccounts\":[\n            {\"emailaccount\":\"test1@cl13016.test.jclouds.org\",\"quota\":{\"max\":200,\"unit\":\"MB\"},\"antispamlevel\":3,\"antivirus\":\"yes\",\"autorespond\":\"no\",\"autorespondmessage\":null,\"autorespondsaveemail\":\"yes\",\"created\":\"2012-06-24T11:53:45+02:00\",\"modified\":null},\n            {\"emailaccount\":\"test@cl13016.test.jclouds.org\",\"quota\":{\"max\":200,\"unit\":\"MB\"},\"antispamlevel\":3,\"antivirus\":\"no\",\"autorespond\":\"no\",\"autorespondmessage\":null,\"autorespondsaveemail\":\"yes\",\"created\":\"2012-06-24T11:53:44+02:00\",\"modified\":\"2012-06-24T11:53:48+02:00\"}\n        ],\n        \"emailaliases\":[\n            {\"emailalias\":\"test2@cl13016.test.jclouds.org\",\"goto\":\"test1@cl13016.test.jclouds.org\"}\n        ]\n    },\n    \"debug\":{\"input\":{\"domainname\":\"cl13016.test.jclouds.org\"}}}}"
  },
  {
    "path": "providers/glesys/src/test/resources/email_overview.json",
    "content": "{\"response\":{\"status\":{\"code\":200,\"timestamp\":\"2012-06-24T11:53:53+02:00\",\"text\":\"OK\"},\n    \"overview\":{\n        \"summary\":{\"accounts\":2,\"maxaccounts\":50,\"aliases\":1,\"maxaliases\":1000},\n        \"domains\":[{\n            \"domainname\":\"cl13016.test.jclouds.org\",\"accounts\":2,\"aliases\":1,\"usingglesysemailserver\":\"no\"}]},\n    \"debug\":{\"input\":[]}}}\"\n"
  },
  {
    "path": "providers/glesys/src/test/resources/ip_get_details.json",
    "content": "{\"response\":{\"status\":{\"code\":200,\"timestamp\":\"2012-06-21T13:11:26+02:00\",\"text\":\"OK\"},\n    \"details\":{\n        \"ipaddress\":\"31.192.227.113\",\n        \"netmask\":null,\n        \"broadcast\":null,\n        \"gateway\":null,\n        \"nameservers\":[\"79.99.4.100\",\"79.99.4.101\"],\n        \"platform\":\"OpenVZ\",\n        \"datacenter\":\"Falkenberg\",\n        \"ipversion\":4,\n        \"serverid\":null,\n        \"reserved\":\"no\",\n        \"ptr\":\"31-192-227-113-static.serverhotell.net.\",\n        \"cost\":{\"amount\":2,\"currency\":\"EUR\",\"timeperiod\":\"month\"}\n    },\n    \"debug\":{\"input\":{\"ipaddress\":\"31.192.227.113\"}}}}"
  },
  {
    "path": "providers/glesys/src/test/resources/ip_get_details_xen.json",
    "content": "{\"response\":{\"status\":{\"code\":200,\"timestamp\":\"2012-06-21T13:11:25+02:00\",\"text\":\"OK\"},\n    \"details\":{\n        \"ipaddress\":\"109.74.10.13\",\n        \"netmask\":\"255.255.254.0\",\n        \"broadcast\":\"109.74.11.255\",\n        \"gateway\":\"109.74.10.1\",\n        \"nameservers\":[\"79.99.4.100\",\"79.99.4.101\"],\n        \"platform\":\"Xen\",\n        \"datacenter\":\"Falkenberg\",\n        \"ipversion\":4,\n        \"serverid\":null,\n        \"reserved\":\"no\",\n        \"ptr\":\"109-74-10-13-static.serverhotell.net.\",\n        \"cost\":{\"amount\":2,\"currency\":\"EUR\",\"timeperiod\":\"month\"}},\n    \"debug\":{\"input\":{\"ipaddress\":\"109.74.10.13\"}}}}\n"
  },
  {
    "path": "providers/glesys/src/test/resources/ip_list_free.json",
    "content": "{\"response\":{\"status\":{\"code\":200,\"timestamp\":\"2012-06-21T13:01:55+02:00\",\"text\":\"OK\"},\"iplist\":{\"ipversion\":4,\"datacenter\":\"Falkenberg\",\"platform\":\"Xen\",\"ipaddresses\":[\"109.74.10.13\",\"109.74.10.50\",\"109.74.10.109\",\"109.74.10.125\",\"109.74.10.131\",\"109.74.10.148\",\"109.74.10.171\",\"109.74.10.173\",\"109.74.10.191\",\"109.74.10.215\",\"109.74.10.216\",\"109.74.10.219\",\"109.74.10.223\",\"109.74.10.224\",\"109.74.10.236\",\"109.74.10.249\",\"109.74.11.49\",\"109.74.11.58\",\"109.74.11.62\",\"109.74.11.63\",\"109.74.11.73\",\"109.74.11.76\",\"109.74.11.86\",\"109.74.11.98\",\"109.74.11.118\",\"109.74.11.124\",\"109.74.11.131\",\"109.74.11.137\",\"109.74.11.146\",\"109.74.11.157\",\"109.74.11.159\",\"109.74.11.173\",\"109.74.11.178\",\"109.74.11.187\",\"109.74.11.190\",\"109.74.11.205\",\"109.74.11.213\",\"109.74.11.234\",\"109.74.11.236\",\"109.74.11.241\",\"109.74.11.243\",\"109.74.11.246\",\"109.74.11.247\"]},\"debug\":{\"input\":{\"ipversion\":\"4\",\"datacenter\":\"Falkenberg\",\"platform\":\"Xen\"}}}}"
  },
  {
    "path": "providers/glesys/src/test/resources/ip_list_own.json",
    "content": "{\"response\":{\"status\":{\"code\":200,\"timestamp\":\"2012-06-24T11:54:43+02:00\",\"text\":\"OK\"},\n    \"iplist\":[\n        {\"ipaddress\":\"31.192.230.68\",\"netmask\":null,\"broadcast\":null,\"gateway\":null,\"nameservers\":[\"79.99.4.100\",\"79.99.4.101\"],\"platform\":\"OpenVZ\",\"datacenter\":\"Falkenberg\",\"ipversion\":4,\"serverid\":null,\"reserved\":\"yes\",\"ptr\":\"31-192-230-68-static.serverhotell.net.\",\"cost\":{\"amount\":2,\"currency\":\"EUR\",\"timeperiod\":\"month\"}},\n        {\"ipaddress\":\"31.192.231.148\",\"netmask\":null,\"broadcast\":null,\"gateway\":null,\"nameservers\":[\"79.99.4.100\",\"79.99.4.101\"],\"platform\":\"OpenVZ\",\"datacenter\":\"Falkenberg\",\"ipversion\":4,\"serverid\":\"vz1609110\",\"reserved\":\"yes\",\"ptr\":\"31-192-231-148-static.serverhotell.net.\",\"cost\":{\"amount\":2,\"currency\":\"EUR\",\"timeperiod\":\"month\"}}\n    ],\"debug\":{\"input\":[]}}}"
  },
  {
    "path": "providers/glesys/src/test/resources/ip_release.json",
    "content": "{\"response\":{\"status\":{\"code\":\"200\",\"text\":\"OK\"},\"debug\":{\"input\":{\"ipaddress\":\"31.192.227.37\"}}}}"
  },
  {
    "path": "providers/glesys/src/test/resources/ip_take.json",
    "content": "{\"response\":{\"status\":{\"code\":\"200\",\"text\":\"OK\"},\"debug\":{\"input\":{\"ipaddress\":\"46.21.105.186\"}}}}"
  },
  {
    "path": "providers/glesys/src/test/resources/log4j.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE log4j:configuration SYSTEM \"log4j.dtd\">\n\n    <!--\n        For more configuration infromation and examples see the Apache\n        Log4j website: http://logging.apache.org/log4j/\n    -->\n<log4j:configuration xmlns:log4j=\"http://jakarta.apache.org/log4j/\"\n    debug=\"false\">\n\n    <!-- A time/date based rolling appender -->\n    <appender name=\"WIREFILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds-wire.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n\n    <!-- A time/date based rolling appender -->\n    <appender name=\"FILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n    \n    <!-- A time/date based rolling appender -->\n    <appender name=\"COMPUTEFILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds-compute.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n\n    <!-- A time/date based rolling appender -->\n    <appender name=\"SSHFILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds-ssh.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n\n    <appender name=\"ASYNCCOMPUTE\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"COMPUTEFILE\" />\n    </appender>\n    \n    <appender name=\"ASYNCSSH\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"SSHFILE\" />\n    </appender>\n\n    <appender name=\"ASYNC\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"FILE\" />\n    </appender>\n\n    <appender name=\"ASYNCWIRE\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"WIREFILE\" />\n    </appender>\n\n    <!-- ================ -->\n    <!-- Limit categories -->\n    <!-- ================ -->\n\n    <category name=\"org.jclouds\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNC\" />\n    </category>\n\n    <category name=\"jclouds.headers\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNCWIRE\" />\n    </category>\n    \n    <category name=\"jclouds.ssh\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNCSSH\" />\n    </category>\n    \n    <category name=\"jclouds.wire\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNCWIRE\" />\n    </category>\n\n    <category name=\"jclouds.compute\">\n        <priority value=\"TRACE\" />\n        <appender-ref ref=\"ASYNCCOMPUTE\" />\n    </category>\n    <!-- ======================= -->\n    <!-- Setup the Root category -->\n    <!-- ======================= -->\n\n    <root>\n        <priority value=\"WARN\" />\n    </root>\n\n</log4j:configuration>\n"
  },
  {
    "path": "providers/glesys/src/test/resources/osmatches.json",
    "content": "{\n    \"Centos 5\": {\n        \"family\": \"CENTOS\",\n        \"version\": \"5.0\",\n        \"is64Bit\": false\n    },\n    \"Centos 5 64-bit\": {\n        \"family\": \"CENTOS\",\n        \"version\": \"5.0\",\n        \"is64Bit\": true\n    },\n    \"CentOS 5.5 x64\": {\n        \"family\": \"CENTOS\",\n        \"version\": \"5.5\",\n        \"is64Bit\": true\n    },    \n    \"CentOS 5.5 x86\": {\n        \"family\": \"CENTOS\",\n        \"version\": \"5.5\",\n        \"is64Bit\": false\n    },\n    \"Centos 6 32-bit\": {\n        \"family\": \"CENTOS\",\n        \"version\": \"6.0\",\n        \"is64Bit\": false\n    },\n    \"Centos 6 64-bit\": {\n        \"family\": \"CENTOS\",\n        \"version\": \"6.0\",\n        \"is64Bit\": true\n    },\n    \"Centos 6 x64\": {\n        \"family\": \"CENTOS\",\n        \"version\": \"6.0\",\n        \"is64Bit\": true\n    },\n    \"Centos 6 x86\": {\n        \"family\": \"CENTOS\",\n        \"version\": \"6.0\",\n        \"is64Bit\": false\n    },\n    \"Debian 5.0\": {\n        \"family\": \"DEBIAN\",\n        \"version\": \"5.0\",\n        \"is64Bit\": false\n    },\n    \"Debian 5.0 64-bit\": {\n        \"family\": \"DEBIAN\",\n        \"version\": \"5.0\",\n        \"is64Bit\": true\n    },\n    \"Debian 5.0.1 x64\": {\n        \"family\": \"DEBIAN\",\n        \"version\": \"5.0\",\n        \"is64Bit\": true\n    },\n    \"Debian 6.0 32-bit\": {\n        \"family\": \"DEBIAN\",\n        \"version\": \"6.0\",\n        \"is64Bit\": false\n    },\n    \"Debian 6.0 64-bit\": {\n        \"family\": \"DEBIAN\",\n        \"version\": \"6.0\",\n        \"is64Bit\": true\n    },\n    \"Debian-6 x64\": {\n        \"family\": \"DEBIAN\",\n        \"version\": \"6.0\",\n        \"is64Bit\": true\n    },\n    \"Fedora Core 11\": {\n        \"family\": \"FEDORA\",\n        \"version\": \"\",\n        \"is64Bit\": false\n    },\n    \"Fedora Core 11 64-bit\": {\n        \"family\": \"FEDORA\",\n        \"version\": \"\",\n        \"is64Bit\": true\n    },\n    \"FreeBSD 8.2\": {\n        \"family\": \"FREEBSD\",\n        \"version\": \"\",\n        \"is64Bit\": false\n    },\n    \"Gentoo\": {\n        \"family\": \"GENTOO\",\n        \"version\": \"\",        \n        \"is64Bit\": false\n    },\n    \"Gentoo 10.1 x64\": {\n        \"family\": \"GENTOO\",\n        \"version\": \"\",\n        \"is64Bit\": true\n    },\n    \"Gentoo 64-bit\": {\n        \"family\": \"GENTOO\",\n        \"version\": \"\",\n        \"is64Bit\": true\n    },\n    \"Scientific Linux 6\": {\n        \"family\": \"SCIENTIFIC\",\n        \"version\": \"\",\n        \"is64Bit\": false\n    },\n    \"Scientific Linux 6 64-bit\": {\n        \"family\": \"SCIENTIFIC\",\n        \"version\": \"\",\n        \"is64Bit\": true\n    },\n    \"Slackware 12\": {\n        \"family\": \"SLACKWARE\",\n        \"version\": \"\",\n        \"is64Bit\": false\n    },                             \n    \"Ubuntu 10.04 LTS 32-bit\": {\n        \"family\": \"UBUNTU\",\n        \"version\": \"10.04\",\n        \"is64Bit\": false\n    },\n    \"Ubuntu 10.04 LTS 64-bit\": {\n        \"family\": \"UBUNTU\",\n        \"version\": \"10.04\",\n        \"is64Bit\": true\n    },\n    \"Ubuntu 10.10 x64\": {\n        \"family\": \"UBUNTU\",\n        \"version\": \"10.10\",\n        \"is64Bit\": true\n    },        \n    \"Ubuntu 11.04 64-bit\": {\n        \"family\": \"UBUNTU\",\n        \"version\": \"11.04\",\n        \"is64Bit\": true\n    },  \n    \"Ubuntu 11.04 x64\": {\n        \"family\": \"UBUNTU\",\n        \"version\": \"11.04\",\n        \"is64Bit\": true\n    },                             \n    \"Ubuntu 8.04 x64\": {\n        \"family\": \"UBUNTU\",\n        \"version\": \"8.04\",\n        \"is64Bit\": true\n    },\n    \"Windows Server 2008 R2 x64 std\": {\n        \"family\": \"WINDOWS\",\n        \"version\": \"2008 R2\",\n        \"is64Bit\": true\n    },\n    \"Windows Server 2008 R2 x64 web\": {\n        \"family\": \"WINDOWS\",\n        \"version\": \"2008 R2\",\n        \"is64Bit\": true\n    },\n    \"Windows Server 2008 x64 web\": {\n        \"family\": \"WINDOWS\",\n        \"version\": \"2008\",\n        \"is64Bit\": true\n    },\n    \"Windows Server 2008 x86 web\": {\n        \"family\": \"WINDOWS\",\n        \"version\": \"2008\",\n        \"is64Bit\": false\n    }\n}"
  },
  {
    "path": "providers/glesys/src/test/resources/server_allowed_arguments.json",
    "content": "{\"response\":{\"status\":{\"code\":200,\"timestamp\":\"2012-12-05T08:15:17+01:00\",\"text\":\"OK\"},\"argumentslist\":{\"Xen\":{\"disksize\":{\"costperunit\":{\"amount\":2.2,\"currency\":\"SEK\",\"timeperiod\":\"month\"},\"units\":[5,10,20,30,40,50,80,100,120,140,150,160,200,250,300]},\"memorysize\":{\"costperunit\":{\"amount\":0.09,\"currency\":\"SEK\",\"timeperiod\":\"month\"},\"units\":[512,768,1024,1536,2048,2560,3072,3584,4096,5120,6144,7168,8192,9216,10240,11264,12288,14336,16384]},\"cpucores\":{\"costperunit\":{\"amount\":30,\"currency\":\"SEK\",\"timeperiod\":\"month\"},\"units\":[1,2,3,4,5,6,7,8]},\"template\":[\"CentOS 5.5 x64\",\"CentOS 5.5 x86\",\"Centos 6 x64\",\"Centos 6 x86\",\"Debian-6 x64\",\"Debian 5.0.1 x64\",\"FreeBSD 8.2\",\"FreeBSD 9.0\",\"Gentoo 10.1 x64\",\"OpenSUSE 11.4 64-bit\",\"Ubuntu 8.04 x64\",\"Ubuntu 10.04 LTS 64-bit\",\"Ubuntu 10.10 x64\",\"Ubuntu 11.04 x64\",\"Ubuntu 12.04 x64\",\"Ubuntu 12.04 x86\",\"Windows Server 2008 R2 x64 std\",\"Windows Server 2008 R2 x64 web\",\"Windows Server 2008 x64 web\"],\"transfer\":{\"costperunit\":{\"amount\":0.2,\"currency\":\"SEK\",\"timeperiod\":\"month\"},\"units\":[50,100,250,500,1000,2000,3000,4000,5000,6000,7000,8000,9000,10000]},\"datacenter\":[\"Falkenberg\"]},\"OpenVZ\":{\"disksize\":{\"costperunit\":{\"amount\":2.2,\"currency\":\"SEK\",\"timeperiod\":\"month\"},\"units\":[5,10,20,30,40,50,60,70,80,90,100,120,140,150]},\"memorysize\":{\"costperunit\":{\"amount\":0.09,\"currency\":\"SEK\",\"timeperiod\":\"month\"},\"units\":[128,256,512,768,1024,1536,2048,2560,3072,3584,4096,5120,6144,7168,8192,9216,10240,11264,12288,14336,16384]},\"cpucores\":{\"costperunit\":{\"amount\":30,\"currency\":\"SEK\",\"timeperiod\":\"month\"},\"units\":[1,2,3,4,5,6,7,8]},\"transfer\":{\"costperunit\":{\"amount\":0.2,\"currency\":\"SEK\",\"timeperiod\":\"month\"},\"units\":[50,100,250,500,1000,2000,3000,4000,5000,6000,7000,8000,9000,10000]},\"template\":[\"Centos 5\",\"Centos 5 64-bit\",\"Centos 6 32-bit\",\"Centos 6 64-bit\",\"Debian 5.0 32-bit\",\"Debian 5.0 64-bit\",\"Debian 6.0 32-bit\",\"Debian 6.0 64-bit\",\"Fedora Core 11\",\"Fedora Core 11 64-bit\",\"Gentoo\",\"Gentoo 64-bit\",\"Scientific Linux 6\",\"Scientific Linux 6 64-bit\",\"Slackware 12\",\"Ubuntu 10.04 LTS 32-bit\",\"Ubuntu 10.04 LTS 64-bit\",\"Ubuntu 11.04 64-bit\",\"Ubuntu 12.04 LTS 32-bit\",\"Ubuntu 12.04 LTS 64-bit\"],\"datacenter\":[\"Amsterdam\",\"Falkenberg\",\"New York City\",\"Stockholm\"]}},\"debug\":{\"input\":[]}}}"
  },
  {
    "path": "providers/glesys/src/test/resources/server_console.json",
    "content": "{\"response\":{\"status\":{\"code\":\"200\",\"text\":\"OK\"},\"console\":{\"host\":\"79.99.2.147\",\"port\":\"59478\",\"protocol\":\"vnc\",\"password\":\"1476897311\"},\"debug\":{\"input\":{\"serverid\":\"vz1842554\"}}}}"
  },
  {
    "path": "providers/glesys/src/test/resources/server_details.json",
    "content": "{\"response\":{\"status\":{\"code\":200,\"timestamp\":\"2012-06-21T14:10:57+02:00\",\"text\":\"OK\"},\n    \"server\":{\n        \"serverid\":\"vz1840356\",\n        \"hostname\":\"glesys-s\",\n        \"description\":\"glesys-s-6dd\",\n        \"cpucores\":1,\n        \"memorysize\":512,\n        \"disksize\":5,\n        \"transfer\":50,\n        \"templatename\":\"Ubuntu 10.04 LTS 32-bit\",\n        \"datacenter\":\"Falkenberg\",\n        \"managedhosting\":\"no\",\n        \"platform\":\"OpenVZ\",\n        \"cost\":{\"amount\":10.22,\"currency\":\"EUR\",\"timeperiod\":\"month\"},\n        \"iplist\":[{\"ipaddress\":\"31.192.231.254\",\"version\":4,\"cost\":2,\"currency\":\"EUR\"}],\"state\":\"running\"},\n        \"debug\":{\"input\":{\"includestate\":\"1\",\"serverid\":\"vz1840356\"}}}}"
  },
  {
    "path": "providers/glesys/src/test/resources/server_limits.json",
    "content": "{\"response\":{\"status\":{\"code\":\"200\",\"text\":\"OK\"},\"limits\":{\"numiptent\":{\"held\":\"24\",\"maxheld\":\"24\",\"barrier\":\"800\",\"limit\":\"800\",\"failcnt\":0},\"numfile\":{\"held\":\"91\",\"maxheld\":\"140\",\"barrier\":\"4000\",\"limit\":\"4000\",\"failcnt\":0},\"dcachesize\":{\"held\":\"695143\",\"maxheld\":\"724260\",\"barrier\":\"3500000\",\"limit\":\"4375000\",\"failcnt\":0},\"numothersock\":{\"held\":\"63\",\"maxheld\":\"66\",\"barrier\":\"6000\",\"limit\":\"6000\",\"failcnt\":0},\"dgramrcvbuf\":{\"held\":\"0\",\"maxheld\":\"0\",\"barrier\":\"209715200\",\"limit\":\"262144000\",\"failcnt\":0},\"othersockbuf\":{\"held\":\"4624\",\"maxheld\":\"13080\",\"barrier\":\"209715200\",\"limit\":\"262144000\",\"failcnt\":0},\"tcprcvbuf\":{\"held\":\"32768\",\"maxheld\":\"32768\",\"barrier\":\"209715200\",\"limit\":\"262144000\",\"failcnt\":0},\"tcpsndbuf\":{\"held\":\"34880\",\"maxheld\":\"34880\",\"barrier\":\"209715200\",\"limit\":\"262144000\",\"failcnt\":0},\"numsiginfo\":{\"held\":\"0\",\"maxheld\":\"15\",\"barrier\":\"256\",\"limit\":\"256\",\"failcnt\":0},\"numpty\":{\"held\":\"0\",\"maxheld\":\"0\",\"barrier\":\"32\",\"limit\":\"32\",\"failcnt\":0},\"numflock\":{\"held\":\"1\",\"maxheld\":\"2\",\"barrier\":\"376\",\"limit\":\"412\",\"failcnt\":0},\"numtcpsock\":{\"held\":\"2\",\"maxheld\":\"2\",\"barrier\":\"6000\",\"limit\":\"6000\",\"failcnt\":0},\"oomguarpages\":{\"held\":\"362\",\"maxheld\":\"464\",\"barrier\":\"32768\",\"limit\":\"32768\",\"failcnt\":0},\"vmguarpages\":{\"held\":\"0\",\"maxheld\":\"0\",\"barrier\":\"32768\",\"limit\":\"32768\",\"failcnt\":0},\"physpages\":{\"held\":\"2056\",\"maxheld\":\"5194\",\"barrier\":\"0\",\"limit\":\"9223372036854775807\",\"failcnt\":0},\"numproc\":{\"held\":\"21\",\"maxheld\":\"33\",\"barrier\":\"2000\",\"limit\":\"2000\",\"failcnt\":0},\"shmpages\":{\"held\":\"0\",\"maxheld\":\"0\",\"barrier\":\"512000\",\"limit\":\"512000\",\"failcnt\":0},\"privvmpages\":{\"held\":\"650\",\"maxheld\":\"1718\",\"barrier\":\"32768\",\"limit\":\"32768\",\"failcnt\":0},\"lockedpages\":{\"held\":\"0\",\"maxheld\":\"0\",\"barrier\":\"256\",\"limit\":\"256\",\"failcnt\":0},\"kmemsize\":{\"held\":\"1964946\",\"maxheld\":\"2932736\",\"barrier\":\"7680000\",\"limit\":\"11520000\",\"failcnt\":0}},\"debug\":{\"input\":{\"serverid\":\"vz1908384\"}}}}"
  },
  {
    "path": "providers/glesys/src/test/resources/server_list.json",
    "content": "{\"response\":{\"status\":{\"code\":\"200\",\"text\":\"OK\"},\"servers\":[{\"serverid\":\"vz1541880\",\"hostname\":\"mammamia\",\"datacenter\":\"Falkenberg\",\"platform\":\"OpenVZ\"}],\"arguments\":[]}}\n"
  },
  {
    "path": "providers/glesys/src/test/resources/server_noip.json",
    "content": "{\"response\":{\"status\":{\"code\":\"200\",\"text\":\"OK\"},\"server\":{\"serverid\":\"vz1541880\",\"hostname\":\"mammamia\",\"description\":\"description\",\"cpucores\":\"1\",\"memorysize\":\"128\",\"disksize\":\"5\",\"transfer\":\"50\",\"templatename\":\"Ubuntu 11.04 64-bit\",\"datacenter\":\"Falkenberg\",\"managedhosting\":\"no\",\"platform\":\"OpenVZ\",\"cost\":{\"amount\":6.38,\"currency\":\"EUR\",\"timeperiod\":\"month\"},\"iplist\":[]},\"debug\":{\"serverid\":\"vz1541880\"}}}\n"
  },
  {
    "path": "providers/glesys/src/test/resources/server_resource_usage.json",
    "content": "{\"response\":{\n    \"status\":{\"code\":200,\"timestamp\":\"2012-06-24T14:28:10+02:00\",\"text\":\"OK\"},\n    \"usage\":{\n        \"info\":{\"type\":\"diskioread\",\"resolution\":\"minute\",\"unit\":\"KB\"},\n        \"values\":[\n            {\"timestamp\":\"2012-06-24T14:21:07+02:00\",\"value\":0},\n            {\"timestamp\":\"2012-06-24T14:22:05+02:00\",\"value\":5.1},\n            {\"timestamp\":\"2012-06-24T14:23:05+02:00\",\"value\":0},\n            {\"timestamp\":\"2012-06-24T14:24:08+02:00\",\"value\":10},\n            {\"timestamp\":\"2012-06-24T14:25:12+02:00\",\"value\":0},\n            {\"timestamp\":\"2012-06-24T14:26:07+02:00\",\"value\":0},\n            {\"timestamp\":\"2012-06-24T14:27:12+02:00\",\"value\":0},\n            {\"timestamp\":\"2012-06-24T14:28:05+02:00\",\"value\":0}\n        ]\n    },\n    \"debug\":{\"input\":{\"serverid\":\"vz1166090\",\"resolution\":\"minute\",\"resource\":\"diskioread\"}}}}"
  },
  {
    "path": "providers/glesys/src/test/resources/server_status.json",
    "content": "{\"response\":{\"status\":{\"code\":200,\"timestamp\":\"2012-06-21T15:29:31+02:00\",\"text\":\"OK\"},\"server\":{\"state\":\"running\",\"cpu\":{\"usage\":0,\"max\":1,\"unit\":\"cores\"},\"memory\":{\"usage\":2,\"max\":512,\"unit\":\"MB\"},\"disk\":{\"usage\":0,\"max\":5120,\"unit\":\"MB\"},\"transfer\":{\"usage\":0,\"max\":50,\"unit\":\"GB last 30 days\"},\"uptime\":{\"current\":21,\"unit\":\"seconds\"},\"warnings\":[]},\"debug\":{\"input\":{\"serverid\":\"vz1321233\"}}}}"
  },
  {
    "path": "providers/glesys/src/test/resources/server_templates.json",
    "content": "{\"response\":{\"status\":{\"code\":200,\"timestamp\":\"2012-02-08T17:07:37+01:00\",\"text\":\"OK\"},\"templates\":{\"OpenVZ\":[{\"name\":\"Centos 5\",\"minimumdisksize\":5,\"minimummemorysize\":128,\"operatingsystem\":\"linux\",\"platform\":\"OpenVZ\"},{\"name\":\"Centos 5 64-bit\",\"minimumdisksize\":5,\"minimummemorysize\":128,\"operatingsystem\":\"linux\",\"platform\":\"OpenVZ\"},{\"name\":\"Centos 6 32-bit\",\"minimumdisksize\":5,\"minimummemorysize\":128,\"operatingsystem\":\"linux\",\"platform\":\"OpenVZ\"},{\"name\":\"Centos 6 64-bit\",\"minimumdisksize\":5,\"minimummemorysize\":128,\"operatingsystem\":\"linux\",\"platform\":\"OpenVZ\"},{\"name\":\"Debian 5.0 32-bit\",\"minimumdisksize\":5,\"minimummemorysize\":128,\"operatingsystem\":\"linux\",\"platform\":\"OpenVZ\"},{\"name\":\"Debian 5.0 64-bit\",\"minimumdisksize\":5,\"minimummemorysize\":128,\"operatingsystem\":\"linux\",\"platform\":\"OpenVZ\"},{\"name\":\"Debian 6.0 32-bit\",\"minimumdisksize\":5,\"minimummemorysize\":128,\"operatingsystem\":\"linux\",\"platform\":\"OpenVZ\"},{\"name\":\"Debian 6.0 64-bit\",\"minimumdisksize\":5,\"minimummemorysize\":128,\"operatingsystem\":\"linux\",\"platform\":\"OpenVZ\"},{\"name\":\"Fedora Core 11\",\"minimumdisksize\":5,\"minimummemorysize\":128,\"operatingsystem\":\"linux\",\"platform\":\"OpenVZ\"},{\"name\":\"Fedora Core 11 64-bit\",\"minimumdisksize\":5,\"minimummemorysize\":128,\"operatingsystem\":\"linux\",\"platform\":\"OpenVZ\"},{\"name\":\"Gentoo\",\"minimumdisksize\":5,\"minimummemorysize\":128,\"operatingsystem\":\"linux\",\"platform\":\"OpenVZ\"},{\"name\":\"Gentoo 64-bit\",\"minimumdisksize\":5,\"minimummemorysize\":128,\"operatingsystem\":\"linux\",\"platform\":\"OpenVZ\"},{\"name\":\"Scientific Linux 6\",\"minimumdisksize\":5,\"minimummemorysize\":128,\"operatingsystem\":\"linux\",\"platform\":\"OpenVZ\"},{\"name\":\"Scientific Linux 6 64-bit\",\"minimumdisksize\":5,\"minimummemorysize\":128,\"operatingsystem\":\"linux\",\"platform\":\"OpenVZ\"},{\"name\":\"Slackware 12\",\"minimumdisksize\":5,\"minimummemorysize\":128,\"operatingsystem\":\"linux\",\"platform\":\"OpenVZ\"},{\"name\":\"Ubuntu 10.04 LTS 32-bit\",\"minimumdisksize\":5,\"minimummemorysize\":128,\"operatingsystem\":\"linux\",\"platform\":\"OpenVZ\"},{\"name\":\"Ubuntu 10.04 LTS 64-bit\",\"minimumdisksize\":5,\"minimummemorysize\":128,\"operatingsystem\":\"linux\",\"platform\":\"OpenVZ\"},{\"name\":\"Ubuntu 11.04 64-bit\",\"minimumdisksize\":5,\"minimummemorysize\":128,\"operatingsystem\":\"linux\",\"platform\":\"OpenVZ\"}],\"Xen\":[{\"name\":\"CentOS 5.5 x64\",\"minimumdisksize\":5,\"minimummemorysize\":512,\"operatingsystem\":\"linux\",\"platform\":\"Xen\"},{\"name\":\"CentOS 5.5 x86\",\"minimumdisksize\":5,\"minimummemorysize\":512,\"operatingsystem\":\"linux\",\"platform\":\"Xen\"},{\"name\":\"Centos 6 x64\",\"minimumdisksize\":5,\"minimummemorysize\":512,\"operatingsystem\":\"linux\",\"platform\":\"Xen\"},{\"name\":\"Centos 6 x86\",\"minimumdisksize\":5,\"minimummemorysize\":512,\"operatingsystem\":\"linux\",\"platform\":\"Xen\"},{\"name\":\"Debian-6 x64\",\"minimumdisksize\":5,\"minimummemorysize\":512,\"operatingsystem\":\"linux\",\"platform\":\"Xen\"},{\"name\":\"Debian 5.0.1 x64\",\"minimumdisksize\":5,\"minimummemorysize\":512,\"operatingsystem\":\"linux\",\"platform\":\"Xen\"},{\"name\":\"FreeBSD 8.2\",\"minimumdisksize\":5,\"minimummemorysize\":512,\"operatingsystem\":\"freebsd\",\"platform\":\"Xen\"},{\"name\":\"Gentoo 10.1 x64\",\"minimumdisksize\":5,\"minimummemorysize\":512,\"operatingsystem\":\"linux\",\"platform\":\"Xen\"},{\"name\":\"Ubuntu 8.04 x64\",\"minimumdisksize\":5,\"minimummemorysize\":512,\"operatingsystem\":\"linux\",\"platform\":\"Xen\"},{\"name\":\"Ubuntu 10.04 LTS 64-bit\",\"minimumdisksize\":5,\"minimummemorysize\":512,\"operatingsystem\":\"linux\",\"platform\":\"Xen\"},{\"name\":\"Ubuntu 10.10 x64\",\"minimumdisksize\":5,\"minimummemorysize\":512,\"operatingsystem\":\"linux\",\"platform\":\"Xen\"},{\"name\":\"Ubuntu 11.04 x64\",\"minimumdisksize\":5,\"minimummemorysize\":512,\"operatingsystem\":\"linux\",\"platform\":\"Xen\"},{\"name\":\"Windows Server 2008 R2 x64 std\",\"minimumdisksize\":20,\"minimummemorysize\":1024,\"operatingsystem\":\"windows\",\"platform\":\"Xen\"},{\"name\":\"Windows Server 2008 R2 x64 web\",\"minimumdisksize\":20,\"minimummemorysize\":1024,\"operatingsystem\":\"windows\",\"platform\":\"Xen\"},{\"name\":\"Windows Server 2008 x64 web\",\"minimumdisksize\":20,\"minimummemorysize\":1024,\"operatingsystem\":\"windows\",\"platform\":\"Xen\"},{\"name\":\"Windows Server 2008 x86 web\",\"minimumdisksize\":20,\"minimummemorysize\":1024,\"operatingsystem\":\"windows\",\"platform\":\"Xen\"}]},\"debug\":{\"input\":[]}}}"
  },
  {
    "path": "providers/go2cloud-jhb1/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.go2cloud.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "providers/go2cloud-jhb1/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.provider</groupId>\n  <artifactId>go2cloud-jhb1</artifactId>\n  <name>jclouds Go2Cloud Johannesburg1 provider</name>\n  <description>Go2Cloud implementation targeted to Johannesburg1</description>\n\n  <properties>\n    <test.go2cloud-jhb1.endpoint>http://api-jhb1.go2cloud.co.za</test.go2cloud-jhb1.endpoint>\n    <test.go2cloud-jhb1.api-version>2.0</test.go2cloud-jhb1.api-version>\n    <test.go2cloud-jhb1.build-version />\n    <test.go2cloud-jhb1.identity>FIXME_IDENTITY</test.go2cloud-jhb1.identity>\n    <test.go2cloud-jhb1.credential>FIXME_CREDENTIAL</test.go2cloud-jhb1.credential>\n    <test.go2cloud-jhb1.template />\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>elasticstack</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>elasticstack</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-log4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-sshj</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.go2cloud-jhb1.endpoint>${test.go2cloud-jhb1.endpoint}</test.go2cloud-jhb1.endpoint>\n                    <test.go2cloud-jhb1.api-version>${test.go2cloud-jhb1.api-version}</test.go2cloud-jhb1.api-version>\n                    <test.go2cloud-jhb1.build-version>${test.go2cloud-jhb1.build-version}</test.go2cloud-jhb1.build-version>\n                    <test.go2cloud-jhb1.identity>${test.go2cloud-jhb1.identity}</test.go2cloud-jhb1.identity>\n                    <test.go2cloud-jhb1.credential>${test.go2cloud-jhb1.credential}</test.go2cloud-jhb1.credential>\n                    <test.go2cloud-jhb1.template>${test.go2cloud-jhb1.template}</test.go2cloud-jhb1.template>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n"
  },
  {
    "path": "providers/go2cloud-jhb1/src/main/java/org/jclouds/go2cloud/Go2CloudJohannesburg1ProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.go2cloud;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.elasticstack.ElasticStackApiMetadata;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\n\nimport com.google.auto.service.AutoService;\n\n/**\n * Implementation of {@link ProviderMetadata} for Go2Cloud's Johannesburg1 provider.\n */\n@AutoService(ProviderMetadata.class)\npublic class Go2CloudJohannesburg1ProviderMetadata extends BaseProviderMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromProviderMetadata(this);\n   }\n\n   public Go2CloudJohannesburg1ProviderMetadata() {\n      super(builder());\n   }\n\n   public Go2CloudJohannesburg1ProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = new Properties();\n      return properties;\n   }\n\n   public static class Builder extends BaseProviderMetadata.Builder {\n\n      protected Builder() {\n         id(\"go2cloud-jhb1\")\n         .name(\"Go2Cloud Johannesburg1\")\n         .apiMetadata(new ElasticStackApiMetadata().toBuilder().version(\"2.0\").build())\n         .homepage(URI.create(\"https://jhb1.go2cloud.co.za\"))\n         .console(URI.create(\"https://jhb1.go2cloud.co.za/accounts\"))\n         .iso3166Codes(\"ZA-GP\")\n         .endpoint(\"https://api-jhb1.go2cloud.co.za\")\n         .defaultProperties(Go2CloudJohannesburg1ProviderMetadata.defaultProperties());\n      }\n\n      @Override\n      public Go2CloudJohannesburg1ProviderMetadata build() {\n         return new Go2CloudJohannesburg1ProviderMetadata(this);\n      }\n\n      @Override\n      public Builder fromProviderMetadata(ProviderMetadata in) {\n         super.fromProviderMetadata(in);\n         return this;\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/go2cloud-jhb1/src/test/java/org/jclouds/go2cloud/Go2CloudJohannesburg1ApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.go2cloud;\n\nimport org.jclouds.elasticstack.ElasticStackApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"Go2CloudJohannesburg1ApiLiveTest\")\npublic class Go2CloudJohannesburg1ApiLiveTest extends ElasticStackApiLiveTest {\n   public Go2CloudJohannesburg1ApiLiveTest() {\n      provider = \"go2cloud-jhb1\";\n   }\n}\n"
  },
  {
    "path": "providers/go2cloud-jhb1/src/test/java/org/jclouds/go2cloud/Go2CloudJohannesburg1ProviderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.go2cloud;\n\nimport org.jclouds.elasticstack.ElasticStackApiMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.testng.annotations.Test;\n\n/**\n * The Go2CloudJohannesburg1ProviderTest tests the {@link Go2CloudJohannesburg1ProviderMetadata} class.\n */\n@Test(groups = \"unit\", testName = \"Go2CloudJohannesburg1ProviderTest\")\npublic class Go2CloudJohannesburg1ProviderTest extends BaseProviderMetadataTest {\n\n   public Go2CloudJohannesburg1ProviderTest() {\n      super(new Go2CloudJohannesburg1ProviderMetadata(), new ElasticStackApiMetadata());\n   }\n\n}\n"
  },
  {
    "path": "providers/go2cloud-jhb1/src/test/java/org/jclouds/go2cloud/compute/Go2CloudJohannesburg1ComputeServiceLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.go2cloud.compute;\n\nimport org.jclouds.elasticstack.compute.ElasticStackComputeServiceLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"Go2CloudJohannesburg1ComputeServiceLiveTest\")\npublic class Go2CloudJohannesburg1ComputeServiceLiveTest extends ElasticStackComputeServiceLiveTest {\n\n   public Go2CloudJohannesburg1ComputeServiceLiveTest() {\n      provider = \"go2cloud-jhb1\";\n      group = \"go2cloud\";\n   }\n\n}\n"
  },
  {
    "path": "providers/go2cloud-jhb1/src/test/java/org/jclouds/go2cloud/compute/Go2CloudJohannesburg1TemplateBuilderLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.go2cloud.compute;\n\nimport static org.jclouds.compute.util.ComputeServiceUtils.getCores;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.internal.BaseTemplateBuilderLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"live\")\npublic class Go2CloudJohannesburg1TemplateBuilderLiveTest extends BaseTemplateBuilderLiveTest {\n\n   public Go2CloudJohannesburg1TemplateBuilderLiveTest() {\n      provider = \"go2cloud-jhb1\";\n   }\n\n   @Test\n   public void testDefaultTemplateBuilder() throws IOException {\n      Template defaultTemplate = this.view.getComputeService().templateBuilder().build();\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true);\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().getVersion(), \"12.04\");\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.UBUNTU);\n      assertEquals(defaultTemplate.getLocation().getId(), \"go2cloud-jhb1\");\n      assertEquals(getCores(defaultTemplate.getHardware()), 1.0d);\n   }\n\n   @Override\n   protected Set<String> getIso3166Codes() {\n      return ImmutableSet.of(\"ZA-GP\");\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/README.txt",
    "content": "#\n# The jclouds provider for GoGrid (http://www.gogrid.com/).\n#\n# TODO: Implementation status.\n# TODO: Supported features.\n# TODO: Usage example.\n"
  },
  {
    "path": "providers/gogrid/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.gogrid.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "providers/gogrid/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.provider</groupId>\n  <artifactId>gogrid</artifactId>\n  <name>jclouds GoGrid provider</name>\n  <description>ComputeService implementation of GoGrid datacenters</description>\n\n  <properties>\n    <test.gogrid.endpoint>https://api.gogrid.com/api</test.gogrid.endpoint>\n    <test.gogrid.api-version>1.5</test.gogrid.api-version>\n    <test.gogrid.build-version />\n    <test.gogrid.identity>FIXME_IDENTITY</test.gogrid.identity>\n    <test.gogrid.credential>FIXME_CREDENTIAL</test.gogrid.credential>\n    <test.gogrid.template />\n  </properties>\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-sshj</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-slf4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>ch.qos.logback</groupId>\n      <artifactId>logback-classic</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <threadCount>1</threadCount>\n                  <systemPropertyVariables>\n                    <test.gogrid.endpoint>${test.gogrid.endpoint}</test.gogrid.endpoint>\n                    <test.gogrid.api-version>${test.gogrid.api-version}</test.gogrid.api-version>\n                    <test.gogrid.build-version>${test.gogrid.build-version}</test.gogrid.build-version>\n                    <test.gogrid.identity>${test.gogrid.identity}</test.gogrid.identity>\n                    <test.gogrid.credential>${test.gogrid.credential}</test.gogrid.credential>\n                    <test.gogrid.template>${test.gogrid.template}</test.gogrid.template>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/GoGridApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid;\n\nimport java.io.Closeable;\n\nimport org.jclouds.gogrid.features.GridImageApi;\nimport org.jclouds.gogrid.features.GridIpApi;\nimport org.jclouds.gogrid.features.GridJobApi;\nimport org.jclouds.gogrid.features.GridLoadBalancerApi;\nimport org.jclouds.gogrid.features.GridServerApi;\nimport org.jclouds.rest.annotations.Delegate;\n\npublic interface GoGridApi extends Closeable {\n\n   /**\n    * Services with methods, related to managing servers\n    */\n   @Delegate\n   GridServerApi getServerServices();\n\n   /**\n    * Services with methods, related to retrieving jobs\n    */\n   @Delegate\n   GridJobApi getJobServices();\n\n   /**\n    * Services with methods, related to retrieving IP addresses\n    */\n   @Delegate\n   GridIpApi getIpServices();\n\n   /**\n    * Services with methods, related to managing load balancers.\n    */\n   @Delegate\n   GridLoadBalancerApi getLoadBalancerServices();\n\n   /**\n    * Services with methods, related to managing images.\n    */\n   @Delegate\n   GridImageApi getImageServices();\n\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/GoGridApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid;\n\nimport static org.jclouds.reflect.Reflection2.typeToken;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.gogrid.compute.config.GoGridComputeServiceContextModule;\nimport org.jclouds.gogrid.config.GoGridHttpApiModule;\nimport org.jclouds.rest.internal.BaseHttpApiMetadata;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n/**\n * Implementation of {@link ApiMetadata} for  API\n */\npublic class GoGridApiMetadata extends BaseHttpApiMetadata<GoGridApi> {\n\n   @Override\n   public Builder toBuilder() {\n      return new Builder().fromApiMetadata(this);\n   }\n\n   public GoGridApiMetadata() {\n      this(new Builder());\n   }\n\n   protected GoGridApiMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = BaseHttpApiMetadata.defaultProperties();\n      properties.setProperty(\"jclouds.ssh.max-retries\", \"5\");\n      properties.setProperty(\"jclouds.ssh.retry-auth\", \"true\");\n      return properties;\n   }\n\n   public static class Builder extends BaseHttpApiMetadata.Builder<GoGridApi, Builder> {\n\n      @SuppressWarnings(\"deprecation\")\n      protected Builder() {\n         id(\"gogrid\")\n         .name(\"GoGrid API\")\n         .identityName(\"API Key\")\n         .credentialName(\"Shared Secret\")\n         .documentation(URI.create(\"https://wiki.gogrid.com/wiki/index.php/API\"))\n         .version(\"1.5\")\n         .defaultEndpoint(\"https://api.gogrid.com/api\")\n         .defaultProperties(GoGridApiMetadata.defaultProperties())\n         .view(typeToken(ComputeServiceContext.class))\n         .defaultModules(ImmutableSet.<Class<? extends Module>>of(GoGridHttpApiModule.class, GoGridComputeServiceContextModule.class));\n      }\n\n      @Override\n      public GoGridApiMetadata build() {\n         return new GoGridApiMetadata(this);\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/GoGridProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid;\n\nimport static org.jclouds.compute.config.ComputeServiceProperties.TEMPLATE;\nimport static org.jclouds.location.reference.LocationConstants.ISO3166_CODES;\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_ZONE;\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_ZONES;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\n\nimport com.google.auto.service.AutoService;\n\n/**\n * Implementation of {@link ProviderMetadata} for GoGrid.\n */\n@AutoService(ProviderMetadata.class)\npublic class GoGridProviderMetadata extends BaseProviderMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromProviderMetadata(this);\n   }\n\n   public GoGridProviderMetadata() {\n      super(builder());\n   }\n\n   public GoGridProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = new Properties();\n      properties.setProperty(PROPERTY_ZONES, \"1,2,3\");\n      properties.setProperty(PROPERTY_ZONE + \".1.\" + ISO3166_CODES, \"US-CA\");\n      properties.setProperty(PROPERTY_ZONE + \".2.\" + ISO3166_CODES, \"US-VA\");\n      properties.setProperty(PROPERTY_ZONE + \".3.\" + ISO3166_CODES, \"NL-NH\");\n      properties.setProperty(TEMPLATE, \"osFamily=UBUNTU,osVersionMatches=1[012].[01][04],imageNameMatches=.*w/ None.*,locationId=1\");\n      return properties;\n   }\n\n   public static class Builder extends BaseProviderMetadata.Builder {\n\n      protected Builder() {\n         id(\"gogrid\")\n         .name(\"GoGrid\")\n         .apiMetadata(new GoGridApiMetadata())\n         .homepage(URI.create(\"http://www.gogrid.com\"))\n         .console(URI.create(\"https://my.gogrid.com/gogrid\"))\n         .iso3166Codes(\"US-CA\", \"US-VA\", \"NL-NH\")\n         .endpoint(\"https://api.gogrid.com/api\")\n         .defaultProperties(GoGridProviderMetadata.defaultProperties());\n      }\n\n      @Override\n      public GoGridProviderMetadata build() {\n         return new GoGridProviderMetadata(this);\n      }\n\n      @Override\n      public Builder fromProviderMetadata(ProviderMetadata in) {\n         super.fromProviderMetadata(in);\n         return this;\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/GoGridResponseException.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid;\n\nimport static java.lang.String.format;\n\nimport java.util.Set;\n\nimport org.jclouds.gogrid.domain.internal.ErrorResponse;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.javax.annotation.Nullable;\n\npublic class GoGridResponseException extends HttpResponseException {\n\n    private transient Set<ErrorResponse> errors;\n\n    public GoGridResponseException(HttpCommand command, HttpResponse response, Set<ErrorResponse> errors) {\n        super(buildMessage(command, response, errors), command, response);\n        this.setErrors(errors);\n    }\n\n    @Nullable\n    public Set<ErrorResponse> getError() {\n        return errors;\n    }\n\n    public void setErrors(Set<ErrorResponse> errors) {\n        this.errors = errors;\n    }\n\n    private static String buildMessage(HttpCommand command, HttpResponse response, Set<ErrorResponse> errors) {\n        StringBuilder builder = new StringBuilder();\n        builder.append(format(\"command %s failed with code %s. \", command.toString(),\n                response.getStatusCode()));\n        for (ErrorResponse error : errors) {\n            builder.append(format(\"Error [%s]: %s. \", error.getErrorCode(), error.getMessage()));\n        }\n        return builder.toString();\n    }\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/binders/BindIdsToQueryParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.binders;\n\nimport static com.google.common.base.Functions.toStringFunction;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.transform;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.ID_KEY;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.primitives.Longs;\n\n/**\n * Binds IDs to corresponding query parameters\n */\n@Singleton\npublic class BindIdsToQueryParams implements Binder {\n\n   /**\n    * Binds the ids to query parameters. The pattern, as specified by GoGrid's specification, is:\n    * \n    * https://api.gogrid.com/api/grid/server/get ?id=5153 &id=3232\n    * \n    * @param request\n    *           request where the query params will be set\n    * @param input\n    *           array of String params\n    */\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n\n      if (checkNotNull(input, \"input is null\") instanceof Long[]) {\n         Long[] names = (Long[]) input;\n         return (R) request.toBuilder()\n                  .replaceQueryParam(ID_KEY, transform(ImmutableList.copyOf(names), toStringFunction())).build();\n      } else if (input instanceof long[]) {\n         long[] names = (long[]) input;\n         return (R) request.toBuilder().replaceQueryParam(ID_KEY, transform(Longs.asList(names), toStringFunction()))\n                  .build();\n      } else {\n         throw new IllegalArgumentException(\"this binder is only valid for Long[] arguments: \" + input.getClass());\n      }\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/binders/BindNamesToQueryParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.NAME_KEY;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\n/**\n * Binds names to corresponding query parameters\n */\npublic class BindNamesToQueryParams implements Binder {\n\n   /**\n    * Binds the names to query parameters. The pattern, as specified by GoGrid's specification, is:\n    * \n    * https://api.gogrid.com/api/grid/server/get ?name=My+Server &name=My+Server+2 &name=My+Server+3\n    * &name=My+Server+4\n    * \n    * @param request\n    *           request where the query params will be set\n    * @param input\n    *           array of String params\n    */\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkArgument(checkNotNull(input, \"input is null\") instanceof String[],\n               \"this binder is only valid for String[] arguments\");\n      String[] names = (String[]) input;\n      return (R) request.toBuilder().replaceQueryParam(NAME_KEY, names).build();\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/binders/BindObjectNameToGetJobsRequestQueryParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.OBJECT_KEY;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\n/**\n * \n * @see org.jclouds.gogrid.features.GridJobApi#getJobsForObjectName(String)\n */\npublic class BindObjectNameToGetJobsRequestQueryParams implements Binder {\n\n   /**\n    * Maps the object's name to the input of <a\n    * href=\"http://wiki.gogrid.com/wiki/index.php/API:grid.job.list/>.\n    */\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkArgument(checkNotNull(input, \"input is null\") instanceof String,\n            \"this binder is only valid for String arguments\");\n\n      String serverName = (String) input;\n      return (R) request.toBuilder().replaceQueryParam(OBJECT_KEY, serverName).build();\n   }\n\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/binders/BindRealIpPortPairsToQueryParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.REAL_IP_LIST_KEY;\n\nimport java.util.List;\n\nimport org.jclouds.gogrid.domain.IpPortPair;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\nimport com.google.common.collect.ImmutableMultimap;\n\n/**\n * Binds a list of real IPs to the request.\n * \n * The {@link IpPortPair pairs} must have a {@link IpPortPair#ip} set with a valid IP address.\n */\npublic class BindRealIpPortPairsToQueryParams implements Binder {\n\n   @SuppressWarnings({ \"unchecked\" })\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkArgument(checkNotNull(input, \"input is null\") instanceof List,\n               \"this binder is only valid for a List argument\");\n\n      List<IpPortPair> ipPortPairs = (List<IpPortPair>) input;\n      ImmutableMultimap.Builder<String, String> builder = ImmutableMultimap.<String, String> builder();\n\n      int i = 0;\n      for (IpPortPair ipPortPair : ipPortPairs) {\n         checkNotNull(ipPortPair.getIp(), \"There must be an IP address defined\");\n         checkNotNull(ipPortPair.getIp().getIp(), \"There must be an IP address defined in Ip object\");\n         checkState(ipPortPair.getPort() > 0, \"The port number must be a positive integer\");\n\n         builder.put(REAL_IP_LIST_KEY + i + \".ip\", ipPortPair.getIp().getIp());\n         builder.put(REAL_IP_LIST_KEY + i + \".port\", String.valueOf(ipPortPair.getPort()));\n         i++;\n      }\n      return (R) request.toBuilder().replaceQueryParams(builder.build()).build();\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/binders/BindVirtualIpPortPairToQueryParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.VIRTUAL_IP_KEY;\n\nimport org.jclouds.gogrid.domain.IpPortPair;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.Binder;\n\nimport com.google.common.collect.ImmutableMultimap;\n\n/**\n * Binds a virtual IP to the request.\n * \n * The {@link IpPortPair} must have a {@link IpPortPair#ip} set with a valid IP address.\n */\npublic class BindVirtualIpPortPairToQueryParams implements Binder {\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkArgument(checkNotNull(input, \"input is null\") instanceof IpPortPair,\n               \"this binder is only valid for a IpPortPair argument\");\n\n      IpPortPair ipPortPair = (IpPortPair) input;\n\n      checkNotNull(ipPortPair.getIp(), \"There must be an IP address defined\");\n      checkNotNull(ipPortPair.getIp().getIp(), \"There must be an IP address defined in Ip object\");\n      checkState(ipPortPair.getPort() > 0, \"The port number must be a positive integer\");\n\n      ImmutableMultimap.Builder<String, String> builder = ImmutableMultimap.<String, String> builder();\n\n      builder.put(VIRTUAL_IP_KEY + \"ip\", ipPortPair.getIp().getIp());\n      builder.put(VIRTUAL_IP_KEY + \"port\", String.valueOf(ipPortPair.getPort()));\n      \n      return (R) request.toBuilder().replaceQueryParams(builder.build()).build();\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/compute/GoGridComputeService.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.compute;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_RUNNING;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_SUSPENDED;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_TERMINATED;\n\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Provider;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Constants;\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.compute.callables.RunScriptOnNode;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.TemplateBuilder;\nimport org.jclouds.compute.extensions.ImageExtension;\nimport org.jclouds.compute.extensions.SecurityGroupExtension;\nimport org.jclouds.compute.extensions.internal.DelegatingImageExtension;\nimport org.jclouds.compute.internal.BaseComputeService;\nimport org.jclouds.compute.internal.PersistNodeCredentials;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.compute.strategy.CreateNodesInGroupThenAddToSet;\nimport org.jclouds.compute.strategy.DestroyNodeStrategy;\nimport org.jclouds.compute.strategy.GetImageStrategy;\nimport org.jclouds.compute.strategy.GetNodeMetadataStrategy;\nimport org.jclouds.compute.strategy.InitializeRunScriptOnNodeOrPlaceInBadMap;\nimport org.jclouds.compute.strategy.ListNodesStrategy;\nimport org.jclouds.compute.strategy.RebootNodeStrategy;\nimport org.jclouds.compute.strategy.ResumeNodeStrategy;\nimport org.jclouds.compute.strategy.SuspendNodeStrategy;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.domain.Location;\nimport org.jclouds.gogrid.compute.options.GoGridTemplateOptions;\nimport org.jclouds.scriptbuilder.functions.InitAdminAccess;\n\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.util.concurrent.ListeningExecutorService;\n\n@Singleton\npublic class GoGridComputeService extends BaseComputeService {\n   @Inject\n   protected GoGridComputeService(ComputeServiceContext context, Map<String, Credentials> credentialStore,\n         @Memoized Supplier<Set<? extends Image>> images, @Memoized Supplier<Set<? extends Hardware>> hardwareProfiles,\n         @Memoized Supplier<Set<? extends Location>> locations, ListNodesStrategy listNodesStrategy,\n         GetImageStrategy getImageStrategy, GetNodeMetadataStrategy getNodeMetadataStrategy,\n         CreateNodesInGroupThenAddToSet runNodesAndAddToSetStrategy, RebootNodeStrategy rebootNodeStrategy,\n         DestroyNodeStrategy destroyNodeStrategy, ResumeNodeStrategy resumeNodeStrategy,\n         SuspendNodeStrategy suspendNodeStrategy, Provider<TemplateBuilder> templateBuilderProvider,\n         @Named(\"DEFAULT\") Provider<TemplateOptions> templateOptionsProvider,\n         @Named(TIMEOUT_NODE_RUNNING) Predicate<AtomicReference<NodeMetadata>> nodeRunning,\n         @Named(TIMEOUT_NODE_TERMINATED) Predicate<AtomicReference<NodeMetadata>> nodeTerminated,\n         @Named(TIMEOUT_NODE_SUSPENDED) Predicate<AtomicReference<NodeMetadata>> nodeSuspended,\n         InitializeRunScriptOnNodeOrPlaceInBadMap.Factory initScriptRunnerFactory, InitAdminAccess initAdminAccess,\n         RunScriptOnNode.Factory runScriptOnNodeFactory, PersistNodeCredentials persistNodeCredentials,\n         @Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor,\n         Optional<ImageExtension> imageExtension, Optional<SecurityGroupExtension> securityGroupExtension,\n         DelegatingImageExtension.Factory delegatingImageExtension) {\n      super(context, credentialStore, images, hardwareProfiles, locations, listNodesStrategy, getImageStrategy,\n            getNodeMetadataStrategy, runNodesAndAddToSetStrategy, rebootNodeStrategy, destroyNodeStrategy,\n            resumeNodeStrategy, suspendNodeStrategy, templateBuilderProvider, templateOptionsProvider, nodeRunning,\n            nodeTerminated, nodeSuspended, initScriptRunnerFactory, initAdminAccess, runScriptOnNodeFactory,\n            persistNodeCredentials, userExecutor, imageExtension, securityGroupExtension, delegatingImageExtension);\n   }\n\n   /**\n    * Returns template options, except of type {@link GoGridTemplateOptions}.\n    */\n   @Override\n   public GoGridTemplateOptions templateOptions() {\n      return GoGridTemplateOptions.class.cast(super.templateOptions());\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/compute/config/GoGridComputeServiceContextModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.compute.config;\n\nimport static org.jclouds.compute.util.ComputeServiceUtils.getCores;\nimport static org.jclouds.compute.util.ComputeServiceUtils.getSpace;\n\nimport java.util.Map;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.ComputeServiceAdapter;\nimport org.jclouds.compute.config.ComputeServiceAdapterContextModule;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadata.Status;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.domain.Location;\nimport org.jclouds.functions.IdentityFunction;\nimport org.jclouds.gogrid.compute.functions.OptionToLocation;\nimport org.jclouds.gogrid.compute.functions.ServerImageToImage;\nimport org.jclouds.gogrid.compute.functions.ServerToNodeMetadata;\nimport org.jclouds.gogrid.compute.options.GoGridTemplateOptions;\nimport org.jclouds.gogrid.compute.strategy.GoGridComputeServiceAdapter;\nimport org.jclouds.gogrid.domain.Option;\nimport org.jclouds.gogrid.domain.Server;\nimport org.jclouds.gogrid.domain.ServerImage;\nimport org.jclouds.gogrid.domain.ServerImageState;\nimport org.jclouds.gogrid.domain.ServerState;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.inject.Provides;\nimport com.google.inject.TypeLiteral;\n\npublic class GoGridComputeServiceContextModule extends\n         ComputeServiceAdapterContextModule<Server, Hardware, ServerImage, Option> {\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   protected void configure() {\n      super.configure();\n      bind(new TypeLiteral<ComputeServiceAdapter<Server, Hardware, ServerImage, Option>>() {\n      }).to(GoGridComputeServiceAdapter.class);\n\n      bind(new TypeLiteral<Function<Server, NodeMetadata>>() {\n      }).to(ServerToNodeMetadata.class);\n\n      bind(new TypeLiteral<Function<ServerImage, Image>>() {\n      }).to(ServerImageToImage.class);\n\n      bind(new TypeLiteral<Function<Option, Location>>() {\n      }).to(OptionToLocation.class);\n\n      // we aren't converting hardware from a provider-specific type\n      bind(new TypeLiteral<Function<Hardware, Hardware>>() {\n      }).to(Class.class.cast(IdentityFunction.class));\n\n      bind(TemplateOptions.class).to(GoGridTemplateOptions.class);\n      \n      // to have the compute service adapter override default locations\n      install(new LocationsFromComputeServiceAdapterModule<Server, Hardware, ServerImage, Option>(){});\n   }\n\n   @VisibleForTesting\n   static final Map<ServerState, Status> toPortableNodeStatus = ImmutableMap.<ServerState, Status> builder()\n            .put(ServerState.ON, Status.RUNNING)\n            .put(ServerState.STARTING, Status.PENDING)\n            .put(ServerState.OFF, Status.SUSPENDED)\n            .put(ServerState.STOPPING, Status.PENDING)\n            .put(ServerState.RESTARTING, Status.PENDING)\n            .put(ServerState.SAVING, Status.PENDING)\n            .put(ServerState.UNRECOGNIZED, Status.UNRECOGNIZED)\n            .put(ServerState.RESTORING, Status.PENDING)\n            .put(ServerState.UPDATING, Status.PENDING).build();\n\n   @Singleton\n   @Provides\n   final Map<ServerState, Status> toPortableNodeStatus() {\n      return toPortableNodeStatus;\n   }\n   \n   @VisibleForTesting\n   static final Map<ServerImageState, Image.Status> toPortableImageStatus = ImmutableMap\n            .<ServerImageState, Image.Status> builder()\n            .put(ServerImageState.AVAILABLE, Image.Status.AVAILABLE)\n            .put(ServerImageState.SAVING, Image.Status.PENDING)\n            .put(ServerImageState.TRASH, Image.Status.DELETED)\n            .put(ServerImageState.UNRECOGNIZED, Image.Status.UNRECOGNIZED).build();\n\n   @Singleton\n   @Provides\n   final Map<ServerImageState, Image.Status> toPortableImageStatus() {\n      return toPortableImageStatus;\n   }\n   \n   /**\n    * Finds matches to required configurations. GoGrid's documentation only specifies how much RAM\n    * one can get with different instance types. The # of cores and disk sizes are purely empirical\n    * and aren't guaranteed. However, these are the matches found: Ram: 512MB, CPU: 1 core, HDD: 28\n    * GB Ram: 1GB, CPU: 1 core, HDD: 57 GB Ram: 2GB, CPU: 1 core, HDD: 113 GB Ram: 4GB, CPU: 3\n    * cores, HDD: 233 GB Ram: 8GB, CPU: 6 cores, HDD: 462 GB (as of March 2010)\n    * \n    * @return matched size\n    */\n   @Singleton\n   @Provides\n   final Function<Hardware, String> provideSizeToRam() {\n      return new Function<Hardware, String>() {\n         @Override\n         public String apply(Hardware hardware) {\n            if (hardware.getRam() >= 8 * 1024 || getCores(hardware) >= 6 || getSpace(hardware) >= 450)\n               return \"8GB\";\n            if (hardware.getRam() >= 4 * 1024 || getCores(hardware) >= 3 || getSpace(hardware) >= 230)\n               return \"4GB\";\n            if (hardware.getRam() >= 2 * 1024 || getSpace(hardware) >= 110)\n               return \"2GB\";\n            if (hardware.getRam() >= 1024 || getSpace(hardware) >= 55)\n               return \"1GB\";\n            return \"512MB\"; /* smallest */\n         }\n      };\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/compute/functions/OptionToLocation.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.compute.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.gogrid.domain.Option;\nimport org.jclouds.location.Iso3166;\nimport org.jclouds.location.suppliers.all.JustProvider;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.Iterables;\n\n@Singleton\npublic class OptionToLocation implements Function<Option, Location> {\n   private final Location provider;\n   private final Supplier<Map<String, Supplier<Set<String>>>> isoCodesByIdSupplier;\n\n   @Inject\n   OptionToLocation(JustProvider justProvider,\n            @Iso3166 Supplier<Map<String, Supplier<Set<String>>>> isoCodesByIdSupplier) {\n      this.provider = Iterables.getOnlyElement(justProvider.get());\n      this.isoCodesByIdSupplier = checkNotNull(isoCodesByIdSupplier, \"isoCodesByIdSupplier\");\n   }\n\n   @Override\n   public Location apply(Option from) {\n      LocationBuilder builder = new LocationBuilder().scope(LocationScope.ZONE).id(from.getId() + \"\").description(\n               from.getDescription()).parent(provider);\n      Map<String, Supplier<Set<String>>> isoCodesById = isoCodesByIdSupplier.get();\n      if (isoCodesById.containsKey(from.getId() + \"\"))\n         builder.iso3166Codes(isoCodesById.get(from.getId() + \"\").get());\n      return builder.build();\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/compute/functions/ServerImageToImage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.compute.functions;\n\nimport java.util.Map;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.ImageBuilder;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.Image.Status;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.compute.util.ComputeServiceUtils;\nimport org.jclouds.gogrid.domain.ServerImage;\nimport org.jclouds.gogrid.domain.ServerImageState;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class ServerImageToImage implements Function<ServerImage, Image> {\n   public static final Pattern GOGRID_OS_PATTERN = Pattern.compile(\"([a-zA-Z]*).*\");\n   public static final Pattern GOGRID_VERSION_PATTERN = Pattern.compile(\".* ([0-9.]+) .*\");\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n   \n   private final Map<ServerImageState, Status> toPortableImageStatus;\n   private final Map<OsFamily, Map<String, String>> osVersionMap;\n\n   @Inject\n   ServerImageToImage(Map<ServerImageState, Image.Status> toPortableImageStatus,\n            Map<OsFamily, Map<String, String>> osVersionMap) {\n      this.toPortableImageStatus = toPortableImageStatus;\n      this.osVersionMap = osVersionMap;\n   }\n\n   protected OperatingSystem parseOs(ServerImage from) {\n      OsFamily osFamily = null;\n      String osName = from.getOs().getName();\n      String osArch = from.getArchitecture().getDescription();\n      String osVersion = null;\n      String osDescription = from.getOs().getDescription();\n      boolean is64Bit = from.getOs().getName().indexOf(\"64\") != -1 || from.getDescription().indexOf(\"64\") != -1;\n\n      if (osName.startsWith(\"Windows\")) {\n         osFamily = OsFamily.WINDOWS;\n      } else {\n         Matcher matcher = GOGRID_OS_PATTERN.matcher(from.getName());\n         if (matcher.find()) {\n            try {\n               osFamily = OsFamily.fromValue(matcher.group(1).toLowerCase());\n            } catch (IllegalArgumentException e) {\n               logger.debug(\"<< didn't match os(%s)\", from.getName());\n            }\n         }\n      }\n      Matcher matcher = GOGRID_VERSION_PATTERN.matcher(osName);\n      if (matcher.find()) {\n         osVersion = ComputeServiceUtils.parseVersionOrReturnEmptyString(osFamily, matcher.group(1), osVersionMap);\n      }\n      // TODO determine DC images are in\n      return new OperatingSystem(osFamily, osName, osVersion, osArch, osDescription, is64Bit);\n   }\n\n   @Override\n   public Image apply(ServerImage from) {\n      ImageBuilder builder = new ImageBuilder();\n      builder.ids(from.getId() + \"\");\n      builder.name(from.getFriendlyName());\n      builder.description(from.getDescription());\n      builder.operatingSystem(parseOs(from));\n      builder.status(toPortableImageStatus.get(from.getState()));\n      return builder.build();\n   }\n\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/compute/functions/ServerToNodeMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.compute.functions;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\nimport java.util.NoSuchElementException;\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadataBuilder;\nimport org.jclouds.compute.domain.NodeMetadata.Status;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.domain.Location;\nimport org.jclouds.gogrid.domain.Server;\nimport org.jclouds.gogrid.domain.ServerState;\nimport org.jclouds.location.predicates.LocationPredicates;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\n\n@Singleton\npublic class ServerToNodeMetadata implements Function<Server, NodeMetadata> {\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n   private final Map<ServerState, Status> serverStateToNodeStatus;\n   private final Supplier<Set<? extends Image>> images;\n   private final Supplier<Set<? extends Hardware>> hardwares;\n   private final Supplier<Set<? extends Location>> locations;\n   private final GroupNamingConvention nodeNamingConvention;\n\n   static class FindImageForServer implements Predicate<Image> {\n      private final Server instance;\n\n      @Inject\n      private FindImageForServer(Server instance) {\n         this.instance = instance;\n      }\n\n      @Override\n      public boolean apply(Image input) {\n         return input.getProviderId().equals(instance.getImage().getId() + \"\")\n                  && (input.getLocation() == null || input.getLocation().getId().equals(\n                           instance.getDatacenter().getId() + \"\"));\n      }\n   }\n\n   static class FindHardwareForServer implements Predicate<Hardware> {\n      private final Server instance;\n\n      @Inject\n      private FindHardwareForServer(Server instance) {\n         this.instance = instance;\n      }\n\n      @Override\n      public boolean apply(Hardware input) {\n         return input.getRam() == Integer.parseInt(instance.getRam().getName().replaceAll(\"[^0-9]\", \"\"));\n      }\n   }\n\n   @Inject\n   ServerToNodeMetadata(Map<ServerState, Status> serverStateToNodeStatus,\n         @Memoized Supplier<Set<? extends Image>> images, @Memoized Supplier<Set<? extends Hardware>> hardwares,\n         @Memoized Supplier<Set<? extends Location>> locations,\n         GroupNamingConvention.Factory namingConvention) {\n      this.nodeNamingConvention = checkNotNull(namingConvention, \"namingConvention\").createWithoutPrefix();\n      this.serverStateToNodeStatus = checkNotNull(serverStateToNodeStatus, \"serverStateToNodeStatus\");\n      this.images = checkNotNull(images, \"images\");\n      this.hardwares = checkNotNull(hardwares, \"hardwares\");\n      this.locations = checkNotNull(locations, \"locations\");\n   }\n\n   @Override\n   public NodeMetadata apply(Server from) {\n      NodeMetadataBuilder builder = new NodeMetadataBuilder();\n      builder.ids(from.getId() + \"\");\n      builder.name(from.getName());\n      Location location = Iterables.find(locations.get(), LocationPredicates.idEquals(from.getDatacenter().getId() + \"\"));\n      builder.location(location);\n      builder.group(nodeNamingConvention.groupInUniqueNameOrNull(from.getName()));\n      builder.hardware(parseHardware(from));\n      builder.imageId(from.getImage().getId() + \"\");\n\n      Image image = parseImage(from);\n      if (image != null)\n         builder.operatingSystem(image.getOperatingSystem());\n\n      builder.status(serverStateToNodeStatus.get(from.getState()));\n      builder.publicAddresses(ImmutableSet.of(from.getIp().getIp()));\n      return builder.build();\n   }\n\n   protected Image parseImage(Server from) {\n      Image image = null;\n      try {\n         image = Iterables.find(images.get(), new FindImageForServer(from));\n      } catch (NoSuchElementException e) {\n         logger.debug(\"could not find a matching image for server %s\", from);\n      }\n      return image;\n   }\n\n   protected Hardware parseHardware(Server from) {\n      Hardware hardware = null;\n      try {\n         hardware = Iterables.find(hardwares.get(), new FindHardwareForServer(from));\n      } catch (NoSuchElementException e) {\n         logger.debug(\"could not find a matching hardware for server %s\", from);\n      }\n      return hardware;\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/compute/options/GoGridTemplateOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.compute.options;\n\nimport java.util.Map;\n\nimport org.jclouds.compute.options.TemplateOptions;\n\n/**\n * Contains options supported by the\n * {@link ComputeService#createNodesInGroup(String, int, TemplateOptions)} and\n * {@link ComputeService#createNodesInGroup(String, int, TemplateOptions)}\n * operations on the <em>gogrid</em> provider.\n * \n * <h2>Usage</h2> The recommended way to instantiate a\n * {@link GoGridTemplateOptions} object is to statically import\n * {@code GoGridTemplateOptions.*} and invoke a static creation method followed\n * by an instance mutator (if needed):\n * <p>\n * \n * <pre>\n * import static org.jclouds.compute.options.GoGridTemplateOptions.Builder.*;\n * ComputeService client = // get connection\n * templateBuilder.options(inboundPorts(22, 80, 8080, 443));\n * Set&lt;? extends NodeMetadata&gt; set = client.createNodesInGroup(tag, 2, templateBuilder.build());\n * </pre>\n * \n * TODO add GoGrid specific options\n */\npublic class GoGridTemplateOptions extends TemplateOptions implements Cloneable {\n   @Override\n   public GoGridTemplateOptions clone() {\n      GoGridTemplateOptions options = new GoGridTemplateOptions();\n      copyTo(options);\n      return options;\n   }\n\n   @Override\n   public void copyTo(TemplateOptions to) {\n      super.copyTo(to);\n   }\n\n   public static final GoGridTemplateOptions NONE = new GoGridTemplateOptions();\n\n   public static class Builder {\n      // methods that only facilitate returning the correct object type\n\n      /**\n       * @see TemplateOptions#inboundPorts(int...)\n       */\n      public static GoGridTemplateOptions inboundPorts(int... ports) {\n         GoGridTemplateOptions options = new GoGridTemplateOptions();\n         return GoGridTemplateOptions.class.cast(options.inboundPorts(ports));\n      }\n\n      /**\n       * @see TemplateOptions#blockOnPort(int, int)\n       */\n      public static GoGridTemplateOptions blockOnPort(int port, int seconds) {\n         GoGridTemplateOptions options = new GoGridTemplateOptions();\n         return GoGridTemplateOptions.class.cast(options.blockOnPort(port, seconds));\n      }\n\n      /**\n       * @see TemplateOptions#userMetadata(Map)\n       */\n      public static GoGridTemplateOptions userMetadata(Map<String, String> userMetadata) {\n         GoGridTemplateOptions options = new GoGridTemplateOptions();\n         return GoGridTemplateOptions.class.cast(options.userMetadata(userMetadata));\n      }\n\n      /**\n       * @see TemplateOptions#userMetadata(String, String)\n       */\n      public static GoGridTemplateOptions userMetadata(String key, String value) {\n         GoGridTemplateOptions options = new GoGridTemplateOptions();\n         return GoGridTemplateOptions.class.cast(options.userMetadata(key, value));\n      }\n\n      /**\n       * @see TemplateOptions#nodeNames(Iterable)\n       */\n      public static GoGridTemplateOptions nodeNames(Iterable<String> nodeNames) {\n         GoGridTemplateOptions options = new GoGridTemplateOptions();\n         return GoGridTemplateOptions.class.cast(options.nodeNames(nodeNames));\n      }\n\n      /**\n       * @see TemplateOptions#networks(Iterable)\n       */\n      public static GoGridTemplateOptions networks(Iterable<String> networks) {\n         GoGridTemplateOptions options = new GoGridTemplateOptions();\n         return GoGridTemplateOptions.class.cast(options.networks(networks));\n      }\n   }\n\n   // methods that only facilitate returning the correct object type\n\n   /**\n    * @see TemplateOptions#blockOnPort(int, int)\n    */\n   @Override\n   public GoGridTemplateOptions blockOnPort(int port, int seconds) {\n      return GoGridTemplateOptions.class.cast(super.blockOnPort(port, seconds));\n   }\n\n   /**\n    * @see TemplateOptions#inboundPorts(int...)\n    */\n   @Override\n   public GoGridTemplateOptions inboundPorts(int... ports) {\n      return GoGridTemplateOptions.class.cast(super.inboundPorts(ports));\n   }\n\n   /**\n    * @see TemplateOptions#authorizePublicKey(String)\n    */\n   @Override\n   public GoGridTemplateOptions authorizePublicKey(String publicKey) {\n      return GoGridTemplateOptions.class.cast(super.authorizePublicKey(publicKey));\n   }\n\n   /**\n    * @see TemplateOptions#installPrivateKey(String)\n    */\n   @Override\n   public GoGridTemplateOptions installPrivateKey(String privateKey) {\n      return GoGridTemplateOptions.class.cast(super.installPrivateKey(privateKey));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public GoGridTemplateOptions userMetadata(Map<String, String> userMetadata) {\n      return GoGridTemplateOptions.class.cast(super.userMetadata(userMetadata));\n   }\n   \n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public GoGridTemplateOptions userMetadata(String key, String value) {\n      return GoGridTemplateOptions.class.cast(super.userMetadata(key, value));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public GoGridTemplateOptions nodeNames(Iterable<String> nodeNames) {\n      return GoGridTemplateOptions.class.cast(super.nodeNames(nodeNames));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public GoGridTemplateOptions networks(Iterable<String> networks) {\n      return GoGridTemplateOptions.class.cast(super.networks(networks));\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/compute/strategy/GoGridComputeServiceAdapter.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.compute.strategy;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.util.Predicates2.retry;\n\nimport java.security.SecureRandom;\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.ComputeServiceAdapter;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.reference.ComputeServiceConstants.Timeouts;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.gogrid.GoGridApi;\nimport org.jclouds.gogrid.compute.suppliers.GoGridHardwareSupplier;\nimport org.jclouds.gogrid.domain.Ip;\nimport org.jclouds.gogrid.domain.IpType;\nimport org.jclouds.gogrid.domain.Option;\nimport org.jclouds.gogrid.domain.PowerCommand;\nimport org.jclouds.gogrid.domain.Server;\nimport org.jclouds.gogrid.domain.ServerImage;\nimport org.jclouds.gogrid.options.GetIpListOptions;\nimport org.jclouds.gogrid.predicates.ServerLatestJobCompleted;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Throwables;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.Iterables;\nimport com.google.common.primitives.Longs;\n\n/**\n * defines the connection between the {@link org.jclouds.gogrid.GoGridApi} implementation and the jclouds\n * {@link ComputeService}\n */\n@Singleton\npublic class GoGridComputeServiceAdapter implements ComputeServiceAdapter<Server, Hardware, ServerImage, Option> {\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   private final GoGridApi client;\n   private final Function<Hardware, String> sizeToRam;\n   private final Predicate<Server> serverLatestJobCompleted;\n   private final Predicate<Server> serverLatestJobCompletedShort;\n\n   @Inject\n   protected GoGridComputeServiceAdapter(GoGridApi client, Function<Hardware, String> sizeToRam, Timeouts timeouts) {\n      this.client = checkNotNull(client, \"client\");\n      this.sizeToRam = checkNotNull(sizeToRam, \"sizeToRam\");\n      this.serverLatestJobCompleted = retry(new ServerLatestJobCompleted(client.getJobServices()),\n            timeouts.nodeRunning * 9L / 10L);\n      this.serverLatestJobCompletedShort = retry(new ServerLatestJobCompleted(client.getJobServices()),\n            timeouts.nodeRunning * 1L / 10L);\n   }\n\n   @Override\n   public NodeAndInitialCredentials<Server> createNodeWithGroupEncodedIntoName(String group, String name,\n            Template template) {\n      Server addedServer = null;\n      boolean notStarted = true;\n      int numOfRetries = 20;\n      GetIpListOptions unassignedIps = new GetIpListOptions().onlyUnassigned().inDatacenter(\n               template.getLocation().getId()).onlyWithType(IpType.PUBLIC);\n      // lock-free consumption of a shared resource: IP address pool\n      while (notStarted) { // TODO: replace with Predicate-based thread\n         // collision avoidance for simplicity\n         Set<Ip> availableIps = client.getIpServices().getIpList(unassignedIps);\n         if (availableIps.isEmpty())\n            throw new RuntimeException(\"No IPs available on this identity.\");\n         int ipIndex = new SecureRandom().nextInt(availableIps.size());\n         Ip availableIp = Iterables.get(availableIps, ipIndex);\n         try {\n            addedServer = addServer(name, template, availableIp);\n            notStarted = false;\n         } catch (Exception e) {\n            if (--numOfRetries == 0)\n               Throwables.propagate(e);\n            notStarted = true;\n         }\n      }\n      if (template.getOptions().shouldBlockUntilRunning()) {\n         serverLatestJobCompleted.apply(addedServer);\n         client.getServerServices().power(addedServer.getName(), PowerCommand.START);\n         serverLatestJobCompletedShort.apply(addedServer);\n         addedServer = Iterables.getOnlyElement(client.getServerServices().getServersByName(addedServer.getName()));\n      }\n      LoginCredentials credentials = LoginCredentials.fromCredentials(client.getServerServices()\n               .getServerCredentialsList().get(addedServer.getName()));\n      return new NodeAndInitialCredentials<Server>(addedServer, addedServer.getId() + \"\", credentials);\n   }\n\n   private Server addServer(String name, Template template, Ip availableIp) {\n      Server addedServer = client.getServerServices().addServer(name,\n               checkNotNull(template.getImage().getProviderId()), sizeToRam.apply(template.getHardware()),\n               availableIp.getIp());\n      return addedServer;\n   }\n\n   @Override\n   public Iterable<Hardware> listHardwareProfiles() {\n      return GoGridHardwareSupplier.H_ALL;\n\n   }\n\n   @Override\n   public Iterable<ServerImage> listImages() {\n      return client.getImageServices().getImageList();\n   }\n\n   @Override\n   public Iterable<Server> listNodes() {\n      return client.getServerServices().getServerList();\n   }\n\n   @Override\n   public Iterable<Server> listNodesByIds(final Iterable<String> ids) {\n      Set<Long> idsAsLongs = FluentIterable.from(ids)\n         .transform(toLong())\n         .toSet();\n                  \n      return client.getServerServices().getServersById(Longs.toArray(idsAsLongs));\n   }\n\n   @Override\n   public Iterable<Option> listLocations() {\n      return client.getServerServices().getDatacenters();\n   }\n\n   @Override\n   public Server getNode(String id) {\n      return Iterables.getOnlyElement(client.getServerServices().getServersById(Long.parseLong(checkNotNull(id, \"id\"))),\n               null);\n   }\n\n   @Override\n   public ServerImage getImage(String id) {\n      return Iterables.getOnlyElement(client.getImageServices().getImagesById(Long.parseLong(checkNotNull(id, \"id\"))),\n               null);\n   }\n   \n   @Override\n   public void destroyNode(String id) {\n      client.getServerServices().deleteById(Long.parseLong(id));\n   }\n\n   @Override\n   public void rebootNode(String id) {\n      executeCommandOnServer(PowerCommand.RESTART, id);\n      Server server = Iterables.getOnlyElement(client.getServerServices().getServersById(Long.parseLong(id)));\n      client.getServerServices().power(server.getName(), PowerCommand.START);\n      serverLatestJobCompletedShort.apply(server);\n   }\n\n   private boolean executeCommandOnServer(PowerCommand command, String id) {\n      Server server = Iterables.getOnlyElement(client.getServerServices().getServersById(Long.parseLong(id)));\n      client.getServerServices().power(server.getName(), command);\n      return serverLatestJobCompleted.apply(server);\n   }\n\n   @Override\n   public void resumeNode(String id) {\n      executeCommandOnServer(PowerCommand.START, id);\n   }\n\n   @Override\n   public void suspendNode(String id) {\n      executeCommandOnServer(PowerCommand.STOP, id);\n   }\n\n   private Function<String, Long> toLong() {\n      return new Function<String, Long>() {\n\n         @Override\n         public Long apply(String id) {\n            return Long.valueOf(checkNotNull(id, \"id\"));\n         }\n      };\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/compute/suppliers/GoGridHardwareSupplier.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.compute.suppliers;\n\nimport java.util.Set;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.HardwareBuilder;\nimport org.jclouds.compute.domain.Processor;\nimport org.jclouds.compute.domain.Volume;\nimport org.jclouds.compute.domain.internal.VolumeImpl;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\n\n@Singleton\npublic class GoGridHardwareSupplier implements Supplier<Set<? extends Hardware>> {\n   public static final Hardware H16384 = new HardwareBuilder().ids(\"6\").ram(16384)\n         .processors(ImmutableList.of(new Processor(16, 1.0)))\n         .volumes(ImmutableList.<Volume> of(new VolumeImpl(800.0f, true, true))).build();\n   public static final Hardware H8192 = new HardwareBuilder().ids(\"5\").ram(8192)\n         .processors(ImmutableList.of(new Processor(8, 1.0)))\n         .volumes(ImmutableList.<Volume> of(new VolumeImpl(400.0f, true, true))).build();\n   public static final Hardware H4096 = new HardwareBuilder().ids(\"4\").ram(4096)\n         .processors(ImmutableList.of(new Processor(4, 1.0)))\n         .volumes(ImmutableList.<Volume> of(new VolumeImpl(200.0f, true, true))).build();\n   public static final Hardware H2048 = new HardwareBuilder().ids(\"3\").ram(2048)\n         .processors(ImmutableList.of(new Processor(2, 1.0)))\n         .volumes(ImmutableList.<Volume> of(new VolumeImpl(100.0f, true, true))).build();\n   public static final Hardware H1024 = new HardwareBuilder().ids(\"2\").ram(1024)\n         .processors(ImmutableList.of(new Processor(1, 1.0)))\n         .volumes(ImmutableList.<Volume> of(new VolumeImpl(50.0f, true, true))).build();\n   public static final Hardware H512 = new HardwareBuilder().ids(\"1\").ram(512)\n         .processors(ImmutableList.of(new Processor(0.5, 1.0)))\n         .volumes(ImmutableList.<Volume> of(new VolumeImpl(25.0f, true, true))).build();\n\n   public static final ImmutableSet<Hardware> H_ALL = ImmutableSet.of(H512, H1024, H2048, H4096, H8192, H16384);\n\n   @Override\n   public Set<? extends Hardware> get() {\n      return H_ALL;\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/config/GoGridHttpApiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.config;\n\nimport static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL;\n\nimport java.util.concurrent.TimeUnit;\n\nimport jakarta.inject.Named;\n\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.gogrid.GoGridApi;\nimport org.jclouds.gogrid.handlers.GoGridErrorHandler;\nimport org.jclouds.gogrid.location.GoGridDefaultLocationSupplier;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.annotation.ClientError;\nimport org.jclouds.http.annotation.Redirection;\nimport org.jclouds.http.annotation.ServerError;\nimport org.jclouds.location.suppliers.ImplicitLocationSupplier;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.config.HttpApiModule;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.inject.Provides;\nimport com.google.inject.Scopes;\n\n/**\n * Configures the GoGrid connection.\n */\n@ConfiguresHttpApi\npublic class GoGridHttpApiModule extends HttpApiModule<GoGridApi> {\n\n   @Provides\n   @TimeStamp\n   protected final Long guiceProvideTimeStamp(@TimeStamp Supplier<Long> cache) {\n      return provideTimeStamp(cache);\n   }\n\n   protected Long provideTimeStamp(@TimeStamp Supplier<Long> cache) {\n      return cache.get();\n   }\n\n   /**\n    * borrowing concurrency code to ensure that caching takes place properly\n    */\n   @Provides\n   @TimeStamp\n   final Supplier<Long> provideTimeStampCache(@Named(PROPERTY_SESSION_INTERVAL) long seconds) {\n      return Suppliers.memoizeWithExpiration(new Supplier<Long>() {\n         @Override\n         public Long get() {\n            return System.currentTimeMillis() / 1000;\n         }\n      }, seconds, TimeUnit.SECONDS);\n   }\n\n   @Override\n   protected void bindErrorHandlers() {\n      bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(GoGridErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(GoGridErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(GoGridErrorHandler.class);\n   }\n\n   @Override\n   protected void configure() {\n      install(new GoGridParserModule());\n      super.configure();\n   }\n\n   @Override\n   protected void installLocations() {\n      super.installLocations();\n      bind(ImplicitLocationSupplier.class).to(GoGridDefaultLocationSupplier.class).in(Scopes.SINGLETON);\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/config/GoGridParserModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.config;\n\nimport java.lang.reflect.Type;\nimport java.util.Map;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.gogrid.domain.IpState;\nimport org.jclouds.gogrid.domain.JobState;\nimport org.jclouds.gogrid.domain.LoadBalancerOs;\nimport org.jclouds.gogrid.domain.LoadBalancerPersistenceType;\nimport org.jclouds.gogrid.domain.LoadBalancerState;\nimport org.jclouds.gogrid.domain.LoadBalancerType;\nimport org.jclouds.gogrid.domain.ObjectType;\nimport org.jclouds.gogrid.domain.ServerImageState;\nimport org.jclouds.gogrid.domain.ServerImageType;\nimport org.jclouds.gogrid.domain.ServerState;\nimport org.jclouds.gogrid.functions.internal.CustomDeserializers;\nimport org.jclouds.json.config.GsonModule.DateAdapter;\nimport org.jclouds.json.config.GsonModule.LongDateAdapter;\n\nimport com.google.common.collect.Maps;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Provides;\n\n/**\n * Configures the GoGrid connection.\n */\n\npublic class GoGridParserModule extends AbstractModule {\n\n   @Provides\n   @Singleton\n   public final Map<Type, Object> provideCustomAdapterBindings() {\n      Map<Type, Object> bindings = Maps.newHashMap();\n      bindings.put(ObjectType.class, new CustomDeserializers.ObjectTypeAdapter());\n      bindings.put(LoadBalancerOs.class, new CustomDeserializers.LoadBalancerOsAdapter());\n      bindings.put(LoadBalancerState.class, new CustomDeserializers.LoadBalancerStateAdapter());\n      bindings.put(LoadBalancerPersistenceType.class, new CustomDeserializers.LoadBalancerPersistenceTypeAdapter());\n      bindings.put(LoadBalancerType.class, new CustomDeserializers.LoadBalancerTypeAdapter());\n      bindings.put(ServerState.class, new CustomDeserializers.ServerStateAdapter());\n      bindings.put(IpState.class, new CustomDeserializers.IpStateAdapter());\n      bindings.put(JobState.class, new CustomDeserializers.JobStateAdapter());\n      bindings.put(ServerImageState.class, new CustomDeserializers.ServerImageStateAdapter());\n      bindings.put(ServerImageType.class, new CustomDeserializers.ServerImageTypeAdapter());\n      return bindings;\n   }\n\n   @Override\n   protected void configure() {\n      bind(DateAdapter.class).to(LongDateAdapter.class);\n   }\n\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/domain/BillingToken.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.primitives.Longs;\n\n/**\n * Class BillingToken\n * \n*/\npublic class BillingToken implements Comparable<BillingToken> {\n\n   public static Builder<?> builder() { \n      return new ConcreteBuilder();\n   }\n   \n   public Builder<?> toBuilder() { \n      return new ConcreteBuilder().fromBillingToken(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>>  {\n      protected abstract T self();\n\n      protected long id;\n      protected String name;\n      protected double price;\n   \n      /** \n       * @see BillingToken#getId()\n       */\n      public T id(long id) {\n         this.id = id;\n         return self();\n      }\n\n      /** \n       * @see BillingToken#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /** \n       * @see BillingToken#getPrice()\n       */\n      public T price(double price) {\n         this.price = price;\n         return self();\n      }\n\n      public BillingToken build() {\n         return new BillingToken(id, name, price);\n      }\n      \n      public T fromBillingToken(BillingToken in) {\n         return this\n                  .id(in.getId())\n                  .name(in.getName())\n                  .price(in.getPrice());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final long id;\n   private final String name;\n   private final double price;\n\n   @ConstructorProperties({\n      \"id\", \"name\", \"price\"\n   })\n   protected BillingToken(long id, String name, double price) {\n      this.id = id;\n      this.name = checkNotNull(name, \"name\");\n      this.price = price;\n   }\n\n   public long getId() {\n      return this.id;\n   }\n\n   public String getName() {\n      return this.name;\n   }\n\n   public double getPrice() {\n      return this.price;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, name, price);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      BillingToken that = BillingToken.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n               && Objects.equal(this.name, that.name)\n               && Objects.equal(this.price, that.price);\n   }\n   \n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"name\", name).add(\"price\", price);\n   }\n   \n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int compareTo(BillingToken o) {\n      return Longs.compare(id, o.getId());\n   }\n\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/domain/Customer.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * Class Customer\n * \n*/\npublic class Customer {\n\n   public static Builder<?> builder() { \n      return new ConcreteBuilder();\n   }\n   \n   public Builder<?> toBuilder() { \n      return new ConcreteBuilder().fromCustomer(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>>  {\n      protected abstract T self();\n\n      protected long id;\n      protected String name;\n   \n      /** \n       * @see Customer#getId()\n       */\n      public T id(long id) {\n         this.id = id;\n         return self();\n      }\n\n      /** \n       * @see Customer#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      public Customer build() {\n         return new Customer(id, name);\n      }\n      \n      public T fromCustomer(Customer in) {\n         return this\n                  .id(in.getId())\n                  .name(in.getName());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final long id;\n   private final String name;\n\n   @ConstructorProperties({\n      \"id\", \"name\"\n   })\n   protected Customer(long id, String name) {\n      this.id = id;\n      this.name = checkNotNull(name, \"name\");\n   }\n\n   public long getId() {\n      return this.id;\n   }\n\n   public String getName() {\n      return this.name;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, name);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Customer that = Customer.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n               && Objects.equal(this.name, that.name);\n   }\n   \n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"name\", name);\n   }\n   \n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/domain/Ip.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.primitives.Longs;\n\n/**\n * Class Ip\n * \n*/\npublic class Ip implements Comparable<Ip> {\n\n   public static Builder<?> builder() { \n      return new ConcreteBuilder();\n   }\n   \n   public Builder<?> toBuilder() { \n      return new ConcreteBuilder().fromIp(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>>  {\n      protected abstract T self();\n\n      protected long id;\n      protected String ip;\n      protected String subnet;\n      protected boolean isPublic;\n      protected IpState state;\n      protected Option datacenter;\n   \n      /** \n       * @see Ip#getId()\n       */\n      public T id(long id) {\n         this.id = id;\n         return self();\n      }\n\n      /** \n       * @see Ip#getIp()\n       */\n      public T ip(String ip) {\n         this.ip = ip;\n         return self();\n      }\n\n      /** \n       * @see Ip#getSubnet()\n       */\n      public T subnet(String subnet) {\n         this.subnet = subnet;\n         return self();\n      }\n\n      /** \n       * @see Ip#isPublic()\n       */\n      public T isPublic(boolean isPublic) {\n         this.isPublic = isPublic;\n         return self();\n      }\n\n      /** \n       * @see Ip#getState()\n       */\n      public T state(IpState state) {\n         this.state = state;\n         return self();\n      }\n\n      /** \n       * @see Ip#getDatacenter()\n       */\n      public T datacenter(Option datacenter) {\n         this.datacenter = datacenter;\n         return self();\n      }\n\n      public Ip build() {\n         return new Ip(id, ip, subnet, isPublic, state, datacenter);\n      }\n      \n      public T fromIp(Ip in) {\n         return this\n                  .id(in.getId())\n                  .ip(in.getIp())\n                  .subnet(in.getSubnet())\n                  .isPublic(in.isPublic())\n                  .state(in.getState())\n                  .datacenter(in.getDatacenter());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final long id;\n   private final String ip;\n   private final String subnet;\n   private final boolean isPublic;\n   private final IpState state;\n   private final Option datacenter;\n\n   @ConstructorProperties({\n      \"id\", \"ip\", \"subnet\", \"public\", \"state\", \"datacenter\"\n   })\n   protected Ip(long id, String ip, @Nullable String subnet, boolean isPublic, @Nullable IpState state, @Nullable Option datacenter) {\n      this.id = id;\n      this.ip = checkNotNull(ip, \"ip\");\n      this.subnet = subnet;\n      this.isPublic = isPublic;\n      this.state = state == null ? IpState.UNRECOGNIZED : state;\n      this.datacenter = datacenter;\n   }\n\n   public long getId() {\n      return this.id;\n   }\n\n   public String getIp() {\n      return this.ip;\n   }\n\n   @Nullable\n   public String getSubnet() {\n      return this.subnet;\n   }\n\n   public boolean isPublic() {\n      return this.isPublic;\n   }\n\n   public IpState getState() {\n      return this.state;\n   }\n\n   @Nullable\n   public Option getDatacenter() {\n      return this.datacenter;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, ip, subnet, isPublic, state, datacenter);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Ip that = Ip.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n               && Objects.equal(this.ip, that.ip)\n               && Objects.equal(this.subnet, that.subnet)\n               && Objects.equal(this.isPublic, that.isPublic)\n               && Objects.equal(this.state, that.state)\n               && Objects.equal(this.datacenter, that.datacenter);\n   }\n   \n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"ip\", ip).add(\"subnet\", subnet).add(\"isPublic\", isPublic).add(\"state\", state).add(\"datacenter\", datacenter);\n   }\n   \n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int compareTo(Ip o) {\n      return Longs.compare(id, o.getId());\n   }\n\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/domain/IpPortPair.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.primitives.Ints;\nimport com.google.common.primitives.Longs;\n\n/**\n * Class IpPortPair\n * \n*/\npublic class IpPortPair implements Comparable<IpPortPair> {\n\n   public static Builder<?> builder() { \n      return new ConcreteBuilder();\n   }\n   \n   public Builder<?> toBuilder() { \n      return new ConcreteBuilder().fromIpPortPair(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>>  {\n      protected abstract T self();\n\n      protected Ip ip;\n      protected int port;\n   \n      /** \n       * @see IpPortPair#getIp()\n       */\n      public T ip(Ip ip) {\n         this.ip = ip;\n         return self();\n      }\n\n      /** \n       * @see IpPortPair#getPort()\n       */\n      public T port(int port) {\n         this.port = port;\n         return self();\n      }\n\n      public IpPortPair build() {\n         return new IpPortPair(ip, port);\n      }\n      \n      public T fromIpPortPair(IpPortPair in) {\n         return this\n                  .ip(in.getIp())\n                  .port(in.getPort());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final Ip ip;\n   private final int port;\n\n   @ConstructorProperties({\n      \"ip\", \"port\"\n   })\n   protected IpPortPair(Ip ip, int port) {\n      this.ip = checkNotNull(ip, \"ip\");\n      this.port = port;\n   }\n\n   public Ip getIp() {\n      return this.ip;\n   }\n\n   public int getPort() {\n      return this.port;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(ip, port);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      IpPortPair that = IpPortPair.class.cast(obj);\n      return Objects.equal(this.ip, that.ip)\n               && Objects.equal(this.port, that.port);\n   }\n   \n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"ip\", ip).add(\"port\", port);\n   }\n   \n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int compareTo(IpPortPair o) {\n      if (ip != null && o.getIp() != null) return Longs.compare(ip.getId(), o.getIp().getId());\n      return Ints.compare(port, o.getPort());\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/domain/IpState.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.CaseFormat;\n\npublic enum IpState {\n   UNASSIGNED, ASSIGNED, UNRECOGNIZED;\n\n   public String toString() {\n      return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name());\n   }\n\n   public static IpState fromValue(String state) {\n      try {\n         return valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, checkNotNull(state, \"state\")));\n      } catch (IllegalArgumentException e) {\n         return UNRECOGNIZED;\n      }\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/domain/IpType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.domain;\n\npublic enum IpType {\n    PRIVATE(\"Private\"),\n    PRIVATE_2(\"Private 2\"),\n    PUBLIC(\"Public\"),\n    PUBLIC_2(\"Public 2\"),\n    PUBLIC_3(\"Public 3\"),\n    PUBLIC_4(\"Public 4\");\n\n    final String name;\n\n    IpType(String name) {\n        this.name = name;\n    }\n\n    @Override\n    public String toString() {\n        return name;\n    }\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/domain/Job.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.primitives.Longs;\n\n/**\n * Represents any job in GoGrid system\n * (jobs include server creation, stopping, etc)\n *\n * @see <a href=\"http://wiki.gogrid.com/wiki/index.php/API:Job_(Object)\" />\n */\npublic class Job implements Comparable<Job> {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromJob(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>> {\n      protected abstract T self();\n\n      protected long id;\n      protected Option command;\n      protected ObjectType objectType;\n      protected Date createdOn;\n      protected Date lastUpdatedOn;\n      protected JobState currentState;\n      protected int attempts;\n      protected String owner;\n      protected Set<JobProperties> history = ImmutableSet.of();\n      protected Map<String, String> details = ImmutableMap.of();\n\n      /**\n       * @see Job#getId()\n       */\n      public T id(long id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see Job#getCommand()\n       */\n      public T command(Option command) {\n         this.command = command;\n         return self();\n      }\n\n      /**\n       * @see Job#getObjectType()\n       */\n      public T objectType(ObjectType objectType) {\n         this.objectType = objectType;\n         return self();\n      }\n\n      /**\n       * @see Job#getCreatedOn()\n       */\n      public T createdOn(Date createdOn) {\n         this.createdOn = createdOn;\n         return self();\n      }\n\n      /**\n       * @see Job#getLastUpdatedOn()\n       */\n      public T lastUpdatedOn(Date lastUpdatedOn) {\n         this.lastUpdatedOn = lastUpdatedOn;\n         return self();\n      }\n\n      /**\n       * @see Job#getCurrentState()\n       */\n      public T currentState(JobState currentState) {\n         this.currentState = currentState;\n         return self();\n      }\n\n      /**\n       * @see Job#getAttempts()\n       */\n      public T attempts(int attempts) {\n         this.attempts = attempts;\n         return self();\n      }\n\n      /**\n       * @see Job#getOwner()\n       */\n      public T owner(String owner) {\n         this.owner = owner;\n         return self();\n      }\n\n      /**\n       * @see Job#getHistory()\n       */\n      public T history(Set<JobProperties> history) {\n         this.history = ImmutableSet.copyOf(checkNotNull(history, \"history\"));\n         return self();\n      }\n\n      public T history(JobProperties... in) {\n         return history(ImmutableSet.copyOf(in));\n      }\n\n      /**\n       * @see Job#getDetails()\n       */\n      public T details(Map<String, String> details) {\n         this.details = ImmutableMap.copyOf(checkNotNull(details, \"details\"));\n         return self();\n      }\n\n      public Job build() {\n         return new Job(id, command, objectType, createdOn, lastUpdatedOn, currentState, attempts, owner, history, details);\n      }\n\n      public T fromJob(Job in) {\n         return this\n               .id(in.getId())\n               .command(in.getCommand())\n               .objectType(in.getObjectType())\n               .createdOn(in.getCreatedOn())\n               .lastUpdatedOn(in.getLastUpdatedOn())\n               .currentState(in.getCurrentState())\n               .attempts(in.getAttempts())\n               .owner(in.getOwner())\n               .history(in.getHistory())\n               .details(in.getDetails());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final long id;\n   private final Option command;\n   private final ObjectType objectType;\n   private final Date createdOn;\n   private final Date lastUpdatedOn;\n   private final JobState currentState;\n   private final int attempts;\n   private final String owner;\n   private final Set<JobProperties> history;\n   private final Map<String, String> details;\n\n   /* NOTE: as of Feb 28, 10, there is a contradiction b/w the name in  documentation (details) and actual param name (detail)*/\n   @ConstructorProperties({\n         \"id\", \"command\", \"objecttype\", \"createdon\", \"lastupdatedon\", \"currentstate\", \"attempts\", \"owner\", \"history\", \"detail\"\n   })\n   protected Job(long id, Option command, ObjectType objectType, Date createdOn, @Nullable Date lastUpdatedOn,\n                 JobState currentState, int attempts, String owner, Set<JobProperties> history, Map<String, String> details) {\n      this.id = id;\n      this.command = checkNotNull(command, \"command\");\n      this.objectType = checkNotNull(objectType, \"objectType\");\n      this.createdOn = checkNotNull(createdOn, \"createdOn\");\n      this.lastUpdatedOn = lastUpdatedOn;\n      this.currentState = checkNotNull(currentState, \"currentState\");\n      this.attempts = attempts;\n      this.owner = checkNotNull(owner, \"owner\");\n      this.history = ImmutableSet.copyOf(checkNotNull(history, \"history\"));\n      this.details = ImmutableMap.copyOf(checkNotNull(details, \"details\"));\n   }\n\n   public long getId() {\n      return this.id;\n   }\n\n   public Option getCommand() {\n      return this.command;\n   }\n\n   public ObjectType getObjectType() {\n      return this.objectType;\n   }\n\n   public Date getCreatedOn() {\n      return this.createdOn;\n   }\n\n   @Nullable\n   public Date getLastUpdatedOn() {\n      return this.lastUpdatedOn;\n   }\n\n   public JobState getCurrentState() {\n      return this.currentState;\n   }\n\n   public int getAttempts() {\n      return this.attempts;\n   }\n\n   public String getOwner() {\n      return this.owner;\n   }\n\n   public Set<JobProperties> getHistory() {\n      return this.history;\n   }\n\n   public Map<String, String> getDetails() {\n      return this.details;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, command, objectType, createdOn, lastUpdatedOn, currentState, attempts, owner, history, details);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Job that = Job.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n            && Objects.equal(this.command, that.command)\n            && Objects.equal(this.objectType, that.objectType)\n            && Objects.equal(this.createdOn, that.createdOn)\n            && Objects.equal(this.lastUpdatedOn, that.lastUpdatedOn)\n            && Objects.equal(this.currentState, that.currentState)\n            && Objects.equal(this.attempts, that.attempts)\n            && Objects.equal(this.owner, that.owner)\n            && Objects.equal(this.history, that.history)\n            && Objects.equal(this.details, that.details);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"command\", command).add(\"objectType\", objectType).add(\"createdOn\", createdOn).add(\"lastUpdatedOn\", lastUpdatedOn).add(\"currentState\", currentState).add(\"attempts\", attempts).add(\"owner\", owner).add(\"history\", history).add(\"details\", details);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int compareTo(Job o) {\n      if (createdOn != null && o.getCreatedOn() != null)\n         return Longs.compare(createdOn.getTime(), o.getCreatedOn().getTime());\n      return Longs.compare(id, o.getId());\n   }\n\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/domain/JobProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.primitives.Longs;\n\n/**\n * State of a job.\n * \n * @see <a href=\"http://wiki.gogrid.com/wiki/index.php/API:Job_State_(Object)\"/>\n*/\npublic class JobProperties implements Comparable<JobProperties> {\n\n   public static Builder<?> builder() { \n      return new ConcreteBuilder();\n   }\n   \n   public Builder<?> toBuilder() { \n      return new ConcreteBuilder().fromJobProperties(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>>  {\n      protected abstract T self();\n\n      protected long id;\n      protected Date updatedOn;\n      protected JobState state;\n      protected String note;\n   \n      /** \n       * @see JobProperties#getId()\n       */\n      public T id(long id) {\n         this.id = id;\n         return self();\n      }\n\n      /** \n       * @see JobProperties#getUpdatedOn()\n       */\n      public T updatedOn(Date updatedOn) {\n         this.updatedOn = updatedOn;\n         return self();\n      }\n\n      /** \n       * @see JobProperties#getState()\n       */\n      public T state(JobState state) {\n         this.state = state;\n         return self();\n      }\n\n      /** \n       * @see JobProperties#getNote()\n       */\n      public T note(String note) {\n         this.note = note;\n         return self();\n      }\n\n      public JobProperties build() {\n         return new JobProperties(id, updatedOn, state, note);\n      }\n      \n      public T fromJobProperties(JobProperties in) {\n         return this\n                  .id(in.getId())\n                  .updatedOn(in.getUpdatedOn())\n                  .state(in.getState())\n                  .note(in.getNote());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final long id;\n   private final Date updatedOn;\n   private final JobState state;\n   private final String note;\n\n   @ConstructorProperties({\n      \"id\", \"updatedon\", \"state\", \"note\"\n   })\n   protected JobProperties(long id, Date updatedOn, JobState state, @Nullable String note) {\n      this.id = id;\n      this.updatedOn = checkNotNull(updatedOn, \"updatedOn\");\n      this.state = checkNotNull(state, \"state\");\n      this.note = note;\n   }\n\n   public long getId() {\n      return this.id;\n   }\n\n   public Date getUpdatedOn() {\n      return this.updatedOn;\n   }\n\n   public JobState getState() {\n      return this.state;\n   }\n\n   @Nullable\n   public String getNote() {\n      return this.note;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, updatedOn, state, note);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      JobProperties that = JobProperties.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n               && Objects.equal(this.updatedOn, that.updatedOn)\n               && Objects.equal(this.state, that.state)\n               && Objects.equal(this.note, that.note);\n   }\n   \n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"updatedOn\", updatedOn).add(\"state\", state).add(\"note\", note);\n   }\n   \n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int compareTo(JobProperties o) {\n      return Longs.compare(id, o.getId());\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/domain/JobState.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\npublic enum JobState {\n\n   QUEUED(\"Queued\", \"Change request is new to the system.\"), PROCESSING(\"Processing\",\n            \"Change request is is transient state...Processing.\"), SUCCEEDED(\"Succeeded\",\n            \"Change request has succeeded.\"), FAILED(\"Failed\", \"Change request has failed.\"), CANCELED(\n            \"Canceled\", \"Change request has been canceled.\"), FATAL(\"Fatal\",\n            \"Change request had Fatal or Unrecoverable Failure\"), CREATED(\"Created\",\n            \"Change request is created but not queued yet\"), UNRECOGNIZED(\"Unknown\",\n            \"The state is unknown to JClouds\");\n\n   String name;\n   String description;\n\n   JobState(String name, String description) {\n      this.name = name;\n      this.description = description;\n   }\n\n   @Override\n   public String toString() {\n      return name;\n   }\n\n   public static JobState fromValue(String state) {\n      for (JobState jobState : values()) {\n         if (jobState.name.equals(checkNotNull(state)))\n            return jobState;\n      }\n      return UNRECOGNIZED;\n   }\n\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/domain/LoadBalancer.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.primitives.Longs;\n\n/**\n * Class LoadBalancer\n * \n*/\npublic class LoadBalancer implements Comparable<LoadBalancer> {\n\n   public static Builder<?> builder() { \n      return new ConcreteBuilder();\n   }\n   \n   public Builder<?> toBuilder() { \n      return new ConcreteBuilder().fromLoadBalancer(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>>  {\n      protected abstract T self();\n\n      protected long id;\n      protected String name;\n      protected String description;\n      protected IpPortPair virtualIp;\n      protected Set<IpPortPair> realIpList = ImmutableSet.of();\n      protected LoadBalancerType type;\n      protected LoadBalancerPersistenceType persistence;\n      protected LoadBalancerOs os;\n      protected LoadBalancerState state;\n      protected Option datacenter;\n   \n      /** \n       * @see LoadBalancer#getId()\n       */\n      public T id(long id) {\n         this.id = id;\n         return self();\n      }\n\n      /** \n       * @see LoadBalancer#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /** \n       * @see LoadBalancer#getDescription()\n       */\n      public T description(String description) {\n         this.description = description;\n         return self();\n      }\n\n      /** \n       * @see LoadBalancer#getVirtualIp()\n       */\n      public T virtualIp(IpPortPair virtualIp) {\n         this.virtualIp = virtualIp;\n         return self();\n      }\n\n      /** \n       * @see LoadBalancer#getRealIpList()\n       */\n      public T realIpList(Set<IpPortPair> realIpList) {\n         this.realIpList = ImmutableSet.copyOf(checkNotNull(realIpList, \"realIpList\"));      \n         return self();\n      }\n\n      public T realIpList(IpPortPair... in) {\n         return realIpList(ImmutableSet.copyOf(in));\n      }\n\n      /** \n       * @see LoadBalancer#getType()\n       */\n      public T type(LoadBalancerType type) {\n         this.type = type;\n         return self();\n      }\n\n      /** \n       * @see LoadBalancer#getPersistence()\n       */\n      public T persistence(LoadBalancerPersistenceType persistence) {\n         this.persistence = persistence;\n         return self();\n      }\n\n      /** \n       * @see LoadBalancer#getOs()\n       */\n      public T os(LoadBalancerOs os) {\n         this.os = os;\n         return self();\n      }\n\n      /** \n       * @see LoadBalancer#getState()\n       */\n      public T state(LoadBalancerState state) {\n         this.state = state;\n         return self();\n      }\n\n      /** \n       * @see LoadBalancer#getDatacenter()\n       */\n      public T datacenter(Option datacenter) {\n         this.datacenter = datacenter;\n         return self();\n      }\n\n      public LoadBalancer build() {\n         return new LoadBalancer(id, name, description, virtualIp, realIpList, type, persistence, os, state, datacenter);\n      }\n      \n      public T fromLoadBalancer(LoadBalancer in) {\n         return this\n                  .id(in.getId())\n                  .name(in.getName())\n                  .description(in.getDescription())\n                  .virtualIp(in.getVirtualIp())\n                  .realIpList(in.getRealIpList())\n                  .type(in.getType())\n                  .persistence(in.getPersistence())\n                  .os(in.getOs())\n                  .state(in.getState())\n                  .datacenter(in.getDatacenter());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final long id;\n   private final String name;\n   private final String description;\n   private final IpPortPair virtualIp;\n   private final Set<IpPortPair> realIpList;\n   private final LoadBalancerType type;\n   private final LoadBalancerPersistenceType persistence;\n   private final LoadBalancerOs os;\n   private final LoadBalancerState state;\n   private final Option datacenter;\n\n   @ConstructorProperties({\n      \"id\", \"name\", \"description\", \"virtualip\", \"realiplist\", \"type\", \"persistence\", \"os\", \"state\", \"datacenter\"\n   })\n   protected LoadBalancer(long id, String name, @Nullable String description, IpPortPair virtualIp, Set<IpPortPair> realIpList, LoadBalancerType type, LoadBalancerPersistenceType persistence, LoadBalancerOs os, LoadBalancerState state, Option datacenter) {\n      this.id = id;\n      this.name = checkNotNull(name, \"name\");\n      this.description = description;\n      this.virtualIp = checkNotNull(virtualIp, \"virtualIp\");\n      this.realIpList = ImmutableSet.copyOf(checkNotNull(realIpList, \"realIpList\"));      \n      this.type = checkNotNull(type, \"type\");\n      this.persistence = checkNotNull(persistence, \"persistence\");\n      this.os = checkNotNull(os, \"os\");\n      this.state = checkNotNull(state, \"state\");\n      this.datacenter = checkNotNull(datacenter, \"datacenter\");\n   }\n\n   public long getId() {\n      return this.id;\n   }\n\n   public String getName() {\n      return this.name;\n   }\n\n   @Nullable\n   public String getDescription() {\n      return this.description;\n   }\n\n   public IpPortPair getVirtualIp() {\n      return this.virtualIp;\n   }\n\n   public Set<IpPortPair> getRealIpList() {\n      return this.realIpList;\n   }\n\n   public LoadBalancerType getType() {\n      return this.type;\n   }\n\n   public LoadBalancerPersistenceType getPersistence() {\n      return this.persistence;\n   }\n\n   public LoadBalancerOs getOs() {\n      return this.os;\n   }\n\n   public LoadBalancerState getState() {\n      return this.state;\n   }\n\n   public Option getDatacenter() {\n      return this.datacenter;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, name, description, virtualIp, realIpList, type, persistence, os, state, datacenter);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      LoadBalancer that = LoadBalancer.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n               && Objects.equal(this.name, that.name)\n               && Objects.equal(this.description, that.description)\n               && Objects.equal(this.virtualIp, that.virtualIp)\n               && Objects.equal(this.realIpList, that.realIpList)\n               && Objects.equal(this.type, that.type)\n               && Objects.equal(this.persistence, that.persistence)\n               && Objects.equal(this.os, that.os)\n               && Objects.equal(this.state, that.state)\n               && Objects.equal(this.datacenter, that.datacenter);\n   }\n   \n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"name\", name).add(\"description\", description).add(\"virtualIp\", virtualIp).add(\"realIpList\", realIpList).add(\"type\", type).add(\"persistence\", persistence).add(\"os\", os).add(\"state\", state).add(\"datacenter\", datacenter);\n   }\n   \n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int compareTo(LoadBalancer o) {\n      return Longs.compare(id, o.getId());\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/domain/LoadBalancerOs.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\npublic enum LoadBalancerOs {\n\n    F5,\n    UNRECOGNIZED;\n\n    public static LoadBalancerOs fromValue(String value) {\n        try {\n            return valueOf(checkNotNull(value));\n        } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n        }\n    }\n\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/domain/LoadBalancerPersistenceType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\npublic enum LoadBalancerPersistenceType {\n\n   NONE(\"None\"), SSL_STICKY(\"SSL Sticky\"), SOURCE_ADDRESS(\"Source Address\"), UNRECOGNIZED(\"Unknown\");\n\n   String type;\n\n   LoadBalancerPersistenceType(String type) {\n      this.type = type;\n   }\n\n   @Override\n   public String toString() {\n      return type;\n   }\n\n   public static LoadBalancerPersistenceType fromValue(String type) {\n      for (LoadBalancerPersistenceType persistenceType : values()) {\n         if (persistenceType.type.equals(checkNotNull(type)))\n            return persistenceType;\n      }\n      return UNRECOGNIZED;\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/domain/LoadBalancerState.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.CaseFormat;\n\npublic enum LoadBalancerState {\n\n    ON,\n    OFF,\n    UNAVAILABLE,\n    UNRECOGNIZED;\n\n    public String value() {\n        return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name());\n    }\n\n    @Override\n    public String toString() {\n        return value();\n    }\n\n    public static LoadBalancerState fromValue(String state) {\n        try {\n            return valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, checkNotNull(state, \"state\")));\n        } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n        }\n    }\n    \n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/domain/LoadBalancerType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\npublic enum LoadBalancerType {\n\n    ROUND_ROBIN(\"Round Robin\"),\n    LEAST_CONNECTED(\"Least Connect\"),\n    UNRECOGNIZED(\"Unknown\");\n\n    String type;\n    LoadBalancerType(String type) {\n        this.type = type;\n    }\n\n    @Override\n    public String toString() {\n        return type;\n    }\n\n    public static LoadBalancerType fromValue(String type) {\n        for (LoadBalancerType persistenceType : values()) {\n            if (persistenceType.type.equals(checkNotNull(type))) return persistenceType;\n        }\n        return UNRECOGNIZED;\n    }\n\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/domain/ObjectType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.CaseFormat;\n\npublic enum ObjectType {\n\n    VIRTUAL_SERVER,\n    LOAD_BALANCER,\n    CLOUD_STORAGE,\n    STORAGE_DNS,\n    SERVER_IMAGE,\n    DEDICATED_SERVER,\n    UNRECOGNIZED;\n\n    public String value() {\n        return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name());\n    }\n\n    @Override\n    public String toString() {\n        return value();\n    }\n\n    public static ObjectType fromValue(String type) {\n        if (\"StorageDNS\".equals(type)) return STORAGE_DNS;\n        try {\n            return valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, checkNotNull(type, \"type\")));\n        } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n        }\n    }\n\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/domain/Option.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.primitives.Longs;\n\n/**\n * Class Option\n * \n*/\npublic class Option implements Comparable<Option> {\n\n   public static Builder<?> builder() { \n      return new ConcreteBuilder();\n   }\n   \n   public Builder<?> toBuilder() { \n      return new ConcreteBuilder().fromOption(this);\n   }\n   \n   public static Option createWithIdNameAndDescription(Long id, String name, String description) {\n      return new Option(id, name, description);\n   }\n\n   public abstract static class Builder<T extends Builder<T>>  {\n      protected abstract T self();\n\n      protected Long id;\n      protected String name;\n      protected String description;\n   \n      /** \n       * @see Option#getId()\n       */\n      public T id(Long id) {\n         this.id = id;\n         return self();\n      }\n\n      /** \n       * @see Option#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /** \n       * @see Option#getDescription()\n       */\n      public T description(String description) {\n         this.description = description;\n         return self();\n      }\n\n      public Option build() {\n         return new Option(id, name, description);\n      }\n      \n      public T fromOption(Option in) {\n         return this\n                  .id(in.getId())\n                  .name(in.getName())\n                  .description(in.getDescription());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final Long id;\n   private final String name;\n   private final String description;\n\n   @ConstructorProperties({\n      \"id\", \"name\", \"description\"\n   })\n   protected Option(Long id, String name, @Nullable String description) {\n      this.id = checkNotNull(id, \"id\");\n      this.name = checkNotNull(name, \"name\");\n      this.description = description;\n   }\n\n   public Long getId() {\n      return this.id;\n   }\n\n   public String getName() {\n      return this.name;\n   }\n\n   @Nullable\n   public String getDescription() {\n      return this.description;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, name, description);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Option that = Option.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n               && Objects.equal(this.name, that.name)\n               && Objects.equal(this.description, that.description);\n   }\n   \n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"name\", name).add(\"description\", description);\n   }\n   \n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int compareTo(Option o) {\n      return Longs.compare(id, o.id);\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/domain/PowerCommand.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.domain;\n\n\n/**\n * Server's state transition.\n * \n * Using this value, server's state will be changed to one of the following:\n * <ul>\n * <li>Start</li>\n * <li>Stop</li>\n * <li>Restart</li>\n * </ul>\n * \n * @see org.jclouds.gogrid.features.GridServerApi#power(String, PowerCommand)\n * @see <a href=\"http://wiki.gogrid.com/wiki/index.php/API:grid.server.power\" />\n */\npublic enum PowerCommand {\n   START, STOP /* NOTE: This is a hard shutdown, equivalent to powering off a server. */, RESTART;\n\n   @Override\n   public String toString() {\n      return name().toLowerCase();\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/domain/Server.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.primitives.Longs;\n\n/**\n * Class Server\n * \n*/\npublic class Server implements Comparable<Server> {\n\n   public static Builder<?> builder() { \n      return new ConcreteBuilder();\n   }\n   \n   public Builder<?> toBuilder() { \n      return new ConcreteBuilder().fromServer(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>>  {\n      protected abstract T self();\n\n      protected long id;\n      protected boolean isSandbox;\n      protected String name;\n      protected String description;\n      protected ServerState state;\n      protected Option datacenter;\n      protected Option type;\n      protected Option ram;\n      protected Option os;\n      protected Ip ip;\n      protected ServerImage image;\n   \n      /** \n       * @see Server#getId()\n       */\n      public T id(long id) {\n         this.id = id;\n         return self();\n      }\n\n      /** \n       * @see Server#isSandbox()\n       */\n      public T isSandbox(boolean isSandbox) {\n         this.isSandbox = isSandbox;\n         return self();\n      }\n\n      /** \n       * @see Server#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /** \n       * @see Server#getDescription()\n       */\n      public T description(String description) {\n         this.description = description;\n         return self();\n      }\n\n      /** \n       * @see Server#getState()\n       */\n      public T state(ServerState state) {\n         this.state = state;\n         return self();\n      }\n\n      /** \n       * @see Server#getDatacenter()\n       */\n      public T datacenter(Option datacenter) {\n         this.datacenter = datacenter;\n         return self();\n      }\n\n      /** \n       * @see Server#getType()\n       */\n      public T type(Option type) {\n         this.type = type;\n         return self();\n      }\n\n      /** \n       * @see Server#getRam()\n       */\n      public T ram(Option ram) {\n         this.ram = ram;\n         return self();\n      }\n\n      /** \n       * @see Server#getOs()\n       */\n      public T os(Option os) {\n         this.os = os;\n         return self();\n      }\n\n      /** \n       * @see Server#getIp()\n       */\n      public T ip(Ip ip) {\n         this.ip = ip;\n         return self();\n      }\n\n      /** \n       * @see Server#getImage()\n       */\n      public T image(ServerImage image) {\n         this.image = image;\n         return self();\n      }\n\n      public Server build() {\n         return new Server(id, isSandbox, name, description, state, datacenter, type, ram, os, ip, image);\n      }\n      \n      public T fromServer(Server in) {\n         return this\n                  .id(in.getId())\n                  .isSandbox(in.isSandbox())\n                  .name(in.getName())\n                  .description(in.getDescription())\n                  .state(in.getState())\n                  .datacenter(in.getDatacenter())\n                  .type(in.getType())\n                  .ram(in.getRam())\n                  .os(in.getOs())\n                  .ip(in.getIp())\n                  .image(in.getImage());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final long id;\n   private final boolean isSandbox;\n   private final String name;\n   private final String description;\n   private final ServerState state;\n   private final Option datacenter;\n   private final Option type;\n   private final Option ram;\n   private final Option os;\n   private final Ip ip;\n   private final ServerImage image;\n\n   @ConstructorProperties({\n      \"id\", \"isSandbox\", \"name\", \"description\", \"state\", \"datacenter\", \"type\", \"ram\", \"os\", \"ip\", \"image\"\n   })\n   protected Server(long id, boolean isSandbox, String name, @Nullable String description, ServerState state,\n                    @Nullable Option datacenter, Option type, Option ram, Option os, Ip ip, ServerImage image) {\n      this.id = id;\n      this.isSandbox = isSandbox;\n      this.name = checkNotNull(name, \"name\");\n      this.description = description;\n      this.state = checkNotNull(state, \"state\");\n      this.datacenter = datacenter;\n      this.type = checkNotNull(type, \"type\");\n      this.ram = checkNotNull(ram, \"ram\");\n      this.os = checkNotNull(os, \"os\");\n      this.ip = checkNotNull(ip, \"ip\");\n      this.image = checkNotNull(image, \"image\");\n   }\n\n   public long getId() {\n      return this.id;\n   }\n\n   public boolean isSandbox() {\n      return this.isSandbox;\n   }\n\n   public String getName() {\n      return this.name;\n   }\n\n   @Nullable\n   public String getDescription() {\n      return this.description;\n   }\n\n   public ServerState getState() {\n      return this.state;\n   }\n   \n   @Nullable\n   public Option getDatacenter() {\n      return this.datacenter;\n   }\n\n   public Option getType() {\n      return this.type;\n   }\n\n   public Option getRam() {\n      return this.ram;\n   }\n\n   public Option getOs() {\n      return this.os;\n   }\n\n   public Ip getIp() {\n      return this.ip;\n   }\n\n   public ServerImage getImage() {\n      return this.image;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, isSandbox, name, description, state, datacenter, type, ram, os, ip, image);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Server that = Server.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n               && Objects.equal(this.isSandbox, that.isSandbox)\n               && Objects.equal(this.name, that.name)\n               && Objects.equal(this.description, that.description)\n               && Objects.equal(this.state, that.state)\n               && Objects.equal(this.datacenter, that.datacenter)\n               && Objects.equal(this.type, that.type)\n               && Objects.equal(this.ram, that.ram)\n               && Objects.equal(this.os, that.os)\n               && Objects.equal(this.ip, that.ip)\n               && Objects.equal(this.image, that.image);\n   }\n   \n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"isSandbox\", isSandbox).add(\"name\", name).add(\"description\", description).add(\"state\", state).add(\"datacenter\", datacenter).add(\"type\", type).add(\"ram\", ram).add(\"os\", os).add(\"ip\", ip).add(\"image\", image);\n   }\n   \n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int compareTo(Server that) {\n      return Longs.compare(id, that.getId());\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/domain/ServerImage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.base.Strings;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.primitives.Longs;\n\n/**\n * Class ServerImage\n * \n*/\npublic class ServerImage implements Comparable<ServerImage> {\n\n   public static Builder<?> builder() { \n      return new ConcreteBuilder();\n   }\n   \n   public Builder<?> toBuilder() { \n      return new ConcreteBuilder().fromServerImage(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>>  {\n      protected abstract T self();\n\n      protected long id;\n      protected String name;\n      protected String friendlyName;\n      protected String description;\n      protected Option os;\n      protected Option architecture;\n      protected ServerImageType type;\n      protected ServerImageState state;\n      protected double price;\n      protected String location;\n      protected boolean isActive;\n      protected boolean isPublic;\n      protected Date createdTime;\n      protected Date updatedTime;\n      protected Set<BillingToken> billingTokens = ImmutableSet.of();\n      protected Customer owner;\n   \n      /** \n       * @see ServerImage#getId()\n       */\n      public T id(long id) {\n         this.id = id;\n         return self();\n      }\n\n      /** \n       * @see ServerImage#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /** \n       * @see ServerImage#getFriendlyName()\n       */\n      public T friendlyName(String friendlyName) {\n         this.friendlyName = friendlyName;\n         return self();\n      }\n\n      /** \n       * @see ServerImage#getDescription()\n       */\n      public T description(String description) {\n         this.description = description;\n         return self();\n      }\n\n      /** \n       * @see ServerImage#getOs()\n       */\n      public T os(Option os) {\n         this.os = os;\n         return self();\n      }\n\n      /** \n       * @see ServerImage#getArchitecture()\n       */\n      public T architecture(Option architecture) {\n         this.architecture = architecture;\n         return self();\n      }\n\n      /** \n       * @see ServerImage#getType()\n       */\n      public T type(ServerImageType type) {\n         this.type = type;\n         return self();\n      }\n\n      /** \n       * @see ServerImage#getState()\n       */\n      public T state(ServerImageState state) {\n         this.state = state;\n         return self();\n      }\n\n      /** \n       * @see ServerImage#getPrice()\n       */\n      public T price(double price) {\n         this.price = price;\n         return self();\n      }\n\n      /** \n       * @see ServerImage#getLocation()\n       */\n      public T location(String location) {\n         this.location = location;\n         return self();\n      }\n\n      /** \n       * @see ServerImage#isActive()\n       */\n      public T isActive(boolean isActive) {\n         this.isActive = isActive;\n         return self();\n      }\n\n      /** \n       * @see ServerImage#isPublic()\n       */\n      public T isPublic(boolean isPublic) {\n         this.isPublic = isPublic;\n         return self();\n      }\n\n      /** \n       * @see ServerImage#getCreatedTime()\n       */\n      public T createdTime(Date createdTime) {\n         this.createdTime = createdTime;\n         return self();\n      }\n\n      /** \n       * @see ServerImage#getUpdatedTime()\n       */\n      public T updatedTime(Date updatedTime) {\n         this.updatedTime = updatedTime;\n         return self();\n      }\n\n      /** \n       * @see ServerImage#getBillingTokens()\n       */\n      public T billingTokens(Set<BillingToken> billingTokens) {\n         this.billingTokens = ImmutableSet.copyOf(checkNotNull(billingTokens, \"billingTokens\"));      \n         return self();\n      }\n\n      public T billingTokens(BillingToken... in) {\n         return billingTokens(ImmutableSet.copyOf(in));\n      }\n\n      /** \n       * @see ServerImage#getOwner()\n       */\n      public T owner(Customer owner) {\n         this.owner = owner;\n         return self();\n      }\n\n      public ServerImage build() {\n         return new ServerImage(id, name, friendlyName, description, os, architecture, type, state, price, location, isActive, isPublic, createdTime, updatedTime, billingTokens, owner);\n      }\n      \n      public T fromServerImage(ServerImage in) {\n         return this\n                  .id(in.getId())\n                  .name(in.getName())\n                  .friendlyName(in.getFriendlyName())\n                  .description(in.getDescription())\n                  .os(in.getOs())\n                  .architecture(in.getArchitecture())\n                  .type(in.getType())\n                  .state(in.getState())\n                  .price(in.getPrice())\n                  .location(in.getLocation())\n                  .isActive(in.isActive())\n                  .isPublic(in.isPublic())\n                  .createdTime(in.getCreatedTime())\n                  .updatedTime(in.getUpdatedTime())\n                  .billingTokens(in.getBillingTokens())\n                  .owner(in.getOwner());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final long id;\n   private final String name;\n   private final String friendlyName;\n   private final String description;\n   private final Option os;\n   private final Option architecture;\n   private final ServerImageType type;\n   private final ServerImageState state;\n   private final double price;\n   private final String location;\n   private final boolean isActive;\n   private final boolean isPublic;\n   private final Date createdTime;\n   private final Date updatedTime;\n   private final Set<BillingToken> billingTokens;\n   private final Customer owner;\n\n   @ConstructorProperties({\n      \"id\", \"name\", \"friendlyName\", \"description\", \"os\", \"architecture\", \"type\", \"state\", \"price\", \"location\", \"isActive\", \"isPublic\", \"createdTime\", \"updatedTime\", \"billingtokens\", \"owner\"\n   })\n   protected ServerImage(long id, String name, String friendlyName, @Nullable String description, Option os, @Nullable Option architecture,\n                         ServerImageType type, ServerImageState state, double price, String location, boolean isActive,\n                         boolean isPublic, @Nullable Date createdTime, @Nullable Date updatedTime, Set<BillingToken> billingTokens, Customer owner) {\n      this.id = id;\n      this.name = checkNotNull(name, \"name\");\n      this.friendlyName = checkNotNull(friendlyName, \"friendlyName\");\n      this.description = Strings.nullToEmpty(description);\n      this.os = checkNotNull(os, \"os\");\n      this.architecture = architecture;\n      this.type = checkNotNull(type, \"type\");\n      this.state = checkNotNull(state, \"state\");\n      this.price = price;\n      this.location = checkNotNull(location, \"location\");\n      this.isActive = isActive;\n      this.isPublic = isPublic;\n      this.createdTime = createdTime;\n      this.updatedTime = updatedTime;\n      this.billingTokens = ImmutableSet.copyOf(checkNotNull(billingTokens, \"billingTokens\"));      \n      this.owner = checkNotNull(owner, \"owner\");\n   }\n\n   public long getId() {\n      return this.id;\n   }\n\n   public String getName() {\n      return this.name;\n   }\n\n   public String getFriendlyName() {\n      return this.friendlyName;\n   }\n   \n   public String getDescription() {\n      return this.description;\n   }\n\n   public Option getOs() {\n      return this.os;\n   }\n\n   @Nullable\n   public Option getArchitecture() {\n      return this.architecture;\n   }\n\n   public ServerImageType getType() {\n      return this.type;\n   }\n\n   public ServerImageState getState() {\n      return this.state;\n   }\n\n   public double getPrice() {\n      return this.price;\n   }\n\n   public String getLocation() {\n      return this.location;\n   }\n\n   public boolean isActive() {\n      return this.isActive;\n   }\n\n   public boolean isPublic() {\n      return this.isPublic;\n   }\n\n   @Nullable\n   public Date getCreatedTime() {\n      return this.createdTime;\n   }\n\n   @Nullable\n   public Date getUpdatedTime() {\n      return this.updatedTime;\n   }\n\n   public Set<BillingToken> getBillingTokens() {\n      return this.billingTokens;\n   }\n\n   public Customer getOwner() {\n      return this.owner;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, name, friendlyName, description, os, architecture, type, state, price, location, isActive, isPublic, createdTime, updatedTime, billingTokens, owner);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      ServerImage that = ServerImage.class.cast(obj);\n      return Objects.equal(this.id, that.id)\n               && Objects.equal(this.name, that.name)\n               && Objects.equal(this.friendlyName, that.friendlyName)\n               && Objects.equal(this.description, that.description)\n               && Objects.equal(this.os, that.os)\n               && Objects.equal(this.architecture, that.architecture)\n               && Objects.equal(this.type, that.type)\n               && Objects.equal(this.state, that.state)\n               && Objects.equal(this.price, that.price)\n               && Objects.equal(this.location, that.location)\n               && Objects.equal(this.isActive, that.isActive)\n               && Objects.equal(this.isPublic, that.isPublic)\n               && Objects.equal(this.createdTime, that.createdTime)\n               && Objects.equal(this.updatedTime, that.updatedTime)\n               && Objects.equal(this.billingTokens, that.billingTokens)\n               && Objects.equal(this.owner, that.owner);\n   }\n   \n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"id\", id).add(\"name\", name).add(\"friendlyName\", friendlyName).add(\"description\", description).add(\"os\", os).add(\"architecture\", architecture).add(\"type\", type).add(\"state\", state).add(\"price\", price).add(\"location\", location).add(\"isActive\", isActive).add(\"isPublic\", isPublic).add(\"createdTime\", createdTime).add(\"updatedTime\", updatedTime).add(\"billingTokens\", billingTokens).add(\"owner\", owner);\n   }\n   \n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n   @Override\n   public int compareTo(ServerImage that) {\n      if (that == null)\n         return 1;\n      if (this == that)\n         return 0;\n      return Longs.compare(id, that.getId());\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/domain/ServerImageState.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\npublic enum ServerImageState {\n\n    AVAILABLE(\"Available\"),\n    SAVING(\"Saving\"),\n    TRASH(\"Trash\"),\n    UNRECOGNIZED(\"Unknown\");\n\n    String type;\n    ServerImageState(String type) {\n        this.type = type;\n    }\n\n    @Override\n    public String toString() {\n        return type;\n    }\n\n    public static ServerImageState fromValue(String type) {\n        for (ServerImageState serverImageState : values()) {\n            if (serverImageState.type.equals(checkNotNull(type))) return serverImageState;\n        }\n        return UNRECOGNIZED;\n    }\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/domain/ServerImageType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\npublic enum ServerImageType {\n\n    WEB_APPLICATION_SERVER(\"Web Server\"),\n    DATABASE_SERVER(\"Database Server\"),\n    UNRECOGNIZED(\"Unknown\");\n\n    String type;\n    ServerImageType(String type) {\n        this.type = type;\n    }\n\n    @Override\n    public String toString() {\n        return type;\n    }\n\n    public static ServerImageType fromValue(String type) {\n        for (ServerImageType serverImageType : values()) {\n            if (serverImageType.type.equals(checkNotNull(type))) return serverImageType;\n        }\n        return UNRECOGNIZED;\n    }\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/domain/ServerState.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.CaseFormat;\n\npublic enum ServerState {\n\n   ON, STARTING, OFF, STOPPING, RESTARTING, SAVING, RESTORING, UPDATING, UNRECOGNIZED;\n\n   public String value() {\n      return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name());\n   }\n\n   @Override\n   public String toString() {\n      return value();\n   }\n\n   public static ServerState fromValue(String state) {\n      try {\n         return valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, checkNotNull(state, \"state\")));\n      } catch (IllegalArgumentException e) {\n         return UNRECOGNIZED;\n      }\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/domain/internal/ErrorResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.domain.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ComparisonChain;\n\n/**\n * Class ErrorResponse\n */\npublic class ErrorResponse implements Comparable<ErrorResponse> {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromErrorResponse(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>>  {\n      protected abstract T self();\n\n      protected String message;\n      protected String errorCode;\n\n      /**\n       * @see ErrorResponse#getMessage()\n       */\n      public T message(String message) {\n         this.message = message;\n         return self();\n      }\n\n      /**\n       * @see ErrorResponse#getErrorCode()\n       */\n      public T errorCode(String errorCode) {\n         this.errorCode = errorCode;\n         return self();\n      }\n\n      public ErrorResponse build() {\n         return new ErrorResponse(message, errorCode);\n      }\n\n      public T fromErrorResponse(ErrorResponse in) {\n         return this\n               .message(in.getMessage())\n               .errorCode(in.getErrorCode());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final String message;\n   private final String errorCode;\n\n   @ConstructorProperties({\n         \"message\", \"errorcode\"\n   })\n   protected ErrorResponse(String message, String errorCode) {\n      this.message = checkNotNull(message, \"message\");\n      this.errorCode = checkNotNull(errorCode, \"errorCode\");\n   }\n\n   public String getMessage() {\n      return this.message;\n   }\n\n   public String getErrorCode() {\n      return this.errorCode;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(message, errorCode);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      ErrorResponse that = ErrorResponse.class.cast(obj);\n      return Objects.equal(this.message, that.message)\n            && Objects.equal(this.errorCode, that.errorCode);\n   }\n\n   @Override\n   public int compareTo(ErrorResponse that) {\n      return ComparisonChain.start()\n            .compare(errorCode, that.errorCode)\n            .compare(message, that.message)\n            .result();\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"message\", message).add(\"errorCode\", errorCode);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/features/GridImageApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.features;\n\nimport static org.jclouds.gogrid.reference.GoGridHeaders.VERSION;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.ID_KEY;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.IMAGE_DESCRIPTION_KEY;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.IMAGE_FRIENDLY_NAME_KEY;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.IMAGE_KEY;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.LOOKUP_LIST_KEY;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.SERVER_ID_OR_NAME_KEY;\n\nimport java.util.Set;\n\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.QueryParam;\n\nimport org.jclouds.Fallbacks;\nimport org.jclouds.gogrid.binders.BindIdsToQueryParams;\nimport org.jclouds.gogrid.binders.BindNamesToQueryParams;\nimport org.jclouds.gogrid.domain.Option;\nimport org.jclouds.gogrid.domain.ServerImage;\nimport org.jclouds.gogrid.filters.SharedKeyLiteAuthentication;\nimport org.jclouds.gogrid.functions.ParseImageFromJsonResponse;\nimport org.jclouds.gogrid.functions.ParseImageListFromJsonResponse;\nimport org.jclouds.gogrid.functions.ParseOptionsFromJsonResponse;\nimport org.jclouds.gogrid.options.GetImageListOptions;\nimport org.jclouds.gogrid.options.SaveImageOptions;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\n\n/**\n * Manages the server images\n * \n * @see <a\n *      href=\"http://wiki.gogrid.com/wiki/index.php/API#Server_Image_Methods\"/>\n */\n@RequestFilters(SharedKeyLiteAuthentication.class)\n@QueryParams(keys = VERSION, values = \"{jclouds.api-version}\")\npublic interface GridImageApi {\n\n   /**\n    * Returns all server images.\n    *\n    * @param options\n    *           options to narrow the search down\n    * @return server images found\n    */\n   @GET\n   @ResponseParser(ParseImageListFromJsonResponse.class)\n   @Path(\"/grid/image/list\")\n   Set<ServerImage> getImageList(GetImageListOptions... options);\n\n   /**\n    * Returns images, found by specified ids\n    *\n    * @param ids\n    *           the ids that match existing images\n    * @return images found\n    */\n   @GET\n   @ResponseParser(ParseImageListFromJsonResponse.class)\n   @Path(\"/grid/image/get\")\n   Set<ServerImage> getImagesById(@BinderParam(BindIdsToQueryParams.class) Long... ids);\n\n   /**\n    * Returns images, found by specified names\n    *\n    * @param names\n    *           the names that march existing images\n    * @return images found\n    */\n   @GET\n   @ResponseParser(ParseImageListFromJsonResponse.class)\n   @Path(\"/grid/image/get\")\n   Set<ServerImage> getImagesByName(@BinderParam(BindNamesToQueryParams.class) String... names);\n\n   /**\n    * Edits an existing image\n    *\n    * @param idOrName\n    *           id or name of the existing image\n    * @param newDescription\n    *           description to replace the current one\n    * @return edited server image\n    */\n   @GET\n   @ResponseParser(ParseImageFromJsonResponse.class)\n   @Path(\"/grid/image/edit\")\n   ServerImage editImageDescription(@QueryParam(IMAGE_KEY) String idOrName,\n                                    @QueryParam(IMAGE_DESCRIPTION_KEY) String newDescription);\n\n   /**\n    * Edits an existing image\n    *\n    * @param idOrName\n    *           id or name of the existing image\n    * @param newFriendlyName\n    *           friendly name to replace the current one\n    * @return edited server image\n    */\n   @GET\n   @ResponseParser(ParseImageFromJsonResponse.class)\n   @Path(\"/grid/image/edit\")\n   ServerImage editImageFriendlyName(@QueryParam(IMAGE_KEY) String idOrName,\n                                     @QueryParam(IMAGE_FRIENDLY_NAME_KEY) String newFriendlyName);\n\n   /**\n    * Retrieves the list of supported Datacenters to save images in. The objects\n    * will have datacenter ID, name and description. In most cases, id or name\n    * will be used for {@link #getImageList}.\n    *\n    * @return supported datacenters\n    */\n   @GET\n   @ResponseParser(ParseOptionsFromJsonResponse.class)\n   @Path(\"/common/lookup/list\")\n   @QueryParams(keys = LOOKUP_LIST_KEY, values = \"datacenter\")\n   Set<Option> getDatacenters();\n\n   /**\n    * Deletes an existing image\n    *\n    * @param id\n    *           id of the existing image\n    */\n   @GET\n   @ResponseParser(ParseImageFromJsonResponse.class)\n   @Path(\"/grid/image/delete\")\n   @Fallback(Fallbacks.NullOnNotFoundOr404.class)\n   ServerImage deleteById(@QueryParam(ID_KEY) long id);\n\n   /**\n    * This call will save a private (visible to only you) server image to your\n    * library of available images. The image will be saved from an existing\n    * server.\n    *\n    * @param idOrName\n    *           id or name of the existing server\n    * @param friendlyName\n    *           friendly name of the image\n    * @return saved server image\n    */\n   @GET\n   @ResponseParser(ParseImageFromJsonResponse.class)\n   @Path(\"/grid/image/save\")\n   ServerImage saveImageFromServer(@QueryParam(IMAGE_FRIENDLY_NAME_KEY) String friendlyName,\n                                   @QueryParam(SERVER_ID_OR_NAME_KEY) String idOrName, SaveImageOptions... options);\n\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/features/GridIpApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.features;\n\nimport static org.jclouds.gogrid.reference.GoGridHeaders.VERSION;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.IP_STATE_KEY;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.IP_TYPE_KEY;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.LOOKUP_LIST_KEY;\n\nimport java.util.Set;\n\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\n\nimport org.jclouds.gogrid.domain.Ip;\nimport org.jclouds.gogrid.domain.Option;\nimport org.jclouds.gogrid.filters.SharedKeyLiteAuthentication;\nimport org.jclouds.gogrid.functions.ParseIpListFromJsonResponse;\nimport org.jclouds.gogrid.functions.ParseOptionsFromJsonResponse;\nimport org.jclouds.gogrid.options.GetIpListOptions;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\n\n@RequestFilters(SharedKeyLiteAuthentication.class)\n@QueryParams(keys = VERSION, values = \"{jclouds.api-version}\")\npublic interface GridIpApi {\n\n   /**\n    * Returns all IPs in the system that match the options\n    *\n    * @param options\n    *           options to narrow the search down\n    * @return IPs found by the search\n    */\n   @GET\n   @ResponseParser(ParseIpListFromJsonResponse.class)\n   @Path(\"/grid/ip/list\")\n   Set<Ip> getIpList(GetIpListOptions... options);\n\n   /**\n    * Returns the list of unassigned IPs.\n    *\n    * NOTE: this returns both public and private IPs!\n    *\n    * @return unassigned IPs\n    */\n   @GET\n   @ResponseParser(ParseIpListFromJsonResponse.class)\n   @Path(\"/grid/ip/list\")\n   @QueryParams(keys = IP_STATE_KEY, values = \"Unassigned\")\n   Set<Ip> getUnassignedIpList();\n\n   /**\n    * Returns the list of unassigned public IPs.\n    *\n    * @return unassigned public IPs\n    */\n   @GET\n   @ResponseParser(ParseIpListFromJsonResponse.class)\n   @Path(\"/grid/ip/list\")\n   @QueryParams(keys = { IP_STATE_KEY, IP_TYPE_KEY }, values = { \"Unassigned\", \"Public\" })\n   Set<Ip> getUnassignedPublicIpList();\n\n   /**\n    * Returns the list of assigned IPs\n    *\n    * NOTE: this returns both public and private IPs!\n    *\n    * @return assigned IPs\n    */\n   @GET\n   @ResponseParser(ParseIpListFromJsonResponse.class)\n   @Path(\"/grid/ip/list\")\n   @QueryParams(keys = IP_STATE_KEY, values = \"Assigned\")\n   Set<Ip> getAssignedIpList();\n\n   /**\n    * Retrieves the list of supported Datacenters to retrieve ips from. The objects will have\n    * datacenter ID, name and description. In most cases, id or name will be used for\n    * {@link #addServer}.\n    *\n    * @return supported datacenters\n    */\n   @GET\n   @ResponseParser(ParseOptionsFromJsonResponse.class)\n   @Path(\"/common/lookup/list\")\n   @QueryParams(keys = LOOKUP_LIST_KEY, values = \"ip.datacenter\")\n   Set<Option> getDatacenters();\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/features/GridJobApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.features;\n\nimport static org.jclouds.gogrid.reference.GoGridHeaders.VERSION;\n\nimport java.util.Set;\n\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\n\nimport org.jclouds.gogrid.binders.BindIdsToQueryParams;\nimport org.jclouds.gogrid.binders.BindObjectNameToGetJobsRequestQueryParams;\nimport org.jclouds.gogrid.domain.Job;\nimport org.jclouds.gogrid.filters.SharedKeyLiteAuthentication;\nimport org.jclouds.gogrid.functions.ParseJobListFromJsonResponse;\nimport org.jclouds.gogrid.options.GetJobListOptions;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\n\n/**\n * Manages the customer's jobs.\n * \n * @see <a href=\"http://wiki.gogrid.com/wiki/index.php/API#Job_Methods\" />\n */\n@RequestFilters(SharedKeyLiteAuthentication.class)\n@QueryParams(keys = VERSION, values = \"{jclouds.api-version}\")\npublic interface GridJobApi {\n\n   /**\n    * Returns all jobs found. The resulting set may be narrowed down by providing\n    * {@link GetJobListOptions}.\n    *\n    * By default, the result is <=100 items from the date range of 4 weeks ago to now.\n    *\n    * NOTE: this method results in a big volume of data in response\n    *\n    * @return jobs found by request\n    */\n   @GET\n   @ResponseParser(ParseJobListFromJsonResponse.class)\n   @Path(\"/grid/job/list\")\n   Set<Job> getJobList(GetJobListOptions... options);\n\n   /**\n    * Returns jobs found for an object with a provided name.\n    *\n    * Usually, in GoGrid a name will uniquely identify the object, or, as the docs state, some API\n    * methods will cause errors.\n    *\n    * @param objectName\n    *           name of the object\n    * @return found jobs for the object\n    */\n   @GET\n   @ResponseParser(ParseJobListFromJsonResponse.class)\n   @Path(\"/grid/job/list\")\n   Set<Job> getJobsForObjectName(\n           @BinderParam(BindObjectNameToGetJobsRequestQueryParams.class) String objectName);\n\n   /**\n    * Returns jobs for the corresponding id(s).\n    *\n    * NOTE: there is a 1:1 relation between a job and its ID.\n    *\n    * @param ids\n    *           ids for the jobs\n    * @return jobs found by the ids\n    */\n   @GET\n   @ResponseParser(ParseJobListFromJsonResponse.class)\n   @Path(\"/grid/job/get\")\n   Set<Job> getJobsById(@BinderParam(BindIdsToQueryParams.class) long... ids);\n\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/features/GridLoadBalancerApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.features;\n\nimport static org.jclouds.gogrid.reference.GoGridHeaders.VERSION;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.ID_KEY;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.LOOKUP_LIST_KEY;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.NAME_KEY;\n\nimport java.util.List;\nimport java.util.Set;\n\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.QueryParam;\n\nimport org.jclouds.gogrid.binders.BindIdsToQueryParams;\nimport org.jclouds.gogrid.binders.BindNamesToQueryParams;\nimport org.jclouds.gogrid.binders.BindRealIpPortPairsToQueryParams;\nimport org.jclouds.gogrid.binders.BindVirtualIpPortPairToQueryParams;\nimport org.jclouds.gogrid.domain.IpPortPair;\nimport org.jclouds.gogrid.domain.LoadBalancer;\nimport org.jclouds.gogrid.domain.Option;\nimport org.jclouds.gogrid.filters.SharedKeyLiteAuthentication;\nimport org.jclouds.gogrid.functions.ParseLoadBalancerFromJsonResponse;\nimport org.jclouds.gogrid.functions.ParseLoadBalancerListFromJsonResponse;\nimport org.jclouds.gogrid.functions.ParseOptionsFromJsonResponse;\nimport org.jclouds.gogrid.options.AddLoadBalancerOptions;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\n\n@RequestFilters(SharedKeyLiteAuthentication.class)\n@QueryParams(keys = VERSION, values = \"{jclouds.api-version}\")\npublic interface GridLoadBalancerApi {\n\n\n   /**\n    * Returns all load balancers found for the current user.\n    *\n    * @return load balancers found\n    */\n   @GET\n   @ResponseParser(ParseLoadBalancerListFromJsonResponse.class)\n   @Path(\"/grid/loadbalancer/list\")\n   Set<LoadBalancer> getLoadBalancerList();\n\n   /**\n    * Returns the load balancer(s) by unique name(s).\n    *\n    * Given a name or a set of names, finds one or multiple load balancers.\n    *\n    * @param names\n    *           to get the load balancers\n    * @return load balancer(s) matching the name(s)\n    */\n   @GET\n   @ResponseParser(ParseLoadBalancerListFromJsonResponse.class)\n   @Path(\"/grid/loadbalancer/get\")\n   Set<LoadBalancer> getLoadBalancersByName(\n           @BinderParam(BindNamesToQueryParams.class) String... names);\n\n   /**\n    * Returns the load balancer(s) by unique id(s).\n    *\n    * Given an id or a set of ids, finds one or multiple load balancers.\n    *\n    * @param ids\n    *           to get the load balancers\n    * @return load balancer(s) matching the ids\n    */\n   @GET\n   @ResponseParser(ParseLoadBalancerListFromJsonResponse.class)\n   @Path(\"/grid/loadbalancer/get\")\n   Set<LoadBalancer> getLoadBalancersById(\n           @BinderParam(BindIdsToQueryParams.class) Long... ids);\n\n   /**\n    * Creates a load balancer with given properties.\n    *\n    * @param name\n    *           name of the load balancer\n    * @param virtualIp\n    *           virtual IP with IP address set in {@link org.jclouds.gogrid.domain.Ip#ip} and port\n    *           set in {@link IpPortPair#port}\n    * @param realIps\n    *           real IPs to bind the virtual IP to, with IP address set in\n    *           {@link org.jclouds.gogrid.domain.Ip#ip} and port set in {@link IpPortPair#port}\n    * @param options\n    *           options that specify load balancer's type (round robin, least load), persistence\n    *           strategy, or description.\n    * @return created load balancer object\n    */\n   @GET\n   @ResponseParser(ParseLoadBalancerFromJsonResponse.class)\n   @Path(\"/grid/loadbalancer/add\")\n   LoadBalancer addLoadBalancer(@QueryParam(NAME_KEY) String name,\n                                @BinderParam(BindVirtualIpPortPairToQueryParams.class) IpPortPair virtualIp,\n                                @BinderParam(BindRealIpPortPairsToQueryParams.class) List<IpPortPair> realIps,\n                                AddLoadBalancerOptions... options);\n\n   /**\n    * Edits the existing load balancer to change the real IP mapping.\n    *\n    * @param name\n    *           id of the existing load balancer\n    * @param realIps\n    *           real IPs to bind the virtual IP to, with IP address set in\n    *           {@link org.jclouds.gogrid.domain.Ip#ip} and port set in {@link IpPortPair#port}\n    * @return edited object\n    */\n   @GET\n   @ResponseParser(ParseLoadBalancerFromJsonResponse.class)\n   @Path(\"/grid/loadbalancer/edit\")\n   LoadBalancer editLoadBalancerNamed(@QueryParam(NAME_KEY) String name,\n                                      @BinderParam(BindRealIpPortPairsToQueryParams.class) List<IpPortPair> realIps);\n\n   /**\n    * Edits the existing load balancer to change the real IP mapping.\n    *\n    * @param id\n    *           name of the existing load balancer\n    * @param realIps\n    *           real IPs to bind the virtual IP to, with IP address set in\n    *           {@link org.jclouds.gogrid.domain.Ip#ip} and port set in {@link IpPortPair#port}\n    * @return edited object\n    */\n   @GET\n   @ResponseParser(ParseLoadBalancerFromJsonResponse.class)\n   @Path(\"/grid/loadbalancer/edit\")\n   LoadBalancer editLoadBalancer(@QueryParam(ID_KEY) long id,\n                                 @BinderParam(BindRealIpPortPairsToQueryParams.class) List<IpPortPair> realIps);\n\n   /**\n    * Deletes the load balancer by Id\n    *\n    * @param id\n    *           id of the load balancer to delete\n    * @return load balancer before the command is executed\n    */\n   @GET\n   @ResponseParser(ParseLoadBalancerFromJsonResponse.class)\n   @Path(\"/grid/loadbalancer/delete\")\n   LoadBalancer deleteById(@QueryParam(ID_KEY) Long id);\n\n   /**\n    * Deletes the load balancer by name;\n    *\n    * NOTE: Using this parameter may generate an error if one or more load balancers share a\n    * non-unique name.\n    *\n    * @param name\n    *           name of the load balancer to be deleted\n    *\n    * @return load balancer before the command is executed\n    */\n   @GET\n   @ResponseParser(ParseLoadBalancerFromJsonResponse.class)\n   @Path(\"/grid/loadbalancer/delete\")\n   LoadBalancer deleteByName(@QueryParam(NAME_KEY) String name);\n\n   /**\n    * Retrieves the list of supported Datacenters to launch servers into. The objects will have\n    * datacenter ID, name and description. In most cases, id or name will be used for\n    * {@link #addLoadBalancer}.\n    *\n    * @return supported datacenters\n    */\n   @GET\n   @ResponseParser(ParseOptionsFromJsonResponse.class)\n   @Path(\"/common/lookup/list\")\n   @QueryParams(keys = LOOKUP_LIST_KEY, values = \"loadbalancer.datacenter\")\n   Set<Option> getDatacenters();\n\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/features/GridServerApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.features;\n\nimport static org.jclouds.gogrid.reference.GoGridHeaders.VERSION;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.ID_KEY;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.IMAGE_KEY;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.IP_KEY;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.LOOKUP_LIST_KEY;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.NAME_KEY;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.POWER_KEY;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.SERVER_ID_OR_NAME_KEY;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.SERVER_RAM_KEY;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.QueryParam;\n\nimport org.jclouds.Fallbacks;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.gogrid.binders.BindIdsToQueryParams;\nimport org.jclouds.gogrid.binders.BindNamesToQueryParams;\nimport org.jclouds.gogrid.domain.Option;\nimport org.jclouds.gogrid.domain.PowerCommand;\nimport org.jclouds.gogrid.domain.Server;\nimport org.jclouds.gogrid.filters.SharedKeyLiteAuthentication;\nimport org.jclouds.gogrid.functions.ParseCredentialsFromJsonResponse;\nimport org.jclouds.gogrid.functions.ParseOptionsFromJsonResponse;\nimport org.jclouds.gogrid.functions.ParseServerNameToCredentialsMapFromJsonResponse;\nimport org.jclouds.gogrid.options.AddServerOptions;\nimport org.jclouds.gogrid.options.GetServerListOptions;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.OnlyElement;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SelectJson;\n\n/**\n * Provides synchronous access to GoGrid.\n * <p/>\n * \n * @see <a href=\"http://wiki.gogrid.com/wiki/index.php/API\" />\n */\n@RequestFilters(SharedKeyLiteAuthentication.class)\n@QueryParams(keys = VERSION, values = \"1.6\")\npublic interface GridServerApi {\n\n   /**\n    * Returns the list of all servers.\n    *\n    * The result can be narrowed down by providing the options.\n    *\n    * @param getServerListOptions\n    *           options to narrow down the result\n    * @return servers found by the request\n    */\n   @GET\n   @SelectJson(\"list\")\n   @Fallback(Fallbacks.EmptySetOnNotFoundOr404.class)\n   @Path(\"/grid/server/list\")\n   Set<Server> getServerList(GetServerListOptions... getServerListOptions);\n\n   /**\n    * Returns the server(s) by unique name(s).\n    *\n    * Given a name or a set of names, finds one or multiple servers.\n    *\n    * @param names\n    *           to get the servers\n    * @return server(s) matching the name(s)\n    */\n   @GET\n   @SelectJson(\"list\")\n   @Fallback(Fallbacks.EmptySetOnNotFoundOr404.class)\n   @Path(\"/grid/server/get\")\n   Set<Server> getServersByName(\n           @BinderParam(BindNamesToQueryParams.class) String... names);\n\n   /**\n    * Returns the server(s) by unique id(s).\n    *\n    * Given an id or a set of ids, finds one or multiple servers.\n    *\n    * @param ids\n    *           to get the servers\n    * @return server(s) matching the ids\n    */\n   @GET\n   @SelectJson(\"list\")\n   @Fallback(Fallbacks.EmptySetOnNotFoundOr404.class)\n   @Path(\"/grid/server/get\")\n   Set<Server> getServersById(\n           @BinderParam(BindIdsToQueryParams.class) long... ids);\n\n   /**\n    * Returns a map of running servers' names to the log in credentials.\n    *\n    * @return map <String server name => Credentials>\n    */\n   @GET\n   @ResponseParser(ParseServerNameToCredentialsMapFromJsonResponse.class)\n   @Path(\"/support/password/list\")\n   Map<String, Credentials> getServerCredentialsList();\n\n   /**\n    *\n    * @return the login user and password of a server, or null if none found\n    */\n   @GET\n   @ResponseParser(ParseCredentialsFromJsonResponse.class)\n   @Path(\"/support/grid/password/get\")\n   Credentials getServerCredentials(@QueryParam(\"id\") long id);\n\n   /**\n    * Adds a server with specified attributes\n    *\n    * @param name\n    *           name of the server\n    * @param image\n    *           image (id or name)\n    * @param ram\n    *           ram type (id or name)\n    * @param ip\n    *           ip address\n    * @param addServerOptions\n    *           options to make it a sandbox instance or/and description\n    * @return created server\n    */\n   @GET\n   @SelectJson(\"list\")\n   @OnlyElement\n   @Path(\"/grid/server/add\")\n   Server addServer(@QueryParam(NAME_KEY) String name,\n                    @QueryParam(IMAGE_KEY) String image, @QueryParam(SERVER_RAM_KEY) String ram,\n                    @QueryParam(IP_KEY) String ip, AddServerOptions... addServerOptions);\n\n   /**\n    * Changes the server's state according to {@link PowerCommand}\n    *\n    * @param idOrName\n    *           id or name of the server to apply the command\n    * @param power\n    *           new desired state\n    * @return server immediately after applying the command\n    */\n   @GET\n   @SelectJson(\"list\")\n   @OnlyElement\n   @Path(\"/grid/server/power\")\n   Server power(\n           @QueryParam(SERVER_ID_OR_NAME_KEY) String idOrName,\n           @QueryParam(POWER_KEY) PowerCommand power);\n\n   /**\n    * Deletes the server by Id\n    *\n    * @param id\n    *           id of the server to delete\n    * @return server before the command is executed\n    */\n   @GET\n   @SelectJson(\"list\")\n   @OnlyElement\n   @Path(\"/grid/server/delete\")\n   @Fallback(Fallbacks.NullOnNotFoundOr404.class)\n   Server deleteById(@QueryParam(ID_KEY) long id);\n\n   /**\n    * Deletes the server by name;\n    *\n    * NOTE: Using this parameter may generate an error if one or more servers\n    * share a non-unique name.\n    *\n    * @param name\n    *           name of the server to be deleted\n    *\n    * @return server before the command is executed\n    */\n   @GET\n   @SelectJson(\"list\")\n   @OnlyElement\n   @Path(\"/grid/server/delete\")\n   @Fallback(Fallbacks.NullOnNotFoundOr404.class)\n   Server deleteByName(@QueryParam(NAME_KEY) String name);\n\n   /**\n    * Retrieves the list of supported RAM configurations. The objects will have\n    * RAM ID, name and description. In most cases, id or name will be used for\n    * {@link #addServer}.\n    *\n    * To see how RAM maps to CPU and disk space (as of March 2010), see\n    * {@link org.jclouds.gogrid.compute.config.GoGridComputeServiceContextModule#provideSizeToRam}\n    * .\n    *\n    * @return supported ram sizes\n    */\n   @GET\n   @ResponseParser(ParseOptionsFromJsonResponse.class)\n   @Path(\"/common/lookup/list\")\n   @QueryParams(keys = LOOKUP_LIST_KEY, values = \"server.ram\")\n   Set<Option> getRamSizes();\n\n   /**\n    * Retrieves the list of supported server types, for example Web/App Server and Database Server. In most cases, id\n    * or name will be used for {@link #editServerType}.\n    *\n    * @return supported server types\n    */\n   @GET\n   @ResponseParser(ParseOptionsFromJsonResponse.class)\n   @Path(\"/common/lookup/list\")\n   @QueryParams(keys = LOOKUP_LIST_KEY, values = \"server.type\")\n   Set<Option> getTypes();\n\n   /**\n    * Retrieves the list of supported Datacenters to launch servers into. The\n    * objects will have datacenter ID, name and description. In most cases, id\n    * or name will be used for {@link #addServer}.\n    *\n    * @return supported datacenters\n    */\n   @GET\n   @ResponseParser(ParseOptionsFromJsonResponse.class)\n   @Path(\"/common/lookup/list\")\n   @QueryParams(keys = LOOKUP_LIST_KEY, values = \"server.datacenter\")\n   Set<Option> getDatacenters();\n\n   /**\n    * Edits an existing server\n    *\n    * @param id\n    *           id of the existing server\n    * @param newDescription\n    *           description to replace the current one\n    * @return edited server\n    */\n   @GET\n   @SelectJson(\"list\")\n   @OnlyElement\n   @Path(\"/grid/server/edit\")\n   Server editServerDescription(@QueryParam(\"id\") long id,\n                                @QueryParam(\"description\") String newDescription);\n\n   /**\n    * Edits an existing server\n    *\n    * @param id\n    *           id of the existing server\n    * @param ram\n    *           ram to replace the current one\n    * @return edited server\n    */\n   @GET\n   @SelectJson(\"list\")\n   @OnlyElement\n   @Path(\"/grid/server/edit\")\n   Server editServerRam(@QueryParam(\"id\") long id,\n                        @QueryParam(\"server.ram\") String ram);\n\n   /**\n    * Edits an existing server\n    *\n    * @param id\n    *           id of the existing server\n    * @param newType\n    *           type to replace the current one\n    * @return edited server\n    */\n   @GET\n   @SelectJson(\"list\")\n   @OnlyElement\n   @Path(\"/grid/server/edit\")\n   Server editServerType(@QueryParam(\"id\") long id,\n                         @QueryParam(\"server.type\") String newType);\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/filters/SharedKeyLiteAuthentication.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.filters;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.hash.Hashing.md5;\nimport static com.google.common.io.BaseEncoding.base16;\nimport static java.lang.String.format;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\n\nimport org.jclouds.Constants;\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpRequestFilter;\nimport org.jclouds.http.HttpUtils;\nimport org.jclouds.location.Provider;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableMap;\n\npublic class SharedKeyLiteAuthentication implements HttpRequestFilter {\n\n   private final Supplier<Credentials> creds;\n   private final Long timeStamp;\n   private final HttpUtils utils;\n\n   @Resource\n   @Named(Constants.LOGGER_SIGNATURE)\n   Logger signatureLog = Logger.NULL;\n\n   @Inject\n   public SharedKeyLiteAuthentication(@Provider Supplier<Credentials> creds, @TimeStamp Long timeStamp, HttpUtils utils) {\n      this.creds = creds;\n      this.timeStamp = timeStamp;\n      this.utils = utils;\n   }\n\n   @Override\n   public HttpRequest filter(HttpRequest request) {\n      String toSign = createStringToSign();\n      String signatureMd5 = getMd5For(toSign);\n      request = request.toBuilder()\n            .replaceQueryParams(ImmutableMap.of(\"sig\", signatureMd5, \"api_key\", creds.get().identity)).build();\n      utils.logRequest(signatureLog, request, \"<<\");\n      return request;\n   }\n\n   private String createStringToSign() {\n      return format(\"%s%s%s\", creds.get().identity, creds.get().credential, timeStamp);\n   }\n\n   private String getMd5For(String stringToHash) {\n      return base16().lowerCase().encode(md5().hashString(stringToHash, UTF_8).asBytes());\n   }\n\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/functions/GenericResponseContainer.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.functions;\n\nimport java.util.SortedSet;\n\n/**\n * General format of GoGrid's response.\n * \n * This is the view for most responses, and the actual result (or error) will\n * be set to {@link #list}. Note that even the single returned item will be set\n * to {@link #list} per GoGrid's design.\n * \n * This class is not intended to be used by customers directly, it is here to\n * assist in deserialization.\n */\npublic class GenericResponseContainer<T> {\n\n   private Summary summary;\n   private String status;\n   private String method;\n   private SortedSet<T> list;\n\n   public Summary getSummary() {\n      return summary;\n   }\n\n   public String getStatus() {\n      return status;\n   }\n\n   public String getMethod() {\n      return method;\n   }\n\n   public SortedSet<T> getList() {\n      return list;\n   }\n\n   static class Summary {\n      private int total;\n      private int start;\n      private int numPages;\n      private int returned;\n\n      public int getTotal() {\n         return total;\n      }\n\n      public int getStart() {\n         return start;\n      }\n\n      public int getNumPages() {\n         return numPages;\n      }\n\n      public int getReturned() {\n         return returned;\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/functions/ParseCredentialsFromJsonResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.functions;\n\nimport static com.google.common.base.Preconditions.checkState;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpResponse;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.Iterables;\n\n@Singleton\npublic class ParseCredentialsFromJsonResponse implements\n      Function<HttpResponse, Credentials> {\n\n   private final ParseServerNameToCredentialsMapFromJsonResponse parser;\n\n   @Inject\n   ParseCredentialsFromJsonResponse(\n         ParseServerNameToCredentialsMapFromJsonResponse parser) {\n      this.parser = parser;\n   }\n\n   @Override\n   public Credentials apply(HttpResponse input) {\n      Map<String, Credentials> returnVal = parser.apply(input);\n      checkState(!(returnVal.size() > 1),\n            \"expecting only 1 credential in response, but had more: \"\n                  + returnVal.keySet());\n      return (!returnVal.isEmpty()) ? Iterables.getOnlyElement(returnVal.values()) : null;\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/functions/ParseImageFromJsonResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.functions;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.gogrid.domain.ServerImage;\nimport org.jclouds.http.HttpResponse;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.Iterables;\nimport com.google.inject.Singleton;\n\n@Singleton\npublic class ParseImageFromJsonResponse implements\n      Function<HttpResponse, ServerImage> {\n   private final ParseImageListFromJsonResponse parser;\n\n   @Inject\n   ParseImageFromJsonResponse(ParseImageListFromJsonResponse parser) {\n      this.parser = parser;\n   }\n\n   @Override\n   public ServerImage apply(HttpResponse arg0) {\n      return Iterables.getOnlyElement(parser.apply(arg0));\n   }\n\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/functions/ParseImageListFromJsonResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.functions;\n\nimport java.util.SortedSet;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.gogrid.domain.ServerImage;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseJson;\n\nimport com.google.common.base.Function;\nimport com.google.inject.Singleton;\n\n@Singleton\npublic class ParseImageListFromJsonResponse implements\n      Function<HttpResponse, SortedSet<ServerImage>> {\n\n   private final ParseJson<GenericResponseContainer<ServerImage>> json;\n\n   @Inject\n   ParseImageListFromJsonResponse(\n         ParseJson<GenericResponseContainer<ServerImage>> json) {\n      this.json = json;\n   }\n\n   @Override\n   public SortedSet<ServerImage> apply(HttpResponse arg0) {\n      return json.apply(arg0).getList();\n   }\n\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/functions/ParseIpListFromJsonResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.functions;\n\nimport java.util.SortedSet;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.gogrid.domain.Ip;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseJson;\n\nimport com.google.common.base.Function;\nimport com.google.inject.Singleton;\n\n/**\n * Parses {@link org.jclouds.gogrid.domain.Ip ips} from a json string.\n */\n@Singleton\npublic class ParseIpListFromJsonResponse implements\n      Function<HttpResponse, SortedSet<Ip>> {\n\n   private final ParseJson<GenericResponseContainer<Ip>> json;\n\n   @Inject\n   ParseIpListFromJsonResponse(ParseJson<GenericResponseContainer<Ip>> json) {\n      this.json = json;\n   }\n\n   @Override\n   public SortedSet<Ip> apply(HttpResponse arg0) {\n      return json.apply(arg0).getList();\n   }\n\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/functions/ParseJobListFromJsonResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.functions;\n\nimport java.util.SortedSet;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.gogrid.domain.Job;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseJson;\n\nimport com.google.common.base.Function;\nimport com.google.inject.Singleton;\n\n/**\n * Parses {@link org.jclouds.gogrid.domain.Job jobs} from a json string.\n */\n@Singleton\npublic class ParseJobListFromJsonResponse implements\n      Function<HttpResponse, SortedSet<Job>> {\n\n   private final ParseJson<GenericResponseContainer<Job>> json;\n\n   @Inject\n   ParseJobListFromJsonResponse(ParseJson<GenericResponseContainer<Job>> json) {\n      this.json = json;\n   }\n\n   @Override\n   public SortedSet<Job> apply(HttpResponse arg0) {\n      return json.apply(arg0).getList();\n   }\n\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/functions/ParseLoadBalancerFromJsonResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.functions;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.gogrid.domain.LoadBalancer;\nimport org.jclouds.http.HttpResponse;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.Iterables;\nimport com.google.inject.Singleton;\n\n/**\n * Parses the single load balancer out of the response.\n * \n * This class delegates parsing to {@link ParseLoadBalancerListFromJsonResponse}\n * .\n */\n@Singleton\npublic class ParseLoadBalancerFromJsonResponse implements\n      Function<HttpResponse, LoadBalancer> {\n   private final ParseLoadBalancerListFromJsonResponse parser;\n\n   @Inject\n   ParseLoadBalancerFromJsonResponse(\n         ParseLoadBalancerListFromJsonResponse parser) {\n      this.parser = parser;\n   }\n\n   @Override\n   public LoadBalancer apply(HttpResponse arg0) {\n      return Iterables.getOnlyElement(parser.apply(arg0));\n   }\n\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/functions/ParseLoadBalancerListFromJsonResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.functions;\n\nimport java.util.SortedSet;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.gogrid.domain.LoadBalancer;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseJson;\n\nimport com.google.common.base.Function;\nimport com.google.inject.Singleton;\n\n/**\n * Parses {@link org.jclouds.gogrid.domain.LoadBalancer jobs} from a json\n * string.\n */\n@Singleton\npublic class ParseLoadBalancerListFromJsonResponse implements\n      Function<HttpResponse, SortedSet<LoadBalancer>> {\n\n   private final ParseJson<GenericResponseContainer<LoadBalancer>> json;\n\n   @Inject\n   ParseLoadBalancerListFromJsonResponse(\n         ParseJson<GenericResponseContainer<LoadBalancer>> json) {\n      this.json = json;\n   }\n\n   @Override\n   public SortedSet<LoadBalancer> apply(HttpResponse arg0) {\n      return json.apply(arg0).getList();\n   }\n\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/functions/ParseOptionsFromJsonResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.functions;\n\nimport java.util.SortedSet;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.gogrid.domain.Option;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseJson;\n\nimport com.google.common.base.Function;\nimport com.google.inject.Singleton;\n\n/**\n * Parses the list of generic options.\n * \n * GoGrid uses options as containers for id/name/description objects.\n */\n@Singleton\npublic class ParseOptionsFromJsonResponse implements\n      Function<HttpResponse, SortedSet<Option>> {\n\n   private final ParseJson<GenericResponseContainer<Option>> json;\n\n   @Inject\n   ParseOptionsFromJsonResponse(ParseJson<GenericResponseContainer<Option>> json) {\n      this.json = json;\n   }\n\n   @Override\n   public SortedSet<Option> apply(HttpResponse arg0) {\n      return json.apply(arg0).getList();\n   }\n\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/functions/ParseServerNameToCredentialsMapFromJsonResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.gogrid.domain.Server;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Objects;\nimport com.google.common.collect.Maps;\n\n@Singleton\npublic class ParseServerNameToCredentialsMapFromJsonResponse implements\n      Function<HttpResponse, Map<String, Credentials>> {\n   private final ParseJson<GenericResponseContainer<Password>> json;\n\n   @Inject\n   ParseServerNameToCredentialsMapFromJsonResponse(\n         ParseJson<GenericResponseContainer<Password>> json) {\n      this.json = json;\n   }\n\n   // incidental view class to assist in getting the correct data\n   // deserialized from json\n   private static class Password implements Comparable<Password> {\n      @Named(\"username\")\n      private final String userName;\n      private final String password;\n      private final Server server;\n\n      @ConstructorProperties({\"username\", \"password\", \"server\"})\n      public Password(String userName, String password, @Nullable Server server) {\n         this.userName = checkNotNull(userName, \"username\");\n         this.password = checkNotNull(password, \"password\");\n         this.server = server;\n      }\n\n      public String getUserName() {\n         return userName;\n      }\n\n      public String getPassword() {\n         return password;\n      }\n\n      public Server getServer() {\n         return server;\n      }\n\n      @Override\n      public boolean equals(Object o) {\n         if (this == o)\n            return true;\n         if (o == null || getClass() != o.getClass())\n            return false;\n\n         Password other = (Password) o;\n         return Objects.equal(userName, other.userName)\n               && Objects.equal(password, other.password)\n               && Objects.equal(server, other.server);\n      }\n\n      @Override\n      public int hashCode() {\n         return Objects.hashCode(userName, password, server);\n      }\n\n      @Override\n      public int compareTo(Password o) {\n         if (null == o.getServer()) return null == server ? 0 : -1;\n         if (server == null) return 1;\n         return server.getName().compareTo(o.getServer().getName());\n      }\n   }\n\n   @Override\n   public Map<String, Credentials> apply(HttpResponse arg0) {\n      Map<String, Credentials> serverNameToCredentials = Maps.newHashMap();\n      for (Password password : json.apply(arg0).getList()) {\n         if (null != password.getServer())\n            serverNameToCredentials.put(password.getServer().getName(),\n                  new Credentials(password.getUserName(), password.getPassword()));\n      }\n      return serverNameToCredentials;\n   }\n\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/functions/internal/CustomDeserializers.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.functions.internal;\n\nimport java.lang.reflect.Type;\n\nimport org.jclouds.gogrid.domain.IpState;\nimport org.jclouds.gogrid.domain.JobState;\nimport org.jclouds.gogrid.domain.LoadBalancerOs;\nimport org.jclouds.gogrid.domain.LoadBalancerPersistenceType;\nimport org.jclouds.gogrid.domain.LoadBalancerState;\nimport org.jclouds.gogrid.domain.LoadBalancerType;\nimport org.jclouds.gogrid.domain.ObjectType;\nimport org.jclouds.gogrid.domain.ServerImageState;\nimport org.jclouds.gogrid.domain.ServerImageType;\nimport org.jclouds.gogrid.domain.ServerState;\n\nimport com.google.gson.JsonDeserializationContext;\nimport com.google.gson.JsonDeserializer;\nimport com.google.gson.JsonElement;\nimport com.google.gson.JsonObject;\nimport com.google.gson.JsonParseException;\n\npublic class CustomDeserializers {\n\n   public static class ServerStateAdapter implements JsonDeserializer<ServerState> {\n      @Override\n      public ServerState deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context)\n            throws JsonParseException {\n         String name = ((JsonObject) jsonElement).get(\"name\").getAsString();\n         return ServerState.fromValue(name);\n      }\n   }\n\n   public static class ObjectTypeAdapter implements JsonDeserializer<ObjectType> {\n      @Override\n      public ObjectType deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context)\n            throws JsonParseException {\n         String name = ((JsonObject) jsonElement).get(\"name\").getAsString();\n         return ObjectType.fromValue(name);\n      }\n   }\n\n   public static class LoadBalancerOsAdapter implements JsonDeserializer<LoadBalancerOs> {\n      @Override\n      public LoadBalancerOs deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context)\n            throws JsonParseException {\n         String name = ((JsonObject) jsonElement).get(\"name\").getAsString();\n         return LoadBalancerOs.fromValue(name);\n      }\n   }\n\n   public static class LoadBalancerStateAdapter implements JsonDeserializer<LoadBalancerState> {\n      @Override\n      public LoadBalancerState deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context)\n            throws JsonParseException {\n         String name = ((JsonObject) jsonElement).get(\"name\").getAsString();\n         return LoadBalancerState.fromValue(name);\n      }\n   }\n\n   public static class LoadBalancerPersistenceTypeAdapter implements JsonDeserializer<LoadBalancerPersistenceType> {\n      @Override\n      public LoadBalancerPersistenceType deserialize(JsonElement jsonElement, Type type,\n            JsonDeserializationContext context) throws JsonParseException {\n         String name = ((JsonObject) jsonElement).get(\"name\").getAsString();\n         return LoadBalancerPersistenceType.fromValue(name);\n      }\n   }\n\n   public static class LoadBalancerTypeAdapter implements JsonDeserializer<LoadBalancerType> {\n      @Override\n      public LoadBalancerType deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context)\n            throws JsonParseException {\n         String name = ((JsonObject) jsonElement).get(\"name\").getAsString();\n         return LoadBalancerType.fromValue(name);\n      }\n   }\n\n   public static class IpStateAdapter implements JsonDeserializer<IpState> {\n      @Override\n      public IpState deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context)\n            throws JsonParseException {\n         String name = ((JsonObject) jsonElement).get(\"name\").getAsString();\n         return IpState.fromValue(name);\n      }\n   }\n\n   public static class JobStateAdapter implements JsonDeserializer<JobState> {\n      @Override\n      public JobState deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context)\n            throws JsonParseException {\n         String name = ((JsonObject) jsonElement).get(\"name\").getAsString();\n         return JobState.fromValue(name);\n      }\n   }\n\n   public static class ServerImageStateAdapter implements JsonDeserializer<ServerImageState> {\n      @Override\n      public ServerImageState deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context)\n            throws JsonParseException {\n         String name = ((JsonObject) jsonElement).get(\"name\").getAsString();\n         return ServerImageState.fromValue(name);\n      }\n   }\n\n   public static class ServerImageTypeAdapter implements JsonDeserializer<ServerImageType> {\n      @Override\n      public ServerImageType deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context)\n            throws JsonParseException {\n         String name = ((JsonObject) jsonElement).get(\"name\").getAsString();\n         return ServerImageType.fromValue(name);\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/handlers/GoGridErrorHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.handlers;\n\nimport static org.jclouds.http.HttpUtils.closeClientButKeepContentStream;\nimport static org.jclouds.http.HttpUtils.releasePayload;\n\nimport java.io.ByteArrayInputStream;\nimport java.util.Set;\n\nimport org.jclouds.gogrid.GoGridResponseException;\nimport org.jclouds.gogrid.domain.internal.ErrorResponse;\nimport org.jclouds.gogrid.functions.GenericResponseContainer;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.ResourceNotFoundException;\n\nimport com.google.common.collect.Iterables;\nimport com.google.inject.Inject;\n\npublic class GoGridErrorHandler implements HttpErrorHandler {\n\n   private final ParseJson<GenericResponseContainer<ErrorResponse>> errorParser;\n\n   @Inject\n   public GoGridErrorHandler(ParseJson<GenericResponseContainer<ErrorResponse>> errorParser) {\n      this.errorParser = errorParser;\n   }\n\n   @Override\n   public void handleError(HttpCommand command, HttpResponse response) {\n      try {\n         // it is important to always read fully and close streams\n         byte[] data = closeClientButKeepContentStream(response);\n         String message = data != null ? new String(data) : null;\n\n         Exception exception = message != null ? new HttpResponseException(command, response, message)\n                  : new HttpResponseException(command, response);\n         Set<ErrorResponse> errors = parseErrorsFromContentOrNull(data);\n         if (errors != null)\n            exception = new GoGridResponseException(command, response, errors);\n         switch (response.getStatusCode()) {\n            case 400:\n               if (Iterables.get(errors, 0).getMessage().indexOf(\"No object found\") != -1) {\n                  exception = new ResourceNotFoundException(Iterables.get(errors, 0).getMessage(), exception);\n                  break;\n               }\n               break;\n            case 403:\n               exception = new AuthorizationException(exception.getMessage(), exception);\n               break;\n         }\n         command.setException(exception);\n      } finally {\n         releasePayload(response);\n      }\n   }\n\n   Set<ErrorResponse> parseErrorsFromContentOrNull(byte[] response) {\n      if (response != null) {\n         try {\n            return errorParser.apply(new ByteArrayInputStream(response)).getList();\n         } catch (/* Parsing */Exception e) {\n            return null;\n         }\n      }\n      return null;\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/location/GoGridDefaultLocationSupplier.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.location;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TEMPLATE;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.domain.Location;\nimport org.jclouds.location.suppliers.ImplicitLocationSupplier;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Splitter;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.Iterables;\n\n@Singleton\npublic class GoGridDefaultLocationSupplier implements ImplicitLocationSupplier {\n   private final Supplier<Set<? extends Location>> locations;\n   private final String defaultDC;\n\n   @Inject\n   GoGridDefaultLocationSupplier(@Memoized Supplier<Set<? extends Location>> locations, @Named(TEMPLATE) String template) {\n      this.locations = locations;\n      Map<String, String> map = Splitter.on(',').trimResults().withKeyValueSeparator(\"=\").split(template);\n      //TODO: move to real ImplicitLocationSupplier\n      this.defaultDC = checkNotNull(map.get(\"locationId\"), \"locationId not in % value: %s\", TEMPLATE, template);\n   }\n\n   @Override\n   public Location get() {\n      return Iterables.find(locations.get(), new Predicate<Location>() {\n\n         @Override\n         public boolean apply(Location input) {\n            return input.getId().equals(defaultDC);\n         }\n\n      });\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/options/AddLoadBalancerOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.options;\n\nimport static com.google.common.base.Preconditions.checkState;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.DESCRIPTION_KEY;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.LOAD_BALANCER_PERSISTENCE_TYPE_KEY;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.LOAD_BALANCER_TYPE_KEY;\n\nimport org.jclouds.gogrid.domain.LoadBalancerPersistenceType;\nimport org.jclouds.gogrid.domain.LoadBalancerType;\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\n/**\n * Optional parameters for adding a load balancer.\n *\n * @see org.jclouds.gogrid.features.GridLoadBalancerApi#addLoadBalancer\n * @see <a href=\"http://wiki.gogrid.com/wiki/index.php/API:grid.loadbalancer.add\"/>\n */\npublic class AddLoadBalancerOptions extends BaseHttpRequestOptions {\n\n    public AddLoadBalancerOptions setDescription(String description) {\n        checkState(!queryParameters.containsKey(DESCRIPTION_KEY), \"Can't have duplicate \" +\n                \"load balancer description\");\n        queryParameters.put(DESCRIPTION_KEY, description);\n        return this;\n    }\n\n    public AddLoadBalancerOptions setType(LoadBalancerType loadBalancerType) {\n        checkState(!queryParameters.containsKey(LOAD_BALANCER_TYPE_KEY), \"Can't have duplicate \" +\n                \"load balancer type limitation\");\n        queryParameters.put(LOAD_BALANCER_TYPE_KEY, loadBalancerType.toString());\n        return this;\n    }\n\n    public AddLoadBalancerOptions setPersistenceType(LoadBalancerPersistenceType loadBalancerPersistenceType) {\n        checkState(!queryParameters.containsKey(LOAD_BALANCER_PERSISTENCE_TYPE_KEY), \"Can't have duplicate \" +\n                \"load balancer type limitation\");\n        queryParameters.put(LOAD_BALANCER_PERSISTENCE_TYPE_KEY, loadBalancerPersistenceType.toString());\n        return this;\n    }\n\n    public static class Builder {\n        public AddLoadBalancerOptions create(LoadBalancerType type,\n                                             LoadBalancerPersistenceType persistenceType) {\n            return new AddLoadBalancerOptions().setType(type).setPersistenceType(persistenceType);\n        }\n    }\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/options/AddServerOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.options;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkState;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.DESCRIPTION_KEY;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.IS_SANDBOX_KEY;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\npublic class AddServerOptions extends BaseHttpRequestOptions {\n\n   public AddServerOptions withDescription(String description) {\n      checkArgument(description.length() <= 500, \"Description cannot be longer than 500 characters\");\n      checkState(!queryParameters.containsKey(DESCRIPTION_KEY),\n               \"Can't have duplicate server description\");\n      queryParameters.put(DESCRIPTION_KEY, description);\n      return this;\n   }\n\n   /**\n    * Make server a sandbox instance. By default, it's not.\n    * \n    * @return itself for convenience\n    */\n   public AddServerOptions asSandboxType() {\n      checkState(!queryParameters.containsKey(IS_SANDBOX_KEY),\n               \"Can only have one sandbox option per server\");\n      queryParameters.put(IS_SANDBOX_KEY, \"true\");\n      return this;\n   }\n\n   public static class Builder {\n      /**\n       * @see AddServerOptions#withDescription(String)\n       */\n      public static AddServerOptions withDescription(String description) {\n         AddServerOptions options = new AddServerOptions();\n         return options.withDescription(description);\n      }\n\n      /**\n       * @see AddServerOptions#asSandboxType()\n       */\n      public static AddServerOptions asSandboxType() {\n         AddServerOptions options = new AddServerOptions();\n         return options.asSandboxType();\n      }\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/options/GetImageListOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.DATACENTER_KEY;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.IMAGE_STATE_KEY;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.IMAGE_TYPE_KEY;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.IS_PUBLIC_KEY;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.MAX_NUMBER_KEY;\n\nimport org.jclouds.gogrid.domain.ServerImageState;\nimport org.jclouds.gogrid.domain.ServerImageType;\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\npublic class GetImageListOptions extends BaseHttpRequestOptions {\n\n   public GetImageListOptions setType(ServerImageType imageType) {\n      checkState(!queryParameters.containsKey(IMAGE_TYPE_KEY), \"Can't have duplicate image type restrictions\");\n      queryParameters.put(IMAGE_TYPE_KEY, imageType.toString());\n      return this;\n   }\n\n   public GetImageListOptions setState(ServerImageState imageState) {\n      checkState(!queryParameters.containsKey(IMAGE_STATE_KEY), \"Can't have duplicate image state restrictions\");\n      queryParameters.put(IMAGE_STATE_KEY, imageState.toString());\n      return this;\n   }\n\n   public GetImageListOptions onlyPublic() {\n      checkState(!queryParameters.containsKey(IS_PUBLIC_KEY), \"Can't have duplicate image visibility restrictions\");\n      queryParameters.put(IS_PUBLIC_KEY, \"true\");\n      return this;\n   }\n\n   public GetImageListOptions onlyPrivate() {\n      checkState(!queryParameters.containsKey(IS_PUBLIC_KEY), \"Can't have duplicate image visibility restrictions\");\n      queryParameters.put(IS_PUBLIC_KEY, \"false\");\n      return this;\n   }\n\n   public GetImageListOptions inDatacenter(String datacenterId) {\n      checkState(!queryParameters.containsKey(DATACENTER_KEY), \"Can't have duplicate datacenter id\");\n      queryParameters.put(DATACENTER_KEY, datacenterId);\n      return this;\n   }\n\n   public GetImageListOptions maxItemsNumber(Integer maxNumber) {\n      checkState(!queryParameters.containsKey(MAX_NUMBER_KEY), \"Can't have duplicate parameter of max returned items\");\n      queryParameters.put(MAX_NUMBER_KEY, maxNumber.toString());\n      return this;\n   }\n\n   public static class Builder {\n      public static GetImageListOptions maxItems(int maxNumber) {\n         return new GetImageListOptions().maxItemsNumber(maxNumber);\n      }\n\n      public static GetImageListOptions inDatacenter(String datacenterId) {\n         return new GetImageListOptions().inDatacenter(checkNotNull(datacenterId, \"datacenterId\"));\n      }\n\n      public static GetImageListOptions publicWebServers() {\n         return new GetImageListOptions().setState(ServerImageState.AVAILABLE).setType(\n                  ServerImageType.WEB_APPLICATION_SERVER).onlyPublic();\n      }\n\n      public static GetImageListOptions publicDatabaseServers() {\n         return new GetImageListOptions().setState(ServerImageState.AVAILABLE).setType(ServerImageType.DATABASE_SERVER)\n                  .onlyPublic();\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/options/GetIpListOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.DATACENTER_KEY;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.IP_STATE_KEY;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.IP_TYPE_KEY;\n\nimport org.jclouds.gogrid.domain.IpState;\nimport org.jclouds.gogrid.domain.IpType;\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\npublic class GetIpListOptions extends BaseHttpRequestOptions {\n\n   public static final GetIpListOptions NONE = new GetIpListOptions();\n\n   public GetIpListOptions onlyAssigned() {\n      checkState(!queryParameters.containsKey(IP_STATE_KEY),\n               \"Can't have multiple values for whether IP is assigned\");\n      queryParameters.put(IP_STATE_KEY, IpState.ASSIGNED.toString());\n      return this;\n   }\n\n   public GetIpListOptions onlyUnassigned() {\n      checkState(!queryParameters.containsKey(IP_STATE_KEY),\n               \"Can't have multiple values for whether IP is assigned\");\n      queryParameters.put(IP_STATE_KEY, IpState.UNASSIGNED.toString());\n      return this;\n   }\n\n   public GetIpListOptions onlyWithType(IpType type) {\n      checkState(!queryParameters.containsKey(IP_TYPE_KEY),\n               \"Can't have multiple values for ip type limit\");\n      queryParameters.put(IP_TYPE_KEY, type.toString());\n      return this;\n   }\n\n   public GetIpListOptions inDatacenter(String datacenterId) {\n      checkState(!queryParameters.containsKey(DATACENTER_KEY), \"Can't have duplicate datacenter id\");\n      queryParameters.put(DATACENTER_KEY, datacenterId);\n      return this;\n   }\n\n   public static class Builder {\n\n      public GetIpListOptions inDatacenter(String datacenterId) {\n         return new GetIpListOptions().inDatacenter(checkNotNull(datacenterId));\n      }\n\n      public GetIpListOptions create() {\n         return new GetIpListOptions();\n      }\n\n      public GetIpListOptions limitToType(IpType type) {\n         return new GetIpListOptions().onlyWithType(type);\n      }\n\n      public GetIpListOptions unassignedPublicIps() {\n         return new GetIpListOptions().onlyWithType(IpType.PUBLIC).onlyUnassigned();\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/options/GetJobListOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.options;\n\nimport static com.google.common.base.Preconditions.checkState;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.END_DATE_KEY;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.JOB_OBJECT_TYPE_KEY;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.JOB_STATE_KEY;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.MAX_NUMBER_KEY;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.OBJECT_KEY;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.OWNER_KEY;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.START_DATE_KEY;\n\nimport java.util.Date;\n\nimport org.jclouds.gogrid.domain.JobState;\nimport org.jclouds.gogrid.domain.ObjectType;\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\npublic class GetJobListOptions extends BaseHttpRequestOptions {\n\n   public static final GetJobListOptions NONE = new GetJobListOptions();\n\n   public GetJobListOptions maxItemsNumber(Integer maxNumber) {\n      checkState(!queryParameters.containsKey(MAX_NUMBER_KEY), \"Can't have duplicate parameter of max returned items\");\n      queryParameters.put(MAX_NUMBER_KEY, maxNumber.toString());\n      return this;\n   }\n\n   public GetJobListOptions withStartDate(Date startDate) {\n      checkState(!queryParameters.containsKey(START_DATE_KEY), \"Can't have duplicate start date for filtering\");\n      queryParameters.put(START_DATE_KEY, String.valueOf(startDate.getTime()));\n      return this;\n   }\n\n   public GetJobListOptions withEndDate(Date endDate) {\n      checkState(!queryParameters.containsKey(END_DATE_KEY), \"Can't have duplicate end date for filtering\");\n      queryParameters.put(END_DATE_KEY, String.valueOf(endDate.getTime()));\n      return this;\n   }\n\n   public GetJobListOptions withOwner(String owner) {\n      checkState(!queryParameters.containsKey(OWNER_KEY), \"Can't have duplicate owner name for filtering\");\n      queryParameters.put(OWNER_KEY, owner);\n      return this;\n   }\n\n   public GetJobListOptions onlyForState(JobState jobState) {\n      checkState(!queryParameters.containsKey(JOB_STATE_KEY), \"Can't have duplicate job state for filtering\");\n      queryParameters.put(JOB_STATE_KEY, jobState.toString());\n      return this;\n   }\n\n   public GetJobListOptions onlyForObjectType(ObjectType objectType) {\n      checkState(!queryParameters.containsKey(JOB_OBJECT_TYPE_KEY), \"Can't have duplicate object type for filtering\");\n      queryParameters.put(JOB_OBJECT_TYPE_KEY, objectType.toString());\n      return this;\n   }\n\n   public GetJobListOptions onlyForObjectName(String objectName) {\n      checkState(!queryParameters.containsKey(OBJECT_KEY), \"Can't have duplicate object name for filtering\");\n      queryParameters.put(OBJECT_KEY, objectName);\n      return this;\n   }\n\n   public GetJobListOptions latestJobForObjectByName(String serverName) {\n      return maxItemsNumber(1).onlyForObjectName(serverName);\n   }\n\n   /*\n    * This method is intended for testing\n    */\n   @Override\n   public boolean equals(Object o) {\n      if (this == o)\n         return true;\n      if (o == null || getClass() != o.getClass())\n         return false;\n\n      GetJobListOptions options = (GetJobListOptions) o;\n\n      return buildQueryParameters().equals(options.buildQueryParameters());\n   }\n\n   @Override\n   public int hashCode() {\n      return buildQueryParameters().hashCode();\n   }\n\n   public static class Builder {\n\n      public static GetJobListOptions maxItems(int maxNumber) {\n         return new GetJobListOptions().maxItemsNumber(maxNumber);\n      }\n      \n      public static GetJobListOptions startDate(Date startDate) {\n         return new GetJobListOptions().withStartDate(startDate);\n      }\n\n      public static GetJobListOptions latestJobForObjectByName(String serverName) {\n         return new GetJobListOptions().latestJobForObjectByName(serverName);\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/options/GetServerListOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.DATACENTER_KEY;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.IS_SANDBOX_KEY;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.SERVER_TYPE_KEY;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\npublic class GetServerListOptions extends BaseHttpRequestOptions {\n\n   public static final GetServerListOptions NONE = new GetServerListOptions();\n\n   public GetServerListOptions limitServerTypeTo(String serverType) {\n      checkState(!queryParameters.containsKey(SERVER_TYPE_KEY),\n               \"Can't have duplicate server type limit\");\n      queryParameters.put(SERVER_TYPE_KEY, serverType);\n      return this;\n   }\n\n   public GetServerListOptions inDatacenter(String datacenterId) {\n      checkState(!queryParameters.containsKey(DATACENTER_KEY), \"Can't have duplicate datacenter id\");\n      queryParameters.put(DATACENTER_KEY, datacenterId);\n      return this;\n   }\n\n   public GetServerListOptions onlySandboxServers() {\n      checkState(!queryParameters.containsKey(IS_SANDBOX_KEY),\n               \"Can't have duplicate sandbox type limit\");\n      queryParameters.put(IS_SANDBOX_KEY, \"true\");\n      return this;\n   }\n\n   public GetServerListOptions excludeSandboxServers() {\n      checkState(!queryParameters.containsKey(IS_SANDBOX_KEY),\n               \"Can't have duplicate sandbox type limit\");\n      queryParameters.put(IS_SANDBOX_KEY, \"false\");\n      return this;\n   }\n\n   public static class Builder {\n      public GetServerListOptions inDatacenter(String datacenterId) {\n         GetServerListOptions getServerListOptions = new GetServerListOptions();\n         getServerListOptions.inDatacenter(checkNotNull(datacenterId));\n         return getServerListOptions;\n      }\n\n      public GetServerListOptions limitServerTypeTo(String serverType) {\n         GetServerListOptions getServerListOptions = new GetServerListOptions();\n         getServerListOptions.limitServerTypeTo(checkNotNull(serverType));\n         return getServerListOptions;\n      }\n\n      public GetServerListOptions onlySandboxServers() {\n         GetServerListOptions getServerListOptions = new GetServerListOptions();\n         getServerListOptions.onlySandboxServers();\n         return getServerListOptions;\n      }\n\n      public GetServerListOptions excludeSandboxServers() {\n         GetServerListOptions getServerListOptions = new GetServerListOptions();\n         getServerListOptions.excludeSandboxServers();\n         return getServerListOptions;\n      }\n\n   }\n\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/options/SaveImageOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.options;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkState;\nimport static org.jclouds.gogrid.reference.GoGridQueryParams.DESCRIPTION_KEY;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\npublic class SaveImageOptions extends BaseHttpRequestOptions {\n\n   public SaveImageOptions withDescription(String description) {\n      checkArgument(description.length() <= 500, \"Description cannot be longer than 500 characters\");\n      checkState(!queryParameters.containsKey(DESCRIPTION_KEY), \"Can't have duplicate image description\");\n      queryParameters.put(DESCRIPTION_KEY, description);\n      return this;\n   }\n\n   public static class Builder {\n      /**\n       * @see SaveImageOptions#withDescription(String)\n       */\n      public static SaveImageOptions withDescription(String description) {\n         SaveImageOptions options = new SaveImageOptions();\n         return options.withDescription(description);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/predicates/LoadBalancerLatestJobCompleted.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.gogrid.options.GetJobListOptions.Builder.latestJobForObjectByName;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.gogrid.domain.Job;\nimport org.jclouds.gogrid.domain.JobState;\nimport org.jclouds.gogrid.domain.LoadBalancer;\nimport org.jclouds.gogrid.features.GridJobApi;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Iterables;\nimport com.google.inject.Inject;\n\n@Singleton\npublic class LoadBalancerLatestJobCompleted implements Predicate<LoadBalancer> {\n\n   protected GridJobApi jobClient;\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   @Inject\n   public LoadBalancerLatestJobCompleted(GridJobApi jobClient) {\n      this.jobClient = jobClient;\n   }\n\n   @Override\n   public boolean apply(LoadBalancer loadBalancer) {\n      checkNotNull(loadBalancer, \"Load balancer must be a valid instance\");\n      checkNotNull(loadBalancer.getName(), \"Load balancer must be a valid name\");\n      Job latestJob = Iterables.getOnlyElement(jobClient.getJobList(latestJobForObjectByName(loadBalancer.getName())));\n      return JobState.SUCCEEDED.equals(latestJob.getCurrentState());\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/predicates/ServerLatestJobCompleted.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.gogrid.options.GetJobListOptions.Builder.latestJobForObjectByName;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.gogrid.domain.Job;\nimport org.jclouds.gogrid.domain.JobState;\nimport org.jclouds.gogrid.domain.Server;\nimport org.jclouds.gogrid.features.GridJobApi;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Iterables;\nimport com.google.inject.Inject;\n\n/**\n * Checks if the latest job for the server is in \"Succeeded\" state. To achieve meaningful results,\n * this must be run in a sequential environment when a server has only one job related to it at a\n * time.\n * \n * The passed server instance must not be null and must have a name.\n */\n@Singleton\npublic class ServerLatestJobCompleted implements Predicate<Server> {\n\n   protected GridJobApi jobClient;\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   @Inject\n   public ServerLatestJobCompleted(GridJobApi jobClient) {\n      this.jobClient = jobClient;\n   }\n\n   @Override\n   public boolean apply(Server server) {\n      checkNotNull(server, \"Server must be a valid instance\");\n      checkNotNull(server.getName(), \"Server must be a valid name\");\n      Job latestJob = Iterables.getOnlyElement(jobClient.getJobList(latestJobForObjectByName(server.getName())));\n      return JobState.SUCCEEDED.equals(latestJob.getCurrentState());\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/reference/GoGridHeaders.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.reference;\n\npublic final class GoGridHeaders {\n    public static final String VERSION = \"v\";\n\n   private GoGridHeaders() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/main/java/org/jclouds/gogrid/reference/GoGridQueryParams.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.reference;\n\npublic final class GoGridQueryParams {\n\n   public static final String ID_KEY = \"id\";\n   public static final String NAME_KEY = \"name\";\n   public static final String SERVER_ID_OR_NAME_KEY = \"server\";\n   public static final String SERVER_TYPE_KEY = \"server.type\";\n\n   public static final String DATACENTER_KEY = \"datacenter\";\n\n   public static final String IS_SANDBOX_KEY = \"isSandbox\";\n   public static final String IMAGE_KEY = \"image\";\n   public static final String IP_KEY = \"ip\";\n\n   public static final String SERVER_RAM_KEY = \"server.ram\";\n\n   public static final String DESCRIPTION_KEY = \"description\";\n   public static final String POWER_KEY = \"power\";\n\n   public static final String MAX_NUMBER_KEY = \"num_items\";\n   public static final String START_DATE_KEY = \"startdate\";\n   public static final String END_DATE_KEY = \"enddate\";\n   public static final String OWNER_KEY = \"owner\";\n\n   public static final String JOB_STATE_KEY = \"job.state\";\n   public static final String JOB_OBJECT_TYPE_KEY = \"job.objecttype\";\n\n   public static final String OBJECT_KEY = \"object\";\n\n   public static final String IP_STATE_KEY = \"ip.state\";\n   public static final String IP_TYPE_KEY = \"ip.type\";\n\n   public static final String LOAD_BALANCER_KEY = \"loadbalancer\";\n   public static final String LOAD_BALANCER_TYPE_KEY = \"loadbalancer.type\";\n   public static final String LOAD_BALANCER_PERSISTENCE_TYPE_KEY = \"loadbalancer.persistence\";\n   public static final String VIRTUAL_IP_KEY = \"virtualip.\";\n   public static final String REAL_IP_LIST_KEY = \"realiplist.\";\n\n   public static final String IS_PUBLIC_KEY = \"isPublic\";\n   public static final String IMAGE_TYPE_KEY = \"image.type\";\n   public static final String IMAGE_STATE_KEY = \"image.state\";\n   public static final String IMAGE_FRIENDLY_NAME_KEY = \"friendlyName\";\n   public static final String IMAGE_DESCRIPTION_KEY = \"description\";\n\n   public static final String LOOKUP_LIST_KEY = \"lookup\";\n\n   private GoGridQueryParams() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/test/java/org/jclouds/gogrid/GoGridApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid;\n\nimport java.io.IOException;\nimport java.util.concurrent.ExecutionException;\n\nimport org.jclouds.gogrid.features.BaseGoGridApiTest;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code GoGridApi}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"GoGridApiTest\")\npublic class GoGridApiTest extends BaseGoGridApiTest<GoGridApi> {\n\n   private GoGridApi syncClient;\n\n   public void testSync() throws SecurityException, NoSuchMethodException, InterruptedException,\n            ExecutionException {\n      assert syncClient.getImageServices() != null;\n      assert syncClient.getIpServices() != null;\n      assert syncClient.getJobServices() != null;\n      assert syncClient.getLoadBalancerServices() != null;\n      assert syncClient.getServerServices() != null;\n   }\n\n   @BeforeClass\n   @Override\n   protected void setupFactory() throws IOException {\n      super.setupFactory();\n      syncClient = injector.getInstance(GoGridApi.class);\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/test/java/org/jclouds/gogrid/GoGridLiveTestDisabled.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static java.lang.String.format;\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static org.jclouds.util.Predicates2.retry;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.util.Arrays;\nimport java.util.Date;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.apis.BaseApiLiveTest;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.gogrid.domain.Ip;\nimport org.jclouds.gogrid.domain.IpPortPair;\nimport org.jclouds.gogrid.domain.Job;\nimport org.jclouds.gogrid.domain.LoadBalancer;\nimport org.jclouds.gogrid.domain.LoadBalancerPersistenceType;\nimport org.jclouds.gogrid.domain.LoadBalancerType;\nimport org.jclouds.gogrid.domain.PowerCommand;\nimport org.jclouds.gogrid.domain.Server;\nimport org.jclouds.gogrid.domain.ServerImage;\nimport org.jclouds.gogrid.domain.ServerImageType;\nimport org.jclouds.gogrid.options.AddLoadBalancerOptions;\nimport org.jclouds.gogrid.options.AddServerOptions;\nimport org.jclouds.gogrid.options.GetImageListOptions;\nimport org.jclouds.gogrid.predicates.LoadBalancerLatestJobCompleted;\nimport org.jclouds.gogrid.predicates.ServerLatestJobCompleted;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.predicates.SocketOpen;\nimport org.testng.SkipException;\nimport org.testng.TestException;\nimport org.testng.annotations.AfterTest;\nimport org.testng.annotations.BeforeGroups;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Lists;\nimport com.google.common.net.HostAndPort;\nimport com.google.inject.Guice;\n\n/**\n * End to end live test for GoGrid\n * <p/>\n * Takes too long to execute. Please split into multiple tests\n */\n@Test(enabled = false, groups = \"live\", singleThreaded = true, testName = \"GoGridLiveTestDisabled\")\npublic class GoGridLiveTestDisabled extends BaseApiLiveTest<GoGridApi> {\n\n   public GoGridLiveTestDisabled() {\n      provider = \"gogrid\";\n   }\n\n   private Predicate<Server> serverLatestJobCompleted;\n   private Predicate<LoadBalancer> loadBalancerLatestJobCompleted;\n   /**\n    * Keeps track of the servers, created during the tests, to remove them after all tests complete\n    */\n   private List<String> serversToDeleteAfterTheTests = Lists.newArrayList();\n   private List<String> loadBalancersToDeleteAfterTest = Lists.newArrayList();\n\n\n   @BeforeGroups(groups = { \"integration\", \"live\" })\n   @Override\n   public void setup() {\n      super.setup();\n      serverLatestJobCompleted = retry(new ServerLatestJobCompleted(api.getJobServices()), 800, 20, SECONDS);\n      loadBalancerLatestJobCompleted = retry(new LoadBalancerLatestJobCompleted(api.getJobServices()), 800, 20,\n            SECONDS);\n   }\n\n   @Test(enabled = true)\n   public void testDescriptionIs500Characters() {\n      final String nameOfServer = \"Description\" + String.valueOf(new Date().getTime()).substring(6);\n      serversToDeleteAfterTheTests.add(nameOfServer);\n\n      Set<Ip> availableIps = api.getIpServices().getUnassignedPublicIpList();\n      Ip availableIp = Iterables.getLast(availableIps);\n\n      String ram = Iterables.get(api.getServerServices().getRamSizes(), 0).getName();\n      StringBuilder builder = new StringBuilder();\n\n      for (int i = 0; i < 500; i++)\n         builder.append('a');\n\n      String description = builder.toString();\n\n      Server createdServer = api.getServerServices().addServer(nameOfServer,\n               \"GSI-f8979644-e646-4711-ad58-d98a5fa3612c\", ram, availableIp.getIp(),\n               new AddServerOptions().withDescription(description));\n      assertNotNull(createdServer);\n      assert serverLatestJobCompleted.apply(createdServer);\n\n      assertEquals(Iterables.getLast(api.getServerServices().getServersByName(nameOfServer)).getDescription(),\n               description);\n\n   }\n\n   /**\n    * Tests server start, reboot and deletion. Also verifies IP services and job services.\n    */\n   @Test(enabled = true)\n   public void testServerLifecycle() {\n      int serverCountBeforeTest = api.getServerServices().getServerList().size();\n\n      final String nameOfServer = \"Server\" + String.valueOf(new Date().getTime()).substring(6);\n      serversToDeleteAfterTheTests.add(nameOfServer);\n\n      Set<Ip> availableIps = api.getIpServices().getUnassignedPublicIpList();\n      Ip availableIp = Iterables.getLast(availableIps);\n\n      String ram = Iterables.get(api.getServerServices().getRamSizes(), 0).getName();\n\n      Server createdServer = api.getServerServices().addServer(nameOfServer,\n               \"GSI-f8979644-e646-4711-ad58-d98a5fa3612c\", ram, availableIp.getIp());\n      assertNotNull(createdServer);\n      assert serverLatestJobCompleted.apply(createdServer);\n\n      // get server by name\n      Set<Server> response = api.getServerServices().getServersByName(nameOfServer);\n      assert response.size() == 1;\n\n      // restart the server\n      api.getServerServices().power(nameOfServer, PowerCommand.RESTART);\n\n      Set<Job> jobs = api.getJobServices().getJobsForObjectName(nameOfServer);\n      assert \"RestartVirtualServer\".equals(Iterables.getLast(jobs).getCommand().getName());\n\n      assert serverLatestJobCompleted.apply(createdServer);\n\n      int serverCountAfterAddingOneServer = api.getServerServices().getServerList().size();\n      assert serverCountAfterAddingOneServer == serverCountBeforeTest + 1 : \"There should be +1 increase in the number of servers since the test started\";\n\n      // delete the server\n      api.getServerServices().deleteByName(nameOfServer);\n\n      jobs = api.getJobServices().getJobsForObjectName(nameOfServer);\n      assert \"DeleteVirtualServer\".equals(Iterables.getLast(jobs).getCommand().getName());\n\n      assert serverLatestJobCompleted.apply(createdServer);\n\n      int serverCountAfterDeletingTheServer = api.getServerServices().getServerList().size();\n      assert serverCountAfterDeletingTheServer == serverCountBeforeTest : \"There should be the same # of servers as since the test started\";\n\n      // make sure that IP is put back to \"unassigned\"\n      assert api.getIpServices().getUnassignedIpList().contains(availableIp);\n   }\n\n   /**\n    * Starts a servers, verifies that jobs are created correctly and an be retrieved from the job\n    * services\n    */\n   @Test(dependsOnMethods = \"testServerLifecycle\", enabled = true)\n   public void testJobs() {\n      final String nameOfServer = \"Server\" + String.valueOf(new Date().getTime()).substring(6);\n      serversToDeleteAfterTheTests.add(nameOfServer);\n\n      Set<Ip> availableIps = api.getIpServices().getUnassignedPublicIpList();\n\n      String ram = Iterables.get(api.getServerServices().getRamSizes(), 0).getName();\n\n      Server createdServer = api.getServerServices().addServer(nameOfServer,\n               \"GSI-f8979644-e646-4711-ad58-d98a5fa3612c\", ram, Iterables.getLast(availableIps).getIp());\n\n      assert serverLatestJobCompleted.apply(createdServer);\n\n      // restart the server\n      api.getServerServices().power(nameOfServer, PowerCommand.RESTART);\n\n      Set<Job> jobs = api.getJobServices().getJobsForObjectName(nameOfServer);\n\n      Job latestJob = Iterables.getLast(jobs);\n      Long latestJobId = latestJob.getId();\n\n      Job latestJobFetched = Iterables.getOnlyElement(api.getJobServices().getJobsById(latestJobId));\n\n      assert latestJob.equals(latestJobFetched) : \"Job and its representation found by ID don't match\";\n\n      long[] idsOfAllJobs = new long[jobs.size()];\n      int i = 0;\n      for (Job job : jobs) {\n         idsOfAllJobs[i++] = job.getId();\n      }\n\n      Set<Job> jobsFetched = api.getJobServices().getJobsById(idsOfAllJobs);\n      assert jobsFetched.size() == jobs.size() : format(\n               \"Number of jobs fetched by ids doesn't match the number of jobs \"\n                        + \"requested. Requested/expected: %d. Found: %d.\", jobs.size(), jobsFetched.size());\n\n      // delete the server\n      api.getServerServices().deleteByName(nameOfServer);\n   }\n\n   /**\n    * Tests common load balancer operations. Also verifies IP services and job services.\n    */\n   @Test(enabled = true)\n   public void testLoadBalancerLifecycle() {\n      int lbCountBeforeTest = api.getLoadBalancerServices().getLoadBalancerList().size();\n\n      final String nameOfLoadBalancer = \"LoadBalancer\" + String.valueOf(new Date().getTime()).substring(6);\n      loadBalancersToDeleteAfterTest.add(nameOfLoadBalancer);\n\n      Set<Ip> availableIps = api.getIpServices().getUnassignedPublicIpList();\n\n      if (availableIps.size() < 4)\n         throw new SkipException(\"Not enough available IPs (4 needed) to run the test\");\n      Iterator<Ip> ipIterator = availableIps.iterator();\n      Ip vip = ipIterator.next();\n      Ip realIp1 = ipIterator.next();\n      Ip realIp2 = ipIterator.next();\n      Ip realIp3 = ipIterator.next();\n\n      AddLoadBalancerOptions options = new AddLoadBalancerOptions.Builder().create(LoadBalancerType.LEAST_CONNECTED,\n               LoadBalancerPersistenceType.SOURCE_ADDRESS);\n      LoadBalancer createdLoadBalancer = api.getLoadBalancerServices().addLoadBalancer(nameOfLoadBalancer,\n               IpPortPair.builder().ip(vip).port(80).build(), Arrays.asList(IpPortPair.builder().ip(realIp1).port(80).build(),\n               IpPortPair.builder().ip(realIp2).port(80).build()),\n               options);\n      assertNotNull(createdLoadBalancer);\n      assert loadBalancerLatestJobCompleted.apply(createdLoadBalancer);\n\n      // get load balancer by name\n      Set<LoadBalancer> response = api.getLoadBalancerServices().getLoadBalancersByName(nameOfLoadBalancer);\n      assert response.size() == 1;\n      createdLoadBalancer = Iterables.getOnlyElement(response);\n      assertNotNull(createdLoadBalancer.getRealIpList());\n      assertEquals(createdLoadBalancer.getRealIpList().size(), 2);\n      assertNotNull(createdLoadBalancer.getVirtualIp());\n      assertEquals(createdLoadBalancer.getVirtualIp().getIp().getIp(), vip.getIp());\n\n      LoadBalancer editedLoadBalancer = api.getLoadBalancerServices().editLoadBalancerNamed(nameOfLoadBalancer,\n               Arrays.asList(IpPortPair.builder().ip(realIp3).port(8181).build()));\n      assert loadBalancerLatestJobCompleted.apply(editedLoadBalancer);\n      assertNotNull(editedLoadBalancer.getRealIpList());\n      assertEquals(editedLoadBalancer.getRealIpList().size(), 1);\n      assertEquals(Iterables.getOnlyElement(editedLoadBalancer.getRealIpList()).getIp().getIp(), realIp3.getIp());\n\n      int lbCountAfterAddingOneServer = api.getLoadBalancerServices().getLoadBalancerList().size();\n      assert lbCountAfterAddingOneServer == lbCountBeforeTest + 1 : \"There should be +1 increase in the number of load balancers since the test started\";\n\n      // delete the load balancer\n      api.getLoadBalancerServices().deleteByName(nameOfLoadBalancer);\n\n      Set<Job> jobs = api.getJobServices().getJobsForObjectName(nameOfLoadBalancer);\n      assert \"DeleteLoadBalancer\".equals(Iterables.getLast(jobs).getCommand().getName());\n\n      assert loadBalancerLatestJobCompleted.apply(createdLoadBalancer);\n\n      int lbCountAfterDeletingTheServer = api.getLoadBalancerServices().getLoadBalancerList().size();\n      assert lbCountAfterDeletingTheServer == lbCountBeforeTest : \"There should be the same # of load balancers as since the test started\";\n   }\n\n   /**\n    * Tests common server image operations.\n    */\n   @Test(enabled = true)\n   public void testImageLifecycle() {\n      GetImageListOptions options = GetImageListOptions.Builder.publicDatabaseServers();\n      Set<ServerImage> images = api.getImageServices().getImageList(options);\n\n      Predicate<ServerImage> isDatabaseServer = new Predicate<ServerImage>() {\n         @Override\n         public boolean apply(@Nullable ServerImage serverImage) {\n            return checkNotNull(serverImage).getType() == ServerImageType.DATABASE_SERVER;\n         }\n      };\n\n      assert Iterables.all(images, isDatabaseServer) : \"All of the images should've been of database type\";\n\n      ServerImage image = Iterables.getLast(images);\n      ServerImage imageFromServer = Iterables\n               .getOnlyElement(api.getImageServices().getImagesByName(image.getName()));\n      assertEquals(image, imageFromServer);\n\n      try {\n         api.getImageServices().editImageDescription(image.getName(), \"newDescription\");\n         throw new TestException(\"An exception hasn't been thrown where expected; expected GoGridResponseException\");\n      } catch (GoGridResponseException e) {\n         // expected situation - check and proceed\n         assertTrue(e.getMessage().contains(\"GoGridIllegalArgumentException\"));\n      }\n\n   }\n\n   @Test(enabled = true)\n   public void testShellAccess() throws IOException {\n      final String nameOfServer = \"Server\" + String.valueOf(new Date().getTime()).substring(6);\n      serversToDeleteAfterTheTests.add(nameOfServer);\n\n      Set<Ip> availableIps = api.getIpServices().getUnassignedIpList();\n      Ip availableIp = Iterables.getLast(availableIps);\n\n      Server createdServer = api.getServerServices().addServer(nameOfServer,\n               \"GSI-f8979644-e646-4711-ad58-d98a5fa3612c\", \"1\", availableIp.getIp());\n      assertNotNull(createdServer);\n      assert serverLatestJobCompleted.apply(createdServer);\n\n      // get server by name\n      Set<Server> response = api.getServerServices().getServersByName(nameOfServer);\n      assert response.size() == 1;\n      createdServer = Iterables.getOnlyElement(response);\n\n      Map<String, Credentials> credsMap = api.getServerServices().getServerCredentialsList();\n      LoginCredentials instanceCredentials = LoginCredentials.fromCredentials(credsMap.get(createdServer.getName()));\n      assertNotNull(instanceCredentials);\n\n      HostAndPort socket = HostAndPort.fromParts(createdServer.getIp().getIp(), 22);\n      SocketOpen socketOpen = Guice.createInjector().getInstance(SocketOpen.class);\n      Predicate<HostAndPort> socketTester = retry(socketOpen, 180, 5, SECONDS);\n      socketTester.apply(socket);\n\n      // check that the get credentials call is the same as this\n      assertEquals(api.getServerServices().getServerCredentials(createdServer.getId()), instanceCredentials);\n\n      try {\n         assertEquals(api.getServerServices().getServerCredentials(Long.MAX_VALUE), null);\n      } catch (AssertionError e) {\n         e.printStackTrace();\n      }\n\n      // delete the server\n      api.getServerServices().deleteByName(nameOfServer);\n   }\n\n   /**\n    * In case anything went wrong during the tests, removes the objects created in the tests.\n    */\n   @AfterTest\n   public void cleanup() {\n      for (String serverName : serversToDeleteAfterTheTests) {\n         try {\n            api.getServerServices().deleteByName(serverName);\n         } catch (Exception e) {\n            // it's already been deleted - proceed\n         }\n      }\n      for (String loadBalancerName : loadBalancersToDeleteAfterTest) {\n         try {\n            api.getLoadBalancerServices().deleteByName(loadBalancerName);\n         } catch (Exception e) {\n            // it's already been deleted - proceed\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/test/java/org/jclouds/gogrid/GoGridProviderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid;\n\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"GoGridProviderTest\")\npublic class GoGridProviderTest extends BaseProviderMetadataTest {\n\n   public GoGridProviderTest() {\n      super(new GoGridProviderMetadata(), new GoGridApiMetadata());\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/test/java/org/jclouds/gogrid/binders/BindIdsToQueryParamsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.http.HttpRequest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests that id bindings are proper for request\n */\n//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"BindIdsToQueryParamsTest\")\npublic class BindIdsToQueryParamsTest {\n\n   @Test\n   public void testWithView() throws SecurityException, NoSuchMethodException {\n\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma/\").build();\n\n      BindIdsToQueryParams binder = new BindIdsToQueryParams();\n\n      request = binder.bindToRequest(request, new Long[] { 123L, 456L });\n\n      assertEquals(request.getRequestLine(), \"GET http://momma/?id=123&id=456 HTTP/1.1\");\n   }\n\n   @Test\n   public void testWithPrimitive() {\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma/\").build();\n\n      BindIdsToQueryParams binder = new BindIdsToQueryParams();\n\n      request = binder.bindToRequest(request, new long[] { 123L, 456L });\n\n      assertEquals(request.getRequestLine(), \"GET http://momma/?id=123&id=456 HTTP/1.1\");\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/test/java/org/jclouds/gogrid/binders/BindNamesToQueryParamsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.http.HttpRequest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests that name bindings are proper for request\n */\n//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"BindNamesToQueryParamsTest\")\npublic class BindNamesToQueryParamsTest {\n\n   @Test\n   public void testBinding() {\n      String[] input = { \"hello\", \"world\" };\n\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma/\").build();\n\n      BindNamesToQueryParams binder = new BindNamesToQueryParams();\n\n      request = binder.bindToRequest(request, input);\n\n      assertEquals(request.getRequestLine(), \"GET http://momma/?name=hello&name=world HTTP/1.1\");\n   }\n\n}\n"
  },
  {
    "path": "providers/gogrid/src/test/java/org/jclouds/gogrid/compute/GoGridComputeServiceLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.compute;\n\nimport static com.google.common.collect.Iterables.get;\nimport static com.google.common.collect.Iterables.getLast;\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static org.jclouds.compute.predicates.NodePredicates.inGroup;\nimport static org.jclouds.util.Predicates2.retry;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport org.jclouds.compute.domain.ExecResponse;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.internal.BaseComputeServiceLiveTest;\nimport org.jclouds.gogrid.GoGridApi;\nimport org.jclouds.gogrid.domain.Server;\nimport org.jclouds.gogrid.predicates.ServerLatestJobCompleted;\nimport org.jclouds.sshj.config.SshjSshClientModule;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.inject.Module;\n\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"live\", singleThreaded = true, testName = \"GoGridComputeServiceLiveTest\")\npublic class GoGridComputeServiceLiveTest extends BaseComputeServiceLiveTest {\n\n   public GoGridComputeServiceLiveTest() {\n      provider = \"gogrid\";\n   }\n\n   @Override\n   protected Module getSshModule() {\n      return new SshjSshClientModule();\n   }\n\n   // gogrid does not support metadata\n   @Override\n   protected void checkUserMetadataContains(NodeMetadata node, ImmutableMap<String, String> userMetadata) {\n      assert node.getUserMetadata().equals(ImmutableMap.<String, String> of()) : String.format(\n            \"node userMetadata did not match %s %s\", userMetadata, node);\n   }\n   \n   protected void checkResponseEqualsHostname(ExecResponse execResponse, NodeMetadata node1) {\n      // hostname is not predictable based on node metadata\n   }\n\n   public void testResizeRam() throws Exception {\n      String group = this.group + \"ram\";\n      GoGridApi api = view.utils().injector().getInstance(GoGridApi.class);\n      try {\n         client.destroyNodesMatching(inGroup(group));\n      } catch (Exception e) {\n\n      }\n      Predicate<Server> serverLatestJobCompleted = retry(new ServerLatestJobCompleted(api\n            .getJobServices()), 800, 20, SECONDS);\n\n      String ram = get(api.getServerServices().getRamSizes(), 1).getName();\n      try {\n         NodeMetadata node = getOnlyElement(client.createNodesInGroup(group, 1));\n\n         Server updatedServer = api.getServerServices().editServerRam(Long.valueOf(node.getId()), ram);\n         assertNotNull(updatedServer);\n         assert serverLatestJobCompleted.apply(updatedServer);\n\n         assertEquals(getLast(api.getServerServices().getServersById(Long.valueOf(node.getId()))).getRam().getName(),\n               ram);\n\n      } finally {\n         client.destroyNodesMatching(inGroup(group));\n      }\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/test/java/org/jclouds/gogrid/compute/GoGridTemplateBuilderLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.compute;\n\nimport static org.jclouds.compute.util.ComputeServiceUtils.getCores;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.internal.BaseTemplateBuilderLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"live\", singleThreaded = true, testName = \"GoGridTemplateBuilderLiveTest\")\npublic class GoGridTemplateBuilderLiveTest extends BaseTemplateBuilderLiveTest {\n\n   public GoGridTemplateBuilderLiveTest() {\n      provider = \"gogrid\";\n   }\n\n   @Test\n   public void testDefaultTemplateBuilder() throws IOException {\n      Template defaultTemplate = view.getComputeService().templateBuilder().build();\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().getVersion(), \"10.04\");\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true);\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.UBUNTU);\n      assertEquals(getCores(defaultTemplate.getHardware()), 0.5d);\n   }\n\n   @Override\n   protected Set<String> getIso3166Codes() {\n      return ImmutableSet.of(\"US-CA\", \"US-VA\", \"NL-NH\");\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/test/java/org/jclouds/gogrid/compute/config/GoGridComputeServiceContextModuleTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.compute.config;\n\nimport org.jclouds.gogrid.domain.ServerState;\nimport org.testng.annotations.Test;\n\n//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"GoGridComputeServiceContextModuleTest\")\npublic class GoGridComputeServiceContextModuleTest {\n\n   public void testAllStatusCovered() {\n\n      for (ServerState state : ServerState.values()) {\n         assert GoGridComputeServiceContextModule.toPortableNodeStatus.containsKey(state) : state;\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/test/java/org/jclouds/gogrid/compute/functions/ServerToNodeMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.compute.functions;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.NodeMetadata.Status;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.gogrid.compute.suppliers.GoGridHardwareSupplier;\nimport org.jclouds.gogrid.domain.Ip;\nimport org.jclouds.gogrid.domain.Option;\nimport org.jclouds.gogrid.domain.Server;\nimport org.jclouds.gogrid.domain.ServerImage;\nimport org.jclouds.gogrid.domain.ServerState;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\n\n//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"ServerToNodeMetadataTest\")\npublic class ServerToNodeMetadataTest {\n   GroupNamingConvention.Factory namingConvention = Guice.createInjector().getInstance(GroupNamingConvention.Factory.class);\n\n   @SuppressWarnings(\"unchecked\")\n   @Test\n   public void testApplySetsTagFromNameAndCredentialsFromName() {\n\n      Map<ServerState, Status> serverStateToNodeStatus = createMock(Map.class);\n      org.jclouds.compute.domain.Image jcImage = createMock(org.jclouds.compute.domain.Image.class);\n      Option dc = Option.createWithIdNameAndDescription(1L, \"US-West-1\", \"US West 1 Datacenter\");\n      Option ram = Option.createWithIdNameAndDescription(1L, \"512MB\", \"Server with 512MB RAM\");\n\n      Set<? extends org.jclouds.compute.domain.Image> images = ImmutableSet.of(jcImage);\n      Server server = createMock(Server.class);\n\n      expect(server.getId()).andReturn(1000L).atLeastOnce();\n      expect(server.getName()).andReturn(\"group-ff\").atLeastOnce();\n      expect(server.getState()).andReturn(ServerState.ON).atLeastOnce();\n\n      expect(serverStateToNodeStatus.get(ServerState.ON)).andReturn(Status.RUNNING);\n\n      Location location = new LocationBuilder().scope(LocationScope.ZONE).id(\"1\").description(\"US-West-1\").build();\n      Set< ? extends Location> locations = ImmutableSet.< Location> of( location);\n      \n      expect(server.getIp()).andReturn(Ip.builder().ip(\"127.0.0.1\").build());\n\n      ServerImage image = createMock(ServerImage.class);\n      expect(server.getImage()).andReturn(image).atLeastOnce();\n      expect(server.getRam()).andReturn(ram).atLeastOnce();\n      expect(server.getDatacenter()).andReturn(dc).atLeastOnce();\n      expect(image.getId()).andReturn(2000L).atLeastOnce();\n      expect(jcImage.getProviderId()).andReturn(\"2000\").atLeastOnce();\n      expect(jcImage.getLocation()).andReturn(location).atLeastOnce();\n      expect(jcImage.getOperatingSystem()).andReturn(createMock(OperatingSystem.class)).atLeastOnce();\n\n      replay(serverStateToNodeStatus);\n      replay(server);\n      replay(image);\n      replay(jcImage);\n\n      ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeStatus, Suppliers\n               .<Set<? extends Image>> ofInstance(images), Suppliers\n               .<Set<? extends Hardware>> ofInstance(GoGridHardwareSupplier.H_ALL), Suppliers\n               .<Set<? extends Location>> ofInstance(locations), namingConvention);\n\n      NodeMetadata metadata = parser.apply(server);\n      assertEquals(metadata.getLocation(), location);\n      assertEquals(metadata.getImageId(), \"2000\");\n      assertEquals(metadata.getGroup(), \"group\");\n\n      verify(serverStateToNodeStatus);\n      verify(image);\n      verify(server);\n      verify(jcImage);\n\n   }\n\n}\n"
  },
  {
    "path": "providers/gogrid/src/test/java/org/jclouds/gogrid/compute/options/GoGridTemplateOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.compute.options;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.testng.annotations.Test;\n\n/**\n * Tests possible uses of {@code GoGridTemplateOptions} and {@code GoGridTemplateOptions.Builder.*}.\n */\n//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"GoGridTemplateOptionsTest\")\npublic class GoGridTemplateOptionsTest {\n   @Test\n   public void testAs() {\n      TemplateOptions options = new GoGridTemplateOptions();\n      assertEquals(options.as(GoGridTemplateOptions.class), options);\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/test/java/org/jclouds/gogrid/features/BaseGoGridApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.features;\n\nimport org.jclouds.apis.BaseApiLiveTest;\nimport org.jclouds.gogrid.GoGridApi;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code GoGridApi}\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"BaseGoGridApiLiveTest\")\npublic class BaseGoGridApiLiveTest extends BaseApiLiveTest<GoGridApi> {\n   public BaseGoGridApiLiveTest() {\n      provider = \"gogrid\";\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/test/java/org/jclouds/gogrid/features/BaseGoGridApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.features;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.gogrid.GoGridProviderMetadata;\nimport org.jclouds.gogrid.config.GoGridHttpApiModule;\nimport org.jclouds.gogrid.filters.SharedKeyLiteAuthentication;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.internal.BaseRestAnnotationProcessingTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.inject.Module;\n\n@Test(groups = \"unit\")\npublic abstract class BaseGoGridApiTest<T> extends BaseRestAnnotationProcessingTest<T> {\n   @Override\n   protected void checkFilters(HttpRequest request) {\n      assertEquals(request.getFilters().size(), 1);\n      assertEquals(request.getFilters().get(0).getClass(), SharedKeyLiteAuthentication.class);\n   }\n\n   @ConfiguresHttpApi\n   protected static final class TestGoGridHttpApiModule extends GoGridHttpApiModule {\n      @Override\n      protected void configure() {\n         super.configure();\n      }\n\n      @Override\n      protected Long provideTimeStamp(@TimeStamp Supplier<Long> cache) {\n         return 1267243795L;\n      }\n   }\n\n   @Override\n   protected Module createModule() {\n      return new TestGoGridHttpApiModule();\n   }\n\n   @Override\n   public ProviderMetadata createProviderMetadata() {\n      return new GoGridProviderMetadata();\n   }\n\n}\n"
  },
  {
    "path": "providers/gogrid/src/test/java/org/jclouds/gogrid/features/BaseGoGridHttpApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.features;\n\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.gogrid.GoGridApi;\nimport org.jclouds.gogrid.config.GoGridHttpApiModule;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.internal.BaseRestApiExpectTest;\n\nimport com.google.common.base.Supplier;\nimport com.google.inject.Module;\n\npublic class BaseGoGridHttpApiExpectTest extends BaseRestApiExpectTest<GoGridApi> {\n\n   public BaseGoGridHttpApiExpectTest() {\n      provider = \"gogrid\";\n   }\n\n   @ConfiguresHttpApi\n   protected static final class TestGoGridHttpApiModule extends GoGridHttpApiModule {\n\n      @Override\n      protected Long provideTimeStamp(@TimeStamp Supplier<Long> cache) {\n         return 1267243795L;\n      }\n   }\n\n   @Override\n   protected Module createModule() {\n      return new TestGoGridHttpApiModule();\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/test/java/org/jclouds/gogrid/features/GridImageApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.features;\n\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static org.jclouds.util.Predicates2.retry;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.util.Date;\nimport java.util.Set;\nimport java.util.logging.Logger;\n\nimport org.jclouds.gogrid.domain.Ip;\nimport org.jclouds.gogrid.domain.Server;\nimport org.jclouds.gogrid.domain.ServerImage;\nimport org.jclouds.gogrid.domain.ServerImageState;\nimport org.jclouds.gogrid.options.SaveImageOptions;\nimport org.jclouds.gogrid.predicates.ServerLatestJobCompleted;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Iterables;\n\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"GridImageApiLiveTest\")\npublic class GridImageApiLiveTest extends BaseGoGridApiLiveTest {\n\n   public void testListImages() throws Exception {\n      Set<ServerImage> response = api.getImageServices().getImageList();\n      assert null != response;\n      for (ServerImage image : response) {\n         assert image.getId() >= 0 : image;\n         checkImage(image);\n\n         ServerImage query = Iterables.getOnlyElement(api.getImageServices()\n               .getImagesById(image.getId()));\n         assertEquals(query.getId(), image.getId());\n\n         checkImage(query);\n      }\n   }\n\n   private void checkImage(ServerImage image) {\n      assert image.getArchitecture() != null : image;\n      assert image.getBillingTokens() != null : image;\n      if (image.getCreatedTime() == null)\n         Logger.getAnonymousLogger().warning(\"image \" + image.getId() + \" is missing the createdTime field\");\n      assert image.getDescription() != null : image;\n      assert image.getFriendlyName() != null : image;\n      assert image.getId() >= 0 : image;\n      assert image.getLocation() != null : image;\n      assert image.getName() != null : image;\n      assert image.getOs() != null : image;\n      assert image.getOwner() != null : image;\n      assert image.getPrice() >= 0 : image;\n      assert image.getState() != null : image;\n      assert image.getType() != null : image;\n      if (image.getUpdatedTime() == null)\n         Logger.getAnonymousLogger().warning(\"image \" + image.getId() + \" is missing the updatedTime field\");\n   }\n\n   @Test\n   public void testSaveServerToImage() throws IOException {\n      Predicate<Server> serverLatestJobCompleted = retry(new ServerLatestJobCompleted(api\n            .getJobServices()), 800, 20, SECONDS);\n\n      final String nameOfServer = \"Server\" + String.valueOf(new Date().getTime()).substring(6);\n      ServerImage image = null;\n      try {\n         Set<Ip> availableIps = api.getIpServices().getUnassignedPublicIpList();\n         Ip availableIp = Iterables.getLast(availableIps);\n\n         Server createdServer = api.getServerServices()\n               .addServer(nameOfServer, \"5489\", \"1\", availableIp.getIp());\n         assertNotNull(createdServer);\n         assert serverLatestJobCompleted.apply(createdServer);\n         image = api\n               .getImageServices()\n               .saveImageFromServer(\"friendlyName\", createdServer.getName(),\n                     SaveImageOptions.Builder.withDescription(\"description\"));\n         \n         assertEquals(image.getFriendlyName(), \"friendlyName\");\n         assertEquals(image.getDescription(), \"description\");\n         assertFalse(image.isPublic());\n\n         assertEventuallyImageStateEquals(image, ServerImageState.AVAILABLE);\n         \n         api.getImageServices().deleteById(image.getId());\n\n         assertEventuallyImageStateEquals(image, ServerImageState.TRASH);\n         \n         image = null;\n      } finally {\n         if (image != null)\n            try {\n               api.getImageServices().deleteById(image.getId());\n            } catch (Exception e) {\n               // not failing so that we can ensure server below deletes\n               e.printStackTrace();\n            }\n         // delete the server\n         api.getServerServices().deleteByName(nameOfServer);\n      }\n\n   }\n\n   protected void assertEventuallyImageStateEquals(ServerImage image, final ServerImageState state) {\n      assertTrue(retry(new Predicate<ServerImage>() {\n         public boolean apply(ServerImage input) {\n            return Iterables.getOnlyElement(api.getImageServices().getImagesById(input.getId()))\n                  .getState() == state;\n         }\n      }, 600, 1, SECONDS).apply(image));\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/test/java/org/jclouds/gogrid/features/GridImageApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.features;\n\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport java.io.IOException;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.gogrid.domain.ServerImageState;\nimport org.jclouds.gogrid.domain.ServerImageType;\nimport org.jclouds.gogrid.functions.ParseImageFromJsonResponse;\nimport org.jclouds.gogrid.functions.ParseImageListFromJsonResponse;\nimport org.jclouds.gogrid.options.GetImageListOptions;\nimport org.jclouds.gogrid.options.SaveImageOptions;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Iterables;\nimport com.google.common.reflect.Invokable;\n/**\n * Tests behavior of {@code GridImageApi}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during\n// surefire\n@Test(groups = \"unit\", testName = \"GridImageApiTest\")\npublic class GridImageApiTest extends BaseGoGridApiTest<GridImageApi> {\n\n   @Test\n   public void testGetImageListWithOptions() throws NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(GridImageApi.class, \"getImageList\", GetImageListOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(\n            method, ImmutableList.<Object> of(\n            new GetImageListOptions().onlyPublic().setState(ServerImageState.AVAILABLE)\n                  .setType(ServerImageType.WEB_APPLICATION_SERVER)));\n\n      assertRequestLineEquals(httpRequest, \"GET https://api.gogrid.com/api/grid/image/list?v=1.5&\"\n            + \"isPublic=true&image.state=Available&\" + \"image.type=Web%20Server HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseImageListFromJsonResponse.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(httpRequest);\n      httpRequest = (GeneratedHttpRequest) Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);\n\n      assertRequestLineEquals(httpRequest, \"GET https://api.gogrid.com/api/grid/image/list?\"\n            + \"v=1.5&isPublic=true&image.state=Available&\" + \"image.type=Web%20Server&\"\n            + \"sig=e9aafd0a5d4c69bb24536be4bce8a528&api_key=identity \" + \"HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n   }\n\n   @Test\n   public void testGetImagesByName() throws NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(GridImageApi.class, \"getImagesByName\", String[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"name1\", \"name2\"));\n\n      assertRequestLineEquals(httpRequest, \"GET https://api.gogrid.com/api/grid/image/get?v=1.5&\"\n            + \"name=name1&name=name2 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseImageListFromJsonResponse.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(httpRequest);\n      httpRequest = (GeneratedHttpRequest) Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);\n\n      assertRequestLineEquals(httpRequest, \"GET https://api.gogrid.com/api/grid/image/get?v=1.5&\"\n            + \"name=name1&name=name2&\" + \"sig=e9aafd0a5d4c69bb24536be4bce8a528&api_key=identity \" + \"HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n   }\n\n   @Test\n   public void testEditImageDescription() throws NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(GridImageApi.class, \"editImageDescription\", String.class, String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"imageName\", \"newDesc\"));\n\n      assertRequestLineEquals(httpRequest, \"GET https://api.gogrid.com/api/grid/image/edit?v=1.5&\"\n            + \"image=imageName&description=newDesc HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseImageFromJsonResponse.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(httpRequest);\n      httpRequest = (GeneratedHttpRequest) Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);\n\n      assertRequestLineEquals(httpRequest, \"GET https://api.gogrid.com/api/grid/image/edit?v=1.5&\"\n            + \"image=imageName&description=newDesc&\" + \"sig=e9aafd0a5d4c69bb24536be4bce8a528&api_key=identity \" + \"HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n   }\n\n   @Test\n   public void testEditImageFriendlyName() throws NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(GridImageApi.class, \"editImageFriendlyName\", String.class, String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"imageName\", \"newFriendlyName\"));\n\n      assertRequestLineEquals(httpRequest, \"GET https://api.gogrid.com/api/grid/image/edit?v=1.5&\"\n            + \"image=imageName&friendlyName=newFriendlyName HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseImageFromJsonResponse.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(httpRequest);\n      httpRequest = (GeneratedHttpRequest) Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);\n\n      assertRequestLineEquals(httpRequest, \"GET https://api.gogrid.com/api/grid/image/edit?v=1.5&\"\n            + \"image=imageName&friendlyName=newFriendlyName&\" + \"sig=e9aafd0a5d4c69bb24536be4bce8a528&api_key=identity \"\n            + \"HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n   }\n\n   @Test\n   public void testDeleteById() throws NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(GridImageApi.class, \"deleteById\", long.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(11L));\n\n      assertRequestLineEquals(httpRequest, \"GET https://api.gogrid.com/api/grid/image/delete?v=1.5&id=11 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseImageFromJsonResponse.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n   }\n\n   @Test\n   public void testSaveImageFromServerNoOptions() throws NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(GridImageApi.class, \"saveImageFromServer\", String.class, String.class,\n            SaveImageOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"friendly\", \"serverName\"));\n\n      assertRequestLineEquals(httpRequest,\n            \"GET https://api.gogrid.com/api/grid/image/save?v=1.5&friendlyName=friendly&server=serverName HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseImageFromJsonResponse.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n   }\n\n   @Test\n   public void testSaveImageOptions() throws NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(GridImageApi.class, \"saveImageFromServer\", String.class, String.class,\n            SaveImageOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"friendly\", \"serverName\",\n            new SaveImageOptions().withDescription(\"fooy\")));\n\n      assertRequestLineEquals(\n            httpRequest,\n            \"GET https://api.gogrid.com/api/grid/image/save?v=1.5&friendlyName=friendly&server=serverName&description=fooy HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseImageFromJsonResponse.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/test/java/org/jclouds/gogrid/features/GridIpApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.features;\n\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport java.io.IOException;\n\nimport org.jclouds.gogrid.domain.IpType;\nimport org.jclouds.gogrid.functions.ParseIpListFromJsonResponse;\nimport org.jclouds.gogrid.options.GetIpListOptions;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Iterables;\nimport com.google.common.reflect.Invokable;\n/**\n * Tests behavior of {@code GridIpApi}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"GridIpApiTest\")\npublic class GridIpApiTest extends BaseGoGridApiTest<GridIpApi> {\n\n   @Test\n   public void testGetIpListWithOptions() throws NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(GridIpApi.class, \"getIpList\", GetIpListOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(new GetIpListOptions()\n            .onlyUnassigned().onlyWithType(IpType.PUBLIC)));\n\n      assertRequestLineEquals(httpRequest, \"GET https://api.gogrid.com/api/grid/ip/list?v=1.5&ip.state=Unassigned&\"\n            + \"ip.type=Public HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseIpListFromJsonResponse.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(httpRequest);\n      httpRequest = (GeneratedHttpRequest) Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);\n\n      assertRequestLineEquals(httpRequest, \"GET https://api.gogrid.com/api/grid/ip/list?v=1.5&ip.state=Unassigned&\"\n            + \"ip.type=Public&sig=e9aafd0a5d4c69bb24536be4bce8a528&api_key=identity \" + \"HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n   }\n\n   @Test\n   public void testGetAssignedIpList() throws NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(GridIpApi.class, \"getAssignedIpList\");\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(httpRequest,\n            \"GET https://api.gogrid.com/api/grid/ip/list?v=1.5&ip.state=Assigned HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseIpListFromJsonResponse.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(httpRequest);\n      httpRequest = (GeneratedHttpRequest) Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);\n\n      assertRequestLineEquals(httpRequest, \"GET https://api.gogrid.com/api/grid/ip/list?v=1.5&ip.state=Assigned&\"\n            + \"sig=e9aafd0a5d4c69bb24536be4bce8a528&api_key=identity \" + \"HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/test/java/org/jclouds/gogrid/features/GridJobApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.features;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Set;\n\nimport org.jclouds.gogrid.domain.Job;\nimport org.jclouds.gogrid.options.GetJobListOptions;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Iterables;\n\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"GridJobApiLiveTest\")\npublic class GridJobApiLiveTest extends BaseGoGridApiLiveTest {\n\n   public void testListJobs() throws Exception {\n      Set<Job> response = api.getJobServices().getJobList(GetJobListOptions.Builder.maxItems(10));\n      assert null != response;\n      assert response.size() <= 10 : response;\n      for (Job job : response) {\n         assert job.getId() >= 0 : job;\n         checkJob(job);\n\n         Job query = Iterables.getOnlyElement(api.getJobServices().getJobsById(job.getId()));\n         assertEquals(query.getId(), job.getId());\n\n         checkJob(query);\n      }\n   }\n\n   private void checkJob(Job job) {\n      assert job.getAttempts() >= 0 : job;\n      assert job.getCommand() != null : job;\n      assert job.getCreatedOn() != null : job;\n      assert job.getCreatedOn() != null : job;\n      assert job.getDetails() != null : job;\n      assert job.getHistory() != null : job;\n      assert job.getId() >= 0 : job;\n      assert job.getLastUpdatedOn() != null : job;\n      assert job.getObjectType() != null : job;\n      assert job.getOwner() != null : job;\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/test/java/org/jclouds/gogrid/features/GridJobApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.features;\n\nimport static org.jclouds.gogrid.options.GetJobListOptions.Builder.startDate;\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport java.io.IOException;\nimport java.util.Date;\n\nimport org.jclouds.gogrid.domain.JobState;\nimport org.jclouds.gogrid.domain.ObjectType;\nimport org.jclouds.gogrid.functions.ParseJobListFromJsonResponse;\nimport org.jclouds.gogrid.options.GetJobListOptions;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Iterables;\nimport com.google.common.reflect.Invokable;\n/**\n * Tests behavior of {@code GridJobApi}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"GridJobApiTest\")\npublic class GridJobApiTest extends BaseGoGridApiTest<GridJobApi> {\n\n   @Test\n   public void testGetJobListWithOptions() throws NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(GridJobApi.class, \"getJobList\", GetJobListOptions[].class);\n      GeneratedHttpRequest httpRequest = processor\n               .createRequest(method, ImmutableList.<Object> of(startDate(new Date(1267385381770L)).withEndDate(new Date(1267385382770L))\n                        .onlyForObjectType(ObjectType.VIRTUAL_SERVER).onlyForState(JobState.PROCESSING)));\n\n      assertRequestLineEquals(httpRequest,\n               \"GET https://api.gogrid.com/api/grid/job/list?v=1.5&startdate=1267385381770&\"\n                        + \"enddate=1267385382770&job.objecttype=VirtualServer&\" + \"job.state=Processing HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseJobListFromJsonResponse.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(httpRequest);\n      httpRequest = (GeneratedHttpRequest) Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);\n\n      assertRequestLineEquals(httpRequest,\n               \"GET https://api.gogrid.com/api/grid/job/list?v=1.5&startdate=1267385381770&\"\n                        + \"enddate=1267385382770&job.objecttype=VirtualServer&\" + \"job.state=Processing&\"\n                        + \"sig=e9aafd0a5d4c69bb24536be4bce8a528&api_key=identity HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n   }\n\n   @Test\n   public void testGetJobListNoOptions() throws NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(GridJobApi.class, \"getJobList\", GetJobListOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(httpRequest, \"GET https://api.gogrid.com/api/grid/job/list?v=1.5 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n   }\n\n   @Test\n   public void testGetJobsForServerName() throws NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(GridJobApi.class, \"getJobsForObjectName\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"MyServer\"));\n\n      assertRequestLineEquals(httpRequest, \"GET https://api.gogrid.com/api/grid/job/list?v=1.5&\"\n               + \"object=MyServer HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseJobListFromJsonResponse.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(httpRequest);\n      httpRequest = (GeneratedHttpRequest) Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);\n\n      assertRequestLineEquals(httpRequest, \"GET https://api.gogrid.com/api/grid/job/list?v=1.5&\"\n               + \"object=MyServer&sig=e9aafd0a5d4c69bb24536be4bce8a528&api_key=identity \" + \"HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n   }\n\n   @Test\n   public void testGetJobsById() throws NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(GridJobApi.class, \"getJobsById\", long[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(123L, 456L));\n\n      assertRequestLineEquals(httpRequest, \"GET https://api.gogrid.com/api/grid/job/get?v=1.5&\"\n               + \"id=123&id=456 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseJobListFromJsonResponse.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(httpRequest);\n      httpRequest = (GeneratedHttpRequest) Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);\n\n      assertRequestLineEquals(httpRequest, \"GET https://api.gogrid.com/api/grid/job/get?v=1.5&\"\n               + \"id=123&id=456&sig=e9aafd0a5d4c69bb24536be4bce8a528&api_key=identity \" + \"HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/test/java/org/jclouds/gogrid/features/GridLoadBalancerApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.features;\n\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport java.io.IOException;\nimport java.util.List;\n\nimport org.jclouds.gogrid.domain.Ip;\nimport org.jclouds.gogrid.domain.IpPortPair;\nimport org.jclouds.gogrid.domain.LoadBalancerPersistenceType;\nimport org.jclouds.gogrid.domain.LoadBalancerType;\nimport org.jclouds.gogrid.functions.ParseLoadBalancerFromJsonResponse;\nimport org.jclouds.gogrid.functions.ParseLoadBalancerListFromJsonResponse;\nimport org.jclouds.gogrid.options.AddLoadBalancerOptions;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Iterables;\nimport com.google.common.reflect.Invokable;\n/**\n * Tests behavior of {@code GridLoadBalancerApi}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"GridLoadBalancerApiTest\")\npublic class GridLoadBalancerApiTest extends BaseGoGridApiTest<GridLoadBalancerApi> {\n\n   @Test\n   public void testGetLoadBalancerList() throws NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(GridLoadBalancerApi.class, \"getLoadBalancerList\");\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(httpRequest, \"GET https://api.gogrid.com/api/grid/loadbalancer/list?v=1.5 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseLoadBalancerListFromJsonResponse.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(httpRequest);\n      httpRequest = (GeneratedHttpRequest) Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);\n\n      assertRequestLineEquals(httpRequest, \"GET https://api.gogrid.com/api/grid/loadbalancer/list?v=1.5&\"\n            + \"sig=e9aafd0a5d4c69bb24536be4bce8a528&api_key=identity \" + \"HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n   }\n\n   HttpRequest addLoadBalancer = HttpRequest.builder().method(\"GET\")\n                                            .endpoint(\"https://api.gogrid.com/api/grid/loadbalancer/add\")\n                                            .addQueryParam(\"v\", \"1.5\")\n                                            .addQueryParam(\"name\", \"BalanceIt\")\n                                            .addQueryParam(\"loadbalancer.type\", \"Least Connect\")\n                                            .addQueryParam(\"loadbalancer.persistence\", \"SSL Sticky\")\n                                            .addQueryParam(\"virtualip.ip\", \"127.0.0.1\")\n                                            .addQueryParam(\"virtualip.port\", \"80\")\n                                            .addQueryParam(\"realiplist.0.ip\", \"127.0.0.1\")\n                                            .addQueryParam(\"realiplist.0.port\", \"8080\")\n                                            .addQueryParam(\"realiplist.1.ip\", \"127.0.0.1\")\n                                            .addQueryParam(\"realiplist.1.port\", \"9090\")\n                                            .addQueryParam(\"sig\", \"e9aafd0a5d4c69bb24536be4bce8a528\")\n                                            .addQueryParam(\"api_key\", \"identity\").build();\n\n   @Test\n   public void testAddLoadBalancer() throws NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(GridLoadBalancerApi.class, \"addLoadBalancer\", String.class, IpPortPair.class,\n            List.class, AddLoadBalancerOptions[].class);\n      GeneratedHttpRequest request = processor.createRequest(method, ImmutableList.<Object> of(\"BalanceIt\",\n            IpPortPair.builder().ip(Ip.builder().ip(\"127.0.0.1\").build()).port(80).build(),\n            ImmutableList.of(IpPortPair.builder().ip(Ip.builder().ip(\"127.0.0.1\").build()).port(8080).build(),\n                  IpPortPair.builder().ip(Ip.builder().ip(\"127.0.0.1\").build()).port(9090).build()),\n            new AddLoadBalancerOptions.Builder().create(\n                  LoadBalancerType.LEAST_CONNECTED, LoadBalancerPersistenceType.SSL_STICKY)));\n\n      request = (GeneratedHttpRequest) request.getFilters().get(0).filter(request);\n\n      assertRequestLineEquals(request, addLoadBalancer.getRequestLine());\n      assertNonPayloadHeadersEqual(request, \"\");\n      assertPayloadEquals(request, null, null, false);\n\n      assertResponseParserClassEquals(method, request, ParseLoadBalancerFromJsonResponse.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(request);\n   }\n\n   @Test\n   public void testEditLoadBalancer() throws NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(GridLoadBalancerApi.class, \"editLoadBalancer\", long.class, List.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(1L, ImmutableList.of(\n            IpPortPair.builder().ip(Ip.builder().ip(\"127.0.0.1\").build()).port(8080).build(),\n            IpPortPair.builder().ip(Ip.builder().ip(\"127.0.0.1\").build()).port(9090).build())));\n\n      assertRequestLineEquals(\n            httpRequest,\n            \"GET https://api.gogrid.com/api/grid/loadbalancer/edit?v=1.5&id=1&realiplist.0.ip=127.0.0.1&realiplist.0.port=8080&realiplist.1.ip=127.0.0.1&realiplist.1.port=9090 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseLoadBalancerFromJsonResponse.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(httpRequest);\n      httpRequest = (GeneratedHttpRequest) Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);\n\n      assertRequestLineEquals(\n            httpRequest,\n            \"GET https://api.gogrid.com/api/grid/loadbalancer/edit?v=1.5&id=1&realiplist.0.ip=127.0.0.1&realiplist.0.port=8080&realiplist.1.ip=127.0.0.1&realiplist.1.port=9090&sig=e9aafd0a5d4c69bb24536be4bce8a528&api_key=identity HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n   }\n\n   @Test\n   public void testEditLoadBalancerNamed() throws NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(GridLoadBalancerApi.class, \"editLoadBalancerNamed\", String.class, List.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"BalanceIt\", ImmutableList.of(\n            IpPortPair.builder().ip(Ip.builder().ip(\"127.0.0.1\").build()).port(8080).build(),\n            IpPortPair.builder().ip(Ip.builder().ip(\"127.0.0.1\").build()).port(9090).build())));\n\n      assertRequestLineEquals(httpRequest, \"GET https://api.gogrid.com/api/grid/loadbalancer/\"\n            + \"edit?v=1.5&name=BalanceIt&realiplist.0.ip=127.0.0.1&\"\n            + \"realiplist.0.port=8080&realiplist.1.ip=127.0.0.1&realiplist.1.port=9090 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseLoadBalancerFromJsonResponse.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(httpRequest);\n      httpRequest = (GeneratedHttpRequest) Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);\n\n      assertRequestLineEquals(\n            httpRequest,\n            \"GET https://api.gogrid.com/api/grid/loadbalancer/edit?v=1.5&name=BalanceIt&realiplist.0.ip=127.0.0.1&realiplist.0.port=8080&realiplist.1.ip=127.0.0.1&realiplist.1.port=9090&sig=e9aafd0a5d4c69bb24536be4bce8a528&api_key=identity HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n   }\n\n   @Test\n   public void testGetLoadBalancersByName() throws NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(GridLoadBalancerApi.class, \"getLoadBalancersByName\", String[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\n            \"My Load Balancer\", \"My Load Balancer 2\"));\n\n      assertRequestLineEquals(httpRequest, \"GET https://api.gogrid.com/api/grid/loadbalancer/\"\n            + \"get?v=1.5&name=My%20Load%20Balancer&name=My%20Load%20Balancer%202 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseLoadBalancerListFromJsonResponse.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(httpRequest);\n      httpRequest = (GeneratedHttpRequest) Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);\n\n      assertRequestLineEquals(httpRequest, \"GET https://api.gogrid.com/api/grid/loadbalancer/\"\n            + \"get?v=1.5&name=My%20Load%20Balancer&name=My%20Load%20Balancer%202&\"\n            + \"sig=e9aafd0a5d4c69bb24536be4bce8a528&api_key=identity \" + \"HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n   }\n\n   @Test\n   public void testDeleteLoadBalancerById() throws NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(GridLoadBalancerApi.class, \"deleteById\", Long.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(55L));\n\n      assertRequestLineEquals(httpRequest, \"GET https://api.gogrid.com/api/grid/loadbalancer/\"\n            + \"delete?v=1.5&id=55 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseLoadBalancerFromJsonResponse.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(httpRequest);\n      httpRequest = (GeneratedHttpRequest) Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);\n\n      assertRequestLineEquals(httpRequest, \"GET https://api.gogrid.com/api/grid/loadbalancer/\" + \"delete?v=1.5&id=55&\"\n            + \"sig=e9aafd0a5d4c69bb24536be4bce8a528&api_key=identity \" + \"HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/test/java/org/jclouds/gogrid/features/GridServerApiTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.features;\n\nimport static org.jclouds.reflect.Reflection2.method;\n\nimport java.io.IOException;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.gogrid.domain.PowerCommand;\nimport org.jclouds.gogrid.functions.ParseCredentialsFromJsonResponse;\nimport org.jclouds.gogrid.functions.ParseOptionsFromJsonResponse;\nimport org.jclouds.gogrid.options.GetServerListOptions;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Iterables;\nimport com.google.common.reflect.Invokable;\n/**\n * Tests behavior of {@code GridServerApi}\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"GridServerApiTest\")\npublic class GridServerApiTest extends BaseGoGridApiTest<GridServerApi> {\n\n   @Test\n   public void testGetServerListWithOptions() throws NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(GridServerApi.class, \"getServerList\", GetServerListOptions[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\n               new GetServerListOptions.Builder().onlySandboxServers()));\n\n      assertRequestLineEquals(httpRequest,\n               \"GET https://api.gogrid.com/api/grid/server/list?v=1.6&isSandbox=true HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n      httpRequest = (GeneratedHttpRequest) Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);\n\n      assertRequestLineEquals(httpRequest, \"GET https://api.gogrid.com/api/grid/server/list?\"\n               + \"v=1.6&isSandbox=true&sig=e9aafd0a5d4c69bb24536be4bce8a528&api_key=identity \" + \"HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n   }\n\n   @Test\n   public void testGetServersByName() throws NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(GridServerApi.class, \"getServersByName\", String[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"server1\"));\n\n      assertRequestLineEquals(httpRequest, \"GET https://api.gogrid.com/api/grid/server/get?v=1.6&name=server1 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n      httpRequest = (GeneratedHttpRequest) Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);\n\n      assertRequestLineEquals(httpRequest, \"GET https://api.gogrid.com/api/grid/server/get?\" + \"v=1.6&name=server1&\"\n               + \"sig=e9aafd0a5d4c69bb24536be4bce8a528&api_key=identity \" + \"HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n   }\n\n   @Test\n   public void testGetServersById() throws NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(GridServerApi.class, \"getServersById\", long[].class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(123L));\n\n      assertRequestLineEquals(httpRequest, \"GET https://api.gogrid.com/api/grid/server/get?v=1.6&id=123 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, EmptySetOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n      httpRequest = (GeneratedHttpRequest) Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);\n\n      assertRequestLineEquals(httpRequest, \"GET https://api.gogrid.com/api/grid/server/get?\" + \"v=1.6&id=123&\"\n               + \"sig=e9aafd0a5d4c69bb24536be4bce8a528&api_key=identity \" + \"HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n   }\n\n\n   @Test\n   public void testPowerServer() throws NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(GridServerApi.class, \"power\", String.class, PowerCommand.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"PowerServer\",\n               PowerCommand.RESTART));\n\n      assertRequestLineEquals(httpRequest, \"GET https://api.gogrid.com/api/grid/server/power?v=1.6&\"\n               + \"server=PowerServer&power=restart \" + \"HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(httpRequest);\n      httpRequest = (GeneratedHttpRequest) Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);\n\n      assertRequestLineEquals(httpRequest, \"GET https://api.gogrid.com/api/grid/server/power?v=1.6&\"\n               + \"server=PowerServer&power=restart&\" + \"sig=e9aafd0a5d4c69bb24536be4bce8a528&api_key=identity \" + \"HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n   }\n\n   @Test\n   public void testDeleteByName() throws NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(GridServerApi.class, \"deleteByName\", String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(\"PowerServer\"));\n\n      assertRequestLineEquals(httpRequest, \"GET https://api.gogrid.com/api/grid/server/delete?v=1.6&\"\n               + \"name=PowerServer \" + \"HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, NullOnNotFoundOr404.class);\n\n      checkFilters(httpRequest);\n      httpRequest = (GeneratedHttpRequest) Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);\n\n      assertRequestLineEquals(httpRequest, \"GET https://api.gogrid.com/api/grid/server/delete?v=1.6&\"\n               + \"name=PowerServer&\" + \"sig=e9aafd0a5d4c69bb24536be4bce8a528&api_key=identity \" + \"HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n   }\n\n   @Test\n   public void testGetRamSizes() throws NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(GridServerApi.class, \"getRamSizes\");\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(httpRequest, \"GET https://api.gogrid.com/api/common/lookup/list?v=1.6&lookup=server.ram \"\n               + \"HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseOptionsFromJsonResponse.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(httpRequest);\n      httpRequest = (GeneratedHttpRequest) Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);\n\n      assertRequestLineEquals(httpRequest, \"GET https://api.gogrid.com/api/common/lookup/list?v=1.6&lookup=server.ram&\"\n               + \"sig=e9aafd0a5d4c69bb24536be4bce8a528&api_key=identity \" + \"HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n   }\n\n   @Test\n   public void testServerCredentials() throws NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(GridServerApi.class, \"getServerCredentials\", long.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(1));\n\n      assertRequestLineEquals(httpRequest,\n               \"GET https://api.gogrid.com/api/support/grid/password/get?v=1.6&id=1 HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseCredentialsFromJsonResponse.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n   }\n\n   @Test\n   public void testTypes() throws NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(GridServerApi.class, \"getTypes\");\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.of());\n\n      assertRequestLineEquals(httpRequest,\n               \"GET https://api.gogrid.com/api/common/lookup/list?v=1.6&lookup=server.type HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertResponseParserClassEquals(method, httpRequest, ParseOptionsFromJsonResponse.class);\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n   }\n\n   @Test\n   public void testEditServerDescription() throws NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(GridServerApi.class, \"editServerDescription\", long.class, String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(2, \"newDesc\"));\n\n      assertRequestLineEquals(httpRequest, \"GET https://api.gogrid.com/api/grid/server/edit?v=1.6&\"\n            + \"id=2&description=newDesc HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(httpRequest);\n      httpRequest = (GeneratedHttpRequest) Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);\n\n      assertRequestLineEquals(httpRequest, \"GET https://api.gogrid.com/api/grid/server/edit?v=1.6&\"\n            + \"id=2&description=newDesc&\" + \"sig=e9aafd0a5d4c69bb24536be4bce8a528&api_key=identity \" + \"HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n   }\n   \n   @Test\n   public void testEditServerRam() throws NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(GridServerApi.class, \"editServerRam\", long.class, String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(2, \"1GB\"));\n\n      assertRequestLineEquals(httpRequest, \"GET https://api.gogrid.com/api/grid/server/edit?v=1.6&\"\n            + \"id=2&server.ram=1GB HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(httpRequest);\n      httpRequest = (GeneratedHttpRequest) Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);\n\n      assertRequestLineEquals(httpRequest, \"GET https://api.gogrid.com/api/grid/server/edit?v=1.6&\"\n            + \"id=2&server.ram=1GB&\" + \"sig=e9aafd0a5d4c69bb24536be4bce8a528&api_key=identity \" + \"HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n   }\n   \n   @Test\n   public void testEditServerType() throws NoSuchMethodException, IOException {\n      Invokable<?, ?> method = method(GridServerApi.class, \"editServerType\", long.class, String.class);\n      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(2, \"web\"));\n\n      assertRequestLineEquals(httpRequest, \"GET https://api.gogrid.com/api/grid/server/edit?v=1.6&\"\n            + \"id=2&server.type=web HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n\n      assertSaxResponseParserClassEquals(method, null);\n      assertFallbackClassEquals(method, null);\n\n      checkFilters(httpRequest);\n      httpRequest = (GeneratedHttpRequest) Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);\n\n      assertRequestLineEquals(httpRequest, \"GET https://api.gogrid.com/api/grid/server/edit?v=1.6&\"\n            + \"id=2&server.type=web&\" + \"sig=e9aafd0a5d4c69bb24536be4bce8a528&api_key=identity \" + \"HTTP/1.1\");\n      assertNonPayloadHeadersEqual(httpRequest, \"\");\n      assertPayloadEquals(httpRequest, null, null, false);\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/test/java/org/jclouds/gogrid/features/GridServerClientExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.Assert.fail;\n\nimport java.net.URI;\n\nimport org.jclouds.gogrid.GoGridApi;\nimport org.jclouds.gogrid.options.AddServerOptions;\nimport org.jclouds.gogrid.options.GetServerListOptions;\nimport org.jclouds.gogrid.parse.ParseServerListTest;\nimport org.jclouds.gogrid.parse.ParseServerTest;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"GridServerClientExpectTest\")\npublic class GridServerClientExpectTest extends BaseGoGridHttpApiExpectTest {\n\n   HttpRequest addServer = HttpRequest.builder().method(\"GET\")\n                                      .endpoint(\"https://api.gogrid.com/api/grid/server/add\")\n                                      .addQueryParam(\"v\", \"1.6\")\n                                      .addQueryParam(\"name\", \"serverName\")\n                                      .addQueryParam(\"image\", \"img55\")\n                                      .addQueryParam(\"server.ram\", \"memory\")\n                                      .addQueryParam(\"ip\", \"127.0.0.1\")\n                                      .addQueryParam(\"sig\", \"e9aafd0a5d4c69bb24536be4bce8a528\")\n                                      .addQueryParam(\"api_key\", \"identity\").build();\n\n   public void testAddServerWhenResponseIs2xx() throws Exception {\n      HttpResponse listGridServersResponse = HttpResponse.builder().statusCode(200).payload(\n               payloadFromResourceWithContentType(\"/test_get_server_list.json\", \"application/json\")).build();\n\n      GoGridApi addServerWorked = requestSendsResponse(addServer, listGridServersResponse);\n\n      assertEquals(addServerWorked.getServerServices().addServer(\"serverName\", \"img55\", \"memory\", \"127.0.0.1\")\n               .toString(), new ParseServerTest().expected().toString());\n   }\n\n   HttpRequest addServerOptions = HttpRequest.builder().method(\"GET\")\n                                             .endpoint(\"https://api.gogrid.com/api/grid/server/add\")\n                                             .addQueryParam(\"v\", \"1.6\")\n                                             .addQueryParam(\"name\", \"serverName\")\n                                             .addQueryParam(\"image\", \"img55\")\n                                             .addQueryParam(\"server.ram\", \"memory\")\n                                             .addQueryParam(\"ip\", \"127.0.0.1\")\n                                             .addQueryParam(\"isSandbox\", \"true\")\n                                             .addQueryParam(\"description\", \"fooy\")\n                                             .addQueryParam(\"sig\", \"e9aafd0a5d4c69bb24536be4bce8a528\")\n                                             .addQueryParam(\"api_key\", \"identity\").build();\n\n   public void testAddServerWithOptionsWhenResponseIs2xx() throws Exception {\n      HttpResponse listGridServersResponse = HttpResponse.builder().statusCode(200).payload(\n               payloadFromResourceWithContentType(\"/test_get_server_list.json\", \"application/json\")).build();\n\n      GoGridApi addServerWithOptionsWorked = requestSendsResponse(addServerOptions, listGridServersResponse);\n\n      assertEquals(addServerWithOptionsWorked.getServerServices().addServer(\"serverName\", \"img55\", \"memory\",\n               \"127.0.0.1\", new AddServerOptions().asSandboxType().withDescription(\"fooy\")).toString(),\n               new ParseServerTest().expected().toString());\n   }\n\n   public void testGetServerListWhenResponseIs2xx() throws Exception {\n      HttpRequest listGridServers = HttpRequest.builder().method(\"GET\").endpoint(\n               URI.create(\"https://api.gogrid.com/api/grid/server/list?\" + \"v=1.6&\"\n                        + \"sig=e9aafd0a5d4c69bb24536be4bce8a528&api_key=identity\")).build();\n\n      HttpResponse listGridServersResponse = HttpResponse.builder().statusCode(200).payload(\n               payloadFromResourceWithContentType(\"/test_get_server_list.json\", \"application/json\")).build();\n\n      GoGridApi clientWhenGridServersExist = requestSendsResponse(listGridServers, listGridServersResponse);\n\n      assertEquals(clientWhenGridServersExist.getServerServices().getServerList().toString(), new ParseServerListTest()\n               .expected().toString());\n   }\n\n   public void testGetServerListWhenReponseIs404IsEmpty() throws Exception {\n      HttpRequest listGridServers = HttpRequest.builder().method(\"GET\").endpoint(\n               URI.create(\"https://api.gogrid.com/api/grid/server/list?\" + \"v=1.6&\"\n                        + \"sig=e9aafd0a5d4c69bb24536be4bce8a528&api_key=identity\")).build();\n\n      HttpResponse listGridServersResponse = HttpResponse.builder().statusCode(404).payload(\n               payloadFromResourceWithContentType(\"/test_error_handler.json\", \"application/json\")).build();\n\n      GoGridApi clientWhenNoGridServersExist = requestSendsResponse(listGridServers, listGridServersResponse);\n\n      assertTrue(clientWhenNoGridServersExist.getServerServices().getServerList().isEmpty());\n   }\n\n   public void testGetServerListWithOptionsWhenResponseIs2xx() throws Exception {\n      HttpRequest listGridServers = HttpRequest.builder().method(\"GET\").endpoint(\n               URI.create(\"https://api.gogrid.com/api/grid/server/list?\" + \"v=1.6&isSandbox=true&\"\n                        + \"sig=e9aafd0a5d4c69bb24536be4bce8a528&api_key=identity\")).build();\n\n      HttpResponse listGridServersResponse = HttpResponse.builder().statusCode(200).payload(\n               payloadFromResourceWithContentType(\"/test_get_server_list.json\", \"application/json\")).build();\n\n      GoGridApi clientWhenGridServersExist = requestSendsResponse(listGridServers, listGridServersResponse);\n\n      assertEquals(clientWhenGridServersExist.getServerServices().getServerList(\n               new GetServerListOptions.Builder().onlySandboxServers()).toString(), new ParseServerListTest()\n               .expected().toString());\n   }\n\n   public void testGetServerCredentialsWhenNotFoundThrowsResourceNotFoundExceptionWithNiceMessage() throws Exception {\n      HttpRequest listGridServers = HttpRequest.builder().method(\"GET\").endpoint(\n               URI.create(\"https://api.gogrid.com/api/support/grid/password/get?\" + \"v=1.6&id=11&\"\n                        + \"sig=e9aafd0a5d4c69bb24536be4bce8a528&api_key=identity\")).build();\n\n      HttpResponse listGridServersResponse = HttpResponse.builder().statusCode(400).payload(\n               payloadFromResourceWithContentType(\"/test_error_handler.json\", \"application/json\")).build();\n\n      GoGridApi clientWhenGridServersNotFound = requestSendsResponse(listGridServers, listGridServersResponse);\n      try {\n         clientWhenGridServersNotFound.getServerServices().getServerCredentials(11);\n         fail(\"should have failed\");\n      } catch (ResourceNotFoundException e) {\n         assertEquals(e.getMessage(), \"No object found that matches your input criteria.\");\n      }\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/test/java/org/jclouds/gogrid/functions/ParseCredentialsFromJsonResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\nimport java.lang.reflect.Type;\nimport java.net.UnknownHostException;\nimport java.util.Map;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.gogrid.domain.IpState;\nimport org.jclouds.gogrid.domain.ServerImageState;\nimport org.jclouds.gogrid.domain.ServerImageType;\nimport org.jclouds.gogrid.domain.ServerState;\nimport org.jclouds.gogrid.functions.internal.CustomDeserializers;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.json.config.GsonModule;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Maps;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport com.google.inject.Provides;\n\n//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"ParseCredentialsFromJsonResponseTest\")\npublic class ParseCredentialsFromJsonResponseTest {\n\n   @Test(expectedExceptions = IllegalStateException.class)\n   public void testFailWhenTooManyPasswords() throws UnknownHostException {\n      InputStream is = getClass().getResourceAsStream(\"/test_credentials_list.json\");\n\n      HttpResponse response = HttpResponse.builder().statusCode(200).message(\"ok\").payload(is).build();\n\n      ParseCredentialsFromJsonResponse parser = i.getInstance(ParseCredentialsFromJsonResponse.class);\n      parser.apply(response);\n   }\n\n   @Test\n   public void testValid() throws UnknownHostException {\n      InputStream is = getClass().getResourceAsStream(\"/test_credential.json\");\n\n      HttpResponse response = HttpResponse.builder().statusCode(200).message(\"ok\").payload(is).build();\n\n      ParseCredentialsFromJsonResponse parser = i.getInstance(ParseCredentialsFromJsonResponse.class);\n      Credentials creds = parser.apply(response);\n      assertEquals(creds.identity, \"root\");\n      assertEquals(creds.credential, \"zot40ced\");\n\n   }\n\n   Injector i = Guice.createInjector(new GsonModule() {\n      @Override\n      protected void configure() {\n         bind(DateAdapter.class).to(LongDateAdapter.class);\n         super.configure();\n      }\n\n      @Provides\n      @Singleton\n      public Map<Type, Object> provideCustomAdapterBindings() {\n         Map<Type, Object> bindings = Maps.newHashMap();\n         bindings.put(IpState.class, new CustomDeserializers.IpStateAdapter());\n         bindings.put(ServerImageType.class, new CustomDeserializers.ServerImageTypeAdapter());\n         bindings.put(ServerImageState.class, new CustomDeserializers.ServerImageStateAdapter());\n         bindings.put(ServerState.class, new CustomDeserializers.ServerStateAdapter());\n         return bindings;\n      }\n   });\n\n}\n"
  },
  {
    "path": "providers/gogrid/src/test/java/org/jclouds/gogrid/functions/ParseJobsFromJsonResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\nimport java.lang.reflect.Type;\nimport java.net.UnknownHostException;\nimport java.util.Date;\nimport java.util.Map;\nimport java.util.SortedSet;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.gogrid.domain.Job;\nimport org.jclouds.gogrid.domain.JobProperties;\nimport org.jclouds.gogrid.domain.JobState;\nimport org.jclouds.gogrid.domain.ObjectType;\nimport org.jclouds.gogrid.domain.Option;\nimport org.jclouds.gogrid.functions.internal.CustomDeserializers;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.json.config.GsonModule;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Maps;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport com.google.inject.Provides;\n\n//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"ParseJobsFromJsonResponseTest\")\npublic class ParseJobsFromJsonResponseTest {\n\n   @Test\n   public void testApplyInputStreamDetails() throws UnknownHostException {\n      InputStream is = getClass().getResourceAsStream(\"/test_get_job_list.json\");\n\n      ParseJobListFromJsonResponse parser = i.getInstance(ParseJobListFromJsonResponse.class);\n      SortedSet<Job> response = parser.apply(HttpResponse.builder().statusCode(200).message(\"ok\").payload(is).build());\n\n      Map<String, String> details = ImmutableMap.of(\n            \"image\", \"GSI-f8979644-e646-4711-ad58-d98a5fa3612c\",\n            \"ip\", \"204.51.240.189\",\n            \"name\", \"ServerCreated40562\",\n            \"type\", \"virtual_server\");\n\n      Job job = Job.builder().id(250628L).command(Option.createWithIdNameAndDescription(7L, \"DeleteVirtualServer\", \"Delete Virtual Server\"))\n            .objectType(ObjectType.VIRTUAL_SERVER).createdOn(new Date(1267404528895L)).lastUpdatedOn(new Date(1267404538592L))\n            .currentState(JobState.SUCCEEDED).attempts(1).owner(\"3116784158f0af2d-24076@api.gogrid.com\").history(\n                  JobProperties.builder().id(940263L).updatedOn(new Date(1267404528897L)).state(JobState.CREATED).build(),\n                  JobProperties.builder().id(940264L).updatedOn(new Date(1267404528967L)).state(JobState.QUEUED).build())\n            .details(details).build();\n      assertEquals(job, Iterables.getOnlyElement(response));\n   }\n\n   Injector i = Guice.createInjector(new GsonModule() {\n      @Override\n      protected void configure() {\n         bind(DateAdapter.class).to(LongDateAdapter.class);\n         super.configure();\n      }\n\n      @Provides\n      @Singleton\n      public Map<Type, Object> provideCustomAdapterBindings() {\n         Map<Type, Object> bindings = Maps.newHashMap();\n         bindings.put(ObjectType.class, new CustomDeserializers.ObjectTypeAdapter());\n         bindings.put(JobState.class, new CustomDeserializers.JobStateAdapter());\n         return bindings;\n      }\n   });\n\n}\n"
  },
  {
    "path": "providers/gogrid/src/test/java/org/jclouds/gogrid/functions/ParseLoadBalancersFromJsonResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\nimport java.lang.reflect.Type;\nimport java.net.UnknownHostException;\nimport java.util.Map;\nimport java.util.SortedSet;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.gogrid.domain.Ip;\nimport org.jclouds.gogrid.domain.IpPortPair;\nimport org.jclouds.gogrid.domain.IpState;\nimport org.jclouds.gogrid.domain.LoadBalancer;\nimport org.jclouds.gogrid.domain.LoadBalancerOs;\nimport org.jclouds.gogrid.domain.LoadBalancerPersistenceType;\nimport org.jclouds.gogrid.domain.LoadBalancerState;\nimport org.jclouds.gogrid.domain.LoadBalancerType;\nimport org.jclouds.gogrid.domain.Option;\nimport org.jclouds.gogrid.functions.internal.CustomDeserializers;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.json.config.GsonModule;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Maps;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport com.google.inject.Provides;\n\n//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"ParseLoadBalancersFromJsonResponseTest\")\npublic class ParseLoadBalancersFromJsonResponseTest {\n\n   @Test\n   public void testApplyInputStreamDetails() throws UnknownHostException {\n      InputStream is = getClass().getResourceAsStream(\"/test_get_load_balancer_list.json\");\n\n      ParseLoadBalancerListFromJsonResponse parser = i.getInstance(ParseLoadBalancerListFromJsonResponse.class);\n      SortedSet<LoadBalancer> response = parser.apply(HttpResponse.builder().statusCode(200).message(\"ok\").payload(is).build());\n\n      Option dc = Option.createWithIdNameAndDescription(1L, \"US-West-1\", \"US West 1 Datacenter\");\n\n      LoadBalancer loadBalancer = LoadBalancer.builder().id(6372L).name(\"Balancer\")\n            .virtualIp(IpPortPair.builder().ip(Ip.builder().id(1313082L)\n                  .ip(\"204.51.240.181\").subnet(\"204.51.240.176/255.255.255.240\").isPublic(true).state(IpState.ASSIGNED).datacenter(dc).build()).port(80).build())\n            .realIpList(\n                  IpPortPair.builder().ip(Ip.builder().id(1313086L).ip(\"204.51.240.185\").subnet(\"204.51.240.176/255.255.255.240\")\n                        .isPublic(true).state(IpState.ASSIGNED).datacenter(dc).build()).port(80).build(),\n                  IpPortPair.builder().ip(Ip.builder().id(1313089L).ip(\"204.51.240.188\").subnet(\"204.51.240.176/255.255.255.240\")\n                        .isPublic(true).state(IpState.ASSIGNED).datacenter(dc).build()).port(80).build())\n            .type(LoadBalancerType.ROUND_ROBIN).persistence(LoadBalancerPersistenceType.NONE)\n            .os(LoadBalancerOs.F5).state(LoadBalancerState.ON).datacenter(dc).build();\n\n      assertEquals(Iterables.getOnlyElement(response), loadBalancer);\n   }\n\n   Injector i = Guice.createInjector(new GsonModule() {\n      @Override\n      protected void configure() {\n         bind(DateAdapter.class).to(LongDateAdapter.class);\n         super.configure();\n      }\n\n      @Provides\n      @Singleton\n      public Map<Type, Object> provideCustomAdapterBindings() {\n         Map<Type, Object> bindings = Maps.newHashMap();\n         bindings.put(LoadBalancerOs.class, new CustomDeserializers.LoadBalancerOsAdapter());\n         bindings.put(LoadBalancerState.class, new CustomDeserializers.LoadBalancerStateAdapter());\n         bindings.put(LoadBalancerPersistenceType.class, new CustomDeserializers.LoadBalancerPersistenceTypeAdapter());\n         bindings.put(LoadBalancerType.class, new CustomDeserializers.LoadBalancerTypeAdapter());\n         bindings.put(IpState.class, new CustomDeserializers.IpStateAdapter());\n         return bindings;\n      }\n   });\n}\n"
  },
  {
    "path": "providers/gogrid/src/test/java/org/jclouds/gogrid/functions/ParseServerNameToCredentialsMapFromJsonResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.functions;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\nimport java.lang.reflect.Type;\nimport java.net.UnknownHostException;\nimport java.util.Map;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.gogrid.domain.IpState;\nimport org.jclouds.gogrid.domain.ServerImageState;\nimport org.jclouds.gogrid.domain.ServerImageType;\nimport org.jclouds.gogrid.domain.ServerState;\nimport org.jclouds.gogrid.functions.internal.CustomDeserializers;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.json.config.GsonModule;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Maps;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\nimport com.google.inject.Provides;\n\n//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"ParseServerNameToCredentialsMapFromJsonResponseTest\")\npublic class ParseServerNameToCredentialsMapFromJsonResponseTest {\n\n   @Test\n   public void testApplyInputStreamDetails() throws UnknownHostException {\n      InputStream is = getClass().getResourceAsStream(\"/test_credentials_list.json\");\n\n      ParseServerNameToCredentialsMapFromJsonResponse parser = i\n            .getInstance(ParseServerNameToCredentialsMapFromJsonResponse.class);\n      Map<String, Credentials> response = parser.apply(HttpResponse.builder().statusCode(200).message(\"ok\").payload(is).build());\n\n      assertEquals(response.size(), 6);\n   }\n\n   Injector i = Guice.createInjector(new GsonModule() {\n      @Override\n      protected void configure() {\n         bind(DateAdapter.class).to(LongDateAdapter.class);\n         super.configure();\n      }\n\n      @Provides\n      @Singleton\n      public Map<Type, Object> provideCustomAdapterBindings() {\n         Map<Type, Object> bindings = Maps.newHashMap();\n         bindings.put(IpState.class, new CustomDeserializers.IpStateAdapter());\n         bindings.put(ServerImageType.class, new CustomDeserializers.ServerImageTypeAdapter());\n         bindings.put(ServerImageState.class, new CustomDeserializers.ServerImageStateAdapter());\n         bindings.put(ServerState.class, new CustomDeserializers.ServerStateAdapter());\n         return bindings;\n      }\n   });\n\n}\n"
  },
  {
    "path": "providers/gogrid/src/test/java/org/jclouds/gogrid/handlers/GoGridErrorHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.handlers;\n\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\n\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.json.config.GsonModule;\nimport org.testng.TestException;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Guice;\n\n/**\n * Tests that the GoGridErrorHandler is correctly handling the exceptions.\n */\n//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"GoGridErrorHandlerTest\")\npublic class GoGridErrorHandlerTest {\n\n   @Test\n   public void testHandler() {\n      InputStream is = getClass().getResourceAsStream(\"/test_error_handler.json\");\n\n      GoGridErrorHandler handler = Guice.createInjector(new GsonModule()).getInstance(GoGridErrorHandler.class);\n\n      HttpCommand command = createHttpCommand();\n      handler.handleError(command, HttpResponse.builder().statusCode(200).message(\"ok\").payload(is).build());\n\n      Exception createdException = command.getException();\n\n      assertNotNull(createdException, \"There should've been an exception generated\");\n      String message = createdException.getMessage();\n      assertTrue(message.contains(\"No object found that matches your input criteria.\"),\n            \"Didn't find the expected error cause in the exception message\");\n      assertTrue(message.contains(\"IllegalArgumentException\"),\n            \"Didn't find the expected error code in the exception message\");\n\n      // make sure the InputStream is closed\n      try {\n         is.available();\n         throw new TestException(\"Stream wasn't closed by the GoGridErrorHandler when it should've\");\n      } catch (IOException e) {\n         // this is the excepted output\n      }\n   }\n\n   HttpCommand createHttpCommand() {\n      return new HttpCommand(HttpRequest.builder().method(\"GET\").endpoint(\"http://localhost\").build());\n   }\n\n   InputStream createInputStreamFromString(String s) {\n      return new ByteArrayInputStream(s.getBytes());\n   }\n\n}\n"
  },
  {
    "path": "providers/gogrid/src/test/java/org/jclouds/gogrid/options/AddServerOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.options;\n\nimport static org.jclouds.gogrid.options.AddServerOptions.Builder.asSandboxType;\nimport static org.jclouds.gogrid.options.AddServerOptions.Builder.withDescription;\nimport static org.testng.Assert.assertEquals;\n\nimport com.google.common.collect.ImmutableList;\n\nimport org.jclouds.http.options.HttpRequestOptions;\nimport org.testng.annotations.Test;\n\n/**\n * Tests possible uses of AddServerOptions and AddServerOptions.Builder.*\n */\n//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"AddServerOptionsTest\")\npublic class AddServerOptionsTest {\n\n   @Test\n   public void testAssignability() {\n      assert HttpRequestOptions.class.isAssignableFrom(AddServerOptions.class);\n      assert !String.class.isAssignableFrom(AddServerOptions.class);\n   }\n\n   @Test\n   public void testWithDescription() {\n      AddServerOptions options = new AddServerOptions();\n      options.withDescription(\"test\");\n      assertEquals(options.buildQueryParameters().get(\"description\"),\n               ImmutableList.of(\"test\"));\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testWith501LengthDescription() {\n      AddServerOptions options = new AddServerOptions();\n      StringBuilder builder = new StringBuilder();\n\n      for (int i = 0; i < 1 * 501; i++)\n         builder.append('a');\n\n      String description = builder.toString();\n\n      options.withDescription(description);\n\n   }\n\n   @Test\n   public void testWith500LengthDescription() {\n      AddServerOptions options = new AddServerOptions();\n      StringBuilder builder = new StringBuilder();\n\n      for (int i = 0; i < 1 * 500; i++)\n         builder.append('a');\n\n      String description = builder.toString();\n\n      options.withDescription(description);\n      assertEquals(options.buildQueryParameters().get(\"description\"),\n               ImmutableList.of(description));\n   }\n\n   @Test\n   public void testNullWithDescription() {\n      AddServerOptions options = new AddServerOptions();\n      assertEquals(options.buildQueryParameters().get(\"description\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testWithDescriptionStatic() {\n      AddServerOptions options = withDescription(\"test\");\n      assertEquals(options.buildQueryParameters().get(\"description\"),\n               ImmutableList.of(\"test\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testWithDescriptionNPE() {\n      withDescription(null);\n   }\n\n   @Test\n   public void testAsSandboxType() {\n      AddServerOptions options = new AddServerOptions();\n      options.asSandboxType();\n      assertEquals(options.buildQueryParameters().get(\"isSandbox\"),\n               ImmutableList.of(\"true\"));\n   }\n\n   @Test\n   public void testAsSandboxTypeStatic() {\n      AddServerOptions options = asSandboxType();\n      assertEquals(options.buildQueryParameters().get(\"isSandbox\"),\n               ImmutableList.of(\"true\"));\n   }\n\n}\n"
  },
  {
    "path": "providers/gogrid/src/test/java/org/jclouds/gogrid/options/SaveImageOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.options;\n\nimport static org.jclouds.gogrid.options.SaveImageOptions.Builder.withDescription;\nimport static org.testng.Assert.assertEquals;\n\nimport com.google.common.collect.ImmutableList;\n\nimport org.jclouds.http.options.HttpRequestOptions;\nimport org.testng.annotations.Test;\n\n/**\n * Tests possible uses of SaveImageOptions and SaveImageOptions.Builder.*\n */\n//NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"SaveImageOptionsTest\")\npublic class SaveImageOptionsTest {\n\n   @Test\n   public void testAssignability() {\n      assert HttpRequestOptions.class.isAssignableFrom(SaveImageOptions.class);\n      assert !String.class.isAssignableFrom(SaveImageOptions.class);\n   }\n\n   @Test\n   public void testWithDescription() {\n      SaveImageOptions options = new SaveImageOptions();\n      options.withDescription(\"test\");\n      assertEquals(options.buildQueryParameters().get(\"description\"),\n               ImmutableList.of(\"test\"));\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testWith501LengthDescription() {\n      SaveImageOptions options = new SaveImageOptions();\n      StringBuilder builder = new StringBuilder();\n\n      for (int i = 0; i < 1 * 501; i++)\n         builder.append('a');\n\n      String description = builder.toString();\n\n      options.withDescription(description);\n\n   }\n\n   @Test\n   public void testWith500LengthDescription() {\n      SaveImageOptions options = new SaveImageOptions();\n      StringBuilder builder = new StringBuilder();\n\n      for (int i = 0; i < 1 * 500; i++)\n         builder.append('a');\n\n      String description = builder.toString();\n\n      options.withDescription(description);\n      assertEquals(options.buildQueryParameters().get(\"description\"),\n               ImmutableList.of(description));\n   }\n\n   @Test\n   public void testNullWithDescription() {\n      SaveImageOptions options = new SaveImageOptions();\n      assertEquals(options.buildQueryParameters().get(\"description\"), ImmutableList.of());\n   }\n\n   @Test\n   public void testWithDescriptionStatic() {\n      SaveImageOptions options = withDescription(\"test\");\n      assertEquals(options.buildQueryParameters().get(\"description\"),\n               ImmutableList.of(\"test\"));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testWithDescriptionNPE() {\n      withDescription(null);\n   }\n\n}\n"
  },
  {
    "path": "providers/gogrid/src/test/java/org/jclouds/gogrid/parse/ParseServerListTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.parse;\n\nimport java.util.Date;\nimport java.util.Set;\n\nimport org.jclouds.gogrid.config.GoGridParserModule;\nimport org.jclouds.gogrid.domain.BillingToken;\nimport org.jclouds.gogrid.domain.Customer;\nimport org.jclouds.gogrid.domain.Ip;\nimport org.jclouds.gogrid.domain.IpState;\nimport org.jclouds.gogrid.domain.Option;\nimport org.jclouds.gogrid.domain.Server;\nimport org.jclouds.gogrid.domain.ServerImage;\nimport org.jclouds.gogrid.domain.ServerImageState;\nimport org.jclouds.gogrid.domain.ServerImageType;\nimport org.jclouds.gogrid.domain.ServerState;\nimport org.jclouds.json.BaseSetParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\", testName = \"ParseServerListTest\")\npublic class ParseServerListTest extends BaseSetParserTest<Server> {\n\n   @Override\n   public String resource() {\n      return \"/test_get_server_list.json\";\n   }\n\n   @Override\n   @SelectJson(\"list\")\n   public Set<Server> expected() {\n      Option dc = Option.createWithIdNameAndDescription(1L, \"US-West-1\", \"US West 1 Datacenter\");\n      Option centOs = Option.createWithIdNameAndDescription(13L, \"CentOS 5.2 (32-bit)\", \"CentOS 5.2 (32-bit)\");\n      Option webServer = Option.createWithIdNameAndDescription(1L, \"Web Server\", \"Web or Application Server\");\n      return ImmutableSet.of(Server.builder().id(75245L).datacenter(dc).name(\"PowerServer\").description(\"server to test the api. created by Alex\")\n            .state(ServerState.ON).type(webServer).ram(Option.createWithIdNameAndDescription(1L, \"512MB\", \"Server with 512MB RAM\")).os(centOs)\n            .ip(Ip.builder().id(1313079L).ip(\"204.51.240.178\").subnet(\"204.51.240.176/255.255.255.240\").isPublic(true).state(IpState.ASSIGNED).datacenter(dc).build())\n            .image(ServerImage.builder().id(1946L).name(\"GSI-f8979644-e646-4711-ad58-d98a5fa3612c\").friendlyName(\"BitNami Gallery 2.3.1-0\")\n                  .description(\"http://bitnami.org/stack/gallery\").os(centOs).type(ServerImageType.WEB_APPLICATION_SERVER)\n                  .state(ServerImageState.AVAILABLE).location(\"24732/GSI-f8979644-e646-4711-ad58-d98a5fa3612c.img\").isActive(true).isPublic(true)\n                  .createdTime(new Date(1261504577971L)).updatedTime(new Date(1262649582180L)).billingTokens(\n                        BillingToken.builder().id(38L).name(\"CentOS 5.2 32bit\").build(),\n                        BillingToken.builder().id(56L).name(\"BitNami: Gallery\").build())\n                  .owner(Customer.builder().id(24732L).name(\"BitRock\").build()).build()).build());\n\n   }\n\n   protected Injector injector() {\n      return Guice.createInjector(new GoGridParserModule(), new GsonModule());\n   }\n\n}\n"
  },
  {
    "path": "providers/gogrid/src/test/java/org/jclouds/gogrid/parse/ParseServerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.parse;\n\nimport java.util.Date;\n\nimport org.jclouds.gogrid.config.GoGridParserModule;\nimport org.jclouds.gogrid.domain.BillingToken;\nimport org.jclouds.gogrid.domain.Customer;\nimport org.jclouds.gogrid.domain.Ip;\nimport org.jclouds.gogrid.domain.IpState;\nimport org.jclouds.gogrid.domain.Option;\nimport org.jclouds.gogrid.domain.Server;\nimport org.jclouds.gogrid.domain.ServerImage;\nimport org.jclouds.gogrid.domain.ServerImageState;\nimport org.jclouds.gogrid.domain.ServerImageType;\nimport org.jclouds.gogrid.domain.ServerState;\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.rest.annotations.OnlyElement;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\n@Test(groups = \"unit\", testName = \"ParseServerTest\")\npublic class ParseServerTest extends BaseItemParserTest<Server> {\n\n   @Override\n   public String resource() {\n      return \"/test_get_server_list.json\";\n   }\n\n   @Override\n   @SelectJson(\"list\")\n   @OnlyElement\n   public Server expected() {\n      Option dc = Option.createWithIdNameAndDescription(1L, \"US-West-1\", \"US West 1 Datacenter\");\n      Option centOs = Option.createWithIdNameAndDescription(13L, \"CentOS 5.2 (32-bit)\", \"CentOS 5.2 (32-bit)\");\n      Option webServer = Option.createWithIdNameAndDescription(1L, \"Web Server\", \"Web or Application Server\");\n      return Server.builder().id(75245L).datacenter(dc).isSandbox(false).name(\"PowerServer\").description(\"server to test the api. created by Alex\")\n            .state(ServerState.ON).type(webServer).ram(Option.createWithIdNameAndDescription(1L, \"512MB\", \"Server with 512MB RAM\"))\n            .os(centOs).ip(Ip.builder().id(1313079L).ip(\"204.51.240.178\").subnet(\"204.51.240.176/255.255.255.240\").isPublic(true).state(IpState.ASSIGNED).datacenter(dc).build())\n            .image(ServerImage.builder().id(1946L).name(\"GSI-f8979644-e646-4711-ad58-d98a5fa3612c\").friendlyName(\"BitNami Gallery 2.3.1-0\")\n                  .description(\"http://bitnami.org/stack/gallery\").os(centOs).type(ServerImageType.WEB_APPLICATION_SERVER)\n                  .state(ServerImageState.AVAILABLE).location(\"24732/GSI-f8979644-e646-4711-ad58-d98a5fa3612c.img\").isPublic(true)\n                  .isActive(true).createdTime(new Date(1261504577971L)).updatedTime(new Date(1262649582180L)).billingTokens(\n                        BillingToken.builder().id(38L).name(\"CentOS 5.2 32bit\").build(),\n                        BillingToken.builder().id(56L).name(\"BitNami: Gallery\").build()).owner(\n                        Customer.builder().id(24732L).name(\"BitRock\").build()).build()).build();\n   }\n\n   protected Injector injector() {\n      return Guice.createInjector(new GoGridParserModule(), new GsonModule());\n   }\n}\n"
  },
  {
    "path": "providers/gogrid/src/test/java/org/jclouds/gogrid/predicates/ServerLatestJobCompletedTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.gogrid.predicates;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.jclouds.gogrid.options.GetJobListOptions.Builder.latestJobForObjectByName;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.gogrid.domain.Job;\nimport org.jclouds.gogrid.domain.JobState;\nimport org.jclouds.gogrid.domain.Server;\nimport org.jclouds.gogrid.features.GridJobApi;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"ServerLatestJobCompletedTest\")\npublic class ServerLatestJobCompletedTest {\n\n   @Test\n   public void testPredicate() {\n      final String serverName = \"SERVER_NAME\";\n      Server server = createMock(Server.class);\n      expect(server.getName()).andStubReturn(serverName);\n\n      Job job = createMock(Job.class);\n      expect(job.getCurrentState()).andReturn(JobState.SUCCEEDED);\n\n      GridJobApi client = createMock(GridJobApi.class);\n      expect(client.getJobList(latestJobForObjectByName(serverName))).andReturn(ImmutableSet.<Job> of(job));\n\n      replay(job);\n      replay(client);\n      replay(server);\n\n      ServerLatestJobCompleted predicate = new ServerLatestJobCompleted(client);\n      assertTrue(predicate.apply(server), \"The result of the predicate should've been 'true'\");\n\n   }\n\n}\n"
  },
  {
    "path": "providers/gogrid/src/test/resources/log4j.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE log4j:configuration SYSTEM \"log4j.dtd\">\n\n    <!--\n        For more configuration infromation and examples see the Apache\n        Log4j website: http://logging.apache.org/log4j/\n    -->\n<log4j:configuration xmlns:log4j=\"http://jakarta.apache.org/log4j/\"\n    debug=\"false\">\n\n    <!-- A time/date based rolling appender -->\n    <appender name=\"WIREFILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds-wire.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n\n    <!-- A time/date based rolling appender -->\n    <appender name=\"FILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n    \n    <!-- A time/date based rolling appender -->\n    <appender name=\"COMPUTEFILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds-compute.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n\n    <!-- A time/date based rolling appender -->\n    <appender name=\"SSHFILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds-ssh.log\" />\n        <param name=\"Append\" value=\"true\" />\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\" />\n\n        <param name=\"Threshold\" value=\"TRACE\" />\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\" />\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n\n    <appender name=\"ASYNCCOMPUTE\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"COMPUTEFILE\" />\n    </appender>\n    \n    <appender name=\"ASYNCSSH\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"SSHFILE\" />\n    </appender>\n\n    <appender name=\"ASYNC\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"FILE\" />\n    </appender>\n\n    <appender name=\"ASYNCWIRE\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"WIREFILE\" />\n    </appender>\n\n    <!-- ================ -->\n    <!-- Limit categories -->\n    <!-- ================ -->\n\n    <category name=\"org.jclouds\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNC\" />\n    </category>\n\n    <category name=\"jclouds.headers\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNCWIRE\" />\n    </category>\n    \n    <category name=\"jclouds.ssh\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNCSSH\" />\n    </category>\n    \n    <category name=\"jclouds.wire\">\n        <priority value=\"DEBUG\" />\n        <appender-ref ref=\"ASYNCWIRE\" />\n    </category>\n\n    <category name=\"jclouds.compute\">\n        <priority value=\"TRACE\" />\n        <appender-ref ref=\"ASYNCCOMPUTE\" />\n    </category>\n    <!-- ======================= -->\n    <!-- Setup the Root category -->\n    <!-- ======================= -->\n\n    <root>\n        <priority value=\"WARN\" />\n    </root>\n\n</log4j:configuration>\n"
  },
  {
    "path": "providers/gogrid/src/test/resources/test_credential.json",
    "content": "{\n    \"list\": [\n      {\n        \"password\": \"zot40ced\",\n        \"object\": \"password\",\n        \"username\": \"root\",\n        \"server\": {\n            \"isSandbox\": false,\n            \"object\": \"server\",\n            \"type\": {\n                \"id\": 1,\n                \"description\": \"Web or Application Server\",\n                \"name\": \"Web Server\",\n                \"object\": \"option\"\n            },\n            \"os\": {\n                \"id\": 17,\n                \"description\": \"CentOS 5.3 (64-bit)\",\n                \"name\": \"CentOS 5.3 (64-bit)\",\n                \"object\": \"option\"\n            },\n            \"image\": {\n                \"type\": {\n                    \"id\": 1,\n                    \"description\": \"Web or Application Server\",\n                    \"name\": \"Web Server\",\n                    \"object\": \"option\"\n                },\n                \"owner\": {\n                    \"id\": -1,\n                    \"name\": \"GoGrid\",\n                    \"object\": \"customer\"\n                },\n                \"updatedTime\": 1257789076417,\n                \"isActive\": true,\n                \"id\": 1532,\n                \"isPublic\": true,\n                \"name\": \"centos5.3_64_base\",\n                \"billingtokens\": [\n                    {\n                        \"id\": 47,\n                        \"price\": 0,\n                        \"name\": \"CentOS 5.3 64bit\",\n                        \"object\": \"billingtoken\"\n                    }\n                ],\n                \"object\": \"serverimage\",\n                \"friendlyName\": \"CentOS 5.3 (64-bit) w/ None\",\n                \"os\": {\n                    \"id\": 17,\n                    \"description\": \"CentOS 5.3 (64-bit)\",\n                    \"name\": \"CentOS 5.3 (64-bit)\",\n                    \"object\": \"option\"\n                },\n                \"price\": 0,\n                \"description\": \"CentOS 5.3 (64-bit) w/ None\",\n                \"state\": {\n                    \"id\": 2,\n                    \"description\": \"Image is available for adds\",\n                    \"name\": \"Available\",\n                    \"object\": \"option\"\n                },\n                \"location\": \"gogrid/GSI-939ef909-84b8-4a2f-ad56-02ccd7da05ff.img\",\n              \"name\": \"bogus\",\n                \"architecture\": {\n                    \"id\": 2,\n                    \"description\": \"64 bit OS\",\n                    \"name\": \"64-bit\",\n                    \"object\": \"option\"\n                }\n            },\n            \"state\": {\n                \"id\": 1,\n                \"description\": \"Server is in active state.\",\n                \"name\": \"On\",\n                \"object\": \"option\"\n            },\n            \"ram\": {\n                \"id\": 1,\n                \"description\": \"Server with 512MB RAM\",\n                \"name\": \"512MB\",\n                \"object\": \"option\"\n            },\n            \"name\": \"proxied-944\",\n            \"ip\": {\n                \"id\": 1104200,\n                \"subnet\": \"173.1.155.16/255.255.255.240\",\n                \"state\": {\n                    \"id\": 2,\n                    \"description\": \"IP is reserved or in use\",\n                    \"name\": \"Assigned\",\n                    \"object\": \"option\"\n                },\n                \"datacenter\": {\n                    \"id\": 1,\n                    \"description\": \"US West 1 Datacenter\",\n                    \"name\": \"US-West-1\",\n                    \"object\": \"option\"\n                },\n                \"object\": \"ip\",\n                \"public\": true,\n                \"ip\": \"173.1.155.19\"\n            },\n            \"datacenter\": {\n                \"id\": 1,\n                \"description\": \"US West 1 Datacenter\",\n                \"name\": \"US-West-1\",\n                \"object\": \"option\"\n            },\n            \"id\": 134551\n        },\n        \"id\": 142243,\n        \"applicationtype\": \"os\"\n    },\n    {\n        \"id\": 28000,\n        \"username\": \"22290\",\n        \"applicationtype\": \"cloudstorage\",\n        \"object\": \"password\",\n        \"password\": \"200FMd2nDeomtfW.\"\n    }\n    ],\n    \"summary\": {\n        \"total\": 6,\n        \"start\": 0,\n        \"numpages\": 0,\n        \"returned\": 6\n    },\n    \"status\": \"success\",\n    \"method\": \"/support/password/list\"\n}\n"
  },
  {
    "path": "providers/gogrid/src/test/resources/test_credentials_list.json",
    "content": "{\n    \"list\": [\n        {\n            \"password\": \"dig44sos\",\n            \"object\": \"password\",\n            \"username\": \"root\",\n            \"server\": {\n                \"object\": \"server\",\n                \"isSandbox\": false,\n                \"type\": {\n                    \"object\": \"option\",\n                    \"description\": \"Web or Application Server\",\n                    \"name\": \"Web Server\",\n                    \"id\": 1\n                },\n                \"os\": {\n                    \"object\": \"option\",\n                    \"description\": \"CentOS 5.3 (64-bit)\",\n                    \"name\": \"CentOS 5.3 (64-bit)\",\n                    \"id\": 17\n                },\n                \"image\": {\n                    \"type\": {\n                        \"object\": \"option\",\n                        \"description\": \"Web or Application Server\",\n                        \"name\": \"Web Server\",\n                        \"id\": 1\n                    },\n                    \"owner\": {\n                        \"object\": \"customer\",\n                        \"name\": \"Gear6\",\n                        \"id\": 26443\n                    },\n                    \"updatedTime\": 1265675466171,\n                    \"isActive\": true,\n                    \"id\": 2500,\n                    \"createdTime\": 1265412834154,\n                    \"isPublic\": true,\n                    \"billingtokens\": [\n                        {\n                            \"price\": 0,\n                            \"name\": \"CentOS 5.3 64bit\",\n                            \"id\": 47\n                        },\n                        {\n                            \"price\": 60,\n                            \"name\": \"Gear 6 Paid Version\",\n                            \"id\": 76\n                        }\n                    ],\n                    \"object\": \"serverimage\",\n                    \"friendlyName\": \"gear6-memcache-server-2.3.6.2-x86_64\",\n                    \"os\": {\n                        \"object\": \"option\",\n                        \"description\": \"CentOS 5.3 (64-bit)\",\n                        \"name\": \"CentOS 5.3 (64-bit)\",\n                        \"id\": 17\n                    },\n                    \"price\": 60,\n                    \"description\": \"Gear6 Memcache Server 2.3.6.2 (64 bit)\",\n                    \"state\": {\n                        \"object\": \"option\",\n                        \"description\": \"Image is available for adds\",\n                        \"name\": \"Available\",\n                        \"id\": 2\n                    },\n                    \"location\": \"26443/GSI-7f498260-2b8a-43ef-aa77-5b403f8f739a.img\",\n                    \"name\": \"GSI-7f498260-2b8a-43ef-aa77-5b403f8f739a\"\n                },\n                \"state\": {\n                    \"object\": \"option\",\n                    \"description\": \"Server is in active state.\",\n                    \"name\": \"On\",\n                    \"id\": 1\n                },\n                \"ram\": {\n                    \"object\": \"option\",\n                    \"description\": \"Server with 512MB RAM\",\n                    \"name\": \"512MB\",\n                    \"id\": 1\n                },\n                \"name\": \"gogrid-19\",\n                \"ip\": {\n                    \"object\": \"ip\",\n                    \"public\": true,\n                    \"subnet\": \"204.51.240.176/255.255.255.240\",\n                    \"state\": {\n                        \"object\": \"option\",\n                        \"description\": \"IP is reserved or in use\",\n                        \"name\": \"Assigned\",\n                        \"id\": 2\n                    },\n                    \"ip\": \"204.51.240.189\",\n                    \"id\": 1313090\n                },\n                \"id\": 77332\n            },\n            \"id\": 82647,\n            \"applicationtype\": \"os\"\n        },\n        {\n            \"password\": \"job96qat\",\n            \"object\": \"password\",\n            \"username\": \"root\",\n            \"server\": {\n                \"object\": \"server\",\n                \"isSandbox\": false,\n                \"type\": {\n                    \"object\": \"option\",\n                    \"description\": \"Web or Application Server\",\n                    \"name\": \"Web Server\",\n                    \"id\": 1\n                },\n                \"os\": {\n                    \"object\": \"option\",\n                    \"description\": \"CentOS 5.3 (64-bit)\",\n                    \"name\": \"CentOS 5.3 (64-bit)\",\n                    \"id\": 17\n                },\n                \"image\": {\n                    \"type\": {\n                        \"object\": \"option\",\n                        \"description\": \"Web or Application Server\",\n                        \"name\": \"Web Server\",\n                        \"id\": 1\n                    },\n                    \"owner\": {\n                        \"object\": \"customer\",\n                        \"name\": \"Gear6\",\n                        \"id\": 26443\n                    },\n                    \"updatedTime\": 1265675466171,\n                    \"isActive\": true,\n                    \"id\": 2500,\n                    \"createdTime\": 1265412834154,\n                    \"isPublic\": true,\n                    \"billingtokens\": [\n                        {\n                            \"price\": 0,\n                            \"name\": \"CentOS 5.3 64bit\",\n                            \"id\": 47\n                        },\n                        {\n                            \"price\": 60,\n                            \"name\": \"Gear 6 Paid Version\",\n                            \"id\": 76\n                        }\n                    ],\n                    \"object\": \"serverimage\",\n                    \"friendlyName\": \"gear6-memcache-server-2.3.6.2-x86_64\",\n                    \"os\": {\n                        \"object\": \"option\",\n                        \"description\": \"CentOS 5.3 (64-bit)\",\n                        \"name\": \"CentOS 5.3 (64-bit)\",\n                        \"id\": 17\n                    },\n                    \"price\": 60,\n                    \"description\": \"Gear6 Memcache Server 2.3.6.2 (64 bit)\",\n                    \"state\": {\n                        \"object\": \"option\",\n                        \"description\": \"Image is available for adds\",\n                        \"name\": \"Available\",\n                        \"id\": 2\n                    },\n                    \"location\": \"26443/GSI-7f498260-2b8a-43ef-aa77-5b403f8f739a.img\",\n                    \"name\": \"GSI-7f498260-2b8a-43ef-aa77-5b403f8f739a\"\n                },\n                \"state\": {\n                    \"object\": \"option\",\n                    \"description\": \"Server is in active state.\",\n                    \"name\": \"On\",\n                    \"id\": 1\n                },\n                \"ram\": {\n                    \"object\": \"option\",\n                    \"description\": \"Server with 512MB RAM\",\n                    \"name\": \"512MB\",\n                    \"id\": 1\n                },\n                \"name\": \"gogrid-5288\",\n                \"ip\": {\n                    \"object\": \"ip\",\n                    \"public\": true,\n                    \"subnet\": \"204.51.240.176/255.255.255.240\",\n                    \"state\": {\n                        \"object\": \"option\",\n                        \"description\": \"IP is reserved or in use\",\n                        \"name\": \"Assigned\",\n                        \"id\": 2\n                    },\n                    \"ip\": \"204.51.240.186\",\n                    \"id\": 1313087\n                },\n                \"id\": 77335\n            },\n            \"id\": 82653,\n            \"applicationtype\": \"os\"\n        },\n        {\n            \"password\": \"fif70cij\",\n            \"object\": \"password\",\n            \"username\": \"root\",\n            \"server\": {\n                \"object\": \"server\",\n                \"isSandbox\": false,\n                \"type\": {\n                    \"object\": \"option\",\n                    \"description\": \"Web or Application Server\",\n                    \"name\": \"Web Server\",\n                    \"id\": 1\n                },\n                \"os\": {\n                    \"object\": \"option\",\n                    \"description\": \"CentOS 5.3 (64-bit)\",\n                    \"name\": \"CentOS 5.3 (64-bit)\",\n                    \"id\": 17\n                },\n                \"image\": {\n                    \"type\": {\n                        \"object\": \"option\",\n                        \"description\": \"Web or Application Server\",\n                        \"name\": \"Web Server\",\n                        \"id\": 1\n                    },\n                    \"owner\": {\n                        \"object\": \"customer\",\n                        \"name\": \"Gear6\",\n                        \"id\": 26443\n                    },\n                    \"updatedTime\": 1265675466171,\n                    \"isActive\": true,\n                    \"id\": 2500,\n                    \"createdTime\": 1265412834154,\n                    \"isPublic\": true,\n                    \"billingtokens\": [\n                        {\n                            \"price\": 0,\n                            \"name\": \"CentOS 5.3 64bit\",\n                            \"id\": 47\n                        },\n                        {\n                            \"price\": 60,\n                            \"name\": \"Gear 6 Paid Version\",\n                            \"id\": 76\n                        }\n                    ],\n                    \"object\": \"serverimage\",\n                    \"friendlyName\": \"gear6-memcache-server-2.3.6.2-x86_64\",\n                    \"os\": {\n                        \"object\": \"option\",\n                        \"description\": \"CentOS 5.3 (64-bit)\",\n                        \"name\": \"CentOS 5.3 (64-bit)\",\n                        \"id\": 17\n                    },\n                    \"price\": 60,\n                    \"description\": \"Gear6 Memcache Server 2.3.6.2 (64 bit)\",\n                    \"state\": {\n                        \"object\": \"option\",\n                        \"description\": \"Image is available for adds\",\n                        \"name\": \"Available\",\n                        \"id\": 2\n                    },\n                    \"location\": \"26443/GSI-7f498260-2b8a-43ef-aa77-5b403f8f739a.img\",\n                    \"name\": \"GSI-7f498260-2b8a-43ef-aa77-5b403f8f739a\"\n                },\n                \"state\": {\n                    \"object\": \"option\",\n                    \"description\": \"Server is in active state.\",\n                    \"name\": \"On\",\n                    \"id\": 1\n                },\n                \"ram\": {\n                    \"object\": \"option\",\n                    \"description\": \"Server with 512MB RAM\",\n                    \"name\": \"512MB\",\n                    \"id\": 1\n                },\n                \"name\": \"gogrid-7210\",\n                \"ip\": {\n                    \"object\": \"ip\",\n                    \"public\": true,\n                    \"subnet\": \"204.51.240.176/255.255.255.240\",\n                    \"state\": {\n                        \"object\": \"option\",\n                        \"description\": \"IP is reserved or in use\",\n                        \"name\": \"Assigned\",\n                        \"id\": 2\n                    },\n                    \"ip\": \"204.51.240.188\",\n                    \"id\": 1313089\n                },\n                \"id\": 77333\n            },\n            \"id\": 82651,\n            \"applicationtype\": \"os\"\n        },\n        {\n            \"password\": \"vam61doz\",\n            \"object\": \"password\",\n            \"username\": \"root\",\n            \"server\": {\n                \"object\": \"server\",\n                \"isSandbox\": false,\n                \"type\": {\n                    \"object\": \"option\",\n                    \"description\": \"Web or Application Server\",\n                    \"name\": \"Web Server\",\n                    \"id\": 1\n                },\n                \"os\": {\n                    \"object\": \"option\",\n                    \"description\": \"CentOS 5.3 (64-bit)\",\n                    \"name\": \"CentOS 5.3 (64-bit)\",\n                    \"id\": 17\n                },\n                \"image\": {\n                    \"type\": {\n                        \"object\": \"option\",\n                        \"description\": \"Web or Application Server\",\n                        \"name\": \"Web Server\",\n                        \"id\": 1\n                    },\n                    \"owner\": {\n                        \"object\": \"customer\",\n                        \"name\": \"Gear6\",\n                        \"id\": 26443\n                    },\n                    \"updatedTime\": 1265675466171,\n                    \"isActive\": true,\n                    \"id\": 2500,\n                    \"createdTime\": 1265412834154,\n                    \"isPublic\": true,\n                    \"billingtokens\": [\n                        {\n                            \"price\": 0,\n                            \"name\": \"CentOS 5.3 64bit\",\n                            \"id\": 47\n                        },\n                        {\n                            \"price\": 60,\n                            \"name\": \"Gear 6 Paid Version\",\n                            \"id\": 76\n                        }\n                    ],\n                    \"object\": \"serverimage\",\n                    \"friendlyName\": \"gear6-memcache-server-2.3.6.2-x86_64\",\n                    \"os\": {\n                        \"object\": \"option\",\n                        \"description\": \"CentOS 5.3 (64-bit)\",\n                        \"name\": \"CentOS 5.3 (64-bit)\",\n                        \"id\": 17\n                    },\n                    \"price\": 60,\n                    \"description\": \"Gear6 Memcache Server 2.3.6.2 (64 bit)\",\n                    \"state\": {\n                        \"object\": \"option\",\n                        \"description\": \"Image is available for adds\",\n                        \"name\": \"Available\",\n                        \"id\": 2\n                    },\n                    \"location\": \"26443/GSI-7f498260-2b8a-43ef-aa77-5b403f8f739a.img\",\n                    \"name\": \"GSI-7f498260-2b8a-43ef-aa77-5b403f8f739a\"\n                },\n                \"state\": {\n                    \"object\": \"option\",\n                    \"description\": \"Server is in active state.\",\n                    \"name\": \"On\",\n                    \"id\": 1\n                },\n                \"ram\": {\n                    \"object\": \"option\",\n                    \"description\": \"Server with 512MB RAM\",\n                    \"name\": \"512MB\",\n                    \"id\": 1\n                },\n                \"name\": \"gogrid-7461\",\n                \"ip\": {\n                    \"object\": \"ip\",\n                    \"public\": true,\n                    \"subnet\": \"204.51.240.176/255.255.255.240\",\n                    \"state\": {\n                        \"object\": \"option\",\n                        \"description\": \"IP is reserved or in use\",\n                        \"name\": \"Assigned\",\n                        \"id\": 2\n                    },\n                    \"ip\": \"204.51.240.187\",\n                    \"id\": 1313088\n                },\n                \"id\": 77334\n            },\n            \"id\": 82652,\n            \"applicationtype\": \"os\"\n        },\n        {\n            \"password\": \"cun86xef\",\n            \"object\": \"password\",\n            \"username\": \"root\",\n            \"server\": {\n                \"object\": \"server\",\n                \"isSandbox\": false,\n                \"type\": {\n                    \"object\": \"option\",\n                    \"description\": \"Web or Application Server\",\n                    \"name\": \"Web Server\",\n                    \"id\": 1\n                },\n                \"os\": {\n                    \"object\": \"option\",\n                    \"description\": \"CentOS 5.3 (64-bit)\",\n                    \"name\": \"CentOS 5.3 (64-bit)\",\n                    \"id\": 17\n                },\n                \"image\": {\n                    \"type\": {\n                        \"object\": \"option\",\n                        \"description\": \"Web or Application Server\",\n                        \"name\": \"Web Server\",\n                        \"id\": 1\n                    },\n                    \"owner\": {\n                        \"object\": \"customer\",\n                        \"name\": \"Gear6\",\n                        \"id\": 26443\n                    },\n                    \"updatedTime\": 1265675466171,\n                    \"isActive\": true,\n                    \"id\": 2500,\n                    \"createdTime\": 1265412834154,\n                    \"isPublic\": true,\n                    \"billingtokens\": [\n                        {\n                            \"price\": 0,\n                            \"name\": \"CentOS 5.3 64bit\",\n                            \"id\": 47\n                        },\n                        {\n                            \"price\": 60,\n                            \"name\": \"Gear 6 Paid Version\",\n                            \"id\": 76\n                        }\n                    ],\n                    \"object\": \"serverimage\",\n                    \"friendlyName\": \"gear6-memcache-server-2.3.6.2-x86_64\",\n                    \"os\": {\n                        \"object\": \"option\",\n                        \"description\": \"CentOS 5.3 (64-bit)\",\n                        \"name\": \"CentOS 5.3 (64-bit)\",\n                        \"id\": 17\n                    },\n                    \"price\": 60,\n                    \"description\": \"Gear6 Memcache Server 2.3.6.2 (64 bit)\",\n                    \"state\": {\n                        \"object\": \"option\",\n                        \"description\": \"Image is available for adds\",\n                        \"name\": \"Available\",\n                        \"id\": 2\n                    },\n                    \"location\": \"26443/GSI-7f498260-2b8a-43ef-aa77-5b403f8f739a.img\",\n                    \"name\": \"GSI-7f498260-2b8a-43ef-aa77-5b403f8f739a\"\n                },\n                \"state\": {\n                    \"object\": \"option\",\n                    \"description\": \"Server is in active state.\",\n                    \"name\": \"On\",\n                    \"id\": 1\n                },\n                \"ram\": {\n                    \"object\": \"option\",\n                    \"description\": \"Server with 512MB RAM\",\n                    \"name\": \"512MB\",\n                    \"id\": 1\n                },\n                \"name\": \"gogridalex-200\",\n                \"ip\": {\n                    \"object\": \"ip\",\n                    \"public\": true,\n                    \"subnet\": \"204.51.240.176/255.255.255.240\",\n                    \"state\": {\n                        \"object\": \"option\",\n                        \"description\": \"IP is reserved or in use\",\n                        \"name\": \"Assigned\",\n                        \"id\": 2\n                    },\n                    \"ip\": \"204.51.240.179\",\n                    \"id\": 1313080\n                },\n                \"id\": 77410\n            },\n            \"id\": 82730,\n            \"applicationtype\": \"os\"\n        },\n        {\n            \"password\": \"nun63wav\",\n            \"object\": \"password\",\n            \"username\": \"root\",\n            \"server\": {\n                \"object\": \"server\",\n                \"isSandbox\": false,\n                \"type\": {\n                    \"object\": \"option\",\n                    \"description\": \"Web or Application Server\",\n                    \"name\": \"Web Server\",\n                    \"id\": 1\n                },\n                \"os\": {\n                    \"object\": \"option\",\n                    \"description\": \"CentOS 5.3 (64-bit)\",\n                    \"name\": \"CentOS 5.3 (64-bit)\",\n                    \"id\": 17\n                },\n                \"image\": {\n                    \"type\": {\n                        \"object\": \"option\",\n                        \"description\": \"Web or Application Server\",\n                        \"name\": \"Web Server\",\n                        \"id\": 1\n                    },\n                    \"owner\": {\n                        \"object\": \"customer\",\n                        \"name\": \"Gear6\",\n                        \"id\": 26443\n                    },\n                    \"updatedTime\": 1265675466171,\n                    \"isActive\": true,\n                    \"id\": 2500,\n                    \"createdTime\": 1265412834154,\n                    \"isPublic\": true,\n                    \"billingtokens\": [\n                        {\n                            \"price\": 0,\n                            \"name\": \"CentOS 5.3 64bit\",\n                            \"id\": 47\n                        },\n                        {\n                            \"price\": 60,\n                            \"name\": \"Gear 6 Paid Version\",\n                            \"id\": 76\n                        }\n                    ],\n                    \"object\": \"serverimage\",\n                    \"friendlyName\": \"gear6-memcache-server-2.3.6.2-x86_64\",\n                    \"os\": {\n                        \"object\": \"option\",\n                        \"description\": \"CentOS 5.3 (64-bit)\",\n                        \"name\": \"CentOS 5.3 (64-bit)\",\n                        \"id\": 17\n                    },\n                    \"price\": 60,\n                    \"description\": \"Gear6 Memcache Server 2.3.6.2 (64 bit)\",\n                    \"state\": {\n                        \"object\": \"option\",\n                        \"description\": \"Image is available for adds\",\n                        \"name\": \"Available\",\n                        \"id\": 2\n                    },\n                    \"location\": \"26443/GSI-7f498260-2b8a-43ef-aa77-5b403f8f739a.img\",\n                    \"name\": \"GSI-7f498260-2b8a-43ef-aa77-5b403f8f739a\"\n                },\n                \"state\": {\n                    \"object\": \"option\",\n                    \"description\": \"Server is in active state.\",\n                    \"name\": \"On\",\n                    \"id\": 1\n                },\n                \"ram\": {\n                    \"object\": \"option\",\n                    \"description\": \"Server with 512MB RAM\",\n                    \"name\": \"512MB\",\n                    \"id\": 1\n                },\n                \"name\": \"gogridalex-201\",\n                \"ip\": {\n                    \"object\": \"ip\",\n                    \"public\": true,\n                    \"subnet\": \"204.51.240.176/255.255.255.240\",\n                    \"state\": {\n                        \"object\": \"option\",\n                        \"description\": \"IP is reserved or in use\",\n                        \"name\": \"Assigned\",\n                        \"id\": 2\n                    },\n                    \"ip\": \"204.51.240.185\",\n                    \"id\": 1313086\n                },\n                \"id\": 77411\n            },\n            \"id\": 82731,\n            \"applicationtype\": \"os\"\n        }\n    ],\n    \"summary\": {\n        \"total\": 6,\n        \"start\": 0,\n        \"numpages\": 0,\n        \"returned\": 6\n    },\n    \"status\": \"success\",\n    \"method\": \"/support/password/list\"\n}"
  },
  {
    "path": "providers/gogrid/src/test/resources/test_error_handler.json",
    "content": "{\n    \"list\": [\n        {\n            \"object\": \"error\",\n            \"message\": \"No object found that matches your input criteria.\",\n            \"errorcode\": \"IllegalArgumentException\"\n        }\n    ],\n    \"summary\": {\n        \"total\": 1,\n        \"start\": 0,\n        \"returned\": 1\n    },\n    \"status\": \"failure\",\n    \"method\": \"/grid/server/get\"\n}"
  },
  {
    "path": "providers/gogrid/src/test/resources/test_get_job_list.json",
    "content": "{\n    \"list\": [\n        {\n            \"object\": \"job\",\n            \"command\": {\n                \"object\": \"option\",\n                \"description\": \"Delete Virtual Server\",\n                \"name\": \"DeleteVirtualServer\",\n                \"id\": 7\n            },\n            \"currentstate\": {\n                \"object\": \"option\",\n                \"description\": \"Change request has succeeded.\",\n                \"name\": \"Succeeded\",\n                \"id\": 3\n            },\n            \"owner\": \"3116784158f0af2d-24076@api.gogrid.com\",\n            \"objecttype\": {\n                \"object\": \"option\",\n                \"description\": null,\n                \"name\": \"VirtualServer\",\n                \"id\": 1\n            },\n            \"detail\": {\n                \"type\": \"virtual_server\",\n                \"description\": null,\n                \"image\": \"GSI-f8979644-e646-4711-ad58-d98a5fa3612c\",\n                \"name\": \"ServerCreated40562\",\n                \"ip\": \"204.51.240.189\"\n            },\n            \"history\": [\n                {\n                    \"state\": {\n                        \"object\": \"option\",\n                        \"description\": \"Change request is created but not queued yet\",\n                        \"name\": \"Created\",\n                        \"id\": 7\n                    },\n                    \"id\": 940263,\n                    \"updatedon\": 1267404528897\n                },\n                {\n                    \"state\": {\n                        \"object\": \"option\",\n                        \"description\": \"Change request is new to the system.\",\n                        \"name\": \"Queued\",\n                        \"id\": 1\n                    },\n                    \"id\": 940264,\n                    \"updatedon\": 1267404528967\n                }\n            ],\n            \"attempts\": 1,\n            \"createdon\": 1267404528895,\n            \"lastupdatedon\": 1267404538592,\n            \"id\": 250628\n        }\n    ],\n    \"summary\": {\n        \"total\": 68,\n        \"start\": 0,\n        \"numpages\": 14,\n        \"returned\": 5\n    },\n    \"status\": \"success\",\n    \"method\": \"/grid/job/list\"\n}"
  },
  {
    "path": "providers/gogrid/src/test/resources/test_get_load_balancer_list.json",
    "content": "{\n    \"list\": [\n        {\n            \"datacenter\": {\n                \"description\": \"US West 1 Datacenter\",\n                \"id\": 1,\n                \"name\": \"US-West-1\",\n                \"object\": \"option\"\n            },\n            \"object\": \"loadbalancer\",\n            \"virtualip\": {\n                \"object\": \"ipportpair\",\n                \"ip\": {\"datacenter\": {\n                \"description\": \"US West 1 Datacenter\",\n                \"id\": 1,\n                \"name\": \"US-West-1\",\n                \"object\": \"option\"\n            },\n                    \"object\": \"ip\",\n                    \"public\": true,\n                    \"subnet\": \"204.51.240.176/255.255.255.240\",\n                    \"state\": {\n                        \"object\": \"option\",\n                        \"description\": \"IP is reserved or in use\",\n                        \"name\": \"Assigned\",\n                        \"id\": 2\n                    },\n                    \"ip\": \"204.51.240.181\",\n                    \"id\": 1313082\n                },\n                \"port\": 80\n            },\n            \"type\": {\n                \"object\": \"option\",\n                \"description\": \"\",\n                \"name\": \"Round Robin\",\n                \"id\": 1\n            },\n            \"os\": {\n                \"object\": \"option\",\n                \"description\": \"The F5 Load Balancer.\",\n                \"name\": \"F5\",\n                \"id\": 1\n            },\n            \"state\": {\n                \"object\": \"option\",\n                \"description\": \"Loadbalancer is enabled and on.\",\n                \"name\": \"On\",\n                \"id\": 1\n            },\n            \"name\": \"Balancer\",\n            \"realiplist\": [\n                {\n                    \"ip\": {\n                                \"datacenter\": {\n                \"description\": \"US West 1 Datacenter\",\n                \"id\": 1,\n                \"name\": \"US-West-1\",\n                \"object\": \"option\"\n            },\n                        \"object\": \"ip\",\n                        \"public\": true,\n                        \"subnet\": \"204.51.240.176/255.255.255.240\",\n                        \"state\": {\n                            \"object\": \"option\",\n                            \"description\": \"IP is reserved or in use\",\n                            \"name\": \"Assigned\",\n                            \"id\": 2\n                        },\n                        \"ip\": \"204.51.240.185\",\n                        \"id\": 1313086\n                    },\n                    \"port\": 80\n                },\n                {\n                    \"ip\": {\n                                \"datacenter\": {\n                \"description\": \"US West 1 Datacenter\",\n                \"id\": 1,\n                \"name\": \"US-West-1\",\n                \"object\": \"option\"\n            },\n                        \"object\": \"ip\",\n                        \"public\": true,\n                        \"subnet\": \"204.51.240.176/255.255.255.240\",\n                        \"state\": {\n                            \"object\": \"option\",\n                            \"description\": \"IP is reserved or in use\",\n                            \"name\": \"Assigned\",\n                            \"id\": 2\n                        },\n                        \"ip\": \"204.51.240.188\",\n                        \"id\": 1313089\n                    },\n                    \"port\": 80\n                }\n            ],\n            \"id\": 6372,\n            \"persistence\": {\n                \"object\": \"option\",\n                \"description\": \"\",\n                \"name\": \"None\",\n                \"id\": 1\n            }\n        }\n    ],\n    \"summary\": {\n        \"total\": 1,\n        \"start\": 0,\n        \"numpages\": 0,\n        \"returned\": 1\n    },\n    \"status\": \"success\",\n    \"method\": \"/grid/loadbalancer/list\"\n}"
  },
  {
    "path": "providers/gogrid/src/test/resources/test_get_server_list.json",
    "content": "{\n    \"list\": [\n        {\n            \"datacenter\": {\n                \"description\": \"US West 1 Datacenter\",\n                \"id\": 1,\n                \"name\": \"US-West-1\",\n                \"object\": \"option\"\n            },\n            \"object\": \"server\",\n            \"isSandbox\": false,\n            \"type\": {\n                \"object\": \"option\",\n                \"description\": \"Web or Application Server\",\n                \"name\": \"Web Server\",\n                \"id\": 1\n            },\n            \"os\": {\n                \"object\": \"option\",\n                \"description\": \"CentOS 5.2 (32-bit)\",\n                \"name\": \"CentOS 5.2 (32-bit)\",\n                \"id\": 13\n            },\n            \"description\": \"server to test the api. created by Alex\",\n            \"image\": {\n                \"type\": {\n                    \"object\": \"option\",\n                    \"description\": \"Web or Application Server\",\n                    \"name\": \"Web Server\",\n                    \"id\": 1\n                },\n                \"owner\": {\n                    \"object\": \"customer\",\n                    \"name\": \"BitRock\",\n                    \"id\": 24732\n                },\n                \"updatedTime\": 1262649582180,\n                \"isActive\": true,\n                \"id\": 1946,\n                \"createdTime\": 1261504577971,\n                \"isPublic\": true,\n                \"billingtokens\": [\n                    {\n                        \"price\": 0,\n                        \"name\": \"CentOS 5.2 32bit\",\n                        \"id\": 38\n                    },\n                    {\n                        \"price\": 0,\n                        \"name\": \"BitNami: Gallery\",\n                        \"id\": 56\n                    }\n                ],\n                \"object\": \"serverimage\",\n                \"friendlyName\": \"BitNami Gallery 2.3.1-0\",\n                \"os\": {\n                    \"object\": \"option\",\n                    \"description\": \"CentOS 5.2 (32-bit)\",\n                    \"name\": \"CentOS 5.2 (32-bit)\",\n                    \"id\": 13\n                },\n                \"price\": 0,\n                \"description\": \"http://bitnami.org/stack/gallery\",\n                \"state\": {\n                    \"object\": \"option\",\n                    \"description\": \"Image is available for adds\",\n                    \"name\": \"Available\",\n                    \"id\": 2\n                },\n                \"location\": \"24732/GSI-f8979644-e646-4711-ad58-d98a5fa3612c.img\",\n                \"name\": \"GSI-f8979644-e646-4711-ad58-d98a5fa3612c\"\n            },\n            \"state\": {\n                \"object\": \"option\",\n                \"description\": \"Server is in active state.\",\n                \"name\": \"On\",\n                \"id\": 1\n            },\n            \"ram\": {\n                \"object\": \"option\",\n                \"description\": \"Server with 512MB RAM\",\n                \"name\": \"512MB\",\n                \"id\": 1\n            },\n            \"name\": \"PowerServer\",\n            \"ip\": {\n             \"datacenter\": {\n                \"description\": \"US West 1 Datacenter\",\n                \"id\": 1,\n                \"name\": \"US-West-1\",\n                \"object\": \"option\"\n                },\n                \"object\": \"ip\",\n                \"public\": true,\n                \"subnet\": \"204.51.240.176/255.255.255.240\",\n                \"state\": {\n                    \"object\": \"option\",\n                    \"description\": \"IP is reserved or in use\",\n                    \"name\": \"Assigned\",\n                    \"id\": 2\n                },\n                \"ip\": \"204.51.240.178\",\n                \"id\": 1313079\n            },\n            \"id\": 75245\n        }\n    ],\n    \"summary\": {\n        \"total\": 1,\n        \"start\": 0,\n        \"numpages\": 0,\n        \"returned\": 1\n    },\n    \"status\": \"success\",\n    \"method\": \"/grid/server/get\"\n}"
  },
  {
    "path": "providers/google-cloud-storage/README.md",
    "content": "jclouds Google Cloud Storage Provider\n======\nMake sure both Google Cloud Storage and Google Cloud Storage JSON API are enabled for the project\n(check from Developers Console -> Api&auth -> APIs)\n\nFAQ:\n--------\n\n* Q. What is the identity for Google Cloud Storage?\n\nA. the identity is the developer email which can be obtained from the admin GUI. Its usually something in the form: [PROJECT_ID](https://cloud.google.com/compute/docs/overview#projectids)@developer.gserviceaccount.com\n\n* Q. What is the credential for Google Cloud Storage\n\nA. the credential is a private key, in pem format. It can be extracted from the p12 keystore that is obtained when creating a \"Service Account\" (in the GUI: Google apis console > Api Access > Create another client ID > \"Service Account\"\n\n* Q. How to convert a p12 keystore into a pem format jclouds Google Cloud Storage can handle:\n\nA.\n\n1. Convert the p12 file into pem format (it will ask for the keystore password, which is usually \"notasecret\"):\n openssl pkcs12 -in <my_keystore>.p12 -out <my_keystore>.pem -nodes\n\n2. Extract only the pk and remove passphrase\n openssl rsa -in <my_keystore>.pem -out <my_key>.pem\n\nThe last file (<my_key>.pem) should contain the pk that needs to be passed to `ContextBuilder.credential()` for the provider `google-cloud-storage`.\n\n\nRunning the live tests:\n--------\n\n1. Place the following in your ~/.m2/settings.xml in a profile enabled when live:\n```\n    <test.google-cloud-storage.identity>PROJECT_ID@developer.gserviceaccount.com</test.google-cloud-storage.identity>\n    <test.google-cloud-storage.credential>-----BEGIN RSA PRIVATE KEY-----\nMIICXgIBAAKBgQRRbRqVDtJLN1MO/xJoKqZuphDeBh5jIKueW3aNIiWs1XFcct+h\n-- this text is literally from your <my_key>.pem\naH7xmpHSTbbXmQkuuv+z8EKijigprd/FoJpTX1f5/R+4wQ==\n-----END RSA PRIVATE KEY-----</test.google-cloud-storage.credential>\n  </properties>\n```\nOr, if using an existing OAuth Bearer Token for authentication.\n```\n    <test.google-cloud-storage.identity>PROJECT_ID@developer.gserviceaccount.com</test.google-cloud-storage.identity>\n    <test.google-cloud-storage.credential>EXISTING_BEARER_TOKEN</test.google-cloud-storage.credential>\n    <test.jclouds.oauth.credential-type>bearerTokenCredentials</test.jclouds.oauth.credential-type>\n  </properties>\n```\n\n2. mvn clean install -Plive \n"
  },
  {
    "path": "providers/google-cloud-storage/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.googlecloudstorage.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "providers/google-cloud-storage/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n         xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n    <modelVersion>4.0.0</modelVersion>\n    <parent>\n        <groupId>org.apache.jclouds</groupId>\n        <artifactId>jclouds-project</artifactId>\n        <version>2.7.1-SNAPSHOT</version>\n        <relativePath>../../project/pom.xml</relativePath>\n    </parent>\n\n    <groupId>org.apache.jclouds.provider</groupId>\n    <artifactId>google-cloud-storage</artifactId>\n    <name>jclouds Google Cloud Storage provider</name>\n    <description>jclouds components to access Google Cloud Storage</description>\n\n    <properties>\n        <test.google-cloud-storage.identity>client_email which usually looks like project_id@developer.gserviceaccount.com</test.google-cloud-storage.identity>\n        <test.google-cloud-storage.credential>Private key (PEM encoded PKCS12 file or literal) associated with the client_email</test.google-cloud-storage.credential>\n        <!-- Add this property to use a different project, or avoid looking up the project for each test. -->\n        <test.jclouds.googlecloud.project-name></test.jclouds.googlecloud.project-name>\n        <test.jclouds.oauth.credential-type>p12PrivateKeyCredentials</test.jclouds.oauth.credential-type>\n        <test.google-cloud-storage.api-version>v1</test.google-cloud-storage.api-version>\n        <test.google-cloud-storage.build-version/>\n    </properties>\n\n    <dependencies>\n        <dependency>\n            <groupId>org.apache.jclouds</groupId>\n            <artifactId>jclouds-core</artifactId>\n            <version>${project.version}</version>\n        </dependency>\n        <dependency>\n            <groupId>org.apache.jclouds.common</groupId>\n            <artifactId>googlecloud</artifactId>\n            <version>${project.version}</version>\n            <type>jar</type>\n        </dependency>\n        <dependency>\n            <groupId>org.apache.jclouds.common</groupId>\n            <artifactId>googlecloud</artifactId>\n            <version>${project.version}</version>\n            <type>test-jar</type>\n            <scope>test</scope>\n        </dependency>\n        <dependency>\n            <groupId>org.apache.jclouds.api</groupId>\n            <artifactId>oauth</artifactId>\n            <version>${project.version}</version>\n            <type>test-jar</type>\n            <scope>test</scope>\n        </dependency>\n        <dependency>\n            <groupId>org.apache.jclouds</groupId>\n            <artifactId>jclouds-blobstore</artifactId>\n            <version>${project.version}</version>\n        </dependency>\n        <dependency>\n            <groupId>com.google.auto.service</groupId>\n            <artifactId>auto-service</artifactId>\n            <scope>provided</scope>\n            <optional>true</optional>\n        </dependency>\n        <dependency>\n            <groupId>com.google.auto.value</groupId>\n            <artifactId>auto-value</artifactId>\n            <scope>provided</scope>\n        </dependency>\n        <dependency>\n            <groupId>org.apache.jclouds</groupId>\n            <artifactId>jclouds-blobstore</artifactId>\n            <version>${project.version}</version>\n            <type>test-jar</type>\n            <scope>test</scope>\n        </dependency>\n        <dependency>\n            <groupId>org.apache.jclouds</groupId>\n            <artifactId>jclouds-core</artifactId>\n            <version>${project.version}</version>\n            <type>test-jar</type>\n            <scope>test</scope>\n        </dependency>\n        <dependency>\n            <groupId>org.apache.jclouds.driver</groupId>\n            <artifactId>jclouds-slf4j</artifactId>\n            <version>${project.version}</version>\n            <scope>test</scope>\n        </dependency>\n        <dependency>\n            <groupId>org.apache.jclouds.driver</groupId>\n            <artifactId>jclouds-okhttp</artifactId>\n            <version>${project.version}</version>\n            <scope>test</scope>\n        </dependency>\n        <dependency>\n            <groupId>ch.qos.logback</groupId>\n            <artifactId>logback-classic</artifactId>\n            <scope>test</scope>\n        </dependency>\n        <dependency>\n          <groupId>com.squareup.okhttp3</groupId>\n          <artifactId>mockwebserver</artifactId>\n          <scope>test</scope>\n        </dependency>\n    </dependencies>\n    <profiles>\n        <profile>\n            <id>live</id>\n            <build>\n                <plugins>\n                    <plugin>\n                        <groupId>org.apache.maven.plugins</groupId>\n                        <artifactId>maven-surefire-plugin</artifactId>\n                        <executions>\n                            <execution>\n                                <id>default-test</id>\n                                <configuration>\n                                    <skipTests>true</skipTests>\n                                </configuration>\n                            </execution>\n                            <execution>\n                                <id>integration</id>\n                                <phase>integration-test</phase>\n                                <goals>\n                                    <goal>test</goal>\n                                </goals>\n                                <configuration>\n                                    <threadCount>1</threadCount>\n                                    <systemPropertyVariables>\n                                        <jclouds.blobstore.httpstream.url>${jclouds.blobstore.httpstream.url}</jclouds.blobstore.httpstream.url>\n                                        <jclouds.blobstore.httpstream.md5>${jclouds.blobstore.httpstream.md5}</jclouds.blobstore.httpstream.md5>\n                                        <test.google-cloud-storage.identity>${test.google-cloud-storage.identity}</test.google-cloud-storage.identity>\n                                        <test.google-cloud-storage.credential>${test.google-cloud-storage.credential}</test.google-cloud-storage.credential>\n                                        <test.jclouds.googlecloud.project-name>${test.jclouds.googlecloud.project-name}</test.jclouds.googlecloud.project-name>\n                                        <test.jclouds.oauth.credential-type>${test.jclouds.oauth.credential-type}</test.jclouds.oauth.credential-type>\n                                        <test.google-cloud-storage.api-version>${test.google-cloud-storage.api-version}</test.google-cloud-storage.api-version>\n                                        <test.google-cloud-storage.build-version>${test.google-cloud-storage.build-version}</test.google-cloud-storage.build-version>\n                                    </systemPropertyVariables>\n                                </configuration>\n                            </execution>\n                        </executions>\n                    </plugin>\n                </plugins>\n            </build>\n        </profile>\n    </profiles>\n</project>\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/GoogleCloudStorageApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage;\n\nimport java.io.Closeable;\n\nimport jakarta.ws.rs.Path;\n\nimport org.jclouds.googlecloudstorage.features.BucketAccessControlsApi;\nimport org.jclouds.googlecloudstorage.features.BucketApi;\nimport org.jclouds.googlecloudstorage.features.DefaultObjectAccessControlsApi;\nimport org.jclouds.googlecloudstorage.features.ObjectAccessControlsApi;\nimport org.jclouds.googlecloudstorage.features.ObjectApi;\nimport org.jclouds.googlecloudstorage.features.ResumableUploadApi;\nimport org.jclouds.rest.annotations.Delegate;\n\n/**\n * Provide access to GoogleCloudStorage\n *\n * @see <a href=\"https://developers.google.com/storage/docs/json_api/v1/\">api doc /a>\n */\npublic interface GoogleCloudStorageApi extends Closeable {\n\n   /**\n    * Provides access to Default Object Access Control features on bucket\n    */\n   @Delegate\n   @Path(\"/storage/v1\")\n   DefaultObjectAccessControlsApi getDefaultObjectAccessControlsApi();\n\n   /**\n    * Provides access to Bucket Access Control features\n    */\n   @Delegate\n   @Path(\"/storage/v1\")\n   BucketAccessControlsApi getBucketAccessControlsApi();\n\n   /**\n    * Provides access to Bucket features\n    */\n   @Delegate\n   @Path(\"/storage/v1\")\n   BucketApi getBucketApi();\n\n   /**\n    * Provides access to Object Access Control features\n    */\n   @Delegate\n   @Path(\"/storage/v1\")\n   ObjectAccessControlsApi getObjectAccessControlsApi();\n\n   /**\n    * Provides access to Google Cloud Storage Object features\n    */\n   @Delegate\n   ObjectApi getObjectApi();\n\n   /**\n    * Provides access to Google Cloud Storage ResumableUpload features\n    */\n   @Delegate\n   ResumableUploadApi getResumableUploadApi();\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/GoogleCloudStorageApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage;\n\nimport static org.jclouds.Constants.PROPERTY_IDEMPOTENT_METHODS;\nimport static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL;\nimport static org.jclouds.googlecloudstorage.reference.GoogleCloudStorageConstants.OPERATION_COMPLETE_INTERVAL;\nimport static org.jclouds.googlecloudstorage.reference.GoogleCloudStorageConstants.OPERATION_COMPLETE_TIMEOUT;\nimport static org.jclouds.oauth.v2.config.OAuthProperties.AUDIENCE;\nimport static org.jclouds.oauth.v2.config.OAuthProperties.JWS_ALG;\nimport static org.jclouds.reflect.Reflection2.typeToken;\n\nimport java.net.URI;\nimport java.util.Properties;\nimport java.util.concurrent.TimeUnit;\n\nimport org.jclouds.Constants;\nimport org.jclouds.blobstore.BlobStoreContext;\nimport org.jclouds.googlecloud.config.CurrentProject;\nimport org.jclouds.googlecloudstorage.blobstore.config.GoogleCloudStorageBlobStoreContextModule;\nimport org.jclouds.googlecloudstorage.config.GoogleCloudStorageHttpApiModule;\nimport org.jclouds.googlecloudstorage.config.GoogleCloudStorageParserModule;\nimport org.jclouds.oauth.v2.config.OAuthModule;\nimport org.jclouds.rest.internal.BaseHttpApiMetadata;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\npublic class GoogleCloudStorageApiMetadata extends BaseHttpApiMetadata<GoogleCloudStorageApi> {\n\n   @Override\n   public Builder toBuilder() {\n      return new Builder().fromApiMetadata(this);\n   }\n\n   public GoogleCloudStorageApiMetadata() {\n      this(new Builder());\n   }\n\n   protected GoogleCloudStorageApiMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = BaseHttpApiMetadata.defaultProperties();\n      properties.put(\"oauth.endpoint\", \"https://accounts.google.com/o/oauth2/token\");\n      properties.put(AUDIENCE, \"https://accounts.google.com/o/oauth2/token\");\n      properties.put(JWS_ALG, \"RS256\");\n      properties.put(PROPERTY_SESSION_INTERVAL, 3600);\n      properties.put(OPERATION_COMPLETE_INTERVAL, 2000);\n      properties.put(OPERATION_COMPLETE_TIMEOUT, 600000);\n      properties.setProperty(PROPERTY_IDEMPOTENT_METHODS, \"DELETE,GET,HEAD,OPTIONS,POST,PUT\");\n      // bucket operations have a longer timeout\n      properties.setProperty(Constants.PROPERTY_RETRY_DELAY_START, String.valueOf(TimeUnit.SECONDS.toMillis(1)));\n      return properties;\n   }\n\n   public static class Builder extends BaseHttpApiMetadata.Builder<GoogleCloudStorageApi, Builder> {\n      protected Builder() {\n         id(\"google-cloud-storage\")\n         .name(\"Google Cloud Storage Api\")\n         .identityName(CurrentProject.ClientEmail.DESCRIPTION)\n         .credentialName(\"PEM encoded P12 private key associated with client_email\")\n         .documentation(URI.create(\"https://developers.google.com/storage/docs/json_api\"))\n         .version(\"v1\")\n         .defaultEndpoint(\"https://www.googleapis.com\")\n         .defaultProperties(GoogleCloudStorageApiMetadata.defaultProperties())\n         .view(typeToken(BlobStoreContext.class))\n         .defaultModules(ImmutableSet.<Class<? extends Module>> builder()\n                 .add(GoogleCloudStorageParserModule.class)\n                 .add(OAuthModule.class)\n                 .add(GoogleCloudStorageHttpApiModule.class)\n                 .add(GoogleCloudStorageBlobStoreContextModule.class).build());\n      }\n\n      @Override\n      public GoogleCloudStorageApiMetadata build() {\n         return new GoogleCloudStorageApiMetadata(this);\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/GoogleCloudStorageFallbacks.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Throwables.propagate;\n\nimport org.jclouds.Fallback;\n\npublic final class GoogleCloudStorageFallbacks {\n\n   public static final class NullOnBucketAlreadyExists implements Fallback<Object> {\n      public Object createOrPropagate(Throwable t) throws Exception {\n         if (checkNotNull(t, \"throwable\") instanceof IllegalStateException) {\n            return null;\n         }\n         throw propagate(t);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/GoogleCloudStorageProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\n\nimport com.google.auto.service.AutoService;\n\n/** Note: This does not set iso3166Codes as Google intentionally does not document them. */\n@AutoService(ProviderMetadata.class)\npublic final class GoogleCloudStorageProviderMetadata extends BaseProviderMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromProviderMetadata(this);\n   }\n\n   public GoogleCloudStorageProviderMetadata() {\n      super(builder());\n   }\n\n   public GoogleCloudStorageProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      return new Properties(); // currently all are set in the api metadata class.\n   }\n\n   public static final class Builder extends BaseProviderMetadata.Builder {\n\n      private Builder() {\n         id(\"google-cloud-storage\") //\n         .name(\"Google Cloud Storage\") //\n         .apiMetadata(new GoogleCloudStorageApiMetadata()) //\n         .homepage(URI.create(\"https://cloud.google.com/storage\")) //\n         .console(URI.create(\"https://console.developers.google.com/project\")) //\n         .defaultProperties(GoogleCloudStorageProviderMetadata.defaultProperties());\n      }\n\n      @Override public GoogleCloudStorageProviderMetadata build() {\n         return new GoogleCloudStorageProviderMetadata(this);\n      }\n\n      @Override public Builder fromProviderMetadata(ProviderMetadata in) {\n         super.fromProviderMetadata(in);\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/binders/MultipartUploadBinder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.binders;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static jakarta.ws.rs.core.HttpHeaders.CONTENT_TYPE;\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.util.Map;\n\nimport org.jclouds.googlecloudstorage.domain.templates.ObjectTemplate;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.io.payloads.MultipartForm;\nimport org.jclouds.io.payloads.Part;\nimport org.jclouds.io.payloads.StringPayload;\nimport org.jclouds.json.Json;\nimport org.jclouds.rest.MapBinder;\n\nimport com.google.inject.Inject;\n\npublic final class MultipartUploadBinder implements MapBinder {\n   private static final String BOUNDARY_HEADER = \"multipart_boundary\";\n\n   private final Json json;\n\n   @Inject MultipartUploadBinder(Json json){\n      this.json = json;\n   }\n\n   @Override public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      ObjectTemplate template = (ObjectTemplate) postParams.get(\"template\");\n      Payload payload = (Payload) postParams.get(\"payload\");\n\n      String contentType = checkNotNull(template.contentType(), \"contentType\");\n      Long length = checkNotNull(template.size(), \"contentLength\");\n\n      StringPayload jsonPayload = Payloads.newStringPayload(json.toJson(template));\n\n      payload.getContentMetadata().setContentLength(length);\n\n      Part jsonPart = Part.create(\"Metadata\", jsonPayload, new Part.PartOptions().contentType(APPLICATION_JSON));\n      Part mediaPart = Part.create(template.name(), payload, new Part.PartOptions().contentType(contentType));\n\n      request.resetPayload(/*release=*/ false);\n      request.setPayload(new MultipartForm(BOUNDARY_HEADER, jsonPart, mediaPart));\n      // HeaderPart\n      request.toBuilder().replaceHeader(CONTENT_TYPE, \"Multipart/related; boundary= \" + BOUNDARY_HEADER).build();\n      return request;\n   }\n\n   @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      return request;\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/binders/UploadBinder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.binders;\n\nimport java.util.Map;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.io.Payload;\nimport org.jclouds.rest.MapBinder;\n\npublic class UploadBinder implements MapBinder {\n\n   @Override public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      Payload payload = (Payload) postParams.get(\"payload\");\n\n      request.getPayload().getContentMetadata().setContentType(payload.getContentMetadata().getContentType());\n      request.setPayload(payload);\n      return bindToRequest(request, payload);\n   }\n\n   @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      return request;\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/blobstore/GoogleCloudStorageBlobRequestSigner.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.blobstore;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.net.URI;\nimport java.security.InvalidKeyException;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.PrivateKey;\nimport java.security.Signature;\nimport java.security.SignatureException;\nimport java.util.Map;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Provider;\n\nimport org.jclouds.Constants;\nimport org.jclouds.blobstore.BlobRequestSigner;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.functions.BlobToHttpGetOptions;\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpUtils;\nimport org.jclouds.http.Uris;\nimport org.jclouds.http.options.GetOptions;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.oauth.v2.config.Authorization;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.base.Strings;\nimport com.google.common.base.Supplier;\nimport com.google.common.io.BaseEncoding;\nimport com.google.common.net.HttpHeaders;\nimport com.google.inject.Inject;\nimport com.google.inject.name.Named;\n\npublic final class GoogleCloudStorageBlobRequestSigner implements BlobRequestSigner {\n   private static final int DEFAULT_EXPIRY_SECONDS = 15 * 60;\n   private static final URI STORAGE_URL = URI.create(\"http://storage.googleapis.com/\");\n\n   private final Supplier<Credentials> creds;\n   private final Supplier<PrivateKey> privateKey;\n   private final Provider<Long> timestamp;\n   private final HttpUtils utils;\n\n   private final BlobToHttpGetOptions toGetOptions = new BlobToHttpGetOptions();\n\n   @Resource\n   @Named(Constants.LOGGER_SIGNATURE)\n   protected Logger signatureLog = Logger.NULL;\n\n   @Inject\n   protected GoogleCloudStorageBlobRequestSigner(@org.jclouds.location.Provider Supplier<Credentials> creds,\n         @Authorization Supplier<PrivateKey> privateKey, @TimeStamp Provider<Long> timestamp, HttpUtils utils) {\n      this.creds = creds;\n      this.privateKey = privateKey;\n      this.timestamp = timestamp;\n      this.utils = utils;\n   }\n\n   @Override\n   public HttpRequest signGetBlob(String container, String name) {\n      return signGetBlob(container, name, DEFAULT_EXPIRY_SECONDS);\n   }\n\n   @Override\n   public HttpRequest signGetBlob(String container, String name, long timeInSeconds) {\n      return sign(\"GET\", container, name, GetOptions.NONE, timestamp.get() + timeInSeconds, null);\n   }\n\n   @Override\n   public HttpRequest signGetBlob(String container, String name, org.jclouds.blobstore.options.GetOptions options) {\n      return sign(\"GET\", container, name, toGetOptions.apply(options), timestamp.get() + DEFAULT_EXPIRY_SECONDS, null);\n   }\n\n   @Override\n   public HttpRequest signPutBlob(String container, Blob blob) {\n      return signPutBlob(container, blob, DEFAULT_EXPIRY_SECONDS);\n   }\n\n   @Override\n   public HttpRequest signPutBlob(String container, Blob blob, long timeInSeconds) {\n      return sign(\"PUT\", container, blob.getMetadata().getName(), GetOptions.NONE, timestamp.get() + timeInSeconds,\n            blob.getMetadata().getContentMetadata().getContentType());\n   }\n\n   private HttpRequest sign(String method, String container, String name, GetOptions options, long expires, String contentType) {\n      checkNotNull(container, \"container\");\n      checkNotNull(name, \"name\");\n\n      HttpRequest.Builder request = HttpRequest.builder()\n            .method(method)\n            .endpoint(Uris.uriBuilder(STORAGE_URL).appendPath(container).appendPath(name).build());\n      if (contentType != null) {\n         request.replaceHeader(HttpHeaders.CONTENT_TYPE, contentType);\n      }\n\n      String stringToSign = createStringToSign(request.build(), expires);\n      byte[] rawSignature;\n      try {\n         Signature signer = Signature.getInstance(\"SHA256withRSA\");\n         signer.initSign(privateKey.get());\n         signer.update(stringToSign.getBytes(Charsets.UTF_8));\n         rawSignature = signer.sign();\n      } catch (InvalidKeyException ike) {\n         throw new RuntimeException(ike);\n      } catch (NoSuchAlgorithmException nsae) {\n         throw new RuntimeException(nsae);\n      } catch (SignatureException se) {\n         throw new RuntimeException(se);\n      }\n      String signature = BaseEncoding.base64().encode(rawSignature);\n\n      for (Map.Entry<String, String> entry : options.buildRequestHeaders().entries()) {\n         request.addHeader(entry.getKey(), entry.getValue());\n      }\n\n      return request\n            .addQueryParam(\"Expires\", String.valueOf(expires))\n            .addQueryParam(\"GoogleAccessId\", creds.get().identity)\n            .addQueryParam(\"Signature\", signature)\n            .build();\n   }\n\n   private String createStringToSign(HttpRequest request, long expires) {\n      utils.logRequest(signatureLog, request, \">>\");\n      StringBuilder buffer = new StringBuilder();\n      buffer.append(request.getMethod()).append(\"\\n\");\n      buffer.append(Strings.nullToEmpty(request.getFirstHeaderOrNull(HttpHeaders.CONTENT_MD5))).append(\"\\n\");\n      buffer.append(Strings.nullToEmpty(request.getFirstHeaderOrNull(HttpHeaders.CONTENT_TYPE))).append(\"\\n\");\n      buffer.append(String.valueOf(expires)).append(\"\\n\");\n      // TODO: extension headers\n      buffer.append(request.getEndpoint().getPath());\n      return buffer.toString();\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/blobstore/GoogleCloudStorageBlobStore.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.blobstore;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.io.BaseEncoding.base64;\nimport static org.jclouds.googlecloudstorage.domain.DomainResourceReferences.ObjectRole.READER;\n\nimport java.util.List;\nimport java.util.Set;\nimport java.util.UUID;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.blobstore.BlobStoreContext;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.BlobAccess;\nimport org.jclouds.blobstore.domain.BlobMetadata;\nimport org.jclouds.blobstore.domain.ContainerAccess;\nimport org.jclouds.blobstore.domain.MultipartPart;\nimport org.jclouds.blobstore.domain.MultipartUpload;\nimport org.jclouds.blobstore.domain.MutableBlobMetadata;\nimport org.jclouds.blobstore.domain.PageSet;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.domain.internal.BlobImpl;\nimport org.jclouds.blobstore.domain.internal.PageSetImpl;\nimport org.jclouds.blobstore.functions.BlobToHttpGetOptions;\nimport org.jclouds.blobstore.internal.BaseBlobStore;\nimport org.jclouds.blobstore.options.CopyOptions;\nimport org.jclouds.blobstore.options.CreateContainerOptions;\nimport org.jclouds.blobstore.options.GetOptions;\nimport org.jclouds.blobstore.options.ListContainerOptions;\nimport org.jclouds.blobstore.options.PutOptions;\nimport org.jclouds.blobstore.util.BlobUtils;\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.domain.Location;\nimport org.jclouds.googlecloud.config.CurrentProject;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecloudstorage.GoogleCloudStorageApi;\nimport org.jclouds.googlecloudstorage.blobstore.functions.BlobMetadataToObjectTemplate;\nimport org.jclouds.googlecloudstorage.blobstore.functions.BlobStoreListContainerOptionsToListObjectOptions;\nimport org.jclouds.googlecloudstorage.blobstore.functions.BucketToStorageMetadata;\nimport org.jclouds.googlecloudstorage.blobstore.functions.ObjectListToStorageMetadata;\nimport org.jclouds.googlecloudstorage.blobstore.functions.ObjectToBlobMetadata;\nimport org.jclouds.googlecloudstorage.domain.Bucket;\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences;\nimport org.jclouds.googlecloudstorage.domain.GoogleCloudStorageObject;\nimport org.jclouds.googlecloudstorage.domain.ListPageWithPrefixes;\nimport org.jclouds.googlecloudstorage.domain.ObjectAccessControls;\nimport org.jclouds.googlecloudstorage.domain.templates.BucketTemplate;\nimport org.jclouds.googlecloudstorage.domain.templates.ComposeObjectTemplate;\nimport org.jclouds.googlecloudstorage.domain.templates.ObjectAccessControlsTemplate;\nimport org.jclouds.googlecloudstorage.domain.templates.ObjectTemplate;\nimport org.jclouds.googlecloudstorage.options.InsertObjectOptions;\nimport org.jclouds.googlecloudstorage.options.ListObjectOptions;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.io.ContentMetadata;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.PayloadSlicer;\nimport org.jclouds.util.Strings2;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Iterables;\nimport com.google.common.hash.HashCode;\n\npublic final class GoogleCloudStorageBlobStore extends BaseBlobStore {\n\n   private final GoogleCloudStorageApi api;\n   private final BucketToStorageMetadata bucketToStorageMetadata;\n   private final ObjectToBlobMetadata objectToBlobMetadata;\n   private final ObjectListToStorageMetadata objectListToStorageMetadata;\n   private final BlobMetadataToObjectTemplate blobMetadataToObjectTemplate;\n   private final BlobStoreListContainerOptionsToListObjectOptions listContainerOptionsToListObjectOptions;\n   private final Supplier<String> projectId;\n   private final BlobToHttpGetOptions blob2ObjectGetOptions;\n\n   @Inject GoogleCloudStorageBlobStore(BlobStoreContext context, BlobUtils blobUtils, Supplier<Location> defaultLocation,\n            @Memoized Supplier<Set<? extends Location>> locations, PayloadSlicer slicer, GoogleCloudStorageApi api,\n            BucketToStorageMetadata bucketToStorageMetadata, ObjectToBlobMetadata objectToBlobMetadata,\n            ObjectListToStorageMetadata objectListToStorageMetadata,\n            BlobMetadataToObjectTemplate blobMetadataToObjectTemplate,\n            BlobStoreListContainerOptionsToListObjectOptions listContainerOptionsToListObjectOptions,\n            @CurrentProject Supplier<String> projectId,\n            BlobToHttpGetOptions blob2ObjectGetOptions) {\n      super(context, blobUtils, defaultLocation, locations, slicer);\n      this.api = api;\n      this.bucketToStorageMetadata = bucketToStorageMetadata;\n      this.objectToBlobMetadata = objectToBlobMetadata;\n      this.objectListToStorageMetadata = objectListToStorageMetadata;\n      this.blobMetadataToObjectTemplate = blobMetadataToObjectTemplate;\n      this.listContainerOptionsToListObjectOptions = listContainerOptionsToListObjectOptions;\n      this.projectId = projectId;\n      this.blob2ObjectGetOptions = checkNotNull(blob2ObjectGetOptions, \"blob2ObjectGetOptions\");\n   }\n\n   @Override\n   public PageSet<? extends StorageMetadata> list() {\n      return new Function<ListPage<Bucket>, PageSet<? extends StorageMetadata>>() {\n         public PageSet<? extends StorageMetadata> apply(ListPage<Bucket> from) {\n            return new PageSetImpl<StorageMetadata>(Iterables.transform(from, bucketToStorageMetadata),\n                  from.nextPageToken());\n         }\n      }.apply(api.getBucketApi().listBucket(projectId.get()));\n   }\n\n   @Override\n   public boolean containerExists(String container) {\n      return api.getBucketApi().bucketExist(container);\n   }\n\n   @Override\n   public boolean createContainerInLocation(Location location, String container) {\n      BucketTemplate template = new BucketTemplate().name(container);\n      if (location != null) {\n         DomainResourceReferences.Location gcsLocation = DomainResourceReferences.Location.fromValue(location.getId());\n         template = template.location(gcsLocation);\n      }\n      return api.getBucketApi().createBucket(projectId.get(), template) != null;\n   }\n\n   @Override\n   public boolean createContainerInLocation(Location location, String container, CreateContainerOptions options) {\n      BucketTemplate template = new BucketTemplate().name(container);\n      if (location != null) {\n         DomainResourceReferences.Location gcsLocation = DomainResourceReferences.Location.fromValue(location.getId());\n         template = template.location(gcsLocation);\n      }\n      Bucket bucket = api.getBucketApi().createBucket(projectId.get(), template);\n      if (options.isPublicRead()) {\n         try {\n            ObjectAccessControlsTemplate doAclTemplate = ObjectAccessControlsTemplate.create(\"allUsers\", READER);\n            api.getDefaultObjectAccessControlsApi().createDefaultObjectAccessControls(container, doAclTemplate);\n         } catch (HttpResponseException e) {\n            // If DefaultObjectAccessControls operation fail, Reverse create operation the operation.\n            api.getBucketApi().deleteBucket(container);\n            return false;\n         }\n      }\n\n      return bucket != null;\n   }\n\n   @Override\n   public ContainerAccess getContainerAccess(String container) {\n      ObjectAccessControls controls = api.getDefaultObjectAccessControlsApi().getDefaultObjectAccessControls(container, \"allUsers\");\n      if (controls == null || controls.role() == DomainResourceReferences.ObjectRole.OWNER) {\n         return ContainerAccess.PRIVATE;\n      } else {\n         return ContainerAccess.PUBLIC_READ;\n      }\n   }\n\n   @Override\n   public void setContainerAccess(String container, ContainerAccess access) {\n      ObjectAccessControlsTemplate doAclTemplate;\n      if (access == ContainerAccess.PUBLIC_READ) {\n         doAclTemplate = ObjectAccessControlsTemplate.create(\"allUsers\", READER);\n         api.getDefaultObjectAccessControlsApi().createDefaultObjectAccessControls(container, doAclTemplate);\n      } else {\n         api.getDefaultObjectAccessControlsApi().deleteDefaultObjectAccessControls(container, \"allUsers\");\n      }\n   }\n\n   /** Returns list of of all the objects */\n   @Override\n   public PageSet<? extends StorageMetadata> list(String container) {\n      return list(container, ListContainerOptions.NONE);\n   }\n\n   @Override\n   public PageSet<? extends StorageMetadata> list(String container, ListContainerOptions options) {\n      ListObjectOptions listOptions = listContainerOptionsToListObjectOptions.apply(options);\n      ListPageWithPrefixes<GoogleCloudStorageObject> gcsList = api.getObjectApi().listObjects(container, listOptions);\n      return objectListToStorageMetadata.apply(gcsList);\n   }\n\n   /**\n    * Checks whether an accessible object is available. Google cloud storage does not support directly support\n    * BucketExist or ObjectExist operations\n    */\n   @Override\n   public boolean blobExists(String container, String name) {\n      return api.getObjectApi().objectExists(container, Strings2.urlEncode(name));\n   }\n\n   /**\n    * This supports multipart/related upload which has exactly 2 parts, media-part and metadata-part\n    */\n   @Override\n   public String putBlob(String container, Blob blob) {\n      return putBlob(container, blob, PutOptions.NONE);\n   }\n\n   @Override\n   public String putBlob(String container, Blob blob, PutOptions options) {\n      long length = checkNotNull(blob.getPayload().getContentMetadata().getContentLength());\n\n      if (length != 0 && options.isMultipart()) {\n         // JCLOUDS-912 prevents using single-part uploads with InputStream payloads.\n         // Work around this with multi-part upload which buffers parts in-memory.\n         return putMultipartBlob(container, blob, options);\n      } else {\n         ObjectTemplate template = blobMetadataToObjectTemplate.apply(blob.getMetadata());\n\n         HashCode md5 = blob.getMetadata().getContentMetadata().getContentMD5AsHashCode();\n         if (md5 != null) {\n            template.md5Hash(base64().encode(md5.asBytes()));\n         }\n\n         if (options.getBlobAccess() == BlobAccess.PUBLIC_READ) {\n            ObjectAccessControls controls = ObjectAccessControls.builder()\n                  .entity(\"allUsers\")\n                  .bucket(container)\n                  .role(READER)\n                  .build();\n            template.addAcl(controls);\n         }\n\n         return api.getObjectApi().multipartUpload(container, template, blob.getPayload()).etag();\n      }\n   }\n\n   @Override\n   public BlobMetadata blobMetadata(String container, String name) {\n      return objectToBlobMetadata.apply(api.getObjectApi().getObject(container, Strings2.urlEncode(name)));\n   }\n\n   @Override\n   public Blob getBlob(String container, String name, GetOptions options) {\n      GoogleCloudStorageObject gcsObject = api.getObjectApi().getObject(container, Strings2.urlEncode(name));\n      if (gcsObject == null) {\n         return null;\n      }\n      org.jclouds.http.options.GetOptions httpOptions = blob2ObjectGetOptions.apply(options);\n      MutableBlobMetadata metadata = objectToBlobMetadata.apply(gcsObject);\n      Blob blob = new BlobImpl(metadata);\n      Payload payload = api.getObjectApi().download(container, Strings2.urlEncode(name), httpOptions).getPayload();\n      Long contentLength = payload.getContentMetadata().getContentLength();\n      payload.setContentMetadata(metadata.getContentMetadata()); // Doing this first retains it on setPayload.\n      blob.setPayload(payload);\n      // getObject() returns the full object length but download() could be smaller due to range requests.\n      payload.getContentMetadata().setContentLength(contentLength);\n      return blob;\n   }\n\n   @Override\n   public void removeBlob(String container, String name) {\n      api.getObjectApi().deleteObject(container, Strings2.urlEncode(name));\n   }\n\n   @Override\n   public BlobAccess getBlobAccess(String container, String name) {\n      ObjectAccessControls controls = api.getObjectAccessControlsApi().getObjectAccessControls(container,\n            Strings2.urlEncode(name), \"allUsers\");\n      if (controls != null && controls.role() == DomainResourceReferences.ObjectRole.READER) {\n         return BlobAccess.PUBLIC_READ;\n      } else {\n         return BlobAccess.PRIVATE;\n      }\n   }\n\n   @Override\n   public void setBlobAccess(String container, String name, BlobAccess access) {\n      if (access == BlobAccess.PUBLIC_READ) {\n         ObjectAccessControls controls = ObjectAccessControls.builder()\n               .entity(\"allUsers\")\n               .bucket(container)\n               .role(READER)\n               .build();\n         api.getObjectApi().patchObject(container, Strings2.urlEncode(name), new ObjectTemplate().addAcl(controls));\n      } else {\n         api.getObjectAccessControlsApi().deleteObjectAccessControls(container, Strings2.urlEncode(name), \"allUsers\");\n      }\n   }\n\n   @Override\n   protected boolean deleteAndVerifyContainerGone(String container) {\n      ListPageWithPrefixes<GoogleCloudStorageObject> list = api.getObjectApi().listObjects(container);\n\n      if (list == null || (!list.iterator().hasNext() && list.prefixes().isEmpty())) {\n         if (!api.getBucketApi().deleteBucket(container)) {\n            return true;\n         } else {\n            return !api.getBucketApi().bucketExist(container);\n         }\n      }\n\n      return false;\n   }\n\n   @Override\n   public String copyBlob(String fromContainer, String fromName, String toContainer, String toName,\n         CopyOptions options) {\n      if (options.ifMatch() != null) {\n         throw new UnsupportedOperationException(\"GCS does not support ifMatch\");\n      }\n      if (options.ifNoneMatch() != null) {\n         throw new UnsupportedOperationException(\"GCS does not support ifNoneMatch\");\n      }\n      if (options.ifModifiedSince() != null) {\n         throw new UnsupportedOperationException(\"GCS does not support ifModifiedSince\");\n      }\n      if (options.ifUnmodifiedSince() != null) {\n         throw new UnsupportedOperationException(\"GCS does not support ifUnmodifiedSince\");\n      }\n\n      if (options.contentMetadata() == null && options.userMetadata() == null) {\n         return api.getObjectApi().copyObject(toContainer, Strings2.urlEncode(toName), fromContainer,\n               Strings2.urlEncode(fromName)).etag();\n      }\n\n      ObjectTemplate template = new ObjectTemplate();\n\n      if (options.contentMetadata() != null) {\n         ContentMetadata contentMetadata = options.contentMetadata();\n\n         String contentDisposition = contentMetadata.getContentDisposition();\n         if (contentDisposition != null) {\n            template.contentDisposition(contentDisposition);\n         }\n\n         // TODO: causes failures with subsequent GET operations:\n         // HTTP/1.1 failed with response: HTTP/1.1 503 Service Unavailable; content: [Service Unavailable]\n/*\n         String contentEncoding = contentMetadata.getContentEncoding();\n         if (contentEncoding != null) {\n            template.contentEncoding(contentEncoding);\n         }\n*/\n\n         String contentLanguage = contentMetadata.getContentLanguage();\n         if (contentLanguage != null) {\n            template.contentLanguage(contentLanguage);\n         }\n\n         String contentType = contentMetadata.getContentType();\n         if (contentType != null) {\n            template.contentType(contentType);\n         }\n      }\n\n      if (options.userMetadata() != null) {\n         template.customMetadata(options.userMetadata());\n      }\n\n      return api.getObjectApi().copyObject(toContainer, Strings2.urlEncode(toName), fromContainer,\n            Strings2.urlEncode(fromName), template).etag();\n   }\n\n   @Override\n   public MultipartUpload initiateMultipartUpload(String container, BlobMetadata blobMetadata, PutOptions options) {\n      String uploadId = UUID.randomUUID().toString();\n      return MultipartUpload.create(container, blobMetadata.getName(), uploadId, blobMetadata, options);\n   }\n\n   @Override\n   public void abortMultipartUpload(MultipartUpload mpu) {\n      ImmutableList.Builder<String> builder = ImmutableList.builder();\n      List<MultipartPart> parts = listMultipartUpload(mpu);\n      for (MultipartPart part : parts) {\n         builder.add(getMPUPartName(mpu, part.partNumber()));\n      }\n      removeBlobs(mpu.containerName(), builder.build());\n   }\n\n   @Override\n   public String completeMultipartUpload(MultipartUpload mpu, List<MultipartPart> parts) {\n      ImmutableList.Builder<GoogleCloudStorageObject> objectsBuilder = ImmutableList.builder();\n      for (MultipartPart part : parts) {\n         objectsBuilder.add(api.getObjectApi().getObject(mpu.containerName(),\n               Strings2.urlEncode(getMPUPartName(mpu, part.partNumber()))));\n      }\n\n      ObjectTemplate destination = blobMetadataToObjectTemplate.apply(mpu.blobMetadata());\n      final ImmutableList<GoogleCloudStorageObject> objects = objectsBuilder.build();\n      if (!objects.isEmpty()) {\n         destination.storageClass(objects.get(0).storageClass());\n      }\n      if (mpu.putOptions().getBlobAccess() == BlobAccess.PUBLIC_READ) {\n         ObjectAccessControls controls = ObjectAccessControls.builder()\n               .entity(\"allUsers\")\n               .bucket(mpu.containerName())\n               .role(READER)\n               .build();\n         destination.addAcl(controls);\n      }\n\n      ComposeObjectTemplate template = ComposeObjectTemplate.builder()\n            .fromGoogleCloudStorageObject(objects)\n            .destination(destination).build();\n      String eTag = api.getObjectApi().composeObjects(mpu.containerName(), Strings2.urlEncode(mpu.blobName()), template)\n            .etag();\n\n      // remove parts, composite object keeps a reference to them\n      ImmutableList.Builder<String> builder = ImmutableList.builder();\n      for (MultipartPart part : parts) {\n         builder.add(getMPUPartName(mpu, part.partNumber()));\n      }\n      removeBlobs(mpu.containerName(), builder.build());\n\n      return eTag;\n   }\n\n   @Override\n   public MultipartPart uploadMultipartPart(MultipartUpload mpu, int partNumber, Payload payload) {\n      String partName = getMPUPartName(mpu, partNumber);\n      long partSize = payload.getContentMetadata().getContentLength();\n      GoogleCloudStorageObject object = api.getObjectApi().simpleUpload(\n            mpu.containerName(), \"application/unknown\", partSize, payload, new InsertObjectOptions().name(partName));\n      return MultipartPart.create(partNumber, partSize, object.etag(), object.updated());\n   }\n\n   @Override\n   public List<MultipartPart> listMultipartUpload(MultipartUpload mpu) {\n      ImmutableList.Builder<MultipartPart> parts = ImmutableList.builder();\n      PageSet<? extends StorageMetadata> pageSet = list(mpu.containerName(),\n            new ListContainerOptions().prefix(mpu.id() + \"_\"));\n      // TODO: pagination\n      for (StorageMetadata sm : pageSet) {\n         int lastUnderscore = sm.getName().lastIndexOf('_');\n         int partNumber = Integer.parseInt(sm.getName().substring(lastUnderscore + 1));\n         parts.add(MultipartPart.create(partNumber, sm.getSize(), sm.getETag(), sm.getLastModified()));\n      }\n      return parts.build();\n   }\n\n   @Override\n   public List<MultipartUpload> listMultipartUploads(String container) {\n      throw new UnsupportedOperationException(\"not supported\");\n   }\n\n   @Override\n   public long getMinimumMultipartPartSize() {\n      return 5L * 1024L * 1024L;\n   }\n\n   @Override\n   public long getMaximumMultipartPartSize() {\n      return 5L * 1024L * 1024L * 1024L;\n   }\n\n   @Override\n   public int getMaximumNumberOfParts() {\n      // can raise limit via composite objects of composites\n      return 32;\n   }\n\n   private static String getMPUPartName(MultipartUpload mpu, int partNumber) {\n      return String.format(\"%s_%08d\", mpu.id(), partNumber);\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/blobstore/config/GoogleCloudStorageBlobStoreContextModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.blobstore.config;\n\nimport org.jclouds.blobstore.BlobRequestSigner;\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.attr.ConsistencyModel;\nimport org.jclouds.date.TimeStamp;\nimport org.jclouds.googlecloudstorage.blobstore.GoogleCloudStorageBlobRequestSigner;\nimport org.jclouds.googlecloudstorage.blobstore.GoogleCloudStorageBlobStore;\n\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Provides;\nimport com.google.inject.Scopes;\n\npublic class GoogleCloudStorageBlobStoreContextModule extends AbstractModule {\n\n   @Override\n   protected void configure() {\n      bind(ConsistencyModel.class).toInstance(ConsistencyModel.EVENTUAL);\n      bind(BlobStore.class).to(GoogleCloudStorageBlobStore.class).in(Scopes.SINGLETON);\n      bind(BlobRequestSigner.class).to(GoogleCloudStorageBlobRequestSigner.class);\n   }\n\n   @Provides\n   @TimeStamp\n   protected final Long unixEpochTimestamp() {\n      return System.currentTimeMillis() / 1000;\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/blobstore/functions/BlobMetadataToObjectTemplate.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.blobstore.functions;\n\nimport static com.google.common.io.BaseEncoding.base64;\n\nimport java.util.Map;\n\nimport org.jclouds.blobstore.domain.BlobMetadata;\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.StorageClass;\nimport org.jclouds.googlecloudstorage.domain.templates.ObjectTemplate;\nimport org.jclouds.io.ContentMetadata;\n\nimport com.google.common.base.Function;\nimport com.google.common.hash.HashCode;\n\npublic class BlobMetadataToObjectTemplate implements Function<BlobMetadata, ObjectTemplate> {\n\n   public ObjectTemplate apply(BlobMetadata from) {\n      if (from == null)\n         return null;\n\n      String name = from.getName();\n      Map<String, String> userMeta = from.getUserMetadata();\n\n      ContentMetadata metadata = from.getContentMetadata();\n      String contentDisposition = metadata.getContentDisposition();\n      String contentEncoding = metadata.getContentEncoding();\n      String contentLanguage = metadata.getContentLanguage();\n      String contentType = metadata.getContentType();\n      Long contentLength = metadata.getContentLength();\n\n      HashCode md5 = metadata.getContentMD5AsHashCode();\n\n      ObjectTemplate template = new ObjectTemplate().contentType(contentType).size(contentLength)\n               .contentEncoding(contentEncoding).contentLanguage(contentLanguage)\n               .contentDisposition(contentDisposition).name(name).customMetadata(userMeta)\n               .storageClass(StorageClass.fromTier(from.getTier()));\n      if (md5 != null) {\n         template.md5Hash(base64().encode(md5.asBytes()));\n      }\n      return template;\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/blobstore/functions/BlobStoreListContainerOptionsToListObjectOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.blobstore.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.blobstore.options.ListContainerOptions;\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.Projection;\nimport org.jclouds.googlecloudstorage.options.ListObjectOptions;\n\nimport com.google.common.base.Function;\n\npublic class BlobStoreListContainerOptionsToListObjectOptions implements\n         Function<ListContainerOptions, ListObjectOptions> {\n   public ListObjectOptions apply(ListContainerOptions from) {\n      if (from.getDir() != null && (from.getPrefix() != null || from.getDelimiter() != null)) {\n         throw new IllegalArgumentException(\"Cannot pass both directory and prefix/delimiter\");\n      }\n      checkNotNull(from, \"set options to instance NONE instead of passing null\");\n      ListObjectOptions httpOptions = new ListObjectOptions();\n\n      if (!from.isRecursive() && from.getDelimiter() == null) {\n         httpOptions = httpOptions.delimiter(\"/\");\n      }\n      if (from.getDelimiter() != null) {\n         httpOptions = httpOptions.delimiter(from.getDelimiter());\n      }\n      if (from.getDir() != null) {\n         String path = from.getDir();\n         if (!path.endsWith(\"/\"))\n            path += \"/\";\n         httpOptions = httpOptions.prefix(path);\n      }\n      if (from.getPrefix() != null) {\n         httpOptions.prefix(from.getPrefix());\n      }\n      if (from.getMarker() != null) {\n         httpOptions = httpOptions.pageToken(from.getMarker());\n      }\n      if (from.getMaxResults() != null) {\n         httpOptions = httpOptions.maxResults(from.getMaxResults());\n      }\n      if (from.isDetailed()) {\n         httpOptions = httpOptions.projection(Projection.FULL);\n      }\n      return httpOptions;\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/blobstore/functions/BucketToStorageMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.blobstore.functions;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.blobstore.domain.MutableStorageMetadata;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.domain.StorageType;\nimport org.jclouds.blobstore.domain.internal.MutableStorageMetadataImpl;\nimport org.jclouds.domain.Location;\nimport org.jclouds.googlecloudstorage.domain.Bucket;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\n\npublic class BucketToStorageMetadata implements Function<Bucket, StorageMetadata> {\n   private Supplier<Location> defaultLocation;\n\n   @Inject BucketToStorageMetadata(Supplier<Location> defaultLocation) {\n      this.defaultLocation = defaultLocation;\n   }\n\n   public StorageMetadata apply(Bucket from) {\n      MutableStorageMetadata to = new MutableStorageMetadataImpl();\n      to.setName(from.name());\n      to.setLocation(defaultLocation.get());\n      to.setType(StorageType.CONTAINER);\n      return to;\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/blobstore/functions/ObjectListToStorageMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.blobstore.functions;\n\nimport java.util.SortedSet;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.blobstore.domain.MutableStorageMetadata;\nimport org.jclouds.blobstore.domain.PageSet;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.domain.StorageType;\nimport org.jclouds.blobstore.domain.internal.MutableStorageMetadataImpl;\nimport org.jclouds.blobstore.domain.internal.PageSetImpl;\nimport org.jclouds.googlecloudstorage.domain.GoogleCloudStorageObject;\nimport org.jclouds.googlecloudstorage.domain.ListPageWithPrefixes;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Sets;\n\npublic class ObjectListToStorageMetadata\n      implements Function<ListPageWithPrefixes<GoogleCloudStorageObject>, PageSet<? extends StorageMetadata>> {\n   private final ObjectToBlobMetadata object2blobMd;\n\n   @Inject public ObjectListToStorageMetadata(ObjectToBlobMetadata object2blobMd) {\n      this.object2blobMd = object2blobMd;\n   }\n\n   public PageSet<? extends StorageMetadata> apply(ListPageWithPrefixes<GoogleCloudStorageObject> from) {\n      if (from == null) {\n         from = ListPageWithPrefixes.create(null, null, null);\n      }\n\n      SortedSet<StorageMetadata> results = Sets.<StorageMetadata> newTreeSet(Iterables.transform(from, object2blobMd));\n      for (String prefix : from.prefixes()) {\n          MutableStorageMetadata metadata = new MutableStorageMetadataImpl();\n          metadata.setType(StorageType.RELATIVE_PATH);\n          metadata.setName(prefix);\n          results.add(metadata);\n      }\n      return new PageSetImpl<StorageMetadata>(results, from.nextPageToken());\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/blobstore/functions/ObjectToBlobMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.blobstore.functions;\n\n\nimport org.jclouds.blobstore.domain.MutableBlobMetadata;\nimport org.jclouds.blobstore.domain.StorageType;\nimport org.jclouds.blobstore.domain.internal.MutableBlobMetadataImpl;\nimport org.jclouds.googlecloudstorage.domain.GoogleCloudStorageObject;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.Function;\nimport com.google.common.hash.HashCode;\nimport com.google.common.io.BaseEncoding;\n\npublic class ObjectToBlobMetadata implements Function<GoogleCloudStorageObject, MutableBlobMetadata> {\n\n   public MutableBlobMetadata apply(GoogleCloudStorageObject from) {\n      if (from == null) {\n         return null;\n      }\n      MutableBlobMetadata to = new MutableBlobMetadataImpl();\n      to.getContentMetadata().setContentMD5(toHashCode(from.md5Hash()));\n      to.getContentMetadata().setContentType(from.contentType());\n      to.getContentMetadata().setContentDisposition(from.contentDisposition());\n      to.getContentMetadata().setContentEncoding(from.contentEncoding());\n      to.getContentMetadata().setContentLanguage(from.contentLanguage());\n      to.getContentMetadata().setContentLength(from.size());\n      to.setLastModified(from.updated());\n      to.setContainer(from.bucket());\n      to.setUserMetadata(from.metadata());\n      to.setETag(from.etag());\n      to.setName(from.name());\n      to.setUri(from.selfLink());\n      to.setId(from.id());\n      to.setPublicUri(from.mediaLink());\n      to.setType(StorageType.BLOB);\n      to.setSize(from.size());\n      to.setTier(from.storageClass().toTier());\n      return to;\n   }\n\n   private static HashCode toHashCode(@Nullable String hashCode) {\n      return hashCode == null ? null : HashCode.fromBytes(BaseEncoding.base64().decode(hashCode));\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/config/GoogleCloudStorageHttpApiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.config;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.googlecloud.config.CurrentProject;\nimport org.jclouds.googlecloudstorage.GoogleCloudStorageApi;\nimport org.jclouds.googlecloudstorage.handlers.GoogleCloudStorageErrorHandler;\nimport org.jclouds.googlecloudstorage.handlers.GoogleCloudStorageClientErrorRetryHandler;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpRetryHandler;\nimport org.jclouds.http.annotation.ClientError;\nimport org.jclouds.http.annotation.Redirection;\nimport org.jclouds.http.annotation.ServerError;\nimport org.jclouds.location.Provider;\nimport org.jclouds.oauth.v2.config.OAuthScopes;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.config.HttpApiModule;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.inject.Provides;\n\n@ConfiguresHttpApi\npublic class GoogleCloudStorageHttpApiModule extends HttpApiModule<GoogleCloudStorageApi> {\n\n   @Override public void configure(){\n      super.configure();\n      bind(OAuthScopes.class).toInstance(GoogleCloudStorageOAuthScopes.create());\n   }\n\n   @Override\n   protected void bindErrorHandlers() {\n      bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(GoogleCloudStorageErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(GoogleCloudStorageErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(GoogleCloudStorageErrorHandler.class);\n   }\n\n   @Override\n   protected void bindRetryHandlers() {\n      bind(HttpRetryHandler.class).annotatedWith(ClientError.class).to(GoogleCloudStorageClientErrorRetryHandler.class);\n      // TODO: GoogleCloudStorageRedirectRetryHandler?\n   }\n\n   @Provides\n   @Singleton @CurrentProject\n   public Supplier<String> supplyProject(@Provider final Supplier<Credentials> creds) {\n      return Suppliers.compose(new Function<Credentials, String>() {\n         @Override public String apply(Credentials in) {\n            return CurrentProject.ClientEmail.toProjectNumber(in.identity);\n         }\n      }, creds);\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/config/GoogleCloudStorageOAuthScopes.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.config;\n\nimport java.util.List;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.oauth.v2.config.OAuthScopes;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\n\n@AutoValue public abstract class GoogleCloudStorageOAuthScopes implements OAuthScopes {\n   abstract OAuthScopes readOrWriteScopes();\n\n   /** Full control is read/write + acls */\n   abstract List<String> fullControlScopes();\n\n   public static GoogleCloudStorageOAuthScopes create() {\n      return new AutoValue_GoogleCloudStorageOAuthScopes( //\n            OAuthScopes.ReadOrWriteScopes.create( //\n                  \"https://www.googleapis.com/auth/devstorage.read_only\", //\n                  \"https://www.googleapis.com/auth/devstorage.read_write\"), //\n            ImmutableList.of(\"https://www.googleapis.com/auth/devstorage.full_control\") //\n      );\n   }\n\n   /** If the path contains or ends with {@code /acl} or {@code /defaultObjectAcl}, it needs full-control. */\n   @Override public List<String> forRequest(HttpRequest input) {\n      String path = input.getEndpoint().getPath();\n      if (path.endsWith(\"/acl\") || path.endsWith(\"/defaultObjectAcl\") //\n            || path.contains(\"/acl/\") || path.contains(\"/defaultObjectAcl/\")) {\n         return fullControlScopes();\n      } else if (input.getMethod().equalsIgnoreCase(\"PUT\") || input.getMethod().equalsIgnoreCase(\"PATCH\")) {\n         return fullControlScopes();\n      } else if (\"PATCH\".equalsIgnoreCase(input.getFirstHeaderOrNull(\"X-HTTP-Method-Override\"))) {\n         return fullControlScopes();\n      }\n      return readOrWriteScopes().forRequest(input);\n   }\n\n   GoogleCloudStorageOAuthScopes() {\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/config/GoogleCloudStorageParserModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.config;\n\nimport java.lang.reflect.Type;\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.googlecloud.config.ListPageAdapterFactory;\nimport org.jclouds.googlecloudstorage.domain.templates.BucketTemplate;\nimport org.jclouds.json.config.GsonModule;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.gson.JsonElement;\nimport com.google.gson.JsonObject;\nimport com.google.gson.JsonSerializationContext;\nimport com.google.gson.JsonSerializer;\nimport com.google.gson.TypeAdapterFactory;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Provides;\n\npublic class GoogleCloudStorageParserModule extends AbstractModule {\n\n   @Override protected void configure() {\n      bind(GsonModule.DateAdapter.class).to(GsonModule.Iso8601DateAdapter.class);\n   }\n\n   @Provides @Singleton public Map<Type, Object> typeAdapters() {\n      return new ImmutableMap.Builder<Type, Object>()\n               .put(BucketTemplate.class, new BucketTemplateTypeAdapter())\n               .build();\n   }\n\n   // TODO: change jclouds core to use collaborative set bindings\n   @Provides @Singleton Set<TypeAdapterFactory> typeAdapterFactories() {\n      return ImmutableSet.<TypeAdapterFactory>of(new ListPageAdapterFactory());\n   }\n\n   private static class BucketTemplateTypeAdapter implements JsonSerializer<BucketTemplate> {\n\n      @Override\n      public JsonElement serialize(BucketTemplate src, Type typeOfSrc, JsonSerializationContext context) {\n         BucketTemplateInternal template = new BucketTemplateInternal(src);\n         JsonObject bucketTemplate = (JsonObject) context.serialize(template, BucketTemplateInternal.class);\n\n         // deal with bucketAccessControls\n         if (!(src.acl() == null) && (src.acl().isEmpty())) {\n            bucketTemplate.add(\"acl\", null);\n         }\n         // deal with DefaultObjectAccessControls\n         if (!(src.defaultObjectAccessControls() == null) && (src.defaultObjectAccessControls().isEmpty())) {\n            bucketTemplate.add(\"defaultObjectAccessControls\", null);\n         }\n\n         // deal with Cors\n         if (!(src.cors() == null) && (src.cors().isEmpty())) {\n            bucketTemplate.add(\"cors\", null);\n         }\n\n         return bucketTemplate;\n      }\n\n      private static class BucketTemplateInternal extends BucketTemplate {\n         private BucketTemplateInternal(BucketTemplate template) {\n            name(template.name()).projectNumber(template.projectNumber()).acl(template.acl())\n                  .defaultObjectAccessControls(template.defaultObjectAccessControls()).owner(template.owner())\n                  .location(template.location()).website(template.website()).logging(template.logging())\n                  .versioning(template.versioning()).cors(template.cors()).lifeCycle(template.lifeCycle())\n                  .storageClass(template.storageClass());\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/domain/Bucket.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.googlecloudstorage.domain;\n\nimport static org.jclouds.googlecloud.internal.NullSafeCopies.copyOf;\n\nimport java.util.Date;\nimport java.util.List;\n\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.Location;\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.StorageClass;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n/**\n * The Bucket represents a bucket in Google Cloud Storage. There is a single global namespace shared by all buckets.\n *\n * @see <a href = \" https://developers.google.com/storage/docs/json_api/v1/buckets\"/>\n */\n@AutoValue\npublic abstract class Bucket {\n   @AutoValue\n   public abstract static class Cors {\n      public abstract List<String> origin();\n\n      public abstract List<String> method();\n\n      public abstract List<String> responseHeader();\n\n      @Nullable public abstract Integer maxAgeSeconds();\n\n      @SerializedNames({ \"origin\", \"method\", \"responseHeader\", \"maxAgeSeconds\" })\n      public static Cors create(List<String> origin, List<String> method, List<String> responseHeader,\n            Integer maxAgeSeconds) {\n         return new AutoValue_Bucket_Cors(copyOf(origin), copyOf(method), copyOf(responseHeader), maxAgeSeconds);\n      }\n   }\n\n   @AutoValue\n   public abstract static class Logging {\n      public abstract String logBucket();\n\n      @Nullable public abstract String logObjectPrefix();\n\n      @SerializedNames({ \"logBucket\", \"logObjectPrefix\" })\n      public static Logging create(String logBucket, String logObjectPrefix) {\n         return new AutoValue_Bucket_Logging(logBucket, logObjectPrefix);\n      }\n   }\n\n   @AutoValue\n   public abstract static class LifeCycle {\n\n      @AutoValue\n      public abstract static class Rule {\n\n         @AutoValue\n         public abstract static class Action {\n            public abstract String type();\n\n            @SerializedNames(\"type\")\n            public static Action create(String type) {\n               return new AutoValue_Bucket_LifeCycle_Rule_Action(type);\n            }\n         }\n\n         @AutoValue\n         public abstract static class Condition {\n            @Nullable public abstract Integer age();\n\n            @Nullable public abstract Date createdBefore();\n\n            @Nullable public abstract Boolean isLive();\n\n            @Nullable public abstract Integer numNewerVersions();\n\n            @SerializedNames({ \"age\", \"createdBefore\", \"isLive\", \"numNewerVersions\" })\n            public static Condition create(Integer age, Date createdBefore, Boolean isLive, Integer numNewerVersions) {\n               return new AutoValue_Bucket_LifeCycle_Rule_Condition(age, createdBefore, isLive, numNewerVersions);\n            }\n         }\n\n         public abstract Action action();\n\n         public abstract Condition condition();\n\n         @SerializedNames({ \"action\", \"condition\" })\n         public static Rule create(Action action, Condition condition) {\n            return new AutoValue_Bucket_LifeCycle_Rule(action, condition);\n         }\n      }\n\n      public abstract List<Rule> rules();\n\n      @SerializedNames(\"rules\")\n      public static LifeCycle create(List<Rule> rules) {\n         return new AutoValue_Bucket_LifeCycle(copyOf(rules));\n      }\n   }\n\n   @AutoValue\n   public abstract static class Website {\n      @Nullable public abstract String mainPageSuffix();\n\n      @Nullable public abstract String notFoundPage();\n\n      @SerializedNames({ \"mainPageSuffix\", \"notFoundPage\" })\n      public static Website create(String mainPageSuffix, String notFoundPage) {\n         return new AutoValue_Bucket_Website(mainPageSuffix, notFoundPage);\n      }\n   }\n\n   @AutoValue\n   public abstract static class Versioning {\n      public abstract Boolean enabled();\n\n      @SerializedNames(\"enabled\")\n      public static Versioning create(Boolean enabled) {\n         return new AutoValue_Bucket_Versioning(enabled);\n      }\n   }\n\n   public abstract String id();\n\n   public abstract String name();\n\n   @Nullable public abstract Long projectNumber();\n\n   public abstract Date timeCreated();\n\n   public abstract Long metageneration();\n\n   public abstract List<BucketAccessControls> acl();\n\n   public abstract List<ObjectAccessControls> defaultObjectAcl();\n\n   @Nullable public abstract Owner owner();\n\n   @Nullable public abstract Location location();\n\n   @Nullable public abstract Website website();\n\n   @Nullable public abstract Logging logging();\n\n   @Nullable public abstract Versioning versioning();\n\n   public abstract List<Cors> cors();\n\n   @Nullable public abstract LifeCycle lifeCycle();\n\n   @Nullable public abstract StorageClass storageClass();\n\n   @SerializedNames(\n         { \"id\", \"name\", \"projectNumber\", \"timeCreated\", \"metageneration\", \"acl\", \"defaultObjectAcl\", \"owner\",\n               \"location\", \"website\", \"logging\", \"versioning\", \"cors\", \"lifeCycle\", \"storageClass\" })\n   public static Bucket create(String id, String name, Long projectNumber, Date timeCreated, Long metageneration,\n         List<BucketAccessControls> acl, List<ObjectAccessControls> defaultObjectAcl, Owner owner,\n         Location location, Website website, Logging logging, Versioning versioning, List<Cors> cors,\n         LifeCycle lifeCycle, StorageClass storageClass) {\n      return new AutoValue_Bucket(id, name, projectNumber, timeCreated, metageneration, copyOf(acl),\n            copyOf(defaultObjectAcl), owner, location, website, logging, versioning, copyOf(cors), lifeCycle,\n            storageClass);\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/domain/BucketAccessControls.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.domain;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n/**\n * Represents a BucketAccessControls Resource\n *\n * @see <a href= \"https://developers.google.com/storage/docs/json_api/v1/bucketAccessControls\" />\n */\n@AutoValue\npublic abstract class BucketAccessControls {\n\n   public enum Role {\n      READER, WRITER, OWNER\n   }\n\n   // TODO: ensure this is actually needed on input.\n   public abstract String kind();\n\n   public abstract String id();\n\n   public abstract String bucket();\n\n   public abstract String entity();\n\n   @Nullable public abstract String entityId();\n\n   public abstract Role role();\n\n   @Nullable public abstract String email();\n\n   @Nullable public abstract String domain();\n\n   @Nullable public abstract ProjectTeam projectTeam();\n\n   @SerializedNames({ \"kind\", \"id\", \"bucket\", \"entity\", \"entityId\", \"role\", \"email\", \"domain\", \"projectTeam\" })\n   static BucketAccessControls create(String kind, String id, String bucket, String entity, String entityId, Role role,\n         String email, String domain, ProjectTeam projectTeam) {\n      return new AutoValue_BucketAccessControls(kind,\n            id == null ? (bucket + \"/\" + entity) : id, bucket, entity, entityId, role, email, domain, projectTeam);\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static final class Builder {\n\n      private String id;\n      private String bucket;\n      private String entity;\n      private String entityId;\n      private Role role;\n      private String email;\n      private String domain;\n      private ProjectTeam projectTeam;\n\n      public Builder id(String id) {\n         this.id = id;\n         return this;\n      }\n\n      public Builder bucket(String bucket) {\n         this.bucket = bucket;\n         return this;\n      }\n\n      public Builder entity(String entity) {\n         this.entity = entity;\n         return this;\n      }\n\n      public Builder entityId(String entityId) {\n         this.entityId = entityId;\n         return this;\n      }\n\n      public Builder role(Role role) {\n         this.role = role;\n         return this;\n      }\n\n      public Builder email(String email) {\n         this.email = email;\n         return this;\n      }\n\n      public Builder domain(String domain) {\n         this.domain = domain;\n         return this;\n      }\n\n      public Builder projectTeam(ProjectTeam projectTeam) {\n         this.projectTeam = projectTeam;\n         return this;\n      }\n\n      public BucketAccessControls build() {\n         return BucketAccessControls\n               .create(\"storage#bucketAccessControl\", id, bucket, entity, entityId, role, email, domain, projectTeam);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/domain/DomainResourceReferences.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.blobstore.domain.Tier;\n\nimport com.google.common.base.CaseFormat;\n\npublic final class DomainResourceReferences {\n\n   private DomainResourceReferences() {\n   }\n\n   public enum ObjectRole {\n      READER, OWNER\n   }\n\n   public enum Location {\n\n     /*\n      *  Multi-Regional\n      */\n      ASIA,\n      EU,\n      IN,\n      US,\n\n      /*\n       *  Regional\n       */\n      ASIA_EAST1,\n      ASIA_EAST2,\n      ASIA_NORTHEAST1,\n      ASIA_NORTHEAST2,\n      ASIA_NORTHEAST3,\n      ASIA_SOUTHEAST1,\n\n      ASIA_SOUTH1,\n      ASIA_SOUTH2,\n\n      ASIA_SOUTHEAST2,\n\n      ME_CENTRAL1,\n      ME_WEST1,\n\n      NORTHAMERICA_NORTHEAST1,\n      NORTHAMERICA_NORTHEAST2,\n      US_CENTRAL1,\n      US_EAST1,\n      US_EAST4,\n      US_EAST5,\n      US_SOUTH1,\n      US_WEST1,\n      US_WEST2,\n      US_WEST3,\n      US_WEST4,\n\n      SOUTHAMERICA_EAST1,\n      SOUTHAMERICA_WEST1,\n\n      EUROPE_CENTRAL2,\n      EUROPE_NORTH1,\n      EUROPE_SOUTHWEST1,\n      EUROPE_WEST1,\n      EUROPE_WEST2,\n      EUROPE_WEST3,\n      EUROPE_WEST4,\n      EUROPE_WEST6,\n      EUROPE_WEST8,\n      EUROPE_WEST9,\n      EUROPE_WEST12,\n\n      AUSTRALIA_SOUTHEAST1,\n      AUSTRALIA_SOUTHEAST2;\n\n      public String value() {\n         return name().replace('_', '-');\n      }\n\n      @Override\n      public String toString() {\n         return value();\n      }\n\n      public static Location fromValue(String location) {\n         return valueOf(location.replace('-', '_'));\n      }\n   }\n\n   public enum StorageClass {\n      ARCHIVE(Tier.ARCHIVE),\n      COLDLINE(Tier.COLD),\n      DURABLE_REDUCED_AVAILABILITY(Tier.STANDARD),\n      MULTI_REGIONAL(Tier.STANDARD),\n      REGIONAL(Tier.STANDARD),\n      NEARLINE(Tier.COOL),\n      STANDARD(Tier.STANDARD);\n\n      private final Tier tier;\n\n      private StorageClass(Tier tier) {\n         this.tier = checkNotNull(tier, \"tier\");\n      }\n\n      public static StorageClass fromTier(Tier tier) {\n         switch (tier) {\n         case STANDARD: return StorageClass.STANDARD;\n         case INFREQUENT: return StorageClass.NEARLINE;\n         case COOL: return StorageClass.NEARLINE;\n         case COLD: return StorageClass.COLDLINE;\n         case ARCHIVE: return StorageClass.ARCHIVE;\n         }\n         throw new IllegalArgumentException(\"invalid tier: \" + tier);\n      }\n\n      public Tier toTier() {\n         return tier;\n      }\n   }\n\n   public enum Projection {\n      NO_ACL, FULL;\n\n      public String value() {\n         return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, name());\n      }\n\n      @Override\n      public String toString() {\n         return value();\n      }\n\n      public static Projection fromValue(String projection) {\n         return valueOf(CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, projection));\n      }\n   }\n\n   public enum PredefinedAcl {\n      AUTHENTICATED_READ, PRIVATE, PROJEECT_PRIVATE, PUBLIC_READ, PUBLIC_READ_WRITE;\n\n      public String value() {\n         return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, name());\n      }\n\n      @Override\n      public String toString() {\n         return value();\n      }\n\n      public static PredefinedAcl fromValue(String predefinedAcl) {\n         return valueOf(CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, predefinedAcl));\n      }\n   }\n\n   public enum DestinationPredefinedAcl {\n      AUTHENTICATED_READ, BUCKET_OWNER_FULLCONTROL, BUCKET_OWNER_READ, PRIVATE, PROJECT_PRIVATE, PUBLIC_READ;\n\n      public String value() {\n         return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, name());\n      }\n\n      @Override\n      public String toString() {\n         return value();\n      }\n\n      public static DestinationPredefinedAcl fromValue(String destinationPredefinedAcl) {\n         return valueOf(CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, destinationPredefinedAcl));\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/domain/GoogleCloudStorageObject.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.googlecloudstorage.domain;\n\nimport static org.jclouds.googlecloud.internal.NullSafeCopies.copyOf;\n\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.StorageClass;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n/**\n * This class represent an object in a Google Cloud Storage Bucket.\n *\n * @see <a href = \"https://developers.google.com/storage/docs/json_api/v1/Objects\"/>\n */\n@AutoValue\n// TODO: nullable sweep\npublic abstract class GoogleCloudStorageObject {\n\n   public abstract String id();\n   public abstract URI selfLink();\n   public abstract String etag();\n   public abstract String name();\n   public abstract String bucket();\n   public abstract long generation();\n   public abstract long metageneration();\n   @Nullable public abstract String contentType();\n   public abstract Date updated();\n   @Nullable public abstract Date timeDeleted();\n   public abstract StorageClass storageClass();\n   public abstract long size();\n   @Nullable public abstract String md5Hash();\n   public abstract URI mediaLink();\n   public abstract Map<String, String> metadata();\n   @Nullable public abstract String contentEncoding();\n   @Nullable public abstract String contentDisposition();\n   @Nullable public abstract String contentLanguage();\n   @Nullable public abstract String cacheControl();\n   public abstract List<ObjectAccessControls> acl();\n   @Nullable public abstract Owner owner();\n   @Nullable public abstract String crc32c();\n   @Nullable public abstract Integer componentCount();\n\n   @SerializedNames(\n         { \"id\", \"selfLink\", \"etag\", \"name\", \"bucket\", \"generation\", \"metageneration\", \"contentType\", \"updated\",\n               \"timeDeleted\", \"storageClass\", \"size\", \"md5Hash\", \"mediaLink\", \"metadata\", \"contentEncoding\",\n               \"contentDisposition\", \"contentLanguage\", \"cacheControl\", \"acl\", \"owner\", \"crc32c\", \"componentCount\" })\n   public static GoogleCloudStorageObject create(String id, URI selfLink, String etag, String name, String bucket, long generation,\n         long metageneration, String contentType, Date updated, Date timeDeleted, StorageClass storageClass, long size,\n         String md5Hash, URI mediaLink, Map<String, String> metadata, String contentEncoding, String contentDisposition,\n         String contentLanguage, String cacheControl, List<ObjectAccessControls> acl, Owner owner, String crc32c,\n         Integer componentCount) {\n      return new AutoValue_GoogleCloudStorageObject(id, selfLink, etag, name, bucket, generation, metageneration, contentType, updated,\n            timeDeleted, storageClass, size, md5Hash, mediaLink, copyOf(metadata), contentEncoding, contentDisposition,\n            contentLanguage, cacheControl, copyOf(acl), owner, crc32c, componentCount);\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/domain/ListPageWithPrefixes.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.domain;\n\nimport static org.jclouds.googlecloud.internal.NullSafeCopies.copyOf;\n\nimport java.beans.ConstructorProperties;\nimport java.util.List;\n\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.collect.ForwardingList;\n\n/** An immutable list that includes a token, if there is another page available. */\npublic final class ListPageWithPrefixes<T> extends ForwardingList<T> implements ListPage<T> {\n\n   private final List<T> items;\n   private final String nextPageToken;\n   private final List<String> prefixes;\n\n   public static <T> ListPageWithPrefixes<T> create(List<T> items, String nextPageToken, List<String> prefixes) {\n      return new ListPageWithPrefixes<T>(items, nextPageToken, prefixes);\n   }\n\n   @ConstructorProperties({ \"items\", \"nextPageToken\", \"prefixes\" })\n   public ListPageWithPrefixes(List<T> items, String nextPageToken, List<String> prefixes) {\n      this.items = copyOf(items);\n      this.nextPageToken = nextPageToken;\n      this.prefixes = copyOf(prefixes);\n   }\n\n   @Override @Nullable public String nextPageToken() {\n      return nextPageToken;\n   }\n\n   public List<String> prefixes() {\n      return prefixes;\n   }\n\n   @Override protected List<T> delegate() {\n      return items;\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/domain/ObjectAccessControls.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.domain;\n\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.ObjectRole;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n/**\n * Represents a Object Access Control Resource.\n *\n * @see <a href= \"https://developers.google.com/storage/docs/json_api/v1/objectAccessControls\"/>\n */\n@AutoValue\npublic abstract class ObjectAccessControls {\n   private final String kind = \"storage#objectAccessControl\";\n\n   @Nullable public abstract String id();\n\n   @Nullable public abstract String bucket();\n\n   @Nullable public abstract String object();\n\n   @Nullable public abstract Long generation();\n\n   public abstract String entity();\n\n   @Nullable public abstract String entityId();\n\n   public abstract ObjectRole role();\n\n   @Nullable public abstract String email();\n\n   @Nullable public abstract String domain();\n\n   @Nullable public abstract ProjectTeam projectTeam();\n\n   @SerializedNames(\n         { \"id\", \"bucket\", \"object\", \"generation\", \"entity\", \"entityId\", \"role\", \"email\", \"domain\", \"projectTeam\" })\n   public static ObjectAccessControls create(String id, String bucket, String object, Long generation, String entity,\n         String entityId, ObjectRole role, String email, String domain, ProjectTeam projectTeam) {\n      return new AutoValue_ObjectAccessControls(id, bucket, object, generation, entity, entityId, role, email, domain,\n            projectTeam);\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static final class Builder {\n      private String id;\n      private String object;\n      private Long generation;\n      private String bucket;\n      private String entity;\n      private String entityId;\n      private ObjectRole role;\n      private String email;\n      private String domain;\n      private ProjectTeam projectTeam;\n\n      public Builder id(String id) {\n         this.id = id;\n         return this;\n      }\n\n      public Builder bucket(String bucket) {\n         this.bucket = bucket;\n         return this;\n      }\n\n      public Builder object(String object) {\n         this.object = object;\n         return this;\n      }\n\n      public Builder generation(Long generation) {\n         this.generation = generation;\n         return this;\n      }\n\n      public Builder entity(String entity) {\n         this.entity = entity;\n         return this;\n      }\n\n      public Builder entityId(String entityId) {\n         this.entityId = entityId;\n         return this;\n      }\n\n      public Builder role(ObjectRole role) {\n         this.role = role;\n         return this;\n      }\n\n      public Builder email(String email) {\n         this.email = email;\n         return this;\n      }\n\n      public Builder domain(String domain) {\n         this.domain = domain;\n         return this;\n      }\n\n      public Builder projectTeam(ProjectTeam projectTeam) {\n         this.projectTeam = projectTeam;\n         return this;\n      }\n\n      public ObjectAccessControls build() {\n         return ObjectAccessControls\n               .create(id, bucket, object, generation, entity, entityId, role, email, domain, projectTeam);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/domain/Owner.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.domain;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class Owner {\n   public abstract String entity();\n\n   @Nullable public abstract String entityId();\n\n   @SerializedNames({\"entity\", \"entityId\"})\n   public static Owner create(String entity, String entityId) {\n      return new AutoValue_Owner(entity, entityId);\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/domain/ProjectTeam.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.domain;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n/**\n * The bucket's logging configuration, which defines the destination bucket and optional name prefix for the current\n * bucket's logs.\n */\n@AutoValue\npublic abstract class ProjectTeam {\n\n   public enum Team {\n      OWNERS, EDITORS, VIEWERS;\n\n      public String value() {\n         return name().toLowerCase();\n      }\n\n      @Override\n      public String toString() {\n         return value();\n      }\n\n      public static Team fromValue(String team) {\n         return valueOf(team.toUpperCase());\n      }\n   }\n\n   public abstract String projectNumber();\n\n   public abstract Team team();\n\n   @SerializedNames({ \"projectNumber\", \"team\" })\n   public static ProjectTeam create(String projectNumber, Team team) {\n      return new AutoValue_ProjectTeam(projectNumber, team);\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/domain/ResumableUpload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.domain;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.auto.value.AutoValue;\n\n/**\n * Represents results of resumable upload response.\n */\n@AutoValue\npublic abstract class ResumableUpload {\n\n   public abstract int statusCode();\n\n   @Nullable public abstract String uploadId();\n\n   @Nullable public abstract String contentLength();\n\n   @Nullable public abstract Long rangeLowerValue();\n\n   @Nullable public abstract Long rangeUpperValue();\n\n   public static ResumableUpload create(int statusCode, String uploadId, String contentLength, Long rangeLowerValue,\n         Long rangeUpperValue) {\n      return new AutoValue_ResumableUpload(statusCode, uploadId, contentLength, rangeLowerValue, rangeUpperValue);\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/domain/RewriteResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.domain;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class RewriteResponse {\n   // TODO(broudy): should these be UnsignedLong?\n   public abstract long totalBytesRewritten();\n   public abstract long objectSize();\n   public abstract boolean done();\n   @Nullable public abstract String rewriteToken();\n   public abstract GoogleCloudStorageObject resource();\n\n   @SerializedNames({\"totalBytesRewritten\", \"objectSize\", \"done\", \"rewriteToken\", \"resource\"})\n   public static RewriteResponse create(long totalBytesRewritten, long objectSize,\n         boolean done, String rewriteToken, GoogleCloudStorageObject resource) {\n      return new AutoValue_RewriteResponse(totalBytesRewritten, objectSize, done, rewriteToken, resource);\n   }\n\n   RewriteResponse() {\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/domain/templates/BucketAccessControlsTemplate.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.domain.templates;\n\nimport org.jclouds.googlecloudstorage.domain.BucketAccessControls.Role;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class BucketAccessControlsTemplate {\n\n   public abstract String entity();\n\n   public abstract Role role();\n\n   public static BucketAccessControlsTemplate create(String entity, Role role) {\n      return new AutoValue_BucketAccessControlsTemplate(entity, role);\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/domain/templates/BucketTemplate.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.googlecloudstorage.domain.templates;\n\nimport java.util.List;\n\nimport org.jclouds.googlecloudstorage.domain.Bucket.Cors;\nimport org.jclouds.googlecloudstorage.domain.Bucket.LifeCycle;\nimport org.jclouds.googlecloudstorage.domain.Bucket.Logging;\nimport org.jclouds.googlecloudstorage.domain.Bucket.Versioning;\nimport org.jclouds.googlecloudstorage.domain.Bucket.Website;\nimport org.jclouds.googlecloudstorage.domain.BucketAccessControls;\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.Location;\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.StorageClass;\nimport org.jclouds.googlecloudstorage.domain.ObjectAccessControls;\nimport org.jclouds.googlecloudstorage.domain.Owner;\n\nimport com.google.common.collect.Lists;\n\npublic class BucketTemplate {\n\n   private String name;\n   private Long projectNumber;\n   private List<BucketAccessControls> acl = Lists.newArrayList();\n   private List<ObjectAccessControls> defaultObjectAccessControls = Lists.newArrayList();\n   private Owner owner;\n   private Location location;\n   private Website website;\n   private Logging logging;\n   private Versioning versioning;\n   private List<Cors> cors = Lists.newArrayList();\n   private LifeCycle lifeCycle;\n   private StorageClass storageClass;\n\n   public BucketTemplate name(String name) {\n      this.name = name;\n      return this;\n   }\n\n   public BucketTemplate projectNumber(Long projectNumber) {\n      this.projectNumber = projectNumber;\n      return this;\n   }\n\n   public BucketTemplate owner(Owner owner) {\n      this.owner = owner;\n      return this;\n   }\n\n   public BucketTemplate location(Location location) {\n      this.location = location;\n      return this;\n   }\n\n   public BucketTemplate website(Website website) {\n      this.website = website;\n      return this;\n   }\n\n   public BucketTemplate logging(Logging logging) {\n      this.logging = logging;\n      return this;\n   }\n\n   public BucketTemplate versioning(Versioning versioning) {\n      this.versioning = versioning;\n      return this;\n   }\n\n   public BucketTemplate lifeCycle(LifeCycle lifeCycle) {\n      this.lifeCycle = lifeCycle;\n      return this;\n   }\n\n   public BucketTemplate storageClass(StorageClass storageClass) {\n      this.storageClass = storageClass;\n      return this;\n   }\n\n   public BucketTemplate addAcl(BucketAccessControls bucketAccessControls) {\n      this.acl.add(bucketAccessControls);\n      return this;\n   }\n\n   public BucketTemplate acl(List<BucketAccessControls> acl) {\n      this.acl.addAll(acl);\n      return this;\n   }\n\n   public BucketTemplate addDefaultObjectAccessControls(ObjectAccessControls oac) {\n      this.defaultObjectAccessControls.add(oac);\n      return this;\n   }\n\n   public BucketTemplate defaultObjectAccessControls(List<ObjectAccessControls> defaultObjectAcl) {\n      this.defaultObjectAccessControls.addAll(defaultObjectAcl);\n      return this;\n   }\n\n   public BucketTemplate addCORS(Cors cors) {\n      this.cors.add(cors);\n      return this;\n   }\n\n   public BucketTemplate cors(List<Cors> cors) {\n      this.cors.addAll(cors);\n      return this;\n   }\n\n   public Long projectNumber() {\n      return projectNumber;\n   }\n\n   public String name() {\n      return name;\n   }\n\n   public List<BucketAccessControls> acl() {\n      return acl;\n   }\n\n   public List<ObjectAccessControls> defaultObjectAccessControls() {\n      return defaultObjectAccessControls;\n   }\n\n   public Owner owner() {\n      return owner;\n   }\n\n   public Location location() {\n      return location;\n   }\n\n   public Website website() {\n      return website;\n   }\n\n   public Logging logging() {\n      return logging;\n   }\n\n   public Versioning versioning() {\n      return versioning;\n   }\n\n   public List<Cors> cors() {\n      return cors;\n   }\n\n   public LifeCycle lifeCycle() {\n      return lifeCycle;\n   }\n\n   public StorageClass storageClass() {\n      return storageClass;\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/domain/templates/ComposeObjectTemplate.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.domain.templates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.List;\n\nimport org.jclouds.googlecloudstorage.domain.GoogleCloudStorageObject;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\n\n@AutoValue\npublic abstract class ComposeObjectTemplate {\n\n   @AutoValue\n   public abstract static class SourceObject {\n\n      @AutoValue\n      public abstract static class ObjectPreconditions {\n         public abstract long ifGenerationMatch();\n\n         @SerializedNames({\"ifGenerationMatch\"})\n         public static ObjectPreconditions create(long ifGenerationMatch){\n            return new AutoValue_ComposeObjectTemplate_SourceObject_ObjectPreconditions(ifGenerationMatch);\n         }\n\n         ObjectPreconditions(){\n         }\n      }\n\n      public abstract String name();\n      @Nullable public abstract Long generation();\n      @Nullable public abstract ObjectPreconditions objectPreconditions();\n\n      public static SourceObject nameOnly(String name){\n         return create(name, null, null);\n      }\n\n      public static SourceObject createWithPrecondition(String name, Long generation, Long objectPreconditions){\n         return create(name, generation, ObjectPreconditions.create(objectPreconditions));\n      }\n\n      @SerializedNames({ \"name\", \"generation\", \"objectPreconditions\"})\n      public static SourceObject create(String name, @Nullable Long generation,\n            @Nullable ObjectPreconditions objectPreconditions) {\n         return new AutoValue_ComposeObjectTemplate_SourceObject(name, generation, objectPreconditions);\n      }\n\n      SourceObject(){\n      }\n   }\n\n   public abstract List<SourceObject> sourceObjects();\n   public abstract ObjectTemplate destination();\n\n   @SerializedNames({\"sourceObjects\", \"destination\"})\n   public static ComposeObjectTemplate create(List<SourceObject> sourceObjects, ObjectTemplate destination) {\n      return new AutoValue_ComposeObjectTemplate(sourceObjects, destination);\n   }\n\n   public static Builder builder(){\n      return new Builder();\n   }\n\n   ComposeObjectTemplate() {\n   }\n\n   public static class Builder {\n      private ImmutableList<SourceObject> sourceObjects;\n      private ObjectTemplate destination;\n\n      Builder() {\n      }\n\n      public Builder fromGoogleCloudStorageObject(Collection<GoogleCloudStorageObject> objects) {\n         ImmutableList.Builder<SourceObject> sourceObjects = new ImmutableList.Builder<ComposeObjectTemplate.SourceObject>();\n         for (GoogleCloudStorageObject obj : objects) {\n            sourceObjects.add(SourceObject.createWithPrecondition(obj.name(), obj.generation(), obj.generation()));\n         }\n         this.sourceObjects = sourceObjects.build();\n         return this;\n      }\n\n      public Builder fromNames(List<String> SourceObjectNames) {\n         ArrayList<SourceObject> sourceObjects = new ArrayList<SourceObject>();\n         for (String name : SourceObjectNames) {\n            sourceObjects.add(SourceObject.nameOnly(name));\n         }\n         this.sourceObjects = ImmutableList.copyOf(sourceObjects);\n         return this;\n      }\n\n      public Builder destination(ObjectTemplate destination) {\n         checkNotNull(destination, \"destination\");\n         this.destination = destination;\n         return this;\n      }\n\n      public ComposeObjectTemplate build() {\n         return ComposeObjectTemplate.create(sourceObjects, destination);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/domain/templates/ObjectAccessControlsTemplate.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.domain.templates;\n\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.ObjectRole;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class ObjectAccessControlsTemplate {\n\n   public abstract String entity();\n\n   public abstract ObjectRole role();\n\n   public static ObjectAccessControlsTemplate create(String entity, ObjectRole role) {\n      return new AutoValue_ObjectAccessControlsTemplate(entity, role);\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/domain/templates/ObjectTemplate.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.googlecloudstorage.domain.templates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.StorageClass;\nimport org.jclouds.googlecloudstorage.domain.ObjectAccessControls;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.collect.Lists;\nimport com.google.common.collect.Maps;\nimport com.google.common.net.MediaType;\n\npublic class ObjectTemplate {\n\n   private String name;\n   private Long size;\n   private String cacheControl;\n   private String contentDisposition;\n   private String contentEncoding;\n   private String contentLanguage;\n   private String contentType;\n   private String crc32c;\n   private String md5Hash;\n   private StorageClass storageClass;\n   private Map<String, String> metadata;\n   private List<ObjectAccessControls> acl;\n\n   public ObjectTemplate name(String name) {\n      this.name = name;\n      return this;\n   }\n\n   public ObjectTemplate size(Long size) {\n      this.size = size;\n      return this;\n   }\n\n   public ObjectTemplate cacheControl(String cacheControl) {\n      this.cacheControl = cacheControl;\n      return this;\n   }\n\n   public ObjectTemplate contentDisposition(String contentDisposition) {\n      this.contentDisposition = contentDisposition;\n      return this;\n   }\n\n   public ObjectTemplate contentEncoding(String contentEncoding) {\n      this.contentEncoding = contentEncoding;\n      return this;\n   }\n\n   public ObjectTemplate contentLanguage(String contentLanguage) {\n      this.contentLanguage = contentLanguage;\n      return this;\n   }\n\n   public ObjectTemplate contentType(MediaType contentType) {\n      this.contentType = contentType.toString();\n      return this;\n   }\n\n   public ObjectTemplate contentType(String contentType) {\n      this.contentType = contentType;\n      return this;\n   }\n\n   public ObjectTemplate customMetadata(Map<String, String> metadata) {\n      if (this.metadata == null) {\n         this.metadata = Maps.newLinkedHashMap();\n      }\n      this.metadata.putAll(metadata);\n      return this;\n   }\n\n   public ObjectTemplate customMetadata(String key, String value) {\n      if (this.metadata == null) {\n         this.metadata = Maps.newLinkedHashMap();\n      }\n      this.metadata.put(key, value);\n      return this;\n   }\n\n   public ObjectTemplate crc32c(String crc32c) {\n      this.crc32c = crc32c;\n      return this;\n   }\n\n   public ObjectTemplate md5Hash(String md5Hash) {\n      this.md5Hash = md5Hash;\n      return this;\n   }\n\n   public ObjectTemplate storageClass(StorageClass storageClass) {\n      this.storageClass = checkNotNull(storageClass);\n      return this;\n   }\n\n   public ObjectTemplate addAcl(ObjectAccessControls acl) {\n      if (this.acl == null) {\n         this.acl = Lists.newArrayList();\n      }\n      this.acl.add(acl);\n      return this;\n   }\n\n   public ObjectTemplate acl(List<ObjectAccessControls> acl) {\n      if (this.acl == null) {\n         this.acl = Lists.newArrayList();\n      }\n      this.acl.addAll(acl);\n      return this;\n   }\n\n   public String cacheControl() {\n      return cacheControl;\n   }\n\n   public String contentDisposition() {\n      return contentDisposition;\n   }\n\n   public String contentEncoding() {\n      return contentEncoding;\n   }\n\n   public String contentLanguage() {\n      return contentLanguage;\n   }\n\n   public String contentType() {\n      return contentType;\n   }\n\n   public Map<String, String> metadata() {\n      return metadata;\n   }\n\n   public String crc32c() {\n      return crc32c;\n   }\n\n   public String md5Hash() {\n      return md5Hash;\n   }\n\n   public StorageClass storageClass() {\n      return storageClass;\n   }\n\n   public String name() {\n      return name;\n   }\n\n   public Long size() {\n      return size;\n   }\n\n   public List<ObjectAccessControls> acl() {\n      return acl;\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this)\n         .add(\"name\", name)\n         .add(\"size\", size)\n         .add(\"cacheControl\", cacheControl)\n         .add(\"contentDisposition\", contentDisposition)\n         .add(\"contentEncoding\", contentEncoding)\n         .add(\"contentLanguage\", contentLanguage)\n         .add(\"contentType\", contentType)\n         .add(\"crc32c\", crc32c)\n         .add(\"md5Hash\", md5Hash)\n         .add(\"storageClass\", storageClass)\n         .add(\"metadata\", metadata)\n         .add(\"acl\", acl)\n         .toString();\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/features/BucketAccessControlsApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.util.List;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.googlecloudstorage.domain.BucketAccessControls;\nimport org.jclouds.googlecloudstorage.domain.templates.BucketAccessControlsTemplate;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.Headers;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.SkipEncoding;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\n/**\n * Provides access to BucketAccessControl entities via their REST API.\n *\n * @see <a href = \" https://developers.google.com/storage/docs/json_api/v1/bucketAccessControls \"/>\n */\n\n@SkipEncoding({ '/', '=' })\n@RequestFilters(OAuthFilter.class)\n@Consumes(APPLICATION_JSON)\npublic interface BucketAccessControlsApi {\n\n   /**\n    * Returns the ACL entry for the specified entity on the specified bucket.\n    *\n    * @param bucketName\n    *           Name of the bucket which ACL is related\n    * @param entity\n    *           The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId,\n    *           group-emailAddress, allUsers, or allAuthenticatedUsers.\n    *\n    * @return a BucketAccessControls resource\n    */\n\n   @Named(\"BucketAccessControls:get\")\n   @GET\n   @Path(\"/b/{bucket}/acl/{entity}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   BucketAccessControls getBucketAccessControls(@PathParam(\"bucket\") String bucketName,\n            @PathParam(\"entity\") String entity);\n\n   /**\n    * Creates a new ACL entry on the specified bucket.\n    *\n    * @param bucketName\n    *           Name of the bucket of which ACL to be created\n    *\n    * @param template\n    *           In the request body,supply a {@link BucketAccessControlsTemplate} resource with role and entity\n    *\n    * @return If successful, this method returns a BucketAccessControls resource in the response body\n    */\n\n   @Named(\"BucketAccessControls:insert\")\n   @POST\n   @Path(\"/b/{bucket}/acl\")\n   BucketAccessControls createBucketAccessControls(@PathParam(\"bucket\") String bucketName,\n            @BinderParam(BindToJsonPayload.class) BucketAccessControlsTemplate template);\n\n   /**\n    * Permanently deletes the ACL entry for the specified entity on the specified bucket.\n    *\n    * @param bucketName\n    *           Name of the bucket of that ACL is related\n    * @return If successful, this method returns an empty response body.\n    */\n\n   @Named(\"BucketAccessControls:delete\")\n   @DELETE\n   @Path(\"/b/{bucket}/acl/{entity}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   HttpResponse deleteBucketAccessControls(@PathParam(\"bucket\") String bucketName, @PathParam(\"entity\") String entity);\n\n   /**\n    * Retrieves all ACL entries on a specified bucket\n    *\n    * @param bucketName\n    *           Name of the bucket which ACL is related\n    *\n    * @return ListBucketAccessControls resource\n    */\n\n   @Named(\"BucketAccessControls:list\")\n   @GET\n   @Produces(APPLICATION_JSON)\n   @Path(\"/b/{bucket}/acl\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   @SelectJson(\"items\")\n   List<BucketAccessControls> listBucketAccessControls(@PathParam(\"bucket\") String bucketName);\n\n   /**\n    * Updates an ACL entry on the specified bucket\n    *\n    * @param bucketName\n    *           Name of the bucket which ACL to be created\n    * @param entity\n    *           The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId,\n    *           group-emailAddress, allUsers, or allAuthenticatedUsers. In the request body, supply a\n    *           {@link BucketAccessControlsTemplate} resource with role\n    *\n    * @return If successful, this method returns a {@link BucketAccessControlsTemplate} resource in the response body\n    */\n   @Named(\"BucketAccessControls:update\")\n   @PUT\n   @Produces(APPLICATION_JSON)\n   @Path(\"/b/{bucket}/acl/{entity}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   BucketAccessControls updateBucketAccessControls(@PathParam(\"bucket\") String bucketName,\n            @PathParam(\"entity\") String entity,\n            @BinderParam(BindToJsonPayload.class) BucketAccessControlsTemplate template);\n\n   /**\n    * Updates an ACL entry on the specified bucket.\n    *\n    * @param bucketName\n    *           Name of the bucket which ACL to be created\n    * @param entity\n    *           The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId,\n    *           group-emailAddress, allUsers, or allAuthenticatedUsers\n    *\n    * @param template\n    *           In the request body, supply a {@link BucketAccessControlsTemplate} resource with role\n    *\n    * @return If successful, this method returns a BucketAccessControls resource in the response body\n    */\n   @Named(\"BucketAccessControls:patch\")\n   @POST\n   @Headers(keys = \"X-HTTP-Method-Override\", values = \"PATCH\")\n   @Produces(APPLICATION_JSON)\n   @Path(\"/b/{bucket}/acl/{entity}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   BucketAccessControls patchBucketAccessControls(@PathParam(\"bucket\") String bucketName,\n            @PathParam(\"entity\") String entity,\n            @BinderParam(BindToJsonPayload.class) BucketAccessControlsTemplate template);\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/features/BucketApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.QueryParam;\n\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.blobstore.BlobStoreFallbacks.NullOnKeyAlreadyExists;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecloudstorage.GoogleCloudStorageFallbacks.NullOnBucketAlreadyExists;\nimport org.jclouds.googlecloudstorage.domain.Bucket;\nimport org.jclouds.googlecloudstorage.domain.templates.BucketTemplate;\nimport org.jclouds.googlecloudstorage.options.DeleteBucketOptions;\nimport org.jclouds.googlecloudstorage.options.GetBucketOptions;\nimport org.jclouds.googlecloudstorage.options.InsertBucketOptions;\nimport org.jclouds.googlecloudstorage.options.ListOptions;\nimport org.jclouds.googlecloudstorage.options.UpdateBucketOptions;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.Headers;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SkipEncoding;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\n/**\n * Provides access to Bucket entities via their REST API.\n *\n * @see <a href = \"https://developers.google.com/storage/docs/json_api/v1/buckets\"/>\n */\n\n@SkipEncoding({ '/', '=' })\n@RequestFilters(OAuthFilter.class)\n@Consumes(APPLICATION_JSON)\npublic interface BucketApi {\n\n   /**\n    * Check the existence of a bucket\n    *\n    * @param bucketName\n    *           Name of the bucket\n    *\n    * @return a {@link Bucket} true if bucket exist\n    */\n   @Named(\"Bucket:get\")\n   @GET\n   @Path(\"/b/{bucket}\")\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean bucketExist(@PathParam(\"bucket\") String bucketName);\n\n   /**\n    * Returns metadata for the specified bucket.\n    *\n    * @param bucketName\n    *           Name of the bucket\n    *\n    * @return a {@link Bucket} resource\n    */\n   @Named(\"Bucket:get\")\n   @GET\n   @Produces(APPLICATION_JSON)\n   @Path(\"/b/{bucket}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Bucket getBucket(@PathParam(\"bucket\") String bucketName);\n\n   /**\n    * Returns metadata for the specified bucket\n    *\n    * @param bucketName\n    *           Name of the bucket\n    * @param options\n    *           Supply {@link GetBucketOptions} with optional query parameters\n    *\n    * @return a {@link Bucket} resource\n    */\n   @Named(\"Bucket:get\")\n   @GET\n   @Produces(APPLICATION_JSON)\n   @Path(\"/b/{bucket}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Bucket getBucket(@PathParam(\"bucket\") String bucketName, GetBucketOptions options);\n\n   /**\n    * Creates a new bucket\n    *\n    * @param projectId\n    *           A valid API project identifier\n    * @param bucketTemplate\n    *           supply a {@link BucketTemplate} resource\n    *\n    * @return If successful, this method returns a {@link Bucket} resource.\n    */\n   @Named(\"Bucket:insert\")\n   @POST\n   @Path(\"/b\")\n   @Fallback(NullOnBucketAlreadyExists.class)\n   Bucket createBucket(@QueryParam(\"project\") String projectId, @BinderParam(BindToJsonPayload.class) BucketTemplate bucketTemplate);\n\n   /**\n    * Creates a new Bucket\n    *\n    * @param projectId\n    *           A valid API project identifier\n    *\n    * @param bucketTemplate\n    *           Supply a {@link BucketTemplate} resource\n    * @param options\n    *           Supply {@link InsertBucketOptions} with optional query parameters\n    *\n    * @return If successful, this method returns a {@link Bucket} resource.\n    */\n   @Named(\"Bucket:insert\")\n   @POST\n   @Path(\"/b\")\n   @Fallback(NullOnKeyAlreadyExists.class)\n   Bucket createBucket(@QueryParam(\"project\") String projectId,\n            @BinderParam(BindToJsonPayload.class) BucketTemplate bucketTemplate, InsertBucketOptions options);\n\n   /**\n    * Permanently deletes an empty Bucket.If bucket is not empty 409 error to indicate the conflict.  \n    *\n    * @param bucketName\n    *           Name of the bucket\n    */\n   @Named(\"Bucket:delete\")\n   @DELETE\n   @Path(\"/b/{bucket}\")\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean deleteBucket(@PathParam(\"bucket\") String bucketName);\n\n   /**\n    * Permanently deletes an empty Bucket.If bucket is not empty 409 error to indicate the conflict.\n    *\n    * @param bucketName\n    *           Name of the bucket\n    * @param options\n    *           Supply {@link DeleteBucketOptions} with optional query parameters\n    */\n   @Named(\"Bucket:delete\")\n   @DELETE\n   @Path(\"/b/{bucket}\")\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean deleteBucket(@PathParam(\"bucket\") String bucketName, DeleteBucketOptions options);\n\n   /**\n    * Retrieves a list of buckets for a given project\n    *\n    * @param projectId\n    *           A valid API project identifier\n    *\n    * @return a {@link ListPage<Bucket>}\n    */\n   @Named(\"Bucket:list\")\n   @GET\n   @Produces(APPLICATION_JSON)\n   @Path(\"/b\")\n   ListPage<Bucket> listBucket(@QueryParam(\"project\") String projectId);\n\n   /**\n    * Retrieves a list of buckets for a given project\n    *\n    * @param projectId\n    *           A valid API project identifier\n    * @param options\n    *           Supply {@link ListOptions} with optional query parameters\n    */\n   @Named(\"Bucket:list\")\n   @GET\n   @Produces(APPLICATION_JSON)\n   @Path(\"/b\")\n   ListPage<Bucket> listBucket(@QueryParam(\"project\") String projectId, ListOptions options);\n\n   /**\n    * Updates a bucket\n    *\n    * @param bucketName\n    *           Name of the bucket\n    * @param bucketTemplate\n    *           Supply a {@link BucketTemplate} resource with list of {@link BucketAccessControls}\n    *\n    * @return If successful, this method returns the updated {@link Bucket} resource.\n    */\n   @Named(\"Bucket:update\")\n   @PUT\n   @Produces(APPLICATION_JSON)\n   @Path(\"/b/{bucket}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   Bucket updateBucket(@PathParam(\"bucket\") String bucketName,\n            @BinderParam(BindToJsonPayload.class) BucketTemplate bucketTemplate);\n\n   /**\n    * Updates a bucket\n    *\n    * @param bucketName\n    *           Name of the bucket\n    * @param bucketTemplate\n    *           Supply a {@link BucketTemplate} resource with list of {@link BucketAccessControls}\n    * @param options\n    *           Supply {@link UpdateBucketOptions} with optional query parameters\n    *\n    * @return If successful,this method returns the updated {@link Bucket} resource.\n    */\n   @Named(\"Bucket:update\")\n   @PUT\n   @Produces(APPLICATION_JSON)\n   @Path(\"/b/{bucket}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   Bucket updateBucket(@PathParam(\"bucket\") String bucketName,\n            @BinderParam(BindToJsonPayload.class) BucketTemplate bucketTemplate, UpdateBucketOptions options);\n\n   /**\n    * Updates a bucket supporting patch semantics.\n    *\n    *  @see <a href = \"https://developers.google.com/storage/docs/json_api/v1/how-tos/performance#patch\"/>\n    *\n    * @param bucketName\n    *           Name of the bucket\n    * @param bucketTemplate\n    *           Supply a {@link BucketTemplate} resource with list of {@link BucketAccessControls}\n    *\n    * @return If successful, this method returns the updated {@link Bucket} resource.\n    */\n   @Named(\"Bucket:patch\")\n   @POST\n   @Headers(keys = \"X-HTTP-Method-Override\", values = \"PATCH\")\n   @Produces(APPLICATION_JSON)\n   @Path(\"/b/{bucket}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   Bucket patchBucket(@PathParam(\"bucket\") String bucketName,\n            @BinderParam(BindToJsonPayload.class) BucketTemplate bucketTemplate);\n\n   /**\n    * Updates a bucket supporting patch semantics.\n    *\n    * @see <a href = \"https://developers.google.com/storage/docs/json_api/v1/how-tos/performance#patch\"/>\n    *\n    * @param bucketName\n    *           Name of the bucket\n    * @param bucketTemplate\n    *           Supply a {@link BucketTemplate} resource with list of {@link BucketAccessControls}\n    * @param options\n    *           Supply {@link UpdateBucketOptions} with optional query parameters\n    *\n    * @return If successful, this method returns the updated {@link Bucket} resource.\n    */\n   @Named(\"Bucket:patch\")\n   @POST\n   @Headers(keys = \"X-HTTP-Method-Override\", values = \"PATCH\")\n   @Produces(APPLICATION_JSON)\n   @Path(\"/b/{bucket}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   Bucket patchBucket(@PathParam(\"bucket\") String bucketName,\n            @BinderParam(BindToJsonPayload.class) BucketTemplate bucketTemplate, UpdateBucketOptions options);\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/features/DefaultObjectAccessControlsApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.util.List;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.QueryParam;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.ObjectRole;\nimport org.jclouds.googlecloudstorage.domain.ObjectAccessControls;\nimport org.jclouds.googlecloudstorage.domain.templates.ObjectAccessControlsTemplate;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.Headers;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.annotations.SkipEncoding;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\n/**\n * Provides access to DefaultObjectAccessControl entities via their REST API.\n *\n * @see <a href = \" https://developers.google.com/storage/docs/json_api/v1/defaultObjectAccessControls\"/>\n */\n\n@SkipEncoding({ '/', '=' })\n@RequestFilters(OAuthFilter.class)\n@Consumes(APPLICATION_JSON)\npublic interface DefaultObjectAccessControlsApi {\n\n   /**\n    * Returns the ACL entry for the specified entity on the specified object.\n    *\n    * @param bucketName\n    *           Name of the bucket which contains the object\n    * @param entity\n    *           The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId,\n    *           group-emailAddress, allUsers, or allAuthenticatedUsers\n    *\n    * @return an DefaultObjectAccessControls resource\n    */\n   @Named(\"DefaultObjectAccessControls:get\")\n   @GET\n   @Path(\"/b/{bucket}/defaultObjectAcl/{entity}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   ObjectAccessControls getDefaultObjectAccessControls(@PathParam(\"bucket\") String bucketName,\n         @PathParam(\"entity\") String entity);\n\n   /**\n    * Creates a new ACL entry for specified object\n    *\n    * @param bucketName\n    *           Name of the bucket of that ACL to be created In the request body, supply a DefaultObjectAccessControls\n    *           resource with the following properties\n    *\n    * @return If successful, this method returns a DefaultObjectAccessControls resource\n    */\n   @Named(\"DefaultObjectAccessControls:insert\")\n   @POST\n   @Produces(APPLICATION_JSON)\n   @Path(\"/b/{bucket}/defaultObjectAcl\")\n   ObjectAccessControls createDefaultObjectAccessControls(@PathParam(\"bucket\") String bucketName,\n            @BinderParam(BindToJsonPayload.class) ObjectAccessControlsTemplate template);\n\n   /**\n    * Permanently deletes the DefaultObjectAcessControl entry for the specified entity on the specified bucket.\n    *\n    * @param bucketName\n    *           Name of the bucket which contains the object\n    * @param entity\n    *           The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId,\n    *           group-emailAddress, allUsers, or allAuthenticatedUsers\n    *\n    * @return If successful, this method returns an empty response body\n    */\n   @Named(\"DefaultObjectAccessControls:delete\")\n   @DELETE\n   @Path(\"/b/{bucket}/defaultObjectAcl/{entity}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   HttpResponse deleteDefaultObjectAccessControls(@PathParam(\"bucket\") String bucketName,\n            @PathParam(\"entity\") String entity);\n\n   /**\n    * Retrieves ACL entries on a specified object\n    *\n    * @param bucketName\n    *           Name of the bucket which contains the object\n    *\n    * @return ListObjectAccessControls resource\n    *\n    */\n   @Named(\"DefaultObjectAccessControls:list\")\n   @GET\n   @Produces(APPLICATION_JSON)\n   @Path(\"/b/{bucket}/defaultObjectAcl\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   @SelectJson(\"items\")\n   List<ObjectAccessControls> listDefaultObjectAccessControls(@PathParam(\"bucket\") String bucketName);\n\n   /**\n    * Retrieves ACL entries on a specified object\n    *\n    * @param bucketName\n    *           Name of the bucket which contains the object\n    *\n    * @return DefaultObjectAccessControls resource\n    *\n    */\n   @Named(\"DefaultObjectAccessControls:update\")\n   @PUT\n   @Produces(APPLICATION_JSON)\n   @Path(\"/b/{bucket}/defaultObjectAcl/{entity}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   ObjectAccessControls updateDefaultObjectAccessControls(@PathParam(\"bucket\") String bucketName,\n            @PathParam(\"entity\") String entity,\n            @BinderParam(BindToJsonPayload.class) ObjectAccessControls payload);\n\n   /**\n    * Retrieves ACL entries on a specified object\n    *\n    * @param bucketName\n    *           Name of the bucket which contains the object\n    */\n   @Named(\"DefaultObjectAccessControls:update\")\n   @PUT\n   @Produces(APPLICATION_JSON)\n   @Path(\"/b/{bucket}/defaultObjectAcl/{entity}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   ObjectAccessControls updateDefaultObjectAccessControls(@PathParam(\"bucket\") String bucketName,\n            @PathParam(\"entity\") String entity,\n            @BinderParam(BindToJsonPayload.class) ObjectAccessControls payload,\n            @QueryParam(\"role\") ObjectRole role);\n\n   /**\n    * Retrieves ACL entries on a specified object\n    *\n    * @param bucketName\n    *           Name of the bucket which contains the object\n    */\n   @Named(\"DefaultObjectAccessControls:patch\")\n   @POST\n   @Headers(keys = \"X-HTTP-Method-Override\", values = \"PATCH\")\n   @Produces(APPLICATION_JSON)\n   @Path(\"/b/{bucket}/defaultObjectAcl/{entity}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   ObjectAccessControls patchDefaultObjectAccessControls(@PathParam(\"bucket\") String bucketName,\n            @PathParam(\"entity\") String entity,\n            @BinderParam(BindToJsonPayload.class) ObjectAccessControls payload);\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/features/ObjectAccessControlsApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.util.List;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.Encoded;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.QueryParam;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.googlecloudstorage.domain.ObjectAccessControls;\nimport org.jclouds.googlecloudstorage.domain.templates.ObjectAccessControlsTemplate;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.Headers;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SelectJson;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\n/**\n * Provides access to ObjectAccessControl entities via their REST API.\n *\n * @see <a href = \" https://developers.google.com/storage/docs/json_api/v1/objectAccessControls \"/>\n */\n@RequestFilters(OAuthFilter.class)\n@Consumes(APPLICATION_JSON)\npublic interface ObjectAccessControlsApi {\n\n   /**\n    * Returns the acl entry for the specified entity on the specified object.\n    *\n    * @param bucketName\n    *           Name of the bucket which contains the object\n    * @param objectName\n    *           Name of the bucket of that acl is related\n    * @param entity\n    *           The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId,\n    *           group-emailAddress, allUsers, or allAuthenticatedUsers\n    *\n    * @return an {@link ObjectAccessControls }\n    */\n\n   @Named(\"ObjectAccessControls:get\")\n   @GET\n   @Path(\"/b/{bucket}/o/{object}/acl/{entity}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   ObjectAccessControls getObjectAccessControls(@PathParam(\"bucket\") String bucketName,\n            @PathParam(\"object\") @Encoded String objectName, @PathParam(\"entity\") String entity);\n\n   /**\n    * Returns the acl entry for the specified entity on the specified object.\n    *\n    * @param bucketName\n    *           Name of the bucket which contains the object\n    * @param objectName\n    *           Name of the object of that acl is related\n    * @param entity\n    *           The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId,\n    *           group-emailAddress, allUsers, or allAuthenticatedUsers\n    * @param generation\n    *           If present, selects a specific revision of this object\n    *\n    * @return an {@link ObjectAccessControls }\n    */\n   @Named(\"ObjectAccessControls:get\")\n   @GET\n   @Path(\"/b/{bucket}/o/{object}/acl/{entity}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   ObjectAccessControls getObjectAccessControls(@PathParam(\"bucket\") String bucketName,\n            @PathParam(\"object\") @Encoded String objectName, @PathParam(\"entity\") String entity,\n            @QueryParam(\"generation\") Long generation);\n\n   /**\n    * Creates a new acl entry for specified object\n    *\n    * @param bucketName\n    *           Name of the bucket of that acl to be created In the request body, supply a ObjectAccessControls resource\n    *           with the following properties\n    * @param objectName\n    *           Name of the bucket of that acl is related\n    *\n    * @return an {@link ObjectAccessControls }\n    */\n   @Named(\"ObjectAccessControls:insert\")\n   @POST\n   @Produces(APPLICATION_JSON)\n   @Path(\"/b/{bucket}/o/{object}/acl\")\n   ObjectAccessControls createObjectAccessControls(@PathParam(\"bucket\") String bucketName,\n            @PathParam(\"object\") @Encoded String objectName,\n            @BinderParam(BindToJsonPayload.class) ObjectAccessControlsTemplate template);\n\n   /**\n    * Creates a new acl entry for specified object\n    *\n    * @param bucketName\n    *           Name of the bucket of that acl to be created In the request body, supply a ObjectAccessControls resource\n    *           with the following properties\n    * @param objectName\n    *           Name of the bucket of that acl is related\n    * @param generation\n    *           If present, selects a specific revision of this object\n    *\n    * @return an {@link ObjectAccessControls }\n    */\n   @Named(\"ObjectAccessControls:insert\")\n   @POST\n   @Produces(APPLICATION_JSON)\n   @Path(\"/b/{bucket}/o/{object}/acl\")\n   ObjectAccessControls createObjectAccessControls(@PathParam(\"bucket\") String bucketName,\n            @PathParam(\"object\") @Encoded String objectName,\n            @BinderParam(BindToJsonPayload.class) ObjectAccessControlsTemplate template,\n            @QueryParam(\"generation\") Long generation);\n\n   /**\n    * Permanently deletes the acl entry for the specified entity on the specified bucket.\n    *\n    * @param bucketName\n    *           Name of the bucket which contains the object\n    * @param objectName\n    *           Name of the bucket of which acl is related\n    * @param entity\n    *           The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId,\n    *           group-emailAddress, allUsers, or allAuthenticatedUsers\n    */\n   @Named(\"ObjectAccessControls:delete\")\n   @DELETE\n   @Path(\"/b/{bucket}/o/{object}/acl/{entity}\")\n   void deleteObjectAccessControls(@PathParam(\"bucket\") String bucketName,\n         @PathParam(\"object\") @Encoded String objectName, @PathParam(\"entity\") String entity);\n\n   /**\n    * Permanently deletes the acl entry for the specified entity on the specified bucket.\n    *\n    * @param bucketName\n    *           Name of the bucket which contains the object\n    * @param objectName\n    *           Name of the bucket of that acl is related\n    * @param generation\n    *           If present, selects a specific revision of this object\n    * @param entity\n    *           The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId,\n    *           group-emailAddress, allUsers, or allAuthenticatedUsers\n    */\n   @Named(\"ObjectAccessControls:delete\")\n   @DELETE\n   @Path(\"/b/{bucket}/o/{object}/acl/{entity}\")\n   void deleteObjectAccessControls(@PathParam(\"bucket\") String bucketName,\n         @PathParam(\"object\") @Encoded String objectName, @PathParam(\"entity\") String entity,\n         @QueryParam(\"generation\") Long generation);\n\n   /**\n    * Retrieves acl entries on a specified object\n    *\n    * @param bucketName\n    *           Name of the bucket which contains the object\n    * @param objectName\n    *           Name of the bucket of that acl is related\n    */\n   @Named(\"ObjectAccessControls:list\")\n   @GET\n   @Produces(APPLICATION_JSON)\n   @Path(\"/b/{bucket}/o/{object}/acl\")\n   @SelectJson(\"items\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   List<ObjectAccessControls> listObjectAccessControls(@PathParam(\"bucket\") String bucketName,\n            @PathParam(\"object\") @Encoded String objectName);\n\n   /**\n    * Retrieves acl entries on a specified object\n    *\n    * @param bucketName\n    *           Name of the bucket which contains the object\n    * @param objectName\n    *           Name of the bucket of that acl is related\n    * @param generation\n    *           If present, selects a specific revision of this object\n    *\n    */\n   @Named(\"ObjectAccessControls:list\")\n   @GET\n   @Produces(APPLICATION_JSON)\n   @Path(\"/b/{bucket}/o/{object}/acl\")\n   @SelectJson(\"items\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   List<ObjectAccessControls> listObjectAccessControls(@PathParam(\"bucket\") String bucketName,\n            @PathParam(\"object\") @Encoded String objectName, @QueryParam(\"generation\") Long generation);\n\n   /**\n    * Updates an acl entry on the specified object\n    *\n    * @param bucketName\n    *           Name of the bucket of which contains the object\n    * @param objectName\n    *           Name of the object which acl is related\n    * @param entity\n    *           The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId,\n    *           group-emailAddress, allUsers, or allAuthenticatedUsers.\n    * @param template\n    *           Supply an {@link ObjectAccessControlsTemplate}\n    *\n    * @return an {@link ObjectAccessControls }\n    */\n\n   @Named(\"ObjectAccessControls:update\")\n   @PUT\n   @Produces(APPLICATION_JSON)\n   @Path(\"/b/{bucket}/o/{object}/acl/{entity}\")\n   ObjectAccessControls updateObjectAccessControls(@PathParam(\"bucket\") String bucketName,\n            @PathParam(\"object\") @Encoded String objectName, @PathParam(\"entity\") String entity,\n            @BinderParam(BindToJsonPayload.class) ObjectAccessControlsTemplate template);\n\n   /**\n    * Updates an acl entry on the specified object\n    *\n    * @param bucketName\n    *           Name of the bucket of which contains the object\n    * @param objectName\n    *           Name of the object which acl is related *\n    * @param entity\n    *           The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId,\n    *           group-emailAddress, allUsers, or allAuthenticatedUsers\n    * @param template\n    *           Supply an {@link ObjectAccessControlsTemplate}\n    * @param generation\n    *           If present, selects a specific revision of this object\n    *\n    * @return {@link ObjectAccessControls }\n    */\n   @Named(\"ObjectAccessControls:update\")\n   @PUT\n   @Produces(APPLICATION_JSON)\n   @Path(\"/b/{bucket}/o/{object}/acl/{entity}\")\n   ObjectAccessControls updateObjectAccessControls(@PathParam(\"bucket\") String bucketName,\n            @PathParam(\"object\") @Encoded String objectName, @PathParam(\"entity\") String entity,\n            @BinderParam(BindToJsonPayload.class) ObjectAccessControlsTemplate template,\n            @QueryParam(\"generation\") Long generation);\n\n   /**\n    * Updates an acl entry on the specified object\n    *\n    * @param bucketName\n    *           Name of the bucket of which contains the object\n    * @param objectName\n    *           Name of the object which acl is related\n    * @param template\n    *           Supply an {@link ObjectAccessControlsTemplate}\n    * @param entity\n    *           The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId,\n    *           group-emailAddress, allUsers, or allAuthenticatedUsers.\n    *\n    * @return an {@link ObjectAccessControls }\n    */\n   @Named(\"ObjectAccessControls:patch\")\n   @POST\n   @Headers(keys = \"X-HTTP-Method-Override\", values = \"PATCH\")\n   @Produces(APPLICATION_JSON)\n   @Path(\"/b/{bucket}/o/{object}/acl/{entity}\")\n   ObjectAccessControls patchObjectAccessControls(@PathParam(\"bucket\") String bucketName,\n            @PathParam(\"object\") @Encoded String objectName, @PathParam(\"entity\") String entity,\n            @BinderParam(BindToJsonPayload.class) ObjectAccessControlsTemplate template);\n\n   /**\n    * Updates an acl entry on the specified object\n    *\n    * @param bucketName\n    *           Name of the bucket of which contains the object\n    * @param objectName\n    *           Name of the object which acl is related\n    * @param entity\n    *           The entity holding the permission. Can be user-userId, user-emailAddress, group-groupId,\n    *           group-emailAddress, allUsers, or allAuthenticatedUsers\n    * @param template\n    *           Supply an {@link ObjectAccessControlsTemplate}\n    * @param generation\n    *           If present, selects a specific revision of this object\n    *\n    * @return {@link ObjectAccessControls }\n    */\n   @Named(\"ObjectAccessControls:patch\")\n   @POST\n   @Headers(keys = \"X-HTTP-Method-Override\", values = \"PATCH\")\n   @Produces(APPLICATION_JSON)\n   @Path(\"/b/{bucket}/o/{object}/acl/{entity}\")\n   ObjectAccessControls patchObjectAccessControls(@PathParam(\"bucket\") String bucketName,\n            @PathParam(\"object\") @Encoded String objectName, @PathParam(\"entity\") String entity,\n            @BinderParam(BindToJsonPayload.class) ObjectAccessControlsTemplate template,\n            @QueryParam(\"generation\") Long generation);\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/features/ObjectApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.Encoded;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.HeaderParam;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\n\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.googlecloudstorage.binders.MultipartUploadBinder;\nimport org.jclouds.googlecloudstorage.domain.GoogleCloudStorageObject;\nimport org.jclouds.googlecloudstorage.domain.ListPageWithPrefixes;\nimport org.jclouds.googlecloudstorage.domain.RewriteResponse;\nimport org.jclouds.googlecloudstorage.domain.templates.ComposeObjectTemplate;\nimport org.jclouds.googlecloudstorage.domain.templates.ObjectTemplate;\nimport org.jclouds.googlecloudstorage.options.ComposeObjectOptions;\nimport org.jclouds.googlecloudstorage.options.CopyObjectOptions;\nimport org.jclouds.googlecloudstorage.options.DeleteObjectOptions;\nimport org.jclouds.googlecloudstorage.options.GetObjectOptions;\nimport org.jclouds.googlecloudstorage.options.InsertObjectOptions;\nimport org.jclouds.googlecloudstorage.options.ListObjectOptions;\nimport org.jclouds.googlecloudstorage.options.RewriteObjectOptions;\nimport org.jclouds.googlecloudstorage.options.UpdateObjectOptions;\nimport org.jclouds.googlecloudstorage.parser.ParseToPayloadEnclosing;\nimport org.jclouds.http.options.HttpRequestOptions;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.PayloadEnclosing;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.Headers;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\n/**\n * Provides access to Object entities via their REST API.\n *\n * @see <a href=\"https://developers.google.com/storage/docs/json_api/v1/objects\"/>\n */\n@RequestFilters(OAuthFilter.class)\npublic interface ObjectApi {\n\n   /**\n    * Check the existence of an object\n    *\n    * @param bucketName\n    *           Name of the bucket in which the object resides\n    * @param objectName\n    *           Name of the object\n    *\n    * @return a {@link Object} true if object exists\n    */\n   @Named(\"Object:Exist\")\n   @GET\n   @Path(\"storage/v1/b/{bucket}/o/{object}\")\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean objectExists(@PathParam(\"bucket\") String bucketName, @PathParam(\"object\") @Encoded String objectName);\n\n   /**\n    * Retrieve an object metadata\n    *\n    * @param bucketName\n    *           Name of the bucket in which the object resides\n    * @param objectName\n    *           Name of the object\n    *\n    * @return a {@link Object} resource\n    */\n   @Named(\"Object:get\")\n   @GET\n   @Path(\"storage/v1/b/{bucket}/o/{object}\")\n   @Consumes(APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   GoogleCloudStorageObject getObject(@PathParam(\"bucket\") String bucketName,\n         @PathParam(\"object\") @Encoded String objectName);\n\n   /**\n    * Retrieves objects metadata\n    *\n    * @param bucketName\n    *           Name of the bucket in which the object resides\n    * @param objectName\n    *           Name of the object\n    * @param options\n    *           A class that implements {@link HttpRequestOptions}\n    *           such as {@link GetObjectOptions} with optional query parameters\n    *\n    * @return a {@link GoogleCloudStorageObject}\n    */\n   @Named(\"Object:get\")\n   @GET\n   @Path(\"storage/v1/b/{bucket}/o/{object}\")\n   @Consumes(APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   GoogleCloudStorageObject getObject(@PathParam(\"bucket\") String bucketName,\n         @PathParam(\"object\") @Encoded String objectName, HttpRequestOptions options);\n\n   /**\n    * Retrieve an object or their metadata\n    *\n    * @param bucketName\n    *           Name of the bucket in which the object resides\n    * @param objectName\n    *           Name of the object\n    *\n    * @return a {@link Object} resource\n    */\n   @Named(\"Object:get\")\n   @GET\n   @QueryParams(keys = \"alt\", values = \"media\")\n   @Path(\"storage/v1/b/{bucket}/o/{object}\")\n   @ResponseParser(ParseToPayloadEnclosing.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   PayloadEnclosing download(@PathParam(\"bucket\") String bucketName, @PathParam(\"object\") @Encoded String objectName);\n\n   /**\n    * Retrieves objects\n    *\n    * @param bucketName\n    *           Name of the bucket in which the object resides\n    * @param objectName\n    *           Name of the object\n    * @param options\n    *           A class that implements {@link HttpRequestOptions}\n    *           such as {@link GetObjectOptions} with optional query parameters\n    *\n    * @return a {@link GoogleCloudStorageObject}\n    */\n   @Named(\"Object:get\")\n   @GET\n   @QueryParams(keys = \"alt\", values = \"media\")\n   @Path(\"storage/v1/b/{bucket}/o/{object}\")\n   @ResponseParser(ParseToPayloadEnclosing.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   PayloadEnclosing download(@PathParam(\"bucket\") String bucketName, @PathParam(\"object\") @Encoded String objectName,\n         HttpRequestOptions options);\n\n   /**\n    * Stores a new object. Object metadata setting is not supported with simple uploads\n    *\n    * @see https://developers.google.com/storage/docs/json_api/v1/how-tos/upload#simple\n    *\n    * @param bucketName\n    *           Name of the bucket in which the object to be stored\n    * @param options\n    *           Supply an {@link InsertObjectOptions}. 'name' should not null.\n    *\n    * @return a {@link GoogleCloudStorageObject}\n    */\n   @Named(\"Object:simpleUpload\")\n   @POST\n   @QueryParams(keys = \"uploadType\", values = \"media\")\n   @Consumes(APPLICATION_JSON)\n   @Path(\"/upload/storage/v1/b/{bucket}/o\")\n   GoogleCloudStorageObject simpleUpload(@PathParam(\"bucket\") String bucketName, @HeaderParam(\"Content-Type\") String contentType,\n            @HeaderParam(\"Content-Length\") Long contentLength, @PayloadParam(\"payload\") Payload payload,\n            InsertObjectOptions options);\n\n   /**\n    * Deletes an object and its metadata. Deletions are permanent if versioning is not enabled.\n    *\n    * @param bucketName\n    *           Name of the bucket in which the object to be deleted resides\n    * @param objectName\n    *           Name of the object\n    */\n   @Named(\"Object:delete\")\n   @DELETE\n   @Path(\"storage/v1/b/{bucket}/o/{object}\")\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean deleteObject(@PathParam(\"bucket\") String bucketName, @PathParam(\"object\") @Encoded String objectName);\n\n   /**\n    * Deletes an object and its metadata. Deletions are permanent if versioning is not enabled for the bucket, or if the\n    * generation parameter is used.\n    *\n    * @param bucketName\n    *           Name of the bucket in which the object to be deleted resides\n    * @param objectName\n    *           Name of the object\n    * @param options\n    *           Supply {@link DeleteObjectOptions} with optional query parameters\n    */\n   @Named(\"Object:delete\")\n   @DELETE\n   @Path(\"storage/v1/b/{bucket}/o/{object}\")\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean deleteObject(@PathParam(\"bucket\") String bucketName, @PathParam(\"object\") @Encoded String objectName,\n            DeleteObjectOptions options);\n\n   /**\n    * Retrieves a list of objects matching the criteria.\n    *\n    * @param bucketName\n    *           Name of the bucket in which to look for objects.\n    */\n   @Named(\"Object:list\")\n   @GET\n   @Consumes(APPLICATION_JSON)\n   @Path(\"storage/v1/b/{bucket}/o\")\n   @Fallback(NullOnNotFoundOr404.class)\n   ListPageWithPrefixes<GoogleCloudStorageObject> listObjects(@PathParam(\"bucket\") String bucketName);\n\n   /**\n    * Retrieves a list of objects matching the criteria.\n    *\n    * @param bucketName\n    *           Name of the bucket in which to look for objects.\n    * @param options\n    *          Supply {@link ListObjectOptions}\n    * @return a {@link ListPage<GoogleCloudStorageObject>}\n    */\n   @Named(\"Object:list\")\n   @GET\n   @Consumes(APPLICATION_JSON)\n   @Path(\"storage/v1/b/{bucket}/o\")\n   @Fallback(NullOnNotFoundOr404.class)\n   ListPageWithPrefixes<GoogleCloudStorageObject> listObjects(@PathParam(\"bucket\") String bucketName, ListObjectOptions options);\n\n   /**\n    * Updates an object metadata\n    *\n    * @param bucketName\n    *           Name of the bucket in which the object resides\n    * @param objectName\n    *           Name of the object\n    * @param objectTemplate\n    *           Supply  an {@link ObjectTemplate}\n    *\n    * @return a {@link GoogleCloudStorageObject}\n    */\n   @Named(\"Object:update\")\n   @PUT\n   @Consumes(APPLICATION_JSON)\n   @Produces(APPLICATION_JSON)\n   @Path(\"storage/v1/b/{bucket}/o/{object}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   GoogleCloudStorageObject updateObject(@PathParam(\"bucket\") String bucketName,\n         @PathParam(\"object\") @Encoded String objectName,\n         @BinderParam(BindToJsonPayload.class) ObjectTemplate objectTemplate);\n\n   /**\n    * Updates an object\n    *\n    * @param bucketName\n    *           Name of the bucket in which the object resides\n    * @param objectName\n    *           Name of the object\n    * @param objectTemplate\n    *           Supply an{@link ObjectTemplate}\n    * @param options\n    *           Supply {@link UpdateObjectOptions} with optional query parameters\n    *\n    * @return a {@link GoogleCloudStorageObject} .\n    */\n   @Named(\"Object:update\")\n   @PUT\n   @Consumes(APPLICATION_JSON)\n   @Produces(APPLICATION_JSON)\n   @Path(\"storage/v1/b/{bucket}/o/{object}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   GoogleCloudStorageObject updateObject(@PathParam(\"bucket\") String bucketName,\n         @PathParam(\"object\") @Encoded String objectName,\n         @BinderParam(BindToJsonPayload.class) ObjectTemplate objectTemplate, UpdateObjectOptions options);\n\n   /**\n    * Updates an object according to patch semantics\n    *\n    * @param bucketName\n    *           Name of the bucket in which the object resides\n    * @param objectName\n    *           Name of the object\n    * @param objectTemplate\n    *           Supply {@link ObjectTemplate} with optional query parameters\n    *\n    * @return  a {@link GoogleCloudStorageObject}\n    */\n   @Named(\"Object:patch\")\n   @POST\n   @Headers(keys = \"X-HTTP-Method-Override\", values = \"PATCH\")\n   @Consumes(APPLICATION_JSON)\n   @Produces(APPLICATION_JSON)\n   @Path(\"storage/v1/b/{bucket}/o/{object}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   GoogleCloudStorageObject patchObject(@PathParam(\"bucket\") String bucketName,\n         @PathParam(\"object\") @Encoded String objectName,\n         @BinderParam(BindToJsonPayload.class) ObjectTemplate objectTemplate);\n\n   /**\n    * Updates an object according to patch semantics\n    *\n    * @param bucketName\n    *           Name of the bucket in which the object resides\n    * @param objectName\n    *           Name of the object\n    * @param objectTemplate\n    *           Supply {@link ObjectTemplate} with optional query parameters\n    * @param options\n    *           Supply {@link UpdateObjectOptions} with optional query parameters\n    *\n    * @return a {@link GoogleCloudStorageObject}\n    */\n   @Named(\"Object:patch\")\n   @POST\n   @Headers(keys = \"X-HTTP-Method-Override\", values = \"PATCH\")\n   @Consumes(APPLICATION_JSON)\n   @Produces(APPLICATION_JSON)\n   @Path(\"storage/v1/b/{bucket}/o/{object}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   GoogleCloudStorageObject patchObject(@PathParam(\"bucket\") String bucketName,\n         @PathParam(\"object\") @Encoded String objectName,\n         @BinderParam(BindToJsonPayload.class) ObjectTemplate objectTemplate, UpdateObjectOptions options);\n\n   /**\n    * Concatenates a list of existing objects into a new object in the same bucket.\n    *\n    * @param destinationBucket\n    *           Name of the bucket in which the object to be stored\n    * @param destinationObject\n    *           The type of upload request.\n    * @param composeObjectTemplate\n    *           Supply a {@link ComposeObjectTemplate}\n    *\n    * @return a {@link GoogleCloudStorageObject}\n    */\n   @Named(\"Object:compose\")\n   @POST\n   @Consumes(APPLICATION_JSON)\n   @Path(\"storage/v1/b/{destinationBucket}/o/{destinationObject}/compose\")\n   GoogleCloudStorageObject composeObjects(@PathParam(\"destinationBucket\") String destinationBucket,\n            @PathParam(\"destinationObject\") @Encoded String destinationObject,\n            @BinderParam(BindToJsonPayload.class) ComposeObjectTemplate composeObjectTemplate);\n\n   /**\n    * Concatenates a list of existing objects into a new object in the same bucket.\n    *\n    * @param destinationBucket\n    *           Name of the bucket in which the object to be stored\n    * @param destinationObject\n    *           The type of upload request.\n    * @param composeObjectTemplate\n    *           Supply a {@link ComposeObjectTemplate}\n    * @param options\n    *           Supply an {@link ComposeObjectOptions}\n    *\n    * @return a {@link GoogleCloudStorageObject}\n    */\n   @Named(\"Object:compose\")\n   @POST\n   @Consumes(APPLICATION_JSON)\n   @Path(\"storage/v1/b/{destinationBucket}/o/{destinationObject}/compose\")\n   GoogleCloudStorageObject composeObjects(@PathParam(\"destinationBucket\") String destinationBucket,\n            @PathParam(\"destinationObject\") @Encoded String destinationObject,\n            @BinderParam(BindToJsonPayload.class) ComposeObjectTemplate composeObjectTemplate,\n            ComposeObjectOptions options);\n\n   /**\n    * Copies an object to a specified location.\n    *\n    * @param destinationBucket\n    *           Name of the bucket in which to store the new object\n    * @param destinationObject\n    *           Name of the new object.\n    * @param sourceBucket\n    *           Name of the bucket in which to find the source object\n    * @param sourceObject\n    *           Name of the source object\n    *\n    * @return a {@link GoogleCloudStorageObject}\n    */\n   @Named(\"Object:copy\")\n   @POST\n   @Consumes(APPLICATION_JSON)\n   @Path(\"/storage/v1/b/{sourceBucket}/o/{sourceObject}/copyTo/b/{destinationBucket}/o/{destinationObject}\")\n   GoogleCloudStorageObject copyObject(@PathParam(\"destinationBucket\") String destinationBucket,\n         @PathParam(\"destinationObject\") @Encoded String destinationObject,\n         @PathParam(\"sourceBucket\") String sourceBucket,\n         @PathParam(\"sourceObject\") @Encoded String sourceObject);\n\n    /**\n     * Copies an object to a specified location with updated metadata.\n     *\n     * @param destinationBucket\n     *           Name of the bucket in which to store the new object\n     * @param destinationObject\n     *           Name of the new object.\n     * @param sourceBucket\n     *           Name of the bucket in which to find the source object\n     * @param sourceObject\n     *           Name of the source object\n     * @param template\n     *           Supply a {@link CopyObjectOptions}\n     *\n     * @return a {@link GoogleCloudStorageObject}\n     */\n    @Named(\"Object:copy\")\n    @POST\n    @Consumes(APPLICATION_JSON)\n    @Path(\"/storage/v1/b/{sourceBucket}/o/{sourceObject}/copyTo/b/{destinationBucket}/o/{destinationObject}\")\n    GoogleCloudStorageObject copyObject(@PathParam(\"destinationBucket\") String destinationBucket,\n          @PathParam(\"destinationObject\") @Encoded String destinationObject,\n          @PathParam(\"sourceBucket\") String sourceBucket,\n          @PathParam(\"sourceObject\") @Encoded String sourceObject,\n          @BinderParam(BindToJsonPayload.class) ObjectTemplate template);\n\n   /**\n    * Copies an object to a specified location. Optionally overrides metadata.\n    *\n    * @param destinationBucket\n    *           Name of the bucket in which to store the new object\n    * @param destinationObject\n    *           Name of the new object.\n    * @param sourceBucket\n    *           Name of the bucket in which to find the source object\n    * @param sourceObject\n    *           Name of the source object\n    * @param options\n    *           Supply a {@link CopyObjectOptions}\n    *\n    * @return a {@link GoogleCloudStorageObject}\n    */\n   @Named(\"Object:copy\")\n   @POST\n   @Consumes(APPLICATION_JSON)\n   @Path(\"/storage/v1/b/{sourceBucket}/o/{sourceObject}/copyTo/b/{destinationBucket}/o/{destinationObject}\")\n   GoogleCloudStorageObject copyObject(@PathParam(\"destinationBucket\") String destinationBucket,\n         @PathParam(\"destinationObject\") @Encoded String destinationObject,\n         @PathParam(\"sourceBucket\") String sourceBucket,\n         @PathParam(\"sourceObject\") @Encoded String sourceObject, CopyObjectOptions options);\n\n   /**\n    * Stores a new object with metadata.\n    *\n    * @see https://developers.google.com/storage/docs/json_api/v1/how-tos/upload#multipart\n    *\n    * @param bucketName\n    *           Name of the bucket in which the object to be stored\n    * @param objectTemplate\n    *           Supply an {@link ObjectTemplate}.\n    *\n    * @return a {@link GoogleCloudStorageObject}\n    */\n   @Named(\"Object:multipartUpload\")\n   @POST\n   @QueryParams(keys = \"uploadType\", values = \"multipart\")\n   @Consumes(APPLICATION_JSON)\n   @Path(\"/upload/storage/v1/b/{bucket}/o\")\n   @MapBinder(MultipartUploadBinder.class)\n   GoogleCloudStorageObject multipartUpload(@PathParam(\"bucket\") String bucketName,\n            @PayloadParam(\"template\") ObjectTemplate objectTemplate,\n            @PayloadParam(\"payload\") Payload payload);\n\n   /**\n    * Rewrites a source object to a destination object.\n    *\n    * @param destinationBucket\n    *           Name of the bucket in which the object to be stored\n    * @param destinationObject\n    *           Name of the new object.\n    * @param sourceBucket\n    *           Name of the bucket in which to find the source object.\n    * @param sourceObject\n    *           Name of the source object.\n    *\n    * @return a {@link RewriteResponse}\n    */\n   @Named(\"Object:rewrite\")\n   @POST\n   @Consumes(APPLICATION_JSON)\n   @Path(\"/storage/v1/b/{sourceBucket}/o/{sourceObject}/rewriteTo/b/{destinationBucket}/o/{destinationObject}\")\n   RewriteResponse rewriteObjects(@PathParam(\"destinationBucket\") String destinationBucket,\n         @PathParam(\"destinationObject\") @Encoded String destinationObject,\n         @PathParam(\"sourceBucket\") String sourceBucket, @PathParam(\"sourceObject\") @Encoded String sourceObject);\n\n   /**\n    * Rewrites a source object to a destination object.\n    *\n    * @param destinationBucket\n    *           Name of the bucket in which the object to be stored\n    * @param destinationObject\n    *           Name of the new object.\n    * @param sourceBucket\n    *           Name of the bucket in which to find the source object.\n    * @param sourceObject\n    *           Name of the source object.\n    * @param options\n    *           Supply an {@link RewriteObjectOptions}\n    *\n    * @return a {@link RewriteResponse}\n    */\n   @Named(\"Object:rewrite\")\n   @POST\n   @Consumes(APPLICATION_JSON)\n   @Path(\"/storage/v1/b/{sourceBucket}/o/{sourceObject}/rewriteTo/b/{destinationBucket}/o/{destinationObject}\")\n   RewriteResponse rewriteObjects(@PathParam(\"destinationBucket\") String destinationBucket,\n         @PathParam(\"destinationObject\") @Encoded String destinationObject,\n         @PathParam(\"sourceBucket\") String sourceBucket,\n         @PathParam(\"sourceObject\") @Encoded String sourceObject,\n         RewriteObjectOptions options);\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/features/ResumableUploadApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DefaultValue;\nimport jakarta.ws.rs.HeaderParam;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.QueryParam;\n\nimport org.jclouds.googlecloudstorage.binders.UploadBinder;\nimport org.jclouds.googlecloudstorage.domain.ResumableUpload;\nimport org.jclouds.googlecloudstorage.domain.templates.ObjectTemplate;\nimport org.jclouds.googlecloudstorage.options.InsertObjectOptions;\nimport org.jclouds.googlecloudstorage.parser.ParseToResumableUpload;\nimport org.jclouds.io.Payload;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.SkipEncoding;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\n/**\n * Provides Resumable Upload support via Rest API\n *\n * @see <a href=\"https://developers.google.com/storage/docs/json_api/v1/objects\"/>\n * @see <a href=\"https://developers.google.com/storage/docs/json_api/v1/how-tos/upload#resumable\"/>\n */\n@SkipEncoding({ '/', '=' })\n@RequestFilters(OAuthFilter.class)\n@Consumes(APPLICATION_JSON)\npublic interface ResumableUploadApi {\n\n   /**\n    * initiate a Resumable Upload Session\n    *\n    * @see https://developers.google.com/storage/docs/json_api/v1/how-tos/upload#resumable\n    *\n    * @param bucketName\n    *           Name of the bucket in which the object to be stored\n    * @param objectName\n    *           Name of the object to upload\n    * @param contentType\n    *           Content type of the uploaded data\n    * @param contentLength\n    *           ContentLength of the uploaded object (Media part)\n    *\n    * @return a {@link ResumableUpload}\n    */\n   @Named(\"Object:initResumableUpload\")\n   @POST\n   @QueryParams(keys = \"uploadType\", values = \"resumable\")\n   @Path(\"/upload/storage/v1/b/{bucket}/o\")\n   @ResponseParser(ParseToResumableUpload.class)\n   ResumableUpload initResumableUpload(@PathParam(\"bucket\") String bucketName, @QueryParam(\"name\") String objectName,\n            @HeaderParam(\"X-Upload-Content-Type\") String contentType,\n            @HeaderParam(\"X-Upload-Content-Length\") String contentLength);\n\n   /**\n    * initiate a Resumable Upload Session\n    *\n    * @see https://developers.google.com/storage/docs/json_api/v1/how-tos/upload#simple\n    *\n    * @param bucketName\n    *           Name of the bucket in which the object to be stored\n    * @param contentType\n    *           Content type of the uploaded data (Media part)\n    * @param contentLength\n    *           Content length of the uploaded data (Media part)\n    * @param metada\n    *           Supply an {@link ObjectTemplate}\n    *\n    * @return a {@link ResumableUpload}\n    */\n   @Named(\"Object:resumableUpload\")\n   @POST\n   @QueryParams(keys = \"uploadType\", values = \"resumable\")\n   @Path(\"/upload/storage/v1/b/{bucket}/o\")\n   @ResponseParser(ParseToResumableUpload.class)\n   ResumableUpload initResumableUpload(@PathParam(\"bucket\") String bucketName,\n            @HeaderParam(\"X-Upload-Content-Type\") String contentType,\n            @HeaderParam(\"X-Upload-Content-Length\") Long contentLength,\n            @BinderParam(BindToJsonPayload.class) ObjectTemplate metadata);\n\n   /**\n    * Stores a new object\n    *\n    * @see https://developers.google.com/storage/docs/json_api/v1/how-tos/upload#resumable\n    *\n    * @param bucketName\n    *           Name of the bucket in which the object to be stored\n    * @param options\n    *           Supply {@link InsertObjectOptions} with optional query parameters. 'name' is mandatory.\n    *\n    * @return If successful, this method returns a {@link GoogleCloudStorageObject} resource.\n    */\n   @Named(\"Object:resumableUpload\")\n   @PUT\n   @QueryParams(keys = \"uploadType\", values = \"resumable\")\n   @Path(\"/upload/storage/v1/b/{bucket}/o\")\n   @MapBinder(UploadBinder.class)\n   @ResponseParser(ParseToResumableUpload.class)\n   ResumableUpload upload(@PathParam(\"bucket\") String bucketName, @QueryParam(\"upload_id\") String uploadId,\n            @HeaderParam(\"Content-Type\") String contentType, @HeaderParam(\"Content-Length\") String contentLength,\n            @PayloadParam(\"payload\") Payload payload);\n\n   /**\n    * Facilitate to use resumable upload operation to upload files in chunks\n    *\n    * @see https://developers.google.com/storage/docs/json_api/v1/how-tos/upload#resumable\n    *\n    * @param bucketName\n    *           Name of the bucket in which the object to be stored\n    * @param uploadId\n    *           uploadId returned from initResumableUpload operation\n    * @param contentType\n    *           Content type of the uploaded data\n    * @param contentLength\n    *           Content length of the uploaded data\n    * @param contentRange\n    *           Range in {bytes StartingByte - Endingbyte/Totalsize } format ex: bytes 0 - 1213/2000\n    * @param payload\n    *           a {@link Payload} with actual data to upload\n    *\n    * @return a {@link ResumableUpload}\n    */\n   @Named(\"Object:Upload\")\n   @PUT\n   @QueryParams(keys = \"uploadType\", values = \"resumable\")\n   @Path(\"/upload/storage/v1/b/{bucket}/o\")\n   @MapBinder(UploadBinder.class)\n   @ResponseParser(ParseToResumableUpload.class)\n   ResumableUpload chunkUpload(@PathParam(\"bucket\") String bucketName, @QueryParam(\"upload_id\") String uploadId,\n            @HeaderParam(\"Content-Type\") String contentType, @HeaderParam(\"Content-Length\") Long contentLength,\n            @HeaderParam(\"Content-Range\") String contentRange, @PayloadParam(\"payload\") Payload payload);\n\n   /**\n    * Check the status of a resumable upload\n    *\n    * @see https://developers.google.com/storage/docs/json_api/v1/how-tos/upload#resumable\n    *\n    * @param bucketName\n    *           Name of the bucket in which the object to be stored\n    * @param uploadId\n    *           uploadId returned from initResumableUpload operation\n    * @param contentRange\n    *           Range in {bytes StartingByte - Endingbyte/Totalsize } format ex: bytes 0 - 1213/2000\n    *\n    * @return a {@link ResumableUpload}\n    */\n\n   @Named(\"Object:Upload\")\n   @PUT\n   @DefaultValue(\"0\")\n   @QueryParams(keys = \"uploadType\", values = \"resumable\")\n   @Path(\"/upload/storage/v1/b/{bucket}/o\")\n   @ResponseParser(ParseToResumableUpload.class)\n   ResumableUpload checkStatus(@PathParam(\"bucket\") String bucketName, @QueryParam(\"upload_id\") String uploadId,\n            @HeaderParam(\"Content-Range\") String contentRange);\n\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/handlers/GoogleCloudStorageClientErrorRetryHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.handlers;\n\nimport jakarta.inject.Singleton;\nimport jakarta.ws.rs.core.Response.Status;\n\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.handlers.BackoffLimitedRetryHandler;\nimport org.jclouds.http.HttpRetryHandler;\n\nimport com.google.inject.Inject;\n\n@Singleton\npublic final class GoogleCloudStorageClientErrorRetryHandler implements HttpRetryHandler {\n   private final BackoffLimitedRetryHandler backoffHandler;\n\n   @Inject\n   protected GoogleCloudStorageClientErrorRetryHandler(BackoffLimitedRetryHandler backoffHandler) {\n      this.backoffHandler = backoffHandler;\n   }\n\n   @Override\n   public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) {\n      if (response.getStatusCode() == Status.TOO_MANY_REQUESTS.getStatusCode()) {\n         return backoffHandler.shouldRetryRequest(command, response);\n      } else {\n         return false;\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/handlers/GoogleCloudStorageErrorHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.handlers;\n\nimport static org.jclouds.http.HttpUtils.closeClientButKeepContentStream;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.ResourceNotFoundException;\n\n/**\n * This will parse and set an appropriate exception on the command object.\n */\n@Singleton\npublic class GoogleCloudStorageErrorHandler implements HttpErrorHandler {\n   public void handleError(HttpCommand command, HttpResponse response) {\n      // it is important to always read fully and close streams\n      byte[] data = closeClientButKeepContentStream(response);\n      String message = data != null ? new String(data) : null;\n\n      Exception exception = message != null ? new HttpResponseException(command, response, message)\n              : new HttpResponseException(command, response);\n      message = message != null ? message : String.format(\"%s -> %s\", command.getCurrentRequest().getRequestLine(),\n              response.getStatusLine());\n\n      String message411 = \"MissingContentLength: You must provide the Content-Length HTTP header.\\n\";\n      String message412 = \"PreconditionFailed: At least one of the pre-conditions you specified did not hold.\\n\";\n\n      switch (response.getStatusCode()) {\n         case 308:\n            return;\n         case 400:\n            if (message.indexOf(\"<Code>ExpiredToken</Code>\") != -1) {\n               exception = new AuthorizationException(message, exception);\n            }\n            break;\n         case 401:\n         case 403:\n            exception = new AuthorizationException(message, exception);\n            break;\n         case 404:            \n             exception = new ResourceNotFoundException(message, exception);           \n             break;\n         case 409:\n            exception = new IllegalStateException(message, exception);\n            break;\n         case 411:\n            exception = new IllegalStateException(message411 + message, exception);\n            break;\n         case 412:\n            exception = new IllegalStateException(message412 + message, exception);\n            break;\n      }\n      command.setException(exception);\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/handlers/GoogleCloudStorageRedirectRetryHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.handlers;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.handlers.BackoffLimitedRetryHandler;\nimport org.jclouds.http.handlers.RedirectionRetryHandler;\n\nimport com.google.inject.Inject;\n\n/**\n * This will parse and set an appropriate exception on the command object.\n */\n@Singleton\npublic class GoogleCloudStorageRedirectRetryHandler extends RedirectionRetryHandler {\n\n   @Inject\n   protected GoogleCloudStorageRedirectRetryHandler(BackoffLimitedRetryHandler backoffHandler) {\n      super(backoffHandler);\n   }\n\n   @Override\n   public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) {\n      if (response.getStatusCode() == 308) {\n         return false;\n      } else {\n         return super.shouldRetryRequest(command, response);\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/options/ComposeObjectOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.DestinationPredefinedAcl;\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\n/**\n * Allows to optionally specify ifMetagenerationMatch,ifMetagenerationNotMatch and destinationPredefinedAcl when\n * ComposingObjects operation.\n */\npublic class ComposeObjectOptions extends BaseHttpRequestOptions {\n\n   public ComposeObjectOptions ifMetagenerationMatch(Long ifMetagenerationMatch) {\n      this.queryParameters.put(\"ifMetagenerationMatch\", checkNotNull(ifMetagenerationMatch, \"ifMetagenerationMatch\")\n               + \"\");\n      return this;\n   }\n\n   public ComposeObjectOptions ifMetagenerationNotMatch(Long ifMetagenerationNotMatch) {\n      this.queryParameters.put(\"ifMetagenerationNotMatch\",\n               checkNotNull(ifMetagenerationNotMatch, \"ifMetagenerationNotMatch\") + \"\");\n      return this;\n   }\n\n   public ComposeObjectOptions destinationPredefinedAcl(DestinationPredefinedAcl destinationPredefinedAcl) {\n      this.queryParameters.put(\"destinationPredefinedAcl\",\n               checkNotNull(destinationPredefinedAcl, \"destinationPredefinedAcl\").toString());\n      return this;\n   }\n\n   public static class Builder {\n\n      public ComposeObjectOptions ifMetagenerationMatch(Long ifMetagenerationMatch) {\n         return new ComposeObjectOptions().ifMetagenerationMatch(ifMetagenerationMatch);\n      }\n\n      public ComposeObjectOptions ifMetagenerationNotMatch(Long ifMetagenerationNotMatch) {\n         return new ComposeObjectOptions().ifMetagenerationNotMatch(ifMetagenerationNotMatch);\n      }\n\n      public ComposeObjectOptions destinationPredefinedAcl(DestinationPredefinedAcl destinationPredefinedAcl) {\n         return new ComposeObjectOptions().destinationPredefinedAcl(destinationPredefinedAcl);\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/options/CopyObjectOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.PredefinedAcl;\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.Projection;\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\n/**\n * Allows to optionally specify ifMetagenerationMatch,ifMetagenerationNotMatch and projection which used in Bucket\n */\npublic class CopyObjectOptions extends BaseHttpRequestOptions {\n\n   public CopyObjectOptions contentEncoding(String contentEncoding) {\n      this.queryParameters.put(\"contentEncoding\", checkNotNull(contentEncoding, \"contentEncoding\") + \"\");\n      return this;\n   }\n\n   public CopyObjectOptions name(String name) {\n      this.queryParameters.put(\"name\", checkNotNull(name, \"name\") + \"\");\n      return this;\n   }\n\n   public CopyObjectOptions ifGenerationMatch(Long ifGenerationMatch) {\n      this.queryParameters.put(\"ifGenerationMatch\", checkNotNull(ifGenerationMatch, \"ifGenerationMatch\") + \"\");\n      return this;\n   }\n\n   public CopyObjectOptions ifGenerationNotMatch(Long ifGenerationNotMatch) {\n      this.queryParameters.put(\"ifGenerationNotMatch\", checkNotNull(ifGenerationNotMatch, \"ifGenerationNotMatch\") + \"\");\n      return this;\n   }\n\n   public CopyObjectOptions ifMetagenerationMatch(Long ifMetagenerationMatch) {\n      this.queryParameters.put(\"ifMetagenerationMatch\", checkNotNull(ifMetagenerationMatch, \"ifMetagenerationMatch\")\n               + \"\");\n      return this;\n   }\n\n   public CopyObjectOptions ifMetagenerationNotMatch(Long ifMetagenerationNotMatch) {\n      this.queryParameters.put(\"ifMetagenerationNotMatch\",\n               checkNotNull(ifMetagenerationNotMatch, \"ifMetagenerationNotMatch\") + \"\");\n      return this;\n   }\n   public CopyObjectOptions ifSourceGenerationMatch(Long ifSourceGenerationMatch) {\n      this.queryParameters.put(\"ifSourceGenerationMatch\", checkNotNull(ifSourceGenerationMatch, \"ifSourceGenerationMatch\") + \"\");\n      return this;\n   }\n\n   public CopyObjectOptions ifSourceGenerationNotMatch(Long ifSourceGenerationNotMatch) {\n      this.queryParameters.put(\"ifSourceGenerationNotMatch\", checkNotNull(ifSourceGenerationNotMatch, \"ifSourceGenerationNotMatch\") + \"\");\n      return this;\n   }\n\n   public CopyObjectOptions ifSourceMetagenerationMatch(Long ifSourceMetagenerationMatch) {\n      this.queryParameters.put(\"ifSourceMetagenerationMatch\", checkNotNull(ifSourceMetagenerationMatch, \"ifSourceMetagenerationMatch\")\n               + \"\");\n      return this;\n   }\n\n   public CopyObjectOptions ifSourceMetagenerationNotMatch(Long ifSourceMetagenerationNotMatch) {\n      this.queryParameters.put(\"ifSourceMetagenerationNotMatch\",\n               checkNotNull(ifSourceMetagenerationNotMatch, \"ifSourceMetagenerationNotMatch\") + \"\");\n      return this;\n   }\n\n   public CopyObjectOptions sourceGeneration(Long sourceGeneration) {\n      this.queryParameters.put(\"sourceGeneration\", checkNotNull(sourceGeneration, \"sourceGeneration\") + \"\");\n      return this;\n   }\n\n   public CopyObjectOptions predefinedAcl(PredefinedAcl predefinedAcl) {\n      this.queryParameters.put(\"predefinedAcl\", checkNotNull(predefinedAcl, \"predefinedAcl\").toString());\n      return this;\n   }\n\n   public CopyObjectOptions projection(Projection projection) {\n      this.queryParameters.put(\"projection\", checkNotNull(projection, \"projection\").toString());\n      return this;\n   }\n\n   public static class Builder {\n\n      public CopyObjectOptions contentEncoding(String contentEncoding) {\n         return new CopyObjectOptions().contentEncoding(contentEncoding);\n      }\n\n      public CopyObjectOptions name(String name) {\n         return new CopyObjectOptions().name(name);\n      }\n\n      public CopyObjectOptions ifGenerationMatch(Long ifGenerationMatch) {\n         return new CopyObjectOptions().ifGenerationMatch(ifGenerationMatch);\n      }\n\n      public CopyObjectOptions ifGenerationNotMatch(Long ifGenerationNotMatch) {\n         return new CopyObjectOptions().ifGenerationNotMatch(ifGenerationNotMatch);\n      }\n\n      public CopyObjectOptions ifMetagenerationMatch(Long ifMetagenerationMatch) {\n         return new CopyObjectOptions().ifMetagenerationMatch(ifMetagenerationMatch);\n      }\n\n      public CopyObjectOptions ifMetagenerationNotMatch(Long ifMetagenerationNotMatch) {\n         return new CopyObjectOptions().ifMetagenerationNotMatch(ifMetagenerationNotMatch);\n      }\n\n      public CopyObjectOptions ifSourceGenerationMatch(Long ifSourceGenerationMatch) {\n         return new CopyObjectOptions().ifSourceGenerationMatch(ifSourceGenerationMatch);\n      }\n\n      public CopyObjectOptions ifSourceGenerationNotMatch(Long ifSourceGenerationNotMatch) {\n         return new CopyObjectOptions().ifSourceGenerationNotMatch(ifSourceGenerationNotMatch);\n      }\n\n      public CopyObjectOptions ifSourceMetagenerationMatch(Long ifSourceMetagenerationMatch) {\n         return new CopyObjectOptions().ifSourceMetagenerationMatch(ifSourceMetagenerationMatch);\n      }\n\n      public CopyObjectOptions ifSourceMetagenerationNotMatch(Long ifSourceMetagenerationNotMatch) {\n         return new CopyObjectOptions().ifSourceMetagenerationNotMatch(ifSourceMetagenerationNotMatch);\n      }\n\n\n      public CopyObjectOptions sourceGeneration(Long sourceGeneration) {\n         return new CopyObjectOptions().sourceGeneration(sourceGeneration);\n      }\n\n      public CopyObjectOptions predefinedAcl(PredefinedAcl predefinedAcl) {\n         return new CopyObjectOptions().predefinedAcl(predefinedAcl);\n      }\n\n      public UpdateObjectOptions projection(Projection projection) {\n         return new UpdateObjectOptions().projection(projection);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/options/DeleteBucketOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\n/**\n * Allows to optionally specify ifMetagenerationMatch,ifMetagenerationNotMatch and projection which used in Bucket\n */\npublic class DeleteBucketOptions extends BaseHttpRequestOptions {\n\n   public DeleteBucketOptions ifMetagenerationMatch(Long ifMetagenerationMatch) {\n      this.queryParameters.put(\"ifMetagenerationMatch\", checkNotNull(ifMetagenerationMatch, \"ifMetagenerationMatch\")\n               + \"\");\n      return this;\n   }\n\n   public DeleteBucketOptions ifMetagenerationNotMatch(Long ifMetagenerationNotMatch) {\n      this.queryParameters.put(\"ifMetagenerationNotMatch\",\n               checkNotNull(ifMetagenerationNotMatch, \"ifMetagenerationNotMatch\") + \"\");\n      return this;\n   }\n\n   public static class Builder {\n\n      public DeleteBucketOptions ifMetagenerationMatch(Long ifMetagenerationMatch) {\n         return new DeleteBucketOptions().ifMetagenerationMatch(ifMetagenerationMatch);\n      }\n\n      public DeleteBucketOptions ifMetagenerationNotMatch(Long ifMetagenerationNotMatch) {\n         return new DeleteBucketOptions().ifMetagenerationNotMatch(ifMetagenerationNotMatch);\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/options/DeleteObjectOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.PredefinedAcl;\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\n/**\n * Allows to optionally specify ifMetagenerationMatch,ifMetagenerationNotMatch and projection which used in Bucket\n */\npublic class DeleteObjectOptions extends BaseHttpRequestOptions {\n\n   public DeleteObjectOptions ifGenerationMatch(Long ifGenerationMatch) {\n      this.queryParameters.put(\"ifGenerationMatch\", checkNotNull(ifGenerationMatch, \"ifGenerationMatch\") + \"\");\n      return this;\n   }\n\n   public DeleteObjectOptions ifGenerationNotMatch(Long ifGenerationNotMatch) {\n      this.queryParameters.put(\"ifGenerationNotMatch\", checkNotNull(ifGenerationNotMatch, \"ifGenerationNotMatch\") + \"\");\n      return this;\n   }\n\n   public DeleteObjectOptions ifMetagenerationMatch(Long ifMetagenerationMatch) {\n      this.queryParameters.put(\"ifMetagenerationMatch\", checkNotNull(ifMetagenerationMatch, \"ifMetagenerationMatch\")\n               + \"\");\n      return this;\n   }\n\n   public DeleteObjectOptions ifMetagenerationNotMatch(Long ifMetagenerationNotMatch) {\n      this.queryParameters.put(\"ifMetagenerationNotMatch\",\n               checkNotNull(ifMetagenerationNotMatch, \"ifMetagenerationNotMatch\") + \"\");\n      return this;\n   }\n\n   public DeleteObjectOptions generation(Long generation) {\n      this.queryParameters.put(\"generation\", checkNotNull(generation, \"generation\").toString());\n      return this;\n   }\n\n   public DeleteObjectOptions predefinedAcl(PredefinedAcl predefinedAcl) {\n      this.queryParameters.put(\"predefinedAcl\", checkNotNull(predefinedAcl, \"predefinedAcl\").toString());\n      return this;\n   }\n\n   public static class Builder {\n\n      public DeleteObjectOptions ifGenerationMatch(Long ifGenerationMatch) {\n         return new DeleteObjectOptions().ifGenerationMatch(ifGenerationMatch);\n      }\n\n      public DeleteObjectOptions ifGenerationNotMatch(Long ifGenerationNotMatch) {\n         return new DeleteObjectOptions().ifGenerationNotMatch(ifGenerationNotMatch);\n      }\n\n      public DeleteObjectOptions ifMetagenerationMatch(Long ifMetagenerationMatch) {\n         return new DeleteObjectOptions().ifMetagenerationMatch(ifMetagenerationMatch);\n      }\n\n      public DeleteObjectOptions ifMetagenerationNotMatch(Long ifMetagenerationNotMatch) {\n         return new DeleteObjectOptions().ifMetagenerationNotMatch(ifMetagenerationNotMatch);\n      }\n\n      public DeleteObjectOptions generation(Long generation) {\n         return new DeleteObjectOptions().generation(generation);\n      }\n\n      public DeleteObjectOptions predefinedAcl(PredefinedAcl predefinedAcl) {\n         return new DeleteObjectOptions().predefinedAcl(predefinedAcl);\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/options/GetBucketOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.Projection;\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\n/**\n * Allows to optionally specify ifMetagenerationMatch,ifMetagenerationNotMatch and projection which used in Bucket\n */\npublic class GetBucketOptions extends BaseHttpRequestOptions {\n\n   public GetBucketOptions ifMetagenerationMatch(Long ifMetagenerationMatch) {\n      this.queryParameters.put(\"ifMetagenerationMatch\", checkNotNull(ifMetagenerationMatch, \"ifMetagenerationMatch\")\n               + \"\");\n      return this;\n   }\n\n   public GetBucketOptions ifMetagenerationNotMatch(Long ifMetagenerationNotMatch) {\n      this.queryParameters.put(\"ifMetagenerationNotMatch\",\n               checkNotNull(ifMetagenerationNotMatch, \"ifMetagenerationNotMatch\") + \"\");\n      return this;\n   }\n\n   public GetBucketOptions projection(Projection projection) {\n      this.queryParameters.put(\"projection\", checkNotNull(projection, \"projection\").toString());\n      return this;\n   }\n\n   public static class Builder {\n\n      public GetBucketOptions ifMetagenerationMatch(Long ifMetagenerationMatch) {\n         return new GetBucketOptions().ifMetagenerationMatch(ifMetagenerationMatch);\n      }\n\n      public GetBucketOptions ifMetagenerationNotMatch(Long ifMetagenerationNotMatch) {\n         return new GetBucketOptions().ifMetagenerationNotMatch(ifMetagenerationNotMatch);\n      }\n\n      public GetBucketOptions projection(Projection projection) {\n         return new GetBucketOptions().projection(projection);\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/options/GetObjectOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.Projection;\nimport org.jclouds.http.options.GetOptions;\n\n/**\n * Allows to optionally specify generation, ifGenerationMatch, ifGenerationNotMatch, ifMetagenerationMatch,\n * ifMetagenerationNotMatch and projection, in addition to the values in {@link GetOptions}.\n */\npublic class GetObjectOptions extends GetOptions {\n\n   public GetObjectOptions ifGenerationMatch(Long ifGenerationMatch) {\n      this.queryParameters.put(\"ifGenerationMatch\", checkNotNull(ifGenerationMatch, \"ifGenerationMatch\") + \"\");\n      return this;\n   }\n\n   public GetObjectOptions ifGenerationNotMatch(Long ifGenerationNotMatch) {\n      this.queryParameters.put(\"ifGenerationNotMatch\", checkNotNull(ifGenerationNotMatch, \"ifGenerationNotMatch\") + \"\");\n      return this;\n   }\n\n   public GetObjectOptions ifMetagenerationMatch(Long ifMetagenerationMatch) {\n      this.queryParameters.put(\"ifMetagenerationMatch\", checkNotNull(ifMetagenerationMatch, \"ifMetagenerationMatch\")\n               + \"\");\n      return this;\n   }\n\n   public GetObjectOptions ifMetagenerationNotMatch(Long ifMetagenerationNotMatch) {\n      this.queryParameters.put(\"ifMetagenerationNotMatch\",\n               checkNotNull(ifMetagenerationNotMatch, \"ifMetagenerationNotMatch\") + \"\");\n      return this;\n   }\n\n   public GetObjectOptions generation(Long generation) {\n      this.queryParameters.put(\"generation\", checkNotNull(generation, \"generation\").toString());\n      return this;\n   }\n\n   public GetObjectOptions projection(Projection projection) {\n      this.queryParameters.put(\"projection\", checkNotNull(projection, \"projection\").toString());\n      return this;\n   }\n\n   public static class Builder {\n\n      public GetObjectOptions ifGenerationMatch(Long ifGenerationMatch) {\n         return new GetObjectOptions().ifGenerationMatch(ifGenerationMatch);\n      }\n\n      public GetObjectOptions ifGenerationNotMatch(Long ifGenerationNotMatch) {\n         return new GetObjectOptions().ifGenerationNotMatch(ifGenerationNotMatch);\n      }\n\n      public GetObjectOptions ifMetagenerationMatch(Long ifMetagenerationMatch) {\n         return new GetObjectOptions().ifMetagenerationMatch(ifMetagenerationMatch);\n      }\n\n      public GetObjectOptions ifMetagenerationNotMatch(Long ifMetagenerationNotMatch) {\n         return new GetObjectOptions().ifMetagenerationNotMatch(ifMetagenerationNotMatch);\n      }\n\n      public GetObjectOptions generation(Long generation) {\n         return new GetObjectOptions().generation(generation);\n      }\n\n      public GetObjectOptions projection(Projection projection) {\n         return new GetObjectOptions().projection(projection);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/options/InsertBucketOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.PredefinedAcl;\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.Projection;\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\n/**\n * Allows to optionally specify predefinedAcl and projection which used in Bucket\n *\n * @see <a href=\"https://developers.google.com/storage/docs/json_api/v1/buckets/insert\"/>\n */\npublic class InsertBucketOptions extends BaseHttpRequestOptions {\n\n   public InsertBucketOptions predefinedAcl(PredefinedAcl predefinedAcl) {\n      this.queryParameters.put(\"predefinedAcl\", checkNotNull(predefinedAcl, \"predefinedAcl\").toString());\n      return this;\n   }\n\n   public InsertBucketOptions projection(Projection projection) {\n      this.queryParameters.put(\"projection\", checkNotNull(projection, \"projection\").toString());\n      return this;\n   }\n\n   public static class Builder {\n\n      public InsertBucketOptions predefinedAcl(PredefinedAcl predefinedAcl) {\n         return new InsertBucketOptions().predefinedAcl(predefinedAcl);\n      }\n\n      public InsertBucketOptions projection(Projection projection) {\n         return new InsertBucketOptions().projection(projection);\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/options/InsertObjectOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.PredefinedAcl;\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.Projection;\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\n/**\n * Allows to optionally specify ifMetagenerationMatch,ifMetagenerationNotMatch and projection which used in Bucket\n */\npublic class InsertObjectOptions extends BaseHttpRequestOptions {\n\n   public InsertObjectOptions contentEncoding(String contentEncoding) {\n      this.queryParameters.put(\"contentEncoding\", checkNotNull(contentEncoding, \"contentEncoding\") + \"\");\n      return this;\n   }\n\n   public InsertObjectOptions name(String name) {\n      this.queryParameters.put(\"name\", checkNotNull(name, \"name\") + \"\");\n      return this;\n   }\n\n   public InsertObjectOptions ifGenerationMatch(Long ifGenerationMatch) {\n      this.queryParameters.put(\"ifGenerationMatch\", checkNotNull(ifGenerationMatch, \"ifGenerationMatch\") + \"\");\n      return this;\n   }\n\n   public InsertObjectOptions ifGenerationNotMatch(Long ifGenerationNotMatch) {\n      this.queryParameters.put(\"ifGenerationNotMatch\", checkNotNull(ifGenerationNotMatch, \"ifGenerationNotMatch\") + \"\");\n      return this;\n   }\n\n   public InsertObjectOptions ifMetagenerationMatch(Long ifMetagenerationMatch) {\n      this.queryParameters.put(\"ifMetagenerationMatch\", checkNotNull(ifMetagenerationMatch, \"ifMetagenerationMatch\")\n               + \"\");\n      return this;\n   }\n\n   public InsertObjectOptions ifMetagenerationNotMatch(Long ifMetagenerationNotMatch) {\n      this.queryParameters.put(\"ifMetagenerationNotMatch\",\n               checkNotNull(ifMetagenerationNotMatch, \"ifMetagenerationNotMatch\") + \"\");\n      return this;\n   }\n\n   public InsertObjectOptions generation(Long generation) {\n      this.queryParameters.put(\"generation\", checkNotNull(generation, \"generation\").toString());\n      return this;\n   }\n\n   public InsertObjectOptions predefinedAcl(PredefinedAcl predefinedAcl) {\n      this.queryParameters.put(\"predefinedAcl\", checkNotNull(predefinedAcl, \"predefinedAcl\").toString());\n      return this;\n   }\n\n   public InsertObjectOptions projection(Projection projection) {\n      this.queryParameters.put(\"projection\", checkNotNull(projection, \"projection\").toString());\n      return this;\n   }\n\n   public static class Builder {\n\n      public InsertObjectOptions contentEncoding(String contentEncoding) {\n         return new InsertObjectOptions().contentEncoding(contentEncoding);\n      }\n\n      public InsertObjectOptions name(String name) {\n         return new InsertObjectOptions().name(name);\n      }\n\n      public InsertObjectOptions ifGenerationMatch(Long ifGenerationMatch) {\n         return new InsertObjectOptions().ifGenerationMatch(ifGenerationMatch);\n      }\n\n      public InsertObjectOptions ifGenerationNotMatch(Long ifGenerationNotMatch) {\n         return new InsertObjectOptions().ifGenerationNotMatch(ifGenerationNotMatch);\n      }\n\n      public InsertObjectOptions ifMetagenerationMatch(Long ifMetagenerationMatch) {\n         return new InsertObjectOptions().ifMetagenerationMatch(ifMetagenerationMatch);\n      }\n\n      public InsertObjectOptions ifMetagenerationNotMatch(Long ifMetagenerationNotMatch) {\n         return new InsertObjectOptions().ifMetagenerationNotMatch(ifMetagenerationNotMatch);\n      }\n\n      public InsertObjectOptions generation(Long generation) {\n         return new InsertObjectOptions().generation(generation);\n      }\n\n      public InsertObjectOptions predefinedAcl(PredefinedAcl predefinedAcl) {\n         return new InsertObjectOptions().predefinedAcl(predefinedAcl);\n      }\n\n      public InsertObjectOptions projection(Projection projection) {\n         return new InsertObjectOptions().projection(projection);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/options/ListObjectOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.Projection;\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\npublic class ListObjectOptions extends BaseHttpRequestOptions {\n\n   public ListObjectOptions delimiter(String delimiter) {\n      this.queryParameters.put(\"delimiter\", checkNotNull(delimiter, \"delimiter\"));\n      return this;\n   }\n\n   public ListObjectOptions prefix(String prefix) {\n      this.queryParameters.put(\"prefix\", checkNotNull(prefix, \"delimeter\"));\n      return this;\n   }\n\n   public ListObjectOptions versions(Boolean versions) {\n      this.queryParameters.put(\"versions\", checkNotNull(versions, \"versions\") + \"\");\n      return this;\n   }\n\n   public ListObjectOptions pageToken(String pageToken) {\n      this.queryParameters.put(\"pageToken\", checkNotNull(pageToken, \"pageToken\"));\n      return this;\n   }\n\n   public ListObjectOptions maxResults(Integer maxResults) {\n      this.queryParameters.put(\"maxResults\", checkNotNull(maxResults, \"maxResults\") + \"\");\n      return this;\n   }\n\n   public ListObjectOptions projection(Projection projection) {\n      this.queryParameters.put(\"projection\", checkNotNull(projection, \"projection\").toString());\n      return this;\n   }\n\n   public static class Builder {\n\n      public ListObjectOptions delimiter(String delimiter) {\n         return new ListObjectOptions().delimiter(delimiter);\n      }\n\n      public ListObjectOptions prefix(String prefix) {\n         return new ListObjectOptions().prefix(prefix);\n      }\n\n      public ListObjectOptions versions(Boolean versions) {\n         return new ListObjectOptions().versions(versions);\n      }\n\n      public ListObjectOptions pageToken(String pageToken) {\n         return new ListObjectOptions().pageToken(pageToken);\n      }\n\n      public ListObjectOptions maxResults(Integer maxResults) {\n         return new ListObjectOptions().maxResults(maxResults);\n      }\n\n      public ListObjectOptions projection(Projection projection) {\n         return new ListObjectOptions().projection(projection);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/options/ListOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.Projection;\n\npublic class ListOptions extends org.jclouds.googlecloud.options.ListOptions {\n\n   public ListOptions pageToken(String pageToken) {\n      this.queryParameters.put(\"pageToken\", checkNotNull(pageToken, \"pageToken\"));\n      return this;\n   }\n\n   @Override public ListOptions maxResults(Integer maxResults) {\n      return (ListOptions) super.maxResults(maxResults);\n   }\n\n   public ListOptions projection(Projection projection) {\n      this.queryParameters.put(\"projection\", checkNotNull(projection, \"projection\").toString());\n      return this;\n   }\n\n   public static class Builder {\n\n      public ListOptions pageToken(String pageToken) {\n         return new ListOptions().pageToken(pageToken);\n      }\n\n      public ListOptions maxResults(Integer maxResults) {\n         return new ListOptions().maxResults(maxResults);\n      }\n\n      public ListOptions projection(Projection projection) {\n         return new ListOptions().projection(projection);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/options/RewriteObjectOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.PredefinedAcl;\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.Projection;\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\n/**\n * Allows to optionally specify ifMetagenerationMatch,ifMetagenerationNotMatch and projection which used in Bucket\n */\npublic class RewriteObjectOptions extends BaseHttpRequestOptions {\n\n   // TODO(broudy): Refactor these redundant options out of every options class.\n\n   public RewriteObjectOptions ifGenerationMatch(Long ifGenerationMatch) {\n      this.queryParameters.put(\"ifGenerationMatch\", checkNotNull(ifGenerationMatch, \"ifGenerationMatch\") + \"\");\n      return this;\n   }\n\n   public RewriteObjectOptions ifGenerationNotMatch(Long ifGenerationNotMatch) {\n      this.queryParameters.put(\"ifGenerationNotMatch\", checkNotNull(ifGenerationNotMatch, \"ifGenerationNotMatch\") + \"\");\n      return this;\n   }\n\n   public RewriteObjectOptions ifMetagenerationMatch(Long ifMetagenerationMatch) {\n      this.queryParameters.put(\"ifMetagenerationMatch\", checkNotNull(ifMetagenerationMatch, \"ifMetagenerationMatch\")\n               + \"\");\n      return this;\n   }\n\n   public RewriteObjectOptions ifMetagenerationNotMatch(Long ifMetagenerationNotMatch) {\n      this.queryParameters.put(\"ifMetagenerationNotMatch\",\n               checkNotNull(ifMetagenerationNotMatch, \"ifMetagenerationNotMatch\") + \"\");\n      return this;\n   }\n   public RewriteObjectOptions ifSourceGenerationMatch(Long ifSourceGenerationMatch) {\n      this.queryParameters.put(\"ifSourceGenerationMatch\", checkNotNull(ifSourceGenerationMatch, \"ifSourceGenerationMatch\") + \"\");\n      return this;\n   }\n\n   public RewriteObjectOptions ifSourceGenerationNotMatch(Long ifSourceGenerationNotMatch) {\n      this.queryParameters.put(\"ifSourceGenerationNotMatch\", checkNotNull(ifSourceGenerationNotMatch, \"ifSourceGenerationNotMatch\") + \"\");\n      return this;\n   }\n\n   public RewriteObjectOptions ifSourceMetagenerationMatch(Long ifSourceMetagenerationMatch) {\n      this.queryParameters.put(\"ifSourceMetagenerationMatch\", checkNotNull(ifSourceMetagenerationMatch, \"ifSourceMetagenerationMatch\")\n               + \"\");\n      return this;\n   }\n\n   public RewriteObjectOptions ifSourceMetagenerationNotMatch(Long ifSourceMetagenerationNotMatch) {\n      this.queryParameters.put(\"ifSourceMetagenerationNotMatch\",\n               checkNotNull(ifSourceMetagenerationNotMatch, \"ifSourceMetagenerationNotMatch\") + \"\");\n      return this;\n   }\n\n   public RewriteObjectOptions sourceGeneration(Long sourceGeneration) {\n      this.queryParameters.put(\"sourceGeneration\", checkNotNull(sourceGeneration, \"sourceGeneration\") + \"\");\n      return this;\n   }\n\n   public RewriteObjectOptions predefinedAcl(PredefinedAcl predefinedAcl) {\n      this.queryParameters.put(\"predefinedAcl\", checkNotNull(predefinedAcl, \"predefinedAcl\").toString());\n      return this;\n   }\n\n   public RewriteObjectOptions projection(Projection projection) {\n      this.queryParameters.put(\"projection\", checkNotNull(projection, \"projection\").toString());\n      return this;\n   }\n\n   public RewriteObjectOptions rewriteToken(String rewriteToken) {\n      this.queryParameters.put(\"rewriteToken\", checkNotNull(rewriteToken, \"rewriteToken\").toString());\n      return this;\n   }\n\n   public RewriteObjectOptions maxBytesRewrittenPerCall(Long maxBytesRewrittenPerCall) {\n      this.queryParameters.put(\"maxBytesRewrittenPerCall\",\n            checkNotNull(maxBytesRewrittenPerCall, \"maxBytesRewrittenPerCall\").toString());\n      return this;\n   }\n\n   public static class Builder {\n\n      public RewriteObjectOptions ifGenerationMatch(Long ifGenerationMatch) {\n         return new RewriteObjectOptions().ifGenerationMatch(ifGenerationMatch);\n      }\n\n      public RewriteObjectOptions ifGenerationNotMatch(Long ifGenerationNotMatch) {\n         return new RewriteObjectOptions().ifGenerationNotMatch(ifGenerationNotMatch);\n      }\n\n      public RewriteObjectOptions ifMetagenerationMatch(Long ifMetagenerationMatch) {\n         return new RewriteObjectOptions().ifMetagenerationMatch(ifMetagenerationMatch);\n      }\n\n      public RewriteObjectOptions ifMetagenerationNotMatch(Long ifMetagenerationNotMatch) {\n         return new RewriteObjectOptions().ifMetagenerationNotMatch(ifMetagenerationNotMatch);\n      }\n\n      public RewriteObjectOptions ifSourceGenerationMatch(Long ifSourceGenerationMatch) {\n         return new RewriteObjectOptions().ifSourceGenerationMatch(ifSourceGenerationMatch);\n      }\n\n      public RewriteObjectOptions ifSourceGenerationNotMatch(Long ifSourceGenerationNotMatch) {\n         return new RewriteObjectOptions().ifSourceGenerationNotMatch(ifSourceGenerationNotMatch);\n      }\n\n      public RewriteObjectOptions ifSourceMetagenerationMatch(Long ifSourceMetagenerationMatch) {\n         return new RewriteObjectOptions().ifSourceMetagenerationMatch(ifSourceMetagenerationMatch);\n      }\n\n      public RewriteObjectOptions ifSourceMetagenerationNotMatch(Long ifSourceMetagenerationNotMatch) {\n         return new RewriteObjectOptions().ifSourceMetagenerationNotMatch(ifSourceMetagenerationNotMatch);\n      }\n\n      public RewriteObjectOptions sourceGeneration(Long sourceGeneration) {\n         return new RewriteObjectOptions().sourceGeneration(sourceGeneration);\n      }\n\n      public RewriteObjectOptions predefinedAcl(PredefinedAcl predefinedAcl) {\n         return new RewriteObjectOptions().predefinedAcl(predefinedAcl);\n      }\n\n      public RewriteObjectOptions projection(Projection projection) {\n         return new RewriteObjectOptions().projection(projection);\n      }\n\n      public RewriteObjectOptions rewriteToken(String rewriteToken) {\n         return new RewriteObjectOptions().rewriteToken(rewriteToken);\n      }\n\n      public RewriteObjectOptions maxBytesRewrittenPerCall(Long maxBytesRewrittenPerCall) {\n         return new RewriteObjectOptions().maxBytesRewrittenPerCall(maxBytesRewrittenPerCall);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/options/UpdateBucketOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.PredefinedAcl;\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.Projection;\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\n/**\n * Allows to optionally specify ifMetagenerationMatch,ifMetagenerationNotMatch and projection which used in Bucket\n */\npublic class UpdateBucketOptions extends BaseHttpRequestOptions {\n\n   public UpdateBucketOptions ifMetagenerationMatch(Long ifMetagenerationMatch) {\n      this.queryParameters.put(\"ifMetagenerationMatch\", checkNotNull(ifMetagenerationMatch, \"ifMetagenerationMatch\")\n               + \"\");\n      return this;\n   }\n\n   public UpdateBucketOptions ifMetagenerationNotMatch(Long ifMetagenerationNotMatch) {\n      this.queryParameters.put(\"ifMetagenerationNotMatch\",\n               checkNotNull(ifMetagenerationNotMatch, \"ifMetagenerationNotMatch\") + \"\");\n      return this;\n   }\n\n   public UpdateBucketOptions projection(Projection projection) {\n      this.queryParameters.put(\"projection\", checkNotNull(projection, \"projection\").toString());\n      return this;\n   }\n\n   public UpdateBucketOptions predefinedAcl(PredefinedAcl predefinedAcl) {\n      this.queryParameters.put(\"predefinedAcl\", checkNotNull(predefinedAcl, \"predefinedAcl\").toString());\n      return this;\n   }\n\n   public static class Builder {\n\n      public UpdateBucketOptions ifMetagenerationMatch(Long ifMetagenerationMatch) {\n         return new UpdateBucketOptions().ifMetagenerationMatch(ifMetagenerationMatch);\n      }\n\n      public UpdateBucketOptions ifMetagenerationNotMatch(Long ifMetagenerationNotMatch) {\n         return new UpdateBucketOptions().ifMetagenerationNotMatch(ifMetagenerationNotMatch);\n      }\n\n      public UpdateBucketOptions projection(Projection projection) {\n         return new UpdateBucketOptions().projection(projection);\n      }\n\n      public UpdateBucketOptions predefinedAcl(PredefinedAcl predefinedAcl) {\n         return new UpdateBucketOptions().predefinedAcl(predefinedAcl);\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/options/UpdateObjectOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.PredefinedAcl;\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.Projection;\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\n/**\n * Allows to optionally specify ifMetagenerationMatch,ifMetagenerationNotMatch and projection which used in Bucket\n */\npublic class UpdateObjectOptions extends BaseHttpRequestOptions {\n\n   public UpdateObjectOptions ifGenerationMatch(Long ifGenerationMatch) {\n      this.queryParameters.put(\"ifGenerationMatch\", checkNotNull(ifGenerationMatch, \"ifGenerationMatch\")\n               + \"\");\n      return this;\n   }\n\n   public UpdateObjectOptions ifGenerationNotMatch(Long ifGenerationNotMatch) {\n      this.queryParameters.put(\"ifGenerationNotMatch\",\n               checkNotNull(ifGenerationNotMatch, \"ifGenerationNotMatch\") + \"\");\n      return this;\n   }\n\n   public UpdateObjectOptions ifMetagenerationMatch(Long ifMetagenerationMatch) {\n      this.queryParameters.put(\"ifMetagenerationMatch\", checkNotNull(ifMetagenerationMatch, \"ifMetagenerationMatch\")\n               + \"\");\n      return this;\n   }\n\n   public UpdateObjectOptions ifMetagenerationNotMatch(Long ifMetagenerationNotMatch) {\n      this.queryParameters.put(\"ifMetagenerationNotMatch\",\n               checkNotNull(ifMetagenerationNotMatch, \"ifMetagenerationNotMatch\") + \"\");\n      return this;\n   }\n\n   public UpdateObjectOptions generation(Long generation) {\n      this.queryParameters.put(\"generation\", checkNotNull(generation, \"generation\").toString());\n      return this;\n   }\n\n   public UpdateObjectOptions predefinedAcl(PredefinedAcl predefinedAcl) {\n      this.queryParameters.put(\"predefinedAcl\", checkNotNull(predefinedAcl, \"predefinedAcl\").toString());\n      return this;\n   }\n\n\n   public UpdateObjectOptions projection(Projection projection) {\n      this.queryParameters.put(\"projection\", checkNotNull(projection, \"projection\").toString());\n      return this;\n   }\n\n   public static class Builder {\n\n      public UpdateObjectOptions ifGenerationMatch(Long ifGenerationMatch) {\n         return new UpdateObjectOptions().ifGenerationMatch(ifGenerationMatch);\n      }\n\n      public UpdateObjectOptions ifGenerationNotMatch(Long ifGenerationNotMatch) {\n         return new UpdateObjectOptions().ifGenerationNotMatch(ifGenerationNotMatch);\n      }\n\n      public UpdateObjectOptions ifMetagenerationMatch(Long ifMetagenerationMatch) {\n         return new UpdateObjectOptions().ifMetagenerationMatch(ifMetagenerationMatch);\n      }\n\n      public UpdateObjectOptions ifMetagenerationNotMatch(Long ifMetagenerationNotMatch) {\n         return new UpdateObjectOptions().ifMetagenerationNotMatch(ifMetagenerationNotMatch);\n      }\n\n      public UpdateObjectOptions generation(Long generation) {\n         return new UpdateObjectOptions().generation(generation);\n      }\n\n      public UpdateObjectOptions predefinedAcl(PredefinedAcl predefinedAcl) {\n         return new UpdateObjectOptions().predefinedAcl(predefinedAcl);\n      }\n\n      public UpdateBucketOptions projection(Projection projection) {\n         return new UpdateBucketOptions().projection(projection);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/parser/ParseToPayloadEnclosing.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.parser;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.internal.PayloadEnclosingImpl;\n\nimport com.google.common.base.Function;\n\npublic class ParseToPayloadEnclosing implements Function<HttpResponse, PayloadEnclosingImpl> {\n\n   @Override\n   public PayloadEnclosingImpl apply(HttpResponse response) {\n      PayloadEnclosingImpl impl = new PayloadEnclosingImpl();\n      impl.setPayload(response.getPayload());\n\n      return impl;\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/parser/ParseToResumableUpload.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.parser;\n\nimport static com.google.common.base.Preconditions.checkArgument;\n\nimport java.util.regex.Pattern;\n\nimport org.jclouds.googlecloudstorage.domain.ResumableUpload;\nimport org.jclouds.http.HttpResponse;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Splitter;\n\npublic class ParseToResumableUpload implements Function<HttpResponse, ResumableUpload> {\n\n   @Override\n   public ResumableUpload apply(HttpResponse response) {\n\n      String contentLength = response.getFirstHeaderOrNull(\"Content-Length\");\n      String sessionUri = response.getFirstHeaderOrNull(\"Location\");\n      String uploadId = null;\n      if (sessionUri != null) {\n         uploadId = getUploadId(sessionUri);\n      }\n      String range = response.getFirstHeaderOrNull(\"Range\");\n      Long upperLimit = null;\n      Long lowerLimit = null;\n      if (range != null) {\n         upperLimit = getUpperLimitFromRange(range);\n         lowerLimit = getLowerLimitFromRange(range);\n         if (lowerLimit != null && upperLimit != null) {\n            checkArgument(lowerLimit < upperLimit, \"lower range must less than upper range, was: %s - %s\", lowerLimit,\n                  upperLimit);\n         }\n      }\n\n      return ResumableUpload.create(response.getStatusCode(), uploadId, contentLength, lowerLimit, upperLimit);\n   }\n\n   // Return the Id of the Upload\n   private String getUploadId(String sessionUri) {\n      // TODO: better way to parse query parameters?\n      return Splitter.on(Pattern.compile(\"\\\\&\")).trimResults().omitEmptyStrings().withKeyValueSeparator(\"=\")\n            .split(sessionUri).get(\"upload_id\");\n   }\n\n   private long getUpperLimitFromRange(String range) {\n      String upperLimit = range.split(\"-\")[1];\n      return Long.parseLong(upperLimit);\n   }\n\n   private long getLowerLimitFromRange(String range) {\n      String removeByte = range.split(\"=\")[1];\n      String lowerLimit = removeByte.split(\"-\")[0];\n      return Long.parseLong(lowerLimit);\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/main/java/org/jclouds/googlecloudstorage/reference/GoogleCloudStorageConstants.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.reference;\n\nimport com.google.common.annotations.Beta;\n\npublic final class GoogleCloudStorageConstants {\n\n   private GoogleCloudStorageConstants() {\n   }\n\n   /**\n    * The total time, in msecs, to wait for an operation to complete.\n    */\n   @Beta\n   public static final String OPERATION_COMPLETE_TIMEOUT = \"jclouds.google-cloud-storage.operation-complete-timeout\";\n\n   /**\n    * The interval, in msecs, between calls to check whether an operation has completed.\n    */\n   @Beta\n   public static final String OPERATION_COMPLETE_INTERVAL = \"jclouds.google-cloud-storage.operation-complete-interval\";\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/java/org/jclouds/googlecloudstorage/GoogleCloudStorageProviderMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage;\n\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests that GoogleComputeProviderMetadata is properly registered in ServiceLoader\n * <p/>\n * <pre>\n * META-INF/services/org.jclouds.providers.ProviderMetadata\n * </pre>\n */\n@Test(groups = \"unit\", testName = \"GoogleCloudStorageProviderMetadataTest\")\npublic class GoogleCloudStorageProviderMetadataTest extends BaseProviderMetadataTest {\n   public GoogleCloudStorageProviderMetadataTest() {\n      super(new GoogleCloudStorageProviderMetadata(), new GoogleCloudStorageApiMetadata());\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/java/org/jclouds/googlecloudstorage/blobstore/integration/GoogleCloudStorageBlobIntegrationLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.blobstore.integration;\n\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.assertj.core.api.Fail.failBecauseExceptionWasNotThrown;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Properties;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.domain.BlobBuilder.PayloadBlobBuilder;\nimport org.jclouds.blobstore.domain.BlobMetadata;\nimport org.jclouds.blobstore.domain.PageSet;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.integration.internal.BaseBlobIntegrationTest;\nimport org.jclouds.blobstore.options.PutOptions;\nimport org.jclouds.googlecloud.config.CurrentProject;\nimport org.jclouds.googlecloud.internal.TestProperties;\nimport org.jclouds.googlecloudstorage.GoogleCloudStorageApi;\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.Location;\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.StorageClass;\nimport org.jclouds.googlecloudstorage.domain.templates.BucketTemplate;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.io.payloads.ByteSourcePayload;\nimport org.jclouds.utils.TestUtils;\nimport org.testng.SkipException;\nimport org.testng.annotations.DataProvider;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.hash.HashCode;\nimport com.google.common.hash.HashFunction;\nimport com.google.common.hash.Hashing;\nimport com.google.common.io.ByteSource;\nimport com.google.common.io.Files;\n\n@Test(groups = { \"live\", \"blobstorelive\" })\npublic class GoogleCloudStorageBlobIntegrationLiveTest extends BaseBlobIntegrationTest {\n\n   private final String PROJECT_NUMBER;\n   private long PART_SIZE = 5L * 1024L * 1024L;\n\n   @Override\n   protected long getMinimumMultipartBlobSize() {\n      return PART_SIZE + 1;\n   }\n\n   public GoogleCloudStorageBlobIntegrationLiveTest() throws IOException {\n      provider = \"google-cloud-storage\";\n      PROJECT_NUMBER = CurrentProject.ClientEmail.toProjectNumber(System.getProperty(\"test.google-cloud-storage.identity\"));\n   }\n\n   @Override protected Properties setupProperties() {\n      TestProperties.setGoogleCredentialsFromJson(provider);\n      Properties properties = super.setupProperties();\n      properties.put(\"jclouds.mpu.parts.size\", 2 * 1024 * 1024);\n      return TestProperties.apply(provider, properties);\n   }\n\n   @Override\n   @Test(enabled = false)\n   public void testGetTwoRanges() throws SkipException {\n      // not supported in GoogleCloudStorage\n   }\n\n   @Override\n   @Test(enabled = false)\n   public void testGetRange() throws SkipException {\n      // not supported in GoogleCloudStorage\n   }\n\n   @Override\n   @Test(enabled = false)\n   public void testCreateBlobWithExpiry() throws SkipException {\n      // not supported in object level.\n   }\n\n   @Override\n   @Test(groups = { \"integration\", \"live\" }, dataProvider = \"gcsPutTest\")\n   public void testPutObject(String name, String type, Object content, Object realObject) throws InterruptedException,\n            IOException {\n      PayloadBlobBuilder blobBuilder = view.getBlobStore().blobBuilder(name).payload(Payloads.newPayload(content))\n               .contentType(type);\n      addContentMetadata(blobBuilder);\n      Blob blob = blobBuilder.build();\n      blob.getPayload().setContentMetadata(blob.getMetadata().getContentMetadata());\n      String container = getContainerName();\n\n      try {\n         assertNotNull(view.getBlobStore().putBlob(container, blob));\n         blob = view.getBlobStore().getBlob(container, blob.getMetadata().getName());\n         validateMetadata(blob.getMetadata(), container, name);\n         checkContentMetadata(blob);\n\n         String returnedString = getContentAsStringOrNullAndClose(blob);\n         assertEquals(returnedString, realObject);\n         PageSet<? extends StorageMetadata> set = view.getBlobStore().list(container);\n         assertThat(set).isNotEmpty();\n      } finally {\n         returnContainer(container);\n      }\n   }\n\n   @Override\n   protected void addContentMetadata(PayloadBlobBuilder blobBuilder) {\n      blobBuilder.contentType(\"text/csv\");\n      blobBuilder.contentDisposition(\"attachment; filename=photo.jpg\");\n      // TODO: causes failures with subsequent GET operations:\n      // HTTP/1.1 failed with response: HTTP/1.1 503 Service Unavailable; content: [Service Unavailable]\n      //blobBuilder.contentEncoding(\"gzip\");\n      blobBuilder.contentLanguage(\"en\");\n   }\n\n   @Override\n   protected void checkContentMetadata(Blob blob) {\n      checkContentType(blob, \"text/csv\");\n      checkContentDisposition(blob, \"attachment; filename=photo.jpg\");\n      //checkContentEncoding(blob, \"gzip\");\n      checkContentLanguage(blob, \"en\");\n   }\n\n   @DataProvider(name = \"gcsPutTest\")\n   public Object[][] createData1() throws IOException {\n      File file = new File(\"pom.xml\");\n      String realObject = Files.toString(file, Charsets.UTF_8);\n\n      return new Object[][] { { \"file.xml\", \"text/xml\", file, realObject },\n               { \"string.xml\", \"text/xml\", realObject, realObject },\n               { \"stringwith/slash.xml\", \"text/xml\", realObject, realObject },\n               { \"bytes.xml\", \"application/octet-stream\", realObject.getBytes(), realObject } };\n   }\n\n   // Content-Length should not be null\n   @Override\n   public void testPutObjectStream() throws InterruptedException, IOException, java.util.concurrent.ExecutionException {\n\n      ByteSource byteSource = ByteSource.wrap(\"foo\".getBytes());\n      ByteSourcePayload payload = new ByteSourcePayload(byteSource);\n      PayloadBlobBuilder blobBuilder = view.getBlobStore().blobBuilder(\"streaming\").payload(payload)\n               .contentLength(byteSource.read().length);\n      addContentMetadata(blobBuilder);\n\n      Blob blob = blobBuilder.build();\n      String container = getContainerName();\n\n      try {\n         assertNotNull(view.getBlobStore().putBlob(container, blob));\n\n         blob = view.getBlobStore().getBlob(container, blob.getMetadata().getName());\n         String returnedString = getContentAsStringOrNullAndClose(blob);\n         assertEquals(returnedString, \"foo\");\n         validateMetadata(blob.getMetadata(), container, blob.getMetadata().getName());\n         checkContentMetadata(blob);\n         PageSet<? extends StorageMetadata> set = view.getBlobStore().list(container);\n         assertThat(set).isNotEmpty();\n      } finally {\n         returnContainer(container);\n      }\n   };\n\n   @Override\n   public void testMetadata() throws InterruptedException, IOException {\n      String name = \"hello\";\n\n      HashFunction hf = Hashing.md5();\n      HashCode md5 = hf.newHasher().putString(TEST_STRING, Charsets.UTF_8).hash();\n      Blob blob = view.getBlobStore().blobBuilder(name).userMetadata(ImmutableMap.of(\"adrian\", \"powderpuff\"))\n               .payload(TEST_STRING).contentType(MediaType.TEXT_PLAIN).contentMD5(md5).build();\n      String container = getContainerName();\n      try {\n         assertNull(view.getBlobStore().blobMetadata(container, \"powderpuff\"));\n\n         addBlobToContainer(container, blob);\n         Blob newObject = validateContent(container, name);\n\n         BlobMetadata metadata = newObject.getMetadata();\n\n         validateMetadata(metadata);\n         validateMetadata(metadata, container, name);\n         validateMetadata(view.getBlobStore().blobMetadata(container, name));\n\n         blob.getMetadata().getUserMetadata().put(\"adrian\", \"wonderpuff\");\n         blob.getMetadata().getUserMetadata().put(\"adrian\", \"powderpuff\");\n\n         addBlobToContainer(container, blob);\n         validateMetadata(view.getBlobStore().blobMetadata(container, name));\n\n      } finally {\n         returnContainer(container);\n      }\n   }\n\n   @Override\n   protected void checkMD5(BlobMetadata metadata) throws IOException {\n      HashCode md5 = Hashing.md5().hashString(TEST_STRING, Charsets.UTF_8);\n      assertEquals(metadata.getContentMetadata().getContentMD5AsHashCode(), md5);\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testMultipartChunkedFileStream() throws IOException, InterruptedException {\n      String containerName = getContainerName();\n      try {\n         BlobStore blobStore = view.getBlobStore();\n         long countBefore = blobStore.countBlobs(containerName);\n\n         addMultipartBlobToContainer(containerName, \"const.txt\");\n\n         long countAfter = blobStore.countBlobs(containerName);\n         assertThat(countAfter).isEqualTo(countBefore + 1);\n      } finally {\n         returnContainer(containerName);\n      }\n   }\n\n   protected void addMultipartBlobToContainer(String containerName, String key) throws IOException {\n      ByteSource sourceToUpload = TestUtils.randomByteSource().slice(0, PART_SIZE + 1);\n\n      BlobStore blobStore = view.getBlobStore();\n      blobStore.createContainerInLocation(null, containerName);\n      Blob blob = blobStore.blobBuilder(key).payload(sourceToUpload).contentLength(sourceToUpload.size())\n               .contentType(MediaType.TEXT_PLAIN).build();\n      blobStore.putBlob(containerName, blob, PutOptions.Builder.multipart());\n   }\n\n   @DataProvider(name = \"delete\")\n   public Object[][] createData() {\n      if (System.getProperty(\"os.name\").toLowerCase().contains(\"windows\")) {\n         return new Object[][] { { \"normal\" }, { \"sp ace\" } };\n      } else {\n         return new Object[][] { { \"normal\" }, { \"sp ace\" }, { \"qu?stion\" }, { \"path/foo\" }, { \"colon:\" },\n                  { \"asteri*k\" }, { \"quote\\\"\" }, { \"{great<r}\" }, { \"lesst>en\" }, { \"p|pe\" } };\n      }\n   }\n\n   // Remove \"unic₪de\" from DataProvider\n   @Override\n   @Test(groups = { \"integration\", \"live\" }, dataProvider = \"delete\")\n   public void deleteObject(String name) throws InterruptedException {\n      super.deleteObject(name);\n   }\n\n   @Override\n   @Test(expectedExceptions = UnsupportedOperationException.class)\n   public void testCopyIfMatch() throws Exception {\n      super.testCopyIfMatch();\n   }\n\n   @Override\n   @Test(expectedExceptions = UnsupportedOperationException.class)\n   public void testCopyIfMatchNegative() throws Exception {\n      super.testCopyIfMatch();\n   }\n\n   @Override\n   @Test(expectedExceptions = UnsupportedOperationException.class)\n   public void testCopyIfNoneMatch() throws Exception {\n      super.testCopyIfNoneMatch();\n   }\n\n   @Override\n   @Test(expectedExceptions = UnsupportedOperationException.class)\n   public void testCopyIfNoneMatchNegative() throws Exception {\n      super.testCopyIfNoneMatch();\n   }\n\n   @Override\n   @Test(expectedExceptions = UnsupportedOperationException.class)\n   public void testCopyIfModifiedSince() throws Exception {\n      super.testCopyIfModifiedSince();\n   }\n\n   @Override\n   @Test(expectedExceptions = UnsupportedOperationException.class)\n   public void testCopyIfModifiedSinceNegative() throws Exception {\n      super.testCopyIfModifiedSince();\n   }\n\n   @Override\n   @Test(expectedExceptions = UnsupportedOperationException.class)\n   public void testCopyIfUnmodifiedSince() throws Exception {\n      super.testCopyIfUnmodifiedSince();\n   }\n\n   @Override\n   @Test(expectedExceptions = UnsupportedOperationException.class)\n   public void testCopyIfUnmodifiedSinceNegative() throws Exception {\n      super.testCopyIfUnmodifiedSince();\n   }\n\n   @Override\n   public void testListMultipartUploads() throws Exception {\n      try {\n         super.testListMultipartUploads();\n      } catch (UnsupportedOperationException uoe) {\n         throw new SkipException(\"GCS does not support listing multipart uploads\", uoe);\n      }\n   }\n\n   @Override\n   public void testPutBlobTierArchiveMultipart() throws Exception {\n      try {\n         super.testPutBlobTierArchiveMultipart();\n         failBecauseExceptionWasNotThrown(AssertionError.class);\n      } catch (AssertionError ae) {\n         throw new SkipException(\"GCS does not report storage class of composed objects\", ae);\n      }\n   }\n\n   @Override\n   public void testPutBlobTierInfrequentMultipart() throws Exception {\n      try {\n         super.testPutBlobTierInfrequentMultipart();\n         failBecauseExceptionWasNotThrown(AssertionError.class);\n      } catch (AssertionError ae) {\n         throw new SkipException(\"GCS does not report storage class of composed objects\", ae);\n      }\n   }\n\n   @Test(groups = { \"integration\", \"live\" })\n   public void testMultipartUploadSinglePartMultiRegional() throws Exception {\n      String containerName = \"jclouds-multiregional\";\n      BucketTemplate template = new BucketTemplate()\n            .name(containerName)\n            .location(Location.US)\n            .storageClass(StorageClass.COLDLINE);\n      GoogleCloudStorageApi api = view.unwrapApi(GoogleCloudStorageApi.class);\n      api.getBucketApi().createBucket(PROJECT_NUMBER, template);\n      String blobName = \"multiregional-blobname\";\n\n      try {\n         long length = 32 * 1024L;\n         ByteSource byteSource = TestUtils.randomByteSource().slice(0, length);\n         Blob blob = view.getBlobStore().blobBuilder(blobName)\n                 .payload(byteSource)\n                 .contentLength(length)\n                 .build();\n         view.getBlobStore().putBlob(containerName, blob, new PutOptions().multipart(true));\n      } finally {\n         view.getBlobStore().removeBlob(containerName, blobName);\n         api.getBucketApi().deleteBucket(containerName);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/java/org/jclouds/googlecloudstorage/blobstore/integration/GoogleCloudStorageBlobLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.blobstore.integration;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.io.IOException;\nimport java.util.Properties;\n\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.blobstore.domain.Blob;\nimport org.jclouds.blobstore.integration.internal.BaseBlobLiveTest;\nimport org.jclouds.googlecloud.internal.TestProperties;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.internal.PayloadEnclosingImpl;\nimport org.jclouds.io.ByteStreams2;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.io.payloads.ByteSourcePayload;\nimport org.jclouds.utils.TestUtils;\nimport org.testng.annotations.Parameters;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.hash.HashCode;\nimport com.google.common.hash.Hashing;\nimport com.google.common.io.BaseEncoding;\nimport com.google.common.io.ByteSource;\n\n@Test(groups = { \"live\" })\npublic class GoogleCloudStorageBlobLiveTest extends BaseBlobLiveTest {\n   private static final String sysHttpStreamUrl = System.getProperty(\"jclouds.blobstore.httpstream.url\");\n   private static final String sysHttpStreamMD5 = System.getProperty(\"jclouds.blobstore.httpstream.md5\");\n\n   public GoogleCloudStorageBlobLiveTest() {\n      provider = \"google-cloud-storage\";\n   }\n\n   @Override protected Properties setupProperties() {\n      TestProperties.setGoogleCredentialsFromJson(provider);\n      return TestProperties.apply(provider, super.setupProperties());\n   }\n\n   @Override\n   @Parameters({ \"jclouds.blobstore.httpstream.url\", \"jclouds.blobstore.httpstream.md5\" })\n   public void testCopyUrl(String httpStreamUrl, String httpStreamMD5) throws Exception {\n      httpStreamUrl = checkNotNull(httpStreamUrl != null ? httpStreamUrl : sysHttpStreamUrl, \"httpStreamUrl\");\n      httpStreamMD5 = checkNotNull(httpStreamMD5 != null ? httpStreamMD5 : sysHttpStreamMD5, \"httpStreamMd5\");\n\n      HttpResponse response = view.utils().http()\n               .invoke(HttpRequest.builder().method(\"GET\").endpoint(httpStreamUrl).build());\n      long length = response.getPayload().getContentMetadata().getContentLength();\n\n      checkNotNull(response.getPayload().getContentMetadata().getContentType());\n      assertEquals(response.getPayload().getContentMetadata().getContentType(), \"application/x-gzip\");\n\n      String name = \"hello\";\n      HashCode md5 = HashCode.fromBytes(BaseEncoding.base16().lowerCase().decode(httpStreamMD5));\n      byte[] payload = ByteStreams2.toByteArrayAndClose(response.getPayload().getInput());\n\n      Blob blob = view.getBlobStore().blobBuilder(name).payload(payload).contentLength(length)\n               .contentType(response.getPayload().getContentMetadata().getContentType())\n               .contentMD5(md5).build();\n      String container = getContainerName();\n      try {\n         assertNotNull(view.getBlobStore().putBlob(container, blob));\n         checkMD5(container, name, md5.asBytes());\n      } finally {\n         returnContainer(container);\n      }\n   }\n\n   @Test(groups = \"live\")\n   public void testPutBlobWithMd5() throws IOException, InterruptedException {\n      String containerName = getContainerName();\n      String blobName = \"md5test\";\n      try {\n         long contentLength = 32 * 1024L;\n         ByteSource byteSource = TestUtils.randomByteSource().slice(0, contentLength);\n         ByteSourcePayload payload = Payloads.newByteSourcePayload(byteSource);\n         PayloadEnclosingImpl payloadImpl = new PayloadEnclosingImpl(payload);\n\n         BlobStore blobStore = view.getBlobStore();\n\n         // This would trigger server side validation of md5\n         HashCode hcMd5 = byteSource.hash(Hashing.md5());\n\n         Blob blob = blobStore.blobBuilder(blobName).payload(payloadImpl.getPayload()).contentType(\"image/jpeg\")\n                  .contentLength(contentLength).contentLanguage(\"en\").contentDisposition(\"attachment\")\n                  .contentMD5(hcMd5).userMetadata(ImmutableMap.of(\"Adrian\", \"powderpuff\")).build();\n\n         blobStore.putBlob(containerName, blob);\n         checkMD5(containerName, blobName, hcMd5.asBytes());\n\n      } finally {\n         returnContainer(containerName);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/java/org/jclouds/googlecloudstorage/blobstore/integration/GoogleCloudStorageBlobSignerLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.blobstore.integration;\n\nimport org.jclouds.blobstore.integration.internal.BaseBlobSignerLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = { \"live\" })\npublic class GoogleCloudStorageBlobSignerLiveTest extends BaseBlobSignerLiveTest {\n   public GoogleCloudStorageBlobSignerLiveTest() {\n      provider = \"google-cloud-storage\";\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/java/org/jclouds/googlecloudstorage/blobstore/integration/GoogleCloudStorageContainerIntegrationLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.blobstore.integration;\n\nimport static com.google.common.collect.Iterables.get;\nimport static org.jclouds.blobstore.options.ListContainerOptions.Builder.maxResults;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.util.Properties;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.blobstore.domain.BlobMetadata;\nimport org.jclouds.blobstore.domain.PageSet;\nimport org.jclouds.blobstore.domain.StorageMetadata;\nimport org.jclouds.blobstore.integration.internal.BaseContainerIntegrationTest;\nimport org.jclouds.googlecloud.internal.TestProperties;\nimport org.testng.SkipException;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.hash.Hashing;\n\npublic class GoogleCloudStorageContainerIntegrationLiveTest extends BaseContainerIntegrationTest {\n\n   public GoogleCloudStorageContainerIntegrationLiveTest() {\n      provider = \"google-cloud-storage\";\n   }\n\n   @Override protected Properties setupProperties() {\n      TestProperties.setGoogleCredentialsFromJson(provider);\n      return TestProperties.apply(provider, super.setupProperties());\n   }\n\n   @Override\n   @Test(groups = { \"integration\", \"live\" })\n   public void testWithDetails() throws InterruptedException, IOException {\n      String key = \"hello\";\n      String containerName = getContainerName();\n      try {\n         addBlobToContainer(\n                  containerName,\n                  view.getBlobStore().blobBuilder(key).userMetadata(ImmutableMap.of(\"adrian\", \"powderpuff\"))\n                           .payload(TEST_STRING).contentType(MediaType.TEXT_PLAIN)\n                           .contentMD5(Hashing.md5().newHasher().putString(TEST_STRING, Charsets.UTF_8).hash()).build());\n         validateContent(containerName, key);\n\n         PageSet<? extends StorageMetadata> container = view.getBlobStore().list(containerName,\n                  maxResults(1).withDetails());\n\n         BlobMetadata metadata = BlobMetadata.class.cast(get(container, 0));\n\n         assert metadata.getContentMetadata().getContentType().startsWith(\"text/plain\") : metadata.getContentMetadata()\n                  .getContentType();\n         assertEquals(metadata.getContentMetadata().getContentLength(), Long.valueOf(TEST_STRING.length()));\n         assertEquals(metadata.getUserMetadata().get(\"adrian\"), \"powderpuff\");\n         checkMD5(metadata);\n      } finally {\n         returnContainer(containerName);\n      }\n   }\n\n   @Override\n   public void testDirectory() throws InterruptedException {\n      // TODO: testDirectory fails when querying blob with name \"directory/directory\"; querying \"directory%2Fdirectory\"\n      // succeeds, however. I believe this is an escaping issue that should be addressed.\n      throw new SkipException(\"directories are not supported in GoogleCloudStorage\");\n   }\n\n   @Override\n   public void testListMarkerAfterLastKey() throws Exception {\n      throw new SkipException(\"cannot specify arbitrary markers\");\n   }\n\n   @Override\n   public void testListMarkerPrefix() throws Exception {\n      throw new SkipException(\"cannot specify arbitrary markers\");\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/java/org/jclouds/googlecloudstorage/blobstore/integration/GoogleCloudStorageContainerLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.blobstore.integration;\n\nimport java.util.Properties;\n\nimport org.jclouds.blobstore.integration.internal.BaseContainerLiveTest;\nimport org.jclouds.googlecloud.internal.TestProperties;\nimport org.testng.annotations.Test;\n\n@Test(groups = { \"live\" })\npublic class GoogleCloudStorageContainerLiveTest extends BaseContainerLiveTest {\n\n   public GoogleCloudStorageContainerLiveTest() {\n      provider = \"google-cloud-storage\";\n   }\n\n   @Override protected Properties setupProperties() {\n      TestProperties.setGoogleCredentialsFromJson(provider);\n      return TestProperties.apply(provider, super.setupProperties());\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/java/org/jclouds/googlecloudstorage/features/BucketAccessControlsApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.googlecloudstorage.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.AssertJUnit.assertNull;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.googlecloudstorage.domain.BucketAccessControls.Role;\nimport org.jclouds.googlecloudstorage.domain.templates.BucketAccessControlsTemplate;\nimport org.jclouds.googlecloudstorage.internal.BaseGoogleCloudStorageApiExpectTest;\nimport org.jclouds.googlecloudstorage.parse.BucketAclGetTest;\nimport org.jclouds.googlecloudstorage.parse.BucketAclInsertTest;\nimport org.jclouds.googlecloudstorage.parse.BucketAclListTest;\nimport org.jclouds.googlecloudstorage.parse.BucketAclUpdateTest;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"BucketAccessControlsApiExpectTest\")\npublic class BucketAccessControlsApiExpectTest extends BaseGoogleCloudStorageApiExpectTest {\n\n   private static final String EXPECTED_TEST_BUCKET = \"jcloudstestbucket\";\n\n   public static final HttpRequest GET_BUCKETACL_REQUEST = HttpRequest.builder().method(\"GET\")\n            .endpoint(\"https://www.googleapis.com/storage/v1/b/jcloudstestbucket/acl/allUsers\")\n            .addHeader(\"Accept\", \"application/json\").addHeader(\"Authorization\", \"Bearer \" + TOKEN).build();\n\n   private final HttpResponse GET_BUCKETACL_RESPONSE = HttpResponse.builder().statusCode(200)\n            .payload(staticPayloadFromResource(\"/bucket_acl_get.json\")).build();\n\n   private final HttpResponse CREATE_BUCKETACL_RESPONSE = HttpResponse.builder().statusCode(200)\n            .payload(staticPayloadFromResource(\"/bucket_acl_insert_response.json\")).build();\n\n   private final HttpRequest LIST_BUCKETACL_REQUEST = HttpRequest.builder().method(\"GET\")\n            .endpoint(\"https://www.googleapis.com/storage/v1/b/jcloudstestbucket/acl\")\n            .addHeader(\"Accept\", \"application/json\").addHeader(\"Authorization\", \"Bearer \" + TOKEN).build();\n\n   private final HttpResponse LIST_BUCKETACL_RESPONSE = HttpResponse.builder().statusCode(200)\n            .payload(staticPayloadFromResource(\"/bucket_acl_list.json\")).build();\n\n   // Test getBucketAccessControls\n   public void testGetBucketAclResponseIs2xx() throws Exception {\n\n      BucketAccessControlsApi api = requestsSendResponses(requestForScopes(STORAGE_FULLCONTROL_SCOPE), TOKEN_RESPONSE,\n               GET_BUCKETACL_REQUEST, GET_BUCKETACL_RESPONSE).getBucketAccessControlsApi();\n\n      assertEquals(api.getBucketAccessControls(EXPECTED_TEST_BUCKET, \"allUsers\"), new BucketAclGetTest().expected());\n   }\n\n   public void testGetBucketAclResponseIs4xx() throws Exception {\n\n      HttpResponse getResponse = HttpResponse.builder().statusCode(404).build();\n\n      BucketAccessControlsApi api = requestsSendResponses(requestForScopes(STORAGE_FULLCONTROL_SCOPE), TOKEN_RESPONSE,\n               GET_BUCKETACL_REQUEST, getResponse).getBucketAccessControlsApi();\n\n      assertNull(\"404\", api.getBucketAccessControls(EXPECTED_TEST_BUCKET, \"allUsers\"));\n\n   }\n\n   // Test listBucketAccessControls\n   public void testListBucketAclResponseIs2xx() throws Exception {\n\n      BucketAccessControlsApi api = requestsSendResponses(requestForScopes(STORAGE_FULLCONTROL_SCOPE), TOKEN_RESPONSE,\n               LIST_BUCKETACL_REQUEST, LIST_BUCKETACL_RESPONSE).getBucketAccessControlsApi();\n\n      assertEquals(api.listBucketAccessControls(EXPECTED_TEST_BUCKET), new BucketAclListTest().expected());\n\n   }\n\n   public void testListBucketAclResponseIs4xx() throws Exception {\n      HttpResponse listResponse = HttpResponse.builder().statusCode(404).build();\n\n      BucketAccessControlsApi api = requestsSendResponses(requestForScopes(STORAGE_FULLCONTROL_SCOPE), TOKEN_RESPONSE,\n               LIST_BUCKETACL_REQUEST, listResponse).getBucketAccessControlsApi();\n\n      assertNull(api.listBucketAccessControls(\"jcloudstestbucket\"));\n   }\n\n   // Test insertBucketAccessControls\n   public void testInsertBucketAclResponseIs2xx() throws Exception {\n      HttpRequest insertRequest = HttpRequest\n               .builder()\n               .method(\"POST\")\n               .endpoint(\"https://www.googleapis.com/storage/v1/b/jcloudstestbucket/acl\")\n               .addHeader(\"Accept\", \"application/json\")\n               .addHeader(\"Authorization\", \"Bearer \" + TOKEN)\n               .payload(payloadFromResourceWithContentType(\"/bucket_acl_insert_initial.json\",\n                        MediaType.APPLICATION_JSON)).build();\n\n      BucketAccessControlsApi api = requestsSendResponses(requestForScopes(STORAGE_FULLCONTROL_SCOPE), TOKEN_RESPONSE,\n               insertRequest, CREATE_BUCKETACL_RESPONSE).getBucketAccessControlsApi();\n\n      BucketAccessControlsTemplate template = BucketAccessControlsTemplate.create(\"allAuthenticatedUsers\", Role.WRITER);\n\n      assertEquals(api.createBucketAccessControls(EXPECTED_TEST_BUCKET, template), new BucketAclInsertTest().expected());\n   }\n\n   // Test deleteBucketAccessControls\n   public void testDeleteBucketAclResponseIs2xx() throws Exception {\n      HttpRequest delete = HttpRequest.builder().method(\"DELETE\")\n               .endpoint(\"https://www.googleapis.com/storage/v1/b/jcloudstestbucket/acl/allAuthenticatedUsers\")\n               .addHeader(\"Accept\", \"application/json\").addHeader(\"Authorization\", \"Bearer \" + TOKEN).build();\n\n      HttpResponse deleteResponse = HttpResponse.builder().statusCode(204).build();\n\n      BucketAccessControlsApi api = requestsSendResponses(requestForScopes(STORAGE_FULLCONTROL_SCOPE), TOKEN_RESPONSE,\n               delete, deleteResponse).getBucketAccessControlsApi();\n\n      assertEquals(api.deleteBucketAccessControls(EXPECTED_TEST_BUCKET, \"allAuthenticatedUsers\"), deleteResponse);\n   }\n\n   public void testDeleteBucketAclResponseIs4xx() throws Exception {\n      HttpRequest delete = HttpRequest.builder().method(\"DELETE\")\n               .endpoint(\"https://www.googleapis.com/storage/v1/b/jcloudstestbucket/acl/allAuthenticatedUsers\")\n               .addHeader(\"Accept\", \"application/json\").addHeader(\"Authorization\", \"Bearer \" + TOKEN).build();\n\n      HttpResponse deleteResponse = HttpResponse.builder().statusCode(404).build();\n\n      BucketAccessControlsApi api = requestsSendResponses(requestForScopes(STORAGE_FULLCONTROL_SCOPE), TOKEN_RESPONSE,\n               delete, deleteResponse).getBucketAccessControlsApi();\n\n      assertNull(api.deleteBucketAccessControls(EXPECTED_TEST_BUCKET, \"allAuthenticatedUsers\"));\n   }\n\n   // Test updateBucketAccessControls\n   public void testUpdateBucketAclResponseIs2xx() throws Exception {\n      HttpRequest update = HttpRequest\n               .builder()\n               .method(\"PUT\")\n               .endpoint(\"https://www.googleapis.com/storage/v1/b/jcloudstestbucket/acl/allUsers\")\n               .addHeader(\"Accept\", \"application/json\")\n               .addHeader(\"Authorization\", \"Bearer \" + TOKEN)\n               .payload(payloadFromResourceWithContentType(\"/bucket_acl_update_initial.json\",\n                        MediaType.APPLICATION_JSON)).build();\n\n      HttpResponse updateResponse = HttpResponse.builder().statusCode(200)\n               .payload(staticPayloadFromResource(\"/bucket_acl_update_response.json\")).build();\n\n      BucketAccessControlsApi api = requestsSendResponses(requestForScopes(STORAGE_FULLCONTROL_SCOPE), TOKEN_RESPONSE,\n               update, updateResponse).getBucketAccessControlsApi();\n\n      BucketAccessControlsTemplate template = BucketAccessControlsTemplate.create(\"allUsers\", Role.OWNER);\n\n      assertEquals(api.updateBucketAccessControls(EXPECTED_TEST_BUCKET, \"allUsers\", template),\n               new BucketAclUpdateTest().expected());\n   }\n\n   // Test updateBucketAccessControls\n   public void testPatchBucketAclResponseIs2xx() throws Exception {\n      HttpRequest patchRequest = HttpRequest\n               .builder()\n               .method(\"POST\")\n               .endpoint(\"https://www.googleapis.com/storage/v1/b/jcloudstestbucket/acl/allUsers\")\n               .addHeader(\"Accept\", \"application/json\")\n               .addHeader(\"Authorization\", \"Bearer \" + TOKEN)\n               .addHeader(\"X-HTTP-Method-Override\", \"PATCH\")\n               .payload(payloadFromResourceWithContentType(\"/bucket_acl_update_initial.json\",\n                        MediaType.APPLICATION_JSON)).build();\n\n      HttpResponse patchResponse = HttpResponse.builder().statusCode(200)\n               .payload(staticPayloadFromResource(\"/bucket_acl_update_response.json\")).build();\n\n      BucketAccessControlsApi api = requestsSendResponses(requestForScopes(STORAGE_FULLCONTROL_SCOPE), TOKEN_RESPONSE,\n               patchRequest, patchResponse).getBucketAccessControlsApi();\n\n      BucketAccessControlsTemplate template = BucketAccessControlsTemplate.create(\"allUsers\", Role.OWNER);\n\n      assertEquals(api.patchBucketAccessControls(EXPECTED_TEST_BUCKET, \"allUsers\", template),\n               new BucketAclUpdateTest().expected());\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/java/org/jclouds/googlecloudstorage/features/BucketAccessControlsApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.List;\nimport java.util.UUID;\n\nimport org.jclouds.googlecloudstorage.domain.Bucket;\nimport org.jclouds.googlecloudstorage.domain.BucketAccessControls;\nimport org.jclouds.googlecloudstorage.domain.BucketAccessControls.Role;\nimport org.jclouds.googlecloudstorage.domain.templates.BucketAccessControlsTemplate;\nimport org.jclouds.googlecloudstorage.domain.templates.BucketTemplate;\nimport org.jclouds.googlecloudstorage.internal.BaseGoogleCloudStorageApiLiveTest;\nimport org.testng.annotations.Test;\n\npublic class BucketAccessControlsApiLiveTest extends BaseGoogleCloudStorageApiLiveTest {\n\n   protected static final String BUCKET_NAME = \"jcloudstestbucketacl\" + UUID.randomUUID();\n\n   private BucketAccessControlsApi api() {\n      return api.getBucketAccessControlsApi();\n   }\n\n   private void createBucket(String BucketName) {\n      BucketTemplate template = new BucketTemplate().name(BucketName);\n      Bucket response = api.getBucketApi().createBucket(PROJECT_NUMBER, template);\n      assertNotNull(response);\n   }\n\n   @Test(groups = \"live\")\n   public void testCreateBucketAcl() {\n      createBucket(BUCKET_NAME);\n      BucketAccessControlsTemplate bucketAcl = BucketAccessControlsTemplate.create(\"allUsers\", Role.READER);\n      BucketAccessControls response = api().createBucketAccessControls(BUCKET_NAME, bucketAcl);\n\n      assertNotNull(response);\n      assertEquals(response.id(), BUCKET_NAME + \"/allUsers\");\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testCreateBucketAcl\")\n   public void testUpdateBucketAcl() {\n      BucketAccessControlsTemplate template = BucketAccessControlsTemplate.create(\"allUsers\", Role.WRITER);\n      BucketAccessControls response = api().updateBucketAccessControls(BUCKET_NAME, \"allUsers\", template);\n\n      assertNotNull(response);\n      assertEquals(response.id(), BUCKET_NAME + \"/allUsers\");\n      assertEquals(response.role(), Role.WRITER);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testUpdateBucketAcl\")\n   public void testGetBucketAcl() {\n      BucketAccessControls response = api().getBucketAccessControls(BUCKET_NAME, \"allUsers\");\n\n      assertNotNull(response);\n      assertEquals(response.id(), BUCKET_NAME + \"/allUsers\");\n      assertEquals(response.role(), Role.WRITER);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testUpdateBucketAcl\")\n   public void testListBucketAcl() {\n      List<BucketAccessControls> response = api().listBucketAccessControls(BUCKET_NAME);\n\n      assertNotNull(response);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testUpdateBucketAcl\")\n   public void testPatchBucketAcl() {\n      BucketAccessControlsTemplate template = BucketAccessControlsTemplate.create(\"allUsers\", Role.READER);\n      BucketAccessControls response = api().patchBucketAccessControls(BUCKET_NAME, \"allUsers\", template);\n\n      assertNotNull(response);\n      assertEquals(response.id(), BUCKET_NAME + \"/allUsers\");\n      assertEquals(response.role(), Role.READER);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testPatchBucketAcl\")\n   public void testDeleteBucketAcl() {\n      api().deleteBucketAccessControls(BUCKET_NAME, \"allUsers\");\n      deleteBucket(BUCKET_NAME);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testDeleteBucketAcl\")\n   public void testDeleteNotExistingBucketAccessControls() {\n      api().deleteBucketAccessControls(BUCKET_NAME, \"allUsers\");\n   }\n\n   private void deleteBucket(String BucketName) {\n      api.getBucketApi().deleteBucket(BucketName);\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/java/org/jclouds/googlecloudstorage/features/BucketApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.AssertJUnit.assertNull;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.googlecloudstorage.domain.BucketAccessControls;\nimport org.jclouds.googlecloudstorage.domain.BucketAccessControls.Role;\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.Projection;\nimport org.jclouds.googlecloudstorage.domain.templates.BucketTemplate;\nimport org.jclouds.googlecloudstorage.internal.BaseGoogleCloudStorageApiExpectTest;\nimport org.jclouds.googlecloudstorage.options.GetBucketOptions;\nimport org.jclouds.googlecloudstorage.options.ListOptions;\nimport org.jclouds.googlecloudstorage.options.UpdateBucketOptions;\nimport org.jclouds.googlecloudstorage.parse.BucketUpdateTest;\nimport org.jclouds.googlecloudstorage.parse.NoAclBucketListTest;\nimport org.jclouds.googlecloudstorage.parse.NoAclBucketTest;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"BucketApiExpectTest\")\npublic class BucketApiExpectTest extends BaseGoogleCloudStorageApiExpectTest {\n\n   private static final String EXPECTED_TEST_BUCKET = \"bhashbucket\";\n   private static final String EXPECTED_TEST_PROJECT_NUMBER = \"1082289308625\";\n\n   private static final HttpRequest GET_BUCKET_REQUEST = HttpRequest.builder().method(\"GET\")\n            .endpoint(\"https://www.googleapis.com/storage/v1/b/bhashbucket\").addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"Authorization\", \"Bearer \" + TOKEN).build();\n\n   private static final HttpRequest GET_BUCKET_REQUEST_WITHOPTIONS = HttpRequest.builder().method(\"GET\")\n            .endpoint(\"https://www.googleapis.com/storage/v1/b/bhashbucket\")\n            .addQueryParam(\"ifMetagenerationNotMatch\", \"100\").addQueryParam(\"projection\", \"full\")\n            .addHeader(\"Accept\", \"application/json\").addHeader(\"Authorization\", \"Bearer \" + TOKEN).build();\n\n   private final HttpResponse BUCKET_RESPONSE = HttpResponse.builder().statusCode(200)\n            .payload(staticPayloadFromResource(\"/no_acl_bucket.json\")).build();\n\n   public static final HttpRequest LIST_BUCKET_REQUEST = HttpRequest.builder().method(\"GET\")\n            .endpoint(\"https://www.googleapis.com/storage/v1/b\").addQueryParam(\"project\", EXPECTED_TEST_PROJECT_NUMBER)\n            .addHeader(\"Accept\", \"application/json\").addHeader(\"Authorization\", \"Bearer \" + TOKEN).build();\n\n   public static final HttpRequest LIST_BUCKET_REQUEST_WITHOPTIONS = HttpRequest.builder().method(\"GET\")\n            .endpoint(\"https://www.googleapis.com/storage/v1/b\").addQueryParam(\"project\", EXPECTED_TEST_PROJECT_NUMBER)\n            .addQueryParam(\"maxResults\", \"2\").addQueryParam(\"pageToken\", \"jcloudstestbucket500\")\n            .addHeader(\"Accept\", \"application/json\").addHeader(\"Authorization\", \"Bearer \" + TOKEN).build();\n\n   private final HttpResponse LIST_BUCKET_RESPONSE = HttpResponse.builder().statusCode(200)\n            .payload(staticPayloadFromResource(\"/no_acl_bucket_list.json\")).build();\n\n   // Test getBucket without options\n   public void testGetBucketWithNoOptionsResponseIs2xx() throws Exception {\n\n      BucketApi api = requestsSendResponses(requestForScopes(STORAGE_READONLY_SCOPE), TOKEN_RESPONSE,\n               GET_BUCKET_REQUEST, BUCKET_RESPONSE).getBucketApi();\n\n      assertEquals(api.getBucket(EXPECTED_TEST_BUCKET), new NoAclBucketTest().expected());\n   }\n\n   public void testGetBucketResponseIs4xx() throws Exception {\n\n      HttpResponse getResponse = HttpResponse.builder().statusCode(404).build();\n\n      BucketApi api = requestsSendResponses(requestForScopes(STORAGE_READONLY_SCOPE), TOKEN_RESPONSE,\n               GET_BUCKET_REQUEST, getResponse).getBucketApi();\n\n      assertNull(\"404\", api.getBucket(EXPECTED_TEST_BUCKET));\n   }\n\n   // Test getBucket with options\n   public void testGetBucketWithOptionsResponseIs2xx() throws Exception {\n\n      BucketApi api = requestsSendResponses(requestForScopes(STORAGE_READONLY_SCOPE), TOKEN_RESPONSE,\n               GET_BUCKET_REQUEST_WITHOPTIONS, BUCKET_RESPONSE).getBucketApi();\n\n      GetBucketOptions options = new GetBucketOptions().ifMetagenerationNotMatch(Long.valueOf(100)).projection(\n               Projection.FULL);\n      assertEquals(api.getBucket(EXPECTED_TEST_BUCKET, options), new NoAclBucketTest().expected());\n   }\n\n   // Test listBucket without options\n   public void testListBucketWithNoOptionsResponseIs2xx() throws Exception {\n\n      BucketApi api = requestsSendResponses(requestForScopes(STORAGE_READONLY_SCOPE), TOKEN_RESPONSE,\n               LIST_BUCKET_REQUEST, LIST_BUCKET_RESPONSE).getBucketApi();\n\n      assertEquals(api.listBucket(EXPECTED_TEST_PROJECT_NUMBER), new NoAclBucketListTest().expected());\n\n   }\n\n   public void testListBucketWithOptionsResponseIs2xx() throws Exception {\n\n      BucketApi api = requestsSendResponses(requestForScopes(STORAGE_READONLY_SCOPE), TOKEN_RESPONSE,\n               LIST_BUCKET_REQUEST_WITHOPTIONS, LIST_BUCKET_RESPONSE).getBucketApi();\n\n      ListOptions options = new ListOptions().maxResults(2).pageToken(\"jcloudstestbucket500\");\n\n      assertEquals(api.listBucket(EXPECTED_TEST_PROJECT_NUMBER, options), new NoAclBucketListTest().expected());\n\n   }\n\n   @Test(enabled = false)\n   public void listBucketEmpty() throws Exception {\n      HttpResponse listResponse = null; // TODO: get a copy of an empty bucket response\n\n      BucketApi api = requestsSendResponses(requestForScopes(STORAGE_READONLY_SCOPE), TOKEN_RESPONSE,\n               LIST_BUCKET_REQUEST, listResponse).getBucketApi();\n\n      assertTrue(api.listBucket(EXPECTED_TEST_PROJECT_NUMBER).isEmpty());\n   }\n\n   // Test createBucket without options\n   public void testCreateBucketWithNoOptionsResponseIs2xx() throws Exception {\n\n      HttpRequest createRequest = HttpRequest\n               .builder()\n               .method(\"POST\")\n               .endpoint(\"https://www.googleapis.com/storage/v1/b\")\n               .addHeader(\"Accept\", \"application/json\")\n               .addQueryParam(\"project\", EXPECTED_TEST_PROJECT_NUMBER)\n               .addHeader(\"Authorization\", \"Bearer \" + TOKEN)\n               .payload(payloadFromResourceWithContentType(\"/bucket_insert_request_payload.json\",\n                        MediaType.APPLICATION_JSON)).build();\n\n      BucketApi api = requestsSendResponses(requestForScopes(STORAGE_READWRITE_SCOPE), TOKEN_RESPONSE,\n               createRequest, BUCKET_RESPONSE).getBucketApi();\n\n      BucketTemplate template = new BucketTemplate().name(\"bhashbucket\");\n\n      assertEquals(api.createBucket(EXPECTED_TEST_PROJECT_NUMBER, template), new NoAclBucketTest().expected());\n\n   }\n\n   public void testUpdateBucketWithNoOptionsResponseIs2xx() throws Exception {\n\n      BucketAccessControls bucketacl = BucketAccessControls.builder().bucket(EXPECTED_TEST_BUCKET)\n               .entity(\"allAuthenticatedUsers\").role(Role.OWNER).build();\n\n      BucketTemplate template = new BucketTemplate().name(EXPECTED_TEST_BUCKET).addAcl(bucketacl);\n\n      HttpRequest updateRequest = HttpRequest\n               .builder()\n               .method(\"PUT\")\n               .endpoint(\"https://www.googleapis.com/storage/v1/b/\" + EXPECTED_TEST_BUCKET)\n               .addHeader(\"Accept\", \"application/json\")\n               .addHeader(\"Authorization\", \"Bearer \" + TOKEN)\n               .payload(payloadFromResourceWithContentType(\"/bucket_update_request_payload.json\",\n                        MediaType.APPLICATION_JSON)).build();\n\n      HttpResponse updateResponse = HttpResponse.builder().statusCode(200)\n               .payload(staticPayloadFromResource(\"/bucket_update_response.json\")).build();\n\n      BucketApi api = requestsSendResponses(requestForScopes(STORAGE_FULLCONTROL_SCOPE), TOKEN_RESPONSE,\n               updateRequest, updateResponse).getBucketApi();\n\n      assertEquals(api.updateBucket(EXPECTED_TEST_BUCKET, template), new BucketUpdateTest().expected());\n   }\n\n   public void testUpdateBucketWithOptionsResponseIs2xx() throws Exception {\n\n      BucketAccessControls bucketacl = BucketAccessControls.builder().bucket(EXPECTED_TEST_BUCKET)\n               .entity(\"allAuthenticatedUsers\").role(Role.OWNER).build();\n      UpdateBucketOptions options = new UpdateBucketOptions().projection(Projection.NO_ACL).ifMetagenerationNotMatch(\n               Long.valueOf(100));\n      BucketTemplate template = new BucketTemplate().name(EXPECTED_TEST_BUCKET).addAcl(bucketacl);\n\n      HttpRequest updateRequest = HttpRequest\n               .builder()\n               .method(\"PUT\")\n               .endpoint(\"https://www.googleapis.com/storage/v1/b/\" + EXPECTED_TEST_BUCKET)\n               .addHeader(\"Accept\", \"application/json\")\n               .addHeader(\"Authorization\", \"Bearer \" + TOKEN)\n               .addQueryParam(\"projection\", Projection.NO_ACL.toString())\n               .addQueryParam(\"ifMetagenerationNotMatch\", \"100\")\n               .payload(payloadFromResourceWithContentType(\"/bucket_update_request_payload.json\",\n                        MediaType.APPLICATION_JSON)).build();\n\n      HttpResponse updateResponse = HttpResponse.builder().statusCode(200)\n               .payload(staticPayloadFromResource(\"/bucket_update_response.json\")).build();\n\n      BucketApi api = requestsSendResponses(requestForScopes(STORAGE_FULLCONTROL_SCOPE), TOKEN_RESPONSE,\n               updateRequest, updateResponse).getBucketApi();\n\n      assertEquals(api.updateBucket(EXPECTED_TEST_BUCKET, template, options), new BucketUpdateTest().expected());\n   }\n\n   public void testPatchBucketWithNoOptionsResponseIs2xx() throws Exception {\n\n      BucketAccessControls bucketacl = BucketAccessControls.builder().bucket(EXPECTED_TEST_BUCKET)\n               .entity(\"allAuthenticatedUsers\").role(Role.OWNER).build();\n\n      BucketTemplate template = new BucketTemplate().name(EXPECTED_TEST_BUCKET).addAcl(bucketacl);\n\n      HttpRequest patchRequest = HttpRequest\n               .builder()\n               .method(\"POST\")\n               .endpoint(\"https://www.googleapis.com/storage/v1/b/\" + EXPECTED_TEST_BUCKET)\n               .addHeader(\"Accept\", \"application/json\")\n               .addHeader(\"Authorization\", \"Bearer \" + TOKEN)\n               .addHeader(\"X-HTTP-Method-Override\", \"PATCH\")\n               .payload(payloadFromResourceWithContentType(\"/bucket_update_request_payload.json\",\n                        MediaType.APPLICATION_JSON)).build();\n\n      HttpResponse patchResponse = HttpResponse.builder().statusCode(200)\n               .payload(staticPayloadFromResource(\"/bucket_update_response.json\")).build();\n\n      BucketApi api = requestsSendResponses(requestForScopes(STORAGE_FULLCONTROL_SCOPE), TOKEN_RESPONSE, patchRequest,\n               patchResponse).getBucketApi();\n\n      assertEquals(api.patchBucket(EXPECTED_TEST_BUCKET, template), new BucketUpdateTest().expected());\n   }\n\n   public void testPatchBucketWithOptionsResponseIs2xx() throws Exception {\n\n      BucketAccessControls bucketacl = BucketAccessControls.builder().bucket(EXPECTED_TEST_BUCKET)\n               .entity(\"allAuthenticatedUsers\").role(Role.OWNER).build();\n      UpdateBucketOptions options = new UpdateBucketOptions().projection(Projection.NO_ACL).ifMetagenerationNotMatch(\n               Long.valueOf(100));\n      BucketTemplate template = new BucketTemplate().name(EXPECTED_TEST_BUCKET).addAcl(bucketacl);\n\n      HttpRequest patchRequest = HttpRequest\n               .builder()\n               .method(\"PUT\")\n               .endpoint(\"https://www.googleapis.com/storage/v1/b/\" + EXPECTED_TEST_BUCKET)\n               .addHeader(\"Accept\", \"application/json\")\n               .addHeader(\"Authorization\", \"Bearer \" + TOKEN)\n               .addQueryParam(\"projection\", Projection.NO_ACL.toString())\n               .addQueryParam(\"ifMetagenerationNotMatch\", \"100\")\n               .payload(payloadFromResourceWithContentType(\"/bucket_update_request_payload.json\",\n                        MediaType.APPLICATION_JSON)).build();\n\n      HttpResponse patchResponse = HttpResponse.builder().statusCode(200)\n               .payload(staticPayloadFromResource(\"/bucket_update_response.json\")).build();\n\n      BucketApi api = requestsSendResponses(requestForScopes(STORAGE_FULLCONTROL_SCOPE), TOKEN_RESPONSE, patchRequest,\n               patchResponse).getBucketApi();\n\n      assertEquals(api.updateBucket(EXPECTED_TEST_BUCKET, template, options), new BucketUpdateTest().expected());\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/java/org/jclouds/googlecloudstorage/features/BucketApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.features;\n\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertSame;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Arrays;\nimport java.util.Iterator;\nimport java.util.List;\n\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecloudstorage.domain.Bucket;\nimport org.jclouds.googlecloudstorage.domain.Bucket.Cors;\nimport org.jclouds.googlecloudstorage.domain.Bucket.Logging;\nimport org.jclouds.googlecloudstorage.domain.Bucket.Versioning;\nimport org.jclouds.googlecloudstorage.domain.BucketAccessControls;\nimport org.jclouds.googlecloudstorage.domain.BucketAccessControls.Role;\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.Location;\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.ObjectRole;\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.Projection;\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.StorageClass;\nimport org.jclouds.googlecloudstorage.domain.ObjectAccessControls;\nimport org.jclouds.googlecloudstorage.domain.templates.BucketTemplate;\nimport org.jclouds.googlecloudstorage.internal.BaseGoogleCloudStorageApiLiveTest;\nimport org.jclouds.googlecloudstorage.options.DeleteBucketOptions;\nimport org.jclouds.googlecloudstorage.options.GetBucketOptions;\nimport org.jclouds.googlecloudstorage.options.InsertBucketOptions;\nimport org.jclouds.googlecloudstorage.options.UpdateBucketOptions;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Lists;\n\npublic class BucketApiLiveTest extends BaseGoogleCloudStorageApiLiveTest {\n\n   // TODO: what removes these buckets?\n\n   private static final String BUCKET_NAME = \"jcloudstestbucket\" + (int) (Math.random() * 10000);\n\n   private static final String BUCKET_NAME_STANDARD = \"jcloudstestbucketstandard\" + (int) (Math.random() * 10000);\n\n   private static final String BUCKET_NAME_COLDLINE = \"jcloudstestbucketcoldline\" + (int) (Math.random() * 10000);\n\n   private static final String BUCKET_NAME_ARCHIVE = \"jcloudstestbucketarchive\" + (int) (Math.random() * 10000);\n\n   private static final String BUCKET_NAME_MULTI_REGIONAL = \"jcloudstestbucketmultiregional\" + (int) (Math.random() * 10000);\n\n   private static final String BUCKET_NAME_NEARLINE = \"jcloudstestbucketnearline\" + (int) (Math.random() * 10000);\n\n   private static final String BUCKET_NAME_WITHOPTIONS = \"jcloudstestbucketoptions\" + (int) (Math.random() * 10000);\n\n   private static final String LOG_BUCKET_NAME = \"jcloudslogbucket\" + (int) (Math.random() * 10000);\n\n   private Long metageneration;\n\n   private BucketApi api() {\n      return api.getBucketApi();\n   }\n\n   // TODO: should this test use STANDARD storage class?\n   @Test(groups = \"live\")\n   public void testCreateBucket() {\n\n      BucketTemplate logTemplate = new BucketTemplate().name(LOG_BUCKET_NAME);\n      Bucket logResponse = api().createBucket(PROJECT_NUMBER, logTemplate);\n      assertNotNull(logResponse);\n\n      BucketAccessControls acl = BucketAccessControls.builder().bucket(BUCKET_NAME).entity(\"allUsers\").role(Role.OWNER)\n               .build();\n      ObjectAccessControls oac = ObjectAccessControls.builder().bucket(BUCKET_NAME).entity(\"allUsers\")\n               .role(ObjectRole.OWNER).build();\n      Cors cors = Cors.create(Arrays.asList(\"http://example.appspot.com\"), Arrays.asList(\"GET\", \"HEAD\"),\n            Arrays.asList(\"x-meta-goog-custom\"), 10);\n      Versioning version = Versioning.create(true);\n\n      Logging log = Logging.create(LOG_BUCKET_NAME, BUCKET_NAME);\n\n      BucketTemplate template = new BucketTemplate().name(BUCKET_NAME).addAcl(acl).addDefaultObjectAccessControls(oac)\n               .versioning(version).location(Location.US_CENTRAL1).logging(log)\n               .storageClass(StorageClass.DURABLE_REDUCED_AVAILABILITY).addCORS(cors);\n\n      Bucket response = api().createBucket(PROJECT_NUMBER, template);\n\n      assertNotNull(response);\n      assertNotNull(response.cors());\n      assertTrue(response.cors().size() == 1);\n      assertEquals(response.name(), BUCKET_NAME);\n      assertEquals(response.location(), Location.US_CENTRAL1);\n      assertThat(response.storageClass()).isEqualTo(StorageClass.DURABLE_REDUCED_AVAILABILITY);\n      assertTrue(response.versioning().enabled());\n   }\n\n   @Test(groups = \"live\")\n   public void testCreateBucketStandard() {\n      BucketTemplate template = new BucketTemplate()\n               .name(BUCKET_NAME_STANDARD)\n               .location(Location.US)\n               .storageClass(StorageClass.STANDARD);\n\n      Bucket response = api().createBucket(PROJECT_NUMBER, template);\n\n      assertNotNull(response);\n      assertEquals(response.name(), BUCKET_NAME_STANDARD);\n      assertEquals(response.location(), Location.US);\n      assertThat(response.storageClass()).isEqualTo(StorageClass.STANDARD);\n\n      api().deleteBucket(BUCKET_NAME_STANDARD);\n   }\n\n   @Test(groups = \"live\")\n   public void testCreateBucketColdline() {\n      BucketTemplate template = new BucketTemplate()\n               .name(BUCKET_NAME_COLDLINE)\n               .location(Location.US)\n               .storageClass(StorageClass.COLDLINE);\n\n      Bucket response = api().createBucket(PROJECT_NUMBER, template);\n\n      assertNotNull(response);\n      assertEquals(response.name(), BUCKET_NAME_COLDLINE);\n      assertEquals(response.location(), Location.US);\n      assertThat(response.storageClass()).isEqualTo(StorageClass.COLDLINE);\n\n      api().deleteBucket(BUCKET_NAME_COLDLINE);\n   }\n\n   @Test(groups = \"live\")\n   public void testCreateBucketArchive() {\n      BucketTemplate template = new BucketTemplate()\n               .name(BUCKET_NAME_ARCHIVE)\n               .location(Location.US)\n               .storageClass(StorageClass.ARCHIVE);\n\n      Bucket response = api().createBucket(PROJECT_NUMBER, template);\n\n      assertNotNull(response);\n      assertEquals(response.name(), BUCKET_NAME_ARCHIVE);\n      assertEquals(response.location(), Location.US);\n      assertThat(response.storageClass()).isEqualTo(StorageClass.ARCHIVE);\n\n      api().deleteBucket(BUCKET_NAME_ARCHIVE);\n   }\n\n   @Test(groups = \"live\")\n   public void testCreateBucketMultiregional() {\n      BucketTemplate template = new BucketTemplate()\n               .name(BUCKET_NAME_MULTI_REGIONAL)\n               .location(Location.US)\n               .storageClass(StorageClass.MULTI_REGIONAL);\n\n      Bucket response = api().createBucket(PROJECT_NUMBER, template);\n\n      assertNotNull(response);\n      assertEquals(response.name(), BUCKET_NAME_MULTI_REGIONAL);\n      assertEquals(response.location(), Location.US);\n      assertThat(response.storageClass()).isEqualTo(StorageClass.MULTI_REGIONAL);\n\n      api().deleteBucket(BUCKET_NAME_NEARLINE);\n   }\n\n   @Test(groups = \"live\")\n   public void testCreateBucketNearline() {\n      BucketTemplate template = new BucketTemplate()\n               .name(BUCKET_NAME_NEARLINE)\n               .location(Location.US)\n               .storageClass(StorageClass.NEARLINE);\n\n      Bucket response = api().createBucket(PROJECT_NUMBER, template);\n\n      assertNotNull(response);\n      assertEquals(response.name(), BUCKET_NAME_NEARLINE);\n      assertEquals(response.location(), Location.US);\n      assertThat(response.storageClass()).isEqualTo(StorageClass.NEARLINE);\n\n      api().deleteBucket(BUCKET_NAME_NEARLINE);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = { \"testCreateBucket\" })\n   public void testCreateAlreadyExistBucket() {\n\n      BucketTemplate template = new BucketTemplate().name(BUCKET_NAME).location(Location.US_CENTRAL1)\n               .storageClass(StorageClass.DURABLE_REDUCED_AVAILABILITY);\n\n      assertNull(api().createBucket(PROJECT_NUMBER, template));\n   }\n\n   @Test(groups = \"live\")\n   public void testCreateBucketWithOptions() {\n      ObjectAccessControls oac = ObjectAccessControls.builder().bucket(BUCKET_NAME_WITHOPTIONS)\n               .entity(\"allUsers\").role(ObjectRole.OWNER).build();\n      Cors cors = Cors.create(Arrays.asList(\"http://example.appspot.com\"), Arrays.asList(\"GET\", \"HEAD\"),\n            Arrays.asList(\"x-meta-goog-custom\"), 10);\n      Versioning version = Versioning.create(true);\n\n      BucketTemplate template = new BucketTemplate().name(BUCKET_NAME_WITHOPTIONS).addDefaultObjectAccessControls(oac)\n               .versioning(version).location(Location.US_CENTRAL1)\n               .storageClass(StorageClass.DURABLE_REDUCED_AVAILABILITY).addCORS(cors);\n\n      InsertBucketOptions options = new InsertBucketOptions().projection(Projection.FULL);\n\n      Bucket response = api().createBucket(PROJECT_NUMBER, template, options);\n\n      assertNotNull(response);\n      assertNotNull(response.cors());\n      assertEquals(response.name(), BUCKET_NAME_WITHOPTIONS);\n      assertEquals(response.location(), Location.US_CENTRAL1);\n      assertTrue(response.versioning().enabled());\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testCreateBucket\")\n   public void testUpdateBucket() {\n      BucketAccessControls bucketacl = BucketAccessControls.builder().bucket(BUCKET_NAME)\n               .entity(\"allAuthenticatedUsers\").role(Role.OWNER).build();\n      BucketTemplate template = new BucketTemplate().name(BUCKET_NAME).addAcl(bucketacl);\n      Bucket response = api().updateBucket(BUCKET_NAME, template);\n\n      assertNotNull(response);\n      assertEquals(response.name(), BUCKET_NAME);\n      assertNotNull(response.acl());\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testCreateBucketWithOptions\")\n   public void testUpdateBucketWithOptions() {\n      BucketAccessControls bucketacl = BucketAccessControls.builder().bucket(BUCKET_NAME_WITHOPTIONS)\n               .entity(\"allAuthenticatedUsers\").role(Role.OWNER).build();\n      UpdateBucketOptions options = new UpdateBucketOptions().projection(Projection.FULL);\n      BucketTemplate template = new BucketTemplate().name(BUCKET_NAME_WITHOPTIONS).addAcl(bucketacl);\n      Bucket response = api().updateBucket(BUCKET_NAME_WITHOPTIONS, template, options);\n\n      assertNotNull(response);\n\n      metageneration = response.metageneration();\n\n      assertEquals(response.name(), BUCKET_NAME_WITHOPTIONS);\n      assertNotNull(response.acl());\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testCreateBucket\")\n   public void testGetBucket() {\n      Bucket response = api().getBucket(BUCKET_NAME);\n\n      assertNotNull(response);\n      assertEquals(response.name(), BUCKET_NAME);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testUpdateBucketWithOptions\")\n   public void testGetBucketWithOptions() {\n      GetBucketOptions options = new GetBucketOptions().ifMetagenerationMatch(metageneration);\n      Bucket response = api().getBucket(BUCKET_NAME_WITHOPTIONS, options);\n\n      assertNotNull(response);\n      assertEquals(response.name(), BUCKET_NAME_WITHOPTIONS);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testCreateBucket\")\n   public void testListBucket() {\n      ListPage<Bucket> bucket = api().listBucket(PROJECT_NUMBER);\n\n      Iterator<Bucket> pageIterator = bucket.iterator();\n      assertTrue(pageIterator.hasNext());\n\n      Bucket iteratedBucket = pageIterator.next();\n      List<Bucket> bucketAsList = Lists.newArrayList(iteratedBucket);\n\n      assertNotNull(iteratedBucket);\n      assertSame(bucketAsList.size(), 1);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testCreateBucket\")\n   public void testPatchBucket() {\n      Logging logging = Logging.create(LOG_BUCKET_NAME, BUCKET_NAME);\n      BucketTemplate template = new BucketTemplate().name(BUCKET_NAME).logging(logging);\n\n      Bucket response = api().patchBucket(BUCKET_NAME, template);\n\n      assertNotNull(response);\n      assertEquals(response.name(), BUCKET_NAME);\n      assertEquals(response.logging().logBucket(), LOG_BUCKET_NAME);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = { \"testListBucket\", \"testGetBucket\", \"testUpdateBucket\" })\n   public void testDeleteBucket() {\n      assertTrue(api().deleteBucket(BUCKET_NAME));\n      assertTrue(api().deleteBucket(LOG_BUCKET_NAME));\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = { \"testDeleteBucket\" })\n   public void testDeleteNotExistingBucket() {\n      assertFalse(api().deleteBucket(BUCKET_NAME));\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = { \"testGetBucketWithOptions\" })\n   public void testDeleteBucketWithOptions() {\n\n      DeleteBucketOptions options = new DeleteBucketOptions().ifMetagenerationMatch(metageneration)\n               .ifMetagenerationNotMatch(metageneration + 1);\n\n      api().deleteBucket(BUCKET_NAME_WITHOPTIONS, options);\n\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/java/org/jclouds/googlecloudstorage/features/DefaultObjectAccessControlsApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.googlecloudstorage.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.AssertJUnit.assertNull;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.ObjectRole;\nimport org.jclouds.googlecloudstorage.domain.ObjectAccessControls;\nimport org.jclouds.googlecloudstorage.domain.templates.ObjectAccessControlsTemplate;\nimport org.jclouds.googlecloudstorage.internal.BaseGoogleCloudStorageApiExpectTest;\nimport org.jclouds.googlecloudstorage.parse.DefaultObjectAclGetTest;\nimport org.jclouds.googlecloudstorage.parse.DefaultObjectAclInsertTest;\nimport org.jclouds.googlecloudstorage.parse.DefaultObjectAclListTest;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"DefaultObjectAccessControlsApiExpectTest\")\npublic class DefaultObjectAccessControlsApiExpectTest extends BaseGoogleCloudStorageApiExpectTest {\n\n   private static final String EXPECTED_TEST_BUCKET = \"jcloudstestbucket\";\n   private static final String EXPECTED_TEST_GROUP_ENTITY = \"group-00b4903a971ec6cff233284d6d24f5bf5cba904c4ade4d43ebd6a5d33800e68b\";\n\n   private static final HttpRequest GET_DEFAULT_OBJECT_ACL_REQUEST = HttpRequest\n            .builder()\n            .method(\"GET\")\n            .endpoint(\n                     \"https://www.googleapis.com/storage/v1/b/jcloudstestbucket/defaultObjectAcl/group-00b4903a971ec6cff233284d6d24f5bf5cba904c4ade4d43ebd6a5d33800e68b\")\n            .addHeader(\"Accept\", \"application/json\").addHeader(\"Authorization\", \"Bearer \" + TOKEN).build();\n\n   private final HttpResponse GET_DEFAULT_OBJECT_ACL_RESPONSE = HttpResponse.builder().statusCode(200)\n            .payload(staticPayloadFromResource(\"/default_object_acl_get.json\")).build();\n\n   private final HttpResponse CREATE_DEFAULT_OBJECT_ACL_RESPONSE = HttpResponse.builder().statusCode(200)\n            .payload(staticPayloadFromResource(\"/default_object_acl_insert_response.json\")).build();\n\n   public  final HttpRequest LIST_DEFAULT_OBJECT_ACL_REQUEST = HttpRequest.builder().method(\"GET\")\n            .endpoint(\"https://www.googleapis.com/storage/v1/b/jcloudstestbucket/defaultObjectAcl\")\n            .addHeader(\"Accept\", \"application/json\").addHeader(\"Authorization\", \"Bearer \" + TOKEN).build();\n\n   private final HttpResponse LIST_DEFAULT_OBJECT_ACL_RESPONSE = HttpResponse.builder().statusCode(200)\n            .payload(staticPayloadFromResource(\"/default_object_acl_list.json\")).build();\n\n   // Test getDefaultObjectAccessControls\n   public void testGetDefaultObjectAclResponseIs2xx() throws Exception {\n\n      DefaultObjectAccessControlsApi api = requestsSendResponses(requestForScopes(STORAGE_FULLCONTROL_SCOPE),\n               TOKEN_RESPONSE, GET_DEFAULT_OBJECT_ACL_REQUEST, GET_DEFAULT_OBJECT_ACL_RESPONSE)\n               .getDefaultObjectAccessControlsApi();\n\n      assertEquals(api.getDefaultObjectAccessControls(EXPECTED_TEST_BUCKET, EXPECTED_TEST_GROUP_ENTITY),\n               new DefaultObjectAclGetTest().expected());\n   }\n\n   public void testGetDefaultObjectAclResponseIs4xx() throws Exception {\n\n      HttpResponse getResponse = HttpResponse.builder().statusCode(404).build();\n\n      DefaultObjectAccessControlsApi api = requestsSendResponses(requestForScopes(STORAGE_FULLCONTROL_SCOPE),\n               TOKEN_RESPONSE, GET_DEFAULT_OBJECT_ACL_REQUEST, getResponse).getDefaultObjectAccessControlsApi();\n\n      assertNull(api.getDefaultObjectAccessControls(EXPECTED_TEST_BUCKET, EXPECTED_TEST_GROUP_ENTITY));\n   }\n\n   // Test listDefaultObjectAccessControls\n   public void testListDefaultObjectAclWithNoOptionsResponseIs2xx() throws Exception {\n\n      DefaultObjectAccessControlsApi api = requestsSendResponses(requestForScopes(STORAGE_FULLCONTROL_SCOPE),\n               TOKEN_RESPONSE, LIST_DEFAULT_OBJECT_ACL_REQUEST, LIST_DEFAULT_OBJECT_ACL_RESPONSE)\n               .getDefaultObjectAccessControlsApi();\n\n      assertEquals(api.listDefaultObjectAccessControls(EXPECTED_TEST_BUCKET), new DefaultObjectAclListTest().expected());\n   }\n\n   public void testListDefaultObjectAclResponseIs4xx() throws Exception {\n\n      HttpResponse listResponse = HttpResponse.builder().statusCode(404).build();\n\n      DefaultObjectAccessControlsApi api = requestsSendResponses(requestForScopes(STORAGE_FULLCONTROL_SCOPE),\n               TOKEN_RESPONSE, LIST_DEFAULT_OBJECT_ACL_REQUEST, listResponse).getDefaultObjectAccessControlsApi();\n\n      assertNull(api.listDefaultObjectAccessControls(EXPECTED_TEST_BUCKET));\n   }\n\n   // Test insertDefaultObjectAccessControls\n   public void testInsertDefaultObjectAclResponseIs2xx() throws Exception {\n      HttpRequest insertRequest = HttpRequest\n               .builder()\n               .method(\"POST\")\n               .endpoint(\"https://www.googleapis.com/storage/v1/b/jcloudstestbucket/defaultObjectAcl\")\n               .addHeader(\"Accept\", \"application/json\")\n               .addHeader(\"Authorization\", \"Bearer \" + TOKEN)\n               .payload(payloadFromResourceWithContentType(\"/default_object_acl_insert_request_payload.json\",\n                        MediaType.APPLICATION_JSON)).build();\n\n      DefaultObjectAccessControlsApi api = requestsSendResponses(requestForScopes(STORAGE_FULLCONTROL_SCOPE),\n               TOKEN_RESPONSE, insertRequest, CREATE_DEFAULT_OBJECT_ACL_RESPONSE).getDefaultObjectAccessControlsApi();\n\n      ObjectAccessControlsTemplate template = ObjectAccessControlsTemplate.create(\"allUsers\", ObjectRole.OWNER);\n\n      assertEquals(api.createDefaultObjectAccessControls(EXPECTED_TEST_BUCKET, template),\n               new DefaultObjectAclInsertTest().expected());\n   }\n\n   // Test deleteDefaultObjectAccessControls\n   public void testDeleteDefaultObjectAclResponseIs2xx() throws Exception {\n      HttpRequest delete = HttpRequest.builder().method(\"DELETE\")\n               .endpoint(\"https://www.googleapis.com/storage/v1/b/jcloudstestbucket/defaultObjectAcl/allUsers\")\n               .addHeader(\"Accept\", \"application/json\").addHeader(\"Authorization\", \"Bearer \" + TOKEN).build();\n\n      HttpResponse deleteResponse = HttpResponse.builder().statusCode(204).build();\n\n      DefaultObjectAccessControlsApi api = requestsSendResponses(requestForScopes(STORAGE_FULLCONTROL_SCOPE),\n               TOKEN_RESPONSE, delete, deleteResponse).getDefaultObjectAccessControlsApi();\n\n      assertEquals(api.deleteDefaultObjectAccessControls(EXPECTED_TEST_BUCKET, \"allUsers\"), deleteResponse);\n   }\n\n   public void testDeleteObjectAclResponseIs4xx() throws Exception {\n      HttpRequest delete = HttpRequest.builder().method(\"DELETE\")\n               .endpoint(\"https://www.googleapis.com/storage/v1/b/jcloudstestbucket/defaultObjectAcl/allUsers\")\n               .addHeader(\"Accept\", \"application/json\").addHeader(\"Authorization\", \"Bearer \" + TOKEN).build();\n\n      HttpResponse deleteResponse = HttpResponse.builder().statusCode(404).build();\n\n      DefaultObjectAccessControlsApi api = requestsSendResponses(requestForScopes(STORAGE_FULLCONTROL_SCOPE),\n               TOKEN_RESPONSE, delete, deleteResponse).getDefaultObjectAccessControlsApi();\n\n      assertNull(api.deleteDefaultObjectAccessControls(EXPECTED_TEST_BUCKET, \"allUsers\"));\n   }\n\n   // Test updateDefaultObjectAccessControls\n   public void testUpdateDefaultObjectAclWithNoOptionsResponseIs2xx() throws Exception {\n      HttpRequest update = HttpRequest\n               .builder()\n               .method(\"PUT\")\n               .endpoint(\"https://www.googleapis.com/storage/v1/b/jcloudstestbucket/defaultObjectAcl/allUsers\")\n               .addHeader(\"Accept\", \"application/json\")\n               .addHeader(\"Authorization\", \"Bearer \" + TOKEN)\n               .payload(payloadFromResourceWithContentType(\"/default_object_acl_update_request_payload.json\",\n                        MediaType.APPLICATION_JSON)).build();\n\n      HttpResponse updateResponse = HttpResponse.builder().statusCode(200)\n               .payload(staticPayloadFromResource(\"/default_object_acl_update_initial.json\")).build();\n\n      DefaultObjectAccessControlsApi api = requestsSendResponses(requestForScopes(STORAGE_FULLCONTROL_SCOPE),\n               TOKEN_RESPONSE, update, updateResponse).getDefaultObjectAccessControlsApi();\n\n      ObjectAccessControls options = ObjectAccessControls.builder().entity(\"allUsers\").role(ObjectRole.OWNER).build();\n\n      assertEquals(api.updateDefaultObjectAccessControls(EXPECTED_TEST_BUCKET, \"allUsers\", options),\n               new DefaultObjectAclInsertTest().expected());\n   }\n\n   // Test updateDefaultObjectAccessControls\n   public void testUpdateDefaultObjectAclWithOptionsResponseIs2xx() throws Exception {\n      HttpRequest update = HttpRequest\n               .builder()\n               .method(\"PUT\")\n               .endpoint(\"https://www.googleapis.com/storage/v1/b/jcloudstestbucket/defaultObjectAcl/allUsers\")\n               .addHeader(\"Accept\", \"application/json\")\n               .addHeader(\"Authorization\", \"Bearer \" + TOKEN)\n               .addQueryParam(\"role\", ObjectRole.OWNER.toString())\n               .payload(payloadFromResourceWithContentType(\"/default_object_acl_update_request_payload.json\",\n                        MediaType.APPLICATION_JSON)).build();\n\n      HttpResponse updateResponse = HttpResponse.builder().statusCode(200)\n               .payload(staticPayloadFromResource(\"/default_object_acl_update_initial.json\")).build();\n\n      DefaultObjectAccessControlsApi api = requestsSendResponses(requestForScopes(STORAGE_FULLCONTROL_SCOPE),\n               TOKEN_RESPONSE, update, updateResponse).getDefaultObjectAccessControlsApi();\n\n      ObjectAccessControls options = ObjectAccessControls.builder().entity(\"allUsers\").role(ObjectRole.OWNER).build();\n\n      assertEquals(api.updateDefaultObjectAccessControls(EXPECTED_TEST_BUCKET, \"allUsers\", options, ObjectRole.OWNER),\n               new DefaultObjectAclInsertTest().expected());\n   }\n\n   // Test patchDefaultObjectAccessControls\n   public void testPatchDefaultObjectAclWithNoOptionsResponseIs2xx() throws Exception {\n      HttpRequest update = HttpRequest\n               .builder()\n               .method(\"POST\")\n               .endpoint(\"https://www.googleapis.com/storage/v1/b/jcloudstestbucket/defaultObjectAcl/allUsers\")\n               .addHeader(\"Accept\", \"application/json\")\n               .addHeader(\"Authorization\", \"Bearer \" + TOKEN)\n               .addHeader(\"X-HTTP-Method-Override\", \"PATCH\")\n               .payload(payloadFromResourceWithContentType(\"/default_object_acl_update_request_payload.json\",\n                        MediaType.APPLICATION_JSON)).build();\n\n      HttpResponse updateResponse = HttpResponse.builder().statusCode(200)\n               .payload(staticPayloadFromResource(\"/default_object_acl_update_initial.json\")).build();\n\n      DefaultObjectAccessControlsApi api = requestsSendResponses(requestForScopes(STORAGE_FULLCONTROL_SCOPE),\n               TOKEN_RESPONSE, update, updateResponse).getDefaultObjectAccessControlsApi();\n\n      ObjectAccessControls options = ObjectAccessControls.builder().entity(\"allUsers\").role(ObjectRole.OWNER).build();\n\n      assertEquals(api.patchDefaultObjectAccessControls(EXPECTED_TEST_BUCKET, \"allUsers\", options),\n               new DefaultObjectAclInsertTest().expected());\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/java/org/jclouds/googlecloudstorage/features/DefaultObjectAccessControlsApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.List;\nimport java.util.UUID;\n\nimport org.jclouds.googlecloudstorage.domain.Bucket;\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.ObjectRole;\nimport org.jclouds.googlecloudstorage.domain.ObjectAccessControls;\nimport org.jclouds.googlecloudstorage.domain.templates.BucketTemplate;\nimport org.jclouds.googlecloudstorage.domain.templates.ObjectAccessControlsTemplate;\nimport org.jclouds.googlecloudstorage.internal.BaseGoogleCloudStorageApiLiveTest;\nimport org.testng.annotations.Test;\n\npublic class DefaultObjectAccessControlsApiLiveTest extends BaseGoogleCloudStorageApiLiveTest {\n\n   protected static final String BUCKET_NAME = \"jcloudsdefaultoacltest\" + UUID.randomUUID();\n\n   private DefaultObjectAccessControlsApi api() {\n      return api.getDefaultObjectAccessControlsApi();\n   }\n\n   private void createBucket(String BucketName) {\n      BucketTemplate template = new BucketTemplate().name(BucketName);\n      Bucket response = api.getBucketApi().createBucket(PROJECT_NUMBER, template);\n      assertNotNull(response);\n   }\n\n   @Test(groups = \"live\")\n   public void testCreateDefaultObjectAcl() {\n      createBucket(BUCKET_NAME);\n      ObjectAccessControlsTemplate template = ObjectAccessControlsTemplate.create(\"allUsers\", ObjectRole.READER);\n\n      ObjectAccessControls response = api().createDefaultObjectAccessControls(BUCKET_NAME, template);\n\n      assertNotNull(response);\n      assertEquals(response.entity(), \"allUsers\");\n      assertEquals(response.role(), ObjectRole.READER);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testCreateDefaultObjectAcl\")\n   public void testUpdateDefaultObjectAcl() {\n      ObjectAccessControls defaultObjectAcl = ObjectAccessControls.builder().bucket(BUCKET_NAME)\n               .entity(\"allUsers\").role(ObjectRole.OWNER).build();\n      ObjectAccessControls response = api().updateDefaultObjectAccessControls(BUCKET_NAME, \"allUsers\", defaultObjectAcl);\n\n      assertNotNull(response);\n      assertEquals(response.entity(), \"allUsers\");\n      assertEquals(response.role(), ObjectRole.OWNER);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testUpdateDefaultObjectAcl\")\n   public void testGetDefaultObjectAcl() {\n      ObjectAccessControls response = api().getDefaultObjectAccessControls(BUCKET_NAME, \"allUsers\");\n\n      assertNotNull(response);\n      assertEquals(response.entity(), \"allUsers\");\n      assertEquals(response.role(), ObjectRole.OWNER);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testUpdateDefaultObjectAcl\")\n   public void testListDefaultObjectAcl() {\n      List<ObjectAccessControls> response = api().listDefaultObjectAccessControls(BUCKET_NAME);\n      assertNotNull(response);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testUpdateDefaultObjectAcl\")\n   public void testPatchDefaultObjectAcl() {\n      ObjectAccessControls defaultObjectAcl = ObjectAccessControls.builder().bucket(BUCKET_NAME)\n               .entity(\"allUsers\").role(ObjectRole.READER).build();\n      ObjectAccessControls response = api().patchDefaultObjectAccessControls(BUCKET_NAME, \"allUsers\", defaultObjectAcl);\n\n      assertNotNull(response);\n      assertEquals(response.entity(), \"allUsers\");\n      assertEquals(response.role(), ObjectRole.READER);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testPatchDefaultObjectAcl\")\n   public void testDeleteBucketAcl() {\n      api().deleteDefaultObjectAccessControls(BUCKET_NAME, \"allUsers\");\n      deleteBucket(BUCKET_NAME);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testDeleteBucketAcl\")\n   public void testDeleteNotExistingBucketAccessControls() {\n      api().deleteDefaultObjectAccessControls(BUCKET_NAME, \"allUsers\");\n   }\n\n   private void deleteBucket(String bucketName) {\n      api.getBucketApi().deleteBucket(bucketName);\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/java/org/jclouds/googlecloudstorage/features/ObjectAccessControlsApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage org.jclouds.googlecloudstorage.features;\n\nimport static org.jclouds.googlecloudstorage.domain.DomainResourceReferences.ObjectRole.OWNER;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.AssertJUnit.assertNull;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.googlecloudstorage.domain.templates.ObjectAccessControlsTemplate;\nimport org.jclouds.googlecloudstorage.internal.BaseGoogleCloudStorageApiExpectTest;\nimport org.jclouds.googlecloudstorage.parse.ObjectAclGetTest;\nimport org.jclouds.googlecloudstorage.parse.ObjectAclInsertTest;\nimport org.jclouds.googlecloudstorage.parse.ObjectAclListTest;\nimport org.jclouds.googlecloudstorage.parse.ObjectAclUpdateTest;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ObjectAccessControlsApiExpectTest\")\npublic class ObjectAccessControlsApiExpectTest extends BaseGoogleCloudStorageApiExpectTest {\n\n   private static final String EXPECTED_TEST_BUCKET = \"jcloudstestbucket\";\n   private static final String EXPECTED_TEST_OBJECT = \"foo.txt\";\n   private static final String EXPECTED_TEST_GROUP_ENTITY = \"group-00b4903a971ec6cff233284d6d24f5bf5cba904c4ade4d43ebd6a5d33800e68b\";\n   private static final String EXPECTED_TEST_USER_ENTITY = \"user-00b4903a97adfde729f0650133a7379693099d8d85d6b1b18255ca70bf89e31d\";\n\n   public static final HttpRequest GET_OBJECT_ACL_REQUEST = HttpRequest\n            .builder()\n            .method(\"GET\")\n            .endpoint(\n                     \"https://www.googleapis.com/storage/v1/b/jcloudstestbucket/o/foo.txt/acl/group-00b4903a971ec6cff233284d6d24f5bf5cba904c4ade4d43ebd6a5d33800e68b\")\n            .addHeader(\"Accept\", \"application/json\").addHeader(\"Authorization\", \"Bearer \" + TOKEN).build();\n\n   public static final HttpRequest GET_OBJECT_ACL_REQUEST_WITHOPTIONS = HttpRequest\n            .builder()\n            .method(\"GET\")\n            .endpoint(\n                     \"https://www.googleapis.com/storage/v1/b/jcloudstestbucket/o/foo.txt/acl/group-00b4903a971ec6cff233284d6d24f5bf5cba904c4ade4d43ebd6a5d33800e68b\")\n            .addQueryParam(\"generation\", \"100\").addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"Authorization\", \"Bearer \" + TOKEN).build();\n\n   public final HttpResponse GET_OBJECT_ACL_RESPONSE = HttpResponse.builder().statusCode(200)\n            .payload(staticPayloadFromResource(\"/object_acl_get.json\")).build();\n\n   public final HttpResponse CREATE_OBJECT_ACL_RESPONSE = HttpResponse.builder().statusCode(200)\n            .payload(staticPayloadFromResource(\"/object_acl_insert_response.json\")).build();\n\n   public final HttpRequest LIST_OBJECT_ACL_REQUEST = HttpRequest.builder().method(\"GET\")\n            .endpoint(\"https://www.googleapis.com/storage/v1/b/jcloudstestbucket/o/foo.txt/acl\")\n            .addHeader(\"Accept\", \"application/json\").addHeader(\"Authorization\", \"Bearer \" + TOKEN).build();\n\n   public final HttpRequest LIST_OBJECT_ACL_REQUEST_WITHOPTIONS = HttpRequest.builder().method(\"GET\")\n            .endpoint(\"https://www.googleapis.com/storage/v1/b/jcloudstestbucket/o/foo.txt/acl\")\n            .addQueryParam(\"generation\", \"100\").addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"Authorization\", \"Bearer \" + TOKEN).build();\n\n   public final HttpResponse LIST_OBJECT_ACL_RESPONSE = HttpResponse.builder().statusCode(200)\n            .payload(staticPayloadFromResource(\"/object_acl_list.json\")).build();\n\n   // Test getObjectAccessControls\n   public void testGetObjectaclWithNoOptionsResponseIs2xx() throws Exception {\n\n      ObjectAccessControlsApi api = requestsSendResponses(requestForScopes(STORAGE_FULLCONTROL_SCOPE), TOKEN_RESPONSE,\n               GET_OBJECT_ACL_REQUEST, GET_OBJECT_ACL_RESPONSE).getObjectAccessControlsApi();\n\n      assertEquals(api.getObjectAccessControls(EXPECTED_TEST_BUCKET, EXPECTED_TEST_OBJECT, EXPECTED_TEST_GROUP_ENTITY),\n               new ObjectAclGetTest().expected());\n   }\n\n   public void testGetObjectaclWithOptionsResponseIs2xx() throws Exception {\n\n      ObjectAccessControlsApi api = requestsSendResponses(requestForScopes(STORAGE_FULLCONTROL_SCOPE), TOKEN_RESPONSE,\n               GET_OBJECT_ACL_REQUEST_WITHOPTIONS, GET_OBJECT_ACL_RESPONSE).getObjectAccessControlsApi();\n\n      assertEquals(\n               api.getObjectAccessControls(EXPECTED_TEST_BUCKET, EXPECTED_TEST_OBJECT, EXPECTED_TEST_GROUP_ENTITY,\n                        Long.valueOf(100)), new ObjectAclGetTest().expected());\n   }\n\n   public void testGetObjectaclResponseIs4xx() throws Exception {\n\n      HttpResponse getResponse = HttpResponse.builder().statusCode(404).build();\n\n      ObjectAccessControlsApi api = requestsSendResponses(requestForScopes(STORAGE_FULLCONTROL_SCOPE), TOKEN_RESPONSE,\n               GET_OBJECT_ACL_REQUEST, getResponse).getObjectAccessControlsApi();\n\n      assertNull(api.getObjectAccessControls(EXPECTED_TEST_BUCKET, EXPECTED_TEST_OBJECT, EXPECTED_TEST_GROUP_ENTITY));\n   }\n\n   // Test listObjectAccessControls\n   public void testListObjectaclWithNoOptionsResponseIs2xx() throws Exception {\n\n      ObjectAccessControlsApi api = requestsSendResponses(requestForScopes(STORAGE_FULLCONTROL_SCOPE), TOKEN_RESPONSE,\n               LIST_OBJECT_ACL_REQUEST, LIST_OBJECT_ACL_RESPONSE).getObjectAccessControlsApi();\n\n      assertEquals(api.listObjectAccessControls(EXPECTED_TEST_BUCKET, EXPECTED_TEST_OBJECT),\n               new ObjectAclListTest().expected());\n\n   }\n\n   // Test listObjectAccessControls\n   public void testListObjectaclWithOptionsResponseIs2xx() throws Exception {\n\n      ObjectAccessControlsApi api = requestsSendResponses(requestForScopes(STORAGE_FULLCONTROL_SCOPE), TOKEN_RESPONSE,\n               LIST_OBJECT_ACL_REQUEST_WITHOPTIONS, LIST_OBJECT_ACL_RESPONSE).getObjectAccessControlsApi();\n\n      assertEquals(api.listObjectAccessControls(EXPECTED_TEST_BUCKET, EXPECTED_TEST_OBJECT, Long.valueOf(100)),\n               new ObjectAclListTest().expected());\n\n   }\n\n   public void testListObjectaclResponseIs4xx() throws Exception {\n\n      HttpResponse listResponse = HttpResponse.builder().statusCode(404).build();\n\n      ObjectAccessControlsApi api = requestsSendResponses(requestForScopes(STORAGE_FULLCONTROL_SCOPE), TOKEN_RESPONSE,\n               LIST_OBJECT_ACL_REQUEST, listResponse).getObjectAccessControlsApi();\n\n      assertNull(api.listObjectAccessControls(EXPECTED_TEST_BUCKET, EXPECTED_TEST_OBJECT));\n   }\n\n   // Test insertObjectAccessControls\n   public void testInsertObjectaclWithNoOptionsResponseIs2xx() throws Exception {\n      HttpRequest insertRequest = HttpRequest\n               .builder()\n               .method(\"POST\")\n               .endpoint(\"https://www.googleapis.com/storage/v1/b/jcloudstestbucket/o/foo.txt/acl\")\n               .addHeader(\"Accept\", \"application/json\")\n               .addHeader(\"Authorization\", \"Bearer \" + TOKEN)\n               .payload(payloadFromResourceWithContentType(\"/object_acl_insert_request_payload.json\",\n                        MediaType.APPLICATION_JSON)).build();\n\n      ObjectAccessControlsApi api = requestsSendResponses(requestForScopes(STORAGE_FULLCONTROL_SCOPE), TOKEN_RESPONSE,\n               insertRequest, CREATE_OBJECT_ACL_RESPONSE).getObjectAccessControlsApi();\n\n      ObjectAccessControlsTemplate template = ObjectAccessControlsTemplate.create(EXPECTED_TEST_USER_ENTITY, OWNER);\n\n      assertEquals(api.createObjectAccessControls(EXPECTED_TEST_BUCKET, EXPECTED_TEST_OBJECT, template),\n               new ObjectAclInsertTest().expected());\n\n   }\n\n   public void testInsertObjectaclWithOptionsResponseIs2xx() throws Exception {\n      HttpRequest insertRequest = HttpRequest\n               .builder()\n               .method(\"POST\")\n               .endpoint(\"https://www.googleapis.com/storage/v1/b/jcloudstestbucket/o/foo.txt/acl\")\n               .addHeader(\"Accept\", \"application/json\")\n               .addHeader(\"Authorization\", \"Bearer \" + TOKEN)\n               .addQueryParam(\"generation\", \"100\")\n               .payload(payloadFromResourceWithContentType(\"/object_acl_insert_request_payload.json\",\n                        MediaType.APPLICATION_JSON)).build();\n\n      ObjectAccessControlsApi api = requestsSendResponses(requestForScopes(STORAGE_FULLCONTROL_SCOPE), TOKEN_RESPONSE,\n               insertRequest, CREATE_OBJECT_ACL_RESPONSE).getObjectAccessControlsApi();\n\n      ObjectAccessControlsTemplate template = ObjectAccessControlsTemplate\n            .create(\"user-00b4903a97adfde729f0650133a7379693099d8d85d6b1b18255ca70bf89e31d\", OWNER);\n\n      assertEquals(\n               api.createObjectAccessControls(EXPECTED_TEST_BUCKET, EXPECTED_TEST_OBJECT, template, Long.valueOf(100)),\n               new ObjectAclInsertTest().expected());\n\n   }\n\n   // Test updateObjectAccessControls\n   public void testUpdateObjectaclWithNoOptionsResponseIs2xx() throws Exception {\n      HttpRequest update = HttpRequest\n               .builder()\n               .method(\"PUT\")\n               .endpoint(\"https://www.googleapis.com/storage/v1/b/jcloudstestbucket/o/foo.txt/acl/allUsers\")\n               .addHeader(\"Accept\", \"application/json\")\n               .addHeader(\"Authorization\", \"Bearer \" + TOKEN)\n               .payload(payloadFromResourceWithContentType(\"/object_acl_request_payload.json\",\n                        MediaType.APPLICATION_JSON)).build();\n\n      HttpResponse updateResponse = HttpResponse.builder().statusCode(200)\n               .payload(staticPayloadFromResource(\"/object_acl_update_initial.json\")).build();\n\n      ObjectAccessControlsApi api = requestsSendResponses(requestForScopes(STORAGE_FULLCONTROL_SCOPE), TOKEN_RESPONSE,\n               update, updateResponse).getObjectAccessControlsApi();\n\n      ObjectAccessControlsTemplate template = ObjectAccessControlsTemplate.create(\"allUsers\", OWNER);\n\n      assertEquals(api.updateObjectAccessControls(EXPECTED_TEST_BUCKET, EXPECTED_TEST_OBJECT, \"allUsers\", template),\n               new ObjectAclUpdateTest().expected());\n   }\n\n   public void testUpdateObjectaclWithOptionsResponseIs2xx() throws Exception {\n      HttpRequest update = HttpRequest\n               .builder()\n               .method(\"PUT\")\n               .endpoint(\"https://www.googleapis.com/storage/v1/b/jcloudstestbucket/o/foo.txt/acl/allUsers\")\n               .addQueryParam(\"generation\", \"100\")\n               .addHeader(\"Accept\", \"application/json\")\n               .addHeader(\"Authorization\", \"Bearer \" + TOKEN)\n               .payload(payloadFromResourceWithContentType(\"/object_acl_request_payload.json\",\n                        MediaType.APPLICATION_JSON)).build();\n\n      HttpResponse updateResponse = HttpResponse.builder().statusCode(200)\n               .payload(staticPayloadFromResource(\"/object_acl_update_initial.json\")).build();\n\n      ObjectAccessControlsApi api = requestsSendResponses(requestForScopes(STORAGE_FULLCONTROL_SCOPE), TOKEN_RESPONSE,\n               update, updateResponse).getObjectAccessControlsApi();\n\n      ObjectAccessControlsTemplate template = ObjectAccessControlsTemplate.create(\"allUsers\", OWNER);\n\n      assertEquals(\n               api.updateObjectAccessControls(EXPECTED_TEST_BUCKET, EXPECTED_TEST_OBJECT, \"allUsers\", template,\n                        Long.valueOf(100)), new ObjectAclUpdateTest().expected());\n   }\n\n   // Test updateObjectAccessControls\n   public void testPatchObjectaclWithNoOptionsResponseIs2xx() throws Exception {\n      HttpRequest patchRequest = HttpRequest\n               .builder()\n               .method(\"POST\")\n               .endpoint(\"https://www.googleapis.com/storage/v1/b/jcloudstestbucket/o/foo.txt/acl/allUsers\")\n               .addHeader(\"Accept\", \"application/json\")\n               .addHeader(\"Authorization\", \"Bearer \" + TOKEN)\n               .addHeader(\"X-HTTP-Method-Override\", \"PATCH\")\n               .payload(payloadFromResourceWithContentType(\"/object_acl_request_payload.json\",\n                        MediaType.APPLICATION_JSON)).build();\n\n      HttpResponse patchResponse = HttpResponse.builder().statusCode(200)\n               .payload(staticPayloadFromResource(\"/object_acl_update_initial.json\")).build();\n\n      ObjectAccessControlsApi api = requestsSendResponses(requestForScopes(STORAGE_FULLCONTROL_SCOPE), TOKEN_RESPONSE,\n               patchRequest, patchResponse).getObjectAccessControlsApi();\n\n      ObjectAccessControlsTemplate template = ObjectAccessControlsTemplate.create(\"allUsers\", OWNER);\n\n      assertEquals(api.patchObjectAccessControls(EXPECTED_TEST_BUCKET, EXPECTED_TEST_OBJECT, \"allUsers\", template),\n               new ObjectAclUpdateTest().expected());\n   }\n\n   public void testPatchObjectaclWithOptionsResponseIs2xx() throws Exception {\n      HttpRequest patchRequest = HttpRequest\n               .builder()\n               .method(\"POST\")\n               .endpoint(\"https://www.googleapis.com/storage/v1/b/jcloudstestbucket/o/foo.txt/acl/allUsers\")\n               .addQueryParam(\"generation\", \"100\")\n               .addHeader(\"Accept\", \"application/json\")\n               .addHeader(\"Authorization\", \"Bearer \" + TOKEN)\n               .addHeader(\"X-HTTP-Method-Override\", \"PATCH\")\n               .payload(payloadFromResourceWithContentType(\"/object_acl_request_payload.json\",\n                        MediaType.APPLICATION_JSON)).build();\n\n      HttpResponse patchResponse = HttpResponse.builder().statusCode(200)\n               .payload(staticPayloadFromResource(\"/object_acl_update_initial.json\")).build();\n\n      ObjectAccessControlsApi api = requestsSendResponses(requestForScopes(STORAGE_FULLCONTROL_SCOPE), TOKEN_RESPONSE,\n               patchRequest, patchResponse).getObjectAccessControlsApi();\n\n      ObjectAccessControlsTemplate template = ObjectAccessControlsTemplate.create(\"allUsers\", OWNER);\n      assertEquals(\n               api.patchObjectAccessControls(EXPECTED_TEST_BUCKET, EXPECTED_TEST_OBJECT, \"allUsers\", template,\n                        Long.valueOf(100)), new ObjectAclUpdateTest().expected());\n   }\n\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/java/org/jclouds/googlecloudstorage/features/ObjectApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.features;\n\nimport static com.google.common.io.BaseEncoding.base64;\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.assertj.core.api.Assertions.entry;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.util.List;\nimport java.util.UUID;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.googlecloudstorage.domain.Bucket;\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.DestinationPredefinedAcl;\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.ObjectRole;\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.Projection;\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.StorageClass;\nimport org.jclouds.googlecloudstorage.domain.GoogleCloudStorageObject;\nimport org.jclouds.googlecloudstorage.domain.ListPageWithPrefixes;\nimport org.jclouds.googlecloudstorage.domain.ObjectAccessControls;\nimport org.jclouds.googlecloudstorage.domain.RewriteResponse;\nimport org.jclouds.googlecloudstorage.domain.templates.BucketTemplate;\nimport org.jclouds.googlecloudstorage.domain.templates.ComposeObjectTemplate;\nimport org.jclouds.googlecloudstorage.domain.templates.ObjectTemplate;\nimport org.jclouds.googlecloudstorage.internal.BaseGoogleCloudStorageApiLiveTest;\nimport org.jclouds.googlecloudstorage.options.ComposeObjectOptions;\nimport org.jclouds.googlecloudstorage.options.CopyObjectOptions;\nimport org.jclouds.googlecloudstorage.options.DeleteObjectOptions;\nimport org.jclouds.googlecloudstorage.options.GetObjectOptions;\nimport org.jclouds.googlecloudstorage.options.InsertObjectOptions;\nimport org.jclouds.googlecloudstorage.options.ListObjectOptions;\nimport org.jclouds.googlecloudstorage.options.UpdateObjectOptions;\nimport org.jclouds.http.internal.PayloadEnclosingImpl;\nimport org.jclouds.io.ByteStreams2;\nimport org.jclouds.io.ContentMetadata;\nimport org.jclouds.io.PayloadEnclosing;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.io.payloads.ByteSourcePayload;\nimport org.jclouds.utils.TestUtils;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.beust.jcommander.internal.Lists;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.hash.Hashing;\nimport com.google.common.io.ByteSource;\n\npublic class ObjectApiLiveTest extends BaseGoogleCloudStorageApiLiveTest {\n\n   private static final String BUCKET_NAME = \"jcloudsobjectoperations\" + UUID.randomUUID();\n   private static final String BUCKET_NAME2 = \"jcloudsobjectdestination\" + UUID.randomUUID();\n   private static final String UPLOAD_OBJECT_NAME = \"objectOperation.txt\";\n   private static final String UPLOAD_OBJECT_NAME2 = \"jcloudslogo.jpg\";\n   private static final String MULTIPART_UPLOAD_OBJECT = \"multipart_related.jpg\";\n   private static final String COPIED_OBJECT_NAME = \"copyofObjectOperation.txt\";\n   private static final String COPIED_OBJECT_NAME2 = \"copyObjectWithMeta.txt\";\n   private static final String COMPOSED_OBJECT = \"ComposedObject1.txt\";\n   private static final String COMPOSED_OBJECT2 = \"ComposedObject2.json\";\n   private static final String NONEXISTENT_OBJECT_NAME = \"noSuchObject.txt\";\n   private static final String REWRITE_OBJECT_NAME = \"rewriteObject.txt\";\n\n   private PayloadEnclosing testPayload;\n   private Long RANDOM_LONG = 100L;\n\n   private Long metageneration;\n   private Long generation;\n   private String md5Hash;\n   private String crc32c;\n\n   private ObjectApi api() {\n      return api.getObjectApi();\n   }\n\n   // Create the buckets\n   @BeforeClass\n   private void createBucket() {\n      BucketTemplate template = new BucketTemplate().name(BUCKET_NAME);\n      Bucket bucket = api.getBucketApi().createBucket(PROJECT_NUMBER, template);\n      assertNotNull(bucket);\n\n      BucketTemplate template2 = new BucketTemplate().name(BUCKET_NAME2);\n      Bucket bucket2 = api.getBucketApi().createBucket(PROJECT_NUMBER, template2);\n      assertNotNull(bucket2);\n   }\n\n   // Object Operations\n   @Test(groups = \"live\")\n   public void testSimpleUpload() throws IOException {\n      long contentLength = 512L;\n      ByteSource byteSource = TestUtils.randomByteSource().slice(0, contentLength);\n      ByteSourcePayload byteSourcePayload = Payloads.newByteSourcePayload(byteSource);\n\n      PayloadEnclosing payload = new PayloadEnclosingImpl(byteSourcePayload);\n      payload.getPayload().getContentMetadata().setContentLength(contentLength);\n\n      this.testPayload = payload;\n\n      InsertObjectOptions options = new InsertObjectOptions().name(UPLOAD_OBJECT_NAME);\n\n      GoogleCloudStorageObject gcsObject = api().simpleUpload(BUCKET_NAME, \"text/plain\",\n               payload.getPayload().getContentMetadata().getContentLength(), payload.getPayload(), options);\n\n      assertNotNull(gcsObject);\n      assertEquals(gcsObject.bucket(), BUCKET_NAME);\n      assertEquals(gcsObject.name(), UPLOAD_OBJECT_NAME);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testSimpleUpload\")\n   public void testRewrite() throws IOException {\n      GoogleCloudStorageObject gcsObject = api().getObject(BUCKET_NAME, UPLOAD_OBJECT_NAME);\n      System.out.println(gcsObject);\n\n      RewriteResponse response = api().rewriteObjects(BUCKET_NAME, REWRITE_OBJECT_NAME, BUCKET_NAME, UPLOAD_OBJECT_NAME);\n      assertNotNull(response);\n      assertTrue(response.done());\n      assertEquals(response.objectSize(), 512);\n      assertEquals(response.totalBytesRewritten(), 512);\n      assertEquals(response.rewriteToken(), null);\n      assertNotNull(response.resource());\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testRewrite\")\n   public void testDownload() throws IOException {\n      PayloadEnclosing impl = api().download(BUCKET_NAME, UPLOAD_OBJECT_NAME);\n      ContentMetadata meta = impl.getPayload().getContentMetadata();\n      assertNotNull(impl);\n      assertNotNull(impl.getPayload());\n      assertNotNull(meta);\n      assertEquals(meta.getContentType(), \"text/plain\");\n\n      testPayload.getPayload().getContentMetadata().setContentDisposition(\"attachment\");\n\n      assertEquals(ByteStreams2.toByteArrayAndClose(impl.getPayload().openStream()),\n               ByteStreams2.toByteArrayAndClose(testPayload.getPayload().openStream()));\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testSimpleUpload\")\n   public void testSimpleJpegUpload() throws IOException {\n      long contentLength = 2 * 1024L;\n      ByteSource testSource = TestUtils.randomByteSource().slice(0, contentLength);\n      ByteSourcePayload payload = Payloads.newByteSourcePayload(testSource);\n\n      InsertObjectOptions options = new InsertObjectOptions().name(UPLOAD_OBJECT_NAME2);\n\n      GoogleCloudStorageObject gcsObject = api().simpleUpload(BUCKET_NAME, \"image/jpeg\", contentLength, payload, options);\n\n      assertNotNull(gcsObject);\n      assertEquals(gcsObject.bucket(), BUCKET_NAME);\n      assertEquals(gcsObject.name(), UPLOAD_OBJECT_NAME2);\n\n      // This is a client side validation of md5\n      md5Hash = base64().encode(testSource.hash(Hashing.md5()).asBytes());\n      // TODO: crc32c = without making a compile dep on guava 18.\n\n      checkHashCodes(gcsObject);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testSimpleUpload\")\n   public void testGetObject() {\n      GoogleCloudStorageObject gcsObject = api().getObject(BUCKET_NAME, UPLOAD_OBJECT_NAME);\n\n      assertNotNull(gcsObject);\n\n      metageneration = gcsObject.metageneration();\n      generation = gcsObject.generation();\n\n      assertEquals(gcsObject.bucket(), BUCKET_NAME);\n      assertEquals(gcsObject.name(), UPLOAD_OBJECT_NAME);\n      assertEquals(gcsObject.contentType(), \"text/plain\");\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testGetObject\")\n   public void testGetObjectWithOptions() {\n      GetObjectOptions options = new GetObjectOptions().ifGenerationMatch(generation)\n               .ifMetagenerationMatch(metageneration).ifGenerationNotMatch(generation + 1).projection(Projection.FULL);\n\n      GoogleCloudStorageObject gcsObject = api().getObject(BUCKET_NAME, UPLOAD_OBJECT_NAME, options);\n\n      assertNotNull(gcsObject);\n      assertNotNull(gcsObject.acl());\n      assertEquals(gcsObject.bucket(), BUCKET_NAME);\n      assertEquals(gcsObject.name(), UPLOAD_OBJECT_NAME);\n      assertEquals(gcsObject.contentType(), \"text/plain\");\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testGetObject\")\n   public void testCopyObject() throws IOException {\n      GoogleCloudStorageObject gcsObject = api().copyObject(BUCKET_NAME2, COPIED_OBJECT_NAME, BUCKET_NAME, UPLOAD_OBJECT_NAME);\n\n      assertNotNull(gcsObject);\n      assertEquals(gcsObject.bucket(), BUCKET_NAME2);\n      assertEquals(gcsObject.name(), COPIED_OBJECT_NAME);\n      assertEquals(gcsObject.contentType(), \"text/plain\");\n\n      // Test for data\n\n      PayloadEnclosing impl = api().download(BUCKET_NAME2, COPIED_OBJECT_NAME);\n      assertNotNull(impl);\n      assertEquals(ByteStreams2.toByteArrayAndClose(impl.getPayload().openStream()),\n               ByteStreams2.toByteArrayAndClose(testPayload.getPayload().openStream()));\n\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testGetObject\")\n   public void testCopyObjectWithUpdatedMetadata() throws IOException {\n      String METADATA_KEY = \"key1\";\n      String METADATA_VALUE = \"value1\";\n\n      ObjectTemplate template = new ObjectTemplate().contentLanguage(\"fr\").contentType(\"text/plain\")\n               .contentDisposition(\"attachment\").customMetadata(METADATA_KEY, METADATA_VALUE);\n\n      GoogleCloudStorageObject gcsObject = api().copyObject(BUCKET_NAME2, COPIED_OBJECT_NAME2, BUCKET_NAME, UPLOAD_OBJECT_NAME, template);\n\n      assertNotNull(gcsObject);\n      assertEquals(gcsObject.bucket(), BUCKET_NAME2);\n      assertEquals(gcsObject.name(), COPIED_OBJECT_NAME2);\n      assertNotNull(gcsObject.acl());\n      assertEquals(gcsObject.contentType(), \"text/plain\");\n      assertEquals(gcsObject.metadata().get(METADATA_KEY), METADATA_VALUE);\n      assertEquals(gcsObject.contentLanguage(), \"fr\");\n      // Test for data\n\n      PayloadEnclosing impl = api().download(BUCKET_NAME2, COPIED_OBJECT_NAME2);\n      assertNotNull(impl);\n      assertEquals(ByteStreams2.toByteArrayAndClose(impl.getPayload().openStream()),\n               ByteStreams2.toByteArrayAndClose(testPayload.getPayload().openStream()));\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testCopyObject\")\n   public void testCopyObjectWithOptions() {\n      CopyObjectOptions options = new CopyObjectOptions().ifSourceGenerationMatch(generation)\n               .ifSourceMetagenerationMatch(metageneration).projection(Projection.FULL);\n\n      GoogleCloudStorageObject gcsObject = api()\n               .copyObject(BUCKET_NAME2, UPLOAD_OBJECT_NAME, BUCKET_NAME, UPLOAD_OBJECT_NAME, options);\n\n      assertNotNull(gcsObject);\n      assertNotNull(gcsObject.acl());\n      assertEquals(gcsObject.bucket(), BUCKET_NAME2);\n      assertEquals(gcsObject.name(), UPLOAD_OBJECT_NAME);\n      assertEquals(gcsObject.contentType(), \"text/plain\");\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testCopyObjectWithOptions\")\n   public void testComposeObject() {\n      ObjectAccessControls oacl = ObjectAccessControls.builder().bucket(BUCKET_NAME).entity(\"allUsers\")\n               .role(ObjectRole.OWNER).build();\n\n      ObjectTemplate destination = new ObjectTemplate().contentType(\"text/plain\").addAcl(oacl);\n      List<GoogleCloudStorageObject> sourceList = Lists.newArrayList();\n      sourceList.add(api().getObject(BUCKET_NAME2, UPLOAD_OBJECT_NAME));\n      sourceList.add(api().getObject(BUCKET_NAME2, COPIED_OBJECT_NAME));\n\n      ComposeObjectTemplate requestTemplate = ComposeObjectTemplate.builder()\n         .fromGoogleCloudStorageObject(sourceList)\n         .destination(destination)\n         .build();\n\n      GoogleCloudStorageObject gcsObject = api().composeObjects(BUCKET_NAME2, COMPOSED_OBJECT, requestTemplate);\n\n      assertNotNull(gcsObject);\n      assertNotNull(gcsObject.acl());\n      assertEquals(gcsObject.bucket(), BUCKET_NAME2);\n      assertEquals(gcsObject.name(), COMPOSED_OBJECT);\n      assertEquals(gcsObject.contentType(), \"text/plain\");\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testComposeObject\")\n   public void testComposeObjectWithOptions() {\n      ObjectTemplate destination = new ObjectTemplate().contentType(MediaType.APPLICATION_JSON);\n      List<GoogleCloudStorageObject> sourceList = Lists.newArrayList();\n      sourceList.add(api().getObject(BUCKET_NAME2, UPLOAD_OBJECT_NAME));\n      sourceList.add(api().getObject(BUCKET_NAME2, COPIED_OBJECT_NAME));\n\n      ComposeObjectTemplate requestTemplate =  ComposeObjectTemplate.builder()\n         .fromGoogleCloudStorageObject(sourceList)\n         .destination(destination)\n         .build();\n      ComposeObjectOptions options = new ComposeObjectOptions().destinationPredefinedAcl(\n               DestinationPredefinedAcl.BUCKET_OWNER_READ).ifMetagenerationNotMatch(RANDOM_LONG);\n\n      GoogleCloudStorageObject gcsObject = api().composeObjects(BUCKET_NAME2, COMPOSED_OBJECT2, requestTemplate, options);\n\n      assertNotNull(gcsObject);\n      assertNotNull(gcsObject.acl());\n      assertEquals(gcsObject.bucket(), BUCKET_NAME2);\n      assertEquals(gcsObject.name(), COMPOSED_OBJECT2);\n      assertEquals(gcsObject.contentType(), MediaType.APPLICATION_JSON);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testComposeObjectWithOptions\")\n   public void listObjects() {\n      ListPageWithPrefixes<GoogleCloudStorageObject> list = api().listObjects(BUCKET_NAME);\n\n      assertNotNull(list);\n      assertNotEquals(list.size(), 0);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testComposeObjectWithOptions\")\n   public void testListObjectsWithOptions() {\n      ListObjectOptions options = new ListObjectOptions().maxResults(1);\n      ListPageWithPrefixes<GoogleCloudStorageObject> list = api().listObjects(BUCKET_NAME, options);\n\n      while (list.nextPageToken() != null) {\n         assertNotNull(list);\n         assertEquals(list.size(), 1);\n\n         options = new ListObjectOptions().maxResults(1).pageToken(list.nextPageToken());\n         list = api().listObjects(BUCKET_NAME, options);\n      }\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testComposeObjectWithOptions\")\n   public void testUpdateObject() {\n      ObjectAccessControls oacl = ObjectAccessControls.builder().bucket(BUCKET_NAME).entity(\"allUsers\")\n               .role(ObjectRole.OWNER).build();\n\n      ObjectTemplate template = new ObjectTemplate().addAcl(oacl).contentType(\"image/jpeg\");\n      GoogleCloudStorageObject gcsObject = api().updateObject(BUCKET_NAME, UPLOAD_OBJECT_NAME2, template);\n\n      assertNotNull(gcsObject);\n      assertNotNull(gcsObject.acl());\n      assertEquals(gcsObject.bucket(), BUCKET_NAME);\n      assertEquals(gcsObject.name(), UPLOAD_OBJECT_NAME2);\n      assertEquals(gcsObject.contentType(), \"image/jpeg\");\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testUpdateObject\")\n   public void testUpdateObjectWithOptions() {\n      String METADATA_KEY = \"key1\";\n      String METADATA_VALUE = \"value1\";\n\n      ObjectAccessControls oacl = ObjectAccessControls.builder().bucket(BUCKET_NAME).entity(\"allUsers\")\n               .role(ObjectRole.OWNER).build();\n\n      UpdateObjectOptions options = new UpdateObjectOptions().ifMetagenerationNotMatch(RANDOM_LONG)\n               .ifGenerationNotMatch(RANDOM_LONG);\n\n      ObjectTemplate template = new ObjectTemplate().addAcl(oacl).contentType(\"image/jpeg\")\n               .contentDisposition(\"attachment\").customMetadata(METADATA_KEY, METADATA_VALUE);\n      GoogleCloudStorageObject gcsObject = api().updateObject(BUCKET_NAME, UPLOAD_OBJECT_NAME2, template, options);\n\n      assertNotNull(gcsObject);\n      assertNotNull(gcsObject.acl());\n      assertEquals(gcsObject.bucket(), BUCKET_NAME);\n      assertEquals(gcsObject.name(), UPLOAD_OBJECT_NAME2);\n      assertEquals(gcsObject.contentType(), \"image/jpeg\");\n      assertNotNull(gcsObject.metadata());\n      assertNotNull(gcsObject.metadata().get(METADATA_KEY), METADATA_VALUE);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testUpdateObjectWithOptions\")\n   public void testPatchObject() {\n      ObjectAccessControls oacl = ObjectAccessControls.builder().bucket(BUCKET_NAME).entity(\"allUsers\")\n               .role(ObjectRole.READER).build();\n\n      ObjectTemplate template = new ObjectTemplate().addAcl(oacl).contentType(\"image/jpeg\");\n      GoogleCloudStorageObject gcsObject = api().patchObject(BUCKET_NAME, UPLOAD_OBJECT_NAME2, template);\n\n      assertNotNull(gcsObject);\n      assertNotNull(gcsObject.acl());\n      assertEquals(gcsObject.bucket(), BUCKET_NAME);\n      assertEquals(gcsObject.name(), UPLOAD_OBJECT_NAME2);\n      assertEquals(gcsObject.contentType(), \"image/jpeg\");\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testPatchObject\")\n   public void testPatchObjectsWithOptions() {\n      ObjectAccessControls oacl = ObjectAccessControls.builder().bucket(BUCKET_NAME).entity(\"allUsers\")\n               .role(ObjectRole.OWNER).build();\n\n      UpdateObjectOptions options = new UpdateObjectOptions().ifMetagenerationNotMatch(RANDOM_LONG)\n               .ifGenerationNotMatch(RANDOM_LONG);\n\n\n      ObjectTemplate template = new ObjectTemplate().addAcl(oacl).contentType(\"image/jpeg\")\n               .contentDisposition(\"attachment\");\n      GoogleCloudStorageObject gcsObject = api().patchObject(BUCKET_NAME, UPLOAD_OBJECT_NAME2, template, options);\n\n      assertNotNull(gcsObject);\n      assertNotNull(gcsObject.acl());\n      assertEquals(gcsObject.bucket(), BUCKET_NAME);\n      assertEquals(gcsObject.name(), UPLOAD_OBJECT_NAME2);\n      assertEquals(gcsObject.contentType(), \"image/jpeg\");\n      assertEquals(gcsObject.contentDisposition(), \"attachment\");\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testPatchObjectsWithOptions\")\n   public void testMultipartJpegUpload() throws IOException {\n      long contentLength = 32 * 1024L;\n      ByteSource byteSource = TestUtils.randomByteSource().slice(0, contentLength);\n      ByteSourcePayload payload = Payloads.newByteSourcePayload(byteSource);\n      PayloadEnclosing payloadImpl = new PayloadEnclosingImpl(payload);\n\n      ObjectTemplate template = new ObjectTemplate();\n\n      ObjectAccessControls oacl = ObjectAccessControls.builder().bucket(BUCKET_NAME).entity(\"allUsers\")\n               .role(ObjectRole.OWNER).build();\n\n      // This would trigger server side validation of md5\n      md5Hash = base64().encode(byteSource.hash(Hashing.md5()).asBytes());\n      // TODO: crc32c = without making a compile dep on guava 18\n\n      template.contentType(\"image/jpeg\").addAcl(oacl).size(contentLength).name(MULTIPART_UPLOAD_OBJECT)\n               .contentLanguage(\"en\").contentDisposition(\"attachment\").md5Hash(md5Hash)\n               .storageClass(StorageClass.NEARLINE)\n               .customMetadata(\"custommetakey1\", \"custommetavalue1\").crc32c(crc32c)\n               .customMetadata(ImmutableMap.of(\"Adrian\", \"powderpuff\"));\n\n      GoogleCloudStorageObject gcsObject = api().multipartUpload(BUCKET_NAME, template, payloadImpl.getPayload());\n\n      assertThat(gcsObject.bucket()).isEqualTo(BUCKET_NAME);\n      assertThat(gcsObject.name()).isEqualTo(MULTIPART_UPLOAD_OBJECT);\n      checkHashCodes(gcsObject);\n\n      assertThat(gcsObject.metadata()).contains(entry(\"custommetakey1\", \"custommetavalue1\"),\n               entry(\"Adrian\", \"powderpuff\")).doesNotContainKey(\"adrian\");\n\n      gcsObject = api().getObject(BUCKET_NAME, MULTIPART_UPLOAD_OBJECT, null);\n\n      assertThat(gcsObject).isNotNull();\n      assertThat(gcsObject.storageClass()).isEqualTo(StorageClass.NEARLINE);\n\n      PayloadEnclosing impl = api().download(BUCKET_NAME, MULTIPART_UPLOAD_OBJECT);\n\n      assertThat(ByteStreams2.toByteArrayAndClose(impl.getPayload().openStream())).isEqualTo(\n               ByteStreams2.toByteArrayAndClose(payloadImpl.getPayload().openStream()));\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testPatchObjectsWithOptions\")\n   public void testMultipartJpegUploadArchive() throws IOException {\n      long contentLength = 32 * 1024L;\n      ByteSource byteSource = TestUtils.randomByteSource().slice(0, contentLength);\n      ByteSourcePayload payload = Payloads.newByteSourcePayload(byteSource);\n      PayloadEnclosing payloadImpl = new PayloadEnclosingImpl(payload);\n\n      ObjectTemplate template = new ObjectTemplate();\n\n      ObjectAccessControls oacl = ObjectAccessControls.builder().bucket(BUCKET_NAME).entity(\"allUsers\")\n               .role(ObjectRole.OWNER).build();\n\n      // This would trigger server side validation of md5\n      md5Hash = base64().encode(byteSource.hash(Hashing.md5()).asBytes());\n      // TODO: crc32c = without making a compile dep on guava 18\n\n      template.contentType(\"image/jpeg\").addAcl(oacl).size(contentLength).name(MULTIPART_UPLOAD_OBJECT)\n               .contentLanguage(\"en\").contentDisposition(\"attachment\").md5Hash(md5Hash)\n               .storageClass(StorageClass.ARCHIVE)\n               .customMetadata(\"custommetakey1\", \"custommetavalue1\").crc32c(crc32c)\n               .customMetadata(ImmutableMap.of(\"Adrian\", \"powderpuff\"));\n\n      GoogleCloudStorageObject gcsObject = api().multipartUpload(BUCKET_NAME, template, payloadImpl.getPayload());\n\n      assertThat(gcsObject.bucket()).isEqualTo(BUCKET_NAME);\n      assertThat(gcsObject.name()).isEqualTo(MULTIPART_UPLOAD_OBJECT);\n      checkHashCodes(gcsObject);\n\n      assertThat(gcsObject.metadata()).contains(entry(\"custommetakey1\", \"custommetavalue1\"),\n               entry(\"Adrian\", \"powderpuff\")).doesNotContainKey(\"adrian\");\n\n      gcsObject = api().getObject(BUCKET_NAME, MULTIPART_UPLOAD_OBJECT, null);\n\n      assertThat(gcsObject).isNotNull();\n      assertThat(gcsObject.storageClass()).isEqualTo(StorageClass.ARCHIVE);\n\n      PayloadEnclosing impl = api().download(BUCKET_NAME, MULTIPART_UPLOAD_OBJECT);\n\n      assertThat(ByteStreams2.toByteArrayAndClose(impl.getPayload().openStream())).isEqualTo(\n               ByteStreams2.toByteArrayAndClose(payloadImpl.getPayload().openStream()));\n   }\n\n   private void checkHashCodes(GoogleCloudStorageObject gcsObject) {\n      assertEquals(gcsObject.md5Hash(), md5Hash);\n      if (crc32c != null) {\n         assertEquals(gcsObject.crc32c(), crc32c);\n      }\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testMultipartJpegUpload\")\n   public void testDeleteObject() {\n      assertTrue(api().deleteObject(BUCKET_NAME2, UPLOAD_OBJECT_NAME));\n      assertTrue(api().deleteObject(BUCKET_NAME2, COMPOSED_OBJECT2));\n      assertTrue(api().deleteObject(BUCKET_NAME2, COMPOSED_OBJECT));\n      assertTrue(api().deleteObject(BUCKET_NAME2, COPIED_OBJECT_NAME));\n      assertTrue(api().deleteObject(BUCKET_NAME2, COPIED_OBJECT_NAME2));\n      assertFalse(api().deleteObject(BUCKET_NAME, UPLOAD_OBJECT_NAME));\n      assertTrue(api().deleteObject(BUCKET_NAME, UPLOAD_OBJECT_NAME2));\n      assertTrue(api().deleteObject(BUCKET_NAME, MULTIPART_UPLOAD_OBJECT));\n      assertTrue(api().deleteObject(BUCKET_NAME, REWRITE_OBJECT_NAME));\n      assertFalse(api().deleteObject(BUCKET_NAME, NONEXISTENT_OBJECT_NAME));\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testPatchObjectsWithOptions\")\n   public void testDeleteObjectWithOptions() {\n      DeleteObjectOptions options = new DeleteObjectOptions().ifGenerationMatch(generation).ifMetagenerationMatch(\n               metageneration);\n      api().deleteObject(BUCKET_NAME, UPLOAD_OBJECT_NAME, options);\n   }\n\n   @AfterClass\n   private void deleteBucket() {\n      api.getBucketApi().deleteBucket(BUCKET_NAME);\n      api.getBucketApi().deleteBucket(BUCKET_NAME2);\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/java/org/jclouds/googlecloudstorage/features/ObjectApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.Assert.assertFalse;\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.RecordedRequest;\n\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.DestinationPredefinedAcl;\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.PredefinedAcl;\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.Projection;\nimport org.jclouds.googlecloudstorage.domain.templates.ComposeObjectTemplate;\nimport org.jclouds.googlecloudstorage.domain.templates.ObjectTemplate;\nimport org.jclouds.googlecloudstorage.internal.BaseGoogleCloudStorageApiMockTest;\nimport org.jclouds.googlecloudstorage.options.ComposeObjectOptions;\nimport org.jclouds.googlecloudstorage.options.CopyObjectOptions;\nimport org.jclouds.googlecloudstorage.options.GetObjectOptions;\nimport org.jclouds.googlecloudstorage.options.InsertObjectOptions;\nimport org.jclouds.googlecloudstorage.options.ListObjectOptions;\nimport org.jclouds.googlecloudstorage.options.RewriteObjectOptions;\nimport org.jclouds.googlecloudstorage.parse.ParseGoogleCloudStorageObject;\nimport org.jclouds.googlecloudstorage.parse.ParseGoogleCloudStorageObjectListTest;\nimport org.jclouds.googlecloudstorage.parse.ParseObjectRewriteResponse;\nimport org.jclouds.http.internal.PayloadEnclosingImpl;\nimport org.jclouds.io.PayloadEnclosing;\nimport org.jclouds.util.Strings2;\nimport org.testng.annotations.Test;\n\nimport com.google.common.net.MediaType;\n\n\n@Test(groups = \"unit\", testName = \"ObjectApiMockTest\", singleThreaded = true)\npublic class ObjectApiMockTest extends BaseGoogleCloudStorageApiMockTest {\n\n\n   public void exists() throws Exception {\n      server.enqueue(jsonResponse(\"/object_get.json\"));\n\n      assertTrue(objectApi().objectExists(\"test\", \"file_name\"));\n      assertSent(server, \"GET\", \"/storage/v1/b/test/o/file_name\", null);\n   }\n\n   public void existsEncoded() throws Exception {\n      server.enqueue(jsonResponse(\"/object_encoded_get.json\"));\n\n      assertTrue(objectApi().objectExists(\"test\", Strings2.urlEncode(\"dir/file name\")));\n      assertSent(server, \"GET\", \"/storage/v1/b/test/o/dir%2Ffile%20name\", null);\n   }\n\n   public void exists_4xx() throws Exception {\n      server.enqueue(response404());\n\n      assertFalse(objectApi().objectExists(\"test\", \"file_name\"));\n      assertSent(server, \"GET\", \"/storage/v1/b/test/o/file_name\", null);\n   }\n\n   public void get() throws Exception {\n      server.enqueue(jsonResponse(\"/object_get.json\"));\n\n      assertEquals(objectApi().getObject(\"test\", \"file_name\"),\n            new ParseGoogleCloudStorageObject().expected());\n      assertSent(server, \"GET\", \"/storage/v1/b/test/o/file_name\");\n   }\n\n   public void get_4xx() throws Exception {\n      server.enqueue(response404());\n\n      assertNull(objectApi().getObject(\"test\", \"file_name\"));\n      assertSent(server, \"GET\", \"/storage/v1/b/test/o/file_name\");\n   }\n\n   public void get_with_options() throws Exception {\n      server.enqueue(jsonResponse(\"/object_get.json\"));\n\n      GetObjectOptions options = new GetObjectOptions().ifGenerationMatch((long) 1000);\n      options.range(0, 1023);\n\n      assertEquals(objectApi().getObject(\"test\", \"file_name\", options),\n            new ParseGoogleCloudStorageObject().expected());\n      RecordedRequest request = assertSent(server, \"GET\", \"/storage/v1/b/test/o/file_name?ifGenerationMatch=1000\");\n      assertEquals(request.getHeader(\"Range\"), \"bytes=0-1023\");\n   }\n\n   public void simpleUpload() throws Exception {\n      server.enqueue(jsonResponse(\"/object_get.json\"));\n\n      PayloadEnclosing p = new PayloadEnclosingImpl();\n      String testPayload = \"this is a test payload for upload!\";\n      p.setPayload(testPayload.getBytes());\n\n      InsertObjectOptions options = new InsertObjectOptions()\n         .name(\"new_object\")\n         .predefinedAcl(PredefinedAcl.PUBLIC_READ_WRITE);\n\n      assertEquals(objectApi().simpleUpload(\"bucket_name\", \"text/plain\",\n            p.getPayload().getContentMetadata().getContentLength(), p.getPayload(), options),\n            new ParseGoogleCloudStorageObject().expected());\n\n      RecordedRequest request = assertSent(server, \"POST\", \"/upload/storage/v1/b/bucket_name/o\" +\n         \"?uploadType=media&name=new_object&predefinedAcl=publicReadWrite\", null);\n      assertEquals(request.getHeader(\"Content-Type\"), \"text/plain\");\n      assertEquals(request.getBody().readUtf8(), testPayload);\n   }\n\n   public void delete() throws Exception {\n      server.enqueue(new MockResponse());\n\n      // TODO: Should this be returning True on not found?\n      assertTrue(objectApi().deleteObject(\"test\", \"object_name\"));\n      assertSent(server, \"DELETE\", \"/storage/v1/b/test/o/object_name\", null);\n   }\n\n   public void delete_encoded() throws Exception {\n      server.enqueue(new MockResponse());\n\n      // TODO: Should this be returning True on not found?\n      assertTrue(objectApi().deleteObject(\"test\", Strings2.urlEncode(\"dir/object name\")));\n      assertSent(server, \"DELETE\", \"/storage/v1/b/test/o/dir%2Fobject%20name\", null);\n   }\n\n   public void list() throws Exception {\n      server.enqueue(jsonResponse(\"/object_list.json\"));\n\n      assertEquals(objectApi().listObjects(\"test\"),\n            new ParseGoogleCloudStorageObjectListTest().expected());\n      assertSent(server, \"GET\", \"/storage/v1/b/test/o\");\n   }\n\n   public void list_with_options() throws Exception {\n      server.enqueue(jsonResponse(\"/object_list.json\"));\n      ListObjectOptions options = new ListObjectOptions()\n         .delimiter(\"-\")\n         .prefix(\"test\")\n         .versions(Boolean.TRUE)\n         .pageToken(\"asdf\")\n         .maxResults(4)\n         .projection(Projection.FULL);\n      assertEquals(objectApi().listObjects(\"test\", options),\n            new ParseGoogleCloudStorageObjectListTest().expected());\n      assertSent(server, \"GET\", \"/storage/v1/b/test/o?\" +\n        \"delimiter=-&prefix=test&versions=true&pageToken=asdf&maxResults=4&projection=full\");\n   }\n\n   public void update() throws Exception {\n      server.enqueue(jsonResponse(\"/object_get.json\"));\n\n      ObjectTemplate template = new ObjectTemplate().name(\"file_name\").size((long) 1000).crc32c(\"crc32c\");\n\n      assertEquals(objectApi().updateObject(\"test\", \"file_name\", template),\n            new ParseGoogleCloudStorageObject().expected());\n      assertSent(server, \"PUT\", \"/storage/v1/b/test/o/file_name\", APPLICATION_JSON,\n            \"{\" +\n            \"  \\\"name\\\": \\\"file_name\\\",\" +\n            \"  \\\"size\\\": 1000,\" +\n            \"  \\\"crc32c\\\": \\\"crc32c\\\"\" +\n            \"}\");\n   }\n\n   public void patch() throws Exception {\n      server.enqueue(jsonResponse(\"/object_get.json\"));\n\n      ObjectTemplate template = new ObjectTemplate().name(\"file_name\").size((long) 1000).crc32c(\"crc32c\");\n\n      assertEquals(objectApi().patchObject(\"test\", \"file_name\", template),\n            new ParseGoogleCloudStorageObject().expected());\n      assertSent(server, \"POST\", \"/storage/v1/b/test/o/file_name\", APPLICATION_JSON,\n            \"{\" +\n            \"  \\\"name\\\": \\\"file_name\\\",\" +\n            \"  \\\"size\\\": 1000,\" +\n            \"  \\\"crc32c\\\": \\\"crc32c\\\"\" +\n            \"}\");\n   }\n\n   public void compose() throws Exception {\n      server.enqueue(jsonResponse(\"/object_get.json\"));\n\n      ObjectTemplate template = new ObjectTemplate().name(\"file_name\").size((long) 1000).crc32c(\"crc32c\");\n\n      ComposeObjectTemplate composeTemplate = ComposeObjectTemplate.builder()\n      .fromGoogleCloudStorageObject(new ParseGoogleCloudStorageObjectListTest().expected())\n      .destination(template).build();\n\n      assertEquals(objectApi().composeObjects(\"destination_bucket\", \"destination_object\", composeTemplate),\n            new ParseGoogleCloudStorageObject().expected());\n      assertSent(server, \"POST\", \"/storage/v1/b/destination_bucket/o/destination_object/compose\", APPLICATION_JSON,\n            stringFromResource(\"/object_compose_request.json\"));\n   }\n\n   public void compose_with_options() throws Exception {\n      server.enqueue(jsonResponse(\"/object_get.json\"));\n\n      ObjectTemplate template = new ObjectTemplate().name(\"file_name\").size((long) 1000).crc32c(\"crc32c\");\n      ComposeObjectTemplate composeTemplate = ComposeObjectTemplate.builder()\n      .fromGoogleCloudStorageObject(new ParseGoogleCloudStorageObjectListTest().expected())\n      .destination(template).build();\n\n      ComposeObjectOptions options = new ComposeObjectOptions()\n         .destinationPredefinedAcl(DestinationPredefinedAcl.BUCKET_OWNER_FULLCONTROL)\n         .ifMetagenerationMatch((long) 15);\n\n      assertEquals(objectApi().composeObjects(\"destination_bucket\", \"destination_object\", composeTemplate, options),\n            new ParseGoogleCloudStorageObject().expected());\n      assertSent(server, \"POST\", \"/storage/v1/b/destination_bucket/o/destination_object/compose\" +\n            \"?destinationPredefinedAcl=bucketOwnerFullcontrol&ifMetagenerationMatch=15\", APPLICATION_JSON,\n            stringFromResource(\"/object_compose_request.json\"));\n   }\n\n   public void copy() throws Exception {\n      server.enqueue(jsonResponse(\"/object_get.json\"));\n\n      assertEquals(objectApi().copyObject(\"destination_bucket\", \"destination_object\", \"source_bucket\", \"source_object\"),\n            new ParseGoogleCloudStorageObject().expected());\n      assertSent(server, \"POST\", \"/storage/v1/b/source_bucket/o/source_object/copyTo\" +\n              \"/b/destination_bucket/o/destination_object\", APPLICATION_JSON);\n   }\n\n    public void copy_update_metadata() throws Exception {\n        server.enqueue(jsonResponse(\"/object_get.json\"));\n\n        ObjectTemplate template = new ObjectTemplate().name(\"file_name\").size((long) 1000).crc32c(\"crc32c\");\n\n        assertEquals(objectApi().copyObject(\"destination_bucket\", \"destination_object\", \"source_bucket\", \"source_object\", template),\n                new ParseGoogleCloudStorageObject().expected());\n        assertSent(server, \"POST\", \"/storage/v1/b/source_bucket/o/source_object/copyTo\" +\n                \"/b/destination_bucket/o/destination_object\", APPLICATION_JSON, \"{\" +\n                \"  \\\"name\\\": \\\"file_name\\\",\" +\n                \"  \\\"size\\\": 1000,\" +\n                \"  \\\"crc32c\\\": \\\"crc32c\\\"\" +\n                \"}\");\n    }\n\n   public void copy_with_options() throws Exception {\n      server.enqueue(jsonResponse(\"/object_get.json\"));\n\n      CopyObjectOptions options = new CopyObjectOptions().ifGenerationMatch((long) 50);\n\n      assertEquals(objectApi().copyObject(\"destination_bucket\", \"destination_object\", \"source_bucket\", \"source_object\", options),\n            new ParseGoogleCloudStorageObject().expected());\n      assertSent(server, \"POST\", \"/storage/v1/b/source_bucket/o/source_object/copyTo\" +\n              \"/b/destination_bucket/o/destination_object?ifGenerationMatch=50\", APPLICATION_JSON);\n   }\n\n   public void multipartUpload() throws Exception {\n      server.enqueue(jsonResponse(\"/object_get.json\"));\n\n      PayloadEnclosing p = new PayloadEnclosingImpl();\n      String testPayload = \"this is a test payload for upload!\";\n      p.setPayload(testPayload.getBytes());\n\n      ObjectTemplate template = new ObjectTemplate().name(\"file_name\").size((long) testPayload.length()).crc32c(\"crc32c\").contentType(MediaType.ANY_TEXT_TYPE);\n\n      assertEquals(objectApi().multipartUpload(\"bucket_name\", template, p.getPayload()),\n            new ParseGoogleCloudStorageObject().expected());\n\n      RecordedRequest request = assertSent(server, \"POST\", \"/upload/storage/v1/b/bucket_name/o?uploadType=multipart\", null);\n      assertTrue(request.getBody().readUtf8().contains(testPayload));\n\n      //TODO: this should be a more robust assertion about the formatting of the payload\n   }\n\n   public void rewrite() throws Exception {\n      server.enqueue(jsonResponse(\"/object_rewrite.json\"));\n\n      assertEquals(objectApi().rewriteObjects(\"destinationBucket\", \"destinationObject\", \"sourceBucket\", \"sourceObject\"),\n            new ParseObjectRewriteResponse().expected());\n\n      assertSent(server, \"POST\", \"/storage/v1/b/sourceBucket/o/sourceObject/rewriteTo/b/destinationBucket/o/destinationObject\");\n   }\n\n   public void rewriteWithOptions() throws Exception {\n      server.enqueue(jsonResponse(\"/object_rewrite.json\"));\n\n      RewriteObjectOptions options = new RewriteObjectOptions.Builder().rewriteToken(\"rewriteToken\");\n      assertEquals(objectApi().rewriteObjects(\"destinationBucket\", \"destinationObject\", \"sourceBucket\", \"sourceObject\", options),\n            new ParseObjectRewriteResponse().expected());\n\n      assertSent(server, \"POST\",\n            \"/storage/v1/b/sourceBucket/o/sourceObject/rewriteTo/b/destinationBucket/o/destinationObject?rewriteToken=rewriteToken\");\n   }\n\n   public ObjectApi objectApi(){\n      return api().getObjectApi();\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/java/org/jclouds/googlecloudstorage/features/ResumableUploadApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.features;\n\nimport static jakarta.ws.rs.core.Response.Status.CREATED;\nimport static jakarta.ws.rs.core.Response.Status.OK;\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.io.IOException;\nimport java.util.UUID;\n\nimport org.jclouds.googlecloudstorage.domain.Bucket;\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.ObjectRole;\nimport org.jclouds.googlecloudstorage.domain.ObjectAccessControls;\nimport org.jclouds.googlecloudstorage.domain.ResumableUpload;\nimport org.jclouds.googlecloudstorage.domain.templates.BucketTemplate;\nimport org.jclouds.googlecloudstorage.domain.templates.ObjectTemplate;\nimport org.jclouds.googlecloudstorage.internal.BaseGoogleCloudStorageApiLiveTest;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.io.payloads.ByteSourcePayload;\nimport org.jclouds.utils.TestUtils;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.io.ByteSource;\n\npublic class ResumableUploadApiLiveTest extends BaseGoogleCloudStorageApiLiveTest {\n\n   private static final String BUCKET_NAME = \"resumableuploadbucket\" + UUID.randomUUID();\n   private static final String UPLOAD_OBJECT_NAME = \"jcloudslogo.jpg\";\n   private static final String CHUNKED_OBJECT_NAME = \"jclouds.pdf\";\n   private static final int INCOMPLETE = 308;\n   private static final long MIN_CHUNK_SIZE = 256 * 1024; // Min allowed size for a chunk\n\n   private ResumableUploadApi api() {\n      return api.getResumableUploadApi();\n   }\n\n   @BeforeClass\n   private void createBucket() {\n      BucketTemplate template = new BucketTemplate().name(BUCKET_NAME);\n      Bucket bucket = api.getBucketApi().createBucket(PROJECT_NUMBER, template);\n      assertNotNull(bucket);\n   }\n\n   @Test(groups = \"live\")\n   public void testResumableJpegUpload() throws IOException {\n\n      // Read Object\n      long contentLength = MIN_CHUNK_SIZE * 4;\n      ByteSource byteSource = TestUtils.randomByteSource().slice(0, contentLength);\n\n      // Initialize resumableUpload with metadata. ObjectTemaplete must provide the name\n      ObjectAccessControls oacl = ObjectAccessControls.builder().bucket(BUCKET_NAME).entity(\"allUsers\")\n               .role(ObjectRole.OWNER).build();\n\n      ObjectTemplate template = new ObjectTemplate();\n      template.contentType(\"image/jpeg\").addAcl(oacl).size(contentLength).name(UPLOAD_OBJECT_NAME)\n               .contentLanguage(\"en\").contentDisposition(\"attachment\");\n\n      ResumableUpload initResponse = api().initResumableUpload(BUCKET_NAME, \"image/jpeg\", contentLength, template);\n\n      assertNotNull(initResponse);\n      assertEquals(initResponse.statusCode(), OK.getStatusCode());\n      assertNotNull(initResponse.uploadId());\n\n      String uploadId = initResponse.uploadId();\n\n      // Upload the payload\n      ByteSourcePayload payload = Payloads.newByteSourcePayload(byteSource);\n      ResumableUpload uploadResponse = api().upload(BUCKET_NAME, uploadId, \"image/jpeg\", byteSource.read().length + \"\",\n               payload);\n\n      assertEquals(uploadResponse.statusCode(), OK.getStatusCode());\n\n      // CheckStatus\n      ResumableUpload status = api().checkStatus(BUCKET_NAME, uploadId, \"bytes */*\");\n\n      int code = status.statusCode();\n      assertNotEquals(code, INCOMPLETE);\n   }\n\n   @Test(groups = \"live\")\n   public void testResumableChunkedUpload() throws IOException, InterruptedException {\n\n      // Read Object\n      long contentLength = MIN_CHUNK_SIZE * 3;\n      ByteSource byteSource = TestUtils.randomByteSource().slice(0, contentLength);\n\n      // Initialize resumableUpload with metadata. ObjectTemaplete must provide the name\n      ObjectAccessControls oacl = ObjectAccessControls.builder().bucket(BUCKET_NAME).entity(\"allUsers\")\n               .role(ObjectRole.OWNER).build();\n\n      ObjectTemplate template = new ObjectTemplate();\n      template.contentType(\"application/pdf\").addAcl(oacl).size(contentLength).name(CHUNKED_OBJECT_NAME)\n               .contentLanguage(\"en\").contentDisposition(\"attachment\");\n\n      ResumableUpload initResponse = api().initResumableUpload(BUCKET_NAME, \"application/pdf\", contentLength, template);\n\n      assertNotNull(initResponse);\n      assertEquals(initResponse.statusCode(), OK.getStatusCode());\n      assertNotNull(initResponse.uploadId());\n\n      // Get the upload_id for the session\n      String uploadId = initResponse.uploadId();\n\n      // Check the status first\n      ResumableUpload status = api().checkStatus(BUCKET_NAME, uploadId, \"bytes */*\");\n      int code = status.statusCode();\n      assertEquals(code, INCOMPLETE);\n\n      // Uploads in 2 chunks.\n      long totalSize = byteSource.read().length;\n      long offset = 0;\n      // Size of the first chunk\n      long chunkSize = MIN_CHUNK_SIZE * 2;\n\n      // Uploading First chunk\n      ByteSourcePayload payload = Payloads.newByteSourcePayload(byteSource.slice(offset, chunkSize));\n      long length = byteSource.slice(offset, chunkSize).size();\n      String Content_Range = generateContentRange(0L, length - 1, totalSize);\n      ResumableUpload uploadResponse = api().chunkUpload(BUCKET_NAME, uploadId, \"application/pdf\", length,\n               Content_Range, payload);\n\n      int code2 = uploadResponse.statusCode();\n      assertEquals(code2, INCOMPLETE);\n\n      // Read uploaded length\n      long lowerValue = uploadResponse.rangeLowerValue();\n      long uploaded = uploadResponse.rangeUpperValue();\n\n      assertThat(lowerValue).isEqualTo(0);\n      assertThat(uploaded).isEqualTo(chunkSize - 1); // confirms chunk is totally uploaded\n\n      long resumeLength = totalSize - (uploaded + 1);\n\n      // 2nd chunk\n      ByteSourcePayload payload2 = Payloads.newByteSourcePayload(byteSource.slice(uploaded + 1,\n               byteSource.read().length - uploaded - 1));\n      // Upload the 2nd chunk\n      String Content_Range2 = generateContentRange(uploaded + 1, totalSize - 1, totalSize);\n      ResumableUpload resumeResponse = api().chunkUpload(BUCKET_NAME, uploadId, \"application/pdf\", resumeLength,\n               Content_Range2, payload2);\n\n      int code3 = resumeResponse.statusCode();\n      assertThat(code3).isIn(OK.getStatusCode(), CREATED.getStatusCode()); // 200 or 201 if upload succeeded\n   }\n\n   @AfterClass\n   private void deleteObjectsandBucket() {\n      api.getObjectApi().deleteObject(BUCKET_NAME, UPLOAD_OBJECT_NAME);\n      api.getObjectApi().deleteObject(BUCKET_NAME, CHUNKED_OBJECT_NAME);\n      api.getBucketApi().deleteBucket(BUCKET_NAME);\n   }\n\n   private static String generateContentRange(Long lowerLimit, Long upperLimit, Long totalSize) {\n      return \"bytes \" + lowerLimit + \"-\" + upperLimit + \"/\" + totalSize;\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/java/org/jclouds/googlecloudstorage/handlers/GoogleCloudStorageErrorHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.handlers;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.reportMatcher;\nimport static org.easymock.EasyMock.verify;\n\nimport java.net.URI;\n\nimport org.easymock.IArgumentMatcher;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"GoogleStorageErrorHandlerTest\")\npublic class GoogleCloudStorageErrorHandlerTest {\n\n   @Test\n   public void test409MakesIllegalStateException() {\n      assertCodeMakes(\"POST\", URI.create(\"https://www.googleapis.com/storage/v1\"), 409, \"HTTP/1.1 409 Conflict\",\n               \"\\\"{\\\"code\\\":\\\"InvalidState\\\",\\\"message\\\":\\\"An incompatible transition has already been queued for this\"\n                        + \" resource\\\"}\\\"\", IllegalStateException.class);\n   }\n\n   @Test\n   public void test401MakesAuthorizationException() {\n      assertCodeMakes(\"POST\", URI.create(\"https://www.googleapis.com/storage/v1\"), 401, \"HTTP/1.1 401 Unauthorized\",\n               \"Login Required\", AuthorizationException.class);\n   }\n\n   @Test\n   public void test403MakesAuthorizationException() {\n      assertCodeMakes(\"POST\", URI.create(\"https://www.googleapis.com/storage/v1\"), 403, \"HTTP/1.1 403 Forbidden\",\n               \"Login Required\", AuthorizationException.class);\n   }\n\n   @Test\n   public void test404MakesResourceNotFoundException() {\n      assertCodeMakes(\"POST\", URI.create(\"https://www.googleapis.com/storage/v1\"), 404, \"HTTP/1.1 404 Not Found\",\n               \"Not Found\", ResourceNotFoundException.class);\n   }\n\n   private void assertCodeMakes(String method, URI uri, int statusCode, String message, String content,\n            Class<? extends Exception> expected) {\n      assertCodeMakes(method, uri, statusCode, message, \"application/json\", content, expected);\n   }\n\n   private void assertCodeMakes(String method, URI uri, int statusCode, String message, String contentType,\n            String content, Class<? extends Exception> expected) {\n\n      GoogleCloudStorageErrorHandler function = new GoogleCloudStorageErrorHandler();\n\n      HttpCommand command = createMock(HttpCommand.class);\n      HttpRequest request = HttpRequest.builder().method(method).endpoint(uri).build();\n      HttpResponse response = HttpResponse.builder().statusCode(statusCode).message(message).payload(content).build();\n      response.getPayload().getContentMetadata().setContentType(contentType);\n\n      expect(command.getCurrentRequest()).andReturn(request).atLeastOnce();\n      command.setException(classEq(expected));\n\n      replay(command);\n\n      function.handleError(command, response);\n\n      verify(command);\n   }\n\n   public static Exception classEq(final Class<? extends Exception> in) {\n      reportMatcher(new IArgumentMatcher() {\n\n         @Override\n         public void appendTo(StringBuffer buffer) {\n            buffer.append(\"classEq(\");\n            buffer.append(in);\n            buffer.append(\")\");\n         }\n\n         @Override\n         public boolean matches(Object arg) {\n            return arg.getClass() == in;\n         }\n\n      });\n      return null;\n   }\n\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/java/org/jclouds/googlecloudstorage/internal/BaseGoogleCloudStorageApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.internal;\n\nimport java.util.Properties;\n\nimport org.jclouds.googlecloudstorage.GoogleCloudStorageApi;\n\npublic class BaseGoogleCloudStorageApiExpectTest extends BaseGoogleCloudStorageExpectTest<GoogleCloudStorageApi> {\n\n   @Override protected Properties setupProperties() {\n      Properties properties = super.setupProperties();\n      properties.put(\"google-cloud-storage.identity\", \"JcloudTest\");\n      return properties;\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/java/org/jclouds/googlecloudstorage/internal/BaseGoogleCloudStorageApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.internal;\n\nimport java.util.Properties;\n\nimport org.jclouds.apis.BaseApiLiveTest;\nimport org.jclouds.googlecloud.config.CurrentProject;\nimport org.jclouds.googlecloud.internal.TestProperties;\nimport org.jclouds.googlecloudstorage.GoogleCloudStorageApi;\nimport org.jclouds.googlecloudstorage.GoogleCloudStorageProviderMetadata;\nimport org.jclouds.providers.ProviderMetadata;\n\nimport com.google.inject.Injector;\nimport com.google.inject.Module;\n\npublic class BaseGoogleCloudStorageApiLiveTest extends BaseApiLiveTest<GoogleCloudStorageApi> {\n\n   protected static String PROJECT_NUMBER;\n\n   protected BaseGoogleCloudStorageApiLiveTest() {\n      provider = \"google-cloud-storage\";\n   }\n\n   @Override protected ProviderMetadata createProviderMetadata(){\n      return new GoogleCloudStorageProviderMetadata();\n   }\n\n   @Override protected Properties setupProperties() {\n      TestProperties.setGoogleCredentialsFromJson(provider);\n      Properties props = TestProperties.apply(provider, super.setupProperties());\n      PROJECT_NUMBER = CurrentProject.ClientEmail.toProjectNumber(System.getProperty(\"test.google-cloud-storage.identity\"));\n      return props;\n   }\n\n   @Override protected GoogleCloudStorageApi create(Properties props, Iterable<Module> modules) {\n      Injector injector = newBuilder().modules(modules).overrides(props).buildInjector();\n      return injector.getInstance(GoogleCloudStorageApi.class);\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/java/org/jclouds/googlecloudstorage/internal/BaseGoogleCloudStorageApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.internal;\n\nimport static com.google.common.base.Throwables.propagate;\nimport static com.google.common.util.concurrent.MoreExecutors.newDirectExecutorService;\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\nimport static org.jclouds.googlecloud.config.GoogleCloudProperties.CREDENTIAL_TYPE;\nimport static org.jclouds.googlecloud.config.GoogleCloudProperties.PROJECT_NAME;\nimport static org.jclouds.oauth.v2.config.CredentialType.BEARER_TOKEN_CREDENTIALS;\nimport static org.jclouds.util.Strings2.toStringAndClose;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.util.Properties;\nimport java.util.Set;\nimport java.util.concurrent.atomic.AtomicInteger;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\nimport okhttp3.mockwebserver.RecordedRequest;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.concurrent.config.ExecutorServiceModule;\nimport org.jclouds.googlecloudstorage.GoogleCloudStorageApi;\nimport org.jclouds.googlecloudstorage.GoogleCloudStorageProviderMetadata;\nimport org.jclouds.http.okhttp.config.OkHttpCommandExecutorServiceModule;\nimport org.testng.annotations.AfterMethod;\nimport org.testng.annotations.BeforeMethod;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.gson.JsonParser;\nimport com.google.inject.AbstractModule;\n\n\n/**\n * Tests need to run {@code singleThreaded = true} as otherwise tests will clash on the server field.\n * Sharing the server field means less code to write.\n */\npublic class BaseGoogleCloudStorageApiMockTest {\n\n   protected final String identity = \"761326798069-r5mljlln1rd4lrbhg75efgigp36m78j5@developer.gserviceaccount.com\";\n   protected final String credential = \"1/8xbJqaOZXSUZbHLl5EOtu1pxz3fmmetKx9W8CV4t79M\"; // Fake Bearer Token\n\n   protected MockWebServer server;\n\n   protected GoogleCloudStorageApi api() {\n      return builder().buildApi(GoogleCloudStorageApi.class);\n   }\n\n\n   protected ContextBuilder builder() {\n      Properties overrides = new Properties();\n      overrides.put(PROJECT_NAME, \"party\");\n      overrides.put(CREDENTIAL_TYPE, BEARER_TOKEN_CREDENTIALS.toString());\n      return ContextBuilder.newBuilder(new GoogleCloudStorageProviderMetadata())\n            .credentials(identity, credential)\n            .endpoint(url(\"\"))\n            .overrides(overrides)\n            .modules(modules);\n   }\n\n   private final Set<AbstractModule> modules = ImmutableSet\n         .of(new ExecutorServiceModule(newDirectExecutorService()), new OkHttpCommandExecutorServiceModule());\n\n\n   final AtomicInteger suffix = new AtomicInteger();\n\n   @BeforeMethod\n   public void start() throws IOException {\n      suffix.set(0);\n      server = new MockWebServer();\n      server.start();\n   }\n\n   protected String url(String path) {\n      return server.url(path).toString();\n   }\n\n   @AfterMethod(alwaysRun = true)\n   public void stop() throws IOException {\n      server.shutdown();\n   }\n\n   protected MockResponse jsonResponse(String resource) {\n      return new MockResponse().addHeader(\"Content-Type\", \"application/json\").setBody(stringFromResource(resource));\n   }\n\n   protected MockResponse response404(){\n      return new MockResponse().setStatus(\"HTTP/1.1 404 Not Found\");\n   }\n\n   protected String stringFromResource(String resourceName) {\n      try {\n         return toStringAndClose(getClass().getResourceAsStream(resourceName));\n      } catch (IOException e) {\n         throw propagate(e);\n      }\n   }\n\n   protected RecordedRequest assertSent(MockWebServer server, String method, String path) throws InterruptedException {\n      return assertSent(server, method, path, APPLICATION_JSON);\n   }\n   protected RecordedRequest assertSent(MockWebServer server, String method, String path, String type) throws InterruptedException {\n      RecordedRequest request = server.takeRequest();\n      assertEquals(request.getMethod(), method);\n      assertEquals(request.getPath(), path);\n      if (type != null){\n         assertEquals(request.getHeader(\"Accept\"), type);\n      }\n      assertEquals(request.getHeader(\"Authorization\"), \"Bearer \" + credential);\n      return request;\n   }\n\n   protected RecordedRequest assertSent(MockWebServer server, String method, String path, String type, String json)\n         throws InterruptedException {\n      RecordedRequest request = assertSent(server, method, path, type);\n      assertEquals(request.getHeader(\"Content-Type\"), APPLICATION_JSON);\n      assertEquals(parser.parse(request.getBody().readUtf8()), parser.parse(json));\n      return request;\n   }\n\n   /** So that we can ignore formatting. */\n   private final JsonParser parser = new JsonParser();\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/java/org/jclouds/googlecloudstorage/internal/BaseGoogleCloudStorageExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.internal;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.base.Throwables.propagate;\nimport static com.google.common.io.BaseEncoding.base64Url;\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.expectLastCall;\nimport static org.easymock.EasyMock.replay;\nimport static org.jclouds.crypto.Pems.privateKeySpec;\nimport static org.jclouds.crypto.Pems.publicKeySpec;\nimport static org.jclouds.crypto.PemsTest.PRIVATE_KEY;\nimport static org.jclouds.crypto.PemsTest.PUBLIC_KEY;\nimport static org.jclouds.oauth.v2.config.OAuthProperties.JWS_ALG;\n\nimport java.io.IOException;\nimport java.net.URI;\nimport java.security.KeyFactory;\nimport java.security.KeyPair;\nimport java.security.KeyPairGenerator;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.PrivateKey;\nimport java.security.PublicKey;\nimport java.security.SecureRandom;\nimport java.security.spec.InvalidKeySpecException;\nimport java.util.Properties;\nimport java.util.concurrent.atomic.AtomicInteger;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.crypto.Crypto;\nimport org.jclouds.googlecloudstorage.GoogleCloudStorageProviderMetadata;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.oauth.v2.filters.JWTBearerTokenFlow;\nimport org.jclouds.oauth.v2.filters.TestJWTBearerTokenFlow;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.rest.internal.BaseRestApiExpectTest;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.base.Joiner;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Throwables;\nimport com.google.common.io.ByteSource;\nimport com.google.common.io.Resources;\nimport com.google.inject.Binder;\nimport com.google.inject.Module;\nimport com.google.inject.TypeLiteral;\n\npublic class BaseGoogleCloudStorageExpectTest<T> extends BaseRestApiExpectTest<T> {\n   protected static final String STORAGE_READONLY_SCOPE = \"https://www.googleapis.com/auth/devstorage.read_only\";\n\n   protected static final String STORAGE_READWRITE_SCOPE = \"https://www.googleapis.com/auth/devstorage.read_write\";\n\n   protected static final String STORAGE_FULLCONTROL_SCOPE = \"https://www.googleapis.com/auth/devstorage.full_control\";\n\n   private static final String header = \"{\\\"alg\\\":\\\"none\\\",\\\"typ\\\":\\\"JWT\\\"}\";\n\n   private static final String CLAIMS_TEMPLATE = \"{\" + \"\\\"iss\\\":\\\"JcloudTest\\\",\" + \"\\\"scope\\\":\\\"%s\\\",\"\n            + \"\\\"aud\\\":\\\"https://accounts.google.com/o/oauth2/token\\\",\" + \"\\\"exp\\\":3600,\" + \"\\\"iat\\\":0}\";\n\n   protected static final String TOKEN = \"1/8xbJqaOZXSUZbHLl5EOtu1pxz3fmmetKx9W8CV4t79M\";\n\n   protected static final HttpResponse TOKEN_RESPONSE = HttpResponse\n            .builder()\n            .statusCode(200)\n            .payload(payloadFromString(\"{\\n\" + \"  \\\"access_token\\\" : \\\"\" + TOKEN + \"\\\",\\n\"\n                     + \"  \\\"token_type\\\" : \\\"Bearer\\\",\\n\" + \"  \\\"expires_in\\\" : 3600\\n\" + \"}\")).build();\n\n   protected BaseGoogleCloudStorageExpectTest() {\n      provider = \"google-cloud-storage\";\n   }\n\n   @Override protected Module createModule() {\n      return new Module() {\n         @Override\n         public void configure(Binder binder) {\n            // Predictable time\n            binder.bind(JWTBearerTokenFlow.class).to(TestJWTBearerTokenFlow.class);\n            try {\n               KeyFactory keyfactory = KeyFactory.getInstance(\"RSA\");\n               PrivateKey privateKey = keyfactory.generatePrivate(privateKeySpec(ByteSource.wrap(PRIVATE_KEY\n                        .getBytes(UTF_8))));\n               PublicKey publicKey = keyfactory\n                        .generatePublic(publicKeySpec(ByteSource.wrap(PUBLIC_KEY.getBytes(UTF_8))));\n               KeyPair keyPair = new KeyPair(publicKey, privateKey);\n               final Crypto crypto = createMock(Crypto.class);\n               KeyPairGenerator rsaKeyPairGenerator = createMock(KeyPairGenerator.class);\n               final SecureRandom secureRandom = createMock(SecureRandom.class);\n               expect(crypto.rsaKeyPairGenerator()).andReturn(rsaKeyPairGenerator).anyTimes();\n               rsaKeyPairGenerator.initialize(2048, secureRandom);\n               expectLastCall().anyTimes();\n               expect(rsaKeyPairGenerator.genKeyPair()).andReturn(keyPair).anyTimes();\n               replay(crypto, rsaKeyPairGenerator, secureRandom);\n               binder.bind(Crypto.class).toInstance(crypto);\n               binder.bind(SecureRandom.class).toInstance(secureRandom);\n            } catch (NoSuchAlgorithmException e) {\n               propagate(e);\n            } catch (InvalidKeySpecException e) {\n               propagate(e);\n            } catch (IOException e) {\n               propagate(e);\n            }\n            // predictable node names\n            final AtomicInteger suffix = new AtomicInteger();\n            binder.bind(new TypeLiteral<Supplier<String>>() {\n            }).toInstance(new Supplier<String>() {\n               @Override\n               public String get() {\n                  return suffix.getAndIncrement() + \"\";\n               }\n            });\n         }\n      };\n   }\n\n   @Override protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      // use no sig algorithm for expect tests (means no credential is required either)\n      props.put(JWS_ALG, \"none\");\n      return props;\n   }\n\n   @Override protected ProviderMetadata createProviderMetadata(){\n      return new GoogleCloudStorageProviderMetadata();\n   }\n\n   @Override\n   protected HttpRequestComparisonType compareHttpRequestAsType(HttpRequest input) {\n      HttpRequestComparisonType reqType = HttpRequestComparisonType.DEFAULT;\n      if (input.getPayload() != null) {\n         if (MediaType.APPLICATION_JSON.toString().equals(input.getPayload().getContentMetadata().getContentType())) {\n            reqType = HttpRequestComparisonType.JSON;\n         }\n      }\n      return reqType;\n   }\n\n   protected HttpRequest requestForScopes(String... scopes) {\n      String claims = String.format(CLAIMS_TEMPLATE, Joiner.on(\",\").join(scopes));\n\n      String payload = \"grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&\" +\n      // Base64 Encoded Header\n               \"assertion=\" + base64Url().omitPadding().encode(header.getBytes(UTF_8)) + \".\" +\n               // Base64 Encoded Claims\n               base64Url().omitPadding().encode(claims.getBytes(UTF_8)) + \".\";\n\n      return HttpRequest.builder().method(\"POST\").endpoint(URI.create(\"https://accounts.google.com/o/oauth2/token\"))\n               .addHeader(\"Accept\", MediaType.APPLICATION_JSON)\n               .payload(payloadFromStringWithContentType(payload, \"application/x-www-form-urlencoded\")).build();\n   }\n\n   protected Payload staticPayloadFromResource(String resource) {\n      try {\n         return Payloads.newStringPayload(Resources.toString(Resources.getResource(getClass(), resource), Charsets.UTF_8));\n      } catch (IOException ex) {\n         throw Throwables.propagate(ex);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/java/org/jclouds/googlecloudstorage/internal/BaseGoogleCloudStorageParseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.internal;\n\nimport java.util.Date;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.googlecloudstorage.config.GoogleCloudStorageParserModule;\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.json.config.GsonModule;\n\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\npublic abstract class BaseGoogleCloudStorageParseTest<T> extends BaseItemParserTest<T> {\n\n   @Override protected Injector injector() {\n      return Guice.createInjector(new GsonModule(), new GoogleCloudStorageParserModule());\n   }\n\n   protected static Date parse(String iso8601) {\n      return new SimpleDateFormatDateService().iso8601DateParse(iso8601);\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/java/org/jclouds/googlecloudstorage/parse/BucketAclGetTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.parse;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.googlecloudstorage.domain.BucketAccessControls;\nimport org.jclouds.googlecloudstorage.domain.BucketAccessControls.Role;\nimport org.jclouds.googlecloudstorage.internal.BaseGoogleCloudStorageParseTest;\n\npublic class BucketAclGetTest extends BaseGoogleCloudStorageParseTest<BucketAccessControls> {\n\n   @Override\n   public String resource() {\n      return \"/bucket_acl_get.json\";\n   }\n\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   public BucketAccessControls expected() {\n      return BucketAccessControls.builder().bucket(\"jcloudstestbucket\").entity(\"allUsers\").role(Role.READER)\n               .id(\"jcloudstestbucket/allUsers\").build();\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/java/org/jclouds/googlecloudstorage/parse/BucketAclInsertTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.parse;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.googlecloudstorage.domain.BucketAccessControls;\nimport org.jclouds.googlecloudstorage.domain.BucketAccessControls.Role;\nimport org.jclouds.googlecloudstorage.internal.BaseGoogleCloudStorageParseTest;\n\npublic class BucketAclInsertTest extends BaseGoogleCloudStorageParseTest<BucketAccessControls> {\n\n   @Override\n   public String resource() {\n      return \"/bucket_acl_insert_response.json\";\n   }\n\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   public BucketAccessControls expected() {\n      return BucketAccessControls\n               .builder()\n               .id(\"jcloudstestbucket/allAuthenticatedUsers\")\n               .bucket(\"jcloudstestbucket\").entity(\"allAuthenticatedUsers\").role(Role.WRITER).build();\n\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/java/org/jclouds/googlecloudstorage/parse/BucketAclListTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.parse;\n\nimport java.util.List;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.googlecloudstorage.domain.BucketAccessControls;\nimport org.jclouds.googlecloudstorage.domain.BucketAccessControls.Role;\nimport org.jclouds.googlecloudstorage.domain.ProjectTeam;\nimport org.jclouds.googlecloudstorage.domain.ProjectTeam.Team;\nimport org.jclouds.googlecloudstorage.internal.BaseGoogleCloudStorageParseTest;\nimport org.jclouds.rest.annotations.SelectJson;\n\nimport com.google.common.collect.ImmutableList;\n\npublic class BucketAclListTest extends BaseGoogleCloudStorageParseTest<List<BucketAccessControls>> {\n\n   private BucketAccessControls item_1 = BucketAccessControls.builder().id(\"jcloudstestbucket/allUsers\")\n            .bucket(\"jcloudstestbucket\").entity(\"allUsers\").role(Role.READER).build();\n\n   private BucketAccessControls item_2 = BucketAccessControls\n            .builder()\n            .id(\"jcloudstestbucket/project-owners-1082289308625\")\n            .projectTeam(ProjectTeam.create(\"1082289308625\", Team.OWNERS))\n            .bucket(\"jcloudstestbucket\").entity(\"project-owners-1082289308625\").role(Role.OWNER).build();\n\n   @Override\n   public String resource() {\n      return \"/bucket_acl_list.json\";\n   }\n\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   @SelectJson(\"items\")\n   public List<BucketAccessControls> expected() {\n      return ImmutableList.of(item_1, item_2);\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/java/org/jclouds/googlecloudstorage/parse/BucketAclUpdateTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.parse;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.googlecloudstorage.domain.BucketAccessControls;\nimport org.jclouds.googlecloudstorage.domain.BucketAccessControls.Role;\nimport org.jclouds.googlecloudstorage.internal.BaseGoogleCloudStorageParseTest;\n\npublic class BucketAclUpdateTest extends BaseGoogleCloudStorageParseTest<BucketAccessControls> {\n\n   @Override\n   public String resource() {\n      return \"/bucket_acl_update_response.json\";\n   }\n\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   public BucketAccessControls expected() {\n      return BucketAccessControls.builder().id(\"jcloudstestbucket/allUsers\")\n               .bucket(\"jcloudstestbucket\").entity(\"allUsers\").role(Role.OWNER).build();\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/java/org/jclouds/googlecloudstorage/parse/BucketUpdateTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.parse;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.googlecloudstorage.domain.Bucket;\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.Location;\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.StorageClass;\nimport org.jclouds.googlecloudstorage.domain.Owner;\nimport org.jclouds.googlecloudstorage.internal.BaseGoogleCloudStorageParseTest;\n\npublic class BucketUpdateTest extends BaseGoogleCloudStorageParseTest<Bucket> {\n\n   @Override\n   public String resource() {\n      return \"/bucket_update_response.json\";\n   }\n\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Bucket expected() {\n      return Bucket.create(\n            \"bhashbucket\", // id\n            \"bhashbucket\", // name\n            1082289308625L, // projectNumber\n            new SimpleDateFormatDateService().iso8601DateParse(\"2014-06-02T19:19:41.112z\"), // timeCreated\n            204L, // metageneration\n            null, // acl\n            null, // defaultObjectAcl\n            Owner.create(\"project-owners-1082289308625\", null), // owner\n            Location.US, // location\n            null, // website\n            null, // logging\n            null, // versioning\n            null, // cors\n            null, // lifeCycle\n            StorageClass.STANDARD // storageClass\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/java/org/jclouds/googlecloudstorage/parse/DefaultObjectAclGetTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.parse;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.ObjectRole;\nimport org.jclouds.googlecloudstorage.domain.ObjectAccessControls;\nimport org.jclouds.googlecloudstorage.domain.ProjectTeam;\nimport org.jclouds.googlecloudstorage.domain.ProjectTeam.Team;\nimport org.jclouds.googlecloudstorage.internal.BaseGoogleCloudStorageParseTest;\n\npublic class DefaultObjectAclGetTest extends BaseGoogleCloudStorageParseTest<ObjectAccessControls> {\n\n   @Override\n   public String resource() {\n      return \"/default_object_acl_get.json\";\n   }\n\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   public ObjectAccessControls expected() {\n      return ObjectAccessControls.builder().entity(\"project-owners-1082289308625\").role(ObjectRole.OWNER)\n               .projectTeam(ProjectTeam.create(\"1082289308625\", Team.OWNERS))\n               .build();\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/java/org/jclouds/googlecloudstorage/parse/DefaultObjectAclInsertTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.parse;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.ObjectRole;\nimport org.jclouds.googlecloudstorage.domain.ObjectAccessControls;\nimport org.jclouds.googlecloudstorage.internal.BaseGoogleCloudStorageParseTest;\n\npublic class DefaultObjectAclInsertTest extends BaseGoogleCloudStorageParseTest<ObjectAccessControls> {\n\n   @Override\n   public String resource() {\n      return \"/default_object_acl_insert_response.json\";\n   }\n\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   public ObjectAccessControls expected() {\n      return ObjectAccessControls.builder().entity(\"allUsers\").role(ObjectRole.OWNER).build();\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/java/org/jclouds/googlecloudstorage/parse/DefaultObjectAclListTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.parse;\n\nimport java.util.Arrays;\nimport java.util.List;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.ObjectRole;\nimport org.jclouds.googlecloudstorage.domain.ObjectAccessControls;\nimport org.jclouds.googlecloudstorage.domain.ProjectTeam;\nimport org.jclouds.googlecloudstorage.domain.ProjectTeam.Team;\nimport org.jclouds.googlecloudstorage.internal.BaseGoogleCloudStorageParseTest;\nimport org.jclouds.rest.annotations.SelectJson;\n\npublic class DefaultObjectAclListTest extends BaseGoogleCloudStorageParseTest<List<ObjectAccessControls>> {\n\n   private ObjectAccessControls item_1 = ObjectAccessControls.builder()\n            .entity(\"project-owners-1082289308625\").role(ObjectRole.OWNER)\n            .projectTeam(ProjectTeam.create(\"1082289308625\", Team.OWNERS))\n            .build();\n\n   @Override\n   public String resource() {\n      return \"/default_object_acl_list.json\";\n   }\n\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   @SelectJson(\"items\")\n   public List<ObjectAccessControls> expected() {\n      return Arrays.asList(item_1);\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/java/org/jclouds/googlecloudstorage/parse/FullBucketGetTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.parse;\n\nimport java.util.Arrays;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.googlecloudstorage.domain.Bucket;\nimport org.jclouds.googlecloudstorage.domain.Bucket.Cors;\nimport org.jclouds.googlecloudstorage.domain.BucketAccessControls;\nimport org.jclouds.googlecloudstorage.domain.BucketAccessControls.Role;\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.Location;\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.ObjectRole;\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.StorageClass;\nimport org.jclouds.googlecloudstorage.domain.ObjectAccessControls;\nimport org.jclouds.googlecloudstorage.domain.Owner;\nimport org.jclouds.googlecloudstorage.domain.ProjectTeam;\nimport org.jclouds.googlecloudstorage.domain.ProjectTeam.Team;\nimport org.jclouds.googlecloudstorage.internal.BaseGoogleCloudStorageParseTest;\n\npublic class FullBucketGetTest extends BaseGoogleCloudStorageParseTest<Bucket> {\n\n   private final BucketAccessControls acl1 = BucketAccessControls\n            .builder()\n            .id(\"jcloudstestbucket3500/project-owners-1082289308625\")\n            .bucket(\"jcloudstestbucket3500\").entity(\"project-owners-1082289308625\").role(Role.OWNER)\n            .projectTeam(ProjectTeam.create(\"1082289308625\", Team.OWNERS))\n            .build();\n\n   private final ObjectAccessControls defObjectAcl = ObjectAccessControls.builder()\n            .entity(\"project-owners-1082289308625\").role(ObjectRole.OWNER).build();\n\n   private final Cors bucketCors = Cors\n         .create(Arrays.asList(\"http://example.appspot.com\"), Arrays.asList(\"GET\", \"HEAD\"),\n               Arrays.asList(\"x-meta-goog-custom\"), 10);\n\n   @Override\n   public String resource() {\n      return \"/full_bucket_get.json\";\n   }\n\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Bucket expected() {\n      return Bucket.create(\n            \"jcloudstestbucket3500\", // id\n            \"jcloudstestbucket3500\", // name\n            1082289308625L, // projectNumber\n            new SimpleDateFormatDateService().iso8601DateParse(\"2014-06-19T14:03:22.345Z\"), // timeCreated\n            10L, // metageneration\n            Arrays.asList(acl1), // acl\n            Arrays.asList(defObjectAcl), // defaultObjectAcl\n            Owner.create(\"project-owners-1082289308625\", null), // owner\n            Location.US, // location\n            null, // website\n            null, // logging\n            null, // versioning\n            Arrays.asList(bucketCors), // cors\n            null, // lifeCycle\n            StorageClass.STANDARD // storageClass\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/java/org/jclouds/googlecloudstorage/parse/NoAclBucketListTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.parse;\n\nimport java.util.Arrays;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.googlecloud.domain.ForwardingListPage;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecloudstorage.domain.Bucket;\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.Location;\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.StorageClass;\nimport org.jclouds.googlecloudstorage.domain.Owner;\nimport org.jclouds.googlecloudstorage.internal.BaseGoogleCloudStorageParseTest;\n\npublic class NoAclBucketListTest extends BaseGoogleCloudStorageParseTest<ListPage<Bucket>> {\n\n   private Bucket item1 = Bucket.create(\"bhashbucket\", // id\n         \"bhashbucket\", // name\n         1082289308625L, // projectNumber\n         new SimpleDateFormatDateService().iso8601DateParse(\"2014-06-02T19:19:41.112z\"), // timeCreated\n         99L, // metageneration\n         null, // acl\n         null, // defaultObjectAcl\n         Owner.create(\"project-owners-1082289308625\", null), // owner\n         Location.US, // location\n         null, // website\n         null, // logging\n         null, // versioning\n         null, // cors\n         null, // lifeCycle\n         StorageClass.STANDARD // storageClass\n   );\n\n   @Override\n   public String resource() {\n      return \"/no_acl_bucket_list.json\";\n   }\n\n   @Override @Consumes(MediaType.APPLICATION_JSON)\n   public ListPage<Bucket> expected() {\n      return ForwardingListPage.create(Arrays.asList(item1), \"bhashbucket\");\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/java/org/jclouds/googlecloudstorage/parse/NoAclBucketTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.parse;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.googlecloudstorage.domain.Bucket;\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.Location;\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.StorageClass;\nimport org.jclouds.googlecloudstorage.domain.Owner;\nimport org.jclouds.googlecloudstorage.internal.BaseGoogleCloudStorageParseTest;\n\npublic class NoAclBucketTest extends BaseGoogleCloudStorageParseTest<Bucket> {\n\n   @Override\n   public String resource() {\n      return \"/no_acl_bucket.json\";\n   }\n\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Bucket expected() {\n      return Bucket.create(\n            \"bhashbucket\", // id\n            \"bhashbucket\", // name\n            1082289308625L, // projectNumber\n            new SimpleDateFormatDateService().iso8601DateParse(\"2014-06-02T19:19:41.112z\"), // timeCreated\n            87L, // metageneration\n            null, // acl\n            null, // defaultObjectAcl\n            Owner.create(\"project-owners-1082289308625\", null), // owner\n            Location.US, // location\n            null, // website\n            null, // logging\n            null, // versioning\n            null, // cors\n            null, // lifeCycle\n            StorageClass.STANDARD // storageClass\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/java/org/jclouds/googlecloudstorage/parse/ObjectAclGetTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.parse;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.ObjectRole;\nimport org.jclouds.googlecloudstorage.domain.ObjectAccessControls;\nimport org.jclouds.googlecloudstorage.domain.ProjectTeam;\nimport org.jclouds.googlecloudstorage.domain.ProjectTeam.Team;\nimport org.jclouds.googlecloudstorage.internal.BaseGoogleCloudStorageParseTest;\n\npublic class ObjectAclGetTest extends BaseGoogleCloudStorageParseTest<ObjectAccessControls> {\n\n   @Override\n   public String resource() {\n      return \"/object_acl_get.json\";\n   }\n\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   public ObjectAccessControls expected() {\n      return ObjectAccessControls\n               .builder()\n               .bucket(\"jcloudstestbucket\")\n               .object(\"foo.txt\")\n               .generation(1394121608485000L)\n               .entity(\"project-owners-1082289308625\")\n               .role(ObjectRole.OWNER)\n               .projectTeam(ProjectTeam.create(\"1082289308625\", Team.OWNERS))\n               .id(\"jcloudstestbucket/foo.txt/1394121608485000/project-owners-1082289308625\").build();\n   }\n\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/java/org/jclouds/googlecloudstorage/parse/ObjectAclInsertTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.parse;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.ObjectRole;\nimport org.jclouds.googlecloudstorage.domain.ObjectAccessControls;\nimport org.jclouds.googlecloudstorage.internal.BaseGoogleCloudStorageParseTest;\n\npublic class ObjectAclInsertTest extends BaseGoogleCloudStorageParseTest<ObjectAccessControls> {\n\n   @Override\n   public String resource() {\n      return \"/object_acl_insert_response.json\";\n   }\n\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   public ObjectAccessControls expected() {\n      return ObjectAccessControls\n               .builder()\n               .bucket(\"jcloudstestbucket\").object(\"foo.txt\")\n               .entity(\"user-00b4903a97adfde729f0650133a7379693099d8d85d6b1b18255ca70bf89e31d\")\n               .entityId(\"00b4903a97adfde729f0650133a7379693099d8d85d6b1b18255ca70bf89e31d\").role(ObjectRole.OWNER)\n               .build();\n   }\n\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/java/org/jclouds/googlecloudstorage/parse/ObjectAclListTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.parse;\n\nimport java.util.Arrays;\nimport java.util.List;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.ObjectRole;\nimport org.jclouds.googlecloudstorage.domain.ObjectAccessControls;\nimport org.jclouds.googlecloudstorage.internal.BaseGoogleCloudStorageParseTest;\nimport org.jclouds.rest.annotations.SelectJson;\n\npublic class ObjectAclListTest extends BaseGoogleCloudStorageParseTest<List<ObjectAccessControls>> {\n\n   private ObjectAccessControls item1 = ObjectAccessControls\n            .builder()\n            .id(\"jcloudstestbucket/foo.txt/1394121608485000/user-00b4903a97adfde729f0650133a7379693099d8d85d6b1b18255ca70bf89e31d\")\n            .bucket(\"jcloudstestbucket\").object(\"foo.txt\").generation(Long.valueOf(\"1394121608485000\"))\n            .entity(\"user-00b4903a97adfde729f0650133a7379693099d8d85d6b1b18255ca70bf89e31d\")\n            .entityId(\"00b4903a97adfde729f0650133a7379693099d8d85d6b1b18255ca70bf89e31d\").role(ObjectRole.OWNER)\n            .build();\n\n   @Override\n   public String resource() {\n      return \"/object_acl_list.json\";\n   }\n\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   @SelectJson(\"items\")\n   public List<ObjectAccessControls> expected() {\n      return Arrays.asList(item1);\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/java/org/jclouds/googlecloudstorage/parse/ObjectAclUpdateTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.parse;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.ObjectRole;\nimport org.jclouds.googlecloudstorage.domain.ObjectAccessControls;\nimport org.jclouds.googlecloudstorage.internal.BaseGoogleCloudStorageParseTest;\n\npublic class ObjectAclUpdateTest extends BaseGoogleCloudStorageParseTest<ObjectAccessControls> {\n\n   @Override\n   public String resource() {\n      return \"/object_acl_update_response.json\";\n   }\n\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   public ObjectAccessControls expected() {\n      return ObjectAccessControls.builder()\n               .bucket(\"jcloudstestbucket\").object(\"foo.txt\").entity(\"allUsers\").role(ObjectRole.OWNER).build();\n   }\n\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/java/org/jclouds/googlecloudstorage/parse/ParseGoogleCloudStorageObject.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.parse;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.StorageClass;\nimport org.jclouds.googlecloudstorage.domain.Owner;\nimport org.jclouds.googlecloudstorage.domain.GoogleCloudStorageObject;\nimport org.jclouds.googlecloudstorage.internal.BaseGoogleCloudStorageParseTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ParseGoogleCloudStorageObject\")\npublic class ParseGoogleCloudStorageObject extends BaseGoogleCloudStorageParseTest<GoogleCloudStorageObject> {\n\n   @Override\n   public String resource() {\n      return \"/object_get.json\";\n   }\n\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   public GoogleCloudStorageObject expected() {\n      return GoogleCloudStorageObject.create(\n            \"test/file_name/1000\", //id\n            URI.create(\"https://www.googleapis.com/storage/v1/b/test/o/file_name\"), //selfLink\n            \"etag\", // etag\n            \"file_name\", // name\n            \"test\", // bucket\n            (long) 1000, //generation\n            (long) 8, // metageneration\n            \"application/x-tar\", // contentType\n            parse(\"2014-09-27T00:01:44.819\"), // updated\n            null, // timeDeleted\n            StorageClass.STANDARD, // storageClass\n            (long) 1000, //size,\n            \"md5Hash\", // md5Hash\n            URI.create(\"https://www.googleapis.com/download/storage/v1/b/test/o/file_name?generation=1000&alt=media\"), // mediaLink\n            null, // metadata\n            null, // contentEncoding\n            null, // contentDisposition,\n            null, // contentLanguage\n            null, // cacheControl\n            null, // acl\n            Owner.create(\"entity\", \"entityId\"), // owner,\n            \"crc32c\", // crc32c,\n            null); //componentCount\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/java/org/jclouds/googlecloudstorage/parse/ParseGoogleCloudStorageObjectListTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.parse;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.StorageClass;\nimport org.jclouds.googlecloudstorage.domain.ListPageWithPrefixes;\nimport org.jclouds.googlecloudstorage.domain.Owner;\nimport org.jclouds.googlecloudstorage.domain.GoogleCloudStorageObject;\nimport org.jclouds.googlecloudstorage.internal.BaseGoogleCloudStorageParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n\n@Test(groups = \"unit\", testName = \"ParseGoogleCloudStorageObjectListTest\")\npublic class ParseGoogleCloudStorageObjectListTest extends BaseGoogleCloudStorageParseTest<ListPageWithPrefixes<GoogleCloudStorageObject>> {\n\n   @Override\n   public String resource() {\n      return \"/object_list.json\";\n   }\n\n   GoogleCloudStorageObject object1 = GoogleCloudStorageObject.create(\n         \"test/file_name/1000\", //id\n         URI.create(\"https://www.googleapis.com/storage/v1/b/test/o/file_name\"), //selfLink\n         \"etag\", // etag\n         \"file_name\", // name\n         \"test\", // bucket\n         (long) 1000, //generation\n         (long) 8, // metageneration\n         \"application/x-tar\", // contentType\n         parse(\"2014-09-27T00:01:44.819\"), // updated\n         null, // timeDeleted\n         StorageClass.STANDARD, // storageClass\n         (long) 1000, //size,\n         \"md5Hash\", // md5Hash\n         URI.create(\"https://www.googleapis.com/download/storage/v1/b/test/o/file_name?generation=1000&alt=media\"), // mediaLink\n         null, // metadata\n         null, // contentEncoding\n         null, // contentDisposition,\n         null, // contentLanguage\n         null, // cacheControl\n         null, // acl\n         Owner.create(\"entity\", \"entityId\"), // owner,\n         \"crc32c\", // crc32c,\n         null); //componentCount\n\n   GoogleCloudStorageObject object2 = GoogleCloudStorageObject.create(\n         \"test/file_name2/1000\", //id\n         URI.create(\"https://www.googleapis.com/storage/v1/b/test/o/file_name2\"), //selfLink\n         \"etag\", // etag\n         \"file_name2\", // name\n         \"test\", // bucket\n         (long) 1001, //generation\n         (long) 9, // metageneration\n         \"image/png\", // contentType\n         parse(\"2014-09-27T00:01:44.819\"), // updated\n         null, // timeDeleted\n         StorageClass.STANDARD, // storageClass\n         (long) 10, //size,\n         \"md5Hash\", // md5Hash\n         URI.create(\"https://www.googleapis.com/download/storage/v1/b/test/o/file_name2?generation=1001&alt=media\"), // mediaLink\n         null, // metadata\n         null, // contentEncoding\n         null, // contentDisposition,\n         null, // contentLanguage\n         null, // cacheControl\n         null, // acl\n         Owner.create(\"entity\", \"entityId\"), // owner,\n         \"crc32c\", // crc32c,\n         null); //componentCount\n\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   public ListPageWithPrefixes<GoogleCloudStorageObject> expected() {\n      List<GoogleCloudStorageObject> items = ImmutableList.of(object1, object2);\n      return new ListPageWithPrefixes<GoogleCloudStorageObject>(items, null, null);\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/java/org/jclouds/googlecloudstorage/parse/ParseObjectRewriteResponse.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecloudstorage.parse;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.googlecloudstorage.domain.DomainResourceReferences.StorageClass;\nimport org.jclouds.googlecloudstorage.domain.Owner;\nimport org.jclouds.googlecloudstorage.domain.GoogleCloudStorageObject;\nimport org.jclouds.googlecloudstorage.domain.RewriteResponse;\nimport org.jclouds.googlecloudstorage.internal.BaseGoogleCloudStorageParseTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ParseObjectRewriteResponse\")\npublic class ParseObjectRewriteResponse extends BaseGoogleCloudStorageParseTest<RewriteResponse> {\n\n   @Override\n   public String resource() {\n      return \"/object_rewrite.json\";\n   }\n\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   public RewriteResponse expected() {\n      return RewriteResponse.create(16, // totalBytesRewritten\n            16, // objectSize\n            true, // done\n            \"rewriteToken\", // rewriteToken\n            GoogleCloudStorageObject.create(\n               \"test/file_name/1000\", //id\n               URI.create(\"https://www.googleapis.com/storage/v1/b/test/o/file_name\"), //selfLink\n               \"etag\", // etag\n               \"file_name\", // name\n               \"test\", // bucket\n               (long) 1000, //generation\n               (long) 8, // metageneration\n               \"application/x-tar\", // contentType\n               parse(\"2014-09-27T00:01:44.819\"), // updated\n               null, // timeDeleted\n               StorageClass.STANDARD, // storageClass\n               (long) 1000, //size,\n               \"md5Hash\", // md5Hash\n               URI.create(\"https://www.googleapis.com/download/storage/v1/b/test/o/file_name?generation=1000&alt=media\"), // mediaLink\n               null, // metadata\n               null, // contentEncoding\n               null, // contentDisposition,\n               null, // contentLanguage\n               null, // cacheControl\n               null, // acl\n               Owner.create(\"entity\", \"entityId\"), // owner,\n               \"crc32c\", // crc32c,\n               null) //componentCount\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/resources/bucket_acl_get.json",
    "content": "{\n   \"kind\": \"storage#bucketAccessControl\",\n   \"id\": \"jcloudstestbucket/allUsers\",\n   \"selfLink\": \"https://content.googleapis.com/storage/v1/b/jcloudstestbucket/acl/allUsers\",\n   \"bucket\": \"jcloudstestbucket\",\n   \"entity\": \"allUsers\",\n   \"role\": \"READER\",\n   \"etag\": \"CAM=\"\n}"
  },
  {
    "path": "providers/google-cloud-storage/src/test/resources/bucket_acl_insert_initial.json",
    "content": "{\n   \"entity\": \"allAuthenticatedUsers\",\n   \"role\": \"WRITER\"\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/resources/bucket_acl_insert_response.json",
    "content": "{\n   \"kind\": \"storage#bucketAccessControl\",\n   \"id\": \"jcloudstestbucket/allAuthenticatedUsers\",\n   \"selfLink\": \"https://content.googleapis.com/storage/v1/b/jcloudstestbucket/acl/allAuthenticatedUsers\",\n   \"bucket\": \"jcloudstestbucket\",\n   \"entity\": \"allAuthenticatedUsers\",\n   \"role\": \"WRITER\",\n   \"etag\": \"CAQ=\"\n}"
  },
  {
    "path": "providers/google-cloud-storage/src/test/resources/bucket_acl_list.json",
    "content": "{\n   \"kind\": \"storage#bucketAccessControls\",\n   \"items\": [\n     {\n       \"kind\": \"storage#bucketAccessControl\",\n       \"id\": \"jcloudstestbucket/allUsers\",\n       \"selfLink\": \"https://content.googleapis.com/storage/v1/b/jcloudstestbucket/acl/allUsers\",\n       \"bucket\": \"jcloudstestbucket\",\n       \"entity\": \"allUsers\",\n       \"role\": \"READER\",\n       \"etag\": \"CAc=\"\n    },\n    {\n       \"kind\": \"storage#bucketAccessControl\",\n       \"id\": \"jcloudstestbucket/project-owners-1082289308625\",\n       \"selfLink\": \"https://content.googleapis.com/storage/v1/b/jcloudstestbucket/acl/project-owners-1082289308625\",\n       \"bucket\": \"jcloudstestbucket\",\n       \"entity\": \"project-owners-1082289308625\",\n       \"role\": \"OWNER\",\n       \"projectTeam\": {\n          \"projectNumber\": \"1082289308625\",\n          \"team\": \"owners\"\n       },\n       \"etag\": \"CAc=\"\n    }\n   ]\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/resources/bucket_acl_update_initial.json",
    "content": "{\n   \"entity\": \"allUsers\",\n   \"role\": \"OWNER\"\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/resources/bucket_acl_update_response.json",
    "content": "{\n   \"kind\": \"storage#bucketAccessControl\",\n   \"id\": \"jcloudstestbucket/allUsers\",\n   \"selfLink\": \"https://content.googleapis.com/storage/v1/b/jcloudstestbucket/acl/allUsers\",\n   \"bucket\": \"jcloudstestbucket\",\n   \"entity\": \"allUsers\",\n   \"role\": \"OWNER\",\n   \"etag\": \"CAg=\"\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/resources/bucket_insert_request_payload.json",
    "content": "{\n   \"name\":\"bhashbucket\"\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/resources/bucket_update_request_payload.json",
    "content": "{\n   \"name\":\"bhashbucket\",\n   \"acl\": [\n      {\n         \"kind\":\"storage#bucketAccessControl\",\n         \"bucket\":\"bhashbucket\",\n         \"id\":\"bhashbucket/allAuthenticatedUsers\",\n         \"entity\": \"allAuthenticatedUsers\",\n         \"role\": \"OWNER\"\n      }\n    ]\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/resources/bucket_update_response.json",
    "content": "{\n   \"kind\": \"storage#bucket\",\n   \"id\": \"bhashbucket\",\n   \"selfLink\": \"https://www.googleapis.com/storage/v1/b/bhashbucket\",\n   \"projectNumber\": \"1082289308625\",\n   \"name\": \"bhashbucket\",\n   \"timeCreated\": \"2014-06-02T19:19:41.112Z\",\n   \"metageneration\": \"204\",\n   \"owner\": {\n      \"entity\": \"project-owners-1082289308625\"\n   },\n   \"location\": \"US\",\n   \"storageClass\": \"STANDARD\",\n   \"etag\": \"CMwB\"\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/resources/default_object_acl_get.json",
    "content": "{\n   \"kind\": \"storage#objectAccessControl\",\n   \"entity\": \"project-owners-1082289308625\",\n   \"role\": \"OWNER\",\n   \"projectTeam\": {\n     \"projectNumber\": \"1082289308625\",\n     \"team\": \"owners\"\n   },\n   \"etag\": \"CAk=\"\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/resources/default_object_acl_insert_request_payload.json",
    "content": "{\n   \"entity\": \"allUsers\",\n   \"role\": \"OWNER\"\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/resources/default_object_acl_insert_response.json",
    "content": "{\n   \"kind\": \"storage#objectAccessControl\",\n   \"entity\": \"allUsers\",\n   \"role\": \"OWNER\",\n   \"etag\": \"CAo=\"\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/resources/default_object_acl_list.json",
    "content": "{\n   \"kind\": \"storage#objectAccessControls\",\n   \"items\": [\n     {\n        \"kind\": \"storage#objectAccessControl\",\n        \"entity\": \"project-owners-1082289308625\",\n        \"role\": \"OWNER\",\n          \"projectTeam\": {\n            \"projectNumber\": \"1082289308625\",\n            \"team\": \"owners\"\n          },\n        \"etag\": \"CAk=\"\n      }\n   ]\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/resources/default_object_acl_update_initial.json",
    "content": "{\n   \"kind\": \"storage#objectAccessControl\",\n   \"entity\": \"allUsers\",\n   \"role\": \"OWNER\",\n   \"etag\": \"CAo=\"\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/resources/default_object_acl_update_request_payload.json",
    "content": "{\n   \"kind\": \"storage#objectAccessControl\",\n   \"entity\": \"allUsers\",\n   \"role\": \"OWNER\"\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/resources/full_bucket_get.json",
    "content": "{\n   \"kind\": \"storage#bucket\",\n   \"id\": \"jcloudstestbucket3500\",\n   \"selfLink\": \"https://www.googleapis.com/storage/v1/b/jcloudstestbucket3500\",\n   \"projectNumber\": \"1082289308625\",\n   \"name\": \"jcloudstestbucket3500\",\n   \"timeCreated\": \"2014-06-19T14:03:22.345Z\",\n   \"metageneration\": \"10\",\n   \"acl\": [\n     {\n        \"kind\": \"storage#bucketAccessControl\",\n        \"id\": \"jcloudstestbucket3500/project-owners-1082289308625\",\n        \"selfLink\": \"https://www.googleapis.com/storage/v1/b/jcloudstestbucket3500/acl/project-owners-1082289308625\",\n        \"bucket\": \"jcloudstestbucket3500\",\n        \"entity\": \"project-owners-1082289308625\",\n        \"role\": \"OWNER\",\n        \"projectTeam\": {\n           \"projectNumber\": \"1082289308625\",\n           \"team\": \"owners\"\n        },\n        \"etag\": \"CAo=\"\n     }\n    ],\n    \"defaultObjectAcl\": [\n       {\n          \"kind\": \"storage#objectAccessControl\",\n          \"entity\": \"project-owners-1082289308625\",\n          \"role\": \"OWNER\",\n          \"etag\": \"CAo=\"\n       }\n    ],\n    \n    \"cors\": [\n       {\n          \"maxAgeSeconds\": 10,\n          \"origin\": [\n             \"http://example.appspot.com\"\n          ],\n          \"responseHeader\": [\n             \"x-meta-goog-custom\"\n          ],\n          \"method\": [\n            \"GET\",\n            \"HEAD\"            \n          ]\n        }\n    ],\n    \"owner\": {\n       \"entity\": \"project-owners-1082289308625\"\n     },\n    \"location\": \"US\",\n    \"storageClass\": \"STANDARD\",\n    \"etag\": \"CAo=\"\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/resources/list_bucket_with_options.json",
    "content": "{\n   \"kind\": \"storage#buckets\",\n   \"nextPageToken\": \"jcloudstestbucket500\",\n   \"items\": [\n      {\n         \"kind\": \"storage#bucket\",\n         \"id\": \"jcloudstestbucket500\",\n         \"selfLink\": \"https://www.googleapis.com/storage/v1/b/jcloudstestbucket500\",\n         \"projectNumber\": \"1082289308625\",\n         \"name\": \"jcloudstestbucket500\",\n         \"timeCreated\": \"2014-06-17T14:17:50.155Z\",\n         \"metageneration\": \"1\",\n         \"owner\": {\n          \"entity\": \"project-owners-1082289308625\"\n         },\n         \"location\": \"US\",\n         \"storageClass\": \"STANDARD\",\n         \"etag\": \"CAE=\"\n      }\n   ]\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/resources/logback.xml",
    "content": "<?xml version=\"1.0\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<configuration scan=\"false\">\n    <appender name=\"FILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <appender name=\"WIREFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds-wire.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <appender name=\"BLOBSTOREFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds-blobstore.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <root>\n        <level value=\"warn\" />\n    </root>\n\n    <logger name=\"org.jclouds\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"FILE\" />\n    </logger>\n\n<!--\n    <logger name=\"jclouds.wire\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n-->\n\n    <logger name=\"jclouds.headers\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n\n    <logger name=\"jclouds.blobstore\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"BLOBSTOREFILE\" />\n    </logger>\n\n</configuration>\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/resources/no_acl_bucket.json",
    "content": "{\n   \"kind\": \"storage#bucket\",\n   \"id\": \"bhashbucket\",\n   \"selfLink\": \"https://content.googleapis.com/storage/v1/b/bhashbucket\",\n   \"projectNumber\": \"1082289308625\",\n   \"name\": \"bhashbucket\",\n   \"timeCreated\": \"2014-06-02T19:19:41.112Z\",\n   \"metageneration\": \"87\",\n   \"owner\": {\n      \"entity\": \"project-owners-1082289308625\"\n   },\n   \"location\": \"US\",\n   \"storageClass\": \"STANDARD\",\n   \"etag\": \"CFc=\"\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/resources/no_acl_bucket_list.json",
    "content": "{\n   \"kind\": \"storage#buckets\",\n   \"nextPageToken\": \"bhashbucket\",\n   \"items\": [\n      {\n         \"kind\": \"storage#bucket\",\n         \"id\": \"bhashbucket\",\n         \"selfLink\": \"https://content.googleapis.com/storage/v1/b/bhashbucket\",\n         \"projectNumber\": \"1082289308625\",\n         \"name\": \"bhashbucket\",\n         \"timeCreated\": \"2014-06-02T19:19:41.112Z\",\n         \"metageneration\": \"99\",\n         \"owner\": {\n            \"entity\": \"project-owners-1082289308625\"\n         },\n         \"location\": \"US\",\n         \"storageClass\": \"STANDARD\",\n         \"etag\": \"CGM=\"\n      }\n   ]\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/resources/object_acl_get.json",
    "content": "{\n   \"kind\": \"storage#objectAccessControl\",\n   \"id\": \"jcloudstestbucket/foo.txt/1394121608485000/project-owners-1082289308625\",\n   \"selfLink\": \"https://www.googleapis.com/storage/v1/b/jcloudstestbucket/o/foo.txt/acl/project-owners-1082289308625\",\n   \"bucket\": \"jcloudstestbucket\",\n   \"object\": \"foo.txt\",\n   \"generation\": \"1394121608485000\",\n   \"entity\": \"project-owners-1082289308625\",\n   \"role\": \"OWNER\",\n   \"projectTeam\": {\n      \"projectNumber\": \"1082289308625\",\n      \"team\": \"owners\"\n   },\n   \"etag\": \"CIix/dmj/rwCEAE=\"\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/resources/object_acl_insert_request_payload.json",
    "content": "{\n   \"entity\": \"user-00b4903a97adfde729f0650133a7379693099d8d85d6b1b18255ca70bf89e31d\",\n   \"role\": \"OWNER\"\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/resources/object_acl_insert_response.json",
    "content": "{\n   \"kind\": \"storage#objectAccessControl\",\n   \"selfLink\": \"https://www.googleapis.com/storage/v1/b/jcloudstestbucket/o/foo.txt/acl/user-00b4903a97adfde729f0650133a7379693099d8d85d6b1b18255ca70bf89e31d\",\n   \"bucket\": \"jcloudstestbucket\",\n   \"object\": \"foo.txt\",\n   \"entity\": \"user-00b4903a97adfde729f0650133a7379693099d8d85d6b1b18255ca70bf89e31d\",\n   \"role\": \"OWNER\",\n   \"entityId\": \"00b4903a97adfde729f0650133a7379693099d8d85d6b1b18255ca70bf89e31d\",\n   \"etag\": \"CIix/dmj/rwCEAE=\"\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/resources/object_acl_list.json",
    "content": "{\n   \"kind\": \"storage#objectAccessControls\",\n   \"items\": [\n      {\n       \"kind\": \"storage#objectAccessControl\",\n       \"id\": \"jcloudstestbucket/foo.txt/1394121608485000/user-00b4903a97adfde729f0650133a7379693099d8d85d6b1b18255ca70bf89e31d\",\n       \"selfLink\": \"https://www.googleapis.com/storage/v1/b/jcloudstestbucket/o/foo.txt/acl/user-00b4903a97adfde729f0650133a7379693099d8d85d6b1b18255ca70bf89e31d\",\n       \"bucket\": \"jcloudstestbucket\",\n       \"object\": \"foo.txt\",\n       \"generation\": \"1394121608485000\",\n       \"entity\": \"user-00b4903a97adfde729f0650133a7379693099d8d85d6b1b18255ca70bf89e31d\",\n       \"role\": \"OWNER\",\n       \"entityId\": \"00b4903a97adfde729f0650133a7379693099d8d85d6b1b18255ca70bf89e31d\",\n       \"etag\": \"CIix/dmj/rwCEAE=\"\n      }\n   ]\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/resources/object_acl_request_payload.json",
    "content": "{\n   \"entity\": \"allUsers\",\n   \"role\": \"OWNER\"\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/resources/object_acl_update_initial.json",
    "content": "{\n   \"kind\": \"storage#objectAccessControl\",\n   \"selfLink\": \"https://www.googleapis.com/storage/v1/b/jcloudstestbucket/o/foo.txt/acl/allUsers\",\n   \"bucket\": \"jcloudstestbucket\",\n   \"object\": \"foo.txt\",\n   \"entity\": \"allUsers\",\n   \"role\": \"OWNER\",\n   \"etag\": \"CIix/dmj/rwCEAQ=\"\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/resources/object_acl_update_response.json",
    "content": "{\n   \"kind\": \"storage#objectAccessControl\",\n   \"selfLink\": \"https://www.googleapis.com/storage/v1/b/jcloudstestbucket/o/foo.txt/acl/allUsers\",\n   \"bucket\": \"jcloudstestbucket\",\n   \"object\": \"foo.txt\",\n   \"entity\": \"allUsers\",\n   \"role\": \"OWNER\",\n   \"etag\": \"CIix/dmj/rwCEAQ=\"\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/resources/object_compose_request.json",
    "content": "{\n  \"sourceObjects\": [\n    {\n      \"name\": \"file_name\",\n      \"generation\": 1000,\n      \"objectPreconditions\": {\n        \"ifGenerationMatch\": 1000\n      }\n    },\n    {\n      \"name\": \"file_name2\",\n      \"generation\": 1001,\n      \"objectPreconditions\": {\n        \"ifGenerationMatch\": 1001\n      }\n    }\n  ],\n  \"destination\": {\n    \"name\": \"file_name\",\n    \"size\": 1000,\n    \"crc32c\": \"crc32c\"\n  }\n}"
  },
  {
    "path": "providers/google-cloud-storage/src/test/resources/object_encoded_get.json",
    "content": "{\n  \"kind\": \"storage#object\",\n  \"id\": \"test/dir%2Ffile%20name/1000\",\n  \"selfLink\": \"https://www.googleapis.com/storage/v1/b/test/o/dir%2Ffile%20name\",\n  \"name\": \"dir%2Ffile%20name\",\n  \"bucket\": \"test\",\n  \"generation\": \"1000\",\n  \"metageneration\": \"8\",\n  \"contentType\": \"application/x-tar\",\n  \"updated\": \"2014-09-27T00:01:44.819\",\n  \"storageClass\": \"STANDARD\",\n  \"size\": \"1000\",\n  \"md5Hash\": \"md5Hash\",\n  \"mediaLink\": \"https://www.googleapis.com/download/storage/v1/b/test/o/dir%2Ffile%20name?generation=1000&alt=media\",\n  \"owner\": {\n    \"entity\": \"entity\",\n    \"entityId\": \"entityId\"\n  },\n  \"crc32c\": \"crc32c\",\n  \"etag\": \"etag\"\n}\n"
  },
  {
    "path": "providers/google-cloud-storage/src/test/resources/object_get.json",
    "content": "{\n  \"kind\": \"storage#object\",\n  \"id\": \"test/file_name/1000\",\n  \"selfLink\": \"https://www.googleapis.com/storage/v1/b/test/o/file_name\",\n  \"name\": \"file_name\",\n  \"bucket\": \"test\",\n  \"generation\": \"1000\",\n  \"metageneration\": \"8\",\n  \"contentType\": \"application/x-tar\",\n  \"updated\": \"2014-09-27T00:01:44.819\",\n  \"storageClass\": \"STANDARD\",\n  \"size\": \"1000\",\n  \"md5Hash\": \"md5Hash\",\n  \"mediaLink\": \"https://www.googleapis.com/download/storage/v1/b/test/o/file_name?generation=1000&alt=media\",\n  \"owner\": {\n    \"entity\": \"entity\",\n    \"entityId\": \"entityId\"\n  },\n  \"crc32c\": \"crc32c\",\n  \"etag\": \"etag\"\n}"
  },
  {
    "path": "providers/google-cloud-storage/src/test/resources/object_list.json",
    "content": "{\n  \"kind\": \"storage#objects\",\n  \"items\": [\n    {\n      \"kind\": \"storage#object\",\n      \"id\": \"test/file_name/1000\",\n      \"selfLink\": \"https://www.googleapis.com/storage/v1/b/test/o/file_name\",\n      \"name\": \"file_name\",\n      \"bucket\": \"test\",\n      \"generation\": \"1000\",\n      \"metageneration\": \"8\",\n      \"contentType\": \"application/x-tar\",\n      \"updated\": \"2014-09-27T00:01:44.819\",\n      \"storageClass\": \"STANDARD\",\n      \"size\": \"1000\",\n      \"md5Hash\": \"md5Hash\",\n      \"mediaLink\": \"https://www.googleapis.com/download/storage/v1/b/test/o/file_name?generation=1000&alt=media\",\n      \"owner\": {\n        \"entity\": \"entity\",\n        \"entityId\": \"entityId\"\n      },\n      \"crc32c\": \"crc32c\",\n      \"etag\": \"etag\"\n    },\n    {\n      \"kind\": \"storage#object\",\n      \"id\": \"test/file_name2/1000\",\n      \"selfLink\": \"https://www.googleapis.com/storage/v1/b/test/o/file_name2\",\n      \"name\": \"file_name2\",\n      \"bucket\": \"test\",\n      \"generation\": \"1001\",\n      \"metageneration\": \"9\",\n      \"contentType\": \"image/png\",\n      \"updated\": \"2014-09-27T00:01:44.819\",\n      \"storageClass\": \"STANDARD\",\n      \"size\": \"10\",\n      \"md5Hash\": \"md5Hash\",\n      \"mediaLink\": \"https://www.googleapis.com/download/storage/v1/b/test/o/file_name2?generation=1001&alt=media\",\n      \"owner\": {\n        \"entity\": \"entity\",\n        \"entityId\": \"entityId\"\n      },\n      \"crc32c\": \"crc32c\",\n      \"etag\": \"etag\"\n    }\n  ]\n}"
  },
  {
    "path": "providers/google-cloud-storage/src/test/resources/object_rewrite.json",
    "content": "{\n  \"kind\": \"storage#rewriteResponse\",\n  \"totalBytesRewritten\": \"16\",\n  \"objectSize\": \"16\",\n  \"rewriteToken\": \"rewriteToken\",\n  \"done\": true,\n  \"resource\": {\n    \"kind\": \"storage#object\",\n    \"id\": \"test/file_name/1000\",\n    \"selfLink\": \"https://www.googleapis.com/storage/v1/b/test/o/file_name\",\n    \"name\": \"file_name\",\n    \"bucket\": \"test\",\n    \"generation\": \"1000\",\n    \"metageneration\": \"8\",\n    \"contentType\": \"application/x-tar\",\n    \"updated\": \"2014-09-27T00:01:44.819\",\n    \"storageClass\": \"STANDARD\",\n    \"size\": \"1000\",\n    \"md5Hash\": \"md5Hash\",\n    \"mediaLink\": \"https://www.googleapis.com/download/storage/v1/b/test/o/file_name?generation=1000&alt=media\",\n    \"owner\": {\n      \"entity\": \"entity\",\n      \"entityId\": \"entityId\"\n    },\n    \"crc32c\": \"crc32c\",\n    \"etag\": \"etag\"\n  }\n}"
  },
  {
    "path": "providers/google-compute-engine/README.md",
    "content": "jclouds Google Compute Engine Provider\n======\n\n\nAuthenticating into the instances:\n--------\n\nUser:\nIf no user is specified in the template options when launching instances, the default one will be used: \"jclouds\" for all instances, \"core\" for CoreOS images, and \"Administrator\" for Windows images.\n\nCredential:\n\nGCE uses exclusively ssh keys to login into instances.\nIn order for an instance to be sshable a public key must be installed. Public keys are installed if they are present in the project or instance's metatada.\n\nFor an instance to be ssable one of the following must happen:\n1 - the project's metadata has an adequately built \"sshKeys\" entry and a corresponding private key is provided in GoogleComputeEngineTemplateOptions when createNodesInGroup is called.\n2 - an instance of GoogleComputeEngineTemplateOptions with an adequate public and private key is provided.\n\nNOTE: if methods 2 is chosen the global project keys will not be installed in the instance.\n\nPlease refer to Google's documentation on how to form valid project wide ssh keys metadata entries.\n\nFAQ:\n--------\n\n* Q. What is the identity for GCE?\n\nA. the identity is the developer email which can be obtained from the admin GUI. Its usually something in the form: [PROJECT_ID](https://cloud.google.com/compute/docs/overview#projectids)@developer.gserviceaccount.com\n\n* Q. What is the credential for GCE\n\nA. the credential is a private key, in pem format. It can be extracted from the p12 keystore that is obtained when creating a \"Service Account\" (in the GUI: Google apis console > Api Access > Create another client ID > \"Service Account\"\n\n* Q. How to convert a p12 keystore into a pem format jclouds Google Compute Engine can handle:\n\nA.\n\n1. Convert the p12 file into pem format (it will ask for the keystore password, which is usually \"notasecret\"):\n openssl pkcs12 -in <my_keystore>.p12 -out <my_keystore>.pem -nodes\n\n2. Extract only the pk and remove passphrase\n openssl rsa -in <my_keystore>.pem -out <my_key>.pem\n\nThe last file (<my_key>.pem) should contain the pk that needs to be passed to `ContextBuilder.credential()` for the provider `google-compute-engine`.\n\n\nRunning the live tests:\n--------\n\n1. Place the following in your ~/.m2/settings.xml in a profile enabled when live:\n```\n    <test.google-compute-engine.identity>PROJECT_ID@developer.gserviceaccount.com</test.google-compute-engine.identity>\n    <test.google-compute-engine.credential>-----BEGIN RSA PRIVATE KEY-----\nMIICXgIBAAKBgQRRbRqVDtJLN1MO/xJoKqZuphDeBh5jIKueW3aNIiWs1XFcct+h\n-- this text is literally from your <my_key>.pem\naH7xmpHSTbbXmQkuuv+z8EKijigprd/FoJpTX1f5/R+4wQ==\n-----END RSA PRIVATE KEY-----</test.google-compute-engine.credential>\n  </properties>\n```\nOr, if using an existing OAuth Bearer Token for authentication.\n```\n    <test.google-compute-engine.identity>PROJECT_ID@developer.gserviceaccount.com</test.google-compute-engine.identity>\n    <test.google-compute-engine.credential>EXISTING_BEARER_TOKEN</test.google-compute-engine.credential>\n    <test.jclouds.oauth.credential-type>bearerTokenCredentials</test.jclouds.oauth.credential-type>\n  </properties>\n```\n\n2. mvn clean install -Plive \n\n"
  },
  {
    "path": "providers/google-compute-engine/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.googlecomputeengine.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "providers/google-compute-engine/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n         xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n    <modelVersion>4.0.0</modelVersion>\n    <parent>\n        <groupId>org.apache.jclouds</groupId>\n        <artifactId>jclouds-project</artifactId>\n        <version>2.7.1-SNAPSHOT</version>\n        <relativePath>../../project/pom.xml</relativePath>\n    </parent>\n\n    <groupId>org.apache.jclouds.provider</groupId>\n    <artifactId>google-compute-engine</artifactId>\n    <name>jclouds Google Compute Engine provider</name>\n    <description>jclouds components to access GoogleCompute</description>\n\n    <properties>\n        <test.google-compute-engine.identity>client_email which usually looks like project_id@developer.gserviceaccount.com</test.google-compute-engine.identity>\n        <test.google-compute-engine.credential>Private key (PEM encoded PKCS12 file or literal) associated with the client_email</test.google-compute-engine.credential>\n        <!-- Add this property to use a different project, or avoid looking up the project for each test. -->\n        <test.jclouds.googlecloud.project-name></test.jclouds.googlecloud.project-name>\n        <test.jclouds.oauth.credential-type>p12PrivateKeyCredentials</test.jclouds.oauth.credential-type>\n        <test.google-compute-engine.api-version>v1</test.google-compute-engine.api-version>\n        <test.google-compute-engine.build-version/>\n        <test.google-compute-engine.template>imageNameMatches=debian-7-wheezy-v[0-9]*,locationId=us-central1-a,minRam=2048</test.google-compute-engine.template>\n    </properties>\n\n    <dependencies>\n        <dependency>\n            <groupId>org.apache.jclouds</groupId>\n            <artifactId>jclouds-core</artifactId>\n            <version>${project.version}</version>\n        </dependency>\n        <dependency>\n            <groupId>org.apache.jclouds.driver</groupId>\n            <artifactId>jclouds-bouncycastle</artifactId>\n            <version>${project.version}</version>\n        </dependency>\n        <dependency>\n            <groupId>org.apache.jclouds.common</groupId>\n            <artifactId>googlecloud</artifactId>\n            <version>${project.version}</version>\n            <type>jar</type>\n        </dependency>\n        <dependency>\n            <groupId>org.apache.jclouds.common</groupId>\n            <artifactId>googlecloud</artifactId>\n            <version>${project.version}</version>\n            <type>test-jar</type>\n            <scope>test</scope>\n        </dependency>\n        <dependency>\n            <groupId>org.apache.jclouds.api</groupId>\n            <artifactId>oauth</artifactId>\n            <version>${project.version}</version>\n            <type>test-jar</type>\n            <scope>test</scope>\n        </dependency>\n        <dependency>\n            <groupId>org.apache.jclouds</groupId>\n            <artifactId>jclouds-compute</artifactId>\n            <version>${project.version}</version>\n        </dependency>\n        <dependency>\n            <groupId>com.google.auto.service</groupId>\n            <artifactId>auto-service</artifactId>\n            <scope>provided</scope>\n            <optional>true</optional>\n        </dependency>\n        <dependency>\n            <groupId>com.google.auto.value</groupId>\n            <artifactId>auto-value</artifactId>\n            <scope>provided</scope>\n        </dependency>\n        <dependency>\n            <groupId>org.apache.jclouds</groupId>\n            <artifactId>jclouds-compute</artifactId>\n            <version>${project.version}</version>\n            <type>test-jar</type>\n            <scope>test</scope>\n        </dependency>\n        <dependency>\n            <groupId>org.apache.jclouds</groupId>\n            <artifactId>jclouds-core</artifactId>\n            <version>${project.version}</version>\n            <type>test-jar</type>\n            <scope>test</scope>\n        </dependency>\n        <dependency>\n            <groupId>org.apache.jclouds.driver</groupId>\n            <artifactId>jclouds-slf4j</artifactId>\n            <version>${project.version}</version>\n            <scope>test</scope>\n        </dependency>\n        <dependency>\n            <groupId>org.apache.jclouds.driver</groupId>\n            <artifactId>jclouds-sshj</artifactId>\n            <version>${project.version}</version>\n            <scope>test</scope>\n        </dependency>\n        <dependency>\n            <groupId>org.apache.jclouds.driver</groupId>\n            <artifactId>jclouds-okhttp</artifactId>\n            <version>${project.version}</version>\n            <scope>test</scope>\n        </dependency>\n        <dependency>\n            <groupId>ch.qos.logback</groupId>\n            <artifactId>logback-classic</artifactId>\n            <scope>test</scope>\n        </dependency>\n        <dependency>\n          <groupId>com.squareup.okhttp3</groupId>\n          <artifactId>mockwebserver</artifactId>\n          <scope>test</scope>\n        </dependency>\n    </dependencies>\n    <profiles>\n        <profile>\n            <id>live</id>\n            <build>\n                <plugins>\n                    <plugin>\n                        <groupId>org.apache.maven.plugins</groupId>\n                        <artifactId>maven-surefire-plugin</artifactId>\n                        <executions>\n                            <execution>\n                                <id>default-test</id>\n                                <configuration>\n                                    <skipTests>true</skipTests>\n                                </configuration>\n                            </execution>\n                            <execution>\n                                <id>integration</id>\n                                <phase>integration-test</phase>\n                                <goals>\n                                    <goal>test</goal>\n                                </goals>\n                                <configuration>\n                                    <threadCount>1</threadCount>\n                                    <systemPropertyVariables>\n                                        <test.google-compute-engine.identity>${test.google-compute-engine.identity}</test.google-compute-engine.identity>\n                                        <test.google-compute-engine.credential>${test.google-compute-engine.credential}</test.google-compute-engine.credential>\n                                        <test.jclouds.googlecloud.project-name>${test.jclouds.googlecloud.project-name}</test.jclouds.googlecloud.project-name>\n                                        <test.jclouds.oauth.credential-type>${test.jclouds.oauth.credential-type}</test.jclouds.oauth.credential-type>\n                                        <test.google-compute-engine.api-version>${test.google-compute-engine.api-version}</test.google-compute-engine.api-version>\n                                        <test.google-compute-engine.build-version>${test.google-compute-engine.build-version}</test.google-compute-engine.build-version>\n                                        <test.google-compute-engine.template>${test.google-compute-engine.template}</test.google-compute-engine.template>\n                                    </systemPropertyVariables>\n                                </configuration>\n                            </execution>\n                        </executions>\n                    </plugin>\n                </plugins>\n            </build>\n        </profile>\n    </profiles>\n</project>\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/GoogleComputeEngineApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine;\n\nimport java.io.Closeable;\n\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\n\nimport org.jclouds.googlecloud.config.CurrentProject;\nimport org.jclouds.googlecomputeengine.features.AddressApi;\nimport org.jclouds.googlecomputeengine.features.AggregatedListApi;\nimport org.jclouds.googlecomputeengine.features.BackendServiceApi;\nimport org.jclouds.googlecomputeengine.features.DiskApi;\nimport org.jclouds.googlecomputeengine.features.DiskTypeApi;\nimport org.jclouds.googlecomputeengine.features.FirewallApi;\nimport org.jclouds.googlecomputeengine.features.ForwardingRuleApi;\nimport org.jclouds.googlecomputeengine.features.HttpHealthCheckApi;\nimport org.jclouds.googlecomputeengine.features.ImageApi;\nimport org.jclouds.googlecomputeengine.features.InstanceApi;\nimport org.jclouds.googlecomputeengine.features.LicenseApi;\nimport org.jclouds.googlecomputeengine.features.MachineTypeApi;\nimport org.jclouds.googlecomputeengine.features.NetworkApi;\nimport org.jclouds.googlecomputeengine.features.OperationApi;\nimport org.jclouds.googlecomputeengine.features.ProjectApi;\nimport org.jclouds.googlecomputeengine.features.RegionApi;\nimport org.jclouds.googlecomputeengine.features.RouteApi;\nimport org.jclouds.googlecomputeengine.features.SnapshotApi;\nimport org.jclouds.googlecomputeengine.features.SubnetworkApi;\nimport org.jclouds.googlecomputeengine.features.TargetHttpProxyApi;\nimport org.jclouds.googlecomputeengine.features.TargetInstanceApi;\nimport org.jclouds.googlecomputeengine.features.TargetPoolApi;\nimport org.jclouds.googlecomputeengine.features.UrlMapApi;\nimport org.jclouds.googlecomputeengine.features.ZoneApi;\nimport org.jclouds.rest.annotations.Delegate;\nimport org.jclouds.rest.annotations.Endpoint;\n\npublic interface GoogleComputeEngineApi extends Closeable {\n\n   @Delegate\n   @Endpoint(CurrentProject.class)\n   @Path(\"/regions/{region}\")\n   AddressApi addressesInRegion(@PathParam(\"region\") String region);\n\n   @Delegate\n   @Endpoint(CurrentProject.class)\n   AggregatedListApi aggregatedList();\n\n   @Delegate\n   @Endpoint(CurrentProject.class)\n   @Path(\"/global/backendServices\")\n   BackendServiceApi backendServices();\n\n   @Delegate\n   @Endpoint(CurrentProject.class)\n   @Path(\"/zones/{zone}\")\n   DiskApi disksInZone(@PathParam(\"zone\") String zone);\n\n   @Delegate\n   @Endpoint(CurrentProject.class)\n   @Path(\"/zones/{zone}\")\n   DiskTypeApi diskTypesInZone(@PathParam(\"zone\") String zone);\n\n   @Delegate\n   @Endpoint(CurrentProject.class)\n   @Path(\"/global\")\n   FirewallApi firewalls();\n\n   @Delegate\n   @Endpoint(CurrentProject.class)\n   @Path(\"/regions/{region}\")\n   ForwardingRuleApi forwardingRulesInRegion(@PathParam(\"region\") String region);\n\n   @Delegate\n   @Endpoint(CurrentProject.class)\n   @Path(\"/global\")\n   ForwardingRuleApi globalForwardingRules();\n\n   @Delegate\n   @Endpoint(CurrentProject.class)\n   @Path(\"/global\")\n   HttpHealthCheckApi httpHeathChecks();\n\n   @Delegate\n   ImageApi images();\n\n   @Delegate\n   @Endpoint(CurrentProject.class)\n   @Path(\"/zones/{zone}\")\n   InstanceApi instancesInZone(@PathParam(\"zone\") String zone);\n\n   @Delegate\n   @Path(\"/projects/{project}/global\")\n   LicenseApi licensesInProject(@PathParam(\"project\") String project);\n\n   @Delegate\n   @Endpoint(CurrentProject.class)\n   @Path(\"/zones/{zone}\")\n   MachineTypeApi machineTypesInZone(@PathParam(\"zone\") String zone);\n\n   @Delegate\n   @Endpoint(CurrentProject.class)\n   @Path(\"/global\")\n   NetworkApi networks();\n\n   @Delegate\n   @Endpoint(CurrentProject.class)\n   @Path(\"/regions/{region}\")\n   SubnetworkApi subnetworksInRegion(@PathParam(\"region\") String region);\n\n   @Delegate\n   OperationApi operations();\n\n   @Delegate\n   @Endpoint(CurrentProject.class)\n   ProjectApi project();\n\n   @Delegate\n   @Endpoint(CurrentProject.class)\n   RegionApi regions();\n\n   @Delegate\n   @Endpoint(CurrentProject.class)\n   @Path(\"/global\")\n   RouteApi routes();\n\n   @Delegate\n   @Endpoint(CurrentProject.class)\n   @Path(\"/global\")\n   SnapshotApi snapshots();\n\n   @Delegate\n   @Endpoint(CurrentProject.class)\n   TargetHttpProxyApi targetHttpProxies();\n\n   @Delegate\n   @Endpoint(CurrentProject.class)\n   @Path(\"/zones/{zone}\")\n   TargetInstanceApi targetInstancesInZone(@PathParam(\"zone\") String zone);\n\n   @Delegate\n   @Endpoint(CurrentProject.class)\n   @Path(\"/regions/{region}\")\n   TargetPoolApi targetPoolsInRegion(@PathParam(\"region\") String region);\n\n   @Delegate\n   @Endpoint(CurrentProject.class)\n   ZoneApi zones();\n\n   @Delegate\n   @Endpoint(CurrentProject.class)\n   @Path(\"/global/urlMaps\")\n   UrlMapApi urlMaps();\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/GoogleComputeEngineApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine;\n\nimport static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TEMPLATE;\nimport static org.jclouds.googlecloud.config.GoogleCloudProperties.PROJECT_NAME;\nimport static org.jclouds.googlecomputeengine.config.GoogleComputeEngineProperties.IMAGE_PROJECTS;\nimport static org.jclouds.googlecomputeengine.config.GoogleComputeEngineProperties.OPERATION_COMPLETE_INTERVAL;\nimport static org.jclouds.googlecomputeengine.config.GoogleComputeEngineProperties.OPERATION_COMPLETE_TIMEOUT;\nimport static org.jclouds.oauth.v2.config.OAuthProperties.AUDIENCE;\nimport static org.jclouds.oauth.v2.config.OAuthProperties.JWS_ALG;\nimport static org.jclouds.reflect.Reflection2.typeToken;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.googlecloud.config.CurrentProject;\nimport org.jclouds.googlecomputeengine.compute.config.GoogleComputeEngineServiceContextModule;\nimport org.jclouds.googlecomputeengine.config.GoogleComputeEngineHttpApiModule;\nimport org.jclouds.googlecomputeengine.config.GoogleComputeEngineParserModule;\nimport org.jclouds.oauth.v2.config.OAuthModule;\nimport org.jclouds.rest.internal.BaseHttpApiMetadata;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\npublic class GoogleComputeEngineApiMetadata extends BaseHttpApiMetadata<GoogleComputeEngineApi> {\n   @Override\n   public Builder toBuilder() {\n      return new Builder().fromApiMetadata(this);\n   }\n\n   public GoogleComputeEngineApiMetadata() {\n      this(new Builder());\n   }\n\n   protected GoogleComputeEngineApiMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = BaseHttpApiMetadata.defaultProperties();\n      properties.put(\"oauth.endpoint\", \"https://accounts.google.com/o/oauth2/token\");\n      properties.put(AUDIENCE, \"https://accounts.google.com/o/oauth2/token\");\n      properties.put(JWS_ALG, \"RS256\");\n      properties.put(PROPERTY_SESSION_INTERVAL, 3600);\n      properties.put(OPERATION_COMPLETE_INTERVAL, 500);\n      properties.put(OPERATION_COMPLETE_TIMEOUT, 1000000);\n      properties.put(TEMPLATE, \"osFamily=DEBIAN,osVersionMatches=7\\\\..*,locationId=us-central1-a\");\n      properties.put(PROJECT_NAME, \"\"); // Defaulting to empty helps avoid temptation for optional inject!\n      properties.put(IMAGE_PROJECTS, \"centos-cloud,debian-cloud,rhel-cloud,suse-cloud,opensuse-cloud,gce-nvme,coreos-cloud,ubuntu-os-cloud,windows-cloud\");\n      return properties;\n   }\n\n   public static class Builder extends BaseHttpApiMetadata.Builder<GoogleComputeEngineApi, Builder> {\n\n      protected Builder() {\n         id(\"google-compute-engine\")\n           .name(\"Google Compute Engine Api\")\n           .identityName(CurrentProject.ClientEmail.DESCRIPTION)\n           .credentialName(\"PEM encoded P12 private key associated with client_email\")\n           .documentation(URI.create(\"https://developers.google.com/compute/docs\"))\n           .version(\"v1\")\n           .defaultEndpoint(\"https://www.googleapis.com/compute/v1\")\n           .defaultProperties(GoogleComputeEngineApiMetadata.defaultProperties())\n           .view(typeToken(ComputeServiceContext.class))\n           .defaultModules(ImmutableSet.<Class<? extends Module>>builder()\n                   .add(GoogleComputeEngineHttpApiModule.class)\n                   .add(GoogleComputeEngineParserModule.class)\n                   .add(OAuthModule.class)\n                   .add(GoogleComputeEngineServiceContextModule.class)\n                   .build());\n      }\n\n      @Override\n      public GoogleComputeEngineApiMetadata build() {\n         return new GoogleComputeEngineApiMetadata(this);\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/GoogleComputeEngineFallbacks.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Predicates.in;\nimport static com.google.common.base.Throwables.propagate;\nimport static com.google.common.primitives.Ints.asList;\nimport static org.jclouds.http.HttpUtils.returnValueOnCodeOrNull;\n\nimport org.jclouds.Fallback;\n\npublic final class GoogleComputeEngineFallbacks {\n   public static class NullOn400or404 implements Fallback<Object> {\n      @Override public Object createOrPropagate(Throwable t) throws Exception {\n         Boolean returnVal = returnValueOnCodeOrNull(checkNotNull(t, \"throwable\"), false, in(asList(400, 404)));\n         if (returnVal != null)\n            return null;\n         throw propagate(t);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/GoogleComputeEngineProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\n\nimport com.google.auto.service.AutoService;\n\n/** Note: This does not set iso3166Codes as Google intentionally does not document them. */\n@AutoService(ProviderMetadata.class)\npublic final class GoogleComputeEngineProviderMetadata extends BaseProviderMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromProviderMetadata(this);\n   }\n\n   public GoogleComputeEngineProviderMetadata() {\n      super(builder());\n   }\n\n   public GoogleComputeEngineProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      return new Properties(); // currently all are set in the api metadata class.\n   }\n\n   public static final class Builder extends BaseProviderMetadata.Builder {\n\n      private Builder() {\n         id(\"google-compute-engine\") //\n         .name(\"Google Compute Engine\") //\n         .apiMetadata(new GoogleComputeEngineApiMetadata()) //\n         .homepage(URI.create(\"https://cloud.google.com/compute\")) //\n         .console(URI.create(\"https://console.developers.google.com/project\")) //\n         .defaultProperties(GoogleComputeEngineProviderMetadata.defaultProperties());\n      }\n\n      @Override public GoogleComputeEngineProviderMetadata build() {\n         return new GoogleComputeEngineProviderMetadata(this);\n      }\n\n      @Override public Builder fromProviderMetadata(ProviderMetadata in) {\n         super.fromProviderMetadata(in);\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/binders/DiskCreationBinder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.binders;\n\nimport java.io.IOException;\nimport java.io.StringWriter;\nimport java.io.Writer;\nimport java.util.Map;\n\nimport org.jclouds.googlecomputeengine.options.DiskCreationOptions;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.MapBinder;\n\nimport com.google.gson.stream.JsonWriter;\n\npublic final class DiskCreationBinder implements MapBinder {\n\n   @Override public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      DiskCreationOptions options = (DiskCreationOptions) postParams.get(\"options\");\n      Writer out = new StringWriter();\n      JsonWriter json = new JsonWriter(out);\n      json.setSerializeNulls(false);\n      try {\n         json.beginObject();\n         json.name(\"name\").value(postParams.get(\"name\").toString());\n         json.name(\"sizeGb\").value(options.sizeGb());\n         json.name(\"type\").value(options.type() != null ? options.type().toString() : null);\n         json.name(\"sourceSnapshot\")\n               .value(options.sourceSnapshot() != null ? options.sourceSnapshot().toString() : null);\n         json.name(\"description\").value(options.description());\n         json.endObject();\n         json.close();\n      } catch (IOException e) {\n         throw new AssertionError(e); // should be impossible as we are writing a string!\n      }\n      request.setPayload(out.toString());\n      request.getPayload().getContentMetadata().setContentType(\"application/json\");\n      return request;\n   }\n\n   @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      throw new UnsupportedOperationException();\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/binders/FirewallBinder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.binders;\n\nimport java.net.URI;\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.googlecomputeengine.options.FirewallOptions;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.MapBinder;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\npublic class FirewallBinder implements MapBinder {\n\n   private final BindToJsonPayload jsonBinder;\n\n   @Inject FirewallBinder(BindToJsonPayload jsonBinder){\n      this.jsonBinder = jsonBinder;\n   }\n\n   @Override public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      FirewallOptions options = (FirewallOptions) postParams.get(\"options\");\n      options.name(postParams.get(\"name\").toString());\n      options.network((URI) postParams.get(\"network\"));\n      return bindToRequest(request, options);\n   }\n\n   @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      return jsonBinder.bindToRequest(request, input);\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/binders/ForwardingRuleCreationBinder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.binders;\n\nimport java.net.URI;\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.googlecomputeengine.domain.ForwardingRule;\nimport org.jclouds.googlecomputeengine.options.ForwardingRuleCreationOptions;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.json.Json;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\n\npublic class ForwardingRuleCreationBinder extends BindToJsonPayload {\n\n   @Inject ForwardingRuleCreationBinder(Json jsonBinder) {\n      super(jsonBinder);\n   }\n\n   @Override public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      ForwardingRuleCreationOptions options = (ForwardingRuleCreationOptions) postParams.get(\"options\");\n      String name = postParams.get(\"name\").toString();\n      ForwardingRuleCreationBinderHelper forwardingRuleCreationBinderHelper = new ForwardingRuleCreationBinderHelper(name, options);\n      return super.bindToRequest(request, forwardingRuleCreationBinderHelper);\n   }\n\n   private static class ForwardingRuleCreationBinderHelper{\n\n      /**\n       * Values used to bind ForwardingRuleOptions to json request.\n       * Note: Two break convention of starting with lower case letters due to\n       *       attributes on GCE starting with upper case letters.\n       */\n      @SuppressWarnings(\"unused\")\n      private String name;\n      @SuppressWarnings(\"unused\")\n      private String description;\n      @SuppressWarnings(\"unused\")\n      private String ipAddress;\n      @SuppressWarnings(\"unused\")\n      private ForwardingRule.IPProtocol ipProtocol;\n      @SuppressWarnings(\"unused\")\n      private String portRange;\n      @SuppressWarnings(\"unused\")\n      private URI target;\n\n      private ForwardingRuleCreationBinderHelper(String name, ForwardingRuleCreationOptions forwardingRuleCreationOptions){\n         this.name = name;\n         this.description = forwardingRuleCreationOptions.description();\n         this.ipAddress = forwardingRuleCreationOptions.ipAddress();\n         this.ipProtocol = forwardingRuleCreationOptions.ipProtocol();\n         this.portRange = forwardingRuleCreationOptions.portRange();\n         this.target = forwardingRuleCreationOptions.target();\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/binders/HttpHealthCheckCreationBinder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.binders;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.googlecomputeengine.options.HttpHealthCheckCreationOptions;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.json.Json;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\n\npublic class HttpHealthCheckCreationBinder extends BindToJsonPayload {\n\n   @Inject HttpHealthCheckCreationBinder(Json jsonBinder) {\n      super(jsonBinder);\n   }\n\n   @Override public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      HttpHealthCheckCreationOptions options = (HttpHealthCheckCreationOptions) postParams.get(\"options\");\n      String name = postParams.get(\"name\").toString();\n      HttpHealthCheckBinderHelper helper = new HttpHealthCheckBinderHelper(name, options);\n      return super.bindToRequest(request, helper);\n   }\n\n   private static class HttpHealthCheckBinderHelper{\n\n      /**\n       * Values used to bind HttpHealthCheckCreationOptions to json request.\n       */\n      @SuppressWarnings(\"unused\")\n      private String name;\n      @SuppressWarnings(\"unused\")\n      private String host;\n      @SuppressWarnings(\"unused\")\n      private String requestPath;\n      @SuppressWarnings(\"unused\")\n      private Integer port;\n      @SuppressWarnings(\"unused\")\n      private Integer checkIntervalSec;\n      @SuppressWarnings(\"unused\")\n      private Integer timeoutSec;\n      @SuppressWarnings(\"unused\")\n      private Integer unhealthyThreshold;\n      @SuppressWarnings(\"unused\")\n      private Integer healthyThreshold;\n      @SuppressWarnings(\"unused\")\n      private String description;\n\n      private HttpHealthCheckBinderHelper(String name, HttpHealthCheckCreationOptions httpHealthCheckCreationOptions){\n         this.name = name;\n         this.host = httpHealthCheckCreationOptions.host();\n         this.requestPath = httpHealthCheckCreationOptions.requestPath();\n         this.port = httpHealthCheckCreationOptions.port();\n         this.checkIntervalSec = httpHealthCheckCreationOptions.checkIntervalSec();\n         this.timeoutSec = httpHealthCheckCreationOptions.timeoutSec();\n         this.unhealthyThreshold = httpHealthCheckCreationOptions.unhealthyThreshold();\n         this.healthyThreshold = httpHealthCheckCreationOptions.healthyThreshold();\n         this.description = httpHealthCheckCreationOptions.description();\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/binders/RouteBinder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.binders;\n\nimport java.net.URI;\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.googlecomputeengine.options.RouteOptions;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.MapBinder;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\npublic class RouteBinder implements MapBinder {\n\n   private final BindToJsonPayload jsonBinder;\n\n   @Inject RouteBinder(BindToJsonPayload jsonBinder){\n      this.jsonBinder = jsonBinder;\n   }\n\n   @Override public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      RouteOptions options = (RouteOptions) postParams.get(\"options\");\n      options.name(postParams.get(\"name\").toString());\n      options.network((URI) postParams.get(\"network\"));\n      return bindToRequest(request, options);\n   }\n\n   @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      return jsonBinder.bindToRequest(request, input);\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/binders/TargetPoolChangeHealthChecksBinder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.binders;\n\nimport jakarta.inject.Inject;\n\n/**\n * Binder used for adding and deleting healthChecks from a target pool.\n */\npublic final class TargetPoolChangeHealthChecksBinder extends TargetPoolMapofListofMapGenericBinder {\n   @Inject TargetPoolChangeHealthChecksBinder() {\n      super(\"healthChecks\", \"healthCheck\");\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/binders/TargetPoolChangeInstancesBinder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.binders;\n\nimport jakarta.inject.Inject;\n\n/**\n * Binder used for adding and deleting instances from a target pool.\n */\npublic final class TargetPoolChangeInstancesBinder extends TargetPoolMapofListofMapGenericBinder {\n   @Inject TargetPoolChangeInstancesBinder() {\n      super(\"instances\", \"instance\");\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/binders/TargetPoolMapofListofMapGenericBinder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.binders;\n\nimport java.io.IOException;\nimport java.io.StringWriter;\nimport java.io.Writer;\nimport java.net.URI;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.MapBinder;\n\nimport com.google.gson.stream.JsonWriter;\n\nclass TargetPoolMapofListofMapGenericBinder implements MapBinder {\n   private final String outterString;\n   private final String innerString;\n\n   TargetPoolMapofListofMapGenericBinder(String outterString, String innerString) {\n      this.outterString = outterString;\n      this.innerString = innerString;\n   }\n\n   @Override public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      Writer out = new StringWriter();\n      JsonWriter json = new JsonWriter(out);\n      try {\n         json.beginObject();\n         json.name(outterString);\n         json.beginArray();\n         for (URI uri : (List<URI>) postParams.get(outterString)) {\n            json.beginObject();\n            json.name(innerString).value(uri.toString());\n            json.endObject();\n         }\n         json.endArray();\n         json.endObject();\n         json.close();\n      } catch (IOException e) {\n         throw new AssertionError(e); // should be impossible as we are writing a string!\n      }\n      request.setPayload(out.toString());\n      request.getPayload().getContentMetadata().setContentType(\"application/json\");\n      return request;\n   }\n\n   @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      throw new UnsupportedOperationException();\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/compute/GoogleComputeEngineService.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.compute;\n\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_RUNNING;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_SUSPENDED;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_TERMINATED;\nimport static org.jclouds.googlecloud.internal.ListPages.concat;\n\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Provider;\n\nimport org.jclouds.Constants;\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.compute.callables.RunScriptOnNode;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.TemplateBuilder;\nimport org.jclouds.compute.extensions.ImageExtension;\nimport org.jclouds.compute.extensions.SecurityGroupExtension;\nimport org.jclouds.compute.extensions.internal.DelegatingImageExtension;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.compute.internal.BaseComputeService;\nimport org.jclouds.compute.internal.PersistNodeCredentials;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.compute.strategy.CreateNodesInGroupThenAddToSet;\nimport org.jclouds.compute.strategy.DestroyNodeStrategy;\nimport org.jclouds.compute.strategy.GetImageStrategy;\nimport org.jclouds.compute.strategy.GetNodeMetadataStrategy;\nimport org.jclouds.compute.strategy.InitializeRunScriptOnNodeOrPlaceInBadMap;\nimport org.jclouds.compute.strategy.ListNodesStrategy;\nimport org.jclouds.compute.strategy.RebootNodeStrategy;\nimport org.jclouds.compute.strategy.ResumeNodeStrategy;\nimport org.jclouds.compute.strategy.SuspendNodeStrategy;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.domain.Location;\nimport org.jclouds.googlecomputeengine.GoogleComputeEngineApi;\nimport org.jclouds.googlecomputeengine.compute.options.GoogleComputeEngineTemplateOptions;\nimport org.jclouds.googlecomputeengine.domain.Firewall;\nimport org.jclouds.googlecomputeengine.domain.Operation;\nimport org.jclouds.googlecomputeengine.features.FirewallApi;\nimport org.jclouds.scriptbuilder.functions.InitAdminAccess;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.util.concurrent.Atomics;\nimport com.google.common.util.concurrent.ListeningExecutorService;\n\npublic final class GoogleComputeEngineService extends BaseComputeService {\n\n   private final Function<Set<? extends NodeMetadata>, Set<String>> findOrphanedGroups;\n   private final GroupNamingConvention.Factory namingConvention;\n   private final GoogleComputeEngineApi api;\n   private final Predicate<AtomicReference<Operation>> operationDone;\n\n   @Inject\n   GoogleComputeEngineService(ComputeServiceContext context, Map<String, Credentials> credentialStore,\n         @Memoized Supplier<Set<? extends Image>> images, @Memoized Supplier<Set<? extends Hardware>> hardwareProfiles,\n         @Memoized Supplier<Set<? extends Location>> locations, ListNodesStrategy listNodesStrategy,\n         GetImageStrategy getImageStrategy, GetNodeMetadataStrategy getNodeMetadataStrategy,\n         CreateNodesInGroupThenAddToSet runNodesAndAddToSetStrategy, RebootNodeStrategy rebootNodeStrategy,\n         DestroyNodeStrategy destroyNodeStrategy, ResumeNodeStrategy resumeNodeStrategy,\n         SuspendNodeStrategy suspendNodeStrategy, Provider<TemplateBuilder> templateBuilderProvider,\n         @Named(\"DEFAULT\") Provider<TemplateOptions> templateOptionsProvider,\n         @Named(TIMEOUT_NODE_RUNNING) Predicate<AtomicReference<NodeMetadata>> nodeRunning,\n         @Named(TIMEOUT_NODE_TERMINATED) Predicate<AtomicReference<NodeMetadata>> nodeTerminated,\n         @Named(TIMEOUT_NODE_SUSPENDED) Predicate<AtomicReference<NodeMetadata>> nodeSuspended,\n         InitializeRunScriptOnNodeOrPlaceInBadMap.Factory initScriptRunnerFactory, InitAdminAccess initAdminAccess,\n         RunScriptOnNode.Factory runScriptOnNodeFactory, PersistNodeCredentials persistNodeCredentials,\n         @Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor,\n         Optional<ImageExtension> imageExtension, Optional<SecurityGroupExtension> securityGroupExtension,\n         Function<Set<? extends NodeMetadata>, Set<String>> findOrphanedGroups,\n         GroupNamingConvention.Factory namingConvention, GoogleComputeEngineApi api,\n         Predicate<AtomicReference<Operation>> operationDone, DelegatingImageExtension.Factory delegatingImageExtension) {\n      super(context, credentialStore, images, hardwareProfiles, locations, listNodesStrategy, getImageStrategy,\n            getNodeMetadataStrategy, runNodesAndAddToSetStrategy, rebootNodeStrategy, destroyNodeStrategy,\n            resumeNodeStrategy, suspendNodeStrategy, templateBuilderProvider, templateOptionsProvider, nodeRunning,\n            nodeTerminated, nodeSuspended, initScriptRunnerFactory, initAdminAccess, runScriptOnNodeFactory,\n            persistNodeCredentials, userExecutor, imageExtension, securityGroupExtension, delegatingImageExtension);\n      this.findOrphanedGroups = findOrphanedGroups;\n      this.namingConvention = namingConvention;\n      this.api = api;\n      this.operationDone = operationDone;\n   }\n   \n   @Override\n   protected synchronized void cleanUpIncidentalResourcesOfDeadNodes(Set<? extends NodeMetadata> deadNodes) {\n      Set<String> orphanedGroups = findOrphanedGroups.apply(deadNodes);\n      for (String orphanedGroup : orphanedGroups) {\n         cleanUpFirewallsForGroup(orphanedGroup);\n      }\n   }\n\n   private void cleanUpFirewallsForGroup(final String groupName) {\n      GroupNamingConvention namingScheme = namingConvention.create();\n      FirewallApi firewallApi = api.firewalls();\n\n      for (Firewall firewall : concat(firewallApi.list())) {\n         String foundGroup = namingScheme.groupInUniqueNameOrNull(firewall.name());\n         if ((foundGroup != null) && foundGroup.equals(groupName)){\n            AtomicReference<Operation> operation = Atomics.newReference(firewallApi.delete(firewall.name()));\n            operationDone.apply(operation);\n\n            if (operation.get().httpErrorStatusCode() != null) {\n               logger.warn(\"delete orphaned firewall %s failed. Http Error Code: %d HttpError: %s\",\n                     operation.get().targetId(), operation.get().httpErrorStatusCode(),\n                     operation.get().httpErrorMessage());\n            }\n         }\n      }\n   }\n\n   @Override\n   public GoogleComputeEngineTemplateOptions templateOptions() {\n      return GoogleComputeEngineTemplateOptions.class.cast(super.templateOptions());\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/compute/GoogleComputeEngineServiceAdapter.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.compute;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.common.collect.Iterables.contains;\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.transform;\nimport static java.lang.String.format;\nimport static org.jclouds.googlecloud.internal.ListPages.concat;\nimport static org.jclouds.googlecomputeengine.compute.domain.internal.RegionAndName.fromRegionAndName;\nimport static org.jclouds.googlecomputeengine.compute.strategy.CreateNodesWithGroupEncodedIntoNameThenAddToSet.nameFromNetworkString;\nimport static org.jclouds.googlecomputeengine.config.GoogleComputeEngineProperties.IMAGE_PROJECTS;\nimport static org.jclouds.location.predicates.LocationPredicates.isZone;\n\nimport java.net.URI;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\n\nimport org.jclouds.compute.ComputeServiceAdapter;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.googlecomputeengine.GoogleComputeEngineApi;\nimport org.jclouds.googlecomputeengine.compute.domain.internal.RegionAndName;\nimport org.jclouds.googlecomputeengine.compute.functions.Resources;\nimport org.jclouds.googlecomputeengine.compute.options.GoogleComputeEngineTemplateOptions;\nimport org.jclouds.googlecomputeengine.domain.AttachDisk;\nimport org.jclouds.googlecomputeengine.domain.DiskType;\nimport org.jclouds.googlecomputeengine.domain.Image;\nimport org.jclouds.googlecomputeengine.domain.Instance;\nimport org.jclouds.googlecomputeengine.domain.Instance.NetworkInterface.AccessConfig;\nimport org.jclouds.googlecomputeengine.domain.Instance.Scheduling;\nimport org.jclouds.googlecomputeengine.domain.Instance.Scheduling.OnHostMaintenance;\nimport org.jclouds.googlecomputeengine.domain.MachineType;\nimport org.jclouds.googlecomputeengine.domain.NewInstance;\nimport org.jclouds.googlecomputeengine.domain.NewInstance.NetworkInterface;\nimport org.jclouds.googlecomputeengine.domain.Operation;\nimport org.jclouds.googlecomputeengine.domain.Region;\nimport org.jclouds.googlecomputeengine.domain.Subnetwork;\nimport org.jclouds.googlecomputeengine.domain.Tags;\nimport org.jclouds.googlecomputeengine.domain.Zone;\nimport org.jclouds.googlecomputeengine.features.InstanceApi;\nimport org.jclouds.location.suppliers.all.JustProvider;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Splitter;\nimport com.google.common.base.Strings;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Lists;\nimport com.google.common.util.concurrent.Atomics;\nimport com.google.common.util.concurrent.UncheckedTimeoutException;\n\n/**\n * This implementation maps the following:\n * <ul>\n *    <li>{@linkplain NodeMetadata#getId()} to {@link Instance#selfLink()}</li>\n *    <li>{@linkplain NodeMetadata#getGroup()} to {@link Instance#metadata()} as {@code jclouds-group}</li>\n *    <li>{@linkplain NodeMetadata#getImageId()} to {@link Instance#metadata()} as {@code jclouds-image}</li>\n *    <li>{@linkplain Hardware#getId()} to {@link MachineType#selfLink()}</li>\n *    <li>{@linkplain org.jclouds.compute.domain.Image#getId()} to {@link Image#selfLink()}</li>\n *    <li>{@linkplain Location#getId()} to {@link org.jclouds.googlecomputeengine.domain.Zone#name()}</li>\n *    <li>{@linkplain Location#getDescription()} to {@link Zone#selfLink()}</li>\n * </ul>\n */\npublic final class GoogleComputeEngineServiceAdapter\n      implements ComputeServiceAdapter<Instance, MachineType, Image, Location> {\n\n   private final JustProvider justProvider;\n   private final GoogleComputeEngineApi api;\n   private final Resources resources;\n   private final Predicate<AtomicReference<Operation>> operationDone;\n   private final Predicate<AtomicReference<Instance>> instanceVisible;\n   private final Function<Map<String, ?>, String> windowsPasswordGenerator;\n   private final List<String> imageProjects;\n   private final LoadingCache<URI, Optional<Image>> diskURIToImage;\n   private final LoadingCache<RegionAndName, Optional<Subnetwork>> subnetworksMap;\n\n   @Inject\n   GoogleComputeEngineServiceAdapter(JustProvider justProvider, GoogleComputeEngineApi api,\n         Predicate<AtomicReference<Operation>> operationDone, Predicate<AtomicReference<Instance>> instanceVisible,\n         Function<Map<String, ?>, String> windowsPasswordGenerator, Resources resources,\n         @Named(IMAGE_PROJECTS) String imageProjects, LoadingCache<URI, Optional<Image>> diskURIToImage,\n         LoadingCache<RegionAndName, Optional<Subnetwork>> subnetworksMap) {\n      this.justProvider = justProvider;\n      this.api = api;\n      this.operationDone = operationDone;\n      this.instanceVisible = instanceVisible;\n      this.windowsPasswordGenerator = windowsPasswordGenerator;\n      this.resources = resources;\n      this.imageProjects = Splitter.on(',').omitEmptyStrings().splitToList(imageProjects);\n      this.diskURIToImage = diskURIToImage;\n      this.subnetworksMap = subnetworksMap;\n   }\n\n   @Override public NodeAndInitialCredentials<Instance> createNodeWithGroupEncodedIntoName(String group, String name,\n         Template template) {\n      GoogleComputeEngineTemplateOptions options = GoogleComputeEngineTemplateOptions.class.cast(template.getOptions());\n\n      checkNotNull(options.getNetworks(), \"template options must specify a network or subnetwork\");\n      checkNotNull(template.getHardware().getUri(), \"hardware must have a URI\");\n      checkNotNull(template.getImage().getUri(), \"image URI is null\");\n\n      String zone = template.getLocation().getId();\n\n      List<AttachDisk> disks = Lists.newArrayList();\n      disks.add(AttachDisk.newBootDisk(template.getImage().getUri(), getDiskTypeArgument(options, zone)));\n\n      URI network = URI.create(options.getNetworks().iterator().next());\n      URI subnetwork = null;\n      \n      if (isSubnetwork(network)) {\n         String region = template.getLocation().getParent().getId();\n         RegionAndName subnetRef = fromRegionAndName(region, nameFromNetworkString(network.toString()));\n         // This must be present, since the subnet is validated and its URI\n         // obtained in the CreateNodesWithGroupEncodedIntoNameThenAddToSet\n         // strategy\n         Optional<Subnetwork> subnet = subnetworksMap.getUnchecked(subnetRef);\n         network = subnet.get().network();\n         subnetwork = subnet.get().selfLink();\n      }\n\n      Scheduling scheduling = getScheduling(options);\n\n      List<NetworkInterface> networks = Lists.newArrayList();\n      if (options.assignExternalIp()) {\n         networks.add(NetworkInterface.create(network, subnetwork));\n      } else {\n         // Do not assign an externally facing IP address to the machine.\n         networks.add(NetworkInterface.create(network, subnetwork, ImmutableList.<AccessConfig>of()));\n      }\n\n      NewInstance.Builder newInstanceBuilder = new NewInstance.Builder(name,\n            template.getHardware().getUri(), // machineType\n            networks,\n            disks)\n            .description(group)\n            .tags(Tags.create(null, ImmutableList.copyOf(options.getTags())))\n            .serviceAccounts(options.serviceAccounts())\n            .scheduling(scheduling);\n\n      NewInstance newInstance = newInstanceBuilder.build();\n\n      // Add metadata from template and for ssh key and image id\n      newInstance.metadata().putAll(options.getUserMetadata());\n\n      LoginCredentials credentials = resolveNodeCredentials(template);\n      if (options.getPublicKey() != null) {\n         newInstance.metadata().put(\"sshKeys\",\n               format(\"%s:%s %s@localhost\", credentials.getUser(), options.getPublicKey(), credentials.getUser()));\n      }\n\n      InstanceApi instanceApi = api.instancesInZone(zone);\n      Operation create = instanceApi.create(newInstance);\n\n      // We need to see the created instance so that we can access the newly created disk.\n      AtomicReference<Instance> instance = Atomics.newReference(Instance.create( //\n            \"0000000000000000000\", // id can't be null, but isn't available until provisioning is done.\n            null, // creationTimestamp\n            create.targetLink(), // selfLink\n            newInstance.name(), // name\n            newInstance.description(), // description\n            newInstance.tags(), // tags\n            newInstance.machineType(), // machineType\n            Instance.Status.PROVISIONING, // status\n            null, // statusMessage\n            create.zone(), // zone\n            null, // canIpForward\n            null, // networkInterfaces\n            null, // disks\n            newInstance.metadata(), // metadata\n            newInstance.serviceAccounts(), // serviceAccounts\n            scheduling) // scheduling\n      );\n      checkState(instanceVisible.apply(instance), \"instance %s is not api visible!\", instance.get());\n\n      // Add lookup for InstanceToNodeMetadata\n      diskURIToImage.getUnchecked(instance.get().disks().get(0).source());\n\n      if ((options.autoCreateWindowsPassword() != null && options.autoCreateWindowsPassword())\n                  || OsFamily.WINDOWS == template.getImage().getOperatingSystem().getFamily()) {\n           Map<String, ?> params = ImmutableMap.of(\"instance\", instance, \"zone\", zone, \"email\", create.user(), \"userName\", credentials.getUser());\n           String password = windowsPasswordGenerator.apply(params);\n           credentials = LoginCredentials.builder(credentials)\n                          .password(password)\n                          .build();\n         }\n      return new NodeAndInitialCredentials<Instance>(instance.get(), instance.get().selfLink().toString(), credentials);\n   }\n\n   @Override public Iterable<MachineType> listHardwareProfiles() {\n      // JCLOUDS-1463: Only return the machine types that belong to zones that are actually available\n      final Iterable<String> zones = transform(filter(listLocations(), isZone()), new Function<Location, String>() {\n         public String apply(Location input) {\n            return input.getId();\n         }\n      });\n\n      return filter(concat(api.aggregatedList().machineTypes()), new Predicate<MachineType>() {\n         @Override\n         public boolean apply(MachineType input) {\n            return input.deprecated() == null && contains(zones, input.zone());\n         }\n      });\n   }\n\n   @Override public Iterable<Image> listImages() {\n      List<Iterable<Image>> images = Lists.newArrayList();\n\n      images.add(concat(api.images().list()));\n\n      for (String project : imageProjects) {\n         images.add(concat(api.images().listInProject(project)));\n      }\n\n      return Iterables.concat(images);\n   }\n\n   @Override public Image getImage(String selfLink) {\n      return api.images().get(URI.create(checkNotNull(selfLink, \"id\")));\n   }\n\n   /**  Unlike EC2, you cannot default GCE instances to a region. Hence, we constrain to zones. */\n   @Override public Iterable<Location> listLocations() {\n      Location provider = justProvider.get().iterator().next();\n      ImmutableList.Builder<Location> zones = ImmutableList.builder();\n      for (Region region : concat(api.regions().list())) {\n         Location regionLocation = new LocationBuilder()\n               .scope(LocationScope.REGION)\n               .id(region.name())\n               .description(region.selfLink().toString())\n               .parent(provider).build();\n         for (URI zoneSelfLink : region.zones()) {\n            String zoneName = toName(zoneSelfLink);\n            zones.add(new LocationBuilder()\n                  .scope(LocationScope.ZONE)\n                  .id(zoneName)\n                  .description(zoneSelfLink.toString())\n                  .parent(regionLocation).build());\n         }\n      }\n      return zones.build();\n   }\n\n   @Override public Instance getNode(String selfLink) {\n      return resources.instance(URI.create(checkNotNull(selfLink, \"id\")));\n   }\n\n   @Override public Iterable<Instance> listNodes() {\n      return concat(api.aggregatedList().instances());\n   }\n\n   @Override public Iterable<Instance> listNodesByIds(final Iterable<String> selfLinks) {\n      return filter(listNodes(), new Predicate<Instance>() { // TODO: convert to server-side filter\n         @Override public boolean apply(Instance instance) {\n            return Iterables.contains(selfLinks, instance.selfLink().toString());\n         }\n      });\n   }\n\n   @Override public void destroyNode(String selfLink) {\n      waitOperationDone(resources.delete(URI.create(checkNotNull(selfLink, \"id\"))));\n   }\n\n   @Override public void rebootNode(String selfLink) {\n      waitOperationDone(resources.resetInstance(URI.create(checkNotNull(selfLink, \"id\"))));\n   }\n\n   @Override public void resumeNode(String selfLink) {\n      waitOperationDone(resources.startInstance(URI.create(checkNotNull(selfLink, \"id\"))));\n   }\n\n   @Override public void suspendNode(String selfLink) {\n      waitOperationDone(resources.stopInstance(URI.create(checkNotNull(selfLink, \"id\"))));\n   }\n\n   private void waitOperationDone(Operation operation) {\n      AtomicReference<Operation> operationRef = Atomics.newReference(operation);\n\n      // wait for the operation to complete\n      if (!operationDone.apply(operationRef)) {\n         throw new UncheckedTimeoutException(\"operation did not reach DONE state\" + operationRef.get());\n      }\n\n      // check if the operation failed\n      if (operationRef.get().httpErrorStatusCode() != null) {\n         throw new IllegalStateException(\n               \"operation failed. Http Error Code: \" + operationRef.get().httpErrorStatusCode() +\n                     \" HttpError: \" + operationRef.get().httpErrorMessage());\n      }\n   }\n\n   private LoginCredentials resolveNodeCredentials(Template template) {\n      TemplateOptions options = template.getOptions();\n      LoginCredentials.Builder credentials = LoginCredentials.builder(template.getImage().getDefaultCredentials());\n      if (!Strings.isNullOrEmpty(options.getLoginUser())) {\n         credentials.user(options.getLoginUser());\n      }\n      if (!Strings.isNullOrEmpty(options.getLoginPrivateKey())) {\n         credentials.privateKey(options.getLoginPrivateKey());\n      }\n      if (!Strings.isNullOrEmpty(options.getLoginPassword())) {\n         credentials.password(options.getLoginPassword());\n      }\n      if (options.shouldAuthenticateSudo() != null) {\n         credentials.authenticateSudo(options.shouldAuthenticateSudo());\n      }\n      return credentials.build();\n   }\n\n   private static String toName(URI link) {\n      String path = link.getPath();\n      return path.substring(path.lastIndexOf('/') + 1);\n   }\n\n   private URI getDiskTypeArgument(GoogleComputeEngineTemplateOptions options, String zone) {\n      if (options.bootDiskType() != null) {\n         DiskType diskType = api.diskTypesInZone(zone).get(options.bootDiskType());\n         if (diskType != null) {\n            return diskType.selfLink();\n         }\n      }\n\n      return null;\n   }\n\n   public Scheduling getScheduling(GoogleComputeEngineTemplateOptions options) {\n      OnHostMaintenance onHostMaintenance = OnHostMaintenance.MIGRATE;\n      boolean automaticRestart = true;\n\n      // Preemptible instances cannot use a MIGRATE maintenance strategy or automatic restarts\n      if (options.preemptible()) {\n         onHostMaintenance = OnHostMaintenance.TERMINATE;\n         automaticRestart = false;\n      }\n\n      return Scheduling.create(onHostMaintenance, automaticRestart, options.preemptible());\n   }\n   \n   private static boolean isSubnetwork(URI uri) {\n      return uri.toString().contains(\"/subnetworks/\");\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/compute/config/GoogleComputeEngineServiceContextModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.compute.config;\n\nimport static com.google.common.base.Suppliers.memoizeWithExpiration;\nimport static java.util.concurrent.TimeUnit.MILLISECONDS;\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL;\nimport static org.jclouds.googlecomputeengine.config.GoogleComputeEngineProperties.OPERATION_COMPLETE_INTERVAL;\nimport static org.jclouds.googlecomputeengine.config.GoogleComputeEngineProperties.OPERATION_COMPLETE_TIMEOUT;\nimport static org.jclouds.rest.config.BinderUtils.bindHttpApi;\nimport static org.jclouds.util.Predicates2.retry;\n\nimport java.net.URI;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.ComputeService;\nimport org.jclouds.compute.ComputeServiceAdapter;\nimport org.jclouds.compute.config.ComputeServiceAdapterContextModule;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.googlecomputeengine.compute.GoogleComputeEngineService;\nimport org.jclouds.googlecomputeengine.compute.GoogleComputeEngineServiceAdapter;\nimport org.jclouds.googlecomputeengine.compute.functions.FirewallTagNamingConvention;\nimport org.jclouds.googlecomputeengine.compute.functions.GoogleComputeEngineImageToImage;\nimport org.jclouds.googlecomputeengine.compute.functions.ImageNameToOperatingSystem;\nimport org.jclouds.googlecomputeengine.compute.functions.InstanceToNodeMetadata;\nimport org.jclouds.googlecomputeengine.compute.functions.MachineTypeToHardware;\nimport org.jclouds.googlecomputeengine.compute.functions.OrphanedGroupsFromDeadNodes;\nimport org.jclouds.googlecomputeengine.compute.functions.Resources;\nimport org.jclouds.googlecomputeengine.compute.functions.ResetWindowsPassword;\nimport org.jclouds.googlecomputeengine.compute.loaders.DiskURIToImage;\nimport org.jclouds.googlecomputeengine.compute.loaders.SubnetworkLoader;\nimport org.jclouds.googlecomputeengine.compute.options.GoogleComputeEngineTemplateOptions;\nimport org.jclouds.googlecomputeengine.compute.predicates.AtomicInstanceVisible;\nimport org.jclouds.googlecomputeengine.compute.predicates.AtomicOperationDone;\nimport org.jclouds.googlecomputeengine.compute.predicates.GroupIsEmpty;\nimport org.jclouds.googlecomputeengine.compute.strategy.CreateNodesWithGroupEncodedIntoNameThenAddToSet;\nimport org.jclouds.googlecomputeengine.domain.Image;\nimport org.jclouds.googlecomputeengine.domain.Instance;\nimport org.jclouds.googlecomputeengine.domain.MachineType;\nimport org.jclouds.googlecomputeengine.domain.Operation;\nimport org.jclouds.googlecomputeengine.domain.Subnetwork;\nimport org.jclouds.location.suppliers.ImplicitLocationSupplier;\nimport org.jclouds.location.suppliers.implicit.FirstZone;\n\nimport com.google.common.base.Optional;\nimport com.google.common.base.Function;\nimport com.google.common.base.Functions;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.inject.Injector;\nimport com.google.inject.Provides;\nimport com.google.inject.Scopes;\nimport com.google.inject.TypeLiteral;\nimport org.jclouds.compute.domain.internal.TemplateBuilderImpl;\nimport org.jclouds.compute.functions.NodeAndTemplateOptionsToStatement;\nimport org.jclouds.compute.functions.NodeAndTemplateOptionsToStatementWithoutPublicKey;\nimport org.jclouds.googlecomputeengine.compute.domain.internal.GoogleComputeEngineArbitraryCpuRamTemplateBuilderImpl;\nimport org.jclouds.googlecomputeengine.compute.domain.internal.RegionAndName;\n\npublic final class GoogleComputeEngineServiceContextModule\n      extends ComputeServiceAdapterContextModule<Instance, MachineType, Image, Location> {\n\n   @Override\n   protected void configure() {\n      super.configure();\n\n      bind(ComputeService.class).to(GoogleComputeEngineService.class);\n\n      bind(new TypeLiteral<ComputeServiceAdapter<Instance, MachineType, Image, Location>>() {\n      }).to(GoogleComputeEngineServiceAdapter.class);\n\n      bind(TemplateBuilderImpl.class).to(GoogleComputeEngineArbitraryCpuRamTemplateBuilderImpl.class);\n\n      // Use compute service to supply locations, which are always zones.\n      install(new LocationsFromComputeServiceAdapterModule<Instance, MachineType, Image, Location>() {\n      });\n      bind(new TypeLiteral<Function<Location, Location>>() {\n      }).toInstance(Functions.<Location>identity());\n      bind(ImplicitLocationSupplier.class).to(FirstZone.class);\n\n      bind(new TypeLiteral<Function<Instance, NodeMetadata>>() {\n      }).to(InstanceToNodeMetadata.class);\n\n      bind(new TypeLiteral<Function<MachineType, Hardware>>() {\n      }).to(MachineTypeToHardware.class);\n\n      bind(new TypeLiteral<Function<Image, org.jclouds.compute.domain.Image>>() {\n      }).to(GoogleComputeEngineImageToImage.class);\n\n      bind(org.jclouds.compute.strategy.impl.CreateNodesWithGroupEncodedIntoNameThenAddToSet.class)\n            .to(CreateNodesWithGroupEncodedIntoNameThenAddToSet.class);\n\n      bind(TemplateOptions.class).to(GoogleComputeEngineTemplateOptions.class);\n      bind(NodeAndTemplateOptionsToStatement.class).to(NodeAndTemplateOptionsToStatementWithoutPublicKey.class);\n\n      bind(new TypeLiteral<Function<Set<? extends NodeMetadata>, Set<String>>>() {\n      }).to(OrphanedGroupsFromDeadNodes.class);\n\n      bind(new TypeLiteral<Predicate<String>>() {\n      }).to(GroupIsEmpty.class);\n      \n      bind(new TypeLiteral<Function<String, OperatingSystem>>() {\n      }).to(ImageNameToOperatingSystem.class);\n\n      bind(new TypeLiteral<Function<Map<String, ?>, String>>() {\n      }).to(ResetWindowsPassword.class);\n\n      bind(FirewallTagNamingConvention.Factory.class).in(Scopes.SINGLETON);\n\n      bind(new TypeLiteral<CacheLoader<URI, Optional<Image>>>() {\n      }).to(DiskURIToImage.class);\n      \n      bind(new TypeLiteral<CacheLoader<RegionAndName, Optional<Subnetwork>>>() {\n      }).to(SubnetworkLoader.class);\n\n      bindHttpApi(binder(), Resources.class);\n   }\n\n   // TODO: these timeouts need thinking through.\n   @Provides Predicate<AtomicReference<Operation>> operationDone(AtomicOperationDone input,\n         @Named(OPERATION_COMPLETE_TIMEOUT) long timeout, @Named(OPERATION_COMPLETE_INTERVAL) long interval) {\n      return retry(input, timeout, interval, MILLISECONDS);\n   }\n\n   @Provides Predicate<AtomicReference<Instance>> instanceVisible(AtomicInstanceVisible input,\n         @Named(OPERATION_COMPLETE_TIMEOUT) long timeout, @Named(OPERATION_COMPLETE_INTERVAL) long interval) {\n      return retry(input, timeout, interval, MILLISECONDS);\n   }\n\n   @Provides @Singleton @Memoized Supplier<Map<URI, Hardware>> hardwareByUri(\n         @Memoized final Supplier<Set<? extends Hardware>> hardwareSupplier,\n         @Named(PROPERTY_SESSION_INTERVAL) long seconds) {\n      return memoizeWithExpiration(new Supplier<Map<URI, Hardware>>() {\n         @Override public Map<URI, Hardware> get() {\n            ImmutableMap.Builder<URI, Hardware> result = ImmutableMap.builder();\n            for (Hardware hardware : hardwareSupplier.get()) {\n               result.put(hardware.getUri(), hardware);\n            }\n            return result.build();\n         }\n      }, seconds, SECONDS);\n   }\n\n   @Provides @Singleton @Memoized Supplier<Map<URI, Location>> locationsByUri(\n         @Memoized final Supplier<Set<? extends Location>> locations, @Named(PROPERTY_SESSION_INTERVAL) long seconds) {\n      return memoizeWithExpiration(new Supplier<Map<URI, Location>>() {\n         @Override\n         public Map<URI, Location> get() {\n            ImmutableMap.Builder<URI, Location> result = ImmutableMap.builder();\n            for (Location location : locations.get()) {\n               result.put(URI.create(location.getDescription()), location);\n            }\n            return result.build();\n         }\n      }, seconds, SECONDS);\n   }\n   \n   @Override\n   protected Map<OsFamily, LoginCredentials> osFamilyToCredentials(Injector injector) {\n      // GCE does not enable the 'root' account for ssh access by default, but it will create a privileged\n      // user when the SSH key is provided. Populate the map to use 'jclouds' as a default user.\n      ImmutableMap.Builder<OsFamily, LoginCredentials> builder = ImmutableMap.builder();\n      for (OsFamily family : OsFamily.values()) {\n         switch (family) {\n            case COREOS:\n               builder.put(family, LoginCredentials.builder().user(\"core\").build());\n               break;\n            case WINDOWS:\n               builder.put(family, LoginCredentials.builder().user(\"Administrator\").build());\n               break;\n            default:\n               builder.put(family, LoginCredentials.builder().user(\"jclouds\").build());\n               break;\n         }\n      }\n      return builder.build();\n   }\n\n   @Provides\n   @Singleton\n   protected LoadingCache<URI, Optional<Image>> diskURIToImageMap(CacheLoader<URI, Optional<Image>> in) {\n      return CacheBuilder.newBuilder().build(in);\n   }\n\n   @Provides\n   @Singleton\n   protected LoadingCache<RegionAndName, Optional<Subnetwork>> subnetworksMap(\n         CacheLoader<RegionAndName, Optional<Subnetwork>> in) {\n      return CacheBuilder.newBuilder().build(in);\n   }\n\n   private static final Map<Instance.Status, NodeMetadata.Status> toPortableNodeStatus =\n         ImmutableMap.<Instance.Status, NodeMetadata.Status>builder()\n                     .put(Instance.Status.PROVISIONING, NodeMetadata.Status.PENDING)\n                     .put(Instance.Status.STAGING, NodeMetadata.Status.PENDING)\n                     .put(Instance.Status.RUNNING, NodeMetadata.Status.RUNNING)\n                     .put(Instance.Status.STOPPING, NodeMetadata.Status.PENDING)\n                     .put(Instance.Status.STOPPED, NodeMetadata.Status.SUSPENDED)\n                     .put(Instance.Status.TERMINATED, NodeMetadata.Status.SUSPENDED).build();\n\n   @Provides Map<Instance.Status, NodeMetadata.Status> toPortableNodeStatus() {\n      return toPortableNodeStatus;\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/compute/domain/internal/GoogleComputeEngineArbitraryCpuRamTemplateBuilderImpl.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.compute.domain.internal;\n\nimport com.google.common.base.Optional;\nimport com.google.common.base.Supplier;\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.HardwareBuilder;\nimport org.jclouds.compute.domain.Processor;\nimport org.jclouds.compute.domain.TemplateBuilder;\nimport org.jclouds.compute.domain.internal.ArbitraryCpuRamTemplateBuilderImpl;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.domain.Location;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Provider;\nimport java.net.URI;\nimport java.util.Set;\n\npublic class GoogleComputeEngineArbitraryCpuRamTemplateBuilderImpl extends ArbitraryCpuRamTemplateBuilderImpl {\n   @Inject\n   protected GoogleComputeEngineArbitraryCpuRamTemplateBuilderImpl(@Memoized Supplier<Set<? extends Location>> locations,\n         @Memoized Supplier<Set<? extends org.jclouds.compute.domain.Image>> images,\n         @Memoized Supplier<Set<? extends Hardware>> hardwares, Supplier<Location> defaultLocation,\n         @Named(\"DEFAULT\") Provider<TemplateOptions> optionsProvider,\n         @Named(\"DEFAULT\") Provider<TemplateBuilder> defaultTemplateProvider) {\n      super(locations, images, hardwares, defaultLocation, optionsProvider, defaultTemplateProvider);\n   }\n\n   @Override\n   protected Hardware automaticHardware(double cores, int ram, Optional<Float> disk) {\n      if (location == null) {\n         location = defaultLocation.get();\n      }\n      String uri = location.getDescription() + \"/machineTypes/custom-\" + (int)cores + \"-\" + ram;\n      return new HardwareBuilder()\n            .id(uri)\n            .ram(ram)\n            .processor(new Processor((int)cores, 1.0))\n            .providerId(uri)\n            .uri(URI.create(uri))\n            .build();\n   }\n\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/compute/domain/internal/RegionAndName.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.compute.domain.internal;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.Iterables;\n\n/**\n * Helpful when looking for resources by region and name\n */\n@AutoValue\npublic abstract class RegionAndName {\n\n   public abstract String regionId();\n   public abstract String name();\n   \n   RegionAndName() {\n      \n   }\n   \n   public static RegionAndName fromSlashEncoded(String name) {\n      Iterable<String> parts = Splitter.on('/').split(checkNotNull(name, \"name\"));\n      checkArgument(Iterables.size(parts) == 2, \"name must be in format regionId/name\");\n      return fromRegionAndName(Iterables.get(parts, 0), Iterables.get(parts, 1));\n   }\n\n   public static RegionAndName fromRegionAndName(String regionId, String name) {\n      return new AutoValue_RegionAndName(regionId, name);\n   }\n   \n   public String slashEncode() {\n      return regionId() + \"/\" + name();\n   }\n\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/compute/functions/FirewallTagNamingConvention.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.compute.functions;\n\nimport java.util.List;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.compute.functions.GroupNamingConvention;\n\n/**\n * The convention for naming instance tags that firewall rules recognise.\n */\npublic final class FirewallTagNamingConvention {\n\n   public static final class Factory {\n\n      private final GroupNamingConvention.Factory namingConvention;\n\n      @Inject Factory(GroupNamingConvention.Factory namingConvention) {\n         this.namingConvention = namingConvention;\n      }\n\n      public FirewallTagNamingConvention get(String groupName) {\n         return new FirewallTagNamingConvention(namingConvention.create().sharedNameForGroup(groupName));\n      }\n   }\n\n   private final String sharedResourceName;\n\n   public FirewallTagNamingConvention(String sharedResourceName) {\n      this.sharedResourceName = sharedResourceName;\n   }\n\n   public String name(List<String> ports) {\n      final int prime = 31;\n      int result = 1;\n      for (String s : ports){\n         result = result * prime + s.hashCode();\n         // TODO(broudy): this may break between java versions! Consider a different implementation.\n      }\n\n      return String.format(\"%s-%s\", sharedResourceName, Integer.toHexString(result));\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/compute/functions/GoogleComputeEngineImageToImage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.compute.functions;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.compute.domain.Image.Status;\nimport org.jclouds.compute.domain.ImageBuilder;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.googlecomputeengine.domain.Deprecated.State;\nimport org.jclouds.googlecomputeengine.domain.Image;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableMap;\n\npublic final class GoogleComputeEngineImageToImage implements Function<Image, org.jclouds.compute.domain.Image> {\n   private final Function<String, OperatingSystem> nameToOperatingSystem;\n   \n   @Inject GoogleComputeEngineImageToImage(Function<String, OperatingSystem> nameToOperatingSystem) {\n      this.nameToOperatingSystem = nameToOperatingSystem;\n   }\n\n   @Override public org.jclouds.compute.domain.Image apply(Image image) {\n      ImageBuilder builder = new ImageBuilder()\n              .id(image.selfLink().toString())\n              .providerId(image.id())\n              .name(image.name())\n              .providerId(image.id())\n              .description(image.description())\n              .status(Status.AVAILABLE)\n              .uri(image.selfLink());\n\n      if (image.deprecated() != null) {\n         builder.userMetadata(ImmutableMap.of(\"deprecatedState\", image.deprecated().state().name()));\n         if (image.deprecated().state() == State.DELETED){\n            builder.status(Status.DELETED);\n         }\n      }\n\n      builder.version(image.name().substring(image.name().lastIndexOf('-') + 1));\n      builder.operatingSystem(nameToOperatingSystem.apply(image.name()));\n      \n      return builder.build();\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/compute/functions/ImageNameToOperatingSystem.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.compute.functions;\n\nimport static com.google.common.base.Joiner.on;\nimport static com.google.common.collect.Iterables.limit;\nimport static com.google.common.collect.Iterables.skip;\n\nimport java.util.List;\n\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.OsFamily;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.Lists;\n\npublic class ImageNameToOperatingSystem implements Function<String, OperatingSystem> {\n\n   @Override public OperatingSystem apply(String input) {\n      // Remove the backport prefix before parsing the name\n      String name = input.contains(\"backports\") ? input.substring(input.indexOf(\"backports-\") + 10) : input;\n      \n      OperatingSystem.Builder builder = defaultOperatingSystem(name);\n      List<String> splits = Lists.newArrayList(name.split(\"-\"));\n      if (splits == null || splits.size() == 0 || splits.size() < 3) {\n         return builder.build();\n      }\n\n      // GCE namings that don't match the OsFamily enum\n      String os = splits.get(0);\n      if (\"opensuse\".equals(os) || \"sles\".equals(os)) {\n         builder.family(OsFamily.SUSE);\n      } else {\n         OsFamily family = OsFamily.fromValue(os);\n         if (family != OsFamily.UNRECOGNIZED) {\n            builder.family(family);\n         }\n      }\n\n      // TODO: Improve the version parsing so it is more portable\n      String version = on(\".\").join(limit(skip(splits, 1), splits.size() - 2));\n      builder.version(version);\n\n      return builder.build();\n   }\n   \n   private OperatingSystem.Builder defaultOperatingSystem(String name) {\n      return OperatingSystem.builder().family(OsFamily.LINUX).is64Bit(true).description(name);\n   }\n\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/compute/functions/InstanceToNodeMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.compute.functions;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Splitter;\nimport com.google.common.base.Supplier;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableList;\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.HardwareBuilder;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadata.Status;\nimport org.jclouds.compute.domain.NodeMetadataBuilder;\nimport org.jclouds.compute.domain.Processor;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.domain.Location;\nimport org.jclouds.googlecomputeengine.domain.Image;\nimport org.jclouds.googlecomputeengine.domain.Instance;\n\nimport jakarta.inject.Inject;\nimport java.net.URI;\nimport java.util.List;\nimport java.util.Map;\n\nimport static org.jclouds.compute.util.ComputeServiceUtils.groupFromMapOrName;\n\npublic final class InstanceToNodeMetadata implements Function<Instance, NodeMetadata> {\n\n   private final Map<Instance.Status, NodeMetadata.Status> toPortableNodeStatus;\n   private final GroupNamingConvention nodeNamingConvention;\n   private final LoadingCache<URI, Optional<Image>> diskURIToImage;\n   private final Supplier<Map<URI, Hardware>> hardwares;\n   private final Supplier<Map<URI, Location>> locationsByUri;\n\n   @Inject InstanceToNodeMetadata(Map<Instance.Status, NodeMetadata.Status> toPortableNodeStatus,\n                                  GroupNamingConvention.Factory namingConvention,\n                                  LoadingCache<URI, Optional<Image>> diskURIToImage,\n                                  @Memoized Supplier<Map<URI, Hardware>> hardwares,\n                                  @Memoized Supplier<Map<URI, Location>> locationsByUri) {\n      this.toPortableNodeStatus = toPortableNodeStatus;\n      this.nodeNamingConvention = namingConvention.createWithoutPrefix();\n      this.diskURIToImage = diskURIToImage;\n      this.hardwares = hardwares;\n      this.locationsByUri = locationsByUri;\n   }\n\n   @Override public NodeMetadata apply(Instance input) {\n      String group = groupFromMapOrName(input.metadata().asMap(), input.name(), nodeNamingConvention);\n      NodeMetadataBuilder builder = new NodeMetadataBuilder();\n\n      Location zone = locationsByUri.get().get(input.zone());\n      if (zone == null) {\n         throw new IllegalStateException(\n               String.format(\"zone %s not present in %s\", input.zone(), locationsByUri.get().keySet()));\n      }\n\n      // The boot disk is the first disk. It may have been created from an image, so look it up.\n      //\n      // Note: This will be present if we created the node. In the future we could choose to make diskToSourceImage\n      // a loading cache. That would be more expensive, but could ensure this isn't null.\n\n      URI diskSource = input.disks().get(0).source();\n      Optional<Image> image = diskURIToImage.getUnchecked(diskSource);\n\n      Hardware hardware;\n      if (isCustomMachineTypeURI(input.machineType())) {\n         hardware = machineTypeURIToCustomHardware(input.machineType());\n      }\n      else {\n         hardware = hardwares.get().get(input.machineType());\n      }\n\n      builder.id(input.selfLink().toString())\n             .name(input.name())\n             .providerId(input.id())\n             .hostname(input.name())\n             .location(zone)\n             .imageId(image.isPresent() ? image.get().selfLink().toString() : null)\n             .hardware(hardware)\n             .status(input.status() != null ? toPortableNodeStatus.get(input.status()) : Status.UNRECOGNIZED)\n             .tags(input.tags().items())\n             .uri(input.selfLink())\n             .userMetadata(input.metadata().asMap())\n             .group(group)\n             .privateAddresses(collectPrivateAddresses(input))\n             .publicAddresses(collectPublicAddresses(input));\n      return builder.build();\n   }\n\n   private List<String> collectPrivateAddresses(Instance input) {\n      ImmutableList.Builder<String> privateAddressesBuilder = ImmutableList.builder();\n      for (Instance.NetworkInterface networkInterface : input.networkInterfaces()) {\n         if (networkInterface.networkIP() != null) {\n            privateAddressesBuilder.add(networkInterface.networkIP());\n         }\n      }\n      return privateAddressesBuilder.build();\n   }\n\n   private List<String> collectPublicAddresses(Instance input) {\n      ImmutableList.Builder<String> publicAddressesBuilder = ImmutableList.builder();\n      for (Instance.NetworkInterface networkInterface : input.networkInterfaces()) {\n         for (Instance.NetworkInterface.AccessConfig accessConfig : networkInterface.accessConfigs()) {\n            if (accessConfig.natIP() != null) {\n               publicAddressesBuilder.add(accessConfig.natIP());\n            }\n         }\n      }\n      return publicAddressesBuilder.build();\n   }\n\n   public static boolean isCustomMachineTypeURI(URI machineType) {\n      return machineType.toString().contains(\"machineTypes/custom\");\n   }\n\n   public static Hardware machineTypeURIToCustomHardware(URI machineType) {\n      String uri = machineType.toString();\n      String values = uri.substring(uri.lastIndexOf('/') + 8);\n      List<String> hardwareValues = Splitter.on('-')\n            .trimResults()\n            .splitToList(values);\n      return new HardwareBuilder()\n            .id(uri)\n            .providerId(uri)\n            .processor(new Processor(Double.parseDouble(hardwareValues.get(0)), 1.0))\n            .ram(Integer.parseInt(hardwareValues.get(1)))\n            .uri(machineType)\n            .build();\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/compute/functions/MachineTypeToHardware.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.compute.functions;\n\nimport java.net.URI;\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.HardwareBuilder;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.Processor;\nimport org.jclouds.compute.domain.Volume;\nimport org.jclouds.compute.domain.VolumeBuilder;\nimport org.jclouds.domain.Location;\nimport org.jclouds.googlecomputeengine.domain.MachineType;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicates;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableSet;\n\npublic final class MachineTypeToHardware implements Function<MachineType, Hardware> {\n\n   private final Supplier<Map<URI, Location>> locationsByUri;\n\n   @Inject MachineTypeToHardware(@Memoized Supplier<Map<URI, Location>> locationsByUri) {\n      this.locationsByUri = locationsByUri;\n   }\n\n   @Override\n   public Hardware apply(MachineType input) {\n      URI zoneLink = URI.create(\n            input.selfLink().toString().replace(\"/machineTypes/\" + input.name(), \"\"));\n\n      Location zone = locationsByUri.get().get(zoneLink);\n      if (zone == null) {\n         throw new IllegalStateException(\n               String.format(\"zone %s not present in %s\", zoneLink, locationsByUri.get().keySet()));\n      }\n      return new HardwareBuilder()\n              .id(input.selfLink().toString())\n              .providerId(input.id())\n              .location(zone)\n              .name(input.name())\n              .hypervisor(\"kvm\")\n              .processor(new Processor(input.guestCpus(), 1.0))\n              .providerId(input.id())\n              .ram(input.memoryMb())\n              .uri(input.selfLink())\n              .volumes(collectVolumes(input))\n              .supportsImage(Predicates.<Image>alwaysTrue())\n              .build();\n   }\n\n   private Iterable<Volume> collectVolumes(MachineType input) {\n      ImmutableSet.Builder<Volume> volumes = ImmutableSet.builder();\n      for (MachineType.ScratchDisk disk : input.scratchDisks()) {\n         volumes.add(new VolumeBuilder()\n                 .type(Volume.Type.LOCAL)\n                 .size(Float.valueOf(disk.diskGb()))\n                 .bootDevice(true)\n                 .durable(false).build());\n      }\n      return volumes.build();\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/compute/functions/OrphanedGroupsFromDeadNodes.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.compute.functions;\n\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.compute.domain.NodeMetadata;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Sets;\n\npublic final class OrphanedGroupsFromDeadNodes implements Function<Set<? extends NodeMetadata>, Set<String>> {\n\n   private final Predicate<String> isOrphanedGroupPredicate;\n\n   @Inject OrphanedGroupsFromDeadNodes(Predicate<String> isOrphanedGroupPredicate) {\n      this.isOrphanedGroupPredicate = isOrphanedGroupPredicate;\n   }\n\n\n   @Override public Set<String> apply(Set<? extends NodeMetadata> deadNodes) {\n      Set<String> groups = Sets.newLinkedHashSet();\n      for (NodeMetadata deadNode : deadNodes) {\n         groups.add(deadNode.getGroup());\n      }\n      Set<String> orphanedGroups = Sets.newLinkedHashSet();\n      for (String group : groups) {\n         if (isOrphanedGroupPredicate.apply(group)) {\n            orphanedGroups.add(group);\n         }\n      }\n      return orphanedGroups;\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/compute/functions/ResetWindowsPassword.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.compute.functions;\n\nimport static com.google.common.base.Predicates.notNull;\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.transform;\nimport static com.google.common.collect.Iterables.tryFind;\n\nimport java.math.BigInteger;\nimport java.nio.charset.Charset;\nimport java.security.InvalidKeyException;\nimport java.security.KeyFactory;\nimport java.security.KeyPair;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.spec.InvalidKeySpecException;\nimport java.security.spec.RSAPublicKeySpec;\nimport java.text.SimpleDateFormat;\nimport java.util.Arrays;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.TimeZone;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport jakarta.annotation.Resource;\nimport javax.crypto.BadPaddingException;\nimport javax.crypto.Cipher;\nimport javax.crypto.IllegalBlockSizeException;\nimport javax.crypto.NoSuchPaddingException;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\n\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.crypto.Crypto;\nimport org.jclouds.googlecomputeengine.GoogleComputeEngineApi;\nimport org.jclouds.googlecomputeengine.domain.Instance;\nimport org.jclouds.googlecomputeengine.domain.Instance.SerialPortOutput;\nimport org.jclouds.googlecomputeengine.domain.Metadata;\nimport org.jclouds.googlecomputeengine.domain.Operation;\nimport org.jclouds.googlecomputeengine.features.InstanceApi;\nimport org.jclouds.json.Json;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.util.Predicates2;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Splitter;\nimport com.google.common.base.Throwables;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.io.BaseEncoding;\nimport com.google.common.util.concurrent.Atomics;\nimport com.google.gson.GsonBuilder;\nimport com.google.inject.TypeLiteral;\n\n/**\n * References:\n * <ul>\n *   <li><a href=\"https://cloud.google.com/compute/docs/instances/automate-pw-generation\">automate-pw-generation</a>\n *   <li><a href=\"https://github.com/GoogleCloudPlatform/compute-image-windows/blob/master/examples/windows_auth_java_sample.java\">windows_auth_java_sample.java</a>\n * </ul>\n * \n * In brief, the sequence is:\n * <ol>\n *   <li>Generate a temporary key for encrypting and decrypting the password\n *   <li>Send the RSA public key to the instance, by settings its metadata\n *   <li>Retrieve the result from the {@link SerialPortOutput}\n *   <li>Decode and decrypt the result.\n * </ol>\n */\npublic class ResetWindowsPassword implements Function<Map<String, ?>, String> {\n\n   /**\n    * Indicates when the key should expire. Keys are one-time use, so the metadata doesn't need to stay around for long.\n    * 10 minutes chosen to allow for differences between time on the client\n    * and time on the server.\n    */\n   private static final long EXPIRE_DURATION = 10 * 60 * 1000;\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   private final GoogleComputeEngineApi api;\n   private final Crypto crypto;\n   private final Predicate<AtomicReference<Operation>> operationDone;\n   private final Json json;\n\n   @Inject\n   protected ResetWindowsPassword(GoogleComputeEngineApi api, Crypto crypto,\n         Predicate<AtomicReference<Operation>> operationDone, Json json) {\n      this.api = api;\n      this.crypto = crypto;\n      this.operationDone = operationDone;\n      this.json = json;\n   }\n\n   @Override\n   public String apply(Map<String, ?> params) {\n      String zone = (String)params.get(\"zone\");\n      final AtomicReference<Instance> instance = (AtomicReference<Instance>)params.get(\"instance\");\n      String userName = (String)params.get(\"userName\");\n      String email = (String)params.get(\"email\");\n\n       // Generate the public/private key pair for encryption and decryption.\n       // TODO do we need to explicitly set 2048 bits? Presumably \"RSA\" is implicit\n       KeyPair keys = crypto.rsaKeyPairGenerator().genKeyPair();\n\n       // Update instance's metadata with new \"windows-keys\" entry, and wait for operation to\n       // complete.\n       logger.debug(\"Generating windows key for instance %s, by updating metadata\", instance.get().name());\n       final InstanceApi instanceApi = api.instancesInZone(zone);\n       Metadata metadata = instance.get().metadata();\n\n      try {\n         // If disableHtmlEscaping is not there, == will be escaped from modulus value\n         metadata.put(\"windows-keys\", new GsonBuilder().disableHtmlEscaping().create().toJson(extractKeyMetadata(keys, userName, email)));\n      } catch (NoSuchAlgorithmException e) {\n         Throwables.propagate(e);\n      } catch (InvalidKeySpecException e) {\n         Throwables.propagate(e);\n      }\n\n       AtomicReference<Operation> operation = Atomics.newReference(instanceApi.setMetadata(instance.get().name(), metadata));\n       operationDone.apply(operation);\n\n       if (operation.get().httpErrorStatusCode() != null) {\n          logger.warn(\"Generating windows key for %s failed. Http Error Code: %d HttpError: %s\",\n                operation.get().targetId(), operation.get().httpErrorStatusCode(),\n                operation.get().httpErrorMessage());\n       }\n\n      try {\n         final AtomicReference<String> encryptedPassword = Atomics.newReference();\n         boolean passwordRetrieved = Predicates2.retry(new Predicate<Instance>() {\n            public boolean apply(Instance instance) {\n               String serialPortContents = instanceApi.getSerialPortOutput(instance.name(), 4).contents();\n               List<String> contentEntries = Splitter.on('\\n').splitToList(serialPortContents);\n\n               Optional<String> retrievedPassword = tryFind(\n                     filter(transform(contentEntries, deserializeSerialOutput(json)), notNull()), HasEncryptedPassword)\n                     .transform(ExtractEncryptedPassword);\n\n               if (retrievedPassword.isPresent()) {\n                  encryptedPassword.set(retrievedPassword.get());\n               }\n\n               return retrievedPassword.isPresent();\n            }\n            // Notice that timeoutDuration should be less than EXPIRE_DURATION\n         }, 10 * 60, 30, TimeUnit.SECONDS).apply(instance.get());\n\n         if (passwordRetrieved) {\n            return decryptPassword(encryptedPassword.get(), keys);\n         } else {\n            throw new IllegalStateException(\"Did not find the encrypted password in the serial port output\");\n         }\n      } catch (Exception e) {\n         throw Throwables.propagate(e);\n      }\n   }\n\n   private static Function<String, Map<String, Object>> deserializeSerialOutput(final Json json) {\n      return new Function<String, Map<String, Object>>() {\n         @Override\n         public Map<String, Object> apply(String input) {\n            try {\n               return json.fromJson(input, new TypeLiteral<Map<String, Object>>() {\n               }.getType());\n            } catch (Exception ex) {\n               return null;\n            }\n         }\n      };\n   }\n\n   private static final Predicate<Map<String, Object>> HasEncryptedPassword = new Predicate<Map<String, Object>>() {\n      @Override\n      public boolean apply(Map<String, Object> input) {\n         return input.containsKey(\"encryptedPassword\");\n      }\n   };\n\n   private static final Function<Map<String, Object>, String> ExtractEncryptedPassword = new Function<Map<String, Object>, String>() {\n      @Override\n      public String apply(Map<String, Object> input) {\n         return (String) input.get(\"encryptedPassword\");\n      }\n   };\n\n   /**\n    * Decrypts the given password - the encrypted text is base64-encoded.\n    * As per the GCE docs, assumes it was encrypted with algorithm \"RSA/NONE/OAEPPadding\", and UTF-8.\n    */\n   protected String decryptPassword(String message, KeyPair keys) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException {\n      Cipher cipher;\n      try {\n         // Assumes user has configured appropriate crypto guice module.\n         cipher = crypto.cipher(\"RSA/NONE/OAEPPadding\");\n      } catch (NoSuchAlgorithmException e) {\n         throw new RuntimeException(\"Problem finding cypher. Try adding bouncycastle dependency.\", e);\n      } catch (NoSuchPaddingException e) {\n         throw new RuntimeException(\"Problem finding cypher. Try adding bouncycastle dependency.\", e);\n      }\n\n      // Add the private key for decryption.\n      cipher.init(Cipher.DECRYPT_MODE, keys.getPrivate());\n\n      // Decrypt the text.\n      byte[] rawMessage = BaseEncoding.base64().decode(message);\n      byte[] decryptedText = cipher.doFinal(rawMessage);\n\n      // The password was encoded using UTF8. Transform into string.\n      return new String(decryptedText, Charset.forName(\"UTF-8\"));\n   }\n\n   /**\n    * Generates the metadata value for this keypair.\n    * Extracts the public key's the RSA spec's modulus and exponent, encoded as Base-64, and\n    * an expires date.\n    *\n    * @param pair\n    * @return\n    * @throws NoSuchAlgorithmException\n    * @throws InvalidKeySpecException\n    */\n   protected Map<String, String> extractKeyMetadata(KeyPair pair, String userName, String email) throws NoSuchAlgorithmException, InvalidKeySpecException {\n      KeyFactory factory = crypto.rsaKeyFactory();\n      RSAPublicKeySpec pubSpec = factory.getKeySpec(pair.getPublic(), RSAPublicKeySpec.class);\n      BigInteger modulus = pubSpec.getModulus();\n      BigInteger exponent = pubSpec.getPublicExponent();\n\n      // Strip out the leading 0 byte in the modulus.\n      byte[] modulusArr = Arrays.copyOfRange(modulus.toByteArray(), 1, modulus.toByteArray().length);\n      String modulusString = BaseEncoding.base64().encode(modulusArr).replaceAll(\"\\n\", \"\");\n      String exponentString = BaseEncoding.base64().encode(exponent.toByteArray()).replaceAll(\"\\n\", \"\");\n\n      // Create the expire date, formatted as rfc3339\n      Date expireDate = new Date(System.currentTimeMillis() + EXPIRE_DURATION);\n      SimpleDateFormat rfc3339Format = new SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ss'Z'\");\n      rfc3339Format.setTimeZone(TimeZone.getTimeZone(\"UTC\"));\n      String expireString = rfc3339Format.format(expireDate);\n\n      return ImmutableMap.<String, String>builder()\n              .put(\"modulus\", modulusString)\n              .put(\"exponent\", exponentString)\n              .put(\"expireOn\", expireString)\n              .put(\"userName\", userName)\n              .put(\"email\", email) // email of the user should be here. Now it is the username.\n              .build();\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/compute/functions/Resources.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.compute.functions;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport java.net.URI;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.googlecomputeengine.domain.Disk;\nimport org.jclouds.googlecomputeengine.domain.Image;\nimport org.jclouds.googlecomputeengine.domain.Instance;\nimport org.jclouds.googlecomputeengine.domain.Network;\nimport org.jclouds.googlecomputeengine.domain.Operation;\nimport org.jclouds.googlecomputeengine.domain.Subnetwork;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.EndpointParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SkipEncoding;\n\n@SkipEncoding({'/', '='})\n@RequestFilters(OAuthFilter.class)\n@Consumes(APPLICATION_JSON)\npublic interface Resources {\n\n   /** Returns an instance by self-link or null if not found. */\n   @Named(\"Instances:get\")\n   @GET\n   @Fallback(NullOnNotFoundOr404.class) @Nullable Instance instance(@EndpointParam URI selfLink);\n\n   /** Returns an network by self-link or null if not found. */\n   @Named(\"Networks:get\")\n   @GET\n   @Fallback(NullOnNotFoundOr404.class) @Nullable Network network(@EndpointParam URI selfLink);\n\n   /** Returns an operation by self-link or null if not found. */\n   @Named(\"Operations:get\")\n   @GET\n   @Fallback(NullOnNotFoundOr404.class) @Nullable Operation operation(@EndpointParam URI selfLink);\n\n   /** Deletes any resource by self-link and returns the operation in progress, or null if not found. */\n   @Named(\"Resources:delete\")\n   @DELETE\n   @Fallback(NullOnNotFoundOr404.class) @Nullable Operation delete(@EndpointParam URI selfLink);\n\n   /** Hard-resets the instance by self-link and returns the operation in progress */\n   @Named(\"Instances:reset\")\n   @POST\n   @Path(\"/reset\")\n   Operation resetInstance(@EndpointParam URI selfLink);\n   \n   /** Starts the instance by self-link and returns the operation in progress */\n   @Named(\"Instances:start\")\n   @POST\n   @Path(\"/start\")\n   Operation startInstance(@EndpointParam URI selfLink);\n   \n   /** Stops the instance by self-link and returns the operation in progress */\n   @Named(\"Instances:stop\")\n   @POST\n   @Path(\"/stop\")\n   Operation stopInstance(@EndpointParam URI selfLink);\n\n   @Named(\"Subnetworks:get\")\n   @GET\n   @Fallback(NullOnNotFoundOr404.class) @Nullable Subnetwork subnetwork(@EndpointParam URI selfLink);\n\n   /** Returns a disk by self-link or null if not found. */\n   @Named(\"Disks:get\")\n   @GET\n   @Fallback(NullOnNotFoundOr404.class) @Nullable Disk disk(@EndpointParam URI selfLink);\n\n   /** Returns an image by self-link or null if not found. */\n   @Named(\"Images:get\")\n   @GET\n   @Fallback(NullOnNotFoundOr404.class) @Nullable Image image(@EndpointParam URI selfLink);\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/compute/loaders/DiskURIToImage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.compute.loaders;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\nimport java.net.URI;\nimport java.util.concurrent.ExecutionException;\n\nimport com.google.common.base.Optional;\nimport com.google.common.cache.CacheLoader;\nimport org.jclouds.googlecomputeengine.compute.functions.Resources;\nimport org.jclouds.googlecomputeengine.domain.Disk;\nimport org.jclouds.googlecomputeengine.domain.Image;\nimport org.jclouds.logging.Logger;\n\n\n@Singleton\npublic class DiskURIToImage extends CacheLoader<URI, Optional<Image>> {\n   @Resource\n   protected Logger logger = Logger.NULL;\n\n   private final Resources resources;\n\n   @Inject\n   DiskURIToImage(Resources resources) {\n      this.resources = resources;\n   }\n\n   @Override\n   public Optional<Image> load(URI key) throws ExecutionException {\n      try {\n         Image image = null;\n         Disk disk = resources.disk(key);\n         if (disk != null && disk.sourceImage() != null) {\n            image = resources.image(disk.sourceImage());\n         }\n         return Optional.fromNullable(image);\n      } catch (Exception e) {\n         throw new ExecutionException(message(key, e), e);\n      }\n   }\n\n   public static String message(URI key, Exception e) {\n      return String.format(\"could not find image for disk %s: %s\", key.toString(), e.getMessage());\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/compute/loaders/SubnetworkLoader.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.compute.loaders;\n\nimport java.util.concurrent.ExecutionException;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.googlecomputeengine.GoogleComputeEngineApi;\nimport org.jclouds.googlecomputeengine.compute.domain.internal.RegionAndName;\nimport org.jclouds.googlecomputeengine.domain.Subnetwork;\n\nimport com.google.common.base.Optional;\nimport com.google.common.cache.CacheLoader;\n\n@Singleton\npublic class SubnetworkLoader extends CacheLoader<RegionAndName, Optional<Subnetwork>> {\n\n   private final GoogleComputeEngineApi api;\n\n   @Inject\n   SubnetworkLoader(GoogleComputeEngineApi api) {\n      this.api = api;\n   }\n\n   @Override\n   public Optional<Subnetwork> load(RegionAndName key) throws ExecutionException {\n      try {\n         return Optional.fromNullable(api.subnetworksInRegion(key.regionId()).get(key.name()));\n      } catch (Exception ex) {\n         throw new ExecutionException(message(key, ex), ex);\n      }\n   }\n\n   public static String message(RegionAndName key, Exception ex) {\n      return String.format(\"could not find subnet %s in region %s: %s\", key.name(), key.regionId(), ex.getMessage());\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/compute/options/GoogleComputeEngineTemplateOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.compute.options;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.googlecomputeengine.domain.Instance.ServiceAccount;\nimport org.jclouds.scriptbuilder.domain.Statement;\n\n\n/** Instance options specific to Google Compute Engine. */\npublic final class GoogleComputeEngineTemplateOptions extends TemplateOptions {\n\n   private boolean assignExternalIp = true;\n   private boolean autoCreateKeyPair = true;\n   private boolean autoCreateWindowsPassword;\n   private List<ServiceAccount> serviceAccounts;\n   private String bootDiskType;\n   private boolean preemptible = false;\n\n   @Override\n   public GoogleComputeEngineTemplateOptions clone() {\n      GoogleComputeEngineTemplateOptions options = new GoogleComputeEngineTemplateOptions();\n      copyTo(options);\n      return options;\n   }\n\n   @Override\n   public void copyTo(TemplateOptions to) {\n      super.copyTo(to);\n      if (to instanceof GoogleComputeEngineTemplateOptions) {\n         GoogleComputeEngineTemplateOptions eTo = GoogleComputeEngineTemplateOptions.class.cast(to);\n         eTo.assignExternalIp(assignExternalIp());\n         eTo.autoCreateKeyPair(autoCreateKeyPair());\n         eTo.serviceAccounts(serviceAccounts());\n         eTo.autoCreateWindowsPassword(autoCreateWindowsPassword());\n         eTo.bootDiskType(bootDiskType());\n         eTo.preemptible(preemptible());\n      }\n   }\n\n   /**\n    * Sets the boot disk type.\n    */\n   public GoogleComputeEngineTemplateOptions bootDiskType(String diskType) {\n      this.bootDiskType = diskType;\n      return this;\n   }\n\n   /**\n    * Gets the boot disk type.\n    */\n   public String bootDiskType() {\n      return bootDiskType;\n   }\n\n   /**\n    * Sets whether an external IP address should be assigned to the machine.\n    */\n   public GoogleComputeEngineTemplateOptions assignExternalIp(boolean assignExternalIp) {\n      this.assignExternalIp = assignExternalIp;\n      return this;\n   }\n\n   /**\n    * Gets whether an external IP address should be assigned to the machine.\n    */\n   public boolean assignExternalIp() {\n      return assignExternalIp;\n   }\n\n   /**\n    * Sets whether an SSH key pair should be created automatically.\n    */\n   public GoogleComputeEngineTemplateOptions autoCreateKeyPair(boolean autoCreateKeyPair) {\n      this.autoCreateKeyPair = autoCreateKeyPair;\n      return this;\n   }\n\n   /**\n    * Gets whether an SSH key pair should be created automatically.\n    */\n   public boolean autoCreateKeyPair() {\n      return autoCreateKeyPair;\n   }\n\n   /**\n    * Sets a list of service accounts, with their specified scopes, to authorize on created instance.\n    * For example, to give a node the 'compute' scope you would add a service account with the email 'default'\n    * and the scope 'https://www.googleapis.com/auth/compute'\n    * These scopes will be given to all nodes created with these template options.\n    */\n   public GoogleComputeEngineTemplateOptions serviceAccounts(List<ServiceAccount> serviceAccounts){\n      this.serviceAccounts = serviceAccounts;\n      return this;\n   }\n\n   /**\n    * Sets whether the resulting instance should be preemptible.\n    */\n   public GoogleComputeEngineTemplateOptions preemptible(boolean preemptible) {\n      this.preemptible = preemptible;\n      return this;\n   }\n\n   /**\n    * Gets whether the resulting instance should be preemptible.\n    */\n   public boolean preemptible() {\n      return preemptible;\n   }\n\n   /**\n    * Whether a Windows password should be created automatically; {@link null} means to generate\n    * the password if and only if the image is for a Windows VM.\n    */\n   public Boolean autoCreateWindowsPassword() {\n      return autoCreateWindowsPassword;\n   }\n   \n   /**\n    * Sets whether to auto-create a windows password. The default ({@code null}) is to always\n    * do so for Windows VMs, inferring this from the image. An explicit value of true or false\n    * overrides this.\n    */\n   public GoogleComputeEngineTemplateOptions autoCreateWindowsPassword(Boolean autoCreateWindowsPassword) {\n      this.autoCreateWindowsPassword = autoCreateWindowsPassword;\n      return this;\n   }\n\n   /**\n    * Gets the list of service accounts, with their specified scopes, that will be authorize on created instances.\n    */\n   public List<ServiceAccount> serviceAccounts(){\n      return serviceAccounts;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public GoogleComputeEngineTemplateOptions blockOnPort(int port, int seconds) {\n      return GoogleComputeEngineTemplateOptions.class.cast(super.blockOnPort(port, seconds));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public GoogleComputeEngineTemplateOptions inboundPorts(int... ports) {\n      return GoogleComputeEngineTemplateOptions.class.cast(super.inboundPorts(ports));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public GoogleComputeEngineTemplateOptions authorizePublicKey(String publicKey) {\n      return GoogleComputeEngineTemplateOptions.class.cast(super.authorizePublicKey(publicKey));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public GoogleComputeEngineTemplateOptions installPrivateKey(String privateKey) {\n      return GoogleComputeEngineTemplateOptions.class.cast(super.installPrivateKey(privateKey));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public GoogleComputeEngineTemplateOptions blockUntilRunning(boolean blockUntilRunning) {\n      return GoogleComputeEngineTemplateOptions.class.cast(super.blockUntilRunning(blockUntilRunning));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public GoogleComputeEngineTemplateOptions dontAuthorizePublicKey() {\n      return GoogleComputeEngineTemplateOptions.class.cast(super.dontAuthorizePublicKey());\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public GoogleComputeEngineTemplateOptions nameTask(String name) {\n      return GoogleComputeEngineTemplateOptions.class.cast(super.nameTask(name));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public GoogleComputeEngineTemplateOptions runAsRoot(boolean runAsRoot) {\n      return GoogleComputeEngineTemplateOptions.class.cast(super.runAsRoot(runAsRoot));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public GoogleComputeEngineTemplateOptions runScript(Statement script) {\n      return GoogleComputeEngineTemplateOptions.class.cast(super.runScript(script));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public GoogleComputeEngineTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials) {\n      return GoogleComputeEngineTemplateOptions.class.cast(super.overrideLoginCredentials(overridingCredentials));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public GoogleComputeEngineTemplateOptions overrideLoginPassword(String password) {\n      return GoogleComputeEngineTemplateOptions.class.cast(super.overrideLoginPassword(password));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public GoogleComputeEngineTemplateOptions overrideLoginPrivateKey(String privateKey) {\n      return GoogleComputeEngineTemplateOptions.class.cast(super.overrideLoginPrivateKey(privateKey));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public GoogleComputeEngineTemplateOptions overrideLoginUser(String loginUser) {\n      return GoogleComputeEngineTemplateOptions.class.cast(super.overrideLoginUser(loginUser));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public GoogleComputeEngineTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo) {\n      return GoogleComputeEngineTemplateOptions.class.cast(super.overrideAuthenticateSudo(authenticateSudo));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public GoogleComputeEngineTemplateOptions userMetadata(Map<String, String> userMetadata) {\n      return GoogleComputeEngineTemplateOptions.class.cast(super.userMetadata(userMetadata));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public GoogleComputeEngineTemplateOptions userMetadata(String key, String value) {\n      return GoogleComputeEngineTemplateOptions.class.cast(super.userMetadata(key, value));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public GoogleComputeEngineTemplateOptions nodeNames(Iterable<String> nodeNames) {\n      return GoogleComputeEngineTemplateOptions.class.cast(super.nodeNames(nodeNames));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public GoogleComputeEngineTemplateOptions networks(Iterable<String> networks) {\n      return GoogleComputeEngineTemplateOptions.class.cast(super.networks(networks));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public GoogleComputeEngineTemplateOptions networks(String... networks) {\n      return GoogleComputeEngineTemplateOptions.class.cast(super.networks(networks));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public GoogleComputeEngineTemplateOptions tags(Iterable<String> tags) {\n      return GoogleComputeEngineTemplateOptions.class.cast(super.tags(tags));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public GoogleComputeEngineTemplateOptions wrapInInitScript(boolean wrapInInitScript) {\n      return GoogleComputeEngineTemplateOptions.class.cast(super.wrapInInitScript(wrapInInitScript));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public GoogleComputeEngineTemplateOptions runScript(String script) {\n      return GoogleComputeEngineTemplateOptions.class.cast(super.runScript(script));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public GoogleComputeEngineTemplateOptions blockOnComplete(boolean blockOnComplete) {\n      return GoogleComputeEngineTemplateOptions.class.cast(super.blockOnComplete(blockOnComplete));\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/compute/predicates/AtomicInstanceVisible.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.compute.predicates;\n\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.googlecomputeengine.compute.functions.Resources;\nimport org.jclouds.googlecomputeengine.domain.Instance;\n\nimport com.google.common.base.Predicate;\n\npublic final class AtomicInstanceVisible implements Predicate<AtomicReference<Instance>> {\n\n   private final Resources resources;\n\n   @Inject AtomicInstanceVisible(Resources resources) {\n      this.resources = resources;\n   }\n\n   @Override public boolean apply(AtomicReference<Instance> input) {\n      Instance response = resources.instance(input.get().selfLink());\n      if (response == null) {\n         return false;\n      }\n      input.set(response);\n      return true;\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/compute/predicates/AtomicOperationDone.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.compute.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\n\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.googlecomputeengine.compute.functions.Resources;\nimport org.jclouds.googlecomputeengine.domain.Operation;\n\nimport com.google.common.base.Predicate;\n\npublic final class AtomicOperationDone implements Predicate<AtomicReference<Operation>> {\n\n   private final Resources resources;\n\n   @Inject AtomicOperationDone(Resources resources) {\n      this.resources = resources;\n   }\n\n   @Override public boolean apply(AtomicReference<Operation> input) {\n      checkNotNull(input.get(), \"operation\");\n      Operation current = resources.operation(input.get().selfLink());\n      input.set(current);\n      checkState(current.error().errors().isEmpty(), \"Task ended in error %s\", current); // ISE will break the loop.\n      switch (current.status()) {\n         case DONE:\n            return true;\n         case PENDING:\n         case RUNNING:\n         default:\n            return false;\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/compute/predicates/GroupIsEmpty.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.compute.predicates;\n\nimport static com.google.common.collect.Iterables.isEmpty;\nimport static com.google.common.collect.Sets.filter;\nimport static org.jclouds.compute.predicates.NodePredicates.all;\nimport static org.jclouds.compute.predicates.NodePredicates.inGroup;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.compute.ComputeService;\n\nimport com.google.common.base.Predicate;\n\npublic final class GroupIsEmpty implements Predicate<String> {\n\n   private final ComputeService computeService;\n\n   @Inject GroupIsEmpty(ComputeService computeService) {\n      this.computeService = computeService;\n   }\n\n\n   @Override public boolean apply(String groupName) {\n      return isEmpty(filter(computeService.listNodesDetailsMatching(all()), inGroup(groupName)));\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/compute/strategy/CreateNodesWithGroupEncodedIntoNameThenAddToSet.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.compute.strategy;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.common.collect.ImmutableList.of;\nimport static org.jclouds.domain.LocationScope.ZONE;\nimport static org.jclouds.googlecomputeengine.compute.domain.internal.RegionAndName.fromRegionAndName;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\n\nimport org.jclouds.Constants;\nimport org.jclouds.compute.config.CustomizationResponse;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.compute.strategy.CreateNodeWithGroupEncodedIntoName;\nimport org.jclouds.compute.strategy.CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap;\nimport org.jclouds.compute.strategy.ListNodesStrategy;\nimport org.jclouds.domain.Location;\nimport org.jclouds.googlecomputeengine.GoogleComputeEngineApi;\nimport org.jclouds.googlecomputeengine.compute.domain.internal.RegionAndName;\nimport org.jclouds.googlecomputeengine.compute.functions.FirewallTagNamingConvention;\nimport org.jclouds.googlecomputeengine.compute.functions.Resources;\nimport org.jclouds.googlecomputeengine.compute.options.GoogleComputeEngineTemplateOptions;\nimport org.jclouds.googlecomputeengine.domain.Firewall;\nimport org.jclouds.googlecomputeengine.domain.Firewall.Rule;\nimport org.jclouds.googlecomputeengine.domain.Network;\nimport org.jclouds.googlecomputeengine.domain.Operation;\nimport org.jclouds.googlecomputeengine.domain.Subnetwork;\nimport org.jclouds.googlecomputeengine.features.FirewallApi;\nimport org.jclouds.googlecomputeengine.options.FirewallOptions;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.ssh.SshKeyPairGenerator;\n\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Strings;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Multimap;\nimport com.google.common.collect.Sets;\nimport com.google.common.util.concurrent.Atomics;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.ListeningExecutorService;\n\npublic final class CreateNodesWithGroupEncodedIntoNameThenAddToSet extends\n      org.jclouds.compute.strategy.impl.CreateNodesWithGroupEncodedIntoNameThenAddToSet {\n\n   public static final String EXTERIOR_RANGE = \"0.0.0.0/0\";\n   public static final String DEFAULT_INTERNAL_NETWORK_RANGE = \"10.0.0.0/8\";\n\n   public static final String DEFAULT_NETWORK_NAME = \"default\";\n\n   private final GoogleComputeEngineApi api;\n   private final Resources resources;\n   private final Predicate<AtomicReference<Operation>> operationDone;\n   private final FirewallTagNamingConvention.Factory firewallTagNamingConvention;\n   private final SshKeyPairGenerator keyGenerator;\n   private final LoadingCache<RegionAndName, Optional<Subnetwork>> subnetworksMap;\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   @Inject\n   CreateNodesWithGroupEncodedIntoNameThenAddToSet(\n         CreateNodeWithGroupEncodedIntoName addNodeWithGroupStrategy,\n         ListNodesStrategy listNodesStrategy,\n         GroupNamingConvention.Factory namingConvention,\n         @Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor,\n         CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap.Factory customizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapFactory,\n         GoogleComputeEngineApi api, Resources resources, Predicate<AtomicReference<Operation>> operationDone,\n         FirewallTagNamingConvention.Factory firewallTagNamingConvention, SshKeyPairGenerator keyGenerator,\n         LoadingCache<RegionAndName, Optional<Subnetwork>> subnetworksMap) {\n      super(addNodeWithGroupStrategy, listNodesStrategy, namingConvention, userExecutor,\n            customizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapFactory);\n      this.api = api;\n      this.resources = resources;\n      this.operationDone = operationDone;\n      this.firewallTagNamingConvention = firewallTagNamingConvention;\n      this.keyGenerator = keyGenerator;\n      this.subnetworksMap = subnetworksMap;\n   }\n\n   @Override\n   public Map<?, ListenableFuture<Void>> execute(String group, int count, Template template,\n         Set<NodeMetadata> goodNodes, Map<NodeMetadata, Exception> badNodes,\n         Multimap<NodeMetadata, CustomizationResponse> customizationResponses) {\n\n      GoogleComputeEngineTemplateOptions templateOptions = GoogleComputeEngineTemplateOptions.class\n            .cast(template.getOptions());\n      assert template.getOptions().equals(templateOptions) : \"options didn't clone properly\";\n\n      // Configure networking\n      configureNetworking(group, templateOptions, template.getLocation());\n      \n      templateOptions.userMetadata(ComputeServiceConstants.NODE_GROUP_KEY, group);\n\n      // Configure the default credentials, if needed\n      if (templateOptions.autoCreateKeyPair() && Strings.isNullOrEmpty(templateOptions.getPublicKey())) {\n         logger.debug(\">> creating default keypair...\");\n         Map<String, String> defaultKeys = keyGenerator.get();\n         templateOptions.authorizePublicKey(defaultKeys.get(\"public\"));\n         templateOptions.overrideLoginPrivateKey(defaultKeys.get(\"private\"));\n      }\n\n      if (templateOptions.getRunScript() != null && templateOptions.getLoginPrivateKey() == null) {\n         logger.warn(\">> a runScript has been configured but no SSH key has been provided.\"\n               + \" Authentication will delegate to the ssh-agent\");\n      }\n\n      return super.execute(group, count, template, goodNodes, badNodes, customizationResponses);\n   }\n\n   /**\n    * Configure the networks taking into account that users may have configured\n    * a custom subnet or a legacy network.\n    */\n   private void configureNetworking(String group, GoogleComputeEngineTemplateOptions options, Location location) {\n      String networkName = null;\n      Network network = null;\n\n      if (options.getNetworks().isEmpty()) {\n         networkName = DEFAULT_NETWORK_NAME;\n      } else {\n         Iterator<String> iterator = options.getNetworks().iterator();\n         networkName = nameFromNetworkString(iterator.next());\n         checkArgument(!iterator.hasNext(),\n               \"Error: Please specify only one network/subnetwork in TemplateOptions when using GCE.\");\n      }\n\n      String region = ZONE == location.getScope() ? location.getParent().getId() : location.getId();\n      Optional<Subnetwork> subnet = subnetworksMap.getUnchecked(fromRegionAndName(region, networkName));\n      if (subnet.isPresent()) {\n         network = resources.network(subnet.get().network());\n         options.networks(ImmutableSet.of(subnet.get().selfLink().toString()));\n         logger.debug(\">> attaching nodes to subnet(%s) in region(%s)\", subnet.get().name(), region);\n      } else {\n         logger.warn(\">> subnet(%s) was not found in region(%s). Trying to find a matching legacy network...\",\n               networkName, region);\n         network = api.networks().get(networkName);\n         options.networks(ImmutableSet.of(network.selfLink().toString()));\n         logger.debug(\">> attaching nodes to legacy network(%s)\", network.name());\n      }\n\n      checkArgument(network != null, \"Error: no network with name %s was found\", networkName);\n\n      // Setup Firewall rules\n      getOrCreateFirewalls(options, network, subnet, firewallTagNamingConvention.get(group));\n   }\n\n   /**\n    * Ensures that a firewall exists for every inbound port that the instance\n    * requests.\n    * <p>\n    * For each port, there must be a firewall with a name following the\n    * {@link FirewallTagNamingConvention}, with a target tag also following the\n    * {@link FirewallTagNamingConvention}, which opens the requested port for\n    * all sources on both TCP and UDP protocols.\n    *\n    * @see org.jclouds.googlecomputeengine.features.FirewallApi#patch(String,\n    *      org.jclouds.googlecomputeengine.options.FirewallOptions)\n    */\n   private void getOrCreateFirewalls(GoogleComputeEngineTemplateOptions templateOptions, Network network,\n         Optional<Subnetwork> subnet, FirewallTagNamingConvention naming) {\n\n      Set<String> tags = Sets.newLinkedHashSet(templateOptions.getTags());\n\n      FirewallApi firewallApi = api.firewalls();\n\n      if (!templateOptions.getGroups().isEmpty()) {\n         for (String firewallName : templateOptions.getGroups()) {\n            Firewall firewall = firewallApi.get(firewallName);\n            validateFirewall(firewall, network);\n            if (!firewall.targetTags().isEmpty()) {\n               // Add tags coming from firewalls\n               tags.addAll(firewall.targetTags());\n            }\n         }\n      }\n\n      int[] inboundPorts = templateOptions.getInboundPorts();\n      \n      if (inboundPorts != null && inboundPorts.length > 0) {\n         List<String> ports = simplifyPorts(inboundPorts);\n         String name = naming.name(ports);\n         Firewall firewall = firewallApi.get(name);\n         AtomicReference<Operation> operation = null;\n\n         String interiorRange = subnet.isPresent() ? subnet.get().ipCidrRange() : DEFAULT_INTERNAL_NETWORK_RANGE;\n\n         if (firewall == null) {\n            List<Rule> rules = ImmutableList.of(Rule.create(\"tcp\", ports), Rule.create(\"udp\", ports));\n            FirewallOptions firewallOptions = new FirewallOptions().name(name).network(network.selfLink())\n                  .allowedRules(rules).sourceTags(templateOptions.getTags())\n                  .sourceRanges(of(interiorRange, EXTERIOR_RANGE)).targetTags(ImmutableList.of(name));\n\n            operation = Atomics.newReference(firewallApi.createInNetwork(firewallOptions.name(), network.selfLink(),\n                  firewallOptions));\n\n            operationDone.apply(operation);\n            checkState(operation.get().httpErrorStatusCode() == null, \"Could not insert firewall, operation failed %s\",\n                  operation);\n         }\n\n         tags.add(name);  // Add tags for the inbound ports firewall\n      }\n\n      templateOptions.tags(tags);\n   }\n\n   private void validateFirewall(Firewall firewall, Network network) {\n      if (firewall == null || !firewall.network().equals(network.selfLink())) {\n         throw new IllegalArgumentException(String.format(\"Can't find firewall %s in network %s.\", firewall.name(), network));\n      }\n   }\n\n   // Helper function for simplifying an array of ports to a list of ranges FirewallOptions expects.\n   public static List<String> simplifyPorts(int[] ports){\n      if ((ports == null) || (ports.length == 0)) {\n         return null;\n      }\n      ArrayList<String> output = new ArrayList<String>();\n      Arrays.sort(ports);\n\n      int range_start = ports[0];\n      int range_end = ports[0];\n      for (int i = 1; i < ports.length; i++) {\n         if ((ports[i - 1] == ports[i] - 1) || (ports[i - 1] == ports[i])){\n            // Range continues.\n            range_end = ports[i];\n         }\n         else {\n            // Range ends.\n            output.add(formatRange(range_start, range_end));\n            range_start = ports[i];\n            range_end = ports[i];\n         }\n      }\n      // Make sure we get the last range.\n      output.add(formatRange(range_start, range_end));\n      return output;\n   }\n\n   // Helper function for simplifyPorts. Formats port range strings.\n   private static String formatRange(int start, int finish){\n      if (start == finish){\n         return Integer.toString(start);\n      }\n      else {\n         return String.format(\"%s-%s\", Integer.toString(start), Integer.toString(finish));\n      }\n   }\n\n   // Helper function for getting the network name from the full URI.\n   public static String nameFromNetworkString(String networkString) {\n      return networkString.substring(networkString.lastIndexOf('/') + 1);\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/config/GoogleComputeEngineHttpApiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.config;\n\nimport static com.google.common.base.Suppliers.compose;\nimport static java.util.concurrent.TimeUnit.SECONDS;\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\nimport static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL;\nimport static org.jclouds.googlecloud.config.GoogleCloudProperties.PROJECT_NAME;\nimport static org.jclouds.rest.config.BinderUtils.bindHttpApi;\n\nimport java.net.URI;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\n\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.googlecloud.config.CurrentProject;\nimport org.jclouds.googlecomputeengine.GoogleComputeEngineApi;\nimport org.jclouds.googlecomputeengine.domain.Project;\nimport org.jclouds.googlecomputeengine.handlers.GoogleComputeEngineErrorHandler;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.annotation.ClientError;\nimport org.jclouds.http.annotation.Redirection;\nimport org.jclouds.http.annotation.ServerError;\nimport org.jclouds.location.Provider;\nimport org.jclouds.oauth.v2.config.OAuthScopes;\nimport org.jclouds.oauth.v2.config.OAuthScopes.ReadOrWriteScopes;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SkipEncoding;\nimport org.jclouds.rest.config.HttpApiModule;\nimport org.jclouds.rest.suppliers.MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Strings;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.inject.Provides;\n\n@ConfiguresHttpApi\npublic final class GoogleComputeEngineHttpApiModule extends HttpApiModule<GoogleComputeEngineApi> {\n\n   @Override protected void configure() {\n      super.configure();\n      bindHttpApi(binder(), UseApiToResolveProjectName.GetProject.class);\n      bind(OAuthScopes.class).toInstance(ReadOrWriteScopes.create( //\n            \"https://www.googleapis.com/auth/compute.readonly\", //\n            \"https://www.googleapis.com/auth/compute\" //\n      ));\n   }\n\n   @Override protected void bindErrorHandlers() {\n      bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(GoogleComputeEngineErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(GoogleComputeEngineErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(GoogleComputeEngineErrorHandler.class);\n   }\n\n   @Provides @Singleton @CurrentProject Supplier<URI> project(@Named(PROJECT_NAME) final String projectName,\n         @Provider Supplier<URI> defaultEndpoint, final UseApiToResolveProjectName useApiToResolveProjectName,\n         @Provider final Supplier<Credentials> creds, AtomicReference<AuthorizationException> authException,\n         @Named(PROPERTY_SESSION_INTERVAL) long seconds) {\n      // Try to avoid a runtime lookup by accepting a project name supplied in context overrides.\n      if (Strings.emptyToNull(projectName) != null) {\n         return Suppliers.memoizeWithExpiration(Suppliers.compose(new Function<URI, URI>() {\n            @Override public URI apply(URI input) {\n               return URI.create(String.format(\"%s/projects/%s\", input, projectName));\n            }\n         }, defaultEndpoint), seconds, SECONDS);\n      }\n\n      // If the project name wasn't explicitly supplied, then we lookup via api.\n      // This supplier must be defensive against any auth exception.\n      return MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier\n            .create(authException, compose(useApiToResolveProjectName, creds), seconds, SECONDS);\n   }\n\n   /**\n    * Parse the project ID from the identity, use it to lookup the project name, return the project-scoped uri.\n    *\n    * <h3>Why are we looking up the project name? We already have the project ID!</h3>\n    * <a href=\"https://cloud.google.com/compute/docs/overview#projectids\">Documentation</a> suggests that the\n    * project name is interchangeable with the project ID, which we already have. However, in practice, using the\n    * project ID leads to problems in POST requests.\n    *\n    * <p/> For example, inserting an instance using the project ID in the instances url, but the project name in\n    * the machineType url results in an error of\n    * <pre>{@code Cross-project references for this resource type are not allowed}.</pre>\n    *\n    * <p/>Similar errors occur in POST requests to other resources including at least forwardingRules, images,\n    * targetPools.\n    */\n   static final class UseApiToResolveProjectName implements Function<Credentials, URI> {\n\n      @SkipEncoding({ '/', '=' })\n      @RequestFilters(OAuthFilter.class)\n      @Consumes(APPLICATION_JSON)\n      interface GetProject {\n         @Named(\"Projects:get\")\n         @GET\n         @Path(\"/projects/{projectNumber}\") Project get(@PathParam(\"projectNumber\") String projectNumber);\n      }\n\n      private final GetProject api;\n      private final Supplier<URI> defaultEndpoint;\n\n      @Inject\n      UseApiToResolveProjectName(GetProject api, @Provider Supplier<URI> defaultEndpoint, ProviderMetadata metadata) {\n         this.api = api;\n         this.defaultEndpoint = defaultEndpoint;\n      }\n\n      @Override public URI apply(Credentials in) {\n         String projectNumber = CurrentProject.ClientEmail.toProjectNumber(in.identity);\n         return URI.create(defaultEndpoint.get() + \"/projects/\" + api.get(projectNumber).name());\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/config/GoogleComputeEngineParserModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.config;\n\nimport java.lang.reflect.Type;\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.googlecloud.config.ListPageAdapterFactory;\nimport org.jclouds.googlecomputeengine.domain.Firewall;\nimport org.jclouds.googlecomputeengine.domain.Firewall.Rule;\nimport org.jclouds.googlecomputeengine.options.FirewallOptions;\nimport org.jclouds.googlecomputeengine.options.RouteOptions;\nimport org.jclouds.json.config.GsonModule;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.gson.JsonArray;\nimport com.google.gson.JsonElement;\nimport com.google.gson.JsonObject;\nimport com.google.gson.JsonPrimitive;\nimport com.google.gson.JsonSerializationContext;\nimport com.google.gson.JsonSerializer;\nimport com.google.gson.TypeAdapterFactory;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Provides;\n\npublic final class GoogleComputeEngineParserModule extends AbstractModule {\n\n   @Override protected void configure() {\n      bind(GsonModule.DateAdapter.class).to(GsonModule.Iso8601DateAdapter.class);\n   }\n\n   @Provides @Singleton Map<Type, Object> typeAdapters() {\n      return new ImmutableMap.Builder<Type, Object>()\n            .put(FirewallOptions.class, new FirewallOptionsTypeAdapter())\n            .put(RouteOptions.class, new RouteOptionsTypeAdapter()).build();\n   }\n\n   // TODO: change jclouds core to use collaborative set bindings\n   @Provides @Singleton Set<TypeAdapterFactory> typeAdapterFactories() {\n      return ImmutableSet.<TypeAdapterFactory>of(new ListPageAdapterFactory());\n   }\n\n   private static final class FirewallOptionsTypeAdapter implements JsonSerializer<FirewallOptions> {\n\n      @Override public JsonElement serialize(FirewallOptions src, Type typeOfSrc, JsonSerializationContext context) {\n         JsonObject firewall = new JsonObject();\n         if (src.name() != null) {\n            firewall.addProperty(\"name\", src.name());\n         }\n         if (src.network() != null) {\n            firewall.addProperty(\"network\", src.network().toString());\n         }\n         if (!src.sourceRanges().isEmpty()) {\n            firewall.add(\"sourceRanges\", buildArrayOfStrings(src.sourceRanges()));\n         }\n         if (!src.sourceTags().isEmpty()) {\n            firewall.add(\"sourceTags\", buildArrayOfStrings(src.sourceTags()));\n         }\n         if (!src.targetTags().isEmpty()) {\n            firewall.add(\"targetTags\", buildArrayOfStrings(src.targetTags()));\n         }\n         if (!src.getAllowed().isEmpty()) {\n            JsonArray rules = new JsonArray();\n            for (Rule rule : src.getAllowed()) {\n               rules.add(context.serialize(rule, Firewall.Rule.class));\n            }\n            firewall.add(\"allowed\", rules);\n         }\n         return firewall;\n      }\n   }\n\n   private static final class RouteOptionsTypeAdapter implements JsonSerializer<RouteOptions> {\n\n      @Override public JsonElement serialize(RouteOptions src, Type typeOfSrc, JsonSerializationContext context) {\n         JsonObject route = new JsonObject();\n         if (src.name() != null) {\n            route.addProperty(\"name\", src.name());\n         }\n         if (src.getNetwork() != null) {\n            route.addProperty(\"network\", src.getNetwork().toString());\n         }\n         if (src.getNextHopGateway() != null) {\n            route.addProperty(\"nextHopGateway\", src.getNextHopGateway().toString());\n         }\n         if (src.getNextHopInstance() != null) {\n            route.addProperty(\"nextHopInstance\", src.getNextHopInstance().toString());\n         }\n         if (src.getNextHopNetwork() != null) {\n            route.addProperty(\"nextHopNetwork\", src.getNextHopNetwork().toString());\n         }\n         if (src.getDestRange() != null) {\n            route.addProperty(\"destRange\", src.getDestRange());\n         }\n         if (src.getDescription() != null) {\n            route.addProperty(\"description\", src.getDescription());\n         }\n         if (src.getPriority() != null) {\n            route.addProperty(\"priority\", src.getPriority());\n         }\n         if (src.getNextHopIp() != null) {\n            route.addProperty(\"nextHopIp\", src.getNextHopIp());\n         }\n         if (!src.getTags().isEmpty()) {\n            route.add(\"tags\", buildArrayOfStrings(src.getTags()));\n         }\n         return route;\n      }\n   }\n\n   private static JsonArray buildArrayOfStrings(Iterable<String> strings) {\n      JsonArray array = new JsonArray();\n      for (String string : strings) {\n         array.add(new JsonPrimitive(string));\n      }\n      return array;\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/config/GoogleComputeEngineProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.config;\n\nimport com.google.common.annotations.Beta;\n\n/**\n * Configuration properties keys used in {@link org.jclouds.ContextBuilder#overrides(java.util.Properties)}.\n * <p/> Note that these are in addition to properties defined in {@link org.jclouds.googlecloud.config.GoogleCloudProperties}.\n */\npublic final class GoogleComputeEngineProperties {\n\n   /** The total time, in msecs, to wait for an operation to complete. */\n   @Beta\n   public static final String OPERATION_COMPLETE_TIMEOUT = \"jclouds.google-compute-engine.operation-complete-timeout\";\n   /** The interval, in msecs, between calls to check whether an operation has completed. */\n   @Beta\n   public static final String OPERATION_COMPLETE_INTERVAL = \"jclouds.google-compute-engine.operation-complete-interval\";\n   /** The list of projects that will be scanned looking for images. */\n   @Beta\n   public static final String IMAGE_PROJECTS = \"jclouds.google-compute-engine.image-projects\";\n\n   private GoogleComputeEngineProperties() {\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/domain/Address.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.domain;\n\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class Address {\n\n   public enum Status{\n      RESERVED,\n      IN_USE;\n   }\n   public abstract String id();\n\n   public abstract URI selfLink();\n\n   public abstract String name();\n\n   public abstract Date creationTimestamp();\n\n   @Nullable public abstract String description();\n\n   /**\n    * The status of the address. Valid items are RESERVED and IN USE.\n    * A reserved address is currently available to the project and can be\n    * used by a resource. An in-use address is currently being used by a resource.\n    */\n   public abstract Status status();\n\n   /** URL of the resource currently using this address. */\n   @Nullable public abstract List<URI> users();\n\n   /** URL of the region where the address resides. */\n   public abstract URI region();\n\n   /** The IP address represented by this resource. */\n   public abstract String address();\n\n   @SerializedNames({ \"id\", \"selfLink\", \"name\", \"creationTimestamp\", \"description\", \"status\", \"users\", \"region\", \"address\" })\n   public static Address create(String id, URI selfLink, String name, Date creationTimestamp, String description, Status status, List<URI> users,\n         URI region, String address) {\n      return new AutoValue_Address(id, selfLink, name, creationTimestamp, description, status, users, region, address);\n   }\n\n   Address() {\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/domain/AttachDisk.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.domain;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class AttachDisk {\n   @AutoValue\n   public abstract static class InitializeParams {\n      /** Override the default naming convention. */\n      @Nullable public abstract String diskName();\n\n      /** Set to use a size larger than the {@link #sourceImage()}. You need to repartition when set. */\n      @Nullable public abstract Long diskSizeGb();\n\n      /** The {@link org.jclouds.googlecomputeengine.domain.Image#selfLink() source image}. */\n      @Nullable public abstract URI sourceImage();\n\n      @Nullable public abstract URI diskType();\n\n      static InitializeParams create(URI sourceImage) {\n         return create(null, null, sourceImage, null);\n      }\n\n      static InitializeParams create(URI sourceImage, URI diskType) {\n         return create(null, null, sourceImage, diskType);\n      }\n\n      @SerializedNames({ \"diskName\", \"diskSizeGb\", \"sourceImage\", \"diskType\" })\n      public static InitializeParams create(String diskName, Long diskSizeGb, URI sourceImage, URI diskType) {\n         return new AutoValue_AttachDisk_InitializeParams(diskName, diskSizeGb, sourceImage, diskType);\n      }\n\n      InitializeParams() {\n      }\n   }\n\n   public enum Type {\n      PERSISTENT,\n      SCRATCH;\n   }\n\n   public enum Mode {\n      READ_WRITE,\n      READ_ONLY;\n   }\n\n   public enum DiskInterface {\n      NVME,\n      SCSI;\n   }\n\n   public abstract Type type();\n\n   @Nullable public abstract Mode mode();\n\n   /** Use an existingBootDisk {@link org.jclouds.googlecomputeengine.domain.Disk#selfLink() boot disk}. */\n   @Nullable public abstract URI source();\n\n   /**\n    * Must be unique within the instance when specified. This represents a unique\n    * device name that is reflected into the /dev/ tree of a Linux operating system running within the\n    * instance. If not specified, a default will be chosen by the system.\n    */\n   @Nullable public abstract String deviceName();\n\n   /** True if this is a boot disk. VM will use the first partition of the disk for its root filesystem. */\n   public abstract boolean boot();\n\n   /** Set to automatically create a boot disk */\n   @Nullable public abstract InitializeParams initializeParams();\n\n   /** True if this disk will be deleted when the instance is delete. */\n   public abstract boolean autoDelete();\n\n   @Nullable public abstract List<String> licenses();\n\n   // Note: this is disks[].interface in the api docs but interface is a Java keyword.\n   @Nullable public abstract DiskInterface diskInterface();\n\n   public static AttachDisk existingBootDisk(URI existingBootDisk) {\n      return create(Type.PERSISTENT, existingBootDisk, null, true, false);\n   }\n\n   public static AttachDisk newBootDisk(URI sourceImage) {\n      return create(Type.PERSISTENT, null, InitializeParams.create(sourceImage), true, true);\n   }\n\n   public static AttachDisk newBootDisk(URI sourceImage, URI diskType) {\n      return create(Type.PERSISTENT, null, InitializeParams.create(sourceImage, diskType), true, true);\n   }\n\n   public static AttachDisk existingDisk(URI existingDisk) {\n      return create(Type.PERSISTENT, existingDisk, null, false, false);\n   }\n\n   static AttachDisk create(Type type, URI source, InitializeParams initializeParams, boolean boot,\n            boolean autoDelete) {\n         return create(type, null, source, null, boot, initializeParams, autoDelete, null, null);\n      }\n\n   @SerializedNames({\"type\", \"mode\", \"source\", \"deviceName\", \"boot\", \"initializeParams\", \"autoDelete\", \"licenses\", \"interface\" })\n   public static AttachDisk create(Type type, Mode mode, URI source, String deviceName, boolean boot, InitializeParams initializeParams,\n         boolean autoDelete, List<String> licenses, DiskInterface diskInterface) {\n      return new AutoValue_AttachDisk(type, mode, source, deviceName, boot, initializeParams, autoDelete, licenses, diskInterface);\n   }\n\n   AttachDisk() {\n   }\n}\n\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/domain/BackendService.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.domain;\n\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class BackendService {\n\n   @AutoValue\n   public abstract static class Backend {\n      public enum BalancingModes{\n         RATE,\n         UTILIZATION;\n      }\n\n      @Nullable public abstract String description();\n      public abstract URI group();\n      @Nullable public abstract BalancingModes balancingMode();\n      @Nullable public abstract Float maxUtilization();\n      @Nullable public abstract Integer maxRate();\n      @Nullable public abstract Float maxRatePerInstance();\n      @Nullable public abstract Float capacityScaler();\n\n\n      @SerializedNames({ \"description\", \"group\", \"balancingMode\", \"maxUtilization\", \"maxRate\",\n         \"maxRatePerInstance\", \"capacityScaler\" })\n      public static Backend create(String description,\n                                   URI group,\n                                   BalancingModes balancingMode,\n                                   Float maxUtilization,\n                                   Integer maxRate,\n                                   Float maxRatePerInstance,\n                                   Float capacityScaler) {\n         return new AutoValue_BackendService_Backend(description, group, balancingMode, maxUtilization, maxRate,\n                                  maxRatePerInstance, capacityScaler);\n      }\n\n      public static Backend create(URI group){\n         return create(null, group, null, null, null, null, null);\n      }\n\n      Backend(){\n      }\n   }\n\n   public abstract String id();\n   public abstract Date creationTimestamp();\n   public abstract URI selfLink();\n   public abstract String name();\n   @Nullable public  abstract String description();\n   @Nullable public  abstract List<Backend> backends();\n   @Nullable public abstract List<URI> healthChecks();\n   public abstract int timeoutSec();\n   public abstract int port();\n   @Nullable public abstract String protocol();\n   @Nullable public abstract String fingerprint();\n   @Nullable public abstract String portName();\n\n   /**\n    * @param timeoutSec Defaults to 30 when null.\n    * @param port Defaults to 80 when null.\n    */\n   @SerializedNames({ \"id\", \"creationTimestamp\", \"selfLink\", \"name\", \"description\",\n      \"backends\", \"healthChecks\", \"timeoutSec\", \"port\", \"protocol\",\n      \"fingerprint\", \"portName\"})\n   public static BackendService create(String id, Date creationTimestamp, URI selfLink,\n                          String name, @Nullable String description,\n                          @Nullable List<Backend> backends, List<URI> healthChecks,\n                          @Nullable Integer timeoutSec, @Nullable Integer port,\n                          @Nullable String protocol,\n                          @Nullable String fingerprint, String portName){\n      return new AutoValue_BackendService(id, creationTimestamp, selfLink, name, description,\n                            backends, healthChecks,\n                            timeoutSec != null ? timeoutSec : 30,\n                            port != null ? port : 80,\n                            protocol, fingerprint, portName);\n   }\n\n   BackendService(){\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/domain/Deprecated.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.domain;\n\nimport java.net.URI;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n/** Deprecation information for an image or kernel */\n@AutoValue\npublic abstract class Deprecated {\n\n   public enum State{\n      DELETED,\n      DEPRECATED,\n      OBSOLETE;\n   }\n\n   /** The deprecation state of this image. */\n   @Nullable public abstract State state();\n\n   /** A fully-qualified URL of the suggested replacement for the deprecated image. */\n   @Nullable public abstract URI replacement();\n\n   /** An optional RFC3339 timestamp for when the deprecation state of this resource will be changed to DEPRECATED. */\n   @Nullable public abstract String deprecated();\n\n   /**\n    * An optional RFC3339 timestamp on or after which the deprecation state of this resource will be changed to\n    * OBSOLETE.\n    */\n   @Nullable public abstract String obsolete();\n\n   /**\n    * An optional RFC3339 timestamp on or after which the deprecation state of this resource will be changed to\n    * DELETED.\n    */\n   @Nullable public abstract String deleted();\n\n   @SerializedNames({ \"state\", \"replacement\", \"deprecated\", \"obsolete\", \"deleted\" })\n   public static Deprecated create(State state, URI replacement, String deprecated, String obsolete, String deleted) {\n      return new AutoValue_Deprecated(state, replacement, deprecated, obsolete, deleted);\n   }\n\n   Deprecated() {\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/domain/Disk.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.domain;\n\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class Disk {\n\n   public enum Status {\n      CREATING,\n      FAILED,\n      READY,\n      RESTORING;\n   }\n\n   public abstract String id();\n\n   public abstract Date creationTimestamp();\n\n   public abstract URI zone();\n\n   public abstract Status status();\n\n   public abstract String name();\n\n   @Nullable public abstract String description();\n\n   public abstract int sizeGb();\n\n   @Nullable public abstract String sourceSnapshot();\n\n   @Nullable public abstract String sourceSnapshotId();\n\n   public abstract URI selfLink();\n\n   @Nullable public abstract URI sourceImage();\n\n   @Nullable public abstract String sourceImageId();\n\n   /** URL of the corresponding disk type resource. */\n   @Nullable public abstract URI type();\n\n   @Nullable public abstract List<String> licenses();\n\n   @SerializedNames({ \"id\", \"creationTimestamp\", \"zone\", \"status\", \"name\", \"description\", \"sizeGb\", \"sourceSnapshot\",\n      \"sourceSnapshotId\", \"selfLink\", \"sourceImage\", \"sourceImageId\", \"type\", \"licenses\" })\n   public static Disk create(String id, Date creationTimestamp, URI zone, Status status, String name, String description, int sizeGb,\n         String sourceSnapshot, String sourceSnapshotId, URI selfLink, URI sourceImage, String sourceImageId, URI type, List<String> licenses) {\n      return new AutoValue_Disk(id, creationTimestamp, zone, status, name, description, sizeGb,\n            sourceSnapshot, sourceSnapshotId, selfLink, sourceImage, sourceImageId, type, licenses);\n   }\n\n   Disk(){\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/domain/DiskType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.domain;\n\nimport java.net.URI;\nimport java.util.Date;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class DiskType {\n\n   public abstract Date creationTimestamp();\n\n   public abstract String name();\n\n   @Nullable public abstract String description();\n\n   /** Textual description of the valid disk size. For example, \"10GB-10TB.\" */\n   @Nullable public abstract String validDiskSize();\n\n   @Nullable public abstract Deprecated deprecated();\n\n   @Nullable public abstract URI zone();\n\n   public abstract URI selfLink();\n\n   /** Server defined default disk size in GB. */\n   public abstract long defaultDiskSizeGb();\n\n   @SerializedNames({ \"creationTimestamp\", \"name\", \"description\", \"validDiskSize\", \"deprecated\", \"zone\", \"selfLink\", \"defaultDiskSizeGb\" })\n   public static DiskType create(Date creationTimestamp, String name, String description, String validDiskSize, Deprecated deprecated, URI zone,\n         URI selfLink, long defaultDiskSizeGb) {\n      return new AutoValue_DiskType(creationTimestamp, name, description, validDiskSize, deprecated, zone, selfLink, defaultDiskSizeGb);\n   }\n\n   DiskType() {\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/domain/Firewall.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.domain;\n\nimport static org.jclouds.googlecloud.internal.NullSafeCopies.copyOf;\n\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class Firewall {\n\n   /** A protocol and port-range tuple that describes a permitted connection. */\n   @AutoValue\n   public abstract static class Rule {\n      /** This can either be a well known protocol string (tcp, udp or icmp) or the IP protocol number. */\n      public abstract String ipProtocol();\n\n      /**\n       * An optional list of ports which are allowed. This is only applicable for UDP or TCP protocol. Each entry must\n       * be either an integer or a range (ex. {@code 12345-12349}). If not specified, connections through any port are\n       * allowed.\n       */\n      @Nullable public abstract List<String> ports();\n\n      @SerializedNames({ \"IPProtocol\", \"ports\" })\n      public static Rule create(String ipProtocol, List<String> ports) {\n         return new AutoValue_Firewall_Rule(ipProtocol, ports);\n      }\n\n      Rule() {\n      }\n   }\n\n   public abstract String id();\n\n   public abstract URI selfLink();\n\n   public abstract Date creationTimestamp();\n\n   public abstract String name();\n\n   @Nullable public abstract String description();\n\n   /**\n    * @return URI of the network to which this firewall is applied; provided by the client when the firewall is created.\n    */\n   public abstract URI network();\n\n   /**\n    * One or both of sourceRanges and sourceTags may be set; an inbound connection is allowed if either the range or\n    * the tag of the source matches.\n    *\n    * @return a list of IP address blocks expressed in CIDR format which this rule applies to.\n    */\n   public abstract List<String> sourceRanges();\n\n   /**\n    * @return a list of instance items which this rule applies to. One or both of sourceRanges and sourceTags may be\n    * set; an inbound connection is allowed if either the range or the tag of the source matches.\n    */\n   public abstract List<String> sourceTags();\n\n   /**\n    * If no targetTags are specified, the firewall rule applies to all instances on the specified network.\n    *\n    * @return a list of instance items indicating sets of instances located on network which may make network\n    * connections as specified in allowed.\n    */\n   public abstract List<String> targetTags();\n\n   /**\n    * Each rule specifies a protocol and port-range tuple that describes a permitted connection.\n    *\n    * @return the list of rules specified by this firewall.\n    */\n   public abstract List<Rule> allowed();\n\n   @SerializedNames(\n         { \"id\", \"selfLink\", \"creationTimestamp\", \"name\", \"description\", \"network\", \"sourceRanges\", \"sourceTags\", \"targetTags\", \"allowed\" })\n   public static Firewall create(String id, URI selfLink, Date creationTimestamp, String name, String description, URI network,\n         List<String> sourceRanges, List<String> sourceTags, List<String> targetTags, List<Rule> allowed) {\n      return new AutoValue_Firewall(id, selfLink, creationTimestamp, name, description, network, copyOf(sourceRanges), copyOf(sourceTags),\n            copyOf(targetTags), copyOf(allowed));\n   }\n\n   Firewall() {\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/domain/ForwardingRule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.domain;\n\nimport java.net.URI;\nimport java.util.Date;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class ForwardingRule {\n\n   public enum IPProtocol {\n      /** IP Authentication Header protocol. */\n      AH,\n      /** IP Encapsulating Security Payload protocol. */\n      ESP,\n      /** Stream Control Transmission Protocol. */\n      SCTP,\n      /** Transmission Control Protocol. */\n      TCP,\n      /** Specifies the User Datagram Protocol. */\n      UDP\n   }\n\n   public abstract String id();\n\n   public abstract URI selfLink();\n\n   public abstract String name();\n\n   @Nullable public abstract String description();\n\n   public abstract Date creationTimestamp();\n\n   /** null when representing a GlobalForwardingRules */\n   @Nullable public abstract URI region();\n\n   /**\n    * The external IP address that this forwarding rule is serving on behalf of. If this is a reserved\n    * address, the address must live in the same region as the forwarding rule. By default,\n    * this field is empty and  an ephemeral IP is assigned to the ForwardingRule.\n    */\n   @Nullable public abstract String ipAddress();\n\n   public abstract IPProtocol ipProtocol();\n\n   /**\n    * If IPProtocol is TCP or UDP, packets addressed to ports in the specified range will be forwarded to\n    * backend. By default, this is empty and all ports are allowed.\n    */\n   @Nullable public abstract String portRange();\n\n   /**\n    * The URL of the target resource to receive the matched traffic. The target resource must live in the\n    * same region as this forwarding rule.\n    */\n   public abstract URI target();\n\n   @SerializedNames(\n         { \"id\", \"selfLink\", \"name\", \"description\", \"creationTimestamp\", \"region\", \"IPAddress\", \"IPProtocol\", \"portRange\", \"target\" })\n   public static ForwardingRule create(String id, URI selfLink, String name, String description, Date creationTimestamp, URI region,\n         String ipAddress, IPProtocol ipProtocol, String portRange, URI target) {\n      return new AutoValue_ForwardingRule(id, selfLink, name, description, creationTimestamp, region, ipAddress,\n            ipProtocol == null ? IPProtocol.TCP : ipProtocol, portRange, target);\n   }\n\n   ForwardingRule() {\n   }\n\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/domain/HealthStatus.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.domain;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class HealthStatus {\n\n   public abstract List<HealthStatusInternal> healthStatus();\n\n   @SerializedNames({\"healthStatus\"})\n   public static HealthStatus create(List<HealthStatusInternal> healthStatus){\n      return new AutoValue_HealthStatus(healthStatus);\n   }\n\n   HealthStatus(){\n   }\n\n   @AutoValue\n   public abstract static class HealthStatusInternal {\n\n      @Nullable public abstract String ipAddress();\n      public abstract Integer port();\n      public abstract URI instance();\n      public abstract String healthState();\n\n      @SerializedNames({\"ipAddress\", \"port\", \"instance\", \"healthState\"})\n      public static HealthStatusInternal create(String ipAddress, int port, URI instance, String healthState) {\n         return new AutoValue_HealthStatus_HealthStatusInternal(ipAddress, port, instance, healthState);\n      }\n\n      HealthStatusInternal(){\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/domain/HttpHealthCheck.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.domain;\n\nimport java.net.URI;\nimport java.util.Date;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class HttpHealthCheck {\n\n   public abstract String id();\n\n   public abstract URI selfLink();\n\n   public abstract Date creationTimestamp();\n\n   public abstract String name();\n\n   @Nullable public abstract String description();\n\n   /**\n    * The value of the host header in the HTTP health check request. If left empty (default value),\n    * the public IP on behalf of which this health check is performed will be used.\n    */\n   @Nullable public abstract String host();\n\n   @Nullable public abstract String requestPath();\n\n   /** The TCP port number for the HTTP health check request. */\n   @Nullable public abstract Integer port();\n\n   /** How often (in seconds) to send a health check. */\n   @Nullable public abstract Integer checkIntervalSec();\n\n   /** How long (in seconds) to wait before claiming failure. */\n   @Nullable public abstract Integer timeoutSec();\n\n   /** A so-far healthy VM will be marked unhealthy after this many consecutive failures. */\n   @Nullable public abstract Integer unhealthyThreshold();\n\n   /** An unhealthy VM will be marked healthy after this many consecutive successes. */\n   @Nullable public abstract Integer healthyThreshold();\n\n   @SerializedNames(\n         { \"id\", \"selfLink\", \"creationTimestamp\", \"name\", \"description\", \"host\", \"requestPath\", \"port\", \"checkIntervalSec\", \"timeoutSec\",\n               \"unhealthyThreshold\", \"healthyThreshold\" })\n   public static HttpHealthCheck create(String id, URI selfLink, Date creationTimestamp, String name, String description, String host,\n         String requestPath, Integer port, Integer checkIntervalSec, Integer timeoutSec, Integer unhealthyThreshold,\n         Integer healthyThreshold) {\n      return new AutoValue_HttpHealthCheck(id, selfLink, creationTimestamp, name, description, host,\n            requestPath, port, checkIntervalSec, timeoutSec, unhealthyThreshold, healthyThreshold);\n   }\n\n   HttpHealthCheck() {\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/domain/Image.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.domain;\n\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class Image {\n\n   public enum Status {\n        FAILED,\n        PENDING,\n        READY;\n   }\n\n   @AutoValue\n   public abstract static class RawDisk {\n      /**\n       * The full Google Cloud Storage URL where the disk image is stored; provided by the client when the disk\n       * image is created.\n       */\n      public abstract URI source();\n\n      /**\n       * The format used to encode and transmit the block device.\n       */\n      public abstract String containerType();\n\n      /**\n       * SHA1 checksum of the disk image before unpacking; provided by the client when the disk\n       * image is created.\n       */\n      @Nullable public abstract String sha1Checksum();\n\n      @SerializedNames({ \"source\", \"containerType\", \"sha1Checksum\" })\n      public static RawDisk create(URI source, String containerType, String sha1Checksum) {\n         return new AutoValue_Image_RawDisk(source, containerType, sha1Checksum);\n      }\n\n      RawDisk() {\n      }\n   }\n\n   public abstract String id();\n\n   public abstract URI selfLink();\n\n   public abstract Date creationTimestamp();\n\n   public abstract String name();\n\n   @Nullable public abstract String description();\n\n   /** Must be RAW; provided by the client when the disk image is created. */\n   // TODO: if this is true, why bother listing it?\n   @Nullable public abstract String sourceType();\n\n   @Nullable public abstract RawDisk rawDisk();\n\n   @Nullable public abstract Deprecated deprecated();\n\n   public abstract Status status();\n\n   @Nullable public abstract Long archiveSizeBytes();\n\n   public abstract Long diskSizeGb();\n\n   @Nullable public abstract String sourceDisk();\n\n   @Nullable public abstract String sourceDiskId();\n\n   @Nullable public abstract List<String> licenses();\n\n   @SerializedNames({ \"id\", \"selfLink\", \"creationTimestamp\", \"name\", \"description\", \"sourceType\", \"rawDisk\", \"deprecated\",\n      \"status\", \"archiveSizeBytes\", \"diskSizeGb\", \"sourceDisk\", \"sourceDiskId\", \"licenses\"})\n   public static Image create(String id, URI selfLink, Date creationTimestamp, String name, String description, String sourceType,\n         RawDisk rawDisk, Deprecated deprecated, Status status, Long archiveSizeBytes, Long diskSizeGb,\n         String sourceDisk, String sourceDiskId, List<String> licenses) {\n      return new AutoValue_Image(id, selfLink, creationTimestamp, name, description, sourceType, rawDisk, deprecated, status,\n            archiveSizeBytes, diskSizeGb, sourceDisk, sourceDiskId, licenses);\n   }\n\n   Image() {\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/domain/Instance.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.domain;\n\nimport static org.jclouds.googlecloud.internal.NullSafeCopies.copyOf;\n\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.List;\n\nimport org.jclouds.googlecomputeengine.domain.AttachDisk.DiskInterface;\nimport org.jclouds.googlecomputeengine.domain.AttachDisk.InitializeParams;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n/** Represents a virtual machine. */\n@AutoValue\npublic abstract class Instance {\n\n   @AutoValue\n   public abstract static class AttachedDisk {\n      public enum Type {\n         PERSISTENT,\n         SCRATCH;\n      }\n\n      public enum Mode {\n         READ_WRITE,\n         READ_ONLY;\n      }\n\n      /** A zero-based index to assign to this disk, where 0 is reserved for the boot disk. */\n      public abstract int index();\n\n      public abstract Type type();\n\n      public abstract Mode mode();\n\n      /** Corresponds to {@linkplain Disk#selfLink()} when {@linkplain #type()} is {@linkplain Type#PERSISTENT}. */\n      @Nullable public abstract URI source();\n\n      /**\n       * Must be unique within the instance when specified. This represents a unique\n       * device name that is reflected into the /dev/ tree of a Linux operating system running within the\n       * instance. If not specified, a default will be chosen by the system.\n       */\n      @Nullable public abstract String deviceName();\n\n      public abstract boolean autoDelete();\n\n      public abstract boolean boot();\n\n      @Nullable public abstract InitializeParams initializeParams();\n\n      @Nullable public abstract List<String> licenses();\n\n      // Note: this is disks[].interface in the api docs but interface is a Java keyword.\n      @Nullable public abstract DiskInterface diskInterface();\n\n      @SerializedNames({ \"index\", \"type\", \"mode\", \"source\", \"deviceName\", \"autoDelete\", \"boot\",\n         \"initializeParams\", \"licenses\", \"interface\" })\n      public static AttachedDisk create(int index, Type type, Mode mode, URI source, String deviceName,\n            boolean autoDelete, boolean boot, InitializeParams initializeParams,\n            List<String> licenses, DiskInterface diskInterface) {\n         return new AutoValue_Instance_AttachedDisk(index, type, mode, source, deviceName, autoDelete,\n               boot, initializeParams, licenses, diskInterface);\n      }\n\n      AttachedDisk() {\n      }\n   }\n\n   @AutoValue\n   public abstract static class NetworkInterface {\n      /**\n       * This specifies how this interface is configured to interact with other network services,\n       * such as connecting to the internet.\n       */\n      @AutoValue\n      public abstract static class AccessConfig {\n\n         public enum Type {\n            ONE_TO_ONE_NAT\n         }\n\n         @Nullable public abstract String name();\n\n         public abstract Type type();\n\n         /** An external IP address associated with this instance, if there is one. */\n         @Nullable public abstract String natIP();\n\n         @SerializedNames({ \"name\", \"type\", \"natIP\" })\n         public static AccessConfig create(String name, Type type, String natIP) {\n            return new AutoValue_Instance_NetworkInterface_AccessConfig(name, type, natIP);\n         }\n\n         AccessConfig() {\n         }\n      }\n\n      public abstract String name();\n\n      public abstract URI network();\n\n      /** An IPV4 internal network address to assign to this instance. */\n      @Nullable public abstract String networkIP();\n\n      public abstract List<AccessConfig> accessConfigs();\n\n      @SerializedNames({ \"name\", \"network\", \"networkIP\", \"accessConfigs\" })\n      public static NetworkInterface create(String name, URI network, String networkIP,\n            List<AccessConfig> accessConfigs) {\n         return new AutoValue_Instance_NetworkInterface(name, network, networkIP, copyOf(accessConfigs));\n      }\n\n      NetworkInterface() {\n      }\n   }\n\n   @AutoValue\n   public abstract static class SerialPortOutput {\n\n      @Nullable public abstract URI selfLink();\n\n      /** The contents of the console output. */\n      public abstract String contents();\n\n      @SerializedNames({ \"selfLink\", \"contents\" })\n      public static SerialPortOutput create(URI selfLink, String contents) {\n         return new AutoValue_Instance_SerialPortOutput(selfLink, contents);\n      }\n\n      SerialPortOutput() {\n      }\n   }\n\n   /**\n    * A service account for which access tokens are to be made available to the instance through metadata queries.\n    */\n   @AutoValue\n   public abstract static class ServiceAccount {\n\n      public abstract String email();\n\n      public abstract List<String> scopes();\n\n      @SerializedNames({ \"email\", \"scopes\" })\n      public static ServiceAccount create(String email, List<String> scopes) {\n         return new AutoValue_Instance_ServiceAccount(email, scopes);\n      }\n\n      ServiceAccount() {\n      }\n   }\n\n   /**\n    * Defines the maintenance behavior for this instance. The default behavior is migrate.\n    */\n   @AutoValue\n   public abstract static class Scheduling {\n\n      public enum OnHostMaintenance {\n         /**\n          * Allows Compute Engine to automatically migrate instances out of the way of maintenance events.\n          */\n         MIGRATE,\n         /**\n          * Allows Compute Engine to terminate and restart the instance away from the maintenance activity.\n          * If you would like your instance to be restarted, set the automaticRestart flag to true.\n          * Your instance may be restarted more than once, and it may be restarted outside the window\n          * of maintenance events.\n          * If you would like your instance to be preemptible, set the preemptible flag to true.\n          */\n         TERMINATE\n      }\n\n      public abstract OnHostMaintenance onHostMaintenance();\n      public abstract boolean automaticRestart();\n      public abstract boolean preemptible();\n\n      @SerializedNames({ \"onHostMaintenance\", \"automaticRestart\", \"preemptible\" })\n      public static Scheduling create(OnHostMaintenance onHostMaintenance, boolean automaticRestart,\n         boolean preemptible) {\n         return new AutoValue_Instance_Scheduling(onHostMaintenance, automaticRestart, preemptible);\n      }\n\n      Scheduling() {\n      }\n   }\n\n   public enum Status {\n      PROVISIONING,\n      STAGING,\n      RUNNING,\n      STOPPING,\n      STOPPED,\n      TERMINATED\n   }\n\n   public abstract String id();\n\n   @Nullable public abstract Date creationTimestamp();\n\n   public abstract URI selfLink();\n\n   public abstract String name();\n\n   @Nullable public abstract String description();\n\n   public abstract Tags tags();\n\n   public abstract URI machineType();\n\n   @Nullable public abstract Status status();\n\n   /** Human-readable explanation of the status. */\n   @Nullable public abstract String statusMessage();\n\n   /**\n    * URL of the zone resource describing where this instance should be hosted; provided by the client when\n    * the instance is created.\n    */\n   public abstract URI zone();\n\n   @Nullable public abstract Boolean canIpForward();\n\n   public abstract List<NetworkInterface> networkInterfaces();\n\n   public abstract List<AttachedDisk> disks();\n\n   public abstract Metadata metadata();\n\n   public abstract List<ServiceAccount> serviceAccounts();\n\n   public abstract Scheduling scheduling();\n\n   @SerializedNames({ \"id\", \"creationTimestamp\", \"selfLink\", \"name\", \"description\", \"tags\", \"machineType\", \"status\", \"statusMessage\", \"zone\",\n         \"canIpForward\", \"networkInterfaces\", \"disks\", \"metadata\", \"serviceAccounts\", \"scheduling\"})\n   public static Instance create(String id, Date creationTimestamp, URI selfLink, String name, String description, Tags tags, URI machineType,\n         Status status, String statusMessage, URI zone, Boolean canIpForward, List<NetworkInterface> networkInterfaces,\n         List<AttachedDisk> disks, Metadata metadata, List<ServiceAccount> serviceAccounts, Scheduling scheduling) {\n      return new AutoValue_Instance(id, creationTimestamp, selfLink, name, description, tags, machineType, status, statusMessage, zone,\n            canIpForward, copyOf(networkInterfaces), copyOf(disks), metadata, copyOf(serviceAccounts), scheduling);\n   }\n\n   Instance() {\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/domain/KeyValuePair.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.domain;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class KeyValuePair {\n\n   public abstract String key();\n\n   public abstract String value();\n\n   @SerializedNames({ \"key\", \"value\" })\n   public static KeyValuePair create(String key, String value) {\n      return new AutoValue_KeyValuePair(key, value);\n   }\n\n   KeyValuePair(){\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/domain/License.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.domain;\n\nimport java.net.URI;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n/** Parameter to {@linkplain org.jclouds.googlecomputeengine.features.InstanceApi#create(NewInstance)}. */\n@AutoValue\npublic abstract class License {\n\n   public abstract URI selfLink();\n   public abstract String name();\n   public abstract boolean chargesUseFee();\n\n   @SerializedNames({\"selfLink\", \"name\", \"chargesUseFee\"})\n   public static License create(URI selfLink, String name, boolean chargesUseFee) {\n      return new AutoValue_License(selfLink, name, chargesUseFee);\n   }\n\n   License() {\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/domain/MachineType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.domain;\n\nimport static org.jclouds.googlecloud.internal.NullSafeCopies.copyOf;\n\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n/** Represents a machine type used to host an instance. */\n@AutoValue\npublic abstract class MachineType {\n\n   @AutoValue\n   public abstract static class ScratchDisk {\n\n      public abstract int diskGb();\n\n      @SerializedNames({ \"diskGb\" })\n      public static ScratchDisk create(int diskGb) {\n         return new AutoValue_MachineType_ScratchDisk(diskGb);\n      }\n\n      ScratchDisk() {\n      }\n   }\n\n   public abstract String id();\n\n   public abstract Date creationTimestamp();\n\n   public abstract URI selfLink();\n\n   public abstract String name();\n\n   @Nullable public abstract String description();\n\n   public abstract int guestCpus();\n\n   public abstract int memoryMb();\n\n   @Nullable public abstract Integer imageSpaceGb();\n\n   public abstract List<ScratchDisk> scratchDisks();\n\n   public abstract int maximumPersistentDisks();\n\n   public abstract long maximumPersistentDisksSizeGb();\n\n   /** The zones that this machine type can run in. */\n   public abstract String zone();\n\n   @Nullable public abstract Deprecated deprecated();\n\n   @SerializedNames(\n         { \"id\", \"creationTimestamp\", \"selfLink\", \"name\", \"description\", \"guestCpus\", \"memoryMb\", \"imageSpaceGb\", \"scratchDisks\", \"maximumPersistentDisks\",\n               \"maximumPersistentDisksSizeGb\", \"zone\", \"deprecated\" })\n   public static MachineType create(String id, Date creationTimestamp, URI selfLink, String name, String description, int guestCpus,\n         int memoryMb, Integer imageSpaceGb, List<ScratchDisk> scratchDisks, int maximumPersistentDisks, long maximumPersistentDisksSizeGb,\n         String zone, Deprecated deprecated) {\n      return new AutoValue_MachineType(id, creationTimestamp, selfLink, name, description, guestCpus, memoryMb, imageSpaceGb, copyOf(scratchDisks),\n            maximumPersistentDisks, maximumPersistentDisksSizeGb, zone, deprecated);\n   }\n\n   MachineType() {\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/domain/Metadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.domain;\n\nimport java.util.ArrayList;\nimport java.util.LinkedHashMap;\nimport java.util.Map;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n/**\n * Metadata for an instance or project, with their fingerprint.\n * <p/>\n * This object is mutable and not thread-safe.\n */\n@AutoValue\npublic abstract class Metadata implements Cloneable {\n\n   /** The fingerprint for the items - needed for updating them. */\n   @Nullable public abstract String fingerprint();\n\n   /** Adds or replaces a metadata entry. */\n   public Metadata put(String key, String value) {\n      remove(key);\n      items().add(KeyValuePair.create(key, value));\n      return this;\n   }\n\n   /** Adds or replaces metadata entries. */\n   public Metadata putAll(Map<String, String> input) {\n      for (Map.Entry<String, String> entry : input.entrySet()) {\n         put(entry.getKey(), entry.getValue());\n      }\n      return this;\n   }\n\n   /** Removes any entry with the supplied key. */\n   public Metadata remove(String key) {\n      for (int i = 0, length = items().size(); i < length; i++) {\n         if (items().get(i).key().equals(key)) {\n            items().remove(i);\n            return this;\n         }\n      }\n      return this;\n   }\n\n   /** Copies the metadata into a new mutable map. */\n   public Map<String, String> asMap() {\n      Map<String, String> result = new LinkedHashMap<String, String>();\n      ArrayList<KeyValuePair> items = items();\n      for (int i = 0, length = items.size(); i < length; i++) {\n         KeyValuePair item = items.get(i);\n         result.put(item.key(), item.value());\n      }\n      return result;\n   }\n\n   /** Returns the value with the supplied key, or null. */\n   @Nullable public String get(String key) {\n      ArrayList<KeyValuePair> items = items();\n      for (int i = 0, length = items.size(); i < length; i++) {\n         KeyValuePair item = items.get(i);\n         if (item.key().equals(key)) {\n            return item.value();\n         }\n      }\n      return null;\n   }\n\n   public boolean containsKey(String key) {\n      return get(key) != null;\n   }\n\n   public int size() {\n      return items().size();\n   }\n\n   /** Mutable list of metadata. */\n   abstract ArrayList<KeyValuePair> items();\n\n   public static Metadata create() {\n      return Metadata.create(null, null);\n   }\n\n   public static Metadata create(String fingerprint) {\n      return Metadata.create(fingerprint, null);\n   }\n\n   @SerializedNames({ \"fingerprint\", \"items\" })\n   static Metadata create(String fingerprint, ArrayList<KeyValuePair> items) { // Dictates the type when created from json!\n      return new AutoValue_Metadata(fingerprint, items != null ? items : new ArrayList<KeyValuePair>());\n   }\n\n   Metadata() {\n   }\n\n   @Override public Metadata clone() {\n      return Metadata.create(fingerprint(), new ArrayList<KeyValuePair>(items()));\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/domain/Network.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.domain;\n\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.base.Strings;\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Represents a network used to enable instance communication.\n */\n@AutoValue\npublic abstract class Network {\n\n   public enum NetworkType {\n      LegacyNetwork,\n      AutoSubnetwork,\n      CustomNetwork,\n   }\n\n   public abstract String id();\n\n   public abstract Date creationTimestamp();\n\n   public abstract URI selfLink();\n\n   public abstract String name();\n\n   @Nullable public abstract String description();\n\n   /**\n    * The range of internal addresses that are legal on this network. This range is a CIDR\n    * specification, for example: {@code 192.168.0.0/16}.\n    */\n   @Nullable public abstract String rangeIPv4();\n\n   /**\n    * This must be within the range specified by IPv4Range, and is typically the first usable address in that range.\n    * If not specified, the default value is the first usable address in IPv4Range.\n    */\n   @Nullable public abstract String gatewayIPv4();\n   \n   public abstract boolean autoCreateSubnetworks();\n\n   public abstract List<URI> subnetworks();\n\n   @SerializedNames({ \"id\", \"creationTimestamp\", \"selfLink\", \"name\", \"description\", \"IPv4Range\", \"gatewayIPv4\",\n         \"autoCreateSubnetworks\", \"subnetworks\" })\n   public static Network create(String id, Date creationTimestamp, URI selfLink, String name, String description,\n         String rangeIPv4, String gatewayIPv4, boolean autoCreateSubnetworks, List<URI> subnetworks) {\n      return new AutoValue_Network(id, creationTimestamp, selfLink, name, description, rangeIPv4, gatewayIPv4,\n            autoCreateSubnetworks, subnetworks == null ? ImmutableList.<URI> of() : ImmutableList.copyOf(subnetworks));\n   }\n\n   Network() {\n   }\n\n   public NetworkType type() {\n      return !Strings.isNullOrEmpty(rangeIPv4()) ? NetworkType.LegacyNetwork\n            : (autoCreateSubnetworks() ? NetworkType.AutoSubnetwork : NetworkType.CustomNetwork);\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/domain/NewInstance.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.domain;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.net.URI;\nimport java.util.Arrays;\nimport java.util.List;\n\nimport org.jclouds.googlecomputeengine.domain.Instance.NetworkInterface.AccessConfig;\nimport org.jclouds.googlecomputeengine.domain.Instance.NetworkInterface.AccessConfig.Type;\nimport org.jclouds.googlecomputeengine.domain.Instance.Scheduling;\nimport org.jclouds.googlecomputeengine.domain.Instance.ServiceAccount;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\n\n/** Parameter to {@linkplain org.jclouds.googlecomputeengine.features.InstanceApi#create(NewInstance)}. */\n@AutoValue\npublic abstract class NewInstance {\n   @AutoValue\n   public abstract static class NetworkInterface {\n      abstract URI network();\n      @Nullable abstract URI subnetwork();\n\n      abstract List<AccessConfig> accessConfigs();\n\n      public static NetworkInterface create(URI network, URI subnetwork) {\n         return create(network, subnetwork,\n             Arrays.asList(AccessConfig.create(null, Type.ONE_TO_ONE_NAT, null)));\n      }\n\n      @SerializedNames({ \"network\", \"subnetwork\", \"accessConfigs\" })\n      public static NetworkInterface create(URI network, URI subnetwork, List<AccessConfig> accessConfigs) {\n         return new AutoValue_NewInstance_NetworkInterface(network, subnetwork, accessConfigs);\n      }\n\n      NetworkInterface() {\n      }\n   }\n\n   public abstract String name();\n\n   public abstract URI machineType();\n\n   @Nullable public abstract Boolean canIpForward();\n\n   public abstract List<NetworkInterface> networkInterfaces();\n\n   public abstract List<AttachDisk> disks();\n\n   @Nullable public abstract String description();\n\n   public abstract Tags tags();\n\n   /** Add metadata via {@link Metadata#items()}. */\n   public abstract Metadata metadata();\n\n   @Nullable public abstract List<ServiceAccount> serviceAccounts();\n\n   @Nullable public abstract Scheduling scheduling();\n\n   /** Convenience for creating a new instance with only a boot disk and minimal parameters. */\n   public static NewInstance create(String name, URI machineType, URI network, URI subnetwork, URI sourceImage) {\n      return create(name, machineType, network, subnetwork, Arrays.asList(AttachDisk.newBootDisk(sourceImage)), null,\n              null);\n   }\n\n   public static NewInstance create(String name, URI machineType, URI network, @Nullable URI subnetwork,\n                                    List<AttachDisk> disks, @Nullable String description, @Nullable Tags tags) {\n      checkArgument(disks.get(0).boot(), \"disk 0 must be a boot disk! %s\", disks);\n      boolean foundBoot = false;\n      for (AttachDisk disk : disks) {\n         if (disk.boot()) {\n            checkArgument(!foundBoot, \"There must be only one boot disk! %s\", disks);\n            foundBoot = true;\n         }\n      }\n      return create(name, machineType, null, ImmutableList.of(NetworkInterface.create(network, subnetwork)),\n            ImmutableList.copyOf(disks), description, tags != null ? tags : Tags.create(), Metadata.create(), null,\n            null);\n   }\n\n   @SerializedNames({ \"name\", \"machineType\", \"canIpForward\", \"networkInterfaces\", \"disks\", \"description\",\n                      \"tags\", \"metadata\", \"serviceAccounts\", \"scheduling\" })\n   static NewInstance create(String name, URI machineType, Boolean canIpForward,\n                             List<NetworkInterface> networkInterfaces, List<AttachDisk> disks, String description,\n                             Tags tags, Metadata metadata, List<ServiceAccount> serviceAccounts, Scheduling scheduling) {\n      return new AutoValue_NewInstance(name, machineType, canIpForward, networkInterfaces, disks, description,\n                                       tags, metadata, serviceAccounts, scheduling);\n   }\n\n   NewInstance() {\n   }\n\n   public static class Builder {\n      private String name;\n      private URI machineType;\n      private Boolean canIpForward;\n      private List<NetworkInterface> networkInterfaces;\n      private List<AttachDisk> disks;\n      private String description;\n      private Tags tags;\n      private Metadata metadata;\n      private List<ServiceAccount> serviceAccounts;\n      private Scheduling scheduling;\n\n      public Builder(String name, URI machineType, URI network, URI subnetwork, List<AttachDisk> disks) {\n         checkNotNull(name, \"NewInstance name cannot be null\");\n         this.name = name;\n         this.machineType = machineType;\n         this.networkInterfaces = ImmutableList.of(NetworkInterface.create(network, subnetwork));\n         this.disks = disks;\n      }\n\n      public Builder(String name, URI machineType, List<NetworkInterface> networks, List<AttachDisk> disks) {\n         checkNotNull(name, \"NewInstance name cannot be null\");\n         this.name = name;\n         this.machineType = machineType;\n         this.networkInterfaces = ImmutableList.copyOf(networks);\n         this.disks = disks;\n      }\n\n      public Builder(String name, URI machineType, URI network, URI subnetwork, URI sourceImage) {\n         checkNotNull(name, \"NewInstance name cannot be null\");\n         this.name = name;\n         this.machineType = machineType;\n         this.networkInterfaces = ImmutableList.of(NetworkInterface.create(network, subnetwork));\n         this.disks = Arrays.asList(AttachDisk.newBootDisk(sourceImage));\n      }\n\n      public Builder canIpForward(Boolean canIpForward){\n         this.canIpForward = canIpForward;\n         return this;\n      }\n\n      public Builder description(String description){\n         this.description = description;\n         return this;\n      }\n\n      public Builder tags(Tags tags){\n         this.tags = tags;\n         return this;\n      }\n\n      public Builder metadata(Metadata metadata){\n         this.metadata = metadata;\n         return this;\n      }\n\n      /**\n       * A list of service accounts, with their specified scopes, authorized for this instance.\n       * Service accounts generate access tokens that can be accessed through the metadata server\n       * and used to authenticate applications on the instance.\n       * Note: to add scopes to the default service account on the VM you can use 'default' as\n       * a keyword for email.\n       */\n      public Builder serviceAccounts(List<ServiceAccount> serviceAccounts){\n         this.serviceAccounts = serviceAccounts;\n         return this;\n      }\n\n      public Builder scheduling(Scheduling scheduling){\n         this.scheduling = scheduling;\n         return this;\n      }\n\n      public NewInstance build() {\n         return create(name, machineType, canIpForward, networkInterfaces, disks, description, tags != null ? tags : Tags.create(),\n                       metadata != null ? metadata : Metadata.create(), serviceAccounts, scheduling);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/domain/NewTargetInstance.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.domain;\n\nimport java.net.URI;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class NewTargetInstance {\n\n   public abstract String name();\n   @Nullable public abstract String description();\n   @Nullable public abstract String natPolicy();\n   @Nullable public abstract URI instance();\n\n   @SerializedNames({\"name\", \"description\", \"natPolicy\", \"instance\"})\n   static NewTargetInstance create(String name, String description, String natPolicy, URI instance){\n      return new AutoValue_NewTargetInstance(name, description, natPolicy, instance);\n   }\n\n   NewTargetInstance() {\n   }\n\n   public static class Builder {\n      private String name;\n      private String description;\n      private String natPolicy;\n      private URI instance;\n\n      public Builder name(String name) {\n         this.name = name;\n         return this;\n      }\n\n      public Builder description(String description) {\n         this.description = description;\n         return this;\n      }\n\n      public Builder natPolicy(String natPolicy) {\n         this.natPolicy = natPolicy;\n         return this;\n      }\n\n      public Builder instance(URI instance) {\n         this.instance = instance;\n         return this;\n      }\n\n      public NewTargetInstance build() {\n         return NewTargetInstance.create(name, description, natPolicy, instance);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/domain/Operation.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.domain;\n\nimport java.net.URI;\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class Operation {\n\n   @AutoValue\n   public abstract static class Error {\n\n      @AutoValue\n      public abstract static class Entry {\n\n         /** The error type identifier for this error. */\n         public abstract String code(); // TODO: enum?\n\n         /** The field in the request which caused the error. */\n         @Nullable public abstract String location();\n\n         @Nullable public abstract String message();\n\n         @SerializedNames({ \"code\", \"location\", \"message\" })\n         public static Entry create(String code, String location, String message) {\n            return new AutoValue_Operation_Error_Entry(code, location, message);\n         }\n\n         Entry() {\n         }\n      }\n\n      public abstract List<Entry> errors();\n\n      @SerializedNames({ \"errors\" })\n      public static Error create(List<Entry> errors) {\n         return new AutoValue_Operation_Error(errors != null ? errors : new ArrayList<Entry>());\n      }\n\n      public static Error empty(){\n         return create(null);\n      }\n\n      Error(){\n      }\n   }\n\n   public static enum Status {\n      PENDING,\n      RUNNING,\n      DONE\n   }\n\n   public abstract String id();\n\n   @Nullable public abstract Date creationTimestamp();\n\n   public abstract URI selfLink();\n\n   public abstract String name();\n\n   @Nullable public abstract String description();\n\n   /** URL of the resource the operation is mutating. */\n   public abstract URI targetLink();\n\n   /** Target id which identifies a particular incarnation of the target. */\n   @Nullable public abstract String targetId();\n\n   /**\n    * Identifier specified by the client when the mutation was initiated. Must be unique for all operation resources in\n    * the project.\n    */\n   @Nullable public abstract String clientOperationId();\n\n   public abstract Status status();\n\n   /** Textual description of the current status of the operation. */\n   @Nullable public abstract String statusMessage();\n\n   /** User who requested the operation, for example {@code user@example.com}. */\n   @Nullable public abstract String user();\n\n   /**\n    * A progress indicator that ranges from 0 to 100. This should not be used to guess at when the\n    * operation will be complete. This number should be monotonically increasing as the operation progresses.\n    */\n   @Nullable public abstract Integer progress(); // TODO: check really nullable\n\n   /** The time that this operation was requested. */\n   public abstract Date insertTime();\n\n   @Nullable public abstract Date startTime();\n\n   @Nullable public abstract Date endTime();\n\n   @Nullable public abstract Integer httpErrorStatusCode();\n\n   @Nullable public abstract String httpErrorMessage();\n\n   /** Examples include insert, update, and delete. */\n   public abstract String operationType(); // TODO: enum\n\n   public abstract Error error();\n\n   @Nullable public abstract List<Warning> warnings();\n\n   @Nullable public abstract URI region();\n\n   @Nullable public abstract URI zone();\n\n   @SerializedNames({ \"id\", \"creationTimestamp\", \"selfLink\", \"name\", \"description\", \"targetLink\", \"targetId\", \"clientOperationId\", \"status\",\n         \"statusMessage\", \"user\", \"progress\", \"insertTime\", \"startTime\", \"endTime\", \"httpErrorStatusCode\",\n         \"httpErrorMessage\", \"operationType\", \"error\", \"warnings\", \"region\", \"zone\" })\n   public static Operation create(String id, Date creationTimestamp, URI selfLink, String name, String description, URI targetLink,\n         String targetId, String clientOperationId, Status status, String statusMessage, String user, Integer progress,\n         Date insertTime, Date startTime, Date endTime, Integer httpErrorStatusCode, String httpErrorMessage,\n         String operationType, Error error, List<Warning> warnings, URI region, URI zone) {\n      return new AutoValue_Operation(id, creationTimestamp, selfLink, name, description, targetLink, targetId, clientOperationId, status,\n            statusMessage, user, progress, insertTime, startTime, endTime, httpErrorStatusCode, httpErrorMessage,\n            operationType, error != null ? error : Error.empty(), warnings, region, zone);\n   }\n\n   Operation() {\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/domain/Project.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.domain;\n\nimport static org.jclouds.googlecloud.internal.NullSafeCopies.copyOf;\n\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n/** The root collection and settings resource for all Google Compute Engine resources. */\n@AutoValue\npublic abstract class Project {\n\n   @AutoValue\n   public abstract static class UsageExportLocation {\n\n      public abstract String bucketName();\n\n      public abstract String reportNamePrefix();\n\n      @SerializedNames({\"bucketName\", \"reportNamePrefix\"})\n      public static UsageExportLocation create(String bucketName, String reporNamePrefix) {\n         return new AutoValue_Project_UsageExportLocation(bucketName, reporNamePrefix);\n      }\n\n      UsageExportLocation () {\n      }\n   }\n\n   public abstract String id();\n\n   public abstract URI selfLink();\n\n   public abstract String name();\n\n   @Nullable public abstract String description();\n\n   /** Key/value pairs available to all instances contained in this project. */\n   public abstract Metadata commonInstanceMetadata();\n\n   public abstract List<Quota> quotas();\n\n   /** Available IP addresses available for use in this project. */\n   public abstract List<String> externalIpAddresses();\n\n   public abstract Date creationTimestamp();\n\n   @Nullable public abstract UsageExportLocation usageExportLocation();\n\n   @SerializedNames(\n         { \"id\", \"selfLink\", \"name\", \"description\", \"commonInstanceMetadata\", \"quotas\", \"externalIpAddresses\", \"creationTimestamp\", \"usageExportLocation\"})\n   public static Project create(String id, URI selfLink, String name, String description,\n         Metadata commonInstanceMetadata, List<Quota> quotas, List<String> externalIpAddresses, Date creationTimestamp, UsageExportLocation usageExportLocation) {\n      return new AutoValue_Project(id, selfLink, name, description, commonInstanceMetadata, copyOf(quotas),\n            copyOf(externalIpAddresses), creationTimestamp, usageExportLocation);\n   }\n\n   Project() {\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/domain/Quota.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.domain;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n/** Quotas assigned to a given project or region. */\n@AutoValue\npublic abstract class Quota {\n\n   @Nullable public abstract String metric(); // Nullable?! really?!\n\n   public abstract double usage();\n\n   public abstract double limit();\n\n   @SerializedNames({ \"metric\", \"usage\", \"limit\" })\n   public static Quota create(String metric, double usage, double limit) {\n      return new AutoValue_Quota(metric, usage, limit);\n   }\n\n   Quota() {\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/domain/Region.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.domain;\n\nimport static org.jclouds.googlecloud.internal.NullSafeCopies.copyOf;\n\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class Region {\n\n   public enum Status {\n      UP,\n      DOWN\n   }\n\n   public abstract String id();\n\n   public abstract Date creationTimestamp();\n\n   public abstract URI selfLink();\n\n   public abstract String name();\n\n   @Nullable public abstract String description();\n\n   public abstract Status status();\n\n   public abstract List<URI> zones();\n\n   public abstract List<Quota> quotas();\n\n   @SerializedNames({ \"id\", \"creationTimestamp\", \"selfLink\", \"name\", \"description\", \"status\", \"zones\", \"quotas\" })\n   public static Region create(String id, Date creationTimestamp, URI selfLink, String name, String description, Status status, List<URI> zones,\n         List<Quota> quotas) {\n      return new AutoValue_Region(id, creationTimestamp, selfLink, name, description, status, copyOf(zones), copyOf(quotas));\n   }\n\n   Region() {\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/domain/Route.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.domain;\n\nimport static org.jclouds.googlecloud.internal.NullSafeCopies.copyOf;\n\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class Route {\n\n   public abstract String id();\n\n   public abstract Date creationTimestamp();\n\n   public abstract URI selfLink();\n\n   public abstract String name();\n\n   @Nullable public abstract String description();\n\n   public abstract URI network();\n\n   /** The set of instance items to which this route applies. */\n   public abstract List<String> tags();\n\n   /** The destination range of outgoing packets that this route applies to. */\n   public abstract String destRange();\n\n   /**\n    * The priority of this route. Priority is used to break ties in the case\n    * where there is more than one matching route of maximum length. A lower value\n    * is higher priority; a priority of 100 is higher than 200.\n    */\n   public abstract int priority();\n\n   /** The fully-qualified URL to an instance that should handle matching packets. */\n   @Nullable public abstract URI nextHopInstance();\n\n   /** The network IP address of an instance that should handle matching packets. */\n   @Nullable public abstract String nextHopIp();\n\n   /** The local network if it should handle matching packets. */\n   @Nullable public abstract URI nextHopNetwork();\n\n   /** The gateway that should handle matching packets. Currently, this is only the internet gateway. */\n   @Nullable public abstract URI nextHopGateway();\n\n   /** Potential misconfigurations are detected for this route. */\n   public abstract List<Warning> warnings();\n\n   /** The URL to a VpnTunnel that should handle matching packets. */\n   @Nullable public abstract URI nextHopVpnTunnel();\n\n   @SerializedNames(\n         { \"id\", \"creationTimestamp\", \"selfLink\", \"name\", \"description\", \"network\", \"tags\", \"destRange\", \"priority\", \"nextHopInstance\",\n               \"nextHopIp\", \"nextHopNetwork\", \"nextHopGateway\", \"warnings\", \"nextHopVpnTunnel\" })\n   public static Route create(String id, Date creationTimestamp, URI selfLink, String name, String description, URI network, List<String> tags,\n         String destRange, int priority, URI nextHopInstance, String nextHopIp, URI nextHopNetwork, URI nextHopGateway,\n         List<Warning> warnings, URI nextHopVpnTunnel) {\n      return new AutoValue_Route(id, creationTimestamp, selfLink, name, description, network, copyOf(tags), destRange, priority,\n            nextHopInstance, nextHopIp, nextHopNetwork, nextHopGateway, copyOf(warnings), nextHopVpnTunnel);\n   }\n\n   Route() {\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/domain/Snapshot.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.domain;\n\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class Snapshot {\n\n   public abstract String id();\n\n   public abstract URI selfLink();\n\n   public abstract Date creationTimestamp();\n\n   public abstract String name();\n\n   @Nullable public abstract String description();\n\n   public abstract int diskSizeGb();\n\n   public abstract String status();\n\n   /**\n    * The source disk used to insert this snapshot. Once the source disk\n    * has been deleted from the system, this field will be cleared, and will\n    * not be set even if a disk with the same name has been re-created (output only).\n    */\n   @Nullable public abstract URI sourceDisk();\n\n   /**\n    * The ID value of the disk used to insert this snapshot. This value\n    * may be used to determine whether the snapshot was taken from the current\n    * or a previous instance of a given disk name.\n    */\n   public abstract String sourceDiskId();\n\n   @Nullable public abstract Long storageBytes();\n\n   @Nullable public abstract String storageByteStatus();\n\n   @Nullable public abstract List<String> licenses();\n\n   @SerializedNames({ \"id\", \"selfLink\", \"creationTimestamp\", \"name\", \"description\", \"diskSizeGb\", \"status\",\n      \"sourceDisk\", \"sourceDiskId\", \"storageBytes\", \"storageByteStatus\", \"licenses\" })\n   public static Snapshot create(String id, URI selfLink, Date creationTimestamp, String name, String description,\n         int diskSizeGb, String status, URI sourceDisk, String sourceDiskId, Long storageBytes, String storageByteStatus, List<String> licenses) {\n      return new AutoValue_Snapshot(id, selfLink, creationTimestamp, name, description, diskSizeGb, status,\n            sourceDisk, sourceDiskId, storageBytes, storageByteStatus, licenses);\n   }\n\n   Snapshot() {\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/domain/Subnetwork.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.domain;\n\nimport java.net.URI;\nimport java.util.Date;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n/**\n * Represents a network used to enable instance communication.\n */\n@AutoValue\npublic abstract class Subnetwork {\n\n   public abstract String id();\n\n   public abstract Date creationTimestamp();\n\n   public abstract URI selfLink();\n\n   public abstract String name();\n\n   @Nullable public abstract String description();\n\n   public abstract String gatewayAddress();\n\n   public abstract URI network();\n\n   public abstract String ipCidrRange();\n\n   public abstract URI region();\n\n   @SerializedNames({ \"id\", \"creationTimestamp\", \"selfLink\", \"name\", \"description\", \"gatewayAddress\", \"network\",\n         \"ipCidrRange\", \"region\" })\n   public static Subnetwork create(String id, Date creationTimestamp, URI selfLink, String name, String description,\n         String gatewayAddress, URI network, String ipCidrRange, URI region) {\n      return new AutoValue_Subnetwork(id, creationTimestamp, selfLink, name, description, gatewayAddress, network,\n            ipCidrRange, region);\n   }\n\n   Subnetwork() {\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/domain/Tags.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.domain;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Tags for an instance or project, with their fingerprint. Each tag must be unique, must be 1-63 characters long, and\n * comply with RFC1035.\n * <p/>\n * This object is mutable and not thread-safe.\n */\n@AutoValue\npublic abstract class Tags implements Cloneable {\n   /** The fingerprint for the items - needed for updating them. */\n   @Nullable public abstract String fingerprint();\n\n   /** Immutable list of tags. */\n   public abstract ImmutableList<String> items();\n\n   public static Tags create() {\n      return Tags.create(null, null);\n   }\n\n   @SerializedNames({ \"fingerprint\", \"items\" })\n   public static Tags create(String fingerprint, ImmutableList<String> items) { // Dictates the type when created from json!\n      ImmutableList<String> empty = ImmutableList.of();\n      return new AutoValue_Tags(fingerprint, items != null ? items : empty);\n   }\n\n   Tags() {\n   }\n\n   @Override public Tags clone() {\n      return Tags.create(fingerprint(), items());\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/domain/TargetHttpProxy.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.domain;\n\nimport java.net.URI;\nimport java.util.Date;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.annotations.Beta;\n\n@AutoValue\n@Beta\npublic abstract class TargetHttpProxy {\n\n   public abstract String id();\n   public abstract Date creationTimestamp();\n   public abstract URI selfLink();\n   public abstract String name();\n   @Nullable public abstract String description();\n   public abstract URI urlMap();\n\n   @SerializedNames({\"id\", \"creationTimestamp\", \"selfLink\", \"name\", \"description\", \"urlMap\"})\n   public static TargetHttpProxy create(String id, Date creationTimestamp, URI selfLink, String name,\n         @Nullable String description, URI urlMap){\n      return new AutoValue_TargetHttpProxy(id, creationTimestamp, selfLink, name, description, urlMap);\n   }\n\n   TargetHttpProxy(){\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/domain/TargetInstance.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.domain;\n\n\nimport java.net.URI;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class TargetInstance {\n\n   public abstract String id();\n   public abstract String creationTimestamp();\n   public abstract String name();\n   @Nullable public abstract String description();\n   public abstract URI zone();\n   public abstract String natPolicy();\n   @Nullable public abstract URI instance();\n   public abstract URI selfLink();\n\n   @SerializedNames({\"id\", \"creationTimestamp\", \"name\", \"description\", \"zone\",\n      \"natPolicy\", \"instance\", \"selfLink\"})\n   public static TargetInstance create(String id, String creationTimestamp, String name,\n         String description, URI zone, String natPolicy, URI instance, URI selfLink){\n      return new AutoValue_TargetInstance(id, creationTimestamp, name, description, zone,\n            natPolicy, instance, selfLink);\n   }\n\n   TargetInstance(){\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/domain/TargetPool.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.domain;\n\nimport static org.jclouds.googlecloud.internal.NullSafeCopies.copyOf;\n\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.List;\n\nimport org.jclouds.googlecomputeengine.options.TargetPoolCreationOptions.SessionAffinityValue;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class TargetPool {\n\n   public abstract String id();\n\n   public abstract URI selfLink();\n\n   public abstract Date creationTimestamp();\n\n   public abstract String name();\n\n   @Nullable public abstract String description();\n\n   public abstract URI region();\n\n   /**\n    * URL to HttpHealthCheck resources. A member VM in this pool is considered healthy if and only if\n    * the specified health checks pass. An empty list means all member virtual machines will be considered healthy at\n    * all times but the health status of this target pool will be marked as unhealthy to indicate that no health checks\n    * are being performed.\n    */\n   public abstract List<URI> healthChecks();\n\n   /**\n    * A list of resource URLs to the member VMs serving this pool. They must live in zones contained in the same\n    * region as this pool.\n    */\n   public abstract List<URI> instances();\n\n   /**\n    * The session affinity option, determines the hash method that Google Compute Engine uses to\n    * distribute traffic.\n    */\n   @Nullable public abstract SessionAffinityValue sessionAffinity();\n\n   /**\n    * This field is applicable only when the target pool is serving a forwarding rule as the primary pool.\n    * The value of the a float between [0, 1]. If set, backupPool must also be set. Together,\n    * they define the fallback behavior of the primary target pool. If the ratio of the healthy VMs in the primary\n    * pool is at or below this number, traffic arriving at the load-balanced IP will be directed to the backup pool.\n    * In case where failoverRatio is not set or all the VMs in the backup pool are unhealthy,\n    * the traffic will be  directed back to the primary pool in the force mode, where traffic will be spread to the\n    * healthy VMs with the best effort, or to all VMs when no VM is healthy.\n    */\n   @Nullable public abstract Float failoverRatio();\n\n   /**\n    * This field is applicable only when the target pool is serving a forwarding rule as the primary pool.\n    * Must be a fully-qualified URL to a target pool that is in the same region as the primary target pool.\n    * If set, failoverRatio must also be set. Together, they define the fallback behavior of the primary target pool.\n    * If the ratio of the healthy VMs in the primary pool is at or below this number,\n    * traffic arriving at the load-balanced IP will be directed to the backup pool. In case where failoverRatio is\n    * not set or all the VMs in the backup pool are unhealthy, the traffic will be directed back to the primary pool\n    * in the force mode, where traffic will be spread to the healthy VMs with the best effort,\n    * or to all VMs when no VM is healthy.\n    */\n   @Nullable public abstract URI backupPool();\n\n   @SerializedNames({ \"id\", \"selfLink\", \"creationTimestamp\", \"name\", \"description\", \"region\", \"healthChecks\", \"instances\", \"sessionAffinity\",\n         \"failoverRatio\", \"backupPool\" })\n   public static TargetPool create(String id, URI selfLink, Date creationTimestamp, String name, String description, URI region,\n         List<URI> healthChecks, List<URI> instances, SessionAffinityValue sessionAffinity, Float failoverRatio,\n         URI backupPool) {\n      return new AutoValue_TargetPool(id, selfLink, creationTimestamp, name, description, region, copyOf(healthChecks), copyOf(instances),\n            sessionAffinity, failoverRatio, backupPool);\n   }\n\n   TargetPool() {\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/domain/UrlMap.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.domain;\n\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class UrlMap {\n\n   /**\n    * An urlMap hostRule used to filter requests based on hostname. Controls what traffic is sent to\n    * which path matcher.\n    */\n   @AutoValue\n   public abstract static class HostRule {\n      @Nullable public abstract String description();\n      public abstract List<String> hosts();\n      public abstract String pathMatcher();\n\n      @SerializedNames({ \"description\", \"hosts\", \"pathMatcher\" })\n      public static HostRule create(String description, List<String> hosts,\n                        String pathMatcher) {\n          return new AutoValue_UrlMap_HostRule(description, hosts, pathMatcher);\n       }\n\n      HostRule(){\n      }\n   }\n\n   @AutoValue\n   public abstract static class PathMatcher {\n\n      @AutoValue\n      public abstract static class PathRule{\n         public abstract List<String> paths();\n         public abstract URI service();\n\n         @SerializedNames({\"paths\", \"service\"})\n         public static PathRule create(List<String> paths, URI service) {\n            return new AutoValue_UrlMap_PathMatcher_PathRule(paths, service);\n         }\n\n         PathRule(){\n         }\n      }\n\n      public abstract String name();\n      @Nullable public abstract String description();\n      public abstract URI defaultService();\n      public abstract List<PathRule> pathRules();\n\n      @SerializedNames({ \"name\", \"description\", \"defaultService\", \"pathRules\" })\n      public static PathMatcher create(String name, @Nullable String description,\n                     URI defaultService, @Nullable List<PathRule> pathRules) {\n         return new AutoValue_UrlMap_PathMatcher(name, description, defaultService, pathRules);\n      }\n\n      PathMatcher(){\n      }\n   }\n\n   @AutoValue\n   public abstract static class UrlMapTest{\n\n      @Nullable public abstract String description();\n      public abstract String host();\n      public abstract String path();\n      public abstract URI service();\n\n      @SerializedNames({\"description\", \"host\", \"path\", \"service\"})\n      public static UrlMapTest create(@Nullable String description, String host, String path, URI service) {\n         return new AutoValue_UrlMap_UrlMapTest(description, host, path, service);\n      }\n      UrlMapTest(){\n      }\n   }\n\n   public abstract String id();\n   public abstract Date creationTimestamp();\n   public abstract URI selfLink();\n   public abstract String name();\n   @Nullable public abstract String description();\n   @Nullable public abstract List<HostRule> hostRules();\n   @Nullable public abstract List<PathMatcher> pathMatchers();\n   @Nullable public abstract List<UrlMapTest> urlMapTests();\n   public abstract URI defaultService();\n   public abstract String fingerprint();\n\n\n   @SerializedNames({\n      \"id\", \"creationTimestamp\", \"selfLink\", \"name\", \"description\", \"hostRules\", \"pathMatchers\",\n      \"tests\", \"defaultService\", \"fingerprint\"})\n   public static UrlMap create (String id, Date creationTimestamp, URI selfLink, String name,\n               @Nullable String description, @Nullable List<HostRule> hostRules,\n               @Nullable List<PathMatcher> pathMatchers,\n               @Nullable List<UrlMapTest> urlMapTests, URI defaultService,\n               @Nullable String fingerprint) {\n      return new AutoValue_UrlMap(id, creationTimestamp, selfLink, name, description, hostRules, pathMatchers,\n            urlMapTests, defaultService, fingerprint);\n   }\n\n   UrlMap(){\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/domain/UrlMapValidateResult.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.domain;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class UrlMapValidateResult {\n\n   public abstract UrlMapValidateResultInternal result();\n\n   @SerializedNames({\"result\"})\n   public static UrlMapValidateResult create(UrlMapValidateResultInternal result){\n      return new AutoValue_UrlMapValidateResult(result);\n   }\n\n   public static UrlMapValidateResult create(Boolean loadSucceeded, List<String> loadErrors,\n                              Boolean testPassed, List<UrlMapValidateResultInternal.TestFailure> testFailures) {\n      return create(UrlMapValidateResultInternal.create(loadSucceeded, loadErrors, testPassed, testFailures));\n   }\n\n   public static UrlMapValidateResult allPass(){\n      return create(true, null, true, null);\n   }\n\n   @AutoValue\n   public abstract static class UrlMapValidateResultInternal {\n\n      public abstract Boolean loadSucceeded();\n      @Nullable public abstract List<String> loadErrors();\n      @Nullable public abstract Boolean testPassed();\n      @Nullable public abstract List<TestFailure> testFailures();\n\n      @SerializedNames({\"loadSucceeded\", \"loadErrors\", \"testPassed\", \"testFailures\"})\n      public static UrlMapValidateResultInternal create(Boolean loadSucceeded, List<String> loadErrors,\n                                 Boolean testPassed, List<TestFailure> testFailures) {\n         return new AutoValue_UrlMapValidateResult_UrlMapValidateResultInternal(loadSucceeded, loadErrors, testPassed, testFailures);\n      }\n\n       UrlMapValidateResultInternal(){\n      }\n\n      @AutoValue\n      public abstract static class TestFailure {\n\n         public abstract String host();\n         public abstract String path();\n         public abstract URI expectedService();\n         public abstract URI actualService();\n\n         @SerializedNames({\"host\", \"path\", \"expectedService\", \"actualService\"})\n         public static TestFailure create(String host, String path, URI expectedService, URI actualService){\n            return new AutoValue_UrlMapValidateResult_UrlMapValidateResultInternal_TestFailure(host, path, expectedService, actualService);\n         }\n\n         TestFailure(){\n         }\n      }\n   }\n\n   UrlMapValidateResult(){\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/domain/Warning.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.domain;\n\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class Warning {\n\n   @Nullable public abstract String code();\n   @Nullable public abstract String message();\n   @Nullable public abstract List<KeyValuePair> data();\n\n   @SerializedNames({\"code\", \"message\", \"data\"})\n   public static Warning create(String code, String message, List<KeyValuePair> data){\n      return new AutoValue_Warning(code, message, data);\n   }\n\n   Warning() {\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/domain/Zone.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.domain;\n\nimport static org.jclouds.googlecloud.internal.NullSafeCopies.copyOf;\n\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class Zone {\n\n   /**\n    * Scheduled maintenance windows for the zone. When the zone is in a maintenance window,\n    * all resources which reside in the zone will be unavailable.\n    */\n   @AutoValue\n   public abstract static class MaintenanceWindow {\n\n      public abstract String name();\n\n      @Nullable public abstract String description();\n\n      public abstract Date beginTime();\n\n      public abstract Date endTime();\n\n      @SerializedNames({ \"name\", \"description\", \"beginTime\", \"endTime\" })\n      public static MaintenanceWindow create(String name, String description, Date beginTime, Date endTime) {\n         return new AutoValue_Zone_MaintenanceWindow(name, description, beginTime, endTime);\n      }\n\n      MaintenanceWindow() {\n      }\n   }\n\n   public enum Status {\n      UP,\n      DOWN\n   }\n\n   public abstract String id();\n\n   public abstract Date creationTimestamp();\n\n   public abstract URI selfLink();\n\n   public abstract String name();\n\n   @Nullable public abstract String description();\n\n   public abstract Status status();\n\n   /**\n    * Scheduled maintenance windows for the zone. When the zone is in a maintenance window,\n    * all resources which reside in the zone will be unavailable.\n    */\n   public abstract List<MaintenanceWindow> maintenanceWindows();\n\n   @Nullable public abstract Deprecated deprecated();\n\n   public abstract String region();\n\n   /** The machine types that can be used in this zone. */\n   public abstract List<String> availableMachineTypes();\n\n   @SerializedNames(\n         { \"id\", \"creationTimestamp\", \"selfLink\", \"name\", \"description\", \"status\", \"maintenanceWindows\", \"deprecated\", \"region\", \"availableMachineTypes\" })\n   public static Zone create(String id, Date creationTimestamp, URI selfLink, String name, String description, Status status,\n         List<MaintenanceWindow> maintenanceWindows, Deprecated deprecated, String region, List<String> availableMachineTypes) {\n      return new AutoValue_Zone(id, creationTimestamp, selfLink, name, description, status, copyOf(maintenanceWindows), deprecated, region,\n            copyOf(availableMachineTypes));\n   }\n\n   Zone() {\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/features/AddressApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.util.Iterator;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.QueryParam;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.GoogleComputeEngineApi;\nimport org.jclouds.googlecomputeengine.domain.Address;\nimport org.jclouds.googlecomputeengine.domain.Operation;\nimport org.jclouds.googlecomputeengine.internal.BaseCallerArg0ToIteratorOfListPage;\nimport org.jclouds.googlecomputeengine.options.AddressCreationOptions;\nimport org.jclouds.googlecomputeengine.options.ListOptions;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SkipEncoding;\nimport org.jclouds.rest.annotations.Transform;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport com.google.common.base.Function;\n\n@SkipEncoding({'/', '='})\n@RequestFilters(OAuthFilter.class)\n@Path(\"/addresses\")\n@Consumes(APPLICATION_JSON)\npublic interface AddressApi {\n\n   /** Returns an address by name or null if not found. */\n   @Named(\"Addresses:get\")\n   @GET\n   @Path(\"/{address}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Address get(@PathParam(\"address\") String address);\n\n   /**\n    * Creates an address resource in the specified project specifying the size of the address.\n    *\n    * @param address the name of address.\n    * @return an Operation resource. To check on the status of an operation, poll the Operations resource returned to\n    *         you, and look for the status field.\n    */\n   @Named(\"Addresses:insert\")\n   @POST\n   @Produces(APPLICATION_JSON)\n   @MapBinder(BindToJsonPayload.class)\n   Operation create(@PayloadParam(\"name\") String address);\n\n   /** @see #create(String) */\n   @Named(\"Addresses:insert\")\n   @POST\n   @Produces(APPLICATION_JSON)\n   Operation create(@BinderParam(BindToJsonPayload.class) AddressCreationOptions options);\n\n   /** Deletes an address by name and returns the operation in progress, or null if not found. */\n   @Named(\"Addresses:delete\")\n   @DELETE\n   @Path(\"/{address}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Operation delete(@PathParam(\"address\") String address);\n\n   /**\n    * Retrieves the list of address resources available to the specified project.\n    * By default the list as a maximum size of 100, if no options are provided or ListOptions#getMaxResults() has not\n    * been set.\n    *\n    * @param pageToken   marks the beginning of the next list page\n    * @param listOptions listing options\n    * @return a page of the list\n    */\n   @Named(\"Addresses:list\")\n   @GET\n   ListPage<Address> listPage(@Nullable @QueryParam(\"pageToken\") String pageToken, ListOptions listOptions);\n\n   /** @see #listPage(String, ListOptions) */\n   @Named(\"Addresses:list\")\n   @GET\n   @Transform(AddressPages.class)\n   Iterator<ListPage<Address>> list();\n\n   /** @see #listPage(String, ListOptions) */\n   @Named(\"Addresses:list\")\n   @GET\n   @Transform(AddressPages.class)\n   Iterator<ListPage<Address>> list(ListOptions options);\n\n   static final class AddressPages extends BaseCallerArg0ToIteratorOfListPage<Address, AddressPages> {\n\n      private final GoogleComputeEngineApi api;\n\n      @Inject AddressPages(GoogleComputeEngineApi api) {\n         this.api = api;\n      }\n\n      @Override\n      protected Function<String, ListPage<Address>> fetchNextPage(final String regionName, final ListOptions options) {\n         return new Function<String, ListPage<Address>>() {\n            @Override public ListPage<Address> apply(String pageToken) {\n               return api.addressesInRegion(regionName).listPage(pageToken, options);\n            }\n         };\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/features/AggregatedListApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.util.Iterator;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.QueryParam;\n\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.GoogleComputeEngineApi;\nimport org.jclouds.googlecomputeengine.domain.Address;\nimport org.jclouds.googlecomputeengine.domain.Disk;\nimport org.jclouds.googlecomputeengine.domain.DiskType;\nimport org.jclouds.googlecomputeengine.domain.ForwardingRule;\nimport org.jclouds.googlecomputeengine.domain.Instance;\nimport org.jclouds.googlecomputeengine.domain.MachineType;\nimport org.jclouds.googlecomputeengine.domain.Operation;\nimport org.jclouds.googlecomputeengine.domain.Subnetwork;\nimport org.jclouds.googlecomputeengine.domain.TargetInstance;\nimport org.jclouds.googlecomputeengine.domain.TargetPool;\nimport org.jclouds.googlecomputeengine.internal.BaseToIteratorOfListPage;\nimport org.jclouds.googlecomputeengine.options.ListOptions;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SkipEncoding;\nimport org.jclouds.rest.annotations.Transform;\n\nimport com.google.common.base.Function;\n\n@SkipEncoding({ '/', '=' })\n@RequestFilters(OAuthFilter.class)\n@Path(\"/aggregated\")\n@Consumes(APPLICATION_JSON)\npublic interface AggregatedListApi {\n\n   /**\n    * Retrieves the list of machine type resources available to the specified\n    * project. By default the list as a maximum size of 100, if no options are\n    * provided or ListOptions#getMaxResults() has not been set.\n    *\n    * @param pageToken\n    *           marks the beginning of the next list page\n    * @param listOptions\n    *           listing options\n    * @return a page of the list\n    */\n   @Named(\"MachineTypes:aggregatedList\")\n   @GET\n   @Path(\"/machineTypes\")\n   ListPage<MachineType> pageOfMachineTypes(@Nullable @QueryParam(\"pageToken\") String pageToken, ListOptions listOptions);\n\n   /** @see #pageOfMachineTypes(String, ListOptions) */\n   @Named(\"MachineTypes:aggregatedList\")\n   @GET\n   @Path(\"/machineTypes\")\n   @Transform(MachineTypePages.class)\n   Iterator<ListPage<MachineType>> machineTypes();\n\n   /** @see #pageOfMachineTypes(String, ListOptions) */\n   @Named(\"MachineTypes:aggregatedList\")\n   @GET\n   @Path(\"/machineTypes\")\n   @Transform(MachineTypePages.class)\n   Iterator<ListPage<MachineType>> machineTypes(ListOptions options);\n\n   static final class MachineTypePages extends BaseToIteratorOfListPage<MachineType, MachineTypePages> {\n      private final GoogleComputeEngineApi api;\n\n      @Inject\n      MachineTypePages(GoogleComputeEngineApi api) {\n         this.api = api;\n      }\n\n      @Override\n      protected Function<String, ListPage<MachineType>> fetchNextPage(final ListOptions options) {\n         return new Function<String, ListPage<MachineType>>() {\n            @Override\n            public ListPage<MachineType> apply(String pageToken) {\n               return api.aggregatedList().pageOfMachineTypes(pageToken, options);\n            }\n         };\n      }\n   }\n\n   /**\n    * Retrieves the list of instance resources available to the specified\n    * project. By default the list as a maximum size of 100, if no options are\n    * provided or ListOptions#getMaxResults() has not been set.\n    *\n    * @param pageToken\n    *           marks the beginning of the next list page\n    * @param listOptions\n    *           listing options\n    * @return a page of the list\n    */\n   @Named(\"Instances:aggregatedList\")\n   @GET\n   @Path(\"/instances\")\n   ListPage<Instance> pageOfInstances(@Nullable @QueryParam(\"pageToken\") String pageToken, ListOptions listOptions);\n\n   /** @see #pageOfInstances(String, ListOptions) */\n   @Named(\"Instances:aggregatedList\")\n   @GET\n   @Path(\"/instances\")\n   @Transform(InstancePages.class)\n   Iterator<ListPage<Instance>> instances();\n\n   /** @see #pageOfInstances(String, ListOptions) */\n   @Named(\"Instances:aggregatedList\")\n   @GET\n   @Path(\"/instances\")\n   @Transform(InstancePages.class)\n   Iterator<ListPage<Instance>> instances(ListOptions options);\n\n   static final class InstancePages extends BaseToIteratorOfListPage<Instance, InstancePages> {\n      private final GoogleComputeEngineApi api;\n\n      @Inject\n      InstancePages(GoogleComputeEngineApi api) {\n         this.api = api;\n      }\n\n      @Override\n      protected Function<String, ListPage<Instance>> fetchNextPage(final ListOptions options) {\n         return new Function<String, ListPage<Instance>>() {\n            @Override\n            public ListPage<Instance> apply(String pageToken) {\n               return api.aggregatedList().pageOfInstances(pageToken, options);\n            }\n         };\n      }\n   }\n\n   /**\n    * Retrieves the list of address resources available to the specified\n    * project. By default the list as a maximum size of 100, if no options are\n    * provided or ListOptions#getMaxResults() has not been set.\n    *\n    * @param pageToken\n    *           marks the beginning of the next list page\n    * @param listOptions\n    *           listing options\n    * @return a page of the list\n    */\n   @Named(\"Addresses:aggregatedList\")\n   @GET\n   @Path(\"/addresses\")\n   ListPage<Address> pageOfAddresses(@Nullable @QueryParam(\"pageToken\") String pageToken, ListOptions listOptions);\n\n   /** @see #pageOfAddresses(String, ListOptions) */\n   @Named(\"Addresses:aggregatedList\")\n   @GET\n   @Path(\"/addresses\")\n   @Transform(AddressPages.class)\n   Iterator<ListPage<Address>> addresses();\n\n   /** @see #pageOfAddresses(String, ListOptions) */\n   @Named(\"Addresses:aggregatedList\")\n   @GET\n   @Path(\"/addresses\")\n   @Transform(AddressPages.class)\n   Iterator<ListPage<Address>> addresses(ListOptions options);\n\n   static final class AddressPages extends BaseToIteratorOfListPage<Address, AddressPages> {\n      private final GoogleComputeEngineApi api;\n\n      @Inject\n      AddressPages(GoogleComputeEngineApi api) {\n         this.api = api;\n      }\n\n      @Override\n      protected Function<String, ListPage<Address>> fetchNextPage(final ListOptions options) {\n         return new Function<String, ListPage<Address>>() {\n            @Override\n            public ListPage<Address> apply(String pageToken) {\n               return api.aggregatedList().pageOfAddresses(pageToken, options);\n            }\n         };\n      }\n   }\n\n   /**\n    * Retrieves the list of disk resources available to the specified project.\n    * By default the list as a maximum size of 100, if no options are provided\n    * or ListOptions#getMaxResults() has not been set.\n    *\n    * @param pageToken\n    *           marks the beginning of the next list page\n    * @param listOptions\n    *           listing options\n    * @return a page of the list\n    */\n   @Named(\"Disks:aggregatedList\")\n   @GET\n   @Path(\"/disks\")\n   ListPage<Disk> pageOfDisks(@Nullable @QueryParam(\"pageToken\") String pageToken, ListOptions listOptions);\n\n   /** @see #pageOfDisks(String, ListOptions) */\n   @Named(\"Disks:aggregatedList\")\n   @GET\n   @Path(\"/disks\")\n   @Transform(DiskPages.class)\n   Iterator<ListPage<Disk>> disks();\n\n   /** @see #pageOfDisks(String, ListOptions) */\n   @Named(\"Disks:aggregatedList\")\n   @GET\n   @Path(\"/disks\")\n   @Transform(DiskPages.class)\n   Iterator<ListPage<Disk>> disks(ListOptions options);\n\n   static final class DiskPages extends BaseToIteratorOfListPage<Disk, DiskPages> {\n      private final GoogleComputeEngineApi api;\n\n      @Inject\n      DiskPages(GoogleComputeEngineApi api) {\n         this.api = api;\n      }\n\n      @Override\n      protected Function<String, ListPage<Disk>> fetchNextPage(final ListOptions options) {\n         return new Function<String, ListPage<Disk>>() {\n            @Override\n            public ListPage<Disk> apply(String pageToken) {\n               return api.aggregatedList().pageOfDisks(pageToken, options);\n            }\n         };\n      }\n   }\n\n   /**\n    * Retrieves the list of disk type resources available to the specified\n    * project. By default the list as a maximum size of 100, if no options are\n    * provided or ListOptions#getMaxResults() has not been set.\n    *\n    * @param pageToken\n    *           marks the beginning of the next list page\n    * @param listOptions\n    *           listing options\n    * @return a page of the list\n    */\n   @Named(\"DiskTypes:aggregatedList\")\n   @GET\n   @Path(\"/diskTypes\")\n   ListPage<DiskType> pageOfDiskTypes(@Nullable @QueryParam(\"pageToken\") String pageToken, ListOptions listOptions);\n\n   /** @see #pageOfDiskTypes(String, ListOptions) */\n   @Named(\"DiskTypes:aggregatedList\")\n   @GET\n   @Path(\"/diskTypes\")\n   @Transform(DiskTypePages.class)\n   Iterator<ListPage<DiskType>> diskTypes();\n\n   /** @see #pageOfDiskTypes(String, ListOptions) */\n   @Named(\"DiskTypes:aggregatedList\")\n   @GET\n   @Path(\"/diskTypes\")\n   @Transform(DiskTypePages.class)\n   Iterator<ListPage<DiskType>> diskTypes(ListOptions options);\n\n   static final class DiskTypePages extends BaseToIteratorOfListPage<DiskType, DiskTypePages> {\n      private final GoogleComputeEngineApi api;\n\n      @Inject\n      DiskTypePages(GoogleComputeEngineApi api) {\n         this.api = api;\n      }\n\n      @Override\n      protected Function<String, ListPage<DiskType>> fetchNextPage(final ListOptions options) {\n         return new Function<String, ListPage<DiskType>>() {\n            @Override\n            public ListPage<DiskType> apply(String pageToken) {\n               return api.aggregatedList().pageOfDiskTypes(pageToken, options);\n            }\n         };\n      }\n   }\n\n   /**\n    * Retrieves the list of global operations resources available to the\n    * specified project. By default the list as a maximum size of 100, if no\n    * options are provided or ListOptions#getMaxResults() has not been set.\n    *\n    * @param pageToken\n    *           marks the beginning of the next list page\n    * @param listOptions\n    *           listing options\n    * @return a page of the list\n    */\n   @Named(\"GlobalOperations:aggregatedList\")\n   @GET\n   @Path(\"/operations\")\n   ListPage<Operation> pageOfGlobalOperations(@Nullable @QueryParam(\"pageToken\") String pageToken,\n         ListOptions listOptions);\n\n   /** @see #pageOfGlobalOperations(String, ListOptions) */\n   @Named(\"GlobalOperations:aggregatedList\")\n   @GET\n   @Path(\"/operations\")\n   @Transform(OperationPages.class)\n   Iterator<ListPage<Operation>> globalOperations();\n\n   /** @see #pageOfGlobalOperations(String, ListOptions) */\n   @Named(\"GlobalOperations:aggregatedList\")\n   @GET\n   @Path(\"/operations\")\n   @Transform(OperationPages.class)\n   Iterator<ListPage<Operation>> globalOperations(ListOptions options);\n\n   static final class OperationPages extends BaseToIteratorOfListPage<Operation, OperationPages> {\n      private final GoogleComputeEngineApi api;\n\n      @Inject\n      OperationPages(GoogleComputeEngineApi api) {\n         this.api = api;\n      }\n\n      @Override\n      protected Function<String, ListPage<Operation>> fetchNextPage(final ListOptions options) {\n         return new Function<String, ListPage<Operation>>() {\n            @Override\n            public ListPage<Operation> apply(String pageToken) {\n               return api.aggregatedList().pageOfGlobalOperations(pageToken, options);\n            }\n         };\n      }\n   }\n\n   /**\n    * Retrieves the list of forwarding rule resources available to the\n    * specified project. By default the list as a maximum size of 100, if no\n    * options are provided or ListOptions#getMaxResults() has not been set.\n    *\n    * @param pageToken\n    *           marks the beginning of the next list page\n    * @param listOptions\n    *           listing options\n    * @return a page of the list\n    */\n   @Named(\"ForwardingRules:aggregatedList\")\n   @GET\n   @Path(\"/forwardingRules\")\n   ListPage<ForwardingRule> pageOfForwardingRules(@Nullable @QueryParam(\"pageToken\") String pageToken,\n         ListOptions listOptions);\n\n   /** @see #pageOfForwardingRules(String, ListOptions) */\n   @Named(\"ForwardingRules:aggregatedList\")\n   @GET\n   @Path(\"/forwardingRules\")\n   @Transform(ForwardingRulePages.class)\n   Iterator<ListPage<ForwardingRule>> forwardingRules();\n\n   /** @see #pageOfForwardingRules(String, ListOptions) */\n   @Named(\"ForwardingRule:aggregatedList\")\n   @GET\n   @Path(\"/forwardingRules\")\n   @Transform(ForwardingRulePages.class)\n   Iterator<ListPage<ForwardingRule>> forwardingRules(ListOptions options);\n\n   static final class ForwardingRulePages extends BaseToIteratorOfListPage<ForwardingRule, ForwardingRulePages> {\n      private final GoogleComputeEngineApi api;\n\n      @Inject\n      ForwardingRulePages(GoogleComputeEngineApi api) {\n         this.api = api;\n      }\n\n      @Override\n      protected Function<String, ListPage<ForwardingRule>> fetchNextPage(final ListOptions options) {\n         return new Function<String, ListPage<ForwardingRule>>() {\n            @Override\n            public ListPage<ForwardingRule> apply(String pageToken) {\n               return api.aggregatedList().pageOfForwardingRules(pageToken, options);\n            }\n         };\n      }\n   }\n\n   /**\n    * Retrieves the list of TargetInstance resources available to the\n    * specified project. By default the list as a maximum size of 100, if no\n    * options are provided or ListOptions#getMaxResults() has not been set.\n    *\n    * @param pageToken\n    *           marks the beginning of the next list page\n    * @param listOptions\n    *           listing options\n    * @return a page of the list\n    */\n   @Named(\"TargetInstances:aggregatedList\")\n   @GET\n   @Path(\"/targetInstances\")\n   ListPage<TargetInstance> pageOfTargetInstances(@Nullable @QueryParam(\"pageToken\") String pageToken,\n         ListOptions listOptions);\n\n   /** @see #pageOfTargetInstances(String, ListOptions) */\n   @Named(\"TargetInstances:aggregatedList\")\n   @GET\n   @Path(\"/targetInstances\")\n   @Transform(TargetInstancePages.class)\n   Iterator<ListPage<TargetInstance>> targetInstances();\n\n   /** @see #pageOfTargetInstances(String, ListOptions) */\n   @Named(\"TargetInstances:aggregatedList\")\n   @GET\n   @Path(\"/targetInstances\")\n   @Transform(TargetInstancePages.class)\n   Iterator<ListPage<TargetInstance>> targetInstances(ListOptions options);\n\n   static final class TargetInstancePages extends BaseToIteratorOfListPage<TargetInstance, TargetInstancePages> {\n      private final GoogleComputeEngineApi api;\n\n      @Inject\n      TargetInstancePages(GoogleComputeEngineApi api) {\n         this.api = api;\n      }\n\n      @Override\n      protected Function<String, ListPage<TargetInstance>> fetchNextPage(final ListOptions options) {\n            return new Function<String, ListPage<TargetInstance>>() {\n               @Override\n               public ListPage<TargetInstance> apply(String pageToken) {\n                  return api.aggregatedList().pageOfTargetInstances(pageToken, options);\n               }\n            };\n      }\n   }\n\n   /**\n    * Retrieves the list of TargetPool resources available to the\n    * specified project. By default the list as a maximum size of 100, if no\n    * options are provided or ListOptions#getMaxResults() has not been set.\n    *\n    * @param pageToken\n    *           marks the beginning of the next list page\n    * @param listOptions\n    *           listing options\n    * @return a page of the list\n    */\n   @Named(\"TargetPool:aggregatedList\")\n   @GET\n   @Path(\"/targetPools\")\n   ListPage<TargetPool> pageOfTargetPools(@Nullable @QueryParam(\"pageToken\") String pageToken,\n         ListOptions listOptions);\n\n   /** @see #pageOfTargetPools(String, ListOptions) */\n   @Named(\"TargetPool:aggregatedList\")\n   @GET\n   @Path(\"/targetPools\")\n   @Transform(TargetPoolPages.class)\n   Iterator<ListPage<TargetPool>> targetPools();\n\n   /** @see #pageOfTargetPools(String, ListOptions) */\n   @Named(\"TargetPool:aggregatedList\")\n   @GET\n   @Path(\"/targetPools\")\n   @Transform(TargetPoolPages.class)\n   Iterator<ListPage<TargetPool>> targetPools(ListOptions options);\n\n   static final class TargetPoolPages extends BaseToIteratorOfListPage<TargetPool, TargetPoolPages> {\n      private final GoogleComputeEngineApi api;\n\n      @Inject\n      TargetPoolPages(GoogleComputeEngineApi api) {\n         this.api = api;\n      }\n\n      @Override\n      protected Function<String, ListPage<TargetPool>> fetchNextPage(final ListOptions options) {\n            return new Function<String, ListPage<TargetPool>>() {\n               @Override\n               public ListPage<TargetPool> apply(String pageToken) {\n                  return api.aggregatedList().pageOfTargetPools(pageToken, options);\n               }\n            };\n      }\n   }\n\n   /**\n    * Retrieves the list of instance resources available to the specified\n    * project. By default the list as a maximum size of 100, if no options are\n    * provided or ListOptions#getMaxResults() has not been set.\n    *\n    * @param pageToken\n    *           marks the beginning of the next list page\n    * @param listOptions\n    *           listing options\n    * @return a page of the list\n    */\n   @Named(\"Subnetworks:aggregatedList\")\n   @GET\n   @Path(\"/subnetworks\")\n   ListPage<Subnetwork> pageOfSubnetworks(@Nullable @QueryParam(\"pageToken\") String pageToken, ListOptions listOptions);\n\n   /** @see #pageOfSubnetworks(String, ListOptions) */\n   @Named(\"Subnetworks:aggregatedList\")\n   @GET\n   @Path(\"/subnetworks\")\n   @Transform(SubnetworksPages.class)\n   Iterator<ListPage<Subnetwork>> subnetworks();\n\n   /** @see #pageOfSubnetworks(String, ListOptions) */\n   @Named(\"Subnetworks:aggregatedList\")\n   @GET\n   @Path(\"/subnetworks\")\n   @Transform(SubnetworksPages.class)\n   Iterator<ListPage<Subnetwork>> subnetworks(ListOptions options);\n\n   static final class SubnetworksPages extends BaseToIteratorOfListPage<Subnetwork, SubnetworksPages> {\n      private final GoogleComputeEngineApi api;\n\n      @Inject\n      SubnetworksPages(GoogleComputeEngineApi api) {\n         this.api = api;\n      }\n\n      @Override\n      protected Function<String, ListPage<Subnetwork>> fetchNextPage(final ListOptions options) {\n         return new Function<String, ListPage<Subnetwork>>() {\n            @Override\n            public ListPage<Subnetwork> apply(String pageToken) {\n               return api.aggregatedList().pageOfSubnetworks(pageToken, options);\n            }\n         };\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/features/BackendServiceApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.net.URI;\nimport java.util.Iterator;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.QueryParam;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.GoogleComputeEngineApi;\nimport org.jclouds.googlecomputeengine.domain.BackendService;\nimport org.jclouds.googlecomputeengine.domain.HealthStatus;\nimport org.jclouds.googlecomputeengine.domain.Operation;\nimport org.jclouds.googlecomputeengine.internal.BaseToIteratorOfListPage;\nimport org.jclouds.googlecomputeengine.options.BackendServiceOptions;\nimport org.jclouds.googlecomputeengine.options.ListOptions;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PATCH;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SkipEncoding;\nimport org.jclouds.rest.annotations.Transform;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport com.google.common.base.Function;\n\n@SkipEncoding({'/', '='})\n@RequestFilters(OAuthFilter.class)\n@Consumes(APPLICATION_JSON)\npublic interface BackendServiceApi {\n   /**\n    * Returns the specified backend service resource.\n    *\n    * @param backendServiceName name of the backend service resource to return.\n    * @return a BackendService resource.\n    */\n   @Named(\"BackendServices:get\")\n   @GET\n   @Path(\"/{backendService}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   BackendService get(@PathParam(\"backendService\") String backendServiceName);\n\n   /**\n    * Creates a backend service resource in the specified project using the data\n    * included in the request.\n    *\n    * @param backendService  options for this backend service.\n    * @return an Operation resource. To check on the status of an operation,\n    *         poll the Operations resource returned to you, and look for the\n    *         status field.\n    */\n   @Named(\"BackendServices:insert\")\n   @POST\n   @Produces(APPLICATION_JSON)\n   Operation create(@BinderParam(BindToJsonPayload.class) BackendServiceOptions backendService);\n\n   /**\n    * Updates the specified backend service resource with the data included in\n    * the request.\n    *\n    * @param backendServiceName    the name backend service to be updated.\n    * @param backendServiceOptions the new backend service.\n    * @return an Operation resource. To check on the status of an operation,\n    *         poll the Operations resource returned to you, and look for the\n    *         status field.\n    */\n   @Named(\"BackendServices:update\")\n   @PUT\n   @Produces(APPLICATION_JSON)\n   @Path(\"/{backendService}\")\n   Operation update(@PathParam(\"backendService\") String backendServiceName,\n                    @BinderParam(BindToJsonPayload.class) BackendServiceOptions backendServiceOptions);\n\n   /**\n    * Updates the specified backend service resource, with patch semantics, with\n    * the data included in the request.\n    *\n    * @param backendServiceName    the name backend service to be updated.\n    * @param backendServiceOptions the new backend service.\n    * @return an Operation resource. To check on the status of an operation,\n    *         poll the Operations resource returned to you, and look for the\n    *         status field.\n    */\n   @Named(\"BackendServices:patch\")\n   @PATCH\n   @Produces(APPLICATION_JSON)\n   @Path(\"/{backendService}\")\n   Operation patch(@PathParam(\"backendService\") String backendServiceName,\n                   @BinderParam(BindToJsonPayload.class) BackendServiceOptions backendServiceOptions);\n\n   /**\n    * Gets the most recent health check results for this backend service. Note\n    * that health check results will only be returned if the backend service has\n    *  a valid global forwarding rule referencing it.\n    *\n    * @param backendServiceName    the name backend service to get health stats on.\n    * @param group                 the group in the backend service to get health stats on.\n    * @return a BackendServiceGroupHealth resource denoting the health states of\n    *         instances in the specified group.\n    */\n   @Named(\"BackendServices:getHealth\")\n   @POST\n   @Produces(APPLICATION_JSON)\n   @Path(\"/{backendService}/getHealth\")\n   @MapBinder(BindToJsonPayload.class)\n   HealthStatus getHealth(@PathParam(\"backendService\") String backendServiceName,\n                                       @PayloadParam(\"group\") URI group);\n\n   /**\n    * Deletes the specified backend service resource.\n    *\n    * @param backendServiceName  name of the backend service resource to delete.\n    * @return an Operation resource. To check on the status of an operation,\n    *         poll the Operations resource returned to you, and look for the\n    *         status field.\n    */\n   @Named(\"BackendServices:delete\")\n   @DELETE\n   @Path(\"/{backendService}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   Operation delete(@PathParam(\"backendService\") String backendServiceName);\n\n   /**\n    * Retrieves the list of backend service resources available to the specified\n    * project. By default the list as a maximum size of 100, if no options are\n    * provided or ListOptions#getMaxResults() has not been set.\n    *\n    * @param pageToken   marks the beginning of the next list page\n    * @param listOptions listing options\n    * @return a page of the list\n    */\n   @Named(\"BackendServices:list\")\n   @GET\n   ListPage<BackendService> listPage(@QueryParam(\"pageToken\") @Nullable String pageToken, ListOptions options);\n\n   /** @see #listPage(String, ListOptions) */\n   @Named(\"BackendServices:list\")\n   @GET\n   @Transform(BackendServicePages.class)\n   Iterator<ListPage<BackendService>> list();\n\n   /** @see #listPage(String, ListOptions) */\n   @Named(\"BackendServices:list\")\n   @GET\n   @Transform(BackendServicePages.class)\n   Iterator<ListPage<BackendService>> list(ListOptions options);\n\n   static final class BackendServicePages extends BaseToIteratorOfListPage<BackendService, BackendServicePages> {\n\n      private final GoogleComputeEngineApi api;\n\n      @Inject BackendServicePages(GoogleComputeEngineApi api) {\n         this.api = api;\n      }\n\n      @Override protected Function<String, ListPage<BackendService>> fetchNextPage(final ListOptions options) {\n         return new Function<String, ListPage<BackendService>>() {\n            @Override public ListPage<BackendService> apply(String pageToken) {\n               return api.backendServices().listPage(pageToken, options);\n            }\n         };\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/features/DiskApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.util.Iterator;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.QueryParam;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.GoogleComputeEngineApi;\nimport org.jclouds.googlecomputeengine.binders.DiskCreationBinder;\nimport org.jclouds.googlecomputeengine.domain.Disk;\nimport org.jclouds.googlecomputeengine.domain.Operation;\nimport org.jclouds.googlecomputeengine.internal.BaseCallerArg0ToIteratorOfListPage;\nimport org.jclouds.googlecomputeengine.options.DiskCreationOptions;\nimport org.jclouds.googlecomputeengine.options.ListOptions;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SkipEncoding;\nimport org.jclouds.rest.annotations.Transform;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport com.google.common.base.Function;\n\n@SkipEncoding({'/', '='})\n@RequestFilters(OAuthFilter.class)\n@Path(\"/disks\")\n@Consumes(APPLICATION_JSON)\npublic interface DiskApi {\n\n   /** Returns a persistent disk by name or null if not found. */\n   @Named(\"Disks:get\")\n   @GET\n   @Path(\"/{disk}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Disk get(@PathParam(\"disk\") String disk);\n\n   /**\n    * Creates a persistent disk resource, in the specified project, specifying the size of the disk and other options.\n    *\n    * @param diskName the name of disk.\n    * @param sizeGb   the size of the disk\n    * @param options the options of the disk to create.\n    * @return an Operation resource. To check on the status of an operation, poll the Operations resource returned to\n    *         you, and look for the status field.\n    */\n   @Named(\"Disks:insert\")\n   @POST\n   @Produces(APPLICATION_JSON)\n   @MapBinder(DiskCreationBinder.class)\n   Operation create(@PayloadParam(\"name\") String diskName,\n                    @PayloadParam(\"options\") DiskCreationOptions options);\n\n   /**\n    * Creates a persistent disk resource, in the specified project, specifying the size of the disk and other options.\n    *\n    * @param diskName the name of disk.\n    * @param sourceImage Fully-qualified URL of the source image to apply to the disk.\n    * @param options the options of the disk to create.\n    * @return an Operation resource. To check on the status of an operation, poll the Operations resource returned to\n    *         you, and look for the status field.\n    */\n   @Named(\"Disks:insert\")\n   @POST\n   @Produces(APPLICATION_JSON)\n   @MapBinder(DiskCreationBinder.class)\n   Operation create(@PayloadParam(\"name\") String diskName,\n                    @QueryParam(\"sourceImage\") String sourceImage,\n                    @PayloadParam(\"options\") DiskCreationOptions options);\n\n   /** Deletes a persistent disk by name and returns the operation in progress, or null if not found. */\n   @Named(\"Disks:delete\")\n   @DELETE\n   @Path(\"/{disk}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Operation delete(@PathParam(\"disk\") String disk);\n\n   /**\n    * Create a snapshot of a given disk in a zone.\n    *\n    * @param diskName the name of the disk.\n    * @param snapshotName the name for the snapshot to be created.\n    *\n    * @return an Operation resource. To check on the status of an operation, poll the Operations resource returned to\n    *         you, and look for the status field.\n    */\n   @Named(\"Disks:createSnapshot\")\n   @POST\n   @Path(\"/{disk}/createSnapshot\")\n   @MapBinder(BindToJsonPayload.class)\n   Operation createSnapshot(@PathParam(\"disk\") String diskName, @PayloadParam(\"name\") String snapshotName);\n\n   /** @see #createSnapshot(String, String) */\n   @Named(\"Disks:createSnapshot\")\n   @POST\n   @Path(\"/{disk}/createSnapshot\")\n   @MapBinder(BindToJsonPayload.class)\n   Operation createSnapshot(@PathParam(\"disk\") String diskName, @PayloadParam(\"name\") String snapshotName,\n         @PayloadParam(\"description\") String description);\n\n   /**\n    * Retrieves the list of persistent disk resources available to the specified project.\n    * By default the list as a maximum size of 100, if no options are provided or ListOptions#getMaxResults() has not\n    * been set.\n    *\n    * @param pageToken   marks the beginning of the next list page\n    * @param listOptions listing options\n    * @return a page of the list\n    */\n   @Named(\"Disks:list\")\n   @GET\n   ListPage<Disk> listPage(@Nullable @QueryParam(\"pageToken\") String pageToken, ListOptions listOptions);\n\n   /** @see #listPage(String, ListOptions) */\n   @Named(\"Disks:list\")\n   @GET\n   @Transform(DiskPages.class)\n   Iterator<ListPage<Disk>> list();\n\n   /** @see #listPage(String, ListOptions) */\n   @Named(\"Disks:list\")\n   @GET\n   @Transform(DiskPages.class)\n   Iterator<ListPage<Disk>> list(ListOptions options);\n\n   static final class DiskPages extends BaseCallerArg0ToIteratorOfListPage<Disk, DiskPages> {\n\n      private final GoogleComputeEngineApi api;\n\n      @Inject DiskPages(GoogleComputeEngineApi api) {\n         this.api = api;\n      }\n\n      @Override\n      protected Function<String, ListPage<Disk>> fetchNextPage(final String zoneName, final ListOptions options) {\n         return new Function<String, ListPage<Disk>>() {\n            @Override public ListPage<Disk> apply(String pageToken) {\n               return api.disksInZone(zoneName).listPage(pageToken, options);\n            }\n         };\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/features/DiskTypeApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.util.Iterator;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.QueryParam;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.GoogleComputeEngineApi;\nimport org.jclouds.googlecomputeengine.domain.DiskType;\nimport org.jclouds.googlecomputeengine.internal.BaseCallerArg0ToIteratorOfListPage;\nimport org.jclouds.googlecomputeengine.options.ListOptions;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SkipEncoding;\nimport org.jclouds.rest.annotations.Transform;\n\nimport com.google.common.base.Function;\n\n@SkipEncoding({'/', '='})\n@RequestFilters(OAuthFilter.class)\n@Path(\"/diskTypes\")\n@Consumes(APPLICATION_JSON)\npublic interface DiskTypeApi {\n\n   /** Returns a disk type by name or null if not found. */\n   @Named(\"DiskTypes:get\")\n   @GET\n   @Path(\"/{diskType}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   DiskType get(@PathParam(\"diskType\") String diskType);\n\n   /**\n    * Retrieves the list of disk type resources available to the specified project.\n    * By default the list as a maximum size of 100, if no options are provided or ListOptions#getMaxResults() has not\n    * been set.\n    *\n    * @param pageToken   marks the beginning of the next list page\n    * @param listOptions listing options\n    * @return a page of the list\n    */\n   @Named(\"DiskTypes:list\")\n   @GET\n   ListPage<DiskType> listPage(@Nullable @QueryParam(\"pageToken\") String pageToken, ListOptions listOptions);\n\n   /** @see #listPage(String, ListOptions) */\n   @Named(\"DiskTypes:list\")\n   @GET\n   @Transform(DiskTypePages.class)\n   Iterator<ListPage<DiskType>> list();\n\n   /** @see #listPage(String, ListOptions) */\n   @Named(\"DiskTypes:list\")\n   @GET\n   @Transform(DiskTypePages.class)\n   Iterator<ListPage<DiskType>> list(ListOptions options);\n\n   static final class DiskTypePages extends BaseCallerArg0ToIteratorOfListPage<DiskType, DiskTypePages> {\n\n      private final GoogleComputeEngineApi api;\n\n      @Inject DiskTypePages(GoogleComputeEngineApi api) {\n         this.api = api;\n      }\n\n      @Override\n      protected Function<String, ListPage<DiskType>> fetchNextPage(final String zoneName, final ListOptions options) {\n         return new Function<String, ListPage<DiskType>>() {\n            @Override public ListPage<DiskType> apply(String pageToken) {\n               return api.diskTypesInZone(zoneName).listPage(pageToken, options);\n            }\n         };\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/features/FirewallApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.net.URI;\nimport java.util.Iterator;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.QueryParam;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.GoogleComputeEngineApi;\nimport org.jclouds.googlecomputeengine.binders.FirewallBinder;\nimport org.jclouds.googlecomputeengine.domain.Firewall;\nimport org.jclouds.googlecomputeengine.domain.Operation;\nimport org.jclouds.googlecomputeengine.internal.BaseToIteratorOfListPage;\nimport org.jclouds.googlecomputeengine.options.FirewallOptions;\nimport org.jclouds.googlecomputeengine.options.ListOptions;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PATCH;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SkipEncoding;\nimport org.jclouds.rest.annotations.Transform;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport com.google.common.base.Function;\n\n@SkipEncoding({'/', '='})\n@RequestFilters(OAuthFilter.class)\n@Path(\"/firewalls\")\n@Consumes(APPLICATION_JSON)\npublic interface FirewallApi {\n\n   /** Returns a firewall by name or null if not found. */\n   @Named(\"Firewalls:get\")\n   @GET\n   @Path(\"/{firewall}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Firewall get(@PathParam(\"firewall\") String firewall);\n\n   /**\n    * Creates a firewall resource in the specified project using the data included in the request.\n    *\n    * @param name            the name of the firewall to be inserted.\n    * @param network         the network to which to add the firewall\n    * @param firewallOptions the options of the firewall to add\n    * @return an Operation resource. To check on the status of an operation, poll the Operations resource returned to\n    *         you, and look for the status field.\n    */\n   @Named(\"Firewalls:insert\")\n   @POST\n   @Produces(APPLICATION_JSON)\n   @MapBinder(FirewallBinder.class)\n   Operation createInNetwork(@PayloadParam(\"name\") String name,\n                             @PayloadParam(\"network\") URI network,\n                             @PayloadParam(\"options\") FirewallOptions firewallOptions);\n\n   /**\n    * Updates the specified firewall resource with the data included in the request.\n    *\n    * @param firewall    the name firewall to be updated.\n    * @param firewallOptions the new firewall.\n    * @return an Operation resource. To check on the status of an operation, poll the Operations resource returned to\n    *         you, and look for the status field.\n    */\n   @Named(\"Firewalls:update\")\n   @PUT\n   @Produces(APPLICATION_JSON)\n   @Path(\"/{firewall}\")\n   Operation update(@PathParam(\"firewall\") String firewall,\n                    @BinderParam(BindToJsonPayload.class) FirewallOptions firewallOptions);\n\n   /**\n    * Updates the specified firewall resource, with patch semantics, with the data included in the request.\n    *\n    * @param firewall    the name firewall to be updated.\n    * @param firewallOptions the new firewall.\n    * @return an Operation resource. To check on the status of an operation, poll the Operations resource returned to\n    *         you, and look for the status field.\n    */\n   @Named(\"Firewalls:patch\")\n   @PATCH\n   @Produces(APPLICATION_JSON)\n   @Path(\"/{firewall}\")\n   Operation patch(@PathParam(\"firewall\") String firewall,\n                   @BinderParam(BindToJsonPayload.class) FirewallOptions firewallOptions);\n\n   /** Deletes a firewall by name and returns the operation in progress, or null if not found. */\n   @Named(\"Firewalls:delete\")\n   @DELETE\n   @Path(\"/{firewall}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   Operation delete(@PathParam(\"firewall\") String firewall);\n\n   /**\n    * Retrieves the list of firewall resources available to the specified project.\n    * By default the list as a maximum size of 100, if no options are provided or ListOptions#getMaxResults() has not\n    * been set.\n    *\n    * @param pageToken   marks the beginning of the next list page\n    * @param listOptions listing options\n    * @return a page of the list\n    */\n   @Named(\"Firewalls:list\")\n   @GET\n   ListPage<Firewall> listPage(@Nullable @QueryParam(\"pageToken\") String pageToken, ListOptions listOptions);\n\n   /** @see #listPage(String, ListOptions) */\n   @Named(\"Firewalls:list\")\n   @GET\n   @Transform(FirewallPages.class)\n   Iterator<ListPage<Firewall>> list();\n\n   /** @see #listPage(String, ListOptions) */\n   @Named(\"Firewalls:list\")\n   @GET\n   @Transform(FirewallPages.class)\n   Iterator<ListPage<Firewall>> list(ListOptions options);\n\n   static final class FirewallPages extends BaseToIteratorOfListPage<Firewall, FirewallPages> {\n\n      private final GoogleComputeEngineApi api;\n\n      @Inject FirewallPages(GoogleComputeEngineApi api) {\n         this.api = api;\n      }\n\n      @Override protected Function<String, ListPage<Firewall>> fetchNextPage(final ListOptions options) {\n         return new Function<String, ListPage<Firewall>>() {\n            @Override public ListPage<Firewall> apply(String pageToken) {\n               return api.firewalls().listPage(pageToken, options);\n            }\n         };\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/features/ForwardingRuleApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.net.URI;\nimport java.util.Iterator;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.QueryParam;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.GoogleComputeEngineApi;\nimport org.jclouds.googlecomputeengine.binders.ForwardingRuleCreationBinder;\n\nimport org.jclouds.googlecomputeengine.domain.ForwardingRule;\nimport org.jclouds.googlecomputeengine.domain.Operation;\nimport org.jclouds.googlecomputeengine.internal.BaseCallerArg0ToIteratorOfListPage;\n\nimport org.jclouds.googlecomputeengine.options.ForwardingRuleCreationOptions;\nimport org.jclouds.googlecomputeengine.options.ListOptions;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SkipEncoding;\nimport org.jclouds.rest.annotations.Transform;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport com.google.common.base.Function;\n\n@SkipEncoding({'/', '='})\n@RequestFilters(OAuthFilter.class)\n@Path(\"/forwardingRules\")\n@Consumes(APPLICATION_JSON)\npublic interface ForwardingRuleApi {\n\n   /** Returns a forwarding rule by name or null if not found. */\n   @Named(\"ForwardingRules:get\")\n   @GET\n   @Path(\"/{forwardingRule}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   ForwardingRule get(@PathParam(\"forwardingRule\") String forwardingRule);\n\n   /**\n    * Creates a ForwardingRule resource in the specified project and region using the data included in the request.\n    *\n    * @param forwardingRuleName the name of the forwarding rule.\n    * @return an Operation resource. To check on the status of an operation, poll the Operations resource returned to\n    *         you, and look for the status field.\n    */\n   @Named(\"ForwardingRules:insert\")\n   @POST\n   @Produces(APPLICATION_JSON)\n   @MapBinder(ForwardingRuleCreationBinder.class)\n   Operation create(@PayloadParam(\"name\") String forwardingRuleName,\n                    @PayloadParam(\"options\") ForwardingRuleCreationOptions options);\n\n\n   /** Deletes a forwarding rule by name and returns the operation in progress, or null if not found. */\n   @Named(\"ForwardingRules:delete\")\n   @DELETE\n   @Path(\"/{forwardingRule}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Operation delete(@PathParam(\"forwardingRule\") String forwardingRule);\n\n   /**\n    * Changes the target url for a forwarding rule.\n    *\n    * @param forwardingRule the name of the ForwardingRule resource in which target is to be set.\n    * @param target The URL of the target resource to receive traffic from this forwarding rule.\n    *               It must live in the same region as this forwarding rule.\n    *\n    * @return an Operation resource. To check on the status of an operation, poll the Operations resource returned to\n    *         you, and look for the status field.\n    */\n   @Named(\"ForwardingRules:setTarget\")\n   @POST\n   @Path(\"/{forwardingRule}/setTarget\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @MapBinder(BindToJsonPayload.class)\n   @Nullable\n   Operation setTarget(@PathParam(\"forwardingRule\") String forwardingRule, @PayloadParam(\"target\") URI target);\n\n   /**\n    * Retrieves the list of forwarding rule resources available to the specified project.\n    * By default the list as a maximum size of 100, if no options are provided or ListOptions#getMaxResults() has not\n    * been set.\n    *\n    * @param pageToken   marks the beginning of the next list page\n    * @param listOptions listing options\n    * @return a page of the list\n    */\n   @Named(\"ForwardingRules:list\")\n   @GET\n   ListPage<ForwardingRule> listPage(@Nullable @QueryParam(\"pageToken\") String pageToken, ListOptions listOptions);\n\n   /** @see #listPage(String, ListOptions) */\n   @Named(\"ForwardingRules:list\")\n   @GET\n   @Transform(ForwardingRulePages.class)\n   Iterator<ListPage<ForwardingRule>> list();\n\n   /** @see #listPage(String, ListOptions) */\n   @Named(\"ForwardingRules:list\")\n   @GET\n   @Transform(ForwardingRulePages.class)\n   Iterator<ListPage<ForwardingRule>> list(ListOptions options);\n\n   static final class ForwardingRulePages\n         extends BaseCallerArg0ToIteratorOfListPage<ForwardingRule, ForwardingRulePages> {\n\n      private final GoogleComputeEngineApi api;\n\n      @Inject ForwardingRulePages(GoogleComputeEngineApi api) {\n         this.api = api;\n      }\n\n      @Override\n      protected Function<String, ListPage<ForwardingRule>> fetchNextPage(final String regionName,\n            final ListOptions options) {\n         return new Function<String, ListPage<ForwardingRule>>() {\n            @Override public ListPage<ForwardingRule> apply(String pageToken) {\n               return api.forwardingRulesInRegion(regionName).listPage(pageToken, options);\n            }\n         };\n      }\n   }\n}\n\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/features/HttpHealthCheckApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.util.Iterator;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.QueryParam;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.GoogleComputeEngineApi;\nimport org.jclouds.googlecomputeengine.binders.HttpHealthCheckCreationBinder;\nimport org.jclouds.googlecomputeengine.domain.HttpHealthCheck;\nimport org.jclouds.googlecomputeengine.domain.Operation;\nimport org.jclouds.googlecomputeengine.internal.BaseToIteratorOfListPage;\nimport org.jclouds.googlecomputeengine.options.HttpHealthCheckCreationOptions;\nimport org.jclouds.googlecomputeengine.options.ListOptions;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PATCH;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SkipEncoding;\nimport org.jclouds.rest.annotations.Transform;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport com.google.common.base.Function;\n\n@SkipEncoding({'/', '='})\n@RequestFilters(OAuthFilter.class)\n@Path(\"/httpHealthChecks\")\n@Consumes(APPLICATION_JSON)\npublic interface HttpHealthCheckApi {\n\n   /** Returns a health check by name or null if not found. */\n   @Named(\"HttpHealthChecks:get\")\n   @GET\n   @Path(\"/{httpHealthCheck}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   HttpHealthCheck get(@PathParam(\"httpHealthCheck\") String httpHealthCheck);\n\n   /**\n    * Creates a HttpHealthCheck resource in the specified project and region using the data included in the request.\n    *\n    * @param httpHealthCheckName the name of the forwarding rule.\n    * @return an Operation resource. To check on the status of an operation, poll the Operations resource returned to\n    *         you, and look for the status field.\n    */\n   @Named(\"HttpHealthChecks:insert\")\n   @POST\n   @Produces(APPLICATION_JSON)\n   @MapBinder(BindToJsonPayload.class)\n   Operation insert(@PayloadParam(\"name\") String httpHealthCheckName);\n\n   /**\n    * Creates a HttpHealthCheck resource in the specified project and region using the data included in the request.\n    *\n    * @param name the name of the forwarding rule.\n    * @return an Operation resource. To check on the status of an operation, poll the Operations resource returned to\n    *         you, and look for the status field.\n    */\n   @Named(\"HttpHealthChecks:insert\")\n   @POST\n   @Produces(APPLICATION_JSON)\n   @MapBinder(HttpHealthCheckCreationBinder.class)\n   Operation insert(@PayloadParam(\"name\") String name, @PayloadParam(\"options\") HttpHealthCheckCreationOptions options);\n\n   /** Deletes a health check by name and returns the operation in progress, or null if not found. */\n   @Named(\"HttpHealthChecks:delete\")\n   @DELETE\n   @Path(\"/{httpHealthCheck}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Operation delete(@PathParam(\"httpHealthCheck\") String httpHealthCheck);\n\n   /**\n    * Updates a HttpHealthCheck resource in the specified project\n    * using the data included in the request. This method supports patch semantics.\n    *\n    * @param name the name of the HttpHealthCheck resource to update.\n    * @param options the options to set for the healthCheck\n    * @return an Operation resource. To check on the status of an operation, poll the Operations resource returned to\n    *         you, and look for the status field.\n    */\n   @Named(\"HttpHealthChecks:patch\")\n   @PATCH\n   @Path(\"/{httpHealthCheck}\")\n   @MapBinder(HttpHealthCheckCreationBinder.class)\n   @Nullable\n   Operation patch(@PathParam(\"httpHealthCheck\") @PayloadParam(\"name\") String name,\n         @PayloadParam(\"options\") HttpHealthCheckCreationOptions options);\n\n   /**\n    * Updates a HttpHealthCheck resource in the specified project using the data included in the request.\n    * Any options left blank will be overwritten!\n    *\n    * @param name the name of the forwarding rule.\n    * @param options the options to set for the healthCheck\n    * @return an Operation resource. To check on the status of an operation, poll the Operations resource returned to\n    *         you, and look for the status field.\n    */\n   @Named(\"HttpHealthChecks:update\")\n   @PUT\n   @Path(\"/{httpHealthCheck}\")\n   @Produces(APPLICATION_JSON)\n   @MapBinder(HttpHealthCheckCreationBinder.class)\n   Operation update(@PathParam(\"httpHealthCheck\") @PayloadParam(\"name\") String name,\n                    @PayloadParam(\"options\") HttpHealthCheckCreationOptions options);\n\n   /**\n    * Retrieves the list of persistent http health check resources available to the specified project.\n    * By default the list as a maximum size of 100, if no options are provided or ListOptions#getMaxResults() has not\n    * been set.\n    *\n    * @param pageToken   marks the beginning of the next list page\n    * @param listOptions listing options\n    * @return a page of the list\n    */\n   @Named(\"HttpHealthChecks:list\")\n   @GET\n   ListPage<HttpHealthCheck> listPage(@Nullable @QueryParam(\"pageToken\") String pageToken, ListOptions listOptions);\n\n   /** @see #listPage(String, ListOptions) */\n   @Named(\"HttpHealthChecks:list\")\n   @GET\n   @Transform(HttpHealthCheckPages.class)\n   Iterator<ListPage<HttpHealthCheck>> list();\n\n   /** @see #listPage(String, ListOptions) */\n   @Named(\"HttpHealthChecks:list\")\n   @GET\n   @Transform(HttpHealthCheckPages.class)\n   Iterator<ListPage<HttpHealthCheck>> list(ListOptions options);\n\n   static final class HttpHealthCheckPages extends BaseToIteratorOfListPage<HttpHealthCheck, HttpHealthCheckPages> {\n\n      private final GoogleComputeEngineApi api;\n\n      @Inject HttpHealthCheckPages(GoogleComputeEngineApi api) {\n         this.api = api;\n      }\n\n      @Override protected Function<String, ListPage<HttpHealthCheck>> fetchNextPage(final ListOptions options) {\n         return new Function<String, ListPage<HttpHealthCheck>>() {\n            @Override public ListPage<HttpHealthCheck> apply(String pageToken) {\n               return api.httpHeathChecks().listPage(pageToken, options);\n            }\n         };\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/features/ImageApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.net.URI;\nimport java.util.Iterator;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.QueryParam;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.googlecloud.config.CurrentProject;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.GoogleComputeEngineApi;\nimport org.jclouds.googlecomputeengine.domain.Image;\nimport org.jclouds.googlecomputeengine.domain.Operation;\nimport org.jclouds.googlecomputeengine.internal.BaseArg0ToIteratorOfListPage;\nimport org.jclouds.googlecomputeengine.internal.BaseToIteratorOfListPage;\nimport org.jclouds.googlecomputeengine.options.DeprecateOptions;\nimport org.jclouds.googlecomputeengine.options.ImageCreationOptions;\nimport org.jclouds.googlecomputeengine.options.ListOptions;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Endpoint;\nimport org.jclouds.rest.annotations.EndpointParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SkipEncoding;\nimport org.jclouds.rest.annotations.Transform;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport com.google.common.base.Function;\n\n@SkipEncoding({'/', '='})\n@RequestFilters(OAuthFilter.class)\n@Consumes(APPLICATION_JSON)\npublic interface ImageApi {\n\n   /** Returns an image by self-link or null if not found. */\n   @Named(\"Images:get\")\n   @GET\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Image get(@EndpointParam URI selfLink);\n\n   /** Returns an image by name or null if not found. */\n   @Named(\"Images:get \")\n   @GET\n   @Endpoint(CurrentProject.class)\n   @Path(\"/global/images/{image}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Image get(@PathParam(\"image\") String image);\n\n   /** Deletes an image by name and returns the operation in progress, or null if not found. */\n   @Named(\"Images:delete\")\n   @DELETE\n   @Endpoint(CurrentProject.class)\n   @Path(\"/global/images/{image}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Operation delete(@PathParam(\"image\") String image);\n\n   /**\n    * Creates an image resource in the specified project from the provided persistent disk.\n    *\n    * @param image  the name of the created image\n    * @param sourceDisk fully qualified URL for the persistent disk to create the image from\n    * @return an Operation resource. To check on the status of an operation, poll the Operations resource returned to\n    *         you, and look for the status field.\n    */\n   @Named(\"Images:insert\")\n   @POST\n   @Endpoint(CurrentProject.class)\n   @Path(\"/global/images\")\n   @Produces(APPLICATION_JSON)\n   @MapBinder(BindToJsonPayload.class)\n   Operation createFromDisk(@PayloadParam(\"name\") String image, @PayloadParam(\"sourceDisk\") String sourceDisk);\n\n   @Named(\"Images:insert\")\n   @POST\n   @Endpoint(CurrentProject.class)\n   @Path(\"/global/images\")\n   @Produces(APPLICATION_JSON)\n   Operation create(@BinderParam(BindToJsonPayload.class) ImageCreationOptions options);\n\n   /**\n    * Sets the deprecation status of an image. If no message body is given, clears the deprecation status instead.\n    *\n    * @param image  The Image resource to deprecate.\n    * @param deprecated the deprecation status to return\n    * @return an Operation resource. To check on the status of an operation, poll the Operations resource returned to\n    *         you, and look for the status field.\n    */\n   @Named(\"Images:deprecate\")\n   @POST\n   @Endpoint(CurrentProject.class)\n   @Path(\"/global/images/{image}/deprecate\")\n   Operation deprecate(@PathParam(\"image\") String image, @BinderParam(BindToJsonPayload.class) DeprecateOptions deprecated);\n\n   /**\n    * Retrieves the list of image resources available to the specified project.\n    * By default the list as a maximum size of 100, if no options are provided or ListOptions#getMaxResults() has not\n    * been set.\n    *\n    * @param pageToken   marks the beginning of the next list page\n    * @param listOptions listing options\n    * @return a page of the list\n    */\n   @Named(\"Images:list\")\n   @GET\n   @Endpoint(CurrentProject.class)\n   @Path(\"/global/images\")\n   ListPage<Image> listPage(@Nullable @QueryParam(\"pageToken\") String pageToken, ListOptions listOptions);\n\n   /** @see #listPage(String, ListOptions) */\n   @Named(\"Images:list\")\n   @GET\n   @Endpoint(CurrentProject.class)\n   @Path(\"/global/images\")\n   @Transform(ImagePages.class)\n   Iterator<ListPage<Image>> list();\n\n   /** @see #listPage(String, ListOptions) */\n   @Named(\"Images:list\")\n   @GET\n   @Endpoint(CurrentProject.class)\n   @Path(\"/global/images\")\n   @Transform(ImagePages.class)\n   Iterator<ListPage<Image>> list(ListOptions options);\n\n   static final class ImagePages extends BaseToIteratorOfListPage<Image, ImagePages> {\n\n      private final GoogleComputeEngineApi api;\n\n      @Inject ImagePages(GoogleComputeEngineApi api) {\n         this.api = api;\n      }\n\n      @Override protected Function<String, ListPage<Image>> fetchNextPage(final ListOptions options) {\n         return new Function<String, ListPage<Image>>() {\n            @Override public ListPage<Image> apply(String pageToken) {\n               return api.images().listPage(pageToken, options);\n            }\n         };\n      }\n   }\n\n   /**\n    * Retrieves the list of image resources available to the specified project.\n    * By default the list as a maximum size of 100, if no options are provided or ListOptions#getMaxResults() has not\n    * been set.\n    *\n    * @param pageToken   marks the beginning of the next list page\n    * @param listOptions listing options\n    * @return a page of the list\n    */\n   @Named(\"Images:list\")\n   @GET\n   @Path(\"/projects/{project}/global/images\")\n   ListPage<Image> listPageInProject(@PathParam(\"project\") String projectName,\n         @Nullable @QueryParam(\"pageToken\") String pageToken, ListOptions listOptions);\n\n   /**\n    * @see #listPageInProject(String, String, ListOptions)\n    */\n   @Named(\"Images:list\")\n   @GET\n   @Path(\"/projects/{project}/global/images\")\n   @Transform(ImagePagesInProject.class)\n   Iterator<ListPage<Image>> listInProject(@PathParam(\"project\") String projectName);\n\n   /**\n    * @see #listPageInProject(String, String, ListOptions)\n    */\n   @Named(\"Images:list\")\n   @GET\n   @Path(\"/projects/{project}/global/images\")\n   @Transform(ImagePagesInProject.class)\n   Iterator<ListPage<Image>> listInProject(@PathParam(\"project\") String projectName, ListOptions options);\n\n   static final class ImagePagesInProject extends BaseArg0ToIteratorOfListPage<Image, ImagePagesInProject> {\n\n      private final GoogleComputeEngineApi api;\n\n      @Inject ImagePagesInProject(GoogleComputeEngineApi api) {\n         this.api = api;\n      }\n\n      @Override\n      protected Function<String, ListPage<Image>> fetchNextPage(final String projectName, final ListOptions options) {\n         return new Function<String, ListPage<Image>>() {\n            @Override public ListPage<Image> apply(String pageToken) {\n               return api.images().listPageInProject(projectName, pageToken, options);\n            }\n         };\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/features/InstanceApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.util.Iterator;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.QueryParam;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.GoogleComputeEngineApi;\nimport org.jclouds.googlecomputeengine.domain.AttachDisk;\nimport org.jclouds.googlecomputeengine.domain.Instance;\nimport org.jclouds.googlecomputeengine.domain.Instance.NetworkInterface.AccessConfig;\nimport org.jclouds.googlecomputeengine.domain.Instance.Scheduling;\nimport org.jclouds.googlecomputeengine.domain.Instance.SerialPortOutput;\nimport org.jclouds.googlecomputeengine.domain.Metadata;\nimport org.jclouds.googlecomputeengine.domain.NewInstance;\nimport org.jclouds.googlecomputeengine.domain.Operation;\nimport org.jclouds.googlecomputeengine.internal.BaseCallerArg0ToIteratorOfListPage;\nimport org.jclouds.googlecomputeengine.options.ListOptions;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SkipEncoding;\nimport org.jclouds.rest.annotations.Transform;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport com.google.common.base.Function;\n\n@SkipEncoding({'/', '='})\n@RequestFilters(OAuthFilter.class)\n@Path(\"/instances\")\n@Consumes(APPLICATION_JSON)\npublic interface InstanceApi {\n\n   /** Returns an instance by name or null if not found. */\n   @Named(\"Instances:get\")\n   @GET\n   @Path(\"/{instance}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Instance get(@PathParam(\"instance\") String instance);\n\n   /**\n    * Creates a instance resource in the specified project using the data included in the request.\n    *\n    * @param template the instance template\n    * @return an Operation resource. To check on the status of an operation, poll the Operations resource returned to\n    *         you, and look for the status field.\n    */\n   @Named(\"Instances:insert\")\n   @POST\n   @Produces(APPLICATION_JSON)\n   Operation create(@BinderParam(BindToJsonPayload.class) NewInstance template);\n\n   /** Deletes an instance by name and returns the operation in progress, or null if not found. */\n   @Named(\"Instances:delete\")\n   @DELETE\n   @Path(\"/{instance}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Operation delete(@PathParam(\"instance\") String instance);\n\n   /**\n    * Adds an access config to an instance's network interface.\n    *\n    * @param instance         the instance name.\n    * @param accessConfig         the AccessConfig to add.\n    * @param networkInterfaceName network interface name.\n    * @return an Operation resource. To check on the status of an operation, poll the Operations resource returned to\n    *         you, and look for the status field.\n    */\n   @Named(\"Instances:addAccessConfig\")\n   @POST\n   @Produces(APPLICATION_JSON)\n   @Path(\"/{instance}/addAccessConfig\")\n   Operation addAccessConfigToNic(@PathParam(\"instance\") String instance,\n                                  @BinderParam(BindToJsonPayload.class)\n                                  AccessConfig accessConfig,\n                                  @QueryParam(\"networkInterface\") String networkInterfaceName);\n\n   /**\n    * Deletes an access config from an instance's network interface.\n    *\n    * @param instance         the instance name.\n    * @param accessConfigName     the name of the access config to delete\n    * @param networkInterfaceName network interface name.\n    * @return an Operation resource. To check on the status of an operation, poll the Operations resource returned to\n    *         you, and look for the status field.\n    */\n   @Named(\"Instances:deleteAccessConfig\")\n   @POST\n   @Path(\"/{instance}/deleteAccessConfig\")\n   Operation deleteAccessConfigFromNic(@PathParam(\"instance\") String instance,\n                                       @QueryParam(\"accessConfig\") String accessConfigName,\n                                       @QueryParam(\"networkInterface\") String networkInterfaceName);\n\n   /**\n    * Returns the specified instance's serial port output.\n    *\n    * @param instance the instance name.\n    * @return if successful, this method returns a SerialPortOutput containing the instance's serial output.\n    */\n   @Named(\"Instances:getSerialPortOutput\")\n   @GET\n   @Path(\"/{instance}/serialPort\")\n   SerialPortOutput getSerialPortOutput(@PathParam(\"instance\") String instance);\n   \n   /**\n    * Returns the specified instance's serial port output.\n    *\n    * @param instance the instance name.\n    * @return if successful, this method returns a SerialPortOutput containing the instance's serial output.\n    */\n   @Named(\"Instances:getSerialPortOutput\")\n   @GET\n   @Path(\"/{instance}/serialPort\")\n   SerialPortOutput getSerialPortOutput(@PathParam(\"instance\") String instance, @QueryParam(\"port\") int port);\n\n   /**\n    * Hard-resets the instance.\n    *\n    * @param instance the instance name\n    * @return an Operation resource. To check on the status of an operation, poll the Operations resource returned to\n    *         you, and look for the status field.\n    */\n   @Named(\"Instances:reset\")\n   @POST\n   @Path(\"/{instance}/reset\")\n   Operation reset(@PathParam(\"instance\") String instance);\n\n   /**\n    * Attaches a disk to an instance\n    *\n    * @param instance The instance name to attach to\n    * @param attachDiskOptions The options for attaching the disk.\n    *\n    * @return an Operation resource. To check on the status of an operation, poll the Operations resource returned to\n    *         you, and look for the status field.\n    */\n   @Named(\"Instances:attachDisk\")\n   @POST\n   @Produces(APPLICATION_JSON)\n   @Path(\"/{instance}/attachDisk\")\n   Operation attachDisk(@PathParam(\"instance\") String instance,\n                        @BinderParam(BindToJsonPayload.class) AttachDisk attachDiskOptions);\n\n   /**\n    * Detaches an attached disk from an instance\n    *\n    * @param instance The instance name to attach to\n    * @param deviceName The device name of the disk to detach.\n    *\n    * @return an Operation resource. To check on the status of an operation, poll the Operations resource returned to\n    *         you, and look for the status field.\n    */\n   @Named(\"Instances:detachDisk\")\n   @POST\n   @Path(\"/{instance}/detachDisk\")\n   Operation detachDisk(@PathParam(\"instance\") String instance, @QueryParam(\"deviceName\") String deviceName);\n\n   /**\n    * Sets metadata for an instance using the data included in the request.\n    * <p/>\n    * NOTE: This *sets* metadata items on the project (vs *adding* items to metadata),\n    * if there are existing metadata that must be kept these must be fetched first and then re-sent on update.\n    * <pre><tt>\n    *    Metadata update = instanceApi.get(\"myInstance\").metadata().clone();\n    *    update.put(\"newItem\",\"newItemValue\");\n    *    instanceApi.setMetadata(\"myInstance\", update);\n    * </tt></pre>\n    *\n    * @param instance The name of the instance\n    * @param metadata the metadata to set\n    *\n    * @return an Operations resource. To check on the status of an operation, poll the Operations resource returned\n    *         to you, and look for the status field.\n    */\n   @Named(\"Instances:setMetadata\")\n   @POST\n   @Path(\"/{instance}/setMetadata\")\n   Operation setMetadata(@PathParam(\"instance\") String instance,\n                         @BinderParam(BindToJsonPayload.class) Metadata metadata);\n\n   /**\n    * Lists items for an instance\n    *\n    * @param instance the name of the instance\n    * @param items A set of items\n    * @param fingerprint The current fingerprint for the items\n    * @return an Operations resource. To check on the status of an operation, poll the Operations resource returned\n    *         to you, and look for the status field.\n    */\n   @Named(\"Instances:setTags\")\n   @POST\n   @Path(\"/{instance}/setTags\")\n   @Produces(APPLICATION_JSON)\n   @MapBinder(BindToJsonPayload.class)\n   Operation setTags(@PathParam(\"instance\") String instance,\n                     @PayloadParam(\"items\") Iterable<String> items,\n                     @PayloadParam(\"fingerprint\") String fingerprint);\n\n   /**\n    * Sets the auto-delete flag for a disk attached to an instance\n    *\n    * @param instanceName The name of the instance\n    * @param deviceName Disk device name to modify.\n    * @param autoDelete Whether to auto-delete the disk when the instance is deleted\n    */\n   @Named(\"Instances:setDiskAutoDelete\")\n   @POST\n   @Path(\"/{instance}/setDiskAutoDelete\")\n   Operation setDiskAutoDelete(@PathParam(\"instance\") String instanceName,\n                               @QueryParam(\"deviceName\") String deviceName,\n                               @QueryParam(\"autoDelete\") boolean autoDelete);\n\n   /**\n    * Sets an instance's scheduling options.\n    * @see <a href = \"https://cloud.google.com/compute/docs/instances#onhostmaintenance\"/>\n    *\n    * @param instanceName The name of the instance\n    * @param onHostMaintenance either MIGRATE or TERMINATE the default is MIGRATE (Live Migration).\n    * @param automaticRestart Defines whether the Instance should be automatically\n    *  restarted when it is terminated by Compute Engine (not terminated by user).\n    *  Used when onHostMaintenance is set to TERMINATE.\n    * @param preemptible Defines whether the Instance should be launched as spot instance\n    * @return\n    */\n   @Named(\"Instances:setScheduling\")\n   @POST\n   @Path(\"/{instance}/setScheduling\")\n   @MapBinder(BindToJsonPayload.class)\n   Operation setScheduling(@PathParam(\"instance\") String instanceName,\n                           @PayloadParam(\"onHostMaintenance\") Scheduling.OnHostMaintenance onHostMaintenance,\n                           @PayloadParam(\"automaticRestart\") boolean automaticRestart,\n                           @PayloadParam(\"preemptible\") boolean preemptible);\n\n   /**\n    * This method starts an instance that was stopped using the using the {@link #stop(String)} method.\n    * @param instance - name of the instance to be started\n    */\n   @Named(\"Instances:start\")\n   @POST\n   @Path(\"/{instance}/start\")\n   @Produces(APPLICATION_JSON)\n   Operation start(@PathParam(\"instance\") String instance);\n\n   /**\n    * This method stops a running instance, shutting it down cleanly, and allows you to restart\n    *  the instance at a later time. Stopped instances do not incur per-minute, virtual machine\n    *  usage charges while they are stopped, but any resources that the virtual machine is using,\n    *  such as persistent disks and static IP addresses,will continue to be charged until they are deleted.\n    * @param instance\n    * @return\n    */\n   @Named(\"Instances:stop\")\n   @POST\n   @Path(\"/{instance}/stop\")\n   @Produces(APPLICATION_JSON)\n   Operation stop(@PathParam(\"instance\") String instance);\n\n   /**\n    * Retrieves the list of instance resources available to the specified project.\n    * By default the list as a maximum size of 100, if no options are provided or ListOptions#getMaxResults() has not\n    * been set.\n    *\n    * @param pageToken   marks the beginning of the next list page\n    * @param listOptions listing options\n    * @return a page of the list\n    */\n   @Named(\"Instances:list\")\n   @GET\n   ListPage<Instance> listPage(@Nullable @QueryParam(\"pageToken\") String pageToken, ListOptions listOptions);\n\n   /** @see #listPage(String, ListOptions) */\n   @Named(\"Instances:list\")\n   @GET\n   @Transform(InstancePages.class)\n   Iterator<ListPage<Instance>> list();\n\n   /** @see #listPage(String, ListOptions) */\n   @Named(\"Instances:list\")\n   @GET\n   @Transform(InstancePages.class)\n   Iterator<ListPage<Instance>> list(ListOptions options);\n\n   static final class InstancePages extends BaseCallerArg0ToIteratorOfListPage<Instance, InstancePages> {\n\n      private final GoogleComputeEngineApi api;\n\n      @Inject InstancePages(GoogleComputeEngineApi api) {\n         this.api = api;\n      }\n\n      @Override\n      protected Function<String, ListPage<Instance>> fetchNextPage(final String zoneName, final ListOptions options) {\n         return new Function<String, ListPage<Instance>>() {\n            @Override public ListPage<Instance> apply(String pageToken) {\n               return api.instancesInZone(zoneName).listPage(pageToken, options);\n            }\n         };\n      }\n   }\n\n}\n\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/features/LicenseApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.googlecomputeengine.domain.License;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SkipEncoding;\n\n@SkipEncoding({'/', '='})\n@RequestFilters(OAuthFilter.class)\n@Consumes(APPLICATION_JSON)\npublic interface LicenseApi {\n\n   /** Returns the specified License resource. */\n   @Named(\"License:get\")\n   @GET\n   @Path(\"/licenses/{license}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   License get(@PathParam(\"license\") String license);\n\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/features/MachineTypeApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.util.Iterator;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.QueryParam;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.GoogleComputeEngineApi;\nimport org.jclouds.googlecomputeengine.domain.MachineType;\nimport org.jclouds.googlecomputeengine.internal.BaseCallerArg0ToIteratorOfListPage;\nimport org.jclouds.googlecomputeengine.options.ListOptions;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SkipEncoding;\nimport org.jclouds.rest.annotations.Transform;\n\nimport com.google.common.base.Function;\n\n@SkipEncoding({'/', '='})\n@RequestFilters(OAuthFilter.class)\n@Path(\"/machineTypes\")\n@Consumes(APPLICATION_JSON)\npublic interface MachineTypeApi {\n\n   /** Returns an machine type by name or null if not found. */\n   @Named(\"MachineTypes:get\")\n   @GET\n   @Path(\"/{machineType}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   MachineType get(@PathParam(\"machineType\") String machineType);\n\n   /**\n    * Retrieves the list of machine type resources available to the specified project.\n    * By default the list as a maximum size of 100, if no options are provided or ListOptions#getMaxResults() has not\n    * been set.\n    *\n    * @param pageToken   marks the beginning of the next list page\n    * @param listOptions listing options\n    * @return a page of the list\n    */\n   @Named(\"MachineTypes:list\")\n   @GET\n   ListPage<MachineType> listPage(@Nullable @QueryParam(\"pageToken\") String pageToken, ListOptions listOptions);\n\n   /** @see #listPage(String, ListOptions) */\n   @Named(\"MachineTypes:list\")\n   @GET\n   @Transform(MachineTypePages.class)\n   Iterator<ListPage<MachineType>> list();\n\n   /** @see #listPage(String, ListOptions) */\n   @Named(\"MachineTypes:list\")\n   @GET\n   @Transform(MachineTypePages.class)\n   Iterator<ListPage<MachineType>> list(ListOptions options);\n\n   static final class MachineTypePages extends BaseCallerArg0ToIteratorOfListPage<MachineType, MachineTypePages> {\n\n      private final GoogleComputeEngineApi api;\n\n      @Inject MachineTypePages(GoogleComputeEngineApi api) {\n         this.api = api;\n      }\n\n      @Override\n      protected Function<String, ListPage<MachineType>> fetchNextPage(final String zoneName, final ListOptions options) {\n         return new Function<String, ListPage<MachineType>>() {\n            @Override public ListPage<MachineType> apply(String pageToken) {\n               return api.machineTypesInZone(zoneName).listPage(pageToken, options);\n            }\n         };\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/features/NetworkApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.util.Iterator;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.QueryParam;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.GoogleComputeEngineApi;\nimport org.jclouds.googlecomputeengine.domain.Network;\nimport org.jclouds.googlecomputeengine.domain.Operation;\nimport org.jclouds.googlecomputeengine.internal.BaseToIteratorOfListPage;\nimport org.jclouds.googlecomputeengine.options.ListOptions;\nimport org.jclouds.googlecomputeengine.options.NetworkCreationOptions;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SkipEncoding;\nimport org.jclouds.rest.annotations.Transform;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport com.google.common.base.Function;\n\n@SkipEncoding({'/', '='})\n@RequestFilters(OAuthFilter.class)\n@Path(\"/networks\")\n@Consumes(APPLICATION_JSON)\npublic interface NetworkApi {\n\n   /** Returns a network by name or null if not found. */\n   @Named(\"Networks:get\")\n   @GET\n   @Path(\"/{network}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   Network get(@PathParam(\"network\") String networkName);\n\n   /**\n    * Creates a legacy persistent network resource in the specified project with the specified range.\n    *\n    * @param networkName the network name\n    * @param IPv4Range   the range of the network to be inserted.\n    * @return an Operation resource. To check on the status of an operation, poll the Operations resource returned to\n    *         you, and look for the status field.\n    */\n   @Named(\"Networks:insert\")\n   @POST\n   @Produces(APPLICATION_JSON)\n   @Payload(\"%7B\\\"name\\\":\\\"{name}\\\",\\\"IPv4Range\\\":\\\"{IPv4Range}\\\"%7D\")\n   Operation createLegacy(@PayloadParam(\"name\") String networkName, @PayloadParam(\"IPv4Range\") String IPv4Range);\n   \n   /**\n    * Creates a custom persistent network resource in the specified project with the specified range.\n    *\n    * @param networkName the network name\n    * @return an Operation resource. To check on the status of an operation, poll the Operations resource returned to\n    *         you, and look for the status field.\n    */\n   @Named(\"Networks:insert\")\n   @POST\n   @Produces(APPLICATION_JSON)\n   @Payload(\"%7B\\\"autoCreateSubnetworks\\\":false,\\\"name\\\":\\\"{name}\\\"%7D\")\n   Operation createCustom(@PayloadParam(\"name\") String networkName);\n\n   /**\n    * Creates a persistent network resource in the specified project with the specified options.\n    *\n    * @param options the network options.\n    * @return an Operation resource. To check on the status of an operation, poll the Operations resource returned to\n    *         you, and look for the status field.\n    */\n   @Named(\"Networks:insert\")\n   @POST\n   @Produces(APPLICATION_JSON)\n   Operation create(@BinderParam(BindToJsonPayload.class) NetworkCreationOptions options);\n\n   /** Deletes a network by name and returns the operation in progress, or null if not found. */\n   @Named(\"Networks:delete\")\n   @DELETE\n   @Path(\"/{network}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   Operation delete(@PathParam(\"network\") String networkName);\n\n   /**\n    * Retrieves the list of network resources available to the specified project.\n    * By default the list as a maximum size of 100, if no options are provided or ListOptions#getMaxResults() has not\n    * been set.\n    *\n    * @param pageToken   marks the beginning of the next list page\n    * @param listOptions listing options\n    * @return a page of the list\n    */\n   @Named(\"Networks:list\")\n   @GET\n   ListPage<Network> listPage(@Nullable @QueryParam(\"pageToken\") String pageToken, ListOptions listOptions);\n\n   /** @see #listPage(String, ListOptions) */\n   @Named(\"Networks:list\")\n   @GET\n   @Transform(NetworkPages.class)\n   Iterator<ListPage<Network>> list();\n\n   /** @see #listPage(String, ListOptions) */\n   @Named(\"Networks:list\")\n   @GET\n   @Transform(NetworkPages.class)\n   Iterator<ListPage<Network>> list(ListOptions options);\n\n   static final class NetworkPages extends BaseToIteratorOfListPage<Network, NetworkPages> {\n\n      private final GoogleComputeEngineApi api;\n\n      @Inject NetworkPages(GoogleComputeEngineApi api) {\n         this.api = api;\n      }\n\n      @Override protected Function<String, ListPage<Network>> fetchNextPage(final ListOptions options) {\n         return new Function<String, ListPage<Network>>() {\n            @Override public ListPage<Network> apply(String pageToken) {\n               return api.networks().listPage(pageToken, options);\n            }\n         };\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/features/OperationApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.net.URI;\nimport java.util.Iterator;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.QueryParam;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.googlecloud.config.CurrentProject;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.GoogleComputeEngineApi;\nimport org.jclouds.googlecomputeengine.domain.Operation;\nimport org.jclouds.googlecomputeengine.internal.BaseArg0ToIteratorOfListPage;\nimport org.jclouds.googlecomputeengine.internal.BaseToIteratorOfListPage;\nimport org.jclouds.googlecomputeengine.options.ListOptions;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.Endpoint;\nimport org.jclouds.rest.annotations.EndpointParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SkipEncoding;\nimport org.jclouds.rest.annotations.Transform;\n\nimport com.google.common.base.Function;\n\n@SkipEncoding({'/', '='})\n@RequestFilters(OAuthFilter.class)\n@Consumes(APPLICATION_JSON)\npublic interface OperationApi {\n\n   /** Returns an operation by self-link or null if not found. */\n   @Named(\"Operations:get\")\n   @GET\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Operation get(@EndpointParam URI operation);\n\n   /** Deletes an operation by name. */\n   @Named(\"Operations:delete\")\n   @DELETE\n   @Fallback(VoidOnNotFoundOr404.class)\n   void delete(@EndpointParam URI operation);\n\n   /**\n    * Retrieves the list of operation resources available to the specified project.\n    * By default the list as a maximum size of 100, if no options are provided or ListOptions#getMaxResults() has not\n    * been set.\n    *\n    * @param pageToken   marks the beginning of the next list page\n    * @param listOptions listing options\n    * @return a page of the list\n    */\n   @Named(\"GlobalOperations:list\")\n   @GET\n   @Endpoint(CurrentProject.class)\n   @Path(\"/global/operations\")\n   ListPage<Operation> listPage(@Nullable @QueryParam(\"pageToken\") String pageToken, ListOptions listOptions);\n\n   /** @see #listPage(String, ListOptions) */\n   @Named(\"GlobalOperations:list\")\n   @GET\n   @Endpoint(CurrentProject.class)\n   @Path(\"/global/operations\")\n   @Transform(OperationPages.class)\n   Iterator<ListPage<Operation>> list();\n\n   /** @see #listPage(String, ListOptions) */\n   @Named(\"GlobalOperations:list\")\n   @GET\n   @Endpoint(CurrentProject.class)\n   @Path(\"/global/operations\")\n   @Transform(OperationPages.class)\n   Iterator<ListPage<Operation>> list(ListOptions options);\n\n   static final class OperationPages extends BaseToIteratorOfListPage<Operation, OperationPages> {\n\n      private final GoogleComputeEngineApi api;\n\n      @Inject OperationPages(GoogleComputeEngineApi api) {\n         this.api = api;\n      }\n\n      @Override protected Function<String, ListPage<Operation>> fetchNextPage(final ListOptions options) {\n         return new Function<String, ListPage<Operation>>() {\n            @Override public ListPage<Operation> apply(String pageToken) {\n               return api.operations().listPage(pageToken, options);\n            }\n         };\n      }\n   }\n\n   /**\n    * Retrieves the list of operation resources available in the specified region.\n    * By default the list as a maximum size of 100, if no options are provided or ListOptions#getMaxResults() has not\n    * been set.\n    *\n    * @param pageToken   marks the beginning of the next list page\n    * @param listOptions listing options\n    * @return a page of the list\n    */\n   @Named(\"RegionOperations:list\")\n   @GET\n   @Endpoint(CurrentProject.class)\n   @Path(\"/regions/{region}/operations\")\n   ListPage<Operation> listPageInRegion(@PathParam(\"region\") String region,\n                                        @Nullable @QueryParam(\"pageToken\") String pageToken, ListOptions listOptions);\n\n   /** @see #listInRegion(String, org.jclouds.googlecomputeengine.options.ListOptions) */\n   @Named(\"RegionOperations:list\")\n   @GET\n   @Endpoint(CurrentProject.class)\n   @Path(\"/regions/{region}/operations\")\n   @Transform(OperationPagesInRegion.class)\n   Iterator<ListPage<Operation>> listInRegion(@PathParam(\"region\") String region);\n\n   /** @see #listInRegion(String, org.jclouds.googlecomputeengine.options.ListOptions) */\n   @Named(\"RegionOperations:list\")\n   @GET\n   @Endpoint(CurrentProject.class)\n   @Path(\"/regions/{region}/operations\")\n   @Transform(OperationPagesInRegion.class)\n   Iterator<ListPage<Operation>> listInRegion(@PathParam(\"region\") String region, ListOptions options);\n\n   static final class OperationPagesInRegion extends BaseArg0ToIteratorOfListPage<Operation, OperationPagesInRegion> {\n\n      private final GoogleComputeEngineApi api;\n\n      @Inject OperationPagesInRegion(GoogleComputeEngineApi api) {\n         this.api = api;\n      }\n\n      @Override\n      protected Function<String, ListPage<Operation>> fetchNextPage(final String regionName,\n            final ListOptions options) {\n         return new Function<String, ListPage<Operation>>() {\n            @Override public ListPage<Operation> apply(String pageToken) {\n               return api.operations().listPageInRegion(regionName, pageToken, options);\n            }\n         };\n      }\n   }\n\n   /**\n    * Retrieves the list of operation resources available in the specified zone.\n    * By default the list as a maximum size of 100, if no options are provided or ListOptions#getMaxResults() has not\n    * been set.\n    *\n    * @param pageToken   marks the beginning of the next list page\n    * @param listOptions listing options\n    * @return a page of the list\n    */\n   @Named(\"ZoneOperations:list\")\n   @GET\n   @Endpoint(CurrentProject.class)\n   @Path(\"/zones/{zone}/operations\")\n   ListPage<Operation> listPageInZone(@PathParam(\"zone\") String zone,\n         @Nullable @QueryParam(\"pageToken\") String pageToken, ListOptions listOptions);\n\n   /** @see #listInZone(String, org.jclouds.googlecomputeengine.options.ListOptions) */\n   @Named(\"ZoneOperations:list\")\n   @GET\n   @Endpoint(CurrentProject.class)\n   @Path(\"/zones/{zone}/operations\")\n   @Transform(OperationPagesInZone.class)\n   Iterator<ListPage<Operation>> listInZone(@PathParam(\"zone\") String zone);\n\n   /** @see #listInZone(String, org.jclouds.googlecomputeengine.options.ListOptions) */\n   @Named(\"ZoneOperations:list\")\n   @GET\n   @Endpoint(CurrentProject.class)\n   @Path(\"/zones/{zone}/operations\")\n   @Transform(OperationPagesInZone.class)\n   Iterator<ListPage<Operation>> listInZone(@PathParam(\"zone\") String zone, ListOptions options);\n\n   static final class OperationPagesInZone extends BaseArg0ToIteratorOfListPage<Operation, OperationPagesInZone> {\n\n      private final GoogleComputeEngineApi api;\n\n      @Inject OperationPagesInZone(GoogleComputeEngineApi api) {\n         this.api = api;\n      }\n\n      @Override\n      protected Function<String, ListPage<Operation>> fetchNextPage(final String zoneName, final ListOptions options) {\n         return new Function<String, ListPage<Operation>>() {\n            @Override public ListPage<Operation> apply(String pageToken) {\n               return api.operations().listPageInZone(zoneName, pageToken, options);\n            }\n         };\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/features/ProjectApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.Produces;\n\nimport org.jclouds.googlecomputeengine.GoogleComputeEngineFallbacks.NullOn400or404;\nimport org.jclouds.googlecomputeengine.domain.Metadata;\nimport org.jclouds.googlecomputeengine.domain.Operation;\nimport org.jclouds.googlecomputeengine.domain.Project;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SkipEncoding;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\n@SkipEncoding({'/', '='})\n@RequestFilters(OAuthFilter.class)\n@Consumes(APPLICATION_JSON)\npublic interface ProjectApi {\n\n   /** Get the current project. */\n   @Named(\"Projects:get\")\n   @GET\n   @Fallback(NullOn400or404.class)\n   Project get();\n\n   /**\n    * Sets metadata common to all instances within the current project using the data included in the request.\n    * <p/>\n    * NOTE: This *sets* metadata items on the project (vs *adding* items to metadata),\n    * if there are existing metadata that must be kept these must be fetched first and then re-sent on update.\n    * <pre><tt>\n    *    Metadata update = projectApi.get(\"myProject\").getCommonInstanceMetadata().clone();\n    *    update.put(\"newItem\",\"newItemValue\");\n    *    projectApi.setCommonInstanceMetadata(\"myProject\", update);\n    * </tt></pre>\n    *\n    * @param metadata      the metadata to set\n    * @return an Operations resource. To check on the status of an operation, poll the Operations resource returned\n    *         to you, and look for the status field.\n    */\n   @Named(\"Projects:setCommonInstanceMetadata\")\n   @POST\n   @Path(\"/setCommonInstanceMetadata\")\n   @Produces(APPLICATION_JSON)\n   Operation setCommonInstanceMetadata(@BinderParam(BindToJsonPayload.class) Metadata metadata);\n\n   @Named(\"Projects:setUsageExportBucket\")\n   @POST\n   @Path(\"/setUsageExportBucket\")\n   @Produces(APPLICATION_JSON)\n   @MapBinder(BindToJsonPayload.class)\n   Operation setUsageExportBucket(@PayloadParam(\"bucketName\") String bucketName,\n                                  @PayloadParam(\"reportNamePrefix\") String reportNamePrefix);\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/features/RegionApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.util.Iterator;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.QueryParam;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.GoogleComputeEngineApi;\nimport org.jclouds.googlecomputeengine.domain.Region;\nimport org.jclouds.googlecomputeengine.internal.BaseToIteratorOfListPage;\nimport org.jclouds.googlecomputeengine.options.ListOptions;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SkipEncoding;\nimport org.jclouds.rest.annotations.Transform;\n\nimport com.google.common.base.Function;\n\n@SkipEncoding({'/', '='})\n@RequestFilters(OAuthFilter.class)\n@Path(\"/regions\")\n@Consumes(APPLICATION_JSON)\npublic interface RegionApi {\n\n   /** Returns a region by name or null if not found. */\n   @Named(\"Regions:get\")\n   @GET\n   @Path(\"/{region}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   Region get(@PathParam(\"region\") String region);\n\n   /**\n    * Retrieves the list of region resources available to the specified project.\n    * By default the list as a maximum size of 100, if no options are provided or ListOptions#getMaxResults() has not\n    * been set.\n    *\n    * @param pageToken   marks the beginning of the next list page\n    * @param listOptions listing options\n    * @return a page of the list\n    */\n   @Named(\"Regions:list\")\n   @GET\n   ListPage<Region> listPage(@Nullable @QueryParam(\"pageToken\") String pageToken, ListOptions listOptions);\n\n   /** @see #listPage(String, ListOptions) */\n   @Named(\"Regions:list\")\n   @GET\n   @Transform(RegionPages.class)\n   Iterator<ListPage<Region>> list();\n\n   /** @see #listPage(String, ListOptions) */\n   @Named(\"Regions:list\")\n   @GET\n   @Transform(RegionPages.class)\n   Iterator<ListPage<Region>> list(ListOptions options);\n\n   static final class RegionPages extends BaseToIteratorOfListPage<Region, RegionPages> {\n\n      private final GoogleComputeEngineApi api;\n\n      @Inject RegionPages(GoogleComputeEngineApi api) {\n         this.api = api;\n      }\n\n      @Override protected Function<String, ListPage<Region>> fetchNextPage(final ListOptions options) {\n         return new Function<String, ListPage<Region>>() {\n            @Override public ListPage<Region> apply(String pageToken) {\n               return api.regions().listPage(pageToken, options);\n            }\n         };\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/features/RouteApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.net.URI;\nimport java.util.Iterator;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.QueryParam;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.GoogleComputeEngineApi;\nimport org.jclouds.googlecomputeengine.binders.RouteBinder;\nimport org.jclouds.googlecomputeengine.domain.Operation;\nimport org.jclouds.googlecomputeengine.domain.Route;\nimport org.jclouds.googlecomputeengine.internal.BaseToIteratorOfListPage;\nimport org.jclouds.googlecomputeengine.options.ListOptions;\nimport org.jclouds.googlecomputeengine.options.RouteOptions;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SkipEncoding;\nimport org.jclouds.rest.annotations.Transform;\n\nimport com.google.common.base.Function;\n\n@SkipEncoding({'/', '='})\n@RequestFilters(OAuthFilter.class)\n@Path(\"/routes\")\n@Consumes(APPLICATION_JSON)\npublic interface RouteApi {\n\n   /** Returns a route type by name or null if not found. */\n   @Named(\"Routes:get\")\n   @GET\n   @Path(\"/{route}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   Route get(@PathParam(\"route\") String routeName);\n\n   /** Deletes a route by name and returns the operation in progress, or null if not found. */\n   @Named(\"Routes:delete\")\n   @DELETE\n   @Path(\"/{route}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Operation delete(@PathParam(\"route\") String routeName);\n\n   /**\n    * Creates a route resource in the specified project using the data included in the request.\n    *\n    * @param name            the name of the route to be inserted.\n    * @param network         the network to which to add the route\n    * @param routeOptions the options of the route to add\n    * @return an Operation resource. To check on the status of an operation, poll the Operations resource returned to\n    *         you, and look for the status field.\n    */\n   @Named(\"Routes:insert\")\n   @POST\n   @Produces(APPLICATION_JSON)\n   @MapBinder(RouteBinder.class)\n   Operation createInNetwork(@PayloadParam(\"name\") String name,\n                             @PayloadParam(\"network\") URI network,\n                             @PayloadParam(\"options\") RouteOptions routeOptions);\n\n   /**\n    * Retrieves the list of route resources available to the specified project.\n    * By default the list as a maximum size of 100, if no options are provided or ListOptions#getMaxResults() has not\n    * been set.\n    *\n    * @param pageToken   marks the beginning of the next list page\n    * @param listOptions listing options\n    * @return a page of the list\n    */\n   @Named(\"Routes:list\")\n   @GET\n   ListPage<Route> listPage(@Nullable @QueryParam(\"pageToken\") String pageToken, ListOptions listOptions);\n\n   /** @see #listPage(String, ListOptions) */\n   @Named(\"Routes:list\")\n   @GET\n   @Transform(RoutePages.class)\n   Iterator<ListPage<Route>> list();\n\n   /** @see #listPage(String, ListOptions) */\n   @Named(\"Routes:list\")\n   @GET\n   @Transform(RoutePages.class)\n   Iterator<ListPage<Route>> list(ListOptions options);\n\n   static final class RoutePages extends BaseToIteratorOfListPage<Route, RoutePages> {\n\n      private final GoogleComputeEngineApi api;\n\n      @Inject RoutePages(GoogleComputeEngineApi api) {\n         this.api = api;\n      }\n\n      @Override protected Function<String, ListPage<Route>> fetchNextPage(final ListOptions options) {\n         return new Function<String, ListPage<Route>>() {\n            @Override public ListPage<Route> apply(String pageToken) {\n               return api.routes().listPage(pageToken, options);\n            }\n         };\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/features/SnapshotApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.util.Iterator;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.QueryParam;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.GoogleComputeEngineApi;\nimport org.jclouds.googlecomputeengine.domain.Operation;\nimport org.jclouds.googlecomputeengine.domain.Snapshot;\nimport org.jclouds.googlecomputeengine.internal.BaseToIteratorOfListPage;\nimport org.jclouds.googlecomputeengine.options.ListOptions;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SkipEncoding;\nimport org.jclouds.rest.annotations.Transform;\n\nimport com.google.common.base.Function;\n\n@SkipEncoding({'/', '='})\n@RequestFilters(OAuthFilter.class)\n@Path(\"/snapshots\")\n@Consumes(APPLICATION_JSON)\npublic interface SnapshotApi {\n\n   /** Returns a snapshot by name or null if not found. */\n   @Named(\"Snapshots:get\")\n   @GET\n   @Path(\"/{snapshot}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Snapshot get(@PathParam(\"snapshot\") String snapshot);\n\n   /** Deletes a snapshot by name and returns the operation in progress, or null if not found. */\n   @Named(\"Snapshots:delete\")\n   @DELETE\n   @Path(\"/{snapshot}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Operation delete(@PathParam(\"snapshot\") String snapshot);\n\n   /**\n    * Retrieves the list of snapshot resources available to the specified project.\n    * By default the list as a maximum size of 100, if no options are provided or ListOptions#getMaxResults() has not\n    * been set.\n    *\n    * @param pageToken   marks the beginning of the next list page\n    * @param listOptions listing options\n    * @return a page of the list\n    */\n   @Named(\"Snapshots:list\")\n   @GET\n   ListPage<Snapshot> listPage(@Nullable @QueryParam(\"pageToken\") String pageToken, ListOptions listOptions);\n\n   /** @see #listPage(String, ListOptions) */\n   @Named(\"Snapshots:list\")\n   @GET\n   @Transform(SnapshotPages.class)\n   Iterator<ListPage<Snapshot>> list();\n\n   /** @see #listPage(String, ListOptions) */\n   @Named(\"Snapshots:list\")\n   @GET\n   @Transform(SnapshotPages.class)\n   Iterator<ListPage<Snapshot>> list(ListOptions options);\n\n   static final class SnapshotPages extends BaseToIteratorOfListPage<Snapshot, SnapshotPages> {\n\n      private final GoogleComputeEngineApi api;\n\n      @Inject SnapshotPages(GoogleComputeEngineApi api) {\n         this.api = api;\n      }\n\n      @Override protected Function<String, ListPage<Snapshot>> fetchNextPage(final ListOptions options) {\n         return new Function<String, ListPage<Snapshot>>() {\n            @Override public ListPage<Snapshot> apply(String pageToken) {\n               return api.snapshots().listPage(pageToken, options);\n            }\n         };\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/features/SubnetworkApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.util.Iterator;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.QueryParam;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.GoogleComputeEngineApi;\nimport org.jclouds.googlecomputeengine.domain.Operation;\nimport org.jclouds.googlecomputeengine.domain.Subnetwork;\nimport org.jclouds.googlecomputeengine.internal.BaseCallerArg0ToIteratorOfListPage;\nimport org.jclouds.googlecomputeengine.options.ListOptions;\nimport org.jclouds.googlecomputeengine.options.SubnetworkCreationOptions;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SkipEncoding;\nimport org.jclouds.rest.annotations.Transform;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport com.google.common.base.Function;\n\n@SkipEncoding({'/', '='})\n@RequestFilters(OAuthFilter.class)\n@Path(\"/subnetworks\")\n@Consumes(APPLICATION_JSON)\npublic interface SubnetworkApi {\n\n   /**\n    * Returns a network by name or null if not found.\n    */\n   @Named(\"Subnetworks:get\")\n   @GET\n   @Path(\"/{subnetwork}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   Subnetwork get(@PathParam(\"subnetwork\") String subnetworkName);\n\n   /**\n    * Creates a persistent network resource in the specified project with the specified range and specified gateway.\n    *\n    * @param newSubnetwork definition of the subnetwork.\n    * @return an Operation resource. To check on the status of an operation, poll the Operations resource returned to\n    *         you, and look for the status field.\n    */\n   @Named(\"Subnetworks:insert\")\n   @POST\n   @Produces(APPLICATION_JSON)\n   Operation createInNetwork(@BinderParam(BindToJsonPayload.class) SubnetworkCreationOptions newSubnetwork);\n\n   /** Deletes a network by name and returns the operation in progress, or null if not found. */\n   @Named(\"Subnetworks:delete\")\n   @DELETE\n   @Path(\"/{subnetwork}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   Operation delete(@PathParam(\"subnetwork\") String subnetworkName);\n\n   /**\n    * Retrieves the list of network resources available to the specified project.\n    * By default the list as a maximum size of 100, if no options are provided or ListOptions#getMaxResults() has not\n    * been set.\n    *\n    * @param pageToken   marks the beginning of the next list page\n    * @param listOptions listing options\n    * @return a page of the list\n    */\n   @Named(\"Subnetworks:list\")\n   @GET\n   ListPage<Subnetwork> listPage(@Nullable @QueryParam(\"pageToken\") String pageToken, ListOptions listOptions);\n\n   /** @see #listPage(String, ListOptions) */\n   @Named(\"Subnetworks:list\")\n   @GET\n   @Transform(SubnetworkPages.class)\n   Iterator<ListPage<Subnetwork>> list();\n   \n   /** @see #listPage(String, ListOptions) */\n   @Named(\"Subnetworks:list\")\n   @GET\n   @Transform(SubnetworkPages.class)\n   Iterator<ListPage<Subnetwork>> list(ListOptions options);\n\n   static final class SubnetworkPages extends BaseCallerArg0ToIteratorOfListPage<Subnetwork, SubnetworkPages> {\n\n      private final GoogleComputeEngineApi api;\n\n      @Inject SubnetworkPages(GoogleComputeEngineApi api) {\n         this.api = api;\n      }\n\n      @Override protected Function<String, ListPage<Subnetwork>> fetchNextPage(final String region, final ListOptions options) {\n         return new Function<String, ListPage<Subnetwork>>() {\n            @Override public ListPage<Subnetwork> apply(String pageToken) {\n               return api.subnetworksInRegion(region).listPage(pageToken, options);\n            }\n         };\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/features/TargetHttpProxyApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport java.net.URI;\nimport java.util.Iterator;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.googlecomputeengine.GoogleComputeEngineApi;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.domain.Operation;\nimport org.jclouds.googlecomputeengine.domain.TargetHttpProxy;\nimport org.jclouds.googlecomputeengine.internal.BaseToIteratorOfListPage;\nimport org.jclouds.googlecomputeengine.options.ListOptions;\nimport org.jclouds.googlecomputeengine.options.TargetHttpProxyOptions;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SkipEncoding;\nimport org.jclouds.rest.annotations.Transform;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport com.google.common.base.Function;\n\n@SkipEncoding({'/', '='})\n@Consumes(MediaType.APPLICATION_JSON)\n@RequestFilters(OAuthFilter.class)\npublic interface TargetHttpProxyApi {\n\n   /**\n    * Returns the specified target http proxy resource.\n    *\n    * @param targetHttpProxyName name of the targetHttpProxy resource to return.\n    * @return an TargetHttpProxy resource.\n    */\n   @Named(\"TargetHttpProxys:get\")\n   @GET\n   @Path(\"/global/targetHttpProxies/{targetHttpProxy}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   TargetHttpProxy get(@PathParam(\"targetHttpProxy\") String targetHttpProxyName);\n\n   /**\n    * Creates a TargetHttpProxy resource in the specified project using the data included in the request.\n    * @param targetHttpProxyOptions the options of the targetHttpProxy to add.\n    *\n    * @return an Operation resource. To check on the status of an operation, poll the Operations resource returned to\n    *         you, and look for the status field.\n    */\n   @Named(\"TargetHttpProxys:insert\")\n   @POST\n   @Produces(MediaType.APPLICATION_JSON)\n   @Path(\"/global/targetHttpProxies\")\n   Operation create(@BinderParam(BindToJsonPayload.class) TargetHttpProxyOptions targetHttpProxyOptions);\n\n   //TODO (broudy) : Should we remove this because it is redundant?\n   /**\n    * Creates a targetHttpProxy resource in the specified project using the given URI for the urlMap.\n    *\n    * @param name            the name of the targetHttpProxy to be inserted.\n    * @param urlMap          URI of the urlMap this proxy points to.\n    * @return an Operation resource. To check on the status of an operation, poll the Operations resource returned to\n    *         you, and look for the status field.\n    */\n   @Named(\"TargetHttpProxys:insert\")\n   @POST\n   @Produces(MediaType.APPLICATION_JSON)\n   @Path(\"/global/targetHttpProxies\")\n   @MapBinder(BindToJsonPayload.class)\n   Operation create(@PayloadParam(\"name\") String name, @PayloadParam(\"urlMap\") URI urlMap);\n\n   /**\n    * Updates the specified targetHttpProxy resource with the data included in the request.\n    *\n    * @param targetHttpProxyName    the name targetHttpProxy to be updated.\n    * @param urlMap                 the new url map this target http proxy points to.\n    * @return an Operation resource. To check on the status of an operation, poll the Operations resource returned to\n    *         you, and look for the status field.\n    */\n   @Named(\"TargetHttpProxys:setUrlMap\")\n   @POST\n   @Produces(MediaType.APPLICATION_JSON)\n   @Path(\"targetHttpProxies/{targetHttpProxy}/setUrlMap\")\n   @MapBinder(BindToJsonPayload.class)\n   Operation setUrlMap(@PathParam(\"targetHttpProxy\") String targetHttpProxyName,\n                       @PayloadParam(\"urlMap\") URI urlMap);\n\n   /**\n    * Deletes the specified image resource.\n    *\n    * @param targetHttpProxyName name of the targetHttpProxy resource to delete.\n    * @return an Operation resource. To check on the status of an operation, poll the Operations resource returned to\n    *         you, and look for the status field.  If the image did not exist the result is null.\n    */\n   @Named(\"TargetHttpProxys:delete\")\n   @DELETE\n   @Path(\"/global/targetHttpProxies/{targetHttpProxy}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   Operation delete(@PathParam(\"targetHttpProxy\") String targetHttpProxyName);\n\n   /**\n    * Retrieves the list of targetHttpProxy resources available to the specified project.\n    * By default the list as a maximum size of 100, if no options are provided or ListOptions#getMaxResults() has not\n    * been set.\n    *\n    * @param pageToken   marks the beginning of the next list page\n    * @param listOptions listing options\n    * @return a page of the list\n    */\n   @Named(\"TargetHttpProxys:list\")\n   @GET\n   @Path(\"/global/targetHttpProxies\")\n   ListPage<TargetHttpProxy> listPage(@Nullable @QueryParam(\"pageToken\") String pageToken, ListOptions listOptions);\n\n   /** @see #listPage(String, ListOptions) */\n   @Named(\"TargetHttpProxys:list\")\n   @GET\n   @Path(\"/global/targetHttpProxies\")\n   @Transform(TargetHttpProxyPages.class)\n   Iterator<ListPage<TargetHttpProxy>> list();\n\n   /** @see #listPage(String, ListOptions) */\n   @Named(\"TargetHttpProxys:list\")\n   @GET\n   @Path(\"/global/targetHttpProxies\")\n   @Transform(TargetHttpProxyPages.class)\n   Iterator<ListPage<TargetHttpProxy>> list(ListOptions listOptions);\n\n   static final class TargetHttpProxyPages extends BaseToIteratorOfListPage<TargetHttpProxy, TargetHttpProxyPages> {\n\n      private final GoogleComputeEngineApi api;\n\n      @Inject TargetHttpProxyPages(GoogleComputeEngineApi api) {\n         this.api = api;\n      }\n\n      @Override protected Function<String, ListPage<TargetHttpProxy>> fetchNextPage(final ListOptions options) {\n         return new Function<String, ListPage<TargetHttpProxy>>() {\n            @Override public ListPage<TargetHttpProxy> apply(String pageToken) {\n               return api.targetHttpProxies().listPage(pageToken, options);\n            }\n         };\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/features/TargetInstanceApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.util.Iterator;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.QueryParam;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.GoogleComputeEngineApi;\nimport org.jclouds.googlecomputeengine.domain.NewTargetInstance;\nimport org.jclouds.googlecomputeengine.domain.Operation;\nimport org.jclouds.googlecomputeengine.domain.TargetInstance;\nimport org.jclouds.googlecomputeengine.internal.BaseCallerArg0ToIteratorOfListPage;\nimport org.jclouds.googlecomputeengine.options.ListOptions;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SkipEncoding;\nimport org.jclouds.rest.annotations.Transform;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport com.google.common.base.Function;\n\n@SkipEncoding({'/', '='})\n@RequestFilters(OAuthFilter.class)\n@Path(\"/targetInstances\")\n@Consumes(APPLICATION_JSON)\npublic interface TargetInstanceApi {\n\n   /** Returns a targetInstance by name or null if not found. */\n   @Named(\"TargetInstances:get\")\n   @GET\n   @Path(\"/{targetInstance}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   TargetInstance get(@PathParam(\"targetInstance\") String targetInstance);\n\n   /**\n    * Creates a instance resource in the specified project using the data included in the request.\n    *\n    * @param template the instance template\n    * @return an Operation resource. To check on the status of an operation, poll the Operations resource returned to\n    *         you, and look for the status field.\n    */\n   @Named(\"TargetInstances:insert\")\n   @POST\n   @Produces(APPLICATION_JSON)\n   Operation create(@BinderParam(BindToJsonPayload.class) NewTargetInstance targetInstance);\n\n   /** Deletes a targetInstance by name and returns the operation in progress, or null if not found. */\n   @Named(\"TargetInstances:delete\")\n   @DELETE\n   @Path(\"/{targetInstance}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Operation delete(@PathParam(\"targetInstance\") String targetInstance);\n\n   /**\n    * Retrieves the list of targetInstance resources available to the specified project.\n    * By default the list as a maximum size of 100, if no options are provided or ListOptions#getMaxResults() has not\n    * been set.\n    *\n    * @param pageToken   marks the beginning of the next list page\n    * @param listOptions listing options\n    * @return a page of the list\n    */\n   @Named(\"TargetInstances:list\")\n   @GET\n   ListPage<TargetInstance> listPage(@Nullable @QueryParam(\"pageToken\") String pageToken, ListOptions listOptions);\n\n   /** @see #listPage(String, ListOptions) */\n   @Named(\"TargetInstances:list\")\n   @GET\n   @Transform(TargetInstancePages.class)\n   Iterator<ListPage<TargetInstance>> list();\n\n   /** @see #listPage(String, ListOptions) */\n   @Named(\"TargetInstances:list\")\n   @GET\n   @Transform(TargetInstancePages.class)\n   Iterator<ListPage<TargetInstance>> list(ListOptions options);\n\n   static final class TargetInstancePages extends BaseCallerArg0ToIteratorOfListPage<TargetInstance, TargetInstancePages> {\n\n      private final GoogleComputeEngineApi api;\n\n      @Inject TargetInstancePages(GoogleComputeEngineApi api) {\n         this.api = api;\n      }\n\n      @Override\n      protected Function<String, ListPage<TargetInstance>> fetchNextPage(final String zoneName, final ListOptions options) {\n         return new Function<String, ListPage<TargetInstance>>() {\n            @Override public ListPage<TargetInstance> apply(String pageToken) {\n               return api.targetInstancesInZone(zoneName).listPage(pageToken, options);\n            }\n         };\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/features/TargetPoolApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.net.URI;\nimport java.util.Iterator;\nimport java.util.List;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.QueryParam;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.GoogleComputeEngineApi;\nimport org.jclouds.googlecomputeengine.binders.TargetPoolChangeHealthChecksBinder;\nimport org.jclouds.googlecomputeengine.binders.TargetPoolChangeInstancesBinder;\nimport org.jclouds.googlecomputeengine.domain.HealthStatus;\nimport org.jclouds.googlecomputeengine.domain.Operation;\nimport org.jclouds.googlecomputeengine.domain.TargetPool;\nimport org.jclouds.googlecomputeengine.internal.BaseCallerArg0ToIteratorOfListPage;\nimport org.jclouds.googlecomputeengine.options.ListOptions;\nimport org.jclouds.googlecomputeengine.options.TargetPoolCreationOptions;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SkipEncoding;\nimport org.jclouds.rest.annotations.Transform;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport com.google.common.base.Function;\n\n@SkipEncoding({'/', '='})\n@RequestFilters(OAuthFilter.class)\n@Path(\"/targetPools\")\n@Consumes(APPLICATION_JSON)\npublic interface TargetPoolApi {\n\n   /** Returns a target pool by name or null if not found. */\n   @Named(\"TargetPools:get\")\n   @GET\n   @Path(\"/{targetPool}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   TargetPool get(@PathParam(\"targetPool\") String targetPool);\n\n   /**\n    * Creates a TargetPool resource in the specified project and region using the data included in the request.\n    *\n    * @param name the name of the targetPool.\n    * @param options options of the TargetPool to create.\n    * @return an Operation resource. To check on the status of an operation, poll the Operations resource returned to\n    *         you, and look for the status field.\n    */\n   @Named(\"TargetPools:insert\")\n   @POST\n   @Produces(APPLICATION_JSON)\n   Operation create(@BinderParam(BindToJsonPayload.class) TargetPoolCreationOptions options);\n\n   /** Deletes a target pool by name and returns the operation in progress, or null if not found. */\n   @Named(\"TargetPools:delete\")\n   @DELETE\n   @Path(\"/{targetPool}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Operation delete(@PathParam(\"targetPool\") String targetPool);\n\n   /**\n    * Adds instance to the targetPool.\n    *\n    * @param targetPool the name of the target pool.\n    * @param instances the self-links of the instances to be added to targetPool.\n    *\n    * @return an Operation resource. To check on the status of an operation, poll the Operations resource returned to\n    *         you, and look for the status field.\n    */\n   @Named(\"TargetPools:addInstance\")\n   @POST\n   @Path(\"/{targetPool}/addInstance\")\n   @MapBinder(TargetPoolChangeInstancesBinder.class)\n   Operation addInstance(@PathParam(\"targetPool\") String targetPool, @PayloadParam(\"instances\") List<URI> instances);\n\n   /**\n    * Removes instance URL from targetPool.\n    *\n    * @param targetPool the name of the target pool.\n    * @param instances the self-links of the instances to be removed from the targetPool.\n    *\n    * @return an Operation resource. To check on the status of an operation, poll the Operations resource returned to\n    *         you, and look for the status field.\n    */\n   @Named(\"TargetPools:removeInstance\")\n   @POST\n   @Path(\"/{targetPool}/removeInstance\")\n   @MapBinder(TargetPoolChangeInstancesBinder.class)\n   Operation removeInstance(@PathParam(\"targetPool\") String targetPool, @PayloadParam(\"instances\") List<URI> instances);\n\n   /**\n    * Adds health check URL to targetPool.\n    *\n    * @param targetPool the name of the target pool.\n    * @param healthChecks the self-links of the health checks to be added to targetPool.\n    *\n    * @return an Operation resource. To check on the status of an operation, poll the Operations resource returned to\n    *         you, and look for the status field.\n    */\n   @Named(\"TargetPools:addHealthCheck\")\n   @POST\n   @Path(\"/{targetPool}/addHealthCheck\")\n   @MapBinder(TargetPoolChangeHealthChecksBinder.class)\n   Operation addHealthCheck(@PathParam(\"targetPool\") String targetPool, @PayloadParam(\"healthChecks\") List<URI> healthChecks);\n\n\n   /**\n    * Removes health check URL from targetPool.\n    *\n    * @param targetPool the name of the target pool.\n    * @param healthChecks the self-links of the health checks to be removed from the targetPool.\n    *\n    * @return an Operation resource. To check on the status of an operation, poll the Operations resource returned to\n    *         you, and look for the status field.\n    */\n   @Named(\"TargetPools:removeHealthCheck\")\n   @POST\n   @Path(\"/{targetPool}/removeHealthCheck\")\n   @MapBinder(TargetPoolChangeHealthChecksBinder.class)\n   Operation removeHealthCheck(@PathParam(\"targetPool\") String targetPool, @PayloadParam(\"healthChecks\") List<URI> healthChecks);\n\n   /**\n    * Gets the HealthStatus of an instance in a targetPool.\n    *\n    * @param targetPool the name of the target pool.\n    * @param healthChecks the self-links of the health checks to be removed from the targetPool.\n    *\n    * @return an Operation resource. To check on the status of an operation, poll the Operations resource returned to\n    *         you, and look for the status field.\n    */\n   @Named(\"TargetPools:getHealth\")\n   @POST\n   @Path(\"/{targetPool}/getHealth\")\n   @MapBinder(BindToJsonPayload.class)\n   HealthStatus getHealth(@PathParam(\"targetPool\") String targetPool, @PayloadParam(\"instance\") URI instance);\n\n\n   /**\n    * Changes backup pool configurations.\n    *\n    * @param targetPool the name of the target pool.\n    * @param target the URL of target pool for which you want to use as backup.\n    * WARNING: failoverRatio and BackupPool must either both be set or not set. This method\n    *          is only for updating the backup pool on a Target Pool that already has a\n    *          failoverRatio.\n    *\n    * @return an Operation resource. To check on the status of an operation, poll the Operations resource returned to\n    *         you, and look for the status field.\n    */\n   @Named(\"TargetPools:setBackup\")\n   @POST\n   @Path(\"/{targetPool}/setBackup\")\n   @MapBinder(BindToJsonPayload.class)\n   @Nullable\n   Operation setBackup(@PathParam(\"targetPool\") String targetPool, @PayloadParam(\"target\") URI target);\n\n   /**\n    * Changes backup pool configurations.\n    *\n    * @param targetPool the name of the target pool.\n    * @param target the URL of target pool for which you want to use as backup.\n    *\n    * @return an Operation resource. To check on the status of an operation, poll the Operations resource returned to\n    *         you, and look for the status field.\n    */\n   @Named(\"TargetPools:setBackup\")\n   @POST\n   @Path(\"/{targetPool}/setBackup\")\n   @MapBinder(BindToJsonPayload.class)\n   @Nullable\n   Operation setBackup(@PathParam(\"targetPool\") String targetPool, @QueryParam(\"failoverRatio\") Float failoverRatio, @PayloadParam(\"target\") URI target);\n\n   /**\n    * Retrieves the list of target pool resources available to the specified project.\n    * By default the list as a maximum size of 100, if no options are provided or ListOptions#getMaxResults() has not\n    * been set.\n    *\n    * @param pageToken   marks the beginning of the next list page\n    * @param listOptions listing options\n    * @return a page of the list\n    */\n   @Named(\"TargetPools:list\")\n   @GET\n   ListPage<TargetPool> listPage(@Nullable @QueryParam(\"pageToken\") String pageToken, ListOptions listOptions);\n\n   /** @see #listPage(String, ListOptions) */\n   @Named(\"TargetPools:list\")\n   @GET\n   @Transform(TargetPoolPages.class)\n   Iterator<ListPage<TargetPool>> list();\n\n   /** @see #listPage(String, ListOptions) */\n   @Named(\"TargetPools:list\")\n   @GET\n   @Transform(TargetPoolPages.class)\n   Iterator<ListPage<TargetPool>> list(ListOptions options);\n\n   static final class TargetPoolPages extends BaseCallerArg0ToIteratorOfListPage<TargetPool, TargetPoolPages> {\n\n      private final GoogleComputeEngineApi api;\n\n      @Inject TargetPoolPages(GoogleComputeEngineApi api) {\n         this.api = api;\n      }\n\n      @Override\n      protected Function<String, ListPage<TargetPool>> fetchNextPage(final String regionName,\n            final ListOptions options) {\n         return new Function<String, ListPage<TargetPool>>() {\n            @Override public ListPage<TargetPool> apply(String pageToken) {\n               return api.targetPoolsInRegion(regionName).listPage(pageToken, options);\n            }\n         };\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/features/UrlMapApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.net.URI;\nimport java.util.Iterator;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.QueryParam;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.googlecomputeengine.GoogleComputeEngineApi;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.domain.Operation;\nimport org.jclouds.googlecomputeengine.domain.UrlMap;\nimport org.jclouds.googlecomputeengine.domain.UrlMapValidateResult;\nimport org.jclouds.googlecomputeengine.internal.BaseToIteratorOfListPage;\nimport org.jclouds.googlecomputeengine.options.ListOptions;\nimport org.jclouds.googlecomputeengine.options.UrlMapOptions;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PATCH;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SkipEncoding;\nimport org.jclouds.rest.annotations.Transform;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport com.google.common.base.Function;\n\n@SkipEncoding({'/', '='})\n@RequestFilters(OAuthFilter.class)\n@Consumes(APPLICATION_JSON)\npublic interface UrlMapApi {\n\n   /** Returns the specified urlMap resource by name or null if not found. */\n   @Named(\"UrlMaps:get\")\n   @GET\n   @Path(\"/{urlMap}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   UrlMap get(@PathParam(\"urlMap\") String urlMapName);\n\n   /**\n    * Creates a urlMap resource in the specified project using the data included in the request.\n    * @param urlMapOptions   the options of the urlMap to add.\n    *\n    * @return an Operation resource. To check on the status of an operation, poll the Operations resource returned to\n    *         you, and look for the status field.\n    */\n   @Named(\"UrlMaps:insert\")\n   @POST\n   @Produces(APPLICATION_JSON)\n   Operation create(@BinderParam(BindToJsonPayload.class) UrlMapOptions urlMapOptions);\n\n   /**\n    * Creates a urlMap resource in the specified project using the data included in the request.\n    *\n    * @param name            the name of the urlMap to be inserted.\n    * @param defaultService  the default backend service of the urlMap to add.\n    * @return an Operation resource. To check on the status of an operation, poll the Operations resource returned to\n    *         you, and look for the status field.\n    */\n   @Named(\"UrlMaps:insert\")\n   @POST\n   @Produces(APPLICATION_JSON)\n   @MapBinder(BindToJsonPayload.class)\n   Operation create(@PayloadParam(\"name\") String name,\n                    @PayloadParam(\"defaultService\") URI defaultService);\n\n   /**\n    * Updates the specified urlMap resource with the data included in the request.\n    *\n    * @param urlMapName    the name urlMap to be updated.\n    * @param urlMapOptions the new urlMap options.\n    * @return an Operation resource. To check on the status of an operation, poll the Operations resource returned to\n    *         you, and look for the status field.\n    */\n   @Named(\"UrlMaps:update\")\n   @PUT\n   @Produces(APPLICATION_JSON)\n   @Path(\"/{urlMap}\")\n   Operation update(@PathParam(\"urlMap\") String urlMapName,\n                    @BinderParam(BindToJsonPayload.class) UrlMapOptions urlMapOptions);\n\n   /**\n    * Updates the specified urlMap resource, with patch semantics, with the data included in the request.\n    * Note:{@link UrlMapOptions.Builder#buildForPatch()} may be helpful.\n    *\n    * @param urlMapName    the name urlMap to be updated.\n    * @param urlMapOptions the new urlMap options.\n    * @return an Operation resource. To check on the status of an operation, poll the Operations resource returned to\n    *         you, and look for the status field.\n    */\n   @Named(\"UrlMaps:patch\")\n   @PATCH\n   @Produces(APPLICATION_JSON)\n   @Path(\"/{urlMap}\")\n   Operation patch(@PathParam(\"urlMap\") String urlMapName,\n                   @BinderParam(BindToJsonPayload.class) UrlMapOptions urlMapOptions);\n\n   /**\n    * Deletes the specified urlMap resource.\n    *\n    * @param urlMapName name of the urlMap resource to delete.\n    * @return an Operation resource. To check on the status of an operation, poll the Operations resource returned to\n    *         you, and look for the status field.  If the image did not exist the result is null.\n    */\n   @Named(\"UrlMaps:delete\")\n   @DELETE\n   @Path(\"/{urlMap}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   Operation delete(@PathParam(\"urlMap\") String urlMapName);\n\n   /**\n    * Runs the tests specified for the give urlMap resource.\n    *\n    * @param urlMapName name of the urlMap to run tests on.\n    * @param options    options that represent the url map to be tested.\n    * @return the result of the tests for the given urlMap resource.\n    */\n   @Named(\"UrlMaps:validate\")\n   @POST\n   @Path(\"/{urlMap}/validate\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   @MapBinder(BindToJsonPayload.class)\n   UrlMapValidateResult validate(@PathParam(\"urlMap\") String urlMapName,\n                                 @PayloadParam(\"resource\") UrlMapOptions options);\n\n   /**\n    * Runs the tests specified for the give urlMap resource.\n    *\n    * @param urlMapName name of the urlMap to run tests on.\n    * @param urlMap     the url map to be tested.\n    * @return the result of the tests for the given urlMap resource.\n    */\n   @Named(\"UrlMaps:validate\")\n   @POST\n   @Path(\"/{urlMap}/validate\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   @MapBinder(BindToJsonPayload.class)\n   UrlMapValidateResult validate(@PathParam(\"urlMap\") String urlMapName,\n                                 @PayloadParam(\"resource\") UrlMap urlMap);\n\n   /**\n    * Retrieves the list of urlMap resources available to the specified project.\n    * By default the list as a maximum size of 100, if no options are provided or ListOptions#getMaxResults() has not\n    * been set.\n    *\n    * @param pageToken   marks the beginning of the next list page\n    * @param listOptions listing options\n    * @return a page of the list\n    */\n   @Named(\"UrlMaps:list\")\n   @GET\n   ListPage<UrlMap> listPage(@Nullable @QueryParam(\"pageToken\") String pageToken, ListOptions listOptions);\n\n   /** @see #listPage(String, String, ListOptions) */\n   @Named(\"UrlMaps:list\")\n   @GET\n   @Transform(UrlMapPages.class)\n   Iterator<ListPage<UrlMap>> list();\n\n   /** @see #listPage(String, String, ListOptions) */\n   @Named(\"UrlMaps:list\")\n   @GET\n   @Transform(UrlMapPages.class)\n   Iterator<ListPage<UrlMap>> list(ListOptions options);\n\n   static final class UrlMapPages extends BaseToIteratorOfListPage<UrlMap, UrlMapPages> {\n\n      private final GoogleComputeEngineApi api;\n\n      @Inject UrlMapPages(GoogleComputeEngineApi api) {\n         this.api = api;\n      }\n\n      @Override protected Function<String, ListPage<UrlMap>> fetchNextPage(final ListOptions options) {\n         return new Function<String, ListPage<UrlMap>>() {\n            @Override public ListPage<UrlMap> apply(String pageToken) {\n               return api.urlMaps().listPage(pageToken, options);\n            }\n         };\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/features/ZoneApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.util.Iterator;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.QueryParam;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.GoogleComputeEngineApi;\nimport org.jclouds.googlecomputeengine.domain.Zone;\nimport org.jclouds.googlecomputeengine.internal.BaseToIteratorOfListPage;\nimport org.jclouds.googlecomputeengine.options.ListOptions;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.oauth.v2.filters.OAuthFilter;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.SkipEncoding;\nimport org.jclouds.rest.annotations.Transform;\n\nimport com.google.common.base.Function;\n\n@SkipEncoding({'/', '='})\n@RequestFilters(OAuthFilter.class)\n@Path(\"/zones\")\n@Consumes(APPLICATION_JSON)\npublic interface ZoneApi {\n\n   /** Returns a zone by name or null if not found. */\n   @Named(\"Zones:get\")\n   @GET\n   @Path(\"/{zone}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   Zone get(@PathParam(\"zone\") String zone);\n\n   /**\n    * Retrieves the list of zone resources available to the specified project.\n    * By default the list as a maximum size of 100, if no options are provided or ListOptions#getMaxResults() has not\n    * been set.\n    *\n    * @param pageToken   marks the beginning of the next list page\n    * @param listOptions listing options\n    * @return a page of the list\n    */\n   @Named(\"Zones:list\")\n   @GET\n   ListPage<Zone> listPage(@Nullable @QueryParam(\"pageToken\") String pageToken, ListOptions listOptions);\n\n   /** @see #listPage(String, ListOptions) */\n   @Named(\"Zones:list\")\n   @GET\n   @Transform(ZonePages.class)\n   Iterator<ListPage<Zone>> list();\n\n   /** @see #listPage(String, ListOptions) */\n   @Named(\"Zones:list\")\n   @GET\n   @Transform(ZonePages.class)\n   Iterator<ListPage<Zone>> list(ListOptions options);\n\n   static final class ZonePages extends BaseToIteratorOfListPage<Zone, ZonePages> {\n\n      private final GoogleComputeEngineApi api;\n\n      @Inject ZonePages(GoogleComputeEngineApi api) {\n         this.api = api;\n      }\n\n      @Override protected Function<String, ListPage<Zone>> fetchNextPage(final ListOptions options) {\n         return new Function<String, ListPage<Zone>>() {\n            @Override public ListPage<Zone> apply(String pageToken) {\n               return api.zones().listPage(pageToken, options);\n            }\n         };\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/handlers/GoogleComputeEngineErrorHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.handlers;\n\nimport static org.jclouds.http.HttpUtils.closeClientButKeepContentStream;\n\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.ResourceNotFoundException;\n\n/**\n * This will parse and set an appropriate exception on the command object.\n */\npublic class GoogleComputeEngineErrorHandler implements HttpErrorHandler {\n   public void handleError(HttpCommand command, HttpResponse response) {\n      // it is important to always read fully and close streams\n      byte[] data = closeClientButKeepContentStream(response);\n      String message = data != null ? new String(data) : null;\n\n      Exception exception = message != null ? new HttpResponseException(command, response, message)\n              : new HttpResponseException(command, response);\n      message = message != null ? message : String.format(\"%s -> %s\", command.getCurrentRequest().getRequestLine(),\n              response.getStatusLine());\n      switch (response.getStatusCode()) {\n         case 400:\n            break;\n         case 401:\n         case 403:\n            exception = new AuthorizationException(message, exception);\n            break;\n         case 404:\n            if (!command.getCurrentRequest().getMethod().equals(\"DELETE\")) {\n               exception = new ResourceNotFoundException(message, exception);\n            }\n            break;\n         case 409:\n            exception = new IllegalStateException(message, exception);\n            break;\n      }\n      command.setException(exception);\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/internal/BaseArg0ToIteratorOfListPage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.internal;\n\nimport org.jclouds.googlecomputeengine.options.ListOptions;\n\npublic abstract class BaseArg0ToIteratorOfListPage<T, I extends BaseArg0ToIteratorOfListPage<T, I>>\n      extends org.jclouds.googlecloud.internal.BaseArg0ToIteratorOfListPage<T, ListOptions, I> {\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/internal/BaseCallerArg0ToIteratorOfListPage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.internal;\n\nimport org.jclouds.googlecomputeengine.options.ListOptions;\n\npublic abstract class BaseCallerArg0ToIteratorOfListPage<T, I extends BaseCallerArg0ToIteratorOfListPage<T, I>>\n      extends org.jclouds.googlecloud.internal.BaseCallerArg0ToIteratorOfListPage<T, ListOptions, I> {\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/internal/BaseToIteratorOfListPage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.internal;\n\nimport org.jclouds.googlecomputeengine.options.ListOptions;\n\npublic abstract class BaseToIteratorOfListPage<T, I extends BaseToIteratorOfListPage<T, I>>\n      extends org.jclouds.googlecloud.internal.BaseToIteratorOfListPage<T, ListOptions, I> {\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/options/AddressCreationOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class AddressCreationOptions {\n\n   public abstract String name();\n   @Nullable public abstract String address();\n   @Nullable public abstract String description();\n\n   @SerializedNames({\"name\", \"address\", \"description\"})\n   static AddressCreationOptions create(String name, String address, String description){\n      return new AutoValue_AddressCreationOptions(name, address, description);\n   }\n\n   public static class Builder {\n      private String name;\n      private String address;\n      private String description;\n\n      public Builder(String name) {\n         this.name = name;\n      }\n\n      public Builder address(String address) {\n         this.address = address;\n         return this;\n      }\n\n      public Builder description(String description) {\n         this.description = description;\n         return this;\n      }\n\n      public AddressCreationOptions build() {\n         checkNotNull(name, \"AddressCreationOptions name cannot be null\");\n         return create(name, address, description);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/options/BackendServiceOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.options;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport org.jclouds.googlecomputeengine.domain.BackendService.Backend;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class BackendServiceOptions {\n\n   @Nullable public abstract String name();\n   @Nullable public abstract String description();\n   @Nullable public abstract List<URI> healthChecks();\n   @Nullable public abstract List<Backend> backends();\n   @Nullable public abstract Integer timeoutSec();\n   @Nullable public abstract Integer port();\n   @Nullable public abstract String protocol();\n   @Nullable public abstract String fingerprint();\n   @Nullable public abstract String portName();\n\n   @SerializedNames({\"name\", \"description\", \"healthChecks\", \"backends\", \"timeoutSec\",\n      \"port\", \"protocol\", \"fingerprint\", \"portName\"})\n   static BackendServiceOptions create(String name, String description, List<URI> healthChecks,\n         List<Backend> backends, Integer timeoutSec, Integer port, String protocol, String fingerprint, String portName){\n      return new AutoValue_BackendServiceOptions(name, description, healthChecks,\n            backends, timeoutSec, port, protocol, fingerprint, portName);\n   }\n\n   BackendServiceOptions(){\n   }\n\n   public static class Builder {\n\n      private String name;\n      private String description;\n      private List<URI> healthChecks;\n      private List<Backend> backends;\n      private Integer timeoutSec;\n      private Integer port;\n      private String protocol;\n      private String fingerprint;\n      private String portName;\n\n      /**\n       * @param name, provided by the client.\n       * @param healthChecks The list of {@link HttpHealthCheck#selfLink Links} to the HttpHealthCheck\n       * resource for health checking this BackendService.\n       * Currently at most one health check can be specified, and a health check is required.\n       */\n      public Builder(String name, List<URI> healthChecks){\n         this.name = name;\n         this.healthChecks = healthChecks;\n      }\n\n      /**\n       * Empty builder for use when patching or updating and existing BackendService\n       * Otherwise use the other {@link #Builder(String, List) builder}\n       */\n      public Builder(){\n      }\n\n      /**\n       * An optional textual description of the BackendService.\n       */\n      public Builder description(String description){\n         this.description =  description;\n         return this;\n      }\n\n      /**\n       *  HealthChecks - The list of {@link HttpHealthCheck#selfLink Links} to the HttpHealthCheck\n       * resource for health checking this BackendService.\n       * Currently at most one health check can be specified, and a health check is required.\n       */\n      public Builder healthChecks(List<URI> healthChecks){\n         this.healthChecks =  healthChecks;\n         return this;\n      }\n\n      /**\n       * The list of backends that serve this BackendService.\n       */\n      public Builder backends(List<Backend> backends){\n         this.backends = backends;\n         return this;\n      }\n\n      /**\n       * How many seconds to wait for the backend before considering it a failed request.\n       * Default is 30 seconds.\n       */\n      public Builder timeoutSec(Integer timeoutSec) {\n         this.timeoutSec = timeoutSec;\n         return this;\n      }\n\n      /**\n       * The TCP port to connect on the backend.\n       * The default value is 80.\n       */\n      public Builder port(Integer port) {\n         this.port = port;\n         return this;\n      }\n\n      /**\n       * The  protocol for incoming requests.\n       */\n      public Builder protocol(String protocol) {\n         this.protocol = protocol;\n         return this;\n      }\n\n      /**\n       * Fingerprint of this resource. A hash of the contents stored in this object.\n       * This field is used in optimistic locking. This field will be ignored when\n       * inserting a BackendService. An up-to-date fingerprint must be provided in\n       * order to update the BackendService.\n       */\n      public Builder fingerprint(String fingerprint) {\n         this.fingerprint = fingerprint;\n         return this;\n      }\n\n      public Builder portName(String portName) {\n         this.portName = portName;\n         return this;\n      }\n\n      public BackendServiceOptions build(){\n         return create(name, description, healthChecks,\n               backends, timeoutSec, port, protocol, fingerprint, portName);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/options/DeprecateOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.options;\n\nimport java.net.URI;\nimport java.util.Date;\n\nimport org.jclouds.googlecomputeengine.domain.Deprecated.State;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n/**\n * Options to set the deprecation status of a resource. Currently only for images.\n *\n * @see <a href=\"https://developers.google.com/compute/docs/reference/latest/images/deprecate\" />\n */\n@AutoValue\npublic abstract class DeprecateOptions {\n\n   @Nullable public abstract State state();\n   @Nullable public abstract URI replacement();\n   @Nullable public abstract Date deprecated();\n   @Nullable public abstract Date obsolete();\n   @Nullable public abstract Date deleted();\n\n   @SerializedNames({\"state\", \"replacement\", \"deprecated\", \"obsolete\", \"deleted\"})\n   static DeprecateOptions create(State state, URI replacement, Date deprecated,\n         Date obsolete, Date deleted){\n      return new AutoValue_DeprecateOptions(state, replacement, deprecated, obsolete, deleted);\n   }\n\n   DeprecateOptions(){\n   }\n\n   public static class Builder {\n      private State state;\n      private URI replacement;\n      private Date deprecated;\n      private Date obsolete;\n      private Date deleted;\n\n      /**\n       * The new deprecation state.\n       *\n       * @return the new deprecation state.\n       */\n      public Builder state(State state) {\n         this.state = state;\n         return this;\n      }\n\n      /**\n       * Optional URL for replacement of deprecated resource.\n       *\n       * @return the URL\n       */\n      public Builder replacement(URI replacement) {\n         this.replacement = replacement;\n         return this;\n      }\n\n      /**\n       * Optional RFC3339 timestamp for when the deprecation state was changed to DEPRECATED.\n       *\n       * @return the timestamp\n       */\n      public Builder deprecated(Date deprecated) {\n         this.deprecated = deprecated;\n         return this;\n      }\n\n      /**\n       * Optional RFC3339 timestamp for when the deprecation state was changed to OBSOLETE.\n       *\n       * @return the timestamp\n       */\n      public Builder obsolete(Date obsolete) {\n         this.obsolete = obsolete;\n         return this;\n      }\n\n      /**\n       * Optional RFC3339 timestamp for when the deprecation state was changed to DELETED.\n       *\n       * @return the timestamp\n       */\n      public Builder deleted(Date deleted) {\n         this.deleted = deleted;\n         return this;\n      }\n\n      public DeprecateOptions build(){\n         return create(state, replacement, deprecated,\n               obsolete, deleted);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/options/DiskCreationOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.options;\n\nimport java.net.URI;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class DiskCreationOptions {\n\n   @Nullable public abstract URI type();\n   @Nullable public abstract Integer sizeGb();\n   @Nullable public abstract URI sourceSnapshot();\n   @Nullable public abstract String description();\n\n   @SerializedNames({\"type\", \"sizeGb\", \"sourceSnapshot\", \"description\"})\n   static DiskCreationOptions create(URI type, Integer sizeGb, URI sourceSnapshot,\n         String description){\n      return new AutoValue_DiskCreationOptions(type, sizeGb, sourceSnapshot, description);\n   }\n\n   DiskCreationOptions(){\n   }\n\n   public static class Builder {\n\n      private URI type;\n      private Integer sizeGb;\n      private URI sourceSnapshot;\n      private String description;\n\n      /**\n       * The disk type, fully qualified URL for the disk type.\n       *\n       * @return the disk type\n       */\n      public Builder type(URI type) {\n         this.type = type;\n         return this;\n      }\n\n      /**\n       * Size of the persistent disk, specified in GB.\n       * You can also specify this when creating a persistent disk\n       * using the sourceImage or sourceSnapshot parameter.\n       */\n      public Builder sizeGb(Integer sizeGb) {\n         this.sizeGb = sizeGb;\n         return this;\n      }\n\n      /**\n       * The source snapshot\n       *\n       * @return sourceSnapshot, fully qualified URL for the snapshot to be copied.\n       */\n      public Builder sourceSnapshot(URI sourceSnapshot) {\n         this.sourceSnapshot = sourceSnapshot;\n         return this;\n      }\n\n      /**\n       * The description\n       *\n       * @return description, An optional textual description of the resource.\n       */\n      public Builder description(String description) {\n         this.description = description;\n         return this;\n      }\n\n      public DiskCreationOptions build(){\n         return create(type, sizeGb, sourceSnapshot, description);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/options/FirewallOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.options;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport org.jclouds.googlecomputeengine.domain.Firewall;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Options to insert a firewall.\n *\n * @see Firewall\n */\npublic class FirewallOptions {\n\n   private String name;\n   private URI network;\n   private String description;\n   private ImmutableList.Builder<String> sourceRanges = ImmutableList.builder();\n   private ImmutableList.Builder<String> sourceTags = ImmutableList.builder();\n   private ImmutableList.Builder<String> targetTags = ImmutableList.builder();\n   private ImmutableList.Builder<Firewall.Rule> allowed = ImmutableList.builder();\n\n   /**\n    * @see org.jclouds.googlecomputeengine.domain.Firewall#allowed()\n    */\n   public List<Firewall.Rule> getAllowed() {\n      return allowed.build();\n   }\n\n   /**\n    * @see org.jclouds.googlecomputeengine.domain.Firewall#allowed()\n    */\n   public FirewallOptions addAllowedRule(Firewall.Rule allowedRule) {\n      this.allowed.add(allowedRule);\n      return this;\n   }\n\n   /**\n    * @see org.jclouds.googlecomputeengine.domain.Firewall#allowed()\n    */\n   public FirewallOptions allowedRules(List<Firewall.Rule> allowedRules) {\n      this.allowed = ImmutableList.builder();\n      this.allowed.addAll(allowedRules);\n      return this;\n   }\n\n   /**\n    * @see org.jclouds.googlecomputeengine.domain.Firewall#name()\n    */\n   public FirewallOptions name(String name) {\n      this.name = name;\n      return this;\n   }\n\n   /**\n    * @see org.jclouds.googlecomputeengine.domain.Firewall#name()\n    */\n   public String name() {\n      return name;\n   }\n\n   /**\n    * @see org.jclouds.googlecomputeengine.domain.Firewall#description()\n    */\n   public FirewallOptions description(String description) {\n      this.description = description;\n      return this;\n   }\n\n   /**\n    * @see org.jclouds.googlecomputeengine.domain.Firewall#description()\n    */\n   public String description() {\n      return description;\n   }\n\n   /**\n    * @see org.jclouds.googlecomputeengine.domain.Firewall#network()\n    */\n   public FirewallOptions network(URI network) {\n      this.network = network;\n      return this;\n   }\n\n   /**\n    * @see org.jclouds.googlecomputeengine.domain.Firewall#network()\n    */\n   public URI network() {\n      return network;\n   }\n\n   /**\n    * @see org.jclouds.googlecomputeengine.domain.Firewall#sourceRanges()\n    */\n   public List<String> sourceRanges() {\n      return sourceRanges.build();\n   }\n\n   /**\n    * @see org.jclouds.googlecomputeengine.domain.Firewall#sourceRanges()\n    */\n   public FirewallOptions addSourceRange(String sourceRange) {\n      this.sourceRanges.add(sourceRange);\n      return this;\n   }\n\n   /**\n    * @see org.jclouds.googlecomputeengine.domain.Firewall#sourceRanges()\n    */\n   public FirewallOptions sourceRanges(Iterable<String> sourceRanges) {\n      this.sourceRanges = ImmutableList.builder();\n      this.sourceRanges.addAll(sourceRanges);\n      return this;\n   }\n\n   /**\n    * @see org.jclouds.googlecomputeengine.domain.Firewall#sourceTags()\n    */\n   public List<String> sourceTags() {\n      return sourceTags.build();\n   }\n\n   /**\n    * @see org.jclouds.googlecomputeengine.domain.Firewall#sourceTags()\n    */\n   public FirewallOptions addSourceTag(String sourceTag) {\n      this.sourceTags.add(sourceTag);\n      return this;\n   }\n\n   /**\n    * @see org.jclouds.googlecomputeengine.domain.Firewall#sourceTags()\n    */\n   public FirewallOptions sourceTags(Iterable<String> sourceTags) {\n      this.sourceTags = ImmutableList.builder();\n      this.sourceTags.addAll(sourceTags);\n      return this;\n   }\n\n   /**\n    * @see org.jclouds.googlecomputeengine.domain.Firewall#targetTags()\n    */\n   public List<String> targetTags() {\n      return targetTags.build();\n   }\n\n   /**\n    * @see org.jclouds.googlecomputeengine.domain.Firewall#targetTags()\n    */\n   public FirewallOptions addTargetTag(String targetTag) {\n      this.targetTags.add(targetTag);\n      return this;\n   }\n\n   /**\n    * @see org.jclouds.googlecomputeengine.domain.Firewall#targetTags()\n    */\n   public FirewallOptions targetTags(List<String> targetTags) {\n      this.targetTags = ImmutableList.builder();\n      this.targetTags.addAll(targetTags);\n      return this;\n   }\n}\n\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/options/ForwardingRuleCreationOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.options;\n\nimport java.net.URI;\n\nimport org.jclouds.googlecomputeengine.domain.ForwardingRule;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n/**\n * Options for creating a Forwarding Rule\n */\n@AutoValue\npublic abstract class ForwardingRuleCreationOptions{\n\n   @Nullable public abstract String description();\n   @Nullable public abstract String ipAddress();\n   @Nullable public abstract ForwardingRule.IPProtocol ipProtocol();\n   @Nullable public abstract String portRange();\n   @Nullable public abstract URI target();\n\n\n   @SerializedNames({\"description\", \"ipAddress\", \"ipProtocol\", \"portRange\", \"target\"})\n   static ForwardingRuleCreationOptions create(\n         String description, String ipAddress, ForwardingRule.IPProtocol ipProtocol,\n         String portRange, URI target){\n      return new AutoValue_ForwardingRuleCreationOptions(description, ipAddress, ipProtocol, portRange, target);\n   }\n\n   ForwardingRuleCreationOptions(){\n   }\n\n   public static class Builder {\n\n      private String description;\n      private String ipAddress;\n      private ForwardingRule.IPProtocol ipProtocol;\n      private String portRange;\n      private URI target;\n\n      /**\n       * An optional textual description of the TargetPool.\n       * @return description, provided by the client.\n       */\n      public Builder description(String description){\n         this.description = description;\n         return this;\n      }\n\n      /**\n       * The external IP address that this forwarding rule is serving on behalf of\n       * @return ipAddress\n       */\n      public Builder ipAddress(String ipAddress){\n         this.ipAddress = ipAddress;\n         return this;\n      }\n\n      /**\n       * The IP protocol to which this rule applies\n       * @return ipProtocol\n       */\n      public Builder ipProtocol(ForwardingRule.IPProtocol ipProtocol){\n         this.ipProtocol = ipProtocol;\n         return this;\n      }\n\n      /**\n       * If IPProtocol is TCP or UDP, packets addressed to ports in the specified range\n       * will be forwarded to backend. By default, this is empty and all ports are allowed.\n       * @return portRange\n       */\n      public Builder portRange(String portRange){\n         this.portRange = portRange;\n         return this;\n      }\n\n      /**\n       * The URL of the target resource to receive the matched traffic.\n       * The target resource must live in the same region as this forwarding rule.\n       * @return target\n       */\n      public Builder target(URI target){\n         this.target = target;\n         return this;\n      }\n\n      public ForwardingRuleCreationOptions build() {\n         return create(description, ipAddress, ipProtocol, portRange, target);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/options/HttpHealthCheckCreationOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.options;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class HttpHealthCheckCreationOptions {\n\n   @Nullable public abstract String host();\n   @Nullable public abstract String requestPath();\n   @Nullable public abstract Integer port();\n   @Nullable public abstract Integer checkIntervalSec();\n   @Nullable public abstract Integer timeoutSec();\n   @Nullable public abstract Integer unhealthyThreshold();\n   @Nullable public abstract Integer healthyThreshold();\n   @Nullable public abstract String description();\n\n   static final String DEFAULT_REQUEST_PATH = \"/\";\n   static final int DEFAULT_PORT = 80;\n   static final int DEFAULT_CHECK_INTERVAL_SEC = 5;\n   static final int DEFAULT_TIMEOUT_SEC = 5;\n   static final int DEFAULT_UNHEALTHY_THRESHOLD = 2;\n   static final int DEFAULT_HEALTHY_THRESHOLD = 2;\n\n   /*\n    * Currently GCE is not setting the advertised defaults so we do so here.\n    * This only leads to trouble in the case of a PATCH operation which we now\n    * have a workaround for.\n    */\n   /**\n    * @param requestPath Defaults to {@value #DEFAULT_REQUEST_PATH} when null.\n    * @param port Defaults to {@value #DEFAULT_PORT} when null.\n    * @param checkIntervalSec Defaults to {@value #DEFAULT_CHECK_INTERVAL_SEC} when null.\n    * @param timeoutSec Defaults to {@value #DEFAULT_TIMEOUT_SEC} when null.\n    * @param unhealthyThreshold Defaults to {@value #DEFAULT_UNHEALTHY_THRESHOLD} when null.\n    * @param healthyThreshold Defaults to {@value #DEFAULT_HEALTHY_THRESHOLD} when null.\n    */\n   static HttpHealthCheckCreationOptions createWithDefaults(String host,\n         String requestPath, Integer port, Integer checkIntervalSec, Integer timeoutSec, Integer unhealthyThreshold,\n         Integer healthyThreshold, String description) {\n      return create(host, requestPath != null ? requestPath : DEFAULT_REQUEST_PATH, port != null ? port : DEFAULT_PORT,\n            checkIntervalSec != null ? checkIntervalSec : DEFAULT_CHECK_INTERVAL_SEC,\n            timeoutSec != null ? timeoutSec : DEFAULT_TIMEOUT_SEC,\n            unhealthyThreshold != null ? unhealthyThreshold : DEFAULT_UNHEALTHY_THRESHOLD,\n            healthyThreshold != null ? healthyThreshold : DEFAULT_HEALTHY_THRESHOLD, description);\n   }\n\n   @SerializedNames(\n         { \"host\", \"requestPath\", \"port\", \"checkIntervalSec\", \"timeoutSec\",\n               \"unhealthyThreshold\", \"healthyThreshold\", \"description\"})\n   static HttpHealthCheckCreationOptions create(String host, String requestPath, Integer port,\n         Integer checkIntervalSec, Integer timeoutSec, Integer unhealthyThreshold,\n         Integer healthyThreshold, String description) {\n      return new AutoValue_HttpHealthCheckCreationOptions(host, requestPath, port,\n            checkIntervalSec, timeoutSec, unhealthyThreshold, healthyThreshold, description);\n   }\n\n   HttpHealthCheckCreationOptions() {\n   }\n\n   public static class Builder {\n\n      private String host;\n      private String requestPath;\n      private Integer port;\n      private Integer checkIntervalSec;\n      private Integer timeoutSec;\n      private Integer unhealthyThreshold;\n      private Integer healthyThreshold;\n      private String description;\n\n\n      /** The value of the host header in the HTTP health check request. */\n      public Builder host(String host){\n         this.host = host;\n         return this;\n      }\n\n      /** The request path of the HTTP health check request. The default value is {@value #DEFAULT_REQUEST_PATH}. */\n      public Builder requestPath(String requestPath){\n         this.requestPath = requestPath;\n         return this;\n      }\n\n      /** The TCP port number for the HTTP health check request. The default value is {@value #DEFAULT_PORT}. */\n      public Builder port(Integer port){\n         this.port = port;\n         return this;\n      }\n\n      /** How often (in seconds) to send a health check. The default value is {@value #DEFAULT_CHECK_INTERVAL_SEC} seconds. */\n      public Builder checkIntervalSec(Integer checkIntervalSec){\n         this.checkIntervalSec = checkIntervalSec;\n         return this;\n      }\n\n      /** How long (in seconds) to wait before claiming failure. The default value is {@value #DEFAULT_TIMEOUT_SEC} seconds. */\n      public Builder timeoutSec(Integer timeoutSec){\n         this.timeoutSec = timeoutSec;\n         return this;\n      }\n\n      /**\n       * A so-far healthy VM will be marked unhealthy after this many consecutive failures.\n       * The default value is {@value #DEFAULT_UNHEALTHY_THRESHOLD}.\n       */\n      public Builder unhealthyThreshold(Integer unhealthyThreshold){\n         this.unhealthyThreshold = unhealthyThreshold;\n         return this;\n      }\n\n      /**\n       * An unhealthy VM will be marked healthy after this many consecutive successes.\n       * The default value is {@value #DEFAULT_HEALTHY_THRESHOLD}.\n       */\n      public Builder healthyThreshold(Integer healthyThreshold){\n         this.healthyThreshold = healthyThreshold;\n         return this;\n      }\n\n      /** An optional textual description of the TargetPool. */\n      public Builder description(String description){\n         this.description = description;\n         return this;\n      }\n\n      /**\n       * Fields left as null will be replaced with their default before the request\n       * is made.\n       * @param requestPath Defaults to {@value #DEFAULT_REQUEST_PATH} when null.\n       * @param port Defaults to {@value #DEFAULT_PORT} when null.\n       * @param checkIntervalSec Defaults to {@value #DEFAULT_CHECK_INTERVAL_SEC} when null.\n       * @param timeoutSec Defaults to {@value #DEFAULT_TIMEOUT_SEC} when null.\n       * @param unhealthyThreshold Defaults to {@value #DEFAULT_UNHEALTHY_THRESHOLD} when null.\n       * @param healthyThreshold Defaults to {@value #DEFAULT_HEALTHY_THRESHOLD} when null.\n       */\n      public HttpHealthCheckCreationOptions buildWithDefaults() {\n         return HttpHealthCheckCreationOptions.createWithDefaults(host, requestPath, port,\n               checkIntervalSec, timeoutSec, unhealthyThreshold, healthyThreshold, description);\n      }\n\n      /**\n       * Useful when performing a PATCH operation and you do not want to overwrite\n       * unspecified values with the default values.\n       */\n      public HttpHealthCheckCreationOptions buildForPatch() {\n         return HttpHealthCheckCreationOptions.create(host, requestPath, port,\n               checkIntervalSec, timeoutSec, unhealthyThreshold, healthyThreshold, description);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/options/ImageCreationOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.googlecomputeengine.domain.Image.RawDisk;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\nimport org.jclouds.googlecomputeengine.domain.Deprecated;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class ImageCreationOptions {\n\n   public abstract String name();\n   @Nullable public abstract String description();\n   @Nullable public abstract String sourceType();\n   @Nullable public abstract RawDisk rawDisk();\n   @Nullable public abstract Deprecated deprecated();\n   @Nullable public abstract String sourceDisk();\n\n   @SerializedNames({\"name\", \"description\", \"sourceType\", \"rawDisk\", \"deprecated\", \"sourceDisk\"})\n   static ImageCreationOptions create(String name, String description, String sourceType,\n         RawDisk rawDisk, Deprecated deprecated, String sourceDisk){\n      return new AutoValue_ImageCreationOptions(name, description, sourceType, rawDisk, deprecated, sourceDisk);\n   }\n\n   public static class Builder {\n      public String name;\n      public String description;\n      public String sourceType;\n      public RawDisk rawDisk;\n      public Deprecated deprecated;\n      public String sourceDisk;\n\n      public Builder(String name) {\n         this.name = name;\n      }\n\n      public Builder description(String description) {\n         this.description = description;\n         return this;\n      }\n\n      public Builder sourceType(String sourceType) {\n         this.sourceType = sourceType;\n         return this;\n      }\n\n      public Builder rawDisk(RawDisk rawDisk) {\n         this.rawDisk = rawDisk;\n         return this;\n      }\n\n      public Builder deprecated(Deprecated deprecated) {\n         this.deprecated = deprecated;\n         return this;\n      }\n\n      public Builder sourceDisk(String sourceDisk) {\n         this.sourceDisk = sourceDisk;\n         return this;\n      }\n\n      public ImageCreationOptions build() {\n         checkNotNull(name, \"ImageCreationOptions: name cannot be null\");\n         return create(name, description, sourceType, rawDisk, deprecated, sourceDisk);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/options/ListOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\n/**\n * Allows to optionally specify a filter, max results and a page token for <code>listPage</code> REST methods.\n */\npublic final class ListOptions extends org.jclouds.googlecloud.options.ListOptions {\n\n   /**\n    * Optional. Filter expression for filtering listed resources, in the form filter={expression}. Your {expression}\n    * must contain the following:\n    * <p/>\n    * {@code <field_name> <comparison_string> <literal_string>}\n    * <ul>\n    * <li>{@code <field_name>}:  The name of the field you want to compare. The field name must be valid for the\n    * type of resource being filtered. Only atomic field types are supported (string, number,\n    * boolean). Array and object fields are not currently supported.</li>\n    * <li>{@code <comparison_string>}: The comparison string, either eq (equals) or ne (not equals).</li>\n    * <li>{@code <literal_string>}: The literal string value to filter to. The literal value must be valid\n    * for the type of field (string, number, boolean). For string fields, the literal value is interpreted as a\n    * regular expression using RE2 syntax. The literal value must match the entire field. For example,\n    * when filtering instances, name eq my_instance won't work, but name eq .*my_instance will work.</li>\n    * </ul>\n    * <p/>\n    * For example:\n    * <p/>\n    * {@code filter=status ne RUNNING}\n    * <p/>\n    * The above filter returns only results whose status field does not equal RUNNING. You can also enclose your\n    * literal string in single, double, or no quotes. For example, all three of the following would be valid\n    * expressions:\n    * <p/>\n    * {@code filter=status ne \"RUNNING\"}<br/>\n    * {@code filter=status ne 'RUNNING'}<br/>\n    * {@code filter=status ne RUNNING}<br/>\n    * <p/>\n    * Complex regular expressions can also be used, like the following:\n    * {@code name eq '.\"my_instance_[0-9]+'}\n    */\n   public ListOptions filter(String filter) {\n      this.queryParameters.put(\"filter\", checkNotNull(filter, \"filter\"));\n      return this;\n   }\n\n   /**\n    * Sets Maximum count of results to be returned. Maximum and default value is 100. Acceptable items are 0 to\n    * 100, inclusive. (Default: 100)\n    */\n   @Override public ListOptions maxResults(Integer maxResults) {\n      return (ListOptions) super.maxResults(maxResults);\n   }\n\n   public static final class Builder {\n\n      /**\n       * @see ListOptions#filter(String)\n       */\n      public static ListOptions filter(String filter) {\n         return new ListOptions().filter(filter);\n      }\n\n      /**\n       * @see ListOptions#maxResults(Integer)\n       */\n      public static ListOptions maxResults(Integer maxResults) {\n         return new ListOptions().maxResults(maxResults);\n      }\n\n      private Builder(){\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/options/NetworkCreationOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n/**\n * Represents a network used to enable instance communication.\n */\n@AutoValue\npublic abstract class NetworkCreationOptions {\n\n   public abstract String name();\n\n   @Nullable public abstract String description();\n\n   /**\n    * The range of internal addresses that are legal on this network. This range is a CIDR\n    * specification, for example: {@code 192.168.0.0/16}.\n    */\n   @Nullable public abstract String rangeIPv4();\n\n   /**\n    * This must be within the range specified by IPv4Range, and is typically the first usable address in that range.\n    * If not specified, the default value is the first usable address in IPv4Range.\n    */\n   @Nullable public abstract String gatewayIPv4();\n   \n   @Nullable public abstract Boolean autoCreateSubnetworks();\n\n   @SerializedNames({ \"name\", \"description\", \"IPv4Range\", \"gatewayIPv4\", \"autoCreateSubnetworks\" })\n   public static NetworkCreationOptions create(String name, String description, String rangeIPv4,\n         String gatewayIPv4, Boolean autoCreateSubnetworks) {\n      return new AutoValue_NetworkCreationOptions(name, description, rangeIPv4, gatewayIPv4, autoCreateSubnetworks);\n   }\n\n   NetworkCreationOptions() {\n   }\n\n   public static class Builder {\n      private String name;\n      private String description;\n      private String rangeIPv4;\n      private String gatewayIPv4;\n      private Boolean autoCreateSubnetworks;\n      \n      public Builder(String name) {\n         this.name = name;\n      }\n      \n      public Builder rangeIPv4(String rangeIPv4) {\n         this.rangeIPv4 = rangeIPv4;\n         return this;\n      }\n\n      public Builder description(String description) {\n         this.description = description;\n         return this;\n      }\n\n      public Builder gatewayIPv4(String gatewayIPv4) {\n         this.gatewayIPv4 = gatewayIPv4;\n         return this;\n      }\n      \n      public Builder autoCreateSubnetworks(Boolean autoCreateSubnetworks) {\n         this.autoCreateSubnetworks = autoCreateSubnetworks;\n         return this;\n      }\n\n      public NetworkCreationOptions build() {\n         checkNotNull(name, \"NetworkCreationOptions name cannot be null\");\n         return create(name, description, rangeIPv4, gatewayIPv4, autoCreateSubnetworks);\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/options/RouteOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.options;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Options to insert a route.\n *\n * @see org.jclouds.googlecomputeengine.domain.Route\n */\npublic class RouteOptions {\n\n   private String name;\n   private URI network;\n   private String destRange;\n   private URI nextHopInstance;\n   private String nextHopIp;\n   private URI nextHopNetwork;\n   private URI nextHopGateway;\n   private String description;\n   private Integer priority;\n   private URI nextHopVpnTunnel;\n\n   private ImmutableList.Builder<String> tags = ImmutableList.builder();\n\n   /**\n    * @see org.jclouds.googlecomputeengine.domain.Route#name()\n    */\n   public String name() {\n      return name;\n   }\n\n   /**\n    * @see org.jclouds.googlecomputeengine.domain.Route#name()\n    */\n   public RouteOptions name(String name) {\n      this.name = name;\n      return this;\n   }\n\n   /**\n    * @see org.jclouds.googlecomputeengine.domain.Route#getDescription()\n    */\n   public String getDescription() {\n      return description;\n   }\n\n   /**\n    * @see org.jclouds.googlecomputeengine.domain.Route#getDescription()\n    */\n   public RouteOptions description(String description) {\n      this.description = description;\n      return this;\n   }\n\n   /**\n    * @see org.jclouds.googlecomputeengine.domain.Route#getDestRange()\n    */\n   public String getDestRange() {\n      return destRange;\n   }\n\n   /**\n    * @see org.jclouds.googlecomputeengine.domain.Route#getDestRange()\n    */\n   public RouteOptions destRange(String destRange) {\n      this.destRange = destRange;\n      return this;\n   }\n\n   /**\n    * @see org.jclouds.googlecomputeengine.domain.Route#getNextHopIp()\n    */\n   public String getNextHopIp() {\n      return nextHopIp;\n   }\n\n   /**\n    * @see org.jclouds.googlecomputeengine.domain.Route#getNextHopIp()\n    */\n   public RouteOptions nextHopIp(String nextHopIp) {\n      this.nextHopIp = nextHopIp;\n      return this;\n   }\n\n   /**\n    * @see org.jclouds.googlecomputeengine.domain.Route#getPriority()\n    */\n   public Integer getPriority() {\n      return priority;\n   }\n\n   /**\n    * @see org.jclouds.googlecomputeengine.domain.Route#getPriority()\n    */\n   public RouteOptions priority(Integer priority) {\n      this.priority = priority;\n      return this;\n   }\n\n   /**\n    * @see org.jclouds.googlecomputeengine.domain.Route#getNextHopVpnTunnel()\n    */\n   public RouteOptions nextHopVpnTunnel(URI nextHopVpnTunnel){\n      this.nextHopVpnTunnel = nextHopVpnTunnel;\n      return this;\n   }\n\n   /**\n    * @see org.jclouds.googlecomputeengine.domain.Route#getNetwork()\n    */\n   public RouteOptions network(URI network) {\n      this.network = network;\n      return this;\n   }\n\n   /**\n    * @see org.jclouds.googlecomputeengine.domain.Route#getNetwork()\n    */\n   public URI getNetwork() {\n      return network;\n   }\n\n   /**\n    * @see org.jclouds.googlecomputeengine.domain.Route#getNextHopInstance()\n    */\n   public RouteOptions nextHopInstance(URI nextHopInstance) {\n      this.nextHopInstance = nextHopInstance;\n      return this;\n   }\n\n   /**\n    * @see org.jclouds.googlecomputeengine.domain.Route#getNextHopInstance()\n    */\n   public URI getNextHopInstance() {\n      return nextHopInstance;\n   }\n\n   /**\n    * @see org.jclouds.googlecomputeengine.domain.Route#getNextHopNetwork()\n    */\n   public RouteOptions nextHopNetwork(URI nextHopNetwork) {\n      this.nextHopNetwork = nextHopNetwork;\n      return this;\n   }\n\n   /**\n    * @see org.jclouds.googlecomputeengine.domain.Route#getNextHopNetwork()\n    */\n   public URI getNextHopNetwork() {\n      return nextHopNetwork;\n   }\n\n   /**\n    * @see org.jclouds.googlecomputeengine.domain.Route#getNextHopGateway()\n    */\n   public RouteOptions nextHopGateway(URI nextHopGateway) {\n      this.nextHopGateway = nextHopGateway;\n      return this;\n   }\n\n   /**\n    * @see org.jclouds.googlecomputeengine.domain.Route#getNextHopGateway()\n    */\n   public URI getNextHopGateway() {\n      return nextHopGateway;\n   }\n\n   /**\n    * @see org.jclouds.googlecomputeengine.domain.Route#getNextHopVpnTunnel()\n    */\n   public URI getNextHopVpnTunnel() {\n      return nextHopVpnTunnel;\n   }\n\n   /**\n    * @see org.jclouds.googlecomputeengine.domain.Route#getTags()\n    */\n   public List<String> getTags() {\n      return tags.build();\n   }\n\n   /**\n    * @see org.jclouds.googlecomputeengine.domain.Route#getTags()\n    */\n   public RouteOptions addTag(String tag) {\n      this.tags.add(tag);\n      return this;\n   }\n\n   /**\n    * @see org.jclouds.googlecomputeengine.domain.Route#getTags()\n    */\n   public RouteOptions tags(List<String> tags) {\n      this.tags = ImmutableList.builder();\n      this.tags.addAll(tags);\n      return this;\n   }\n\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/options/SubnetworkCreationOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.options;\n\nimport java.net.URI;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n/**\n * Represents a subnetwork used to enable instance communication.\n */\n@AutoValue\npublic abstract class SubnetworkCreationOptions {\n\n   public abstract String name();\n\n   @Nullable\n   public abstract String description();\n\n   public abstract URI network();\n\n   public abstract String ipCidrRange();\n\n   public abstract URI region();\n\n   public abstract boolean privateIpGoogleAccess();\n\n   @SerializedNames({ \"name\", \"description\", \"network\", \"ipCidrRange\", \"region\", \"privateIpGoogleAccess\" })\n   public static SubnetworkCreationOptions create(String name, String description, URI network, String ipCidrRange,\n         URI region, boolean privateIpGoogleAccess) {\n      return new AutoValue_SubnetworkCreationOptions(name, description, network, ipCidrRange, region,\n            privateIpGoogleAccess);\n   }\n\n   SubnetworkCreationOptions() {\n      \n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/options/TargetHttpProxyOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.net.URI;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class TargetHttpProxyOptions {\n\n   public abstract String name();\n   @Nullable public abstract String description();\n   public abstract URI urlMap();\n\n   @SerializedNames({ \"name\", \"description\", \"urlMap\"})\n   static TargetHttpProxyOptions create(String name, String description, URI urlMap) {\n      return new AutoValue_TargetHttpProxyOptions(name, description, urlMap);\n   }\n\n   TargetHttpProxyOptions() {\n   }\n\n   public static class Builder {\n      private String name;\n      private String description;\n      private URI urlMap;\n\n      public Builder(String name, URI urlMap) {\n         this.name = name;\n         this.urlMap = urlMap;\n      }\n\n      /**\n       * @see TargetHttpProxyOptions#getDescription()\n       */\n      public Builder description(String description) {\n         this.description = description;\n         return this;\n      }\n\n      public TargetHttpProxyOptions build() {\n         checkNotNull(name, \"TargetHttpProxyOptions name cannot be null\");\n         checkNotNull(urlMap, \"TargetHttpProxyOptions name cannot be null\");\n         return create(name, description, urlMap);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/options/TargetPoolCreationOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n/**\n * Options for creating a Target Pool\n */\n@AutoValue\npublic abstract class TargetPoolCreationOptions{\n\n   /**\n    * Session affinity determines the hash method that\n    * Google Compute Engine uses to distribute traffic.\n    * @see <a href=\"https://cloud.google.com/compute/docs/reference/latest/targetPools#resource\"/>\n    */\n   public enum SessionAffinityValue {\n      CLIENT_IP,\n      CLIENT_IP_PROTO,\n      NONE\n   }\n\n   public abstract String name();\n   @Nullable public abstract List<URI> healthChecks();\n   @Nullable public abstract List<URI> instances();\n   @Nullable public abstract SessionAffinityValue sessionAffinity();\n   @Nullable public abstract Float failoverRatio();\n   @Nullable public abstract URI backupPool();\n   @Nullable public abstract String description();\n\n   @SerializedNames({ \"name\", \"healthChecks\", \"instances\", \"sessionAffinity\", \"failoverRatio\",\n                     \"backupPool\", \"description\"})\n   public static TargetPoolCreationOptions create(String name, List<URI> healthChecks, List<URI> instances,\n         SessionAffinityValue sessionAffinity, Float failoverRatio, URI backupPool, String description) {\n      return new AutoValue_TargetPoolCreationOptions(name, healthChecks, instances, sessionAffinity, failoverRatio,\n            backupPool, description);\n   }\n\n   TargetPoolCreationOptions() {\n   }\n\n   public static class Builder {\n\n      private String name;\n      private List<URI> healthChecks;\n      private List<URI> instances;\n      private SessionAffinityValue sessionAffinity;\n      private Float failoverRatio;\n      private URI backupPool;\n      private String description;\n\n      public Builder(String name){\n         checkNotNull(name, \"TargetPoolCreationOptions name cannot be null\");\n         this.name = name;\n      }\n\n      /** The set of HealthChecks */\n      public Builder healthChecks(List<URI> healthChecks){\n         this.healthChecks = healthChecks;\n         return this;\n      }\n\n      /**\n       * A List of resource URIs to the member VMs serving this pool.\n       * They must live in zones contained in the same region as this pool.\n       */\n      public Builder instances(List<URI> instances){\n         this.instances = instances;\n         return this;\n      }\n\n      /**\n       * Defines the session affinity option.\n       * Session affinity determines the hash method that Google Compute Engine uses to distribute traffic.\n       */\n      public Builder sessionAffinity(SessionAffinityValue sessionAffinity){\n         this.sessionAffinity = sessionAffinity;\n         return this;\n      }\n\n      /**\n       * This field is applicable only when the target pool is serving a forwarding rule as the primary pool\n       * (e.g. not as a backup pool to some other target pool).\n       * The value of the a float between [0, 1].\n       * If set, backupPool must also be set.\n       * @return failoverRatio, a float between [0, 1]\n       */\n      public Builder failoverRatio(float failoverRatio){\n         this.failoverRatio = failoverRatio;\n         return this;\n      }\n\n      /**\n       * This field is applicable only when the target pool is serving a forwarding rule as the primary pool\n       * (e.g. not as a backup pool to some other target pool). Must be a fully-qualified URL to a target pool\n       * that is in the same region as the primary target pool.\n       * If set, failoverRatio must also be set\n       * @return backupPool, Fully-qualified URI to a target pool in the same region as primary target pool\n       */\n      public Builder backupPool(URI backupPool){\n         this.backupPool = backupPool;\n         return this;\n      }\n\n      /**\n       * An optional textual description of the TargetPool.\n       * @return description, provided by the client.\n       */\n      public Builder description(String description){\n         this.description = description;\n         return this;\n      }\n\n      public TargetPoolCreationOptions build() {\n         return create(name, healthChecks, instances, sessionAffinity, failoverRatio,\n               backupPool, description);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/main/java/org/jclouds/googlecomputeengine/options/UrlMapOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.options;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport org.jclouds.googlecomputeengine.domain.UrlMap.HostRule;\nimport org.jclouds.googlecomputeengine.domain.UrlMap.PathMatcher;\nimport org.jclouds.googlecomputeengine.domain.UrlMap.UrlMapTest;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class UrlMapOptions {\n\n   @Nullable public abstract String name();\n   @Nullable public abstract String description();\n   @Nullable public abstract List<HostRule> hostRules();\n   @Nullable public abstract List<PathMatcher> pathMatchers();\n   @Nullable public abstract List<UrlMapTest> tests();\n   @Nullable public abstract URI defaultService();\n   @Nullable public abstract String fingerprint();\n\n   @SerializedNames({ \"name\", \"description\", \"hostRules\", \"pathMatchers\", \"tests\",\n                     \"defaultService\", \"fingerprint\"})\n   static UrlMapOptions create(String name, String description, List<HostRule> hostRules,\n         List<PathMatcher> pathMatchers, List<UrlMapTest> tests, URI defaultService, String fingerprint) {\n      return new AutoValue_UrlMapOptions(name, description, hostRules,\n             pathMatchers, tests, defaultService, fingerprint);\n   }\n\n   UrlMapOptions(){\n   }\n\n   public static class Builder {\n\n      private String name;\n      private String description;\n      private List<HostRule> hostRules;\n      private List<PathMatcher> pathMatchers;\n      private List<UrlMapTest> tests;\n      private URI defaultService;\n      private String fingerprint;\n\n      /**\n       * Name of the UrlMap resource.\n       */\n      public Builder name(String name) {\n         this.name = name;\n         return this;\n      }\n\n      /**\n       * An optional textual description of the UrlMap.\n       */\n      public Builder description(String description) {\n         this.description = description;\n         return this;\n      }\n\n      /**\n       * Rules for matching and directing incoming hosts.\n       */\n      public Builder hostRules(List<HostRule> hostRules) {\n         this.hostRules = hostRules;\n         return this;\n      }\n\n      /**\n       * The list of named PathMatchers to use against the URL.\n       */\n      public Builder pathMatchers(List<PathMatcher> pathMatchers) {\n         this.pathMatchers = pathMatchers;\n         return this;\n      }\n\n      /**\n       * The list of expected URL mappings. Request to update this\n       * UrlMap will succeed only all of the test cases pass.\n       */\n      public Builder tests(List<UrlMapTest> tests) {\n         this.tests = tests;\n         return this;\n      }\n\n      /**\n       * The URL of the BackendService resource if none of the hostRules match.\n       */\n      public Builder defaultService(URI defaultService) {\n         this.defaultService = defaultService;\n         return this;\n      }\n\n      /**\n       * Fingerprint of this resource. A hash of the contents stored in this object.\n       * This field is used in optimistic locking. This field will be ignored when\n       * inserting a UrlMap. An up-to-date fingerprint must be provided in order to\n       * update the UrlMap.\n       */\n      public Builder fingerprint(String fingerprint) {\n         this.fingerprint = fingerprint;\n         return this;\n      }\n\n      /**\n       * Builds the UrlMapOptions.\n       * Note: This enforces that \"name\" and \"defaultService\" are not null as the GCE API expects.\n       * If you are patching an existing UrlMap you may wish to use {@link #buildForPatch()} instead.\n       */\n      public UrlMapOptions build() {\n         checkNotNull(name, \"In UrlMapOptions: A UrlMap name cannot be null, if patching an existing UrlMap use buildForPatch() instead of build()\");\n         checkNotNull(defaultService, \"In UrlMapOptions: A UrlMap defaultService cannot be null, if patching an existing UrlMap use buildForPatch() instead of build()\");\n         return create(name, description, hostRules, pathMatchers, tests,\n               defaultService, fingerprint);\n      }\n\n      /**\n       * This build option is specifically for when patching an existing UrlMap.\n       * If not patching an existing urlMap it is recommended that you use {@link #build()}.\n       */\n      public UrlMapOptions buildForPatch() {\n         return create(name, description, hostRules, pathMatchers, tests,\n               defaultService, fingerprint);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/GoogleComputeEngineProviderMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine;\n\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests that GoogleComputeProviderMetadata is properly registered in ServiceLoader\n * <p/>\n * <pre>\n * META-INF/services/org.jclouds.providers.ProviderMetadata\n * </pre>\n */\n@Test(groups = \"unit\", testName = \"GoogleComputeEngineProviderMetadataTest\")\npublic class GoogleComputeEngineProviderMetadataTest extends BaseProviderMetadataTest {\n   public GoogleComputeEngineProviderMetadataTest() {\n      super(new GoogleComputeEngineProviderMetadata(), new GoogleComputeEngineApiMetadata());\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/binders/DiskCreationBinderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\nimport java.util.Map;\n\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineExpectTest;\nimport org.jclouds.googlecomputeengine.options.DiskCreationOptions;\nimport org.jclouds.http.HttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\n\n@Test(groups = \"unit\", testName = \"DiskCreationBinderTest\")\npublic class DiskCreationBinderTest extends BaseGoogleComputeEngineExpectTest<Object>{\n\n   private static final String FAKE_SOURCE_SNAPSHOT = \"https://www.googleapis.com/compute/v1/projects/\" +\n                                       \"debian-cloud/global/images/backports-debian-7-wheezy-v20141017\";\n\n   DiskCreationBinder binder = new DiskCreationBinder();\n\n   @Test\n   public void testMap() throws SecurityException, NoSuchMethodException {\n      DiskCreationOptions diskCreationOptions = new DiskCreationOptions.Builder()\n         .sourceSnapshot(URI.create(FAKE_SOURCE_SNAPSHOT)).sizeGb(15).description(null).build();\n\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").build();\n      Map<String, Object> postParams = ImmutableMap.of(\"name\", \"testName\", \"options\", diskCreationOptions);\n\n      request = binder.bindToRequest(request, postParams);\n\n      assertEquals(request.getPayload().getRawContent(),\n            \"{\\\"name\\\":\\\"testName\\\",\\\"sizeGb\\\":15,\\\"sourceSnapshot\\\":\\\"\" + FAKE_SOURCE_SNAPSHOT + \"\\\"}\");\n      assertEquals(request.getPayload().getContentMetadata().getContentType(), \"application/json\");\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/binders/ForwardingRuleCreationBinderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\nimport java.util.Map;\n\nimport org.jclouds.googlecomputeengine.domain.ForwardingRule;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineExpectTest;\nimport org.jclouds.googlecomputeengine.options.ForwardingRuleCreationOptions;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.json.Json;\nimport org.jclouds.json.internal.GsonWrapper;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.gson.Gson;\n\n@Test(groups = \"unit\", testName = \"ForwardingRuleCreationBinderTest\")\npublic class ForwardingRuleCreationBinderTest extends BaseGoogleComputeEngineExpectTest<Object>{\n\n   private static final String DESCRIPTION = \"This is a test!\";\n   private static final String IP_ADDRESS = \"1.2.1.1.1\";\n   private static final String PORT_RANGE = \"1.2.3.4.1\";\n   private static final URI TARGET = URI.create(BASE_URL + \"/party/regions/europe-west1/targetPools/test-target-pool\");\n\n   Json json = new GsonWrapper(new Gson());\n\n   @Test\n   public void testMap() throws SecurityException, NoSuchMethodException {\n      ForwardingRuleCreationBinder binder = new ForwardingRuleCreationBinder(json);\n      ForwardingRuleCreationOptions forwardingRuleCreationOptions = new ForwardingRuleCreationOptions.Builder()\n                                                                  .description(DESCRIPTION)\n                                                                  .ipAddress(IP_ADDRESS)\n                                                                  .ipProtocol(ForwardingRule.IPProtocol.SCTP)\n                                                                  .portRange(PORT_RANGE)\n                                                                  .target(TARGET)\n                                                                  .build();\n\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").build();\n      Map<String, Object> postParams = ImmutableMap.of(\"name\", \"testForwardingRuleName\", \"options\", forwardingRuleCreationOptions);\n\n      binder.bindToRequest(request, postParams);\n\n      assertEquals(request.getPayload().getRawContent(),\n            \"{\\\"\"\n            + \"name\\\":\\\"testForwardingRuleName\\\",\"\n            + \"\\\"description\\\":\\\"\" + DESCRIPTION + \"\\\",\"\n            + \"\\\"ipAddress\\\":\\\"\" + IP_ADDRESS + \"\\\",\"\n            + \"\\\"ipProtocol\\\":\\\"SCTP\\\",\"\n            + \"\\\"portRange\\\":\\\"\" + PORT_RANGE + \"\\\",\"\n            + \"\\\"target\\\":\\\"\" + TARGET + \"\\\"\"\n            + \"}\");\n      assertEquals(request.getPayload().getContentMetadata().getContentType(), \"application/json\");\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/binders/HttpHealthCheckCreationBinderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Map;\n\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineExpectTest;\nimport org.jclouds.googlecomputeengine.options.HttpHealthCheckCreationOptions;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.json.Json;\nimport org.jclouds.json.internal.GsonWrapper;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.gson.Gson;\n\n@Test(groups = \"unit\", testName = \"HttpHealthCheckCreationBinderTest\")\npublic class HttpHealthCheckCreationBinderTest extends BaseGoogleComputeEngineExpectTest<Object>{\n\n   private static final String NAME = \"testHttpHealthCheck\";\n   private static final int TIMEOUTSEC = 3;\n   private static final int UNHEALTHYTHRESHOLD = 5;\n   private static final int HEALTHYTHRESHOLD = 4;\n   private static final String DESCRIPTION = \"This is a test!\";\n\n   Json json = new GsonWrapper(new Gson());\n\n   @Test\n   public void testMap() throws SecurityException, NoSuchMethodException {\n      HttpHealthCheckCreationBinder binder = new HttpHealthCheckCreationBinder(json);\n      HttpHealthCheckCreationOptions httpHealthCheckCreationOptions = new HttpHealthCheckCreationOptions.Builder()\n                                                                              .timeoutSec(TIMEOUTSEC)\n                                                                              .unhealthyThreshold(UNHEALTHYTHRESHOLD)\n                                                                              .healthyThreshold(HEALTHYTHRESHOLD)\n                                                                              .description(DESCRIPTION)\n                                                                              .buildWithDefaults();\n\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").build();\n      Map<String, Object> postParams = ImmutableMap.of(\"name\", NAME, \"options\", httpHealthCheckCreationOptions);\n\n      binder.bindToRequest(request, postParams);\n\n      assertEquals(request.getPayload().getRawContent(),\n            \"{\"\n            + \"\\\"name\\\":\\\"\" + NAME + \"\\\",\"\n            + \"\\\"requestPath\\\":\\\"/\\\",\"\n            + \"\\\"port\\\":80,\"\n            + \"\\\"checkIntervalSec\\\":5,\"\n            + \"\\\"timeoutSec\\\":\" + TIMEOUTSEC + \",\"\n            + \"\\\"unhealthyThreshold\\\":\" + UNHEALTHYTHRESHOLD + \",\"\n            + \"\\\"healthyThreshold\\\":\" + HEALTHYTHRESHOLD + \",\"\n            + \"\\\"description\\\":\\\"\" + DESCRIPTION + \"\\\"\"\n            + \"}\");\n      assertEquals(request.getPayload().getContentMetadata().getContentType(), \"application/json\");\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/binders/TargetPoolAddInstanceBinderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineExpectTest;\nimport org.jclouds.http.HttpRequest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\n\n@Test(groups = \"unit\", testName = \"TargetPoolAddInstanceBinderTest\")\npublic class TargetPoolAddInstanceBinderTest extends BaseGoogleComputeEngineExpectTest<Object>{\n\n   private static final List<URI> FAKE_INSTANCES = ImmutableList.of(\n                                       URI.create(\"https://www.googleapis.com/compute/v1/\" +\n                                                  \"projects/project/zones/us-central1-a/instances/instance-1\"),\n                                       URI.create(\"https://www.googleapis.com/compute/v1/\" +\n                                                  \"projects/project/zones/us-central1-a/instances/instance-2\"));\n\n   TargetPoolChangeInstancesBinder binder = new TargetPoolChangeInstancesBinder();\n \n   @Test\n   public void testMap() throws SecurityException, NoSuchMethodException {\n      HttpRequest request = HttpRequest.builder().method(\"GET\").endpoint(\"http://momma\").build();\n      Map<String, Object> postParams = ImmutableMap.of(\"instances\", (Object) FAKE_INSTANCES);\n\n      binder.bindToRequest(request, postParams);\n\n      assertEquals(request.getPayload().getRawContent(),\n               \"{\"\n            + \"\\\"instances\\\":[\"\n            + \"{\\\"instance\\\":\\\"https://www.googleapis.com/compute/v1/projects/project/zones/us-central1-a/instances/instance-1\\\"},\"\n            + \"{\\\"instance\\\":\\\"https://www.googleapis.com/compute/v1/projects/project/zones/us-central1-a/instances/instance-2\\\"}\"\n            + \"]\"\n            + \"}\");\n      assertEquals(request.getPayload().getContentMetadata().getContentType(), \"application/json\");\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/compute/GoogleComputeEngineServiceLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.compute;\n\nimport static com.google.common.collect.Iterables.contains;\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.jclouds.compute.predicates.NodePredicates.inGroup;\nimport static org.jclouds.util.Strings2.toStringAndClose;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.internal.BaseComputeServiceLiveTest;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.googlecloud.internal.TestProperties;\nimport org.jclouds.googlecomputeengine.GoogleComputeEngineApi;\nimport org.jclouds.googlecomputeengine.compute.options.GoogleComputeEngineTemplateOptions;\nimport org.jclouds.googlecomputeengine.domain.Disk;\nimport org.jclouds.googlecomputeengine.domain.Instance;\nimport org.jclouds.googlecomputeengine.domain.MachineType;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.sshj.config.SshjSshClientModule;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.inject.Module;\n\n@Test(groups = \"live\", singleThreaded = true)\npublic class GoogleComputeEngineServiceLiveTest extends BaseComputeServiceLiveTest {\n\n   protected static final String DEFAULT_ZONE_NAME = \"us-central1-a\";\n\n   public GoogleComputeEngineServiceLiveTest() {\n      provider = \"google-compute-engine\";\n   }\n\n   @Override protected Properties setupProperties() {\n      TestProperties.setGoogleCredentialsFromJson(provider);\n      return TestProperties.apply(provider, super.setupProperties());\n   }\n\n   public void testListHardwareProfiles() throws Exception {\n      GoogleComputeEngineApi api = client.getContext().unwrapApi(GoogleComputeEngineApi.class);\n      ImmutableSet.Builder<String> deprecatedMachineTypes = ImmutableSet.builder();\n      for (MachineType machine : api.machineTypesInZone(DEFAULT_ZONE_NAME).list().next()) {\n         if (machine.deprecated() != null) {\n            deprecatedMachineTypes.add(machine.id());\n         }\n      }\n      ImmutableSet<String> deprecatedMachineTypeIds = deprecatedMachineTypes.build();\n      for (Hardware hardwareProfile : client.listHardwareProfiles()) {\n         assertFalse(contains(deprecatedMachineTypeIds, hardwareProfile.getId()));\n      }\n   }\n\n   public void testCreatePreemptibleNodeWithSsd() throws Exception {\n      String group = this.group + \"ssd\";\n      try {\n         TemplateOptions options = client.templateOptions();\n\n         options.as(GoogleComputeEngineTemplateOptions.class).bootDiskType(\"pd-ssd\").preemptible(true);\n\n         // create a node\n         Set<? extends NodeMetadata> nodes =\n               client.createNodesInGroup(group, 1, options);\n         assertEquals(nodes.size(), 1, \"One node should have been created\");\n\n         // Verify the disk on the instance is an ssd.\n         NodeMetadata node = Iterables.get(nodes, 0);\n         GoogleComputeEngineApi api = client.getContext().unwrapApi(GoogleComputeEngineApi.class);\n         Instance instance = api.instancesInZone(node.getLocation().getId()).get(node.getName());\n         Disk disk = api.disksInZone(node.getLocation().getId()).get(toName(instance.disks().get(0).source()));\n         assertTrue(disk.type().toString().endsWith(\"pd-ssd\"));\n         assertTrue(instance.scheduling().preemptible());\n\n      } finally {\n         client.destroyNodesMatching(inGroup(group));\n      }\n   }\n   /**\n    * Nodes may have additional metadata entries (particularly they may have an \"sshKeys\" entry)\n    */\n   protected void checkUserMetadataInNodeEquals(NodeMetadata node, ImmutableMap<String, String> userMetadata) {\n      assertTrue(node.getUserMetadata().keySet().containsAll(userMetadata.keySet()));\n   }\n\n   @Test(expectedExceptions = AuthorizationException.class)\n   @Override\n   public void testCorrectAuthException() throws Exception {\n      ComputeServiceContext context = null;\n      try {\n         String credential = toStringAndClose(getClass().getResourceAsStream(\"/test\"));\n         Properties overrides = setupProperties();\n         overrides.setProperty(provider + \".identity\", \"000000000000@developer.gserviceaccount.com\");\n         overrides.setProperty(provider + \".credential\", credential);\n         context = newBuilder()\n               .modules(ImmutableSet.of(getLoggingModule(), credentialStoreModule))\n               .overrides(overrides).build(ComputeServiceContext.class);\n         context.getComputeService().listNodes();\n      } catch (AuthorizationException e) {\n         throw e;\n      } catch (RuntimeException e) {\n         e.printStackTrace();\n         throw e;\n      } finally {\n         if (context != null)\n            context.close();\n      }\n   }\n\n   @Override\n   protected Module getSshModule() {\n      return new SshjSshClientModule();\n   }\n\n   @Override\n   protected void checkTagsInNodeEquals(NodeMetadata node, ImmutableSet<String> tags) {\n      Set<String> nodeTags = node.getTags();\n      for (String tag : tags){\n         assert nodeTags.contains(tag) : String.format(\"node tags did not match %s %s node %s:\", tags, nodeTags, node);\n      }\n   }\n\n   private static String toName(URI link) {\n      String path = link.getPath();\n      return path.substring(path.lastIndexOf('/') + 1);\n   }\n\n   @Override\n   protected void checkVolumes(Hardware hardware) {\n      // Hardware profiles might not have volumes.\n   }\n\n   @Override\n   @Test(dataProvider = \"onlyIfAutomaticHardwareSupported\", groups = {\"integration\", \"live\"})\n   public void testCreateNodeWithCustomHardware() throws Exception {\n      Template template = buildTemplate(templateBuilder()\n            .hardwareId(\"automatic:cores=2;ram=4096\"));\n      try {\n         NodeMetadata node = getOnlyElement(client.createNodesInGroup(group + \"custom\", 1, template));\n         assertThat(node.getHardware().getRam()).isEqualTo(4096);\n         assertThat(node.getHardware().getProcessors().get(0).getCores()).isEqualTo(2);\n         assertThat(node.getHardware().getId()).isEqualTo(node.getLocation().getDescription() + \"/machineTypes/custom-2-4096\");\n      }\n      finally {\n         client.destroyNodesMatching(inGroup(group + \"custom\"));\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/compute/GoogleComputeEngineServiceMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.compute;\n\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static org.jclouds.googlecomputeengine.domain.Instance.Status.RUNNING;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.util.Set;\n\nimport okhttp3.mockwebserver.MockResponse;\n\nimport org.jclouds.compute.ComputeService;\nimport org.jclouds.compute.domain.ComputeMetadata;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.googlecomputeengine.compute.options.GoogleComputeEngineTemplateOptions;\nimport org.jclouds.googlecomputeengine.domain.Instance;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiMockTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n\n@Test(groups = \"unit\", testName = \"GoogleComputeEngineServiceMockTest\", singleThreaded = true)\npublic class GoogleComputeEngineServiceMockTest extends BaseGoogleComputeEngineApiMockTest {\n\n   public void templateMatch() throws Exception {\n      server.enqueue(singleRegionSingleZoneResponse());\n      server.enqueue(jsonResponse(\"/image_list.json\"));\n      server.enqueue(jsonResponse(\"/image_list_debian.json\")); // per IMAGE_PROJECTS = \"debian-cloud\"\n      server.enqueue(singleRegionSingleZoneResponse());\n      server.enqueue(jsonResponse(\"/aggregated_machinetype_list.json\"));\n\n      ComputeService computeService = computeService();\n\n      Template template = computeService.templateBuilder().build();\n      Hardware defaultSize = computeService.templateBuilder().build().getHardware();\n\n      Hardware smallest = computeService.templateBuilder().smallest().build().getHardware();\n      assertEquals(defaultSize, smallest);\n\n      Hardware fastest = computeService.templateBuilder().fastest().build().getHardware();\n      assertNotNull(fastest);\n\n      assertEquals(computeService.listHardwareProfiles().size(), 2);\n\n      Template toMatch = computeService.templateBuilder().imageId(template.getImage().getId()).build();\n      assertEquals(toMatch.getImage(), template.getImage());\n\n      assertSent(server, \"GET\", \"/projects/party/regions\");\n      assertSent(server, \"GET\", \"/projects/party/global/images\");\n      assertSent(server, \"GET\", \"/projects/debian-cloud/global/images\");\n      assertSent(server, \"GET\", \"/projects/party/regions\");\n      assertSent(server, \"GET\", \"/projects/party/aggregated/machineTypes\");\n   }\n\n   public void firewallDeletedWhenAllGroupNodesAreTerminated() throws IOException, InterruptedException {\n      server.enqueue(instanceWithNetworkAndStatus(\"test-delete-1\", \"default\", RUNNING));\n      server.enqueue(singleRegionSingleZoneResponse());\n      server.enqueue(jsonResponse(\"/disk_get_with_source_image.json\"));\n      server.enqueue(jsonResponse(\"/image_get_for_source_image.json\"));\n      server.enqueue(singleRegionSingleZoneResponse());\n      server.enqueue(jsonResponse(\"/aggregated_machinetype_list.json\")); // Why are we getting machineTypes to delete an instance?\n      server.enqueue(jsonResponse(\"/operation.json\")); // instance delete\n      server.enqueue(jsonResponse(\"/zone_operation.json\"));\n      server.enqueue(response404()); // deleted instance no longer exists\n      server.enqueue(aggregatedListInstanceEmpty());\n      server.enqueue(jsonResponse(\"/firewall_list_compute.json\"));\n      server.enqueue(jsonResponse(\"/operation.json\"));\n      server.enqueue(jsonResponse(\"/zone_operation.json\"));\n\n      ComputeService computeService = computeService();\n      computeService.destroyNode(url(\"/jclouds/zones/us-central1-a/instances/test-delete-1\"));\n\n      assertSent(server, \"GET\", \"/jclouds/zones/us-central1-a/instances/test-delete-1\");\n      assertSent(server, \"GET\", \"/projects/party/regions\");\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/disks/test\");\n      assertSent(server, \"GET\", \"/projects/debian-cloud/global/images/debian-7-wheezy-v20140718\");\n      assertSent(server, \"GET\", \"/projects/party/regions\");\n      assertSent(server, \"GET\", \"/projects/party/aggregated/machineTypes\"); // Why are we getting machineTypes to delete an instance?\n      assertSent(server, \"DELETE\", \"/jclouds/zones/us-central1-a/instances/test-delete-1\"); // instance delete\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/operations/operation-1354084865060\");\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/instances/test-delete-1\"); // get instance\n      assertSent(server, \"GET\", \"/projects/party/aggregated/instances\");\n      assertSent(server, \"GET\", \"/projects/party/global/firewalls\");\n      assertSent(server, \"DELETE\", \"/projects/party/global/firewalls/jclouds-test-delete-34sf\");\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/operations/operation-1354084865060\");\n   }\n\n\n   public void listAssignableLocations() throws Exception {\n      server.enqueue(singleRegionSingleZoneResponse());\n\n      ComputeService computeService = computeService();\n\n      Set<? extends Location> locations = computeService.listAssignableLocations();\n\n      assertNotNull(locations);\n      assertEquals(locations.size(), 1);\n      Location firstZone = locations.iterator().next();\n      assertEquals(firstZone.getId(), \"us-central1-a\");\n      assertEquals(firstZone.getDescription(), url(\"/projects/party/zones/us-central1-a\"));\n      assertEquals(firstZone.getScope(), LocationScope.ZONE);\n\n      assertEquals(firstZone.getParent().getId(), \"us-central1\");\n      assertEquals(firstZone.getParent().getDescription(), url(\"/projects/party/regions/us-central1\"));\n      assertEquals(firstZone.getParent().getScope(), LocationScope.REGION);\n\n     // Google intentionally does not document locations!\n      assertTrue(firstZone.getIso3166Codes().isEmpty());\n      assertTrue(firstZone.getParent().getIso3166Codes().isEmpty());\n\n      assertSent(server, \"GET\", \"/projects/party/regions\");\n   }\n\n   public void listNodes() throws Exception {\n      server.enqueue(aggregatedListWithInstanceNetworkAndStatus(\"test-0\", \"test-network\", RUNNING));\n      server.enqueue(singleRegionSingleZoneResponse());\n      server.enqueue(jsonResponse(\"/disk_get_with_source_image.json\"));\n      server.enqueue(jsonResponse(\"/image_get_for_source_image.json\"));\n      server.enqueue(singleRegionSingleZoneResponse());\n      server.enqueue(jsonResponse(\"/aggregated_machinetype_list.json\"));\n\n      Set<? extends ComputeMetadata> nodes = computeService().listNodes();\n      assertEquals(nodes.size(), 1);\n      NodeMetadata node = (NodeMetadata) nodes.iterator().next();\n      assertNotNull(node.getImageId());\n\n      assertSent(server, \"GET\", \"/projects/party/aggregated/instances\");\n      assertSent(server, \"GET\", \"/projects/party/regions\");\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/disks/test\");\n      assertSent(server, \"GET\", \"/projects/debian-cloud/global/images/debian-7-wheezy-v20140718\");\n      assertSent(server, \"GET\", \"/projects/party/regions\");\n      assertSent(server, \"GET\", \"/projects/party/aggregated/machineTypes\");\n   }\n\n\n   public void listNodesWithSnapshotSource() throws Exception {\n      server.enqueue(aggregatedListWithInstanceNetworkAndStatus(\"test-0\", \"test-network\", RUNNING));\n      server.enqueue(singleRegionSingleZoneResponse());\n      server.enqueue(jsonResponse(\"/disk_get_with_source_snapshot.json\"));\n      server.enqueue(singleRegionSingleZoneResponse());\n      server.enqueue(jsonResponse(\"/aggregated_machinetype_list.json\"));\n\n      Set<? extends ComputeMetadata> nodes = computeService().listNodes();\n      assertEquals(nodes.size(), 1);\n      NodeMetadata node = (NodeMetadata) nodes.iterator().next();\n      String imageId = node.getImageId();\n      assertEquals(imageId, null);\n      assertSent(server, \"GET\", \"/projects/party/aggregated/instances\");\n      assertSent(server, \"GET\", \"/projects/party/regions\");\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/disks/test\");\n      assertSent(server, \"GET\", \"/projects/party/regions\");\n      assertSent(server, \"GET\", \"/projects/party/aggregated/machineTypes\");\n   }\n\n\n\n   public void createNodeWhenFirewallDoesNotExist() throws Exception {\n      server.enqueue(singleRegionSingleZoneResponse());\n      server.enqueue(jsonResponse(\"/image_list.json\"));\n      server.enqueue(jsonResponse(\"/image_list_debian.json\")); // per IMAGE_PROJECTS = \"debian-cloud\"\n      server.enqueue(singleRegionSingleZoneResponse());\n      server.enqueue(jsonResponse(\"/aggregated_machinetype_list.json\"));\n      server.enqueue(new MockResponse().setResponseCode(404)); // Get Subnet\n      server.enqueue(jsonResponse(\"/network_get_default.json\"));\n      server.enqueue(new MockResponse().setResponseCode(404)); // Get Firewall\n      server.enqueue(jsonResponse(\"/operation.json\")); // Create Firewall\n      server.enqueue(jsonResponse(\"/zone_operation.json\"));\n      server.enqueue(aggregatedListWithInstanceNetworkAndStatus(\"test-0\", \"test-network\", RUNNING));\n      server.enqueue(jsonResponse(\"/disk_get_with_source_image.json\"));\n      server.enqueue(jsonResponse(\"/image_get_for_source_image.json\"));\n      server.enqueue(jsonResponse(\"/operation.json\")); // Create Instance\n      server.enqueue(instanceWithNetworkAndStatus(\"test-1\", \"test-network\", RUNNING));\n\n      ComputeService computeService = computeService();\n\n      GoogleComputeEngineTemplateOptions options = computeService.templateOptions()\n            .as(GoogleComputeEngineTemplateOptions.class).autoCreateKeyPair(false)\n            .tags(ImmutableSet.of(\"aTag\")).blockUntilRunning(false);\n\n      Template template = computeService.templateBuilder().options(options).build();\n      NodeMetadata node = getOnlyElement(computeService.createNodesInGroup(\"test\", 1, template));\n\n      // prove our caching works.\n      assertEquals(node.getImageId(), template.getImage().getId());\n\n      assertSent(server, \"GET\", \"/projects/party/regions\");\n      assertSent(server, \"GET\", \"/projects/party/global/images\");\n      assertSent(server, \"GET\", \"/projects/debian-cloud/global/images\");\n      assertSent(server, \"GET\", \"/projects/party/regions\");\n      assertSent(server, \"GET\", \"/projects/party/aggregated/machineTypes\");\n      assertSent(server, \"GET\", \"/projects/party/regions/us-central1/subnetworks/default\");\n      assertSent(server, \"GET\", \"/projects/party/global/networks/default\");\n      assertSent(server, \"GET\", \"/projects/party/global/firewalls/jclouds-test-65f\"); // Get Firewall\n      assertSent(server, \"POST\", \"/projects/party/global/firewalls\", // Create Firewall\n            stringFromResource(\"/firewall_insert_2.json\"));\n\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/operations/operation-1354084865060\");\n      assertSent(server, \"GET\", \"/projects/party/aggregated/instances\");\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/disks/test\");\n      assertSent(server, \"GET\", \"/projects/debian-cloud/global/images/debian-7-wheezy-v20140718\");\n      assertSent(server, \"POST\", \"/projects/party/zones/us-central1-a/instances\",\n            String.format(stringFromResource(\"/instance_insert_2.json\"), template.getHardware().getId(), template.getImage().getId()));\n\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/instances/test-1\");\n   }\n\n   public void createNodeWithSpecificDiskType() throws Exception {\n      server.enqueue(singleRegionSingleZoneResponse());\n      server.enqueue(jsonResponse(\"/image_list.json\"));\n      server.enqueue(jsonResponse(\"/image_list_debian.json\")); // per IMAGE_PROJECTS = \"debian-cloud\"\n      server.enqueue(singleRegionSingleZoneResponse());\n      server.enqueue(jsonResponse(\"/aggregated_machinetype_list.json\"));\n      server.enqueue(new MockResponse().setResponseCode(404)); // Get Subnet\n      server.enqueue(jsonResponse(\"/network_get_default.json\"));\n      server.enqueue(new MockResponse().setResponseCode(404)); // Get Firewall\n      server.enqueue(jsonResponse(\"/operation.json\")); // Create Firewall\n      server.enqueue(jsonResponse(\"/zone_operation.json\"));\n      server.enqueue(aggregatedListWithInstanceNetworkAndStatus(\"test-0\", \"test-network\", RUNNING));\n      server.enqueue(jsonResponse(\"/disk_get_with_source_image.json\"));\n      server.enqueue(jsonResponse(\"/image_get_for_source_image.json\"));\n      server.enqueue(jsonResponse(\"/disktype_ssd.json\"));\n      server.enqueue(jsonResponse(\"/operation.json\")); // Create Instance\n      server.enqueue(instanceWithNetworkAndStatusAndSsd(\"test-1\", \"test-network\", RUNNING));\n\n      ComputeService computeService = computeService();\n\n      GoogleComputeEngineTemplateOptions options = computeService.templateOptions()\n            .as(GoogleComputeEngineTemplateOptions.class).autoCreateKeyPair(false)\n            .tags(ImmutableSet.of(\"aTag\")).blockUntilRunning(false)\n            .bootDiskType(\"pd-ssd\");\n\n      Template template = computeService.templateBuilder().options(options).build();\n      NodeMetadata node = getOnlyElement(computeService.createNodesInGroup(\"test\", 1, template));\n\n      // prove our caching works.\n      assertEquals(node.getImageId(), template.getImage().getId());\n      assertEquals(node.getLocation().getId(), template.getLocation().getId());\n\n      assertSent(server, \"GET\", \"/projects/party/regions\");\n      assertSent(server, \"GET\", \"/projects/party/global/images\");\n      assertSent(server, \"GET\", \"/projects/debian-cloud/global/images\");\n      assertSent(server, \"GET\", \"/projects/party/regions\");\n      assertSent(server, \"GET\", \"/projects/party/aggregated/machineTypes\");\n      assertSent(server, \"GET\", \"/projects/party/regions/us-central1/subnetworks/default\");\n      assertSent(server, \"GET\", \"/projects/party/global/networks/default\");\n      assertSent(server, \"GET\", \"/projects/party/global/firewalls/jclouds-test-65f\"); // Get Firewall\n      assertSent(server, \"POST\", \"/projects/party/global/firewalls\", // Create Firewall\n            stringFromResource(\"/firewall_insert_2.json\"));\n\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/operations/operation-1354084865060\");\n      assertSent(server, \"GET\", \"/projects/party/aggregated/instances\");\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/disks/test\");\n      assertSent(server, \"GET\", \"/projects/debian-cloud/global/images/debian-7-wheezy-v20140718\");\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/diskTypes/pd-ssd\");\n      assertSent(server, \"POST\", \"/projects/party/zones/us-central1-a/instances\",\n            String.format(stringFromResource(\"/instance_insert_ssd.json\"), template.getHardware().getId(), template.getImage().getId()));\n\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/instances/test-1\");\n   }\n   \n   public void createNodeWithCustomSubnetwork() throws Exception {\n      server.enqueue(singleRegionSingleZoneResponse());\n      server.enqueue(jsonResponse(\"/image_list.json\"));\n      server.enqueue(jsonResponse(\"/image_list_debian.json\")); // per IMAGE_PROJECTS = \"debian-cloud\"\n      server.enqueue(singleRegionSingleZoneResponse());\n      server.enqueue(jsonResponse(\"/aggregated_machinetype_list.json\"));\n      server.enqueue(jsonResponse(\"/subnetwork_get.json\"));\n      server.enqueue(jsonResponse(\"/network_get.json\"));\n      server.enqueue(new MockResponse().setResponseCode(404)); // Get Firewall\n      server.enqueue(jsonResponse(\"/operation.json\")); // Create Firewall\n      server.enqueue(jsonResponse(\"/zone_operation.json\"));\n      server.enqueue(aggregatedListWithInstanceNetworkAndStatus(\"test-0\", \"test-network\", RUNNING));\n      server.enqueue(jsonResponse(\"/disk_get_with_source_image.json\"));\n      server.enqueue(jsonResponse(\"/image_get_for_source_image.json\"));\n      server.enqueue(jsonResponse(\"/disktype_ssd.json\"));\n      server.enqueue(jsonResponse(\"/operation.json\")); // Create Instance\n      server.enqueue(instanceWithNetworkAndStatusAndSsd(\"test-1\", \"test-network\", RUNNING));\n\n      ComputeService computeService = computeService();\n\n      GoogleComputeEngineTemplateOptions options = computeService.templateOptions()\n            .as(GoogleComputeEngineTemplateOptions.class).autoCreateKeyPair(false)\n            .tags(ImmutableSet.of(\"aTag\")).blockUntilRunning(false)\n            .bootDiskType(\"pd-ssd\").networks(\"jclouds-test\");\n\n      Template template = computeService.templateBuilder().options(options).build();\n      NodeMetadata node = getOnlyElement(computeService.createNodesInGroup(\"test\", 1, template));\n\n      // prove our caching works.\n      assertEquals(node.getImageId(), template.getImage().getId());\n      assertEquals(node.getLocation().getId(), template.getLocation().getId());\n\n      assertSent(server, \"GET\", \"/projects/party/regions\");\n      assertSent(server, \"GET\", \"/projects/party/global/images\");\n      assertSent(server, \"GET\", \"/projects/debian-cloud/global/images\");\n      assertSent(server, \"GET\", \"/projects/party/regions\");\n      assertSent(server, \"GET\", \"/projects/party/aggregated/machineTypes\");\n      assertSent(server, \"GET\", \"/projects/party/regions/us-central1/subnetworks/jclouds-test\");\n      assertSent(server, \"GET\", \"/projects/party/global/networks/mynetwork\");\n      assertSent(server, \"GET\", \"/projects/party/global/firewalls/jclouds-test-65f\"); // Get Firewall\n      assertSent(server, \"POST\", \"/projects/party/global/firewalls\", // Create Firewall\n            stringFromResource(\"/firewall_insert_3.json\"));\n\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/operations/operation-1354084865060\");\n      assertSent(server, \"GET\", \"/projects/party/aggregated/instances\");\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/disks/test\");\n      assertSent(server, \"GET\", \"/projects/debian-cloud/global/images/debian-7-wheezy-v20140718\");\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/diskTypes/pd-ssd\");\n      assertSent(server, \"POST\", \"/projects/party/zones/us-central1-a/instances\",\n            String.format(stringFromResource(\"/instance_insert_subnet.json\"), template.getHardware().getId(), template.getImage().getId()));\n\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/instances/test-1\");\n   }\n\n   public void createNodeWithoutExternalIp() throws Exception {\n      server.enqueue(singleRegionSingleZoneResponse());\n      server.enqueue(jsonResponse(\"/image_list.json\"));\n      server.enqueue(jsonResponse(\"/image_list_debian.json\")); // per IMAGE_PROJECTS = \"debian-cloud\"\n      server.enqueue(singleRegionSingleZoneResponse());\n      server.enqueue(jsonResponse(\"/aggregated_machinetype_list.json\"));\n      server.enqueue(jsonResponse(\"/subnetwork_get.json\"));\n      server.enqueue(jsonResponse(\"/network_get.json\"));\n      server.enqueue(new MockResponse().setResponseCode(404)); // Get Firewall\n      server.enqueue(jsonResponse(\"/operation.json\")); // Create Firewall\n      server.enqueue(jsonResponse(\"/zone_operation.json\"));\n      server.enqueue(aggregatedListWithInstanceNetworkAndStatus(\"test-0\", \"test-network\", RUNNING));\n      server.enqueue(jsonResponse(\"/disk_get_with_source_image.json\"));\n      server.enqueue(jsonResponse(\"/image_get_for_source_image.json\"));\n      server.enqueue(jsonResponse(\"/disktype_ssd.json\"));\n      server.enqueue(jsonResponse(\"/operation.json\")); // Create Instance\n      server.enqueue(instanceWithNetworkAndStatusAndSsd(\"test-1\", \"test-network\", RUNNING));\n\n      ComputeService computeService = computeService();\n\n      GoogleComputeEngineTemplateOptions options = computeService.templateOptions()\n            .as(GoogleComputeEngineTemplateOptions.class).autoCreateKeyPair(false)\n            .tags(ImmutableSet.of(\"aTag\")).blockUntilRunning(false)\n            .bootDiskType(\"pd-ssd\").networks(\"jclouds-test\").assignExternalIp(false);\n\n      Template template = computeService.templateBuilder().options(options).build();\n      NodeMetadata node = getOnlyElement(computeService.createNodesInGroup(\"test\", 1, template));\n\n      // prove our caching works.\n      assertEquals(node.getImageId(), template.getImage().getId());\n      assertEquals(node.getLocation().getId(), template.getLocation().getId());\n\n      assertSent(server, \"GET\", \"/projects/party/regions\");\n      assertSent(server, \"GET\", \"/projects/party/global/images\");\n      assertSent(server, \"GET\", \"/projects/debian-cloud/global/images\");\n      assertSent(server, \"GET\", \"/projects/party/regions\");\n      assertSent(server, \"GET\", \"/projects/party/aggregated/machineTypes\");\n      assertSent(server, \"GET\", \"/projects/party/regions/us-central1/subnetworks/jclouds-test\");\n      assertSent(server, \"GET\", \"/projects/party/global/networks/mynetwork\");\n      assertSent(server, \"GET\", \"/projects/party/global/firewalls/jclouds-test-65f\"); // Get Firewall\n      assertSent(server, \"POST\", \"/projects/party/global/firewalls\", // Create Firewall\n            stringFromResource(\"/firewall_insert_3.json\"));\n\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/operations/operation-1354084865060\");\n      assertSent(server, \"GET\", \"/projects/party/aggregated/instances\");\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/disks/test\");\n      assertSent(server, \"GET\", \"/projects/debian-cloud/global/images/debian-7-wheezy-v20140718\");\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/diskTypes/pd-ssd\");\n      assertSent(server, \"POST\", \"/projects/party/zones/us-central1-a/instances\",\n            String.format(stringFromResource(\"/instance_insert_no_ip.json\"), template.getHardware().getId(), template.getImage().getId()));\n\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/instances/test-1\");\n   }\n\n   private MockResponse instanceWithNetworkAndStatus(String instanceName, String networkName, Instance.Status status) {\n      return new MockResponse().setBody(\n            stringFromResource(\"/instance_get.json\").replace(\"test-0\", instanceName).replace(\"default\", networkName)\n                  .replace(\"RUNNING\", status.toString()));\n   }\n\n   private MockResponse instanceWithNetworkAndStatusAndSsd(String instanceName, String networkName, Instance.Status status) {\n      return new MockResponse().setBody(\n            stringFromResource(\"/instance_get.json\").replace(\"test-0\", instanceName).replace(\"default\", networkName)\n                  .replace(\"RUNNING\", status.toString()).replace(\"pd-standard\", \"pd-ssd\"));\n   }\n\n   private MockResponse aggregatedListWithInstanceNetworkAndStatus(String instanceName, String networkName,\n         Instance.Status status) {\n      return new MockResponse().setBody(\n            stringFromResource(\"/aggregated_instance_list.json\").replace(\"test-0\", instanceName)\n                  .replace(\"default\", networkName).replace(\"RUNNING\", status.toString()));\n   }\n   \n   private MockResponse aggregatedListInstanceEmpty() {\n      return new MockResponse().setBody(stringFromResource(\"/aggregated_instance_list_empty.json\"));\n   }\n}\n\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/compute/GoogleComputeEngineTemplateBuilderLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.compute;\n\nimport static com.google.common.base.MoreObjects.firstNonNull;\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.jclouds.compute.domain.OsFamily.COREOS;\nimport static org.jclouds.compute.domain.OsFamily.DEBIAN;\nimport static org.jclouds.compute.domain.OsFamily.WINDOWS;\nimport static org.jclouds.compute.util.ComputeServiceUtils.getCores;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\nimport java.net.URI;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.internal.BaseTemplateBuilderLiveTest;\nimport org.jclouds.googlecloud.internal.TestProperties;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"live\", testName = \"GoogleComputeEngineTemplateBuilderLiveTest\")\npublic class GoogleComputeEngineTemplateBuilderLiveTest extends BaseTemplateBuilderLiveTest {\n\n   public GoogleComputeEngineTemplateBuilderLiveTest() {\n      provider = \"google-compute-engine\";\n   }\n\n   @Override protected Properties setupProperties() {\n      TestProperties.setGoogleCredentialsFromJson(provider);\n      return TestProperties.apply(provider, super.setupProperties());\n   }\n\n   @Test\n   @Override\n   public void testDefaultTemplateBuilder() throws IOException {\n      Template defaultTemplate = view.getComputeService().templateBuilder().build();\n      assertTrue(defaultTemplate.getImage().getOperatingSystem().getVersion().equals(\"7.wheezy\"));\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true);\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), DEBIAN);\n      assertEquals(getCores(defaultTemplate.getHardware()), 1.0d);\n   }\n\n   @Test\n   public void testDefaultCredentials() {\n      Map<OsFamily, String> defaultUsernames = ImmutableMap.of(COREOS, \"core\", WINDOWS, \"Administrator\");\n      Set<? extends Image> images = view.getComputeService().listImages();\n      for (Image image : images) {\n         assertEquals(image.getDefaultCredentials().getUser(),\n               firstNonNull(defaultUsernames.get(image.getOperatingSystem().getFamily()), \"jclouds\"));\n      }\n   }\n\n   @Override\n   protected Set<String> getIso3166Codes() {\n      return ImmutableSet.<String> of();\n   }\n\n   @Override\n   @Test(dataProvider = \"onlyIfAutomaticHardwareSupported\", groups = {\"integration\", \"live\"})\n   public void testAutoGeneratedHardwareFromId() {\n      Template template = view.getComputeService().templateBuilder()\n            .hardwareId(\"automatic:cores=2;ram=1024\").build();\n      assertThat(template.getHardware().getId()).isEqualTo(template.getLocation()\n            .getDescription() + \"/machineTypes/custom-2-1024\");\n      assertThat(template.getHardware().getRam()).isEqualTo(1024);\n      assertThat(template.getHardware().getProcessors().get(0).getCores()).isEqualTo(2);\n      assertThat(template.getHardware().getUri()).isEqualTo(URI.create(template.getLocation()\n            .getDescription() + \"/machineTypes/custom-2-1024\"));\n   }\n\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/compute/domain/internal/GoogleComputeEngineArbitraryCpuRamTemplateBuilderImplTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.compute.domain.internal;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.util.concurrent.Atomics;\nimport com.google.inject.Provider;\nimport com.google.inject.util.Providers;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.HardwareBuilder;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.ImageBuilder;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.Processor;\nimport org.jclouds.compute.domain.TemplateBuilder;\nimport org.jclouds.compute.domain.internal.TemplateBuilderImpl;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.compute.strategy.GetImageStrategy;\nimport org.jclouds.compute.suppliers.ImageCacheSupplier;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.rest.AuthorizationException;\nimport org.testng.annotations.Test;\n\nimport java.net.URI;\nimport java.util.Set;\n\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.easymock.EasyMock.anyObject;\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\n\n@Test(groups = \"unit\", singleThreaded = true, testName = \"GoogleComputeEngineTemplateBuilderImplTest\")\npublic class GoogleComputeEngineArbitraryCpuRamTemplateBuilderImplTest {\n   private Location provider = new LocationBuilder()\n         .scope(LocationScope.PROVIDER)\n         .id(\"google-compute-engine\")\n         .description(\"google-compute-engine\")\n         .build();\n\n   private Location region = new LocationBuilder()\n         .scope(LocationScope.REGION)\n         .id(\"us-east-1\")\n         .description(\"http://localhost/projects/party/zones/us-east-1\")\n         .parent(provider)\n         .build();\n\n   private OperatingSystem os = OperatingSystem.builder()\n         .name(\"osName\")\n         .version(\"osVersion\")\n         .description(\"osDescription\")\n         .arch(\"X86_32\")\n         .build();\n\n   private Image image = new ImageBuilder()\n         .id(\"imageId\")\n         .providerId(\"imageId\")\n         .name(\"imageName\")\n         .description(\"imageDescription\")\n         .version(\"imageVersion\")\n         .operatingSystem(os)\n         .status(Image.Status.AVAILABLE)\n         .location(null)\n         .build();\n\n   private Hardware hardware = new HardwareBuilder()\n         .ram(2048)\n         .processor(new Processor(2, 1))\n         .id(\"http://localhost/projects/party/zones/us-east-1/machineTypes/n2-standard-2\")\n         .name(\"n2-standard-2\")\n         .location(region)\n         .uri(URI.create(\"http://localhost/projects/party/zones/us-east-1/machineTypes/n2-standard-2\"))\n         .build();\n\n   private final String errorMessage = \"No hardware profile matching the given criteria was found. If you want to use\" +\n           \" exact values, please set the minCores, minRam and minDisk to positive values.\";\n\n   @Test\n   public void testAutoGeneratedHardwareFromIdTest(){\n      Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet.of(region));\n      Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.of(image));\n      Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet\n            .<Hardware> of(hardware));\n      Provider<TemplateOptions> optionsProvider = createMock(Provider.class);\n      Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);\n      TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class);\n      GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class);\n\n      expect(optionsProvider.get()).andReturn(new TemplateOptions());\n      expect(getImageStrategy.getImage(anyObject(String.class))).andReturn(null);\n      replay(defaultTemplate, optionsProvider, templateBuilderProvider, getImageStrategy);\n\n      TemplateBuilderImpl templateBuilder =\n            new GoogleComputeEngineArbitraryCpuRamTemplateBuilderImpl(locations, new ImageCacheSupplier(images, 60,\n                  Atomics.<AuthorizationException>newReference(), Providers.of(getImageStrategy)), hardwares,\n                  Suppliers.ofInstance(region),\n                  optionsProvider, templateBuilderProvider);\n\n      Hardware hardware = templateBuilder.hardwareId(\"automatic:cores=2;ram=1024\").build().getHardware();\n      assertThat(hardware.getRam()).isEqualTo(1024);\n      assertThat(hardware.getProcessors()).extracting(\"cores\").containsExactly(2.0);\n      assertThat(hardware.getUri()).isEqualTo(URI.create(\"http://localhost/projects/party/zones/us-east-1/machineTypes/custom-2-1024\"));\n      assertThat(hardware.getId()).isEqualTo(\"http://localhost/projects/party/zones/us-east-1/machineTypes/custom-2-1024\");\n   }\n\n   @Test\n   public void testAutoGeneratedHardwareWithMinCoresAndMinRamDontMatchTest() {\n      Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n            .of(region));\n      Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.of(image));\n      Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet\n            .<Hardware> of(hardware));\n      Provider<TemplateOptions> optionsProvider = createMock(Provider.class);\n      Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);\n      TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class);\n      GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class);\n\n      expect(optionsProvider.get()).andReturn(new TemplateOptions());\n      expect(getImageStrategy.getImage(anyObject(String.class))).andReturn(null);\n      replay(defaultTemplate, optionsProvider, templateBuilderProvider, getImageStrategy);\n      TemplateBuilderImpl templateBuilder = new GoogleComputeEngineArbitraryCpuRamTemplateBuilderImpl(locations,\n            new ImageCacheSupplier(images, 60,\n                  Atomics.<AuthorizationException>newReference(), Providers.of(getImageStrategy)), hardwares,\n                  Suppliers.ofInstance(region), optionsProvider, templateBuilderProvider);\n      templateBuilder.minRam(4096);\n      templateBuilder.minCores(2);\n      Hardware hardware = templateBuilder.build().getHardware();\n      assertThat(hardware.getRam()).isEqualTo(4096);\n      assertThat(hardware.getProcessors()).extracting(\"cores\").containsExactly(2.0);\n      assertThat(hardware.getId()).isEqualTo(\"http://localhost/projects/party/zones/us-east-1/machineTypes/custom-2-4096\");\n   }\n\n   @Test\n   public void testAutoGeneratedHardwareMatchHardwareProfile() {\n      Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n            .of(region));\n      Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.of(image));\n      Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet\n            .<Hardware> of(hardware));\n      Provider<TemplateOptions> optionsProvider = createMock(Provider.class);\n      Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);\n      TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class);\n      GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class);\n\n      expect(optionsProvider.get()).andReturn(new TemplateOptions());\n      expect(getImageStrategy.getImage(anyObject(String.class))).andReturn(null);\n      replay(defaultTemplate, optionsProvider, templateBuilderProvider, getImageStrategy);\n      TemplateBuilderImpl templateBuilder = new GoogleComputeEngineArbitraryCpuRamTemplateBuilderImpl(locations,\n            new ImageCacheSupplier(images, 60,\n                  Atomics.<AuthorizationException>newReference(), Providers.of(getImageStrategy)), hardwares,\n                  Suppliers.ofInstance(region), optionsProvider, templateBuilderProvider);\n      templateBuilder.minRam(1024);\n      templateBuilder.minCores(2);\n      Hardware hardware = templateBuilder.build().getHardware();\n      assertThat(hardware.getRam()).isEqualTo(2048);\n      assertThat(hardware.getProcessors()).extracting(\"cores\").containsExactly(2.0);\n      assertThat(hardware.getId()).isEqualTo(\"http://localhost/projects/party/zones/us-east-1/machineTypes/n2-standard-2\");\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class,\n         expectedExceptionsMessageRegExp = errorMessage)\n   public void testAutoGeneratedHardwareWithOnlyMinCoresTest() {\n      Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n            .of(region));\n      Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.of(image));\n      Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet\n            .<Hardware> of(hardware));\n      Provider<TemplateOptions> optionsProvider = createMock(Provider.class);\n      Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);\n      TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class);\n      GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class);\n\n      expect(optionsProvider.get()).andReturn(new TemplateOptions());\n      expect(getImageStrategy.getImage(anyObject(String.class))).andReturn(null);\n      replay(defaultTemplate, optionsProvider, templateBuilderProvider, getImageStrategy);\n      TemplateBuilderImpl templateBuilder = new GoogleComputeEngineArbitraryCpuRamTemplateBuilderImpl(locations,\n            new ImageCacheSupplier(images, 60,\n                  Atomics.<AuthorizationException>newReference(), Providers.of(getImageStrategy)), hardwares,\n                  Suppliers.ofInstance(region), optionsProvider, templateBuilderProvider);\n      templateBuilder.minCores(4);\n      templateBuilder.build().getHardware();\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class,\n         expectedExceptionsMessageRegExp = errorMessage)\n   public void testAutoGeneratedHardwareWithOnlyMinRamTest() {\n      Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n            .of(region));\n      Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.of(image));\n      Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet\n            .<Hardware> of(hardware));\n      Provider<TemplateOptions> optionsProvider = createMock(Provider.class);\n      Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);\n      TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class);\n      GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class);\n\n      expect(optionsProvider.get()).andReturn(new TemplateOptions());\n      expect(getImageStrategy.getImage(anyObject(String.class))).andReturn(null);\n      replay(defaultTemplate, optionsProvider, templateBuilderProvider, getImageStrategy);\n      TemplateBuilderImpl templateBuilder = new GoogleComputeEngineArbitraryCpuRamTemplateBuilderImpl(locations,\n            new ImageCacheSupplier(images, 60,\n                  Atomics.<AuthorizationException>newReference(), Providers.of(getImageStrategy)), hardwares,\n                  Suppliers.ofInstance(region), optionsProvider, templateBuilderProvider);\n      templateBuilder.minRam(4096);\n      templateBuilder.build().getHardware();\n   }\n\n   @Test\n   public void testAutoGeneratedHardwareWithOnlyMinCoresMatchedHardware() {\n      Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n            .of(region));\n      Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.of(image));\n      Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet\n            .<Hardware> of(hardware));\n      Provider<TemplateOptions> optionsProvider = createMock(Provider.class);\n      Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);\n      TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class);\n      GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class);\n\n      expect(optionsProvider.get()).andReturn(new TemplateOptions());\n      expect(getImageStrategy.getImage(anyObject(String.class))).andReturn(null);\n      replay(defaultTemplate, optionsProvider, templateBuilderProvider, getImageStrategy);\n      TemplateBuilderImpl templateBuilder = new GoogleComputeEngineArbitraryCpuRamTemplateBuilderImpl(locations,\n            new ImageCacheSupplier(images, 60,\n                  Atomics.<AuthorizationException>newReference(), Providers.of(getImageStrategy)), hardwares,\n                  Suppliers.ofInstance(region), optionsProvider, templateBuilderProvider);\n      templateBuilder.minCores(2);\n      Hardware hardware = templateBuilder.build().getHardware();\n      assertThat(hardware.getRam()).isEqualTo(2048);\n      assertThat(hardware.getProcessors()).extracting(\"cores\").containsExactly(2.0);\n      assertThat(hardware.getId())\n            .isEqualTo(\"http://localhost/projects/party/zones/us-east-1/machineTypes/n2-standard-2\");\n   }\n\n   @Test\n   public void testAutoGeneratedHardwareOnlyRamMatchHardwareProfile() {\n      Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet\n            .of(region));\n      Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.of(image));\n      Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet\n            .<Hardware> of(hardware));\n      Provider<TemplateOptions> optionsProvider = createMock(Provider.class);\n      Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);\n      TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class);\n      GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class);\n\n      expect(optionsProvider.get()).andReturn(new TemplateOptions());\n      expect(getImageStrategy.getImage(anyObject(String.class))).andReturn(null);\n      replay(defaultTemplate, optionsProvider, templateBuilderProvider, getImageStrategy);\n      TemplateBuilderImpl templateBuilder = new GoogleComputeEngineArbitraryCpuRamTemplateBuilderImpl(locations,\n            new ImageCacheSupplier(images, 60,\n                  Atomics.<AuthorizationException>newReference(), Providers.of(getImageStrategy)), hardwares,\n                  Suppliers.ofInstance(region), optionsProvider, templateBuilderProvider);\n      templateBuilder.minRam(1024);\n      Hardware hardware = templateBuilder.build().getHardware();\n      assertThat(hardware.getRam()).isEqualTo(2048);\n      assertThat(hardware.getProcessors()).extracting(\"cores\").containsExactly(2.0);\n      assertThat(hardware.getId())\n            .isEqualTo(\"http://localhost/projects/party/zones/us-east-1/machineTypes/n2-standard-2\");\n   }\n\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/compute/functions/GoogleComputeEngineImageToImageTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.compute.functions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertSame;\n\nimport java.net.URI;\n\nimport org.jclouds.compute.domain.Image.Status;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.googlecomputeengine.domain.Deprecated;\nimport org.jclouds.googlecomputeengine.domain.Deprecated.State;\nimport org.jclouds.googlecomputeengine.domain.Image;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"GoogleComputeEngineImageToImageTest\")\npublic class GoogleComputeEngineImageToImageTest {\n   public void testArbitraryImageName() {\n      GoogleComputeEngineImageToImage imageToImage = new GoogleComputeEngineImageToImage(new ImageNameToOperatingSystem());\n      Image image = image(\"arbitratyname\", null);\n      org.jclouds.compute.domain.Image transformed = imageToImage.apply(image);\n      assertEquals(transformed.getName(), image.name());\n      assertEquals(transformed.getId(), image.selfLink().toString());\n      assertEquals(transformed.getProviderId(), image.id());\n      assertSame(transformed.getOperatingSystem().getFamily(), OsFamily.LINUX);\n   }\n\n   public void testWellFormedImageName() {\n      GoogleComputeEngineImageToImage imageToImage = new GoogleComputeEngineImageToImage(new ImageNameToOperatingSystem());\n      Image image = image(\"ubuntu-12-04-v123123\", null);\n      org.jclouds.compute.domain.Image transformed = imageToImage.apply(image);\n      assertEquals(transformed.getName(), image.name());\n      assertEquals(transformed.getId(), image.selfLink().toString());\n      assertEquals(transformed.getProviderId(), image.id());\n      assertSame(transformed.getOperatingSystem().getFamily(), OsFamily.UBUNTU);\n      assertEquals(transformed.getOperatingSystem().getVersion(), \"12.04\");\n   }\n\n   public void testDeleted(){\n      GoogleComputeEngineImageToImage imageToImage = new GoogleComputeEngineImageToImage(new ImageNameToOperatingSystem());\n      Deprecated deprecated =  Deprecated.create(\n         State.DELETED, // state\n         URI.create(\"http://baseurl/projects/centos-cloud/global/images/centos-6-2-v20120326test\"), // replacement\n         \"2014-07-16T22:16:13.468Z\", // deprecated\n         \"2015-07-16T22:16:13.468Z\", // obsolete\n         \"2016-07-16T22:16:13.468Z\"); // deleted\n      Image image = image(\"test-deprecated\", deprecated);\n      org.jclouds.compute.domain.Image transformed = imageToImage.apply(image);\n      assertEquals(transformed.getName(), image.name());\n      assertEquals(transformed.getId(), image.selfLink().toString());\n      assertEquals(transformed.getProviderId(), image.id());\n      assertSame(transformed.getOperatingSystem().getFamily(), OsFamily.LINUX);\n      assertEquals(transformed.getUserMetadata().get(\"deprecatedState\"), image.deprecated().state().name());\n      assertEquals(transformed.getStatus(), Status.DELETED);\n   }\n\n   public void testDeprecated(){\n      GoogleComputeEngineImageToImage imageToImage = new GoogleComputeEngineImageToImage(new ImageNameToOperatingSystem());\n      Deprecated deprecated =  Deprecated.create(\n         State.DEPRECATED, // state\n         URI.create(\"http://baseurl/projects/centos-cloud/global/images/centos-6-2-v20120326test\"), // replacement\n         \"2014-07-16T22:16:13.468Z\", // deprecated\n         \"2015-07-16T22:16:13.468Z\", // obsolete\n         \"2016-07-16T22:16:13.468Z\"); // deleted\n      Image image = image(\"test-deprecated\", deprecated);\n      org.jclouds.compute.domain.Image transformed = imageToImage.apply(image);\n      assertEquals(transformed.getStatus(), Status.AVAILABLE);\n   }\n\n   private static Image image(String name, Deprecated deprecated) {\n      return Image.create( //\n            \"1234\", // id\n            URI.create(\"http://test.com/1234\"), // selfLink\n            new SimpleDateFormatDateService().iso8601DateParse(\"2012-07-16T22:16:13.468\"), // creationTimestamp\n            name, // name\n            \"\", // description\n            \"RAW\", // sourceType\n            Image.RawDisk.create(URI.create(\"foo\"), \"TAR\", null), // rawDisk\n            deprecated, // deprecated\n            Image.Status.READY, // status\n            Long.parseLong(\"881210631\", 10), // archivedSizeBytes\n            Long.parseLong(\"8\", 10), // diskSizeGb\n            \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/disk/disk\", // sourceDisk\n            \"9598530021316715047\", // sourceDiskId\n            ImmutableList.of(\"https://www.googleapis.com/compute/v1/projects/suse-cloud/global/licenses/sles-12\") // license\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/compute/functions/ImageNameToOperatingSystemTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.compute.functions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ImageNameToOperatingSystemTest\")\npublic class ImageNameToOperatingSystemTest {\n   \n   private final ImageNameToOperatingSystem function = new ImageNameToOperatingSystem();\n   \n   public void testVersions() {\n      assertVersion(\"centos-6-v20150603\", OsFamily.CENTOS, \"6\");\n      assertVersion(\"coreos-stable-681-0-0-v20150609\", OsFamily.COREOS, \"stable.681.0.0\");\n      assertVersion(\"debian-7-wheezy-v20150603\", OsFamily.DEBIAN, \"7.wheezy\");\n      assertVersion(\"backports-debian-7-wheezy-v20150603\", OsFamily.DEBIAN, \"7.wheezy\");\n      assertVersion(\"nvme-backports-debian-7-wheezy-v20140904\", OsFamily.DEBIAN, \"7.wheezy\");\n      assertVersion(\"opensuse-13-1-v20150515\", OsFamily.SUSE, \"13.1\");\n      assertVersion(\"rhel-6-v20150603\", OsFamily.RHEL, \"6\");\n      assertVersion(\"sles-11-sp3-v20150511\", OsFamily.SUSE, \"11.sp3\");\n      assertVersion(\"sles-12-v20150511\", OsFamily.SUSE, \"12\");\n      assertVersion(\"ubuntu-1204-precise-v20150316\", OsFamily.UBUNTU, \"1204.precise\");\n      assertVersion(\"windows-server-2008-r2-dc-v20150511\", OsFamily.WINDOWS, \"server.2008.r2.dc\");\n   }\n\n   private void assertVersion(String name, OsFamily family, String version) {\n      OperatingSystem result = function.apply(name);\n      assertEquals(result.getFamily(), family);\n      assertEquals(result.getVersion(), version);\n      assertTrue(result.is64Bit());\n   }\n   \n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/compute/functions/InstanceToNodeMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.compute.functions;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Functions;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.HardwareBuilder;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.Processor;\nimport org.jclouds.compute.domain.Volume.Type;\nimport org.jclouds.compute.domain.VolumeBuilder;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.googlecomputeengine.domain.Image;\nimport org.jclouds.googlecomputeengine.domain.Instance;\nimport org.jclouds.googlecomputeengine.parse.ParseImageTest;\nimport org.jclouds.googlecomputeengine.parse.ParseInstanceTest;\nimport org.testng.annotations.BeforeMethod;\nimport org.testng.annotations.Test;\n\nimport java.net.URI;\nimport java.util.Map;\nimport java.util.Set;\n\nimport static com.google.common.collect.Maps.uniqueIndex;\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.jclouds.googlecomputeengine.compute.functions.InstanceToNodeMetadata.isCustomMachineTypeURI;\nimport static org.jclouds.googlecomputeengine.compute.functions.InstanceToNodeMetadata.machineTypeURIToCustomHardware;\nimport static org.testng.Assert.assertEquals;\n\n@Test(groups = \"unit\", testName = \"InstanceToNodeMetadataTest\", singleThreaded = true) // BeforeMethod = singleThreaded\npublic class InstanceToNodeMetadataTest {\n\n   /**\n    * GroupNamingConvention that always returns the same name provided in the constructor.\n    * The predicates returned always evaluate to true.\n    *\n    */\n   static class FixedGroupNamingConvention implements GroupNamingConvention {\n      private final String name;\n\n      public FixedGroupNamingConvention(final String name) {\n         this.name = name;\n      }\n\n      @Override\n      public String sharedNameForGroup(final String group) {\n         return name;\n      }\n\n      @Override\n      public String uniqueNameForGroup(final String group) {\n         return name;\n      }\n\n      @Override\n      public String groupInUniqueNameOrNull(final String encoded) {\n         return name;\n      }\n\n      @Override\n      public String groupInSharedNameOrNull(final String encoded) {\n         return name;\n      }\n\n      @Override\n      public Predicate<String> containsGroup(final String group) {\n         return new Predicate<String>() {\n            @Override\n            public boolean apply(final String input) {\n               return true;\n            }\n         };\n      }\n\n      @Override\n      public Predicate<String> containsAnyGroup() {\n         return new Predicate<String>() {\n            @Override\n            public boolean apply(final String input) {\n               return true;\n            }\n         };\n      }\n\n      @Override\n      public String extractGroup(final String encoded) {\n         return name;\n      }\n   }\n\n   private Instance instance;\n   private Set<Hardware> hardwares;\n   private URI imageUrl = new ParseImageTest().expected().selfLink();\n   private Set<Location> locations;\n   private InstanceToNodeMetadata groupNullNodeParser;\n\n   @BeforeMethod\n   public final void setup() {\n      instance = new ParseInstanceTest().expected();\n\n      hardwares = ImmutableSet.of(new HardwareBuilder().id(\"my_id\")\n         .uri(URI.create(\"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/machineTypes/\"\n               + \"n1-standard-1\"))\n         .providerId(\"1\")\n         .name(\"mock hardware\").processor(new Processor(1.0, 1.0)).ram(2048)\n         .volume(new VolumeBuilder().size(20f).type(Type.LOCAL).build()).build());\n\n      locations = ImmutableSet.of(new LocationBuilder()\n         .id(\"id\")\n         .description(\"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a\")\n         .scope(LocationScope.REGION)\n         .parent(\n               new LocationBuilder().id(\"0\").description(\"mock parent location\").scope(LocationScope.PROVIDER)\n               .build()).build());\n\n      groupNullNodeParser = createNodeParser(hardwares, locations, null);\n   }\n\n   private InstanceToNodeMetadata createNodeParser(final Set<Hardware> hardware, final Set<Location> locations,\n         final String groupName) {\n      Supplier<Map<URI, Location>> locationSupplier = new Supplier<Map<URI, Location>>() {\n         @Override\n         public Map<URI, Location> get() {\n            return uniqueIndex(locations, new Function<Location, URI>() {\n               @Override\n               public URI apply(final Location input) {\n                  return URI.create(input.getDescription());\n               }\n            });\n         }\n      };\n\n      Supplier<Map<URI, Hardware>> hardwareSupplier = Suppliers\n            .<Map<URI, Hardware>>ofInstance(uniqueIndex(hardware, new Function<Hardware, URI>() {\n               @Override\n               public URI apply(final Hardware input) {\n                  return input.getUri();\n               }\n            }));\n\n      GroupNamingConvention.Factory namingConventionFactory =\n         new GroupNamingConvention.Factory() {\n            @Override\n            public GroupNamingConvention createWithoutPrefix() {\n               return new FixedGroupNamingConvention(groupName);\n            }\n\n            @Override\n            public GroupNamingConvention create() {\n               return new FixedGroupNamingConvention(groupName);\n            }\n         };\n\n      Map<URI, Optional<Image>> imageMap = ImmutableMap.of(instance.disks().get(0).source(),\n            Optional.of(new ParseImageTest().expected()));\n\n      return new InstanceToNodeMetadata(\n         ImmutableMap.<Instance.Status, NodeMetadata.Status>builder()\n            .put(Instance.Status.RUNNING, NodeMetadata.Status.PENDING).build(),\n            namingConventionFactory,\n            CacheBuilder.newBuilder().build(CacheLoader.from(Functions.forMap(imageMap))),\n            hardwareSupplier,\n            locationSupplier);\n   }\n\n   @Test\n   public void imageUrl() {\n      NodeMetadata nodeMetadata = groupNullNodeParser.apply(instance);\n      assertEquals(nodeMetadata.getImageId(), imageUrl.toString());\n   }\n\n   @Test\n   public final void testInstanceWithGroupNull() {\n      NodeMetadata nodeMetadata = groupNullNodeParser.apply(instance);\n      assertEquals(nodeMetadata.getId(), instance.selfLink().toString());\n      assertEquals(nodeMetadata.getTags(), ImmutableSet.of(\"aTag\", \"Group-port-42\"));\n   }\n\n   @Test\n   public void isCustomMachineTypeTest() {\n      URI uri = URI.create(\"https://www.googleapis.com/compute/v1/projects/jclouds-dev/zones/asia-east1-a/machineTypes/custom-1-1024\");\n      assertThat(isCustomMachineTypeURI(uri)).isTrue();\n\n      URI uri2 = URI.create(\"https://www.googleapis.com/compute/v1/projects/jclouds-dev/\");\n      assertThat(isCustomMachineTypeURI(uri2)).isFalse();\n   }\n\n   @Test\n   public void machineTypeParserTest() {\n      URI uri = URI.create(\"https://www.googleapis.com/compute/v1/projects/jclouds-dev/zones/asia-east1-a/machineTypes/custom-1-1024\");\n      Hardware hardware = machineTypeURIToCustomHardware(uri);\n      assertThat(hardware.getRam()).isEqualTo(1024);\n      assertThat(hardware.getProcessors().get(0).getCores()).isEqualTo(1);\n      assertThat(hardware.getUri())\n            .isEqualTo(URI.create(\"https://www.googleapis.com/compute/v1/projects/jclouds-dev/zones/asia-east1-a/machineTypes/custom-1-1024\"));\n      assertThat(hardware.getId())\n            .isEqualTo(\"https://www.googleapis.com/compute/v1/projects/jclouds-dev/zones/asia-east1-a/machineTypes/custom-1-1024\");\n   }\n\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/compute/functions/OrphanedGroupsFromDeadNodesTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.compute.functions;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.testng.Assert.assertSame;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\n\nimport org.easymock.EasyMock;\nimport org.jclouds.compute.ComputeService;\nimport org.jclouds.compute.domain.ComputeMetadata;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.internal.NodeMetadataImpl;\nimport org.jclouds.googlecomputeengine.compute.predicates.GroupIsEmpty;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Sets;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\n\npublic class OrphanedGroupsFromDeadNodesTest {\n\n   private static class IdAndGroupOnlyNodeMetadata extends NodeMetadataImpl {\n\n      public IdAndGroupOnlyNodeMetadata(String id, String group, Status status) {\n         super(null, null, id, null, null, ImmutableMap.<String, String>of(), ImmutableSet.<String>of(), group, null,\n                 null, null, status, null, 0, ImmutableSet.<String>of(), ImmutableSet.<String>of(), null, null);\n      }\n   }\n\n\n   @Test\n   public void testDetectsNoOrphanedGroupsWhenAllNodesArePresentAndTerminated() {\n\n      Set<NodeMetadata> deadNodesGroup1 = ImmutableSet.<NodeMetadata>builder()\n              .add(new IdAndGroupOnlyNodeMetadata(\"a\", \"1\", NodeMetadata.Status.TERMINATED)).build();\n\n      Set<NodeMetadata> deadNodesGroup2 = ImmutableSet.<NodeMetadata> builder()\n              .add(new IdAndGroupOnlyNodeMetadata(\"b\", \"2\", NodeMetadata.Status.SUSPENDED)).build();\n\n      Set<NodeMetadata> allDeadNodes = Sets.union(deadNodesGroup1, deadNodesGroup2);\n\n      ComputeService mock = createMock(ComputeService.class);\n      expect(mock.listNodesDetailsMatching(EasyMock.<Predicate<ComputeMetadata>>anyObject()))\n              .andReturn((Set) deadNodesGroup1).once();\n      expect(mock.listNodesDetailsMatching(EasyMock.<Predicate<ComputeMetadata>>anyObject()))\n              .andReturn((Set) deadNodesGroup2).once();\n\n      replay(mock);\n\n      OrphanedGroupsFromDeadNodes orphanedGroupsFromDeadNodes = new OrphanedGroupsFromDeadNodes(\n              allNodesInGroupTerminated(mock));\n\n      Set<String> orphanedGroups = orphanedGroupsFromDeadNodes.apply(allDeadNodes);\n\n      assertTrue(orphanedGroups.isEmpty());\n   }\n\n   @Test\n   public void testDetectsOneOrphanedGroupWhenSomeNodesTerminatedAndOtherMissing() {\n\n      Set<NodeMetadata> deadNodesGroup1 = ImmutableSet.<NodeMetadata> builder()\n              .add(new IdAndGroupOnlyNodeMetadata(\"a\", \"1\", NodeMetadata.Status.TERMINATED)).build();\n\n      Set<NodeMetadata> deadNodesGroup2 = ImmutableSet.<NodeMetadata> builder()\n              .add(new IdAndGroupOnlyNodeMetadata(\"b\", \"2\", NodeMetadata.Status.TERMINATED)).build();\n\n      Set<NodeMetadata> allDeadNodes = Sets.union(deadNodesGroup1, deadNodesGroup2);\n\n      ComputeService mock = createMock(ComputeService.class);\n      expect(mock.listNodesDetailsMatching(EasyMock.<Predicate<ComputeMetadata>>anyObject()))\n              .andReturn((Set) deadNodesGroup1).once();\n      expect(mock.listNodesDetailsMatching(EasyMock.<Predicate<ComputeMetadata>>anyObject()))\n              .andReturn((Set) ImmutableSet.of()).once();\n\n      replay(mock);\n\n      OrphanedGroupsFromDeadNodes orphanedGroupsFromDeadNodes = new OrphanedGroupsFromDeadNodes(\n            allNodesInGroupTerminated(mock));\n\n      Set<String> orphanedGroups = orphanedGroupsFromDeadNodes.apply(allDeadNodes);\n\n      assertSame(orphanedGroups.size(), 1);\n      assertTrue(orphanedGroups.contains(\"2\"));\n   }\n\n   @Test\n   public void testDetectsOneOrphanedGroupWhenSomeNodesAreAliveAndOtherMissing() {\n\n      Set<NodeMetadata> deadNodesGroup1 = ImmutableSet.<NodeMetadata> builder()\n              .add(new IdAndGroupOnlyNodeMetadata(\"a\", \"1\", NodeMetadata.Status.RUNNING)).build();\n\n      Set<NodeMetadata> deadNodesGroup2 = ImmutableSet.<NodeMetadata> builder()\n              .add(new IdAndGroupOnlyNodeMetadata(\"b\", \"2\", NodeMetadata.Status.TERMINATED)).build();\n\n      Set<NodeMetadata> allDeadNodes = Sets.union(deadNodesGroup1, deadNodesGroup2);\n\n      ComputeService mock = createMock(ComputeService.class);\n      expect(mock.listNodesDetailsMatching(EasyMock.<Predicate<ComputeMetadata>>anyObject()))\n              .andReturn((Set) deadNodesGroup1).once();\n      expect(mock.listNodesDetailsMatching(EasyMock.<Predicate<ComputeMetadata>>anyObject()))\n              .andReturn((Set) ImmutableSet.of()).once();\n\n      replay(mock);\n\n      OrphanedGroupsFromDeadNodes orphanedGroupsFromDeadNodes = new OrphanedGroupsFromDeadNodes(\n              allNodesInGroupTerminated(mock));\n\n      Set<String> orphanedGroups = orphanedGroupsFromDeadNodes.apply(allDeadNodes);\n\n      assertSame(orphanedGroups.size(), 1);\n      assertTrue(orphanedGroups.contains(\"2\"));\n   }\n   \n   @Test\n   public void testDetectsAllOrphanedGroupsWhenAllNodesArerMissing() {\n\n      Set<NodeMetadata> deadNodesGroup1 = ImmutableSet.<NodeMetadata> builder()\n              .add(new IdAndGroupOnlyNodeMetadata(\"a\", \"1\", NodeMetadata.Status.RUNNING)).build();\n\n      Set<NodeMetadata> deadNodesGroup2 = ImmutableSet.<NodeMetadata> builder()\n              .add(new IdAndGroupOnlyNodeMetadata(\"b\", \"2\", NodeMetadata.Status.TERMINATED)).build();\n\n      Set<NodeMetadata> allDeadNodes = Sets.union(deadNodesGroup1, deadNodesGroup2);\n\n      ComputeService mock = createMock(ComputeService.class);\n      expect(mock.listNodesDetailsMatching(EasyMock.<Predicate<ComputeMetadata>>anyObject()))\n              .andReturn((Set) ImmutableSet.of()).once();\n      expect(mock.listNodesDetailsMatching(EasyMock.<Predicate<ComputeMetadata>>anyObject()))\n              .andReturn((Set) ImmutableSet.of()).once();\n\n      replay(mock);\n\n      OrphanedGroupsFromDeadNodes orphanedGroupsFromDeadNodes = new OrphanedGroupsFromDeadNodes(\n              allNodesInGroupTerminated(mock));\n\n      Set<String> orphanedGroups = orphanedGroupsFromDeadNodes.apply(allDeadNodes);\n\n      assertSame(orphanedGroups.size(), 2);\n      assertTrue(orphanedGroups.contains(\"1\"));\n      assertTrue(orphanedGroups.contains(\"2\"));\n   }\n\n   private Predicate<String> allNodesInGroupTerminated(final ComputeService mock) {\n      return Guice.createInjector(new AbstractModule() {\n         @Override protected void configure() {\n            bind(ComputeService.class).toInstance(mock);\n         }\n      }).getInstance(GroupIsEmpty.class); // rather than opening ctor.\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/compute/functions/ResetWindowsPasswordTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.compute.functions;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Predicates;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.io.BaseEncoding;\nimport com.google.gson.Gson;\n\nimport org.jclouds.crypto.Crypto;\nimport org.jclouds.encryption.bouncycastle.BouncyCastleCrypto;\nimport org.jclouds.googlecomputeengine.GoogleComputeEngineApi;\nimport org.jclouds.googlecomputeengine.domain.Instance;\nimport org.jclouds.googlecomputeengine.domain.Instance.SerialPortOutput;\nimport org.jclouds.googlecomputeengine.domain.Metadata;\nimport org.jclouds.googlecomputeengine.domain.Operation;\nimport org.jclouds.googlecomputeengine.features.InstanceApi;\nimport org.jclouds.googlecomputeengine.parse.ParseInstanceTest;\nimport org.jclouds.json.internal.GsonWrapper;\nimport org.testng.annotations.Test;\n\nimport javax.crypto.Cipher;\nimport java.math.BigInteger;\nimport java.nio.charset.Charset;\nimport java.security.KeyFactory;\nimport java.security.KeyPair;\nimport java.security.KeyPairGenerator;\nimport java.security.Security;\nimport java.security.spec.RSAPublicKeySpec;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.eq;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.isA;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertEquals;\n\n@Test(groups = \"unit\")\npublic class ResetWindowsPasswordTest {\n   public void testGeneratePassword() throws Exception {\n      Crypto bcCrypto = new BouncyCastleCrypto();\n      Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());\n\n      String password = \"|opj213'33423'*\";\n\n      KeyPair keyPair = bcCrypto.rsaKeyPairGenerator().genKeyPair();\n\n      KeyFactory factory = bcCrypto.rsaKeyFactory();\n      RSAPublicKeySpec pubSpec = factory.getKeySpec(keyPair.getPublic(), RSAPublicKeySpec.class);\n      BigInteger exponent = pubSpec.getPublicExponent();\n      String exponentString = BaseEncoding.base64().encode(exponent.toByteArray()).replaceAll(\"\\n\", \"\");\n\n      Cipher cipher = bcCrypto.cipher(\"RSA/NONE/OAEPPadding\");\n      cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());\n      String encryptedPass = BaseEncoding.base64().encode(cipher.doFinal(password.getBytes(Charset.forName(\"UTF-8\")), 0, password.length()));\n\n      Predicate<AtomicReference<Operation>> operationDone = Predicates.alwaysTrue();\n      Instance instance = new ParseInstanceTest().expected();\n      String zone = \"us-central1-a\";\n\n      GoogleComputeEngineApi api = createMock(GoogleComputeEngineApi.class);\n      InstanceApi instanceApi = createMock(InstanceApi.class);\n      Operation operation = createMock(Operation.class);\n      SerialPortOutput serialPortOutput = createMock(SerialPortOutput.class);\n      Crypto crypto = createMock(Crypto.class);\n      KeyPairGenerator keyPairGenerator = createMock(KeyPairGenerator.class);\n      \n      expect(api.instancesInZone(zone)).andReturn(instanceApi).atLeastOnce();\n      expect(crypto.rsaKeyPairGenerator()).andReturn(keyPairGenerator);\n      expect(crypto.rsaKeyFactory()).andReturn(factory);\n      expect(keyPairGenerator.genKeyPair()).andReturn(keyPair);\n      // FIXME assert that metadata contained what we expected\n      expect(instanceApi.setMetadata(eq(instance.name()), isA(Metadata.class))).andReturn(operation).atLeastOnce();\n      expect(operation.httpErrorStatusCode()).andReturn(null);\n      expect(instanceApi.getSerialPortOutput(instance.name(), 4)).andReturn(serialPortOutput).atLeastOnce();\n      expect(serialPortOutput.contents()).andReturn(\"{\\\"ready\\\":true,\\\"version\\\":\\\"Microsoft Windows NT 6.2.9200.0\\\"}\\n\" +\n              \"{\\\"encryptedPassword\\\":\\\"\" + encryptedPass + \"\\\",\\\"exponent\\\":\\\"\" + exponentString + \"\\\",\\\"passwordFound\\\":true,\\\"userName\\\":\\\"Administrator\\\"}\");\n      expect(crypto.cipher(\"RSA/NONE/OAEPPadding\")).andReturn(bcCrypto.cipher(\"RSA/NONE/OAEPPadding\"));\n\n      replay(api, instanceApi, operation, serialPortOutput, crypto, keyPairGenerator);\n\n      ResetWindowsPassword generator = new ResetWindowsPassword(api, crypto, operationDone, new GsonWrapper(new Gson()));\n      String result = generator.apply(ImmutableMap.of(\"instance\", new AtomicReference<Instance>(instance), \"zone\", zone,  \"email\", \"test@google.com\", \"userName\", \"test\"));\n\n      verify(api, instanceApi, operation, serialPortOutput);\n\n      assertEquals(result, password);\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/compute/functions/ResourcesMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.compute.functions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\n\nimport org.jclouds.googlecomputeengine.domain.Disk;\nimport org.jclouds.googlecomputeengine.domain.Image;\nimport org.jclouds.googlecomputeengine.domain.Instance;\nimport org.jclouds.googlecomputeengine.domain.Network;\nimport org.jclouds.googlecomputeengine.domain.Operation;\nimport org.jclouds.googlecomputeengine.domain.Subnetwork;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiMockTest;\nimport org.jclouds.googlecomputeengine.parse.ParseDiskTest;\nimport org.jclouds.googlecomputeengine.parse.ParseImageTest;\nimport org.jclouds.googlecomputeengine.parse.ParseInstanceTest;\nimport org.jclouds.googlecomputeengine.parse.ParseNetworkTest;\nimport org.jclouds.googlecomputeengine.parse.ParseOperationTest;\nimport org.jclouds.googlecomputeengine.parse.ParseSubnetworkTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ResourcesMockTest\", singleThreaded = true)\npublic class ResourcesMockTest extends BaseGoogleComputeEngineApiMockTest {\n\n   public void testInstance() throws Exception {\n      server.enqueue(jsonResponse(\"/instance_get.json\"));\n\n      Instance instance = resourceApi().instance(server.url(\"/foo/bar\").uri());\n      assertEquals(instance, new ParseInstanceTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/foo/bar\");\n   }\n   \n   public void testInstanceReturns404() throws Exception {\n      server.enqueue(response404());\n\n      Instance instance = resourceApi().instance(server.url(\"/foo/bar\").uri());\n      assertNull(instance);\n      assertSent(server, \"GET\", \"/foo/bar\");\n   }\n   \n   public void testNetwork() throws Exception {\n      server.enqueue(jsonResponse(\"/network_get.json\"));\n\n      Network network = resourceApi().network(server.url(\"/foo/bar\").uri());\n      assertEquals(network, new ParseNetworkTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/foo/bar\");\n   }\n   \n   public void testNetworkReturns404() throws Exception {\n      server.enqueue(response404());\n\n      Network network = resourceApi().network(server.url(\"/foo/bar\").uri());\n      assertNull(network);\n      assertSent(server, \"GET\", \"/foo/bar\");\n   }\n\n   public void testDisk() throws Exception {\n      server.enqueue(jsonResponse(\"/disk_get.json\"));\n\n      Disk disk = resourceApi().disk(server.url(\"/foo/bar\").uri());\n      assertEquals(disk, new ParseDiskTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/foo/bar\");\n   }\n\n   public void testDiskReturns404() throws Exception {\n      server.enqueue(response404());\n\n      Disk disk = resourceApi().disk(server.url(\"/foo/bar\").uri());\n      assertNull(disk);\n      assertSent(server, \"GET\", \"/foo/bar\");\n   }\n\n   public void testImage() throws Exception {\n      server.enqueue(jsonResponse(\"/image_get.json\"));\n\n      Image image = resourceApi().image(server.url(\"/foo/bar\").uri());\n      assertEquals(image, new ParseImageTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/foo/bar\");\n   }\n\n   public void testImageReturns404() throws Exception {\n      server.enqueue(response404());\n\n      Image image = resourceApi().image(server.url(\"/foo/bar\").uri());\n      assertNull(image);\n      assertSent(server, \"GET\", \"/foo/bar\");\n   }\n\n   public void testOperation() throws Exception {\n      server.enqueue(jsonResponse(\"/operation.json\"));\n\n      Operation operation = resourceApi().operation(server.url(\"/foo/bar\").uri());\n      assertEquals(operation, new ParseOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/foo/bar\");\n   }\n   \n   public void testOperationReturns404() throws Exception {\n      server.enqueue(response404());\n\n      Operation operation = resourceApi().operation(server.url(\"/foo/bar\").uri());\n      assertNull(operation);\n      assertSent(server, \"GET\", \"/foo/bar\");\n   }\n   \n   public void testDelete() throws Exception {\n      server.enqueue(jsonResponse(\"/operation.json\"));\n\n      Operation operation = resourceApi().delete(server.url(\"/foo/bar\").uri());\n      assertEquals(operation, new ParseOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"DELETE\", \"/foo/bar\");\n   }\n   \n   public void testDeleteReturns404() throws Exception {\n      server.enqueue(response404());\n\n      Operation operation = resourceApi().delete(server.url(\"/foo/bar\").uri());\n      assertNull(operation);\n      assertSent(server, \"DELETE\", \"/foo/bar\");\n   }\n   \n   public void testResetInstance() throws Exception {\n      server.enqueue(jsonResponse(\"/operation.json\"));\n\n      Operation operation = resourceApi().resetInstance(server.url(\"/foo/bar\").uri());\n      assertEquals(operation, new ParseOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"POST\", \"/foo/bar/reset\");\n   }\n   \n   public void testStopInstance() throws Exception {\n      server.enqueue(jsonResponse(\"/operation.json\"));\n\n      Operation operation = resourceApi().stopInstance(server.url(\"/foo/bar\").uri());\n      assertEquals(operation, new ParseOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"POST\", \"/foo/bar/stop\");\n   }\n   \n   public void testStartInstance() throws Exception {\n      server.enqueue(jsonResponse(\"/operation.json\"));\n\n      Operation operation = resourceApi().startInstance(server.url(\"/foo/bar\").uri());\n      assertEquals(operation, new ParseOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"POST\", \"/foo/bar/start\");\n   }\n   \n   public void testSubnetwork() throws Exception {\n      server.enqueue(jsonResponse(\"/subnetwork_get.json\"));\n\n      Subnetwork subnet = resourceApi().subnetwork(server.url(\"/foo/bar\").uri());\n      assertEquals(subnet, new ParseSubnetworkTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/foo/bar\");\n   }\n   \n   public void testSubnetworkReturns404() throws Exception {\n      server.enqueue(response404());\n\n      Subnetwork subnet = resourceApi().subnetwork(server.url(\"/foo/bar\").uri());\n      assertNull(subnet);\n      assertSent(server, \"GET\", \"/foo/bar\");\n   }\n   \n   private Resources resourceApi() {\n      return builder().build().utils().injector().getInstance(Resources.class);\n   }\n}\n\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/compute/loaders/DiskURIToImageTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.compute.loaders;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.mock;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.Date;\nimport java.util.concurrent.ExecutionException;\n\nimport org.jclouds.googlecomputeengine.compute.functions.Resources;\nimport org.jclouds.googlecomputeengine.domain.Disk;\nimport org.jclouds.googlecomputeengine.domain.Disk.Status;\nimport org.jclouds.googlecomputeengine.domain.Image;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"DiskURIToImageTest\")\npublic class DiskURIToImageTest {\n   \n   private static final URI DISK_URI = URI.create(\"http://localhost/disk/1\");\n   private static final URI IMAGE_URI = URI.create(\"http://localhost/image/1\");\n   \n   public void testLoadNotFound() throws ExecutionException {\n      Resources resources = mock(Resources.class);\n      expect(resources.disk(DISK_URI)).andReturn(null);\n      replay(resources);\n      \n      DiskURIToImage diskURIToImage = new DiskURIToImage(resources);\n      assertFalse(diskURIToImage.load(DISK_URI).isPresent());\n      \n      verify(resources);\n   }\n   \n   public void testImageSourceMissing() throws ExecutionException {\n      Resources resources = mock(Resources.class);\n      expect(resources.disk(DISK_URI)).andReturn(disk(null));\n      replay(resources);\n      \n      DiskURIToImage diskURIToImage = new DiskURIToImage(resources);\n      assertFalse(diskURIToImage.load(DISK_URI).isPresent());\n      \n      verify(resources);\n   }\n   \n   public void testImageNotFound() throws ExecutionException {\n      Resources resources = mock(Resources.class);\n      expect(resources.disk(DISK_URI)).andReturn(disk(IMAGE_URI));\n      expect(resources.image(IMAGE_URI)).andReturn(null);\n      replay(resources);\n      \n      DiskURIToImage diskURIToImage = new DiskURIToImage(resources);\n      assertFalse(diskURIToImage.load(DISK_URI).isPresent());\n      \n      verify(resources);\n   }\n   \n   public void testImageFound() throws ExecutionException {\n      Resources resources = mock(Resources.class);\n      expect(resources.disk(DISK_URI)).andReturn(disk(IMAGE_URI));\n      expect(resources.image(IMAGE_URI)).andReturn(image());\n      replay(resources);\n      \n      DiskURIToImage diskURIToImage = new DiskURIToImage(resources);\n      assertTrue(diskURIToImage.load(DISK_URI).isPresent());\n      \n      verify(resources);\n   }\n   \n   private static Disk disk(URI sourceImage) {\n      return Disk.create( //\n            \"13050421646334304115\", // id\n            new Date(), // creationTimestamp\n            URI.create(\"http://localhost/zone\"), // zone\n            Status.READY, // status\n            \"testimage1\", // name\n            null, // description\n            1, // sizeGb\n            null, // sourceSnapshot\n            null, // sourceSnapshotId\n            DISK_URI, // selfLink\n            sourceImage, // sourceImage\n            null, // sourceImageId\n            URI.create(\"http://localhost/type\"), // type\n            null // license\n      );\n   }\n   \n   private static Image image() {\n      return Image.create( //\n            \"1234\", // id\n            IMAGE_URI, // selfLink\n            new Date(), // creationTimestamp\n            \"\", // name\n            \"\", // description\n            \"RAW\", // sourceType\n            Image.RawDisk.create(URI.create(\"foo\"), \"TAR\", null), // rawDisk\n            null, // deprecated\n            Image.Status.READY, // status\n            Long.parseLong(\"881210631\", 10), // archivedSizeBytes\n            Long.parseLong(\"8\", 10), // diskSizeGb\n            DISK_URI.toString(), // sourceDisk\n            \"9598530021316715047\", // sourceDiskId\n            ImmutableList.of(\"https://www.googleapis.com/compute/v1/projects/suse-cloud/global/licenses/sles-12\") // license\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/config/UseApiToResolveProjectNameMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.config;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.fail;\n\nimport java.net.URI;\n\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.googlecomputeengine.GoogleComputeEngineApiMetadata;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiMockTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"UseApiToResolveProjectSelfLinkMockTest\", singleThreaded = true)\npublic class UseApiToResolveProjectNameMockTest extends BaseGoogleComputeEngineApiMockTest {\n   private final String projectNumber = \"761326798069\";\n\n   public void validClientEmail() throws Exception {\n      server.enqueue(jsonResponse(\"/project.json\"));\n\n      URI projectSelfLink = fn().apply(new Credentials(projectNumber + \"@developer.gserviceaccount.com\", credential));\n\n      assertEquals(projectSelfLink.toString(), url(\"/projects/party\"));\n\n      assertSent(server, \"GET\", \"/projects/\" + projectNumber);\n   }\n\n   public void validClientEmail_extendedUid() throws Exception {\n      server.enqueue(jsonResponse(\"/project.json\"));\n\n      URI projectSelfLink = fn().apply(\n            new Credentials(projectNumber + \"-r5mljlln1rd4lrbhg75efgigp36m78j5@developer.gserviceaccount.com\", credential));\n\n      assertEquals(projectSelfLink.toString(), url(\"/projects/party\"));\n\n      assertSent(server, \"GET\", \"/projects/\" + projectNumber);\n   }\n\n   /**\n    * We do not support just supplying the projectNumber, as this causes confusion when using oauth. OAuth JWT requires\n    * the whole email for the ISS field. This is better than confusing users with instructions like \"Use the email,\n    * except if using bearer token. Then, you don't need the entire email, just put in the numeric id part of it.\"\n    */\n   public void justProjectIdIsInvalid() throws Exception {\n      server.enqueue(jsonResponse(\"/project.json\"));\n\n      try {\n         fn().apply(new Credentials(projectNumber, credential));\n         fail();\n      } catch (IllegalArgumentException e) {\n         assertEquals(e.getMessage(), String.format(\"Client email %s is malformed. Should be %s\", projectNumber,\n               new GoogleComputeEngineApiMetadata().getIdentityName()));\n      }\n\n      assertEquals(server.getRequestCount(), 0);\n   }\n\n   GoogleComputeEngineHttpApiModule.UseApiToResolveProjectName fn() {\n      return builder().buildInjector().getInstance(GoogleComputeEngineHttpApiModule.UseApiToResolveProjectName.class);\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/AddressApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.jclouds.googlecomputeengine.options.ListOptions.Builder.filter;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.Iterator;\n\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.domain.Address;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiLiveTest;\nimport org.testng.annotations.Test;\n\npublic class AddressApiLiveTest extends BaseGoogleComputeEngineApiLiveTest {\n\n   private static final String ADDRESS_NAME = \"address-api-live-test-address\";\n\n   private AddressApi api() {\n      return api.addressesInRegion(DEFAULT_REGION_NAME);\n   }\n\n   @Test(groups = \"live\")\n   public void testInsertAddress() {\n      assertOperationDoneSuccessfully(api().create(ADDRESS_NAME));\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testInsertAddress\")\n   public void testGetAddress() {\n      Address address = api().get(ADDRESS_NAME);\n      assertNotNull(address);\n      assertEquals(address.name(), ADDRESS_NAME);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testGetAddress\")\n   public void testListAddress() {\n      Iterator<ListPage<Address>> addresses = api().list(filter(\"name eq \" + ADDRESS_NAME));\n      assertEquals(addresses.next().size(), 1);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testListAddress\", alwaysRun = true)\n   public void testDeleteAddress() {\n      assertOperationDoneSuccessfully(api().delete(ADDRESS_NAME));\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/AddressApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.AssertJUnit.assertNull;\n\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiMockTest;\nimport org.jclouds.googlecomputeengine.options.AddressCreationOptions;\nimport org.jclouds.googlecomputeengine.parse.ParseAddressListTest;\nimport org.jclouds.googlecomputeengine.parse.ParseAddressTest;\nimport org.jclouds.googlecomputeengine.parse.ParseRegionOperationTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"AddressApiExpectTest\", singleThreaded = true)\npublic class AddressApiMockTest extends BaseGoogleComputeEngineApiMockTest {\n\n   public void get() throws Exception{\n      server.enqueue(jsonResponse(\"/address_get.json\"));\n\n      assertEquals(addressApi().get(\"test-ip1\"), new ParseAddressTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/projects/party/regions/us-central1/addresses/test-ip1\");\n   }\n\n   public void get_4xx() throws Exception {\n      server.enqueue(response404());\n\n      assertNull(addressApi().get(\"test-ip1\"));\n      assertSent(server, \"GET\", \"/projects/party/regions/us-central1/addresses/test-ip1\");\n   }\n\n   public void insert() throws Exception {\n      server.enqueue(jsonResponse(\"/region_operation.json\"));\n\n      assertEquals(addressApi().create(\"test-ip1\"),\n            new ParseRegionOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"POST\", \"/projects/party/regions/us-central1/addresses\",\n            stringFromResource(\"/address_insert.json\"));\n   }\n\n   public void insert_options() throws Exception {\n      server.enqueue(jsonResponse(\"/region_operation.json\"));\n\n      AddressCreationOptions options = new AddressCreationOptions.Builder(\"address-with-options\")\n         .description(\"This is a test\").address(\"1.1.1.1\").build();\n      assertEquals(addressApi().create(options),\n            new ParseRegionOperationTest().expected(url(\"/projects\")));\n\n      assertSent(server, \"POST\", \"/projects/party/regions/us-central1/addresses\",\n            \"{\\\"name\\\": \\\"address-with-options\\\",\\\"description\\\":\\\"This is a test\\\",\\\"address\\\":\\\"1.1.1.1\\\"}\");\n   }\n\n   public void delete() throws Exception {\n      server.enqueue(jsonResponse(\"/region_operation.json\"));\n\n      assertEquals(addressApi().delete(\"test-ip1\"),\n            new ParseRegionOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"DELETE\", \"/projects/party/regions/us-central1/addresses/test-ip1\");\n   }\n\n   public void delete_4xx() throws Exception {\n      server.enqueue(response404());\n\n      assertNull(addressApi().delete(\"test-ip1\"));\n      assertSent(server, \"DELETE\", \"/projects/party/regions/us-central1/addresses/test-ip1\");\n   }\n\n   public void list() throws Exception {\n      server.enqueue(jsonResponse(\"/address_list.json\"));\n\n      assertEquals(addressApi().list().next(), new ParseAddressListTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/projects/party/regions/us-central1/addresses\");\n   }\n\n   public void list_empty() throws Exception {\n      server.enqueue(jsonResponse(\"/list_empty.json\"));\n\n      assertFalse(addressApi().list().hasNext());\n      assertSent(server, \"GET\", \"/projects/party/regions/us-central1/addresses\");\n   }\n\n   AddressApi addressApi(){\n      return api().addressesInRegion(\"us-central1\");\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/AggregatedListApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.jclouds.googlecomputeengine.options.ListOptions.Builder.maxResults;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Iterator;\nimport java.util.List;\n\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.domain.Address;\nimport org.jclouds.googlecomputeengine.domain.Disk;\nimport org.jclouds.googlecomputeengine.domain.DiskType;\nimport org.jclouds.googlecomputeengine.domain.ForwardingRule;\nimport org.jclouds.googlecomputeengine.domain.MachineType;\nimport org.jclouds.googlecomputeengine.domain.Operation;\nimport org.jclouds.googlecomputeengine.domain.TargetInstance;\nimport org.jclouds.googlecomputeengine.domain.TargetPool;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiLiveTest;\nimport org.testng.SkipException;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"AggregatedListApiLiveTest\")\npublic class AggregatedListApiLiveTest extends BaseGoogleComputeEngineApiLiveTest {\n\n   public static final String DISK_NAME = \"aggregated-list-api-live-test-disk\";\n   public static final int sizeGb = 1;\n\n   private AggregatedListApi api() {\n      return api.aggregatedList();\n   }\n\n   public void machineTypes() {\n      Iterator<ListPage<MachineType>> pageIterator = api().machineTypes(maxResults(1));\n      assertTrue(pageIterator.hasNext());\n\n      List<MachineType> machineTypeAsList = pageIterator.next();\n\n      assertEquals(machineTypeAsList.size(), 1);\n   }\n\n   public void addresses() {\n      Iterator<ListPage<Address>> pageIterator = api().addresses(maxResults(1));\n      // make sure that in spite of having only one result per page we get at\n      // least two results\n      int count = 0;\n      for (; count < 2 && pageIterator.hasNext();) {\n         ListPage<Address> result = pageIterator.next();\n         if (!result.isEmpty()) {\n            count++;\n         }\n      }\n      if (count < 2) {\n         throw new SkipException(\"Not enough addresses\");\n      }\n      assertEquals(count, 2);\n   }\n\n   public void disks() {\n      Iterator<ListPage<Disk>> pageIterator = api().disks(maxResults(1));\n      // make sure that in spite of having only one result per page we get at\n      // least two results\n      int count = 0;\n      for (; count < 2 && pageIterator.hasNext();) {\n         ListPage<Disk> result = pageIterator.next();\n         if (!result.isEmpty()) {\n            count++;\n         }\n      }\n      if (count < 2) {\n         throw new SkipException(\"Not enough disks\");\n      }\n      assertEquals(count, 2);\n   }\n\n   public void diskTypes() {\n      Iterator<ListPage<DiskType>> pageIterator = api().diskTypes(maxResults(1));\n      assertTrue(pageIterator.hasNext());\n\n      List<DiskType> diskTypeAsList = pageIterator.next();\n\n      assertEquals(diskTypeAsList.size(), 1);\n   }\n\n   public void globalOperations() {\n      Iterator<ListPage<Operation>> pageIterator = api().globalOperations(maxResults(1));\n      // make sure that in spite of having only one result per page we get at\n      // least two results\n      int count = 0;\n      for (; count < 2 && pageIterator.hasNext();) {\n         ListPage<Operation> result = pageIterator.next();\n         if (!result.isEmpty()) {\n            count++;\n         }\n      }\n      if (count < 2) {\n         throw new SkipException(\"Not enough global operations\");\n      }\n      assertEquals(count, 2);\n   }\n\n   public void forwardingRules() {\n      Iterator<ListPage<ForwardingRule>> pageIterator = api().forwardingRules(maxResults(1));\n      // make sure that in spite of having only one result per page we get at\n      // least two results\n      int count = 0;\n      for (; count < 2 && pageIterator.hasNext();) {\n         ListPage<ForwardingRule> result = pageIterator.next();\n         if (!result.isEmpty()) {\n            count++;\n         }\n      }\n      if (count < 2) {\n         throw new SkipException(\"Not enough forwarding rules\");\n      }\n      assertEquals(count, 2);\n   }\n\n   public void targetInstances() {\n      Iterator<ListPage<TargetInstance>> pageIterator = api().targetInstances(maxResults(1));\n      // make sure that in spite of having only one result per page we get at\n      // least two results\n      int count = 0;\n      for (; count < 2 && pageIterator.hasNext();) {\n         ListPage<TargetInstance> result = pageIterator.next();\n         if (!result.isEmpty()) {\n            count++;\n         }\n      }\n      if (count < 2) {\n         throw new SkipException(\"Not enough target instances\");\n      }\n      assertEquals(count, 2);\n   }\n\n   public void targetPools() {\n      Iterator<ListPage<TargetPool>> pageIterator = api().targetPools(maxResults(1));\n      // make sure that in spite of having only one result per page we get at\n      // least two results\n      int count = 0;\n      for (; count < 2 && pageIterator.hasNext();) {\n         ListPage<TargetPool> result = pageIterator.next();\n         if (!result.isEmpty()) {\n            count++;\n         }\n      }\n      if (count < 2) {\n         throw new SkipException(\"Not enough target pools\");\n      }\n      assertEquals(count, 2);\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/AggregatedListApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiMockTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"AggregatedListApiMockTest\", singleThreaded = true)\npublic class AggregatedListApiMockTest extends BaseGoogleComputeEngineApiMockTest {\n\n   public void machineTypes() throws Exception {\n      server.enqueue(jsonResponse(\"/aggregated_machinetype_list.json\"));\n\n      AggregatedListApi aggregatedList = api().aggregatedList();\n\n      assertTrue(aggregatedList.machineTypes().hasNext());\n\n      assertSent(server, \"GET\", \"/projects/party/aggregated/machineTypes\");\n   }\n\n   public void machineTypes_4xx() throws Exception {\n      server.enqueue(jsonResponse(\"/aggregated_instance_list_empty.json\"));\n\n      AggregatedListApi aggregatedList = api().aggregatedList();\n\n      assertFalse(aggregatedList.machineTypes().hasNext());\n\n      assertSent(server, \"GET\", \"/projects/party/aggregated/machineTypes\");\n   }\n\n   public void instances() throws Exception {\n      server.enqueue(jsonResponse(\"/aggregated_instance_list.json\"));\n\n      AggregatedListApi aggregatedList = api().aggregatedList();\n\n      assertTrue(aggregatedList.instances().hasNext());\n\n      assertSent(server, \"GET\", \"/projects/party/aggregated/instances\");\n   }\n\n   public void instances_4xx() throws Exception {\n      server.enqueue(jsonResponse(\"/aggregated_instance_list_empty.json\"));\n\n      AggregatedListApi aggregatedList = api().aggregatedList();\n\n      assertFalse(aggregatedList.instances().hasNext());\n\n      assertSent(server, \"GET\", \"/projects/party/aggregated/instances\");\n   }\n\n   public void addresses() throws Exception {\n      server.enqueue(jsonResponse(\"/aggregated_address_list.json\"));\n\n      AggregatedListApi aggregatedList = api().aggregatedList();\n\n      assertTrue(aggregatedList.addresses().hasNext());\n\n      assertSent(server, \"GET\", \"/projects/party/aggregated/addresses\");\n   }\n\n   public void addresses_4xx() throws Exception {\n      server.enqueue(jsonResponse(\"/aggregated_address_list_empty.json\"));\n\n      AggregatedListApi aggregatedList = api().aggregatedList();\n\n      assertFalse(aggregatedList.addresses().hasNext());\n\n      assertSent(server, \"GET\", \"/projects/party/aggregated/addresses\");\n   }\n\n   public void disks() throws Exception {\n      server.enqueue(jsonResponse(\"/aggregated_disk_list.json\"));\n\n      AggregatedListApi aggregatedList = api().aggregatedList();\n\n      assertTrue(aggregatedList.disks().hasNext());\n\n      assertSent(server, \"GET\", \"/projects/party/aggregated/disks\");\n   }\n\n   public void disks_4xx() throws Exception {\n      server.enqueue(jsonResponse(\"/aggregated_disk_list_empty.json\"));\n\n      AggregatedListApi aggregatedList = api().aggregatedList();\n\n      assertFalse(aggregatedList.disks().hasNext());\n\n      assertSent(server, \"GET\", \"/projects/party/aggregated/disks\");\n   }\n\n   public void diskTypes() throws Exception {\n      server.enqueue(jsonResponse(\"/aggregated_disktype_list.json\"));\n\n      AggregatedListApi aggregatedList = api().aggregatedList();\n\n      assertTrue(aggregatedList.diskTypes().hasNext());\n\n      assertSent(server, \"GET\", \"/projects/party/aggregated/diskTypes\");\n   }\n\n   public void diskTypes_4xx() throws Exception {\n      server.enqueue(jsonResponse(\"/aggregated_disktype_list_empty.json\"));\n\n      AggregatedListApi aggregatedList = api().aggregatedList();\n\n      assertFalse(aggregatedList.diskTypes().hasNext());\n\n      assertSent(server, \"GET\", \"/projects/party/aggregated/diskTypes\");\n   }\n\n   public void globalOperations() throws Exception {\n      server.enqueue(jsonResponse(\"/aggregated_global_operation_list.json\"));\n\n      AggregatedListApi aggregatedList = api().aggregatedList();\n\n      assertTrue(aggregatedList.globalOperations().hasNext());\n\n      assertSent(server, \"GET\", \"/projects/party/aggregated/operations\");\n   }\n\n   public void globalOperations_4xx() throws Exception {\n      server.enqueue(jsonResponse(\"/aggregated_global_operation_list_empty.json\"));\n\n      AggregatedListApi aggregatedList = api().aggregatedList();\n\n      assertFalse(aggregatedList.globalOperations().hasNext());\n\n      assertSent(server, \"GET\", \"/projects/party/aggregated/operations\");\n   }\n\n   public void forwardingRules() throws Exception {\n      server.enqueue(jsonResponse(\"/aggregated_forwarding_rule_list.json\"));\n\n      AggregatedListApi aggregatedList = api().aggregatedList();\n\n      assertTrue(aggregatedList.forwardingRules().hasNext());\n\n      assertSent(server, \"GET\", \"/projects/party/aggregated/forwardingRules\");\n   }\n\n   public void forwardingRules_4xx() throws Exception {\n      server.enqueue(jsonResponse(\"/aggregated_forwarding_rule_list_empty.json\"));\n\n      AggregatedListApi aggregatedList = api().aggregatedList();\n\n      assertFalse(aggregatedList.forwardingRules().hasNext());\n\n      assertSent(server, \"GET\", \"/projects/party/aggregated/forwardingRules\");\n   }\n\n   public void targetInstances() throws Exception {\n      server.enqueue(jsonResponse(\"/aggregated_target_instance_list.json\"));\n\n      AggregatedListApi aggregatedList = api().aggregatedList();\n\n      assertTrue(aggregatedList.targetInstances().hasNext());\n\n      assertSent(server, \"GET\", \"/projects/party/aggregated/targetInstances\");\n   }\n\n   public void targetInstances_4xx() throws Exception {\n      server.enqueue(jsonResponse(\"/aggregated_target_instance_list_empty.json\"));\n\n      AggregatedListApi aggregatedList = api().aggregatedList();\n\n      assertFalse(aggregatedList.targetInstances().hasNext());\n\n      assertSent(server, \"GET\", \"/projects/party/aggregated/targetInstances\");\n   }\n\n   public void targetPools() throws Exception {\n      server.enqueue(jsonResponse(\"/aggregated_target_pool_list.json\"));\n\n      AggregatedListApi aggregatedList = api().aggregatedList();\n\n      assertTrue(aggregatedList.targetPools().hasNext());\n\n      assertSent(server, \"GET\", \"/projects/party/aggregated/targetPools\");\n   }\n\n   public void targetPools_4xx() throws Exception {\n      server.enqueue(jsonResponse(\"/aggregated_target_pool_list_empty.json\"));\n\n      AggregatedListApi aggregatedList = api().aggregatedList();\n\n      assertFalse(aggregatedList.targetPools().hasNext());\n\n      assertSent(server, \"GET\", \"/projects/party/aggregated/targetPools\");\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/BackendServiceApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static org.jclouds.googlecomputeengine.options.ListOptions.Builder.filter;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.net.URI;\nimport java.util.Iterator;\nimport java.util.List;\n\nimport org.jclouds.googlecomputeengine.domain.BackendService;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiLiveTest;\nimport org.jclouds.googlecomputeengine.options.BackendServiceOptions;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\npublic class BackendServiceApiLiveTest extends BaseGoogleComputeEngineApiLiveTest {\n\n   private static final String BACKEND_SERVICE_NAME = \"backend-service-api-live-test-backend-service\";\n   private static final String BACKEND_SERVICE_HEALTH_CHECK_NAME = \"backend-service-api-live-test-health-check\";\n\n   private BackendServiceApi api() {\n      return api.backendServices();\n   }\n\n   @Test(groups = \"live\")\n   public void testInsertBackendService() {\n      assertOperationDoneSuccessfully(api.httpHeathChecks().insert(BACKEND_SERVICE_HEALTH_CHECK_NAME));\n\n      List<URI> healthChecks = ImmutableList.of(getHealthCheckUrl(BACKEND_SERVICE_HEALTH_CHECK_NAME));\n\n      BackendServiceOptions b = new BackendServiceOptions.Builder(BACKEND_SERVICE_NAME, healthChecks).build();\n      assertOperationDoneSuccessfully(api().create(b));\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testInsertBackendService\")\n   public void testGetBackendService() {\n      BackendService service = api().get(BACKEND_SERVICE_NAME);\n      assertNotNull(service);\n      assertBackendServiceEquals(service);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testGetBackendService\")\n   public void testPatchBackendService() {\n      String fingerprint = api().get(BACKEND_SERVICE_NAME).fingerprint();\n      BackendServiceOptions backendService = new BackendServiceOptions.Builder(BACKEND_SERVICE_NAME, ImmutableList.of(getHealthCheckUrl(BACKEND_SERVICE_HEALTH_CHECK_NAME)))\n              .timeoutSec(10)\n              .fingerprint(fingerprint)\n              .build();\n\n      assertOperationDoneSuccessfully(api().update(BACKEND_SERVICE_NAME, backendService));\n      assertBackendServiceEquals(api().get(BACKEND_SERVICE_NAME), backendService);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testPatchBackendService\")\n   public void testUpdateBackendService() {\n      String fingerprint = api().get(BACKEND_SERVICE_NAME).fingerprint();\n\n      BackendServiceOptions backendService = new BackendServiceOptions.Builder(BACKEND_SERVICE_NAME, ImmutableList.of(getHealthCheckUrl(BACKEND_SERVICE_HEALTH_CHECK_NAME)))\n              .timeoutSec(45)\n              .port(8080)\n              .fingerprint(fingerprint)\n              .build();\n\n      assertOperationDoneSuccessfully(api().update(BACKEND_SERVICE_NAME, backendService));\n      assertBackendServiceEquals(api().get(BACKEND_SERVICE_NAME),\n                                 backendService);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testUpdateBackendService\")\n   public void testListBackendService() {\n      Iterator<ListPage<BackendService>> backendServices = api().list(filter(\"name eq \" + BACKEND_SERVICE_NAME));\n\n      List<BackendService> backendServicesAsList = backendServices.next();\n\n      assertEquals(backendServicesAsList.size(), 1);\n\n   }\n\n   /*\n   @Test(groups = \"live\", dependsOnMethods = \"testListBackendService\")\n   public void testGetHealthBackendService() {\n      // TODO: Once resourceViews are merged into the project. Test this actually works.\n   }\n    */\n\n   @Test(groups = \"live\", dependsOnMethods = \"testListBackendService\", alwaysRun = true)\n   public void testDeleteBackendService() {\n      assertOperationDoneSuccessfully(api().delete(BACKEND_SERVICE_NAME));\n\n      assertOperationDoneSuccessfully(api.httpHeathChecks().delete(BACKEND_SERVICE_HEALTH_CHECK_NAME));\n\n   }\n\n   private void assertBackendServiceEquals(BackendService result) {\n      assertEquals(result.name(), BACKEND_SERVICE_NAME);\n      assertEquals(getOnlyElement(result.healthChecks()),\n                   getHealthCheckUrl(BACKEND_SERVICE_HEALTH_CHECK_NAME));\n   }\n\n   private void assertBackendServiceEquals(BackendService result, BackendServiceOptions expected) {\n      assertEquals(result.name(), expected.name());\n      assertEquals(result.healthChecks(), expected.healthChecks());\n      if (expected.timeoutSec() != null) {\n         org.testng.Assert.assertEquals(result.timeoutSec(), expected.timeoutSec().intValue());\n      }\n      if (expected.port() != null) {\n         org.testng.Assert.assertEquals(result.port(), expected.port().intValue());\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/BackendServiceApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.AssertJUnit.assertNull;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiMockTest;\nimport org.jclouds.googlecomputeengine.options.BackendServiceOptions;\nimport org.jclouds.googlecomputeengine.parse.ParseHealthStatusTest;\nimport org.jclouds.googlecomputeengine.parse.ParseBackendServiceListTest;\nimport org.jclouds.googlecomputeengine.parse.ParseBackendServiceTest;\nimport org.jclouds.googlecomputeengine.parse.ParseOperationTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"BackendServiceApiMockTest\", singleThreaded = true)\npublic class BackendServiceApiMockTest extends BaseGoogleComputeEngineApiMockTest {\n\n   public void get() throws Exception {\n      server.enqueue(jsonResponse(\"/backend_service_get.json\"));\n\n      assertEquals(backendServiceApi().get(\"jclouds-test\"),\n            new ParseBackendServiceTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/projects/party/global/backendServices/jclouds-test\");\n   }\n\n   public void get_4xx() throws Exception {\n      server.enqueue(response404());\n\n      assertNull(backendServiceApi().get(\"jclouds-test\"));\n      assertSent(server, \"GET\", \"/projects/party/global/backendServices/jclouds-test\");\n   }\n\n   public void insert() throws Exception {\n      server.enqueue(jsonResponse(\"/operation.json\"));\n\n      List<URI> healthChecks = ImmutableList.of(URI.create(url(\"/projects/\"\n            + \"myproject/global/httpHealthChecks/jclouds-test\")));\n\n      assertEquals(backendServiceApi().create( new BackendServiceOptions.Builder(\"jclouds-test\", healthChecks)\n            .protocol(\"HTTP\")\n            .port(80)\n            .timeoutSec(30)\n            .build()),\n            new ParseOperationTest().expected(url(\"/projects\")));\n\n      assertSent(server, \"POST\", \"/projects/party/global/backendServices\",\n            stringFromResource(\"/backend_service_insert.json\"));\n   }\n\n   public void update() throws Exception {\n      server.enqueue(jsonResponse(\"/operation.json\"));\n\n      List<URI> healthChecks = ImmutableList.of(URI.create(url(\"/projects/\"\n            + \"myproject/global/httpHealthChecks/jclouds-test\")));\n\n      assertEquals(backendServiceApi().update(\"jclouds-test\",\n            new BackendServiceOptions.Builder(\"jclouds-test\", healthChecks)\n               .protocol(\"HTTP\")\n               .port(80)\n               .timeoutSec(30)\n               .build()),\n            new ParseOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"PUT\", \"/projects/party/global/backendServices/jclouds-test\",\n            stringFromResource(\"/backend_service_insert.json\"));\n   }\n\n   public void patch() throws Exception {\n      server.enqueue(jsonResponse(\"/operation.json\"));\n\n      List<URI> healthChecks = ImmutableList.of(URI.create(url(\"/projects/\"\n            + \"myproject/global/httpHealthChecks/jclouds-test\")));\n\n      assertEquals(backendServiceApi().patch(\"jclouds-test\",\n            new BackendServiceOptions.Builder(\"jclouds-test\", healthChecks)\n               .protocol(\"HTTP\")\n               .port(80)\n               .timeoutSec(30)\n               .build()),\n            new ParseOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"PATCH\", \"/projects/party/global/backendServices/jclouds-test\",\n            stringFromResource(\"/backend_service_insert.json\"));\n   }\n\n   public void delete() throws Exception {\n      server.enqueue(jsonResponse(\"/operation.json\"));\n\n      assertEquals(backendServiceApi().delete(\"jclouds-test\"),\n            new ParseOperationTest().expected(url(\"/projects\")));\n\n      assertSent(server, \"DELETE\", \"/projects/party/global/backendServices/jclouds-test\");\n   }\n\n   public void delete_4xx() throws Exception {\n      server.enqueue(response404());\n\n      assertNull(backendServiceApi().delete(\"jclouds-test\"));\n\n      assertSent(server, \"DELETE\", \"/projects/party/global/backendServices/jclouds-test\");\n   }\n\n   public void list() throws Exception {\n      server.enqueue(jsonResponse(\"/backend_service_list.json\"));\n\n      assertEquals(backendServiceApi().list().next(), new ParseBackendServiceListTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/projects/party/global/backendServices\");\n   }\n\n   public void list_empty() throws Exception {\n      server.enqueue(jsonResponse(\"/list_empty.json\"));\n\n      assertFalse(backendServiceApi().list().hasNext());\n      assertSent(server, \"GET\", \"/projects/party/global/backendServices\");\n   }\n\n   public void getHealth() throws Exception {\n      server.enqueue(jsonResponse(\"/health_status_get_health.json\"));\n\n      URI group = URI.create(\"https://www.googleapis.com/resourceviews/v1beta1/\"\n            + \"projects/myproject/zones/us-central1-a/\"\n            + \"resourceViews/jclouds-test\");\n      assertEquals(backendServiceApi().getHealth(\"jclouds-test\", group),\n            new ParseHealthStatusTest().expected(url(\"/projects\")));\n\n      assertSent(server, \"POST\", \"/projects/party/global/backendServices/jclouds-test/getHealth\",\n            stringFromResource(\"/backend_service_get_health_request.json\"));\n   }\n\n   public BackendServiceApi backendServiceApi(){\n      return api().backendServices();\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/DiskApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.jclouds.googlecomputeengine.options.ListOptions.Builder.filter;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.net.URI;\nimport java.util.Iterator;\nimport java.util.List;\n\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.domain.Disk;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiLiveTest;\nimport org.jclouds.googlecomputeengine.options.DiskCreationOptions;\nimport org.testng.annotations.Test;\n\npublic class DiskApiLiveTest extends BaseGoogleComputeEngineApiLiveTest {\n\n   public static final String DISK_NAME = \"disk-api-live-test-disk\";\n   public static final String SSD_DISK_NAME = \"disk-api-live-test-disk-ssd\";\n   public static final int SIZE_GB = 1;\n\n   private DiskApi api() {\n      return api.disksInZone(DEFAULT_ZONE_NAME);\n   }\n\n   @Test(groups = \"live\")\n   public void testInsertDisk() {\n      DiskCreationOptions options = new DiskCreationOptions.Builder().sizeGb( SIZE_GB).build();\n      assertOperationDoneSuccessfully(api().create(DISK_NAME, options));\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testInsertDisk\")\n   public void testGetDisk() {\n      Disk disk = api().get(DISK_NAME);\n      assertNotNull(disk);\n      assertDiskEquals(disk);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testGetDisk\")\n   public void testListDisk() {\n      Iterator<ListPage<Disk>> disks = api().list(filter(\"name eq \" + DISK_NAME));\n\n      List<Disk> disksAsList = disks.next();\n\n      assertEquals(disksAsList.size(), 1);\n\n      assertDiskEquals(disksAsList.get(0));\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testListDisk\", alwaysRun = true)\n   public void testDeleteDisk() {\n      assertOperationDoneSuccessfully(api().delete(DISK_NAME));\n   }\n\n   private void assertDiskEquals(Disk result) {\n      assertEquals(result.name(), DISK_NAME);\n      assertEquals(result.sizeGb(), SIZE_GB);\n      assertEquals(result.zone(), getDefaultZoneUrl());\n   }\n\n   @Test(groups = \"live\")\n   public void testInsertSSDDisk() {\n      URI diskType = getDiskTypeUrl(DEFAULT_ZONE_NAME, \"pd-ssd\");\n      DiskCreationOptions diskCreationOptions = new DiskCreationOptions.Builder().type(diskType).sizeGb(SIZE_GB).build();\n      assertOperationDoneSuccessfully(api().create(SSD_DISK_NAME, diskCreationOptions));\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testInsertSSDDisk\")\n   public void testGetSSDDisk() {\n      Disk disk = api().get(SSD_DISK_NAME);\n      assertNotNull(disk);\n      assertSSDDiskEquals(disk);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testGetSSDDisk\")\n   public void testDeleteSSDDisk() {\n      assertOperationDoneSuccessfully(api().delete(SSD_DISK_NAME));\n   }\n\n   private void assertSSDDiskEquals(Disk result) {\n      assertEquals(result.name(), SSD_DISK_NAME);\n      assertEquals(result.sizeGb(), SIZE_GB);\n      assertEquals(result.zone(), getDefaultZoneUrl());\n      assertEquals(result.type(), getDiskTypeUrl(DEFAULT_ZONE_NAME, \"pd-ssd\"));\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/DiskApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.AssertJUnit.assertNull;\n\nimport java.net.URI;\n\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiMockTest;\nimport org.jclouds.googlecomputeengine.options.DiskCreationOptions;\nimport org.jclouds.googlecomputeengine.parse.ParseDiskListTest;\nimport org.jclouds.googlecomputeengine.parse.ParseDiskTest;\nimport org.jclouds.googlecomputeengine.parse.ParseZoneOperationTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"DiskApiMockTest\", singleThreaded = true)\npublic class DiskApiMockTest extends BaseGoogleComputeEngineApiMockTest {\n\n   public static final String IMAGE_URL = \"/projects/party/zones/us-central1-a/images/foo\";\n   public static final String SSD_URL =  \"/projects/party/zones/us-central1-a/diskTypes/pd-ssd\";\n\n   public void get() throws Exception {\n      server.enqueue(jsonResponse(\"/disk_get.json\"));\n\n      assertEquals(diskApi().get(\"testimage1\"), new ParseDiskTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/disks/testimage1\");\n   }\n\n   public void get_4xx() throws Exception {\n      server.enqueue(response404());\n\n      assertNull(diskApi().get(\"testimage1\"));\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/disks/testimage1\");\n   }\n\n   public void insert() throws Exception {\n      server.enqueue(jsonResponse(\"/zone_operation.json\"));\n\n      DiskCreationOptions options = new DiskCreationOptions.Builder().sizeGb(1).build();\n      assertEquals(diskApi().create(\"testimage1\", options),\n            new ParseZoneOperationTest().expected(url(\"/projects\")));\n\n      assertSent(server, \"POST\", \"/projects/party/zones/us-central1-a/disks\",\n            stringFromResource(\"/disk_insert.json\"));\n   }\n\n   public void insertFromImage() throws Exception {\n      server.enqueue(jsonResponse(\"/zone_operation.json\"));\n\n      DiskCreationOptions diskCreationOptions = new DiskCreationOptions.Builder().sizeGb(1).description(\"testing 123\").build();\n\n      assertEquals(diskApi().create(\"testimage1\", url(IMAGE_URL), diskCreationOptions),\n            new ParseZoneOperationTest().expected(url(\"/projects\")));\n\n      assertSent(server, \"POST\", \"/projects/party/zones/us-central1-a/disks?sourceImage=\"\n            + url(\"/projects/party/zones/us-central1-a/images/foo\").replace(\":\", \"%3A\"), //TODO (broudy) clean this up.\n            \"{\\\"name\\\":\\\"testimage1\\\",\\\"sizeGb\\\":1,\\\"description\\\":\\\"testing 123\\\"}\");\n   }\n\n   public void insertFromSSD() throws Exception {\n      server.enqueue(jsonResponse(\"/zone_operation.json\"));\n\n      DiskCreationOptions diskCreationOptions = new DiskCreationOptions.Builder()\n         .type(URI.create(url(SSD_URL))).sizeGb(1).build();\n\n      assertEquals(diskApi().create(\"testimage1\", diskCreationOptions),\n            new ParseZoneOperationTest().expected(url(\"/projects\")));\n\n      assertSent(server, \"POST\", \"/projects/party/zones/us-central1-a/disks\",\n            stringFromResource(\"/disk_insert_ssd.json\"));\n   }\n\n   public void creatSnapshot() throws Exception {\n      server.enqueue(jsonResponse(\"/zone_operation.json\"));\n\n      assertEquals(diskApi().createSnapshot(\"testimage1\", \"test-snap\"),\n            new ParseZoneOperationTest().expected(url(\"/projects\")));\n\n      assertSent(server, \"POST\", \"/projects/party/zones/us-central1-a/disks/testimage1/createSnapshot\",\n            stringFromResource(\"/disk_create_snapshot.json\"));\n   }\n\n   public void creatSnapshot_description() throws Exception {\n      server.enqueue(jsonResponse(\"/zone_operation.json\"));\n\n      assertEquals(diskApi().createSnapshot(\"testimage1\", \"test-snap\", \"This is a test\"),\n            new ParseZoneOperationTest().expected(url(\"/projects\")));\n\n      assertSent(server, \"POST\", \"/projects/party/zones/us-central1-a/disks/testimage1/createSnapshot\",\n            \"{\\\"name\\\":\\\"test-snap\\\",\\\"description\\\":\\\"This is a test\\\"}\");\n   }\n\n   public void delete() throws Exception {\n      server.enqueue(jsonResponse(\"/zone_operation.json\"));\n\n      assertEquals(diskApi().delete(\"testimage1\"),\n            new ParseZoneOperationTest().expected(url(\"/projects\")));\n\n      assertSent(server, \"DELETE\", \"/projects/party/zones/us-central1-a/disks/testimage1\");\n   }\n\n   public void delete_4xx() throws Exception {\n      server.enqueue(response404());\n\n      assertNull(diskApi().delete(\"testimage1\"));\n      assertSent(server, \"DELETE\", \"/projects/party/zones/us-central1-a/disks/testimage1\");\n   }\n\n   public void list() throws Exception {\n      server.enqueue(jsonResponse(\"/disk_list.json\"));\n\n      assertEquals(diskApi().list().next(), new ParseDiskListTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/disks\");\n   }\n\n   public void list_empty() throws Exception {\n      server.enqueue(jsonResponse(\"/list_empty.json\"));\n\n      assertFalse(diskApi().list().hasNext());\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/disks\");\n   }\n\n   public DiskApi diskApi(){\n      return api().disksInZone(\"us-central1-a\");\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/DiskTypeApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.jclouds.googlecomputeengine.options.ListOptions.Builder.maxResults;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Iterator;\n\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.domain.DiskType;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiLiveTest;\nimport org.testng.annotations.Test;\n\npublic class DiskTypeApiLiveTest extends BaseGoogleComputeEngineApiLiveTest {\n\n   private DiskType diskType;\n\n   private DiskTypeApi api() {\n      return api.diskTypesInZone(DEFAULT_ZONE_NAME);\n   }\n\n   @Test(groups = \"live\")\n   public void testDiskType() {\n\n      Iterator<ListPage<DiskType>> pageIterator = api().list(maxResults(1));\n      assertTrue(pageIterator.hasNext());\n\n      ListPage<DiskType> page = pageIterator.next();\n\n      assertEquals(page.size(), 1);\n\n      this.diskType = page.get(0);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testDiskType\")\n   public void testGetDiskType() {\n      DiskType diskType = api().get(this.diskType.name());\n      assertNotNull(diskType);\n      assertDiskTypeEquals(diskType, this.diskType);\n   }\n\n   private void assertDiskTypeEquals(DiskType result, DiskType expected) {\n      assertEquals(result.name(), expected.name());\n      assertEquals(result.validDiskSize(), expected.validDiskSize());\n      assertEquals(result.zone(), expected.zone());\n      assertEquals(result.defaultDiskSizeGb(), expected.defaultDiskSizeGb());\n      assertEquals(result.selfLink(), expected.selfLink());\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/DiskTypeApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNull;\n\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiMockTest;\nimport org.jclouds.googlecomputeengine.parse.ParseDiskTypeListTest;\nimport org.jclouds.googlecomputeengine.parse.ParseDiskTypeTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"DiskTypeApiMockTest\", singleThreaded = true)\npublic class DiskTypeApiMockTest extends BaseGoogleComputeEngineApiMockTest {\n\n   public void get() throws Exception {\n      server.enqueue(jsonResponse(\"/disktype.json\"));\n\n      assertEquals(diskTypeApi().get(\"pd-standard\"),\n            new ParseDiskTypeTest().expected());\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/diskTypes/pd-standard\");\n   }\n\n   public void get_4xx() throws Exception {\n      server.enqueue(response404());\n\n      assertNull(diskTypeApi().get(\"pd-standard\"));\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/diskTypes/pd-standard\");\n   }\n\n   public void list() throws Exception {\n      server.enqueue(jsonResponse(\"/disktype_list.json\"));\n\n      assertEquals(diskTypeApi().list().next(), new ParseDiskTypeListTest().expected());\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/diskTypes\");\n   }\n\n   public void list_empty() throws Exception {\n      server.enqueue(jsonResponse(\"/list_empty.json\"));\n\n      assertFalse(diskTypeApi().list().hasNext());\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/diskTypes\");\n   }\n\n   public DiskTypeApi diskTypeApi() {\n      return api().diskTypesInZone(\"us-central1-a\");\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/FirewallApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static org.jclouds.googlecomputeengine.options.ListOptions.Builder.filter;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.Iterator;\n\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.domain.Firewall;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiLiveTest;\nimport org.jclouds.googlecomputeengine.options.FirewallOptions;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"live\", testName = \"FirewallApiLiveTest\")\npublic class FirewallApiLiveTest extends BaseGoogleComputeEngineApiLiveTest {\n\n   private static final String FIREWALL_NAME = \"firewall-api-live-test-firewall\";\n   private static final String FIREWALL_NETWORK_NAME = \"firewall-api-live-test-network\";\n   private static final String IPV4_RANGE = \"10.0.0.0/8\";\n\n   private FirewallApi api() {\n      return api.firewalls();\n   }\n\n   @Test(groups = \"live\")\n   public void testInsertFirewall() {\n      // need to insert the network first\n      assertOperationDoneSuccessfully(api.networks().createLegacy(FIREWALL_NETWORK_NAME, IPV4_RANGE));\n\n      FirewallOptions firewall = new FirewallOptions()\n              .addAllowedRule(Firewall.Rule.create(\"tcp\", ImmutableList.of(\"22\")))\n              .addSourceRange(\"10.0.0.0/8\")\n              .addSourceTag(\"tag1\")\n              .addTargetTag(\"tag2\");\n\n      assertOperationDoneSuccessfully(\n            api().createInNetwork(FIREWALL_NAME, getNetworkUrl(FIREWALL_NETWORK_NAME), firewall));\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testInsertFirewall\")\n   public void testUpdateFirewall() {\n      FirewallOptions firewall = new FirewallOptions()\n              .name(FIREWALL_NAME)\n              .network(getNetworkUrl(FIREWALL_NETWORK_NAME))\n              .addSourceRange(\"10.0.0.0/8\")\n              .addSourceTag(\"tag1\")\n              .addTargetTag(\"tag2\")\n              .allowedRules(ImmutableList.of(Firewall.Rule.create(\"tcp\", ImmutableList.of(\"23\"))));\n\n      assertOperationDoneSuccessfully(api().update(FIREWALL_NAME, firewall));\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testUpdateFirewall\")\n   public void testPatchFirewall() {\n      FirewallOptions firewall = new FirewallOptions()\n              .name(FIREWALL_NAME)\n              .network(getNetworkUrl(FIREWALL_NETWORK_NAME))\n              .allowedRules(ImmutableList.of(Firewall.Rule.create(\"tcp\", ImmutableList.of(\"22\")),\n                    Firewall.Rule.create(\"tcp\", ImmutableList.of(\"23\"))))\n              .addSourceRange(\"10.0.0.0/8\")\n              .addSourceTag(\"tag1\")\n              .addTargetTag(\"tag2\");\n\n      assertOperationDoneSuccessfully(api().update(FIREWALL_NAME, firewall));\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testPatchFirewall\")\n   public void testGetFirewall() {\n      FirewallOptions patchedFirewall = new FirewallOptions()\n              .name(FIREWALL_NAME)\n              .network(getNetworkUrl(FIREWALL_NETWORK_NAME))\n              .allowedRules(ImmutableList.of(Firewall.Rule.create(\"tcp\", ImmutableList.of(\"22\")),\n                    Firewall.Rule.create(\"tcp\", ImmutableList.of(\"23\"))))\n              .addSourceRange(\"10.0.0.0/8\")\n              .addSourceTag(\"tag1\")\n              .addTargetTag(\"tag2\");\n\n      Firewall firewall = api().get(FIREWALL_NAME);\n      assertNotNull(firewall);\n      assertFirewallEquals(firewall, patchedFirewall);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testGetFirewall\")\n   public void testListFirewall() {\n      Iterator<ListPage<Firewall>> firewalls = api().list(filter(\"name eq \" + FIREWALL_NAME));\n\n      assertEquals(firewalls.next().size(), 1);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testListFirewall\", alwaysRun = true)\n   public void testDeleteFirewall() {\n      assertOperationDoneSuccessfully(api().delete(FIREWALL_NAME));\n      assertOperationDoneSuccessfully(api.networks().delete(FIREWALL_NETWORK_NAME));\n   }\n\n   private void assertFirewallEquals(Firewall result, FirewallOptions expected) {\n      assertEquals(result.name(), expected.name());\n      assertEquals(getOnlyElement(result.sourceRanges()), getOnlyElement(expected.sourceRanges()));\n      assertEquals(getOnlyElement(result.sourceTags()), getOnlyElement(expected.sourceTags()));\n      assertEquals(getOnlyElement(result.targetTags()), getOnlyElement(expected.targetTags()));\n      assertEquals(result.allowed(), expected.getAllowed());\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/FirewallApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.AssertJUnit.assertNull;\n\nimport java.net.URI;\n\nimport org.jclouds.googlecomputeengine.domain.Firewall;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiMockTest;\nimport org.jclouds.googlecomputeengine.options.FirewallOptions;\nimport org.jclouds.googlecomputeengine.parse.ParseFirewallListTest;\nimport org.jclouds.googlecomputeengine.parse.ParseFirewallTest;\nimport org.jclouds.googlecomputeengine.parse.ParseOperationTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"FirewallApiMockTest\", singleThreaded = true)\npublic class FirewallApiMockTest extends BaseGoogleComputeEngineApiMockTest {\n\n   public void get() throws Exception {\n      server.enqueue(jsonResponse(\"/firewall_get.json\"));\n\n      assertEquals(firewallApi().get(\"jclouds-test\"),\n            new ParseFirewallTest().expected(url(\"/projects\")));\n\n      assertSent(server, \"GET\", \"/projects/party/global/firewalls/jclouds-test\");\n   }\n\n   public void get_4xx() throws Exception {\n      server.enqueue(response404());\n\n      assertNull(firewallApi().get(\"jclouds-test\"));\n\n      assertSent(server, \"GET\", \"/projects/party/global/firewalls/jclouds-test\");\n   }\n\n   public void delete() throws Exception {\n      server.enqueue(jsonResponse(\"/operation.json\"));\n\n      assertEquals(firewallApi().delete(\"default-allow-internal\"),\n            new ParseOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"DELETE\", \"/projects/party/global/firewalls/default-allow-internal\");\n   }\n\n   public void delete_4xx() throws Exception {\n      server.enqueue(response404());\n\n      assertNull(firewallApi().delete(\"default-allow-internal\"));\n      assertSent(server, \"DELETE\", \"/projects/party/global/firewalls/default-allow-internal\");\n   }\n\n   public void list() throws Exception {\n      server.enqueue(jsonResponse(\"/firewall_list.json\"));\n\n      assertEquals(firewallApi().list().next(), new ParseFirewallListTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/projects/party/global/firewalls\");\n   }\n\n   public void list_empty() throws Exception {\n      server.enqueue(jsonResponse(\"/list_empty.json\"));\n\n      assertFalse(firewallApi().list().hasNext());\n      assertSent(server, \"GET\", \"/projects/party/global/firewalls\");\n   }\n\n   public void insert() throws Exception {\n      server.enqueue(jsonResponse(\"/operation.json\"));\n\n      FirewallOptions options = new FirewallOptions()\n         .addAllowedRule(Firewall.Rule.create(\"tcp\", ImmutableList.of(\"22\", \"23-24\")))\n         .addSourceTag(\"tag1\")\n         .addSourceRange(\"10.0.1.0/32\")\n         .addTargetTag(\"tag2\");\n\n      assertEquals(firewallApi().createInNetwork(\"myfw\", URI.create(url(\"/projects/party/global/networks/default\")), options),\n            new ParseOperationTest().expected(url(\"/projects\")));\n\n      assertSent(server, \"POST\", \"/projects/party/global/firewalls\",\n            stringFromResource(\"/firewall_insert.json\"));\n   }\n\n   public void update() throws Exception {\n      server.enqueue(jsonResponse(\"/operation.json\"));\n\n      FirewallOptions options = new FirewallOptions()\n         .name(\"myfw\")\n         .network(URI.create(url(\"/projects/party/global/networks/default\")))\n         .addAllowedRule(Firewall.Rule.create(\"tcp\", ImmutableList.of(\"22\", \"23-24\")))\n         .addSourceTag(\"tag1\")\n         .addSourceRange(\"10.0.1.0/32\")\n         .addTargetTag(\"tag2\");\n\n      assertEquals(firewallApi().update(\"myfw\", options),\n            new ParseOperationTest().expected(url(\"/projects\")));\n\n      assertSent(server, \"PUT\", \"/projects/party/global/firewalls/myfw\",\n            stringFromResource(\"/firewall_insert.json\"));\n   }\n\n   public void patch() throws Exception {\n      server.enqueue(jsonResponse(\"/operation.json\"));\n\n      FirewallOptions options = new FirewallOptions()\n         .name(\"myfw\")\n         .network(URI.create(url(\"/projects/party/global/networks/default\")))\n         .addAllowedRule(Firewall.Rule.create(\"tcp\", ImmutableList.of(\"22\", \"23-24\")))\n         .addSourceTag(\"tag1\")\n         .addSourceRange(\"10.0.1.0/32\")\n         .addTargetTag(\"tag2\");\n\n      assertEquals(firewallApi().patch(\"myfw\", options),\n            new ParseOperationTest().expected(url(\"/projects\")));\n\n      assertSent(server, \"PATCH\", \"/projects/party/global/firewalls/myfw\",\n            stringFromResource(\"/firewall_insert.json\"));\n   }\n\n   FirewallApi firewallApi(){\n      return api().firewalls();\n   }\n\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/ForwardingRuleApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.jclouds.googlecomputeengine.options.ListOptions.Builder.filter;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.domain.Address;\nimport org.jclouds.googlecomputeengine.domain.ForwardingRule;\nimport org.jclouds.googlecomputeengine.domain.TargetPool;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiLiveTest;\nimport org.jclouds.googlecomputeengine.options.ForwardingRuleCreationOptions;\nimport org.jclouds.googlecomputeengine.options.TargetPoolCreationOptions;\n\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\npublic class ForwardingRuleApiLiveTest extends BaseGoogleComputeEngineApiLiveTest {\n\n   private static final String FORWARDING_RULE_NAME = \"forwarding-rule-api-live-test\";\n   private static final String TARGETPOOL_NAME = \"forwarding-rule-api-live-test-targetpool\";\n   private static final String TARGETPOOL_NAME_NEW = \"forwarding-rule-api-live-test-new-targetpool\";\n   private static final String DESCRIPTION = \"Forwarding rule api live test forwarding rule.\";\n   private static final String ADDRESS_NAME = \"forwarding-rule-api-address\";\n   private TargetPool targetPool;\n   private TargetPool newTargetPool;\n   private Address address;\n\n   /**\n    * The API under test\n    * @return\n    */\n   private ForwardingRuleApi api() {\n      return api.forwardingRulesInRegion(DEFAULT_REGION_NAME);\n   }\n\n   private TargetPoolApi targetPoolApi() {\n      return api.targetPoolsInRegion(DEFAULT_REGION_NAME);\n   }\n\n   private AddressApi addressApi(){\n      return  api.addressesInRegion(DEFAULT_REGION_NAME);\n   }\n\n   @BeforeClass\n   public void init() {\n      TargetPoolCreationOptions targetPoolCreationOptions = new TargetPoolCreationOptions.Builder(TARGETPOOL_NAME).build();\n      assertOperationDoneSuccessfully(targetPoolApi().create(targetPoolCreationOptions));\n      targetPool = targetPoolApi().get(TARGETPOOL_NAME);\n\n      targetPoolCreationOptions = new TargetPoolCreationOptions.Builder(TARGETPOOL_NAME_NEW).build();\n      assertOperationDoneSuccessfully(targetPoolApi().create(targetPoolCreationOptions));\n      newTargetPool = targetPoolApi().get(TARGETPOOL_NAME_NEW);\n\n      assertOperationDoneSuccessfully(addressApi().create(ADDRESS_NAME));\n      address = addressApi().get(ADDRESS_NAME);\n   }\n\n   @AfterClass(alwaysRun = true)\n   public void tearDown() {\n      assertOperationDoneSuccessfully(targetPoolApi().delete(TARGETPOOL_NAME));\n      assertOperationDoneSuccessfully(targetPoolApi().delete(TARGETPOOL_NAME_NEW));\n      assertOperationDoneSuccessfully(addressApi().delete(ADDRESS_NAME));\n   }\n\n   @Test(groups = \"live\")\n   public void testInsertForwardingRule() {\n      ForwardingRuleCreationOptions forwardingRuleCreationOptions = new ForwardingRuleCreationOptions.Builder()\n                                                                           .description(DESCRIPTION)\n                                                                           .ipAddress(address.address())\n                                                                           .ipProtocol(ForwardingRule.IPProtocol.TCP)\n                                                                           .target(targetPool.selfLink())\n                                                                           .build();\n      assertOperationDoneSuccessfully(api().create(FORWARDING_RULE_NAME, forwardingRuleCreationOptions));\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testInsertForwardingRule\")\n   public void testGetForwardingRule() {\n      ForwardingRule forwardingRule = api().get(FORWARDING_RULE_NAME);\n      assertNotNull(forwardingRule);\n      assertEquals(forwardingRule.name(), FORWARDING_RULE_NAME);\n      assertEquals(forwardingRule.description(), DESCRIPTION);\n      assertEquals(forwardingRule.ipAddress(), address.address());\n      assertEquals(forwardingRule.ipProtocol(), ForwardingRule.IPProtocol.TCP);\n      assertEquals(forwardingRule.target(), targetPool.selfLink());\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testGetForwardingRule\")\n   public void testSetTargetForwardingRule(){\n      assertOperationDoneSuccessfully(api().setTarget(FORWARDING_RULE_NAME, newTargetPool.selfLink()));\n      ForwardingRule forwardingRule = api().get(FORWARDING_RULE_NAME);\n      assertNotNull(forwardingRule);\n      assertEquals(forwardingRule.name(), FORWARDING_RULE_NAME);\n      assertEquals(forwardingRule.target(), newTargetPool.selfLink());\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testInsertForwardingRule\")\n   public void testListForwardingRule() {\n      ListPage<ForwardingRule> forwardingRule = api().list(filter(\"name eq \" + FORWARDING_RULE_NAME)).next();\n      assertEquals(forwardingRule.size(), 1);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = {\"testListForwardingRule\", \"testSetTargetForwardingRule\"}, alwaysRun = true)\n   public void testDeleteForwardingRule() {\n      assertOperationDoneSuccessfully(api().delete(FORWARDING_RULE_NAME));\n   }\n\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/ForwardingRuleApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.AssertJUnit.assertNull;\n\nimport java.net.URI;\n\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiMockTest;\nimport org.jclouds.googlecomputeengine.options.ForwardingRuleCreationOptions;\nimport org.jclouds.googlecomputeengine.parse.ParseForwardingRuleListTest;\nimport org.jclouds.googlecomputeengine.parse.ParseForwardingRuleTest;\nimport org.jclouds.googlecomputeengine.parse.ParseRegionOperationTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ForwardingRuleApiMockTest\", singleThreaded = true)\npublic class ForwardingRuleApiMockTest extends BaseGoogleComputeEngineApiMockTest {\n\n   public void get() throws Exception {\n      server.enqueue(jsonResponse(\"/forwardingrule_get.json\"));\n\n      assertEquals(forwardingRuleApi().get(\"test-forwarding-rule\"),\n            new ParseForwardingRuleTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/projects/party/regions/us-central1/forwardingRules/test-forwarding-rule\");\n   }\n\n   public void get_4xx() throws Exception {\n      server.enqueue(response404());\n\n      assertNull(forwardingRuleApi().get(\"test-forwarding-rule\"));\n      assertSent(server, \"GET\", \"/projects/party/regions/us-central1/forwardingRules/test-forwarding-rule\");\n   }\n\n   public void insert() throws Exception {\n      server.enqueue(jsonResponse(\"/region_operation.json\"));\n\n      ForwardingRuleCreationOptions forwardingRuleCreationOptions = new ForwardingRuleCreationOptions.Builder()\n      .target(URI.create(url(\"/projects/party/regions/europe-west1/targetPools/test-target-pool\"))).build();\n      assertEquals(forwardingRuleApi().create(\"test-forwarding-rule\", forwardingRuleCreationOptions),\n            new ParseRegionOperationTest().expected(url(\"/projects\")));\n\n      assertSent(server, \"POST\", \"/projects/party/regions/us-central1/forwardingRules\",\n            stringFromResource(\"/forwardingrule_insert.json\"));\n   }\n\n   public void delete() throws Exception {\n      server.enqueue(jsonResponse(\"/region_operation.json\"));\n\n      assertEquals(forwardingRuleApi().delete(\"test-forwarding-rule\"),\n            new ParseRegionOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"DELETE\", \"/projects/party/regions/us-central1/forwardingRules/test-forwarding-rule\");\n   }\n\n   public void delete_4xx() throws Exception {\n      server.enqueue(response404());\n\n      assertNull(forwardingRuleApi().delete(\"test-forwarding-rule\"));\n      assertSent(server, \"DELETE\", \"/projects/party/regions/us-central1/forwardingRules/test-forwarding-rule\");\n   }\n\n   public void list() throws Exception {\n      server.enqueue(jsonResponse(\"/forwardingrule_list.json\"));\n\n      assertEquals(forwardingRuleApi().list().next(), new ParseForwardingRuleListTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/projects/party/regions/us-central1/forwardingRules\");\n   }\n\n   public void list_empty() throws Exception {\n      server.enqueue(jsonResponse(\"/list_empty.json\"));\n\n      assertFalse(forwardingRuleApi().list().hasNext());\n      assertSent(server, \"GET\", \"/projects/party/regions/us-central1/forwardingRules\");\n   }\n\n   public void setTarget() throws Exception {\n      server.enqueue(jsonResponse(\"/region_operation.json\"));\n\n      URI newTarget = URI.create(url(\"/projects/party/regions/europe-west1/targetPools/test-target-pool\"));\n      assertEquals(forwardingRuleApi().setTarget(\"testForwardingRule\", newTarget), new ParseRegionOperationTest().expected(url(\"/projects\")));\n\n      assertSent(server, \"POST\", \"/projects/party/regions/us-central1/forwardingRules/testForwardingRule/setTarget\",\n            stringFromResource(\"/forwardingrule_set_target.json\"));\n   }\n\n   public void setTarget_partialUrl() throws Exception {\n      server.enqueue(jsonResponse(\"/region_operation.json\"));\n\n      URI newTarget = URI.create(\"projects/project-id/regions/region/targetPools/target-pool\");\n      assertEquals(forwardingRuleApi().setTarget(\"testForwardingRule\", newTarget), new ParseRegionOperationTest().expected(url(\"/projects\")));\n\n      assertSent(server, \"POST\", \"/projects/party/regions/us-central1/forwardingRules/testForwardingRule/setTarget\",\n            \"{\\\"target\\\":\\\"projects/project-id/regions/region/targetPools/target-pool\\\"}\");\n   }\n\n   ForwardingRuleApi forwardingRuleApi() {\n      return api().forwardingRulesInRegion(\"us-central1\");\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/GlobalForwardingRuleApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.jclouds.googlecomputeengine.options.ListOptions.Builder.filter;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.googlecomputeengine.domain.ForwardingRule;\nimport org.jclouds.googlecomputeengine.domain.ForwardingRule.IPProtocol;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiLiveTest;\nimport org.jclouds.googlecomputeengine.options.ForwardingRuleCreationOptions;\nimport org.jclouds.googlecomputeengine.options.BackendServiceOptions;\nimport org.jclouds.googlecomputeengine.options.UrlMapOptions;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\nimport java.net.URI;\nimport java.util.List;\n\n\n\npublic class GlobalForwardingRuleApiLiveTest extends BaseGoogleComputeEngineApiLiveTest {\n\n   private static final String GLOBAL_FORWARDING_RULE_NAME = \"global-forwarding-rule-api-live-test-forwarding-rule\";\n   private static final String GLOBAL_FORWARDING_RULE_TARGET_HTTP_PROXY_NAME = \"global-\"\n            + \"forwarding-rule-api-live-test-target-http-proxy\";\n   private static final String GLOBAL_FORWARDING_RULE_URL_MAP_NAME = \"global-\"\n            + \"forwarding-rule-api-live-test-url-map\";\n   private static final String GLOBAL_FORWARDING_RULE_BACKEND_SERVICE_NAME = \"global-\"\n            + \"forwarding-rule-api-live-test-backend-service\";\n   private static final String GLOBAL_FORWARDING_RULE_HEALTH_CHECK_NAME = \"global-\"\n            + \"forwarding-rule-api-live-test-health-check\";\n   private static final String PORT_RANGE = \"80\";\n\n   private ForwardingRuleApi api() {\n      return api.globalForwardingRules();\n   }\n\n   @Test(groups = \"live\")\n   public void testInsertGlobalForwardingRule() {\n      assertOperationDoneSuccessfully(api.httpHeathChecks().insert(GLOBAL_FORWARDING_RULE_HEALTH_CHECK_NAME));\n\n      List<URI> healthChecks = ImmutableList.of(getHealthCheckUrl(GLOBAL_FORWARDING_RULE_HEALTH_CHECK_NAME));\n      BackendServiceOptions b = new BackendServiceOptions.Builder(GLOBAL_FORWARDING_RULE_BACKEND_SERVICE_NAME, healthChecks).build();\n      assertOperationDoneSuccessfully(api.backendServices()\n                                              .create(b));\n\n      UrlMapOptions map = new UrlMapOptions.Builder().name(GLOBAL_FORWARDING_RULE_URL_MAP_NAME)\n            .description(\"simple url map\")\n            .defaultService(getBackendServiceUrl(GLOBAL_FORWARDING_RULE_BACKEND_SERVICE_NAME)).build();\n      assertOperationDoneSuccessfully(api.urlMaps().create(map));\n      assertOperationDoneSuccessfully(api.targetHttpProxies().create(GLOBAL_FORWARDING_RULE_TARGET_HTTP_PROXY_NAME,\n            getUrlMapUrl(GLOBAL_FORWARDING_RULE_URL_MAP_NAME)));\n      assertOperationDoneSuccessfully(api().create(\n            GLOBAL_FORWARDING_RULE_NAME,\n            new ForwardingRuleCreationOptions.Builder()\n                  .target(getTargetHttpProxyUrl(GLOBAL_FORWARDING_RULE_TARGET_HTTP_PROXY_NAME))\n                  .description(\"jclodus-test\").portRange(PORT_RANGE).build()));\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testInsertGlobalForwardingRule\")\n   public void testGetGlobalForwardingRule() {\n      ForwardingRule forwardingRule = api().get(GLOBAL_FORWARDING_RULE_NAME);\n      assertNotNull(forwardingRule);\n      ForwardingRuleCreationOptions expected = new ForwardingRuleCreationOptions.Builder()\n            .target(getTargetHttpProxyUrl(GLOBAL_FORWARDING_RULE_TARGET_HTTP_PROXY_NAME))\n            .portRange(\"80-80\")\n            .ipProtocol(IPProtocol.TCP)\n            .description(\"jclodus-test\")\n            .build();\n      assertGlobalForwardingRuleEquals(forwardingRule, expected);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testGetGlobalForwardingRule\")\n   public void testSetGlobalForwardingRuleTarget() {\n      assertOperationDoneSuccessfully(api.targetHttpProxies()\n                                           .create(GLOBAL_FORWARDING_RULE_TARGET_HTTP_PROXY_NAME + \"-2\",\n                                                   getUrlMapUrl(GLOBAL_FORWARDING_RULE_URL_MAP_NAME)));\n      assertOperationDoneSuccessfully(api().setTarget(GLOBAL_FORWARDING_RULE_NAME,\n            getTargetHttpProxyUrl(GLOBAL_FORWARDING_RULE_TARGET_HTTP_PROXY_NAME + \"-2\")));\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testSetGlobalForwardingRuleTarget\")\n   public void testListGlobalForwardingRule() {\n      ListPage<ForwardingRule> forwardingRules = api().list(filter(\"name eq \" + GLOBAL_FORWARDING_RULE_NAME)).next();\n      assertEquals(forwardingRules.size(), 1);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testListGlobalForwardingRule\", alwaysRun = true)\n   public void testDeleteGlobalForwardingRule() {\n      assertOperationDoneSuccessfully(api().delete(GLOBAL_FORWARDING_RULE_NAME));\n\n      // Teardown other created resources\n      assertOperationDoneSuccessfully(api.targetHttpProxies()\n                                              .delete(GLOBAL_FORWARDING_RULE_TARGET_HTTP_PROXY_NAME));\n\n      assertOperationDoneSuccessfully(api.targetHttpProxies()\n                                           .delete(GLOBAL_FORWARDING_RULE_TARGET_HTTP_PROXY_NAME + \"-2\"));\n\n      assertOperationDoneSuccessfully(api.urlMaps()\n                                           .delete(GLOBAL_FORWARDING_RULE_URL_MAP_NAME));\n\n      assertOperationDoneSuccessfully(api.backendServices()\n                                           .delete(GLOBAL_FORWARDING_RULE_BACKEND_SERVICE_NAME));\n\n      assertOperationDoneSuccessfully(api.httpHeathChecks().delete(GLOBAL_FORWARDING_RULE_HEALTH_CHECK_NAME));\n\n   }\n\n   private void assertGlobalForwardingRuleEquals(ForwardingRule result, ForwardingRuleCreationOptions expected) {\n      assertEquals(result.target(), expected.target());\n      assertEquals(result.ipProtocol(), expected.ipProtocol());\n      assertEquals(result.description(), expected.description());\n      assertEquals(result.portRange(), expected.portRange());\n      assertTrue(result.ipAddress() != null);\n   }\n\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/GlobalForwardingRuleApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.AssertJUnit.assertNull;\n\nimport java.net.URI;\n\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiMockTest;\nimport org.jclouds.googlecomputeengine.options.ForwardingRuleCreationOptions;\nimport org.jclouds.googlecomputeengine.parse.ParseForwardingRuleListTest;\nimport org.jclouds.googlecomputeengine.parse.ParseForwardingRuleTest;\nimport org.jclouds.googlecomputeengine.parse.ParseRegionOperationTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"GlobalForwardingRuleApiMockTest\", singleThreaded = true)\npublic class GlobalForwardingRuleApiMockTest extends BaseGoogleComputeEngineApiMockTest {\n\n   public void get() throws Exception {\n      server.enqueue(jsonResponse(\"/forwardingrule_get.json\"));\n\n      assertEquals(globalForwardingRuleApi().get(\"test-forwarding-rule\"),\n            new ParseForwardingRuleTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/projects/party/global/forwardingRules/test-forwarding-rule\");\n   }\n\n   public void get_4xx() throws Exception {\n      server.enqueue(response404());\n\n      assertNull(globalForwardingRuleApi().get(\"test-forwarding-rule\"));\n      assertSent(server, \"GET\", \"/projects/party/global/forwardingRules/test-forwarding-rule\");\n   }\n\n   public void insert() throws Exception {\n      server.enqueue(jsonResponse(\"/region_operation.json\"));\n\n      ForwardingRuleCreationOptions forwardingRuleCreationOptions = new ForwardingRuleCreationOptions.Builder()\n      .target(URI.create(url(\"/projects/party/regions/europe-west1/targetPools/test-target-pool\"))).build();\n\n      assertEquals(globalForwardingRuleApi().create(\"test-forwarding-rule\", forwardingRuleCreationOptions),\n            new ParseRegionOperationTest().expected(url(\"/projects\")));\n\n      assertSent(server, \"POST\", \"/projects/party/global/forwardingRules\",\n            stringFromResource(\"/forwardingrule_insert.json\"));\n   }\n\n   public void delete() throws Exception {\n      server.enqueue(jsonResponse(\"/region_operation.json\"));\n\n      assertEquals(globalForwardingRuleApi().delete(\"test-forwarding-rule\"),\n            new ParseRegionOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"DELETE\", \"/projects/party/global/forwardingRules/test-forwarding-rule\");\n   }\n\n   public void delete_4xx() throws Exception {\n      server.enqueue(response404());\n\n      assertNull(globalForwardingRuleApi().delete(\"test-forwarding-rule\"));\n      assertSent(server, \"DELETE\", \"/projects/party/global/forwardingRules/test-forwarding-rule\");\n   }\n\n   public void list() throws Exception {\n      server.enqueue(jsonResponse(\"/forwardingrule_list.json\"));\n\n      assertEquals(globalForwardingRuleApi().list().next(), new ParseForwardingRuleListTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/projects/party/global/forwardingRules\");\n   }\n\n   public void list_empty() throws Exception {\n      server.enqueue(jsonResponse(\"/list_empty.json\"));\n\n      assertFalse(globalForwardingRuleApi().list().hasNext());\n      assertSent(server, \"GET\", \"/projects/party/global/forwardingRules\");\n   }\n\n   public void setTarget() throws Exception {\n      server.enqueue(jsonResponse(\"/region_operation.json\"));\n\n      URI newTarget = URI.create(url(\"/projects/party/regions/europe-west1/targetPools/test-target-pool\"));\n      assertEquals(globalForwardingRuleApi().setTarget(\"testForwardingRule\", newTarget),\n            new ParseRegionOperationTest().expected(url(\"/projects\")));\n\n      assertSent(server, \"POST\", \"/projects/party/global/forwardingRules/testForwardingRule/setTarget\",\n            stringFromResource(\"/forwardingrule_set_target.json\"));\n   }\n\n   ForwardingRuleApi globalForwardingRuleApi(){\n      return api().globalForwardingRules();\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/HttpHealthCheckApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.jclouds.googlecomputeengine.options.ListOptions.Builder.filter;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.domain.HttpHealthCheck;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiLiveTest;\nimport org.jclouds.googlecomputeengine.options.HttpHealthCheckCreationOptions;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Iterables;\n\npublic class HttpHealthCheckApiLiveTest extends BaseGoogleComputeEngineApiLiveTest {\n\n   private static final String HTTP_HEALTH_CHECK_NAME = \"http-health-check-api-live-test\";\n   private static final Integer OFFSET = 2;\n\n   private HttpHealthCheckCreationOptions options;\n\n   private HttpHealthCheckApi api() {\n      return api.httpHeathChecks();\n   }\n\n   @Test(groups = \"live\")\n   public void testInsertHttpHealthCheck() {\n      options = new HttpHealthCheckCreationOptions.Builder()\n                     .port(56)\n                     .checkIntervalSec(40)\n                     .timeoutSec(40)\n                     .healthyThreshold(5)\n                     .unhealthyThreshold(3)\n                     .description(\"A First Health Check!\")\n                     .buildWithDefaults();\n      assertOperationDoneSuccessfully(api().insert(HTTP_HEALTH_CHECK_NAME, options));\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testInsertHttpHealthCheck\")\n   public void testGetHttpHealthCheck() {\n      HttpHealthCheck httpHealthCheck = api().get(HTTP_HEALTH_CHECK_NAME);\n      assertNotNull(httpHealthCheck);\n      assertEquals(httpHealthCheck.name(), HTTP_HEALTH_CHECK_NAME);\n      assertEquals(httpHealthCheck.port(), options.port());\n      assertEquals(httpHealthCheck.checkIntervalSec(), options.checkIntervalSec());\n      assertEquals(httpHealthCheck.timeoutSec(), options.timeoutSec());\n      assertEquals(httpHealthCheck.healthyThreshold(), options.healthyThreshold());\n      assertEquals(httpHealthCheck.unhealthyThreshold(), options.unhealthyThreshold());\n      assertEquals(httpHealthCheck.description(), options.description());\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testInsertHttpHealthCheck\")\n   public void testListHttpHealthCheck() {\n      ListPage<HttpHealthCheck> httpHealthCheck = api().list(filter(\"name eq \" + HTTP_HEALTH_CHECK_NAME)).next();\n      assertEquals(Iterables.size(httpHealthCheck), 1);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testGetHttpHealthCheck\")\n   public void testPatchHttpHealthCheck() {\n      HttpHealthCheckCreationOptions newOptions = new HttpHealthCheckCreationOptions.Builder()\n         .port(options.port() + OFFSET)\n         .checkIntervalSec(options.checkIntervalSec() + OFFSET)\n         .timeoutSec(options.timeoutSec() + OFFSET)\n         .buildForPatch();\n      assertOperationDoneSuccessfully(api().patch(HTTP_HEALTH_CHECK_NAME, newOptions));\n\n      // Check changes happened and others unchanged.\n      HttpHealthCheck httpHealthCheck = api().get(HTTP_HEALTH_CHECK_NAME);\n      assertNotNull(httpHealthCheck);\n      assertEquals(httpHealthCheck.name(), HTTP_HEALTH_CHECK_NAME);\n      assertEquals(httpHealthCheck.port(), newOptions.port());\n      assertEquals(httpHealthCheck.checkIntervalSec(), newOptions.checkIntervalSec());\n      assertEquals(httpHealthCheck.timeoutSec(), newOptions.timeoutSec());\n      assertEquals(httpHealthCheck.healthyThreshold(), options.healthyThreshold());\n      assertEquals(httpHealthCheck.unhealthyThreshold(), options.unhealthyThreshold());\n      assertEquals(httpHealthCheck.description(), options.description());\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testPatchHttpHealthCheck\")\n   public void testUpdateHttpHealthCheck() {\n      HttpHealthCheckCreationOptions newOptions = new HttpHealthCheckCreationOptions.Builder()\n         .checkIntervalSec(options.checkIntervalSec() - OFFSET)\n         .timeoutSec(options.timeoutSec() - OFFSET)\n         .buildWithDefaults();\n      assertOperationDoneSuccessfully(api().update(HTTP_HEALTH_CHECK_NAME, newOptions));\n\n      // Check changes happened.\n      HttpHealthCheck httpHealthCheck = api().get(HTTP_HEALTH_CHECK_NAME);\n      assertNotNull(httpHealthCheck);\n      assertEquals(httpHealthCheck.name(), HTTP_HEALTH_CHECK_NAME);\n      assertEquals(httpHealthCheck.checkIntervalSec(), newOptions.checkIntervalSec());\n      assertEquals(httpHealthCheck.timeoutSec(), newOptions.timeoutSec());\n      // Update overwrites unspecified parameters to their defaults.\n      assertNotEquals(httpHealthCheck.healthyThreshold(), options.healthyThreshold());\n      assertNotEquals(httpHealthCheck.unhealthyThreshold(), options.unhealthyThreshold());\n      assertNotEquals(httpHealthCheck.description(), options.description());\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = {\"testListHttpHealthCheck\", \"testUpdateHttpHealthCheck\"}, alwaysRun = true)\n   public void testDeleteHttpHealthCheck() {\n      assertOperationDoneSuccessfully(api().delete(HTTP_HEALTH_CHECK_NAME));\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/HttpHealthCheckApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.AssertJUnit.assertNull;\n\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiMockTest;\nimport org.jclouds.googlecomputeengine.options.HttpHealthCheckCreationOptions;\nimport org.jclouds.googlecomputeengine.parse.ParseGlobalOperationTest;\nimport org.jclouds.googlecomputeengine.parse.ParseHttpHealthCheckListTest;\nimport org.jclouds.googlecomputeengine.parse.ParseHttpHealthCheckTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"HttpHealthCheckApiMockTest\", singleThreaded = true)\npublic class HttpHealthCheckApiMockTest extends BaseGoogleComputeEngineApiMockTest {\n\n   public void get() throws Exception{\n      server.enqueue(jsonResponse(\"/httphealthcheck_get.json\"));\n\n      assertEquals(httpHealthCheckApi().get(\"http-health-check-api-live-test\"),\n            new ParseHttpHealthCheckTest().expected(url(\"/projects\")));\n\n      assertSent(server, \"GET\", \"/projects/party/global/httpHealthChecks/http-health-check-api-live-test\");\n   }\n\n   public void get_4xx() throws Exception{\n      server.enqueue(response404());\n\n      assertNull(httpHealthCheckApi().get(\"http-health-check-api-live-test\"));\n      assertSent(server, \"GET\", \"/projects/party/global/httpHealthChecks/http-health-check-api-live-test\");\n   }\n\n   public void insert() throws Exception {\n      server.enqueue(jsonResponse(\"/global_operation.json\"));\n\n      HttpHealthCheckCreationOptions options = new HttpHealthCheckCreationOptions.Builder()\n         .timeoutSec(0).unhealthyThreshold(0).buildWithDefaults();\n      assertEquals(httpHealthCheckApi().insert(\"http-health-check\", options),\n            new ParseGlobalOperationTest().expected(url(\"/projects\")));\n\n      assertSent(server, \"POST\", \"/projects/party/global/httpHealthChecks\",\n            stringFromResource(\"/httphealthcheck_insert.json\"));\n   }\n\n   public void delete() throws Exception {\n      server.enqueue(jsonResponse(\"/global_operation.json\"));\n\n      assertEquals(httpHealthCheckApi().delete(\"http-health-check\"),\n            new ParseGlobalOperationTest().expected(url(\"/projects\")));\n\n      assertSent(server, \"DELETE\", \"/projects/party/global/httpHealthChecks/http-health-check\");\n   }\n\n   public void delete_4xx() throws Exception {\n      server.enqueue(response404());\n\n      assertNull(httpHealthCheckApi().delete(\"http-health-check\"));\n\n      assertSent(server, \"DELETE\", \"/projects/party/global/httpHealthChecks/http-health-check\");\n   }\n\n   public void update() throws Exception {\n      server.enqueue(jsonResponse(\"/global_operation.json\"));\n\n      HttpHealthCheckCreationOptions options = new HttpHealthCheckCreationOptions.Builder()\n         .timeoutSec(0).unhealthyThreshold(0).buildWithDefaults();\n      assertEquals(httpHealthCheckApi().update(\"http-health-check\", options),\n            new ParseGlobalOperationTest().expected(url(\"/projects\")));\n\n      assertSent(server, \"PUT\", \"/projects/party/global/httpHealthChecks/http-health-check\",\n            stringFromResource(\"/httphealthcheck_insert.json\"));\n   }\n\n   public void patch() throws Exception {\n      server.enqueue(jsonResponse(\"/global_operation.json\"));\n\n      HttpHealthCheckCreationOptions options = new HttpHealthCheckCreationOptions.Builder()\n         .timeoutSec(0).unhealthyThreshold(0).buildForPatch();\n      assertEquals(httpHealthCheckApi().patch(\"http-health-check\", options),\n            new ParseGlobalOperationTest().expected(url(\"/projects\")));\n\n      assertSent(server, \"PATCH\", \"/projects/party/global/httpHealthChecks/http-health-check\",\n            stringFromResource(\"/httphealthcheck_patch.json\"));\n   }\n\n   public void list() throws Exception {\n      server.enqueue(jsonResponse(\"/httphealthcheck_list.json\"));\n\n      assertEquals(httpHealthCheckApi().list().next(),\n            new ParseHttpHealthCheckListTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/projects/party/global/httpHealthChecks\");\n   }\n\n   public void list_empty() throws Exception {\n      server.enqueue(jsonResponse(\"/list_empty.json\"));\n\n      assertFalse(httpHealthCheckApi().list().hasNext());\n      assertSent(server, \"GET\", \"/projects/party/global/httpHealthChecks\");\n   }\n\n\n   HttpHealthCheckApi httpHealthCheckApi() {\n      return api().httpHeathChecks();\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/ImageApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.jclouds.googlecomputeengine.options.ListOptions.Builder.maxResults;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\n\nimport java.net.URI;\nimport java.util.Iterator;\nimport java.util.List;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.domain.Disk;\nimport org.jclouds.googlecomputeengine.domain.Image;\nimport org.jclouds.googlecomputeengine.domain.Deprecated.State;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiLiveTest;\nimport org.jclouds.googlecomputeengine.options.DeprecateOptions;\nimport org.jclouds.googlecomputeengine.options.DiskCreationOptions;\nimport org.testng.annotations.Test;\n\npublic class ImageApiLiveTest extends BaseGoogleComputeEngineApiLiveTest {\n\n   public static final String DISK_NAME = \"image-api-live-test-disk\";\n   public static final int sizeGb = 10;\n   public static final String IMAGE_NAME = \"image-api-live-test-image\";\n\n   private Image image;\n   private URI diskURI;\n\n   private ImageApi api(){\n      return api.images();\n   }\n\n   private DiskApi diskApi() {\n      return api.disksInZone(DEFAULT_ZONE_NAME);\n   }\n\n   @Test(groups = \"live\")\n   public void testListImage() {\n      Iterator<ListPage<Image>> images = api().listInProject(\"centos-cloud\", maxResults(1));\n\n      List<Image> imageAsList = images.next();\n\n      assertEquals(imageAsList.size(), 1);\n\n      this.image = imageAsList.get(0);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testListImage\")\n   public void testGetImage() {\n      assertEquals(image, api().get(image.selfLink()));\n   }\n\n   @Test(groups = \"live\")\n   public void testInsertDisk() {\n      assertOperationDoneSuccessfully(diskApi().create(DISK_NAME,\n            new DiskCreationOptions.Builder().sizeGb(sizeGb).build()));\n      Disk disk = diskApi().get(DISK_NAME);\n      diskURI = disk.selfLink();\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testInsertDisk\")\n   public void testCreateImageFromPD(){\n      assertOperationDoneSuccessfully(api().createFromDisk(IMAGE_NAME, diskURI.toString()));\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testCreateImageFromPD\")\n   public void testGetCreatedImage(){\n      Image image = api().get(IMAGE_NAME);\n      assertImageEquals(image);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testGetCreatedImage\")\n   public void testDeprecateImage(){\n      Image image = api().get(IMAGE_NAME);\n      assertNull(image.deprecated());\n      String deprecated = \"2015-07-16T22:16:13.468Z\";\n      String obsolete = \"2016-10-16T22:16:13.468Z\";\n      String deleted = \"2017-01-16T22:16:13.468Z\";\n\n      URI replacement = URI.create(\"https://www.googleapis.com/compute/v1/projects/centos-cloud/global/images/centos-6-2-v20120326test\");\n\n      DeprecateOptions deprecateOptions = new DeprecateOptions.Builder().state(State.DEPRECATED)\n            .replacement(replacement)\n            .deprecated(new SimpleDateFormatDateService().iso8601DateParse(deprecated))\n            .obsolete(new SimpleDateFormatDateService().iso8601DateParse(obsolete))\n            .deleted(new SimpleDateFormatDateService().iso8601DateParse(deleted))\n            .build();\n\n      assertOperationDoneSuccessfully(api().deprecate(IMAGE_NAME, deprecateOptions));\n\n      image = api().get(IMAGE_NAME);\n      assertEquals(image.deprecated().state(), State.DEPRECATED);\n      assertEquals(image.deprecated().replacement(), replacement);\n      assertEquals(image.deprecated().deprecated(), deprecated);\n      assertEquals(image.deprecated().obsolete(), obsolete);\n      assertEquals(image.deprecated().deleted(), deleted);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testDeprecateImage\", alwaysRun = true)\n   public void testCleanup(){\n      assertOperationDoneSuccessfully(api().delete(IMAGE_NAME));\n      assertOperationDoneSuccessfully(diskApi().delete(DISK_NAME));\n   }\n\n   private void assertImageEquals(Image result) {\n      assertEquals(result.name(), IMAGE_NAME);\n      assertEquals(result.sourceType(), \"RAW\");\n      assertEquals(result.selfLink(), getImageUrl(IMAGE_NAME) );\n   }\n}\n\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/ImageApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNull;\n\nimport java.net.URI;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.googlecomputeengine.domain.Deprecated;\nimport org.jclouds.googlecomputeengine.domain.Deprecated.State;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiMockTest;\nimport org.jclouds.googlecomputeengine.options.DeprecateOptions;\nimport org.jclouds.googlecomputeengine.options.ImageCreationOptions;\nimport org.jclouds.googlecomputeengine.parse.ParseImageListTest;\nimport org.jclouds.googlecomputeengine.parse.ParseImageTest;\nimport org.jclouds.googlecomputeengine.parse.ParseOperationTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ImageApiMockTest\", singleThreaded = true)\npublic class ImageApiMockTest extends BaseGoogleComputeEngineApiMockTest {\n\n   public void get() throws Exception {\n      server.enqueue(jsonResponse(\"/image_get.json\"));\n\n      assertEquals(imageApi().get(URI.create(url(\"/projects/party/global/images/centos-6-2-v20120326\"))),\n            new ParseImageTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/projects/party/global/images/centos-6-2-v20120326\");\n   }\n\n   public void get_4xx() throws Exception {\n      server.enqueue(response404());\n\n      assertNull(imageApi().get(URI.create(url(\"/projects/party/global/images/centos-6-2-v20120326\"))));\n      assertSent(server, \"GET\", \"/projects/party/global/images/centos-6-2-v20120326\");\n   }\n\n   public void getByName() throws Exception {\n      server.enqueue(jsonResponse(\"/image_get.json\"));\n\n      assertEquals(imageApi().get(\"centos-6-2-v20120326\"), new ParseImageTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/projects/party/global/images/centos-6-2-v20120326\");\n   }\n\n   public void getByName_4xx() throws Exception {\n      server.enqueue(response404());\n\n      assertNull(imageApi().get(\"centos-6-2-v20120326\"));\n      assertSent(server, \"GET\", \"/projects/party/global/images/centos-6-2-v20120326\");\n   }\n\n   public void deleteImage_2xx()  throws Exception {\n      server.enqueue(jsonResponse(\"/operation.json\"));\n\n      assertEquals(imageApi().delete(\"centos-6-2-v20120326\"),\n            new ParseOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"DELETE\", \"/projects/party/global/images/centos-6-2-v20120326\");\n   }\n\n   public void deleteImage_4xx() throws Exception {\n      server.enqueue(response404());\n\n      assertNull(imageApi().delete(\"centos-6-2-v20120326\"));\n      assertSent(server, \"DELETE\", \"/projects/party/global/images/centos-6-2-v20120326\");\n   }\n\n   public void list() throws Exception {\n      server.enqueue(jsonResponse(\"/image_list.json\"));\n\n      assertEquals(imageApi().list().next(), new ParseImageListTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/projects/party/global/images\");\n   }\n\n   public void list_empty() throws Exception {\n      server.enqueue(jsonResponse(\"/list_empty.json\"));\n\n      assertFalse(imageApi().list().hasNext());\n      assertSent(server, \"GET\", \"/projects/party/global/images\");\n   }\n\n   public void listInProject() throws Exception {\n      server.enqueue(jsonResponse(\"/image_list.json\"));\n\n      assertEquals(imageApi().listInProject(\"centos-cloud\").next(), new ParseImageListTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/projects/centos-cloud/global/images\");\n   }\n\n   public void listInProject_empty() throws Exception {\n      server.enqueue(jsonResponse(\"/list_empty.json\"));\n\n      assertFalse(imageApi().listInProject(\"centos-cloud\").hasNext());\n      assertSent(server, \"GET\", \"/projects/centos-cloud/global/images\");\n   }\n\n   public void createImageFromPd_2xx() throws Exception {\n      server.enqueue(jsonResponse(\"/operation.json\"));\n\n      assertEquals(imageApi().createFromDisk(\"my-image\", url(\"/projects/party/zones/us-central1-a/disks/mydisk\")),\n            new ParseOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"POST\", \"/projects/party/global/images\", stringFromResource(\"/image_insert_from_pd.json\"));\n   }\n\n   public void createImage_options() throws Exception {\n      server.enqueue(jsonResponse(\"/operation.json\"));\n\n      ImageCreationOptions options = new ImageCreationOptions.Builder(\"name\")\n         .description(\"this is a test\")\n         .sourceDisk(\"projects/project/zones/zone/disks/disks\")\n         .deprecated(Deprecated.create(State.DEPRECATED, null, null, null, null)).build();\n      assertEquals(imageApi().create(options),\n            new ParseOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"POST\", \"/projects/party/global/images\",\n            \"{\\\"name\\\":\\\"name\\\",\\\"description\\\":\\\"this is a test\\\",\\\"\"\n            + \"deprecated\\\":{\\\"state\\\":\\\"DEPRECATED\\\"},\\\"sourceDisk\\\":\"\n            + \"\\\"projects/project/zones/zone/disks/disks\\\"}\");\n\n   }\n\n   public void deprecateImage_2xx() throws Exception{\n      String imageName = \"test-image\";\n      server.enqueue(jsonResponse(\"/operation.json\"));\n\n      DeprecateOptions options = new DeprecateOptions.Builder().state(State.DEPRECATED)\n            .replacement(URI.create(url(\"/projects/centos-cloud/global/images/centos-6-2-v20120326test\")))\n            .deprecated(new SimpleDateFormatDateService().iso8601DateParse(\"2014-07-16T22:16:13.468Z\"))\n            .obsolete(new SimpleDateFormatDateService().iso8601DateParse(\"2014-10-16T22:16:13.468Z\"))\n            .deleted(new SimpleDateFormatDateService().iso8601DateParse(\"2015-01-16T22:16:13.468Z\"))\n            .build();\n\n      assertEquals(imageApi().deprecate(imageName, options),\n            new ParseOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"POST\", \"/projects/party/global/images/\" + imageName + \"/deprecate\", stringFromResource(\"/image_deprecate.json\"));\n   }\n\n   ImageApi imageApi(){\n      return api().images();\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/InstanceApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.jclouds.googlecomputeengine.options.ListOptions.Builder.filter;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.Arrays;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Properties;\n\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.GoogleComputeEngineApi;\nimport org.jclouds.googlecomputeengine.domain.AttachDisk;\nimport org.jclouds.googlecomputeengine.domain.Image;\nimport org.jclouds.googlecomputeengine.domain.Instance;\nimport org.jclouds.googlecomputeengine.domain.Instance.AttachedDisk;\nimport org.jclouds.googlecomputeengine.domain.Instance.NetworkInterface.AccessConfig;\nimport org.jclouds.googlecomputeengine.domain.Instance.NetworkInterface.AccessConfig.Type;\nimport org.jclouds.googlecomputeengine.domain.Instance.Scheduling;\nimport org.jclouds.googlecomputeengine.domain.Instance.Scheduling.OnHostMaintenance;\nimport org.jclouds.googlecomputeengine.domain.Instance.SerialPortOutput;\nimport org.jclouds.googlecomputeengine.domain.Instance.ServiceAccount;\nimport org.jclouds.googlecomputeengine.domain.Metadata;\nimport org.jclouds.googlecomputeengine.domain.NewInstance;\nimport org.jclouds.googlecomputeengine.domain.Operation;\nimport org.jclouds.googlecomputeengine.domain.Tags;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiLiveTest;\nimport org.jclouds.googlecomputeengine.options.DiskCreationOptions;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Ordering;\nimport com.google.inject.Module;\n\n@Test(groups = \"live\", testName = \"InstanceApiLiveTest\")\npublic class InstanceApiLiveTest extends BaseGoogleComputeEngineApiLiveTest {\n\n   private static final String INSTANCE_NETWORK_NAME = \"instance-api-live-test-network\";\n   private static final String INSTANCE_NAME = \"instance-api-test-instance-1\";\n   private static final String INSTANCE_NAME2 = \"instance-api-test-instance-2\";\n   private static final String DISK_NAME = \"instance-live-test-disk\";\n   private static final String IPV4_RANGE = \"10.0.0.0/8\";\n   private static final String METADATA_ITEM_KEY = \"instanceLiveTestTestProp\";\n   private static final String METADATA_ITEM_VALUE = \"instanceLiveTestTestValue\";\n   private static final List<String> TAGS = ImmutableList.of(\"instance-live-test-tag1\", \"instance-live-test-tag2\");\n   private static final String ATTACH_DISK_NAME = \"instance-api-live-test-attach-disk\";\n   private static final String ATTACH_DISK_DEVICE_NAME = \"attach-disk-1\";\n   private static final int DEFAULT_DISK_SIZE_GB = 10;\n\n   private static final String DEFAULT_BOOT_DISK_NAME = \"persistent-disk-0\";\n\n   private NewInstance instance;\n   private NewInstance instance2;\n\n   @Override\n   protected GoogleComputeEngineApi create(Properties props, Iterable<Module> modules) {\n      GoogleComputeEngineApi api = super.create(props, modules);\n      List<Image> list = api.images().listInProject(\"centos-cloud\", filter(\"name eq centos.*\")).next();\n      URI imageUri = FluentIterable.from(list)\n                        .filter(new Predicate<Image>() {\n                           @Override\n                           public boolean apply(Image input) {\n                              // filter out all deprecated images\n                              return !(input.deprecated() != null && input.deprecated().state() != null);\n                           }\n                        })\n                        .first()\n                        .get()\n                        .selfLink();\n\n      instance = NewInstance.create(\n            INSTANCE_NAME, // name\n            getDefaultMachineTypeUrl(), // machineType\n            getNetworkUrl(INSTANCE_NETWORK_NAME), // network\n            null, // subnetwork\n            Arrays.asList(AttachDisk.newBootDisk(imageUri),\n                  AttachDisk.existingDisk(getDiskUrl(DISK_NAME))), // disks\n            \"a description\", // description\n            Tags.create(null, ImmutableList.of(\"foo\", \"bar\")) // tags\n      );\n      instance.metadata().put(\"mykey\", \"myvalue\");\n\n      instance2 = new NewInstance.Builder(INSTANCE_NAME2, // name\n            getDefaultMachineTypeUrl(), // machineType\n            getNetworkUrl(INSTANCE_NETWORK_NAME), // network\n            null, // subnetwork\n            imageUri) // sourceImage\n            .canIpForward(true)\n            .description(\"description\")\n            .tags(Tags.create(null, ImmutableList.of(\"tag1\")))\n            .serviceAccounts(ImmutableList.of(ServiceAccount.create(\"default\", ImmutableList.of(\"https://www.googleapis.com/auth/compute\"))))\n            .scheduling(Scheduling.create(OnHostMaintenance.MIGRATE, true, false))\n            .build();\n\n      return api;\n   }\n\n   private InstanceApi api() {\n      return api.instancesInZone(DEFAULT_ZONE_NAME);\n   }\n\n   private DiskApi diskApi() {\n      return api.disksInZone(DEFAULT_ZONE_NAME);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testInsertInstance\")\n   public void testGetInstance2() {\n      Instance instance = api().get(INSTANCE_NAME2);\n      assertNotNull(instance);\n      assertInstanceEquals(instance, this.instance2);\n      assertTrue(instance.canIpForward());\n      assertEquals(instance.description(), \"description\");\n      assertEquals(instance.serviceAccounts().get(0).scopes(), ImmutableList.of(\"https://www.googleapis.com/auth/compute\"));\n      assertTrue(instance.scheduling().automaticRestart());\n      assertFalse(instance.scheduling().preemptible());\n      assertEquals(instance.scheduling().onHostMaintenance(), OnHostMaintenance.MIGRATE);\n   }\n\n   @Test(groups = \"live\")\n   public void testInsertInstance() {\n      // need to insert the network first\n      assertOperationDoneSuccessfully(api.networks().createLegacy(INSTANCE_NETWORK_NAME, IPV4_RANGE));\n\n      assertOperationDoneSuccessfully(diskApi().create(DISK_NAME,\n            new DiskCreationOptions.Builder().sizeGb(DEFAULT_DISK_SIZE_GB).build()));\n      assertOperationDoneSuccessfully(api().create(instance));\n      assertOperationDoneSuccessfully(api().create(instance2));\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testInsertInstance\")\n   public void testGetInstance() {\n      Instance instance = api().get(INSTANCE_NAME);\n      assertNotNull(instance);\n      assertInstanceEquals(instance, this.instance);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testInsertInstance\")\n   public void testAddAccessConfig() {\n      Instance instance = api().get(INSTANCE_NAME);\n      assertNotNull(instance);\n      assertOperationDoneSuccessfully(api().deleteAccessConfigFromNic(INSTANCE_NAME,\n            instance.networkInterfaces().get(0).accessConfigs().get(0).name(), \"nic0\"));\n\n      AccessConfig config = AccessConfig.create(\"test-config\", Type.ONE_TO_ONE_NAT, null);\n      assertOperationDoneSuccessfully(api().addAccessConfigToNic(INSTANCE_NAME, config, \"nic0\"));\n      instance = api().get(INSTANCE_NAME);\n      assertNotNull(instance);\n      assertEquals(instance.networkInterfaces().get(0).accessConfigs().get(0).name(), \"test-config\");\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testAddAccessConfig\")\n   public void testDeleteAccessConfig() {\n      Instance instance = api().get(INSTANCE_NAME);\n      assertOperationDoneSuccessfully(api().deleteAccessConfigFromNic(INSTANCE_NAME, \"test-config\", \"nic0\"));\n      instance = api().get(INSTANCE_NAME);\n      assertNotNull(instance);\n      assertTrue(instance.networkInterfaces().get(0).accessConfigs().isEmpty());\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testInsertInstance\")\n   public void testGetSerialPortOutput() {\n      SerialPortOutput output = api().getSerialPortOutput(INSTANCE_NAME);\n      assertNotNull(output);\n      assertNotNull(output.contents());\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testInsertInstance\")\n   public void testSetDiskAutoDelete() {\n\n      assertTrue(existsDiskWithNameAndAutoDelete(INSTANCE_NAME, DEFAULT_BOOT_DISK_NAME, true));\n\n      Operation o = api().setDiskAutoDelete(INSTANCE_NAME, DEFAULT_BOOT_DISK_NAME, false);\n      assertOperationDoneSuccessfully(o);\n\n      assertTrue(existsDiskWithNameAndAutoDelete(INSTANCE_NAME, DEFAULT_BOOT_DISK_NAME, false));\n\n      o = api().setDiskAutoDelete(INSTANCE_NAME, DEFAULT_BOOT_DISK_NAME, true);\n\n      assertOperationDoneSuccessfully(o);\n      assertTrue(existsDiskWithNameAndAutoDelete(INSTANCE_NAME, DEFAULT_BOOT_DISK_NAME, true));\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testInsertInstance\")\n   public void testSetScheduling() {\n      Instance instance = api().get(INSTANCE_NAME);\n      assertEquals(instance.scheduling().automaticRestart(), true);\n      assertEquals(instance.scheduling().preemptible(), false);\n      assertEquals(instance.scheduling().onHostMaintenance(), Scheduling.OnHostMaintenance.MIGRATE);\n\n      assertOperationDoneSuccessfully(api().setScheduling(INSTANCE_NAME, Scheduling.OnHostMaintenance.TERMINATE, false,\n          false));\n\n      Instance instanceAltered = api().get(INSTANCE_NAME);\n      assertEquals(instanceAltered.scheduling().automaticRestart(), false);\n      assertEquals(instanceAltered.scheduling().preemptible(), false);\n      assertEquals(instanceAltered.scheduling().onHostMaintenance(), Scheduling.OnHostMaintenance.TERMINATE);\n   }\n\n   private boolean existsDiskWithNameAndAutoDelete(String instanceName, final String diskName, final boolean autoDelete){\n      Instance revertedInstance = api().get(instanceName);\n\n      return Iterables.any(revertedInstance.disks(), new Predicate<AttachedDisk>() {\n         @Override\n         public boolean apply(AttachedDisk disk) {\n            return disk.type() == AttachedDisk.Type.PERSISTENT &&\n            diskName.equals(disk.deviceName()) &&\n            disk.autoDelete() == autoDelete;\n         }\n      });\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testListInstance\")\n   public void testSetMetadataForInstance() {\n      Instance originalInstance = api().get(INSTANCE_NAME);\n      Metadata update = Metadata.create(originalInstance.metadata().fingerprint())\n            .put(METADATA_ITEM_KEY, METADATA_ITEM_VALUE);\n      assertOperationDoneSuccessfully(api().setMetadata(INSTANCE_NAME, update));\n\n      Instance modifiedInstance = api().get(INSTANCE_NAME);\n\n      assertTrue(modifiedInstance.metadata().containsKey(METADATA_ITEM_KEY));\n      assertEquals(modifiedInstance.metadata().get(METADATA_ITEM_KEY), METADATA_ITEM_VALUE);\n      assertNotNull(modifiedInstance.metadata().fingerprint());\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testListInstance\")\n   public void testSetTagsForInstance() {\n      Instance originalInstance = api().get(INSTANCE_NAME);\n      assertOperationDoneSuccessfully(\n            api().setTags(INSTANCE_NAME, TAGS, originalInstance.tags().fingerprint()));\n\n      Instance modifiedInstance = api().get(INSTANCE_NAME);\n\n      assertTrue(modifiedInstance.tags().items().containsAll(TAGS));\n      assertNotNull(modifiedInstance.tags().fingerprint());\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testSetMetadataForInstance\")\n   public void testAttachDiskToInstance() {\n      assertOperationDoneSuccessfully(diskApi().create(ATTACH_DISK_NAME,\n            new DiskCreationOptions.Builder().sizeGb(1).build()));\n\n      Instance originalInstance = api().get(INSTANCE_NAME);\n      assertOperationDoneSuccessfully(api().attachDisk(INSTANCE_NAME,\n                  AttachDisk.create(AttachDisk.Type.PERSISTENT, // type\n                                    AttachDisk.Mode.READ_ONLY, // mode\n                                    getDiskUrl(ATTACH_DISK_NAME), // source\n                                    ATTACH_DISK_DEVICE_NAME, // deviceName\n                                    false, // boot\n                                    null, // initializeParams\n                                    false, // autoDelete\n                                    null, // licenses\n                                    null // interface\n                                    )));\n\n      Instance modifiedInstance = api().get(INSTANCE_NAME);\n\n      assertTrue(modifiedInstance.disks().size() > originalInstance.disks().size());\n      assertTrue(Iterables.any(modifiedInstance.disks(), new Predicate<AttachedDisk>() {\n\n         @Override\n         public boolean apply(AttachedDisk disk) {\n            return disk.type() == AttachedDisk.Type.PERSISTENT &&\n                  ATTACH_DISK_DEVICE_NAME.equals(disk.deviceName());\n         }\n      }));\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testAttachDiskToInstance\", alwaysRun = true)\n   public void testDetachDiskFromInstance() {\n      Instance originalInstance = api().get(INSTANCE_NAME);\n      assertOperationDoneSuccessfully(api().detachDisk(INSTANCE_NAME, ATTACH_DISK_DEVICE_NAME));\n\n      Instance modifiedInstance = api().get(INSTANCE_NAME);\n\n      assertTrue(modifiedInstance.disks().size() < originalInstance.disks().size());\n\n      assertOperationDoneSuccessfully(diskApi().delete(ATTACH_DISK_NAME));\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testInsertInstance\")\n   public void testListInstance() {\n\n      Iterator<ListPage<Instance>> instances = api().list(filter(\"name eq \" + INSTANCE_NAME));\n\n      List<Instance> instancesAsList = instances.next();\n\n      assertEquals(instancesAsList.size(), 1);\n\n      assertInstanceEquals(instancesAsList.get(0), instance);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testDetachDiskFromInstance\")\n   public void testResetInstance() {\n      assertOperationDoneSuccessfully(api().reset(INSTANCE_NAME));\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testGetInstance2\")\n   public void testStopInstance() {\n      Instance originalInstance = api().get(INSTANCE_NAME2);\n      assertEquals(originalInstance.status(), Instance.Status.RUNNING);\n      assertOperationDoneSuccessfully(api().stop(INSTANCE_NAME2));\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testStopInstance\")\n   public void testStartInstance() {\n      Instance originalInstance = api().get(INSTANCE_NAME2);\n      assertEquals(originalInstance.status(), Instance.Status.TERMINATED);\n      assertOperationDoneSuccessfully(api().start(INSTANCE_NAME2));\n      originalInstance = api().get(INSTANCE_NAME2);\n      assertEquals(originalInstance.status(), Instance.Status.RUNNING);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = {\"testSetDiskAutoDelete\", \"testResetInstance\", \"testSetScheduling\",\n         \"testGetInstance\", \"testGetSerialPortOutput\", \"testDeleteAccessConfig\", \"testStartInstance\"}, alwaysRun = true)\n   public void testDeleteInstance() {\n      assertOperationDoneSuccessfully(api().delete(INSTANCE_NAME));\n      assertOperationDoneSuccessfully(api().delete(INSTANCE_NAME2));\n      assertOperationDoneSuccessfully(diskApi().delete(DISK_NAME));\n      Operation deleteNetwork = api.networks().delete(INSTANCE_NETWORK_NAME);\n      assertOperationDoneSuccessfully(deleteNetwork);\n   }\n\n   private void assertInstanceEquals(Instance result, NewInstance expected) {\n      assertEquals(result.name(), expected.name());\n      assertEquals(result.metadata().asMap(), expected.metadata().asMap()); // ignore fingerprint!\n      // Do not assume tags come in the same order\n      List<String> resultTags = Ordering.from(String.CASE_INSENSITIVE_ORDER).sortedCopy(result.tags().items());\n      List<String> expectedTags = Ordering.from(String.CASE_INSENSITIVE_ORDER).sortedCopy(expected.tags().items());\n      assertEquals(resultTags, expectedTags);\n   }\n\n   @AfterClass(groups = { \"integration\", \"live\" }, alwaysRun = true)\n   protected void tearDownContext() {\n      try {\n         waitOperationDone(api().delete(INSTANCE_NAME));\n         waitOperationDone(diskApi().delete(DISK_NAME));\n         waitOperationDone(api.networks().delete(INSTANCE_NETWORK_NAME));\n      } catch (Exception e) {\n         // we don't really care about any exception here, so just delete away.\n       }\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/InstanceApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNull;\n\nimport java.net.URI;\nimport java.util.Arrays;\n\nimport org.jclouds.googlecomputeengine.domain.AttachDisk;\nimport org.jclouds.googlecomputeengine.domain.AttachDisk.DiskInterface;\nimport org.jclouds.googlecomputeengine.domain.Instance.NetworkInterface.AccessConfig;\nimport org.jclouds.googlecomputeengine.domain.Instance.NetworkInterface.AccessConfig.Type;\nimport org.jclouds.googlecomputeengine.domain.Instance.Scheduling;\nimport org.jclouds.googlecomputeengine.domain.Instance.ServiceAccount;\nimport org.jclouds.googlecomputeengine.domain.Metadata;\nimport org.jclouds.googlecomputeengine.domain.NewInstance;\nimport org.jclouds.googlecomputeengine.domain.Instance.Scheduling.OnHostMaintenance;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiMockTest;\nimport org.jclouds.googlecomputeengine.parse.ParseInstanceListTest;\nimport org.jclouds.googlecomputeengine.parse.ParseInstanceSerialOutputTest;\nimport org.jclouds.googlecomputeengine.parse.ParseInstanceTest;\nimport org.jclouds.googlecomputeengine.parse.ParseZoneOperationTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"InstanceApiMockTest\", singleThreaded = true)\npublic class InstanceApiMockTest extends BaseGoogleComputeEngineApiMockTest {\n\n   public void get() throws Exception {\n      server.enqueue(jsonResponse(\"/instance_get.json\"));\n\n      assertEquals(instanceApi().get(\"test-instance\"), new ParseInstanceTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/instances/test-instance\");\n   }\n\n   public void get_4xx() throws Exception {\n      server.enqueue(response404());\n\n      assertNull(instanceApi().get(\"test-1\"));\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/instances/test-1\");\n   }\n\n   public void getInstanceSerialPortOutput() throws Exception {\n      server.enqueue(jsonResponse(\"/instance_serial_port.json\"));\n\n      assertEquals(instanceApi().getSerialPortOutput(\"test-1\"),\n            new ParseInstanceSerialOutputTest().expected(url(\"/projects\")));\n\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/instances/test-1/serialPort\");\n   }\n\n   public void getInstanceSerialPortOutputWindowsPassword() throws Exception {\n      server.enqueue(jsonResponse(\"/instance_serial_port_4_windows.json\"));\n\n      assertEquals(instanceApi().getSerialPortOutput(\"test-1\", 4),\n              new ParseInstanceSerialOutputTest().expected(\n                      url(\"/projects\"),\n                      \"{\\\"ready\\\":true,\\\"version\\\":\\\"Microsoft Windows NT 6.1.7601 Service Pack 1\\\"}\\n{\\\"encryptedPassword\\\":\\\"uiHDEhxyvj6lF5GalHh9TsMZb4bG6Y9qGmFb9S3XI29yvVsDCLdp4IbUg21MncHcaxP0rFu0kyjxlEXDs8y4L1KOhy6iyB42Lh+vZ4XIMjmvU4rZrjsBZ5TxQo9hL0lBW7o3FRM\\\\/UIXCeRk39ObUl2AjDmQ0mcw1byJI5v9KVJnNMaHdRCy\\\\/kvN6bx3qqjIhIMu0JExp4UVkAX2Mxb9b+c4o2DiZF5pY6ZfbuEmjSbvGRJXyswkOJ4jTZl+7e6+SZfEal8HJyRfZKiqTjrz+DLjYSlXrfIRqlvKeAFGOJq6IRojNWiTOOh8Zorc0iHDTIkf+MY0scfbBUo5m30Bf4w==\\\",\\\"exponent\\\":\\\"AQAB\\\",\\\"modulus\\\":\\\"0tiKdO2JmBHss26jnrSAwb583KG\\\\/ZIw5JwwMPXrCVsFAPwY1OV3RlT1Hp4Xvpibr7rvJbOC+f\\\\/Gd0cBrK5pccQfccB+OHKpbBof473zEfRbdtFwPn10RfAFj\\\\/xikW0r\\\\/XxgG\\\\/c8tz9bmALBStGqmwOVOLRHxjwgtGu4poeuwmFfG6TuwgCadxpllW74mviFd4LZVSuCSni5YJnBM2HSJ8NP6g1fqI17KDXt2XO\\\\/7kSItubmMk+HGEXdH4qiugHYewaIf1o4XSQROC8xlRl7t\\\\/RaD4U58hKYkVwg0Ir7WzYzAVpG2UR4Co\\\\/GDG9Hct7HOYekDqVQ+sSZbwzajnVunkw==\\\",\\\"passwordFound\\\":true,\\\"userName\\\":\\\"example-user\\\"}\\n\"\n              ));\n\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/instances/test-1/serialPort?port=4\");\n   }\n\n   public void insert_noOptions() throws Exception {\n      server.enqueue(jsonResponse(\"/zone_operation.json\"));\n\n      NewInstance newInstance = NewInstance.create(\n            \"test-1\", // name\n            URI.create(url(\"/projects/party/zones/us-central1-a/machineTypes/n1-standard-1\")), // machineType\n            URI.create(url(\"/projects/party/global/networks/default\")), // network\n            null, // subnetwork\n            URI.create(url(\"/projects/party/global/images/centos-6-2-v20120326\")) // sourceImage\n      );\n\n      assertEquals(instanceApi().create(newInstance), new ParseZoneOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"POST\", \"/projects/party/zones/us-central1-a/instances\",\n            stringFromResource(\"/instance_insert_simple.json\"));\n   }\n\n   public void insert_allOptions() throws Exception {\n      server.enqueue(jsonResponse(\"/zone_operation.json\"));\n\n      NewInstance newInstance = NewInstance.create(\n            \"test-1\", // name\n            URI.create(url(\"/projects/party/zones/us-central1-a/machineTypes/n1-standard-1\")), // machineType\n            URI.create(url(\"/projects/party/global/networks/default\")), // network\n            null, // subnetwork\n            Arrays.asList(AttachDisk.existingBootDisk(URI.create(url(\"/projects/party/zones/us-central1-a/disks/test\")))),\n            \"desc\", // description\n            null // tags\n      );\n\n      newInstance.metadata().put(\"aKey\", \"aValue\");\n      assertEquals(instanceApi().create(newInstance), new ParseZoneOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"POST\", \"/projects/party/zones/us-central1-a/instances\",\n            stringFromResource(\"/instance_insert.json\"));\n   }\n\n   public void addAccessConfig() throws Exception {\n      server.enqueue(jsonResponse(\"/zone_operation.json\"));\n\n      AccessConfig config = AccessConfig.create(\"test-access\", Type.ONE_TO_ONE_NAT, \"1.1.1.1\");\n      assertEquals(instanceApi().addAccessConfigToNic(\"test-instance\", config, \"test-network\"),\n            new ParseZoneOperationTest().expected(url(\"/projects\")));\n\n      assertSent(server, \"POST\", \"/projects/party/zones/us-central1-a/instances/test-instance/\"\n            + \"addAccessConfig?networkInterface=test-network\",\n            \"{\" +\n            \"  \\\"type\\\": \\\"ONE_TO_ONE_NAT\\\",\" +\n            \"  \\\"name\\\": \\\"test-access\\\",\" +\n            \"  \\\"natIP\\\": \\\"1.1.1.1\\\"\" +\n            \"}\");\n   }\n\n   public void deleteAccessConfig() throws Exception {\n      server.enqueue(jsonResponse(\"/zone_operation.json\"));\n\n      assertEquals(instanceApi().deleteAccessConfigFromNic(\"test-instance\", \"test-access\", \"test-network\"),\n            new ParseZoneOperationTest().expected(url(\"/projects\")));\n\n      assertSent(server, \"POST\", \"/projects/party/zones/us-central1-a/instances/test-instance/\"\n            + \"deleteAccessConfig?accessConfig=test-access&networkInterface=test-network\");\n   }\n\n   public void delete() throws Exception {\n      server.enqueue(jsonResponse(\"/zone_operation.json\"));\n\n      assertEquals(instanceApi().delete(\"test-1\"),\n            new ParseZoneOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"DELETE\", \"/projects/party/zones/us-central1-a/instances/test-1\");\n   }\n\n   public void delete_4xx() throws Exception {\n      server.enqueue(response404());\n\n      assertNull(instanceApi().delete(\"test-1\"));\n      assertSent(server, \"DELETE\", \"/projects/party/zones/us-central1-a/instances/test-1\");\n   }\n\n   public void list() throws Exception {\n      server.enqueue(jsonResponse(\"/instance_list.json\"));\n\n      assertEquals(instanceApi().list().next(), new ParseInstanceListTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/instances\");\n   }\n\n   public void list_empty() throws Exception {\n      server.enqueue(jsonResponse(\"/list_empty.json\"));\n\n      assertFalse(instanceApi().list().hasNext());\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/instances\");\n   }\n\n   public void setMetadata() throws Exception {\n      server.enqueue(jsonResponse(\"/zone_operation.json\"));\n\n      assertEquals(instanceApi().setMetadata(\"test-1\", Metadata.create(\"efgh\").put(\"foo\", \"bar\")),\n            new ParseZoneOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"POST\", \"/projects/party/zones/us-central1-a/instances/test-1/setMetadata\",\n            stringFromResource(\"/instance_set_metadata.json\"));\n   }\n\n   public void setTags() throws Exception {\n      server.enqueue(jsonResponse(\"/zone_operation.json\"));\n\n      assertEquals(instanceApi().setTags(\"test-1\", ImmutableList.of(\"foo\", \"bar\"), \"efgh\"),\n            new ParseZoneOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"POST\", \"/projects/party/zones/us-central1-a/instances/test-1/setTags\",\n            stringFromResource(\"/instance_set_tags.json\"));\n   }\n\n   public void reset() throws Exception {\n      server.enqueue(jsonResponse(\"/zone_operation.json\"));\n\n      assertEquals(instanceApi().reset(\"test-1\"),\n            new ParseZoneOperationTest().expected(url(\"/projects\")));\n\n      assertSent(server, \"POST\", \"/projects/party/zones/us-central1-a/instances/test-1/reset\");\n   }\n\n   public void attachDisk() throws Exception {\n      server.enqueue(jsonResponse(\"/zone_operation.json\"));\n\n      assertEquals(instanceApi().attachDisk(\"test-1\",\n            AttachDisk.create(AttachDisk.Type.PERSISTENT, // type\n                                     AttachDisk.Mode.READ_WRITE, // mode\n                                     URI.create(url(\"/projects/party/zones/us-central1-a/disks/test\")), // source\n                                     \"test\", // deviceName\n                                     true, // boot\n                                     AttachDisk.InitializeParams.create(\n                                           \"test\", // diskName\n                                           Long.parseLong(\"100\", 10), // diskSizeGb\n                                           URI.create(url(\"/projects/party/global/images/test\")), // sourceImage\n                                           URI.create(url(\"/projects/party/zones/us-central1-a/diskTypes/pd-standard\")) // diskType\n                                           ), // initializeParams\n                                     true, // autoDelete\n                                     ImmutableList.of(url(\"/projects/suse-cloud/global/licenses/sles-12\")), // licenses\n                                     DiskInterface.NVME // interface\n                                     )),\n            new ParseZoneOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"POST\", \"/projects/party/zones/us-central1-a/instances/test-1/attachDisk\",\n            stringFromResource(\"/instance_attach_disk.json\"));\n   }\n\n   public void detatchDisk() throws Exception {\n      server.enqueue(jsonResponse(\"/zone_operation.json\"));\n\n      assertEquals(instanceApi().detachDisk(\"test-1\", \"test-disk-1\"),\n            new ParseZoneOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"POST\", \"/projects/party/zones/us-central1-a/instances/test-1/detachDisk?deviceName=test-disk-1\");\n   }\n\n   public void setDiskAutoDelete() throws Exception {\n      server.enqueue(jsonResponse(\"/zone_operation.json\"));\n\n      assertEquals(instanceApi().setDiskAutoDelete(\"test-1\", \"test-disk-1\", true),\n            new ParseZoneOperationTest().expected(url(\"/projects\")));\n\n      assertSent(server, \"POST\", \"/projects/party/zones/us-central1-a/instances/test-1/setDiskAutoDelete\"\n          + \"?deviceName=test-disk-1&autoDelete=true\");\n   }\n\n   public void setScheduling() throws Exception {\n      server.enqueue(jsonResponse(\"/zone_operation.json\"));\n\n      assertEquals(instanceApi().setScheduling(\"test-1\", OnHostMaintenance.TERMINATE, true, false),\n            new ParseZoneOperationTest().expected(url(\"/projects\")));\n\n      assertSent(server, \"POST\", \"/projects/party/zones/us-central1-a/instances/test-1/setScheduling\",\n            \"{\\\"onHostMaintenance\\\": \\\"TERMINATE\\\",\\\"automaticRestart\\\": true,\\\"preemptible\\\": false}\");\n   }\n\n   public void start_test() throws Exception {\n      server.enqueue(jsonResponse(\"/zone_operation.json\"));\n\n      assertEquals(instanceApi().start(\"test-1\"),\n            new ParseZoneOperationTest().expected(url(\"/projects\")));\n\n      assertSent(server, \"POST\", \"/projects/party/zones/us-central1-a/instances/test-1/start\");\n   }\n\n   public void stop_test() throws Exception {\n      server.enqueue(jsonResponse(\"/zone_operation.json\"));\n\n      assertEquals(instanceApi().stop(\"test-1\"),\n            new ParseZoneOperationTest().expected(url(\"/projects\")));\n\n      assertSent(server, \"POST\", \"/projects/party/zones/us-central1-a/instances/test-1/stop\");\n   }\n\n   public void builderTest() throws Exception {\n      server.enqueue(jsonResponse(\"/zone_operation.json\"));\n\n      NewInstance newInstance = new NewInstance.Builder(\"test-1\", // name\n            URI.create(url(\"/projects/party/zones/us-central1-a/machineTypes/n1-standard-1\")), // machineType\n            URI.create(url(\"/projects/party/global/networks/default\")), // network\n            null, // subnetwork\n            URI.create(url(\"/projects/party/global/images/centos-6-2-v20120326\"))).build(); // sourceImage)\n\n      assertEquals(instanceApi().create(newInstance), new ParseZoneOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"POST\", \"/projects/party/zones/us-central1-a/instances\",\n            stringFromResource(\"/instance_insert_simple.json\"));\n   }\n\n   public void insert_builder_allOptions() throws Exception {\n      server.enqueue(jsonResponse(\"/zone_operation.json\"));\n\n      NewInstance newInstance = new NewInstance.Builder(\n            \"test-1\", // name\n            URI.create(url(\"/projects/party/zones/us-central1-a/machineTypes/n1-standard-1\")), // machineType\n            URI.create(url(\"/projects/party/global/networks/default\")), // network\n            null, // subnetwork\n            Arrays.asList(AttachDisk.existingBootDisk(URI.create(url(\"/projects/party/zones/us-central1-a/disks/test\")))))\n            .canIpForward(true)\n            .description(\"desc\")\n            .tags(null)\n            .metadata(Metadata.create().put(\"aKey\", \"aValue\"))\n            .serviceAccounts(ImmutableList.of(ServiceAccount.create(\"default\",\n                                              ImmutableList.of(\"https://www.googleapis.com/auth/compute\"))))\n            .scheduling(Scheduling.create(OnHostMaintenance.MIGRATE, true, false))\n            .build();\n\n      assertEquals(instanceApi().create(newInstance), new ParseZoneOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"POST\", \"/projects/party/zones/us-central1-a/instances\",\n            stringFromResource(\"/instance_insert_full.json\"));\n   }\n\n   InstanceApi instanceApi(){\n      return api().instancesInZone(\"us-central1-a\");\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/InstanceApiWindowsLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.jclouds.googlecomputeengine.options.ListOptions.Builder.filter;\nimport static org.testng.Assert.assertFalse;\n\nimport java.net.URI;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.Security;\nimport java.security.cert.CertificateException;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport org.jclouds.encryption.bouncycastle.config.BouncyCastleCryptoModule;\nimport org.jclouds.googlecomputeengine.GoogleComputeEngineApi;\nimport org.jclouds.googlecomputeengine.domain.Image;\nimport org.jclouds.googlecomputeengine.domain.Instance;\nimport org.jclouds.googlecomputeengine.domain.NewInstance;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiLiveTest;\nimport org.jclouds.googlecomputeengine.options.DiskCreationOptions;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Strings;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Key;\nimport com.google.inject.Module;\nimport com.google.inject.TypeLiteral;\n\n@Test(groups = \"live\", testName = \"InstanceApiWindowsLiveTest\")\npublic class InstanceApiWindowsLiveTest extends BaseGoogleComputeEngineApiLiveTest {\n\n   private static final String INSTANCE_NETWORK_NAME = \"instance-api-live-test-network\";\n   private static final String INSTANCE_NAME = \"instance-api-test-instance-1\";\n   private static final String DISK_NAME = \"instance-live-test-disk\";\n   private static final String IPV4_RANGE = \"10.0.0.0/8\";\n   private static final int DEFAULT_DISK_SIZE_GB = 25;\n\n   private Function<Map<String, ?>, String> reset_windows_password;\n   private NewInstance instance;\n\n   @Override\n   protected GoogleComputeEngineApi create(Properties props, Iterable<Module> modules) {\n      GoogleComputeEngineApi api = super.create(props, modules);\n      reset_windows_password = injector.getInstance(Key.get(new TypeLiteral<Function<Map<String, ?>, String>>() {}));\n\n      List<Image> list = api.images().listInProject(\"windows-cloud\", filter(\"name eq windows-server-2012.*\")).next();\n      URI imageUri = FluentIterable.from(list)\n              .filter(new Predicate<Image>() {\n                 @Override\n                 public boolean apply(Image input) {\n                    // filter out all deprecated images\n                    return !(input.deprecated() != null && input.deprecated().state() != null);\n                 }\n              })\n              .first()\n              .get()\n              .selfLink();\n      instance = NewInstance.create(\n              INSTANCE_NAME,\n              getDefaultMachineTypeUrl(),\n              getNetworkUrl(INSTANCE_NETWORK_NAME),\n              null,\n              imageUri\n      );\n\n      return api;\n   }\n\n   @Override\n   protected Iterable<Module> setupModules() {\n      return ImmutableSet.<Module>builder().addAll(super.setupModules()).add(new BouncyCastleCryptoModule()).build();\n   }\n\n   private InstanceApi api() {\n      return api.instancesInZone(DEFAULT_ZONE_NAME);\n   }\n\n   private DiskApi diskApi() {\n      return api.disksInZone(DEFAULT_ZONE_NAME);\n   }\n\n   @Test(groups = \"live\")\n   public void testInsertInstanceWindows() {\n      // need to insert the network first\n      assertOperationDoneSuccessfully(api.networks().createLegacy(INSTANCE_NETWORK_NAME, IPV4_RANGE));\n\n      assertOperationDoneSuccessfully(diskApi().create(DISK_NAME,\n            new DiskCreationOptions.Builder().sizeGb(DEFAULT_DISK_SIZE_GB).build()));\n      assertOperationDoneSuccessfully(api().create(instance));\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testInsertInstanceWindows\")\n   public void testGetSerialPortOutput4() throws NoSuchAlgorithmException, CertificateException {\n      Instance instance = api().get(INSTANCE_NAME);\n      Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); // Needed when initializing the cipher\n      String result = reset_windows_password.apply(ImmutableMap.of(\"instance\", new AtomicReference<Instance>(instance), \"zone\", DEFAULT_ZONE_NAME, \"email\", identity, \"userName\", prefix));\n      assertFalse(Strings.isNullOrEmpty(result), \"Password shouldn't be empty\");\n   }\n\n   @AfterClass(groups = { \"integration\", \"live\" }, alwaysRun = true)\n   protected void tearDownContext() {\n      try {\n         waitOperationDone(api().delete(INSTANCE_NAME));\n         waitOperationDone(diskApi().delete(DISK_NAME));\n         waitOperationDone(api.networks().delete(INSTANCE_NETWORK_NAME));\n      } catch (Exception e) {\n         // we don't really care about any exception here, so just delete away.\n       }\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/LicenseApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.net.URI;\n\nimport org.jclouds.googlecomputeengine.domain.License;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiLiveTest;\nimport org.testng.annotations.Test;\n\npublic class LicenseApiLiveTest extends BaseGoogleComputeEngineApiLiveTest {\n\n   public static final String PROJECT = \"suse-cloud\";\n   public static final String LICENSE = \"sles-12\";\n\n\n   private LicenseApi api() {\n      return api.licensesInProject(PROJECT);\n   }\n\n   @Test(groups = \"live\")\n   public void testGetLicense() {\n      License license = api().get(LICENSE);\n      assertNotNull(license);\n      assertEquals(license.name(), LICENSE);\n      URI selfLink = URI.create(\"https://www.googleapis.com/compute/v1/projects/\" +\n            PROJECT + \"/global/licenses/\" + LICENSE);\n      assertEquals(license.selfLink(), selfLink);\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/LicenseApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\n\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiMockTest;\nimport org.jclouds.googlecomputeengine.parse.ParseLicenseTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"LicenseApiMockTest\", singleThreaded = true)\npublic class LicenseApiMockTest extends BaseGoogleComputeEngineApiMockTest {\n\n   public void get() throws Exception {\n      server.enqueue(jsonResponse(\"/license_get.json\"));\n\n      assertEquals(licenseApi().get(\"sles-12\"), new ParseLicenseTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/projects/suse-cloud/global/licenses/sles-12\");\n   }\n\n   public void get_4xx() throws Exception {\n      server.enqueue(response404());\n\n      assertNull(licenseApi().get(\"sles-12\"));\n      assertSent(server, \"GET\", \"/projects/suse-cloud/global/licenses/sles-12\");\n   }\n\n   public LicenseApi licenseApi(){\n      return api().licensesInProject(\"suse-cloud\");\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/MachineTypeApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.jclouds.googlecomputeengine.options.ListOptions.Builder.maxResults;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Iterator;\nimport java.util.List;\n\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.domain.MachineType;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiLiveTest;\nimport org.testng.annotations.Test;\n\npublic class MachineTypeApiLiveTest extends BaseGoogleComputeEngineApiLiveTest {\n\n   private MachineType machineType;\n\n   private MachineTypeApi api() {\n      return api.machineTypesInZone(DEFAULT_ZONE_NAME);\n   }\n\n   @Test(groups = \"live\")\n   public void testListMachineType() {\n      Iterator<ListPage<MachineType>> pageIterator = api().list(maxResults(1));\n      assertTrue(pageIterator.hasNext());\n\n      List<MachineType> machineTypeAsList = pageIterator.next();\n\n      assertEquals(machineTypeAsList.size(), 1);\n\n      this.machineType = machineTypeAsList.get(0);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testListMachineType\")\n   public void testGetMachineType() {\n      MachineType machineType = api().get(this.machineType.name());\n      assertNotNull(machineType);\n      assertMachineTypeEquals(machineType, this.machineType);\n   }\n\n   private void assertMachineTypeEquals(MachineType result, MachineType expected) {\n      assertEquals(result.name(), expected.name());\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/MachineTypeApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNull;\n\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiMockTest;\nimport org.jclouds.googlecomputeengine.parse.ParseMachineTypeListTest;\nimport org.jclouds.googlecomputeengine.parse.ParseMachineTypeTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"MachineTypeApiMockTest\", singleThreaded = true)\npublic class MachineTypeApiMockTest extends BaseGoogleComputeEngineApiMockTest {\n\n   public void get() throws Exception{\n      server.enqueue(jsonResponse(\"/machinetype.json\"));\n\n      assertEquals(machineTypeApi().get(\"n1-standard-1\"),\n            new ParseMachineTypeTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/machineTypes/n1-standard-1\");\n   }\n\n   public void get_4xx() throws Exception{\n      server.enqueue(response404());\n\n      assertNull(machineTypeApi().get(\"n1-standard-1\"));\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/machineTypes/n1-standard-1\");\n   }\n\n   public void list() throws Exception {\n      server.enqueue(jsonResponse(\"/machinetype_list.json\"));\n\n      assertEquals(machineTypeApi().list().next(), new ParseMachineTypeListTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/machineTypes\");\n   }\n\n   public void list_empty() throws Exception {\n      server.enqueue(jsonResponse(\"/list_empty.json\"));\n\n      assertFalse(machineTypeApi().list().hasNext());\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/machineTypes\");\n   }\n\n   MachineTypeApi machineTypeApi() {\n      return api().machineTypesInZone(\"us-central1-a\");\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/NetworkApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.jclouds.googlecomputeengine.options.ListOptions.Builder.filter;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.Iterator;\nimport java.util.List;\n\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.domain.Network;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"NetworkApiLiveTest\")\npublic class NetworkApiLiveTest extends BaseGoogleComputeEngineApiLiveTest {\n\n   private static final String NETWORK_NAME = \"network-api-live-test-network\";\n   private static final String IPV4_RANGE = \"10.0.0.0/8\";\n\n   private NetworkApi api() {\n      return api.networks();\n   }\n\n   @Test(groups = \"live\")\n   public void testInsertNetwork() {\n      assertOperationDoneSuccessfully(api().createLegacy(NETWORK_NAME, IPV4_RANGE));\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testInsertNetwork\")\n   public void testGetNetwork() {\n      Network network = api().get(NETWORK_NAME);\n      assertNotNull(network);\n      assertNetworkEquals(network);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testGetNetwork\")\n   public void testListNetwork() {\n      Iterator<ListPage<Network>> networks = api().list(filter(\"name eq \" + NETWORK_NAME));\n\n      List<Network> networksAsList = networks.next();\n\n      assertEquals(networksAsList.size(), 1);\n\n      assertNetworkEquals(networksAsList.get(0));\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testListNetwork\", alwaysRun = true)\n   public void testDeleteNetwork() {\n      assertOperationDoneSuccessfully(api().delete(NETWORK_NAME));\n   }\n\n   private void assertNetworkEquals(Network result) {\n      assertEquals(result.name(), NETWORK_NAME);\n      assertEquals(result.rangeIPv4(), IPV4_RANGE);\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/NetworkApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNull;\n\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiMockTest;\nimport org.jclouds.googlecomputeengine.parse.ParseNetworkListTest;\nimport org.jclouds.googlecomputeengine.parse.ParseNetworkTest;\nimport org.jclouds.googlecomputeengine.parse.ParseOperationTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"NetworkApiMockTest\", singleThreaded = true)\npublic class NetworkApiMockTest extends BaseGoogleComputeEngineApiMockTest {\n\n   public void get() throws Exception {\n      server.enqueue(jsonResponse(\"/network_get.json\"));\n\n      assertEquals(networkApi().get(\"jclouds-test\"),\n            new ParseNetworkTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/projects/party/global/networks/jclouds-test\");\n   }\n\n   public void get_4xx() throws Exception {\n      server.enqueue(response404());\n\n      assertNull(networkApi().get(\"jclouds-test\"));\n      assertSent(server, \"GET\", \"/projects/party/global/networks/jclouds-test\");\n   }\n\n   public void insertLegacy() throws Exception {\n      server.enqueue(jsonResponse(\"/operation.json\"));\n\n      assertEquals(networkApi().createLegacy(\"test-network\", \"10.0.0.0/8\"), new ParseOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"POST\", \"/projects/party/global/networks\",\n            stringFromResource(\"/network_insert.json\"));\n   }\n   \n   public void insertCustom() throws Exception {\n      server.enqueue(jsonResponse(\"/operation.json\"));\n\n      assertEquals(networkApi().createCustom(\"test-network\"), new ParseOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"POST\", \"/projects/party/global/networks\",\n            stringFromResource(\"/network_insert_custom.json\"));\n   }\n\n   public void delete() throws Exception {\n      server.enqueue(jsonResponse(\"/operation.json\"));\n\n      assertEquals(networkApi().delete(\"jclouds-test\"),\n            new ParseOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"DELETE\", \"/projects/party/global/networks/jclouds-test\");\n   }\n\n   public void delete_4xx() throws Exception {\n      server.enqueue(response404());\n\n      assertNull(networkApi().delete(\"jclouds-test\"));\n      assertSent(server, \"DELETE\", \"/projects/party/global/networks/jclouds-test\");\n   }\n\n   public void list() throws Exception {\n      server.enqueue(jsonResponse(\"/network_list.json\"));\n\n      assertEquals(networkApi().list().next(), new ParseNetworkListTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/projects/party/global/networks\");\n   }\n\n   public void list_empty() throws Exception {\n      server.enqueue(jsonResponse(\"/list_empty.json\"));\n\n      assertFalse(networkApi().list().hasNext());\n      assertSent(server, \"GET\", \"/projects/party/global/networks\");\n   }\n\n   NetworkApi networkApi(){\n      return api().networks();\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/OperationApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.jclouds.googlecomputeengine.options.ListOptions.Builder.maxResults;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.Iterator;\n\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.domain.Operation;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiLiveTest;\nimport org.testng.SkipException;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"GlobalOperationApiLiveTest\")\npublic class OperationApiLiveTest extends BaseGoogleComputeEngineApiLiveTest {\n\n   private Operation operation;\n\n   private OperationApi api() {\n      return api.operations();\n   }\n\n   public void listWithOptions() {\n      Iterator<ListPage<Operation>> operations = api().list(maxResults(1));\n\n      // make sure that in spite of having only one result per page we get at least two results\n      int count = 0;\n      for (; count < 2 && operations.hasNext(); ) {\n         ListPage<Operation> result = operations.next();\n         if (!result.isEmpty()) {\n            operation = result.get(0);\n            count++;\n         }\n      }\n      if (count < 2) {\n         throw new SkipException(\"Not enough global operations\");\n      }\n      assertEquals(count, 2);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"listWithOptions\")\n   public void testGetOperation() {\n      Operation result = api().get(operation.selfLink());\n      assertNotNull(result);\n      assertEquals(result.name(), operation.name()); // Checking state besides name can lead to flaky test.\n   }\n\n   public void listInRegionWithOptions() {\n      Iterator<ListPage<Operation>> operations = api().listInRegion(DEFAULT_REGION_NAME, maxResults(1));\n\n      // make sure that in spite of having only one result per page we get at least two results\n      int count = 0;\n      for (; count < 2 && operations.hasNext(); ) {\n         ListPage<Operation> result = operations.next();\n         if (!result.isEmpty()) {\n            count++;\n         }\n      }\n      if (count < 2) {\n         throw new SkipException(\"Not enough region operations\");\n      }\n      assertEquals(count, 2);\n   }\n\n   public void listInZoneWithOptions() {\n      Iterator<ListPage<Operation>> operations = api().listInZone(DEFAULT_ZONE_NAME, maxResults(1));\n\n      // make sure that in spite of having only one result per page we get at least two results\n      int count = 0;\n      for (; count < 2 && operations.hasNext(); ) {\n         ListPage<Operation> result = operations.next();\n         if (!result.isEmpty()) {\n            count++;\n         }\n      }\n      if (count < 2) {\n         throw new SkipException(\"Not enough zone operations\");\n      }\n      assertEquals(count, 2);\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/OperationApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.jclouds.googlecomputeengine.options.ListOptions.Builder.filter;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNull;\n\nimport java.net.URI;\n\nimport okhttp3.mockwebserver.MockResponse;\n\nimport org.jclouds.googlecloud.domain.ForwardingListPage;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.domain.Operation;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiMockTest;\nimport org.jclouds.googlecomputeengine.parse.ParseGlobalOperationListTest;\nimport org.jclouds.googlecomputeengine.parse.ParseGlobalOperationTest;\nimport org.jclouds.googlecomputeengine.parse.ParseRegionOperationTest;\nimport org.jclouds.googlecomputeengine.parse.ParseZoneOperationTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n\n@Test(groups = \"unit\", testName = \"OperationApiMockTest\", singleThreaded = true)\npublic class OperationApiMockTest extends BaseGoogleComputeEngineApiMockTest {\n\n   public void get() throws Exception {\n      server.enqueue(jsonResponse(\"/global_operation.json\"));\n\n      assertEquals(operationApi().get(URI.create(url(\"/projects/party/global/operations/operation-1354084865060\"))),\n            new ParseGlobalOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/projects/party/global/operations/operation-1354084865060\");\n   }\n\n   public void get_4xx() throws Exception {\n      server.enqueue(response404());\n\n      assertNull(operationApi().get(URI.create(url(\"/projects/party/global/operations/operation-1354084865060\"))));\n      assertSent(server, \"GET\", \"/projects/party/global/operations/operation-1354084865060\");\n   }\n\n   public void delete() throws Exception {\n      server.enqueue(new MockResponse().setBody(\"\"));\n\n      operationApi().delete(URI.create(url(\"/projects/party/global/operations/operation-1352178598164-4cdcc9d031510-4aa46279\")));\n      assertSent(server, \"DELETE\", \"/projects/party/global/operations/operation-1352178598164-4cdcc9d031510-4aa46279\");\n   }\n\n   public void delete_4xx() throws Exception {\n      server.enqueue(response404());\n\n      operationApi().delete(URI.create(url(\"/projects/party/global/operations/operation-1352178598164-4cdcc9d031510-4aa46279\")));\n      assertSent(server, \"DELETE\", \"/projects/party/global/operations/operation-1352178598164-4cdcc9d031510-4aa46279\");\n   }\n\n   public void list() throws Exception {\n      server.enqueue(jsonResponse(\"/global_operation_list.json\"));\n\n      assertEquals(operationApi().list().next(), new ParseGlobalOperationListTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/projects/party/global/operations\");\n   }\n\n   public void list_empty() throws Exception {\n      server.enqueue(jsonResponse(\"/list_empty.json\"));\n\n      assertFalse(operationApi().list().hasNext());\n      assertSent(server, \"GET\", \"/projects/party/global/operations\");\n   }\n\n   public void listPage_options() throws Exception {\n      server.enqueue(jsonResponse(\"/global_operation_list.json\"));\n\n      assertEquals(operationApi().listPage(\"CglPUEVSQVRJT04SOzU5MDQyMTQ4Nzg1Mi5vcGVyYXRpb24tMTM1Mj\" +\n            \"I0NDI1ODAzMC00Y2RkYmU2YTJkNmIwLWVkMzIyMzQz\",\n            filter(\"status eq done\").maxResults(3)), new ParseGlobalOperationListTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/projects/party/global/operations?pageToken=CglPUEVSQVRJT04SOzU5MDQyMTQ4Nzg1Mi5vcG\" +\n                      \"VyYXRpb24tMTM1MjI0NDI1ODAzMC00Y2RkYmU2YTJkNmIwLWVkMzIyMzQz&\" +\n                      \"filter=status%20eq%20done&maxResults=3\");\n   }\n\n   private ListPage<Operation> regionList() {\n      return ForwardingListPage.create( //\n            ImmutableList.of(new ParseRegionOperationTest().expected(url(\"/projects\"))), // items\n            null // nextPageToken\n      );\n   }\n\n   public void listInRegion() throws Exception {\n      server.enqueue(jsonResponse(\"/region_operation_list.json\"));\n\n      assertEquals(operationApi().listInRegion(\"us-central1\").next(), regionList());\n      assertSent(server, \"GET\", \"/projects/party/regions/us-central1/operations\");\n   }\n\n   public void listInRegion_empty() throws Exception {\n      server.enqueue(jsonResponse(\"/list_empty.json\"));\n\n      assertFalse(operationApi().listInRegion(\"us-central1\").hasNext());\n      assertSent(server, \"GET\", \"/projects/party/regions/us-central1/operations\");\n   }\n\n   public void listPageInRegion() throws Exception {\n      server.enqueue(jsonResponse(\"/region_operation_list.json\"));\n\n      assertEquals(operationApi().listPageInRegion(\"us-central1\", \"CglPUEVSQVRJT04SOzU5MDQyMTQ4Nzg1Mi5vcGVyYXRpb24tMTM1MjI0NDI1ODAzMC00Y2RkYmU2YTJkNmIwLWVkMzIyMzQz\",\n            filter(\"status eq done\").maxResults(3)).toString(), regionList().toString());\n      assertSent(server, \"GET\", \"/projects/party/regions/us-central1/operations?pageToken=CglPUEVSQVRJT04SOzU5MDQyMTQ4Nzg1Mi5vcG\" +\n                  \"VyYXRpb24tMTM1MjI0NDI1ODAzMC00Y2RkYmU2YTJkNmIwLWVkMzIyMzQz&\" +\n                  \"filter=\" +\n                  \"status%20eq%20done&\" +\n                  \"maxResults=3\");\n   }\n\n   private ListPage<Operation> zoneList() {\n      return ForwardingListPage.create( //\n            ImmutableList.of(new ParseZoneOperationTest().expected(url(\"/projects\"))), // items\n            null // nextPageToken\n      );\n   }\n\n   public void listInZone() throws Exception {\n      server.enqueue(jsonResponse(\"/zone_operation_list.json\"));\n\n      assertEquals(operationApi().listInZone(\"us-central1-a\").next(), zoneList());\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/operations\");\n   }\n\n   public void listInZone_empty() throws Exception {\n      server.enqueue(jsonResponse(\"/list_empty.json\"));\n\n      assertFalse(operationApi().listInZone(\"us-central1-a\").hasNext());\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/operations\");\n   }\n\n   public void listPageInZone() throws Exception {\n      server.enqueue(jsonResponse(\"/zone_operation_list.json\"));\n\n      assertEquals(operationApi().listPageInZone(\"us-central1-a\",\n            \"CglPUEVSQVRJT04SOzU5MDQyMTQ4Nzg1Mi5vcGVyYXRpb24tMTM1MjI0NDI1ODAzMC00Y2RkYmU2YTJkNmIwLWVkMzIyMzQz\",\n            filter(\"status eq done\").maxResults(3)).toString(), zoneList().toString());\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/operations?pageToken=CglPUEVSQVRJT04SOzU5MDQyMTQ4Nzg1Mi5vcG\" +\n                  \"VyYXRpb24tMTM1MjI0NDI1ODAzMC00Y2RkYmU2YTJkNmIwLWVkMzIyMzQz&\" +\n                  \"filter=\" +\n                  \"status%20eq%20done&\" +\n                  \"maxResults=3\");\n   }\n\n   OperationApi operationApi(){\n      return api().operations();\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/ProjectApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static java.util.concurrent.TimeUnit.MILLISECONDS;\nimport static org.jclouds.util.Predicates2.retry;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport org.jclouds.googlecomputeengine.domain.Metadata;\nimport org.jclouds.googlecomputeengine.domain.Operation;\nimport org.jclouds.googlecomputeengine.domain.Operation.Status;\nimport org.jclouds.googlecomputeengine.domain.Project;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\n\npublic class ProjectApiLiveTest extends BaseGoogleComputeEngineApiLiveTest {\n\n   private static final String METADATA_ITEM_KEY = \"projectLiveTestTestProp\";\n   private static final String METADATA_ITEM_VALUE = \"projectLiveTestTestValue\";\n\n   private Project project;\n   private int initialMetadataSize;\n   private String initialFingerprint;\n\n   @Test(groups = \"live\")\n   public void getProject() {\n      project = api.project().get();\n      assertNotNull(project);\n      assertNotNull(project.id());\n      assertNotNull(project.name());\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"getProject\")\n   public void addItemToMetadata() {\n      initialMetadataSize = project.commonInstanceMetadata().size();\n      initialFingerprint = project.commonInstanceMetadata().fingerprint();\n      Metadata metadata = project.commonInstanceMetadata().put(METADATA_ITEM_KEY, METADATA_ITEM_VALUE);\n      assertOperationDoneSuccessfully(api.project().setCommonInstanceMetadata(metadata));\n      project = api.project().get();\n      assertNotNull(project);\n      assertTrue(project.commonInstanceMetadata().containsKey(METADATA_ITEM_KEY), project.toString());\n      assertEquals(project.commonInstanceMetadata().get(METADATA_ITEM_KEY), METADATA_ITEM_VALUE);\n      assertNotNull(project.commonInstanceMetadata().fingerprint());\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"addItemToMetadata\", alwaysRun = true)\n   public void testDeleteItemFromMetadata() {\n      Metadata metadata = project.commonInstanceMetadata().remove(METADATA_ITEM_KEY);\n      assertOperationDoneSuccessfully(api.project().setCommonInstanceMetadata(metadata));\n      project = api.project().get();\n      assertNotNull(project);\n      assertFalse(project.commonInstanceMetadata().containsKey(METADATA_ITEM_KEY));\n      assertEquals(project.commonInstanceMetadata().size(), initialMetadataSize);\n      assertEquals(project.commonInstanceMetadata().fingerprint(), initialFingerprint);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"getProject\")\n   public void testSetUsageExportBucket() {\n      AtomicReference<Operation> o = new AtomicReference<Operation>(api.project().setUsageExportBucket(\n            \"unexisting-bucket\", \"test-\"));\n\n      retry(new Predicate<AtomicReference<Operation>>() {\n         @Override\n         public boolean apply(AtomicReference<Operation> input) {\n            input.set(api.operations().get(input.get().selfLink()));\n            return Status.DONE == input.get().status();\n         }\n      }, operationDoneTimeout, operationDoneInterval, MILLISECONDS).apply(o);\n\n      assertEquals(o.get().status(), Status.DONE);\n      assertEquals(o.get().error().errors().get(0).code(), \"EXTERNAL_RESOURCE_NOT_FOUND\");\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/ProjectApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\n\nimport org.jclouds.googlecomputeengine.domain.Metadata;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiMockTest;\nimport org.jclouds.googlecomputeengine.parse.ParseGlobalOperationTest;\nimport org.jclouds.googlecomputeengine.parse.ParseMetadataTest;\nimport org.jclouds.googlecomputeengine.parse.ParseProjectTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ProjectApiMockTest\", singleThreaded = true)\npublic class ProjectApiMockTest extends BaseGoogleComputeEngineApiMockTest {\n\n   public void get() throws Exception {\n      server.enqueue(jsonResponse(\"/project.json\"));\n\n      assertEquals(projectApi().get(), new ParseProjectTest().expected(url(\"/projects\")));\n\n      assertSent(server, \"GET\", \"/projects/party\");\n   }\n\n   public void get_4xx() throws Exception {\n      server.enqueue(response404());\n\n      assertNull(projectApi().get());\n\n      assertSent(server, \"GET\", \"/projects/party\");\n   }\n\n   public void setCommonInstanceMetadata() throws Exception {\n      server.enqueue(jsonResponse(\"/global_operation.json\"));\n\n      Metadata expected = new ParseMetadataTest().expected();\n      assertEquals(projectApi().setCommonInstanceMetadata(expected), new ParseGlobalOperationTest().expected(url(\"/projects\")));\n\n      assertSent(server, \"POST\", \"/projects/party/setCommonInstanceMetadata\",\n            stringFromResource(\"/metadata.json\"));\n   }\n\n   public void setUsageExportBucket() throws Exception {\n      server.enqueue(jsonResponse(\"/global_operation.json\"));\n\n      assertEquals(projectApi().setUsageExportBucket(\"bucket-name\", \"report-name-prefix\"),\n            new ParseGlobalOperationTest().expected(url(\"/projects\")));\n\n      assertSent(server, \"POST\", \"/projects/party/setUsageExportBucket\",\n            \"{\\\"bucketName\\\": \\\"bucket-name\\\",\\\"reportNamePrefix\\\": \\\"report-name-prefix\\\"}\");\n   }\n\n   ProjectApi projectApi() {\n      return api().project();\n   }\n\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/RegionApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.jclouds.googlecomputeengine.options.ListOptions.Builder.maxResults;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Iterator;\nimport java.util.List;\n\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.domain.Region;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiLiveTest;\nimport org.testng.annotations.Test;\n\npublic class RegionApiLiveTest extends BaseGoogleComputeEngineApiLiveTest {\n\n   private Region region;\n\n   private RegionApi api() {\n      return api.regions();\n   }\n\n   @Test(groups = \"live\")\n   public void testListRegion() {\n      Iterator<ListPage<Region>> pageIterator = api().list(maxResults(1));\n      assertTrue(pageIterator.hasNext());\n\n      List<Region> regionAsList = pageIterator.next();\n\n      assertEquals(regionAsList.size(), 1);\n\n      this.region = regionAsList.get(0);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testListRegion\")\n   public void testGetRegion() {\n      Region region = api().get(this.region.name());\n      assertNotNull(region);\n      assertRegionEquals(region, this.region);\n   }\n\n   private void assertRegionEquals(Region result, Region expected) {\n      assertEquals(result.name(), expected.name());\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/RegionApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNull;\n\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiMockTest;\n\nimport org.jclouds.googlecomputeengine.parse.ParseRegionListTest;\nimport org.jclouds.googlecomputeengine.parse.ParseRegionTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"RegionApiMockTest\", singleThreaded = true)\npublic class RegionApiMockTest extends BaseGoogleComputeEngineApiMockTest {\n\n   public void get() throws Exception {\n      server.enqueue(jsonResponse(\"/region_get.json\"));\n\n      assertEquals(regionApi().get(\"us-central1\"), new ParseRegionTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/projects/party/regions/us-central1\");\n   }\n\n   public void get_4xx() throws Exception {\n      server.enqueue(response404());\n\n      assertNull(regionApi().get(\"us-central1\"));\n      assertSent(server, \"GET\", \"/projects/party/regions/us-central1\");\n   }\n\n   public void list() throws Exception {\n      server.enqueue(jsonResponse(\"/region_list.json\"));\n\n      assertEquals(regionApi().list().next(), new ParseRegionListTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/projects/party/regions\");\n   }\n\n   public void list_empty() throws Exception {\n      server.enqueue(jsonResponse(\"/list_empty.json\"));\n\n      assertFalse(regionApi().list().hasNext());\n      assertSent(server, \"GET\", \"/projects/party/regions\");\n   }\n\n   RegionApi regionApi() {\n      return api().regions();\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/RouteApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.Iterator;\nimport java.util.List;\n\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.domain.Route;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiLiveTest;\nimport org.jclouds.googlecomputeengine.options.ListOptions;\nimport org.jclouds.googlecomputeengine.options.RouteOptions;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"RouteApiLiveTest\")\npublic class RouteApiLiveTest extends BaseGoogleComputeEngineApiLiveTest {\n\n   private static final String DEST_RANGE = \"20.10.0.0/16\";\n   private static final String IPV4_RANGE = \"10.0.0.0/8\";\n   private static final String ROUTE_NAME = \"route-api-live-test-route\";\n   private static final String ROUTE_NETWORK_NAME = \"route-api-live-test-network\";\n\n   private RouteApi api() {\n      return api.routes();\n   }\n\n   @Test(groups = \"live\")\n   public void testInsertRoute() {\n      assertOperationDoneSuccessfully(api.networks().createLegacy(ROUTE_NETWORK_NAME, IPV4_RANGE));\n      assertOperationDoneSuccessfully(api().createInNetwork(ROUTE_NAME,\n              getNetworkUrl(ROUTE_NETWORK_NAME),\n              new RouteOptions().addTag(\"footag\")\n                      .addTag(\"bartag\")\n                      .description(\"RouteApi Live Test\")\n                      .destRange(DEST_RANGE)\n                      .priority(1000)\n                      .nextHopGateway(getGatewayUrl(DEFAULT_GATEWAY_NAME))));\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testInsertRoute\")\n   public void testGetRoute() {\n      Route route = api().get(ROUTE_NAME);\n\n      assertNotNull(route);\n      assertRouteEquals(route);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testGetRoute\")\n   public void testListRoute() {\n\n      Iterator<ListPage<Route>> routes = api().list(new ListOptions()\n              .filter(\"name eq \" + ROUTE_NAME));\n\n      List<Route> routesAsList = routes.next();\n\n      assertEquals(routesAsList.size(), 1);\n\n      assertRouteEquals(routesAsList.get(0));\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testListRoute\", alwaysRun = true)\n   public void testDeleteRoute() {\n      assertOperationDoneSuccessfully(api().delete(ROUTE_NAME));\n      assertOperationDoneSuccessfully(api.networks().delete(ROUTE_NETWORK_NAME));\n   }\n\n   private void assertRouteEquals(Route result) {\n      assertEquals(result.name(), ROUTE_NAME);\n      assertEquals(result.destRange(), DEST_RANGE);\n      assertEquals(result.nextHopGateway(), getGatewayUrl(DEFAULT_GATEWAY_NAME));\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/RouteApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNull;\n\nimport java.net.URI;\n\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiMockTest;\nimport org.jclouds.googlecomputeengine.options.RouteOptions;\nimport org.jclouds.googlecomputeengine.parse.ParseGlobalOperationTest;\nimport org.jclouds.googlecomputeengine.parse.ParseRouteListTest;\nimport org.jclouds.googlecomputeengine.parse.ParseRouteTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"RouteApiMockTest\", singleThreaded = true)\npublic class RouteApiMockTest extends BaseGoogleComputeEngineApiMockTest {\n\n   public void get() throws Exception {\n      server.enqueue(jsonResponse(\"/route_get.json\"));\n\n      assertEquals(routeApi().get(\"default-route-c99ebfbed0e1f375\"),\n            new ParseRouteTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/projects/party/global/routes/default-route-c99ebfbed0e1f375\");\n   }\n\n   public void get_4xx() throws Exception {\n      server.enqueue(response404());\n\n      assertNull(routeApi().get(\"default-route-c99ebfbed0e1f375\"));\n      assertSent(server, \"GET\", \"/projects/party/global/routes/default-route-c99ebfbed0e1f375\");\n   }\n\n   public void insert() throws Exception {\n      server.enqueue(jsonResponse(\"/global_operation.json\"));\n\n      assertEquals(routeApi().createInNetwork(\"default-route-c99ebfbed0e1f375\",\n            URI.create(url(\"/projects/party/global/networks/default\")),\n            new RouteOptions().addTag(\"fooTag\")\n                    .addTag(\"barTag\")\n                    .description(\"Default route to the virtual network.\")\n            .destRange(\"10.240.0.0/16\")\n            .priority(1000)\n            .nextHopNetwork(URI.create(url(\"/projects/party/global/networks/default\")))),\n            new ParseGlobalOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"POST\", \"/projects/party/global/routes\",\n            stringFromResource(\"/route_insert.json\"));\n   }\n\n   public void delete() throws Exception {\n      server.enqueue(jsonResponse(\"/global_operation.json\"));\n\n      assertEquals(routeApi().delete(\"default-route-c99ebfbed0e1f375\"),\n            new ParseGlobalOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"DELETE\", \"/projects/party/global/routes/default-route-c99ebfbed0e1f375\");\n   }\n\n   public void delete_4xx() throws Exception {\n      server.enqueue(response404());\n\n      assertNull(routeApi().delete(\"default-route-c99ebfbed0e1f375\"));\n      assertSent(server, \"DELETE\", \"/projects/party/global/routes/default-route-c99ebfbed0e1f375\");\n   }\n\n   public void list() throws Exception {\n      server.enqueue(jsonResponse(\"/route_list.json\"));\n\n      assertEquals(routeApi().list().next(), new ParseRouteListTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/projects/party/global/routes\");\n   }\n\n   public void list_empty() throws Exception {\n      server.enqueue(jsonResponse(\"/list_empty.json\"));\n\n      assertFalse(routeApi().list().hasNext());\n      assertSent(server, \"GET\", \"/projects/party/global/routes\");\n   }\n\n   RouteApi routeApi() {\n      return api().routes();\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/SnapshotApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.jclouds.googlecomputeengine.options.ListOptions.Builder.filter;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Iterator;\nimport java.util.List;\n\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.domain.Disk;\nimport org.jclouds.googlecomputeengine.domain.Snapshot;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiLiveTest;\nimport org.jclouds.googlecomputeengine.options.DiskCreationOptions;\nimport org.testng.annotations.Test;\n\npublic class SnapshotApiLiveTest extends BaseGoogleComputeEngineApiLiveTest {\n\n   private static final String DISK_NAME = \"snapshot-api-live-test-disk\";\n   private static final String SNAPSHOT_NAME = \"snapshot-api-live-test-snapshot\";\n\n   private Disk disk;\n   private SnapshotApi api() {\n      return api.snapshots();\n   }\n\n   private DiskApi diskApi() {\n      return api.disksInZone(DEFAULT_ZONE_NAME);\n   }\n\n   @Test(groups = \"live\")\n   public void testCreateSnapshot() {\n      assertOperationDoneSuccessfully(diskApi().create(DISK_NAME,\n            new DiskCreationOptions.Builder().sizeGb(1).build()));\n      disk = diskApi().get(DISK_NAME);\n\n      assertOperationDoneSuccessfully(diskApi().createSnapshot(DISK_NAME, SNAPSHOT_NAME));\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testCreateSnapshot\")\n   public void testGetSnapshot() {\n      Snapshot snapshot = api().get(SNAPSHOT_NAME);\n\n      assertEquals(snapshot.name(), SNAPSHOT_NAME);\n      assertSnapshotEquals(snapshot);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testGetSnapshot\")\n   public void testListSnapshot() {\n      Iterator<ListPage<Snapshot>> snapshots = api().list(filter(\"name eq \" + SNAPSHOT_NAME));\n\n      List<Snapshot> snapshotsAsList = snapshots.next();\n\n      assertEquals(snapshotsAsList.size(), 1);\n\n      assertSnapshotEquals(snapshotsAsList.get(0));\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testListSnapshot\", alwaysRun = true)\n   public void testDeleteDisk() {\n      assertOperationDoneSuccessfully(diskApi().delete(DISK_NAME));\n      assertOperationDoneSuccessfully(api().delete(SNAPSHOT_NAME));\n   }\n\n   private void assertSnapshotEquals(Snapshot result) {\n      assertEquals(result.name(), SNAPSHOT_NAME);\n      assertEquals(result.sourceDisk(), disk.selfLink());\n      assertEquals(result.diskSizeGb(), disk.sizeGb());\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/SnapshotApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNull;\n\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiMockTest;\nimport org.jclouds.googlecomputeengine.parse.ParseGlobalOperationTest;\nimport org.jclouds.googlecomputeengine.parse.ParseSnapshotListTest;\nimport org.jclouds.googlecomputeengine.parse.ParseSnapshotTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"SnapshotApiMockTest\", singleThreaded = true)\npublic class SnapshotApiMockTest extends BaseGoogleComputeEngineApiMockTest {\n\n   public void get() throws Exception {\n      server.enqueue(jsonResponse(\"/snapshot_get.json\"));\n\n      assertEquals(snapshotApi().get(\"test-snap\"),\n            new ParseSnapshotTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/projects/party/global/snapshots/test-snap\");\n   }\n\n   public void get_4xx() throws Exception {\n      server.enqueue(response404());\n\n      assertNull(snapshotApi().get(\"test-snap\"));\n      assertSent(server, \"GET\", \"/projects/party/global/snapshots/test-snap\");\n   }\n\n   public void delete() throws Exception {\n      server.enqueue(jsonResponse(\"/global_operation.json\"));\n\n      assertEquals(snapshotApi().delete(\"test-snap\"),\n            new ParseGlobalOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"DELETE\", \"/projects/party/global/snapshots/test-snap\");\n   }\n\n   public void delete_4xx() throws Exception {\n      server.enqueue(response404());\n\n      assertNull(snapshotApi().delete(\"test-snap\"));\n      assertSent(server, \"DELETE\", \"/projects/party/global/snapshots/test-snap\");\n   }\n\n   public void list() throws Exception {\n      server.enqueue(jsonResponse(\"/snapshot_list.json\"));\n\n      assertEquals(snapshotApi().list().next(), new ParseSnapshotListTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/projects/party/global/snapshots\");\n   }\n\n   public void list_empty() throws Exception {\n      server.enqueue(jsonResponse(\"/list_empty.json\"));\n\n      assertFalse(snapshotApi().list().hasNext());\n      assertSent(server, \"GET\", \"/projects/party/global/snapshots\");\n   }\n\n   SnapshotApi snapshotApi() {\n      return api().snapshots();\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/SubnetworkApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.jclouds.googlecomputeengine.options.ListOptions.Builder.filter;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.Iterator;\nimport java.util.List;\n\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.domain.Network;\nimport org.jclouds.googlecomputeengine.domain.Subnetwork;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiLiveTest;\nimport org.jclouds.googlecomputeengine.options.SubnetworkCreationOptions;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"SubnetworkApiLiveTest\")\npublic class SubnetworkApiLiveTest extends BaseGoogleComputeEngineApiLiveTest {\n\n   private static final String SUBNETWORK_NAME = \"subnetwork-api-live-test-network\";\n   private static final String SUBNETWORK_RANGE = \"10.0.0.0/8\";\n\n   private SubnetworkApi api() {\n      return api.subnetworksInRegion(DEFAULT_REGION_NAME);\n   }\n\n   @Test\n   public void testInsertSubnetwork() {\n      assertOperationDoneSuccessfully(api.networks().createCustom(SUBNETWORK_NAME));\n      Network network = api.networks().get(SUBNETWORK_NAME);\n      assertNotNull(network);\n\n      SubnetworkCreationOptions opts = SubnetworkCreationOptions.create(SUBNETWORK_NAME, SUBNETWORK_NAME,\n            network.selfLink(), SUBNETWORK_RANGE, getDefaultRegionUrl(), false);\n      assertOperationDoneSuccessfully(api().createInNetwork(opts));\n   }\n\n   @Test(dependsOnMethods = \"testInsertSubnetwork\")\n   public void testGetSubnetwork() {\n      Subnetwork subnet = api().get(SUBNETWORK_NAME);\n      assertNotNull(subnet);\n      assertSubnetworkEquals(subnet);\n   }\n\n   @Test(dependsOnMethods = \"testInsertSubnetwork\")\n   public void testListSubnetworks() {\n      Iterator<ListPage<Subnetwork>> subnets = api().list(filter(\"name eq \" + SUBNETWORK_NAME));\n      List<Subnetwork> subnetsAsList = subnets.next();\n\n      assertEquals(subnetsAsList.size(), 1);\n      assertSubnetworkEquals(subnetsAsList.get(0));\n   }\n\n   @Test(dependsOnMethods = { \"testListSubnetworks\", \"testGetSubnetwork\" }, alwaysRun = true)\n   public void testDeleteSubnetwork() {\n      assertOperationDoneSuccessfully(api().delete(SUBNETWORK_NAME));\n      assertOperationDoneSuccessfully(api.networks().delete(SUBNETWORK_NAME));\n   }\n\n   private void assertSubnetworkEquals(Subnetwork result) {\n      assertEquals(result.name(), SUBNETWORK_NAME);\n      assertEquals(result.ipCidrRange(), SUBNETWORK_RANGE);\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/SubnetworkApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNull;\n\nimport java.net.URI;\n\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiMockTest;\nimport org.jclouds.googlecomputeengine.options.SubnetworkCreationOptions;\nimport org.jclouds.googlecomputeengine.parse.ParseSubnetworkListTest;\nimport org.jclouds.googlecomputeengine.parse.ParseSubnetworkTest;\nimport org.jclouds.googlecomputeengine.parse.ParseOperationTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"SubnetworkApiMockTest\", singleThreaded = true)\npublic class SubnetworkApiMockTest extends BaseGoogleComputeEngineApiMockTest {\n\n   public void get() throws Exception {\n      server.enqueue(jsonResponse(\"/subnetwork_get.json\"));\n\n      assertEquals(subnetworkApi().get(\"jclouds-test\"),\n            new ParseSubnetworkTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/projects/party/regions/someregion/subnetworks/jclouds-test\");\n   }\n\n   public void get_4xx() throws Exception {\n      server.enqueue(response404());\n\n      assertNull(subnetworkApi().get(\"jclouds-test\"));\n      assertSent(server, \"GET\", \"/projects/party/regions/someregion/subnetworks/jclouds-test\");\n   }\n\n   public void insert() throws Exception {\n      server.enqueue(jsonResponse(\"/operation.json\"));\n\n      assertEquals(subnetworkApi().createInNetwork(SubnetworkCreationOptions.create(\n              \"jclouds-test\",\n              \"my subnetwork\",\n              URI.create(url(\"/projects/party/global/networks/mynetwork\")),\n              \"10.0.0.0/24\",\n              URI.create(url(\"/projects/party/regions/someregion\")),\n              false)), new ParseOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"POST\", \"/projects/party/regions/someregion/subnetworks\",\n            stringFromResource(\"/subnetwork_insert.json\"));\n   }\n\n   public void delete() throws Exception {\n      server.enqueue(jsonResponse(\"/operation.json\"));\n\n      assertEquals(subnetworkApi().delete(\"jclouds-test\"),\n            new ParseOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"DELETE\", \"/projects/party/regions/someregion/subnetworks/jclouds-test\");\n   }\n\n   public void delete_4xx() throws Exception {\n      server.enqueue(response404());\n\n      assertNull(subnetworkApi().delete(\"jclouds-test\"));\n      assertSent(server, \"DELETE\", \"/projects/party/regions/someregion/subnetworks/jclouds-test\");\n   }\n\n   public void list() throws Exception {\n      server.enqueue(jsonResponse(\"/subnetwork_list.json\"));\n\n      assertEquals(subnetworkApi().list().next(), new ParseSubnetworkListTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/projects/party/regions/someregion/subnetworks\");\n   }\n\n   public void list_empty() throws Exception {\n      server.enqueue(jsonResponse(\"/list_empty.json\"));\n\n      assertFalse(subnetworkApi().list().hasNext());\n      assertSent(server, \"GET\", \"/projects/party/regions/someregion/subnetworks\");\n   }\n\n   SubnetworkApi subnetworkApi() {\n      return api().subnetworksInRegion(\"someregion\");\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/TargetHttpProxyApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.jclouds.googlecomputeengine.options.ListOptions.Builder.filter;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.domain.TargetHttpProxy;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiLiveTest;\nimport org.jclouds.googlecomputeengine.options.BackendServiceOptions;\nimport org.jclouds.googlecomputeengine.options.UrlMapOptions;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Iterables;\n\npublic class TargetHttpProxyApiLiveTest extends BaseGoogleComputeEngineApiLiveTest {\n\n   public static final String TARGET_HTTP_PROXY_NAME = \"target-http-proxy-api-live-test-target-http-proxy\";\n   public static final String TARGET_HTTP_PROXY_URL_MAP_NAME = \"target-http-proxy-api-live-test-url-map\";\n   public static final String URL_MAP_DEFAULT_SERVICE_NAME = \"target-http-proxy-api-live-test-backend-service\";\n   public static final String HEALTH_CHECK_NAME = \"target-http-proxy-api-live-test-health-check\";\n\n   private TargetHttpProxyApi api() {\n      return api.targetHttpProxies();\n   }\n\n   @Test(groups = \"live\")\n   public void testInsertTargetHttpProxy() {\n\n      // Create resources that are required for target http proxies\n\n      assertOperationDoneSuccessfully(api.httpHeathChecks().insert(HEALTH_CHECK_NAME));\n\n      List<URI> healthChecks = ImmutableList.of(getHealthCheckUrl(HEALTH_CHECK_NAME));\n      BackendServiceOptions b = new BackendServiceOptions.Builder(URL_MAP_DEFAULT_SERVICE_NAME, healthChecks)\n                                                           .build();\n\n      assertOperationDoneSuccessfully(api.backendServices().create(b));\n\n      UrlMapOptions map = new UrlMapOptions.Builder().name(TARGET_HTTP_PROXY_URL_MAP_NAME).description(\"simple url map\")\n                                             .defaultService(getBackendServiceUrl(URL_MAP_DEFAULT_SERVICE_NAME)).build();\n      assertOperationDoneSuccessfully(api.urlMaps().create(map));\n\n      UrlMapOptions map2 = new UrlMapOptions.Builder().name(TARGET_HTTP_PROXY_URL_MAP_NAME + \"-2\")\n            .description(\"a second simple url map\")\n            .defaultService(getBackendServiceUrl(URL_MAP_DEFAULT_SERVICE_NAME))\n            .build();\n      assertOperationDoneSuccessfully(api.urlMaps().create(map2));\n\n\n      assertOperationDoneSuccessfully(api().create(TARGET_HTTP_PROXY_NAME, getUrlMapUrl(TARGET_HTTP_PROXY_URL_MAP_NAME)));\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testInsertTargetHttpProxy\")\n   public void testGetTargetHttpProxy() {\n      TargetHttpProxy targetHttpProxy = api().get(TARGET_HTTP_PROXY_NAME);\n      assertNotNull(targetHttpProxy);\n      assertTargetHttpProxyEquals(targetHttpProxy, getUrlMapUrl(TARGET_HTTP_PROXY_URL_MAP_NAME));\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testGetTargetHttpProxy\")\n   public void testSetUrlMapTargetHttpProxy() {\n      assertOperationDoneSuccessfully(api().setUrlMap(TARGET_HTTP_PROXY_NAME,\n                                                     getUrlMapUrl(TARGET_HTTP_PROXY_URL_MAP_NAME + \"-2\")));\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testSetUrlMapTargetHttpProxy\")\n   public void testListTargetHttpProxy() {\n      ListPage<TargetHttpProxy> targetHttpProxies = api().list(filter(\"name eq \" + TARGET_HTTP_PROXY_NAME)).next();\n\n      assertEquals(targetHttpProxies.size(), 1);\n\n      assertTargetHttpProxyEquals(Iterables.getOnlyElement(targetHttpProxies),\n                                  getUrlMapUrl(TARGET_HTTP_PROXY_URL_MAP_NAME + \"-2\"));\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testListTargetHttpProxy\", alwaysRun = true)\n   public void testDeleteTargetHttpProxy() {\n      assertOperationDoneSuccessfully(api().delete(TARGET_HTTP_PROXY_NAME));\n\n      //remove extra resources created\n      assertOperationDoneSuccessfully(api.urlMaps().delete(TARGET_HTTP_PROXY_URL_MAP_NAME));\n      assertOperationDoneSuccessfully(api.urlMaps().delete(TARGET_HTTP_PROXY_URL_MAP_NAME + \"-2\"));\n      assertOperationDoneSuccessfully(api.backendServices().delete(URL_MAP_DEFAULT_SERVICE_NAME));\n      assertOperationDoneSuccessfully(api.httpHeathChecks().delete(HEALTH_CHECK_NAME));\n\n   }\n\n   private void assertTargetHttpProxyEquals(TargetHttpProxy result, URI urlMap) {\n      assertEquals(result.name(), TARGET_HTTP_PROXY_NAME);\n      assertEquals(result.urlMap(), urlMap);\n   }\n\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/TargetHttpProxyApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.AssertJUnit.assertNull;\n\nimport java.net.URI;\n\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiMockTest;\nimport org.jclouds.googlecomputeengine.options.TargetHttpProxyOptions;\nimport org.jclouds.googlecomputeengine.parse.ParseOperationTest;\nimport org.jclouds.googlecomputeengine.parse.ParseTargetHttpProxyListTest;\nimport org.jclouds.googlecomputeengine.parse.ParseTargetHttpProxyTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"TargetHttpProxyApiMockTest\", singleThreaded = true)\npublic class TargetHttpProxyApiMockTest extends BaseGoogleComputeEngineApiMockTest {\n\n   public void get() throws Exception {\n      server.enqueue(jsonResponse(\"/target_http_proxy_get.json\"));\n\n      assertEquals(targetHttpProxyApi().get(\"jclouds-test\"),\n            new ParseTargetHttpProxyTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/projects/party/global/targetHttpProxies/jclouds-test\");\n   }\n\n   public void get_4xx() throws Exception {\n      server.enqueue(response404());\n\n      assertNull(targetHttpProxyApi().get(\"jclouds-test\"));\n      assertSent(server, \"GET\", \"/projects/party/global/targetHttpProxies/jclouds-test\");\n   }\n\n   public void insert() throws Exception {\n      server.enqueue(jsonResponse(\"/operation.json\"));\n\n      URI urlMap = URI.create(url(\"/projects/myproject/global/urlMaps/jclouds-test\"));\n      assertEquals(targetHttpProxyApi().create(\"jclouds-test\", urlMap), new ParseOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"POST\", \"/projects/party/global/targetHttpProxies\",\n            stringFromResource(\"/target_http_proxy_insert.json\"));\n   }\n\n   public void insert_options() throws Exception {\n      server.enqueue(jsonResponse(\"/operation.json\"));\n\n      URI urlMap = URI.create(url(\"/projects/myproject/global/urlMaps/jclouds-test\"));\n      TargetHttpProxyOptions options = new TargetHttpProxyOptions.Builder(\"jclouds-test\", urlMap).description(\"test\").build();\n      assertEquals(targetHttpProxyApi().create(options), new ParseOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"POST\", \"/projects/party/global/targetHttpProxies\",\n            \"{\" +\n            \"  \\\"name\\\": \\\"jclouds-test\\\",\" +\n            \"  \\\"urlMap\\\": \\\"\" + url(\"/projects/myproject/global/urlMaps/jclouds-test\") + \"\\\",\" +\n            \"  \\\"description\\\": \\\"test\\\"\" +\n            \"}\");\n   }\n\n   public void delete() throws Exception {\n      server.enqueue(jsonResponse(\"/operation.json\"));\n\n      assertEquals(targetHttpProxyApi().delete(\"jclouds-test\"),\n            new ParseOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"DELETE\", \"/projects/party/global/targetHttpProxies/jclouds-test\");\n   }\n\n   public void delete_4xx() throws Exception {\n      server.enqueue(response404());\n\n      assertNull(targetHttpProxyApi().delete(\"jclouds-test\"));\n      assertSent(server, \"DELETE\", \"/projects/party/global/targetHttpProxies/jclouds-test\");\n   }\n\n   public void setUrlMap() throws Exception {\n      server.enqueue(jsonResponse(\"/operation.json\"));\n\n      URI urlMap = URI.create(url(\"/projects/myproject/global/urlMaps/jclouds-test\"));\n      assertEquals(targetHttpProxyApi().setUrlMap(\"jclouds-test\", urlMap), new ParseOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"POST\", \"/projects/party/targetHttpProxies/jclouds-test/setUrlMap\",\n            stringFromResource(\"/target_http_proxy_set_url_map.json\"));\n   }\n\n   public void list() throws Exception {\n      server.enqueue(jsonResponse(\"/target_http_proxy_list.json\"));\n\n      assertEquals(targetHttpProxyApi().list().next(), new ParseTargetHttpProxyListTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/projects/party/global/targetHttpProxies\");\n   }\n\n   public void list_empty() throws Exception {\n      server.enqueue(jsonResponse(\"/list_empty.json\"));\n\n      assertFalse(targetHttpProxyApi().list().hasNext());\n      assertSent(server, \"GET\", \"/projects/party/global/targetHttpProxies\");\n   }\n\n   TargetHttpProxyApi targetHttpProxyApi() {\n      return api().targetHttpProxies();\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/TargetInstanceApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.jclouds.googlecomputeengine.options.ListOptions.Builder.filter;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.net.URI;\nimport java.util.List;\nimport java.util.Properties;\n\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.GoogleComputeEngineApi;\nimport org.jclouds.googlecomputeengine.domain.Image;\nimport org.jclouds.googlecomputeengine.domain.Instance;\nimport org.jclouds.googlecomputeengine.domain.NewInstance;\nimport org.jclouds.googlecomputeengine.domain.NewTargetInstance;\nimport org.jclouds.googlecomputeengine.domain.TargetInstance;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.Iterables;\nimport com.google.inject.Module;\n\n\npublic class TargetInstanceApiLiveTest extends BaseGoogleComputeEngineApiLiveTest {\n\n   private static final String INSTANCE_NAME = \"test-target-instance-source-1\";\n   private static final String INSTANCE_NETWORK_NAME = \"test-target-instance-test-network\";\n   private static final String IPV4_RANGE = \"10.0.0.0/8\";\n   private static final String TARGET_INSTANCE_NAME = \"test-target-instance-1\";\n   \n   private Instance instance;\n   \n   @Override\n   protected GoogleComputeEngineApi create(Properties props, Iterable<Module> modules) {\n      GoogleComputeEngineApi api = super.create(props, modules);\n      List<Image> list = api.images().listInProject(\"centos-cloud\", filter(\"name eq centos.*\")).next();\n      URI imageUri = FluentIterable.from(list)\n                        .filter(new Predicate<Image>() {\n                           @Override\n                           public boolean apply(Image input) {\n                              // filter out all deprecated images\n                              return !(input.deprecated() != null && input.deprecated().state() != null);\n                           }\n                        })\n                        .first()\n                        .get()\n                        .selfLink();\n\n      NewInstance newInstance = NewInstance.create(\n            INSTANCE_NAME, // name\n            getDefaultMachineTypeUrl(), // machineType\n            getNetworkUrl(INSTANCE_NETWORK_NAME), // network\n            null, // subnetwork\n            imageUri);\n      \n      // need to insert the network first\n      assertOperationDoneSuccessfully(api.networks().createLegacy(INSTANCE_NETWORK_NAME, IPV4_RANGE));\n      \n      assertOperationDoneSuccessfully(api.instancesInZone(DEFAULT_ZONE_NAME).create(newInstance));\n      instance = api.instancesInZone(DEFAULT_ZONE_NAME).get(INSTANCE_NAME);\n      assertNotNull(instance);\n\n      return api;\n   }\n\n   @Test(groups = \"live\")\n   public void testInsertTargetInstance(){\n      NewTargetInstance newTargetInstance = new NewTargetInstance.Builder()\n         .name(TARGET_INSTANCE_NAME)\n         .description(\"A test Target Instance\")\n         .instance(instance.selfLink())\n         .build();\n\n      assertOperationDoneSuccessfully(api.targetInstancesInZone(DEFAULT_ZONE_NAME).create(newTargetInstance));\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testInsertTargetInstance\")\n   public void testGetTargetInstance(){\n      TargetInstance targetInstance = api.targetInstancesInZone(DEFAULT_ZONE_NAME).get(TARGET_INSTANCE_NAME);\n\n      assertNotNull(targetInstance);\n      assertEquals(targetInstance.name(), TARGET_INSTANCE_NAME);\n      assertEquals(targetInstance.description(), \"A test Target Instance\");\n      assertEquals(targetInstance.zone(), getZoneUrl(DEFAULT_ZONE_NAME));\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testInsertTargetInstance\", alwaysRun = true)\n   public void testListTargetInstance(){\n      ListPage<TargetInstance> targetInstances = api.targetInstancesInZone(DEFAULT_ZONE_NAME)\n            .list(filter(\"name eq \" + TARGET_INSTANCE_NAME)).next();\n\n      assertEquals(targetInstances.size(), 1);\n      assertTargetInstanceEquals(Iterables.getOnlyElement(targetInstances));\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = {\"testListTargetInstance\", \"testGetTargetInstance\"}, alwaysRun = true)\n   public void testDeleteTargetInstance(){\n      assertOperationDoneSuccessfully(api.targetInstancesInZone(DEFAULT_ZONE_NAME).delete(TARGET_INSTANCE_NAME));\n      assertOperationDoneSuccessfully(api.instancesInZone(DEFAULT_ZONE_NAME).delete(INSTANCE_NAME));\n      assertOperationDoneSuccessfully(api.networks().delete(INSTANCE_NETWORK_NAME));\n   }\n\n   private void assertTargetInstanceEquals(TargetInstance targetInstance){\n      assertNotNull(targetInstance);\n      assertEquals(targetInstance.name(), TARGET_INSTANCE_NAME);\n      assertEquals(targetInstance.description(), \"A test Target Instance\");\n      assertEquals(targetInstance.zone(), getZoneUrl(DEFAULT_ZONE_NAME));\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/TargetInstanceApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNull;\n\nimport java.net.URI;\n\nimport org.jclouds.googlecomputeengine.domain.NewTargetInstance;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiMockTest;\nimport org.jclouds.googlecomputeengine.parse.ParseOperationTest;\nimport org.jclouds.googlecomputeengine.parse.ParseTargetInstanceListTest;\nimport org.jclouds.googlecomputeengine.parse.ParseTargetInstanceTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"TargetInstanceApiMockTest\", singleThreaded = true)\npublic class TargetInstanceApiMockTest extends BaseGoogleComputeEngineApiMockTest {\n\n   public static final String TARGET_INSTANCE_NAME = \"target-instance-1\";\n\n   public void get() throws Exception {\n      server.enqueue(jsonResponse(\"/target_instance_get.json\"));\n\n      assertEquals(targetInstanceApi().get(TARGET_INSTANCE_NAME),\n            new ParseTargetInstanceTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/targetInstances/\" + TARGET_INSTANCE_NAME);\n   }\n\n   public void get_4xx() throws Exception {\n      server.enqueue(response404());\n\n      assertNull(targetInstanceApi().get(TARGET_INSTANCE_NAME));\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/targetInstances/\" + TARGET_INSTANCE_NAME);\n   }\n\n   public void insert() throws Exception {\n      server.enqueue(jsonResponse(\"/operation.json\"));\n\n      NewTargetInstance options = new NewTargetInstance.Builder()\n         .name(\"test-target-instance\")\n         .description(\"This is a test\")\n         .natPolicy(\"NO_NAT\")\n         .instance(URI.create(url(\"/projects/party/zones/us-central1-a/instances/instance-1\")))\n         .build();\n\n      assertEquals(targetInstanceApi().create(options),\n            new ParseOperationTest().expected(url(\"/projects\")));\n\n      assertSent(server, \"POST\", \"/projects/party/zones/us-central1-a/targetInstances\",\n            stringFromResource(\"/target_instance_insert.json\"));\n   }\n\n   public void testDeleteImageResponseIs2xx()  throws Exception {\n      server.enqueue(jsonResponse(\"/operation.json\"));\n\n      assertEquals(targetInstanceApi().delete(TARGET_INSTANCE_NAME),\n            new ParseOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"DELETE\", \"/projects/party/zones/us-central1-a/targetInstances/\" + TARGET_INSTANCE_NAME);\n   }\n\n   public void delete() throws Exception {\n      server.enqueue(response404());\n\n      assertNull(targetInstanceApi().delete(TARGET_INSTANCE_NAME));\n      assertSent(server, \"DELETE\", \"/projects/party/zones/us-central1-a/targetInstances/\" + TARGET_INSTANCE_NAME);\n   }\n\n   public void list() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/target_instance_list.json\"));\n\n      assertEquals(targetInstanceApi().list().next(), new ParseTargetInstanceListTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/targetInstances\");\n   }\n\n   public void listEmpty() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/list_empty.json\"));\n\n      assertFalse(targetInstanceApi().list().hasNext());\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a/targetInstances\");\n   }\n\n   TargetInstanceApi targetInstanceApi() {\n      return api().targetInstancesInZone(\"us-central1-a\");\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/TargetPoolApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.jclouds.googlecomputeengine.options.ListOptions.Builder.filter;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.net.URI;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.domain.ForwardingRule.IPProtocol;\nimport org.jclouds.googlecomputeengine.domain.HealthStatus;\nimport org.jclouds.googlecomputeengine.domain.HttpHealthCheck;\nimport org.jclouds.googlecomputeengine.domain.Image;\nimport org.jclouds.googlecomputeengine.domain.Instance;\nimport org.jclouds.googlecomputeengine.domain.NewInstance;\nimport org.jclouds.googlecomputeengine.domain.TargetPool;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiLiveTest;\nimport org.jclouds.googlecomputeengine.options.ForwardingRuleCreationOptions;\nimport org.jclouds.googlecomputeengine.options.HttpHealthCheckCreationOptions;\nimport org.jclouds.googlecomputeengine.options.TargetPoolCreationOptions;\nimport org.jclouds.googlecomputeengine.options.TargetPoolCreationOptions.SessionAffinityValue;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.Iterables;\n\n@Test(groups = \"live\", testName = \"TargetPoolApiLiveTest\")\npublic class TargetPoolApiLiveTest extends BaseGoogleComputeEngineApiLiveTest {\n\n   private static final String BACKUP_TARGETPOOL_NAME = \"targetpool-api-live-test-backup\";\n   private static final String TARGETPOOL_NAME = \"targetpool-api-live-test-primary\";\n   private static final String THIRD_TARGETPOOL_NAME = \"targetpool-api-live-test-third\";\n   private static final String DESCRIPTION = \"A New TargetPool!\";\n   private static final String DESCRIPTION_BACKUP = \"A backup target pool!\";\n\n   private static final String INSTANCE_NETWORK_NAME = \"target-pool-api-live-test-network\";\n   private static final String INSTANCE_NAME = \"target-pool-api-live-test-instance\";\n   private static final String IPV4_RANGE = \"10.0.0.0/8\";\n   private static final String HEALTHCHECK_NAME = \"target-pool-test-health-check\";\n   private static final String FORWARDING_RULE_NAME = \"target-pool-api-forwarding-rule\";\n\n   private List<URI> instances;\n   private List<URI> httpHealthChecks;\n\n   private TargetPoolApi api() {\n      return api.targetPoolsInRegion(DEFAULT_REGION_NAME);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testInsertTargetPool2\")\n   public void testCreateInstanceAndHealthCheck(){\n      InstanceApi instanceApi = api.instancesInZone(DEFAULT_ZONE_NAME);\n      HttpHealthCheckApi httpHealthCheckApi = api.httpHeathChecks();\n\n      ListPage<Image> list = api.images().listInProject(\"centos-cloud\", filter(\"name eq centos.*\")).next();\n      // Get an imageUri\n      URI imageUri = FluentIterable.from(list)\n            .filter(new Predicate<Image>() {\n               @Override\n               public boolean apply(Image input) {\n                  // filter out all deprecated images\n                  return !(input.deprecated() != null && input.deprecated().state() != null);\n               }\n            })\n            .first().get().selfLink();\n\n      // need to insert the network first\n      assertOperationDoneSuccessfully(api.networks().createLegacy(INSTANCE_NETWORK_NAME, IPV4_RANGE));\n\n      // Create an instance.\n      assertOperationDoneSuccessfully(\n            instanceApi.create(NewInstance.create( //\n                  INSTANCE_NAME, // name\n                  getDefaultMachineTypeUrl(), // machineType\n                  getNetworkUrl(INSTANCE_NETWORK_NAME), // network\n                  null, // subnetwork\n                  imageUri // disks\n            )));\n\n      Instance instance = instanceApi.get(INSTANCE_NAME);\n      instances = new ArrayList<URI>();\n      instances.add(instance.selfLink());\n\n      // Create a healthCheck\n      HttpHealthCheckCreationOptions options = new HttpHealthCheckCreationOptions.Builder()\n         .checkIntervalSec(3)\n         .timeoutSec(2)\n         .description(\"A test HealthCheck for adding to targetPools\")\n         .buildWithDefaults();\n      assertOperationDoneSuccessfully(httpHealthCheckApi.insert(HEALTHCHECK_NAME, options));\n      HttpHealthCheck healthCheck = httpHealthCheckApi.get(HEALTHCHECK_NAME);\n      httpHealthChecks = new ArrayList<URI>();\n      httpHealthChecks.add(healthCheck.selfLink());\n\n      // Create a forwarding rule\n      TargetPool targetPool = api().get(TARGETPOOL_NAME);\n      URI target = targetPool.selfLink();\n\n      ForwardingRuleCreationOptions forwardingRuleOptions = new ForwardingRuleCreationOptions.Builder()\n         .ipProtocol(IPProtocol.TCP)\n         .portRange(\"80-80\")\n         .target(target)\n         .build();\n\n      assertOperationDoneSuccessfully(api.forwardingRulesInRegion(DEFAULT_REGION_NAME)\n               .create(FORWARDING_RULE_NAME, forwardingRuleOptions));\n   }\n\n   @Test(groups = \"live\")\n   public void testInsertTargetPool() {\n      TargetPoolCreationOptions targetPoolCreationOptions = new TargetPoolCreationOptions.Builder(BACKUP_TARGETPOOL_NAME)\n      .description(DESCRIPTION_BACKUP)\n      .sessionAffinity(SessionAffinityValue.CLIENT_IP)\n      .build();\n      assertOperationDoneSuccessfully(api().create(targetPoolCreationOptions));\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testInsertTargetPool\")\n   public void testInsertTargetPool2(){\n      TargetPool targetPool = api().get(BACKUP_TARGETPOOL_NAME);\n      assertNotNull(targetPool);\n      // Make a Target Pool with a backup and failoverRatio specified.\n      TargetPoolCreationOptions targetPoolCreationOptions = new TargetPoolCreationOptions.Builder(TARGETPOOL_NAME)\n         .description(DESCRIPTION)\n         .sessionAffinity(SessionAffinityValue.CLIENT_IP)\n         .backupPool(targetPool.selfLink())\n         .failoverRatio((float) 0.5)\n         .build();\n      assertOperationDoneSuccessfully(api().create(targetPoolCreationOptions));\n      TargetPool targetPool2 = api().get(TARGETPOOL_NAME);\n      assertNotNull(targetPool2);\n      assertEquals(targetPool2.name(), TARGETPOOL_NAME);\n      assertEquals(targetPool2.description(), DESCRIPTION);\n      assertEquals(targetPool2.failoverRatio(), (float) 0.5);\n      assertEquals(targetPool2.backupPool(), targetPool.selfLink());\n      assertEquals(targetPool2.sessionAffinity(), SessionAffinityValue.CLIENT_IP);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testInsertTargetPool\")\n   public void testGetTargetPool() {\n      TargetPool targetPool = api().get(BACKUP_TARGETPOOL_NAME);\n      assertNotNull(targetPool);\n      assertEquals(targetPool.name(), BACKUP_TARGETPOOL_NAME);\n      assertEquals(targetPool.description(), DESCRIPTION_BACKUP);\n      assertEquals(targetPool.sessionAffinity(), SessionAffinityValue.CLIENT_IP);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = {\"testInsertTargetPool\", \"testCreateInstanceAndHealthCheck\"})\n   public void testAddInstanceTargetPool() {\n      assertOperationDoneSuccessfully(api().addInstance(TARGETPOOL_NAME, instances));\n      TargetPool targetPool = api().get(TARGETPOOL_NAME);\n      assertNotNull(targetPool);\n      assertEquals(targetPool.name(), TARGETPOOL_NAME);\n      assertEquals(targetPool.instances(), instances);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = {\"testInsertTargetPool2\", \"testCreateInstanceAndHealthCheck\"})\n   public void testAddHealthCheckTargetPool() {\n      assertOperationDoneSuccessfully(api().addHealthCheck(TARGETPOOL_NAME, httpHealthChecks));\n      TargetPool targetPool = api().get(TARGETPOOL_NAME);\n      assertNotNull(targetPool);\n      assertEquals(targetPool.name(), TARGETPOOL_NAME);\n      assertEquals(targetPool.healthChecks(), httpHealthChecks);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = {\"testAddHealthCheckTargetPool\", \"testAddInstanceTargetPool\"} )\n   public void testGetHealthTargetPool() {\n      TargetPool targetPool = api().get(TARGETPOOL_NAME);\n      assertNotNull(targetPool);\n      assertEquals(targetPool.instances(), instances);\n      assertEquals(targetPool.healthChecks(), httpHealthChecks);\n\n      HealthStatus healthStatus = api().getHealth(TARGETPOOL_NAME, instances.get(0));\n      assertNotNull(healthStatus);\n      assertEquals(healthStatus.healthStatus().get(0).instance(), instances.get(0));\n      assertEquals(healthStatus.healthStatus().get(0).healthState(), \"UNHEALTHY\");\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testGetHealthTargetPool\")\n   public void testRemoveInstanceTargetPool() {\n      assertOperationDoneSuccessfully(api().removeInstance(TARGETPOOL_NAME, instances));\n\n      TargetPool targetPool = api().get(TARGETPOOL_NAME);\n\n      assertNotNull(targetPool);\n      assertEquals(targetPool.name(), TARGETPOOL_NAME);\n      assertNotEquals(targetPool.instances(), instances);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testGetHealthTargetPool\")\n   public void testRemoveHealthCheckTargetPool() {\n      assertOperationDoneSuccessfully(api().removeHealthCheck(TARGETPOOL_NAME, httpHealthChecks));\n\n      TargetPool targetPool = api().get(TARGETPOOL_NAME);\n\n      assertNotNull(targetPool);\n      assertEquals(targetPool.name(), TARGETPOOL_NAME);\n      assertNotEquals(targetPool.healthChecks(), httpHealthChecks);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testInsertTargetPool\")\n   public void testListTargetPool() {\n      ListPage<TargetPool> targetPool = api().list(filter(\"name eq \" + BACKUP_TARGETPOOL_NAME)).next();\n      assertEquals(Iterables.size(targetPool), 1);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = {\"testInsertTargetPool2\"})\n   public void testListBackupTargetPool() {\n      TargetPoolCreationOptions options = new TargetPoolCreationOptions.Builder(THIRD_TARGETPOOL_NAME)\n            .description(\"A targetPool for testing setBackup.\").build();\n      assertOperationDoneSuccessfully(api().create(options));\n      TargetPool targetPool = api().get(THIRD_TARGETPOOL_NAME);\n      assertNotNull(targetPool);\n      assertEquals(targetPool.name(), THIRD_TARGETPOOL_NAME);\n      assertEquals(targetPool.backupPool(), null);\n\n      URI selfLink = api().get(BACKUP_TARGETPOOL_NAME).selfLink();\n\n      Float failoverRatio = Float.valueOf((float) 0.5);\n      assertOperationDoneSuccessfully(api().setBackup(THIRD_TARGETPOOL_NAME, failoverRatio, selfLink));\n\n      TargetPool targetPoolUpdated = api().get(THIRD_TARGETPOOL_NAME);\n      assertNotNull(targetPoolUpdated);\n      assertEquals(targetPoolUpdated.name(), THIRD_TARGETPOOL_NAME);\n      assertEquals(targetPoolUpdated.backupPool(), selfLink);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = {\"testListTargetPool\",\n                                              \"testGetTargetPool\",\n                                              \"testRemoveInstanceTargetPool\",\n                                              \"testRemoveHealthCheckTargetPool\",\n                                              \"testListBackupTargetPool\"}, alwaysRun = true)\n   public void testDeleteTargetPool() {\n      // Note: This ordering matters due one being the backup of the other ect.\n      assertOperationDoneSuccessfully(api().delete(THIRD_TARGETPOOL_NAME));\n      assertOperationDoneSuccessfully(api.forwardingRulesInRegion(DEFAULT_REGION_NAME).delete(FORWARDING_RULE_NAME));\n      assertOperationDoneSuccessfully(api().delete(TARGETPOOL_NAME));\n      assertOperationDoneSuccessfully(api().delete(BACKUP_TARGETPOOL_NAME));\n   }\n\n   @AfterClass(groups = { \"integration\", \"live\" }, alwaysRun = true)\n   public void testCleanup(){\n      InstanceApi instanceApi = api.instancesInZone(DEFAULT_ZONE_NAME);\n      HttpHealthCheckApi httpHealthCheckApi = api.httpHeathChecks();\n\n      try {\n         waitOperationDone(instanceApi.delete(INSTANCE_NAME));\n         waitOperationDone(api.networks().delete(INSTANCE_NETWORK_NAME));\n         waitOperationDone(httpHealthCheckApi.delete(HEALTHCHECK_NAME));\n      } catch (Exception e) {\n         // we don't really care about any exception here, so just delete away.\n       }\n   }\n\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/TargetPoolApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.AssertJUnit.assertNull;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiMockTest;\nimport org.jclouds.googlecomputeengine.options.TargetPoolCreationOptions;\nimport org.jclouds.googlecomputeengine.parse.ParseHealthStatusTest;\nimport org.jclouds.googlecomputeengine.parse.ParseRegionOperationTest;\nimport org.jclouds.googlecomputeengine.parse.ParseTargetPoolListTest;\nimport org.jclouds.googlecomputeengine.parse.ParseTargetPoolTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"TargetPoolApiMockTest\", singleThreaded = true)\npublic class TargetPoolApiMockTest extends BaseGoogleComputeEngineApiMockTest {\n\n   public void get() throws Exception {\n      server.enqueue(jsonResponse(\"/targetpool_get.json\"));\n\n      assertEquals(targetPoolApi().get(\"test\"),\n            new ParseTargetPoolTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/projects/party/regions/us-central1/targetPools/test\");\n   }\n\n   public void get_4xx() throws Exception {\n      server.enqueue(response404());\n\n      assertNull(targetPoolApi().get(\"test\"));\n      assertSent(server, \"GET\", \"/projects/party/regions/us-central1/targetPools/test\");\n   }\n\n   public void insert() throws Exception {\n      server.enqueue(jsonResponse(\"/region_operation.json\"));\n\n      TargetPoolCreationOptions targetPoolCreationOptions = new TargetPoolCreationOptions.Builder(\"test\").build();\n      assertEquals(targetPoolApi().create(targetPoolCreationOptions),\n            new ParseRegionOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"POST\", \"/projects/party/regions/us-central1/targetPools\",\n            stringFromResource(\"/targetpool_insert.json\"));\n   }\n\n   public void delete() throws Exception {\n      server.enqueue(jsonResponse(\"/region_operation.json\"));\n\n      assertEquals(targetPoolApi().delete(\"test-targetPool\"),\n            new ParseRegionOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"DELETE\", \"/projects/party/regions/us-central1/targetPools/test-targetPool\");\n   }\n\n   public void delete_4xx() throws Exception {\n      server.enqueue(response404());\n\n      assertNull(targetPoolApi().delete(\"test-targetPool\"));\n      assertSent(server, \"DELETE\", \"/projects/party/regions/us-central1/targetPools/test-targetPool\");\n   }\n\n   public void list() throws Exception {\n      server.enqueue(jsonResponse(\"/targetpool_list.json\"));\n\n      assertEquals(targetPoolApi().list().next(), new ParseTargetPoolListTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/projects/party/regions/us-central1/targetPools\");\n   }\n\n   public void list_empty() throws Exception {\n      server.enqueue(jsonResponse(\"/list_empty.json\"));\n\n      assertFalse(targetPoolApi().list().hasNext());\n      assertSent(server, \"GET\", \"/projects/party/regions/us-central1/targetPools\");\n   }\n\n   public void addInstance() throws Exception {\n      server.enqueue(jsonResponse(\"/region_operation.json\"));\n\n      List<URI> instances = ImmutableList\n            .of(URI.create(url(\"/projects/party/zones/europe-west1-a/instances/test\")));\n\n      assertEquals(targetPoolApi().addInstance(\"test\", instances),\n            new ParseRegionOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"POST\", \"/projects/party/regions/us-central1/targetPools/test/addInstance\",\n            stringFromResource(\"/targetpool_addinstance.json\"));\n   }\n\n   public void removeInstance() throws Exception {\n      server.enqueue(jsonResponse(\"/region_operation.json\"));\n\n      List<URI> instances = ImmutableList\n            .of(URI.create(url(\"/projects/party/zones/europe-west1-a/instances/test\")));\n\n      assertEquals(targetPoolApi().removeInstance(\"test\", instances),\n            new ParseRegionOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"POST\", \"/projects/party/regions/us-central1/targetPools/test/removeInstance\",\n            stringFromResource(\"/targetpool_addinstance.json\"));\n   }\n\n   public void addHealthCheck() throws Exception {\n      server.enqueue(jsonResponse(\"/region_operation.json\"));\n\n      List<URI> healthChecks = ImmutableList\n            .of(URI.create(url(\"/projects/party/global/httpHealthChecks/health-check-1\")));\n\n      assertEquals(targetPoolApi().addHealthCheck(\"test\", healthChecks),\n            new ParseRegionOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"POST\", \"/projects/party/regions/us-central1/targetPools/test/addHealthCheck\",\n            stringFromResource(\"/targetpool_changehealthcheck.json\"));\n   }\n\n   public void removeHealthCheck() throws Exception {\n      server.enqueue(jsonResponse(\"/region_operation.json\"));\n\n      List<URI> healthChecks = ImmutableList\n            .of(URI.create(url(\"/projects/party/global/httpHealthChecks/health-check-1\")));\n\n      assertEquals(targetPoolApi().removeHealthCheck(\"test\", healthChecks),\n            new ParseRegionOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"POST\", \"/projects/party/regions/us-central1/targetPools/test/removeHealthCheck\",\n            stringFromResource(\"/targetpool_changehealthcheck.json\"));\n   }\n\n   public void setBackup() throws Exception {\n      server.enqueue(jsonResponse(\"/region_operation.json\"));\n\n      URI backup = URI.create(url(\"/projects/party/regions/us-central1/targetPools/tpool\"));\n\n      assertEquals(targetPoolApi().setBackup(\"test\", backup),\n            new ParseRegionOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"POST\", \"/projects/party/regions/us-central1/targetPools/test/setBackup\",\n            stringFromResource(\"/targetpool_setbackup.json\"));\n   }\n\n   public void setBackup_FailoverRatio() throws Exception {\n      server.enqueue(jsonResponse(\"/region_operation.json\"));\n\n      URI backup = URI.create(url(\"/projects/party/regions/us-central1/targetPools/tpool\"));\n\n      Float failoverRatio = Float.valueOf(\"0.5\");\n      assertEquals(targetPoolApi().setBackup(\"test\", failoverRatio, backup),\n            new ParseRegionOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"POST\", \"/projects/party/regions/us-central1/targetPools/\"\n            + \"test/setBackup?failoverRatio=0.5\",\n            stringFromResource(\"/targetpool_setbackup.json\"));\n   }\n\n   public void getHealth() throws Exception {\n      server.enqueue(jsonResponse(\"/health_status_get_health.json\"));\n\n      URI instance = URI.create(url(\"/party/zones/us-central1-a/instances/jclouds-test\"));\n      assertEquals(targetPoolApi().getHealth(\"test-pool\", instance),\n            new ParseHealthStatusTest().expected(url(\"/projects\")));\n      assertSent(server, \"POST\", \"/projects/party/regions/us-central1/targetPools/test-pool/getHealth\",\n            \"{\\\"instance\\\": \\\"\" + instance.toString() + \"\\\"}\");\n   }\n\n   public TargetPoolApi targetPoolApi() {\n      return api().targetPoolsInRegion(\"us-central1\");\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/UrlMapApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.jclouds.googlecomputeengine.options.ListOptions.Builder.filter;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static com.google.common.collect.ImmutableList.of;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.domain.UrlMap;\nimport org.jclouds.googlecomputeengine.domain.UrlMap.HostRule;\nimport org.jclouds.googlecomputeengine.domain.UrlMap.PathMatcher;\nimport org.jclouds.googlecomputeengine.domain.UrlMap.PathMatcher.PathRule;\nimport org.jclouds.googlecomputeengine.domain.UrlMap.UrlMapTest;\nimport org.jclouds.googlecomputeengine.domain.UrlMapValidateResult;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiLiveTest;\nimport org.jclouds.googlecomputeengine.options.BackendServiceOptions;\nimport org.jclouds.googlecomputeengine.options.UrlMapOptions;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Iterables;\n\npublic class UrlMapApiLiveTest extends BaseGoogleComputeEngineApiLiveTest {\n\n   public static final String URL_MAP_NAME = \"url-map-api-live-test-url-map\";\n   public static final String URL_MAP_DEFAULT_BACKEND_SERVICE_NAME = \"url-map-api-live-test-backend-service\";\n   public static final String URL_MAP_OTHER_BACKEND_SERVICE_NAME = \"url-map-api-live-test-other-backend-service\";\n   public static final String HEALTH_CHECK_NAME = \"url-map-api-live-test-health-check\";\n\n   public URI default_backend_service_url;\n   public URI other_backend_service_url;\n\n   private UrlMapApi api() {\n      return api.urlMaps();\n   }\n\n   @Test(groups = \"live\")\n   public void testInsertUrlMap() {\n      // Create extra resources needed for url maps\n      assertOperationDoneSuccessfully(api.httpHeathChecks().insert(HEALTH_CHECK_NAME));\n\n      List<URI> healthChecks = of(getHealthCheckUrl(HEALTH_CHECK_NAME));\n      BackendServiceOptions b = new BackendServiceOptions.Builder(URL_MAP_DEFAULT_BACKEND_SERVICE_NAME, healthChecks).build();\n      assertOperationDoneSuccessfully(api.backendServices().create(b));\n\n\n      UrlMapOptions map = new UrlMapOptions.Builder().name(URL_MAP_NAME).description(\"simple url map\")\n                                             .defaultService(getBackendServiceUrl(URL_MAP_DEFAULT_BACKEND_SERVICE_NAME)).build();\n\n      BackendServiceOptions b2 = new BackendServiceOptions.Builder(URL_MAP_OTHER_BACKEND_SERVICE_NAME, healthChecks).build();\n      assertOperationDoneSuccessfully(api.backendServices().create(b2));\n\n      assertOperationDoneSuccessfully(api().create(map));\n\n      default_backend_service_url = getBackendServiceUrl(URL_MAP_DEFAULT_BACKEND_SERVICE_NAME);\n      other_backend_service_url = getBackendServiceUrl(URL_MAP_OTHER_BACKEND_SERVICE_NAME);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testInsertUrlMap\")\n   public void testGetUrlMap() {\n\n      UrlMap urlMap = api().get(URL_MAP_NAME);\n      assertNotNull(urlMap);\n      assertUrlMapEquals(urlMap);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testGetUrlMap\")\n   public void testListUrlMap() {\n\n      ListPage<UrlMap> urlMaps = api().list(filter(\"name eq \" + URL_MAP_NAME)).next();\n\n      assertEquals(urlMaps.size(), 1);\n\n      assertUrlMapEquals(Iterables.getOnlyElement(urlMaps));\n\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testGetUrlMap\")\n   public void testUpdateUrlMap() {\n      String fingerprint = api().get(URL_MAP_NAME).fingerprint();\n\n      ImmutableList<String> paths = of(\"/other\", \"/other/*\");\n\n      ImmutableList<PathRule> rules = of(PathRule.create(paths, other_backend_service_url));\n\n      ImmutableList<PathMatcher> matchers = of(\n            PathMatcher.create(\"test-path-matcher\", \"\", default_backend_service_url, rules));\n\n      ImmutableList<HostRule> hostRules = of(\n            HostRule.create(\"\", of(\"*\"), \"test-path-matcher\"));\n\n      UrlMapOptions options = new UrlMapOptions.Builder().name(URL_MAP_NAME)\n                                                 .pathMatchers(matchers)\n                                                 .hostRules(hostRules)\n                                                 .defaultService(default_backend_service_url)\n                                                 .fingerprint(fingerprint).build();\n\n      assertOperationDoneSuccessfully(api().update(URL_MAP_NAME, options));\n\n      assertUrlMapEquals(api().get(URL_MAP_NAME), options);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testUpdateUrlMap\")\n   public void testPatchUrlMap() {\n      String fingerprint = api().get(URL_MAP_NAME).fingerprint();\n\n      ImmutableList<UrlMap.UrlMapTest> urlMapTests = of(\n            UrlMapTest.create(null, \"jclouds-test\", \"/test/path\", default_backend_service_url),\n            UrlMapTest.create(null, \"jclouds-test\", \"/other\", other_backend_service_url));\n\n      UrlMapOptions options = new UrlMapOptions.Builder().tests(urlMapTests)\n                                                 .fingerprint(fingerprint).buildForPatch();\n      assertOperationDoneSuccessfully(api().patch(URL_MAP_NAME, options));\n\n      // Update options with settings it should have for later assertions.\n      ImmutableList<String> paths = of(\"/other\", \"/other/*\");\n      ImmutableList<PathRule> rules = of(PathRule.create(paths, other_backend_service_url));\n      ImmutableList<PathMatcher> matchers = of(\n            PathMatcher.create(\"test-path-matcher\", \"\", default_backend_service_url, rules));\n      ImmutableList<HostRule> hostRules = of(\n            HostRule.create(\"\", of(\"*\"), \"test-path-matcher\"));\n\n      options = new UrlMapOptions.Builder().name(URL_MAP_NAME)\n             .description(\"simple url map\")\n             .pathMatchers(matchers)\n             .hostRules(hostRules)\n             .defaultService(default_backend_service_url)\n             .tests(urlMapTests)\n             .fingerprint(fingerprint)\n             .build();\n\n      assertUrlMapEquals(api().get(URL_MAP_NAME), options);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testPatchUrlMap\")\n   public void testValidateUrlMap() {\n      UrlMapValidateResult results = api().validate(URL_MAP_NAME, api().get(URL_MAP_NAME));\n      UrlMapValidateResult expected = UrlMapValidateResult.allPass();\n      assertEquals(results, expected);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testPatchUrlMap\")\n   public void testValidateUrlMapWithOptions() {\n      ImmutableList<String> paths = of(\"/test/*\");\n      ImmutableList<PathRule> rules = of(PathRule.create(paths, other_backend_service_url));\n\n      ImmutableList<PathMatcher> matchers = of(PathMatcher.create(\"test-path-matcher\", \"\", default_backend_service_url, rules));\n\n      ImmutableList<String> hosts = of(\"jclouds-test\");\n\n      ImmutableList<HostRule> hostRules = of(HostRule.create(\"\", hosts, \"test-path-matcher\"));\n      UrlMapTest urlMapTest = UrlMapTest.create(null, \"jclouds-test\", \"/test/path\", other_backend_service_url);\n      ImmutableList<UrlMap.UrlMapTest> urlMapTests = of(urlMapTest);\n\n      UrlMapOptions options = new UrlMapOptions.Builder()\n             .pathMatchers(matchers)\n             .name(URL_MAP_NAME)\n             .hostRules(hostRules)\n             .tests(urlMapTests)\n             .defaultService(default_backend_service_url)\n             .description(\"simple url map\")\n             .build();\n\n      UrlMapValidateResult results = api().validate(URL_MAP_NAME, options);\n      UrlMapValidateResult expected = UrlMapValidateResult.allPass();\n\n\n      assertEquals(results, expected);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testValidateUrlMapWithOptions\", alwaysRun = true)\n   public void testDeleteUrlMap() {\n\n      assertOperationDoneSuccessfully(api().delete(URL_MAP_NAME));\n\n      // remove extra resources created\n      assertOperationDoneSuccessfully(api.backendServices().delete(URL_MAP_DEFAULT_BACKEND_SERVICE_NAME));\n      assertOperationDoneSuccessfully(api.backendServices().delete(URL_MAP_OTHER_BACKEND_SERVICE_NAME));\n\n      assertOperationDoneSuccessfully(api.httpHeathChecks().delete(HEALTH_CHECK_NAME));\n   }\n\n   private void assertUrlMapEquals(UrlMap result) {\n      assertEquals(result.name(), URL_MAP_NAME);\n      assertEquals(result.defaultService(), default_backend_service_url);\n      assertEquals(result.description(), \"simple url map\");\n   }\n\n   private void assertUrlMapEquals(UrlMap result, UrlMapOptions expected) {\n      assertEquals(result.name(), expected.name());\n      assertEquals(result.defaultService(), expected.defaultService());\n      assertEquals(result.pathMatchers(), expected.pathMatchers());\n      assertEquals(result.hostRules(), expected.hostRules());\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/UrlMapApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.AssertJUnit.assertNull;\n\nimport java.net.URI;\n\nimport org.jclouds.googlecomputeengine.domain.UrlMap;\nimport org.jclouds.googlecomputeengine.domain.UrlMap.HostRule;\nimport org.jclouds.googlecomputeengine.domain.UrlMap.PathMatcher;\nimport org.jclouds.googlecomputeengine.domain.UrlMap.PathMatcher.PathRule;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiMockTest;\nimport org.jclouds.googlecomputeengine.options.UrlMapOptions;\nimport org.jclouds.googlecomputeengine.parse.ParseOperationTest;\nimport org.jclouds.googlecomputeengine.parse.ParseUrlMapListTest;\nimport org.jclouds.googlecomputeengine.parse.ParseUrlMapTest;\nimport org.jclouds.googlecomputeengine.parse.ParseUrlMapValidateTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"UrlMapApiMockTest\", singleThreaded = true)\npublic class UrlMapApiMockTest extends BaseGoogleComputeEngineApiMockTest {\n\n   public void get() throws Exception {\n      server.enqueue(jsonResponse(\"/url_map_get.json\"));\n\n      assertEquals(urlMapApi().get(\"jclouds-test\"), new ParseUrlMapTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/projects/party/global/urlMaps/jclouds-test\");\n   }\n\n   public void get_4xx() throws Exception {\n      server.enqueue(response404());\n\n      assertNull(urlMapApi().get(\"jclouds-test\"));\n      assertSent(server, \"GET\", \"/projects/party/global/urlMaps/jclouds-test\");\n   }\n\n   public void insert() throws Exception {\n      server.enqueue(jsonResponse(\"/operation.json\"));\n\n      assertEquals(urlMapApi().create(createBasicMap()), new ParseOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"POST\", \"/projects/party/global/urlMaps\",\n            stringFromResource(\"/url_map_insert.json\"));\n   }\n\n   public void update() throws Exception {\n      server.enqueue(jsonResponse(\"/operation.json\"));\n\n      assertEquals(urlMapApi().update(\"jclouds-test\", createBasicMap()),\n            new ParseOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"PUT\", \"/projects/party/global/urlMaps/jclouds-test\",\n            stringFromResource(\"/url_map_insert.json\"));\n   }\n\n   public void patch() throws Exception {\n      server.enqueue(jsonResponse(\"/operation.json\"));\n\n      assertEquals(urlMapApi().patch(\"jclouds-test\", createBasicMap()),\n            new ParseOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"PATCH\", \"/projects/party/global/urlMaps/jclouds-test\",\n            stringFromResource(\"/url_map_insert.json\"));\n   }\n\n   public void delete() throws Exception {\n      server.enqueue(jsonResponse(\"/operation.json\"));\n\n      assertEquals(urlMapApi().delete(\"jclouds-test\"),\n            new ParseOperationTest().expected(url(\"/projects\")));\n      assertSent(server, \"DELETE\", \"/projects/party/global/urlMaps/jclouds-test\");\n   }\n\n   public void delete_4xx() throws Exception {\n      server.enqueue(response404());\n\n      assertNull(urlMapApi().delete(\"jclouds-test\"));\n      assertSent(server, \"DELETE\", \"/projects/party/global/urlMaps/jclouds-test\");\n   }\n\n   public void list() throws Exception {\n      server.enqueue(jsonResponse(\"/url_map_list.json\"));\n\n      assertEquals(urlMapApi().list().next(),\n            new ParseUrlMapListTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/projects/party/global/urlMaps\");\n   }\n\n   public void list_empty() throws Exception {\n      server.enqueue(jsonResponse(\"/list_empty.json\"));\n\n      assertFalse(urlMapApi().list().hasNext());\n      assertSent(server, \"GET\", \"/projects/party/global/urlMaps\");\n   }\n\n   public void validate() throws Exception {\n      server.enqueue(jsonResponse(\"/url_map_validate.json\"));\n\n      assertEquals(urlMapApi().validate(\"jclouds-test\", createBasicMap()),\n            new ParseUrlMapValidateTest().expected(url(\"/projects\")));\n      assertSent(server, \"POST\", \"/projects/party/global/urlMaps/jclouds-test/validate\");\n   }\n\n   private UrlMapOptions createBasicMap() {\n      URI service = URI.create(url(\"/projects/myproject/global/backendServices/jclouds-test\"));\n      return new UrlMapOptions.Builder().name(\"jclouds-test\")\n                                .description(\"Sample url map\")\n                                .hostRules(ImmutableList.of(HostRule.create(null, ImmutableList.of(\"jclouds-test\"), \"path\")))\n                                .pathMatchers(ImmutableList.of(PathMatcher.create(\"path\",\n                                                                null,\n                                                                service,\n                                                                ImmutableList.of(\n                                                                      PathRule.create(ImmutableList.of(\"/\"),\n                                                                                      service)))))\n                                .tests(ImmutableList.of(UrlMap.UrlMapTest.create(null, \"jclouds-test\", \"/test/path\", service)))\n                                .defaultService(service)\n                                .build();\n   }\n\n   UrlMapApi urlMapApi() {\n      return api().urlMaps();\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/ZoneApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.jclouds.googlecomputeengine.options.ListOptions.Builder.maxResults;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Iterator;\nimport java.util.List;\n\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.domain.Zone;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiLiveTest;\nimport org.testng.annotations.Test;\n\npublic class ZoneApiLiveTest extends BaseGoogleComputeEngineApiLiveTest {\n\n   private Zone zone;\n\n   private ZoneApi api() {\n      return api.zones();\n   }\n\n   @Test(groups = \"live\")\n   public void testListZone() {\n      Iterator<ListPage<Zone>> pageIterator = api().list(maxResults(1));\n      assertTrue(pageIterator.hasNext());\n\n      List<Zone> zoneAsList = pageIterator.next();\n\n      assertEquals(zoneAsList.size(), 1);\n\n      this.zone = zoneAsList.get(0);\n   }\n\n\n   @Test(groups = \"live\", dependsOnMethods = \"testListZone\")\n   public void testGetZone() {\n      Zone zone = api().get(this.zone.name());\n      assertNotNull(zone);\n      assertZoneEquals(zone, this.zone);\n   }\n\n   private void assertZoneEquals(Zone result, Zone expected) {\n      assertEquals(result.name(), expected.name());\n   }\n\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/features/ZoneApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.AssertJUnit.assertNull;\n\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineApiMockTest;\nimport org.jclouds.googlecomputeengine.parse.ParseZoneListTest;\nimport org.jclouds.googlecomputeengine.parse.ParseZoneTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ZoneApiMockTest\", singleThreaded = true)\npublic class ZoneApiMockTest extends BaseGoogleComputeEngineApiMockTest {\n\n   public void get() throws Exception {\n      server.enqueue(jsonResponse(\"/zone_get.json\"));\n\n      assertEquals(zoneApi().get(\"us-central1-a\"),\n            new ParseZoneTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a\");\n   }\n\n   public void get_4xx() throws Exception {\n      server.enqueue(response404());\n\n      assertNull(zoneApi().get(\"us-central1-a\"));\n      assertSent(server, \"GET\", \"/projects/party/zones/us-central1-a\");\n   }\n\n   public void list() throws Exception {\n      server.enqueue(jsonResponse(\"/zone_list.json\"));\n\n      assertEquals(zoneApi().list().next(), new ParseZoneListTest().expected(url(\"/projects\")));\n      assertSent(server, \"GET\", \"/projects/party/zones\");\n   }\n\n   public void list_empty() throws Exception {\n      server.enqueue(jsonResponse(\"/list_empty.json\"));\n\n      assertFalse(zoneApi().list().hasNext());\n      assertSent(server, \"GET\", \"/projects/party/zones\");\n   }\n\n   ZoneApi zoneApi() {\n      return api().zones();\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/handlers/GoogleComputeEngineErrorHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.handlers;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.reportMatcher;\nimport static org.easymock.EasyMock.verify;\n\nimport java.net.URI;\n\nimport org.easymock.IArgumentMatcher;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"GoogleComputeErrorHandlerTest\")\npublic class GoogleComputeEngineErrorHandlerTest {\n\n   @Test\n   public void test409MakesIllegalStateException() {\n      assertCodeMakes(\n              \"POST\",\n              URI.create(\"https://www.googleapis.com/compute/v1\"),\n              409,\n              \"HTTP/1.1 409 Conflict\",\n              \"\\\"{\\\"code\\\":\\\"InvalidState\\\",\\\"message\\\":\\\"An incompatible transition has already been queued for this\" +\n                      \" resource\\\"}\\\"\",\n              IllegalStateException.class);\n   }\n\n   private void assertCodeMakes(String method, URI uri, int statusCode, String message, String content,\n                                Class<? extends Exception> expected) {\n      assertCodeMakes(method, uri, statusCode, message, \"application/json\", content, expected);\n   }\n\n   private void assertCodeMakes(String method, URI uri, int statusCode, String message, String contentType,\n                                String content, Class<? extends Exception> expected) {\n\n      GoogleComputeEngineErrorHandler function = new GoogleComputeEngineErrorHandler();\n\n      HttpCommand command = createMock(HttpCommand.class);\n      HttpRequest request = HttpRequest.builder().method(method).endpoint(uri).build();\n      HttpResponse response = HttpResponse.builder().statusCode(statusCode).message(message).payload(content).build();\n      response.getPayload().getContentMetadata().setContentType(contentType);\n\n      expect(command.getCurrentRequest()).andReturn(request).atLeastOnce();\n      command.setException(classEq(expected));\n\n      replay(command);\n\n      function.handleError(command, response);\n\n      verify(command);\n   }\n\n   public static Exception classEq(final Class<? extends Exception> in) {\n      reportMatcher(new IArgumentMatcher() {\n\n         @Override\n         public void appendTo(StringBuffer buffer) {\n            buffer.append(\"classEq(\");\n            buffer.append(in);\n            buffer.append(\")\");\n         }\n\n         @Override\n         public boolean matches(Object arg) {\n            return arg.getClass() == in;\n         }\n\n      });\n      return null;\n   }\n\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/internal/BaseGoogleComputeEngineApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.internal;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static org.jclouds.googlecomputeengine.config.GoogleComputeEngineProperties.OPERATION_COMPLETE_INTERVAL;\nimport static org.jclouds.googlecomputeengine.config.GoogleComputeEngineProperties.OPERATION_COMPLETE_TIMEOUT;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.net.URI;\nimport java.util.Properties;\nimport java.util.concurrent.atomic.AtomicReference;\nimport java.util.logging.Logger;\n\nimport org.jclouds.apis.BaseApiLiveTest;\nimport org.jclouds.googlecloud.config.CurrentProject;\nimport org.jclouds.googlecloud.internal.TestProperties;\nimport org.jclouds.googlecomputeengine.GoogleComputeEngineApi;\nimport org.jclouds.googlecomputeengine.domain.Operation;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.util.concurrent.Atomics;\nimport com.google.inject.Injector;\nimport com.google.inject.Key;\nimport com.google.inject.Module;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.name.Names;\n\npublic class BaseGoogleComputeEngineApiLiveTest extends BaseApiLiveTest<GoogleComputeEngineApi> {\n\n   protected static final String ZONE_API_URL_SUFFIX = \"/zones/\";\n   protected static final String DEFAULT_ZONE_NAME = \"us-central1-f\";\n   protected static final String REGION_API_URL_SUFFIX = \"/regions/\";\n   protected static final String DEFAULT_REGION_NAME = \"us-central1\";\n   protected static final String NETWORK_API_URL_SUFFIX = \"/global/networks/\";\n   protected static final String MACHINE_TYPE_API_URL_SUFFIX = \"/machineTypes/\";\n   protected static final String DEFAULT_MACHINE_TYPE_NAME = \"n1-standard-1\";\n   protected static final String GATEWAY_API_URL_SUFFIX = \"/global/gateways/\";\n   protected static final String DEFAULT_GATEWAY_NAME = \"default-internet-gateway\";\n   protected static final String IMAGE_API_URL_SUFFIX = \"/global/images/\";\n   protected static final String DISK_TYPE_API_URL_SUFFIX = \"/diskTypes/\";\n\n   protected static final String BACKEND_SERVICE_API_URL_SUFFIX = \"/global/backendServices/\";\n   protected static final String URL_MAP_API_URL_SUFFIX = \"/global/urlMaps/\";\n   protected static final String HEALTH_CHECK_API_URL_SUFFIX = \"/global/httpHealthChecks/\";\n   protected static final String TARGET_HTTP_PROXY_API_URL_SUFFIX = \"/global/targetHttpProxies/\";\n   protected static final String GOOGLE_PROJECT = \"google\";\n\n   protected Injector injector;\n   protected Predicate<AtomicReference<Operation>> operationDone;\n   protected long operationDoneInterval;\n   protected long operationDoneTimeout;\n   protected URI projectUrl;\n\n   public BaseGoogleComputeEngineApiLiveTest() {\n      provider = \"google-compute-engine\";\n   }\n\n   @Override protected Properties setupProperties() {\n      TestProperties.setGoogleCredentialsFromJson(provider);\n      return TestProperties.apply(provider, super.setupProperties());\n   }\n\n   @Override protected GoogleComputeEngineApi create(Properties props, Iterable<Module> modules) {\n      injector = newBuilder().modules(modules).overrides(props).buildInjector();\n      operationDone = injector.getInstance(Key.get(new TypeLiteral<Predicate<AtomicReference<Operation>>>() {\n      }));\n      projectUrl = injector.getInstance(Key.get(new TypeLiteral<Supplier<URI>>() {\n      }, CurrentProject.class)).get();\n      operationDoneInterval = Long.parseLong(injector.getInstance(Key.get(String.class, Names.named(OPERATION_COMPLETE_INTERVAL))));\n      operationDoneTimeout = Long.parseLong(injector.getInstance(Key.get(String.class, Names.named(OPERATION_COMPLETE_TIMEOUT))));\n      return injector.getInstance(GoogleComputeEngineApi.class);\n   }\n\n   protected void assertOperationDoneSuccessfully(Operation operation) {\n      AtomicReference<Operation> ref = Atomics.newReference(checkNotNull(operation, \"operation\"));\n      checkState(operationDone.apply(ref), \"Timeout waiting for operation: %s\", operation);\n      assertEquals(ref.get().status(), Operation.Status.DONE);\n      assertTrue(ref.get().error().errors().isEmpty());\n   }\n\n   protected void waitOperationDone(@Nullable Operation operation) {\n      if (operation == null) {\n         return;\n      }\n      if (!operationDone.apply(Atomics.newReference(operation))) {\n         Logger.getAnonymousLogger().warning(\"Timeout waiting for operation: \" + operation);\n      }\n   }\n\n   protected URI getDiskTypeUrl(String zone, String diskType){\n      return URI.create(projectUrl + ZONE_API_URL_SUFFIX + zone + DISK_TYPE_API_URL_SUFFIX + diskType);\n   }\n\n   protected URI getDefaultZoneUrl() {\n      return getZoneUrl(DEFAULT_ZONE_NAME);\n   }\n\n   protected URI getZoneUrl(String zone) {\n      return URI.create(projectUrl + ZONE_API_URL_SUFFIX + zone);\n   }\n   \n   protected URI getDefaultRegionUrl() {\n      return getRegionUrl(DEFAULT_REGION_NAME);\n   }\n\n   protected URI getRegionUrl(String region) {\n      return URI.create(projectUrl + REGION_API_URL_SUFFIX + region);\n   }\n\n   protected URI getNetworkUrl(String network) {\n      return URI.create(projectUrl + NETWORK_API_URL_SUFFIX + network);\n   }\n\n   protected URI getGatewayUrl(String gateway) {\n      return URI.create(projectUrl + GATEWAY_API_URL_SUFFIX + gateway);\n   }\n\n   protected URI getImageUrl(String image){\n      return URI.create(projectUrl + IMAGE_API_URL_SUFFIX + image);\n   }\n\n   protected URI getHealthCheckUrl(String healthCheck) {\n      return URI.create(projectUrl + HEALTH_CHECK_API_URL_SUFFIX + healthCheck);\n   }\n\n   protected URI getInstanceUrl(String instanceName) {\n      return URI.create(projectUrl + ZONE_API_URL_SUFFIX + DEFAULT_ZONE_NAME + \"/instances/\" + instanceName);\n   }\n\n   protected URI getTargetHttpProxyUrl(String targetHttpProxy) {\n      return URI.create(projectUrl + TARGET_HTTP_PROXY_API_URL_SUFFIX + targetHttpProxy);\n   }\n\n   protected URI getDefaultMachineTypeUrl() {\n      return getMachineTypeUrl(DEFAULT_MACHINE_TYPE_NAME);\n   }\n\n   protected URI getMachineTypeUrl(String machineType) {\n      return URI.create(projectUrl + ZONE_API_URL_SUFFIX\n              + DEFAULT_ZONE_NAME + MACHINE_TYPE_API_URL_SUFFIX + machineType);\n   }\n\n   protected URI getDiskUrl(String diskName) {\n      return URI.create(projectUrl + ZONE_API_URL_SUFFIX + DEFAULT_ZONE_NAME + \"/disks/\" + diskName);\n   }\n\n   protected URI getBackendServiceUrl(String backendService) {\n      return URI.create(projectUrl + BACKEND_SERVICE_API_URL_SUFFIX\n                  + backendService);\n   }\n\n   protected URI getUrlMapUrl(String urlMap) {\n      return URI.create(projectUrl + URL_MAP_API_URL_SUFFIX + urlMap);\n   }\n   \n   protected URI getSubnetworkUrl(String region, String subnetName) {\n      return URI.create(projectUrl + REGION_API_URL_SUFFIX + region + \"/subnetworks/\" + subnetName);\n   }\n}\n\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/internal/BaseGoogleComputeEngineApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.internal;\n\nimport static com.google.common.base.Throwables.propagate;\nimport static com.google.common.util.concurrent.MoreExecutors.newDirectExecutorService;\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_TERMINATED;\nimport static org.jclouds.googlecloud.config.GoogleCloudProperties.CREDENTIAL_TYPE;\nimport static org.jclouds.googlecloud.config.GoogleCloudProperties.PROJECT_NAME;\nimport static org.jclouds.googlecomputeengine.config.GoogleComputeEngineProperties.IMAGE_PROJECTS;\nimport static org.jclouds.oauth.v2.config.CredentialType.BEARER_TOKEN_CREDENTIALS;\nimport static org.jclouds.util.Strings2.toStringAndClose;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.util.Properties;\nimport java.util.Set;\nimport java.util.concurrent.atomic.AtomicInteger;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\nimport okhttp3.mockwebserver.RecordedRequest;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.compute.ComputeService;\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.concurrent.config.ExecutorServiceModule;\nimport org.jclouds.googlecomputeengine.GoogleComputeEngineApi;\nimport org.jclouds.googlecomputeengine.GoogleComputeEngineProviderMetadata;\nimport org.jclouds.http.okhttp.config.OkHttpCommandExecutorServiceModule;\nimport org.testng.annotations.AfterMethod;\nimport org.testng.annotations.BeforeMethod;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.gson.JsonParser;\nimport com.google.inject.Module;\n\n\n/**\n * Tests need to run {@code singleThreaded = true} as otherwise tests will clash on the server field.\n * Sharing the server field means less code to write.\n */\npublic class BaseGoogleComputeEngineApiMockTest {\n\n   protected final String identity = \"761326798069-r5mljlln1rd4lrbhg75efgigp36m78j5@developer.gserviceaccount.com\";\n   protected final String credential = \"1/8xbJqaOZXSUZbHLl5EOtu1pxz3fmmetKx9W8CV4t79M\"; // Fake Bearer Token\n\n   protected MockWebServer server;\n\n   protected GoogleComputeEngineApi api() {\n      return builder().buildApi(GoogleComputeEngineApi.class);\n   }\n\n   protected ComputeService computeService() {\n      return builder().buildView(ComputeServiceContext.class).getComputeService();\n   }\n\n   protected ContextBuilder builder() {\n      Properties overrides = new Properties();\n      overrides.put(PROJECT_NAME, \"party\");\n      overrides.put(IMAGE_PROJECTS, \"debian-cloud\");\n      overrides.put(TIMEOUT_NODE_TERMINATED, \"0\"); // Avoid retry & polling in mock tests\n      overrides.put(CREDENTIAL_TYPE, BEARER_TOKEN_CREDENTIALS.toString());\n      return ContextBuilder.newBuilder(new GoogleComputeEngineProviderMetadata())\n            .credentials(identity, credential)\n            .endpoint(url(\"\"))\n            .overrides(overrides)\n            .modules(modules);\n   }\n\n   private final Set<Module> modules = ImmutableSet\n         .of(new ExecutorServiceModule(newDirectExecutorService()), GoogleComputeEngineTestModule.INSTANCE, new OkHttpCommandExecutorServiceModule());\n\n   final AtomicInteger suffix = new AtomicInteger();\n\n   @BeforeMethod\n   public void start() throws IOException {\n      suffix.set(0);\n      server = new MockWebServer();\n      server.start();\n   }\n\n   protected String url(String path) {\n      if (\"\".equals(path)) {\n         final String serverUrl = server.url(\"\").toString();\n\n         return serverUrl.substring(0, serverUrl.length() - 1);\n      }\n\n      return server.url(path).toString();\n   }\n\n   @AfterMethod(alwaysRun = true)\n   public void stop() throws IOException {\n      server.shutdown();\n   }\n\n   protected MockResponse jsonResponse(String resource) {\n      return new MockResponse().addHeader(\"Content-Type\", \"application/json\").setBody(stringFromResource(resource));\n   }\n\n   protected MockResponse response404(){\n      return new MockResponse().setStatus(\"HTTP/1.1 404 Not Found\");\n   }\n\n   protected String stringFromResource(String resourceName) {\n      try {\n         return toStringAndClose(getClass().getResourceAsStream(resourceName))\n               .replace(\"https://www.googleapis.com/compute/v1/\", url(\"/\"));\n      } catch (IOException e) {\n         throw propagate(e);\n      }\n   }\n\n   protected MockResponse singleRegionSingleZoneResponse() {\n      return new MockResponse().setBody(\"{\\\"items\\\":[\" + stringFromResource(\"/region_get.json\")\n            .replace(\"\\\"\" + url(\"/\") + \"projects/party/zones/us-central1-b\\\"\", \"\") + \"]}\");\n   }\n\n   protected RecordedRequest assertSent(MockWebServer server, String method, String path) throws InterruptedException {\n      RecordedRequest request = server.takeRequest();\n      assertEquals(request.getMethod(), method);\n      assertEquals(request.getPath(), path);\n      assertEquals(request.getHeader(\"Accept\"), APPLICATION_JSON);\n      assertEquals(request.getHeader(\"Authorization\"), \"Bearer \" + credential);\n      return request;\n   }\n\n   protected RecordedRequest assertSent(MockWebServer server, String method, String path, String json)\n         throws InterruptedException {\n      RecordedRequest request = assertSent(server, method, path);\n      assertEquals(request.getHeader(\"Content-Type\"), APPLICATION_JSON);\n      assertEquals(parser.parse(request.getBody().readUtf8()), parser.parse(json));\n      return request;\n   }\n\n   /** So that we can ignore formatting. */\n   private final JsonParser parser = new JsonParser();\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/internal/BaseGoogleComputeEngineExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.internal;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.base.Throwables.propagate;\nimport static com.google.common.io.BaseEncoding.base64Url;\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\nimport static org.jclouds.googlecloud.config.GoogleCloudProperties.PROJECT_NAME;\nimport static org.jclouds.oauth.v2.config.OAuthProperties.JWS_ALG;\nimport static org.jclouds.util.Strings2.toStringAndClose;\n\nimport java.io.IOException;\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.googlecomputeengine.GoogleComputeEngineProviderMetadata;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.io.Payload;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.rest.internal.BaseRestApiExpectTest;\n\nimport com.google.common.base.Joiner;\nimport com.google.inject.Module;\n\npublic class BaseGoogleComputeEngineExpectTest<T> extends BaseRestApiExpectTest<T> {\n   protected static final String COMPUTE_SCOPE = \"https://www.googleapis.com/auth/compute\";\n   protected static final String COMPUTE_READONLY_SCOPE = \"https://www.googleapis.com/auth/compute.readonly\";\n   protected static final String BASE_URL = \"https://www.googleapis.com/compute/v1/projects\";\n\n   private static final String header = \"{\\\"alg\\\":\\\"none\\\",\\\"typ\\\":\\\"JWT\\\"}\";\n\n   private static final String CLAIMS_TEMPLATE = \"{\" +\n           \"\\\"iss\\\":\\\"%s\\\",\" +\n           \"\\\"scope\\\":\\\"%s\\\",\" +\n           \"\\\"aud\\\":\\\"https://accounts.google.com/o/oauth2/token\\\",\" +\n           \"\\\"exp\\\":3600,\" +\n           \"\\\"iat\\\":0}\";\n\n   protected static final String TOKEN = \"1/8xbJqaOZXSUZbHLl5EOtu1pxz3fmmetKx9W8CV4t79M\";\n\n   protected static final HttpResponse TOKEN_RESPONSE = HttpResponse.builder().statusCode(200).payload(\n           payloadFromString(\"{\\n\" +\n                   \"  \\\"access_token\\\" : \\\"\" + TOKEN + \"\\\",\\n\" +\n                   \"  \\\"token_type\\\" : \\\"Bearer\\\",\\n\" +\n                   \"  \\\"expires_in\\\" : 3600\\n\" +\n                   \"}\")).build();\n\n   protected BaseGoogleComputeEngineExpectTest() {\n      provider = \"google-compute-engine\";\n      identity = \"761326798069-r5mljlln1rd4lrbhg75efgigp36m78j5@developer.gserviceaccount.com\";\n   }\n\n   @Override protected ProviderMetadata createProviderMetadata(){\n      return new GoogleComputeEngineProviderMetadata();\n   }\n\n   @Override protected Module createModule() {\n      return GoogleComputeEngineTestModule.INSTANCE;\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      props.put(PROJECT_NAME, \"party\");\n      // use no sig algorithm for expect tests (means no credential is required either)\n      props.put(JWS_ALG, \"none\");\n      return props;\n   }\n\n   @Override\n   protected HttpRequestComparisonType compareHttpRequestAsType(HttpRequest input) {\n      HttpRequestComparisonType reqType = HttpRequestComparisonType.DEFAULT;\n      if (input.getPayload() != null) {\n         if (input.getPayload().getContentMetadata().getContentType().equals(APPLICATION_JSON)) {\n            reqType = HttpRequestComparisonType.JSON;\n         }\n      }\n      return reqType;\n   }\n\n   protected HttpRequest requestForScopes(String... scopes) {\n      String claims = String.format(CLAIMS_TEMPLATE, identity, Joiner.on(\",\").join(scopes));\n\n      String payload = \"grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&\" +\n              // Base64 Encoded Header\n              \"assertion=\" + base64Url().omitPadding().encode(header.getBytes(UTF_8)) + \".\" +\n              // Base64 Encoded Claims\n              base64Url().omitPadding().encode(claims.getBytes(UTF_8)) + \".\";\n\n      return HttpRequest.builder()\n              .method(\"POST\")\n              .endpoint(URI.create(\"https://accounts.google.com/o/oauth2/token\"))\n              .addHeader(\"Accept\", APPLICATION_JSON)\n              .payload(payloadFromStringWithContentType(payload, \"application/x-www-form-urlencoded\"))\n              .build();\n   }\n\n   protected static Payload staticPayloadFromResource(String resource) {\n      try {\n         return payloadFromString(\n               toStringAndClose(BaseGoogleComputeEngineExpectTest.class.getResourceAsStream(resource)));\n      } catch (IOException e) {\n         throw propagate(e);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/internal/BaseGoogleComputeEngineParseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.internal;\n\nimport java.util.Date;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.googlecomputeengine.config.GoogleComputeEngineParserModule;\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.json.config.GsonModule;\n\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\npublic abstract class BaseGoogleComputeEngineParseTest<T> extends BaseItemParserTest<T> {\n\n   protected static final String BASE_URL = \"https://www.googleapis.com/compute/v1/projects\";\n\n   @Override\n   protected Injector injector() {\n      return Guice.createInjector(new GsonModule(), new GoogleComputeEngineParserModule());\n   }\n\n   protected static Date parse(String iso8601) {\n      return new SimpleDateFormatDateService().iso8601DateParse(iso8601);\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/internal/GoogleComputeEngineTestModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.internal;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.base.Throwables.propagate;\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.expectLastCall;\nimport static org.easymock.EasyMock.replay;\nimport static org.jclouds.crypto.Pems.privateKeySpec;\nimport static org.jclouds.crypto.Pems.publicKeySpec;\nimport static org.jclouds.crypto.PemsTest.PRIVATE_KEY;\nimport static org.jclouds.crypto.PemsTest.PUBLIC_KEY;\n\nimport java.security.KeyFactory;\nimport java.security.KeyPair;\nimport java.security.KeyPairGenerator;\nimport java.security.PrivateKey;\nimport java.security.PublicKey;\nimport java.security.SecureRandom;\nimport java.security.interfaces.RSAPublicKey;\nimport java.util.concurrent.atomic.AtomicInteger;\n\nimport org.jclouds.crypto.Crypto;\nimport org.jclouds.oauth.v2.filters.JWTBearerTokenFlow;\nimport org.jclouds.oauth.v2.filters.TestJWTBearerTokenFlow;\nimport org.jclouds.ssh.SshKeys;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.io.ByteSource;\nimport com.google.inject.Binder;\nimport com.google.inject.Module;\nimport com.google.inject.TypeLiteral;\n\nenum GoogleComputeEngineTestModule implements Module {\n   INSTANCE;\n\n   private final KeyPair keyPair;\n   final String openSshKey;\n\n   GoogleComputeEngineTestModule() {\n      try {\n         KeyFactory keyfactory = KeyFactory.getInstance(\"RSA\");\n         PrivateKey privateKey = keyfactory\n               .generatePrivate(privateKeySpec(ByteSource.wrap(PRIVATE_KEY.getBytes(UTF_8))));\n         PublicKey publicKey = keyfactory.generatePublic(publicKeySpec(ByteSource.wrap(PUBLIC_KEY.getBytes(UTF_8))));\n         keyPair = new KeyPair(publicKey, privateKey);\n         openSshKey = SshKeys.encodeAsOpenSSH(RSAPublicKey.class.cast(publicKey));\n      } catch (Exception e) {\n         throw propagate(e);\n      }\n   }\n\n   @Override public void configure(Binder binder) {\n      // Predictable time\n      binder.bind(JWTBearerTokenFlow.class).to(TestJWTBearerTokenFlow.class);\n\n      // Predictable ssh keys\n      Crypto crypto = createMock(Crypto.class);\n      KeyPairGenerator rsaKeyPairGenerator = createMock(KeyPairGenerator.class);\n      SecureRandom secureRandom = createMock(SecureRandom.class);\n      expect(crypto.rsaKeyPairGenerator()).andReturn(rsaKeyPairGenerator).anyTimes();\n      rsaKeyPairGenerator.initialize(2048, secureRandom);\n      expectLastCall().anyTimes();\n      expect(rsaKeyPairGenerator.genKeyPair()).andReturn(keyPair).anyTimes();\n      replay(crypto, rsaKeyPairGenerator, secureRandom);\n      binder.bind(Crypto.class).toInstance(crypto);\n      binder.bind(SecureRandom.class).toInstance(secureRandom);\n\n      //  predictable node names\n      final AtomicInteger suffix = new AtomicInteger();\n      binder.bind(new TypeLiteral<Supplier<String>>() {\n      }).toInstance(new Supplier<String>() {\n         @Override\n         public String get() {\n            return suffix.getAndIncrement() + \"\";\n         }\n      });\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/internal/ToIteratorOfListPageExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.internal;\n\nimport static org.jclouds.googlecomputeengine.options.ListOptions.Builder.maxResults;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Iterator;\nimport java.util.List;\n\nimport org.jclouds.googlecloud.domain.ForwardingListPage;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.GoogleComputeEngineApi;\nimport org.jclouds.googlecomputeengine.config.GoogleComputeEngineParserModule;\nimport org.jclouds.googlecomputeengine.domain.Address;\nimport org.jclouds.googlecomputeengine.domain.Image;\nimport org.jclouds.googlecomputeengine.domain.Instance;\nimport org.jclouds.googlecomputeengine.features.AddressApi;\nimport org.jclouds.googlecomputeengine.features.ImageApi;\nimport org.jclouds.googlecomputeengine.features.InstanceApi;\nimport org.jclouds.googlecomputeengine.parse.ParseAddressTest;\nimport org.jclouds.googlecomputeengine.parse.ParseImageTest;\nimport org.jclouds.googlecomputeengine.parse.ParseInstanceTest;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.json.Json;\nimport org.jclouds.json.config.GsonModule;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.inject.Guice;\n\n@Test(groups = \"unit\", testName = \"ToIteratorOfListPageTest\")\npublic class ToIteratorOfListPageExpectTest extends BaseGoogleComputeEngineExpectTest<GoogleComputeEngineApi> {\n\n   private final Json json = Guice.createInjector(new GsonModule(), new GoogleComputeEngineParserModule())\n         .getInstance(Json.class);\n\n   public void globalScope() {\n      HttpRequest list = HttpRequest\n              .builder()\n              .method(\"GET\")\n              .endpoint(BASE_URL + \"/party/global/images\")\n              .addHeader(\"Accept\", \"application/json\")\n              .addHeader(\"Authorization\", \"Bearer \" + TOKEN).build();\n\n      HttpResponse operationResponse = HttpResponse.builder().statusCode(200)\n              .payload(payloadFromResource(\"/image_list_single_page.json\")).build();\n\n      ImageApi imageApi = requestsSendResponses(requestForScopes(COMPUTE_READONLY_SCOPE),\n              TOKEN_RESPONSE, list, operationResponse).images();\n\n      Iterator<ListPage<Image>> images = imageApi.list();\n\n      assertEquals(images.next().size(), 3);\n   }\n\n   public void multiplePagesProjectScoped() {\n      HttpRequest list1 = HttpRequest\n              .builder()\n              .method(\"GET\")\n              .endpoint(BASE_URL + \"/party/global/images?maxResults=1\")\n              .addHeader(\"Accept\", \"application/json\")\n              .addHeader(\"Authorization\", \"Bearer \" + TOKEN).build();\n\n      HttpRequest list2 = list1.toBuilder()\n               .endpoint(BASE_URL + \"/party/global/images?pageToken=token1&maxResults=1\").build();\n\n      HttpRequest list3 = list1.toBuilder()\n               .endpoint(BASE_URL + \"/party/global/images?pageToken=token2&maxResults=1\").build();\n\n      List<Image> items = ImmutableList.of(new ParseImageTest().expected());\n\n      HttpResponse list1Response = HttpResponse.builder().statusCode(200)\n              .payload(json.toJson(ForwardingListPage.create(items, \"token1\"))).build();\n\n      HttpResponse list2Response = HttpResponse.builder().statusCode(200)\n            .payload(json.toJson(ForwardingListPage.create(items, \"token2\"))).build();\n\n      HttpResponse list3Response = HttpResponse.builder().statusCode(200)\n            .payload(json.toJson(ForwardingListPage.create(items, null))).build();\n\n      ImageApi imageApi = orderedRequestsSendResponses(requestForScopes(COMPUTE_READONLY_SCOPE),\n              TOKEN_RESPONSE, list1, list1Response, list2, list2Response, list3, list3Response).images();\n\n      Iterator<ListPage<Image>> images = imageApi.list(maxResults(1));\n\n      int imageCounter = 0;\n      while (images.hasNext()) {\n         imageCounter += images.next().size();\n      }\n      assertEquals(imageCounter, 3);\n   }\n\n   public void multiplePagesRegionScoped() {\n      HttpRequest list1 = HttpRequest\n            .builder()\n            .method(\"GET\")\n            .endpoint(BASE_URL + \"/party/regions/us-central1/addresses?maxResults=1\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"Authorization\", \"Bearer \" + TOKEN).build();\n\n      HttpRequest list2 = list1.toBuilder()\n            .endpoint(BASE_URL + \"/party/regions/us-central1/addresses?pageToken=token1&maxResults=1\").build();\n\n      HttpRequest list3 = list1.toBuilder()\n            .endpoint(BASE_URL + \"/party/regions/us-central1/addresses?pageToken=token2&maxResults=1\").build();\n\n      List<Address> items = ImmutableList.of(new ParseAddressTest().expected());\n\n      HttpResponse list1Response = HttpResponse.builder().statusCode(200)\n            .payload(json.toJson(ForwardingListPage.create(items, \"token1\"))).build();\n\n      HttpResponse list2Response = HttpResponse.builder().statusCode(200)\n            .payload(json.toJson(ForwardingListPage.create(items, \"token2\"))).build();\n\n      HttpResponse list3Response = HttpResponse.builder().statusCode(200)\n            .payload(json.toJson(ForwardingListPage.create(items, null))).build();\n\n      AddressApi addressApi = orderedRequestsSendResponses(requestForScopes(COMPUTE_READONLY_SCOPE),\n            TOKEN_RESPONSE, list1, list1Response, list2, list2Response, list3, list3Response)\n            .addressesInRegion(\"us-central1\");\n\n      Iterator<ListPage<Address>> addresses = addressApi.list(maxResults(1));\n\n      int addressCounter = 0;\n      while (addresses.hasNext()) {\n         addressCounter += addresses.next().size();\n      }\n      assertEquals(addressCounter, 3);\n   }\n\n   public void multiplePagesZoneScoped() {\n      HttpRequest list1 = HttpRequest\n            .builder()\n            .method(\"GET\")\n            .endpoint(BASE_URL + \"/party/zones/us-central1-a/instances?maxResults=1\")\n            .addHeader(\"Accept\", \"application/json\")\n            .addHeader(\"Authorization\", \"Bearer \" + TOKEN).build();\n\n      HttpRequest list2 = list1.toBuilder()\n            .endpoint(BASE_URL + \"/party/zones/us-central1-a/instances?pageToken=token1&maxResults=1\").build();\n\n      HttpRequest list3 = list1.toBuilder()\n            .endpoint(BASE_URL + \"/party/zones/us-central1-a/instances?pageToken=token2&maxResults=1\").build();\n\n      List<Instance> items = ImmutableList.of(new ParseInstanceTest().expected());\n\n      HttpResponse list1Response = HttpResponse.builder().statusCode(200)\n            .payload(json.toJson(ForwardingListPage.create(items, \"token1\"))).build();\n\n      HttpResponse list2Response = HttpResponse.builder().statusCode(200)\n            .payload(json.toJson(ForwardingListPage.create(items, \"token2\"))).build();\n\n      HttpResponse list3Response = HttpResponse.builder().statusCode(200)\n            .payload(json.toJson(ForwardingListPage.create(items, null))).build();\n\n      InstanceApi instanceApi = orderedRequestsSendResponses(requestForScopes(COMPUTE_READONLY_SCOPE),\n            TOKEN_RESPONSE, list1, list1Response, list2, list2Response, list3, list3Response)\n            .instancesInZone(\"us-central1-a\");\n\n      Iterator<ListPage<Instance>> instances = instanceApi.list(maxResults(1));\n\n      int instanceCounter = 0;\n      while (instances.hasNext()) {\n         instanceCounter += instances.next().size();\n      }\n      assertEquals(instanceCounter, 3);\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseAddressListTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\n\nimport org.jclouds.googlecloud.domain.ForwardingListPage;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.domain.Address;\nimport org.jclouds.googlecomputeengine.domain.Address.Status;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"ParseAddressListTest\")\npublic class ParseAddressListTest extends BaseGoogleComputeEngineParseTest<ListPage<Address>> {\n\n   @Override\n   public String resource() {\n      return \"/address_list.json\";\n   }\n\n   @Override @Consumes(APPLICATION_JSON)\n   public ListPage<Address> expected() {\n      return expected(BASE_URL);\n   }\n\n   @Consumes(APPLICATION_JSON)\n   public ListPage<Address> expected(String baseUrl) {\n      Address address1 = new ParseAddressTest().expected(baseUrl);\n      Address address2 = Address.create( //\n            \"4881363978908129158\", // id\n            URI.create(baseUrl + \"/party/regions/us-central1/addresses/test-ip2\"), // selfLink\n            \"test-ip2\", // name\n            parse(\"2013-07-26T14:08:21.552-07:00\"), //creationTimestamp\n            \"\", // description\n            Status.RESERVED, // status\n            null, // users\n            URI.create(baseUrl + \"/party/regions/us-central1\"), // region\n            \"173.255.118.115\" // address\n      );\n      return ForwardingListPage.create( //\n            ImmutableList.of(address1, address2), // items\n            null // nextPageToken\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseAddressTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\n\nimport org.jclouds.googlecomputeengine.domain.Address;\nimport org.jclouds.googlecomputeengine.domain.Address.Status;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"ParseAddressTest\")\npublic class ParseAddressTest extends BaseGoogleComputeEngineParseTest<Address> {\n\n   @Override\n   public String resource() {\n      return \"/address_get.json\";\n   }\n\n   @Override @Consumes(APPLICATION_JSON)\n   public Address expected() {\n      return expected(BASE_URL);\n   }\n\n   @Consumes(APPLICATION_JSON)\n   public Address expected(String baseUrl) {\n      return Address.create( //d\n            \"4439373783165447583\", // id\n            URI.create(baseUrl + \"/party/regions/us-central1/addresses/test-ip1\"), // selfLink\n            \"test-ip1\", // name\n            parse(\"2013-07-26T13:57:20.204-07:00\"), // creationTimestamp\n            \"\", // description\n            Status.IN_USE, // status\n            ImmutableList.of(URI.create(baseUrl + \"/party/regions/us-central1-a/forwardingRules/test-forwarding-rule\")), // users\n            URI.create(baseUrl + \"/party/regions/us-central1\"), // region\n            \"173.255.115.190\" // address\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseBackendServiceListTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.googlecomputeengine.domain.BackendService;\nimport org.jclouds.googlecloud.domain.ForwardingListPage;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\")\npublic class ParseBackendServiceListTest extends BaseGoogleComputeEngineParseTest<ListPage<BackendService>> {\n\n   @Override\n   public String resource() {\n      return \"/backend_service_list.json\";\n   }\n\n   @Override\n   @Consumes(APPLICATION_JSON)\n   public ListPage<BackendService> expected() {\n      return expected(BASE_URL);\n   }\n\n   @Consumes(APPLICATION_JSON)\n   public ListPage<BackendService> expected(String baseUrl) {\n      return ForwardingListPage.create(\n            ImmutableList.of(\n                  new ParseBackendServiceTest().expected(baseUrl),\n                  BackendService.create(\"12862241067393040785\", //id\n                        new SimpleDateFormatDateService().iso8601DateParse(\"2012-04-13T03:05:04.365\"), //creationTimestamp,\n                        URI.create(baseUrl + \"/myproject/global/backendServices/jclouds-test-2\"), //selfLink,\n                        \"jclouds-test-2\", //name,\n                        \"Backend Service 2\", //description\n                        null, // backends,\n                        ImmutableList.of(URI.create(baseUrl + \"/myproject/global/httpHealthChecks/jclouds-test\")), //healthChecks,\n                        45, //timeoutSec,\n                        80, //port,\n                        \"HTTP\", //protocol,\n                        null, //fingerprint\n                        null) // portName\n                  ),\n            null\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseBackendServiceTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.googlecomputeengine.domain.BackendService;\nimport org.jclouds.googlecomputeengine.domain.BackendService.Backend;\nimport org.jclouds.googlecomputeengine.domain.BackendService.Backend.BalancingModes;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\")\npublic class ParseBackendServiceTest extends BaseGoogleComputeEngineParseTest<BackendService> {\n\n   @Override\n   public String resource() {\n      return \"/backend_service_get.json\";\n   }\n\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   public BackendService expected() {\n      return expected(BASE_URL);\n   }\n\n   public BackendService expected(String baseUrl) {\n      URI selfLink = URI.create(baseUrl + \"/myproject/global/backendServices/jclouds-test\");\n      URI healthCheck = URI.create(baseUrl + \"/myproject/global/httpHealthChecks/jclouds-test\");\n      URI group = URI.create(\"https://www.googleapis.com/resourceviews/v1beta1\"\n                             + \"/projects/myproject/zones/us-central1-a/\"\n                             + \"resourceViews/jclouds-test\");\n      Backend backend = Backend.create(\"A resource view\", //description\n                                       group, //group\n                                       BalancingModes.UTILIZATION, //balancingMode\n                                       (float) 0.8, //maxUtilization\n                                       null, //maxRate\n                                       null, //maxRatePerInstance\n                                       (float) 1.0); // capacityScaler\n      return BackendService.create(\"15448612110458377529\", //id\n            new SimpleDateFormatDateService().iso8601DateParse(\"2014-07-18T13:37:48.574-07:00\"), //creationTimestamp\n            selfLink, //selfLink\n            \"jclouds-test\", //name\n            \"Backend service\", // description\n            ImmutableList.of(backend), //backends\n            ImmutableList.of(healthCheck), //healthChecks\n            30, //timeoutSec\n            80, //port\n            \"HTTP\", //protocol\n            \"I6n5NPSXn8g=\", //fingerprint\n            null // portName\n            );\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseDiskListTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport jakarta.ws.rs.Consumes;\n\nimport org.jclouds.googlecloud.domain.ForwardingListPage;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.domain.Disk;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"ParseDiskListTest\")\npublic class ParseDiskListTest extends BaseGoogleComputeEngineParseTest<ListPage<Disk>> {\n\n   @Override\n   public String resource() {\n      return \"/disk_list.json\";\n   }\n\n   @Override @Consumes(APPLICATION_JSON)\n   public ListPage<Disk> expected() {\n      return expected(BASE_URL);\n   }\n\n   @Consumes(APPLICATION_JSON)\n   public ListPage<Disk> expected(String baseUrl) {\n      return ForwardingListPage.create( //\n            ImmutableList.of(new ParseDiskTest().expected(baseUrl)), // items\n            null // nextPageToken\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseDiskTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\n\nimport org.jclouds.googlecomputeengine.domain.Disk;\nimport org.jclouds.googlecomputeengine.domain.Disk.Status;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ParseDiskTest\")\npublic class ParseDiskTest extends BaseGoogleComputeEngineParseTest<Disk> {\n\n   @Override\n   public String resource() {\n      return \"/disk_get.json\";\n   }\n\n   @Override @Consumes(APPLICATION_JSON)\n   public Disk expected() {\n      return expected(BASE_URL);\n   }\n\n   @Consumes(APPLICATION_JSON)\n   public Disk expected(String baseUrl){\n      return Disk.create( //\n            \"13050421646334304115\", // id\n            parse(\"2012-11-25T01:38:48.306\"), // creationTimestamp\n            URI.create(baseUrl + \"/party/zones/us-central1-a\"), // zone\n            Status.READY, // status\n            \"testimage1\", // name\n            null, // description\n            1, // sizeGb\n            null, // sourceSnapshot\n            null, // sourceSnapshotId\n            URI.create(baseUrl + \"/party/zones/us-central1-a/disks/testimage1\"), // selfLink\n            null, // sourceImage\n            null, // sourceImageId\n            URI.create(baseUrl + \"/studied-point-720/zones/us-central1-a/diskTypes/pd-standard\"), // type\n            null // license\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseDiskTypeListTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\n\nimport org.jclouds.googlecloud.domain.ForwardingListPage;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.domain.DiskType;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"ParseDiskTypeListTest\")\npublic class ParseDiskTypeListTest extends BaseGoogleComputeEngineParseTest<ListPage<DiskType>> {\n\n   @Override\n   public String resource() {\n      return \"/disktype_list.json\";\n   }\n\n   @Override @Consumes(APPLICATION_JSON)\n   public ListPage<DiskType> expected() {\n      String contentBaseUrl = BASE_URL.replace(\"www\", \"content\");\n      DiskType diskType1 = DiskType.create(\n            parse(\"2014-06-02T11:07:28.530-07:00\"), // creationTimestamp\n            \"pd-standard\", // name\n            \"Standard Persistent Disk\", // description\n            \"10GB-10TB\", // validDiskSize\n            null, // deprecated\n            URI.create(contentBaseUrl + \"/studied-point-720/zones/us-central1-a\"), // zone\n            URI.create(contentBaseUrl + \"/studied-point-720/zones/us-central1-a/diskTypes/pd-standard\"), // selfLink\n            500 // defaultDiskSizeGb\n      );\n      DiskType diskType2 = new ParseDiskTypeTest().expected();\n      return ForwardingListPage.create( //\n            ImmutableList.of(diskType1, diskType2), // items\n            null // nextPageToken\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseDiskTypeTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\n\nimport org.jclouds.googlecomputeengine.domain.DiskType;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ParseDiskTypeTest\")\npublic class ParseDiskTypeTest extends BaseGoogleComputeEngineParseTest<DiskType> {\n\n   @Override\n   public String resource() {\n      return \"/disktype.json\";\n   }\n\n   @Override @Consumes(APPLICATION_JSON)\n   public DiskType expected() {\n      String contentBaseUrl = BASE_URL.replace(\"www\", \"content\");\n      return DiskType.create(\n            parse(\"2014-06-02T11:07:28.529-07:00\"), // creationTimestamp\n            \"pd-ssd\", // name\n            \"SSD Persistent Disk\", // description\n            \"10GB-1TB\", // validDiskSize\n            null, // deprecated\n            URI.create(contentBaseUrl + \"/studied-point-720/zones/us-central1-a\"), // zone\n            URI.create(contentBaseUrl + \"/studied-point-720/zones/us-central1-a/diskTypes/pd-ssd\"), // selfLink\n            100 // defaultDiskSizeGb\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseFirewallListTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\n\nimport org.jclouds.googlecloud.domain.ForwardingListPage;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.domain.Firewall;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"ParseFirewallListTest\")\npublic class ParseFirewallListTest extends BaseGoogleComputeEngineParseTest<ListPage<Firewall>> {\n\n   @Override\n   public String resource() {\n      return \"/firewall_list.json\";\n   }\n\n   @Override @Consumes(APPLICATION_JSON)\n   public ListPage<Firewall> expected() {\n      return expected(BASE_URL);\n   }\n\n   @Consumes(APPLICATION_JSON)\n   public ListPage<Firewall> expected(String baseUrl) {\n      Firewall firewall1 = new ParseFirewallTest().expected(baseUrl);\n      Firewall firewall2 = Firewall.create( //\n            \"12862241067393040785\", // id\n            URI.create(baseUrl + \"/google/global/firewalls/default-ssh\"), // selfLink\n            parse(\"2012-04-13T03:05:04.365\"), // creationTimestamp\n            \"default-ssh\", // name\n            \"SSH allowed from anywhere\", // description\n            URI.create(baseUrl + \"/google/global/networks/default\"), // network\n            ImmutableList.of(\"0.0.0.0/0\"), // sourceRanges\n            null, // sourceTags\n            null, // targetTags\n            ImmutableList.of(Firewall.Rule.create(\"tcp\", ImmutableList.of(\"22\"))) // allowed\n      );\n      return ForwardingListPage.create( //\n            ImmutableList.of(firewall1, firewall2), // items\n            null // nextPageToken\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseFirewallTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\n\nimport org.jclouds.googlecomputeengine.domain.Firewall;\nimport org.jclouds.googlecomputeengine.domain.Firewall.Rule;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"ParseFirewallTest\")\npublic class ParseFirewallTest extends BaseGoogleComputeEngineParseTest<Firewall> {\n\n   @Override\n   public String resource() {\n      return \"/firewall_get.json\";\n   }\n\n   @Override @Consumes(APPLICATION_JSON)\n   public Firewall expected() {\n      return expected(BASE_URL);\n   }\n\n   @Consumes(APPLICATION_JSON)\n   public Firewall expected(String base_url) {\n      return Firewall.create( //\n            \"12862241031274216284\", // id\n            URI.create(base_url + \"/party/global/firewalls/jclouds-test\"), // selfLink\n            parse(\"2012-04-13T03:05:02.855\"), // creationTimestamp\n            \"jclouds-test\", // name\n            \"Internal traffic from default allowed\", // description\n            URI.create(base_url + \"/party/global/networks/jclouds-test\"), // network\n            ImmutableList.of(\"10.0.0.0/8\"), // sourceRanges\n            null, // sourceTags\n            null, // targetTags\n            ImmutableList.of( // allowed\n                  Rule.create(\"tcp\", ImmutableList.of(\"1-65535\")), //\n                  Rule.create(\"udp\", ImmutableList.of(\"1-65535\")), //\n                  Rule.create(\"icmp\", null) //\n            ));\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseForwardingRuleListTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport jakarta.ws.rs.Consumes;\n\nimport org.jclouds.googlecloud.domain.ForwardingListPage;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.domain.ForwardingRule;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"ParseForwardingRuleListTest\")\npublic class ParseForwardingRuleListTest extends BaseGoogleComputeEngineParseTest<ListPage<ForwardingRule>> {\n\n   @Override\n   public String resource() {\n      return \"/forwardingrule_list.json\";\n   }\n\n   @Override @Consumes(APPLICATION_JSON)\n   public ListPage<ForwardingRule> expected() {\n      return expected(BASE_URL);\n   }\n\n   @Consumes(APPLICATION_JSON)\n   public ListPage<ForwardingRule> expected(String baseUrl) {\n      return ForwardingListPage.create( //\n            ImmutableList.of(new ParseForwardingRuleTest().expected(baseUrl)), // items\n            null // nextPageToken\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseForwardingRuleTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.googlecomputeengine.domain.ForwardingRule;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ParseForwardingRuleTest\")\npublic class ParseForwardingRuleTest extends BaseGoogleComputeEngineParseTest<ForwardingRule> {\n\n   @Override\n   public String resource() {\n      return \"/forwardingrule_get.json\";\n   }\n\n   @Override @Consumes(APPLICATION_JSON)\n   public ForwardingRule expected() {\n      return expected(BASE_URL);\n   }\n\n   public ForwardingRule expected(String baseUrl) {\n      return ForwardingRule.create( //\n            \"6732523704970219884\", // id\n            URI.create(baseUrl + \"/party/regions/europe-west1/forwardingRules/test-forwarding-rule\"), // selfLink\n            \"test-forwarding-rule\", // name\n            null, // description\n            new SimpleDateFormatDateService().iso8601DateParse(\"2014-01-08T06:51:10.809-08:00\"), // creationTimestamp\n            URI.create(baseUrl + \"/party/regions/europe-west1\"), // region\n            \"23.251.129.77\", // ipAddress\n            ForwardingRule.IPProtocol.TCP, // ipProtocol\n            \"1-65535\", // portRange\n            URI.create(baseUrl + \"/party/regions/europe-west1/targetPools/test-target-pool\") // target\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseGlobalForwardingRuleListTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport jakarta.ws.rs.Consumes;\n\nimport org.jclouds.googlecloud.domain.ForwardingListPage;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.domain.ForwardingRule;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"ParseGlobalForwardingRuleListTest\")\npublic class ParseGlobalForwardingRuleListTest extends BaseGoogleComputeEngineParseTest<ListPage<ForwardingRule>> {\n\n   @Override\n   public String resource() {\n      return \"/global_forwarding_rule_list.json\";\n   }\n\n   @Override @Consumes(APPLICATION_JSON)\n   public ListPage<ForwardingRule> expected() {\n      return ForwardingListPage.create(\n            ImmutableList.of(new ParseGlobalForwardingRuleTest().expected()), // items\n            null // nextPageToken\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseGlobalForwardingRuleTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.googlecomputeengine.domain.ForwardingRule;\nimport org.jclouds.googlecomputeengine.domain.ForwardingRule.IPProtocol;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\n\npublic class ParseGlobalForwardingRuleTest extends BaseGoogleComputeEngineParseTest<ForwardingRule> {\n\n   @Override\n   public String resource() {\n      return \"/global_forwarding_rule_get.json\";\n   }\n\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   public ForwardingRule expected() {\n      return ForwardingRule.create(\"8192211304399313984\", // id\n         URI.create(\"https://www.googleapis.com/compute/v1/projects/myproject/global/forwardingRules/jclouds-test\"), // selfLink\n         \"jclouds-test\", // name\n         \"tcp forwarding rule\", // description\n         new SimpleDateFormatDateService().iso8601DateParse(\"2014-07-18T09:47:30.826-07:00\"), // creationTimestamp\n         null, // region\n         \"107.178.255.156\", //IPAddress\n         IPProtocol.TCP, //IPProtocol\n         \"80-80\", // portRange\n         URI.create(\"https://www.googleapis.com/compute/v1/projects/myproject/global/targetHttpProxies/jclouds-test\") // Target\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseGlobalOperationListTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport jakarta.ws.rs.Consumes;\n\nimport org.jclouds.googlecloud.domain.ForwardingListPage;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.domain.Operation;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"ParseGlobalOperationListTest\")\npublic class ParseGlobalOperationListTest extends BaseGoogleComputeEngineParseTest<ListPage<Operation>> {\n\n   @Override\n   public String resource() {\n      return \"/global_operation_list.json\";\n   }\n\n   @Override @Consumes(APPLICATION_JSON)\n   public ListPage<Operation> expected() {\n      return expected(BASE_URL);\n   }\n\n   @Consumes(APPLICATION_JSON)\n   public ListPage<Operation> expected(String baseUrl) {\n      return ForwardingListPage.create( //\n            ImmutableList.of(new ParseGlobalOperationTest().expected(baseUrl)), // items\n            null // nextPageToken\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseGlobalOperationTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\n\nimport org.jclouds.googlecomputeengine.domain.Operation;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ParseGlobalOperationTest\")\npublic class ParseGlobalOperationTest extends BaseGoogleComputeEngineParseTest<Operation> {\n\n   @Override\n   public String resource() {\n      return \"/global_operation.json\";\n   }\n\n   @Override @Consumes(APPLICATION_JSON)\n   public Operation expected() {\n      return expected(BASE_URL);\n   }\n\n   @Consumes(APPLICATION_JSON)\n   public Operation expected(String baseUrl) {\n      return Operation.create( //\n            \"13053095055850848306\", // id\n            parse(\"2013-07-26T13:57:20.204-07:00\"), // creationTimestamp\n            URI.create(baseUrl + \"/party/global/operations/operation-1354084865060\"),\n            \"operation-1354084865060\", // name\n            null, // description\n            URI.create(baseUrl + \"/party/global/firewalls/jclouds-test-delete\"), // targetLink\n            \"13053094017547040099\", // targetId\n            null, // clientOperationId\n            Operation.Status.DONE, // status\n            null, // statusMessage\n            \"user@developer.gserviceaccount.com\", // user\n            100, // progress\n            parse(\"2012-11-28T06:41:05.060\"), // insertTime\n            parse(\"2012-11-28T06:41:05.142\"), // startTime\n            parse(\"2012-11-28T06:41:06.142\"), // endTime\n            null, // httpErrorStatusCode\n            null, // httpErrorMessage\n            \"insert\", // operationType\n            null, // errors\n            null, // warnings\n            null, // region\n            null // zone\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseHealthStatusTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.net.URI;\nimport jakarta.ws.rs.Consumes;\n\nimport org.jclouds.googlecomputeengine.domain.HealthStatus;\nimport org.jclouds.googlecomputeengine.domain.HealthStatus.HealthStatusInternal;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\")\npublic class ParseHealthStatusTest extends BaseGoogleComputeEngineParseTest<HealthStatus> {\n\n   @Override\n   public String resource() {\n      return \"/health_status_get_health.json\";\n   }\n\n   @Override\n   @Consumes(APPLICATION_JSON)\n   public HealthStatus expected() {\n      return expected(BASE_URL);\n   }\n\n   @Consumes(APPLICATION_JSON)\n   public HealthStatus expected(String baseUrl) {\n      URI uri = URI.create(baseUrl + \"/party/zones/us-central1-a/instances/\"\n                           + \"jclouds-test\");\n      return HealthStatus.create(\n            ImmutableList.of(HealthStatusInternal.create(\n                  null, // ipAddress\n                  80, // port\n                  uri, // instance\n                  \"HEALTHY\" //healthState\n                  )) //healthStatuses\n            );\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseHttpHealthCheckListTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\n\nimport org.jclouds.googlecloud.domain.ForwardingListPage;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.domain.HttpHealthCheck;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"ParseHttpHealthCheckListTest\")\npublic class ParseHttpHealthCheckListTest extends BaseGoogleComputeEngineParseTest<ListPage<HttpHealthCheck>> {\n\n   @Override\n   public String resource() {\n      return \"/httphealthcheck_list.json\";\n   }\n\n   @Override @Consumes(APPLICATION_JSON)\n   public ListPage<HttpHealthCheck> expected() {\n      return expected(BASE_URL);\n   }\n\n   @Consumes(APPLICATION_JSON)\n   public ListPage<HttpHealthCheck> expected(String baseUrl) {\n      HttpHealthCheck healthCheck1 = new ParseHttpHealthCheckTest().expected(baseUrl);\n      HttpHealthCheck healthCheck2 = HttpHealthCheck.create( //\n            \"1035854271083519643\", // id\n            URI.create(baseUrl + \"/party-gce/global/httpHealthChecks/myname-andrea-kmzmi1bh-http-health-check\"),\n            // selfLink\n            parse(\"2014-01-08T14:38:29.363-08:00\"),\n            \"myname-andrea-kmzmi1bh-http-health-check\", // name\n            null, // description\n            null, // host\n            null, // requestPath\n            null,  // port\n            null,  // checkIntervalSec\n            5,  // timeoutSec\n            2,  // unhealthyThreshold\n            null // healthyThreshold\n      );\n      HttpHealthCheck healthCheck3 = HttpHealthCheck.create( //\n            \"7006563292274658743\", // id\n            URI.create(baseUrl + \"/party-gce/global/httpHealthChecks/myname-andrea-zk7gadwq-http-health-check\"),\n            // selfLink\n            parse(\"2014-01-08T14:48:03.276-08:00\"), // creationTimestamp\n            \"myname-andrea-zk7gadwq-http-health-check\", // name\n            null, // description\n            null, // host\n            null, // requestPath\n            null,  // port\n            null,  // checkIntervalSec\n            5,  // timeoutSec\n            2,  // unhealthyThreshold\n            null // healthyThreshold\n      );\n      return ForwardingListPage.create( //\n            ImmutableList.of(healthCheck1, healthCheck2, healthCheck3), // items\n            null // nextPageToken\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseHttpHealthCheckTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\n\nimport org.jclouds.googlecomputeengine.domain.HttpHealthCheck;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ParseHttpHealthCheckTest\")\npublic class ParseHttpHealthCheckTest extends BaseGoogleComputeEngineParseTest<HttpHealthCheck> {\n\n   @Override\n   public String resource() {\n      return \"/httphealthcheck_get.json\";\n   }\n\n   @Override @Consumes(APPLICATION_JSON)\n   public HttpHealthCheck expected() {\n      return expected(BASE_URL);\n   }\n\n   @Consumes(APPLICATION_JSON)\n   public HttpHealthCheck expected(String baseUrl) {\n      return HttpHealthCheck.create( //\n            \"2761502483700014319\", // id\n            URI.create(baseUrl + \"/party-gce/global/httpHealthChecks/http-health-check-api-live-test\"), // selfLink\n            parse(\"2014-01-14T05:55:54.910-08:00\"), // creationTimestamp\n            \"http-health-check-api-live-test\", // name\n            \"Test Health Check\", // description\n            null, // host\n            \"/\", // requestPath\n            80,  // port\n            5,  // checkIntervalSec\n            5,  // timeoutSec\n            2,  // unhealthyThreshold\n            2 // healthyThreshold\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseImageListTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.googlecloud.domain.ForwardingListPage;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.domain.Image;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"ParseImageListTest\")\npublic class ParseImageListTest extends BaseGoogleComputeEngineParseTest<ListPage<Image>> {\n\n   @Override\n   public String resource() {\n      return \"/image_list.json\";\n   }\n\n   @Override @Consumes(MediaType.APPLICATION_JSON)\n   public ListPage<Image> expected() {\n      return expected(BASE_URL);\n      }\n\n   @Consumes(MediaType.APPLICATION_JSON)\n   public ListPage<Image> expected(String baseUrl) {\n       return ForwardingListPage.create( //\n            ImmutableList.of(new ParseImageTest().expected(baseUrl)), // items\n            null // nextPageToken\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseImageTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\n\nimport org.jclouds.googlecomputeengine.domain.Deprecated;\nimport org.jclouds.googlecomputeengine.domain.Deprecated.State;\nimport org.jclouds.googlecomputeengine.domain.Image;\nimport org.jclouds.googlecomputeengine.domain.Image.RawDisk;\nimport org.jclouds.googlecomputeengine.domain.Image.Status;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"ParseImageTest\")\npublic class ParseImageTest extends BaseGoogleComputeEngineParseTest<Image> {\n\n   @Override\n   public String resource() {\n      return \"/image_get.json\";\n   }\n\n   @Override @Consumes(APPLICATION_JSON)\n   public Image expected() {\n      return expected(BASE_URL);\n   }\n\n   @Consumes(APPLICATION_JSON)\n   public Image expected(String baseUrl) {\n      return Image.create( //\n            \"12941197498378735318\", // id\n            URI.create(baseUrl + \"/centos-cloud/global/images/centos-6-2-v20120326\"), // selfLink\n            parse(\"2012-07-16T22:16:13.468\"), // creationTimestamp\n            \"centos-6-2-v20120326\", // name\n            \"DEPRECATED. CentOS 6.2 image; Created Mon, 26 Mar 2012 21:19:09 +0000\", // description\n            \"RAW\", // sourceType\n            RawDisk.create(URI.create(\"\"), \"TAR\", null), // rawDisk\n            Deprecated.create( // deprecated\n                  State.DEPRECATED, // state\n                  URI.create(baseUrl + \"/centos-cloud/global/images/centos-6-v20130104\"), // replacement\n                  null, // deprecated\n                  null, // obsolete\n                  null // deleted\n           ),\n           Status.READY, // status\n           Long.parseLong(\"881210631\", 10), // archivedSizeBytes\n           Long.parseLong(\"8\", 10), // diskSizeGb\n           baseUrl + \"/party/zones/us-central1-a/disk/disk\", // sourceDisk\n           \"9598530021316715047\", // sourceDiskId\n           ImmutableList.of(baseUrl + \"/suse-cloud/global/licenses/sles-12\") // license\n            );\n\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseInstanceListTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport jakarta.ws.rs.Consumes;\n\nimport org.jclouds.googlecloud.domain.ForwardingListPage;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.domain.Instance;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"ParseInstanceListTest\")\npublic class ParseInstanceListTest extends BaseGoogleComputeEngineParseTest<ListPage<Instance>> {\n\n   @Override\n   public String resource() {\n      return \"/instance_list.json\";\n   }\n\n   @Override @Consumes(APPLICATION_JSON)\n   public ListPage<Instance> expected() {\n      return expected(BASE_URL);\n   }\n\n   @Consumes(APPLICATION_JSON)\n   public ListPage<Instance> expected(String baseUrl) {\n      return ForwardingListPage.create( //\n            ImmutableList.of(new ParseInstanceTest().expected(baseUrl)), // items\n            null // nextPageToken\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseInstanceSerialOutputTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\n\nimport org.jclouds.googlecomputeengine.domain.Instance.SerialPortOutput;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ParseInstanceSerialOutputTest\")\npublic class ParseInstanceSerialOutputTest extends BaseGoogleComputeEngineParseTest<SerialPortOutput> {\n\n   @Override\n   public String resource() {\n      return \"/instance_serial_port.json\";\n   }\n\n   @Override @Consumes(APPLICATION_JSON)\n   public SerialPortOutput expected() {\n      return expected(BASE_URL);\n   }\n\n   @Consumes(APPLICATION_JSON)\n   public SerialPortOutput expected(String baseUrl) {\n      return SerialPortOutput.create(\n            URI.create(baseUrl + \"/party/zones/us-central1-a/instances/test-instance/serialPort\"),\n            \"console output\");\n   }\n\n   @Consumes(APPLICATION_JSON)\n   public SerialPortOutput expected(String baseUrl, String contents) {\n      return SerialPortOutput.create(\n              URI.create(baseUrl + \"/party/zones/us-central1-a/instances/test-instance/serialPort\"),\n              contents\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseInstanceTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport jakarta.ws.rs.Consumes;\nimport java.net.URI;\n\nimport com.google.common.collect.ImmutableList;\nimport org.jclouds.googlecomputeengine.domain.AttachDisk;\nimport org.jclouds.googlecomputeengine.domain.AttachDisk.DiskInterface;\nimport org.jclouds.googlecomputeengine.domain.Instance;\nimport org.jclouds.googlecomputeengine.domain.Instance.AttachedDisk;\nimport org.jclouds.googlecomputeengine.domain.Instance.NetworkInterface;\nimport org.jclouds.googlecomputeengine.domain.Instance.Scheduling.OnHostMaintenance;\nimport org.jclouds.googlecomputeengine.domain.Instance.ServiceAccount;\nimport org.jclouds.googlecomputeengine.domain.Metadata;\nimport org.jclouds.googlecomputeengine.domain.Tags;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ParseInstanceTest\")\npublic class ParseInstanceTest extends BaseGoogleComputeEngineParseTest<Instance> {\n\n   @Override\n   public String resource() {\n      return \"/instance_get.json\";\n   }\n\n   @Override @Consumes(APPLICATION_JSON)\n   public Instance expected() {\n      return expected(BASE_URL);\n   }\n\n   @Consumes(APPLICATION_JSON)\n   public Instance expected(String baseUrl) {\n      return Instance.create( //\n            \"13051190678907570425\", // id\n            parse(\"2012-11-25T23:48:20.758\"), // creationTimestamp\n            URI.create(baseUrl + \"/party/zones/us-central1-a/instances/test-0\"), // selfLink\n            \"test-0\", // name\n            \"desc\", // description\n            Tags.create(\"abcd\", ImmutableList.of(\"aTag\", \"Group-port-42\")), // tags\n            URI.create(baseUrl + \"/party/zones/us-central1-a/machineTypes/n1-standard-1\"), // machineType\n            Instance.Status.RUNNING, // status\n            null, // statusMessage\n            URI.create(baseUrl + \"/party/zones/us-central1-a\"), // zone\n            true, // canIpForward\n            ImmutableList.of(NetworkInterface.create( //\n                  \"nic0\", // name\n                  URI.create(baseUrl + \"/party/global/networks/default\"), // network\n                  \"10.240.121.115\", // networkIP\n                  null // accessConfigs\n            )), // networkInterfaces\n            ImmutableList.of(AttachedDisk.create( //\n                  0, // index\n                  AttachedDisk.Type.PERSISTENT, // type\n                  AttachedDisk.Mode.READ_WRITE, // mode\n                  URI.create(baseUrl + \"/party/zones/us-central1-a/disks/test\"), // source\n                  \"test\", // deviceName\n                  false, // autoDelete\n                  true, // boot\n                  AttachDisk.InitializeParams.create(\n                        \"test\", // diskName\n                        Long.parseLong(\"100\", 10), // diskSizeGb\n                        URI.create(baseUrl + \"/debian-cloud/global/images/debian-7-wheezy-v20140718\"), // sourceImage\n                        URI.create(baseUrl + \"/party/zones/us-central1-a/diskTypes/pd-standard\") // diskType\n                        ), // initializeParams\n                  ImmutableList.of(baseUrl + \"/suse-cloud/global/licenses/sles-12\"), // licenses\n                  DiskInterface.NVME // interface\n            )), // disks\n            Metadata.create(\"efgh\")\n                    .put(\"aKey\", \"aValue\")\n                    .put(\"jclouds-delete-boot-disk\", \"true\"), // metadata\n            ImmutableList.of(ServiceAccount.create(\"default\", ImmutableList.of(\"myscope\"))), // serviceAccounts\n            Instance.Scheduling.create(OnHostMaintenance.MIGRATE, false, false) // scheduling\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseLicenseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\n\nimport org.jclouds.googlecomputeengine.domain.License;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ParseLicenseTest\")\npublic class ParseLicenseTest extends BaseGoogleComputeEngineParseTest<License> {\n\n   @Override\n   public String resource() {\n      return \"/license_get.json\";\n   }\n\n   @Override @Consumes(APPLICATION_JSON)\n   public License expected() {\n      return expected(BASE_URL);\n   }\n\n   @Consumes(APPLICATION_JSON)\n   public License expected(String baseUrl) {\n      return License.create(URI.create(baseUrl + \"/suse-cloud/global/licenses/sles-12\"), \"sles-12\", true);\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseMachineTypeListTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\n\nimport org.jclouds.googlecloud.domain.ForwardingListPage;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.domain.MachineType;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"ParseMachineTypeListTest\")\npublic class ParseMachineTypeListTest extends BaseGoogleComputeEngineParseTest<ListPage<MachineType>> {\n\n   @Override\n   public String resource() {\n      return \"/machinetype_list.json\";\n   }\n\n   @Override @Consumes(APPLICATION_JSON)\n   public ListPage<MachineType> expected() {\n      return expected(BASE_URL);\n   }\n\n   @Consumes(APPLICATION_JSON)\n   public ListPage<MachineType> expected(String baseUrl) {\n      MachineType machineType1 = MachineType.create( //\n            \"4618642685664990776\", // id\n            parse(\"2013-04-25T13:32:49.088-07:00\"), // creationTimestamp\n            URI.create(baseUrl + \"/party/zones/us-central1-a/machineTypes/f1-micro\"), // selfLink\n            \"f1-micro\", // name\n            \"1 vCPU (shared physical core) and 0.6 GB RAM\", // description\n            1, // guestCpus\n            614, // memoryMb\n            null, // imageSpaceGb\n            null, // scratchDisks\n            4, // maximumPersistentDisks\n            3072, // maximumPersistentDisksSizeGb\n            \"us-central1-a\", // zone\n            null // deprecated\n      );\n      MachineType machineType2 = MachineType.create( //\n            \"12907738072351752276\", // id\n            parse(\"2012-06-07T20:48:14.670\"), // creationTimestamp\n            URI.create(baseUrl + \"/party/zones/us-central1-a/machineTypes/n1-standard-1\"), // selfLink\n            \"n1-standard-1\", // name\n            \"1 vCPU, 3.75 GB RAM, and a 10 GB ephemeral root disk\", // description\n            1, // guestCpus\n            3840, // memoryMb\n            null, // imageSpaceGb\n            null, // scratchDisks\n            16, // maximumPersistentDisks\n            128, // maximumPersistentDisksSizeGb\n            \"us-central1-a\", // zone\n            null // deprecated\n      );\n      MachineType machineType3 = MachineType.create( //\n            \"12908560709887590691\", // id\n            parse(\"2012-06-07T20:51:19.936\"), // creationTimestamp\n            URI.create(baseUrl + \"/party/zones/us-central1-a/machineTypes/n1-standard-8-d\"), // selfLink\n            \"n1-standard-8-d\", // name\n            \"8 vCPUs, 30 GB RAM, a 10 GB ephemeral root disk, and 2 extra 1770 GB ephemeral disks\", // description\n            8, // guestCpus\n            30720, // memoryMb\n            null, // imageSpaceGb\n            ImmutableList.of(MachineType.ScratchDisk.create(1770), MachineType.ScratchDisk.create(1770)), // scratchDisks\n            16, // maximumPersistentDisks\n            1024, // maximumPersistentDisksSizeGb\n            \"us-central1-a\", // zone\n            null // deprecated\n      );\n      return ForwardingListPage.create( //\n            ImmutableList.of(machineType1, machineType2, machineType3), // items\n            null // nextPageToken\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseMachineTypeTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\n\nimport org.jclouds.googlecomputeengine.domain.MachineType;\nimport org.jclouds.googlecomputeengine.domain.MachineType.ScratchDisk;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"ParseMachineTypeTest\")\npublic class ParseMachineTypeTest extends BaseGoogleComputeEngineParseTest<MachineType> {\n\n   @Override\n   public String resource() {\n      return \"/machinetype.json\";\n   }\n\n   @Override @Consumes(APPLICATION_JSON)\n   public MachineType expected() {\n      return expected(BASE_URL);\n   }\n\n   @Consumes(APPLICATION_JSON)\n   public MachineType expected(String baseUrl) {\n      return MachineType.create( //\n            \"12907738072351752276\", // id\n            parse(\"2012-06-07T20:48:14.670\"), // creationTimestamp\n            URI.create(baseUrl + \"/party/zones/us-central1-a/machineTypes/n1-standard-1\"), // selfLink\n            \"n1-standard-1\", // name\n            \"1 vCPU, 3.75 GB RAM, and a 10 GB ephemeral root disk\", // description\n            1, // guestCpus\n            3840, // memoryMb\n            null, // imageSpaceGb\n            ImmutableList.of(ScratchDisk.create(1770), ScratchDisk.create(1770)), // scratchDisks\n            16, // maximumPersistentDisks\n            128, // maximumPersistentDisksSizeGb\n            \"us-central1-a\", // zone\n            null // deprecated\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport jakarta.ws.rs.Consumes;\n\nimport org.jclouds.googlecomputeengine.domain.Metadata;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ParseMetadataTest\")\npublic class ParseMetadataTest extends BaseGoogleComputeEngineParseTest<Metadata> {\n\n   @Override\n   public String resource() {\n      return \"/metadata.json\";\n   }\n\n   @Override @Consumes(APPLICATION_JSON)\n   public Metadata expected() {\n      return Metadata.create(\"efgh\").put(\"propA\", \"valueA\").put(\"propB\", \"valueB\");\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseNetworkListTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport jakarta.ws.rs.Consumes;\n\nimport org.jclouds.googlecloud.domain.ForwardingListPage;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.domain.Network;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"ParseNetworkListTest\")\npublic class ParseNetworkListTest extends BaseGoogleComputeEngineParseTest<ListPage<Network>> {\n\n   @Override\n   public String resource() {\n      return \"/network_list.json\";\n   }\n\n   @Override @Consumes(APPLICATION_JSON)\n   public ListPage<Network> expected() {\n      return expected(BASE_URL);\n   }\n\n   @Consumes(APPLICATION_JSON)\n   public ListPage<Network> expected(String baseUrl) {\n      return ForwardingListPage.create( //\n            ImmutableList.of(new ParseNetworkTest().expected(baseUrl)), // items\n            null // nextPageToken\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseNetworkTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.net.URI;\nimport java.util.Collections;\n\nimport jakarta.ws.rs.Consumes;\n\nimport org.jclouds.googlecomputeengine.domain.Network;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ParseNetworkTest\")\npublic class ParseNetworkTest extends BaseGoogleComputeEngineParseTest<Network> {\n\n   @Override\n   public String resource() {\n      return \"/network_get.json\";\n   }\n\n   @Override @Consumes(APPLICATION_JSON)\n   public Network expected() {\n      return expected(BASE_URL);\n   }\n\n   @Consumes(APPLICATION_JSON)\n   public Network expected(String baseUrl) {\n      return Network.create( //\n            \"13024414170909937976\", // id\n            parse(\"2012-10-24T20:13:19.967\"), // creationTimestamp\n            URI.create(baseUrl + \"/party/networks/jclouds-test\"), // selfLink\n            \"jclouds-test\", // name\n            \"A custom network for the project\", // description\n            \"10.0.0.0/8\", // rangeIPv4\n            \"10.0.0.1\", // gatewayIPv4\n            false,\n            Collections.<URI> emptyList() // subnetworks\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseOperationTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\n\nimport org.jclouds.googlecomputeengine.domain.KeyValuePair;\nimport org.jclouds.googlecomputeengine.domain.Operation;\nimport org.jclouds.googlecomputeengine.domain.Warning;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"ParseOperationTest\")\npublic class ParseOperationTest extends BaseGoogleComputeEngineParseTest<Operation> {\n\n   @Override\n   public String resource() {\n      return \"/operation.json\";\n   }\n\n   @Override @Consumes(APPLICATION_JSON)\n   public Operation expected() {\n      return expected(BASE_URL);\n   }\n\n   @Consumes(APPLICATION_JSON)\n   public Operation expected(String baseUrl) {\n      return Operation.create( //\n            \"13053095055850848306\", // id\n            parse(\"2013-07-26T13:57:20.204-07:00\"), // creationTimestamp\n            URI.create(baseUrl + \"/party/zones/us-central1-a/operations/operation-1354084865060\"),\n            \"operation-1354084865060\", // name\n            null, // description\n            URI.create(baseUrl + \"/party/zones/us-central1-a/instances/test-1\"), // targetLink\n            \"13053094017547040099\", // targetId\n            null, // clientOperationId\n            Operation.Status.DONE, // status\n            null, // statusMessage\n            \"user@developer.gserviceaccount.com\", // user\n            100, // progress\n            parse(\"2012-11-28T06:41:05.060\"), // insertTime\n            parse(\"2012-11-28T06:41:05.142\"), // startTime\n            parse(\"2012-11-28T06:41:06.142\"), // endTime\n            400, // httpErrorStatusCode\n            \"BAD REQUEST\", // httpErrorMessage\n            \"insert\", // operationType\n            Operation.Error.create(ImmutableList.of(Operation.Error.Entry\n                  .create(\"INVALID_FIELD_VALUE\", null,\n                        \"Invalid value for field 'resource.urlMaps': \"\n                        + \"'projects/party/global/urlMaps/target-http-proxy-api-live-test-url-map-2'.\"\n                        + \" Resource was not found.\"))), // errors\n            ImmutableList.of(Warning.create(\"NO_RESULTS_ON_PAGE\", \"This is an example warning\",\n                  ImmutableList.of(KeyValuePair\n                        .create(\"scope\", \"There are no results for scope 'zones/asia-east1-b' on this page.\")))), // warnings\n            URI.create(baseUrl + \"/party/regions/us-central1\"), // region\n            URI.create(baseUrl + \"/party/zones/us-central1-a\") // zone\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseProjectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.googlecomputeengine.domain.Metadata;\nimport org.jclouds.googlecomputeengine.domain.Project;\nimport org.jclouds.googlecomputeengine.domain.Quota;\nimport org.jclouds.googlecomputeengine.domain.Project.UsageExportLocation;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"ParseProjectTest\")\npublic class ParseProjectTest extends BaseGoogleComputeEngineParseTest<Project> {\n\n   @Override\n   public String resource() {\n      return \"/project.json\";\n   }\n\n   @Override @Consumes(APPLICATION_JSON)\n   public Project expected() {\n      return expected(BASE_URL);\n   }\n\n   @Consumes(APPLICATION_JSON)\n   public Project expected(String baseUrl) {\n      return Project.create( //\n            \"13024414184846275913\", // id\n            URI.create(baseUrl + \"/761326798069\"), // selfLink\n            \"party\", // name\n            \"\", // description\n            Metadata.create(\"efgh\").put(\"propA\", \"valueA\").put(\"propB\", \"valueB\"), // commonInstanceMetadata\n            ImmutableList.of( //\n                  Quota.create(\"INSTANCES\", 0, 8), //\n                  Quota.create(\"CPUS\", 0, 8), //\n                  Quota.create(\"EPHEMERAL_ADDRESSES\", 0, 8), //\n                  Quota.create(\"DISKS\", 0, 8), //\n                  Quota.create(\"DISKS_TOTAL_GB\", 0, 100), //\n                  Quota.create(\"SNAPSHOTS\", 0, 1000), //\n                  Quota.create(\"NETWORKS\", 1, 5), //\n                  Quota.create(\"FIREWALLS\", 2, 100), //\n                  Quota.create(\"IMAGES\", 0, 100)), // quotas\n            null, // externalIpAddresses\n            new SimpleDateFormatDateService().iso8601DateParse(\"2012-10-24T20:13:16.252\"), // creationTimestamp\n            UsageExportLocation.create(\"test-bucket\", \"report-prefix\")// usageExportLocation\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseQuotaTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport jakarta.ws.rs.Consumes;\n\nimport org.jclouds.googlecomputeengine.domain.Quota;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ParseQuotaTest\")\npublic class ParseQuotaTest extends BaseGoogleComputeEngineParseTest<Quota> {\n\n   @Override\n   public String resource() {\n      return \"/quota.json\";\n   }\n\n   @Override @Consumes(APPLICATION_JSON)\n   public Quota expected() {\n      return Quota.create(\"INSTANCES\", 0.0, 8.0);\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseRegionListTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\n\nimport org.jclouds.googlecloud.domain.ForwardingListPage;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.domain.Quota;\nimport org.jclouds.googlecomputeengine.domain.Region;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"ParseRegionListTest\")\npublic class ParseRegionListTest extends BaseGoogleComputeEngineParseTest<ListPage<Region>> {\n\n   @Override\n   public String resource() {\n      return \"/region_list.json\";\n   }\n\n   @Override @Consumes(APPLICATION_JSON)\n   public ListPage<Region> expected() {\n      return expected(BASE_URL);\n   }\n\n   @Consumes(APPLICATION_JSON)\n   public ListPage<Region> expected(String baseUrl) {\n      Region region1 = new ParseRegionTest().expected(baseUrl);\n      Region region2 = Region.create( //\n            \"6396763663251190992\", // id\n            parse(\"2013-07-08T14:40:37.939-07:00\"), // creationTimestamp\n            URI.create(baseUrl + \"/party/regions/us-central1\"), // selfLink\n            \"us-central1\", // name\n            \"us-central1\", // description\n            Region.Status.UP, // status\n            ImmutableList.of(URI.create(baseUrl + \"/party/zones/us-central1-a\")), // zones\n            ImmutableList.of( //\n                  Quota.create(\"INSTANCES\", 0, 8), //\n                  Quota.create(\"CPUS\", 0, 8), //\n                  Quota.create(\"EPHEMERAL_ADDRESSES\", 0, 8), //\n                  Quota.create(\"DISKS\", 0, 8), //\n                  Quota.create(\"DISKS_TOTAL_GB\", 0, 100), //\n                  Quota.create(\"SNAPSHOTS\", 0, 1000), //\n                  Quota.create(\"NETWORKS\", 1, 5), //\n                  Quota.create(\"FIREWALLS\", 2, 100), //\n                  Quota.create(\"IMAGES\", 0, 100)) // quotas\n      );\n      return ForwardingListPage.create( //\n            ImmutableList.of(region1, region2), // items\n            null // nextPageToken\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseRegionOperationTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\n\nimport org.jclouds.googlecomputeengine.domain.Operation;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ParseRegionOperationTest\")\npublic class ParseRegionOperationTest extends BaseGoogleComputeEngineParseTest<Operation> {\n\n   @Override\n   public String resource() {\n      return \"/region_operation.json\";\n   }\n\n   @Override @Consumes(APPLICATION_JSON)\n   public Operation expected() {\n      return expected(BASE_URL);\n   }\n\n   @Consumes(APPLICATION_JSON)\n   public Operation expected(String baseUrl) {\n      return Operation.create( //\n            \"13053095055850848306\", // id\n            parse(\"2013-07-26T13:57:20.204-07:00\"), // creationTimestamp\n            URI.create(baseUrl + \"/party/regions/us-central1/operations/operation-1354084865060\"), // selfLink\n            \"operation-1354084865060\", // name\n            null, // description\n            URI.create(baseUrl + \"/party/regions/us-central1/addresses/test-address\"), // targetLink\n            \"13053094017547040099\", // targetId\n            null, // clientOperationId\n            Operation.Status.DONE, // status\n            null, // statusMessage\n            \"user@developer.gserviceaccount.com\", // user\n            100, // progress\n            parse(\"2012-11-28T06:41:05.060\"), // insertTime\n            parse(\"2012-11-28T06:41:05.142\"), // startTime\n            parse(\"2012-11-28T06:41:06.142\"), // endTime\n            null, // httpErrorStatusCode\n            null, // httpErrorMessage\n            \"insert\", // operationType\n            null, // errors\n            null, // warnings\n            URI.create(baseUrl + \"/party/regions/us-central1\"), // region\n            null // zone\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseRegionTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\n\nimport org.jclouds.googlecomputeengine.domain.Quota;\nimport org.jclouds.googlecomputeengine.domain.Region;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"ParseRegionTest\")\npublic class ParseRegionTest extends BaseGoogleComputeEngineParseTest<Region> {\n\n   @Override\n   public String resource() {\n      return \"/region_get.json\";\n   }\n\n   @Override @Consumes(APPLICATION_JSON)\n   public Region expected() {\n      return expected(BASE_URL);\n   }\n\n   @Consumes(APPLICATION_JSON)\n   public Region expected(String baseUrl) {\n      return Region.create( //\n            \"12912210600542709766\", // id\n            parse(\"2013-07-08T14:40:37.939-07:00\"), // creationTimestamp\n            URI.create(baseUrl + \"/party/regions/us-central1\"), // selfLink\n            \"us-central1\", // name\n            \"us-central1\", // description\n            Region.Status.UP, // status\n            ImmutableList.of(//\n                  URI.create(baseUrl + \"/party/zones/us-central1-a\"),\n                  URI.create(baseUrl + \"/party/zones/us-central1-b\")), // zones\n            ImmutableList.of( //\n                  Quota.create(\"INSTANCES\", 0, 8), //\n                  Quota.create(\"CPUS\", 0, 8), //\n                  Quota.create(\"EPHEMERAL_ADDRESSES\", 0, 8), //\n                  Quota.create(\"DISKS\", 0, 8), //\n                  Quota.create(\"DISKS_TOTAL_GB\", 0, 100), //\n                  Quota.create(\"SNAPSHOTS\", 0, 1000), //\n                  Quota.create(\"NETWORKS\", 1, 5), //\n                  Quota.create(\"FIREWALLS\", 2, 100), //\n                  Quota.create(\"IMAGES\", 0, 100)) // quotas\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseRouteListTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.googlecloud.domain.ForwardingListPage;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.domain.Route;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"ParseRouteListTest\")\npublic class ParseRouteListTest extends BaseGoogleComputeEngineParseTest<ListPage<Route>> {\n\n   @Override\n   public String resource() {\n      return \"/route_list.json\";\n   }\n\n   @Override @Consumes(MediaType.APPLICATION_JSON)\n   public ListPage<Route> expected() {\n      return expected(BASE_URL);\n   }\n\n   @Consumes(MediaType.APPLICATION_JSON)\n   public ListPage<Route> expected(String baseUrl) {\n      Route route1 = new ParseRouteTest().expected(baseUrl);\n      Route route2 = Route.create( //\n            \"507025480040058551\", // id\n            parse(\"2013-07-08T14:40:38.502-07:00\"), // creationTimestamp\n            URI.create(baseUrl + \"/party/global/routes/default-route-fc92a41ecb5a8d17\"), // selfLink\n            \"default-route-fc92a41ecb5a8d17\", // name\n            \"Default route to the Internet.\", // description\n            URI.create(baseUrl + \"/party/global/networks/default\"), // network\n            null, // tags\n            \"0.0.0.0/0\", // destRange\n            1000, // priority\n            null, // nextHopInstance\n            null, // nextHopIp\n            null, // nextHopNetwork\n            URI.create(baseUrl + \"/party/global/gateways/default-internet-gateway\"), // nextHopGateway\n            null, // warnings\n            null // nextHopVpnTunnel\n      );\n      return ForwardingListPage.create( //\n            ImmutableList.of(route1, route2), // items\n            null // nextPageToken\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseRouteTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\n\nimport org.jclouds.googlecomputeengine.domain.KeyValuePair;\nimport org.jclouds.googlecomputeengine.domain.Route;\nimport org.jclouds.googlecomputeengine.domain.Warning;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"ParseRouteTest\")\npublic class ParseRouteTest extends BaseGoogleComputeEngineParseTest<Route> {\n\n   @Override\n   public String resource() {\n      return \"/route_get.json\";\n   }\n\n   @Override @Consumes(APPLICATION_JSON)\n   public Route expected() {\n      return expected(BASE_URL);\n   }\n\n   @Consumes(APPLICATION_JSON)\n   public Route expected(String baseUrl) {\n      return Route.create( //\n            \"7241926205630356071\", // id\n            parse(\"2013-07-08T14:40:38.502-07:00\"), // creationTimestamp\n            URI.create(baseUrl + \"/party/global/routes/default-route-c99ebfbed0e1f375\"), // selfLink\n            \"default-route-c99ebfbed0e1f375\", // name\n            \"Default route to the virtual network.\", // description\n            URI.create(baseUrl + \"/party/global/networks/default\"), // network\n            ImmutableList.of(\"fooTag\", \"barTag\"), // tags\n            \"10.240.0.0/16\", // destRange\n            1000, // priority\n            null, // nextHopInstance\n            null, // nextHopIp\n            URI.create(baseUrl + \"/party/global/networks/default\"), // nextHopNetwork\n            null, // nextHopGateway\n            ImmutableList.of(Warning.create(\"NO_RESULTS_ON_PAGE\", \"This is an example warning\", ImmutableList.of(\n                  KeyValuePair.create(\"scope\", \"There are no results for scope 'zones/asia-east1-b' on this page.\")))), // warnings\n            null // nextHopVpnTunnel\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseSnapshotListTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\n\nimport org.jclouds.googlecloud.domain.ForwardingListPage;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.domain.Snapshot;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"ParseSnapshotListTest\")\npublic class ParseSnapshotListTest extends BaseGoogleComputeEngineParseTest<ListPage<Snapshot>> {\n\n   @Override\n   public String resource() {\n      return \"/snapshot_list.json\";\n   }\n\n   @Override @Consumes(APPLICATION_JSON)\n   public ListPage<Snapshot> expected() {\n      return expected(BASE_URL);\n   }\n\n   @Consumes(APPLICATION_JSON)\n   public ListPage<Snapshot> expected(String baseUrl) {\n      Snapshot snapshot1 = new ParseSnapshotTest().expected(baseUrl);\n      Snapshot snapshot2 = Snapshot.create( //\n            \"13895715048576107883\", // id\n            URI.create(baseUrl + \"/party/global/snapshots/test-snap2\"), // selfLink\n            parse(\"2013-07-26T12:57:01.927-07:00\"), // creationTimestamp\n            \"test-snap2\", // name\n            \"\", // description\n            10, // sizeGb\n            \"READY\", // status\n            URI.create(baseUrl + \"/party/zones/us-central1-a/disks/testimage1\"), // sourceDisk\n            \"8243603669926824540\", // sourceDiskId\n            null, // storageBytes\n            null, // storageByteStatus\n            null // licenses\n      );\n      return ForwardingListPage.create( //\n            ImmutableList.of(snapshot1, snapshot2), // items\n            null // nextPageToken\n      );\n   }\n\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseSnapshotTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\n\nimport org.jclouds.googlecomputeengine.domain.Snapshot;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ParseSnapshotTest\")\npublic class ParseSnapshotTest extends BaseGoogleComputeEngineParseTest<Snapshot> {\n\n   @Override\n   public String resource() {\n      return \"/snapshot_get.json\";\n   }\n\n   @Override @Consumes(APPLICATION_JSON)\n   public Snapshot expected() {\n      return expected(BASE_URL);\n   }\n\n   @Consumes(APPLICATION_JSON)\n   public Snapshot expected(String baseUrl) {\n      return Snapshot.create( //\n            \"9734455566806191190\", // id\n            URI.create(baseUrl + \"/party/global/snapshots/test-snap\"), // selfLink\n            parse(\"2013-07-26T12:54:23.173-07:00\"), // creationTimestamp\n            \"test-snap\", // name\n            \"\", // description\n            10, // sizeGb\n            \"READY\", // status\n            URI.create(baseUrl + \"/party/zones/us-central1-a/disks/testimage1\"), // sourceDisk\n            \"8243603669926824540\", // sourceDiskId\n            null, // storageBytes\n            null, // storageByteStatus\n            null // licenses\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseSubnetworkListTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport jakarta.ws.rs.Consumes;\n\nimport org.jclouds.googlecloud.domain.ForwardingListPage;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.domain.Subnetwork;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"ParseSubnetworkListTest\")\npublic class ParseSubnetworkListTest extends BaseGoogleComputeEngineParseTest<ListPage<Subnetwork>> {\n\n   @Override\n   public String resource() {\n      return \"/subnetwork_list.json\";\n   }\n\n   @Override @Consumes(APPLICATION_JSON)\n   public ListPage<Subnetwork> expected() {\n      return expected(BASE_URL);\n   }\n\n   @Consumes(APPLICATION_JSON)\n   public ListPage<Subnetwork> expected(String baseUrl) {\n      return ForwardingListPage.create( //\n            ImmutableList.of(new ParseSubnetworkTest().expected(baseUrl)), // items\n            null // nextPageToken\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseSubnetworkTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\n\nimport org.jclouds.googlecomputeengine.domain.Subnetwork;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ParseSubnetworkTest\")\npublic class ParseSubnetworkTest extends BaseGoogleComputeEngineParseTest<Subnetwork> {\n\n   @Override\n   public String resource() {\n      return \"/subnetwork_get.json\";\n   }\n\n   @Override @Consumes(APPLICATION_JSON)\n   public Subnetwork expected() {\n      return expected(BASE_URL);\n   }\n\n   @Consumes(APPLICATION_JSON)\n   public Subnetwork expected(String baseUrl) {\n      return Subnetwork.create( //\n            \"5850679262666457680\", // id\n            parse(\"2016-06-07T14:29:35.476-07:00\"), // creationTimestamp\n            URI.create(baseUrl + \"/party/regions/someregion/subnetworks/jclouds-test\"), // selfLink\n            \"jclouds-test\", // name\n            \"A custom subnetwork for the project\", // description\n            \"10.128.0.1\",\n            URI.create(baseUrl + \"/party/global/networks/mynetwork\"), // network\n            \"10.128.0.0/20\", // rangeIPv4\n            URI.create(baseUrl + \"/party/regions/someregion\") // region\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseTargetHttpProxyListTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.googlecloud.domain.ForwardingListPage;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.domain.TargetHttpProxy;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\")\npublic class ParseTargetHttpProxyListTest extends BaseGoogleComputeEngineParseTest<ListPage<TargetHttpProxy>> {\n\n   @Override\n   public String resource() {\n      return \"/target_http_proxy_list.json\";\n   }\n\n   @Override @Consumes(MediaType.APPLICATION_JSON)\n   public ListPage<TargetHttpProxy> expected() {\n      return expected(BASE_URL);\n   }\n\n   @Consumes(MediaType.APPLICATION_JSON)\n   public ListPage<TargetHttpProxy> expected(String baseUrl) {\n      return ForwardingListPage.create(\n            ImmutableList.of(\n                  new ParseTargetHttpProxyTest().expected(baseUrl),\n                  TargetHttpProxy.create(\"13050421646334304116\", // id\n                        new SimpleDateFormatDateService().iso8601DateParse(\"2012-11-25T01:38:48.306\"), // creationTimestamp\n                        URI.create(baseUrl + \"/myproject/global/targetHttpProxies/jclouds-test-2\"), // selfLink\n                        \"jclouds-test-2\", // name\n                        \"Simple proxy\", // description\n                        URI.create(baseUrl + \"/myproject/global/urlMaps/jclouds-test-2\"))), // urlMap\n                  null // nextPageToken d\n            );\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseTargetHttpProxyTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.googlecomputeengine.domain.TargetHttpProxy;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class ParseTargetHttpProxyTest extends BaseGoogleComputeEngineParseTest<TargetHttpProxy> {\n\n   @Override\n   public String resource() {\n      return \"/target_http_proxy_get.json\";\n   }\n\n   @Override @Consumes(MediaType.APPLICATION_JSON)\n   public TargetHttpProxy expected() {\n      return expected(BASE_URL);\n   }\n\n   @Consumes(MediaType.APPLICATION_JSON)\n   public TargetHttpProxy expected(String baseUrl) {\n      return TargetHttpProxy.create(\"13050421646334304115\", // id\n            new SimpleDateFormatDateService().iso8601DateParse(\"2012-11-25T01:38:48.306\"), // creationTimestamp\n            URI.create(baseUrl + \"/myproject/global/targetHttpProxies/jclouds-test\"), // selfLink\n            \"jclouds-test\", // name\n            null,\n            URI.create(baseUrl + \"/myproject/global/urlMaps/jclouds-test\")); // urlMap\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseTargetInstanceListTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\n\nimport org.jclouds.googlecloud.domain.ForwardingListPage;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.domain.TargetInstance;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"ParseTargetInstanceListTest\")\npublic class ParseTargetInstanceListTest extends BaseGoogleComputeEngineParseTest<ListPage<TargetInstance>> {\n\n   @Override\n   public String resource() {\n      return \"/target_instance_list.json\";\n   }\n\n   @Override @Consumes(APPLICATION_JSON)\n   public ListPage<TargetInstance> expected() {\n      return expected(BASE_URL);\n   }\n\n   public ListPage<TargetInstance> expected(String baseURL){\n      return ForwardingListPage.create( //\n            ImmutableList.of(new ParseTargetInstanceTest().expected(baseURL),\n                  TargetInstance.create(\n                        \"7362436693678237415\", // id\n                        \"2014-11-20T17:35:17.268-08:00\", // creationTimestamp\n                        \"target-instance-2\", // name\n                        null, // description\n                        URI.create(baseURL + \"/party/zones/us-central1-a\"), // zone\n                        \"NO_NAT\", // natPolicy\n                        URI.create(baseURL + \"/party/zones/us-central1-a/instances/test-3\"), // instance\n                        URI.create(baseURL + \"/party/zones/us-central1-a/targetInstances/target-instance-2\") // selfLink\n                        )), // items\n            null // nextPageToken\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseTargetInstanceTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\n\nimport org.jclouds.googlecomputeengine.domain.TargetInstance;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ParseTargetInstanceTest\")\npublic class ParseTargetInstanceTest extends BaseGoogleComputeEngineParseTest<TargetInstance> {\n\n   @Override\n   public String resource() {\n      return \"/target_instance_get.json\";\n   }\n\n   @Override @Consumes(APPLICATION_JSON)\n   public TargetInstance expected() {\n      return expected(BASE_URL);\n   }\n\n   public TargetInstance expected(String baseUrl) {\n      return TargetInstance.create(\n            \"13050421646334304115\", // id\n            \"2014-07-18T09:47:30.826-07:00\", // creationTimestamp\n            \"target-instance-1\", // name\n            \"A pretty cool target instance\", // description\n            URI.create(baseUrl + \"/party/zones/us-central1-a\"), // zone\n            \"NO_NAT\", // natPolicy\n            URI.create(baseUrl + \"/party/zones/us-central1-a/instances/test-0\"), // instance\n            URI.create(baseUrl + \"/party/zones/us-central1-a/targetInstances/target-instance-1\")); //selfLink\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseTargetPoolListTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport jakarta.ws.rs.Consumes;\n\nimport org.jclouds.googlecloud.domain.ForwardingListPage;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.domain.TargetPool;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"ParseTargetPoolListTest\")\npublic class ParseTargetPoolListTest extends BaseGoogleComputeEngineParseTest<ListPage<TargetPool>> {\n\n   @Override\n   public String resource() {\n      return \"/targetpool_list.json\";\n   }\n\n   @Override @Consumes(APPLICATION_JSON)\n   public ListPage<TargetPool> expected() {\n      return expected(BASE_URL);\n   }\n\n   @Consumes(APPLICATION_JSON)\n   public ListPage<TargetPool> expected(String baseUrl) {\n      return ForwardingListPage.create( //\n            ImmutableList.of(new ParseTargetPoolTest().expected(baseUrl)), // items\n            null // nextPageToken\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseTargetPoolTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.googlecomputeengine.domain.TargetPool;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.jclouds.googlecomputeengine.options.TargetPoolCreationOptions.SessionAffinityValue;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ParseTargetPoolTest\")\npublic class ParseTargetPoolTest extends BaseGoogleComputeEngineParseTest<TargetPool> {\n\n   @Override\n   public String resource() {\n      return \"/targetpool_get.json\";\n   }\n\n   @Override @Consumes(MediaType.APPLICATION_JSON)\n   public TargetPool expected() {\n      return expected(BASE_URL);\n   }\n\n   @Consumes(MediaType.APPLICATION_JSON)\n   public TargetPool expected(String baseUrl) {\n      return TargetPool.create( //\n            \"5199309593612841404\", // id\n            URI.create(baseUrl + \"/party/regions/us-central1/targetPools/test-targetpool\"), // selfLink\n            parse(\"2014-01-07T05:25:27.783-08:00\"), // creationTimestamp\n            \"test-targetpool\", // name\n            null, // description\n            URI.create(baseUrl + \"/party/regions/us-central1\"), // region\n            null, // healthChecks\n            null, // instances\n            SessionAffinityValue.NONE, // sessionAffinity\n            null, // failoverRatio\n            null // backupPool\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseUrlMapListTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.googlecloud.domain.ForwardingListPage;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.domain.UrlMap;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\")\npublic class ParseUrlMapListTest extends BaseGoogleComputeEngineParseTest<ListPage<UrlMap>> {\n\n   @Override\n   public String resource() {\n      return \"/url_map_list.json\";\n   }\n\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   public ListPage<UrlMap> expected() {\n      return expected(BASE_URL);\n   }\n\n   @Consumes(MediaType.APPLICATION_JSON)\n   public ListPage<UrlMap> expected(String baseUrl) {\n      return ForwardingListPage.create(\n            ImmutableList.of(new ParseUrlMapTest().expected(baseUrl),\n                  UrlMap.create(\"13741966667737398120\", // id\n                        new SimpleDateFormatDateService().iso8601DateParse(\"2014-07-23T12:39:50.022-07:00\"), // creationTimestamp\n                        URI.create(baseUrl + \"/myproject/global/urlMaps/jclouds-test-2\"), // selfLink\n                        \"jclouds-test-2\", // name\n                        \"Basic url map\", // description\n                        null, // hostRules\n                        null, // pathMatchers\n                        null, // urlMapTests\n                        URI.create(baseUrl + \"/myproject/global/backendServices/jclouds-test\"), // defaultService\n                        \"EDqhvJucpz4=\")), // fingerprint\n            null);\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseUrlMapTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport java.net.URI;\nimport java.util.List;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.googlecomputeengine.domain.UrlMap;\nimport org.jclouds.googlecomputeengine.domain.UrlMap.UrlMapTest;\nimport org.jclouds.googlecomputeengine.domain.UrlMap.HostRule;\nimport org.jclouds.googlecomputeengine.domain.UrlMap.PathMatcher;\nimport org.jclouds.googlecomputeengine.domain.UrlMap.PathMatcher.PathRule;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\")\npublic class ParseUrlMapTest extends BaseGoogleComputeEngineParseTest<UrlMap> {\n\n   @Override\n   public String resource() {\n      return \"/url_map_get.json\";\n   }\n\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   public UrlMap expected() {\n      return expected(BASE_URL);\n   }\n\n   @Consumes(MediaType.APPLICATION_JSON)\n   public UrlMap expected(String baseUrl) {\n      URI service = URI.create(baseUrl + \"/myproject/global/backendServices/jclouds-test\");\n\n      List<HostRule> hostRules = ImmutableList.of(HostRule.create(null, // description\n            ImmutableList.of(\"jclouds-test\"), // hosts\n            \"path\")); // pathMatcher\n\n      List<PathMatcher> pathMatchers = ImmutableList.of(PathMatcher.create(\"path\", // name\n                                                                           null, // description\n                                                                           service, // defaultService\n            ImmutableList.of(PathRule.create(ImmutableList.of(\"/\"), // paths\n                                             service // service\n                                             )))); // pathRules\n\n      List<UrlMapTest> urlMapTests = ImmutableList.of(UrlMapTest.create(null, // description\n            \"jclouds-test\", // host\n            \"/test/path\", // path\n            service)); // service\n\n      return UrlMap.create(\"13741966667737398119\", // id\n            new SimpleDateFormatDateService().iso8601DateParse(\"2014-07-23T12:39:50.022-07:00\"), // creationTimestamp\n            URI.create(baseUrl + \"/myproject/global/urlMaps/jclouds-test\"), // selfLink\n            \"jclouds-test\", // name\n            \"Sample url map\", // description\n            hostRules, // hostRules\n            pathMatchers, // pathMatchers\n            urlMapTests, // urlMapTests\n            service, // defaultService\n            \"EDmhvJucpz4=\"); // fingerprint\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseUrlMapValidateTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport java.net.URI;\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport jakarta.ws.rs.Consumes;\n\nimport org.jclouds.googlecomputeengine.domain.UrlMapValidateResult;\nimport org.jclouds.googlecomputeengine.domain.UrlMapValidateResult.UrlMapValidateResultInternal.TestFailure;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\")\npublic class ParseUrlMapValidateTest extends BaseGoogleComputeEngineParseTest<UrlMapValidateResult> {\n\n   @Override\n   public String resource() {\n      return \"/url_map_validate.json\";\n   }\n\n   @Override\n   @Consumes(APPLICATION_JSON)\n   public UrlMapValidateResult expected() {\n      return expected(BASE_URL);\n   }\n\n   @Consumes(APPLICATION_JSON)\n   public UrlMapValidateResult expected(String baseUrl) {\n      return UrlMapValidateResult.create(false, // loadSucceded\n            ImmutableList.of(\"jclouds-test\"), // loadError\n            false, // testPassed\n            ImmutableList.of(TestFailure.create(\"jclouds-test\", // host\n                  \"/test/path\", // path\n                  URI.create(baseUrl + \"/myproject/global/backendServices/jclouds-test\"), // expectedService\n                  URI.create(baseUrl + \"/myproject/global/backendServices/jclouds-test-2\") //actualService\n                  ))); //testFailures)\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseZoneListTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\n\nimport org.jclouds.googlecloud.domain.ForwardingListPage;\nimport org.jclouds.googlecloud.domain.ListPage;\nimport org.jclouds.googlecomputeengine.domain.Zone;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"ParseZoneListTest\")\npublic class ParseZoneListTest extends BaseGoogleComputeEngineParseTest<ListPage<Zone>> {\n\n   @Override\n   public String resource() {\n      return \"/zone_list.json\";\n   }\n\n   @Override @Consumes(APPLICATION_JSON)\n   public ListPage<Zone> expected() {\n      return expected(BASE_URL);\n   }\n\n   @Consumes(APPLICATION_JSON)\n   public ListPage<Zone> expected(String baseUrl) {\n      Zone zone1 = new ParseZoneTest().expected(baseUrl);\n      Zone zone2 = Zone.create( //\n            \"13024414164050619686\", // id\n            parse(\"2012-10-24T20:13:19.271\"), // creationTimestamp\n            URI.create(baseUrl + \"/party/zones/us-central1-b\"), // selfLink\n            \"us-central1-b\", // name\n            \"us-central1-b\", // description\n            Zone.Status.UP, // status\n            ImmutableList.of( // maintenanceWindows\n                  Zone.MaintenanceWindow.create( //\n                        \"2013-02-17-planned-outage\", // name\n                        \"maintenance zone\", // description\n                        parse(\"2013-02-17T08:00:00.000\"), // beginTime\n                        parse(\"2013-03-03T08:00:00.000\") // endTime)\n                  )), //\n            null, // deprecated\n            \"us-central1\", // region\n            null // availableMachineTypes\n      );\n      return ForwardingListPage.create( //\n            ImmutableList.of(zone1, zone2), // items\n            null // nextPageToken\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseZoneOperationTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\n\nimport org.jclouds.googlecomputeengine.domain.Operation;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ParseZoneOperationTest\")\npublic class ParseZoneOperationTest extends BaseGoogleComputeEngineParseTest<Operation> {\n\n   @Override\n   public String resource() {\n      return \"/zone_operation.json\";\n   }\n\n   @Override @Consumes(APPLICATION_JSON)\n   public Operation expected() {\n      return expected(BASE_URL);\n   }\n\n   @Consumes(APPLICATION_JSON)\n   public Operation expected(String baseUrl) {\n      return Operation.create( //\n            \"13053095055850848306\", // id\n            parse(\"2013-07-26T13:57:20.204-07:00\"), // creationTimestamp\n            URI.create(baseUrl + \"/party/zones/us-central1-a/operations/operation-1354084865060\"),\n            \"operation-1354084865060\", // name\n            null, // description\n            URI.create(baseUrl + \"/party/zones/us-central1-a/instances/test-1\"),\n            \"13053094017547040099\", // targetId\n            null, // clientOperationId\n            Operation.Status.DONE, // status\n            null, // statusMessage\n            \"user@developer.gserviceaccount.com\", // user\n            100, // progress\n            parse(\"2012-11-28T06:41:05.060\"), // insertTime\n            parse(\"2012-11-28T06:41:05.142\"), // startTime\n            parse(\"2012-11-28T06:41:06.142\"), // endTime\n            null, // httpErrorStatusCode\n            null, // httpErrorMessage\n            \"insert\", // operationType\n            null, // errors\n            null, // warnings\n            null, // region\n            URI.create(baseUrl + \"/party/zones/us-central1-a\") // zone\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/ParseZoneTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;\n\nimport java.net.URI;\n\nimport jakarta.ws.rs.Consumes;\n\nimport org.jclouds.googlecomputeengine.domain.Zone;\nimport org.jclouds.googlecomputeengine.internal.BaseGoogleComputeEngineParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"ParseZoneTest\")\npublic class ParseZoneTest extends BaseGoogleComputeEngineParseTest<Zone> {\n\n   @Override\n   public String resource() {\n      return \"/zone_get.json\";\n   }\n\n   @Override @Consumes(APPLICATION_JSON)\n   public Zone expected() {\n      return expected(BASE_URL);\n   }\n\n   @Consumes(APPLICATION_JSON)\n   public Zone expected(String baseUrl) {\n      return Zone.create( //\n            \"13020128040171887099\", // id\n            parse(\"2012-10-19T16:42:54.131\"), // creationTimestamp\n            URI.create(baseUrl + \"/party/zones/us-central1-a\"), // selfLink\n            \"us-central1-a\", // name\n            \"us-central1-a\", // description\n            Zone.Status.DOWN, // status\n            ImmutableList.of( // maintenanceWindows\n                  Zone.MaintenanceWindow.create( //\n                        \"2012-11-10-planned-outage\", // name\n                        \"maintenance zone\", // description\n                        parse(\"2012-11-10T20:00:00.000\"), // beginTime\n                        parse(\"2012-12-02T20:00:00.000\") // endTime)\n                  )), //\n            null, // deprecated\n            \"us-central1\", // region\n            null // availableMachineTypes\n      );\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/java/org/jclouds/googlecomputeengine/parse/SimpleParsingTests.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.googlecomputeengine.parse;\n\nimport static org.jclouds.googlecomputeengine.compute.strategy.CreateNodesWithGroupEncodedIntoNameThenAddToSet.simplifyPorts;\nimport static org.jclouds.googlecomputeengine.compute.strategy.CreateNodesWithGroupEncodedIntoNameThenAddToSet.nameFromNetworkString;\n\nimport java.util.List;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\nimport static org.testng.Assert.assertEquals;\n\n\n@Test(groups = \"unit\", testName = \"SimpleParsingTests\", singleThreaded = true)\npublic class SimpleParsingTests {\n\n   public void testOnePort(){\n      int[] ports = {22};\n      List<String> output = simplifyPorts(ports);\n\n      assertEquals(ImmutableList.of(\"22\"), output);\n   }\n\n   public void testBasic(){\n      int[] ports = {1, 2, 3, 4};\n      List<String> output = simplifyPorts(ports);\n\n      assertEquals(ImmutableList.of(\"1-4\"), output);\n   }\n\n   public void testComplex(){\n      int[] ports = {3, 1, 5, 2, 1002, 17, 1001, 22, 80, 1000};\n      List<String> output = simplifyPorts(ports);\n\n      assertEquals(ImmutableList.of(\"1-3\", \"5\", \"17\", \"22\", \"80\", \"1000-1002\"), output);\n   }\n\n   public void testEmpty(){\n      int[] ports = {};\n      List<String> output = simplifyPorts(ports);\n\n      assertEquals(null, output);\n   }\n\n   public void testEndSingle(){\n      int[] ports = {1, 2, 3, 4, 7};\n      List<String> output = simplifyPorts(ports);\n\n      assertEquals(ImmutableList.of(\"1-4\", \"7\"), output);\n   }\n\n   public void testNetworkFromString(){\n      String network = \"https://www.googleapis.com/compute/v1/projects/project/global/networks/network\";\n      assertEquals(\"network\", nameFromNetworkString(network));\n\n      network = \"projects/project/global/networks/network\";\n      assertEquals(\"network\", nameFromNetworkString(network));\n\n      network = \"global/networks/default\";\n      assertEquals(\"default\", nameFromNetworkString(network));\n\n      network = \"default\";\n      assertEquals(\"default\", nameFromNetworkString(network));\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/address_get.json",
    "content": "{\n  \"kind\": \"compute#address\",\n  \"id\": \"4439373783165447583\",\n  \"creationTimestamp\": \"2013-07-26T13:57:20.204-07:00\",\n  \"status\": \"IN_USE\",\n  \"region\": \"https://www.googleapis.com/compute/v1/projects/party/regions/us-central1\",\n  \"name\": \"test-ip1\",\n  \"description\": \"\",\n  \"address\": \"173.255.115.190\",\n  \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/regions/us-central1/addresses/test-ip1\",\n  \"users\": [\n    \"https://www.googleapis.com/compute/v1/projects/party/regions/us-central1-a/forwardingRules/test-forwarding-rule\"\n  ]\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/address_insert.json",
    "content": "{\"name\":\"test-ip1\"}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/address_list.json",
    "content": "{\n  \"kind\": \"compute#addressList\",\n  \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/regions/us-central1/addresses\",\n  \"id\": \"projects/party/regions/us-central1/addresses\",\n  \"items\": [\n    {\n      \"kind\": \"compute#address\",\n      \"id\": \"4439373783165447583\",\n      \"creationTimestamp\": \"2013-07-26T13:57:20.204-07:00\",\n      \"status\": \"IN_USE\",\n      \"region\": \"https://www.googleapis.com/compute/v1/projects/party/regions/us-central1\",\n      \"name\": \"test-ip1\",\n      \"description\": \"\",\n      \"address\": \"173.255.115.190\",\n      \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/regions/us-central1/addresses/test-ip1\",\n      \"users\": [\n        \"https://www.googleapis.com/compute/v1/projects/party/regions/us-central1-a/forwardingRules/test-forwarding-rule\"\n      ]\n    },\n    {\n      \"kind\": \"compute#address\",\n      \"id\": \"4881363978908129158\",\n      \"creationTimestamp\": \"2013-07-26T14:08:21.552-07:00\",\n      \"status\": \"RESERVED\",\n      \"region\": \"https://www.googleapis.com/compute/v1/projects/party/regions/us-central1\",\n      \"name\": \"test-ip2\",\n      \"description\": \"\",\n      \"address\": \"173.255.118.115\",\n      \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/regions/us-central1/addresses/test-ip2\"\n    }\n  ]\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/aggregated_address_list.json",
    "content": "{\n \"kind\": \"compute#addressAggregatedList\",\n \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/aggregated/addresses\",\n \"id\": \"projects/party/aggregated/addresses\",\n \"items\": {\n  \"zones/asia-east1-a\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/asia-east1-a' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/asia-east1-a\"\n     }\n    ]\n   }\n  },\n  \"zones/asia-east1-b\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/asia-east1-b' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/asia-east1-b\"\n     }\n    ]\n   }\n  },\n  \"zones/asia-east1-c\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/asia-east1-c' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/asia-east1-c\"\n     }\n    ]\n   }\n  },\n  \"zones/europe-west1-a\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/europe-west1-a' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/europe-west1-a\"\n     }\n    ]\n   }\n  },\n  \"zones/europe-west1-b\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/europe-west1-b' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/europe-west1-b\"\n     }\n    ]\n   }\n  },\n  \"zones/europe-west1-c\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/europe-west1-c' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/europe-west1-c\"\n     }\n    ]\n   }\n  },\n  \"zones/us-central1-a\": {\n   \"addresses\": [\n    {\n\n        \"kind\": \"compute#address\",\n        \"id\": \"4439373783165447583\",\n        \"creationTimestamp\": \"2013-07-26T13:57:20.204-07:00\",\n        \"status\": \"RESERVED\",\n        \"region\": \"https://www.googleapis.com/compute/v1/projects/party/regions/us-central1\",\n        \"name\": \"test-ip1\",\n        \"description\": \"\",\n        \"address\": \"173.255.115.190\",\n        \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/regions/us-central1/addresses/test-ip1\"\n    },\n    {\n\n        \"kind\": \"compute#address\",\n        \"id\": \"4881363978908129158\",\n        \"creationTimestamp\": \"2013-07-26T14:08:21.552-07:00\",\n        \"status\": \"RESERVED\",\n        \"region\": \"https://www.googleapis.com/compute/v1/projects/party/regions/us-central1\",\n        \"name\": \"test-ip2\",\n        \"description\": \"\",\n        \"address\": \"173.255.118.115\",\n        \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/regions/us-central1/addresses/test-ip2\"\n    }\n   ]\n  },\n  \"zones/us-central1-b\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/us-central1-b' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/us-central1-b\"\n     }\n    ]\n   }\n  },\n  \"zones/us-central1-f\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/us-central1-f' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/us-central1-f\"\n     }\n    ]\n   }\n  }\n }\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/aggregated_address_list_empty.json",
    "content": "{\n \"kind\": \"compute#addressAggregatedList\",\n \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/aggregated/addresses\",\n \"id\": \"projects/party/aggregated/addresses\",\n \"items\": {\n  \"zones/asia-east1-a\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/asia-east1-a' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/asia-east1-a\"\n     }\n    ]\n   }\n  },\n  \"zones/asia-east1-b\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/asia-east1-b' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/asia-east1-b\"\n     }\n    ]\n   }\n  },\n  \"zones/asia-east1-c\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/asia-east1-c' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/asia-east1-c\"\n     }\n    ]\n   }\n  },\n  \"zones/europe-west1-a\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/europe-west1-a' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/europe-west1-a\"\n     }\n    ]\n   }\n  },\n  \"zones/europe-west1-b\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/europe-west1-b' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/europe-west1-b\"\n     }\n    ]\n   }\n  },\n  \"zones/europe-west1-c\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/europe-west1-c' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/europe-west1-c\"\n     }\n    ]\n   }\n  },\n  \"zones/us-central1-a\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/us-central1-a' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/us-central1-a\"\n     }\n    ]\n   }\n  },\n  \"zones/us-central1-b\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/us-central1-b' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/us-central1-b\"\n     }\n    ]\n   }\n  },\n  \"zones/us-central1-f\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/us-central1-f' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/us-central1-f\"\n     }\n    ]\n   }\n  }\n }\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/aggregated_disk_list.json",
    "content": "{\n \"kind\": \"compute#diskAggregatedList\",\n \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/aggregated/disks\",\n \"id\": \"projects/party/aggregated/disks\",\n \"items\": {\n  \"zones/asia-east1-a\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/asia-east1-a' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/asia-east1-a\"\n     }\n    ]\n   }\n  },\n  \"zones/asia-east1-b\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/asia-east1-b' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/asia-east1-b\"\n     }\n    ]\n   }\n  },\n  \"zones/asia-east1-c\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/asia-east1-c' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/asia-east1-c\"\n     }\n    ]\n   }\n  },\n  \"zones/europe-west1-a\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/europe-west1-a' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/europe-west1-a\"\n     }\n    ]\n   }\n  },\n  \"zones/europe-west1-b\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/europe-west1-b' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/europe-west1-b\"\n     }\n    ]\n   }\n  },\n  \"zones/europe-west1-c\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/europe-west1-c' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/europe-west1-c\"\n     }\n    ]\n   }\n  },\n  \"zones/us-central1-a\": {\n   \"disks\": [\n    {\n\t     \"kind\": \"compute#disk\",\n\t     \"id\": \"13050421646334304115\",\n\t     \"creationTimestamp\": \"2012-11-25T01:38:48.306\",\n\t     \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/disks/testimage1\",\n\t     \"name\": \"testimage1\",\n\t     \"sizeGb\": \"1\",\n\t     \"zone\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a\",\n\t     \"status\": \"READY\",\n\t     \"type\": \"https://www.googleapis.com/compute/v1/projects/studied-point-720/zones/us-central1-a/diskTypes/pd-standard\"\n\t}\n   ]\n  },\n  \"zones/us-central1-b\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/us-central1-b' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/us-central1-b\"\n     }\n    ]\n   }\n  },\n  \"zones/us-central1-f\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/us-central1-f' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/us-central1-f\"\n     }\n    ]\n   }\n  }\n }\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/aggregated_disk_list_empty.json",
    "content": "{\n \"kind\": \"compute#diskAggregatedList\",\n \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/aggregated/disks\",\n \"id\": \"projects/party/aggregated/disks\",\n \"items\": {\n  \"zones/asia-east1-a\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/asia-east1-a' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/asia-east1-a\"\n     }\n    ]\n   }\n  },\n  \"zones/asia-east1-b\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/asia-east1-b' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/asia-east1-b\"\n     }\n    ]\n   }\n  },\n  \"zones/asia-east1-c\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/asia-east1-c' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/asia-east1-c\"\n     }\n    ]\n   }\n  },\n  \"zones/europe-west1-a\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/europe-west1-a' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/europe-west1-a\"\n     }\n    ]\n   }\n  },\n  \"zones/europe-west1-b\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/europe-west1-b' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/europe-west1-b\"\n     }\n    ]\n   }\n  },\n  \"zones/europe-west1-c\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/europe-west1-c' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/europe-west1-c\"\n     }\n    ]\n   }\n  },\n  \"zones/us-central1-a\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/us-central1-a' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/us-central1-a\"\n     }\n    ]\n   }\n  },\n  \"zones/us-central1-b\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/us-central1-b' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/us-central1-b\"\n     }\n    ]\n   }\n  },\n  \"zones/us-central1-f\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/us-central1-f' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/us-central1-f\"\n     }\n    ]\n   }\n  }\n }\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/aggregated_disktype_list.json",
    "content": "{\n \"kind\": \"compute#diskTypeAggregatedList\",\n \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/aggregated/diskTypes\",\n \"id\": \"projects/party/aggregated/diskTypes\",\n \"items\": {\n  \"zones/asia-east1-a\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/asia-east1-a' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/asia-east1-a\"\n     }\n    ]\n   }\n  },\n  \"zones/asia-east1-b\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/asia-east1-b' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/asia-east1-b\"\n     }\n    ]\n   }\n  },\n  \"zones/asia-east1-c\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/asia-east1-c' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/asia-east1-c\"\n     }\n    ]\n   }\n  },\n  \"zones/europe-west1-a\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/europe-west1-a' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/europe-west1-a\"\n     }\n    ]\n   }\n  },\n  \"zones/europe-west1-b\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/europe-west1-b' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/europe-west1-b\"\n     }\n    ]\n   }\n  },\n  \"zones/europe-west1-c\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/europe-west1-c' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/europe-west1-c\"\n     }\n    ]\n   }\n  },\n  \"zones/us-central1-a\": {\n   \"diskTypes\": [\n\t  {\n\t   \"kind\": \"compute#diskType\",\n\t   \"creationTimestamp\": \"2014-06-02T11:07:28.530-07:00\",\n\t   \"name\": \"pd-standard\",\n\t   \"description\": \"Standard Persistent Disk\",\n\t   \"validDiskSize\": \"10GB-10TB\",\n\t   \"zone\": \"https://content.googleapis.com/compute/v1/projects/studied-point-720/zones/us-central1-a\",\n\t   \"selfLink\": \"https://content.googleapis.com/compute/v1/projects/studied-point-720/zones/us-central1-a/diskTypes/pd-standard\",\n\t   \"defaultDiskSizeGb\": \"500\"\n\t  },\n\t  {\n\t   \"kind\": \"compute#diskType\",\n\t   \"creationTimestamp\": \"2014-06-02T11:07:28.529-07:00\",\n\t   \"name\": \"pd-ssd\",\n\t   \"description\": \"SSD Persistent Disk\",\n\t   \"validDiskSize\": \"10GB-1TB\",\n\t   \"zone\": \"https://content.googleapis.com/compute/v1/projects/studied-point-720/zones/us-central1-a\",\n\t   \"selfLink\": \"https://content.googleapis.com/compute/v1/projects/studied-point-720/zones/us-central1-a/diskTypes/pd-ssd\",\n\t   \"defaultDiskSizeGb\": \"100\"\n\t  }\n   ]\n  },\n  \"zones/us-central1-b\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/us-central1-b' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/us-central1-b\"\n     }\n    ]\n   }\n  },\n  \"zones/us-central1-f\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/us-central1-f' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/us-central1-f\"\n     }\n    ]\n   }\n  }\n }\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/aggregated_disktype_list_empty.json",
    "content": "{\n \"kind\": \"compute#diskTypeAggregatedList\",\n \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/aggregated/diskTypes\",\n \"id\": \"projects/party/aggregated/diskTypes\",\n \"items\": {\n  \"zones/asia-east1-a\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/asia-east1-a' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/asia-east1-a\"\n     }\n    ]\n   }\n  },\n  \"zones/asia-east1-b\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/asia-east1-b' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/asia-east1-b\"\n     }\n    ]\n   }\n  },\n  \"zones/asia-east1-c\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/asia-east1-c' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/asia-east1-c\"\n     }\n    ]\n   }\n  },\n  \"zones/europe-west1-a\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/europe-west1-a' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/europe-west1-a\"\n     }\n    ]\n   }\n  },\n  \"zones/europe-west1-b\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/europe-west1-b' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/europe-west1-b\"\n     }\n    ]\n   }\n  },\n  \"zones/europe-west1-c\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/europe-west1-c' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/europe-west1-c\"\n     }\n    ]\n   }\n  },\n  \"zones/us-central1-a\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/us-central1-a' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/us-central1-a\"\n     }\n    ]\n   }\n  },\n  \"zones/us-central1-b\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/us-central1-b' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/us-central1-b\"\n     }\n    ]\n   }\n  },\n  \"zones/us-central1-f\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/us-central1-f' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/us-central1-f\"\n     }\n    ]\n   }\n  }\n }\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/aggregated_forwarding_rule_list.json",
    "content": "{\n \"kind\": \"compute#forwardingRuleAggregatedList\",\n \"id\": \"projects/party/aggregated/forwardingRules\",\n \"items\": {\n  \"regions/asia-east1\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'regions/asia-east1' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"regions/asia-east1\"\n     }\n    ]\n   }\n  },\n  \"regions/europe-west1\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'regions/europe-west1' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"regions/europe-west1\"\n     }\n    ]\n   }\n  },\n  \"regions/us-central1\": {\n   \"forwardingRules\": [\n    {\n\n     \"kind\": \"compute#forwardingRule\",\n     \"id\": \"943206052144235641\",\n     \"creationTimestamp\": \"2014-11-24T15:33:26.664-08:00\",\n     \"name\": \"test-forwarding-rule\",\n     \"region\": \"https://www.googleapis.com/compute/v1/projects/party/regions/us-central1\",\n     \"IPAddress\": \"130.211.140.61\",\n     \"IPProtocol\": \"TCP\",\n     \"portRange\": \"1-65535\",\n     \"target\": \"https://www.googleapis.com/compute/v1/projects/party/regions/us-central1/targetPools/test\",\n     \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/regions/us-central1/forwardingRules/test-forwarding-rule\"\n    }\n   ]\n  },\n  \"global\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'global' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"global\"\n     }\n    ]\n   }\n  }\n },\n \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/aggregated/forwardingRules\"\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/aggregated_forwarding_rule_list_empty.json",
    "content": "{\n \"kind\": \"compute#forwardingRuleAggregatedList\",\n \"id\": \"projects/party/aggregated/forwardingRules\",\n \"items\": {\n  \"regions/asia-east1\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'regions/asia-east1' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"regions/asia-east1\"\n     }\n    ]\n   }\n  },\n  \"regions/europe-west1\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'regions/europe-west1' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"regions/europe-west1\"\n     }\n    ]\n   }\n  },\n  \"regions/us-central1\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'regions/us-central1' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"regions/us-central1\"\n     }\n    ]\n   }\n  },\n  \"global\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'global' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"global\"\n     }\n    ]\n   }\n  }\n },\n \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/aggregated/forwardingRules\"\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/aggregated_global_operation_list.json",
    "content": "{\n \"kind\": \"compute#operationAggregatedList\",\n \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/aggregated/operations\",\n \"id\": \"projects/party/aggregated/operations\",\n \"items\": {\n  \"zones/asia-east1-a\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/asia-east1-a' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/asia-east1-a\"\n     }\n    ]\n   }\n  },\n  \"zones/asia-east1-b\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/asia-east1-b' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/asia-east1-b\"\n     }\n    ]\n   }\n  },\n  \"zones/asia-east1-c\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/asia-east1-c' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/asia-east1-c\"\n     }\n    ]\n   }\n  },\n  \"zones/europe-west1-a\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/europe-west1-a' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/europe-west1-a\"\n     }\n    ]\n   }\n  },\n  \"zones/europe-west1-b\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/europe-west1-b' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/europe-west1-b\"\n     }\n    ]\n   }\n  },\n  \"zones/europe-west1-c\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/europe-west1-c' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/europe-west1-c\"\n     }\n    ]\n   }\n  },\n  \"zones/us-central1-a\": {\n   \"operations\": [\n      {\n         \"kind\": \"compute#operation\",\n         \"id\": \"13053095055850848306\",\n         \"creationTimestamp\": \"2013-07-26T13:57:20.204-07:00\",\n         \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/global/operations/operation-1354084865060\",\n         \"name\": \"operation-1354084865060\",\n         \"targetLink\": \"https://www.googleapis.com/compute/v1/projects/party/global/firewalls/jclouds-test-delete\",\n         \"targetId\": \"13053094017547040099\",\n         \"status\": \"DONE\",\n         \"user\": \"user@developer.gserviceaccount.com\",\n         \"progress\": 100,\n         \"insertTime\": \"2012-11-28T06:41:05.060\",\n         \"startTime\": \"2012-11-28T06:41:05.142\",\n         \"endTime\": \"2012-11-28T06:41:06.142\",\n         \"operationType\": \"insert\"\n      }\n    ]\n  }\n }\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/aggregated_global_operation_list_empty.json",
    "content": "{\n \"kind\": \"compute#operationAggregatedList\",\n \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/aggregated/operations\",\n \"id\": \"projects/party/aggregated/operations\",\n \"items\": {\n  \"zones/asia-east1-a\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/asia-east1-a' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/asia-east1-a\"\n     }\n    ]\n   }\n  },\n  \"zones/asia-east1-b\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/asia-east1-b' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/asia-east1-b\"\n     }\n    ]\n   }\n  },\n  \"zones/asia-east1-c\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/asia-east1-c' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/asia-east1-c\"\n     }\n    ]\n   }\n  },\n  \"zones/europe-west1-a\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/europe-west1-a' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/europe-west1-a\"\n     }\n    ]\n   }\n  },\n  \"zones/europe-west1-b\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/europe-west1-b' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/europe-west1-b\"\n     }\n    ]\n   }\n  },\n  \"zones/europe-west1-c\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/europe-west1-c' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/europe-west1-c\"\n     }\n    ]\n   }\n  },\n  \"zones/us-central1-a\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/us-central1-a' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/us-central1-a\"\n     }\n    ]\n   }\n  },\n  \"zones/us-central1-b\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/us-central1-b' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/us-central1-b\"\n     }\n    ]\n   }\n  },\n  \"zones/us-central1-f\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/us-central1-f' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/us-central1-f\"\n     }\n    ]\n   }\n  }\n }\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/aggregated_instance_list.json",
    "content": "{\n \"kind\": \"compute#instanceAggregatedList\",\n \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/aggregated/instances\",\n \"id\": \"projects/party/aggregated/instances\",\n \"items\": {\n  \"zones/asia-east1-a\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/asia-east1-a' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/asia-east1-a\"\n     }\n    ]\n   }\n  },\n  \"zones/asia-east1-b\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/asia-east1-b' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/asia-east1-b\"\n     }\n    ]\n   }\n  },\n  \"zones/asia-east1-c\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/asia-east1-c' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/asia-east1-c\"\n     }\n    ]\n   }\n  },\n  \"zones/europe-west1-a\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/europe-west1-a' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/europe-west1-a\"\n     }\n    ]\n   }\n  },\n  \"zones/europe-west1-b\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/europe-west1-b' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/europe-west1-b\"\n     }\n    ]\n   }\n  },\n  \"zones/europe-west1-c\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/europe-west1-c' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/europe-west1-c\"\n     }\n    ]\n   }\n  },\n  \"zones/us-central1-a\": {\n   \"instances\": [\n      {\n         \"kind\": \"compute#instance\",\n         \"id\": \"13051190678907570425\",\n         \"description\": \"desc\",\n         \"creationTimestamp\": \"2012-11-25T23:48:20.758\",\n         \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/instances/test-0\",\n         \"name\": \"test-0\",\n         \"machineType\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/machineTypes/n1-standard-1\",\n         \"status\": \"RUNNING\",\n         \"zone\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a\",\n         \"networkInterfaces\": [\n            {\n               \"kind\": \"compute#instanceNetworkInterface\",\n               \"name\": \"nic0\",\n               \"networkIP\": \"10.240.121.115\",\n               \"network\": \"https://www.googleapis.com/compute/v1/projects/party/global/networks/default\"\n            }\n         ],\n         \"disks\": [\n            {\n               \"kind\": \"compute#instanceDisk\",\n               \"type\": \"PERSISTENT\",\n               \"mode\": \"READ_WRITE\",\n               \"deviceName\": \"test\",\n               \"source\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/disks/test\",\n               \"index\": 0,\n               \"boot\": true\n            }\n         ],\n         \"serviceAccounts\": [\n            {\n               \"kind\": \"compute#serviceAccount\",\n               \"email\": \"default\",\n               \"scopes\": [\n                  \"myscope\"\n               ]\n            }\n         ],\n         \"metadata\": {\n            \"items\": [\n               {\n                  \"key\": \"aKey\",\n                  \"value\": \"aValue\"\n               },\n               {\n                  \"key\": \"jclouds-image\",\n                  \"value\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-7-wheezy-v20140718\"\n               },\n               {\n                  \"key\": \"jclouds-delete-boot-disk\",\n                  \"value\": \"true\"\n               }\n            ],\n            \"fingerprint\": \"efgh\"\n         },\n         \"tags\": {\n            \"items\": [\n               \"aTag\",\n               \"Group-port-42\"\n            ],\n            \"fingerprint\": \"abcd\"\n         },\n        \"scheduling\": {\n            \"onHostMaintenance\": \"MIGRATE\",\n            \"automaticRestart\": false\n         }\n      }\n   ]\n  },\n  \"zones/us-central1-b\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/us-central1-b' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/us-central1-b\"\n     }\n    ]\n   }\n  },\n  \"zones/us-central1-f\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/us-central1-f' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/us-central1-f\"\n     }\n    ]\n   }\n  }\n }\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/aggregated_instance_list_empty.json",
    "content": "{\n \"kind\": \"compute#instanceAggregatedList\",\n \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/aggregated/instances\",\n \"id\": \"projects/party/aggregated/instances\",\n \"items\": {\n  \"zones/asia-east1-a\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/asia-east1-a' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/asia-east1-a\"\n     }\n    ]\n   }\n  },\n  \"zones/asia-east1-b\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/asia-east1-b' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/asia-east1-b\"\n     }\n    ]\n   }\n  },\n  \"zones/asia-east1-c\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/asia-east1-c' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/asia-east1-c\"\n     }\n    ]\n   }\n  },\n  \"zones/europe-west1-a\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/europe-west1-a' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/europe-west1-a\"\n     }\n    ]\n   }\n  },\n  \"zones/europe-west1-b\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/europe-west1-b' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/europe-west1-b\"\n     }\n    ]\n   }\n  },\n  \"zones/europe-west1-c\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/europe-west1-c' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/europe-west1-c\"\n     }\n    ]\n   }\n  },\n  \"zones/us-central1-a\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/us-central1-a' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/us-central1-a\"\n     }\n    ]\n   }\n  },\n  \"zones/us-central1-b\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/us-central1-b' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/us-central1-b\"\n     }\n    ]\n   }\n  },\n  \"zones/us-central1-f\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/us-central1-f' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/us-central1-f\"\n     }\n    ]\n   }\n  }\n }\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/aggregated_machinetype_list.json",
    "content": "{\n \"kind\": \"compute#machineTypeAggregatedList\",\n \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/aggregated/machineTypes\",\n \"id\": \"projects/party/aggregated/machineTypes\",\n \"items\": {\n   \"zones/us-central1-a\": {\n     \"machineTypes\": [\n       {\n           \"kind\": \"compute#machineType\",\n           \"id\": \"4618642685664990776\",\n           \"creationTimestamp\": \"2013-04-25T13:32:49.088-07:00\",\n           \"name\": \"f1-micro\",\n           \"description\": \"1 vCPU (shared physical core) and 0.6 GB RAM\",\n           \"guestCpus\": 1,\n           \"memoryMb\": 614,\n           \"maximumPersistentDisks\": 4,\n           \"maximumPersistentDisksSizeGb\": \"3072\",\n           \"zone\": \"us-central1-a\",\n           \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/machineTypes/f1-micro\"\n       },\n       {\n         \"kind\": \"compute#machineType\",\n         \"id\": \"12907738072351752276\",\n         \"creationTimestamp\": \"2012-06-07T20:48:14.670\",\n         \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/machineTypes/n1-standard-1\",\n         \"name\": \"n1-standard-1\",\n         \"description\": \"1 vCPU, 3.75 GB RAM, and a 10 GB ephemeral root disk\",\n         \"guestCpus\": 1,\n         \"memoryMb\": 3840,\n         \"maximumPersistentDisks\": 16,\n         \"maximumPersistentDisksSizeGb\": \"128\",\n         \"zone\": \"us-central1-a\"\n       },\n       {\n         \"kind\": \"compute#machineType\",\n         \"id\": \"12908560709887590691\",\n         \"creationTimestamp\": \"2012-06-07T20:51:19.936\",\n         \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/machineTypes/n1-standard-8-d\",\n         \"name\": \"n1-standard-8-d\",\n         \"description\": \"8 vCPUs, 30 GB RAM, a 10 GB ephemeral root disk, and 2 extra 1770 GB ephemeral disks\",\n         \"guestCpus\": 8,\n         \"memoryMb\": 30720,\n         \"scratchDisks\": [\n            {\n               \"diskGb\": 1770\n            },\n            {\n               \"diskGb\": 1770\n            }\n         ],\n         \"maximumPersistentDisks\": 16,\n         \"maximumPersistentDisksSizeGb\": \"1024\",\n         \"zone\": \"asia-east2-a\"\n       }\n     ]\n   }\n }\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/aggregated_target_instance_list.json",
    "content": "{\n \"kind\": \"compute#targetInstanceAggregatedList\",\n \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/aggregated/targetInstances\",\n \"id\": \"projects/party/aggregated/targetInstances\",\n \"items\": {\n  \"zones/asia-east1-a\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/asia-east1-a' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/asia-east1-a\"\n     }\n    ]\n   }\n  },\n  \"zones/asia-east1-b\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/asia-east1-b' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/asia-east1-b\"\n     }\n    ]\n   }\n  },\n  \"zones/asia-east1-c\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/asia-east1-c' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/asia-east1-c\"\n     }\n    ]\n   }\n  },\n  \"zones/europe-west1-a\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/europe-west1-a' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/europe-west1-a\"\n     }\n    ]\n   }\n  },\n  \"zones/europe-west1-b\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/europe-west1-b' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/europe-west1-b\"\n     }\n    ]\n   }\n  },\n  \"zones/europe-west1-c\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/europe-west1-c' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/europe-west1-c\"\n     }\n    ]\n   }\n  },\n  \"zones/us-central1-a\": {\n   \"targetInstances\": [\n    {\n\n     \"kind\": \"compute#targetInstance\",\n     \"id\": \"3191835352771895826\",\n     \"creationTimestamp\": \"2014-11-24T10:42:45.135-08:00\",\n     \"name\": \"test-target-instance\",\n     \"zone\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a\",\n     \"natPolicy\": \"NO_NAT\",\n     \"instance\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/instances/instance-1\",\n     \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/targetInstances/test-target-instance\"\n    },\n    {\n\n     \"kind\": \"compute#targetInstance\",\n     \"id\": \"7362436693678237415\",\n     \"creationTimestamp\": \"2014-11-20T17:35:17.268-08:00\",\n     \"name\": \"target-instance-1\",\n     \"zone\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a\",\n     \"natPolicy\": \"NO_NAT\",\n     \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/targetInstances/target-instance-1\"\n    }\n   ]\n  },\n  \"zones/us-central1-b\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/us-central1-b' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/us-central1-b\"\n     }\n    ]\n   }\n  },\n  \"zones/us-central1-f\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'zones/us-central1-f' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"zones/us-central1-f\"\n     }\n    ]\n   }\n  }\n }\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/aggregated_target_instance_list_empty.json",
    "content": "{\n \"kind\": \"compute#addressAggregatedList\",\n \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/studied-point-720/aggregated/addresses\",\n \"id\": \"projects/studied-point-720/aggregated/addresses\",\n \"items\": {\n  \"regions/asia-east1\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'regions/asia-east1' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"regions/asia-east1\"\n     }\n    ]\n   }\n  },\n  \"regions/europe-west1\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'regions/europe-west1' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"regions/europe-west1\"\n     }\n    ]\n   }\n  },\n  \"regions/us-central1\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'regions/us-central1' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"regions/us-central1\"\n     }\n    ]\n   }\n  },\n  \"global\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'global' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"global\"\n     }\n    ]\n   }\n  }\n }\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/aggregated_target_pool_list.json",
    "content": "{\n \"kind\": \"compute#targetPoolAggregatedList\",\n \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/aggregated/targetPools\",\n \"id\": \"projects/party/aggregated/targetPools\",\n \"items\": {\n  \"regions/asia-east1\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'regions/asia-east1' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"regions/asia-east1\"\n     }\n    ]\n   }\n  },\n  \"regions/europe-west1\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'regions/europe-west1' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"regions/europe-west1\"\n     }\n    ]\n   }\n  },\n  \"regions/us-central1\": {\n   \"targetPools\": [\n    {\n\n     \"kind\": \"compute#targetPool\",\n     \"id\": \"17592955481805765508\",\n     \"creationTimestamp\": \"2014-12-01T11:51:15.611-08:00\",\n     \"name\": \"test\",\n     \"description\": \"a Pool!\",\n     \"region\": \"https://www.googleapis.com/compute/v1/projects/party/regions/us-central1\",\n     \"sessionAffinity\": \"NONE\",\n     \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/regions/us-central1/targetPools/test\"\n    }\n   ]\n  }\n }\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/aggregated_target_pool_list_empty.json",
    "content": "{\n \"kind\": \"compute#targetPoolAggregatedList\",\n \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/aggregated/targetPools\",\n \"id\": \"projects/party/aggregated/targetPools\",\n \"items\": {\n  \"regions/asia-east1\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'regions/asia-east1' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"regions/asia-east1\"\n     }\n    ]\n   }\n  },\n  \"regions/europe-west1\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'regions/europe-west1' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"regions/europe-west1\"\n     }\n    ]\n   }\n  },\n  \"regions/us-central1\": {\n   \"warning\": {\n    \"code\": \"NO_RESULTS_ON_PAGE\",\n    \"message\": \"There are no results for scope 'regions/us-central1' on this page.\",\n    \"data\": [\n     {\n      \"key\": \"scope\",\n      \"value\": \"regions/us-central1\"\n     }\n    ]\n   }\n  }\n }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/backend_service_get.json",
    "content": "{\n   \"kind\": \"compute#backendService\",\n   \"id\": \"15448612110458377529\",\n   \"creationTimestamp\": \"2014-07-18T13:37:48.574-07:00\",\n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/myproject/global/backendServices/jclouds-test\",\n   \"name\": \"jclouds-test\",\n   \"description\": \"Backend service\",\n   \"backends\": [\n      {\n         \"balancingMode\": \"UTILIZATION\",\n         \"capacityScaler\": 1.0,\n         \"description\": \"A resource view\",\n         \"group\": \"https://www.googleapis.com/resourceviews/v1beta1/projects/myproject/zones/us-central1-a/resourceViews/jclouds-test\",\n         \"maxUtilization\": 0.8\n      }\n   ],\n   \"healthChecks\": [\n      \"https://www.googleapis.com/compute/v1/projects/myproject/global/httpHealthChecks/jclouds-test\"\n   ],\n   \"port\": 80,\n   \"protocol\": \"HTTP\",\n   \"timeoutSec\": 30,\n   \"fingerprint\": \"I6n5NPSXn8g=\"\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/backend_service_get_health_request.json",
    "content": "{\"group\":\"https://www.googleapis.com/resourceviews/v1beta1/projects/myproject/zones/us-central1-a/resourceViews/jclouds-test\"}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/backend_service_insert.json",
    "content": "{\n   \"name\": \"jclouds-test\",\n   \"healthChecks\": [\n      \"https://www.googleapis.com/compute/v1/projects/myproject/global/httpHealthChecks/jclouds-test\"\n   ],\n   \"timeoutSec\": 30,\n   \"port\": 80,\n   \"protocol\": \"HTTP\"\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/backend_service_list.json",
    "content": "{\n   \"kind\": \"compute#backendServiceList\",\n   \"id\": \"projects/myproject/backendServices\",\n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/myproject/global/backendServices\",\n   \"items\": [\n      {\n         \"kind\": \"compute#backendService\",\n         \"id\": \"15448612110458377529\",\n         \"creationTimestamp\": \"2014-07-18T13:37:48.574-07:00\",\n         \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/myproject/global/backendServices/jclouds-test\",\n         \"name\": \"jclouds-test\",\n         \"description\": \"Backend service\",\n         \"backends\": [\n            {\n               \"balancingMode\": \"UTILIZATION\",\n               \"capacityScaler\": 1.0,\n               \"description\": \"A resource view\",\n               \"group\": \"https://www.googleapis.com/resourceviews/v1beta1/projects/myproject/zones/us-central1-a/resourceViews/jclouds-test\",\n               \"maxUtilization\": 0.8\n            }\n         ],\n         \"healthChecks\": [\n            \"https://www.googleapis.com/compute/v1/projects/myproject/global/httpHealthChecks/jclouds-test\"\n         ],\n         \"port\": 80,\n         \"protocol\": \"HTTP\",\n         \"timeoutSec\": 30,\n         \"fingerprint\": \"I6n5NPSXn8g=\"\n      },\n      {\n         \"kind\": \"compute#backendService\",\n         \"id\": \"12862241067393040785\",\n         \"creationTimestamp\": \"2012-04-13T03:05:04.365\",\n         \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/myproject/global/backendServices/jclouds-test-2\",\n         \"name\": \"jclouds-test-2\",\n         \"description\": \"Backend Service 2\",\n         \"port\": 80,\n         \"healthChecks\": [\n            \"https://www.googleapis.com/compute/v1/projects/myproject/global/httpHealthChecks/jclouds-test\"\n         ],\n         \"protocol\": \"HTTP\",\n         \"timeoutSec\": 45\n      }\n   ]\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/disk_create_snapshot.json",
    "content": "{\"name\":\"test-snap\"}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/disk_get.json",
    "content": "{\n   \"kind\": \"compute#disk\",\n   \"id\": \"13050421646334304115\",\n   \"creationTimestamp\": \"2012-11-25T01:38:48.306\",\n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/disks/testimage1\",\n   \"name\": \"testimage1\",\n   \"sizeGb\": \"1\",\n   \"zone\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a\",\n   \"status\": \"READY\",\n   \"type\": \"https://www.googleapis.com/compute/v1/projects/studied-point-720/zones/us-central1-a/diskTypes/pd-standard\"\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/disk_get_with_source_image.json",
    "content": "{\n   \"kind\": \"compute#disk\",\n   \"id\": \"13050421646334304115\",\n   \"creationTimestamp\": \"2012-11-25T01:38:48.306\",\n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/disks/test\",\n   \"name\": \"test\",\n   \"sizeGb\": \"1\",\n   \"zone\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a\",\n   \"status\": \"READY\",\n   \"type\": \"https://www.googleapis.com/compute/v1/projects/studied-point-720/zones/us-central1-a/diskTypes/pd-standard\",\n   \"sourceImage\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-7-wheezy-v20140718\"\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/disk_get_with_source_snapshot.json",
    "content": "{\n   \"kind\": \"compute#disk\",\n   \"id\": \"13050421646334304115\",\n   \"creationTimestamp\": \"2012-11-25T01:38:48.306\",\n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/disks/test\",\n   \"name\": \"test\",\n   \"sizeGb\": \"1\",\n   \"zone\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a\",\n   \"status\": \"READY\",\n   \"type\": \"https://www.googleapis.com/compute/v1/projects/studied-point-720/zones/us-central1-a/diskTypes/pd-standard\",\n   \"sourceSnapshot\": \"https://www.googleapis.com/compute/v1/projects/party/global/snapshots/snapshot\"\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/disk_insert.json",
    "content": "{\"name\":\"testimage1\",\"sizeGb\":1}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/disk_insert_ssd.json",
    "content": "{\"name\":\"testimage1\",\"sizeGb\":1,\"type\":\"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/diskTypes/pd-ssd\"}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/disk_list.json",
    "content": "{\n   \"kind\": \"compute#diskList\",\n   \"id\": \"projects/party/zones/us-central1-a/disks\",\n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/disks\",\n   \"items\": [\n      {\n         \"kind\": \"compute#disk\",\n         \"id\": \"13050421646334304115\",\n         \"creationTimestamp\": \"2012-11-25T01:38:48.306\",\n         \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/disks/testimage1\",\n         \"name\": \"testimage1\",\n         \"sizeGb\": \"1\",\n         \"zone\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a\",\n         \"status\": \"READY\",\n         \"type\": \"https://www.googleapis.com/compute/v1/projects/studied-point-720/zones/us-central1-a/diskTypes/pd-standard\"\n      }\n   ]\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/disktype.json",
    "content": "{\n \"kind\": \"compute#diskType\",\n \"creationTimestamp\": \"2014-06-02T11:07:28.529-07:00\",\n \"name\": \"pd-ssd\",\n \"description\": \"SSD Persistent Disk\",\n \"validDiskSize\": \"10GB-1TB\",\n \"zone\": \"https://content.googleapis.com/compute/v1/projects/studied-point-720/zones/us-central1-a\",\n \"selfLink\": \"https://content.googleapis.com/compute/v1/projects/studied-point-720/zones/us-central1-a/diskTypes/pd-ssd\",\n \"defaultDiskSizeGb\": \"100\"\n}\n\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/disktype_list.json",
    "content": "{\n \"kind\": \"compute#diskTypeList\",\n \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/studied-point-720/zones/us-central1-a/diskTypes\",\n \"items\": [\n  {\n   \"kind\": \"compute#diskType\",\n   \"creationTimestamp\": \"2014-06-02T11:07:28.530-07:00\",\n   \"name\": \"pd-standard\",\n   \"description\": \"Standard Persistent Disk\",\n   \"validDiskSize\": \"10GB-10TB\",\n   \"zone\": \"https://content.googleapis.com/compute/v1/projects/studied-point-720/zones/us-central1-a\",\n   \"selfLink\": \"https://content.googleapis.com/compute/v1/projects/studied-point-720/zones/us-central1-a/diskTypes/pd-standard\",\n   \"defaultDiskSizeGb\": \"500\"\n  },\n  {\n   \"kind\": \"compute#diskType\",\n   \"creationTimestamp\": \"2014-06-02T11:07:28.529-07:00\",\n   \"name\": \"pd-ssd\",\n   \"description\": \"SSD Persistent Disk\",\n   \"validDiskSize\": \"10GB-1TB\",\n   \"zone\": \"https://content.googleapis.com/compute/v1/projects/studied-point-720/zones/us-central1-a\",\n   \"selfLink\": \"https://content.googleapis.com/compute/v1/projects/studied-point-720/zones/us-central1-a/diskTypes/pd-ssd\",\n   \"defaultDiskSizeGb\": \"100\"\n  }\n ]\n}\n\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/disktype_list_central1b.json",
    "content": "{\n \"kind\": \"compute#diskTypeList\",\n \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/studied-point-720/zones/us-central1-a/diskTypes\",\n \"items\": [\n  {\n   \"kind\": \"compute#diskType\",\n   \"creationTimestamp\": \"2014-06-02T11:07:28.530-07:00\",\n   \"name\": \"pd-standard\",\n   \"description\": \"Standard Persistent Disk\",\n   \"validDiskSize\": \"10GB-10TB\",\n   \"zone\": \"https://content.googleapis.com/compute/v1/projects/studied-point-720/zones/us-central1-a\",\n   \"selfLink\": \"https://content.googleapis.com/compute/v1/projects/studied-point-720/zones/us-central1-a/diskTypes/pd-standard\",\n   \"defaultDiskSizeGb\": \"500\"\n  }\n ]\n}\n\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/disktype_ssd.json",
    "content": "{\n \"kind\": \"compute#diskType\",\n \"creationTimestamp\": \"2014-06-02T11:07:28.529-07:00\",\n \"name\": \"pd-ssd\",\n \"description\": \"SSD Persistent Disk\",\n \"validDiskSize\": \"10GB-1TB\",\n \"zone\": \"https://content.googleapis.com/compute/v1/projects/party/zones/us-central1-a\",\n \"selfLink\": \"https://content.googleapis.com/compute/v1/projects/party/zones/us-central1-a/diskTypes/pd-ssd\",\n \"defaultDiskSizeGb\": \"100\"\n}\n\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/firewall_get.json",
    "content": "{\n\n   \"kind\": \"compute#firewall\",\n   \"id\": \"12862241031274216284\",\n   \"creationTimestamp\": \"2012-04-13T03:05:02.855\",\n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/global/firewalls/jclouds-test\",\n   \"name\": \"jclouds-test\",\n   \"description\": \"Internal traffic from default allowed\",\n   \"network\": \"https://www.googleapis.com/compute/v1/projects/party/global/networks/jclouds-test\",\n   \"sourceRanges\": [\n      \"10.0.0.0/8\"\n   ],\n   \"allowed\": [\n      {\n         \"IPProtocol\": \"tcp\",\n         \"ports\": [\n            \"1-65535\"\n         ]\n      },\n      {\n         \"IPProtocol\": \"udp\",\n         \"ports\": [\n            \"1-65535\"\n         ]\n      },\n      {\n         \"IPProtocol\": \"icmp\"\n      }\n   ]\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/firewall_insert.json",
    "content": "{\n  \"name\": \"myfw\",\n  \"network\": \"https://www.googleapis.com/compute/v1/projects/party/global/networks/default\",\n  \"sourceRanges\": [\n    \"10.0.1.0/32\"\n  ],\n  \"sourceTags\": [\n    \"tag1\"\n  ],\n  \"targetTags\": [\n    \"tag2\"\n  ],\n  \"allowed\": [\n    {\n      \"IPProtocol\": \"tcp\",\n      \"ports\": [\n        \"22\",\n        \"23-24\"\n      ]\n    }\n  ]\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/firewall_insert_2.json",
    "content": "{\n  \"name\": \"jclouds-test-65f\",\n  \"network\": \"https://www.googleapis.com/compute/v1/projects/party/networks/default\",\n  \"sourceRanges\": [\n    \"10.0.0.0/8\",\n    \"0.0.0.0/0\"\n  ],\n  \"sourceTags\": [\n    \"aTag\"\n  ],\n  \"targetTags\": [\n    \"jclouds-test-65f\"\n  ],\n  \"allowed\": [\n    {\n      \"IPProtocol\": \"tcp\",\n      \"ports\": [\n        \"22\"\n      ]\n    },\n    {\n      \"IPProtocol\": \"udp\",\n      \"ports\": [\n        \"22\"\n      ]\n    }\n  ]\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/firewall_insert_3.json",
    "content": "{\n  \"name\": \"jclouds-test-65f\",\n  \"network\": \"https://www.googleapis.com/compute/v1/projects/party/networks/jclouds-test\",\n  \"sourceRanges\": [\n    \"10.128.0.0/20\",\n    \"0.0.0.0/0\"\n  ],\n  \"sourceTags\": [\n    \"aTag\"\n  ],\n  \"targetTags\": [\n    \"jclouds-test-65f\"\n  ],\n  \"allowed\": [\n    {\n      \"IPProtocol\": \"tcp\",\n      \"ports\": [\n        \"22\"\n      ]\n    },\n    {\n      \"IPProtocol\": \"udp\",\n      \"ports\": [\n        \"22\"\n      ]\n    }\n  ]\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/firewall_list.json",
    "content": "{\n   \"kind\": \"compute#firewallList\",\n   \"id\": \"projects/google/firewalls\",\n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/google/global/firewalls\",\n   \"items\": [\n      {\n\n         \"kind\": \"compute#firewall\",\n         \"id\": \"12862241031274216284\",\n         \"creationTimestamp\": \"2012-04-13T03:05:02.855\",\n         \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/global/firewalls/jclouds-test\",\n         \"name\": \"jclouds-test\",\n         \"description\": \"Internal traffic from default allowed\",\n         \"network\": \"https://www.googleapis.com/compute/v1/projects/party/global/networks/jclouds-test\",\n         \"sourceRanges\": [\n            \"10.0.0.0/8\"\n         ],\n         \"allowed\": [\n            {\n               \"IPProtocol\": \"tcp\",\n               \"ports\": [\n                  \"1-65535\"\n               ]\n            },\n            {\n               \"IPProtocol\": \"udp\",\n               \"ports\": [\n                  \"1-65535\"\n               ]\n            },\n            {\n               \"IPProtocol\": \"icmp\"\n            }\n         ]\n      },\n      {\n\n         \"kind\": \"compute#firewall\",\n         \"id\": \"12862241067393040785\",\n         \"creationTimestamp\": \"2012-04-13T03:05:04.365\",\n         \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/google/global/firewalls/default-ssh\",\n         \"name\": \"default-ssh\",\n         \"description\": \"SSH allowed from anywhere\",\n         \"network\": \"https://www.googleapis.com/compute/v1/projects/google/global/networks/default\",\n         \"sourceRanges\": [\n            \"0.0.0.0/0\"\n         ],\n         \"allowed\": [\n            {\n               \"IPProtocol\": \"tcp\",\n               \"ports\": [\n                  \"22\"\n               ]\n            }\n         ]\n      }\n   ]\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/firewall_list_compute.json",
    "content": "{\n   \"kind\": \"compute#firewallList\",\n   \"id\": \"projects/google/firewalls\",\n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/google/global/firewalls\",\n   \"items\": [\n      {\n         \"kind\": \"compute#firewall\",\n         \"id\": \"12862241031274216284\",\n         \"creationTimestamp\": \"2012-04-13T03:05:02.855\",\n         \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/global/firewalls/jclouds-test-delete\",\n         \"name\": \"jclouds-test-delete-34sf\",\n         \"description\": \"Internal traffic from default allowed\",\n         \"network\": \"https://www.googleapis.com/compute/v1/projects/party/global/networks/jclouds-test-delete\",\n         \"sourceRanges\": [\n            \"10.0.0.0/8\"\n         ],\n         \"allowed\": [\n            {\n               \"IPProtocol\": \"tcp\",\n               \"ports\": [\n                  \"1-65535\"\n               ]\n            },\n            {\n               \"IPProtocol\": \"udp\",\n               \"ports\": [\n                  \"1-65535\"\n               ]\n            },\n            {\n               \"IPProtocol\": \"icmp\"\n            }\n         ]\n      }\n   ]\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/forwardingrule_get.json",
    "content": "{\n    \"kind\": \"compute#forwardingRule\",\n    \"id\": \"6732523704970219884\",\n    \"creationTimestamp\": \"2014-01-08T06:51:10.809-08:00\",\n    \"name\": \"test-forwarding-rule\",\n    \"region\": \"https://www.googleapis.com/compute/v1/projects/party/regions/europe-west1\",\n    \"IPAddress\": \"23.251.129.77\",\n    \"IPProtocol\": \"TCP\",\n    \"portRange\": \"1-65535\",\n    \"target\": \"https://www.googleapis.com/compute/v1/projects/party/regions/europe-west1/targetPools/test-target-pool\",\n    \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/regions/europe-west1/forwardingRules/test-forwarding-rule\"\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/forwardingrule_insert.json",
    "content": "{\n\"name\": \"test-forwarding-rule\",\n\"target\": \"https://www.googleapis.com/compute/v1/projects/party/regions/europe-west1/targetPools/test-target-pool\"\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/forwardingrule_list.json",
    "content": "{\n\"kind\": \"compute#forwardingRuleList\",\n\"selfLink\": \"https://content.googleapis.com/compute/v1/projects/party/regions/europe-west1/forwardingRules\",\n\"id\": \"projects/party/regions/europe-west1/forwardingRules\",\n\"items\": [\n{\n\"kind\": \"compute#forwardingRule\",\n\"id\": \"6732523704970219884\",\n\"creationTimestamp\": \"2014-01-08T06:51:10.809-08:00\",\n\"name\": \"test-forwarding-rule\",\n\"region\": \"https://www.googleapis.com/compute/v1/projects/party/regions/europe-west1\",\n\"IPAddress\": \"23.251.129.77\",\n\"IPProtocol\": \"TCP\",\n\"portRange\": \"1-65535\",\n\"target\": \"https://www.googleapis.com/compute/v1/projects/party/regions/europe-west1/targetPools/test-target-pool\",\n\"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/regions/europe-west1/forwardingRules/test-forwarding-rule\"\n}\n]\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/forwardingrule_set_target.json",
    "content": "{\"target\":\"https://www.googleapis.com/compute/v1/projects/party/regions/europe-west1/targetPools/test-target-pool\"}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/global_forwarding_rule_get.json",
    "content": "{\n   \"kind\": \"compute#forwardingRule\",\n   \"id\": \"8192211304399313984\",\n   \"creationTimestamp\": \"2014-07-18T09:47:30.826-07:00\",\n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/myproject/global/forwardingRules/jclouds-test\",\n   \"name\": \"jclouds-test\",\n   \"description\": \"tcp forwarding rule\",\n   \"IPAddress\": \"107.178.255.156\",\n   \"IPProtocol\": \"TCP\",\n   \"portRange\": \"80-80\",\n   \"target\": \"https://www.googleapis.com/compute/v1/projects/myproject/global/targetHttpProxies/jclouds-test\"\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/global_forwarding_rule_insert.json",
    "content": "{\"name\":\"jclouds-test\",\"target\":\"https://www.googleapis.com/compute/v1/projects/myproject/global/targetHttpProxies/jclouds-test\", \"portRange\":\"80\"}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/global_forwarding_rule_list.json",
    "content": "{\n   \"kind\": \"compute#forwardingRuleList\",\n   \"id\": \"projects/myproject/global/forwardingRules\",\n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/myproject/global/forwardingRules\",\n   \"items\": [\n      {\n         \"kind\": \"compute#forwardingRule\",\n         \"id\": \"8192211304399313984\",\n         \"creationTimestamp\": \"2014-07-18T09:47:30.826-07:00\",\n         \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/myproject/global/forwardingRules/jclouds-test\",\n         \"name\": \"jclouds-test\",\n         \"description\": \"tcp forwarding rule\",\n         \"IPAddress\": \"107.178.255.156\",\n         \"IPProtocol\": \"TCP\",\n         \"portRange\": \"80-80\",\n         \"target\": \"https://www.googleapis.com/compute/v1/projects/myproject/global/targetHttpProxies/jclouds-test\"\n      }\n   ]\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/global_forwarding_rule_setTarget.json",
    "content": "{\n   \"target\": \"https://www.googleapis.com/compute/v1/projects/myproject/global/targetHttpProxies/jclouds-test-2\"\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/global_operation.json",
    "content": "{\n   \"kind\": \"compute#operation\",\n   \"id\": \"13053095055850848306\",\n   \"creationTimestamp\": \"2013-07-26T13:57:20.204-07:00\",\n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/global/operations/operation-1354084865060\",\n   \"name\": \"operation-1354084865060\",\n   \"targetLink\": \"https://www.googleapis.com/compute/v1/projects/party/global/firewalls/jclouds-test-delete\",\n   \"targetId\": \"13053094017547040099\",\n   \"status\": \"DONE\",\n   \"user\": \"user@developer.gserviceaccount.com\",\n   \"progress\": 100,\n   \"insertTime\": \"2012-11-28T06:41:05.060\",\n   \"startTime\": \"2012-11-28T06:41:05.142\",\n   \"endTime\": \"2012-11-28T06:41:06.142\",\n   \"operationType\": \"insert\"\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/global_operation_list.json",
    "content": "{\n   \"kind\": \"compute#operationList\",\n   \"id\": \"projects/party/global/operations\",\n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/global/operations\",\n   \"items\": [\n      {\n         \"kind\": \"compute#operation\",\n         \"id\": \"13053095055850848306\",\n         \"creationTimestamp\": \"2013-07-26T13:57:20.204-07:00\",\n         \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/global/operations/operation-1354084865060\",\n         \"name\": \"operation-1354084865060\",\n         \"targetLink\": \"https://www.googleapis.com/compute/v1/projects/party/global/firewalls/jclouds-test-delete\",\n         \"targetId\": \"13053094017547040099\",\n         \"status\": \"DONE\",\n         \"user\": \"user@developer.gserviceaccount.com\",\n         \"progress\": 100,\n         \"insertTime\": \"2012-11-28T06:41:05.060\",\n         \"startTime\": \"2012-11-28T06:41:05.142\",\n         \"endTime\": \"2012-11-28T06:41:06.142\",\n         \"operationType\": \"insert\"\n      }\n   ]\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/health_status_get_health.json",
    "content": "{\n   \"kind\": \"compute#backendServiceGroupHealth\",\n   \"healthStatus\": [\n      {\n         \"port\": 80,         \n         \"instance\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/instances/jclouds-test\",\n         \"healthState\": \"HEALTHY\"\n      }\n   ]\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/httphealthcheck_get.json",
    "content": "{\n  \"kind\": \"compute#httpHealthCheck\",\n  \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party-gce/global/httpHealthChecks/http-health-check-api-live-test\",\n  \"id\": \"2761502483700014319\",\n  \"creationTimestamp\": \"2014-01-14T05:55:54.910-08:00\",\n  \"name\": \"http-health-check-api-live-test\",\n  \"description\": \"Test Health Check\",\n  \"requestPath\": \"/\",\n  \"port\": 80,\n  \"checkIntervalSec\": 5,\n  \"timeoutSec\": 5,\n  \"unhealthyThreshold\": 2,\n  \"healthyThreshold\": 2\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/httphealthcheck_insert.json",
    "content": "{\"name\":\"http-health-check\",\"requestPath\":\"/\",\"port\":80,\"checkIntervalSec\":5,\"timeoutSec\":0,\"unhealthyThreshold\":0,\"healthyThreshold\":2}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/httphealthcheck_list.json",
    "content": "{\n  \"kind\": \"compute#httpHealthCheckList\",\n  \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party-gce/global/httpHealthChecks\",\n  \"id\": \"projects/party-gce/global/httpHealthChecks\",\n  \"items\": [\n    {\n      \"kind\": \"compute#httpHealthCheck\",\n      \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party-gce/global/httpHealthChecks/http-health-check-api-live-test\",\n      \"id\": \"2761502483700014319\",\n      \"creationTimestamp\": \"2014-01-14T05:55:54.910-08:00\",\n      \"name\": \"http-health-check-api-live-test\",\n      \"description\": \"Test Health Check\",\n      \"requestPath\": \"/\",\n      \"port\": 80,\n      \"checkIntervalSec\": 5,\n      \"timeoutSec\": 5,\n      \"unhealthyThreshold\": 2,\n      \"healthyThreshold\": 2\n    },\n    {\n      \"kind\": \"compute#httpHealthCheck\",\n      \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party-gce/global/httpHealthChecks/myname-andrea-kmzmi1bh-http-health-check\",\n      \"id\": \"1035854271083519643\",\n      \"creationTimestamp\": \"2014-01-08T14:38:29.363-08:00\",\n      \"name\": \"myname-andrea-kmzmi1bh-http-health-check\",\n      \"timeoutSec\": 5,\n      \"unhealthyThreshold\": 2\n    },\n    {\n      \"kind\": \"compute#httpHealthCheck\",\n      \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party-gce/global/httpHealthChecks/myname-andrea-zk7gadwq-http-health-check\",\n      \"id\": \"7006563292274658743\",\n      \"creationTimestamp\": \"2014-01-08T14:48:03.276-08:00\",\n      \"name\": \"myname-andrea-zk7gadwq-http-health-check\",\n      \"timeoutSec\": 5,\n      \"unhealthyThreshold\": 2\n    }\n  ]\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/httphealthcheck_patch.json",
    "content": "{\"name\":\"http-health-check\",\"timeoutSec\":0,\"unhealthyThreshold\":0}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/image_deprecate.json",
    "content": "{\n  \"state\": \"DEPRECATED\",\n  \"replacement\": \"https://www.googleapis.com/compute/v1/projects/centos-cloud/global/images/centos-6-2-v20120326test\",\n  \"deprecated\": \"2014-07-16T22:16:13.468Z\",\n  \"obsolete\": \"2014-10-16T22:16:13.468Z\",\n  \"deleted\": \"2015-01-16T22:16:13.468Z\"\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/image_get.json",
    "content": "{\n  \"kind\": \"compute#image\",\n  \"id\": \"12941197498378735318\",\n  \"creationTimestamp\": \"2012-07-16T22:16:13.468\",\n  \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/centos-cloud/global/images/centos-6-2-v20120326\",\n  \"name\": \"centos-6-2-v20120326\",\n  \"description\": \"DEPRECATED. CentOS 6.2 image; Created Mon, 26 Mar 2012 21:19:09 +0000\",\n  \"sourceType\": \"RAW\",\n  \"deprecated\": {\n    \"state\": \"DEPRECATED\",\n    \"replacement\": \"https://www.googleapis.com/compute/v1/projects/centos-cloud/global/images/centos-6-v20130104\"\n  },\n  \"rawDisk\": {\n    \"source\": \"\",\n    \"containerType\": \"TAR\"\n  },\n  \"status\": \"READY\",\n  \"archiveSizeBytes\": \"881210631\",\n  \"diskSizeGb\": \"8\",\n  \"sourceDisk\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/disk/disk\",\n  \"sourceDiskId\": \"9598530021316715047\",\n  \"licenses\": [\n    \"https://www.googleapis.com/compute/v1/projects/suse-cloud/global/licenses/sles-12\"\n  ]\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/image_get_for_source_image.json",
    "content": "{\n  \"kind\": \"compute#image\",\n  \"id\": \"12941197498378735318\",\n  \"creationTimestamp\": \"2012-07-16T22:16:13.468\",\n  \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-7-wheezy-v20140718\",\n  \"name\": \"debian-7-wheezy-v20140718\",\n  \"description\": \"DEPRECATED. CentOS 6.2 image; Created Mon, 26 Mar 2012 21:19:09 +0000\",\n  \"sourceType\": \"RAW\",\n  \"deprecated\": {\n    \"state\": \"DEPRECATED\",\n    \"replacement\": \"https://www.googleapis.com/compute/v1/projects/party/global/images/centos-6-v20130104\"\n  },\n  \"rawDisk\": {\n    \"source\": \"\",\n    \"containerType\": \"TAR\"\n  },\n  \"status\": \"READY\",\n  \"archiveSizeBytes\": \"881210631\",\n  \"diskSizeGb\": \"8\",\n  \"sourceDisk\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/disk/disk\",\n  \"sourceDiskId\": \"9598530021316715047\",\n  \"licenses\": [\n    \"https://www.googleapis.com/compute/v1/projects/suse-cloud/global/licenses/sles-12\"\n  ]\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/image_insert.json",
    "content": "{\"sourceType\": \"RAW\", \"rawDisk\": {\n   \"source\": \"https://storage.googleapis.com/mybuket/myimage.image.tar.gz\",\n   \"containerType\": \"TAR\"\n}, \"kind\": \"compute#image\", \"name\": \"myimage\"}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/image_insert_from_pd.json",
    "content": "{\"name\":\"my-image\",\"sourceDisk\":\"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/disks/mydisk\"}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/image_list.json",
    "content": "{\n  \"kind\": \"compute#imageList\",\n  \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/centos-cloud/global/images\",\n  \"id\": \"projects/centos-cloud/global/images\",\n  \"items\": [\n    {\n      \"kind\": \"compute#image\",\n      \"id\": \"12941197498378735318\",\n      \"creationTimestamp\": \"2012-07-16T22:16:13.468\",\n      \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/centos-cloud/global/images/centos-6-2-v20120326\",\n      \"name\": \"centos-6-2-v20120326\",\n      \"description\": \"DEPRECATED. CentOS 6.2 image; Created Mon, 26 Mar 2012 21:19:09 +0000\",\n      \"sourceType\": \"RAW\",\n      \"deprecated\": {\n        \"state\": \"DEPRECATED\",\n        \"replacement\": \"https://www.googleapis.com/compute/v1/projects/centos-cloud/global/images/centos-6-v20130104\"\n      },\n      \"rawDisk\": {\n        \"source\": \"\",\n        \"containerType\": \"TAR\"\n      },\n      \"status\": \"READY\",\n      \"archiveSizeBytes\": \"881210631\",\n      \"diskSizeGb\": \"8\",\n      \"sourceDisk\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/disk/disk\",\n      \"sourceDiskId\": \"9598530021316715047\",\n      \"licenses\": [\n        \"https://www.googleapis.com/compute/v1/projects/suse-cloud/global/licenses/sles-12\"\n      ]\n    }\n  ]\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/image_list_centos.json",
    "content": "{\n    \"kind\": \"compute#imageList\",\n    \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/centos-cloud/global/images\",\n    \"id\": \"projects/centos-cloud/global/images\",\n    \"items\": [\n        {\n            \"kind\": \"compute#image\",\n            \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/centos-cloud/global/images/centos-6-v20131120\",\n            \"id\": \"11748647391859510935\",\n            \"creationTimestamp\": \"2013-11-25T15:13:50.611-08:00\",\n            \"name\": \"centos-6-v20131120\",\n            \"description\": \"SCSI-enabled CentOS 6 built on 2013-11-20\",\n            \"sourceType\": \"RAW\",\n            \"rawDisk\": {\n                \"source\": \"\",\n                \"containerType\": \"TAR\"\n            },\n            \"deprecated\": {\n                \"state\": \"DEPRECATED\",\n                \"replacement\": \"https://www.googleapis.com/compute/v1/projects/centos-cloud/global/images/centos-6-v20140318\"\n            },\n            \"status\": \"READY\",\n            \"archiveSizeBytes\": \"269993565\",\n            \"diskSizeGb\": \"10\"\n        },\n        {\n            \"kind\": \"compute#image\",\n            \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/centos-cloud/global/images/centos-6-v20140318\",\n            \"id\": \"11743140967858608122\",\n            \"creationTimestamp\": \"2014-03-19T15:01:13.388-07:00\",\n            \"name\": \"centos-6-v20140318\",\n            \"description\": \"CentOS 6.5 x86_64 built on 2014-03-18\",\n            \"sourceType\": \"RAW\",\n            \"rawDisk\": {\n                \"source\": \"\",\n                \"containerType\": \"TAR\"\n            },\n            \"deprecated\": {\n                \"state\": \"DEPRECATED\",\n                \"replacement\": \"https://www.googleapis.com/compute/v1/projects/centos-cloud/global/images/centos-6-v20140408\"\n            },\n            \"status\": \"READY\",\n            \"archiveSizeBytes\": \"341230444\",\n            \"diskSizeGb\": \"10\"\n        },\n        {\n            \"kind\": \"compute#image\",\n            \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/centos-cloud/global/images/centos-6-v20140408\",\n            \"id\": \"18033188469723077298\",\n            \"creationTimestamp\": \"2014-04-09T10:31:57.518-07:00\",\n            \"name\": \"centos-6-v20140408\",\n            \"description\": \"CentOS 6.5 x86_64 built on 2014-04-08\",\n            \"sourceType\": \"RAW\",\n            \"rawDisk\": {\n                \"source\": \"\",\n                \"containerType\": \"TAR\"\n            },\n            \"deprecated\": {\n                \"state\": \"DEPRECATED\",\n                \"replacement\": \"https://www.googleapis.com/compute/v1/projects/centos-cloud/global/images/centos-6-v20140415\"\n            },\n            \"status\": \"READY\",\n            \"archiveSizeBytes\": \"342252847\",\n            \"diskSizeGb\": \"10\"\n        },\n        {\n            \"kind\": \"compute#image\",\n            \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/centos-cloud/global/images/centos-6-v20140415\",\n            \"id\": \"10463166969914166288\",\n            \"creationTimestamp\": \"2014-04-22T12:05:16.927-07:00\",\n            \"name\": \"centos-6-v20140415\",\n            \"description\": \"CentOS 6.5 x86_64 built on 2014-04-15\",\n            \"sourceType\": \"RAW\",\n            \"rawDisk\": {\n                \"source\": \"\",\n                \"containerType\": \"TAR\"\n            },\n            \"deprecated\": {\n                \"state\": \"DEPRECATED\",\n                \"replacement\": \"https://www.googleapis.com/compute/v1/projects/centos-cloud/global/images/centos-6-v20140522\"\n            },\n            \"status\": \"READY\",\n            \"archiveSizeBytes\": \"1026663807\",\n            \"diskSizeGb\": \"10\"\n        },\n        {\n            \"kind\": \"compute#image\",\n            \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/centos-cloud/global/images/centos-6-v20140522\",\n            \"id\": \"14390164727436022001\",\n            \"creationTimestamp\": \"2014-06-03T10:21:42.109-07:00\",\n            \"name\": \"centos-6-v20140522\",\n            \"description\": \"CentOS 6.5 x86_64 built on 2014-05-22\",\n            \"sourceType\": \"RAW\",\n            \"rawDisk\": {\n                \"source\": \"\",\n                \"containerType\": \"TAR\"\n            },\n            \"deprecated\": {\n                \"state\": \"DEPRECATED\",\n                \"replacement\": \"https://www.googleapis.com/compute/v1/projects/centos-cloud/global/images/centos-6-v20140606\"\n            },\n            \"status\": \"READY\",\n            \"archiveSizeBytes\": \"1028292810\",\n            \"diskSizeGb\": \"10\"\n        },\n        {\n            \"kind\": \"compute#image\",\n            \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/centos-cloud/global/images/centos-6-v20140605\",\n            \"id\": \"16310166269920012092\",\n            \"creationTimestamp\": \"2014-06-05T11:04:45.767-07:00\",\n            \"name\": \"centos-6-v20140605\",\n            \"description\": \"CentOS 6.5 x86_64 built on 2014-06-05\",\n            \"sourceType\": \"RAW\",\n            \"rawDisk\": {\n                \"source\": \"\",\n                \"containerType\": \"TAR\"\n            },\n            \"deprecated\": {\n                \"state\": \"DEPRECATED\",\n                \"replacement\": \"https://www.googleapis.com/compute/v1/projects/centos-cloud/global/images/centos-6-v20140606\"\n            },\n            \"status\": \"READY\",\n            \"archiveSizeBytes\": \"1028745777\",\n            \"diskSizeGb\": \"10\"\n        },\n        {\n            \"kind\": \"compute#image\",\n            \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/centos-cloud/global/images/centos-6-v20140606\",\n            \"id\": \"6290630306542078308\",\n            \"creationTimestamp\": \"2014-06-06T13:16:42.265-07:00\",\n            \"name\": \"centos-6-v20140606\",\n            \"description\": \"CentOS 6.5 x86_64 built on 2014-06-06\",\n            \"sourceType\": \"RAW\",\n            \"rawDisk\": {\n                \"source\": \"\",\n                \"containerType\": \"TAR\"\n            },\n            \"deprecated\": {\n                \"state\": \"DEPRECATED\",\n                \"replacement\": \"https://www.googleapis.com/compute/v1/projects/centos-cloud/global/images/centos-6-v20140619\"\n            },\n            \"status\": \"READY\",\n            \"archiveSizeBytes\": \"1028757792\",\n            \"diskSizeGb\": \"10\"\n        },\n        {\n            \"kind\": \"compute#image\",\n            \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/centos-cloud/global/images/centos-6-v20140619\",\n            \"id\": \"3614861379648377676\",\n            \"creationTimestamp\": \"2014-06-24T13:28:11.552-07:00\",\n            \"name\": \"centos-6-v20140619\",\n            \"description\": \"CentOS 6.5 x86_64 built on 2014-06-19\",\n            \"sourceType\": \"RAW\",\n            \"rawDisk\": {\n                \"source\": \"\",\n                \"containerType\": \"TAR\"\n            },\n            \"deprecated\": {\n                \"state\": \"DEPRECATED\",\n                \"replacement\": \"https://www.googleapis.com/compute/v1/projects/centos-cloud/global/images/centos-6-v20140718\"\n            },\n            \"status\": \"READY\",\n            \"archiveSizeBytes\": \"1029860991\",\n            \"diskSizeGb\": \"10\"\n        },\n        {\n            \"kind\": \"compute#image\",\n            \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/centos-cloud/global/images/centos-6-v20140718\",\n            \"id\": \"16259951858818091437\",\n            \"creationTimestamp\": \"2014-07-24T09:02:18.298-07:00\",\n            \"name\": \"centos-6-v20140718\",\n            \"description\": \"CentOS 6.5 x86_64 built on 2014-07-18\",\n            \"sourceType\": \"RAW\",\n            \"rawDisk\": {\n                \"source\": \"\",\n                \"containerType\": \"TAR\"\n            },\n            \"status\": \"READY\",\n            \"archiveSizeBytes\": \"1031630715\",\n            \"diskSizeGb\": \"10\"\n        }\n    ]\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/image_list_debian.json",
    "content": "{\n    \"kind\": \"compute#imageList\",\n    \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images\",\n    \"id\": \"projects/debian-cloud/global/images\",\n    \"items\": [\n        {\n            \"kind\": \"compute#image\",\n            \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/backports-debian-7-wheezy-v20131127\",\n            \"id\": \"12371298324486102144\",\n            \"creationTimestamp\": \"2013-12-02T17:49:01.206-08:00\",\n            \"name\": \"backports-debian-7-wheezy-v20131127\",\n            \"description\": \"Debian GNU/Linux 7.2 (wheezy) with backports kernel built on 2013-11-27\",\n            \"sourceType\": \"RAW\",\n            \"rawDisk\": {\n                \"source\": \"\",\n                \"containerType\": \"TAR\"\n            },\n            \"deprecated\": {\n                \"state\": \"DEPRECATED\",\n                \"replacement\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/backports-debian-7-wheezy-v20140318\"\n            },\n            \"status\": \"READY\",\n            \"archiveSizeBytes\": \"365056004\",\n            \"diskSizeGb\": \"10\"\n        },\n        {\n            \"kind\": \"compute#image\",\n            \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/backports-debian-7-wheezy-v20140318\",\n            \"id\": \"4359542978415320596\",\n            \"creationTimestamp\": \"2014-03-19T14:59:48.212-07:00\",\n            \"name\": \"backports-debian-7-wheezy-v20140318\",\n            \"description\": \"Debian GNU/Linux 7.4 (wheezy) amd64 with backports kernel built on 2014-03-18\",\n            \"sourceType\": \"RAW\",\n            \"rawDisk\": {\n                \"source\": \"\",\n                \"containerType\": \"TAR\"\n            },\n            \"deprecated\": {\n                \"state\": \"DEPRECATED\",\n                \"replacement\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/backports-debian-7-wheezy-v20140331\"\n            },\n            \"status\": \"READY\",\n            \"archiveSizeBytes\": \"363791902\",\n            \"diskSizeGb\": \"10\"\n        },\n        {\n            \"kind\": \"compute#image\",\n            \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/backports-debian-7-wheezy-v20140331\",\n            \"id\": \"15835408046770346721\",\n            \"creationTimestamp\": \"2014-04-02T13:22:10.344-07:00\",\n            \"name\": \"backports-debian-7-wheezy-v20140331\",\n            \"description\": \"Debian GNU/Linux 7.4 (wheezy) amd64 with backports kernel and SSH packages built on 2014-03-31\",\n            \"sourceType\": \"RAW\",\n            \"rawDisk\": {\n                \"source\": \"\",\n                \"containerType\": \"TAR\"\n            },\n            \"deprecated\": {\n                \"state\": \"DEPRECATED\",\n                \"replacement\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/backports-debian-7-wheezy-v20140408\"\n            },\n            \"status\": \"READY\",\n            \"archiveSizeBytes\": \"442398181\",\n            \"diskSizeGb\": \"10\"\n        },\n        {\n            \"kind\": \"compute#image\",\n            \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/backports-debian-7-wheezy-v20140408\",\n            \"id\": \"11347897274148340677\",\n            \"creationTimestamp\": \"2014-04-09T10:34:36.072-07:00\",\n            \"name\": \"backports-debian-7-wheezy-v20140408\",\n            \"description\": \"Debian GNU/Linux 7.4 (wheezy) amd64 with backports kernel and SSH packages built on 2014-04-08\",\n            \"sourceType\": \"RAW\",\n            \"rawDisk\": {\n                \"source\": \"\",\n                \"containerType\": \"TAR\"\n            },\n            \"deprecated\": {\n                \"state\": \"DEPRECATED\",\n                \"replacement\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/backports-debian-7-wheezy-v20140415\"\n            },\n            \"status\": \"READY\",\n            \"archiveSizeBytes\": \"460293681\",\n            \"diskSizeGb\": \"10\"\n        },\n        {\n            \"kind\": \"compute#image\",\n            \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/backports-debian-7-wheezy-v20140415\",\n            \"id\": \"1961353585117201359\",\n            \"creationTimestamp\": \"2014-04-22T12:05:21.799-07:00\",\n            \"name\": \"backports-debian-7-wheezy-v20140415\",\n            \"description\": \"Debian GNU/Linux 7.4 (wheezy) amd64 with backports kernel and SSH packages built on 2014-04-15\",\n            \"sourceType\": \"RAW\",\n            \"rawDisk\": {\n                \"source\": \"\",\n                \"containerType\": \"TAR\"\n            },\n            \"deprecated\": {\n                \"state\": \"DEPRECATED\",\n                \"replacement\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/backports-debian-7-wheezy-v20140522\"\n            },\n            \"status\": \"READY\",\n            \"archiveSizeBytes\": \"1305361944\",\n            \"diskSizeGb\": \"10\"\n        },\n        {\n            \"kind\": \"compute#image\",\n            \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/backports-debian-7-wheezy-v20140522\",\n            \"id\": \"9086860851120583043\",\n            \"creationTimestamp\": \"2014-06-03T10:22:40.439-07:00\",\n            \"name\": \"backports-debian-7-wheezy-v20140522\",\n            \"description\": \"Debian GNU/Linux 7.5 (wheezy) amd64 with backports kernel and SSH packages built on 2014-05-22\",\n            \"sourceType\": \"RAW\",\n            \"rawDisk\": {\n                \"source\": \"\",\n                \"containerType\": \"TAR\"\n            },\n            \"deprecated\": {\n                \"state\": \"DEPRECATED\",\n                \"replacement\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/backports-debian-7-wheezy-v20140606\"\n            },\n            \"status\": \"READY\",\n            \"archiveSizeBytes\": \"1291544127\",\n            \"diskSizeGb\": \"10\"\n        },\n        {\n            \"kind\": \"compute#image\",\n            \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/backports-debian-7-wheezy-v20140605\",\n            \"id\": \"3162880700849242534\",\n            \"creationTimestamp\": \"2014-06-05T11:15:06.942-07:00\",\n            \"name\": \"backports-debian-7-wheezy-v20140605\",\n            \"description\": \"Debian GNU/Linux 7.5 (wheezy) amd64 with backports kernel and SSH packages built on 2014-06-05\",\n            \"sourceType\": \"RAW\",\n            \"rawDisk\": {\n                \"source\": \"\",\n                \"containerType\": \"TAR\"\n            },\n            \"deprecated\": {\n                \"state\": \"DEPRECATED\",\n                \"replacement\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/backports-debian-7-wheezy-v20140606\"\n            },\n            \"status\": \"READY\",\n            \"archiveSizeBytes\": \"1342678611\",\n            \"diskSizeGb\": \"10\"\n        },\n        {\n            \"kind\": \"compute#image\",\n            \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/backports-debian-7-wheezy-v20140606\",\n            \"id\": \"10385475893990329896\",\n            \"creationTimestamp\": \"2014-06-06T13:16:42.088-07:00\",\n            \"name\": \"backports-debian-7-wheezy-v20140606\",\n            \"description\": \"Debian GNU/Linux 7.5 (wheezy) amd64 with backports kernel and SSH packages built on 2014-06-06\",\n            \"sourceType\": \"RAW\",\n            \"rawDisk\": {\n                \"source\": \"\",\n                \"containerType\": \"TAR\"\n            },\n            \"deprecated\": {\n                \"state\": \"DEPRECATED\",\n                \"replacement\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/backports-debian-7-wheezy-v20140619\"\n            },\n            \"status\": \"READY\",\n            \"archiveSizeBytes\": \"1356729999\",\n            \"diskSizeGb\": \"10\"\n        },\n        {\n            \"kind\": \"compute#image\",\n            \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/backports-debian-7-wheezy-v20140619\",\n            \"id\": \"15689321734978914353\",\n            \"creationTimestamp\": \"2014-06-24T13:29:10.490-07:00\",\n            \"name\": \"backports-debian-7-wheezy-v20140619\",\n            \"description\": \"Debian GNU/Linux 7.5 (wheezy) amd64 with backports kernel and SSH packages built on 2014-06-19\",\n            \"sourceType\": \"RAW\",\n            \"rawDisk\": {\n                \"source\": \"\",\n                \"containerType\": \"TAR\"\n            },\n            \"deprecated\": {\n                \"state\": \"DEPRECATED\",\n                \"replacement\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/backports-debian-7-wheezy-v20140718\"\n            },\n            \"status\": \"READY\",\n            \"archiveSizeBytes\": \"1281043596\",\n            \"diskSizeGb\": \"10\"\n        },\n        {\n            \"kind\": \"compute#image\",\n            \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/backports-debian-7-wheezy-v20140718\",\n            \"id\": \"12577251946941921963\",\n            \"creationTimestamp\": \"2014-07-24T09:10:05.365-07:00\",\n            \"name\": \"backports-debian-7-wheezy-v20140718\",\n            \"description\": \"Debian GNU/Linux 7.6 (wheezy) amd64 with backports kernel and SSH packages built on 2014-07-18\",\n            \"sourceType\": \"RAW\",\n            \"rawDisk\": {\n                \"source\": \"\",\n                \"containerType\": \"TAR\"\n            },\n            \"status\": \"READY\",\n            \"archiveSizeBytes\": \"1335987075\",\n            \"diskSizeGb\": \"10\"\n        },\n        {\n            \"kind\": \"compute#image\",\n            \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-7-wheezy-v20131014\",\n            \"id\": \"2768298251193329825\",\n            \"creationTimestamp\": \"2013-10-28T13:52:08.233-07:00\",\n            \"name\": \"debian-7-wheezy-v20131014\",\n            \"description\": \"Debian GNU/Linux 7.2 (wheezy) built on 2013-10-14\",\n            \"sourceType\": \"RAW\",\n            \"rawDisk\": {\n                \"source\": \"\",\n                \"containerType\": \"TAR\"\n            },\n            \"deprecated\": {\n                \"state\": \"DEPRECATED\",\n                \"replacement\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-7-wheezy-v20131120\",\n                \"deprecated\": \"2013-12-02T12:00:00Z\"\n            },\n            \"status\": \"READY\",\n            \"archiveSizeBytes\": \"405683884\",\n            \"diskSizeGb\": \"10\"\n        },\n        {\n            \"kind\": \"compute#image\",\n            \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-7-wheezy-v20131120\",\n            \"id\": \"17312518942796567788\",\n            \"creationTimestamp\": \"2013-11-25T15:17:00.436-08:00\",\n            \"name\": \"debian-7-wheezy-v20131120\",\n            \"description\": \"Debian GNU/Linux 7.2 (wheezy) built on 2013-11-20\",\n            \"sourceType\": \"RAW\",\n            \"rawDisk\": {\n                \"source\": \"\",\n                \"containerType\": \"TAR\"\n            },\n            \"deprecated\": {\n                \"state\": \"DEPRECATED\",\n                \"replacement\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-7-wheezy-v20140318\"\n            },\n            \"status\": \"READY\",\n            \"archiveSizeBytes\": \"341857472\",\n            \"diskSizeGb\": \"10\"\n        },\n        {\n            \"kind\": \"compute#image\",\n            \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-7-wheezy-v20140318\",\n            \"id\": \"17164003659829548087\",\n            \"creationTimestamp\": \"2014-03-19T15:00:34.317-07:00\",\n            \"name\": \"debian-7-wheezy-v20140318\",\n            \"description\": \"Debian GNU/Linux 7.4 (wheezy) amd64 built on 2014-03-18\",\n            \"sourceType\": \"RAW\",\n            \"rawDisk\": {\n                \"source\": \"\",\n                \"containerType\": \"TAR\"\n            },\n            \"deprecated\": {\n                \"state\": \"DEPRECATED\",\n                \"replacement\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-7-wheezy-v20140408\"\n            },\n            \"status\": \"READY\",\n            \"archiveSizeBytes\": \"357365652\",\n            \"diskSizeGb\": \"10\"\n        },\n        {\n            \"kind\": \"compute#image\",\n            \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-7-wheezy-v20140408\",\n            \"id\": \"5009074516965108296\",\n            \"creationTimestamp\": \"2014-04-09T10:32:46.862-07:00\",\n            \"name\": \"debian-7-wheezy-v20140408\",\n            \"description\": \"Debian GNU/Linux 7.4 (wheezy) amd64 built on 2014-04-08\",\n            \"sourceType\": \"RAW\",\n            \"rawDisk\": {\n                \"source\": \"\",\n                \"containerType\": \"TAR\"\n            },\n            \"deprecated\": {\n                \"state\": \"DEPRECATED\",\n                \"replacement\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-7-wheezy-v20140415\"\n            },\n            \"status\": \"READY\",\n            \"archiveSizeBytes\": \"387525228\",\n            \"diskSizeGb\": \"10\"\n        },\n        {\n            \"kind\": \"compute#image\",\n            \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-7-wheezy-v20140415\",\n            \"id\": \"17362901286054305778\",\n            \"creationTimestamp\": \"2014-04-22T12:05:19.303-07:00\",\n            \"name\": \"debian-7-wheezy-v20140415\",\n            \"description\": \"Debian GNU/Linux 7.4 (wheezy) amd64 built on 2014-04-15\",\n            \"sourceType\": \"RAW\",\n            \"rawDisk\": {\n                \"source\": \"\",\n                \"containerType\": \"TAR\"\n            },\n            \"deprecated\": {\n                \"state\": \"DEPRECATED\",\n                \"replacement\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-7-wheezy-v20140522\"\n            },\n            \"status\": \"READY\",\n            \"archiveSizeBytes\": \"1151530332\",\n            \"diskSizeGb\": \"10\"\n        },\n        {\n            \"kind\": \"compute#image\",\n            \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-7-wheezy-v20140522\",\n            \"id\": \"5741466168076626639\",\n            \"creationTimestamp\": \"2014-06-03T10:22:05.775-07:00\",\n            \"name\": \"debian-7-wheezy-v20140522\",\n            \"description\": \"Debian GNU/Linux 7.5 (wheezy) amd64 built on 2014-05-22\",\n            \"sourceType\": \"RAW\",\n            \"rawDisk\": {\n                \"source\": \"\",\n                \"containerType\": \"TAR\"\n            },\n            \"deprecated\": {\n                \"state\": \"DEPRECATED\",\n                \"replacement\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-7-wheezy-v20140606\"\n            },\n            \"status\": \"READY\",\n            \"archiveSizeBytes\": \"1129290498\",\n            \"diskSizeGb\": \"10\"\n        },\n        {\n            \"kind\": \"compute#image\",\n            \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-7-wheezy-v20140605\",\n            \"id\": \"15036511115619902874\",\n            \"creationTimestamp\": \"2014-06-05T11:10:23.037-07:00\",\n            \"name\": \"debian-7-wheezy-v20140605\",\n            \"description\": \"Debian GNU/Linux 7.5 (wheezy) amd64 built on 2014-06-05\",\n            \"sourceType\": \"RAW\",\n            \"rawDisk\": {\n                \"source\": \"\",\n                \"containerType\": \"TAR\"\n            },\n            \"deprecated\": {\n                \"state\": \"DEPRECATED\",\n                \"replacement\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-7-wheezy-v20140606\"\n            },\n            \"status\": \"READY\",\n            \"archiveSizeBytes\": \"1064425338\",\n            \"diskSizeGb\": \"10\"\n        },\n        {\n            \"kind\": \"compute#image\",\n            \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-7-wheezy-v20140606\",\n            \"id\": \"16280724435269635469\",\n            \"creationTimestamp\": \"2014-06-06T13:16:42.897-07:00\",\n            \"name\": \"debian-7-wheezy-v20140606\",\n            \"description\": \"Debian GNU/Linux 7.5 (wheezy) amd64 built on 2014-06-06\",\n            \"sourceType\": \"RAW\",\n            \"rawDisk\": {\n                \"source\": \"\",\n                \"containerType\": \"TAR\"\n            },\n            \"deprecated\": {\n                \"state\": \"DEPRECATED\",\n                \"replacement\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-7-wheezy-v20140619\"\n            },\n            \"status\": \"READY\",\n            \"archiveSizeBytes\": \"1108438332\",\n            \"diskSizeGb\": \"10\"\n        },\n        {\n            \"kind\": \"compute#image\",\n            \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-7-wheezy-v20140619\",\n            \"id\": \"15990799122418306096\",\n            \"creationTimestamp\": \"2014-06-24T13:28:42.697-07:00\",\n            \"name\": \"debian-7-wheezy-v20140619\",\n            \"description\": \"Debian GNU/Linux 7.5 (wheezy) amd64 built on 2014-06-19\",\n            \"sourceType\": \"RAW\",\n            \"rawDisk\": {\n                \"source\": \"\",\n                \"containerType\": \"TAR\"\n            },\n            \"deprecated\": {\n                \"state\": \"DEPRECATED\",\n                \"replacement\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-7-wheezy-v20140718\"\n            },\n            \"status\": \"READY\",\n            \"archiveSizeBytes\": \"1158839577\",\n            \"diskSizeGb\": \"10\"\n        },\n        {\n            \"kind\": \"compute#image\",\n            \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-7-wheezy-v20140718\",\n            \"id\": \"11535450626613878896\",\n            \"creationTimestamp\": \"2014-07-24T09:06:16.694-07:00\",\n            \"name\": \"debian-7-wheezy-v20140718\",\n            \"description\": \"Debian GNU/Linux 7.6 (wheezy) amd64 built on 2014-07-18\",\n            \"sourceType\": \"RAW\",\n            \"rawDisk\": {\n                \"source\": \"\",\n                \"containerType\": \"TAR\"\n            },\n            \"status\": \"READY\",\n            \"archiveSizeBytes\": \"1195066695\",\n            \"diskSizeGb\": \"10\"\n        }\n    ]\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/image_list_empty.json",
    "content": "{\n   \"kind\": \"compute#imageList\",\n   \"id\": \"projects/debian-cloud/global/images\",\n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images\",\n   \"items\": [ ]\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/image_list_multiple_page_1.json",
    "content": "{\n   \"kind\": \"compute#imageList\",\n   \"id\": \"projects/centos-cloud/global/images\",\n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/centos-cloud/global/images\",\n   \"nextPageToken\": \"CgVJTUFHRRIbZ29vZ2xlLmNlbnRvcy02LTItdjIwMTIwNjIx\",\n   \"items\": [\n      {\n         \"kind\": \"compute#image\",\n         \"id\": \"12941197498378735318\",\n         \"creationTimestamp\": \"2012-07-16T15:16:13.468-07:00\",\n         \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/centos-cloud/global/images/centos-6-2-v20120326\",\n         \"name\": \"centos-6-2-v20120326\",\n         \"description\": \"DEPRECATED. CentOS 6.2 image; Created Mon, 26 Mar 2012 21:19:09 +0000\",\n         \"sourceType\": \"RAW\",\n         \"deprecated\": {\n            \"state\": \"DELETED\",\n            \"replacement\": \"https://www.googleapis.com/compute/v1/projects/centos-cloud/global/images/centos-6-v20130104\"\n         },\n         \"rawDisk\": {\n            \"source\": \"\",\n            \"containerType\": \"TAR\"\n         }\n      },\n      {\n         \"kind\": \"compute#image\",\n         \"id\": \"12894486577628239762\",\n         \"creationTimestamp\": \"2012-05-21T13:15:37.215-07:00\",\n         \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/centos-cloud/global/images/centos-6-2-v20120503\",\n         \"name\": \"centos-6-2-v20120503\",\n         \"description\": \"CentOS 6.2; Created Wed, 09 May 2012 11:55:54 +0000\",\n         \"sourceType\": \"RAW\",\n         \"rawDisk\": {\n            \"source\": \"\",\n            \"containerType\": \"TAR\"\n         }\n      },\n      {\n         \"kind\": \"compute#image\",\n         \"id\": \"12917726455664967299\",\n         \"creationTimestamp\": \"2012-06-18T11:05:30.664-07:00\",\n         \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/centos-cloud/global/images/centos-6-2-v20120611\",\n         \"name\": \"centos-6-2-v20120611\",\n         \"description\": \"CentOS 6.2; Created Mon, 11 Jun 2012 13:15:44 +0000\",\n         \"sourceType\": \"RAW\",\n         \"deprecated\": {\n            \"state\": \"DEPRECATED\",\n            \"replacement\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-7-wheezy-20130509\"\n         },\n         \"rawDisk\": {\n            \"source\": \"\",\n            \"containerType\": \"TAR\"\n         }\n      }\n   ]\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/image_list_multiple_page_2.json",
    "content": "{\n   \"kind\": \"compute#imageList\",\n   \"id\": \"projects/centos-cloud/global/images\",\n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/centos-cloud/global/images\",\n   \"nextPageToken\": \"CgVJTUFHRRIbZ29vZ2xlLmdjZWwtMTAtMDQtdjIwMTIxMTA2\",\n   \"items\": [\n      {\n         \"kind\": \"compute#image\",\n         \"id\": \"12920641029336858796\",\n         \"creationTimestamp\": \"2012-06-21T22:59:56.392-07:00\",\n         \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/centos-cloud/global/images/centos-6-2-v20120621\",\n         \"name\": \"centos-6-2-v20120621\",\n         \"description\": \"CentOS 6.2; Created Thu, 21 Jun 2012 14:22:21 +0000\",\n         \"sourceType\": \"RAW\",\n         \"rawDisk\": {\n            \"source\": \"\",\n            \"containerType\": \"TAR\"\n         }\n      },\n      {\n         \"kind\": \"compute#image\",\n         \"id\": \"12994279803511049620\",\n         \"creationTimestamp\": \"2012-09-18T08:52:47.584-07:00\",\n         \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/centos-cloud/global/images/centos-6-v20120912\",\n         \"name\": \"centos-6-v20120912\",\n         \"description\": \"CentOS 6; Created Wed, 12 Sep 2012 00:00:00 +0000\",\n         \"sourceType\": \"RAW\",\n         \"rawDisk\": {\n            \"source\": \"\",\n            \"containerType\": \"TAR\"\n         }\n      },\n      {\n         \"kind\": \"compute#image\",\n         \"id\": \"13037720516378381209\",\n         \"creationTimestamp\": \"2012-11-09T11:40:41.079-08:00\",\n         \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/centos-cloud/global/images/centos-6-v20121106\",\n         \"name\": \"centos-6-v20121106\",\n         \"description\": \"SCSI-enabled CentOS 6; Created Tue, 06 Nov 2012 00:00:00 +0000\",\n         \"sourceType\": \"RAW\",\n         \"rawDisk\": {\n            \"source\": \"\",\n            \"containerType\": \"TAR\"\n         }\n      }\n   ]\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/image_list_single_page.json",
    "content": "{\n \"kind\": \"compute#imageList\",\n \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/centos-cloud/global/images\",\n \"id\": \"projects/centos-cloud/global/images\",\n \"items\": [\n  {\n\n   \"kind\": \"compute#image\",\n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/centos-cloud/global/images/centos-6-v20131120\",\n   \"id\": \"11748647391859510935\",\n   \"creationTimestamp\": \"2013-11-25T15:13:50.611-08:00\",\n   \"name\": \"centos-6-v20131120\",\n   \"description\": \"SCSI-enabled CentOS 6 built on 2013-11-20\",\n   \"sourceType\": \"RAW\",\n   \"rawDisk\": {\n    \"source\": \"\",\n    \"containerType\": \"TAR\"\n   },\n   \"deprecated\": {\n    \"state\": \"DEPRECATED\",\n    \"replacement\": \"https://content.googleapis.com/compute/v1/projects/centos-cloud/global/images/centos-6-v20140318\"\n   },\n   \"status\": \"READY\",\n   \"archiveSizeBytes\": \"269993565\",\n   \"diskSizeGb\": \"10\"\n  },\n  {\n\n   \"kind\": \"compute#image\",\n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/centos-cloud/global/images/centos-6-v20140318\",\n   \"id\": \"11743140967858608122\",\n   \"creationTimestamp\": \"2014-03-19T15:01:13.388-07:00\",\n   \"name\": \"centos-6-v20140318\",\n   \"description\": \"CentOS 6.5 x86_64 built on 2014-03-18\",\n   \"sourceType\": \"RAW\",\n   \"rawDisk\": {\n    \"source\": \"\",\n    \"containerType\": \"TAR\"\n   },\n   \"deprecated\": {\n    \"state\": \"DEPRECATED\",\n    \"replacement\": \"https://content.googleapis.com/compute/v1/projects/centos-cloud/global/images/centos-6-v20140408\"\n   },\n   \"status\": \"READY\",\n   \"archiveSizeBytes\": \"341230444\",\n   \"diskSizeGb\": \"10\"\n  },\n  {\n\n   \"kind\": \"compute#image\",\n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/centos-cloud/global/images/centos-6-v20140408\",\n   \"id\": \"18033188469723077298\",\n   \"creationTimestamp\": \"2014-04-09T10:31:57.518-07:00\",\n   \"name\": \"centos-6-v20140408\",\n   \"description\": \"CentOS 6.5 x86_64 built on 2014-04-08\",\n   \"sourceType\": \"RAW\",\n   \"rawDisk\": {\n    \"source\": \"\",\n    \"containerType\": \"TAR\"\n   },\n   \"deprecated\": {\n    \"state\": \"DEPRECATED\",\n    \"replacement\": \"https://content.googleapis.com/compute/v1/projects/centos-cloud/global/images/centos-6-v20140415\"\n   },\n   \"status\": \"READY\",\n   \"archiveSizeBytes\": \"342252847\",\n   \"diskSizeGb\": \"10\"\n  }\n ],\n \"nextPageToken\": \"CkcIjf6H7sqqwgI6PAoCGAEKAiAACgIYAgoHIJT6lOrjDQoCGAYKFCoSY2VudG9zLTYtdjIwMTQwNDA4CgsgsrWOzOirsKH6AQ==\"\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/instance_add_access_config.json",
    "content": "POST https://www.googleapis.com/compute/v1/projects/party-gce/zones/us-central1-a/instances/test-instance/addAccessConfig?network_interface=nic0&key={YOUR_API_KEY}\n\nContent-Type:  application/json\nAuthorization:  Bearer ya29.AHES6ZRyNKVHwnMPUvZitAuA8mR8b0lcWh1bMI5UQ5bgsJ4j\nX-JavaScript-User-Agent:  Google APIs Explorer\n\n{\n\"name\": \"config1\",\n\"natIP\": \"10.0.1.1\",\n\"type\": \"ONE_TO_ONE_NAT\"\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/instance_attach_disk.json",
    "content": "{\n  \"type\": \"PERSISTENT\",\n  \"mode\": \"READ_WRITE\",\n  \"deviceName\": \"test\",\n  \"source\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/disks/test\",\n  \"boot\": true,\n  \"autoDelete\": true,\n  \"initializeParams\": {\n    \"diskName\": \"test\",\n    \"sourceImage\": \"https://www.googleapis.com/compute/v1/projects/party/global/images/test\",\n    \"diskSizeGb\": 100,\n    \"diskType\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/diskTypes/pd-standard\"\n  },\n  \"licenses\": [\n    \"https://www.googleapis.com/compute/v1/projects/suse-cloud/global/licenses/sles-12\"\n  ],\n  \"interface\": \"NVME\"\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/instance_get.json",
    "content": "{\n   \"kind\": \"compute#instance\",\n   \"id\": \"13051190678907570425\",\n   \"description\": \"desc\",\n   \"creationTimestamp\": \"2012-11-25T23:48:20.758\",\n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/instances/test-0\",\n   \"name\": \"test-0\",\n   \"machineType\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/machineTypes/n1-standard-1\",\n   \"status\": \"RUNNING\",\n   \"canIpForward\": true,\n   \"zone\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a\",\n   \"networkInterfaces\": [\n      {\n         \"kind\": \"compute#instanceNetworkInterface\",\n         \"name\": \"nic0\",\n         \"networkIP\": \"10.240.121.115\",\n         \"network\": \"https://www.googleapis.com/compute/v1/projects/party/global/networks/default\"\n      }\n   ],\n   \"disks\": [\n      {\n         \"kind\": \"compute#instanceDisk\",\n         \"type\": \"PERSISTENT\",\n         \"mode\": \"READ_WRITE\",\n         \"deviceName\": \"test\",\n         \"source\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/disks/test\",\n         \"index\": 0,\n         \"boot\": true,\n         \"initializeParams\": {\n            \"diskName\": \"test\",\n            \"sourceImage\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-7-wheezy-v20140718\",\n            \"diskSizeGb\": \"100\",\n            \"diskType\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/diskTypes/pd-standard\"\n         },\n         \"licenses\": [\n            \"https://www.googleapis.com/compute/v1/projects/suse-cloud/global/licenses/sles-12\"\n         ],\n         \"interface\": \"NVME\"\n      }\n   ],\n   \"serviceAccounts\": [\n      {\n         \"kind\": \"compute#serviceAccount\",\n         \"email\": \"default\",\n         \"scopes\": [\n            \"myscope\"\n         ]\n      }\n   ],\n   \"metadata\": {\n      \"items\": [\n         {\n            \"key\": \"aKey\",\n            \"value\": \"aValue\"\n         },\n         {\n            \"key\": \"jclouds-delete-boot-disk\",\n            \"value\": \"true\"\n         }\n      ],\n      \"fingerprint\": \"efgh\"\n   },\n   \"tags\": {\n      \"items\": [\n         \"aTag\",\n         \"Group-port-42\"\n      ],\n      \"fingerprint\": \"abcd\"\n   },\n    \"scheduling\": {\n        \"onHostMaintenance\": \"MIGRATE\",\n        \"automaticRestart\": false,\n        \"preemptible\": false\n   }\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/instance_insert.json",
    "content": "{\n  \"machineType\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/machineTypes/n1-standard-1\",\n  \"name\": \"test-1\",\n  \"networkInterfaces\": [\n    {\n      \"network\": \"https://www.googleapis.com/compute/v1/projects/party/global/networks/default\",\n      \"accessConfigs\": [\n        {\n          \"type\": \"ONE_TO_ONE_NAT\"\n        }\n      ]\n    }\n  ],\n  \"disks\": [\n    {\n      \"type\": \"PERSISTENT\",\n      \"source\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/disks/test\",\n      \"boot\": true,\n      \"autoDelete\": false\n    }\n  ],\n  \"description\": \"desc\",\n  \"tags\": {\n    \"items\": []\n  },\n  \"metadata\": {\n    \"items\": [\n      {\n        \"key\": \"aKey\",\n        \"value\": \"aValue\"\n      }\n    ]\n  }\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/instance_insert_2.json",
    "content": "{\n  \"machineType\": \"%s\",\n  \"name\": \"test-1\",\n  \"networkInterfaces\": [\n    {\n      \"network\": \"https://www.googleapis.com/compute/v1/projects/party/networks/default\",\n      \"accessConfigs\": [\n        {\n          \"type\": \"ONE_TO_ONE_NAT\"\n        }\n      ]\n    }\n  ],\n  \"disks\": [\n    {\n      \"type\": \"PERSISTENT\",\n      \"initializeParams\": {\n        \"sourceImage\": \"%s\"\n      },\n      \"boot\": true,\n      \"autoDelete\": true\n    }\n  ],\n  \"description\": \"test\",\n  \"tags\": {\n    \"items\": [\n      \"aTag\",\n      \"jclouds-test-65f\"\n    ]\n  },\n  \"metadata\": {\n    \"items\": [\n      {\n        \"key\": \"jclouds-group\",\n        \"value\": \"test\"\n      }\n    ]\n  },\n  \"scheduling\": {\n    \"onHostMaintenance\": \"MIGRATE\",\n    \"automaticRestart\": true,\n    \"preemptible\": false\n  }\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/instance_insert_full.json",
    "content": "{\n  \"name\": \"test-1\",\n  \"machineType\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/machineTypes/n1-standard-1\",\n  \"canIpForward\": true,\n  \"networkInterfaces\": [\n    {\n      \"network\": \"https://www.googleapis.com/compute/v1/projects/party/global/networks/default\",\n      \"accessConfigs\": [\n        {\n          \"type\": \"ONE_TO_ONE_NAT\"\n        }\n      ]\n    }\n  ],\n  \"disks\": [\n    {\n      \"type\": \"PERSISTENT\",\n      \"source\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/disks/test\",\n      \"boot\": true,\n      \"autoDelete\": false\n    }\n  ],\n  \"description\": \"desc\",\n  \"tags\": {\n    \"items\": []\n  },\n  \"metadata\": {\n    \"items\": [\n      {\n        \"key\": \"aKey\",\n        \"value\": \"aValue\"\n      }\n    ]\n  },\n  \"serviceAccounts\": [\n    {\n      \"email\": \"default\",\n      \"scopes\": [\n        \"https://www.googleapis.com/auth/compute\"\n      ]\n    }\n  ],\n  \"scheduling\": {\n    \"onHostMaintenance\": \"MIGRATE\",\n    \"automaticRestart\": true,\n    \"preemptible\": false\n  }\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/instance_insert_no_ip.json",
    "content": "{\n  \"machineType\": \"%s\",\n  \"name\": \"test-1\",\n  \"networkInterfaces\": [\n    {\n      \"network\": \"https://www.googleapis.com/compute/v1/projects/party/global/networks/mynetwork\",\n      \"subnetwork\": \"https://www.googleapis.com/compute/v1/projects/party/regions/someregion/subnetworks/jclouds-test\",\n      \"accessConfigs\": []\n    }\n  ],\n  \"disks\": [\n    {\n      \"type\": \"PERSISTENT\",\n      \"initializeParams\": {\n        \"sourceImage\": \"%s\",\n        \"diskType\": \"https://content.googleapis.com/compute/v1/projects/party/zones/us-central1-a/diskTypes/pd-ssd\"\n      },\n      \"boot\": true,\n      \"autoDelete\": true\n    }\n  ],\n  \"description\": \"test\",\n  \"tags\": {\n    \"items\": [\n      \"aTag\",\n      \"jclouds-test-65f\"\n    ]\n  },\n  \"metadata\": {\n    \"items\": [\n      {\n        \"key\": \"jclouds-group\",\n        \"value\": \"test\"\n      }\n    ]\n  },\n  \"scheduling\": {\n    \"onHostMaintenance\": \"MIGRATE\",\n    \"automaticRestart\": true,\n    \"preemptible\": false\n  }\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/instance_insert_simple.json",
    "content": "{\n  \"name\": \"test-1\",\n  \"machineType\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/machineTypes/n1-standard-1\",\n  \"networkInterfaces\": [\n    {\n      \"network\": \"https://www.googleapis.com/compute/v1/projects/party/global/networks/default\",\n      \"accessConfigs\": [\n        {\n          \"type\": \"ONE_TO_ONE_NAT\"\n        }\n      ]\n    }\n  ],\n  \"disks\": [\n    {\n      \"type\": \"PERSISTENT\",\n      \"initializeParams\": {\n        \"sourceImage\": \"https://www.googleapis.com/compute/v1/projects/party/global/images/centos-6-2-v20120326\"\n      },\n      \"boot\": true,\n      \"autoDelete\": true\n    }\n  ],\n  \"tags\": {\n    \"items\": []\n  },\n  \"metadata\": {\n    \"items\": []\n  }\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/instance_insert_ssd.json",
    "content": "{\n  \"machineType\": \"%s\",\n  \"name\": \"test-1\",\n  \"networkInterfaces\": [\n    {\n      \"network\": \"https://www.googleapis.com/compute/v1/projects/party/networks/default\",\n      \"accessConfigs\": [\n        {\n          \"type\": \"ONE_TO_ONE_NAT\"\n        }\n      ]\n    }\n  ],\n  \"disks\": [\n    {\n      \"type\": \"PERSISTENT\",\n      \"initializeParams\": {\n        \"sourceImage\": \"%s\",\n        \"diskType\": \"https://content.googleapis.com/compute/v1/projects/party/zones/us-central1-a/diskTypes/pd-ssd\"\n      },\n      \"boot\": true,\n      \"autoDelete\": true\n    }\n  ],\n  \"description\": \"test\",\n  \"tags\": {\n    \"items\": [\n      \"aTag\",\n      \"jclouds-test-65f\"\n    ]\n  },\n  \"metadata\": {\n    \"items\": [\n      {\n        \"key\": \"jclouds-group\",\n        \"value\": \"test\"\n      }\n    ]\n  },\n  \"scheduling\": {\n    \"onHostMaintenance\": \"MIGRATE\",\n    \"automaticRestart\": true,\n    \"preemptible\": false\n  }\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/instance_insert_subnet.json",
    "content": "{\n  \"machineType\": \"%s\",\n  \"name\": \"test-1\",\n  \"networkInterfaces\": [\n    {\n      \"network\": \"https://www.googleapis.com/compute/v1/projects/party/global/networks/mynetwork\",\n      \"subnetwork\": \"https://www.googleapis.com/compute/v1/projects/party/regions/someregion/subnetworks/jclouds-test\",\n      \"accessConfigs\": [\n        {\n          \"type\": \"ONE_TO_ONE_NAT\"\n        }\n      ]\n    }\n  ],\n  \"disks\": [\n    {\n      \"type\": \"PERSISTENT\",\n      \"initializeParams\": {\n        \"sourceImage\": \"%s\",\n        \"diskType\": \"https://content.googleapis.com/compute/v1/projects/party/zones/us-central1-a/diskTypes/pd-ssd\"\n      },\n      \"boot\": true,\n      \"autoDelete\": true\n    }\n  ],\n  \"description\": \"test\",\n  \"tags\": {\n    \"items\": [\n      \"aTag\",\n      \"jclouds-test-65f\"\n    ]\n  },\n  \"metadata\": {\n    \"items\": [\n      {\n        \"key\": \"jclouds-group\",\n        \"value\": \"test\"\n      }\n    ]\n  },\n  \"scheduling\": {\n    \"onHostMaintenance\": \"MIGRATE\",\n    \"automaticRestart\": true,\n    \"preemptible\": false\n  }\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/instance_list.json",
    "content": "{\n  \"kind\": \"compute#instanceList\",\n  \"id\": \"projects/party/zones/us-central1-a/instances\",\n  \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/instances\",\n  \"items\": [\n    {\n      \"kind\": \"compute#instance\",\n      \"id\": \"13051190678907570425\",\n      \"description\": \"desc\",\n      \"creationTimestamp\": \"2012-11-25T23:48:20.758\",\n      \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/instances/test-0\",\n      \"name\": \"test-0\",\n      \"machineType\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/machineTypes/n1-standard-1\",\n      \"status\": \"RUNNING\",\n      \"canIpForward\": true,\n      \"zone\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a\",\n      \"networkInterfaces\": [\n        {\n          \"kind\": \"compute#instanceNetworkInterface\",\n          \"name\": \"nic0\",\n          \"networkIP\": \"10.240.121.115\",\n          \"network\": \"https://www.googleapis.com/compute/v1/projects/party/global/networks/default\"\n        }\n      ],\n      \"disks\": [\n        {\n          \"kind\": \"compute#instanceDisk\",\n          \"type\": \"PERSISTENT\",\n          \"mode\": \"READ_WRITE\",\n          \"deviceName\": \"test\",\n          \"source\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/disks/test\",\n          \"index\": 0,\n          \"boot\": true,\n          \"initializeParams\": {\n            \"diskName\": \"test\",\n            \"sourceImage\": \"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-7-wheezy-v20140718\",\n            \"diskSizeGb\": \"100\",\n            \"diskType\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/diskTypes/pd-standard\"\n          },\n          \"licenses\": [\n            \"https://www.googleapis.com/compute/v1/projects/suse-cloud/global/licenses/sles-12\"\n          ],\n          \"interface\": \"NVME\"\n        }\n      ],\n      \"serviceAccounts\": [\n        {\n          \"kind\": \"compute#serviceAccount\",\n          \"email\": \"default\",\n          \"scopes\": [\n            \"myscope\"\n          ]\n        }\n      ],\n      \"metadata\": {\n        \"items\": [\n          {\n            \"key\": \"aKey\",\n            \"value\": \"aValue\"\n          },\n          {\n            \"key\": \"jclouds-delete-boot-disk\",\n            \"value\": \"true\"\n          }\n        ],\n        \"fingerprint\": \"efgh\"\n      },\n      \"tags\": {\n        \"items\": [\n          \"aTag\",\n          \"Group-port-42\"\n        ],\n        \"fingerprint\": \"abcd\"\n      },\n      \"scheduling\": {\n        \"onHostMaintenance\": \"MIGRATE\",\n        \"automaticRestart\": false,\n        \"preemptible\": false\n      }\n    }\n  ]\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/instance_list_central1b_empty.json",
    "content": "{\n   \"kind\": \"compute#instanceList\",\n   \"id\": \"projects/party/zones/us-central1-b/instances\",\n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-b/instances\",\n   \"items\": [ ]\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/instance_serial_port.json",
    "content": "{\n  \"kind\": \"compute#serialPortOutput\",\n  \"contents\": \"console output\",\n  \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/instances/test-instance/serialPort\"\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/instance_serial_port_4_windows.json",
    "content": "{\n  \"kind\": \"compute#serialPortOutput\",\n  \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/instances/test-instance/serialPort\",\n  \"contents\": \"{\\\"ready\\\":true,\\\"version\\\":\\\"Microsoft Windows NT 6.1.7601 Service Pack 1\\\"}\\n{\\\"encryptedPassword\\\":\\\"uiHDEhxyvj6lF5GalHh9TsMZb4bG6Y9qGmFb9S3XI29yvVsDCLdp4IbUg21MncHcaxP0rFu0kyjxlEXDs8y4L1KOhy6iyB42Lh+vZ4XIMjmvU4rZrjsBZ5TxQo9hL0lBW7o3FRM\\\\/UIXCeRk39ObUl2AjDmQ0mcw1byJI5v9KVJnNMaHdRCy\\\\/kvN6bx3qqjIhIMu0JExp4UVkAX2Mxb9b+c4o2DiZF5pY6ZfbuEmjSbvGRJXyswkOJ4jTZl+7e6+SZfEal8HJyRfZKiqTjrz+DLjYSlXrfIRqlvKeAFGOJq6IRojNWiTOOh8Zorc0iHDTIkf+MY0scfbBUo5m30Bf4w==\\\",\\\"exponent\\\":\\\"AQAB\\\",\\\"modulus\\\":\\\"0tiKdO2JmBHss26jnrSAwb583KG\\\\/ZIw5JwwMPXrCVsFAPwY1OV3RlT1Hp4Xvpibr7rvJbOC+f\\\\/Gd0cBrK5pccQfccB+OHKpbBof473zEfRbdtFwPn10RfAFj\\\\/xikW0r\\\\/XxgG\\\\/c8tz9bmALBStGqmwOVOLRHxjwgtGu4poeuwmFfG6TuwgCadxpllW74mviFd4LZVSuCSni5YJnBM2HSJ8NP6g1fqI17KDXt2XO\\\\/7kSItubmMk+HGEXdH4qiugHYewaIf1o4XSQROC8xlRl7t\\\\/RaD4U58hKYkVwg0Ir7WzYzAVpG2UR4Co\\\\/GDG9Hct7HOYekDqVQ+sSZbwzajnVunkw==\\\",\\\"passwordFound\\\":true,\\\"userName\\\":\\\"example-user\\\"}\\n\"\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/instance_set_metadata.json",
    "content": "{\"fingerprint\":\"efgh\",\"items\":[{\"key\":\"foo\",\"value\":\"bar\"}]}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/instance_set_tags.json",
    "content": "{\n    \"items\": [ \"foo\", \"bar\" ],\n    \"fingerprint\": \"efgh\"\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/license_get.json",
    "content": "{\n \"kind\": \"compute#license\",\n \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/suse-cloud/global/licenses/sles-12\",\n \"name\": \"sles-12\",\n \"chargesUseFee\": true\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/list_empty.json",
    "content": "{\n \"kind\": \"compute#forwardingRuleList\",\n \"id\": \"projects/jclouds-dev/regions/asia-east1/forwardingRules\",\n \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/jclouds-dev/regions/asia-east1/forwardingRules\"\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/logback-test.xml",
    "content": "<?xml version=\"1.0\"?>\n<configuration scan=\"false\">\n    <appender name=\"FILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds.log</file>\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n    <appender name=\"WIREFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds-wire.log</file>\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n    <appender name=\"COMPUTEFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds-compute.log</file>\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <logger name=\"org.jclouds\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"FILE\" />\n    </logger>\n    <logger name=\"jclouds.compute\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"COMPUTEFILE\" />\n    </logger>\n    <logger name=\"jclouds.wire\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n    <logger name=\"jclouds.headers\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n\n    <root>\n        <level value=\"INFO\" />\n    </root>\n</configuration>\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/machinetype.json",
    "content": "{\n   \"kind\": \"compute#machineType\",\n   \"id\": \"12907738072351752276\",\n   \"creationTimestamp\": \"2012-06-07T20:48:14.670\",\n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/machineTypes/n1-standard-1\",\n   \"name\": \"n1-standard-1\",\n   \"description\": \"1 vCPU, 3.75 GB RAM, and a 10 GB ephemeral root disk\",\n   \"guestCpus\": 1,\n   \"memoryMb\": 3840,\n   \"scratchDisks\": [\n      {\n         \"diskGb\": 1770\n      },\n      {\n         \"diskGb\": 1770\n      }\n   ],\n   \"maximumPersistentDisks\": 16,\n   \"maximumPersistentDisksSizeGb\": \"128\",\n   \"zone\": \"us-central1-a\"\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/machinetype_list.json",
    "content": "{\n   \"kind\": \"compute#machineTypeList\",\n   \"id\": \"projects/party/machineTypes\",\n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/machineTypes\",\n   \"items\": [\n       {\n           \"kind\": \"compute#machineType\",\n           \"id\": \"4618642685664990776\",\n           \"creationTimestamp\": \"2013-04-25T13:32:49.088-07:00\",\n           \"name\": \"f1-micro\",\n           \"description\": \"1 vCPU (shared physical core) and 0.6 GB RAM\",\n           \"guestCpus\": 1,\n           \"memoryMb\": 614,\n           \"maximumPersistentDisks\": 4,\n           \"maximumPersistentDisksSizeGb\": \"3072\",\n           \"zone\": \"us-central1-a\",\n           \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/machineTypes/f1-micro\"\n       },\n       {\n         \"kind\": \"compute#machineType\",\n         \"id\": \"12907738072351752276\",\n         \"creationTimestamp\": \"2012-06-07T20:48:14.670\",\n         \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/machineTypes/n1-standard-1\",\n         \"name\": \"n1-standard-1\",\n         \"description\": \"1 vCPU, 3.75 GB RAM, and a 10 GB ephemeral root disk\",\n         \"guestCpus\": 1,\n         \"memoryMb\": 3840,\n         \"maximumPersistentDisks\": 16,\n         \"maximumPersistentDisksSizeGb\": \"128\",\n         \"zone\": \"us-central1-a\"\n      },\n      {\n         \"kind\": \"compute#machineType\",\n         \"id\": \"12908560709887590691\",\n         \"creationTimestamp\": \"2012-06-07T20:51:19.936\",\n         \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/machineTypes/n1-standard-8-d\",\n         \"name\": \"n1-standard-8-d\",\n         \"description\": \"8 vCPUs, 30 GB RAM, a 10 GB ephemeral root disk, and 2 extra 1770 GB ephemeral disks\",\n         \"guestCpus\": 8,\n         \"memoryMb\": 30720,\n         \"scratchDisks\": [\n            {\n               \"diskGb\": 1770\n            },\n            {\n               \"diskGb\": 1770\n            }\n         ],\n         \"maximumPersistentDisks\": 16,\n         \"maximumPersistentDisksSizeGb\": \"1024\",\n         \"zone\": \"us-central1-a\"\n      }\n   ]\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/metadata.json",
    "content": "{\"fingerprint\":\"efgh\",\"items\":[{\"key\":\"propA\",\"value\":\"valueA\"},{\"key\":\"propB\",\"value\":\"valueB\"}]}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/network_get.json",
    "content": "{\n   \"kind\": \"compute#network\",\n   \"id\": \"13024414170909937976\",\n   \"creationTimestamp\": \"2012-10-24T20:13:19.967\",\n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/networks/jclouds-test\",\n   \"name\": \"jclouds-test\",\n   \"description\": \"A custom network for the project\",\n   \"IPv4Range\": \"10.0.0.0/8\",\n   \"gatewayIPv4\": \"10.0.0.1\",\n   \"subnetworks\": []\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/network_get_default.json",
    "content": "{\n   \"kind\": \"compute#network\",\n   \"id\": \"13024414170909937976\",\n   \"creationTimestamp\": \"2012-10-24T20:13:19.967\",\n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/networks/default\",\n   \"name\": \"default\",\n   \"description\": \"Default network for the project\",\n   \"IPv4Range\": \"10.0.0.0/8\",\n   \"gatewayIPv4\": \"10.0.0.1\"\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/network_insert.json",
    "content": "{\"name\":\"test-network\",\"IPv4Range\":\"10.0.0.0/8\"}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/network_insert_custom.json",
    "content": "{\"autoCreateSubnetworks\":false,\"name\":\"test-network\"}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/network_list.json",
    "content": "{\n   \"kind\": \"compute#networkList\",\n   \"id\": \"projects/party/networks\",\n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/networks\",\n   \"items\": [\n      {\n\n         \"kind\": \"compute#network\",\n         \"id\": \"13024414170909937976\",\n         \"creationTimestamp\": \"2012-10-24T20:13:19.967\",\n         \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/networks/jclouds-test\",\n         \"name\": \"jclouds-test\",\n         \"description\": \"A custom network for the project\",\n         \"IPv4Range\": \"10.0.0.0/8\",\n         \"gatewayIPv4\": \"10.0.0.1\"\n      }\n   ]\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/operation.json",
    "content": "{\n  \"kind\": \"compute#operation\",\n  \"id\": \"13053095055850848306\",\n  \"creationTimestamp\": \"2013-07-26T13:57:20.204-07:00\",\n  \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/operations/operation-1354084865060\",\n  \"name\": \"operation-1354084865060\",\n  \"targetLink\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/instances/test-1\",\n  \"targetId\": \"13053094017547040099\",\n  \"status\": \"DONE\",\n  \"user\": \"user@developer.gserviceaccount.com\",\n  \"progress\": 100,\n  \"insertTime\": \"2012-11-28T06:41:05.060\",\n  \"startTime\": \"2012-11-28T06:41:05.142\",\n  \"endTime\": \"2012-11-28T06:41:06.142\",\n  \"operationType\": \"insert\",\n  \"error\": {\n    \"errors\": [\n      {\n        \"code\": \"INVALID_FIELD_VALUE\",\n        \"message\": \"Invalid value for field 'resource.urlMaps': 'projects/party/global/urlMaps/target-http-proxy-api-live-test-url-map-2'. Resource was not found.\"\n      }\n    ]\n  },\n  \"warnings\": [\n    {\n      \"code\": \"NO_RESULTS_ON_PAGE\",\n      \"message\": \"This is an example warning\",\n      \"data\": [\n        {\n          \"key\": \"scope\",\n          \"value\": \"There are no results for scope 'zones/asia-east1-b' on this page.\"\n        }\n      ]\n    }\n  ],\n  \"httpErrorStatusCode\": 400,\n  \"httpErrorMessage\": \"BAD REQUEST\",\n  \"region\": \"https://www.googleapis.com/compute/v1/projects/party/regions/us-central1\",\n  \"zone\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a\"\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/operation_error.json",
    "content": "{\n   \"kind\": \"compute#operation\",\n   \"id\": \"13053095055850848306\",\n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/operations/operation-1354084865060\",\n   \"name\": \"operation-1354084865060\",\n   \"targetLink\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/instances/test-1\",\n   \"targetId\": \"13053094017547040099\",\n   \"status\": \"DONE\",\n   \"user\": \"user@developer.gserviceaccount.com\",\n   \"progress\": 100,\n   \"insertTime\": \"2012-11-28T06:41:05.060\",\n   \"startTime\": \"2012-11-28T06:41:05.142\",\n   \"httpErrorStatusCode\": 400,\n   \"httpErrorMessage\": \"BAD REQUEST\",\n   \"error\": {\n      \"errors\": [\n         {\n            \"code\": \"RESOURCE_ALREADY_EXISTS\",\n            \"message\": \"The resource 'projects/party/zones/us-central1-a/instances/test-1' already exists\"\n         }\n      ]\n   },\n   \"operationType\": \"insert\",\n   \"region\": \"https://www.googleapis.com/compute/v1/projects/party/regions/us-central1\",\n   \"zone\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a\"\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/operation_list.json",
    "content": "{\n   \"kind\": \"compute#operationList\",\n   \"id\": \"projects/party/operations\",\n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/operations\",\n   \"items\": [\n      {\n         \"kind\": \"compute#operation\",\n         \"id\": \"13053095055850848306\",\n         \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/operations/operation-1354084865060\",\n         \"name\": \"operation-1354084865060\",\n         \"targetLink\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/instances/test-1\",\n         \"targetId\": \"13053094017547040099\",\n         \"status\": \"DONE\",\n         \"user\": \"user@developer.gserviceaccount.com\",\n         \"progress\": 100,\n         \"insertTime\": \"2012-11-28T06:41:05.060\",\n         \"startTime\": \"2012-11-28T06:41:05.142\",\n         \"endTime\": \"2012-11-28T06:41:06.142\",\n         \"operationType\": \"insert\",\n         \"region\": \"https://www.googleapis.com/compute/v1/projects/party/regions/us-central1\",\n         \"zone\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a\"\n      }\n   ]\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/project.json",
    "content": "{\n   \"kind\": \"compute#project\",\n   \"id\": \"13024414184846275913\",\n   \"creationTimestamp\": \"2012-10-24T20:13:16.252\",\n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/761326798069\",\n   \"name\": \"party\",\n   \"description\": \"\",\n   \"commonInstanceMetadata\": {\n      \"kind\": \"compute#metadata\",\n      \"items\": [\n         {\n            \"key\": \"propA\",\n            \"value\": \"valueA\"\n         },\n         {\n            \"key\": \"propB\",\n            \"value\": \"valueB\"\n         }\n      ],\n       \"fingerprint\": \"efgh\"\n   },\n   \"quotas\": [\n      {\n         \"metric\": \"INSTANCES\",\n         \"usage\": 0,\n         \"limit\": 8\n      },\n      {\n         \"metric\": \"CPUS\",\n         \"usage\": 0,\n         \"limit\": 8\n      },\n      {\n         \"metric\": \"EPHEMERAL_ADDRESSES\",\n         \"usage\": 0,\n         \"limit\": 8\n      },\n      {\n         \"metric\": \"DISKS\",\n         \"usage\": 0,\n         \"limit\": 8\n      },\n      {\n         \"metric\": \"DISKS_TOTAL_GB\",\n         \"usage\": 0,\n         \"limit\": 100\n      },\n      {\n         \"metric\": \"SNAPSHOTS\",\n         \"usage\": 0,\n         \"limit\": 1000\n      },\n      {\n         \"metric\": \"NETWORKS\",\n         \"usage\": 1,\n         \"limit\": 5\n      },\n      {\n         \"metric\": \"FIREWALLS\",\n         \"usage\": 2,\n         \"limit\": 100\n      },\n      {\n         \"metric\": \"IMAGES\",\n         \"usage\": 0,\n         \"limit\": 100\n      }\n   ],\n   \"usageExportLocation\": {\n       \"bucketName\": \"test-bucket\",\n       \"reportNamePrefix\": \"report-prefix\"\n  }\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/quota.json",
    "content": "{\n   \"metric\": \"INSTANCES\",\n   \"usage\": 0,\n   \"limit\": 8\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/region_get.json",
    "content": "{\n    \"kind\": \"compute#region\",\n    \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/regions/us-central1\",\n    \"id\": \"12912210600542709766\",\n    \"creationTimestamp\": \"2013-07-08T14:40:37.939-07:00\",\n    \"name\": \"us-central1\",\n    \"description\": \"us-central1\",\n    \"status\": \"UP\",\n    \"zones\": [\n        \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a\",\n        \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-b\"\n    ],\n    \"quotas\": [\n        {\n            \"metric\": \"INSTANCES\",\n            \"usage\": 0,\n            \"limit\": 8\n        },\n        {\n            \"metric\": \"CPUS\",\n            \"usage\": 0,\n            \"limit\": 8\n        },\n        {\n            \"metric\": \"EPHEMERAL_ADDRESSES\",\n            \"usage\": 0,\n            \"limit\": 8\n        },\n        {\n            \"metric\": \"DISKS\",\n            \"usage\": 0,\n            \"limit\": 8\n        },\n        {\n            \"metric\": \"DISKS_TOTAL_GB\",\n            \"usage\": 0,\n            \"limit\": 100\n        },\n        {\n            \"metric\": \"SNAPSHOTS\",\n            \"usage\": 0,\n            \"limit\": 1000\n        },\n        {\n            \"metric\": \"NETWORKS\",\n            \"usage\": 1,\n            \"limit\": 5\n        },\n        {\n            \"metric\": \"FIREWALLS\",\n            \"usage\": 2,\n            \"limit\": 100\n        },\n        {\n            \"metric\": \"IMAGES\",\n            \"usage\": 0,\n            \"limit\": 100\n        }\n    ]\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/region_list.json",
    "content": "{\n    \"kind\": \"compute#regionList\",\n    \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/regions\",\n    \"id\": \"projects/party/regions\",\n    \"items\": [\n        {\n            \"kind\": \"compute#region\",\n            \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/regions/us-central1\",\n            \"id\": \"12912210600542709766\",\n            \"creationTimestamp\": \"2013-07-08T14:40:37.939-07:00\",\n            \"name\": \"us-central1\",\n            \"description\": \"us-central1\",\n            \"status\": \"UP\",\n            \"zones\": [\n                \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a\",\n                \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-b\"\n            ],\n            \"quotas\": [\n                {\n                    \"metric\": \"INSTANCES\",\n                    \"usage\": 0,\n                    \"limit\": 8\n                },\n                {\n                    \"metric\": \"CPUS\",\n                    \"usage\": 0,\n                    \"limit\": 8\n                },\n                {\n                    \"metric\": \"EPHEMERAL_ADDRESSES\",\n                    \"usage\": 0,\n                    \"limit\": 8\n                },\n                {\n                    \"metric\": \"DISKS\",\n                    \"usage\": 0,\n                    \"limit\": 8\n                },\n                {\n                    \"metric\": \"DISKS_TOTAL_GB\",\n                    \"usage\": 0,\n                    \"limit\": 100\n                },\n                {\n                    \"metric\": \"SNAPSHOTS\",\n                    \"usage\": 0,\n                    \"limit\": 1000\n                },\n                {\n                    \"metric\": \"NETWORKS\",\n                    \"usage\": 1,\n                    \"limit\": 5\n                },\n                {\n                    \"metric\": \"FIREWALLS\",\n                    \"usage\": 2,\n                    \"limit\": 100\n                },\n                {\n                    \"metric\": \"IMAGES\",\n                    \"usage\": 0,\n                    \"limit\": 100\n                }\n            ]\n        },\n        {\n            \"kind\": \"compute#region\",\n            \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/regions/us-central1\",\n            \"id\": \"6396763663251190992\",\n            \"creationTimestamp\": \"2013-07-08T14:40:37.939-07:00\",\n            \"name\": \"us-central1\",\n            \"description\": \"us-central1\",\n            \"status\": \"UP\",\n            \"zones\": [\n                \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a\"\n            ],\n            \"quotas\": [\n                {\n                    \"metric\": \"INSTANCES\",\n                    \"usage\": 0,\n                    \"limit\": 8\n                },\n                {\n                    \"metric\": \"CPUS\",\n                    \"usage\": 0,\n                    \"limit\": 8\n                },\n                {\n                    \"metric\": \"EPHEMERAL_ADDRESSES\",\n                    \"usage\": 0,\n                    \"limit\": 8\n                },\n                {\n                    \"metric\": \"DISKS\",\n                    \"usage\": 0,\n                    \"limit\": 8\n                },\n                {\n                    \"metric\": \"DISKS_TOTAL_GB\",\n                    \"usage\": 0,\n                    \"limit\": 100\n                },\n                {\n                    \"metric\": \"SNAPSHOTS\",\n                    \"usage\": 0,\n                    \"limit\": 1000\n                },\n                {\n                    \"metric\": \"NETWORKS\",\n                    \"usage\": 1,\n                    \"limit\": 5\n                },\n                {\n                    \"metric\": \"FIREWALLS\",\n                    \"usage\": 2,\n                    \"limit\": 100\n                },\n                {\n                    \"metric\": \"IMAGES\",\n                    \"usage\": 0,\n                    \"limit\": 100\n                }\n            ]\n        }\n    ]\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/region_operation.json",
    "content": "{\n   \"kind\": \"compute#operation\",\n   \"id\": \"13053095055850848306\",\n   \"creationTimestamp\": \"2013-07-26T13:57:20.204-07:00\",      \n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/regions/us-central1/operations/operation-1354084865060\",\n   \"name\": \"operation-1354084865060\",\n   \"targetLink\": \"https://www.googleapis.com/compute/v1/projects/party/regions/us-central1/addresses/test-address\",\n   \"targetId\": \"13053094017547040099\",\n   \"status\": \"DONE\",\n   \"user\": \"user@developer.gserviceaccount.com\",\n   \"progress\": 100,\n   \"insertTime\": \"2012-11-28T06:41:05.060\",\n   \"startTime\": \"2012-11-28T06:41:05.142\",\n   \"endTime\": \"2012-11-28T06:41:06.142\",\n   \"operationType\": \"insert\",\n   \"region\": \"https://www.googleapis.com/compute/v1/projects/party/regions/us-central1\"\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/region_operation_list.json",
    "content": "{\n   \"kind\": \"compute#operationList\",\n   \"id\": \"projects/party/regions/us-central1/operations\",\n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/regions/us-central1/operations\",\n   \"items\": [\n      {\n         \"kind\": \"compute#operation\",\n         \"id\": \"13053095055850848306\",\n         \"creationTimestamp\": \"2013-07-26T13:57:20.204-07:00\",\n         \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/regions/us-central1/operations/operation-1354084865060\",\n         \"name\": \"operation-1354084865060\",\n         \"targetLink\": \"https://www.googleapis.com/compute/v1/projects/party/regions/us-central1/addresses/test-address\",\n         \"targetId\": \"13053094017547040099\",\n         \"status\": \"DONE\",\n         \"user\": \"user@developer.gserviceaccount.com\",\n         \"progress\": 100,\n         \"insertTime\": \"2012-11-28T06:41:05.060\",\n         \"startTime\": \"2012-11-28T06:41:05.142\",\n         \"endTime\": \"2012-11-28T06:41:06.142\",\n         \"operationType\": \"insert\",\n         \"region\": \"https://www.googleapis.com/compute/v1/projects/party/regions/us-central1\"\n      }\n   ]\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/route_get.json",
    "content": "{\n  \"kind\": \"compute#route\",\n  \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/global/routes/default-route-c99ebfbed0e1f375\",\n  \"id\": \"7241926205630356071\",\n  \"creationTimestamp\": \"2013-07-08T14:40:38.502-07:00\",\n  \"name\": \"default-route-c99ebfbed0e1f375\",\n  \"description\": \"Default route to the virtual network.\",\n  \"network\": \"https://www.googleapis.com/compute/v1/projects/party/global/networks/default\",\n  \"destRange\": \"10.240.0.0/16\",\n  \"priority\": 1000,\n  \"nextHopNetwork\": \"https://www.googleapis.com/compute/v1/projects/party/global/networks/default\",\n  \"tags\": [\n    \"fooTag\",\n    \"barTag\"\n  ],\n  \"warnings\": [\n    {\n      \"code\": \"NO_RESULTS_ON_PAGE\",\n      \"message\": \"This is an example warning\",\n      \"data\": [\n        {\n          \"key\": \"scope\",\n          \"value\": \"There are no results for scope 'zones/asia-east1-b' on this page.\"\n        }\n      ]\n    }\n  ]\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/route_insert.json",
    "content": "{\"name\":\"default-route-c99ebfbed0e1f375\",\"description\":\"Default route to the virtual network.\",\"network\":\"https://www.googleapis.com/compute/v1/projects/party/global/networks/default\",\"destRange\":\"10.240.0.0/16\",\"priority\":1000,\"nextHopNetwork\":\"https://www.googleapis.com/compute/v1/projects/party/global/networks/default\",\"tags\":[\"fooTag\",\"barTag\"]}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/route_list.json",
    "content": "{\n  \"kind\": \"compute#routeList\",\n  \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/global/routes\",\n  \"id\": \"projects/party/global/routes\",\n  \"items\": [\n    {\n      \"kind\": \"compute#route\",\n      \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/global/routes/default-route-c99ebfbed0e1f375\",\n      \"id\": \"7241926205630356071\",\n      \"creationTimestamp\": \"2013-07-08T14:40:38.502-07:00\",\n      \"name\": \"default-route-c99ebfbed0e1f375\",\n      \"description\": \"Default route to the virtual network.\",\n      \"network\": \"https://www.googleapis.com/compute/v1/projects/party/global/networks/default\",\n      \"destRange\": \"10.240.0.0/16\",\n      \"priority\": 1000,\n      \"nextHopNetwork\": \"https://www.googleapis.com/compute/v1/projects/party/global/networks/default\",\n      \"tags\": [\n        \"fooTag\",\n        \"barTag\"\n      ],\n      \"warnings\": [\n        {\n          \"code\": \"NO_RESULTS_ON_PAGE\",\n          \"message\": \"This is an example warning\",\n          \"data\": [\n            {\n              \"key\": \"scope\",\n              \"value\": \"There are no results for scope 'zones/asia-east1-b' on this page.\"\n            }\n          ]\n        }\n      ]\n    },\n    {\n      \"kind\": \"compute#route\",\n      \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/global/routes/default-route-fc92a41ecb5a8d17\",\n      \"id\": \"507025480040058551\",\n      \"creationTimestamp\": \"2013-07-08T14:40:38.502-07:00\",\n      \"name\": \"default-route-fc92a41ecb5a8d17\",\n      \"description\": \"Default route to the Internet.\",\n      \"network\": \"https://www.googleapis.com/compute/v1/projects/party/global/networks/default\",\n      \"destRange\": \"0.0.0.0/0\",\n      \"priority\": 1000,\n      \"nextHopGateway\": \"https://www.googleapis.com/compute/v1/projects/party/global/gateways/default-internet-gateway\"\n    }\n  ]\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/snapshot_get.json",
    "content": "{\n\n    \"kind\": \"compute#snapshot\",\n    \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/global/snapshots/test-snap\",\n    \"id\": \"9734455566806191190\",\n    \"creationTimestamp\": \"2013-07-26T12:54:23.173-07:00\",\n    \"status\": \"READY\",\n    \"diskSizeGb\": \"10\",\n    \"sourceDisk\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/disks/testimage1\",\n    \"name\": \"test-snap\",\n    \"description\": \"\",\n    \"sourceDiskId\": \"8243603669926824540\"\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/snapshot_list.json",
    "content": "{\n    \"kind\": \"compute#snapshotList\",\n    \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/global/snapshots\",\n    \"id\": \"projects/party/global/snapshots\",\n    \"items\": [\n        {\n\n            \"kind\": \"compute#snapshot\",\n            \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/global/snapshots/test-snap\",\n            \"id\": \"9734455566806191190\",\n            \"creationTimestamp\": \"2013-07-26T12:54:23.173-07:00\",\n            \"status\": \"READY\",\n            \"diskSizeGb\": \"10\",\n            \"sourceDisk\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/disks/testimage1\",\n            \"name\": \"test-snap\",\n            \"description\": \"\",\n            \"sourceDiskId\": \"8243603669926824540\"\n        },\n        {\n\n            \"kind\": \"compute#snapshot\",\n            \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/global/snapshots/test-snap2\",\n            \"id\": \"13895715048576107883\",\n            \"creationTimestamp\": \"2013-07-26T12:57:01.927-07:00\",\n            \"status\": \"READY\",\n            \"diskSizeGb\": \"10\",\n            \"sourceDisk\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/disks/testimage1\",\n            \"name\": \"test-snap2\",\n            \"description\": \"\",\n            \"sourceDiskId\": \"8243603669926824540\"\n        }\n    ]\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/subnetwork_get.json",
    "content": "{\n  \"kind\": \"compute#subnetwork\",\n   \"id\": \"5850679262666457680\",\n   \"creationTimestamp\": \"2016-06-07T14:29:35.476-07:00\",\n   \"gatewayAddress\": \"10.128.0.1\",\n   \"name\": \"jclouds-test\",\n   \"network\": \"https://www.googleapis.com/compute/v1/projects/party/global/networks/mynetwork\",\n   \"ipCidrRange\": \"10.128.0.0/20\",\n   \"region\": \"https://www.googleapis.com/compute/v1/projects/party/regions/someregion\",\n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/regions/someregion/subnetworks/jclouds-test\",\n   \"description\": \"A custom subnetwork for the project\"\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/subnetwork_insert.json",
    "content": "{\n  \"name\": \"jclouds-test\",\n  \"description\": \"my subnetwork\",\n  \"network\": \"https://www.googleapis.com/compute/v1/projects/party/global/networks/mynetwork\",\n  \"ipCidrRange\": \"10.0.0.0/24\",\n  \"region\": \"https://www.googleapis.com/compute/v1/projects/party/regions/someregion\",\n  \"privateIpGoogleAccess\": false\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/subnetwork_list.json",
    "content": "{\n   \"kind\": \"compute#networkList\",\n   \"id\": \"projects/party/networks\",\n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/regions/someregion/subnetworks\",\n   \"items\": [\n      {\n         \"kind\": \"compute#subnetwork\",\n         \"id\": \"5850679262666457680\",\n         \"creationTimestamp\": \"2016-06-07T14:29:35.476-07:00\",\n         \"gatewayAddress\": \"10.128.0.1\",\n         \"name\": \"jclouds-test\",\n         \"network\": \"https://www.googleapis.com/compute/v1/projects/party/global/networks/mynetwork\",\n         \"ipCidrRange\": \"10.128.0.0/20\",\n         \"region\": \"https://www.googleapis.com/compute/v1/projects/party/regions/someregion\",\n         \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/regions/someregion/subnetworks/jclouds-test\",\n         \"description\": \"A custom subnetwork for the project\"\n      }\n   ]\n}\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/tag_insert.json",
    "content": "{\"items\":[\"aTag\"],\"fingerprint\":\"abcd\"}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/target_http_proxy_get.json",
    "content": "{\n   \"kind\": \"compute#targetHttpProxy\",\n   \"id\": \"13050421646334304115\",\n   \"creationTimestamp\": \"2012-11-25T01:38:48.306\",\n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/myproject/global/targetHttpProxies/jclouds-test\",\n   \"name\": \"jclouds-test\",\n   \"urlMap\": \"https://www.googleapis.com/compute/v1/projects/myproject/global/urlMaps/jclouds-test\"\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/target_http_proxy_insert.json",
    "content": "{\n  \"name\": \"jclouds-test\",\n  \"urlMap\": \"https://www.googleapis.com/compute/v1/projects/myproject/global/urlMaps/jclouds-test\"\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/target_http_proxy_list.json",
    "content": "{\n   \"kind\": \"compute#targetHttpProxyList\",\n   \"id\": \"projects/myproject/targetHttpProxies\",\n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/myproject/global/targetHttpProxies\",\n   \"items\": [\n      {\n         \"kind\": \"compute#targetHttpProxy\",\n         \"id\": \"13050421646334304115\",\n         \"creationTimestamp\": \"2012-11-25T01:38:48.306\",\n         \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/myproject/global/targetHttpProxies/jclouds-test\",\n         \"name\": \"jclouds-test\",\n         \"urlMap\": \"https://www.googleapis.com/compute/v1/projects/myproject/global/urlMaps/jclouds-test\"\n      },\n      {\n         \"kind\": \"compute#targetHttpProxy\",\n         \"id\": \"13050421646334304116\",\n         \"creationTimestamp\": \"2012-11-25T01:38:48.306\",\n         \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/myproject/global/targetHttpProxies/jclouds-test-2\",\n         \"name\": \"jclouds-test-2\",\n         \"description\": \"Simple proxy\",\n         \"urlMap\": \"https://www.googleapis.com/compute/v1/projects/myproject/global/urlMaps/jclouds-test-2\"\n      }\n   ]\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/target_http_proxy_set_url_map.json",
    "content": "{\"urlMap\":\"https://www.googleapis.com/compute/v1/projects/myproject/global/urlMaps/jclouds-test\"}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/target_instance_get.json",
    "content": "{\n  \"kind\": \"compute#targetInstance\",\n  \"id\": \"13050421646334304115\",\n  \"creationTimestamp\": \"2014-07-18T09:47:30.826-07:00\",\n  \"name\": \"target-instance-1\",\n  \"description\": \"A pretty cool target instance\",\n  \"zone\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a\",\n  \"natPolicy\": \"NO_NAT\",\n  \"instance\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/instances/test-0\",\n  \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/targetInstances/target-instance-1\"\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/target_instance_insert.json",
    "content": "{\n \"name\": \"test-target-instance\",\n \"description\": \"This is a test\",\n \"natPolicy\": \"NO_NAT\",\n \"instance\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/instances/instance-1\"\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/target_instance_list.json",
    "content": "{\n \"kind\": \"compute#targetInstanceList\",\n \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/studied-point-720/zones/us-central1-a/targetInstances\",\n \"id\": \"projects/studied-point-720/zones/us-central1-a/targetInstances\",\n \"items\": [\n  {\n\n   \"kind\": \"compute#targetInstance\",\n   \"id\": \"13050421646334304115\",\n   \"creationTimestamp\": \"2014-07-18T09:47:30.826-07:00\",\n   \"name\": \"target-instance-1\",\n   \"description\": \"A pretty cool target instance\",\n   \"zone\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a\",\n   \"natPolicy\": \"NO_NAT\",\n   \"instance\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/instances/test-0\",\n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/targetInstances/target-instance-1\"\n  },\n  {\n\n   \"kind\": \"compute#targetInstance\",\n   \"id\": \"7362436693678237415\",\n   \"creationTimestamp\": \"2014-11-20T17:35:17.268-08:00\",\n   \"name\": \"target-instance-2\",\n   \"zone\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a\",\n   \"natPolicy\": \"NO_NAT\",\n   \"instance\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/instances/test-3\",\n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/targetInstances/target-instance-2\"\n  }\n ]\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/targetpool_addinstance.json",
    "content": "{\"instances\":[{\"instance\":\"https://www.googleapis.com/compute/v1/projects/party/zones/europe-west1-a/instances/test\"}]}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/targetpool_changehealthcheck.json",
    "content": "{\"healthChecks\":[{\"healthCheck\":\"https://www.googleapis.com/compute/v1/projects/party/global/httpHealthChecks/health-check-1\"}]}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/targetpool_get.json",
    "content": "{\n \"kind\": \"compute#targetPool\",\n \"id\": \"5199309593612841404\",\n \"creationTimestamp\": \"2014-01-07T05:25:27.783-08:00\",\n \"name\": \"test-targetpool\",\n \"region\": \"https://www.googleapis.com/compute/v1/projects/party/regions/us-central1\",\n \"sessionAffinity\": \"NONE\",\n \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/regions/us-central1/targetPools/test-targetpool\"\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/targetpool_insert.json",
    "content": "{\n \"name\": \"test\"\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/targetpool_list.json",
    "content": "{\n \"kind\": \"compute#targetPoolList\",\n \"selfLink\": \"https://content.googleapis.com/compute/v1/projects/party/regions/us-central1/targetPools\",\n \"id\": \"projects/party/regions/us-central1/targetPools\",\n \"items\": [\n  {\n\n   \"kind\": \"compute#targetPool\",\n   \"id\": \"5199309593612841404\",\n   \"creationTimestamp\": \"2014-01-07T05:25:27.783-08:00\",\n   \"name\": \"test-targetpool\",\n   \"region\": \"https://www.googleapis.com/compute/v1/projects/party/regions/us-central1\",\n   \"sessionAffinity\": \"NONE\",\n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/regions/us-central1/targetPools/test-targetpool\"\n  }\n ]\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/targetpool_setbackup.json",
    "content": "{\"target\":\"https://www.googleapis.com/compute/v1/projects/party/regions/us-central1/targetPools/tpool\"}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/test",
    "content": "-----BEGIN RSA PRIVATE KEY-----\nMIIEogIBAAKCAQEAnJvA40x4OK+9nVYTS0N916VMjC6/qYe/IuDUdy6hdW1wz9IO\nMTS3CPxlE0KuoNO1/M7O7yFso6IragTxUkNqJ2mUOqV0Bf0CEkUIKzeYRGfpx+QM\nPorHbLQXjjFinWKwibZuv6lqtvqwcsrjW7bpWsz9x+0qqKM0o0UhjUMhTRqZoYxo\nE2zUH7WA8JRatE/bQkjv/nWBfI+/WzSDhJn7AjIql0Nd4Q+bxohIJEZu8yDw1H6T\npd7mw83m6UYBk4eZH79r3d2euuQMUKIunyLbw7vNJJ8qYTJQuNYIiJuWKnzzjxuJ\nUfumhdOqfjSobznhAjTLUbA/btZCiQ/TasV4cQIDAQABAoIBAEeOn1b8ZN455qDS\naKR2JTT4cX6ICckznnEYW9xNMTcPl4FN0HBJTuzLLn/bcyFHOxtVf5YiJpqqCb46\nne1hokp54mHdoaLu1Rh19GKS139CH77XA4U8Mh0IOM8e35lcM5/o/LeUeI89Aoyh\nCbupWvzDN543TsuZLv7/InKCXt/0dXhAQpq3UiBT63EITQbyom5fSPnMzqM3F8jD\nE9ZqkX4JsnTPC7FQDIpPCaKjG9YCZqoljz+1ssli3mN66V/JKefcCiVoubalmmT2\ndpvmRtFaKvhAmkWYakYybYg8aDi3YygAHSU1bzxlY4TNiQgPdnTTDAPyeqqVrE1D\nChi+18UCgYEAzlk7c+tFwxZ3ryycOe0loFudUNE5rviHhPgbOHoSTooXh0Hq1Vrb\n2ic+4FbRpoPHLpcLM9LX+arezUdeFBZ8qunjUG6MbUhAeAm/3cfMk+nZg3Skpg8+\nC1D3hxGX4qdhURHvc2QUH7VIUWbucvPgtL8pt1z5Su/EE1Cb2XVsvu8CgYEAwkqZ\n4vTZxI0XqJo6BfUnKGJEDC8xeWr10ELPdXLTCuNDpLSYNedQAxZi9XzvbnbWZ/MF\nZ7IWkzzyAjsX0gpI56cxxtas/chxUboBlUo6ZW8QcPDcU2sKJi318wzElqqvRMNM\nInfLf8nuPC9hyhe49/lFBBSZJeIo396DuqnTPp8CgYBO4NVVLm5wcLo3gDoH+psT\nfXHZXuFJ/T7wmVbuc9tjom30CkKWZDD+Z1olr4pcuKr/KEXj/YkJq0OX/Nv9mcr2\nGooGSPvtGl1qhW+Oe728HPxEv+XghJsXAFBelV8WCR2uO8jotyzqIgYO9+XWk1sm\nPJzZtvSkrJqrN3kb20NCiQKBgDDVP0hj8jgMnl2qJdtJesYTrLbDRdQWpiHqKOqE\nKbca1+2V1ov1z453GfhJpoRFKi6GTl15zWLEdq9I2vvXyesvgrtPSbufnZvE/JDh\nTzwfZip832O4C5z9AExOcTrNO7A0xfYD1goQXuiRoCqDO+JXrJkR9EwpQ8zAyKsp\n9AZRAoGAGq3TYpmlI5oucEURHKsHOrIBirHFD+RaXMynxzgwkRnt6Z5Mg10I7Ddr\nLiGK8/IrF8bg1F7weLVmj93zjvhQTh5yvb1jwVdFGXM2rbR7/P7F6n2f7xM4+lmv\nTq7E9Sv8UVuraAwJihlKCuBtpZM1t2JhcuNjXAZngj7R9j5HIZg=\n-----END RSA PRIVATE KEY-----\n"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/url_map_get.json",
    "content": "{\n   \"kind\": \"compute#urlMap\",\n   \"id\": \"13741966667737398119\",\n   \"creationTimestamp\": \"2014-07-23T12:39:50.022-07:00\",\n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/myproject/global/urlMaps/jclouds-test\",\n   \"name\": \"jclouds-test\",\n   \"description\": \"Sample url map\",\n   \"hostRules\": [\n      {\n         \"hosts\": [\n            \"jclouds-test\"\n         ],\n         \"pathMatcher\": \"path\"\n      }\n   ],\n   \"pathMatchers\": [\n      {\n         \"name\": \"path\",\n         \"defaultService\": \"https://www.googleapis.com/compute/v1/projects/myproject/global/backendServices/jclouds-test\",\n         \"pathRules\": [\n            {\n               \"service\": \"https://www.googleapis.com/compute/v1/projects/myproject/global/backendServices/jclouds-test\",\n               \"paths\": [\n                  \"/\"\n               ]\n            }\n         ]\n      }\n   ],\n   \"tests\": [\n      {\n         \"host\": \"jclouds-test\",\n         \"path\": \"/test/path\",\n         \"service\": \"https://www.googleapis.com/compute/v1/projects/myproject/global/backendServices/jclouds-test\"\n      }\n   ],\n   \"defaultService\": \"https://www.googleapis.com/compute/v1/projects/myproject/global/backendServices/jclouds-test\",\n   \"fingerprint\": \"EDmhvJucpz4=\"\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/url_map_insert.json",
    "content": "{\"name\":\"jclouds-test\",\"description\":\"Sample url map\",\"hostRules\":[{\"hosts\":[\"jclouds-test\"],\"pathMatcher\":\"path\"}],\"pathMatchers\":[{\"name\":\"path\",\"defaultService\":\"https://www.googleapis.com/compute/v1/projects/myproject/global/backendServices/jclouds-test\",\"pathRules\":[{\"service\":\"https://www.googleapis.com/compute/v1/projects/myproject/global/backendServices/jclouds-test\",\"paths\":[\"/\"]}]}],\"tests\":[{\"host\":\"jclouds-test\",\"path\":\"/test/path\",\"service\":\"https://www.googleapis.com/compute/v1/projects/myproject/global/backendServices/jclouds-test\"}],\"defaultService\":\"https://www.googleapis.com/compute/v1/projects/myproject/global/backendServices/jclouds-test\"}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/url_map_list.json",
    "content": "{\n   \"kind\": \"compute#urlMapList\",\n   \"id\": \"projects/myproject/global/urlMaps\",\n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/myproject/global/urlMaps\",\n   \"items\": [\n      {\n          \"kind\": \"compute#urlMap\",\n           \"id\": \"13741966667737398119\",\n           \"creationTimestamp\": \"2014-07-23T12:39:50.022-07:00\",\n           \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/myproject/global/urlMaps/jclouds-test\",\n           \"name\": \"jclouds-test\",\n           \"description\": \"Sample url map\",\n           \"hostRules\": [\n              {\n                 \"hosts\": [\n                    \"jclouds-test\"\n                 ],\n                 \"pathMatcher\": \"path\"\n              }\n           ],\n           \"pathMatchers\": [\n              {\n                 \"name\": \"path\",\n                 \"defaultService\": \"https://www.googleapis.com/compute/v1/projects/myproject/global/backendServices/jclouds-test\",\n                 \"pathRules\": [\n                    {\n                       \"service\": \"https://www.googleapis.com/compute/v1/projects/myproject/global/backendServices/jclouds-test\",\n                       \"paths\": [\n                          \"/\"\n                       ]\n                    }\n                 ]\n              }\n           ],\n           \"tests\": [\n              {\n                 \"host\": \"jclouds-test\",\n                 \"path\": \"/test/path\",\n                 \"service\": \"https://www.googleapis.com/compute/v1/projects/myproject/global/backendServices/jclouds-test\"\n              }\n           ],\n           \"defaultService\": \"https://www.googleapis.com/compute/v1/projects/myproject/global/backendServices/jclouds-test\",\n           \"fingerprint\": \"EDmhvJucpz4=\"\n       },\n       {\n          \"kind\": \"compute#urlMap\",\n           \"id\": \"13741966667737398120\",\n           \"creationTimestamp\": \"2014-07-23T12:39:50.022-07:00\",\n           \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/myproject/global/urlMaps/jclouds-test-2\",\n           \"name\": \"jclouds-test-2\",\n           \"description\": \"Basic url map\",\n           \"defaultService\": \"https://www.googleapis.com/compute/v1/projects/myproject/global/backendServices/jclouds-test\",\n           \"fingerprint\": \"EDqhvJucpz4=\"\n       }\n   ]\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/url_map_validate.json",
    "content": "{\n   \"result\": {\n      \"loadSucceeded\": false,\n      \"loadErrors\": [\n         \"jclouds-test\"\n      ],\n      \"testPassed\": false,\n      \"testFailures\": [\n         {\n            \"host\": \"jclouds-test\",\n            \"path\": \"/test/path\",\n            \"expectedService\": \"https://www.googleapis.com/compute/v1/projects/myproject/global/backendServices/jclouds-test\",\n            \"actualService\": \"https://www.googleapis.com/compute/v1/projects/myproject/global/backendServices/jclouds-test-2\"\n         }\n      ]\n   } \n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/url_map_validate_request.json",
    "content": "{\"resource\":{\"name\":\"jclouds-test\",\"description\":\"Sample url map\",\"hostRules\":[{\"hosts\":[\"jclouds-test\"],\"pathMatcher\":\"path\"}],\"pathMatchers\":[{\"name\":\"path\",\"defaultService\":\"https://www.googleapis.com/compute/v1/projects/myproject/global/backendServices/jclouds-test\",\"pathRules\":[{\"service\":\"https://www.googleapis.com/compute/v1/projects/myproject/global/backendServices/jclouds-test\",\"paths\":[\"/\"]}]}],\"tests\":[{\"host\":\"jclouds-test\",\"path\":\"/test/path\",\"service\":\"https://www.googleapis.com/compute/v1/projects/myproject/global/backendServices/jclouds-test\"}],\"defaultService\":\"https://www.googleapis.com/compute/v1/projects/myproject/global/backendServices/jclouds-test\"}}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/zone_get.json",
    "content": "{\n   \"kind\": \"compute#zone\",\n   \"id\": \"13020128040171887099\",\n   \"creationTimestamp\": \"2012-10-19T16:42:54.131\",\n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a\",\n   \"name\": \"us-central1-a\",\n   \"description\": \"us-central1-a\",\n   \"region\": \"us-central1\",\n   \"status\": \"DOWN\",\n   \"maintenanceWindows\": [\n      {\n         \"name\": \"2012-11-10-planned-outage\",\n         \"description\": \"maintenance zone\",\n         \"beginTime\": \"2012-11-10T20:00:00.000\",\n         \"endTime\": \"2012-12-02T20:00:00.000\"\n      }\n   ]\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/zone_list.json",
    "content": "{\n   \"kind\": \"compute#zoneList\",\n   \"id\": \"projects/party/zones\",\n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/zones\",\n   \"items\": [\n      {\n         \"kind\": \"compute#zone\",\n         \"id\": \"13020128040171887099\",\n         \"creationTimestamp\": \"2012-10-19T16:42:54.131\",\n         \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a\",\n         \"name\": \"us-central1-a\",\n         \"description\": \"us-central1-a\",\n         \"status\": \"DOWN\",\n         \"region\": \"us-central1\",\n         \"maintenanceWindows\": [\n            {\n               \"name\": \"2012-11-10-planned-outage\",\n               \"description\": \"maintenance zone\",\n               \"beginTime\": \"2012-11-10T20:00:00.000\",\n               \"endTime\": \"2012-12-02T20:00:00.000\"\n            }\n         ]\n      },\n      {\n         \"kind\": \"compute#zone\",\n         \"id\": \"13024414164050619686\",\n         \"creationTimestamp\": \"2012-10-24T20:13:19.271\",\n         \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-b\",\n         \"name\": \"us-central1-b\",\n         \"description\": \"us-central1-b\",\n         \"status\": \"UP\",\n         \"region\": \"us-central1\",\n         \"maintenanceWindows\": [\n            {\n               \"name\": \"2013-02-17-planned-outage\",\n               \"description\": \"maintenance zone\",\n               \"beginTime\": \"2013-02-17T08:00:00.000\",\n               \"endTime\": \"2013-03-03T08:00:00.000\"\n            }\n         ]\n      }\n   ]\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/zone_list_short.json",
    "content": "{\n   \"kind\": \"compute#zoneList\",\n   \"id\": \"projects/party/zones\",\n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/zones\",\n   \"items\": [\n      {\n         \"kind\": \"compute#zone\",\n         \"id\": \"13020128040171887099\",\n         \"creationTimestamp\": \"2012-10-19T16:42:54.131\",\n         \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a\",\n         \"name\": \"us-central1-a\",\n         \"description\": \"us-central1-a\",\n         \"status\": \"DOWN\",\n         \"region\": \"us-central1\",\n         \"maintenanceWindows\": [\n            {\n               \"name\": \"2012-11-10-planned-outage\",\n               \"description\": \"maintenance zone\",\n               \"beginTime\": \"2012-11-10T20:00:00.000\",\n               \"endTime\": \"2012-12-02T20:00:00.000\"\n            }\n         ]\n      }\n   ]\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/zone_operation.json",
    "content": "{\n   \"kind\": \"compute#operation\",\n   \"id\": \"13053095055850848306\",\n   \"creationTimestamp\": \"2013-07-26T13:57:20.204-07:00\",\n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/operations/operation-1354084865060\",\n   \"name\": \"operation-1354084865060\",\n   \"targetLink\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/instances/test-1\",\n   \"targetId\": \"13053094017547040099\",\n   \"status\": \"DONE\",\n   \"user\": \"user@developer.gserviceaccount.com\",\n   \"progress\": 100,\n   \"insertTime\": \"2012-11-28T06:41:05.060\",\n   \"startTime\": \"2012-11-28T06:41:05.142\",\n   \"endTime\": \"2012-11-28T06:41:06.142\",\n   \"operationType\": \"insert\",\n   \"zone\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a\"\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/zone_operation_error.json",
    "content": "{\n   \"kind\": \"compute#operation\",\n   \"id\": \"13053095055850848306\",\n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/operations/operation-1354084865060\",\n   \"name\": \"operation-1354084865060\",\n   \"targetLink\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/instances/test-1\",\n   \"targetId\": \"13053094017547040099\",\n   \"status\": \"DONE\",\n   \"user\": \"user@developer.gserviceaccount.com\",\n   \"progress\": 100,\n   \"insertTime\": \"2012-11-28T06:41:05.060\",\n   \"startTime\": \"2012-11-28T06:41:05.142\",\n   \"httpErrorStatusCode\": 400,\n   \"httpErrorMessage\": \"BAD REQUEST\",\n   \"error\": {\n      \"errors\": [\n         {\n            \"code\": \"RESOURCE_ALREADY_EXISTS\",\n            \"message\": \"The resource 'projects/party/zones/us-central1-a/instances/test-1' already exists\"\n         }\n      ]\n   },\n   \"operationType\": \"insert\",\n   \"zone\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a\"\n}"
  },
  {
    "path": "providers/google-compute-engine/src/test/resources/zone_operation_list.json",
    "content": "{\n   \"kind\": \"compute#operationList\",\n   \"id\": \"projects/party/zones/us-central1-a/operations\",\n   \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/operations\",\n   \"items\": [\n      {\n         \"kind\": \"compute#operation\",\n         \"id\": \"13053095055850848306\",\n         \"creationTimestamp\": \"2013-07-26T13:57:20.204-07:00\",\n         \"selfLink\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/operations/operation-1354084865060\",\n         \"name\": \"operation-1354084865060\",\n         \"targetLink\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/instances/test-1\",\n         \"targetId\": \"13053094017547040099\",\n         \"status\": \"DONE\",\n         \"user\": \"user@developer.gserviceaccount.com\",\n         \"progress\": 100,\n         \"insertTime\": \"2012-11-28T06:41:05.060\",\n         \"startTime\": \"2012-11-28T06:41:05.142\",\n         \"endTime\": \"2012-11-28T06:41:06.142\",\n         \"operationType\": \"insert\",\n         \"zone\": \"https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a\"\n      }\n   ]\n}"
  },
  {
    "path": "providers/openhosting-east1/README.txt",
    "content": "#\n# The jclouds provider for Open Hosting's ElasticStack (http://openhosting.com/).\n#\n# Expects the jclouds elasticstack API to be present on your application's classpath.\n#\n# TODO: Implementation status.\n# TODO: Supported features.\n# TODO: Usage example.\n"
  },
  {
    "path": "providers/openhosting-east1/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.openhosting.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "providers/openhosting-east1/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.provider</groupId>\n  <artifactId>openhosting-east1</artifactId>\n  <name>jclouds Open Hosting East1 provider</name>\n  <description>Open Hosting implementation targeted to East1</description>\n\n  <properties>\n    <test.openhosting-east1.endpoint>https://api.east1.openhosting.com</test.openhosting-east1.endpoint>\n    <test.openhosting-east1.api-version>2.0</test.openhosting-east1.api-version>\n    <test.openhosting-east1.build-version />\n    <test.openhosting-east1.identity>FIXME_IDENTITY</test.openhosting-east1.identity>\n    <test.openhosting-east1.credential>FIXME_CREDENTIAL</test.openhosting-east1.credential>\n    <test.openhosting-east1.template />\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>elasticstack</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>elasticstack</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-log4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-sshj</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.openhosting-east1.endpoint>${test.openhosting-east1.endpoint}</test.openhosting-east1.endpoint>\n                    <test.openhosting-east1.api-version>${test.openhosting-east1.api-version}</test.openhosting-east1.api-version>\n                    <test.openhosting-east1.build-version>${test.openhosting-east1.build-version}</test.openhosting-east1.build-version>\n                    <test.openhosting-east1.identity>${test.openhosting-east1.identity}</test.openhosting-east1.identity>\n                    <test.openhosting-east1.credential>${test.openhosting-east1.credential}</test.openhosting-east1.credential>\n                    <test.openhosting-east1.template>${test.openhosting-east1.template}</test.openhosting-east1.template>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n"
  },
  {
    "path": "providers/openhosting-east1/src/main/java/org/jclouds/openhosting/OpenHostingEast1ProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openhosting;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.elasticstack.ElasticStackApiMetadata;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\n\nimport com.google.auto.service.AutoService;\n\n/**\n * Implementation of {@link ProviderMetadata} for OpenHosting East1.\n */\n@AutoService(ProviderMetadata.class)\npublic class OpenHostingEast1ProviderMetadata extends BaseProviderMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromProviderMetadata(this);\n   }\n\n   public OpenHostingEast1ProviderMetadata() {\n      super(builder());\n   }\n\n   public OpenHostingEast1ProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = new Properties();\n      return properties;\n   }\n\n   public static class Builder\n         extends\n         BaseProviderMetadata.Builder {\n\n      protected Builder() {\n         id(\"openhosting-east1\")\n         .name(\"OpenHosting East1\")\n         .apiMetadata(new ElasticStackApiMetadata())\n         .homepage(URI.create(\"https://east1.openhosting.com\"))\n         .console(URI.create(\"https://east1.openhosting.com/accounts\"))\n         .iso3166Codes(\"US-VA\")\n         .endpoint(\"https://api.east1.openhosting.com\")\n         .defaultProperties(OpenHostingEast1ProviderMetadata.defaultProperties());\n      }\n\n      @Override\n      public OpenHostingEast1ProviderMetadata build() {\n         return new OpenHostingEast1ProviderMetadata(this);\n      }\n\n      @Override\n      public Builder fromProviderMetadata(\n            ProviderMetadata in) {\n         super.fromProviderMetadata(in);\n         return this;\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/openhosting-east1/src/main/java/org/jclouds/openhosting/config/OpenHostingEast1ComputeServiceContextModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openhosting.config;\n\nimport org.jclouds.elasticstack.compute.config.ElasticStackComputeServiceContextModule;\n\npublic class OpenHostingEast1ComputeServiceContextModule extends ElasticStackComputeServiceContextModule {\n\n}\n"
  },
  {
    "path": "providers/openhosting-east1/src/test/java/org/jclouds/openhosting/OpenHostingEast1ApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openhosting;\n\nimport org.jclouds.elasticstack.ElasticStackApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"OpenHostingEast1ApiLiveTest\")\npublic class OpenHostingEast1ApiLiveTest extends ElasticStackApiLiveTest {\n   public OpenHostingEast1ApiLiveTest() {\n      provider = \"openhosting-east1\";\n   }\n}\n"
  },
  {
    "path": "providers/openhosting-east1/src/test/java/org/jclouds/openhosting/OpenHostingEast1ProviderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openhosting;\n\nimport org.jclouds.elasticstack.ElasticStackApiMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.testng.annotations.Test;\n\n/**\n * The OpenHostingEast1ProviderTest tests the {@link OpenHostingEast1ProviderMetadata} class.\n */\n@Test(groups = \"unit\", testName = \"OpenHostingEast1ProviderTest\")\npublic class OpenHostingEast1ProviderTest extends BaseProviderMetadataTest {\n\n   public OpenHostingEast1ProviderTest() {\n      super(new OpenHostingEast1ProviderMetadata(), new ElasticStackApiMetadata());\n   }\n\n}\n"
  },
  {
    "path": "providers/openhosting-east1/src/test/java/org/jclouds/openhosting/compute/OpenHostingEast1ComputeServiceLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openhosting.compute;\n\nimport org.jclouds.elasticstack.compute.ElasticStackComputeServiceLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"OpenHostingEast1ComputeServiceLiveTest\")\npublic class OpenHostingEast1ComputeServiceLiveTest extends ElasticStackComputeServiceLiveTest {\n\n   public OpenHostingEast1ComputeServiceLiveTest() {\n      provider = \"openhosting-east1\";\n      group = \"openhosting\";\n   }\n\n}\n"
  },
  {
    "path": "providers/openhosting-east1/src/test/java/org/jclouds/openhosting/compute/OpenHostingEast1TemplateBuilderLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.openhosting.compute;\n\nimport static org.jclouds.compute.util.ComputeServiceUtils.getCores;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.internal.BaseTemplateBuilderLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"live\")\npublic class OpenHostingEast1TemplateBuilderLiveTest extends BaseTemplateBuilderLiveTest {\n\n   public OpenHostingEast1TemplateBuilderLiveTest() {\n      provider = \"openhosting-east1\";\n   }\n\n   @Test\n   public void testDefaultTemplateBuilder() throws IOException {\n      Template defaultTemplate = this.view.getComputeService().templateBuilder().build();\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true);\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().getVersion(), \"10.04\");\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.UBUNTU);\n      assertEquals(defaultTemplate.getLocation().getId(), \"openhosting-east1\");\n      assertEquals(getCores(defaultTemplate.getHardware()), 1.0d);\n   }\n\n   @Override\n   protected Set<String> getIso3166Codes() {\n      return ImmutableSet.of(\"US-VA\");\n   }\n}\n"
  },
  {
    "path": "providers/packet/README.md",
    "content": "# Apache jclouds Packet (packet.net) provider\n\n\n## Pre-requisites\n\nIf you are using Oracle JDK, you may get this exception\n```\nCaused by: javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure\n```\nwhen calling Packet endpoints. To solve this, you want to install JCE following the [official documentation](http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html).\n"
  },
  {
    "path": "providers/packet/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.packet.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "providers/packet/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n    <modelVersion>4.0.0</modelVersion>\n    <parent>\n        <groupId>org.apache.jclouds</groupId>\n        <artifactId>jclouds-project</artifactId>\n        <version>2.7.1-SNAPSHOT</version>\n        <relativePath>../../project/pom.xml</relativePath>\n    </parent>\n\n    <groupId>org.apache.jclouds.provider</groupId>\n    <artifactId>packet</artifactId>\n    <name>jclouds Packet compute API</name>\n    <description>jclouds components to access an implementation of Packet's Compute Service</description>\n\n    <properties>\n        <test.packet.endpoint>https://api.packet.net/</test.packet.endpoint>\n        <test.packet.identity>projectId</test.packet.identity>\n        <test.packet.credential>api key</test.packet.credential>\n    </properties>\n\n    <dependencies>\n        <dependency>\n            <groupId>org.apache.jclouds</groupId>\n            <artifactId>jclouds-compute</artifactId>\n            <version>${project.version}</version>\n        </dependency>\n        <dependency>\n            <groupId>com.google.auto.service</groupId>\n            <artifactId>auto-service</artifactId>\n            <scope>provided</scope>\n            <optional>true</optional>\n        </dependency>\n        <dependency>\n            <groupId>com.google.auto.value</groupId>\n            <artifactId>auto-value</artifactId>\n            <scope>provided</scope>\n        </dependency>\n\n        <dependency>\n            <groupId>org.apache.jclouds</groupId>\n            <artifactId>jclouds-core</artifactId>\n            <version>${project.version}</version>\n            <type>test-jar</type>\n            <scope>test</scope>\n        </dependency>\n        <dependency>\n            <groupId>org.apache.jclouds</groupId>\n            <artifactId>jclouds-compute</artifactId>\n            <version>${project.version}</version>\n            <type>test-jar</type>\n            <scope>test</scope>\n        </dependency>\n        <dependency>\n            <groupId>org.apache.jclouds.driver</groupId>\n            <artifactId>jclouds-slf4j</artifactId>\n            <version>${project.version}</version>\n            <type>test-jar</type>\n            <scope>test</scope>\n        </dependency>\n        <dependency>\n            <groupId>org.apache.jclouds.driver</groupId>\n            <artifactId>jclouds-slf4j</artifactId>\n            <version>${project.version}</version>\n            <scope>test</scope>\n        </dependency>\n        <dependency>\n            <groupId>ch.qos.logback</groupId>\n            <artifactId>logback-classic</artifactId>\n            <scope>test</scope>\n        </dependency>\n        <dependency>\n            <groupId>org.apache.jclouds.driver</groupId>\n            <artifactId>jclouds-sshj</artifactId>\n            <version>${project.version}</version>\n            <scope>test</scope>\n        </dependency>\n        <dependency>\n            <groupId>com.squareup.okhttp3</groupId>\n            <artifactId>mockwebserver</artifactId>\n            <scope>test</scope>\n        </dependency>\n    </dependencies>\n\n    <profiles>\n        <profile>\n            <id>live</id>\n\n            <build>\n                <defaultGoal>clean verify</defaultGoal>\n\n                <plugins>\n                    <plugin>\n                        <groupId>org.apache.maven.plugins</groupId>\n                        <artifactId>maven-surefire-plugin</artifactId>\n                        <executions>\n                            <execution>\n                                <id>integration</id>\n                                <phase>integration-test</phase>\n                                <goals>\n                                    <goal>test</goal>\n                                </goals>\n                                <configuration>\n                                    <systemPropertyVariables>\n                                        <test.packet.endpoint>${test.packet.endpoint}</test.packet.endpoint>\n                                        <test.packet.identity>${test.packet.identity}</test.packet.identity>\n                                        <test.packet.credential>${test.packet.credential}</test.packet.credential>\n                                    </systemPropertyVariables>\n                                </configuration>\n                            </execution>\n                        </executions>\n                    </plugin>\n                </plugins>\n            </build>\n        </profile>\n    </profiles>\n\n</project>\n"
  },
  {
    "path": "providers/packet/src/main/java/org/jclouds/packet/PacketApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet;\n\nimport java.io.Closeable;\n\nimport jakarta.ws.rs.PathParam;\n\nimport org.jclouds.packet.features.DeviceApi;\nimport org.jclouds.packet.features.FacilityApi;\nimport org.jclouds.packet.features.OperatingSystemApi;\nimport org.jclouds.packet.features.PlanApi;\nimport org.jclouds.packet.features.ProjectApi;\nimport org.jclouds.packet.features.SshKeyApi;\nimport org.jclouds.rest.annotations.Delegate;\n\n/**\n * The Packet API is a REST API for managing your services and deployments.\n * <p>\n *\n * @see <a href=\"https://www.packet.net/help/api/\" >doc</a>\n */\npublic interface PacketApi extends Closeable {\n\n   /**\n    * The Packet API includes operations for managing project.\n    *\n    * @see <a href=\"https://www.packet.net/help/api/#page:projects,header:projects-projects\">docs</a>\n    */\n   @Delegate\n   ProjectApi projectApi();\n\n   /**\n    * This Packet API provides all of the devices\n    *\n    * @see <a href=\"https://www.packet.net/help/api/#page:devices\">docs</a>\n    */\n   @Delegate\n   DeviceApi deviceApi(@PathParam(\"projectId\") String projectId);\n\n   /**\n    * This Packet API provides all of the facilities\n    *\n    * @see <a href=\"https://www.packet.net/help/api/#page:devices,header:devices-operating-systems\">docs</a>\n    */\n   @Delegate\n   FacilityApi facilityApi();\n\n   /**\n    * This Packet API provides all of the plans\n    *\n    * @see <a href=\"https://www.packet.net/help/api/#page:devices,header:devices-plans\">docs</a>\n    */\n   @Delegate\n   PlanApi planApi();\n\n   /**\n    * This Packet API provides all of the operating systems\n    *\n    * @see <a href=\"https://www.packet.net/help/api/#page:devices,header:devices-operating-systems\">docs</a>\n    */\n   @Delegate\n   OperatingSystemApi operatingSystemApi();\n\n   /**\n    * This Packet API provides all of the operating systems\n    *\n    * @see <a href=\"https://www.packet.net/help/api/#page:ssh-keys\">docs</a>\n    */\n   @Delegate\n   SshKeyApi sshKeyApi();\n}\n"
  },
  {
    "path": "providers/packet/src/main/java/org/jclouds/packet/PacketApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.packet.compute.config.PacketComputeServiceContextModule;\nimport org.jclouds.packet.config.PacketComputeParserModule;\nimport org.jclouds.packet.config.PacketHttpApiModule;\nimport org.jclouds.rest.internal.BaseHttpApiMetadata;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\nimport static org.jclouds.compute.config.ComputeServiceProperties.TEMPLATE;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_RUNNING;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_SUSPENDED;\nimport static org.jclouds.reflect.Reflection2.typeToken;\n\n/**\n * Implementation of {@link ApiMetadata} for Packet API\n */\npublic class PacketApiMetadata extends BaseHttpApiMetadata<PacketApi> {\n\n   @Override\n   public Builder toBuilder() {\n      return new Builder().fromApiMetadata(this);\n   }\n\n   public PacketApiMetadata() {\n      this(new Builder());\n   }\n\n   protected PacketApiMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = BaseHttpApiMetadata.defaultProperties();\n      properties.put(TEMPLATE, \"osFamily=UBUNTU,os64Bit=true,osVersionMatches=16.*\");\n      properties.put(TIMEOUT_NODE_RUNNING, 900000); // 15 mins\n      properties.put(TIMEOUT_NODE_SUSPENDED, 900000); // 15 mins\n      return properties;\n   }\n\n   public static class Builder extends BaseHttpApiMetadata.Builder<PacketApi, Builder> {\n\n      protected Builder() {\n         id(\"packet\")\n                 .name(\"Packet API\")\n                 .identityName(\"Packet Project Id\")\n                 .credentialName(\"Must be Packet Token\")\n                 .documentation(URI.create(\"https://www.packet.net/help/api/#\"))\n                 .defaultEndpoint(\"https://api.packet.net\")\n                 .defaultProperties(PacketApiMetadata.defaultProperties())\n                 .version(\"1\")\n                 .view(typeToken(ComputeServiceContext.class))\n                 .defaultModules(ImmutableSet.<Class<? extends Module>>builder()\n                         .add(PacketHttpApiModule.class)\n                         .add(PacketComputeParserModule.class)\n                         .add(PacketComputeServiceContextModule.class)\n                         .build());\n      }\n\n      @Override\n      public PacketApiMetadata build() {\n         return new PacketApiMetadata(this);\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "providers/packet/src/main/java/org/jclouds/packet/PacketProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\n\nimport com.google.auto.service.AutoService;\n\n@AutoService(ProviderMetadata.class)\npublic class PacketProviderMetadata extends BaseProviderMetadata {\n\n    public static Builder builder() {\n        return new Builder();\n    }\n\n    @Override\n    public Builder toBuilder() {\n        return builder().fromProviderMetadata(this);\n    }\n\n    public PacketProviderMetadata() {\n        super(builder());\n    }\n\n    public PacketProviderMetadata(Builder builder) {\n        super(builder);\n    }\n\n    public static Properties defaultProperties() {\n        final Properties properties = PacketApiMetadata.defaultProperties();\n        return properties;\n    }\n\n    public static class Builder extends BaseProviderMetadata.Builder {\n\n        protected Builder() {\n            id(\"packet\")\n                    .name(\"Packet Compute Services\")\n                    .apiMetadata(new PacketApiMetadata())\n                    .homepage(URI.create(\"https://www.packet.net/\"))\n                    .console(URI.create(\"https://app.packet.net/portal\"))\n                    .endpoint(\"https://api.packet.net\")\n                    .iso3166Codes(\"US-CA\", \"US-NJ\", \"NL\", \"JP\")\n                    .defaultProperties(PacketProviderMetadata.defaultProperties());\n        }\n\n        @Override\n        public PacketProviderMetadata build() {\n            return new PacketProviderMetadata(this);\n        }\n\n        @Override\n        public Builder fromProviderMetadata(ProviderMetadata in) {\n            super.fromProviderMetadata(in);\n            return this;\n        }\n    }\n}\n\n\n"
  },
  {
    "path": "providers/packet/src/main/java/org/jclouds/packet/compute/PacketComputeServiceAdapter.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.compute;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.ComputeServiceAdapter;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.location.Provider;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.packet.PacketApi;\nimport org.jclouds.packet.compute.options.PacketTemplateOptions;\nimport org.jclouds.packet.domain.BillingCycle;\nimport org.jclouds.packet.domain.Device;\nimport org.jclouds.packet.domain.Facility;\nimport org.jclouds.packet.domain.OperatingSystem;\nimport org.jclouds.packet.domain.Plan;\n\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.Iterables;\n\nimport static com.google.common.collect.Iterables.contains;\nimport static com.google.common.collect.Iterables.filter;\n\n/**\n * defines the connection between the {@link org.jclouds.packet.PacketApi} implementation and\n * the jclouds {@link org.jclouds.compute.ComputeService}\n */\n@Singleton\npublic class PacketComputeServiceAdapter implements ComputeServiceAdapter<Device, Plan, OperatingSystem, Facility> {\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   private final PacketApi api;\n   private final String projectId;\n\n   @Inject\n   PacketComputeServiceAdapter(PacketApi api, @Provider final Supplier<Credentials> creds) {\n      this.api = api;\n      this.projectId = creds.get().identity;\n   }\n\n   @Override\n   public NodeAndInitialCredentials<Device> createNodeWithGroupEncodedIntoName(String group, String name, Template template) {\n\n      PacketTemplateOptions templateOptions = template.getOptions().as(PacketTemplateOptions.class);\n      Map<String, String> features = templateOptions.getFeatures();\n      BillingCycle billingCycle = BillingCycle.fromValue(templateOptions.getBillingCycle());\n      boolean locked = templateOptions.isLocked();\n      String userdata = templateOptions.getUserData();\n      Set<String> tags = templateOptions.getTags();\n\n      String plan = template.getHardware().getId();\n      String facility = template.getLocation().getId();\n      String operatingSystem = template.getImage().getId();\n\n      Device device = api.deviceApi(projectId).create(\n              Device.CreateDevice.builder()\n                      .hostname(name)\n                      .plan(plan)\n                      .billingCycle(billingCycle.value())\n                      .facility(facility)\n                      .features(features)\n                      .operatingSystem(operatingSystem)\n                      .locked(locked)\n                      .userdata(userdata)\n                      .tags(tags)\n                      .build()\n              );\n\n      // Any new servers you deploy to projects you are a collaborator on will have your project and personal SSH keys, if defined.\n      // If no SSH keys are defined in your account, jclouds will generate one usiing CreateSshKeysThenCreateNodes \n      // so that it will add it to the device with the default mechanism.\n\n      // Safe to pass null credentials here, as jclouds will default populate\n      // the node with the default credentials from the image, or the ones in\n      // the options, if provided.\n      return new NodeAndInitialCredentials<Device>(device, device.id(), null);\n   }\n\n   @Override\n   public Iterable<Plan> listHardwareProfiles() {\n      return Iterables.filter(api.planApi().list().concat(), new Predicate<Plan>() {\n         @Override\n         public boolean apply(Plan input) {\n            return input.line().equals(\"baremetal\");\n         }\n      });\n   }\n\n   @Override\n   public Iterable<OperatingSystem> listImages() {\n      return api.operatingSystemApi().list().concat();\n   }\n\n   @Override\n   public OperatingSystem getImage(final String id) {\n      Optional<OperatingSystem> firstInterestingOperatingSystem = api\n              .operatingSystemApi().list()\n              .concat()\n              .firstMatch(new Predicate<OperatingSystem>() {\n                 @Override\n                 public boolean apply(OperatingSystem input) {\n                    return input.slug().equals(id);\n                 }\n              });\n      if (!firstInterestingOperatingSystem.isPresent()) {\n         throw new IllegalStateException(\"Cannot find image with the required slug \" + id);\n      }\n      return firstInterestingOperatingSystem.get();\n   }\n\n   @Override\n   public Iterable<Facility> listLocations() {\n      return api.facilityApi().list().concat();\n   }\n\n   @Override\n   public Device getNode(String id) {\n      return api.deviceApi(projectId).get(id);\n   }\n\n   @Override\n   public void destroyNode(String id) {\n      api.deviceApi(projectId).delete(id);\n   }\n\n   @Override\n   public void rebootNode(String id) {\n      api.deviceApi(projectId).reboot(id);\n   }\n\n   @Override\n   public void resumeNode(String id) {\n      api.deviceApi(projectId).powerOn(id);\n   }\n\n   @Override\n   public void suspendNode(String id) {\n      api.deviceApi(projectId).powerOff(id);\n   }\n\n   @Override\n   public Iterable<Device> listNodes() {\n     return api.deviceApi(projectId).list().concat();\n   }\n\n   @Override\n   public Iterable<Device> listNodesByIds(final Iterable<String> ids) {\n      return filter(listNodes(), new Predicate<Device>() {\n         @Override\n         public boolean apply(Device device) {\n            return contains(ids, String.valueOf(device.id()));\n         }\n      });\n   }\n\n}\n"
  },
  {
    "path": "providers/packet/src/main/java/org/jclouds/packet/compute/config/PacketComputeServiceContextModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.compute.config;\n\nimport org.jclouds.compute.ComputeServiceAdapter;\nimport org.jclouds.compute.config.ComputeServiceAdapterContextModule;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.functions.NodeAndTemplateOptionsToStatement;\nimport org.jclouds.compute.functions.NodeAndTemplateOptionsToStatementWithoutPublicKey;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.compute.strategy.CreateNodesInGroupThenAddToSet;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.domain.Location;\nimport org.jclouds.location.Provider;\nimport org.jclouds.packet.PacketApi;\nimport org.jclouds.packet.compute.PacketComputeServiceAdapter;\nimport org.jclouds.packet.compute.functions.DeviceStateToStatus;\nimport org.jclouds.packet.compute.functions.DeviceToNodeMetadata;\nimport org.jclouds.packet.compute.functions.FacilityToLocation;\nimport org.jclouds.packet.compute.functions.OperatingSystemToImage;\nimport org.jclouds.packet.compute.functions.PlanToHardware;\nimport org.jclouds.packet.compute.options.PacketTemplateOptions;\nimport org.jclouds.packet.compute.strategy.CreateSshKeysThenCreateNodes;\nimport org.jclouds.packet.domain.Device;\nimport org.jclouds.packet.domain.Facility;\nimport org.jclouds.packet.domain.OperatingSystem;\nimport org.jclouds.packet.domain.Plan;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.inject.Provides;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.name.Named;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_RUNNING;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_SUSPENDED;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_TERMINATED;\nimport static org.jclouds.util.Predicates2.retry;\n\npublic class PacketComputeServiceContextModule extends\n        ComputeServiceAdapterContextModule<Device, Plan, OperatingSystem, Facility> {\n\n   @Override\n   protected void configure() {\n      super.configure();\n\n      bind(new TypeLiteral<ComputeServiceAdapter<Device, Plan, OperatingSystem, Facility>>() {\n      }).to(PacketComputeServiceAdapter.class);\n\n      bind(new TypeLiteral<Function<Device, NodeMetadata>>() {\n      }).to(DeviceToNodeMetadata.class);\n      bind(new TypeLiteral<Function<Plan, Hardware>>() {\n      }).to(PlanToHardware.class);\n      bind(new TypeLiteral<Function<OperatingSystem, Image>>() {\n      }).to(OperatingSystemToImage.class);\n      bind(new TypeLiteral<Function<Facility, Location>>() {\n      }).to(FacilityToLocation.class);\n      bind(new TypeLiteral<Function<Device.State, NodeMetadata.Status>>() {\n      }).to(DeviceStateToStatus.class);\n      install(new LocationsFromComputeServiceAdapterModule<Device, Plan, OperatingSystem, Facility>() {\n      });\n      bind(TemplateOptions.class).to(PacketTemplateOptions.class);\n      bind(CreateNodesInGroupThenAddToSet.class).to(CreateSshKeysThenCreateNodes.class);\n      bind(NodeAndTemplateOptionsToStatement.class).to(NodeAndTemplateOptionsToStatementWithoutPublicKey.class);\n   }\n\n   @Provides\n   @Named(TIMEOUT_NODE_RUNNING)\n   protected Predicate<String> provideDeviceRunningPredicate(final PacketApi api,\n                                                             @Provider final Supplier<Credentials> creds,\n                                                             ComputeServiceConstants.Timeouts timeouts,\n                                                             ComputeServiceConstants.PollPeriod pollPeriod) {\n      return retry(new DeviceInStatusPredicate(api, creds.get().identity, Device.State.ACTIVE), timeouts.nodeRunning,\n              pollPeriod.pollInitialPeriod, pollPeriod.pollMaxPeriod);\n   }\n\n   @Provides\n   @Named(TIMEOUT_NODE_SUSPENDED)\n   protected Predicate<String> provideDeviceSuspendedPredicate(final PacketApi api, @Provider final Supplier<Credentials> creds, ComputeServiceConstants.Timeouts timeouts,\n                                                                 ComputeServiceConstants.PollPeriod pollPeriod) {\n      return retry(new DeviceInStatusPredicate(api, creds.get().identity, Device.State.INACTIVE), timeouts.nodeSuspended,\n              pollPeriod.pollInitialPeriod, pollPeriod.pollMaxPeriod);\n   }\n   \n   @Provides\n   @Named(TIMEOUT_NODE_TERMINATED)\n   protected Predicate<String> provideDeviceTerminatedPredicate(final PacketApi api, @Provider final Supplier<Credentials> creds, ComputeServiceConstants.Timeouts timeouts,\n                                                                 ComputeServiceConstants.PollPeriod pollPeriod) {\n      return retry(new DeviceTerminatedPredicate(api, creds.get().identity), timeouts.nodeTerminated, pollPeriod.pollInitialPeriod,\n              pollPeriod.pollMaxPeriod);\n   }\n\n   @VisibleForTesting\n   static class DeviceInStatusPredicate implements Predicate<String> {\n\n      private final PacketApi api;\n      private final String projectId;\n      private final Device.State state;\n\n      public DeviceInStatusPredicate(PacketApi api, String projectId, Device.State state) {\n         this.api = checkNotNull(api, \"api must not be null\");\n         this.projectId = checkNotNull(projectId, \"projectId must not be null\");\n         this.state = checkNotNull(state, \"state must not be null\");\n      }\n\n      @Override\n      public boolean apply(String input) {\n         checkNotNull(input, \"device id\");\n         Device device = api.deviceApi(projectId).get(input);\n         return device != null && state == device.state();\n      }\n   }\n\n   @VisibleForTesting\n   static class DeviceTerminatedPredicate implements Predicate<String> {\n\n      private final PacketApi api;\n      private final String projectId;\n\n      public DeviceTerminatedPredicate(PacketApi api, String projectId) {\n         this.api = checkNotNull(api, \"api must not be null\");\n         this.projectId = checkNotNull(projectId, \"projectId must not be null\");\n      }\n\n      @Override\n      public boolean apply(String input) {\n         checkNotNull(input, \"device id\");\n         Device device = api.deviceApi(projectId).get(input);\n         return device == null;\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/packet/src/main/java/org/jclouds/packet/compute/functions/DeviceStateToStatus.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.compute.functions;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.domain.NodeMetadata.Status;\nimport org.jclouds.packet.domain.Device;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Functions;\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Transforms an {@link Device.State} to the jclouds portable model.\n */\n@Singleton\npublic class DeviceStateToStatus implements Function<Device.State, Status> {\n\n   private static final Function<Device.State, Status> toPortableStatus = Functions.forMap(\n         ImmutableMap.<Device.State, Status> builder()\n                 .put(Device.State.PROVISIONING, Status.PENDING)\n                 .put(Device.State.POWERING_ON, Status.PENDING)\n                 .put(Device.State.POWERING_OFF, Status.PENDING)\n                 .put(Device.State.REBOOTING, Status.PENDING)\n                 .put(Device.State.QUEUED, Status.PENDING)\n                 .put(Device.State.INACTIVE, Status.SUSPENDED)\n                 .put(Device.State.ACTIVE, Status.RUNNING)\n               .build(),\n         Status.UNRECOGNIZED);\n\n   @Override\n   public Status apply(final Device.State input) {\n      return toPortableStatus.apply(input);\n   }\n}\n"
  },
  {
    "path": "providers/packet/src/main/java/org/jclouds/packet/compute/functions/DeviceToNodeMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.compute.functions;\n\nimport java.util.List;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadataBuilder;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.packet.domain.Device;\nimport org.jclouds.packet.domain.IpAddress;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Predicates;\n\nimport static com.google.common.collect.FluentIterable.from;\n\n/**\n * Transforms an {@link Device} to the jclouds portable model.\n */\n@Singleton\npublic class DeviceToNodeMetadata implements Function<Device, NodeMetadata> {\n\n    @Resource\n    @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n    protected Logger logger = Logger.NULL;\n\n    private final PlanToHardware planToHardware;\n    private final OperatingSystemToImage operatingSystemToImage;\n    private final FacilityToLocation facilityToLocation;\n    private final Function<Device.State, NodeMetadata.Status> toPortableStatus;\n    private final GroupNamingConvention groupNamingConvention;\n\n    @Inject\n    DeviceToNodeMetadata(PlanToHardware planToHardware, OperatingSystemToImage operatingSystemToImage, FacilityToLocation facilityToLocation,\n                         Function<Device.State, NodeMetadata.Status> toPortableStatus,\n                         GroupNamingConvention.Factory groupNamingConvention) {\n        this.planToHardware = planToHardware;\n        this.operatingSystemToImage = operatingSystemToImage;\n        this.facilityToLocation = facilityToLocation;\n        this.toPortableStatus = toPortableStatus;\n        this.groupNamingConvention = groupNamingConvention.createWithoutPrefix();\n    }\n\n   @Override\n   public NodeMetadata apply(Device input) {\n      return new NodeMetadataBuilder()\n              .ids(input.id())\n              .name(input.hostname())\n              .hostname(String.format(\"%s\", input.hostname()))  \n              .group(groupNamingConvention.extractGroup(input.hostname()))\n              .location(facilityToLocation.apply(input.facility()))\n              .hardware(planToHardware.apply(input.plan()))\n              .imageId(input.operatingSystem().slug())\n              .operatingSystem(operatingSystemToImage.apply(input.operatingSystem()).getOperatingSystem())\n              .status(toPortableStatus.apply(input.state()))\n              .publicAddresses(getPublicIpAddresses(input.ipAddresses()))\n              .privateAddresses(getPrivateIpAddresses(input.ipAddresses()))\n              .tags(input.tags())\n              .build();\n   }\n\n   private Iterable<String> getPublicIpAddresses(List<IpAddress> input) {\n      return filterAndTransformIpAddresses(input, new IsPublicIpAddress());\n   }\n\n   private Iterable<String> getPrivateIpAddresses(List<IpAddress> input) {\n      return filterAndTransformIpAddresses(input, Predicates.not(new IsPublicIpAddress()));\n   }\n\n   private Iterable<String> filterAndTransformIpAddresses(List<IpAddress> input, Predicate<IpAddress> filter) {\n      return from(input).filter(filter).transform(new IpAddressToIp());\n   }\n\n   private static class IpAddressToIp implements Function<IpAddress, String> {\n        @Override\n        public String apply(final IpAddress input) {\n            return input.address();\n        }\n    }\n\n    private static class IsPublicIpAddress implements Predicate<IpAddress> {\n        @Override\n        public boolean apply(IpAddress input) {\n            return input.publicAddress();\n        }\n    }\n}\n"
  },
  {
    "path": "providers/packet/src/main/java/org/jclouds/packet/compute/functions/FacilityToLocation.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.compute.functions;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.location.suppliers.all.JustProvider;\nimport org.jclouds.packet.domain.Facility;\n\nimport com.google.common.base.Function;\n\nimport static com.google.common.collect.Iterables.getOnlyElement;\n\n/**\n * Transforms an {@link Facility} to the jclouds portable model.\n */\n@Singleton\npublic class FacilityToLocation implements Function<Facility, Location> {\n\n    private final JustProvider justProvider;\n\n    // allow us to lazy discover the provider of a resource\n    @Inject\n    FacilityToLocation(JustProvider justProvider) {\n        this.justProvider = justProvider;\n    }\n\n    @Override\n    public Location apply(final Facility facility) {\n        final LocationBuilder builder = new LocationBuilder();\n        builder.id(facility.code());\n        builder.description(facility.name());\n        builder.parent(getOnlyElement(justProvider.get()));\n        builder.scope(LocationScope.REGION);\n        return builder.build();\n    }\n}\n"
  },
  {
    "path": "providers/packet/src/main/java/org/jclouds/packet/compute/functions/OperatingSystemToImage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.compute.functions;\n\nimport static com.google.common.collect.Iterables.tryFind;\nimport static java.util.Arrays.asList;\nimport static org.jclouds.compute.domain.OperatingSystem.builder;\n\nimport java.util.Map;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.ImageBuilder;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.packet.domain.OperatingSystem;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Transforms an {@link OperatingSystem} to the jclouds portable model.\n */\n@Singleton\npublic class OperatingSystemToImage implements Function<OperatingSystem, Image> {\n\n    private static final Map<String, OsFamily> OTHER_OS_MAP = ImmutableMap.<String, OsFamily> builder()\n        .put(\"nixos\", OsFamily.LINUX)\n        .put(\"rancher\", OsFamily.LINUX)\n        .put(\"vmware\", OsFamily.ESX)\n        .build();\n    \n    @Override\n    public Image apply(final OperatingSystem input) {\n        ImageBuilder builder = new ImageBuilder();\n        builder.ids(input.slug());\n        builder.name(input.name());\n        builder.description(input.name());\n        builder.status(Image.Status.AVAILABLE);\n        \n      OsFamily family = findInStandardFamilies(input.distribution())\n          .or(findInOtherOSMap(input.distribution()))\n          .or(OsFamily.UNRECOGNIZED);\n\n        builder.operatingSystem(builder()\n                .name(input.name())\n                .family(family)\n                .description(input.name())\n                .version(input.version())\n                .is64Bit(true)\n                .build());\n\n        return builder.build();\n    }\n    \n    private static Optional<OsFamily> findInStandardFamilies(final String label) {\n        return tryFind(asList(OsFamily.values()), new Predicate<OsFamily>() {\n           @Override\n           public boolean apply(OsFamily input) {\n              return label.contains(input.value());\n           }\n        });\n     }\n\n     private static Optional<OsFamily> findInOtherOSMap(final String label) {\n        return tryFind(OTHER_OS_MAP.keySet(), new Predicate<String>() {\n           @Override\n           public boolean apply(String input) {\n              return label.contains(input);\n           }\n        }).transform(new Function<String, OsFamily>() {\n           @Override\n           public OsFamily apply(String input) {\n              return OTHER_OS_MAP.get(input);\n           }\n        });\n     }\n}\n"
  },
  {
    "path": "providers/packet/src/main/java/org/jclouds/packet/compute/functions/PlanToHardware.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.compute.functions;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.HardwareBuilder;\nimport org.jclouds.compute.domain.Processor;\nimport org.jclouds.compute.domain.Volume;\nimport org.jclouds.compute.domain.internal.VolumeImpl;\nimport org.jclouds.packet.domain.Plan;\nimport org.jclouds.packet.domain.Specs;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Lists;\n\n/**\n * Transforms an {@link Plan} to the jclouds portable model.\n */\n@Singleton\npublic class PlanToHardware implements Function<Plan, Hardware> {\n\n    @Override\n    public Hardware apply(Plan plan) {\n        HardwareBuilder builder = new HardwareBuilder()\n                .ids(plan.slug())\n                .name(plan.name())\n                .hypervisor(\"none\")\n                .processors(getProcessors(plan))\n                .ram(getMemory(plan))\n                .volumes(getVolumes(plan));\n        return builder.build();\n    }\n\n    private Integer getMemory(Plan plan) {\n        if (plan.specs() == null || plan.specs().drives() == null) return 0;\n        String total = plan.specs().memory().total();\n        if (total.endsWith(\"GB\")) {\n            return Integer.valueOf(total.substring(0, total.length() - 2)) * 1024;\n        } else {\n            throw new IllegalArgumentException(\"Cannot parse memory: \" + plan.specs().memory());\n        }\n    }\n\n    private Iterable<Volume> getVolumes(Plan plan) {\n        if (plan.specs() == null || plan.specs().drives() == null) return Lists.newArrayList();\n\n        return Iterables.transform(plan.specs().drives(), new Function<Specs.Drive, Volume>() {\n            @Override\n            public Volume apply(Specs.Drive drive) {\n                return new VolumeImpl(\n                        drive.type(),\n                        Volume.Type.LOCAL,\n                        Float.parseFloat(drive.size().substring(0, drive.size().length() - 2)), null, true, false);\n            }\n        });\n    }\n\n\n    private Iterable<Processor> getProcessors(Plan plan) {\n        if (plan.specs() == null || plan.specs().cpus() == null) return Lists.newArrayList();\n        return Iterables.transform(plan.specs().cpus(), new Function<Specs.CPU, Processor>() {\n            @Override\n            public Processor apply(Specs.CPU input) {\n                // No cpu speed from Packet API, so assume more cores == faster\n                return new Processor(input.count(), input.count()); \n            }\n        });\n    }\n}\n"
  },
  {
    "path": "providers/packet/src/main/java/org/jclouds/packet/compute/options/PacketTemplateOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.compute.options;\n\nimport java.util.Map;\n\nimport org.jclouds.compute.options.TemplateOptions;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\nimport com.google.common.collect.ImmutableMap;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\n/**\n * Custom options for the Packet API.\n */\npublic class PacketTemplateOptions extends TemplateOptions implements Cloneable {\n\n   private Map<String, String> features = ImmutableMap.of();\n   private boolean locked = false;\n   private String billingCycle = \"hourly\";\n   private String userData = \"\";\n\n   public PacketTemplateOptions features(Map<String, String> features) {\n      this.features = ImmutableMap.copyOf(checkNotNull(features, \"features cannot be null\"));\n      return this;\n   }\n   \n   public PacketTemplateOptions locked(boolean locked) {\n      this.locked = locked;\n      return this;\n   }\n\n   public PacketTemplateOptions billingCycle(String billingCycle) {\n      this.billingCycle = billingCycle;\n      return this;\n   }\n   \n   public PacketTemplateOptions userData(String userData) {\n      this.userData = userData;\n      return this;\n   }\n\n   public Map<String, String> getFeatures() {\n      return features;\n   }\n   public boolean isLocked() {\n      return locked;\n   }\n   public String getBillingCycle() {\n      return billingCycle;\n   }\n   public String getUserData() {\n      return userData;\n   }\n\n   @Override\n   public PacketTemplateOptions clone() {\n      PacketTemplateOptions options = new PacketTemplateOptions();\n      copyTo(options);\n      return options;\n   }\n\n   @Override\n   public void copyTo(TemplateOptions to) {\n      super.copyTo(to);\n      if (to instanceof PacketTemplateOptions) {\n         PacketTemplateOptions eTo = PacketTemplateOptions.class.cast(to);\n         eTo.features(features);\n         eTo.locked(locked);\n         eTo.billingCycle(billingCycle);\n         eTo.userData(userData);\n      }\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(super.hashCode(), features, locked, billingCycle, userData);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) {\n         return true;\n      }\n      if (!super.equals(obj)) {\n         return false;\n      }\n      if (getClass() != obj.getClass()) {\n         return false;\n      }\n      PacketTemplateOptions other = (PacketTemplateOptions) obj;\n      return super.equals(other) && equal(this.locked, other.locked) && equal(this.billingCycle, other.billingCycle) && equal(this.userData, other.userData) && equal(this.features, other.features);\n   }\n\n   @Override\n   public ToStringHelper string() {\n      ToStringHelper toString = super.string().omitNullValues();\n      if (!features.isEmpty()) {\n         toString.add(\"features\", features);\n      }      toString.add(\"locked\", locked);\n      toString.add(\"billingCycle\", billingCycle);\n      toString.add(\"userData\", userData);\n      return toString;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see PacketTemplateOptions#features\n       */\n      public static PacketTemplateOptions features(Map<String, String> features) {\n         PacketTemplateOptions options = new PacketTemplateOptions();\n         return options.features(features);\n      }\n      \n      /**\n       * @see PacketTemplateOptions#locked\n       */\n      public static PacketTemplateOptions locked(boolean locked) {\n         PacketTemplateOptions options = new PacketTemplateOptions();\n         return options.locked(locked);\n      }\n\n      /**\n       * @see PacketTemplateOptions#billingCycle\n       */\n      public static PacketTemplateOptions billingCycle(String billingCycle) {\n         PacketTemplateOptions options = new PacketTemplateOptions();\n         return options.billingCycle(billingCycle);\n      }\n      \n      /**\n       * @see PacketTemplateOptions#userData\n       */\n      public static PacketTemplateOptions userData(String userData) {\n         PacketTemplateOptions options = new PacketTemplateOptions();\n         return options.userData(userData);\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/packet/src/main/java/org/jclouds/packet/compute/strategy/CreateSshKeysThenCreateNodes.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.compute.strategy;\n\nimport java.security.KeyFactory;\nimport java.security.NoSuchAlgorithmException;\nimport java.security.PublicKey;\nimport java.security.interfaces.RSAPublicKey;\nimport java.security.spec.InvalidKeySpecException;\nimport java.security.spec.RSAPublicKeySpec;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.Constants;\nimport org.jclouds.compute.config.CustomizationResponse;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.compute.strategy.CreateNodeWithGroupEncodedIntoName;\nimport org.jclouds.compute.strategy.CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap;\nimport org.jclouds.compute.strategy.ListNodesStrategy;\nimport org.jclouds.compute.strategy.impl.CreateNodesWithGroupEncodedIntoNameThenAddToSet;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.packet.PacketApi;\nimport org.jclouds.packet.compute.options.PacketTemplateOptions;\nimport org.jclouds.packet.domain.SshKey;\nimport org.jclouds.ssh.SshKeyPairGenerator;\nimport org.jclouds.ssh.SshKeys;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Splitter;\nimport com.google.common.base.Strings;\nimport com.google.common.collect.Multimap;\nimport com.google.common.collect.Sets;\nimport com.google.common.util.concurrent.FutureCallback;\nimport com.google.common.util.concurrent.Futures;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.ListeningExecutorService;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Throwables.propagate;\nimport static com.google.common.collect.Iterables.get;\nimport static com.google.common.collect.Iterables.size;\n\n@Singleton\npublic class CreateSshKeysThenCreateNodes extends CreateNodesWithGroupEncodedIntoNameThenAddToSet {\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   private final PacketApi api;\n   private final SshKeyPairGenerator keyGenerator;\n\n   @Inject\n   protected CreateSshKeysThenCreateNodes(\n         CreateNodeWithGroupEncodedIntoName addNodeWithGroupStrategy,\n         ListNodesStrategy listNodesStrategy,\n         GroupNamingConvention.Factory namingConvention,\n         @Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor,\n         CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap.Factory customizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapFactory,\n         PacketApi api, SshKeyPairGenerator keyGenerator) {\n      super(addNodeWithGroupStrategy, listNodesStrategy, namingConvention, userExecutor,\n            customizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapFactory);\n      this.api = api;\n      this.keyGenerator = keyGenerator;\n   }\n\n   @Override\n   public Map<?, ListenableFuture<Void>> execute(String group, int count, Template template,\n         Set<NodeMetadata> goodNodes, Map<NodeMetadata, Exception> badNodes,\n         Multimap<NodeMetadata, CustomizationResponse> customizationResponses) {\n\n      PacketTemplateOptions options = template.getOptions().as(PacketTemplateOptions.class);\n      Set<String> generatedSshKeyIds = Sets.newHashSet();\n\n      // If no key has been configured, generate a key pair\n      if (Strings.isNullOrEmpty(options.getPublicKey())) {\n         generateKeyPairAndAddKeyToSet(options, generatedSshKeyIds, group);\n      }\n\n      // If there is a script to run in the node, make sure a private key has\n      // been configured so jclouds will be able to access the node\n      if (options.getRunScript() != null && Strings.isNullOrEmpty(options.getLoginPrivateKey())) {\n         logger.warn(\">> A runScript has been configured but no SSH key has been provided.\"\n               + \" Authentication will delegate to the ssh-agent\");\n      }\n\n      // If there is a key configured, then make sure there is a key pair for it\n      if (!Strings.isNullOrEmpty(options.getPublicKey())) {\n         createKeyPairForPublicKeyInOptionsAndAddToSet(options, generatedSshKeyIds);\n      }\n\n      Map<?, ListenableFuture<Void>> responses = super.execute(group, count, template, goodNodes, badNodes,\n            customizationResponses);\n\n      // Key pairs in Packet are only required to create the devices. They\n      // aren't used anymore so it is better\n      // to delete the auto-generated key pairs at this point where we know\n      // exactly which ones have been\n      // auto-generated by jclouds.\n      registerAutoGeneratedKeyPairCleanupCallbacks(responses, generatedSshKeyIds);\n\n      return responses;\n   }\n\n   private void createKeyPairForPublicKeyInOptionsAndAddToSet(PacketTemplateOptions options,\n         Set<String> generatedSshKeyIds) {\n      logger.debug(\">> checking if the key pair already exists...\");\n\n      PublicKey userKey = readPublicKey(options.getPublicKey());\n      final String fingerprint = computeFingerprint(userKey);\n\n      synchronized (CreateSshKeysThenCreateNodes.class) {\n         boolean keyExists = api.sshKeyApi().list().concat().anyMatch(new Predicate<SshKey>() {\n            @Override\n            public boolean apply(SshKey input) {\n               return input.fingerprint().equals(fingerprint);\n            }\n         });\n\n         if (!keyExists) {\n            logger.debug(\">> key pair not found. creating a new key pair %s ...\", fingerprint);\n            SshKey newKey = api.sshKeyApi().create(fingerprint, options.getPublicKey());\n            logger.debug(\">> key pair created! %s\", newKey);\n            generatedSshKeyIds.add(newKey.id());\n         } else {\n            logger.debug(\">> key pair found for key %s\", fingerprint);\n         }\n      }\n   }\n\n   private static PublicKey readPublicKey(String publicKey) {\n      Iterable<String> parts = Splitter.on(' ').split(publicKey);\n      checkArgument(size(parts) >= 2, \"bad format, should be: ssh-rsa AAAAB3...\");\n      String type = get(parts, 0);\n\n      try {\n         if (\"ssh-rsa\".equals(type)) {\n            RSAPublicKeySpec spec = SshKeys.publicKeySpecFromOpenSSH(publicKey);\n            return KeyFactory.getInstance(\"RSA\").generatePublic(spec);\n         } else {\n            throw new IllegalArgumentException(\"bad format, ssh-rsa is only supported\");\n         }\n      } catch (InvalidKeySpecException ex) {\n         throw propagate(ex);\n      } catch (NoSuchAlgorithmException ex) {\n         throw propagate(ex);\n      }\n   }\n\n   private void generateKeyPairAndAddKeyToSet(PacketTemplateOptions options, Set<String> generatedSshKeyIds,\n         String prefix) {\n      logger.debug(\">> creating default keypair for node...\");\n\n      Map<String, String> defaultKeys = keyGenerator.get();\n\n      SshKey sshKey = api.sshKeyApi().create(namingConvention.create().uniqueNameForGroup(prefix),\n            defaultKeys.get(\"public\"));\n      generatedSshKeyIds.add(sshKey.id());\n      logger.debug(\">> keypair created! %s\", sshKey);\n\n      // If a private key has not been explicitly set, configure the generated\n      // one\n      if (Strings.isNullOrEmpty(options.getLoginPrivateKey())) {\n         options.overrideLoginPrivateKey(defaultKeys.get(\"private\"));\n      }\n   }\n\n   private void registerAutoGeneratedKeyPairCleanupCallbacks(Map<?, ListenableFuture<Void>> responses,\n         final Set<String> generatedSshKeyIds) {\n      // The Futures.allAsList fails immediately if some of the futures fail.\n      // The Futures.successfulAsList, however,\n      // returns a list containing the results or 'null' for those futures that\n      // failed. We want to wait for all them\n      // (even if they fail), so better use the latter form.\n      ListenableFuture<List<Void>> aggregatedResponses = Futures.successfulAsList(responses.values());\n\n      // Key pairs must be cleaned up after all futures completed (even if some\n      // failed).\n      Futures.addCallback(aggregatedResponses, new FutureCallback<List<Void>>() {\n         @Override\n         public void onSuccess(List<Void> result) {\n            cleanupAutoGeneratedKeyPairs(generatedSshKeyIds);\n         }\n\n         @Override\n         public void onFailure(Throwable t) {\n            cleanupAutoGeneratedKeyPairs(generatedSshKeyIds);\n         }\n\n         private void cleanupAutoGeneratedKeyPairs(Set<String> generatedSshKeyIds) {\n            logger.debug(\">> cleaning up auto-generated key pairs...\");\n            for (String sshKeyId : generatedSshKeyIds) {\n               try {\n                  api.sshKeyApi().delete(sshKeyId);\n               } catch (Exception ex) {\n                  logger.warn(\">> could not delete key pair %s: %s\", sshKeyId, ex.getMessage());\n               }\n            }\n         }\n      }, userExecutor);\n   }\n\n   private static String computeFingerprint(PublicKey key) {\n      if (key instanceof RSAPublicKey) {\n         RSAPublicKey rsaKey = (RSAPublicKey) key;\n         return SshKeys.fingerprint(rsaKey.getPublicExponent(), rsaKey.getModulus());\n      } else {\n         throw new IllegalArgumentException(\"Only RSA keys are supported\");\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/packet/src/main/java/org/jclouds/packet/config/PacketComputeParserModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.config;\n\nimport org.jclouds.json.config.GsonModule;\n\nimport com.google.inject.AbstractModule;\n\npublic class PacketComputeParserModule extends AbstractModule {\n\n   @Override\n   protected void configure() {\n      bind(GsonModule.DateAdapter.class).to(GsonModule.Iso8601DateAdapter.class);\n   }\n\n}\n"
  },
  {
    "path": "providers/packet/src/main/java/org/jclouds/packet/config/PacketHttpApiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.config;\n\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.annotation.ClientError;\nimport org.jclouds.http.annotation.Redirection;\nimport org.jclouds.http.annotation.ServerError;\nimport org.jclouds.location.suppliers.ImplicitLocationSupplier;\nimport org.jclouds.location.suppliers.implicit.FirstRegion;\nimport org.jclouds.packet.PacketApi;\nimport org.jclouds.packet.domain.Href;\nimport org.jclouds.packet.domain.options.ListOptions;\nimport org.jclouds.packet.functions.HrefToListOptions;\nimport org.jclouds.packet.handlers.PacketErrorHandler;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.config.HttpApiModule;\n\nimport com.google.common.base.Function;\nimport com.google.inject.Scopes;\nimport com.google.inject.TypeLiteral;\n\n@ConfiguresHttpApi\npublic class PacketHttpApiModule extends HttpApiModule<PacketApi> {\n\n   @Override\n   protected void configure() {\n      super.configure();\n      bind(ImplicitLocationSupplier.class).to(FirstRegion.class).in(Scopes.SINGLETON);\n      bind(new TypeLiteral<Function<Href, ListOptions>>() {\n      }).to(HrefToListOptions.class);\n   }\n\n   @Override\n   protected void bindErrorHandlers() {\n      bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(PacketErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(PacketErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(PacketErrorHandler.class);\n   }\n\n}\n"
  },
  {
    "path": "providers/packet/src/main/java/org/jclouds/packet/domain/BillingCycle.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.domain;\n\nimport java.util.List;\n\nimport com.google.common.base.Predicate;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.tryFind;\nimport static java.util.Arrays.asList;\n\npublic enum BillingCycle {\n   HOURLY(\"hourly\"),\n   MONTHLY(\"monthly\"),\n   UNRECOGNIZED(\"\");\n\n   private static final List<BillingCycle> values = asList(BillingCycle.values());\n\n   private final String value;\n\n   private BillingCycle(String value) {\n      this.value = checkNotNull(value, \"value cannot be null\");\n   }\n\n   public String value() {\n      return this.value;\n   }\n\n   public static BillingCycle fromValue(String value) {\n      return tryFind(values, hasValue(value)).or(UNRECOGNIZED);\n   }\n\n   private static Predicate<BillingCycle> hasValue(final String value) {\n      return new Predicate<BillingCycle>() {\n         @Override\n         public boolean apply(BillingCycle input) {\n            return input.value.equalsIgnoreCase(value);\n         }\n      };\n   }\n}\n"
  },
  {
    "path": "providers/packet/src/main/java/org/jclouds/packet/domain/Device.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.domain;\n\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.base.Enums;\nimport com.google.common.base.Joiner;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\n\nimport static com.google.common.base.Preconditions.checkArgument;\n\n@AutoValue\npublic abstract class Device {\n\n    public enum State {\n        PROVISIONING, QUEUED, ACTIVE, REBOOTING, POWERING_OFF, POWERING_ON, INACTIVE;\n\n        public static State fromValue(String value) {\n            Optional<State> state = Enums.getIfPresent(State.class, value.toUpperCase());\n            checkArgument(state.isPresent(), \"Expected one of %s but was %s\", Joiner.on(',').join(State.values()), value);\n            return state.get();\n        }\n    }\n\n    public abstract String id();\n    public abstract String shortId();\n    public abstract String hostname();\n    @Nullable\n    public abstract String description();\n    public abstract State state();\n    public abstract List<String> tags();\n    public abstract String billingCycle();\n    public abstract String user();\n    public abstract String iqn();\n    public abstract Boolean locked();\n    public abstract String bondingMode();\n    public abstract Date createdAt();\n    public abstract Date updatedAt();\n    public abstract OperatingSystem operatingSystem();\n    public abstract Facility facility();\n    public abstract Href project();\n    public abstract List<Href> sshKeys();\n    public abstract Href projectLite();\n    public abstract List<Object> volumes();\n    public abstract List<IpAddress> ipAddresses();\n    public abstract List<ProvisioningEvent> provisioningEvents();\n    public abstract Plan plan();\n    @Nullable public abstract String rootPassword();\n    public abstract String userdata();\n    public abstract String href();\n\n    @SerializedNames({\"id\", \"short_id\", \"hostname\", \"description\", \"state\", \"tags\", \"billing_cycle\", \"user\", \"iqn\",\n            \"locked\", \"bonding_mode\", \"created_at\", \"updated_at\", \"operating_system\", \"facility\", \"project\", \"ssh_keys\",\n            \"project_lite\", \"volumes\", \"ip_addresses\", \"provisioning_events\", \"plan\", \"root_password\", \"userdata\", \"href\"})\n    public static Device create(String id,\n                                String shortId,\n                                String hostname,\n                                String description,\n                                State state,\n                                List<String> tags,\n                                String billingCycle,\n                                String user,\n                                String iqn,\n                                Boolean locked,\n                                String bondingMode,\n                                Date createdAt,\n                                Date updatedAt,\n                                OperatingSystem operatingSystem,\n                                Facility facility,\n                                Href project,\n                                List<Href> sshKeys,\n                                Href projectLite,\n                                List<Object> volumes,\n                                List<IpAddress> ipAddresses,\n                                List<ProvisioningEvent> provisioningEvents,\n                                Plan plan,\n                                String rootPassword,\n                                String userdata,\n                                String href\n    ) {\n        return new AutoValue_Device(id, shortId, hostname, description, state,\n                tags == null ? ImmutableList.<String> of() : ImmutableList.copyOf(tags),\n                billingCycle, user, iqn, locked, bondingMode, createdAt, updatedAt, operatingSystem, facility, project,\n                sshKeys == null ? ImmutableList.<Href> of() : ImmutableList.copyOf(sshKeys),\n                projectLite,\n                volumes == null ? ImmutableList.of() : ImmutableList.copyOf(volumes),\n                ipAddresses == null ? ImmutableList.<IpAddress>of() : ImmutableList.copyOf(ipAddresses),\n                provisioningEvents == null ? ImmutableList.<ProvisioningEvent> of() : ImmutableList.copyOf(provisioningEvents),\n                plan,\n                rootPassword, userdata, href\n        );\n    }\n\n    Device() {\n    }\n\n    @AutoValue\n    public abstract static class CreateDevice {\n\n        public abstract String hostname();\n        public abstract String plan();\n        public abstract String billingCycle();\n        public abstract String facility();\n        public abstract Map<String, String> features();\n        public abstract String operatingSystem();\n        public abstract Boolean locked();\n        public abstract String userdata();\n        public abstract Set<String> tags();\n\n        @SerializedNames({\"hostname\", \"plan\", \"billing_cycle\", \"facility\", \"features\", \"operating_system\",\n                \"locked\", \"userdata\", \"tags\" })\n        private static CreateDevice create(final String hostname, final String plan, final String billingCycle,\n                                          final String facility, final Map<String, String> features, final String operatingSystem,\n                                          final Boolean locked, final String userdata,\n                                          final Set<String> tags) {\n            return builder()\n                    .hostname(hostname)\n                    .plan(plan)\n                    .billingCycle(billingCycle)\n                    .facility(facility)\n                    .features(features)\n                    .operatingSystem(operatingSystem)\n                    .locked(locked)\n                    .userdata(userdata)\n                    .tags(tags)\n                    .build();\n        }\n\n        public static Builder builder() {\n            return new AutoValue_Device_CreateDevice.Builder();\n        }\n\n        @AutoValue.Builder\n        public abstract static class Builder {\n\n            public abstract Builder hostname(String hostname);\n            public abstract Builder plan(String plan);\n            public abstract Builder billingCycle(String billingCycle);\n            public abstract Builder facility(String facility);\n            public abstract Builder features(Map<String, String> features);\n            public abstract Builder operatingSystem(String operatingSystem);\n            public abstract Builder locked(Boolean locked);\n            public abstract Builder userdata(String userdata);\n            public abstract Builder tags(Set<String> tags);\n\n           abstract Map<String, String> features();\n           abstract Set<String> tags();\n\n           abstract CreateDevice autoBuild();\n\n           public CreateDevice build() {\n              return tags(tags() != null ? ImmutableSet.copyOf(tags()) : ImmutableSet.<String> of())\n                      .features(features() != null ? ImmutableMap.copyOf(features()) : ImmutableMap.<String, String> of())\n                      .autoBuild();\n           }\n        }\n    }\n\n}\n"
  },
  {
    "path": "providers/packet/src/main/java/org/jclouds/packet/domain/Facility.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.domain;\n\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\n\n@AutoValue\npublic abstract class Facility {\n\n    public abstract String id();\n    public abstract String name();\n    public abstract String code();\n    public abstract List<String> features();\n    @Nullable\n    public abstract Href address();\n\n    @SerializedNames({\"id\", \"name\", \"code\", \"features\", \"address\"})\n    public static Facility create(final String id, String name, String code, List<String> features, Href address) {\n        return new AutoValue_Facility(id, name, code,\n                features == null ? ImmutableList.<String> of() : ImmutableList.copyOf(features),\n                address);\n    }\n\n    Facility() {}\n}\n"
  },
  {
    "path": "providers/packet/src/main/java/org/jclouds/packet/domain/Href.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.domain;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class Href {\n\n    public abstract String href();\n\n    @SerializedNames({ \"href\" })\n    public static Href create(String href) {\n        return new AutoValue_Href(href);\n    }\n\n    Href() {}\n}\n"
  },
  {
    "path": "providers/packet/src/main/java/org/jclouds/packet/domain/IpAddress.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.domain;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class IpAddress {\n\n    public abstract String id();\n    public abstract Integer addressFamily();\n    public abstract String netmask();\n    public abstract Boolean publicAddress();\n    public abstract Integer cidr();\n    public abstract Boolean management();\n    public abstract Boolean manageable();\n    public abstract Href assignedTo();\n    public abstract String network();\n    public abstract String address();\n    public abstract String gateway();\n    public abstract String href();\n\n    @SerializedNames({\"id\", \"address_family\", \"netmask\", \"public\", \"cidr\", \"management\", \"manageable\", \"assigned_to\", \"network\", \"address\", \"gateway\", \"href\"})\n    public static IpAddress create(\n            String id,\n            Integer addressFamily,\n            String netmask,\n            Boolean publicAddress,\n            Integer cidr,\n            Boolean management,\n            Boolean manageable,\n            Href assignedTo,\n            String network,\n            String address,\n            String gateway,\n            String href\n    ) {\n        return new AutoValue_IpAddress(id, addressFamily, netmask, publicAddress, cidr, management, manageable, assignedTo, network, address, gateway, href\n        );\n    }\n\n    IpAddress() {}\n}\n"
  },
  {
    "path": "providers/packet/src/main/java/org/jclouds/packet/domain/OperatingSystem.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.domain;\n\nimport java.util.Set;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableSet;\n\n@AutoValue\npublic abstract class OperatingSystem {\n\n    public abstract String id();\n    public abstract String slug();\n    public abstract String name();\n    public abstract String distribution();\n    public abstract String version();\n    public abstract Set<String> provisionableOn();\n\n    @SerializedNames({\"id\", \"slug\", \"name\", \"distro\", \"version\", \"provisionable_on\"})\n    public static OperatingSystem create(String id, String slug, String name, String distribution, String version, Set<String> provisionableOn) {\n        return new AutoValue_OperatingSystem(id, slug, name, distribution, version,\n                provisionableOn == null ? ImmutableSet.<String> of() : ImmutableSet.copyOf(provisionableOn)\n        );\n    }\n\n    OperatingSystem() {}\n\n}\n"
  },
  {
    "path": "providers/packet/src/main/java/org/jclouds/packet/domain/Plan.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.domain;\n\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\n\n@AutoValue\npublic abstract class Plan {\n\n    public abstract String id();\n    public abstract String slug();\n    public abstract String name();\n    public abstract String description();\n    public abstract String line();\n    @Nullable\n    public abstract Specs specs();\n    public abstract List<Href> availableIn();\n    public abstract Pricing pricing();\n\n    @SerializedNames({\"id\", \"slug\", \"name\", \"description\", \"line\", \"specs\", \"available_in\", \"pricing\"})\n    public static Plan create(final String id, String slug, String name, String description, String line, Specs specs, List<Href> availableIn, Pricing pricing) {\n        return new AutoValue_Plan(id, slug, name, description, line,\n                specs,\n                availableIn == null ? ImmutableList.<Href> of() : ImmutableList.copyOf(availableIn),\n                pricing\n        );\n    }\n\n    Plan() {}\n}\n"
  },
  {
    "path": "providers/packet/src/main/java/org/jclouds/packet/domain/Pricing.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.domain;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class Pricing {\n\n    public abstract double hour();\n\n    @SerializedNames({ \"hour\" })\n    public static Pricing create(double hour) {\n        return new AutoValue_Pricing(hour);\n    }\n\n    Pricing() {}\n}\n"
  },
  {
    "path": "providers/packet/src/main/java/org/jclouds/packet/domain/Project.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.domain;\n\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\n\n@AutoValue\npublic abstract class Project {\n\n    public abstract String id();\n    public abstract String name();\n    public abstract Date createdAt();\n    public abstract Date updatedAt();\n    public abstract Map<String, Object> maxDevices();\n    public abstract List<Href> members();\n    public abstract List<Href> memberships();\n    public abstract List<Href> invitations();\n    public abstract Href paymentMethod();\n    public abstract List<Href> devices();\n    public abstract List<Href> sshKeys();\n    public abstract List<Href> volumes();\n    public abstract String href();\n\n    @SerializedNames({\"id\", \"name\", \"created_at\", \"updated_at\", \"max_devices\", \"members\", \"memberships\", \"invitations\", \"payment_method\", \"devices\", \"ssh_keys\", \"volumes\", \"href\"})\n    public static Project create(String id, String name, Date createdAt, Date updatedAt, Map<String, Object> maxDevices,\n                                 List<Href> members, List<Href> memberships, List<Href> invitations, Href paymentMethod,\n                                 List<Href> devices,\n                                 List<Href> sshKeys,\n                                 List<Href> volumes,\n                                 String href) {\n        return new AutoValue_Project(id, name, createdAt, updatedAt,\n                maxDevices == null ? ImmutableMap.<String, Object> of() : ImmutableMap.copyOf(maxDevices),\n                members == null ? ImmutableList.<Href> of() : ImmutableList.copyOf(members),\n                memberships == null ? ImmutableList.<Href> of() : ImmutableList.copyOf(memberships),\n                invitations == null ? ImmutableList.<Href> of() : ImmutableList.copyOf(invitations),\n                paymentMethod,\n                devices == null ? ImmutableList.<Href> of() : ImmutableList.copyOf(devices),\n                sshKeys == null ? ImmutableList.<Href> of() : ImmutableList.copyOf(sshKeys),\n                volumes == null ? ImmutableList.<Href> of() : ImmutableList.copyOf(volumes),\n                href);\n    }\n\n    Project() {}\n}\n"
  },
  {
    "path": "providers/packet/src/main/java/org/jclouds/packet/domain/ProvisioningEvent.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.domain;\n\nimport java.util.Date;\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\n\n@AutoValue\npublic abstract class ProvisioningEvent {\n\n   @Nullable\n   public abstract String id();\n   public abstract String type();\n   public abstract String body();\n   @Nullable\n   public abstract Date createdAt();\n   public abstract List<Href> relationships();\n   public abstract String interpolated();\n   @Nullable\n   public abstract String href();\n\n   @SerializedNames({\"id\", \"type\", \"body\", \"created_at\", \"relationships\", \"interpolated\", \"href\"})\n   public static ProvisioningEvent create(String id, String type, String body, Date createdAt,\n                                          List<Href> relationships, String interpolated, String href) {\n      return new AutoValue_ProvisioningEvent(id, type, body, createdAt,\n              relationships == null ? ImmutableList.<Href> of() : ImmutableList.copyOf(relationships),\n              interpolated,\n              href);\n   }\n\n   ProvisioningEvent() {}\n}\n"
  },
  {
    "path": "providers/packet/src/main/java/org/jclouds/packet/domain/Specs.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.domain;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\n\n@AutoValue\npublic abstract class Specs {\n\n    @AutoValue\n    public abstract static class NIC {\n\n        public abstract Integer count();\n        public abstract String type();\n\n        @SerializedNames({ \"count\", \"type\" })\n        public static NIC create(Integer count, String type) {\n            return new AutoValue_Specs_NIC(count, type);\n        }\n    }\n\n    @AutoValue\n    public abstract static class Drive {\n\n        public abstract Integer count();\n        public abstract String size();\n        public abstract String type();\n\n        @SerializedNames({ \"count\", \"size\", \"type\" })\n        public static Drive create(Integer count, String size, String type) {\n            return new AutoValue_Specs_Drive(count, size, type);\n        }\n    }\n\n    @AutoValue\n    public abstract static class CPU {\n\n        public abstract Integer count();\n        public abstract String type();\n\n        @SerializedNames({ \"count\", \"type\" })\n        public static CPU create(Integer count, String type) {\n            return new AutoValue_Specs_CPU(count, type);\n        }\n    }\n\n    @AutoValue\n    public abstract static class Memory {\n\n        public abstract String total();\n\n        @SerializedNames({ \"total\" })\n        public static Memory create(String total) {\n            return new AutoValue_Specs_Memory(total);\n        }\n    }\n\n    public abstract List<CPU> cpus();\n    public abstract Memory memory();\n    public abstract List<Drive> drives();\n    public abstract List<NIC> nics();\n    public abstract Map<String, Object> features();\n\n    @SerializedNames({\"cpus\", \"memory\", \"drives\", \"nics\", \"features\"})\n    public static Specs create(List<CPU> cpus, Memory memory, List<Drive> drives, List<NIC> nics, Map<String, Object> features) {\n        return new AutoValue_Specs(\n                cpus == null ? ImmutableList.<CPU> of() : ImmutableList.copyOf(cpus),\n                memory,\n                drives == null ? ImmutableList.<Drive> of() : ImmutableList.copyOf(drives),\n                nics == null ? ImmutableList.<NIC> of() : ImmutableList.copyOf(nics),\n                features == null ? ImmutableMap.<String, Object> of() : ImmutableMap.copyOf(features)\n        );\n    }\n\n    Specs() {}\n\n}\n"
  },
  {
    "path": "providers/packet/src/main/java/org/jclouds/packet/domain/SshKey.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.domain;\n\nimport java.util.Date;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport com.google.auto.value.AutoValue;\n\n@AutoValue\npublic abstract class SshKey {\n\n    @AutoValue\n    public abstract static class Owner {\n\n        public abstract String href();\n\n        @SerializedNames({ \"href\" })\n        public static Owner create(String href) {\n            return new AutoValue_SshKey_Owner(href);\n        }\n    }\n\n    public abstract String id();\n    public abstract String label();\n    public abstract String key();\n    public abstract String fingerprint();\n    public abstract Date createdAt();\n    public abstract Date updatedAt();\n    @Nullable public abstract Owner owner();\n    public abstract String href();\n\n    @SerializedNames({\"id\", \"label\", \"key\", \"fingerprint\", \"created_at\", \"updated_at\", \"owner\", \"href\"})\n    public static SshKey create(String id, String label, String key, String fingerprint, Date createdAt, Date updatedAt, Owner owner, String href) {\n        return new AutoValue_SshKey(id, label, key, fingerprint, createdAt, updatedAt, owner, href);\n    }\n\n    SshKey() {}\n}\n"
  },
  {
    "path": "providers/packet/src/main/java/org/jclouds/packet/domain/internal/PaginatedCollection.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.domain.internal;\n\nimport java.util.Iterator;\nimport java.util.List;\n\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\nimport org.jclouds.packet.domain.Href;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableList;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\n/**\n * Base class for all collections that return paginated results.\n */\npublic abstract class PaginatedCollection<T> extends IterableWithMarker<T> {\n\n   @AutoValue\n   public abstract static class Meta {\n      public abstract long total();\n      @Nullable public abstract Href first();\n      @Nullable public abstract Href previous();\n      @Nullable public abstract Href self();\n      @Nullable public abstract Href next();\n      @Nullable public abstract Href last();\n\n      @SerializedNames({ \"total\", \"first\", \"previous\", \"self\", \"next\", \"last\" })\n      public static Meta create(long total, Href first, Href previous, Href self, Href next, Href last) {\n         return new AutoValue_PaginatedCollection_Meta(total, first, previous, self, next, last);\n      }\n\n      Meta() { }\n   }\n\n   private final List<T> items;\n   private final Meta meta;\n\n   protected PaginatedCollection(List<T> items, Meta meta) {\n      this.items = ImmutableList.copyOf(checkNotNull(items, \"items cannot be null\"));\n      this.meta = meta;\n   }\n\n   public List<T> items() {\n      return items;\n   }\n\n   public Meta meta() {\n      return meta;\n   }  \n\n   @Override\n   public Iterator<T> iterator() {\n      return items.iterator();\n   }\n\n   @Override\n   public Optional<Object> nextMarker() {\n      if (meta == null || meta.next() == null) {\n         return Optional.absent();\n      }\n      return Optional.fromNullable((Object) meta.next());\n   }\n\n}\n"
  },
  {
    "path": "providers/packet/src/main/java/org/jclouds/packet/domain/options/ListOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.domain.options;\n\nimport org.jclouds.http.options.BaseHttpRequestOptions;\n\n/**\n * Options to customize how paginated lists are returned.\n */\npublic class ListOptions extends BaseHttpRequestOptions {\n   public static final String PAGE_PARAM = \"page\";\n   public static final String PER_PAGE_PARAM = \"per_page\";\n   \n   /**\n    * Configures the number of entries to return in each page.\n    */\n   public ListOptions perPage(int perPage) {\n      queryParameters.put(PER_PAGE_PARAM, String.valueOf(perPage));\n      return this;\n   }\n   \n   /**\n    * Configures the number of the page to be returned.\n    */\n   public ListOptions page(int page) {\n      queryParameters.put(PAGE_PARAM, String.valueOf(page));\n      return this;\n   }\n   \n   public static final class Builder {\n      \n      /**\n       * @see {@link ListOptions#perPage(int)}\n       */\n      public static ListOptions perPage(int perPage) {\n         return new ListOptions().perPage(perPage);\n      }\n      \n      /**\n       * @see {@link ListOptions#page(int)}\n       */\n      public static ListOptions page(int page) {\n         return new ListOptions().page(page);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/packet/src/main/java/org/jclouds/packet/features/DeviceApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.features;\n\nimport java.beans.ConstructorProperties;\nimport java.util.List;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.PagedIterable;\nimport org.jclouds.collect.internal.Arg0ToPagedIterable;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.Json;\nimport org.jclouds.packet.PacketApi;\nimport org.jclouds.packet.domain.Device;\nimport org.jclouds.packet.domain.Href;\nimport org.jclouds.packet.domain.internal.PaginatedCollection;\nimport org.jclouds.packet.domain.options.ListOptions;\nimport org.jclouds.packet.filters.AddApiVersionToRequest;\nimport org.jclouds.packet.filters.AddXAuthTokenToRequest;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.Transform;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.inject.TypeLiteral;\n\n@Consumes(MediaType.APPLICATION_JSON)\n@RequestFilters({AddXAuthTokenToRequest.class, AddApiVersionToRequest.class})\npublic interface DeviceApi {\n\n   @Named(\"device:list\")\n   @GET\n   @Path(\"/projects/{projectId}/devices\")\n   @ResponseParser(ParseDevices.class)\n   @Transform(ParseDevices.ToPagedIterable.class)\n   @Fallback(Fallbacks.EmptyPagedIterableOnNotFoundOr404.class)\n   PagedIterable<Device> list();\n\n   @Named(\"device:list\")\n   @GET\n   @Path(\"/projects/{projectId}/devices\")\n   @ResponseParser(ParseDevices.class)\n   @Fallback(Fallbacks.EmptyIterableWithMarkerOnNotFoundOr404.class)\n   IterableWithMarker<Device> list(ListOptions options);\n\n   final class ParseDevices extends ParseJson<ParseDevices.Devices> {\n      @Inject\n      ParseDevices(Json json) {\n         super(json, TypeLiteral.get(Devices.class));\n      }\n\n       private static class Devices extends PaginatedCollection<Device> {\n         @ConstructorProperties({\"devices\", \"meta\"})\n         public Devices(List<Device> items, Meta meta) {\n            super(items, meta);\n         }\n      }\n\n      public static class ToPagedIterable extends Arg0ToPagedIterable.FromCaller<Device, ToPagedIterable> {\n\n         private final PacketApi api;\n         private final Function<Href, ListOptions> hrefToOptions;\n\n         @Inject\n         ToPagedIterable(PacketApi api, Function<Href, ListOptions> hrefToOptions) {\n            this.api = api;\n            this.hrefToOptions = hrefToOptions;\n         }\n\n         @Override\n         protected Function<Object, IterableWithMarker<Device>> markerToNextForArg0(Optional<Object> arg0) {\n            String projectId = arg0.get().toString();\n            final DeviceApi deviceApi = api.deviceApi(projectId);\n            return new Function<Object, IterableWithMarker<Device>>() {\n\n               @SuppressWarnings(\"unchecked\")\n               @Override\n               public IterableWithMarker<Device> apply(Object input) {\n                  ListOptions listOptions = hrefToOptions.apply(Href.class.cast(input));\n                  return IterableWithMarker.class.cast(deviceApi.list(listOptions));\n               }\n\n            };\n         }\n      }\n   }\n\n   @Named(\"device:create\")\n   @POST\n   @Path(\"/projects/{projectId}/devices\")\n   @Produces(MediaType.APPLICATION_JSON)\n   Device create(@BinderParam(BindToJsonPayload.class) Device.CreateDevice device);\n\n\n   @Named(\"device:get\")\n   @GET\n   @Path(\"/devices/{id}\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Device get(@PathParam(\"id\") String id);\n\n   @Named(\"device:delete\")\n   @DELETE\n   @Path(\"/devices/{id}\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void delete(@PathParam(\"id\") String id);\n\n   @Named(\"device:powerOff\")\n   @POST\n   @Produces(MediaType.APPLICATION_JSON)\n   @Path(\"/devices/{id}/actions\")\n   @Payload(\"{\\\"type\\\":\\\"power_off\\\"}\")\n   void powerOff(@PathParam(\"id\") String id);\n\n   @Named(\"device:powerOn\")\n   @POST\n   @Produces(MediaType.APPLICATION_JSON)\n   @Path(\"/devices/{id}/actions\")\n   @Payload(\"{\\\"type\\\":\\\"power_on\\\"}\")\n   void powerOn(@PathParam(\"id\") String id);\n   \n   @Named(\"device:reboot\")\n   @POST\n   @Produces(MediaType.APPLICATION_JSON)\n   @Path(\"/devices/{id}/actions\")\n   @Payload(\"{\\\"type\\\":\\\"reboot\\\"}\")\n   void reboot(@PathParam(\"id\") String id);\n\n}\n"
  },
  {
    "path": "providers/packet/src/main/java/org/jclouds/packet/features/FacilityApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.features;\n\nimport java.beans.ConstructorProperties;\nimport java.util.List;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks;\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.PagedIterable;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\nimport org.jclouds.packet.PacketApi;\nimport org.jclouds.packet.domain.Facility;\nimport org.jclouds.packet.domain.Href;\nimport org.jclouds.packet.domain.internal.PaginatedCollection;\nimport org.jclouds.packet.domain.options.ListOptions;\nimport org.jclouds.packet.filters.AddApiVersionToRequest;\nimport org.jclouds.packet.filters.AddXAuthTokenToRequest;\nimport org.jclouds.packet.functions.BaseToPagedIterable;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.Transform;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.inject.TypeLiteral;\n\n@Path(\"/facilities\")\n@Consumes(MediaType.APPLICATION_JSON)\n@RequestFilters({ AddXAuthTokenToRequest.class, AddApiVersionToRequest.class} )\npublic interface FacilityApi {\n\n    @Named(\"facility:list\")\n    @GET\n    @ResponseParser(ParseFacilities.class)\n    @Transform(ParseFacilities.ToPagedIterable.class)\n    @Fallback(Fallbacks.EmptyPagedIterableOnNotFoundOr404.class)\n    PagedIterable<Facility> list();\n\n    @Named(\"facility:list\")\n    @GET\n    @ResponseParser(ParseFacilities.class)\n    @Fallback(Fallbacks.EmptyIterableWithMarkerOnNotFoundOr404.class)\n    IterableWithMarker<Facility> list(ListOptions options);\n\n    final class ParseFacilities extends ParseJson<ParseFacilities.Facilities> {\n        @Inject\n        ParseFacilities(Json json) {\n            super(json, TypeLiteral.get(Facilities.class));\n        }\n\n        private static class Facilities extends PaginatedCollection<Facility> {\n            @ConstructorProperties({ \"facilities\", \"meta\" })\n            public Facilities(List<Facility> items, Meta meta) {\n                super(items, meta);\n            }\n        }\n\n        private static class ToPagedIterable extends BaseToPagedIterable<Facility, ListOptions> {\n            @Inject ToPagedIterable(PacketApi api, Function<Href, ListOptions> hrefToOptions) {\n                super(api, hrefToOptions);\n            }\n\n            @Override\n            protected IterableWithMarker<Facility> fetchPageUsingOptions(ListOptions options, Optional<Object> arg0) {\n                return api.facilityApi().list(options);\n            }\n        }\n    }\n\n}\n"
  },
  {
    "path": "providers/packet/src/main/java/org/jclouds/packet/features/OperatingSystemApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.features;\n\nimport java.beans.ConstructorProperties;\nimport java.util.List;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks;\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.PagedIterable;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\nimport org.jclouds.packet.PacketApi;\nimport org.jclouds.packet.domain.Href;\nimport org.jclouds.packet.domain.OperatingSystem;\nimport org.jclouds.packet.domain.internal.PaginatedCollection;\nimport org.jclouds.packet.domain.options.ListOptions;\nimport org.jclouds.packet.filters.AddApiVersionToRequest;\nimport org.jclouds.packet.filters.AddXAuthTokenToRequest;\nimport org.jclouds.packet.functions.BaseToPagedIterable;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.Transform;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.inject.TypeLiteral;\n\n@Path(\"/operating-systems\")\n@Consumes(MediaType.APPLICATION_JSON)\n@RequestFilters({ AddXAuthTokenToRequest.class, AddApiVersionToRequest.class} )\npublic interface OperatingSystemApi {\n\n    @Named(\"operatingsystem:list\")\n    @GET\n    @ResponseParser(ParseOperatingSystems.class)\n    @Transform(ParseOperatingSystems.ToPagedIterable.class)\n    @Fallback(Fallbacks.EmptyPagedIterableOnNotFoundOr404.class)\n    PagedIterable<OperatingSystem> list();\n\n    @Named(\"operatingsystem:list\")\n    @GET\n    @ResponseParser(ParseOperatingSystems.class)\n    @Fallback(Fallbacks.EmptyIterableWithMarkerOnNotFoundOr404.class)\n    IterableWithMarker<OperatingSystem> list(ListOptions options);\n\n    final class ParseOperatingSystems extends ParseJson<ParseOperatingSystems.OperatingSystems> {\n        @Inject\n        ParseOperatingSystems(Json json) {\n            super(json, TypeLiteral.get(ParseOperatingSystems.OperatingSystems.class));\n        }\n\n        private static class OperatingSystems extends PaginatedCollection<OperatingSystem> {\n            @ConstructorProperties({ \"operating_systems\", \"meta\" })\n            public OperatingSystems(List<OperatingSystem> items, Meta meta) {\n                super(items, meta);\n            }\n        }\n\n        private static class ToPagedIterable extends BaseToPagedIterable<OperatingSystem, ListOptions> {\n            @Inject ToPagedIterable(PacketApi api, Function<Href, ListOptions> hrefToOptions) {\n                super(api, hrefToOptions);\n            }\n\n            @Override\n            protected IterableWithMarker<OperatingSystem> fetchPageUsingOptions(ListOptions options, Optional<Object> arg0) {\n                return api.operatingSystemApi().list(options);\n            }\n        }\n    }\n\n}\n"
  },
  {
    "path": "providers/packet/src/main/java/org/jclouds/packet/features/PlanApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.features;\n\nimport java.beans.ConstructorProperties;\nimport java.util.List;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks;\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.PagedIterable;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\nimport org.jclouds.packet.PacketApi;\nimport org.jclouds.packet.domain.Href;\nimport org.jclouds.packet.domain.Plan;\nimport org.jclouds.packet.domain.internal.PaginatedCollection;\nimport org.jclouds.packet.domain.options.ListOptions;\nimport org.jclouds.packet.filters.AddApiVersionToRequest;\nimport org.jclouds.packet.filters.AddXAuthTokenToRequest;\nimport org.jclouds.packet.functions.BaseToPagedIterable;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.Transform;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.inject.TypeLiteral;\n\n@Path(\"/plans\")\n@Consumes(MediaType.APPLICATION_JSON)\n@RequestFilters({ AddXAuthTokenToRequest.class, AddApiVersionToRequest.class} )\npublic interface PlanApi {\n\n    @Named(\"plan:list\")\n    @GET\n    @ResponseParser(ParsePlans.class)\n    @Transform(ParsePlans.ToPagedIterable.class)\n    @Fallback(Fallbacks.EmptyPagedIterableOnNotFoundOr404.class)\n    PagedIterable<Plan> list();\n\n    @Named(\"plan:list\")\n    @GET\n    @ResponseParser(ParsePlans.class)\n    @Fallback(Fallbacks.EmptyIterableWithMarkerOnNotFoundOr404.class)\n    IterableWithMarker<Plan> list(ListOptions options);\n\n    final class ParsePlans extends ParseJson<ParsePlans.Plans> {\n        @Inject\n        ParsePlans(Json json) {\n            super(json, TypeLiteral.get(ParsePlans.Plans.class));\n        }\n\n        private static class Plans extends PaginatedCollection<Plan> {\n            @ConstructorProperties({ \"plans\", \"meta\" })\n            public Plans(List<Plan> items, Meta meta) {\n                super(items, meta);\n            }\n        }\n\n        private static class ToPagedIterable extends BaseToPagedIterable<Plan, ListOptions> {\n            @Inject ToPagedIterable(PacketApi api, Function<Href, ListOptions> hrefToOptions) {\n                super(api, hrefToOptions);\n            }\n\n            @Override\n            protected IterableWithMarker<Plan> fetchPageUsingOptions(ListOptions options, Optional<Object> arg0) {\n                return api.planApi().list(options);\n            }\n        }\n    }\n\n}\n"
  },
  {
    "path": "providers/packet/src/main/java/org/jclouds/packet/features/ProjectApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.features;\n\nimport java.beans.ConstructorProperties;\nimport java.util.List;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks;\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.PagedIterable;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.json.Json;\nimport org.jclouds.packet.PacketApi;\nimport org.jclouds.packet.domain.Href;\nimport org.jclouds.packet.domain.Project;\nimport org.jclouds.packet.domain.internal.PaginatedCollection;\nimport org.jclouds.packet.domain.options.ListOptions;\nimport org.jclouds.packet.filters.AddApiVersionToRequest;\nimport org.jclouds.packet.filters.AddXAuthTokenToRequest;\nimport org.jclouds.packet.functions.BaseToPagedIterable;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.Transform;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.inject.TypeLiteral;\n\n@Path(\"/projects\")\n@Consumes(MediaType.APPLICATION_JSON)\n@RequestFilters({ AddXAuthTokenToRequest.class, AddApiVersionToRequest.class} )\npublic interface ProjectApi {\n\n    @Named(\"project:list\")\n    @GET\n    @ResponseParser(ParseProjects.class)\n    @Transform(ParseProjects.ToPagedIterable.class)\n    @Fallback(Fallbacks.EmptyPagedIterableOnNotFoundOr404.class)\n    PagedIterable<Project> list();\n\n    @Named(\"project:list\")\n    @GET\n    @ResponseParser(ParseProjects.class)\n    @Fallback(Fallbacks.EmptyIterableWithMarkerOnNotFoundOr404.class)\n    IterableWithMarker<Project> list(ListOptions options);\n\n    final class ParseProjects extends ParseJson<ParseProjects.Projects> {\n        @Inject\n        ParseProjects(Json json) {\n            super(json, TypeLiteral.get(Projects.class));\n        }\n\n        private static class Projects extends PaginatedCollection<Project> {\n            @ConstructorProperties({ \"projects\", \"meta\" })\n            public Projects(List<Project> items, Meta meta) {\n                super(items, meta);\n            }\n        }\n\n        private static class ToPagedIterable extends BaseToPagedIterable<Project, ListOptions> {\n            @Inject ToPagedIterable(PacketApi api, Function<Href, ListOptions> hrefToOptions) {\n                super(api, hrefToOptions);\n            }\n\n            @Override\n            protected IterableWithMarker<Project> fetchPageUsingOptions(ListOptions options, Optional<Object> arg0) {\n                return api.projectApi().list(options);\n            }\n        }\n    }\n\n}\n"
  },
  {
    "path": "providers/packet/src/main/java/org/jclouds/packet/features/SshKeyApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.features;\n\nimport java.beans.ConstructorProperties;\nimport java.util.List;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.DELETE;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.PagedIterable;\nimport org.jclouds.http.functions.ParseJson;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.Json;\nimport org.jclouds.packet.PacketApi;\nimport org.jclouds.packet.domain.Href;\nimport org.jclouds.packet.domain.SshKey;\nimport org.jclouds.packet.domain.internal.PaginatedCollection;\nimport org.jclouds.packet.domain.options.ListOptions;\nimport org.jclouds.packet.filters.AddApiVersionToRequest;\nimport org.jclouds.packet.filters.AddXAuthTokenToRequest;\nimport org.jclouds.packet.functions.BaseToPagedIterable;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.ResponseParser;\nimport org.jclouds.rest.annotations.Transform;\nimport org.jclouds.rest.binders.BindToJsonPayload;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.inject.TypeLiteral;\n\n@Path(\"/ssh-keys\")\n@Consumes(MediaType.APPLICATION_JSON)\n@RequestFilters({ AddXAuthTokenToRequest.class, AddApiVersionToRequest.class} )\npublic interface SshKeyApi {\n\n    @Named(\"sshkey:list\")\n    @GET\n    @ResponseParser(ParseSshKeys.class)\n    @Transform(ParseSshKeys.ToPagedIterable.class)\n    @Fallback(Fallbacks.EmptyPagedIterableOnNotFoundOr404.class)\n    PagedIterable<SshKey> list();\n\n    @Named(\"sshkey:list\")\n    @GET\n    @ResponseParser(ParseSshKeys.class)\n    @Fallback(Fallbacks.EmptyIterableWithMarkerOnNotFoundOr404.class)\n    IterableWithMarker<SshKey> list(ListOptions options);\n\n    final class ParseSshKeys extends ParseJson<ParseSshKeys.SshKeys> {\n        @Inject\n        ParseSshKeys(Json json) {\n            super(json, TypeLiteral.get(ParseSshKeys.SshKeys.class));\n        }\n\n        private static class SshKeys extends PaginatedCollection<SshKey> {\n            @ConstructorProperties({ \"ssh_keys\", \"meta\" })\n            public SshKeys(List<SshKey> items, Meta meta) {\n                super(items, meta);\n            }\n        }\n\n        private static class ToPagedIterable extends BaseToPagedIterable<SshKey, ListOptions> {\n            @Inject ToPagedIterable(PacketApi api, Function<Href, ListOptions> hrefToOptions) {\n                super(api, hrefToOptions);\n            }\n\n            @Override\n            protected IterableWithMarker<SshKey> fetchPageUsingOptions(ListOptions options, Optional<Object> arg0) {\n                return api.sshKeyApi().list(options);\n            }\n        }\n    }\n\n    @Named(\"sshkey:create\")\n    @POST\n    @Produces(MediaType.APPLICATION_JSON)\n    @MapBinder(BindToJsonPayload.class)\n    SshKey create(@PayloadParam(\"label\") String label, @PayloadParam(\"key\") String key);\n\n    @Named(\"sshkey:get\")\n    @GET\n    @Path(\"/{id}\")\n    @Fallback(NullOnNotFoundOr404.class)\n    @Nullable\n    SshKey get(@PathParam(\"id\") String id);\n\n    @Named(\"sshkey:delete\")\n    @DELETE\n    @Path(\"/{id}\")\n    @Fallback(VoidOnNotFoundOr404.class)\n    void delete(@PathParam(\"id\") String id);\n}\n"
  },
  {
    "path": "providers/packet/src/main/java/org/jclouds/packet/filters/AddApiVersionToRequest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.filters;\n\nimport java.util.Collection;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpRequestFilter;\nimport org.jclouds.rest.annotations.ApiVersion;\n\nimport com.google.common.base.Joiner;\nimport com.google.common.collect.ImmutableList;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.net.HttpHeaders.ACCEPT;\nimport static java.lang.String.format;\n\n@Singleton\npublic class AddApiVersionToRequest implements HttpRequestFilter {\n\n    private final String apiVersion;\n\n    @Inject\n    AddApiVersionToRequest(@ApiVersion String apiVersion) {\n        this.apiVersion = apiVersion;\n    }\n\n    @Override\n    public HttpRequest filter(final HttpRequest request) throws HttpException {\n        Collection<String> accept = checkNotNull(request.getHeaders().get(ACCEPT), \"accept header must not be null\");\n        String versionHeader = Joiner.on(\"; \").join(ImmutableList.builder()\n                .addAll(accept)\n                .add(format(\"version=%s\", apiVersion))\n                .build());\n        return request.toBuilder()\n                .replaceHeader(ACCEPT, versionHeader)\n                .build();\n    }\n}\n"
  },
  {
    "path": "providers/packet/src/main/java/org/jclouds/packet/filters/AddXAuthTokenToRequest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.filters;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpRequestFilter;\nimport org.jclouds.location.Provider;\n\nimport com.google.common.base.Supplier;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\n@Singleton\npublic class AddXAuthTokenToRequest implements HttpRequestFilter {\n\n    private final Supplier<Credentials> creds;\n\n    @Inject\n    AddXAuthTokenToRequest(@Provider Supplier<Credentials> creds) {\n        this.creds = creds;\n    }\n\n    @Override\n    public HttpRequest filter(HttpRequest request) throws HttpException {\n        Credentials currentCreds = checkNotNull(creds.get(), \"credential supplier returned null\");\n        return request.toBuilder().replaceHeader(\"X-Auth-Token\", currentCreds.credential).build();\n    }\n}\n"
  },
  {
    "path": "providers/packet/src/main/java/org/jclouds/packet/functions/BaseToPagedIterable.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.functions;\n\nimport org.jclouds.collect.IterableWithMarker;\nimport org.jclouds.collect.internal.Arg0ToPagedIterable;\nimport org.jclouds.packet.PacketApi;\nimport org.jclouds.packet.domain.Href;\nimport org.jclouds.packet.domain.options.ListOptions;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\n\n/**\n * Base class to implement the functions that build the\n * <code>PagedIterable</code>. Subclasses just need to override the\n * {@link #fetchPageUsingOptions(ListOptions, Optional)} to invoke the right API\n * method with the given options parameter to get the next page.\n */\npublic abstract class BaseToPagedIterable<T, O extends ListOptions> extends\n        Arg0ToPagedIterable<T, BaseToPagedIterable<T, O>> {\n   private final Function<Href, O> hrefToOptions;\n   protected final PacketApi api;\n\n   protected BaseToPagedIterable(PacketApi api, Function<Href, O> hrefToOptions) {\n      this.api = api;\n      this.hrefToOptions = hrefToOptions;\n   }\n\n   protected abstract IterableWithMarker<T> fetchPageUsingOptions(O options, Optional<Object> arg0);\n\n   @Override\n   protected Function<Object, IterableWithMarker<T>> markerToNextForArg0(final Optional<Object> arg0) {\n      return new Function<Object, IterableWithMarker<T>>() {\n         @Override\n         public IterableWithMarker<T> apply(Object input) {\n            O nextOptions = hrefToOptions.apply(Href.class.cast(input));\n            return fetchPageUsingOptions(nextOptions, arg0);\n         }\n      };\n   }\n\n}\n"
  },
  {
    "path": "providers/packet/src/main/java/org/jclouds/packet/functions/HrefToListOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.functions;\n\nimport java.net.URI;\n\nimport org.jclouds.packet.domain.Href;\nimport org.jclouds.packet.domain.options.ListOptions;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.Multimap;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Strings.emptyToNull;\nimport static com.google.common.collect.Iterables.getFirst;\nimport static org.jclouds.http.utils.Queries.queryParser;\nimport static org.jclouds.packet.domain.options.ListOptions.PAGE_PARAM;\nimport static org.jclouds.packet.domain.options.ListOptions.PER_PAGE_PARAM;\n\n/**\n * Transforms an href returned by the API into a {@link ListOptions} that can be\n * used to perform a request to get another page of a paginated list.\n */\npublic class HrefToListOptions implements Function<Href, ListOptions> {\n\n   @Override\n   public ListOptions apply(Href input) {\n      checkNotNull(input, \"input cannot be null\");\n\n      Multimap<String, String> queryParams = queryParser().apply(URI.create(input.href()).getQuery());\n      String nextPage = getFirstOrNull(PAGE_PARAM, queryParams);\n      String nextPerPage = getFirstOrNull(PER_PAGE_PARAM, queryParams);\n\n      ListOptions options = new ListOptions();\n      if (nextPage != null) {\n         options.page(Integer.parseInt(nextPage));\n      }\n      if (nextPerPage != null) {\n         options.perPage(Integer.parseInt(nextPerPage));\n      }\n\n      return options;\n   }\n\n   public static String getFirstOrNull(String key, Multimap<String, String> params) {\n      return params.containsKey(key) ? emptyToNull(getFirst(params.get(key), null)) : null;\n   }\n\n}\n"
  },
  {
    "path": "providers/packet/src/main/java/org/jclouds/packet/handlers/PacketErrorHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.handlers;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.ResourceNotFoundException;\n\nimport static org.jclouds.http.HttpUtils.closeClientButKeepContentStream;\n\n/**\n * This will parse and set an appropriate exception on the command object.\n */\n@Singleton\npublic class PacketErrorHandler implements HttpErrorHandler {\n\n   public void handleError(HttpCommand command, HttpResponse response) {\n      // it is important to always read fully and close streams\n      byte[] data = closeClientButKeepContentStream(response);\n      String message = data != null ? new String(data) : null;\n\n      Exception exception = message != null ? new HttpResponseException(command, response, message)\n              : new HttpResponseException(command, response);\n      message = message != null ? message : String.format(\"%s -> %s\", command.getCurrentRequest().getRequestLine(),\n              response.getStatusLine());\n      switch (response.getStatusCode()) {\n         case 400:\n            exception = new IllegalArgumentException(message, exception);\n            break;\n         case 401:\n         case 403:\n               exception = new AuthorizationException(message, exception);\n            break;\n         case 404:\n            if (!command.getCurrentRequest().getMethod().equals(\"DELETE\")) {\n               exception = new ResourceNotFoundException(message, exception);\n            }\n            break;\n         case 409:\n            exception = new IllegalStateException(message, exception);\n            break;\n      }\n      command.setException(exception);\n   }\n}\n"
  },
  {
    "path": "providers/packet/src/test/java/org/jclouds/packet/PacketProviderMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet;\n\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"PacketProviderMetadataTest\")\npublic class PacketProviderMetadataTest extends BaseProviderMetadataTest {\n\n   public PacketProviderMetadataTest() {\n      super(new PacketProviderMetadata(), new PacketApiMetadata());\n   }\n\n}\n"
  },
  {
    "path": "providers/packet/src/test/java/org/jclouds/packet/compute/PacketComputeProviderMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.compute;\n\nimport org.jclouds.packet.PacketApiMetadata;\nimport org.jclouds.packet.PacketProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"PacketComputeProviderMetadataTest\")\npublic class PacketComputeProviderMetadataTest extends BaseProviderMetadataTest {\n\n   public PacketComputeProviderMetadataTest() {\n      super(new PacketProviderMetadata(), new PacketApiMetadata());\n   }\n}\n"
  },
  {
    "path": "providers/packet/src/test/java/org/jclouds/packet/compute/PacketComputeServiceLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.compute;\n\nimport java.util.Properties;\n\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.internal.BaseComputeServiceLiveTest;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.sshj.config.SshjSshClientModule;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n/**\n * Live tests for the {@link org.jclouds.compute.ComputeService} integration.\n */\n@Test(groups = \"live\", singleThreaded = true, testName = \"PacketComputeServiceLiveTest\")\npublic class PacketComputeServiceLiveTest extends BaseComputeServiceLiveTest {\n\n   public PacketComputeServiceLiveTest() {\n      provider = \"packet\";\n   }\n\n   @Override\n   protected Module getSshModule() {\n      return new SshjSshClientModule();\n   }\n\n   @Override\n   @Test(expectedExceptions = AuthorizationException.class)\n   public void testCorrectAuthException() throws Exception {\n      ComputeServiceContext context = null;\n      try {\n         Properties overrides = setupProperties();\n         overrides.setProperty(provider + \".identity\", \"MOM:MA\");\n         overrides.setProperty(provider + \".credential\", \"MIA\");\n         context = newBuilder()\n                 .modules(ImmutableSet.of(getLoggingModule(), credentialStoreModule))\n                 .overrides(overrides)\n                 .build(ComputeServiceContext.class);\n         // replace listNodes with listImages as it doesn't require `projectId`\n         context.getComputeService().listImages();\n      } catch (AuthorizationException e) {\n         throw e;\n      } catch (RuntimeException e) {\n         e.printStackTrace();\n         throw e;\n      } finally {\n         if (context != null)\n            context.close();\n      }\n   }\n\n   @Override\n   public void testOptionToNotBlock() throws Exception {\n      // Packet ComputeService implementation has to block until the node\n      // is provisioned, to be able to return it.\n   }\n\n   @Override\n   protected void checkUserMetadataContains(NodeMetadata node, ImmutableMap<String, String> userMetadata) {\n      // The Packet API does not return the user data\n   }\n\n}\n"
  },
  {
    "path": "providers/packet/src/test/java/org/jclouds/packet/compute/PacketTemplateBuilderLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.compute;\n\nimport java.io.IOException;\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.internal.BaseTemplateBuilderLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\nimport static org.jclouds.compute.util.ComputeServiceUtils.getCores;\nimport static org.testng.Assert.assertEquals;\n\n@Test(groups = \"live\", testName = \"PacketTemplateBuilderLiveTest\")\npublic class PacketTemplateBuilderLiveTest extends BaseTemplateBuilderLiveTest {\n\n   public PacketTemplateBuilderLiveTest() {\n      provider = \"packet\";\n   }\n\n   @Test\n   @Override\n   public void testDefaultTemplateBuilder() throws IOException {\n      Template defaultTemplate = view.getComputeService().templateBuilder().build();\n      assert defaultTemplate.getImage().getOperatingSystem().getVersion().startsWith(\"16.\") : defaultTemplate\n            .getImage().getOperatingSystem().getVersion();\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true);\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.UBUNTU);\n      assertEquals(getCores(defaultTemplate.getHardware()), 1.0d);\n   }\n\n   @Override\n   protected Set<String> getIso3166Codes() {\n      return ImmutableSet.of(\"US-CA\", \"US-NJ\", \"NL\", \"JP\");\n   }\n\n}\n"
  },
  {
    "path": "providers/packet/src/test/java/org/jclouds/packet/compute/internal/BasePacketApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.compute.internal;\n\nimport java.util.Properties;\nimport java.util.concurrent.TimeUnit;\n\nimport org.jclouds.apis.BaseApiLiveTest;\nimport org.jclouds.compute.config.ComputeServiceProperties;\nimport org.jclouds.packet.PacketApi;\n\nimport com.google.common.base.Predicate;\nimport com.google.inject.Injector;\nimport com.google.inject.Key;\nimport com.google.inject.Module;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.name.Names;\n\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_RUNNING;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_SUSPENDED;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_TERMINATED;\nimport static org.testng.Assert.assertTrue;\n\npublic class BasePacketApiLiveTest extends BaseApiLiveTest<PacketApi> {\n\n   private Predicate<String> deviceRunning;\n   private Predicate<String> deviceSuspended;\n   private Predicate<String> deviceTerminated;\n\n   public BasePacketApiLiveTest() {\n      provider = \"packet\";\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      props.put(ComputeServiceProperties.POLL_INITIAL_PERIOD, 1000);\n      props.put(ComputeServiceProperties.POLL_MAX_PERIOD, 10000);\n      props.put(ComputeServiceProperties.TIMEOUT_IMAGE_AVAILABLE, TimeUnit.MINUTES.toMillis(45));\n      return props;\n   }\n\n   @Override\n   protected PacketApi create(Properties props, Iterable<Module> modules) {\n      Injector injector = newBuilder().modules(modules).overrides(props).buildInjector();\n      deviceRunning = injector.getInstance(Key.get(new TypeLiteral<Predicate<String>>(){},\n            Names.named(TIMEOUT_NODE_RUNNING)));\n      deviceSuspended = injector.getInstance(Key.get(new TypeLiteral<Predicate<String>>(){},\n              Names.named(TIMEOUT_NODE_SUSPENDED)));\n      deviceTerminated = injector.getInstance(Key.get(new TypeLiteral<Predicate<String>>(){},\n              Names.named(TIMEOUT_NODE_TERMINATED)));\n      return injector.getInstance(PacketApi.class);\n   }\n\n   protected void assertNodeRunning(String deviceId) {\n      assertTrue(deviceRunning.apply(deviceId), String.format(\"Device %s did not start in the configured timeout\", deviceId));\n   }\n\n   protected void assertNodeSuspended(String deviceId) {\n      assertTrue(deviceSuspended.apply(deviceId), String.format(\"Device %s was not suspended in the configured timeout\", deviceId));\n   }\n   \n   protected void assertNodeTerminated(String deviceId) {\n      assertTrue(deviceTerminated.apply(deviceId), String.format(\"Device %s was not terminated in the configured timeout\", deviceId));\n   }\n\n}\n"
  },
  {
    "path": "providers/packet/src/test/java/org/jclouds/packet/compute/internal/BasePacketApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.compute.internal;\n\nimport java.io.IOException;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\nimport okhttp3.mockwebserver.RecordedRequest;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.concurrent.config.ExecutorServiceModule;\nimport org.jclouds.json.Json;\nimport org.jclouds.packet.PacketApi;\nimport org.jclouds.packet.PacketProviderMetadata;\nimport org.jclouds.rest.ApiContext;\nimport org.testng.annotations.AfterMethod;\nimport org.testng.annotations.BeforeMethod;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.base.Throwables;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.io.Resources;\nimport com.google.common.reflect.TypeToken;\nimport com.google.gson.JsonParser;\nimport com.google.inject.Module;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static com.google.common.util.concurrent.MoreExecutors.newDirectExecutorService;\nimport static org.jclouds.Constants.PROPERTY_MAX_RETRIES;\nimport static org.testng.Assert.assertEquals;\n\npublic class BasePacketApiMockTest {\n   \n   private static final String X_AUTHORIZATION_TOKEN = \"c5401990f0c24135e8d6b5d260603fc71696d4738da9aa04a720229a01a2521d\";\n   private static final String DEFAULT_ENDPOINT = new PacketProviderMetadata().getEndpoint();\n   \n   private final Set<Module> modules = ImmutableSet.<Module> of(new ExecutorServiceModule(newDirectExecutorService()));\n   \n   protected MockWebServer server;\n   protected PacketApi api;\n   private Json json;\n   private ApiContext<PacketApi> ctx;\n   \n   // So that we can ignore formatting.\n   private final JsonParser parser = new JsonParser();\n   \n   @BeforeMethod\n   public void start() throws IOException {\n      server = new MockWebServer();\n      server.start();\n      ctx = ContextBuilder.newBuilder(\"packet\")\n            .credentials(\"\", X_AUTHORIZATION_TOKEN)\n            .endpoint(url(\"\"))\n            .modules(modules)\n            .overrides(overrides())\n            .build();\n      json = ctx.utils().injector().getInstance(Json.class);\n      api = ctx.getApi();\n   }\n\n   @AfterMethod(alwaysRun = true)\n   public void stop() throws IOException {\n      server.shutdown();\n      api.close();\n   }\n   \n   protected Properties overrides() {\n      Properties properties = new Properties();\n      properties.put(PROPERTY_MAX_RETRIES, \"0\"); // Do not retry\n      return properties;\n   }\n\n   protected String url(String path) {\n      return server.url(path).toString();\n   }\n\n   protected MockResponse jsonResponse(String resource) {\n      return new MockResponse().addHeader(\"Content-Type\", \"application/json\").setBody(stringFromResource(resource));\n   }\n\n   protected MockResponse response404() {\n      return new MockResponse().setStatus(\"HTTP/1.1 404 Not Found\");\n   }\n   \n   protected MockResponse response204() {\n      return new MockResponse().setStatus(\"HTTP/1.1 204 No Content\");\n   }\n\n   protected String stringFromResource(String resourceName) {\n      try {\n         return Resources.toString(getClass().getResource(resourceName), Charsets.UTF_8)\n               .replace(DEFAULT_ENDPOINT, url(\"\"));\n      } catch (IOException e) {\n         throw Throwables.propagate(e);\n      }\n   }\n   \n   protected <T> T onlyObjectFromResource(String resourceName, TypeToken<Map<String, T>> type) {\n      // Assume JSON objects passed here will be in the form: { \"entity\": { ... } }\n      String text = stringFromResource(resourceName);\n      Map<String, T> object = json.fromJson(text, type.getType());\n      checkArgument(!object.isEmpty(), \"The given json does not contain any object: %s\", text);\n      checkArgument(object.keySet().size() == 1, \"The given json does not contain more than one object: %s\", text);\n      return object.get(getOnlyElement(object.keySet()));\n   }\n   \n   protected <T> T objectFromResource(String resourceName, Class<T> type) {\n      String text = stringFromResource(resourceName);\n      return json.fromJson(text, type);\n   }\n\n   protected RecordedRequest assertSent(MockWebServer server, String method, String path) throws InterruptedException {\n      RecordedRequest request = server.takeRequest();\n      assertEquals(request.getMethod(), method);\n      assertEquals(request.getPath(), path);\n      assertEquals(request.getHeader(\"Accept\"), \"application/json; version=\" + ctx.getMetadata().get(\"apiVersion\"));\n      assertEquals(request.getHeader(\"X-Auth-Token\"), X_AUTHORIZATION_TOKEN);\n      return request;\n   }\n\n   protected RecordedRequest assertSent(MockWebServer server, String method, String path, String json)\n         throws InterruptedException {\n      RecordedRequest request = assertSent(server, method, path);\n      assertEquals(request.getHeader(\"Content-Type\"), \"application/json\");\n      assertEquals(parser.parse(request.getBody().readUtf8()), parser.parse(json));\n      return request;\n   }\n}\n"
  },
  {
    "path": "providers/packet/src/test/java/org/jclouds/packet/features/DeviceApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.features;\n\nimport java.util.Map;\nimport java.util.concurrent.atomic.AtomicInteger;\n\nimport org.jclouds.packet.compute.internal.BasePacketApiLiveTest;\nimport org.jclouds.packet.domain.BillingCycle;\nimport org.jclouds.packet.domain.Device;\nimport org.jclouds.packet.domain.SshKey;\nimport org.jclouds.ssh.SshKeys;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\n\nimport static org.jclouds.packet.domain.options.ListOptions.Builder.page;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.util.Strings.isNullOrEmpty;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"DeviceApiLiveTest\")\npublic class DeviceApiLiveTest extends BasePacketApiLiveTest {\n\n   private SshKey sshKey;\n   private String deviceId;\n\n   @BeforeClass\n   public void setupDevice() {\n      Map<String, String> keyPair = SshKeys.generate();\n      sshKey = api.sshKeyApi().create(prefix + \"-device-livetest\", keyPair.get(\"public\"));\n   }\n\n   @AfterClass(alwaysRun = true)\n   public void tearDown() {\n      if (sshKey != null) {\n         api.sshKeyApi().delete(sshKey.id());\n      }\n   }\n\n   public void testCreate() {\n      Device deviceCreated = api().create(\n              Device.CreateDevice.builder()\n                      .hostname(prefix + \"-device-livetest\")\n                      .plan(\"baremetal_0\")\n                      .billingCycle(BillingCycle.HOURLY.value())\n                      .facility(\"ewr1\")\n                      .features(ImmutableMap.<String, String>of())\n                      .operatingSystem(\"ubuntu_16_04\")\n                      .locked(false)\n                      .userdata(\"\")\n                      .tags(ImmutableSet.<String> of())\n                      .build()\n      );\n      deviceId = deviceCreated.id();\n      assertNodeRunning(deviceId);\n      Device device = api().get(deviceId);\n      assertNotNull(device, \"Device must not be null\");\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testCreate\")\n   public void testReboot() {\n      api().reboot(deviceId);\n      assertNodeRunning(deviceId);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testReboot\")\n   public void testPowerOff() {\n      api().powerOff(deviceId);\n      assertNodeSuspended(deviceId);\n   }\n\n   @Test(groups = \"live\", dependsOnMethods = \"testPowerOff\")\n   public void testPowerOn() {\n      api().powerOn(deviceId);\n      assertNodeRunning(deviceId);\n   }\n\n   @Test(dependsOnMethods = \"testCreate\")\n   public void testList() {\n      final AtomicInteger found = new AtomicInteger(0);\n      assertTrue(Iterables.all(api().list().concat(), new Predicate<Device>() {\n         @Override\n         public boolean apply(Device input) {\n            found.incrementAndGet();\n            return !isNullOrEmpty(input.id());\n         }\n      }), \"All devices must have the 'id' field populated\");\n      assertTrue(found.get() > 0, \"Expected some devices to be returned\");\n   }\n\n   @Test(dependsOnMethods = \"testCreate\")\n   public void testListOnePage() {\n      final AtomicInteger found = new AtomicInteger(0);\n      assertTrue(api().list(page(1).perPage(5)).allMatch(new Predicate<Device>() {\n         @Override\n         public boolean apply(Device input) {\n            found.incrementAndGet();\n            return !isNullOrEmpty(input.id());\n         }\n      }), \"All devices must have the 'id' field populated\");\n      assertTrue(found.get() > 0, \"Expected some devices to be returned\");\n   }\n\n   @Test(dependsOnMethods = \"testPowerOn\", alwaysRun = true)\n   public void testDelete() throws InterruptedException {\n      if (deviceId != null) {\n         api().delete(deviceId);\n         assertNodeTerminated(deviceId);\n         assertNull(api().get(deviceId));\n      }\n   }\n\n   private DeviceApi api() {\n      return api.deviceApi(identity);\n   }\n}\n"
  },
  {
    "path": "providers/packet/src/test/java/org/jclouds/packet/features/DeviceApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.features;\n\nimport org.jclouds.packet.compute.internal.BasePacketApiMockTest;\nimport org.jclouds.packet.domain.BillingCycle;\nimport org.jclouds.packet.domain.Device;\nimport org.jclouds.packet.domain.Device.CreateDevice;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\n\nimport static com.google.common.collect.Iterables.isEmpty;\nimport static com.google.common.collect.Iterables.size;\nimport static org.jclouds.packet.domain.options.ListOptions.Builder.page;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\n@Test(groups = \"unit\", testName = \"DeviceApiMockTest\", singleThreaded = true)\npublic class DeviceApiMockTest extends BasePacketApiMockTest {\n\n   public void testListDevices() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/devices-first.json\"));\n      server.enqueue(jsonResponse(\"/devices-last.json\"));\n\n      Iterable<Device> devices = api.deviceApi(\"93907f48-adfe-43ed-ad89-0e6e83721a54\").list().concat();\n\n      assertEquals(size(devices), 7); // Force the PagedIterable to advance\n      assertEquals(server.getRequestCount(), 2);\n\n      assertSent(server, \"GET\", \"/projects/93907f48-adfe-43ed-ad89-0e6e83721a54/devices\");\n      assertSent(server, \"GET\", \"/projects/93907f48-adfe-43ed-ad89-0e6e83721a54/devices?page=2\");\n   }\n\n   public void testListDevicesReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      Iterable<Device> devices = api.deviceApi(\"93907f48-adfe-43ed-ad89-0e6e83721a54\").list().concat();\n\n      assertTrue(isEmpty(devices));\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/projects/93907f48-adfe-43ed-ad89-0e6e83721a54/devices\");\n   }\n\n   public void testListDevicesWithOptions() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/devices-first.json\"));\n\n      Iterable<Device> devices = api.deviceApi(\"93907f48-adfe-43ed-ad89-0e6e83721a54\").list(page(1).perPage(5));\n\n      assertEquals(size(devices), 5);\n      assertEquals(server.getRequestCount(), 1);\n\n      assertSent(server, \"GET\", \"/projects/93907f48-adfe-43ed-ad89-0e6e83721a54/devices?page=1&per_page=5\");\n   }\n\n   public void testListDevicesWithOptionsReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      Iterable<Device> actions = api.deviceApi(\"93907f48-adfe-43ed-ad89-0e6e83721a54\").list(page(1).perPage(5));\n\n      assertTrue(isEmpty(actions));\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/projects/93907f48-adfe-43ed-ad89-0e6e83721a54/devices?page=1&per_page=5\");\n   }\n\n   public void testGetDevice() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/device.json\"));\n\n      Device device = api.deviceApi(\"93907f48-adfe-43ed-ad89-0e6e83721a54\").get(\"1\");\n\n      assertEquals(device, objectFromResource(\"/device.json\", Device.class));\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/devices/1\");\n   }\n\n   public void testGetDeviceReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      Device device = api.deviceApi(\"93907f48-adfe-43ed-ad89-0e6e83721a54\").get(\"1\");\n\n      assertNull(device);\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/devices/1\");\n   }\n\n   public void testCreateDevice() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/device-create-res.json\"));\n\n      Device device = api.deviceApi(\"93907f48-adfe-43ed-ad89-0e6e83721a54\").create(\n              CreateDevice.builder()\n                      .hostname(\"jclouds-device-livetest\")\n                      .plan(\"baremetal_0\")\n                      .billingCycle(BillingCycle.HOURLY.value())\n                      .facility(\"ewr1\")\n                      .features(ImmutableMap.<String, String>of())\n                      .operatingSystem(\"ubuntu_16_04\")\n                      .locked(false)\n                      .userdata(\"\")\n                      .tags(ImmutableSet.<String> of())\n                      .build()\n      );\n\n      assertEquals(device, objectFromResource(\"/device-create-res.json\", Device.class));\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"POST\", \"/projects/93907f48-adfe-43ed-ad89-0e6e83721a54/devices\", stringFromResource(\"/device-create-req.json\"));\n   }\n\n   public void testDeleteDevice() throws InterruptedException {\n      server.enqueue(response204());\n\n      api.deviceApi(\"93907f48-adfe-43ed-ad89-0e6e83721a54\").delete(\"1\");\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"DELETE\", \"/devices/1\");\n   }\n\n   public void testDeleteDeviceReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      api.deviceApi(\"93907f48-adfe-43ed-ad89-0e6e83721a54\").delete(\"1\");\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"DELETE\", \"/devices/1\");\n   }\n\n   public void testActionPowerOn() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/power-on.json\"));\n\n      api.deviceApi(\"93907f48-adfe-43ed-ad89-0e6e83721a54\").powerOn(\"deviceId\");\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"POST\", \"/devices/deviceId/actions\");\n   }\n\n   public void testActionPowerOff() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/power-off.json\"));\n\n      api.deviceApi(\"93907f48-adfe-43ed-ad89-0e6e83721a54\").powerOff(\"deviceId\");\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"POST\", \"/devices/deviceId/actions\");\n   }\n\n   public void testActionReboot() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/reboot.json\"));\n\n      api.deviceApi(\"93907f48-adfe-43ed-ad89-0e6e83721a54\").reboot(\"deviceId\");\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"POST\", \"/devices/deviceId/actions\");\n   }\n\n}\n"
  },
  {
    "path": "providers/packet/src/test/java/org/jclouds/packet/features/FacilityApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.features;\n\nimport java.util.concurrent.atomic.AtomicInteger;\n\nimport org.jclouds.packet.compute.internal.BasePacketApiLiveTest;\nimport org.jclouds.packet.domain.Facility;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Iterables;\n\nimport static org.jclouds.packet.domain.options.ListOptions.Builder.page;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.util.Strings.isNullOrEmpty;\n\n@Test(groups = \"live\", testName = \"FacilityApiLiveTest\")\npublic class FacilityApiLiveTest extends BasePacketApiLiveTest {\n\n   public void testList() {\n      final AtomicInteger found = new AtomicInteger(0);\n      assertTrue(Iterables.all(api().list().concat(), new Predicate<Facility>() {\n         @Override\n         public boolean apply(Facility input) {\n            found.incrementAndGet();\n            return !isNullOrEmpty(input.id());\n         }\n      }), \"All facilities must have the 'id' field populated\");\n      assertTrue(found.get() > 0, \"Expected some facilities to be returned\");\n   }\n\n   public void testListOnePage() {\n      final AtomicInteger found = new AtomicInteger(0);\n      assertTrue(api().list(page(1).perPage(5)).allMatch(new Predicate<Facility>() {\n         @Override\n         public boolean apply(Facility input) {\n            found.incrementAndGet();\n            return !isNullOrEmpty(input.id());\n         }\n      }), \"All facilities must have the 'id' field populated\");\n      assertTrue(found.get() > 0, \"Expected some facilities to be returned\");\n   }\n\n   private FacilityApi api() {\n      return api.facilityApi();\n   }\n}\n"
  },
  {
    "path": "providers/packet/src/test/java/org/jclouds/packet/features/FacilityApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.features;\n\nimport org.jclouds.packet.compute.internal.BasePacketApiMockTest;\nimport org.jclouds.packet.domain.Facility;\nimport org.testng.annotations.Test;\n\nimport static com.google.common.collect.Iterables.isEmpty;\nimport static com.google.common.collect.Iterables.size;\nimport static org.jclouds.packet.domain.options.ListOptions.Builder.page;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\n@Test(groups = \"unit\", testName = \"FacilityApiMockTest\", singleThreaded = true)\npublic class FacilityApiMockTest extends BasePacketApiMockTest {\n\n   public void testListFacilities() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/facilities-first.json\"));\n      server.enqueue(jsonResponse(\"/facilities-last.json\"));\n\n      Iterable<Facility> facilities = api.facilityApi().list().concat();\n\n      assertEquals(size(facilities), 3); // Force the PagedIterable to advance\n      assertEquals(server.getRequestCount(), 2);\n\n      assertSent(server, \"GET\", \"/facilities\");\n      assertSent(server, \"GET\", \"/facilities?page=2\");\n   }\n\n   public void testListFacilitiesReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      Iterable<Facility> facilities = api.facilityApi().list().concat();\n\n      assertTrue(isEmpty(facilities));\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/facilities\");\n   }\n\n   public void testListFacilitiesWithOptions() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/facilities-first.json\"));\n\n      Iterable<Facility> actions = api.facilityApi().list(page(1).perPage(2));\n\n      assertEquals(size(actions), 2);\n      assertEquals(server.getRequestCount(), 1);\n\n      assertSent(server, \"GET\", \"/facilities?page=1&per_page=2\");\n   }\n\n   public void testListFacilitiesWithOptionsReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      Iterable<Facility> actions = api.facilityApi().list(page(1).perPage(2));\n\n      assertTrue(isEmpty(actions));\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/facilities?page=1&per_page=2\");\n   }\n\n}\n"
  },
  {
    "path": "providers/packet/src/test/java/org/jclouds/packet/features/OperatingSystemApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.features;\n\nimport java.util.concurrent.atomic.AtomicInteger;\n\nimport org.jclouds.packet.compute.internal.BasePacketApiLiveTest;\nimport org.jclouds.packet.domain.OperatingSystem;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Iterables;\n\nimport static org.jclouds.packet.domain.options.ListOptions.Builder.page;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.util.Strings.isNullOrEmpty;\n\n@Test(groups = \"live\", testName = \"OperatingSystemApiLiveTest\")\npublic class OperatingSystemApiLiveTest extends BasePacketApiLiveTest {\n\n   public void testList() {\n      final AtomicInteger found = new AtomicInteger(0);\n      assertTrue(Iterables.all(api().list().concat(), new Predicate<OperatingSystem>() {\n         @Override\n         public boolean apply(OperatingSystem input) {\n            found.incrementAndGet();\n            return !isNullOrEmpty(input.id());\n         }\n      }), \"All operating systems must have the 'id' field populated\");\n      assertTrue(found.get() > 0, \"Expected some operating systems to be returned\");\n   }\n\n   public void testListOnePage() {\n      final AtomicInteger found = new AtomicInteger(0);\n      assertTrue(api().list(page(1).perPage(5)).allMatch(new Predicate<OperatingSystem>() {\n         @Override\n         public boolean apply(OperatingSystem input) {\n            found.incrementAndGet();\n            return !isNullOrEmpty(input.id());\n         }\n      }), \"All operating systems must have the 'id' field populated\");\n      assertTrue(found.get() > 0, \"Expected some operating systems to be returned\");\n   }\n\n   private OperatingSystemApi api() {\n      return api.operatingSystemApi();\n   }\n}\n"
  },
  {
    "path": "providers/packet/src/test/java/org/jclouds/packet/features/OperatingSystemApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.features;\n\nimport org.jclouds.packet.compute.internal.BasePacketApiMockTest;\nimport org.jclouds.packet.domain.OperatingSystem;\nimport org.testng.annotations.Test;\n\nimport static com.google.common.collect.Iterables.isEmpty;\nimport static com.google.common.collect.Iterables.size;\nimport static org.jclouds.packet.domain.options.ListOptions.Builder.page;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\n@Test(groups = \"unit\", testName = \"OperatingSystemApiMockTest\", singleThreaded = true)\npublic class OperatingSystemApiMockTest extends BasePacketApiMockTest {\n\n   public void testListOperatingSystems() throws InterruptedException {\n\n      server.enqueue(jsonResponse(\"/operatingSystems-first.json\"));\n      server.enqueue(jsonResponse(\"/operatingSystems-last.json\"));\n\n      Iterable<OperatingSystem> operatingSystems = api.operatingSystemApi().list().concat();\n      assertEquals(size(operatingSystems), 14); // Force the PagedIterable to advance\n      assertEquals(server.getRequestCount(), 2);\n\n      assertSent(server, \"GET\", \"/operating-systems\");\n      assertSent(server, \"GET\", \"/operating-systems?page=2\");\n   }\n\n   public void testListOperatingSystemsReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      Iterable<OperatingSystem> operatingSystems = api.operatingSystemApi().list().concat();\n\n      assertTrue(isEmpty(operatingSystems));\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/operating-systems\");\n   }\n\n   public void testListOperatingSystemsWithOptions() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/operatingSystems-first.json\"));\n\n      Iterable<OperatingSystem> operatingSystems = api.operatingSystemApi().list(page(1).perPage(5));\n\n      assertEquals(size(operatingSystems), 7);\n      assertEquals(server.getRequestCount(), 1);\n\n      assertSent(server, \"GET\", \"/operating-systems?page=1&per_page=5\");\n   }\n\n   public void testListOperatingSystemsWithOptionsReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      Iterable<OperatingSystem> operatingSystems = api.operatingSystemApi().list(page(1).perPage(5));\n\n      assertTrue(isEmpty(operatingSystems));\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/operating-systems?page=1&per_page=5\");\n   }\n\n}\n"
  },
  {
    "path": "providers/packet/src/test/java/org/jclouds/packet/features/PlanApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.features;\n\nimport java.util.concurrent.atomic.AtomicInteger;\n\nimport org.jclouds.packet.compute.internal.BasePacketApiLiveTest;\nimport org.jclouds.packet.domain.Plan;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Iterables;\n\nimport static org.jclouds.packet.domain.options.ListOptions.Builder.page;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.util.Strings.isNullOrEmpty;\n\n@Test(groups = \"live\", testName = \"PlanApiLiveTest\")\npublic class PlanApiLiveTest extends BasePacketApiLiveTest {\n\n   public void testList() {\n      final AtomicInteger found = new AtomicInteger(0);\n      assertTrue(Iterables.all(api().list().concat(), new Predicate<Plan>() {\n         @Override\n         public boolean apply(Plan input) {\n            found.incrementAndGet();\n            return !isNullOrEmpty(input.id());\n         }\n      }), \"All plans must have the 'id' field populated\");\n      assertTrue(found.get() > 0, \"Expected some plans to be returned\");\n   }\n\n   public void testListOnePage() {\n      final AtomicInteger found = new AtomicInteger(0);\n      assertTrue(api().list(page(1).perPage(5)).allMatch(new Predicate<Plan>() {\n         @Override\n         public boolean apply(Plan input) {\n            found.incrementAndGet();\n            return !isNullOrEmpty(input.id());\n         }\n      }), \"All plans must have the 'id' field populated\");\n      assertTrue(found.get() > 0, \"Expected some plans to be returned\");\n   }\n\n   private PlanApi api() {\n      return api.planApi();\n   }\n}\n"
  },
  {
    "path": "providers/packet/src/test/java/org/jclouds/packet/features/PlanApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.features;\n\nimport org.jclouds.packet.compute.internal.BasePacketApiMockTest;\nimport org.jclouds.packet.domain.Plan;\nimport org.testng.annotations.Test;\n\nimport static com.google.common.collect.Iterables.isEmpty;\nimport static com.google.common.collect.Iterables.size;\nimport static org.jclouds.packet.domain.options.ListOptions.Builder.page;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\n@Test(groups = \"unit\", testName = \"PlanApiMockTest\", singleThreaded = true)\npublic class PlanApiMockTest extends BasePacketApiMockTest {\n\n   public void testListPlans() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/plans-first.json\"));\n      server.enqueue(jsonResponse(\"/plans-last.json\"));\n\n      Iterable<Plan> plans = api.planApi().list().concat();\n\n      assertEquals(size(plans), 7); // Force the PagedIterable to advance\n      assertEquals(server.getRequestCount(), 2);\n\n      assertSent(server, \"GET\", \"/plans\");\n      assertSent(server, \"GET\", \"/plans?page=2\");\n   }\n\n   public void testListPlansReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      Iterable<Plan> plans = api.planApi().list().concat();\n\n      assertTrue(isEmpty(plans));\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/plans\");\n   }\n\n   public void testListPlansWithOptions() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/plans-first.json\"));\n\n      Iterable<Plan> plans = api.planApi().list(page(1).perPage(5));\n\n      assertEquals(size(plans), 4);\n      assertEquals(server.getRequestCount(), 1);\n\n      assertSent(server, \"GET\", \"/plans?page=1&per_page=5\");\n   }\n\n   public void testListPlansWithOptionsReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      Iterable<Plan> plans = api.planApi().list(page(1).perPage(5));\n\n      assertTrue(isEmpty(plans));\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/plans?page=1&per_page=5\");\n   }\n\n}\n"
  },
  {
    "path": "providers/packet/src/test/java/org/jclouds/packet/features/ProjectApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.features;\n\nimport java.util.concurrent.atomic.AtomicInteger;\n\nimport org.jclouds.packet.compute.internal.BasePacketApiLiveTest;\nimport org.jclouds.packet.domain.Project;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Iterables;\n\nimport static org.jclouds.packet.domain.options.ListOptions.Builder.page;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.util.Strings.isNullOrEmpty;\n\n@Test(groups = \"live\", testName = \"ProjectApiLiveTest\")\npublic class ProjectApiLiveTest extends BasePacketApiLiveTest {\n\n   public void testList() {\n      final AtomicInteger found = new AtomicInteger(0);\n      assertTrue(Iterables.all(api().list().concat(), new Predicate<Project>() {\n         @Override\n         public boolean apply(Project input) {\n            found.incrementAndGet();\n            return !isNullOrEmpty(input.id());\n         }\n      }), \"All projects must have the 'id' field populated\");\n      assertTrue(found.get() > 0, \"Expected some projects to be returned\");\n   }\n\n   public void testListOnePage() {\n      final AtomicInteger found = new AtomicInteger(0);\n      assertTrue(api().list(page(1).perPage(5)).allMatch(new Predicate<Project>() {\n         @Override\n         public boolean apply(Project input) {\n            found.incrementAndGet();\n            return !isNullOrEmpty(input.id());\n         }\n      }), \"All projects must have the 'id' field populated\");\n      assertTrue(found.get() > 0, \"Expected some projects to be returned\");\n   }\n\n   private ProjectApi api() {\n      return api.projectApi();\n   }\n}\n"
  },
  {
    "path": "providers/packet/src/test/java/org/jclouds/packet/features/ProjectApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.features;\n\nimport org.jclouds.packet.compute.internal.BasePacketApiMockTest;\nimport org.jclouds.packet.domain.Project;\nimport org.testng.annotations.Test;\n\nimport static com.google.common.collect.Iterables.isEmpty;\nimport static com.google.common.collect.Iterables.size;\nimport static org.jclouds.packet.domain.options.ListOptions.Builder.page;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\n@Test(groups = \"unit\", testName = \"ProjectApiMockTest\", singleThreaded = true)\npublic class ProjectApiMockTest extends BasePacketApiMockTest {\n\n   public void testListProjects() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/projects-first.json\"));\n      server.enqueue(jsonResponse(\"/projects-last.json\"));\n\n      Iterable<Project> projects = api.projectApi().list().concat();\n\n      assertEquals(size(projects), 8); // Force the PagedIterable to advance\n      assertEquals(server.getRequestCount(), 2);\n\n      assertSent(server, \"GET\", \"/projects\");\n      assertSent(server, \"GET\", \"/projects?page=2\");\n   }\n\n   public void testListProjectsReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      Iterable<Project> projects = api.projectApi().list().concat();\n\n      assertTrue(isEmpty(projects));\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/projects\");\n   }\n\n   public void testListProjectsWithOptions() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/projects-first.json\"));\n\n      Iterable<Project> actions = api.projectApi().list(page(1).perPage(5));\n\n      assertEquals(size(actions), 5);\n      assertEquals(server.getRequestCount(), 1);\n\n      assertSent(server, \"GET\", \"/projects?page=1&per_page=5\");\n   }\n\n   public void testListProjectsWithOptionsReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      Iterable<Project> actions = api.projectApi().list(page(1).perPage(5));\n\n      assertTrue(isEmpty(actions));\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/projects?page=1&per_page=5\");\n   }\n\n}\n"
  },
  {
    "path": "providers/packet/src/test/java/org/jclouds/packet/features/SshKeyApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.features;\n\nimport java.util.Map;\nimport java.util.concurrent.atomic.AtomicInteger;\n\nimport org.jclouds.packet.compute.internal.BasePacketApiLiveTest;\nimport org.jclouds.packet.domain.SshKey;\nimport org.jclouds.ssh.SshKeys;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Iterables;\n\nimport static org.jclouds.packet.domain.options.ListOptions.Builder.page;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.util.Strings.isNullOrEmpty;\n\n@Test(groups = \"live\", testName = \"SshKeyApiLiveTest\")\npublic class SshKeyApiLiveTest extends BasePacketApiLiveTest {\n\n   private SshKey sshKey;\n\n   public void testCreate() {\n      Map<String, String> keyPair = SshKeys.generate();\n      sshKey = api.sshKeyApi().create(prefix + \"-sshkey-livetest\", keyPair.get(\"public\"));\n   }\n\n   @Test(dependsOnMethods = \"testCreate\")\n   public void testGet() {\n      api.sshKeyApi().get(sshKey.id());\n   }\n\n   @Test(dependsOnMethods = \"testCreate\")\n   public void testList() {\n      final AtomicInteger found = new AtomicInteger(0);\n      assertTrue(Iterables.all(api().list().concat(), new Predicate<SshKey>() {\n         @Override\n         public boolean apply(SshKey input) {\n            found.incrementAndGet();\n            return !isNullOrEmpty(input.id());\n         }\n      }), \"All ssh keys must have the 'id' field populated\");\n      assertTrue(found.get() > 0, \"Expected some ssh keys to be returned\");\n   }\n\n   @Test(dependsOnMethods = \"testCreate\")\n   public void testListOnePage() {\n      final AtomicInteger found = new AtomicInteger(0);\n      assertTrue(api().list(page(1).perPage(5)).allMatch(new Predicate<SshKey>() {\n         @Override\n         public boolean apply(SshKey input) {\n            found.incrementAndGet();\n            return !isNullOrEmpty(input.id());\n         }\n      }), \"All ssh keys must have the 'id' field populated\");\n      assertTrue(found.get() > 0, \"Expected some ssh keys to be returned\");\n   }\n\n   @Test(dependsOnMethods = \"testList\", alwaysRun = true)\n   public void testDelete() throws InterruptedException {\n      api.sshKeyApi().delete(sshKey.id());\n   }\n\n   private SshKeyApi api() {\n      return api.sshKeyApi();\n   }\n}\n"
  },
  {
    "path": "providers/packet/src/test/java/org/jclouds/packet/features/SshKeyApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.features;\n\nimport org.jclouds.packet.compute.internal.BasePacketApiMockTest;\nimport org.jclouds.packet.domain.SshKey;\nimport org.testng.annotations.Test;\n\nimport static com.google.common.collect.Iterables.isEmpty;\nimport static com.google.common.collect.Iterables.size;\nimport static org.jclouds.packet.domain.options.ListOptions.Builder.page;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\n@Test(groups = \"unit\", testName = \"SshKeyApiMockTest\", singleThreaded = true)\npublic class SshKeyApiMockTest extends BasePacketApiMockTest {\n\n   public void testListSshKeys() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/sshKeys-first.json\"));\n      server.enqueue(jsonResponse(\"/sshKeys-last.json\"));\n\n      Iterable<SshKey> sshkeys = api.sshKeyApi().list().concat();\n\n      assertEquals(size(sshkeys), 8); // Force the PagedIterable to advance\n      assertEquals(server.getRequestCount(), 2);\n\n      assertSent(server, \"GET\", \"/ssh-keys\");\n      assertSent(server, \"GET\", \"/ssh-keys?page=2\");\n   }\n\n   public void testListSshKeysReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      Iterable<SshKey> sshkeys = api.sshKeyApi().list().concat();\n\n      assertTrue(isEmpty(sshkeys));\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/ssh-keys\");\n   }\n\n   public void testListSshKeysWithOptions() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/sshKeys-first.json\"));\n\n      Iterable<SshKey> actions = api.sshKeyApi().list(page(1).perPage(5));\n\n      assertEquals(size(actions), 5);\n      assertEquals(server.getRequestCount(), 1);\n\n      assertSent(server, \"GET\", \"/ssh-keys?page=1&per_page=5\");\n   }\n\n   public void testListSshKeysWithOptionsReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      Iterable<SshKey> actions = api.sshKeyApi().list(page(1).perPage(5));\n\n      assertTrue(isEmpty(actions));\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/ssh-keys?page=1&per_page=5\");\n   }\n\n   public void testGetSshKey() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/ssh-key.json\"));\n\n      SshKey sshKey = api.sshKeyApi().get(\"1\");\n\n      assertEquals(sshKey, objectFromResource(\"/ssh-key.json\", SshKey.class));\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/ssh-keys/1\");\n   }\n\n   public void testGetSshKeyReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      SshKey sshKey = api.sshKeyApi().get(\"1\");\n\n      assertNull(sshKey);\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"GET\", \"/ssh-keys/1\");\n   }\n\n   public void testCreateSshKey() throws InterruptedException {\n      server.enqueue(jsonResponse(\"/ssh-key-create-res.json\"));\n\n      SshKey sshKey = api.sshKeyApi().create(\n              \"jclouds-ssh-key-livetest\",\n              \"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCdgcoNzH4hCc0j3b4MuG503L/J54uyFvwCAOu8vSsYuLpJ4AEyEOv+T0SfdF605fK6GYXA16Rxk3lrPt7mfKGNtXR0Ripbv7Zc6PvCRorwgj/cjh/45miozjrkXAiHD1GFZycfbi4YsoWAqZj7W4mwtctmhrYM0FPdya2XoRpVy89N+A5Xo4Xtd6EZn6JGEKQM5+kF2aL3ggy0od/DqjuEVYwZoyTe1RgUTXZSU/Woh7WMhsRHbqd3eYz4s6ac8n8IJPGKtUaQeqUtH7OK6NRYXVypUrkqNlwdNYZAwrjXg/x5T3D+bo11LENASRt9OJ2OkmRSTqRxBeDkhnVauWK/\"\n      );\n\n      assertEquals(sshKey, objectFromResource(\"/ssh-key-create-res.json\", SshKey.class));\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"POST\", \"/ssh-keys\", stringFromResource(\"/ssh-key-create-req.json\"));\n   }\n\n   public void testDeleteSshKey() throws InterruptedException {\n      server.enqueue(response204());\n\n      api.sshKeyApi().delete(\"1\");\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"DELETE\", \"/ssh-keys/1\");\n   }\n\n   public void testDeleteSshKeyReturns404() throws InterruptedException {\n      server.enqueue(response404());\n\n      api.sshKeyApi().delete(\"1\");\n\n      assertEquals(server.getRequestCount(), 1);\n      assertSent(server, \"DELETE\", \"/ssh-keys/1\");\n   }\n\n\n}\n"
  },
  {
    "path": "providers/packet/src/test/java/org/jclouds/packet/functions/HrefToListOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.packet.functions;\n\nimport org.jclouds.packet.domain.Href;\nimport org.jclouds.packet.domain.options.ListOptions;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Multimap;\n\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static org.jclouds.packet.domain.options.ListOptions.PAGE_PARAM;\nimport static org.jclouds.packet.domain.options.ListOptions.PER_PAGE_PARAM;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\n\n@Test(groups = \"unit\", testName = \"HrefToListOptionsTest\")\npublic class HrefToListOptionsTest {\n\n   public void testNoOptions() {\n      HrefToListOptions function = new HrefToListOptions();\n\n      ListOptions options = function.apply(Href.create(\"https://api.packet.net/projects\"));\n      assertNotNull(options);\n\n      Multimap<String, String> params = options.buildQueryParameters();\n      assertFalse(params.containsKey(PAGE_PARAM));\n      assertFalse(params.containsKey(PER_PAGE_PARAM));\n   }\n\n   public void testWithOptions() {\n      HrefToListOptions function = new HrefToListOptions();\n\n      ListOptions options = function.apply(Href.create(\"https://api.packet.net/projects?page=2&per_page=5\"));\n      assertNotNull(options);\n\n      Multimap<String, String> params = options.buildQueryParameters();\n      assertEquals(getOnlyElement(params.get(PAGE_PARAM)), \"2\");\n      assertEquals(getOnlyElement(params.get(PER_PAGE_PARAM)), \"5\");\n   }\n\n}\n"
  },
  {
    "path": "providers/packet/src/test/resources/device-create-req.json",
    "content": "{\n  \"hostname\": \"jclouds-device-livetest\",\n  \"plan\": \"baremetal_0\",\n  \"billing_cycle\": \"hourly\",\n  \"facility\": \"ewr1\",\n  \"features\": {},\n  \"operating_system\": \"ubuntu_16_04\",\n  \"locked\": false,\n  \"userdata\": \"\",\n  \"tags\": []\n}\n"
  },
  {
    "path": "providers/packet/src/test/resources/device-create-res.json",
    "content": "{\n  \"id\": \"3238ce59-fe02-4b9b-92c1-915ef4f3fb9e\",\n  \"short_id\": \"3238ce59\",\n  \"hostname\": \"andrea-device-livetest\",\n  \"description\": null,\n  \"state\": \"queued\",\n  \"tags\": [],\n  \"billing_cycle\": \"hourly\",\n  \"user\": \"root\",\n  \"iqn\": \"iqn.2017-01.net.packet:device.3238ce59\",\n  \"locked\": false,\n  \"bonding_mode\": 5,\n  \"created_at\": \"2017-01-20T14:15:28Z\",\n  \"updated_at\": \"2017-01-20T14:15:29Z\",\n  \"provisioning_percentage\": 10.0,\n  \"operating_system\": {\n    \"id\": \"1b9b78e3-de68-466e-ba00-f2123e89c112\",\n    \"slug\": \"ubuntu_16_04\",\n    \"name\": \"Ubuntu 16.04 LTS\",\n    \"distro\": \"ubuntu\",\n    \"version\": \"16.04\",\n    \"provisionable_on\": [\n      \"baremetal_0\",\n      \"baremetal_1\",\n      \"baremetal_2\",\n      \"baremetal_2a\",\n      \"baremetal_3\",\n      \"baremetal_hua\"\n    ]\n  },\n  \"facility\": {\n    \"id\": \"e1e9c52e-a0bc-4117-b996-0fc94843ea09\",\n    \"name\": \"Parsippany, NJ\",\n    \"code\": \"ewr1\",\n    \"features\": [\n      \"baremetal\",\n      \"storage\"\n    ],\n    \"address\": null\n  },\n  \"project\": {\n    \"href\": \"/projects/93907f48-adfe-43ed-ad89-0e6e83721a54\"\n  },\n  \"ssh_keys\": [\n    {\n      \"href\": \"/ssh-keys/a3d8bebe-574f-427d-80ee-bc2ba17f7074\"\n    },\n    {\n      \"href\": \"/ssh-keys/a8d6cc17-7d9d-4fb9-8190-afdb301b67df\"\n    },\n    {\n      \"href\": \"/ssh-keys/084a5dec-30be-415a-8937-9c615932e459\"\n    },\n    {\n      \"href\": \"/ssh-keys/eacfb002-45e1-4047-a0d5-cd9d8bab19ed\"\n    },\n    {\n      \"href\": \"/ssh-keys/f82b69d7-8c7e-4a38-9283-ecdbcaba56aa\"\n    },\n    {\n      \"href\": \"/ssh-keys/da5d6c21-2e8c-43ac-820f-ff41bd4e6ebc\"\n    }\n  ],\n  \"project_lite\": {\n    \"href\": \"/projects/93907f48-adfe-43ed-ad89-0e6e83721a54\"\n  },\n  \"volumes\": [],\n  \"ip_addresses\": [],\n  \"provisioning_events\": [\n    {\n      \"id\": \"32a4da09-37dd-446b-99ef-9f64c1eb0097\",\n      \"type\": \"provisioning.101\",\n      \"body\": \"Provisioning started\",\n      \"created_at\": \"2017-01-20T14:15:29Z\",\n      \"relationships\": [\n        {\n          \"href\": \"#5062a5fe-19ea-4b41-864c-e5f4dcb02fa0\"\n        }\n      ],\n      \"interpolated\": \"Provisioning started\",\n      \"href\": \"/events/32a4da09-37dd-446b-99ef-9f64c1eb0097\"\n    },\n    {\n      \"id\": null,\n      \"type\": \"provisioning.102\",\n      \"body\": \"Network configured\",\n      \"created_at\": null,\n      \"relationships\": [],\n      \"interpolated\": \"Network configured\"\n    },\n    {\n      \"id\": null,\n      \"type\": \"provisioning.103\",\n      \"body\": \"Configuration written, restarting device\",\n      \"created_at\": null,\n      \"relationships\": [],\n      \"interpolated\": \"Configuration written, restarting device\"\n    },\n    {\n      \"id\": null,\n      \"type\": \"provisioning.104\",\n      \"body\": \"Connected to magic install system\",\n      \"created_at\": null,\n      \"relationships\": [],\n      \"interpolated\": \"Connected to magic install system\"\n    },\n    {\n      \"id\": null,\n      \"type\": \"provisioning.105\",\n      \"body\": \"Server partitions created\",\n      \"created_at\": null,\n      \"relationships\": [],\n      \"interpolated\": \"Server partitions created\"\n    },\n    {\n      \"id\": null,\n      \"type\": \"provisioning.106\",\n      \"body\": \"Operating system packages installed\",\n      \"created_at\": null,\n      \"relationships\": [],\n      \"interpolated\": \"Operating system packages installed\"\n    },\n    {\n      \"id\": null,\n      \"type\": \"provisioning.107\",\n      \"body\": \"Server networking interfaces configured\",\n      \"created_at\": null,\n      \"relationships\": [],\n      \"interpolated\": \"Server networking interfaces configured\"\n    },\n    {\n      \"id\": null,\n      \"type\": \"provisioning.108\",\n      \"body\": \"Cloud-init packages installed and configured\",\n      \"created_at\": null,\n      \"relationships\": [],\n      \"interpolated\": \"Cloud-init packages installed and configured\"\n    },\n    {\n      \"id\": null,\n      \"type\": \"provisioning.109\",\n      \"body\": \"Installation finished, rebooting server\",\n      \"created_at\": null,\n      \"relationships\": [],\n      \"interpolated\": \"Installation finished, rebooting server\"\n    },\n    {\n      \"id\": null,\n      \"type\": \"provisioning.109\",\n      \"body\": \"Installation finished, rebooting server\",\n      \"created_at\": null,\n      \"relationships\": [],\n      \"interpolated\": \"Installation finished, rebooting server\"\n    }\n  ],\n  \"plan\": {\n    \"id\": \"e69c0169-4726-46ea-98f1-939c9e8a3607\",\n    \"slug\": \"baremetal_0\",\n    \"name\": \"Type 0\",\n    \"description\": \"Our Type 0 configuration is a general use \\\"cloud killer\\\" server, with a Intel Atom 2.4Ghz processor and 8GB of RAM.\",\n    \"line\": \"baremetal\",\n    \"specs\": {\n      \"cpus\": [\n        {\n          \"count\": 1,\n          \"type\": \"Intel Atom C2550 @ 2.4Ghz\"\n        }\n      ],\n      \"memory\": {\n        \"total\": \"8GB\"\n      },\n      \"drives\": [\n        {\n          \"count\": 1,\n          \"size\": \"80GB\",\n          \"type\": \"SSD\"\n        }\n      ],\n      \"nics\": [\n        {\n          \"count\": 2,\n          \"type\": \"1Gbps\"\n        }\n      ],\n      \"features\": {\n        \"raid\": false,\n        \"txt\": true\n      }\n    },\n    \"available_in\": [\n      {\n        \"href\": \"/facilities/2b70eb8f-fa18-47c0-aba7-222a842362fd\"\n      },\n      {\n        \"href\": \"/facilities/8e6470b3-b75e-47d1-bb93-45b225750975\"\n      },\n      {\n        \"href\": \"/facilities/8ea03255-89f9-4e62-9d3f-8817db82ceed\"\n      },\n      {\n        \"href\": \"/facilities/e1e9c52e-a0bc-4117-b996-0fc94843ea09\"\n      }\n    ],\n    \"pricing\": {\n      \"hour\": 0.05\n    }\n  },\n  \"userdata\": \"\",\n  \"root_password\": \"$n4hwka3!i\",\n  \"href\": \"/devices/3238ce59-fe02-4b9b-92c1-915ef4f3fb9e\"\n}\n"
  },
  {
    "path": "providers/packet/src/test/resources/device.json",
    "content": "{\n  \"id\": \"98e22032-579e-4c04-bb12-05cc6a3864c8\",\n  \"short_id\": \"98e22032\",\n  \"hostname\": \"test\",\n  \"description\": null,\n  \"state\": \"provisioning\",\n  \"tags\": [],\n  \"billing_cycle\": \"hourly\",\n  \"user\": \"root\",\n  \"iqn\": \"iqn.2017-01.net.packet:device.98e22032\",\n  \"locked\": false,\n  \"bonding_mode\": 5,\n  \"created_at\": \"2017-01-03T09:47:59Z\",\n  \"updated_at\": \"2017-01-03T09:50:13Z\",\n  \"provisioning_percentage\": 50,\n  \"operating_system\": {\n    \"id\": \"68bad60d-f5a7-45c2-ad09-573edaad3a3c\",\n    \"slug\": \"centos_7\",\n    \"name\": \"Centos 7\",\n    \"distro\": \"centos\",\n    \"version\": \"7\",\n    \"provisionable_on\": [\n      \"baremetal_0\",\n      \"baremetal_1\",\n      \"baremetal_2\",\n      \"baremetal_3\"\n    ]\n  },\n  \"facility\": {\n    \"id\": \"e1e9c52e-a0bc-4117-b996-0fc94843ea09\",\n    \"name\": \"Parsippany, NJ\",\n    \"code\": \"ewr1\",\n    \"features\": [\n      \"baremetal\",\n      \"storage\"\n    ],\n    \"address\": null\n  },\n  \"project\": {\n    \"href\": \"/projects/93907f48-adfe-43ed-ad89-0e6e83721a54\"\n  },\n  \"ssh_keys\": [\n    {\n      \"href\": \"/ssh-keys/084a5dec-30be-415a-8937-9c615932e459\"\n    },\n    {\n      \"href\": \"/ssh-keys/a8d6cc17-7d9d-4fb9-8190-afdb301b67df\"\n    },\n    {\n      \"href\": \"/ssh-keys/a3d8bebe-574f-427d-80ee-bc2ba17f7074\"\n    },\n    {\n      \"href\": \"/ssh-keys/eacfb002-45e1-4047-a0d5-cd9d8bab19ed\"\n    },\n    {\n      \"href\": \"/ssh-keys/bba63e41-b12c-493a-81d4-e52f50f247ed\"\n    }\n  ],\n  \"project_lite\": {\n    \"href\": \"/projects/93907f48-adfe-43ed-ad89-0e6e83721a54\"\n  },\n  \"volumes\": [],\n  \"ip_addresses\": [\n    {\n      \"id\": \"5d0262c7-1727-411c-94c4-9e6f15490dd3\",\n      \"address_family\": 4,\n      \"netmask\": \"255.255.255.254\",\n      \"created_at\": \"2017-01-03T09:47:59Z\",\n      \"public\": true,\n      \"cidr\": 31,\n      \"management\": true,\n      \"manageable\": true,\n      \"assigned_to\": {\n        \"href\": \"/devices/98e22032-579e-4c04-bb12-05cc6a3864c8\"\n      },\n      \"network\": \"147.75.106.80\",\n      \"address\": \"147.75.106.81\",\n      \"gateway\": \"147.75.106.80\",\n      \"href\": \"/ips/5d0262c7-1727-411c-94c4-9e6f15490dd3\"\n    },\n    {\n      \"id\": \"f7d0e65c-eb3b-42bd-af9b-ad3a736d8d43\",\n      \"address_family\": 6,\n      \"netmask\": \"ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe\",\n      \"created_at\": \"2017-01-03T09:47:59Z\",\n      \"public\": true,\n      \"cidr\": 127,\n      \"management\": true,\n      \"manageable\": true,\n      \"assigned_to\": {\n        \"href\": \"/devices/98e22032-579e-4c04-bb12-05cc6a3864c8\"\n      },\n      \"network\": \"2604:1380:2:9800::\",\n      \"address\": \"2604:1380:2:9800::1\",\n      \"gateway\": \"2604:1380:2:9800::\",\n      \"href\": \"/ips/f7d0e65c-eb3b-42bd-af9b-ad3a736d8d43\"\n    },\n    {\n      \"id\": \"a3d00b4e-d74f-4ac2-8bc9-91065d815b41\",\n      \"address_family\": 4,\n      \"netmask\": \"255.255.255.254\",\n      \"created_at\": \"2017-01-03T09:47:59Z\",\n      \"public\": false,\n      \"cidr\": 31,\n      \"management\": true,\n      \"manageable\": true,\n      \"assigned_to\": {\n        \"href\": \"/devices/98e22032-579e-4c04-bb12-05cc6a3864c8\"\n      },\n      \"network\": \"10.99.214.0\",\n      \"address\": \"10.99.214.1\",\n      \"gateway\": \"10.99.214.0\",\n      \"href\": \"/ips/a3d00b4e-d74f-4ac2-8bc9-91065d815b41\"\n    }\n  ],\n  \"provisioning_events\": [\n    {\n      \"id\": \"bd62123b-afed-4e54-b1b9-89e219ba9cf0\",\n      \"type\": \"provisioning.101\",\n      \"body\": \"Provisioning started\",\n      \"created_at\": \"2017-01-03T09:47:59Z\",\n      \"relationships\": [\n        {\n          \"href\": \"#81909921-255e-413c-883a-c58d14c801ae\"\n        }\n      ],\n      \"interpolated\": \"Provisioning started\",\n      \"href\": \"/events/bd62123b-afed-4e54-b1b9-89e219ba9cf0\"\n    },\n    {\n      \"id\": \"14b4a9e6-be90-40ee-be48-b272f855e39c\",\n      \"type\": \"provisioning.102\",\n      \"body\": \"Network configured with addresses 147.75.106.81, 2604:1380:2:9800::1, and 10.99.214.1\",\n      \"created_at\": \"2017-01-03T09:48:46Z\",\n      \"relationships\": [\n        {\n          \"href\": \"#28588657-b8bf-44a1-98d3-27f8e04b660a\"\n        }\n      ],\n      \"interpolated\": \"Network configured with addresses 147.75.106.81, 2604:1380:2:9800::1, and 10.99.214.1\",\n      \"href\": \"/events/14b4a9e6-be90-40ee-be48-b272f855e39c\"\n    },\n    {\n      \"id\": \"57e3cadb-f9aa-4c73-be54-3c83e6cf462e\",\n      \"type\": \"provisioning.103\",\n      \"body\": \"Configuration written, restarting device\",\n      \"created_at\": \"2017-01-03T09:48:57Z\",\n      \"relationships\": [\n        {\n          \"href\": \"#25a7e807-f4aa-4f36-83cd-8347baeb26bc\"\n        }\n      ],\n      \"interpolated\": \"Configuration written, restarting device\",\n      \"href\": \"/events/57e3cadb-f9aa-4c73-be54-3c83e6cf462e\"\n    },\n    {\n      \"id\": \"b8322996-f57e-4c87-96cc-a16f33a0c305\",\n      \"type\": \"provisioning.104\",\n      \"body\": \"Connected to magic install system\",\n      \"created_at\": \"2017-01-03T09:50:13Z\",\n      \"relationships\": [\n        {\n          \"href\": \"#a4825d20-f7f2-426a-88db-38696bd3dfd6\"\n        }\n      ],\n      \"interpolated\": \"Connected to magic install system\",\n      \"href\": \"/events/b8322996-f57e-4c87-96cc-a16f33a0c305\"\n    },\n    {\n      \"id\": \"f00a00a9-7c59-420d-bdcf-2c0993303cf6\",\n      \"type\": \"provisioning.105\",\n      \"body\": \"Server partitions created\",\n      \"created_at\": \"2017-01-03T09:50:13Z\",\n      \"relationships\": [\n        {\n          \"href\": \"#6140659b-5e3d-4686-be8f-8879b6d3e27f\"\n        }\n      ],\n      \"interpolated\": \"Server partitions created\",\n      \"href\": \"/events/f00a00a9-7c59-420d-bdcf-2c0993303cf6\"\n    },\n    {\n      \"id\": null,\n      \"type\": \"provisioning.106\",\n      \"body\": \"Operating system packages installed\",\n      \"created_at\": null,\n      \"relationships\": [],\n      \"interpolated\": \"Operating system packages installed\"\n    },\n    {\n      \"id\": null,\n      \"type\": \"provisioning.107\",\n      \"body\": \"Server networking interfaces configured\",\n      \"created_at\": null,\n      \"relationships\": [],\n      \"interpolated\": \"Server networking interfaces configured\"\n    },\n    {\n      \"id\": null,\n      \"type\": \"provisioning.108\",\n      \"body\": \"Cloud-init packages installed and configured\",\n      \"created_at\": null,\n      \"relationships\": [],\n      \"interpolated\": \"Cloud-init packages installed and configured\"\n    },\n    {\n      \"id\": null,\n      \"type\": \"provisioning.109\",\n      \"body\": \"Installation finished, rebooting server\",\n      \"created_at\": null,\n      \"relationships\": [],\n      \"interpolated\": \"Installation finished, rebooting server\"\n    },\n    {\n      \"id\": null,\n      \"type\": \"provisioning.109\",\n      \"body\": \"Installation finished, rebooting server\",\n      \"created_at\": null,\n      \"relationships\": [],\n      \"interpolated\": \"Installation finished, rebooting server\"\n    }\n  ],\n  \"plan\": {\n    \"id\": \"e69c0169-4726-46ea-98f1-939c9e8a3607\",\n    \"slug\": \"baremetal_0\",\n    \"name\": \"Type 0\",\n    \"description\": \"Our Type 0 configuration is a general use \\\"cloud killer\\\" server, with a Intel Atom 2.4Ghz processor and 8GB of RAM.\",\n    \"line\": \"baremetal\",\n    \"specs\": {\n      \"cpus\": [\n        {\n          \"count\": 1,\n          \"type\": \"Intel Atom C2550 @ 2.4Ghz\"\n        }\n      ],\n      \"memory\": {\n        \"total\": \"8GB\"\n      },\n      \"drives\": [\n        {\n          \"count\": 1,\n          \"size\": \"80GB\",\n          \"type\": \"SSD\"\n        }\n      ],\n      \"nics\": [\n        {\n          \"count\": 2,\n          \"type\": \"1Gbps\"\n        }\n      ],\n      \"features\": {\n        \"raid\": false,\n        \"txt\": true\n      }\n    },\n    \"available_in\": [\n      {\n        \"href\": \"/facilities/2b70eb8f-fa18-47c0-aba7-222a842362fd\"\n      },\n      {\n        \"href\": \"/facilities/8e6470b3-b75e-47d1-bb93-45b225750975\"\n      },\n      {\n        \"href\": \"/facilities/8ea03255-89f9-4e62-9d3f-8817db82ceed\"\n      },\n      {\n        \"href\": \"/facilities/e1e9c52e-a0bc-4117-b996-0fc94843ea09\"\n      }\n    ],\n    \"pricing\": {\n      \"hour\": 0.05\n    }\n  },\n  \"userdata\": \"\",\n  \"root_password\": \",q4*a8(eny\",\n  \"href\": \"/devices/98e22032-579e-4c04-bb12-05cc6a3864c8\"\n}\n"
  },
  {
    "path": "providers/packet/src/test/resources/devices-first.json",
    "content": "{\n  \"devices\": [\n    {\n      \"id\": \"5bd27259-8b71-48f7-879d-c4e695cb2f31\",\n      \"short_id\": \"5bd27259\",\n      \"hostname\": \"andrea-device-livetest\",\n      \"description\": null,\n      \"state\": \"active\",\n      \"tags\": [],\n      \"billing_cycle\": \"hourly\",\n      \"user\": \"root\",\n      \"iqn\": \"iqn.2017-01.net.packet:device.5bd27259\",\n      \"locked\": false,\n      \"bonding_mode\": 5,\n      \"created_at\": \"2017-01-18T17:12:29Z\",\n      \"updated_at\": \"2017-01-18T17:16:29Z\",\n      \"operating_system\": {\n        \"id\": \"1b9b78e3-de68-466e-ba00-f2123e89c112\",\n        \"slug\": \"ubuntu_16_04\",\n        \"name\": \"Ubuntu 16.04 LTS\",\n        \"distro\": \"ubuntu\",\n        \"version\": \"16.04\",\n        \"provisionable_on\": [\n          \"baremetal_0\",\n          \"baremetal_1\",\n          \"baremetal_2\",\n          \"baremetal_2a\",\n          \"baremetal_3\",\n          \"baremetal_hua\"\n        ]\n      },\n      \"facility\": {\n        \"id\": \"e1e9c52e-a0bc-4117-b996-0fc94843ea09\",\n        \"name\": \"Parsippany, NJ\",\n        \"code\": \"ewr1\",\n        \"features\": [\n          \"baremetal\",\n          \"storage\"\n        ],\n        \"address\": null\n      },\n      \"project\": {\n        \"href\": \"/projects/93907f48-adfe-43ed-ad89-0e6e83721a54\"\n      },\n      \"ssh_keys\": [\n        {\n          \"href\": \"/ssh-keys/a3d8bebe-574f-427d-80ee-bc2ba17f7074\"\n        },\n        {\n          \"href\": \"/ssh-keys/a8d6cc17-7d9d-4fb9-8190-afdb301b67df\"\n        },\n        {\n          \"href\": \"/ssh-keys/084a5dec-30be-415a-8937-9c615932e459\"\n        },\n        {\n          \"href\": \"/ssh-keys/eacfb002-45e1-4047-a0d5-cd9d8bab19ed\"\n        },\n        {\n          \"href\": \"/ssh-keys/f82b69d7-8c7e-4a38-9283-ecdbcaba56aa\"\n        },\n        {\n          \"href\": \"/ssh-keys/cf9db551-ec79-4c16-a776-97cdbcb3cec4\"\n        }\n      ],\n      \"project_lite\": {\n        \"href\": \"/projects/93907f48-adfe-43ed-ad89-0e6e83721a54\"\n      },\n      \"volumes\": [],\n      \"ip_addresses\": [\n        {\n          \"id\": \"cbff502b-12ca-4986-b683-2cb4e119ae40\",\n          \"address_family\": 4,\n          \"netmask\": \"255.255.255.254\",\n          \"created_at\": \"2017-01-18T17:12:30Z\",\n          \"public\": true,\n          \"cidr\": 31,\n          \"management\": true,\n          \"manageable\": true,\n          \"enabled\": true,\n          \"assigned_to\": {\n            \"href\": \"/devices/5bd27259-8b71-48f7-879d-c4e695cb2f31\"\n          },\n          \"network\": \"147.75.197.54\",\n          \"address\": \"147.75.197.55\",\n          \"gateway\": \"147.75.197.54\",\n          \"href\": \"/ips/cbff502b-12ca-4986-b683-2cb4e119ae40\"\n        },\n        {\n          \"id\": \"d5cec621-18c1-4e02-8f71-8dd46370c3e5\",\n          \"address_family\": 6,\n          \"netmask\": \"ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe\",\n          \"created_at\": \"2017-01-18T17:12:30Z\",\n          \"public\": true,\n          \"cidr\": 127,\n          \"management\": true,\n          \"manageable\": true,\n          \"enabled\": true,\n          \"assigned_to\": {\n            \"href\": \"/devices/5bd27259-8b71-48f7-879d-c4e695cb2f31\"\n          },\n          \"network\": \"2604:1380:2:9800::\",\n          \"address\": \"2604:1380:2:9800::1\",\n          \"gateway\": \"2604:1380:2:9800::\",\n          \"href\": \"/ips/d5cec621-18c1-4e02-8f71-8dd46370c3e5\"\n        },\n        {\n          \"id\": \"6d206311-1f88-454d-9cf2-afca79f51fa3\",\n          \"address_family\": 4,\n          \"netmask\": \"255.255.255.254\",\n          \"created_at\": \"2017-01-18T17:12:30Z\",\n          \"public\": false,\n          \"cidr\": 31,\n          \"management\": true,\n          \"manageable\": true,\n          \"enabled\": true,\n          \"assigned_to\": {\n            \"href\": \"/devices/5bd27259-8b71-48f7-879d-c4e695cb2f31\"\n          },\n          \"network\": \"10.99.214.0\",\n          \"address\": \"10.99.214.1\",\n          \"gateway\": \"10.99.214.0\",\n          \"href\": \"/ips/6d206311-1f88-454d-9cf2-afca79f51fa3\"\n        }\n      ],\n      \"plan\": {\n        \"id\": \"e69c0169-4726-46ea-98f1-939c9e8a3607\",\n        \"slug\": \"baremetal_0\",\n        \"name\": \"Type 0\",\n        \"description\": \"Our Type 0 configuration is a general use \\\"cloud killer\\\" server, with a Intel Atom 2.4Ghz processor and 8GB of RAM.\",\n        \"line\": \"baremetal\",\n        \"specs\": {\n          \"cpus\": [\n            {\n              \"count\": 1,\n              \"type\": \"Intel Atom C2550 @ 2.4Ghz\"\n            }\n          ],\n          \"memory\": {\n            \"total\": \"8GB\"\n          },\n          \"drives\": [\n            {\n              \"count\": 1,\n              \"size\": \"80GB\",\n              \"type\": \"SSD\"\n            }\n          ],\n          \"nics\": [\n            {\n              \"count\": 2,\n              \"type\": \"1Gbps\"\n            }\n          ],\n          \"features\": {\n            \"raid\": false,\n            \"txt\": true\n          }\n        },\n        \"available_in\": [\n          {\n            \"href\": \"/facilities/2b70eb8f-fa18-47c0-aba7-222a842362fd\"\n          },\n          {\n            \"href\": \"/facilities/8e6470b3-b75e-47d1-bb93-45b225750975\"\n          },\n          {\n            \"href\": \"/facilities/8ea03255-89f9-4e62-9d3f-8817db82ceed\"\n          },\n          {\n            \"href\": \"/facilities/e1e9c52e-a0bc-4117-b996-0fc94843ea09\"\n          }\n        ],\n        \"pricing\": {\n          \"hour\": 0.05\n        }\n      },\n      \"userdata\": \"\",\n      \"root_password\": \"soaz0#a=cd\",\n      \"href\": \"/devices/5bd27259-8b71-48f7-879d-c4e695cb2f31\"\n    },\n    {\n      \"id\": \"5bd27259-8b71-48f7-879d-c4e695cb2f32\",\n      \"short_id\": \"5bd27259\",\n      \"hostname\": \"andrea-device-livetest\",\n      \"description\": null,\n      \"state\": \"active\",\n      \"tags\": [],\n      \"billing_cycle\": \"hourly\",\n      \"user\": \"root\",\n      \"iqn\": \"iqn.2017-01.net.packet:device.5bd27259\",\n      \"locked\": false,\n      \"bonding_mode\": 5,\n      \"created_at\": \"2017-01-18T17:12:29Z\",\n      \"updated_at\": \"2017-01-18T17:16:29Z\",\n      \"operating_system\": {\n        \"id\": \"1b9b78e3-de68-466e-ba00-f2123e89c112\",\n        \"slug\": \"ubuntu_16_04\",\n        \"name\": \"Ubuntu 16.04 LTS\",\n        \"distro\": \"ubuntu\",\n        \"version\": \"16.04\",\n        \"provisionable_on\": [\n          \"baremetal_0\",\n          \"baremetal_1\",\n          \"baremetal_2\",\n          \"baremetal_2a\",\n          \"baremetal_3\",\n          \"baremetal_hua\"\n        ]\n      },\n      \"facility\": {\n        \"id\": \"e1e9c52e-a0bc-4117-b996-0fc94843ea09\",\n        \"name\": \"Parsippany, NJ\",\n        \"code\": \"ewr1\",\n        \"features\": [\n          \"baremetal\",\n          \"storage\"\n        ],\n        \"address\": null\n      },\n      \"project\": {\n        \"href\": \"/projects/93907f48-adfe-43ed-ad89-0e6e83721a54\"\n      },\n      \"ssh_keys\": [\n        {\n          \"href\": \"/ssh-keys/a3d8bebe-574f-427d-80ee-bc2ba17f7074\"\n        },\n        {\n          \"href\": \"/ssh-keys/a8d6cc17-7d9d-4fb9-8190-afdb301b67df\"\n        },\n        {\n          \"href\": \"/ssh-keys/084a5dec-30be-415a-8937-9c615932e459\"\n        },\n        {\n          \"href\": \"/ssh-keys/eacfb002-45e1-4047-a0d5-cd9d8bab19ed\"\n        },\n        {\n          \"href\": \"/ssh-keys/f82b69d7-8c7e-4a38-9283-ecdbcaba56aa\"\n        },\n        {\n          \"href\": \"/ssh-keys/cf9db551-ec79-4c16-a776-97cdbcb3cec4\"\n        }\n      ],\n      \"project_lite\": {\n        \"href\": \"/projects/93907f48-adfe-43ed-ad89-0e6e83721a54\"\n      },\n      \"volumes\": [],\n      \"ip_addresses\": [\n        {\n          \"id\": \"cbff502b-12ca-4986-b683-2cb4e119ae40\",\n          \"address_family\": 4,\n          \"netmask\": \"255.255.255.254\",\n          \"created_at\": \"2017-01-18T17:12:30Z\",\n          \"public\": true,\n          \"cidr\": 31,\n          \"management\": true,\n          \"manageable\": true,\n          \"enabled\": true,\n          \"assigned_to\": {\n            \"href\": \"/devices/5bd27259-8b71-48f7-879d-c4e695cb2f31\"\n          },\n          \"network\": \"147.75.197.54\",\n          \"address\": \"147.75.197.55\",\n          \"gateway\": \"147.75.197.54\",\n          \"href\": \"/ips/cbff502b-12ca-4986-b683-2cb4e119ae40\"\n        },\n        {\n          \"id\": \"d5cec621-18c1-4e02-8f71-8dd46370c3e5\",\n          \"address_family\": 6,\n          \"netmask\": \"ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe\",\n          \"created_at\": \"2017-01-18T17:12:30Z\",\n          \"public\": true,\n          \"cidr\": 127,\n          \"management\": true,\n          \"manageable\": true,\n          \"enabled\": true,\n          \"assigned_to\": {\n            \"href\": \"/devices/5bd27259-8b71-48f7-879d-c4e695cb2f31\"\n          },\n          \"network\": \"2604:1380:2:9800::\",\n          \"address\": \"2604:1380:2:9800::1\",\n          \"gateway\": \"2604:1380:2:9800::\",\n          \"href\": \"/ips/d5cec621-18c1-4e02-8f71-8dd46370c3e5\"\n        },\n        {\n          \"id\": \"6d206311-1f88-454d-9cf2-afca79f51fa3\",\n          \"address_family\": 4,\n          \"netmask\": \"255.255.255.254\",\n          \"created_at\": \"2017-01-18T17:12:30Z\",\n          \"public\": false,\n          \"cidr\": 31,\n          \"management\": true,\n          \"manageable\": true,\n          \"enabled\": true,\n          \"assigned_to\": {\n            \"href\": \"/devices/5bd27259-8b71-48f7-879d-c4e695cb2f31\"\n          },\n          \"network\": \"10.99.214.0\",\n          \"address\": \"10.99.214.1\",\n          \"gateway\": \"10.99.214.0\",\n          \"href\": \"/ips/6d206311-1f88-454d-9cf2-afca79f51fa3\"\n        }\n      ],\n      \"plan\": {\n        \"id\": \"e69c0169-4726-46ea-98f1-939c9e8a3607\",\n        \"slug\": \"baremetal_0\",\n        \"name\": \"Type 0\",\n        \"description\": \"Our Type 0 configuration is a general use \\\"cloud killer\\\" server, with a Intel Atom 2.4Ghz processor and 8GB of RAM.\",\n        \"line\": \"baremetal\",\n        \"specs\": {\n          \"cpus\": [\n            {\n              \"count\": 1,\n              \"type\": \"Intel Atom C2550 @ 2.4Ghz\"\n            }\n          ],\n          \"memory\": {\n            \"total\": \"8GB\"\n          },\n          \"drives\": [\n            {\n              \"count\": 1,\n              \"size\": \"80GB\",\n              \"type\": \"SSD\"\n            }\n          ],\n          \"nics\": [\n            {\n              \"count\": 2,\n              \"type\": \"1Gbps\"\n            }\n          ],\n          \"features\": {\n            \"raid\": false,\n            \"txt\": true\n          }\n        },\n        \"available_in\": [\n          {\n            \"href\": \"/facilities/2b70eb8f-fa18-47c0-aba7-222a842362fd\"\n          },\n          {\n            \"href\": \"/facilities/8e6470b3-b75e-47d1-bb93-45b225750975\"\n          },\n          {\n            \"href\": \"/facilities/8ea03255-89f9-4e62-9d3f-8817db82ceed\"\n          },\n          {\n            \"href\": \"/facilities/e1e9c52e-a0bc-4117-b996-0fc94843ea09\"\n          }\n        ],\n        \"pricing\": {\n          \"hour\": 0.05\n        }\n      },\n      \"userdata\": \"\",\n      \"root_password\": \"soaz0#a=cd\",\n      \"href\": \"/devices/5bd27259-8b71-48f7-879d-c4e695cb2f31\"\n    },\n    {\n      \"id\": \"5bd27259-8b71-48f7-879d-c4e695cb2f33\",\n      \"short_id\": \"5bd27259\",\n      \"hostname\": \"andrea-device-livetest\",\n      \"description\": null,\n      \"state\": \"active\",\n      \"tags\": [],\n      \"billing_cycle\": \"hourly\",\n      \"user\": \"root\",\n      \"iqn\": \"iqn.2017-01.net.packet:device.5bd27259\",\n      \"locked\": false,\n      \"bonding_mode\": 5,\n      \"created_at\": \"2017-01-18T17:12:29Z\",\n      \"updated_at\": \"2017-01-18T17:16:29Z\",\n      \"operating_system\": {\n        \"id\": \"1b9b78e3-de68-466e-ba00-f2123e89c112\",\n        \"slug\": \"ubuntu_16_04\",\n        \"name\": \"Ubuntu 16.04 LTS\",\n        \"distro\": \"ubuntu\",\n        \"version\": \"16.04\",\n        \"provisionable_on\": [\n          \"baremetal_0\",\n          \"baremetal_1\",\n          \"baremetal_2\",\n          \"baremetal_2a\",\n          \"baremetal_3\",\n          \"baremetal_hua\"\n        ]\n      },\n      \"facility\": {\n        \"id\": \"e1e9c52e-a0bc-4117-b996-0fc94843ea09\",\n        \"name\": \"Parsippany, NJ\",\n        \"code\": \"ewr1\",\n        \"features\": [\n          \"baremetal\",\n          \"storage\"\n        ],\n        \"address\": null\n      },\n      \"project\": {\n        \"href\": \"/projects/93907f48-adfe-43ed-ad89-0e6e83721a54\"\n      },\n      \"ssh_keys\": [\n        {\n          \"href\": \"/ssh-keys/a3d8bebe-574f-427d-80ee-bc2ba17f7074\"\n        },\n        {\n          \"href\": \"/ssh-keys/a8d6cc17-7d9d-4fb9-8190-afdb301b67df\"\n        },\n        {\n          \"href\": \"/ssh-keys/084a5dec-30be-415a-8937-9c615932e459\"\n        },\n        {\n          \"href\": \"/ssh-keys/eacfb002-45e1-4047-a0d5-cd9d8bab19ed\"\n        },\n        {\n          \"href\": \"/ssh-keys/f82b69d7-8c7e-4a38-9283-ecdbcaba56aa\"\n        },\n        {\n          \"href\": \"/ssh-keys/cf9db551-ec79-4c16-a776-97cdbcb3cec4\"\n        }\n      ],\n      \"project_lite\": {\n        \"href\": \"/projects/93907f48-adfe-43ed-ad89-0e6e83721a54\"\n      },\n      \"volumes\": [],\n      \"ip_addresses\": [\n        {\n          \"id\": \"cbff502b-12ca-4986-b683-2cb4e119ae40\",\n          \"address_family\": 4,\n          \"netmask\": \"255.255.255.254\",\n          \"created_at\": \"2017-01-18T17:12:30Z\",\n          \"public\": true,\n          \"cidr\": 31,\n          \"management\": true,\n          \"manageable\": true,\n          \"enabled\": true,\n          \"assigned_to\": {\n            \"href\": \"/devices/5bd27259-8b71-48f7-879d-c4e695cb2f31\"\n          },\n          \"network\": \"147.75.197.54\",\n          \"address\": \"147.75.197.55\",\n          \"gateway\": \"147.75.197.54\",\n          \"href\": \"/ips/cbff502b-12ca-4986-b683-2cb4e119ae40\"\n        },\n        {\n          \"id\": \"d5cec621-18c1-4e02-8f71-8dd46370c3e5\",\n          \"address_family\": 6,\n          \"netmask\": \"ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe\",\n          \"created_at\": \"2017-01-18T17:12:30Z\",\n          \"public\": true,\n          \"cidr\": 127,\n          \"management\": true,\n          \"manageable\": true,\n          \"enabled\": true,\n          \"assigned_to\": {\n            \"href\": \"/devices/5bd27259-8b71-48f7-879d-c4e695cb2f31\"\n          },\n          \"network\": \"2604:1380:2:9800::\",\n          \"address\": \"2604:1380:2:9800::1\",\n          \"gateway\": \"2604:1380:2:9800::\",\n          \"href\": \"/ips/d5cec621-18c1-4e02-8f71-8dd46370c3e5\"\n        },\n        {\n          \"id\": \"6d206311-1f88-454d-9cf2-afca79f51fa3\",\n          \"address_family\": 4,\n          \"netmask\": \"255.255.255.254\",\n          \"created_at\": \"2017-01-18T17:12:30Z\",\n          \"public\": false,\n          \"cidr\": 31,\n          \"management\": true,\n          \"manageable\": true,\n          \"enabled\": true,\n          \"assigned_to\": {\n            \"href\": \"/devices/5bd27259-8b71-48f7-879d-c4e695cb2f31\"\n          },\n          \"network\": \"10.99.214.0\",\n          \"address\": \"10.99.214.1\",\n          \"gateway\": \"10.99.214.0\",\n          \"href\": \"/ips/6d206311-1f88-454d-9cf2-afca79f51fa3\"\n        }\n      ],\n      \"plan\": {\n        \"id\": \"e69c0169-4726-46ea-98f1-939c9e8a3607\",\n        \"slug\": \"baremetal_0\",\n        \"name\": \"Type 0\",\n        \"description\": \"Our Type 0 configuration is a general use \\\"cloud killer\\\" server, with a Intel Atom 2.4Ghz processor and 8GB of RAM.\",\n        \"line\": \"baremetal\",\n        \"specs\": {\n          \"cpus\": [\n            {\n              \"count\": 1,\n              \"type\": \"Intel Atom C2550 @ 2.4Ghz\"\n            }\n          ],\n          \"memory\": {\n            \"total\": \"8GB\"\n          },\n          \"drives\": [\n            {\n              \"count\": 1,\n              \"size\": \"80GB\",\n              \"type\": \"SSD\"\n            }\n          ],\n          \"nics\": [\n            {\n              \"count\": 2,\n              \"type\": \"1Gbps\"\n            }\n          ],\n          \"features\": {\n            \"raid\": false,\n            \"txt\": true\n          }\n        },\n        \"available_in\": [\n          {\n            \"href\": \"/facilities/2b70eb8f-fa18-47c0-aba7-222a842362fd\"\n          },\n          {\n            \"href\": \"/facilities/8e6470b3-b75e-47d1-bb93-45b225750975\"\n          },\n          {\n            \"href\": \"/facilities/8ea03255-89f9-4e62-9d3f-8817db82ceed\"\n          },\n          {\n            \"href\": \"/facilities/e1e9c52e-a0bc-4117-b996-0fc94843ea09\"\n          }\n        ],\n        \"pricing\": {\n          \"hour\": 0.05\n        }\n      },\n      \"userdata\": \"\",\n      \"root_password\": \"soaz0#a=cd\",\n      \"href\": \"/devices/5bd27259-8b71-48f7-879d-c4e695cb2f31\"\n    },\n    {\n      \"id\": \"5bd27259-8b71-48f7-879d-c4e695cb2f34\",\n      \"short_id\": \"5bd27259\",\n      \"hostname\": \"andrea-device-livetest\",\n      \"description\": null,\n      \"state\": \"active\",\n      \"tags\": [],\n      \"billing_cycle\": \"hourly\",\n      \"user\": \"root\",\n      \"iqn\": \"iqn.2017-01.net.packet:device.5bd27259\",\n      \"locked\": false,\n      \"bonding_mode\": 5,\n      \"created_at\": \"2017-01-18T17:12:29Z\",\n      \"updated_at\": \"2017-01-18T17:16:29Z\",\n      \"operating_system\": {\n        \"id\": \"1b9b78e3-de68-466e-ba00-f2123e89c112\",\n        \"slug\": \"ubuntu_16_04\",\n        \"name\": \"Ubuntu 16.04 LTS\",\n        \"distro\": \"ubuntu\",\n        \"version\": \"16.04\",\n        \"provisionable_on\": [\n          \"baremetal_0\",\n          \"baremetal_1\",\n          \"baremetal_2\",\n          \"baremetal_2a\",\n          \"baremetal_3\",\n          \"baremetal_hua\"\n        ]\n      },\n      \"facility\": {\n        \"id\": \"e1e9c52e-a0bc-4117-b996-0fc94843ea09\",\n        \"name\": \"Parsippany, NJ\",\n        \"code\": \"ewr1\",\n        \"features\": [\n          \"baremetal\",\n          \"storage\"\n        ],\n        \"address\": null\n      },\n      \"project\": {\n        \"href\": \"/projects/93907f48-adfe-43ed-ad89-0e6e83721a54\"\n      },\n      \"ssh_keys\": [\n        {\n          \"href\": \"/ssh-keys/a3d8bebe-574f-427d-80ee-bc2ba17f7074\"\n        },\n        {\n          \"href\": \"/ssh-keys/a8d6cc17-7d9d-4fb9-8190-afdb301b67df\"\n        },\n        {\n          \"href\": \"/ssh-keys/084a5dec-30be-415a-8937-9c615932e459\"\n        },\n        {\n          \"href\": \"/ssh-keys/eacfb002-45e1-4047-a0d5-cd9d8bab19ed\"\n        },\n        {\n          \"href\": \"/ssh-keys/f82b69d7-8c7e-4a38-9283-ecdbcaba56aa\"\n        },\n        {\n          \"href\": \"/ssh-keys/cf9db551-ec79-4c16-a776-97cdbcb3cec4\"\n        }\n      ],\n      \"project_lite\": {\n        \"href\": \"/projects/93907f48-adfe-43ed-ad89-0e6e83721a54\"\n      },\n      \"volumes\": [],\n      \"ip_addresses\": [\n        {\n          \"id\": \"cbff502b-12ca-4986-b683-2cb4e119ae40\",\n          \"address_family\": 4,\n          \"netmask\": \"255.255.255.254\",\n          \"created_at\": \"2017-01-18T17:12:30Z\",\n          \"public\": true,\n          \"cidr\": 31,\n          \"management\": true,\n          \"manageable\": true,\n          \"enabled\": true,\n          \"assigned_to\": {\n            \"href\": \"/devices/5bd27259-8b71-48f7-879d-c4e695cb2f31\"\n          },\n          \"network\": \"147.75.197.54\",\n          \"address\": \"147.75.197.55\",\n          \"gateway\": \"147.75.197.54\",\n          \"href\": \"/ips/cbff502b-12ca-4986-b683-2cb4e119ae40\"\n        },\n        {\n          \"id\": \"d5cec621-18c1-4e02-8f71-8dd46370c3e5\",\n          \"address_family\": 6,\n          \"netmask\": \"ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe\",\n          \"created_at\": \"2017-01-18T17:12:30Z\",\n          \"public\": true,\n          \"cidr\": 127,\n          \"management\": true,\n          \"manageable\": true,\n          \"enabled\": true,\n          \"assigned_to\": {\n            \"href\": \"/devices/5bd27259-8b71-48f7-879d-c4e695cb2f31\"\n          },\n          \"network\": \"2604:1380:2:9800::\",\n          \"address\": \"2604:1380:2:9800::1\",\n          \"gateway\": \"2604:1380:2:9800::\",\n          \"href\": \"/ips/d5cec621-18c1-4e02-8f71-8dd46370c3e5\"\n        },\n        {\n          \"id\": \"6d206311-1f88-454d-9cf2-afca79f51fa3\",\n          \"address_family\": 4,\n          \"netmask\": \"255.255.255.254\",\n          \"created_at\": \"2017-01-18T17:12:30Z\",\n          \"public\": false,\n          \"cidr\": 31,\n          \"management\": true,\n          \"manageable\": true,\n          \"enabled\": true,\n          \"assigned_to\": {\n            \"href\": \"/devices/5bd27259-8b71-48f7-879d-c4e695cb2f31\"\n          },\n          \"network\": \"10.99.214.0\",\n          \"address\": \"10.99.214.1\",\n          \"gateway\": \"10.99.214.0\",\n          \"href\": \"/ips/6d206311-1f88-454d-9cf2-afca79f51fa3\"\n        }\n      ],\n      \"plan\": {\n        \"id\": \"e69c0169-4726-46ea-98f1-939c9e8a3607\",\n        \"slug\": \"baremetal_0\",\n        \"name\": \"Type 0\",\n        \"description\": \"Our Type 0 configuration is a general use \\\"cloud killer\\\" server, with a Intel Atom 2.4Ghz processor and 8GB of RAM.\",\n        \"line\": \"baremetal\",\n        \"specs\": {\n          \"cpus\": [\n            {\n              \"count\": 1,\n              \"type\": \"Intel Atom C2550 @ 2.4Ghz\"\n            }\n          ],\n          \"memory\": {\n            \"total\": \"8GB\"\n          },\n          \"drives\": [\n            {\n              \"count\": 1,\n              \"size\": \"80GB\",\n              \"type\": \"SSD\"\n            }\n          ],\n          \"nics\": [\n            {\n              \"count\": 2,\n              \"type\": \"1Gbps\"\n            }\n          ],\n          \"features\": {\n            \"raid\": false,\n            \"txt\": true\n          }\n        },\n        \"available_in\": [\n          {\n            \"href\": \"/facilities/2b70eb8f-fa18-47c0-aba7-222a842362fd\"\n          },\n          {\n            \"href\": \"/facilities/8e6470b3-b75e-47d1-bb93-45b225750975\"\n          },\n          {\n            \"href\": \"/facilities/8ea03255-89f9-4e62-9d3f-8817db82ceed\"\n          },\n          {\n            \"href\": \"/facilities/e1e9c52e-a0bc-4117-b996-0fc94843ea09\"\n          }\n        ],\n        \"pricing\": {\n          \"hour\": 0.05\n        }\n      },\n      \"userdata\": \"\",\n      \"root_password\": \"soaz0#a=cd\",\n      \"href\": \"/devices/5bd27259-8b71-48f7-879d-c4e695cb2f31\"\n    },\n    {\n      \"id\": \"5bd27259-8b71-48f7-879d-c4e695cb2f35\",\n      \"short_id\": \"5bd27259\",\n      \"hostname\": \"andrea-device-livetest\",\n      \"description\": null,\n      \"state\": \"active\",\n      \"tags\": [],\n      \"billing_cycle\": \"hourly\",\n      \"user\": \"root\",\n      \"iqn\": \"iqn.2017-01.net.packet:device.5bd27259\",\n      \"locked\": false,\n      \"bonding_mode\": 5,\n      \"created_at\": \"2017-01-18T17:12:29Z\",\n      \"updated_at\": \"2017-01-18T17:16:29Z\",\n      \"operating_system\": {\n        \"id\": \"1b9b78e3-de68-466e-ba00-f2123e89c112\",\n        \"slug\": \"ubuntu_16_04\",\n        \"name\": \"Ubuntu 16.04 LTS\",\n        \"distro\": \"ubuntu\",\n        \"version\": \"16.04\",\n        \"provisionable_on\": [\n          \"baremetal_0\",\n          \"baremetal_1\",\n          \"baremetal_2\",\n          \"baremetal_2a\",\n          \"baremetal_3\",\n          \"baremetal_hua\"\n        ]\n      },\n      \"facility\": {\n        \"id\": \"e1e9c52e-a0bc-4117-b996-0fc94843ea09\",\n        \"name\": \"Parsippany, NJ\",\n        \"code\": \"ewr1\",\n        \"features\": [\n          \"baremetal\",\n          \"storage\"\n        ],\n        \"address\": null\n      },\n      \"project\": {\n        \"href\": \"/projects/93907f48-adfe-43ed-ad89-0e6e83721a54\"\n      },\n      \"ssh_keys\": [\n        {\n          \"href\": \"/ssh-keys/a3d8bebe-574f-427d-80ee-bc2ba17f7074\"\n        },\n        {\n          \"href\": \"/ssh-keys/a8d6cc17-7d9d-4fb9-8190-afdb301b67df\"\n        },\n        {\n          \"href\": \"/ssh-keys/084a5dec-30be-415a-8937-9c615932e459\"\n        },\n        {\n          \"href\": \"/ssh-keys/eacfb002-45e1-4047-a0d5-cd9d8bab19ed\"\n        },\n        {\n          \"href\": \"/ssh-keys/f82b69d7-8c7e-4a38-9283-ecdbcaba56aa\"\n        },\n        {\n          \"href\": \"/ssh-keys/cf9db551-ec79-4c16-a776-97cdbcb3cec4\"\n        }\n      ],\n      \"project_lite\": {\n        \"href\": \"/projects/93907f48-adfe-43ed-ad89-0e6e83721a54\"\n      },\n      \"volumes\": [],\n      \"ip_addresses\": [\n        {\n          \"id\": \"cbff502b-12ca-4986-b683-2cb4e119ae40\",\n          \"address_family\": 4,\n          \"netmask\": \"255.255.255.254\",\n          \"created_at\": \"2017-01-18T17:12:30Z\",\n          \"public\": true,\n          \"cidr\": 31,\n          \"management\": true,\n          \"manageable\": true,\n          \"enabled\": true,\n          \"assigned_to\": {\n            \"href\": \"/devices/5bd27259-8b71-48f7-879d-c4e695cb2f31\"\n          },\n          \"network\": \"147.75.197.54\",\n          \"address\": \"147.75.197.55\",\n          \"gateway\": \"147.75.197.54\",\n          \"href\": \"/ips/cbff502b-12ca-4986-b683-2cb4e119ae40\"\n        },\n        {\n          \"id\": \"d5cec621-18c1-4e02-8f71-8dd46370c3e5\",\n          \"address_family\": 6,\n          \"netmask\": \"ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe\",\n          \"created_at\": \"2017-01-18T17:12:30Z\",\n          \"public\": true,\n          \"cidr\": 127,\n          \"management\": true,\n          \"manageable\": true,\n          \"enabled\": true,\n          \"assigned_to\": {\n            \"href\": \"/devices/5bd27259-8b71-48f7-879d-c4e695cb2f31\"\n          },\n          \"network\": \"2604:1380:2:9800::\",\n          \"address\": \"2604:1380:2:9800::1\",\n          \"gateway\": \"2604:1380:2:9800::\",\n          \"href\": \"/ips/d5cec621-18c1-4e02-8f71-8dd46370c3e5\"\n        },\n        {\n          \"id\": \"6d206311-1f88-454d-9cf2-afca79f51fa3\",\n          \"address_family\": 4,\n          \"netmask\": \"255.255.255.254\",\n          \"created_at\": \"2017-01-18T17:12:30Z\",\n          \"public\": false,\n          \"cidr\": 31,\n          \"management\": true,\n          \"manageable\": true,\n          \"enabled\": true,\n          \"assigned_to\": {\n            \"href\": \"/devices/5bd27259-8b71-48f7-879d-c4e695cb2f31\"\n          },\n          \"network\": \"10.99.214.0\",\n          \"address\": \"10.99.214.1\",\n          \"gateway\": \"10.99.214.0\",\n          \"href\": \"/ips/6d206311-1f88-454d-9cf2-afca79f51fa3\"\n        }\n      ],\n      \"plan\": {\n        \"id\": \"e69c0169-4726-46ea-98f1-939c9e8a3607\",\n        \"slug\": \"baremetal_0\",\n        \"name\": \"Type 0\",\n        \"description\": \"Our Type 0 configuration is a general use \\\"cloud killer\\\" server, with a Intel Atom 2.4Ghz processor and 8GB of RAM.\",\n        \"line\": \"baremetal\",\n        \"specs\": {\n          \"cpus\": [\n            {\n              \"count\": 1,\n              \"type\": \"Intel Atom C2550 @ 2.4Ghz\"\n            }\n          ],\n          \"memory\": {\n            \"total\": \"8GB\"\n          },\n          \"drives\": [\n            {\n              \"count\": 1,\n              \"size\": \"80GB\",\n              \"type\": \"SSD\"\n            }\n          ],\n          \"nics\": [\n            {\n              \"count\": 2,\n              \"type\": \"1Gbps\"\n            }\n          ],\n          \"features\": {\n            \"raid\": false,\n            \"txt\": true\n          }\n        },\n        \"available_in\": [\n          {\n            \"href\": \"/facilities/2b70eb8f-fa18-47c0-aba7-222a842362fd\"\n          },\n          {\n            \"href\": \"/facilities/8e6470b3-b75e-47d1-bb93-45b225750975\"\n          },\n          {\n            \"href\": \"/facilities/8ea03255-89f9-4e62-9d3f-8817db82ceed\"\n          },\n          {\n            \"href\": \"/facilities/e1e9c52e-a0bc-4117-b996-0fc94843ea09\"\n          }\n        ],\n        \"pricing\": {\n          \"hour\": 0.05\n        }\n      },\n      \"userdata\": \"\",\n      \"root_password\": \"soaz0#a=cd\",\n      \"href\": \"/devices/5bd27259-8b71-48f7-879d-c4e695cb2f31\"\n    }\n  ],\n  \"meta\": {\n    \"first\": {\n      \"href\": \"/projects/93907f48-adfe-43ed-ad89-0e6e83721a54/devices?page=1\"\n    },\n    \"previous\": null,\n    \"self\": {\n      \"href\": \"/projects/93907f48-adfe-43ed-ad89-0e6e83721a54/devices?page=1\"\n    },\n    \"next\": {\n      \"href\": \"/projects/93907f48-adfe-43ed-ad89-0e6e83721a54/devices?page=2\"\n    },\n    \"last\": {\n      \"href\": \"/projects/93907f48-adfe-43ed-ad89-0e6e83721a54/devices?page=2\"\n    },\n    \"total\": 7\n  }\n}\n"
  },
  {
    "path": "providers/packet/src/test/resources/devices-last.json",
    "content": "{\n  \"devices\": [\n    {\n      \"id\": \"5bd27259-8b71-48f7-879d-c4e695cb2f36\",\n      \"short_id\": \"5bd27259\",\n      \"hostname\": \"andrea-device-livetest\",\n      \"description\": null,\n      \"state\": \"active\",\n      \"tags\": [],\n      \"billing_cycle\": \"hourly\",\n      \"user\": \"root\",\n      \"iqn\": \"iqn.2017-01.net.packet:device.5bd27259\",\n      \"locked\": false,\n      \"bonding_mode\": 5,\n      \"created_at\": \"2017-01-18T17:12:29Z\",\n      \"updated_at\": \"2017-01-18T17:16:29Z\",\n      \"operating_system\": {\n        \"id\": \"1b9b78e3-de68-466e-ba00-f2123e89c112\",\n        \"slug\": \"ubuntu_16_04\",\n        \"name\": \"Ubuntu 16.04 LTS\",\n        \"distro\": \"ubuntu\",\n        \"version\": \"16.04\",\n        \"provisionable_on\": [\n          \"baremetal_0\",\n          \"baremetal_1\",\n          \"baremetal_2\",\n          \"baremetal_2a\",\n          \"baremetal_3\",\n          \"baremetal_hua\"\n        ]\n      },\n      \"facility\": {\n        \"id\": \"e1e9c52e-a0bc-4117-b996-0fc94843ea09\",\n        \"name\": \"Parsippany, NJ\",\n        \"code\": \"ewr1\",\n        \"features\": [\n          \"baremetal\",\n          \"storage\"\n        ],\n        \"address\": null\n      },\n      \"project\": {\n        \"href\": \"/projects/93907f48-adfe-43ed-ad89-0e6e83721a54\"\n      },\n      \"ssh_keys\": [\n        {\n          \"href\": \"/ssh-keys/a3d8bebe-574f-427d-80ee-bc2ba17f7074\"\n        },\n        {\n          \"href\": \"/ssh-keys/a8d6cc17-7d9d-4fb9-8190-afdb301b67df\"\n        },\n        {\n          \"href\": \"/ssh-keys/084a5dec-30be-415a-8937-9c615932e459\"\n        },\n        {\n          \"href\": \"/ssh-keys/eacfb002-45e1-4047-a0d5-cd9d8bab19ed\"\n        },\n        {\n          \"href\": \"/ssh-keys/f82b69d7-8c7e-4a38-9283-ecdbcaba56aa\"\n        },\n        {\n          \"href\": \"/ssh-keys/cf9db551-ec79-4c16-a776-97cdbcb3cec4\"\n        }\n      ],\n      \"project_lite\": {\n        \"href\": \"/projects/93907f48-adfe-43ed-ad89-0e6e83721a54\"\n      },\n      \"volumes\": [],\n      \"ip_addresses\": [\n        {\n          \"id\": \"cbff502b-12ca-4986-b683-2cb4e119ae40\",\n          \"address_family\": 4,\n          \"netmask\": \"255.255.255.254\",\n          \"created_at\": \"2017-01-18T17:12:30Z\",\n          \"public\": true,\n          \"cidr\": 31,\n          \"management\": true,\n          \"manageable\": true,\n          \"enabled\": true,\n          \"assigned_to\": {\n            \"href\": \"/devices/5bd27259-8b71-48f7-879d-c4e695cb2f31\"\n          },\n          \"network\": \"147.75.197.54\",\n          \"address\": \"147.75.197.55\",\n          \"gateway\": \"147.75.197.54\",\n          \"href\": \"/ips/cbff502b-12ca-4986-b683-2cb4e119ae40\"\n        },\n        {\n          \"id\": \"d5cec621-18c1-4e02-8f71-8dd46370c3e5\",\n          \"address_family\": 6,\n          \"netmask\": \"ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe\",\n          \"created_at\": \"2017-01-18T17:12:30Z\",\n          \"public\": true,\n          \"cidr\": 127,\n          \"management\": true,\n          \"manageable\": true,\n          \"enabled\": true,\n          \"assigned_to\": {\n            \"href\": \"/devices/5bd27259-8b71-48f7-879d-c4e695cb2f31\"\n          },\n          \"network\": \"2604:1380:2:9800::\",\n          \"address\": \"2604:1380:2:9800::1\",\n          \"gateway\": \"2604:1380:2:9800::\",\n          \"href\": \"/ips/d5cec621-18c1-4e02-8f71-8dd46370c3e5\"\n        },\n        {\n          \"id\": \"6d206311-1f88-454d-9cf2-afca79f51fa3\",\n          \"address_family\": 4,\n          \"netmask\": \"255.255.255.254\",\n          \"created_at\": \"2017-01-18T17:12:30Z\",\n          \"public\": false,\n          \"cidr\": 31,\n          \"management\": true,\n          \"manageable\": true,\n          \"enabled\": true,\n          \"assigned_to\": {\n            \"href\": \"/devices/5bd27259-8b71-48f7-879d-c4e695cb2f31\"\n          },\n          \"network\": \"10.99.214.0\",\n          \"address\": \"10.99.214.1\",\n          \"gateway\": \"10.99.214.0\",\n          \"href\": \"/ips/6d206311-1f88-454d-9cf2-afca79f51fa3\"\n        }\n      ],\n      \"plan\": {\n        \"id\": \"e69c0169-4726-46ea-98f1-939c9e8a3607\",\n        \"slug\": \"baremetal_0\",\n        \"name\": \"Type 0\",\n        \"description\": \"Our Type 0 configuration is a general use \\\"cloud killer\\\" server, with a Intel Atom 2.4Ghz processor and 8GB of RAM.\",\n        \"line\": \"baremetal\",\n        \"specs\": {\n          \"cpus\": [\n            {\n              \"count\": 1,\n              \"type\": \"Intel Atom C2550 @ 2.4Ghz\"\n            }\n          ],\n          \"memory\": {\n            \"total\": \"8GB\"\n          },\n          \"drives\": [\n            {\n              \"count\": 1,\n              \"size\": \"80GB\",\n              \"type\": \"SSD\"\n            }\n          ],\n          \"nics\": [\n            {\n              \"count\": 2,\n              \"type\": \"1Gbps\"\n            }\n          ],\n          \"features\": {\n            \"raid\": false,\n            \"txt\": true\n          }\n        },\n        \"available_in\": [\n          {\n            \"href\": \"/facilities/2b70eb8f-fa18-47c0-aba7-222a842362fd\"\n          },\n          {\n            \"href\": \"/facilities/8e6470b3-b75e-47d1-bb93-45b225750975\"\n          },\n          {\n            \"href\": \"/facilities/8ea03255-89f9-4e62-9d3f-8817db82ceed\"\n          },\n          {\n            \"href\": \"/facilities/e1e9c52e-a0bc-4117-b996-0fc94843ea09\"\n          }\n        ],\n        \"pricing\": {\n          \"hour\": 0.05\n        }\n      },\n      \"userdata\": \"\",\n      \"root_password\": \"soaz0#a=cd\",\n      \"href\": \"/devices/5bd27259-8b71-48f7-879d-c4e695cb2f31\"\n    },\n    {\n      \"id\": \"5bd27259-8b71-48f7-879d-c4e695cb2f37\",\n      \"short_id\": \"5bd27259\",\n      \"hostname\": \"andrea-device-livetest\",\n      \"description\": null,\n      \"state\": \"active\",\n      \"tags\": [],\n      \"billing_cycle\": \"hourly\",\n      \"user\": \"root\",\n      \"iqn\": \"iqn.2017-01.net.packet:device.5bd27259\",\n      \"locked\": false,\n      \"bonding_mode\": 5,\n      \"created_at\": \"2017-01-18T17:12:29Z\",\n      \"updated_at\": \"2017-01-18T17:16:29Z\",\n      \"operating_system\": {\n        \"id\": \"1b9b78e3-de68-466e-ba00-f2123e89c112\",\n        \"slug\": \"ubuntu_16_04\",\n        \"name\": \"Ubuntu 16.04 LTS\",\n        \"distro\": \"ubuntu\",\n        \"version\": \"16.04\",\n        \"provisionable_on\": [\n          \"baremetal_0\",\n          \"baremetal_1\",\n          \"baremetal_2\",\n          \"baremetal_2a\",\n          \"baremetal_3\",\n          \"baremetal_hua\"\n        ]\n      },\n      \"facility\": {\n        \"id\": \"e1e9c52e-a0bc-4117-b996-0fc94843ea09\",\n        \"name\": \"Parsippany, NJ\",\n        \"code\": \"ewr1\",\n        \"features\": [\n          \"baremetal\",\n          \"storage\"\n        ],\n        \"address\": null\n      },\n      \"project\": {\n        \"href\": \"/projects/93907f48-adfe-43ed-ad89-0e6e83721a54\"\n      },\n      \"ssh_keys\": [\n        {\n          \"href\": \"/ssh-keys/a3d8bebe-574f-427d-80ee-bc2ba17f7074\"\n        },\n        {\n          \"href\": \"/ssh-keys/a8d6cc17-7d9d-4fb9-8190-afdb301b67df\"\n        },\n        {\n          \"href\": \"/ssh-keys/084a5dec-30be-415a-8937-9c615932e459\"\n        },\n        {\n          \"href\": \"/ssh-keys/eacfb002-45e1-4047-a0d5-cd9d8bab19ed\"\n        },\n        {\n          \"href\": \"/ssh-keys/f82b69d7-8c7e-4a38-9283-ecdbcaba56aa\"\n        },\n        {\n          \"href\": \"/ssh-keys/cf9db551-ec79-4c16-a776-97cdbcb3cec4\"\n        }\n      ],\n      \"project_lite\": {\n        \"href\": \"/projects/93907f48-adfe-43ed-ad89-0e6e83721a54\"\n      },\n      \"volumes\": [],\n      \"ip_addresses\": [\n        {\n          \"id\": \"cbff502b-12ca-4986-b683-2cb4e119ae40\",\n          \"address_family\": 4,\n          \"netmask\": \"255.255.255.254\",\n          \"created_at\": \"2017-01-18T17:12:30Z\",\n          \"public\": true,\n          \"cidr\": 31,\n          \"management\": true,\n          \"manageable\": true,\n          \"enabled\": true,\n          \"assigned_to\": {\n            \"href\": \"/devices/5bd27259-8b71-48f7-879d-c4e695cb2f31\"\n          },\n          \"network\": \"147.75.197.54\",\n          \"address\": \"147.75.197.55\",\n          \"gateway\": \"147.75.197.54\",\n          \"href\": \"/ips/cbff502b-12ca-4986-b683-2cb4e119ae40\"\n        },\n        {\n          \"id\": \"d5cec621-18c1-4e02-8f71-8dd46370c3e5\",\n          \"address_family\": 6,\n          \"netmask\": \"ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe\",\n          \"created_at\": \"2017-01-18T17:12:30Z\",\n          \"public\": true,\n          \"cidr\": 127,\n          \"management\": true,\n          \"manageable\": true,\n          \"enabled\": true,\n          \"assigned_to\": {\n            \"href\": \"/devices/5bd27259-8b71-48f7-879d-c4e695cb2f31\"\n          },\n          \"network\": \"2604:1380:2:9800::\",\n          \"address\": \"2604:1380:2:9800::1\",\n          \"gateway\": \"2604:1380:2:9800::\",\n          \"href\": \"/ips/d5cec621-18c1-4e02-8f71-8dd46370c3e5\"\n        },\n        {\n          \"id\": \"6d206311-1f88-454d-9cf2-afca79f51fa3\",\n          \"address_family\": 4,\n          \"netmask\": \"255.255.255.254\",\n          \"created_at\": \"2017-01-18T17:12:30Z\",\n          \"public\": false,\n          \"cidr\": 31,\n          \"management\": true,\n          \"manageable\": true,\n          \"enabled\": true,\n          \"assigned_to\": {\n            \"href\": \"/devices/5bd27259-8b71-48f7-879d-c4e695cb2f31\"\n          },\n          \"network\": \"10.99.214.0\",\n          \"address\": \"10.99.214.1\",\n          \"gateway\": \"10.99.214.0\",\n          \"href\": \"/ips/6d206311-1f88-454d-9cf2-afca79f51fa3\"\n        }\n      ],\n      \"plan\": {\n        \"id\": \"e69c0169-4726-46ea-98f1-939c9e8a3607\",\n        \"slug\": \"baremetal_0\",\n        \"name\": \"Type 0\",\n        \"description\": \"Our Type 0 configuration is a general use \\\"cloud killer\\\" server, with a Intel Atom 2.4Ghz processor and 8GB of RAM.\",\n        \"line\": \"baremetal\",\n        \"specs\": {\n          \"cpus\": [\n            {\n              \"count\": 1,\n              \"type\": \"Intel Atom C2550 @ 2.4Ghz\"\n            }\n          ],\n          \"memory\": {\n            \"total\": \"8GB\"\n          },\n          \"drives\": [\n            {\n              \"count\": 1,\n              \"size\": \"80GB\",\n              \"type\": \"SSD\"\n            }\n          ],\n          \"nics\": [\n            {\n              \"count\": 2,\n              \"type\": \"1Gbps\"\n            }\n          ],\n          \"features\": {\n            \"raid\": false,\n            \"txt\": true\n          }\n        },\n        \"available_in\": [\n          {\n            \"href\": \"/facilities/2b70eb8f-fa18-47c0-aba7-222a842362fd\"\n          },\n          {\n            \"href\": \"/facilities/8e6470b3-b75e-47d1-bb93-45b225750975\"\n          },\n          {\n            \"href\": \"/facilities/8ea03255-89f9-4e62-9d3f-8817db82ceed\"\n          },\n          {\n            \"href\": \"/facilities/e1e9c52e-a0bc-4117-b996-0fc94843ea09\"\n          }\n        ],\n        \"pricing\": {\n          \"hour\": 0.05\n        }\n      },\n      \"userdata\": \"\",\n      \"root_password\": \"soaz0#a=cd\",\n      \"href\": \"/devices/5bd27259-8b71-48f7-879d-c4e695cb2f31\"\n    }\n  ],\n  \"meta\": {\n    \"first\": {\n      \"href\": \"/projects/93907f48-adfe-43ed-ad89-0e6e83721a54/devices?page=1\"\n    },\n    \"previous\": {\n      \"href\": \"/projects/93907f48-adfe-43ed-ad89-0e6e83721a54/devices?page=1\"\n    },\n    \"self\": {\n      \"href\": \"/projects/93907f48-adfe-43ed-ad89-0e6e83721a54/devices?page=2\"\n    },\n    \"next\": null,\n    \"last\": {\n      \"href\": \"/projects/93907f48-adfe-43ed-ad89-0e6e83721a54/devices?page=2\"\n    },\n    \"total\": 7\n  }\n}\n"
  },
  {
    "path": "providers/packet/src/test/resources/devices.json",
    "content": "{\n  \"devices\": [\n    {\n      \"id\": \"98e22032-579e-4c04-bb12-05cc6a3864c8\",\n      \"short_id\": \"98e22032\",\n      \"hostname\": \"test\",\n      \"description\": null,\n      \"state\": \"provisioning\",\n      \"tags\": [],\n      \"billing_cycle\": \"hourly\",\n      \"user\": \"root\",\n      \"iqn\": \"iqn.2017-01.net.packet:device.98e22032\",\n      \"locked\": false,\n      \"bonding_mode\": 5,\n      \"created_at\": \"2017-01-03T09:47:59Z\",\n      \"updated_at\": \"2017-01-03T09:50:13Z\",\n      \"provisioning_percentage\": 50,\n      \"operating_system\": {\n        \"id\": \"68bad60d-f5a7-45c2-ad09-573edaad3a3c\",\n        \"slug\": \"centos_7\",\n        \"name\": \"Centos 7\",\n        \"distro\": \"centos\",\n        \"version\": \"7\",\n        \"provisionable_on\": [\n          \"baremetal_0\",\n          \"baremetal_1\",\n          \"baremetal_2\",\n          \"baremetal_3\"\n        ]\n      },\n      \"facility\": {\n        \"id\": \"e1e9c52e-a0bc-4117-b996-0fc94843ea09\",\n        \"name\": \"Parsippany, NJ\",\n        \"code\": \"ewr1\",\n        \"features\": [\n          \"baremetal\",\n          \"storage\"\n        ],\n        \"address\": null\n      },\n      \"project\": {\n        \"href\": \"/projects/93907f48-adfe-43ed-ad89-0e6e83721a54\"\n      },\n      \"ssh_keys\": [\n        {\n          \"href\": \"/ssh-keys/084a5dec-30be-415a-8937-9c615932e459\"\n        },\n        {\n          \"href\": \"/ssh-keys/a8d6cc17-7d9d-4fb9-8190-afdb301b67df\"\n        },\n        {\n          \"href\": \"/ssh-keys/a3d8bebe-574f-427d-80ee-bc2ba17f7074\"\n        },\n        {\n          \"href\": \"/ssh-keys/eacfb002-45e1-4047-a0d5-cd9d8bab19ed\"\n        },\n        {\n          \"href\": \"/ssh-keys/bba63e41-b12c-493a-81d4-e52f50f247ed\"\n        }\n      ],\n      \"project_lite\": {\n        \"href\": \"/projects/93907f48-adfe-43ed-ad89-0e6e83721a54\"\n      },\n      \"volumes\": [],\n      \"ip_addresses\": [\n        {\n          \"id\": \"5d0262c7-1727-411c-94c4-9e6f15490dd3\",\n          \"address_family\": 4,\n          \"netmask\": \"255.255.255.254\",\n          \"created_at\": \"2017-01-03T09:47:59Z\",\n          \"public\": true,\n          \"cidr\": 31,\n          \"management\": true,\n          \"manageable\": true,\n          \"assigned_to\": {\n            \"href\": \"/devices/98e22032-579e-4c04-bb12-05cc6a3864c8\"\n          },\n          \"network\": \"147.75.106.80\",\n          \"address\": \"147.75.106.81\",\n          \"gateway\": \"147.75.106.80\",\n          \"href\": \"/ips/5d0262c7-1727-411c-94c4-9e6f15490dd3\"\n        },\n        {\n          \"id\": \"f7d0e65c-eb3b-42bd-af9b-ad3a736d8d43\",\n          \"address_family\": 6,\n          \"netmask\": \"ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe\",\n          \"created_at\": \"2017-01-03T09:47:59Z\",\n          \"public\": true,\n          \"cidr\": 127,\n          \"management\": true,\n          \"manageable\": true,\n          \"assigned_to\": {\n            \"href\": \"/devices/98e22032-579e-4c04-bb12-05cc6a3864c8\"\n          },\n          \"network\": \"2604:1380:2:9800::\",\n          \"address\": \"2604:1380:2:9800::1\",\n          \"gateway\": \"2604:1380:2:9800::\",\n          \"href\": \"/ips/f7d0e65c-eb3b-42bd-af9b-ad3a736d8d43\"\n        },\n        {\n          \"id\": \"a3d00b4e-d74f-4ac2-8bc9-91065d815b41\",\n          \"address_family\": 4,\n          \"netmask\": \"255.255.255.254\",\n          \"created_at\": \"2017-01-03T09:47:59Z\",\n          \"public\": false,\n          \"cidr\": 31,\n          \"management\": true,\n          \"manageable\": true,\n          \"assigned_to\": {\n            \"href\": \"/devices/98e22032-579e-4c04-bb12-05cc6a3864c8\"\n          },\n          \"network\": \"10.99.214.0\",\n          \"address\": \"10.99.214.1\",\n          \"gateway\": \"10.99.214.0\",\n          \"href\": \"/ips/a3d00b4e-d74f-4ac2-8bc9-91065d815b41\"\n        }\n      ],\n      \"provisioning_events\": [\n        {\n          \"id\": \"bd62123b-afed-4e54-b1b9-89e219ba9cf0\",\n          \"type\": \"provisioning.101\",\n          \"body\": \"Provisioning started\",\n          \"created_at\": \"2017-01-03T09:47:59Z\",\n          \"relationships\": [\n            {\n              \"href\": \"#81909921-255e-413c-883a-c58d14c801ae\"\n            }\n          ],\n          \"interpolated\": \"Provisioning started\",\n          \"href\": \"/events/bd62123b-afed-4e54-b1b9-89e219ba9cf0\"\n        },\n        {\n          \"id\": \"14b4a9e6-be90-40ee-be48-b272f855e39c\",\n          \"type\": \"provisioning.102\",\n          \"body\": \"Network configured with addresses 147.75.106.81, 2604:1380:2:9800::1, and 10.99.214.1\",\n          \"created_at\": \"2017-01-03T09:48:46Z\",\n          \"relationships\": [\n            {\n              \"href\": \"#28588657-b8bf-44a1-98d3-27f8e04b660a\"\n            }\n          ],\n          \"interpolated\": \"Network configured with addresses 147.75.106.81, 2604:1380:2:9800::1, and 10.99.214.1\",\n          \"href\": \"/events/14b4a9e6-be90-40ee-be48-b272f855e39c\"\n        },\n        {\n          \"id\": \"57e3cadb-f9aa-4c73-be54-3c83e6cf462e\",\n          \"type\": \"provisioning.103\",\n          \"body\": \"Configuration written, restarting device\",\n          \"created_at\": \"2017-01-03T09:48:57Z\",\n          \"relationships\": [\n            {\n              \"href\": \"#25a7e807-f4aa-4f36-83cd-8347baeb26bc\"\n            }\n          ],\n          \"interpolated\": \"Configuration written, restarting device\",\n          \"href\": \"/events/57e3cadb-f9aa-4c73-be54-3c83e6cf462e\"\n        },\n        {\n          \"id\": \"b8322996-f57e-4c87-96cc-a16f33a0c305\",\n          \"type\": \"provisioning.104\",\n          \"body\": \"Connected to magic install system\",\n          \"created_at\": \"2017-01-03T09:50:13Z\",\n          \"relationships\": [\n            {\n              \"href\": \"#a4825d20-f7f2-426a-88db-38696bd3dfd6\"\n            }\n          ],\n          \"interpolated\": \"Connected to magic install system\",\n          \"href\": \"/events/b8322996-f57e-4c87-96cc-a16f33a0c305\"\n        },\n        {\n          \"id\": \"f00a00a9-7c59-420d-bdcf-2c0993303cf6\",\n          \"type\": \"provisioning.105\",\n          \"body\": \"Server partitions created\",\n          \"created_at\": \"2017-01-03T09:50:13Z\",\n          \"relationships\": [\n            {\n              \"href\": \"#6140659b-5e3d-4686-be8f-8879b6d3e27f\"\n            }\n          ],\n          \"interpolated\": \"Server partitions created\",\n          \"href\": \"/events/f00a00a9-7c59-420d-bdcf-2c0993303cf6\"\n        },\n        {\n          \"id\": null,\n          \"type\": \"provisioning.106\",\n          \"body\": \"Operating system packages installed\",\n          \"created_at\": null,\n          \"relationships\": [],\n          \"interpolated\": \"Operating system packages installed\"\n        },\n        {\n          \"id\": null,\n          \"type\": \"provisioning.107\",\n          \"body\": \"Server networking interfaces configured\",\n          \"created_at\": null,\n          \"relationships\": [],\n          \"interpolated\": \"Server networking interfaces configured\"\n        },\n        {\n          \"id\": null,\n          \"type\": \"provisioning.108\",\n          \"body\": \"Cloud-init packages installed and configured\",\n          \"created_at\": null,\n          \"relationships\": [],\n          \"interpolated\": \"Cloud-init packages installed and configured\"\n        },\n        {\n          \"id\": null,\n          \"type\": \"provisioning.109\",\n          \"body\": \"Installation finished, rebooting server\",\n          \"created_at\": null,\n          \"relationships\": [],\n          \"interpolated\": \"Installation finished, rebooting server\"\n        },\n        {\n          \"id\": null,\n          \"type\": \"provisioning.109\",\n          \"body\": \"Installation finished, rebooting server\",\n          \"created_at\": null,\n          \"relationships\": [],\n          \"interpolated\": \"Installation finished, rebooting server\"\n        }\n      ],\n      \"plan\": {\n        \"id\": \"e69c0169-4726-46ea-98f1-939c9e8a3607\",\n        \"slug\": \"baremetal_0\",\n        \"name\": \"Type 0\",\n        \"description\": \"Our Type 0 configuration is a general use \\\"cloud killer\\\" server, with a Intel Atom 2.4Ghz processor and 8GB of RAM.\",\n        \"line\": \"baremetal\",\n        \"specs\": {\n          \"cpus\": [\n            {\n              \"count\": 1,\n              \"type\": \"Intel Atom C2550 @ 2.4Ghz\"\n            }\n          ],\n          \"memory\": {\n            \"total\": \"8GB\"\n          },\n          \"drives\": [\n            {\n              \"count\": 1,\n              \"size\": \"80GB\",\n              \"type\": \"SSD\"\n            }\n          ],\n          \"nics\": [\n            {\n              \"count\": 2,\n              \"type\": \"1Gbps\"\n            }\n          ],\n          \"features\": {\n            \"raid\": false,\n            \"txt\": true\n          }\n        },\n        \"available_in\": [\n          {\n            \"href\": \"/facilities/2b70eb8f-fa18-47c0-aba7-222a842362fd\"\n          },\n          {\n            \"href\": \"/facilities/8e6470b3-b75e-47d1-bb93-45b225750975\"\n          },\n          {\n            \"href\": \"/facilities/8ea03255-89f9-4e62-9d3f-8817db82ceed\"\n          },\n          {\n            \"href\": \"/facilities/e1e9c52e-a0bc-4117-b996-0fc94843ea09\"\n          }\n        ],\n        \"pricing\": {\n          \"hour\": 0.05\n        }\n      },\n      \"userdata\": \"\",\n      \"root_password\": \",q4*a8(eny\",\n      \"href\": \"/devices/98e22032-579e-4c04-bb12-05cc6a3864c8\"\n    }\n  ]\n}\n"
  },
  {
    "path": "providers/packet/src/test/resources/facilities-first.json",
    "content": "{\n  \"facilities\": [\n    {\n      \"id\": \"e1e9c52e-a0bc-4117-b996-0fc94843ea09\",\n      \"name\": \"Parsippany, NJ\",\n      \"code\": \"ewr1\",\n      \"features\": [\n        \"baremetal\",\n        \"storage\"\n      ],\n      \"address\":  {\n        \"href\": \"e1e9c52e-a0bc-4117-b996-0fc94843ea09\"\n      }\n    },\n    {\n      \"id\": \"8e6470b3-b75e-47d1-bb93-45b225750975\",\n      \"name\": \"Amsterdam, NL\",\n      \"code\": \"ams1\",\n      \"features\": [\n        \"storage\"\n      ],\n      \"address\":  {\n        \"href\": \"e1e9c52e-a0bc-4117-b996-0fc94843ea09\"\n      }\n    }\n  ],\n  \"meta\": {\n    \"first\": {\n      \"href\": \"/facilities?page=1\"\n    },\n    \"previous\": null,\n    \"self\": {\n      \"href\": \"/facilities?page=1\"\n    },\n    \"next\": {\n      \"href\": \"/facilities?page=2\"\n    },\n    \"last\": {\n      \"href\": \"/facilities?page=2\"\n    },\n    \"total\": 3\n  }\n}\n"
  },
  {
    "path": "providers/packet/src/test/resources/facilities-last.json",
    "content": "{\n  \"facilities\": [\n    {\n      \"id\": \"2b70eb8f-fa18-47c0-aba7-222a842362fd\",\n      \"name\": \"Sunnyvale, CA\",\n      \"code\": \"sjc1\",\n      \"features\": [],\n      \"address\":  {\n        \"href\": \"e1e9c52e-a0bc-4117-b996-0fc94843ea09\"\n      }\n    }\n  ],\n  \"meta\": {\n    \"first\": {\n      \"href\": \"/facilities?page=1\"\n    },\n    \"previous\": {\n      \"href\": \"/facilities?page=1\"\n    },\n    \"self\": {\n      \"href\": \"/facilities?page=2\"\n    },\n    \"next\": null,\n    \"last\": {\n      \"href\": \"/facilities?page=2\"\n    },\n    \"total\": 3\n  }\n}\n"
  },
  {
    "path": "providers/packet/src/test/resources/facilities.json",
    "content": "{\n  \"facilities\": [\n    {\n      \"id\": \"e1e9c52e-a0bc-4117-b996-0fc94843ea09\",\n      \"name\": \"Parsippany, NJ\",\n      \"code\": \"ewr1\",\n      \"features\": [\n        \"baremetal\",\n        \"storage\"\n      ],\n      \"address\":  {\n        \"href\": \"e1e9c52e-a0bc-4117-b996-0fc94843ea09\"\n      }\n    },\n    {\n      \"id\": \"8e6470b3-b75e-47d1-bb93-45b225750975\",\n      \"name\": \"Amsterdam, NL\",\n      \"code\": \"ams1\",\n      \"features\": [\n        \"storage\"\n      ],\n      \"address\":  {\n        \"href\": \"e1e9c52e-a0bc-4117-b996-0fc94843ea09\"\n      }\n    },\n    {\n      \"id\": \"2b70eb8f-fa18-47c0-aba7-222a842362fd\",\n      \"name\": \"Sunnyvale, CA\",\n      \"code\": \"sjc1\",\n      \"features\": [],\n      \"address\":  {\n        \"href\": \"e1e9c52e-a0bc-4117-b996-0fc94843ea09\"\n      }\n    }\n  ]\n}\n"
  },
  {
    "path": "providers/packet/src/test/resources/logback-test.xml",
    "content": "<?xml version=\"1.0\"?>\n<configuration scan=\"false\">\n    <appender name=\"FILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds.log</file>\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n    <appender name=\"WIREFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds-wire.log</file>\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n    <appender name=\"COMPUTEFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/jclouds-compute.log</file>\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <logger name=\"org.jclouds\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"FILE\" />\n    </logger>\n    <logger name=\"jclouds.compute\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"COMPUTEFILE\" />\n    </logger>\n    <logger name=\"jclouds.wire\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n    <logger name=\"jclouds.headers\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n\n    <root>\n        <level value=\"INFO\" />\n    </root>\n</configuration>\n"
  },
  {
    "path": "providers/packet/src/test/resources/operatingSystems-first.json",
    "content": "{\n  \"operating_systems\": [\n    {\n      \"id\": \"06e21644-a769-11e6-80f5-76304dec7eb7\",\n      \"slug\": \"alpine_3\",\n      \"name\": \"Alpine 3\",\n      \"distro\": \"alpine\",\n      \"version\": \"3\",\n      \"provisionable_on\": []\n    },\n    {\n      \"id\": \"06e21978-a769-11e6-80f5-76304dec7eb7\",\n      \"slug\": \"centos_6\",\n      \"name\": \"CentOS 6\",\n      \"distro\": \"centos\",\n      \"version\": \"6\",\n      \"provisionable_on\": []\n    },\n    {\n      \"id\": \"68bad60d-f5a7-45c2-ad09-573edaad3a3c\",\n      \"slug\": \"centos_7\",\n      \"name\": \"Centos 7\",\n      \"distro\": \"centos\",\n      \"version\": \"7\",\n      \"provisionable_on\": [\n        \"baremetal_0\",\n        \"baremetal_1\",\n        \"baremetal_2\",\n        \"baremetal_3\"\n      ]\n    },\n    {\n      \"id\": \"06e21ce8-a769-11e6-80f5-76304dec7eb7\",\n      \"slug\": \"coreos_alpha\",\n      \"name\": \"CoreOS Alpha\",\n      \"distro\": \"coreos\",\n      \"version\": \"alpha\",\n      \"provisionable_on\": [\n        \"baremetal_0\",\n        \"baremetal_1\",\n        \"baremetal_2\",\n        \"baremetal_3\"\n      ]\n    },\n    {\n      \"id\": \"6345f310-0bb0-4b59-b051-954fed05183a\",\n      \"slug\": \"coreos_beta\",\n      \"name\": \"CoreOS Beta\",\n      \"distro\": \"coreos\",\n      \"version\": \"beta\",\n      \"provisionable_on\": [\n        \"baremetal_0\",\n        \"baremetal_1\",\n        \"baremetal_2\",\n        \"baremetal_3\"\n      ]\n    },\n    {\n      \"id\": \"d61c3912-8422-4daf-835e-854efa0062e4\",\n      \"slug\": \"coreos_stable\",\n      \"name\": \"CoreOS Stable\",\n      \"distro\": \"coreos\",\n      \"version\": \"stable\",\n      \"provisionable_on\": [\n        \"baremetal_0\",\n        \"baremetal_1\",\n        \"baremetal_2\",\n        \"baremetal_3\"\n      ]\n    },\n    {\n      \"id\": \"06e21e78-a769-11e6-80f5-76304dec7eb7\",\n      \"slug\": \"debian_7\",\n      \"name\": \"Debian 7\",\n      \"distro\": \"debian\",\n      \"version\": \"7\",\n      \"provisionable_on\": []\n    }\n  ],\n  \"meta\": {\n    \"first\": {\n      \"href\": \"/operating-systems?page=1\"\n    },\n    \"previous\": null,\n    \"self\": {\n      \"href\": \"/operating-systems?page=1\"\n    },\n    \"next\": {\n      \"href\": \"/operating-systems?page=2\"\n    },\n    \"last\": {\n      \"href\": \"/operating-systems?page=2\"\n    },\n    \"total\": 14\n  }\n}\n"
  },
  {
    "path": "providers/packet/src/test/resources/operatingSystems-last.json",
    "content": "{\n  \"operating_systems\": [\n    {\n      \"id\": \"88239019-abc7-41e8-9a4d-cd334da97ff1\",\n      \"slug\": \"debian_8\",\n      \"name\": \"Debian 8\",\n      \"distro\": \"debian\",\n      \"version\": \"8\",\n      \"provisionable_on\": [\n        \"baremetal_0\",\n        \"baremetal_1\",\n        \"baremetal_2\",\n        \"baremetal_3\"\n      ]\n    },\n    {\n      \"id\": \"06e21ffe-a769-11e6-80f5-76304dec7eb7\",\n      \"slug\": \"deprovision\",\n      \"name\": \"Deprovision\",\n      \"distro\": \"centos\",\n      \"version\": \"\",\n      \"provisionable_on\": []\n    },\n    {\n      \"id\": \"06e22198-a769-11e6-80f5-76304dec7eb7\",\n      \"slug\": \"freebsd_10_3\",\n      \"name\": \"FreeBSD 10.3\",\n      \"distro\": \"freebsd\",\n      \"version\": \"10.3\",\n      \"provisionable_on\": [\n        \"baremetal_0\",\n        \"baremetal_1\",\n        \"baremetal_2\",\n        \"baremetal_3\"\n      ]\n    },\n    {\n      \"id\": \"06e22328-a769-11e6-80f5-76304dec7eb7\",\n      \"slug\": \"rancher\",\n      \"name\": \"RancherOS\",\n      \"distro\": \"rancher\",\n      \"version\": \"latest\",\n      \"provisionable_on\": [\n        \"baremetal_0\",\n        \"baremetal_1\",\n        \"baremetal_2\",\n        \"baremetal_3\"\n      ]\n    },\n    {\n      \"id\": \"06e224b8-a769-11e6-80f5-76304dec7eb7\",\n      \"slug\": \"ubuntu_14_04\",\n      \"name\": \"Ubuntu 14.04 LTS\",\n      \"distro\": \"ubuntu\",\n      \"version\": \"14.04\",\n      \"provisionable_on\": [\n        \"baremetal_0\",\n        \"baremetal_1\",\n        \"baremetal_2\",\n        \"baremetal_3\"\n      ]\n    },\n    {\n      \"id\": \"1b9b78e3-de68-466e-ba00-f2123e89c112\",\n      \"slug\": \"ubuntu_16_04\",\n      \"name\": \"Ubuntu 16.04 LTS\",\n      \"distro\": \"ubuntu\",\n      \"version\": \"16.04\",\n      \"provisionable_on\": [\n        \"baremetal_0\",\n        \"baremetal_1\",\n        \"baremetal_2\",\n        \"baremetal_2a\",\n        \"baremetal_3\"\n      ]\n    },\n    {\n      \"id\": \"06e22972-a769-11e6-80f5-76304dec7eb7\",\n      \"slug\": \"windows_2012_rc2\",\n      \"name\": \"Windows 2012 RC2\",\n      \"distro\": \"windows\",\n      \"version\": \"2012 RC2\",\n      \"provisionable_on\": [\n        \"baremetal_1\",\n        \"baremetal_2\",\n        \"baremetal_3\"\n      ]\n    }\n  ],\n  \"meta\": {\n    \"first\": {\n      \"href\": \"/operating-systems?page=1\"\n    },\n    \"previous\": {\n      \"href\": \"/operating-systems?page=1\"\n    },\n    \"self\": {\n      \"href\": \"/operating-systems?page=2\"\n    },\n    \"next\": null,\n    \"last\": {\n      \"href\": \"/operating-systems?page=2\"\n    },\n    \"total\": 14\n  }\n}\n"
  },
  {
    "path": "providers/packet/src/test/resources/operatingSystems.json",
    "content": "{\n  \"operating_systems\": [\n    {\n      \"id\": \"06e21644-a769-11e6-80f5-76304dec7eb7\",\n      \"slug\": \"alpine_3\",\n      \"name\": \"Alpine 3\",\n      \"distro\": \"alpine\",\n      \"version\": \"3\",\n      \"provisionable_on\": []\n    },\n    {\n      \"id\": \"06e21978-a769-11e6-80f5-76304dec7eb7\",\n      \"slug\": \"centos_6\",\n      \"name\": \"CentOS 6\",\n      \"distro\": \"centos\",\n      \"version\": \"6\",\n      \"provisionable_on\": []\n    },\n    {\n      \"id\": \"68bad60d-f5a7-45c2-ad09-573edaad3a3c\",\n      \"slug\": \"centos_7\",\n      \"name\": \"Centos 7\",\n      \"distro\": \"centos\",\n      \"version\": \"7\",\n      \"provisionable_on\": [\n        \"baremetal_0\",\n        \"baremetal_1\",\n        \"baremetal_2\",\n        \"baremetal_3\"\n      ]\n    },\n    {\n      \"id\": \"06e21ce8-a769-11e6-80f5-76304dec7eb7\",\n      \"slug\": \"coreos_alpha\",\n      \"name\": \"CoreOS Alpha\",\n      \"distro\": \"coreos\",\n      \"version\": \"alpha\",\n      \"provisionable_on\": [\n        \"baremetal_0\",\n        \"baremetal_1\",\n        \"baremetal_2\",\n        \"baremetal_3\"\n      ]\n    },\n    {\n      \"id\": \"6345f310-0bb0-4b59-b051-954fed05183a\",\n      \"slug\": \"coreos_beta\",\n      \"name\": \"CoreOS Beta\",\n      \"distro\": \"coreos\",\n      \"version\": \"beta\",\n      \"provisionable_on\": [\n        \"baremetal_0\",\n        \"baremetal_1\",\n        \"baremetal_2\",\n        \"baremetal_3\"\n      ]\n    },\n    {\n      \"id\": \"d61c3912-8422-4daf-835e-854efa0062e4\",\n      \"slug\": \"coreos_stable\",\n      \"name\": \"CoreOS Stable\",\n      \"distro\": \"coreos\",\n      \"version\": \"stable\",\n      \"provisionable_on\": [\n        \"baremetal_0\",\n        \"baremetal_1\",\n        \"baremetal_2\",\n        \"baremetal_3\"\n      ]\n    },\n    {\n      \"id\": \"06e21e78-a769-11e6-80f5-76304dec7eb7\",\n      \"slug\": \"debian_7\",\n      \"name\": \"Debian 7\",\n      \"distro\": \"debian\",\n      \"version\": \"7\",\n      \"provisionable_on\": []\n    },\n    {\n      \"id\": \"88239019-abc7-41e8-9a4d-cd334da97ff1\",\n      \"slug\": \"debian_8\",\n      \"name\": \"Debian 8\",\n      \"distro\": \"debian\",\n      \"version\": \"8\",\n      \"provisionable_on\": [\n        \"baremetal_0\",\n        \"baremetal_1\",\n        \"baremetal_2\",\n        \"baremetal_3\"\n      ]\n    },\n    {\n      \"id\": \"06e21ffe-a769-11e6-80f5-76304dec7eb7\",\n      \"slug\": \"deprovision\",\n      \"name\": \"Deprovision\",\n      \"distro\": \"centos\",\n      \"version\": \"\",\n      \"provisionable_on\": []\n    },\n    {\n      \"id\": \"06e22198-a769-11e6-80f5-76304dec7eb7\",\n      \"slug\": \"freebsd_10_3\",\n      \"name\": \"FreeBSD 10.3\",\n      \"distro\": \"freebsd\",\n      \"version\": \"10.3\",\n      \"provisionable_on\": [\n        \"baremetal_0\",\n        \"baremetal_1\",\n        \"baremetal_2\",\n        \"baremetal_3\"\n      ]\n    },\n    {\n      \"id\": \"06e22328-a769-11e6-80f5-76304dec7eb7\",\n      \"slug\": \"rancher\",\n      \"name\": \"RancherOS\",\n      \"distro\": \"rancher\",\n      \"version\": \"latest\",\n      \"provisionable_on\": [\n        \"baremetal_0\",\n        \"baremetal_1\",\n        \"baremetal_2\",\n        \"baremetal_3\"\n      ]\n    },\n    {\n      \"id\": \"06e224b8-a769-11e6-80f5-76304dec7eb7\",\n      \"slug\": \"ubuntu_14_04\",\n      \"name\": \"Ubuntu 14.04 LTS\",\n      \"distro\": \"ubuntu\",\n      \"version\": \"14.04\",\n      \"provisionable_on\": [\n        \"baremetal_0\",\n        \"baremetal_1\",\n        \"baremetal_2\",\n        \"baremetal_3\"\n      ]\n    },\n    {\n      \"id\": \"1b9b78e3-de68-466e-ba00-f2123e89c112\",\n      \"slug\": \"ubuntu_16_04\",\n      \"name\": \"Ubuntu 16.04 LTS\",\n      \"distro\": \"ubuntu\",\n      \"version\": \"16.04\",\n      \"provisionable_on\": [\n        \"baremetal_0\",\n        \"baremetal_1\",\n        \"baremetal_2\",\n        \"baremetal_2a\",\n        \"baremetal_3\"\n      ]\n    },\n    {\n      \"id\": \"06e22972-a769-11e6-80f5-76304dec7eb7\",\n      \"slug\": \"windows_2012_rc2\",\n      \"name\": \"Windows 2012 RC2\",\n      \"distro\": \"windows\",\n      \"version\": \"2012 RC2\",\n      \"provisionable_on\": [\n        \"baremetal_1\",\n        \"baremetal_2\",\n        \"baremetal_3\"\n      ]\n    }\n  ]\n}\n"
  },
  {
    "path": "providers/packet/src/test/resources/plans-first.json",
    "content": "{\n  \"plans\": [\n    {\n      \"id\": \"e69c0169-4726-46ea-98f1-939c9e8a3607\",\n      \"slug\": \"baremetal_0\",\n      \"name\": \"Type 0\",\n      \"description\": \"Our Type 0 configuration is a general use \\\"cloud killer\\\" server, with a Intel Atom 2.4Ghz processor and 8GB of RAM.\",\n      \"line\": \"baremetal\",\n      \"specs\": {\n        \"cpus\": [\n          {\n            \"count\": 1,\n            \"type\": \"Intel Atom C2550 @ 2.4Ghz\"\n          }\n        ],\n        \"memory\": {\n          \"total\": \"8GB\"\n        },\n        \"drives\": [\n          {\n            \"count\": 1,\n            \"size\": \"80GB\",\n            \"type\": \"SSD\"\n          }\n        ],\n        \"nics\": [\n          {\n            \"count\": 2,\n            \"type\": \"1Gbps\"\n          }\n        ],\n        \"features\": {\n          \"raid\": false,\n          \"txt\": true\n        }\n      },\n      \"available_in\": [\n        {\n          \"href\": \"/facilities/2b70eb8f-fa18-47c0-aba7-222a842362fd\"\n        },\n        {\n          \"href\": \"/facilities/8e6470b3-b75e-47d1-bb93-45b225750975\"\n        },\n        {\n          \"href\": \"/facilities/8ea03255-89f9-4e62-9d3f-8817db82ceed\"\n        },\n        {\n          \"href\": \"/facilities/e1e9c52e-a0bc-4117-b996-0fc94843ea09\"\n        }\n      ],\n      \"pricing\": {\n        \"hour\": 0.05\n      }\n    },\n    {\n      \"id\": \"6d1f1ffa-7912-4b78-b50d-88cc7c8ab40f\",\n      \"slug\": \"baremetal_1\",\n      \"name\": \"Type 1\",\n      \"description\": \"Our Type 1 configuration is a zippy general use server, with an Intel E3-1240 v3 processor and 32GB of RAM.\",\n      \"line\": \"baremetal\",\n      \"specs\": {\n        \"cpus\": [\n          {\n            \"count\": 1,\n            \"type\": \"Intel E3-1240 v3\"\n          }\n        ],\n        \"memory\": {\n          \"total\": \"32GB\"\n        },\n        \"drives\": [\n          {\n            \"count\": 2,\n            \"size\": \"120GB\",\n            \"type\": \"SSD\"\n          }\n        ],\n        \"nics\": [\n          {\n            \"count\": 2,\n            \"type\": \"1Gbps\"\n          }\n        ],\n        \"features\": {\n          \"raid\": true,\n          \"txt\": true\n        }\n      },\n      \"available_in\": [\n        {\n          \"href\": \"/facilities/2b70eb8f-fa18-47c0-aba7-222a842362fd\"\n        },\n        {\n          \"href\": \"/facilities/8e6470b3-b75e-47d1-bb93-45b225750975\"\n        },\n        {\n          \"href\": \"/facilities/8ea03255-89f9-4e62-9d3f-8817db82ceed\"\n        },\n        {\n          \"href\": \"/facilities/e1e9c52e-a0bc-4117-b996-0fc94843ea09\"\n        }\n      ],\n      \"pricing\": {\n        \"hour\": 0.4\n      }\n    },\n    {\n      \"id\": \"a3729923-fdc4-4e85-a972-aafbad3695db\",\n      \"slug\": \"baremetal_2\",\n      \"name\": \"Type 2\",\n      \"description\": \"Our Type 2 configuration is the perfect all purpose virtualization server, with dual E5-2650 v4 processors, 256 GB of DDR4 RAM, and six SSDs totaling 2.8 TB of storage.\",\n      \"line\": \"baremetal\",\n      \"specs\": {\n        \"cpus\": [\n          {\n            \"count\": 2,\n            \"type\": \"Intel Xeon E5-2650 v4 @2.2GHz\"\n          }\n        ],\n        \"memory\": {\n          \"total\": \"256GB\"\n        },\n        \"drives\": [\n          {\n            \"count\": 6,\n            \"size\": \"480GB\",\n            \"type\": \"SSD\"\n          }\n        ],\n        \"nics\": [\n          {\n            \"count\": 2,\n            \"type\": \"10Gbps\"\n          }\n        ],\n        \"features\": {\n          \"raid\": true,\n          \"txt\": true\n        }\n      },\n      \"available_in\": [\n        {\n          \"href\": \"/facilities/2b70eb8f-fa18-47c0-aba7-222a842362fd\"\n        },\n        {\n          \"href\": \"/facilities/8ea03255-89f9-4e62-9d3f-8817db82ceed\"\n        },\n        {\n          \"href\": \"/facilities/e1e9c52e-a0bc-4117-b996-0fc94843ea09\"\n        }\n      ],\n      \"pricing\": {\n        \"hour\": 1.25\n      }\n    },\n    {\n      \"id\": \"3bc8a214-b807-4058-ad4a-6925f2411155\",\n      \"slug\": \"baremetal_2a\",\n      \"name\": \"Type 2A\",\n      \"description\": \"Our Type 2A configuration is a 96-core dual socket ARM 64 beast based on Cavium ThunderX chips\",\n      \"line\": \"baremetal\",\n      \"specs\": {\n        \"cpus\": [\n          {\n            \"count\": 2,\n            \"type\": \"Cavium ThunderX CN8890 @2GHz\"\n          }\n        ],\n        \"memory\": {\n          \"total\": \"128GB\"\n        },\n        \"drives\": [\n          {\n            \"count\": 1,\n            \"size\": \"512GB\",\n            \"type\": \"SSD\"\n          }\n        ],\n        \"nics\": [\n          {\n            \"count\": 2,\n            \"type\": \"10Gbps\"\n          }\n        ],\n        \"features\": {}\n      },\n      \"available_in\": [\n        {\n          \"href\": \"/facilities/2b70eb8f-fa18-47c0-aba7-222a842362fd\"\n        },\n        {\n          \"href\": \"/facilities/8e6470b3-b75e-47d1-bb93-45b225750975\"\n        },\n        {\n          \"href\": \"/facilities/8ea03255-89f9-4e62-9d3f-8817db82ceed\"\n        },\n        {\n          \"href\": \"/facilities/e1e9c52e-a0bc-4117-b996-0fc94843ea09\"\n        }\n      ],\n      \"pricing\": {\n        \"hour\": 0.5\n      }\n    }\n  ],\n  \"meta\": {\n    \"first\": {\n      \"href\": \"/plans?page=1\"\n    },\n    \"previous\": null,\n    \"self\": {\n      \"href\": \"/plans?page=1\"\n    },\n    \"next\": {\n      \"href\": \"/plans?page=2\"\n    },\n    \"last\": {\n      \"href\": \"/plans?page=2\"\n    },\n    \"total\": 7\n  }\n}\n"
  },
  {
    "path": "providers/packet/src/test/resources/plans-last.json",
    "content": "{\n  \"plans\": [\n    {\n      \"id\": \"741f3afb-bb2f-4694-93a0-fcbad7cd5e78\",\n      \"slug\": \"baremetal_3\",\n      \"name\": \"Type 3\",\n      \"description\": \"Our Type 3 configuration is a high core, high IO server, with dual Intel E5-2640 v3 processors, 128GB of DDR4 RAM and ultra fast NVME flash drives.\",\n      \"line\": \"baremetal\",\n      \"specs\": {\n        \"cpus\": [\n          {\n            \"count\": 2,\n            \"type\": \"Intel E5-2640 v3\"\n          }\n        ],\n        \"memory\": {\n          \"total\": \"128GB\"\n        },\n        \"drives\": [\n          {\n            \"count\": 2,\n            \"size\": \"120GB\",\n            \"type\": \"SSD\"\n          },\n          {\n            \"count\": 1,\n            \"size\": \"1.6TB\",\n            \"type\": \"NVME\"\n          }\n        ],\n        \"nics\": [\n          {\n            \"count\": 2,\n            \"type\": \"10Gbps\"\n          }\n        ],\n        \"features\": {\n          \"raid\": true,\n          \"txt\": true\n        }\n      },\n      \"available_in\": [\n        {\n          \"href\": \"/facilities/2b70eb8f-fa18-47c0-aba7-222a842362fd\"\n        },\n        {\n          \"href\": \"/facilities/8e6470b3-b75e-47d1-bb93-45b225750975\"\n        },\n        {\n          \"href\": \"/facilities/e1e9c52e-a0bc-4117-b996-0fc94843ea09\"\n        }\n      ],\n      \"pricing\": {\n        \"hour\": 1.75\n      }\n    },\n    {\n      \"id\": \"87728148-3155-4992-a730-8d1e6aca8a32\",\n      \"slug\": \"storage_1\",\n      \"name\": \"Standard\",\n      \"description\": \"TBD\",\n      \"line\": \"storage\",\n      \"specs\": {},\n      \"available_in\": [],\n      \"pricing\": {\n        \"hour\": 0.000104\n      }\n    },\n    {\n      \"id\": \"d6570cfb-38fa-4467-92b3-e45d059bb249\",\n      \"slug\": \"storage_2\",\n      \"name\": \"Performance\",\n      \"description\": \"TBD\",\n      \"line\": \"storage\",\n      \"specs\": {},\n      \"available_in\": [],\n      \"pricing\": {\n        \"hour\": 0.000223\n      }\n    }\n  ],\n  \"meta\": {\n    \"first\": {\n      \"href\": \"/plans?page=1\"\n    },\n    \"previous\": {\n      \"href\": \"/plans?page=1\"\n    },\n    \"self\": {\n      \"href\": \"/plans?page=2\"\n    },\n    \"next\": null,\n    \"last\": {\n      \"href\": \"/plans?page=2\"\n    },\n    \"total\": 7\n  }\n}\n"
  },
  {
    "path": "providers/packet/src/test/resources/plans.json",
    "content": "{\n  \"plans\": [\n    {\n      \"id\": \"e69c0169-4726-46ea-98f1-939c9e8a3607\",\n      \"slug\": \"baremetal_0\",\n      \"name\": \"Type 0\",\n      \"description\": \"Our Type 0 configuration is a general use \\\"cloud killer\\\" server, with a Intel Atom 2.4Ghz processor and 8GB of RAM.\",\n      \"line\": \"baremetal\",\n      \"specs\": {\n        \"cpus\": [\n          {\n            \"count\": 1,\n            \"type\": \"Intel Atom C2550 @ 2.4Ghz\"\n          }\n        ],\n        \"memory\": {\n          \"total\": \"8GB\"\n        },\n        \"drives\": [\n          {\n            \"count\": 1,\n            \"size\": \"80GB\",\n            \"type\": \"SSD\"\n          }\n        ],\n        \"nics\": [\n          {\n            \"count\": 2,\n            \"type\": \"1Gbps\"\n          }\n        ],\n        \"features\": {\n          \"raid\": false,\n          \"txt\": true\n        }\n      },\n      \"available_in\": [\n        {\n          \"href\": \"/facilities/2b70eb8f-fa18-47c0-aba7-222a842362fd\"\n        },\n        {\n          \"href\": \"/facilities/8e6470b3-b75e-47d1-bb93-45b225750975\"\n        },\n        {\n          \"href\": \"/facilities/8ea03255-89f9-4e62-9d3f-8817db82ceed\"\n        },\n        {\n          \"href\": \"/facilities/e1e9c52e-a0bc-4117-b996-0fc94843ea09\"\n        }\n      ],\n      \"pricing\": {\n        \"hour\": 0.05\n      }\n    },\n    {\n      \"id\": \"6d1f1ffa-7912-4b78-b50d-88cc7c8ab40f\",\n      \"slug\": \"baremetal_1\",\n      \"name\": \"Type 1\",\n      \"description\": \"Our Type 1 configuration is a zippy general use server, with an Intel E3-1240 v3 processor and 32GB of RAM.\",\n      \"line\": \"baremetal\",\n      \"specs\": {\n        \"cpus\": [\n          {\n            \"count\": 1,\n            \"type\": \"Intel E3-1240 v3\"\n          }\n        ],\n        \"memory\": {\n          \"total\": \"32GB\"\n        },\n        \"drives\": [\n          {\n            \"count\": 2,\n            \"size\": \"120GB\",\n            \"type\": \"SSD\"\n          }\n        ],\n        \"nics\": [\n          {\n            \"count\": 2,\n            \"type\": \"1Gbps\"\n          }\n        ],\n        \"features\": {\n          \"raid\": true,\n          \"txt\": true\n        }\n      },\n      \"available_in\": [\n        {\n          \"href\": \"/facilities/2b70eb8f-fa18-47c0-aba7-222a842362fd\"\n        },\n        {\n          \"href\": \"/facilities/8e6470b3-b75e-47d1-bb93-45b225750975\"\n        },\n        {\n          \"href\": \"/facilities/8ea03255-89f9-4e62-9d3f-8817db82ceed\"\n        },\n        {\n          \"href\": \"/facilities/e1e9c52e-a0bc-4117-b996-0fc94843ea09\"\n        }\n      ],\n      \"pricing\": {\n        \"hour\": 0.4\n      }\n    },\n    {\n      \"id\": \"a3729923-fdc4-4e85-a972-aafbad3695db\",\n      \"slug\": \"baremetal_2\",\n      \"name\": \"Type 2\",\n      \"description\": \"Our Type 2 configuration is the perfect all purpose virtualization server, with dual E5-2650 v4 processors, 256 GB of DDR4 RAM, and six SSDs totaling 2.8 TB of storage.\",\n      \"line\": \"baremetal\",\n      \"specs\": {\n        \"cpus\": [\n          {\n            \"count\": 2,\n            \"type\": \"Intel Xeon E5-2650 v4 @2.2GHz\"\n          }\n        ],\n        \"memory\": {\n          \"total\": \"256GB\"\n        },\n        \"drives\": [\n          {\n            \"count\": 6,\n            \"size\": \"480GB\",\n            \"type\": \"SSD\"\n          }\n        ],\n        \"nics\": [\n          {\n            \"count\": 2,\n            \"type\": \"10Gbps\"\n          }\n        ],\n        \"features\": {\n          \"raid\": true,\n          \"txt\": true\n        }\n      },\n      \"available_in\": [\n        {\n          \"href\": \"/facilities/2b70eb8f-fa18-47c0-aba7-222a842362fd\"\n        },\n        {\n          \"href\": \"/facilities/8ea03255-89f9-4e62-9d3f-8817db82ceed\"\n        },\n        {\n          \"href\": \"/facilities/e1e9c52e-a0bc-4117-b996-0fc94843ea09\"\n        }\n      ],\n      \"pricing\": {\n        \"hour\": 1.25\n      }\n    },\n    {\n      \"id\": \"3bc8a214-b807-4058-ad4a-6925f2411155\",\n      \"slug\": \"baremetal_2a\",\n      \"name\": \"Type 2A\",\n      \"description\": \"Our Type 2A configuration is a 96-core dual socket ARM 64 beast based on Cavium ThunderX chips\",\n      \"line\": \"baremetal\",\n      \"specs\": {\n        \"cpus\": [\n          {\n            \"count\": 2,\n            \"type\": \"Cavium ThunderX CN8890 @2GHz\"\n          }\n        ],\n        \"memory\": {\n          \"total\": \"128GB\"\n        },\n        \"drives\": [\n          {\n            \"count\": 1,\n            \"size\": \"512GB\",\n            \"type\": \"SSD\"\n          }\n        ],\n        \"nics\": [\n          {\n            \"count\": 2,\n            \"type\": \"10Gbps\"\n          }\n        ],\n        \"features\": {}\n      },\n      \"available_in\": [\n        {\n          \"href\": \"/facilities/2b70eb8f-fa18-47c0-aba7-222a842362fd\"\n        },\n        {\n          \"href\": \"/facilities/8e6470b3-b75e-47d1-bb93-45b225750975\"\n        },\n        {\n          \"href\": \"/facilities/8ea03255-89f9-4e62-9d3f-8817db82ceed\"\n        },\n        {\n          \"href\": \"/facilities/e1e9c52e-a0bc-4117-b996-0fc94843ea09\"\n        }\n      ],\n      \"pricing\": {\n        \"hour\": 0.5\n      }\n    },\n    {\n      \"id\": \"741f3afb-bb2f-4694-93a0-fcbad7cd5e78\",\n      \"slug\": \"baremetal_3\",\n      \"name\": \"Type 3\",\n      \"description\": \"Our Type 3 configuration is a high core, high IO server, with dual Intel E5-2640 v3 processors, 128GB of DDR4 RAM and ultra fast NVME flash drives.\",\n      \"line\": \"baremetal\",\n      \"specs\": {\n        \"cpus\": [\n          {\n            \"count\": 2,\n            \"type\": \"Intel E5-2640 v3\"\n          }\n        ],\n        \"memory\": {\n          \"total\": \"128GB\"\n        },\n        \"drives\": [\n          {\n            \"count\": 2,\n            \"size\": \"120GB\",\n            \"type\": \"SSD\"\n          },\n          {\n            \"count\": 1,\n            \"size\": \"1.6TB\",\n            \"type\": \"NVME\"\n          }\n        ],\n        \"nics\": [\n          {\n            \"count\": 2,\n            \"type\": \"10Gbps\"\n          }\n        ],\n        \"features\": {\n          \"raid\": true,\n          \"txt\": true\n        }\n      },\n      \"available_in\": [\n        {\n          \"href\": \"/facilities/2b70eb8f-fa18-47c0-aba7-222a842362fd\"\n        },\n        {\n          \"href\": \"/facilities/8e6470b3-b75e-47d1-bb93-45b225750975\"\n        },\n        {\n          \"href\": \"/facilities/e1e9c52e-a0bc-4117-b996-0fc94843ea09\"\n        }\n      ],\n      \"pricing\": {\n        \"hour\": 1.75\n      }\n    },\n    {\n      \"id\": \"87728148-3155-4992-a730-8d1e6aca8a32\",\n      \"slug\": \"storage_1\",\n      \"name\": \"Standard\",\n      \"description\": \"TBD\",\n      \"line\": \"storage\",\n      \"specs\": {},\n      \"available_in\": [],\n      \"pricing\": {\n        \"hour\": 0.000104\n      }\n    },\n    {\n      \"id\": \"d6570cfb-38fa-4467-92b3-e45d059bb249\",\n      \"slug\": \"storage_2\",\n      \"name\": \"Performance\",\n      \"description\": \"TBD\",\n      \"line\": \"storage\",\n      \"specs\": {},\n      \"available_in\": [],\n      \"pricing\": {\n        \"hour\": 0.000223\n      }\n    }\n  ]\n}\n"
  },
  {
    "path": "providers/packet/src/test/resources/power-off.json",
    "content": "{\n  \"type\": \"power_off\"\n}\n"
  },
  {
    "path": "providers/packet/src/test/resources/power-on.json",
    "content": "{\n  \"type\": \"power_on\"\n}\n"
  },
  {
    "path": "providers/packet/src/test/resources/projects-first.json",
    "content": "{\n  \"projects\": [\n    {\n      \"id\": \"93907f48-adfe-43ed-ad89-0e6e83721a54\",\n      \"name\": \"Cloudsoft CCS Testing\",\n      \"created_at\": \"2016-09-15T08:50:58Z\",\n      \"updated_at\": \"2017-01-05T09:36:53Z\",\n      \"max_devices\": {\n        \"baremetal_0\": null,\n        \"baremetal_1\": null,\n        \"baremetal_2\": null,\n        \"baremetal_3\": null,\n        \"baremetal_2a\": null,\n        \"storage_1\": null,\n        \"storage_2\": null\n      },\n      \"members\": [\n        {\n          \"href\": \"/users/1140617d-262d-4502-a3d6-771d83c930da\"\n        },\n        {\n          \"href\": \"/users/343345fe-18b3-46a3-9b9c-e4a2fe88ccbd\"\n        },\n        {\n          \"href\": \"/users/73b0442e-cc4b-42a0-8d3a-c8dfb8a4ff2e\"\n        },\n        {\n          \"href\": \"/users/ad711bc3-6333-449a-a405-23ca81f38c00\"\n        }\n      ],\n      \"memberships\": [\n        {\n          \"href\": \"/memberships/914facae-547f-46fc-93e8-860eb53d9bf6\"\n        },\n        {\n          \"href\": \"/memberships/1ce7c9d9-d11f-47f2-b5a6-d1221338ad69\"\n        },\n        {\n          \"href\": \"/memberships/e25c4478-9e44-465a-a9d7-bffc7a83300d\"\n        },\n        {\n          \"href\": \"/memberships/8a00c05b-3ddc-41c3-8dd7-4a3d5984ecec\"\n        }\n      ],\n      \"invitations\": [],\n      \"payment_method\": {\n        \"href\": \"/payment-methods/b2bb4ee0-506b-4c01-b17d-ba41d5c430c5\"\n      },\n      \"devices\": [\n        {\n          \"href\": \"/devices/4942a6c7-55c6-42cc-a06b-cccd6f2fa5df\"\n        }\n      ],\n      \"ssh_keys\": [\n        {\n          \"href\": \"/ssh-keys/070e3282-5b6a-4f75-8f18-a4e7488eafaa\"\n        }\n      ],\n      \"volumes\": [],\n      \"href\": \"/projects/93907f48-adfe-43ed-ad89-0e6e83721a54\"\n    },\n    {\n      \"id\": \"93907f48-adfe-43ed-ad89-0e6e83721a53\",\n      \"name\": \"Cloudsoft CCS Testing\",\n      \"created_at\": \"2016-09-15T08:50:58Z\",\n      \"updated_at\": \"2017-01-05T09:36:53Z\",\n      \"max_devices\": {\n        \"baremetal_0\": null,\n        \"baremetal_1\": null,\n        \"baremetal_2\": null,\n        \"baremetal_3\": null,\n        \"baremetal_2a\": null,\n        \"storage_1\": null,\n        \"storage_2\": null\n      },\n      \"members\": [\n        {\n          \"href\": \"/users/1140617d-262d-4502-a3d6-771d83c930da\"\n        },\n        {\n          \"href\": \"/users/343345fe-18b3-46a3-9b9c-e4a2fe88ccbd\"\n        },\n        {\n          \"href\": \"/users/73b0442e-cc4b-42a0-8d3a-c8dfb8a4ff2e\"\n        },\n        {\n          \"href\": \"/users/ad711bc3-6333-449a-a405-23ca81f38c00\"\n        }\n      ],\n      \"memberships\": [\n        {\n          \"href\": \"/memberships/914facae-547f-46fc-93e8-860eb53d9bf6\"\n        },\n        {\n          \"href\": \"/memberships/1ce7c9d9-d11f-47f2-b5a6-d1221338ad69\"\n        },\n        {\n          \"href\": \"/memberships/e25c4478-9e44-465a-a9d7-bffc7a83300d\"\n        },\n        {\n          \"href\": \"/memberships/8a00c05b-3ddc-41c3-8dd7-4a3d5984ecec\"\n        }\n      ],\n      \"invitations\": [],\n      \"payment_method\": {\n        \"href\": \"/payment-methods/b2bb4ee0-506b-4c01-b17d-ba41d5c430c5\"\n      },\n      \"devices\": [\n        {\n          \"href\": \"/devices/4942a6c7-55c6-42cc-a06b-cccd6f2fa5df\"\n        }\n      ],\n      \"ssh_keys\": [\n        {\n          \"href\": \"/ssh-keys/070e3282-5b6a-4f75-8f18-a4e7488eafaa\"\n        }\n      ],\n      \"volumes\": [],\n      \"href\": \"/projects/93907f48-adfe-43ed-ad89-0e6e83721a54\"\n    },\n    {\n      \"id\": \"93907f48-adfe-43ed-ad89-0e6e83721a52\",\n      \"name\": \"Cloudsoft CCS Testing\",\n      \"created_at\": \"2016-09-15T08:50:58Z\",\n      \"updated_at\": \"2017-01-05T09:36:53Z\",\n      \"max_devices\": {\n        \"baremetal_0\": null,\n        \"baremetal_1\": null,\n        \"baremetal_2\": null,\n        \"baremetal_3\": null,\n        \"baremetal_2a\": null,\n        \"storage_1\": null,\n        \"storage_2\": null\n      },\n      \"members\": [\n        {\n          \"href\": \"/users/1140617d-262d-4502-a3d6-771d83c930da\"\n        },\n        {\n          \"href\": \"/users/343345fe-18b3-46a3-9b9c-e4a2fe88ccbd\"\n        },\n        {\n          \"href\": \"/users/73b0442e-cc4b-42a0-8d3a-c8dfb8a4ff2e\"\n        },\n        {\n          \"href\": \"/users/ad711bc3-6333-449a-a405-23ca81f38c00\"\n        }\n      ],\n      \"memberships\": [\n        {\n          \"href\": \"/memberships/914facae-547f-46fc-93e8-860eb53d9bf6\"\n        },\n        {\n          \"href\": \"/memberships/1ce7c9d9-d11f-47f2-b5a6-d1221338ad69\"\n        },\n        {\n          \"href\": \"/memberships/e25c4478-9e44-465a-a9d7-bffc7a83300d\"\n        },\n        {\n          \"href\": \"/memberships/8a00c05b-3ddc-41c3-8dd7-4a3d5984ecec\"\n        }\n      ],\n      \"invitations\": [],\n      \"payment_method\": {\n        \"href\": \"/payment-methods/b2bb4ee0-506b-4c01-b17d-ba41d5c430c5\"\n      },\n      \"devices\": [\n        {\n          \"href\": \"/devices/4942a6c7-55c6-42cc-a06b-cccd6f2fa5df\"\n        }\n      ],\n      \"ssh_keys\": [\n        {\n          \"href\": \"/ssh-keys/070e3282-5b6a-4f75-8f18-a4e7488eafaa\"\n        }\n      ],\n      \"volumes\": [],\n      \"href\": \"/projects/93907f48-adfe-43ed-ad89-0e6e83721a54\"\n    },\n    {\n      \"id\": \"93907f48-adfe-43ed-ad89-0e6e83721a51\",\n      \"name\": \"Cloudsoft CCS Testing\",\n      \"created_at\": \"2016-09-15T08:50:58Z\",\n      \"updated_at\": \"2017-01-05T09:36:53Z\",\n      \"max_devices\": {\n        \"baremetal_0\": null,\n        \"baremetal_1\": null,\n        \"baremetal_2\": null,\n        \"baremetal_3\": null,\n        \"baremetal_2a\": null,\n        \"storage_1\": null,\n        \"storage_2\": null\n      },\n      \"members\": [\n        {\n          \"href\": \"/users/1140617d-262d-4502-a3d6-771d83c930da\"\n        },\n        {\n          \"href\": \"/users/343345fe-18b3-46a3-9b9c-e4a2fe88ccbd\"\n        },\n        {\n          \"href\": \"/users/73b0442e-cc4b-42a0-8d3a-c8dfb8a4ff2e\"\n        },\n        {\n          \"href\": \"/users/ad711bc3-6333-449a-a405-23ca81f38c00\"\n        }\n      ],\n      \"memberships\": [\n        {\n          \"href\": \"/memberships/914facae-547f-46fc-93e8-860eb53d9bf6\"\n        },\n        {\n          \"href\": \"/memberships/1ce7c9d9-d11f-47f2-b5a6-d1221338ad69\"\n        },\n        {\n          \"href\": \"/memberships/e25c4478-9e44-465a-a9d7-bffc7a83300d\"\n        },\n        {\n          \"href\": \"/memberships/8a00c05b-3ddc-41c3-8dd7-4a3d5984ecec\"\n        }\n      ],\n      \"invitations\": [],\n      \"payment_method\": {\n        \"href\": \"/payment-methods/b2bb4ee0-506b-4c01-b17d-ba41d5c430c5\"\n      },\n      \"devices\": [\n        {\n          \"href\": \"/devices/4942a6c7-55c6-42cc-a06b-cccd6f2fa5df\"\n        }\n      ],\n      \"ssh_keys\": [\n        {\n          \"href\": \"/ssh-keys/070e3282-5b6a-4f75-8f18-a4e7488eafaa\"\n        }\n      ],\n      \"volumes\": [],\n      \"href\": \"/projects/93907f48-adfe-43ed-ad89-0e6e83721a54\"\n    },\n    {\n      \"id\": \"93907f48-adfe-43ed-ad89-0e6e83721a50\",\n      \"name\": \"Cloudsoft CCS Testing\",\n      \"created_at\": \"2016-09-15T08:50:58Z\",\n      \"updated_at\": \"2017-01-05T09:36:53Z\",\n      \"max_devices\": {\n        \"baremetal_0\": null,\n        \"baremetal_1\": null,\n        \"baremetal_2\": null,\n        \"baremetal_3\": null,\n        \"baremetal_2a\": null,\n        \"storage_1\": null,\n        \"storage_2\": null\n      },\n      \"members\": [\n        {\n          \"href\": \"/users/1140617d-262d-4502-a3d6-771d83c930da\"\n        },\n        {\n          \"href\": \"/users/343345fe-18b3-46a3-9b9c-e4a2fe88ccbd\"\n        },\n        {\n          \"href\": \"/users/73b0442e-cc4b-42a0-8d3a-c8dfb8a4ff2e\"\n        },\n        {\n          \"href\": \"/users/ad711bc3-6333-449a-a405-23ca81f38c00\"\n        }\n      ],\n      \"memberships\": [\n        {\n          \"href\": \"/memberships/914facae-547f-46fc-93e8-860eb53d9bf6\"\n        },\n        {\n          \"href\": \"/memberships/1ce7c9d9-d11f-47f2-b5a6-d1221338ad69\"\n        },\n        {\n          \"href\": \"/memberships/e25c4478-9e44-465a-a9d7-bffc7a83300d\"\n        },\n        {\n          \"href\": \"/memberships/8a00c05b-3ddc-41c3-8dd7-4a3d5984ecec\"\n        }\n      ],\n      \"invitations\": [],\n      \"payment_method\": {\n        \"href\": \"/payment-methods/b2bb4ee0-506b-4c01-b17d-ba41d5c430c5\"\n      },\n      \"devices\": [\n        {\n          \"href\": \"/devices/4942a6c7-55c6-42cc-a06b-cccd6f2fa5df\"\n        }\n      ],\n      \"ssh_keys\": [\n        {\n          \"href\": \"/ssh-keys/070e3282-5b6a-4f75-8f18-a4e7488eafaa\"\n        }\n      ],\n      \"volumes\": [],\n      \"href\": \"/projects/93907f48-adfe-43ed-ad89-0e6e83721a54\"\n    }\n  ],\n  \"meta\": {\n    \"first\": {\n      \"href\": \"/projects?page=1\"\n    },\n    \"previous\": null,\n    \"self\": {\n      \"href\": \"/projects?page=1\"\n    },\n    \"next\": {\n      \"href\": \"/projects?page=2\"\n    },\n    \"last\": {\n      \"href\": \"/projects?page=2\"\n    },\n    \"total\": 8\n  }\n}\n"
  },
  {
    "path": "providers/packet/src/test/resources/projects-last.json",
    "content": "{\n  \"projects\": [\n    {\n      \"id\": \"93907f48-adfe-43ed-ad89-0e6e83721a55\",\n      \"name\": \"Cloudsoft CCS Testing\",\n      \"created_at\": \"2016-09-15T08:50:58Z\",\n      \"updated_at\": \"2017-01-05T09:36:53Z\",\n      \"max_devices\": {\n        \"baremetal_0\": null,\n        \"baremetal_1\": null,\n        \"baremetal_2\": null,\n        \"baremetal_3\": null,\n        \"baremetal_2a\": null,\n        \"storage_1\": null,\n        \"storage_2\": null\n      },\n      \"members\": [\n        {\n          \"href\": \"/users/1140617d-262d-4502-a3d6-771d83c930da\"\n        },\n        {\n          \"href\": \"/users/343345fe-18b3-46a3-9b9c-e4a2fe88ccbd\"\n        },\n        {\n          \"href\": \"/users/73b0442e-cc4b-42a0-8d3a-c8dfb8a4ff2e\"\n        },\n        {\n          \"href\": \"/users/ad711bc3-6333-449a-a405-23ca81f38c00\"\n        }\n      ],\n      \"memberships\": [\n        {\n          \"href\": \"/memberships/914facae-547f-46fc-93e8-860eb53d9bf6\"\n        },\n        {\n          \"href\": \"/memberships/1ce7c9d9-d11f-47f2-b5a6-d1221338ad69\"\n        },\n        {\n          \"href\": \"/memberships/e25c4478-9e44-465a-a9d7-bffc7a83300d\"\n        },\n        {\n          \"href\": \"/memberships/8a00c05b-3ddc-41c3-8dd7-4a3d5984ecec\"\n        }\n      ],\n      \"invitations\": [],\n      \"payment_method\": {\n        \"href\": \"/payment-methods/b2bb4ee0-506b-4c01-b17d-ba41d5c430c5\"\n      },\n      \"devices\": [\n        {\n          \"href\": \"/devices/4942a6c7-55c6-42cc-a06b-cccd6f2fa5df\"\n        }\n      ],\n      \"ssh_keys\": [\n        {\n          \"href\": \"/ssh-keys/070e3282-5b6a-4f75-8f18-a4e7488eafaa\"\n        }\n      ],\n      \"volumes\": [],\n      \"href\": \"/projects/93907f48-adfe-43ed-ad89-0e6e83721a54\"\n    },\n    {\n      \"id\": \"93907f48-adfe-43ed-ad89-0e6e83721a56\",\n      \"name\": \"Cloudsoft CCS Testing\",\n      \"created_at\": \"2016-09-15T08:50:58Z\",\n      \"updated_at\": \"2017-01-05T09:36:53Z\",\n      \"max_devices\": {\n        \"baremetal_0\": null,\n        \"baremetal_1\": null,\n        \"baremetal_2\": null,\n        \"baremetal_3\": null,\n        \"baremetal_2a\": null,\n        \"storage_1\": null,\n        \"storage_2\": null\n      },\n      \"members\": [\n        {\n          \"href\": \"/users/1140617d-262d-4502-a3d6-771d83c930da\"\n        },\n        {\n          \"href\": \"/users/343345fe-18b3-46a3-9b9c-e4a2fe88ccbd\"\n        },\n        {\n          \"href\": \"/users/73b0442e-cc4b-42a0-8d3a-c8dfb8a4ff2e\"\n        },\n        {\n          \"href\": \"/users/ad711bc3-6333-449a-a405-23ca81f38c00\"\n        }\n      ],\n      \"memberships\": [\n        {\n          \"href\": \"/memberships/914facae-547f-46fc-93e8-860eb53d9bf6\"\n        },\n        {\n          \"href\": \"/memberships/1ce7c9d9-d11f-47f2-b5a6-d1221338ad69\"\n        },\n        {\n          \"href\": \"/memberships/e25c4478-9e44-465a-a9d7-bffc7a83300d\"\n        },\n        {\n          \"href\": \"/memberships/8a00c05b-3ddc-41c3-8dd7-4a3d5984ecec\"\n        }\n      ],\n      \"invitations\": [],\n      \"payment_method\": {\n        \"href\": \"/payment-methods/b2bb4ee0-506b-4c01-b17d-ba41d5c430c5\"\n      },\n      \"devices\": [\n        {\n          \"href\": \"/devices/4942a6c7-55c6-42cc-a06b-cccd6f2fa5df\"\n        }\n      ],\n      \"ssh_keys\": [\n        {\n          \"href\": \"/ssh-keys/070e3282-5b6a-4f75-8f18-a4e7488eafaa\"\n        }\n      ],\n      \"volumes\": [],\n      \"href\": \"/projects/93907f48-adfe-43ed-ad89-0e6e83721a54\"\n    },\n    {\n      \"id\": \"93907f48-adfe-43ed-ad89-0e6e83721a57\",\n      \"name\": \"Cloudsoft CCS Testing\",\n      \"created_at\": \"2016-09-15T08:50:58Z\",\n      \"updated_at\": \"2017-01-05T09:36:53Z\",\n      \"max_devices\": {\n        \"baremetal_0\": null,\n        \"baremetal_1\": null,\n        \"baremetal_2\": null,\n        \"baremetal_3\": null,\n        \"baremetal_2a\": null,\n        \"storage_1\": null,\n        \"storage_2\": null\n      },\n      \"members\": [\n        {\n          \"href\": \"/users/1140617d-262d-4502-a3d6-771d83c930da\"\n        },\n        {\n          \"href\": \"/users/343345fe-18b3-46a3-9b9c-e4a2fe88ccbd\"\n        },\n        {\n          \"href\": \"/users/73b0442e-cc4b-42a0-8d3a-c8dfb8a4ff2e\"\n        },\n        {\n          \"href\": \"/users/ad711bc3-6333-449a-a405-23ca81f38c00\"\n        }\n      ],\n      \"memberships\": [\n        {\n          \"href\": \"/memberships/914facae-547f-46fc-93e8-860eb53d9bf6\"\n        },\n        {\n          \"href\": \"/memberships/1ce7c9d9-d11f-47f2-b5a6-d1221338ad69\"\n        },\n        {\n          \"href\": \"/memberships/e25c4478-9e44-465a-a9d7-bffc7a83300d\"\n        },\n        {\n          \"href\": \"/memberships/8a00c05b-3ddc-41c3-8dd7-4a3d5984ecec\"\n        }\n      ],\n      \"invitations\": [],\n      \"payment_method\": {\n        \"href\": \"/payment-methods/b2bb4ee0-506b-4c01-b17d-ba41d5c430c5\"\n      },\n      \"devices\": [\n        {\n          \"href\": \"/devices/4942a6c7-55c6-42cc-a06b-cccd6f2fa5df\"\n        }\n      ],\n      \"ssh_keys\": [\n        {\n          \"href\": \"/ssh-keys/070e3282-5b6a-4f75-8f18-a4e7488eafaa\"\n        }\n      ],\n      \"volumes\": [],\n      \"href\": \"/projects/93907f48-adfe-43ed-ad89-0e6e83721a54\"\n    }\n  ],\n  \"meta\": {\n    \"first\": {\n      \"href\": \"/projects?page=1\"\n    },\n    \"previous\": {\n      \"href\": \"/projects?page=1\"\n    },\n    \"self\": {\n      \"href\": \"/projects?page=2\"\n    },\n    \"next\": null,\n    \"last\": {\n      \"href\": \"/projects?page=2\"\n    },\n    \"total\": 8\n  }\n}\n"
  },
  {
    "path": "providers/packet/src/test/resources/projects.json",
    "content": "{\n  \"projects\": [\n    {\n      \"id\": \"93907f48-adfe-43ed-ad89-0e6e83721a54\",\n      \"name\": \"Cloudsoft CCS Testing\",\n      \"created_at\": \"2016-09-15T08:50:58Z\",\n      \"updated_at\": \"2017-01-05T09:36:53Z\",\n      \"max_devices\": {\n        \"baremetal_0\": null,\n        \"baremetal_1\": null,\n        \"baremetal_2\": null,\n        \"baremetal_3\": null,\n        \"baremetal_2a\": null,\n        \"storage_1\": null,\n        \"storage_2\": null\n      },\n      \"members\": [\n        {\n          \"href\": \"/users/1140617d-262d-4502-a3d6-771d83c930da\"\n        },\n        {\n          \"href\": \"/users/343345fe-18b3-46a3-9b9c-e4a2fe88ccbd\"\n        },\n        {\n          \"href\": \"/users/73b0442e-cc4b-42a0-8d3a-c8dfb8a4ff2e\"\n        },\n        {\n          \"href\": \"/users/ad711bc3-6333-449a-a405-23ca81f38c00\"\n        }\n      ],\n      \"memberships\": [\n        {\n          \"href\": \"/memberships/914facae-547f-46fc-93e8-860eb53d9bf6\"\n        },\n        {\n          \"href\": \"/memberships/1ce7c9d9-d11f-47f2-b5a6-d1221338ad69\"\n        },\n        {\n          \"href\": \"/memberships/e25c4478-9e44-465a-a9d7-bffc7a83300d\"\n        },\n        {\n          \"href\": \"/memberships/8a00c05b-3ddc-41c3-8dd7-4a3d5984ecec\"\n        }\n      ],\n      \"invitations\": [],\n      \"payment_method\": {\n        \"href\": \"/payment-methods/b2bb4ee0-506b-4c01-b17d-ba41d5c430c5\"\n      },\n      \"devices\": [\n        {\n          \"href\": \"/devices/4942a6c7-55c6-42cc-a06b-cccd6f2fa5df\"\n        }\n      ],\n      \"ssh_keys\": [\n        {\n          \"href\": \"/ssh-keys/070e3282-5b6a-4f75-8f18-a4e7488eafaa\"\n        }\n      ],\n      \"volumes\": [],\n      \"href\": \"/projects/93907f48-adfe-43ed-ad89-0e6e83721a54\"\n    }\n  ],\n  \"meta\": {\n    \"first\": {\n      \"href\": \"/projects?page=1\"\n    },\n    \"previous\": null,\n    \"self\": {\n      \"href\": \"/projects?page=1\"\n    },\n    \"next\": null,\n    \"last\": {\n      \"href\": \"/projects?page=1\"\n    },\n    \"total\": 1\n  }\n}\n"
  },
  {
    "path": "providers/packet/src/test/resources/reboot.json",
    "content": "{\n  \"type\": \"reboot\"\n}\n"
  },
  {
    "path": "providers/packet/src/test/resources/ssh-key-create-req.json",
    "content": "{\n  \"label\": \"jclouds-ssh-key-livetest\",\n  \"key\": \"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCdgcoNzH4hCc0j3b4MuG503L/J54uyFvwCAOu8vSsYuLpJ4AEyEOv+T0SfdF605fK6GYXA16Rxk3lrPt7mfKGNtXR0Ripbv7Zc6PvCRorwgj/cjh/45miozjrkXAiHD1GFZycfbi4YsoWAqZj7W4mwtctmhrYM0FPdya2XoRpVy89N+A5Xo4Xtd6EZn6JGEKQM5+kF2aL3ggy0od/DqjuEVYwZoyTe1RgUTXZSU/Woh7WMhsRHbqd3eYz4s6ac8n8IJPGKtUaQeqUtH7OK6NRYXVypUrkqNlwdNYZAwrjXg/x5T3D+bo11LENASRt9OJ2OkmRSTqRxBeDkhnVauWK/\"\n}\n"
  },
  {
    "path": "providers/packet/src/test/resources/ssh-key-create-res.json",
    "content": "{\n  \"id\": \"da5d6c21-2e8c-43ac-820f-ff41bd4e6ebc\",\n  \"label\": \"andrea-device-livetest\",\n  \"key\": \"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCdgcoNzH4hCc0j3b4MuG503L/J54uyFvwCAOu8vSsYuLpJ4AEyEOv+T0SfdF605fK6GYXA16Rxk3lrPt7mfKGNtXR0Ripbv7Zc6PvCRorwgj/cjh/45miozjrkXAiHD1GFZycfbi4YsoWAqZj7W4mwtctmhrYM0FPdya2XoRpVy89N+A5Xo4Xtd6EZn6JGEKQM5+kF2aL3ggy0od/DqjuEVYwZoyTe1RgUTXZSU/Woh7WMhsRHbqd3eYz4s6ac8n8IJPGKtUaQeqUtH7OK6NRYXVypUrkqNlwdNYZAwrjXg/x5T3D+bo11LENASRt9OJ2OkmRSTqRxBeDkhnVauWK/\",\n  \"fingerprint\": \"60:b0:5a:23:42:b8:53:19:d0:32:f1:4d:a8:7c:9b:71\",\n  \"created_at\": \"2017-01-20T14:15:26Z\",\n  \"updated_at\": \"2017-01-20T14:15:26Z\",\n  \"owner\": {\n    \"href\": \"/users/ad711bc3-6333-449a-a405-23ca81f38c00\"\n  },\n  \"href\": \"/ssh-keys/da5d6c21-2e8c-43ac-820f-ff41bd4e6ebc\"\n}\n"
  },
  {
    "path": "providers/packet/src/test/resources/ssh-key.json",
    "content": "{\n  \"id\": \"bba63e41-b12c-493a-81d4-e52f50f247ed\",\n  \"label\": \"test\",\n  \"key\": \"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDNnvPZ25wZK19grrbal6R5JP1hLRBUuNh86KxZVMAFkGd5ouVSgO9dFajHZ45Q4mbaTkdOiqf7otMLDzkaztEa7oLK7Jso0Y0LOi+nT4gf38rvbEF5mq069G9b9XqlNleaGnpLuTN54iEK8c4TWZxIJqgelHEHhjp7V1asmilBbpZDmwA5cTt9vGJIhqA/BptKH3folZKeAQjRa1ZRSwSQUnk9rBKn4PKSRDojVa9A9jKt4qboJh5q7ZjtE8z+665F/4TgLzElTXUA8+uUFGpuynMSmQEt301e18dXAl+vBr8fMiThcoVVbdVdqdjXsw75fMXPAgqhjrw8k3+0/4P9 andrea@bigmac.local\",\n  \"fingerprint\": \"88:8a:7d:0f:db:fb:f4:2a:63:2e:d3:4b:1f:7f:0b:12\",\n  \"created_at\": \"2017-01-03T09:42:54Z\",\n  \"updated_at\": \"2017-01-03T09:42:54Z\",\n  \"owner\": {\n    \"href\": \"/users/ad711bc3-6333-449a-a405-23ca81f38c00\"\n  },\n  \"href\": \"/ssh-keys/bba63e41-b12c-493a-81d4-e52f50f247ed\"\n}\n"
  },
  {
    "path": "providers/packet/src/test/resources/sshKeys-first.json",
    "content": "{\n  \"ssh_keys\": [\n    {\n      \"id\": \"bba63e41-b12c-493a-81d4-e52f50f247e1\",\n      \"label\": \"test\",\n      \"key\": \"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDNnvPZ25wZK19grrbal6R5JP1hLRBUuNh86KxZVMAFkGd5ouVSgO9dFajHZ45Q4mbaTkdOiqf7otMLDzkaztEa7oLK7Jso0Y0LOi+nT4gf38rvbEF5mq069G9b9XqlNleaGnpLuTN54iEK8c4TWZxIJqgelHEHhjp7V1asmilBbpZDmwA5cTt9vGJIhqA/BptKH3folZKeAQjRa1ZRSwSQUnk9rBKn4PKSRDojVa9A9jKt4qboJh5q7ZjtE8z+665F/4TgLzElTXUA8+uUFGpuynMSmQEt301e18dXAl+vBr8fMiThcoVVbdVdqdjXsw75fMXPAgqhjrw8k3+0/4P9 andrea@bigmac.local\",\n      \"fingerprint\": \"88:8a:7d:0f:db:fb:f4:2a:63:2e:d3:4b:1f:7f:0b:12\",\n      \"created_at\": \"2017-01-03T09:42:54Z\",\n      \"updated_at\": \"2017-01-03T09:42:54Z\",\n      \"owner\": {\n        \"href\": \"/users/ad711bc3-6333-449a-a405-23ca81f38c00\"\n      },\n      \"href\": \"/ssh-keys/bba63e41-b12c-493a-81d4-e52f50f247ed\"\n    },\n    {\n      \"id\": \"bba63e41-b12c-493a-81d4-e52f50f247e2\",\n      \"label\": \"test\",\n      \"key\": \"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDNnvPZ25wZK19grrbal6R5JP1hLRBUuNh86KxZVMAFkGd5ouVSgO9dFajHZ45Q4mbaTkdOiqf7otMLDzkaztEa7oLK7Jso0Y0LOi+nT4gf38rvbEF5mq069G9b9XqlNleaGnpLuTN54iEK8c4TWZxIJqgelHEHhjp7V1asmilBbpZDmwA5cTt9vGJIhqA/BptKH3folZKeAQjRa1ZRSwSQUnk9rBKn4PKSRDojVa9A9jKt4qboJh5q7ZjtE8z+665F/4TgLzElTXUA8+uUFGpuynMSmQEt301e18dXAl+vBr8fMiThcoVVbdVdqdjXsw75fMXPAgqhjrw8k3+0/4P9 andrea@bigmac.local\",\n      \"fingerprint\": \"88:8a:7d:0f:db:fb:f4:2a:63:2e:d3:4b:1f:7f:0b:12\",\n      \"created_at\": \"2017-01-03T09:42:54Z\",\n      \"updated_at\": \"2017-01-03T09:42:54Z\",\n      \"owner\": {\n        \"href\": \"/users/ad711bc3-6333-449a-a405-23ca81f38c00\"\n      },\n      \"href\": \"/ssh-keys/bba63e41-b12c-493a-81d4-e52f50f247ed\"\n    },\n    {\n      \"id\": \"bba63e41-b12c-493a-81d4-e52f50f247e3\",\n      \"label\": \"test\",\n      \"key\": \"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDNnvPZ25wZK19grrbal6R5JP1hLRBUuNh86KxZVMAFkGd5ouVSgO9dFajHZ45Q4mbaTkdOiqf7otMLDzkaztEa7oLK7Jso0Y0LOi+nT4gf38rvbEF5mq069G9b9XqlNleaGnpLuTN54iEK8c4TWZxIJqgelHEHhjp7V1asmilBbpZDmwA5cTt9vGJIhqA/BptKH3folZKeAQjRa1ZRSwSQUnk9rBKn4PKSRDojVa9A9jKt4qboJh5q7ZjtE8z+665F/4TgLzElTXUA8+uUFGpuynMSmQEt301e18dXAl+vBr8fMiThcoVVbdVdqdjXsw75fMXPAgqhjrw8k3+0/4P9 andrea@bigmac.local\",\n      \"fingerprint\": \"88:8a:7d:0f:db:fb:f4:2a:63:2e:d3:4b:1f:7f:0b:12\",\n      \"created_at\": \"2017-01-03T09:42:54Z\",\n      \"updated_at\": \"2017-01-03T09:42:54Z\",\n      \"owner\": {\n        \"href\": \"/users/ad711bc3-6333-449a-a405-23ca81f38c00\"\n      },\n      \"href\": \"/ssh-keys/bba63e41-b12c-493a-81d4-e52f50f247ed\"\n    },\n    {\n      \"id\": \"bba63e41-b12c-493a-81d4-e52f50f247e4\",\n      \"label\": \"test\",\n      \"key\": \"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDNnvPZ25wZK19grrbal6R5JP1hLRBUuNh86KxZVMAFkGd5ouVSgO9dFajHZ45Q4mbaTkdOiqf7otMLDzkaztEa7oLK7Jso0Y0LOi+nT4gf38rvbEF5mq069G9b9XqlNleaGnpLuTN54iEK8c4TWZxIJqgelHEHhjp7V1asmilBbpZDmwA5cTt9vGJIhqA/BptKH3folZKeAQjRa1ZRSwSQUnk9rBKn4PKSRDojVa9A9jKt4qboJh5q7ZjtE8z+665F/4TgLzElTXUA8+uUFGpuynMSmQEt301e18dXAl+vBr8fMiThcoVVbdVdqdjXsw75fMXPAgqhjrw8k3+0/4P9 andrea@bigmac.local\",\n      \"fingerprint\": \"88:8a:7d:0f:db:fb:f4:2a:63:2e:d3:4b:1f:7f:0b:12\",\n      \"created_at\": \"2017-01-03T09:42:54Z\",\n      \"updated_at\": \"2017-01-03T09:42:54Z\",\n      \"owner\": {\n        \"href\": \"/users/ad711bc3-6333-449a-a405-23ca81f38c00\"\n      },\n      \"href\": \"/ssh-keys/bba63e41-b12c-493a-81d4-e52f50f247ed\"\n    },\n    {\n      \"id\": \"bba63e41-b12c-493a-81d4-e52f50f247e5\",\n      \"label\": \"test\",\n      \"key\": \"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDNnvPZ25wZK19grrbal6R5JP1hLRBUuNh86KxZVMAFkGd5ouVSgO9dFajHZ45Q4mbaTkdOiqf7otMLDzkaztEa7oLK7Jso0Y0LOi+nT4gf38rvbEF5mq069G9b9XqlNleaGnpLuTN54iEK8c4TWZxIJqgelHEHhjp7V1asmilBbpZDmwA5cTt9vGJIhqA/BptKH3folZKeAQjRa1ZRSwSQUnk9rBKn4PKSRDojVa9A9jKt4qboJh5q7ZjtE8z+665F/4TgLzElTXUA8+uUFGpuynMSmQEt301e18dXAl+vBr8fMiThcoVVbdVdqdjXsw75fMXPAgqhjrw8k3+0/4P9 andrea@bigmac.local\",\n      \"fingerprint\": \"88:8a:7d:0f:db:fb:f4:2a:63:2e:d3:4b:1f:7f:0b:12\",\n      \"created_at\": \"2017-01-03T09:42:54Z\",\n      \"updated_at\": \"2017-01-03T09:42:54Z\",\n      \"owner\": {\n        \"href\": \"/users/ad711bc3-6333-449a-a405-23ca81f38c00\"\n      },\n      \"href\": \"/ssh-keys/bba63e41-b12c-493a-81d4-e52f50f247ed\"\n    }\n  ],\n  \"meta\": {\n    \"first\": {\n      \"href\": \"/ssh-keys?page=1\"\n    },\n    \"previous\": null,\n    \"self\": {\n      \"href\": \"/ssh-keys?page=1\"\n    },\n    \"next\": {\n      \"href\": \"/ssh-keys?page=2\"\n    },\n    \"last\": {\n      \"href\": \"/ssh-keys?page=2\"\n    },\n    \"total\": 8\n  }\n}\n"
  },
  {
    "path": "providers/packet/src/test/resources/sshKeys-last.json",
    "content": "{\n  \"ssh_keys\": [\n    {\n      \"id\": \"bba63e41-b12c-493a-81d4-e52f50f247e6\",\n      \"label\": \"test\",\n      \"key\": \"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDNnvPZ25wZK19grrbal6R5JP1hLRBUuNh86KxZVMAFkGd5ouVSgO9dFajHZ45Q4mbaTkdOiqf7otMLDzkaztEa7oLK7Jso0Y0LOi+nT4gf38rvbEF5mq069G9b9XqlNleaGnpLuTN54iEK8c4TWZxIJqgelHEHhjp7V1asmilBbpZDmwA5cTt9vGJIhqA/BptKH3folZKeAQjRa1ZRSwSQUnk9rBKn4PKSRDojVa9A9jKt4qboJh5q7ZjtE8z+665F/4TgLzElTXUA8+uUFGpuynMSmQEt301e18dXAl+vBr8fMiThcoVVbdVdqdjXsw75fMXPAgqhjrw8k3+0/4P9 andrea@bigmac.local\",\n      \"fingerprint\": \"88:8a:7d:0f:db:fb:f4:2a:63:2e:d3:4b:1f:7f:0b:12\",\n      \"created_at\": \"2017-01-03T09:42:54Z\",\n      \"updated_at\": \"2017-01-03T09:42:54Z\",\n      \"owner\": {\n        \"href\": \"/users/ad711bc3-6333-449a-a405-23ca81f38c00\"\n      },\n      \"href\": \"/ssh-keys/bba63e41-b12c-493a-81d4-e52f50f247ed\"\n    },\n    {\n      \"id\": \"bba63e41-b12c-493a-81d4-e52f50f247e7\",\n      \"label\": \"test\",\n      \"key\": \"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDNnvPZ25wZK19grrbal6R5JP1hLRBUuNh86KxZVMAFkGd5ouVSgO9dFajHZ45Q4mbaTkdOiqf7otMLDzkaztEa7oLK7Jso0Y0LOi+nT4gf38rvbEF5mq069G9b9XqlNleaGnpLuTN54iEK8c4TWZxIJqgelHEHhjp7V1asmilBbpZDmwA5cTt9vGJIhqA/BptKH3folZKeAQjRa1ZRSwSQUnk9rBKn4PKSRDojVa9A9jKt4qboJh5q7ZjtE8z+665F/4TgLzElTXUA8+uUFGpuynMSmQEt301e18dXAl+vBr8fMiThcoVVbdVdqdjXsw75fMXPAgqhjrw8k3+0/4P9 andrea@bigmac.local\",\n      \"fingerprint\": \"88:8a:7d:0f:db:fb:f4:2a:63:2e:d3:4b:1f:7f:0b:12\",\n      \"created_at\": \"2017-01-03T09:42:54Z\",\n      \"updated_at\": \"2017-01-03T09:42:54Z\",\n      \"owner\": {\n        \"href\": \"/users/ad711bc3-6333-449a-a405-23ca81f38c00\"\n      },\n      \"href\": \"/ssh-keys/bba63e41-b12c-493a-81d4-e52f50f247ed\"\n    },\n    {\n      \"id\": \"bba63e41-b12c-493a-81d4-e52f50f247e8\",\n      \"label\": \"test\",\n      \"key\": \"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDNnvPZ25wZK19grrbal6R5JP1hLRBUuNh86KxZVMAFkGd5ouVSgO9dFajHZ45Q4mbaTkdOiqf7otMLDzkaztEa7oLK7Jso0Y0LOi+nT4gf38rvbEF5mq069G9b9XqlNleaGnpLuTN54iEK8c4TWZxIJqgelHEHhjp7V1asmilBbpZDmwA5cTt9vGJIhqA/BptKH3folZKeAQjRa1ZRSwSQUnk9rBKn4PKSRDojVa9A9jKt4qboJh5q7ZjtE8z+665F/4TgLzElTXUA8+uUFGpuynMSmQEt301e18dXAl+vBr8fMiThcoVVbdVdqdjXsw75fMXPAgqhjrw8k3+0/4P9 andrea@bigmac.local\",\n      \"fingerprint\": \"88:8a:7d:0f:db:fb:f4:2a:63:2e:d3:4b:1f:7f:0b:12\",\n      \"created_at\": \"2017-01-03T09:42:54Z\",\n      \"updated_at\": \"2017-01-03T09:42:54Z\",\n      \"owner\": {\n        \"href\": \"/users/ad711bc3-6333-449a-a405-23ca81f38c00\"\n      },\n      \"href\": \"/ssh-keys/bba63e41-b12c-493a-81d4-e52f50f247ed\"\n    }\n  ],\n  \"meta\": {\n    \"first\": {\n      \"href\": \"/ssh-keys?page=1\"\n    },\n    \"previous\": {\n      \"href\": \"/ssh-keys?page=1\"\n    },\n    \"self\": {\n      \"href\": \"/ssh-keys?page=2\"\n    },\n    \"next\": null,\n    \"last\": {\n      \"href\": \"/ssh-keys?page=2\"\n    },\n    \"total\": 8\n  }\n}\n"
  },
  {
    "path": "providers/packet/src/test/resources/sshKeys.json",
    "content": "{\n  \"ssh_keys\": [\n    {\n      \"id\": \"bba63e41-b12c-493a-81d4-e52f50f247ed\",\n      \"label\": \"test\",\n      \"key\": \"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDNnvPZ25wZK19grrbal6R5JP1hLRBUuNh86KxZVMAFkGd5ouVSgO9dFajHZ45Q4mbaTkdOiqf7otMLDzkaztEa7oLK7Jso0Y0LOi+nT4gf38rvbEF5mq069G9b9XqlNleaGnpLuTN54iEK8c4TWZxIJqgelHEHhjp7V1asmilBbpZDmwA5cTt9vGJIhqA/BptKH3folZKeAQjRa1ZRSwSQUnk9rBKn4PKSRDojVa9A9jKt4qboJh5q7ZjtE8z+665F/4TgLzElTXUA8+uUFGpuynMSmQEt301e18dXAl+vBr8fMiThcoVVbdVdqdjXsw75fMXPAgqhjrw8k3+0/4P9 andrea@bigmac.local\",\n      \"fingerprint\": \"88:8a:7d:0f:db:fb:f4:2a:63:2e:d3:4b:1f:7f:0b:12\",\n      \"created_at\": \"2017-01-03T09:42:54Z\",\n      \"updated_at\": \"2017-01-03T09:42:54Z\",\n      \"owner\": {\n        \"href\": \"/users/ad711bc3-6333-449a-a405-23ca81f38c00\"\n      },\n      \"href\": \"/ssh-keys/bba63e41-b12c-493a-81d4-e52f50f247ed\"\n    }\n  ]\n}\n"
  },
  {
    "path": "providers/packet/src/test/resources/user.json",
    "content": "{\n  \"id\": \"faaaec30-be0c-4b6d-b1a7-1bf6e494a333\",\n  \"first_name\": \"Melissa\",\n  \"last_name\": \"Smith\",\n  \"full_name\": \"Melissa Smith\",\n  \"email\": \"melissa@example.com\",\n  \"max_projects\": 1,\n  \"two_factor_auth\": \"sms\",\n  \"timezone\": \"America/New_York\",\n  \"phone_number\": \"555-555-5555\",\n  \"created_at\": \"2014-04-14T02:15:15Z\",\n  \"updated_at\": \"2014-04-14T02:15:15Z\",\n  \"timezone\": \"America/New_York\",\n  \"emails\": [\n    { \"href\": \"/emails/7e407a6a-4f96-4da0-8c48-5665352ebf06\" }\n  ],\n  \"avatar_url\": \"https://www.gravatar.com/avatar/d248bbb3a03ed?d=https://app.packet.net/client-portal/assets/images/default_gravatar.png\",\n  \"href\": \"/users/faaaec30-be0c-4b6d-b1a7-1bf6e494a333\"\n}\n"
  },
  {
    "path": "providers/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <artifactId>jclouds-project</artifactId>\n    <groupId>org.apache.jclouds</groupId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.provider</groupId>\n  <artifactId>jclouds-providers-project</artifactId>\n  <packaging>pom</packaging>\n  <name>jclouds providers project</name>\n  <modules>\n    <module>aws-cloudwatch</module>\n    <module>aws-ec2</module>\n    <module>aws-route53</module>\n    <module>aws-s3</module>\n    <module>aws-sqs</module>\n    <module>aws-sts</module>\n    <module>azureblob</module>\n    <module>azurecompute-arm</module>\n    <module>b2</module>\n    <module>digitalocean2</module>\n    <module>dynect</module>\n    <module>elastichosts-ams-e</module>\n    <module>elastichosts-dal-a</module>\n    <module>elastichosts-hkg-e</module>\n    <module>elastichosts-lax-p</module>\n    <module>elastichosts-lon-b</module>\n    <module>elastichosts-lon-p</module>\n    <module>elastichosts-mmi-a</module>\n    <module>elastichosts-sat-p</module>\n    <module>elastichosts-sjc-c</module>\n    <module>elastichosts-syd-v</module>\n    <module>elastichosts-tor-p</module>\n    <module>glesys</module>\n    <module>go2cloud-jhb1</module>\n    <module>gogrid</module>\n    <module>google-cloud-storage</module>\n    <module>google-compute-engine</module>\n    <module>openhosting-east1</module>\n    <module>packet</module>\n    <module>profitbricks</module>\n    <module>rackspace-cloudblockstorage-uk</module>\n    <module>rackspace-cloudblockstorage-us</module>\n    <module>rackspace-clouddatabases-uk</module>\n    <module>rackspace-clouddatabases-us</module>\n    <module>rackspace-clouddns-uk</module>\n    <module>rackspace-clouddns-us</module>\n    <module>rackspace-cloudfiles-uk</module>\n    <module>rackspace-cloudfiles-us</module>\n    <module>rackspace-cloudloadbalancers-uk</module>\n    <module>rackspace-cloudloadbalancers-us</module>\n    <module>rackspace-cloudnetworks-uk</module>\n    <module>rackspace-cloudnetworks-us</module>\n    <module>rackspace-cloudservers-uk</module>\n    <module>rackspace-cloudservers-us</module>\n    <module>serverlove-z1-man</module>\n    <module>skalicloud-sdg-my</module>\n    <module>softlayer</module>\n    <module>ultradns-ws</module>\n  </modules>\n</project>\n"
  },
  {
    "path": "providers/profitbricks/README.md",
    "content": "# jclouds ProfitBricks\n\n## Terms\nLike any cloud provider, ProfitBricks has its own set of terms in cloud computing. To abstract this into jclouds' Compute interface, these terms were associated:\n\n- Node - composite instance of `Server` and `Storage`\n- Image - both *user-uploaded* and *provided* `Images`; and `Snapshots`\n- Location - `DataCenters` and `Region` (Las Vegas, Frankfurt, etc.)\n- Hardware - number of cores, RAM size and storage size\n\n## Getting Started\n\n```java\nComputeService compute = ContextBuilder.newBuilder( \"profitbricks\" )\n\t\t\t\t\t.credentials( \"profitbricks email\", \"password\" )\n\t\t\t\t\t.buildView( ComputeServiceContext.class )\n\t\t\t\t\t.getComputeService();\n```\n\n\nThis works well; however, we won't be able to use jclouds' ability to execute *scripts* on a remote node. This is because, ProfitBricks' default images require users to change passwords upon first log in.\n\nTo enable jclouds to execute script, we need to use a custom image. The easiest way to do this is via ProfitBricks snapshot:\n\n-  Go to your [DCD](https://my.profitbricks.com/dashboard/).\n-  Provision a server + storage, and connect it to the internet. Upon success, you will receive an email containing the credentials needed to login to your server.\n-  Login to your server, and change the password, as requested.\n\n```\n~ ssh root@<remote-ip>\n...\nChanging password for root.\n(current) UNIX password: \nEnter new UNIX password: \nRetype new UNIX password: \n~ root@ubuntu:~# exit\n\n```\n\n- Go back to the DCD, and *make a snapshot* of the storage. Put a descriptive name.\n- Configure jclouds to use this *snapshot*.\n\n```java \nTemplate template = compute.templateBuilder()\n\t.imageNameMatches( \"<ideally-unique-snapshot-name>\" )\n\t.options( compute.templateOptions()\n\t\t\t\t.overrideLoginUser( \"root\" ) // unless you changed the user\n\t\t\t\t.overrideLoginPassword( \"<changed-password>\" ))\n\t// more options, as you need\n\t.build();\n\t\ncompute.createNodesInGroup( \"cluster1\", 1, template );\n```\n\n## Limitations\n\n- There's no direct way of specifying arbitrary number of cores, RAM size, and storage size via the compute interface, at least until after [JCLOUDS-482](https://issues.apache.org/jira/browse/JCLOUDS-482) is resolved. The adapter uses a predefined list hardware profiles instead.\n\n> Take note that these features are still accessible by *unwraping* the ProfitBricks API, but this'll reduce portability of your code. See [Concepts](https://jclouds.apache.org/start/concepts/).\n"
  },
  {
    "path": "providers/profitbricks/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.profitbricks.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "providers/profitbricks/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n    <modelVersion>4.0.0</modelVersion>\n    <parent>\n        <groupId>org.apache.jclouds</groupId>\n        <artifactId>jclouds-project</artifactId>\n        <version>2.7.1-SNAPSHOT</version>\n        <relativePath>../../project/pom.xml</relativePath>\n    </parent>\n  \n    <groupId>org.apache.jclouds.provider</groupId>\n    <artifactId>profitbricks</artifactId>\n    <name>jclouds ProfitBricks api</name>\n    <description>jclouds components to access an implementation of ProfitBricks</description>\n\n    <properties>\n        <test.profitbricks.endpoint>https://api.profitbricks.com/1.3</test.profitbricks.endpoint>\n        <test.profitbricks.identity>FIXME</test.profitbricks.identity>\n        <test.profitbricks.credential>FIXME</test.profitbricks.credential>\n        <test.profitbricks.api-version>1.3</test.profitbricks.api-version>\n    </properties>\n  \n    <dependencies>\n        <dependency>\n            <groupId>org.apache.jclouds</groupId>\n            <artifactId>jclouds-core</artifactId>\n            <version>${project.version}</version>\n        </dependency>\n        <dependency>\n            <groupId>org.apache.jclouds</groupId>\n            <artifactId>jclouds-compute</artifactId>\n            <version>${project.version}</version>\n        </dependency>\n        <dependency>\n            <groupId>com.google.auto.service</groupId>\n            <artifactId>auto-service</artifactId>\n            <scope>provided</scope>\n            <optional>true</optional>\n        </dependency>\n        <dependency>\n            <groupId>com.google.auto.value</groupId>\n            <artifactId>auto-value</artifactId>\n            <scope>provided</scope>\n        </dependency>\n        <!-- Test dependencies -->\n        <dependency>\n            <groupId>org.apache.jclouds</groupId>\n            <artifactId>jclouds-core</artifactId>\n            <version>${project.version}</version>\n            <type>test-jar</type>\n            <scope>test</scope>\n        </dependency>\n        <dependency>\n            <groupId>org.apache.jclouds</groupId>\n            <artifactId>jclouds-compute</artifactId>\n            <version>${project.version}</version>\n            <type>test-jar</type>\n            <scope>test</scope>\n        </dependency>\n        <dependency>\n            <groupId>org.apache.jclouds.driver</groupId>\n            <artifactId>jclouds-sshj</artifactId>\n            <version>${project.version}</version>\n            <scope>test</scope>\n        </dependency>\n        <dependency>\n            <groupId>com.squareup.okhttp3</groupId>\n            <artifactId>mockwebserver</artifactId>\n            <scope>test</scope>\n        </dependency>\n        <dependency>\n            <groupId>org.apache.jclouds.driver</groupId>\n            <artifactId>jclouds-slf4j</artifactId>\n            <version>${project.version}</version>\n            <scope>test</scope>\n        </dependency>\n        <dependency>\n            <groupId>ch.qos.logback</groupId>\n            <artifactId>logback-core</artifactId>\n            <scope>test</scope>\n        </dependency>\n        <dependency>\n            <groupId>ch.qos.logback</groupId>\n            <artifactId>logback-classic</artifactId>\n            <scope>test</scope>\n        </dependency>\n    </dependencies>\n  \n    <profiles>\n        <profile>\n            <id>live</id>\n            <build>\n                <plugins>\n                    <plugin>\n                        <groupId>org.apache.maven.plugins</groupId>\n                        <artifactId>maven-surefire-plugin</artifactId>\n                        <executions>\n                            <execution>\n                                <id>integration</id>\n                                <phase>integration-test</phase>\n                                <goals>\n                                    <goal>test</goal>\n                                </goals>\n                                <configuration>\n                                    <threadCount>1</threadCount>\n                                    <systemPropertyVariables>\n                                        <test.profitbricks.endpoint>${test.profitbricks.endpoint}</test.profitbricks.endpoint>\n                                        <test.profitbricks.identity>${test.profitbricks.identity}</test.profitbricks.identity>\n                                        <test.profitbricks.credential>${test.profitbricks.credential}</test.profitbricks.credential>\n                                        <test.profitbricks.api-version>${test.profitbricks.api-version}</test.profitbricks.api-version>\n                                        <test.profitbricks.template>${test.profitbricks.template}</test.profitbricks.template>\n                                    </systemPropertyVariables>\n                                </configuration>\n                            </execution>\n                        </executions>\n                    </plugin>\n                </plugins>\n            </build>\n        </profile>\n    </profiles>\n</project>\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/ProfitBricksApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks;\n\nimport java.io.Closeable;\nimport org.jclouds.profitbricks.features.DataCenterApi;\nimport org.jclouds.profitbricks.features.DrivesApi;\nimport org.jclouds.profitbricks.features.FirewallApi;\nimport org.jclouds.profitbricks.features.ImageApi;\n\nimport org.jclouds.profitbricks.features.IpBlockApi;\nimport org.jclouds.profitbricks.features.LoadBalancerApi;\nimport org.jclouds.profitbricks.features.NicApi;\nimport org.jclouds.profitbricks.features.ServerApi;\nimport org.jclouds.profitbricks.features.SnapshotApi;\nimport org.jclouds.profitbricks.features.StorageApi;\nimport org.jclouds.rest.annotations.Delegate;\n\npublic interface ProfitBricksApi extends Closeable {\n\n   @Delegate\n   DataCenterApi dataCenterApi();\n\n   @Delegate\n   ImageApi imageApi();\n\n   @Delegate\n   ServerApi serverApi();\n\n   @Delegate\n   StorageApi storageApi();\n\n   @Delegate\n   NicApi nicApi();\n\n   @Delegate\n   FirewallApi firewallApi();\n\n   @Delegate\n   SnapshotApi snapshotApi();\n\n   @Delegate\n   IpBlockApi ipBlockApi();\n\n   @Delegate\n   DrivesApi drivesApi();\n\n   @Delegate\n   LoadBalancerApi loadBalancerApi();\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/ProfitBricksApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.profitbricks.compute.config.ProfitBricksComputeServiceContextModule;\nimport org.jclouds.profitbricks.config.ProfitBricksHttpApiModule;\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.profitbricks.config.ProfitBricksHttpApiModule.ProfitBricksHttpCommandExecutorServiceModule;\nimport org.jclouds.rest.internal.BaseHttpApiMetadata;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n/**\n * Implementation of {@link ApiMetadata} for ProfitBricks API.\n */\npublic class ProfitBricksApiMetadata extends BaseHttpApiMetadata<ProfitBricksApi> {\n\n   public ProfitBricksApiMetadata() {\n      this(new Builder());\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return new Builder().fromApiMetadata(this);\n   }\n\n   protected ProfitBricksApiMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = BaseHttpApiMetadata.defaultProperties();\n      return properties;\n   }\n\n   public static class Builder extends BaseHttpApiMetadata.Builder<ProfitBricksApi, Builder> {\n\n      protected Builder() {\n         id(\"profitbricks\")\n                 .name(\"ProfitBricks API\")\n                 .identityName(\"API Username\")\n                 .credentialName(\"API Password\")\n                 .documentation(URI.create(\"https://www.profitbricks.com/sites/default/files/profitbricks_api_1_3.pdf\"))\n                 .defaultEndpoint(\"https://api.profitbricks.com/1.3\")\n                 .version(\"1.3\")\n                 .view(ComputeServiceContext.class)\n                 .defaultProperties(ProfitBricksApiMetadata.defaultProperties())\n                 .defaultModules(ImmutableSet.<Class<? extends Module>>of(\n                                 ProfitBricksHttpApiModule.class,\n                                 ProfitBricksHttpCommandExecutorServiceModule.class,\n                                 ProfitBricksComputeServiceContextModule.class\n                         ));\n      }\n\n      @Override\n      public ProfitBricksApiMetadata build() {\n         return new ProfitBricksApiMetadata(this);\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/ProfitBricksProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks;\n\nimport static org.jclouds.Constants.PROPERTY_ISO3166_CODES;\nimport static org.jclouds.Constants.PROPERTY_SO_TIMEOUT;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_RUNNING;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_SUSPENDED;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_TERMINATED;\nimport static org.jclouds.location.reference.LocationConstants.ISO3166_CODES;\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_REGION;\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_REGIONS;\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_ZONE;\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_ZONES;\nimport static org.jclouds.profitbricks.config.ProfitBricksComputeProperties.POLL_INITIAL_PERIOD;\nimport static org.jclouds.profitbricks.config.ProfitBricksComputeProperties.POLL_MAX_PERIOD;\nimport static org.jclouds.profitbricks.config.ProfitBricksComputeProperties.TIMEOUT_DATACENTER_AVAILABLE;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\n\nimport com.google.auto.service.AutoService;\n\n@AutoService(ProviderMetadata.class)\npublic class ProfitBricksProviderMetadata extends BaseProviderMetadata {\n\n   public ProfitBricksProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public ProfitBricksProviderMetadata() {\n      super(builder());\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromProviderMetadata(this);\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = ProfitBricksApiMetadata.defaultProperties();\n      \n      properties.setProperty(PROPERTY_REGIONS, \"de,us\");\n      properties.setProperty(PROPERTY_REGION + \".de.zones\", \"de/fkb,de/fra\");\n      properties.setProperty(PROPERTY_REGION + \".us.zones\", \"us/las,us/lasdev\");\n      properties.setProperty(PROPERTY_ZONES, \"de/fkb,de/fra,us/las,us/lasdev\");\n      properties.setProperty(PROPERTY_ISO3166_CODES, \"DE-BW,DE-HE,US_NV\");\n      properties.setProperty(PROPERTY_REGION + \".de.\" + ISO3166_CODES, \"DE-BW,DE-HE\");\n      properties.setProperty(PROPERTY_REGION + \".us.\" + ISO3166_CODES, \"US-NV\");\n      properties.setProperty(PROPERTY_ZONE + \".de/fkb.\" + ISO3166_CODES, \"DE-BW\");\n      properties.setProperty(PROPERTY_ZONE + \".de/fra.\" + ISO3166_CODES, \"DE-HE\");\n      properties.setProperty(PROPERTY_ZONE + \".us/las.\" + ISO3166_CODES, \"US-NV\");\n      properties.setProperty(PROPERTY_ZONE + \".us/lasdebv.\" + ISO3166_CODES, \"US-NV\");\n      \n      properties.put(TIMEOUT_DATACENTER_AVAILABLE, 30L * 60L); // 30 minutes\n      properties.put(POLL_INITIAL_PERIOD, 5L);\n      properties.put(POLL_MAX_PERIOD, 60L);\n\n      properties.put(\"jclouds.ssh.max-retries\", \"7\");\n      properties.put(\"jclouds.ssh.retry-auth\", \"true\");\n      \n      properties.put(PROPERTY_SO_TIMEOUT, 10 * 60 * 1000);\n\n      // Node might still not be available even after DataCenter is done provisioning\n      // Use 5-minute timeout by default\n      properties.put(TIMEOUT_NODE_RUNNING, 5 * 60 * 1000);\n      properties.put(TIMEOUT_NODE_SUSPENDED, 5 * 60 * 1000);\n      properties.put(TIMEOUT_NODE_TERMINATED, 5 * 60 * 1000);\n\n      return properties;\n   }\n\n   public static class Builder extends BaseProviderMetadata.Builder {\n\n      protected Builder() {\n         id(\"profitbricks\")\n                 .name(\"ProfitBricks Cloud Compute 2.0\")\n                 .homepage(URI.create(\"http://www.profitbricks.com\"))\n                 .console(URI.create(\"https://my.profitbricks.com/dashboard/dcdr2/\"))\n                 .iso3166Codes(\"DE-BW\", \"DE-HE\", \"US-NV\")\n                 .linkedServices(\"profitbricks\")\n                 .apiMetadata(new ProfitBricksApiMetadata())\n                 .defaultProperties(ProfitBricksProviderMetadata.defaultProperties());\n      }\n\n      @Override\n      public ProfitBricksProviderMetadata build() {\n         return new ProfitBricksProviderMetadata(this);\n      }\n\n      @Override\n      public Builder fromProviderMetadata(ProviderMetadata in) {\n         super.fromProviderMetadata(in);\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/binder/BaseProfitBricksRequestBinder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.binder;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\n\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.MapBinder;\n\nimport com.google.common.base.Strings;\n\nimport org.jclouds.io.MutableContentMetadata;\nimport org.jclouds.io.payloads.BaseMutableContentMetadata;\n\npublic abstract class BaseProfitBricksRequestBinder<T> implements MapBinder {\n\n   protected final String paramName;\n\n   protected BaseProfitBricksRequestBinder(String paramName) {\n      this.paramName = checkNotNull(paramName, \"Initialize 'paramName' in constructor\");\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      checkNotNull(request, \"request\");\n\n      Object obj = checkNotNull(postParams.get(paramName), \"Param '%s' cannot be null.\", paramName);\n      T payload = (T) obj;\n\n      return createRequest(request, createPayload(payload));\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      throw new UnsupportedOperationException(\"Not supported yet.\");\n   }\n\n   protected abstract String createPayload(T payload);\n\n   protected static String formatIfNotEmpty(String pattern, Object param) {\n      return Strings.isNullOrEmpty(nullableToString(param)) ? \"\" : String.format(pattern, param);\n   }\n\n   protected static String nullableToString(Object object) {\n      return object == null ? \"\" : object.toString();\n   }\n\n   protected <R extends HttpRequest> R createRequest(R fromRequest, String payload) {\n      MutableContentMetadata metadata = new BaseMutableContentMetadata();\n      metadata.setContentType(MediaType.TEXT_XML);\n      metadata.setContentLength(Long.valueOf(payload.getBytes().length));\n\n      fromRequest.setPayload(payload);\n      fromRequest.getPayload().setContentMetadata(metadata);\n      return fromRequest;\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/binder/datacenter/CreateDataCenterRequestBinder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.binder.datacenter;\n\nimport static java.lang.String.format;\n\nimport org.jclouds.profitbricks.binder.BaseProfitBricksRequestBinder;\nimport org.jclouds.profitbricks.domain.DataCenter;\n\npublic class CreateDataCenterRequestBinder extends BaseProfitBricksRequestBinder<DataCenter.Request.CreatePayload> {\n\n   protected final StringBuilder requestBuilder;\n\n   CreateDataCenterRequestBinder() {\n      super(\"dataCenter\");\n      this.requestBuilder = new StringBuilder(128);\n   }\n\n   @Override\n   protected String createPayload(DataCenter.Request.CreatePayload payload) {\n      requestBuilder.append(\"<ws:createDataCenter>\")\n              .append(\"<request>\")\n              .append(format(\"<dataCenterName>%s</dataCenterName>\", payload.name()))\n              .append(format(\"<location>%s</location>\", payload.location().getId()))\n              .append(\"</request>\")\n              .append(\"</ws:createDataCenter>\");\n      return requestBuilder.toString();\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/binder/datacenter/UpdateDataCenterRequestBinder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.binder.datacenter;\n\nimport static java.lang.String.format;\n\nimport org.jclouds.profitbricks.binder.BaseProfitBricksRequestBinder;\nimport org.jclouds.profitbricks.domain.DataCenter;\n\npublic class UpdateDataCenterRequestBinder extends BaseProfitBricksRequestBinder<DataCenter.Request.UpdatePayload> {\n\n   protected final StringBuilder requestBuilder;\n\n   UpdateDataCenterRequestBinder() {\n      super(\"dataCenter\");\n      this.requestBuilder = new StringBuilder(128);\n   }\n\n   @Override\n   protected String createPayload(DataCenter.Request.UpdatePayload payload) {\n      requestBuilder.append(\"<ws:updateDataCenter>\")\n              .append(\"<request>\")\n              .append(format(\"<dataCenterId>%s</dataCenterId>\", payload.id()))\n              .append(format(\"<dataCenterName>%s</dataCenterName>\", payload.name()))\n              .append(\"</request>\")\n              .append(\"</ws:updateDataCenter>\");\n      return requestBuilder.toString();\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/binder/drive/AddRomDriveToServerRequestBinder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.binder.drive;\n\nimport static java.lang.String.format;\nimport org.jclouds.profitbricks.binder.BaseProfitBricksRequestBinder;\nimport org.jclouds.profitbricks.domain.Drive;\n\npublic class AddRomDriveToServerRequestBinder extends BaseProfitBricksRequestBinder<Drive.Request.AddRomDriveToServerPayload> {\n\n   private final StringBuilder requestBuilder;\n\n   AddRomDriveToServerRequestBinder() {\n      super(\"payload\");\n      this.requestBuilder = new StringBuilder(128);\n   }\n\n   @Override\n   protected String createPayload(Drive.Request.AddRomDriveToServerPayload payload) {\n      requestBuilder.append(\"<ws:addRomDriveToServer>\")\n              .append(\"<request>\")\n              .append(format(\"<imageId>%s</imageId>\", payload.imageId()))\n              .append(format(\"<serverId>%s</serverId>\", payload.serverId()))\n              .append(formatIfNotEmpty(\"<deviceNumber>%s</deviceNumber>\", payload.deviceNumber()))\n              .append(\"</request>\")\n              .append(\"</ws:addRomDriveToServer>\");\n\n      return requestBuilder.toString();\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/binder/firewall/AddFirewallRuleToNicRequestBinder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.binder.firewall;\n\nimport org.jclouds.profitbricks.binder.BaseProfitBricksRequestBinder;\nimport org.jclouds.profitbricks.domain.Firewall;\nimport static java.lang.String.format;\n\npublic class AddFirewallRuleToNicRequestBinder extends BaseProfitBricksRequestBinder<Firewall.Request.AddRulePayload> {\n\n   private final StringBuilder requestBuilder;\n\n   AddFirewallRuleToNicRequestBinder() {\n      super(\"firewall\");\n      this.requestBuilder = new StringBuilder(128);\n   }\n\n   @Override\n   protected String createPayload(Firewall.Request.AddRulePayload payload) {\n      requestBuilder.append(\"<ws:addFirewallRulesToNic>\")\n              .append(format(\"<nicId>%s</nicId>\", payload.nicId()));\n      for (Firewall.Rule rule : payload.rules())\n         requestBuilder\n                 .append(\"<request>\")\n                 .append(formatIfNotEmpty(\"<icmpCode>%s</icmpCode>\", rule.icmpCode()))\n                 .append(formatIfNotEmpty(\"<icmpType>%s</icmpType>\", rule.icmpType()))\n                 .append(formatIfNotEmpty(\"<name>%s</name>\", rule.name()))\n                 .append(formatIfNotEmpty(\"<portRangeEnd>%s</portRangeEnd>\", rule.portRangeEnd()))\n                 .append(formatIfNotEmpty(\"<portRangeStart>%s</portRangeStart>\", rule.portRangeStart()))\n                 .append(formatIfNotEmpty(\"<protocol>%s</protocol>\", rule.protocol()))\n                 .append(formatIfNotEmpty(\"<sourceIp>%s</sourceIp>\", rule.sourceIp()))\n                 .append(formatIfNotEmpty(\"<sourceMac>%s</sourceMac>\", rule.sourceMac()))\n                 .append(formatIfNotEmpty(\"<targetIp>%s</targetIp>\", rule.targetIp()))\n                 .append(\"</request>\");\n      requestBuilder.append(\"</ws:addFirewallRulesToNic>\");\n      return requestBuilder.toString();\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/binder/firewall/FirewallBinder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.binder.firewall;\n\nimport static java.lang.String.format;\n\nimport java.util.List;\n\nimport org.jclouds.profitbricks.binder.BaseProfitBricksRequestBinder;\n\nimport com.google.common.base.Strings;\n\npublic abstract class FirewallBinder extends BaseProfitBricksRequestBinder<List<String>> {\n\n   protected final StringBuilder requestBuilder;\n\n   FirewallBinder() {\n      super(\"ids\");\n      this.requestBuilder = new StringBuilder(128);\n   }\n\n   protected void bindListWithTag(List<String> ids, String tag) {\n      if (ids == null || ids.isEmpty() || Strings.isNullOrEmpty(tag))\n         return;\n      for (String id : ids)\n         requestBuilder.append(format(\"<%s>%s</%s>\", tag, id, tag));\n   }\n\n   public static class ActivateFirewallRequestBinder extends FirewallBinder {\n\n      @Override\n      protected String createPayload(List<String> payload) {\n         requestBuilder.append(\"<ws:activateFirewalls>\");\n         bindListWithTag(payload, \"firewallIds\");\n         requestBuilder.append(\"</ws:activateFirewalls>\");\n\n         return requestBuilder.toString();\n      }\n\n   }\n\n   public static class DeactivateFirewallRequestBinder extends FirewallBinder {\n\n      @Override\n      protected String createPayload(List<String> payload) {\n         requestBuilder.append(\"<ws:deactivateFirewalls>\");\n         bindListWithTag(payload, \"firewallIds\");\n         requestBuilder.append(\"</ws:deactivateFirewalls>\");\n\n         return requestBuilder.toString();\n      }\n\n   }\n\n   public static class DeleteFirewallRequestBinder extends FirewallBinder {\n\n      @Override\n      protected String createPayload(List<String> payload) {\n         requestBuilder.append(\"<ws:deleteFirewalls>\");\n         bindListWithTag(payload, \"firewallIds\");\n         requestBuilder.append(\"</ws:deleteFirewalls>\");\n\n         return requestBuilder.toString();\n      }\n\n   }\n\n   public static class RemoveFirewallRuleRequestBinder extends FirewallBinder {\n\n      @Override\n      protected String createPayload(List<String> payload) {\n         requestBuilder.append(\"<ws:removeFirewallRules>\");\n         bindListWithTag(payload, \"firewallRuleIds\");\n         requestBuilder.append(\"</ws:removeFirewallRules>\");\n\n         return requestBuilder.toString();\n      }\n\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/binder/loadbalancer/CreateLoadBalancerRequestBinder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.binder.loadbalancer;\n\nimport org.jclouds.profitbricks.binder.BaseProfitBricksRequestBinder;\nimport org.jclouds.profitbricks.domain.LoadBalancer;\n\nimport static java.lang.String.format;\n\npublic class CreateLoadBalancerRequestBinder extends BaseProfitBricksRequestBinder<LoadBalancer.Request.CreatePayload> {\n\n   protected final StringBuilder requestBuilder;\n\n   CreateLoadBalancerRequestBinder() {\n      super(\"loadbalancer\");\n      this.requestBuilder = new StringBuilder(128 * 4);\n   }\n\n   @Override\n   protected String createPayload(LoadBalancer.Request.CreatePayload payload) {\n      requestBuilder.append(\"<ws:createLoadBalancer>\")\n              .append(\"<request>\")\n              .append(format(\"<dataCenterId>%s</dataCenterId>\", payload.dataCenterId()))\n              .append(format(\"<loadBalancerName>%s</loadBalancerName>\", payload.name()))\n              .append(format(\"<loadBalancerAlgorithm>%s</loadBalancerAlgorithm>\", payload.algorithm()))\n              .append(format(\"<ip>%s</ip>\", payload.ip()))\n              .append(format(\"<lanId>%s</lanId>\", payload.lanId()));\n      for (String serverId : payload.serverIds())\n         requestBuilder.append(format(\"<serverIds>%s</serverIds>\", serverId));\n      requestBuilder\n              .append(\"</request>\")\n              .append(\"</ws:createLoadBalancer>\");\n\n      return requestBuilder.toString();\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/binder/loadbalancer/DeregisterLoadBalancerRequestBinder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.binder.loadbalancer;\n\nimport static java.lang.String.format;\nimport org.jclouds.profitbricks.binder.BaseProfitBricksRequestBinder;\nimport org.jclouds.profitbricks.domain.LoadBalancer;\n\npublic class DeregisterLoadBalancerRequestBinder extends BaseProfitBricksRequestBinder<LoadBalancer.Request.DeregisterPayload> {\n\n   protected final StringBuilder requestBuilder;\n\n   DeregisterLoadBalancerRequestBinder() {\n      super(\"loadbalancer\");\n      this.requestBuilder = new StringBuilder(128 * 4);\n   }\n\n   @Override\n   protected String createPayload(LoadBalancer.Request.DeregisterPayload payload) {\n      requestBuilder.append(\"<ws:deregisterServersOnLoadBalancer>\");\n      for (String s : payload.serverIds())\n         requestBuilder.append(format(\"<serverIds>%s</serverIds>\", s));\n      requestBuilder.append(format(\"<loadBalancerId>%s</loadBalancerId>\", payload.id()))\n              .append(\"</ws:deregisterServersOnLoadBalancer>\");\n\n      return requestBuilder.toString();\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/binder/loadbalancer/RegisterLoadBalancerRequestBinder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.binder.loadbalancer;\n\nimport static java.lang.String.format;\nimport org.jclouds.profitbricks.binder.BaseProfitBricksRequestBinder;\nimport org.jclouds.profitbricks.domain.LoadBalancer;\n\npublic class RegisterLoadBalancerRequestBinder extends BaseProfitBricksRequestBinder<LoadBalancer.Request.RegisterPayload> {\n\n   protected final StringBuilder requestBuilder;\n\n   RegisterLoadBalancerRequestBinder() {\n      super(\"loadbalancer\");\n      this.requestBuilder = new StringBuilder(128 * 4);\n   }\n\n   @Override\n   protected String createPayload(LoadBalancer.Request.RegisterPayload payload) {\n      requestBuilder\n              .append(\"<ws:registerServersOnLoadBalancer>\")\n              .append(format(\"<loadBalancerId>%s</loadBalancerId>\", payload.id()));\n\n      for (String s : payload.serverIds())\n         requestBuilder.append(format(\"<serverIds>%s</serverIds>\", s));\n      requestBuilder.append(\"</ws:registerServersOnLoadBalancer>\");\n\n      return requestBuilder.toString().replaceAll(\"\\\\s+\", \"\");\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/binder/loadbalancer/UpdateLoadBalancerRequestBinder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.binder.loadbalancer;\n\nimport org.jclouds.profitbricks.binder.BaseProfitBricksRequestBinder;\nimport org.jclouds.profitbricks.domain.LoadBalancer;\n\nimport static java.lang.String.format;\n\npublic class UpdateLoadBalancerRequestBinder extends BaseProfitBricksRequestBinder<LoadBalancer.Request.UpdatePayload> {\n\n   protected final StringBuilder requestBuilder;\n\n   UpdateLoadBalancerRequestBinder() {\n      super(\"loadbalancer\");\n      this.requestBuilder = new StringBuilder(128 * 4);\n   }\n\n   @Override\n   protected String createPayload(LoadBalancer.Request.UpdatePayload payload) {\n      return requestBuilder.append(\"<ws:updateLoadBalancer>\")\n              .append(\"<request>\")\n              .append(format(\"<loadBalancerId>%s</loadBalancerId>\", payload.id()))\n              .append(formatIfNotEmpty(\"<loadBalancerName>%s</loadBalancerName>\", payload.name()))\n              .append(formatIfNotEmpty(\"<loadBalancerAlgorithm>%s</loadBalancerAlgorithm>\", payload.algorithm()))\n              .append(formatIfNotEmpty(\"<ip>%s</ip>\", payload.ip()))\n              .append(\"</request>\")\n              .append(\"</ws:updateLoadBalancer>\").toString();\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/binder/nic/CreateNicRequestBinder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.binder.nic;\n\nimport static java.lang.String.format;\nimport org.jclouds.profitbricks.binder.BaseProfitBricksRequestBinder;\nimport org.jclouds.profitbricks.domain.Nic;\n\npublic class CreateNicRequestBinder extends BaseProfitBricksRequestBinder<Nic.Request.CreatePayload> {\n\n   private final StringBuilder requestBuilder;\n\n   CreateNicRequestBinder() {\n      super(\"nic\");\n      this.requestBuilder = new StringBuilder(128 * 2);\n   }\n\n   @Override\n   protected String createPayload(Nic.Request.CreatePayload payload) {\n      requestBuilder.append(\"<ws:createNic>\")\n              .append(\"<request>\")\n              .append(formatIfNotEmpty(\"<ip>%s</ip>\", payload.ip()))\n              .append(formatIfNotEmpty(\"<nicName>%s</nicName>\", payload.name()))\n              .append(formatIfNotEmpty(\"<dhcpActive>%s</dhcpActive>\", payload.dhcpActive()))\n              .append(format(\"<serverId>%s</serverId>\", payload.serverId()))\n              .append(format(\"<lanId>%s</lanId>\", payload.lanId()))\n              .append(\"</request>\")\n              .append(\"</ws:createNic>\");\n      return requestBuilder.toString();\n\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/binder/nic/SetInternetAccessBinder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.binder.nic;\n\nimport org.jclouds.profitbricks.binder.BaseProfitBricksRequestBinder;\nimport org.jclouds.profitbricks.domain.Nic;\n\nimport static java.lang.String.format;\n\npublic class SetInternetAccessBinder extends BaseProfitBricksRequestBinder<Nic.Request.SetInternetAccessPayload> {\n\n   private final StringBuilder requestBuilder;\n\n   SetInternetAccessBinder() {\n      super(\"nic\");\n      this.requestBuilder = new StringBuilder(128);\n   }\n\n   @Override\n   protected String createPayload(Nic.Request.SetInternetAccessPayload payload) {\n      requestBuilder.append(\"<ws:setInternetAccess>\")\n              .append(format(\"<dataCenterId>%s</dataCenterId>\", payload.dataCenterId()))\n              .append(format(\"<lanId>%s</lanId>\", payload.lanId()))\n              .append(format(\"<internetAccess>%s</internetAccess>\", payload.internetAccess()))\n              .append(\"</ws:setInternetAccess>\");\n      return requestBuilder.toString();\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/binder/nic/UpdateNicRequestBinder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.binder.nic;\n\nimport org.jclouds.profitbricks.binder.BaseProfitBricksRequestBinder;\nimport org.jclouds.profitbricks.domain.Nic;\n\nimport static java.lang.String.format;\n\npublic class UpdateNicRequestBinder extends BaseProfitBricksRequestBinder<Nic.Request.UpdatePayload> {\n\n   private final StringBuilder requestBuilder;\n\n   UpdateNicRequestBinder() {\n      super(\"nic\");\n      this.requestBuilder = new StringBuilder(128 * 2);\n   }\n\n   @Override\n   protected String createPayload(Nic.Request.UpdatePayload payload) {\n      requestBuilder.append(\"<ws:updateNic>\")\n              .append(\"<request>\")\n              .append(format(\"<nicId>%s</nicId>\", payload.id()))\n              .append(formatIfNotEmpty(\"<ip>%s</ip>\", payload.ip()))\n              .append(formatIfNotEmpty(\"<nicName>%s</nicName>\", payload.name()))\n              .append(formatIfNotEmpty(\"<dhcpActive>%s</dhcpActive>\", payload.dhcpActive()))\n              .append(formatIfNotEmpty(\"<lanId>%s</lanId>\", payload.lanId()))\n              .append(\"</request>\")\n              .append(\"</ws:updateNic>\");\n      return requestBuilder.toString();\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/binder/server/CreateServerRequestBinder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.binder.server;\n\nimport static java.lang.String.format;\nimport org.jclouds.profitbricks.binder.BaseProfitBricksRequestBinder;\nimport org.jclouds.profitbricks.domain.Server;\n\npublic class CreateServerRequestBinder extends BaseProfitBricksRequestBinder<Server.Request.CreatePayload> {\n\n   protected final StringBuilder requestBuilder;\n\n   CreateServerRequestBinder() {\n      super(\"server\");\n      this.requestBuilder = new StringBuilder(128 * 4);\n   }\n\n   @Override\n   protected String createPayload(Server.Request.CreatePayload payload) {\n      requestBuilder.append(\"<ws:createServer>\")\n              .append(\"<request>\")\n              .append(format(\"<dataCenterId>%s</dataCenterId>\", payload.dataCenterId()))\n              .append(format(\"<cores>%s</cores>\", payload.cores()))\n              .append(format(\"<ram>%s</ram>\", payload.ram()))\n              .append(formatIfNotEmpty(\"<serverName>%s</serverName>\", payload.name()))\n              .append(formatIfNotEmpty(\"<bootFromStorageId>%s</bootFromStorageId>\", payload.bootFromStorageId()))\n              .append(formatIfNotEmpty(\"<bootFromImageId>%s</bootFromImageId>\", payload.bootFromImageId()))\n              .append(formatIfNotEmpty(\"<internetAccess>%s</internetAccess>\", payload.hasInternetAccess()))\n              .append(formatIfNotEmpty(\"<lanId>%s</lanId>\", payload.lanId()))\n              .append(formatIfNotEmpty(\"<osType>%s</osType>\", payload.osType()))\n              .append(formatIfNotEmpty(\"<availabilityZone>%s</availabilityZone>\", payload.availabilityZone()))\n              .append(formatIfNotEmpty(\"<cpuHotPlug>%s</cpuHotPlug>\", payload.isCpuHotPlug()))\n              .append(formatIfNotEmpty(\"<ramHotPlug>%s</ramHotPlug>\", payload.isRamHotPlug()))\n              .append(formatIfNotEmpty(\"<nicHotPlug>%s</nicHotPlug>\", payload.isNicHotPlug()))\n              .append(formatIfNotEmpty(\"<nicHotUnPlug>%s</nicHotUnPlug>\", payload.isNicHotUnPlug()))\n              .append(formatIfNotEmpty(\"<discVirtioHotPlug>%s</discVirtioHotPlug>\", payload.isDiscVirtioHotPlug()))\n              .append(formatIfNotEmpty(\"<discVirtioHotUnPlug>%s</discVirtioHotUnPlug>\", payload.isDiscVirtioHotUnPlug()))\n              .append(\"</request>\")\n              .append(\"</ws:createServer>\");\n      return requestBuilder.toString();\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/binder/server/UpdateServerRequestBinder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.binder.server;\n\nimport static java.lang.String.format;\nimport org.jclouds.profitbricks.binder.BaseProfitBricksRequestBinder;\nimport org.jclouds.profitbricks.domain.Server;\n\npublic class UpdateServerRequestBinder extends BaseProfitBricksRequestBinder<Server.Request.UpdatePayload> {\n\n   protected final StringBuilder requestBuilder;\n\n   UpdateServerRequestBinder() {\n      super(\"server\");\n      this.requestBuilder = new StringBuilder(128 * 4);\n\n   }\n\n   @Override\n   protected String createPayload(Server.Request.UpdatePayload payload) {\n      requestBuilder.append(\"<ws:updateServer>\")\n              .append(\"<request>\")\n              .append(format(\"<serverId>%s</serverId>\", payload.id()))\n              .append(format(\"<cores>%s</cores>\", payload.cores()))\n              .append(format(\"<ram>%s</ram>\", payload.ram()))\n              .append(formatIfNotEmpty(\"<serverName>%s</serverName>\", payload.name()))\n              .append(formatIfNotEmpty(\"<bootFromStorageId>%s</bootFromStorageId>\", payload.bootFromStorageId()))\n              .append(formatIfNotEmpty(\"<bootFromImageId>%s</bootFromImageId>\", payload.bootFromImageId()))\n              .append(formatIfNotEmpty(\"<osType>%s</osType>\", payload.osType()))\n              .append(formatIfNotEmpty(\"<availabilityZone>%s</availabilityZone>\", payload.availabilityZone()))\n              .append(formatIfNotEmpty(\"<cpuHotPlug>%s</cpuHotPlug>\", payload.isCpuHotPlug()))\n              .append(formatIfNotEmpty(\"<ramHotPlug>%s</ramHotPlug>\", payload.isRamHotPlug()))\n              .append(formatIfNotEmpty(\"<nicHotPlug>%s</nicHotPlug>\", payload.isNicHotPlug()))\n              .append(formatIfNotEmpty(\"<nicHotUnPlug>%s</nicHotUnPlug>\", payload.isNicHotUnPlug()))\n              .append(formatIfNotEmpty(\"<discVirtioHotPlug>%s</discVirtioHotPlug>\", payload.isDiscVirtioHotPlug()))\n              .append(formatIfNotEmpty(\"<discVirtioHotUnPlug>%s</discVirtioHotUnPlug>\", payload.isDiscVirtioHotUnPlug()))\n              .append(\"</request>\")\n              .append(\"</ws:updateServer>\");\n      return requestBuilder.toString();\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/binder/snapshot/CreateSnapshotRequestBinder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.binder.snapshot;\n\nimport org.jclouds.profitbricks.binder.BaseProfitBricksRequestBinder;\nimport org.jclouds.profitbricks.domain.Snapshot;\n\nimport static java.lang.String.format;\n\npublic class CreateSnapshotRequestBinder extends BaseProfitBricksRequestBinder<Snapshot.Request.CreatePayload> {\n\n   protected final StringBuilder requestBuilder;\n\n   protected CreateSnapshotRequestBinder() {\n      super(\"snapshot\");\n      this.requestBuilder = new StringBuilder(128);\n   }\n\n   @Override\n   protected String createPayload(Snapshot.Request.CreatePayload payload) {\n      requestBuilder.append(\"<ws:createSnapshot>\")\n              .append(\"<request>\")\n              .append(format(\"<storageId>%s</storageId>\", payload.storageId()))\n              .append(formatIfNotEmpty(\"<description>%s</description>\", payload.description()))\n              .append(formatIfNotEmpty(\"<snapshotName>%s</snapshotName>\", payload.name()))\n              .append(\"</request>\")\n              .append(\"</ws:createSnapshot>\");\n      return requestBuilder.toString();\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/binder/snapshot/RollbackSnapshotRequestBinder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.binder.snapshot;\n\nimport org.jclouds.profitbricks.binder.BaseProfitBricksRequestBinder;\nimport org.jclouds.profitbricks.domain.Snapshot;\n\nimport static java.lang.String.format;\n\npublic class RollbackSnapshotRequestBinder extends BaseProfitBricksRequestBinder<Snapshot.Request.RollbackPayload> {\n\n   protected final StringBuilder requestBuilder;\n\n   protected RollbackSnapshotRequestBinder() {\n      super(\"snapshot\");\n      this.requestBuilder = new StringBuilder(128);\n   }\n\n   @Override\n   protected String createPayload(Snapshot.Request.RollbackPayload payload) {\n      requestBuilder.append(\"<ws:rollbackSnapshot>\")\n              .append(\"<request>\")\n              .append(format(\"<snapshotId>%s</snapshotId>\", payload.snapshotId()))\n              .append(format(\"<storageId>%s</storageId>\", payload.storageId()))\n              .append(\"</request>\")\n              .append(\"</ws:rollbackSnapshot>\");\n      return requestBuilder.toString();\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/binder/snapshot/UpdateSnapshotRequestBinder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.binder.snapshot;\n\nimport static java.lang.String.format;\nimport org.jclouds.profitbricks.binder.BaseProfitBricksRequestBinder;\nimport org.jclouds.profitbricks.domain.Snapshot;\n\npublic class UpdateSnapshotRequestBinder extends BaseProfitBricksRequestBinder<Snapshot.Request.UpdatePayload> {\n\n   protected final StringBuilder requestBuilder;\n\n   protected UpdateSnapshotRequestBinder() {\n      super(\"snapshot\");\n      this.requestBuilder = new StringBuilder(128);\n   }\n\n   @Override\n   protected String createPayload(Snapshot.Request.UpdatePayload payload) {\n      requestBuilder.append(\"<ws:updateSnapshot>\")\n              .append(\"<request>\")\n              .append(format(\"<snapshotId>%s</snapshotId>\", payload.id()))\n              .append(format(\"<description>%s</description>\", payload.description()))\n              .append(format(\"<snapshotName>%s</snapshotName>\", payload.name()))\n              .append(formatIfNotEmpty(\"<bootable>%s</bootable>\", payload.bootable()))\n              .append(formatIfNotEmpty(\"<osType>%s</osType>\", payload.osType()))\n              .append(formatIfNotEmpty(\"<cpuHotPlug>%s</cpuHotPlug>\", payload.isCpuHotPlug()))\n              .append(formatIfNotEmpty(\"<cpuHotUnPlug>%s</cpuHotUnPlug>\", payload.isCpuHotUnPlug()))\n              .append(formatIfNotEmpty(\"<ramHotPlug>%s</ramHotPlug>\", payload.isRamHotPlug()))\n              .append(formatIfNotEmpty(\"<ramHotUnPlug>%s</ramHotUnPlug>\", payload.isRamHotUnPlug()))\n              .append(formatIfNotEmpty(\"<nicHotPlug>%s</nicHotPlug>\", payload.isNicHotPlug()))\n              .append(formatIfNotEmpty(\"<nicHotUnPlug>%s</nicHotUnPlug>\", payload.isNicHotUnPlug()))\n              .append(formatIfNotEmpty(\"<discVirtioHotPlug>%s</discVirtioHotPlug>\", payload.isDiscVirtioHotPlug()))\n              .append(formatIfNotEmpty(\"<discVirtioHotUnPlug>%s</discVirtioHotUnPlug>\", payload.isDiscVirtioHotUnPlug()))\n              .append(\"</request>\")\n              .append(\"</ws:updateSnapshot>\");\n      return requestBuilder.toString();\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/binder/storage/ConnectStorageToServerRequestBinder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.binder.storage;\n\nimport static java.lang.String.format;\n\nimport org.jclouds.profitbricks.binder.BaseProfitBricksRequestBinder;\nimport org.jclouds.profitbricks.domain.Storage;\n\npublic class ConnectStorageToServerRequestBinder extends BaseProfitBricksRequestBinder<Storage.Request.ConnectPayload> {\n\n   protected final StringBuilder requestBuilder;\n\n   ConnectStorageToServerRequestBinder() {\n      super(\"storage\");\n      this.requestBuilder = new StringBuilder(128 * 2);\n   }\n\n   @Override\n   protected String createPayload(Storage.Request.ConnectPayload payload) {\n      requestBuilder.append(\"<ws:connectStorageToServer>\")\n              .append(\"<request>\")\n              .append(format(\"<storageId>%s</storageId>\", payload.storageId()))\n              .append(format(\"<serverId>%s</serverId>\", payload.serverId()))\n              .append(formatIfNotEmpty(\"<busType>%s</busType>\", payload.busType()))\n              .append(formatIfNotEmpty(\"<deviceNumber>%s</deviceNumber>\", payload.deviceNumber()))\n              .append(\"</request>\")\n              .append(\"</ws:connectStorageToServer>\");\n      return requestBuilder.toString();\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/binder/storage/CreateStorageRequestBinder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.binder.storage;\n\nimport static java.lang.String.format;\nimport org.jclouds.profitbricks.binder.BaseProfitBricksRequestBinder;\nimport org.jclouds.profitbricks.domain.Storage;\n\npublic class CreateStorageRequestBinder extends BaseProfitBricksRequestBinder<Storage.Request.CreatePayload> {\n\n   protected final StringBuilder requestBuilder;\n\n   CreateStorageRequestBinder() {\n      super(\"storage\");\n      this.requestBuilder = new StringBuilder(128 * 2);\n   }\n\n   @Override\n   protected String createPayload(Storage.Request.CreatePayload payload) {\n      requestBuilder.append(\"<ws:createStorage>\")\n              .append(\"<request>\")\n              .append(format(\"<dataCenterId>%s</dataCenterId>\", payload.dataCenterId()))\n              .append(formatIfNotEmpty(\"<storageName>%s</storageName>\", payload.name()))\n              .append(format(\"<size>%.0f</size>\", payload.size()))\n              .append(formatIfNotEmpty(\"<mountImageId>%s</mountImageId>\", payload.mountImageId()))\n              .append(formatIfNotEmpty(\"<profitBricksImagePassword>%s</profitBricksImagePassword>\", payload.imagePassword()))\n              .append(\"</request>\")\n              .append(\"</ws:createStorage>\");\n      return requestBuilder.toString();\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/binder/storage/UpdateStorageRequestBinder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.binder.storage;\n\nimport static java.lang.String.format;\nimport org.jclouds.profitbricks.binder.BaseProfitBricksRequestBinder;\nimport org.jclouds.profitbricks.domain.Storage;\n\npublic class UpdateStorageRequestBinder extends BaseProfitBricksRequestBinder<Storage.Request.UpdatePayload> {\n\n   protected final StringBuilder requestBuilder;\n\n   UpdateStorageRequestBinder() {\n      super(\"storage\");\n      this.requestBuilder = new StringBuilder(128 * 2);\n   }\n\n   @Override\n   protected String createPayload(Storage.Request.UpdatePayload payload) {\n      requestBuilder\n              .append(\"<ws:updateStorage>\")\n              .append(\"<request>\")\n              .append(format(\"<storageId>%s</storageId>\", payload.id()))\n              .append(formatIfNotEmpty(\"<size>%.0f</size>\", payload.size()))\n              .append(formatIfNotEmpty(\"<storageName>%s</storageName>\", payload.name()))\n              .append(formatIfNotEmpty(\"<mountImageId>%s</mountImageId>\", payload.mountImageId()))\n              .append(\"</request>\")\n              .append(\"</ws:updateStorage>\");\n\n      return requestBuilder.toString();\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/compute/ProfitBricksComputeServiceAdapter.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.compute;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Strings.isNullOrEmpty;\nimport static com.google.common.collect.Iterables.transform;\nimport static com.google.common.util.concurrent.Futures.allAsList;\nimport static com.google.common.util.concurrent.Futures.getUnchecked;\nimport static java.lang.String.format;\nimport static org.jclouds.Constants.PROPERTY_USER_THREADS;\nimport static org.jclouds.profitbricks.config.ProfitBricksComputeProperties.POLL_PREDICATE_DATACENTER;\n\nimport java.util.List;\nimport java.util.concurrent.Callable;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.ComputeServiceAdapter;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.HardwareBuilder;\nimport org.jclouds.compute.domain.Processor;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.domain.Volume;\nimport org.jclouds.compute.domain.internal.VolumeImpl;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.compute.util.ComputeServiceUtils;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.profitbricks.ProfitBricksApi;\nimport org.jclouds.profitbricks.compute.concurrent.ProvisioningJob;\nimport org.jclouds.profitbricks.compute.concurrent.ProvisioningManager;\nimport org.jclouds.profitbricks.compute.function.ProvisionableToImage;\nimport org.jclouds.profitbricks.compute.strategy.TemplateWithDataCenter;\nimport org.jclouds.profitbricks.domain.AvailabilityZone;\nimport org.jclouds.profitbricks.domain.DataCenter;\nimport org.jclouds.profitbricks.domain.Image;\nimport org.jclouds.profitbricks.domain.Provisionable;\nimport org.jclouds.profitbricks.domain.Server;\nimport org.jclouds.profitbricks.domain.Snapshot;\nimport org.jclouds.profitbricks.domain.Storage;\nimport org.jclouds.profitbricks.features.ServerApi;\nimport org.jclouds.rest.ResourceNotFoundException;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Throwables;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Lists;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.ListeningExecutorService;\nimport com.google.inject.Inject;\n\nimport org.jclouds.util.PasswordGenerator;\n\n@Singleton\npublic class ProfitBricksComputeServiceAdapter implements ComputeServiceAdapter<Server, Hardware, Provisionable, Location> {\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   private final ProfitBricksApi api;\n   private final Predicate<String> waitDcUntilAvailable;\n   private final ListeningExecutorService executorService;\n   private final ProvisioningJob.Factory jobFactory;\n   private final ProvisioningManager provisioningManager;\n   private final PasswordGenerator.Config passwordGenerator;\n\n   private static final Integer DEFAULT_LAN_ID = 1;\n\n   @Inject\n   ProfitBricksComputeServiceAdapter(ProfitBricksApi api,\n           @Named(POLL_PREDICATE_DATACENTER) Predicate<String> waitDcUntilAvailable,\n           @Named(PROPERTY_USER_THREADS) ListeningExecutorService executorService,\n           ProvisioningJob.Factory jobFactory,\n           ProvisioningManager provisioningManager,\n           PasswordGenerator.Config passwordGenerator) {\n      this.api = api;\n      this.waitDcUntilAvailable = waitDcUntilAvailable;\n      this.executorService = executorService;\n      this.jobFactory = jobFactory;\n      this.provisioningManager = provisioningManager;\n      this.passwordGenerator = passwordGenerator;\n   }\n   \n   @Override\n   public NodeAndInitialCredentials<Server> createNodeWithGroupEncodedIntoName(String group, String name, Template template) {\n      checkArgument(template instanceof TemplateWithDataCenter, \"This implementation requires a TemplateWithDataCenter\");\n      return createNodeWithGroupEncodedIntoName(group, name, TemplateWithDataCenter.class.cast(template));\n   }\n\n   protected NodeAndInitialCredentials<Server> createNodeWithGroupEncodedIntoName(String group, String name, TemplateWithDataCenter template) {\n      checkArgument(template.getLocation().getScope() == LocationScope.ZONE, \"Template must use a ZONE-scoped location\");\n      final String dataCenterId = template.getDataCenter().id();\n\n      Hardware hardware = template.getHardware();\n\n      TemplateOptions options = template.getOptions();\n      final String loginUser = isNullOrEmpty(options.getLoginUser()) ? \"root\" : options.getLoginUser();\n      final String password = options.hasLoginPassword() ? options.getLoginPassword() : passwordGenerator.generate();\n\n      final org.jclouds.compute.domain.Image image = template.getImage();\n\n      // provision all storages based on hardware\n      List<? extends Volume> volumes = hardware.getVolumes();\n      List<String> storageIds = Lists.newArrayListWithExpectedSize(volumes.size());\n\n      int i = 1;\n      for (final Volume volume : volumes)\n         try {\n            logger.trace(\"<< provisioning storage '%s'\", volume);\n            final Storage.Request.CreatePayload.Builder storageBuilder = Storage.Request.creatingBuilder();\n            if (i == 1) {\n               storageBuilder.mountImageId(image.getId());\n               // we don't need to pass password to the API if we're using a snapshot\n               Provisionable.Type provisionableType = Provisionable.Type.fromValue(\n                       image.getUserMetadata().get(ProvisionableToImage.KEY_PROVISIONABLE_TYPE));\n               if (provisionableType == Provisionable.Type.IMAGE)\n                  storageBuilder.imagePassword(password);\n            }\n            storageBuilder.dataCenterId(dataCenterId)\n                    .name(format(\"%s-disk-%d\", name, i++))\n                    .size(volume.getSize());\n\n            String storageId = (String) provisioningManager.provision(jobFactory.create(dataCenterId, new Supplier<Object>() {\n\n               @Override\n               public Object get() {\n                  return api.storageApi().createStorage(storageBuilder.build());\n               }\n            }));\n\n            storageIds.add(storageId);\n            logger.trace(\">> provisioning complete for storage. returned id='%s'\", storageId);\n         } catch (Exception ex) {\n            if (i - 1 == 1) // if first storage (one with image) provisioning fails; stop method\n               throw Throwables.propagate(ex);\n            logger.warn(ex, \">> failed to provision storage. skipping..\");\n         }\n\n      int lanId = DEFAULT_LAN_ID;\n      if (options.getNetworks() != null)\n         try {\n            String networkId = Iterables.get(options.getNetworks(), 0);\n            lanId = Integer.parseInt(networkId);\n         } catch (Exception ex) {\n            logger.warn(\"no valid network id found from options. using default id='%d'\", DEFAULT_LAN_ID);\n         }\n\n      Double cores = ComputeServiceUtils.getCores(hardware);\n\n      // provision server and connect boot storage (first provisioned)\n      String serverId = null;\n      try {\n         String storageBootDeviceId = Iterables.get(storageIds, 0); // must have atleast 1\n         final Server.Request.CreatePayload serverRequest = Server.Request.creatingBuilder()\n                 .dataCenterId(dataCenterId)\n                 .name(name)\n                 .bootFromStorageId(storageBootDeviceId)\n                 .cores(cores.intValue())\n                 .ram(hardware.getRam())\n                 .availabilityZone(AvailabilityZone.AUTO)\n                 .hasInternetAccess(true)\n                 .lanId(lanId)\n                 .build();\n         logger.trace(\"<< provisioning server '%s'\", serverRequest);\n\n         serverId = (String) provisioningManager.provision(jobFactory.create(dataCenterId, new Supplier<Object>() {\n\n            @Override\n            public Object get() {\n               return api.serverApi().createServer(serverRequest);\n            }\n         }));\n         logger.trace(\">> provisioning complete for server. returned id='%s'\", serverId);\n\n      } catch (Exception ex) {\n         logger.error(ex, \">> failed to provision server. rollbacking..\");\n         destroyStorages(storageIds, dataCenterId);\n         throw Throwables.propagate(ex);\n      }\n\n      // connect the rest of storages to server; delete if fails\n      final int storageCount = storageIds.size();\n      for (int j = 1; j < storageCount; j++) { // skip first; already connected\n         String storageId = storageIds.get(j);\n         try {\n            logger.trace(\"<< connecting storage '%s' to server '%s'\", storageId, serverId);\n            final Storage.Request.ConnectPayload request = Storage.Request.connectingBuilder()\n                    .storageId(storageId)\n                    .serverId(serverId)\n                    .build();\n\n            provisioningManager.provision(jobFactory.create(group, new Supplier<Object>() {\n\n               @Override\n               public Object get() {\n                  return api.storageApi().connectStorageToServer(request);\n               }\n            }));\n\n            logger.trace(\">> storage connected.\");\n         } catch (Exception ex) {\n            // delete unconnected storage\n            logger.warn(ex, \">> failed to connect storage '%s'. deleting..\", storageId);\n            destroyStorage(storageId, dataCenterId);\n         }\n      }\n\n      // Last paranoid check\n      waitDcUntilAvailable.apply(dataCenterId);\n\n      LoginCredentials serverCredentials = LoginCredentials.builder()\n              .user(loginUser)\n              .password(password)\n              .build();\n\n      Server server = getNode(serverId);\n\n      return new NodeAndInitialCredentials<Server>(server, serverId, serverCredentials);\n   }\n\n   @Override\n   public Iterable<Hardware> listHardwareProfiles() {\n      // Max [cores=48] [disk size per storage=2048GB] [ram=200704 MB]\n      List<Hardware> hardwares = Lists.newArrayList();\n      for (int core = 1; core <= 48; core++)\n         for (int ram : new int[]{1024, 2 * 1024, 4 * 1024, 8 * 1024,\n            10 * 1024, 16 * 1024, 24 * 1024, 28 * 1024, 32 * 1024})\n            for (float size : new float[]{10, 20, 30, 50, 80, 100, 150, 200, 250, 500}) {\n               String id = String.format(\"cpu=%d,ram=%s,disk=%f\", core, ram, size);\n               hardwares.add(new HardwareBuilder()\n                       .ids(id)\n                       .ram(ram)\n                       .hypervisor(\"kvm\")\n                       .name(id)\n                       .processor(new Processor(core, 1d))\n                       .volume(new VolumeImpl(size, true, true))\n                       .build());\n            }\n      return hardwares;\n   }\n\n   @Override\n   public Iterable<Provisionable> listImages() {\n      // fetch images..\n      ListenableFuture<List<Image>> images = executorService.submit(new Callable<List<Image>>() {\n\n         @Override\n         public List<Image> call() throws Exception {\n            logger.trace(\"<< fetching images..\");\n            // Filter HDD types only, since JClouds doesn't have a concept of \"CD-ROM\" anyway\n            Iterable<Image> filteredImages = Iterables.filter(api.imageApi().getAllImages(), new Predicate<Image>() {\n\n               @Override\n               public boolean apply(Image image) {\n                  return image.type() == Image.Type.HDD;\n               }\n            });\n            logger.trace(\">> images fetched.\");\n\n            return ImmutableList.copyOf(filteredImages);\n         }\n\n      });\n      // and snapshots at the same time\n      ListenableFuture<List<Snapshot>> snapshots = executorService.submit(new Callable<List<Snapshot>>() {\n\n         @Override\n         public List<Snapshot> call() throws Exception {\n            logger.trace(\"<< fetching snapshots\");\n            List<Snapshot> remoteSnapshots = api.snapshotApi().getAllSnapshots();\n            logger.trace(\">> snapshots feched.\");\n\n            return remoteSnapshots;\n         }\n\n      });\n\n      return Iterables.concat(getUnchecked(images), getUnchecked(snapshots));\n   }\n\n   @Override\n   public Provisionable getImage(String id) {\n      // try search images\n      logger.trace(\"<< searching for image with id=%s\", id);\n      try {\n         Image image = api.imageApi().getImage(id);\n         if (image != null) {\n            logger.trace(\">> found image [%s].\", image.name());\n            return image;\n         }\n      } catch (Exception ex) {\n         logger.warn(ex, \">> unexpected error getting image. Trying to get as a snapshot...\");\n      }\n      \n      // try search snapshots\n      logger.trace(\"<< not found from images. searching for snapshot with id=%s\", id);\n      Snapshot snapshot = api.snapshotApi().getSnapshot(id);\n      if (snapshot != null) {\n         logger.trace(\">> found snapshot [%s]\", snapshot.name());\n         return snapshot;\n      }\n      throw new ResourceNotFoundException(\"No image/snapshot with id '\" + id + \"' was found\");\n   }\n\n   @Override\n   public Iterable<Location> listLocations() {\n      // Will never be called\n      throw new UnsupportedOperationException(\"Locations are configured in jclouds properties\");\n   }\n\n   @Override\n   public Server getNode(String id) {\n      logger.trace(\"<< searching for server with id=%s\", id);\n\n      Server server = api.serverApi().getServer(id);\n      if (server != null)\n         logger.trace(\">> found server [%s]\", server.name());\n      return server;\n   }\n\n   @Override\n   public void destroyNode(String nodeId) {\n      ServerApi serverApi = api.serverApi();\n      Server server = serverApi.getServer(nodeId);\n      if (server != null) {\n         String dataCenterId = server.dataCenter().id();\n         for (Storage storage : server.storages())\n            destroyStorage(storage.id(), dataCenterId);\n\n         try {\n            destroyServer(nodeId, dataCenterId);\n         } catch (Exception ex) {\n            logger.warn(ex, \">> failed to delete server with id=%s\", nodeId);\n         }\n      }\n   }\n\n   @Override\n   public void rebootNode(final String id) {\n      // Fail pre-emptively if not found\n      final Server node = getRequiredNode(id);\n      final DataCenter dataCenter = node.dataCenter();\n      provisioningManager.provision(jobFactory.create(dataCenter.id(), new Supplier<Object>() {\n\n         @Override\n         public Object get() {\n            api.serverApi().resetServer(id);\n\n            return node;\n         }\n      }));\n   }\n\n   @Override\n   public void resumeNode(final String id) {\n      final Server node = getRequiredNode(id);\n      if (node.status() == Server.Status.RUNNING)\n         return;\n\n      final DataCenter dataCenter = node.dataCenter();\n      provisioningManager.provision(jobFactory.create(dataCenter.id(), new Supplier<Object>() {\n\n         @Override\n         public Object get() {\n            api.serverApi().startServer(id);\n\n            return node;\n         }\n      }));\n   }\n\n   @Override\n   public void suspendNode(final String id) {\n      final Server node = getRequiredNode(id);\n      // Intentionally didn't include SHUTDOWN (only achieved via UI; soft-shutdown). \n      // A SHUTOFF server is no longer billed, so we execute method for all other status\n      if (node.status() == Server.Status.SHUTOFF)\n         return;\n\n      final DataCenter dataCenter = node.dataCenter();\n      provisioningManager.provision(jobFactory.create(dataCenter.id(), new Supplier<Object>() {\n\n         @Override\n         public Object get() {\n            api.serverApi().stopServer(id);\n\n            return node;\n         }\n      }));\n   }\n\n   @Override\n   public Iterable<Server> listNodes() {\n      logger.trace(\">> fetching all servers..\");\n      List<Server> servers = api.serverApi().getAllServers();\n      logger.trace(\">> servers fetched.\");\n      return servers;\n   }\n\n   @Override\n   public Iterable<Server> listNodesByIds(final Iterable<String> ids) {\n      // Only fetch the requested nodes. Do it in parallel.\n      ListenableFuture<List<Server>> futures = allAsList(transform(ids,\n              new Function<String, ListenableFuture<Server>>() {\n\n                 @Override\n                 public ListenableFuture<Server> apply(final String input) {\n                    return executorService.submit(new Callable<Server>() {\n\n                       @Override\n                       public Server call() throws Exception {\n                          return getNode(input);\n                       }\n                    });\n                 }\n              }));\n\n      return getUnchecked(futures);\n   }\n\n   private void destroyServer(final String serverId, final String dataCenterId) {\n      try {\n         logger.trace(\"<< deleting server with id=%s\", serverId);\n         provisioningManager.provision(jobFactory.create(dataCenterId, new Supplier<Object>() {\n\n            @Override\n            public Object get() {\n               api.serverApi().deleteServer(serverId);\n\n               return serverId;\n            }\n         }));\n         logger.trace(\">> server '%s' deleted.\", serverId);\n      } catch (Exception ex) {\n         logger.warn(ex, \">> failed to delete server with id=%s\", serverId);\n      }\n   }\n\n   private void destroyStorages(List<String> storageIds, String dataCenterId) {\n      for (String storageId : storageIds)\n         destroyStorage(storageId, dataCenterId);\n   }\n\n   private void destroyStorage(final String storageId, final String dataCenterId) {\n      try {\n         logger.trace(\"<< deleting storage with id=%s\", storageId);\n         provisioningManager.provision(jobFactory.create(dataCenterId, new Supplier<Object>() {\n\n            @Override\n            public Object get() {\n               api.storageApi().deleteStorage(storageId);\n\n               return storageId;\n            }\n         }));\n         logger.trace(\">> storage '%s' deleted.\", storageId);\n      } catch (Exception ex) {\n         logger.warn(ex, \">> failed to delete storage with id=%s\", storageId);\n      }\n   }\n\n   private Server getRequiredNode(String nodeId) {\n      Server node = getNode(nodeId);\n      if (node == null)\n         throw new ResourceNotFoundException(\"Node with id'\" + nodeId + \"' was not found.\");\n      return node;\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/compute/concurrent/ProvisioningJob.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.compute.concurrent;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.profitbricks.config.ProfitBricksComputeProperties.POLL_PREDICATE_DATACENTER;\n\nimport java.util.concurrent.Callable;\n\nimport jakarta.inject.Named;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.inject.Inject;\nimport com.google.inject.assistedinject.Assisted;\n\npublic class ProvisioningJob implements Callable {\n\n   public interface Factory {\n\n      ProvisioningJob create(String group, Supplier<Object> operation);\n   }\n\n   private final Predicate<String> waitDataCenterUntilReady;\n   private final String group;\n   private final Supplier<Object> operation;\n\n   @Inject\n   ProvisioningJob(@Named(POLL_PREDICATE_DATACENTER) Predicate<String> waitDataCenterUntilReady,\n           @Assisted String group, @Assisted Supplier<Object> operation) {\n      this.waitDataCenterUntilReady = waitDataCenterUntilReady;\n      this.group = checkNotNull(group, \"group cannot be null\");\n      this.operation = checkNotNull(operation, \"operation cannot be null\");\n   }\n\n   @Override\n   public Object call() throws Exception {\n      waitDataCenterUntilReady.apply(group);\n      Object obj = operation.get();\n      waitDataCenterUntilReady.apply(group);\n\n      return obj;\n   }\n\n   public String getGroup() {\n      return group;\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/compute/concurrent/ProvisioningManager.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.compute.concurrent;\n\nimport static com.google.common.util.concurrent.Futures.getUnchecked;\nimport static com.google.common.util.concurrent.MoreExecutors.listeningDecorator;\n\nimport java.io.Closeable;\nimport java.io.IOException;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.atomic.AtomicBoolean;\n\nimport jakarta.annotation.Resource;\n\nimport org.jclouds.concurrent.config.WithSubmissionTrace;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.util.concurrent.ListeningExecutorService;\n\n/**\n * Delegates {@link Job} to single-threaded executor services based on it's group.\n *\n */\npublic final class ProvisioningManager implements Closeable {\n\n   @Resource\n   private Logger logger = Logger.NULL;\n\n   private final Map<String, ListeningExecutorService> workers\n           = new ConcurrentHashMap<String, ListeningExecutorService>(1);\n\n   private final AtomicBoolean terminated = new AtomicBoolean(false);\n\n   public Object provision(ProvisioningJob job) {\n      if (terminated.get()) {\n         logger.warn(\"Job(%s) submitted but the provisioning manager is already closed\", job);\n         return null;\n      }\n\n      logger.debug(\"Job(%s) submitted to group '%s'\", job, job.getGroup());\n      ListeningExecutorService workerGroup = getWorkerGroup(job.getGroup());\n      return getUnchecked(workerGroup.submit(job));\n   }\n\n   protected ListeningExecutorService newExecutorService() {\n      return WithSubmissionTrace.wrap(listeningDecorator(Executors.newSingleThreadExecutor()));\n   }\n\n   private void newWorkerGroupIfAbsent(String name) {\n      if (!workers.containsKey(name))\n         workers.put(name, newExecutorService());\n   }\n\n   private ListeningExecutorService getWorkerGroup(String name) {\n      newWorkerGroupIfAbsent(name);\n      return workers.get(name);\n   }\n\n   @Override\n   public void close() throws IOException {\n      terminated.set(true); // Do not allow to enqueue more jobs\n      Collection<ListeningExecutorService> executors = workers.values();\n      for (ListeningExecutorService executor : executors) {\n         List<Runnable> runnables = executor.shutdownNow();\n         if (!runnables.isEmpty())\n            logger.warn(\"when shutting down executor %s, runnables outstanding: %s\", executor, runnables);\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/compute/config/ProfitBricksComputeServiceContextModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.compute.config;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_RUNNING;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_SUSPENDED;\nimport static org.jclouds.profitbricks.config.ProfitBricksComputeProperties.POLL_INITIAL_PERIOD;\nimport static org.jclouds.profitbricks.config.ProfitBricksComputeProperties.POLL_MAX_PERIOD;\nimport static org.jclouds.profitbricks.config.ProfitBricksComputeProperties.POLL_PREDICATE_DATACENTER;\nimport static org.jclouds.profitbricks.config.ProfitBricksComputeProperties.POLL_PREDICATE_SNAPSHOT;\nimport static org.jclouds.profitbricks.config.ProfitBricksComputeProperties.TIMEOUT_DATACENTER_AVAILABLE;\nimport static org.jclouds.util.Predicates2.retry;\n\nimport java.util.concurrent.TimeUnit;\n\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.ComputeServiceAdapter;\nimport org.jclouds.compute.config.ComputeServiceAdapterContextModule;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.Volume;\nimport org.jclouds.compute.domain.internal.ArbitraryCpuRamTemplateBuilderImpl;\nimport org.jclouds.compute.domain.internal.TemplateBuilderImpl;\nimport org.jclouds.compute.strategy.CreateNodesInGroupThenAddToSet;\nimport org.jclouds.domain.Location;\nimport org.jclouds.functions.IdentityFunction;\nimport org.jclouds.lifecycle.Closer;\nimport org.jclouds.location.suppliers.ImplicitLocationSupplier;\nimport org.jclouds.location.suppliers.implicit.OnlyLocationOrFirstZone;\nimport org.jclouds.profitbricks.ProfitBricksApi;\nimport org.jclouds.profitbricks.compute.ProfitBricksComputeServiceAdapter;\nimport org.jclouds.profitbricks.compute.concurrent.ProvisioningJob;\nimport org.jclouds.profitbricks.compute.concurrent.ProvisioningManager;\nimport org.jclouds.profitbricks.compute.function.ProvisionableToImage;\nimport org.jclouds.profitbricks.compute.function.ServerToNodeMetadata;\nimport org.jclouds.profitbricks.compute.function.StorageToVolume;\nimport org.jclouds.profitbricks.compute.strategy.AssignDataCenterToTemplate;\nimport org.jclouds.profitbricks.domain.Provisionable;\nimport org.jclouds.profitbricks.domain.ProvisioningState;\nimport org.jclouds.profitbricks.domain.Server;\nimport org.jclouds.profitbricks.domain.Storage;\nimport org.jclouds.util.PasswordGenerator;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.inject.Inject;\nimport com.google.inject.Provides;\nimport com.google.inject.Scopes;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.assistedinject.FactoryModuleBuilder;\n\n\npublic class ProfitBricksComputeServiceContextModule extends\n        ComputeServiceAdapterContextModule<Server, Hardware, Provisionable, Location> {\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   protected void configure() {\n      super.configure();\n\n      install(new FactoryModuleBuilder().build(ProvisioningJob.Factory.class));\n\n      bind(ImplicitLocationSupplier.class).to(OnlyLocationOrFirstZone.class).in(Scopes.SINGLETON);\n\n      bind(CreateNodesInGroupThenAddToSet.class).to(AssignDataCenterToTemplate.class).in(Scopes.SINGLETON);\n\n      bind(TemplateBuilderImpl.class).to(ArbitraryCpuRamTemplateBuilderImpl.class);\n\n      bind(new TypeLiteral<ComputeServiceAdapter<Server, Hardware, Provisionable, Location>>() {\n      }).to(ProfitBricksComputeServiceAdapter.class);\n\n      bind(new TypeLiteral<Function<Server, NodeMetadata>>() {\n      }).to(ServerToNodeMetadata.class);\n\n      bind(new TypeLiteral<Function<Provisionable, Image>>() {\n      }).to(ProvisionableToImage.class);\n\n      bind(new TypeLiteral<Function<Storage, Volume>>() {\n      }).to(StorageToVolume.class);\n\n      bind(new TypeLiteral<Function<Hardware, Hardware>>() {\n      }).to(Class.class.cast(IdentityFunction.class));\n   }\n   \n   @Provides\n   @Singleton\n   protected PasswordGenerator.Config providePasswordGenerator() {\n      return new PasswordGenerator()\n            .lower().min(2).max(10).exclude(\"ilowyz\".toCharArray())\n            .upper().min(2).max(10).exclude(\"IOWYZ\".toCharArray())\n            .numbers().min(2).max(10).exclude(\"10\".toCharArray())\n            .symbols().count(0);\n   }\n\n   @Provides\n   @Singleton\n   @Named(POLL_PREDICATE_DATACENTER)\n   Predicate<String> provideDataCenterAvailablePredicate(\n           final ProfitBricksApi api, ComputeConstants constants) {\n      return retry(new DataCenterProvisioningStatePredicate(\n              api, ProvisioningState.AVAILABLE),\n              constants.pollTimeout(), constants.pollPeriod(), constants.pollMaxPeriod(), TimeUnit.SECONDS);\n   }\n\n   @Provides\n   @Named(TIMEOUT_NODE_RUNNING)\n   Predicate<String> provideServerRunningPredicate(final ProfitBricksApi api, ComputeConstants constants) {\n      return retry(new ServerStatusPredicate(\n              api, Server.Status.RUNNING),\n              constants.pollTimeout(), constants.pollPeriod(), constants.pollMaxPeriod(), TimeUnit.SECONDS);\n   }\n\n   @Provides\n   @Named(TIMEOUT_NODE_SUSPENDED)\n   Predicate<String> provideServerSuspendedPredicate(final ProfitBricksApi api, ComputeConstants constants) {\n      return retry(new ServerStatusPredicate(\n              api, Server.Status.SHUTOFF),\n              constants.pollTimeout(), constants.pollPeriod(), constants.pollMaxPeriod(), TimeUnit.SECONDS);\n   }\n\n   @Provides\n   @Singleton\n   ProvisioningManager provideProvisioningManager(Closer closer) {\n      ProvisioningManager provisioningManager = new ProvisioningManager();\n      closer.addToClose(provisioningManager);\n\n      return provisioningManager;\n   }\n\n   @Provides\n   @Singleton\n   @Named(POLL_PREDICATE_SNAPSHOT)\n   Predicate<String> provideSnapshotAvailablePredicate(final ProfitBricksApi api, ComputeConstants constants) {\n      return retry(new SnapshotProvisioningStatePredicate(\n              api, ProvisioningState.AVAILABLE),\n              constants.pollTimeout(), constants.pollPeriod(), constants.pollMaxPeriod(), TimeUnit.SECONDS);\n   }\n\n   static class DataCenterProvisioningStatePredicate implements Predicate<String> {\n\n      private final ProfitBricksApi api;\n      private final ProvisioningState expectedState;\n\n      public DataCenterProvisioningStatePredicate(ProfitBricksApi api, ProvisioningState expectedState) {\n         this.api = checkNotNull(api, \"api must not be null\");\n         this.expectedState = checkNotNull(expectedState, \"expectedState must not be null\");\n      }\n\n      @Override\n      public boolean apply(String input) {\n         checkNotNull(input, \"datacenter id\");\n         return api.dataCenterApi().getDataCenterState(input) == expectedState;\n      }\n\n   }\n\n   static class ServerStatusPredicate implements Predicate<String> {\n\n      private final ProfitBricksApi api;\n      private final Server.Status expectedStatus;\n\n      public ServerStatusPredicate(ProfitBricksApi api, Server.Status expectedStatus) {\n         this.api = checkNotNull(api, \"api must not be null\");\n         this.expectedStatus = checkNotNull(expectedStatus, \"expectedStatus must not be null\");\n      }\n\n      @Override\n      public boolean apply(String input) {\n         checkNotNull(input, \"server id\");\n         return api.serverApi().getServer(input).status() == expectedStatus;\n      }\n\n   }\n\n   static class SnapshotProvisioningStatePredicate implements Predicate<String> {\n\n      private final ProfitBricksApi api;\n      private final ProvisioningState expectedState;\n\n      public SnapshotProvisioningStatePredicate(ProfitBricksApi api, ProvisioningState expectedState) {\n         this.api = checkNotNull(api, \"api must not be null\");\n         this.expectedState = checkNotNull(expectedState, \"expectedState must not be null\");\n      }\n\n      @Override\n      public boolean apply(String input) {\n         checkNotNull(input, \"snapshot id\");\n         return api.snapshotApi().getSnapshot(input).state() == expectedState;\n      }\n\n   }\n\n   @Singleton\n   public static class ComputeConstants {\n\n      @Inject\n      @Named(TIMEOUT_DATACENTER_AVAILABLE)\n      private String pollTimeout;\n\n      @Inject\n      @Named(POLL_INITIAL_PERIOD)\n      private String pollPeriod;\n\n      @Inject\n      @Named(POLL_MAX_PERIOD)\n      private String pollMaxPeriod;\n\n      public long pollTimeout() {\n         return Long.parseLong(pollTimeout);\n      }\n\n      public long pollPeriod() {\n         return Long.parseLong(pollPeriod);\n      }\n\n      public long pollMaxPeriod() {\n         return Long.parseLong(pollMaxPeriod);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/compute/function/ProvisionableToImage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.compute.function;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.find;\nimport static org.jclouds.location.predicates.LocationPredicates.idEquals;\n\nimport java.util.Set;\nimport java.util.regex.Pattern;\n\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.ImageBuilder;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.domain.Location;\nimport org.jclouds.profitbricks.domain.OsType;\nimport org.jclouds.profitbricks.domain.ProvisioningState;\nimport org.jclouds.profitbricks.domain.Snapshot;\nimport org.jclouds.profitbricks.domain.Provisionable;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Strings;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.inject.Inject;\n\npublic class ProvisionableToImage implements Function<Provisionable, Image> {\n\n   public static final String KEY_PROVISIONABLE_TYPE = \"provisionableType\";\n\n   private final ImageToImage fnImageToImage;\n   private final SnapshotToImage fnSnapshotToImage;\n\n   @Inject\n   ProvisionableToImage(@Memoized Supplier<Set<? extends Location>> locations) {\n      this.fnImageToImage = new ImageToImage(locations);\n      this.fnSnapshotToImage = new SnapshotToImage(locations);\n   }\n\n   @Override\n   public Image apply(Provisionable input) {\n      checkNotNull(input, \"Cannot convert null input\");\n\n      if (input instanceof org.jclouds.profitbricks.domain.Image)\n         return fnImageToImage.apply((org.jclouds.profitbricks.domain.Image) input);\n\n      else if (input instanceof Snapshot)\n         return fnSnapshotToImage.apply((Snapshot) input);\n\n      else\n         throw new UnsupportedOperationException(\"No implementation found for provisionable of concrete type '\"\n                 + input.getClass().getCanonicalName() + \"'\");\n   }\n\n   private static OsFamily mapOsFamily(OsType osType) {\n      if (osType == null)\n         return OsFamily.UNRECOGNIZED;\n      switch (osType) {\n         case WINDOWS:\n            return OsFamily.WINDOWS;\n         case LINUX:\n            return OsFamily.LINUX;\n         case UNRECOGNIZED:\n         case OTHER:\n         default:\n            return OsFamily.UNRECOGNIZED;\n      }\n   }\n\n   private static class ImageToImage implements ImageFunction<org.jclouds.profitbricks.domain.Image> {\n\n      private static final Pattern HAS_NUMBERS = Pattern.compile(\".*\\\\d+.*\");\n\n      private final Supplier<Set<? extends Location>> locations;\n\n      ImageToImage(Supplier<Set<? extends Location>> locations) {\n         this.locations = locations;\n      }\n\n      @Override\n      public Image apply(org.jclouds.profitbricks.domain.Image from) {\n         String desc = from.name();\n         OsFamily osFamily = parseOsFamily(desc, from.osType());\n         Location location = find(locations.get(), idEquals(from.location().getId()));\n\n         OperatingSystem os = OperatingSystem.builder()\n                 .description(osFamily.value())\n                 .family(osFamily)\n                 .version(parseVersion(desc))\n                 .is64Bit(is64Bit(desc, from.type()))\n                 .build();\n\n         return addTypeMetadata(new ImageBuilder()\n                 .ids(from.id())\n                 .name(desc)\n                 .location(location)\n                 .status(Image.Status.AVAILABLE)\n                 .operatingSystem(os))\n                 .build();\n      }\n\n      private OsFamily parseOsFamily(String from, OsType fallbackValue) {\n         if (from != null)\n            try {\n               // ProfitBricks images names are usually in format:\n               // [osType]-[version]-[subversion]-..-[date-created]\n               String desc = from.toUpperCase().split(\"-\")[0];\n               OsFamily osFamily = OsFamily.fromValue(desc);\n               checkArgument(osFamily != OsFamily.UNRECOGNIZED);\n\n               return osFamily;\n            } catch (Exception ex) {\n               // do nothing\n            }\n         return mapOsFamily(fallbackValue);\n      }\n\n      private String parseVersion(String from) {\n         if (from != null) {\n            String[] split = from.toLowerCase().split(\"-\");\n            if (split.length >= 2) {\n               int i = 1; // usually on second token\n               String version = split[i];\n               while (!HAS_NUMBERS.matcher(version).matches())\n                  version = split[++i];\n               return version;\n            }\n         }\n         return \"\";\n      }\n\n      private boolean is64Bit(String from, org.jclouds.profitbricks.domain.Image.Type type) {\n         switch (type) {\n            case CDROM:\n               if (!Strings.isNullOrEmpty(from))\n                  return from.matches(\"x86_64|amd64\");\n            case HDD: // HDD provided by ProfitBricks are always 64-bit\n            default:\n               return true;\n         }\n      }\n\n      @Override\n      public ImageBuilder addTypeMetadata(ImageBuilder builder) {\n         return builder.userMetadata(ImmutableMap.of(KEY_PROVISIONABLE_TYPE, Provisionable.Type.IMAGE.toString()));\n      }\n   }\n\n   private static class SnapshotToImage implements ImageFunction<Snapshot> {\n\n      private final Supplier<Set<? extends Location>> locations;\n\n      SnapshotToImage(Supplier<Set<? extends Location>> locations) {\n         this.locations = locations;\n      }\n\n      @Override\n      public Image apply(Snapshot from) {\n         String textToParse = from.name() + from.description();\n         OsFamily osFamily = parseOsFamily(textToParse, from.osType());\n         Location location = find(locations.get(), idEquals(from.location().getId()));\n\n         OperatingSystem os = OperatingSystem.builder()\n                 .description(osFamily.value())\n                 .family(osFamily)\n                 .is64Bit(true)\n                 .version(\"00.00\")\n                 .build();\n\n         return addTypeMetadata(new ImageBuilder()\n                 .ids(from.id())\n                 .name(from.name())\n                 .description(from.description())\n                 .location(location)\n                 .status(mapStatus(from.state()))\n                 .operatingSystem(os))\n                 .build();\n      }\n\n      private OsFamily parseOsFamily(String text, OsType fallbackValue) {\n         if (text != null)\n            try {\n               // Attempt parsing OsFamily by scanning name and description\n               // @see ProfitBricksComputeServiceAdapter#L190\n               OsFamily[] families = OsFamily.values();\n               for (OsFamily family : families)\n                  if (text.contains(family.value()))\n                     return family;\n            } catch (Exception ex) {\n               // do nothing\n            }\n         return mapOsFamily(fallbackValue);\n      }\n\n      static Image.Status mapStatus(ProvisioningState state) {\n         if (state == null)\n            return Image.Status.UNRECOGNIZED;\n         switch (state) {\n            case AVAILABLE:\n               return Image.Status.AVAILABLE;\n            case DELETED:\n               return Image.Status.DELETED;\n            case ERROR:\n               return Image.Status.ERROR;\n            case INACTIVE:\n            case INPROCESS:\n               return Image.Status.PENDING;\n            default:\n               return Image.Status.UNRECOGNIZED;\n         }\n      }\n\n      @Override\n      public ImageBuilder addTypeMetadata(ImageBuilder builder) {\n         return builder.userMetadata(ImmutableMap.of(KEY_PROVISIONABLE_TYPE, Provisionable.Type.SNAPSHOT.toString()));\n      }\n   }\n\n   private interface ImageFunction<T extends Provisionable> extends Function<T, Image> {\n\n      ImageBuilder addTypeMetadata(ImageBuilder builder);\n\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/compute/function/ServerToNodeMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.compute.function;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Predicates.not;\nimport static com.google.common.collect.Iterables.find;\nimport static org.jclouds.location.predicates.LocationPredicates.idEquals;\n\nimport java.util.List;\nimport java.util.Set;\n\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.HardwareBuilder;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadataBuilder;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.Processor;\nimport org.jclouds.compute.domain.Volume;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.domain.Location;\nimport org.jclouds.profitbricks.ProfitBricksApi;\nimport org.jclouds.profitbricks.domain.DataCenter;\nimport org.jclouds.profitbricks.domain.Nic;\nimport org.jclouds.profitbricks.domain.OsType;\nimport org.jclouds.profitbricks.domain.Server;\nimport org.jclouds.profitbricks.domain.Storage;\nimport org.jclouds.util.InetAddresses2.IsPrivateIPAddress;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Lists;\nimport com.google.inject.Inject;\n\npublic class ServerToNodeMetadata implements Function<Server, NodeMetadata> {\n\n   private final Function<Storage, Volume> fnVolume;\n   private final Supplier<Set<? extends Location>> locations;\n   private final Function<List<Nic>, List<String>> fnCollectIps;\n   private final ProfitBricksApi api;\n\n   private final GroupNamingConvention groupNamingConvention;\n\n   @Inject\n   ServerToNodeMetadata(Function<Storage, Volume> fnVolume,\n           @Memoized Supplier<Set<? extends Location>> locations,\n           ProfitBricksApi api,\n           GroupNamingConvention.Factory groupNamingConvention) {\n      this.fnVolume = fnVolume;\n      this.locations = locations;\n      this.api = api;\n      this.groupNamingConvention = groupNamingConvention.createWithoutPrefix();\n      this.fnCollectIps = new Function<List<Nic>, List<String>>() {\n         @Override\n         public List<String> apply(List<Nic> in) {\n            List<String> ips = Lists.newArrayListWithExpectedSize(in.size());\n            for (Nic nic : in)\n               ips.addAll(nic.ips());\n            return ips;\n         }\n      };\n   }\n\n   @Override\n   public NodeMetadata apply(final Server server) {\n      checkNotNull(server, \"Null server\");\n      // Location is not populated in the datacenter on a server response\n      DataCenter dataCenter = api.dataCenterApi().getDataCenter(server.dataCenter().id());\n      Location location = find(locations.get(), idEquals(dataCenter.location().getId()));\n\n      float size = 0f;\n      List<Volume> volumes = Lists.newArrayList();\n      List<Storage> storages = server.storages();\n      if (storages != null)\n         for (Storage storage : storages) {\n            size += storage.size();\n            volumes.add(fnVolume.apply(storage));\n         }\n\n      // Build hardware\n      String id = String.format(\"cpu=%d,ram=%d,disk=%.0f\", server.cores(), server.ram(), size);\n      Hardware hardware = new HardwareBuilder()\n              .ids(id)\n              .name(id)\n              .ram(server.ram())\n              .processor(new Processor(server.cores(), 1d))\n              .hypervisor(\"kvm\")\n              .volumes(volumes)\n              .location(location)\n              .build();\n\n      // Collect ips\n      List<String> addresses = fnCollectIps.apply(server.nics());\n\n      // Build node\n      NodeMetadataBuilder nodeBuilder = new NodeMetadataBuilder();\n      nodeBuilder.ids(server.id())\n              .group(groupNamingConvention.extractGroup(server.name()))\n              .hostname(server.hostname())\n              .name(server.name())\n              .backendStatus(server.state().toString())\n              .status(mapStatus(server.status()))\n              .hardware(hardware)\n              .operatingSystem(mapOsType(server.osType()))\n              .location(location)\n              .privateAddresses(Iterables.filter(addresses, IsPrivateIPAddress.INSTANCE))\n              .publicAddresses(Iterables.filter(addresses, not(IsPrivateIPAddress.INSTANCE)));\n\n      return nodeBuilder.build();\n   }\n\n   static NodeMetadata.Status mapStatus(Server.Status status) {\n      if (status == null)\n         return NodeMetadata.Status.UNRECOGNIZED;\n      switch (status) {\n         case SHUTDOWN:\n         case SHUTOFF:\n         case PAUSED:\n            return NodeMetadata.Status.SUSPENDED;\n         case RUNNING:\n            return NodeMetadata.Status.RUNNING;\n         case BLOCKED:\n            return NodeMetadata.Status.PENDING;\n         case CRASHED:\n            return NodeMetadata.Status.ERROR;\n         default:\n            return NodeMetadata.Status.UNRECOGNIZED;\n      }\n   }\n\n   static OperatingSystem mapOsType(OsType osType) {\n      if (osType != null)\n         switch (osType) {\n            case WINDOWS:\n               return OperatingSystem.builder()\n                       .description(OsFamily.WINDOWS.value())\n                       .family(OsFamily.WINDOWS)\n                       .build();\n            case LINUX:\n               return OperatingSystem.builder()\n                       .description(OsFamily.LINUX.value())\n                       .family(OsFamily.LINUX)\n                       .build();\n         }\n      return OperatingSystem.builder()\n              .description(OsFamily.UNRECOGNIZED.value())\n              .family(OsFamily.UNRECOGNIZED)\n              .build();\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/compute/function/StorageToVolume.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.compute.function;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.compute.domain.Volume;\nimport org.jclouds.compute.domain.VolumeBuilder;\nimport org.jclouds.profitbricks.domain.Storage;\n\nimport com.google.common.base.Function;\n\npublic class StorageToVolume implements Function<Storage, Volume> {\n\n   @Override\n   public Volume apply(Storage storage) {\n      checkNotNull(storage, \"Null storage\");\n\n      String device = \"\";\n      if (storage.deviceNumber() != null)\n         device = storage.deviceNumber().toString();\n\n      return new VolumeBuilder()\n              .id(storage.id())\n              .size(storage.size())\n              .bootDevice(storage.bootDevice())\n              .device(device)\n              .durable(true)\n              .type(Volume.Type.LOCAL)\n              .build();\n\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/compute/strategy/AssignDataCenterToTemplate.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.compute.strategy;\n\nimport static com.google.common.collect.Iterables.find;\nimport static org.jclouds.Constants.PROPERTY_USER_THREADS;\nimport static org.jclouds.profitbricks.config.ProfitBricksComputeProperties.POLL_PREDICATE_DATACENTER;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.config.CustomizationResponse;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.compute.strategy.CreateNodeWithGroupEncodedIntoName;\nimport org.jclouds.compute.strategy.CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap;\nimport org.jclouds.compute.strategy.ListNodesStrategy;\nimport org.jclouds.compute.strategy.impl.CreateNodesWithGroupEncodedIntoNameThenAddToSet;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.profitbricks.ProfitBricksApi;\nimport org.jclouds.profitbricks.domain.DataCenter;\nimport org.jclouds.profitbricks.domain.Location;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Multimap;\nimport com.google.common.util.concurrent.ListenableFuture;\nimport com.google.common.util.concurrent.ListeningExecutorService;\n\n/**\n * Attempts to find a valid datacenter in the configured location where the\n * servers will be deployed. If no datacenter is found, one will be created.\n */\n@Beta\n@Singleton\npublic class AssignDataCenterToTemplate extends CreateNodesWithGroupEncodedIntoNameThenAddToSet {\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   private final ProfitBricksApi api;\n   private final Predicate<String> waitDcUntilAvailable;\n\n   @Inject\n   protected AssignDataCenterToTemplate(\n         CreateNodeWithGroupEncodedIntoName addNodeWithGroupStrategy,\n         ListNodesStrategy listNodesStrategy,\n         GroupNamingConvention.Factory namingConvention,\n         @Named(PROPERTY_USER_THREADS) ListeningExecutorService userExecutor,\n         CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap.Factory customizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapFactory,\n         ProfitBricksApi api, @Named(POLL_PREDICATE_DATACENTER) Predicate<String> waitDcUntilAvailable) {\n      super(addNodeWithGroupStrategy, listNodesStrategy, namingConvention, userExecutor,\n            customizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapFactory);\n      this.api = api;\n      this.waitDcUntilAvailable = waitDcUntilAvailable;\n   }\n\n   @Override\n   public Map<?, ListenableFuture<Void>> execute(String group, int count, final Template template,\n         Set<NodeMetadata> goodNodes, Map<NodeMetadata, Exception> badNodes,\n         Multimap<NodeMetadata, CustomizationResponse> customizationResponses) {\n\n      logger.info(\">> looking for a datacenter in %s\", template.getLocation().getId());\n\n      // Try to find an existing datacenter in the selected location\n      DataCenter dataCenter = find(api.dataCenterApi().getAllDataCenters(), new Predicate<DataCenter>() {\n         @Override\n         public boolean apply(DataCenter input) {\n            // The location field is not populated when getting the list of datacenters\n            DataCenter details = api.dataCenterApi().getDataCenter(input.id());\n            return details != null && template.getLocation().getId().equals(details.location().getId());\n         }\n      }, null);\n\n      if (dataCenter == null) {\n         String name = namingConvention.create().sharedNameForGroup(group);\n         logger.info(\">> no datacenter was found. Creating a new one named %s in %s...\", name, template.getLocation()\n               .getId());\n         dataCenter = api.dataCenterApi().createDataCenter(\n               DataCenter.Request.creatingPayload(name, Location.fromId(template.getLocation().getId())));\n         waitDcUntilAvailable.apply(dataCenter.id());\n      }\n\n      return super.execute(group, count, new TemplateWithDataCenter(template, dataCenter), goodNodes, badNodes,\n            customizationResponses);\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/compute/strategy/TemplateWithDataCenter.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.compute.strategy;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.domain.Location;\nimport org.jclouds.profitbricks.domain.DataCenter;\n\nimport com.google.common.annotations.Beta;\n\n/**\n * Extends the default {@link Template} object to provide the {@link DataCenter}\n * where the nodes must be created.\n */\n@Beta\npublic class TemplateWithDataCenter implements Template {\n\n   private final Template delegate;\n\n   private final DataCenter dataCenter;\n\n   // For internal use only\n   TemplateWithDataCenter(Template delegate, DataCenter dataCenter) {\n      this.delegate = checkNotNull(delegate, \"delegate cannot be null\");\n      this.dataCenter = checkNotNull(dataCenter, \"dataCenter cannot be null\");\n   }\n\n   public DataCenter getDataCenter() {\n      return dataCenter;\n   }\n\n   public Template clone() {\n      return new TemplateWithDataCenter(delegate.clone(), dataCenter);\n   }\n\n   public Hardware getHardware() {\n      return delegate.getHardware();\n   }\n\n   public Image getImage() {\n      return delegate.getImage();\n   }\n\n   public Location getLocation() {\n      return delegate.getLocation();\n   }\n\n   public TemplateOptions getOptions() {\n      return delegate.getOptions();\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((dataCenter == null) ? 0 : dataCenter.hashCode());\n      result = prime * result + ((delegate == null) ? 0 : delegate.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      TemplateWithDataCenter other = (TemplateWithDataCenter) obj;\n      if (dataCenter == null) {\n         if (other.dataCenter != null)\n            return false;\n      } else if (!dataCenter.equals(other.dataCenter))\n         return false;\n      if (delegate == null) {\n         if (other.delegate != null)\n            return false;\n      } else if (!delegate.equals(other.delegate))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return delegate.toString();\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/config/ProfitBricksComputeProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.config;\n\npublic class ProfitBricksComputeProperties {\n\n   public static final String POLL_PREDICATE_DATACENTER     = \"jclouds.profitbricks.predicate.datacenter\";\n   public static final String POLL_PREDICATE_SNAPSHOT       = \"jclouds.profitbricks.predicate.snapshot\";\n\n   public static final String TIMEOUT_DATACENTER_AVAILABLE  = \"jclouds.profitbricks.timeout.datacenter-available\";\n   public static final String POLL_INITIAL_PERIOD           = \"jclouds.profitbricks.poll-status.initial-period\";\n   public static final String POLL_MAX_PERIOD               = \"jclouds.profitbricks.poll-status.poll.max-period\";\n\n   private ProfitBricksComputeProperties() {\n      throw new AssertionError(\"Intentionally unimplemented\");\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/config/ProfitBricksHttpApiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.config;\n\nimport org.jclouds.http.HttpCommandExecutorService;\nimport org.jclouds.profitbricks.ProfitBricksApi;\nimport org.jclouds.profitbricks.handlers.ProfitBricksHttpErrorHandler;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.annotation.ClientError;\nimport org.jclouds.http.annotation.Redirection;\nimport org.jclouds.http.annotation.ServerError;\nimport org.jclouds.http.config.ConfiguresHttpCommandExecutorService;\nimport org.jclouds.http.config.SSLModule;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.profitbricks.domain.ServiceFault;\nimport org.jclouds.profitbricks.http.ResponseStatusFromPayloadHttpCommandExecutorService;\nimport org.jclouds.profitbricks.http.parser.ServiceFaultResponseHandler;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.config.HttpApiModule;\n\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Injector;\nimport com.google.inject.Provides;\nimport com.google.inject.Scopes;\n\n/**\n * Configures the ProfitBricks connection.\n */\n@ConfiguresHttpApi\npublic class ProfitBricksHttpApiModule extends HttpApiModule<ProfitBricksApi> {\n\n   @Override\n   protected void bindErrorHandlers() {\n      bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(ProfitBricksHttpErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(ProfitBricksHttpErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(ProfitBricksHttpErrorHandler.class);\n   }\n\n   @ConfiguresHttpCommandExecutorService\n   public static class ProfitBricksHttpCommandExecutorServiceModule extends AbstractModule {\n\n      @Override\n      protected void configure() {\n         install(new SSLModule());\n         bind(HttpCommandExecutorService.class).to(ResponseStatusFromPayloadHttpCommandExecutorService.class)\n                 .in(Scopes.SINGLETON);\n      }\n\n      @Provides\n      public ParseSax<ServiceFault> serviceFaultParser(ParseSax.Factory factory, Injector injector) {\n         return factory.create(injector.getInstance(ServiceFaultResponseHandler.class));\n      }\n\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/domain/AvailabilityZone.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.domain;\n\nimport com.google.common.base.Enums;\n\npublic enum AvailabilityZone {\n\n   AUTO, ZONE_1, ZONE_2, UNRECOGNIZED;\n\n   public String value() {\n      return name();\n   }\n\n   public static AvailabilityZone fromValue(String v) {\n      return Enums.getIfPresent(AvailabilityZone.class, v).or(UNRECOGNIZED);\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/domain/DataCenter.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.domain;\n\nimport static org.jclouds.profitbricks.util.Preconditions.checkInvalidChars;\n\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\n\n@AutoValue\npublic abstract class DataCenter {\n\n   public abstract String id();\n\n   @Nullable\n   public abstract String name();\n\n   public abstract int version();\n\n   @Nullable\n   public abstract ProvisioningState state();\n\n   @Nullable\n   public abstract Location location();\n\n   @Nullable\n   public abstract List<Server> servers();\n\n   @Nullable\n   public abstract List<Storage> storages();\n\n   public static Builder builder() {\n      return new AutoValue_DataCenter.Builder()\n              .servers(ImmutableList.<Server>of())\n              .storages(ImmutableList.<Storage>of());\n   }\n\n   public abstract Builder toBuilder();\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n\n      public abstract Builder id(String id);\n\n      public abstract Builder name(String name);\n\n      public abstract Builder version(int version);\n\n      public abstract Builder state(ProvisioningState state);\n\n      public abstract Builder location(Location location);\n\n      public abstract Builder servers(List<Server> servers);\n\n      public abstract Builder storages(List<Storage> storages);\n\n      abstract DataCenter autoBuild();\n      \n      public DataCenter build(){\n         DataCenter built = autoBuild();\n         return built.toBuilder()\n                 .servers(ImmutableList.copyOf(built.servers()))\n                 .storages(ImmutableList.copyOf(built.storages()))\n                 .autoBuild();\n      }\n\n   }\n\n   public static final class Request {\n\n      public static CreatePayload creatingPayload(String name, Location location) {\n         CreatePayload payload = new AutoValue_DataCenter_Request_CreatePayload(name, location);\n         checkInvalidChars(payload.name());\n\n         return payload;\n      }\n\n      public static UpdatePayload updatingPayload(String id, String name) {\n         UpdatePayload payload = new AutoValue_DataCenter_Request_UpdatePayload(id, name);\n         checkInvalidChars(payload.name());\n\n         return payload;\n      }\n\n      @AutoValue\n      public abstract static class CreatePayload {\n\n         public abstract String name();\n\n         public abstract Location location();\n\n      }\n\n      @AutoValue\n      public abstract static class UpdatePayload {\n\n         public abstract String id();\n\n         public abstract String name();\n\n      }\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/domain/Drive.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.domain;\n\nimport com.google.auto.value.AutoValue;\n\nimport org.jclouds.javax.annotation.Nullable;\n\n@AutoValue\npublic abstract class Drive {\n\n   public abstract static class Request {\n\n      @AutoValue\n      public abstract static class AddRomDriveToServerPayload {\n\n         public abstract String serverId();\n\n         public abstract String imageId();\n\n         @Nullable\n         public abstract String deviceNumber();\n\n         public static Builder builder() {\n            return new AutoValue_Drive_Request_AddRomDriveToServerPayload.Builder();\n         }\n\n         @AutoValue.Builder\n         public abstract static class Builder {\n\n            public abstract Builder serverId(String serverId);\n\n            public abstract Builder imageId(String imageId);\n\n            public abstract Builder deviceNumber(String deviceNumber);\n\n            public abstract AddRomDriveToServerPayload build();\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/domain/Firewall.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.domain;\n\nimport static org.jclouds.profitbricks.util.Preconditions.checkIcmp;\nimport static org.jclouds.profitbricks.util.Preconditions.checkIp;\nimport static org.jclouds.profitbricks.util.Preconditions.checkMacAddress;\nimport static org.jclouds.profitbricks.util.Preconditions.checkPortRange;\n\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.base.Enums;\nimport com.google.common.collect.ImmutableList;\n\n@AutoValue\npublic abstract class Firewall {\n\n   public enum Protocol {\n\n      TCP, UDP, ICMP, ANY, UNRECOGNIZED;\n\n      public static Protocol fromValue(String value) {\n         return Enums.getIfPresent(Protocol.class, value).or(UNRECOGNIZED);\n      }\n   }\n\n   @Nullable\n   public abstract String id();\n\n   @Nullable\n   public abstract String nicId();\n\n   @Nullable\n   public abstract Boolean active();\n\n   @Nullable\n   public abstract ProvisioningState state();\n\n   @Nullable\n   public abstract List<Rule> rules();\n\n   public static Builder builder() {\n      return new AutoValue_Firewall.Builder()\n              .rules(ImmutableList.<Rule>of());\n   }\n\n   public abstract Builder toBuilder();\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n\n      public abstract Builder id(String id);\n\n      public abstract Builder nicId(String nicId);\n\n      public abstract Builder active(Boolean active);\n\n      public abstract Builder state(ProvisioningState state);\n\n      public abstract Builder rules(List<Rule> rules);\n\n      abstract Firewall autoBuild();\n      \n      public Firewall build(){\n         Firewall built = autoBuild();\n         \n         return built.toBuilder()\n                 .rules(ImmutableList.copyOf(built.rules()))\n                 .autoBuild();\n      }\n   }\n\n   public static final class Request {\n\n      public static AddRulePayload createAddRulePayload(String nicId, List<Rule> rules) {\n         return new AutoValue_Firewall_Request_AddRulePayload(nicId, ImmutableList.copyOf(rules));\n      }\n\n      @AutoValue\n      public abstract static class AddRulePayload {\n\n         public abstract String nicId();\n\n         public abstract List<Rule> rules();\n\n      }\n   }\n\n   @AutoValue\n   public abstract static class Rule {\n\n      @Nullable\n      public abstract String id();\n\n      @Nullable\n      public abstract String name();\n\n      @Nullable\n      public abstract Integer portRangeEnd();\n\n      @Nullable\n      public abstract Integer portRangeStart();\n\n      @Nullable\n      public abstract Protocol protocol();\n\n      @Nullable\n      public abstract String sourceIp();\n\n      @Nullable\n      public abstract String sourceMac();\n\n      @Nullable\n      public abstract String targetIp();\n\n      @Nullable\n      public abstract Integer icmpCode();\n\n      @Nullable\n      public abstract Integer icmpType();\n\n      public static Builder builder() {\n         return new AutoValue_Firewall_Rule.Builder()\n                 .protocol(Protocol.ANY);\n      }\n\n      public abstract Builder toBuilder();\n\n      @AutoValue.Builder\n      public abstract static class Builder {\n\n         public abstract Builder id(String id);\n\n         public abstract Builder name(String name);\n\n         public abstract Builder portRangeEnd(Integer portRangeEnd);\n\n         public abstract Builder portRangeStart(Integer portRangeStart);\n\n         public abstract Builder protocol(Protocol protocol);\n\n         public abstract Builder sourceIp(String sourceIp);\n\n         public abstract Builder sourceMac(String sourceMac);\n\n         public abstract Builder targetIp(String targetIp);\n\n         public abstract Builder icmpCode(Integer icmpCode);\n\n         public abstract Builder icmpType(Integer icmpType);\n\n         abstract Rule autoBuild();\n\n         public Rule build() {\n            Rule rule = autoBuild();\n            if (rule.sourceIp() != null)\n               checkIp(rule.sourceIp());\n            if (rule.targetIp() != null)\n               checkIp(rule.targetIp());\n            if (rule.sourceMac() != null)\n               checkMacAddress(rule.sourceMac());\n            checkPortRange(rule.portRangeStart(), rule.portRangeEnd(), rule.protocol());\n            checkIcmp(rule.icmpType(), rule.icmpCode(), rule.protocol());\n\n            return rule;\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/domain/Image.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.domain;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.base.Enums;\n\nimport org.jclouds.javax.annotation.Nullable;\n\n@AutoValue\npublic abstract class Image implements Provisionable {\n\n   public enum Type {\n\n      HDD, CDROM, UNRECOGNIZED;\n\n      public static Type fromValue(String v) {\n         return Enums.getIfPresent(Type.class, v).or(UNRECOGNIZED);\n      }\n   }\n\n   public abstract String id();\n\n   public abstract String name();\n\n   public abstract float size(); // MB\n\n   public abstract Location location();\n\n   public abstract OsType osType();\n\n   public abstract Type type();\n\n   @Nullable\n   public abstract Boolean isPublic();\n\n   @Nullable\n   public abstract Boolean isWriteable();\n\n   @Nullable\n   public abstract Boolean isBootable();\n\n   @Nullable\n   public abstract Boolean isCpuHotPlug();\n\n   @Nullable\n   public abstract Boolean isCpuHotUnPlug();\n\n   @Nullable\n   public abstract Boolean isRamHotPlug();\n\n   @Nullable\n   public abstract Boolean isRamHotUnPlug();\n\n   @Nullable\n   public abstract Boolean isNicHotPlug();\n\n   @Nullable\n   public abstract Boolean isNicHotUnPlug();\n\n   @Nullable\n   public abstract Boolean isDiscVirtioHotPlug();\n\n   @Nullable\n   public abstract Boolean isDiscVirtioHotUnPlug();\n\n   public static Builder builder() {\n      return new AutoValue_Image.Builder();\n   }\n\n   public abstract Builder toBuilder();\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n\n      public abstract Builder id(String id);\n\n      public abstract Builder name(String name);\n\n      public abstract Builder size(float size);\n\n      public abstract Builder location(Location location);\n\n      public abstract Builder osType(OsType osType);\n\n      public abstract Builder type(Type type);\n\n      public abstract Builder isPublic(Boolean isPublic);\n\n      public abstract Builder isWriteable(Boolean isWriteable);\n\n      public abstract Builder isBootable(Boolean isBootable);\n\n      public abstract Builder isCpuHotPlug(Boolean isCpuHotPlug);\n\n      public abstract Builder isCpuHotUnPlug(Boolean isCpuHotUnPlug);\n\n      public abstract Builder isRamHotPlug(Boolean isRamHotPlug);\n\n      public abstract Builder isRamHotUnPlug(Boolean isRamHotUnPlug);\n\n      public abstract Builder isNicHotPlug(Boolean isNicHotPlug);\n\n      public abstract Builder isNicHotUnPlug(Boolean isNicHotUnPlug);\n\n      public abstract Builder isDiscVirtioHotPlug(Boolean isDiscVirtioHotPlug);\n\n      public abstract Builder isDiscVirtioHotUnPlug(Boolean isDiscVirtioHotUnPlug);\n\n      public abstract Image build();\n\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/domain/IpBlock.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.domain;\n\nimport static org.jclouds.profitbricks.util.Preconditions.checkIp;\nimport static org.jclouds.profitbricks.util.Preconditions.checkIps;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\n\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\n\n@AutoValue\npublic abstract class IpBlock {\n\n   public abstract String id();\n\n   public abstract Location location();\n\n   public abstract List<PublicIp> publicIps();\n\n   @Nullable\n   public abstract List<String> ips();\n\n   public static Builder builder() {\n      return new AutoValue_IpBlock.Builder()\n              .publicIps(ImmutableList.<PublicIp>of())\n              .ips(ImmutableList.<String>of());\n   }\n\n   public abstract Builder toBuilder();\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n\n      public abstract Builder id(String id);\n\n      public abstract Builder location(Location location);\n\n      public abstract Builder publicIps(List<PublicIp> publicIps);\n\n      public abstract Builder ips(List<String> ips);\n\n      abstract IpBlock autoBuild();\n\n      public IpBlock build() {\n         IpBlock ipBlock = autoBuild();\n         checkIps(ipBlock.ips());\n\n         return ipBlock.toBuilder()\n                 .publicIps(ImmutableList.copyOf(ipBlock.publicIps()))\n                 .ips(ImmutableList.copyOf(ipBlock.ips()))\n                 .autoBuild();\n      }\n   }\n\n   @AutoValue\n   public abstract static class PublicIp {\n\n      public abstract String ip();\n\n      @Nullable\n      public abstract String nicId();\n\n      public static Builder builder() {\n         return new AutoValue_IpBlock_PublicIp.Builder();\n      }\n\n      @AutoValue.Builder\n      public abstract static class Builder {\n\n         public abstract Builder ip(String ip);\n\n         public abstract Builder nicId(String nicId);\n\n         abstract PublicIp autoBuild();\n\n         public PublicIp build() {\n            PublicIp publicIp = autoBuild();\n            checkIp(publicIp.ip());\n\n            return publicIp;\n         }\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/domain/LoadBalancer.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.domain;\n\nimport static org.jclouds.profitbricks.util.Preconditions.checkIp;\nimport static org.jclouds.profitbricks.util.Preconditions.checkLanId;\n\nimport java.util.Date;\nimport java.util.List;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.base.Enums;\nimport com.google.common.collect.ImmutableList;\n\nimport org.jclouds.javax.annotation.Nullable;\n\n@AutoValue\npublic abstract class LoadBalancer {\n\n   public enum Algorithm {\n\n      ROUND_ROBIN, UNRECOGNIZED;\n\n      public static Algorithm\n              fromValue(String value) {\n         return Enums.getIfPresent(Algorithm.class, value).or(UNRECOGNIZED);\n      }\n   }\n\n   @Nullable\n   public abstract String id();\n\n   @Nullable\n   public abstract String name();\n\n   @Nullable\n   public abstract Algorithm algorithm();\n\n   @Nullable\n   public abstract DataCenter dataCenter();\n\n   @Nullable\n   public abstract Boolean internetAccess();\n\n   @Nullable\n   public abstract String ip();\n\n   @Nullable\n   public abstract Integer lanId();\n\n   @Nullable\n   public abstract ProvisioningState state();\n\n   @Nullable\n   public abstract Date creationTime();\n\n   @Nullable\n   public abstract Date lastModificationTime();\n\n   @Nullable\n   public abstract List<Server> balancedServers();\n\n   @Nullable\n   public abstract List<Firewall> firewalls();\n\n   public static Builder builder() {\n      return new AutoValue_LoadBalancer.Builder()\n              .balancedServers(ImmutableList.<Server>of())\n              .firewalls(ImmutableList.<Firewall>of());\n   }\n\n   public abstract Builder toBuilder();\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n\n      public abstract Builder id(String id);\n\n      public abstract Builder name(String name);\n\n      public abstract Builder algorithm(Algorithm algorithm);\n\n      public abstract Builder dataCenter(DataCenter dataCenter);\n\n      public abstract Builder internetAccess(Boolean internetAccess);\n\n      public abstract Builder ip(String ip);\n\n      public abstract Builder lanId(Integer lanId);\n\n      public abstract Builder creationTime(Date creationTime);\n\n      public abstract Builder state(ProvisioningState state);\n\n      public abstract Builder lastModificationTime(Date lastModificationTime);\n\n      public abstract Builder balancedServers(List<Server> balancedServers);\n\n      public abstract Builder firewalls(List<Firewall> firewalls);\n\n      abstract LoadBalancer autoBuild();\n\n      public LoadBalancer build() {\n         LoadBalancer loadBalancer = autoBuild();\n         if (loadBalancer.ip() != null)\n            checkIp(loadBalancer.ip());\n         if (loadBalancer.lanId() != null)\n            checkLanId(loadBalancer.lanId());\n\n         return loadBalancer.toBuilder()\n                 .balancedServers(ImmutableList.copyOf(loadBalancer.balancedServers()))\n                 .firewalls(ImmutableList.copyOf(loadBalancer.firewalls()))\n                 .autoBuild();\n      }\n   }\n\n   public static final class Request {\n\n      public static CreatePayload.Builder creatingBuilder() {\n         return new AutoValue_LoadBalancer_Request_CreatePayload.Builder()\n                 .serverIds(ImmutableList.<String>of())\n                 .algorithm(Algorithm.ROUND_ROBIN);\n      }\n\n      public static UpdatePayload.Builder updatingBuilder() {\n         return new AutoValue_LoadBalancer_Request_UpdatePayload.Builder()\n                 .algorithm(Algorithm.ROUND_ROBIN);\n      }\n\n      public static RegisterPayload createRegisteringPaylod(String loadBalancerId, List<String> serverIds) {\n         return new AutoValue_LoadBalancer_Request_RegisterPayload(loadBalancerId, ImmutableList.copyOf(serverIds));\n      }\n\n      public static DeregisterPayload createDeregisteringPayload(String loadBalancerId, List<String> serverIds) {\n         return new AutoValue_LoadBalancer_Request_DeregisterPayload(loadBalancerId, ImmutableList.copyOf(serverIds));\n      }\n\n      @AutoValue\n      public abstract static class CreatePayload {\n\n         public abstract String dataCenterId();\n\n         @Nullable\n         public abstract String name();\n\n         public abstract Algorithm algorithm();\n\n         @Nullable\n         public abstract String ip();\n\n         @Nullable\n         public abstract Integer lanId();\n\n         public abstract List<String> serverIds();\n         \n         public abstract Builder toBuilder();\n\n         @AutoValue.Builder\n         public abstract static class Builder {\n\n            public abstract Builder dataCenterId(String dataCenterId);\n\n            public abstract Builder name(String name);\n\n            public abstract Builder algorithm(Algorithm algorithm);\n\n            public abstract Builder ip(String ip);\n\n            public abstract Builder lanId(Integer lanId);\n\n            public abstract Builder serverIds(List<String> serverIds);\n\n            abstract CreatePayload autoBuild();\n\n            public CreatePayload build() {\n               CreatePayload payload = autoBuild();\n               if (payload.ip() != null)\n                  checkIp(payload.ip());\n               if (payload.lanId() != null)\n                  checkLanId(payload.lanId());\n\n               return payload.toBuilder()\n                       .serverIds(ImmutableList.copyOf(payload.serverIds()))\n                       .autoBuild();\n            }\n         }\n      }\n\n      @AutoValue\n      public abstract static class RegisterPayload {\n\n         public abstract String id();\n\n         public abstract List<String> serverIds();\n\n      }\n\n      @AutoValue\n      public abstract static class DeregisterPayload {\n\n         public abstract String id();\n\n         public abstract List<String> serverIds();\n\n      }\n\n      @AutoValue\n      public abstract static class UpdatePayload {\n\n         public abstract String id();\n\n         @Nullable\n         public abstract String name();\n\n         public abstract Algorithm algorithm();\n\n         @Nullable\n         public abstract String ip();\n\n         @AutoValue.Builder\n         public abstract static class Builder {\n\n            public abstract Builder id(String id);\n\n            public abstract Builder name(String name);\n\n            public abstract Builder algorithm(Algorithm algorithm);\n\n            public abstract Builder ip(String ip);\n\n            abstract UpdatePayload autoBuild();\n\n            public UpdatePayload build() {\n               UpdatePayload payload = autoBuild();\n               if (payload.ip() != null)\n                  checkIp(payload.ip());\n\n               return payload;\n            }\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/domain/Location.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.domain;\n\nimport com.google.common.base.Enums;\n\npublic enum Location {\n\n   DE_FKB(\"de/fkb\", \"Germany, Karlsruhe\"),\n   DE_FRA(\"de/fra\", \"Germany, Frankfurt (M)\"),\n   US_LAS(\"us/las\", \"USA, Las Vegas\"),\n   US_LASDEV(\"us/lasdev\", \"USA Developer cluster\"),\n   UNRECOGNIZED(\"unrecognized\", \"Unrecognized location\");\n\n   private final String id;\n   private final String description;\n\n   Location(String id, String description) {\n      this.id = id;\n      this.description = description;\n   }\n\n   public String getId() {\n      return id;\n   }\n\n   public String getDescription() {\n      return description;\n   }\n\n   public static Location fromValue(String v) {\n      return Enums.getIfPresent(Location.class, v).or(UNRECOGNIZED);\n   }\n\n   public static Location fromId(String id) {\n      for (Location location : values())\n         if (location.id.equals(id))\n            return location;\n      return UNRECOGNIZED;\n   }\n\n   @Override\n   public String toString() {\n      return id;\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/domain/Nic.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.domain;\n\nimport static org.jclouds.profitbricks.util.Preconditions.checkIp;\nimport static org.jclouds.profitbricks.util.Preconditions.checkIps;\nimport static org.jclouds.profitbricks.util.Preconditions.checkLanId;\nimport static org.jclouds.profitbricks.util.Preconditions.checkMacAddress;\n\nimport java.util.List;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\n\nimport org.jclouds.javax.annotation.Nullable;\n\n@AutoValue\npublic abstract class Nic {\n\n   @Nullable\n   public abstract String id();\n\n   @Nullable\n   public abstract String name();\n\n   @Nullable\n   public abstract String dataCenterId();\n\n   @Nullable\n   public abstract Integer lanId();\n\n   @Nullable\n   public abstract Boolean internetAccess();\n\n   @Nullable\n   public abstract String serverId();\n\n   @Nullable\n   public abstract List<String> ips();\n\n   @Nullable\n   public abstract String macAddress();\n\n   @Nullable\n   public abstract Firewall firewall();\n\n   @Nullable\n   public abstract Boolean dhcpActive();\n\n   @Nullable\n   public abstract String gatewayIp();\n\n   @Nullable\n   public abstract ProvisioningState state();\n\n   public static Builder builder() {\n      return new AutoValue_Nic.Builder()\n              .ips(ImmutableList.<String>of());\n   }\n\n   public abstract Builder toBuilder();\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n\n      public abstract Builder id(String id);\n\n      public abstract Builder name(String name);\n\n      public abstract Builder dataCenterId(String dataCenterId);\n\n      public abstract Builder lanId(Integer lanId);\n\n      public abstract Builder internetAccess(Boolean internetAccess);\n\n      public abstract Builder serverId(String serverId);\n\n      public abstract Builder ips(List<String> ips);\n\n      public abstract Builder macAddress(String macAddress);\n\n      public abstract Builder firewall(Firewall firewall);\n\n      public abstract Builder dhcpActive(Boolean dhcpActive);\n\n      public abstract Builder gatewayIp(String gatewayIp);\n\n      public abstract Builder state(ProvisioningState state);\n\n      abstract Nic autoBuild();\n\n      public Nic build() {\n         Nic nic = autoBuild();\n         if (nic.ips() != null)\n            checkIps(nic.ips());\n         if (nic.gatewayIp() != null)\n            checkIp(nic.gatewayIp());\n         if (nic.lanId() != null)\n            checkLanId(nic.lanId());\n         if (nic.macAddress() != null)\n            checkMacAddress(nic.macAddress());\n\n         return nic.toBuilder()\n                 .ips(ImmutableList.copyOf(nic.ips()))\n                 .autoBuild();\n      }\n\n   }\n\n   public static final class Request {\n\n      public static CreatePayload.Builder creatingBuilder() {\n         return new AutoValue_Nic_Request_CreatePayload.Builder();\n      }\n\n      public static UpdatePayload.Builder updatingBuilder() {\n         return new AutoValue_Nic_Request_UpdatePayload.Builder();\n      }\n\n      public static SetInternetAccessPayload.Builder setInternetAccessBuilder() {\n         return new AutoValue_Nic_Request_SetInternetAccessPayload.Builder();\n      }\n\n      @AutoValue\n      public abstract static class CreatePayload {\n\n         public abstract String serverId();\n\n         public abstract int lanId();\n\n         @Nullable\n         public abstract String ip();\n\n         @Nullable\n         public abstract String name();\n\n         @Nullable\n         public abstract Boolean dhcpActive();\n\n         @AutoValue.Builder\n         public abstract static class Builder {\n\n            public abstract Builder serverId(String serverId);\n\n            public abstract Builder lanId(int lanId);\n\n            public abstract Builder ip(String ip);\n\n            public abstract Builder name(String name);\n\n            public abstract Builder dhcpActive(Boolean dhcpActive);\n\n            abstract CreatePayload autoBuild();\n\n            public CreatePayload build() {\n               CreatePayload payload = autoBuild();\n               if (payload.ip() != null)\n                  checkIp(payload.ip());\n               checkLanId(payload.lanId());\n\n               return payload;\n            }\n         }\n      }\n\n      @AutoValue\n      public abstract static class UpdatePayload {\n\n         public abstract String id();\n\n         @Nullable\n         public abstract String ip();\n\n         @Nullable\n         public abstract String name();\n\n         @Nullable\n         public abstract Boolean dhcpActive();\n\n         @Nullable\n         public abstract Integer lanId();\n\n         @AutoValue.Builder\n         public abstract static class Builder {\n\n            public abstract Builder id(String id);\n\n            public abstract Builder ip(String ip);\n\n            public abstract Builder name(String name);\n\n            public abstract Builder dhcpActive(Boolean dhcpActive);\n\n            public abstract Builder lanId(Integer lanId);\n\n            abstract UpdatePayload autoBuild();\n\n            public UpdatePayload build() {\n               UpdatePayload payload = autoBuild();\n               if (payload.ip() != null)\n                  checkIp(payload.ip());\n               if (payload.lanId() != null)\n                  checkLanId(payload.lanId());\n\n               return payload;\n            }\n         }\n      }\n\n      @AutoValue\n      public abstract static class SetInternetAccessPayload {\n\n         public abstract String dataCenterId();\n\n         public abstract int lanId();\n\n         public abstract boolean internetAccess();\n\n         @AutoValue.Builder\n         public abstract static class Builder {\n\n            public abstract Builder dataCenterId(String dataCenterId);\n\n            public abstract Builder lanId(int lanId);\n\n            public abstract Builder internetAccess(boolean internetAccess);\n\n            public abstract SetInternetAccessPayload build();\n\n         }\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/domain/OsType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.domain;\n\nimport com.google.common.base.Enums;\n\npublic enum OsType {\n\n   WINDOWS, LINUX, OTHER, UNRECOGNIZED;\n\n   public static OsType fromValue(String v) {\n      return Enums.getIfPresent(OsType.class, v).or(UNRECOGNIZED);\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/domain/Provisionable.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.domain;\n\nimport com.google.common.base.Enums;\n\n/**\n * Marker interface for {@link org.jclouds.profitbricks.domain.Image} and\n * {@link org.jclouds.profitbricks.domain.Snapshot}\n */\npublic interface Provisionable {\n\n   public enum Type {\n\n      IMAGE, SNAPSHOT;\n\n      public static Type fromValue(String v) {\n         return Enums.getIfPresent(Type.class, v).or(IMAGE);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/domain/ProvisioningState.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.domain;\n\nimport com.google.common.base.Enums;\n\npublic enum ProvisioningState {\n\n   INACTIVE, INPROCESS, AVAILABLE, DELETED, ERROR, UNRECOGNIZED;\n\n   public static ProvisioningState fromValue(String value) {\n      return Enums.getIfPresent(ProvisioningState.class, value).or(UNRECOGNIZED);\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/domain/Server.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.domain;\n\nimport static org.jclouds.profitbricks.util.Preconditions.checkCores;\nimport static org.jclouds.profitbricks.util.Preconditions.checkRam;\n\nimport java.util.Date;\nimport java.util.List;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.base.Enums;\nimport com.google.common.collect.ImmutableList;\n\nimport org.jclouds.javax.annotation.Nullable;\n\n@AutoValue\npublic abstract class Server {\n\n   public enum Status {\n\n      NOSTATE, RUNNING, BLOCKED, PAUSED, SHUTDOWN, SHUTOFF, CRASHED, UNRECOGNIZED;\n\n      public String value() {\n         return name();\n      }\n\n      public static Status fromValue(String v) {\n         return Enums.getIfPresent(Status.class, v).or(UNRECOGNIZED);\n      }\n   }\n\n   @Nullable\n   public abstract DataCenter dataCenter();\n\n   @Nullable\n   public abstract String id();\n\n   @Nullable\n   public abstract String name();\n\n   @Nullable\n   public abstract Integer cores();\n\n   @Nullable\n   public abstract Integer ram();\n\n   @Nullable\n   public abstract Boolean hasInternetAccess();\n\n   @Nullable\n   public abstract ProvisioningState state();\n\n   @Nullable\n   public abstract Status status();\n\n   @Nullable\n   public abstract OsType osType();\n\n   @Nullable\n   public abstract AvailabilityZone availabilityZone();\n\n   @Nullable\n   public abstract Date creationTime();\n\n   @Nullable\n   public abstract Date lastModificationTime();\n\n   @Nullable\n   public abstract List<Storage> storages();\n\n   @Nullable\n   public abstract List<Nic> nics();\n\n   @Nullable\n   public abstract String balancedNicId();\n\n   @Nullable\n   public abstract Boolean loadBalanced();\n\n   @Nullable\n   public abstract Boolean isCpuHotPlug();\n\n   @Nullable\n   public abstract Boolean isCpuHotUnPlug();\n\n   @Nullable\n   public abstract Boolean isRamHotPlug();\n\n   @Nullable\n   public abstract Boolean isRamHotUnPlug();\n\n   @Nullable\n   public abstract Boolean isNicHotPlug();\n\n   @Nullable\n   public abstract Boolean isNicHotUnPlug();\n\n   @Nullable\n   public abstract Boolean isDiscVirtioHotPlug();\n\n   @Nullable\n   public abstract Boolean isDiscVirtioHotUnPlug();\n\n   @Nullable\n   public abstract String hostname(); // Non-profitbricks property; Added to hold hostname parsed from image temporarily\n\n   public static Builder builder() {\n      return new AutoValue_Server.Builder()\n              .storages(ImmutableList.<Storage>of())\n              .nics(ImmutableList.<Nic>of());\n   }\n\n   public abstract Builder toBuilder();\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n\n      public abstract Builder dataCenter(DataCenter dataCenter);\n\n      public abstract Builder id(String id);\n\n      public abstract Builder name(String name);\n\n      public abstract Builder cores(Integer cores);\n\n      public abstract Builder ram(Integer ram);\n\n      public abstract Builder hasInternetAccess(Boolean internetAccess);\n\n      public abstract Builder state(ProvisioningState state);\n\n      public abstract Builder status(Status status);\n\n      public abstract Builder osType(OsType osType);\n\n      public abstract Builder availabilityZone(AvailabilityZone availabilityZone);\n\n      public abstract Builder creationTime(Date creationTime);\n\n      public abstract Builder lastModificationTime(Date lastModificationTime);\n\n      public abstract Builder storages(List<Storage> storages);\n\n      public abstract Builder nics(List<Nic> nics);\n\n      public abstract Builder balancedNicId(String balancedNicIds);\n\n      public abstract Builder loadBalanced(Boolean isLoadBalanced);\n\n      public abstract Builder isCpuHotPlug(Boolean isCpuHotPlug);\n\n      public abstract Builder isCpuHotUnPlug(Boolean isCpuHotUnPlug);\n\n      public abstract Builder isRamHotPlug(Boolean isRamHotPlug);\n\n      public abstract Builder isRamHotUnPlug(Boolean isRamHotUnPlug);\n\n      public abstract Builder isNicHotPlug(Boolean isNicHotPlug);\n\n      public abstract Builder isNicHotUnPlug(Boolean isNicHotUnPlug);\n\n      public abstract Builder isDiscVirtioHotPlug(Boolean isDiscVirtioHotPlug);\n\n      public abstract Builder isDiscVirtioHotUnPlug(Boolean isDiscVirtioHotUnPlug);\n\n      public abstract Builder hostname(String hostname);\n\n      abstract Server autoBuild();\n\n      public Server build() {\n         Server server = autoBuild();\n         if (server.cores() != null)\n            checkCores(server.cores());\n         if (server.ram() != null)\n            checkRam(server.ram(), server.isRamHotUnPlug());\n         return server.toBuilder()\n                 .storages(ImmutableList.copyOf(server.storages()))\n                 .nics(ImmutableList.copyOf(server.nics()))\n                 .autoBuild();\n      }\n   }\n\n   public static final class Request {\n\n      public static CreatePayload.Builder creatingBuilder() {\n         return new AutoValue_Server_Request_CreatePayload.Builder();\n      }\n\n      public static UpdatePayload.Builder updatingBuilder() {\n         return new AutoValue_Server_Request_UpdatePayload.Builder();\n      }\n\n      @AutoValue\n      public abstract static class CreatePayload {\n\n         public abstract int cores();\n\n         public abstract int ram();\n\n         public abstract String dataCenterId();\n\n         public abstract String name();\n\n         @Nullable\n         public abstract String bootFromStorageId();\n\n         @Nullable\n         public abstract String bootFromImageId();\n\n         @Nullable\n         public abstract Integer lanId();\n\n         @Nullable\n         public abstract Boolean hasInternetAccess();\n\n         @Nullable\n         public abstract AvailabilityZone availabilityZone();\n\n         @Nullable\n         public abstract OsType osType();\n\n         @Nullable\n         public abstract Boolean isCpuHotPlug();\n\n         @Nullable\n         public abstract Boolean isCpuHotUnPlug();\n\n         @Nullable\n         public abstract Boolean isRamHotPlug();\n\n         @Nullable\n         public abstract Boolean isRamHotUnPlug();\n\n         @Nullable\n         public abstract Boolean isNicHotPlug();\n\n         @Nullable\n         public abstract Boolean isNicHotUnPlug();\n\n         @Nullable\n         public abstract Boolean isDiscVirtioHotPlug();\n\n         @Nullable\n         public abstract Boolean isDiscVirtioHotUnPlug();\n\n         @AutoValue.Builder\n         public abstract static class Builder {\n\n            public abstract Builder cores(int cores);\n\n            public abstract Builder ram(int ram);\n\n            public abstract Builder dataCenterId(String dataCenterId);\n\n            public abstract Builder name(String name);\n\n            public abstract Builder bootFromStorageId(String bootFromStorageId);\n\n            public abstract Builder bootFromImageId(String bootFromImageId);\n\n            public abstract Builder lanId(Integer lanId);\n\n            public abstract Builder hasInternetAccess(Boolean hasInternetAccess);\n\n            public abstract Builder availabilityZone(AvailabilityZone availabilityZone);\n\n            public abstract Builder osType(OsType osType);\n\n            public abstract Builder isCpuHotPlug(Boolean isCpuHotPlug);\n\n            public abstract Builder isCpuHotUnPlug(Boolean isCpuHotUnPlug);\n\n            public abstract Builder isRamHotPlug(Boolean isRamHotPlug);\n\n            public abstract Builder isRamHotUnPlug(Boolean isRamHotUnPlug);\n\n            public abstract Builder isNicHotPlug(Boolean isNicHotPlug);\n\n            public abstract Builder isNicHotUnPlug(Boolean isNicHotUnPlug);\n\n            public abstract Builder isDiscVirtioHotPlug(Boolean isDiscVirtioHotPlug);\n\n            public abstract Builder isDiscVirtioHotUnPlug(Boolean isDiscVirtioHotUnPlug);\n\n            abstract CreatePayload autoBuild();\n\n            public CreatePayload build() {\n               CreatePayload payload = autoBuild();\n               checkCores(payload.cores());\n               checkRam(payload.ram(), payload.isRamHotUnPlug());\n               return payload;\n            }\n         }\n\n      }\n\n      @AutoValue\n      public abstract static class UpdatePayload {\n\n         public abstract String id();\n\n         @Nullable\n         public abstract Integer cores();\n\n         @Nullable\n         public abstract Integer ram();\n\n         @Nullable\n         public abstract String name();\n\n         @Nullable\n         public abstract String bootFromStorageId();\n\n         @Nullable\n         public abstract String bootFromImageId();\n\n         @Nullable\n         public abstract AvailabilityZone availabilityZone();\n\n         @Nullable\n         public abstract OsType osType();\n\n         @Nullable\n         public abstract Boolean isCpuHotPlug();\n\n         @Nullable\n         public abstract Boolean isCpuHotUnPlug();\n\n         @Nullable\n         public abstract Boolean isRamHotPlug();\n\n         @Nullable\n         public abstract Boolean isRamHotUnPlug();\n\n         @Nullable\n         public abstract Boolean isNicHotPlug();\n\n         @Nullable\n         public abstract Boolean isNicHotUnPlug();\n\n         @Nullable\n         public abstract Boolean isDiscVirtioHotPlug();\n\n         @Nullable\n         public abstract Boolean isDiscVirtioHotUnPlug();\n\n         @AutoValue.Builder\n         public abstract static class Builder {\n\n            public abstract Builder id(String id);\n\n            public abstract Builder cores(Integer cores);\n\n            public abstract Builder ram(Integer ram);\n\n            public abstract Builder name(String name);\n\n            public abstract Builder bootFromStorageId(String bootFromStorageId);\n\n            public abstract Builder bootFromImageId(String bootFromImageId);\n\n            public abstract Builder availabilityZone(AvailabilityZone availabilityZone);\n\n            public abstract Builder osType(OsType osType);\n\n            public abstract Builder isCpuHotPlug(Boolean isCpuHotPlug);\n\n            public abstract Builder isCpuHotUnPlug(Boolean isCpuHotUnPlug);\n\n            public abstract Builder isRamHotPlug(Boolean isRamHotPlug);\n\n            public abstract Builder isRamHotUnPlug(Boolean isRamHotUnPlug);\n\n            public abstract Builder isNicHotPlug(Boolean isNicHotPlug);\n\n            public abstract Builder isNicHotUnPlug(Boolean isNicHotUnPlug);\n\n            public abstract Builder isDiscVirtioHotPlug(Boolean isDiscVirtioHotPlug);\n\n            public abstract Builder isDiscVirtioHotUnPlug(Boolean isDiscVirtioHotUnPlug);\n\n            abstract UpdatePayload autoBuild();\n\n            public UpdatePayload build() {\n               UpdatePayload payload = autoBuild();\n               if (payload.cores() != null)\n                  checkCores(payload.cores());\n               if (payload.ram() != null)\n                  checkRam(payload.ram(), payload.isRamHotUnPlug());\n               return payload;\n            }\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/domain/ServiceFault.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.domain;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.base.Enums;\n\n@AutoValue\npublic abstract class ServiceFault {\n\n   public abstract String faultCode();\n   public abstract String faultString();\n   @Nullable public abstract Details details();\n   \n   public static Builder builder() {\n      return new AutoValue_ServiceFault.Builder();\n   }\n   \n   @AutoValue.Builder\n   public abstract static class Builder {\n      public abstract Builder faultCode(String faultCode);\n      public abstract Builder faultString(String faultString);\n      public abstract Builder details(Details details);\n      public abstract ServiceFault build();\n   }\n   \n   @AutoValue\n   public abstract static class Details {\n   \n      public enum FaultCode {\n   \n         BAD_REQUEST,\n         UNEXPECTED,\n         UNAUTHORIZED,\n         RESOURCE_NOT_FOUND,\n         RESOURCE_DELETED,\n         PROVISIONING_IN_PROCESS,\n         PROVISIONING_NO_CHANGES,\n         OVER_LIMIT_SETTING,\n         SERVER_EXCEED_CAPACITY,\n         SERVICE_UNAVAILABLE,\n         UNRECOGNIZED;\n   \n         public static FaultCode fromValue(String v) {\n            return Enums.getIfPresent(FaultCode.class, v).or(UNRECOGNIZED);\n         }\n      }\n   \n      public abstract FaultCode faultCode();\n      public abstract int httpCode();\n      public abstract String message();\n      public abstract int requestId();\n   \n      public static Builder builder() {\n         return new AutoValue_ServiceFault_Details.Builder();\n      }\n   \n      @AutoValue.Builder\n      public abstract static class Builder {\n         public abstract Builder faultCode(FaultCode faultCode);\n         public abstract Builder httpCode(int httpCode);\n         public abstract Builder message(String message);\n         public abstract Builder requestId(int requestId);\n         public abstract Details build();\n      }\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/domain/Snapshot.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.domain;\n\nimport java.util.Date;\n\nimport com.google.auto.value.AutoValue;\n\nimport org.jclouds.javax.annotation.Nullable;\n\n@AutoValue\npublic abstract class Snapshot implements Provisionable {\n\n   @Nullable\n   public abstract String id();\n\n   @Nullable\n   public abstract String name();\n\n   @Nullable\n   public abstract Float size();\n\n   @Nullable\n   public abstract Location location();\n\n   @Nullable\n   public abstract OsType osType();\n\n   @Nullable\n   public abstract Boolean isBootable();\n\n   @Nullable\n   public abstract String description();\n\n   @Nullable\n   public abstract Date creationTime();\n\n   @Nullable\n   public abstract Date lastModificationTime();\n\n   @Nullable\n   public abstract ProvisioningState state();\n\n   @Nullable\n   public abstract Boolean isCpuHotPlug();\n\n   @Nullable\n   public abstract Boolean isCpuHotUnPlug();\n\n   @Nullable\n   public abstract Boolean isRamHotPlug();\n\n   @Nullable\n   public abstract Boolean isRamHotUnPlug();\n\n   @Nullable\n   public abstract Boolean isNicHotPlug();\n\n   @Nullable\n   public abstract Boolean isNicHotUnPlug();\n\n   @Nullable\n   public abstract Boolean isDiscVirtioHotPlug();\n\n   @Nullable\n   public abstract Boolean isDiscVirtioHotUnPlug();\n\n   public static Builder builder() {\n      return new AutoValue_Snapshot.Builder();\n   }\n\n   public abstract Builder toBuilder();\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n\n      public abstract Builder id(String id);\n\n      public abstract Builder name(String name);\n\n      public abstract Builder size(Float size);\n\n      public abstract Builder location(Location location);\n\n      public abstract Builder osType(OsType osType);\n\n      public abstract Builder isBootable(Boolean bootable);\n\n      public abstract Builder description(String description);\n\n      public abstract Builder creationTime(Date creationTime);\n\n      public abstract Builder lastModificationTime(Date lastModificationTime);\n\n      public abstract Builder state(ProvisioningState state);\n\n      public abstract Builder isCpuHotPlug(Boolean isCpuHotPlug);\n\n      public abstract Builder isCpuHotUnPlug(Boolean isCpuHotUnPlug);\n\n      public abstract Builder isRamHotPlug(Boolean isRamHotPlug);\n\n      public abstract Builder isRamHotUnPlug(Boolean isRamHotUnPlug);\n\n      public abstract Builder isNicHotPlug(Boolean isNicHotPlug);\n\n      public abstract Builder isNicHotUnPlug(Boolean isNicHotUnPlug);\n\n      public abstract Builder isDiscVirtioHotPlug(Boolean isDiscVirtioHotPlug);\n\n      public abstract Builder isDiscVirtioHotUnPlug(Boolean isDiscVirtioHotUnPlug);\n\n      public abstract Snapshot build();\n   }\n\n   public static final class Request {\n\n      public static CreatePayload.Builder creatingBuilder() {\n         return new AutoValue_Snapshot_Request_CreatePayload.Builder();\n      }\n\n      public static UpdatePayload.Builder updatingBuilder() {\n         return new AutoValue_Snapshot_Request_UpdatePayload.Builder();\n      }\n\n      public static RollbackPayload createRollbackPayload(String snapshotId, String storageId) {\n         return new AutoValue_Snapshot_Request_RollbackPayload(snapshotId, storageId);\n      }\n\n      @AutoValue\n      public abstract static class CreatePayload {\n\n         public abstract String storageId();\n\n         public abstract String name();\n\n         @Nullable\n         public abstract String description();\n\n         @AutoValue.Builder\n         public abstract static class Builder {\n\n            public abstract Builder storageId(String storageId);\n\n            public abstract Builder name(String name);\n\n            public abstract Builder description(String description);\n\n            public abstract CreatePayload build();\n         }\n      }\n\n      @AutoValue\n      public abstract static class UpdatePayload {\n\n         public abstract String id();\n\n         @Nullable\n         public abstract String description();\n\n         @Nullable\n         public abstract String name();\n\n         @Nullable\n         public abstract Boolean bootable();\n\n         @Nullable\n         public abstract OsType osType();\n\n         @Nullable\n         public abstract Boolean isCpuHotPlug();\n\n         @Nullable\n         public abstract Boolean isCpuHotUnPlug();\n\n         @Nullable\n         public abstract Boolean isRamHotPlug();\n\n         @Nullable\n         public abstract Boolean isRamHotUnPlug();\n\n         @Nullable\n         public abstract Boolean isNicHotPlug();\n\n         @Nullable\n         public abstract Boolean isNicHotUnPlug();\n\n         @Nullable\n         public abstract Boolean isDiscVirtioHotPlug();\n\n         @Nullable\n         public abstract Boolean isDiscVirtioHotUnPlug();\n\n         @AutoValue.Builder\n         public abstract static class Builder {\n\n            public abstract Builder id(String snapshotId);\n\n            public abstract Builder description(String description);\n\n            public abstract Builder name(String name);\n\n            public abstract Builder bootable(Boolean bootable);\n\n            public abstract Builder osType(OsType osType);\n\n            public abstract Builder isCpuHotPlug(Boolean isCpuHotPlug);\n\n            public abstract Builder isCpuHotUnPlug(Boolean isCpuHotUnPlug);\n\n            public abstract Builder isRamHotPlug(Boolean isRamHotPlug);\n\n            public abstract Builder isRamHotUnPlug(Boolean isRamHotUnPlug);\n\n            public abstract Builder isNicHotPlug(Boolean isNicHotPlug);\n\n            public abstract Builder isNicHotUnPlug(Boolean isNicHotUnPlug);\n\n            public abstract Builder isDiscVirtioHotPlug(Boolean isDiscVirtioHotPlug);\n\n            public abstract Builder isDiscVirtioHotUnPlug(Boolean isDiscVirtioHotUnPlug);\n\n            public abstract UpdatePayload build();\n         }\n\n      }\n\n      @AutoValue\n      public abstract static class RollbackPayload {\n\n         public abstract String snapshotId();\n\n         public abstract String storageId();\n\n      }\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/domain/Storage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.domain;\n\nimport static org.jclouds.profitbricks.util.Preconditions.checkPassword;\nimport static org.jclouds.profitbricks.util.Preconditions.checkSize;\n\nimport java.util.Date;\nimport java.util.List;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.base.Enums;\nimport com.google.common.collect.ImmutableList;\nimport org.jclouds.javax.annotation.Nullable;\n\n\n@AutoValue\npublic abstract class Storage {\n\n   public enum BusType {\n\n      IDE, SCSI, VIRTIO, UNRECOGNIZED;\n\n      public static BusType fromValue(String value) {\n         return Enums.getIfPresent(BusType.class, value).or(UNRECOGNIZED);\n      }\n   }\n\n   public abstract String id();\n\n   @Nullable\n   public abstract String name();\n\n   public abstract float size(); // GB\n\n   @Nullable\n   public abstract Date creationTime();\n\n   @Nullable\n   public abstract Date lastModificationTime();\n\n   @Nullable\n   public abstract ProvisioningState state();\n\n   @Nullable\n   public abstract List<String> serverIds();\n\n   @Nullable\n   public abstract Boolean bootDevice();\n\n   @Nullable\n   public abstract BusType busType();\n\n   @Nullable\n   public abstract Integer deviceNumber();\n\n   public static Builder builder() {\n      return new AutoValue_Storage.Builder()\n              .serverIds(ImmutableList.<String>of());\n   }\n\n   public abstract Builder toBuilder();\n\n   @AutoValue.Builder\n   public abstract static class Builder {\n\n      public abstract Builder id(String id);\n\n      public abstract Builder name(String name);\n\n      public abstract Builder size(float size);\n\n      public abstract Builder creationTime(Date creationTime);\n\n      public abstract Builder lastModificationTime(Date lastModificationTime);\n\n      public abstract Builder state(ProvisioningState state);\n\n      public abstract Builder serverIds(List<String> serverIds);\n\n      public abstract Builder bootDevice(Boolean bootDevice);\n\n      public abstract Builder busType(BusType busType);\n\n      public abstract Builder deviceNumber(Integer deviceNumber);\n\n      abstract Storage autoBuild();\n      \n      public Storage build(){\n         Storage built = autoBuild();\n         return built.toBuilder()\n                 .serverIds(ImmutableList.copyOf(built.serverIds()))\n                 .autoBuild();\n      }\n\n   }\n\n   public static final class Request {\n\n      public static CreatePayload.Builder creatingBuilder() {\n         return new AutoValue_Storage_Request_CreatePayload.Builder();\n      }\n\n      public static UpdatePayload.Builder updatingBuilder() {\n         return new AutoValue_Storage_Request_UpdatePayload.Builder();\n      }\n\n      public static ConnectPayload.Builder connectingBuilder() {\n         return new AutoValue_Storage_Request_ConnectPayload.Builder();\n      }\n\n      @AutoValue\n      public abstract static class CreatePayload {\n\n         public abstract String dataCenterId();\n\n         public abstract float size();\n\n         @Nullable\n         public abstract String name();\n\n         @Nullable\n         public abstract String mountImageId();\n\n         @Nullable\n         public abstract String imagePassword();\n\n         @AutoValue.Builder\n         public abstract static class Builder {\n\n            public abstract Builder dataCenterId(String dataCenterId);\n\n            public abstract Builder size(float size);\n\n            public abstract Builder name(String name);\n\n            public abstract Builder mountImageId(String mountImageId);\n\n            public abstract Builder imagePassword(String profitBricksImagePassword);\n\n            abstract CreatePayload autoBuild();\n\n            public CreatePayload build() {\n               CreatePayload payload = autoBuild();\n               if (payload.imagePassword() != null)\n                  checkPassword(payload.imagePassword());\n               checkSize(payload.size());\n\n               return payload;\n            }\n         }\n      }\n\n      @AutoValue\n      public abstract static class UpdatePayload {\n\n         public abstract String id();\n\n         @Nullable\n         public abstract Float size();\n\n         @Nullable\n         public abstract String name();\n\n         @Nullable\n         public abstract String mountImageId();\n\n         @AutoValue.Builder\n         public abstract static class Builder {\n\n            public abstract Builder id(String id);\n\n            public abstract Builder size(Float size);\n\n            public abstract Builder name(String name);\n\n            public abstract Builder mountImageId(String mountImageId);\n\n            abstract UpdatePayload autoBuild();\n\n            public UpdatePayload build() {\n               UpdatePayload payload = autoBuild();\n               if (payload.size() != null)\n                  checkSize(payload.size());\n\n               return payload;\n            }\n         }\n      }\n\n      @AutoValue\n      public abstract static class ConnectPayload {\n\n         public abstract String storageId();\n\n         public abstract String serverId();\n\n         @Nullable\n         public abstract BusType busType();\n\n         @Nullable\n         public abstract Integer deviceNumber();\n\n         @AutoValue.Builder\n         public abstract static class Builder {\n\n            public abstract Builder storageId(String storageId);\n\n            public abstract Builder serverId(String serverId);\n\n            public abstract Builder busType(BusType busType);\n\n            public abstract Builder deviceNumber(Integer deviceNumber);\n\n            public abstract ConnectPayload build();\n         }\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/features/DataCenterApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.features;\n\nimport java.util.List;\nimport jakarta.inject.Named;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks;\nimport org.jclouds.http.filters.BasicAuthentication;\nimport org.jclouds.profitbricks.binder.datacenter.CreateDataCenterRequestBinder;\nimport org.jclouds.profitbricks.binder.datacenter.UpdateDataCenterRequestBinder;\nimport org.jclouds.profitbricks.domain.DataCenter;\nimport org.jclouds.profitbricks.domain.ProvisioningState;\nimport org.jclouds.profitbricks.http.filters.ProfitBricksSoapMessageEnvelope;\nimport org.jclouds.profitbricks.http.parser.datacenter.DataCenterInfoResponseHandler;\nimport org.jclouds.profitbricks.http.parser.datacenter.DataCenterListResponseHandler;\nimport org.jclouds.profitbricks.http.parser.state.GetProvisioningStateResponseHandler;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.XMLResponseParser;\n\n@RequestFilters({BasicAuthentication.class, ProfitBricksSoapMessageEnvelope.class})\n@Consumes(MediaType.TEXT_XML)\n@Produces(MediaType.TEXT_XML)\npublic interface DataCenterApi {\n\n   /**\n    * @return Returns a list of all Virtual Data Centers created by the user, including ID, name and version number.\n    */\n   @POST\n   @Named(\"datacenter:getall\")\n   @Payload(\"<ws:getAllDataCenters/>\")\n   @XMLResponseParser(DataCenterListResponseHandler.class)\n   @Fallback(Fallbacks.EmptyListOnNotFoundOr404.class)\n   List<DataCenter> getAllDataCenters();\n\n   /**\n    * @param identifier Data Center identifier\n    * @return Returns information about an existing virtual data center's state and configuration or <code>null</code>\n    * if it doesn't exist.\n    */\n   @POST\n   @Named(\"datacenter:get\")\n   @Payload(\"<ws:getDataCenter><dataCenterId>{id}</dataCenterId></ws:getDataCenter>\")\n   @XMLResponseParser(DataCenterInfoResponseHandler.class)\n   @Fallback(Fallbacks.NullOnNotFoundOr404.class)\n   DataCenter getDataCenter(@PayloadParam(\"id\") String identifier);\n\n   /**\n    * This is a lightweight function for polling the current provisioning state of the Virtual Data Center. It is\n    * recommended to use this function for large Virtual Data Centers to query request results.\n    * <p>\n    * @param identifier Data Center identifier\n    */\n   @POST\n   @Named(\"datacenter:getstate\")\n   @Payload(\"<ws:getDataCenterState><dataCenterId>{id}</dataCenterId></ws:getDataCenterState>\")\n   @XMLResponseParser(GetProvisioningStateResponseHandler.class)\n   ProvisioningState getDataCenterState(@PayloadParam(\"id\") String identifier);\n\n   /**\n    * Creates and saves a new, empty Virtual Data Center. Returns its identifier for further reference.\n    * <p>\n    * <b>Note: </b>Data center names cannot start with or contain (@, /, \\, |, ‘’, ‘)\n    * <p>\n    * @param createRequest VDC payload containing dataCenterName, region\n    * @return Response containing requestId, dataCenterId, version, and location\n    */\n   @POST\n   @Named(\"datacenter:create\")\n   @MapBinder(CreateDataCenterRequestBinder.class)\n   @XMLResponseParser(DataCenterInfoResponseHandler.class)\n   DataCenter createDataCenter(@PayloadParam(\"dataCenter\") DataCenter.Request.CreatePayload createRequest);\n\n   /**\n    * Updates the information associated to an existing Virtual Data Center.\n    * <p>\n    * @param updateRequest VDC payload containing dataCenterId, and name\n    * @return Response containing requestId, dataCenterId, version\n    */\n   @POST\n   @Named(\"datacenter:update\")\n   @MapBinder(UpdateDataCenterRequestBinder.class)\n   @XMLResponseParser(DataCenterInfoResponseHandler.class)\n   DataCenter updateDataCenter(@PayloadParam(\"dataCenter\") DataCenter.Request.UpdatePayload updateRequest);\n\n   /**\n    * Removes all components from an existing Virtual Data Center.\n    * <p>\n    * @param identifier Identifier of the virtual data center\n    * @return Response containing requestId, dataCenterId, version\n    */\n   @POST\n   @Named(\"datacenter:clear\")\n   @Payload(\"<ws:clearDataCenter><dataCenterId>{id}</dataCenterId></ws:clearDataCenter>\")\n   @XMLResponseParser(DataCenterInfoResponseHandler.class)\n   DataCenter clearDataCenter(@PayloadParam(\"id\") String identifier);\n\n   /**\n    * Deletes an Virtual Data Center. If a previous request on the target data center is still in progress, the data\n    * center is going to be deleted after this request has been completed. Once a Data Center has been deleted, no\n    * further request can be performed on it.\n    * <p>\n    * @param identifier Identifier of the virtual data center\n    * @return Returns a boolean indicating whether delete operation was made\n    */\n   @POST\n   @Named(\"datacenter:delete\")\n   @Payload(\"<ws:deleteDataCenter><dataCenterId>{id}</dataCenterId></ws:deleteDataCenter>\")\n   @Fallback(Fallbacks.FalseOnNotFoundOr404.class)\n   boolean deleteDataCenter(@PayloadParam(\"id\") String identifier);\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/features/DrivesApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\nimport org.jclouds.http.filters.BasicAuthentication;\nimport org.jclouds.profitbricks.binder.drive.AddRomDriveToServerRequestBinder;\nimport org.jclouds.profitbricks.domain.Drive;\nimport org.jclouds.profitbricks.http.filters.ProfitBricksSoapMessageEnvelope;\nimport org.jclouds.profitbricks.http.parser.RequestIdOnlyResponseHandler;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.XMLResponseParser;\n\n@RequestFilters({BasicAuthentication.class, ProfitBricksSoapMessageEnvelope.class})\n@Consumes(MediaType.TEXT_XML)\n@Produces(MediaType.TEXT_XML)\npublic interface DrivesApi {\n\n   @POST\n   @Named(\"drives:add\")\n   @MapBinder(AddRomDriveToServerRequestBinder.class)\n   @XMLResponseParser(RequestIdOnlyResponseHandler.class)\n   String addRomDriveToServer(@PayloadParam(\"payload\") Drive.Request.AddRomDriveToServerPayload payload);\n\n   @POST\n   @Named(\"drives:remove\")\n   @Payload(\"<ws:removeRomDriveFromServer><imageId>{imageid}</imageId><serverId>{serverid}</serverId></ws:removeRomDriveFromServer>\")\n   @XMLResponseParser(RequestIdOnlyResponseHandler.class)\n   String removeRomDriveFromServer(@PayloadParam(\"imageid\") String imageid, @PayloadParam(\"serverid\") String serverid);\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/features/FirewallApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.features;\n\nimport java.util.List;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks;\nimport org.jclouds.http.filters.BasicAuthentication;\nimport org.jclouds.profitbricks.binder.firewall.AddFirewallRuleToNicRequestBinder;\nimport org.jclouds.profitbricks.binder.firewall.FirewallBinder.ActivateFirewallRequestBinder;\nimport org.jclouds.profitbricks.binder.firewall.FirewallBinder.DeactivateFirewallRequestBinder;\nimport org.jclouds.profitbricks.binder.firewall.FirewallBinder.DeleteFirewallRequestBinder;\nimport org.jclouds.profitbricks.binder.firewall.FirewallBinder.RemoveFirewallRuleRequestBinder;\nimport org.jclouds.profitbricks.domain.Firewall;\nimport org.jclouds.profitbricks.http.filters.ProfitBricksSoapMessageEnvelope;\nimport org.jclouds.profitbricks.http.parser.firewall.FirewallListResponseHandler;\nimport org.jclouds.profitbricks.http.parser.firewall.FirewallResponseHandler;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.XMLResponseParser;\nimport org.jclouds.rest.annotations.Fallback;\n\n@RequestFilters({BasicAuthentication.class, ProfitBricksSoapMessageEnvelope.class})\n@Consumes(MediaType.TEXT_XML)\n@Produces(MediaType.TEXT_XML)\npublic interface FirewallApi {\n\n   @POST\n   @Named(\"firewall:get\")\n   @Payload(\"<ws:getFirewall><firewallId>{id}</firewallId></ws:getFirewall>\")\n   @XMLResponseParser(FirewallResponseHandler.class)\n   @Fallback(Fallbacks.NullOnNotFoundOr404.class)\n   Firewall getFirewall(@PayloadParam(\"id\") String identifier);\n\n   @POST\n   @Named(\"firewall:getall\")\n   @Payload(\"<ws:getAllFirewalls/>\")\n   @XMLResponseParser(FirewallListResponseHandler.class)\n   @Fallback(Fallbacks.EmptyListOnNotFoundOr404.class)\n   List<Firewall> getAllFirewalls();\n\n   @POST\n   @Named(\"firewall:addrule\")\n   @MapBinder(AddFirewallRuleToNicRequestBinder.class)\n   @XMLResponseParser(FirewallResponseHandler.class)\n   Firewall addFirewallRuleToNic(@PayloadParam(\"firewall\") Firewall.Request.AddRulePayload payload);\n\n   @POST\n   @Named(\"firewall:removerule\")\n   @MapBinder(RemoveFirewallRuleRequestBinder.class)\n   @Fallback(Fallbacks.FalseOnNotFoundOr404.class)\n   boolean removeFirewallRules(@PayloadParam(\"ids\") List<String> firewallRuleIds);\n\n   @POST\n   @Named(\"firewall:activate\")\n   @MapBinder(ActivateFirewallRequestBinder.class)\n   @Fallback(Fallbacks.FalseOnNotFoundOr404.class)\n   boolean activateFirewall(@PayloadParam(\"ids\") List<String> firewallIds);\n\n   @POST\n   @Named(\"firewall:activate\")\n   @MapBinder(DeactivateFirewallRequestBinder.class)\n   @Fallback(Fallbacks.FalseOnNotFoundOr404.class)\n   boolean deactivateFirewall(@PayloadParam(\"ids\") List<String> firewallIds);\n\n   @POST\n   @Named(\"firewall:activate\")\n   @MapBinder(DeleteFirewallRequestBinder.class)\n   @Fallback(Fallbacks.FalseOnNotFoundOr404.class)\n   boolean deleteFirewall(@PayloadParam(\"ids\") List<String> firewallIds);\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/features/ImageApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.features;\n\nimport java.util.List;\nimport jakarta.inject.Named;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\nimport org.jclouds.Fallbacks;\n\nimport org.jclouds.http.filters.BasicAuthentication;\nimport org.jclouds.profitbricks.domain.Image;\nimport org.jclouds.profitbricks.http.filters.ProfitBricksSoapMessageEnvelope;\nimport org.jclouds.profitbricks.http.parser.image.ImageInfoResponseHandler;\nimport org.jclouds.profitbricks.http.parser.image.ImageListResponseHandler;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.XMLResponseParser;\n\n@RequestFilters({BasicAuthentication.class, ProfitBricksSoapMessageEnvelope.class})\n@Consumes(MediaType.TEXT_XML)\n@Produces(MediaType.TEXT_XML)\npublic interface ImageApi {\n\n   /**\n    * @return Outputs a list of all HDD and/or CD-ROM/DVD images existing on or uploaded to the ProfitBricks FTP server.\n    */\n   @POST\n   @Named(\"image:getall\")\n   @Payload(\"<ws:getAllImages/>\")\n   @XMLResponseParser(ImageListResponseHandler.class)\n   @Fallback(Fallbacks.EmptyListOnNotFoundOr404.class)\n   List<Image> getAllImages();\n\n   /**\n    *\n    * @param identifier Image Id\n    * @return Returns information about a HDD or CD-ROM/DVD (ISO) image.\n    */\n   @POST\n   @Named(\"image:get\")\n   @Payload(\"<ws:getImage><imageId>{id}</imageId></ws:getImage>\")\n   @XMLResponseParser(ImageInfoResponseHandler.class)\n   @Fallback(Fallbacks.NullOnNotFoundOr404.class)\n   Image getImage(@PayloadParam(\"id\") String identifier);\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/features/IpBlockApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.features;\n\nimport java.util.List;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks;\nimport org.jclouds.http.filters.BasicAuthentication;\nimport org.jclouds.profitbricks.domain.IpBlock;\nimport org.jclouds.profitbricks.domain.Location;\nimport org.jclouds.profitbricks.http.filters.ProfitBricksSoapMessageEnvelope;\nimport org.jclouds.profitbricks.http.parser.RequestIdOnlyResponseHandler;\nimport org.jclouds.profitbricks.http.parser.ipblock.IpBlockListResponseHandler;\nimport org.jclouds.profitbricks.http.parser.ipblock.IpBlockResponseHandler;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.XMLResponseParser;\n\n@RequestFilters({BasicAuthentication.class, ProfitBricksSoapMessageEnvelope.class})\n@Consumes(MediaType.TEXT_XML)\n@Produces(MediaType.TEXT_XML)\npublic interface IpBlockApi {\n\n   @POST\n   @Named(\"publicipblock:get\")\n   @Payload(\"<ws:getPublicIpBlock><blockId>{id}</blockId></ws:getPublicIpBlock>\")\n   @XMLResponseParser(IpBlockResponseHandler.class)\n   @Fallback(Fallbacks.NullOnNotFoundOr404.class)\n   IpBlock getIpBlock(@PayloadParam(\"id\") String identifier);\n\n   @POST\n   @Named(\"publicipblock:getall\")\n   @Payload(\"<ws:getAllPublicIpBlocks />\")\n   @XMLResponseParser(IpBlockListResponseHandler.class)\n   @Fallback(Fallbacks.EmptyListOnNotFoundOr404.class)\n   List<IpBlock> getAllIpBlock();\n\n   @POST\n   @Named(\"publicipblock:reserve\")\n   @Payload(\"<ws:reservePublicIpBlock><request><blockSize>{blockSize}</blockSize><location>{location}</location></request></ws:reservePublicIpBlock>\")\n   @XMLResponseParser(IpBlockResponseHandler.class)\n   IpBlock reservePublicIpBlock(@PayloadParam(\"blockSize\") int blockSize, @PayloadParam(\"location\") Location location);\n\n   @POST\n   @Named(\"publicipblock:addip\")\n   @Payload(\"<ws:addPublicIpToNic><ip>{ip}</ip><nicId>{nicid}</nicId></ws:addPublicIpToNic>\")\n   @XMLResponseParser(RequestIdOnlyResponseHandler.class)\n   String addPublicIpToNic(@PayloadParam(\"ip\") String ip, @PayloadParam(\"nicid\") String nicid);\n\n   @POST\n   @Named(\"publicipblock:removeip\")\n   @Payload(\"<ws:removePublicIpFromNic><ip>{ip}</ip><nicId>{nicid}</nicId></ws:removePublicIpFromNic>\")\n   @XMLResponseParser(RequestIdOnlyResponseHandler.class)\n   String removePublicIpFromNic(@PayloadParam(\"ip\") String ip, @PayloadParam(\"nicid\") String nicid);\n\n   @POST\n   @Named(\"publicipblock:releaseblock\")\n   @Payload(\"<ws:releasePublicIpBlock><blockId>{blockid}</blockId></ws:releasePublicIpBlock>\")\n   @XMLResponseParser(RequestIdOnlyResponseHandler.class)\n   String releasePublicIpBlock(@PayloadParam(\"blockid\") String blockid);\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/features/LoadBalancerApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\n\nimport java.util.List;\n\nimport org.jclouds.Fallbacks;\nimport org.jclouds.http.filters.BasicAuthentication;\nimport org.jclouds.profitbricks.binder.loadbalancer.CreateLoadBalancerRequestBinder;\nimport org.jclouds.profitbricks.binder.loadbalancer.DeregisterLoadBalancerRequestBinder;\nimport org.jclouds.profitbricks.binder.loadbalancer.RegisterLoadBalancerRequestBinder;\nimport org.jclouds.profitbricks.binder.loadbalancer.UpdateLoadBalancerRequestBinder;\nimport org.jclouds.profitbricks.domain.LoadBalancer;\nimport org.jclouds.profitbricks.http.filters.ProfitBricksSoapMessageEnvelope;\nimport org.jclouds.profitbricks.http.parser.RequestIdOnlyResponseHandler;\nimport org.jclouds.profitbricks.http.parser.loadbalancer.LoadBalancerIdOnlyResponseHandler;\nimport org.jclouds.profitbricks.http.parser.loadbalancer.LoadBalancerListResponseHandler;\nimport org.jclouds.profitbricks.http.parser.loadbalancer.LoadBalancerResponseHandler;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.XMLResponseParser;\n\n@RequestFilters({BasicAuthentication.class, ProfitBricksSoapMessageEnvelope.class})\n@Consumes(MediaType.TEXT_XML)\n@Produces(MediaType.TEXT_XML)\npublic interface LoadBalancerApi {\n\n   @POST\n   @Named(\"loadbalancer:getall\")\n   @Payload(\"<ws:getAllLoadBalancers/>\")\n   @XMLResponseParser(LoadBalancerListResponseHandler.class)\n   @Fallback(Fallbacks.EmptyListOnNotFoundOr404.class)\n   List<LoadBalancer> getAllLoadBalancers();\n\n   @POST\n   @Named(\"loadbalancer:get\")\n   @Payload(\"<ws:getLoadBalancer><loadBalancerId>{id}</loadBalancerId></ws:getLoadBalancer>\")\n   @XMLResponseParser(LoadBalancerResponseHandler.class)\n   @Fallback(Fallbacks.NullOnNotFoundOr404.class)\n   LoadBalancer getLoadBalancer(@PayloadParam(\"id\") String identifier);\n\n   @POST\n   @Named(\"loadbalancer:create\")\n   @MapBinder(CreateLoadBalancerRequestBinder.class)\n   @XMLResponseParser(LoadBalancerIdOnlyResponseHandler.class)\n   String createLoadBalancer(@PayloadParam(\"loadbalancer\") LoadBalancer.Request.CreatePayload payload);\n\n   @POST\n   @Named(\"loadbalancer:register\")\n   @MapBinder(RegisterLoadBalancerRequestBinder.class)\n   @XMLResponseParser(LoadBalancerResponseHandler.class)\n   LoadBalancer registerLoadBalancer(@PayloadParam(\"loadbalancer\") LoadBalancer.Request.RegisterPayload payload);\n\n   @POST\n   @Named(\"loadbalancer:deregister\")\n   @MapBinder(DeregisterLoadBalancerRequestBinder.class)\n   @XMLResponseParser(RequestIdOnlyResponseHandler.class)\n   String deregisterLoadBalancer(@PayloadParam(\"loadbalancer\") LoadBalancer.Request.DeregisterPayload payload);\n\n   @POST\n   @Named(\"loadbalancer:delete\")\n   @Payload(\"<ws:deleteLoadBalancer><loadBalancerId>{id}</loadBalancerId></ws:deleteLoadBalancer>\")\n   boolean deleteLoadBalancer(@PayloadParam(\"id\") String id);\n\n   @POST\n   @Named(\"loadbalancer:update\")\n   @MapBinder(UpdateLoadBalancerRequestBinder.class)\n   @XMLResponseParser(RequestIdOnlyResponseHandler.class)\n   String updateLoadBalancer(@PayloadParam(\"loadbalancer\") LoadBalancer.Request.UpdatePayload payload);\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/features/NicApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.features;\n\nimport org.jclouds.Fallbacks;\nimport org.jclouds.http.filters.BasicAuthentication;\nimport org.jclouds.profitbricks.binder.nic.CreateNicRequestBinder;\nimport org.jclouds.profitbricks.binder.nic.SetInternetAccessBinder;\nimport org.jclouds.profitbricks.binder.nic.UpdateNicRequestBinder;\nimport org.jclouds.profitbricks.domain.Nic;\nimport org.jclouds.profitbricks.http.filters.ProfitBricksSoapMessageEnvelope;\nimport org.jclouds.profitbricks.http.parser.nic.NicListResponseHandler;\nimport org.jclouds.profitbricks.http.parser.nic.NicResponseHandler;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.XMLResponseParser;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.PayloadParam;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\nimport jakarta.ws.rs.POST;\n\nimport java.util.List;\n\nimport org.jclouds.profitbricks.http.parser.RequestIdOnlyResponseHandler;\nimport org.jclouds.profitbricks.http.parser.nic.NicIdOnlyResponseHandler;\n\n@RequestFilters({BasicAuthentication.class, ProfitBricksSoapMessageEnvelope.class})\n@Consumes(MediaType.TEXT_XML)\n@Produces(MediaType.TEXT_XML)\npublic interface NicApi {\n\n   @POST\n   @Named(\"nics:getall\")\n   @Payload(\"<ws:getAllNic/>\")\n   @XMLResponseParser(NicListResponseHandler.class)\n   @Fallback(Fallbacks.EmptyListOnNotFoundOr404.class)\n   List<Nic> getAllNics();\n\n   @POST\n   @Named(\"nic:create\")\n   @MapBinder(CreateNicRequestBinder.class)\n   @XMLResponseParser(NicIdOnlyResponseHandler.class)\n   String createNic(@PayloadParam(\"nic\") Nic.Request.CreatePayload payload);\n\n   @POST\n   @Named(\"nic:get\")\n   @Payload(\"<ws:getNic><nicId>{id}</nicId></ws:getNic>\")\n   @XMLResponseParser(NicResponseHandler.class)\n   @Fallback(Fallbacks.NullOnNotFoundOr404.class)\n   Nic getNic(@PayloadParam(\"id\") String identifier);\n\n   @POST\n   @Named(\"nic:update\")\n   @MapBinder(UpdateNicRequestBinder.class)\n   @XMLResponseParser(RequestIdOnlyResponseHandler.class)\n   String updateNic(@PayloadParam(\"nic\") Nic.Request.UpdatePayload payload);\n\n   @POST\n   @Named(\"nic:setInternetAccess\")\n   @MapBinder(SetInternetAccessBinder.class)\n   @XMLResponseParser(RequestIdOnlyResponseHandler.class)\n   String setInternetAccess(@PayloadParam(\"nic\") Nic.Request.SetInternetAccessPayload payload);\n\n   @POST\n   @Named(\"nic:delete\")\n   @Payload(\"<ws:deleteNic><nicId>{id}</nicId></ws:deleteNic>\")\n   @Fallback(Fallbacks.FalseOnNotFoundOr404.class)\n   boolean deleteNic(@PayloadParam(\"id\") String id);\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/features/ServerApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.features;\n\nimport java.util.List;\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\nimport org.jclouds.Fallbacks;\nimport org.jclouds.http.filters.BasicAuthentication;\nimport org.jclouds.profitbricks.binder.server.CreateServerRequestBinder;\nimport org.jclouds.profitbricks.binder.server.UpdateServerRequestBinder;\nimport org.jclouds.profitbricks.domain.Server;\nimport org.jclouds.profitbricks.http.filters.ProfitBricksSoapMessageEnvelope;\nimport org.jclouds.profitbricks.http.parser.RequestIdOnlyResponseHandler;\nimport org.jclouds.profitbricks.http.parser.server.ServerIdOnlyResponseHandler;\nimport org.jclouds.profitbricks.http.parser.server.ServerInfoResponseHandler;\nimport org.jclouds.profitbricks.http.parser.server.ServerListResponseHandler;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.XMLResponseParser;\n\n@RequestFilters({BasicAuthentication.class, ProfitBricksSoapMessageEnvelope.class})\n@Consumes(MediaType.TEXT_XML)\n@Produces(MediaType.TEXT_XML)\npublic interface ServerApi {\n\n   /**\n    * @return Returns information about all virtual server, such as configuration, provisioning status, power status,\n    * etc.\n    */\n   @POST\n   @Named(\"server:getall\")\n   @Payload(\"<ws:getAllServers/>\")\n   @XMLResponseParser(ServerListResponseHandler.class)\n   @Fallback(Fallbacks.EmptyListOnNotFoundOr404.class)\n   List<Server> getAllServers();\n\n   /**\n    * @param identifier Identifier of the virtual server\n    * @return Returns information about a virtual server, such as configuration, provisioning status, power status, etc.\n    */\n   @POST\n   @Named(\"server:get\")\n   @Payload(\"<ws:getServer><serverId>{id}</serverId></ws:getServer>\")\n   @XMLResponseParser(ServerInfoResponseHandler.class)\n   @Fallback(Fallbacks.NullOnNotFoundOr404.class)\n   Server getServer(@PayloadParam(\"id\") String identifier);\n\n   /**\n    * Starts an existing virtual server\n    * <ul>\n    * <li>Server may receive new public IP addresses if necessary </li>\n    * <li>Billing will continue</li>\n    * </ul>\n    *\n    *\n    * @param id Identifier of the target virtual server\n    * @return Identifier of current request\n    */\n   @POST\n   @Named(\"server:start\")\n   @Payload(\"<ws:startServer><serverId>{id}</serverId></ws:startServer>\")\n   @XMLResponseParser(RequestIdOnlyResponseHandler.class)\n   String startServer(@PayloadParam(\"id\") String id);\n\n   /**\n    *\n    * Stops an existing virtual server forcefully (HARD stop)\n    * <ul>\n    * <li>Server will be forcefully powered off. Any unsaved data may be lost! </li>\n    * <li>Billing for this server will be stopped </li>\n    * <li>When restarting the server a new public IP gets assigned, alternatively, you can reserve IP addresses, see\n    * reservation of public IP blocks</li>\n    * </ul>\n    *\n    * A graceful stop of a server is not possible through the ProfitBricks API. We recommend to access and execute the\n    * command on the virtual server directly. Once the server was shutdown you still can use the \"stopServer\" method\n    * that will stop billing.\n    *\n    * @param id Identifier of the target virtual server\n    * @return Identifier of current request\n    */\n   @POST\n   @Named(\"server:stop\")\n   @Payload(\"<ws:stopServer><serverId>{id}</serverId></ws:stopServer>\")\n   @XMLResponseParser(RequestIdOnlyResponseHandler.class)\n   String stopServer(@PayloadParam(\"id\") String id);\n\n   /**\n    * Resets an existing virtual server (POWER CYCLE).\n    * <ul>\n    * <li>Server will be forcefully powered off and restarted immediately. Any unsaved data may be lost!</li>\n    * <li> Billing will continue</li>\n    * </ul>\n    * <b>Graceful REBOOT</b>\n    *\n    * A graceful reboot of a server is not possible through the ProfitBricks API. We recommend to access and execute the\n    * command on the virtual server directly.\n    *\n    * @param id Identifier of the target virtual server\n    * @return Identifier of current request\n    */\n   @POST\n   @Named(\"server:reset\")\n   @Payload(\"<ws:resetServer><serverId>{id}</serverId></ws:resetServer>\")\n   @XMLResponseParser(RequestIdOnlyResponseHandler.class)\n   String resetServer(@PayloadParam(\"id\") String id);\n\n   /**\n    * Creates a Virtual Server within an existing data center. Parameters can be specified to set up a boot device and\n    * connect the server to an existing LAN or the Internet.\n    *\n    * @param payload Payload\n    * @return serverId of the created server\n    */\n   @POST\n   @Named(\"server:create\")\n   @MapBinder(CreateServerRequestBinder.class)\n   @XMLResponseParser(ServerIdOnlyResponseHandler.class)\n   String createServer(@PayloadParam(\"server\") Server.Request.CreatePayload payload);\n\n   /**\n    * Updates parameters of an existing virtual server device.\n    *\n    * @param payload Payload\n    * @return Identifier of current request\n    */\n   @POST\n   @Named(\"server:update\")\n   @MapBinder(UpdateServerRequestBinder.class)\n   @XMLResponseParser(RequestIdOnlyResponseHandler.class)\n   String updateServer(@PayloadParam(\"server\") Server.Request.UpdatePayload payload);\n\n   /**\n    * Deletes an existing Virtual Server.\n    *\n    * @param id Identifier of the target virtual server\n    * @return Identifier of current request\n    */\n   @POST\n   @Named(\"server:delete\")\n   @Payload(\"<ws:deleteServer><serverId>{id}</serverId></ws:deleteServer>\")\n   @Fallback(Fallbacks.FalseOnNotFoundOr404.class)\n   boolean deleteServer(@PayloadParam(\"id\") String id);\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/features/SnapshotApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.features;\n\nimport java.util.List;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks;\nimport org.jclouds.http.filters.BasicAuthentication;\nimport org.jclouds.profitbricks.binder.snapshot.CreateSnapshotRequestBinder;\nimport org.jclouds.profitbricks.binder.snapshot.RollbackSnapshotRequestBinder;\nimport org.jclouds.profitbricks.binder.snapshot.UpdateSnapshotRequestBinder;\nimport org.jclouds.profitbricks.domain.Snapshot;\nimport org.jclouds.profitbricks.http.filters.ProfitBricksSoapMessageEnvelope;\nimport org.jclouds.profitbricks.http.parser.RequestIdOnlyResponseHandler;\nimport org.jclouds.profitbricks.http.parser.snapshot.SnapshotResponseHandler;\nimport org.jclouds.profitbricks.http.parser.snapshot.SnapshotListResponseHandler;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.XMLResponseParser;\n\n@RequestFilters({BasicAuthentication.class, ProfitBricksSoapMessageEnvelope.class})\n@Consumes(MediaType.TEXT_XML)\n@Produces(MediaType.TEXT_XML)\npublic interface SnapshotApi {\n\n   @POST\n   @Named(\"snapshot:getall\")\n   @Payload(\"<ws:getAllSnapshots/>\")\n   @XMLResponseParser(SnapshotListResponseHandler.class)\n   @Fallback(Fallbacks.EmptyListOnNotFoundOr404.class)\n   List<Snapshot> getAllSnapshots();\n\n   @POST\n   @Named(\"snapshot:get\")\n   @Payload(\"<ws:getSnapshot><snapshotId>{snapshotId}</snapshotId></ws:getSnapshot>\")\n   @XMLResponseParser(SnapshotResponseHandler.class)\n   @Fallback(Fallbacks.NullOnNotFoundOr404.class)\n   Snapshot getSnapshot(@PayloadParam(\"snapshotId\") String identifier);\n\n   @POST\n   @Named(\"snapshot:create\")\n   @MapBinder(CreateSnapshotRequestBinder.class)\n   @XMLResponseParser(SnapshotResponseHandler.class)\n   Snapshot createSnapshot(@PayloadParam(\"snapshot\") Snapshot.Request.CreatePayload payload);\n\n   @POST\n   @Named(\"snapshot:update\")\n   @MapBinder(UpdateSnapshotRequestBinder.class)\n   @XMLResponseParser(RequestIdOnlyResponseHandler.class)\n   String updateSnapshot(@PayloadParam(\"snapshot\") Snapshot.Request.UpdatePayload payload);\n\n   @POST\n   @Named(\"snapshot:delete\")\n   @Payload(\"<ws:deleteSnapshot><snapshotId>{id}</snapshotId></ws:deleteSnapshot>\")\n   @Fallback(Fallbacks.FalseOnNotFoundOr404.class)\n   boolean deleteSnapshot(@PayloadParam(\"id\") String id);\n\n   @POST\n   @Named(\"snapshot:rollback\")\n   @MapBinder(RollbackSnapshotRequestBinder.class)\n   @XMLResponseParser(RequestIdOnlyResponseHandler.class)\n   String rollbackSnapshot(@PayloadParam(\"snapshot\") Snapshot.Request.RollbackPayload payload);\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/features/StorageApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.features;\n\nimport java.util.List;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks;\nimport org.jclouds.http.filters.BasicAuthentication;\nimport org.jclouds.profitbricks.binder.storage.ConnectStorageToServerRequestBinder;\nimport org.jclouds.profitbricks.binder.storage.CreateStorageRequestBinder;\nimport org.jclouds.profitbricks.binder.storage.UpdateStorageRequestBinder;\nimport org.jclouds.profitbricks.domain.Storage;\nimport org.jclouds.profitbricks.http.filters.ProfitBricksSoapMessageEnvelope;\nimport org.jclouds.profitbricks.http.parser.RequestIdOnlyResponseHandler;\nimport org.jclouds.profitbricks.http.parser.storage.StorageIdOnlyResponseHandler;\nimport org.jclouds.profitbricks.http.parser.storage.StorageInfoResponseHandler;\nimport org.jclouds.profitbricks.http.parser.storage.StorageListResponseHandler;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.XMLResponseParser;\n\n@RequestFilters({BasicAuthentication.class, ProfitBricksSoapMessageEnvelope.class})\n@Consumes(MediaType.TEXT_XML)\n@Produces(MediaType.TEXT_XML)\npublic interface StorageApi {\n\n   /**\n    *\n    * @return Returns information about all virtual storage, such as configuration and provisioning state.\n    */\n   @POST\n   @Named(\"storage:getall\")\n   @Payload(\"<ws:getAllStorages/>\")\n   @XMLResponseParser(StorageListResponseHandler.class)\n   @Fallback(Fallbacks.EmptyListOnNotFoundOr404.class)\n   List<Storage> getAllStorages();\n\n   /**\n    *\n    * @param id Storage identifier\n    * @return Returns information about a virtual storage’s configuration and provisioning state.\n    */\n   @POST\n   @Named(\"storage:get\")\n   @Payload(\"<ws:getStorage><storageId>{id}</storageId></ws:getStorage>\")\n   @XMLResponseParser(StorageInfoResponseHandler.class)\n   @Fallback(Fallbacks.NullOnNotFoundOr404.class)\n   Storage getStorage(@PayloadParam(\"id\") String id);\n\n   /**\n    * Creates a virtual storage within an existing virtual data center. Additional parameters can be specified, e.g. for\n    * assigning a HDD image to the storage.\n    *\n    * @param payload Payload\n    * @return storageId of the created storage\n    */\n   @POST\n   @Named(\"storage:create\")\n   @MapBinder(CreateStorageRequestBinder.class)\n   @XMLResponseParser(StorageIdOnlyResponseHandler.class)\n   String createStorage(@PayloadParam(\"storage\") Storage.Request.CreatePayload payload);\n\n   /**\n    * Updates parameters of an existing virtual storage device. It is possible to increase the storage size without\n    * reboot of an already provisioned storage. The additional capacity is not added to any partition. You have to\n    * partition the storage afterwards. Vice versa, it is not possible to decrease the storage size of an already\n    * provisioned storage.\n    *\n    * @param payload Payload\n    * @return Identifier of current request\n    */\n   @POST\n   @Named(\"storage:update\")\n   @MapBinder(UpdateStorageRequestBinder.class)\n   @XMLResponseParser(RequestIdOnlyResponseHandler.class)\n   String updateStorage(@PayloadParam(\"storage\") Storage.Request.UpdatePayload payload);\n\n   /**\n    * Deletes an existing virtual storage device.\n    *\n    * @param id Identifier of the target virtual storage\n    * @return Identifier of current request\n    */\n   @POST\n   @Named(\"storage:delete\")\n   @Payload(\"<ws:deleteStorage><storageId>{id}</storageId></ws:deleteStorage>\")\n   @Fallback(Fallbacks.FalseOnNotFoundOr404.class)\n   boolean deleteStorage(@PayloadParam(\"id\") String id);\n\n   /**\n    * Connects a virtual storage device to an existing server.\n    *\n    * @param payload Payload\n    * @return Identifier of current request\n    */\n   @POST\n   @Named(\"storage:connect\")\n   @MapBinder(ConnectStorageToServerRequestBinder.class)\n   @XMLResponseParser(RequestIdOnlyResponseHandler.class)\n   String connectStorageToServer(@PayloadParam(\"storage\") Storage.Request.ConnectPayload payload);\n\n   /**\n    * Disconnects a virtual storage device from a connected server.\n    *\n    * @param storageId Identifier of the connected virtual storage\n    * @param serverId Identifier of the connected virtual server\n    * @return Identifier of current request\n    */\n   @POST\n   @Named(\"storage:disconnect\")\n   @Payload(\"<ws:disconnectStorageFromServer><storageId>{storageId}</storageId><serverId>{serverId}</serverId></ws:disconnectStorageFromServer>\")\n   @XMLResponseParser(RequestIdOnlyResponseHandler.class)\n   String disconnectStorageFromServer(@PayloadParam(\"storageId\") String storageId, @PayloadParam(\"serverId\") String serverId);\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/handlers/ProfitBricksHttpErrorHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.handlers;\n\nimport static org.jclouds.http.HttpUtils.closeClientButKeepContentStream;\nimport static org.jclouds.util.Closeables2.closeQuietly;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.InsufficientResourcesException;\nimport org.jclouds.rest.ResourceNotFoundException;\n\n/**\n * Parse ProfitBricks API errors and set the appropriate exception.\n *\n * @see org.jclouds.profitbricks.http.ResponseStatusFromPayloadHttpCommandExecutorService\n *\n */\n@Singleton\npublic class ProfitBricksHttpErrorHandler implements HttpErrorHandler {\n\n   @Override\n   public void handleError(final HttpCommand command, final HttpResponse response) {\n   // it is important to always read fully and close streams\n      byte[] data = closeClientButKeepContentStream(response);\n      String message = data != null ? new String(data) : null;\n\n      Exception exception = message != null ? new HttpResponseException(command, response, message)\n            : new HttpResponseException(command, response);\n      \n      try {\n         switch (response.getStatusCode()) {\n            case 400:\n            case 405:\n               exception = new IllegalArgumentException(response.getMessage(), exception);\n               break;\n            case 401:\n               exception = new AuthorizationException(\"This request requires authentication.\", exception);\n               break;\n            case 403:\n               exception = new AuthorizationException(response.getMessage(), exception);\n               break;\n            case 402:\n            case 409:\n               exception = new IllegalStateException(response.getMessage(), exception);\n               break;\n            case 404:\n            case 410:\n               if (!command.getCurrentRequest().getMethod().equals(\"DELETE\"))\n                  exception = new ResourceNotFoundException(response.getMessage(), exception);\n               break;\n            case 413:\n            case 503:\n               // if nothing (default message was OK) was parsed from command executor, assume it was an 503 (Maintenance) html response.\n               if (response.getMessage().equals(\"OK\"))\n                  exception = new HttpResponseException(\"The ProfitBricks team is currently carrying out maintenance.\", command, response);\n               else\n                  exception = new InsufficientResourcesException(response.getMessage(), exception);\n               break;\n         }\n      } finally {\n         closeQuietly(response.getPayload());\n         command.setException(exception);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/http/ResponseStatusFromPayloadHttpCommandExecutorService.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http;\n\nimport static org.jclouds.Constants.PROPERTY_IDEMPOTENT_METHODS;\nimport static org.jclouds.Constants.PROPERTY_OUTPUT_SOCKET_BUFFER_SIZE;\nimport static org.jclouds.Constants.PROPERTY_USER_AGENT;\nimport static org.jclouds.util.Closeables2.closeQuietly;\n\nimport java.io.ByteArrayInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.net.HttpURLConnection;\nimport java.net.Proxy;\nimport java.net.URI;\nimport java.util.regex.Pattern;\n\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\nimport javax.net.ssl.HostnameVerifier;\nimport javax.net.ssl.SSLContext;\n\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpUtils;\nimport org.jclouds.http.IOExceptionRetryHandler;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.http.handlers.DelegatingErrorHandler;\nimport org.jclouds.http.handlers.DelegatingRetryHandler;\nimport org.jclouds.http.internal.HttpWire;\nimport org.jclouds.http.internal.JavaUrlHttpCommandExecutorService;\nimport org.jclouds.io.ContentMetadataCodec;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.profitbricks.domain.ServiceFault;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.io.ByteStreams;\nimport com.google.inject.Inject;\n\n/**\n * Custom implementation of the HTTP driver to read actual http status and message from SOAP Fault.\n * <br/>\n * ProfitBricks API errors are always returned with 500 HTTP code. This class parses and reads the SOAP response to map\n * the actual http code and message\n */\n@Singleton\npublic class ResponseStatusFromPayloadHttpCommandExecutorService extends JavaUrlHttpCommandExecutorService {\n\n   private final ParseSax<ServiceFault> faultHandler;\n\n   private static final Pattern endSoapTag = Pattern.compile(\"</.+:Envelope>$\");\n\n   @Inject\n   ResponseStatusFromPayloadHttpCommandExecutorService(HttpUtils utils, ContentMetadataCodec contentMetadataCodec,\n           DelegatingRetryHandler retryHandler, IOExceptionRetryHandler ioRetryHandler,\n           DelegatingErrorHandler errorHandler, HttpWire wire, @Named(\"untrusted\") HostnameVerifier verifier,\n           @Named(\"untrusted\") Supplier<SSLContext> untrustedSSLContextProvider, Function<URI, Proxy> proxyForURI,\n           ParseSax<ServiceFault> faultHandler,\n           @Named(PROPERTY_IDEMPOTENT_METHODS) String idempotentMethods,\n           @Named(PROPERTY_OUTPUT_SOCKET_BUFFER_SIZE) int outputSocketBufferSize,\n           @Named(PROPERTY_USER_AGENT) String userAgent) {\n      super(utils, contentMetadataCodec, retryHandler, ioRetryHandler, errorHandler, wire, verifier, untrustedSSLContextProvider, proxyForURI,\n            idempotentMethods, outputSocketBufferSize, userAgent);\n      this.faultHandler = faultHandler;\n   }\n\n   @Override\n   protected HttpResponse invoke(HttpURLConnection connection) throws IOException, InterruptedException {\n      HttpResponse originalResponse = super.invoke(connection);\n      HttpResponse.Builder<?> responseBuilder = originalResponse.toBuilder();\n\n      if (hasServerError(originalResponse) && hasPayload(originalResponse)) {\n         // As we need to read the response body to determine if there are errors, but we may need to process the body\n         // again later in the response parsers if everything is OK, we buffer the body into an InputStream we can reset\n         InputStream in = null;\n         InputStream originalInputStream = originalResponse.getPayload().openStream();\n\n         if (originalInputStream instanceof ByteArrayInputStream)\n            in = originalInputStream;\n         else\n            try {\n               in = new ByteArrayInputStream(ByteStreams.toByteArray(originalInputStream));\n            } finally {\n               closeQuietly(originalInputStream);\n            }\n         try {\n            if (isSoapPayload(in)) {\n               ServiceFault fault = faultHandler.parse(in);\n               if (fault != null) {\n                  if (fault.details() != null) {\n                     responseBuilder.statusCode(fault.details().httpCode()).message(fault.details().message());\n                  } else {\n                     responseBuilder.message(fault.faultString());\n                  }\n               }\n            }\n         } catch (Exception ex) {\n            // ignore\n         } finally {\n            // Reset the input stream and set the payload, so it can be read again\n            // by the response and error parsers\n            if (in != null) {\n               in.reset();\n               Payload payload = Payloads.newInputStreamPayload(in);\n               contentMetadataCodec.fromHeaders(payload.getContentMetadata(), originalResponse.getHeaders());\n               responseBuilder.payload(payload);\n            }\n         }\n      }\n\n      return responseBuilder.build();\n   }\n\n   private static boolean hasServerError(final HttpResponse response) {\n      return response.getStatusCode() >= 500;\n   }\n\n   private static boolean hasPayload(final HttpResponse response) {\n      return response.getPayload() != null && response.getPayload().getRawContent() != null;\n   }\n\n   private static boolean isSoapPayload(final InputStream is) throws IOException {\n      int size = is.available();\n      char[] chars = new char[size];\n      byte[] bytes = new byte[size];\n\n      ByteStreams.readFully(is, bytes);\n      for (int i = 0; i < size;)\n         chars[i] = (char) (bytes[i++] & 0xff);\n\n      is.reset(); // throws premature end of file w/o this\n\n      return endSoapTag.matcher(new String(chars)).find();\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/http/filters/ProfitBricksSoapMessageEnvelope.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.filters;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.http.HttpException;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpRequestFilter;\nimport org.jclouds.http.HttpUtils;\nimport org.jclouds.io.ContentMetadata;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\n\n/**\n * Filters {@link HttpRequest} request and wraps request body into SOAP envelope.\n */\npublic class ProfitBricksSoapMessageEnvelope implements HttpRequestFilter {\n\n   private static final String SOAP_PREFIX\n           = \"<soapenv:Envelope xmlns:soapenv=\\\"http://schemas.xmlsoap.org/soap/envelope/\\\" xmlns:ws=\\\"http://ws.api.profitbricks.com/\\\">\"\n           + \"<soapenv:Header/>\"\n           + \"<soapenv:Body>\";\n\n   private static final String SOAP_SUFFIX = \"</soapenv:Body></soapenv:Envelope>\";\n\n   @Override\n   public HttpRequest filter(HttpRequest request) throws HttpException {\n      checkNotNull(request.getPayload(), \"HTTP Request must contain payload message.\");\n      return createSoapRequest(request);\n   }\n\n   private HttpRequest createSoapRequest(HttpRequest request) {\n      Payload oldPayload = request.getPayload();\n      ContentMetadata oldMetadata = oldPayload.getContentMetadata();\n\n      String body = SOAP_PREFIX.concat(oldPayload.getRawContent().toString()).concat(SOAP_SUFFIX);\n      Payload newPayload = Payloads.newStringPayload(body);\n      HttpUtils.copy(oldMetadata, newPayload.getContentMetadata());\n      newPayload.getContentMetadata().setContentLength(Long.valueOf(body.getBytes().length)); // resize, add prefix/suffix length\n\n      return request.toBuilder().payload(newPayload).build();\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/http/parser/BaseProfitBricksResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.xml.sax.SAXException;\n\npublic abstract class BaseProfitBricksResponseHandler<T> extends ParseSax.HandlerForGeneratedRequestWithResult<T> {\n\n   private final StringBuilder strBuilder;\n\n   public BaseProfitBricksResponseHandler() {\n      this.strBuilder = new StringBuilder();\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      strBuilder.append(ch, start, length);\n   }\n\n   protected String textToStringValue() {\n      return strBuilder.toString().trim();\n   }\n\n   protected Float textToFloatValue() {\n      return Float.valueOf(textToStringValue());\n   }\n\n   protected Double textToDoubleValue() {\n      return Double.valueOf(textToStringValue());\n   }\n\n   protected int textToIntValue() {\n      return Integer.parseInt(textToStringValue());\n   }\n\n   protected boolean textToBooleanValue() {\n      return Boolean.parseBoolean(textToStringValue());\n   }\n\n   protected void clearTextBuffer() {\n      strBuilder.setLength(0);\n   }\n\n   public void reset() {\n\n   }\n\n   @Override\n   public abstract void endElement(String uri, String localName, String qName) throws SAXException;\n\n   protected abstract void setPropertyOnEndTag(String qName);\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/http/parser/RequestIdOnlyResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser;\n\nimport org.xml.sax.SAXException;\n\npublic class RequestIdOnlyResponseHandler extends BaseProfitBricksResponseHandler<String> {\n\n   private String requestId;\n\n   RequestIdOnlyResponseHandler() {\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) throws SAXException {\n      setPropertyOnEndTag(qName);\n      clearTextBuffer();\n   }\n\n   @Override\n   protected void setPropertyOnEndTag(String qName) {\n      if (\"requestId\".equals(qName))\n         requestId = textToStringValue();\n   }\n\n   @Override\n   public String getResult() {\n      return requestId;\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/http/parser/ServiceFaultResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser;\n\nimport org.jclouds.profitbricks.domain.ServiceFault;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\n\npublic class ServiceFaultResponseHandler extends BaseProfitBricksResponseHandler<ServiceFault> {\n\n   private final ServiceFault.Builder builder;\n   private ServiceFault.Details.Builder detailsBuilder;\n   private boolean done = false;\n\n   ServiceFaultResponseHandler() {\n      this.builder = ServiceFault.builder();\n   }\n   \n   @Override\n   public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {\n      if (\"detail\".equals(qName)) {\n         detailsBuilder = ServiceFault.Details.builder();\n      }\n   }\n\n   @Override\n   protected void setPropertyOnEndTag(String qName) {\n      if (\"faultcode\".equals(qName))\n         builder.faultCode(textToStringValue());\n      else if (\"faultstring\".equals(qName))\n         builder.faultString(textToStringValue());\n      else if (\"faultCode\".equals(qName))\n         detailsBuilder.faultCode(ServiceFault.Details.FaultCode.fromValue(textToStringValue()));\n      else if (\"httpCode\".equals(qName))\n         detailsBuilder.httpCode(textToIntValue());\n      else if (\"message\".equals(qName))\n         detailsBuilder.message(textToStringValue());\n      else if (\"requestId\".equals(qName))\n         detailsBuilder.requestId(textToIntValue());\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) throws SAXException {\n      if (done)\n         return;\n      setPropertyOnEndTag(qName);\n      if (\"S:Fault\".equals(qName))\n         done = true;\n      if (\"detail\".equals(qName))\n         builder.details(detailsBuilder.build());\n      clearTextBuffer();\n   }\n\n   @Override\n   public ServiceFault getResult() {\n      return builder.build();\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/http/parser/datacenter/BaseDataCenterResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.datacenter;\n\nimport org.jclouds.profitbricks.domain.DataCenter;\nimport org.jclouds.profitbricks.http.parser.BaseProfitBricksResponseHandler;\n\npublic abstract class BaseDataCenterResponseHandler<T> extends BaseProfitBricksResponseHandler<T> {\n\n   protected DataCenter.Builder builder;\n\n   BaseDataCenterResponseHandler() {\n      this.builder = DataCenter.builder();\n   }\n\n   @Override\n   protected void setPropertyOnEndTag(String qName) {\n      if (\"dataCenterId\".equals(qName))\n         builder.id(textToStringValue());\n      else if (\"dataCenterVersion\".equals(qName))\n         builder.version(textToIntValue());\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/http/parser/datacenter/DataCenterInfoResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.datacenter;\n\nimport org.jclouds.profitbricks.domain.DataCenter;\nimport org.jclouds.profitbricks.domain.Location;\nimport org.jclouds.profitbricks.domain.ProvisioningState;\nimport org.jclouds.profitbricks.http.parser.server.ServerListResponseHandler;\nimport org.jclouds.profitbricks.http.parser.storage.StorageListResponseHandler;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\n\nimport com.google.inject.Inject;\n\npublic class DataCenterInfoResponseHandler extends BaseDataCenterResponseHandler<DataCenter> {\n\n   private final ServerListResponseHandler serverListResponseHandler;\n   private final StorageListResponseHandler storageListResponseHandler;\n\n   private boolean done = false;\n   private boolean useServerParser = false;\n   private boolean useStorageParser = false;\n\n   @Inject\n   DataCenterInfoResponseHandler(ServerListResponseHandler serverListResponseHandler, StorageListResponseHandler storageListResponseHandler) {\n      this.serverListResponseHandler = serverListResponseHandler;\n      this.storageListResponseHandler = storageListResponseHandler;\n   }\n\n   @Override\n   public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {\n      if (\"servers\".equals(qName))\n         useServerParser = true;\n      else if (\"storages\".equals(qName))\n         useStorageParser = true;\n\n      if (useServerParser)\n         serverListResponseHandler.startElement(uri, localName, qName, attributes);\n      else if (useStorageParser)\n         storageListResponseHandler.startElement(uri, localName, qName, attributes);\n      else\n         super.startElement(uri, localName, qName, attributes);\n   }\n\n   @Override\n   protected void setPropertyOnEndTag(String qName) {\n      super.setPropertyOnEndTag(qName);\n      if (\"dataCenterName\".equals(qName))\n         builder.name(textToStringValue());\n      else if (\"location\".equals(qName))\n         builder.location(Location.fromId(textToStringValue()));\n      else if (\"provisioningState\".equals(qName))\n         builder.state(ProvisioningState.fromValue(textToStringValue()));\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      if (useServerParser)\n         serverListResponseHandler.characters(ch, start, length);\n      else if (useStorageParser)\n         storageListResponseHandler.characters(ch, start, length);\n      else\n         super.characters(ch, start, length);\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) throws SAXException {\n      if (done)\n         return;\n\n      if (useServerParser)\n         serverListResponseHandler.endElement(uri, localName, qName);\n      else if (useStorageParser)\n         storageListResponseHandler.endElement(uri, localName, qName);\n      else {\n         setPropertyOnEndTag(qName);\n         if (\"return\".equals(qName)) {\n            done = true;\n            builder.servers(serverListResponseHandler.getResult());\n            builder.storages(storageListResponseHandler.getResult());\n         }\n         clearTextBuffer();\n      }\n\n      if (\"servers\".equals(qName))\n         useServerParser = false;\n      else if (\"storages\".equals(qName))\n         useStorageParser = false;\n   }\n\n   @Override\n   public DataCenter getResult() {\n      return builder.build();\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/http/parser/datacenter/DataCenterListResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.datacenter;\n\nimport java.util.List;\n\nimport org.jclouds.profitbricks.domain.DataCenter;\nimport org.jclouds.profitbricks.domain.Location;\nimport org.jclouds.profitbricks.domain.ProvisioningState;\nimport org.xml.sax.SAXException;\n\nimport com.google.common.collect.Lists;\n\npublic class DataCenterListResponseHandler extends BaseDataCenterResponseHandler<List<DataCenter>> {\n\n   private final List<DataCenter> dataCenters;\n\n   DataCenterListResponseHandler() {\n      this.dataCenters = Lists.newArrayList();\n   }\n\n   @Override\n   public List<DataCenter> getResult() {\n      return dataCenters;\n   }\n\n   @Override\n   protected void setPropertyOnEndTag(String qName) {\n      super.setPropertyOnEndTag(qName);\n      if (\"dataCenterName\".equals(qName))\n         builder.name(textToStringValue());\n      else if (\"location\".equals(qName))\n         builder.location(Location.fromValue(textToStringValue()));\n      else if (\"provisioningState\".equals(qName))\n         builder.state(ProvisioningState.fromValue(textToStringValue()));\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) throws SAXException {\n      setPropertyOnEndTag(qName);\n      if (\"return\".equals(qName)) {\n         dataCenters.add(builder.build());\n         builder = DataCenter.builder();\n      }\n      clearTextBuffer();\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/http/parser/firewall/BaseFirewallResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.firewall;\n\nimport org.jclouds.profitbricks.domain.Firewall;\nimport org.jclouds.profitbricks.domain.ProvisioningState;\nimport org.jclouds.profitbricks.http.parser.BaseProfitBricksResponseHandler;\nimport org.jclouds.profitbricks.http.parser.firewall.rule.FirewallRuleListResponseHandler;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\n\npublic abstract class BaseFirewallResponseHandler<T> extends BaseProfitBricksResponseHandler<T> {\n\n   protected final FirewallRuleListResponseHandler firewallRuleListResponseHandler;\n\n   protected boolean useFirewallRuleParser = false;\n   protected Firewall.Builder builder;\n\n   protected BaseFirewallResponseHandler(FirewallRuleListResponseHandler firewallRuleListResponseHandler) {\n      this.builder = Firewall.builder();\n      this.firewallRuleListResponseHandler = firewallRuleListResponseHandler;\n   }\n\n   @Override\n   public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {\n      if (\"firewallRules\".equals(qName))\n         useFirewallRuleParser = true;\n\n      if (useFirewallRuleParser)\n         firewallRuleListResponseHandler.startElement(uri, localName, qName, attributes);\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      if (useFirewallRuleParser)\n         firewallRuleListResponseHandler.characters(ch, start, length);\n      else\n         super.characters(ch, start, length);\n   }\n\n   @Override\n   protected void setPropertyOnEndTag(String qName) {\n      if (\"firewallId\".equals(qName))\n         builder.id(textToStringValue());\n      else if (\"active\".equals(qName))\n         builder.active(textToBooleanValue());\n      else if (\"nicId\".equals(qName))\n         builder.nicId(textToStringValue());\n      else if (\"provisioningState\".equals(qName))\n         builder.state(ProvisioningState.fromValue(textToStringValue()));\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/http/parser/firewall/FirewallListResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.firewall;\n\nimport java.util.List;\n\nimport org.jclouds.profitbricks.domain.Firewall;\nimport org.jclouds.profitbricks.http.parser.firewall.rule.FirewallRuleListResponseHandler;\nimport org.xml.sax.SAXException;\n\nimport com.google.inject.Inject;\nimport com.google.common.collect.Lists;\n\npublic class FirewallListResponseHandler extends BaseFirewallResponseHandler<List<Firewall>> {\n\n   private List<Firewall> firewalls;\n\n   @Inject\n   FirewallListResponseHandler(FirewallRuleListResponseHandler firewallRuleListResponseHandler) {\n      super(firewallRuleListResponseHandler);\n      this.firewalls = Lists.newArrayList();\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) throws SAXException {\n      if (useFirewallRuleParser)\n         firewallRuleListResponseHandler.endElement(uri, localName, qName);\n      else {\n         setPropertyOnEndTag(qName);\n         if (\"return\".equals(qName) || \"firewall\".equals(qName)) {\n            firewalls.add(builder\n                    .rules(firewallRuleListResponseHandler.getResult())\n                    .build());\n            firewallRuleListResponseHandler.reset();\n            builder = Firewall.builder();\n         }\n         clearTextBuffer();\n      }\n\n      if (\"firewallRules\".equals(qName))\n         useFirewallRuleParser = false;\n   }\n\n   @Override\n   public void reset() {\n      this.firewalls = Lists.newArrayList();\n   }\n\n   @Override\n   public List<Firewall> getResult() {\n      return firewalls;\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/http/parser/firewall/FirewallResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.firewall;\n\nimport com.google.inject.Inject;\n\nimport org.jclouds.profitbricks.domain.Firewall;\nimport org.jclouds.profitbricks.http.parser.firewall.rule.FirewallRuleListResponseHandler;\nimport org.xml.sax.SAXException;\n\npublic class FirewallResponseHandler extends BaseFirewallResponseHandler<Firewall> {\n\n   private boolean done = false;\n\n   @Inject\n   FirewallResponseHandler(FirewallRuleListResponseHandler firewallRuleListResponseHandler) {\n      super(firewallRuleListResponseHandler);\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) throws SAXException {\n      if (done)\n         return;\n\n      if (useFirewallRuleParser)\n         firewallRuleListResponseHandler.endElement(uri, localName, qName);\n      else {\n         setPropertyOnEndTag(qName);\n         if (\"return\".equals(qName)) {\n            done = true;\n            builder.rules(firewallRuleListResponseHandler.getResult());\n         }\n         clearTextBuffer();\n      }\n\n      if (\"firewallRules\".equals(qName))\n         useFirewallRuleParser = false;\n   }\n\n   @Override\n   public void reset() {\n      this.builder = Firewall.builder();\n   }\n\n   @Override\n   public Firewall getResult() {\n      return builder.build();\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/http/parser/firewall/rule/BaseFirewallRuleResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.firewall.rule;\n\nimport org.jclouds.profitbricks.domain.Firewall;\nimport org.jclouds.profitbricks.domain.Firewall.Protocol;\n\nimport org.jclouds.profitbricks.http.parser.BaseProfitBricksResponseHandler;\n\npublic abstract class BaseFirewallRuleResponseHandler<T> extends BaseProfitBricksResponseHandler<T> {\n\n   protected Firewall.Rule.Builder builder;\n\n   protected BaseFirewallRuleResponseHandler() {\n      this.builder = Firewall.Rule.builder();\n   }\n\n   @Override\n   protected void setPropertyOnEndTag(String qName) {\n      if (\"firewallRuleId\".equals(qName))\n         builder.id(textToStringValue());\n      else if (\"name\".equals(qName))\n         builder.name(textToStringValue());\n      else if (\"portRangeEnd\".equals(qName))\n         builder.portRangeEnd(textToIntValue());\n      else if (\"portRangeStart\".equals(qName))\n         builder.portRangeStart(textToIntValue());\n      else if (\"protocol\".equals(qName))\n         builder.protocol(Protocol.fromValue(textToStringValue()));\n      else if (\"sourceIp\".equals(qName))\n         builder.sourceIp(textToStringValue());\n      else if (\"sourceMac\".equals(qName))\n         builder.sourceMac(textToStringValue());\n      else if (\"targetIp\".equals(qName))\n         builder.targetIp(textToStringValue());\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/http/parser/firewall/rule/FirewallRuleListResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.firewall.rule;\n\nimport java.util.List;\n\nimport org.jclouds.profitbricks.domain.Firewall.Rule;\nimport org.xml.sax.SAXException;\n\nimport com.google.common.collect.Lists;\n\npublic class FirewallRuleListResponseHandler extends BaseFirewallRuleResponseHandler<List<Rule>> {\n\n   private List<Rule> rules;\n\n   FirewallRuleListResponseHandler() {\n      this.rules = Lists.newArrayList();\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) throws SAXException {\n      setPropertyOnEndTag(qName);\n\n      if (\"firewallRules\".equals(qName))\n         rules.add(builder.build());\n      clearTextBuffer();\n\n   }\n\n   @Override\n   public void reset() {\n      this.rules = Lists.newArrayList();\n   }\n\n   @Override\n   public List<Rule> getResult() {\n      return rules;\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/http/parser/image/BaseImageResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.image;\n\nimport org.jclouds.profitbricks.domain.Image;\nimport org.jclouds.profitbricks.domain.Image.Type;\nimport org.jclouds.profitbricks.domain.Location;\nimport org.jclouds.profitbricks.domain.OsType;\nimport org.jclouds.profitbricks.http.parser.BaseProfitBricksResponseHandler;\n\npublic abstract class BaseImageResponseHandler<T> extends BaseProfitBricksResponseHandler<T> {\n\n   protected Image.Builder builder;\n\n   BaseImageResponseHandler() {\n      this.builder = Image.builder();\n   }\n\n   @Override\n   protected void setPropertyOnEndTag(String qName) {\n      if (\"imageId\".equals(qName))\n         builder.id(textToStringValue());\n      else if (\"imageName\".equals(qName))\n         builder.name(textToStringValue());\n      else if (\"imageSize\".equals(qName))\n         builder.size(textToFloatValue());\n      else if (\"imageType\".equals(qName))\n         builder.type(Type.fromValue(textToStringValue()));\n      else if (\"location\".equals(qName))\n         builder.location(Location.fromId(textToStringValue()));\n      else if (\"osType\".equals(qName))\n         builder.osType(OsType.fromValue(textToStringValue()));\n      else if (\"public\".equals(qName))\n         builder.isPublic(textToBooleanValue());\n      else if (\"writeable\".equals(qName))\n         builder.isWriteable(textToBooleanValue());\n      else if (\"bootable\".equals(qName))\n         builder.isBootable(textToBooleanValue());\n      else if (\"cpuHotPlug\".equals(qName))\n         builder.isCpuHotPlug(textToBooleanValue());\n      else if (\"cpuHotUnPlug\".equals(qName))\n         builder.isCpuHotUnPlug(textToBooleanValue());\n      else if (\"ramHotPlug\".equals(qName))\n         builder.isRamHotPlug(textToBooleanValue());\n      else if (\"ramHotUnPlug\".equals(qName))\n         builder.isRamHotUnPlug(textToBooleanValue());\n      else if (\"nicHotPlug\".equals(qName))\n         builder.isNicHotPlug(textToBooleanValue());\n      else if (\"nicHotUnPlug\".equals(qName))\n         builder.isNicHotUnPlug(textToBooleanValue());\n      else if (\"discVirtioHotPlug\".equals(qName))\n         builder.isDiscVirtioHotPlug(textToBooleanValue());\n      else if (\"discVirtioHotUnPlug\".equals(qName))\n         builder.isDiscVirtioHotUnPlug(textToBooleanValue());\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/http/parser/image/ImageInfoResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.image;\n\nimport org.jclouds.profitbricks.domain.Image;\nimport org.xml.sax.SAXException;\n\npublic class ImageInfoResponseHandler extends BaseImageResponseHandler<Image> {\n\n   private boolean done = false;\n\n   ImageInfoResponseHandler() {\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) throws SAXException {\n      if (done)\n         return;\n      setPropertyOnEndTag(qName);\n      if (\"return\".equals(qName))\n         done = true;\n      clearTextBuffer();\n   }\n\n   @Override\n   public Image getResult() {\n      return builder.build();\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/http/parser/image/ImageListResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.image;\n\nimport com.google.common.collect.Lists;\n\nimport java.util.List;\n\nimport org.jclouds.profitbricks.domain.Image;\nimport org.xml.sax.SAXException;\n\npublic class ImageListResponseHandler extends BaseImageResponseHandler<List<Image>> {\n\n   private final List<Image> images;\n\n   ImageListResponseHandler() {\n      this.images = Lists.newArrayList();\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) throws SAXException {\n      setPropertyOnEndTag(qName);\n      if (\"return\".equals(qName)) {\n         images.add(builder.build());\n         builder = Image.builder();\n      }\n      clearTextBuffer();\n   }\n\n   @Override\n   public List<Image> getResult() {\n      return images;\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/http/parser/ipblock/BaseIpBlockResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.ipblock;\n\nimport java.util.List;\n\nimport com.google.common.collect.Lists;\n\nimport org.jclouds.profitbricks.domain.IpBlock;\nimport org.jclouds.profitbricks.domain.Location;\nimport org.jclouds.profitbricks.http.parser.BaseProfitBricksResponseHandler;\nimport org.jclouds.profitbricks.http.parser.publicip.PublicIpListResponseHandler;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\n\npublic abstract class BaseIpBlockResponseHandler<T> extends BaseProfitBricksResponseHandler<T> {\n\n   protected final PublicIpListResponseHandler publicIpListResponseHandler;\n   protected List<String> ips;\n\n   protected IpBlock.Builder builder;\n   protected boolean usePublicIpListParser = false;\n\n   BaseIpBlockResponseHandler(PublicIpListResponseHandler publicIpListResponseHandler) {\n      this.builder = IpBlock.builder();\n      this.publicIpListResponseHandler = publicIpListResponseHandler;\n      this.ips = Lists.newArrayList();\n   }\n\n   @Override\n   public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {\n      if (\"publicIps\".equals(qName))\n         usePublicIpListParser = true;\n      if (usePublicIpListParser)\n         publicIpListResponseHandler.startElement(uri, localName, qName, attributes);\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      if (usePublicIpListParser)\n         publicIpListResponseHandler.characters(ch, start, length);\n      else\n         super.characters(ch, start, length);\n   }\n\n   @Override\n   protected void setPropertyOnEndTag(String qName) {\n      if (\"blockId\".equals(qName))\n         builder.id(textToStringValue());\n      else if (\"location\".equals(qName))\n         builder.location(Location.fromId(textToStringValue()));\n      else if (\"ips\".equals(qName))\n         ips.add(textToStringValue());\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/http/parser/ipblock/IpBlockListResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.ipblock;\n\nimport java.util.List;\n\nimport org.jclouds.profitbricks.domain.IpBlock;\nimport org.jclouds.profitbricks.http.parser.publicip.PublicIpListResponseHandler;\nimport org.xml.sax.SAXException;\n\nimport com.google.inject.Inject;\nimport com.google.common.collect.Lists;\n\npublic class IpBlockListResponseHandler extends BaseIpBlockResponseHandler<List<IpBlock>> {\n\n   private final List<IpBlock> ipBlocks;\n\n   @Inject\n   IpBlockListResponseHandler(PublicIpListResponseHandler publicIpListResponseHandler) {\n      super(publicIpListResponseHandler);\n      ipBlocks = Lists.newArrayList();\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) throws SAXException {\n      if (usePublicIpListParser)\n         publicIpListResponseHandler.endElement(uri, localName, qName);\n      else {\n         setPropertyOnEndTag(qName);\n         if (\"return\".equals(qName)) {\n            ipBlocks.add(builder\n                    .publicIps(publicIpListResponseHandler.getResult())\n                    .build());\n            publicIpListResponseHandler.reset();\n            builder = IpBlock.builder();\n         }\n         clearTextBuffer();\n      }\n\n      if (\"publicIps\".equals(qName))\n         usePublicIpListParser = false;\n\n   }\n\n   @Override\n   public List<IpBlock> getResult() {\n      return ipBlocks;\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/http/parser/ipblock/IpBlockResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.ipblock;\n\nimport com.google.inject.Inject;\nimport org.jclouds.profitbricks.domain.IpBlock;\nimport org.jclouds.profitbricks.http.parser.publicip.PublicIpListResponseHandler;\nimport org.xml.sax.SAXException;\n\npublic class IpBlockResponseHandler extends BaseIpBlockResponseHandler<IpBlock> {\n\n   private boolean done = false;\n\n   @Inject\n   IpBlockResponseHandler(PublicIpListResponseHandler publicIpListResponseHandler) {\n      super(publicIpListResponseHandler);\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) throws SAXException {\n      if (done)\n         return;\n\n      if (usePublicIpListParser)\n         publicIpListResponseHandler.endElement(uri, localName, qName);\n      else {\n         setPropertyOnEndTag(qName);\n         if (\"return\".equals(qName)) {\n            done = true;\n            builder.publicIps(publicIpListResponseHandler.getResult())\n                    .ips(ips);\n         }\n         clearTextBuffer();\n      }\n\n      if (\"publicIps\".equals(qName))\n         usePublicIpListParser = false;\n   }\n\n   @Override\n   public void reset() {\n      this.builder = IpBlock.builder();\n   }\n\n   @Override\n   public IpBlock getResult() {\n      return builder.build();\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/http/parser/loadbalancer/BaseLoadBalancerResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.loadbalancer;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Date;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.profitbricks.domain.DataCenter;\nimport org.jclouds.profitbricks.domain.LoadBalancer;\nimport org.jclouds.profitbricks.domain.LoadBalancer.Algorithm;\nimport org.jclouds.profitbricks.domain.ProvisioningState;\nimport org.jclouds.profitbricks.http.parser.BaseProfitBricksResponseHandler;\nimport org.jclouds.profitbricks.http.parser.firewall.FirewallListResponseHandler;\nimport org.jclouds.profitbricks.http.parser.server.ServerListResponseHandler;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\n\npublic abstract class BaseLoadBalancerResponseHandler<T> extends BaseProfitBricksResponseHandler<T> {\n\n   protected final ServerListResponseHandler balancedServerResponseHandler;\n   protected final FirewallListResponseHandler firewallListResponseHandler;\n\n   protected LoadBalancer.Builder builder;\n   protected DataCenter.Builder dataCenterBuilder;\n\n   protected final DateService dateService;\n\n   protected boolean useBalancedServerParser = false;\n   protected boolean useFirewallParser = false;\n\n   protected BaseLoadBalancerResponseHandler(DateService dateService,\n           ServerListResponseHandler balancedServerResponseHandler, FirewallListResponseHandler firewallResponseHandler) {\n\n      checkNotNull(dateService, \"DateService cannot be null\");\n      checkNotNull(balancedServerResponseHandler, \"BalancedServerResponseHandler cannot be null\");\n      checkNotNull(firewallResponseHandler, \"FirewallListResponseHandler cannot be null\");\n\n      this.dateService = dateService;\n      this.builder = LoadBalancer.builder();\n      this.dataCenterBuilder = DataCenter.builder();\n\n      this.balancedServerResponseHandler = balancedServerResponseHandler;\n      this.firewallListResponseHandler = firewallResponseHandler;\n   }\n\n   @Override\n   public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {\n      if (\"balancedServers\".equals(qName))\n         useBalancedServerParser = true;\n      if (\"firewall\".equals(qName))\n         useFirewallParser = true;\n\n      if (useBalancedServerParser)\n         balancedServerResponseHandler.startElement(uri, localName, qName, attributes);\n      else if (useFirewallParser)\n         firewallListResponseHandler.startElement(uri, localName, qName, attributes);\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      if (useBalancedServerParser)\n         balancedServerResponseHandler.characters(ch, start, length);\n      else if (useFirewallParser)\n         firewallListResponseHandler.characters(ch, start, length);\n      else\n         super.characters(ch, start, length);\n   }\n\n   protected final Date textToIso8601Date() {\n      return dateService.iso8601DateOrSecondsDateParse(textToStringValue());\n   }\n\n   @Override\n   protected void setPropertyOnEndTag(String qName) {\n      if (\"loadBalancerId\".equals(qName))\n         builder.id(textToStringValue());\n      else if (\"loadBalancerName\".equals(qName))\n         builder.name(textToStringValue());\n      else if (\"loadBalancerAlgorithm\".equals(qName))\n         builder.algorithm(Algorithm.fromValue(textToStringValue()));\n      else if (\"dataCenterId\".equals(qName))\n         dataCenterBuilder.id(textToStringValue());\n      else if (\"dataCenterVersion\".equals(qName))\n         dataCenterBuilder.version(textToIntValue());\n      else if (\"internetAccess\".equals(qName))\n         builder.internetAccess(textToBooleanValue());\n      else if (\"ip\".equals(qName))\n         builder.ip(textToStringValue());\n      else if (\"lanId\".equals(qName))\n         builder.lanId(textToIntValue());\n      else if (\"provisioningState\".equals(qName))\n         builder.state(ProvisioningState.fromValue(textToStringValue()));\n      else if (\"creationTime\".equals(qName))\n         builder.creationTime(textToIso8601Date());\n      else if (\"lastModificationTime\".equals(qName))\n         builder.lastModificationTime(textToIso8601Date());\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/http/parser/loadbalancer/LoadBalancerIdOnlyResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.loadbalancer;\n\nimport org.jclouds.profitbricks.http.parser.BaseProfitBricksResponseHandler;\nimport org.xml.sax.SAXException;\n\n/**\n * Handler for parsing SOAP response where <i>loadBalancerId</i> is the only <i>usable</i> value.\n *\n * Other properties available (which are ignored): requestId, dataCenterId, dataCenterVersion\n */\npublic class LoadBalancerIdOnlyResponseHandler extends BaseProfitBricksResponseHandler<String> {\n\n   private String loadBalancerId;\n\n   LoadBalancerIdOnlyResponseHandler() {\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) throws SAXException {\n      setPropertyOnEndTag(qName);\n      clearTextBuffer();\n   }\n\n   @Override\n   protected void setPropertyOnEndTag(String qName) {\n      if (\"loadBalancerId\".equals(qName))\n         loadBalancerId = textToStringValue();\n   }\n\n   @Override\n   public String getResult() {\n      return loadBalancerId;\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/http/parser/loadbalancer/LoadBalancerListResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.loadbalancer;\n\nimport com.google.common.collect.Lists;\nimport com.google.inject.Inject;\n\nimport java.util.List;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.profitbricks.domain.DataCenter;\nimport org.jclouds.profitbricks.domain.LoadBalancer;\nimport org.jclouds.profitbricks.http.parser.firewall.FirewallListResponseHandler;\nimport org.jclouds.profitbricks.http.parser.server.ServerListResponseHandler;\nimport org.xml.sax.SAXException;\n\npublic class LoadBalancerListResponseHandler extends BaseLoadBalancerResponseHandler<List<LoadBalancer>> {\n\n   private final List<LoadBalancer> loadBalancers;\n\n   @Inject\n   LoadBalancerListResponseHandler(DateService dateService, ServerListResponseHandler balancedServerResponseHandler, FirewallListResponseHandler firewallListResponseHandler) {\n      super(dateService, balancedServerResponseHandler, firewallListResponseHandler);\n      this.loadBalancers = Lists.newArrayList();\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) throws SAXException {\n      if (useBalancedServerParser)\n         balancedServerResponseHandler.endElement(uri, localName, qName);\n      else if (useFirewallParser)\n         firewallListResponseHandler.endElement(uri, localName, qName);\n      else {\n         setPropertyOnEndTag(qName);\n         if (\"return\".equals(qName)) {\n            loadBalancers.add(builder\n                    .dataCenter(dataCenterBuilder.build())\n                    .firewalls(firewallListResponseHandler.getResult())\n                    .balancedServers(balancedServerResponseHandler.getResult())\n                    .build());\n\n            balancedServerResponseHandler.reset();\n            firewallListResponseHandler.reset();\n\n            builder = LoadBalancer.builder();\n         }\n         clearTextBuffer();\n      }\n      if (\"firewall\".equals(qName))\n         useFirewallParser = false;\n      else if (\"balancedServers\".equals(qName))\n         useBalancedServerParser = false;\n\n   }\n\n   @Override\n   public void reset() {\n      this.dataCenterBuilder = DataCenter.builder();\n   }\n\n   @Override\n   public List<LoadBalancer> getResult() {\n      return loadBalancers;\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/http/parser/loadbalancer/LoadBalancerResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.loadbalancer;\n\nimport com.google.inject.Inject;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.profitbricks.domain.LoadBalancer;\nimport org.jclouds.profitbricks.http.parser.firewall.FirewallListResponseHandler;\nimport org.jclouds.profitbricks.http.parser.server.ServerListResponseHandler;\nimport org.xml.sax.SAXException;\n\npublic class LoadBalancerResponseHandler extends BaseLoadBalancerResponseHandler<LoadBalancer> {\n\n   private boolean done = false;\n\n   @Inject\n   LoadBalancerResponseHandler(DateService dateService, ServerListResponseHandler serverListResponseHandler,\n           FirewallListResponseHandler firewallListResponseHandler) {\n      super(dateService, serverListResponseHandler, firewallListResponseHandler);\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) throws SAXException {\n      if (done)\n         return;\n\n      if (useBalancedServerParser)\n         balancedServerResponseHandler.endElement(uri, localName, qName);\n      else if (useFirewallParser)\n         firewallListResponseHandler.endElement(uri, localName, qName);\n      else {\n         setPropertyOnEndTag(qName);\n         if (\"return\".equals(qName)) {\n            done = true;\n            builder.dataCenter(dataCenterBuilder.build())\n                    .balancedServers(balancedServerResponseHandler.getResult())\n                    .firewalls(firewallListResponseHandler.getResult());\n         }\n         clearTextBuffer();\n      }\n\n      if (\"balancedServers\".equals(qName))\n         useBalancedServerParser = false;\n      else if (\"firewall\".equals(qName))\n         useFirewallParser = false;\n\n   }\n\n   @Override\n   public LoadBalancer getResult() {\n      return builder.build();\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/http/parser/nic/BaseNicResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.nic;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.jclouds.profitbricks.domain.Nic;\nimport org.jclouds.profitbricks.domain.ProvisioningState;\nimport org.jclouds.profitbricks.http.parser.BaseProfitBricksResponseHandler;\nimport org.jclouds.profitbricks.http.parser.firewall.FirewallResponseHandler;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\n\npublic abstract class BaseNicResponseHandler<T> extends BaseProfitBricksResponseHandler<T> {\n\n   protected final FirewallResponseHandler firewallResponseHandler;\n\n   protected boolean useFirewallParser = false;\n   protected Nic.Builder builder;\n   protected List<String> ips;\n\n   BaseNicResponseHandler(FirewallResponseHandler firewallResponseHandler) {\n      this.builder = Nic.builder();\n      this.firewallResponseHandler = firewallResponseHandler;\n      this.ips = new ArrayList<String>();\n   }\n\n   @Override\n   public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {\n      if (\"firewall\".equals(qName))\n         useFirewallParser = true;\n      if (useFirewallParser)\n         firewallResponseHandler.startElement(uri, localName, qName, attributes);\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      if (useFirewallParser)\n         firewallResponseHandler.characters(ch, start, length);\n      else\n         super.characters(ch, start, length);\n   }\n\n   @Override\n   protected void setPropertyOnEndTag(String qName) {\n      if (\"dataCenterId\".equals(qName))\n         builder.dataCenterId(textToStringValue());\n      else if (\"nicName\".equals(qName))\n         builder.name(textToStringValue());\n      else if (\"nicId\".equals(qName))\n         builder.id(textToStringValue());\n      else if (\"lanId\".equals(qName))\n         builder.lanId(textToIntValue());\n      else if (\"internetAccess\".equals(qName))\n         builder.internetAccess(textToBooleanValue());\n      else if (\"serverId\".equals(qName))\n         builder.serverId(textToStringValue());\n      else if (\"ips\".equals(qName))\n         ips.add(textToStringValue());\n      else if (\"macAddress\".equals(qName))\n         builder.macAddress(textToStringValue());\n      else if (\"dhcpActive\".equals(qName))\n         builder.dhcpActive(textToBooleanValue());\n      else if (\"gatewayIp\".equals(qName))\n         builder.gatewayIp(textToStringValue());\n      else if (\"provisioningState\".equals(qName))\n         builder.state(ProvisioningState.fromValue(textToStringValue()));\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/http/parser/nic/NicIdOnlyResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.nic;\n\nimport org.jclouds.profitbricks.http.parser.BaseProfitBricksResponseHandler;\nimport org.xml.sax.SAXException;\n\n/**\n * Handler for parsing SOAP response where <i>nicId</i> is the only <i>usable</i> value.\n *\n * Other properties available (which are ignored): requestId, dataCenterId, dataCenterVersion\n */\npublic class NicIdOnlyResponseHandler extends BaseProfitBricksResponseHandler<String> {\n\n   private String nicId;\n\n   NicIdOnlyResponseHandler() {\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) throws SAXException {\n      setPropertyOnEndTag(qName);\n      clearTextBuffer();\n   }\n\n   @Override\n   protected void setPropertyOnEndTag(String qName) {\n      if (\"nicId\".equals(qName))\n         nicId = textToStringValue();\n   }\n\n   @Override\n   public String getResult() {\n      return nicId;\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/http/parser/nic/NicListResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.nic;\n\nimport java.util.ArrayList;\n\nimport com.google.common.collect.Lists;\nimport com.google.inject.Inject;\n\nimport org.jclouds.profitbricks.domain.Nic;\nimport org.xml.sax.SAXException;\n\nimport java.util.List;\n\nimport org.jclouds.profitbricks.http.parser.firewall.FirewallResponseHandler;\n\npublic class NicListResponseHandler extends BaseNicResponseHandler<List<Nic>> {\n\n   private List<Nic> nics;\n\n   @Inject\n   public NicListResponseHandler(FirewallResponseHandler firewallResponseHandler) {\n      super(firewallResponseHandler);\n      this.nics = Lists.newArrayList();\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) throws SAXException {\n      if (useFirewallParser)\n         firewallResponseHandler.endElement(uri, localName, qName);\n      else {\n         setPropertyOnEndTag(qName);\n         if (\"return\".equals(qName) || \"nics\".equals(qName)) {\n            nics.add(builder\n                    .ips(ips)\n                    .firewall(firewallResponseHandler.getResult())\n                    .build());\n            builder = Nic.builder();\n            ips = new ArrayList<String>();\n            firewallResponseHandler.reset();\n         }\n         clearTextBuffer();\n      }\n\n      if (\"firewall\".equals(qName))\n         useFirewallParser = false;\n   }\n\n   @Override\n   public void reset() {\n      this.ips = new ArrayList<String>();\n      this.nics = Lists.newArrayList();\n   }\n\n   @Override\n   public List<Nic> getResult() {\n      return nics;\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/http/parser/nic/NicResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.nic;\n\nimport java.util.ArrayList;\n\nimport com.google.inject.Inject;\n\nimport org.jclouds.profitbricks.domain.Nic;\nimport org.jclouds.profitbricks.http.parser.firewall.FirewallResponseHandler;\nimport org.xml.sax.SAXException;\n\npublic class NicResponseHandler extends BaseNicResponseHandler<Nic> {\n\n   private boolean done = false;\n\n   @Inject\n   public NicResponseHandler(FirewallResponseHandler firewallResponseHandler) {\n      super(firewallResponseHandler);\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) throws SAXException {\n      if (done)\n         return;\n\n      if (useFirewallParser)\n         firewallResponseHandler.endElement(uri, localName, qName);\n      else {\n         setPropertyOnEndTag(qName);\n         if (\"return\".equals(qName)) {\n            done = true;\n            builder.ips(ips)\n                    .firewall(firewallResponseHandler.getResult());\n            ips = new ArrayList<String>();\n            firewallResponseHandler.reset();\n         }\n         clearTextBuffer();\n      }\n\n      if (\"firewall\".equals(qName))\n         useFirewallParser = false;\n   }\n\n   @Override\n   public Nic getResult() {\n      return builder.build();\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/http/parser/publicip/BasePublicIpResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.publicip;\n\nimport org.jclouds.profitbricks.domain.IpBlock;\nimport org.jclouds.profitbricks.http.parser.BaseProfitBricksResponseHandler;\n\npublic abstract class BasePublicIpResponseHandler<T> extends BaseProfitBricksResponseHandler<T> {\n\n   protected IpBlock.PublicIp.Builder builder;\n\n   BasePublicIpResponseHandler() {\n      this.builder = IpBlock.PublicIp.builder();\n   }\n\n   @Override\n   protected void setPropertyOnEndTag(String qName) {\n      if (\"ip\".equals(qName))\n         builder.ip(textToStringValue());\n      else if (\"nicId\".equals(qName))\n         builder.nicId(textToStringValue());\n\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/http/parser/publicip/PublicIpListResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.publicip;\n\nimport com.google.common.collect.Lists;\nimport java.util.List;\nimport org.jclouds.profitbricks.domain.IpBlock.PublicIp;\nimport org.xml.sax.SAXException;\n\npublic class PublicIpListResponseHandler extends BasePublicIpResponseHandler<List<PublicIp>> {\n\n   private List<PublicIp> publicIps;\n\n   PublicIpListResponseHandler() {\n      this.publicIps = Lists.newArrayList();\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) throws SAXException {\n      setPropertyOnEndTag(qName);\n\n      if (\"publicIps\".equals(qName)){\n         publicIps.add(builder.build());\n         this.builder = PublicIp.builder();\n      }\n      clearTextBuffer();\n   }\n\n   @Override\n   public void reset() {\n      this.publicIps = Lists.newArrayList();\n   }\n\n   @Override\n   public List<PublicIp> getResult() {\n      return publicIps;\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/http/parser/server/BaseServerResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.server;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Date;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.profitbricks.domain.AvailabilityZone;\nimport org.jclouds.profitbricks.domain.DataCenter;\nimport org.jclouds.profitbricks.domain.OsType;\nimport org.jclouds.profitbricks.domain.ProvisioningState;\nimport org.jclouds.profitbricks.domain.Server;\nimport org.jclouds.profitbricks.http.parser.BaseProfitBricksResponseHandler;\nimport org.jclouds.profitbricks.http.parser.nic.NicListResponseHandler;\nimport org.jclouds.profitbricks.http.parser.storage.StorageListResponseHandler;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.SAXException;\n\npublic abstract class BaseServerResponseHandler<T> extends BaseProfitBricksResponseHandler<T> {\n\n   protected final StorageListResponseHandler storageListResponseHandler;\n   protected final NicListResponseHandler nicListResponseHandler;\n\n   protected DataCenter.Builder dataCenterBuilder;\n   protected Server.Builder builder;\n\n   protected final DateService dateService;\n\n   protected boolean useStorageParser = false;\n   protected boolean useNicParser = false;\n\n   BaseServerResponseHandler(DateService dateService, StorageListResponseHandler storageListResponseHandler,\n           NicListResponseHandler nicListResponseHandler) {\n      checkNotNull(dateService, \"DateService cannot be null\");\n      checkNotNull(storageListResponseHandler, \"StorageListResponseHandler cannot be null\");\n      checkNotNull(nicListResponseHandler, \"NicListResponseHandler cannot be null\");\n\n      this.dateService = dateService;\n      this.storageListResponseHandler = storageListResponseHandler;\n      this.nicListResponseHandler = nicListResponseHandler;\n      this.builder = Server.builder();\n      this.dataCenterBuilder = DataCenter.builder();\n   }\n\n   @Override\n   public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {\n      if (\"connectedStorages\".equals(qName))\n         useStorageParser = true;\n      else if (\"nics\".equals(qName))\n         useNicParser = true;\n\n      if (useStorageParser)\n         storageListResponseHandler.startElement(uri, localName, qName, attributes);\n      else if (useNicParser)\n         nicListResponseHandler.startElement(uri, localName, qName, attributes);\n      else\n         super.startElement(uri, localName, qName, attributes);\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      if (useStorageParser)\n         storageListResponseHandler.characters(ch, start, length);\n      else if (useNicParser)\n         nicListResponseHandler.characters(ch, start, length);\n      else\n         super.characters(ch, start, length);\n   }\n\n   protected final Date textToIso8601Date() {\n      return dateService.iso8601DateOrSecondsDateParse(textToStringValue());\n   }\n\n   @Override\n   protected void setPropertyOnEndTag(String qName) {\n      if (\"dataCenterId\".equals(qName))\n         dataCenterBuilder.id(textToStringValue());\n      else if (\"dataCenterVersion\".equals(qName))\n         dataCenterBuilder.version(textToIntValue());\n      else if (\"serverId\".equals(qName))\n         builder.id(textToStringValue());\n      else if (\"serverName\".equals(qName))\n         builder.name(textToStringValue());\n      else if (\"cores\".equals(qName))\n         builder.cores(textToIntValue());\n      else if (\"ram\".equals(qName))\n         builder.ram(textToIntValue());\n      else if (\"provisioningState\".equals(qName))\n         builder.state(ProvisioningState.fromValue(textToStringValue()));\n      else if (\"virtualMachineState\".equals(qName))\n         builder.status(Server.Status.fromValue(textToStringValue()));\n      else if (\"osType\".equals(qName))\n         builder.osType(OsType.fromValue(textToStringValue()));\n      else if (\"availabilityZone\".equals(qName))\n         builder.availabilityZone(AvailabilityZone.fromValue(textToStringValue()));\n      else if (\"creationTime\".equals(qName))\n         builder.creationTime(textToIso8601Date());\n      else if (\"lastModificationTime\".equals(qName))\n         builder.lastModificationTime(textToIso8601Date());\n      else if (\"internetAccess\".equals(qName))\n         builder.hasInternetAccess(textToBooleanValue());\n      else if (\"cpuHotPlug\".equals(qName))\n         builder.isCpuHotPlug(textToBooleanValue());\n      else if (\"ramHotPlug\".equals(qName))\n         builder.isRamHotPlug(textToBooleanValue());\n      else if (\"nicHotPlug\".equals(qName))\n         builder.isNicHotPlug(textToBooleanValue());\n      else if (\"nicHotUnPlug\".equals(qName))\n         builder.isNicHotUnPlug(textToBooleanValue());\n      else if (\"discVirtioHotPlug\".equals(qName))\n         builder.isDiscVirtioHotPlug(textToBooleanValue());\n      else if (\"discVirtioHotUnPlug\".equals(qName))\n         builder.isDiscVirtioHotUnPlug(textToBooleanValue());\n      else if (\"activate\".equals(qName))\n         builder.loadBalanced(textToBooleanValue());\n      else if (\"balancedNicId\".equals(qName))\n         builder.balancedNicId(textToStringValue());\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/http/parser/server/ServerIdOnlyResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.server;\n\nimport org.jclouds.profitbricks.http.parser.BaseProfitBricksResponseHandler;\nimport org.xml.sax.SAXException;\n\n/**\n * Handler for parsing SOAP response where <i>serverId</i> is the only <i>usable</i> value.\n *\n * Other properties available (which are ignored): requestId, dataCenterId, dataCenterVersion\n */\npublic class ServerIdOnlyResponseHandler extends BaseProfitBricksResponseHandler<String> {\n\n   private String serverId;\n\n   ServerIdOnlyResponseHandler() {\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) throws SAXException {\n      setPropertyOnEndTag(qName);\n      clearTextBuffer();\n   }\n\n   @Override\n   protected void setPropertyOnEndTag(String qName) {\n      if (\"serverId\".equals(qName))\n         serverId = textToStringValue();\n   }\n\n   @Override\n   public String getResult() {\n      return serverId;\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/http/parser/server/ServerInfoResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.server;\n\nimport com.google.inject.Inject;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.profitbricks.domain.Server;\nimport org.jclouds.profitbricks.http.parser.nic.NicListResponseHandler;\nimport org.jclouds.profitbricks.http.parser.storage.StorageListResponseHandler;\nimport org.xml.sax.SAXException;\n\npublic class ServerInfoResponseHandler extends BaseServerResponseHandler<Server> {\n\n   private boolean done = false;\n\n   @Inject\n   ServerInfoResponseHandler(DateService dateService, StorageListResponseHandler storageListResponseHandler,\n           NicListResponseHandler nicListResponseHandler) {\n      super(dateService, storageListResponseHandler, nicListResponseHandler);\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) throws SAXException {\n      if (done)\n         return;\n\n      if (useStorageParser)\n         storageListResponseHandler.endElement(uri, localName, qName);\n      else if (useNicParser)\n         nicListResponseHandler.endElement(uri, localName, qName);\n      else {\n         setPropertyOnEndTag(qName);\n         if (\"return\".equals(qName)) {\n            done = true;\n            builder\n                    .dataCenter(dataCenterBuilder.build())\n                    .storages(storageListResponseHandler.getResult())\n                    .nics(nicListResponseHandler.getResult());\n         }\n         clearTextBuffer();\n      }\n\n      if (\"connectedStorages\".equals(qName))\n         useStorageParser = false;\n      else if (\"nics\".equals(qName))\n         useNicParser = false;\n   }\n\n   @Override\n   public Server getResult() {\n      return builder.build();\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/http/parser/server/ServerListResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.server;\n\nimport com.google.common.collect.Lists;\nimport com.google.inject.Inject;\n\nimport java.util.List;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.profitbricks.domain.DataCenter;\nimport org.jclouds.profitbricks.domain.Server;\nimport org.jclouds.profitbricks.http.parser.nic.NicListResponseHandler;\nimport org.jclouds.profitbricks.http.parser.storage.StorageListResponseHandler;\nimport org.xml.sax.SAXException;\n\npublic class ServerListResponseHandler extends BaseServerResponseHandler<List<Server>> {\n\n   private List<Server> servers;\n\n   @Inject\n   ServerListResponseHandler(DateService dateService, StorageListResponseHandler storageListResponseHandler,\n           NicListResponseHandler nicListResponseHandler) {\n      super(dateService, storageListResponseHandler, nicListResponseHandler);\n      this.servers = Lists.newArrayList();\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) throws SAXException {\n\n      if (useStorageParser)\n         storageListResponseHandler.endElement(uri, localName, qName);\n      else if (useNicParser)\n         nicListResponseHandler.endElement(uri, localName, qName);\n      else {\n         setPropertyOnEndTag(qName);\n         if (\"return\".equals(qName) || \"servers\".equals(qName) || \"balancedServers\".equals(qName)) {\n            Server.Builder sdb = null;\n            try {\n               sdb = builder\n                       .storages(storageListResponseHandler.getResult())\n                       .nics(nicListResponseHandler.getResult());\n               servers.add(sdb\n                       // For LoadBalancer's case, there's no DataCenter (may throw NPE on #build()). \n                       .dataCenter(dataCenterBuilder.build())\n                       .build());\n            } catch (Exception ex) {\n               servers.add(sdb.build());\n            }\n            storageListResponseHandler.reset();\n            nicListResponseHandler.reset();\n\n            builder = Server.builder();\n         }\n         clearTextBuffer();\n      }\n\n      if (\"connectedStorages\".equals(qName))\n         useStorageParser = false;\n      else if (\"nics\".equals(qName))\n         useNicParser = false;\n   }\n\n   @Override\n   public void reset() {\n      this.servers = Lists.newArrayList();\n      this.dataCenterBuilder = DataCenter.builder();\n   }\n\n   @Override\n   public List<Server> getResult() {\n      return servers;\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/http/parser/snapshot/BaseSnapshotResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.snapshot;\n\nimport java.util.Date;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.profitbricks.domain.Location;\nimport org.jclouds.profitbricks.domain.OsType;\nimport org.jclouds.profitbricks.domain.ProvisioningState;\nimport org.jclouds.profitbricks.domain.Snapshot;\nimport org.jclouds.profitbricks.http.parser.BaseProfitBricksResponseHandler;\n\npublic abstract class BaseSnapshotResponseHandler<T> extends BaseProfitBricksResponseHandler<T> {\n\n   protected Snapshot.Builder builder;\n\n   protected final DateService dateService;\n\n   BaseSnapshotResponseHandler(DateService dateService) {\n      this.dateService = dateService;\n      this.builder = Snapshot.builder();\n   }\n\n   protected final Date textToIso8601Date() {\n      return dateService.iso8601DateOrSecondsDateParse(textToStringValue());\n   }\n\n   @Override\n   protected void setPropertyOnEndTag(String qName) {\n      if (\"snapshotId\".equals(qName))\n         builder.id(textToStringValue());\n      else if (\"snapshotName\".equals(qName))\n         builder.name(textToStringValue());\n      else if (\"snapshotSize\".equals(qName))\n         builder.size(textToFloatValue());\n      else if (\"osType\".equals(qName))\n         builder.osType(OsType.fromValue(textToStringValue()));\n      else if (\"location\".equals(qName))\n         builder.location(Location.fromId(textToStringValue()));\n      else if (\"description\".equals(qName))\n         builder.description(qName);\n      else if (\"bootable\".equals(qName))\n         builder.isBootable(textToBooleanValue());\n      else if (\"cpuHotPlug\".equals(qName))\n         builder.isCpuHotPlug(textToBooleanValue());\n      else if (\"cpuHotUnPlug\".equals(qName))\n         builder.isCpuHotUnPlug(textToBooleanValue());\n      else if (\"ramHotPlug\".equals(qName))\n         builder.isRamHotPlug(textToBooleanValue());\n      else if (\"ramHotUnPlug\".equals(qName))\n         builder.isRamHotUnPlug(textToBooleanValue());\n      else if (\"nicHotPlug\".equals(qName))\n         builder.isNicHotPlug(textToBooleanValue());\n      else if (\"nicHotUnPlug\".equals(qName))\n         builder.isNicHotUnPlug(textToBooleanValue());\n      else if (\"discVirtioHotPlug\".equals(qName))\n         builder.isDiscVirtioHotPlug(textToBooleanValue());\n      else if (\"discVirtioHotUnPlug\".equals(qName))\n         builder.isDiscVirtioHotUnPlug(textToBooleanValue());\n      else if (\"provisioningState\".equals(qName))\n         builder.state(ProvisioningState.fromValue(textToStringValue()));\n      else if (\"creationTimestamp\".equals(qName))\n         builder.creationTime(textToIso8601Date());\n      else if (\"modificationTimestamp\".equals(qName))\n         builder.lastModificationTime(textToIso8601Date());\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/http/parser/snapshot/SnapshotListResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.snapshot;\n\nimport com.google.common.collect.Lists;\nimport com.google.inject.Inject;\n\nimport org.jclouds.profitbricks.domain.Snapshot;\nimport org.xml.sax.SAXException;\n\nimport java.util.List;\n\nimport org.jclouds.date.DateService;\n\npublic class SnapshotListResponseHandler extends BaseSnapshotResponseHandler<List<Snapshot>> {\n\n   private final List<Snapshot> snapshots;\n\n   @Inject\n   SnapshotListResponseHandler(DateService dateService) {\n      super(dateService);\n      this.snapshots = Lists.newArrayList();\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) throws SAXException {\n      setPropertyOnEndTag(qName);\n      if (\"return\".equals(qName)) {\n         snapshots.add(builder.build());\n         builder = Snapshot.builder();\n      }\n      clearTextBuffer();\n   }\n\n   @Override\n   public List<Snapshot> getResult() {\n      return snapshots;\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/http/parser/snapshot/SnapshotResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.snapshot;\n\nimport com.google.inject.Inject;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.profitbricks.domain.Snapshot;\nimport org.xml.sax.SAXException;\n\npublic class SnapshotResponseHandler extends BaseSnapshotResponseHandler<Snapshot> {\n\n   private boolean done = false;\n\n   @Inject\n   SnapshotResponseHandler(DateService dateService) {\n      super(dateService);\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) throws SAXException {\n      if (done)\n         return;\n      setPropertyOnEndTag(qName);\n      if (\"return\".equals(qName))\n         done = true;\n      clearTextBuffer();\n   }\n\n   @Override\n   public Snapshot getResult() {\n      return builder.build();\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/http/parser/state/GetProvisioningStateResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.state;\n\nimport org.jclouds.profitbricks.domain.ProvisioningState;\nimport org.jclouds.profitbricks.http.parser.BaseProfitBricksResponseHandler;\nimport org.xml.sax.SAXException;\n\npublic class GetProvisioningStateResponseHandler extends BaseProfitBricksResponseHandler<ProvisioningState> {\n\n   private ProvisioningState state = ProvisioningState.UNRECOGNIZED;\n\n   GetProvisioningStateResponseHandler() {\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) throws SAXException {\n      setPropertyOnEndTag(qName);\n      clearTextBuffer();\n   }\n\n   @Override\n   protected void setPropertyOnEndTag(String qName) {\n      if (\"return\".equals(qName))\n         state = ProvisioningState.fromValue(textToStringValue());\n   }\n\n   @Override\n   public ProvisioningState getResult() {\n      return state;\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/http/parser/storage/BaseStorageResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.storage;\n\nimport java.util.Date;\nimport java.util.List;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.profitbricks.domain.ProvisioningState;\nimport org.jclouds.profitbricks.domain.Storage;\nimport org.jclouds.profitbricks.domain.Storage.BusType;\nimport org.jclouds.profitbricks.http.parser.BaseProfitBricksResponseHandler;\n\nimport com.google.common.collect.Lists;\n\npublic abstract class BaseStorageResponseHandler<T> extends BaseProfitBricksResponseHandler<T> {\n\n   protected final DateService dateService;\n\n   protected Storage.Builder builder;\n   protected List<String> serverIds;\n\n   protected BaseStorageResponseHandler(DateService dateService) {\n      this.dateService = dateService;\n      this.builder = Storage.builder();\n      this.serverIds = Lists.newArrayList();\n   }\n\n   protected final Date textToIso8601Date() {\n      return dateService.iso8601DateOrSecondsDateParse(textToStringValue());\n   }\n\n   @Override\n   protected void setPropertyOnEndTag(String qName) {\n//            <requestId>?</requestId>\n//            <dataCenterId>?</dataCenterId>\n//            <dataCenterVersion>?</dataCenterVersion>\n      if (\"storageId\".equals(qName))\n         builder.id(textToStringValue());\n      else if (\"size\".equals(qName))\n         builder.size(textToFloatValue());\n      else if (\"storageName\".equals(qName))\n         builder.name(textToStringValue());\n      else if (\"provisioningState\".equals(qName))\n         builder.state(ProvisioningState.fromValue(textToStringValue()));\n      else if (\"creationTime\".equals(qName))\n         builder.creationTime(textToIso8601Date());\n      else if (\"lastModificationTime\".equals(qName))\n         builder.lastModificationTime(textToIso8601Date());\n//            <mountImage>\n//               <imageId>?</imageId>\n//               <imageName>?</imageName>\n//            </mountImage>\n      else if (\"serverIds\".equals(qName))\n         serverIds.add(textToStringValue());\n      else if (\"bootDevice\".equals(qName))\n         builder.bootDevice(textToBooleanValue());\n      else if (\"busType\".equals(qName))\n         builder.busType(BusType.fromValue(textToStringValue()));\n      else if (\"deviceNumber\".equals(qName))\n         builder.deviceNumber(textToIntValue());\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/http/parser/storage/StorageIdOnlyResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.storage;\n\nimport org.jclouds.profitbricks.http.parser.BaseProfitBricksResponseHandler;\nimport org.xml.sax.SAXException;\n\npublic class StorageIdOnlyResponseHandler extends BaseProfitBricksResponseHandler<String> {\n\n   private String storageId;\n\n   StorageIdOnlyResponseHandler() {\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) throws SAXException {\n      setPropertyOnEndTag(qName);\n      clearTextBuffer();\n   }\n\n   @Override\n   protected void setPropertyOnEndTag(String qName) {\n      if (\"storageId\".equals(qName))\n         storageId = textToStringValue();\n   }\n\n   @Override\n   public String getResult() {\n      return storageId;\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/http/parser/storage/StorageInfoResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.storage;\n\nimport com.google.inject.Inject;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.profitbricks.domain.Storage;\nimport org.xml.sax.SAXException;\n\npublic class StorageInfoResponseHandler extends BaseStorageResponseHandler<Storage> {\n\n   private boolean done = false;\n\n   @Inject\n   StorageInfoResponseHandler(DateService dateService) {\n      super(dateService);\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) throws SAXException {\n      if (done)\n         return;\n      setPropertyOnEndTag(qName);\n      if (\"return\".equals(qName)) {\n         done = true;\n         builder.serverIds(serverIds);\n      }\n      clearTextBuffer();\n   }\n\n   @Override\n   public Storage getResult() {\n      return builder.build();\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/http/parser/storage/StorageListResponseHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.storage;\n\nimport java.util.List;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.profitbricks.domain.Storage;\nimport org.xml.sax.SAXException;\n\nimport com.google.inject.Inject;\nimport com.google.common.collect.Lists;\n\npublic class StorageListResponseHandler extends BaseStorageResponseHandler<List<Storage>> {\n\n   private List<Storage> storages;\n\n   @Inject\n   StorageListResponseHandler(DateService dateService) {\n      super(dateService);\n      this.storages = Lists.newArrayList();\n   }\n\n   @Override\n   public void endElement(String uri, String localName, String qName) throws SAXException {\n      setPropertyOnEndTag(qName);\n      if (\"return\".equals(qName) || \"connectedStorages\".equals(qName) || \"storages\".equals(qName)) {\n         storages.add(builder\n                 .serverIds(serverIds)\n                 .build());\n         builder = Storage.builder();\n         serverIds = Lists.newArrayList();\n      }\n      clearTextBuffer();\n   }\n\n   @Override\n   public void reset() {\n      this.storages = Lists.newArrayList();\n   }\n\n   @Override\n   public List<Storage> getResult() {\n      return storages;\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/util/MacAddresses.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.util;\n\nimport java.util.regex.Pattern;\n\npublic class MacAddresses {\n\n   private static final String MAC_ADDR_FORMAT = \"^([0-9a-f]{2}[:]){5}([0-9a-f]{2})$\";\n   private static final Pattern MAC_ADDR_PATTERN = Pattern.compile(MAC_ADDR_FORMAT);\n\n   public static boolean isMacAddress(String in) {\n      return MAC_ADDR_PATTERN.matcher(in).matches();\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/main/java/org/jclouds/profitbricks/util/Preconditions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.util;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Strings.isNullOrEmpty;\nimport static com.google.common.net.InetAddresses.isInetAddress;\nimport static org.jclouds.profitbricks.util.MacAddresses.isMacAddress;\n\nimport java.util.List;\nimport java.util.regex.Pattern;\n\nimport org.jclouds.profitbricks.domain.Firewall;\nimport org.jclouds.profitbricks.domain.Firewall.Protocol;\n\n/**\n * Static convenience methods for validating various ProfitBricks domain preconditions\n */\npublic final class Preconditions {\n\n   private static final Pattern INVALID_CHARS = Pattern.compile(\"^.*[@/\\\\|'`’^].*$\");\n\n   public static void checkInvalidChars(String name) {\n      checkArgument(!isNullOrEmpty(name), \"Name is required.\");\n      checkArgument(!INVALID_CHARS.matcher(name).matches(), \"Name must not contain any of: @ / \\\\ | ' ` ’ ^\");\n   }\n\n   public static void checkIp(String ip) {\n      checkArgument(isInetAddress(ip), \"IP '%s' is invalid\", ip);\n   }\n\n   public static void checkIps(List<String> ips) {\n      checkNotNull(ips, \"Null ip list\");\n      for (String ip : ips)\n         checkIp(ip);\n   }\n\n   public static void checkPortRange(Integer portRangeStart, Integer portRangeEnd, Firewall.Protocol protocol) {\n      checkArgument(!(portRangeEnd == null ^ portRangeStart == null), \"Port range must be both present or null\");\n      if (portRangeEnd != null) {\n         checkArgument(protocol == Firewall.Protocol.TCP || protocol == Firewall.Protocol.UDP, \"Port range can only be set for TCP or UDP\");\n         checkArgument(portRangeEnd > portRangeStart, \"portRangeEnd must be greater than portRangeStart\");\n         checkArgument(portRangeEnd >= 1 && portRangeEnd <= 65534, \"Port range end must be 1 to 65534\");\n         checkArgument(portRangeStart >= 1 && portRangeStart <= 65534, \"Port range start must be 1 to 65534\");\n      }\n   }\n\n   public static void checkMacAddress(String macAddress) {\n      checkArgument(isMacAddress(macAddress), \"MAC must match pattern 'aa:bb:cc:dd:ee:ff'\");\n   }\n\n   public static void checkIcmp(Integer icmpType, Integer icmpCode, Protocol protocol) {\n      checkNotNull(protocol, \"Protocol can't be null\");\n      if (protocol == Protocol.ICMP) {\n         if (icmpType != null)\n            checkArgument(icmpType >= 1 && icmpType <= 254, \"ICMP type must be 1 to 254\");\n         if (icmpCode != null)\n            checkArgument(icmpCode >= 1 && icmpCode <= 254, \"ICMP code must be 1 to 254\");\n      }\n   }\n\n   public static void checkLanId(Integer id) {\n      checkArgument(id >= 0, \"LAN ID must be non-negative\");\n   }\n\n   public static void checkCores(Integer cores) {\n      checkArgument(cores > 0, \"Number of cores must be atleast 1.\");\n   }\n\n   public static void checkRam(Integer ram, Boolean isRamHotPlug) {\n      int minRam = (isRamHotPlug == null || !isRamHotPlug) ? 256 : 1024;\n      checkArgument(ram >= minRam && ram % 256 == 0, \"RAM must be multiples of 256 with minimum of 256 MB \"\n              + \"(1024 MB if ramHotPlug is enabled)\");\n   }\n\n   public static void checkSize(Float size) {\n      checkArgument(size > 1, \"Storage size must be > 1GB\");\n   }\n   \n   private static final int VALID_PASSWORD_MIN_LENGTH = 8;\n   private static final int VALID_PASSWORD_MAX_LENGTH = 50;\n   private static final String PASSWORD_FORMAT = String.format(\n           \"[a-zA-Z0-9][^iIloOwWyYzZ10]{%d,%d}\", VALID_PASSWORD_MIN_LENGTH - 1, VALID_PASSWORD_MAX_LENGTH);\n   private static final Pattern PASSWORD_PATTERN = Pattern.compile(PASSWORD_FORMAT);\n\n   public static void checkPassword(String password) {\n      checkArgument(PASSWORD_PATTERN.matcher(password).matches(), \"Password must be between 8 and 50 characters, \"\n              + \"only a-z, A-Z, 0-9 without  characters i, I, l, o, O, w, W, y, Y, z, Z and 1, 0\");\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/BaseProfitBricksLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks;\n\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_RUNNING;\nimport static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_SUSPENDED;\nimport static org.jclouds.profitbricks.config.ProfitBricksComputeProperties.POLL_PREDICATE_DATACENTER;\nimport static org.jclouds.profitbricks.config.ProfitBricksComputeProperties.POLL_PREDICATE_SNAPSHOT;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.List;\nimport java.util.Objects;\nimport java.util.Properties;\n\nimport org.jclouds.apis.BaseApiLiveTest;\nimport org.jclouds.profitbricks.domain.DataCenter;\nimport org.jclouds.profitbricks.domain.Location;\nimport org.jclouds.profitbricks.domain.Server;\nimport org.jclouds.profitbricks.domain.ProvisioningState;\nimport org.jclouds.profitbricks.features.DataCenterApi;\nimport org.jclouds.profitbricks.features.ServerApi;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.FluentIterable;\nimport com.google.inject.Injector;\nimport com.google.inject.Key;\nimport com.google.inject.Module;\nimport com.google.inject.TypeLiteral;\nimport com.google.inject.name.Names;\n\nimport org.jclouds.profitbricks.domain.Nic;\nimport org.jclouds.profitbricks.features.NicApi;\n\npublic abstract class BaseProfitBricksLiveTest extends BaseApiLiveTest<ProfitBricksApi> {\n\n   public static final Location testLocation = Location.US_LAS;\n\n   private Predicate<String> dataCenterAvailable;\n   private Predicate<String> snapshotAvailable;\n   private Predicate<String> serverRunning;\n   private Predicate<String> serverSuspended;\n\n   public BaseProfitBricksLiveTest() {\n      provider = \"profitbricks\";\n   }\n\n   @Override\n   protected ProfitBricksApi create(Properties props, Iterable<Module> modules) {\n      Injector injector = newBuilder().modules(modules).overrides(props).buildInjector();\n      dataCenterAvailable = injector.getInstance(Key.get(new TypeLiteral<Predicate<String>>() {\n      }, Names.named(POLL_PREDICATE_DATACENTER)));\n      snapshotAvailable = injector.getInstance(Key.get(new TypeLiteral<Predicate<String>>() {\n      }, Names.named(POLL_PREDICATE_SNAPSHOT)));\n      serverRunning = injector.getInstance(Key.get(new TypeLiteral<Predicate<String>>() {\n      }, Names.named(TIMEOUT_NODE_RUNNING)));\n      serverSuspended = injector.getInstance(Key.get(new TypeLiteral<Predicate<String>>() {\n      }, Names.named(TIMEOUT_NODE_SUSPENDED)));\n\n      return injector.getInstance(ProfitBricksApi.class);\n   }\n\n   protected void assertDataCenterAvailable(DataCenter dataCenter) {\n      assertDataCenterAvailable(dataCenter.id());\n   }\n\n   protected void assertDataCenterAvailable(String dataCenterId) {\n      assertTrue(dataCenterAvailable.apply(dataCenterId),\n              String.format(\"Datacenter %s wasn't available in the configured timeout\", dataCenterId));\n   }\n   \n   protected void assertSnapshotAvailable(String snapshotId){\n      assertTrue(snapshotAvailable.apply(snapshotId),\n              String.format(\"Snapshot %s wasn't available in the configured timeout\", snapshotId));\n   }\n\n   protected void assertNodeRunning(String serverId) {\n      assertTrue(serverRunning.apply(serverId), String.format(\"Server %s did not start in the configured timeout\", serverId));\n   }\n\n   protected void assertNodeSuspended(String serverId) {\n      assertTrue(serverSuspended.apply(serverId), String.format(\"Server %s did not stop in the configured timeout\", serverId));\n   }\n\n   protected DataCenter findOrCreateDataCenter(final String name) {\n      DataCenterApi dataCenterApi = api.dataCenterApi();\n\n      return FluentIterable.from(dataCenterApi.getAllDataCenters()).firstMatch(new Predicate<DataCenter>() {\n\n         @Override\n         public boolean apply(DataCenter input) {\n            boolean match = Objects.equals(input.name(), name);\n            if (match && input.location() == testLocation)\n               assertDataCenterAvailable(input);\n\n            return match;\n         }\n      }).or(new Supplier<DataCenter>() {\n\n         @Override\n         public DataCenter get() {\n            DataCenter dataCenter = api.dataCenterApi().createDataCenter(\n                    DataCenter.Request.creatingPayload(name, testLocation));\n            assertDataCenterAvailable(dataCenter);\n\n            return api.dataCenterApi().getDataCenter(dataCenter.id());\n         }\n      });\n   }\n\n   protected Server findOrCreateServer(final DataCenter dataCenter) {\n      return FluentIterable.from(dataCenter.servers()).firstMatch(new Predicate<Server>() {\n\n         @Override\n         public boolean apply(Server input) {\n            return input.state() == ProvisioningState.AVAILABLE;\n         }\n      }).or(new Supplier<Server>() {\n\n         @Override\n         public Server get() {\n            ServerApi serverApi = api.serverApi();\n            String name = String.format(\"server-%d\", dataCenter.servers().size());\n            String createdServerId = serverApi.createServer(\n                    Server.Request.creatingBuilder()\n                    .dataCenterId(dataCenter.id())\n                    .name(name)\n                    .cores(1)\n                    .ram(256)\n                    .build());\n            assertDataCenterAvailable(dataCenter);\n            assertNodeRunning(createdServerId);\n\n            return serverApi.getServer(createdServerId);\n         }\n      });\n   }\n\n   protected Nic findOrCreateNic(final DataCenter dataCenter) {\n      final NicApi nicApi = api.nicApi();\n      final List<Nic> nics = nicApi.getAllNics();\n\n      return FluentIterable.from(nics).firstMatch(new Predicate<Nic>() {\n\n         @Override\n         public boolean apply(Nic input) {\n            return Objects.equals(input.dataCenterId(), dataCenter.id())\n                    && input.state() == ProvisioningState.AVAILABLE;\n         }\n      }).or(new Supplier<Nic>() {\n\n         @Override\n         public Nic get() {\n            Server server = findOrCreateServer(dataCenter);\n            String name = String.format(\"%s-nic-%d\", server.name(), nics.size());\n            String nicId = nicApi.createNic(Nic.Request.creatingBuilder()\n                    .name(name)\n                    .lanId(1)\n                    .serverId(server.id())\n                    .build());\n            assertDataCenterAvailable(dataCenter);\n\n            return nicApi.getNic(nicId);\n         }\n      });\n   }\n\n   protected void destroyDataCenter(final DataCenter dataCenter) {\n      boolean success = api.dataCenterApi().deleteDataCenter(dataCenter.id());\n      assertTrue(success, \"DataCenter wasn't deleted\");\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/ProfitBricksProviderMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks;\n\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ProfitBricksProviderMetadataTest\")\npublic class ProfitBricksProviderMetadataTest extends BaseProviderMetadataTest {\n\n   public ProfitBricksProviderMetadataTest() {\n      super(new ProfitBricksProviderMetadata(), new ProfitBricksApiMetadata());\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/binder/datacenter/CreateDataCenterRequestBinderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.binder.datacenter;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport org.jclouds.profitbricks.domain.DataCenter;\nimport org.jclouds.profitbricks.domain.Location;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"CreateDataCenterRequestBinderTest\")\npublic class CreateDataCenterRequestBinderTest {\n\n   @Test\n   public void testCreatePayload() {\n      CreateDataCenterRequestBinder binder = new CreateDataCenterRequestBinder();\n\n      DataCenter.Request.CreatePayload payload = DataCenter.Request.creatingPayload(\"JClouds-DC\", Location.DE_FKB);\n\n      String actual = binder.createPayload(payload);\n      assertNotNull(actual, \"Binder returned null payload\");\n      assertEquals(actual, expectedPayload);\n   }\n\n   private final String expectedPayload\n           = (\"      <ws:createDataCenter>\\n\"\n           + \"         <request>\\n\"\n           + \"            <dataCenterName>JClouds-DC</dataCenterName>\\n\"\n           + \"            <location>de/fkb</location>\\n\"\n           + \"         </request>\\n\"\n           + \"      </ws:createDataCenter>\\n\").replaceAll(\"\\\\s+\", \"\");\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/binder/datacenter/UpdateDataCenterRequestBinderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.binder.datacenter;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport org.jclouds.profitbricks.domain.DataCenter;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"UpdateDataCenterRequestBinderTest\")\npublic class UpdateDataCenterRequestBinderTest {\n\n   @Test\n   public void testCreatePayload() {\n      UpdateDataCenterRequestBinder binder = new UpdateDataCenterRequestBinder();\n\n      DataCenter.Request.UpdatePayload payload = DataCenter.Request.updatingPayload(\"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee\", \"Apache-DC\");\n\n      String actual = binder.createPayload(payload);\n      assertNotNull(actual, \"Binder returned null payload\");\n      assertEquals(actual, expectedPayload);\n   }\n\n   private final String expectedPayload\n           = (\"      <ws:updateDataCenter>\\n\"\n           + \"         <request>\\n\"\n           + \"            <dataCenterId>aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee</dataCenterId>\\n\"\n           + \"            <dataCenterName>Apache-DC</dataCenterName>\\n\"\n           + \"         </request>\\n\"\n           + \"      </ws:updateDataCenter>\").replaceAll(\"\\\\s+\", \"\");\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/binder/drive/AddRomDriveToServerRequestBinderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.binder.drive;\n\nimport org.jclouds.profitbricks.domain.Drive;\nimport static org.testng.Assert.assertEquals;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"AddRomDriveToServerRequestBinderTest\")\npublic class AddRomDriveToServerRequestBinderTest {\n\n   @Test\n   public void testAddRomDriveToServerPayload() {\n      AddRomDriveToServerRequestBinder binder = new AddRomDriveToServerRequestBinder();\n\n      Drive.Request.AddRomDriveToServerPayload payload = Drive.Request.AddRomDriveToServerPayload.builder()\n              .serverId(\"server-id\")\n              .imageId(\"image-id\")\n              .deviceNumber(\"device-number\")\n              .build();\n\n      String actual = binder.createPayload(payload);\n      assertEquals(actual, expectedPayload);\n   }\n\n   private final String expectedPayload\n           = (\"   <ws:addRomDriveToServer>\"\n           + \"    <request>\"\n           + \"       <imageId>image-id</imageId>\"\n           + \"       <serverId>server-id</serverId>\"\n           + \"       <deviceNumber>device-number</deviceNumber>\"\n           + \"    </request>\"\n           + \" </ws:addRomDriveToServer>\").replaceAll(\"\\\\s+\", \"\");\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/binder/firewall/AddFirewallRuleToNicRequestBinderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.binder.firewall;\n\nimport org.jclouds.profitbricks.domain.Firewall;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport com.google.common.collect.ImmutableList;\n\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"AddFirewallRuleToNicRequestBinderTest\")\npublic class AddFirewallRuleToNicRequestBinderTest {\n\n   @Test\n   public void testCreatePayload() {\n      AddFirewallRuleToNicRequestBinder binder = new AddFirewallRuleToNicRequestBinder();\n\n      Firewall.Request.AddRulePayload payload = Firewall.Request.createAddRulePayload(\n              \"nic-id\", ImmutableList.of(\n                      Firewall.Rule.builder()\n                      .name(\"name\")\n                      .portRangeEnd(45678)\n                      .portRangeStart(12345)\n                      .protocol(Firewall.Protocol.TCP)\n                      .sourceIp(\"192.168.0.1\")\n                      .sourceMac(\"aa:bb:cc:dd:ee:ff\")\n                      .targetIp(\"192.168.0.2\")\n                      .build()\n              ));\n\n      String actual = binder.createPayload(payload);\n      assertNotNull(actual, \"Binder returned null payload\");\n      assertEquals(actual, expectedPayload);\n   }\n\n   private final String expectedPayload = (\"  <ws:addFirewallRulesToNic>\\n\"\n           + \"        <nicId>nic-id</nicId>\\n\"\n           + \"            <request>\\n\"\n           + \"                <name>name</name>\\n\"\n           + \"                <portRangeEnd>45678</portRangeEnd>\\n\"\n           + \"                <portRangeStart>12345</portRangeStart>\\n\"\n           + \"                <protocol>TCP</protocol>\\n\"\n           + \"                <sourceIp>192.168.0.1</sourceIp>\\n\"\n           + \"                <sourceMac>aa:bb:cc:dd:ee:ff</sourceMac>\\n\"\n           + \"                <targetIp>192.168.0.2</targetIp>\\n\"\n           + \"            </request>\\n\"\n           + \"        </ws:addFirewallRulesToNic>\").replaceAll(\"\\\\s+\", \"\");\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/binder/firewall/FirewallBinderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.binder.firewall;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.List;\n\nimport org.jclouds.profitbricks.binder.firewall.FirewallBinder.ActivateFirewallRequestBinder;\nimport org.jclouds.profitbricks.binder.firewall.FirewallBinder.DeactivateFirewallRequestBinder;\nimport org.jclouds.profitbricks.binder.firewall.FirewallBinder.DeleteFirewallRequestBinder;\nimport org.jclouds.profitbricks.binder.firewall.FirewallBinder.RemoveFirewallRuleRequestBinder;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"FirewallBinderTest\")\npublic class FirewallBinderTest {\n\n   @Test\n   public void testActivateFirewallBindPayload() {\n      ActivateFirewallRequestBinder binder = new ActivateFirewallRequestBinder();\n\n      List<String> payload = ImmutableList.of(\n              \"firewall-id-1\",\n              \"firewall-id-2\",\n              \"firewall-id-3\",\n              \"firewall-id-4\"\n      );\n\n      String actual = binder.createPayload(payload);\n      assertNotNull(actual, \"Binder returned null payload\");\n\n      String expected = (\"<ws:activateFirewalls>\\n\"\n              + \"         <firewallIds>firewall-id-1</firewallIds>\\n\"\n              + \"         <firewallIds>firewall-id-2</firewallIds>\\n\"\n              + \"         <firewallIds>firewall-id-3</firewallIds>\\n\"\n              + \"         <firewallIds>firewall-id-4</firewallIds>\\n\"\n              + \"      </ws:activateFirewalls>\").replaceAll(\"\\\\s+\", \"\");\n\n      assertEquals(actual, expected);\n   }\n\n   @Test\n   public void testDeactivateFirewallBindPayload() {\n      DeactivateFirewallRequestBinder binder = new DeactivateFirewallRequestBinder();\n\n      List<String> payload = ImmutableList.of(\n              \"firewall-id-1\",\n              \"firewall-id-2\",\n              \"firewall-id-3\",\n              \"firewall-id-4\"\n      );\n\n      String actual = binder.createPayload(payload);\n      assertNotNull(actual, \"Binder returned null payload\");\n\n      String expected = (\"<ws:deactivateFirewalls>\\n\"\n              + \"         <firewallIds>firewall-id-1</firewallIds>\\n\"\n              + \"         <firewallIds>firewall-id-2</firewallIds>\\n\"\n              + \"         <firewallIds>firewall-id-3</firewallIds>\\n\"\n              + \"         <firewallIds>firewall-id-4</firewallIds>\\n\"\n              + \"      </ws:deactivateFirewalls>\").replaceAll(\"\\\\s+\", \"\");\n\n      assertEquals(actual, expected);\n   }\n\n   @Test\n   public void testDeleteFirewallBindPayload() {\n      DeleteFirewallRequestBinder binder = new DeleteFirewallRequestBinder();\n\n      List<String> payload = ImmutableList.of(\n              \"firewall-id-1\",\n              \"firewall-id-2\",\n              \"firewall-id-3\",\n              \"firewall-id-4\"\n      );\n\n      String actual = binder.createPayload(payload);\n      assertNotNull(actual, \"Binder returned null payload\");\n\n      String expected = (\"<ws:deleteFirewalls>\\n\"\n              + \"         <firewallIds>firewall-id-1</firewallIds>\\n\"\n              + \"         <firewallIds>firewall-id-2</firewallIds>\\n\"\n              + \"         <firewallIds>firewall-id-3</firewallIds>\\n\"\n              + \"         <firewallIds>firewall-id-4</firewallIds>\\n\"\n              + \"      </ws:deleteFirewalls>\").replaceAll(\"\\\\s+\", \"\");\n\n      assertEquals(actual, expected);\n   }\n\n   @Test\n   public void testRemoveFirewallRuleBindPayload() {\n      RemoveFirewallRuleRequestBinder binder = new RemoveFirewallRuleRequestBinder();\n\n      List<String> payload = ImmutableList.of(\n              \"firewall-rule-id-1\",\n              \"firewall-rule-id-2\",\n              \"firewall-rule-id-3\",\n              \"firewall-rule-id-4\"\n      );\n\n      String actual = binder.createPayload(payload);\n      assertNotNull(actual, \"Binder returned null payload\");\n\n      String expected = (\"<ws:removeFirewallRules>\\n\"\n              + \"         <firewallRuleIds>firewall-rule-id-1</firewallRuleIds>\\n\"\n              + \"         <firewallRuleIds>firewall-rule-id-2</firewallRuleIds>\\n\"\n              + \"         <firewallRuleIds>firewall-rule-id-3</firewallRuleIds>\\n\"\n              + \"         <firewallRuleIds>firewall-rule-id-4</firewallRuleIds>\\n\"\n              + \"      </ws:removeFirewallRules>\").replaceAll(\"\\\\s+\", \"\");\n\n      assertEquals(actual, expected);\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/binder/loadbalancer/CreateLoadBalancerRequestBinderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.binder.loadbalancer;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport com.google.common.collect.ImmutableList;\n\nimport org.testng.annotations.Test;\nimport org.jclouds.profitbricks.domain.LoadBalancer;\nimport org.jclouds.profitbricks.domain.LoadBalancer.Algorithm;\n\n@Test(groups = \"unit\", testName = \"CreateLoadBalancerRequestBinderTest\")\npublic class CreateLoadBalancerRequestBinderTest {\n\n   @Test\n   public void testCreatePayload() {\n      CreateLoadBalancerRequestBinder binder = new CreateLoadBalancerRequestBinder();\n\n      String actual = binder.createPayload(\n              LoadBalancer.Request.creatingBuilder()\n              .dataCenterId(\"datacenter-id\")\n              .name(\"load-balancer-name\")\n              .algorithm(Algorithm.ROUND_ROBIN)\n              .ip(\"10.0.0.1\")\n              .lanId(2)\n              .serverIds(ImmutableList.<String>of(\n                              \"server-id-1\", \"server-id-2\"))\n              .build());\n\n      assertNotNull(actual, \"Binder returned null payload\");\n      assertEquals(actual, expectedPayload);\n   }\n\n   private final String expectedPayload\n           = (\"<ws:createLoadBalancer>\\n\"\n           + \"            <request>\\n\"\n           + \"                <dataCenterId>datacenter-id</dataCenterId>\\n\"\n           + \"                <loadBalancerName>load-balancer-name</loadBalancerName>\\n\"\n           + \"                <loadBalancerAlgorithm>ROUND_ROBIN</loadBalancerAlgorithm>\\n\"\n           + \"                <ip>10.0.0.1</ip>\\n\"\n           + \"                <lanId>2</lanId>\\n\"\n           + \"                <serverIds>server-id-1</serverIds>\\n\"\n           + \"                <serverIds>server-id-2</serverIds>\\n\"\n           + \"            </request>\\n\"\n           + \"        </ws:createLoadBalancer>\").replaceAll(\"\\\\s+\", \"\");\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/binder/loadbalancer/DeregisterLoadBalancerRequestBinderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.binder.loadbalancer;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport com.google.common.collect.ImmutableList;\n\nimport org.jclouds.profitbricks.domain.LoadBalancer;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"DeregisterLoadBalancerRequestBinderTest\")\npublic class DeregisterLoadBalancerRequestBinderTest {\n\n   @Test\n   public void testDeregisterPayload() {\n      DeregisterLoadBalancerRequestBinder binder = new DeregisterLoadBalancerRequestBinder();\n\n      String actual = binder.createPayload(LoadBalancer.Request.createDeregisteringPayload(\n              \"load-balancer-id\", ImmutableList.of(\"1\", \"2\")));\n\n      assertNotNull(actual, \"Binder returned null payload\");\n      assertEquals(actual, expectedPayload);\n   }\n\n   private final String expectedPayload\n           = (\"        <ws:deregisterServersOnLoadBalancer>\\n\"\n           + \"                <serverIds>1</serverIds>\\n\"\n           + \"                <serverIds>2</serverIds>\\n\"\n           + \"                <loadBalancerId>load-balancer-id</loadBalancerId>\\n\"\n           + \"        </ws:deregisterServersOnLoadBalancer>\").replaceAll(\"\\\\s+\", \"\");\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/binder/loadbalancer/RegisterLoadBalancerRequestBinderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.binder.loadbalancer;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport org.jclouds.profitbricks.domain.LoadBalancer;\n\nimport com.google.common.collect.ImmutableList;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"RegisterLoadBalancerRequestBinderTest\")\npublic class RegisterLoadBalancerRequestBinderTest {\n\n   @Test\n   public void testRegisterPayload() {\n      RegisterLoadBalancerRequestBinder binder = new RegisterLoadBalancerRequestBinder();\n      String actual = binder.createPayload(LoadBalancer.Request.createRegisteringPaylod(\n              \"load-balancer-id\", ImmutableList.of(\"1\", \"2\")));\n\n      assertNotNull(actual, \"Binder returned null payload\");\n      assertEquals(actual, expectedPayload);\n   }\n\n   private final String expectedPayload\n           = (\"        <ws:registerServersOnLoadBalancer>\\n\"\n           + \"                <loadBalancerId>load-balancer-id</loadBalancerId>\\n\"\n           + \"                <serverIds>1</serverIds>\\n\"\n           + \"                <serverIds>2</serverIds>\\n\"\n           + \"        </ws:registerServersOnLoadBalancer>\").replaceAll(\"\\\\s+\", \"\");\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/binder/loadbalancer/UpdateLoadBalancerRequestBinderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.binder.loadbalancer;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport org.jclouds.profitbricks.domain.LoadBalancer;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"UpdateLoadBalancerRequestBinderTest\")\npublic class UpdateLoadBalancerRequestBinderTest {\n\n   @Test\n   public void testDeregisterPayload() {\n      UpdateLoadBalancerRequestBinder binder = new UpdateLoadBalancerRequestBinder();\n\n      LoadBalancer.Request.UpdatePayload payload = LoadBalancer.Request.updatingBuilder()\n              .id(\"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee\")\n              .name(\"load-balancer-name\")\n              .algorithm(LoadBalancer.Algorithm.ROUND_ROBIN)\n              .ip(\"10.0.0.2\")\n              .build();\n\n      String actual = binder.createPayload(payload);\n\n      assertNotNull(actual, \"Binder returned null payload\");\n      assertEquals(actual, expectedPayload);\n   }\n\n   private final String expectedPayload\n           = (\"        <ws:updateLoadBalancer>\\n\"\n           + \"            <request>\\n\"\n           + \"                <loadBalancerId>aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee</loadBalancerId>\\n\"\n           + \"                <loadBalancerName>load-balancer-name</loadBalancerName>\\n\"\n           + \"                <loadBalancerAlgorithm>ROUND_ROBIN</loadBalancerAlgorithm>\\n\"\n           + \"                <ip>10.0.0.2</ip>              \\n\"\n           + \"            </request>\\n\"\n           + \"        </ws:updateLoadBalancer>\").replaceAll(\"\\\\s+\", \"\");\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/binder/nic/CreateNicRequestBinderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.binder.nic;\n\nimport org.jclouds.profitbricks.domain.Nic;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"CreateNicRequestBinderTest\")\npublic class CreateNicRequestBinderTest {\n\n   @Test\n   public void testCreatePayload() {\n      CreateNicRequestBinder binder = new CreateNicRequestBinder();\n\n      Nic.Request.CreatePayload payload = Nic.Request.creatingBuilder()\n              .ip(\"192.168.0.1\")\n              .name(\"nic-name\")\n              .dhcpActive(true)\n              .serverId(\"server-id\")\n              .lanId(1)\n              .build();\n\n      String actual = binder.createPayload(payload);\n      assertNotNull(actual, \"Binder returned null payload\");\n      assertEquals(actual, expectedPayload);\n   }\n\n   private final String expectedPayload = (\"<ws:createNic>\\n\"\n           + \"            <request>\\n\"\n           + \"                <ip>192.168.0.1</ip>\\n\"\n           + \"                <nicName>nic-name</nicName>\\n\"\n           + \"                <dhcpActive>true</dhcpActive>\\n\"\n           + \"                <serverId>server-id</serverId>\\n\"\n           + \"                <lanId>1</lanId>\\n\"\n           + \"            </request>\\n\"\n           + \"        </ws:createNic>\").replaceAll(\"\\\\s+\", \"\");\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/binder/nic/SetInternetAccessBinderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.binder.nic;\n\nimport org.jclouds.profitbricks.domain.Nic;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"SetInternetAccessBinderTest\")\npublic class SetInternetAccessBinderTest {\n\n   @Test\n   public void testCreatePayload() {\n      SetInternetAccessBinder binder = new SetInternetAccessBinder();\n\n      Nic.Request.SetInternetAccessPayload payload = Nic.Request.setInternetAccessBuilder()\n              .dataCenterId(\"datacenter-id\")\n              .internetAccess(true)\n              .lanId(1)\n              .build();\n\n      String actual = binder.createPayload(payload);\n\n      assertNotNull(actual, \"Binder returned null payload\");\n      assertEquals(actual, expectedPayload);\n   }\n\n   private final String expectedPayload = (\" <ws:setInternetAccess>\\n\"\n           + \"                <dataCenterId>datacenter-id</dataCenterId>\\n\"\n           + \"                <lanId>1</lanId>\\n\"\n           + \"                <internetAccess>true</internetAccess>\\n\"\n           + \"        </ws:setInternetAccess>\").replaceAll(\"\\\\s+\", \"\");\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/binder/nic/UpdateNicRequestBinderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.binder.nic;\n\nimport org.jclouds.profitbricks.domain.Nic;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"UpdateNicRequestBinderTest\")\npublic class UpdateNicRequestBinderTest {\n\n   @Test\n   public void testCreatePayload() {\n      UpdateNicRequestBinder binder = new UpdateNicRequestBinder();\n\n      Nic.Request.UpdatePayload payload = Nic.Request.updatingBuilder()\n              .id(\"nic-id\")\n              .ip(\"192.168.0.1\")\n              .name(\"nic-name\")\n              .dhcpActive(true)\n              .lanId(1)\n              .build();\n\n      String actual = binder.createPayload(payload);\n\n      assertNotNull(actual, \"Binder returned null payload\");\n      assertEquals(actual, expectedPayload);\n   }\n\n   private final String expectedPayload = (\" <ws:updateNic>\\n\"\n           + \"            <request>\\n\"\n           + \"                <nicId>nic-id</nicId>\\n\"\n           + \"                <ip>192.168.0.1</ip>\\n\"\n           + \"                <nicName>nic-name</nicName>\\n\"\n           + \"                <dhcpActive>true</dhcpActive>\\n\"\n           + \"                <lanId>1</lanId>\\n\"\n           + \"            </request>\\n\"\n           + \"        </ws:updateNic>\").replaceAll(\"\\\\s+\", \"\");\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/binder/server/CreateServerRequestBinderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.binder.server;\n\nimport org.jclouds.profitbricks.domain.Server;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"CreateServerRequestBinderTest\")\npublic class CreateServerRequestBinderTest {\n\n   @Test\n   public void testCreatePayload() {\n      CreateServerRequestBinder binder = new CreateServerRequestBinder();\n\n      Server.Request.CreatePayload payload = Server.Request.creatingBuilder()\n              .name(\"jclouds-node\")\n              .cores(4)\n              .ram(4 * 1024)\n              .dataCenterId(\"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee\")\n              .build();\n\n      String actual = binder.createPayload(payload);\n      assertNotNull(actual, \"Binder returned null payload\");\n      assertEquals(actual, expectedPayload);\n   }\n\n   private final String expectedPayload\n           = (\"      <ws:createServer>\\n\"\n           + \"         <request>\\n\"\n           + \"            <dataCenterId>aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee</dataCenterId>\\n\"\n           + \"            <cores>4</cores>\\n\"\n           + \"            <ram>4096</ram>\\n\"\n           + \"            <serverName>jclouds-node</serverName>\\n\"\n           //           + \"            <bootFromStorageId>?</bootFromStorageId>\\n\"\n           //           + \"            <bootFromImageId>?</bootFromImageId>\\n\"\n           //           + \"            <internetAccess>false</internetAccess>\\n\"\n           //           + \"            <lanId>?</lanId>\\n\"\n           //           + \"            <osType>?</osType>\\n\"\n           //           + \"            <availabilityZone>AUTO</availabilityZone>\\n\"\n           //           + \"            <cpuHotPlug>false</cpuHotPlug>\\n\"\n           //           + \"            <ramHotPlug>false</ramHotPlug>\\n\"\n           //           + \"            <nicHotPlug>false</nicHotPlug>\\n\"\n           //           + \"            <nicHotUnPlug>false</nicHotUnPlug>\\n\"\n           //           + \"            <discVirtioHotPlug>false</discVirtioHotPlug>\\n\"\n           //           + \"            <discVirtioHotUnPlug>false</discVirtioHotUnPlug>\\n\"\n           + \"         </request>\\n\"\n           + \"      </ws:createServer>\")\n           .replaceAll(\"\\\\s+\", \"\");\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/binder/server/UpdateServerRequestBinderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.binder.server;\n\nimport org.jclouds.profitbricks.domain.Server;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"UpdateServerRequestBinderTest\")\npublic class UpdateServerRequestBinderTest {\n\n   @Test\n   public void testCreatePayload() {\n      UpdateServerRequestBinder binder = new UpdateServerRequestBinder();\n\n      Server.Request.UpdatePayload payload = Server.Request.updatingBuilder()\n              .id(\"qwertyui-qwer-qwer-qwer-qwertyyuiiop\")\n              .cores(8)\n              .ram(8 * 1024)\n              .name(\"apache-node\")\n              .build();\n\n      String actual = binder.createPayload(payload);\n      assertNotNull(actual, \"Binder returned null payload\");\n      assertEquals(actual, expectedPayload);\n   }\n\n   private final String expectedPayload\n           = (\"      <ws:updateServer>\\n\"\n           + \"         <request>\\n\"\n           + \"            <serverId>qwertyui-qwer-qwer-qwer-qwertyyuiiop</serverId>\\n\"\n           + \"            <cores>8</cores>\\n\"\n           + \"            <ram>8192</ram>\\n\"\n           + \"            <serverName>apache-node</serverName>\\n\"\n           //           + \"            <bootFromStorageId>?</bootFromStorageId>\\n\"\n           //           + \"            <bootFromImageId>?</bootFromImageId>\\n\"\n           //           + \"            <osType>?</osType>\\n\"\n           //           + \"            <availabilityZone>?</availabilityZone>\\n\"\n           //           + \"            <cpuHotPlug>?</cpuHotPlug>\\n\"\n           //           + \"            <ramHotPlug>?</ramHotPlug>\\n\"\n           //           + \"            <nicHotPlug>?</nicHotPlug>\\n\"\n           //           + \"            <nicHotUnPlug>?</nicHotUnPlug>\\n\"\n           //           + \"            <discVirtioHotPlug>?</discVirtioHotPlug>\\n\"\n           //           + \"            <discVirtioHotUnPlug>?</discVirtioHotUnPlug>\\n\"\n           + \"         </request>\\n\"\n           + \"      </ws:updateServer>\")\n           .replaceAll(\"\\\\s+\", \"\");\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/binder/snapshot/CreateSnapshotRequestBinderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.binder.snapshot;\n\nimport org.jclouds.profitbricks.domain.Snapshot;\nimport org.testng.annotations.Test;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\n@Test(groups = \"unit\", testName = \"CreateSnapshotRequestBinderTest\")\npublic class CreateSnapshotRequestBinderTest {\n\n   @Test\n   public void testCreatePayload() {\n      CreateSnapshotRequestBinder binder = new CreateSnapshotRequestBinder();\n\n      Snapshot.Request.CreatePayload payload = Snapshot.Request.creatingBuilder()\n              .storageId(\"123-1233-1324\")\n              .name(\"snapshot-name\")\n              .description(\"describing-the-snapshot\")\n              .build();\n\n      String actual = binder.createPayload(payload);\n      assertNotNull(actual, \"Binder returned null payload\");\n      assertEquals(actual, expectedPayload);\n   }\n\n   private final String expectedPayload\n           = (\"      <ws:createSnapshot>\\n\"\n           + \"<request>\\n\"\n           + \"<storageId>123-1233-1324</storageId>\\n\"\n           + \"<description>describing-the-snapshot</description>\\n\"\n           + \"<snapshotName>snapshot-name</snapshotName>\\n\"\n           + \"</request>\\n\"\n           + \"</ws:createSnapshot>\").replaceAll(\"\\\\s+\", \"\");\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/binder/snapshot/RollbackSnapshotRequestBinderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.binder.snapshot;\n\nimport org.jclouds.profitbricks.domain.Snapshot;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"RollbackSnapshotRequestBinderTest\")\npublic class RollbackSnapshotRequestBinderTest {\n\n   @Test\n   public void testRollbackPayload() {\n      RollbackSnapshotRequestBinder binder = new RollbackSnapshotRequestBinder();\n\n      Snapshot.Request.RollbackPayload payload = Snapshot.Request.createRollbackPayload(\"snapshot-id\", \"storage-id\");\n\n      String actual = binder.createPayload(payload);\n      assertNotNull(actual, \"Binder returned null payload\");\n      assertEquals(actual, expectedPayload);\n   }\n\n   private final String expectedPayload = \"<ws:rollbackSnapshot>\"\n           + \"<request>\"\n           + \"<snapshotId>snapshot-id</snapshotId>\"\n           + \"<storageId>storage-id</storageId>\"\n           + \"</request>\"\n           + \"</ws:rollbackSnapshot>\".replaceAll(\"\\\\s\", \"\");\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/binder/snapshot/UpdateSnapshotRequestBinderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.binder.snapshot;\n\nimport org.jclouds.profitbricks.domain.OsType;\nimport org.jclouds.profitbricks.domain.Snapshot;\nimport org.testng.annotations.Test;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\n@Test(groups = \"unit\", testName = \"UpdateSnapshotRequestBinderTest\")\npublic class UpdateSnapshotRequestBinderTest {\n\n   @Test\n   public void testUpdatePayload() {\n      UpdateSnapshotRequestBinder binder = new UpdateSnapshotRequestBinder();\n\n      Snapshot.Request.UpdatePayload payload = Snapshot.Request.updatingBuilder()\n              .id(\"qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh\")\n              .description(\"description\")\n              .name(\"snapshot-name\")\n              .bootable(true)\n              .osType(OsType.LINUX)\n              .isCpuHotPlug(true)\n              .isCpuHotUnPlug(true)\n              .isRamHotPlug(true)\n              .isRamHotUnPlug(true)\n              .isNicHotPlug(true)\n              .isNicHotUnPlug(true)\n              .isDiscVirtioHotPlug(true)\n              .isDiscVirtioHotUnPlug(true)\n              .build();\n\n      String actual = binder.createPayload(payload);\n      assertNotNull(actual, \"Binder returned null payload\");\n      assertEquals(actual, expectedPayload);\n\n   }\n\n   private final String expectedPayload\n           = \"<ws:updateSnapshot>\"\n           + \"<request>\"\n           + \"<snapshotId>qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh</snapshotId>\"\n           + \"<description>description</description>\"\n           + \"<snapshotName>snapshot-name</snapshotName>\"\n           + \"<bootable>true</bootable>\"\n           + \"<osType>LINUX</osType>\"\n           + \"<cpuHotPlug>true</cpuHotPlug>\"\n           + \"<cpuHotUnPlug>true</cpuHotUnPlug>\"\n           + \"<ramHotPlug>true</ramHotPlug>\"\n           + \"<ramHotUnPlug>true</ramHotUnPlug>\"\n           + \"<nicHotPlug>true</nicHotPlug>\"\n           + \"<nicHotUnPlug>true</nicHotUnPlug>\"\n           + \"<discVirtioHotPlug>true</discVirtioHotPlug>\"\n           + \"<discVirtioHotUnPlug>true</discVirtioHotUnPlug>\"\n           + \"</request>\"\n           + \"</ws:updateSnapshot>\".replaceAll(\"\\\\s\", \"\");\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/binder/storage/ConnectStorageToServerRequestBinderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.binder.storage;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport org.jclouds.profitbricks.domain.Storage;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ConnectStorageToServerRequestBinderTest\")\npublic class ConnectStorageToServerRequestBinderTest {\n\n   @Test\n   public void testCreatePayload() {\n      ConnectStorageToServerRequestBinder binder = new ConnectStorageToServerRequestBinder();\n\n      Storage.Request.ConnectPayload payload = Storage.Request.connectingBuilder()\n              .serverId(\"qwertyui-qwer-qwer-qwer-qwertyyuiiop\")\n              .storageId(\"qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh\")\n              .busType(Storage.BusType.VIRTIO)\n              .deviceNumber(2)\n              .build();\n\n      String actual = binder.createPayload(payload);\n      assertNotNull(actual, \"Binder returned null payload\");\n      assertEquals(actual, expectedPayload);\n   }\n\n   private final String expectedPayload\n           = (\"      <ws:connectStorageToServer>\\n\"\n           + \"         <request>\\n\"\n           + \"            <storageId>qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh</storageId>\\n\"\n           + \"            <serverId>qwertyui-qwer-qwer-qwer-qwertyyuiiop</serverId>\\n\"\n           + \"            <busType>VIRTIO</busType>\\n\"\n           + \"            <deviceNumber>2</deviceNumber>\\n\"\n           + \"         </request>\\n\"\n           + \"      </ws:connectStorageToServer>\")\n           .replaceAll(\"\\\\s+\", \"\");\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/binder/storage/CreateStorageRequestBinderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.binder.storage;\n\nimport org.jclouds.profitbricks.domain.Storage;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"CreateStorageRequestBinderTest\")\npublic class CreateStorageRequestBinderTest {\n\n   @Test\n   public void testCreatePayload() {\n      CreateStorageRequestBinder binder = new CreateStorageRequestBinder();\n\n      Storage.Request.CreatePayload payload = Storage.Request.creatingBuilder()\n              .name(\"hdd-1\")\n              .size(60f)\n              .dataCenterId(\"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee\")\n              .mountImageId(\"5ad99c9e-9166-11e4-9d74-52540066fee9\")\n              .imagePassword(\"qqqqqqqqq\")\n              .build();\n\n      String actual = binder.createPayload(payload);\n      assertNotNull(actual, \"Binder returned null payload\");\n      assertEquals(actual, expectedPayload);\n   }\n\n   private final String expectedPayload\n           = (\"      <ws:createStorage>\\n\"\n           + \"         <request>\\n\"\n           + \"            <dataCenterId>aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee</dataCenterId>\\n\"\n           + \"            <storageName>hdd-1</storageName>\\n\"\n           + \"            <size>60</size>\\n\"\n           + \"            <mountImageId>5ad99c9e-9166-11e4-9d74-52540066fee9</mountImageId>\\n\"\n           + \"            <profitBricksImagePassword>qqqqqqqqq</profitBricksImagePassword>\\n\"\n           + \"         </request>\\n\"\n           + \"      </ws:createStorage>\")\n           .replaceAll(\"\\\\s+\", \"\");\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/binder/storage/UpdateStorageRequestBinderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.binder.storage;\n\nimport org.jclouds.profitbricks.domain.Storage;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"UpdateStorageRequestBinderTest\")\npublic class UpdateStorageRequestBinderTest {\n\n   @Test\n   public void testUpdatePayload() {\n      UpdateStorageRequestBinder binder = new UpdateStorageRequestBinder();\n\n      Storage.Request.UpdatePayload payload = Storage.Request.updatingBuilder()\n              .id(\"pppppppp-llkl-kkjk-fhgh-vnmegrdgdsgr\")\n              .size(100f)\n              .name(\"hdd-2\")\n              .mountImageId(\"5f3cac96-915f-11e4-9d74-52540066fee9\")\n              .build();\n\n      String actual = binder.createPayload(payload);\n      assertNotNull(actual, \"Binder returned null payload\");\n      assertEquals(actual, expectedPayload);\n   }\n\n   private final String expectedPayload\n           = (\"      <ws:updateStorage>\\n\"\n           + \"         <request>\\n\"\n           + \"            <storageId>pppppppp-llkl-kkjk-fhgh-vnmegrdgdsgr</storageId>\\n\"\n           + \"            <size>100</size>\\n\"\n           + \"            <storageName>hdd-2</storageName>\\n\"\n           + \"            <mountImageId>5f3cac96-915f-11e4-9d74-52540066fee9</mountImageId>\\n\"\n           + \"         </request>\\n\"\n           + \"      </ws:updateStorage>\")\n           .replaceAll(\"\\\\s+\", \"\");\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/compute/ProfitBricksComputeServiceLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.compute;\n\nimport org.jclouds.compute.domain.ExecResponse;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.internal.BaseComputeServiceLiveTest;\nimport org.jclouds.logging.config.LoggingModule;\nimport org.jclouds.logging.slf4j.config.SLF4JLoggingModule;\nimport org.jclouds.sshj.config.SshjSshClientModule;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\nimport static com.google.common.collect.Iterables.getOnlyElement;\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.jclouds.compute.predicates.NodePredicates.inGroup;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"ProfitBricksComputeServiceLiveTest\")\npublic class ProfitBricksComputeServiceLiveTest extends BaseComputeServiceLiveTest {\n\n   public ProfitBricksComputeServiceLiveTest() {\n      provider = \"profitbricks\";\n   }\n\n   @Override\n   protected Module getSshModule() {\n      return new SshjSshClientModule();\n   }\n\n   @Override\n   protected LoggingModule getLoggingModule() {\n      return new SLF4JLoggingModule();\n   }\n\n   @Override\n   public void testOptionToNotBlock() throws Exception {\n      // ProfitBricks implementation intentionally blocks until the node is 'AVAILABLE'\n   }\n\n   @Override\n   protected void checkTagsInNodeEquals(NodeMetadata node, ImmutableSet<String> tags) {\n      // ProfitBricks doesn't support tags\n   }\n\n   @Override\n   protected void checkUserMetadataContains(NodeMetadata node, ImmutableMap<String, String> userMetadata) {\n      // ProfitBricks doesn't support user metadata\n   }\n\n   @Override\n   protected void checkResponseEqualsHostname(ExecResponse execResponse, NodeMetadata node1) {\n      // ProfitBricks doesn't support hostname\n   }\n\n   @Override\n   protected void checkOsMatchesTemplate(NodeMetadata node) {\n      // Not enough description from API to match template\n   }\n\n   @Override\n   @Test(dataProvider = \"onlyIfAutomaticHardwareSupported\", groups = {\"integration\", \"live\"})\n   public void testCreateNodeWithCustomHardware() throws Exception {\n      Template template = buildTemplate(templateBuilder()\n              .hardwareId(\"automatic:cores=2;ram=2048;disk=10\"));\n      try {\n         NodeMetadata node = getOnlyElement(client.createNodesInGroup(group + \"custom\", 1, template));\n         assertThat(node.getHardware().getRam()).isEqualTo(2048);\n         assertThat(node.getHardware().getProcessors().get(0).getCores()).isEqualTo(2);\n         assertThat(node.getHardware().getVolumes().get(0).getSize()).isEqualTo(10);\n         assertThat(node.getHardware().getId()).isEqualTo(\"cpu=2,ram=2048,disk=10\");\n      }\n      finally {\n         client.destroyNodesMatching(inGroup(group + \"custom\"));\n      }\n   }\n\n   @Test(dataProvider = \"onlyIfAutomaticHardwareSupported\", groups = {\"integration\", \"live\"})\n   public void testCreateNodeWithCustomHardwareUsingMins() throws Exception {\n      Template template = buildTemplate(templateBuilder()\n           .minCores(2).minRam(2048).minDisk(10));\n      try {\n         NodeMetadata node = getOnlyElement(client.createNodesInGroup(group + \"custom\", 1, template));\n         assertThat(node.getHardware().getRam()).isEqualTo(2048);\n         assertThat(node.getHardware().getProcessors().get(0).getCores()).isEqualTo(2);\n         assertThat(node.getHardware().getVolumes().get(0).getSize()).isEqualTo(10);\n         assertThat(node.getHardware().getId()).isEqualTo(\"cpu=2,ram=2048,disk=10\");\n      }\n      finally {\n         client.destroyNodesMatching(inGroup(group + \"custom\"));\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/compute/ProfitBricksTemplateBuilderLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.compute;\n\nimport java.util.Set;\n\nimport org.jclouds.compute.internal.BaseTemplateBuilderLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"live\", testName = \"ProfitBricksTemplateBuilderLiveTest\", singleThreaded = true)\npublic class ProfitBricksTemplateBuilderLiveTest extends BaseTemplateBuilderLiveTest {\n\n   public ProfitBricksTemplateBuilderLiveTest() {\n      this.provider = \"profitbricks\";\n   }\n\n   @Override\n   protected Set<String> getIso3166Codes() {\n      return ImmutableSet.of(\"DE-BW\", \"DE-HE\", \"US-NV\");\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/compute/concurrent/ProvisioningManagerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.compute.concurrent;\n\nimport static com.google.common.util.concurrent.Uninterruptibles.sleepUninterruptibly;\nimport static java.util.logging.Logger.getAnonymousLogger;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicInteger;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Predicates;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.base.Throwables;\n\n@Test(groups = \"unit\", testName = \"ProvisioningManagerTest\")\npublic class ProvisioningManagerTest {\n\n   @Test\n   public void testProvision() throws IOException {\n      ProvisioningManager manager = new ProvisioningManager();\n      AtomicInteger completedJobs = new AtomicInteger(0);\n\n      try {\n         for (int i = 0; i < 5; i++) {\n            manager.provision(new MockJob(200, \"slow\", completedJobs));\n            manager.provision(new MockJob(0, \"fast\", completedJobs));\n            manager.provision(new MockJob(100, \"normal\", completedJobs));\n         }\n      } finally {\n         manager.close();\n      }\n\n      assertEquals(completedJobs.get(), 15);\n   }\n\n   @Test\n   public void testProvisionInterrupted() {\n      ProvisioningManager manager = new ProvisioningManager();\n      AtomicInteger completedJobs = new AtomicInteger(0);\n\n      manager.provision(new ShutdownExecutorJob(manager, completedJobs));\n      manager.provision(new MockJob(0, \"rejected\", completedJobs));\n\n      assertEquals(completedJobs.get(), 1);\n   }\n\n   private static class MockJob extends ProvisioningJob {\n\n      private final long delay;\n      private final AtomicInteger completedJobs;\n\n      public MockJob(long delay, String group, AtomicInteger completedJobs) {\n         super(sleepPredicate(delay), group, Suppliers.ofInstance((Object) 0));\n         this.delay = delay;\n         this.completedJobs = completedJobs;\n      }\n\n      @Override\n      public Integer call() throws Exception {\n         getAnonymousLogger().info(\"ProvisioningManagerTest: Starting \" + this);\n         super.call();\n         getAnonymousLogger().info(\"ProvisioningManagerTest: Completed \" + this);\n         return completedJobs.incrementAndGet();\n      }\n\n      @Override\n      public String toString() {\n         return \"MockJob [id=\" + hashCode() + \", group=\" + getGroup() + \", delay=\" + delay + \"]\";\n      }\n   }\n\n   private static class ShutdownExecutorJob extends ProvisioningJob {\n\n      public ShutdownExecutorJob(final ProvisioningManager manager, final AtomicInteger completedJobs) {\n         super(Predicates.<String>alwaysTrue(), \"shutdown\", new Supplier<Object>() {\n            @Override\n            public Integer get() {\n               try {\n                  manager.close();\n                  return completedJobs.incrementAndGet();\n               } catch (IOException ex) {\n                  throw Throwables.propagate(ex);\n               }\n            }\n         });\n      }\n   }\n\n   private static Predicate<String> sleepPredicate(final long delay) {\n      return new Predicate<String>() {\n         @Override\n         public boolean apply(String input) {\n            sleepUninterruptibly(delay, TimeUnit.MILLISECONDS);\n            return true;\n         }\n      };\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/compute/config/StatusPredicateTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.compute.config;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.concurrent.TimeUnit;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\n\nimport org.jclouds.profitbricks.ProfitBricksApi;\nimport org.jclouds.profitbricks.compute.config.ProfitBricksComputeServiceContextModule.DataCenterProvisioningStatePredicate;\nimport org.jclouds.profitbricks.compute.config.ProfitBricksComputeServiceContextModule.ServerStatusPredicate;\nimport org.jclouds.profitbricks.compute.config.ProfitBricksComputeServiceContextModule.SnapshotProvisioningStatePredicate;\nimport org.jclouds.profitbricks.domain.ProvisioningState;\nimport org.jclouds.profitbricks.domain.Server;\nimport org.jclouds.profitbricks.domain.Snapshot;\nimport org.jclouds.profitbricks.internal.BaseProfitBricksMockTest;\nimport org.jclouds.util.Predicates2;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\n\n\n/**\n * Test class for {@link DataCenterProvisioningStatePredicate} and {@link ServerStatusPredicate}\n */\n@Test(groups = \"unit\", testName = \"ProvisioningStatusPollingPredicateTest\")\npublic class StatusPredicateTest extends BaseProfitBricksMockTest {\n\n   @Test\n   public void testDataCenterPredicate() throws Exception {\n      MockWebServer server = mockWebServer();\n\n      String payloadInProcess = payloadFromResource(\"/datacenter/datacenter-state-inprocess.xml\");\n      String payloadAvailable = payloadFromResource(\"/datacenter/datacenter-state.xml\");\n\n      // wait 3 times\n      server.enqueue(new MockResponse().setBody(payloadInProcess));\n      server.enqueue(new MockResponse().setBody(payloadInProcess));\n      server.enqueue(new MockResponse().setBody(payloadInProcess));\n      server.enqueue(new MockResponse().setBody(payloadAvailable));\n\n      server.enqueue(new MockResponse().setBody(payloadAvailable));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n\n      Predicate<String> waitUntilAvailable = Predicates2.retry(\n              new DataCenterProvisioningStatePredicate(pbApi, ProvisioningState.AVAILABLE),\n              30L, 1L, TimeUnit.SECONDS);\n\n      String id = \"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee\";\n      try {\n         waitUntilAvailable.apply(id);\n         ProvisioningState finalState = pbApi.dataCenterApi().getDataCenterState(id);\n         assertRequestHasCommonProperties(server.takeRequest());\n         assertEquals(finalState, ProvisioningState.AVAILABLE);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testServerPredicate() throws Exception {\n      MockWebServer server = mockWebServer();\n\n      String payloadInProcess = payloadFromResource(\"/server/server-state-inprocess.xml\");\n      String payloadAvailable = payloadFromResource(\"/server/server.xml\");\n\n      // wait 3 times\n      server.enqueue(new MockResponse().setBody(payloadInProcess));\n      server.enqueue(new MockResponse().setBody(payloadInProcess));\n      server.enqueue(new MockResponse().setBody(payloadInProcess));\n      server.enqueue(new MockResponse().setBody(payloadAvailable));\n\n      server.enqueue(new MockResponse().setBody(payloadAvailable));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n\n      Predicate<String> waitUntilAvailable = Predicates2.retry(\n              new ServerStatusPredicate(pbApi, Server.Status.RUNNING),\n              30L, 1L, TimeUnit.SECONDS);\n\n      String id = \"qwertyui-qwer-qwer-qwer-qwertyyuiiop\";\n      try {\n         waitUntilAvailable.apply(id);\n         Server remoteServer = pbApi.serverApi().getServer(id);\n         assertEquals(remoteServer.status(), Server.Status.RUNNING);\n         assertRequestHasCommonProperties(server.takeRequest());\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testSnapshotPredicate() throws Exception {\n      MockWebServer server = mockWebServer();\n\n      String payloadInProcess = payloadFromResource(\"/snapshot/snapshot-state-inprocess.xml\");\n      String payloadAvailable = payloadFromResource(\"/snapshot/snapshot.xml\");\n\n      // wait 3 times\n      server.enqueue(new MockResponse().setBody(payloadInProcess));\n      server.enqueue(new MockResponse().setBody(payloadInProcess));\n      server.enqueue(new MockResponse().setBody(payloadInProcess));\n      server.enqueue(new MockResponse().setBody(payloadAvailable));\n\n      server.enqueue(new MockResponse().setBody(payloadAvailable));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n\n      Predicate<String> waitUntilAvailable = Predicates2.retry(\n              new SnapshotProvisioningStatePredicate(pbApi, ProvisioningState.AVAILABLE),\n              30L, 1L, TimeUnit.SECONDS);\n\n      String id = \"qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh\";\n      try {\n         waitUntilAvailable.apply(id);\n         Snapshot snapshot = pbApi.snapshotApi().getSnapshot(id);\n         assertEquals(snapshot.state(), ProvisioningState.AVAILABLE);\n         assertRequestHasCommonProperties(server.takeRequest());\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/compute/function/ProvisionableToImageTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.compute.function;\n\nimport static org.jclouds.profitbricks.domain.Location.US_LAS;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Calendar;\nimport java.util.Date;\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.ImageBuilder;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.profitbricks.domain.OsType;\nimport org.jclouds.profitbricks.domain.ProvisioningState;\nimport org.jclouds.profitbricks.domain.Snapshot;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\", testName = \"ProvisionableToImageTest\")\npublic class ProvisionableToImageTest {\n\n   private ProvisionableToImage fnImage;\n   \n   private final Location location = new LocationBuilder().id(\"us/las\").description(\"us/las\").scope(LocationScope.ZONE)\n         .parent(new LocationBuilder().id(\"us\").description(\"us\").scope(LocationScope.REGION).build()).build();\n\n   @BeforeTest\n   public void setup() {\n      this.fnImage = new ProvisionableToImage(Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet.of(location)));\n   }\n\n   @Test\n   public void testImageToImage() {\n      org.jclouds.profitbricks.domain.Image image\n              = org.jclouds.profitbricks.domain.Image.builder()\n              .isBootable(true)\n              .isCpuHotPlug(true)\n              .isCpuHotUnPlug(false)\n              .isDiscVirtioHotPlug(true)\n              .isDiscVirtioHotUnPlug(true)\n              .id(\"5ad99c9e-9166-11e4-9d74-52540066fee9\")\n              .name(\"Ubuntu-14.04-LTS-server-2015-01-01\")\n              .size(2048f)\n              .type(org.jclouds.profitbricks.domain.Image.Type.HDD)\n              .location(US_LAS)\n              .isNicHotPlug(true)\n              .isNicHotUnPlug(true)\n              .osType(OsType.LINUX)\n              .isPublic(true)\n              .isRamHotPlug(true)\n              .isRamHotUnPlug(false)\n              .isWriteable(true)\n              .build();\n\n      Image actual = fnImage.apply(image);\n\n      Image expected = new ImageBuilder()\n              .ids(image.id())\n              .name(image.name())\n              .location(location)\n              .status(Image.Status.AVAILABLE)\n              .operatingSystem(OperatingSystem.builder()\n                      .description(\"UBUNTU\")\n                      .family(OsFamily.UBUNTU)\n                      .version(\"14.04\")\n                      .is64Bit(false)\n                      .build())\n              .userMetadata(ImmutableMap.of(\"provisionableType\", \"image\"))\n              .build();\n\n      assertEquals(actual, expected);\n   }\n\n   @Test\n   public void testImageDescriptionParsing() {\n      org.jclouds.profitbricks.domain.Image image1\n              = org.jclouds.profitbricks.domain.Image.builder()\n              .id(\"f4742db0-9160-11e4-9d74-52540066fee9\")\n              .name(\"Fedora-19-server-2015-01-01\")\n              .size(2048f)\n              .type(org.jclouds.profitbricks.domain.Image.Type.HDD)\n              .location(US_LAS)\n              .osType(OsType.LINUX)\n              .build();\n\n      Image actual1 = fnImage.apply(image1);\n\n      Image expected1 = new ImageBuilder()\n              .ids(image1.id())\n              .name(image1.name())\n              .location(location)\n              .status(Image.Status.AVAILABLE)\n              .operatingSystem(OperatingSystem.builder()\n                      .description(\"FEDORA\")\n                      .family(OsFamily.FEDORA)\n                      .version(\"7\")\n                      .is64Bit(true)\n                      .build())\n              .userMetadata(ImmutableMap.of(\"provisionableType\", \"image\"))\n              .build();\n\n      assertEquals(actual1, expected1);\n\n      org.jclouds.profitbricks.domain.Image image2\n              = org.jclouds.profitbricks.domain.Image.builder()\n              .id(\"457bf707-d5d1-11e3-8b4f-52540066fee9\")\n              .name(\"clearos-community-6.5.0-x86_64.iso\")\n              .size(2048f)\n              .type(org.jclouds.profitbricks.domain.Image.Type.CDROM)\n              .location(US_LAS)\n              .osType(OsType.LINUX)\n              .build();\n\n      Image actual2 = fnImage.apply(image2);\n\n      Image expected2 = new ImageBuilder()\n              .ids(image2.id())\n              .name(image2.name())\n              .location(location)\n              .status(Image.Status.AVAILABLE)\n              .operatingSystem(OperatingSystem.builder()\n                      .description(\"UNRECOGNIZED\")\n                      .family(OsFamily.UNRECOGNIZED)\n                      .version(\"6.5.0\")\n                      .is64Bit(true)\n                      .build())\n              .userMetadata(ImmutableMap.of(\"provisionableType\", \"image\"))\n              .build();\n\n      assertEquals(actual2, expected2);\n\n      org.jclouds.profitbricks.domain.Image image3\n              = org.jclouds.profitbricks.domain.Image.builder()\n              .id(\"e54af701-53b8-11e3-8f17-52540066fee9\")\n              .name(\"windows-2008-r2-server-setup.iso\")\n              .size(2048f)\n              .type(org.jclouds.profitbricks.domain.Image.Type.CDROM)\n              .location(US_LAS)\n              .osType(OsType.WINDOWS)\n              .build();\n\n      Image actual3 = fnImage.apply(image3);\n\n      Image expected3 = new ImageBuilder()\n              .ids(image3.id())\n              .name(image3.name())\n              .location(location)\n              .status(Image.Status.AVAILABLE)\n              .operatingSystem(OperatingSystem.builder()\n                      .description(\"WINDOWS\")\n                      .family(OsFamily.WINDOWS)\n                      .version(\"2008\")\n                      .is64Bit(false)\n                      .build())\n              .userMetadata(ImmutableMap.of(\"provisionableType\", \"image\"))\n              .build();\n\n      assertEquals(actual3, expected3);\n\n   }\n\n   @Test\n   public void testSnapshotToImage() {\n      Calendar calendar = Calendar.getInstance();\n      calendar.set(2015, 4, 13);\n      Date date = calendar.getTime();\n      \n      Snapshot snapshot1 = Snapshot.builder()\n              .isBootable(true)\n              .isCpuHotPlug(true)\n              .isCpuHotUnPlug(false)\n              .isDiscVirtioHotPlug(true)\n              .isDiscVirtioHotUnPlug(true)\n              .id(\"qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh\")\n              .name(\"placeholder-snapshot-04/13/2015\")\n              .description(\"Created from \\\"placeholder\\\" in Data Center \\\"sbx-computeservice\\\"\")\n              .size(2048f)\n              .location(US_LAS)\n              .isNicHotPlug(true)\n              .isNicHotUnPlug(true)\n              .osType(OsType.LINUX)\n              .isRamHotPlug(true)\n              .isRamHotUnPlug(false)\n              .creationTime(date)\n              .lastModificationTime(new Date())\n              .state(ProvisioningState.AVAILABLE)\n              .build();\n\n      Image actual1 = fnImage.apply(snapshot1);\n\n      Image expected1 = new ImageBuilder()\n              .ids(snapshot1.id())\n              .name(snapshot1.name())\n              .location(location)\n              .status(Image.Status.AVAILABLE)\n              .operatingSystem(OperatingSystem.builder()\n                      .description(snapshot1.description())\n                      .family(OsFamily.LINUX)\n                      .is64Bit(true)\n                      .build())\n              .userMetadata(ImmutableMap.of(\"provisionableType\", \"snapshot\"))\n              .build();\n\n      assertEquals(actual1, expected1);\n\n      Snapshot snapshot2 = Snapshot.builder()\n              .isBootable(true)\n              .isCpuHotPlug(true)\n              .isCpuHotUnPlug(false)\n              .isDiscVirtioHotPlug(true)\n              .isDiscVirtioHotUnPlug(true)\n              .id(\"d80bf9c0-ce6e-4283-9ea4-2906635f6137\")\n              .name(\"jclouds-ubuntu14.10-template\")\n              .description(\"Created from \\\"jclouds-ubuntu14.10 Storage\\\" in Data Center \\\"jclouds-computeservice\\\"\")\n              .size(10240f)\n              .location(US_LAS)\n              .isNicHotPlug(true)\n              .isNicHotUnPlug(true)\n              .osType(OsType.LINUX)\n              .isRamHotPlug(true)\n              .isRamHotUnPlug(false)\n              .creationTime(date)\n              .lastModificationTime(new Date())\n              .state(ProvisioningState.INPROCESS)\n              .build();\n\n      Image actual2 = fnImage.apply(snapshot2);\n\n      Image expected2 = new ImageBuilder()\n              .ids(snapshot2.id())\n              .name(snapshot2.name())\n              .location(location)\n              .status(Image.Status.PENDING)\n              .operatingSystem(OperatingSystem.builder()\n                      .description(\"ubuntu\")\n                      .family(OsFamily.UBUNTU)\n                      .is64Bit(true)\n                      .version(\"00.00\")\n                      .build())\n              .userMetadata(ImmutableMap.of(\"provisionableType\", \"snapshot\"))\n              .build();\n\n      assertEquals(actual2, expected2);\n      assertEquals(actual2.getOperatingSystem(), expected2.getOperatingSystem());\n\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/compute/function/ServerToNodeMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.compute.function;\n\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.jclouds.profitbricks.domain.Location.DE_FRA;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.Set;\n\nimport org.easymock.EasyMock;\nimport org.jclouds.compute.domain.HardwareBuilder;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadataBuilder;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.Processor;\nimport org.jclouds.compute.domain.Volume;\nimport org.jclouds.compute.domain.VolumeBuilder;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.profitbricks.ProfitBricksApi;\nimport org.jclouds.profitbricks.ProfitBricksApiMetadata;\nimport org.jclouds.profitbricks.domain.AvailabilityZone;\nimport org.jclouds.profitbricks.domain.DataCenter;\nimport org.jclouds.profitbricks.domain.Nic;\nimport org.jclouds.profitbricks.domain.OsType;\nimport org.jclouds.profitbricks.domain.ProvisioningState;\nimport org.jclouds.profitbricks.domain.Server;\nimport org.jclouds.profitbricks.domain.Storage;\nimport org.jclouds.profitbricks.features.DataCenterApi;\nimport org.testng.annotations.AfterMethod;\nimport org.testng.annotations.BeforeMethod;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.AbstractModule;\nimport com.google.inject.Guice;\nimport com.google.inject.name.Names;\n\n@Test(groups = \"unit\", testName = \"ServerToNodeMetadataTest\")\npublic class ServerToNodeMetadataTest {\n\n   private ServerToNodeMetadata fnNodeMetadata;\n   \n   private ProfitBricksApi api;\n   \n   private DataCenterApi dataCenterApi;\n\n   @BeforeMethod\n   public void setup() {\n      Supplier<Set<? extends Location>> locationsSupply = new Supplier<Set<? extends Location>>() {\n         @Override\n         public Set<? extends Location> get() {\n            return ImmutableSet.of(\n                    new LocationBuilder()\n                    .id(\"de/fra\")\n                    .description(\"de/fra\")\n                    .scope(LocationScope.ZONE)\n                    .parent(new LocationBuilder()\n                            .id(\"de\")\n                            .description(\"de\")\n                            .scope(LocationScope.REGION)\n                            .build())\n                    .build());\n         }\n      };\n\n      GroupNamingConvention.Factory namingConvention = Guice.createInjector(new AbstractModule() {\n         @Override\n         protected void configure() {\n            Names.bindProperties(binder(), new ProfitBricksApiMetadata().getDefaultProperties());\n         }\n      }).getInstance(GroupNamingConvention.Factory.class);\n      \n      dataCenterApi = EasyMock.createMock(DataCenterApi.class);\n      api = EasyMock.createMock(ProfitBricksApi.class);\n\n      expect(dataCenterApi.getDataCenter(\"mock\")).andReturn(\n            DataCenter.builder().id(\"mock\").version(10).location(DE_FRA).build());\n      expect(api.dataCenterApi()).andReturn(dataCenterApi);\n      \n      replay(dataCenterApi, api);\n\n      this.fnNodeMetadata = new ServerToNodeMetadata(new StorageToVolume(), locationsSupply, api, namingConvention);\n   }\n   \n   @AfterMethod\n   public void tearDown() {\n      verify(api, dataCenterApi);\n   }\n\n   @Test\n   public void testServerToNodeMetadata() {\n      Server server = Server.builder()\n              .dataCenter(DataCenter.builder()\n                      .id(\"mock\")\n                      .version(10)\n                      .location(org.jclouds.profitbricks.domain.Location.DE_FRA)\n                      .build())\n              .id(\"qwertyui-qwer-qwer-qwer-qwertyyuiiop\")\n              .name(\"mock-facebook-node\")\n              .cores(4)\n              .ram(4096)\n              .hasInternetAccess(true)\n              .state(ProvisioningState.AVAILABLE)\n              .status(Server.Status.RUNNING)\n              .osType(OsType.LINUX)\n              .availabilityZone(AvailabilityZone.AUTO)\n              .isCpuHotPlug(true)\n              .isRamHotPlug(true)\n              .isNicHotPlug(true)\n              .isNicHotUnPlug(true)\n              .isDiscVirtioHotPlug(true)\n              .isDiscVirtioHotUnPlug(true)\n              .storages(ImmutableList.<Storage>of(\n                              Storage.builder()\n                              .bootDevice(true)\n                              .busType(Storage.BusType.VIRTIO)\n                              .deviceNumber(1)\n                              .size(40f)\n                              .id(\"qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh\")\n                              .name(\"facebook-storage\")\n                              .build()\n                      )\n              )\n              .nics(ImmutableList.<Nic>of(\n                              Nic.builder()\n                              .id(\"qwqwqwqw-wewe-erer-rtrt-tytytytytyty\")\n                              .lanId(1)\n                              .dataCenterId(\"12345678-abcd-efgh-ijkl-987654321000\")\n                              .internetAccess(true)\n                              .serverId(\"qwertyui-qwer-qwer-qwer-qwertyyuiiop\")\n                              .macAddress(\"02:01:09:cd:f0:b0\")\n                              .ips( ImmutableList.<String>of(\"173.252.120.6\"))\n                              .build()\n                      )\n              )\n              .build();\n\n      NodeMetadata expected = fnNodeMetadata.apply(server);\n      assertNotNull(expected);\n\n      NodeMetadata actual = new NodeMetadataBuilder()\n              .group(\"mock\")\n              .ids(server.id())\n              .name(server.name())\n              .backendStatus(\"AVAILABLE\")\n              .status(NodeMetadata.Status.RUNNING)\n              .hardware(new HardwareBuilder()\n                      .ids(\"cpu=4,ram=4096,disk=40\")\n                      .name(\"cpu=4,ram=4096,disk=40\")\n                      .ram(server.ram())\n                      .processor(new Processor(server.cores(), 1d))\n                      .hypervisor(\"kvm\")\n                      .volume(new VolumeBuilder()\n                              .bootDevice(true)\n                              .size(40f)\n                              .id(\"qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh\")\n                              .durable(true)\n                              .type(Volume.Type.LOCAL)\n                              .build())\n                      .build())\n              .operatingSystem(new OperatingSystem.Builder()\n                      .description(OsFamily.LINUX.value())\n                      .family(OsFamily.LINUX)\n                      .build())\n              .location(new LocationBuilder()\n                      .id(\"de/fra\")\n                      .description(\"de/fra\")\n                      .scope(LocationScope.ZONE)\n                      .parent(new LocationBuilder()\n                              .id(\"de\")\n                              .description(\"de\")\n                              .scope(LocationScope.REGION)\n                              .build())\n                      .build())\n              .publicAddresses(ImmutableList.<String>of(\"173.252.120.6\"))\n              .build();\n\n      assertEquals(actual, expected);\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/compute/function/StorageToVolumeTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.compute.function;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.compute.domain.Volume;\nimport org.jclouds.compute.domain.VolumeBuilder;\nimport org.jclouds.profitbricks.domain.Storage;\nimport org.testng.annotations.BeforeTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"StorageToVolumeTest\")\npublic class StorageToVolumeTest {\n\n   private StorageToVolume fnVolume;\n\n   @BeforeTest\n   public void setup() {\n      this.fnVolume = new StorageToVolume();\n   }\n\n   @Test\n   public void testStorageToVolume() {\n      Storage storage = Storage.builder()\n              .id(\"qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh\")\n              .size(40)\n              .name(\"hdd-1\")\n              .busType(Storage.BusType.VIRTIO)\n              .bootDevice(true)\n              .deviceNumber(1)\n              .build();\n\n      Volume actual = fnVolume.apply(storage);\n\n      Volume expected = new VolumeBuilder()\n              .id(storage.id())\n              .size(40f)\n              .bootDevice(true)\n              .device(\"1\")\n              .type(Volume.Type.LOCAL)\n              .durable(true)\n              .build();\n\n      assertEquals(actual, expected);\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/domain/FirewallRuleBuilderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.domain;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\n\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"FirewallRuleBuilderTest\")\npublic class FirewallRuleBuilderTest {\n\n   private final String _name = \"rule-name\";\n   private final Integer _portRangeEnd = 45678;\n   private final Integer _portRangeStart = 12345;\n   private final Firewall.Protocol _protocol = Firewall.Protocol.TCP;\n   private final String _sourceIp = \"192.168.0.1\";\n   private final String _sourceMac = \"aa:bb:cc:dd:ee:ff\";\n   private final String _targetIp = \"192.168.0.2\";\n\n   private final Integer _icmpType = 2;\n   private final Integer _icmpCode = 24;\n\n   @Test\n   public void testAutoValueFirewallRulePropertiesSettingCorrectly() {\n      Firewall.Rule actual = Firewall.Rule.builder()\n              .name(_name)\n              .portRangeEnd(_portRangeEnd)\n              .portRangeStart(_portRangeStart)\n              .protocol(_protocol)\n              .sourceIp(_sourceIp)\n              .sourceMac(_sourceMac)\n              .targetIp(_targetIp)\n              .build();\n\n      assertEquals(actual.name(), _name);\n      assertEquals(actual.portRangeEnd(), _portRangeEnd);\n      assertEquals(actual.portRangeStart(), _portRangeStart);\n      assertEquals(actual.protocol(), _protocol);\n      assertEquals(actual.sourceIp(), _sourceIp);\n      assertEquals(actual.sourceMac(), _sourceMac);\n      assertEquals(actual.targetIp(), _targetIp);\n   }\n\n   @Test\n   public void testAutoValueFirewallRuleWithIcmpPropertiesSettingCorrectly() {\n      Firewall.Rule actual = Firewall.Rule.builder()\n              .name(_name)\n              .icmpCode(_icmpCode)\n              .icmpType(_icmpType)\n              .protocol(Firewall.Protocol.ICMP)\n              .sourceIp(_sourceIp)\n              .sourceMac(_sourceMac)\n              .targetIp(_targetIp)\n              .build();\n\n      assertEquals(actual.name(), _name);\n      assertNull(actual.portRangeEnd());\n      assertNull(actual.portRangeStart());\n      assertEquals(actual.protocol(), Firewall.Protocol.ICMP);\n      assertEquals(actual.sourceIp(), _sourceIp);\n      assertEquals(actual.sourceMac(), _sourceMac);\n      assertEquals(actual.targetIp(), _targetIp);\n      assertEquals(actual.icmpCode(), _icmpCode);\n      assertEquals(actual.icmpType(), _icmpType);\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/domain/ServerBuilderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.domain;\n\nimport java.util.Date;\nimport static org.testng.Assert.assertEquals;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ServerBuilderTest\")\npublic class ServerBuilderTest {\n\n   private final Boolean _isCpuHotPlug = true;\n   private final Boolean _isRamHotPlug = false;\n   private final Boolean _isNicHotPlug = true;\n   private final Boolean _isNicHotUnPlug = false;\n   private final Boolean _isDiscVirtioHotPlug = true;\n   private final Boolean _isDiscVirtioHotUnPlug = false;\n   private final Integer _cores = 8;\n   private final Integer _ram = 8 * 1024;\n   private final String _id = \"some-random-server-id\";\n   private final String _name = \"jclouds-node\";\n   private final Boolean _hasInternetAccess = true;\n   private final ProvisioningState _state = ProvisioningState.INACTIVE;\n   private final Server.Status _status = Server.Status.SHUTOFF;\n   private final OsType _osType = OsType.LINUX;\n   private final AvailabilityZone _availabilityZone = AvailabilityZone.ZONE_1;\n   private final Date _creationTime = new Date();\n   private final Date _lastModificationTime = new Date();\n\n   private final Integer _lanId = 5;\n   private final String _dataCenterId = \"some-random-datacenter-id\";\n   private final String _bootFromStorageId = \"some-random-storage-id\";\n   private final String _bootFromImageId = \"some-random-image-id\";\n\n   @Test\n   public void testAutoValueServerPropertiesSettingCorrectly() {\n      Server actual = Server.builder()\n              .availabilityZone(_availabilityZone)\n              .creationTime(_creationTime)\n              .cores(_cores)\n              .hasInternetAccess(_hasInternetAccess)\n              .id(_id)\n              .name(_name)\n              .isCpuHotPlug(_isCpuHotPlug)\n              .isDiscVirtioHotPlug(_isDiscVirtioHotPlug)\n              .isDiscVirtioHotUnPlug(_isDiscVirtioHotUnPlug)\n              .isNicHotPlug(_isNicHotPlug)\n              .isNicHotUnPlug(_isNicHotUnPlug)\n              .isRamHotPlug(_isRamHotPlug)\n              .lastModificationTime(_lastModificationTime)\n              .ram(_ram)\n              .osType(_osType)\n              .state(_state)\n              .status(_status)\n              .build();\n\n      assertEquals(actual.availabilityZone(), _availabilityZone);\n      assertEquals(actual.cores(), _cores);\n      assertEquals(actual.creationTime(), _creationTime);\n      assertEquals(actual.hasInternetAccess(), _hasInternetAccess);\n      assertEquals(actual.id(), _id);\n      assertEquals(actual.name(), _name);\n      assertEquals(actual.isCpuHotPlug(), _isCpuHotPlug);\n      assertEquals(actual.isDiscVirtioHotPlug(), _isDiscVirtioHotPlug);\n      assertEquals(actual.isDiscVirtioHotUnPlug(), _isDiscVirtioHotUnPlug);\n      assertEquals(actual.isNicHotPlug(), _isNicHotPlug);\n      assertEquals(actual.isNicHotUnPlug(), _isNicHotUnPlug);\n      assertEquals(actual.isRamHotPlug(), _isRamHotPlug);\n      assertEquals(actual.lastModificationTime(), _lastModificationTime);\n      assertEquals(actual.ram(), _ram);\n      assertEquals(actual.osType(), _osType);\n      assertEquals(actual.state(), _state);\n   }\n\n   @Test\n   public void testAutoValueServerRequestCreatePayloadPropertiesSettingCorrectly() {\n      Server.Request.CreatePayload actual = Server.Request.creatingBuilder()\n              .availabilityZone(_availabilityZone)\n              .bootFromImageId(_bootFromImageId)\n              .bootFromStorageId(_bootFromStorageId)\n              .cores(_cores)\n              .dataCenterId(_dataCenterId)\n              .hasInternetAccess(_hasInternetAccess)\n              .name(_name)\n              .isCpuHotPlug(_isCpuHotPlug)\n              .isDiscVirtioHotPlug(_isDiscVirtioHotPlug)\n              .isDiscVirtioHotUnPlug(_isDiscVirtioHotUnPlug)\n              .isNicHotPlug(_isNicHotPlug)\n              .isNicHotUnPlug(_isNicHotUnPlug)\n              .isRamHotPlug(_isRamHotPlug)\n              .lanId(_lanId)\n              .ram(_ram)\n              .osType(_osType)\n              .build();\n\n      assertEquals(actual.availabilityZone(), _availabilityZone);\n      assertEquals(actual.bootFromImageId(), _bootFromImageId);\n      assertEquals(actual.bootFromStorageId(), _bootFromStorageId);\n      assertEquals(actual.cores(), _cores.intValue());\n      assertEquals(actual.dataCenterId(), _dataCenterId);\n      assertEquals(actual.hasInternetAccess(), _hasInternetAccess);\n      assertEquals(actual.name(), _name);\n      assertEquals(actual.isCpuHotPlug(), _isCpuHotPlug);\n      assertEquals(actual.isDiscVirtioHotPlug(), _isDiscVirtioHotPlug);\n      assertEquals(actual.isDiscVirtioHotUnPlug(), _isDiscVirtioHotUnPlug);\n      assertEquals(actual.isNicHotPlug(), _isNicHotPlug);\n      assertEquals(actual.isNicHotUnPlug(), _isNicHotUnPlug);\n      assertEquals(actual.isRamHotPlug(), _isRamHotPlug);\n      assertEquals(actual.lanId(), _lanId);\n      assertEquals(actual.ram(), _ram.intValue());\n      assertEquals(actual.osType(), _osType);\n   }\n\n   @Test\n   public void testAutoValueServerRequestUpdatePayloadPropertiesSettingCorrectly() {\n      Server.Request.UpdatePayload actual = Server.Request.updatingBuilder()\n              .availabilityZone(_availabilityZone)\n              .bootFromImageId(_bootFromImageId)\n              .bootFromStorageId(_bootFromStorageId)\n              .cores(_cores)\n              .name(_name)\n              .id(_id)\n              .isCpuHotPlug(_isCpuHotPlug)\n              .isDiscVirtioHotPlug(_isDiscVirtioHotPlug)\n              .isDiscVirtioHotUnPlug(_isDiscVirtioHotUnPlug)\n              .isNicHotPlug(_isNicHotPlug)\n              .isNicHotUnPlug(_isNicHotUnPlug)\n              .isRamHotPlug(_isRamHotPlug)\n              .ram(_ram)\n              .osType(_osType)\n              .build();\n\n      assertEquals(actual.availabilityZone(), _availabilityZone);\n      assertEquals(actual.bootFromImageId(), _bootFromImageId);\n      assertEquals(actual.bootFromStorageId(), _bootFromStorageId);\n      assertEquals(actual.cores(), _cores);\n      assertEquals(actual.name(), _name);\n      assertEquals(actual.id(), _id);\n      assertEquals(actual.isCpuHotPlug(), _isCpuHotPlug);\n      assertEquals(actual.isDiscVirtioHotPlug(), _isDiscVirtioHotPlug);\n      assertEquals(actual.isDiscVirtioHotUnPlug(), _isDiscVirtioHotUnPlug);\n      assertEquals(actual.isNicHotPlug(), _isNicHotPlug);\n      assertEquals(actual.isNicHotUnPlug(), _isNicHotUnPlug);\n      assertEquals(actual.isRamHotPlug(), _isRamHotPlug);\n      assertEquals(actual.ram(), _ram);\n      assertEquals(actual.osType(), _osType);\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/features/DataCenterApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.List;\n\nimport org.jclouds.profitbricks.BaseProfitBricksLiveTest;\nimport org.jclouds.profitbricks.domain.DataCenter;\nimport org.jclouds.profitbricks.domain.Location;\nimport org.jclouds.profitbricks.domain.ProvisioningState;\n\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"DataCenterApiLiveTest\")\npublic class DataCenterApiLiveTest extends BaseProfitBricksLiveTest {\n\n   private String dcId;\n\n   @Test\n   public void testCreateDataCenter() {\n      DataCenter dc = api.dataCenterApi().createDataCenter(\n              DataCenter.Request.creatingPayload(\"JClouds\", Location.DE_FKB)\n      );\n\n      assertNotNull(dc);\n      assertDataCenterAvailable(dc);\n\n      dcId = dc.id();\n   }\n\n   @Test(dependsOnMethods = \"testCreateDataCenter\")\n   public void testGetDataCenter() {\n      assertNotNull(dcId, \"No available datacenter found.\");\n\n      DataCenter dataCenter = api.dataCenterApi().getDataCenter(dcId);\n\n      assertNotNull(dataCenter);\n      assertEquals(dataCenter.id(), dcId);\n   }\n\n   @Test(dependsOnMethods = \"testCreateDataCenter\")\n   public void testGetAllDataCenters() {\n      List<DataCenter> dataCenters = api.dataCenterApi().getAllDataCenters();\n\n      assertNotNull(dataCenters);\n      assertFalse(dataCenters.isEmpty(), \"No datacenter found.\");\n   }\n\n   @Test(dependsOnMethods = \"testCreateDataCenter\")\n   public void testGetDataCenterState() {\n      assertNotNull(dcId, \"No available datacenter found.\");\n\n      ProvisioningState state = api.dataCenterApi().getDataCenterState(dcId);\n\n      assertNotNull(state);\n   }\n\n   @Test(dependsOnMethods = \"testGetDataCenter\")\n   public void testUpdateDataCenter() {\n      assertNotNull(dcId, \"No available datacenter found.\");\n\n      final String newName = \"Apache\";\n      DataCenter dataCenter = api.dataCenterApi().updateDataCenter(\n              DataCenter.Request.updatingPayload(dcId, newName)\n      );\n\n      assertNotNull(dataCenter);\n      assertDataCenterAvailable(dataCenter);\n\n      DataCenter fetchedDc = api.dataCenterApi().getDataCenter(dcId);\n\n      assertNotNull(fetchedDc);\n      assertEquals(newName, fetchedDc.name());\n   }\n\n   @Test(dependsOnMethods = \"testUpdateDataCenter\")\n   public void testClearDataCenter() {\n      DataCenter dataCenter = api.dataCenterApi().clearDataCenter(dcId);\n\n      assertNotNull(dataCenter);\n   }\n\n   @Test\n   public void testGetNonExistingDataCenter() {\n      DataCenter dataCenter = api.dataCenterApi().getDataCenter(\"random-non-existing-id\");\n\n      assertNull(dataCenter);\n   }\n\n   @Test\n   public void testDeleteNonExistingDataCenterMustReturnFalse() {\n      boolean result = api.dataCenterApi().deleteDataCenter(\"random-non-existing-id\");\n\n      assertFalse(result);\n   }\n\n   @AfterClass(alwaysRun = true)\n   public void testDeleteDataCenter() {\n      boolean result = api.dataCenterApi().deleteDataCenter(dcId);\n      assertTrue(result, \"Created test data center was not deleted.\");\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/features/DataCenterApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.Assert.fail;\n\nimport java.util.List;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\n\nimport org.jclouds.profitbricks.ProfitBricksApi;\nimport org.jclouds.profitbricks.domain.DataCenter;\nimport org.jclouds.profitbricks.domain.Location;\nimport org.jclouds.profitbricks.domain.ProvisioningState;\nimport org.jclouds.profitbricks.internal.BaseProfitBricksMockTest;\nimport org.testng.annotations.Test;\n\n\n/**\n * Mock tests for the {@link org.jclouds.profitbricks.features.DataCenterApi} class\n */\n@Test(groups = \"unit\", testName = \"DataCenterApiMockTest\")\npublic class DataCenterApiMockTest extends BaseProfitBricksMockTest {\n\n   @Test\n   public void testGetAllDataCenters() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/datacenter/datacenters.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      DataCenterApi api = pbApi.dataCenterApi();\n\n      try {\n         List<DataCenter> dataCenters = api.getAllDataCenters();\n         assertRequestHasCommonProperties(server.takeRequest(), \"<ws:getAllDataCenters/>\");\n         assertNotNull(dataCenters);\n         assertEquals(dataCenters.size(), 2);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testGetAllDataCentersReturning404() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setResponseCode(404));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      DataCenterApi api = pbApi.dataCenterApi();\n\n      try {\n         List<DataCenter> dataCenters = api.getAllDataCenters();\n         assertRequestHasCommonProperties(server.takeRequest());\n         assertTrue(dataCenters.isEmpty());\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testGetDataCenter() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/datacenter/datacenter.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      DataCenterApi api = pbApi.dataCenterApi();\n\n      String id = \"12345678-abcd-efgh-ijkl-987654321000\";\n      String content = \"<ws:getDataCenter><dataCenterId>\" + id + \"</dataCenterId></ws:getDataCenter>\";\n      try {\n         DataCenter dataCenter = api.getDataCenter(id);\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertNotNull(dataCenter);\n         assertEquals(dataCenter.id(), id);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testGetNonExistingDataCenter() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setResponseCode(404));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      DataCenterApi api = pbApi.dataCenterApi();\n\n      String id = \"random-non-existing-id\";\n      try {\n         DataCenter dataCenter = api.getDataCenter(id);\n         assertRequestHasCommonProperties(server.takeRequest());\n         assertNull(dataCenter);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testGetDataCenterState() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/datacenter/datacenter-state.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      DataCenterApi api = pbApi.dataCenterApi();\n\n      String id = \"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee\";\n      String content = \"<ws:getDataCenterState><dataCenterId>\" + id + \"</dataCenterId></ws:getDataCenterState>\";\n      try {\n         ProvisioningState state = api.getDataCenterState(id);\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertNotNull(state);\n         assertEquals(state, ProvisioningState.AVAILABLE);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testCreateDataCenter() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/datacenter/datacenter-created.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      DataCenterApi api = pbApi.dataCenterApi();\n\n      String content = \"<ws:createDataCenter><request>\"\n              + \"<dataCenterName>JClouds-DC</dataCenterName>\"\n              + \"<location>de/fra</location>\"\n              + \"</request></ws:createDataCenter>\";\n      try {\n         DataCenter dataCenter = api.createDataCenter(\n                 DataCenter.Request.creatingPayload(\"JClouds-DC\", Location.DE_FRA)\n         );\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertNotNull(dataCenter);\n         assertEquals(dataCenter.id(), \"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee\");\n         assertEquals(dataCenter.version(), 1);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testCreateDataCenterWithIllegalArguments() throws Exception {\n      String[] names = {\"JCl@ouds\", \"JC|ouds\", \"^clouds\", \"\"};\n      for (String name : names)\n         try {\n            DataCenter.Request.creatingPayload(name, Location.US_LAS);\n            fail(\"Should have failed for name: \".concat(name));\n         } catch (IllegalArgumentException ex) {\n            // expected exception\n         }\n   }\n\n   @Test\n   public void testUpdateDataCenter() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/datacenter/datacenter-updated.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      DataCenterApi api = pbApi.dataCenterApi();\n\n      String id = \"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee\";\n      String newName = \"Apache\";\n\n      String content = \"<ws:updateDataCenter><request>\"\n              + \"<dataCenterId>\" + id + \"</dataCenterId>\"\n              + \"<dataCenterName>\" + newName + \"</dataCenterName>\"\n              + \"</request></ws:updateDataCenter>\";\n      try {\n         DataCenter dataCenter = api.updateDataCenter(\n                 DataCenter.Request.updatingPayload(id, newName)\n         );\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertNotNull(dataCenter);\n         assertEquals(dataCenter.id(), id);\n         assertEquals(dataCenter.version(), 2);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testClearDataCenter() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/datacenter/datacenter-cleared.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      DataCenterApi api = pbApi.dataCenterApi();\n\n      String id = \"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee\";\n\n      String content = \"<ws:clearDataCenter><dataCenterId>\" + id + \"</dataCenterId></ws:clearDataCenter>\";\n      try {\n         DataCenter dataCenter = api.clearDataCenter(id);\n\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertNotNull(dataCenter);\n         assertEquals(dataCenter.id(), id);\n         assertEquals(dataCenter.version(), 3);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testDeleteDataCenter() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/datacenter/datacenter-deleted.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      DataCenterApi api = pbApi.dataCenterApi();\n\n      String id = \"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee\";\n\n      String content = \"<ws:deleteDataCenter><dataCenterId>\" + id + \"</dataCenterId></ws:deleteDataCenter>\";\n      try {\n         boolean result = api.deleteDataCenter(id);\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertTrue(result);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testDeleteNonExistingDataCenter() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setResponseCode(404));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      DataCenterApi api = pbApi.dataCenterApi();\n\n      try {\n         boolean result = api.deleteDataCenter(\"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee\");\n         assertRequestHasCommonProperties(server.takeRequest());\n         assertFalse(result);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/features/DrivesApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.features;\n\nimport static org.testng.Assert.assertNotNull;\n\nimport org.jclouds.profitbricks.BaseProfitBricksLiveTest;\nimport org.jclouds.profitbricks.domain.DataCenter;\nimport org.jclouds.profitbricks.domain.Drive;\nimport org.jclouds.profitbricks.domain.Image;\nimport org.jclouds.profitbricks.domain.Server;\nimport org.testng.annotations.Test;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Iterables;\n\n@Test(groups = \"live\", testName = \"DrivesApiLiveTest\")\npublic class DrivesApiLiveTest extends BaseProfitBricksLiveTest {\n\n   private DataCenter dataCenter;\n   private Server server;\n   private Image image;\n\n   @BeforeClass\n   public void setupTest() {\n      dataCenter = findOrCreateDataCenter(\"drivesApiLiveTest\" + System.currentTimeMillis());\n      server = findOrCreateServer(dataCenter);\n      image = Iterables.tryFind(api.imageApi().getAllImages(), new Predicate<Image>() {\n\n         @Override\n         public boolean apply(Image input) {\n            return input.location() == dataCenter.location()\n                    && input.type() == Image.Type.CDROM;\n         }\n      }).get();\n   }\n\n   @Test\n   public void addRomDriveToServerTest() {\n      assertDataCenterAvailable(dataCenter);\n      String requestId = api.drivesApi().addRomDriveToServer(\n              Drive.Request.AddRomDriveToServerPayload.builder()\n              .serverId(server.id())\n              .imageId(image.id())\n              .deviceNumber(\"0\")\n              .build());\n      assertNotNull(requestId);\n   }\n\n   @Test(dependsOnMethods = \"addRomDriveToServerTest\")\n   public void removeRomDriveFromServerTest() {\n      assertDataCenterAvailable(dataCenter);\n      String requestId = api.drivesApi().removeRomDriveFromServer(image.id(), server.id());\n      assertNotNull(requestId);\n   }\n\n   @AfterClass(alwaysRun = true)\n   public void cleanUp() {\n      destroyDataCenter(dataCenter);\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/features/DrivesApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.features;\n\nimport static org.testng.Assert.assertNotNull;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\n\nimport org.jclouds.profitbricks.ProfitBricksApi;\nimport org.jclouds.profitbricks.domain.Drive;\nimport org.jclouds.profitbricks.internal.BaseProfitBricksMockTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"DrivesApiMockTest\")\npublic class DrivesApiMockTest extends BaseProfitBricksMockTest {\n\n   @Test\n   public void addRomDriveToServerTest() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/drives/drives-add.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      DrivesApi api = pbApi.drivesApi();\n\n      String content = \"<ws:addRomDriveToServer>\"\n              + \"<request>\"\n              + \"<imageId>image-id</imageId>\"\n              + \"<serverId>server-id</serverId>\"\n              + \"<deviceNumber>device-number</deviceNumber>\"\n              + \"</request>\"\n              + \"</ws:addRomDriveToServer>\";\n      try {\n         String requestId = api.addRomDriveToServer(Drive.Request.AddRomDriveToServerPayload.builder()\n                 .serverId(\"server-id\")\n                 .imageId(\"image-id\")\n                 .deviceNumber(\"device-number\")\n                 .build());\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertNotNull(requestId);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void removeRomDriveFromServerTest() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/drives/drives-remove.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      DrivesApi api = pbApi.drivesApi();\n\n      String content = \"<ws:removeRomDriveFromServer>\"\n              + \"<imageId>image-id</imageId>\"\n              + \"<serverId>server-id</serverId>\"\n              + \"</ws:removeRomDriveFromServer>\";\n      try {\n         String requestId = api.removeRomDriveFromServer(\"image-id\", \"server-id\");\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertNotNull(requestId);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/features/FirewallApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.List;\n\nimport org.jclouds.profitbricks.BaseProfitBricksLiveTest;\nimport org.jclouds.profitbricks.domain.DataCenter;\nimport org.jclouds.profitbricks.domain.Firewall;\nimport org.jclouds.profitbricks.domain.Nic;\nimport org.jclouds.profitbricks.domain.Firewall.Protocol;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n\n@Test(groups = \"live\", testName = \"FirewallApiLiveTest\")\npublic class FirewallApiLiveTest extends BaseProfitBricksLiveTest {\n\n   private DataCenter dataCenter;\n   private Nic nic;\n\n   private Firewall createdFirewall;\n\n   @BeforeClass\n   public void setupTest() {\n      dataCenter = findOrCreateDataCenter(\"firewallApiLiveTest\" + System.currentTimeMillis());\n      nic = findOrCreateNic(dataCenter);\n   }\n\n   @Test\n   public void testAddFirewallRuleToNic() {\n      assertDataCenterAvailable(dataCenter);\n      Firewall firewall = api.firewallApi().addFirewallRuleToNic(\n              Firewall.Request.createAddRulePayload(\n                      nic.id(), ImmutableList.of(\n                              Firewall.Rule.builder()\n                              .name(\"test-rule-tcp\")\n                              .protocol(Protocol.TCP)\n                              .build()\n                      )\n              )\n      );\n\n      assertNotNull(firewall);\n      assertFalse(firewall.rules().isEmpty());\n      assertDataCenterAvailable(dataCenter);\n\n      createdFirewall = firewall;\n   }\n\n   @Test(dependsOnMethods = \"testAddFirewallRuleToNic\")\n   public void testGetAllFirewalls() {\n      List<Firewall> firewalls = api.firewallApi().getAllFirewalls();\n\n      assertNotNull(firewalls);\n      assertFalse(firewalls.isEmpty());\n   }\n\n   @Test(dependsOnMethods = \"testAddFirewallRuleToNic\")\n   public void testGetFirewall() {\n      Firewall firewall = api.firewallApi().getFirewall(createdFirewall.id());\n\n      assertNotNull(firewall);\n      assertEquals(createdFirewall.id(), firewall.id());\n   }\n\n   @Test(dependsOnMethods = \"testAddFirewallRuleToNic\")\n   public void testActivateFirewall() {\n      assertDataCenterAvailable(dataCenter);\n      boolean result = api.firewallApi().activateFirewall(\n              ImmutableList.of(createdFirewall.id()));\n      assertDataCenterAvailable(dataCenter);\n      assertTrue(result);\n\n      Firewall firewall = api.firewallApi().getFirewall(createdFirewall.id());\n      assertTrue(firewall.active(), \"Firewall wasn't activated\");\n   }\n\n   @Test(dependsOnMethods = \"testActivateFirewall\")\n   void testDeactivateFirewall() {\n      assertDataCenterAvailable(dataCenter);\n      boolean result = api.firewallApi().deactivateFirewall(\n              ImmutableList.of(createdFirewall.id()));\n      assertDataCenterAvailable(dataCenter);\n      assertTrue(result);\n\n      Firewall firewall = api.firewallApi().getFirewall(createdFirewall.id());\n      assertFalse(firewall.active(), \"Firewall wasn't deactivated\");\n   }\n\n   @Test(dependsOnMethods = \"testDeactivateFirewall\")\n   void testRemoveFirewallRule() {\n      assertDataCenterAvailable(dataCenter);\n      for (Firewall.Rule rule : createdFirewall.rules()) {\n         boolean result = api.firewallApi().removeFirewallRules(\n                 ImmutableList.of(rule.id()));\n\n         assertTrue(result);\n         assertDataCenterAvailable(dataCenter);\n\n      }\n      Firewall firewall = api.firewallApi().getFirewall(createdFirewall.id());\n      assertTrue(firewall.rules().isEmpty(), \"Not all rules removed\");\n   }\n\n   @Test(dependsOnMethods = \"testRemoveFirewallRule\")\n   public void testDeleteFirewall() {\n      assertDataCenterAvailable(dataCenter);\n      boolean result = api.firewallApi().deleteFirewall(ImmutableList.of(createdFirewall.id()));\n      assertTrue(result, \"Created firewall was not deleted.\");\n   }\n\n   @AfterClass(alwaysRun = true)\n   public void cleanUp() {\n      destroyDataCenter(dataCenter);\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/features/FirewallApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.List;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\n\nimport org.jclouds.profitbricks.ProfitBricksApi;\nimport org.jclouds.profitbricks.domain.Firewall;\nimport org.jclouds.profitbricks.domain.Firewall.Protocol;\nimport org.jclouds.profitbricks.internal.BaseProfitBricksMockTest;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"live\", testName = \"FirewallApiMockTest\", singleThreaded = true)\npublic class FirewallApiMockTest extends BaseProfitBricksMockTest {\n\n   @Test\n   public void testGetAllFirewalls() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/firewall/firewalls.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n\n      FirewallApi api = pbApi.firewallApi();\n\n      try {\n         List<Firewall> firewalls = api.getAllFirewalls();\n         assertRequestHasCommonProperties(server.takeRequest(), \"<ws:getAllFirewalls/>\");\n         assertNotNull(firewalls);\n         assertEquals(firewalls.size(), 2);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testGetFirewall() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/firewall/firewall.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n\n      FirewallApi api = pbApi.firewallApi();\n\n      String id = \"firewall-id\";\n      String firewallruleid = \"firewall-rule-id\";\n\n      String content = \"<ws:getFirewall><firewallId>\" + id + \"</firewallId></ws:getFirewall>\";\n\n      try {\n         Firewall firewall = api.getFirewall(id);\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertNotNull(firewall);\n         assertEquals(firewall.id(), id);\n         assertFalse(firewall.rules().isEmpty());\n         assertEquals(firewall.rules().get(0).id(), firewallruleid);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testGetNonExistingFirewall() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setResponseCode(404));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      FirewallApi api = pbApi.firewallApi();\n\n      String id = \"firewall-id\";\n\n      try {\n         Firewall firewall = api.getFirewall(id);\n         assertRequestHasCommonProperties(server.takeRequest());\n         assertNull(firewall);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testAddFirewallRuleToNic() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/firewall/firewall-addtonic.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      FirewallApi api = pbApi.firewallApi();\n\n      String content = \"<ws:addFirewallRulesToNic>\"\n              + \"<nicId>nic-id</nicId>\"\n              + \"<request>\"\n              + \"<name>name</name>\"\n              + \"<portRangeEnd>45678</portRangeEnd>\"\n              + \"<portRangeStart>12345</portRangeStart>\"\n              + \"<protocol>TCP</protocol>\"\n              + \"<sourceIp>192.168.0.1</sourceIp>\"\n              + \"<sourceMac>aa:bb:cc:dd:ee:ff</sourceMac>\"\n              + \"<targetIp>192.168.0.2</targetIp>\"\n              + \"</request>\"\n              + \"</ws:addFirewallRulesToNic>\";\n      try {\n         Firewall.Request.AddRulePayload payload = Firewall.Request.createAddRulePayload(\n                 \"nic-id\", ImmutableList.of(\n                         Firewall.Rule.builder()\n                         .name(\"name\")\n                         .portRangeEnd(45678)\n                         .portRangeStart(12345)\n                         .protocol(Protocol.TCP)\n                         .sourceIp(\"192.168.0.1\")\n                         .sourceMac(\"aa:bb:cc:dd:ee:ff\")\n                         .targetIp(\"192.168.0.2\")\n                         .build()\n                 ));\n         Firewall response = api.addFirewallRuleToNic(payload);\n\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertNotNull(response);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testRemoveFirewall() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/firewall/firewall-remove.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      FirewallApi api = pbApi.firewallApi();\n\n      String firewallId = \"12345\";\n      String content = \"<ws:removeFirewallRules>\"\n              + \"<firewallRuleIds>\" + firewallId + \"</firewallRuleIds>\"\n              + \"</ws:removeFirewallRules>\";\n\n      try {\n         boolean result = api.removeFirewallRules(ImmutableList.of(firewallId));\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertTrue(result);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testRemoveNonExitingFirewall() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setResponseCode(404));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      FirewallApi api = pbApi.firewallApi();\n\n      String firewallRuleId = \"12345\";\n\n      try {\n         boolean result = api.removeFirewallRules(ImmutableList.of(firewallRuleId));\n         assertRequestHasCommonProperties(server.takeRequest());\n         assertFalse(result);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testActivateFirewall() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/firewall/firewall-activate.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      FirewallApi api = pbApi.firewallApi();\n\n      String firewallId = \"12345\";\n      String content = \"<ws:activateFirewalls>\"\n              + \"<firewallIds>\" + firewallId + \"</firewallIds>\"\n              + \"</ws:activateFirewalls>\";\n\n      try {\n         boolean result = api.activateFirewall(ImmutableList.of(firewallId));\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertTrue(result);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testActivateNonExitingFirewall() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setResponseCode(404));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      FirewallApi api = pbApi.firewallApi();\n\n      String firewallId = \"12345\";\n\n      try {\n         boolean result = api.activateFirewall(ImmutableList.of(firewallId));\n         assertRequestHasCommonProperties(server.takeRequest());\n         assertFalse(result);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testDeactivateFirewall() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/firewall/firewall-deactivate.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      FirewallApi api = pbApi.firewallApi();\n\n      String firewallId = \"12345\";\n      String content = \"<ws:deactivateFirewalls>\"\n              + \"<firewallIds>\" + firewallId + \"</firewallIds>\"\n              + \"</ws:deactivateFirewalls>\";\n\n      try {\n         boolean result = api.deactivateFirewall(ImmutableList.of(firewallId));\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertTrue(result);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testDeactivateNonExitingFirewall() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setResponseCode(404));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      FirewallApi api = pbApi.firewallApi();\n\n      String firewallId = \"12345\";\n\n      try {\n         boolean result = api.deactivateFirewall(ImmutableList.of(firewallId));\n         assertRequestHasCommonProperties(server.takeRequest());\n         assertFalse(result);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testDeleteFirewall() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/firewall/firewall-delete.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      FirewallApi api = pbApi.firewallApi();\n\n      String firewallId = \"12345\";\n      String content = \"<ws:deleteFirewalls>\"\n              + \"<firewallIds>\" + firewallId + \"</firewallIds>\"\n              + \"</ws:deleteFirewalls>\";\n\n      try {\n         boolean result = api.deleteFirewall(ImmutableList.of(firewallId));\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertTrue(result);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testDeleteNonExitingFirewall() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setResponseCode(404));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      FirewallApi api = pbApi.firewallApi();\n\n      String firewallId = \"12345\";\n\n      try {\n         boolean result = api.deleteFirewall(ImmutableList.of(firewallId));\n         assertRequestHasCommonProperties(server.takeRequest());\n         assertFalse(result);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/features/ImageApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.features;\n\nimport static org.testng.Assert.assertEquals;\n\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\n\nimport java.util.List;\n\nimport org.jclouds.profitbricks.BaseProfitBricksLiveTest;\nimport org.jclouds.profitbricks.domain.Image;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Iterables;\n\n@Test(groups = \"live\", testName = \"ImageApiLiveTest\")\npublic class ImageApiLiveTest extends BaseProfitBricksLiveTest {\n\n   private Image image;\n\n   @Test\n   public void testGetAllImages() {\n      List<Image> images = api.imageApi().getAllImages();\n\n      assertNotNull(images);\n      assertFalse(images.isEmpty(), \"No images found.\");\n\n      image = Iterables.getFirst(images, null);\n      assertNotNull(image);\n   }\n\n   @Test(dependsOnMethods = \"testGetAllImages\")\n   public void testGetImage() {\n      Image fetchedImage = api.imageApi().getImage(image.id());\n\n      assertNotNull(fetchedImage);\n      assertEquals(fetchedImage, image);\n   }\n\n   @Test\n   public void testGetNonExistingImage() {\n      String id = \"random-non-existing-id\";\n      assertNull(api.imageApi().getImage(id), \"Should've just returned null\");\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/features/ImageApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.List;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\n\nimport org.jclouds.profitbricks.ProfitBricksApi;\nimport org.jclouds.profitbricks.domain.Image;\nimport org.jclouds.profitbricks.internal.BaseProfitBricksMockTest;\nimport org.testng.annotations.Test;\n\n/**\n * Mock tests for the {@link org.jclouds.profitbricks.features.ImageApi} class\n */\n@Test(groups = \"unit\", testName = \"ImageApiMockTest\")\npublic class ImageApiMockTest extends BaseProfitBricksMockTest {\n\n   @Test\n   public void testGetAllImages() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/image/images.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      ImageApi api = pbApi.imageApi();\n\n      try {\n         List<Image> images = api.getAllImages();\n         assertRequestHasCommonProperties(server.takeRequest(), \"<ws:getAllImages/>\");\n         assertNotNull(images);\n         assertTrue(images.size() == 7);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testGetAllImagesReturning404() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setResponseCode(404));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      ImageApi api = pbApi.imageApi();\n\n      try {\n         List<Image> images = api.getAllImages();\n         assertRequestHasCommonProperties(server.takeRequest());\n         assertTrue(images.isEmpty());\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testGetImage() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/image/image.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      ImageApi api = pbApi.imageApi();\n\n      String id = \"5ad99c9e-9166-11e4-9d74-52540066fee9\";\n\n      String content = \"<ws:getImage><imageId>\" + id + \"</imageId></ws:getImage>\";\n      try {\n         Image image = api.getImage(id);\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertNotNull(image);\n         assertEquals(image.id(), id);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n\n   }\n\n   @Test\n   public void testGetNonExistingImage() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setResponseCode(404));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      ImageApi api = pbApi.imageApi();\n\n      String id = \"random-non-existing-id\";\n      try {\n         Image image = api.getImage(id);\n         assertRequestHasCommonProperties(server.takeRequest());\n         assertNull(image);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/features/IpBlockApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.features;\n\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.List;\n\nimport com.google.common.collect.Iterables;\n\nimport org.jclouds.profitbricks.BaseProfitBricksLiveTest;\nimport org.jclouds.profitbricks.domain.DataCenter;\nimport org.jclouds.profitbricks.domain.IpBlock;\nimport org.jclouds.profitbricks.domain.Nic;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"IpBlockApiLiveTest\")\npublic class IpBlockApiLiveTest extends BaseProfitBricksLiveTest {\n\n   private DataCenter dataCenter;\n   private Nic nic;\n\n   private IpBlock newIpBlock;\n\n   @BeforeClass\n   public void setupTest() {\n      dataCenter = findOrCreateDataCenter(\"ipBlockApiLiveTest\" + System.currentTimeMillis());\n      nic = findOrCreateNic(dataCenter);\n   }\n\n   @Test\n   public void testReservePublicIpBlock() {\n      assertDataCenterAvailable(dataCenter);\n      newIpBlock = api.ipBlockApi().reservePublicIpBlock(1, testLocation);\n\n      assertNotNull(newIpBlock);\n      assertFalse(newIpBlock.ips().isEmpty());\n   }\n\n   @Test(dependsOnMethods = \"testReservePublicIpBlock\")\n   public void testGetAllIpBlocks() {\n      List<IpBlock> ipBlocks = api.ipBlockApi().getAllIpBlock();\n\n      assertNotNull(ipBlocks);\n      assertFalse(ipBlocks.isEmpty());\n   }\n\n   @Test(dependsOnMethods = \"testReservePublicIpBlock\")\n   public void testGetOneIpBlock() {\n      IpBlock ipBlock = api.ipBlockApi().getIpBlock(newIpBlock.id());\n\n      assertNotNull(ipBlock);\n   }\n\n   @Test(dependsOnMethods = \"testReservePublicIpBlock\")\n   public void testAddPublicIpToNic() {\n      assertDataCenterAvailable(dataCenter);\n      String ipToAdd = Iterables.getFirst(newIpBlock.ips(), null);\n      String requestId = api.ipBlockApi().addPublicIpToNic(\n              ipToAdd, nic.id());\n\n      assertNotNull(requestId);\n      assertDataCenterAvailable(dataCenter);\n      List<String> ips = api.nicApi().getNic(nic.id()).ips();\n      assertTrue(ips.contains(ipToAdd), \"NIC didn't contain added public ip\");\n   }\n\n   @Test(dependsOnMethods = \"testAddPublicIpToNic\")\n   public void testRemovePublicIpFromNic() {\n      assertDataCenterAvailable(dataCenter);\n      String ipToRemove = Iterables.getFirst(newIpBlock.ips(), null);\n      String requestId = api.ipBlockApi().removePublicIpFromNic(\n              ipToRemove, nic.id());\n\n      assertNotNull(requestId);\n      assertDataCenterAvailable(dataCenter);\n      List<String> ips = api.nicApi().getNic(nic.id()).ips();\n      assertFalse(ips.contains(ipToRemove), \"NIC still contains removed public ip\");\n   }\n\n   @Test(dependsOnMethods = \"testRemovePublicIpFromNic\")\n   public void testReleasePublicIpBlock() {\n      assertDataCenterAvailable(dataCenter);\n      String requestId = api.ipBlockApi().releasePublicIpBlock(newIpBlock.id());\n\n      assertNotNull(requestId);\n   }\n\n   @AfterClass(alwaysRun = true)\n   public void cleanUp() {\n      destroyDataCenter(dataCenter);\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/features/IpBlockApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.List;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\n\nimport org.jclouds.profitbricks.ProfitBricksApi;\nimport org.jclouds.profitbricks.domain.IpBlock;\nimport org.jclouds.profitbricks.domain.Location;\nimport org.jclouds.profitbricks.internal.BaseProfitBricksMockTest;\n\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"IpBlockApiMockTest\")\npublic class IpBlockApiMockTest extends BaseProfitBricksMockTest {\n\n   @Test\n   public void testGetOneIpBlock() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/ipblock/ipblock.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      IpBlockApi api = pbApi.ipBlockApi();\n\n      String id = \"qwertyui-qwer-qwer-qwer-qwertyyuiiop\";\n\n      String content = \"<ws:getPublicIpBlock><blockId>\" + id + \"</blockId></ws:getPublicIpBlock>\";\n\n      try {\n         IpBlock ipBlock = api.getIpBlock(id);\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertNotNull(ipBlock);\n         assertEquals(ipBlock.id(), id);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testGetNonExisingIpBlock() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setResponseCode(404));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      IpBlockApi api = pbApi.ipBlockApi();\n\n      String id = \"qwertyui-qwer-qwer-qwer-qwertyyuiiop\";\n\n      try {\n         IpBlock ipBlock = api.getIpBlock(id);\n         assertRequestHasCommonProperties(server.takeRequest());\n         assertNull(ipBlock);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testGetAllIpBlock() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/ipblock/ipblocks.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      IpBlockApi api = pbApi.ipBlockApi();\n\n      try {\n         List<IpBlock> ipBlocks = api.getAllIpBlock();\n         assertRequestHasCommonProperties(server.takeRequest());\n         assertNotNull(ipBlocks);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testGetAllIpBlockReturning404() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setResponseCode(404));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      IpBlockApi api = pbApi.ipBlockApi();\n\n      try {\n         List<IpBlock> ipBlocks = api.getAllIpBlock();\n         assertRequestHasCommonProperties(server.takeRequest());\n         assertTrue(ipBlocks.isEmpty());\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testReservePublicIpBlock() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/ipblock/ipblock-reserve.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      IpBlockApi api = pbApi.ipBlockApi();\n\n      int blockSize = 2;\n      Location location = Location.US_LAS;\n\n      String content = \"<ws:reservePublicIpBlock><request><blockSize>\" + blockSize + \"</blockSize><location>\" + location.getId() + \"</location></request></ws:reservePublicIpBlock>\";\n      try {\n         IpBlock ipBlock = api.reservePublicIpBlock(blockSize, location);\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertNotNull(ipBlock);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testAddPublicIpToNic() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/ipblock/ipblock-addtonic.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      IpBlockApi api = pbApi.ipBlockApi();\n\n      String ip = \"2\";\n      String nicid = \"nicid\";\n\n      String content = \"<ws:addPublicIpToNic><ip>\" + ip + \"</ip><nicId>\" + nicid + \"</nicId></ws:addPublicIpToNic>\";\n      try {\n         String requestId = api.addPublicIpToNic(ip, nicid);\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertNotNull(requestId);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testRemovePublicIpFromNic() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/ipblock/ipblock-removefromnic.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      IpBlockApi api = pbApi.ipBlockApi();\n\n      String ip = \"2\";\n      String nicid = \"nicid\";\n\n      String content = \"<ws:removePublicIpFromNic><ip>\" + ip + \"</ip><nicId>\" + nicid + \"</nicId></ws:removePublicIpFromNic>\";\n      try {\n         String requestId = api.removePublicIpFromNic(ip, nicid);\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertNotNull(requestId);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testReleasePublicIpBlock() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/ipblock/ipblock-release.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      IpBlockApi api = pbApi.ipBlockApi();\n\n      String blockid = \"2\";\n\n      String content = \"<ws:releasePublicIpBlock><blockId>\" + blockid + \"</blockId></ws:releasePublicIpBlock>\";\n      try {\n         String requestId = api.releasePublicIpBlock(blockid);\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertNotNull(requestId);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/features/LoadBalancerApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.List;\nimport java.util.Objects;\n\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Iterables;\n\nimport org.jclouds.profitbricks.BaseProfitBricksLiveTest;\nimport org.jclouds.profitbricks.domain.DataCenter;\nimport org.jclouds.profitbricks.domain.LoadBalancer;\nimport org.jclouds.profitbricks.domain.LoadBalancer.Algorithm;\nimport org.jclouds.profitbricks.domain.Server;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"LoadBalancerApiLiveTest\")\npublic class LoadBalancerApiLiveTest extends BaseProfitBricksLiveTest {\n\n   private DataCenter dataCenter;\n   private Server server;\n\n   private String loadBalancerId;\n\n   @BeforeClass\n   public void setupTest() {\n      dataCenter = findOrCreateDataCenter(\"loadBalancerApiLiveTest\" + System.currentTimeMillis());\n      server = findOrCreateServer(dataCenter);\n   }\n\n   @Test\n   public void testCreateLoadBalancer() {\n      assertDataCenterAvailable(dataCenter);\n      String createdId = api.loadBalancerApi().createLoadBalancer(\n              LoadBalancer.Request.creatingBuilder()\n              .dataCenterId(dataCenter.id())\n              .name(\"testName\")\n              .algorithm(Algorithm.ROUND_ROBIN)\n              .ip(\"192.168.0.200\")\n              .lanId(1)\n              .build()\n      );\n\n      assertNotNull(createdId);\n      assertDataCenterAvailable(dataCenter);\n      this.loadBalancerId = createdId;\n   }\n\n   @Test(dependsOnMethods = \"testCreateLoadBalancer\")\n   public void testGetAllLoadBalancers() {\n      List<LoadBalancer> loadBalancers = api.loadBalancerApi().getAllLoadBalancers();\n\n      assertFalse(loadBalancers.isEmpty());\n   }\n\n   @Test(dependsOnMethods = \"testCreateLoadBalancer\")\n   public void testGetLoadBalancer() {\n      LoadBalancer loadBalancer = api.loadBalancerApi().getLoadBalancer(loadBalancerId);\n\n      assertNotNull(loadBalancer);\n      assertEquals(loadBalancer.id(), loadBalancerId);\n   }\n\n   @Test(dependsOnMethods = \"testGetLoadBalancer\")\n   public void testRegisterLoadBalancer() {\n      assertDataCenterAvailable(dataCenter);\n      LoadBalancer loadBalancer = api.loadBalancerApi().registerLoadBalancer(\n              LoadBalancer.Request\n              .createRegisteringPaylod(loadBalancerId, ImmutableList.of(server.id()))\n      );\n\n      assertNotNull(loadBalancer);\n      assertDataCenterAvailable(dataCenter);\n      Optional<Server> balancedServer = Iterables.tryFind(loadBalancer.balancedServers(), new Predicate<Server>() {\n\n         @Override\n         public boolean apply(Server t) {\n            return Objects.equals(t.id(), server.id());\n         }\n      });\n      assertTrue(balancedServer.isPresent(), \"Server input wasn't registered to loadbalancer\");\n   }\n\n   @Test(dependsOnMethods = \"testRegisterLoadBalancer\")\n   public void testDeregisterLoadBalancer() {\n      assertDataCenterAvailable(dataCenter);\n      String requestId = api.loadBalancerApi().deregisterLoadBalancer(\n              LoadBalancer.Request\n              .createDeregisteringPayload(loadBalancerId, ImmutableList.of(server.id()))\n      );\n\n      assertNotNull(requestId);\n      assertDataCenterAvailable(dataCenter);\n      LoadBalancer loadBalancer = api.loadBalancerApi().getLoadBalancer(loadBalancerId);\n      Optional<Server> balancedServer = Iterables.tryFind(loadBalancer.balancedServers(), new Predicate<Server>() {\n\n         @Override\n         public boolean apply(Server t) {\n            return Objects.equals(t.id(), loadBalancerId);\n         }\n      });\n      assertFalse(balancedServer.isPresent(), \"Server input wasn't deregistered from loadbalancer\");\n   }\n\n   @Test(dependsOnMethods = \"testDeregisterLoadBalancer\")\n   public void testUpdateLoadBalancer() {\n      assertDataCenterAvailable(dataCenter);\n      String newName = \"whatever\";\n      String requestId = api.loadBalancerApi().updateLoadBalancer(\n              LoadBalancer.Request.updatingBuilder()\n              .id(loadBalancerId)\n              .name(newName)\n              .build()\n      );\n\n      assertNotNull(requestId);\n      assertDataCenterAvailable(dataCenter);\n      LoadBalancer loadBalancer = api.loadBalancerApi().getLoadBalancer(loadBalancerId);\n      assertEquals(loadBalancer.name(), newName);\n   }\n\n   @Test(dependsOnMethods = \"testUpdateLoadBalancer\")\n   public void testDeleteLoadBalancer() {\n      assertDataCenterAvailable(dataCenter);\n      boolean result = api.loadBalancerApi().deleteLoadBalancer(loadBalancerId);\n      assertTrue(result, \"Test load balancer wasn't deleted\");\n   }\n\n   @AfterClass(alwaysRun = true)\n   public void cleanUp() {\n      destroyDataCenter(dataCenter);\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/features/LoadBalancerApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.AssertJUnit.assertTrue;\n\nimport java.util.List;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Lists;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\n\nimport org.jclouds.profitbricks.ProfitBricksApi;\nimport org.jclouds.profitbricks.domain.LoadBalancer;\nimport org.jclouds.profitbricks.domain.LoadBalancer.Algorithm;\nimport org.jclouds.profitbricks.internal.BaseProfitBricksMockTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"LoadBalancerApiMockTest\")\npublic class LoadBalancerApiMockTest extends BaseProfitBricksMockTest {\n\n   @Test\n   public void testGetAllLoadBalancers() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/loadbalancer/loadbalancers.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      LoadBalancerApi api = pbApi.loadBalancerApi();\n\n      try {\n         List<LoadBalancer> loadBalancerList = api.getAllLoadBalancers();\n\n         assertRequestHasCommonProperties(server.takeRequest(), \"<ws:getAllLoadBalancers/>\");\n         assertNotNull(loadBalancerList);\n         assertTrue(loadBalancerList.size() == 2);\n\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testGetAllLoadBalancersReturning404() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setResponseCode(404));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      LoadBalancerApi api = pbApi.loadBalancerApi();\n\n      try {\n         List<LoadBalancer> loadBalancerList = api.getAllLoadBalancers();\n\n         assertRequestHasCommonProperties(server.takeRequest());\n         assertTrue(loadBalancerList.isEmpty());\n\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testGetLoadBalancer() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/loadbalancer/loadbalancer.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      LoadBalancerApi api = pbApi.loadBalancerApi();\n\n      String id = \"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee\";\n\n      String content = \"<ws:getLoadBalancer><loadBalancerId>\" + id + \"</loadBalancerId></ws:getLoadBalancer>\";\n      try {\n         LoadBalancer loadBalancer = api.getLoadBalancer(id);\n\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertNotNull(loadBalancer);\n         assertEquals(loadBalancer.id(), id);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testGetNonExistingLoadBalancer() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setResponseCode(404));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      LoadBalancerApi api = pbApi.loadBalancerApi();\n\n      String id = \"random-non-existing-id\";\n\n      try {\n         LoadBalancer loadBalancer = api.getLoadBalancer(id);\n\n         assertRequestHasCommonProperties(server.takeRequest());\n         assertNull(loadBalancer);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testCreateLoadBalancer() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/loadbalancer/loadbalancer-create.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      LoadBalancerApi api = pbApi.loadBalancerApi();\n\n      String content = \"<ws:createLoadBalancer>\"\n              + \"<request>\"\n              + \"<dataCenterId>aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeeee</dataCenterId>\"\n              + \"<loadBalancerName>load-balancer-name</loadBalancerName>\"\n              + \"<loadBalancerAlgorithm>ROUND_ROBIN</loadBalancerAlgorithm>\"\n              + \"<ip>192.168.0.1</ip>\"\n              + \"<lanId>3</lanId>\"\n              + \"<serverIds>server-ids</serverIds>\"\n              + \"</request>\"\n              + \"</ws:createLoadBalancer>\";\n\n      try {\n         List<String> serverIds = Lists.newArrayList();\n         serverIds.add(\"server-ids\");\n         String loadBalancerId = api.createLoadBalancer(LoadBalancer.Request.creatingBuilder()\n                 .dataCenterId(\"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeeee\")\n                 .name(\"load-balancer-name\")\n                 .algorithm(Algorithm.ROUND_ROBIN)\n                 .ip(\"192.168.0.1\")\n                 .lanId(3)\n                 .serverIds(serverIds)\n                 .build());\n\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertEquals(loadBalancerId, \"1234-1234-1234-1234\");\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testUpdateLoadBalancer() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/loadbalancer/loadbalancer-update.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      LoadBalancerApi api = pbApi.loadBalancerApi();\n\n      String id = \"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee\";\n      String newName = \"Apache\";\n\n      String content = \"<ws:updateLoadBalancer>\"\n              + \"<request>\"\n              + \"<loadBalancerId>\" + id + \"</loadBalancerId>\"\n              + \"<loadBalancerName>load-balancer-name</loadBalancerName>\"\n              + \"<loadBalancerAlgorithm>ROUND_ROBIN</loadBalancerAlgorithm>\"\n              + \"<ip>192.168.0.1</ip>\"\n              + \"</request>\"\n              + \"</ws:updateLoadBalancer>\";\n\n      try {\n         LoadBalancer.Request.UpdatePayload toUpdate = LoadBalancer.Request.updatingBuilder()\n                 .id(id)\n                 .name(\"load-balancer-name\")\n                 .algorithm(Algorithm.ROUND_ROBIN)\n                 .ip(\"192.168.0.1\")\n                 .build();\n\n         String requestId = api.updateLoadBalancer(toUpdate);\n\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertEquals(requestId, \"request-id\");\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n\n   }\n\n   @Test\n   public void testRegisterLoadBalancer() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/loadbalancer/loadbalancer-register.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      LoadBalancerApi api = pbApi.loadBalancerApi();\n\n      String content = \"<ws:registerServersOnLoadBalancer>\"\n              + \"<loadBalancerId>1234</loadBalancerId>\"\n              + \"<serverIds>1</serverIds>\"\n              + \"<serverIds>2</serverIds>\"\n              + \"</ws:registerServersOnLoadBalancer>\";\n\n      try {\n         List<String> serverIds = Lists.newArrayList();\n         serverIds.add(\"1\");\n         serverIds.add(\"2\");\n         LoadBalancer.Request.RegisterPayload payload = LoadBalancer.Request\n                 .createRegisteringPaylod(\"1234\", serverIds);\n\n         LoadBalancer loadBalancer = api.registerLoadBalancer(payload);\n\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertNotNull(loadBalancer);\n         assertEquals(loadBalancer.id(), \"load-balancer-id\");\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testDeregisterLoadBalancer() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/loadbalancer/loadbalancer-deregister.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      LoadBalancerApi api = pbApi.loadBalancerApi();\n\n      String content = \"<ws:deregisterServersOnLoadBalancer>\"\n              + \"<serverIds>1</serverIds>\"\n              + \"<serverIds>2</serverIds>\"\n              + \"<loadBalancerId>load-balancer-id</loadBalancerId>\"\n              + \"</ws:deregisterServersOnLoadBalancer>\";\n\n      try {\n         LoadBalancer.Request.DeregisterPayload payload = LoadBalancer.Request\n                 .createDeregisteringPayload(\"load-balancer-id\", ImmutableList.of(\"1\", \"2\"));\n\n         String requestId = api.deregisterLoadBalancer(payload);\n\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertEquals(requestId, \"request-id\");\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testDeleteLoadBalancer() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/loadbalancer/loadbalancer-delete.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      LoadBalancerApi api = pbApi.loadBalancerApi();\n\n      String loadBalancerId = \"qwertyui-qwer-qwer-qwer-qwertyyuiiop\";\n\n      String content = \"<ws:deleteLoadBalancer><loadBalancerId>\" + loadBalancerId + \"</loadBalancerId></ws:deleteLoadBalancer>\";\n\n      try {\n         boolean done = api.deleteLoadBalancer(loadBalancerId);\n\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertTrue(done);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/features/NicApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.List;\n\nimport org.jclouds.profitbricks.BaseProfitBricksLiveTest;\nimport org.jclouds.profitbricks.domain.DataCenter;\nimport org.jclouds.profitbricks.domain.Nic;\nimport org.jclouds.profitbricks.domain.Server;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.Test;\nimport org.testng.annotations.BeforeClass;\n\n@Test(groups = \"live\", testName = \"NicApiLiveTest\")\npublic class NicApiLiveTest extends BaseProfitBricksLiveTest {\n\n   private DataCenter dataCenter;\n   private Server server;\n\n   private String createdNicId;\n\n   @BeforeClass\n   public void setupTest() {\n      dataCenter = findOrCreateDataCenter(\"nicApiLiveTest-\" + System.currentTimeMillis());\n      server = findOrCreateServer(dataCenter);\n   }\n\n   @Test\n   public void testCreateNic() {\n      assertDataCenterAvailable(dataCenter);\n      String nicId = api.nicApi().createNic(Nic.Request.creatingBuilder()\n              .name(\"name nr1\")\n              .dhcpActive(true)\n              .serverId(server.id())\n              .lanId(1)\n              .build());\n\n      assertNotNull(nicId);\n      assertDataCenterAvailable(dataCenter);\n\n      this.createdNicId = nicId;\n   }\n\n   @Test(dependsOnMethods = \"testCreateNic\")\n   public void testGetAllNics() {\n      List<Nic> nics = api.nicApi().getAllNics();\n\n      assertNotNull(nics);\n   }\n\n   @Test(dependsOnMethods = \"testCreateNic\")\n   public void testGetNic() {\n      Nic nic = api.nicApi().getNic(createdNicId);\n\n      assertNotNull(nic);\n      assertEquals(nic.id(), createdNicId);\n   }\n\n   @Test(dependsOnMethods = \"testGetNic\")\n   public void testUpdateNic() {\n      assertDataCenterAvailable(dataCenter);\n      String newName = \"name nr2\";\n      String requestId = api.nicApi().updateNic(\n              Nic.Request.updatingBuilder()\n              .name(\"name nr2\")\n              .id(createdNicId)\n              .build()\n      );\n\n      assertNotNull(requestId);\n      assertDataCenterAvailable(dataCenter);\n\n      Nic nic = api.nicApi().getNic(createdNicId);\n      assertEquals(nic.name(), newName);\n   }\n\n   @Test(dependsOnMethods = \"testUpdateNic\")\n   public void testSetInternetAccess() {\n      assertDataCenterAvailable(dataCenter);\n\n      String requestId = api.nicApi().setInternetAccess(Nic.Request.setInternetAccessBuilder()\n              .dataCenterId(dataCenter.id())\n              .lanId(1)\n              .internetAccess(true)\n              .build()\n      );\n      assertDataCenterAvailable(dataCenter);\n      assertNotNull(requestId);\n\n      Nic nic = api.nicApi().getNic(createdNicId);\n      assertTrue(nic.internetAccess(), \"Expected nic to have internet access\");\n   }\n\n   @Test(dependsOnMethods = \"testSetInternetAccess\")\n   public void testDeleteNic() {\n      assertDataCenterAvailable(dataCenter);\n      boolean result = api.nicApi().deleteNic(createdNicId);\n      assertTrue(result, \"Created test NIC was not deleted.\");\n   }\n\n   @AfterClass(alwaysRun = true)\n   public void cleanUp() {\n      destroyDataCenter(dataCenter);\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/features/NicApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.List;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\n\nimport org.jclouds.profitbricks.ProfitBricksApi;\nimport org.jclouds.profitbricks.domain.Nic;\nimport org.jclouds.profitbricks.internal.BaseProfitBricksMockTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"NicApiMockTest\")\n\npublic class NicApiMockTest extends BaseProfitBricksMockTest {\n\n   @Test\n   public void testGetNic() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/nic/nic.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      NicApi api = pbApi.nicApi();\n\n      String id = \"12345678-abcd-efgh-ijkl-987654321000\";\n\n      String content = \"<ws:getNic><nicId>\" + id + \"</nicId></ws:getNic>\";\n      try {\n         Nic nic = api.getNic(id);\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertNotNull(nic);\n         assertEquals(nic.id(), id);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testGetNonExistingNic() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setResponseCode(404));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      NicApi api = pbApi.nicApi();\n\n      String id = \"nonexisting-nic-id\";\n\n      try {\n         Nic nic = api.getNic(id);\n         assertRequestHasCommonProperties(server.takeRequest());\n         assertNull(nic);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testGetAllNic() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/nic/nics.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      NicApi api = pbApi.nicApi();\n      try {\n         List<Nic> nics = api.getAllNics();\n         assertRequestHasCommonProperties(server.takeRequest(), \"<ws:getAllNic/>\");\n         assertNotNull(nics);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testCreateNic() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/nic/nic-create.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      NicApi api = pbApi.nicApi();\n\n      String content = \"<ws:createNic>\"\n              + \"<request>\"\n              + \"<ip>192.168.0.1</ip>\"\n              + \"<nicName>nic-name</nicName>\"\n              + \"<dhcpActive>true</dhcpActive>\"\n              + \"<serverId>server-id</serverId>\"\n              + \"<lanId>1</lanId>\"\n              + \"</request>\"\n              + \"</ws:createNic>\";\n\n      try {\n         String nicId = api.createNic(\n                 Nic.Request.creatingBuilder()\n                 .ip(\"192.168.0.1\")\n                 .name(\"nic-name\")\n                 .dhcpActive(true)\n                 .lanId(1)\n                 .serverId(\"server-id\")\n                 .build());\n\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertNotNull(nicId);\n\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testUpdateNic() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/nic/nic-update.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      NicApi api = pbApi.nicApi();\n\n      String content = \"<ws:updateNic>\"\n              + \"<request>\"\n              + \"<nicId>nic-id</nicId>\"\n              + \"<ip>10.0.0.1</ip>\"\n              + \"<nicName>nic-name</nicName>\"\n              + \"<dhcpActive>true</dhcpActive>\"\n              + \"<lanId>1</lanId>\"\n              + \"</request>\"\n              + \"</ws:updateNic>\";\n      try {\n         String requestId = api.updateNic(Nic.Request.updatingBuilder()\n                 .id(\"nic-id\")\n                 .ip(\"10.0.0.1\")\n                 .name(\"nic-name\")\n                 .dhcpActive(true)\n                 .lanId(1)\n                 .build());\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertEquals(requestId, \"request-id\");\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testSetInternetAccess() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/nic/nic-internetaccess.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      NicApi api = pbApi.nicApi();\n\n      String content = \"<ws:setInternetAccess>\"\n              + \"<dataCenterId>datacenter-id</dataCenterId>\"\n              + \"<lanId>1</lanId>\"\n              + \"<internetAccess>true</internetAccess>\"\n              + \"</ws:setInternetAccess>\";\n      try {\n         String requestId = api.setInternetAccess(Nic.Request.setInternetAccessBuilder()\n                 .dataCenterId(\"datacenter-id\")\n                 .lanId(1)\n                 .internetAccess(true)\n                 .build());\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertEquals(requestId, \"request-id\");\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testDeleteNic() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/nic/nic-delete.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      NicApi api = pbApi.nicApi();\n\n      String id = \"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee\";\n\n      String content = \"<ws:deleteNic><nicId>\" + id + \"</nicId></ws:deleteNic>\";\n\n      try {\n         boolean result = api.deleteNic(id);\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertTrue(result);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testDeleteNonExistingNic() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setResponseCode(404));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      NicApi api = pbApi.nicApi();\n\n      String id = \"nonexisting-nic-id\";\n\n      try {\n         boolean result = api.deleteNic(id);\n         assertRequestHasCommonProperties(server.takeRequest());\n         assertFalse(result);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/features/ServerApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.List;\n\nimport org.jclouds.profitbricks.BaseProfitBricksLiveTest;\nimport org.jclouds.profitbricks.domain.DataCenter;\nimport org.jclouds.profitbricks.domain.ProvisioningState;\nimport org.jclouds.profitbricks.domain.Server;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"ServerApiLiveTest\")\npublic class ServerApiLiveTest extends BaseProfitBricksLiveTest {\n\n   private DataCenter dataCenter;\n   private String createdServerId;\n\n   @BeforeClass\n   public void setupTest() {\n      dataCenter = findOrCreateDataCenter(\"serverApiLiveTest-\" + System.currentTimeMillis());\n   }\n\n   @Test\n   public void testCreateServer() {\n      assertDataCenterAvailable(dataCenter);\n      String serverId = api.serverApi().createServer(\n              Server.Request.creatingBuilder()\n              .dataCenterId(dataCenter.id())\n              .name(\"jclouds-node\")\n              .cores(1)\n              .ram(1024)\n              .build());\n\n      assertNotNull(serverId);\n      assertDataCenterAvailable(dataCenter);\n      assertNodeRunning(serverId);\n\n      this.createdServerId = serverId;\n   }\n\n   @Test(dependsOnMethods = \"testCreateServer\")\n   public void testGetServer() {\n      Server server = api.serverApi().getServer(createdServerId);\n\n      assertNotNull(server);\n      assertEquals(server.id(), createdServerId);\n   }\n\n   @Test(dependsOnMethods = \"testCreateServer\")\n   public void testGetAllServers() {\n      List<Server> servers = api.serverApi().getAllServers();\n\n      assertNotNull(servers);\n      assertFalse(servers.isEmpty());\n   }\n\n   @Test(dependsOnMethods = \"testGetServer\")\n   public void testUpdateServer() {\n      assertDataCenterAvailable(dataCenter);\n      String requestId = api.serverApi().updateServer(\n              Server.Request.updatingBuilder()\n              .id(createdServerId)\n              .name(\"apache-node\")\n              .cores(2)\n              .ram(2 * 1024)\n              .build());\n\n      assertNotNull(requestId);\n      assertDataCenterAvailable(dataCenter);\n\n      Server server = api.serverApi().getServer(createdServerId);\n      assertEquals(server.state(), ProvisioningState.AVAILABLE);\n   }\n\n   @Test(dependsOnMethods = \"testUpdateServer\")\n   public void testStopServer() {\n      String requestId = api.serverApi().stopServer(createdServerId);\n      assertNotNull(requestId);\n      assertNodeSuspended(createdServerId);\n\n      Server server = api.serverApi().getServer(createdServerId);\n      assertEquals(server.status(), Server.Status.SHUTOFF);\n   }\n\n   @Test(dependsOnMethods = \"testStopServer\")\n   public void testStartServer() {\n      String requestId = api.serverApi().startServer(createdServerId);\n      assertNotNull(requestId);\n      assertNodeRunning(createdServerId);\n\n      Server server = api.serverApi().getServer(createdServerId);\n      assertEquals(server.status(), Server.Status.RUNNING);\n   }\n\n   @Test(dependsOnMethods = \"testStartServer\")\n   public void testDeleteServer() {\n      assertDataCenterAvailable(dataCenter);\n      boolean result = api.serverApi().deleteServer(createdServerId);\n      assertTrue(result, \"Created test server was not deleted.\");\n   }\n\n   @AfterClass(alwaysRun = true)\n   public void cleanUp() {\n      destroyDataCenter(dataCenter);\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/features/ServerApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.features;\n\nimport java.util.List;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\n\nimport org.jclouds.profitbricks.ProfitBricksApi;\nimport org.jclouds.profitbricks.domain.AvailabilityZone;\nimport org.jclouds.profitbricks.domain.OsType;\nimport org.jclouds.profitbricks.domain.Server;\nimport org.jclouds.profitbricks.internal.BaseProfitBricksMockTest;\nimport org.jclouds.rest.ResourceNotFoundException;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.Assert.fail;\n\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ServerApiMockTest\")\npublic class ServerApiMockTest extends BaseProfitBricksMockTest {\n\n   @Test\n   public void testGetAllServers() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/server/servers.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      ServerApi api = pbApi.serverApi();\n\n      try {\n         List<Server> servers = api.getAllServers();\n         assertRequestHasCommonProperties(server.takeRequest(), \"<ws:getAllServers/>\");\n         assertNotNull(servers);\n         assertTrue(servers.size() == 2);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testGetAllServersReturning404() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setResponseCode(404));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      ServerApi api = pbApi.serverApi();\n\n      try {\n         List<Server> servers = api.getAllServers();\n         assertRequestHasCommonProperties(server.takeRequest());\n         assertTrue(servers.isEmpty());\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testGetServer() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/server/server.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      ServerApi api = pbApi.serverApi();\n\n      String id = \"qwertyui-qwer-qwer-qwer-qwertyyuiiop\";\n\n      String content = \"<ws:getServer><serverId>\" + id + \"</serverId></ws:getServer>\";\n      try {\n         Server svr = api.getServer(id);\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertNotNull(svr);\n         assertEquals(svr.id(), id);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testGetNonExistingServer() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setResponseCode(404));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      ServerApi api = pbApi.serverApi();\n\n      String id = \"random-non-existing-id\";\n      try {\n         Server srvr = api.getServer(id);\n         assertRequestHasCommonProperties(server.takeRequest());\n         assertNull(srvr);\n\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testStartServer() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/server/server-start.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      ServerApi api = pbApi.serverApi();\n\n      String id = \"qwertyui-qwer-qwer-qwer-qwertyyuiiop\";\n\n      String content = \"<ws:startServer><serverId>\" + id + \"</serverId></ws:startServer>\";\n      try {\n         String requestId = api.startServer(id);\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertEquals(requestId, \"123456\");\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testStartNonExistingServer() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setResponseCode(500).setBody(payloadFromResource(\"/fault-404.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      ServerApi api = pbApi.serverApi();\n\n      String id = \"random-non-existing-id\";\n      try {\n         String requestId = api.startServer(id);\n         assertRequestHasCommonProperties(server.takeRequest());\n         fail(\"Should've failed.\");\n      } catch (ResourceNotFoundException ex) {\n         // expected exception\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testStopServer() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/server/server-stop.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      ServerApi api = pbApi.serverApi();\n\n      String id = \"qwertyui-qwer-qwer-qwer-qwertyyuiiop\";\n\n      String content = \"<ws:stopServer><serverId>\" + id + \"</serverId></ws:stopServer>\";\n      try {\n         String requestId = api.stopServer(id);\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertEquals(requestId, \"123456\");\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testResetServer() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/server/server-reset.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      ServerApi api = pbApi.serverApi();\n\n      String id = \"qwertyui-qwer-qwer-qwer-qwertyyuiiop\";\n\n      String content = \"<ws:resetServer><serverId>\" + id + \"</serverId></ws:resetServer>\";\n      try {\n         String requestId = api.resetServer(id);\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertEquals(requestId, \"123456\");\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testCreateServer() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/server/server-create.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      ServerApi api = pbApi.serverApi();\n\n      String dataCenterId = \"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee\";\n      String name = \"jclouds-node\";\n      String imageId = \"some-random-image-id\";\n\n      String content = \"<ws:createServer>\"\n              + \"<request>\"\n              + \"<dataCenterId>\" + dataCenterId + \"</dataCenterId>\"\n              + \"<cores>4</cores>\"\n              + \"<ram>4096</ram>\"\n              + \"<serverName>\" + name + \"</serverName>\"\n              //              + \"<bootFromStorageId></bootFromStorageId>\"\n              + \"<bootFromImageId>\" + imageId + \"</bootFromImageId>\"\n              + \"<internetAccess>true</internetAccess>\"\n              + \"<lanId>2</lanId>\"\n              + \"<osType>LINUX</osType>\"\n              + \"<availabilityZone>ZONE_1</availabilityZone>\"\n              + \"<cpuHotPlug>true</cpuHotPlug>\"\n              + \"<ramHotPlug>false</ramHotPlug>\"\n              + \"<nicHotPlug>true</nicHotPlug>\"\n              + \"<nicHotUnPlug>false</nicHotUnPlug>\"\n              + \"<discVirtioHotPlug>true</discVirtioHotPlug>\"\n              + \"<discVirtioHotUnPlug>false</discVirtioHotUnPlug>\"\n              + \"</request>\"\n              + \"</ws:createServer>\";\n\n      try {\n         String serverId = api.createServer(Server.Request.creatingBuilder()\n                 .dataCenterId(dataCenterId)\n                 .name(name)\n                 .cores(4)\n                 .ram(4 * 1024)\n                 .bootFromImageId(imageId)\n                 .hasInternetAccess(Boolean.TRUE)\n                 .lanId(2)\n                 .osType(OsType.LINUX)\n                 .availabilityZone(AvailabilityZone.ZONE_1)\n                 .isCpuHotPlug(Boolean.TRUE)\n                 .isRamHotPlug(Boolean.FALSE)\n                 .isNicHotPlug(Boolean.TRUE)\n                 .isNicHotUnPlug(Boolean.FALSE)\n                 .isDiscVirtioHotPlug(Boolean.TRUE)\n                 .isDiscVirtioHotUnPlug(Boolean.FALSE)\n                 .build());\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertNotNull(serverId);\n         assertEquals(serverId, \"qwertyui-qwer-qwer-qwer-qwertyyuiiop\");\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testUpdateServer() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/server/server-update.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      ServerApi api = pbApi.serverApi();\n\n      String serverId = \"qwertyui-qwer-qwer-qwer-qwertyyuiiop\";\n      String newName = \"apache-node\";\n      String storageId = \"some-random-storage-id\";\n\n      String content = \"<ws:updateServer>\"\n              + \"<request>\"\n              + \"<serverId>\" + serverId + \"</serverId>\"\n              + \"<cores>8</cores>\"\n              + \"<ram>8192</ram>\"\n              + \"<serverName>\" + newName + \"</serverName>\"\n              + \"<bootFromStorageId>\" + storageId + \"</bootFromStorageId>\"\n              //              + \"<bootFromImageId>?</bootFromImageId>\"\n              + \"<osType>OTHER</osType>\"\n              + \"<availabilityZone>AUTO</availabilityZone>\"\n              + \"<cpuHotPlug>false</cpuHotPlug>\"\n              + \"<ramHotPlug>true</ramHotPlug>\"\n              + \"<nicHotPlug>false</nicHotPlug>\"\n              + \"<nicHotUnPlug>true</nicHotUnPlug>\"\n              + \"<discVirtioHotPlug>false</discVirtioHotPlug>\"\n              + \"<discVirtioHotUnPlug>true</discVirtioHotUnPlug>\"\n              + \"</request>\"\n              + \"</ws:updateServer>\";\n      try {\n         String requestId = api.updateServer(Server.Request.updatingBuilder()\n                 .id(serverId)\n                 .name(newName)\n                 .cores(8)\n                 .ram(8 * 1024)\n                 .bootFromStorageId(storageId)\n                 .osType(OsType.OTHER)\n                 .availabilityZone(AvailabilityZone.AUTO)\n                 .isCpuHotPlug(false)\n                 .isRamHotPlug(true)\n                 .isNicHotPlug(false)\n                 .isNicHotUnPlug(true)\n                 .isDiscVirtioHotPlug(false)\n                 .isDiscVirtioHotUnPlug(true)\n                 .build());\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertNotNull(requestId);\n         assertEquals(requestId, \"102458\");\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testDeleteServer() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/server/server-delete.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      ServerApi api = pbApi.serverApi();\n\n      String serverId = \"qwertyui-qwer-qwer-qwer-qwertyyuiiop\";\n\n      String content = \"<ws:deleteServer><serverId>\" + serverId + \"</serverId></ws:deleteServer>\";\n      try {\n         boolean result = api.deleteServer(serverId);\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertTrue(result);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n\n   }\n\n   @Test\n   public void testDeleteNonExistingServer() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setResponseCode(404));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      ServerApi api = pbApi.serverApi();\n\n      String id = \"random-non-existing-id\";\n      try {\n         boolean result = api.deleteServer(id);\n         assertRequestHasCommonProperties(server.takeRequest());\n         assertFalse(result);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/features/SnapshotApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.List;\nimport java.util.concurrent.TimeUnit;\n\nimport org.jclouds.profitbricks.BaseProfitBricksLiveTest;\nimport org.jclouds.profitbricks.domain.OsType;\nimport org.jclouds.profitbricks.domain.Snapshot;\nimport org.jclouds.profitbricks.domain.Storage;\nimport org.testng.annotations.Test;\nimport org.jclouds.profitbricks.domain.DataCenter;\nimport org.jclouds.profitbricks.domain.ProvisioningState;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.FluentIterable;\n\nimport org.jclouds.util.Predicates2;\n\n@Test(groups = \"live\", testName = \"SnapshotApiLiveTest\")\npublic class SnapshotApiLiveTest extends BaseProfitBricksLiveTest {\n\n   private DataCenter dataCenter;\n   private Storage storage;\n\n   private String createdSnapshotId;\n\n   @BeforeClass\n   public void setupTest() {\n      dataCenter = findOrCreateDataCenter(\"snapshotApiLiveTest-\" + System.currentTimeMillis());\n      storage = FluentIterable.from(dataCenter.storages()).firstMatch(new Predicate<Storage>() {\n\n         @Override\n         public boolean apply(Storage input) {\n            return input.state() == ProvisioningState.AVAILABLE\n                    && input.size() <= 10f;\n         }\n      }).or(new Supplier<Storage>() {\n\n         @Override\n         public Storage get() {\n            StorageApi storageApi = api.storageApi();\n            String name = String.format(\"server-%d\", dataCenter.servers().size());\n            String createdStorageId = storageApi.createStorage(\n                    Storage.Request.creatingBuilder()\n                    .dataCenterId(dataCenter.id())\n                    .name(name)\n                    .size(2f)\n                    .build()\n            );\n            assertDataCenterAvailable(dataCenter);\n\n            return storageApi.getStorage(createdStorageId);\n         }\n      });\n   }\n\n   @Test\n   public void testCreateSnapshot() {\n      assertDataCenterAvailable(dataCenter);\n      Snapshot snapshot = api.snapshotApi().createSnapshot(\n              Snapshot.Request.creatingBuilder()\n              .storageId(storage.id())\n              .description(\"my description\")\n              .name(\"test snapshot\")\n              .build());\n\n      assertNotNull(snapshot);\n      assertSnapshotAvailable(snapshot.id());\n\n      createdSnapshotId = snapshot.id();\n   }\n\n   @Test(dependsOnMethods = \"testCreateSnapshot\")\n   public void testGetAllSnapshots() {\n      List<Snapshot> snapshots = api.snapshotApi().getAllSnapshots();\n\n      assertNotNull(snapshots);\n      assertTrue(snapshots.size() > 0);\n   }\n\n   @Test(dependsOnMethods = \"testCreateSnapshot\")\n   public void testGetSnapshot() {\n      Snapshot snapshot = api.snapshotApi().getSnapshot(createdSnapshotId);\n\n      assertNotNull(snapshot);\n      assertEquals(snapshot.id(), createdSnapshotId);\n   }\n\n   @Test(dependsOnMethods = \"testGetSnapshot\")\n   public void testUpdateSnapshot() {\n      assertSnapshotAvailable(createdSnapshotId);\n      String newName = \"new name\";\n      String newDescription = \"new description\";\n\n      String requestId = api.snapshotApi().updateSnapshot(\n              Snapshot.Request.updatingBuilder()\n              .id(createdSnapshotId)\n              .description(newDescription)\n              .name(newName)\n              .bootable(true)\n              .osType(OsType.LINUX)\n              .isCpuHotPlug(true)\n              .isCpuHotUnPlug(true)\n              .isDiscVirtioHotPlug(true)\n              .isDiscVirtioHotUnPlug(true)\n              .isNicHotPlug(true)\n              .isNicHotUnPlug(true)\n              .isRamHotPlug(true)\n              .isRamHotUnPlug(true)\n              .build());\n      assertNotNull(requestId);\n   }\n\n   @Test(dependsOnMethods = \"testUpdateSnapshot\")\n   public void testRollbackSnapshot() {\n      assertSnapshotAvailable(createdSnapshotId);\n      String requestid = api.snapshotApi().rollbackSnapshot(\n              Snapshot.Request.createRollbackPayload(createdSnapshotId, storage.id()));\n      assertNotNull(requestid);\n   }\n\n   @Test(dependsOnMethods = \"testRollbackSnapshot\", alwaysRun = true)\n   public void testDeleteSnapshot() {\n      assertSnapshotAvailable(createdSnapshotId);\n      // Newly created snapshots doesn't seem to reflect in the API right away,\n      // so we need to persistently try to delete (to clean up resources as well)\n      Predicate<String> persistentDelete = Predicates2.retry(new Predicate<String>() {\n\n         @Override\n         public boolean apply(String input) {\n            try {\n               return api.snapshotApi().deleteSnapshot(input);\n            } catch (Exception ex) {\n               return false;\n            }\n         }\n      }, 120L, 5L, 10L, TimeUnit.SECONDS);\n      assertTrue(persistentDelete.apply(createdSnapshotId), \"Created snapshot wasn't deleted\");\n   }\n\n   @AfterClass(alwaysRun = true)\n   public void cleanUp() {\n      destroyDataCenter(dataCenter);\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/features/SnapshotApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.features;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\n\nimport org.jclouds.profitbricks.ProfitBricksApi;\nimport org.jclouds.profitbricks.domain.OsType;\nimport org.jclouds.profitbricks.domain.Snapshot;\nimport org.jclouds.profitbricks.internal.BaseProfitBricksMockTest;\nimport org.testng.annotations.Test;\n\nimport java.util.List;\nimport org.testng.Assert;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\n/**\n * Mock tests for the {@link org.jclouds.profitbricks.features.DataCenterApi} class\n */\n@Test(groups = \"unit\", testName = \"SnapshotApiMockTest\")\npublic class SnapshotApiMockTest extends BaseProfitBricksMockTest {\n\n   @Test\n   public void testGetAllSnapshots() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/snapshot/snapshots.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      SnapshotApi api = pbApi.snapshotApi();\n\n      try {\n         List<Snapshot> snapshots = api.getAllSnapshots();\n         assertRequestHasCommonProperties(server.takeRequest(), \"<ws:getAllSnapshots/>\");\n         assertNotNull(snapshots);\n         assertEquals(snapshots.size(), 2);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testGetAllSnapshotsReturning404() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setResponseCode(404));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      SnapshotApi api = pbApi.snapshotApi();\n\n      try {\n         List<Snapshot> snapshots = api.getAllSnapshots();\n         assertRequestHasCommonProperties(server.takeRequest());\n         assertTrue(snapshots.isEmpty());\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testGetSnapshot() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/snapshot/snapshot.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      SnapshotApi api = pbApi.snapshotApi();\n\n      String id = \"qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh\";\n\n      String content = \"<ws:getSnapshot><snapshotId>\" + id + \"</snapshotId></ws:getSnapshot>\";\n\n      try {\n         Snapshot snapshot = api.getSnapshot(id);\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertNotNull(snapshot);\n         assertEquals(snapshot.id(), id);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testGetNonExistingSnapshot() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setResponseCode(404));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      SnapshotApi api = pbApi.snapshotApi();\n\n      String id = \"random-non-existing-id\";\n      try {\n         Snapshot snapshot = api.getSnapshot(id);\n         assertRequestHasCommonProperties(server.takeRequest());\n         assertNull(snapshot);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testCreateSnapshot() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/snapshot/snapshot-create.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      SnapshotApi api = pbApi.snapshotApi();\n\n      String storageId = \"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee\";\n\n      String content = \"<ws:createSnapshot>\"\n              + \"<request>\"\n              + \"<storageId>\" + storageId + \"</storageId>\"\n              + \"<description>description</description>\"\n              + \"<snapshotName>snapshot-name</snapshotName>\"\n              + \"</request>\"\n              + \"</ws:createSnapshot>\";\n\n      try {\n         Snapshot snapshot = api.createSnapshot(\n                 Snapshot.Request.creatingBuilder()\n                 .storageId(storageId)\n                 .description(\"description\")\n                 .name(\"snapshot-name\")\n                 .build());\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertNotNull(snapshot.id());\n         assertEquals(snapshot.id(), \"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee\");\n\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testUpdateSnapshot() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/snapshot/snapshot-update.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      SnapshotApi api = pbApi.snapshotApi();\n\n      String snapshotId = \"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee\";\n\n      String content = \"<ws:updateSnapshot>\"\n              + \"<request>\"\n              + \"<snapshotId>\" + snapshotId + \"</snapshotId>\"\n              + \"<description>description</description>\"\n              + \"<snapshotName>snapshot-name</snapshotName>\"\n              + \"<bootable>false</bootable>\"\n              + \"<osType>LINUX</osType>\"\n              + \"<cpuHotPlug>false</cpuHotPlug>\"\n              + \"<cpuHotUnPlug>false</cpuHotUnPlug>\"\n              + \"<ramHotPlug>false</ramHotPlug>\"\n              + \"<ramHotUnPlug>false</ramHotUnPlug>\"\n              + \"<nicHotPlug>false</nicHotPlug>\"\n              + \"<nicHotUnPlug>false</nicHotUnPlug>\"\n              + \"<discVirtioHotPlug>false</discVirtioHotPlug>\"\n              + \"<discVirtioHotUnPlug>false</discVirtioHotUnPlug>\"\n              + \"</request>\"\n              + \"</ws:updateSnapshot>\";\n\n      try {\n         String requestId = api.updateSnapshot(Snapshot.Request.updatingBuilder()\n                 .id(snapshotId)\n                 .description(\"description\")\n                 .name(\"snapshot-name\")\n                 .bootable(false)\n                 .osType(OsType.LINUX)\n                 .isCpuHotPlug(false)\n                 .isCpuHotUnPlug(false)\n                 .isDiscVirtioHotPlug(false)\n                 .isDiscVirtioHotUnPlug(false)\n                 .isNicHotPlug(false)\n                 .isNicHotUnPlug(false)\n                 .isRamHotPlug(false)\n                 .isRamHotUnPlug(false)\n                 .build());\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertNotNull(requestId);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testDeleteSnapshot() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/snapshot/snapshot-delete.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      SnapshotApi api = pbApi.snapshotApi();\n\n      String snapshotId = \"qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh\";\n      String content = \"<ws:deleteSnapshot><snapshotId>\" + snapshotId + \"</snapshotId></ws:deleteSnapshot>\";\n\n      try {\n         boolean result = api.deleteSnapshot(snapshotId);\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertTrue(result);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testDeleteNonExistingSnapshot() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setResponseCode(404));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      SnapshotApi api = pbApi.snapshotApi();\n\n      String id = \"random-non-existing-id\";\n      try {\n         boolean result = api.deleteSnapshot(id);\n         assertRequestHasCommonProperties(server.takeRequest());\n         Assert.assertFalse(result);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testRollbackSnapshot() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/snapshot/snapshot-rollback.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      SnapshotApi api = pbApi.snapshotApi();\n\n      String snapshotId = \"qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh\";\n      String storageId = \"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee\";\n\n      String content = \"<ws:rollbackSnapshot><request><snapshotId>\" + snapshotId + \"</snapshotId><storageId>\" + storageId + \"</storageId></request></ws:rollbackSnapshot>\";\n      try {\n         String result = api.rollbackSnapshot(Snapshot.Request.createRollbackPayload(snapshotId, storageId));\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertNotNull(result);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/features/StorageApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.List;\n\nimport org.jclouds.profitbricks.BaseProfitBricksLiveTest;\nimport org.jclouds.profitbricks.domain.DataCenter;\nimport org.jclouds.profitbricks.domain.Server;\nimport org.jclouds.profitbricks.domain.Storage;\nimport org.jclouds.rest.InsufficientResourcesException;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.Test;\nimport org.testng.annotations.BeforeClass;\n\n@Test(groups = \"live\", testName = \"StorageApiLiveTest\")\npublic class StorageApiLiveTest extends BaseProfitBricksLiveTest {\n\n   private DataCenter dataCenter;\n   private Server server;\n\n   private String createdStorageId;\n\n   @BeforeClass\n   public void setupTest() {\n      dataCenter = findOrCreateDataCenter(\"storageApiLiveTest\" + System.currentTimeMillis());\n      server = findOrCreateServer(dataCenter);\n   }\n\n   @Test(expectedExceptions = InsufficientResourcesException.class)\n   public void testUberStorage() {\n      api.storageApi().createStorage(\n              Storage.Request.creatingBuilder()\n              .dataCenterId(dataCenter.id())\n              .name(\"Uber Storage\")\n              .size(9999999f)\n              .build());\n   }\n\n   @Test\n   public void testCreateStorage() {\n      assertDataCenterAvailable(dataCenter);\n      String storageId = api.storageApi().createStorage(\n              Storage.Request.creatingBuilder()\n              .dataCenterId(dataCenter.id())\n              .name(\"hdd-1\")\n              .size(2f)\n              .build());\n\n      assertNotNull(storageId);\n      assertDataCenterAvailable(dataCenter);\n\n      createdStorageId = storageId;\n   }\n\n   @Test(dependsOnMethods = \"testCreateStorage\")\n   public void testGetStorage() {\n      Storage storage = api.storageApi().getStorage(createdStorageId);\n\n      assertNotNull(storage);\n      assertEquals(storage.id(), createdStorageId);\n   }\n\n   @Test(dependsOnMethods = \"testCreateStorage\")\n   public void testGetAllStorages() {\n      List<Storage> storages = api.storageApi().getAllStorages();\n\n      assertNotNull(storages);\n      assertFalse(storages.isEmpty());\n   }\n\n   @Test(dependsOnMethods = \"testCreateStorage\")\n   public void testUpdateStorage() {\n      assertDataCenterAvailable(dataCenter);\n      String requestId = api.storageApi().updateStorage(\n              Storage.Request.updatingBuilder()\n              .id(createdStorageId)\n              .name(\"hdd-2\")\n              .size(5f)\n              .build());\n\n      assertNotNull(requestId);\n      assertDataCenterAvailable(dataCenter);\n\n      Storage storage = api.storageApi().getStorage(createdStorageId);\n      assertEquals(storage.size(), 5f);\n      assertEquals(storage.name(), \"hdd-2\");\n   }\n\n   @Test(dependsOnMethods = \"testUpdateStorage\")\n   public void testConnectStorage() {\n      assertDataCenterAvailable(dataCenter);\n      String requestId = api.storageApi().connectStorageToServer(\n              Storage.Request.connectingBuilder()\n              .storageId(createdStorageId)\n              .serverId(server.id())\n              .build()\n      );\n\n      assertNotNull(requestId);\n      assertDataCenterAvailable(dataCenter);\n\n      Storage storage = api.storageApi().getStorage(createdStorageId);\n      assertTrue(storage.serverIds().contains(server.id()));\n   }\n\n   @Test(dependsOnMethods = \"testConnectStorage\")\n   public void testDisconnectStorage() {\n      assertDataCenterAvailable(dataCenter);\n      String requestId = api.storageApi()\n              .disconnectStorageFromServer(createdStorageId, server.id());\n\n      assertNotNull(requestId);\n      assertDataCenterAvailable(dataCenter);\n\n      Storage storage = api.storageApi().getStorage(createdStorageId);\n      assertFalse(storage.serverIds().contains(server.id()));\n   }\n\n   @Test(dependsOnMethods = \"testDisconnectStorage\")\n   public void testDeleteStorage() {\n      assertDataCenterAvailable(dataCenter);\n      boolean result = api.storageApi().deleteStorage(createdStorageId);\n      assertTrue(result, \"Created test storage was not deleted\");\n   }\n\n   @AfterClass(alwaysRun = true)\n   public void cleanUp() {\n      destroyDataCenter(dataCenter);\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/features/StorageApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.List;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\n\nimport org.jclouds.profitbricks.ProfitBricksApi;\nimport org.jclouds.profitbricks.domain.Storage;\nimport org.jclouds.profitbricks.internal.BaseProfitBricksMockTest;\nimport org.testng.annotations.Test;\n\n\n@Test(groups = \"unit\", testName = \"StorageApiMockTest\")\npublic class StorageApiMockTest extends BaseProfitBricksMockTest {\n\n   @Test\n   public void testGetAllStorages() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/storage/storages.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      StorageApi api = pbApi.storageApi();\n\n      try {\n         List<Storage> storages = api.getAllStorages();\n         assertRequestHasCommonProperties(server.takeRequest(), \"<ws:getAllStorages/>\");\n         assertNotNull(storages);\n         assertTrue(storages.size() == 2);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testGetAllStoragesReturning404() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setResponseCode(404));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      StorageApi api = pbApi.storageApi();\n\n      try {\n         List<Storage> storages = api.getAllStorages();\n         assertRequestHasCommonProperties(server.takeRequest());\n         assertTrue(storages.isEmpty());\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testGetStorage() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/storage/storage.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      StorageApi api = pbApi.storageApi();\n\n      String id = \"qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh\";\n\n      String content = \"<ws:getStorage><storageId>\" + id + \"</storageId></ws:getStorage>\";\n      try {\n         Storage storage = api.getStorage(id);\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertNotNull(storage);\n         assertEquals(storage.id(), id);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testGetNonExistingStorage() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setResponseCode(404));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      StorageApi api = pbApi.storageApi();\n\n      String id = \"random-non-existing-id\";\n      try {\n         Storage storage = api.getStorage(id);\n         assertRequestHasCommonProperties(server.takeRequest());\n         assertNull(storage);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testConnectStorageToServer() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/storage/storage-connect.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      StorageApi api = pbApi.storageApi();\n\n      String storageId = \"qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh\";\n      String serverId = \"qwertyui-qwer-qwer-qwer-qwertyyuiiop\";\n\n      String content = \"<ws:connectStorageToServer><request>\"\n              + \"<storageId>\" + storageId + \"</storageId>\"\n              + \"<serverId>\" + serverId + \"</serverId>\"\n              + \"<busType>VIRTIO</busType>\"\n              + \"<deviceNumber>2</deviceNumber>\"\n              + \"</request></ws:connectStorageToServer>\";\n      try {\n         String requestId = api.connectStorageToServer(\n                 Storage.Request.connectingBuilder()\n                 .serverId(serverId)\n                 .storageId(storageId)\n                 .busType(Storage.BusType.VIRTIO)\n                 .deviceNumber(2)\n                 .build()\n         );\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertEquals(requestId, \"16463317\");\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testDisconnectStorageFromServer() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/storage/storage-disconnect.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      StorageApi api = pbApi.storageApi();\n\n      String storageId = \"qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh\";\n      String serverId = \"qwertyui-qwer-qwer-qwer-qwertyyuiiop\";\n\n      String content = \"<ws:disconnectStorageFromServer>\"\n              + \"<storageId>\" + storageId + \"</storageId>\"\n              + \"<serverId>\" + serverId + \"</serverId>\"\n              + \"</ws:disconnectStorageFromServer>\";\n\n      try {\n         String requestId = api.disconnectStorageFromServer(storageId, serverId);\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertEquals(requestId, \"16463318\");\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testCreateStorage() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/storage/storage-create.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      StorageApi api = pbApi.storageApi();\n\n      String dataCenterId = \"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee\";\n      String imageId = \"f0a59a5c-7940-11e4-8053-52540066fee9\";\n\n      String content = \"<ws:createStorage><request>\"\n              + \"<dataCenterId>\" + dataCenterId + \"</dataCenterId>\"\n              + \"<storageName>hdd-1</storageName>\" + \"<size>80</size>\"\n              + \"<mountImageId>\" + imageId + \"</mountImageId>\"\n              + \"<profitBricksImagePassword>qqqqqqqqq</profitBricksImagePassword>\"\n              + \"</request></ws:createStorage>\";\n      try {\n         String storageId = api.createStorage(\n                 Storage.Request.creatingBuilder()\n                 .dataCenterId(dataCenterId)\n                 .name(\"hdd-1\")\n                 .size(80f)\n                 .mountImageId(imageId)\n                 .imagePassword(\"qqqqqqqqq\")\n                 .build());\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertNotNull(storageId);\n         assertEquals(storageId, \"qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh\");\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testUpdateStorage() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/storage/storage-update.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      StorageApi api = pbApi.storageApi();\n\n      String storageId = \"qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh\";\n      String imageId = \"f4742db0-9160-11e4-9d74-52540066fee9\";\n\n      String content = \"<ws:updateStorage><request>\"\n              + \"<storageId>\" + storageId + \"</storageId>\"\n              + \"<size>20</size><storageName>hdd-2</storageName>\"\n              + \"<mountImageId>\" + imageId + \"</mountImageId>\"\n              + \"</request></ws:updateStorage>\";\n      try {\n         String requestId = api.updateStorage(\n                 Storage.Request.updatingBuilder()\n                 .id(storageId)\n                 .size(20f)\n                 .name(\"hdd-2\")\n                 .mountImageId(imageId)\n                 .build());\n\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertNotNull(requestId);\n         assertEquals(requestId, \"1234568\");\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testDeleteStorage() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setBody(payloadFromResource(\"/storage/storage-delete.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      StorageApi api = pbApi.storageApi();\n\n      String storageId = \"qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh\";\n\n      String content = \"<ws:deleteStorage><storageId>\" + storageId + \"</storageId></ws:deleteStorage>\";\n\n      try {\n         boolean result = api.deleteStorage(storageId);\n         assertRequestHasCommonProperties(server.takeRequest(), content);\n         assertTrue(result);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testDeleteNonExistingStorage() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setResponseCode(404));\n\n      ProfitBricksApi pbApi = api(server.url(rootUrl).url());\n      StorageApi api = pbApi.storageApi();\n\n      String id = \"random-non-existing-id\";\n      try {\n         boolean result = api.deleteStorage(id);\n         assertRequestHasCommonProperties(server.takeRequest());\n         assertFalse(result);\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/http/ResponseStatusFromPayloadHttpCommandExecutorServiceTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http;\n\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.Assert.fail;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\n\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.profitbricks.ProfitBricksApi;\nimport org.jclouds.profitbricks.domain.DataCenter;\nimport org.jclouds.profitbricks.domain.Location;\nimport org.jclouds.profitbricks.domain.Server;\nimport org.jclouds.profitbricks.features.DataCenterApi;\nimport org.jclouds.profitbricks.features.ServerApi;\nimport org.jclouds.profitbricks.internal.BaseProfitBricksMockTest;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.InsufficientResourcesException;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.testng.annotations.Test;\n\n\n/**\n * Mock tests for the {@link ResponseStatusFromPayloadHttpCommandExecutorService} class.\n */\n@Test(groups = \"unit\", testName = \"ResponseStatusFromPayloadHttpCommandExecutorServiceTest\")\npublic class ResponseStatusFromPayloadHttpCommandExecutorServiceTest extends BaseProfitBricksMockTest {\n\n   private static final int MAX_RETRIES = 5;\n\n   @Test\n   public void testNotFound() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setResponseCode(500).setBody(payloadFromResource(\"/fault-404.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(\"/\").url());\n      DataCenterApi api = pbApi.dataCenterApi();\n\n      String id = \"random-non-existing-id\";\n      try {\n         api.clearDataCenter(id);\n         fail(\"Request should have failed\");\n      } catch (Exception ex) {\n         assertTrue(ex instanceof ResourceNotFoundException, \"Exception should be an ResourceNotFoundException\");\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testBadRequest() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setResponseCode(500).setBody(payloadFromResource(\"/fault-400.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(\"/\").url());\n      DataCenterApi api = pbApi.dataCenterApi();\n\n      try {\n         api.createDataCenter(DataCenter.Request.creatingPayload(\"D@tacenter\", Location.DE_FKB));\n         fail(\"Request should have failed\");\n      } catch (Exception ex) {\n         assertTrue(ex instanceof IllegalArgumentException, \"Exception should be an IllegalArgumentException\");\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testUnauthorized() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setResponseCode(401).setBody(payloadFromResource(\"/html/fault-401.html\")));\n\n      ProfitBricksApi pbApi = api(server.url(\"/\").url());\n      DataCenterApi api = pbApi.dataCenterApi();\n\n      try {\n         api.clearDataCenter(\"some-datacenter-id\");\n         fail(\"Request should have failed\");\n      } catch (Exception ex) {\n         assertTrue(ex instanceof AuthorizationException, \"Exception should be an AuthorizationException\");\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testOverLimitSettings() throws Exception {\n      MockWebServer server = mockWebServer();\n      server.enqueue(new MockResponse().setResponseCode(503).setBody(payloadFromResource(\"/fault-413.xml\")));\n\n      ProfitBricksApi pbApi = api(server.url(\"/\").url());\n      ServerApi api = pbApi.serverApi();\n\n      try {\n         api.createServer(\n                 Server.Request.creatingBuilder()\n                 .dataCenterId(\"some-datacenter-id\")\n                 .name(\"node1\")\n                 .cores(99)\n                 .ram(12800)\n                 .build());\n         fail(\"Request should have failed.\");\n      } catch (Exception ex) {\n         assertTrue(ex instanceof InsufficientResourcesException, \"Exception should be InsufficientResourcesException\");\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   @Test\n   public void testServiceUnderMaintenance() throws Exception {\n      MockWebServer server = mockWebServer();\n      for (int i = 0; i <= MAX_RETRIES; i++)  // jclouds retries 5 times\n         server.enqueue(new MockResponse().setStatus(statusLine503ok()).setBody(payloadFromResource(\"/html/maintenance-503.html\")));\n\n      ProfitBricksApi pbApi = api(server.url(\"/\").url());\n      DataCenterApi api = pbApi.dataCenterApi();\n\n      try {\n         api.clearDataCenter(\"some-datacenter-id\");\n         fail(\"Request should have failed.\");\n      } catch (Exception ex) {\n         assertTrue(ex instanceof HttpResponseException, \"Exception should be HttpResponseException\");\n      } finally {\n         pbApi.close();\n         server.shutdown();\n      }\n   }\n\n   public String statusLine503ok() {\n      return \"HTTP/1.1 503 OK\";\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/http/filters/ProfitBricksSoapMessageEnvelopeTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.filters;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.http.HttpRequest;\nimport org.testng.annotations.Test;\n\n/**\n * Unit tests for the {@link ProfitBricksSoapMessageEnvelope} class.\n */\n@Test(groups = \"unit\", testName = \"ProfitBricksSoapMessageEnvelopeTest\")\npublic class ProfitBricksSoapMessageEnvelopeTest {\n\n   private static final String SOAP_PREFIX\n           = \"<soapenv:Envelope xmlns:soapenv=\\\"http://schemas.xmlsoap.org/soap/envelope/\\\" xmlns:ws=\\\"http://ws.api.profitbricks.com/\\\">\"\n           + \"<soapenv:Header/>\"\n           + \"<soapenv:Body>\";\n   private static final String SOAP_SUFFIX = \"</soapenv:Body></soapenv:Envelope>\";\n   private static final String ENDPOINT = \"https://api.profitbricks.com/1.3\";\n\n   @Test\n   public void testPayloadEnclosedWithSoapTags() {\n      String requestBody = \"<ws:getAllDataCenters/>\";\n      String expectedPayload = SOAP_PREFIX.concat(requestBody).concat(SOAP_SUFFIX);\n\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(ENDPOINT).payload(requestBody).build();\n\n      ProfitBricksSoapMessageEnvelope soapEnvelope = new ProfitBricksSoapMessageEnvelope();\n      HttpRequest filtered = soapEnvelope.filter(request);\n\n      assertEquals(filtered.getPayload().getRawContent(), expectedPayload);\n      assertEquals(filtered.getPayload().getContentMetadata().getContentLength(), Long.valueOf(expectedPayload.getBytes().length));\n   }\n\n   @Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = \".*must contain payload message.*\")\n   public void testNullRequest() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(ENDPOINT).build();\n      new ProfitBricksSoapMessageEnvelope().filter(request);\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/http/parser/BaseResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser;\n\nimport static org.jclouds.util.Strings2.toStringAndClose;\n\nimport java.io.IOException;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.http.functions.config.SaxParserModule;\nimport org.jclouds.rest.internal.GeneratedHttpRequest;\nimport org.testng.annotations.AfterTest;\nimport org.testng.annotations.BeforeTest;\n\nimport com.google.common.base.Throwables;\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\npublic abstract class BaseResponseHandlerTest<T> {\n\n   protected Injector injector = null;\n   protected ParseSax.Factory factory;\n   protected GeneratedHttpRequest request;\n\n   protected abstract ParseSax<T> createParser();\n\n   @BeforeTest\n   protected void setUpInjector() {\n      injector = Guice.createInjector(new SaxParserModule());\n      factory = injector.getInstance(ParseSax.Factory.class);\n      assert factory != null;\n   }\n\n   protected String payloadFromResource(String resource) {\n      try {\n         return toStringAndClose(getClass().getResourceAsStream(resource));\n      } catch (IOException e) {\n         throw Throwables.propagate(e);\n      }\n   }\n\n   @AfterTest\n   protected void tearDownInjector() {\n      factory = null;\n      injector = null;\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/http/parser/RequestIdOnlyResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser;\n\nimport org.jclouds.http.functions.ParseSax;\nimport static org.testng.Assert.assertEquals;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"RequestIdOnlyResponseHandlerTest\")\npublic class RequestIdOnlyResponseHandlerTest extends BaseResponseHandlerTest<String> {\n\n   @Override\n   protected ParseSax<String> createParser() {\n      return factory.create(injector.getInstance(RequestIdOnlyResponseHandler.class));\n   }\n\n   @Test\n   public void testParseResponseFromStartServer() {\n      ParseSax<String> parser = createParser();\n\n      String requestId = parser.parse(payloadFromResource(\"/server/server-start.xml\"));\n\n      assertEquals(requestId, \"123456\");\n   }\n\n   @Test\n   public void testParseResponseFromStopServer() {\n      ParseSax<String> parser = createParser();\n\n      String requestId = parser.parse(payloadFromResource(\"/server/server-stop.xml\"));\n\n      assertEquals(requestId, \"123456\");\n   }\n\n   @Test\n   public void testParseResponseFromResetServer() {\n      ParseSax<String> parser = createParser();\n\n      String requestId = parser.parse(payloadFromResource(\"/server/server-reset.xml\"));\n\n      assertEquals(requestId, \"123456\");\n   }\n\n   @Test\n   public void testParseResponseFromUpdateServer() {\n      ParseSax<String> parser = createParser();\n\n      String requestId = parser.parse(payloadFromResource(\"/server/server-update.xml\"));\n\n      assertEquals(requestId, \"102458\");\n   }\n\n   @Test\n   public void testParseResponseFromDeleteServer() {\n      ParseSax<String> parser = createParser();\n\n      String requestId = parser.parse(payloadFromResource(\"/server/server-delete.xml\"));\n\n      assertEquals(requestId, \"102459\");\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/http/parser/ServiceFaultResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.profitbricks.domain.ServiceFault;\nimport org.jclouds.profitbricks.domain.ServiceFault.Details;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ServiceFaultResponseHandlerTest\")\npublic class ServiceFaultResponseHandlerTest extends BaseResponseHandlerTest<ServiceFault> {\n\n   @Override\n   protected ParseSax<ServiceFault> createParser() {\n      return factory.create(injector.getInstance(ServiceFaultResponseHandler.class));\n   }\n\n   @Test\n   public void testParseSoapServiceFault() {\n      ParseSax<ServiceFault> parser = createParser();\n      ServiceFault actual = parser.parse(payloadFromResource(\"/fault-404.xml\"));\n      assertNotNull(actual, \"Parsed content returned null\");\n\n      ServiceFault expected = ServiceFault\n            .builder()\n            .faultCode(\"S:Server\")\n            .faultString(\n                  \"The requested resource could not be found. Please refer to Request Id : 16370720. [VDC-6-404] The requested resource does not exist or already deleted by the users. ResourceId ﻿random-non-existing-id\")\n            .details(\n                  Details\n                        .builder()\n                        .faultCode(ServiceFault.Details.FaultCode.RESOURCE_NOT_FOUND)\n                        .httpCode(404)\n                        .message(\n                              \"The requested resource could not be found. Please refer to Request Id : 16370720. [VDC-6-404] The requested resource does not exist or already deleted by the users. ResourceId ﻿random-non-existing-id\")\n                        .requestId(16370720).build()).build();\n\n      assertEquals(actual, expected);\n   }\n\n   @Test\n   public void testParseSoapServiceFaultWithoutDetails() {\n      ParseSax<ServiceFault> parser = createParser();\n      ServiceFault actual = parser.parse(payloadFromResource(\"/fault-500.xml\"));\n      assertNotNull(actual, \"Parsed content returned null\");\n\n      ServiceFault expected = ServiceFault.builder().faultCode(\"S:Server\").faultString(\"javax.ejb.EJBException\")\n            .build();\n\n      assertEquals(actual, expected);\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/http/parser/datacenter/DataCenterInfoResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.datacenter;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.profitbricks.domain.AvailabilityZone;\nimport org.jclouds.profitbricks.domain.DataCenter;\nimport org.jclouds.profitbricks.domain.Firewall;\nimport org.jclouds.profitbricks.domain.Location;\nimport org.jclouds.profitbricks.domain.Nic;\nimport org.jclouds.profitbricks.domain.OsType;\nimport org.jclouds.profitbricks.domain.ProvisioningState;\nimport org.jclouds.profitbricks.domain.Server;\nimport org.jclouds.profitbricks.domain.Storage;\nimport org.jclouds.profitbricks.http.parser.BaseResponseHandlerTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"DataCenterInfoResponseHandlerTest\")\npublic class DataCenterInfoResponseHandlerTest extends BaseResponseHandlerTest<DataCenter> {\n\n   @Override\n   protected ParseSax<DataCenter> createParser() {\n      return factory.create(injector.getInstance(DataCenterInfoResponseHandler.class));\n   }\n\n   protected DateService createDateParser() {\n      return injector.getInstance(DateService.class);\n   }\n\n   @Test\n   public void testParseResponseFromGetDataCenter() {\n      ParseSax<DataCenter> parser = createParser();\n\n      DataCenter actual = parser.parse(payloadFromResource(\"/datacenter/datacenter.xml\"));\n      assertNotNull(actual, \"Parsed content returned null\");\n\n      DateService dateParser = createDateParser();\n\n      DataCenter expected = DataCenter.builder()\n              .id(\"12345678-abcd-efgh-ijkl-987654321000\")\n              .version(10)\n              .name(\"JClouds-DC\")\n              .state(ProvisioningState.AVAILABLE)\n              .location(Location.US_LAS)\n              .servers(ImmutableList.<Server>of(\n                              Server.builder()\n                              .dataCenter(DataCenter.builder()\n                                      .id(\"12345678-abcd-efgh-ijkl-987654321000\")\n                                      .version(10)\n                                      .build()\n                              )\n                              .id(\"qqqqqqqq-wwww-eeee-rrrr-tttttttttttt\")\n                              .name(\"jnode1\")\n                              .cores(4)\n                              .ram(4096)\n                              .hasInternetAccess(true)\n                              .state(ProvisioningState.AVAILABLE)\n                              .status(Server.Status.RUNNING)\n                              .creationTime(dateParser.iso8601DateOrSecondsDateParse(\"2014-12-04T07:09:23.138Z\"))\n                              .lastModificationTime(dateParser.iso8601DateOrSecondsDateParse(\"2014-12-12T03:08:35.629Z\"))\n                              .osType(OsType.LINUX)\n                              .availabilityZone(AvailabilityZone.AUTO)\n                              .isCpuHotPlug(true)\n                              .isRamHotPlug(true)\n                              .isNicHotPlug(true)\n                              .isNicHotUnPlug(true)\n                              .isDiscVirtioHotPlug(true)\n                              .isDiscVirtioHotUnPlug(true)\n                              .storages(ImmutableList.<Storage>of(\n                                              Storage.builder()\n                                              .bootDevice(Boolean.TRUE)\n                                              .id(\"ssssssss-aaaa-ffff-gggg-hhhhhhhhhhhh\")\n                                              .busType(Storage.BusType.VIRTIO)\n                                              .deviceNumber(1)\n                                              .size(40f)\n                                              .name(\"jnode1-disk1\")\n                                              .build()\n                                      )\n                              )\n                              .nics(ImmutableList.<Nic>of(\n                                              Nic.builder()\n                                              .dataCenterId(\"12345678-abcd-efgh-ijkl-987654321000\")\n                                              .id(\"zzzzzzzz-xxxx-cccc-vvvv-bbbbbbbbbbbb\")\n                                              .lanId(1)\n                                              .internetAccess(true)\n                                              .serverId(\"qqqqqqqq-wwww-eeee-rrrr-tttttttttttt\")\n                                              .ips(ImmutableList.of(\"202.94.38.12\"))\n                                              .macAddress(\"02:01:09:cd:f0:b0\")\n                                              .firewall(\n                                                      Firewall.builder()\n                                                      .active(false)\n                                                      .id(\"llllllll-kkkk-jjjj-hhhh-gggggggggggg\")\n                                                      .nicId(\"zzzzzzzz-xxxx-cccc-vvvv-bbbbbbbbbbbb\")\n                                                      .state(ProvisioningState.AVAILABLE)\n                                                      .build()\n                                              )\n                                              .dhcpActive(true)\n                                              .gatewayIp(\"202.94.38.1\")\n                                              .state(ProvisioningState.AVAILABLE)\n                                              .build()\n                                      )\n                              )\n                              .build()\n                      )\n              )\n              .storages(ImmutableList.<Storage>of(\n                              Storage.builder()\n                              .id(\"ssssssss-aaaa-ffff-gggg-hhhhhhhhhhhh\")\n                              .size(40)\n                              .name(\"jnode1-disk1\")\n                              .state(ProvisioningState.AVAILABLE)\n                              .creationTime(dateParser.iso8601DateOrSecondsDateParse(\"2014-12-04T07:09:23.138Z\"))\n                              .lastModificationTime(dateParser.iso8601DateOrSecondsDateParse(\"2014-12-12T03:14:48.316Z\"))\n                              .serverIds(ImmutableList.of(\n                                              \"qqqqqqqq-wwww-eeee-rrrr-tttttttttttt\"\n                                      ))\n                              .build()\n                      ))\n              .build();\n      assertEquals(actual, expected);\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/http/parser/datacenter/DataCenterListResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.datacenter;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.List;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.profitbricks.domain.DataCenter;\nimport org.jclouds.profitbricks.domain.ProvisioningState;\nimport org.jclouds.profitbricks.http.parser.BaseResponseHandlerTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"DataCenterListResponseHandlerTest\")\npublic class DataCenterListResponseHandlerTest extends BaseResponseHandlerTest<List<DataCenter>> {\n\n   @Override\n   protected ParseSax<List<DataCenter>> createParser() {\n      return factory.create(injector.getInstance(DataCenterListResponseHandler.class));\n   }\n\n   @Test\n   public void testParseResponseFromGetAllDataCenter() {\n      ParseSax<List<DataCenter>> parser = createParser();\n\n      List<DataCenter> actual = parser.parse(payloadFromResource(\"/datacenter/datacenters.xml\"));\n      assertNotNull(actual, \"Parsed content returned null\");\n\n      List<DataCenter> expected = ImmutableList.<DataCenter>of(\n              DataCenter.builder().id(\"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee\").name(\"JClouds-DC\").version(10).state(ProvisioningState.AVAILABLE).build(),\n              DataCenter.builder().id(\"qqqqqqqq-wwww-rrrr-tttt-yyyyyyyyyyyy\").name(\"Random DC\").version(238).state(ProvisioningState.INPROCESS).build()\n      );\n      assertEquals(actual, expected);\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/http/parser/firewall/FirewallListResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.firewall;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.List;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.profitbricks.domain.Firewall;\nimport org.jclouds.profitbricks.domain.ProvisioningState;\nimport org.jclouds.profitbricks.http.parser.BaseResponseHandlerTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"FirewallListResponseHandlerTest\")\npublic class FirewallListResponseHandlerTest extends BaseResponseHandlerTest<List<Firewall>> {\n\n   @Override\n   protected ParseSax<List<Firewall>> createParser() {\n      return factory.create(injector.getInstance(FirewallListResponseHandler.class));\n   }\n\n   @Test\n   public void testParseResponseFromGetAllFirewalls() {\n      ParseSax<List<Firewall>> parser = createParser();\n      List<Firewall> actual = parser.parse(payloadFromResource(\"/firewall/firewalls.xml\"));\n      assertNotNull(actual, \"Parsed content returned null\");\n\n      List<Firewall> expected = ImmutableList.of(\n              Firewall.builder()\n              .active(true)\n              .id(\"firewall-id\")\n              .nicId(\"nic-id\")\n              .state(ProvisioningState.AVAILABLE)\n              .rules(ImmutableList.of(\n                              Firewall.Rule.builder()\n                              .id(\"firewall-rule-id\")\n                              .name(\"name\")\n                              .portRangeEnd(45678)\n                              .portRangeStart(12345)\n                              .protocol(Firewall.Protocol.TCP)\n                              .sourceIp(\"192.168.0.1\")\n                              .sourceMac(\"aa:bb:cc:dd:ee:ff\")\n                              .targetIp(\"192.168.0.2\")\n                              .build()\n                      ))\n              .build(),\n              Firewall.builder()\n              .active(true)\n              .id(\"firewall-id2\")\n              .nicId(\"nic-id\")\n              .state(ProvisioningState.AVAILABLE)\n              .rules(ImmutableList.of(\n                              Firewall.Rule.builder()\n                              .id(\"firewall-rule-id2\")\n                              .name(\"name\")\n                              .portRangeEnd(56789)\n                              .portRangeStart(23456)\n                              .protocol(Firewall.Protocol.TCP)\n                              .sourceIp(\"192.168.0.2\")\n                              .sourceMac(\"aa:bb:cc:dd:ee:ff\")\n                              .targetIp(\"192.168.0.3\")\n                              .build()\n                      ))\n              .build()\n      );\n\n      assertEquals(actual, expected);\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/http/parser/firewall/FirewallResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.firewall;\n\nimport java.util.List;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.profitbricks.domain.Firewall;\nimport org.jclouds.profitbricks.domain.ProvisioningState;\nimport org.jclouds.profitbricks.http.parser.BaseResponseHandlerTest;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport org.jclouds.profitbricks.domain.Firewall.Protocol;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"FirewallResponseHandlerTest\")\npublic class FirewallResponseHandlerTest extends BaseResponseHandlerTest<Firewall> {\n\n   @Override\n   protected ParseSax<Firewall> createParser() {\n      return factory.create(injector.getInstance(FirewallResponseHandler.class));\n   }\n\n   @Test\n   public void testParseResponseFromGetFirewall() {\n      ParseSax<Firewall> parser = createParser();\n      Firewall actual = parser.parse(payloadFromResource(\"/firewall/firewall.xml\"));\n      assertNotNull(actual, \"Parsed content returned null\");\n      List<Firewall.Rule> firewallRules = ImmutableList.of(\n              Firewall.Rule.builder()\n              .id(\"firewall-rule-id\")\n              .name(\"name\")\n              .portRangeEnd(45678)\n              .portRangeStart(12345)\n              .protocol(Protocol.TCP)\n              .sourceIp(\"192.168.0.1\")\n              .sourceMac(\"aa:bb:cc:dd:ee:ff\")\n              .targetIp(\"192.168.0.2\")\n              .build());\n\n      Firewall expected = Firewall.builder()\n              .active(true)\n              .id(\"firewall-id\")\n              .nicId(\"nic-id\")\n              .state(ProvisioningState.AVAILABLE)\n              .rules(firewallRules)\n              .build();\n\n      assertEquals(actual, expected);\n\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/http/parser/image/ImageInfoResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.image;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.profitbricks.domain.Image;\nimport org.jclouds.profitbricks.domain.Location;\nimport org.jclouds.profitbricks.domain.OsType;\nimport org.jclouds.profitbricks.http.parser.BaseResponseHandlerTest;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ImageInfoResponseHandlerTest\")\npublic class ImageInfoResponseHandlerTest extends BaseResponseHandlerTest<Image> {\n\n   @Override\n   protected ParseSax<Image> createParser() {\n      return factory.create(injector.getInstance(ImageInfoResponseHandler.class));\n   }\n\n   @Test\n   public void testParseResponseFromGetImage() {\n      ParseSax<Image> parser = createParser();\n      Image actual = parser.parse(payloadFromResource(\"/image/image.xml\"));\n      assertNotNull(actual, \"Parsed content returned null\");\n\n      Image expected = Image.builder()\n              .isBootable(true)\n              .isCpuHotPlug(true)\n              .isCpuHotUnPlug(false)\n              .isDiscVirtioHotPlug(true)\n              .isDiscVirtioHotUnPlug(true)\n              .id(\"5ad99c9e-9166-11e4-9d74-52540066fee9\")\n              .name(\"Ubuntu-14.04-LTS-server-2015-01-01\")\n              .size(2048f)\n              .type(Image.Type.HDD)\n              .location(Location.US_LAS)\n              .isNicHotPlug(true)\n              .isNicHotUnPlug(true)\n              .osType(OsType.LINUX)\n              .isPublic(true)\n              .isRamHotPlug(true)\n              .isRamHotUnPlug(false)\n              .isWriteable(true)\n              .build();\n\n      assertEquals(actual, expected);\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/http/parser/image/ImageListResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.image;\n\nimport com.google.common.collect.ImmutableList;\nimport java.util.List;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.profitbricks.domain.Image;\nimport org.jclouds.profitbricks.domain.Location;\nimport org.jclouds.profitbricks.domain.OsType;\nimport org.jclouds.profitbricks.http.parser.BaseResponseHandlerTest;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ImageListResponseHandlerTest\")\npublic class ImageListResponseHandlerTest extends BaseResponseHandlerTest<List<Image>> {\n\n   @Override\n   protected ParseSax<List<Image>> createParser() {\n      return factory.create(injector.getInstance(ImageListResponseHandler.class));\n   }\n\n   @Test\n   public void testParseResponseFromGetAllImages() {\n      ParseSax<List<Image>> parser = createParser();\n\n      List<Image> actual = parser.parse(payloadFromResource(\"/image/images.xml\"));\n      assertNotNull(actual, \"Parsed content returned null\");\n\n      List<Image> expected = ImmutableList.<Image>of(\n              Image.builder()\n              .isBootable(true)\n              .isCpuHotPlug(true)\n              .isCpuHotUnPlug(false)\n              .isDiscVirtioHotPlug(true)\n              .isDiscVirtioHotUnPlug(true)\n              .id(\"e4f73936-9161-11e4-9d74-52540066fee9\")\n              .name(\"Ubuntu-12.04-LTS-server-2015-01-01\")\n              .size(2048f)\n              .type(Image.Type.HDD)\n              .location(Location.DE_FRA)\n              .isNicHotPlug(true)\n              .isNicHotUnPlug(true)\n              .osType(OsType.LINUX)\n              .isPublic(true)\n              .isRamHotPlug(true)\n              .isRamHotUnPlug(false)\n              .isWriteable(true)\n              .build(),\n              Image.builder()\n              .isBootable(true)\n              .isCpuHotPlug(true)\n              .isCpuHotUnPlug(false)\n              .isDiscVirtioHotPlug(true)\n              .isDiscVirtioHotUnPlug(true)\n              .id(\"a984a5d3-9163-11e4-9d74-52540066fee9\")\n              .name(\"Ubuntu-14.04-LTS-server-2015-01-01\")\n              .size(2048f)\n              .type(Image.Type.HDD)\n              .location(Location.DE_FRA)\n              .isNicHotPlug(true)\n              .isNicHotUnPlug(true)\n              .osType(OsType.LINUX)\n              .isPublic(true)\n              .isRamHotPlug(true)\n              .isRamHotUnPlug(false)\n              .isWriteable(true)\n              .build(),\n              Image.builder()\n              .isBootable(true)\n              .isCpuHotPlug(true)\n              .isCpuHotUnPlug(false)\n              .isDiscVirtioHotPlug(true)\n              .isDiscVirtioHotUnPlug(true)\n              .id(\"5f3cac96-915f-11e4-9d74-52540066fee9\")\n              .name(\"Debian-jessie-prerelease-server-2015-01-01\")\n              .size(2048f)\n              .type(Image.Type.HDD)\n              .location(Location.US_LASDEV)\n              .isNicHotPlug(true)\n              .isNicHotUnPlug(true)\n              .osType(OsType.LINUX)\n              .isPublic(true)\n              .isRamHotPlug(true)\n              .isRamHotUnPlug(false)\n              .isWriteable(true)\n              .build(),\n              Image.builder()\n              .isBootable(true)\n              .isCpuHotPlug(true)\n              .isCpuHotUnPlug(false)\n              .isDiscVirtioHotPlug(true)\n              .isDiscVirtioHotUnPlug(true)\n              .id(\"f4742db0-9160-11e4-9d74-52540066fee9\")\n              .name(\"Fedora-19-server-2015-01-01\")\n              .size(2048f)\n              .type(Image.Type.HDD)\n              .location(Location.US_LASDEV)\n              .isNicHotPlug(true)\n              .isNicHotUnPlug(true)\n              .osType(OsType.LINUX)\n              .isPublic(true)\n              .isRamHotPlug(true)\n              .isRamHotUnPlug(false)\n              .isWriteable(true)\n              .build(),\n              Image.builder()\n              .isBootable(true)\n              .isCpuHotPlug(true)\n              .isCpuHotUnPlug(false)\n              .isDiscVirtioHotPlug(true)\n              .isDiscVirtioHotUnPlug(true)\n              .id(\"86902c18-9164-11e4-9d74-52540066fee9\")\n              .name(\"Ubuntu-12.04-LTS-server-2015-01-01\")\n              .size(2048f)\n              .type(Image.Type.HDD)\n              .location(Location.US_LASDEV)\n              .isNicHotPlug(true)\n              .isNicHotUnPlug(true)\n              .osType(OsType.LINUX)\n              .isPublic(true)\n              .isRamHotPlug(true)\n              .isRamHotUnPlug(false)\n              .isWriteable(true)\n              .build(),\n              Image.builder()\n              .isBootable(true)\n              .isCpuHotPlug(true)\n              .isCpuHotUnPlug(false)\n              .isDiscVirtioHotPlug(true)\n              .isDiscVirtioHotUnPlug(true)\n              .id(\"3b48e3ff-9163-11e4-9d74-52540066fee9\")\n              .name(\"Ubuntu-14.04-LTS-server-2015-01-01\")\n              .size(2048f)\n              .type(Image.Type.HDD)\n              .location(Location.DE_FKB)\n              .isNicHotPlug(true)\n              .isNicHotUnPlug(true)\n              .osType(OsType.LINUX)\n              .isPublic(true)\n              .isRamHotPlug(true)\n              .isRamHotUnPlug(false)\n              .isWriteable(true)\n              .build(),\n              Image.builder()\n              .isBootable(true)\n              .isCpuHotPlug(true)\n              .isCpuHotUnPlug(false)\n              .isDiscVirtioHotPlug(true)\n              .isDiscVirtioHotUnPlug(true)\n              .id(\"6ce17716-9164-11e4-9d74-52540066fee9\")\n              .name(\"Ubuntu-12.04-LTS-server-2015-01-01\")\n              .size(2048f)\n              .type(Image.Type.HDD)\n              .location(Location.US_LAS)\n              .isNicHotPlug(true)\n              .isNicHotUnPlug(true)\n              .osType(OsType.LINUX)\n              .isPublic(true)\n              .isRamHotPlug(true)\n              .isRamHotUnPlug(false)\n              .isWriteable(true)\n              .build()\n      );\n\n      assertEquals(actual, expected);\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/http/parser/ipblock/IpBlockListResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.ipblock;\n\nimport com.google.common.collect.ImmutableList;\nimport java.util.List;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.profitbricks.domain.IpBlock;\nimport org.jclouds.profitbricks.domain.Location;\nimport org.jclouds.profitbricks.domain.IpBlock.PublicIp;\nimport org.jclouds.profitbricks.http.parser.BaseResponseHandlerTest;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"IpBlockListResponseHandlerTest\")\npublic class IpBlockListResponseHandlerTest extends BaseResponseHandlerTest<List<IpBlock>> {\n\n   @Override\n   protected ParseSax<List<IpBlock>> createParser() {\n      return factory.create(injector.getInstance(IpBlockListResponseHandler.class));\n   }\n\n   @Test\n   public void testParseResponseFromGetAllIpBlock() {\n      ParseSax<List<IpBlock>> parser = createParser();\n\n      List<IpBlock> actual = parser.parse(payloadFromResource(\"/ipblock/ipblocks.xml\"));\n      assertNotNull(actual, \"Parsed content returned null\");\n\n      List<IpBlock> expected = ImmutableList.<IpBlock>of(\n              IpBlock.builder()\n              .id(\"block-id-1\")\n              .location(Location.US_LAS)\n              .publicIps(ImmutableList.<PublicIp>of(\n                              PublicIp.builder()\n                              .ip(\"10.0.0.2\")\n                              .nicId(\"nic-id-1\")\n                              .build(),\n                              PublicIp.builder()\n                              .ip(\"10.0.0.3\")\n                              .nicId(\"nic-id-2\")\n                              .build()))\n              .build(),\n              IpBlock.builder()\n              .id(\"block-id-2\")\n              .location(Location.US_LAS)\n              .publicIps(ImmutableList.<PublicIp>of(\n                              PublicIp.builder()\n                              .ip(\"10.0.0.4\")\n                              .build(),\n                              PublicIp.builder()\n                              .ip(\"10.0.0.5\")\n                              .nicId(\"nic-id-4\")\n                              .build()))\n              .build()\n      );\n\n      assertEquals(actual, expected);\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/http/parser/ipblock/IpBlockResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.ipblock;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Lists;\nimport java.util.List;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.profitbricks.domain.IpBlock;\nimport org.jclouds.profitbricks.domain.Location;\nimport org.jclouds.profitbricks.domain.IpBlock.PublicIp;\nimport org.jclouds.profitbricks.http.parser.BaseResponseHandlerTest;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"IpBlockResponseHandlerTest\")\npublic class IpBlockResponseHandlerTest extends BaseResponseHandlerTest<IpBlock> {\n\n   @Override\n   protected ParseSax<IpBlock> createParser() {\n      return factory.create(injector.getInstance(IpBlockResponseHandler.class));\n   }\n\n   @Test\n   public void testParseResponseFromGetIpBlock() {\n      ParseSax<IpBlock> parser = createParser();\n\n      IpBlock actual = parser.parse(payloadFromResource(\"/ipblock/ipblock.xml\"));\n      assertNotNull(actual, \"Parsed content returned null\");\n      List<String> emptyIpList = Lists.newArrayList();\n\n      IpBlock expected = IpBlock.builder()\n              .id(\"qwertyui-qwer-qwer-qwer-qwertyyuiiop\")\n              .location(Location.US_LAS)\n              .publicIps(ImmutableList.<PublicIp>of(\n                              PublicIp.builder()\n                              .ip(\"10.0.0.2\")\n                              .nicId(\"nic-id\")\n                              .build(),\n                              PublicIp.builder()\n                              .ip(\"10.0.0.3\")\n                              .build()))\n              .ips(emptyIpList)\n              .build();\n      assertEquals(actual, expected);\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/http/parser/loadbalancer/LoadBalancerIdOnlyResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.loadbalancer;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.profitbricks.http.parser.BaseResponseHandlerTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"LoadBalancerIdOnlyResponseHandlerTest\")\npublic class LoadBalancerIdOnlyResponseHandlerTest extends BaseResponseHandlerTest<String> {\n\n   @Override\n   protected ParseSax<String> createParser() {\n      return factory.create(injector.getInstance(LoadBalancerIdOnlyResponseHandler.class));\n   }\n\n   @Test\n   public void testParseResponseFromCreateLoadBalancer() {\n      ParseSax<String> parser = createParser();\n\n      String loadBalancerId = parser.parse(payloadFromResource(\"/loadbalancer/loadbalancer-create.xml\"));\n\n      assertEquals(\"1234-1234-1234-1234\", loadBalancerId);\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/http/parser/loadbalancer/LoadBalancerListResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.loadbalancer;\n\nimport com.google.common.collect.ImmutableList;\n\nimport java.util.List;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.profitbricks.domain.Firewall;\nimport org.jclouds.profitbricks.domain.LoadBalancer;\nimport org.jclouds.profitbricks.domain.LoadBalancer.Algorithm;\nimport org.jclouds.profitbricks.domain.ProvisioningState;\nimport org.jclouds.profitbricks.domain.Server;\nimport org.jclouds.profitbricks.http.parser.BaseResponseHandlerTest;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.profitbricks.domain.DataCenter;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"LoadBalancerListResponseHandlerTest\")\npublic class LoadBalancerListResponseHandlerTest extends BaseResponseHandlerTest<List<LoadBalancer>> {\n\n   @Override\n   protected ParseSax<List<LoadBalancer>> createParser() {\n      return factory.create(injector.getInstance(LoadBalancerListResponseHandler.class));\n   }\n\n   protected DateService createDateParser() {\n      return injector.getInstance(DateService.class);\n   }\n\n   @Test\n   public void testParseResponseFromGetAllLoadbalancer() {\n      ParseSax<List<LoadBalancer>> parser = createParser();\n\n      List<LoadBalancer> actual = parser.parse(payloadFromResource(\"/loadbalancer/loadbalancers.xml\"));\n      assertNotNull(actual, \"Parsed content returned null\");\n\n      DateService dateParser = createDateParser();\n\n      List<LoadBalancer> expected = ImmutableList.<LoadBalancer>of(\n              LoadBalancer.builder()\n              .id(\"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee\")\n              .algorithm(Algorithm.ROUND_ROBIN)\n              .name(\"load-1234567890-name\")\n              .dataCenter(DataCenter.builder()\n                      .id(\"datacenter-id\")\n                      .version(4)\n                      .build())\n              .internetAccess(true)\n              .ip(\"192.168.0.1\")\n              .lanId(1)\n              .state(ProvisioningState.AVAILABLE)\n              .creationTime(dateParser.iso8601DateOrSecondsDateParse(\"2014-12-04T07:09:23.138Z\"))\n              .lastModificationTime(dateParser.iso8601DateOrSecondsDateParse(\"2014-12-04T07:09:23.138Z\"))\n              .firewalls(ImmutableList.<Firewall>of(\n                              Firewall.builder()\n                              .id(\"firewall-id\")\n                              .nicId(\"nic-id\")\n                              .active(false)\n                              .state(ProvisioningState.AVAILABLE)\n                              .build()\n                      ))\n              .balancedServers(ImmutableList.<Server>of(\n                              Server.builder()\n                              .loadBalanced(true)\n                              .balancedNicId(\"balanced-nic-id\")\n                              .id(\"server-id\")\n                              .name(\"server-name\")\n                              .build()\n                      )).build(),\n              LoadBalancer.builder()\n              .id(\"qqqqqqqq-wwww-rrrr-tttt-yyyyyyyyyyyy\")\n              .algorithm(Algorithm.ROUND_ROBIN)\n              .name(\"load-balancer-name\")\n              .dataCenter(DataCenter.builder()\n                      .id(\"datacenter-id\")\n                      .version(4)\n                      .build())\n              .internetAccess(false)\n              .ip(\"192.168.0.1\")\n              .lanId(2)\n              .state(ProvisioningState.AVAILABLE)\n              .creationTime(dateParser.iso8601DateOrSecondsDateParse(\"2014-12-04T07:09:23.138Z\"))\n              .lastModificationTime(dateParser.iso8601DateOrSecondsDateParse(\"2014-12-04T07:09:23.138Z\"))\n              .firewalls(ImmutableList.<Firewall>of(\n                              Firewall.builder()\n                              .id(\"firewall-id\")\n                              .nicId(\"nic-id\")\n                              .active(false)\n                              .state(ProvisioningState.AVAILABLE)\n                              .build()\n                      ))\n              .balancedServers(ImmutableList.<Server>of(\n                              Server.builder()\n                              .loadBalanced(false)\n                              .balancedNicId(\"balanced-nic-id\")\n                              .id(\"server-id\")\n                              .name(\"server-name\")\n                              .build()\n                      ))\n              .build()\n      );\n      assertEquals(actual, expected);\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/http/parser/loadbalancer/LoadBalancerResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.loadbalancer;\n\nimport com.google.common.collect.Lists;\n\nimport java.util.List;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.profitbricks.domain.Firewall;\nimport org.jclouds.profitbricks.domain.LoadBalancer;\nimport org.jclouds.profitbricks.domain.LoadBalancer.Algorithm;\nimport org.jclouds.profitbricks.domain.ProvisioningState;\nimport org.jclouds.profitbricks.domain.Server;\nimport org.jclouds.profitbricks.domain.Storage;\nimport org.jclouds.profitbricks.http.parser.BaseResponseHandlerTest;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.profitbricks.domain.DataCenter;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"LoadBalancerResponseHandlerTest\")\npublic class LoadBalancerResponseHandlerTest extends BaseResponseHandlerTest<LoadBalancer> {\n\n   @Override\n   protected ParseSax<LoadBalancer> createParser() {\n      return factory.create(injector.getInstance(LoadBalancerResponseHandler.class));\n   }\n\n   protected DateService createDateParser() {\n      return injector.getInstance(DateService.class);\n   }\n\n   @Test\n   public void testParseResponseFromGetLoadbalancer() {\n      ParseSax<LoadBalancer> parser = createParser();\n\n      LoadBalancer actual = parser.parse(payloadFromResource(\"/loadbalancer/loadbalancer.xml\"));\n      assertNotNull(actual, \"Parsed content returned null\");\n\n      DateService dateParser = createDateParser();\n\n      List<Storage> emptyStorages = Lists.newArrayList();\n\n      List<Server> balancedServers = Lists.newArrayList();\n      balancedServers.add(Server.builder()\n              .loadBalanced(true)\n              .balancedNicId(\"balanced-nic-id\")\n              .id(\"server-id\")\n              .name(\"server-name\")\n              .storages(emptyStorages)\n              .build());\n      List<Firewall> firewalls = Lists.newArrayList();\n      firewalls.add(Firewall.builder()\n              .id(\"firewall-id\")\n              .nicId(\"nic-id\")\n              .active(false)\n              .state(ProvisioningState.AVAILABLE)\n              .build());\n\n      LoadBalancer expected = LoadBalancer.builder()\n              .id(\"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee\")\n              .algorithm(Algorithm.ROUND_ROBIN)\n              .name(\"load-balancer-name\")\n              .dataCenter(DataCenter.builder()\n                      .id(\"datacenter-id\")\n                      .version(4)\n                      .build())\n              .internetAccess(true)\n              .ip(\"192.168.0.1\")\n              .lanId(2)\n              .state(ProvisioningState.AVAILABLE)\n              .creationTime(dateParser.iso8601DateOrSecondsDateParse(\"2014-12-12T03:08:35.629Z\"))\n              .lastModificationTime(dateParser.iso8601DateOrSecondsDateParse(\"2014-12-12T03:08:35.629Z\"))\n              .firewalls(firewalls)\n              .balancedServers(balancedServers)\n              .build();\n\n      assertEquals(actual, expected);\n\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/http/parser/nic/NicIdOnlyResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.nic;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.profitbricks.http.parser.BaseResponseHandlerTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"NicIdOnlyResponseHandlerTest\")\npublic class NicIdOnlyResponseHandlerTest extends BaseResponseHandlerTest<String> {\n\n   @Override\n   protected ParseSax<String> createParser() {\n      return factory.create(injector.getInstance(NicIdOnlyResponseHandler.class));\n   }\n\n   @Test\n   public void testParseResponseFromCreateNic() {\n      ParseSax<String> parser = createParser();\n      String nicId = parser.parse(payloadFromResource(\"/nic/nic-create.xml\"));\n      assertEquals(\"nic-id\", nicId);\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/http/parser/nic/NicListResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.nic;\n\nimport com.google.common.collect.ImmutableList;\nimport java.util.List;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.profitbricks.domain.Firewall;\nimport org.jclouds.profitbricks.domain.Nic;\nimport org.jclouds.profitbricks.domain.ProvisioningState;\nimport org.jclouds.profitbricks.http.parser.BaseResponseHandlerTest;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"NicListResponseHandlerTest\")\npublic class NicListResponseHandlerTest extends BaseResponseHandlerTest<List<Nic>> {\n\n   @Override\n   protected ParseSax<List<Nic>> createParser() {\n      return factory.create(injector.getInstance(NicListResponseHandler.class));\n   }\n\n   @Test\n   public void testParseResponseFromGetAllNic() {\n      ParseSax<List<Nic>> parser = createParser();\n      List<Nic> actual = parser.parse(payloadFromResource(\"/nic/nics.xml\"));\n      assertNotNull(actual, \"Parsed content returned null\");\n\n      List<Nic> expected = ImmutableList.of(\n              Nic.builder()\n              .dataCenterId(\"datacenter-id\")\n              .id(\"nic-id\")\n              .name(\"nic-name\")\n              .lanId(1)\n              .internetAccess(true)\n              .serverId(\"server-id\")\n              .ips(ImmutableList.of(\"192.168.0.1\"))\n              .macAddress(\"aa:bb:cc:dd:ee:f1\")\n              .firewall(\n                      Firewall.builder()\n                      .active(true)\n                      .id(\"firewall-id\")\n                      .nicId(\"nic-id\")\n                      .state(ProvisioningState.AVAILABLE)\n                      .build()\n              )\n              .dhcpActive(true)\n              .gatewayIp(\"192.168.0.0\")\n              .state(ProvisioningState.AVAILABLE)\n              .build(),\n              Nic.builder()\n              .dataCenterId(\"datacenter-id\")\n              .id(\"nic-id2\")\n              .name(\"nick\")\n              .lanId(1)\n              .internetAccess(false)\n              .serverId(\"server-id\")\n              .ips(ImmutableList.of(\n                              \"192.168.0.2\",\n                              \"192.168.0.3\",\n                              \"192.168.0.4\"\n                      ))\n              .macAddress(\"aa:bb:cc:dd:ee:f2\")\n              .firewall(\n                      Firewall.builder()\n                      .active(false)\n                      .id(\"firewall-id2\")\n                      .nicId(\"nic-id\")\n                      .state(ProvisioningState.AVAILABLE)\n                      .build()\n              )\n              .dhcpActive(false)\n              .gatewayIp(\"192.168.0.0\")\n              .state(ProvisioningState.AVAILABLE)\n              .build()\n      );\n\n      assertEquals(actual, expected);\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/http/parser/nic/NicResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.nic;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport com.google.common.collect.ImmutableList;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.profitbricks.domain.Firewall;\nimport org.jclouds.profitbricks.domain.Nic;\nimport org.jclouds.profitbricks.domain.ProvisioningState;\nimport org.jclouds.profitbricks.http.parser.BaseResponseHandlerTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"NicResponseHandlerTest\")\npublic class NicResponseHandlerTest extends BaseResponseHandlerTest<Nic> {\n\n   @Override\n   protected ParseSax<Nic> createParser() {\n      return factory.create(injector.getInstance(NicResponseHandler.class));\n   }\n\n   @Test\n   public void testParseResponseFromGetNic() {\n      ParseSax<Nic> parser = createParser();\n      Nic actual = parser.parse(payloadFromResource(\"/nic/nic.xml\"));\n      assertNotNull(actual, \"Parsed content returned null\");\n\n      Nic expected = Nic.builder()\n              .id(\"12345678-abcd-efgh-ijkl-987654321000\")\n              .dataCenterId(\"0\")\n              .name(\"name\")\n              .lanId(1)\n              .internetAccess(true)\n              .serverId(\"server-id\")\n              .ips(ImmutableList.of(\"192.168.0.1\"))\n              .macAddress(\"aa:bb:cc:dd:ee:ff\")\n              .dhcpActive(true)\n              .gatewayIp(\"10.0.0.1\")\n              .state(ProvisioningState.AVAILABLE)\n              .firewall(\n                      Firewall.builder()\n                      .active(true)\n                      .id(\"firewall-id\")\n                      .nicId(\"nic-id\")\n                      .state(ProvisioningState.AVAILABLE)\n                      .build())\n              .build();\n\n      assertEquals(actual, expected);\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/http/parser/server/ServerIdOnlyResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.server;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.profitbricks.http.parser.BaseResponseHandlerTest;\nimport static org.testng.Assert.assertEquals;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ServerIdOnlyResponseHandlerTest\")\npublic class ServerIdOnlyResponseHandlerTest extends BaseResponseHandlerTest<String> {\n\n   @Override\n   protected ParseSax<String> createParser() {\n      return factory.create(injector.getInstance(ServerIdOnlyResponseHandler.class));\n   }\n\n   @Test\n   public void testParseResponseFromCreateServer() {\n      ParseSax<String> parser = createParser();\n\n      String serverId = parser.parse(payloadFromResource(\"/server/server-create.xml\"));\n\n      assertEquals(\"qwertyui-qwer-qwer-qwer-qwertyyuiiop\", serverId);\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/http/parser/server/ServerInfoResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.server;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.profitbricks.domain.AvailabilityZone;\nimport org.jclouds.profitbricks.domain.DataCenter;\nimport org.jclouds.profitbricks.domain.Firewall;\nimport org.jclouds.profitbricks.domain.Nic;\nimport org.jclouds.profitbricks.domain.OsType;\nimport org.jclouds.profitbricks.domain.ProvisioningState;\nimport org.jclouds.profitbricks.domain.Server;\nimport org.jclouds.profitbricks.domain.Storage;\nimport org.jclouds.profitbricks.http.parser.BaseResponseHandlerTest;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"ServerInfoResponseHandlerTest\")\npublic class ServerInfoResponseHandlerTest extends BaseResponseHandlerTest<Server> {\n\n   @Override\n   protected ParseSax<Server> createParser() {\n      return factory.create(injector.getInstance(ServerInfoResponseHandler.class));\n   }\n\n   protected DateService createDateParser() {\n      return injector.getInstance(DateService.class);\n   }\n\n   @Test\n   public void testParseResponseFromGetServer() {\n      ParseSax<Server> parser = createParser();\n\n      Server actual = parser.parse(payloadFromResource(\"/server/server.xml\"));\n      assertNotNull(actual, \"Parsed content returned null\");\n\n      DateService dateParser = createDateParser();\n\n      Server expected = Server.builder()\n              .id(\"qwertyui-qwer-qwer-qwer-qwertyyuiiop\")\n              .dataCenter(DataCenter.builder()\n                      .id(\"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee\")\n                      .version(10)\n                      .build())\n              .name(\"facebook-node\")\n              .cores(4)\n              .ram(4096)\n              .hasInternetAccess(true)\n              .state(ProvisioningState.AVAILABLE)\n              .status(Server.Status.RUNNING)\n              .creationTime(dateParser.iso8601DateOrSecondsDateParse(\"2014-12-04T07:09:23.138Z\"))\n              .lastModificationTime(dateParser.iso8601DateOrSecondsDateParse(\"2014-12-12T03:08:35.629Z\"))\n              .osType(OsType.LINUX)\n              .availabilityZone(AvailabilityZone.AUTO)\n              .isCpuHotPlug(true)\n              .isRamHotPlug(true)\n              .isNicHotPlug(true)\n              .isNicHotUnPlug(true)\n              .isDiscVirtioHotPlug(true)\n              .isDiscVirtioHotUnPlug(true)\n              .loadBalanced(true)\n              .balancedNicId(\"qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh\")\n              .storages(ImmutableList.<Storage>of(\n                              Storage.builder()\n                              .bootDevice(Boolean.TRUE)\n                              .busType(Storage.BusType.VIRTIO)\n                              .deviceNumber(1)\n                              .size(40f)\n                              .id(\"qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh\")\n                              .name(\"facebook-storage\")\n                              .build()\n                      )\n              )\n              .nics(ImmutableList.<Nic>of(\n                              Nic.builder()\n                              .dataCenterId(\"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee\")\n                              .id(\"qwqwqwqw-wewe-erer-rtrt-tytytytytyty\")\n                              .lanId(1)\n                              .internetAccess(true)\n                              .serverId(\"qwertyui-qwer-qwer-qwer-qwertyyuiiop\")\n                              .ips(ImmutableList.of(\"173.252.120.6\"))\n                              .macAddress(\"02:01:09:cd:f0:b0\")\n                              .firewall(Firewall.builder()\n                                      .active(false)\n                                      .id(\"wqwqwqwq-ewew-rere-trtr-ytytytytytyt\")\n                                      .nicId(\"qwqwqwqw-wewe-erer-rtrt-tytytytytyty\")\n                                      .state(ProvisioningState.AVAILABLE)\n                                      .build())\n                              .dhcpActive(true)\n                              .gatewayIp(\"173.252.120.1\")\n                              .state(ProvisioningState.AVAILABLE)\n                              .build()\n                      ))\n              .build();\n\n      assertEquals(actual, expected);\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/http/parser/server/ServerListResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.server;\n\nimport com.google.common.collect.ImmutableList;\n\nimport java.util.List;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.profitbricks.domain.AvailabilityZone;\nimport org.jclouds.profitbricks.domain.OsType;\nimport org.jclouds.profitbricks.domain.ProvisioningState;\nimport org.jclouds.profitbricks.domain.Server;\nimport org.jclouds.profitbricks.http.parser.BaseResponseHandlerTest;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.profitbricks.domain.DataCenter;\nimport org.jclouds.profitbricks.domain.Firewall;\nimport org.jclouds.profitbricks.domain.Nic;\nimport org.jclouds.profitbricks.domain.Storage;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ServerListResponseHandlerTest\")\npublic class ServerListResponseHandlerTest extends BaseResponseHandlerTest<List<Server>> {\n\n   @Override\n   protected ParseSax<List<Server>> createParser() {\n      return factory.create(injector.getInstance(ServerListResponseHandler.class));\n   }\n\n   protected DateService createDateParser() {\n      return injector.getInstance(DateService.class);\n   }\n\n   @Test\n   public void testParseResponseFromGetAllServers() {\n      ParseSax<List<Server>> parser = createParser();\n\n      List<Server> actual = parser.parse(payloadFromResource(\"/server/servers.xml\"));\n      assertNotNull(actual, \"Parsed content returned null\");\n\n      DateService dateParser = createDateParser();\n\n      List<Server> expected = ImmutableList.<Server>of(\n              Server.builder()\n              .dataCenter(DataCenter.builder()\n                      .id(\"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee\")\n                      .version(10)\n                      .build()\n              )\n              .id(\"qwertyui-qwer-qwer-qwer-qwertyyuiiop\")\n              .name(\"facebook-node\")\n              .cores(4)\n              .ram(4096)\n              .hasInternetAccess(true)\n              .state(ProvisioningState.AVAILABLE)\n              .status(Server.Status.RUNNING)\n              .creationTime(dateParser.iso8601DateOrSecondsDateParse(\"2014-12-04T07:09:23.138Z\"))\n              .lastModificationTime(dateParser.iso8601DateOrSecondsDateParse(\"2014-12-12T03:08:35.629Z\"))\n              .osType(OsType.LINUX)\n              .availabilityZone(AvailabilityZone.AUTO)\n              .isCpuHotPlug(true)\n              .isRamHotPlug(true)\n              .isNicHotPlug(true)\n              .isNicHotUnPlug(true)\n              .isDiscVirtioHotPlug(true)\n              .isDiscVirtioHotUnPlug(true)\n              .loadBalanced(true)\n              .balancedNicId(\"qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh\")\n              .storages(ImmutableList.<Storage>of(\n                              Storage.builder()\n                              .bootDevice(Boolean.TRUE)\n                              .busType(Storage.BusType.VIRTIO)\n                              .deviceNumber(1)\n                              .size(40f)\n                              .id(\"qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh\")\n                              .name(\"facebook-storage\")\n                              .build()\n                      )\n              )\n              .nics(ImmutableList.<Nic>of(\n                              Nic.builder()\n                              .dataCenterId(\"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee\")\n                              .id(\"qwqwqwqw-wewe-erer-rtrt-tytytytytyty\")\n                              .lanId(1)\n                              .internetAccess(true)\n                              .serverId(\"qwertyui-qwer-qwer-qwer-qwertyyuiiop\")\n                              .ips(ImmutableList.of(\"173.252.120.6\"))\n                              .macAddress(\"02:01:09:cd:f0:b0\")\n                              .firewall(Firewall.builder()\n                                      .active(false)\n                                      .id(\"wqwqwqwq-ewew-rere-trtr-ytytytytytyt\")\n                                      .nicId(\"qwqwqwqw-wewe-erer-rtrt-tytytytytyty\")\n                                      .state(ProvisioningState.AVAILABLE)\n                                      .build())\n                              .dhcpActive(true)\n                              .gatewayIp(\"173.252.120.1\")\n                              .state(ProvisioningState.AVAILABLE)\n                              .build()\n                      )\n              )\n              .build(),\n              Server.builder()\n              .dataCenter(DataCenter.builder()\n                      .id(\"qqqqqqqq-wwww-rrrr-tttt-yyyyyyyyyyyy\")\n                      .version(238)\n                      .build()\n              )\n              .id(\"asdfghjk-asdf-asdf-asdf-asdfghjklkjl\")\n              .name(\"google-node\")\n              .cores(1)\n              .ram(1024)\n              .hasInternetAccess(false)\n              .state(ProvisioningState.AVAILABLE)\n              .status(Server.Status.RUNNING)\n              .creationTime(dateParser.iso8601DateOrSecondsDateParse(\"2014-11-12T07:01:00.441Z\"))\n              .lastModificationTime(dateParser.iso8601DateOrSecondsDateParse(\"2014-11-12T07:01:00.441Z\"))\n              .osType(OsType.LINUX)\n              .availabilityZone(AvailabilityZone.AUTO)\n              .isCpuHotPlug(true)\n              .isRamHotPlug(true)\n              .isNicHotPlug(true)\n              .isNicHotUnPlug(true)\n              .isDiscVirtioHotPlug(true)\n              .isDiscVirtioHotUnPlug(true)\n              .loadBalanced(true)\n              .balancedNicId(\"qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh\")\n              .storages(ImmutableList.<Storage>of(\n                              Storage.builder()\n                              .bootDevice(Boolean.TRUE)\n                              .busType(Storage.BusType.VIRTIO)\n                              .deviceNumber(1)\n                              .size(5f)\n                              .id(\"asfasfle-f23n-cu89-klfr-njkdsvwllkfa\")\n                              .name(\"google-disk\")\n                              .build()\n                      )\n              )\n              .nics(ImmutableList.<Nic>of(\n                              Nic.builder()\n                              .dataCenterId(\"qqqqqqqq-wwww-rrrr-tttt-yyyyyyyyyyyy\")\n                              .id(\"mkl45h5e-sdgb-h6rh-235r-rfweshdfhreh\")\n                              .lanId(3)\n                              .internetAccess(false)\n                              .serverId(\"asdfghjk-asdf-asdf-asdf-asdfghjklkjl\")\n                              .ips(ImmutableList.of(\"202.69.181.241\"))\n                              .macAddress(\"02:01:9e:5e:35:1e\")\n                              .firewall(Firewall.builder()\n                                      .active(false)\n                                      .id(\"cvvdsgbd-sdgj-eger-h56j-wet43gvsgeg4\")\n                                      .nicId(\"mkl45h5e-sdgb-h6rh-235r-rfweshdfhreh\")\n                                      .state(ProvisioningState.INPROCESS)\n                                      .build())\n                              .dhcpActive(false)\n                              .gatewayIp(\"202.69.181.1\")\n                              .state(ProvisioningState.AVAILABLE)\n                              .build()\n                      )\n              )\n              .build()\n      );\n\n      assertEquals(actual, expected);\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/http/parser/snapshot/SnapshotListResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.snapshot;\n\nimport com.google.common.collect.Lists;\n\nimport java.util.List;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.profitbricks.domain.Location;\nimport org.jclouds.profitbricks.domain.OsType;\nimport org.jclouds.profitbricks.domain.ProvisioningState;\nimport org.jclouds.profitbricks.domain.Snapshot;\nimport org.jclouds.profitbricks.http.parser.BaseResponseHandlerTest;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport org.jclouds.date.DateService;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"SnapshotListResponseHandlerTest\")\npublic class SnapshotListResponseHandlerTest extends BaseResponseHandlerTest<List<Snapshot>> {\n\n   @Override\n   protected ParseSax<List<Snapshot>> createParser() {\n      return factory.create(injector.getInstance(SnapshotListResponseHandler.class));\n   }\n\n   protected DateService createDateParser() {\n      return injector.getInstance(DateService.class);\n   }\n\n   @Test\n   public void testParseResponseFromGetSnapshot() {\n      ParseSax<List<Snapshot>> parser = createParser();\n\n      List<Snapshot> actual = parser.parse(payloadFromResource(\"/snapshot/snapshots.xml\"));\n      assertNotNull(actual);\n\n      DateService dateParser = createDateParser();\n\n      List<Snapshot> expected = Lists.newArrayList();\n\n      expected.add(Snapshot.builder()\n              .id(\"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee\")\n              .description(\"description\")\n              .size(1024f)\n              .name(\"snapshot01\")\n              .state(ProvisioningState.AVAILABLE)\n              .isBootable(true)\n              .osType(OsType.LINUX)\n              .isCpuHotPlug(true)\n              .isCpuHotUnPlug(true)\n              .isDiscVirtioHotPlug(true)\n              .isDiscVirtioHotUnPlug(true)\n              .isRamHotPlug(true)\n              .isRamHotUnPlug(true)\n              .isNicHotPlug(true)\n              .isNicHotUnPlug(true)\n              .location(Location.US_LAS)\n              .creationTime(dateParser.iso8601DateOrSecondsDateParse(\"2015-01-26T07:09:23.138Z\"))\n              .lastModificationTime(dateParser.iso8601DateOrSecondsDateParse(\"2015-01-26T07:09:23.138Z\"))\n              .build());\n\n      expected.add(Snapshot.builder()\n              .id(\"qqqqqqqq-wwww-rrrr-tttt-yyyyyyyyyyyy\")\n              .description(\"description\")\n              .size(1024f)\n              .name(\"snapshot02\")\n              .state(ProvisioningState.AVAILABLE)\n              .isBootable(true)\n              .osType(OsType.LINUX)\n              .isCpuHotPlug(true)\n              .isCpuHotUnPlug(true)\n              .isDiscVirtioHotPlug(true)\n              .isDiscVirtioHotUnPlug(true)\n              .isRamHotPlug(true)\n              .isRamHotUnPlug(true)\n              .isNicHotPlug(true)\n              .isNicHotUnPlug(true)\n              .location(Location.US_LAS)\n              .creationTime(dateParser.iso8601DateOrSecondsDateParse(\"2015-01-26T07:09:23.138Z\"))\n              .lastModificationTime(dateParser.iso8601DateOrSecondsDateParse(\"2015-01-26T07:09:23.138Z\"))\n              .build());\n\n      assertEquals(actual, expected);\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/http/parser/snapshot/SnapshotResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.snapshot;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.profitbricks.domain.Location;\nimport org.jclouds.profitbricks.domain.OsType;\nimport org.jclouds.profitbricks.domain.ProvisioningState;\nimport org.jclouds.profitbricks.domain.Snapshot;\nimport org.jclouds.profitbricks.http.parser.BaseResponseHandlerTest;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport org.jclouds.date.DateService;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ServerResponseHandlerTest\")\npublic class SnapshotResponseHandlerTest extends BaseResponseHandlerTest<Snapshot> {\n\n   @Override\n   protected ParseSax<Snapshot> createParser() {\n      return factory.create(injector.getInstance(SnapshotResponseHandler.class));\n   }\n\n   protected DateService createDateParser() {\n      return injector.getInstance(DateService.class);\n   }\n\n   @Test\n   public void testParseResponseFromGetSnapshot() {\n      ParseSax<Snapshot> parser = createParser();\n\n      Snapshot actual = parser.parse(payloadFromResource(\"/snapshot/snapshot.xml\"));\n      assertNotNull(actual, \"Parsed content returned null\");\n\n      DateService dateParser = createDateParser();\n\n      Snapshot expected = Snapshot.builder()\n              .id(\"qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh\")\n              .description(\"description\")\n              .size(1024f)\n              .name(\"snapshot01\")\n              .state(ProvisioningState.AVAILABLE)\n              .isBootable(true)\n              .osType(OsType.LINUX)\n              .isCpuHotPlug(true)\n              .isCpuHotUnPlug(true)\n              .isDiscVirtioHotPlug(true)\n              .isDiscVirtioHotUnPlug(true)\n              .isRamHotPlug(true)\n              .isRamHotUnPlug(true)\n              .isNicHotPlug(true)\n              .isNicHotUnPlug(true)\n              .location(Location.US_LAS)\n              .creationTime(dateParser.iso8601DateOrSecondsDateParse(\"2015-01-26T07:09:23.138Z\"))\n              .lastModificationTime(dateParser.iso8601DateOrSecondsDateParse(\"2015-01-26T07:09:23.138Z\"))\n              .build();\n\n      assertEquals(actual, expected);\n\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/http/parser/state/GetProvisioningStateResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.state;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.LinkedHashMap;\nimport java.util.Map;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.profitbricks.domain.ProvisioningState;\nimport org.jclouds.profitbricks.http.parser.BaseResponseHandlerTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"GetProvisioningStateResponseHandlerTest\")\npublic class GetProvisioningStateResponseHandlerTest extends BaseResponseHandlerTest<ProvisioningState> {\n\n   private final Map<ProvisioningState, String> sampleResponses = new LinkedHashMap<ProvisioningState, String>();\n\n   GetProvisioningStateResponseHandlerTest() {\n      sampleResponses.put(ProvisioningState.INACTIVE,\n              \"<soapenv:Envelope xmlns:soapenv=\\\"http://schemas.xmlsoap.org/soap/envelope/\\\" xmlns:ws=\\\"http://ws.api.profitbricks.com/\\\">\\n\"\n              + \"   <soapenv:Header/>\\n\"\n              + \"   <soapenv:Body>\\n\"\n              + \"      <ws:getDataCenterStateResponse>\\n\"\n              + \"         <return>INACTIVE</return>\\n\"\n              + \"      </ws:getDataCenterStateResponse>\\n\"\n              + \"   </soapenv:Body>\\n\"\n              + \"</soapenv:Envelope>\");\n      sampleResponses.put(ProvisioningState.INPROCESS,\n              \"<soapenv:Envelope xmlns:soapenv=\\\"http://schemas.xmlsoap.org/soap/envelope/\\\" xmlns:ws=\\\"http://ws.api.profitbricks.com/\\\">\\n\"\n              + \"   <soapenv:Header/>\\n\"\n              + \"   <soapenv:Body>\\n\"\n              + \"      <ws:getDataCenterStateResponse>\\n\"\n              + \"         <return>INPROCESS</return>\\n\"\n              + \"      </ws:getDataCenterStateResponse>\\n\"\n              + \"   </soapenv:Body>\\n\"\n              + \"</soapenv:Envelope>\");\n      sampleResponses.put(ProvisioningState.AVAILABLE,\n              \"<soapenv:Envelope xmlns:soapenv=\\\"http://schemas.xmlsoap.org/soap/envelope/\\\" xmlns:ws=\\\"http://ws.api.profitbricks.com/\\\">\\n\"\n              + \"   <soapenv:Header/>\\n\"\n              + \"   <soapenv:Body>\\n\"\n              + \"      <ws:getDataCenterStateResponse>\\n\"\n              + \"         <return>AVAILABLE</return>\\n\"\n              + \"      </ws:getDataCenterStateResponse>\\n\"\n              + \"   </soapenv:Body>\\n\"\n              + \"</soapenv:Envelope>\");\n      sampleResponses.put(ProvisioningState.DELETED,\n              \"<soapenv:Envelope xmlns:soapenv=\\\"http://schemas.xmlsoap.org/soap/envelope/\\\" xmlns:ws=\\\"http://ws.api.profitbricks.com/\\\">\\n\"\n              + \"   <soapenv:Header/>\\n\"\n              + \"   <soapenv:Body>\\n\"\n              + \"      <ws:getDataCenterStateResponse>\\n\"\n              + \"         <return>DELETED</return>\\n\"\n              + \"      </ws:getDataCenterStateResponse>\\n\"\n              + \"   </soapenv:Body>\\n\"\n              + \"</soapenv:Envelope>\");\n      sampleResponses.put(ProvisioningState.ERROR,\n              \"<soapenv:Envelope xmlns:soapenv=\\\"http://schemas.xmlsoap.org/soap/envelope/\\\" xmlns:ws=\\\"http://ws.api.profitbricks.com/\\\">\\n\"\n              + \"   <soapenv:Header/>\\n\"\n              + \"   <soapenv:Body>\\n\"\n              + \"      <ws:getDataCenterStateResponse>\\n\"\n              + \"         <return>ERROR</return>\\n\"\n              + \"      </ws:getDataCenterStateResponse>\\n\"\n              + \"   </soapenv:Body>\\n\"\n              + \"</soapenv:Envelope>\");\n      sampleResponses.put(ProvisioningState.UNRECOGNIZED,\n              \"<soapenv:Envelope xmlns:soapenv=\\\"http://schemas.xmlsoap.org/soap/envelope/\\\" xmlns:ws=\\\"http://ws.api.profitbricks.com/\\\">\\n\"\n              + \"   <soapenv:Header/>\\n\"\n              + \"   <soapenv:Body>\\n\"\n              + \"      <ws:getDataCenterStateResponse>\\n\"\n              + \"         <return>MEH</return>\\n\"\n              + \"      </ws:getDataCenterStateResponse>\\n\"\n              + \"   </soapenv:Body>\\n\"\n              + \"</soapenv:Envelope>\");\n   }\n\n   @Override\n   protected ParseSax<ProvisioningState> createParser() {\n      return factory.create(injector.getInstance(GetProvisioningStateResponseHandler.class));\n   }\n\n   @Test\n   public void testParseResponseFromGetProvisioningState() {\n      ParseSax<ProvisioningState> parser = createParser();\n\n      for (Map.Entry<ProvisioningState, String> pair : sampleResponses.entrySet()) {\n         ProvisioningState actual = parser.parse(pair.getValue());\n         assertNotNull(actual, \"Parsed content returned null\");\n\n         assertEquals(pair.getKey(), actual);\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/http/parser/storage/StorageIdOnlyResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.storage;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.profitbricks.http.parser.BaseResponseHandlerTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"StorageIdOnlyResponseHandlerTest\")\npublic class StorageIdOnlyResponseHandlerTest extends BaseResponseHandlerTest<String> {\n\n   @Override\n   protected ParseSax<String> createParser() {\n      return factory.create(injector.getInstance(StorageIdOnlyResponseHandler.class));\n   }\n\n   @Test\n   public void testParseResponseFromCreateStorage() {\n      ParseSax<String> parser = createParser();\n\n      String storageId = parser.parse(payloadFromResource(\"/storage/storage-create.xml\"));\n\n      assertEquals(\"qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh\", storageId);\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/http/parser/storage/StorageInfoResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.storage;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.profitbricks.domain.ProvisioningState;\nimport org.jclouds.profitbricks.domain.Storage;\nimport org.jclouds.profitbricks.http.parser.BaseResponseHandlerTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\", testName = \"StorageInfoResponseHandlerTest\")\npublic class StorageInfoResponseHandlerTest extends BaseResponseHandlerTest<Storage> {\n\n   @Override\n   protected ParseSax<Storage> createParser() {\n      return factory.create(injector.getInstance(StorageInfoResponseHandler.class));\n   }\n\n   protected DateService createDateParser() {\n      return injector.getInstance(DateService.class);\n   }\n\n   @Test\n   public void testParseResponseFromGetStorage() {\n      ParseSax<Storage> parser = createParser();\n\n      Storage actual = parser.parse(payloadFromResource(\"/storage/storage.xml\"));\n      assertNotNull(actual, \"Parsed content returned null\");\n\n      DateService dateParser = createDateParser();\n\n      Storage expected = Storage.builder()\n              .id(\"qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh\")\n              .size(40)\n              .name(\"hdd-1\")\n              .state(ProvisioningState.AVAILABLE)\n              .serverIds(ImmutableList.<String>of(\"qwertyui-qwer-qwer-qwer-qwertyyuiiop\"))\n              .creationTime(dateParser.iso8601DateOrSecondsDateParse(\"2014-12-04T07:09:23.138Z\"))\n              .lastModificationTime(dateParser.iso8601DateOrSecondsDateParse(\"2014-12-12T03:14:48.316Z\"))\n              .build();\n\n      assertEquals(actual, expected);\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/http/parser/storage/StorageListResponseHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.http.parser.storage;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport com.google.common.collect.ImmutableList;\n\nimport java.util.List;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.profitbricks.domain.ProvisioningState;\nimport org.jclouds.profitbricks.domain.Storage;\nimport org.jclouds.profitbricks.http.parser.BaseResponseHandlerTest;\n\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"StorageListResponseHandlerTest\")\npublic class StorageListResponseHandlerTest extends BaseResponseHandlerTest<List<Storage>> {\n\n   @Override\n   protected ParseSax<List<Storage>> createParser() {\n      return factory.create(injector.getInstance(StorageListResponseHandler.class));\n   }\n\n   protected DateService createDateParser() {\n      return injector.getInstance(DateService.class);\n   }\n\n   @Test\n   public void testParseResponseFromGetAllStorages() {\n      ParseSax<List<Storage>> parser = createParser();\n\n      List<Storage> actual = parser.parse(payloadFromResource(\"/storage/storages.xml\"));\n      assertNotNull(actual, \"Parsed content returned null\");\n\n      DateService dateParser = createDateParser();\n\n      List<Storage> expected = ImmutableList.<Storage>of(\n              Storage.builder()\n              .id(\"qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh\")\n              .size(40f)\n              .name(\"hdd-1\")\n              .state(ProvisioningState.AVAILABLE)\n              .serverIds(ImmutableList.<String>of(\"qwertyui-qwer-qwer-qwer-qwertyyuiiop\"))\n              .creationTime(dateParser.iso8601DateOrSecondsDateParse(\"2014-12-04T07:09:23.138Z\"))\n              .lastModificationTime(dateParser.iso8601DateOrSecondsDateParse(\"2014-12-12T03:14:48.316Z\"))\n              .build(),\n              Storage.builder()\n              .id(\"asfasfle-f23n-cu89-klfr-njkdsvwllkfa\")\n              .size(100f)\n              .name(\"hdd-2\")\n              .state(ProvisioningState.INPROCESS)\n              .serverIds(ImmutableList.<String>of(\"asdfghjk-asdf-asdf-asdf-asdfghjklkjl\"))\n              .creationTime(dateParser.iso8601DateOrSecondsDateParse(\"2014-11-04T07:09:23.138Z\"))\n              .lastModificationTime(dateParser.iso8601DateOrSecondsDateParse(\"2014-11-12T03:14:48.316Z\"))\n              .build()\n      );\n\n      assertEquals(actual, expected);\n   }\n\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/internal/BaseProfitBricksMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.internal;\n\nimport static org.jclouds.util.Strings2.toStringAndClose;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.net.URL;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport jakarta.ws.rs.core.HttpHeaders;\nimport jakarta.ws.rs.core.MediaType;\n\nimport okhttp3.mockwebserver.MockWebServer;\nimport okhttp3.mockwebserver.RecordedRequest;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.http.filters.BasicAuthentication;\nimport org.jclouds.profitbricks.ProfitBricksApi;\n\nimport com.google.common.base.Throwables;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n\n/**\n * Base class for all ProfitBricks mock test\n */\npublic class BaseProfitBricksMockTest {\n\n   protected static final String authHeader = BasicAuthentication.basic(\"username\", \"password\");\n   protected static final String provider = \"profitbricks\";\n   protected static final String rootUrl = \"/1.3\";\n\n   private static final String SOAP_PREFIX\n           = \"<soapenv:Envelope xmlns:soapenv=\\\"http://schemas.xmlsoap.org/soap/envelope/\\\" xmlns:ws=\\\"http://ws.api.profitbricks.com/\\\">\"\n           + \"<soapenv:Header/>\"\n           + \"<soapenv:Body>\";\n\n   private static final String SOAP_SUFFIX = \"</soapenv:Body></soapenv:Envelope>\";\n\n   private final Set<Module> modules = ImmutableSet.<Module>of();\n\n   public BaseProfitBricksMockTest() {\n   }\n\n   public ProfitBricksApi api(URL url) {\n      return ContextBuilder.newBuilder(provider)\n              .credentials(\"username\", \"password\")\n              .endpoint(url.toString())\n              .modules(modules)\n              .overrides(setupProperties())\n              .buildApi(ProfitBricksApi.class);\n   }\n\n   protected Properties setupProperties() {\n      return new Properties();\n   }\n\n   public static MockWebServer mockWebServer() throws IOException {\n      MockWebServer server = new MockWebServer();\n      server.start();\n      return server;\n   }\n\n   public String payloadFromResource(String resource) {\n      try {\n         return toStringAndClose(getClass().getResourceAsStream(resource));\n      } catch (IOException e) {\n         throw Throwables.propagate(e);\n      }\n   }\n\n   protected static String payloadSoapWithBody(String body) {\n      return SOAP_PREFIX.concat(body).concat(SOAP_SUFFIX);\n   }\n\n   protected static void assertRequestHasCommonProperties(final RecordedRequest request) {\n      assertEquals(request.getMethod(), \"POST\");\n      assertEquals(request.getPath(), rootUrl);\n      assertEquals(request.getHeader(HttpHeaders.AUTHORIZATION), authHeader);\n      assertEquals(request.getHeader(HttpHeaders.ACCEPT), MediaType.TEXT_XML);\n   }\n\n   protected static void assertRequestHasCommonProperties(final RecordedRequest request, String content) {\n      assertEquals(request.getBody().readUtf8(), payloadSoapWithBody(content));\n      assertRequestHasCommonProperties(request);\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/java/org/jclouds/profitbricks/util/MacAddressesTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.profitbricks.util;\n\nimport com.google.common.collect.ImmutableList;\nimport java.util.List;\nimport static org.jclouds.profitbricks.util.MacAddresses.isMacAddress;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"MacAddressesTest\")\npublic class MacAddressesTest {\n\n   private final List<String> expectedValidAddresses = ImmutableList.of(\n           \"aa:bb:cc:dd:ee:ff\", \"11:22:33:44:55:66\"\n   );\n   private final List<String> expectedInvalidAddresses = ImmutableList.of(\n           \"AA:BB:CC:DD:EE:FF\", \"aa-bb-cc-dd-ee-ff\", \"\", \"aabbccddeeff\",\n           \"aa:bb:cc:dd:ff\", \"gg:aa:bb:cc:dd:ee\"\n   );\n\n   @Test\n   public void testIsMacAddress() {\n      for (String addr : expectedValidAddresses)\n         assertTrue(isMacAddress(addr));\n\n      for (String addr : expectedInvalidAddresses)\n         assertFalse(isMacAddress(addr));\n   }\n}\n"
  },
  {
    "path": "providers/profitbricks/src/test/resources/datacenter/datacenter-cleared.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:clearDataCenterResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>\n                <requestId>1143191</requestId>\n                <dataCenterId>aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee</dataCenterId>\n                <dataCenterVersion>3</dataCenterVersion>\n            </return>\n        </ns2:clearDataCenterResponse>\n    </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/datacenter/datacenter-created.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ws=\"http://ws.api.profitbricks.com/\">\n    <soapenv:Body>\n        <ws:createDataCenterResponse>\n            <return>\n                <requestId>102456</requestId>\n                <dataCenterId>aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee</dataCenterId>\n                <dataCenterVersion>1</dataCenterVersion>\n                <location>de/fra</location>\n            </return>\n        </ws:createDataCenterResponse>\n    </soapenv:Body>\n</soapenv:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/datacenter/datacenter-deleted.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:deleteDataCenterResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>\n                <requestId>11411363</requestId>\n            </return>\n        </ns2:deleteDataCenterResponse>\n    </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/datacenter/datacenter-not-found.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <S:Fault xmlns:ns4=\"http://www.w3.org/2003/05/soap-envelope\">\n            <faultcode>S:Server</faultcode>\n            <faultstring>The requested resource could not be found. Please refer to Request Id : 11122416. [VDC-6-404] The requested data center does not exist or already deleted by the users. ResourceId ﻿random-non-existing-id</faultstring>\n            <detail>\n                <ns2:ProfitbricksServiceFault xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n                    <faultCode>RESOURCE_NOT_FOUND</faultCode>\n                    <httpCode>404</httpCode>\n                    <message>The requested resource could not be found. Please refer to Request Id : 11122416. [VDC-6-404] The requested data center does not exist or already deleted by the users. ResourceId ﻿random-non-existing-id</message>\n                    <requestId>11122416</requestId>\n                </ns2:ProfitbricksServiceFault>\n            </detail>\n        </S:Fault>\n    </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/datacenter/datacenter-state-inprocess.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:getDataCenterStateResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>INPROCESS</return>\n        </ns2:getDataCenterStateResponse>\n    </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/datacenter/datacenter-state.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:getDataCenterStateResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>AVAILABLE</return>\n        </ns2:getDataCenterStateResponse>\n    </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/datacenter/datacenter-updated.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:updateDataCenterResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>\n                <requestId>1143190</requestId>\n                <dataCenterId>aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee</dataCenterId>\n                <dataCenterVersion>2</dataCenterVersion>\n            </return>\n        </ns2:updateDataCenterResponse>\n    </S:Body>\n</S:Envelope>\n"
  },
  {
    "path": "providers/profitbricks/src/test/resources/datacenter/datacenter.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:getDataCenterResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>\n                <requestId>10933055</requestId>\n                <dataCenterId>12345678-abcd-efgh-ijkl-987654321000</dataCenterId>\n                <dataCenterVersion>10</dataCenterVersion>\n                <dataCenterName>JClouds-DC</dataCenterName>\n                <servers>\n                    <dataCenterId>12345678-abcd-efgh-ijkl-987654321000</dataCenterId>\n                    <dataCenterVersion>10</dataCenterVersion>\n                    <serverId>qqqqqqqq-wwww-eeee-rrrr-tttttttttttt</serverId>\n                    <serverName>jnode1</serverName>\n                    <cores>4</cores>\n                    <ram>4096</ram>\n                    <internetAccess>true</internetAccess>\n                    <ips>202.94.38.12</ips>\n                    <connectedStorages>\n                        <bootDevice>true</bootDevice>\n                        <busType>VIRTIO</busType>\n                        <deviceNumber>1</deviceNumber>\n                        <size>40</size>\n                        <storageId>ssssssss-aaaa-ffff-gggg-hhhhhhhhhhhh</storageId>\n                        <storageName>jnode1-disk1</storageName>\n                    </connectedStorages>\n                    <nics>\n                        <dataCenterId>12345678-abcd-efgh-ijkl-987654321000</dataCenterId>\n                        <dataCenterVersion>10</dataCenterVersion>\n                        <nicId>zzzzzzzz-xxxx-cccc-vvvv-bbbbbbbbbbbb</nicId>\n                        <lanId>1</lanId>\n                        <internetAccess>true</internetAccess>\n                        <serverId>qqqqqqqq-wwww-eeee-rrrr-tttttttttttt</serverId>\n                        <ips>202.94.38.12</ips>\n                        <macAddress>02:01:09:cd:f0:b0</macAddress>\n                        <firewall>\n                            <active>false</active>\n                            <firewallId>llllllll-kkkk-jjjj-hhhh-gggggggggggg</firewallId>\n                            <nicId>zzzzzzzz-xxxx-cccc-vvvv-bbbbbbbbbbbb</nicId>\n                            <provisioningState>AVAILABLE</provisioningState>\n                        </firewall>\n                        <dhcpActive>true</dhcpActive>\n                        <gatewayIp>202.94.38.1</gatewayIp>\n                        <provisioningState>AVAILABLE</provisioningState>\n                    </nics>\n                    <provisioningState>AVAILABLE</provisioningState>\n                    <virtualMachineState>RUNNING</virtualMachineState>\n                    <creationTime>2014-12-04T07:09:23.138Z</creationTime>\n                    <lastModificationTime>2014-12-12T03:08:35.629Z</lastModificationTime>\n                    <osType>LINUX</osType>\n                    <availabilityZone>AUTO</availabilityZone>\n                    <cpuHotPlug>true</cpuHotPlug>\n                    <ramHotPlug>true</ramHotPlug>\n                    <nicHotPlug>true</nicHotPlug>\n                    <nicHotUnPlug>true</nicHotUnPlug>\n                    <discVirtioHotPlug>true</discVirtioHotPlug>\n                    <discVirtioHotUnPlug>true</discVirtioHotUnPlug>\n                </servers>\n                <storages>\n                    <dataCenterId>12345678-abcd-efgh-ijkl-987654321000</dataCenterId>\n                    <dataCenterVersion>10</dataCenterVersion>\n                    <storageId>ssssssss-aaaa-ffff-gggg-hhhhhhhhhhhh</storageId>\n                    <size>40</size>\n                    <storageName>jnode1-disk1</storageName>\n                    <mountImage>\n                        <imageId>f0a59a5c-7940-11e4-8053-52540066fee9</imageId>\n                        <imageName>Ubuntu-14.04-LTS-server-2014-12-01</imageName>\n                    </mountImage>\n                    <serverIds>qqqqqqqq-wwww-eeee-rrrr-tttttttttttt</serverIds>\n                    <provisioningState>AVAILABLE</provisioningState>\n                    <creationTime>2014-12-04T07:09:23.138Z</creationTime>\n                    <lastModificationTime>2014-12-12T03:14:48.316Z</lastModificationTime>\n                </storages>\n                <provisioningState>AVAILABLE</provisioningState>\n                <location>us/las</location>\n            </return>\n        </ns2:getDataCenterResponse>\n    </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/datacenter/datacenters.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:getAllDataCentersResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>\n                <dataCenterId>aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee</dataCenterId>\n                <dataCenterName>JClouds-DC</dataCenterName>\n                <dataCenterVersion>10</dataCenterVersion>\n                <provisioningState>AVAILABLE</provisioningState>\n            </return>\n            <return>\n                <dataCenterId>qqqqqqqq-wwww-rrrr-tttt-yyyyyyyyyyyy</dataCenterId>\n                <dataCenterName>Random DC</dataCenterName>\n                <dataCenterVersion>238</dataCenterVersion>\n                <provisioningState>INPROCESS</provisioningState>\n            </return>\n        </ns2:getAllDataCentersResponse>\n    </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/drives/drives-add.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:addRomDriveToServerResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>\n                <requestId>request-id</requestId>\n                <dataCenterId>datacenter-id</dataCenterId>\n                <dataCenterVersion>datacenter-version</dataCenterVersion>\n            </return>\n        </ns2:addRomDriveToServerResponse>\n    </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/drives/drives-remove.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:removeRomDriveFromServerResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>\n                <requestId>request-id</requestId>\n                <dataCenterId>datacenter-id</dataCenterId>\n                <dataCenterVersion>datacenter-version</dataCenterVersion>\n            </return>\n        </ns2:removeRomDriveFromServerResponse>\n    </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/fault-400.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <S:Fault xmlns:ns4=\"http://www.w3.org/2003/05/soap-envelope\">\n            <faultcode>S:Server</faultcode>\n            <faultstring>RAM of requested server too small, 256 Mb is minimum</faultstring>\n            <detail>\n                <ns2:ProfitbricksServiceFault xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n                    <faultCode>BAD_REQUEST</faultCode>\n                    <httpCode>400</httpCode>\n                    <message>RAM of requested server too small, 256 Mb is minimum</message>\n                    <requestId>1045</requestId>\n                </ns2:ProfitbricksServiceFault>\n            </detail>\n        </S:Fault>\n    </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/fault-404.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <S:Fault xmlns:ns4=\"http://www.w3.org/2003/05/soap-envelope\">\n            <faultcode>S:Server</faultcode>\n            <faultstring>The requested resource could not be found. Please refer to Request Id : 16370720. [VDC-6-404] The requested resource does not exist or already deleted by the users. ResourceId ﻿random-non-existing-id</faultstring>\n            <detail>\n                <ns2:ProfitbricksServiceFault xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n                    <faultCode>RESOURCE_NOT_FOUND</faultCode>\n                    <httpCode>404</httpCode>\n                    <message>The requested resource could not be found. Please refer to Request Id : 16370720. [VDC-6-404] The requested resource does not exist or already deleted by the users. ResourceId ﻿random-non-existing-id</message>\n                    <requestId>16370720</requestId>\n                </ns2:ProfitbricksServiceFault>\n            </detail>\n        </S:Fault>\n    </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/fault-413.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <S:Fault xmlns:ns4=\"http://www.w3.org/2003/05/soap-envelope\">\n            <faultcode>S:Server</faultcode>\n            <faultstring>New request exceeds the current capacity settings of this user contract.  Please refer to Request Id : 16503940. [VDC-5-1020] Server  has 12,800 MiB configured RAM. Your personal limit is 10,240 MiB per server.</faultstring>\n            <detail>\n                <ns2:ProfitbricksServiceFault xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n                    <faultCode>OVER_LIMIT_SETTING</faultCode>\n                    <httpCode>413</httpCode>\n                    <message>New request exceeds the current capacity settings of this user contract.  Please refer to Request Id : 16503940. [VDC-5-1020] Server  has 12,800 MiB configured RAM. Your personal limit is 10,240 MiB per server.</message>\n                    <requestId>16503940</requestId>\n                </ns2:ProfitbricksServiceFault>\n            </detail>\n        </S:Fault>\n    </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/fault-500.xml",
    "content": "<?xml version='1.0' encoding='UTF-8'?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <S:Fault xmlns:ns4=\"http://www.w3.org/2003/05/soap-envelope\">\n            <faultcode>S:Server</faultcode>\n            <faultstring>javax.ejb.EJBException</faultstring>\n        </S:Fault>\n    </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/firewall/firewall-activate.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:activateFirewallsResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>\n                <requestId>request-id</requestId>\n                <dataCenterId>datacenter-id</dataCenterId>\n                <dataCenterVersion>datacenter-version</dataCenterVersion>\n            </return>\n        </ns2:activateFirewallsResponse>\n    </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/firewall/firewall-addtonic.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:addFirewallRulesToNicResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>\n                <active>active</active>\n                <firewallId>firewall-id</firewallId>\n                <firewallRules>\n                    <firewallRuleId>firewall-rule-id</firewallRuleId>\n                    <name>name</name>\n                    <portRangeEnd>45678</portRangeEnd>\n                    <portRangeStart>12345</portRangeStart>\n                    <protocol>TCP</protocol>\n                    <sourceIp>192.168.0.1</sourceIp>\n                    <sourceMac>aa:bb:cc:dd:ee:ff</sourceMac>\n                    <targetIp>192.168.0.2</targetIp>\n                </firewallRules>\n                <nicId>nic-id</nicId>\n                <provisioningState>AVAILABLE</provisioningState>\n            </return>\n        </ns2:addFirewallRulesToNicResponse>\n    </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/firewall/firewall-deactivate.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:deactivateFirewallsResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>\n                <requestId>request-id1111</requestId>\n                <dataCenterId>datacenter-id</dataCenterId>\n                <dataCenterVersion>datacenter-version</dataCenterVersion>\n            </return>\n        </ns2:deactivateFirewallsResponse>\n    </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/firewall/firewall-delete.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:deleteFirewallsResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>\n                <requestId>request-id</requestId>\n                <dataCenterId>datacenter-id</dataCenterId>\n                <dataCenterVersion>datacenter-version</dataCenterVersion>\n            </return>\n        </ns2:deleteFirewallsResponse>\n    </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/firewall/firewall-remove.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:removeFirewallRulesResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>\n                <requestId>request-id</requestId>\n                <dataCenterId>datacenter-id</dataCenterId>\n                <dataCenterVersion>datacenter-version</dataCenterVersion>\n            </return>\n        </ns2:removeFirewallRulesResponse>\n    </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/firewall/firewall.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:getFirewallResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>\n                <active>true</active>\n                <firewallId>firewall-id</firewallId>\n                <firewallRules>\n                    <firewallRuleId>firewall-rule-id</firewallRuleId>\n                    <name>name</name>\n                    <portRangeEnd>45678</portRangeEnd>\n                    <portRangeStart>12345</portRangeStart>\n                    <protocol>TCP</protocol>\n                    <sourceIp>192.168.0.1</sourceIp>\n                    <sourceMac>aa:bb:cc:dd:ee:ff</sourceMac>\n                    <targetIp>192.168.0.2</targetIp>\n                </firewallRules>\n                <nicId>nic-id</nicId>\n                <provisioningState>AVAILABLE</provisioningState>\n            </return>\n        </ns2:getFirewallResponse>\n    </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/firewall/firewalls.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:getFirewallResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>\n                <active>true</active>\n                <firewallId>firewall-id</firewallId>\n                <firewallRules>\n                    <firewallRuleId>firewall-rule-id</firewallRuleId>\n                    <name>name</name>\n                    <portRangeEnd>45678</portRangeEnd>\n                    <portRangeStart>12345</portRangeStart>\n                    <protocol>TCP</protocol>\n                    <sourceIp>192.168.0.1</sourceIp>\n                    <sourceMac>aa:bb:cc:dd:ee:ff</sourceMac>\n                    <targetIp>192.168.0.2</targetIp>\n                </firewallRules>\n                <nicId>nic-id</nicId>\n                <provisioningState>AVAILABLE</provisioningState>\n            </return>\n            <return>\n                <active>true</active>\n                <firewallId>firewall-id2</firewallId>\n                <firewallRules>\n                    <firewallRuleId>firewall-rule-id2</firewallRuleId>\n                    <name>name</name>\n                    <portRangeEnd>56789</portRangeEnd>\n                    <portRangeStart>23456</portRangeStart>\n                    <protocol>TCP</protocol>\n                    <sourceIp>192.168.0.2</sourceIp>\n                    <sourceMac>aa:bb:cc:dd:ee:ff</sourceMac>\n                    <targetIp>192.168.0.3</targetIp>\n                </firewallRules>\n                <nicId>nic-id</nicId>\n                <provisioningState>AVAILABLE</provisioningState>\n            </return>\n        </ns2:getFirewallResponse>\n    </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/html/fault-401.html",
    "content": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n    <head>\n        <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" lang=\"en\"/>\n        <title>Profitbricks | 401 Unauthorized</title>\n        <base href=\"/\"/>\n        <link rel=\"stylesheet\" type=\"text/css\" href=\"css/style.css\"/>\n        <link rel=\"stylesheet\" type=\"text/css\" href=\"css/content.css\"/>\n        <link rel=\"stylesheet\" type=\"text/css\" href=\"css/recent_additions.css\"/>\n        <link rel=\"shortcut icon\" href=\"favicon.ico\" type=\"image/x-icon\"/>\n    </head>\n    <body>\n        <div class=\"head1 h_bg\"/>\n        <div class=\"head2 h_bg\"/>\n        <div class=\"head3 h_bg\"/>\n        <div id=\"wrapper\">\n            <div class=\"wrapper_inner\">\n                <div id=\"header\">\n                    <a id=\"logo\" href=\"#\">\n                        <img alt=\"Profitbricks\" src=\"img/logo.png\"/>\n                    </a>\n                </div>\n                <div id=\"main\">\n                    <div id=\"right\" style=\"min-height: 550px;\">\n                        <div class=\"article msg\">\n                            <h1>Unauthorized</h1>\n                            <img title=\"\" alt=\"message error\" src=\"img/msg_error.png\" class=\"msg_sign\" style=\"margin: 10px;\" height=\"49\" width=\"49\"/>\n                            <div class=\"container\" style=\"margin:20px 80px !important;\">\n                                <p class=\"bigmargin\">This request requires authentication.</p>\n                            </div>\n                        </div>\n                    </div>\n                    <br class=\"clear\"/>\n                </div>\n            </div>\n        </div>\n        <div id=\"footer\">\n            <div class=\"bottom\">\n                <div class=\"inner\"></div>\n            </div>\n        </div>\n    </body>\n</html>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/html/maintenance-503.html",
    "content": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n    <head>\n        <meta lang=\"en\" http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n        <title>Profitbricks | Maintenance</title>\n        <link rel=\"stylesheet\" type=\"text/css\" href=\"css/style.css\" />\n        <link rel=\"stylesheet\" type=\"text/css\" href=\"css/content.css\" />\n        <link rel=\"stylesheet\" type=\"text/css\" href=\"css/recent_additions.css\" />\n        <link rel=\"shortcut icon\" href=\"https://my.profitbricks.com/errorpages/favicon.ico\" type=\"image/x-icon\" />\n    </head>\n\n    <body>\n        <div class=\"head1 h_bg\"></div>\n        <div class=\"head2 h_bg\"></div>\n        <div class=\"head3 h_bg\"></div>\n\n        <div id=\"wrapper\">\n            <div class=\"wrapper_inner\">\n\n                <div id=\"header\">\n                    <a id=\"logo\" href=\"#\"><img alt=\"Profitbricks\" src=\"img/logo.png\" /></a>\n                </div>\n\n                <div id=\"main\">\n                    <div id=\"right\" style=\"min-height: 550px;\">\n                        <div class=\"article msg\">\n                            <h1>Maintenance</h1>\n                            <img width=\"49\" height=\"49\" title=\"\" alt=\"message error\" src=\"Profitbricks%20%7C%20Maintenance_files/msg_error.png\" class=\"msg_sign\" style=\"margin: 10px;\" />\n                            <div class=\"container\" style=\"margin:20px 80px !important;\">\n                                <div class=\"bigmargin\">\n                                    <h2>Dear ProfitBricks users,</h2>\n                                    <p>actually we are carrying out maintenance work right now.</p>\n                                    <p>For urgent matters please contact:<br /><a href=\"mailto:support@profitbricks.com\">support@profitbricks.com</a>.</p>\n                                    <br />\n                                    <p>We ask for your understanding and your patience.</p>\n                                    <p>Your ProfitBricks Team</p>\n                                </div>\n\n                                <div class=\"bigmargin\">\n                                    <h2>Sehr geehrte(r) ProfitBricks Nutzerin/Nutzer,</h2>\n                                    <p>zur Zeit führen wir Wartungsarbeiten durch.</p>\n                                    <p>Bei dringenden Angelegenheiten wenden Sie sich bitte an:<br />\n                                        <a href=\"mailto:support@profitbricks.com\">support@profitbricks.com</a>\n                                    </p>\n                                    <br />\n                                    <p>Wir bitten Sie um Ihr Verständnis und um etwas Geduld.</p>\n                                    <p>Ihr ProfitBricks Team</p>\n                                </div>\n\n                            </div>\n                        </div>\n                    </div>\n                    <br class=\"clear\" />\n                </div>\n\n            </div>\n        </div>\n\n        <div id=\"footer\">\n            <div class=\"bottom\">\n                <div class=\"inner\">\n                </div>\n            </div>\n        </div>\n\n    </body>\n</html>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/image/image-not-found.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <S:Fault xmlns:ns4=\"http://www.w3.org/2003/05/soap-envelope\">\n            <faultcode>S:Server</faultcode>\n            <faultstring>The requested resource could not be found. Please refer to Request Id : 16361390. [VDC-6-404] The requested image does not exist or already deleted by the users. ResourceId ﻿random-non-existing-id</faultstring>\n            <detail>\n                <ns2:ProfitbricksServiceFault xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n                    <faultCode>RESOURCE_NOT_FOUND</faultCode>\n                    <httpCode>404</httpCode>\n                    <message>The requested resource could not be found. Please refer to Request Id : 16361390. [VDC-6-404] The requested image does not exist or already deleted by the users. ResourceId ﻿random-non-existing-id</message>\n                    <requestId>16361390</requestId>\n                </ns2:ProfitbricksServiceFault>\n            </detail>\n        </S:Fault>\n    </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/image/image.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:getImageResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>\n                <bootable>true</bootable>\n                <cpuHotPlug>true</cpuHotPlug>\n                <cpuHotUnPlug>false</cpuHotUnPlug>\n                <discVirtioHotPlug>true</discVirtioHotPlug>\n                <discVirtioHotUnPlug>true</discVirtioHotUnPlug>\n                <imageId>5ad99c9e-9166-11e4-9d74-52540066fee9</imageId>\n                <imageName>Ubuntu-14.04-LTS-server-2015-01-01</imageName>\n                <imageSize>2048</imageSize>\n                <imageType>HDD</imageType>\n                <location>us/las</location>\n                <nicHotPlug>true</nicHotPlug>\n                <nicHotUnPlug>true</nicHotUnPlug>\n                <osType>LINUX</osType>\n                <public>true</public>\n                <ramHotPlug>true</ramHotPlug>\n                <ramHotUnPlug>false</ramHotUnPlug>\n                <writeable>true</writeable>\n            </return>\n        </ns2:getImageResponse>\n    </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/image/images.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:getAllImagesResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>\n                <bootable>true</bootable>\n                <cpuHotPlug>true</cpuHotPlug>\n                <cpuHotUnPlug>false</cpuHotUnPlug>\n                <discVirtioHotPlug>true</discVirtioHotPlug>\n                <discVirtioHotUnPlug>true</discVirtioHotUnPlug>\n                <imageId>e4f73936-9161-11e4-9d74-52540066fee9</imageId>\n                <imageName>Ubuntu-12.04-LTS-server-2015-01-01</imageName>\n                <imageSize>2048</imageSize>\n                <imageType>HDD</imageType>\n                <location>de/fra</location>\n                <nicHotPlug>true</nicHotPlug>\n                <nicHotUnPlug>true</nicHotUnPlug>\n                <osType>LINUX</osType>\n                <public>true</public>\n                <ramHotPlug>true</ramHotPlug>\n                <ramHotUnPlug>false</ramHotUnPlug>\n                <writeable>true</writeable>\n            </return>\n            <return>\n                <bootable>true</bootable>\n                <cpuHotPlug>true</cpuHotPlug>\n                <cpuHotUnPlug>false</cpuHotUnPlug>\n                <discVirtioHotPlug>true</discVirtioHotPlug>\n                <discVirtioHotUnPlug>true</discVirtioHotUnPlug>\n                <imageId>a984a5d3-9163-11e4-9d74-52540066fee9</imageId>\n                <imageName>Ubuntu-14.04-LTS-server-2015-01-01</imageName>\n                <imageSize>2048</imageSize>\n                <imageType>HDD</imageType>\n                <location>de/fra</location>\n                <nicHotPlug>true</nicHotPlug>\n                <nicHotUnPlug>true</nicHotUnPlug>\n                <osType>LINUX</osType>\n                <public>true</public>\n                <ramHotPlug>true</ramHotPlug>\n                <ramHotUnPlug>false</ramHotUnPlug>\n                <writeable>true</writeable>\n            </return>\n            <return>\n                <bootable>true</bootable>\n                <cpuHotPlug>true</cpuHotPlug>\n                <cpuHotUnPlug>false</cpuHotUnPlug>\n                <discVirtioHotPlug>true</discVirtioHotPlug>\n                <discVirtioHotUnPlug>true</discVirtioHotUnPlug>\n                <imageId>5f3cac96-915f-11e4-9d74-52540066fee9</imageId>\n                <imageName>Debian-jessie-prerelease-server-2015-01-01</imageName>\n                <imageSize>2048</imageSize>\n                <imageType>HDD</imageType>\n                <location>us/lasdev</location>\n                <nicHotPlug>true</nicHotPlug>\n                <nicHotUnPlug>true</nicHotUnPlug>\n                <osType>LINUX</osType>\n                <public>true</public>\n                <ramHotPlug>true</ramHotPlug>\n                <ramHotUnPlug>false</ramHotUnPlug>\n                <writeable>true</writeable>\n            </return>\n            <return>\n                <bootable>true</bootable>\n                <cpuHotPlug>true</cpuHotPlug>\n                <cpuHotUnPlug>false</cpuHotUnPlug>\n                <discVirtioHotPlug>true</discVirtioHotPlug>\n                <discVirtioHotUnPlug>true</discVirtioHotUnPlug>\n                <imageId>f4742db0-9160-11e4-9d74-52540066fee9</imageId>\n                <imageName>Fedora-19-server-2015-01-01</imageName>\n                <imageSize>2048</imageSize>\n                <imageType>HDD</imageType>\n                <location>us/lasdev</location>\n                <nicHotPlug>true</nicHotPlug>\n                <nicHotUnPlug>true</nicHotUnPlug>\n                <osType>LINUX</osType>\n                <public>true</public>\n                <ramHotPlug>true</ramHotPlug>\n                <ramHotUnPlug>false</ramHotUnPlug>\n                <writeable>true</writeable>\n            </return>\n            <return>\n                <bootable>true</bootable>\n                <cpuHotPlug>true</cpuHotPlug>\n                <cpuHotUnPlug>false</cpuHotUnPlug>\n                <discVirtioHotPlug>true</discVirtioHotPlug>\n                <discVirtioHotUnPlug>true</discVirtioHotUnPlug>\n                <imageId>86902c18-9164-11e4-9d74-52540066fee9</imageId>\n                <imageName>Ubuntu-12.04-LTS-server-2015-01-01</imageName>\n                <imageSize>2048</imageSize>\n                <imageType>HDD</imageType>\n                <location>us/lasdev</location>\n                <nicHotPlug>true</nicHotPlug>\n                <nicHotUnPlug>true</nicHotUnPlug>\n                <osType>LINUX</osType>\n                <public>true</public>\n                <ramHotPlug>true</ramHotPlug>\n                <ramHotUnPlug>false</ramHotUnPlug>\n                <writeable>true</writeable>\n            </return>\n            <return>\n                <bootable>true</bootable>\n                <cpuHotPlug>true</cpuHotPlug>\n                <cpuHotUnPlug>false</cpuHotUnPlug>\n                <discVirtioHotPlug>true</discVirtioHotPlug>\n                <discVirtioHotUnPlug>true</discVirtioHotUnPlug>\n                <imageId>3b48e3ff-9163-11e4-9d74-52540066fee9</imageId>\n                <imageName>Ubuntu-14.04-LTS-server-2015-01-01</imageName>\n                <imageSize>2048</imageSize>\n                <imageType>HDD</imageType>\n                <location>de/fkb</location>\n                <nicHotPlug>true</nicHotPlug>\n                <nicHotUnPlug>true</nicHotUnPlug>\n                <osType>LINUX</osType>\n                <public>true</public>\n                <ramHotPlug>true</ramHotPlug>\n                <ramHotUnPlug>false</ramHotUnPlug>\n                <writeable>true</writeable>\n            </return>\n            <return>\n                <bootable>true</bootable>\n                <cpuHotPlug>true</cpuHotPlug>\n                <cpuHotUnPlug>false</cpuHotUnPlug>\n                <discVirtioHotPlug>true</discVirtioHotPlug>\n                <discVirtioHotUnPlug>true</discVirtioHotUnPlug>\n                <imageId>6ce17716-9164-11e4-9d74-52540066fee9</imageId>\n                <imageName>Ubuntu-12.04-LTS-server-2015-01-01</imageName>\n                <imageSize>2048</imageSize>\n                <imageType>HDD</imageType>\n                <location>us/las</location>\n                <nicHotPlug>true</nicHotPlug>\n                <nicHotUnPlug>true</nicHotUnPlug>\n                <osType>LINUX</osType>\n                <public>true</public>\n                <ramHotPlug>true</ramHotPlug>\n                <ramHotUnPlug>false</ramHotUnPlug>\n                <writeable>true</writeable>\n            </return>\n        </ns2:getAllImagesResponse>\n    </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/ipblock/ipblock-addtonic.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:addPublicIpToNicResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>\n                <requestId>request-id</requestId>\n                <dataCenterId>datacenter-id</dataCenterId>\n                <dataCenterVersion>datacenter-version</dataCenterVersion>\n            </return>\n        </ns2:addPublicIpToNicResponse>\n    </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/ipblock/ipblock-release.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:releasePublicIpBlockResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>\n                <requestId>request-id</requestId>\n            </return>\n        </ns2:releasePublicIpBlockResponse>\n    </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/ipblock/ipblock-removefromnic.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:addPublicIpToNicResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>\n                <requestId>request-id</requestId>\n                <dataCenterId>datacenter-id</dataCenterId>\n                <dataCenterVersion>datacenter-version</dataCenterVersion>\n            </return>\n        </ns2:addPublicIpToNicResponse>\n    </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/ipblock/ipblock-reserve.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:reservePublicIpBlockResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>\n                <requestId>request-id</requestId>\n                <blockId>block-id</blockId>\n                <location>us/las</location>\n                <ips>10.0.0.1</ips>\n            </return>\n        </ns2:reservePublicIpBlockResponse>\n    </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/ipblock/ipblock.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:getAllPublicIpBlocksResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>\n                <blockId>qwertyui-qwer-qwer-qwer-qwertyyuiiop</blockId>\n                <location>us/las</location>\n                <publicIps>\n                    <ip>10.0.0.2</ip>\n                    <nicId>nic-id</nicId>\n                </publicIps>\n                <publicIps>\n                    <ip>10.0.0.3</ip>\n                </publicIps>\n            </return>\n        </ns2:getAllPublicIpBlocksResponse>\n    </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/ipblock/ipblocks.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:getAllPublicIpBlocksResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>\n                <blockId>block-id-1</blockId>\n                <location>us/las</location>\n                <publicIps>\n                    <ip>10.0.0.2</ip>\n                    <nicId>nic-id-1</nicId>      \n                </publicIps>\n                <publicIps>\n                    <ip>10.0.0.3</ip>\n                    <nicId>nic-id-2</nicId>\n                </publicIps>\n            </return>\n            <return>\n                <blockId>block-id-2</blockId>\n                <location>us/las</location>\n                <publicIps>\n                    <ip>10.0.0.4</ip>\n                </publicIps>\n                <publicIps>\n                    <ip>10.0.0.5</ip>\n                    <nicId>nic-id-4</nicId>\n                </publicIps>\n            </return>\n        </ns2:getAllPublicIpBlocksResponse>\n    </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/loadbalancer/loadbalancer-create.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:createLoadBalancerResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>\n                <requestId>request-id</requestId>\n                <dataCenterId>aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee</dataCenterId>\n                <dataCenterVersion>10</dataCenterVersion>\n                <loadBalancerId>1234-1234-1234-1234</loadBalancerId>\n            </return>\n        </ns2:createLoadBalancerResponse>\n    </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/loadbalancer/loadbalancer-delete.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:deleteLoadBalancerResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>\n                <requestId>request-id</requestId>\n                <dataCenterId>datacenter-id</dataCenterId>\n                <dataCenterVersion>123</dataCenterVersion>\n            </return>\n        </ns2:deleteLoadBalancerResponse>\n    </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/loadbalancer/loadbalancer-deregister.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:deregisterServersOnLoadBalancerResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>\n                <requestId>request-id</requestId>\n                <dataCenterId>datacenter-id</dataCenterId>\n                <dataCenterVersion>10</dataCenterVersion>\n            </return>\n        </ns2:deregisterServersOnLoadBalancerResponse>\n    </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/loadbalancer/loadbalancer-register.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n  <S:Body>\n    <ns2:registerServersOnLoadBalancerResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n      <return>\n        <dataCenterId>datacenter-id</dataCenterId>\n        <dataCenterVersion>4</dataCenterVersion>\n        <loadBalancerId>load-balancer-id</loadBalancerId>\n        <lanId>1</lanId>\n        <balancedServers>\n          <activate>true</activate>\n          <balancedNicId>balanced-nic-id</balancedNicId>\n          <serverId>server-id</serverId>\n          <serverName>server-name</serverName>\n        </balancedServers>\n      </return>\n    </ns2:registerServersOnLoadBalancerResponse>\n  </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/loadbalancer/loadbalancer-update.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:updateLoadBalancerResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>\n                <requestId>request-id</requestId>\n                <dataCenterId>datacenter-id</dataCenterId>\n                <dataCenterVersion>10</dataCenterVersion>\n            </return>\n        </ns2:updateLoadBalancerResponse>\n    </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/loadbalancer/loadbalancer.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:getLoadBalancerResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>\n                <dataCenterId>datacenter-id</dataCenterId>\n                <dataCenterVersion>4</dataCenterVersion>\n                <loadBalancerId>aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee</loadBalancerId>\n                <loadBalancerName>load-balancer-name</loadBalancerName>\n                <loadBalancerAlgorithm>ROUND_ROBIN</loadBalancerAlgorithm>\n                <internetAccess>true</internetAccess>\n                <ip>192.168.0.1</ip>\n                <lanId>2</lanId>\n                <balancedServers>\n                    <activate>true</activate>\n                    <balancedNicId>balanced-nic-id</balancedNicId>\n                    <serverId>server-id</serverId>\n                    <serverName>server-name</serverName>\n                </balancedServers>\n                <provisioningState>AVAILABLE</provisioningState>\n                <creationTime>2014-12-12T03:08:35.629Z</creationTime>\n                <lastModificationTime>2014-12-12T03:08:35.629Z</lastModificationTime>\n                <firewall>\n                    <active>false</active>\n                    <firewallId>firewall-id</firewallId>\n                    <nicId>nic-id</nicId>\n                    <provisioningState>AVAILABLE</provisioningState>\n                </firewall>\n            </return>\n        </ns2:getLoadBalancerResponse>\n    </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/loadbalancer/loadbalancers.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:getAllLoadBalancersResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>\n                <dataCenterId>datacenter-id</dataCenterId>\n                <dataCenterVersion>4</dataCenterVersion>\n                <loadBalancerId>aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee</loadBalancerId>\n                <loadBalancerName>load-1234567890-name</loadBalancerName>\n                <loadBalancerAlgorithm>ROUND_ROBIN</loadBalancerAlgorithm>\n                <internetAccess>true</internetAccess>\n                <ip>192.168.0.1</ip>\n                <lanId>1</lanId>\n                <balancedServers>\n                    <activate>true</activate>\n                    <balancedNicId>balanced-nic-id</balancedNicId>\n                    <serverId>server-id</serverId>\n                    <serverName>server-name</serverName>\n                </balancedServers>\n                <provisioningState>AVAILABLE</provisioningState>\n                <creationTime>2014-12-04T07:09:23.138Z</creationTime>\n                <lastModificationTime>2014-12-04T07:09:23.138Z</lastModificationTime>\n                <firewall>\n                    <active>false</active>\n                    <firewallId>firewall-id</firewallId>\n                    <nicId>nic-id</nicId>\n                    <provisioningState>AVAILABLE</provisioningState>\n                </firewall>\n            </return>\n            <return>\n                <dataCenterId>datacenter-id</dataCenterId>\n                <dataCenterVersion>4</dataCenterVersion>\n                <loadBalancerId>qqqqqqqq-wwww-rrrr-tttt-yyyyyyyyyyyy</loadBalancerId>\n                <loadBalancerName>load-balancer-name</loadBalancerName>\n                <loadBalancerAlgorithm>ROUND_ROBIN</loadBalancerAlgorithm>\n                <internetAccess>false</internetAccess>\n                <ip>192.168.0.1</ip>\n                <lanId>2</lanId>\n                <balancedServers>\n                    <activate>false</activate>\n                    <balancedNicId>balanced-nic-id</balancedNicId>\n                    <serverId>server-id</serverId>\n                    <serverName>server-name</serverName>\n                </balancedServers>\n                <provisioningState>AVAILABLE</provisioningState>\n                <creationTime>2014-12-04T07:09:23.138Z</creationTime>\n                <lastModificationTime>2014-12-04T07:09:23.138Z</lastModificationTime>\n                <firewall>\n                    <active>false</active>\n                    <firewallId>firewall-id</firewallId>\n                    <nicId>nic-id</nicId>\n                    <provisioningState>AVAILABLE</provisioningState>\n                </firewall>\n            </return>\n        </ns2:getAllLoadBalancersResponse>\n    </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/logback-test.xml",
    "content": "<?xml version=\"1.0\"?>\n<configuration scan=\"false\">\n    <appender name=\"STDOUT\" class=\"ch.qos.logback.core.ConsoleAppender\">\n        <encoder>\n            <pattern>%m%n</pattern>\n        </encoder>\n    </appender>\n\n    <appender name=\"FILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <appender name=\"WIREFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds-wire.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <appender name=\"COMPUTEFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds-compute.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <appender name=\"SSHFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds-ssh.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <root>\n        <level value=\"info\" />\n    </root>\n\n    <logger name=\"org.jclouds\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"FILE\" />\n    </logger>\n\n    <logger name=\"jclouds.compute\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"COMPUTEFILE\" />\n    </logger>\n\n    <logger name=\"jclouds.wire\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n\n    <logger name=\"jclouds.headers\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n\n    <logger name=\"jclouds.ssh\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"SSHFILE\" />\n    </logger>\n\n    <logger name=\"net.schmizz\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"SSHFILE\" />\n    </logger>\n</configuration>\n"
  },
  {
    "path": "providers/profitbricks/src/test/resources/nic/nic-create.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:createNicReturn xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>\n                <requestId>request-id</requestId>\n                <dataCenterId>datacenter-id</dataCenterId>\n                <dataCenterVersion>1</dataCenterVersion>\n                <nicId>nic-id</nicId>\n            </return>\n        </ns2:createNicReturn>\n    </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/nic/nic-delete.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n   <S:Body>\n      <ns2:deleteNicResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n         <return>\n            <requestId>request-id</requestId>\n            <dataCenterId>datacenter-id</dataCenterId>\n            <dataCenterVersion>datacenter-version</dataCenterVersion>\n         </return>\n      </ns2:deleteNicResponse>\n   </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/nic/nic-internetaccess.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:setInternetAccessResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>\n                <requestId>request-id</requestId>\n                <dataCenterId>datacenter-id</dataCenterId>\n                <dataCenterVersion>8</dataCenterVersion>\n            </return>\n        </ns2:setInternetAccessResponse>\n    </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/nic/nic-update.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n   <S:Body>\n      <ns2:updateNicResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n         <return>\n            <requestId>request-id</requestId>\n            <dataCenterId>datacenter-id</dataCenterId>\n            <dataCenterVersion>2</dataCenterVersion>\n         </return>\n      </ns2:updateNicResponse>\n   </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/nic/nic.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:getNicResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>\n                <nicId>12345678-abcd-efgh-ijkl-987654321000</nicId>\n                <dataCenterId>0</dataCenterId>\n                <dataCenterVersion>1</dataCenterVersion>\n                <lanId>1</lanId>\n                <nicName>name</nicName>\n                <internetAccess>true</internetAccess>\n                <serverId>server-id</serverId>\n                <ips>192.168.0.1</ips>\n                <macAddress>aa:bb:cc:dd:ee:ff</macAddress>\n                <firewall>\n                    <active>true</active>\n                    <firewallId>firewall-id</firewallId>\n                    <nicId>nic-id</nicId>\n                    <provisioningState>AVAILABLE</provisioningState>\n                </firewall>\n                <dhcpActive>true</dhcpActive>\n                <gatewayIp>10.0.0.1</gatewayIp>\n                <provisioningState>AVAILABLE</provisioningState>\n            </return>\n        </ns2:getNicResponse>\n    </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/nic/nics.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:getAllNicResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>\n                <dataCenterId>datacenter-id</dataCenterId>\n                <dataCenterVersion>12</dataCenterVersion>\n                <nicId>nic-id</nicId>\n                <nicName>nic-name</nicName>\n                <lanId>1</lanId>\n                <internetAccess>true</internetAccess>\n                <serverId>server-id</serverId>\n                <ips>192.168.0.1</ips>\n                <macAddress>aa:bb:cc:dd:ee:f1</macAddress>\n                <firewall>\n                    <active>true</active>\n                    <firewallId>firewall-id</firewallId>\n                    <nicId>nic-id</nicId>\n                    <provisioningState>AVAILABLE</provisioningState>\n                </firewall>\n                <dhcpActive>true</dhcpActive>\n                <gatewayIp>192.168.0.0</gatewayIp>\n                <provisioningState>AVAILABLE</provisioningState>\n            </return>\n            <return>\n                <dataCenterId>datacenter-id</dataCenterId>\n                <dataCenterVersion>21</dataCenterVersion>\n                <nicId>nic-id2</nicId>\n                <nicName>nick</nicName>\n                <lanId>1</lanId>\n                <internetAccess>false</internetAccess>\n                <serverId>server-id</serverId>\n                <ips>192.168.0.2</ips>\n                <ips>192.168.0.3</ips>\n                <ips>192.168.0.4</ips>\n                <macAddress>aa:bb:cc:dd:ee:f2</macAddress>\n                <firewall>\n                    <active>false</active>\n                    <firewallId>firewall-id2</firewallId>\n                    <nicId>nic-id</nicId>\n                    <provisioningState>AVAILABLE</provisioningState>\n                </firewall>\n                <dhcpActive>false</dhcpActive>\n                <gatewayIp>192.168.0.0</gatewayIp>\n                <provisioningState>AVAILABLE</provisioningState>\n            </return>\n        </ns2:getAllNicResponse>\n    </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/server/server-create.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ws=\"http://ws.api.profitbricks.com/\">\n    <soapenv:Header/>\n    <soapenv:Body>\n        <ws:createServerReturn>\n            <return>\n                <requestId>102457</requestId>\n                <dataCenterId>aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee</dataCenterId>\n                <dataCenterVersion>2</dataCenterVersion>\n                <serverId>qwertyui-qwer-qwer-qwer-qwertyyuiiop</serverId>\n            </return>\n        </ws:createServerReturn>\n    </soapenv:Body>\n</soapenv:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/server/server-delete.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ws=\"http://ws.api.profitbricks.com/\">\n    <soapenv:Header/>\n    <soapenv:Body>\n        <ws:deleteServerResponse>\n            <return>\n                <requestId>102459</requestId>\n                <dataCenterId>aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee</dataCenterId>\n                <dataCenterVersion>4</dataCenterVersion>\n            </return>\n        </ws:deleteServerResponse>\n    </soapenv:Body>\n</soapenv:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/server/server-reset.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ws=\"http://ws.api.profitbricks.com/\">\n    <soapenv:Header/>\n    <soapenv:Body>\n        <ws:resetServerResponse>\n            <return>\n                <requestId>123456</requestId>\n            </return>\n        </ws:resetServerResponse>\n    </soapenv:Body>\n</soapenv:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/server/server-start.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ws=\"http://ws.api.profitbricks.com/\">\n    <soapenv:Header/>\n    <soapenv:Body>\n        <ws:startServerResponse>\n            <return>\n                <requestId>123456</requestId>\n            </return>\n        </ws:startServerResponse>\n    </soapenv:Body>\n</soapenv:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/server/server-state-inprocess.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:getServerResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>\n                <requestId>16577212</requestId>\n                <dataCenterId>aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee</dataCenterId>\n                <dataCenterVersion>22</dataCenterVersion>\n                <serverId>qwertyui-qwer-qwer-qwer-qwertyyuiiop</serverId>\n                <cores>1</cores>\n                <ram>512</ram>\n                <internetAccess>false</internetAccess>\n                <provisioningState>INPROCESS</provisioningState>\n                <virtualMachineState>NOSTATE</virtualMachineState>\n                <creationTime>2015-01-29T00:37:49.096Z</creationTime>\n                <lastModificationTime>2015-01-29T00:37:49.096Z</lastModificationTime>\n                <osType>UNKNOWN</osType>\n                <availabilityZone>AUTO</availabilityZone>\n                <cpuHotPlug>false</cpuHotPlug>\n                <ramHotPlug>false</ramHotPlug>\n                <nicHotPlug>false</nicHotPlug>\n                <nicHotUnPlug>false</nicHotUnPlug>\n                <discVirtioHotPlug>false</discVirtioHotPlug>\n                <discVirtioHotUnPlug>false</discVirtioHotUnPlug>\n            </return>\n        </ns2:getServerResponse>\n    </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/server/server-stop.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ws=\"http://ws.api.profitbricks.com/\">\n    <soapenv:Header/>\n    <soapenv:Body>\n        <ws:stopServerResponse>\n            <return>\n                <requestId>123456</requestId>\n            </return>\n        </ws:stopServerResponse>\n    </soapenv:Body>\n</soapenv:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/server/server-update.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ws=\"http://ws.api.profitbricks.com/\">\n    <soapenv:Header/>\n    <soapenv:Body>\n        <ws:updateServerResponse>\n            <return>\n                <requestId>102458</requestId>\n                <dataCenterId>aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee</dataCenterId>\n                <dataCenterVersion>3</dataCenterVersion>\n            </return>\n        </ws:updateServerResponse>\n    </soapenv:Body>\n</soapenv:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/server/server.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:getServerResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>\n                <requestId>16366014</requestId>\n                <dataCenterId>aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee</dataCenterId>\n                <dataCenterVersion>10</dataCenterVersion>\n                <serverId>qwertyui-qwer-qwer-qwer-qwertyyuiiop</serverId>\n                <serverName>facebook-node</serverName>\n                <cores>4</cores>\n                <ram>4096</ram>\n                <internetAccess>true</internetAccess>\n                <ips>173.252.120.6</ips>\n                <balancedNicId>qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh</balancedNicId>\n                <activate>true</activate>\n                <connectedStorages>\n                    <bootDevice>true</bootDevice>\n                    <busType>VIRTIO</busType>\n                    <deviceNumber>1</deviceNumber>\n                    <size>40</size>\n                    <storageId>qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh</storageId>\n                    <storageName>facebook-storage</storageName>\n                </connectedStorages>\n                <nics>\n                    <dataCenterId>aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee</dataCenterId>\n                    <dataCenterVersion>10</dataCenterVersion>\n                    <nicId>qwqwqwqw-wewe-erer-rtrt-tytytytytyty</nicId>\n                    <lanId>1</lanId>\n                    <internetAccess>true</internetAccess>\n                    <serverId>qwertyui-qwer-qwer-qwer-qwertyyuiiop</serverId>\n                    <ips>173.252.120.6</ips>\n                    <macAddress>02:01:09:cd:f0:b0</macAddress>\n                    <firewall>\n                        <active>false</active>\n                        <firewallId>wqwqwqwq-ewew-rere-trtr-ytytytytytyt</firewallId>\n                        <nicId>qwqwqwqw-wewe-erer-rtrt-tytytytytyty</nicId>\n                        <provisioningState>AVAILABLE</provisioningState>\n                    </firewall>\n                    <dhcpActive>true</dhcpActive>\n                    <gatewayIp>173.252.120.1</gatewayIp>\n                    <provisioningState>AVAILABLE</provisioningState>\n                </nics>\n                <provisioningState>AVAILABLE</provisioningState>\n                <virtualMachineState>RUNNING</virtualMachineState>\n                <creationTime>2014-12-04T07:09:23.138Z</creationTime>\n                <lastModificationTime>2014-12-12T03:08:35.629Z</lastModificationTime>\n                <osType>LINUX</osType>\n                <availabilityZone>AUTO</availabilityZone>\n                <cpuHotPlug>true</cpuHotPlug>\n                <ramHotPlug>true</ramHotPlug>\n                <nicHotPlug>true</nicHotPlug>\n                <nicHotUnPlug>true</nicHotUnPlug>\n                <discVirtioHotPlug>true</discVirtioHotPlug>\n                <discVirtioHotUnPlug>true</discVirtioHotUnPlug>\n            </return>\n        </ns2:getServerResponse>\n    </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/server/servers.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:getAllServersResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>\n                <dataCenterId>aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee</dataCenterId>\n                <dataCenterVersion>10</dataCenterVersion>\n                <serverId>qwertyui-qwer-qwer-qwer-qwertyyuiiop</serverId>\n                <serverName>facebook-node</serverName>\n                <cores>4</cores>\n                <ram>4096</ram>\n                <internetAccess>true</internetAccess>\n                <ips>173.252.120.6</ips>\n                <balancedNicId>qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh</balancedNicId>\n                <activate>true</activate>\n                <connectedStorages>\n                    <bootDevice>true</bootDevice>\n                    <busType>VIRTIO</busType>\n                    <deviceNumber>1</deviceNumber>\n                    <size>40</size>\n                    <storageId>qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh</storageId>\n                    <storageName>facebook-storage</storageName>\n                </connectedStorages>\n                <nics>\n                    <dataCenterId>aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee</dataCenterId>\n                    <dataCenterVersion>10</dataCenterVersion>\n                    <nicId>qwqwqwqw-wewe-erer-rtrt-tytytytytyty</nicId>\n                    <lanId>1</lanId>\n                    <internetAccess>true</internetAccess>\n                    <serverId>qwertyui-qwer-qwer-qwer-qwertyyuiiop</serverId>\n                    <ips>173.252.120.6</ips>\n                    <macAddress>02:01:09:cd:f0:b0</macAddress>\n                    <firewall>\n                        <active>false</active>\n                        <firewallId>wqwqwqwq-ewew-rere-trtr-ytytytytytyt</firewallId>\n                        <nicId>qwqwqwqw-wewe-erer-rtrt-tytytytytyty</nicId>\n                        <provisioningState>AVAILABLE</provisioningState>\n                    </firewall>\n                    <dhcpActive>true</dhcpActive>\n                    <gatewayIp>173.252.120.1</gatewayIp>\n                    <provisioningState>AVAILABLE</provisioningState>\n                </nics>\n                <provisioningState>AVAILABLE</provisioningState>\n                <virtualMachineState>RUNNING</virtualMachineState>\n                <creationTime>2014-12-04T07:09:23.138Z</creationTime>\n                <lastModificationTime>2014-12-12T03:08:35.629Z</lastModificationTime>\n                <osType>LINUX</osType>\n                <availabilityZone>AUTO</availabilityZone>\n                <cpuHotPlug>true</cpuHotPlug>\n                <ramHotPlug>true</ramHotPlug>\n                <nicHotPlug>true</nicHotPlug>\n                <nicHotUnPlug>true</nicHotUnPlug>\n                <discVirtioHotPlug>true</discVirtioHotPlug>\n                <discVirtioHotUnPlug>true</discVirtioHotUnPlug>\n            </return>\n            <return>\n                <dataCenterId>qqqqqqqq-wwww-rrrr-tttt-yyyyyyyyyyyy</dataCenterId>\n                <dataCenterVersion>238</dataCenterVersion>\n                <serverId>asdfghjk-asdf-asdf-asdf-asdfghjklkjl</serverId>\n                <serverName>google-node</serverName>\n                <cores>1</cores>\n                <ram>1024</ram>\n                <internetAccess>false</internetAccess>\n                <ips>202.69.181.241</ips>\n                <balancedNicId>qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh</balancedNicId>\n                <activate>true</activate>\n                <connectedStorages>\n                    <bootDevice>true</bootDevice>\n                    <busType>VIRTIO</busType>\n                    <deviceNumber>1</deviceNumber>\n                    <size>5</size>\n                    <storageId>asfasfle-f23n-cu89-klfr-njkdsvwllkfa</storageId>\n                    <storageName>google-disk</storageName>\n                </connectedStorages>\n                <nics>\n                    <dataCenterId>qqqqqqqq-wwww-rrrr-tttt-yyyyyyyyyyyy</dataCenterId>\n                    <dataCenterVersion>238</dataCenterVersion>\n                    <nicId>mkl45h5e-sdgb-h6rh-235r-rfweshdfhreh</nicId>\n                    <lanId>3</lanId>\n                    <internetAccess>false</internetAccess>\n                    <serverId>asdfghjk-asdf-asdf-asdf-asdfghjklkjl</serverId>\n                    <ips>202.69.181.241</ips>\n                    <macAddress>02:01:9e:5e:35:1e</macAddress>\n                    <firewall>\n                        <active>false</active>\n                        <firewallId>cvvdsgbd-sdgj-eger-h56j-wet43gvsgeg4</firewallId>\n                        <nicId>mkl45h5e-sdgb-h6rh-235r-rfweshdfhreh</nicId>\n                        <provisioningState>INPROCESS</provisioningState>\n                    </firewall>\n                    <dhcpActive>false</dhcpActive>\n                    <gatewayIp>202.69.181.1</gatewayIp>\n                    <provisioningState>AVAILABLE</provisioningState>\n                </nics>\n                <provisioningState>AVAILABLE</provisioningState>\n                <virtualMachineState>RUNNING</virtualMachineState>\n                <creationTime>2014-11-12T07:01:00.441Z</creationTime>\n                <lastModificationTime>2014-11-12T07:01:00.441Z</lastModificationTime>\n                <osType>LINUX</osType>\n                <availabilityZone>AUTO</availabilityZone>\n                <cpuHotPlug>true</cpuHotPlug>\n                <ramHotPlug>true</ramHotPlug>\n                <nicHotPlug>true</nicHotPlug>\n                <nicHotUnPlug>true</nicHotUnPlug>\n                <discVirtioHotPlug>true</discVirtioHotPlug>\n                <discVirtioHotUnPlug>true</discVirtioHotUnPlug>\n            </return>\n        </ns2:getAllServersResponse>\n    </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/snapshot/snapshot-create.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:createSnapshotReturn xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>\n                <requestId>12345678</requestId>\n                <snapshotId>aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee</snapshotId>\n            </return>\n        </ns2:createSnapshotReturn>\n    </S:Body>\n</S:Envelope>\n"
  },
  {
    "path": "providers/profitbricks/src/test/resources/snapshot/snapshot-delete.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:deleteSnapshotResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>\n                <requestId>123456789</requestId>\n            </return>\n        </ns2:deleteSnapshotResponse>\n    </S:Body>\n</S:Envelope>\n"
  },
  {
    "path": "providers/profitbricks/src/test/resources/snapshot/snapshot-rollback.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:rollbackSnapshotResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>\n                <requestId>1234567890</requestId>\n                <dataCenterId>qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh</dataCenterId>\n                <dataCenterVersion>1</dataCenterVersion>\n            </return>\n        </ns2:rollbackSnapshotResponse>\n    </S:Body>\n</S:Envelope>\n"
  },
  {
    "path": "providers/profitbricks/src/test/resources/snapshot/snapshot-state-inprocess.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:getSnapshotResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>\n                <snapshotId>qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh</snapshotId>\n                <description>description</description>\n                <snapshotSize>1024</snapshotSize>\n                <snapshotName>snapshot01</snapshotName>\n                <provisioningState>INPROCESS</provisioningState>\n                <bootable>true</bootable>\n                <osType>LINUX</osType>\n                <cpuHotPlug>true</cpuHotPlug>\n                <cpuHotUnPlug>true</cpuHotUnPlug>\n                <discVirtioHotPlug>true</discVirtioHotPlug>\n                <discVirtioHotUnPlug>true</discVirtioHotUnPlug>\n                <ramHotPlug>true</ramHotPlug>\n                <ramHotUnPlug>true</ramHotUnPlug>\n                <nicHotPlug>true</nicHotPlug>\n                <nicHotUnPlug>true</nicHotUnPlug>\n                <creationTimestamp>2015-01-26T07:09:23.138Z</creationTimestamp>\n                <modificationTimestamp>2015-01-26T07:09:23.138Z</modificationTimestamp>\n                <location>us/las</location>\n            </return>\n        </ns2:getSnapshotResponse>\n    </S:Body>\n</S:Envelope>\n"
  },
  {
    "path": "providers/profitbricks/src/test/resources/snapshot/snapshot-update.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:updateSnapshotResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>\n                <requestId>12345678</requestId>\n            </return>\n        </ns2:updateSnapshotResponse>\n    </S:Body>\n</S:Envelope>\n"
  },
  {
    "path": "providers/profitbricks/src/test/resources/snapshot/snapshot.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:getSnapshotResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>\n                <snapshotId>qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh</snapshotId>\n                <description>description</description>\n                <snapshotSize>1024</snapshotSize>\n                <snapshotName>snapshot01</snapshotName>\n                <provisioningState>AVAILABLE</provisioningState>\n                <bootable>true</bootable>\n                <osType>LINUX</osType>\n                <cpuHotPlug>true</cpuHotPlug>\n                <cpuHotUnPlug>true</cpuHotUnPlug>\n                <discVirtioHotPlug>true</discVirtioHotPlug>\n                <discVirtioHotUnPlug>true</discVirtioHotUnPlug>\n                <ramHotPlug>true</ramHotPlug>\n                <ramHotUnPlug>true</ramHotUnPlug>\n                <nicHotPlug>true</nicHotPlug>\n                <nicHotUnPlug>true</nicHotUnPlug>\n                <creationTimestamp>2015-01-26T07:09:23.138Z</creationTimestamp>\n                <modificationTimestamp>2015-01-26T07:09:23.138Z</modificationTimestamp>\n                <location>us/las</location>\n            </return>\n        </ns2:getSnapshotResponse>\n    </S:Body>\n</S:Envelope>\n"
  },
  {
    "path": "providers/profitbricks/src/test/resources/snapshot/snapshots.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:getAllSnapshotsResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>\n                <snapshotId>aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee</snapshotId>\n                <description>description</description>\n                <snapshotSize>1024</snapshotSize>\n                <snapshotName>snapshot01</snapshotName>\n                <provisioningState>AVAILABLE</provisioningState>\n                <bootable>true</bootable>\n                <osType>LINUX</osType>\n                <cpuHotPlug>true</cpuHotPlug>\n                <cpuHotUnPlug>true</cpuHotUnPlug>\n                <discVirtioHotPlug>true</discVirtioHotPlug>\n                <discVirtioHotUnPlug>true</discVirtioHotUnPlug>\n                <ramHotPlug>true</ramHotPlug>\n                <ramHotUnPlug>true</ramHotUnPlug>\n                <nicHotPlug>true</nicHotPlug>\n                <nicHotUnPlug>true</nicHotUnPlug>\n                <creationTimestamp>2015-01-26T07:09:23.138Z</creationTimestamp>\n                <modificationTimestamp>2015-01-26T07:09:23.138Z</modificationTimestamp>\n                <location>us/las</location>\n            </return>\n            <return>\n                <snapshotId>qqqqqqqq-wwww-rrrr-tttt-yyyyyyyyyyyy</snapshotId>\n                <description>description</description>\n                <snapshotSize>1024</snapshotSize>\n                <snapshotName>snapshot02</snapshotName>\n                <provisioningState>AVAILABLE</provisioningState>\n                <bootable>true</bootable>\n                <osType>LINUX</osType>\n                <cpuHotPlug>true</cpuHotPlug>\n                <cpuHotUnPlug>true</cpuHotUnPlug>\n                <discVirtioHotPlug>true</discVirtioHotPlug>\n                <discVirtioHotUnPlug>true</discVirtioHotUnPlug>\n                <ramHotPlug>true</ramHotPlug>\n                <ramHotUnPlug>true</ramHotUnPlug>\n                <nicHotPlug>true</nicHotPlug>\n                <nicHotUnPlug>true</nicHotUnPlug>\n                <creationTimestamp>2015-01-26T07:09:23.138Z</creationTimestamp>\n                <modificationTimestamp>2015-01-26T07:09:23.138Z</modificationTimestamp>\n                <location>us/las</location>\n            </return>\n        </ns2:getAllSnapshotsResponse>\n    </S:Body>\n</S:Envelope>\n"
  },
  {
    "path": "providers/profitbricks/src/test/resources/storage/storage-connect.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ws=\"http://ws.api.profitbricks.com/\">\n    <soapenv:Header/>\n    <soapenv:Body>\n        <ws:connectStorageToServerResponse>\n            <return>\n                <requestId>16463317</requestId>\n                <dataCenterId>aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee</dataCenterId>\n                <dataCenterVersion>49</dataCenterVersion>\n            </return>\n        </ws:connectStorageToServerResponse>\n    </soapenv:Body>\n</soapenv:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/storage/storage-create.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ws=\"http://ws.api.profitbricks.com/\">\n    <soapenv:Header/>\n    <soapenv:Body>\n        <ws:createStorageReturn>\n            <return>\n                <requestId>1234567</requestId>\n                <dataCenterId>aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee</dataCenterId>\n                <dataCenterVersion>45</dataCenterVersion>\n                <storageId>qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh</storageId>\n            </return>\n        </ws:createStorageReturn>\n    </soapenv:Body>\n</soapenv:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/storage/storage-delete.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ws=\"http://ws.api.profitbricks.com/\">\n    <soapenv:Header/>\n    <soapenv:Body>\n        <ws:deleteStorageResponse>\n            <return>\n                <requestId>12345679</requestId>\n                <dataCenterId>aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee</dataCenterId>\n                <dataCenterVersion>47</dataCenterVersion>\n            </return>\n        </ws:deleteStorageResponse>\n    </soapenv:Body>\n</soapenv:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/storage/storage-disconnect.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ws=\"http://ws.api.profitbricks.com/\">\n    <soapenv:Header/>\n    <soapenv:Body>\n        <ws:disconnectStorageFromServerResponse>\n            <return>\n                <requestId>16463318</requestId>\n                <dataCenterId>aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee</dataCenterId>\n                <dataCenterVersion>50</dataCenterVersion>\n            </return>\n        </ws:disconnectStorageFromServerResponse>\n    </soapenv:Body>\n</soapenv:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/storage/storage-state-inprocess.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:getStorageResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>\n                <requestId>16463316</requestId>\n                <dataCenterId>aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee</dataCenterId>\n                <dataCenterVersion>49</dataCenterVersion>\n                <storageId>qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh</storageId>\n                <size>40</size>\n                <storageName>hdd-1</storageName>\n                <mountImage>\n                    <imageId>f0a59a5c-7940-11e4-8053-52540066fee9</imageId>\n                    <imageName>Ubuntu-14.04-LTS-server-2014-12-01</imageName>\n                </mountImage>\n                <serverIds>qwertyui-qwer-qwer-qwer-qwertyyuiiop</serverIds>\n                <provisioningState>INPROCESS</provisioningState>\n                <creationTime>2014-12-04T07:09:23.138Z</creationTime>\n                <lastModificationTime>2014-12-12T03:14:48.316Z</lastModificationTime>\n            </return>\n        </ns2:getStorageResponse>\n    </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/storage/storage-update.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ws=\"http://ws.api.profitbricks.com/\">\n    <soapenv:Header/>\n    <soapenv:Body>\n        <ws:updateStorageResponse>\n            <return>\n                <requestId>1234568</requestId>\n                <dataCenterId>aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee</dataCenterId>\n                <dataCenterVersion>46</dataCenterVersion>\n            </return>\n        </ws:updateStorageResponse>\n    </soapenv:Body>\n</soapenv:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/storage/storage.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:getStorageResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>\n                <requestId>16463316</requestId>\n                <dataCenterId>aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee</dataCenterId>\n                <dataCenterVersion>49</dataCenterVersion>\n                <storageId>qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh</storageId>\n                <size>40</size>\n                <storageName>hdd-1</storageName>\n                <mountImage>\n                    <imageId>f0a59a5c-7940-11e4-8053-52540066fee9</imageId>\n                    <imageName>Ubuntu-14.04-LTS-server-2014-12-01</imageName>\n                </mountImage>\n                <serverIds>qwertyui-qwer-qwer-qwer-qwertyyuiiop</serverIds>\n                <provisioningState>AVAILABLE</provisioningState>\n                <creationTime>2014-12-04T07:09:23.138Z</creationTime>\n                <lastModificationTime>2014-12-12T03:14:48.316Z</lastModificationTime>\n            </return>\n        </ns2:getStorageResponse>\n    </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/profitbricks/src/test/resources/storage/storages.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n    <S:Body>\n        <ns2:getAllStoragesResponse xmlns:ns2=\"http://ws.api.profitbricks.com/\">\n            <return>\n                <dataCenterId>aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee</dataCenterId>\n                <dataCenterVersion>49</dataCenterVersion>\n                <storageId>qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh</storageId>\n                <size>40</size>\n                <storageName>hdd-1</storageName>\n                <mountImage>\n                    <imageId>f0a59a5c-7940-11e4-8053-52540066fee9</imageId>\n                    <imageName>Ubuntu-14.04-LTS-server-2014-12-01</imageName>\n                </mountImage>\n                <serverIds>qwertyui-qwer-qwer-qwer-qwertyyuiiop</serverIds>\n                <provisioningState>AVAILABLE</provisioningState>\n                <creationTime>2014-12-04T07:09:23.138Z</creationTime>\n                <lastModificationTime>2014-12-12T03:14:48.316Z</lastModificationTime>\n            </return>\n            <return>\n                <dataCenterId>qqqqqqqq-wwww-rrrr-tttt-yyyyyyyyyyyy</dataCenterId>\n                <dataCenterVersion>238</dataCenterVersion>\n                <storageId>asfasfle-f23n-cu89-klfr-njkdsvwllkfa</storageId>\n                <size>100</size>\n                <storageName>hdd-2</storageName>\n                <mountImage>\n                    <imageId>f4742db0-9160-11e4-9d74-52540066fee9</imageId>\n                    <imageName>Fedora-19-server-2015-01-01</imageName>\n                </mountImage>\n                <serverIds>asdfghjk-asdf-asdf-asdf-asdfghjklkjl</serverIds>\n                <provisioningState>INPROCESS</provisioningState>\n                <creationTime>2014-11-04T07:09:23.138Z</creationTime>\n                <lastModificationTime>2014-11-12T03:14:48.316Z</lastModificationTime>\n            </return>\n        </ns2:getAllStoragesResponse>\n    </S:Body>\n</S:Envelope>"
  },
  {
    "path": "providers/rackspace-cloudblockstorage-uk/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.rackspace.cloudblockstorage.uk.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "providers/rackspace-cloudblockstorage-uk/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.provider</groupId>\n  <artifactId>rackspace-cloudblockstorage-uk</artifactId>\n  <name>jclouds Rackspace Next Generation Cloud Block Storage UK provider</name>\n  <description>OpenStack Cinder implementation targeted to Rackspace Next Generation Cloud Block Storage UK</description>\n\n  <properties>\n    <test.rackspace-cloudblockstorage-uk.endpoint>https://lon.identity.api.rackspacecloud.com/v2.0/</test.rackspace-cloudblockstorage-uk.endpoint>\n    <test.rackspace-cloudblockstorage-uk.api-version>1</test.rackspace-cloudblockstorage-uk.api-version>\n    <test.rackspace-cloudblockstorage-uk.build-version />\n    <test.rackspace-cloudblockstorage-uk.identity>${test.rackspace-uk.identity}</test.rackspace-cloudblockstorage-uk.identity>\n    <test.rackspace-cloudblockstorage-uk.credential>${test.rackspace-uk.credential}</test.rackspace-cloudblockstorage-uk.credential>\n    <test.rackspace-cloudblockstorage-uk.template />\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-cinder</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-keystone</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>rackspace-cloudidentity</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-cinder</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-keystone</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>rackspace-cloudidentity</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-slf4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>ch.qos.logback</groupId>\n      <artifactId>logback-classic</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <threadCount>1</threadCount>\n                  <systemPropertyVariables>\n                    <test.rackspace-cloudblockstorage-uk.endpoint>${test.rackspace-cloudblockstorage-uk.endpoint}</test.rackspace-cloudblockstorage-uk.endpoint>\n                    <test.rackspace-cloudblockstorage-uk.api-version>${test.rackspace-cloudblockstorage-uk.api-version}</test.rackspace-cloudblockstorage-uk.api-version>\n                    <test.rackspace-cloudblockstorage-uk.build-version>${test.rackspace-cloudblockstorage-uk.build-version}</test.rackspace-cloudblockstorage-uk.build-version>\n                    <test.rackspace-cloudblockstorage-uk.identity>${test.rackspace-cloudblockstorage-uk.identity}</test.rackspace-cloudblockstorage-uk.identity>\n                    <test.rackspace-cloudblockstorage-uk.credential>${test.rackspace-cloudblockstorage-uk.credential}</test.rackspace-cloudblockstorage-uk.credential>\n                    <test.rackspace-cloudblockstorage-uk.template>${test.rackspace-cloudblockstorage-uk.template}</test.rackspace-cloudblockstorage-uk.template>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n"
  },
  {
    "path": "providers/rackspace-cloudblockstorage-uk/src/main/java/org/jclouds/rackspace/cloudblockstorage/uk/CloudBlockStorageUKProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudblockstorage.uk;\n\nimport static org.jclouds.location.reference.LocationConstants.ISO3166_CODES;\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_REGION;\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_REGIONS;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.CREDENTIAL_TYPE;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.KEYSTONE_VERSION;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.openstack.cinder.v1.CinderApiMetadata;\nimport org.jclouds.openstack.cinder.v1.config.CinderHttpApiModule;\nimport org.jclouds.openstack.cinder.v1.config.CinderParserModule;\nimport org.jclouds.openstack.keystone.catalog.config.ServiceCatalogModule;\nimport org.jclouds.openstack.keystone.catalog.config.ServiceCatalogModule.RegionModule;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\nimport org.jclouds.rackspace.cloudidentity.v2_0.config.CloudIdentityAuthenticationModule;\nimport org.jclouds.rackspace.cloudidentity.v2_0.config.CloudIdentityCredentialTypes;\n\nimport com.google.auto.service.AutoService;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n/**\n * Implementation of {@link ProviderMetadata} for Rackspace Next Generation Cloud Block Storage.\n */\n@AutoService(ProviderMetadata.class)\npublic class CloudBlockStorageUKProviderMetadata extends BaseProviderMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromProviderMetadata(this);\n   }\n\n   public CloudBlockStorageUKProviderMetadata() {\n      super(builder());\n   }\n\n   public CloudBlockStorageUKProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = new Properties();\n      properties.setProperty(CREDENTIAL_TYPE, CloudIdentityCredentialTypes.API_KEY_CREDENTIALS);\n      properties.setProperty(KEYSTONE_VERSION, \"2\");\n      properties.setProperty(PROPERTY_REGIONS, \"LON\");\n      properties.setProperty(PROPERTY_REGION + \".LON.\" + ISO3166_CODES, \"GB-SLG\");\n      return properties;\n   }\n\n   public static class Builder extends BaseProviderMetadata.Builder {\n\n      protected Builder() {\n         id(\"rackspace-cloudblockstorage-uk\")\n         .name(\"Rackspace Next Generation Cloud Block Storage UK\")\n         .apiMetadata(new CinderApiMetadata().toBuilder()\n                  .identityName(\"${userName}\")\n                  .credentialName(\"${apiKey}\")\n                  .defaultEndpoint(\"https://lon.identity.api.rackspacecloud.com/v2.0/\")\n                  .endpointName(\"identity service url ending in /v2.0/\")\n                  .documentation(URI.create(\"http://docs.rackspace.com/cbs/api/v1.0/cbs-devguide/content/overview.html\"))\n                  .defaultModules(ImmutableSet.<Class<? extends Module>>builder()\n                                              .add(CloudIdentityAuthenticationModule.class)\n                                              .add(ServiceCatalogModule.class)\n                                              .add(RegionModule.class)\n                                              .add(CinderParserModule.class)\n                                              .add(CinderHttpApiModule.class).build())\n                  .build())\n         .homepage(URI.create(\"http://www.rackspace.co.uk/cloud-hosting/cloud-products/cloud-block-storage/\"))\n         .console(URI.create(\"https://mycloud.rackspace.co.uk\"))\n         .linkedServices(\"rackspace-cloudservers-uk\", \"cloudfiles-uk\")\n         .iso3166Codes(\"GB-SLG\")\n         .endpoint(\"https://lon.identity.api.rackspacecloud.com/v2.0/\")\n         .defaultProperties(CloudBlockStorageUKProviderMetadata.defaultProperties());\n      }\n\n      @Override\n      public CloudBlockStorageUKProviderMetadata build() {\n         return new CloudBlockStorageUKProviderMetadata(this);\n      }\n\n      @Override\n      public Builder fromProviderMetadata(ProviderMetadata in) {\n         super.fromProviderMetadata(in);\n         return this;\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/rackspace-cloudblockstorage-uk/src/test/java/org/jclouds/rackspace/cloudblockstorage/uk/CloudBlockStorageUKProviderMetadataExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudblockstorage.uk;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.cinder.v1.CinderApi;\nimport org.jclouds.openstack.cinder.v1.internal.BaseCinderApiExpectTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * This test ensures that the wiring in {@link CloudBlockStorageUKProviderMetadata} is correct.\n */\n@Test(groups = \"unit\", testName = \"CloudBlockStorageUKProviderMetadataExpectTest\")\npublic class CloudBlockStorageUKProviderMetadataExpectTest extends BaseCinderApiExpectTest {\n\n   public CloudBlockStorageUKProviderMetadataExpectTest() {\n      this.provider = \"rackspace-cloudblockstorage-uk\";\n      this.identity = \"myUsername\";\n      this.credential = \"myApiKey\";\n   }\n\n   public void testCanGetConfiguredRegions() {\n\n      HttpRequest authenticate = HttpRequest.builder().method(\"POST\")\n            .endpoint(\"https://lon.identity.api.rackspacecloud.com/v2.0/tokens\")\n            .addHeader(\"Accept\", \"application/json\")\n            .payload(payloadFromStringWithContentType(\n                     \"{\\\"auth\\\":{\\\"RAX-KSKEY:apiKeyCredentials\\\":{\\\"username\\\":\\\"myUsername\\\",\\\"apiKey\\\":\\\"myApiKey\\\"}}}\",\n                     \"application/json\")).build();\n\n\n      HttpResponse authenticationResponse = HttpResponse.builder()\n            .statusCode(200)\n            .payload(payloadFromResourceWithContentType(\"/access_rax_uk.json\", \"application/json\"))\n            .build();\n\n      CinderApi whenNovaRegionExists = requestSendsResponse(authenticate, authenticationResponse);\n\n      assertEquals(whenNovaRegionExists.getConfiguredRegions(), ImmutableSet.of(\"LON\"));\n\n   }\n\n}\n"
  },
  {
    "path": "providers/rackspace-cloudblockstorage-uk/src/test/java/org/jclouds/rackspace/cloudblockstorage/uk/CloudBlockStorageUKProviderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudblockstorage.uk;\n\nimport org.jclouds.openstack.cinder.v1.CinderApiMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"CloudBlockStorageUKProviderTest\")\npublic class CloudBlockStorageUKProviderTest extends BaseProviderMetadataTest {\n\n   public CloudBlockStorageUKProviderTest() {\n      super(new CloudBlockStorageUKProviderMetadata(), new CinderApiMetadata());\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudblockstorage-uk/src/test/java/org/jclouds/rackspace/cloudblockstorage/uk/features/CloudBlockStorageUKVolumeAndSnapshotApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudblockstorage.uk.features;\n\nimport org.jclouds.openstack.cinder.v1.features.VolumeAndSnapshotApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"CloudBlockStorageUKVolumeAndSnapshotApiLiveTest\")\npublic class CloudBlockStorageUKVolumeAndSnapshotApiLiveTest extends VolumeAndSnapshotApiLiveTest {\n   public CloudBlockStorageUKVolumeAndSnapshotApiLiveTest() {\n      provider = \"rackspace-cloudblockstorage-uk\";\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudblockstorage-uk/src/test/java/org/jclouds/rackspace/cloudblockstorage/uk/features/CloudBlockStorageUKVolumeTypeApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudblockstorage.uk.features;\n\nimport org.jclouds.openstack.cinder.v1.features.VolumeTypeApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"CloudBlockStorageUSVolumeTypeApiLiveTest\")\npublic class CloudBlockStorageUKVolumeTypeApiLiveTest extends VolumeTypeApiLiveTest {\n    public CloudBlockStorageUKVolumeTypeApiLiveTest() {\n        provider = \"rackspace-cloudblockstorage-uk\";\n    }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudblockstorage-uk/src/test/resources/access_rax_uk.json",
    "content": "{\n    \"access\": {\n        \"token\": {\n            \"id\": \"bdd18214-e266-4ad3-b985-d9bfb22c8da8\",\n            \"expires\": \"2012-10-01T02:11:16.000+01:00\",\n            \"tenant\": {\n                \"id\": \"10001786\",\n                \"name\": \"10001786\"\n            }\n        },\n        \"serviceCatalog\": [\n            {\n                \"endpoints\": [\n                    {\n                        \"region\": \"LON\",\n                        \"tenantId\": \"MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953\",\n                        \"publicURL\": \"https://storage101.lon3.clouddrive.com/v1/MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953\",\n                        \"internalURL\": \"https://snet-storage101.lon3.clouddrive.com/v1/MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953\"\n                    }\n                ],\n                \"name\": \"cloudFiles\",\n                \"type\": \"object-store\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"region\": \"LON\",\n                        \"tenantId\": \"MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953\",\n                        \"publicURL\": \"https://cdn3.clouddrive.com/v1/MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953\"\n                    }\n                ],\n                \"name\": \"cloudFilesCDN\",\n                \"type\": \"rax:object-cdn\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"tenantId\": \"10001786\",\n                        \"publicURL\": \"https://lon.servers.api.rackspacecloud.com/v1.0/10001786\",\n                        \"versionInfo\": \"https://lon.servers.api.rackspacecloud.com/v1.0\",\n                        \"versionList\": \"https://lon.servers.api.rackspacecloud.com/\",\n                        \"versionId\": \"1.0\"\n                    }\n                ],\n                \"name\": \"cloudServers\",\n                \"type\": \"compute\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"tenantId\": \"10001786\",\n                        \"publicURL\": \"https://lon.dns.api.rackspacecloud.com/v1.0/10001786\"\n                    }\n                ],\n                \"name\": \"cloudDNS\",\n                \"type\": \"rax:dns\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"region\": \"LON\",\n                        \"tenantId\": \"10001786\",\n                        \"publicURL\": \"https://lon.loadbalancers.api.rackspacecloud.com/v1.0/10001786\"\n                    }\n                ],\n                \"name\": \"cloudLoadBalancers\",\n                \"type\": \"rax:load-balancer\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"tenantId\": \"10001786\",\n                        \"publicURL\": \"https://monitoring.api.rackspacecloud.com/v1.0/10001786\"\n                    }\n                ],\n                \"name\": \"cloudMonitoring\",\n                \"type\": \"rax:monitor\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"region\": \"LON\",\n                        \"tenantId\": \"10001786\",\n                        \"publicURL\": \"https://lon.databases.api.rackspacecloud.com/v1.0/10001786\"\n                    }\n                ],\n                \"name\": \"cloudDatabases\",\n                \"type\": \"rax:database\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"region\": \"LON\",\n                        \"tenantId\": \"10001786\",\n                        \"publicURL\": \"https://lon.servers.api.rackspacecloud.com/v2/10001786\",\n                        \"versionInfo\": \"https://lon.servers.api.rackspacecloud.com/v2\",\n                        \"versionList\": \"https://lon.servers.api.rackspacecloud.com/\",\n                        \"versionId\": \"2\"\n                    }\n                ],\n                \"name\": \"cloudServersOpenStack\",\n                \"type\": \"compute\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"publicURL\": \"https://lon.blockstorage.api.rackspacecloud.com/v1/10001786\",\n                        \"tenantId\": \"10001786\",\n                        \"region\": \"LON\"\n                    }\n                ],\n                \"name\": \"cloudBlockStorage\",\n                \"type\": \"volume\"\n            }\n        ],\n        \"user\": {\n            \"id\": \"378\",\n            \"roles\": [\n                {\n                    \"id\": \"3\",\n                    \"description\": \"User Admin Role.\",\n                    \"name\": \"identity:user-admin\"\n                }\n            ],\n            \"name\": \"jclouds\",\n            \"RAX-AUTH:defaultRegion\": \"\"\n        }\n    }\n}"
  },
  {
    "path": "providers/rackspace-cloudblockstorage-us/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.rackspace.cloudblockstorage.us.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "providers/rackspace-cloudblockstorage-us/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.provider</groupId>\n  <artifactId>rackspace-cloudblockstorage-us</artifactId>\n  <name>jclouds Rackspace Next Generation Cloud Block Storage US provider</name>\n  <description>OpenStack Cinder implementation targeted to Rackspace Next Generation Cloud Block Storage US</description>\n\n  <properties>\n    <test.rackspace-cloudblockstorage-us.endpoint>https://identity.api.rackspacecloud.com/v2.0/</test.rackspace-cloudblockstorage-us.endpoint>\n    <test.rackspace-cloudblockstorage-us.api-version>1</test.rackspace-cloudblockstorage-us.api-version>\n    <test.rackspace-cloudblockstorage-us.build-version />\n    <test.rackspace-cloudblockstorage-us.identity>${test.rackspace-us.identity}</test.rackspace-cloudblockstorage-us.identity>\n    <test.rackspace-cloudblockstorage-us.credential>${test.rackspace-us.credential}</test.rackspace-cloudblockstorage-us.credential>\n    <test.rackspace-cloudblockstorage-us.template />\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-cinder</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-keystone</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>rackspace-cloudidentity</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-cinder</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-keystone</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>rackspace-cloudidentity</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-slf4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>ch.qos.logback</groupId>\n      <artifactId>logback-classic</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <threadCount>1</threadCount>\n                  <systemPropertyVariables>\n                    <test.rackspace-cloudblockstorage-us.endpoint>${test.rackspace-cloudblockstorage-us.endpoint}</test.rackspace-cloudblockstorage-us.endpoint>\n                    <test.rackspace-cloudblockstorage-us.api-version>${test.rackspace-cloudblockstorage-us.api-version}</test.rackspace-cloudblockstorage-us.api-version>\n                    <test.rackspace-cloudblockstorage-us.build-version>${test.rackspace-cloudblockstorage-us.build-version}</test.rackspace-cloudblockstorage-us.build-version>\n                    <test.rackspace-cloudblockstorage-us.identity>${test.rackspace-cloudblockstorage-us.identity}</test.rackspace-cloudblockstorage-us.identity>\n                    <test.rackspace-cloudblockstorage-us.credential>${test.rackspace-cloudblockstorage-us.credential}</test.rackspace-cloudblockstorage-us.credential>\n                    <test.rackspace-cloudblockstorage-us.template>${test.rackspace-cloudblockstorage-us.template}</test.rackspace-cloudblockstorage-us.template>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n"
  },
  {
    "path": "providers/rackspace-cloudblockstorage-us/src/main/java/org/jclouds/rackspace/cloudblockstorage/us/CloudBlockStorageUSProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudblockstorage.us;\n\nimport static org.jclouds.location.reference.LocationConstants.ISO3166_CODES;\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_REGION;\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_REGIONS;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.CREDENTIAL_TYPE;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.KEYSTONE_VERSION;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.openstack.cinder.v1.CinderApiMetadata;\nimport org.jclouds.openstack.cinder.v1.config.CinderHttpApiModule;\nimport org.jclouds.openstack.cinder.v1.config.CinderParserModule;\nimport org.jclouds.openstack.keystone.catalog.config.ServiceCatalogModule;\nimport org.jclouds.openstack.keystone.catalog.config.ServiceCatalogModule.RegionModule;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\nimport org.jclouds.rackspace.cloudidentity.v2_0.config.CloudIdentityAuthenticationModule;\nimport org.jclouds.rackspace.cloudidentity.v2_0.config.CloudIdentityCredentialTypes;\n\nimport com.google.auto.service.AutoService;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n/**\n * Implementation of {@link ProviderMetadata} for Rackspace Next Generation Cloud Block Storage.\n */\n@AutoService(ProviderMetadata.class)\npublic class CloudBlockStorageUSProviderMetadata extends BaseProviderMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromProviderMetadata(this);\n   }\n\n   public CloudBlockStorageUSProviderMetadata() {\n      super(builder());\n   }\n\n   public CloudBlockStorageUSProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = new Properties();\n      properties.setProperty(CREDENTIAL_TYPE, CloudIdentityCredentialTypes.API_KEY_CREDENTIALS);\n      properties.setProperty(KEYSTONE_VERSION, \"2\");\n      properties.setProperty(PROPERTY_REGIONS, \"ORD,DFW,IAD,SYD,HKG\");\n      properties.setProperty(PROPERTY_REGION + \".ORD.\" + ISO3166_CODES, \"US-IL\");\n      properties.setProperty(PROPERTY_REGION + \".DFW.\" + ISO3166_CODES, \"US-TX\");\n      properties.setProperty(PROPERTY_REGION + \".IAD.\" + ISO3166_CODES, \"US-VA\");\n      properties.setProperty(PROPERTY_REGION + \".SYD.\" + ISO3166_CODES, \"AU-NSW\");\n      properties.setProperty(PROPERTY_REGION + \".HKG.\" + ISO3166_CODES, \"HK\");\n      return properties;\n   }\n\n   public static class Builder extends BaseProviderMetadata.Builder {\n\n      protected Builder() {\n         id(\"rackspace-cloudblockstorage-us\")\n         .name(\"Rackspace Next Generation Cloud Block Storage US\")\n         .apiMetadata(new CinderApiMetadata().toBuilder()\n                  .identityName(\"${userName}\")\n                  .credentialName(\"${apiKey}\")\n                  .defaultEndpoint(\"https://identity.api.rackspacecloud.com/v2.0/\")\n                  .endpointName(\"identity service url ending in /v2.0/\")\n                  .documentation(URI.create(\"http://docs.rackspace.com/cbs/api/v1.0/cbs-devguide/content/overview.html\"))\n                  .defaultModules(ImmutableSet.<Class<? extends Module>>builder()\n                                              .add(CloudIdentityAuthenticationModule.class)\n                                              .add(ServiceCatalogModule.class)\n                                              .add(RegionModule.class)\n                                              .add(CinderParserModule.class)\n                                              .add(CinderHttpApiModule.class).build())\n                  .build())\n         .homepage(URI.create(\"http://www.rackspace.com/cloud/public/blockstorage/\"))\n         .console(URI.create(\"https://mycloud.rackspace.com\"))\n         .linkedServices(\"rackspace-cloudservers-us\", \"cloudfiles-us\")\n         .iso3166Codes(\"US-IL\", \"US-TX\", \"AU-NSW\")\n         .endpoint(\"https://identity.api.rackspacecloud.com/v2.0/\")\n         .defaultProperties(CloudBlockStorageUSProviderMetadata.defaultProperties());\n      }\n\n      @Override\n      public CloudBlockStorageUSProviderMetadata build() {\n         return new CloudBlockStorageUSProviderMetadata(this);\n      }\n\n      @Override\n      public Builder fromProviderMetadata(ProviderMetadata in) {\n         super.fromProviderMetadata(in);\n         return this;\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/rackspace-cloudblockstorage-us/src/test/java/org/jclouds/rackspace/cloudblockstorage/us/CloudBlockStorageUSProviderMetadataExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudblockstorage.us;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.cinder.v1.CinderApi;\nimport org.jclouds.openstack.cinder.v1.internal.BaseCinderApiExpectTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * This test ensures that the wiring in {@link CloudBlockStorageUSProviderMetadata} is correct.\n */\n@Test(groups = \"unit\", testName = \"CloudBlockStorageUSProviderMetadataExpectTest\")\npublic class CloudBlockStorageUSProviderMetadataExpectTest extends BaseCinderApiExpectTest {\n\n   public CloudBlockStorageUSProviderMetadataExpectTest() {\n      this.provider = \"rackspace-cloudblockstorage-us\";\n      this.identity = \"myUsername\";\n      this.credential = \"myApiKey\";\n   }\n\n   public void testCanGetConfiguredRegions() {\n\n      HttpRequest authenticate = HttpRequest.builder().method(\"POST\")\n            .endpoint(\"https://identity.api.rackspacecloud.com/v2.0/tokens\")\n            .addHeader(\"Accept\", \"application/json\")\n            .payload(payloadFromStringWithContentType(\n                     \"{\\\"auth\\\":{\\\"RAX-KSKEY:apiKeyCredentials\\\":{\\\"username\\\":\\\"myUsername\\\",\\\"apiKey\\\":\\\"myApiKey\\\"}}}\",\n                     \"application/json\")).build();\n\n\n      HttpResponse authenticationResponse = HttpResponse.builder()\n            .statusCode(200)\n            .payload(payloadFromResourceWithContentType(\"/access_rax_us.json\", \"application/json\"))\n            .build();\n\n      CinderApi whenNovaRegionExists = requestSendsResponse(authenticate, authenticationResponse);\n\n      assertEquals(whenNovaRegionExists.getConfiguredRegions(), ImmutableSet.of(\"ORD\", \"DFW\"));\n\n   }\n\n}\n"
  },
  {
    "path": "providers/rackspace-cloudblockstorage-us/src/test/java/org/jclouds/rackspace/cloudblockstorage/us/CloudBlockStorageUSProviderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudblockstorage.us;\n\nimport org.jclouds.openstack.cinder.v1.CinderApiMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"CloudBlockStorageUSProviderTest\")\npublic class CloudBlockStorageUSProviderTest extends BaseProviderMetadataTest {\n\n   public CloudBlockStorageUSProviderTest() {\n      super(new CloudBlockStorageUSProviderMetadata(), new CinderApiMetadata());\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudblockstorage-us/src/test/java/org/jclouds/rackspace/cloudblockstorage/us/features/CloudBlockStorageUSVolumeAndSnapshotApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudblockstorage.us.features;\n\nimport org.jclouds.openstack.cinder.v1.features.VolumeAndSnapshotApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"CloudBlockStorageUSVolumeAndSnapshotApiLiveTest\")\npublic class CloudBlockStorageUSVolumeAndSnapshotApiLiveTest extends VolumeAndSnapshotApiLiveTest {\n   public CloudBlockStorageUSVolumeAndSnapshotApiLiveTest() {\n      provider = \"rackspace-cloudblockstorage-us\";\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudblockstorage-us/src/test/java/org/jclouds/rackspace/cloudblockstorage/us/features/CloudBlockStorageUSVolumeTypeApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudblockstorage.us.features;\n\nimport org.jclouds.openstack.cinder.v1.features.VolumeTypeApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"CloudBlockStorageUSVolumeTypeApiLiveTest\")\npublic class CloudBlockStorageUSVolumeTypeApiLiveTest extends VolumeTypeApiLiveTest {\n    public CloudBlockStorageUSVolumeTypeApiLiveTest() {\n        provider = \"rackspace-cloudblockstorage-us\";\n    }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudblockstorage-us/src/test/resources/access_rax_us.json",
    "content": "{\n    \"access\": {\n        \"token\": {\n            \"id\": \"myToken\",\n            \"expires\": \"2012-09-30T17:15:32.000-05:00\",\n            \"tenant\": {\n                \"id\": \"717071\",\n                \"name\": \"717071\"\n            }\n        },\n        \"serviceCatalog\": [\n            {\n                \"endpoints\": [\n                    {\n                        \"tenantId\": \"717071\",\n                        \"publicURL\": \"https://dns.api.rackspacecloud.com/v1.0/717071\"\n                    }\n                ],\n                \"name\": \"cloudDNS\",\n                \"type\": \"rax:dns\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"tenantId\": \"717071\",\n                        \"publicURL\": \"https://monitoring.api.rackspacecloud.com/v1.0/717071\"\n                    }\n                ],\n                \"name\": \"cloudMonitoring\",\n                \"type\": \"rax:monitor\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"region\": \"DFW\",\n                        \"tenantId\": \"717071\",\n                        \"publicURL\": \"https://dfw.servers.api.rackspacecloud.com/v2/717071\",\n                        \"versionInfo\": \"https://dfw.servers.api.rackspacecloud.com/v2\",\n                        \"versionList\": \"https://dfw.servers.api.rackspacecloud.com/\",\n                        \"versionId\": \"2\"\n                    },\n                    {\n                        \"region\": \"ORD\",\n                        \"tenantId\": \"717071\",\n                        \"publicURL\": \"https://ord.servers.api.rackspacecloud.com/v2/717071\",\n                        \"versionInfo\": \"https://ord.servers.api.rackspacecloud.com/v2\",\n                        \"versionList\": \"https://ord.servers.api.rackspacecloud.com/\",\n                        \"versionId\": \"2\"\n                    }\n                ],\n                \"name\": \"cloudServersOpenStack\",\n                \"type\": \"compute\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"region\": \"ORD\",\n                        \"tenantId\": \"717071\",\n                        \"publicURL\": \"https://ord.loadbalancers.api.rackspacecloud.com/v1.0/717071\"\n                    },\n                    {\n                        \"region\": \"DFW\",\n                        \"tenantId\": \"717071\",\n                        \"publicURL\": \"https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/717071\"\n                    }\n                ],\n                \"name\": \"cloudLoadBalancers\",\n                \"type\": \"rax:load-balancer\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"region\": \"DFW\",\n                        \"tenantId\": \"717071\",\n                        \"publicURL\": \"https://dfw.databases.api.rackspacecloud.com/v1.0/717071\"\n                    },\n                    {\n                        \"region\": \"ORD\",\n                        \"tenantId\": \"717071\",\n                        \"publicURL\": \"https://ord.databases.api.rackspacecloud.com/v1.0/717071\"\n                    }\n                ],\n                \"name\": \"cloudDatabases\",\n                \"type\": \"rax:database\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"region\": \"DFW\",\n                        \"tenantId\": \"MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\",\n                        \"publicURL\": \"https://storage101.dfw1.clouddrive.com/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\",\n                        \"internalURL\": \"https://snet-storage101.dfw1.clouddrive.com/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\"\n                    },\n                    {\n                        \"region\": \"ORD\",\n                        \"tenantId\": \"MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\",\n                        \"publicURL\": \"https://storage101.ord1.clouddrive.com/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\",\n                        \"internalURL\": \"https://snet-storage101.ord1.clouddrive.com/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\"\n                    }\n                ],\n                \"name\": \"cloudFiles\",\n                \"type\": \"object-store\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"region\": \"DFW\",\n                        \"tenantId\": \"MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\",\n                        \"publicURL\": \"https://cdn1.clouddrive.com/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\"\n                    },\n                    {\n                        \"region\": \"ORD\",\n                        \"tenantId\": \"MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\",\n                        \"publicURL\": \"https://cdn2.clouddrive.com/v1/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\"\n                    }\n                ],\n                \"name\": \"cloudFilesCDN\",\n                \"type\": \"rax:object-cdn\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"tenantId\": \"717071\",\n                        \"publicURL\": \"https://servers.api.rackspacecloud.com/v1.0/717071\",\n                        \"versionInfo\": \"https://servers.api.rackspacecloud.com/v1.0\",\n                        \"versionList\": \"https://servers.api.rackspacecloud.com/\",\n                        \"versionId\": \"1.0\"\n                    }\n                ],\n                \"name\": \"cloudServers\",\n                \"type\": \"compute\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                         \"publicURL\": \"https://ord.blockstorage.api.rackspacecloud.com/v1/717071\",\n                         \"tenantId\": \"717071\",\n                         \"region\": \"ORD\"\n                    },\n                    {\n                        \"region\": \"DFW\",\n                        \"tenantId\": \"717071\",\n                        \"publicURL\": \"https://dfw.blockstorage.api.rackspacecloud.com/v1/717071\"\n                    }\n                ],\n                \"name\": \"cloudBlockStorage\",\n                \"type\": \"volume\"\n            }\n        ],\n        \"user\": {\n            \"id\": \"224085\",\n            \"roles\": [\n                {\n                    \"id\": \"3\",\n                    \"description\": \"User Admin Role.\",\n                    \"name\": \"identity:user-admin\"\n                }\n            ],\n            \"name\": \"myUsername\",\n            \"RAX-AUTH:defaultRegion\": \"DFW\"\n        }\n    }\n}"
  },
  {
    "path": "providers/rackspace-clouddatabases-uk/README.md",
    "content": "Rackspace Cloud Databases UK\n============================\n\nThe Rackspace deployment of OpenStack Trove, the Database as a Service.\n\nProduction ready?\nYes\n"
  },
  {
    "path": "providers/rackspace-clouddatabases-uk/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.rackspace.clouddatabases.uk.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "providers/rackspace-clouddatabases-uk/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.provider</groupId>\n  <artifactId>rackspace-clouddatabases-uk</artifactId>\n  <name>jclouds Rackspace Cloud Databases UK provider</name>\n  <description>OpenStack Trove implementation targeted to Rackspace Cloud Databases UK</description>\n\n  <properties>\n    <test.rackspace-clouddatabases-uk.endpoint>https://identity.api.rackspacecloud.com/v2.0/</test.rackspace-clouddatabases-uk.endpoint>\n    <test.rackspace-clouddatabases-uk.api-version>1</test.rackspace-clouddatabases-uk.api-version>\n    <test.rackspace-clouddatabases-uk.build-version />\n    <test.rackspace-clouddatabases-uk.identity>${test.rackspace-uk.identity}</test.rackspace-clouddatabases-uk.identity>\n    <test.rackspace-clouddatabases-uk.credential>${test.rackspace-uk.credential}</test.rackspace-clouddatabases-uk.credential>\n    <test.rackspace-clouddatabases-uk.template />\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-trove</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-keystone</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>rackspace-cloudidentity</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-trove</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-keystone</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>rackspace-cloudidentity</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-slf4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>ch.qos.logback</groupId>\n      <artifactId>logback-classic</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <forkCount>5</forkCount>\n                  <reuseForks>true</reuseForks>\n                  <parallel>classes</parallel>\n                  <systemPropertyVariables>\n                    <test.rackspace-clouddatabases-uk.endpoint>${test.rackspace-clouddatabases-uk.endpoint}</test.rackspace-clouddatabases-uk.endpoint>\n                    <test.rackspace-clouddatabases-uk.api-version>${test.rackspace-clouddatabases-uk.api-version}</test.rackspace-clouddatabases-uk.api-version>\n                    <test.rackspace-clouddatabases-uk.build-version>${test.rackspace-clouddatabases-uk.build-version}</test.rackspace-clouddatabases-uk.build-version>\n                    <test.rackspace-clouddatabases-uk.identity>${test.rackspace-clouddatabases-uk.identity}</test.rackspace-clouddatabases-uk.identity>\n                    <test.rackspace-clouddatabases-uk.credential>${test.rackspace-clouddatabases-uk.credential}</test.rackspace-clouddatabases-uk.credential>\n                    <test.rackspace-clouddatabases-uk.template>${test.rackspace-clouddatabases-uk.template}</test.rackspace-clouddatabases-uk.template>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n"
  },
  {
    "path": "providers/rackspace-clouddatabases-uk/src/main/java/org/jclouds/rackspace/clouddatabases/uk/CloudDatabasesUKProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddatabases.uk;\n\nimport static org.jclouds.location.reference.LocationConstants.ISO3166_CODES;\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_REGION;\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_REGIONS;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.CREDENTIAL_TYPE;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.KEYSTONE_VERSION;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.SERVICE_TYPE;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.openstack.keystone.catalog.config.ServiceCatalogModule;\nimport org.jclouds.openstack.keystone.catalog.config.ServiceCatalogModule.RegionModule;\nimport org.jclouds.openstack.trove.v1.TroveApiMetadata;\nimport org.jclouds.openstack.trove.v1.config.TroveHttpApiModule;\nimport org.jclouds.openstack.trove.v1.config.TroveParserModule;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\nimport org.jclouds.rackspace.cloudidentity.v2_0.ServiceType;\nimport org.jclouds.rackspace.cloudidentity.v2_0.config.CloudIdentityAuthenticationModule;\nimport org.jclouds.rackspace.cloudidentity.v2_0.config.CloudIdentityCredentialTypes;\n\nimport com.google.auto.service.AutoService;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n/**\n * Implementation of {@link ProviderMetadata} for Rackspace Cloud Databases.\n */\n@AutoService(ProviderMetadata.class)\npublic class CloudDatabasesUKProviderMetadata extends BaseProviderMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromProviderMetadata(this);\n   }\n\n   public CloudDatabasesUKProviderMetadata() {\n      super(builder());\n   }\n\n   public CloudDatabasesUKProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = new Properties();\n      properties.setProperty(CREDENTIAL_TYPE, CloudIdentityCredentialTypes.API_KEY_CREDENTIALS);\n      properties.setProperty(SERVICE_TYPE, ServiceType.DATABASES);\n      properties.setProperty(KEYSTONE_VERSION, \"2\");\n      properties.setProperty(PROPERTY_REGIONS, \"LON\");\n      properties.setProperty(PROPERTY_REGION + \".LON.\" + ISO3166_CODES, \"GB-SLG\");\n      return properties;\n   }\n\n   public static class Builder extends BaseProviderMetadata.Builder {\n\n      protected Builder(){\n         id(\"rackspace-clouddatabases-uk\")\n         .name(\"Rackspace Clouddatabases UK\")\n         .apiMetadata(new TroveApiMetadata().toBuilder()\n                  .identityName(\"${userName}\")\n                  .credentialName(\"${apiKey}\")\n                  .defaultEndpoint(\"https://lon.identity.api.rackspacecloud.com/v2.0\")\n                  .endpointName(\"identity service url ending in /v2.0/\")\n                  .documentation(URI.create(\"http://docs.rackspace.com/cbs/api/v1.0/cbs-devguide/content/overview.html\"))\n                  .defaultModules(ImmutableSet.<Class<? extends Module>>builder()\n                                              .add(CloudIdentityAuthenticationModule.class)\n                                              .add(ServiceCatalogModule.class)\n                                              .add(RegionModule.class)\n                                              .add(TroveParserModule.class)\n                                              .add(TroveHttpApiModule.class).build())\n                  .build())\n         .homepage(URI.create(\"http://www.rackspace.com/cloud/public/databases/\"))\n         .console(URI.create(\"https://mycloud.rackspace.com\"))\n         .linkedServices(\"rackspace-cloudservers-uk\", \"cloudfiles-uk\")\n         .iso3166Codes(\"GB-SLG\")\n         .endpoint(\"https://lon.identity.api.rackspacecloud.com/v2.0\")\n         .defaultProperties(CloudDatabasesUKProviderMetadata.defaultProperties());\n      }\n\n      @Override\n      public CloudDatabasesUKProviderMetadata build() {\n         return new CloudDatabasesUKProviderMetadata(this);\n      }\n\n      @Override\n      public Builder fromProviderMetadata(ProviderMetadata in) {\n         super.fromProviderMetadata(in);\n         return this;\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/rackspace-clouddatabases-uk/src/test/java/org/jclouds/rackspace/clouddatabases/uk/CloudDatabasesUKProviderMetadataExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddatabases.uk;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.trove.v1.TroveApi;\nimport org.jclouds.openstack.trove.v1.internal.BaseTroveApiExpectTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * This test ensures that the wiring in {@link CloudDatabasesUKProviderMetadata} is correct.\n */\n@Test(groups = \"unit\", testName = \"CloudDatabasesUKProviderMetadataExpectTest\")\npublic class CloudDatabasesUKProviderMetadataExpectTest extends BaseTroveApiExpectTest {\n\n   public CloudDatabasesUKProviderMetadataExpectTest() {\n      this.provider = \"rackspace-clouddatabases-uk\";\n      this.identity = \"myUsername\";\n      this.credential = \"myApiKey\";\n   }\n\n   public void testCanGetConfiguredRegions() {\n\n      HttpRequest authenticate = HttpRequest.builder().method(\"POST\")\n            .endpoint(\"https://lon.identity.api.rackspacecloud.com/v2.0/tokens\")\n            .addHeader(\"Accept\", \"application/json\")\n            .payload(payloadFromStringWithContentType(\n                     \"{\\\"auth\\\":{\\\"RAX-KSKEY:apiKeyCredentials\\\":{\\\"username\\\":\\\"myUsername\\\",\\\"apiKey\\\":\\\"myApiKey\\\"}}}\",\n                     \"application/json\")).build();\n\n\n      HttpResponse authenticationResponse = HttpResponse.builder()\n            .statusCode(200)\n            .payload(payloadFromResourceWithContentType(\"/access_rax_uk.json\", \"application/json\"))\n            .build();\n\n      TroveApi whenNovaRegionExists = requestSendsResponse(authenticate, authenticationResponse);\n\n      assertEquals(whenNovaRegionExists.getConfiguredRegions(), ImmutableSet.of(\"LON\"));\n\n   }\n\n}\n"
  },
  {
    "path": "providers/rackspace-clouddatabases-uk/src/test/java/org/jclouds/rackspace/clouddatabases/uk/CloudDatabasesUKProviderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddatabases.uk;\n\nimport org.jclouds.openstack.trove.v1.TroveApiMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"CloudDatabasesUKProviderTest\")\npublic class CloudDatabasesUKProviderTest extends BaseProviderMetadataTest {\n\n   public CloudDatabasesUKProviderTest() {\n      super(new CloudDatabasesUKProviderMetadata(), new TroveApiMetadata());\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-clouddatabases-uk/src/test/java/org/jclouds/rackspace/clouddatabases/uk/features/CloudDatabasesUKDatabaseApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddatabases.uk.features;\n\nimport org.jclouds.openstack.trove.v1.features.DatabaseApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"CloudDatabasesUKDatabaseApiLiveTest\")\npublic class CloudDatabasesUKDatabaseApiLiveTest extends DatabaseApiLiveTest {\n   public CloudDatabasesUKDatabaseApiLiveTest() {\n      provider = \"rackspace-clouddatabases-uk\";\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-clouddatabases-uk/src/test/java/org/jclouds/rackspace/clouddatabases/uk/features/CloudDatabasesUKFlavorApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddatabases.uk.features;\n\nimport org.jclouds.openstack.trove.v1.features.FlavorApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"CloudDatabasesUKFlavorApiLiveTest\")\npublic class CloudDatabasesUKFlavorApiLiveTest extends FlavorApiLiveTest {\n   public CloudDatabasesUKFlavorApiLiveTest() {\n      provider = \"rackspace-clouddatabases-uk\";\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-clouddatabases-uk/src/test/java/org/jclouds/rackspace/clouddatabases/uk/features/CloudDatabasesUKInstanceApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddatabases.uk.features;\n\nimport org.jclouds.openstack.trove.v1.features.InstanceApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"CloudDatabasesUKInstanceApiLiveTest\")\npublic class CloudDatabasesUKInstanceApiLiveTest extends InstanceApiLiveTest {\n   public CloudDatabasesUKInstanceApiLiveTest() {\n      provider = \"rackspace-clouddatabases-uk\";\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-clouddatabases-uk/src/test/java/org/jclouds/rackspace/clouddatabases/uk/features/CloudDatabasesUKUserApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddatabases.uk.features;\n\nimport org.jclouds.openstack.trove.v1.features.UserApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"CloudDatabasesUKUserApiLiveTest\")\npublic class CloudDatabasesUKUserApiLiveTest extends UserApiLiveTest {\n   public CloudDatabasesUKUserApiLiveTest() {\n      provider = \"rackspace-clouddatabases-uk\";\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-clouddatabases-uk/src/test/resources/access_rax_uk.json",
    "content": "{\n    \"access\": {\n        \"token\": {\n            \"id\": \"bdd18214-e266-4ad3-b985-d9bfb22c8da8\",\n            \"expires\": \"2012-10-01T02:11:16.000+01:00\",\n            \"tenant\": {\n                \"id\": \"10001786\",\n                \"name\": \"10001786\"\n            }\n        },\n        \"serviceCatalog\": [\n            {\n                \"endpoints\": [\n                    {\n                        \"region\": \"LON\",\n                        \"tenantId\": \"MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953\",\n                        \"publicURL\": \"https://storage101.lon3.clouddrive.com/v1/MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953\",\n                        \"internalURL\": \"https://snet-storage101.lon3.clouddrive.com/v1/MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953\"\n                    }\n                ],\n                \"name\": \"cloudFiles\",\n                \"type\": \"object-store\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"region\": \"LON\",\n                        \"tenantId\": \"MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953\",\n                        \"publicURL\": \"https://cdn3.clouddrive.com/v1/MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953\"\n                    }\n                ],\n                \"name\": \"cloudFilesCDN\",\n                \"type\": \"rax:object-cdn\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"tenantId\": \"10001786\",\n                        \"publicURL\": \"https://lon.servers.api.rackspacecloud.com/v1.0/10001786\",\n                        \"versionInfo\": \"https://lon.servers.api.rackspacecloud.com/v1.0\",\n                        \"versionList\": \"https://lon.servers.api.rackspacecloud.com/\",\n                        \"versionId\": \"1.0\"\n                    }\n                ],\n                \"name\": \"cloudServers\",\n                \"type\": \"compute\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"tenantId\": \"10001786\",\n                        \"publicURL\": \"https://lon.dns.api.rackspacecloud.com/v1.0/10001786\"\n                    }\n                ],\n                \"name\": \"cloudDNS\",\n                \"type\": \"rax:dns\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"region\": \"LON\",\n                        \"tenantId\": \"10001786\",\n                        \"publicURL\": \"https://lon.loadbalancers.api.rackspacecloud.com/v1.0/10001786\"\n                    }\n                ],\n                \"name\": \"cloudLoadBalancers\",\n                \"type\": \"rax:load-balancer\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"tenantId\": \"10001786\",\n                        \"publicURL\": \"https://monitoring.api.rackspacecloud.com/v1.0/10001786\"\n                    }\n                ],\n                \"name\": \"cloudMonitoring\",\n                \"type\": \"rax:monitor\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"region\": \"LON\",\n                        \"tenantId\": \"10001786\",\n                        \"publicURL\": \"https://lon.databases.api.rackspacecloud.com/v1.0/10001786\"\n                    }\n                ],\n                \"name\": \"cloudDatabases\",\n                \"type\": \"rax:database\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"region\": \"LON\",\n                        \"tenantId\": \"10001786\",\n                        \"publicURL\": \"https://lon.servers.api.rackspacecloud.com/v2/10001786\",\n                        \"versionInfo\": \"https://lon.servers.api.rackspacecloud.com/v2\",\n                        \"versionList\": \"https://lon.servers.api.rackspacecloud.com/\",\n                        \"versionId\": \"2\"\n                    }\n                ],\n                \"name\": \"cloudServersOpenStack\",\n                \"type\": \"compute\"\n            },\n            {\n                \"endpoints\": [\n                    {\n                        \"publicURL\": \"https://lon.blockstorage.api.rackspacecloud.com/v1/10001786\",\n                        \"tenantId\": \"10001786\",\n                        \"region\": \"LON\"\n                    }\n                ],\n                \"name\": \"cloudBlockStorage\",\n                \"type\": \"volume\"\n            }\n        ],\n        \"user\": {\n            \"id\": \"378\",\n            \"roles\": [\n                {\n                    \"id\": \"3\",\n                    \"description\": \"User Admin Role.\",\n                    \"name\": \"identity:user-admin\"\n                }\n            ],\n            \"name\": \"jclouds\",\n            \"RAX-AUTH:defaultRegion\": \"\"\n        }\n    }\n}\n"
  },
  {
    "path": "providers/rackspace-clouddatabases-uk/src/test/resources/logback.xml",
    "content": "<?xml version=\"1.0\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<configuration scan=\"false\">\n    <appender name=\"FILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <appender name=\"WIREFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds-wire.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <root>\n        <level value=\"warn\" />\n    </root>\n\n    <logger name=\"org.jclouds\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"FILE\" />\n    </logger>\n\n    <logger name=\"jclouds.wire\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n\n    <logger name=\"jclouds.headers\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n\n</configuration>\n"
  },
  {
    "path": "providers/rackspace-clouddatabases-us/README.md",
    "content": "Rackspace Cloud Databases US\n============================\n\nThe Rackspace deployment of OpenStack Trove, the Database as a Service.\n\nProduction ready?\nYes\n"
  },
  {
    "path": "providers/rackspace-clouddatabases-us/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.rackspace.clouddatabases.us.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "providers/rackspace-clouddatabases-us/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.provider</groupId>\n  <artifactId>rackspace-clouddatabases-us</artifactId>\n  <name>jclouds Rackspace Cloud Databases US provider</name>\n  <description>OpenStack Trove implementation targeted to Rackspace Cloud Databases US</description>\n\n  <properties>\n    <test.rackspace-clouddatabases-us.endpoint>https://identity.api.rackspacecloud.com/v2.0/</test.rackspace-clouddatabases-us.endpoint>\n    <test.rackspace-clouddatabases-us.api-version>1</test.rackspace-clouddatabases-us.api-version>\n    <test.rackspace-clouddatabases-us.build-version />\n    <test.rackspace-clouddatabases-us.identity>${test.rackspace-us.identity}</test.rackspace-clouddatabases-us.identity>\n    <test.rackspace-clouddatabases-us.credential>${test.rackspace-us.credential}</test.rackspace-clouddatabases-us.credential>\n    <test.rackspace-clouddatabases-us.template />\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-trove</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-keystone</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>rackspace-cloudidentity</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-trove</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-keystone</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>rackspace-cloudidentity</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-slf4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>ch.qos.logback</groupId>\n      <artifactId>logback-classic</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <forkCount>5</forkCount>\n                  <reuseForks>true</reuseForks>\n                  <parallel>classes</parallel>\n                  <systemPropertyVariables>\n                    <test.rackspace-clouddatabases-us.endpoint>${test.rackspace-clouddatabases-us.endpoint}</test.rackspace-clouddatabases-us.endpoint>\n                    <test.rackspace-clouddatabases-us.api-version>${test.rackspace-clouddatabases-us.api-version}</test.rackspace-clouddatabases-us.api-version>\n                    <test.rackspace-clouddatabases-us.build-version>${test.rackspace-clouddatabases-us.build-version}</test.rackspace-clouddatabases-us.build-version>\n                    <test.rackspace-clouddatabases-us.identity>${test.rackspace-clouddatabases-us.identity}</test.rackspace-clouddatabases-us.identity>\n                    <test.rackspace-clouddatabases-us.credential>${test.rackspace-clouddatabases-us.credential}</test.rackspace-clouddatabases-us.credential>\n                    <test.rackspace-clouddatabases-us.template>${test.rackspace-clouddatabases-us.template}</test.rackspace-clouddatabases-us.template>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n"
  },
  {
    "path": "providers/rackspace-clouddatabases-us/src/main/java/org/jclouds/rackspace/clouddatabases/us/CloudDatabasesUSProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddatabases.us;\n\nimport static org.jclouds.location.reference.LocationConstants.ISO3166_CODES;\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_REGION;\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_REGIONS;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.CREDENTIAL_TYPE;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.KEYSTONE_VERSION;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.SERVICE_TYPE;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.openstack.keystone.catalog.config.ServiceCatalogModule;\nimport org.jclouds.openstack.keystone.catalog.config.ServiceCatalogModule.RegionModule;\nimport org.jclouds.openstack.trove.v1.TroveApiMetadata;\nimport org.jclouds.openstack.trove.v1.config.TroveHttpApiModule;\nimport org.jclouds.openstack.trove.v1.config.TroveParserModule;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\nimport org.jclouds.rackspace.cloudidentity.v2_0.ServiceType;\nimport org.jclouds.rackspace.cloudidentity.v2_0.config.CloudIdentityAuthenticationModule;\nimport org.jclouds.rackspace.cloudidentity.v2_0.config.CloudIdentityCredentialTypes;\n\nimport com.google.auto.service.AutoService;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n/**\n * Implementation of {@link ProviderMetadata} for Rackspace Cloud Databases.\n */\n@AutoService(ProviderMetadata.class)\npublic class CloudDatabasesUSProviderMetadata extends BaseProviderMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromProviderMetadata(this);\n   }\n\n   public CloudDatabasesUSProviderMetadata() {\n      super(builder());\n   }\n\n   public CloudDatabasesUSProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = new Properties();\n      properties.setProperty(CREDENTIAL_TYPE, CloudIdentityCredentialTypes.API_KEY_CREDENTIALS);\n      properties.setProperty(KEYSTONE_VERSION, \"2\");\n      properties.setProperty(SERVICE_TYPE, ServiceType.DATABASES);\n      properties.setProperty(PROPERTY_REGIONS, \"ORD,DFW,IAD,SYD,HKG\");\n      properties.setProperty(PROPERTY_REGION + \".ORD.\" + ISO3166_CODES, \"US-IL\");\n      properties.setProperty(PROPERTY_REGION + \".DFW.\" + ISO3166_CODES, \"US-TX\");\n      properties.setProperty(PROPERTY_REGION + \".IAD.\" + ISO3166_CODES, \"US-VA\");\n      properties.setProperty(PROPERTY_REGION + \".SYD.\" + ISO3166_CODES, \"AU-NSW\");\n      properties.setProperty(PROPERTY_REGION + \".HKG.\" + ISO3166_CODES, \"HK\");\n      return properties;\n   }\n\n   public static class Builder extends BaseProviderMetadata.Builder {\n\n      protected Builder(){\n         id(\"rackspace-clouddatabases-us\")\n         .name(\"Rackspace Clouddatabases US\")\n         .apiMetadata(new TroveApiMetadata().toBuilder()\n                  .identityName(\"${userName}\")\n                  .credentialName(\"${apiKey}\")\n                  .defaultEndpoint(\"https://identity.api.rackspacecloud.com/v2.0/\")\n                  .endpointName(\"identity service url ending in /v2.0/\")\n                  .documentation(URI.create(\"http://docs.rackspace.com/cbs/api/v1.0/cbs-devguide/content/overview.html\"))\n                  .defaultModules(ImmutableSet.<Class<? extends Module>>builder()\n                                              .add(CloudIdentityAuthenticationModule.class)\n                                              .add(ServiceCatalogModule.class)\n                                              .add(RegionModule.class)\n                                              .add(TroveParserModule.class)\n                                              .add(TroveHttpApiModule.class).build())\n                  .build())\n         .homepage(URI.create(\"http://www.rackspace.com/cloud/public/databases/\"))\n         .console(URI.create(\"https://mycloud.rackspace.com\"))\n         .linkedServices(\"rackspace-cloudservers-us\", \"cloudfiles-us\")\n         .iso3166Codes(\"US-IL\", \"US-TX\")\n         .endpoint(\"https://identity.api.rackspacecloud.com/v2.0/\")\n         .defaultProperties(CloudDatabasesUSProviderMetadata.defaultProperties());\n      }\n\n      @Override\n      public CloudDatabasesUSProviderMetadata build() {\n         return new CloudDatabasesUSProviderMetadata(this);\n      }\n\n      @Override\n      public Builder fromProviderMetadata(ProviderMetadata in) {\n         super.fromProviderMetadata(in);\n         return this;\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/rackspace-clouddatabases-us/src/test/java/org/jclouds/rackspace/clouddatabases/us/CloudDatabasesUSProviderMetadataExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddatabases.us;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.trove.v1.TroveApi;\nimport org.jclouds.openstack.trove.v1.internal.BaseTroveApiExpectTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * This test ensures that the wiring in {@link CloudDatabasesUSProviderMetadata} is correct.\n */\n@Test(groups = \"unit\", testName = \"CloudDatabasesUSProviderMetadataExpectTest\")\npublic class CloudDatabasesUSProviderMetadataExpectTest extends BaseTroveApiExpectTest {\n\n   public CloudDatabasesUSProviderMetadataExpectTest() {\n      this.provider = \"rackspace-clouddatabases-us\";\n      this.identity = \"myUsername\";\n      this.credential = \"myApiKey\";\n   }\n\n   public void testCanGetConfiguredRegions() {\n\n      HttpRequest authenticate = HttpRequest.builder().method(\"POST\")\n            .endpoint(\"https://identity.api.rackspacecloud.com/v2.0/tokens\")\n            .addHeader(\"Accept\", \"application/json\")\n            .payload(payloadFromStringWithContentType(\n                     \"{\\\"auth\\\":{\\\"RAX-KSKEY:apiKeyCredentials\\\":{\\\"username\\\":\\\"myUsername\\\",\\\"apiKey\\\":\\\"myApiKey\\\"}}}\",\n                    \"application/json\")).build();\n\n\n      HttpResponse authenticationResponse = HttpResponse.builder()\n            .statusCode(200)\n            .payload(payloadFromResourceWithContentType(\"/access_rax_us.json\", \"application/json\"))\n            .build();\n\n      TroveApi whenRegionExists = requestSendsResponse(authenticate, authenticationResponse);\n\n      assertEquals(whenRegionExists.getConfiguredRegions(), ImmutableSet.of(\"ORD\", \"DFW\", \"SYD\"));\n\n   }\n\n}\n"
  },
  {
    "path": "providers/rackspace-clouddatabases-us/src/test/java/org/jclouds/rackspace/clouddatabases/us/CloudDatabasesUSProviderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddatabases.us;\n\nimport org.jclouds.openstack.trove.v1.TroveApiMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"CloudDatabasesUSProviderTest\")\npublic class CloudDatabasesUSProviderTest extends BaseProviderMetadataTest {\n\n   public CloudDatabasesUSProviderTest() {\n      super(new CloudDatabasesUSProviderMetadata(), new TroveApiMetadata());\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-clouddatabases-us/src/test/java/org/jclouds/rackspace/clouddatabases/us/features/CloudDatabasesUSDatabaseApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddatabases.us.features;\n\nimport org.jclouds.openstack.trove.v1.features.DatabaseApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"CloudDatabasesUSDatabaseApiLiveTest\")\npublic class CloudDatabasesUSDatabaseApiLiveTest extends DatabaseApiLiveTest {\n   public CloudDatabasesUSDatabaseApiLiveTest() {\n      provider = \"rackspace-clouddatabases-us\";\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-clouddatabases-us/src/test/java/org/jclouds/rackspace/clouddatabases/us/features/CloudDatabasesUSFlavorApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddatabases.us.features;\n\nimport org.jclouds.openstack.trove.v1.features.FlavorApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"CloudDatabasesUSFlavorApiLiveTest\")\npublic class CloudDatabasesUSFlavorApiLiveTest extends FlavorApiLiveTest {\n   public CloudDatabasesUSFlavorApiLiveTest() {\n      provider = \"rackspace-clouddatabases-us\";\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-clouddatabases-us/src/test/java/org/jclouds/rackspace/clouddatabases/us/features/CloudDatabasesUSInstanceApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddatabases.us.features;\n\nimport org.jclouds.openstack.trove.v1.features.InstanceApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"CloudDatabasesUSInstanceApiLiveTest\")\npublic class CloudDatabasesUSInstanceApiLiveTest extends InstanceApiLiveTest {\n   public CloudDatabasesUSInstanceApiLiveTest() {\n      provider = \"rackspace-clouddatabases-us\";\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-clouddatabases-us/src/test/java/org/jclouds/rackspace/clouddatabases/us/features/CloudDatabasesUSUserApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddatabases.us.features;\n\nimport org.jclouds.openstack.trove.v1.features.UserApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"CloudDatabasesUSUserApiLiveTest\")\npublic class CloudDatabasesUSUserApiLiveTest extends UserApiLiveTest {\n   public CloudDatabasesUSUserApiLiveTest() {\n      provider = \"rackspace-clouddatabases-us\";\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-clouddatabases-us/src/test/resources/logback.xml",
    "content": "<?xml version=\"1.0\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<configuration scan=\"false\">\n    <appender name=\"FILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <appender name=\"WIREFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds-wire.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <root>\n        <level value=\"warn\" />\n    </root>\n\n    <logger name=\"org.jclouds\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"FILE\" />\n    </logger>\n\n    <logger name=\"jclouds.wire\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n\n    <logger name=\"jclouds.headers\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n\n</configuration>\n"
  },
  {
    "path": "providers/rackspace-clouddns-uk/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.rackspace.clouddns.uk.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "providers/rackspace-clouddns-uk/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.provider</groupId>\n  <artifactId>rackspace-clouddns-uk</artifactId>\n  <name>jclouds Rackspace Next Generation Cloud DNS UK provider</name>\n  <description>Rackspace Next Generation Cloud DNS UK</description>\n\n  <properties>\n    <test.rackspace-clouddns-uk.endpoint>https://lon.identity.api.rackspacecloud.com/v2.0/</test.rackspace-clouddns-uk.endpoint>\n    <test.rackspace-clouddns-uk.api-version>1.0</test.rackspace-clouddns-uk.api-version>\n    <test.rackspace-clouddns-uk.build-version />\n    <test.rackspace-clouddns-uk.identity>${test.rackspace-uk.identity}</test.rackspace-clouddns-uk.identity>\n    <test.rackspace-clouddns-uk.credential>${test.rackspace-uk.credential}</test.rackspace-clouddns-uk.credential>\n    <test.rackspace-clouddns-uk.template />\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-keystone</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>rackspace-clouddns</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>rackspace-cloudidentity</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-keystone</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>rackspace-clouddns</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>rackspace-cloudidentity</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-slf4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>ch.qos.logback</groupId>\n      <artifactId>logback-classic</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <threadCount>1</threadCount>\n                  <systemPropertyVariables>\n                    <test.rackspace-clouddns-uk.endpoint>${test.rackspace-clouddns-uk.endpoint}</test.rackspace-clouddns-uk.endpoint>\n                    <test.rackspace-clouddns-uk.api-version>${test.rackspace-clouddns-uk.api-version}</test.rackspace-clouddns-uk.api-version>\n                    <test.rackspace-clouddns-uk.build-version>${test.rackspace-clouddns-uk.build-version}</test.rackspace-clouddns-uk.build-version>\n                    <test.rackspace-clouddns-uk.identity>${test.rackspace-clouddns-uk.identity}</test.rackspace-clouddns-uk.identity>\n                    <test.rackspace-clouddns-uk.credential>${test.rackspace-clouddns-uk.credential}</test.rackspace-clouddns-uk.credential>\n                    <test.rackspace-clouddns-uk.template>${test.rackspace-clouddns-uk.template}</test.rackspace-clouddns-uk.template>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n"
  },
  {
    "path": "providers/rackspace-clouddns-uk/src/main/java/org/jclouds/rackspace/clouddns/uk/CloudDNSUKProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.uk;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\nimport org.jclouds.rackspace.clouddns.v1.CloudDNSApiMetadata;\n\nimport com.google.auto.service.AutoService;\n\n/**\n * Implementation of {@link ProviderMetadata} for Rackspace DNS UK.\n */\n@AutoService(ProviderMetadata.class)\npublic class CloudDNSUKProviderMetadata extends BaseProviderMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromProviderMetadata(this);\n   }\n   \n   public CloudDNSUKProviderMetadata() {\n      super(builder());\n   }\n\n   public CloudDNSUKProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = new Properties();\n      return properties;\n   }\n   \n   public static class Builder extends BaseProviderMetadata.Builder {\n\n      protected Builder() {\n         id(\"rackspace-clouddns-uk\")\n         .name(\"Rackspace Cloud DNS UK\")\n         .apiMetadata(new CloudDNSApiMetadata().toBuilder()\n                  .defaultEndpoint(\"https://lon.identity.api.rackspacecloud.com/v2.0/\")\n                  .build())\n         .homepage(URI.create(\"http://www.rackspace.com/cloud/public/dns/\"))\n         .console(URI.create(\"https://mycloud.rackspace.com\"))\n         .linkedServices(\"rackspace-cloudidentity\", \"rackspace-cloudservers-uk\", \"cloudfiles-uk\", \"rackspace-cloudblockstorage-uk\", \"rackspace-cloudloadbalancers-uk\")\n         .iso3166Codes(\"GB-SLG\")\n         .endpoint(\"https://lon.identity.api.rackspacecloud.com/v2.0/\")\n         .defaultProperties(CloudDNSApiMetadata.defaultProperties());\n      }\n\n      @Override\n      public CloudDNSUKProviderMetadata build() {\n         return new CloudDNSUKProviderMetadata(this);\n      }\n      \n      @Override\n      public Builder fromProviderMetadata(\n            ProviderMetadata in) {\n         super.fromProviderMetadata(in);\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-clouddns-uk/src/test/java/org/jclouds/rackspace/clouddns/uk/features/CloudDNSUKDomainApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.uk.features;\n\nimport org.jclouds.rackspace.clouddns.v1.features.DomainApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"CloudDNSUKDomainApiLiveTest\")\npublic class CloudDNSUKDomainApiLiveTest extends DomainApiLiveTest {\n   public CloudDNSUKDomainApiLiveTest() {\n      provider = \"rackspace-clouddns-uk\";\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-clouddns-uk/src/test/java/org/jclouds/rackspace/clouddns/uk/features/CloudDNSUKLimitApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.uk.features;\n\nimport org.jclouds.rackspace.clouddns.v1.features.LimitApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"CloudDNSUKLimitApiLiveTest\")\npublic class CloudDNSUKLimitApiLiveTest extends LimitApiLiveTest {\n   public CloudDNSUKLimitApiLiveTest() {\n      provider = \"rackspace-clouddns-uk\";\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-clouddns-uk/src/test/java/org/jclouds/rackspace/clouddns/uk/features/CloudDNSUKProviderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.uk.features;\n\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.jclouds.rackspace.clouddns.uk.CloudDNSUKProviderMetadata;\nimport org.jclouds.rackspace.clouddns.v1.CloudDNSApiMetadata;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"CloudDNSUKProviderTest\")\npublic class CloudDNSUKProviderTest extends BaseProviderMetadataTest {\n\n   public CloudDNSUKProviderTest() {\n      super(new CloudDNSUKProviderMetadata(), new CloudDNSApiMetadata());\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-clouddns-uk/src/test/java/org/jclouds/rackspace/clouddns/uk/features/CloudDNSUKRecordApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.uk.features;\n\nimport org.jclouds.rackspace.clouddns.v1.features.RecordApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"CloudDNSUKRecordApiLiveTest\")\npublic class CloudDNSUKRecordApiLiveTest extends RecordApiLiveTest {\n   public CloudDNSUKRecordApiLiveTest() {\n      provider = \"rackspace-clouddns-uk\";\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-clouddns-us/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.rackspace.clouddns.us.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "providers/rackspace-clouddns-us/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.provider</groupId>\n  <artifactId>rackspace-clouddns-us</artifactId>\n  <name>jclouds Rackspace Next Generation Cloud DNS US provider</name>\n  <description>Rackspace Next Generation Cloud DNS US</description>\n\n  <properties>\n    <test.rackspace-clouddns-us.endpoint>https://identity.api.rackspacecloud.com/v2.0/</test.rackspace-clouddns-us.endpoint>\n    <test.rackspace-clouddns-us.api-version>1.0</test.rackspace-clouddns-us.api-version>\n    <test.rackspace-clouddns-us.build-version />\n    <test.rackspace-clouddns-us.identity>${test.rackspace-us.identity}</test.rackspace-clouddns-us.identity>\n    <test.rackspace-clouddns-us.credential>${test.rackspace-us.credential}</test.rackspace-clouddns-us.credential>\n    <test.rackspace-clouddns-us.template />\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-keystone</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>rackspace-clouddns</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>rackspace-cloudidentity</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-keystone</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-nova</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>rackspace-clouddns</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>rackspace-cloudidentity</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.provider</groupId>\n      <artifactId>rackspace-cloudservers-us</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-slf4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>ch.qos.logback</groupId>\n      <artifactId>logback-classic</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <threadCount>1</threadCount>\n                  <systemPropertyVariables>\n                    <test.rackspace-clouddns-us.endpoint>${test.rackspace-clouddns-us.endpoint}</test.rackspace-clouddns-us.endpoint>\n                    <test.rackspace-clouddns-us.api-version>${test.rackspace-clouddns-us.api-version}</test.rackspace-clouddns-us.api-version>\n                    <test.rackspace-clouddns-us.build-version>${test.rackspace-clouddns-us.build-version}</test.rackspace-clouddns-us.build-version>\n                    <test.rackspace-clouddns-us.identity>${test.rackspace-clouddns-us.identity}</test.rackspace-clouddns-us.identity>\n                    <test.rackspace-clouddns-us.credential>${test.rackspace-clouddns-us.credential}</test.rackspace-clouddns-us.credential>\n                    <test.rackspace-clouddns-us.template>${test.rackspace-clouddns-us.template}</test.rackspace-clouddns-us.template>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n"
  },
  {
    "path": "providers/rackspace-clouddns-us/src/main/java/org/jclouds/rackspace/clouddns/us/CloudDNSUSProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.us;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\nimport org.jclouds.rackspace.clouddns.v1.CloudDNSApiMetadata;\n\nimport com.google.auto.service.AutoService;\n\n/**\n * Implementation of {@link ProviderMetadata} for Rackspace DNS US.\n */\n@AutoService(ProviderMetadata.class)\npublic class CloudDNSUSProviderMetadata extends BaseProviderMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromProviderMetadata(this);\n   }\n   \n   public CloudDNSUSProviderMetadata() {\n      super(builder());\n   }\n\n   public CloudDNSUSProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = new Properties();\n      return properties;\n   }\n   \n   public static class Builder extends BaseProviderMetadata.Builder {\n\n      protected Builder() {\n         id(\"rackspace-clouddns-us\")\n         .name(\"Rackspace Cloud DNS US\")\n         .apiMetadata(new CloudDNSApiMetadata().toBuilder()\n                  .defaultEndpoint(\"https://identity.api.rackspacecloud.com/v2.0/\")\n                  .build())\n         .homepage(URI.create(\"http://www.rackspace.com/cloud/public/dns/\"))\n         .console(URI.create(\"https://mycloud.rackspace.com\"))\n         .linkedServices(\"rackspace-cloudidentity\", \"rackspace-cloudservers-us\", \"cloudfiles-us\", \"rackspace-cloudblockstorage-us\", \"rackspace-cloudloadbalancers-us\")\n         .iso3166Codes(\"US-TX\")\n         .endpoint(\"https://identity.api.rackspacecloud.com/v2.0/\")\n         .defaultProperties(CloudDNSApiMetadata.defaultProperties());\n      }\n\n      @Override\n      public CloudDNSUSProviderMetadata build() {\n         return new CloudDNSUSProviderMetadata(this);\n      }\n      \n      @Override\n      public Builder fromProviderMetadata(\n            ProviderMetadata in) {\n         super.fromProviderMetadata(in);\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-clouddns-us/src/test/java/org/jclouds/rackspace/clouddns/us/features/CloudDNSUSDomainApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.us.features;\n\nimport org.jclouds.rackspace.clouddns.v1.features.DomainApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"CloudDNSUSDomainApiLiveTest\")\npublic class CloudDNSUSDomainApiLiveTest extends DomainApiLiveTest {\n   public CloudDNSUSDomainApiLiveTest() {\n      provider = \"rackspace-clouddns-us\";\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-clouddns-us/src/test/java/org/jclouds/rackspace/clouddns/us/features/CloudDNSUSLimitApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.us.features;\n\nimport org.jclouds.rackspace.clouddns.v1.features.LimitApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"CloudDNSUSLimitApiLiveTest\")\npublic class CloudDNSUSLimitApiLiveTest extends LimitApiLiveTest {\n   public CloudDNSUSLimitApiLiveTest() {\n      provider = \"rackspace-clouddns-us\";\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-clouddns-us/src/test/java/org/jclouds/rackspace/clouddns/us/features/CloudDNSUSProviderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.us.features;\n\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.jclouds.rackspace.clouddns.us.CloudDNSUSProviderMetadata;\nimport org.jclouds.rackspace.clouddns.v1.CloudDNSApiMetadata;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"CloudDNSUSProviderTest\")\npublic class CloudDNSUSProviderTest extends BaseProviderMetadataTest {\n\n   public CloudDNSUSProviderTest() {\n      super(new CloudDNSUSProviderMetadata(), new CloudDNSApiMetadata());\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-clouddns-us/src/test/java/org/jclouds/rackspace/clouddns/us/features/CloudDNSUSRecordApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.us.features;\n\nimport org.jclouds.rackspace.clouddns.v1.features.RecordApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"CloudDNSUSRecordApiLiveTest\")\npublic class CloudDNSUSRecordApiLiveTest extends RecordApiLiveTest {\n   public CloudDNSUSRecordApiLiveTest() {\n      provider = \"rackspace-clouddns-us\";\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-clouddns-us/src/test/java/org/jclouds/rackspace/clouddns/us/features/CloudDNSUSReverseDNSApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.clouddns.us.features;\n\nimport org.jclouds.rackspace.clouddns.v1.features.ReverseDNSApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"CloudDNSUSReverseDNSApiLiveTest\")\npublic class CloudDNSUSReverseDNSApiLiveTest extends ReverseDNSApiLiveTest {\n   public CloudDNSUSReverseDNSApiLiveTest() {\n      provider = \"rackspace-clouddns-us\";\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudfiles-uk/README.md",
    "content": "Rackspace Cloud Files UK\n========================\n\nThe new Rackspace Cloud Files UK multi-region based provider.\n\nThis new \"rackspace-cloudfiles-uk\" provider supercedes the jclouds \"cloudfiles-uk\" provider, which will eventually be deprecated.\n\nWith this multi-region support, a BlobStore can be isolated to a specific region:\n\n     RegionScopedBlobStoreContext ctx = \n     \tcontextBuilder.buildView(RegionScopedBlobStoreContext.class);\n \n     Set<String> regionIds = ctx.configuredRegions();\n \n     // isolated to the only UK region\n     BlobStore dfwBlobStore = ctx.blobStoreInRegion(\"LON\");\n\nProduction ready?\nBeta\n\nThis API is new to jclouds and hence is in Beta. That means we need people to use it and give us feedback. Based on that feedback, minor changes to the interfaces may happen. This code will replace org.jclouds.openstack.swift.SwiftClient in jclouds 2.0 and it is recommended you adopt it sooner than later.\n"
  },
  {
    "path": "providers/rackspace-cloudfiles-uk/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.rackspace.cloudfiles.uk.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "providers/rackspace-cloudfiles-uk/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n\n  <groupId>org.apache.jclouds.provider</groupId>\n  <artifactId>rackspace-cloudfiles-uk</artifactId>\n  <version>2.7.1-SNAPSHOT</version>\n  <name>jclouds Rackspace Cloud Files UK provider</name>\n  <description>OpenStack Object Storage implementation targeted to Rackspace Cloud Files UK</description>\n\n  <properties>\n    <!-- identity endpoint -->\n    <test.rackspace-cloudfiles-uk.endpoint>https://lon.identity.api.rackspacecloud.com/v2.0/</test.rackspace-cloudfiles-uk.endpoint>\n    <test.rackspace-cloudfiles-uk.api-version>1</test.rackspace-cloudfiles-uk.api-version>\n    <test.rackspace-cloudfiles-uk.build-version />\n    <test.rackspace-cloudfiles-uk.identity>${test.rackspace-uk.identity}</test.rackspace-cloudfiles-uk.identity>\n    <test.rackspace-cloudfiles-uk.credential>${test.rackspace-uk.credential}</test.rackspace-cloudfiles-uk.credential>\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-swift</artifactId>\n      <version>${project.parent.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-swift</artifactId>\n      <version>${project.parent.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>rackspace-cloudfiles</artifactId>\n      <version>${project.parent.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>rackspace-cloudfiles</artifactId>\n      <version>${project.parent.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-keystone</artifactId>\n      <version>${project.parent.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-keystone</artifactId>\n      <version>${project.parent.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-blobstore</artifactId>\n      <version>${project.parent.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.parent.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.parent.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-slf4j</artifactId>\n      <version>${project.parent.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>ch.qos.logback</groupId>\n      <artifactId>logback-classic</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>rackspace-cloudidentity</artifactId>\n      <version>${project.parent.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <scope>provided</scope>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <jclouds.blobstore.httpstream.url>${jclouds.blobstore.httpstream.url}</jclouds.blobstore.httpstream.url>\n                    <jclouds.blobstore.httpstream.md5>${jclouds.blobstore.httpstream.md5}</jclouds.blobstore.httpstream.md5>\n                    <test.rackspace-cloudfiles-uk.endpoint>${test.rackspace-cloudfiles-uk.endpoint}</test.rackspace-cloudfiles-uk.endpoint>\n                    <test.rackspace-cloudfiles-uk.api-version>${test.rackspace-cloudfiles-uk.api-version}</test.rackspace-cloudfiles-uk.api-version>\n                    <test.rackspace-cloudfiles-uk.build-version>${test.rackspace-cloudfiles-uk.build-version}</test.rackspace-cloudfiles-uk.build-version>\n                    <test.rackspace-cloudfiles-uk.identity>${test.rackspace-cloudfiles-uk.identity}</test.rackspace-cloudfiles-uk.identity>\n                    <test.rackspace-cloudfiles-uk.credential>${test.rackspace-cloudfiles-uk.credential}</test.rackspace-cloudfiles-uk.credential>\n                    <jclouds.blobstore.httpstream.url>${jclouds.blobstore.httpstream.url}</jclouds.blobstore.httpstream.url>\n                    <jclouds.blobstore.httpstream.md5>${jclouds.blobstore.httpstream.md5}</jclouds.blobstore.httpstream.md5>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n"
  },
  {
    "path": "providers/rackspace-cloudfiles-uk/src/main/java/org/jclouds/rackspace/cloudfiles/uk/CloudFilesUKProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.uk;\n\nimport static org.jclouds.location.reference.LocationConstants.ISO3166_CODES;\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_REGION;\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_REGIONS;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.CREDENTIAL_TYPE;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.KEYSTONE_VERSION;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.SERVICE_TYPE;\nimport static org.jclouds.reflect.Reflection2.typeToken;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.openstack.keystone.catalog.config.ServiceCatalogModule;\nimport org.jclouds.openstack.keystone.catalog.config.ServiceCatalogModule.RegionModule;\nimport org.jclouds.openstack.swift.v1.blobstore.RegionScopedBlobStoreContext;\nimport org.jclouds.openstack.swift.v1.blobstore.config.SignUsingTemporaryUrls;\nimport org.jclouds.openstack.swift.v1.blobstore.config.SwiftBlobStoreContextModule;\nimport org.jclouds.openstack.swift.v1.config.SwiftTypeAdapters;\nimport org.jclouds.openstack.v2_0.ServiceType;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\nimport org.jclouds.rackspace.cloudfiles.v1.CloudFilesApiMetadata;\nimport org.jclouds.rackspace.cloudfiles.v1.config.CloudFilesHttpApiModule;\nimport org.jclouds.rackspace.cloudidentity.v2_0.config.CloudIdentityAuthenticationModule;\nimport org.jclouds.rackspace.cloudidentity.v2_0.config.CloudIdentityCredentialTypes;\n\nimport com.google.auto.service.AutoService;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n@AutoService(ProviderMetadata.class)\npublic class CloudFilesUKProviderMetadata extends BaseProviderMetadata {\n   \n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromProviderMetadata(this);\n   }\n\n   public CloudFilesUKProviderMetadata() {\n      this(new Builder());\n   }\n\n   protected CloudFilesUKProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = new Properties();\n      properties.setProperty(CREDENTIAL_TYPE, CloudIdentityCredentialTypes.API_KEY_CREDENTIALS);\n      properties.setProperty(SERVICE_TYPE, ServiceType.OBJECT_STORE); \n      properties.setProperty(KEYSTONE_VERSION, \"2\"); \n\n      properties.setProperty(PROPERTY_REGIONS, \"LON\");\n      properties.setProperty(PROPERTY_REGION + \".LON.\" + ISO3166_CODES, \"GB-SLG\");\n\n      return properties;\n   }\n\n   public static class Builder extends BaseProviderMetadata.Builder {\n\n      protected Builder() {\n         id(\"rackspace-cloudfiles-uk\")\n         .name(\"Rackspace Cloud Files UK\")\n         .apiMetadata(new CloudFilesApiMetadata().toBuilder()\n               .identityName(\"${userName}\")\n               .credentialName(\"${apiKey}\")\n               .defaultEndpoint(\"https://lon.identity.api.rackspacecloud.com/v2.0/\")\n               .documentation(URI.create(\"http://docs.rackspace.com/files/api/v1/cf-devguide/content/index.html\"))\n               .endpointName(\"Rackspace Cloud Identity service URL ending in /v2.0/\")\n               .version(\"1.0\")\n               .view(typeToken(RegionScopedBlobStoreContext.class))\n               .defaultModules(ImmutableSet.<Class<? extends Module>>builder()\n                     .add(CloudIdentityAuthenticationModule.class)\n                     .add(ServiceCatalogModule.class)\n                     .add(RegionModule.class)\n                     .add(SwiftTypeAdapters.class)\n                     .add(CloudFilesHttpApiModule.class)\n                     .add(SwiftBlobStoreContextModule.class)\n                     .add(SignUsingTemporaryUrls.class)\n                     .build())\n               .build())\n         .homepage(URI.create(\"http://www.rackspace.co.uk/cloud/files/\"))\n         .console(URI.create(\"https://mycloud.rackspace.co.uk\"))\n         .linkedServices(\"rackspace-autoscale-uk\", \"rackspace-cloudblockstorage-uk\",\n                         \"rackspace-clouddatabases-uk\", \"rackspace-clouddns-uk\",\n                         \"rackspace-cloudidentity\", \"rackspace-cloudloadbalancers-uk\",\n                         \"rackspace-cloudqueues-uk\")\n         .iso3166Codes(\"GB-SLG\")\n         .defaultProperties(CloudFilesUKProviderMetadata.defaultProperties());\n         \n      }\n\n      @Override\n      public CloudFilesUKProviderMetadata build() {\n         return new CloudFilesUKProviderMetadata(this);\n      }\n\n      @Override\n      public Builder fromProviderMetadata(ProviderMetadata in) {\n         super.fromProviderMetadata(in);\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudfiles-uk/src/test/java/org/jclouds/rackspace/cloudfiles/uk/CloudFilesUKProviderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.uk;\n\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.jclouds.rackspace.cloudfiles.v1.CloudFilesApiMetadata;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"CloudFilesUKProviderTest\")\npublic class CloudFilesUKProviderTest extends BaseProviderMetadataTest {\n   public CloudFilesUKProviderTest() {\n      super(new CloudFilesUKProviderMetadata(), new CloudFilesApiMetadata());\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudfiles-uk/src/test/java/org/jclouds/rackspace/cloudfiles/uk/blobstore/integration/CloudFilesUKBlobIntegrationLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.uk.blobstore.integration;\n\nimport org.jclouds.rackspace.cloudfiles.v1.blobstore.integration.CloudFilesBlobIntegrationLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"CloudFilesUKBlobIntegrationLiveTest\")\npublic class CloudFilesUKBlobIntegrationLiveTest extends CloudFilesBlobIntegrationLiveTest {\n   public CloudFilesUKBlobIntegrationLiveTest() {\n      provider = \"rackspace-cloudfiles-uk\";\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudfiles-uk/src/test/java/org/jclouds/rackspace/cloudfiles/uk/blobstore/integration/CloudFilesUKBlobLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.uk.blobstore.integration;\n\nimport org.jclouds.rackspace.cloudfiles.v1.blobstore.integration.CloudFilesBlobLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"CloudFilesUKBlobLiveTest\")\npublic class CloudFilesUKBlobLiveTest extends CloudFilesBlobLiveTest {\n   public CloudFilesUKBlobLiveTest() {\n      provider = \"rackspace-cloudfiles-uk\";\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudfiles-uk/src/test/java/org/jclouds/rackspace/cloudfiles/uk/blobstore/integration/CloudFilesUKBlobSignerLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.uk.blobstore.integration;\n\nimport org.jclouds.rackspace.cloudfiles.v1.blobstore.integration.CloudFilesBlobSignerLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"CloudFilesUKBlobSignerLiveTest\")\npublic class CloudFilesUKBlobSignerLiveTest extends CloudFilesBlobSignerLiveTest {\n   public CloudFilesUKBlobSignerLiveTest() {\n      provider = \"rackspace-cloudfiles-uk\";\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudfiles-uk/src/test/java/org/jclouds/rackspace/cloudfiles/uk/blobstore/integration/CloudFilesUKContainerIntegrationLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.uk.blobstore.integration;\n\nimport org.jclouds.rackspace.cloudfiles.v1.blobstore.integration.CloudFilesContainerIntegrationLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"CloudFilesUKContainerIntegrationLiveTest\")\npublic class CloudFilesUKContainerIntegrationLiveTest extends CloudFilesContainerIntegrationLiveTest {\n   public CloudFilesUKContainerIntegrationLiveTest() {\n      provider = \"rackspace-cloudfiles-uk\";\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudfiles-uk/src/test/java/org/jclouds/rackspace/cloudfiles/uk/blobstore/integration/CloudFilesUKContainerLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.uk.blobstore.integration;\n\nimport org.jclouds.rackspace.cloudfiles.v1.blobstore.integration.CloudFilesContainerLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"CloudFilesUKContainerLiveTest\")\npublic class CloudFilesUKContainerLiveTest extends CloudFilesContainerLiveTest {\n   public CloudFilesUKContainerLiveTest() {\n      provider = \"rackspace-cloudfiles-uk\";\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudfiles-uk/src/test/java/org/jclouds/rackspace/cloudfiles/uk/blobstore/integration/CloudFilesUKServiceIntegrationLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.uk.blobstore.integration;\n\nimport java.util.Set;\n\nimport org.jclouds.rackspace.cloudfiles.v1.blobstore.integration.CloudFilesServiceIntegrationLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"live\", testName = \"CloudFilesUKServiceIntegrationLiveTest\")\npublic class CloudFilesUKServiceIntegrationLiveTest extends CloudFilesServiceIntegrationLiveTest {\n   public CloudFilesUKServiceIntegrationLiveTest() {\n      provider = \"rackspace-cloudfiles-uk\";\n   }\n\n   @Override\n   protected Set<String> getIso3166Codes() {\n      return ImmutableSet.<String> of(\"GB-SLG\");\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudfiles-uk/src/test/java/org/jclouds/rackspace/cloudfiles/uk/features/CloudFilesUKDynamicLargeObjectApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.uk.features;\n\nimport org.jclouds.rackspace.cloudfiles.v1.features.CloudFilesDynamicLargeObjectApiLiveTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests the live behavior of the OpenStack Object Storage {@link DynamicLargeObjectApi}\n * via the {@link CloudFilesApi}.\n */\n@Test(groups = \"live\", testName = \"CloudFilesUKDynamicLargeObjectApiLiveTest\")\npublic final class CloudFilesUKDynamicLargeObjectApiLiveTest extends CloudFilesDynamicLargeObjectApiLiveTest {\n   public CloudFilesUKDynamicLargeObjectApiLiveTest() {\n      provider = \"rackspace-cloudfiles-uk\";\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudfiles-uk/src/test/java/org/jclouds/rackspace/cloudfiles/uk/features/CloudFilesUKObjectApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.uk.features;\n\nimport org.jclouds.rackspace.cloudfiles.v1.features.CloudFilesObjectApiLiveTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests the live behavior of the OpenStack Object Storage {@link ObjectApi}\n * via the {@link CloudFilesApi}.\n */\n@Test(groups = \"live\", testName = \"CloudFilesUKObjectApiLiveTest\")\npublic class CloudFilesUKObjectApiLiveTest extends CloudFilesObjectApiLiveTest {\n   public CloudFilesUKObjectApiLiveTest() {\n      provider = \"rackspace-cloudfiles-uk\";\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudfiles-uk/src/test/java/org/jclouds/rackspace/cloudfiles/uk/features/CloudFilesUKStaticLargeObjectApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.uk.features;\n\nimport org.jclouds.rackspace.cloudfiles.v1.features.CloudFilesStaticLargeObjectApiLiveTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests the live behavior of the OpenStack Object Storage {@link StaticLargeObjectApi}\n * via the {@link CloudFilesApi}.\n */\n@Test(groups = \"live\", testName = \"CloudFilesUKStaticLargeObjectApiLiveTest\")\npublic class CloudFilesUKStaticLargeObjectApiLiveTest extends CloudFilesStaticLargeObjectApiLiveTest {\n   public CloudFilesUKStaticLargeObjectApiLiveTest() {\n      provider = \"rackspace-cloudfiles-uk\";\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudfiles-uk/src/test/resources/logback.xml",
    "content": "<?xml version=\"1.0\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<configuration scan=\"false\">\n    <appender name=\"FILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <appender name=\"WIREFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds-wire.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <appender name=\"BLOBSTOREFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds-blobstore.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n    \n    <root>\n        <level value=\"warn\" />\n    </root>\n\n    <logger name=\"org.jclouds\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"FILE\" />\n    </logger>\n\n<!--\n    <logger name=\"jclouds.wire\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n-->\n\n    <logger name=\"jclouds.headers\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n\n    <logger name=\"jclouds.blobstore\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"BLOBSTOREFILE\" />\n    </logger>\n\n</configuration>\n"
  },
  {
    "path": "providers/rackspace-cloudfiles-us/README.md",
    "content": "Rackspace Cloud Files US\n========================\n\nThe new Rackspace Cloud Files US multi-region based provider.\n\nThis new \"rackspace-cloudfiles-us\" provider supercedes the jclouds \"cloudfiles-us\" provider, which will eventually be deprecated.\n\nWith this multi-region support, each BlobStore can be isolated to a specific region:\n\n     RegionScopedBlobStoreContext ctx = \n     \tcontextBuilder.buildView(RegionScopedBlobStoreContext.class);\n \n     Set<String> regionIds = ctx.configuredRegions();\n \n     // isolated to a specific region\n     BlobStore dfwBlobStore = ctx.blobStoreInRegion(\"DFW\");\n     BlobStore iadBlobStore = ctx.blobStoreInRegion(\"IAD\");\n\nProduction ready?\nBeta\n\nThis API is new to jclouds and hence is in Beta. That means we need people to use it and give us feedback. Based on that feedback, minor changes to the interfaces may happen. This code will replace org.jclouds.openstack.swift.SwiftClient in jclouds 2.0 and it is recommended you adopt it sooner than later.\n"
  },
  {
    "path": "providers/rackspace-cloudfiles-us/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.rackspace.cloudfiles.us.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "providers/rackspace-cloudfiles-us/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n\n  <groupId>org.apache.jclouds.provider</groupId>\n  <artifactId>rackspace-cloudfiles-us</artifactId>\n  <version>2.7.1-SNAPSHOT</version>\n  <name>jclouds Rackspace Cloud Files US provider</name>\n  <description>OpenStack Object Storage implementation targeted to Rackspace Cloud Files US</description>\n\n  <properties>\n    <!-- identity endpoint -->\n    <test.rackspace-cloudfiles-us.endpoint>https://identity.api.rackspacecloud.com/v2.0/</test.rackspace-cloudfiles-us.endpoint>\n    <test.rackspace-cloudfiles-us.api-version>1</test.rackspace-cloudfiles-us.api-version>\n    <test.rackspace-cloudfiles-us.build-version />\n    <test.rackspace-cloudfiles-us.identity>${test.rackspace-us.identity}</test.rackspace-cloudfiles-us.identity>\n    <test.rackspace-cloudfiles-us.credential>${test.rackspace-us.credential}</test.rackspace-cloudfiles-us.credential>\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-swift</artifactId>\n      <version>${project.parent.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-swift</artifactId>\n      <version>${project.parent.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>rackspace-cloudfiles</artifactId>\n      <version>${project.parent.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>rackspace-cloudfiles</artifactId>\n      <version>${project.parent.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-keystone</artifactId>\n      <version>${project.parent.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-keystone</artifactId>\n      <version>${project.parent.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-blobstore</artifactId>\n      <version>${project.parent.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.parent.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.parent.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-slf4j</artifactId>\n      <version>${project.parent.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>ch.qos.logback</groupId>\n      <artifactId>logback-classic</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>rackspace-cloudidentity</artifactId>\n      <version>${project.parent.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <scope>provided</scope>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <jclouds.blobstore.httpstream.url>${jclouds.blobstore.httpstream.url}</jclouds.blobstore.httpstream.url>\n                    <jclouds.blobstore.httpstream.md5>${jclouds.blobstore.httpstream.md5}</jclouds.blobstore.httpstream.md5>\n                    <test.rackspace-cloudfiles-us.endpoint>${test.rackspace-cloudfiles-us.endpoint}</test.rackspace-cloudfiles-us.endpoint>\n                    <test.rackspace-cloudfiles-us.api-version>${test.rackspace-cloudfiles-us.api-version}</test.rackspace-cloudfiles-us.api-version>\n                    <test.rackspace-cloudfiles-us.build-version>${test.rackspace-cloudfiles-us.build-version}</test.rackspace-cloudfiles-us.build-version>\n                    <test.rackspace-cloudfiles-us.identity>${test.rackspace-cloudfiles-us.identity}</test.rackspace-cloudfiles-us.identity>\n                    <test.rackspace-cloudfiles-us.credential>${test.rackspace-cloudfiles-us.credential}</test.rackspace-cloudfiles-us.credential>\n                    <jclouds.blobstore.httpstream.url>${jclouds.blobstore.httpstream.url}</jclouds.blobstore.httpstream.url>\n                    <jclouds.blobstore.httpstream.md5>${jclouds.blobstore.httpstream.md5}</jclouds.blobstore.httpstream.md5>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n"
  },
  {
    "path": "providers/rackspace-cloudfiles-us/src/main/java/org/jclouds/rackspace/cloudfiles/us/CloudFilesUSProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.us;\n\nimport static org.jclouds.location.reference.LocationConstants.ISO3166_CODES;\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_REGION;\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_REGIONS;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.CREDENTIAL_TYPE;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.KEYSTONE_VERSION;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.SERVICE_TYPE;\nimport static org.jclouds.reflect.Reflection2.typeToken;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.openstack.keystone.catalog.config.ServiceCatalogModule;\nimport org.jclouds.openstack.keystone.catalog.config.ServiceCatalogModule.RegionModule;\nimport org.jclouds.openstack.swift.v1.blobstore.RegionScopedBlobStoreContext;\nimport org.jclouds.openstack.swift.v1.blobstore.config.SignUsingTemporaryUrls;\nimport org.jclouds.openstack.swift.v1.blobstore.config.SwiftBlobStoreContextModule;\nimport org.jclouds.openstack.swift.v1.config.SwiftTypeAdapters;\nimport org.jclouds.openstack.v2_0.ServiceType;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\nimport org.jclouds.rackspace.cloudfiles.v1.CloudFilesApiMetadata;\nimport org.jclouds.rackspace.cloudfiles.v1.config.CloudFilesHttpApiModule;\nimport org.jclouds.rackspace.cloudidentity.v2_0.config.CloudIdentityAuthenticationModule;\nimport org.jclouds.rackspace.cloudidentity.v2_0.config.CloudIdentityCredentialTypes;\n\nimport com.google.auto.service.AutoService;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n/**\n * Implementation of {@link ProviderMetadata} for Rackspace Cloud Files US regions.\n */\n@AutoService(ProviderMetadata.class)\npublic class CloudFilesUSProviderMetadata extends BaseProviderMetadata {\n   \n   /**\n    * @return The Builder object.\n    */\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromProviderMetadata(this);\n   }\n\n   /**\n    * Provider constructor.\n    */\n   public CloudFilesUSProviderMetadata() {\n      this(new Builder());\n   }\n\n   /**\n    * @param builder the Builder for the provider.\n    */\n   protected CloudFilesUSProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   /**\n    * @return a {@link Properties} object containing the default provider properties.\n    */\n   public static Properties defaultProperties() {\n      Properties properties = new Properties();\n      properties.setProperty(CREDENTIAL_TYPE, CloudIdentityCredentialTypes.API_KEY_CREDENTIALS);\n      properties.setProperty(SERVICE_TYPE, ServiceType.OBJECT_STORE);\n      properties.setProperty(KEYSTONE_VERSION, \"2\");\n\n      properties.setProperty(PROPERTY_REGIONS, \"ORD,DFW,IAD,SYD,HKG\");\n      properties.setProperty(PROPERTY_REGION + \".ORD.\" + ISO3166_CODES, \"US-IL\");\n      properties.setProperty(PROPERTY_REGION + \".DFW.\" + ISO3166_CODES, \"US-TX\");\n      properties.setProperty(PROPERTY_REGION + \".IAD.\" + ISO3166_CODES, \"US-VA\");\n      properties.setProperty(PROPERTY_REGION + \".SYD.\" + ISO3166_CODES, \"AU-NSW\");\n      properties.setProperty(PROPERTY_REGION + \".HKG.\" + ISO3166_CODES, \"HK\");\n\n      return properties;\n   }\n\n   /**\n    * Builder pattern class.\n    */\n   public static class Builder extends BaseProviderMetadata.Builder {\n\n      protected Builder() {\n         id(\"rackspace-cloudfiles-us\")\n         .name(\"Rackspace Cloud Files US\")\n         .apiMetadata(new CloudFilesApiMetadata().toBuilder()\n               .identityName(\"${userName}\")\n               .credentialName(\"${apiKey}\")\n               .defaultEndpoint(\"https://identity.api.rackspacecloud.com/v2.0/\")\n               .documentation(URI.create(\"http://docs.rackspace.com/files/api/v1/cf-devguide/content/index.html\"))\n               .endpointName(\"Rackspace Cloud Identity service URL ending in /v2.0/\")\n               .version(\"1.0\")\n               .view(typeToken(RegionScopedBlobStoreContext.class))\n               .defaultModules(ImmutableSet.<Class<? extends Module>>builder()\n                     .add(CloudIdentityAuthenticationModule.class)\n                     .add(ServiceCatalogModule.class)\n                     .add(RegionModule.class)\n                     .add(SwiftTypeAdapters.class)\n                     .add(CloudFilesHttpApiModule.class)\n                     .add(SwiftBlobStoreContextModule.class)\n                     .add(SignUsingTemporaryUrls.class)\n                     .build())\n               .build())\n         .homepage(URI.create(\"http://www.rackspace.com/cloud/files\"))\n         .console(URI.create(\"https://mycloud.rackspace.com\"))\n         .linkedServices(\"rackspace-autoscale-us\", \"rackspace-cloudblockstorage-us\",\n                         \"rackspace-clouddatabases-us\", \"rackspace-clouddns-us\",\n                         \"rackspace-cloudidentity\", \"rackspace-cloudloadbalancers-us\",\n                         \"rackspace-cloudqueues-us\")\n         .iso3166Codes(\"US-IL\", \"US-TX\", \"US-VA\", \"AU-NSW\", \"HK\")\n         .defaultProperties(CloudFilesUSProviderMetadata.defaultProperties());\n         \n      }\n\n      @Override\n      public CloudFilesUSProviderMetadata build() {\n         return new CloudFilesUSProviderMetadata(this);\n      }\n\n      @Override\n      public Builder fromProviderMetadata(ProviderMetadata in) {\n         super.fromProviderMetadata(in);\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudfiles-us/src/test/java/org/jclouds/rackspace/cloudfiles/us/CloudFilesUSProviderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.us;\n\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.jclouds.rackspace.cloudfiles.v1.CloudFilesApiMetadata;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"CloudFilesUSProviderTest\")\npublic class CloudFilesUSProviderTest extends BaseProviderMetadataTest {\n   public CloudFilesUSProviderTest() {\n      super(new CloudFilesUSProviderMetadata(), new CloudFilesApiMetadata());\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudfiles-us/src/test/java/org/jclouds/rackspace/cloudfiles/us/blobstore/integration/CloudFilesUSBlobIntegrationLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.us.blobstore.integration;\n\nimport org.jclouds.rackspace.cloudfiles.v1.blobstore.integration.CloudFilesBlobIntegrationLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"CloudFilesUSBlobIntegrationLiveTest\")\npublic class CloudFilesUSBlobIntegrationLiveTest extends CloudFilesBlobIntegrationLiveTest {\n   public CloudFilesUSBlobIntegrationLiveTest() {\n      provider = \"rackspace-cloudfiles-us\";\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudfiles-us/src/test/java/org/jclouds/rackspace/cloudfiles/us/blobstore/integration/CloudFilesUSBlobIntegrationParallelLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.us.blobstore.integration;\n\nimport org.jclouds.blobstore.BlobStore;\nimport org.jclouds.openstack.swift.v1.blobstore.RegionScopedBlobStoreContext;\nimport org.jclouds.rackspace.cloudfiles.v1.blobstore.CloudFilesRegionScopedSwiftBlobStoreParallelLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"CloudFilesUSBlobIntegrationLiveTest\")\npublic class CloudFilesUSBlobIntegrationParallelLiveTest extends CloudFilesRegionScopedSwiftBlobStoreParallelLiveTest {\n   public CloudFilesUSBlobIntegrationParallelLiveTest() {\n      provider = \"rackspace-cloudfiles-us\";\n   }\n\n   @Override\n   protected BlobStore getBlobStore() {\n      RegionScopedBlobStoreContext ctx = RegionScopedBlobStoreContext.class.cast(view);\n      return ctx.getBlobStore(\"DFW\");\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudfiles-us/src/test/java/org/jclouds/rackspace/cloudfiles/us/blobstore/integration/CloudFilesUSBlobLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.us.blobstore.integration;\n\nimport org.jclouds.rackspace.cloudfiles.v1.blobstore.integration.CloudFilesBlobLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"CloudFilesUSBlobLiveTest\")\npublic class CloudFilesUSBlobLiveTest extends CloudFilesBlobLiveTest {\n   public CloudFilesUSBlobLiveTest() {\n      provider = \"rackspace-cloudfiles-us\";\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudfiles-us/src/test/java/org/jclouds/rackspace/cloudfiles/us/blobstore/integration/CloudFilesUSBlobSignerLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.us.blobstore.integration;\n\nimport org.jclouds.rackspace.cloudfiles.v1.blobstore.integration.CloudFilesBlobSignerLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"CloudFilesUSBlobSignerLiveTest\")\npublic class CloudFilesUSBlobSignerLiveTest extends CloudFilesBlobSignerLiveTest {\n   public CloudFilesUSBlobSignerLiveTest() {\n      provider = \"rackspace-cloudfiles-us\";\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudfiles-us/src/test/java/org/jclouds/rackspace/cloudfiles/us/blobstore/integration/CloudFilesUSContainerIntegrationLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.us.blobstore.integration;\n\nimport org.jclouds.rackspace.cloudfiles.v1.blobstore.integration.CloudFilesContainerIntegrationLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"CloudFilesUSContainerIntegrationLiveTest\")\npublic class CloudFilesUSContainerIntegrationLiveTest extends CloudFilesContainerIntegrationLiveTest {\n   public CloudFilesUSContainerIntegrationLiveTest() {\n      provider = \"rackspace-cloudfiles-us\";\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudfiles-us/src/test/java/org/jclouds/rackspace/cloudfiles/us/blobstore/integration/CloudFilesUSContainerLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.us.blobstore.integration;\n\nimport org.jclouds.rackspace.cloudfiles.v1.blobstore.integration.CloudFilesContainerLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"CloudFilesUSContainerLiveTest\")\npublic class CloudFilesUSContainerLiveTest extends CloudFilesContainerLiveTest {\n   public CloudFilesUSContainerLiveTest() {\n      provider = \"rackspace-cloudfiles-us\";\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudfiles-us/src/test/java/org/jclouds/rackspace/cloudfiles/us/blobstore/integration/CloudFilesUSServiceIntegrationLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.us.blobstore.integration;\n\nimport java.util.Set;\n\nimport org.jclouds.rackspace.cloudfiles.v1.blobstore.integration.CloudFilesServiceIntegrationLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"live\", testName = \"CloudFilesUSServiceIntegrationLiveTest\")\npublic class CloudFilesUSServiceIntegrationLiveTest extends CloudFilesServiceIntegrationLiveTest {\n   public CloudFilesUSServiceIntegrationLiveTest() {\n      provider = \"rackspace-cloudfiles-us\";\n   }\n\n   @Override\n   protected Set<String> getIso3166Codes() {\n      return ImmutableSet.<String> of(\"US-IL\", \"US-TX\", \"US-VA\", \"AU-NSW\", \"HK\");\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudfiles-us/src/test/java/org/jclouds/rackspace/cloudfiles/us/features/CloudFilesUSAccountApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.us.features;\n\nimport org.jclouds.openstack.swift.v1.features.AccountApi;\nimport org.jclouds.rackspace.cloudfiles.v1.CloudFilesApi;\nimport org.jclouds.rackspace.cloudfiles.v1.features.CloudFilesAccountApiLiveTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests the live behavior of the OpenStack Object Storage {@link AccountApi}\n * via the {@link CloudFilesApi}.\n * Uses the Rackspace US provider\n */\n@Test(groups = \"live\", testName = \"CloudFilesUSAccountApiLiveTest\")\npublic class CloudFilesUSAccountApiLiveTest extends CloudFilesAccountApiLiveTest {\n\n   public CloudFilesUSAccountApiLiveTest() {\n      provider = \"rackspace-cloudfiles-us\";\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudfiles-us/src/test/java/org/jclouds/rackspace/cloudfiles/us/features/CloudFilesUSDynamicLargeObjectApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.us.features;\n\nimport org.jclouds.rackspace.cloudfiles.v1.features.CloudFilesDynamicLargeObjectApiLiveTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests the live behavior of the OpenStack Object Storage {@link DynamicLargeObjectApi}\n * via the {@link CloudFilesApi}.\n */\n@Test(groups = \"live\", testName = \"CloudFilesUSDynamicLargeObjectApiLiveTest\")\npublic final class CloudFilesUSDynamicLargeObjectApiLiveTest extends CloudFilesDynamicLargeObjectApiLiveTest {\n   public CloudFilesUSDynamicLargeObjectApiLiveTest() {\n      provider = \"rackspace-cloudfiles-us\";\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudfiles-us/src/test/java/org/jclouds/rackspace/cloudfiles/us/features/CloudFilesUSObjectApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.us.features;\n\nimport org.jclouds.rackspace.cloudfiles.v1.features.CloudFilesObjectApiLiveTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests the live behavior of the OpenStack Object Storage {@link ObjectApi}\n * via the {@link CloudFilesApi}.\n */\n@Test(groups = \"live\", testName = \"CloudFilesUSObjectApiLiveTest\")\npublic class CloudFilesUSObjectApiLiveTest extends CloudFilesObjectApiLiveTest {\n   public CloudFilesUSObjectApiLiveTest() {\n      provider = \"rackspace-cloudfiles-us\";\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudfiles-us/src/test/java/org/jclouds/rackspace/cloudfiles/us/features/CloudFilesUSStaticLargeObjectApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudfiles.us.features;\n\nimport org.jclouds.rackspace.cloudfiles.v1.features.CloudFilesStaticLargeObjectApiLiveTest;\nimport org.testng.annotations.Test;\n\n/**\n * Tests the live behavior of the OpenStack Object Storage {@link StaticLargeObjectApi}\n * via the {@link CloudFilesApi}.\n */\n@Test(groups = \"live\", testName = \"CloudFilesUSStaticLargeObjectApiLiveTest\")\npublic class CloudFilesUSStaticLargeObjectApiLiveTest extends CloudFilesStaticLargeObjectApiLiveTest {\n   public CloudFilesUSStaticLargeObjectApiLiveTest() {\n      provider = \"rackspace-cloudfiles-us\";\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudfiles-us/src/test/resources/logback.xml",
    "content": "<?xml version=\"1.0\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<configuration scan=\"false\">\n    <appender name=\"FILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <appender name=\"WIREFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds-wire.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <appender name=\"BLOBSTOREFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds-blobstore.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n    \n    <root>\n        <level value=\"warn\" />\n    </root>\n\n    <logger name=\"org.jclouds\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"FILE\" />\n    </logger>\n\n<!--\n    <logger name=\"jclouds.wire\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n-->\n\n    <logger name=\"jclouds.headers\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n\n    <logger name=\"jclouds.blobstore\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"BLOBSTOREFILE\" />\n    </logger>\n\n</configuration>\n"
  },
  {
    "path": "providers/rackspace-cloudloadbalancers-uk/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.rackspace.cloudloadbalancers.uk.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "providers/rackspace-cloudloadbalancers-uk/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.provider</groupId>\n  <artifactId>rackspace-cloudloadbalancers-uk</artifactId>\n  <name>jclouds Rackspace Cloud Load Balancers UK provider</name>\n  <description>Cloud Load Balancers implementation targeted to Rackspace UK</description>\n\n  <properties>\n    <test.rackspace-cloudloadbalancers-uk.endpoint>https://lon.identity.api.rackspacecloud.com/v2.0/</test.rackspace-cloudloadbalancers-uk.endpoint>\n    <test.rackspace-cloudloadbalancers-uk.api-version>1</test.rackspace-cloudloadbalancers-uk.api-version>\n    <test.rackspace-cloudloadbalancers-uk.build-version />\n    <test.rackspace-cloudloadbalancers-uk.identity>${test.rackspace-uk.identity}</test.rackspace-cloudloadbalancers-uk.identity>\n    <test.rackspace-cloudloadbalancers-uk.credential>${test.rackspace-uk.credential}</test.rackspace-cloudloadbalancers-uk.credential>\n  </properties>\n  \n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-loadbalancer</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>rackspace-cloudloadbalancers</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-keystone</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>rackspace-cloudidentity</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-loadbalancer</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>rackspace-cloudloadbalancers</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-keystone</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-slf4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>ch.qos.logback</groupId>\n      <artifactId>logback-classic</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.rackspace-cloudloadbalancers-uk.endpoint>${test.rackspace-cloudloadbalancers-uk.endpoint}</test.rackspace-cloudloadbalancers-uk.endpoint>\n                    <test.rackspace-cloudloadbalancers-uk.api-version>${test.rackspace-cloudloadbalancers-uk.api-version}</test.rackspace-cloudloadbalancers-uk.api-version>\n                    <test.rackspace-cloudloadbalancers-uk.build-version>${test.rackspace-cloudloadbalancers-uk.build-version}</test.rackspace-cloudloadbalancers-uk.build-version>\n                    <test.rackspace-cloudloadbalancers-uk.identity>${test.rackspace-cloudloadbalancers-uk.identity}</test.rackspace-cloudloadbalancers-uk.identity>\n                    <test.rackspace-cloudloadbalancers-uk.credential>${test.rackspace-cloudloadbalancers-uk.credential}</test.rackspace-cloudloadbalancers-uk.credential>\n                    <test.jclouds.keystone.credential-type>${test.jclouds.keystone.credential-type}</test.jclouds.keystone.credential-type>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n"
  },
  {
    "path": "providers/rackspace-cloudloadbalancers-uk/src/main/java/org/jclouds/rackspace/cloudloadbalancers/uk/CloudLoadBalancersUKProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.uk;\n\nimport static org.jclouds.location.reference.LocationConstants.ISO3166_CODES;\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_REGION;\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_REGIONS;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.CloudLoadBalancersApiMetadata;\n\nimport com.google.auto.service.AutoService;\n\n/**\n * Implementation of {@link ProviderMetadata} for Rackspace Cloud LoadBalancers UK.\n */\n@AutoService(ProviderMetadata.class)\npublic class CloudLoadBalancersUKProviderMetadata extends BaseProviderMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromProviderMetadata(this);\n   }\n\n   public CloudLoadBalancersUKProviderMetadata() {\n      super(builder());\n   }\n\n   public CloudLoadBalancersUKProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = new Properties();\n      properties.setProperty(PROPERTY_REGIONS, \"LON\");\n      properties.setProperty(PROPERTY_REGION + \".LON.\" + ISO3166_CODES, \"GB-SLG\");\n      return properties;\n   }\n   public static class Builder extends BaseProviderMetadata.Builder {\n\n      protected Builder() {\n         id(\"rackspace-cloudloadbalancers-uk\")\n         .name(\"Rackspace Cloud Load Balancers UK\")\n         .apiMetadata(new CloudLoadBalancersApiMetadata().toBuilder()\n                  .defaultEndpoint(\"https://lon.identity.api.rackspacecloud.com/v2.0/\")\n                  .build())\n         .homepage(URI.create(\"http://www.rackspace.co.uk/cloud-load-balancers/\"))\n         .console(URI.create(\"https://mycloud.rackspace.co.uk\"))\n         .linkedServices(\"rackspace-cloudservers-uk\", \"cloudfiles-uk\", \"rackspace-cloudblockstorage-uk\")\n         .iso3166Codes(\"GB-SLG\")\n         .endpoint(\"https://lon.identity.api.rackspacecloud.com/v2.0/\")\n         .defaultProperties(CloudLoadBalancersApiMetadata.defaultProperties());\n      }\n\n      @Override\n      public CloudLoadBalancersUKProviderMetadata build() {\n         return new CloudLoadBalancersUKProviderMetadata(this);\n      }\n\n      @Override\n      public Builder fromProviderMetadata(\n            ProviderMetadata in) {\n         super.fromProviderMetadata(in);\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudloadbalancers-uk/src/test/java/org/jclouds/rackspace/cloudloadbalancers/uk/CloudLoadBalancersUKLoadBalancerClientLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.uk;\n\nimport org.jclouds.rackspace.cloudloadbalancers.v1.features.LoadBalancerApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"CloudLoadBalancersUKLoadBalancerClientLiveTest\")\npublic class CloudLoadBalancersUKLoadBalancerClientLiveTest extends LoadBalancerApiLiveTest {\n   public CloudLoadBalancersUKLoadBalancerClientLiveTest() {\n      provider = \"rackspace-cloudloadbalancers-uk\";\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudloadbalancers-uk/src/test/java/org/jclouds/rackspace/cloudloadbalancers/uk/CloudLoadBalancersUKNodeClientLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.uk;\n\nimport org.jclouds.rackspace.cloudloadbalancers.v1.features.NodeApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"CloudLoadBalancersUKNodeClientLiveTest\")\npublic class CloudLoadBalancersUKNodeClientLiveTest extends NodeApiLiveTest {\n   public CloudLoadBalancersUKNodeClientLiveTest() {\n      provider = \"rackspace-cloudloadbalancers-uk\";\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudloadbalancers-uk/src/test/java/org/jclouds/rackspace/cloudloadbalancers/uk/CloudLoadBalancersUKProviderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.uk;\n\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.CloudLoadBalancersApiMetadata;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"CloudLoadBalancersUKProviderTest\")\npublic class CloudLoadBalancersUKProviderTest extends BaseProviderMetadataTest {\n\n   public CloudLoadBalancersUKProviderTest() {\n      super(new CloudLoadBalancersUKProviderMetadata(), new CloudLoadBalancersApiMetadata());\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudloadbalancers-us/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.rackspace.cloudloadbalancers.us.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "providers/rackspace-cloudloadbalancers-us/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.provider</groupId>\n  <artifactId>rackspace-cloudloadbalancers-us</artifactId>\n  <name>jclouds Rackspace Cloud Load Balancers US provider</name>\n  <description>Cloud Load Balancers implementation targeted to Rackspace US</description>\n\n  <properties>\n    <test.rackspace-cloudloadbalancers-us.endpoint>https://identity.api.rackspacecloud.com/v2.0/</test.rackspace-cloudloadbalancers-us.endpoint>\n    <test.rackspace-cloudloadbalancers-us.api-version>1</test.rackspace-cloudloadbalancers-us.api-version>\n    <test.rackspace-cloudloadbalancers-us.build-version />\n    <test.rackspace-cloudloadbalancers-us.identity>${test.rackspace-us.identity}</test.rackspace-cloudloadbalancers-us.identity>\n    <test.rackspace-cloudloadbalancers-us.credential>${test.rackspace-us.credential}</test.rackspace-cloudloadbalancers-us.credential>\n  </properties>\n  \n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-loadbalancer</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>rackspace-cloudloadbalancers</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-keystone</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>rackspace-cloudidentity</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-loadbalancer</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>rackspace-cloudloadbalancers</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-keystone</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-slf4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>ch.qos.logback</groupId>\n      <artifactId>logback-classic</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.rackspace-cloudloadbalancers-us.endpoint>${test.rackspace-cloudloadbalancers-us.endpoint}</test.rackspace-cloudloadbalancers-us.endpoint>\n                    <test.rackspace-cloudloadbalancers-us.api-version>${test.rackspace-cloudloadbalancers-us.api-version}</test.rackspace-cloudloadbalancers-us.api-version>\n                    <test.rackspace-cloudloadbalancers-us.build-version>${test.rackspace-cloudloadbalancers-us.build-version}</test.rackspace-cloudloadbalancers-us.build-version>\n                    <test.rackspace-cloudloadbalancers-us.identity>${test.rackspace-cloudloadbalancers-us.identity}</test.rackspace-cloudloadbalancers-us.identity>\n                    <test.rackspace-cloudloadbalancers-us.credential>${test.rackspace-cloudloadbalancers-us.credential}</test.rackspace-cloudloadbalancers-us.credential>\n                    <test.jclouds.keystone.credential-type>${test.jclouds.keystone.credential-type}</test.jclouds.keystone.credential-type>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n"
  },
  {
    "path": "providers/rackspace-cloudloadbalancers-us/src/main/java/org/jclouds/rackspace/cloudloadbalancers/us/CloudLoadBalancersUSProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.us;\n\nimport static org.jclouds.location.reference.LocationConstants.ISO3166_CODES;\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_REGION;\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_REGIONS;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.CloudLoadBalancersApiMetadata;\n\nimport com.google.auto.service.AutoService;\n\n/**\n * Implementation of {@link ProviderMetadata} for Rackspace Cloud LoadBalancers US.\n */\n@AutoService(ProviderMetadata.class)\npublic class CloudLoadBalancersUSProviderMetadata extends BaseProviderMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromProviderMetadata(this);\n   }\n\n   public CloudLoadBalancersUSProviderMetadata() {\n      super(builder());\n   }\n\n   public CloudLoadBalancersUSProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = new Properties();\n      properties.setProperty(PROPERTY_REGIONS, \"ORD,DFW,IAD,SYD,HKG\");\n      properties.setProperty(PROPERTY_REGION + \".ORD.\" + ISO3166_CODES, \"US-IL\");\n      properties.setProperty(PROPERTY_REGION + \".DFW.\" + ISO3166_CODES, \"US-TX\");\n      properties.setProperty(PROPERTY_REGION + \".IAD.\" + ISO3166_CODES, \"US-VA\");\n      properties.setProperty(PROPERTY_REGION + \".SYD.\" + ISO3166_CODES, \"AU-NSW\");\n      properties.setProperty(PROPERTY_REGION + \".HKG.\" + ISO3166_CODES, \"HK\");\n      return properties;\n   }\n\n   public static class Builder extends BaseProviderMetadata.Builder {\n\n      protected Builder() {\n         id(\"rackspace-cloudloadbalancers-us\")\n         .name(\"Rackspace Cloud Load Balancers US\")\n         .apiMetadata(new CloudLoadBalancersApiMetadata().toBuilder()\n                  .defaultEndpoint(\"https://identity.api.rackspacecloud.com/v2.0/\")\n                  .build())\n         .homepage(URI.create(\"http://www.rackspace.com/cloud/public/loadbalancers/\"))\n         .console(URI.create(\"https://mycloud.rackspace.com\"))\n         .linkedServices(\"rackspace-cloudservers-us\", \"cloudfiles-us\", \"rackspace-cloudblockstorage-us\")\n         .iso3166Codes(\"US-IL\", \"US-TX\", \"AU-NSW\")\n         .endpoint(\"https://identity.api.rackspacecloud.com/v2.0/\")\n         .defaultProperties(CloudLoadBalancersApiMetadata.defaultProperties());\n      }\n\n      @Override\n      public CloudLoadBalancersUSProviderMetadata build() {\n         return new CloudLoadBalancersUSProviderMetadata(this);\n      }\n\n      @Override\n      public Builder fromProviderMetadata(\n            ProviderMetadata in) {\n         super.fromProviderMetadata(in);\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudloadbalancers-us/src/test/java/org/jclouds/rackspace/cloudloadbalancers/us/CloudLoadBalancersUSLoadBalancerClientLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.us;\n\nimport org.jclouds.rackspace.cloudloadbalancers.v1.features.LoadBalancerApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"CloudLoadBalancersUSLoadBalancerClientLiveTest\")\npublic class CloudLoadBalancersUSLoadBalancerClientLiveTest extends LoadBalancerApiLiveTest {\n   public CloudLoadBalancersUSLoadBalancerClientLiveTest() {\n      provider = \"rackspace-cloudloadbalancers-us\";\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudloadbalancers-us/src/test/java/org/jclouds/rackspace/cloudloadbalancers/us/CloudLoadBalancersUSNodeClientLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.us;\n\nimport org.jclouds.rackspace.cloudloadbalancers.v1.features.NodeApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"CloudLoadBalancersUSNodeClientLiveTest\")\npublic class CloudLoadBalancersUSNodeClientLiveTest extends NodeApiLiveTest {\n   public CloudLoadBalancersUSNodeClientLiveTest() {\n      provider = \"rackspace-cloudloadbalancers-us\";\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudloadbalancers-us/src/test/java/org/jclouds/rackspace/cloudloadbalancers/us/CloudLoadBalancersUSProviderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudloadbalancers.us;\n\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.jclouds.rackspace.cloudloadbalancers.v1.CloudLoadBalancersApiMetadata;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"CloudLoadBalancersUSProviderTest\")\npublic class CloudLoadBalancersUSProviderTest extends BaseProviderMetadataTest {\n\n   public CloudLoadBalancersUSProviderTest() {\n      super(new CloudLoadBalancersUSProviderMetadata(), new CloudLoadBalancersApiMetadata());\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudnetworks-uk/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.rackspace.cloudnetworks.uk.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "providers/rackspace-cloudnetworks-uk/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.provider</groupId>\n  <artifactId>rackspace-cloudnetworks-uk</artifactId>\n  <name>jclouds Rackspace Cloud Networks UK provider</name>\n  <description>OpenStack Neutron implementation targeted to Rackspace Cloud Networks UK</description>\n\n  <properties>\n    <!-- identity endpoint -->\n    <test.rackspace-cloudnetworks-uk.endpoint>https://lon.identity.api.rackspacecloud.com/v2.0/</test.rackspace-cloudnetworks-uk.endpoint>\n    <test.rackspace-cloudnetworks-uk.api-version>2.0</test.rackspace-cloudnetworks-uk.api-version>\n    <test.rackspace-cloudnetworks-uk.build-version />\n    <test.rackspace-cloudnetworks-uk.identity>${test.rackspace-uk.identity}</test.rackspace-cloudnetworks-uk.identity>\n    <test.rackspace-cloudnetworks-uk.credential>${test.rackspace-uk.credential}</test.rackspace-cloudnetworks-uk.credential>\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-neutron</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>rackspace-cloudidentity</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n\n    <!-- Test Dependencies -->\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-neutron</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-slf4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>ch.qos.logback</groupId>\n      <artifactId>logback-classic</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.rackspace-cloudnetworks-uk.endpoint>${test.rackspace-cloudnetworks-uk.endpoint}</test.rackspace-cloudnetworks-uk.endpoint>\n                    <test.rackspace-cloudnetworks-uk.api-version>${test.rackspace-cloudnetworks-uk.api-version}</test.rackspace-cloudnetworks-uk.api-version>\n                    <test.rackspace-cloudnetworks-uk.build-version>${test.rackspace-cloudnetworks-uk.build-version}</test.rackspace-cloudnetworks-uk.build-version>\n                    <test.rackspace-cloudnetworks-uk.identity>${test.rackspace-cloudnetworks-uk.identity}</test.rackspace-cloudnetworks-uk.identity>\n                    <test.rackspace-cloudnetworks-uk.credential>${test.rackspace-cloudnetworks-uk.credential}</test.rackspace-cloudnetworks-uk.credential>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n"
  },
  {
    "path": "providers/rackspace-cloudnetworks-uk/src/main/java/org/jclouds/rackspace/cloudnetworks/uk/CloudNetworksUKProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudnetworks.uk;\n\nimport static org.jclouds.location.reference.LocationConstants.ISO3166_CODES;\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_REGION;\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_REGIONS;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.CREDENTIAL_TYPE;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.KEYSTONE_VERSION;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.SERVICE_TYPE;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.openstack.keystone.catalog.config.ServiceCatalogModule;\nimport org.jclouds.openstack.keystone.catalog.config.ServiceCatalogModule.RegionModule;\nimport org.jclouds.openstack.neutron.v2.NeutronApiMetadata;\nimport org.jclouds.openstack.neutron.v2.config.NeutronHttpApiModule;\nimport org.jclouds.openstack.v2_0.ServiceType;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\nimport org.jclouds.rackspace.cloudidentity.v2_0.config.CloudIdentityAuthenticationModule;\nimport org.jclouds.rackspace.cloudidentity.v2_0.config.CloudIdentityCredentialTypes;\n\nimport com.google.auto.service.AutoService;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n@AutoService(ProviderMetadata.class)\npublic class CloudNetworksUKProviderMetadata extends BaseProviderMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromProviderMetadata(this);\n   }\n\n   public CloudNetworksUKProviderMetadata() {\n      this(new Builder());\n   }\n\n   protected CloudNetworksUKProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   /**\n    * @return a {@link Properties} object containing the default provider properties.\n    * This returns the credential type, service type, and configured regions.\n    */\n   public static Properties defaultProperties() {\n      Properties properties = new Properties();\n      properties.setProperty(CREDENTIAL_TYPE, CloudIdentityCredentialTypes.API_KEY_CREDENTIALS);\n      properties.setProperty(SERVICE_TYPE, ServiceType.NETWORK);\n      properties.setProperty(KEYSTONE_VERSION, \"2\");\n\n      properties.setProperty(PROPERTY_REGIONS, \"LON\");\n      properties.setProperty(PROPERTY_REGION + \".LON.\" + ISO3166_CODES, \"GB-SLG\");\n\n      return properties;\n   }\n\n   public static class Builder extends BaseProviderMetadata.Builder {\n\n      protected Builder() {\n         id(\"rackspace-cloudnetworks-uk\")\n         .name(\"Rackspace Cloud Networks UK\")\n         .apiMetadata(new NeutronApiMetadata().toBuilder()\n               .identityName(\"${userName}\")\n               .credentialName(\"${apiKey}\")\n               .defaultEndpoint(\"https://lon.identity.api.rackspacecloud.com/v2.0/\")\n               .documentation(URI.create(\"http://docs.rackspace.com/networks/api/v1/cf-devguide/content/index.html\"))\n               .endpointName(\"Rackspace Cloud Identity service URL ending in /v2.0/\")\n               .version(\"2.0\")\n               .defaultModules(ImmutableSet.<Class<? extends Module>>builder()\n                     .add(CloudIdentityAuthenticationModule.class)\n                     .add(ServiceCatalogModule.class)\n                     .add(RegionModule.class)\n                     .add(NeutronHttpApiModule.class)\n                     .build())\n               .build())\n         .homepage(URI.create(\"http://www.rackspace.com/cloud/networks\"))\n         .console(URI.create(\"https://mycloud.rackspace.co.uk\"))\n         .linkedServices(\"rackspace-autoscale-uk\", \"rackspace-cloudblockstorage-uk\",\n               \"rackspace-clouddatabases-uk\", \"rackspace-clouddns-uk\", \"rackspace-cloudidentity\",\n               \"rackspace-cloudloadbalancers-uk\", \"rackspace-cloudqueues-uk\",\n               \"rackspace-cloudservers-uk\")\n         .iso3166Codes(\"GB-SLG\")\n         .defaultProperties(CloudNetworksUKProviderMetadata.defaultProperties());\n\n      }\n\n      @Override\n      public CloudNetworksUKProviderMetadata build() {\n         return new CloudNetworksUKProviderMetadata(this);\n      }\n\n      @Override\n      public Builder fromProviderMetadata(ProviderMetadata in) {\n         super.fromProviderMetadata(in);\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudnetworks-uk/src/test/java/org/jclouds/rackspace/cloudnetworks/uk/CloudNetworksUKNetworkApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudnetworks.uk;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.openstack.neutron.v2.domain.Network;\nimport org.jclouds.openstack.neutron.v2.features.NetworkApi;\nimport org.jclouds.openstack.neutron.v2.features.NetworkApiLiveTest;\nimport org.testng.SkipException;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"CloudNetworksUKNetworkApiLiveTest\", singleThreaded = true)\npublic class CloudNetworksUKNetworkApiLiveTest extends NetworkApiLiveTest {\n   public CloudNetworksUKNetworkApiLiveTest() {\n      provider = \"rackspace-cloudnetworks-uk\";\n   }\n\n   @Override\n   public void testCreateUpdateAndDeleteNetwork() {\n      for (String region : api.getConfiguredRegions()) {\n         NetworkApi networkApi = api.getNetworkApi(region);\n         Network net = networkApi.create(Network.createBuilder(\"jclouds-test\").build());\n         Network test = networkApi.create(Network.createBuilder(\"jclouds-test\").build());\n         assertNotNull(net);\n\n         /* List and get tests */\n         Network networkList = api.getNetworkApi(region).list().concat().toSet().iterator().next();\n         assertNotNull(networkList);\n         Network networkGet = api.getNetworkApi(region).get(networkList.getId());\n         assertEquals(networkList, networkGet);\n         /****/\n\n         Network network = networkApi.get(net.getId());\n\n         assertEquals(network.getId(), net.getId());\n         assertEquals(network.getName(), \"jclouds-test\");\n         assertTrue(network.getSubnets().isEmpty());\n         assertNotNull(networkApi.update(net.getId(), Network.updateBuilder().name(\"jclouds-live-test\").build()));\n\n         network = networkApi.get(net.getId());\n\n         assertEquals(network.getId(), net.getId());\n         assertEquals(network.getName(), \"jclouds-live-test\");\n         assertTrue(network.getSubnets().isEmpty());\n\n         Network net2 = networkApi.create(Network.createBuilder(\"jclouds-test2\").build());\n         assertNotNull(net2);\n\n         assertTrue(networkApi.delete(net.getId()));\n         assertTrue(networkApi.delete(net2.getId()));\n         assertTrue(networkApi.delete(test.getId()));\n      }\n   }\n\n   @Override\n   public void testBulkCreateNetwork() {\n      throw new SkipException(\"unsupported functionality\");\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudnetworks-uk/src/test/java/org/jclouds/rackspace/cloudnetworks/uk/CloudNetworksUKPortApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudnetworks.uk;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.openstack.neutron.v2.domain.Network;\nimport org.jclouds.openstack.neutron.v2.domain.Port;\nimport org.jclouds.openstack.neutron.v2.domain.Subnet;\nimport org.jclouds.openstack.neutron.v2.features.NetworkApi;\nimport org.jclouds.openstack.neutron.v2.features.PortApi;\nimport org.jclouds.openstack.neutron.v2.features.PortApiLiveTest;\nimport org.jclouds.openstack.neutron.v2.features.SubnetApi;\nimport org.testng.SkipException;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"live\", testName = \"CloudNetworksUKPortApiLiveTest\", singleThreaded = true)\npublic class CloudNetworksUKPortApiLiveTest extends PortApiLiveTest {\n   public CloudNetworksUKPortApiLiveTest() {\n      provider = \"rackspace-cloudnetworks-uk\";\n   }\n\n   public void testCreateUpdateAndDeletePort() {\n      for (String region : api.getConfiguredRegions()) {\n         NetworkApi networkApi = api.getNetworkApi(region);\n         SubnetApi subnetApi = api.getSubnetApi(region);\n         PortApi portApi = api.getPortApi(region);\n         String networkId = networkApi.create(\n               Network.createBuilder(\"JClouds-Live-Network\").build()).getId();\n         String ipv4SubnetId = subnetApi.create(Subnet.createBuilder(networkId, \"192.168.0.0/30\").ipVersion(4)\n               .name(\"JClouds-Live-IPv4-Subnet\").build()).getId();\n\n         assertNotNull(networkId);\n         assertNotNull(ipv4SubnetId);\n\n         String ipv4PortId = portApi.create(Port.createBuilder(networkId).name(\"JClouds-Live-IPv4-Port\")\n               .fixedIps(ImmutableSet.copyOf(getFixedAddresses(ipv4SubnetId))).build()).getId();\n\n         /* List and get test */\n         Port portList = api.getPortApi(region).list().concat().toSet().iterator().next();\n         assertNotNull(portList);\n         Port portGet = api.getPortApi(region).get(portList.getId());\n         assertEquals(portList, portGet);\n         /****/\n\n         assertNotNull(ipv4PortId);\n\n         Port ipv4Port = portApi.get(ipv4PortId);\n         assertNotNull(ipv4Port);\n         assertEquals(ipv4Port.getId(), ipv4PortId);\n         assertEquals(ipv4Port.getName(), \"JClouds-Live-IPv4-Port\");\n\n         assertNotNull(portApi.update(ipv4PortId, Port.updateBuilder().name(\"Updated\").build()));\n         Port updatedIpv4Port = portApi.get(ipv4PortId);\n         assertEquals(updatedIpv4Port.getName(), \"Updated\");\n\n         assertTrue(portApi.delete(ipv4PortId));\n         assertTrue(subnetApi.delete(ipv4SubnetId));\n         assertTrue(networkApi.delete(networkId));\n      }\n   }\n\n   @Override\n   public void testBulkCreatePort() {\n      throw new SkipException(\"unsupported functionality\");\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudnetworks-uk/src/test/java/org/jclouds/rackspace/cloudnetworks/uk/CloudNetworksUKProviderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudnetworks.uk;\n\nimport org.jclouds.openstack.neutron.v2.NeutronApiMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"CloudNetworksUKProviderTest\", singleThreaded = true)\npublic class CloudNetworksUKProviderTest extends BaseProviderMetadataTest {\n   public CloudNetworksUKProviderTest() {\n      super(new CloudNetworksUKProviderMetadata(), new NeutronApiMetadata());\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudnetworks-uk/src/test/java/org/jclouds/rackspace/cloudnetworks/uk/CloudNetworksUKSubnetApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudnetworks.uk;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.openstack.neutron.v2.domain.AllocationPool;\nimport org.jclouds.openstack.neutron.v2.domain.HostRoute;\nimport org.jclouds.openstack.neutron.v2.domain.Network;\nimport org.jclouds.openstack.neutron.v2.domain.Subnet;\nimport org.jclouds.openstack.neutron.v2.features.NetworkApi;\nimport org.jclouds.openstack.neutron.v2.features.SubnetApi;\nimport org.jclouds.openstack.neutron.v2.features.SubnetApiLiveTest;\nimport org.testng.SkipException;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"live\", testName = \"CloudNetworksUKSubnetApiLiveTest\", singleThreaded = true)\npublic class CloudNetworksUKSubnetApiLiveTest extends SubnetApiLiveTest {\n   public CloudNetworksUKSubnetApiLiveTest() {\n      provider = \"rackspace-cloudnetworks-uk\";\n   }\n\n   @Override\n   public void testCreateUpdateAndDeleteSubnet() {\n      for (String region : api.getConfiguredRegions()) {\n         NetworkApi networkApi = api.getNetworkApi(region);\n         String networkId = networkApi.create(\n               Network.createBuilder(\"jclouds-live-test\").build()).getId();\n\n         SubnetApi subnetApi = api.getSubnetApi(region);\n         ImmutableSet<AllocationPool> allocationPools = ImmutableSet.of(\n               AllocationPool.builder().start(\"192.168.100.0\").end(\"192.168.100.2\").build()\n         );\n         ImmutableSet<HostRoute> hostRoutes = ImmutableSet.of(\n               HostRoute.builder().destinationCidr(\"192.168.100.0/30\").nextHop(\"192.168.100.4\").build()\n         );\n         Subnet subnet = subnetApi.create(Subnet.createBuilder(networkId, \"192.168.100.0/30\").ipVersion(4).allocationPools(allocationPools).hostRoutes(hostRoutes).build());\n         assertNotNull(subnet);\n\n         /* Test list and get */\n         Subnet subnetList = api.getSubnetApi(region).list().concat().toSet().iterator().next();\n         assertNotNull(subnetList);\n         Subnet subnetGet = api.getSubnetApi(region).get(subnetList.getId());\n         assertEquals(subnetList, subnetGet);\n         /***/\n\n         Subnet retrievedSubnet = subnetApi.get(subnet.getId());\n\n         assertEquals(retrievedSubnet.getId(), subnet.getId());\n         assertEquals(retrievedSubnet.getCidr(), \"192.168.100.0/30\");\n         assertTrue(retrievedSubnet.getDnsNameservers().isEmpty());\n         assertEquals(retrievedSubnet.getAllocationPools().size(), 1);\n         assertEquals(retrievedSubnet.getHostRoutes().size(), 1);\n         assertNotNull(subnetApi.update(retrievedSubnet.getId(), Subnet.updateBuilder().name(\"jclouds-live-test-update\").build()));\n\n         retrievedSubnet = subnetApi.get(retrievedSubnet.getId());\n\n         assertEquals(retrievedSubnet.getId(), subnet.getId());\n         assertEquals(retrievedSubnet.getName(), \"jclouds-live-test-update\");\n         assertTrue(retrievedSubnet.getDnsNameservers().isEmpty());\n\n         assertTrue(subnetApi.delete(subnet.getId()));\n         assertTrue(networkApi.delete(networkId));\n      }\n   }\n\n   @Override\n   public void testBulkCreateSubnet() {\n      throw new SkipException(\"unsupported functionality\");\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudnetworks-uk/src/test/resources/logback.xml",
    "content": "<?xml version=\"1.0\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<configuration scan=\"false\">\n    <appender name=\"FILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <appender name=\"WIREFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds-wire.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <root>\n        <level value=\"warn\" />\n    </root>\n\n    <logger name=\"org.jclouds\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"FILE\" />\n    </logger>\n\n    <logger name=\"jclouds.wire\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n\n    <logger name=\"jclouds.headers\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n\n</configuration>\n"
  },
  {
    "path": "providers/rackspace-cloudnetworks-us/README.md",
    "content": "Rackspace Networks US\n========================\n\n"
  },
  {
    "path": "providers/rackspace-cloudnetworks-us/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.rackspace.cloudnetworks.us.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "providers/rackspace-cloudnetworks-us/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.provider</groupId>\n  <artifactId>rackspace-cloudnetworks-us</artifactId>\n  <name>jclouds Rackspace Cloud Networks US provider</name>\n  <description>OpenStack Neutron implementation targeted to Rackspace Cloud Networks US</description>\n\n  <properties>\n    <!-- identity endpoint -->\n    <test.rackspace-cloudnetworks-us.endpoint>https://identity.api.rackspacecloud.com/v2.0/</test.rackspace-cloudnetworks-us.endpoint>\n    <test.rackspace-cloudnetworks-us.api-version>2.0</test.rackspace-cloudnetworks-us.api-version>\n    <test.rackspace-cloudnetworks-us.build-version />\n    <test.rackspace-cloudnetworks-us.identity>${test.rackspace-us.identity}</test.rackspace-cloudnetworks-us.identity>\n    <test.rackspace-cloudnetworks-us.credential>${test.rackspace-us.credential}</test.rackspace-cloudnetworks-us.credential>\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-neutron</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>rackspace-cloudidentity</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n\n    <!-- Test Dependencies -->\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-neutron</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-slf4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>ch.qos.logback</groupId>\n      <artifactId>logback-classic</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <scope>provided</scope>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.rackspace-cloudnetworks-us.endpoint>${test.rackspace-cloudnetworks-us.endpoint}</test.rackspace-cloudnetworks-us.endpoint>\n                    <test.rackspace-cloudnetworks-us.api-version>${test.rackspace-cloudnetworks-us.api-version}</test.rackspace-cloudnetworks-us.api-version>\n                    <test.rackspace-cloudnetworks-us.build-version>${test.rackspace-cloudnetworks-us.build-version}</test.rackspace-cloudnetworks-us.build-version>\n                    <test.rackspace-cloudnetworks-us.identity>${test.rackspace-cloudnetworks-us.identity}</test.rackspace-cloudnetworks-us.identity>\n                    <test.rackspace-cloudnetworks-us.credential>${test.rackspace-cloudnetworks-us.credential}</test.rackspace-cloudnetworks-us.credential>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n"
  },
  {
    "path": "providers/rackspace-cloudnetworks-us/src/main/java/org/jclouds/rackspace/cloudnetworks/us/CloudNetworksUSProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudnetworks.us;\n\nimport static org.jclouds.location.reference.LocationConstants.ISO3166_CODES;\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_REGION;\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_REGIONS;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.CREDENTIAL_TYPE;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.KEYSTONE_VERSION;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.SERVICE_TYPE;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.openstack.keystone.catalog.config.ServiceCatalogModule;\nimport org.jclouds.openstack.keystone.catalog.config.ServiceCatalogModule.RegionModule;\nimport org.jclouds.openstack.neutron.v2.NeutronApiMetadata;\nimport org.jclouds.openstack.neutron.v2.config.NeutronHttpApiModule;\nimport org.jclouds.openstack.v2_0.ServiceType;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\nimport org.jclouds.rackspace.cloudidentity.v2_0.config.CloudIdentityAuthenticationModule;\nimport org.jclouds.rackspace.cloudidentity.v2_0.config.CloudIdentityCredentialTypes;\n\nimport com.google.auto.service.AutoService;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n@AutoService(ProviderMetadata.class)\npublic class CloudNetworksUSProviderMetadata extends BaseProviderMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromProviderMetadata(this);\n   }\n\n   public CloudNetworksUSProviderMetadata() {\n      this(new Builder());\n   }\n\n   protected CloudNetworksUSProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   /**\n    * @return a {@link Properties} object containing the default provider properties.\n    * This returns the credential type, service type, and configured regions.\n    */\n   public static Properties defaultProperties() {\n      Properties properties = new Properties();\n      properties.setProperty(CREDENTIAL_TYPE, CloudIdentityCredentialTypes.API_KEY_CREDENTIALS);\n      properties.setProperty(SERVICE_TYPE, ServiceType.NETWORK);\n      properties.setProperty(KEYSTONE_VERSION, \"2\");\n\n      properties.setProperty(PROPERTY_REGIONS, \"ORD,DFW,IAD,SYD,HKG\");\n      properties.setProperty(PROPERTY_REGION + \".ORD.\" + ISO3166_CODES, \"US-IL\");\n      properties.setProperty(PROPERTY_REGION + \".DFW.\" + ISO3166_CODES, \"US-TX\");\n      properties.setProperty(PROPERTY_REGION + \".IAD.\" + ISO3166_CODES, \"US-VA\");\n      properties.setProperty(PROPERTY_REGION + \".SYD.\" + ISO3166_CODES, \"AU-NSW\");\n      properties.setProperty(PROPERTY_REGION + \".HKG.\" + ISO3166_CODES, \"HK\");\n\n      return properties;\n   }\n\n   public static class Builder extends BaseProviderMetadata.Builder {\n\n      protected Builder() {\n         id(\"rackspace-cloudnetworks-us\")\n         .name(\"Rackspace Cloud Networks US\")\n         .apiMetadata(new NeutronApiMetadata().toBuilder()\n               .identityName(\"${userName}\")\n               .credentialName(\"${apiKey}\")\n               .defaultEndpoint(\"https://identity.api.rackspacecloud.com/v2.0/\")\n               .documentation(URI.create(\"http://docs.rackspace.com/networks/api/v1/cf-devguide/content/index.html\"))\n               .endpointName(\"Rackspace Cloud Identity service URL ending in /v2.0/\")\n               .version(\"2.0\")\n               .defaultModules(ImmutableSet.<Class<? extends Module>>builder()\n                     .add(CloudIdentityAuthenticationModule.class)\n                     .add(ServiceCatalogModule.class)\n                     .add(RegionModule.class)\n                     .add(NeutronHttpApiModule.class)\n                     .build())\n               .build())\n         .homepage(URI.create(\"http://www.rackspace.com/cloud/networks\"))\n         .console(URI.create(\"https://mycloud.rackspace.com\"))\n         .linkedServices(\"rackspace-autoscale-us\", \"rackspace-cloudblockstorage-us\",\n                         \"rackspace-clouddatabases-us\", \"rackspace-clouddns-us\",\n                         \"rackspace-cloudidentity\", \"rackspace-cloudloadbalancers-us\",\n                         \"rackspace-cloudqueues-us\")\n         .iso3166Codes(\"US-IL\", \"US-TX\", \"US-VA\", \"AU-NSW\", \"HK\")\n         .defaultProperties(CloudNetworksUSProviderMetadata.defaultProperties());\n\n      }\n\n      @Override\n      public CloudNetworksUSProviderMetadata build() {\n         return new CloudNetworksUSProviderMetadata(this);\n      }\n\n      @Override\n      public Builder fromProviderMetadata(ProviderMetadata in) {\n         super.fromProviderMetadata(in);\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudnetworks-us/src/test/java/org/jclouds/rackspace/cloudnetworks/us/CloudNetworksUSNetworkApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudnetworks.us;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.openstack.neutron.v2.domain.Network;\nimport org.jclouds.openstack.neutron.v2.features.NetworkApi;\nimport org.jclouds.openstack.neutron.v2.features.NetworkApiLiveTest;\nimport org.testng.SkipException;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"CloudNetworksUSNetworkApiLiveTest\", singleThreaded = true)\npublic class CloudNetworksUSNetworkApiLiveTest extends NetworkApiLiveTest {\n   public CloudNetworksUSNetworkApiLiveTest() {\n      provider = \"rackspace-cloudnetworks-us\";\n   }\n\n   @Override\n   public void testCreateUpdateAndDeleteNetwork() {\n      for (String region : api.getConfiguredRegions()) {\n         NetworkApi networkApi = api.getNetworkApi(region);\n         Network net = networkApi.create(Network.createBuilder(\"jclouds-test\").build());\n         Network test = networkApi.create(Network.createBuilder(\"jclouds-test\").build());\n         assertNotNull(net);\n\n         /* List and get tests */\n         Network networkList = api.getNetworkApi(region).list().concat().toSet().iterator().next();\n         assertNotNull(networkList);\n         Network networkGet = api.getNetworkApi(region).get(networkList.getId());\n         assertEquals(networkList, networkGet);\n         /****/\n\n         Network network = networkApi.get(net.getId());\n\n         assertEquals(network.getId(), net.getId());\n         assertEquals(network.getName(), \"jclouds-test\");\n         assertTrue(network.getSubnets().isEmpty());\n         assertNotNull(networkApi.update(net.getId(), Network.updateBuilder().name(\"jclouds-live-test\").build()));\n\n         network = networkApi.get(net.getId());\n\n         assertEquals(network.getId(), net.getId());\n         assertEquals(network.getName(), \"jclouds-live-test\");\n         assertTrue(network.getSubnets().isEmpty());\n\n         Network net2 = networkApi.create(Network.createBuilder(\"jclouds-test2\").build());\n         assertNotNull(net2);\n\n         assertTrue(networkApi.delete(net.getId()));\n         assertTrue(networkApi.delete(net2.getId()));\n         assertTrue(networkApi.delete(test.getId()));\n      }\n   }\n\n   @Override\n   public void testBulkCreateNetwork() {\n      throw new SkipException(\"unsupported functionality\");\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudnetworks-us/src/test/java/org/jclouds/rackspace/cloudnetworks/us/CloudNetworksUSPortApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudnetworks.us;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.openstack.neutron.v2.domain.Network;\nimport org.jclouds.openstack.neutron.v2.domain.Port;\nimport org.jclouds.openstack.neutron.v2.domain.Subnet;\nimport org.jclouds.openstack.neutron.v2.features.NetworkApi;\nimport org.jclouds.openstack.neutron.v2.features.PortApi;\nimport org.jclouds.openstack.neutron.v2.features.PortApiLiveTest;\nimport org.jclouds.openstack.neutron.v2.features.SubnetApi;\nimport org.testng.SkipException;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"live\", testName = \"CloudNetworksUSPortApiLiveTest\", singleThreaded = true)\npublic class CloudNetworksUSPortApiLiveTest extends PortApiLiveTest {\n   public CloudNetworksUSPortApiLiveTest() {\n      provider = \"rackspace-cloudnetworks-us\";\n   }\n\n   public void testCreateUpdateAndDeletePort() {\n      for (String region : api.getConfiguredRegions()) {\n         NetworkApi networkApi = api.getNetworkApi(region);\n         SubnetApi subnetApi = api.getSubnetApi(region);\n         PortApi portApi = api.getPortApi(region);\n         String networkId = networkApi.create(\n               Network.createBuilder(\"JClouds-Live-Network\").build()).getId();\n         String ipv4SubnetId = subnetApi.create(Subnet.createBuilder(networkId, \"192.168.0.0/30\").ipVersion(4)\n               .name(\"JClouds-Live-IPv4-Subnet\").build()).getId();\n\n         assertNotNull(networkId);\n         assertNotNull(ipv4SubnetId);\n\n         String ipv4PortId = portApi.create(Port.createBuilder(networkId).name(\"JClouds-Live-IPv4-Port\")\n               .fixedIps(ImmutableSet.copyOf(getFixedAddresses(ipv4SubnetId))).build()).getId();\n\n         /* List and get test */\n         Port portList = api.getPortApi(region).list().concat().toSet().iterator().next();\n         assertNotNull(portList);\n         Port portGet = api.getPortApi(region).get(portList.getId());\n         assertEquals(portList, portGet);\n         /****/\n\n         assertNotNull(ipv4PortId);\n\n         Port ipv4Port = portApi.get(ipv4PortId);\n         assertNotNull(ipv4Port);\n         assertEquals(ipv4Port.getId(), ipv4PortId);\n         assertEquals(ipv4Port.getName(), \"JClouds-Live-IPv4-Port\");\n\n         assertNotNull(portApi.update(ipv4PortId, Port.updateBuilder().name(\"Updated\").build()));\n         Port updatedIpv4Port = portApi.get(ipv4PortId);\n         assertEquals(updatedIpv4Port.getName(), \"Updated\");\n\n         assertTrue(portApi.delete(ipv4PortId));\n         assertTrue(subnetApi.delete(ipv4SubnetId));\n         assertTrue(networkApi.delete(networkId));\n      }\n   }\n\n   @Override\n   public void testBulkCreatePort() {\n      throw new SkipException(\"unsupported functionality\");\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudnetworks-us/src/test/java/org/jclouds/rackspace/cloudnetworks/us/CloudNetworksUSProviderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudnetworks.us;\n\nimport org.jclouds.openstack.neutron.v2.NeutronApiMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"CloudNetworksUSProviderTest\", singleThreaded = true)\npublic class CloudNetworksUSProviderTest extends BaseProviderMetadataTest {\n   public CloudNetworksUSProviderTest() {\n      super(new CloudNetworksUSProviderMetadata(), new NeutronApiMetadata());\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudnetworks-us/src/test/java/org/jclouds/rackspace/cloudnetworks/us/CloudNetworksUSSecurityGroupApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudnetworks.us;\n\nimport org.jclouds.openstack.neutron.v2.features.SecurityGroupApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"CloudNetworksUSSecurityGroupApiLiveTest\", singleThreaded = true)\npublic class CloudNetworksUSSecurityGroupApiLiveTest extends SecurityGroupApiLiveTest {\n   public CloudNetworksUSSecurityGroupApiLiveTest() {\n      provider = \"rackspace-cloudnetworks-us\";\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudnetworks-us/src/test/java/org/jclouds/rackspace/cloudnetworks/us/CloudNetworksUSSubnetApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudnetworks.us;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.openstack.neutron.v2.domain.AllocationPool;\nimport org.jclouds.openstack.neutron.v2.domain.HostRoute;\nimport org.jclouds.openstack.neutron.v2.domain.Network;\nimport org.jclouds.openstack.neutron.v2.domain.Subnet;\nimport org.jclouds.openstack.neutron.v2.features.NetworkApi;\nimport org.jclouds.openstack.neutron.v2.features.SubnetApi;\nimport org.jclouds.openstack.neutron.v2.features.SubnetApiLiveTest;\nimport org.testng.SkipException;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"live\", testName = \"CloudNetworksUSSubnetApiLiveTest\", singleThreaded = true)\npublic class CloudNetworksUSSubnetApiLiveTest extends SubnetApiLiveTest {\n   public CloudNetworksUSSubnetApiLiveTest() {\n      provider = \"rackspace-cloudnetworks-us\";\n   }\n\n   @Override\n   public void testCreateUpdateAndDeleteSubnet() {\n      for (String region : api.getConfiguredRegions()) {\n         NetworkApi networkApi = api.getNetworkApi(region);\n         String networkId = networkApi.create(\n               Network.createBuilder(\"jclouds-live-test\").build()).getId();\n\n         SubnetApi subnetApi = api.getSubnetApi(region);\n         ImmutableSet<AllocationPool> allocationPools = ImmutableSet.of(\n               AllocationPool.builder().start(\"192.168.100.0\").end(\"192.168.100.2\").build()\n         );\n         ImmutableSet<HostRoute> hostRoutes = ImmutableSet.of(\n               HostRoute.builder().destinationCidr(\"192.168.100.0/30\").nextHop(\"192.168.100.4\").build()\n         );\n         Subnet subnet = subnetApi.create(Subnet.createBuilder(networkId, \"192.168.100.0/30\").ipVersion(4).allocationPools(allocationPools).hostRoutes(hostRoutes).build());\n         assertNotNull(subnet);\n\n         /* Test list and get */\n         Subnet subnetList = api.getSubnetApi(region).list().concat().toSet().iterator().next();\n         assertNotNull(subnetList);\n         Subnet subnetGet = api.getSubnetApi(region).get(subnetList.getId());\n         assertEquals(subnetList, subnetGet);\n         /***/\n\n         Subnet retrievedSubnet = subnetApi.get(subnet.getId());\n\n         assertEquals(retrievedSubnet.getId(), subnet.getId());\n         assertEquals(retrievedSubnet.getCidr(), \"192.168.100.0/30\");\n         assertTrue(retrievedSubnet.getDnsNameservers().isEmpty());\n         assertEquals(retrievedSubnet.getAllocationPools().size(), 1);\n         assertEquals(retrievedSubnet.getHostRoutes().size(), 1);\n         assertNotNull(subnetApi.update(retrievedSubnet.getId(), Subnet.updateBuilder().name(\"jclouds-live-test-update\").build()));\n\n         retrievedSubnet = subnetApi.get(retrievedSubnet.getId());\n\n         assertEquals(retrievedSubnet.getId(), subnet.getId());\n         assertEquals(retrievedSubnet.getName(), \"jclouds-live-test-update\");\n         assertTrue(retrievedSubnet.getDnsNameservers().isEmpty());\n\n         assertTrue(subnetApi.delete(subnet.getId()));\n         assertTrue(networkApi.delete(networkId));\n      }\n   }\n\n   @Override\n   public void testBulkCreateSubnet() {\n      throw new SkipException(\"unsupported functionality\");\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudnetworks-us/src/test/resources/logback.xml",
    "content": "<?xml version=\"1.0\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<configuration scan=\"false\">\n    <appender name=\"FILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <appender name=\"WIREFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds-wire.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <appender name=\"BLOBSTOREFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds-blobstore.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <root>\n        <level value=\"warn\" />\n    </root>\n\n    <logger name=\"org.jclouds\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"FILE\" />\n    </logger>\n\n    <logger name=\"jclouds.wire\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n\n    <logger name=\"jclouds.headers\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n\n    <logger name=\"jclouds.blobstore\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"BLOBSTOREFILE\" />\n    </logger>\n\n</configuration>\n"
  },
  {
    "path": "providers/rackspace-cloudservers-uk/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.rackspace.cloudservers.uk.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "providers/rackspace-cloudservers-uk/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.provider</groupId>\n  <artifactId>rackspace-cloudservers-uk</artifactId>\n  <name>jclouds Rackspace Next Generation Cloud Servers provider</name>\n  <description>OpenStack Nova implementation targeted to Rackspace Next Generation Cloud Servers</description>\n\n  <properties>\n    <test.rackspace-cloudservers-uk.endpoint>https://lon.identity.api.rackspacecloud.com/v2.0/</test.rackspace-cloudservers-uk.endpoint>\n    <test.rackspace-cloudservers-uk.api-version>2</test.rackspace-cloudservers-uk.api-version>\n    <test.rackspace-cloudservers-uk.build-version />\n    <test.rackspace-cloudservers-uk.identity>${test.rackspace-uk.identity}</test.rackspace-cloudservers-uk.identity>\n    <test.rackspace-cloudservers-uk.credential>${test.rackspace-uk.credential}</test.rackspace-cloudservers-uk.credential>\n    <test.rackspace-cloudservers-uk.template />\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>rackspace-cloudidentity</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-nova</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>rackspace-cloudidentity</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-nova</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-keystone</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-slf4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-sshj</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>ch.qos.logback</groupId>\n      <artifactId>logback-classic</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.provider</groupId>\n      <artifactId>rackspace-cloudblockstorage-uk</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <threadCount>1</threadCount>\n                  <systemPropertyVariables>\n                    <test.rackspace-cloudservers-uk.endpoint>${test.rackspace-cloudservers-uk.endpoint}</test.rackspace-cloudservers-uk.endpoint>\n                    <test.rackspace-cloudservers-uk.api-version>${test.rackspace-cloudservers-uk.api-version}</test.rackspace-cloudservers-uk.api-version>\n                    <test.rackspace-cloudservers-uk.build-version>${test.rackspace-cloudservers-uk.build-version}</test.rackspace-cloudservers-uk.build-version>\n                    <test.rackspace-cloudservers-uk.identity>${test.rackspace-cloudservers-uk.identity}</test.rackspace-cloudservers-uk.identity>\n                    <test.rackspace-cloudservers-uk.credential>${test.rackspace-cloudservers-uk.credential}</test.rackspace-cloudservers-uk.credential>\n                    <test.rackspace-cloudservers-uk.template>${test.rackspace-cloudservers-uk.template}</test.rackspace-cloudservers-uk.template>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n"
  },
  {
    "path": "providers/rackspace-cloudservers-uk/src/main/java/org/jclouds/rackspace/cloudservers/uk/CloudServersUKProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudservers.uk;\n\nimport static org.jclouds.compute.config.ComputeServiceProperties.TEMPLATE;\nimport static org.jclouds.location.reference.LocationConstants.ISO3166_CODES;\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_REGION;\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_REGIONS;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.CREDENTIAL_TYPE;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.KEYSTONE_VERSION;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.openstack.keystone.catalog.config.ServiceCatalogModule;\nimport org.jclouds.openstack.keystone.catalog.config.ServiceCatalogModule.RegionModule;\nimport org.jclouds.openstack.nova.v2_0.NovaApiMetadata;\nimport org.jclouds.openstack.nova.v2_0.config.NovaParserModule;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\nimport org.jclouds.rackspace.cloudidentity.v2_0.config.CloudIdentityAuthenticationModule;\nimport org.jclouds.rackspace.cloudidentity.v2_0.config.CloudIdentityCredentialTypes;\nimport org.jclouds.rackspace.cloudservers.uk.config.CloudServersUKComputeServiceContextModule;\nimport org.jclouds.rackspace.cloudservers.uk.config.CloudServersUKHttpApiModule;\n\nimport com.google.auto.service.AutoService;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n/**\n * Implementation of {@link ProviderMetadata} for Rackspace Next Generation Cloud Servers.\n */\n@AutoService(ProviderMetadata.class)\npublic class CloudServersUKProviderMetadata extends BaseProviderMetadata\n{\n\n    public static Builder builder()\n    {\n        return new Builder();\n    }\n\n    @Override\n    public Builder toBuilder()\n    {\n        return builder().fromProviderMetadata(this);\n    }\n\n    public CloudServersUKProviderMetadata()\n    {\n        super(builder());\n    }\n\n    public CloudServersUKProviderMetadata(final Builder builder)\n    {\n        super(builder);\n    }\n\n    public static Properties defaultProperties()\n    {\n        Properties properties = new Properties();\n        properties.setProperty(CREDENTIAL_TYPE, CloudIdentityCredentialTypes.API_KEY_CREDENTIALS);\n        properties.setProperty(KEYSTONE_VERSION, \"2\");\n        properties.setProperty(PROPERTY_REGIONS, \"LON\");\n        properties.setProperty(PROPERTY_REGION + \".LON.\" + ISO3166_CODES, \"GB-SLG\");\n        properties.setProperty(TEMPLATE, \"imageNameMatches=.*Ubuntu.*\");\n        return properties;\n    }\n\n    public static class Builder extends BaseProviderMetadata.Builder\n    {\n\n        protected Builder()\n        {\n            id(\"rackspace-cloudservers-uk\")\n                .name(\"Rackspace Next Generation Cloud Servers UK\")\n                .apiMetadata(\n                    new NovaApiMetadata()\n                        .toBuilder()\n                        .identityName(\"${userName}\")\n                        .credentialName(\"${apiKey}\")\n                        .version(\"2\")\n                        .defaultEndpoint(\"https://lon.identity.api.rackspacecloud.com/v2.0/\")\n                        .endpointName(\"identity service url ending in /v2.0/\")\n                        .documentation(\n                            URI.create(\"http://docs.rackspace.com/servers/api/v2/cs-devguide/content/ch_preface.html#webhelp-currentid\"))\n                        .defaultModules(\n                            ImmutableSet.<Class< ? extends Module>>builder()\n                                .add(CloudIdentityAuthenticationModule.class)\n                                .add(ServiceCatalogModule.class).add(RegionModule.class)\n                                .add(NovaParserModule.class).add(CloudServersUKHttpApiModule.class)\n                                .add(CloudServersUKComputeServiceContextModule.class).build())\n                        .build()).homepage(URI.create(\"http://www.rackspace.co.uk/opencloud\"))\n                .console(URI.create(\"https://mycloud.rackspace.co.uk/\"))\n                .linkedServices(\"rackspace-cloudservers-uk\", \"cloudfiles-swift-uk\")\n                .iso3166Codes(\"GB-SLG\")\n                .endpoint(\"https://lon.identity.api.rackspacecloud.com/v2.0/\")\n                .defaultProperties(CloudServersUKProviderMetadata.defaultProperties());\n        }\n\n        @Override\n        public CloudServersUKProviderMetadata build()\n        {\n            return new CloudServersUKProviderMetadata(this);\n        }\n\n        @Override\n        public Builder fromProviderMetadata(final ProviderMetadata in)\n        {\n            super.fromProviderMetadata(in);\n            return this;\n        }\n    }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudservers-uk/src/main/java/org/jclouds/rackspace/cloudservers/uk/config/CloudServersUKComputeServiceContextModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudservers.uk.config;\n\nimport java.util.Map;\n\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.openstack.nova.v2_0.compute.config.NovaComputeServiceContextModule;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.inject.Injector;\n\npublic class CloudServersUKComputeServiceContextModule extends NovaComputeServiceContextModule {\n\n   /**\n    * CloudServers images are accessible via the root user, not ubuntu\n    */\n   @Override\n   protected Map<OsFamily, LoginCredentials> osFamilyToCredentials(Injector injector) {\n      return ImmutableMap.of(OsFamily.WINDOWS, LoginCredentials.builder().user(\"Administrator\").build(),\n               OsFamily.UBUNTU, LoginCredentials.builder().user(\"root\").build());\n   }\n\n}\n"
  },
  {
    "path": "providers/rackspace-cloudservers-uk/src/main/java/org/jclouds/rackspace/cloudservers/uk/config/CloudServersUKHttpApiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudservers.uk.config;\n\nimport static org.jclouds.openstack.keystone.v2_0.config.KeystoneHttpApiModule.namespaceAliasBinder;\n\nimport java.net.URI;\n\nimport org.jclouds.openstack.nova.v2_0.config.NovaHttpApiModule;\nimport org.jclouds.openstack.nova.v2_0.extensions.ExtensionNamespaces;\nimport org.jclouds.rest.ConfiguresHttpApi;\n\nimport com.google.inject.multibindings.MapBinder;\n\n/**\n * Configures the Rackspace connection.\n */\n@ConfiguresHttpApi\npublic class CloudServersUKHttpApiModule extends NovaHttpApiModule {\n\n    @Override\n    protected void configure() {\n        super.configure();\n        MapBinder<URI, URI> aliases = namespaceAliasBinder(binder());\n        aliases.addBinding(URI.create(ExtensionNamespaces.VOLUME_ATTACHMENTS)).toInstance(\n            URI.create(\"http://docs.openstack.org/compute/ext/volumes/api/v1.1\"));\n    }\n\n}\n"
  },
  {
    "path": "providers/rackspace-cloudservers-uk/src/test/java/org/jclouds/rackspace/cloudservers/uk/CloudServersUKProviderMetadataExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudservers.uk;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.nova.v2_0.NovaApi;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiExpectTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * This test ensures that the wiring in {@link CloudServersUKProviderMetadata} is correct.\n */\n@Test(groups = \"unit\", testName = \"CloudServersUKProviderMetadataExpectTest\")\npublic class CloudServersUKProviderMetadataExpectTest extends BaseNovaApiExpectTest {\n\n   public CloudServersUKProviderMetadataExpectTest() {\n      this.provider = \"rackspace-cloudservers-uk\";\n      this.identity = \"myUsername\";\n      this.credential = \"myApiKey\";\n   }\n\n   public void testCanGetConfiguredRegions() {\n\n      HttpRequest authenticate = HttpRequest.builder().method(\"POST\")\n            .endpoint(\"https://lon.identity.api.rackspacecloud.com/v2.0/tokens\")\n            .addHeader(\"Accept\", \"application/json\")\n            .payload(payloadFromStringWithContentType(\n                     \"{\\\"auth\\\":{\\\"RAX-KSKEY:apiKeyCredentials\\\":{\\\"username\\\":\\\"myUsername\\\",\\\"apiKey\\\":\\\"myApiKey\\\"}}}\",\n                     \"application/json\")).build();\n\n\n      HttpResponse authenticationResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResourceWithContentType(\"/access_rax_uk.json\", \"application/json\")).build();\n\n      NovaApi whenNovaRegionExists = requestSendsResponse(authenticate, authenticationResponse);\n\n      assertEquals(whenNovaRegionExists.getConfiguredRegions(), ImmutableSet.of(\"LON\"));\n\n   }\n\n}\n"
  },
  {
    "path": "providers/rackspace-cloudservers-uk/src/test/java/org/jclouds/rackspace/cloudservers/uk/CloudServersUKProviderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n *\n *\n * ====================================================================\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * ====================================================================\n */\npackage org.jclouds.rackspace.cloudservers.uk;\n\nimport org.jclouds.openstack.nova.v2_0.NovaApiMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"CloudServersUKProviderTest\")\npublic class CloudServersUKProviderTest extends BaseProviderMetadataTest {\n\n   public CloudServersUKProviderTest() {\n      super(new CloudServersUKProviderMetadata(), new NovaApiMetadata());\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudservers-uk/src/test/java/org/jclouds/rackspace/cloudservers/uk/compute/CloudServersUKComputeServiceLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudservers.uk.compute;\n\nimport org.jclouds.openstack.nova.v2_0.compute.NovaComputeServiceLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"CloudServersUKComputeServiceLiveTest\")\npublic class CloudServersUKComputeServiceLiveTest extends NovaComputeServiceLiveTest {\n\n   public CloudServersUKComputeServiceLiveTest() {\n      provider = \"rackspace-cloudservers-uk\";\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudservers-uk/src/test/java/org/jclouds/rackspace/cloudservers/uk/compute/CloudServersUKTemplateBuilderLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudservers.uk.compute;\n\nimport static org.jclouds.compute.util.ComputeServiceUtils.getCores;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.internal.BaseTemplateBuilderLiveTest;\nimport org.jclouds.openstack.nova.v2_0.compute.options.NovaTemplateOptions;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"CloudServersUKTemplateBuilderLiveTest\")\npublic class CloudServersUKTemplateBuilderLiveTest extends BaseTemplateBuilderLiveTest {\n\n   public CloudServersUKTemplateBuilderLiveTest() {\n      provider = \"rackspace-cloudservers-uk\";\n   }\n\n   @Test\n   public void testTemplateBuilder() {\n      Template defaultTemplate = this.view.getComputeService().templateBuilder().build();\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true);\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.UBUNTU);\n      assertTrue(defaultTemplate.getImage().getName().contains(\"Ubuntu\"));\n      assertEquals(defaultTemplate.getImage().getDefaultCredentials().getUser(), \"root\");\n      assertEquals(defaultTemplate.getLocation().getId(), \"LON\");\n      assertEquals(defaultTemplate.getImage().getLocation().getId(), \"LON\");\n      assertEquals(defaultTemplate.getHardware().getLocation().getId(), \"LON\");\n      assertEquals(defaultTemplate.getOptions().as(NovaTemplateOptions.class).shouldAutoAssignFloatingIp(), false);\n      assertNull(defaultTemplate.getOptions().as(NovaTemplateOptions.class).getDiskConfig());\n      assertEquals(getCores(defaultTemplate.getHardware()), 1.0d);\n   }\n\n   @Override\n   protected Set<String> getIso3166Codes() {\n      return ImmutableSet.<String> of(\"GB-SLG\");\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudservers-uk/src/test/java/org/jclouds/rackspace/cloudservers/uk/compute/extensions/CloudServersUKImageExtensionLivetest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudservers.uk.compute.extensions;\n\nimport org.jclouds.compute.extensions.internal.BaseImageExtensionLiveTest;\nimport org.jclouds.sshj.config.SshjSshClientModule;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Module;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"CloudServersUKImageExtensionLivetest\")\npublic class CloudServersUKImageExtensionLivetest extends BaseImageExtensionLiveTest {\n\n   public CloudServersUKImageExtensionLivetest() {\n      provider = \"rackspace-cloudservers-uk\";\n   }\n\n   @Override\n   protected Module getSshModule() {\n      return new SshjSshClientModule();\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudservers-uk/src/test/java/org/jclouds/rackspace/cloudservers/uk/compute/extensions/CloudServersUKVolumeAttachmentExtensionLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudservers.uk.compute.extensions;\n\nimport java.util.Properties;\n\nimport org.jclouds.openstack.nova.v2_0.extensions.VolumeAttachmentApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"CloudServersUKVolumeAttachmentExtensionLiveTest\")\npublic class CloudServersUKVolumeAttachmentExtensionLiveTest extends VolumeAttachmentApiLiveTest {\n\n   public CloudServersUKVolumeAttachmentExtensionLiveTest() {\n      provider = \"rackspace-cloudservers-uk\";\n      // Specifying a device currently does not work for rackspace and causes issues\n      deviceId = \"\";\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      volumeProvider = \"rackspace-cloudblockstorage-uk\";\n      volumeSizeGB = 80;\n      singleRegion = \"LON\";\n      return props;\n   }\n\n}\n"
  },
  {
    "path": "providers/rackspace-cloudservers-uk/src/test/java/org/jclouds/rackspace/cloudservers/uk/features/CloudServersUKFlavorApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudservers.uk.features;\n\nimport org.jclouds.openstack.nova.v2_0.features.FlavorApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"CloudServersUKFlavorApiLiveTest\")\npublic class CloudServersUKFlavorApiLiveTest extends FlavorApiLiveTest {\n   public CloudServersUKFlavorApiLiveTest() {\n      provider = \"rackspace-cloudservers-uk\";\n   }\n\n}\n"
  },
  {
    "path": "providers/rackspace-cloudservers-uk/src/test/java/org/jclouds/rackspace/cloudservers/uk/features/CloudServersUKImageApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudservers.uk.features;\n\nimport org.jclouds.openstack.nova.v2_0.features.ImageApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"CloudServersUKImageApiLiveTest\")\npublic class CloudServersUKImageApiLiveTest extends ImageApiLiveTest {\n    public CloudServersUKImageApiLiveTest() {\n        provider = \"rackspace-cloudservers-uk\";\n    }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudservers-uk/src/test/java/org/jclouds/rackspace/cloudservers/uk/features/CloudServersUKServerApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudservers.uk.features;\n\nimport org.jclouds.openstack.nova.v2_0.features.ServerApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"CloudServersUKServerApiLiveTest\")\npublic class CloudServersUKServerApiLiveTest extends ServerApiLiveTest {\n   public CloudServersUKServerApiLiveTest() {\n      provider = \"rackspace-cloudservers-uk\";\n   }\n\n}\n"
  },
  {
    "path": "providers/rackspace-cloudservers-uk/src/test/resources/access_rax_uk.json",
    "content": "{\"access\":{\"token\":{\"id\":\"bdd18214-e266-4ad3-b985-d9bfb22c8da8\",\"expires\":\"2012-10-01T02:11:16.000+01:00\",\"tenant\":{\"id\":\"10001786\",\"name\":\"10001786\"}},\"serviceCatalog\":[{\"endpoints\":[{\"region\":\"LON\",\"tenantId\":\"MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953\",\"publicURL\":\"https:\\/\\/storage101.lon3.clouddrive.com\\/v1\\/MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953\",\"internalURL\":\"https:\\/\\/snet-storage101.lon3.clouddrive.com\\/v1\\/MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953\"}],\"name\":\"cloudFiles\",\"type\":\"object-store\"},{\"endpoints\":[{\"region\":\"LON\",\"tenantId\":\"MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953\",\"publicURL\":\"https:\\/\\/cdn3.clouddrive.com\\/v1\\/MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953\"}],\"name\":\"cloudFilesCDN\",\"type\":\"rax:object-cdn\"},{\"endpoints\":[{\"tenantId\":\"10001786\",\"publicURL\":\"https:\\/\\/lon.servers.api.rackspacecloud.com\\/v1.0\\/10001786\",\"versionInfo\":\"https:\\/\\/lon.servers.api.rackspacecloud.com\\/v1.0\",\"versionList\":\"https:\\/\\/lon.servers.api.rackspacecloud.com\\/\",\"versionId\":\"1.0\"}],\"name\":\"cloudServers\",\"type\":\"compute\"},{\"endpoints\":[{\"tenantId\":\"10001786\",\"publicURL\":\"https:\\/\\/lon.dns.api.rackspacecloud.com\\/v1.0\\/10001786\"}],\"name\":\"cloudDNS\",\"type\":\"rax:dns\"},{\"endpoints\":[{\"region\":\"LON\",\"tenantId\":\"10001786\",\"publicURL\":\"https:\\/\\/lon.loadbalancers.api.rackspacecloud.com\\/v1.0\\/10001786\"}],\"name\":\"cloudLoadBalancers\",\"type\":\"rax:load-balancer\"},{\"endpoints\":[{\"tenantId\":\"10001786\",\"publicURL\":\"https:\\/\\/monitoring.api.rackspacecloud.com\\/v1.0\\/10001786\"}],\"name\":\"cloudMonitoring\",\"type\":\"rax:monitor\"},{\"endpoints\":[{\"region\":\"LON\",\"tenantId\":\"10001786\",\"publicURL\":\"https:\\/\\/lon.databases.api.rackspacecloud.com\\/v1.0\\/10001786\"}],\"name\":\"cloudDatabases\",\"type\":\"rax:database\"},{\"endpoints\":[{\"region\":\"LON\",\"tenantId\":\"10001786\",\"publicURL\":\"https:\\/\\/lon.servers.api.rackspacecloud.com\\/v2\\/10001786\",\"versionInfo\":\"https:\\/\\/lon.servers.api.rackspacecloud.com\\/v2\",\"versionList\":\"https:\\/\\/lon.servers.api.rackspacecloud.com\\/\",\"versionId\":\"2\"}],\"name\":\"cloudServersOpenStack\",\"type\":\"compute\"}],\"user\":{\"id\":\"378\",\"roles\":[{\"id\":\"3\",\"description\":\"User Admin Role.\",\"name\":\"identity:user-admin\"}],\"name\":\"jclouds\",\"RAX-AUTH:defaultRegion\":\"\"}}}"
  },
  {
    "path": "providers/rackspace-cloudservers-uk/src/test/resources/raxImages.json",
    "content": "{\"images\": [{\"status\": \"ACTIVE\", \"updated\": \"2012-05-17T17:13:17Z\", \"links\": [{\"href\": \"https://dfw.servers.api.rackspacecloud.com/v2/413274/images/d6dd6c70-a122-4391-91a8-decb1a356549\", \"rel\": \"self\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/d6dd6c70-a122-4391-91a8-decb1a356549\", \"rel\": \"bookmark\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/d6dd6c70-a122-4391-91a8-decb1a356549\", \"type\": \"application/vnd.openstack.image\", \"rel\": \"alternate\"}], \"minDisk\": 0, \"id\": \"d6dd6c70-a122-4391-91a8-decb1a356549\", \"name\": \"Red Hat Enterprise Linux 6.1\", \"created\": \"2012-04-06T22:12:02Z\", \"OS-DCF:diskConfig\": \"AUTO\", \"progress\": 100, \"minRam\": 256, \"metadata\": {\"os_distro\": \"rhel\", \"org.openstack__1__os_distro\": \"com.redhat\", \"arch\": \"x86-64\", \"org.openstack__1__os_version\": \"6.1\", \"rax_managed\": \"false\", \"os_version\": \"6.1\", \"auto_disk_config\": \"True\", \"rax_options\": \"1\", \"os_type\": \"linux\", \"rax_activation_profile\": \"redhat\", \"org.openstack__1__architecture\": \"x64\"}}, {\"status\": \"ACTIVE\", \"updated\": \"2012-05-17T17:14:17Z\", \"links\": [{\"href\": \"https://dfw.servers.api.rackspacecloud.com/v2/413274/images/644be485-411d-4bac-aba5-5f60641d92b5\", \"rel\": \"self\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/644be485-411d-4bac-aba5-5f60641d92b5\", \"rel\": \"bookmark\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/644be485-411d-4bac-aba5-5f60641d92b5\", \"type\": \"application/vnd.openstack.image\", \"rel\": \"alternate\"}], \"minDisk\": 0, \"id\": \"644be485-411d-4bac-aba5-5f60641d92b5\", \"name\": \"Red Hat Enterprise Linux 5.5\", \"created\": \"2012-04-06T22:11:47Z\", \"OS-DCF:diskConfig\": \"AUTO\", \"progress\": 100, \"minRam\": 256, \"metadata\": {\"os_distro\": \"rhel\", \"org.openstack__1__os_distro\": \"com.redhat\", \"arch\": \"x86-64\", \"org.openstack__1__os_version\": \"5.5\", \"rax_managed\": \"false\", \"os_version\": \"5.5\", \"auto_disk_config\": \"True\", \"rax_options\": \"1\", \"os_type\": \"linux\", \"rax_activation_profile\": \"redhat\", \"org.openstack__1__architecture\": \"x64\"}}, {\"status\": \"ACTIVE\", \"updated\": \"2012-05-17T17:14:18Z\", \"links\": [{\"href\": \"https://dfw.servers.api.rackspacecloud.com/v2/413274/images/8bf22129-8483-462b-a020-1754ec822770\", \"rel\": \"self\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/8bf22129-8483-462b-a020-1754ec822770\", \"rel\": \"bookmark\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/8bf22129-8483-462b-a020-1754ec822770\", \"type\": \"application/vnd.openstack.image\", \"rel\": \"alternate\"}], \"minDisk\": 10, \"id\": \"8bf22129-8483-462b-a020-1754ec822770\", \"name\": \"Ubuntu 11.04\", \"created\": \"2012-02-28T21:24:42Z\", \"OS-DCF:diskConfig\": \"AUTO\", \"progress\": 100, \"minRam\": 256, \"metadata\": {\"os_distro\": \"ubuntu\", \"org.openstack__1__os_distro\": \"com.ubuntu\", \"org.openstack__1__os_version\": \"11.10\", \"rax_managed\": \"false\", \"os_version\": \"11.10\", \"auto_disk_config\": \"True\", \"rax_options\": \"0\", \"os_type\": \"linux\", \"arch\": \"x86-64\", \"org.openstack__1__architecture\": \"x64\"}}, {\"status\": \"ACTIVE\", \"updated\": \"2012-05-17T17:13:50Z\", \"links\": [{\"href\": \"https://dfw.servers.api.rackspacecloud.com/v2/413274/images/0d589460-f177-4b0f-81c1-8ab8903ac7d8\", \"rel\": \"self\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/0d589460-f177-4b0f-81c1-8ab8903ac7d8\", \"rel\": \"bookmark\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/0d589460-f177-4b0f-81c1-8ab8903ac7d8\", \"type\": \"application/vnd.openstack.image\", \"rel\": \"alternate\"}], \"minDisk\": 10, \"id\": \"0d589460-f177-4b0f-81c1-8ab8903ac7d8\", \"name\": \"Arch 2011.10\", \"created\": \"2012-02-28T19:42:22Z\", \"OS-DCF:diskConfig\": \"AUTO\", \"progress\": 100, \"minRam\": 256, \"metadata\": {\"os_distro\": \"arch\", \"org.openstack__1__os_distro\": \"org.archlinux\", \"org.openstack__1__os_version\": \"2011.10\", \"rax_managed\": \"false\", \"os_version\": \"2011.10\", \"auto_disk_config\": \"True\", \"rax_options\": \"0\", \"os_type\": \"linux\", \"arch\": \"x86-64\", \"org.openstack__1__architecture\": \"x64\"}}, {\"status\": \"ACTIVE\", \"updated\": \"2012-05-17T17:12:59Z\", \"links\": [{\"href\": \"https://dfw.servers.api.rackspacecloud.com/v2/413274/images/096c55e5-39f3-48cf-a413-68d9377a3ab6\", \"rel\": \"self\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/096c55e5-39f3-48cf-a413-68d9377a3ab6\", \"rel\": \"bookmark\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/096c55e5-39f3-48cf-a413-68d9377a3ab6\", \"type\": \"application/vnd.openstack.image\", \"rel\": \"alternate\"}], \"minDisk\": 10, \"id\": \"096c55e5-39f3-48cf-a413-68d9377a3ab6\", \"name\": \"openSUKE 12\", \"created\": \"2012-02-28T19:42:04Z\", \"OS-DCF:diskConfig\": \"AUTO\", \"progress\": 100, \"minRam\": 256, \"metadata\": {\"os_distro\": \"opensuse\", \"org.openstack__1__os_distro\": \"org.opensuse\", \"org.openstack__1__os_version\": \"12.0\", \"rax_managed\": \"false\", \"os_version\": \"12\", \"auto_disk_config\": \"True\", \"rax_options\": \"0\", \"os_type\": \"linux\", \"arch\": \"x86-64\", \"org.openstack__1__architecture\": \"x64\"}}, {\"status\": \"ACTIVE\", \"updated\": \"2012-05-17T17:13:17Z\", \"links\": [{\"href\": \"https://dfw.servers.api.rackspacecloud.com/v2/413274/images/040e6c82-6618-4f53-9f27-44db2c4ce9ee\", \"rel\": \"self\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/040e6c82-6618-4f53-9f27-44db2c4ce9ee\", \"rel\": \"bookmark\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/040e6c82-6618-4f53-9f27-44db2c4ce9ee\", \"type\": \"application/vnd.openstack.image\", \"rel\": \"alternate\"}], \"minDisk\": 10, \"id\": \"040e6c82-6618-4f53-9f27-44db2c4ce9ee\", \"name\": \"Gentoo 11.0\", \"created\": \"2012-02-28T19:41:50Z\", \"OS-DCF:diskConfig\": \"AUTO\", \"progress\": 100, \"minRam\": 256, \"metadata\": {\"os_distro\": \"gentoo\", \"org.openstack__1__os_distro\": \"org.gentoo\", \"org.openstack__1__os_version\": \"11.0\", \"rax_managed\": \"false\", \"os_version\": \"11.0\", \"auto_disk_config\": \"True\", \"rax_options\": \"0\", \"os_type\": \"linux\", \"arch\": \"x86-64\", \"org.openstack__1__architecture\": \"x64\"}}, {\"status\": \"ACTIVE\", \"updated\": \"2012-05-17T17:13:50Z\", \"links\": [{\"href\": \"https://dfw.servers.api.rackspacecloud.com/v2/413274/images/a10eacf7-ac15-4225-b533-5744f1fe47c1\", \"rel\": \"self\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/a10eacf7-ac15-4225-b533-5744f1fe47c1\", \"rel\": \"bookmark\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/a10eacf7-ac15-4225-b533-5744f1fe47c1\", \"type\": \"application/vnd.openstack.image\", \"rel\": \"alternate\"}], \"minDisk\": 10, \"id\": \"a10eacf7-ac15-4225-b533-5744f1fe47c1\", \"name\": \"Debian 6 (Squeeze)\", \"created\": \"2012-02-28T19:41:44Z\", \"OS-DCF:diskConfig\": \"AUTO\", \"progress\": 100, \"minRam\": 256, \"metadata\": {\"os_distro\": \"debian\", \"org.openstack__1__os_distro\": \"org.debian\", \"org.openstack__1__os_version\": \"6.0\", \"rax_managed\": \"false\", \"os_version\": \"6\", \"auto_disk_config\": \"True\", \"rax_options\": \"0\", \"os_type\": \"linux\", \"arch\": \"x86-64\", \"org.openstack__1__architecture\": \"x64\"}}, {\"status\": \"ACTIVE\", \"updated\": \"2012-05-17T17:14:18Z\", \"links\": [{\"href\": \"https://dfw.servers.api.rackspacecloud.com/v2/413274/images/25a025a8-b126-409c-ab02-0ca70af61d8d\", \"rel\": \"self\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/25a025a8-b126-409c-ab02-0ca70af61d8d\", \"rel\": \"bookmark\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/25a025a8-b126-409c-ab02-0ca70af61d8d\", \"type\": \"application/vnd.openstack.image\", \"rel\": \"alternate\"}], \"minDisk\": 10, \"id\": \"25a025a8-b126-409c-ab02-0ca70af61d8d\", \"name\": \"Debian 5 (Lenny)\", \"created\": \"2012-02-28T19:41:37Z\", \"OS-DCF:diskConfig\": \"AUTO\", \"progress\": 100, \"minRam\": 256, \"metadata\": {\"os_distro\": \"debian\", \"org.openstack__1__os_distro\": \"org.debian\", \"org.openstack__1__os_version\": \"5.0\", \"rax_managed\": \"false\", \"os_version\": \"5\", \"auto_disk_config\": \"True\", \"rax_options\": \"0\", \"os_type\": \"linux\", \"arch\": \"x86-64\", \"org.openstack__1__architecture\": \"x64\"}}, {\"status\": \"ACTIVE\", \"updated\": \"2012-05-17T17:12:26Z\", \"links\": [{\"href\": \"https://dfw.servers.api.rackspacecloud.com/v2/413274/images/bca91446-e60e-42e7-9e39-0582e7e20fb9\", \"rel\": \"self\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/bca91446-e60e-42e7-9e39-0582e7e20fb9\", \"rel\": \"bookmark\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/bca91446-e60e-42e7-9e39-0582e7e20fb9\", \"type\": \"application/vnd.openstack.image\", \"rel\": \"alternate\"}], \"minDisk\": 10, \"id\": \"bca91446-e60e-42e7-9e39-0582e7e20fb9\", \"name\": \"Fedora 16\", \"created\": \"2012-02-28T19:41:07Z\", \"OS-DCF:diskConfig\": \"AUTO\", \"progress\": 100, \"minRam\": 256, \"metadata\": {\"os_distro\": \"fedora\", \"org.openstack__1__os_distro\": \"org.fedoraproject\", \"org.openstack__1__os_version\": \"16.0\", \"rax_managed\": \"false\", \"os_version\": \"16\", \"auto_disk_config\": \"True\", \"rax_options\": \"0\", \"os_type\": \"linux\", \"arch\": \"x86-64\", \"org.openstack__1__architecture\": \"x64\"}}, {\"status\": \"ACTIVE\", \"updated\": \"2012-05-17T17:13:50Z\", \"links\": [{\"href\": \"https://dfw.servers.api.rackspacecloud.com/v2/413274/images/7c151d6f-d87b-420d-9f8e-b6ed7a160fbb\", \"rel\": \"self\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/7c151d6f-d87b-420d-9f8e-b6ed7a160fbb\", \"rel\": \"bookmark\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/7c151d6f-d87b-420d-9f8e-b6ed7a160fbb\", \"type\": \"application/vnd.openstack.image\", \"rel\": \"alternate\"}], \"minDisk\": 10, \"id\": \"7c151d6f-d87b-420d-9f8e-b6ed7a160fbb\", \"name\": \"Fedora 15\", \"created\": \"2012-02-28T19:40:57Z\", \"OS-DCF:diskConfig\": \"AUTO\", \"progress\": 100, \"minRam\": 256, \"metadata\": {\"os_distro\": \"fedora\", \"org.openstack__1__os_distro\": \"org.fedoraproject\", \"org.openstack__1__os_version\": \"15.0\", \"rax_managed\": \"false\", \"os_version\": \"15\", \"auto_disk_config\": \"True\", \"rax_options\": \"0\", \"os_type\": \"linux\", \"arch\": \"x86-64\", \"org.openstack__1__architecture\": \"x64\"}}, {\"status\": \"ACTIVE\", \"updated\": \"2012-05-17T17:14:17Z\", \"links\": [{\"href\": \"https://dfw.servers.api.rackspacecloud.com/v2/413274/images/03318d19-b6e6-4092-9b5c-4758ee0ada60\", \"rel\": \"self\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/03318d19-b6e6-4092-9b5c-4758ee0ada60\", \"rel\": \"bookmark\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/03318d19-b6e6-4092-9b5c-4758ee0ada60\", \"type\": \"application/vnd.openstack.image\", \"rel\": \"alternate\"}], \"minDisk\": 10, \"id\": \"03318d19-b6e6-4092-9b5c-4758ee0ada60\", \"name\": \"CentOS 5.6\", \"created\": \"2012-02-28T19:40:46Z\", \"OS-DCF:diskConfig\": \"AUTO\", \"progress\": 100, \"minRam\": 256, \"metadata\": {\"os_distro\": \"centos\", \"org.openstack__1__os_distro\": \"org.centos\", \"org.openstack__1__os_version\": \"5.6\", \"rax_managed\": \"false\", \"os_version\": \"5.6\", \"auto_disk_config\": \"True\", \"rax_options\": \"0\", \"os_type\": \"linux\", \"arch\": \"x86-64\", \"org.openstack__1__architecture\": \"x64\"}}, {\"status\": \"ACTIVE\", \"updated\": \"2012-05-17T17:14:18Z\", \"links\": [{\"href\": \"https://dfw.servers.api.rackspacecloud.com/v2/413274/images/a3a2c42f-575f-4381-9c6d-fcd3b7d07d17\", \"rel\": \"self\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/a3a2c42f-575f-4381-9c6d-fcd3b7d07d17\", \"rel\": \"bookmark\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/a3a2c42f-575f-4381-9c6d-fcd3b7d07d17\", \"type\": \"application/vnd.openstack.image\", \"rel\": \"alternate\"}], \"minDisk\": 10, \"id\": \"a3a2c42f-575f-4381-9c6d-fcd3b7d07d17\", \"name\": \"CentOS 6.0\", \"created\": \"2012-02-28T19:40:32Z\", \"OS-DCF:diskConfig\": \"AUTO\", \"progress\": 100, \"minRam\": 256, \"metadata\": {\"os_distro\": \"centos\", \"org.openstack__1__os_distro\": \"org.centos\", \"org.openstack__1__os_version\": \"6.0\", \"rax_managed\": \"false\", \"os_version\": \"6.0\", \"auto_disk_config\": \"True\", \"rax_options\": \"0\", \"os_type\": \"linux\", \"arch\": \"x86-64\", \"org.openstack__1__architecture\": \"x64\"}}, {\"status\": \"ACTIVE\", \"updated\": \"2012-05-17T17:14:18Z\", \"links\": [{\"href\": \"https://dfw.servers.api.rackspacecloud.com/v2/413274/images/5f68715f-201f-4600-b5a1-0b97e2b1cb31\", \"rel\": \"self\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/5f68715f-201f-4600-b5a1-0b97e2b1cb31\", \"rel\": \"bookmark\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/5f68715f-201f-4600-b5a1-0b97e2b1cb31\", \"type\": \"application/vnd.openstack.image\", \"rel\": \"alternate\"}], \"minDisk\": 10, \"id\": \"5f68715f-201f-4600-b5a1-0b97e2b1cb31\", \"name\": \"Ubuntu 10.04 LTS\", \"created\": \"2012-02-28T19:40:25Z\", \"OS-DCF:diskConfig\": \"AUTO\", \"progress\": 100, \"minRam\": 256, \"metadata\": {\"os_distro\": \"ubuntu\", \"org.openstack__1__os_distro\": \"com.ubuntu\", \"org.openstack__1__os_version\": \"10.04\", \"rax_managed\": \"false\", \"os_version\": \"10.04LTS\", \"auto_disk_config\": \"True\", \"rax_options\": \"0\", \"os_type\": \"linux\", \"arch\": \"x86-64\", \"org.openstack__1__architecture\": \"x64\"}}, {\"status\": \"ACTIVE\", \"updated\": \"2012-02-28T19:39:05Z\", \"links\": [{\"href\": \"https://dfw.servers.api.rackspacecloud.com/v2/413274/images/3afe97b2-26dc-49c5-a2cc-a2fc8d80c001\", \"rel\": \"self\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/3afe97b2-26dc-49c5-a2cc-a2fc8d80c001\", \"rel\": \"bookmark\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/3afe97b2-26dc-49c5-a2cc-a2fc8d80c001\", \"type\": \"application/vnd.openstack.image\", \"rel\": \"alternate\"}], \"minDisk\": 10, \"id\": \"3afe97b2-26dc-49c5-a2cc-a2fc8d80c001\", \"name\": \"Ubuntu 11.10\", \"created\": \"2012-02-28T19:38:57Z\", \"OS-DCF:diskConfig\": \"AUTO\", \"progress\": 100, \"minRam\": 256, \"metadata\": {\"os_distro\": \"ubuntu\", \"rax_managed\": \"false\", \"os_version\": \"11.10\", \"auto_disk_config\": \"True\", \"rax_options\": \"0\", \"os_type\": \"linux\", \"arch\": \"x86-64\"}}]}\n"
  },
  {
    "path": "providers/rackspace-cloudservers-us/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.rackspace.cloudservers.us.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "providers/rackspace-cloudservers-us/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.provider</groupId>\n  <artifactId>rackspace-cloudservers-us</artifactId>\n  <name>jclouds Rackspace Next Generation Cloud Servers US provider</name>\n  <description>OpenStack Nova implementation targeted to Rackspace Next Generation Cloud Servers US</description>\n\n  <properties>\n    <test.rackspace-cloudservers-us.endpoint>https://identity.api.rackspacecloud.com/v2.0/</test.rackspace-cloudservers-us.endpoint>\n    <test.rackspace-cloudservers-us.api-version>2</test.rackspace-cloudservers-us.api-version>\n    <test.rackspace-cloudservers-us.build-version />\n    <test.rackspace-cloudservers-us.identity>${test.rackspace-us.identity}</test.rackspace-cloudservers-us.identity>\n    <test.rackspace-cloudservers-us.credential>${test.rackspace-us.credential}</test.rackspace-cloudservers-us.credential>\n    <test.rackspace-cloudservers-us.template />\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>rackspace-cloudidentity</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-nova</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>rackspace-cloudidentity</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-nova</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>openstack-keystone</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-slf4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-sshj</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>ch.qos.logback</groupId>\n      <artifactId>logback-classic</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.provider</groupId>\n      <artifactId>rackspace-cloudblockstorage-us</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <threadCount>1</threadCount>\n                  <systemPropertyVariables>\n                    <test.rackspace-cloudservers-us.endpoint>${test.rackspace-cloudservers-us.endpoint}</test.rackspace-cloudservers-us.endpoint>\n                    <test.rackspace-cloudservers-us.api-version>${test.rackspace-cloudservers-us.api-version}</test.rackspace-cloudservers-us.api-version>\n                    <test.rackspace-cloudservers-us.build-version>${test.rackspace-cloudservers-us.build-version}</test.rackspace-cloudservers-us.build-version>\n                    <test.rackspace-cloudservers-us.identity>${test.rackspace-cloudservers-us.identity}</test.rackspace-cloudservers-us.identity>\n                    <test.rackspace-cloudservers-us.credential>${test.rackspace-cloudservers-us.credential}</test.rackspace-cloudservers-us.credential>\n                    <test.rackspace-cloudservers-us.template>${test.rackspace-cloudservers-us.template}</test.rackspace-cloudservers-us.template>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n"
  },
  {
    "path": "providers/rackspace-cloudservers-us/src/main/java/org/jclouds/rackspace/cloudservers/us/CloudServersUSProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudservers.us;\n\nimport static org.jclouds.compute.config.ComputeServiceProperties.TEMPLATE;\nimport static org.jclouds.location.reference.LocationConstants.ISO3166_CODES;\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_REGION;\nimport static org.jclouds.location.reference.LocationConstants.PROPERTY_REGIONS;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.CREDENTIAL_TYPE;\nimport static org.jclouds.openstack.keystone.config.KeystoneProperties.KEYSTONE_VERSION;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.openstack.keystone.catalog.config.ServiceCatalogModule;\nimport org.jclouds.openstack.keystone.catalog.config.ServiceCatalogModule.RegionModule;\nimport org.jclouds.openstack.nova.v2_0.NovaApiMetadata;\nimport org.jclouds.openstack.nova.v2_0.config.NovaParserModule;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\nimport org.jclouds.rackspace.cloudidentity.v2_0.config.CloudIdentityAuthenticationModule;\nimport org.jclouds.rackspace.cloudidentity.v2_0.config.CloudIdentityCredentialTypes;\nimport org.jclouds.rackspace.cloudservers.us.config.CloudServersUSComputeServiceContextModule;\nimport org.jclouds.rackspace.cloudservers.us.config.CloudServersUSHttpApiModule;\n\nimport com.google.auto.service.AutoService;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n/**\n * Implementation of {@link ProviderMetadata} for Rackspace Next Generation Cloud Servers.\n */\n@AutoService(ProviderMetadata.class)\npublic class CloudServersUSProviderMetadata extends BaseProviderMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromProviderMetadata(this);\n   }\n\n   public CloudServersUSProviderMetadata() {\n      super(builder());\n   }\n\n   public CloudServersUSProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = new Properties();\n      properties.setProperty(CREDENTIAL_TYPE, CloudIdentityCredentialTypes.API_KEY_CREDENTIALS);\n      properties.setProperty(KEYSTONE_VERSION, \"2\");\n      properties.setProperty(PROPERTY_REGIONS, \"ORD,DFW,IAD,SYD,HKG\");\n      properties.setProperty(PROPERTY_REGION + \".ORD.\" + ISO3166_CODES, \"US-IL\");\n      properties.setProperty(PROPERTY_REGION + \".DFW.\" + ISO3166_CODES, \"US-TX\");\n      properties.setProperty(PROPERTY_REGION + \".IAD.\" + ISO3166_CODES, \"US-VA\");\n      properties.setProperty(PROPERTY_REGION + \".SYD.\" + ISO3166_CODES, \"AU-NSW\");\n      properties.setProperty(PROPERTY_REGION + \".HKG.\" + ISO3166_CODES, \"HK\");\n      /*\n      * Debian - script problems\n      * Ubuntu - script problems\n      * */\n      properties.setProperty(TEMPLATE, \"imageNameMatches=.*Ubuntu.*,os64Bit=true\");\n      return properties;\n   }\n\n   public static class Builder extends BaseProviderMetadata.Builder {\n\n      protected Builder() {\n         id(\"rackspace-cloudservers-us\")\n         .name(\"Rackspace Next Generation Cloud Servers US\")\n         .apiMetadata(new NovaApiMetadata().toBuilder()\n                  .identityName(\"${userName}\")\n                  .credentialName(\"${apiKey}\")\n                  .version(\"2\")\n                  .defaultEndpoint(\"https://identity.api.rackspacecloud.com/v2.0/\")\n                  .endpointName(\"identity service url ending in /v2.0/\")\n                  .documentation(\n                        URI.create(\"http://docs.rackspace.com/loadbalancers/api/v1.0/clb-devguide/content/index.html\"))\n                  .defaultModules(ImmutableSet.<Class<? extends Module>>builder()\n                        .add(CloudIdentityAuthenticationModule.class)\n                        .add(ServiceCatalogModule.class)\n                        .add(RegionModule.class)\n                        .add(NovaParserModule.class)\n                        .add(CloudServersUSHttpApiModule.class)\n                        .add(CloudServersUSComputeServiceContextModule.class).build())\n                  .build())\n         .homepage(URI.create(\"http://www.rackspace.com/cloud/nextgen\"))\n         .console(URI.create(\"https://mycloud.rackspace.com\"))\n         .linkedServices(\"rackspace-cloudservers-us\", \"cloudfiles-swift-us\")\n         .iso3166Codes(\"US-IL\", \"US-TX\", \"US-VA\", \"AU-NSW\", \"HK\")\n         .endpoint(\"https://identity.api.rackspacecloud.com/v2.0/\")\n         .defaultProperties(CloudServersUSProviderMetadata.defaultProperties());\n      }\n\n      @Override\n      public CloudServersUSProviderMetadata build() {\n         return new CloudServersUSProviderMetadata(this);\n      }\n\n      @Override\n      public Builder fromProviderMetadata(ProviderMetadata in) {\n         super.fromProviderMetadata(in);\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudservers-us/src/main/java/org/jclouds/rackspace/cloudservers/us/config/CloudServersUSComputeServiceContextModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudservers.us.config;\n\nimport java.util.Map;\n\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.openstack.nova.v2_0.compute.config.NovaComputeServiceContextModule;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.inject.Injector;\n\npublic class CloudServersUSComputeServiceContextModule extends NovaComputeServiceContextModule {\n\n   /**\n    * CloudServers images are accessible via the root user, not ubuntu\n    */\n   @Override\n   protected Map<OsFamily, LoginCredentials> osFamilyToCredentials(Injector injector) {\n      return ImmutableMap.of(OsFamily.WINDOWS, LoginCredentials.builder().user(\"Administrator\").build(),\n               OsFamily.UBUNTU, LoginCredentials.builder().user(\"root\").build());\n   }\n\n}\n"
  },
  {
    "path": "providers/rackspace-cloudservers-us/src/main/java/org/jclouds/rackspace/cloudservers/us/config/CloudServersUSHttpApiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudservers.us.config;\n\nimport static org.jclouds.openstack.keystone.v2_0.config.KeystoneHttpApiModule.namespaceAliasBinder;\n\nimport java.net.URI;\n\nimport org.jclouds.openstack.nova.v2_0.config.NovaHttpApiModule;\nimport org.jclouds.openstack.nova.v2_0.extensions.ExtensionNamespaces;\nimport org.jclouds.rest.ConfiguresHttpApi;\n\nimport com.google.inject.multibindings.MapBinder;\n\n/**\n * Configures the Rackspace connection.\n *\n */\n@ConfiguresHttpApi\npublic class CloudServersUSHttpApiModule extends NovaHttpApiModule {\n\n   @Override\n   protected void configure() {\n      super.configure();\n      MapBinder<URI, URI> aliases = namespaceAliasBinder(binder());\n      aliases.addBinding(URI.create(ExtensionNamespaces.VOLUME_ATTACHMENTS)).toInstance(\n            URI.create(\"http://docs.openstack.org/compute/ext/volumes/api/v1.1\"));\n   }\n\n}\n"
  },
  {
    "path": "providers/rackspace-cloudservers-us/src/test/java/org/jclouds/rackspace/cloudservers/us/CloudServersUSProviderMetadataExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudservers.us;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.openstack.nova.v2_0.NovaApi;\nimport org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiExpectTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * This test ensures that the wiring in {@link CloudServersUSProviderMetadata} is correct.\n */\n@Test(groups = \"unit\", testName = \"CloudServersUSProviderMetadataExpectTest\")\npublic class CloudServersUSProviderMetadataExpectTest extends BaseNovaApiExpectTest {\n\n   public CloudServersUSProviderMetadataExpectTest() {\n      this.provider = \"rackspace-cloudservers-us\";\n      this.identity = \"myUsername\";\n      this.credential = \"myApiKey\";\n   }\n\n   public void testCanGetConfiguredRegions() {\n\n      HttpRequest authenticate = HttpRequest.builder().method(\"POST\")\n            .endpoint(\"https://identity.api.rackspacecloud.com/v2.0/tokens\")\n            .addHeader(\"Accept\", \"application/json\")\n            .payload(payloadFromStringWithContentType(\n                     \"{\\\"auth\\\":{\\\"RAX-KSKEY:apiKeyCredentials\\\":{\\\"username\\\":\\\"myUsername\\\",\\\"apiKey\\\":\\\"myApiKey\\\"}}}\",\n                     \"application/json\")).build();\n\n\n      HttpResponse authenticationResponse = HttpResponse.builder().statusCode(200)\n            .payload(payloadFromResourceWithContentType(\"/access_rax_us.json\", \"application/json\")).build();\n\n      NovaApi whenNovaRegionExists = requestSendsResponse(authenticate, authenticationResponse);\n\n      assertEquals(whenNovaRegionExists.getConfiguredRegions(), ImmutableSet.of(\"ORD\", \"DFW\"));\n\n   }\n\n}\n"
  },
  {
    "path": "providers/rackspace-cloudservers-us/src/test/java/org/jclouds/rackspace/cloudservers/us/CloudServersUSProviderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n *\n *\n * ====================================================================\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * ====================================================================\n */\npackage org.jclouds.rackspace.cloudservers.us;\n\nimport org.jclouds.openstack.nova.v2_0.NovaApiMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"CloudServersUSProviderTest\")\npublic class CloudServersUSProviderTest extends BaseProviderMetadataTest {\n\n   public CloudServersUSProviderTest() {\n      super(new CloudServersUSProviderMetadata(), new NovaApiMetadata());\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudservers-us/src/test/java/org/jclouds/rackspace/cloudservers/us/compute/CloudServersUSComputeServiceLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudservers.us.compute;\n\nimport org.jclouds.openstack.nova.v2_0.compute.NovaComputeServiceLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"CloudServersUSComputeServiceLiveTest\")\npublic class CloudServersUSComputeServiceLiveTest extends NovaComputeServiceLiveTest {\n\n   public CloudServersUSComputeServiceLiveTest() {\n      provider = \"rackspace-cloudservers-us\";\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudservers-us/src/test/java/org/jclouds/rackspace/cloudservers/us/compute/CloudServersUSTemplateBuilderLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudservers.us.compute;\n\nimport static org.jclouds.compute.util.ComputeServiceUtils.getCores;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.internal.BaseTemplateBuilderLiveTest;\nimport org.jclouds.openstack.nova.v2_0.compute.options.NovaTemplateOptions;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"CloudServersUSTemplateBuilderLiveTest\")\npublic class CloudServersUSTemplateBuilderLiveTest extends BaseTemplateBuilderLiveTest {\n\n   public CloudServersUSTemplateBuilderLiveTest() {\n      provider = \"rackspace-cloudservers-us\";\n   }\n\n   @Test\n   public void testTemplateBuilder() {\n      Template defaultTemplate = this.view.getComputeService().templateBuilder().build();\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true);\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.UBUNTU);\n      assertTrue(defaultTemplate.getImage().getName().contains(\"Ubuntu\"));\n      assertEquals(defaultTemplate.getImage().getDefaultCredentials().getUser(), \"root\");\n      assertEquals(defaultTemplate.getLocation().getId(), \"SYD\");\n      assertEquals(defaultTemplate.getImage().getLocation().getId(), \"SYD\");\n      assertEquals(defaultTemplate.getHardware().getLocation().getId(), \"SYD\");\n      assertEquals(defaultTemplate.getOptions().as(NovaTemplateOptions.class).shouldAutoAssignFloatingIp(), false);\n      assertNull(defaultTemplate.getOptions().as(NovaTemplateOptions.class).getDiskConfig());\n      assertEquals(getCores(defaultTemplate.getHardware()), 1.0d);\n   }\n\n   @Override\n   protected Set<String> getIso3166Codes() {\n      return ImmutableSet.of(\"US-IL\", \"US-TX\", \"US-VA\", \"AU-NSW\", \"HK\");\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudservers-us/src/test/java/org/jclouds/rackspace/cloudservers/us/compute/extensions/CloudServersUSImageExtensionLivetest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudservers.us.compute.extensions;\n\nimport org.jclouds.compute.extensions.internal.BaseImageExtensionLiveTest;\nimport org.jclouds.sshj.config.SshjSshClientModule;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Module;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"CloudServersUSImageExtensionLivetest\")\npublic class CloudServersUSImageExtensionLivetest extends BaseImageExtensionLiveTest {\n\n   public CloudServersUSImageExtensionLivetest() {\n      provider = \"rackspace-cloudservers-us\";\n   }\n\n   @Override\n   protected Module getSshModule() {\n      return new SshjSshClientModule();\n   }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudservers-us/src/test/java/org/jclouds/rackspace/cloudservers/us/compute/extensions/CloudServersUSVolumeAttachmentExtensionLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudservers.us.compute.extensions;\n\nimport java.util.Properties;\n\nimport org.jclouds.openstack.nova.v2_0.extensions.VolumeAttachmentApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"CloudServersUSVolumeAttachmentExtensionLivetest\")\npublic class CloudServersUSVolumeAttachmentExtensionLiveTest extends VolumeAttachmentApiLiveTest {\n\n   public CloudServersUSVolumeAttachmentExtensionLiveTest() {\n      provider = \"rackspace-cloudservers-us\";\n      // Specifying a device currently does not work for rackspace and causes issues\n      deviceId = \"\";\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties props = super.setupProperties();\n      volumeProvider = \"rackspace-cloudblockstorage-us\";\n      volumeSizeGB = 80;\n      singleRegion = \"IAD\";\n      return props;\n   }\n\n}\n"
  },
  {
    "path": "providers/rackspace-cloudservers-us/src/test/java/org/jclouds/rackspace/cloudservers/us/features/CloudServersUSFlavorApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudservers.us.features;\n\nimport org.jclouds.openstack.nova.v2_0.features.FlavorApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"CloudServersUSFlavorApiLiveTest\")\npublic class CloudServersUSFlavorApiLiveTest extends FlavorApiLiveTest {\n   public CloudServersUSFlavorApiLiveTest() {\n      provider = \"rackspace-cloudservers-us\";\n   }\n\n}\n"
  },
  {
    "path": "providers/rackspace-cloudservers-us/src/test/java/org/jclouds/rackspace/cloudservers/us/features/CloudServersUSImageApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudservers.us.features;\n\nimport org.jclouds.openstack.nova.v2_0.features.ImageApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"CloudServersUSImageApiLiveTest\")\npublic class CloudServersUSImageApiLiveTest extends ImageApiLiveTest {\n    public CloudServersUSImageApiLiveTest() {\n        provider = \"rackspace-cloudservers-us\";\n    }\n}\n"
  },
  {
    "path": "providers/rackspace-cloudservers-us/src/test/java/org/jclouds/rackspace/cloudservers/us/features/CloudServersUSServerApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.rackspace.cloudservers.us.features;\n\nimport org.jclouds.openstack.nova.v2_0.features.ServerApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"CloudServersUSServerApiLiveTest\")\npublic class CloudServersUSServerApiLiveTest extends ServerApiLiveTest {\n   public CloudServersUSServerApiLiveTest() {\n      provider = \"rackspace-cloudservers-us\";\n   }\n\n}\n"
  },
  {
    "path": "providers/rackspace-cloudservers-us/src/test/resources/access_rax_us.json",
    "content": "{\"access\":{\"token\":{\"id\":\"myToken\",\"expires\":\"2012-09-30T17:15:32.000-05:00\",\"tenant\":{\"id\":\"717071\",\"name\":\"717071\"}},\"serviceCatalog\":[{\"endpoints\":[{\"tenantId\":\"717071\",\"publicURL\":\"https:\\/\\/dns.api.rackspacecloud.com\\/v1.0\\/717071\"}],\"name\":\"cloudDNS\",\"type\":\"rax:dns\"},{\"endpoints\":[{\"tenantId\":\"717071\",\"publicURL\":\"https:\\/\\/monitoring.api.rackspacecloud.com\\/v1.0\\/717071\"}],\"name\":\"cloudMonitoring\",\"type\":\"rax:monitor\"},{\"endpoints\":[{\"region\":\"DFW\",\"tenantId\":\"717071\",\"publicURL\":\"https:\\/\\/dfw.servers.api.rackspacecloud.com\\/v2\\/717071\",\"versionInfo\":\"https:\\/\\/dfw.servers.api.rackspacecloud.com\\/v2\",\"versionList\":\"https:\\/\\/dfw.servers.api.rackspacecloud.com\\/\",\"versionId\":\"2\"},{\"region\":\"ORD\",\"tenantId\":\"717071\",\"publicURL\":\"https:\\/\\/ord.servers.api.rackspacecloud.com\\/v2\\/717071\",\"versionInfo\":\"https:\\/\\/ord.servers.api.rackspacecloud.com\\/v2\",\"versionList\":\"https:\\/\\/ord.servers.api.rackspacecloud.com\\/\",\"versionId\":\"2\"}],\"name\":\"cloudServersOpenStack\",\"type\":\"compute\"},{\"endpoints\":[{\"region\":\"ORD\",\"tenantId\":\"717071\",\"publicURL\":\"https:\\/\\/ord.loadbalancers.api.rackspacecloud.com\\/v1.0\\/717071\"},{\"region\":\"DFW\",\"tenantId\":\"717071\",\"publicURL\":\"https:\\/\\/dfw.loadbalancers.api.rackspacecloud.com\\/v1.0\\/717071\"}],\"name\":\"cloudLoadBalancers\",\"type\":\"rax:load-balancer\"},{\"endpoints\":[{\"region\":\"DFW\",\"tenantId\":\"717071\",\"publicURL\":\"https:\\/\\/dfw.databases.api.rackspacecloud.com\\/v1.0\\/717071\"},{\"region\":\"ORD\",\"tenantId\":\"717071\",\"publicURL\":\"https:\\/\\/ord.databases.api.rackspacecloud.com\\/v1.0\\/717071\"}],\"name\":\"cloudDatabases\",\"type\":\"rax:database\"},{\"endpoints\":[{\"region\":\"DFW\",\"tenantId\":\"MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\",\"publicURL\":\"https:\\/\\/storage101.dfw1.clouddrive.com\\/v1\\/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\",\"internalURL\":\"https:\\/\\/snet-storage101.dfw1.clouddrive.com\\/v1\\/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\"},{\"region\":\"ORD\",\"tenantId\":\"MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\",\"publicURL\":\"https:\\/\\/storage101.ord1.clouddrive.com\\/v1\\/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\",\"internalURL\":\"https:\\/\\/snet-storage101.ord1.clouddrive.com\\/v1\\/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\"}],\"name\":\"cloudFiles\",\"type\":\"object-store\"},{\"endpoints\":[{\"region\":\"DFW\",\"tenantId\":\"MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\",\"publicURL\":\"https:\\/\\/cdn1.clouddrive.com\\/v1\\/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\"},{\"region\":\"ORD\",\"tenantId\":\"MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\",\"publicURL\":\"https:\\/\\/cdn2.clouddrive.com\\/v1\\/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9\"}],\"name\":\"cloudFilesCDN\",\"type\":\"rax:object-cdn\"},{\"endpoints\":[{\"tenantId\":\"717071\",\"publicURL\":\"https:\\/\\/servers.api.rackspacecloud.com\\/v1.0\\/717071\",\"versionInfo\":\"https:\\/\\/servers.api.rackspacecloud.com\\/v1.0\",\"versionList\":\"https:\\/\\/servers.api.rackspacecloud.com\\/\",\"versionId\":\"1.0\"}],\"name\":\"cloudServers\",\"type\":\"compute\"},{\"endpoints\":[{\"region\":\"DFW\",\"tenantId\":\"717071\",\"publicURL\":\"https:\\/\\/dfw.blockstorage.api.rackspacecloud.com\\/v1\\/717071\"}],\"name\":\"cloudBlockStorage\",\"type\":\"volume\"}],\"user\":{\"id\":\"224085\",\"roles\":[{\"id\":\"3\",\"description\":\"User Admin Role.\",\"name\":\"identity:user-admin\"}],\"name\":\"myUsername\",\"RAX-AUTH:defaultRegion\":\"DFW\"}}}"
  },
  {
    "path": "providers/rackspace-cloudservers-us/src/test/resources/raxImages.json",
    "content": "{\"images\": [{\"status\": \"ACTIVE\", \"updated\": \"2012-05-17T17:13:17Z\", \"links\": [{\"href\": \"https://dfw.servers.api.rackspacecloud.com/v2/413274/images/d6dd6c70-a122-4391-91a8-decb1a356549\", \"rel\": \"self\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/d6dd6c70-a122-4391-91a8-decb1a356549\", \"rel\": \"bookmark\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/d6dd6c70-a122-4391-91a8-decb1a356549\", \"type\": \"application/vnd.openstack.image\", \"rel\": \"alternate\"}], \"minDisk\": 0, \"id\": \"d6dd6c70-a122-4391-91a8-decb1a356549\", \"name\": \"Red Hat Enterprise Linux 6.1\", \"created\": \"2012-04-06T22:12:02Z\", \"OS-DCF:diskConfig\": \"AUTO\", \"progress\": 100, \"minRam\": 256, \"metadata\": {\"os_distro\": \"rhel\", \"org.openstack__1__os_distro\": \"com.redhat\", \"arch\": \"x86-64\", \"org.openstack__1__os_version\": \"6.1\", \"rax_managed\": \"false\", \"os_version\": \"6.1\", \"auto_disk_config\": \"True\", \"rax_options\": \"1\", \"os_type\": \"linux\", \"rax_activation_profile\": \"redhat\", \"org.openstack__1__architecture\": \"x64\"}}, {\"status\": \"ACTIVE\", \"updated\": \"2012-05-17T17:14:17Z\", \"links\": [{\"href\": \"https://dfw.servers.api.rackspacecloud.com/v2/413274/images/644be485-411d-4bac-aba5-5f60641d92b5\", \"rel\": \"self\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/644be485-411d-4bac-aba5-5f60641d92b5\", \"rel\": \"bookmark\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/644be485-411d-4bac-aba5-5f60641d92b5\", \"type\": \"application/vnd.openstack.image\", \"rel\": \"alternate\"}], \"minDisk\": 0, \"id\": \"644be485-411d-4bac-aba5-5f60641d92b5\", \"name\": \"Red Hat Enterprise Linux 5.5\", \"created\": \"2012-04-06T22:11:47Z\", \"OS-DCF:diskConfig\": \"AUTO\", \"progress\": 100, \"minRam\": 256, \"metadata\": {\"os_distro\": \"rhel\", \"org.openstack__1__os_distro\": \"com.redhat\", \"arch\": \"x86-64\", \"org.openstack__1__os_version\": \"5.5\", \"rax_managed\": \"false\", \"os_version\": \"5.5\", \"auto_disk_config\": \"True\", \"rax_options\": \"1\", \"os_type\": \"linux\", \"rax_activation_profile\": \"redhat\", \"org.openstack__1__architecture\": \"x64\"}}, {\"status\": \"ACTIVE\", \"updated\": \"2012-05-17T17:14:18Z\", \"links\": [{\"href\": \"https://dfw.servers.api.rackspacecloud.com/v2/413274/images/8bf22129-8483-462b-a020-1754ec822770\", \"rel\": \"self\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/8bf22129-8483-462b-a020-1754ec822770\", \"rel\": \"bookmark\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/8bf22129-8483-462b-a020-1754ec822770\", \"type\": \"application/vnd.openstack.image\", \"rel\": \"alternate\"}], \"minDisk\": 10, \"id\": \"8bf22129-8483-462b-a020-1754ec822770\", \"name\": \"Ubuntu 11.04\", \"created\": \"2012-02-28T21:24:42Z\", \"OS-DCF:diskConfig\": \"AUTO\", \"progress\": 100, \"minRam\": 256, \"metadata\": {\"os_distro\": \"ubuntu\", \"org.openstack__1__os_distro\": \"com.ubuntu\", \"org.openstack__1__os_version\": \"11.10\", \"rax_managed\": \"false\", \"os_version\": \"11.10\", \"auto_disk_config\": \"True\", \"rax_options\": \"0\", \"os_type\": \"linux\", \"arch\": \"x86-64\", \"org.openstack__1__architecture\": \"x64\"}}, {\"status\": \"ACTIVE\", \"updated\": \"2012-05-17T17:13:50Z\", \"links\": [{\"href\": \"https://dfw.servers.api.rackspacecloud.com/v2/413274/images/0d589460-f177-4b0f-81c1-8ab8903ac7d8\", \"rel\": \"self\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/0d589460-f177-4b0f-81c1-8ab8903ac7d8\", \"rel\": \"bookmark\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/0d589460-f177-4b0f-81c1-8ab8903ac7d8\", \"type\": \"application/vnd.openstack.image\", \"rel\": \"alternate\"}], \"minDisk\": 10, \"id\": \"0d589460-f177-4b0f-81c1-8ab8903ac7d8\", \"name\": \"Arch 2011.10\", \"created\": \"2012-02-28T19:42:22Z\", \"OS-DCF:diskConfig\": \"AUTO\", \"progress\": 100, \"minRam\": 256, \"metadata\": {\"os_distro\": \"arch\", \"org.openstack__1__os_distro\": \"org.archlinux\", \"org.openstack__1__os_version\": \"2011.10\", \"rax_managed\": \"false\", \"os_version\": \"2011.10\", \"auto_disk_config\": \"True\", \"rax_options\": \"0\", \"os_type\": \"linux\", \"arch\": \"x86-64\", \"org.openstack__1__architecture\": \"x64\"}}, {\"status\": \"ACTIVE\", \"updated\": \"2012-05-17T17:12:59Z\", \"links\": [{\"href\": \"https://dfw.servers.api.rackspacecloud.com/v2/413274/images/096c55e5-39f3-48cf-a413-68d9377a3ab6\", \"rel\": \"self\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/096c55e5-39f3-48cf-a413-68d9377a3ab6\", \"rel\": \"bookmark\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/096c55e5-39f3-48cf-a413-68d9377a3ab6\", \"type\": \"application/vnd.openstack.image\", \"rel\": \"alternate\"}], \"minDisk\": 10, \"id\": \"096c55e5-39f3-48cf-a413-68d9377a3ab6\", \"name\": \"openSUSE 12\", \"created\": \"2012-02-28T19:42:04Z\", \"OS-DCF:diskConfig\": \"AUTO\", \"progress\": 100, \"minRam\": 256, \"metadata\": {\"os_distro\": \"opensuse\", \"org.openstack__1__os_distro\": \"org.opensuse\", \"org.openstack__1__os_version\": \"12.0\", \"rax_managed\": \"false\", \"os_version\": \"12\", \"auto_disk_config\": \"True\", \"rax_options\": \"0\", \"os_type\": \"linux\", \"arch\": \"x86-64\", \"org.openstack__1__architecture\": \"x64\"}}, {\"status\": \"ACTIVE\", \"updated\": \"2012-05-17T17:13:17Z\", \"links\": [{\"href\": \"https://dfw.servers.api.rackspacecloud.com/v2/413274/images/040e6c82-6618-4f53-9f27-44db2c4ce9ee\", \"rel\": \"self\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/040e6c82-6618-4f53-9f27-44db2c4ce9ee\", \"rel\": \"bookmark\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/040e6c82-6618-4f53-9f27-44db2c4ce9ee\", \"type\": \"application/vnd.openstack.image\", \"rel\": \"alternate\"}], \"minDisk\": 10, \"id\": \"040e6c82-6618-4f53-9f27-44db2c4ce9ee\", \"name\": \"Gentoo 11.0\", \"created\": \"2012-02-28T19:41:50Z\", \"OS-DCF:diskConfig\": \"AUTO\", \"progress\": 100, \"minRam\": 256, \"metadata\": {\"os_distro\": \"gentoo\", \"org.openstack__1__os_distro\": \"org.gentoo\", \"org.openstack__1__os_version\": \"11.0\", \"rax_managed\": \"false\", \"os_version\": \"11.0\", \"auto_disk_config\": \"True\", \"rax_options\": \"0\", \"os_type\": \"linux\", \"arch\": \"x86-64\", \"org.openstack__1__architecture\": \"x64\"}}, {\"status\": \"ACTIVE\", \"updated\": \"2012-05-17T17:13:50Z\", \"links\": [{\"href\": \"https://dfw.servers.api.rackspacecloud.com/v2/413274/images/a10eacf7-ac15-4225-b533-5744f1fe47c1\", \"rel\": \"self\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/a10eacf7-ac15-4225-b533-5744f1fe47c1\", \"rel\": \"bookmark\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/a10eacf7-ac15-4225-b533-5744f1fe47c1\", \"type\": \"application/vnd.openstack.image\", \"rel\": \"alternate\"}], \"minDisk\": 10, \"id\": \"a10eacf7-ac15-4225-b533-5744f1fe47c1\", \"name\": \"Debian 6 (Squeeze)\", \"created\": \"2012-02-28T19:41:44Z\", \"OS-DCF:diskConfig\": \"AUTO\", \"progress\": 100, \"minRam\": 256, \"metadata\": {\"os_distro\": \"debian\", \"org.openstack__1__os_distro\": \"org.debian\", \"org.openstack__1__os_version\": \"6.0\", \"rax_managed\": \"false\", \"os_version\": \"6\", \"auto_disk_config\": \"True\", \"rax_options\": \"0\", \"os_type\": \"linux\", \"arch\": \"x86-64\", \"org.openstack__1__architecture\": \"x64\"}}, {\"status\": \"ACTIVE\", \"updated\": \"2012-05-17T17:14:18Z\", \"links\": [{\"href\": \"https://dfw.servers.api.rackspacecloud.com/v2/413274/images/25a025a8-b126-409c-ab02-0ca70af61d8d\", \"rel\": \"self\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/25a025a8-b126-409c-ab02-0ca70af61d8d\", \"rel\": \"bookmark\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/25a025a8-b126-409c-ab02-0ca70af61d8d\", \"type\": \"application/vnd.openstack.image\", \"rel\": \"alternate\"}], \"minDisk\": 10, \"id\": \"25a025a8-b126-409c-ab02-0ca70af61d8d\", \"name\": \"Debian 5 (Lenny)\", \"created\": \"2012-02-28T19:41:37Z\", \"OS-DCF:diskConfig\": \"AUTO\", \"progress\": 100, \"minRam\": 256, \"metadata\": {\"os_distro\": \"debian\", \"org.openstack__1__os_distro\": \"org.debian\", \"org.openstack__1__os_version\": \"5.0\", \"rax_managed\": \"false\", \"os_version\": \"5\", \"auto_disk_config\": \"True\", \"rax_options\": \"0\", \"os_type\": \"linux\", \"arch\": \"x86-64\", \"org.openstack__1__architecture\": \"x64\"}}, {\"status\": \"ACTIVE\", \"updated\": \"2012-05-17T17:12:26Z\", \"links\": [{\"href\": \"https://dfw.servers.api.rackspacecloud.com/v2/413274/images/bca91446-e60e-42e7-9e39-0582e7e20fb9\", \"rel\": \"self\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/bca91446-e60e-42e7-9e39-0582e7e20fb9\", \"rel\": \"bookmark\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/bca91446-e60e-42e7-9e39-0582e7e20fb9\", \"type\": \"application/vnd.openstack.image\", \"rel\": \"alternate\"}], \"minDisk\": 10, \"id\": \"bca91446-e60e-42e7-9e39-0582e7e20fb9\", \"name\": \"Fedora 16\", \"created\": \"2012-02-28T19:41:07Z\", \"OS-DCF:diskConfig\": \"AUTO\", \"progress\": 100, \"minRam\": 256, \"metadata\": {\"os_distro\": \"fedora\", \"org.openstack__1__os_distro\": \"org.fedoraproject\", \"org.openstack__1__os_version\": \"16.0\", \"rax_managed\": \"false\", \"os_version\": \"16\", \"auto_disk_config\": \"True\", \"rax_options\": \"0\", \"os_type\": \"linux\", \"arch\": \"x86-64\", \"org.openstack__1__architecture\": \"x64\"}}, {\"status\": \"ACTIVE\", \"updated\": \"2012-05-17T17:13:50Z\", \"links\": [{\"href\": \"https://dfw.servers.api.rackspacecloud.com/v2/413274/images/7c151d6f-d87b-420d-9f8e-b6ed7a160fbb\", \"rel\": \"self\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/7c151d6f-d87b-420d-9f8e-b6ed7a160fbb\", \"rel\": \"bookmark\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/7c151d6f-d87b-420d-9f8e-b6ed7a160fbb\", \"type\": \"application/vnd.openstack.image\", \"rel\": \"alternate\"}], \"minDisk\": 10, \"id\": \"7c151d6f-d87b-420d-9f8e-b6ed7a160fbb\", \"name\": \"Fedora 15\", \"created\": \"2012-02-28T19:40:57Z\", \"OS-DCF:diskConfig\": \"AUTO\", \"progress\": 100, \"minRam\": 256, \"metadata\": {\"os_distro\": \"fedora\", \"org.openstack__1__os_distro\": \"org.fedoraproject\", \"org.openstack__1__os_version\": \"15.0\", \"rax_managed\": \"false\", \"os_version\": \"15\", \"auto_disk_config\": \"True\", \"rax_options\": \"0\", \"os_type\": \"linux\", \"arch\": \"x86-64\", \"org.openstack__1__architecture\": \"x64\"}}, {\"status\": \"ACTIVE\", \"updated\": \"2012-05-17T17:14:17Z\", \"links\": [{\"href\": \"https://dfw.servers.api.rackspacecloud.com/v2/413274/images/03318d19-b6e6-4092-9b5c-4758ee0ada60\", \"rel\": \"self\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/03318d19-b6e6-4092-9b5c-4758ee0ada60\", \"rel\": \"bookmark\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/03318d19-b6e6-4092-9b5c-4758ee0ada60\", \"type\": \"application/vnd.openstack.image\", \"rel\": \"alternate\"}], \"minDisk\": 10, \"id\": \"03318d19-b6e6-4092-9b5c-4758ee0ada60\", \"name\": \"CentOS 5.6\", \"created\": \"2012-02-28T19:40:46Z\", \"OS-DCF:diskConfig\": \"AUTO\", \"progress\": 100, \"minRam\": 256, \"metadata\": {\"os_distro\": \"centos\", \"org.openstack__1__os_distro\": \"org.centos\", \"org.openstack__1__os_version\": \"5.6\", \"rax_managed\": \"false\", \"os_version\": \"5.6\", \"auto_disk_config\": \"True\", \"rax_options\": \"0\", \"os_type\": \"linux\", \"arch\": \"x86-64\", \"org.openstack__1__architecture\": \"x64\"}}, {\"status\": \"ACTIVE\", \"updated\": \"2012-05-17T17:14:18Z\", \"links\": [{\"href\": \"https://dfw.servers.api.rackspacecloud.com/v2/413274/images/a3a2c42f-575f-4381-9c6d-fcd3b7d07d17\", \"rel\": \"self\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/a3a2c42f-575f-4381-9c6d-fcd3b7d07d17\", \"rel\": \"bookmark\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/a3a2c42f-575f-4381-9c6d-fcd3b7d07d17\", \"type\": \"application/vnd.openstack.image\", \"rel\": \"alternate\"}], \"minDisk\": 10, \"id\": \"a3a2c42f-575f-4381-9c6d-fcd3b7d07d17\", \"name\": \"CentOS 6.0\", \"created\": \"2012-02-28T19:40:32Z\", \"OS-DCF:diskConfig\": \"AUTO\", \"progress\": 100, \"minRam\": 256, \"metadata\": {\"os_distro\": \"centos\", \"org.openstack__1__os_distro\": \"org.centos\", \"org.openstack__1__os_version\": \"6.0\", \"rax_managed\": \"false\", \"os_version\": \"6.0\", \"auto_disk_config\": \"True\", \"rax_options\": \"0\", \"os_type\": \"linux\", \"arch\": \"x86-64\", \"org.openstack__1__architecture\": \"x64\"}}, {\"status\": \"ACTIVE\", \"updated\": \"2012-05-17T17:14:18Z\", \"links\": [{\"href\": \"https://dfw.servers.api.rackspacecloud.com/v2/413274/images/5f68715f-201f-4600-b5a1-0b97e2b1cb31\", \"rel\": \"self\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/5f68715f-201f-4600-b5a1-0b97e2b1cb31\", \"rel\": \"bookmark\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/5f68715f-201f-4600-b5a1-0b97e2b1cb31\", \"type\": \"application/vnd.openstack.image\", \"rel\": \"alternate\"}], \"minDisk\": 10, \"id\": \"5f68715f-201f-4600-b5a1-0b97e2b1cb31\", \"name\": \"Ubuntu 10.04 LTS\", \"created\": \"2012-02-28T19:40:25Z\", \"OS-DCF:diskConfig\": \"AUTO\", \"progress\": 100, \"minRam\": 256, \"metadata\": {\"os_distro\": \"ubuntu\", \"org.openstack__1__os_distro\": \"com.ubuntu\", \"org.openstack__1__os_version\": \"10.04\", \"rax_managed\": \"false\", \"os_version\": \"10.04LTS\", \"auto_disk_config\": \"True\", \"rax_options\": \"0\", \"os_type\": \"linux\", \"arch\": \"x86-64\", \"org.openstack__1__architecture\": \"x64\"}}, {\"status\": \"ACTIVE\", \"updated\": \"2012-02-28T19:39:05Z\", \"links\": [{\"href\": \"https://dfw.servers.api.rackspacecloud.com/v2/413274/images/3afe97b2-26dc-49c5-a2cc-a2fc8d80c001\", \"rel\": \"self\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/3afe97b2-26dc-49c5-a2cc-a2fc8d80c001\", \"rel\": \"bookmark\"}, {\"href\": \"https://dfw.servers.api.rackspacecloud.com/413274/images/3afe97b2-26dc-49c5-a2cc-a2fc8d80c001\", \"type\": \"application/vnd.openstack.image\", \"rel\": \"alternate\"}], \"minDisk\": 10, \"id\": \"3afe97b2-26dc-49c5-a2cc-a2fc8d80c001\", \"name\": \"Ubuntu 11.10\", \"created\": \"2012-02-28T19:38:57Z\", \"OS-DCF:diskConfig\": \"AUTO\", \"progress\": 100, \"minRam\": 256, \"metadata\": {\"os_distro\": \"ubuntu\", \"rax_managed\": \"false\", \"os_version\": \"11.10\", \"auto_disk_config\": \"True\", \"rax_options\": \"0\", \"os_type\": \"linux\", \"arch\": \"x86-64\"}}]}"
  },
  {
    "path": "providers/serverlove-z1-man/README.txt",
    "content": "#\n# The jclouds provider for serverlove's ElasticStack (http://www.serverlove.com/).\n#\n# Expects the jclouds elasticstack API to be present on your application's classpath.\n#\n# TODO: Implementation status.\n# TODO: Supported features.\n# TODO: Usage example.\n"
  },
  {
    "path": "providers/serverlove-z1-man/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.serverlove.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "providers/serverlove-z1-man/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.provider</groupId>\n  <artifactId>serverlove-z1-man</artifactId>\n  <name>jclouds Serverlove Manchester provider</name>\n  <description>Serverlove implementation targeted to Manchester</description>\n\n  <properties>\n    <test.serverlove-z1-man.endpoint>https://api.z1-man.serverlove.com</test.serverlove-z1-man.endpoint>\n    <test.serverlove-z1-man.api-version>1.0</test.serverlove-z1-man.api-version>\n    <test.serverlove-z1-man.build-version />\n    <test.serverlove-z1-man.identity>FIXME_IDENTITY</test.serverlove-z1-man.identity>\n    <test.serverlove-z1-man.credential>FIXME_CREDENTIAL</test.serverlove-z1-man.credential>\n    <test.serverlove-z1-man.template />\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>elasticstack</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>elasticstack</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-log4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-sshj</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.serverlove-z1-man.endpoint>${test.serverlove-z1-man.endpoint}</test.serverlove-z1-man.endpoint>\n                    <test.serverlove-z1-man.api-version>${test.serverlove-z1-man.api-version}</test.serverlove-z1-man.api-version>\n                    <test.serverlove-z1-man.build-version>${test.serverlove-z1-man.build-version}</test.serverlove-z1-man.build-version>\n                    <test.serverlove-z1-man.identity>${test.serverlove-z1-man.identity}</test.serverlove-z1-man.identity>\n                    <test.serverlove-z1-man.credential>${test.serverlove-z1-man.credential}</test.serverlove-z1-man.credential>\n                    <test.serverlove-z1-man.template>${test.serverlove-z1-man.template}</test.serverlove-z1-man.template>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n"
  },
  {
    "path": "providers/serverlove-z1-man/src/main/java/org/jclouds/serverlove/ServerloveManchesterProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.serverlove;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.elasticstack.ElasticStackApiMetadata;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\nimport org.jclouds.serverlove.config.ServerloveImagesModule;\n\nimport com.google.auto.service.AutoService;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n/**\n * Implementation of {@link ProviderMetadata} for Serverlove Manchester.\n */\n@AutoService(ProviderMetadata.class)\npublic class ServerloveManchesterProviderMetadata extends BaseProviderMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromProviderMetadata(this);\n   }\n\n   public ServerloveManchesterProviderMetadata() {\n      super(builder());\n   }\n\n   public ServerloveManchesterProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = new Properties();\n      return properties;\n   }\n\n   public static class Builder extends BaseProviderMetadata.Builder {\n\n      protected Builder() {\n         ElasticStackApiMetadata apiMedatada = new ElasticStackApiMetadata();\n\n         ImmutableSet.Builder<Class<? extends Module>> modules = ImmutableSet.builder();\n         modules.addAll(apiMedatada.getDefaultModules());\n         modules.add(ServerloveImagesModule.class); // Custom image supplier binding\n\n         id(\"serverlove-z1-man\").name(\"Serverlove Manchester\")\n               .apiMetadata(apiMedatada.toBuilder().version(\"2.0\").defaultModules(modules.build()).build())\n               .homepage(URI.create(\"http://www.serverlove.com\"))\n               .console(URI.create(\"http://www.serverlove.com/accounts\"))\n               .iso3166Codes(\"GB-MAN\")\n               .endpoint(\"https://api.z1-man.serverlove.com\")\n               .defaultProperties(ServerloveManchesterProviderMetadata.defaultProperties());\n      }\n\n      @Override\n      public ServerloveManchesterProviderMetadata build() {\n         return new ServerloveManchesterProviderMetadata(this);\n      }\n\n      @Override\n      public Builder fromProviderMetadata(ProviderMetadata in) {\n         super.fromProviderMetadata(in);\n         return this;\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/serverlove-z1-man/src/main/java/org/jclouds/serverlove/config/ServerloveImagesModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.serverlove.config;\n\nimport static com.google.inject.Scopes.SINGLETON;\n\nimport org.jclouds.elasticstack.suppliers.WellKnownImageSupplier;\nimport org.jclouds.serverlove.suppliers.FixedWellKnownImageSupplier;\n\nimport com.google.inject.AbstractModule;\n\n/**\n * Custom configuration for the Serverlove provider.\n */\npublic class ServerloveImagesModule extends AbstractModule {\n\n   @Override\n   protected void configure() {\n      bind(WellKnownImageSupplier.class).to(FixedWellKnownImageSupplier.class).in(SINGLETON);\n   }\n\n}\n"
  },
  {
    "path": "providers/serverlove-z1-man/src/main/java/org/jclouds/serverlove/suppliers/FixedWellKnownImageSupplier.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.serverlove.suppliers;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.io.IOException;\nimport java.util.List;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.elasticstack.domain.WellKnownImage;\nimport org.jclouds.elasticstack.suppliers.WellKnownImageSupplier;\nimport org.jclouds.json.Json;\nimport org.jclouds.location.Provider;\nimport org.jclouds.util.Strings2;\n\nimport com.google.common.base.Throwables;\nimport com.google.inject.TypeLiteral;\n\n/**\n * Supplies the pre-installed images.\n */\n@Singleton\npublic class FixedWellKnownImageSupplier implements WellKnownImageSupplier {\n\n   private final Json json;\n\n   private final String providerName;\n\n   @Inject\n   FixedWellKnownImageSupplier(Json json, @Provider String providerName) {\n      this.json = checkNotNull(json, \"json\");\n      this.providerName = checkNotNull(providerName, \"providerName\");\n   }\n\n   @Override\n   public List<WellKnownImage> get() {\n      try {\n         return json.fromJson(\n               Strings2.toStringAndClose(getClass().getResourceAsStream(\n                     \"/\" + providerName + \"/preinstalled_images.json\")), new TypeLiteral<List<WellKnownImage>>() {\n               }.getType());\n      } catch (IOException ex) {\n         throw Throwables.propagate(ex);\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/serverlove-z1-man/src/main/resources/serverlove-z1-man/preinstalled_images.json",
    "content": "[\n  {\n      \"uuid\": \"88ed067f-d2b8-42ce-a25f-5297818a3b6f\",\n      \"description\": \"CentOS Linux 5.7\",\n      \"osFamily\": \"CENTOS\",\n      \"osVersion\": \"5.7\",\n      \"size\": \"3\",\n      \"loginUser\": \"root\"\n  },\n  {\n      \"uuid\": \"bcd758d4-cfc8-4d42-a707-c4bebe47900b\",\n      \"description\": \"CentOS Linux 6.2\",\n      \"osFamily\": \"CENTOS\",\n      \"osVersion\": \"6.2\",\n      \"size\": \"3\",\n      \"loginUser\": \"root\"\n  },\n  {\n      \"uuid\": \"aca2fa0b-40bc-4e06-ad99-f1467690d5de\",\n      \"description\": \"Debian Linux 6.0\",\n      \"osFamily\": \"DEBIAN\",\n      \"osVersion\": \"6.0\",\n      \"size\": \"1\",\n      \"loginUser\": \"root\"\n  },\n  {\n      \"uuid\": \"574a3921-2926-4a61-bdd9-8d9282b32810\",\n      \"description\": \"Ubuntu 10.04 LTS\",\n      \"osFamily\": \"UBUNTU\",\n      \"osVersion\": \"10.04\",\n      \"size\": \"1\",\n      \"loginUser\": \"root\"\n  },\n  {\n      \"uuid\": \"80f7b359-b25f-48ea-b208-cc1f39d8bf07\",\n      \"description\": \"Ubuntu 12.04 LTS\",\n      \"osFamily\": \"UBUNTU\",\n      \"osVersion\": \"12.04\",\n      \"size\": \"1\",\n      \"loginUser\": \"root\"\n  },\n  {\n      \"uuid\": \"41993a02-0b22-4e49-bb47-0aa8975217e4\",\n      \"description\": \"Windows Server 2008 R2 Standard\",\n      \"osFamily\": \"WINDOWS\",\n      \"osVersion\": \"2008 R2\",\n      \"size\": \"13\",\n      \"loginUser\": \"Administrator\"\n  },\n  {\n      \"uuid\": \"7a488d27-7b79-472c-8fbc-84dca822027e\",\n      \"description\": \"Windows Server 2008 R2 Standard SP1 with SQL Server 2008 R2 Web Edition\",\n      \"osFamily\": \"WINDOWS\",\n      \"osVersion\": \"2008 R2 SP1 SQL\",\n      \"size\": \"13\",\n      \"loginUser\": \"Administrator\"\n  },\n  {\n      \"uuid\": \"a90a65b0-9452-4ac8-acfa-3e607c77cc9c\",\n      \"description\": \"Windows Server 2012 Standard\",\n      \"osFamily\": \"WINDOWS\",\n      \"osVersion\": \"2012\",\n      \"size\": \"13\",\n      \"loginUser\": \"Administrator\"\n  },\n  {\n      \"uuid\": \"85623ca1-9c2a-4398-a771-9a43c347e86b\",\n      \"description\": \"Windows Web Server 2008 R2\",\n      \"osFamily\": \"WINDOWS\",\n      \"osVersion\": \"2008 R2 Web\",\n      \"size\": \"13\",\n      \"loginUser\": \"Administrator\"\n  },\n  {\n      \"uuid\": \"9183de46-ca66-43aa-aa8a-8d172acca51d\",\n      \"description\": \"Windows Web Server 2008 R2 SP1 with SQL Server 2008 R2 Web Edition\",\n      \"osFamily\": \"WINDOWS\",\n      \"osVersion\": \"2008 R2 SP1 Web SQL\",\n      \"size\": \"13\",\n      \"loginUser\": \"Administrator\"\n  }\n]\n"
  },
  {
    "path": "providers/serverlove-z1-man/src/test/java/org/jclouds/serverlove/ServerloveManchesterApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.serverlove;\n\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.elasticstack.ElasticStackApiLiveTest;\nimport org.jclouds.elasticstack.domain.Server;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"ServerloveManchesterApiLiveTest\")\npublic class ServerloveManchesterApiLiveTest extends ElasticStackApiLiveTest {\n   public ServerloveManchesterApiLiveTest() {\n      provider = \"serverlove-z1-man\";\n   }\n\n   @Override\n   protected LoginCredentials getSshCredentials(Server server) {\n      return LoginCredentials.builder().user(\"root\").password(server.getVnc().getPassword()).build();\n   }\n\n   @Override\n   @Test(enabled = false, description = \"Standard drive API still not supported\")\n   public void testListStandardDrives() throws Exception {\n\n   }\n\n   @Override\n   @Test(enabled = false, description = \"Standard drive API still not supported\")\n   public void testListStandardDriveInfo() throws Exception {\n\n   }\n\n}\n"
  },
  {
    "path": "providers/serverlove-z1-man/src/test/java/org/jclouds/serverlove/ServerloveManchesterProviderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.serverlove;\n\nimport org.jclouds.elasticstack.ElasticStackApiMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ServerloveManchesterProviderTest\")\npublic class ServerloveManchesterProviderTest extends BaseProviderMetadataTest {\n\n   public ServerloveManchesterProviderTest() {\n      super(new ServerloveManchesterProviderMetadata(), new ElasticStackApiMetadata());\n   }\n}\n"
  },
  {
    "path": "providers/serverlove-z1-man/src/test/java/org/jclouds/serverlove/compute/ServerloveManchesterComputeServiceLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.serverlove.compute;\n\nimport org.jclouds.elasticstack.compute.ElasticStackComputeServiceLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"ServerloveManchesterComputeServiceLiveTest\")\npublic class ServerloveManchesterComputeServiceLiveTest extends ElasticStackComputeServiceLiveTest {\n\n   public ServerloveManchesterComputeServiceLiveTest() {\n      provider = \"serverlove-z1-man\";\n      group = \"serverlove\";\n   }\n\n}\n"
  },
  {
    "path": "providers/serverlove-z1-man/src/test/java/org/jclouds/serverlove/compute/ServerloveManchesterTemplateBuilderLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.serverlove.compute;\n\nimport static org.jclouds.compute.util.ComputeServiceUtils.getCores;\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.internal.BaseTemplateBuilderLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"live\")\npublic class ServerloveManchesterTemplateBuilderLiveTest extends BaseTemplateBuilderLiveTest {\n\n   public ServerloveManchesterTemplateBuilderLiveTest() {\n      provider = \"serverlove-z1-man\";\n   }\n\n   @Test\n   public void testTemplateBuilder() {\n      Template defaultTemplate = this.view.getComputeService().templateBuilder().build();\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true);\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().getVersion(), \"10.04\");\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.UBUNTU);\n      assertEquals(defaultTemplate.getLocation().getId(), \"serverlove-z1-man\");\n      assertEquals(getCores(defaultTemplate.getHardware()), 1.0d);\n   }\n\n   @Override\n   protected Set<String> getIso3166Codes() {\n      return ImmutableSet.of(\"GB-MAN\");\n   }\n}\n"
  },
  {
    "path": "providers/skalicloud-sdg-my/README.txt",
    "content": "#\n# The jclouds provider for SKALI Cloud's ElasticStack (http://www.skalicloud.com/).\n#\n# Expects the jclouds elasticstack API to be present on your application's classpath.\n#\n# TODO: Implementation status.\n# TODO: Supported features.\n# TODO: Usage example.\n"
  },
  {
    "path": "providers/skalicloud-sdg-my/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.skalicloud.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "providers/skalicloud-sdg-my/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.provider</groupId>\n  <artifactId>skalicloud-sdg-my</artifactId>\n  <name>jclouds SkaliCloud Malaysia provider</name>\n  <description>SkaliCloud implementation targeted to Malaysia</description>\n\n  <properties>\n    <test.skalicloud-sdg-my.endpoint>https://api.sdg-my.skalicloud.com</test.skalicloud-sdg-my.endpoint>\n    <test.skalicloud-sdg-my.api-version>1.0</test.skalicloud-sdg-my.api-version>\n    <test.skalicloud-sdg-my.build-version />\n    <test.skalicloud-sdg-my.identity>FIXME_IDENTITY</test.skalicloud-sdg-my.identity>\n    <test.skalicloud-sdg-my.credential>FIXME_CREDENTIAL</test.skalicloud-sdg-my.credential>\n    <test.skalicloud-sdg-my.template />\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>elasticstack</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.api</groupId>\n      <artifactId>elasticstack</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-log4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-sshj</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.skalicloud-sdg-my.endpoint>${test.skalicloud-sdg-my.endpoint}</test.skalicloud-sdg-my.endpoint>\n                    <test.skalicloud-sdg-my.api-version>${test.skalicloud-sdg-my.api-version}</test.skalicloud-sdg-my.api-version>\n                    <test.skalicloud-sdg-my.build-version>${test.skalicloud-sdg-my.build-version}</test.skalicloud-sdg-my.build-version>\n                    <test.skalicloud-sdg-my.identity>${test.skalicloud-sdg-my.identity}</test.skalicloud-sdg-my.identity>\n                    <test.skalicloud-sdg-my.credential>${test.skalicloud-sdg-my.credential}</test.skalicloud-sdg-my.credential>\n                    <test.skalicloud-sdg-my.template>${test.skalicloud-sdg-my.template}</test.skalicloud-sdg-my.template>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n\n</project>\n"
  },
  {
    "path": "providers/skalicloud-sdg-my/src/main/java/org/jclouds/skalicloud/SkaliCloudMalaysiaProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.skalicloud;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.elasticstack.ElasticStackApiMetadata;\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\n\nimport com.google.auto.service.AutoService;\n\n/**\n * Implementation of {@link ProviderMetadata} for SkaliCloud Malaysia.\n */\n@AutoService(ProviderMetadata.class)\npublic class SkaliCloudMalaysiaProviderMetadata extends BaseProviderMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromProviderMetadata(this);\n   }\n\n   public SkaliCloudMalaysiaProviderMetadata() {\n      super(builder());\n   }\n\n   public SkaliCloudMalaysiaProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = new Properties();\n      return properties;\n   }\n\n   public static class Builder\n         extends\n         BaseProviderMetadata.Builder {\n\n      protected Builder() {\n         id(\"skalicloud-sdg-my\")\n         .name(\"SkaliCloud Malaysia\")\n         .apiMetadata(new ElasticStackApiMetadata())\n         .homepage(URI.create(\"https://sdg-my.skalicloud.com\"))\n         .console(URI.create(\"https://api.sdg-my.skalicloud.com/accounts\"))\n         .iso3166Codes(\"MY-10\")\n         .endpoint(\"https://api.sdg-my.skalicloud.com\")\n         .defaultProperties(SkaliCloudMalaysiaProviderMetadata.defaultProperties());\n      }\n\n      @Override\n      public SkaliCloudMalaysiaProviderMetadata build() {\n         return new SkaliCloudMalaysiaProviderMetadata(this);\n      }\n\n      @Override\n      public Builder fromProviderMetadata(\n            ProviderMetadata in) {\n         super.fromProviderMetadata(in);\n         return this;\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/skalicloud-sdg-my/src/test/java/org/jclouds/skalicloud/SkaliCloudMalaysiaApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.skalicloud;\n\nimport org.jclouds.elasticstack.ElasticStackApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"SkaliCloudMalaysiaApiLiveTest\")\npublic class SkaliCloudMalaysiaApiLiveTest extends ElasticStackApiLiveTest {\n   public SkaliCloudMalaysiaApiLiveTest() {\n      provider = \"skalicloud-sdg-my\";\n   }\n}\n"
  },
  {
    "path": "providers/skalicloud-sdg-my/src/test/java/org/jclouds/skalicloud/SkaliCloudMalaysiaProviderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.skalicloud;\n\nimport org.jclouds.elasticstack.ElasticStackApiMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"SkaliCloudMalaysiaProviderTest\")\npublic class SkaliCloudMalaysiaProviderTest extends BaseProviderMetadataTest {\n\n   public SkaliCloudMalaysiaProviderTest() {\n      super(new SkaliCloudMalaysiaProviderMetadata(), new ElasticStackApiMetadata());\n   }\n}\n"
  },
  {
    "path": "providers/skalicloud-sdg-my/src/test/java/org/jclouds/skalicloud/compute/SkaliCloudMalaysiaComputeServiceLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.skalicloud.compute;\n\nimport org.jclouds.elasticstack.compute.ElasticStackComputeServiceLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"SkaliCloudMalaysiaComputeServiceLiveTest\")\npublic class SkaliCloudMalaysiaComputeServiceLiveTest extends ElasticStackComputeServiceLiveTest {\n\n   public SkaliCloudMalaysiaComputeServiceLiveTest() {\n      provider = \"skalicloud-sdg-my\";\n   }\n\n}\n"
  },
  {
    "path": "providers/skalicloud-sdg-my/src/test/java/org/jclouds/skalicloud/compute/SkaliCloudMalaysiaTemplateBuilderLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.skalicloud.compute;\n\nimport static org.jclouds.compute.util.ComputeServiceUtils.getCores;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.internal.BaseTemplateBuilderLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"live\")\npublic class SkaliCloudMalaysiaTemplateBuilderLiveTest extends BaseTemplateBuilderLiveTest {\n\n   public SkaliCloudMalaysiaTemplateBuilderLiveTest() {\n      provider = \"skalicloud-sdg-my\";\n   }\n\n   @Override\n   public void testDefaultTemplateBuilder() throws IOException {\n      Template defaultTemplate = this.view.getComputeService().templateBuilder().build();\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true);\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().getVersion(), \"10.10\");\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.UBUNTU);\n      assertEquals(defaultTemplate.getLocation().getId(), \"skalicloud-sdg-my\");\n      assertEquals(getCores(defaultTemplate.getHardware()), 1.0d);\n   }\n\n   @Override\n   protected Set<String> getIso3166Codes() {\n      return ImmutableSet.of(\"MY-10\");\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.softlayer.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "providers/softlayer/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.provider</groupId>\n  <artifactId>softlayer</artifactId>\n  <name>jclouds SoftLayer core</name>\n  <description>jclouds components to access SoftLayer</description>\n\n  <properties>\n    <test.softlayer.endpoint>https://api.softlayer.com/rest</test.softlayer.endpoint>\n    <test.softlayer.api-version>3</test.softlayer.api-version>\n    <test.softlayer.build-version />\n    <test.softlayer.identity>FIXME_IDENTITY</test.softlayer.identity>\n    <test.softlayer.credential>FIXME_CREDENTIAL</test.softlayer.credential>\n    <test.softlayer.template />\n  </properties>\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.value</groupId>\n      <artifactId>auto-value</artifactId>\n      <scope>provided</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-sshj</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n        <groupId>org.apache.jclouds.driver</groupId>\n        <artifactId>jclouds-slf4j</artifactId>\n        <version>${project.version}</version>\n        <scope>test</scope>\n    </dependency>\n    <dependency>\n        <groupId>ch.qos.logback</groupId>\n        <artifactId>logback-classic</artifactId>\n        <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.squareup.okhttp3</groupId>\n      <artifactId>mockwebserver</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.squareup.okhttp3</groupId>\n      <artifactId>okhttp-tls</artifactId>\n      <scope>test</scope>\n      <exclusions>\n        <exclusion>\n          <groupId>org.bouncycastle</groupId>\n          <artifactId>bcprov-jdk15on</artifactId>\n        </exclusion>\n      </exclusions>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.softlayer.endpoint>${test.softlayer.endpoint}</test.softlayer.endpoint>\n                    <test.softlayer.api-version>${test.softlayer.api-version}</test.softlayer.api-version>\n                    <test.softlayer.build-version>${test.softlayer.build-version}</test.softlayer.build-version>\n                    <test.softlayer.identity>${test.softlayer.identity}</test.softlayer.identity>\n                    <test.softlayer.credential>${test.softlayer.credential}</test.softlayer.credential>\n                    <test.softlayer.template>${test.softlayer.template}</test.softlayer.template>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/SoftLayerApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer;\n\nimport org.jclouds.rest.annotations.Delegate;\nimport org.jclouds.softlayer.features.AccountApi;\nimport org.jclouds.softlayer.features.DatacenterApi;\nimport org.jclouds.softlayer.features.NetworkApi;\nimport org.jclouds.softlayer.features.SoftwareDescriptionApi;\nimport org.jclouds.softlayer.features.VirtualGuestApi;\nimport org.jclouds.softlayer.features.VirtualGuestBlockDeviceTemplateGroupApi;\n\nimport java.io.Closeable;\n\npublic interface SoftLayerApi extends Closeable {\n\n   /**\n    * Provides access to VirtualGuest features.\n    */\n   @Delegate\n   VirtualGuestApi getVirtualGuestApi();\n\n   /**\n    * Provides access to Datacenter features.\n    */\n   @Delegate\n   DatacenterApi getDatacenterApi();\n\n   /**\n    * Provides access to SoftwareDescription features.\n    */\n   @Delegate\n   SoftwareDescriptionApi getSoftwareDescriptionApi();\n\n   /**\n    * Provides access to VirtualGuestBlockDeviceTemplateGroup features.\n    */\n   @Delegate\n   VirtualGuestBlockDeviceTemplateGroupApi getVirtualGuestBlockDeviceTemplateGroupApi();\n\n   /**\n    * Provides access to Account features.\n    */\n   @Delegate\n   AccountApi getAccountApi();\n\n   /**\n    * Provides access to Network features.\n    */\n   @Delegate\n   NetworkApi getNetworkApi();\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/SoftLayerApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer;\n\nimport static org.jclouds.reflect.Reflection2.typeToken;\nimport static org.jclouds.softlayer.reference.SoftLayerConstants.SOFTLAYER_PROVIDER_NAME;\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.rest.internal.BaseHttpApiMetadata;\nimport org.jclouds.softlayer.compute.config.SoftLayerComputeServiceContextModule;\nimport org.jclouds.softlayer.config.SoftLayerHttpApiModule;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.inject.Module;\n\n/**\n * Implementation of {@link org.jclouds.apis.ApiMetadata} for API\n */\npublic class SoftLayerApiMetadata extends BaseHttpApiMetadata<SoftLayerApi> {\n\n   @Override\n   public Builder toBuilder() {\n      return new Builder().fromApiMetadata(this);\n   }\n\n   public SoftLayerApiMetadata() {\n      this(new Builder());\n   }\n\n   protected SoftLayerApiMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = BaseHttpApiMetadata.defaultProperties();\n      properties.setProperty(\"jclouds.ssh.max-retries\", \"5\");\n      properties.setProperty(\"jclouds.ssh.retry-auth\", \"true\");\n      return properties;\n   }\n\n   public static class Builder extends BaseHttpApiMetadata.Builder<SoftLayerApi, Builder> {\n\n      protected Builder() {\n         id(SOFTLAYER_PROVIDER_NAME)\n                 .name(\"SoftLayer API\")\n                 .identityName(\"API Username\")\n                 .credentialName(\"API Key\")\n                 .documentation(URI.create(\"http://sldn.softlayer.com/article/REST\"))\n                 .version(\"3\")\n                 .defaultEndpoint(\"https://api.softlayer.com/rest\")\n                 .defaultProperties(SoftLayerApiMetadata.defaultProperties())\n                 .view(typeToken(ComputeServiceContext.class))\n                 .defaultModules(ImmutableSet.<Class<? extends Module>>of(SoftLayerHttpApiModule.class,\n                         SoftLayerComputeServiceContextModule.class)).build();\n      }\n\n      @Override\n      public SoftLayerApiMetadata build() {\n         return new SoftLayerApiMetadata(this);\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/SoftLayerProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer;\n\nimport static org.jclouds.compute.config.ComputeServiceProperties.TEMPLATE;\nimport static org.jclouds.softlayer.reference.SoftLayerConstants.PROPERTY_SOFTLAYER_VIRTUALGUEST_ACTIVE_TRANSACTIONS_DELAY;\nimport static org.jclouds.softlayer.reference.SoftLayerConstants.PROPERTY_SOFTLAYER_VIRTUALGUEST_LOGIN_DETAILS_DELAY;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\n\nimport com.google.auto.service.AutoService;\n\n/**\n * Implementation of {@link ProviderMetadata} for SoftLayer.\n */\n@AutoService(ProviderMetadata.class)\npublic class SoftLayerProviderMetadata extends BaseProviderMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromProviderMetadata(this);\n   }\n\n   public SoftLayerProviderMetadata() {\n      super(builder());\n   }\n\n   public SoftLayerProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = new Properties();\n      properties.setProperty(PROPERTY_SOFTLAYER_VIRTUALGUEST_LOGIN_DETAILS_DELAY, \"\" + 60 * 60 * 1000);\n      properties.setProperty(PROPERTY_SOFTLAYER_VIRTUALGUEST_ACTIVE_TRANSACTIONS_DELAY, \"\" + 3 * 60 * 1000);\n      properties.setProperty(TEMPLATE, \"osFamily=UBUNTU,osVersionMatches=1[01234].[01][04],os64Bit=true\");\n      return properties;\n   }\n\n   public static class Builder extends BaseProviderMetadata.Builder {\n\n      protected Builder() {\n         id(\"softlayer\")\n         .name(\"SoftLayer\")\n         .apiMetadata(new SoftLayerApiMetadata())\n         .homepage(URI.create(\"http://www.softlayer.com\"))\n         .console(URI.create(\"https://manage.softlayer.com\"))\n         .iso3166Codes(\"SG\", \"US-CA\", \"US-TX\", \"US-VA\", \"US-WA\", \"NL\", \"HK\", \"NSFTW-IL\", \"AU\", \"CA-ON\", \"GB\", \"FR\", \"IT\", \"DE\", \"JP\", \"MX\", \"CA-ON\", \"CA-QC\")\n         .endpoint(\"https://api.softlayer.com/rest\")\n         .defaultProperties(SoftLayerProviderMetadata.defaultProperties());\n      }\n\n      @Override\n      public SoftLayerProviderMetadata build() {\n         return new SoftLayerProviderMetadata(this);\n      }\n\n      @Override\n      public Builder fromProviderMetadata(ProviderMetadata in) {\n         super.fromProviderMetadata(in);\n         return this;\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/binders/NotesToJson.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.json.Json;\nimport org.jclouds.rest.Binder;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.inject.Inject;\nimport com.google.inject.Singleton;\n\n/**\n * Converts a String into a json string for changing the notes property of an instance\n * The string is set into the payload of the HttpRequest\n * \n */\n@Singleton\npublic class NotesToJson implements Binder {\n\n   private final Json json;\n\n   @Inject\n   NotesToJson(Json json) {\n      this.json = json;\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkArgument(input instanceof String);\n      String notes = (String)input;\n      request.setPayload(buildJson(notes));\n      return request;\n   }\n\n   private String buildJson(String notes) {\n      return json.toJson(ImmutableMap.of(\"parameters\", ImmutableList.of(ImmutableMap.of(\"notes\", notes))));\n   }\n\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/binders/TagToJson.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.json.Json;\nimport org.jclouds.rest.Binder;\n\nimport com.google.common.base.Joiner;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Converts a Tag into a json string valid for creating a CCI via softlayer api\n * The string is set into the payload of the HttpRequest\n * \n */\n@Singleton\npublic class TagToJson implements Binder {\n\n   private final Json json;\n\n   @Inject\n   public TagToJson(Json json) {\n      this.json = checkNotNull(json, \"json\");\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkArgument(input instanceof Set);\n      Set<String> tags = Set.class.cast(checkNotNull(input, \"input\"));\n      request.setPayload(buildJson(tags));\n      return request;\n   }\n\n   String buildJson(Set<String> tags) {\n      return json.toJson(ImmutableMap.of(\"parameters\", ImmutableSet.of(Joiner.on(\",\").join(tags))));\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/binders/VirtualGuestToJson.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.binders;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.json.Json;\nimport org.jclouds.rest.Binder;\nimport org.jclouds.softlayer.domain.SecuritySshKey;\nimport org.jclouds.softlayer.domain.VirtualGuest;\nimport org.jclouds.softlayer.domain.VirtualGuestBlockDevice;\nimport org.jclouds.softlayer.domain.VirtualGuestNetworkComponent;\nimport org.jclouds.softlayer.domain.internal.BlockDevice;\nimport org.jclouds.softlayer.domain.internal.BlockDeviceTemplateGroup;\nimport org.jclouds.softlayer.domain.internal.Datacenter;\nimport org.jclouds.softlayer.domain.internal.NetworkComponent;\nimport org.jclouds.softlayer.domain.internal.NetworkVlan;\nimport org.jclouds.softlayer.domain.internal.PrimaryBackendNetworkComponent;\nimport org.jclouds.softlayer.domain.internal.PrimaryNetworkComponent;\nimport org.jclouds.softlayer.domain.internal.TemplateObject;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Lists;\nimport com.google.common.collect.Sets;\n\n/**\n * Converts a VirtualGuest into a json string valid for creating a CCI via softlayer api\n * The string is set into the payload of the HttpRequest\n *\n */\npublic class VirtualGuestToJson implements Binder {\n\n   public static final String USER_DATA_KEY = \"value\";\n   private static final String SSH_KEY_ID = \"id\";\n   protected Json json;\n\n   @Inject\n   public VirtualGuestToJson(Json json) {\n      this.json = checkNotNull(json, \"json\");\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      checkArgument(input instanceof VirtualGuest);\n      VirtualGuest virtualGuest = VirtualGuest.class.cast(checkNotNull(input, \"input\"));\n      request.setPayload(buildJson(virtualGuest));\n      return request;\n   }\n\n   /**\n    * Builds a Json string suitable for sending to the softlayer api\n    *\n    * @param virtualGuest\n    * @return String\n    */\n   String buildJson(VirtualGuest virtualGuest) {\n      TemplateObject.Builder templateObjectBuilder = TemplateObject.builder();\n      String hostname = checkNotNull(virtualGuest.getHostname(), \"hostname\");\n      String domain = checkNotNull(virtualGuest.getDomain(), \"domain\");\n      int startCpus = virtualGuest.getStartCpus();\n      int maxMemory = virtualGuest.getMaxMemory();\n      boolean hourlyBillingFlag = virtualGuest.isHourlyBillingFlag();\n      boolean localDisk = virtualGuest.isLocalDiskFlag();\n\n      String datacenterName = checkNotNull(virtualGuest.getDatacenter().getName(), \"datacenterName\");\n      Set<VirtualGuestNetworkComponent> virtualGuestNetworkComponents = virtualGuest.getVirtualGuestNetworkComponents();\n      Set<NetworkComponent> networkComponents = Sets.newHashSet();\n      if (virtualGuestNetworkComponents != null) {\n         networkComponents = FluentIterable.from(virtualGuestNetworkComponents)\n                 .transform(new Function<VirtualGuestNetworkComponent, NetworkComponent>() {\n                    @Override\n                    public NetworkComponent apply(VirtualGuestNetworkComponent virtualGuestNetworkComponent) {\n                       return new NetworkComponent(virtualGuestNetworkComponent.getSpeed());\n                    }\n                 }).toSet();\n      }\n\n      templateObjectBuilder.hostname(hostname)\n                           .domain(domain)\n                           .startCpus(startCpus)\n                           .maxMemory(maxMemory)\n                           .hourlyBillingFlag(hourlyBillingFlag)\n                           .localDiskFlag(localDisk)\n                           .dedicatedAccountHostOnlyFlag(virtualGuest.isDedicatedAccountHostOnly())\n                           .privateNetworkOnlyFlag(virtualGuest.isPrivateNetworkOnly())\n                           .datacenter(new Datacenter(datacenterName));\n\n      if (!networkComponents.isEmpty()) {\n         templateObjectBuilder.networkComponents(networkComponents);\n      }\n      if (virtualGuest.getOperatingSystem() != null) {\n         String operatingSystemReferenceCode = checkNotNull(virtualGuest.getOperatingSystem()\n                 .getOperatingSystemReferenceCode(), \"operatingSystemReferenceCode\");\n         templateObjectBuilder.operatingSystemReferenceCode(operatingSystemReferenceCode)\n                              .blockDevices(getBlockDevices(virtualGuest));\n      } else if (virtualGuest.getVirtualGuestBlockDeviceTemplateGroup() != null) {\n         String globalIdentifier = checkNotNull(virtualGuest.getVirtualGuestBlockDeviceTemplateGroup()\n                 .getGlobalIdentifier(), \"blockDeviceTemplateGroup.globalIdentifier\");\n         templateObjectBuilder.blockDeviceTemplateGroup(new BlockDeviceTemplateGroup(globalIdentifier));\n      }\n\n      if (virtualGuest.getPrimaryNetworkComponent() != null) {\n         templateObjectBuilder.primaryNetworkComponent(new PrimaryNetworkComponent(new NetworkVlan(virtualGuest\n                 .getPrimaryNetworkComponent().getNetworkVlan().getId())));\n      }\n\n      if (virtualGuest.getPrimaryBackendNetworkComponent() != null) {\n         templateObjectBuilder.primaryBackendNetworkComponent(new PrimaryBackendNetworkComponent(new NetworkVlan(virtualGuest\n                 .getPrimaryBackendNetworkComponent().getNetworkVlan().getId())));\n      }\n\n      if (virtualGuest.getPostInstallScriptUri() != null) {\n         templateObjectBuilder.postInstallScriptUri(virtualGuest.getPostInstallScriptUri());\n      }\n\n      if (virtualGuest.getVirtualGuestAttribute() != null) {\n         templateObjectBuilder.userData(ImmutableSet.<Map<String, String>>of(ImmutableMap.of(USER_DATA_KEY,\n                 virtualGuest.getVirtualGuestAttribute().getValue())));\n      }\n\n      if (virtualGuest.getSshKeys() != null) {\n         Set<Map<String, Integer>> sshKeys = Sets.newHashSet();\n         for (SecuritySshKey securitySshKey : virtualGuest.getSshKeys()) {\n            sshKeys.add(ImmutableMap.of(SSH_KEY_ID, securitySshKey.getId()));\n         }\n         templateObjectBuilder.sshKeys(sshKeys);\n      }\n\n      return json.toJson(ImmutableMap.of(\"parameters\", ImmutableList.of(templateObjectBuilder.build())));\n   }\n\n   private List<BlockDevice> getBlockDevices(VirtualGuest virtualGuest) {\n      if (virtualGuest.getVirtualGuestBlockDevices() == null) {\n         return null;\n      }\n      List<BlockDevice> blockDevices = Lists.newArrayList();\n      for (VirtualGuestBlockDevice blockDevice : virtualGuest.getVirtualGuestBlockDevices()) {\n         blockDevices.add(new BlockDevice(blockDevice.getDevice(), blockDevice.getVirtualDiskImage().getCapacity()));\n      }\n      Collections.sort(blockDevices, new BlockDevicesComparator());\n      return ImmutableList.copyOf(blockDevices);\n   }\n\n   public static class BlockDevicesComparator implements Comparator<BlockDevice> {\n\n      @Override\n      public int compare(BlockDevice b1, BlockDevice b2) {\n         return Integer.valueOf(b1.getDevice()).compareTo(Integer.valueOf(b2.getDevice()));\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/compute/config/SoftLayerComputeServiceContextModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.compute.config;\n\nimport static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.ComputeServiceAdapter;\nimport org.jclouds.compute.config.ComputeServiceAdapterContextModule;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.domain.Location;\nimport org.jclouds.functions.IdentityFunction;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.suppliers.MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier;\nimport org.jclouds.softlayer.SoftLayerApi;\nimport org.jclouds.softlayer.compute.functions.DatacenterToLocation;\nimport org.jclouds.softlayer.compute.functions.OperatingSystemToImage;\nimport org.jclouds.softlayer.compute.functions.VirtualGuestToHardware;\nimport org.jclouds.softlayer.compute.functions.VirtualGuestToNodeMetadata;\nimport org.jclouds.softlayer.compute.options.SoftLayerTemplateOptions;\nimport org.jclouds.softlayer.compute.strategy.SoftLayerComputeServiceAdapter;\nimport org.jclouds.softlayer.domain.ContainerVirtualGuestConfiguration;\nimport org.jclouds.softlayer.domain.Datacenter;\nimport org.jclouds.softlayer.domain.OperatingSystem;\nimport org.jclouds.softlayer.domain.VirtualGuest;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Supplier;\nimport com.google.inject.Provides;\nimport com.google.inject.TypeLiteral;\n\npublic class SoftLayerComputeServiceContextModule extends\n         ComputeServiceAdapterContextModule<VirtualGuest, Hardware, OperatingSystem, Datacenter> {\n\n   @Override\n   protected void configure() {\n      super.configure();\n      bind(new TypeLiteral<ComputeServiceAdapter<VirtualGuest, Hardware, OperatingSystem, Datacenter>>() {\n      }).to(SoftLayerComputeServiceAdapter.class);\n      bind(new TypeLiteral<Function<VirtualGuest, NodeMetadata>>() {\n      }).to(VirtualGuestToNodeMetadata.class);\n      bind(new TypeLiteral<Function<OperatingSystem, org.jclouds.compute.domain.Image>>() {\n      }).to(OperatingSystemToImage.class);\n      bind(new TypeLiteral<Function<Hardware, Hardware>>() {\n      }).to(Class.class.cast(IdentityFunction.class));\n      bind(new TypeLiteral<Function<VirtualGuest, org.jclouds.compute.domain.Hardware>>() {\n      }).to(VirtualGuestToHardware.class);\n      bind(new TypeLiteral<Function<Datacenter, Location>>() {\n      }).to(DatacenterToLocation.class);\n      bind(TemplateOptions.class).to(SoftLayerTemplateOptions.class);\n      // to have the compute service adapter override default locations\n      install(new LocationsFromComputeServiceAdapterModule<VirtualGuest, Hardware, OperatingSystem, Datacenter>() {\n      });\n\n   }\n\n   @Provides\n   @Singleton\n   @Memoized\n   public final Supplier<ContainerVirtualGuestConfiguration> getCreateObjectOptions(\n           AtomicReference<AuthorizationException> authException, @Named(PROPERTY_SESSION_INTERVAL) long seconds,\n           final SoftLayerApi api) {\n      return MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier.create(authException,\n              new Supplier<ContainerVirtualGuestConfiguration>() {\n                 @Override\n                 public ContainerVirtualGuestConfiguration get() {\n                    return api.getVirtualGuestApi().getCreateObjectOptions();\n                 }\n\n                 @Override\n                 public String toString() {\n                    return MoreObjects.toStringHelper(api)\n                            .add(\"method\", \"virtualGuestApi.getCreateObjectOptions\")\n                            .toString();\n                 }\n              }, seconds, TimeUnit.SECONDS);\n   }\n\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/compute/functions/DatacenterToLocation.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.compute.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Strings.nullToEmpty;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.location.suppliers.all.JustProvider;\nimport org.jclouds.softlayer.domain.Address;\nimport org.jclouds.softlayer.domain.Datacenter;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\n\n/**\n * Converts an Datacenter into a Location.\n */\n@Singleton\npublic class DatacenterToLocation implements Function<Datacenter, Location> {\n   private final JustProvider provider;\n\n   // allow us to lazy discover the provider of a resource\n   @Inject\n   public DatacenterToLocation(JustProvider provider) {\n      this.provider = checkNotNull(provider, \"provider\");\n   }\n\n    @Override\n    public Location apply(Datacenter datacenter) {\n        return new LocationBuilder().id(datacenter.getName())\n                                    .description(datacenter.getLongName())\n                                    .scope(LocationScope.ZONE)\n                                    .iso3166Codes(createIso3166Codes(datacenter.getLocationAddress()))\n                                    .parent(Iterables.getOnlyElement(provider.get()))\n                                    .metadata(ImmutableMap.<String, Object>of(\"name\", datacenter.getName()))\n                                    .build();\n   }\n\n   private Iterable<String> createIso3166Codes(Address address) {\n      if (address == null) return ImmutableSet.<String> of();\n\n      final String country = nullToEmpty(address.getCountry()).trim();\n      if (country.isEmpty()) return ImmutableSet.<String> of();\n\n      final String state = nullToEmpty(address.getState()).trim();\n      if (state.isEmpty()) return ImmutableSet.<String> of(address.getCountry());\n\n      return ImmutableSet.<String> of(\"\" + country + \"-\" + state);\n\n\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/compute/functions/OperatingSystemToImage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.compute.functions;\n\nimport static com.google.common.base.Optional.fromNullable;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.ImageBuilder;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.softlayer.compute.functions.internal.OperatingSystems;\nimport org.jclouds.softlayer.domain.OperatingSystem;\nimport org.jclouds.softlayer.domain.SoftwareDescription;\nimport org.jclouds.softlayer.domain.SoftwareLicense;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Objects;\nimport com.google.common.base.Optional;\n\n@Singleton\npublic class OperatingSystemToImage implements Function<OperatingSystem, Image> {\n\n   private static final String UNRECOGNIZED = \"UNRECOGNIZED\";\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   @Override\n   public Image apply(OperatingSystem operatingSystem) {\n      checkNotNull(operatingSystem, \"operatingSystem\");\n      final SoftwareLicense defaultSoftwareLicense = SoftwareLicense.builder().softwareDescription(SoftwareDescription.builder().build()).build();\n      SoftwareLicense softwareLicense = fromNullable(operatingSystem.getSoftwareLicense()).or(defaultSoftwareLicense);\n      Optional<String> optOSReferenceCode = fromNullable(softwareLicense.getSoftwareDescription().getReferenceCode());\n      Optional<String> optVersion = fromNullable(softwareLicense.getSoftwareDescription().getVersion());\n      Optional<String> optLongDescription = fromNullable(softwareLicense.getSoftwareDescription().getLongDescription());\n      OsFamily osFamily = OsFamily.UNRECOGNIZED;\n      String osVersion = UNRECOGNIZED;\n      Integer bits = null;\n      if (optOSReferenceCode.isPresent()) {\n         String operatingSystemReferenceCode = optOSReferenceCode.get();\n         osFamily = OperatingSystems.osFamily().apply(operatingSystemReferenceCode);\n         bits = OperatingSystems.bits().apply(operatingSystemReferenceCode);\n      }\n      if (optVersion.isPresent()) {\n         osVersion = OperatingSystems.version().apply(optVersion.get());\n      }\n      if (osFamily == OsFamily.UNRECOGNIZED) {\n         logger.debug(\"Cannot determine os family for item: %s\", operatingSystem);\n      }\n      if (osVersion == null) {\n         logger.debug(\"Cannot determine os version for item: %s\", operatingSystem);\n      }\n      if (bits == null) {\n         logger.debug(\"Cannot determine os bits for item: %s\", operatingSystem);\n      }\n\n      org.jclouds.compute.domain.OperatingSystem os = org.jclouds.compute.domain.OperatingSystem.builder()\n              .description(optLongDescription.or(UNRECOGNIZED))\n              .family(osFamily)\n              .version(osVersion)\n              .is64Bit(Objects.equal(bits, 64))\n              .build();\n\n      return new ImageBuilder()\n              .ids(optOSReferenceCode.or(operatingSystem.getId()))\n              .description(optOSReferenceCode.or(UNRECOGNIZED))\n              .operatingSystem(os)\n              .status(Image.Status.AVAILABLE)\n              .build();\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/compute/functions/VirtualGuestToHardware.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.compute.functions;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.HardwareBuilder;\nimport org.jclouds.compute.domain.Processor;\nimport org.jclouds.compute.domain.Volume;\nimport org.jclouds.compute.domain.internal.VolumeImpl;\nimport org.jclouds.softlayer.domain.VirtualGuest;\nimport org.jclouds.softlayer.domain.VirtualGuestBlockDevice;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableList;\n\n@Singleton\npublic class VirtualGuestToHardware implements Function<VirtualGuest, Hardware> {\n\n   @Override\n   public Hardware apply(final VirtualGuest from) {\n      HardwareBuilder builder = new HardwareBuilder().ids(from.getId() + \"\")\n              .name(from.getHostname())\n              .hypervisor(\"XenServer\")\n              .processors(ImmutableList.of(new Processor(from.getStartCpus(), 2)))\n              .ram(from.getMaxMemory());\n\n      if (from.getVirtualGuestBlockDevices() != null) {\n         builder.volumes(\n                 FluentIterable.from(from.getVirtualGuestBlockDevices()).filter(new Predicate<VirtualGuestBlockDevice>() {\n                    @Override\n                    public boolean apply(VirtualGuestBlockDevice input) {\n                       return input.getMountType().equals(\"Disk\");\n                    }\n                 })\n                         .transform(new Function<VirtualGuestBlockDevice, Volume>() {\n                            @Override\n                            public Volume apply(VirtualGuestBlockDevice item) {\n                               float volumeSize = -1;\n                               if (item.getVirtualDiskImage() != null) {\n                                  volumeSize = item.getVirtualDiskImage().getCapacity();\n                               }\n                               return new VolumeImpl(\n                                       item.getId() + \"\",\n                                       from.isLocalDiskFlag() ? Volume.Type.LOCAL : Volume.Type.SAN,\n                                       volumeSize, null, item.getBootableFlag() == 1, false);\n                            }\n                         }).toSet());\n      }\n      return builder.build();\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/compute/functions/VirtualGuestToImage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.compute.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.ImageBuilder;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.softlayer.domain.VirtualGuest;\n\nimport com.google.common.base.Function;\nimport com.google.inject.Inject;\n\n@Singleton\npublic class VirtualGuestToImage implements Function<VirtualGuest, Image> {\n\n   private static final String UNRECOGNIZED = \"UNRECOGNIZED\";\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   private final OperatingSystemToImage operatingSystemToImage;\n\n   @Inject\n   protected VirtualGuestToImage(OperatingSystemToImage operatingSystemToImage) {\n      this.operatingSystemToImage = checkNotNull(operatingSystemToImage, \"operatingSystemToImage\");\n   }\n\n   @Override\n   public Image apply(VirtualGuest from) {\n      checkNotNull(from, \"from\");\n      if (from.getOperatingSystem() == null) {\n         return new ImageBuilder().ids(getReferenceCodeOrId(from))\n                 .name(from.getHostname())\n                 .status(Image.Status.UNRECOGNIZED)\n                 .operatingSystem(OperatingSystem.builder()\n                         .family(OsFamily.UNRECOGNIZED)\n                         .version(UNRECOGNIZED)\n                         .description(UNRECOGNIZED)\n                         .build())\n                 .build();\n      } else {\n         return operatingSystemToImage.apply(from.getOperatingSystem());\n      }\n   }\n\n   public String getReferenceCodeOrId(VirtualGuest from) {\n      String val = from.getSoftwareLicense() != null &&\n              from.getSoftwareLicense().getSoftwareDescription() != null ?\n              from.getSoftwareLicense().getSoftwareDescription().getReferenceCode() :\n              from.getId() + \"\";\n      return val;\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/compute/functions/VirtualGuestToNodeMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.compute.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.FluentIterable.from;\n\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadata.Status;\nimport org.jclouds.compute.domain.NodeMetadataBuilder;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.location.predicates.LocationPredicates;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.softlayer.domain.Password;\nimport org.jclouds.softlayer.domain.TagReference;\nimport org.jclouds.softlayer.domain.VirtualGuest;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Lists;\nimport com.google.common.collect.Sets;\n\n@Singleton\npublic class VirtualGuestToNodeMetadata implements Function<VirtualGuest, NodeMetadata> {\n\n   @Resource\n   protected Logger logger = Logger.NULL;\n    \n   public static final Map<VirtualGuest.State, Status> serverStateToNodeStatus = ImmutableMap\n         .<VirtualGuest.State, Status> builder().put(VirtualGuest.State.HALTED, Status.PENDING)\n         .put(VirtualGuest.State.PAUSED, Status.SUSPENDED).put(VirtualGuest.State.RUNNING, Status.RUNNING)\n         .put(VirtualGuest.State.UNRECOGNIZED, Status.UNRECOGNIZED).build();\n\n   private final Supplier<Set<? extends Location>> locations;\n   private final GroupNamingConvention nodeNamingConvention;\n   private final VirtualGuestToImage virtualGuestToImage;\n   private final VirtualGuestToHardware virtualGuestToHardware;\n\n\n   @Inject\n   VirtualGuestToNodeMetadata(@Memoized Supplier<Set<? extends Location>> locations,\n         GroupNamingConvention.Factory namingConvention, VirtualGuestToImage virtualGuestToImage,\n         VirtualGuestToHardware virtualGuestToHardware) {\n      this.nodeNamingConvention = checkNotNull(namingConvention, \"namingConvention\").createWithoutPrefix();\n      this.locations = checkNotNull(locations, \"locations\");\n      this.virtualGuestToImage = checkNotNull(virtualGuestToImage, \"virtualGuestToImage\");\n      this.virtualGuestToHardware = checkNotNull(virtualGuestToHardware, \"virtualGuestToHardware\");\n   }\n\n   @Override\n   public NodeMetadata apply(VirtualGuest from) {\n      NodeMetadataBuilder builder = new NodeMetadataBuilder();\n      builder.ids(from.getId() + \"\");\n      builder.name(from.getHostname());\n      builder.hostname(from.getFullyQualifiedDomainName());\n      if (from.getDatacenter() != null) {\n         builder.location(from(locations.get()).firstMatch(\n                 LocationPredicates.idEquals(from.getDatacenter().getName())).orNull());\n      }\n      builder.group(nodeNamingConvention.groupInUniqueNameOrNull(from.getHostname()));\n      builder.hardware(virtualGuestToHardware.apply(from));\n      Image image = virtualGuestToImage.apply(from);\n      if (image != null) {\n         builder.imageId(image.getId());\n         builder.operatingSystem(image.getOperatingSystem());\n      }\n      if (from.getPowerState() != null) {\n         builder.status(serverStateToNodeStatus.get(from.getPowerState().getKeyName()));\n      }\n      if (from.getPrimaryIpAddress() != null)\n         builder.publicAddresses(ImmutableSet.of(from.getPrimaryIpAddress()));\n      if (from.getPrimaryBackendIpAddress() != null)\n         builder.privateAddresses(ImmutableSet.of(from.getPrimaryBackendIpAddress()));\n      // TODO simplify once we move domain classes to AutoValue\n      if (from.getOperatingSystem() != null && from.getOperatingSystem().getPasswords() != null && !from.getOperatingSystem().getPasswords().isEmpty()) {\n         Password password = getBestPassword(from.getOperatingSystem().getPasswords(), from);\n         builder.credentials(LoginCredentials.builder().identity(password.getUsername()).credential(password.getPassword()).build());\n      }\n      if (from.getTagReferences() != null && !from.getTagReferences().isEmpty()) {\n         List<String> tags = Lists.newArrayList();\n         for (TagReference tagReference : from.getTagReferences()) {\n            if (tagReference != null) {\n               tags.add(tagReference.getTag().getName());\n            }\n         }\n         builder.tags(tags);\n      }\n      return builder.build();\n   }\n\n   @VisibleForTesting\n   Password getBestPassword(Set<Password> passwords, VirtualGuest context) {\n      if (passwords == null || passwords.isEmpty()) {\n         throw new IllegalStateException(\"No credentials declared for \" + context);\n      }\n      if (passwords.size() == 1) {\n          // usual path\n          return Iterables.getOnlyElement(passwords);\n      }\n      // in some setups a there may be multiple passwords; pick the best\n      Password bestPassword = null;\n      Set<Password> alternates = Sets.newLinkedHashSet();\n      int bestScore = -1;\n      for (Password p : passwords) {\n         int score = -1;\n         if (\"root\".equals(p.getUsername())) score = 10;\n         else if (\"root\".equalsIgnoreCase(p.getUsername())) score = 4;\n         else if (\"ubuntu\".equals(p.getUsername())) score = 8;\n         else if (\"ubuntu\".equalsIgnoreCase(p.getUsername())) score = 3;\n         else if (\"administrator\".equals(p.getUsername())) score = 5;\n         else if (\"administrator\".equalsIgnoreCase(p.getUsername())) score = 2;\n         else if (p.getUsername() != null && p.getUsername().length() > 1) score = 1;\n         \n         if (score > 0) {\n            if (score > bestScore) {\n                bestPassword = p;\n                alternates.clear();\n                bestScore = score;\n            } else if (score == bestScore) {\n                alternates.add(p);\n            }\n         }\n      }\n      if (bestPassword == null) {\n          throw new IllegalStateException(\"No valid credentials available for \" + context + \"; found: \" + passwords);\n      }\n      if (!alternates.isEmpty()) {\n         logger.warn(\"Multiple credentials for \" + bestPassword.getUsername() + \"@\" + context + \"; using first declared \" + bestPassword + \" and ignoring \" + alternates);\n      } else {\n         logger.debug(\"Multiple credentials for \" + context + \"; using preferred username \" + bestPassword.getUsername());\n      }\n      return bestPassword;\n   }\n\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/compute/functions/internal/OperatingSystems.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.compute.functions.internal;\n\nimport static com.google.common.collect.Iterables.getLast;\n\nimport org.jclouds.compute.domain.OsFamily;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.Iterables;\nimport com.google.common.primitives.Ints;\n\npublic class OperatingSystems {\n\n   protected static final String CENTOS = \"CENTOS\";\n   protected static final String DEBIAN = \"DEBIAN\";\n   protected static final String RHEL = \"REDHAT\";\n   protected static final String UBUNTU = \"UBUNTU\";\n   protected static final String WINDOWS = \"WIN_\";\n   protected static final String CLOUD_LINUX = \"CLOUDLINUX\";\n   protected static final String VYATTACE = \"VYATTACE\";\n\n   public static Function<String, OsFamily> osFamily() {\n      return new Function<String, OsFamily>() {\n         @Override\n         public OsFamily apply(final String description) {\n            if (description != null) {\n               if (description.startsWith(CENTOS)) return OsFamily.CENTOS;\n               else if (description.startsWith(DEBIAN)) return OsFamily.DEBIAN;\n               else if (description.startsWith(RHEL)) return OsFamily.RHEL;\n               else if (description.startsWith(UBUNTU)) return OsFamily.UBUNTU;\n               else if (description.startsWith(WINDOWS)) return OsFamily.WINDOWS;\n               else if (description.startsWith(CLOUD_LINUX)) return OsFamily.CLOUD_LINUX;\n               else if (description.startsWith(VYATTACE)) return OsFamily.LINUX;\n            }\n            return OsFamily.UNRECOGNIZED;\n         }\n      };\n   }\n\n   public static Function<String, Integer> bits() {\n      return new Function<String, Integer>() {\n         @Override\n         public Integer apply(String operatingSystemReferenceCode) {\n            if (operatingSystemReferenceCode != null) {\n               return Ints.tryParse(getLast(Splitter.on(\"_\").split(operatingSystemReferenceCode)));\n            }\n            return null;\n         }\n      };\n   }\n\n   public static Function<String, String> version() {\n      return new Function<String, String>() {\n         @Override\n         public String apply(final String version) {\n            return parseVersion(version);\n         }\n      };\n   }\n\n   private static String parseVersion(String version) {\n      if (version.contains(\"-\")) {\n         String rawVersion = version.substring(0, version.lastIndexOf(\"-\"));\n         if (Iterables.size(Splitter.on(\".\").split(rawVersion)) == 3) {\n            return rawVersion.substring(0, rawVersion.lastIndexOf(\".\"));\n         } else {\n            return rawVersion;\n         }\n      } else if (version.contains(\" \")) {\n         return version.substring(0, version.indexOf(\" \"));\n      } else if (version.matches(\"^(\\\\d+\\\\.)?(\\\\d+\\\\.)?(\\\\*|\\\\d+)$\")) {\n         return version;\n      }\n      return null;\n   }\n\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/compute/options/SoftLayerTemplateOptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.compute.options;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.scriptbuilder.domain.Statement;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.net.InternetDomainName;\n\n/**\n * Contains options supported by the\n * {@link org.jclouds.compute.ComputeService#createNodesInGroup(String, int, TemplateOptions)} and\n * {@link org.jclouds.compute.ComputeService#createNodesInGroup(String, int, TemplateOptions)}\n * operations on the <em>gogrid</em> provider.\n *\n * <h2>Usage</h2> The recommended way to instantiate a\n * {@link SoftLayerTemplateOptions} object is to statically import\n * {@code SoftLayerTemplateOptions.*} and invoke a static creation method\n * followed by an instance mutator (if needed):\n * <p>\n *\n * <pre>\n * import static org.jclouds.compute.options.SoftLayerTemplateOptions.Builder.*;\n * ComputeService client = // get connection\n * templateBuilder.options(inboundPorts(22, 80, 8080, 443));\n * Set&lt;? extends NodeMetadata&gt; set = client.createNodesInGroup(tag, 2, templateBuilder.build());\n * </pre>\n *\n */\npublic class SoftLayerTemplateOptions extends TemplateOptions implements Cloneable {\n\n   protected String domainName = \"jclouds.org\";\n   protected List<Integer> blockDevices = ImmutableList.of();\n   protected String diskType;\n   protected Integer portSpeed;\n   protected String userData;\n   protected Integer primaryNetworkComponentNetworkVlanId;\n   protected Integer primaryBackendNetworkComponentNetworkVlanId;\n   protected Boolean hourlyBillingFlag;\n   protected Boolean dedicatedAccountHostOnlyFlag;\n   protected Boolean privateNetworkOnlyFlag;\n   protected String postInstallScriptUri;\n   protected List<Integer> sshKeys = ImmutableList.of();\n\n   @Override\n   public SoftLayerTemplateOptions clone() {\n      SoftLayerTemplateOptions options = new SoftLayerTemplateOptions();\n      copyTo(options);\n      return options;\n   }\n\n   @Override\n   public void copyTo(TemplateOptions to) {\n      super.copyTo(to);\n      if (to instanceof SoftLayerTemplateOptions) {\n         SoftLayerTemplateOptions eTo = SoftLayerTemplateOptions.class.cast(to);\n         eTo.domainName(domainName);\n         if (!blockDevices.isEmpty()) {\n            eTo.blockDevices(blockDevices);\n         }\n         eTo.diskType(diskType);\n         eTo.portSpeed(portSpeed);\n         eTo.userData(userData);\n         eTo.primaryNetworkComponentNetworkVlanId(primaryNetworkComponentNetworkVlanId);\n         eTo.primaryBackendNetworkComponentNetworkVlanId(primaryBackendNetworkComponentNetworkVlanId);\n         eTo.hourlyBillingFlag(hourlyBillingFlag);\n         eTo.dedicatedAccountHostOnlyFlag(dedicatedAccountHostOnlyFlag);\n         eTo.privateNetworkOnlyFlag(privateNetworkOnlyFlag);\n         if (!sshKeys.isEmpty()) {\n            eTo.sshKeys(sshKeys);\n         }\n      }\n   }\n\n   /**\n    * will replace the default domain used when ordering virtual guests. Note\n    * this needs to contain a public suffix!\n    *\n    * @see org.jclouds.softlayer.features.VirtualGuestApi#createVirtualGuest(org.jclouds.softlayer.domain.VirtualGuest)\n    * @see InternetDomainName#hasPublicSuffix\n    */\n   public SoftLayerTemplateOptions domainName(String domainName) {\n      checkNotNull(domainName, \"domainName was null\");\n      checkArgument(InternetDomainName.from(domainName).hasPublicSuffix(), \"domainName %s has no public suffix\",\n            domainName);\n      this.domainName = domainName;\n      return this;\n   }\n\n   public SoftLayerTemplateOptions blockDevices(Iterable<Integer> capacities) {\n      for (Integer capacity : checkNotNull(capacities, \"capacities\"))\n         checkNotNull(capacity, \"all block devices must be non-empty\");\n      this.blockDevices = ImmutableList.copyOf(capacities);\n      return this;\n   }\n\n   public SoftLayerTemplateOptions blockDevices(Integer... capacities) {\n      return blockDevices(ImmutableList.copyOf(checkNotNull(capacities, \"capacities\")));\n   }\n\n   public SoftLayerTemplateOptions diskType(@Nullable String diskType) {\n      this.diskType = diskType;\n      return this;\n   }\n\n   public SoftLayerTemplateOptions portSpeed(@Nullable Integer portSpeed) {\n      this.portSpeed = portSpeed;\n      return this;\n   }\n\n   public SoftLayerTemplateOptions userData(@Nullable String userData) {\n      this.userData = userData;\n      return this;\n   }\n\n   public SoftLayerTemplateOptions primaryNetworkComponentNetworkVlanId(@Nullable Integer primaryNetworkComponentNetworkVlanId) {\n      this.primaryNetworkComponentNetworkVlanId = primaryNetworkComponentNetworkVlanId;\n      return this;\n   }\n\n   public SoftLayerTemplateOptions primaryBackendNetworkComponentNetworkVlanId(@Nullable Integer primaryBackendNetworkComponentNetworkVlanId) {\n      this.primaryBackendNetworkComponentNetworkVlanId = primaryBackendNetworkComponentNetworkVlanId;\n      return this;\n   }\n\n   public SoftLayerTemplateOptions hourlyBillingFlag(@Nullable Boolean hourlyBillingFlag) {\n      this.hourlyBillingFlag = hourlyBillingFlag;\n      return this;\n   }\n\n   public SoftLayerTemplateOptions dedicatedAccountHostOnlyFlag(@Nullable Boolean dedicatedAccountHostOnlyFlag) {\n      this.dedicatedAccountHostOnlyFlag = dedicatedAccountHostOnlyFlag;\n      return this;\n   }\n\n   public SoftLayerTemplateOptions privateNetworkOnlyFlag(@Nullable Boolean privateNetworkOnlyFlag) {\n      this.privateNetworkOnlyFlag = privateNetworkOnlyFlag;\n      return this;\n   }\n\n   public SoftLayerTemplateOptions postInstallScriptUri(@Nullable String postInstallScriptUri) {\n      this.postInstallScriptUri = postInstallScriptUri;\n      return this;\n   }\n\n   public SoftLayerTemplateOptions sshKeys(Iterable<Integer> sshKeys) {\n      for (Integer sshKey : checkNotNull(sshKeys, \"sshKeys\"))\n         checkNotNull(sshKey, \"sshKeys must be non-empty\");\n      this.sshKeys = ImmutableList.copyOf(sshKeys);\n      return this;\n   }\n\n   public SoftLayerTemplateOptions sshKeys(Integer... sshKeys) {\n      return sshKeys(ImmutableList.copyOf(checkNotNull(sshKeys, \"sshKeys\")));\n   }\n\n   public String getDomainName() {\n      return domainName;\n   }\n\n   public List<Integer> getBlockDevices() {\n      return blockDevices;\n   }\n\n   public String getDiskType() {\n      return diskType;\n   }\n\n   public Integer getPortSpeed() {\n      return portSpeed;\n   }\n\n   public String getUserData() { return userData; }\n\n   public Integer getPrimaryNetworkComponentNetworkVlanId() { return primaryNetworkComponentNetworkVlanId; }\n\n   public Integer getPrimaryBackendNetworkComponentNetworkVlanId() { return primaryBackendNetworkComponentNetworkVlanId; }\n\n   public Boolean isHourlyBillingFlag() { return hourlyBillingFlag; }\n\n   public Boolean isDedicatedAccountHostOnlyFlag() { return dedicatedAccountHostOnlyFlag; }\n\n   public Boolean isPrivateNetworkOnlyFlag() { return privateNetworkOnlyFlag; }\n\n   public String getPostInstallScriptUri() { return postInstallScriptUri; }\n\n   public List<Integer> getSshKeys() {\n      return sshKeys;\n   }\n\n   public static class Builder {\n\n      /**\n       * @see #domainName\n       */\n      public static SoftLayerTemplateOptions domainName(String domainName) {\n         SoftLayerTemplateOptions options = new SoftLayerTemplateOptions();\n         return options.domainName(domainName);\n      }\n\n      /**\n       * @see #blockDevices\n       */\n      public static SoftLayerTemplateOptions blockDevices(Integer... capacities) {\n         SoftLayerTemplateOptions options = new SoftLayerTemplateOptions();\n         return options.blockDevices(capacities);\n      }\n\n      public static SoftLayerTemplateOptions blockDevices(Iterable<Integer> capacities) {\n         SoftLayerTemplateOptions options = new SoftLayerTemplateOptions();\n         return options.blockDevices(capacities);\n      }\n\n      /**\n       * @see #diskType\n       */\n      public static SoftLayerTemplateOptions diskType(String diskType) {\n         SoftLayerTemplateOptions options = new SoftLayerTemplateOptions();\n         return options.diskType(diskType);\n      }\n\n      /**\n       * @see #portSpeed\n       */\n      public static SoftLayerTemplateOptions portSpeed(Integer portSpeed) {\n         SoftLayerTemplateOptions options = new SoftLayerTemplateOptions();\n         return options.portSpeed(portSpeed);\n      }\n\n      /**\n       * @see #userData\n       */\n      public static SoftLayerTemplateOptions userData(String userData) {\n         SoftLayerTemplateOptions options = new SoftLayerTemplateOptions();\n         return options.userData(userData);\n      }\n\n      /**\n       * @see #primaryNetworkComponentNetworkVlanId\n       */\n      public static SoftLayerTemplateOptions primaryNetworkComponentNetworkVlanId(Integer primaryNetworkComponentNetworkVlanId) {\n         SoftLayerTemplateOptions options = new SoftLayerTemplateOptions();\n         return options.primaryNetworkComponentNetworkVlanId(primaryNetworkComponentNetworkVlanId);\n      }\n\n      /**\n       * @see #primaryBackendNetworkComponentNetworkVlanId\n       */\n      public static SoftLayerTemplateOptions primaryBackendNetworkComponentNetworkVlanId(Integer primaryBackendNetworkComponentNetworkVlanId) {\n         SoftLayerTemplateOptions options = new SoftLayerTemplateOptions();\n         return options.primaryBackendNetworkComponentNetworkVlanId(primaryBackendNetworkComponentNetworkVlanId);\n      }\n\n      /**\n       * @see #hourlyBillingFlag\n       */\n      public static SoftLayerTemplateOptions hourlyBillingFlag(boolean hourlyBillingFlag) {\n         SoftLayerTemplateOptions options = new SoftLayerTemplateOptions();\n         return options.hourlyBillingFlag(hourlyBillingFlag);\n      }\n\n      /**\n       * @see #dedicatedAccountHostOnlyFlag\n       */\n      public static SoftLayerTemplateOptions dedicatedAccountHostOnlyFlag(boolean dedicatedAccountHostOnlyFlag) {\n         SoftLayerTemplateOptions options = new SoftLayerTemplateOptions();\n         return options.dedicatedAccountHostOnlyFlag(dedicatedAccountHostOnlyFlag);\n      }\n\n      /**\n       * @see #privateNetworkOnlyFlag\n       */\n      public static SoftLayerTemplateOptions privateNetworkOnlyFlag(boolean privateNetworkOnlyFlag) {\n         SoftLayerTemplateOptions options = new SoftLayerTemplateOptions();\n         return options.privateNetworkOnlyFlag(privateNetworkOnlyFlag);\n      }\n\n      /**\n       * @see #postInstallScriptUri(String)\n       */\n      public static SoftLayerTemplateOptions postInstallScriptUri(String postInstallScriptUri) {\n         SoftLayerTemplateOptions options = new SoftLayerTemplateOptions();\n         return options.postInstallScriptUri(postInstallScriptUri);\n      }\n\n      /**\n       * @see #sshKeys(Iterable)\n       */\n      public static SoftLayerTemplateOptions sshKeys(Integer... sshKeys) {\n         SoftLayerTemplateOptions options = new SoftLayerTemplateOptions();\n         return options.sshKeys(sshKeys);\n      }\n\n      public static SoftLayerTemplateOptions sshKeys(Iterable<Integer> sshKeys) {\n         SoftLayerTemplateOptions options = new SoftLayerTemplateOptions();\n         return options.blockDevices(sshKeys);\n      }\n\n      /**\n       * @see TemplateOptions#inboundPorts(int...)\n       */\n      public static SoftLayerTemplateOptions inboundPorts(int... ports) {\n         SoftLayerTemplateOptions options = new SoftLayerTemplateOptions();\n         return options.inboundPorts(ports);\n      }\n\n      /**\n       * @see TemplateOptions#blockOnPort(int, int)\n       */\n      public static SoftLayerTemplateOptions blockOnPort(int port, int seconds) {\n         SoftLayerTemplateOptions options = new SoftLayerTemplateOptions();\n         return options.blockOnPort(port, seconds);\n      }\n\n      /**\n       * @see TemplateOptions#installPrivateKey(String)\n       */\n      public static SoftLayerTemplateOptions installPrivateKey(String rsaKey) {\n         SoftLayerTemplateOptions options = new SoftLayerTemplateOptions();\n         return options.installPrivateKey(rsaKey);\n      }\n\n      /**\n       * @see TemplateOptions#authorizePublicKey(String)\n       */\n      public static SoftLayerTemplateOptions authorizePublicKey(String rsaKey) {\n         SoftLayerTemplateOptions options = new SoftLayerTemplateOptions();\n         return options.authorizePublicKey(rsaKey);\n      }\n\n      /**\n       * @see TemplateOptions#userMetadata(Map)\n       */\n      public static SoftLayerTemplateOptions userMetadata(Map<String, String> userMetadata) {\n         SoftLayerTemplateOptions options = new SoftLayerTemplateOptions();\n         return options.userMetadata(userMetadata);\n      }\n\n      /**\n       * @see TemplateOptions#nodeNames(Iterable)\n       */\n      public static SoftLayerTemplateOptions nodeNames(Iterable<String> nodeNames) {\n         SoftLayerTemplateOptions options = new SoftLayerTemplateOptions();\n         return options.nodeNames(nodeNames);\n      }\n\n      /**\n       * @see TemplateOptions#networks(Iterable)\n       */\n      public static SoftLayerTemplateOptions networks(Iterable<String> networks) {\n         SoftLayerTemplateOptions options = new SoftLayerTemplateOptions();\n         return options.networks(networks);\n      }\n\n      /**\n       * @see TemplateOptions#overrideLoginUser(String)\n       */\n      public static SoftLayerTemplateOptions overrideLoginUser(String user) {\n         SoftLayerTemplateOptions options = new SoftLayerTemplateOptions();\n         return options.overrideLoginUser(user);\n      }\n\n      /**\n       * @see TemplateOptions#overrideLoginPassword(String)\n       */\n      public static SoftLayerTemplateOptions overrideLoginPassword(String password) {\n         SoftLayerTemplateOptions options = new SoftLayerTemplateOptions();\n         return options.overrideLoginPassword(password);\n      }\n\n      /**\n       * @see TemplateOptions#overrideLoginPrivateKey(String)\n       */\n      public static SoftLayerTemplateOptions overrideLoginPrivateKey(String privateKey) {\n         SoftLayerTemplateOptions options = new SoftLayerTemplateOptions();\n         return options.overrideLoginPrivateKey(privateKey);\n      }\n\n      /**\n       * @see TemplateOptions#overrideAuthenticateSudo(boolean)\n       */\n      public static SoftLayerTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo) {\n         SoftLayerTemplateOptions options = new SoftLayerTemplateOptions();\n         return options.overrideAuthenticateSudo(authenticateSudo);\n      }\n\n      /**\n       * @see TemplateOptions#overrideLoginCredentials(LoginCredentials)\n       */\n      public static SoftLayerTemplateOptions overrideLoginCredentials(LoginCredentials credentials) {\n         SoftLayerTemplateOptions options = new SoftLayerTemplateOptions();\n         return options.overrideLoginCredentials(credentials);\n      }\n\n      /**\n       * @see TemplateOptions#blockUntilRunning(boolean)\n       */\n      public static SoftLayerTemplateOptions blockUntilRunning(boolean blockUntilRunning) {\n         SoftLayerTemplateOptions options = new SoftLayerTemplateOptions();\n         return options.blockUntilRunning(blockUntilRunning);\n      }\n\n   }\n   // methods that only facilitate returning the correct object type\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public SoftLayerTemplateOptions blockOnPort(int port, int seconds) {\n      return SoftLayerTemplateOptions.class.cast(super.blockOnPort(port, seconds));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public SoftLayerTemplateOptions inboundPorts(int... ports) {\n      return SoftLayerTemplateOptions.class.cast(super.inboundPorts(ports));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public SoftLayerTemplateOptions authorizePublicKey(String publicKey) {\n      return SoftLayerTemplateOptions.class.cast(super.authorizePublicKey(publicKey));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public SoftLayerTemplateOptions installPrivateKey(String privateKey) {\n      return SoftLayerTemplateOptions.class.cast(super.installPrivateKey(privateKey));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public SoftLayerTemplateOptions blockUntilRunning(boolean blockUntilRunning) {\n      return SoftLayerTemplateOptions.class.cast(super.blockUntilRunning(blockUntilRunning));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public SoftLayerTemplateOptions dontAuthorizePublicKey() {\n      return SoftLayerTemplateOptions.class.cast(super.dontAuthorizePublicKey());\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public SoftLayerTemplateOptions nameTask(String name) {\n      return SoftLayerTemplateOptions.class.cast(super.nameTask(name));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public SoftLayerTemplateOptions runAsRoot(boolean runAsRoot) {\n      return SoftLayerTemplateOptions.class.cast(super.runAsRoot(runAsRoot));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public SoftLayerTemplateOptions runScript(Statement script) {\n      return SoftLayerTemplateOptions.class.cast(super.runScript(script));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public SoftLayerTemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials) {\n      return SoftLayerTemplateOptions.class.cast(super.overrideLoginCredentials(overridingCredentials));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public SoftLayerTemplateOptions overrideLoginPassword(String password) {\n      return SoftLayerTemplateOptions.class.cast(super.overrideLoginPassword(password));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public SoftLayerTemplateOptions overrideLoginPrivateKey(String privateKey) {\n      return SoftLayerTemplateOptions.class.cast(super.overrideLoginPrivateKey(privateKey));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public SoftLayerTemplateOptions overrideLoginUser(String loginUser) {\n      return SoftLayerTemplateOptions.class.cast(super.overrideLoginUser(loginUser));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public SoftLayerTemplateOptions overrideAuthenticateSudo(boolean authenticateSudo) {\n      return SoftLayerTemplateOptions.class.cast(super.overrideAuthenticateSudo(authenticateSudo));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public SoftLayerTemplateOptions userMetadata(Map<String, String> userMetadata) {\n      return SoftLayerTemplateOptions.class.cast(super.userMetadata(userMetadata));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public SoftLayerTemplateOptions userMetadata(String key, String value) {\n      return SoftLayerTemplateOptions.class.cast(super.userMetadata(key, value));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public SoftLayerTemplateOptions nodeNames(Iterable<String> nodeNames) {\n      return SoftLayerTemplateOptions.class.cast(super.nodeNames(nodeNames));\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public SoftLayerTemplateOptions networks(Iterable<String> networks) {\n      return SoftLayerTemplateOptions.class.cast(super.networks(networks));\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/compute/strategy/SoftLayerComputeServiceAdapter.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.compute.strategy;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.common.collect.Iterables.contains;\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.get;\nimport static com.google.common.collect.Iterables.tryFind;\nimport static java.lang.Math.round;\nimport static java.lang.String.format;\nimport static org.jclouds.compute.util.ComputeServiceUtils.getCores;\nimport static org.jclouds.compute.util.ComputeServiceUtils.getSpace;\nimport static org.jclouds.softlayer.reference.SoftLayerConstants.PROPERTY_SOFTLAYER_VIRTUALGUEST_ACTIVE_TRANSACTIONS_DELAY;\nimport static org.jclouds.softlayer.reference.SoftLayerConstants.PROPERTY_SOFTLAYER_VIRTUALGUEST_LOGIN_DETAILS_DELAY;\nimport static org.jclouds.util.Predicates2.retry;\nimport java.util.Comparator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.TimeUnit;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Inject;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.ComputeServiceAdapter;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.HardwareBuilder;\nimport org.jclouds.compute.domain.Processor;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.domain.Volume;\nimport org.jclouds.compute.domain.Volume.Type;\nimport org.jclouds.compute.domain.internal.VolumeImpl;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.softlayer.SoftLayerApi;\nimport org.jclouds.softlayer.compute.options.SoftLayerTemplateOptions;\nimport org.jclouds.softlayer.domain.ContainerVirtualGuestConfiguration;\nimport org.jclouds.softlayer.domain.Datacenter;\nimport org.jclouds.softlayer.domain.NetworkVlan;\nimport org.jclouds.softlayer.domain.OperatingSystem;\nimport org.jclouds.softlayer.domain.Password;\nimport org.jclouds.softlayer.domain.SecuritySshKey;\nimport org.jclouds.softlayer.domain.SoftwareDescription;\nimport org.jclouds.softlayer.domain.SoftwareLicense;\nimport org.jclouds.softlayer.domain.VirtualDiskImage;\nimport org.jclouds.softlayer.domain.VirtualDiskImageSoftware;\nimport org.jclouds.softlayer.domain.VirtualGuest;\nimport org.jclouds.softlayer.domain.VirtualGuestAttribute;\nimport org.jclouds.softlayer.domain.VirtualGuestBlockDevice;\nimport org.jclouds.softlayer.domain.VirtualGuestBlockDeviceTemplate;\nimport org.jclouds.softlayer.domain.VirtualGuestBlockDeviceTemplateGroup;\nimport org.jclouds.softlayer.domain.VirtualGuestNetworkComponent;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Stopwatch;\nimport com.google.common.base.Strings;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ComparisonChain;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\nimport com.google.common.collect.ImmutableSortedSet;\nimport com.google.common.collect.Sets;\n\n/**\n * defines the connection between the {@link SoftLayerApi} implementation and\n * the jclouds {@link org.jclouds.compute.ComputeService}\n *\n */\n@Singleton\npublic class SoftLayerComputeServiceAdapter implements\n      ComputeServiceAdapter<VirtualGuest, Hardware, OperatingSystem, Datacenter> {\n\n   private static final String USER_META_NOTES = \"notes\";\n   private static final int USER_META_NOTES_MAX_LENGTH = 1000;\n   private static final String BOOTABLE_DEVICE = \"0\";\n   public static final String DEFAULT_DISK_TYPE = \"LOCAL\";\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   private final SoftLayerApi api;\n   private final Supplier<ContainerVirtualGuestConfiguration> createObjectOptionsSupplier;\n   private final Predicate<VirtualGuest> loginDetailsTester;\n   private final long guestLoginDelay;\n   private final long activeTransactionsDelay;\n\n   @Inject\n   public SoftLayerComputeServiceAdapter(SoftLayerApi api,\n         VirtualGuestHasLoginDetailsPresent virtualGuestHasLoginDetailsPresent,\n         @Memoized Supplier<ContainerVirtualGuestConfiguration> createObjectOptionsSupplier,\n         @Named(PROPERTY_SOFTLAYER_VIRTUALGUEST_LOGIN_DETAILS_DELAY) long guestLoginDelay,\n         @Named(PROPERTY_SOFTLAYER_VIRTUALGUEST_ACTIVE_TRANSACTIONS_DELAY) long activeTransactionsDelay) {\n      this.api = checkNotNull(api, \"api\");\n      this.guestLoginDelay = guestLoginDelay;\n      this.activeTransactionsDelay = activeTransactionsDelay;\n      this.createObjectOptionsSupplier = checkNotNull(createObjectOptionsSupplier, \"createObjectOptionsSupplier\");\n      checkArgument(guestLoginDelay > 500, \"guestOrderDelay must be in milliseconds and greater than 500\");\n      this.loginDetailsTester = retry(virtualGuestHasLoginDetailsPresent, guestLoginDelay);\n   }\n\n   @Override\n   public NodeAndInitialCredentials<VirtualGuest> createNodeWithGroupEncodedIntoName(String group, String name,\n         Template template) {\n      checkNotNull(template, \"template was null\");\n      checkNotNull(template.getOptions(), \"template options was null\");\n      checkArgument(template.getOptions().getClass().isAssignableFrom(SoftLayerTemplateOptions.class),\n              \"options class %s should have been assignable from SoftLayerTemplateOptions\",\n              template.getOptions().getClass());\n\n      SoftLayerTemplateOptions templateOptions = template.getOptions().as(SoftLayerTemplateOptions.class);\n      String domainName = templateOptions.getDomainName();\n      String diskType = templateOptions.getDiskType() == null ? DEFAULT_DISK_TYPE : templateOptions.getDiskType();\n      boolean hourlyBillingFlag = templateOptions.isHourlyBillingFlag()  == null ? true : templateOptions.isHourlyBillingFlag();\n      Integer portSpeed = templateOptions.getPortSpeed();\n      Set<VirtualGuestNetworkComponent> networkComponents = portSpeed != null ?\n              ImmutableSet.of(VirtualGuestNetworkComponent.builder().speed(portSpeed).build()) :\n              ImmutableSet.<VirtualGuestNetworkComponent>of();\n      final Datacenter datacenter = Datacenter.builder().name(template.getLocation().getId()).build();\n      final String imageId = template.getImage().getId();\n      int cores = (int) template.getHardware().getProcessors().get(0).getCores();\n      String notes = getNotes(templateOptions);\n\n      VirtualGuest.Builder<?> virtualGuestBuilder = VirtualGuest.builder()\n              .domain(domainName)\n              .hostname(name)\n              .hourlyBillingFlag(hourlyBillingFlag)\n              .startCpus(cores)\n              .maxMemory(template.getHardware().getRam())\n              .datacenter(datacenter)\n              .localDiskFlag(isLocalDisk(diskType))\n              .networkComponents(networkComponents);\n\n      // set operating system or blockDeviceTemplateGroup\n      Optional<OperatingSystem> optionalOperatingSystem = tryExtractOperatingSystemFrom(imageId);\n      if (optionalOperatingSystem.isPresent()) {\n         virtualGuestBuilder.operatingSystem(optionalOperatingSystem.get());\n      // the imageId specified is an id of a public/private/flex image\n      } else {\n         VirtualGuestBlockDeviceTemplateGroup blockDeviceTemplateGroup = VirtualGuestBlockDeviceTemplateGroup\n                 .builder().globalIdentifier(imageId).build();\n         virtualGuestBuilder.blockDeviceTemplateGroup(blockDeviceTemplateGroup);\n      }\n      // set multi-disks\n      if (!templateOptions.getBlockDevices().isEmpty()) {\n         List<VirtualGuestBlockDevice> blockDevices = getBlockDevices(templateOptions.getBlockDevices(), diskType);\n         virtualGuestBuilder.blockDevices(blockDevices);\n      }\n      // set dedicatedAccountHostOnlyFlag\n      if (templateOptions.isDedicatedAccountHostOnlyFlag() != null) {\n         virtualGuestBuilder.dedicatedAccountHostOnly(templateOptions.isDedicatedAccountHostOnlyFlag());\n      }\n      // set privateNetworkOnlyFlag\n      if (templateOptions.isPrivateNetworkOnlyFlag() != null) {\n         virtualGuestBuilder.privateNetworkOnlyFlag(templateOptions.isPrivateNetworkOnlyFlag());\n      }\n      // set primaryNetworkComponent.networkVlan.id\n      if (templateOptions.getPrimaryNetworkComponentNetworkVlanId() != null) {\n         int primaryNetworkComponentNetworkVlanId = templateOptions.getPrimaryNetworkComponentNetworkVlanId();\n         virtualGuestBuilder.primaryNetworkComponent(\n                 VirtualGuestNetworkComponent.builder()\n                         .networkVlan(NetworkVlan.builder().id(primaryNetworkComponentNetworkVlanId).build())\n                         .build());\n      }\n      // set primaryBackendNetworkComponent.networkVlan.id\n      if (templateOptions.getPrimaryBackendNetworkComponentNetworkVlanId() != null) {\n         int primaryBackendNetworkComponentNetworkVlanId = templateOptions.getPrimaryBackendNetworkComponentNetworkVlanId();\n         virtualGuestBuilder.primaryBackendNetworkComponent(\n                 VirtualGuestNetworkComponent.builder()\n                         .networkVlan(NetworkVlan.builder().id(primaryBackendNetworkComponentNetworkVlanId).build())\n                         .build());\n      }\n      // set postInstallScriptUri\n      if (templateOptions.getPostInstallScriptUri() != null) {\n         // Specifies the uri location of the script to be downloaded and run after installation is complete.\n         virtualGuestBuilder.postInstallScriptUri(templateOptions.getPostInstallScriptUri());\n      }\n      // set userData\n      if (templateOptions.getUserData() != null) {\n         virtualGuestBuilder.virtualGuestAttribute(VirtualGuestAttribute.builder().value(templateOptions.getUserData()).build());\n      }\n      // set sshKeys\n      if (!templateOptions.getSshKeys().isEmpty()) {\n         Set<SecuritySshKey> sshKeys = Sets.newHashSet();\n         for (int sshKeyId : templateOptions.getSshKeys()) {\n            sshKeys.add(SecuritySshKey.builder().id(sshKeyId).build());\n         }\n         virtualGuestBuilder.sshKeys(sshKeys);\n      }\n\n      VirtualGuest virtualGuest = virtualGuestBuilder.build();\n      logger.debug(\">> creating new VirtualGuest(%s)\", virtualGuest);\n      VirtualGuest result = api.getVirtualGuestApi().createVirtualGuest(virtualGuest);\n      logger.trace(\"<< VirtualGuest(%s)\", result.getId());\n\n      // tags\n      if (!templateOptions.getTags().isEmpty()) {\n         api.getVirtualGuestApi().setTags(result.getId(), templateOptions.getTags());\n      }\n\n      // notes\n      if (!Strings.isNullOrEmpty(notes)) {\n         api.getVirtualGuestApi().setNotes(result.getId(), notes);\n      }\n\n      logger.debug(\">> awaiting login details for virtualGuest(%s)\", result.getId());\n      boolean orderInSystem = loginDetailsTester.apply(result);\n      logger.trace(\"<< VirtualGuest(%s) complete(%s)\", result.getId(), orderInSystem);\n\n      if (!orderInSystem) {\n         logger.warn(\"VirtualGuest(%s) doesn't have login details within %sms so it will be destroyed.\", result,\n              Long.toString(guestLoginDelay));\n         api.getVirtualGuestApi().deleteVirtualGuest(result.getId());\n         throw new IllegalStateException(format(\"VirtualGuest(%s) is being destroyed as it doesn't have login details\" +\n                 \" after %sms. Please, try by increasing `jclouds.softlayer.virtualguest.login_details_delay` and \" +\n                 \" try again\", result, Long.toString(guestLoginDelay)));\n      }\n      result = api.getVirtualGuestApi().getVirtualGuest(result.getId());\n      Password pwd = get(result.getOperatingSystem().getPasswords(), 0);\n      return new NodeAndInitialCredentials<VirtualGuest>(result, result.getId() + \"\",\n              LoginCredentials.builder().user(pwd.getUsername()).password(pwd.getPassword()).build());\n   }\n\n   private String getNotes(SoftLayerTemplateOptions templateOptions) {\n      String notes = null;\n      Map<String, String> meta = templateOptions.getUserMetadata();\n      if (meta != null) {\n         notes = meta.get(USER_META_NOTES);\n         if (!Strings.isNullOrEmpty(notes)) {\n            checkArgument(notes.length() <= USER_META_NOTES_MAX_LENGTH, \"'notes' property in user metadata should be long at most \" + USER_META_NOTES_MAX_LENGTH + \" characters.\");\n         }\n      }\n      return notes;\n   }\n\n   @Override\n   public Iterable<Hardware> listHardwareProfiles() {\n      ContainerVirtualGuestConfiguration virtualGuestConfiguration = createObjectOptionsSupplier.get();\n      Builder<Hardware> hardware = ImmutableSortedSet.orderedBy(new Comparator<Hardware>() {\n         @Override\n         public int compare(Hardware h1, Hardware h2) {\n            List<? extends Volume> volumes1 = h1.getVolumes();\n            List<? extends Volume> volumes2 = h2.getVolumes();\n            ComparisonChain comparisonChain = ComparisonChain.start().compare(getCores(h1), getCores(h2))\n                    .compare(h1.getRam(), h2.getRam())\n                    .compare(getSpace(h1), getSpace(h2))\n                    .compare(getBootableDeviceType(h1), getBootableDeviceType(h2));\n            if (!volumes1.isEmpty() && !volumes2.isEmpty() && volumes1.size() == volumes2.size()) {\n               for (int i = 0; i < volumes1.size(); i++) {\n                  comparisonChain = comparisonChain.compare(volumes1.get(i).getType(), volumes2.get(i).getType());\n               }\n            }\n            return comparisonChain.result();\n         }\n      });\n      for (VirtualGuestBlockDevice blockDevice : virtualGuestConfiguration.getVirtualGuestBlockDevices()) {\n         float capacity = blockDevice.getVirtualDiskImage().getCapacity();\n         Type type = blockDevice.getVirtualGuest().isLocalDiskFlag() ? Type.LOCAL : Type.SAN;\n         if (blockDevice.getDevice().equals(BOOTABLE_DEVICE)) {\n            for (Integer cpus : virtualGuestConfiguration.getCpusOfProcessors()) {\n               for (Integer memory : virtualGuestConfiguration.getMemories()) {\n                  String id = format(\"cpu=%s,memory=%s,disk=%s,type=%s\", cpus, memory, round(capacity), type);\n                  hardware.add(new HardwareBuilder()\n                          .ids(id)\n                          .ram(memory)\n                          .processors(ImmutableList.of(new Processor(cpus, 2)))\n                          .hypervisor(\"XenServer\")\n                          .volumes(ImmutableList.<Volume>of(\n                                  new VolumeImpl(blockDevice.getId() + \"\",\n                                          type,\n                                          capacity,\n                                          blockDevice.getDevice(),\n                                          blockDevice.getBootableFlag() == 1,\n                                          true)))\n                          .build());\n               }\n            }\n         }\n      }\n      return hardware.build();\n   }\n\n   @Override\n   public Set<OperatingSystem> listImages() {\n      Set<OperatingSystem> result = Sets.newHashSet();\n      // add allObjects filtered by the available OS\n      Set<SoftwareDescription> allObjects = api.getSoftwareDescriptionApi().getAllObjects();\n      for (OperatingSystem os : createObjectOptionsSupplier.get().getVirtualGuestOperatingSystems()) {\n         result.addAll(FluentIterable.from(allObjects)\n                 .filter(new IsOperatingSystem())\n                 .filter(new HasSameOsReferenceCode(os.getOperatingSystemReferenceCode()))\n                 .transform(new SoftwareDescriptionToOperatingSystem(os.getId()))\n                 .toSet());\n      }\n      return result;\n   }\n\n   @Override\n   public OperatingSystem getImage(final String id) {\n      // look for imageId among stock images\n      Optional<OperatingSystem> operatingSystemOptional = tryFind(listImages(),\n              new Predicate<OperatingSystem>() {\n                 @Override\n                 public boolean apply(OperatingSystem input) {\n                    return input.getId().equals(id);\n                 }\n              }\n      );\n      if (operatingSystemOptional.isPresent()) return operatingSystemOptional.get();\n\n      // if imageId is not a stock image, it searches among private and public images\n      Stopwatch stopwatch = Stopwatch.createStarted();\n      VirtualGuestBlockDeviceTemplateGroup image = api.getVirtualGuestBlockDeviceTemplateGroupApi().getObject(id);\n      logger.trace(\"<< Image(%s) found in (%s)\", id, stopwatch.elapsed(TimeUnit.SECONDS));\n      return tryExtractOperatingSystemFrom(image).orNull();\n   }\n\n   @Override\n   public Iterable<VirtualGuest> listNodes() {\n      return api.getAccountApi().listVirtualGuests();\n   }\n\n   @Override\n   public Iterable<VirtualGuest> listNodesByIds(final Iterable<String> ids) {\n      return filter(listNodes(), new Predicate<VirtualGuest>() {\n\n         @Override\n         public boolean apply(VirtualGuest server) {\n            return contains(ids, server.getId());\n         }\n      });\n   }\n\n   @Override\n   public Iterable<Datacenter> listLocations() {\n      Set<Datacenter> result = Sets.newHashSet();\n      Set<Datacenter> unfiltered = api.getDatacenterApi().listDatacenters();\n      Set<Datacenter> datacenterAvailable = createObjectOptionsSupplier.get().getVirtualGuestDatacenters();\n      for (Datacenter datacenter : datacenterAvailable) {\n         final String datacenterName = datacenter.getName();\n         result.addAll(Sets.newHashSet(filter(unfiltered,\n                 new Predicate<Datacenter>() {\n                    @Override\n                    public boolean apply(Datacenter input) {\n                       return input.getName().equals(datacenterName);\n                    }\n                 })));\n      }\n      return result;\n   }\n\n   @Override\n   public VirtualGuest getNode(String id) {\n      long serverId = Long.parseLong(id);\n      return api.getVirtualGuestApi().getVirtualGuest(serverId);\n   }\n\n   @Override\n   public void destroyNode(String id) {\n      VirtualGuest guest = getNode(id);\n      if (guest == null) return;\n      logger.debug(\">> awaiting virtualGuest(%s) without active transactions\", guest.getId());\n      checkState(retry(new Predicate<VirtualGuest>() {\n         public boolean apply(VirtualGuest guest) {\n               return getNode(guest.getId() + \"\").getActiveTransactionCount() == 0;\n         }\n      }, activeTransactionsDelay).apply(guest), \"%s still has active transactions!\", guest);\n      logger.debug(\">> canceling virtualGuest with globalIdentifier(%s)\", id);\n      checkState(api.getVirtualGuestApi().deleteVirtualGuest(guest.getId()), \"server(%s) still there after deleting!?\", id);\n   }\n\n   @Override\n   public void rebootNode(String id) {\n      api.getVirtualGuestApi().rebootHardVirtualGuest(Long.parseLong(id));\n   }\n\n   @Override\n   public void resumeNode(String id) {\n      api.getVirtualGuestApi().resumeVirtualGuest(Long.parseLong(id));\n   }\n\n   @Override\n   public void suspendNode(String id) {\n      api.getVirtualGuestApi().pauseVirtualGuest(Long.parseLong(id));\n   }\n\n   /**\n    * This method will deliberately skip device position 1 as it is reserved to SWAP\n    * @param blockDeviceCapacities list of blockDevices to be attached\n    * @param diskType disks can be LOCAL or SAN\n    * @return\n    */\n   private static List<VirtualGuestBlockDevice> getBlockDevices(List<Integer> blockDeviceCapacities, String diskType) {\n      ImmutableList.Builder<VirtualGuestBlockDevice> blockDevicesBuilder = ImmutableList.builder();\n      int devicePosition = 0;\n      for (int i = 0; i < blockDeviceCapacities.size(); i++) {\n         if (i > 0) { devicePosition = i + 1; }\n         blockDevicesBuilder.add(VirtualGuestBlockDevice.builder()\n                 .device(devicePosition + \"\")\n                 .diskImage(VirtualDiskImage.builder()\n                         .capacity(blockDeviceCapacities.get(i))\n                         .typeId(Type.valueOf(diskType).ordinal())\n                         .build())\n                 .build());\n      }\n      return blockDevicesBuilder.build();\n   }\n\n   private static boolean isLocalDisk(String diskType) {\n      return diskType.equalsIgnoreCase(Type.LOCAL.name());\n   }\n\n   private static int getBootableDeviceType(Hardware hardware) {\n      List<? extends Volume> volumes = hardware.getVolumes();\n      Optional<? extends Volume> optionalBootableVolume = tryFind(volumes, new Predicate<Volume>() {\n         @Override\n         public boolean apply(Volume volume) {\n            return volume.getDevice().equals(BOOTABLE_DEVICE);\n         }\n      });\n      if (!optionalBootableVolume.isPresent()) {\n         return Type.LOCAL.ordinal();\n      }\n      return optionalBootableVolume.get().getType().ordinal();\n   }\n\n   private Optional<OperatingSystem> tryExtractOperatingSystemFrom(final String imageId) {\n      Set<OperatingSystem> operatingSystemsAvailable = createObjectOptionsSupplier.get().getVirtualGuestOperatingSystems();\n      return FluentIterable.from(operatingSystemsAvailable)\n              .filter(new Predicate<OperatingSystem>() {\n                 @Override\n                 public boolean apply(OperatingSystem input) {\n                    if (input == null) return false;\n                    return input.getId().contains(imageId);\n                 }\n              })\n              .first();\n   }\n\n   private Optional<OperatingSystem> tryExtractOperatingSystemFrom(VirtualGuestBlockDeviceTemplateGroup image) {\n      if (image.getGlobalIdentifier() == null) return Optional.absent();\n      return FluentIterable.from(image.getChildren())\n              .transformAndConcat(new BlockDeviceTemplateGroupToBlockDeviceTemplateIterable())\n              .filter(new IsBootableDevice())\n              .transformAndConcat(new BlockDeviceTemplateToDiskImageSoftware())\n              .transform(new DiskImageSoftwareToSoftwareDescription())\n              .filter(new IsOperatingSystem())\n              .transform(new SoftwareDescriptionToOperatingSystem(image.getGlobalIdentifier()))\n              .first();\n   }\n\n   public static class VirtualGuestHasLoginDetailsPresent implements Predicate<VirtualGuest> {\n      private final SoftLayerApi client;\n\n      @Inject\n      public VirtualGuestHasLoginDetailsPresent(SoftLayerApi client) {\n         this.client = checkNotNull(client, \"client was null\");\n      }\n\n      @Override\n      public boolean apply(VirtualGuest guest) {\n         checkNotNull(guest, \"virtual guest was null\");\n\n         VirtualGuest virtualGuest = client.getVirtualGuestApi().getVirtualGuest(guest.getId());\n         boolean hasBackendIp = virtualGuest.getPrimaryBackendIpAddress() != null;\n         boolean hasPrimaryIp = virtualGuest.getPrimaryIpAddress() != null;\n         boolean hasPasswords = virtualGuest.getOperatingSystem() != null\n                 && !virtualGuest.getOperatingSystem().getPasswords().isEmpty();\n\n         return virtualGuest.isPrivateNetworkOnly() ? hasBackendIp && hasPasswords : hasBackendIp && hasPrimaryIp && hasPasswords;\n      }\n   }\n\n   private static class SoftwareDescriptionToOperatingSystem implements Function<SoftwareDescription, OperatingSystem> {\n      private final String osId;\n\n      public SoftwareDescriptionToOperatingSystem(String osId) {\n         this.osId = osId;\n      }\n\n      @Override\n      public OperatingSystem apply(SoftwareDescription input) {\n         return OperatingSystem.builder().id(osId)\n                                         .softwareLicense(SoftwareLicense.builder().softwareDescription(input).build())\n                                         .operatingSystemReferenceCode(input.getReferenceCode())\n                                         .build();\n      }\n   }\n\n   private static class IsBootableDevice implements Predicate<VirtualGuestBlockDeviceTemplate> {\n      @Override\n      public boolean apply(VirtualGuestBlockDeviceTemplate blockDeviceTemplate) {\n         return blockDeviceTemplate.getDevice().equals(BOOTABLE_DEVICE);\n      }\n   }\n\n   private static class BlockDeviceTemplateGroupToBlockDeviceTemplateIterable implements Function<VirtualGuestBlockDeviceTemplateGroup,\n                         Iterable<VirtualGuestBlockDeviceTemplate>> {\n      @Override\n      public Iterable<VirtualGuestBlockDeviceTemplate> apply(VirtualGuestBlockDeviceTemplateGroup input) {\n         return input.getBlockDevices();\n      }\n   }\n\n   private static class BlockDeviceTemplateToDiskImageSoftware implements Function<VirtualGuestBlockDeviceTemplate, Iterable<VirtualDiskImageSoftware>> {\n      @Override\n      public Iterable<VirtualDiskImageSoftware> apply(VirtualGuestBlockDeviceTemplate bootableDevice) {\n         return bootableDevice.getDiskImage().getSoftwareReferences();\n      }\n   }\n\n   private static class DiskImageSoftwareToSoftwareDescription implements Function<VirtualDiskImageSoftware, SoftwareDescription> {\n      @Override\n      public SoftwareDescription apply(VirtualDiskImageSoftware software) {\n         return software.getSoftwareDescription();\n      }\n   }\n\n   private static class HasSameOsReferenceCode implements Predicate<SoftwareDescription> {\n      private final String osReferenceCode;\n\n      public HasSameOsReferenceCode(String osReferenceCode) {\n         this.osReferenceCode = osReferenceCode;\n      }\n\n      @Override\n      public boolean apply(SoftwareDescription input) {\n         return input.getReferenceCode().equals(osReferenceCode);\n      }\n   }\n\n   private static class IsOperatingSystem implements Predicate<SoftwareDescription> {\n      @Override\n      public boolean apply(SoftwareDescription softwareDescription) {\n         // operatingSystem is set to '1' if this Software Description describes an Operating System.\n         return softwareDescription.getOperatingSystem() == 1;\n      }\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/config/SoftLayerHttpApiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.config;\n\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpRetryHandler;\nimport org.jclouds.http.annotation.ClientError;\nimport org.jclouds.http.annotation.Redirection;\nimport org.jclouds.http.annotation.ServerError;\nimport org.jclouds.http.handlers.BackoffLimitedRetryHandler;\nimport org.jclouds.location.config.LocationModule;\nimport org.jclouds.location.suppliers.ImplicitLocationSupplier;\nimport org.jclouds.location.suppliers.implicit.OnlyLocationOrFirstZone;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.config.HttpApiModule;\nimport org.jclouds.softlayer.SoftLayerApi;\nimport org.jclouds.softlayer.handlers.SoftLayerErrorHandler;\n\nimport com.google.inject.Scopes;\n\n/**\n * Configures the SoftLayer connection.\n */\n@ConfiguresHttpApi\npublic class SoftLayerHttpApiModule extends HttpApiModule<SoftLayerApi> {\n\n   @Override\n   protected void configure() {\n      install(new SoftLayerParserModule());\n      super.configure();\n   }\n\n   @Override\n   protected void bindErrorHandlers() {\n      bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(SoftLayerErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(SoftLayerErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(SoftLayerErrorHandler.class);\n   }\n\n   @Override\n   protected void bindRetryHandlers() {\n      bind(HttpRetryHandler.class).annotatedWith(ClientError.class).to(BackoffLimitedRetryHandler.class);\n   }\n\n   @Override\n   protected void installLocations() {\n      install(new LocationModule());\n      bind(ImplicitLocationSupplier.class).to(OnlyLocationOrFirstZone.class).in(Scopes.SINGLETON);\n   }\n\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/config/SoftLayerParserModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.config;\n\nimport org.jclouds.json.config.GsonModule.DateAdapter;\nimport org.jclouds.json.config.GsonModule.Iso8601DateAdapter;\n\nimport com.google.inject.AbstractModule;\n\npublic class SoftLayerParserModule extends AbstractModule {\n\n   @Override\n   protected void configure() {\n      bind(DateAdapter.class).to(Iso8601DateAdapter.class);\n   }\n\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/domain/Address.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Strings.emptyToNull;\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.inject.name.Named;\n\n/**\n * Class Address\n *\n * @see <a href= \"http://sldn.softlayer.com/reference/datatypes/SoftLayer_Account_Address\"/>\n */\npublic class Address {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromAddress(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>>  {\n      protected abstract T self();\n\n      protected int id;\n      protected String country;\n      protected String state;\n      protected String description;\n      protected int accountId;\n      @Named(\"address1\")\n      protected String address;\n      protected String city;\n      protected String contactName;\n      protected int isActive;\n      protected int locationId;\n      protected String postalCode;\n\n      /**\n       * @see Address#getId()\n       */\n      public T id(int id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see Address#getCountry()\n       */\n      public T country(String country) {\n         this.country = country;\n         return self();\n      }\n\n      /**\n       * @see Address#getState()\n       */\n      public T state(String state) {\n         this.state = state;\n         return self();\n      }\n\n      /**\n       * @see Address#getDescription()\n       */\n      public T description(String description) {\n         this.description = description;\n         return self();\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.Address#getAccountId()\n       */\n      public T accountId(int accountId) {\n         this.accountId = accountId;\n         return self();\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.Address#getAddress1()\n       */\n      public T address(String address) {\n         this.address = address;\n         return self();\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.Address#getCity()\n       */\n      public T city(String city) {\n         this.city = city;\n         return self();\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.Address#getContactName()\n       */\n      public T contactName(String contactName) {\n         this.contactName = contactName;\n         return self();\n      }\n\n      /**\n       * @see Address#isActive()\n       */\n      public T isActive(int isActive) {\n         this.isActive = isActive;\n         return self();\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.Address#getLocationId()\n       */\n      public T locationId(int locationId) {\n         this.locationId = locationId;\n         return self();\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.Address#getPostalCode()\n       */\n      public T postalCode(String postalCode) {\n         this.postalCode = postalCode;\n         return self();\n      }\n\n      public Address build() {\n         return new Address(id, country, state, description, accountId, address, city, contactName, isActive,\n                 locationId, postalCode);\n      }\n\n      public T fromAddress(Address in) {\n         return this\n               .id(in.getId())\n               .country(in.getCountry())\n               .state(in.getState())\n               .description(in.getDescription())\n               .accountId(in.getAccountId())\n               .address(in.getAddress1())\n               .city(in.getCity())\n               .contactName(in.getContactName())\n               .isActive(in.isActive())\n               .locationId(in.getLocationId())\n               .postalCode(in.getPostalCode());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final int id;\n   private final String country;\n   private final String state;\n   private final String description;\n   private final int accountId;\n   @Named(\"address1\")\n   private final String address;\n   private final String city;\n   private final String contactName;\n   private final int isActive;\n   private final int locationId;\n   private final String postalCode;\n\n   @ConstructorProperties({\n         \"id\", \"country\", \"state\", \"description\", \"accountId\", \"address1\", \"city\", \"contactName\", \"isActive\",\n           \"locationId\", \"postalCode\"\n   })\n   protected Address(int id, String country, @Nullable String state, @Nullable String description, int accountId,\n                     @Nullable String address, @Nullable String city, @Nullable String contactName,\n                     int isActive, int locationId, @Nullable String postalCode) {\n      this.id = id;\n      this.accountId = accountId;\n      this.address = address;\n      this.city = city;\n      this.contactName = contactName;\n      this.isActive = isActive;\n      this.locationId = locationId;\n      this.postalCode = postalCode;\n      this.country = checkNotNull(emptyToNull(country), \"country cannot be null or empty:\" + country);\n      this.state = state;\n      this.description = description;\n   }\n\n   /**\n    * @return The unique id of the address.\n    */\n   public int getId() {\n      return this.id;\n   }\n\n   /**\n    * @return The country of the address.\n    */\n   public String getCountry() {\n      return this.country;\n   }\n\n   /**\n    * @return The state of the address.\n    */\n   @Nullable\n   public String getState() {\n      return this.state;\n   }\n\n   /**\n    * @return The description of the address.\n    */\n   @Nullable\n   public String getDescription() {\n      return this.description;\n   }\n\n   /**\n    * @return The id of the account.\n    */\n   public int getAccountId() {\n      return accountId;\n   }\n\n   /**\n    * @return The value of the address.\n    */\n   @Nullable\n   public String getAddress1() {\n      return address;\n   }\n\n   /**\n    * @return The name of the city.\n    */\n   @Nullable\n   public String getCity() {\n      return city;\n   }\n\n   /**\n    * @return The name of the contact.\n    */\n   @Nullable\n   public String getContactName() {\n      return contactName;\n   }\n\n   /**\n    * @return The name of the contact.\n    */\n   public int isActive() {\n      return isActive;\n   }\n\n   /**\n    * @return The id of the location.\n    */\n   public int getLocationId() {\n      return locationId;\n   }\n\n   /**\n    * @return The postal code of the address.\n    */\n   @Nullable\n   public String getPostalCode() {\n      return postalCode;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Address that = Address.class.cast(obj);\n      return Objects.equal(this.id, that.id);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this)\n              .add(\"id\", id)\n              .add(\"country\", country)\n              .add(\"state\", state)\n              .add(\"description\", description)\n              .add(\"accountId\", accountId)\n              .add(\"address\", address)\n              .add(\"city\", city)\n              .add(\"contactName\", contactName)\n              .add(\"isActive\", isActive)\n              .add(\"locationId\", locationId)\n              .add(\"postalCode\", postalCode)\n              .toString();\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/domain/ContainerVirtualGuestConfiguration.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.domain;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Predicates;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Sets;\n\nimport java.beans.ConstructorProperties;\nimport java.util.Set;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\n/**\n * @see <a href= \"http://sldn.softlayer.com/reference/datatypes/SoftLayer_Container_Virtual_Guest_Configuration\"/\n * *\n */\npublic class ContainerVirtualGuestConfiguration {\n\n   public static final String SWAP_DEVICE = \"1\";\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().fromContainerVirtualGuestConfiguration(this);\n   }\n\n   public static class Builder {\n      protected Set<ContainerVirtualGuestConfigurationOption> blockDevices;\n      protected Set<ContainerVirtualGuestConfigurationOption> datacenters;\n      protected Set<ContainerVirtualGuestConfigurationOption> memory;\n      protected Set<ContainerVirtualGuestConfigurationOption> networkComponents;\n      protected Set<ContainerVirtualGuestConfigurationOption> operatingSystems;\n      protected Set<ContainerVirtualGuestConfigurationOption> processors;\n\n      public Builder blockDevices(Set<ContainerVirtualGuestConfigurationOption> blockDevices) {\n         this.blockDevices = ImmutableSet.copyOf(checkNotNull(blockDevices, \"blockDevices\"));\n         return this;\n      }\n\n      public Builder blockDevices(ContainerVirtualGuestConfigurationOption... in) {\n         return blockDevices(ImmutableSet.copyOf(in));\n      }\n\n      public Builder datacenters(Set<ContainerVirtualGuestConfigurationOption> datacenters) {\n         this.datacenters = ImmutableSet.copyOf(checkNotNull(datacenters, \"datacenters\"));\n         return this;\n      }\n\n      public Builder datacenters(ContainerVirtualGuestConfigurationOption... in) {\n         return datacenters(ImmutableSet.copyOf(in));\n      }\n\n      public Builder memory(Set<ContainerVirtualGuestConfigurationOption> memory) {\n         this.memory = ImmutableSet.copyOf(checkNotNull(memory, \"memory\"));\n         return this;\n      }\n\n      public Builder memory(ContainerVirtualGuestConfigurationOption... in) {\n         return memory(ImmutableSet.copyOf(in));\n      }\n\n      public Builder networkComponents(Set<ContainerVirtualGuestConfigurationOption> networkComponents) {\n         this.networkComponents = ImmutableSet.copyOf(checkNotNull(networkComponents, \"networkComponents\"));\n         return this;\n      }\n\n      public Builder networkComponents(ContainerVirtualGuestConfigurationOption... in) {\n         return networkComponents(ImmutableSet.copyOf(in));\n      }\n\n      public Builder operatingSystems(Set<ContainerVirtualGuestConfigurationOption> operatingSystems) {\n         this.operatingSystems = ImmutableSet.copyOf(checkNotNull(operatingSystems, \"operatingSystems\"));\n         return this;\n      }\n\n      public Builder operatingSystems(ContainerVirtualGuestConfigurationOption... in) {\n         return operatingSystems(ImmutableSet.copyOf(in));\n      }\n\n      public Builder processors(Set<ContainerVirtualGuestConfigurationOption> processors) {\n         this.processors = ImmutableSet.copyOf(checkNotNull(processors, \"processors\"));\n         return this;\n      }\n\n      public Builder processors(ContainerVirtualGuestConfigurationOption... in) {\n         return processors(ImmutableSet.copyOf(in));\n      }\n\n      public ContainerVirtualGuestConfiguration build() {\n         return new ContainerVirtualGuestConfiguration(blockDevices, datacenters, memory, networkComponents,\n                 operatingSystems, processors);\n      }\n\n      public Builder fromContainerVirtualGuestConfiguration(ContainerVirtualGuestConfiguration in) {\n         return this\n                 .blockDevices(in.getBlockDevices())\n                 .datacenters(in.getDatacenters())\n                 .memory(in.getMemory())\n                 .networkComponents(in.getNetworkComponents())\n                 .operatingSystems(in.getOperatingSystems())\n                 .processors(in.getProcessors());\n      }\n   }\n\n   private final Set<ContainerVirtualGuestConfigurationOption> blockDevices;\n   private final Set<ContainerVirtualGuestConfigurationOption> datacenters;\n   private final Set<ContainerVirtualGuestConfigurationOption> memory;\n   private final Set<ContainerVirtualGuestConfigurationOption> networkComponents;\n   private final Set<ContainerVirtualGuestConfigurationOption> operatingSystems;\n   private final Set<ContainerVirtualGuestConfigurationOption> processors;\n\n   @ConstructorProperties({\n           \"blockDevices\", \"datacenters\", \"memory\", \"networkComponents\", \"operatingSystems\", \"processors\"\n   })\n   public ContainerVirtualGuestConfiguration(Set<ContainerVirtualGuestConfigurationOption> blockDevices,\n                                             Set<ContainerVirtualGuestConfigurationOption> datacenters,\n                                             Set<ContainerVirtualGuestConfigurationOption> memory,\n                                             Set<ContainerVirtualGuestConfigurationOption> networkComponents,\n                                             Set<ContainerVirtualGuestConfigurationOption> operatingSystems,\n                                             Set<ContainerVirtualGuestConfigurationOption> processors) {\n      this.blockDevices = checkNotNull(blockDevices, \"blockDevices\");\n      this.datacenters = checkNotNull(datacenters, \"datacenters\");\n      this.memory = checkNotNull(memory, \"memory\");\n      this.networkComponents = checkNotNull(networkComponents, \"networkComponents\");\n      this.operatingSystems = checkNotNull(operatingSystems, \"operatingSystems\");\n      this.processors = checkNotNull(processors, \"processors\");\n   }\n\n   public Set<ContainerVirtualGuestConfigurationOption> getBlockDevices() {\n      return blockDevices;\n   }\n\n   public Set<ContainerVirtualGuestConfigurationOption> getDatacenters() {\n      return datacenters;\n   }\n\n   public Set<ContainerVirtualGuestConfigurationOption> getMemory() {\n      return memory;\n   }\n\n   public Set<ContainerVirtualGuestConfigurationOption> getNetworkComponents() {\n      return networkComponents;\n   }\n\n   public Set<ContainerVirtualGuestConfigurationOption> getOperatingSystems() {\n      return operatingSystems;\n   }\n\n   public Set<ContainerVirtualGuestConfigurationOption> getProcessors() {\n      return processors;\n   }\n\n   public Set<Integer> getCpusOfProcessors() {\n      return Sets.newHashSet(Iterables.transform(processors, new Function<ContainerVirtualGuestConfigurationOption,\n              Integer>() {\n         @Override\n         public Integer apply(ContainerVirtualGuestConfigurationOption input) {\n            return input.getTemplate().getStartCpus();\n         }\n      }));\n   }\n\n   public Set<Integer> getMemories() {\n      return Sets.newHashSet(Iterables.transform(memory, new Function<ContainerVirtualGuestConfigurationOption,\n              Integer>() {\n         @Override\n         public Integer apply(ContainerVirtualGuestConfigurationOption input) {\n            return input.getTemplate().getMaxMemory();\n         }\n      }));\n   }\n\n   public Set<Datacenter> getVirtualGuestDatacenters() {\n      return Sets.newHashSet(Iterables.transform(datacenters, new Function<ContainerVirtualGuestConfigurationOption,\n              Datacenter>() {\n         @Override\n         public Datacenter apply(ContainerVirtualGuestConfigurationOption input) {\n            return input.getTemplate().getDatacenter();\n         }\n      }));\n   }\n\n   public Set<OperatingSystem> getVirtualGuestOperatingSystems() {\n      return Sets.newHashSet(FluentIterable.from(operatingSystems)\n               .transform(new Function<ContainerVirtualGuestConfigurationOption, OperatingSystem>() {\n         @Override\n         public OperatingSystem apply(ContainerVirtualGuestConfigurationOption input) {\n            String operatingSystemReferenceCode = input.getTemplate().getOperatingSystemReferenceCode();\n            if (operatingSystemReferenceCode == null) {\n               return null;\n            } else {\n               return OperatingSystem.builder()\n                       .id(operatingSystemReferenceCode)\n                       .operatingSystemReferenceCode(operatingSystemReferenceCode)\n                       .build();\n            }\n         }\n      }).filter(Predicates.notNull()));\n   }\n\n   public Set<VirtualGuestBlockDevice> getVirtualGuestBlockDevices() {\n      Set<VirtualGuestBlockDevice> virtualGuestBlockDevices = Sets.newHashSet();\n      for (final ContainerVirtualGuestConfigurationOption configurationOption : blockDevices) {\n         virtualGuestBlockDevices.addAll(FluentIterable.from(configurationOption.getTemplate().getVirtualGuestBlockDevices())\n                 .filter(new Predicate<VirtualGuestBlockDevice>() {\n                    @Override\n                    public boolean apply(VirtualGuestBlockDevice input) {\n                       return !input.getDevice().equals(SWAP_DEVICE);\n                    }\n                 })\n                 .transform(new Function<VirtualGuestBlockDevice, VirtualGuestBlockDevice>() {\n                    @Override\n                    public VirtualGuestBlockDevice apply(VirtualGuestBlockDevice input) {\n                       return input.toBuilder().guest(configurationOption.getTemplate()).build();\n                    }\n                 })\n                 .toSet());\n      }\n      return virtualGuestBlockDevices;\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o) return true;\n      if (o == null || getClass() != o.getClass()) return false;\n\n      ContainerVirtualGuestConfiguration that = (ContainerVirtualGuestConfiguration) o;\n\n      return Objects.equal(this.blockDevices, that.blockDevices) &&\n              Objects.equal(this.datacenters, that.datacenters) &&\n              Objects.equal(this.memory, that.memory) &&\n              Objects.equal(this.networkComponents, that.networkComponents) &&\n              Objects.equal(this.operatingSystems, that.operatingSystems) &&\n              Objects.equal(this.processors, that.processors);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(blockDevices, datacenters, memory, networkComponents, operatingSystems,\n              processors);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this)\n              .add(\"blockDevices\", blockDevices)\n              .add(\"datacenters\", datacenters)\n              .add(\"memory\", memory)\n              .add(\"networkComponents\", networkComponents)\n              .add(\"operatingSystems\", operatingSystems)\n              .add(\"processors\", processors)\n              .toString();\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/domain/ContainerVirtualGuestConfigurationOption.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.inject.name.Named;\n\n/**\n * @see <a href=\"http://sldn.softlayer.com/reference/datatypes/SoftLayer_Container_Virtual_Guest_Configuration_Option\"/>\n */\npublic class ContainerVirtualGuestConfigurationOption {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().fromContainerVirtualGuestConfigurationOption(this);\n   }\n\n   public static class Builder {\n\n      protected ProductItemPrice productItemPrice;\n      protected VirtualGuest template;\n\n      public Builder productItemPrice(ProductItemPrice productItemPrice) {\n         this.productItemPrice = productItemPrice;\n         return this;\n      }\n\n      public Builder template(VirtualGuest template) {\n         this.template = template;\n         return this;\n      }\n\n      public ContainerVirtualGuestConfigurationOption build() {\n         return new ContainerVirtualGuestConfigurationOption(productItemPrice, template);\n      }\n\n      public Builder fromContainerVirtualGuestConfigurationOption(ContainerVirtualGuestConfigurationOption in) {\n         return this\n                 .productItemPrice(in.getProductItemPrice())\n                 .template(in.getTemplate());\n      }\n   }\n\n   @Named(\"itemPrice\")\n   private final ProductItemPrice productItemPrice;\n   private final VirtualGuest template;\n\n   @ConstructorProperties({\"itemPrice\", \"template\"})\n   public ContainerVirtualGuestConfigurationOption(@Nullable ProductItemPrice productItemPrice,\n                                                   VirtualGuest template) {\n      this.productItemPrice = productItemPrice;\n      this.template = checkNotNull(template, \"template\");\n   }\n\n   public ProductItemPrice getProductItemPrice() {\n      return productItemPrice;\n   }\n\n   public VirtualGuest getTemplate() {\n      return template;\n   }\n\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o) return true;\n      if (o == null || getClass() != o.getClass()) return false;\n\n      ContainerVirtualGuestConfigurationOption that = (ContainerVirtualGuestConfigurationOption) o;\n\n      return Objects.equal(this.productItemPrice, that.productItemPrice) &&\n              Objects.equal(this.template, that.template);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(productItemPrice, template);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this)\n              .add(\"productItemPrice\", productItemPrice)\n              .add(\"template\", template)\n              .toString();\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/domain/Datacenter.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport java.beans.ConstructorProperties;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Class Datacenter\n *\n * @see <a href= \"http://sldn.softlayer.com/reference/datatypes/SoftLayer_Location_Datacenter\"\n/>\n */\npublic class Datacenter {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromDatacenter(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>>  {\n      protected abstract T self();\n\n      protected int id;\n      protected String name;\n      protected String longName;\n      protected Address locationAddress;\n      protected Set<Region> regions = ImmutableSet.of();\n\n      /**\n       * @see Datacenter#getId()\n       */\n      public T id(int id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see Datacenter#getName()\n       */\n      public T name(String name) {\n         this.name = name;\n         return self();\n      }\n\n      /**\n       * @see Datacenter#getLongName()\n       */\n      public T longName(String longName) {\n         this.longName = longName;\n         return self();\n      }\n\n      /**\n       * @see Datacenter#getLocationAddress()\n       */\n      public T locationAddress(Address locationAddress) {\n         this.locationAddress = locationAddress;\n         return self();\n      }\n\n      /**\n       * @see Datacenter#getRegions()\n       */\n      public T regions(Set<Region> regions) {\n         this.regions = ImmutableSet.copyOf(checkNotNull(regions, \"regions\"));\n         return self();\n      }\n\n      public T regions(Region... in) {\n         return regions(ImmutableSet.copyOf(in));\n      }\n\n      public Datacenter build() {\n         return new Datacenter(id, name, longName, locationAddress, regions);\n      }\n\n      public T fromDatacenter(Datacenter in) {\n         return this\n               .id(in.getId())\n               .name(in.getName())\n               .longName(in.getLongName())\n               .locationAddress(in.getLocationAddress())\n               .regions(in.getRegions());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final int id;\n   private final String name;\n   private final String longName;\n   private final Address locationAddress;\n   private final Set<Region> regions;\n\n   @ConstructorProperties({\n         \"id\", \"name\", \"longName\", \"locationAddress\", \"regions\"\n   })\n   protected Datacenter(int id, @Nullable String name, @Nullable String longName, @Nullable Address locationAddress, @Nullable Set<Region> regions) {\n      this.id = id;\n      this.name = name;\n      this.longName = longName;\n      this.locationAddress = locationAddress;\n      this.regions = regions == null ? ImmutableSet.<Region>of() : ImmutableSet.copyOf(regions);\n   }\n\n   /**\n    * @return The unique identifier of a specific location.\n    */\n   public int getId() {\n      return this.id;\n   }\n\n   /**\n    * @return A short location description.\n    */\n   @Nullable\n   public String getName() {\n      return this.name;\n   }\n\n   /**\n    * @return A longer location description.\n    */\n   @Nullable\n   public String getLongName() {\n      return this.longName;\n   }\n\n   /**\n    * @return A location's physical address (optional).\n    */\n   @Nullable\n   public Address getLocationAddress() {\n      return this.locationAddress;\n   }\n\n   /**\n    * A location can be a member of 1 or more regions.\n    * Sometimes the list of regions is empty, for example as a new Datacenter is being added.\n    * The list of regions usually contains one with keyName=FIRST_AVAILABLE which should be ignored.\n    *\n    * @return The regions to which a location belongs.\n    */\n   public Set<Region> getRegions() {\n      return this.regions;\n   }\n\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o) return true;\n      if (o == null || getClass() != o.getClass()) return false;\n\n      Datacenter that = (Datacenter) o;\n\n      return Objects.equal(this.id, that.id) &&\n              Objects.equal(this.name, that.name) &&\n              Objects.equal(this.longName, that.longName) &&\n              Objects.equal(this.locationAddress, that.locationAddress) &&\n              Objects.equal(this.regions, that.regions);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, name, longName, locationAddress, regions);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this)\n              .add(\"id\", id)\n              .add(\"name\", name)\n              .add(\"longName\", longName)\n              .add(\"locationAddress\", locationAddress)\n              .add(\"regions\", regions)\n              .toString();\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/domain/Network.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.domain;\n\nimport com.google.auto.value.AutoValue;\nimport com.google.common.collect.ImmutableList;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport java.util.List;\n\n/**\n * Class Network\n *\n * @see <a href= \"http://sldn.softlayer.com/reference/datatypes/SoftLayer_Network\" />\n */\n\n@AutoValue\npublic abstract class Network {\n\n   public abstract long accountId();\n   public abstract long id();\n   public abstract int cidr();\n   public abstract String networkIdentifier();\n   @Nullable\n   public abstract String name();\n   @Nullable\n   public abstract String notes();\n   @Nullable\n   public abstract List<Subnet> subnets();\n\n   @SerializedNames({\"accountId\", \"id\", \"cidr\", \"networkIdentifier\", \"name\", \"notes\", \"subnets\"})\n   public static Network create(long accountId, long id, int cidr, String networkIdentifier, String name,\n                                String notes, List<Subnet> subnets) {\n      return new AutoValue_Network(accountId, id, cidr, networkIdentifier, name, notes,\n                                    subnets == null ? ImmutableList.<Subnet> of() : ImmutableList.copyOf(subnets));\n   }\n\n   Network() {}\n\n   @AutoValue\n   public abstract static class CreateNetwork {\n\n      public abstract String networkIdentifier();\n      public abstract String name();\n      public abstract int cidr();\n      @Nullable\n      public abstract String notes();\n\n      @SerializedNames({\"networkIdentifier\", \"name\", \"cidr\", \"notes\"})\n      private static CreateNetwork create(final String networkIdentifier, final String name, final int cidr, @Nullable final String notes) {\n         return builder()\n                 .networkIdentifier(networkIdentifier)\n                 .name(name)\n                 .cidr(cidr)\n                 .notes(notes)\n                 .build();\n      }\n\n      public static Builder builder() {\n         return new AutoValue_Network_CreateNetwork.Builder();\n      }\n\n      @AutoValue.Builder\n      public abstract static class Builder {\n\n         public abstract Builder networkIdentifier(String networkIdentifier);\n         public abstract Builder name(String name);\n         public abstract Builder cidr(int cidr);\n         @Nullable\n         public abstract Builder notes(String notes);\n\n         abstract CreateNetwork autoBuild();\n\n         public CreateNetwork build() {\n            return autoBuild();\n         }\n      }\n   }\n\n   @AutoValue\n   public abstract static class EditNetwork {\n\n      public abstract String name();\n      public abstract String notes();\n      public abstract long id();\n\n      @SerializedNames({\"name\", \"notes\", \"id\"})\n      private static EditNetwork create(final String name, final String notes, final long id) {\n         return builder()\n                 .name(name)\n                 .notes(notes)\n                 .id(id)\n                 .build();\n      }\n\n      public static Builder builder() {\n         return new AutoValue_Network_EditNetwork.Builder();\n      }\n\n      @AutoValue.Builder\n      public abstract static class Builder {\n\n         public abstract Builder name(String name);\n         public abstract Builder notes(String notes);\n         public abstract Builder id(long id);\n\n         abstract EditNetwork autoBuild();\n\n         public EditNetwork build() {\n            return autoBuild();\n         }\n      }\n   }\n\n   @AutoValue\n   public abstract static class DeleteNetwork {\n\n      public abstract long id();\n\n      @SerializedNames({\"id\"})\n      private static DeleteNetwork create(final long id) {\n         return builder()\n                 .id(id)\n                 .build();\n      }\n\n      public static Builder builder() {\n         return new AutoValue_Network_DeleteNetwork.Builder();\n      }\n\n      @AutoValue.Builder\n      public abstract static class Builder {\n\n         public abstract Builder id(long id);\n\n         abstract DeleteNetwork autoBuild();\n\n         public DeleteNetwork build() {\n            return autoBuild();\n         }\n      }\n   }\n}\n\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/domain/NetworkVlan.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\npublic class NetworkVlan {\n\n   private final int id;\n   private final int accountId;\n   private final String name;\n   private final int networkVrfId;\n   private final int primarySubnetId;\n   private final int vlanNumber;\n   private final String note;\n\n   @ConstructorProperties({\n           \"id\", \"accountId\", \"name\", \"networkVrfId\", \"primarySubnetId\", \"vlanNumber\", \"note\"\n   })\n   public NetworkVlan(int id, int accountId, @Nullable String name, int networkVrfId, int primarySubnetId,\n                      int vlanNumber, @Nullable String note) {\n      this.id = id;\n      this.accountId = accountId;\n      this.name = name;\n      this.networkVrfId = networkVrfId;\n      this.primarySubnetId = primarySubnetId;\n      this.vlanNumber = vlanNumber;\n      this.note = note;\n   }\n\n   public int getId() {\n      return id;\n   }\n\n   public int getAccountId() {\n      return accountId;\n   }\n\n   public String getName() {\n      return name;\n   }\n\n   public int getNetworkVrfId() {\n      return networkVrfId;\n   }\n\n   public int getPrimarySubnetId() {\n      return primarySubnetId;\n   }\n\n   public int getVlanNumber() {\n      return vlanNumber;\n   }\n\n   public String getNote() {\n      return note;\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o) return true;\n      if (o == null || getClass() != o.getClass()) return false;\n\n      NetworkVlan that = (NetworkVlan) o;\n\n      return Objects.equal(this.id, that.id) &&\n              Objects.equal(this.accountId, that.accountId) &&\n              Objects.equal(this.name, that.name) &&\n              Objects.equal(this.networkVrfId, that.networkVrfId) &&\n              Objects.equal(this.primarySubnetId, that.primarySubnetId) &&\n              Objects.equal(this.vlanNumber, that.vlanNumber) &&\n              Objects.equal(this.note, that.note);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, accountId, name, networkVrfId, primarySubnetId, vlanNumber,\n              note);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this)\n              .add(\"id\", id)\n              .add(\"accountId\", accountId)\n              .add(\"name\", name)\n              .add(\"networkVrfId\", networkVrfId)\n              .add(\"primarySubnetId\", primarySubnetId)\n              .add(\"vlanNumber\", vlanNumber)\n              .add(\"note\", note)\n              .toString();\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().fromNetworkVlan(this);\n   }\n\n   public static class Builder {\n\n      protected int id;\n      protected int accountId;\n      protected String name;\n      protected int networkVrfId;\n      protected int primarySubnetId;\n      protected int vlanNumber;\n      protected String note;\n\n      public Builder id(int id) {\n         this.id = id;\n         return this;\n      }\n\n      public Builder accountId(int accountId) {\n         this.accountId = accountId;\n         return this;\n      }\n\n      public Builder name(String name) {\n         this.name = name;\n         return this;\n      }\n\n      public Builder networkVrfId(int networkVrfId) {\n         this.networkVrfId = networkVrfId;\n         return this;\n      }\n\n      public Builder primarySubnetId(int primarySubnetId) {\n         this.primarySubnetId = primarySubnetId;\n         return this;\n      }\n\n      public Builder vlanNumber(int vlanNumber) {\n         this.vlanNumber = vlanNumber;\n         return this;\n      }\n\n      public Builder note(String note) {\n         this.note = note;\n         return this;\n      }\n\n      public NetworkVlan build() {\n         return new NetworkVlan(id, accountId, name, networkVrfId, primarySubnetId,\n                 vlanNumber, note);\n      }\n\n      public Builder fromNetworkVlan(NetworkVlan in) {\n         return this\n                 .id(in.getId())\n                 .accountId(in.getAccountId())\n                 .name(in.getName())\n                 .networkVrfId(in.getNetworkVrfId())\n                 .primarySubnetId(in.getPrimarySubnetId())\n                 .vlanNumber(in.getVlanNumber())\n                 .note(in.getNote());\n      }\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/domain/OperatingSystem.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport java.beans.ConstructorProperties;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Extends the SoftLayer_Software_Component data type to include operating system specific properties.\n *\n * @see <a href=\"http://sldn.softlayer.com/reference/datatypes/SoftLayer_Software_Component_OperatingSystem\"/>\n */\npublic class OperatingSystem {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().fromOperatingSystem(this);\n   }\n\n   public static class Builder {\n\n      protected String id;\n      protected SoftwareLicense softwareLicense;\n      protected String operatingSystemReferenceCode;\n      protected Set<Password> passwords = ImmutableSet.of();\n\n      /**\n       * @see OperatingSystem#getId()\n       */\n      public Builder id(String id) {\n         this.id = id;\n         return this;\n      }\n\n      /**\n       * @see OperatingSystem#getSoftwareLicense()\n       */\n      public Builder softwareLicense(SoftwareLicense softwareLicense) {\n         this.softwareLicense = softwareLicense;\n         return this;\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.OperatingSystem#getOperatingSystemReferenceCode()\n       */\n      public Builder operatingSystemReferenceCode(String operatingSystemReferenceCode) {\n         this.operatingSystemReferenceCode = operatingSystemReferenceCode;\n         return this;\n      }\n\n      /**\n       * @see OperatingSystem#getPasswords()\n       */\n      public Builder passwords(Set<Password> passwords) {\n         this.passwords = ImmutableSet.copyOf(checkNotNull(passwords, \"passwords\"));\n         return this;\n      }\n\n      public Builder passwords(Password... in) {\n         return passwords(ImmutableSet.copyOf(in));\n      }\n\n      public OperatingSystem build() {\n         return new OperatingSystem(id, softwareLicense, operatingSystemReferenceCode, passwords);\n      }\n\n      public Builder fromOperatingSystem(OperatingSystem in) {\n         return this.id(in.getId()).passwords(in.getPasswords());\n      }\n\n   }\n\n   private final String id;\n   private final SoftwareLicense softwareLicense;\n   private final String operatingSystemReferenceCode;\n   private final Set<Password> passwords;\n\n   @ConstructorProperties({\n         \"id\", \"softwareLicense\", \"operatingSystemReferenceCode\", \"passwords\"\n   })\n   protected OperatingSystem(String id, @Nullable SoftwareLicense softwareLicense,\n                             @Nullable String operatingSystemReferenceCode, @Nullable Set<Password> passwords) {\n      this.id = checkNotNull(id, \"id\");\n      this.softwareLicense = softwareLicense;\n      this.operatingSystemReferenceCode = operatingSystemReferenceCode;\n      this.passwords = passwords == null ? ImmutableSet.<Password>of() : ImmutableSet.copyOf(passwords);\n   }\n\n   /**\n    * @return An ID number identifying this Software Component (Software Installation)\n    */\n   public String getId() {\n      return this.id;\n   }\n\n   public SoftwareLicense getSoftwareLicense() {\n      return softwareLicense;\n   }\n\n   public String getOperatingSystemReferenceCode() {\n      return operatingSystemReferenceCode;\n   }\n\n   /**\n    * @return Username/Password pairs used for access to this Software Installation.\n    */\n   public Set<Password> getPasswords() {\n      return this.passwords;\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o) return true;\n      if (o == null || getClass() != o.getClass()) return false;\n\n      OperatingSystem that = (OperatingSystem) o;\n\n      return Objects.equal(this.id, that.id) &&\n              Objects.equal(this.softwareLicense, that.softwareLicense) &&\n              Objects.equal(this.operatingSystemReferenceCode, that.operatingSystemReferenceCode) &&\n              Objects.equal(this.passwords, that.passwords);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, softwareLicense, operatingSystemReferenceCode, passwords);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this)\n              .add(\"id\", id)\n              .add(\"softwareLicense\", softwareLicense)\n              .add(\"operatingSystemReferenceCode\", operatingSystemReferenceCode)\n              .add(\"passwords\", passwords)\n              .toString();\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/domain/Password.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Strings.emptyToNull;\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\n/**\n * Contains a password for a specific software component instance\n *\n * @see <a href= \"http://sldn.softlayer.com/reference/datatypes/SoftLayer_Software_Component_Password\"\n/>\n */\npublic class Password {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromPassword(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>>  {\n      protected abstract T self();\n\n      protected int id;\n      protected String username;\n      protected String password;\n\n      /**\n       * @see Password#getId()\n       */\n      public T id(int id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see Password#getUsername()\n       */\n      public T username(String username) {\n         this.username = username;\n         return self();\n      }\n\n      /**\n       * @see Password#getPassword()\n       */\n      public T password(String password) {\n         this.password = password;\n         return self();\n      }\n\n      public Password build() {\n         return new Password(id, username, password);\n      }\n\n      public T fromPassword(Password in) {\n         return this\n               .id(in.getId())\n               .username(in.getUsername())\n               .password(in.getPassword());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final int id;\n   private final String username;\n   private final String password;\n\n   @ConstructorProperties({\"id\", \"username\", \"password\"})\n   public Password(int id, String username, @Nullable String password) {\n      this.id = id;\n      this.username = checkNotNull(emptyToNull(username), \"username cannot be null or empty:\" + username);\n      this.password = password;\n   }\n\n   /**\n    * @return An id number for this specific username/password pair.\n    */\n   public int getId() {\n      return this.id;\n   }\n\n   /**\n    * @return The username part of the username/password pair.\n    */\n   @Nullable\n   public String getUsername() {\n      return this.username;\n   }\n\n   /**\n    * @return The password part of the username/password pair.\n    */\n   @Nullable\n   public String getPassword() {\n      return this.password;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      Password that = Password.class.cast(obj);\n      return Objects.equal(this.id, that.id);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this)\n              .add(\"id\", id)\n              .add(\"username\", username)\n              .add(\"password\", password)\n              .toString();\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/domain/PowerState.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.MoreObjects.ToStringHelper;\n\n/**\n * The power state class provides a common set of values for which a guest's power state will be presented in the SoftLayer API.\n *\n * @see <a href= \"http://sldn.softlayer.com/reference/datatypes/SoftLayer_Virtual_Guest_Power_State\"\n/>\n */\npublic class PowerState {\n\n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromPowerState(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>>  {\n      protected abstract T self();\n\n      protected VirtualGuest.State keyName;\n\n      /**\n       * @see PowerState#getKeyName()\n       */\n      public T keyName(VirtualGuest.State keyName) {\n         this.keyName = keyName;\n         return self();\n      }\n\n      public PowerState build() {\n         return new PowerState(keyName);\n      }\n\n      public T fromPowerState(PowerState in) {\n         return this\n               .keyName(in.getKeyName());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final VirtualGuest.State keyName;\n\n   @ConstructorProperties(\"keyName\")\n   public PowerState(VirtualGuest.State keyName) {\n      this.keyName = checkNotNull(keyName, \"keyName cannot be null or empty:\" + keyName);\n   }\n\n   /**\n    * Maps onto {@code VirtualGuest.State}\n    *\n    * @return The key name of a power state.\n    */\n   @Nullable\n   public VirtualGuest.State getKeyName() {\n      return this.keyName;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(keyName);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      PowerState that = PowerState.class.cast(obj);\n      return Objects.equal(this.keyName, that.keyName);\n   }\n\n   protected ToStringHelper string() {\n      return MoreObjects.toStringHelper(this)\n            .add(\"keyName\", keyName);\n   }\n\n   @Override\n   public String toString() {\n      return string().toString();\n   }\n\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/domain/ProductItem.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\n/**\n * @see <a href= \"http://sldn.softlayer.com/reference/datatypes/SoftLayer_Product_Item\"\n */\npublic class ProductItem {\n\n   private final int id;\n   private final String description;\n   private final String softwareDescriptionId;\n   private final SoftwareDescription softwareDescription;\n\n   @ConstructorProperties({\"id\", \"description\", \"softwareDescriptionId\", \"softwareDescription\"})\n   public ProductItem(int id, @Nullable String description, @Nullable String softwareDescriptionId,\n                      @Nullable SoftwareDescription softwareDescription) {\n      this.id = id;\n      this.description = description;\n      this.softwareDescriptionId = softwareDescriptionId;\n      this.softwareDescription = softwareDescription;\n   }\n\n   public int getId() {\n      return id;\n   }\n\n   public String getDescription() {\n      return description;\n   }\n\n   public String getSoftwareDescriptionId() {\n      return softwareDescriptionId;\n   }\n\n   public SoftwareDescription getSoftwareDescription() {\n      return softwareDescription;\n   }\n\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o) return true;\n      if (o == null || getClass() != o.getClass()) return false;\n\n      ProductItem that = (ProductItem) o;\n\n      return Objects.equal(this.id, that.id) &&\n              Objects.equal(this.description, that.description) &&\n              Objects.equal(this.softwareDescriptionId, that.softwareDescriptionId) &&\n              Objects.equal(this.softwareDescription, that.softwareDescription);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, description, softwareDescriptionId, softwareDescription);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this)\n              .add(\"id\", id)\n              .add(\"description\", description)\n              .add(\"softwareDescriptionId\", softwareDescriptionId)\n              .add(\"softwareDescription\", softwareDescription)\n              .toString();\n   }\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().fromProductItem(this);\n   }\n\n   public static class Builder {\n      private int id;\n      private String description;\n      private String softwareDescriptionId;\n      private SoftwareDescription softwareDescription;\n\n      /**\n       * @see ProductItem#getId()\n       */\n      public Builder id(int id) {\n         this.id = id;\n         return this;\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.ProductItem#getDescription() ()\n       */\n      public Builder description(String description) {\n         this.description = description;\n         return this;\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.ProductItem#getSoftwareDescriptionId() ()\n       */\n      public Builder softwareDescriptionId(String softwareDescriptionId) {\n         this.softwareDescriptionId = softwareDescriptionId;\n         return this;\n      }\n\n      /**\n       * @see ProductItem#getSoftwareDescription()\n       */\n      public Builder softwareDescription(SoftwareDescription softwareDescription) {\n         this.softwareDescription = softwareDescription;\n         return this;\n      }\n\n      public ProductItem build() {\n         return new ProductItem(id, description, softwareDescriptionId, softwareDescription);\n      }\n\n      public Builder fromProductItem(ProductItem in) {\n         return this\n                 .id(in.getId())\n                 .description(in.getDescription())\n                 .softwareDescriptionId(in.getSoftwareDescriptionId())\n                 .softwareDescription(in.getSoftwareDescription());\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/domain/ProductItemPrice.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport java.beans.ConstructorProperties;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\n/**\n * @see <a href= \"http://sldn.softlayer.com/reference/datatypes/SoftLayer_Product_Item_Price\"\n */\npublic class ProductItemPrice {\n\n   private final int id;\n   private final float hourlyRecurringFee;\n   private final String recurringFee;\n   private final ProductItem item;\n\n   @ConstructorProperties({\"id\", \"hourlyRecurringFee\", \"recurringFee\", \"item\"})\n   public ProductItemPrice(int id, float hourlyRecurringFee, String recurringFee, ProductItem item) {\n      this.id = id;\n      this.hourlyRecurringFee = hourlyRecurringFee;\n      this.recurringFee = checkNotNull(recurringFee, \"recurringFee\");\n      this.item = checkNotNull(item, \"item\");\n   }\n\n   public int getId() {\n      return id;\n   }\n\n   public float getHourlyRecurringFee() {\n      return hourlyRecurringFee;\n   }\n\n   public String getRecurringFee() {\n      return recurringFee;\n   }\n\n   public ProductItem getItem() {\n      return item;\n   }\n\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o) return true;\n      if (o == null || getClass() != o.getClass()) return false;\n\n      ProductItemPrice that = (ProductItemPrice) o;\n\n      return Objects.equal(this.id, that.id) &&\n              Objects.equal(this.hourlyRecurringFee, that.hourlyRecurringFee) &&\n              Objects.equal(this.recurringFee, that.recurringFee) &&\n              Objects.equal(this.item, that.item);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, hourlyRecurringFee, recurringFee, item);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this)\n              .add(\"id\", id)\n              .add(\"hourlyRecurringFee\", hourlyRecurringFee)\n              .add(\"recurringFee\", recurringFee)\n              .add(\"item\", item)\n              .toString();\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().fromProductItemPrice(this);\n   }\n\n   public static class Builder {\n      private int id;\n      private float hourlyRecurringFee;\n      private String recurringFee;\n      private ProductItem item;\n\n      /**\n       * @see ProductItemPrice#getId()\n       */\n      public Builder id(int id) {\n         this.id = id;\n         return this;\n      }\n\n      /**\n       * @see ProductItemPrice#getHourlyRecurringFee()\n       */\n      public Builder hourlyRecurringFee(float hourlyRecurringFee) {\n         this.hourlyRecurringFee = hourlyRecurringFee;\n         return this;\n      }\n\n      /**\n       * @see ProductItemPrice#getRecurringFee()\n       */\n      public Builder recurringFee(String recurringFee) {\n         this.recurringFee = recurringFee;\n         return this;\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.ProductItemPrice#getItem()\n       */\n      public Builder item(ProductItem item) {\n         this.item = item;\n         return this;\n      }\n\n      public ProductItemPrice build() {\n         return new ProductItemPrice(id, hourlyRecurringFee, recurringFee, item);\n      }\n\n      public Builder fromProductItemPrice(ProductItemPrice in) {\n         return this\n                 .id(in.getId())\n                 .hourlyRecurringFee(in.getHourlyRecurringFee())\n                 .recurringFee(in.getRecurringFee())\n                 .item(in.getItem());\n      }\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/domain/Region.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Strings.emptyToNull;\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\n/**\n * A region is made up of a keyname and a description of that region.\n * A region keyname can be used as part of an order.\n * Check the SoftLayer_Product_Order service for more details.\n *\n * @see <a href= \"http://sldn.softlayer.com/reference/datatypes/SoftLayer_Location_Region\"\n *      />\n */\npublic class Region implements Comparable<Region> {\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n      private String keyname;\n      private String description;\n\n      public Builder keyname(String keyname) {\n         this.keyname = keyname;\n         return this;\n      }\n\n      public Builder description(String description) {\n         this.description = description;\n         return this;\n      }\n\n      public Region build() {\n         return new Region(0, keyname, description);\n      }\n\n      public static Builder fromAddress(Region in) {\n         return Region.builder().keyname(in.getKeyname())\n               .description(in.getDescription());\n      }\n   }\n\n   /* An integer representing the order in which this element is displayed */\n   private final int sortOrder;\n   private final String keyname;\n   private final String description;\n\n   @ConstructorProperties({\"sortOrder\", \"keyname\", \"description\"})\n   public Region(int sortOrder, String keyname, String description) {\n      this.sortOrder = sortOrder;\n      this.keyname = checkNotNull(emptyToNull(keyname), \"keyname cannot be null or empty:\" + keyname);\n      this.description = description;\n   }\n\n   @Override\n   public int compareTo(Region arg0) {\n      return Integer.valueOf(sortOrder).compareTo(arg0.sortOrder);\n   }\n\n   /**\n    * @return A unique key name for a region. Provided for easy debugging. This is to be sent in with an order.\n    */\n   public String getKeyname() {\n      return keyname;\n   }\n\n   /**\n    * @return A short description of a region's name. This description is seen on the order forms.\n    */\n   @Nullable\n   public String getDescription() {\n      return description;\n   }\n\n   public Builder toBuilder() {\n      return Builder.fromAddress(this);\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o) return true;\n      if (o == null || getClass() != o.getClass()) return false;\n\n      Region region = (Region) o;\n      return Objects.equal(keyname, region.keyname)\n            && Objects.equal(description, region.description);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(keyname, description);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this)\n              .add(\"sortOrder\", sortOrder)\n              .add(\"keyname\", keyname)\n              .add(\"description\", description)\n              .toString();\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/domain/SecuritySshKey.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\npublic class SecuritySshKey {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().fromSecuritySshKey(this);\n   }\n\n   public static class Builder {\n\n      protected int id;\n      protected String key;\n      protected String label;\n      protected String fingerprint;\n      protected String notes;\n      protected String createDate;\n      protected String modifyDate;\n\n      /**\n       * @see SecuritySshKey#getId()\n       */\n      public Builder id(int id) {\n         this.id = id;\n         return this;\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.SecuritySshKey#getKey()\n       */\n      public Builder key(String key) {\n         this.key = key;\n         return this;\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.SecuritySshKey#getLabel() ()\n       */\n      public Builder label(String label) {\n         this.label = label;\n         return this;\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.SecuritySshKey#getFingerprint()\n       */\n      public Builder fingerprint(String fingerprint) {\n         this.fingerprint = fingerprint;\n         return this;\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.SecuritySshKey#getNotes()\n       */\n      public Builder notes(String notes) {\n         this.notes = notes;\n         return this;\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.SecuritySshKey#getCreateDate()\n       */\n      public Builder createDate(String createDate) {\n         this.createDate = createDate;\n         return this;\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.SecuritySshKey#getModifyDate()\n       */\n      public Builder modifyDate(String modifyDate) {\n         this.modifyDate = modifyDate;\n         return this;\n      }\n\n      public SecuritySshKey build() {\n         return new SecuritySshKey(id, key, label, fingerprint, notes, createDate, modifyDate);\n      }\n\n      public Builder fromSecuritySshKey(SecuritySshKey in) {\n         return this\n                 .id(in.getId())\n                 .key(in.getKey())\n                 .label(in.getLabel())\n                 .fingerprint(in.getFingerprint())\n                 .notes(in.getNotes())\n                 .createDate(in.getCreateDate())\n                 .modifyDate(in.getModifyDate());\n      }\n   }\n\n   private final int id;\n   private final String key;\n   private final String label;\n   private final String fingerprint;\n   private final String notes;\n   private final String createDate;\n   private final String modifyDate;\n\n   @ConstructorProperties({\n           \"id\", \"key\", \"label\", \"name\", \"notes\", \"createDate\", \"modifyDate\" })\n   protected SecuritySshKey(int id, @Nullable String key, @Nullable String label,\n                            @Nullable String fingerprint, @Nullable String notes, @Nullable String createDate,\n                            @Nullable String modifyDate) {\n      this.id = id;\n      this.key = key;\n      this.label = label;\n      this.fingerprint = fingerprint;\n      this.notes = notes;\n      this.createDate = createDate;\n      this.modifyDate = modifyDate;\n   }\n\n   public int getId() {\n      return id;\n   }\n\n   public String getKey() {\n      return key;\n   }\n\n   public String getLabel() {\n      return label;\n   }\n\n   public String getFingerprint() {\n      return fingerprint;\n   }\n\n   public String getNotes() {\n      return notes;\n   }\n\n   public String getCreateDate() {\n      return createDate;\n   }\n\n   public String getModifyDate() {\n      return modifyDate;\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o) return true;\n      if (o == null || getClass() != o.getClass()) return false;\n\n      SecuritySshKey that = (SecuritySshKey) o;\n\n      return Objects.equal(this.id, that.id) &&\n              Objects.equal(this.key, that.key) &&\n              Objects.equal(this.label, that.label) &&\n              Objects.equal(this.fingerprint, that.fingerprint) &&\n              Objects.equal(this.notes, that.notes) &&\n              Objects.equal(this.createDate, that.createDate) &&\n              Objects.equal(this.modifyDate, that.modifyDate);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, key, label, fingerprint, notes, createDate, modifyDate);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this)\n              .add(\"id\", id)\n              .add(\"key\", key)\n              .add(\"label\", label)\n              .add(\"name\", fingerprint)\n              .add(\"notes\", notes)\n              .add(\"createDate\", createDate)\n              .add(\"modifyDate\", modifyDate)\n              .toString();\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/domain/SoftwareDescription.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\npublic class SoftwareDescription {\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().fromSoftwareDescription(this);\n   }\n\n   public static class Builder {\n\n      protected int id;\n      protected String longDescription;\n      protected String manufacturer;\n      protected String name;\n      protected int operatingSystem;\n      protected String referenceCode;\n      protected String requiredUser;\n      protected String version;\n      protected int controlPanel;\n      protected String upgradeSoftwareDescriptionId;\n      protected String upgradeSwDescId;\n      protected String virtualLicense;\n      protected String virtualizationPlatform;\n\n      /**\n       * @see SoftwareDescription#getId()\n       */\n      public Builder id(int id) {\n         this.id = id;\n         return this;\n      }\n\n      /**\n       * @see SoftwareDescription#getLongDescription()\n       */\n      public Builder longDescription(String longDescription) {\n         this.longDescription = longDescription;\n         return this;\n      }\n\n      /**\n       * @see SoftwareDescription#getManufacturer()\n       */\n      public Builder manufacturer(String manufacturer) {\n         this.manufacturer = manufacturer;\n         return this;\n      }\n\n      /**\n       * @see SoftwareDescription#getName()\n       */\n      public Builder name(String name) {\n         this.name = name;\n         return this;\n      }\n\n      /**\n       * @see SoftwareDescription#isOperatingSystem()\n       */\n      public Builder operatingSystem(int operatingSystem) {\n         this.operatingSystem = operatingSystem;\n         return this;\n      }\n\n      /**\n       * @see SoftwareDescription#getReferenceCode()\n       */\n      public Builder referenceCode(String referenceCode) {\n         this.referenceCode = referenceCode;\n         return this;\n      }\n\n      /**\n       * @see SoftwareDescription#getRequiredUser()\n       */\n      public Builder requiredUser(String requiredUser) {\n         this.requiredUser = requiredUser;\n         return this;\n      }\n\n      /**\n       * @see SoftwareDescription#getVersion()\n       */\n      public Builder version(String version) {\n         this.version = version;\n         return this;\n      }\n\n      public Builder controlPanel(int controlPanel) {\n         this.controlPanel = controlPanel;\n         return this;\n      }\n\n      public Builder upgradeSoftwareDescriptionId(String upgradeSoftwareDescriptionId) {\n         this.upgradeSoftwareDescriptionId = upgradeSoftwareDescriptionId;\n         return this;\n      }\n\n      public Builder upgradeSwDescId(String upgradeSwDescId) {\n         this.upgradeSwDescId = upgradeSwDescId;\n         return this;\n      }\n\n      public Builder virtualLicense(String virtualLicense) {\n         this.virtualLicense = virtualLicense;\n         return this;\n      }\n\n      public Builder virtualizationPlatform(String virtualizationPlatform) {\n         this.virtualizationPlatform = virtualizationPlatform;\n         return this;\n      }\n\n      public SoftwareDescription build() {\n         return new SoftwareDescription(id, longDescription, manufacturer, name, operatingSystem, referenceCode,\n                 requiredUser, version, controlPanel, upgradeSoftwareDescriptionId, upgradeSwDescId, virtualLicense,\n                 virtualizationPlatform);\n      }\n\n      public Builder fromSoftwareDescription(SoftwareDescription in) {\n         return this\n                 .id(in.getId())\n                 .longDescription(in.getLongDescription())\n                 .manufacturer(in.getManufacturer())\n                 .name(in.getName())\n                 .operatingSystem(in.getOperatingSystem())\n                 .referenceCode(in.getReferenceCode())\n                 .requiredUser(in.getRequiredUser())\n                 .version(in.getVersion())\n                 .controlPanel(in.getControlPanel())\n                 .upgradeSoftwareDescriptionId(in.getUpgradeSoftwareDescriptionId())\n                 .upgradeSwDescId(in.getUpgradeSwDescId())\n                 .virtualLicense(in.getVirtualLicense())\n                 .virtualizationPlatform(in.getVirtualizationPlatform());\n      }\n   }\n\n   private final int id;\n   private final String longDescription;\n   private final String manufacturer;\n   private final String name;\n   private final int operatingSystem;\n   private final String referenceCode;\n   private final String requiredUser;\n   private final String version;\n   private final int controlPanel;\n   private final String upgradeSoftwareDescriptionId;\n   private final String upgradeSwDescId;\n   private final String virtualLicense;\n   private final String virtualizationPlatform;\n\n   @ConstructorProperties({\n           \"id\", \"longDescription\", \"manufacturer\", \"name\", \"operatingSystem\", \"referenceCode\", \"requiredUser\",\n           \"version\", \"controlPanel\", \"upgradeSoftwareDescriptionId\", \"upgradeSwDescId\", \"virtualLicense\",\n           \"virtualizationPlatform\"\n   })\n   protected SoftwareDescription(int id, @Nullable String longDescription, @Nullable String manufacturer,\n                                 @Nullable String name, int operatingSystem, @Nullable String referenceCode,\n                                 @Nullable String requiredUser, @Nullable String version, int controlPanel,\n                                 @Nullable String upgradeSoftwareDescriptionId, @Nullable String upgradeSwDescId,\n                                 @Nullable String virtualLicense, @Nullable String virtualizationPlatform) {\n      this.id = id;\n      this.longDescription = longDescription;\n      this.manufacturer = manufacturer;\n      this.name = name;\n      this.operatingSystem = operatingSystem;\n      this.referenceCode = referenceCode;\n      this.requiredUser = requiredUser;\n      this.version = version;\n      this.controlPanel = controlPanel;\n      this.upgradeSoftwareDescriptionId = upgradeSoftwareDescriptionId;\n      this.upgradeSwDescId = upgradeSwDescId;\n      this.virtualLicense = virtualLicense;\n      this.virtualizationPlatform = virtualizationPlatform;\n   }\n\n   public int getId() {\n      return id;\n   }\n\n   public String getLongDescription() {\n      return longDescription;\n   }\n\n   public String getManufacturer() {\n      return manufacturer;\n   }\n\n   public String getName() {\n      return name;\n   }\n\n   public int getOperatingSystem() {\n      return operatingSystem;\n   }\n\n   public String getReferenceCode() {\n      return referenceCode;\n   }\n\n   public String getRequiredUser() {\n      return requiredUser;\n   }\n\n   public String getVersion() {\n      return version;\n   }\n\n   public int getControlPanel() {\n      return controlPanel;\n   }\n\n   public String getUpgradeSoftwareDescriptionId() {\n      return upgradeSoftwareDescriptionId;\n   }\n\n   public String getUpgradeSwDescId() {\n      return upgradeSwDescId;\n   }\n\n   public String getVirtualLicense() {\n      return virtualLicense;\n   }\n\n   public String getVirtualizationPlatform() {\n      return virtualizationPlatform;\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o) return true;\n      if (o == null || getClass() != o.getClass()) return false;\n\n      SoftwareDescription that = (SoftwareDescription) o;\n\n      return Objects.equal(this.id, that.id) &&\n              Objects.equal(this.longDescription, that.longDescription) &&\n              Objects.equal(this.manufacturer, that.manufacturer) &&\n              Objects.equal(this.name, that.name) &&\n              Objects.equal(this.operatingSystem, that.operatingSystem) &&\n              Objects.equal(this.referenceCode, that.referenceCode) &&\n              Objects.equal(this.requiredUser, that.requiredUser) &&\n              Objects.equal(this.version, that.version) &&\n              Objects.equal(this.controlPanel, that.controlPanel) &&\n              Objects.equal(this.upgradeSoftwareDescriptionId, that.upgradeSoftwareDescriptionId) &&\n              Objects.equal(this.upgradeSwDescId, that.upgradeSwDescId) &&\n              Objects.equal(this.virtualLicense, that.virtualLicense) &&\n              Objects.equal(this.virtualizationPlatform, that.virtualizationPlatform);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, longDescription, manufacturer, name, operatingSystem, referenceCode,\n              requiredUser, version, controlPanel, upgradeSoftwareDescriptionId, upgradeSwDescId,\n              virtualLicense, virtualizationPlatform);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this)\n              .add(\"id\", id)\n              .add(\"longDescription\", longDescription)\n              .add(\"manufacturer\", manufacturer)\n              .add(\"name\", name)\n              .add(\"operatingSystem\", operatingSystem)\n              .add(\"referenceCode\", referenceCode)\n              .add(\"requiredUser\", requiredUser)\n              .add(\"version\", version)\n              .add(\"controlPanel\", controlPanel)\n              .add(\"upgradeSoftwareDescriptionId\", upgradeSoftwareDescriptionId)\n              .add(\"upgradeSwDescId\", upgradeSwDescId)\n              .add(\"virtualLicense\", virtualLicense)\n              .add(\"virtualizationPlatform\", virtualizationPlatform)\n              .toString();\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/domain/SoftwareLicense.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.domain;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport java.beans.ConstructorProperties;\n\npublic class SoftwareLicense {\n\n   private final int id;\n   private final SoftwareDescription softwareDescription;\n   private final int softwareDescriptionId;\n\n   @ConstructorProperties({\n           \"id\", \"softwareDescription\", \"softwareDescriptionId\"\n   })\n   protected SoftwareLicense(int id, @Nullable SoftwareDescription softwareDescription, int softwareDescriptionId) {\n      this.id = id;\n      this.softwareDescription = softwareDescription;\n      this.softwareDescriptionId = softwareDescriptionId;\n   }\n\n   public int getId() {\n      return this.id;\n   }\n\n   @Nullable\n   public SoftwareDescription getSoftwareDescription() {\n      return this.softwareDescription;\n   }\n\n   /**\n    * @return A longer location description.\n    */\n   public int getSoftwareDescriptionId() {\n      return this.softwareDescriptionId;\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o) return true;\n      if (o == null || getClass() != o.getClass()) return false;\n\n      SoftwareLicense that = (SoftwareLicense) o;\n\n      return Objects.equal(this.id, that.id) &&\n              Objects.equal(this.softwareDescription, that.softwareDescription) &&\n              Objects.equal(this.softwareDescriptionId, that.softwareDescriptionId);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, softwareDescription, softwareDescriptionId);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this)\n              .add(\"id\", id)\n              .add(\"softwareDescription\", softwareDescription)\n              .add(\"softwareDescriptionId\", softwareDescriptionId)\n              .toString();\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().fromSoftwareLicense(this);\n   }\n\n   public static class Builder {\n      protected int id;\n      protected SoftwareDescription softwareDescription;\n      protected int softwareDescriptionId;\n\n      /**\n       * @see SoftwareLicense#getId()\n       */\n      public Builder id(int id) {\n         this.id = id;\n         return this;\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.SoftwareLicense#getSoftwareDescription() ()\n       */\n      public Builder softwareDescription(SoftwareDescription softwareDescription) {\n         this.softwareDescription = softwareDescription;\n         return this;\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.SoftwareLicense#getSoftwareDescriptionId() ()\n       */\n      public Builder softwareDescriptionId(int softwareDescriptionId) {\n         this.softwareDescriptionId = softwareDescriptionId;\n         return this;\n      }\n\n      public SoftwareLicense build() {\n         return new SoftwareLicense(id, softwareDescription, softwareDescriptionId);\n      }\n\n      public Builder fromSoftwareLicense(SoftwareLicense in) {\n         return this\n                 .id(in.getId())\n                 .softwareDescription(in.getSoftwareDescription())\n                 .softwareDescriptionId(in.getSoftwareDescriptionId());\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/domain/Subnet.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.domain;\n\nimport com.google.auto.value.AutoValue;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.json.SerializedNames;\n\nimport java.util.Date;\n\n/**\n * Class SecurityGroup\n *\n * @see <a href= \"http://sldn.softlayer.com/reference/datatypes/softlayer_network_subnet\" />\n */\n\n@AutoValue\npublic abstract class Subnet {\n\n   public abstract String boradcastAddress();\n   public abstract int cidr();\n   public abstract String gateway();\n   public abstract long id();\n   public abstract boolean isCustomerOwned();\n   public abstract boolean isCustomerRoutable();\n   @Nullable\n   public abstract Date modifyDate();\n   public abstract String netmask();\n   public abstract String networkIdentifier();\n   public abstract long networkVlanId();\n   @Nullable\n   public abstract String note();\n   public abstract String sortOrder();\n   @Nullable\n   public abstract String subnetType();\n   public abstract String totalIpAddresses();\n   public abstract String usableIpAddressCount();\n   public abstract int version();\n   @Nullable\n   public abstract String addressSpace();\n\n   @SerializedNames({\"broadcastAddress\", \"cidr\", \"gateway\", \"id\", \"isCustomerOwned\", \"isCustomerRoutable\", \"modifyDate\",\n                     \"netmask\", \"networkIdentifier\", \"networkVlanId\", \"note\", \"sortOrder\", \"subnetType\", \"totalIpAddresses\",\n                     \"usableIpAddressCount\", \"version\", \"addressSpace\"})\n   public static Subnet create(String broadcastAddress, int cidr, String gateway, final long id, boolean isCustomerOwned, boolean isCustomerRoutable,\n                               Date modifyDate, String netmask, String networkIdentifier, long networkVlanId, String note, String sortOrder, String subnetType,\n                               String totalIpAddresses, String usableIpAddressCount, int version, String addressSpace) {\n      return new AutoValue_Subnet(broadcastAddress, cidr, gateway, id, isCustomerOwned, isCustomerRoutable, modifyDate, netmask,\n              networkIdentifier, networkVlanId, note, sortOrder, subnetType, totalIpAddresses, usableIpAddressCount, version, addressSpace);\n   }\n\n   Subnet() {}\n\n   @AutoValue\n   public abstract static class CreateSubnet {\n\n      public abstract String networkIdentifier();\n      public abstract String note();\n      public abstract int cidr();\n\n      @SerializedNames({\"networkIdentifier\", \"note\", \"cidr\"})\n      private static CreateSubnet create(final String networkIdentifier, final String note, final int cidr) {\n         return builder()\n                 .networkIdentifier(networkIdentifier)\n                 .cidr(cidr)\n                 .note(note)\n                 .build();\n      }\n\n      public static Builder builder() {\n         return new AutoValue_Subnet_CreateSubnet.Builder();\n      }\n\n      @AutoValue.Builder\n      public abstract static class Builder {\n\n         public abstract Builder networkIdentifier(String networkIdentifier);\n         public abstract Builder note(String note);\n         public abstract Builder cidr(int cidr);\n\n         abstract CreateSubnet autoBuild();\n\n         public CreateSubnet build() {\n            return autoBuild();\n         }\n      }\n   }\n\n   @AutoValue\n   public abstract static class DeleteSubnet {\n\n      public abstract long id();\n\n      @SerializedNames({\"id\"})\n      private static DeleteSubnet create(final long id) {\n         return builder()\n                 .id(id)\n                 .build();\n      }\n\n      public static Builder builder() {\n         return new AutoValue_Subnet_DeleteSubnet.Builder();\n      }\n\n      @AutoValue.Builder\n      public abstract static class Builder {\n\n         public abstract Builder id(long id);\n\n         abstract DeleteSubnet autoBuild();\n\n         public DeleteSubnet build() {\n            return autoBuild();\n         }\n      }\n   }\n\n   @AutoValue\n   public abstract static class CreateDatacenterName {\n      public abstract String name();\n\n      @SerializedNames({\"name\"})\n      public static CreateDatacenterName create(String name) {\n         return builder()\n                 .name(name)\n                 .build();\n      }\n\n      CreateDatacenterName() {}\n\n      public static Builder builder() {\n         return new AutoValue_Subnet_CreateDatacenterName.Builder();\n      }\n\n      @AutoValue.Builder\n      public abstract static class Builder {\n\n         public abstract Builder name(String name);\n\n         abstract CreateDatacenterName autoBuild();\n\n         public CreateDatacenterName build() {\n            return autoBuild();\n         }\n      }\n   }\n}\n\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/domain/Tag.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport java.beans.ConstructorProperties;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\npublic class Tag {\n   private final int accountId;\n   private final int id;\n   private final int internal;\n   private final String name;\n\n   @ConstructorProperties({\"accountId\", \"id\", \"internal\", \"name\"} )\n   public Tag(int accountId, int id, int internal, String name) {\n      this.accountId = accountId;\n      this.id = id;\n      this.internal = internal;\n      this.name = checkNotNull(name, \"name\");\n   }\n\n   public int getAccountId() {\n      return accountId;\n   }\n\n   public int getId() {\n      return id;\n   }\n\n   public int getInternal() {\n      return internal;\n   }\n\n   public String getName() {\n      return name;\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o) return true;\n      if (o == null || getClass() != o.getClass()) return false;\n\n      Tag that = (Tag) o;\n\n      return Objects.equal(this.accountId, that.accountId) &&\n              Objects.equal(this.id, that.id) &&\n              Objects.equal(this.internal, that.internal) &&\n              Objects.equal(this.name, that.name);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(accountId, id, internal, name);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this)\n              .add(\"accountId\", accountId)\n              .add(\"id\", id)\n              .add(\"internal\", internal)\n              .add(\"name\", name)\n              .toString();\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().fromTag(this);\n   }\n\n   public static class Builder {\n      private int accountId;\n      private int id;\n      private int internal;\n      private String name;\n\n      /**\n       * @see org.jclouds.softlayer.domain.Tag#getAccountId()\n       */\n      public Builder accountId(int accountId) {\n         this.accountId = accountId;\n         return this;\n      }\n\n      /**\n       * @see Tag#getId()\n       */\n      public Builder id(int id) {\n         this.id = id;\n         return this;\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.Tag#getInternal()\n       */\n      public Builder internal(int internal) {\n         this.internal = internal;\n         return this;\n      }\n\n      /**\n       * @see Tag#getName()\n       */\n      public Builder name(String name) {\n         this.name = name;\n         return this;\n      }\n\n      public Tag build() {\n         return new Tag(accountId, id, internal, name);\n      }\n\n      public Builder fromTag(Tag in) {\n         return this\n                 .accountId(in.getAccountId())\n                 .id(in.getId())\n                 .internal(in.getInternal())\n                 .name(in.getName());\n      }\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/domain/TagReference.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\n/**\n * @see <a href= \"http://sldn.softlayer.com/reference/datatypes/SoftLayer_Tag_Reference\"/>\n */\npublic class TagReference {\n   private final int id;\n   private final int usrRecordId;\n   private final int tagTypeId;\n   private final int tagId;\n   private final int resourceTableId;\n   private final int empRecordId;\n   private final Tag tag;\n   private final TagType tagType;\n\n   @ConstructorProperties({\"id\", \"usrRecordId\", \"tagTypeId\", \"tagId\", \"resourceTableId\", \"empRecordId\", \"tag\", \"tagType\"} )\n   public TagReference(int id, int usrRecordId, int tagTypeId, int tagId, int resourceTableId, int empRecordId,\n                       @Nullable Tag tag, @Nullable TagType tagType) {\n      this.id = id;\n      this.usrRecordId = usrRecordId;\n      this.tagTypeId = tagTypeId;\n      this.tagId = tagId;\n      this.resourceTableId = resourceTableId;\n      this.empRecordId = empRecordId;\n      this.tag = tag;\n      this.tagType = tagType;\n   }\n\n   public int getId() {\n      return id;\n   }\n\n   public int getUsrRecordId() {\n      return usrRecordId;\n   }\n\n   public int getTagTypeId() {\n      return tagTypeId;\n   }\n\n   public int getTagId() {\n      return tagId;\n   }\n\n   public int getResourceTableId() {\n      return resourceTableId;\n   }\n\n   public int getEmpRecordId() {\n      return empRecordId;\n   }\n\n   public Tag getTag() {\n      return tag;\n   }\n\n   public TagType getTagType() {\n      return tagType;\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o) return true;\n      if (o == null || getClass() != o.getClass()) return false;\n\n      TagReference that = (TagReference) o;\n\n      return Objects.equal(this.id, that.id) &&\n              Objects.equal(this.usrRecordId, that.usrRecordId) &&\n              Objects.equal(this.tagTypeId, that.tagTypeId) &&\n              Objects.equal(this.tagId, that.tagId) &&\n              Objects.equal(this.resourceTableId, that.resourceTableId) &&\n              Objects.equal(this.empRecordId, that.empRecordId) &&\n              Objects.equal(this.tag, that.tag) &&\n              Objects.equal(this.tagType, that.tagType);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, usrRecordId, tagTypeId, tagId, resourceTableId, empRecordId,\n              tag, tagType);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this)\n              .add(\"id\", id)\n              .add(\"usrRecordId\", usrRecordId)\n              .add(\"tagTypeId\", tagTypeId)\n              .add(\"tagId\", tagId)\n              .add(\"resourceTableId\", resourceTableId)\n              .add(\"empRecordId\", empRecordId)\n              .add(\"tag\", tag)\n              .add(\"tagType\", tagType)\n              .toString();\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().fromTagReference(this);\n   }\n\n   public static class Builder {\n      private int id;\n      private int usrRecordId;\n      private int tagTypeId;\n      private int tagId;\n      private int resourceTableId;\n      private int empRecordId;\n      private Tag tag;\n      private TagType tagType;\n\n      /**\n       * @see TagReference#getId()\n       */\n      public Builder id(int id) {\n         this.id = id;\n         return this;\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.TagReference#getUsrRecordId()\n       */\n      public Builder usrRecordId(int usrRecordId) {\n         this.usrRecordId = usrRecordId;\n         return this;\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.TagReference#getTagTypeId()\n       */\n      public Builder tagTypeId(int tagTypeId) {\n         this.tagTypeId = tagTypeId;\n         return this;\n      }\n\n      /**\n       * @see TagReference#getTagId()\n       */\n      public Builder tagId(int tagId) {\n         this.tagId = tagId;\n         return this;\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.TagReference#getResourceTableId()\n       */\n      public Builder resourceTableId(int resourceTableId) {\n         this.resourceTableId = resourceTableId;\n         return this;\n      }\n\n      /**\n       * @see TagReference#getEmpRecordId()\n       */\n      public Builder empRecordId(int empRecordId) {\n         this.empRecordId = empRecordId;\n         return this;\n      }\n\n      /**\n       * @see TagReference#getTag()\n       */\n      public Builder tag(Tag tag) {\n         this.tag = tag;\n         return this;\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.TagReference#getTagType()\n       */\n      public Builder tagType(TagType tagType) {\n         this.tagType = tagType;\n         return this;\n      }\n\n      public TagReference build() {\n         return new TagReference(id, usrRecordId, tagTypeId, tagId, resourceTableId, empRecordId, tag, tagType);\n      }\n\n      public Builder fromTagReference(TagReference in) {\n         return this\n                 .id(in.getId())\n                 .usrRecordId(in.getUsrRecordId())\n                 .tagTypeId(in.getTagTypeId())\n                 .tagId(in.getTagId())\n                 .resourceTableId(in.getResourceTableId())\n                 .empRecordId(in.getResourceTableId())\n                 .tag(in.getTag())\n                 .tagType(in.getTagType());\n      }\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/domain/TagType.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.domain;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport org.jclouds.javax.annotation.Nullable;\n\nimport java.beans.ConstructorProperties;\n\npublic class TagType {\n   private final String keyName;\n   private final String description;\n\n   @ConstructorProperties({\"keyName\", \"description\"} )\n   public TagType(@Nullable String keyName, @Nullable String description) {\n      this.keyName = keyName;\n      this.description = description;\n   }\n\n   public String getKeyName() {\n      return keyName;\n   }\n\n   public String getDescription() {\n      return description;\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o) return true;\n      if (o == null || getClass() != o.getClass()) return false;\n\n      TagType that = (TagType) o;\n\n      return Objects.equal(this.keyName, that.keyName) &&\n              Objects.equal(this.description, that.description);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(keyName, description);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this)\n              .add(\"keyName\", keyName)\n              .add(\"description\", description)\n              .toString();\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().fromTagType(this);\n   }\n\n   public static class Builder {\n      private String keyName;\n      private String description;\n\n      /**\n       * @see org.jclouds.softlayer.domain.TagType#getKeyName()\n       */\n      public Builder keyName(String keyName) {\n         this.keyName = keyName;\n         return this;\n      }\n\n      /**\n       * @see TagType#getDescription()\n       */\n      public Builder description(String description) {\n         this.description = description;\n         return this;\n      }\n\n      public TagType build() {\n         return new TagType(keyName, description);\n      }\n\n      public Builder fromTagType(TagType in) {\n         return this\n                 .keyName(in.getKeyName())\n                 .description(in.getDescription());\n      }\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/domain/VirtualDiskImage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport java.beans.ConstructorProperties;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Class VirtualDiskImage\n *\n * @see <a href= \"http://sldn.softlayer.com/reference/datatypes/SoftLayer_Virtual_Disk_Image\"/>\n */\npublic class VirtualDiskImage {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().fromVirtualDiskImage(this);\n   }\n\n   public static class Builder {\n\n      protected int id;\n      protected String uuid;\n      protected float capacity;\n      protected String units;\n      protected int typeId;\n      protected String description;\n      protected String name;\n      protected int storageRepositoryId;\n      protected ImmutableSet.Builder<VirtualDiskImageSoftware> softwareReferences = ImmutableSet.builder();\n\n      /**\n       * @see org.jclouds.softlayer.domain.VirtualDiskImage#getId()\n       */\n      public Builder id(int id) {\n         this.id = id;\n         return this;\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.VirtualDiskImage#getUuid()\n       */\n      public Builder uuid(String uuid) {\n         this.uuid = uuid;\n         return this;\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.VirtualDiskImage#getCapacity()\n       */\n      public Builder capacity(float capacity) {\n         this.capacity = capacity;\n         return this;\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.VirtualDiskImage#getUnits()\n       */\n      public Builder units(String units) {\n         this.units = units;\n         return this;\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.VirtualDiskImage#getBuilderypeId()\n       */\n      public Builder typeId(int typeId) {\n         this.typeId = typeId;\n         return this;\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.VirtualDiskImage#getDescription()\n       */\n      public Builder description(String description) {\n         this.description = description;\n         return this;\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.VirtualDiskImage#getName()\n       */\n      public Builder name(String name) {\n         this.name = name;\n         return this;\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.VirtualDiskImage#getStorageRepositoryId()\n       */\n      public Builder storageRepositoryId(int storageRepositoryId) {\n         this.storageRepositoryId = storageRepositoryId;\n         return this;\n      }\n\n      public Builder softwareReferences(Set<VirtualDiskImageSoftware> softwareReferences) {\n         this.softwareReferences.addAll(checkNotNull(softwareReferences, \"softwareReferences\"));\n         return this;\n      }\n\n      public Builder softwareReferences(VirtualDiskImageSoftware... in) {\n         return softwareReferences(ImmutableSet.copyOf(in));\n      }\n\n      public VirtualDiskImage build() {\n         return new VirtualDiskImage(id, uuid, capacity, units, typeId, description, name,\n                 storageRepositoryId, softwareReferences.build());\n      }\n\n      public Builder fromVirtualDiskImage(VirtualDiskImage in) {\n         return this\n                 .id(in.getId())\n                 .uuid(in.getUuid())\n                 .capacity(in.getCapacity())\n                 .units(in.getUnits())\n                 .typeId(in.getBuilderypeId())\n                 .description(in.getDescription())\n                 .name(in.getName())\n                 .storageRepositoryId(in.getStorageRepositoryId())\n                 .softwareReferences(in.getSoftwareReferences());\n      }\n   }\n\n   private final int id;\n   private final String uuid;\n   private final float capacity;\n   private final String units;\n   private final int typeId;\n   private final String description;\n   private final String name;\n   private final int storageRepositoryId;\n   private final Set<VirtualDiskImageSoftware> softwareReferences;\n\n   @ConstructorProperties({\n           \"id\", \"uuid\", \"capacity\", \"units\", \"typeId\", \"description\", \"name\", \"storageRepositoryId\", \"softwareReferences\"\n   })\n   public VirtualDiskImage(int id, @Nullable String uuid, float capacity, @Nullable String units, int typeId,\n                           @Nullable String description, @Nullable String name, int storageRepositoryId,\n                           @Nullable Set<VirtualDiskImageSoftware> softwareReferences) {\n      this.id = id;\n      this.uuid = uuid;\n      this.capacity = capacity;\n      this.units = units;\n      this.typeId = typeId;\n      this.description = description;\n      this.name = name;\n      this.storageRepositoryId = storageRepositoryId;\n      this.softwareReferences = softwareReferences == null ? ImmutableSet.<VirtualDiskImageSoftware>of() :\n              ImmutableSet.copyOf(softwareReferences);\n   }\n\n   public int getId() {\n      return id;\n   }\n\n   public String getUuid() {\n      return uuid;\n   }\n\n   public float getCapacity() {\n      return capacity;\n   }\n\n   public String getUnits() {\n      return units;\n   }\n\n   public int getBuilderypeId() {\n      return typeId;\n   }\n\n   public String getDescription() {\n      return description;\n   }\n\n   public String getName() {\n      return name;\n   }\n\n   public int getStorageRepositoryId() {\n      return storageRepositoryId;\n   }\n\n   public Set<VirtualDiskImageSoftware> getSoftwareReferences() {\n      return softwareReferences;\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o) return true;\n      if (o == null || getClass() != o.getClass()) return false;\n\n      VirtualDiskImage that = (VirtualDiskImage) o;\n\n      return Objects.equal(this.id, that.id) &&\n              Objects.equal(this.uuid, that.uuid) &&\n              Objects.equal(this.capacity, that.capacity) &&\n              Objects.equal(this.units, that.units) &&\n              Objects.equal(this.typeId, that.typeId) &&\n              Objects.equal(this.description, that.description) &&\n              Objects.equal(this.name, that.name) &&\n              Objects.equal(this.storageRepositoryId, that.storageRepositoryId) &&\n              Objects.equal(this.softwareReferences, that.softwareReferences);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, uuid, capacity, units, typeId, description,\n              name, storageRepositoryId, softwareReferences);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this)\n              .add(\"id\", id)\n              .add(\"uuid\", uuid)\n              .add(\"capacity\", capacity)\n              .add(\"units\", units)\n              .add(\"typeId\", typeId)\n              .add(\"description\", description)\n              .add(\"name\", name)\n              .add(\"storageRepositoryId\", storageRepositoryId)\n              .add(\"softwareReferences\", softwareReferences)\n              .toString();\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/domain/VirtualDiskImageSoftware.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\npublic class VirtualDiskImageSoftware {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().fromVirtualDiskImageSoftware(this);\n   }\n\n   public static class Builder {\n\n      protected int id;\n      protected int softwareDescriptionId;\n      protected SoftwareDescription softwareDescription;\n\n      /**\n       * @see VirtualDiskImageSoftware#getId()\n       */\n      public Builder id(int id) {\n         this.id = id;\n         return this;\n      }\n\n      /**\n       * @see VirtualDiskImageSoftware#getSoftwareDescriptionId()\n       */\n      public Builder softwareDescriptionId(int softwareDescriptionId) {\n         this.softwareDescriptionId = softwareDescriptionId;\n         return this;\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.VirtualDiskImageSoftware#getSoftwareDescription()\n       */\n      public Builder softwareDescription(SoftwareDescription softwareDescription) {\n         this.softwareDescription = softwareDescription;\n         return this;\n      }\n\n      public VirtualDiskImageSoftware build() {\n         return new VirtualDiskImageSoftware(id, softwareDescriptionId, softwareDescription);\n      }\n\n      public Builder fromVirtualDiskImageSoftware(VirtualDiskImageSoftware in) {\n         return this\n                 .id(in.getId())\n                 .softwareDescriptionId(in.getSoftwareDescriptionId())\n                 .softwareDescription(in.getSoftwareDescription());\n      }\n   }\n\n   private final int id;\n   private final int softwareDescriptionId;\n   private final SoftwareDescription softwareDescription;\n\n   @ConstructorProperties({\"id\", \"softwareDescriptionId\", \"softwareDescription\"})\n   public VirtualDiskImageSoftware(int id, int softwareDescriptionId, @Nullable SoftwareDescription softwareDescription) {\n      this.id = id;\n      this.softwareDescriptionId = softwareDescriptionId;\n      this.softwareDescription = softwareDescription;\n   }\n\n   public int getId() {\n      return this.id;\n   }\n\n   public int getSoftwareDescriptionId() {\n      return this.softwareDescriptionId;\n   }\n\n   @Nullable\n   public SoftwareDescription getSoftwareDescription() {\n      return this.softwareDescription;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, softwareDescriptionId, softwareDescription);\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o) return true;\n      if (o == null || getClass() != o.getClass()) return false;\n\n      VirtualDiskImageSoftware that = (VirtualDiskImageSoftware) o;\n\n      return Objects.equal(this.id, that.id) &&\n              Objects.equal(this.softwareDescriptionId, that.softwareDescriptionId) &&\n              Objects.equal(this.softwareDescription, that.softwareDescription);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this)\n              .add(\"id\", id)\n              .add(\"softwareDescriptionId\", softwareDescriptionId)\n              .add(\"softwareDescription\", softwareDescription)\n              .toString();\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/domain/VirtualGuest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport java.beans.ConstructorProperties;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.CaseFormat;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * The virtual guest data type presents the structure in which all virtual guests will be presented.\n * Internally, the structure supports various virtualization platforms with no change to external\n * interaction. <br/>\n * A guest, also known as a virtual server or CloudLayer Computing Instance, represents an\n * allocation of resources on a virtual host.\n *\n * The hostname and domain must be alphanumeric strings that may be separated by periods '.'.\n * The only other allowable special character is the dash '-'.\n * However the special characters '.' and '-' may not be consecutive.\n * Each alphanumeric string separated by a period is considered a label.\n * Labels must begin and end with an alphanumeric character.\n * Each label cannot be solely comprised of digits and must be between 1-63 characters in length.\n * The last label, the TLD (top level domain) must be between 2-6 alphabetic characters.\n * The domain portion must consist of least one label followed by a period '.' then ending with the TLD label.\n * Combining the hostname, followed by a period '.', followed by the domain gives the FQDN (fully qualified domain name),\n * which may not exceed 253 characters in total length.\n *\n * @see <a href=\"http://sldn.softlayer.com/reference/datatypes/SoftLayer_Virtual_Guest\"/>\n */\npublic class VirtualGuest {\n\n   /**\n    * These states come from the powerState field. i.e.\n    * https://api.softlayer.com/rest/v3/SoftLayer_Account/getVirtualGuests/{id}?objectMask=powerState\n    */\n   public static enum State {\n      HALTED,\n      PAUSED,\n      RUNNING,\n      UNRECOGNIZED;\n\n      @Override\n      public String toString() {\n         return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name());\n      }\n\n      public static State fromValue(String state) {\n         try {\n            return valueOf(CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, checkNotNull(state, \"state\")));\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n   }\n\n   public static class BillingItem {\n      private final int id;\n\n      @ConstructorProperties(\"id\")\n      public BillingItem(int id) {\n         this.id = id;\n      }\n\n      @Override\n      public String toString() {\n         return \"[id=\" + id + \"]\";\n      }\n   }\n   \n   public static Builder<?> builder() {\n      return new ConcreteBuilder();\n   }\n\n   public Builder<?> toBuilder() {\n      return new ConcreteBuilder().fromVirtualGuest(this);\n   }\n\n   public abstract static class Builder<T extends Builder<T>>  {\n      protected abstract T self();\n\n      protected int accountId;\n      protected Date createDate;\n      protected String domain;\n      protected String fullyQualifiedDomainName;\n      protected String hostname;\n      protected int id;\n      protected Date lastVerifiedDate;\n      protected int maxCpu;\n      protected String maxCpuUnits;\n      protected int maxMemory;\n      protected Date metricPollDate;\n      protected Date modifyDate;\n      protected String notes;\n      protected int startCpus;\n      protected int statusId;\n      protected String uuid;\n      protected String primaryBackendIpAddress;\n      protected String primaryIpAddress;\n      protected int billingItemId;\n      protected OperatingSystem operatingSystem;\n      protected String operatingSystemReferenceCode;\n      protected Datacenter datacenter;\n      protected PowerState powerState;\n      protected SoftwareLicense softwareLicense;\n      protected int activeTransactionCount;\n      protected List<VirtualGuestBlockDevice> blockDevices;\n      protected boolean hourlyBillingFlag;\n      protected boolean localDiskFlag;\n      protected boolean dedicatedAccountHostOnlyFlag;\n      protected boolean privateNetworkOnlyFlag;\n      protected VirtualGuestBlockDeviceTemplateGroup blockDeviceTemplateGroup;\n      protected Set<VirtualGuestNetworkComponent> networkComponents;\n      protected Set<TagReference> tagReferences;\n      protected VirtualGuestNetworkComponent primaryNetworkComponent;\n      protected VirtualGuestNetworkComponent primaryBackendNetworkComponent;\n      protected String postInstallScriptUri;\n      protected VirtualGuestAttribute virtualGuestAttribute;\n      protected Set<SecuritySshKey> sshKeys;\n\n      /**\n       * @see VirtualGuest#getAccountId()\n       */\n      public T accountId(int accountId) {\n         this.accountId = accountId;\n         return self();\n      }\n\n      /**\n       * @see VirtualGuest#getCreateDate()\n       */\n      public T createDate(Date createDate) {\n         this.createDate = createDate;\n         return self();\n      }\n\n      /**\n       * @see VirtualGuest#isDedicatedAccountHostOnly()\n       */\n      public T dedicatedAccountHostOnly(boolean dedicatedAccountHostOnlyFlag) {\n         this.dedicatedAccountHostOnlyFlag = dedicatedAccountHostOnlyFlag;\n         return self();\n      }\n\n      /**\n       * @see VirtualGuest#getDomain()\n       */\n      public T domain(String domain) {\n         this.domain = domain;\n         return self();\n      }\n\n      /**\n       * @see VirtualGuest#getFullyQualifiedDomainName()\n       */\n      public T fullyQualifiedDomainName(String fullyQualifiedDomainName) {\n         this.fullyQualifiedDomainName = fullyQualifiedDomainName;\n         return self();\n      }\n\n      /**\n       * @see VirtualGuest#getHostname()\n       */\n      public T hostname(String hostname) {\n         this.hostname = hostname;\n         return self();\n      }\n\n      /**\n       * @see VirtualGuest#getId()\n       */\n      public T id(int id) {\n         this.id = id;\n         return self();\n      }\n\n      /**\n       * @see VirtualGuest#getLastVerifiedDate()\n       */\n      public T lastVerifiedDate(Date lastVerifiedDate) {\n         this.lastVerifiedDate = lastVerifiedDate;\n         return self();\n      }\n\n      /**\n       * @see VirtualGuest#getMaxCpu()\n       */\n      public T maxCpu(int maxCpu) {\n         this.maxCpu = maxCpu;\n         return self();\n      }\n\n      /**\n       * @see VirtualGuest#getMaxCpuUnits()\n       */\n      public T maxCpuUnits(String maxCpuUnits) {\n         this.maxCpuUnits = maxCpuUnits;\n         return self();\n      }\n\n      /**\n       * @see VirtualGuest#getMaxMemory()\n       */\n      public T maxMemory(int maxMemory) {\n         this.maxMemory = maxMemory;\n         return self();\n      }\n\n      /**\n       * @see VirtualGuest#getMetricPollDate()\n       */\n      public T metricPollDate(Date metricPollDate) {\n         this.metricPollDate = metricPollDate;\n         return self();\n      }\n\n      /**\n       * @see VirtualGuest#getModifyDate()\n       */\n      public T modifyDate(Date modifyDate) {\n         this.modifyDate = modifyDate;\n         return self();\n      }\n\n      /**\n       * @see VirtualGuest#getNotes()\n       */\n      public T notes(String notes) {\n         this.notes = notes;\n         return self();\n      }\n\n      /**\n       * @see VirtualGuest#getStartCpus()\n       */\n      public T startCpus(int startCpus) {\n         this.startCpus = startCpus;\n         return self();\n      }\n\n      /**\n       * @see VirtualGuest#getStatusId()\n       */\n      public T statusId(int statusId) {\n         this.statusId = statusId;\n         return self();\n      }\n\n      /**\n       * @see VirtualGuest#getUuid()\n       */\n      public T uuid(String uuid) {\n         this.uuid = uuid;\n         return self();\n      }\n\n      /**\n       * @see VirtualGuest#getPrimaryBackendIpAddress()\n       */\n      public T primaryBackendIpAddress(String primaryBackendIpAddress) {\n         this.primaryBackendIpAddress = primaryBackendIpAddress;\n         return self();\n      }\n\n      /**\n       * @see VirtualGuest#getPrimaryIpAddress()\n       */\n      public T primaryIpAddress(String primaryIpAddress) {\n         this.primaryIpAddress = primaryIpAddress;\n         return self();\n      }\n\n      /**\n       * @see VirtualGuest#getBillingItemId()\n       */\n      public T billingItemId(int billingItemId) {\n         this.billingItemId = billingItemId;\n         return self();\n      }\n\n      /**\n       * @see VirtualGuest#getOperatingSystem()\n       */\n      public T operatingSystem(OperatingSystem operatingSystem) {\n         this.operatingSystem = operatingSystem;\n         return self();\n      }\n\n      /**\n       * @see VirtualGuest#getOperatingSystemReferenceCode()\n       */\n      public T operatingSystemReferenceCode(String operatingSystemReferenceCode) {\n         this.operatingSystemReferenceCode = operatingSystemReferenceCode;\n         return self();\n      }\n\n      /**\n       * @see VirtualGuest#getDatacenter()\n       */\n      public T datacenter(Datacenter datacenter) {\n         this.datacenter = datacenter;\n         return self();\n      }\n\n      /**\n       * @see VirtualGuest#getPowerState()\n       */\n      public T powerState(PowerState powerState) {\n         this.powerState = powerState;\n         return self();\n      }\n\n      /**\n       * @see VirtualGuest#getSoftwareLicense()\n       */\n      public T softwareLicense(SoftwareLicense softwareLicense) {\n         this.softwareLicense = softwareLicense;\n         return self();\n      }\n\n      /**\n       * @see VirtualGuest#getActiveTransactionCount()\n       */\n      public T activeTransactionCount(int activeTransactionCount) {\n         this.activeTransactionCount = activeTransactionCount;\n         return self();\n      }\n\n      /**\n       * @see VirtualGuest#getVirtualGuestBlockDevices()\n       */\n      public T blockDevices(List<VirtualGuestBlockDevice> blockDevices) {\n         this.blockDevices = ImmutableList.copyOf(checkNotNull(blockDevices, \"blockDevices\"));\n         return self();\n      }\n\n      public T blockDevices(VirtualGuestBlockDevice... in) {\n         return blockDevices(ImmutableList.copyOf(checkNotNull(in, \"blockDevices\")));\n      }\n\n      public T hourlyBillingFlag(boolean hourlyBillingFlag) {\n         this.hourlyBillingFlag = hourlyBillingFlag;\n         return self();\n      }\n\n      public T localDiskFlag(boolean localDiskFlag) {\n         this.localDiskFlag = localDiskFlag;\n         return self();\n      }\n\n      public T dedicatedAccountHostOnlyFlag(boolean dedicatedAccountHostOnlyFlag) {\n         this.dedicatedAccountHostOnlyFlag = dedicatedAccountHostOnlyFlag;\n         return self();\n      }\n\n      public T privateNetworkOnlyFlag(boolean privateNetworkOnlyFlag) {\n         this.privateNetworkOnlyFlag = privateNetworkOnlyFlag;\n         return self();\n      }\n\n      public T blockDeviceTemplateGroup(VirtualGuestBlockDeviceTemplateGroup blockDeviceTemplateGroup) {\n         this.blockDeviceTemplateGroup = blockDeviceTemplateGroup;\n         return self();\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.VirtualGuest#getPrimaryBackendNetworkComponent() ()\n       */\n      public T networkComponents(Set<VirtualGuestNetworkComponent> networkComponents) {\n         this.networkComponents = ImmutableSet.copyOf(checkNotNull(networkComponents, \"networkComponents\"));\n         return self();\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.VirtualGuest#getPrimaryBackendNetworkComponent() ()\n       */\n      public T networkComponents(VirtualGuestNetworkComponent... in) {\n         return networkComponents(ImmutableSet.copyOf(checkNotNull(in, \"networkComponents\")));\n      }\n\n      public T tagReferences(Set<TagReference> tagReferences) {\n         this.tagReferences = ImmutableSet.copyOf(checkNotNull(tagReferences, \"tagReferences\"));\n         return self();\n      }\n\n      public T tagReferences(TagReference... in) {\n         return tagReferences(ImmutableSet.copyOf(checkNotNull(in, \"tagReferences\")));\n      }\n\n      public T primaryNetworkComponent(VirtualGuestNetworkComponent primaryNetworkComponent) {\n         this.primaryNetworkComponent = primaryNetworkComponent;\n         return self();\n      }\n\n      public T primaryBackendNetworkComponent(VirtualGuestNetworkComponent primaryBackendNetworkComponent) {\n         this.primaryBackendNetworkComponent = primaryBackendNetworkComponent;\n         return self();\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.VirtualGuest#getPostInstallScriptUri() ()\n       */\n      public T postInstallScriptUri(String postInstallScriptUri) {\n         this.postInstallScriptUri = postInstallScriptUri;\n         return self();\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.VirtualGuest#getVirtualGuestAttribute() ()\n       */\n      public T virtualGuestAttribute(VirtualGuestAttribute virtualGuestAttribute) {\n         this.virtualGuestAttribute = virtualGuestAttribute;\n         return self();\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.VirtualGuest#getSshKeys() ()\n       */\n      public T sshKeys(Set<SecuritySshKey> sshKeys) {\n         this.sshKeys = ImmutableSet.copyOf(checkNotNull(sshKeys, \"sshKeys\"));\n         return self();\n      }\n\n      public T sshKeys(SecuritySshKey... in) {\n         return sshKeys(ImmutableSet.copyOf(checkNotNull(in, \"sshKeys\")));\n      }\n\n      public VirtualGuest build() {\n         return new VirtualGuest(accountId, createDate, domain, fullyQualifiedDomainName, hostname,\n               id, lastVerifiedDate, maxCpu, maxCpuUnits, maxMemory, metricPollDate, modifyDate, notes,\n               startCpus, statusId, uuid, primaryBackendIpAddress, primaryIpAddress, new BillingItem(billingItemId),\n               operatingSystem, operatingSystemReferenceCode, datacenter, powerState, softwareLicense,\n               activeTransactionCount, blockDevices, hourlyBillingFlag, localDiskFlag, dedicatedAccountHostOnlyFlag,\n               privateNetworkOnlyFlag, blockDeviceTemplateGroup, networkComponents, tagReferences,\n               primaryNetworkComponent, primaryBackendNetworkComponent, postInstallScriptUri, virtualGuestAttribute,\n               sshKeys);\n      }\n\n      public T fromVirtualGuest(VirtualGuest in) {\n         return this\n               .accountId(in.getAccountId())\n               .createDate(in.getCreateDate())\n               .dedicatedAccountHostOnly(in.isDedicatedAccountHostOnly())\n               .domain(in.getDomain())\n               .fullyQualifiedDomainName(in.getFullyQualifiedDomainName())\n               .hostname(in.getHostname())\n               .id(in.getId())\n               .lastVerifiedDate(in.getLastVerifiedDate())\n               .maxCpu(in.getMaxCpu())\n               .maxCpuUnits(in.getMaxCpuUnits())\n               .maxMemory(in.getMaxMemory())\n               .metricPollDate(in.getMetricPollDate())\n               .modifyDate(in.getModifyDate())\n               .notes(in.getNotes())\n               .startCpus(in.getStartCpus())\n               .statusId(in.getStatusId())\n               .uuid(in.getUuid())\n               .primaryBackendIpAddress(in.getPrimaryBackendIpAddress())\n               .primaryIpAddress(in.getPrimaryIpAddress())\n               .billingItemId(in.getBillingItemId())\n               .operatingSystem(in.getOperatingSystem())\n               .operatingSystemReferenceCode(in.getOperatingSystemReferenceCode())\n               .datacenter(in.getDatacenter())\n               .powerState(in.getPowerState())\n               .activeTransactionCount(in.getActiveTransactionCount())\n               .hourlyBillingFlag(in.isHourlyBillingFlag())\n               .localDiskFlag(in.isLocalDiskFlag())\n               .dedicatedAccountHostOnlyFlag(in.isDedicatedAccountHostOnly())\n               .privateNetworkOnlyFlag(in.isPrivateNetworkOnly())\n               .blockDeviceTemplateGroup(in.getVirtualGuestBlockDeviceTemplateGroup())\n               .networkComponents(in.getVirtualGuestNetworkComponents())\n               .tagReferences(in.getTagReferences())\n               .postInstallScriptUri(in.getPostInstallScriptUri())\n               .virtualGuestAttribute(in.getVirtualGuestAttribute())\n               .sshKeys(in.getSshKeys());\n      }\n   }\n\n   private static class ConcreteBuilder extends Builder<ConcreteBuilder> {\n      @Override\n      protected ConcreteBuilder self() {\n         return this;\n      }\n   }\n\n   private final int accountId;\n   private final Date createDate;\n   private final String domain;\n   private final String fullyQualifiedDomainName;\n   private final String hostname;\n   private final int id;\n   private final Date lastVerifiedDate;\n   private final int maxCpu;\n   private final String maxCpuUnits;\n   private final int maxMemory;\n   private final Date metricPollDate;\n   private final Date modifyDate;\n   private final String notes;\n   private final int startCpus;\n   private final int statusId;\n   private final String uuid;\n   private final String primaryBackendIpAddress;\n   private final String primaryIpAddress;\n   private final int billingItemId;\n   private final OperatingSystem operatingSystem;\n   private final String operatingSystemReferenceCode;\n   private final Datacenter datacenter;\n   private final PowerState powerState;\n   private final SoftwareLicense softwareLicense;\n   private final int activeTransactionCount;\n   private final List<VirtualGuestBlockDevice> blockDevices;\n   private final boolean hourlyBillingFlag;\n   private final boolean localDiskFlag;\n   private final boolean dedicatedAccountHostOnlyFlag;\n   private final boolean privateNetworkOnlyFlag;\n   private final VirtualGuestBlockDeviceTemplateGroup blockDeviceTemplateGroup;\n   private final Set<VirtualGuestNetworkComponent> networkComponents;\n   private final Set<TagReference> tagReferences;\n   private final VirtualGuestNetworkComponent primaryNetworkComponent;\n   private final VirtualGuestNetworkComponent primaryBackendNetworkComponent;\n   private final String postInstallScriptUri;\n   private final VirtualGuestAttribute virtualGuestAttribute;\n   private final Set<SecuritySshKey> sshKeys;\n\n   @ConstructorProperties({\"accountId\", \"createDate\", \"domain\", \"fullyQualifiedDomainName\", \"hostname\", \"id\",\n           \"lastVerifiedDate\", \"maxCpu\", \"maxCpuUnits\", \"maxMemory\", \"metricPollDate\", \"modifyDate\", \"notes\",\n           \"startCpus\", \"statusId\", \"uuid\", \"primaryBackendIpAddress\", \"primaryIpAddress\", \"billingItem\",\n           \"operatingSystem\", \"operatingSystemReferenceCode\", \"datacenter\", \"powerState\", \"softwareLicense\",\n           \"activeTransactionCount\", \"blockDevices\", \"hourlyBillingFlag\", \"localDiskFlag\",\n           \"dedicatedAccountHostOnlyFlag\", \"privateNetworkOnlyFlag\", \"blockDeviceTemplateGroup\", \"networkComponents\",\n           \"tagReferences\", \"primaryNetworkComponent\", \"primaryBackendNetworkComponent\", \"postInstallScriptUri\",\n           \"virtualGuestAttribute\", \"sshKeys\"})\n   protected VirtualGuest(int accountId, @Nullable Date createDate, @Nullable String domain,\n                          @Nullable String fullyQualifiedDomainName, @Nullable String hostname, int id, @Nullable Date lastVerifiedDate,\n                          int maxCpu, @Nullable String maxCpuUnits, int maxMemory, @Nullable Date metricPollDate, @Nullable Date modifyDate,\n                          @Nullable String notes, int startCpus, int statusId, @Nullable String uuid,\n                          @Nullable String primaryBackendIpAddress, @Nullable String primaryIpAddress, @Nullable BillingItem billingItem,\n                          @Nullable OperatingSystem operatingSystem, @Nullable String operatingSystemReferenceCode,\n                          @Nullable Datacenter datacenter, @Nullable PowerState powerState, @Nullable SoftwareLicense softwareLicense,\n                          int activeTransactionCount, @Nullable List<VirtualGuestBlockDevice> blockDevices,\n                          boolean hourlyBillingFlag, boolean localDiskFlag, boolean dedicatedAccountHostOnlyFlag,\n                          boolean privateNetworkOnlyFlag, @Nullable VirtualGuestBlockDeviceTemplateGroup blockDeviceTemplateGroup,\n                          @Nullable Set<VirtualGuestNetworkComponent> networkComponents,\n                          @Nullable Set<TagReference> tagReferences,\n                          @Nullable VirtualGuestNetworkComponent primaryNetworkComponent,\n                          @Nullable VirtualGuestNetworkComponent primaryBackendNetworkComponent,\n                          @Nullable String postInstallScriptUri, @Nullable VirtualGuestAttribute virtualGuestAttribute,\n                          @Nullable Set<SecuritySshKey> sshKeys) {\n      this.accountId = accountId;\n      this.createDate = createDate;\n      this.domain = domain;\n      this.fullyQualifiedDomainName = fullyQualifiedDomainName;\n      this.hostname = hostname;\n      this.id = id;\n      this.lastVerifiedDate = lastVerifiedDate;\n      this.maxCpu = maxCpu;\n      this.maxCpuUnits = maxCpuUnits;\n      this.maxMemory = maxMemory;\n      this.metricPollDate = metricPollDate;\n      this.modifyDate = modifyDate;\n      this.notes = notes;\n      this.startCpus = startCpus;\n      this.statusId = statusId;\n      this.uuid = uuid;\n      this.primaryBackendIpAddress = primaryBackendIpAddress;\n      this.primaryIpAddress = primaryIpAddress;\n      this.blockDevices = blockDevices;\n      this.billingItemId = billingItem == null ? 0 : billingItem.id;\n      this.operatingSystem = operatingSystem;\n      this.operatingSystemReferenceCode = operatingSystemReferenceCode;\n      this.datacenter = datacenter;\n      this.powerState = powerState;\n      this.softwareLicense = softwareLicense;\n      this.activeTransactionCount = activeTransactionCount;\n      this.hourlyBillingFlag = hourlyBillingFlag;\n      this.localDiskFlag = localDiskFlag;\n      this.dedicatedAccountHostOnlyFlag = dedicatedAccountHostOnlyFlag;\n      this.privateNetworkOnlyFlag = privateNetworkOnlyFlag;\n      this.blockDeviceTemplateGroup = blockDeviceTemplateGroup;\n      this.networkComponents = networkComponents;\n      this.tagReferences = tagReferences;\n      this.primaryNetworkComponent = primaryNetworkComponent;\n      this.primaryBackendNetworkComponent = primaryBackendNetworkComponent;\n      this.postInstallScriptUri = postInstallScriptUri;\n      this.virtualGuestAttribute = virtualGuestAttribute;\n      this.sshKeys = sshKeys;\n   }\n\n   /**\n    * @return A computing instance's associated account id\n    */\n   public int getAccountId() {\n      return this.accountId;\n   }\n\n   /**\n    * @return The date a virtual computing instance was created.\n    */\n   @Nullable\n   public Date getCreateDate() {\n      return this.createDate;\n   }\n\n   /**\n    * @return A computing instance's domain name\n    */\n   @Nullable\n   public String getDomain() {\n      return this.domain;\n   }\n\n   /**\n    * @return A name reflecting the hostname and domain of the computing instance.\n    */\n   @Nullable\n   public String getFullyQualifiedDomainName() {\n      return this.fullyQualifiedDomainName;\n   }\n\n   /**\n    * @return A virtual computing instance's hostname\n    */\n   @Nullable\n   public String getHostname() {\n      return this.hostname;\n   }\n\n   /**\n    * @return Unique ID for a computing instance.\n    */\n   public int getId() {\n      return this.id;\n   }\n\n   /**\n    * @return The last timestamp of when the guest was verified as a resident virtual machine on the\n   host's hypervisor platform.\n    */\n   @Nullable\n   public Date getLastVerifiedDate() {\n      return this.lastVerifiedDate;\n   }\n\n   /**\n    * @return The maximum amount of CPU resources a computing instance may utilize.\n    */\n   public int getMaxCpu() {\n      return this.maxCpu;\n   }\n\n   /**\n    * @return The unit of the maximum amount of CPU resources a computing instance may utilize.\n    */\n   @Nullable\n   public String getMaxCpuUnits() {\n      return this.maxCpuUnits;\n   }\n\n   /**\n    * @return The maximum amount of memory a computing instance may utilize.\n    */\n   public int getMaxMemory() {\n      return this.maxMemory;\n   }\n\n   /**\n    * @return The date of the most recent metric tracking poll performed.\n    */\n   @Nullable\n   public Date getMetricPollDate() {\n      return this.metricPollDate;\n   }\n\n   /**\n    * @return The date a virtual computing instance was last modified.\n    */\n   @Nullable\n   public Date getModifyDate() {\n      return this.modifyDate;\n   }\n\n   /**\n    * @return A small note about a cloud instance to use at your discretion.\n    */\n   @Nullable\n   public String getNotes() {\n      return this.notes;\n   }\n\n   /**\n    * @return The number of CPUs available to a computing instance upon startup.\n    */\n   public int getStartCpus() {\n      return this.startCpus;\n   }\n\n   /**\n    * @return A computing instances status ID\n    */\n   public int getStatusId() {\n      return this.statusId;\n   }\n\n   /**\n    * @return Unique ID for a computing instance's record on a virtualization platform.\n    */\n   @Nullable\n   public String getUuid() {\n      return this.uuid;\n   }\n\n   /**\n    * @return private ip address\n    */\n   @Nullable\n   public String getPrimaryBackendIpAddress() {\n      return this.primaryBackendIpAddress;\n   }\n\n   /**\n    * @return public ip address\n    */\n   @Nullable\n   public String getPrimaryIpAddress() {\n      return this.primaryIpAddress;\n   }\n\n   /**\n    * @return The billing item for a CloudLayer Compute Instance.\n    */\n   public int getBillingItemId() {\n      return this.billingItemId;\n   }\n\n   /**\n    * @return A guest's operating system.\n    */\n   @Nullable\n   public OperatingSystem getOperatingSystem() {\n      return this.operatingSystem;\n   }\n\n   public String getOperatingSystemReferenceCode() {\n      return this.operatingSystemReferenceCode;\n   }\n\n   /**\n    * @return The guest's datacenter\n    */\n   @Nullable\n   public Datacenter getDatacenter() {\n      return this.datacenter;\n   }\n\n   /**\n    * @return The softwareLicense of a virtual guest.\n    */\n   @Nullable\n   public SoftwareLicense getSoftwareLicense() {\n      return this.softwareLicense;\n   }\n\n   /**\n    * @return The current power state of a virtual guest.\n    */\n   @Nullable\n   public PowerState getPowerState() {\n      return this.powerState;\n   }\n\n   public int getActiveTransactionCount() {\n      return activeTransactionCount;\n   }\n\n   @Nullable\n   public List<VirtualGuestBlockDevice> getVirtualGuestBlockDevices() {\n      return blockDevices;\n   }\n\n   public boolean isHourlyBillingFlag() {\n      return this.hourlyBillingFlag;\n   }\n\n   public boolean isLocalDiskFlag() {\n      return localDiskFlag;\n   }\n\n   /**\n    * @return Whether the computing instance only has access to the private network.\n    */\n   public boolean isPrivateNetworkOnly() {\n      return this.privateNetworkOnlyFlag;\n   }\n\n   /**\n    * @return When true this flag specifies that a compute instance is to run on hosts that only\n   have guests from the same account.\n    */\n   public boolean isDedicatedAccountHostOnly() {\n      return this.dedicatedAccountHostOnlyFlag;\n   }\n\n\n   public VirtualGuestBlockDeviceTemplateGroup getVirtualGuestBlockDeviceTemplateGroup() {\n      return blockDeviceTemplateGroup;\n   }\n\n   @Nullable\n   public Set<VirtualGuestNetworkComponent> getVirtualGuestNetworkComponents() {\n      return networkComponents;\n   }\n\n   @Nullable\n   public Set<TagReference> getTagReferences() {\n      return tagReferences;\n   }\n\n   public VirtualGuestNetworkComponent getPrimaryNetworkComponent() {\n      return primaryNetworkComponent;\n   }\n\n   public VirtualGuestNetworkComponent getPrimaryBackendNetworkComponent() {\n      return primaryBackendNetworkComponent;\n   }\n\n   public String getPostInstallScriptUri() {\n      return postInstallScriptUri;\n   }\n\n   public VirtualGuestAttribute getVirtualGuestAttribute() {\n      return virtualGuestAttribute;\n   }\n\n   public Set<SecuritySshKey> getSshKeys() {\n      return sshKeys;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(accountId, createDate, domain, fullyQualifiedDomainName,\n              hostname, id, lastVerifiedDate, maxCpu, maxCpuUnits, maxMemory, metricPollDate, modifyDate, notes,\n              startCpus, statusId, uuid, primaryBackendIpAddress, primaryIpAddress,\n              billingItemId, operatingSystem, datacenter, powerState, softwareLicense, blockDevices,\n              hourlyBillingFlag, localDiskFlag, dedicatedAccountHostOnlyFlag, privateNetworkOnlyFlag,\n              blockDeviceTemplateGroup, tagReferences, primaryNetworkComponent, primaryBackendNetworkComponent,\n              postInstallScriptUri, virtualGuestAttribute, sshKeys);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) return true;\n      if (obj == null || getClass() != obj.getClass()) return false;\n      VirtualGuest that = VirtualGuest.class.cast(obj);\n      return Objects.equal(this.accountId, that.accountId)\n            && Objects.equal(this.createDate, that.createDate)\n            && Objects.equal(this.domain, that.domain)\n            && Objects.equal(this.fullyQualifiedDomainName, that.fullyQualifiedDomainName)\n            && Objects.equal(this.hostname, that.hostname)\n            && Objects.equal(this.id, that.id)\n            && Objects.equal(this.lastVerifiedDate, that.lastVerifiedDate)\n            && Objects.equal(this.maxCpu, that.maxCpu)\n            && Objects.equal(this.maxCpuUnits, that.maxCpuUnits)\n            && Objects.equal(this.maxMemory, that.maxMemory)\n            && Objects.equal(this.metricPollDate, that.metricPollDate)\n            && Objects.equal(this.modifyDate, that.modifyDate)\n            && Objects.equal(this.notes, that.notes)\n            && Objects.equal(this.startCpus, that.startCpus)\n            && Objects.equal(this.statusId, that.statusId)\n            && Objects.equal(this.uuid, that.uuid)\n            && Objects.equal(this.primaryBackendIpAddress, that.primaryBackendIpAddress)\n            && Objects.equal(this.primaryIpAddress, that.primaryIpAddress)\n            && Objects.equal(this.billingItemId, that.billingItemId)\n            && Objects.equal(this.operatingSystem, that.operatingSystem)\n            && Objects.equal(this.operatingSystemReferenceCode, that.operatingSystemReferenceCode)\n            && Objects.equal(this.datacenter, that.datacenter)\n            && Objects.equal(this.powerState, that.powerState)\n            && Objects.equal(this.softwareLicense, that.softwareLicense)\n            && Objects.equal(this.blockDevices, that.blockDevices)\n            && Objects.equal(this.hourlyBillingFlag, that.hourlyBillingFlag)\n            && Objects.equal(this.localDiskFlag, that.localDiskFlag)\n            && Objects.equal(this.dedicatedAccountHostOnlyFlag, that.dedicatedAccountHostOnlyFlag)\n            && Objects.equal(this.privateNetworkOnlyFlag, that.privateNetworkOnlyFlag)\n            && Objects.equal(this.blockDeviceTemplateGroup, that.blockDeviceTemplateGroup)\n            && Objects.equal(this.networkComponents, that.networkComponents)\n            && Objects.equal(this.tagReferences, that.tagReferences)\n            && Objects.equal(this.sshKeys, that.sshKeys);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this)\n              .add(\"accountId\", accountId)\n              .add(\"createDate\", createDate)\n              .add(\"domain\", domain)\n              .add(\"fullyQualifiedDomainName\", fullyQualifiedDomainName)\n              .add(\"hostname\", hostname)\n              .add(\"id\", id)\n              .add(\"lastVerifiedDate\", lastVerifiedDate)\n              .add(\"maxCpu\", maxCpu)\n              .add(\"maxCpuUnits\", maxCpuUnits)\n              .add(\"maxMemory\", maxMemory)\n              .add(\"metricPollDate\", metricPollDate)\n              .add(\"modifyDate\", modifyDate)\n              .add(\"notes\", notes)\n              .add(\"startCpus\", startCpus)\n              .add(\"statusId\", statusId)\n              .add(\"uuid\", uuid)\n              .add(\"primaryBackendIpAddress\", primaryBackendIpAddress)\n              .add(\"primaryIpAddress\", primaryIpAddress)\n              .add(\"billingItemId\", billingItemId)\n              .add(\"operatingSystem\", operatingSystem)\n              .add(\"operatingSystemReferenceCode\", operatingSystemReferenceCode)\n              .add(\"datacenter\", datacenter)\n              .add(\"powerState\", powerState)\n              .add(\"softwareLicense\", softwareLicense)\n              .add(\"activeTransactionCount\", activeTransactionCount)\n              .add(\"blockDevices\", blockDevices)\n              .add(\"hourlyBillingFlag\", hourlyBillingFlag)\n              .add(\"localDiskFlag\", localDiskFlag)\n              .add(\"dedicatedAccountHostOnlyFlag\", dedicatedAccountHostOnlyFlag)\n              .add(\"privateNetworkOnlyFlag\", privateNetworkOnlyFlag)\n              .add(\"blockDeviceTemplateGroup\", blockDeviceTemplateGroup)\n              .add(\"networkComponents\", networkComponents)\n              .add(\"tagReferences\", tagReferences)\n              .add(\"primaryNetworkComponent\", primaryNetworkComponent)\n              .add(\"primaryBackendNetworkComponent\", primaryBackendNetworkComponent)\n              .add(\"postInstallScriptUri\", postInstallScriptUri)\n              .add(\"virtualGuestAttribute\", virtualGuestAttribute)\n              .add(\"sshKeys\", sshKeys)\n              .toString();\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/domain/VirtualGuestAttribute.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport java.beans.ConstructorProperties;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\npublic class VirtualGuestAttribute {\n   private final String value;\n\n   @ConstructorProperties({\"value\"} )\n   public VirtualGuestAttribute(String value) {\n      this.value = checkNotNull(value, \"value\");\n   }\n\n   public String getValue() {\n      return value;\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o) return true;\n      if (o == null || getClass() != o.getClass()) return false;\n\n      VirtualGuestAttribute that = (VirtualGuestAttribute) o;\n\n      return Objects.equal(this.value, that.value);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(value);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this)\n              .add(\"value\", value)\n              .toString();\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().fromVirtualGuestAttribute(this);\n   }\n\n   public static class Builder {\n      private String value;\n\n      /**\n       * @see VirtualGuestAttribute#getValue()\n       */\n      public Builder value(String value) {\n         this.value = value;\n         return this;\n      }\n\n      public VirtualGuestAttribute build() {\n         return new VirtualGuestAttribute(value);\n      }\n\n      public Builder fromVirtualGuestAttribute(VirtualGuestAttribute in) {\n         return this\n                 .value(in.getValue());\n      }\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/domain/VirtualGuestBlockDevice.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\n/**\n * Class VirtualGuestBlockDevice\n *\n * @see <a href= \"http://sldn.softlayer.com/reference/datatypes/SoftLayer_Virtual_Guest_Block_Device\"/>\n */\npublic class VirtualGuestBlockDevice {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().fromVirtualGuestBlockDevice(this);\n   }\n\n   public static class Builder {\n\n      protected int id;\n      protected String uuid;\n      protected int statusId;\n      protected String mountType;\n      protected String mountMode;\n      protected int bootableFlag;\n      protected String device;\n      protected VirtualDiskImage diskImage;\n      protected VirtualGuest guest;\n\n      /**\n       * @see org.jclouds.softlayer.domain.VirtualGuestBlockDevice#getId()\n       */\n      public Builder id(int id) {\n         this.id = id;\n         return this;\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.VirtualGuestBlockDevice#getUuid()\n       */\n      public Builder uuid(String uuid) {\n         this.uuid = uuid;\n         return this;\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.VirtualGuestBlockDevice#getStatusId()\n       */\n      public Builder statusId(int statusId) {\n         this.statusId = statusId;\n         return this;\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.VirtualGuestBlockDevice#getMountType()\n       */\n      public Builder mountType(String mountType) {\n         this.mountType = mountType;\n         return this;\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.VirtualGuestBlockDevice#getMountMode()\n       */\n      public Builder mountMode(String mountMode) {\n         this.mountMode = mountMode;\n         return this;\n      }\n\n      /**\n       * @see VirtualGuestBlockDevice#getBootableFlag()\n       */\n      public Builder bootableFlag(int bootableFlag) {\n         this.bootableFlag = bootableFlag;\n         return this;\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.VirtualGuestBlockDevice#getDevice()\n       */\n      public Builder device(String device) {\n         this.device = device;\n         return this;\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.VirtualGuestBlockDevice#getVirtualDiskImage()\n       */\n      public Builder diskImage(VirtualDiskImage diskImage) {\n         this.diskImage = diskImage;\n         return this;\n      }\n\n      public Builder guest(VirtualGuest guest) {\n         this.guest = guest;\n         return this;\n      }\n\n      public VirtualGuestBlockDevice build() {\n         return new VirtualGuestBlockDevice(id, uuid, statusId, mountType, mountMode, bootableFlag, device,\n                 diskImage, guest);\n      }\n\n      public Builder fromVirtualGuestBlockDevice(VirtualGuestBlockDevice in) {\n         return this\n               .id(in.getId())\n               .uuid(in.getUuid())\n               .statusId(in.getStatusId())\n               .mountMode(in.getMountMode())\n               .mountType(in.getMountType())\n               .bootableFlag(in.getBootableFlag())\n               .device(in.getDevice())\n               .diskImage(in.getVirtualDiskImage())\n               .guest(in.getVirtualGuest());\n      }\n   }\n\n   private final int id;\n   private final String uuid;\n   private final int statusId;\n   private final String mountType;\n   private final String mountMode;\n   private final int bootableFlag;\n   private final String device;\n   private final VirtualDiskImage diskImage;\n   private final VirtualGuest guest;\n\n   @ConstructorProperties({ \"id\", \"uuid\", \"statusId\", \"mountType\", \"mountMode\", \"bootableFlag\", \"device\",\n           \"diskImage\", \"guest\" })\n   protected VirtualGuestBlockDevice(int id, @Nullable String uuid, int statusId,  @Nullable String mountType,\n                                     @Nullable String mountMode, int bootableFlag, String device,\n                                     @Nullable VirtualDiskImage diskImage, @Nullable VirtualGuest guest) {\n      this.id = id;\n      this.uuid = uuid;\n      this.statusId = statusId;\n      this.mountType = mountType;\n      this.mountMode = mountMode;\n      this.bootableFlag = bootableFlag;\n      this.device = checkNotNull(device, \"device\");\n      this.diskImage = diskImage;\n      this.guest = guest;\n   }\n\n   public int getId() {\n      return id;\n   }\n\n   public String getUuid() {\n      return uuid;\n   }\n\n   public int getStatusId() {\n      return statusId;\n   }\n\n   public String getMountType() {\n      return mountType;\n   }\n\n   public String getMountMode() {\n      return mountMode;\n   }\n\n   public int getBootableFlag() {\n      return bootableFlag;\n   }\n\n   public String getDevice() {\n      return device;\n   }\n\n   public VirtualDiskImage getVirtualDiskImage() {\n      return diskImage;\n   }\n\n   public VirtualGuest getVirtualGuest() {\n      return guest;\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o) return true;\n      if (o == null || getClass() != o.getClass()) return false;\n\n      VirtualGuestBlockDevice that = (VirtualGuestBlockDevice) o;\n\n      return Objects.equal(this.id, that.id) &&\n              Objects.equal(this.uuid, that.uuid) &&\n              Objects.equal(this.statusId, that.statusId) &&\n              Objects.equal(this.mountType, that.mountType) &&\n              Objects.equal(this.mountMode, that.mountMode) &&\n              Objects.equal(this.bootableFlag, that.bootableFlag) &&\n              Objects.equal(this.device, that.device) &&\n              Objects.equal(this.diskImage, that.diskImage) &&\n              Objects.equal(this.guest, that.guest);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, uuid, statusId, mountType, mountMode, bootableFlag,\n              device, diskImage, guest);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this)\n              .add(\"id\", id)\n              .add(\"uuid\", uuid)\n              .add(\"statusId\", statusId)\n              .add(\"mountType\", mountType)\n              .add(\"mountMode\", mountMode)\n              .add(\"bootableFlag\", bootableFlag)\n              .add(\"device\", device)\n              .add(\"diskImage\", diskImage)\n              .add(\"guest\", guest)\n              .toString();\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/domain/VirtualGuestBlockDeviceTemplate.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport java.beans.ConstructorProperties;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\n/**\n * Class VirtualGuestBlockDeviceTemplate\n *\n * @see <a href= \"http://sldn.softlayer.com/reference/datatypes/SoftLayer_Virtual_Guest_Block_Device_Template\"/>\n */\npublic class VirtualGuestBlockDeviceTemplate {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().fromVirtualGuestBlockDeviceTemplate(this);\n   }\n\n   public static class Builder {\n\n      protected int id;\n      protected String device;\n      protected int diskImageId;\n      protected float diskSpace;\n      protected int groupId;\n      protected String units;\n      protected VirtualDiskImage diskImage;\n\n      /**\n       * @see org.jclouds.softlayer.domain.VirtualGuestBlockDeviceTemplate#getId()\n       */\n      public Builder id(int id) {\n         this.id = id;\n         return this;\n      }\n\n      /**\n       * @see VirtualGuestBlockDeviceTemplate#getDevice()\n       */\n      public Builder device(String device) {\n         this.device = device;\n         return this;\n      }\n\n      /**\n       * @see VirtualGuestBlockDeviceTemplate#getDiskImage()\n       */\n      public Builder diskImageId(int diskImageId) {\n         this.diskImageId = diskImageId;\n         return this;\n      }\n\n      /**\n       * @see VirtualGuestBlockDeviceTemplate#getDiskSpace()\n       */\n      public Builder diskSpace(float diskSpace) {\n         this.diskSpace = diskSpace;\n         return this;\n      }\n\n      /**\n       * @see VirtualGuestBlockDeviceTemplate#getGroupId()\n       */\n      public Builder groupId(int groupId) {\n         this.groupId = groupId;\n         return this;\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.VirtualGuestBlockDeviceTemplate#getUnits()\n       */\n      public Builder units(String units) {\n         this.units = units;\n         return this;\n      }\n\n      /**\n       * @see VirtualGuestBlockDeviceTemplate#getDiskImage()\n       */\n      public Builder diskImage(VirtualDiskImage diskImage) {\n         this.diskImage = diskImage;\n         return this;\n      }\n\n      public VirtualGuestBlockDeviceTemplate build() {\n         return new VirtualGuestBlockDeviceTemplate(id, device, diskImageId, diskSpace, groupId, units, diskImage);\n      }\n\n      public Builder fromVirtualGuestBlockDeviceTemplate(VirtualGuestBlockDeviceTemplate in) {\n         return this\n                 .id(in.getId())\n                 .device(in.getDevice())\n                 .diskImageId(in.getDiskImageId())\n                 .diskSpace(in.getDiskSpace())\n                 .groupId(in.getGroupId())\n                 .units(in.getUnits())\n                 .diskImage(in.getDiskImage());\n      }\n   }\n\n   private final int id;\n   private final String device;\n   private final int diskImageId;\n   private final float diskSpace;\n   private final int groupId;\n   private final String units;\n   private final VirtualDiskImage diskImage;\n\n   @ConstructorProperties({ \"id\", \"device\", \"diskImageId\", \"diskSpace\", \"groupId\", \"units\", \"diskImage\" })\n   protected VirtualGuestBlockDeviceTemplate(int id, String device, int diskImageId, float diskSpace, int groupId,\n                                             String units, VirtualDiskImage diskImage) {\n      this.id = id;\n      this.device = checkNotNull(device, \"device\");\n      this.diskImageId = diskImageId;\n      this.diskSpace = diskSpace;\n      this.groupId = groupId;\n      this.units = units;\n      this.diskImage = checkNotNull(diskImage, \"diskImage\");\n   }\n\n   public int getId() {\n      return id;\n   }\n\n   public String getDevice() {\n      return device;\n   }\n\n   public int getDiskImageId() {\n      return diskImageId;\n   }\n\n   public float getDiskSpace() {\n      return diskSpace;\n   }\n\n   public int getGroupId() {\n      return groupId;\n   }\n\n   public String getUnits() {\n      return units;\n   }\n\n   public VirtualDiskImage getDiskImage() {\n      return diskImage;\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o) return true;\n      if (o == null || getClass() != o.getClass()) return false;\n\n      VirtualGuestBlockDeviceTemplate that = (VirtualGuestBlockDeviceTemplate) o;\n\n      return Objects.equal(this.id, that.id) &&\n              Objects.equal(this.device, that.device) &&\n              Objects.equal(this.diskImageId, that.diskImageId) &&\n              Objects.equal(this.diskSpace, that.diskSpace) &&\n              Objects.equal(this.groupId, that.groupId) &&\n              Objects.equal(this.units, that.units) &&\n              Objects.equal(this.diskImage, that.diskImage);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, device, diskImageId, diskSpace, groupId, units, diskImage);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this)\n              .add(\"id\", id)\n              .add(\"device\", device)\n              .add(\"diskImageId\", diskImageId)\n              .add(\"diskSpace\", diskSpace)\n              .add(\"groupId\", groupId)\n              .add(\"units\", units)\n              .add(\"diskImage\", diskImage)\n              .toString();\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/domain/VirtualGuestBlockDeviceTemplateGroup.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport java.beans.ConstructorProperties;\nimport java.util.Set;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Class VirtualGuestBlockDeviceTemplateGroup\n *\n * @see <a href= \"http://sldn.softlayer.com/reference/datatypes/SoftLayer_Virtual_Guest_Block_Device_Template_Group\"/>\n */\npublic class VirtualGuestBlockDeviceTemplateGroup {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().fromVirtualGuestBlockDeviceTemplateGroup(this);\n   }\n\n   public static class Builder {\n\n      protected int id;\n      protected String name;\n      protected String globalIdentifier;\n      protected int statusId;\n      protected int accountId;\n      protected int parentId;\n      protected String summary;\n      protected ImmutableSet.Builder<VirtualGuestBlockDeviceTemplateGroup> children = ImmutableSet.builder();\n      protected ImmutableSet.Builder<VirtualGuestBlockDeviceTemplate> blockDevices = ImmutableSet.builder();\n\n      /**\n       * @see org.jclouds.softlayer.domain.VirtualGuestBlockDeviceTemplateGroup#getId()\n       */\n      public Builder id(int id) {\n         this.id = id;\n         return this;\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.VirtualGuestBlockDeviceTemplateGroup#getName()\n       */\n      public Builder name(String name) {\n         this.name = name;\n         return this;\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.VirtualGuestBlockDeviceTemplateGroup#getGlobalIdentifier()\n       */\n      public Builder globalIdentifier(String globalIdentifier) {\n         this.globalIdentifier = globalIdentifier;\n         return this;\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.VirtualGuestBlockDeviceTemplateGroup#getStatusId()\n       */\n      public Builder statusId(int statusId) {\n         this.statusId = statusId;\n         return this;\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.VirtualGuestBlockDeviceTemplateGroup#getAccountId()\n       */\n      public Builder accountId(int accountId) {\n         this.accountId = accountId;\n         return this;\n      }\n\n      /**\n       * @see VirtualGuestBlockDeviceTemplateGroup#getParentId()\n       */\n      public Builder parentId(int parentId) {\n         this.parentId = parentId;\n         return this;\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.VirtualGuestBlockDeviceTemplateGroup#getSummary()\n       */\n      public Builder summary(String summary) {\n         this.summary = summary;\n         return this;\n      }\n\n      /**\n       * @see VirtualGuestBlockDeviceTemplateGroup#getChildren()\n       */\n      public Builder children(Iterable<VirtualGuestBlockDeviceTemplateGroup> children) {\n         this.children.addAll(checkNotNull(children, \"children\"));\n         return this;\n      }\n\n      public Builder children(VirtualGuestBlockDeviceTemplateGroup... in) {\n         return children(ImmutableSet.copyOf(checkNotNull(in, \"children\")));\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.VirtualGuestBlockDeviceTemplateGroup#getBlockDevices()\n       */\n      public Builder blockDevices(Set<VirtualGuestBlockDeviceTemplate> blockDevices) {\n         this.blockDevices.addAll(checkNotNull(blockDevices, \"blockDevices\"));\n         return this;\n      }\n\n      public Builder blockDevices(VirtualGuestBlockDeviceTemplate... in) {\n         return blockDevices(ImmutableSet.copyOf(checkNotNull(in, \"blockDevices\")));\n      }\n\n      public VirtualGuestBlockDeviceTemplateGroup build() {\n         return new VirtualGuestBlockDeviceTemplateGroup(id, name, globalIdentifier, statusId, accountId, parentId,\n                 summary, children.build(), blockDevices.build());\n      }\n\n      public Builder fromVirtualGuestBlockDeviceTemplateGroup(VirtualGuestBlockDeviceTemplateGroup in) {\n         return this\n                 .id(in.getId())\n                 .name(in.getName())\n                 .statusId(in.getStatusId())\n                 .accountId(in.getAccountId())\n                 .parentId(in.getParentId())\n                 .summary(in.getSummary())\n                 .children(in.getChildren())\n                 .blockDevices(in.getBlockDevices());\n      }\n   }\n\n   private final int id;\n   private final String name;\n   private final String globalIdentifier;\n   private final int statusId;\n   private final int accountId;\n   private final int parentId;\n   private final String summary;\n   private final Set<VirtualGuestBlockDeviceTemplateGroup> children;\n   private final Set<VirtualGuestBlockDeviceTemplate> blockDevices;\n\n   @ConstructorProperties({ \"id\", \"name\", \"globalIdentifier\", \"statusId\", \"accountId\", \"parentId\", \"summary\",\n           \"children\", \"blockDevices\" })\n   protected VirtualGuestBlockDeviceTemplateGroup(int id, @Nullable String name, @Nullable String globalIdentifier,\n                                                  int statusId, int accountId,  int parentId, @Nullable String summary,\n                                                  @Nullable Set<VirtualGuestBlockDeviceTemplateGroup> children,\n                                                  @Nullable Set<VirtualGuestBlockDeviceTemplate> blockDevices) {\n      this.id = id;\n      this.name = name;\n      this.globalIdentifier = globalIdentifier;\n      this.statusId = statusId;\n      this.accountId = accountId;\n      this.parentId = parentId;\n      this.summary = summary;\n      this.children = children == null ? ImmutableSet.<VirtualGuestBlockDeviceTemplateGroup>of() :\n              ImmutableSet.copyOf(children);\n      this.blockDevices = blockDevices == null ? ImmutableSet.<VirtualGuestBlockDeviceTemplate>of() :\n              ImmutableSet.copyOf(blockDevices);\n   }\n\n   public int getId() {\n      return id;\n   }\n\n   public String getName() {\n      return name;\n   }\n\n   public String getGlobalIdentifier() {\n      return globalIdentifier;\n   }\n\n   public int getStatusId() {\n      return statusId;\n   }\n\n   public int getAccountId() {\n      return accountId;\n   }\n\n   public int getParentId() {\n      return parentId;\n   }\n\n   public String getSummary() {\n      return summary;\n   }\n\n   public Set<VirtualGuestBlockDeviceTemplateGroup> getChildren() {\n      return children;\n   }\n\n   public Set<VirtualGuestBlockDeviceTemplate> getBlockDevices() {\n      return blockDevices;\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o) return true;\n      if (o == null || getClass() != o.getClass()) return false;\n\n      VirtualGuestBlockDeviceTemplateGroup that = (VirtualGuestBlockDeviceTemplateGroup) o;\n\n      return Objects.equal(this.id, that.id) &&\n              Objects.equal(this.name, that.name) &&\n              Objects.equal(this.globalIdentifier, that.globalIdentifier) &&\n              Objects.equal(this.statusId, that.statusId) &&\n              Objects.equal(this.accountId, that.accountId) &&\n              Objects.equal(this.parentId, that.parentId) &&\n              Objects.equal(this.summary, that.summary) &&\n              Objects.equal(this.children, that.children) &&\n              Objects.equal(this.blockDevices, that.blockDevices);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, name, globalIdentifier, statusId, accountId, parentId, summary, children,\n              blockDevices);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this)\n              .add(\"id\", id)\n              .add(\"name\", name)\n              .add(\"globalIdentifier\", globalIdentifier)\n              .add(\"statusId\", statusId)\n              .add(\"accountId\", accountId)\n              .add(\"parentId\", parentId)\n              .add(\"summary\", summary)\n              .add(\"children\", children)\n              .add(\"blockDevices\", blockDevices)\n              .toString();\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/domain/VirtualGuestNetworkComponent.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.domain;\n\nimport java.beans.ConstructorProperties;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\n/**\n * Class VirtualGuestBlockDeviceTemplateGroup\n *\n * @see <a href= \"http://sldn.softlayer.com/reference/datatypes/SoftLayer_Virtual_Guest_Network_Component\"/>\n */\npublic class VirtualGuestNetworkComponent {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().fromVirtualGuestNetworkComponent(this);\n   }\n\n   public static class Builder {\n\n      protected int id;\n      protected String uuid;\n      protected int guestId;\n      protected int networkId;\n      protected String macAddress;\n      protected int maxSpeed;\n      protected String name;\n      protected int port;\n      protected int speed;\n      protected String status;\n      protected NetworkVlan networkVlan;\n\n      /**\n       * @see org.jclouds.softlayer.domain.VirtualGuestNetworkComponent#getId()\n       */\n      public Builder id(int id) {\n         this.id = id;\n         return this;\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.VirtualGuestNetworkComponent#getUuid()\n       */\n      public Builder uuid(String uuid) {\n         this.uuid = uuid;\n         return this;\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.VirtualGuestNetworkComponent#getGuestId()\n       */\n      public Builder guestId(int guestId) {\n         this.guestId = guestId;\n         return this;\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.VirtualGuestNetworkComponent#getNetworkId()\n       */\n      public Builder networkId(int networkId) {\n         this.networkId = networkId;\n         return this;\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.VirtualGuestNetworkComponent#getMacAddress()\n       */\n      public Builder macAddress(String macAddress) {\n         this.macAddress = macAddress;\n         return this;\n      }\n\n      /**\n       * @see VirtualGuestNetworkComponent#getMaxSpeed()\n       */\n      public Builder maxSpeed(int maxSpeed) {\n         this.maxSpeed = maxSpeed;\n         return this;\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.VirtualGuestNetworkComponent#getPort()\n       */\n      public Builder port(int port) {\n         this.port = port;\n         return this;\n      }\n\n      /**\n       * @see org.jclouds.softlayer.domain.VirtualGuestNetworkComponent#getSpeed()\n       */\n      public Builder speed(int speed) {\n         this.speed = speed;\n         return this;\n      }\n\n      public Builder status(String status) {\n         this.status = status;\n         return this;\n      }\n\n      public Builder networkVlan(NetworkVlan networkVlan) {\n         this.networkVlan = networkVlan;\n         return this;\n      }\n\n      public VirtualGuestNetworkComponent build() {\n         return new VirtualGuestNetworkComponent(id, uuid, guestId, networkId, macAddress, maxSpeed, name, port,\n                 speed, status, networkVlan);\n      }\n\n      public Builder fromVirtualGuestNetworkComponent(VirtualGuestNetworkComponent in) {\n         return this\n                 .id(in.getId())\n                 .uuid(in.getUuid())\n                 .guestId(in.getGuestId())\n                 .networkId(in.getNetworkId())\n                 .macAddress(in.getMacAddress())\n                 .maxSpeed(in.getMaxSpeed())\n                 .port(in.getPort())\n                 .speed(in.getSpeed())\n                 .status(in.getStatus())\n                 .networkVlan(in.getNetworkVlan());\n      }\n   }\n\n   private final int id;\n   private final String uuid;\n   private final int guestId;\n   private final int networkId;\n   private final String macAddress;\n   private final int maxSpeed;\n   private final String name;\n   private final int port;\n   private final int speed;\n   private final String status;\n   private final NetworkVlan networkVlan;\n\n   @ConstructorProperties({ \"id\", \"uuid\", \"guestId\", \"networkId\", \"macAddress\", \"maxSpeed\", \"name\", \"port\", \"speed\",\n           \"status\", \"networkVlan\" })\n   protected VirtualGuestNetworkComponent(int id, String uuid, int guestId, int networkId, @Nullable String macAddress,\n                                          int maxSpeed, @Nullable String name, int port, int speed,\n                                          @Nullable String status, @Nullable NetworkVlan networkVlan) {\n      this.id = id;\n      this.uuid = uuid;\n      this.guestId = guestId;\n      this.networkId = networkId;\n      this.macAddress = macAddress;\n      this.maxSpeed = maxSpeed;\n      this.name = name;\n      this.port = port;\n      this.speed = speed;\n      this.status = status;\n      this.networkVlan = networkVlan;\n   }\n\n   public int getId() {\n      return id;\n   }\n\n   public String getUuid() {\n      return uuid;\n   }\n\n   public int getGuestId() {\n      return guestId;\n   }\n\n   public int getNetworkId() {\n      return networkId;\n   }\n\n   public String getMacAddress() {\n      return macAddress;\n   }\n\n   public int getMaxSpeed() {\n      return maxSpeed;\n   }\n\n   public String getName() {\n      return name;\n   }\n\n   public int getPort() {\n      return port;\n   }\n\n   public int getSpeed() {\n      return speed;\n   }\n\n   public String getStatus() {\n      return status;\n   }\n\n   public NetworkVlan getNetworkVlan() {\n      return networkVlan;\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o) return true;\n      if (o == null || getClass() != o.getClass()) return false;\n\n      VirtualGuestNetworkComponent that = (VirtualGuestNetworkComponent) o;\n\n      return Objects.equal(this.id, that.id) &&\n              Objects.equal(this.uuid, that.uuid) &&\n              Objects.equal(this.guestId, that.guestId) &&\n              Objects.equal(this.networkId, that.networkId) &&\n              Objects.equal(this.macAddress, that.macAddress) &&\n              Objects.equal(this.maxSpeed, that.maxSpeed) &&\n              Objects.equal(this.name, that.name) &&\n              Objects.equal(this.port, that.port) &&\n              Objects.equal(this.speed, that.speed) &&\n              Objects.equal(this.status, that.status) &&\n              Objects.equal(this.networkVlan, that.networkVlan);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, uuid, guestId, networkId, macAddress, maxSpeed,\n              name, port, speed, status, networkVlan);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this)\n              .add(\"id\", id)\n              .add(\"uuid\", uuid)\n              .add(\"guestId\", guestId)\n              .add(\"networkId\", networkId)\n              .add(\"macAddress\", macAddress)\n              .add(\"maxSpeed\", maxSpeed)\n              .add(\"name\", name)\n              .add(\"port\", port)\n              .add(\"speed\", speed)\n              .add(\"status\", status)\n              .add(\"networkVlan\", networkVlan)\n              .toString();\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/domain/internal/BlockDevice.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.domain.internal;\n\npublic class BlockDevice {\n   private final String device;\n   private final DiskImage diskImage;\n\n   public String getDevice() {\n      return device;\n   }\n\n   public DiskImage getDiskImage() {\n      return diskImage;\n   }\n\n   public BlockDevice(String device, float diskImageCapacity) {\n      this.device = device;\n      this.diskImage = new DiskImage(diskImageCapacity);\n   }\n\n   private static class DiskImage {\n      private float capacity;\n\n      public DiskImage(float capacity) {\n         this.capacity = capacity;\n      }\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/domain/internal/BlockDeviceTemplateGroup.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.domain.internal;\n\npublic class BlockDeviceTemplateGroup {\n\n   private final String globalIdentifier;\n\n   public BlockDeviceTemplateGroup(String globalIdentifier) {\n      this.globalIdentifier = globalIdentifier;\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/domain/internal/Datacenter.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.domain.internal;\n\npublic class Datacenter {\n\n   private final String name;\n\n   public Datacenter(String name) {\n      this.name = name;\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/domain/internal/NetworkComponent.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.domain.internal;\n\npublic class NetworkComponent {\n   private final int maxSpeed;\n\n   public NetworkComponent(int maxSpeed) {\n      this.maxSpeed = maxSpeed;\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/domain/internal/NetworkVlan.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.domain.internal;\n\npublic class NetworkVlan {\n   private final int id;\n\n   public NetworkVlan(int id) {\n      this.id = id;\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/domain/internal/PrimaryBackendNetworkComponent.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.domain.internal;\n\npublic class PrimaryBackendNetworkComponent {\n   private final NetworkVlan networkVlan;\n\n   public PrimaryBackendNetworkComponent(NetworkVlan networkVlan) {\n      this.networkVlan = networkVlan;\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/domain/internal/PrimaryNetworkComponent.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.domain.internal;\n\npublic class PrimaryNetworkComponent {\n   private final NetworkVlan networkVlan;\n\n   public PrimaryNetworkComponent(NetworkVlan networkVlan) {\n      this.networkVlan = networkVlan;\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/domain/internal/TemplateObject.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.domain.internal;\n\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\n\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ImmutableSet;\n\npublic class TemplateObject {\n   private final String hostname;\n   private final String domain;\n   private final int startCpus;\n   private final int maxMemory;\n   private final boolean hourlyBillingFlag;\n   private final boolean localDiskFlag;\n   private final boolean dedicatedAccountHostOnlyFlag;\n   private final boolean privateNetworkOnlyFlag;\n   private final BlockDeviceTemplateGroup blockDeviceTemplateGroup;\n   private final String operatingSystemReferenceCode;\n   private final Datacenter datacenter;\n   private final Set<NetworkComponent> networkComponents;\n   private final List<BlockDevice> blockDevices;\n   private final String postInstallScriptUri;\n   private final PrimaryNetworkComponent primaryNetworkComponent;\n   private final PrimaryBackendNetworkComponent primaryBackendNetworkComponent;\n   private final Set<Map<String, String>> userData;\n   private final Set<Map<String, Integer>> sshKeys;\n\n   private TemplateObject(String hostname, String domain, int startCpus, int maxMemory, boolean hourlyBillingFlag,\n                          boolean localDiskFlag, boolean dedicatedAccountHostOnlyFlag,\n                          boolean privateNetworkOnlyFlag, String operatingSystemReferenceCode,\n                          BlockDeviceTemplateGroup blockDeviceTemplateGroup, Datacenter datacenter,\n                          Set<NetworkComponent> networkComponents, List<BlockDevice> blockDevices,\n                          String postInstallScriptUri, PrimaryNetworkComponent primaryNetworkComponent,\n                          PrimaryBackendNetworkComponent primaryBackendNetworkComponent, Set<Map<String,\n           String>> userData, Set<Map<String, Integer>> sshKeys) {\n      this.hostname = hostname;\n      this.domain = domain;\n      this.startCpus = startCpus;\n      this.maxMemory = maxMemory;\n      this.hourlyBillingFlag = hourlyBillingFlag;\n      this.localDiskFlag = localDiskFlag;\n      this.dedicatedAccountHostOnlyFlag = dedicatedAccountHostOnlyFlag;\n      this.privateNetworkOnlyFlag = privateNetworkOnlyFlag;\n      this.operatingSystemReferenceCode = operatingSystemReferenceCode;\n      this.blockDeviceTemplateGroup = blockDeviceTemplateGroup;\n      this.datacenter = datacenter;\n      this.networkComponents = networkComponents;\n      this.blockDevices = blockDevices;\n      this.postInstallScriptUri = postInstallScriptUri;\n      this.primaryNetworkComponent = primaryNetworkComponent;\n      this.primaryBackendNetworkComponent = primaryBackendNetworkComponent;\n      this.userData = userData;\n      this.sshKeys = sshKeys;\n   }\n\n   public String getHostname() {\n      return hostname;\n   }\n\n   public String getDomain() {\n      return domain;\n   }\n\n   public int getStartCpus() {\n      return startCpus;\n   }\n\n   public int getMaxMemory() {\n      return maxMemory;\n   }\n\n   public boolean isHourlyBillingFlag() {\n      return hourlyBillingFlag;\n   }\n\n   public boolean isLocalDiskFlag() {\n      return localDiskFlag;\n   }\n\n   public boolean isDedicatedAccountHostOnlyFlag() {\n      return dedicatedAccountHostOnlyFlag;\n   }\n\n   public boolean isPrivateNetworkOnlyFlag() {\n      return privateNetworkOnlyFlag;\n   }\n\n   public BlockDeviceTemplateGroup getBlockDeviceTemplateGroup() {\n      return blockDeviceTemplateGroup;\n   }\n\n   public String getOperatingSystemReferenceCode() {\n      return operatingSystemReferenceCode;\n   }\n\n   public Datacenter getDatacenter() {\n      return datacenter;\n   }\n\n   public Set<NetworkComponent> getNetworkComponents() {\n      return networkComponents;\n   }\n\n   public List<BlockDevice> getBlockDevices() {\n      return blockDevices;\n   }\n\n   public String getPostInstallScriptUri() {\n      return postInstallScriptUri;\n   }\n\n   public PrimaryNetworkComponent getPrimaryNetworkComponent() {\n      return primaryNetworkComponent;\n   }\n\n   public Set<Map<String, String>> getUserData() {\n      return userData;\n   }\n\n   public Set<Map<String, Integer>> getSshKeys() {\n      return sshKeys;\n   }\n\n   public PrimaryBackendNetworkComponent getPrimaryBackendNetworkComponent() {\n      return primaryBackendNetworkComponent;\n   }\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().fromTemplateObject(this);\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o) return true;\n      if (o == null || getClass() != o.getClass()) return false;\n\n      TemplateObject that = (TemplateObject) o;\n\n      return Objects.equal(this.hostname, that.hostname) &&\n              Objects.equal(this.domain, that.domain) &&\n              Objects.equal(this.startCpus, that.startCpus) &&\n              Objects.equal(this.maxMemory, that.maxMemory) &&\n              Objects.equal(this.hourlyBillingFlag, that.hourlyBillingFlag) &&\n              Objects.equal(this.localDiskFlag, that.localDiskFlag) &&\n              Objects.equal(this.dedicatedAccountHostOnlyFlag, that.dedicatedAccountHostOnlyFlag) &&\n              Objects.equal(this.privateNetworkOnlyFlag, that.privateNetworkOnlyFlag) &&\n              Objects.equal(this.blockDeviceTemplateGroup, that.blockDeviceTemplateGroup) &&\n              Objects.equal(this.operatingSystemReferenceCode, that.operatingSystemReferenceCode) &&\n              Objects.equal(this.datacenter, that.datacenter) &&\n              Objects.equal(this.networkComponents, that.networkComponents) &&\n              Objects.equal(this.blockDevices, that.blockDevices) &&\n              Objects.equal(this.postInstallScriptUri, that.postInstallScriptUri) &&\n              Objects.equal(this.primaryNetworkComponent, that.primaryNetworkComponent) &&\n              Objects.equal(this.primaryBackendNetworkComponent, that.primaryBackendNetworkComponent) &&\n              Objects.equal(this.userData, that.userData) &&\n              Objects.equal(this.sshKeys, that.sshKeys);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(hostname, domain, startCpus, maxMemory, hourlyBillingFlag, localDiskFlag,\n              dedicatedAccountHostOnlyFlag, privateNetworkOnlyFlag, blockDeviceTemplateGroup, operatingSystemReferenceCode, datacenter,\n              networkComponents, blockDevices, postInstallScriptUri, primaryNetworkComponent,\n              primaryBackendNetworkComponent, userData, sshKeys);\n   }\n\n\n   public static class Builder {\n\n      protected String hostname;\n      protected String domain;\n      protected int startCpus;\n      protected int maxMemory;\n      protected boolean hourlyBillingFlag;\n      protected boolean localDiskFlag;\n      protected boolean dedicatedAccountHostOnlyFlag;\n      protected boolean privateNetworkOnlyFlag;\n      protected String operatingSystemReferenceCode;\n      protected BlockDeviceTemplateGroup blockDeviceTemplateGroup;\n      protected Datacenter datacenter;\n      protected Set<NetworkComponent> networkComponents;\n      protected List<BlockDevice> blockDevices;\n      protected String postInstallScriptUri;\n      protected PrimaryNetworkComponent primaryNetworkComponent;\n      protected PrimaryBackendNetworkComponent primaryBackendNetworkComponent;\n      protected Set<Map<String, String>> userData;\n      protected Set<Map<String, Integer>> sshKeys;\n\n      public Builder hostname(String hostname) {\n         this.hostname = hostname;\n         return this;\n      }\n\n      public Builder domain(String domain) {\n         this.domain = domain;\n         return this;\n      }\n\n      public Builder startCpus(int startCpus) {\n         this.startCpus = startCpus;\n         return this;\n      }\n\n      public Builder maxMemory(int maxMemory) {\n         this.maxMemory = maxMemory;\n         return this;\n      }\n\n      public Builder hourlyBillingFlag(boolean hourlyBillingFlag) {\n         this.hourlyBillingFlag = hourlyBillingFlag;\n         return this;\n      }\n\n      public Builder localDiskFlag(boolean localDiskFlag) {\n         this.localDiskFlag = localDiskFlag;\n         return this;\n      }\n\n      public Builder dedicatedAccountHostOnlyFlag(boolean dedicatedAccountHostOnlyFlag) {\n         this.dedicatedAccountHostOnlyFlag = dedicatedAccountHostOnlyFlag;\n         return this;\n      }\n\n      public Builder privateNetworkOnlyFlag(boolean privateNetworkOnlyFlag) {\n         this.privateNetworkOnlyFlag = privateNetworkOnlyFlag;\n         return this;\n      }\n\n      public Builder operatingSystemReferenceCode(String operatingSystemReferenceCode) {\n         this.operatingSystemReferenceCode = operatingSystemReferenceCode;\n         return this;\n      }\n\n      public Builder blockDeviceTemplateGroup(BlockDeviceTemplateGroup blockDeviceTemplateGroup) {\n         this.blockDeviceTemplateGroup = blockDeviceTemplateGroup;\n         return this;\n      }\n\n      public Builder datacenter(Datacenter datacenter) {\n         this.datacenter = datacenter;\n         return this;\n      }\n\n      public Builder networkComponents(Set<NetworkComponent> networkComponents) {\n         this.networkComponents = networkComponents;\n         return this;\n      }\n\n      public Builder blockDevices(List<BlockDevice> blockDevices) {\n         this.blockDevices = blockDevices;\n         return this;\n      }\n\n      public Builder postInstallScriptUri(String postInstallScriptUri) {\n         this.postInstallScriptUri = postInstallScriptUri;\n         return this;\n      }\n\n      public Builder primaryNetworkComponent(PrimaryNetworkComponent primaryNetworkComponent) {\n         this.primaryNetworkComponent = primaryNetworkComponent;\n         return this;\n      }\n\n      public Builder primaryBackendNetworkComponent(PrimaryBackendNetworkComponent primaryBackendNetworkComponent) {\n         this.primaryBackendNetworkComponent = primaryBackendNetworkComponent;\n         return this;\n      }\n\n      public Builder userData(Set<Map<String, String>> userData) {\n         this.userData = ImmutableSet.copyOf(userData);\n         return this;\n      }\n\n      public Builder sshKeys(Set<Map<String, Integer>> sshKeys) {\n         this.sshKeys = ImmutableSet.copyOf(sshKeys);\n         return this;\n      }\n\n      public TemplateObject build() {\n         return new TemplateObject(hostname, domain, startCpus, maxMemory, hourlyBillingFlag, localDiskFlag,\n                 dedicatedAccountHostOnlyFlag, privateNetworkOnlyFlag, operatingSystemReferenceCode,\n                 blockDeviceTemplateGroup, datacenter, networkComponents, blockDevices, postInstallScriptUri,\n                 primaryNetworkComponent, primaryBackendNetworkComponent, userData, sshKeys);\n      }\n\n      public Builder fromTemplateObject(TemplateObject in) {\n         return this\n                 .hostname(in.getHostname())\n                 .domain(in.getDomain())\n                 .startCpus(in.getStartCpus())\n                 .maxMemory(in.getMaxMemory())\n                 .hourlyBillingFlag(in.isHourlyBillingFlag())\n                 .localDiskFlag(in.isLocalDiskFlag())\n                 .dedicatedAccountHostOnlyFlag(in.isDedicatedAccountHostOnlyFlag())\n                 .privateNetworkOnlyFlag(in.isPrivateNetworkOnlyFlag())\n                 .operatingSystemReferenceCode(in.getOperatingSystemReferenceCode())\n                 .blockDeviceTemplateGroup(in.getBlockDeviceTemplateGroup())\n                 .datacenter(in.getDatacenter())\n                 .networkComponents(in.getNetworkComponents())\n                 .blockDevices(in.getBlockDevices())\n                 .postInstallScriptUri(in.getPostInstallScriptUri())\n                 .primaryNetworkComponent(in.getPrimaryNetworkComponent())\n                 .primaryBackendNetworkComponent(in.getPrimaryBackendNetworkComponent())\n                 .userData(in.getUserData())\n                 .sshKeys(in.getSshKeys());\n      }\n\n   }\n\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/features/AccountApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.features;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.http.filters.BasicAuthentication;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.softlayer.domain.VirtualGuest;\nimport org.jclouds.softlayer.domain.VirtualGuestBlockDeviceTemplateGroup;\n\n/**\n * Provides access to Account via their REST API.\n * <p/>\n *\n * @see <a href=\"http://sldn.softlayer.com/reference/services/SoftLayer_Virtual_Guest_Block_Device_Template_Group\" />\n */\n@RequestFilters(BasicAuthentication.class)\n@Path(\"/v{jclouds.api-version}\")\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface AccountApi {\n\n   String GUEST_MASK = \"children.blockDevices.diskImage.softwareReferences.softwareDescription\";\n   String LIST_GUEST_MASK = \"powerState;operatingSystem.passwords;datacenter;billingItem;blockDevices\" +\n           \".diskImage;tagReferences.tag.name\";\n\n   /**\n    * @return an account's associated virtual guest objects.\n    */\n   @Named(\"Account:listVirtualGuest\")\n   @GET\n   @Path(\"/SoftLayer_Account/VirtualGuests\")\n   @QueryParams(keys = \"objectMask\", values = LIST_GUEST_MASK)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<VirtualGuest> listVirtualGuests();\n\n   /**\n    * @return retrieve block device groups for an account (private images)\n    * @see <a href=\"http://sldn.softlayer.com/reference/services/SoftLayer_Account/getBlockDeviceTemplateGroups/\" />\n    */\n   @Named(\"Account:getBlockDeviceTemplateGroups\")\n   @GET\n   @Path(\"/SoftLayer_Account/getBlockDeviceTemplateGroups\")\n   @QueryParams(keys = \"objectMask\", values = GUEST_MASK)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<VirtualGuestBlockDeviceTemplateGroup> getBlockDeviceTemplateGroups();\n\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/features/DatacenterApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.features;\n\nimport java.util.Set;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.http.filters.BasicAuthentication;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.softlayer.domain.Datacenter;\n\n/**\n * Provides access to LocationDatacenter via their REST API.\n * <p/>\n * @see <a href=\"http://sldn.softlayer.com/article/REST\" />\n */\n@RequestFilters(BasicAuthentication.class)\n@Path(\"/v{jclouds.api-version}\")\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface DatacenterApi {\n\n   /**\n    * @return an account's associated datacenter objects.\n    */\n   @GET\n   @Path(\"/SoftLayer_Location_Datacenter/Datacenters\")\n   @QueryParams(keys = \"objectMask\", values = \"locationAddress;regions\")\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<Datacenter> listDatacenters();\n\n   /**\n    * @param id\n    *           id of the datacenter\n    * @return datacenter or null if not found\n    */\n   @GET\n   @Path(\"/SoftLayer_Location_Datacenter/{id}\")\n   @QueryParams(keys = \"objectMask\", values = \"locationAddress;regions\")\n   @Fallback(NullOnNotFoundOr404.class)\n   Datacenter getDatacenter(@PathParam(\"id\") long id);\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/features/NetworkApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.features;\n\nimport org.jclouds.Fallbacks;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.http.filters.BasicAuthentication;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.WrapWith;\nimport org.jclouds.softlayer.domain.Network;\nimport org.jclouds.softlayer.domain.Subnet;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.PUT;\nimport jakarta.ws.rs.DELETE;\n\nimport jakarta.ws.rs.core.MediaType;\nimport java.io.Closeable;\nimport java.util.List;\n\n/**\n * Provides access to Network via their REST API.\n * <p/>\n * @see <a href=\"http://sldn.softlayer.com/article/REST\" />\n */\n@RequestFilters(BasicAuthentication.class)\n@Path(\"/v{jclouds.api-version}\")\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface NetworkApi extends Closeable {\n\n   String NAME_MASK = \"mask.subnets\";\n\n   /**\n    * returns a list of networks belong to the account\n    * @return an account's associated network objects.\n    * @see <a href=\"http://sldn.softlayer.com/reference/services/softlayer_network/getallobjects\" />\n    */\n   @GET\n   @Named(\"Network:getAlllObjects\")\n   @Path(\"/SoftLayer_Network/getAllObjects\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @QueryParams(keys = \"objectMask\", values = NAME_MASK)\n   @Fallback(Fallbacks.EmptyListOnNotFoundOr404.class)\n   List<Network> listNetworks();\n\n   /**\n    * returns the name of the network of the given id\n    * @param id id of the network\n    * @return String or null\n    * @see <a href=\"http://sldn.softlayer.com/reference/services/softlayer_network/getname\" />\n    */\n   @GET\n   @Named(\"Network:getName\")\n   @Path(\"/SoftLayer_Network/{id}/getName\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   String getName(@PathParam(\"id\") long id);\n\n   /**\n    * returns the notes of the network of the given id\n    * @param id id of the network\n    * @return String or null\n    * @see <a href=\"http://sldn.softlayer.com/reference/services/softlayer_network/getnotes\" />\n    */\n   @GET\n   @Named(\"Network:getNotes\")\n   @Path(\"/SoftLayer_Network/{id}/getNotes\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   String getNotes(@PathParam(\"id\") long id);\n\n   /**\n    * returns the details of the network of the given id\n    * @param id id of the network\n    * @return String or null\n    * @see <a href=\"http://sldn.softlayer.com/reference/services/softlayer_network/getObject\" />\n    */\n   @GET\n   @Named(\"Network:getObject\")\n   @Path(\"/SoftLayer_Network/{id}/getObject\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @QueryParams(keys = \"objectMask\", values = NAME_MASK)\n   @Fallback(NullOnNotFoundOr404.class)\n   Network getNetwork(@PathParam(\"id\") long id);\n\n   /**\n    * returns the subnets of the network of the given id\n    * @param id id of the network\n    * @return list of subnets under the network or null\n    * @see <a href=\"http://sldn.softlayer.com/reference/services/softlayer_network/getSubnet\" />\n    */\n   @GET\n   @Named(\"Network:getSubnets\")\n   @Path(\"/SoftLayer_Network/{id}/getSubnets\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @Fallback(Fallbacks.EmptyListOnNotFoundOr404.class)\n   List<Subnet> getSubnets(@PathParam(\"id\") long id);\n\n   /**\n    * creates a network\n    * @param networkToBeCreated the network creation definition of Network.CreateNetwork\n    * @return Network created\n    * @see <a href=\"http://sldn.softlayer.com/reference/services/SoftLayer_network/createObject\" />\n    */\n   @POST\n   @Named(\"network:createObject\")\n   @Path(\"/SoftLayer_Network/createObject\")\n   @Produces(MediaType.APPLICATION_JSON)\n   Network createNetwork(@WrapWith(\"parameters\") List<Network.CreateNetwork> networkToBeCreated);\n\n   /**\n    * modifies a network with the given id\n    * @param id the id of the network to be edited\n    * @param networkToBeEdited the network edition definition of Network.EditNetwork\n    * @return true when edition was successful and false for unsuccessful edition\n    * @see <a href=\"http://sldn.softlayer.com/reference/services/SoftLayer_network/editObject\" />\n    */\n   @PUT\n   @Named(\"Network:editObject\")\n   @Path(\"/SoftLayer_Network/{id}/editObject\")\n   @Fallback(Fallbacks.FalseOnNotFoundOr404.class)\n   boolean editNetwork(@PathParam(\"id\") long id, @WrapWith(\"parameters\") List<Network.EditNetwork> networkToBeEdited);\n\n   /**\n    * deletes a network with the given id\n    * @param id the id of the network to be deleted\n    * @return boolean value true for successful deletion and false for failed deletion\n    * @see <a href=\"http://sldn.softlayer.com/reference/services/SoftLayer_network/deleteObject\" />\n    */\n   @DELETE\n   @Named(\"network:deleteObject\")\n   @Path(\"/SoftLayer_Network/{id}\")\n   @Fallback(Fallbacks.FalseOnNotFoundOr404.class)\n   boolean deleteNetwork(@PathParam(\"id\") long id);\n\n   /**\n    * creates a subnet on the given network\n    * @param id the id of the network to be edited\n    * @param subnetToBeCreated the subnet creation definition of Subnet.CreateSubnet\n    * @return subnet created\n    * @see <a href=\"http://sldn.softlayer.com/reference/services/softlayer_network/createSubnet\" />\n    */\n   @POST\n   @Named(\"Network:createSubnet\")\n   @Path(\"/SoftLayer_Network/{id}/createSubnet\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @Fallback(NullOnNotFoundOr404.class)\n   Subnet createSubnet(@PathParam(\"id\") long id, @WrapWith(\"parameters\") List<Object> subnetToBeCreated);\n\n   /**\n    * removes the subnet of the given network\n    * @param id id of the targeted seurity group\n    * @param subnetToBeDeleted the subnet deletion definition of Subnet.DeleteSubnet\n    * @reutrn boolean value true for successful deletion and false for failed deletion\n    * @see <a href=\"http://sldn.softlayer.com/reference/services/softlayer_network/deleteSubnet\" />\n    */\n   @POST\n   @Named(\"Network:deleteSubnet\")\n   @Path(\"/SoftLayer_Network/{id}/deleteSubnet\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @Fallback(Fallbacks.FalseOnNotFoundOr404.class)\n   boolean deleteSubnet(@PathParam(\"id\") long id, @WrapWith(\"parameters\") List<Subnet.DeleteSubnet> subnetToBeDeleted);\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/features/SoftwareDescriptionApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.features;\n\nimport java.util.Set;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks;\nimport org.jclouds.http.filters.BasicAuthentication;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.softlayer.domain.SoftwareDescription;\n\n/**\n * Provides access to Software_Description via their REST API.\n * <p/>\n * @see <a href=\"http://sldn.softlayer.com/reference/services/SoftLayer_Software_Description\" />\n */\n@RequestFilters(BasicAuthentication.class)\n@Path(\"/v{jclouds.api-version}\")\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface SoftwareDescriptionApi {\n\n   /**\n    * @return all objects.\n    */\n   @GET\n   @Path(\"/SoftLayer_Software_Description/getAllObjects\")\n   @QueryParams(keys = \"objectMask\", values = \"id;name;version;operatingSystem;longDescription;referenceCode\")\n   @Fallback(Fallbacks.EmptySetOnNotFoundOr404.class)\n   Set<SoftwareDescription> getAllObjects();\n\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/features/VirtualGuestApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.features;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.POST;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.Produces;\nimport jakarta.ws.rs.QueryParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.FalseOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.http.filters.BasicAuthentication;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.softlayer.binders.NotesToJson;\nimport org.jclouds.softlayer.binders.TagToJson;\nimport org.jclouds.softlayer.binders.VirtualGuestToJson;\nimport org.jclouds.softlayer.domain.ContainerVirtualGuestConfiguration;\nimport org.jclouds.softlayer.domain.VirtualGuest;\n\n/**\n * Provides access to VirtualGuest via their REST API.\n * <p/>\n *\n * @see <a http://sldn.softlayer.com/reference/services/SoftLayer_Virtual_Guest\" />\n */\n@RequestFilters(BasicAuthentication.class)\n@Path(\"/v{jclouds.api-version}\")\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface VirtualGuestApi {\n\n   String GUEST_MASK = \"id;hostname;domain;fullyQualifiedDomainName;powerState;maxCpu;maxMemory;\" +\n           \"statusId;operatingSystem.passwords;primaryBackendIpAddress;primaryIpAddress;activeTransactionCount;\" +\n           \"blockDevices.diskImage;datacenter;tagReferences;privateNetworkOnlyFlag;sshKeys\";\n\n   String NOTES_MASK = \"id;notes\";\n\n   /**\n    * Enables the creation of computing instances on an account.\n    * @param virtualGuest this data type presents the structure in which all virtual guests will be presented.\n    * @return the new Virtual Guest\n    * @see <a href=\"http://sldn.softlayer.com/reference/services/SoftLayer_Virtual_Guest/createObject\" />\n    */\n   @Named(\"VirtualGuests:create\")\n   @POST\n   @Path(\"SoftLayer_Virtual_Guest\")\n   @Produces(MediaType.APPLICATION_JSON)\n   VirtualGuest createVirtualGuest(@BinderParam(VirtualGuestToJson.class) VirtualGuest virtualGuest);\n\n   /**\n    * @param id id of the virtual guest\n    * @return virtual guest or null if not found\n    * @see <a href=\"http://sldn.softlayer.com/reference/services/SoftLayer_Virtual_Guest/getObject\" />\n    */\n   @Named(\"VirtualGuests:get\")\n   @GET\n   @Path(\"/SoftLayer_Virtual_Guest/{id}/getObject\")\n   @QueryParams(keys = \"objectMask\", values = GUEST_MASK)\n   @Fallback(NullOnNotFoundOr404.class)\n   VirtualGuest getVirtualGuest(@PathParam(\"id\") long id);\n\n   /**\n    * Returns a {@link VirtualGuest} with <b>only</b> the fields listed in the filter string.\n    * @param id id of the virtual guest\n    * @param filter semicolon separated list of fields to return in the resulting object\n    * @return virtual guest or null if not found\n    * @see <a href=\"http://sldn.softlayer.com/reference/services/SoftLayer_Virtual_Guest/getObject\" />\n    * @see <a href=\"http://sldn.softlayer.com/article/object-masks\" />\n    */\n   @Named(\"VirtualGuests:get\")\n   @GET\n   @Path(\"/SoftLayer_Virtual_Guest/{id}/getObject\")\n   @Fallback(NullOnNotFoundOr404.class)\n   VirtualGuest getVirtualGuestFiltered(@PathParam(\"id\") long id, @QueryParam(\"objectMask\") String filter);\n\n   /**\n    * Delete a computing instance\n    * @param id the id of the virtual guest.\n    * @return the result of the deletion\n    * @see <a href=\"http://sldn.softlayer.com/reference/services/SoftLayer_Virtual_Guest/deleteObject\" />\n    */\n   @Named(\"VirtualGuests:delete\")\n   @GET\n   @Path(\"/SoftLayer_Virtual_Guest/{id}/deleteObject\")\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean deleteVirtualGuest(@PathParam(\"id\") long id);\n\n   /**\n    * Determine options available when creating a computing instance\n    * @see <a href=\"http://sldn.softlayer.com/reference/services/SoftLayer_Virtual_Guest/getCreateObjectOptions\" />\n    */\n   @Named(\"VirtualGuests:getCreateObjectOptions\")\n   @GET\n   @Path(\"/SoftLayer_Virtual_Guest/getCreateObjectOptions\")\n   @Fallback(NullOnNotFoundOr404.class)\n   ContainerVirtualGuestConfiguration getCreateObjectOptions();\n\n   /**\n    * Hard reboot the guest.\n    *\n    * @param id\n    *           id of the virtual guest\n    */\n   @Named(\"VirtualGuest:rebootHard\")\n   @GET\n   @Path(\"/SoftLayer_Virtual_Guest/{id}/rebootHard.json\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void rebootHardVirtualGuest(@PathParam(\"id\") long id);\n\n   /**\n    * Pause the guest.\n    *\n    * @param id\n    *           id of the virtual guest\n    */\n   @Named(\"VirtualGuest:pause\")\n   @GET\n   @Path(\"/SoftLayer_Virtual_Guest/{id}/pause.json\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void pauseVirtualGuest(@PathParam(\"id\") long id);\n\n   /**\n    * Resume the guest.\n    *\n    * @param id\n    *           id of the virtual guest\n    */\n   @Named(\"VirtualGuest:resume\")\n   @GET\n   @Path(\"/SoftLayer_Virtual_Guest/{id}/resume.json\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void resumeVirtualGuest(@PathParam(\"id\") long id);\n\n   /**\n    * Set the tags on the instance\n    *\n    * @param id\n    *           id of the virtual guest\n    */\n   @Named(\"VirtualGuest:setTags\")\n   @POST\n   @Path(\"/SoftLayer_Virtual_Guest/{id}/setTags\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @Fallback(FalseOnNotFoundOr404.class)\n   boolean setTags(@PathParam(\"id\") long id, @BinderParam(TagToJson.class) Set<String> tags);\n\n   /**\n    * Set notes (visible in UI)\n    *\n    * @param id id of the virtual guest\n    * @param notes The notes property to set on the machine - visible in UI\n    */\n   @Named(\"VirtualGuest:setNotes\")\n   @POST\n   @Path(\"/SoftLayer_Virtual_Guest/{id}/editObject\")\n   @Produces(MediaType.APPLICATION_JSON)\n   boolean setNotes(@PathParam(\"id\") long id, @BinderParam(NotesToJson.class) String notes);\n\n   /**\n    * Get notes (visible in UI)\n    *\n    * Don't include it in default getObject mask as it can get quite big (up to 1000 chars).\n    * Also no place to put it in NodeMetadata.\n    *\n    * @param id\n    *           id of the virtual guest\n    */\n   @Named(\"VirtualGuest:getNotes\")\n   @GET\n   @Path(\"/SoftLayer_Virtual_Guest/{id}/getObject\")\n   @Produces(MediaType.APPLICATION_JSON)\n   @QueryParams(keys = \"objectMask\", values = NOTES_MASK)\n   @Fallback(NullOnNotFoundOr404.class)\n   VirtualGuest getNotes(@PathParam(\"id\") long id);\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/features/VirtualGuestBlockDeviceTemplateGroupApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.features;\n\nimport java.util.Set;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.GET;\nimport jakarta.ws.rs.Path;\nimport jakarta.ws.rs.PathParam;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.Fallbacks.EmptySetOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.http.filters.BasicAuthentication;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.QueryParams;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.softlayer.domain.VirtualGuestBlockDeviceTemplateGroup;\n\n/**\n * Provides access to VirtualGuestBlockDeviceTemplateGroup via their REST API.\n * <p/>\n *\n * @see <a href=\"http://sldn.softlayer.com/reference/services/SoftLayer_Virtual_Guest_Block_Device_Template_Group\" />\n */\n@RequestFilters(BasicAuthentication.class)\n@Path(\"/v{jclouds.api-version}\")\n@Consumes(MediaType.APPLICATION_JSON)\npublic interface VirtualGuestBlockDeviceTemplateGroupApi {\n\n   String MASK = \"children.blockDevices.diskImage.softwareReferences.softwareDescription\";\n\n   /**\n    * @return public images\n    * @see <a href=\"http://sldn.softlayer.com/reference/services/SoftLayer_Virtual_Guest_Block_Device_Template_Group/getPublicImages\" />\n    */\n   @Named(\"VirtualGuestBlockDeviceTemplateGroup:getPublicImages\")\n   @GET\n   @Path(\"/SoftLayer_Virtual_Guest_Block_Device_Template_Group/getPublicImages\")\n   @QueryParams(keys = \"objectMask\", values = MASK)\n   @Fallback(EmptySetOnNotFoundOr404.class)\n   Set<VirtualGuestBlockDeviceTemplateGroup> getPublicImages();\n\n   /**\n    * Retrieves a virtual block device template group structure. It consists of a parent template group which contain\n    * multiple child template group objects.\n    * Each child template group object represents the image template in a particular location.\n    *\n    * @return a virtual block device template group\n    * @see <a href=\"http://sldn.softlayer.com/reference/services/SoftLayer_Virtual_Guest_Block_Device_Template_Group/getObject\" />\n    */\n   @Named(\"VirtualGuestBlockDeviceTemplateGroup:getObject\")\n   @GET\n   @Path(\"/SoftLayer_Virtual_Guest_Block_Device_Template_Group/{id}/getObject\")\n   @QueryParams(keys = \"objectMask\", values = MASK)\n   @Fallback(NullOnNotFoundOr404.class)\n   VirtualGuestBlockDeviceTemplateGroup getObject(@PathParam(\"id\") String id);\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/handlers/SoftLayerErrorHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.handlers;\n\nimport java.io.IOException;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.jclouds.util.Closeables2;\nimport org.jclouds.util.Strings2;\n\nimport com.google.common.base.Throwables;\n\n/**\n * This will parse and set an appropriate exception on the command object.\n */\n@Singleton\npublic class SoftLayerErrorHandler implements HttpErrorHandler {\n\n   public void handleError(HttpCommand command, HttpResponse response) {\n      // it is important to always read fully and close streams\n      String message = parseMessage(response);\n      Exception exception = message != null ? new HttpResponseException(command, response, message)\n               : new HttpResponseException(command, response);\n      try {\n         message = message != null ? message : String.format(\"%s -> %s\", command.getCurrentRequest().getRequestLine(),\n                  response.getStatusLine());\n         switch (response.getStatusCode()) {\n            case 401:\n            case 403:\n               exception = new AuthorizationException(message, exception);\n               break;\n            case 404:\n               if (!command.getCurrentRequest().getMethod().equals(\"DELETE\")) {\n                  exception = new ResourceNotFoundException(message, exception);\n               }\n               break;\n            case 500:\n               if (message != null ){\n                  if (message.indexOf(\"Unable to determine package for\") != -1) {\n                     exception = new ResourceNotFoundException(message, exception);\n                  } else if (message.indexOf(\"currently an active transaction\") != -1) {\n                     exception = new IllegalStateException(message, exception);\n                  }\n               }\n         }\n      } finally {\n         Closeables2.closeQuietly(response.getPayload());\n         command.setException(exception);\n      }\n   }\n\n   public String parseMessage(HttpResponse response) {\n      if (response.getPayload() == null)\n         return null;\n      try {\n         return Strings2.toStringAndClose(response.getPayload().openStream());\n      } catch (IOException e) {\n         throw new RuntimeException(e);\n      } finally {\n         try {\n            response.getPayload().getInput().close();\n         } catch (IOException e) {\n            Throwables.propagate(e);\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/main/java/org/jclouds/softlayer/reference/SoftLayerConstants.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.reference;\n\n/**\n * Configuration properties and constants used in SoftLayer connections.\n */\npublic final class SoftLayerConstants {\n\n   public static final String SOFTLAYER_PROVIDER_NAME = \"softlayer\";\n\n   /**\n    * Number of milliseconds to wait for an order to arrive on the api.\n    */\n   public static final String PROPERTY_SOFTLAYER_VIRTUALGUEST_LOGIN_DETAILS_DELAY = \"jclouds.softlayer.virtualguest\" +\n           \".login_details_delay\";\n\n   /**\n    * Number of milliseconds to wait for a virtualguest to be without active transactions\n    */\n   public static final String PROPERTY_SOFTLAYER_VIRTUALGUEST_ACTIVE_TRANSACTIONS_DELAY = \"jclouds.softlayer\" +\n           \".virtualguest.active_transactions_delay\";\n\n   private SoftLayerConstants() {\n      throw new AssertionError(\"intentionally unimplemented\");\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/java/org/jclouds/softlayer/SoftLayerProviderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer;\n\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"SoftLayerApiMetadataTest\")\npublic class SoftLayerProviderTest extends BaseProviderMetadataTest {\n   public SoftLayerProviderTest() {\n      super(new SoftLayerProviderMetadata(), new SoftLayerApiMetadata());\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/java/org/jclouds/softlayer/binders/NotesToJsonTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.json.Json;\nimport org.jclouds.json.internal.GsonWrapper;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.gson.Gson;\n\n@Test(groups = \"unit\", testName = \"NotesToJsonTest\")\npublic class NotesToJsonTest {\n\n   private Json json;\n\n   @BeforeClass\n   public void init() {\n      json = new GsonWrapper(new Gson());\n   }\n\n   @Test\n   public void testVirtualGuestWithNotes() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"https://api.softlayer.com/rest/v3/SoftLayer_Virtual_Guest\").build();\n      NotesToJson binder = new NotesToJson(json);\n      String notes = \"some notes\";\n\n      request = binder.bindToRequest(request, notes);\n\n      assertEquals(request.getPayload().getRawContent(), \"{\\\"parameters\\\":[{\\\"notes\\\":\\\"some notes\\\"}]}\");\n   }\n\n   @Test\n   public void testVirtualGuestWithoutNotes() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"https://api.softlayer.com/rest/v3/SoftLayer_Virtual_Guest\").build();\n      NotesToJson binder = new NotesToJson(json);\n      request = binder.bindToRequest(request, \"\");\n\n      assertEquals(request.getPayload().getRawContent(), \"{\\\"parameters\\\":[{\\\"notes\\\":\\\"\\\"}]}\");\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testVirtualGuestNullNotes() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"https://api.softlayer.com/rest/v3/SoftLayer_Virtual_Guest\").build();\n      NotesToJson binder = new NotesToJson(json);\n      binder.bindToRequest(request, null);\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/java/org/jclouds/softlayer/binders/TagToJsonTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.binders;\n\nimport static org.testng.Assert.assertEquals;\nimport java.util.Set;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.json.Json;\nimport org.jclouds.json.internal.GsonWrapper;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.gson.Gson;\n\n@Test(groups = \"unit\", testName = \"TagToJsonTest\")\npublic class TagToJsonTest {\n\n   private Json json;\n\n   @BeforeClass\n   public void init() {\n      json = new GsonWrapper(new Gson());\n   }\n\n   @Test\n   public void testVirtualGuestWithOperatingSystem() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"https://api.softlayer.com/rest/v3/SoftLayer_Virtual_Guest\").build();\n      TagToJson binder = new TagToJson(json);\n      Set<String> tags = ImmutableSet.of(\"jclouds\");\n\n      request = binder.bindToRequest(request, tags);\n\n      assertEquals(request.getPayload().getRawContent(), \"{\\\"parameters\\\":[\\\"jclouds\\\"]}\");\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/java/org/jclouds/softlayer/binders/VirtualGuestToJsonTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.json.Json;\nimport org.jclouds.json.internal.GsonWrapper;\nimport org.jclouds.softlayer.domain.Datacenter;\nimport org.jclouds.softlayer.domain.OperatingSystem;\nimport org.jclouds.softlayer.domain.VirtualGuest;\nimport org.jclouds.softlayer.domain.VirtualGuestBlockDeviceTemplateGroup;\nimport org.jclouds.softlayer.domain.VirtualGuestNetworkComponent;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.gson.Gson;\n\n@Test(groups = \"unit\", testName = \"VirtualGuestToJsonTest\")\npublic class VirtualGuestToJsonTest {\n\n   private Json json;\n\n   @BeforeClass\n   public void init() {\n      json = new GsonWrapper(new Gson());\n   }\n\n   @Test\n   public void testVirtualGuestWithOperatingSystem() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"https://api.softlayer.com/rest/v3/SoftLayer_Virtual_Guest\").build();\n      VirtualGuestToJson binder = new VirtualGuestToJson(json);\n      VirtualGuest virtualGuestWithOS = VirtualGuest.builder()\n              .hostname(\"hostname\")\n              .domain(\"domain\")\n              .startCpus(1)\n              .maxMemory(1024)\n              .datacenter(Datacenter.builder()\n                      .name(\"datacenterName\")\n                      .build())\n              .operatingSystem(OperatingSystem.builder().id(\"123456789\")\n                      .operatingSystemReferenceCode(\"UBUNTU_12_64\")\n                      .build())\n              .localDiskFlag(true)\n              .networkComponents(ImmutableSet.<VirtualGuestNetworkComponent>of())\n              .build();\n\n      request = binder.bindToRequest(request, virtualGuestWithOS);\n\n      assertEquals(request.getPayload().getRawContent(), \"{\" +\n              \"\\\"parameters\\\":[{\\\"hostname\\\":\\\"hostname\\\",\\\"domain\\\":\\\"domain\\\",\\\"startCpus\\\":1,\\\"maxMemory\\\":1024,\\\"hourlyBillingFlag\\\":false,\\\"localDiskFlag\\\":true,\\\"dedicatedAccountHostOnlyFlag\\\":false,\\\"privateNetworkOnlyFlag\\\":false,\\\"operatingSystemReferenceCode\\\":\\\"UBUNTU_12_64\\\",\\\"datacenter\\\":{\\\"name\\\":\\\"datacenterName\\\"}}]}\");\n   }\n\n   @Test\n   public void testVirtualGuestWithVirtualGuestBlockDeviceTemplateGroup() {\n      HttpRequest request = HttpRequest.builder().method(\"POST\").endpoint(\"https://api.softlayer.com/rest/v3/SoftLayer_Virtual_Guest\").build();\n      VirtualGuestToJson binder = new VirtualGuestToJson(json);\n      VirtualGuest virtualGuestWithVirtualGuestBlockDeviceTemplateGroup = VirtualGuest.builder()\n              .hostname(\"hostname\")\n              .domain(\"domain\")\n              .startCpus(1)\n              .maxMemory(1024)\n              .datacenter(Datacenter.builder()\n                      .name(\"datacenterName\")\n                      .build())\n              .blockDeviceTemplateGroup(VirtualGuestBlockDeviceTemplateGroup.builder()\n                      .globalIdentifier(\"ffaafa98-4b4a-4fa7-b9f7-b1bad5ec50f0\")\n                      .build())\n              .localDiskFlag(true)\n              .networkComponents(ImmutableSet.<VirtualGuestNetworkComponent>of())\n              .build();\n\n      request = binder.bindToRequest(request, virtualGuestWithVirtualGuestBlockDeviceTemplateGroup);\n\n      assertEquals(request.getPayload().getRawContent(), \"{\" +\n              \"\\\"parameters\\\":[{\" +\n              \"\\\"hostname\\\":\\\"hostname\\\",\" +\n              \"\\\"domain\\\":\\\"domain\\\",\" +\n              \"\\\"startCpus\\\":1,\" +\n              \"\\\"maxMemory\\\":1024,\" +\n              \"\\\"hourlyBillingFlag\\\":false,\" +\n              \"\\\"localDiskFlag\\\":true,\" +\n              \"\\\"dedicatedAccountHostOnlyFlag\\\":false,\" +\n              \"\\\"privateNetworkOnlyFlag\\\":false,\" +\n              \"\\\"blockDeviceTemplateGroup\\\":{\\\"globalIdentifier\\\":\\\"ffaafa98-4b4a-4fa7-b9f7-b1bad5ec50f0\\\"},\" +\n              \"\\\"datacenter\\\":{\\\"name\\\":\\\"datacenterName\\\"}}]}\");\n   }\n\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/java/org/jclouds/softlayer/compute/SoftLayerComputeServiceAdapterLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.compute;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.net.HostAndPort;\nimport com.google.common.net.InetAddresses;\nimport com.google.inject.Injector;\nimport com.google.inject.Module;\nimport org.jclouds.compute.ComputeServiceAdapter.NodeAndInitialCredentials;\nimport org.jclouds.compute.domain.ExecResponse;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.domain.TemplateBuilder;\nimport org.jclouds.compute.functions.DefaultCredentialsFromImageOrOverridingCredentials;\nimport org.jclouds.compute.strategy.PrioritizeCredentialsFromTemplate;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.softlayer.SoftLayerApi;\nimport org.jclouds.softlayer.compute.options.SoftLayerTemplateOptions;\nimport org.jclouds.softlayer.compute.strategy.SoftLayerComputeServiceAdapter;\nimport org.jclouds.softlayer.domain.Datacenter;\nimport org.jclouds.softlayer.domain.VirtualGuest;\nimport org.jclouds.softlayer.features.BaseSoftLayerApiLiveTest;\nimport org.jclouds.ssh.SshClient;\nimport org.jclouds.ssh.SshClient.Factory;\nimport org.jclouds.sshj.config.SshjSshClientModule;\nimport org.testng.annotations.AfterGroups;\nimport org.testng.annotations.Test;\n\nimport java.util.Properties;\nimport java.util.Random;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"SoftLayerComputeServiceAdapterLiveTest\")\npublic class SoftLayerComputeServiceAdapterLiveTest extends BaseSoftLayerApiLiveTest {\n\n   private SoftLayerComputeServiceAdapter adapter;\n   private TemplateBuilder templateBuilder;\n   private Factory sshFactory;\n   private NodeAndInitialCredentials<VirtualGuest> guest;\n\n   @Override\n   protected SoftLayerApi create(Properties props, Iterable<Module> modules) {\n      Injector injector = newBuilder().modules(modules).overrides(props).buildInjector();\n      adapter = injector.getInstance(SoftLayerComputeServiceAdapter.class);\n      templateBuilder = injector.getInstance(TemplateBuilder.class);\n      sshFactory = injector.getInstance(SshClient.Factory.class);\n      return injector.getInstance(SoftLayerApi.class);\n   }\n\n   @Test\n   public void testListLocations() {\n      Iterable<Datacenter> locations = adapter.listLocations();\n      assertFalse(Iterables.isEmpty(locations), \"locations must not be empty\");\n   }\n\n   @Test\n   public void testListImages() {\n      assertFalse(Iterables.isEmpty(adapter.listImages()), \"images must not be empty\");\n   }\n\n   private static final PrioritizeCredentialsFromTemplate prioritizeCredentialsFromTemplate = new PrioritizeCredentialsFromTemplate(\n         new DefaultCredentialsFromImageOrOverridingCredentials());\n\n   @Test\n   public void testCreateNodeWithGroupEncodedIntoNameThenStoreCredentials() {\n      String group = \"foo\";\n      String name = \"node\" + new Random().nextInt();\n\n      Template template = templateBuilder.build();\n      // test passing custom options\n      template.getOptions().as(SoftLayerTemplateOptions.class).domainName(\"me.org\");\n\n      guest = adapter.createNodeWithGroupEncodedIntoName(group, name, template);\n      assertEquals(guest.getNode().getHostname(), name);\n      assertEquals(guest.getNodeId(), guest.getNode().getId() + \"\");\n      assertEquals(guest.getNode().getDomain(), template.getOptions().as(SoftLayerTemplateOptions.class)\n            .getDomainName());\n      assert InetAddresses.isInetAddress(guest.getNode().getPrimaryBackendIpAddress()) : guest;\n      doConnectViaSsh(guest.getNode(), prioritizeCredentialsFromTemplate.apply(template, guest.getCredentials()));\n   }\n\n   protected void doConnectViaSsh(VirtualGuest guest, LoginCredentials creds) {\n      SshClient ssh = sshFactory.create(HostAndPort.fromParts(guest.getPrimaryIpAddress(), 22), creds);\n      try {\n         ssh.connect();\n         ExecResponse hello = ssh.exec(\"echo hello\");\n         assertEquals(hello.getOutput().trim(), \"hello\");\n         System.err.println(ssh.exec(\"df -k\").getOutput());\n         System.err.println(ssh.exec(\"mount\").getOutput());\n         System.err.println(ssh.exec(\"uname -a\").getOutput());\n      } finally {\n         if (ssh != null)\n            ssh.disconnect();\n      }\n   }\n\n   @Test\n   public void testListHardwareProfiles() {\n      Iterable<Hardware> profiles = adapter.listHardwareProfiles();\n      assertFalse(Iterables.isEmpty(profiles));\n\n      for (Hardware profile : profiles) {\n         assertNotNull(profile);\n      }\n   }\n\n   @AfterGroups(groups = \"live\")\n   protected void tearDown() {\n      if (guest != null) {\n         adapter.destroyNode(guest.getNodeId() + \"\");\n      }\n      super.tearDown();\n   }\n\n   @Override\n   protected Iterable<Module> setupModules() {\n      return ImmutableSet.<Module> of(getLoggingModule(), new SshjSshClientModule());\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties properties = super.setupProperties();\n      properties.setProperty(\"jclouds.ssh.max-retries\", \"10\");\n      return properties;\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/java/org/jclouds/softlayer/compute/SoftLayerComputeServiceContextLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.compute;\n\nimport static org.testng.Assert.assertEquals;\nimport java.util.Set;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\n\nimport org.jclouds.compute.RunNodesException;\nimport org.jclouds.compute.domain.ExecResponse;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.internal.BaseComputeServiceContextLiveTest;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.logging.Logger;\nimport org.jclouds.softlayer.compute.options.SoftLayerTemplateOptions;\nimport org.jclouds.ssh.SshClient;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"live\", testName = \"SoftLayerComputeServiceContextLiveTest\")\npublic class SoftLayerComputeServiceContextLiveTest extends BaseComputeServiceContextLiveTest {\n\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   public SoftLayerComputeServiceContextLiveTest() {\n      provider = \"softlayer\";\n   }\n\n   @Test\n   public void testLaunchClusterWithDomainName() throws RunNodesException {\n      int numNodes = 1;\n      final String name = \"node\";\n      Template template = view.getComputeService().templateBuilder().build();\n      // test passing custom options\n      SoftLayerTemplateOptions options = template.getOptions().as(SoftLayerTemplateOptions.class);\n      options.domainName(\"live.org\");\n\n      //tags\n      options.tags(ImmutableList.of(\"jclouds\"));\n\n      Set<? extends NodeMetadata> nodes = view.getComputeService().createNodesInGroup(name, numNodes, template);\n      assertEquals(numNodes, nodes.size(), \"wrong number of nodes\");\n      for (NodeMetadata node : nodes) {\n         logger.debug(\"Created Node: %s\", node);\n         SshClient client = view.utils().sshForNode().apply(node);\n         client.connect();\n         ExecResponse hello = client.exec(\"mount\");\n         logger.debug(hello.getOutput().trim());\n         view.getComputeService().destroyNode(node.getId());\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/java/org/jclouds/softlayer/compute/SoftLayerComputeServiceLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.compute;\n\nimport java.util.Properties;\n\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.internal.BaseComputeServiceLiveTest;\nimport org.jclouds.sshj.config.SshjSshClientModule;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.inject.Module;\n\n@Test(groups = \"live\", enabled = true, singleThreaded = true)\npublic class SoftLayerComputeServiceLiveTest extends BaseComputeServiceLiveTest {\n\n   public SoftLayerComputeServiceLiveTest() {\n      provider = \"softlayer\";\n      group = \"soft-layer\";\n   }\n\n   @Override\n   protected Module getSshModule() {\n      return new SshjSshClientModule();\n   }\n\n   // softlayer does not support metadata\n   @Override\n   protected void checkUserMetadataContains(NodeMetadata node, ImmutableMap<String, String> userMetadata) {\n      assert node.getUserMetadata().equals(ImmutableMap.<String, String> of()) : String.format(\n            \"node userMetadata did not match %s %s\", userMetadata, node);\n   }\n\n   @Override\n   public void testOptionToNotBlock() {\n      // start call is blocking anyway.\n   }\n\n   @Override\n   protected Properties setupProperties() {\n      Properties properties = super.setupProperties();\n      properties.setProperty(\"jclouds.ssh.max-retries\", \"20\");\n      return properties;\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/java/org/jclouds/softlayer/compute/SoftLayerTemplateBuilderLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.compute;\n\nimport static org.jclouds.compute.util.ComputeServiceUtils.getCores;\nimport static org.jclouds.compute.util.ComputeServiceUtils.getSpace;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.domain.Volume;\nimport org.jclouds.compute.internal.BaseTemplateBuilderLiveTest;\nimport org.jclouds.softlayer.compute.options.SoftLayerTemplateOptions;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", alwaysRun = false)\npublic class SoftLayerTemplateBuilderLiveTest extends BaseTemplateBuilderLiveTest {\n\n   public static final int MAX_RAM = 64 * 1024;\n\n   public SoftLayerTemplateBuilderLiveTest() {\n      provider = \"softlayer\";\n   }\n\n   @Test\n   public void testDefaultTemplateBuilder() throws IOException {\n      Template defaultTemplate = view.getComputeService().templateBuilder().build();\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().getVersion(), \"14.04\");\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true);\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.UBUNTU);\n      assertEquals(getCores(defaultTemplate.getHardware()), 1.0d);\n      assertEquals(defaultTemplate.getHardware().getRam(), 1 * 1024);\n      assertEquals(getSpace(defaultTemplate.getHardware()), 25.0d);\n      assertEquals(defaultTemplate.getHardware().getVolumes().get(0).getType(), Volume.Type.LOCAL);\n      // test that we bound the correct templateoptions in guice\n      assertEquals(defaultTemplate.getOptions().getClass(), SoftLayerTemplateOptions.class);\n   }\n\n   @Test\n   public void testTemplateBuilderFindsGigabitUplink() throws IOException {\n      ComputeServiceContext context = null;\n      try {\n         Properties overrides = setupProperties();\n\n         context = createView(overrides, setupModules());\n\n         // TODO add something to the template about port speed?\n         context.getComputeService().templateBuilder().build();\n\n      } finally {\n         if (context != null)\n            context.close();\n      }\n   }\n\n   @Test\n   public void testTemplateBuilderFindsMegabitUplink() throws IOException {\n      ComputeServiceContext context = null;\n      try {\n         Properties overrides = setupProperties();\n         context = createView(overrides, setupModules());\n\n         // TODO add something to the template about port speed?\n         context.getComputeService().templateBuilder().build();\n\n      } finally {\n         if (context != null)\n            context.close();\n      }\n   }\n\n   @Test\n   public void testDefaultTemplateBuilderWhenPrivateNetwork() throws IOException {\n      ComputeServiceContext context = null;\n      try {\n         Properties overrides = setupProperties();\n         context = createView(overrides, setupModules());\n\n         Template template = context.getComputeService().templateBuilder().build();\n         assertEquals(getCores(template.getHardware()), 1.0d);\n         assertEquals(template.getHardware().getRam(), 1 * 1024);\n         assertEquals(getSpace(template.getHardware()), 25.0d);\n         assertEquals(template.getHardware().getVolumes().get(0).getType(), Volume.Type.LOCAL);\n      } finally {\n         if (context != null)\n            context.close();\n      }\n   }\n\n   @Test\n   public void testFastestTemplateBuilder() throws IOException {\n      Template template = view.getComputeService().templateBuilder().fastest().build();\n      assertEquals(getCores(template.getHardware()), 16.0d);\n      assertEquals(template.getHardware().getRam(), 1 * 1024);\n      assertEquals(getSpace(template.getHardware()), 25.0d);\n      assertEquals(template.getHardware().getVolumes().get(0).getType(), Volume.Type.LOCAL);\n   }\n\n   @Test\n   public void testBiggestTemplateBuilder() throws IOException {\n      Template template = view.getComputeService().templateBuilder().biggest().build();\n      assertEquals(getCores(template.getHardware()), 16.0d);\n      assertEquals(template.getHardware().getRam(), MAX_RAM);\n      assertEquals(getSpace(template.getHardware()), 100.0d);\n      assertEquals(template.getHardware().getVolumes().get(0).getType(), Volume.Type.LOCAL);\n   }\n\n   @Override\n   protected Set<String> getIso3166Codes() {\n      return createProviderMetadata().getIso3166Codes();\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/java/org/jclouds/softlayer/compute/functions/DatacenterToLocationTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.compute.functions;\n\nimport static org.testng.AssertJUnit.assertEquals;\nimport static org.testng.AssertJUnit.assertTrue;\n\nimport java.net.URI;\nimport java.util.Set;\n\nimport org.jclouds.domain.Location;\nimport org.jclouds.location.suppliers.all.JustProvider;\nimport org.jclouds.softlayer.domain.Address;\nimport org.jclouds.softlayer.domain.Datacenter;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Tests {@code DatacenterToLocation}\n */\n@Test(singleThreaded = true, groups = \"unit\")\npublic class DatacenterToLocationTest {\n\n   static DatacenterToLocation function = new DatacenterToLocation(new JustProvider(\"softlayer\", Suppliers\n            .ofInstance(URI.create(\"foo\")), ImmutableSet.<String> of()));\n\n   @Test\n   public void testDatacenterToLocation() {\n      Address address = Address.builder().country(\"US\").state(\"TX\").description(\"This is Texas!\").build();\n\n      Datacenter datacenter = Datacenter.builder().id(1).name(\"Texas\").longName(\"Texas Datacenter\")\n              .locationAddress(address).build();\n\n      Location location = function.apply(datacenter);\n\n      assertEquals(location.getId(), datacenter.getName());\n      Set<String> iso3166Codes = location.getIso3166Codes();\n      assertEquals(iso3166Codes.size(), 1);\n      assertTrue(iso3166Codes.contains(\"US-TX\"));\n   }\n\n   @Test\n   public void testGetIso3166CodeNoCountryAndState() {\n      Datacenter datacenter = Datacenter.builder().id(1).name(\"Nowhere\").longName(\"No where\").build();\n\n      Location location = function.apply(datacenter);\n\n      assertEquals(location.getId(), datacenter.getName());\n      Set<String> iso3166Codes = location.getIso3166Codes();\n      assertEquals(iso3166Codes.size(), 0);\n   }\n\n   @Test\n   public void testGetIso3166CodeCountryOnly() {\n      Address address = Address.builder().country(\"US\").description(\"This is North America!\").build();\n\n      Datacenter datacenter = Datacenter.builder().id(1).name(\"Nowhere\").longName(\"No where\").locationAddress(address)\n              .build();\n\n      Location location = function.apply(datacenter);\n\n      assertEquals(location.getId(), datacenter.getName());\n      Set<String> iso3166Codes = location.getIso3166Codes();\n      assertEquals(iso3166Codes.size(), 1);\n      assertTrue(iso3166Codes.contains(\"US\"));\n   }\n\n   @Test\n   public void testGetIso3166CodeWhitespaceTrimmer() {\n      Address address = Address.builder().country(\" US \").state(\"  TX  \").description(\"This is spaced out Texas\")\n            .build();\n\n      Datacenter datacenter = Datacenter.builder().id(1).name(\"NoWhere\").longName(\"Nowhere\").locationAddress(address)\n             .build();\n\n      Location location = function.apply(datacenter);\n\n      assertEquals(location.getId(), datacenter.getName());\n      Set<String> iso3166Codes = location.getIso3166Codes();\n      assertEquals(iso3166Codes.size(), 1);\n      assertTrue(iso3166Codes.contains(\"US-TX\"));\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/java/org/jclouds/softlayer/compute/functions/OperatingSystemToImageTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.compute.functions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.softlayer.domain.OperatingSystem;\nimport org.jclouds.softlayer.domain.SoftwareDescription;\nimport org.jclouds.softlayer.domain.SoftwareLicense;\nimport org.testng.annotations.Test;\n\n/**\n * Tests the function that transforms SoftLayer OperatingSystem to generic image.\n */\n@Test(groups = \"unit\", testName = \"OperatingSystemToImageTest\")\npublic class OperatingSystemToImageTest {\n\n   @Test\n   public void testOperatingSystemToImage() {\n      OperatingSystem operatingSystem = OperatingSystem.builder()\n              .id(\"UBUNTU_12_64\")\n              .softwareLicense(SoftwareLicense.builder()\n                      .softwareDescription(SoftwareDescription.builder()\n                              .version(\"12.04-64 Minimal for CCI\")\n                              .referenceCode(\"UBUNTU_12_64\")\n                              .longDescription(\"Ubuntu Linux 12.04 LTS Precise Pangolin - Minimal Install (64 bit)\")\n                              .build())\n                      .build())\n              .build();\n      Image image = new OperatingSystemToImage().apply(operatingSystem);\n\n      assertEquals(image.getId(), operatingSystem.getId());\n      String referenceCode = operatingSystem.getSoftwareLicense().getSoftwareDescription().getReferenceCode();\n      assertEquals(image.getDescription(), referenceCode);\n      assertTrue(image.getOperatingSystem().getFamily().toString().equalsIgnoreCase(\"UBUNTU\"));\n      assertEquals(image.getOperatingSystem().getVersion(), \"12.04\");\n      assertEquals(image.getOperatingSystem().is64Bit(), true);\n      assertEquals(image.getStatus(), Image.Status.AVAILABLE);\n   }\n\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/java/org/jclouds/softlayer/compute/functions/VirtualGuestToHardwareTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.compute.functions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.softlayer.domain.Datacenter;\nimport org.jclouds.softlayer.domain.OperatingSystem;\nimport org.jclouds.softlayer.domain.VirtualGuest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Iterables;\n\n/**\n * Tests the function that transforms SoftLayer VirtualGuest to generic hardware.\n */\n@Test(groups = \"unit\", testName = \"VirtualGuestToHardwareTest\")\npublic class VirtualGuestToHardwareTest {\n\n   @Test\n   public void testVirtualGuestToHardware() {\n      VirtualGuest virtualGuest = createVirtualGuest();\n      Hardware hardware = new VirtualGuestToHardware().apply(virtualGuest);\n      assertNotNull(hardware);\n      assertEquals(hardware.getRam(), virtualGuest.getMaxMemory());\n      assertTrue(hardware.getProcessors().size() == 1);\n      assertEquals(Iterables.get(hardware.getProcessors(), 0).getCores(), (double) virtualGuest.getStartCpus());\n   }\n\n   private VirtualGuest createVirtualGuest() {\n      return VirtualGuest.builder()\n              .domain(\"example.com\")\n              .hostname(\"host1\")\n              .id(1301396)\n              .maxMemory(1024)\n              .startCpus(1)\n              .localDiskFlag(true)\n              .operatingSystem(OperatingSystem.builder().id(\"UBUNTU_LATEST\")\n                      .operatingSystemReferenceCode(\"UBUNTU_LATEST\")\n                      .build())\n              .datacenter(Datacenter.builder().name(\"test\").build())\n              .build();\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/java/org/jclouds/softlayer/compute/functions/VirtualGuestToImageTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.compute.functions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\n\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.softlayer.domain.Datacenter;\nimport org.jclouds.softlayer.domain.OperatingSystem;\nimport org.jclouds.softlayer.domain.SoftwareDescription;\nimport org.jclouds.softlayer.domain.SoftwareLicense;\nimport org.jclouds.softlayer.domain.VirtualGuest;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Guice;\n\n/**\n * Tests the function that transforms SoftLayer VirtualGuest to generic image.\n */\n@Test(groups = \"unit\", testName = \"VirtualGuestToImageTest\")\npublic class VirtualGuestToImageTest {\n\n   OperatingSystemToImage operatingSystemToImage = Guice.createInjector().getInstance(OperatingSystemToImage.class);\n\n   @Test\n   public void testVirtualGuestToImageWhenOperatingSystemIsNull() {\n      VirtualGuest virtualGuest = createVirtualGuestWithoutOperatingSystem();\n      Image image = new VirtualGuestToImage(operatingSystemToImage).apply(virtualGuest);\n      assertNotNull(image);\n      assertEquals(image.getStatus(), Image.Status.UNRECOGNIZED);\n      assertEquals(image.getOperatingSystem().getFamily(), OsFamily.UNRECOGNIZED);\n      assertEquals(image.getOperatingSystem().getVersion(), \"UNRECOGNIZED\");\n   }\n\n   @Test\n   public void testVirtualGuestToImageWhenVirtualGuestIsSoftwareLicense() {\n      VirtualGuest virtualGuest = createVirtualGuestWithoutSoftwareLicenseDetails();\n      Image image = new VirtualGuestToImage(operatingSystemToImage).apply(virtualGuest);\n      assertNotNull(image);\n      assertEquals(image.getOperatingSystem().getFamily(), OsFamily.UNRECOGNIZED);\n      assertEquals(image.getOperatingSystem().getVersion(), \"UNRECOGNIZED\");\n   }\n\n   @Test\n   public void testVirtualGuestToImageWithSoftwareLicense() {\n      VirtualGuest virtualGuest = createVirtualGuestWithSoftwareLicenseDetails();\n      Image image = new VirtualGuestToImage(operatingSystemToImage).apply(virtualGuest);\n      assertNotNull(image);\n      assertEquals(image.getOperatingSystem().getFamily(), OsFamily.UBUNTU);\n      assertEquals(image.getOperatingSystem().getVersion(), \"12.04\");\n      assertEquals(image.getOperatingSystem().is64Bit(), true);\n   }\n\n   private VirtualGuest createVirtualGuestWithoutOperatingSystem() {\n      return VirtualGuest.builder()\n              .domain(\"example.com\")\n              .hostname(\"host1\")\n              .id(1301396)\n              .maxMemory(1024)\n              .startCpus(1)\n              .localDiskFlag(true)\n              .datacenter(Datacenter.builder().name(\"test\").build())\n              .softwareLicense(SoftwareLicense.builder().build())\n              .build();\n   }\n\n   private VirtualGuest createVirtualGuestWithoutSoftwareLicenseDetails() {\n      return VirtualGuest.builder()\n              .domain(\"example.com\")\n              .hostname(\"host1\")\n              .id(1301396)\n              .maxMemory(1024)\n              .startCpus(1)\n              .localDiskFlag(true)\n              .operatingSystem(OperatingSystem.builder().id(\"UBUNTU_LATEST\")\n                      .operatingSystemReferenceCode(\"UBUNTU_LATEST\")\n                      .build())\n              .datacenter(Datacenter.builder().name(\"test\").build())\n              .build();\n   }\n\n   private VirtualGuest createVirtualGuestWithSoftwareLicenseDetails() {\n      return VirtualGuest.builder()\n              .domain(\"example.com\")\n              .hostname(\"host1\")\n              .id(1301396)\n              .maxMemory(1024)\n              .startCpus(1)\n              .localDiskFlag(true)\n              .operatingSystem(OperatingSystem.builder().id(\"UBUNTU_LATEST\")\n                      .operatingSystemReferenceCode(\"UBUNTU_LATEST\")\n                      .softwareLicense(SoftwareLicense.builder()\n                              .softwareDescription(SoftwareDescription.builder()\n                                      .version(\"12.04-64 Minimal for CCI\")\n                                      .referenceCode(\"UBUNTU_12_64\")\n                                      .longDescription(\"Ubuntu Linux 12.04 LTS Precise Pangolin - Minimal Install (64 bit)\")\n                                      .build())\n                              .build())\n                      .build())\n              .datacenter(Datacenter.builder().name(\"test\").build())\n              .build();\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/java/org/jclouds/softlayer/compute/functions/VirtualGuestToNodeMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.compute.functions;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.Set;\n\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.softlayer.domain.Datacenter;\nimport org.jclouds.softlayer.domain.OperatingSystem;\nimport org.jclouds.softlayer.domain.Password;\nimport org.jclouds.softlayer.domain.PowerState;\nimport org.jclouds.softlayer.domain.SoftwareDescription;\nimport org.jclouds.softlayer.domain.SoftwareLicense;\nimport org.jclouds.softlayer.domain.VirtualGuest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Sets;\nimport com.google.inject.Guice;\n\n/**\n * Tests the function that transforms SoftLayer VirtualGuest to NodeMetadata.\n */\n@Test(groups = \"unit\", testName = \"VirtualGuestToNodeMetadataTest\")\npublic class VirtualGuestToNodeMetadataTest {\n\n   VirtualGuestToImage virtualGuestToImage = Guice.createInjector().getInstance(VirtualGuestToImage.class);\n   VirtualGuestToHardware virtualGuestToHardware = Guice.createInjector().getInstance(VirtualGuestToHardware.class);\n   GroupNamingConvention.Factory namingConvention = Guice.createInjector().getInstance(GroupNamingConvention.Factory.class);\n\n   Location location = new LocationBuilder().id(\"test\")\n                                            .description(\"example\")\n                                            .scope(LocationScope.ZONE)\n                                            .build();\n   Supplier<Set<? extends Location>> locationSupplier = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet.of(location));\n\n   @Test\n   public void testVirtualGuestToNodeMetadata() {\n\n      VirtualGuest virtualGuest = createVirtualGuest();\n      NodeMetadata nodeMetadata = new VirtualGuestToNodeMetadata(locationSupplier, namingConvention,\n              virtualGuestToImage, virtualGuestToHardware).apply(virtualGuest);\n      assertNotNull(nodeMetadata);\n      assertEquals(nodeMetadata.getName(), virtualGuest.getHostname());\n      assertNotNull(nodeMetadata.getLocation());\n      assertEquals(nodeMetadata.getLocation().getId(), location.getId());\n      assertEquals(nodeMetadata.getHostname(), virtualGuest.getFullyQualifiedDomainName());\n      assertEquals(nodeMetadata.getHardware().getRam(), virtualGuest.getMaxMemory());\n      assertTrue(nodeMetadata.getHardware().getProcessors().size() == 1);\n      assertEquals(Iterables.get(nodeMetadata.getHardware().getProcessors(), 0).getCores(), (double) virtualGuest.getStartCpus());\n      assertEquals(nodeMetadata.getOperatingSystem().getFamily(), OsFamily.UBUNTU);\n      assertEquals(nodeMetadata.getOperatingSystem().getVersion(), \"12.04\");\n      assertEquals(nodeMetadata.getOperatingSystem().is64Bit(), true);\n   }\n\n   private VirtualGuest createVirtualGuest() {\n      return VirtualGuest.builder()\n              .domain(\"example.com\")\n              .hostname(\"host1\")\n              .fullyQualifiedDomainName(\"host1.example.com\")\n              .id(1301396)\n              .maxMemory(1024)\n              .startCpus(1)\n              .localDiskFlag(true)\n              .operatingSystem(OperatingSystem.builder().id(\"UBUNTU_LATEST\")\n                      .operatingSystemReferenceCode(\"UBUNTU_LATEST\")\n                      .softwareLicense(SoftwareLicense.builder()\n                              .softwareDescription(SoftwareDescription.builder()\n                                      .version(\"12.04-64 Minimal for CCI\")\n                                      .referenceCode(\"UBUNTU_12_64\")\n                                      .longDescription(\"Ubuntu Linux 12.04 LTS Precise Pangolin - Minimal Install (64 bit)\")\n                                      .build())\n                              .build())\n                      .build())\n              .datacenter(Datacenter.builder().name(\"test\").build())\n              .powerState(PowerState.builder().keyName(VirtualGuest.State.RUNNING).build())\n              .build();\n   }\n\n   @Test(expectedExceptions = { IllegalStateException.class })\n   public void testGetBestPasswordNone() {\n      Set<Password> passwords = Sets.newLinkedHashSet();\n      VirtualGuestToNodeMetadata f = new VirtualGuestToNodeMetadata(locationSupplier, namingConvention, \n         virtualGuestToImage, virtualGuestToHardware);\n      f.getBestPassword(passwords, null);\n   }\n   \n   @Test\n   public void testGetBestPasswordOneRoot() {\n      Set<Password> passwords = Sets.newLinkedHashSet();\n      passwords.add(new Password(1, \"root\", \"pass\"));\n      VirtualGuestToNodeMetadata f = new VirtualGuestToNodeMetadata(locationSupplier, namingConvention, \n         virtualGuestToImage, virtualGuestToHardware);\n      Password best = f.getBestPassword(passwords, null);\n      assertEquals(best.getUsername(), \"root\");\n   }\n   \n   @Test\n   public void testGetBestPasswordOneNonRoot() {\n      Set<Password> passwords = Sets.newLinkedHashSet();\n      passwords.add(new Password(1, \"nonroot\", \"word\"));\n      VirtualGuestToNodeMetadata f = new VirtualGuestToNodeMetadata(locationSupplier, namingConvention, \n         virtualGuestToImage, virtualGuestToHardware);\n      Password best = f.getBestPassword(passwords, null);\n      assertEquals(best.getUsername(), \"nonroot\");\n   }\n   \n   @Test\n   public void testGetBestPasswordTwoDifferent() {\n      Set<Password> passwords = Sets.newLinkedHashSet();\n      passwords.add(new Password(1, \"nonroot\", \"word\"));\n      passwords.add(new Password(2, \"root\", \"pass\"));\n      VirtualGuestToNodeMetadata f = new VirtualGuestToNodeMetadata(locationSupplier, namingConvention, \n         virtualGuestToImage, virtualGuestToHardware);\n      Password best = f.getBestPassword(passwords, null);\n      assertEquals(best.getUsername(), \"root\");\n   }\n   \n   @Test\n   public void testGetBestPasswordTwoSame() {\n      Set<Password> passwords = Sets.newLinkedHashSet();\n      passwords.add(new Password(1, \"root\", \"word\"));\n      passwords.add(new Password(2, \"root\", \"pass\"));\n      VirtualGuestToNodeMetadata f = new VirtualGuestToNodeMetadata(locationSupplier, namingConvention, \n         virtualGuestToImage, virtualGuestToHardware);\n      Password best = f.getBestPassword(passwords, null);\n      assertEquals(best.getUsername(), \"root\");\n      // should take the first\n      assertEquals(best.getPassword(), \"word\");\n   }\n   \n}\n"
  },
  {
    "path": "providers/softlayer/src/test/java/org/jclouds/softlayer/compute/functions/internal/OperatingSystemsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.compute.functions.internal;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.compute.domain.OsFamily;\nimport org.testng.annotations.Test;\n\n@Test(singleThreaded = true, groups = \"unit\")\npublic class OperatingSystemsTest {\n\n   @Test\n   public void testOsFamily() {\n      assertEquals(OperatingSystems.osFamily().apply(OperatingSystems.CENTOS), OsFamily.CENTOS);\n      assertEquals(OperatingSystems.osFamily().apply(OperatingSystems.DEBIAN), OsFamily.DEBIAN);\n      assertEquals(OperatingSystems.osFamily().apply(OperatingSystems.RHEL), OsFamily.RHEL);\n      assertEquals(OperatingSystems.osFamily().apply(OperatingSystems.UBUNTU), OsFamily.UBUNTU);\n      assertEquals(OperatingSystems.osFamily().apply(OperatingSystems.WINDOWS), OsFamily.WINDOWS);\n      assertEquals(OperatingSystems.osFamily().apply(OperatingSystems.CLOUD_LINUX), OsFamily.CLOUD_LINUX);\n      assertEquals(OperatingSystems.osFamily().apply(OperatingSystems.VYATTACE), OsFamily.LINUX);\n   }\n\n   @Test\n   public void testOsBits() {\n      assertEquals(OperatingSystems.bits().apply(\"UBUNTU_12_64\").intValue(), 64);\n      assertEquals(OperatingSystems.bits().apply(\"UBUNTU_12_32\").intValue(), 32);\n   }\n\n   @Test\n   public void testOsVersion() {\n      assertEquals(OperatingSystems.version().apply(\"12.04-64 Minimal for VSI\"), \"12.04\");\n      assertEquals(OperatingSystems.version().apply(\"STD 32 bit\"), \"STD\");\n   }\n\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/java/org/jclouds/softlayer/compute/options/SoftLayerTemplateOptionsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.compute.options;\n\nimport static org.jclouds.softlayer.compute.options.SoftLayerTemplateOptions.Builder.domainName;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.fail;\n\nimport org.jclouds.compute.options.TemplateOptions;\nimport org.testng.annotations.Test;\n\n/**\n * Tests possible uses of {@code SoftLayerTemplateOptions} and {@code\n * SoftLayerTemplateOptions.Builder.*}.\n */\n// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire\n@Test(groups = \"unit\", testName = \"SoftLayerTemplateOptionsTest\")\npublic class SoftLayerTemplateOptionsTest {\n   @Test\n   public void testAs() {\n      TemplateOptions options = new SoftLayerTemplateOptions();\n      assertEquals(options.as(SoftLayerTemplateOptions.class), options);\n   }\n\n   @Test\n   public void testDefaultDomainName() {\n      TemplateOptions options = new SoftLayerTemplateOptions();\n      assertEquals(options.as(SoftLayerTemplateOptions.class).getDomainName(), \"jclouds.org\");\n   }\n\n   @Test\n   public void testDomainName() {\n      TemplateOptions options = new SoftLayerTemplateOptions().domainName(\"me.com\");\n      assertEquals(options.as(SoftLayerTemplateOptions.class).getDomainName(), \"me.com\");\n   }\n\n   @Test\n   public void testDomainNameStatic() {\n      TemplateOptions options = domainName(\"me.com\");\n      assertEquals(options.as(SoftLayerTemplateOptions.class).getDomainName(), \"me.com\");\n   }\n\n   @Test\n   public void testDomainNameNullHasDecentMessage() {\n      try {\n         new SoftLayerTemplateOptions().domainName(null);\n         fail(\"should NPE\");\n      } catch (NullPointerException e) {\n         assertEquals(e.getMessage(), \"domainName was null\");\n      }\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testDomainNameIsInvalidThrowsIllegalArgument() {\n      new SoftLayerTemplateOptions().domainName(\"notapublicsuffix\");\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/java/org/jclouds/softlayer/domain/AddressTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.domain;\n\nimport org.testng.annotations.Test;\n\n@Test(singleThreaded = true, groups = \"unit\")\npublic class AddressTest {\n\n    @Test(expectedExceptions = java.lang.NullPointerException.class )\n    public void testConstructionWithEmpty() {\n        Address.builder().country(null).build();\n    }\n\n    @Test(expectedExceptions = java.lang.NullPointerException.class )\n    public void testConstructionWithNoCountry() {\n        Address.builder().country(\"\").build();\n    }\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/java/org/jclouds/softlayer/domain/ContainerVirtualGuestConfigurationTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.domain;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Set;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\n\n@Test(groups = \"unit\")\npublic class ContainerVirtualGuestConfigurationTest {\n   @Test\n   public void testGetVirtualGuestOperatingSystemsWithMissingReferenceCode() {\n      // Malformed response leading to failure:\n      // {\n      //    \"itemPrice\": {\n      //        \"hourlyRecurringFee\": \".131\",\n      //        \"item\": {\n      //            \"description\": \"Windows Server 2012 Datacenter Edition (64bit)\"\n      //        },\n      //        \"recurringFee\": \"90.63\"\n      //    },\n      //    \"template\": {\n      //        \"id\": null\n      //        missing operatingSystemReferenceCode entry!\n      //    }\n      // },\n\n      ContainerVirtualGuestConfigurationOption osValid = ContainerVirtualGuestConfigurationOption.builder()\n            .productItemPrice(ProductItemPrice.builder()\n                    .hourlyRecurringFee(0)\n                    .recurringFee(\"0\")\n                    .item(ProductItem.builder().description(\"CentOS - Latest\").build())\n                    .build())\n            .template(VirtualGuest.builder().operatingSystemReferenceCode(\"CENTOS_LATEST\").build())\n            .build();\n      ContainerVirtualGuestConfigurationOption osInvalid = ContainerVirtualGuestConfigurationOption.builder()\n            .productItemPrice(ProductItemPrice.builder()\n                    .hourlyRecurringFee(0.131f)\n                    .recurringFee(\"90.63\")\n                    .item(ProductItem.builder().description(\"Windows Server 2012 Datacenter Edition (64bit)\").build())\n                    .build())\n            .template(VirtualGuest.builder().build())\n            .build();\n      ContainerVirtualGuestConfiguration conf = ContainerVirtualGuestConfiguration.builder()\n         .blockDevices(ImmutableSet.<ContainerVirtualGuestConfigurationOption>of())\n         .datacenters(ImmutableSet.<ContainerVirtualGuestConfigurationOption>of())\n         .memory(ImmutableSet.<ContainerVirtualGuestConfigurationOption>of())\n         .networkComponents(ImmutableSet.<ContainerVirtualGuestConfigurationOption>of())\n         .operatingSystems(ImmutableSet.<ContainerVirtualGuestConfigurationOption>of(osValid, osInvalid))\n         .processors(ImmutableSet.<ContainerVirtualGuestConfigurationOption>of())\n         .build();\n      Set<OperatingSystem> virtualGuestOperatingSystems = conf.getVirtualGuestOperatingSystems();\n      OperatingSystem os = Iterables.getOnlyElement(virtualGuestOperatingSystems);\n      assertEquals(os.getOperatingSystemReferenceCode(), osValid.getTemplate().getOperatingSystemReferenceCode());\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/java/org/jclouds/softlayer/features/AccountApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.features;\n\nimport org.jclouds.softlayer.domain.VirtualGuest;\nimport org.jclouds.softlayer.domain.VirtualGuestBlockDeviceTemplateGroup;\nimport org.testng.annotations.Test;\n\nimport java.util.Set;\n\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\n/**\n * Tests behavior of {@code AccountApi}\n */\n@Test(groups = \"live\")\npublic class AccountApiLiveTest extends BaseSoftLayerApiLiveTest {\n\n   @Test\n   public void testGetBlockDeviceTemplateGroups() {\n      Set<VirtualGuestBlockDeviceTemplateGroup> privateImages = api().getBlockDeviceTemplateGroups();\n      assertNotNull(privateImages);\n      for (VirtualGuestBlockDeviceTemplateGroup privateImage : privateImages) {\n         assertTrue(privateImage.getId() > 0, \"id must be greater than 0\");\n         assertTrue(privateImage.getStatusId() > 0, \"status id must be greater than 0\");\n         assertTrue(privateImage.getAccountId() > 0, \"id must be greater than 0\");\n      }\n   }\n\n   @Test\n   public void testListVirtualGuests() throws Exception {\n      Set<VirtualGuest> response = api().listVirtualGuests();\n      assertTrue(response.size() > 0);\n      for (VirtualGuest vg : response) {\n         checkVirtualGuest(vg);\n      }\n   }\n\n   private AccountApi api() {\n      return api.getAccountApi();\n   }\n\n   private void checkVirtualGuest(VirtualGuest vg) {\n      if (vg.getActiveTransactionCount() == 0) {\n         assertNotNull(vg.getDomain(), \"domain must be not null\");\n         assertNotNull(vg.getFullyQualifiedDomainName(), \"fullyQualifiedDomainName must be not null\");\n         assertNotNull(vg.getHostname(), \"hostname must be not null\");\n         assertTrue(vg.getId() > 0, \"id must be greater than 0\");\n         assertTrue(vg.getMaxCpu() > 0, \"maxCpu must be greater than 0\");\n         assertNotNull(vg.getMaxCpuUnits(), \"maxCpuUnits must be not null\");\n         assertTrue(vg.getMaxMemory() > 0, \"maxMemory must be greater than 0\");\n         assertTrue(vg.getStartCpus() > 0, \"startCpus must be greater than 0\");\n         assertTrue(vg.getStatusId() > 0, \"statusId must be greater than 0\");\n         assertNotNull(vg.getUuid(), \"uuid must be not null\");\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/java/org/jclouds/softlayer/features/AccountApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\n\nimport org.jclouds.http.config.JavaUrlHttpCommandExecutorServiceModule;\nimport org.jclouds.softlayer.SoftLayerApi;\nimport org.jclouds.softlayer.config.SoftLayerParserModule;\nimport org.jclouds.softlayer.internal.BaseSoftLayerMockTest;\nimport org.jclouds.softlayer.parse.VirtualGuestBlockDeviceTemplateGroupsParseTest;\nimport org.jclouds.softlayer.parse.VirtualGuestsParseTest;\nimport org.testng.annotations.Test;\n\n\n/**\n * Mock tests for the {@link org.jclouds.softlayer.features.AccountApi} class.\n */\n@Test(groups = \"unit\", testName = \"AccountApiMockTest\")\npublic class AccountApiMockTest extends BaseSoftLayerMockTest {\n\n   public void testListVirtualGuests() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(payloadFromResource(\"/account_list.json\")));\n      AccountApi api = getAccountApi(server);\n      try {\n         assertEquals(api.listVirtualGuests(), new VirtualGuestsParseTest().expected());\n         assertSent(server, \"GET\", \"/SoftLayer_Account/VirtualGuests?objectMask=powerState%3BoperatingSystem.passwords%3Bdatacenter%3BbillingItem%3BblockDevices.diskImage%3BtagReferences.tag.name\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testEmptyListVirtualGuests() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(404));\n      AccountApi api = getAccountApi(server);\n      try {\n         assertTrue(api.listVirtualGuests().isEmpty());\n         assertSent(server, \"GET\", \"/SoftLayer_Account/VirtualGuests?objectMask=powerState%3BoperatingSystem.passwords%3Bdatacenter%3BbillingItem%3BblockDevices.diskImage%3BtagReferences.tag.name\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGetBlockDeviceTemplateGroups() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(payloadFromResource(\"/account_get_block_devices_template_groups.json\")));\n      AccountApi api = api(SoftLayerApi.class, server.url(\"/\").toString()).getAccountApi();\n      try {\n         assertEquals(api.getBlockDeviceTemplateGroups(), new VirtualGuestBlockDeviceTemplateGroupsParseTest().expected());\n         assertSent(server, \"GET\", \"/SoftLayer_Account/getBlockDeviceTemplateGroups?objectMask=children.blockDevices.diskImage.softwareReferences.softwareDescription\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testEmptyBlockDeviceTemplateGroups() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(404));\n      AccountApi api = getAccountApi(server);\n      try {\n         assertTrue(api.getBlockDeviceTemplateGroups().isEmpty());\n         assertSent(server, \"GET\", \"/SoftLayer_Account/getBlockDeviceTemplateGroups?objectMask=children.blockDevices.diskImage.softwareReferences.softwareDescription\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   private AccountApi getAccountApi(MockWebServer server) {\n      return api(SoftLayerApi.class, server.url(\"/\").toString(), new\n              JavaUrlHttpCommandExecutorServiceModule(), new SoftLayerParserModule()).getAccountApi();\n   }\n\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/java/org/jclouds/softlayer/features/BaseSoftLayerApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.features;\n\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.rest.internal.BaseRestApiExpectTest;\nimport org.jclouds.softlayer.SoftLayerApi;\nimport org.jclouds.softlayer.SoftLayerProviderMetadata;\n\npublic abstract class BaseSoftLayerApiExpectTest extends BaseRestApiExpectTest<SoftLayerApi> {\n\n   @Override\n   public ProviderMetadata createProviderMetadata() {\n      return new SoftLayerProviderMetadata();\n   }\n\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/java/org/jclouds/softlayer/features/BaseSoftLayerApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.features;\n\nimport org.jclouds.apis.BaseApiLiveTest;\nimport org.jclouds.softlayer.SoftLayerApi;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code SoftLayerApi}\n */\n@Test(groups = \"live\")\npublic class BaseSoftLayerApiLiveTest extends BaseApiLiveTest<SoftLayerApi> {\n\n   public BaseSoftLayerApiLiveTest() {\n      this.provider = \"softlayer\";\n   }\n\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/java/org/jclouds/softlayer/features/DatacenterApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\nimport java.util.Set;\n\nimport org.jclouds.softlayer.domain.Address;\nimport org.jclouds.softlayer.domain.Datacenter;\nimport org.jclouds.softlayer.domain.Region;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\n\n/**\n * Tests behavior of {@code DatacenterApi}\n */\n@Test(groups = \"live\")\npublic class DatacenterApiLiveTest extends BaseSoftLayerApiLiveTest {\n\n   @Test\n   public void testListDatacenters() {\n      Set<Datacenter> response = api().listDatacenters();\n      assertNotNull(response);\n      assertTrue(response.size() > 0);\n      for (Datacenter vg : response) {\n         Datacenter newDetails = api().getDatacenter(vg.getId());\n         assertEquals(vg.getId(), newDetails.getId());\n         checkDatacenter(newDetails);\n      }\n   }\n\n   @Test\n   public void testListDatacentersContent() {\n      Builder<Datacenter> builder = ImmutableSet.builder();\n      builder.add(Datacenter.builder().id(265592).name(\"ams01\").longName(\"Amsterdam 1\").build());\n      builder.add(Datacenter.builder().id(814994).name(\"ams03\").longName(\"Amsterdam 3\").build());\n      builder.add(Datacenter.builder().id(3).name(\"dal01\").longName(\"Dallas\").build());\n      builder.add(Datacenter.builder().id(154770).name(\"dal02\").longName(\"Dallas 2\").build());\n      builder.add(Datacenter.builder().id(167092).name(\"dal04\").longName(\"Dallas 4\").build());\n      builder.add(Datacenter.builder().id(138124).name(\"dal05\").longName(\"Dallas 5\").build());\n      builder.add(Datacenter.builder().id(154820).name(\"dal06\").longName(\"Dallas 6\").build());\n      builder.add(Datacenter.builder().id(142776).name(\"dal07\").longName(\"Dallas 7\").build());\n      builder.add(Datacenter.builder().id(449494).name(\"dal09\").longName(\"Dallas 9\").build());\n      builder.add(Datacenter.builder().id(449506).name(\"fra02\").longName(\"Frankfurt 2\").build());\n      builder.add(Datacenter.builder().id(352494).name(\"hkg02\").longName(\"Hong Kong 2\").build());\n      builder.add(Datacenter.builder().id(142775).name(\"hou02\").longName(\"Houston 2\").build());\n      builder.add(Datacenter.builder().id(358694).name(\"lon02\").longName(\"London 2\").build());\n      builder.add(Datacenter.builder().id(449596).name(\"mel01\").longName(\"Melbourne 1\").build());\n      builder.add(Datacenter.builder().id(449600).name(\"mex01\").longName(\"Mexico 1\").build());\n      builder.add(Datacenter.builder().id(815394).name(\"mil01\").longName(\"Milan 1\").build());\n      builder.add(Datacenter.builder().id(449610).name(\"mon01\").longName(\"Montreal 1\").build());\n      builder.add(Datacenter.builder().id(449500).name(\"par01\").longName(\"Paris 1\").build());\n      builder.add(Datacenter.builder().id(168642).name(\"sjc01\").longName(\"San Jose 1\").build());\n      builder.add(Datacenter.builder().id(18171).name(\"sea01\").longName(\"Seattle\").build());\n      builder.add(Datacenter.builder().id(224092).name(\"sng01\").longName(\"Singapore 1\").build());\n      builder.add(Datacenter.builder().id(449612).name(\"syd01\").longName(\"Sydney 1\").build());\n      builder.add(Datacenter.builder().id(449604).name(\"tok02\").longName(\"Tokio 2\").build());\n      builder.add(Datacenter.builder().id(448994).name(\"tor01\").longName(\"Toronto 1\").build());\n      builder.add(Datacenter.builder().id(37473).name(\"wdc01\").longName(\"Washington, DC 1\").build());\n\n      Set<Datacenter> response = api().listDatacenters();\n      Set<Datacenter> expected = builder.build();\n\n      assertEquals(response.size(), expected.size());\n\n      for (Datacenter datacenter : response) {\n         Address address = datacenter.getLocationAddress();\n         if (address != null) checkAddress(address);\n      }\n   }\n\n   private DatacenterApi api() {\n      return api.getDatacenterApi();\n   }\n\n   private void checkDatacenter(Datacenter dc) {\n      assertNotNull(dc.getId());\n      assertNotNull(dc.getName());\n      assertNotNull(dc.getLongName());\n      for (Region region : dc.getRegions()) checkRegion(region);\n   }\n\n   private void checkRegion(Region region) {\n      assertNotNull(region.getDescription());\n      assertNotNull(region.getKeyname());\n   }\n\n   private void checkAddress(Address address) {\n      assertNotNull(address.getId());\n      assertNotNull(address.getCountry());\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/java/org/jclouds/softlayer/features/DatacenterApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\n\nimport org.jclouds.softlayer.SoftLayerApi;\nimport org.jclouds.softlayer.internal.BaseSoftLayerMockTest;\nimport org.jclouds.softlayer.parse.DatacenterParseTest;\nimport org.jclouds.softlayer.parse.DatacentersParseTest;\nimport org.testng.annotations.Test;\n\n\n/**\n * Mock tests for the {@link org.jclouds.softlayer.features.DatacenterApi} class.\n */\n@Test(groups = \"unit\", testName = \"DatacenterApiMockTest\")\npublic class DatacenterApiMockTest extends BaseSoftLayerMockTest {\n\n   public void testListDatacenters() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(payloadFromResource(\"/datacenter_list.json\")));\n      DatacenterApi api = getDatacenterApi(server);\n      try {\n         assertEquals(api.listDatacenters(), new DatacentersParseTest().expected());\n         assertSent(server, \"GET\", \"/SoftLayer_Location_Datacenter/Datacenters?objectMask=locationAddress%3Bregions\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n\n   public void testEmptyListDatacenters() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(404));\n      DatacenterApi api = getDatacenterApi(server);\n      try {\n         assertTrue(api.listDatacenters().isEmpty());\n         assertSent(server, \"GET\", \"/SoftLayer_Location_Datacenter/Datacenters?objectMask=locationAddress%3Bregions\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGetDatacenter() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(payloadFromResource(\"/datacenter_get.json\")));\n      DatacenterApi api = getDatacenterApi(server);\n      try {\n         assertEquals(api.getDatacenter(265592), new DatacenterParseTest().expected());\n         assertSent(server, \"GET\", \"/SoftLayer_Location_Datacenter/265592?objectMask=locationAddress%3Bregions\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGetNullDatacenter() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(404));\n      DatacenterApi api = getDatacenterApi(server);\n      try {\n         assertNull(api.getDatacenter(265592));\n         assertSent(server, \"GET\", \"/SoftLayer_Location_Datacenter/265592?objectMask=locationAddress%3Bregions\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   private DatacenterApi getDatacenterApi(MockWebServer server) {\n      return api(SoftLayerApi.class, server.url(\"/\").toString()).getDatacenterApi();\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/java/org/jclouds/softlayer/features/NetworkApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.features;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Iterables;\nimport org.jclouds.softlayer.domain.Network;\nimport org.jclouds.softlayer.domain.Subnet;\nimport org.jclouds.softlayer.domain.Datacenter;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport java.util.List;\nimport java.util.ArrayList;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.Assert.assertNull;\n\n/**\n * Tests behavior of {@code NetworkApi}\n */\n@Test(groups = \"live\")\npublic class NetworkApiLiveTest extends BaseSoftLayerApiLiveTest {\n\n   private NetworkApi networkApi;\n\n   private Network network = null;\n   private Subnet subnet = null;\n\n   private Datacenter datacenter = null;\n\n   @BeforeClass(groups = {\"integration\", \"live\"})\n   @Override\n   public void setup() {\n      super.setup();\n\n      networkApi = api.getNetworkApi();\n\n      datacenter = Iterables.get(api.getDatacenterApi().listDatacenters(), 0);\n      assertNotNull(datacenter, \"Datacenter must not be null\");\n   }\n\n   @Test\n   public void testCreateNetwork() throws Exception {\n      Network.CreateNetwork createNetwork = Network.CreateNetwork.builder()\n              .networkIdentifier(\"192.168.253.0\")\n              .name(\"NetworkApiLiveTestNetwork\")\n              .cidr(24)\n              .notes(\"this is a test network from jclouds NetworkApiLiveTest.\")\n              .build();\n\n      network = networkApi.createNetwork(ImmutableList.of(createNetwork));\n\n      checkNetwork(network);\n   }\n\n   @Test(dependsOnMethods = \"testCreateNetwork\")\n   public void testListNetworks() throws Exception {\n      List<Network> response = networkApi.listNetworks();\n      assertNotNull(response, \"listNetworks returns null\");\n\n      boolean found = false;\n\n      for (Network n : response) {\n         Network newDetails = networkApi.getNetwork(n.id());\n         assertEquals(n.id(), newDetails.id());\n         checkNetwork(newDetails);\n         if (n.id() == network.id()) {\n            found = true;\n            assertEquals(n.cidr(), network.cidr());\n            assertEquals(n.networkIdentifier(), network.networkIdentifier());\n            assertEquals(n.name(), n.name());\n         }\n      }\n\n      assertTrue(found, \"List Networks didn't return created network.\");\n   }\n\n   @Test(dependsOnMethods = \"testCreateNetwork\")\n   public void testGetNetwork() throws Exception {\n      Network found = networkApi.getNetwork(network.id());\n      assertEquals(found, network);\n      checkNetwork(found);\n      assertEquals(found.networkIdentifier(), \"192.168.253.0\");\n      assertEquals(found.name(), \"NetworkApiLiveTestNetwork\");\n      assertEquals(found.cidr(), 24);\n      assertEquals(found.notes(), \"this is a test network from jclouds NetworkApiLiveTest.\");\n   }\n\n   @Test(dependsOnMethods = \"testCreateNetwork\")\n   public void testGetName() throws Exception {\n      String name = networkApi.getName(network.id());\n\n      assertEquals(name, \"NetworkApiLiveTestNetwork\");\n   }\n\n   @Test(dependsOnMethods = \"testCreateNetwork\")\n   public void testGetNotes() throws Exception {\n      String notes = networkApi.getNotes(network.id());\n\n      assertEquals(notes, \"this is a test network from jclouds NetworkApiLiveTest.\");\n   }\n\n   @Test(dependsOnMethods = \"testCreateNetwork\")\n   public void testCreateSubnet() throws Exception {\n      Subnet.CreateSubnet createSubnet = Subnet.CreateSubnet.builder()\n              .networkIdentifier(\"192.168.253.0\")\n              .cidr(28)\n              .note(\"This is a test subnet from NetworkApiLiveTest\")\n              .build();\n\n      Subnet.CreateDatacenterName createDatacenterName = Subnet.CreateDatacenterName.builder()\n              .name(\"dal10.pod01\")\n              .build();\n\n      List<Object> parameters = new ArrayList<Object>();\n      parameters.add(createSubnet);\n      parameters.add(createDatacenterName);\n\n      subnet = networkApi.createSubnet(network.id(), parameters);\n\n      network = networkApi.getNetwork(network.id());\n      assertEquals(network.subnets().size(), 1);\n   }\n\n   @Test(dependsOnMethods = \"testCreateSubnet\")\n   public void testGetSubnets() throws Exception {\n      List<Subnet> subnets = networkApi.getSubnets(network.id());\n\n      assertEquals(subnets.size(), 1);\n      assertEquals(subnets.get(0).id(), subnet.id());\n      assertEquals(subnets.get(0).cidr(), subnet.cidr());\n      assertEquals(subnets.get(0).networkIdentifier(), subnet.networkIdentifier());\n      assertEquals(subnets.get(0).note(), subnet.note());\n   }\n\n   @Test(dependsOnMethods = \"testGetSubnets\")\n   public void testDeleteSubnet() throws Exception {\n      Subnet.DeleteSubnet deleteSubnet = Subnet.DeleteSubnet.builder()\n              .id(subnet.id())\n              .build();\n\n\n      List<Subnet.DeleteSubnet> parameters = new ArrayList<Subnet.DeleteSubnet>();\n      parameters.add(deleteSubnet);\n\n      boolean deletion = networkApi.deleteSubnet(network.id(), parameters);\n\n      assertTrue(deletion, \"deletion of subnet failed\");\n\n      List<Subnet> subnets = networkApi.getSubnets(network.id());\n      assertEquals(subnets.size(), 0);\n\n      subnet = null;\n   }\n\n   @Test(dependsOnMethods = \"testGetNetwork\")\n   public void testEditNetwork() throws Exception {\n      Network.EditNetwork editNetwork = Network.EditNetwork.builder()\n              .name(\"newNetworkApiLiveTestNetwork\")\n              .notes(\"new notes\")\n              .id(network.id())\n              .build();\n\n      boolean edit = networkApi.editNetwork(network.id(), ImmutableList.of(editNetwork));\n      assertTrue(edit, \"edition failed\");\n\n      Network newFound = networkApi.getNetwork(network.id());\n      assertEquals(newFound.name(), \"newNetworkApiLiveTestNetwork\");\n      assertEquals(newFound.notes(), \"new notes\");\n\n      network = newFound;\n   }\n\n   @Test(dependsOnMethods = \"testDeleteSubnet\")\n   public void testDeleteNetwork() throws Exception {\n      boolean deletion = networkApi.deleteNetwork(network.id());\n\n      Network found = networkApi.getNetwork(network.id());\n      assertNull(found, \"deletion failed\");\n\n      network = null;\n   }\n\n   private void checkNetwork(Network n) {\n      assertNotNull(n.id());\n      assertNotNull(n.name());\n      assertNotNull(n.networkIdentifier());\n      assertNotNull(n.cidr());\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/java/org/jclouds/softlayer/features/NetworkApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.features;\n\nimport com.google.common.collect.ImmutableList;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\n\nimport org.jclouds.http.config.JavaUrlHttpCommandExecutorServiceModule;\nimport org.jclouds.softlayer.SoftLayerApi;\nimport org.jclouds.softlayer.config.SoftLayerParserModule;\nimport org.jclouds.softlayer.domain.Network;\nimport org.jclouds.softlayer.domain.Subnet;\nimport org.jclouds.softlayer.internal.BaseSoftLayerMockTest;\nimport org.testng.annotations.Test;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport static com.google.common.collect.Iterables.size;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.Assert.assertFalse;\n/**\n * Mock tests for the {@link NetworkApi} class.\n */\n@Test(groups = \"unit\", testName = \"SecurityGroupApiMockTest\")\npublic class NetworkApiMockTest extends BaseSoftLayerMockTest {\n\n   public void testListNetworks() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(payloadFromResource(\"/network_list.json\")));\n      NetworkApi api = getNetworkApi(server);\n\n      Iterable<Network> networks = api.listNetworks();\n\n      try {\n         assertEquals(size(networks), 5);\n         assertEquals(server.getRequestCount(), 1);\n\n         assertSent(server, \"GET\", \"/SoftLayer_Network/getAllObjects?objectMask=mask.subnets\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testEmptyListNetworks() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(404));\n      NetworkApi api = getNetworkApi(server);\n\n      try {\n         assertTrue(api.listNetworks().isEmpty());\n         assertSent(server, \"GET\", \"/SoftLayer_Network/getAllObjects?objectMask=mask.subnets\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testCreateNetwork() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(payloadFromResource(\"/network_createObject.json\")));\n      NetworkApi api = getNetworkApi(server);\n\n      Network.CreateNetwork createNetwork = Network.CreateNetwork.builder()\n              .networkIdentifier(\"192.168.0.0\")\n              .name(\"testNet\")\n              .cidr(16)\n              .notes(\"testNotes\")\n              .build();\n\n      Network network = api.createNetwork(ImmutableList.of(createNetwork));\n\n      try {\n         assertEquals(server.getRequestCount(), 1);\n         assertSent(server, \"POST\", \"/SoftLayer_Network/createObject\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGetNetwork() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(payloadFromResource(\"/network_get_153001.json\")));\n      NetworkApi api = getNetworkApi(server);\n\n      Network network = api.getNetwork(153001);\n\n      try {\n         assertEquals(server.getRequestCount(), 1);\n         assertSent(server, \"GET\", \"/SoftLayer_Network/153001/getObject?objectMask=mask.subnets\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGetNullNetwork() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(404));\n      NetworkApi api = getNetworkApi(server);\n\n      try {\n         assertNull(api.getNetwork(153001));\n         assertSent(server, \"GET\", \"/SoftLayer_Network/153001/getObject?objectMask=mask.subnets\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGetName() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(\"testNet\"));\n      NetworkApi api = getNetworkApi(server);\n\n      String name = api.getName(153001);\n\n      try {\n         assertEquals(server.getRequestCount(), 1);\n         assertSent(server, \"GET\", \"/SoftLayer_Network/153001/getName\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGetNullName() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(404));\n      NetworkApi api = getNetworkApi(server);\n\n      try {\n         assertNull(api.getName(153001));\n         assertSent(server, \"GET\", \"/SoftLayer_Network/153001/getName\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGetNotes() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(\"testNotes\"));\n      NetworkApi api = getNetworkApi(server);\n\n      String notes = api.getNotes(153001);\n\n      try {\n         assertEquals(server.getRequestCount(), 1);\n         assertSent(server, \"GET\", \"/SoftLayer_Network/153001/getNotes\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGetNullNotes() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(404));\n      NetworkApi api = getNetworkApi(server);\n\n      try {\n         assertNull(api.getNotes(153001));\n         assertSent(server, \"GET\", \"/SoftLayer_Network/153001/getNotes\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testCreateSubnet() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(payloadFromResource(\"/network_createSubnet.json\")));\n      NetworkApi api = getNetworkApi(server);\n\n      Subnet.CreateSubnet createSubnet = Subnet.CreateSubnet.builder()\n              .networkIdentifier(\"192.168.1.0\")\n              .cidr(24)\n              .note(\"testNet test create subnet\")\n              .build();\n\n      Subnet.CreateDatacenterName createDatacenterName = Subnet.CreateDatacenterName.builder()\n              .name(\"dal10.pod01\")\n              .build();\n\n      List<Object> parameters = new ArrayList<Object>();\n      parameters.add(createSubnet);\n      parameters.add(createDatacenterName);\n\n      Subnet subnet = api.createSubnet(153001, parameters);\n\n      try {\n         assertEquals(server.getRequestCount(), 1);\n         assertSent(server, \"POST\", \"/SoftLayer_Network/153001/createSubnet\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testCreateSubnetOnNonExistingNetwork() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(404));\n      NetworkApi api = getNetworkApi(server);\n\n      Subnet.CreateSubnet createSubnet = Subnet.CreateSubnet.builder()\n              .networkIdentifier(\"192.168.1.0\")\n              .cidr(24)\n              .note(\"testNet test create subnet\")\n              .build();\n\n      Subnet.CreateDatacenterName createDatacenterName = Subnet.CreateDatacenterName.builder()\n              .name(\"dal10.pod01\")\n              .build();\n\n      List<Object> parameters = new ArrayList<Object>();\n      parameters.add(createSubnet);\n      parameters.add(createDatacenterName);\n\n      Subnet subnet = api.createSubnet(153001, parameters);\n\n      try {\n         assertNull(subnet);\n         assertSent(server, \"POST\", \"/SoftLayer_Network/153001/createSubnet\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGetSubnets() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(payloadFromResource(\"/network_subnet_get_1592631.json\")));\n      NetworkApi api = getNetworkApi(server);\n\n      List<Subnet> subnets = api.getSubnets(153001);\n\n      try {\n         assertEquals(server.getRequestCount(), 1);\n         assertSent(server, \"GET\", \"/SoftLayer_Network/153001/getSubnets\");\n         assertEquals(subnets.size(), 1);\n         assertEquals(subnets.get(0).id(), 1592631);\n         assertEquals(subnets.get(0).cidr(), 28);\n         assertEquals(subnets.get(0).networkIdentifier(), \"192.168.253.0\");\n         assertEquals(subnets.get(0).note(), \"This is a test subnet from NetworkApiMockTest\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGetSubnetsOnNonExistingNetwork() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(404));\n      NetworkApi api = getNetworkApi(server);\n\n      try {\n         assertTrue(api.getSubnets(153001).isEmpty());\n         assertSent(server, \"GET\", \"/SoftLayer_Network/153001/getSubnets\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testDeleteSubnet() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(\"true\"));\n      NetworkApi api = getNetworkApi(server);\n\n      Subnet.DeleteSubnet deleteSubnet = Subnet.DeleteSubnet.builder()\n              .id(1592631)\n              .build();\n\n      List<Subnet.DeleteSubnet> parameters = new ArrayList<Subnet.DeleteSubnet>();\n      parameters.add(deleteSubnet);\n      boolean deletion = api.deleteSubnet(153001, parameters);\n\n      try {\n         assertTrue(deletion, \"deletion failed\");\n\n         assertEquals(server.getRequestCount(), 1);\n         assertSent(server, \"POST\", \"/SoftLayer_Network/153001/deleteSubnet\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testDeleteNonExistingSubnet() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(404));\n      NetworkApi api = getNetworkApi(server);\n\n      Subnet.DeleteSubnet deleteSubnet = Subnet.DeleteSubnet.builder()\n              .id(1592631)\n              .build();\n\n      List<Subnet.DeleteSubnet> parameters = new ArrayList<Subnet.DeleteSubnet>();\n      parameters.add(deleteSubnet);\n      boolean deletion = api.deleteSubnet(153001, parameters);\n\n      try {\n         assertFalse(deletion);\n         assertSent(server, \"POST\", \"/SoftLayer_Network/153001/deleteSubnet\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testEditNetwork() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(\"true\"));\n      NetworkApi api = getNetworkApi(server);\n\n      Network.EditNetwork editNetwork = Network.EditNetwork.builder()\n              .name(\"newNetworkApiLiveTestNetwork\")\n              .notes(\"new notes\")\n              .id(153001)\n              .build();\n\n      boolean edit = api.editNetwork(153001, ImmutableList.of(editNetwork));\n\n      try {\n         assertEquals(server.getRequestCount(), 1);\n         assertSent(server, \"PUT\", \"/SoftLayer_Network/153001/editObject\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testEditNullNetwork() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(404));\n      NetworkApi api = getNetworkApi(server);\n\n      Network.EditNetwork editNetwork = Network.EditNetwork.builder()\n              .name(\"newNetworkApiLiveTestNetwork\")\n              .notes(\"new notes\")\n              .id(153001)\n              .build();\n\n      boolean edit = api.editNetwork(153001, ImmutableList.of(editNetwork));\n\n      try {\n         assertFalse(edit);\n         assertSent(server, \"PUT\", \"/SoftLayer_Network/153001/editObject\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testDeleteNetwork() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(\"true\"));\n      NetworkApi api = getNetworkApi(server);\n\n      boolean deletion = api.deleteNetwork(153001);\n\n      try {\n         assertEquals(server.getRequestCount(), 1);\n         assertSent(server, \"DELETE\", \"/SoftLayer_Network/153001\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testDeleteNonExistingNetwork() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(404));\n      NetworkApi api = getNetworkApi(server);\n\n      try {\n         assertFalse(api.deleteNetwork(153001));\n         assertSent(server, \"DELETE\", \"/SoftLayer_Network/153001\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   private NetworkApi getNetworkApi(MockWebServer server) {\n      return api(SoftLayerApi.class, server.url(\"/\").toString(), new\n              JavaUrlHttpCommandExecutorServiceModule(), new SoftLayerParserModule()).getNetworkApi();\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/java/org/jclouds/softlayer/features/SoftwareDescriptionApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.features;\n\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\nimport java.util.Set;\n\nimport org.jclouds.softlayer.domain.SoftwareDescription;\nimport org.testng.annotations.Test;\n\n/**\n * Tests behavior of {@code SoftwareDescriptionApi}\n */\n@Test(groups = \"live\")\npublic class SoftwareDescriptionApiLiveTest extends BaseSoftLayerApiLiveTest {\n\n   @Test\n   public void testGetAllObjects() {\n      Set<SoftwareDescription> response = api().getAllObjects();\n      assertNotNull(response);\n      assertTrue(response.size() > 0);\n   }\n\n   private SoftwareDescriptionApi api() {\n      return api.getSoftwareDescriptionApi();\n   }\n\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/java/org/jclouds/softlayer/features/SoftwareDescriptionApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.features;\n\nimport static org.testng.Assert.assertEquals;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\n\nimport org.jclouds.softlayer.SoftLayerApi;\nimport org.jclouds.softlayer.internal.BaseSoftLayerMockTest;\nimport org.jclouds.softlayer.parse.SoftwareDescriptionsParseTest;\nimport org.testng.annotations.Test;\n\n\n/**\n * Mock tests for the {@link org.jclouds.softlayer.features.SoftwareDescriptionApi} class.\n */\n@Test(groups = \"unit\", testName = \"SoftwareDescriptionApiMockTest\")\npublic class SoftwareDescriptionApiMockTest extends BaseSoftLayerMockTest {\n\n   public void testGetAllObjects() throws Exception {\n\n      MockWebServer server = mockWebServer(new MockResponse().setBody(payloadFromResource(\"/software_description_list.json\")));\n      SoftwareDescriptionApi api = api(SoftLayerApi.class, server.url(\"/\").toString()).getSoftwareDescriptionApi();\n\n      try {\n         assertEquals(api.getAllObjects(), new SoftwareDescriptionsParseTest().expected());\n         assertSent(server, \"GET\", \"/SoftLayer_Software_Description/getAllObjects?objectMask=id%3Bname%3Bversion%3BoperatingSystem%3BlongDescription%3BreferenceCode\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/java/org/jclouds/softlayer/features/VirtualGuestApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.features;\n\nimport static com.google.common.base.Preconditions.checkState;\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.jclouds.util.Predicates2.retry;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\nimport java.util.Properties;\nimport java.util.Set;\n\nimport org.jclouds.softlayer.SoftLayerApi;\nimport org.jclouds.softlayer.compute.strategy.SoftLayerComputeServiceAdapter.VirtualGuestHasLoginDetailsPresent;\nimport org.jclouds.softlayer.domain.ContainerVirtualGuestConfiguration;\nimport org.jclouds.softlayer.domain.Datacenter;\nimport org.jclouds.softlayer.domain.OperatingSystem;\nimport org.jclouds.softlayer.domain.TagReference;\nimport org.jclouds.softlayer.domain.VirtualGuest;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.base.Strings;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.inject.Injector;\nimport com.google.inject.Module;\n\n/**\n * Tests behavior of {@code VirtualGuestApi}\n */\n@Test(groups = \"live\")\npublic class VirtualGuestApiLiveTest extends BaseSoftLayerApiLiveTest {\n\n   private VirtualGuestApi virtualGuestApi;\n   private Predicate<VirtualGuest> loginDetailsTester;\n   private VirtualGuestHasLoginDetailsPresent virtualGuestHasLoginDetailsPresent;\n   private long guestLoginDelay = 60 * 60 * 1000;\n\n   private VirtualGuest virtualGuest = null;\n   private Datacenter datacenter = null;\n\n   @BeforeClass(groups = {\"integration\", \"live\"})\n   @Override\n   public void setup() {\n      super.setup();\n      virtualGuestApi = api.getVirtualGuestApi();\n      datacenter = Iterables.get(api.getDatacenterApi().listDatacenters(), 0);\n      assertNotNull(datacenter, \"Datacenter must not be null\");\n   }\n\n   @AfterClass(groups = {\"integration\", \"live\"})\n   protected void tearDownContext() {\n      if (virtualGuest != null) {\n         destroyMachine(virtualGuest);\n         virtualGuest = null;\n      }\n   }\n\n   @Override\n   protected SoftLayerApi create(Properties props, Iterable<Module> modules) {\n      Injector injector = newBuilder().modules(modules).overrides(props).buildInjector();\n      virtualGuestHasLoginDetailsPresent = injector.getInstance(VirtualGuestHasLoginDetailsPresent.class);\n      loginDetailsTester = retry(virtualGuestHasLoginDetailsPresent, guestLoginDelay);\n      return injector.getInstance(SoftLayerApi.class);\n   }\n\n   @Test\n   public void testGetCreateObjectOptions() {\n      ContainerVirtualGuestConfiguration configurationOption = api().getCreateObjectOptions();\n      assertNotNull(configurationOption);\n   }\n\n   @Test\n   public void testCreateVirtualGuest() throws Exception {\n      VirtualGuest virtualGuestRequest = VirtualGuest.builder()\n              .domain(\"jclouds.org\")\n              .hostname(\"virtualGuestApiLiveTest\")\n              .startCpus(1)\n              .maxMemory(1024)\n              .operatingSystem(OperatingSystem.builder().id(\"CENTOS_6_64\").operatingSystemReferenceCode(\"CENTOS_6_64\").build())\n              .datacenter(Datacenter.builder().name(datacenter.getName()).build())\n              .build();\n\n      virtualGuest = virtualGuestApi.createVirtualGuest(virtualGuestRequest);\n      boolean orderInSystem = loginDetailsTester.apply(virtualGuest);\n      checkState(orderInSystem, \"order for guest %s doesn't have login details within %sms\", virtualGuest,\n              Long.toString(guestLoginDelay));\n      virtualGuest = virtualGuestApi.getVirtualGuest(virtualGuest.getId());\n      checkVirtualGuest(virtualGuest);\n      assertNotNull(virtualGuest.getPrimaryIpAddress(), \"primaryIpAddress must be not null\");\n      assertNotNull(virtualGuest.getPrimaryBackendIpAddress(), \"backendIpAddress must be not null\");\n   }\n\n   @Test(dependsOnMethods = \"testCreateVirtualGuest\")\n   public void testGetVirtualGuest() throws Exception {\n      VirtualGuest found = virtualGuestApi.getVirtualGuest(virtualGuest.getId());\n      assertEquals(found, virtualGuest);\n      assertNull(found.getPrimaryBackendNetworkComponent(), \"backendNetworkComponent should be null\");\n   }\n\n   @Test(dependsOnMethods = \"testGetVirtualGuest\")\n   public void testGetVirtualGuestFiltered() throws Exception {\n      VirtualGuest found = virtualGuestApi.getVirtualGuestFiltered(virtualGuest.getId(), \"id;primaryBackendNetworkComponent;primaryBackendNetworkComponent.networkVlan\");\n      assertEquals(found.getId(), virtualGuest.getId());\n      assertNotNull(found.getPrimaryBackendNetworkComponent(), \"backendNetworkComponent must be returned\");\n      assertNotNull(found.getPrimaryBackendNetworkComponent().getNetworkVlan(), \"backendNetworkComponent networkVlan must be returned\");\n      assertTrue(found.getPrimaryBackendNetworkComponent().getNetworkVlan().getId() > 0, \"backendNetworkComponent must have a valid networkVlan ID\");\n   }\n\n   @Test(dependsOnMethods = \"testGetVirtualGuestFiltered\")\n   public void testSetTagsOnVirtualGuest() throws Exception {\n      ImmutableSet<String> tags = ImmutableSet.of(\"test\", \"jclouds\");\n      assertTrue(virtualGuestApi.setTags(virtualGuest.getId(), tags));\n      VirtualGuest found = virtualGuestApi.getVirtualGuest(virtualGuest.getId());\n      Set<TagReference> tagReferences = found.getTagReferences();\n      assertNotNull(tagReferences);\n\n      ImmutableSet.Builder<String> actualTagsBuilder = ImmutableSet.builder();\n      for (TagReference ref : tagReferences) {\n         actualTagsBuilder.add(ref.getTag().getName());\n      }\n      Set<String> actualTags = actualTagsBuilder.build();\n      assertThat(actualTags).containsAll(tags);\n   }\n\n   @Test(dependsOnMethods = \"testSetTagsOnVirtualGuest\")\n   public void testSetNotesOnVirtualGuest() throws Exception {\n      // Test with maximum allowed notes length - 1000 characters.\n      String notes = Strings.padStart(\"\", 1000, 'x');\n      assertTrue(virtualGuestApi.setNotes(virtualGuest.getId(), notes));\n      VirtualGuest found = virtualGuestApi.getNotes(virtualGuest.getId());\n      assertEquals(found.getNotes(), notes);\n   }\n\n   @Test(dependsOnMethods = \"testSetNotesOnVirtualGuest\")\n   public void testPauseVirtualGuest() throws Exception {\n      virtualGuestApi.pauseVirtualGuest(virtualGuest.getId());\n      checkState(retry(new Predicate<VirtualGuest>() {\n         public boolean apply(VirtualGuest guest) {\n            guest = api().getVirtualGuest(virtualGuest.getId());\n            return guest.getPowerState().getKeyName() == VirtualGuest.State.PAUSED;\n         }\n      }, 5 * 60 * 1000).apply(virtualGuest), \"%s still not paused!\", virtualGuest);\n      VirtualGuest found = virtualGuestApi.getVirtualGuest(virtualGuest.getId());\n      assertTrue(found.getPowerState().getKeyName() == VirtualGuest.State.PAUSED);\n   }\n\n   @Test(dependsOnMethods = \"testPauseVirtualGuest\")\n   public void testResumeVirtualGuest() throws Exception {\n      virtualGuestApi.resumeVirtualGuest(virtualGuest.getId());\n      checkState(retry(new Predicate<VirtualGuest>() {\n         public boolean apply(VirtualGuest guest) {\n            guest = api().getVirtualGuest(virtualGuest.getId());\n            return guest.getPowerState().getKeyName() == VirtualGuest.State.RUNNING;\n         }\n      }, 5 * 60 * 1000).apply(virtualGuest), \"%s still not running!\", virtualGuest);\n      VirtualGuest found = virtualGuestApi.getVirtualGuest(virtualGuest.getId());\n      assertTrue(found.getPowerState().getKeyName() == VirtualGuest.State.RUNNING);\n   }\n\n   private void destroyMachine(final VirtualGuest virtualGuest) {\n      checkState(retry(new Predicate<VirtualGuest>() {\n         public boolean apply(VirtualGuest guest) {\n            guest = api().getVirtualGuest(virtualGuest.getId());\n            return guest.getActiveTransactionCount() == 0;\n         }\n      }, 5 * 60 * 1000).apply(virtualGuest), \"%s still has active transactions!\", virtualGuest);\n      assertTrue(api().deleteVirtualGuest(virtualGuest.getId()));\n   }\n\n   private VirtualGuestApi api() {\n      return api.getVirtualGuestApi();\n   }\n\n   private void checkVirtualGuest(VirtualGuest vg) {\n      if (vg.getActiveTransactionCount() == 0) {\n         assertNotNull(vg.getDomain(), \"domain must be not null\");\n         assertNotNull(vg.getFullyQualifiedDomainName(), \"fullyQualifiedDomainName must be not null\");\n         assertNotNull(vg.getHostname(), \"hostname must be not null\");\n         assertTrue(vg.getId() > 0, \"id must be greater than 0\");\n         assertTrue(vg.getMaxCpu() > 0, \"maxCpu must be greater than 0\");\n         assertTrue(vg.getMaxMemory() > 0, \"maxMemory must be greater than 0\");\n         assertTrue(vg.getStatusId() > 0, \"statusId must be greater than 0\");\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/java/org/jclouds/softlayer/features/VirtualGuestApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\n\nimport org.jclouds.http.config.JavaUrlHttpCommandExecutorServiceModule;\nimport org.jclouds.softlayer.SoftLayerApi;\nimport org.jclouds.softlayer.config.SoftLayerParserModule;\nimport org.jclouds.softlayer.domain.Datacenter;\nimport org.jclouds.softlayer.domain.OperatingSystem;\nimport org.jclouds.softlayer.domain.VirtualGuest;\nimport org.jclouds.softlayer.internal.BaseSoftLayerMockTest;\nimport org.jclouds.softlayer.parse.GetCreateObjectOptionsParseTest;\nimport org.jclouds.softlayer.parse.VirtualGuestFilteredParseTest;\nimport org.jclouds.softlayer.parse.VirtualGuestParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Mock tests for the {@link org.jclouds.softlayer.features.VirtualGuestApi} class.\n */\n@Test(groups = \"unit\", testName = \"VirtualGuestApiMockTest\")\npublic class VirtualGuestApiMockTest extends BaseSoftLayerMockTest {\n\n    public void testGetVirtualGuest() throws Exception {\n       MockWebServer server = mockWebServer(new MockResponse().setBody(payloadFromResource(\"/virtual_guest_get.json\")));\n       VirtualGuestApi api = getVirtualGuestApi(server);\n\n       try {\n          assertEquals(api.getVirtualGuest(3001812), new VirtualGuestParseTest().expected());\n          assertSent(server, \"GET\", \"/SoftLayer_Virtual_Guest/3001812/getObject?objectMask=id%3Bhostname%3Bdomain%3BfullyQualifiedDomainName%3BpowerState%3BmaxCpu%3BmaxMemory%3BstatusId%3BoperatingSystem.passwords%3BprimaryBackendIpAddress%3BprimaryIpAddress%3BactiveTransactionCount%3BblockDevices.diskImage%3Bdatacenter%3BtagReferences%3BprivateNetworkOnlyFlag%3BsshKeys\");\n       } finally {\n          server.shutdown();\n       }\n    }\n\n    public void testGetVirtualGuestFiltered() throws Exception {\n       MockWebServer server = mockWebServer(new MockResponse().setBody(payloadFromResource(\"/virtual_guest_get_filtered.json\")));\n       VirtualGuestApi api = getVirtualGuestApi(server);\n\n       try {\n          assertEquals(api.getVirtualGuestFiltered(3001812, \"id;primaryBackendNetworkComponent;primaryBackendNetworkComponent.networkVlan\"), new VirtualGuestFilteredParseTest().expected());\n          assertSent(server, \"GET\", \"/SoftLayer_Virtual_Guest/3001812/getObject?objectMask=id%3BprimaryBackendNetworkComponent%3BprimaryBackendNetworkComponent.networkVlan\");\n       } finally {\n          server.shutdown();\n       }\n    }\n\n   public void testGetNullVirtualGuest() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(404));\n      VirtualGuestApi api = getVirtualGuestApi(server);\n      try {\n         assertNull(api.getVirtualGuest(3001812));\n         assertSent(server, \"GET\", \"/SoftLayer_Virtual_Guest/3001812/getObject?objectMask=id%3Bhostname%3Bdomain%3BfullyQualifiedDomainName%3BpowerState%3BmaxCpu%3BmaxMemory%3BstatusId%3BoperatingSystem.passwords%3BprimaryBackendIpAddress%3BprimaryIpAddress%3BactiveTransactionCount%3BblockDevices.diskImage%3Bdatacenter%3BtagReferences%3BprivateNetworkOnlyFlag%3BsshKeys\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testCreateVirtualGuest() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(payloadFromResource(\"/virtual_guest_get.json\")));\n      VirtualGuestApi api = getVirtualGuestApi(server);\n      VirtualGuest virtualGuest = createVirtualGuest();\n      try {\n         assertEquals(api.createVirtualGuest(virtualGuest), new VirtualGuestParseTest().expected());\n         assertSent(server, \"POST\", \"/SoftLayer_Virtual_Guest\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testDeleteVirtualGuest() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse());\n      VirtualGuestApi api = api(SoftLayerApi.class, server.url(\"/\").toString()).getVirtualGuestApi();\n      try {\n         assertTrue(api.deleteVirtualGuest(1301396));\n         assertSent(server, \"GET\", \"/SoftLayer_Virtual_Guest/1301396/deleteObject\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testDeleteNonExistingVirtualGuest() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(404));\n      VirtualGuestApi api = api(SoftLayerApi.class, server.url(\"/\").toString()).getVirtualGuestApi();\n      try {\n         assertFalse(api.deleteVirtualGuest(1301396));\n         assertSent(server, \"GET\", \"/SoftLayer_Virtual_Guest/1301396/deleteObject\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGetCreateObjectOptions() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(payloadFromResource(\"/container_virtual_guest_configuration.json\")));\n      VirtualGuestApi api = getVirtualGuestApi(server);\n      try {\n         assertEquals(api.getCreateObjectOptions(), new GetCreateObjectOptionsParseTest().expected());\n         assertSent(server, \"GET\", \"/SoftLayer_Virtual_Guest/getCreateObjectOptions\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGetNullCreateObjectOptions() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(404));\n      VirtualGuestApi api = api(SoftLayerApi.class, server.url(\"/\").toString()).getVirtualGuestApi();\n      try {\n         assertNull(api.getCreateObjectOptions());\n         assertSent(server, \"GET\", \"/SoftLayer_Virtual_Guest/getCreateObjectOptions\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testRebootHardVirtualGuest() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(payloadFromResource(\"/datacenter_get.json\")));\n      VirtualGuestApi api = api(SoftLayerApi.class, server.url(\"/\").toString()).getVirtualGuestApi();\n      try {\n         api.rebootHardVirtualGuest(1301396);\n         assertSent(server, \"GET\", \"/SoftLayer_Virtual_Guest/1301396/rebootHard.json\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testRebootNonExistingVirtualGuest() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(404));\n      VirtualGuestApi api = api(SoftLayerApi.class, server.url(\"/\").toString()).getVirtualGuestApi();\n      try {\n         api.rebootHardVirtualGuest(1301396);\n         assertSent(server, \"GET\", \"/SoftLayer_Virtual_Guest/1301396/rebootHard.json\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testPauseVirtualGuest() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(payloadFromResource(\"/datacenter_get.json\")));\n      VirtualGuestApi api = api(SoftLayerApi.class, server.url(\"/\").toString()).getVirtualGuestApi();\n      try {\n         api.pauseVirtualGuest(1301396);\n         assertSent(server, \"GET\", \"/SoftLayer_Virtual_Guest/1301396/pause.json\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testPauseNonExistingVirtualGuest() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(404));\n      VirtualGuestApi api = api(SoftLayerApi.class, server.url(\"/\").toString()).getVirtualGuestApi();\n      try {\n         api.pauseVirtualGuest(1301396);\n         assertSent(server, \"GET\", \"/SoftLayer_Virtual_Guest/1301396/pause.json\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testResumeVirtualGuest() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(payloadFromResource(\"/datacenter_get.json\")));\n      VirtualGuestApi api = api(SoftLayerApi.class, server.url(\"/\").toString()).getVirtualGuestApi();\n      try {\n         api.resumeVirtualGuest(1301396);\n         assertSent(server, \"GET\", \"/SoftLayer_Virtual_Guest/1301396/resume.json\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testResumeNonExistingVirtualGuest() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(404));\n      VirtualGuestApi api = api(SoftLayerApi.class, server.url(\"/\").toString()).getVirtualGuestApi();\n      try {\n         api.resumeVirtualGuest(1301396);\n         assertSent(server, \"GET\", \"/SoftLayer_Virtual_Guest/1301396/resume.json\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testSetTagsOnVirtualGuest() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(payloadFromResource(\"/virtual_guest_set_tags_response.json\")));\n      VirtualGuestApi api = api(SoftLayerApi.class, server.url(\"/\").toString()).getVirtualGuestApi();\n      VirtualGuest virtualGuest = createVirtualGuest();\n      try {\n         assertTrue(api.setTags(virtualGuest.getId(), ImmutableSet.of(\"test1\", \"test2\", \"test3\")));\n         assertSent(server, \"POST\", \"/SoftLayer_Virtual_Guest/1301396/setTags\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testSetTagsOnNonExistingVirtualGuest() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(404));\n      VirtualGuestApi api = api(SoftLayerApi.class, server.url(\"/\").toString()).getVirtualGuestApi();\n      VirtualGuest virtualGuest = createVirtualGuest();\n      try {\n         assertFalse(api.setTags(virtualGuest.getId(), ImmutableSet.of(\"test1\", \"test2\", \"test3\")));\n         assertSent(server, \"POST\", \"/SoftLayer_Virtual_Guest/1301396/setTags\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   private VirtualGuest createVirtualGuest() {\n      return VirtualGuest.builder()\n              .domain(\"example.com\")\n              .hostname(\"host1\")\n              .id(1301396)\n              .maxMemory(1024)\n              .startCpus(1)\n              .localDiskFlag(true)\n              .operatingSystem(OperatingSystem.builder().id(\"UBUNTU_LATEST\")\n                      .operatingSystemReferenceCode(\"UBUNTU_LATEST\")\n                      .build())\n              .datacenter(Datacenter.builder().name(\"test\").build())\n              .build();\n   }\n\n   private VirtualGuestApi getVirtualGuestApi(MockWebServer server) {\n      return api(SoftLayerApi.class, server.url(\"/\").toString(), new\n              JavaUrlHttpCommandExecutorServiceModule(), new SoftLayerParserModule()).getVirtualGuestApi();\n   }\n\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/java/org/jclouds/softlayer/features/VirtualGuestBlockDeviceTemplateGroupApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.features;\n\nimport static com.google.common.collect.Iterables.get;\nimport static org.testng.Assert.assertNotNull;\nimport java.util.Set;\n\nimport org.jclouds.softlayer.domain.VirtualGuestBlockDeviceTemplateGroup;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.beust.jcommander.internal.Sets;\n\n/**\n * Tests behavior of {@code VirtualGuestBlockDeviceTemplateGroupApi} which depends on the account\n */\n@Test(groups = \"live\")\npublic class VirtualGuestBlockDeviceTemplateGroupApiLiveTest extends BaseSoftLayerApiLiveTest {\n\n   Set<VirtualGuestBlockDeviceTemplateGroup> publicImages = Sets.newHashSet();\n\n   @BeforeClass\n   void init() {\n      publicImages = api().getPublicImages();\n   }\n\n   @Test\n   public void testGetBlockDeviceTemplateGroups() {\n      for (VirtualGuestBlockDeviceTemplateGroup publicImage : publicImages) {\n         assertNotNull(publicImage);\n      }\n   }\n\n   @Test(dependsOnMethods = \"testGetBlockDeviceTemplateGroups\")\n   public void testGetObject() {\n      if (!publicImages.isEmpty()) {\n         VirtualGuestBlockDeviceTemplateGroup virtualGuestBlockDeviceTemplateGroup = api().getObject(get(publicImages, 0).getGlobalIdentifier());\n         assertNotNull(virtualGuestBlockDeviceTemplateGroup);\n      }\n   }\n\n   private VirtualGuestBlockDeviceTemplateGroupApi api() {\n      return api.getVirtualGuestBlockDeviceTemplateGroupApi();\n   }\n\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/java/org/jclouds/softlayer/features/VirtualGuestBlockDeviceTemplateGroupApiMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport okhttp3.mockwebserver.MockResponse;\nimport okhttp3.mockwebserver.MockWebServer;\n\nimport org.jclouds.softlayer.SoftLayerApi;\nimport org.jclouds.softlayer.internal.BaseSoftLayerMockTest;\nimport org.jclouds.softlayer.parse.PublicImagesParseTest;\nimport org.jclouds.softlayer.parse.VirtualGuestBlockDeviceTemplateGroupParseTest;\nimport org.testng.annotations.Test;\n\n\n/**\n * Mock tests for the {@link VirtualGuestBlockDeviceTemplateGroupApi} class.\n */\n@Test(groups = \"unit\", testName = \"VirtualGuestBlockDeviceTemplateGroupApiMockTest\")\npublic class VirtualGuestBlockDeviceTemplateGroupApiMockTest extends BaseSoftLayerMockTest {\n\n   public void testListPublicImages() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(payloadFromResource(\"/virtual_guest_block_device_template_group_get_public_images.json\")));\n      VirtualGuestBlockDeviceTemplateGroupApi api = getVirtualGuestBlockDeviceTemplateGroupApi(server);\n      try {\n         assertEquals(api.getPublicImages(), new PublicImagesParseTest().expected());\n         assertSent(server, \"GET\", \"/SoftLayer_Virtual_Guest_Block_Device_Template_Group/getPublicImages?objectMask=children.blockDevices.diskImage.softwareReferences.softwareDescription\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testEmptyListImages() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(404));\n      VirtualGuestBlockDeviceTemplateGroupApi api = getVirtualGuestBlockDeviceTemplateGroupApi(server);\n      try {\n         assertTrue(api.getPublicImages().isEmpty());\n         assertSent(server, \"GET\", \"/SoftLayer_Virtual_Guest_Block_Device_Template_Group/getPublicImages?objectMask=children.blockDevices.diskImage.softwareReferences.softwareDescription\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGetObject() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setBody(payloadFromResource(\"/virtual_guest_block_device_template_group_get.json\")));\n      VirtualGuestBlockDeviceTemplateGroupApi api = getVirtualGuestBlockDeviceTemplateGroupApi(server);\n      try {\n         assertEquals(api.getObject(\"3001812\"), new VirtualGuestBlockDeviceTemplateGroupParseTest().expected());\n         assertSent(server, \"GET\", \"/SoftLayer_Virtual_Guest_Block_Device_Template_Group/3001812/getObject?objectMask=children.blockDevices.diskImage.softwareReferences.softwareDescription\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   public void testGetNullObject() throws Exception {\n      MockWebServer server = mockWebServer(new MockResponse().setResponseCode(404));\n      VirtualGuestBlockDeviceTemplateGroupApi api = getVirtualGuestBlockDeviceTemplateGroupApi(server);\n      try {\n         assertNull(api.getObject(\"3001812\"));\n         assertSent(server, \"GET\", \"/SoftLayer_Virtual_Guest_Block_Device_Template_Group/3001812/getObject?objectMask=children.blockDevices.diskImage.softwareReferences.softwareDescription\");\n      } finally {\n         server.shutdown();\n      }\n   }\n\n   private VirtualGuestBlockDeviceTemplateGroupApi getVirtualGuestBlockDeviceTemplateGroupApi(MockWebServer server) {\n      return api(SoftLayerApi.class, server.url(\"/\").toString()).getVirtualGuestBlockDeviceTemplateGroupApi();\n   }\n\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/java/org/jclouds/softlayer/handlers/SoftLayerErrorHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.handlers;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.reportMatcher;\nimport static org.easymock.EasyMock.verify;\n\nimport java.net.URI;\n\nimport org.easymock.IArgumentMatcher;\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rest.AuthorizationException;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Guice;\n\n@Test(groups = { \"unit\" })\npublic class SoftLayerErrorHandlerTest {\n\n   @Test\n   public void test500MakesResourceNotFoundExceptionOnUnableToDeterminePackage() {\n      assertCodeMakes(\n            \"GET\",\n            URI.create(\"https://api.softlayer.com/foo\"),\n            500,\n            \"\",\n            \"{\\\"error\\\":\\\"Unable to determine package for 'node2102835255.me.org'.\\\"}\",\n            ResourceNotFoundException.class);\n   }\n   \n   @Test\n   public void test500MakesIllegalStateExceptionOnActiveTransaction() {\n      assertCodeMakes(\n            \"GET\",\n            URI.create(\"https://api.softlayer.com/rest/v3/SoftLayer_Billing_Item/8676376/cancelService.json\"),\n            500,\n            \"\",\n            \"{\\\"error\\\":\\\"There is currently an active transaction.\\\"}\",\n            IllegalStateException.class);\n   }\n\n   @Test\n   public void test401MakesAuthorizationException() {\n      assertCodeMakes(\"GET\", URI.create(\"https://api.softlayer.com/foo\"), 401, \"\", \"Unauthorized\",\n            AuthorizationException.class);\n   }\n\n   @Test\n   public void test404MakesResourceNotFoundException() {\n      assertCodeMakes(\"GET\", URI.create(\"https://api.softlayer.com/foo\"), 404, \"\", \"Not Found\",\n            ResourceNotFoundException.class);\n   }\n\n   private void assertCodeMakes(String method, URI uri, int statusCode, String message, String content,\n         Class<? extends Exception> expected) {\n      assertCodeMakes(method, uri, statusCode, message, \"text/xml\", content, expected);\n   }\n\n   private void assertCodeMakes(String method, URI uri, int statusCode, String message, String contentType,\n         String content, Class<? extends Exception> expected) {\n\n      SoftLayerErrorHandler function = Guice.createInjector().getInstance(SoftLayerErrorHandler.class);\n\n      HttpCommand command = createMock(HttpCommand.class);\n      HttpRequest request = HttpRequest.builder().method(method).endpoint(uri).build();\n      HttpResponse response = HttpResponse.builder().statusCode(statusCode).message(message).payload(content).build();\n      response.getPayload().getContentMetadata().setContentType(contentType);\n\n      expect(command.getCurrentRequest()).andReturn(request).atLeastOnce();\n      command.setException(classEq(expected));\n\n      replay(command);\n\n      function.handleError(command, response);\n\n      verify(command);\n   }\n\n   public static Exception classEq(final Class<? extends Exception> in) {\n      reportMatcher(new IArgumentMatcher() {\n\n         @Override\n         public void appendTo(StringBuffer buffer) {\n            buffer.append(\"classEq(\");\n            buffer.append(in);\n            buffer.append(\")\");\n         }\n\n         @Override\n         public boolean matches(Object arg) {\n            return arg.getClass() == in;\n         }\n\n      });\n      return null;\n   }\n\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/java/org/jclouds/softlayer/internal/BaseSoftLayerMockTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.internal;\n\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.jclouds.Constants.PROPERTY_CREDENTIAL;\nimport static org.jclouds.Constants.PROPERTY_IDENTITY;\nimport static org.jclouds.Constants.PROPERTY_API_VERSION;\nimport static org.jclouds.util.Strings2.toStringAndClose;\nimport java.io.IOException;\nimport java.util.Properties;\n\nimport jakarta.ws.rs.core.HttpHeaders;\nimport jakarta.ws.rs.core.MediaType;\n\nimport okhttp3.mockwebserver.MockWebServer;\nimport okhttp3.mockwebserver.RecordedRequest;\n\nimport org.jclouds.http.BaseMockWebServerTest;\nimport org.jclouds.http.config.JavaUrlHttpCommandExecutorServiceModule;\nimport org.jclouds.softlayer.SoftLayerApiMetadata;\n\nimport com.google.common.base.Throwables;\nimport com.google.inject.Module;\n\n\n/**\n * Base class for all SoftLayer mock tests.\n */\npublic class BaseSoftLayerMockTest extends BaseMockWebServerTest {\n\n   @Override\n   protected void addOverrideProperties(Properties properties) {\n      properties.setProperty(PROPERTY_IDENTITY, \"uuid\");\n      properties.setProperty(PROPERTY_CREDENTIAL, \"apikey\");\n      properties.setProperty(PROPERTY_API_VERSION, \"3\");\n   }\n\n   @Override\n   protected Module createConnectionModule() {\n      return new JavaUrlHttpCommandExecutorServiceModule();\n   }\n\n   public String payloadFromResource(String resource) {\n      try {\n         return toStringAndClose(getClass().getResourceAsStream(resource));\n      } catch (IOException e) {\n         throw Throwables.propagate(e);\n      }\n   }\n\n   protected RecordedRequest assertSent(MockWebServer server, String method, String path) throws InterruptedException {\n      RecordedRequest request = server.takeRequest();\n      assertThat(request.getMethod()).isEqualTo(method);\n      assertThat(request.getPath()).isEqualTo(\"/v\" + new SoftLayerApiMetadata().getVersion() + path);\n      assertThat(request.getHeader(HttpHeaders.ACCEPT)).isEqualTo(MediaType.APPLICATION_JSON);\n      return request;\n   }\n\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/java/org/jclouds/softlayer/internal/BaseSoftLayerParseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.internal;\n\nimport org.jclouds.json.BaseItemParserTest;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.softlayer.config.SoftLayerParserModule;\n\nimport com.google.inject.Guice;\nimport com.google.inject.Injector;\n\npublic abstract class BaseSoftLayerParseTest<T> extends BaseItemParserTest<T> {\n\n   @Override\n   protected Injector injector() {\n      return Guice.createInjector(new GsonModule(), new SoftLayerParserModule());\n   }\n\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/java/org/jclouds/softlayer/parse/CreateVirtualGuestResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.parse;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.softlayer.domain.VirtualGuest;\nimport org.jclouds.softlayer.internal.BaseSoftLayerParseTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class CreateVirtualGuestResponseTest extends BaseSoftLayerParseTest<VirtualGuest> {\n\n   @Override\n   public String resource() {\n      return \"/virtual_guest_create_response.json\";\n   }\n\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   public VirtualGuest expected() {\n      return VirtualGuest.builder()\n              .accountId(232298)\n              .createDate(new SimpleDateFormatDateService().iso8601DateParse(\"2012-11-30T22:28:17.000Z\"))\n              .dedicatedAccountHostOnly(false)\n              .domain(\"example.com\")\n              .hostname(\"host1\")\n              .id(1301396)\n              .maxCpu(1)\n              .maxCpuUnits(\"CORE\")\n              .maxMemory(1024)\n              .privateNetworkOnlyFlag(false)\n              .startCpus(1)\n              .statusId(1001)\n              .billingItemId(0)\n              .operatingSystem(null)\n              .datacenter(null)\n              .build();\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/java/org/jclouds/softlayer/parse/DatacenterParseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.parse;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.softlayer.domain.Address;\nimport org.jclouds.softlayer.domain.Datacenter;\nimport org.jclouds.softlayer.domain.Region;\nimport org.jclouds.softlayer.internal.BaseSoftLayerParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\")\npublic class DatacenterParseTest extends BaseSoftLayerParseTest<Datacenter> {\n\n   @Override\n   public String resource() {\n      return \"/datacenter_get.json\";\n   }\n\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Datacenter expected() {\n      return Datacenter.builder()\n              .id(265592)\n              .longName(\"Amsterdam 1\")\n              .name(\"ams01\")\n              .locationAddress(Address.builder()\n                      .address(\"Paul van Vlissingenstraat 16\")\n                      .accountId(1)\n                      .city(\"Amsterdam\")\n                      .contactName(\"SoftLayer\")\n                      .country(\"NL\")\n                      .description(\"Amsterdam - AMS01\")\n                      .id(3322)\n                      .isActive(1)\n                      .locationId(265592)\n                      .postalCode(\"1096 BK\")\n                      .build())\n              .regions(ImmutableSet.of(Region.builder().keyname(\"AMSTERDAM\")\n                              .description(\"AMS01 - Amsterdam - Western Europe\")\n                              .build()))\n              .build();\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/java/org/jclouds/softlayer/parse/DatacentersParseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.parse;\n\nimport java.util.Set;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.softlayer.domain.Datacenter;\nimport org.jclouds.softlayer.internal.BaseSoftLayerParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\")\npublic class DatacentersParseTest extends BaseSoftLayerParseTest<Set<Datacenter>> {\n\n   @Override\n   public String resource() {\n      return \"/datacenter_list.json\";\n   }\n\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Set<Datacenter> expected() {\n      return ImmutableSet.of(\n              Datacenter.builder()\n                      .id(265592)\n                      .longName(\"Amsterdam 1\")\n                      .name(\"ams01\")\n                      .build(),\n              Datacenter.builder()\n                      .id(3)\n                      .longName(\"Dallas 1\")\n                      .name(\"dal01\")\n                      .build(),\n              Datacenter.builder()\n                      .id(154770)\n                      .longName(\"Dallas 2\")\n                      .name(\"dal02\")\n                      .build(),\n              Datacenter.builder()\n                      .id(167092)\n                      .longName(\"Dallas 4\")\n                      .name(\"dal04\")\n                      .build(),\n              Datacenter.builder()\n                      .id(138124)\n                      .longName(\"Dallas 5\")\n                      .name(\"dal05\")\n                      .build(),\n              Datacenter.builder()\n                      .id(154820)\n                      .longName(\"Dallas 6\")\n                      .name(\"dal06\")\n                      .build(),\n              Datacenter.builder()\n                      .id(142776)\n                      .longName(\"Dallas 7\")\n                      .name(\"dal07\")\n                      .build(),\n              Datacenter.builder()\n                      .id(352392)\n                      .longName(\"Dallas 8\")\n                      .name(\"dal08\")\n                      .build(),\n              Datacenter.builder()\n                      .id(352494)\n                      .longName(\"Hong Kong 2\")\n                      .name(\"hkg02\")\n                      .build(),\n              Datacenter.builder()\n                      .id(142775)\n                      .longName(\"Houston 2\")\n                      .name(\"hou02\")\n                      .build(),\n              Datacenter.builder()\n                      .id(168642)\n                      .longName(\"San Jose 1\")\n                      .name(\"sjc01\")\n                      .build(),\n              Datacenter.builder()\n                      .id(18171)\n                      .longName(\"Seattle\")\n                      .name(\"sea01\")\n                      .build(),\n              Datacenter.builder()\n                      .id(224092)\n                      .longName(\"Singapore 1\")\n                      .name(\"sng01\")\n                      .build(),\n              Datacenter.builder()\n                      .id(37473)\n                      .longName(\"Washington, DC\")\n                      .name(\"wdc01\")\n                      .build()\n              );\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/java/org/jclouds/softlayer/parse/GetCreateObjectOptionsParseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.parse;\n\nimport org.jclouds.softlayer.domain.ContainerVirtualGuestConfiguration;\nimport org.jclouds.softlayer.domain.ContainerVirtualGuestConfigurationOption;\nimport org.jclouds.softlayer.domain.Datacenter;\nimport org.jclouds.softlayer.domain.ProductItem;\nimport org.jclouds.softlayer.domain.ProductItemPrice;\nimport org.jclouds.softlayer.domain.VirtualDiskImage;\nimport org.jclouds.softlayer.domain.VirtualGuest;\nimport org.jclouds.softlayer.domain.VirtualGuestBlockDevice;\nimport org.jclouds.softlayer.domain.VirtualGuestNetworkComponent;\nimport org.jclouds.softlayer.internal.BaseSoftLayerParseTest;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\npublic class GetCreateObjectOptionsParseTest extends BaseSoftLayerParseTest<ContainerVirtualGuestConfiguration> {\n\n   @Override\n   public String resource() {\n      return \"/container_virtual_guest_configuration.json\";\n   }\n\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   public ContainerVirtualGuestConfiguration expected() {\n      return ContainerVirtualGuestConfiguration.builder()\n              .blockDevices(ContainerVirtualGuestConfigurationOption.builder()\n                      .productItemPrice(ProductItemPrice.builder()\n                              .hourlyRecurringFee(0)\n                              .recurringFee(\"0\")\n                              .item(ProductItem.builder().description(\"25 GB (SAN)\").build())\n                              .build())\n                      .template(VirtualGuest.builder()\n                              .blockDevices(VirtualGuestBlockDevice.builder()\n                                      .device(\"0\")\n                                      .diskImage(VirtualDiskImage.builder().capacity(25).build())\n                                      .build())\n                              .localDiskFlag(false)\n                              .build())\n                      .build())\n              .datacenters(ContainerVirtualGuestConfigurationOption.builder()\n                      .template(VirtualGuest.builder().datacenter(Datacenter.builder().name(\"ams01\").build()).build())\n                      .build())\n              .memory(ContainerVirtualGuestConfigurationOption.builder()\n                      .productItemPrice(ProductItemPrice.builder()\n                              .hourlyRecurringFee(.02f)\n                              .recurringFee(\"14\")\n                              .item(ProductItem.builder().description(\"1 GB\").build())\n                              .build())\n                      .template(VirtualGuest.builder().maxMemory(1024).build())\n                      .build())\n              .networkComponents(ContainerVirtualGuestConfigurationOption.builder()\n                      .productItemPrice(ProductItemPrice.builder()\n                              .hourlyRecurringFee(0)\n                              .recurringFee(\"0\")\n                              .item(ProductItem.builder().description(\"10 Mbps Public & Private Networks\").build())\n                              .build())\n                      .template(VirtualGuest.builder().networkComponents(\n                              VirtualGuestNetworkComponent.builder()\n                                      .maxSpeed(10)\n                                      .build())\n                              .build())\n                      .build())\n              .operatingSystems(ContainerVirtualGuestConfigurationOption.builder()\n                      .productItemPrice(ProductItemPrice.builder()\n                              .hourlyRecurringFee(0)\n                              .recurringFee(\"0\")\n                              .item(ProductItem.builder().description(\"CentOS 6.x - Minimal Install (64 bit)\").build())\n                              .build())\n                      .template(VirtualGuest.builder()\n                                              .operatingSystemReferenceCode(\"CENTOS_6_64\")\n                                              .build())\n                      .build())\n              .processors(ContainerVirtualGuestConfigurationOption.builder()\n                      .productItemPrice(ProductItemPrice.builder()\n                              .hourlyRecurringFee(.022f)\n                              .recurringFee(\"15\")\n                              .item(ProductItem.builder().description(\"1 x 2.0 GHz Core\").build())\n                              .build())\n                      .template(VirtualGuest.builder().startCpus(1).build())\n                      .build())\n              .build();\n   }\n\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/java/org/jclouds/softlayer/parse/PublicImagesParseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.parse;\n\nimport java.util.Set;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.softlayer.domain.SoftwareDescription;\nimport org.jclouds.softlayer.domain.VirtualDiskImage;\nimport org.jclouds.softlayer.domain.VirtualDiskImageSoftware;\nimport org.jclouds.softlayer.domain.VirtualGuestBlockDeviceTemplate;\nimport org.jclouds.softlayer.domain.VirtualGuestBlockDeviceTemplateGroup;\nimport org.jclouds.softlayer.internal.BaseSoftLayerParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\")\npublic class PublicImagesParseTest extends\n        BaseSoftLayerParseTest<Set<VirtualGuestBlockDeviceTemplateGroup>> {\n\n   @Override\n   public String resource() {\n      return \"/virtual_guest_block_device_template_group_get_public_images.json\";\n   }\n\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Set<VirtualGuestBlockDeviceTemplateGroup> expected() {\n      return ImmutableSet.of(VirtualGuestBlockDeviceTemplateGroup.builder()\n              .id(33352)\n              .name(\"25G CentOS 6 32-bit\")\n              .statusId(1)\n              .accountId(208938)\n              .parentId(10616)\n              .blockDevices(ImmutableSet.of(\n                      VirtualGuestBlockDeviceTemplate.builder()\n                              .id(42678)\n                              .device(\"0\")\n                              .diskSpace(2597196288f)\n                              .diskImageId(1692629)\n                              .groupId(33352)\n                              .units(\"B\")\n                              .diskImage(VirtualDiskImage.builder()\n                                      .id(1692629)\n                                      .uuid(\"3764c062-43d7-4488-8119-0cf847c3e4db\")\n                                      .capacity(25f)\n                                      .units(\"GB\")\n                                      .typeId(241)\n                                      .description(\"25G CentOS 6 32-bit\")\n                                      .name(\"25G CentOS 6 32-bit\")\n                                      .storageRepositoryId(863078)\n                                      .softwareReferences(\n                                              VirtualDiskImageSoftware.builder()\n                                                      .id(1227351)\n                                                      .softwareDescriptionId(885)\n                                                      .softwareDescription(\n                                                              SoftwareDescription.builder()\n                                                                      .id(885)\n                                                                      .longDescription(\"CentOS / CentOS / 6.0-32 Minimal for CCI\")\n                                                                      .manufacturer(\"CentOS\")\n                                                                      .name(\"CentOS\")\n                                                                      .operatingSystem(1)\n                                                                      .referenceCode(\"CENTOS_6_32\")\n                                                                      .requiredUser(\"root\")\n                                                                      .version(\"6.0-32 Minimal for CCI\")\n                                                                      .controlPanel(0)\n                                                                      .virtualLicense(\"0\")\n                                                                      .virtualizationPlatform(\"0\")\n                                                                      .build())\n                                                      .build())\n                                      .build())\n                              .build(), VirtualGuestBlockDeviceTemplate.builder()\n                      .id(42679)\n                      .device(\"1\")\n                      .diskImageId(1692630)\n                      .diskSpace(0f)\n                      .groupId(33352)\n                      .diskImage(VirtualDiskImage.builder()\n                              .id(1692630)\n                              .name(\"10617-SWAP\")\n                              .uuid(\"ae3d12c3-f624-4c3a-80f5-ceeea2259c16\")\n                              .capacity(2f)\n                              .units(\"GB\")\n                              .typeId(246)\n                              .description(\"10617-SWAP\")\n                              .storageRepositoryId(863078)\n                              .build())\n                      .build()))\n              .build());\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/java/org/jclouds/softlayer/parse/SoftwareDescriptionsParseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.parse;\n\nimport java.util.Set;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.softlayer.domain.SoftwareDescription;\nimport org.jclouds.softlayer.internal.BaseSoftLayerParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\")\npublic class SoftwareDescriptionsParseTest extends BaseSoftLayerParseTest<Set<SoftwareDescription>> {\n\n   @Override\n   public String resource() {\n      return \"/software_description_list.json\";\n   }\n\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Set<SoftwareDescription> expected() {\n      return ImmutableSet.of(\n              SoftwareDescription.builder()\n                      .version(\"6.0-64 LAMP for CCI\")\n                      .referenceCode(\"CENTOS_6_64\")\n                      .operatingSystem(1)\n                      .longDescription(\"CentOS / CentOS / 6.0-64 LAMP for CCI\")\n                      .build(),\n              SoftwareDescription.builder()\n                      .version(\"WEB 64 bit\")\n                      .referenceCode(\"WIN_2008-WEB-R2_64\")\n                      .operatingSystem(1)\n                      .longDescription(\"Microsoft / Windows 2008 FULL WEB 64 bit R2 / WEB 64 bit\")\n                      .build(),\n              SoftwareDescription.builder()\n                      .version(\"12.04-32 Minimal for CCI\")\n                      .referenceCode(\"UBUNTU_12_32\")\n                      .operatingSystem(1)\n                      .longDescription(\"Ubuntu / Ubuntu / 12.04-32 Minimal for CCI\")\n                      .build()\n              );\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/java/org/jclouds/softlayer/parse/VirtualGuestBlockDeviceTemplateGroupParseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.parse;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.softlayer.domain.SoftwareDescription;\nimport org.jclouds.softlayer.domain.VirtualDiskImage;\nimport org.jclouds.softlayer.domain.VirtualDiskImageSoftware;\nimport org.jclouds.softlayer.domain.VirtualGuestBlockDeviceTemplate;\nimport org.jclouds.softlayer.domain.VirtualGuestBlockDeviceTemplateGroup;\nimport org.jclouds.softlayer.internal.BaseSoftLayerParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\")\npublic class\n        VirtualGuestBlockDeviceTemplateGroupParseTest extends\n        BaseSoftLayerParseTest<VirtualGuestBlockDeviceTemplateGroup> {\n\n   @Override\n   public String resource() {\n      return \"/virtual_guest_block_device_template_group_get.json\";\n   }\n\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   public VirtualGuestBlockDeviceTemplateGroup expected() {\n      return VirtualGuestBlockDeviceTemplateGroup.builder()\n              .id(402456)\n              .name(\"DST_Windows-2008_R2DC_x86-64_Base_ICOv2\")\n              .globalIdentifier(\"8df677d9-02a0-43b0-9cc8-88015fcb6ad7\")\n              .statusId(1)\n              .accountId(278462)\n              .summary(\"DST_Windows-2008_R2DC_x86-64_Base with preparation for ICO 2.4\")\n              .children(VirtualGuestBlockDeviceTemplateGroup.builder()\n                              .id(402458)\n                              .name(\"DST_Windows-2008_R2DC_x86-64_Base_ICOv2\")\n                              .statusId(1)\n                              .accountId(278462)\n                              .parentId(402456)\n                              .summary(\"DST_Windows-2008_R2DC_x86-64_Base with preparation for ICO 2.4\")\n                              .blockDevices(ImmutableSet.of(\n                                      VirtualGuestBlockDeviceTemplate.builder()\n                                              .id(508130)\n                                              .device(\"0\")\n                                              .diskSpace(20926382592f)\n                                              .diskImageId(6865056)\n                                              .groupId(402458)\n                                              .units(\"B\")\n                                              .diskImage(VirtualDiskImage.builder()\n                                                      .id(6865056)\n                                                      .uuid(\"00c9bb78-9ac0-4f43-b4d8-35a6568c7db8\")\n                                                      .capacity(25f)\n                                                      .units(\"GB\")\n                                                      .typeId(241)\n                                                      .description(\"rrm-2k8r2dc-ico.dstdev.sl.edst.ibm.com\")\n                                                      .name(\"rrm-2k8r2dc-ico.dstdev.sl.edst.ibm.com\")\n                                                      .storageRepositoryId(2330744)\n                                                      .softwareReferences(ImmutableSet.of(\n                                                              VirtualDiskImageSoftware.builder()\n                                                                      .id(4259392)\n                                                                      .softwareDescriptionId(727)\n                                                                      .softwareDescription(\n                                                                              SoftwareDescription.builder()\n                                                                                      .id(727)\n                                                                                      .longDescription(\"Nimsoft / Nimsoft Robot / 5.0\")\n                                                                                      .manufacturer(\"Nimsoft\")\n                                                                                      .name(\"Nimsoft Robot\")\n                                                                                      .operatingSystem(0)\n                                                                                      .requiredUser(\"administrator\")\n                                                                                      .version(\"5.0\")\n                                                                                      .controlPanel(0)\n                                                                                      .virtualLicense(\"0\")\n                                                                                      .virtualizationPlatform(\"0\")\n                                                                                      .build())\n                                                                      .build(),\n                                                              VirtualDiskImageSoftware.builder()\n                                                                      .id(4259394)\n                                                                      .softwareDescriptionId(829)\n                                                                      .softwareDescription(\n                                                                              SoftwareDescription.builder()\n                                                                                      .id(829)\n                                                                                      .longDescription(\"Microsoft / Windows 2008 FULL DC 64 bit R2 SP1 / DC 64 bit\")\n                                                                                      .manufacturer(\"Microsoft\")\n                                                                                      .name(\"Windows 2008 FULL DC 64 bit R2 SP1\")\n                                                                                      .operatingSystem(1)\n                                                                                      .referenceCode(\"WIN_2008-DC-R2-SP1_64\")\n                                                                                      .requiredUser(\"Administrator\")\n                                                                                      .version(\"DC 64 bit\")\n                                                                                      .controlPanel(0)\n                                                                                      .virtualLicense(\"0\")\n                                                                                      .virtualizationPlatform(\"0\")\n                                                                                      .build())\n                                                                      .build()))\n                                                      .build())\n                                              .build(),\n                                      VirtualGuestBlockDeviceTemplate.builder()\n                                              .id(508136)\n                                              .device(\"1\")\n                                              .diskImageId(6865060)\n                                              .groupId(402458)\n                                              .diskImage(VirtualDiskImage.builder()\n                                                      .id(6865060)\n                                                      .name(\"7903014-SWAP\")\n                                                      .uuid(\"38eb1c23-0cf9-4325-b78a-95545829a36d\")\n                                                      .capacity(2f)\n                                                      .units(\"GB\")\n                                                      .typeId(246)\n                                                      .description(\"7903014-SWAP\")\n                                                      .storageRepositoryId(2330744)\n                                                      .build())\n                                              .build()))\n                              .build(),\n                      VirtualGuestBlockDeviceTemplateGroup.builder()\n                              .id(402460)\n                              .name(\"DST_Windows-2008_R2DC_x86-64_Base_ICOv2\")\n                              .statusId(1)\n                              .accountId(278462)\n                              .parentId(402456)\n                              .summary(\"DST_Windows-2008_R2DC_x86-64_Base with preparation for ICO 2.4\")\n                              .blockDevices(\n                                      VirtualGuestBlockDeviceTemplate.builder()\n                                              .id(508132)\n                                              .device(\"0\")\n                                              .diskSpace(20926382592f)\n                                              .diskImageId(6865054)\n                                              .groupId(402460)\n                                              .units(\"B\")\n                                              .diskImage(VirtualDiskImage.builder()\n                                                      .id(6865054)\n                                                      .capacity(25f)\n                                                      .description(\"rrm-2k8r2dc-ico.dstdev.sl.edst.ibm.com\")\n                                                      .name(\"rrm-2k8r2dc-ico.dstdev.sl.edst.ibm.com\")\n                                                      .storageRepositoryId(2330746)\n                                                      .units(\"GB\")\n                                                      .typeId(241)\n                                                      .uuid(\"ef20e61c-6814-47bf-8cd9-9d26f84d3789\")\n                                                      .softwareReferences(ImmutableSet.of(\n                                                              VirtualDiskImageSoftware.builder()\n                                                                      .id(4259396)\n                                                                      .softwareDescriptionId(727)\n                                                                      .softwareDescription(\n                                                                              SoftwareDescription.builder()\n                                                                                      .id(727)\n                                                                                      .longDescription(\"Nimsoft / Nimsoft Robot / 5.0\")\n                                                                                      .manufacturer(\"Nimsoft\")\n                                                                                      .name(\"Nimsoft Robot\")\n                                                                                      .operatingSystem(0)\n                                                                                      .requiredUser(\"administrator\")\n                                                                                      .version(\"5.0\")\n                                                                                      .controlPanel(0)\n                                                                                      .virtualLicense(\"0\")\n                                                                                      .virtualizationPlatform(\"0\")\n                                                                                      .build())\n                                                                      .build(),\n                                                              VirtualDiskImageSoftware.builder()\n                                                                      .id(4259398)\n                                                                      .softwareDescriptionId(829)\n                                                                      .softwareDescription(\n                                                                              SoftwareDescription.builder()\n                                                                                      .id(829)\n                                                                                      .longDescription(\"Microsoft / Windows 2008 FULL DC 64 bit R2 SP1 / DC 64 bit\")\n                                                                                      .manufacturer(\"Microsoft\")\n                                                                                      .name(\"Windows 2008 FULL DC 64 bit R2 SP1\")\n                                                                                      .operatingSystem(1)\n                                                                                      .referenceCode(\"WIN_2008-DC-R2-SP1_64\")\n                                                                                      .requiredUser(\"Administrator\")\n                                                                                      .version(\"DC 64 bit\")\n                                                                                      .controlPanel(0)\n                                                                                      .virtualLicense(\"0\")\n                                                                                      .virtualizationPlatform(\"0\")\n                                                                                      .build())\n                                                                      .build()))\n                                                      .build())\n                                              .build(),\n                                      VirtualGuestBlockDeviceTemplate.builder()\n                                              .id(508134)\n                                              .device(\"1\")\n                                              .diskImageId(6865058)\n                                              .groupId(402460)\n                                              .diskImage(VirtualDiskImage.builder()\n                                                      .id(6865058)\n                                                      .name(\"7903014-SWAP\")\n                                                      .capacity(2f)\n                                                      .description(\"7903014-SWAP\")\n                                                      .storageRepositoryId(2330746)\n                                                      .typeId(246)\n                                                      .units(\"GB\")\n                                                      .uuid(\"c84edb86-a9ce-4932-bf2c-c3e4b2b44ae9\")\n                                                      .build())\n                                              .build())\n                              .build())\n              .build();\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/java/org/jclouds/softlayer/parse/VirtualGuestBlockDeviceTemplateGroupsParseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.parse;\n\nimport java.util.Set;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.softlayer.domain.SoftwareDescription;\nimport org.jclouds.softlayer.domain.VirtualDiskImage;\nimport org.jclouds.softlayer.domain.VirtualDiskImageSoftware;\nimport org.jclouds.softlayer.domain.VirtualGuestBlockDeviceTemplate;\nimport org.jclouds.softlayer.domain.VirtualGuestBlockDeviceTemplateGroup;\nimport org.jclouds.softlayer.internal.BaseSoftLayerParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\")\npublic class\n        VirtualGuestBlockDeviceTemplateGroupsParseTest extends\n        BaseSoftLayerParseTest<Set<VirtualGuestBlockDeviceTemplateGroup>> {\n\n   @Override\n   public String resource() {\n      return \"/account_get_block_devices_template_groups.json\";\n   }\n\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Set<VirtualGuestBlockDeviceTemplateGroup> expected() {\n      return ImmutableSet.of(VirtualGuestBlockDeviceTemplateGroup.builder()\n              .id(82898)\n              .name(\"Backup template for disk migration of 'ljvsilauncher1.scic.ibm.com'.\")\n              .globalIdentifier(\"e4055a07-13f5-4fa9-ab46-b023b65c47d2\")\n              .statusId(1)\n              .accountId(278184)\n              .children(VirtualGuestBlockDeviceTemplateGroup.builder()\n                      .id(82900)\n                      .name(\"Backup template for disk migration of 'ljvsilauncher1.scic.ibm.com'.\")\n                      .statusId(1)\n                      .accountId(278184)\n                      .parentId(82898)\n                      .blockDevices(ImmutableSet.of(\n                              VirtualGuestBlockDeviceTemplate.builder()\n                                      .id(108100)\n                                      .device(\"0\")\n                                      .diskSpace(21832020480f)\n                                      .diskImageId(2190750)\n                                      .groupId(82900)\n                                      .units(\"B\")\n                                      .diskImage(VirtualDiskImage.builder()\n                                              .id(2190750)\n                                              .uuid(\"42423638-a54e-4d82-9b23-25af5fb13547\")\n                                              .capacity(25f)\n                                              .units(\"GB\")\n                                              .typeId(241)\n                                              .description(\"ljvsilauncher1.scic.ibm.com\")\n                                              .name(\"ljvsilauncher1.scic.ibm.com\")\n                                              .storageRepositoryId(906427)\n                                              .softwareReferences(ImmutableSet.of(\n                                                      VirtualDiskImageSoftware.builder()\n                                                              .id(1498856)\n                                                              .softwareDescriptionId(1076)\n                                                              .softwareDescription(\n                                                                      SoftwareDescription.builder()\n                                                                              .id(1076)\n                                                                              .longDescription(\"Microsoft / Windows 2012 FULL STD 64 bit / STD x64\")\n                                                                              .manufacturer(\"Microsoft\")\n                                                                              .name(\"Windows 2012 FULL STD 64 bit\")\n                                                                              .operatingSystem(1)\n                                                                              .referenceCode(\"WIN_2012-STD_64\")\n                                                                              .requiredUser(\"Administrator\")\n                                                                              .version(\"STD x64\")\n                                                                              .controlPanel(0)\n                                                                              .virtualLicense(\"0\")\n                                                                              .virtualizationPlatform(\"0\")\n                                                                              .build())\n                                                              .build(),\n                                                      VirtualDiskImageSoftware.builder()\n                                                              .id(1498858)\n                                                              .softwareDescriptionId(106)\n                                                              .softwareDescription(\n                                                                      SoftwareDescription.builder()\n                                                                              .id(106)\n                                                                              .longDescription(\"Microsoft / Windows Firewall / 1\")\n                                                                              .manufacturer(\"Microsoft\")\n                                                                              .name(\"Windows Firewall\")\n                                                                              .operatingSystem(0)\n                                                                              .version(\"1\")\n                                                                              .controlPanel(0)\n                                                                              .virtualLicense(\"0\")\n                                                                              .virtualizationPlatform(\"0\")\n                                                                              .build())\n                                                              .build()))\n                                              .build())\n                                      .build(), VirtualGuestBlockDeviceTemplate.builder()\n                                      .id(108102)\n                                      .device(\"1\")\n                                      .diskImageId(2190752)\n                                      .groupId(82900)\n                                      .diskImage(VirtualDiskImage.builder()\n                                              .id(2190752)\n                                              .name(\"3334230-SWAP\")\n                                              .uuid(\"9f087bfb-3ed4-4985-a8b7-ac67bd8316e6\")\n                                              .capacity(2f)\n                                              .units(\"GB\")\n                                              .typeId(246)\n                                              .description(\"3334230-SWAP\")\n                                              .storageRepositoryId(906427)\n                                              .build())\n                                      .build()))\n                      .build())\n              .build());\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/java/org/jclouds/softlayer/parse/VirtualGuestFilteredParseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.parse;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.softlayer.domain.NetworkVlan;\nimport org.jclouds.softlayer.domain.VirtualGuest;\nimport org.jclouds.softlayer.domain.VirtualGuestNetworkComponent;\nimport org.jclouds.softlayer.internal.BaseSoftLayerParseTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class VirtualGuestFilteredParseTest extends BaseSoftLayerParseTest<VirtualGuest> {\n\n   @Override\n   public String resource() {\n      return \"/virtual_guest_get_filtered.json\";\n   }\n\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   public VirtualGuest expected() {\n      return VirtualGuest.builder()\n                              .id(3001812)\n                              .primaryBackendNetworkComponent(VirtualGuestNetworkComponent.builder()\n                                      .networkId(123456)\n                                      .networkVlan(NetworkVlan.builder()\n                                              .id(1234)\n                                              .name(\"abc\")\n                                              .build())\n                                      .build())\n                              .build();\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/java/org/jclouds/softlayer/parse/VirtualGuestParseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.parse;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.softlayer.domain.VirtualGuest;\nimport org.jclouds.softlayer.internal.BaseSoftLayerParseTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class VirtualGuestParseTest extends BaseSoftLayerParseTest<VirtualGuest> {\n\n   @Override\n   public String resource() {\n      return \"/virtual_guest_get.json\";\n   }\n\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   public VirtualGuest expected() {\n      return VirtualGuest.builder()\n                              .accountId(278184)\n                              .createDate(new SimpleDateFormatDateService().iso8601DateParse(\"2013-07-26T14:08:21.552-07:00\"))\n                              .dedicatedAccountHostOnly(false)\n                              .domain(\"test.com\")\n                              .fullyQualifiedDomainName(\"my.test.com\")\n                              .hostname(\"my\")\n                              .id(3001812)\n                              .lastVerifiedDate(null)\n                              .maxCpu(1)\n                              .maxCpuUnits(\"CORE\")\n                              .maxMemory(1024)\n                              .metricPollDate(null)\n                              .modifyDate(new SimpleDateFormatDateService().iso8601DateParse(\"2013-07-26T14:10:21.552-07:00\"))\n                              .privateNetworkOnlyFlag(false)\n                              .startCpus(1)\n                              .statusId(1001)\n                              .uuid(\"92102aff-93c9-05f1-b3f2-50787e865344\")\n                              .primaryBackendIpAddress(\"10.32.23.74\")\n                              .primaryIpAddress(\"174.37.252.118\")\n                              .billingItemId(0)\n                              .operatingSystem(null)\n                              .datacenter(null)\n                              .powerState(null)\n                              .softwareLicense(null)\n                              .build();\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/java/org/jclouds/softlayer/parse/VirtualGuestsParseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.softlayer.parse;\n\nimport java.util.Set;\n\nimport jakarta.ws.rs.Consumes;\nimport jakarta.ws.rs.core.MediaType;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.softlayer.domain.VirtualGuest;\nimport org.jclouds.softlayer.internal.BaseSoftLayerParseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\")\npublic class VirtualGuestsParseTest extends BaseSoftLayerParseTest<Set<VirtualGuest>> {\n\n   @Override\n   public String resource() {\n      return \"/account_list.json\";\n   }\n\n   @Override\n   @Consumes(MediaType.APPLICATION_JSON)\n   public Set<VirtualGuest> expected() {\n      return ImmutableSet.of(\n                      VirtualGuest.builder()\n                              .accountId(278184)\n                              .createDate(new SimpleDateFormatDateService().iso8601DateParse(\"2013-07-26T14:08:21.552-07:00\"))\n                              .dedicatedAccountHostOnly(false)\n                              .domain(\"test.com\")\n                              .fullyQualifiedDomainName(\"my.test.com\")\n                              .hostname(\"my\")\n                              .id(3001812)\n                              .lastVerifiedDate(null)\n                              .maxCpu(1)\n                              .maxCpuUnits(\"CORE\")\n                              .maxMemory(1024)\n                              .metricPollDate(null)\n                              .modifyDate(new SimpleDateFormatDateService().iso8601DateParse(\"2013-07-26T14:10:21.552-07:00\"))\n                              .privateNetworkOnlyFlag(false)\n                              .startCpus(1)\n                              .statusId(1001)\n                              .uuid(\"92102aff-93c9-05f1-b3f2-50787e865344\")\n                              .primaryBackendIpAddress(\"10.32.23.74\")\n                              .primaryIpAddress(\"174.37.252.118\")\n                              .billingItemId(0)\n                              .operatingSystem(null)\n                              .datacenter(null)\n                              .powerState(null)\n                              .softwareLicense(null)\n                              .build());\n   }\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/resources/account_get_block_devices_template_groups.json",
    "content": "[\n  {\n    \"accountId\": 278184,\n    \"createDate\": \"2014-01-30T13:00:23+00:00\",\n    \"id\": 82898,\n    \"name\": \"Backup template for disk migration of 'ljvsilauncher1.scic.ibm.com'.\",\n    \"note\": \"This is a backup template for the disk migration of 'ljvsilauncher1.scic.ibm.com' and is not required. This image may be removed at any time.\",\n    \"parentId\": null,\n    \"statusId\": 1,\n    \"transactionId\": null,\n    \"userRecordId\": null,\n    \"children\": [\n      {\n        \"accountId\": 278184,\n        \"createDate\": \"2014-01-30T13:00:53+00:00\",\n        \"id\": 82900,\n        \"name\": \"Backup template for disk migration of 'ljvsilauncher1.scic.ibm.com'.\",\n        \"note\": \"This is a backup template for the disk migration of 'ljvsilauncher1.scic.ibm.com' and is not required. This image may be removed at any time.\",\n        \"parentId\": 82898,\n        \"statusId\": 1,\n        \"transactionId\": null,\n        \"userRecordId\": null,\n        \"blockDevices\": [\n          {\n            \"device\": \"0\",\n            \"diskImageId\": 2190750,\n            \"diskSpace\": 21832020480,\n            \"groupId\": 82900,\n            \"id\": 108100,\n            \"units\": \"B\",\n            \"diskImage\": {\n              \"capacity\": 25,\n              \"checksum\": \"304a9bce56437af567444567e612506d\",\n              \"createDate\": \"2014-01-30T13:00:53+00:00\",\n              \"description\": \"ljvsilauncher1.scic.ibm.com\",\n              \"id\": 2190750,\n              \"modifyDate\": \"2014-01-30T13:14:09+00:00\",\n              \"name\": \"ljvsilauncher1.scic.ibm.com\",\n              \"parentId\": null,\n              \"storageRepositoryId\": 906427,\n              \"typeId\": 241,\n              \"units\": \"GB\",\n              \"uuid\": \"42423638-a54e-4d82-9b23-25af5fb13547\",\n              \"softwareReferences\": [\n                {\n                  \"id\": 1498856,\n                  \"softwareDescriptionId\": 1076,\n                  \"softwareDescription\": {\n                    \"controlPanel\": 0,\n                    \"id\": 1076,\n                    \"longDescription\": \"Microsoft / Windows 2012 FULL STD 64 bit / STD x64\",\n                    \"manufacturer\": \"Microsoft\",\n                    \"name\": \"Windows 2012 FULL STD 64 bit\",\n                    \"operatingSystem\": 1,\n                    \"referenceCode\": \"WIN_2012-STD_64\",\n                    \"upgradeSoftwareDescriptionId\": null,\n                    \"upgradeSwDescId\": null,\n                    \"version\": \"STD x64\",\n                    \"virtualLicense\": 0,\n                    \"virtualizationPlatform\": 0,\n                    \"requiredUser\": \"Administrator\"\n                  }\n                },\n                {\n                  \"id\": 1498858,\n                  \"softwareDescriptionId\": 106,\n                  \"softwareDescription\": {\n                    \"controlPanel\": 0,\n                    \"id\": 106,\n                    \"longDescription\": \"Microsoft / Windows Firewall / 1\",\n                    \"manufacturer\": \"Microsoft\",\n                    \"name\": \"Windows Firewall\",\n                    \"operatingSystem\": 0,\n                    \"upgradeSoftwareDescriptionId\": null,\n                    \"upgradeSwDescId\": null,\n                    \"version\": \"1\",\n                    \"virtualLicense\": 0,\n                    \"virtualizationPlatform\": 0\n                  }\n                }\n              ]\n            }\n          },\n          {\n            \"device\": \"1\",\n            \"diskImageId\": 2190752,\n            \"groupId\": 82900,\n            \"id\": 108102,\n            \"diskImage\": {\n              \"capacity\": 2,\n              \"createDate\": \"2014-01-30T13:00:58+00:00\",\n              \"description\": \"3334230-SWAP\",\n              \"id\": 2190752,\n              \"modifyDate\": null,\n              \"name\": \"3334230-SWAP\",\n              \"parentId\": null,\n              \"storageRepositoryId\": 906427,\n              \"typeId\": 246,\n              \"units\": \"GB\",\n              \"uuid\": \"9f087bfb-3ed4-4985-a8b7-ac67bd8316e6\",\n              \"softwareReferences\": []\n            }\n          }\n        ],\n        \"children\": []\n      }\n    ],\n    \"globalIdentifier\": \"e4055a07-13f5-4fa9-ab46-b023b65c47d2\"\n  }\n]"
  },
  {
    "path": "providers/softlayer/src/test/resources/account_list.json",
    "content": "[\n  {\n    \"primaryIpAddress\": \"174.37.252.118\",\n    \"primaryBackendIpAddress\": \"10.32.23.74\",\n    \"globalIdentifier\": \"da2b9f87-2319-4a12-91a5-f7f732061dcc\",\n    \"uuid\": \"92102aff-93c9-05f1-b3f2-50787e865344\",\n    \"lastPowerStateId\": null,\n    \"id\": 3001812,\n    \"hostname\": \"my\",\n    \"fullyQualifiedDomainName\": \"my.test.com\",\n    \"domain\": \"test.com\",\n    \"dedicatedAccountHostOnlyFlag\": false,\n    \"createDate\": \"2013-07-26T14:08:21.552-07:00\",\n    \"accountId\": 278184,\n    \"lastVerifiedDate\": null,\n    \"maxCpu\": 1,\n    \"maxCpuUnits\": \"CORE\",\n    \"maxMemory\": 1024,\n    \"metricPollDate\": null,\n    \"modifyDate\": \"2013-07-26T14:10:21.552-07:00\",\n    \"startCpus\": 1,\n    \"statusId\": 1001\n  }\n]"
  },
  {
    "path": "providers/softlayer/src/test/resources/container_virtual_guest_configuration.json",
    "content": "{\n  \"blockDevices\": [\n    {\n      \"itemPrice\": {\n        \"hourlyRecurringFee\": \"0\",\n        \"recurringFee\": \"0\",\n        \"item\": {\n          \"description\": \"25 GB (SAN)\"\n        }\n      },\n      \"template\": {\n        \"blockDevices\": [\n          {\n            \"device\": \"0\",\n            \"diskImage\": {\n              \"capacity\": 25\n            }\n          }\n        ],\n        \"localDiskFlag\": false\n      }\n    }\n  ],\n  \"datacenters\": [\n    {\n      \"template\": {\n        \"datacenter\": {\n          \"name\": \"ams01\"\n        }\n      }\n    }\n  ],\n  \"memory\": [\n    {\n      \"itemPrice\": {\n        \"hourlyRecurringFee\": \".02\",\n        \"recurringFee\": \"14\",\n        \"item\": {\n          \"description\": \"1 GB\"\n        }\n      },\n      \"template\": {\n        \"maxMemory\": 1024\n      }\n    }\n  ],\n  \"networkComponents\": [\n    {\n      \"itemPrice\": {\n        \"hourlyRecurringFee\": \"0\",\n        \"recurringFee\": \"0\",\n        \"item\": {\n          \"description\": \"10 Mbps Public & Private Networks\"\n        }\n      },\n      \"template\": {\n        \"networkComponents\": [\n          {\n            \"maxSpeed\": 10\n          }\n        ]\n      }\n    }\n  ],\n  \"operatingSystems\": [\n    {\n      \"itemPrice\": {\n        \"hourlyRecurringFee\": \"0\",\n        \"recurringFee\": \"0\",\n        \"item\": {\n          \"description\": \"CentOS 6.x - Minimal Install (64 bit)\"\n        }\n      },\n      \"template\": {\n        \"operatingSystemReferenceCode\": \"CENTOS_6_64\"\n      }\n    }\n  ],\n  \"processors\": [\n    {\n      \"itemPrice\": {\n        \"hourlyRecurringFee\": \".022\",\n        \"recurringFee\": \"15\",\n        \"item\": {\n          \"description\": \"1 x 2.0 GHz Core\"\n        }\n      },\n      \"template\": {\n        \"startCpus\": 1\n      }\n    }\n  ]\n}"
  },
  {
    "path": "providers/softlayer/src/test/resources/datacenter_get.json",
    "content": "{\n  \"id\": 265592,\n  \"longName\": \"Amsterdam 1\",\n  \"name\": \"ams01\",\n  \"locationAddress\": {\n    \"accountId\": 1,\n    \"address1\": \"Paul van Vlissingenstraat 16\",\n    \"city\": \"Amsterdam\",\n    \"contactName\": \"SoftLayer\",\n    \"country\": \"NL\",\n    \"description\": \"Amsterdam - AMS01\",\n    \"id\": 3322,\n    \"isActive\": 1,\n    \"locationId\": 265592,\n    \"postalCode\": \"1096 BK\",\n    \"type\": {\n      \"createDate\": \"2010-04-06T04:49:15+01:00\",\n      \"id\": 1,\n      \"keyName\": \"SOFTLAYER_DATACENTER\",\n      \"name\": \"SoftLayer Datacenter (accepts customer DTS shipments)\"\n    }\n  },\n  \"regions\": [\n    {\n      \"description\": \"AMS01 - Amsterdam - Western Europe\",\n      \"keyname\": \"AMSTERDAM\",\n      \"sortOrder\": 0\n    }\n  ]\n}"
  },
  {
    "path": "providers/softlayer/src/test/resources/datacenter_list.json",
    "content": "[\n  {\n    \"id\": 265592,\n    \"longName\": \"Amsterdam 1\",\n    \"name\": \"ams01\"\n  },\n  {\n    \"id\": 3,\n    \"longName\": \"Dallas 1\",\n    \"name\": \"dal01\"\n  },\n  {\n    \"id\": 154770,\n    \"longName\": \"Dallas 2\",\n    \"name\": \"dal02\"\n  },\n  {\n    \"id\": 167092,\n    \"longName\": \"Dallas 4\",\n    \"name\": \"dal04\"\n  },\n  {\n    \"id\": 138124,\n    \"longName\": \"Dallas 5\",\n    \"name\": \"dal05\"\n  },\n  {\n    \"id\": 154820,\n    \"longName\": \"Dallas 6\",\n    \"name\": \"dal06\"\n  },\n  {\n    \"id\": 142776,\n    \"longName\": \"Dallas 7\",\n    \"name\": \"dal07\"\n  },\n  {\n    \"id\": 352392,\n    \"longName\": \"Dallas 8\",\n    \"name\": \"dal08\"\n  },\n  {\n    \"id\": 352494,\n    \"longName\": \"Hong Kong 2\",\n    \"name\": \"hkg02\"\n  },\n  {\n    \"id\": 142775,\n    \"longName\": \"Houston 2\",\n    \"name\": \"hou02\"\n  },\n  {\n    \"id\": 168642,\n    \"longName\": \"San Jose 1\",\n    \"name\": \"sjc01\"\n  },\n  {\n    \"id\": 18171,\n    \"longName\": \"Seattle\",\n    \"name\": \"sea01\"\n  },\n  {\n    \"id\": 224092,\n    \"longName\": \"Singapore 1\",\n    \"name\": \"sng01\"\n  },\n  {\n    \"id\": 37473,\n    \"longName\": \"Washington, DC\",\n    \"name\": \"wdc01\"\n  }\n]"
  },
  {
    "path": "providers/softlayer/src/test/resources/logback-test.xml",
    "content": "<?xml version=\"1.0\"?>\n<configuration scan=\"false\">\n    <appender name=\"FILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds.log</file>\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n    <appender name=\"WIREFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds-wire.log</file>\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n    <appender name=\"COMPUTEFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/jclouds-compute.log</file>\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <logger name=\"org.jclouds\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"FILE\" />\n    </logger>\n    <logger name=\"jclouds.compute\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"COMPUTEFILE\" />\n    </logger>\n    <logger name=\"jclouds.wire\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n    <logger name=\"jclouds.headers\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n    \n    <root>\n        <level value=\"INFO\" />\n    </root>\n</configuration>"
  },
  {
    "path": "providers/softlayer/src/test/resources/network_createObject.json",
    "content": "{\n  \"accountId\": 1186236,\n  \"id\": 153001,\n  \"cidr\": 16,\n  \"name\": \"testNet\",\n  \"networkIdentifier\": \"192.168.0.0\"\n}\n"
  },
  {
    "path": "providers/softlayer/src/test/resources/network_createSubnet.json",
    "content": "{\n  \"broadcastAddress\": \"192.168.1.255\",\n  \"cidr\": 24,\n  \"gateway\": \"192.168.1.1\",\n  \"id\": 1581517,\n  \"isCustomerOwned\": true,\n  \"isCustomerRoutable\": false,\n  \"modifyDate\": null,\n  \"netmask\": \"255.255.255.0\",\n  \"networkIdentifier\": \"192.168.1.0\",\n  \"networkVlanId\": null,\n  \"note\": \"testNet test create subnet\",\n  \"sortOrder\": \"4\",\n  \"totalIpAddresses\": \"256\",\n  \"usableIpAddressCount\": \"253\",\n  \"version\": 4,\n  \"addressSpace\": \"PRIVATE\"\n}"
  },
  {
    "path": "providers/softlayer/src/test/resources/network_get_153001.json",
    "content": "{\n  \"accountId\": 1186236,\n  \"id\": 153503,\n  \"cidr\": 16,\n  \"name\": \"testNet\",\n  \"networkIdentifier\": \"192.168.0.0\",\n  \"notes\": \"this is a test network from JClouds NetworkApiMockTest.\"\n}"
  },
  {
    "path": "providers/softlayer/src/test/resources/network_list.json",
    "content": "[\n  {\n    \"accountId\": 1186236,\n    \"id\": 153602,\n    \"cidr\": 24,\n    \"name\": \"newNetworkApiLiveTestNetwork\",\n    \"networkIdentifier\": \"192.168.253.0\",\n    \"notes\": \"new notes\"\n  },\n  {\n    \"accountId\": 1186236,\n    \"id\": 7505,\n    \"cidr\": 16,\n    \"name\": \"ADN-public\",\n    \"networkIdentifier\": \"10.0.0.0\",\n    \"notes\": \"This network is available for testing and demo purposes.  Anything here will be automatically removed periodically\"\n  },\n  {\n    \"accountId\": 1186236,\n    \"id\": 12202,\n    \"cidr\": 24,\n    \"name\": \"testNet\",\n    \"networkIdentifier\": \"10.0.0.0\"\n  },\n  {\n    \"accountId\": 1186236,\n    \"id\": 6802,\n    \"cidr\": 24,\n    \"name\": \"mcltn-172-31-1\",\n    \"networkIdentifier\": \"172.31.1.0\",\n    \"notes\": \"mcltn network\"\n  },\n  {\n    \"accountId\": 1186236,\n    \"id\": 6932,\n    \"cidr\": 16,\n    \"name\": \"khoa_network\",\n    \"networkIdentifier\": \"10.0.0.0\",\n    \"notes\": \"Khoa's first test network\"\n  }\n]"
  },
  {
    "path": "providers/softlayer/src/test/resources/network_subnet_get_1592631.json",
    "content": "[\n  {\n    \"broadcastAddress\": \"192.168.253.15\",\n    \"cidr\": 28,\n    \"gateway\": \"192.168.253.1\",\n    \"id\": 1592631,\n    \"isCustomerOwned\": true,\n    \"isCustomerRoutable\": false,\n    \"modifyDate\": \"2017-11-09T08:07:22-06:00\",\n    \"netmask\": \"255.255.255.240\",\n    \"networkIdentifier\": \"192.168.253.0\",\n    \"networkVlanId\": 2188589,\n    \"note\": \"This is a test subnet from NetworkApiMockTest\",\n    \"sortOrder\": \"1\",\n    \"subnetType\": \"ADDITIONAL_PRIMARY\",\n    \"totalIpAddresses\": \"16\",\n    \"usableIpAddressCount\": \"13\",\n    \"version\": 4,\n    \"datacenter\": {\n      \"id\": 1441195,\n      \"longName\": \"Dallas 10\",\n      \"name\": \"dal10\",\n      \"statusId\": 2\n    }\n  }\n]"
  },
  {
    "path": "providers/softlayer/src/test/resources/software_description_list.json",
    "content": "[\n  {\n    \"version\": \"6.0-64 LAMP for CCI\",\n    \"referenceCode\": \"CENTOS_6_64\",\n    \"operatingSystem\": 1,\n    \"longDescription\": \"CentOS / CentOS / 6.0-64 LAMP for CCI\"\n  },\n\n  {\n    \"version\": \"WEB 64 bit\",\n    \"referenceCode\": \"WIN_2008-WEB-R2_64\",\n    \"operatingSystem\": 1,\n    \"longDescription\": \"Microsoft / Windows 2008 FULL WEB 64 bit R2 / WEB 64 bit\"\n  },\n  {\n    \"version\": \"12.04-32 Minimal for CCI\",\n    \"referenceCode\": \"UBUNTU_12_32\",\n    \"operatingSystem\": 1,\n    \"longDescription\": \"Ubuntu / Ubuntu / 12.04-32 Minimal for CCI\"\n  },\n]\n"
  },
  {
    "path": "providers/softlayer/src/test/resources/virtual_guest_block_device_template_group_get.json",
    "content": "{\n  \"accountId\": 278462,\n  \"createDate\": \"2015-01-26T23:36:05+00:00\",\n  \"id\": 402456,\n  \"name\": \"DST_Windows-2008_R2DC_x86-64_Base_ICOv2\",\n  \"note\": \"DST Standard Windows image for deploying into VSP in ICO 2.4\",\n  \"parentId\": null,\n  \"publicFlag\": 1,\n  \"statusId\": 1,\n  \"summary\": \"DST_Windows-2008_R2DC_x86-64_Base with preparation for ICO 2.4\",\n  \"transactionId\": null,\n  \"userRecordId\": 146842,\n  \"accountReferences\": [],\n  \"children\": [\n    {\n      \"accountId\": 278462,\n      \"createDate\": \"2015-01-26T23:36:10+00:00\",\n      \"id\": 402458,\n      \"name\": \"DST_Windows-2008_R2DC_x86-64_Base_ICOv2\",\n      \"note\": \"DST Standard Windows image for deploying into VSP in ICO 2.4\",\n      \"parentId\": 402456,\n      \"publicFlag\": 1,\n      \"statusId\": 1,\n      \"summary\": \"DST_Windows-2008_R2DC_x86-64_Base with preparation for ICO 2.4\",\n      \"transactionId\": null,\n      \"userRecordId\": 146842,\n      \"blockDevices\": [\n        {\n          \"device\": \"0\",\n          \"diskImageId\": 6865056,\n          \"diskSpace\": 20926382592,\n          \"groupId\": 402458,\n          \"id\": 508130,\n          \"units\": \"B\",\n          \"diskImage\": {\n            \"capacity\": 25,\n            \"createDate\": \"2015-01-26T23:36:10+00:00\",\n            \"description\": \"rrm-2k8r2dc-ico.dstdev.sl.edst.ibm.com\",\n            \"id\": 6865056,\n            \"modifyDate\": null,\n            \"name\": \"rrm-2k8r2dc-ico.dstdev.sl.edst.ibm.com\",\n            \"parentId\": null,\n            \"storageRepositoryId\": 2330744,\n            \"typeId\": 241,\n            \"units\": \"GB\",\n            \"uuid\": \"00c9bb78-9ac0-4f43-b4d8-35a6568c7db8\",\n            \"softwareReferences\": [\n              {\n                \"id\": 4259392,\n                \"softwareDescriptionId\": 727,\n                \"softwareDescription\": {\n                  \"controlPanel\": 0,\n                  \"id\": 727,\n                  \"longDescription\": \"Nimsoft / Nimsoft Robot / 5.0\",\n                  \"manufacturer\": \"Nimsoft\",\n                  \"name\": \"Nimsoft Robot\",\n                  \"operatingSystem\": 0,\n                  \"upgradeSoftwareDescriptionId\": null,\n                  \"upgradeSwDescId\": null,\n                  \"version\": \"5.0\",\n                  \"virtualLicense\": 0,\n                  \"virtualizationPlatform\": 0,\n                  \"requiredUser\": \"administrator\"\n                }\n              },\n              {\n                \"id\": 4259394,\n                \"softwareDescriptionId\": 829,\n                \"softwareDescription\": {\n                  \"controlPanel\": 0,\n                  \"id\": 829,\n                  \"longDescription\": \"Microsoft / Windows 2008 FULL DC 64 bit R2 SP1 / DC 64 bit\",\n                  \"manufacturer\": \"Microsoft\",\n                  \"name\": \"Windows 2008 FULL DC 64 bit R2 SP1\",\n                  \"operatingSystem\": 1,\n                  \"referenceCode\": \"WIN_2008-DC-R2-SP1_64\",\n                  \"upgradeSoftwareDescriptionId\": null,\n                  \"upgradeSwDescId\": null,\n                  \"version\": \"DC 64 bit\",\n                  \"virtualLicense\": 0,\n                  \"virtualizationPlatform\": 0,\n                  \"requiredUser\": \"Administrator\"\n                }\n              }\n            ],\n            \"storageRepository\": {\n              \"description\": \"SL278462 Public\",\n              \"id\": 2330744,\n              \"name\": \"SL278462 Public\",\n              \"publicFlag\": 1,\n              \"typeId\": 181\n            }\n          }\n        },\n        {\n          \"device\": \"1\",\n          \"diskImageId\": 6865060,\n          \"groupId\": 402458,\n          \"id\": 508136,\n          \"diskImage\": {\n            \"capacity\": 2,\n            \"createDate\": \"2015-01-26T23:36:11+00:00\",\n            \"description\": \"7903014-SWAP\",\n            \"id\": 6865060,\n            \"modifyDate\": null,\n            \"name\": \"7903014-SWAP\",\n            \"parentId\": null,\n            \"storageRepositoryId\": 2330744,\n            \"typeId\": 246,\n            \"units\": \"GB\",\n            \"uuid\": \"38eb1c23-0cf9-4325-b78a-95545829a36d\",\n            \"softwareReferences\": [],\n            \"storageRepository\": {\n              \"description\": \"SL278462 Public\",\n              \"id\": 2330744,\n              \"name\": \"SL278462 Public\",\n              \"publicFlag\": 1,\n              \"typeId\": 181\n            }\n          }\n        }\n      ],\n      \"parent\": {\n        \"accountId\": 278462,\n        \"createDate\": \"2015-01-26T23:36:05+00:00\",\n        \"id\": 402456,\n        \"name\": \"DST_Windows-2008_R2DC_x86-64_Base_ICOv2\",\n        \"note\": \"DST Standard Windows image for deploying into VSP in ICO 2.4\",\n        \"parentId\": null,\n        \"publicFlag\": 1,\n        \"statusId\": 1,\n        \"summary\": \"DST_Windows-2008_R2DC_x86-64_Base with preparation for ICO 2.4\",\n        \"transactionId\": null,\n        \"userRecordId\": 146842,\n        \"accountReferences\": [],\n        \"children\": [\n          {\n            \"accountId\": 278462,\n            \"createDate\": \"2015-01-26T23:36:10+00:00\",\n            \"id\": 402458,\n            \"name\": \"DST_Windows-2008_R2DC_x86-64_Base_ICOv2\",\n            \"note\": \"DST Standard Windows image for deploying into VSP in ICO 2.4\",\n            \"parentId\": 402456,\n            \"publicFlag\": 1,\n            \"statusId\": 1,\n            \"summary\": \"DST_Windows-2008_R2DC_x86-64_Base with preparation for ICO 2.4\",\n            \"transactionId\": null,\n            \"userRecordId\": 146842,\n            \"blockDevices\": [\n              {\n                \"device\": \"0\",\n                \"diskImageId\": 6865056,\n                \"diskSpace\": 20926382592,\n                \"groupId\": 402458,\n                \"id\": 508130,\n                \"units\": \"B\",\n                \"diskImage\": {\n                  \"capacity\": 25,\n                  \"createDate\": \"2015-01-26T23:36:10+00:00\",\n                  \"description\": \"rrm-2k8r2dc-ico.dstdev.sl.edst.ibm.com\",\n                  \"id\": 6865056,\n                  \"modifyDate\": null,\n                  \"name\": \"rrm-2k8r2dc-ico.dstdev.sl.edst.ibm.com\",\n                  \"parentId\": null,\n                  \"storageRepositoryId\": 2330744,\n                  \"typeId\": 241,\n                  \"units\": \"GB\",\n                  \"uuid\": \"00c9bb78-9ac0-4f43-b4d8-35a6568c7db8\",\n                  \"softwareReferences\": [\n                    {\n                      \"id\": 4259392,\n                      \"softwareDescriptionId\": 727,\n                      \"softwareDescription\": {\n                        \"controlPanel\": 0,\n                        \"id\": 727,\n                        \"longDescription\": \"Nimsoft / Nimsoft Robot / 5.0\",\n                        \"manufacturer\": \"Nimsoft\",\n                        \"name\": \"Nimsoft Robot\",\n                        \"operatingSystem\": 0,\n                        \"upgradeSoftwareDescriptionId\": null,\n                        \"upgradeSwDescId\": null,\n                        \"version\": \"5.0\",\n                        \"virtualLicense\": 0,\n                        \"virtualizationPlatform\": 0,\n                        \"requiredUser\": \"administrator\"\n                      }\n                    },\n                    {\n                      \"id\": 4259394,\n                      \"softwareDescriptionId\": 829,\n                      \"softwareDescription\": {\n                        \"controlPanel\": 0,\n                        \"id\": 829,\n                        \"longDescription\": \"Microsoft / Windows 2008 FULL DC 64 bit R2 SP1 / DC 64 bit\",\n                        \"manufacturer\": \"Microsoft\",\n                        \"name\": \"Windows 2008 FULL DC 64 bit R2 SP1\",\n                        \"operatingSystem\": 1,\n                        \"referenceCode\": \"WIN_2008-DC-R2-SP1_64\",\n                        \"upgradeSoftwareDescriptionId\": null,\n                        \"upgradeSwDescId\": null,\n                        \"version\": \"DC 64 bit\",\n                        \"virtualLicense\": 0,\n                        \"virtualizationPlatform\": 0,\n                        \"requiredUser\": \"Administrator\"\n                      }\n                    }\n                  ],\n                  \"storageRepository\": {\n                    \"description\": \"SL278462 Public\",\n                    \"id\": 2330744,\n                    \"name\": \"SL278462 Public\",\n                    \"publicFlag\": 1,\n                    \"typeId\": 181\n                  }\n                }\n              },\n              {\n                \"device\": \"1\",\n                \"diskImageId\": 6865060,\n                \"groupId\": 402458,\n                \"id\": 508136,\n                \"diskImage\": {\n                  \"capacity\": 2,\n                  \"createDate\": \"2015-01-26T23:36:11+00:00\",\n                  \"description\": \"7903014-SWAP\",\n                  \"id\": 6865060,\n                  \"modifyDate\": null,\n                  \"name\": \"7903014-SWAP\",\n                  \"parentId\": null,\n                  \"storageRepositoryId\": 2330744,\n                  \"typeId\": 246,\n                  \"units\": \"GB\",\n                  \"uuid\": \"38eb1c23-0cf9-4325-b78a-95545829a36d\",\n                  \"softwareReferences\": [],\n                  \"storageRepository\": {\n                    \"description\": \"SL278462 Public\",\n                    \"id\": 2330744,\n                    \"name\": \"SL278462 Public\",\n                    \"publicFlag\": 1,\n                    \"typeId\": 181\n                  }\n                }\n              }\n            ],\n            \"parent\": null\n          },\n          {\n            \"accountId\": 278462,\n            \"createDate\": \"2015-01-26T23:36:10+00:00\",\n            \"id\": 402460,\n            \"name\": \"DST_Windows-2008_R2DC_x86-64_Base_ICOv2\",\n            \"note\": \"DST Standard Windows image for deploying into VSP in ICO 2.4\",\n            \"parentId\": 402456,\n            \"publicFlag\": 1,\n            \"statusId\": 1,\n            \"summary\": \"DST_Windows-2008_R2DC_x86-64_Base with preparation for ICO 2.4\",\n            \"transactionId\": null,\n            \"userRecordId\": 146842,\n            \"blockDevices\": [\n              {\n                \"device\": \"0\",\n                \"diskImageId\": 6865054,\n                \"diskSpace\": 20926382592,\n                \"groupId\": 402460,\n                \"id\": 508132,\n                \"units\": \"B\",\n                \"diskImage\": {\n                  \"capacity\": 25,\n                  \"createDate\": \"2015-01-26T23:36:10+00:00\",\n                  \"description\": \"rrm-2k8r2dc-ico.dstdev.sl.edst.ibm.com\",\n                  \"id\": 6865054,\n                  \"modifyDate\": null,\n                  \"name\": \"rrm-2k8r2dc-ico.dstdev.sl.edst.ibm.com\",\n                  \"parentId\": null,\n                  \"storageRepositoryId\": 2330746,\n                  \"typeId\": 241,\n                  \"units\": \"GB\",\n                  \"uuid\": \"ef20e61c-6814-47bf-8cd9-9d26f84d3789\",\n                  \"softwareReferences\": [\n                    {\n                      \"id\": 4259396,\n                      \"softwareDescriptionId\": 727,\n                      \"softwareDescription\": {\n                        \"controlPanel\": 0,\n                        \"id\": 727,\n                        \"longDescription\": \"Nimsoft / Nimsoft Robot / 5.0\",\n                        \"manufacturer\": \"Nimsoft\",\n                        \"name\": \"Nimsoft Robot\",\n                        \"operatingSystem\": 0,\n                        \"upgradeSoftwareDescriptionId\": null,\n                        \"upgradeSwDescId\": null,\n                        \"version\": \"5.0\",\n                        \"virtualLicense\": 0,\n                        \"virtualizationPlatform\": 0,\n                        \"requiredUser\": \"administrator\"\n                      }\n                    },\n                    {\n                      \"id\": 4259398,\n                      \"softwareDescriptionId\": 829,\n                      \"softwareDescription\": {\n                        \"controlPanel\": 0,\n                        \"id\": 829,\n                        \"longDescription\": \"Microsoft / Windows 2008 FULL DC 64 bit R2 SP1 / DC 64 bit\",\n                        \"manufacturer\": \"Microsoft\",\n                        \"name\": \"Windows 2008 FULL DC 64 bit R2 SP1\",\n                        \"operatingSystem\": 1,\n                        \"referenceCode\": \"WIN_2008-DC-R2-SP1_64\",\n                        \"upgradeSoftwareDescriptionId\": null,\n                        \"upgradeSwDescId\": null,\n                        \"version\": \"DC 64 bit\",\n                        \"virtualLicense\": 0,\n                        \"virtualizationPlatform\": 0,\n                        \"requiredUser\": \"Administrator\"\n                      }\n                    }\n                  ],\n                  \"storageRepository\": {\n                    \"description\": \"SL278462 Public\",\n                    \"id\": 2330746,\n                    \"name\": \"SL278462 Public\",\n                    \"publicFlag\": 1,\n                    \"typeId\": 181\n                  }\n                }\n              },\n              {\n                \"device\": \"1\",\n                \"diskImageId\": 6865058,\n                \"groupId\": 402460,\n                \"id\": 508134,\n                \"diskImage\": {\n                  \"capacity\": 2,\n                  \"createDate\": \"2015-01-26T23:36:11+00:00\",\n                  \"description\": \"7903014-SWAP\",\n                  \"id\": 6865058,\n                  \"modifyDate\": null,\n                  \"name\": \"7903014-SWAP\",\n                  \"parentId\": null,\n                  \"storageRepositoryId\": 2330746,\n                  \"typeId\": 246,\n                  \"units\": \"GB\",\n                  \"uuid\": \"c84edb86-a9ce-4932-bf2c-c3e4b2b44ae9\",\n                  \"softwareReferences\": [],\n                  \"storageRepository\": {\n                    \"description\": \"SL278462 Public\",\n                    \"id\": 2330746,\n                    \"name\": \"SL278462 Public\",\n                    \"publicFlag\": 1,\n                    \"typeId\": 181\n                  }\n                }\n              }\n            ],\n            \"parent\": null\n          }\n        ],\n        \"globalIdentifier\": \"8df677d9-02a0-43b0-9cc8-88015fcb6ad7\"\n      }\n    },\n    {\n      \"accountId\": 278462,\n      \"createDate\": \"2015-01-26T23:36:10+00:00\",\n      \"id\": 402460,\n      \"name\": \"DST_Windows-2008_R2DC_x86-64_Base_ICOv2\",\n      \"note\": \"DST Standard Windows image for deploying into VSP in ICO 2.4\",\n      \"parentId\": 402456,\n      \"publicFlag\": 1,\n      \"statusId\": 1,\n      \"summary\": \"DST_Windows-2008_R2DC_x86-64_Base with preparation for ICO 2.4\",\n      \"transactionId\": null,\n      \"userRecordId\": 146842,\n      \"blockDevices\": [\n        {\n          \"device\": \"0\",\n          \"diskImageId\": 6865054,\n          \"diskSpace\": 20926382592,\n          \"groupId\": 402460,\n          \"id\": 508132,\n          \"units\": \"B\",\n          \"diskImage\": {\n            \"capacity\": 25,\n            \"createDate\": \"2015-01-26T23:36:10+00:00\",\n            \"description\": \"rrm-2k8r2dc-ico.dstdev.sl.edst.ibm.com\",\n            \"id\": 6865054,\n            \"modifyDate\": null,\n            \"name\": \"rrm-2k8r2dc-ico.dstdev.sl.edst.ibm.com\",\n            \"parentId\": null,\n            \"storageRepositoryId\": 2330746,\n            \"typeId\": 241,\n            \"units\": \"GB\",\n            \"uuid\": \"ef20e61c-6814-47bf-8cd9-9d26f84d3789\",\n            \"softwareReferences\": [\n              {\n                \"id\": 4259396,\n                \"softwareDescriptionId\": 727,\n                \"softwareDescription\": {\n                  \"controlPanel\": 0,\n                  \"id\": 727,\n                  \"longDescription\": \"Nimsoft / Nimsoft Robot / 5.0\",\n                  \"manufacturer\": \"Nimsoft\",\n                  \"name\": \"Nimsoft Robot\",\n                  \"operatingSystem\": 0,\n                  \"upgradeSoftwareDescriptionId\": null,\n                  \"upgradeSwDescId\": null,\n                  \"version\": \"5.0\",\n                  \"virtualLicense\": 0,\n                  \"virtualizationPlatform\": 0,\n                  \"requiredUser\": \"administrator\"\n                }\n              },\n              {\n                \"id\": 4259398,\n                \"softwareDescriptionId\": 829,\n                \"softwareDescription\": {\n                  \"controlPanel\": 0,\n                  \"id\": 829,\n                  \"longDescription\": \"Microsoft / Windows 2008 FULL DC 64 bit R2 SP1 / DC 64 bit\",\n                  \"manufacturer\": \"Microsoft\",\n                  \"name\": \"Windows 2008 FULL DC 64 bit R2 SP1\",\n                  \"operatingSystem\": 1,\n                  \"referenceCode\": \"WIN_2008-DC-R2-SP1_64\",\n                  \"upgradeSoftwareDescriptionId\": null,\n                  \"upgradeSwDescId\": null,\n                  \"version\": \"DC 64 bit\",\n                  \"virtualLicense\": 0,\n                  \"virtualizationPlatform\": 0,\n                  \"requiredUser\": \"Administrator\"\n                }\n              }\n            ],\n            \"storageRepository\": {\n              \"description\": \"SL278462 Public\",\n              \"id\": 2330746,\n              \"name\": \"SL278462 Public\",\n              \"publicFlag\": 1,\n              \"typeId\": 181\n            }\n          }\n        },\n        {\n          \"device\": \"1\",\n          \"diskImageId\": 6865058,\n          \"groupId\": 402460,\n          \"id\": 508134,\n          \"diskImage\": {\n            \"capacity\": 2,\n            \"createDate\": \"2015-01-26T23:36:11+00:00\",\n            \"description\": \"7903014-SWAP\",\n            \"id\": 6865058,\n            \"modifyDate\": null,\n            \"name\": \"7903014-SWAP\",\n            \"parentId\": null,\n            \"storageRepositoryId\": 2330746,\n            \"typeId\": 246,\n            \"units\": \"GB\",\n            \"uuid\": \"c84edb86-a9ce-4932-bf2c-c3e4b2b44ae9\",\n            \"softwareReferences\": [],\n            \"storageRepository\": {\n              \"description\": \"SL278462 Public\",\n              \"id\": 2330746,\n              \"name\": \"SL278462 Public\",\n              \"publicFlag\": 1,\n              \"typeId\": 181\n            }\n          }\n        }\n      ],\n      \"parent\": {\n        \"accountId\": 278462,\n        \"createDate\": \"2015-01-26T23:36:05+00:00\",\n        \"id\": 402456,\n        \"name\": \"DST_Windows-2008_R2DC_x86-64_Base_ICOv2\",\n        \"note\": \"DST Standard Windows image for deploying into VSP in ICO 2.4\",\n        \"parentId\": null,\n        \"publicFlag\": 1,\n        \"statusId\": 1,\n        \"summary\": \"DST_Windows-2008_R2DC_x86-64_Base with preparation for ICO 2.4\",\n        \"transactionId\": null,\n        \"userRecordId\": 146842,\n        \"accountReferences\": [],\n        \"children\": [\n          {\n            \"accountId\": 278462,\n            \"createDate\": \"2015-01-26T23:36:10+00:00\",\n            \"id\": 402458,\n            \"name\": \"DST_Windows-2008_R2DC_x86-64_Base_ICOv2\",\n            \"note\": \"DST Standard Windows image for deploying into VSP in ICO 2.4\",\n            \"parentId\": 402456,\n            \"publicFlag\": 1,\n            \"statusId\": 1,\n            \"summary\": \"DST_Windows-2008_R2DC_x86-64_Base with preparation for ICO 2.4\",\n            \"transactionId\": null,\n            \"userRecordId\": 146842,\n            \"blockDevices\": [\n              {\n                \"device\": \"0\",\n                \"diskImageId\": 6865056,\n                \"diskSpace\": 20926382592,\n                \"groupId\": 402458,\n                \"id\": 508130,\n                \"units\": \"B\",\n                \"diskImage\": {\n                  \"capacity\": 25,\n                  \"createDate\": \"2015-01-26T23:36:10+00:00\",\n                  \"description\": \"rrm-2k8r2dc-ico.dstdev.sl.edst.ibm.com\",\n                  \"id\": 6865056,\n                  \"modifyDate\": null,\n                  \"name\": \"rrm-2k8r2dc-ico.dstdev.sl.edst.ibm.com\",\n                  \"parentId\": null,\n                  \"storageRepositoryId\": 2330744,\n                  \"typeId\": 241,\n                  \"units\": \"GB\",\n                  \"uuid\": \"00c9bb78-9ac0-4f43-b4d8-35a6568c7db8\",\n                  \"softwareReferences\": [\n                    {\n                      \"id\": 4259392,\n                      \"softwareDescriptionId\": 727,\n                      \"softwareDescription\": {\n                        \"controlPanel\": 0,\n                        \"id\": 727,\n                        \"longDescription\": \"Nimsoft / Nimsoft Robot / 5.0\",\n                        \"manufacturer\": \"Nimsoft\",\n                        \"name\": \"Nimsoft Robot\",\n                        \"operatingSystem\": 0,\n                        \"upgradeSoftwareDescriptionId\": null,\n                        \"upgradeSwDescId\": null,\n                        \"version\": \"5.0\",\n                        \"virtualLicense\": 0,\n                        \"virtualizationPlatform\": 0,\n                        \"requiredUser\": \"administrator\"\n                      }\n                    },\n                    {\n                      \"id\": 4259394,\n                      \"softwareDescriptionId\": 829,\n                      \"softwareDescription\": {\n                        \"controlPanel\": 0,\n                        \"id\": 829,\n                        \"longDescription\": \"Microsoft / Windows 2008 FULL DC 64 bit R2 SP1 / DC 64 bit\",\n                        \"manufacturer\": \"Microsoft\",\n                        \"name\": \"Windows 2008 FULL DC 64 bit R2 SP1\",\n                        \"operatingSystem\": 1,\n                        \"referenceCode\": \"WIN_2008-DC-R2-SP1_64\",\n                        \"upgradeSoftwareDescriptionId\": null,\n                        \"upgradeSwDescId\": null,\n                        \"version\": \"DC 64 bit\",\n                        \"virtualLicense\": 0,\n                        \"virtualizationPlatform\": 0,\n                        \"requiredUser\": \"Administrator\"\n                      }\n                    }\n                  ],\n                  \"storageRepository\": {\n                    \"description\": \"SL278462 Public\",\n                    \"id\": 2330744,\n                    \"name\": \"SL278462 Public\",\n                    \"publicFlag\": 1,\n                    \"typeId\": 181\n                  }\n                }\n              },\n              {\n                \"device\": \"1\",\n                \"diskImageId\": 6865060,\n                \"groupId\": 402458,\n                \"id\": 508136,\n                \"diskImage\": {\n                  \"capacity\": 2,\n                  \"createDate\": \"2015-01-26T23:36:11+00:00\",\n                  \"description\": \"7903014-SWAP\",\n                  \"id\": 6865060,\n                  \"modifyDate\": null,\n                  \"name\": \"7903014-SWAP\",\n                  \"parentId\": null,\n                  \"storageRepositoryId\": 2330744,\n                  \"typeId\": 246,\n                  \"units\": \"GB\",\n                  \"uuid\": \"38eb1c23-0cf9-4325-b78a-95545829a36d\",\n                  \"softwareReferences\": [],\n                  \"storageRepository\": {\n                    \"description\": \"SL278462 Public\",\n                    \"id\": 2330744,\n                    \"name\": \"SL278462 Public\",\n                    \"publicFlag\": 1,\n                    \"typeId\": 181\n                  }\n                }\n              }\n            ],\n            \"parent\": null\n          },\n          {\n            \"accountId\": 278462,\n            \"createDate\": \"2015-01-26T23:36:10+00:00\",\n            \"id\": 402460,\n            \"name\": \"DST_Windows-2008_R2DC_x86-64_Base_ICOv2\",\n            \"note\": \"DST Standard Windows image for deploying into VSP in ICO 2.4\",\n            \"parentId\": 402456,\n            \"publicFlag\": 1,\n            \"statusId\": 1,\n            \"summary\": \"DST_Windows-2008_R2DC_x86-64_Base with preparation for ICO 2.4\",\n            \"transactionId\": null,\n            \"userRecordId\": 146842,\n            \"blockDevices\": [\n              {\n                \"device\": \"0\",\n                \"diskImageId\": 6865054,\n                \"diskSpace\": 20926382592,\n                \"groupId\": 402460,\n                \"id\": 508132,\n                \"units\": \"B\",\n                \"diskImage\": {\n                  \"capacity\": 25,\n                  \"createDate\": \"2015-01-26T23:36:10+00:00\",\n                  \"description\": \"rrm-2k8r2dc-ico.dstdev.sl.edst.ibm.com\",\n                  \"id\": 6865054,\n                  \"modifyDate\": null,\n                  \"name\": \"rrm-2k8r2dc-ico.dstdev.sl.edst.ibm.com\",\n                  \"parentId\": null,\n                  \"storageRepositoryId\": 2330746,\n                  \"typeId\": 241,\n                  \"units\": \"GB\",\n                  \"uuid\": \"ef20e61c-6814-47bf-8cd9-9d26f84d3789\",\n                  \"softwareReferences\": [\n                    {\n                      \"id\": 4259396,\n                      \"softwareDescriptionId\": 727,\n                      \"softwareDescription\": {\n                        \"controlPanel\": 0,\n                        \"id\": 727,\n                        \"longDescription\": \"Nimsoft / Nimsoft Robot / 5.0\",\n                        \"manufacturer\": \"Nimsoft\",\n                        \"name\": \"Nimsoft Robot\",\n                        \"operatingSystem\": 0,\n                        \"upgradeSoftwareDescriptionId\": null,\n                        \"upgradeSwDescId\": null,\n                        \"version\": \"5.0\",\n                        \"virtualLicense\": 0,\n                        \"virtualizationPlatform\": 0,\n                        \"requiredUser\": \"administrator\"\n                      }\n                    },\n                    {\n                      \"id\": 4259398,\n                      \"softwareDescriptionId\": 829,\n                      \"softwareDescription\": {\n                        \"controlPanel\": 0,\n                        \"id\": 829,\n                        \"longDescription\": \"Microsoft / Windows 2008 FULL DC 64 bit R2 SP1 / DC 64 bit\",\n                        \"manufacturer\": \"Microsoft\",\n                        \"name\": \"Windows 2008 FULL DC 64 bit R2 SP1\",\n                        \"operatingSystem\": 1,\n                        \"referenceCode\": \"WIN_2008-DC-R2-SP1_64\",\n                        \"upgradeSoftwareDescriptionId\": null,\n                        \"upgradeSwDescId\": null,\n                        \"version\": \"DC 64 bit\",\n                        \"virtualLicense\": 0,\n                        \"virtualizationPlatform\": 0,\n                        \"requiredUser\": \"Administrator\"\n                      }\n                    }\n                  ],\n                  \"storageRepository\": {\n                    \"description\": \"SL278462 Public\",\n                    \"id\": 2330746,\n                    \"name\": \"SL278462 Public\",\n                    \"publicFlag\": 1,\n                    \"typeId\": 181\n                  }\n                }\n              },\n              {\n                \"device\": \"1\",\n                \"diskImageId\": 6865058,\n                \"groupId\": 402460,\n                \"id\": 508134,\n                \"diskImage\": {\n                  \"capacity\": 2,\n                  \"createDate\": \"2015-01-26T23:36:11+00:00\",\n                  \"description\": \"7903014-SWAP\",\n                  \"id\": 6865058,\n                  \"modifyDate\": null,\n                  \"name\": \"7903014-SWAP\",\n                  \"parentId\": null,\n                  \"storageRepositoryId\": 2330746,\n                  \"typeId\": 246,\n                  \"units\": \"GB\",\n                  \"uuid\": \"c84edb86-a9ce-4932-bf2c-c3e4b2b44ae9\",\n                  \"softwareReferences\": [],\n                  \"storageRepository\": {\n                    \"description\": \"SL278462 Public\",\n                    \"id\": 2330746,\n                    \"name\": \"SL278462 Public\",\n                    \"publicFlag\": 1,\n                    \"typeId\": 181\n                  }\n                }\n              }\n            ],\n            \"parent\": null\n          }\n        ],\n        \"globalIdentifier\": \"8df677d9-02a0-43b0-9cc8-88015fcb6ad7\"\n      }\n    }\n  ],\n  \"globalIdentifier\": \"8df677d9-02a0-43b0-9cc8-88015fcb6ad7\"\n}"
  },
  {
    "path": "providers/softlayer/src/test/resources/virtual_guest_block_device_template_group_get_public_images.json",
    "content": "[\n{\n  \"accountId\": 208938,\n  \"createDate\": \"2013-07-31T11:02:09+01:00\",\n  \"id\": 33352,\n  \"name\": \"25G CentOS 6 32-bit\",\n  \"parentId\": 10616,\n  \"statusId\": 1,\n  \"transactionId\": null,\n  \"userRecordId\": null,\n  \"accountReferences\": [],\n  \"blockDevices\": [\n    {\n      \"device\": \"0\",\n      \"diskImageId\": 1692629,\n      \"diskSpace\": 2597196288,\n      \"groupId\": 33352,\n      \"id\": 42678,\n      \"units\": \"B\",\n      \"diskImage\": {\n        \"capacity\": 25,\n        \"createDate\": \"2013-07-31T11:02:09+01:00\",\n        \"description\": \"25G CentOS 6 32-bit\",\n        \"id\": 1692629,\n        \"modifyDate\": null,\n        \"name\": \"25G CentOS 6 32-bit\",\n        \"parentId\": null,\n        \"storageRepositoryId\": 863078,\n        \"typeId\": 241,\n        \"units\": \"GB\",\n        \"uuid\": \"3764c062-43d7-4488-8119-0cf847c3e4db\",\n        \"softwareReferences\": [\n          {\n            \"id\": 1227351,\n            \"softwareDescriptionId\": 885,\n            \"softwareDescription\": {\n              \"controlPanel\": 0,\n              \"id\": 885,\n              \"longDescription\": \"CentOS / CentOS / 6.0-32 Minimal for CCI\",\n              \"manufacturer\": \"CentOS\",\n              \"name\": \"CentOS\",\n              \"operatingSystem\": 1,\n              \"referenceCode\": \"CENTOS_6_32\",\n              \"upgradeSoftwareDescriptionId\": null,\n              \"upgradeSwDescId\": null,\n              \"version\": \"6.0-32 Minimal for CCI\",\n              \"virtualLicense\": 0,\n              \"virtualizationPlatform\": 0,\n              \"requiredUser\": \"root\"\n            }\n          }\n        ],\n        \"storageRepository\": {\n          \"description\": \"SL208938 Public\",\n          \"id\": 863078,\n          \"name\": \"SL208938 Public\",\n          \"publicFlag\": 1,\n          \"typeId\": 181\n        }\n      }\n    },\n    {\n      \"device\": \"1\",\n      \"diskImageId\": 1692630,\n      \"groupId\": 33352,\n      \"id\": 42679,\n      \"diskImage\": {\n        \"capacity\": 2,\n        \"createDate\": \"2013-07-31T11:02:09+01:00\",\n        \"description\": \"10617-SWAP\",\n        \"id\": 1692630,\n        \"modifyDate\": null,\n        \"name\": \"10617-SWAP\",\n        \"parentId\": null,\n        \"storageRepositoryId\": 863078,\n        \"typeId\": 246,\n        \"units\": \"GB\",\n        \"uuid\": \"ae3d12c3-f624-4c3a-80f5-ceeea2259c16\",\n        \"softwareReferences\": [],\n        \"storageRepository\": {\n          \"description\": \"SL208938 Public\",\n          \"id\": 863078,\n          \"name\": \"SL208938 Public\",\n          \"publicFlag\": 1,\n          \"typeId\": 181\n        }\n      }\n    }\n  ],\n  \"storageRepository\": {\n    \"description\": \"SL208938 Public\",\n    \"id\": 863078,\n    \"name\": \"SL208938 Public\",\n    \"publicFlag\": 1,\n    \"typeId\": 181\n  }\n}\n]"
  },
  {
    "path": "providers/softlayer/src/test/resources/virtual_guest_create.json",
    "content": "{\"parameters\":[{\"hostname\":\"host1\",\"domain\":\"example.com\",\"startCpus\":1,\"maxMemory\":1024,\"hourlyBillingFlag\":false,\"localDiskFlag\":true,\"dedicatedAccountHostOnlyFlag\":false,\"privateNetworkOnlyFlag\":false,\"operatingSystemReferenceCode\":\"UBUNTU_LATEST\",\"datacenter\":{\"name\":\"test\"}}]}"
  },
  {
    "path": "providers/softlayer/src/test/resources/virtual_guest_create_response.json",
    "content": "{ \n    \"accountId\": 232298, \n    \"createDate\": \"2012-11-30T16:28:17-06:00\", \n    \"dedicatedAccountHostOnlyFlag\": false, \n    \"domain\": \"example.com\", \n    \"hostname\": \"host1\", \n    \"id\": 1301396, \n    \"lastPowerStateId\": null, \n    \"lastVerifiedDate\": null, \n    \"maxCpu\": 1, \n    \"maxCpuUnits\": \"CORE\", \n    \"maxMemory\": 1024, \n    \"metricPollDate\": null, \n    \"modifyDate\": null, \n    \"privateNetworkOnlyFlag\": false, \n    \"startCpus\": 1, \n    \"statusId\": 1001, \n    \"globalIdentifier\": \"2d203774-0ee1-49f5-9599-6ef67358dd31\" \n} "
  },
  {
    "path": "providers/softlayer/src/test/resources/virtual_guest_get.json",
    "content": "{\n    \"primaryIpAddress\": \"174.37.252.118\",\n    \"primaryBackendIpAddress\": \"10.32.23.74\",\n    \"globalIdentifier\": \"da2b9f87-2319-4a12-91a5-f7f732061dcc\",\n    \"uuid\": \"92102aff-93c9-05f1-b3f2-50787e865344\",\n    \"lastPowerStateId\": null,\n    \"id\": 3001812,\n    \"hostname\": \"my\",\n    \"fullyQualifiedDomainName\": \"my.test.com\",\n    \"domain\": \"test.com\",\n    \"dedicatedAccountHostOnlyFlag\": false,\n    \"createDate\": \"2013-07-26T14:08:21.552-07:00\",\n    \"accountId\": 278184,\n    \"lastVerifiedDate\": null,\n    \"maxCpu\": 1,\n    \"maxCpuUnits\": \"CORE\",\n    \"maxMemory\": 1024,\n    \"metricPollDate\": null,\n    \"modifyDate\": \"2013-07-26T14:10:21.552-07:00\",\n    \"startCpus\": 1,\n    \"statusId\": 1001\n}"
  },
  {
    "path": "providers/softlayer/src/test/resources/virtual_guest_get_filtered.json",
    "content": "{\n    \"primaryBackendNetworkComponent\": {\n        \"networkId\" : 123456,\n        \"networkVlan\": {\n            \"id\": 1234,\n            \"name\": \"abc\"\n        }\n    },\n    \"id\": 3001812\n}"
  },
  {
    "path": "providers/softlayer/src/test/resources/virtual_guest_set_notes.json",
    "content": "{\"parameters\":[{\"notes\":\"some notes\"}]}"
  },
  {
    "path": "providers/softlayer/src/test/resources/virtual_guest_set_tags.json",
    "content": "{\"parameters\":[\"test1,test2,test3\"]}"
  },
  {
    "path": "providers/softlayer/src/test/resources/virtual_guest_set_tags_response.json",
    "content": "\"true\""
  },
  {
    "path": "providers/ultradns-ws/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.ultradns.ws.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "providers/ultradns-ws/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.provider</groupId>\n  <artifactId>ultradns-ws</artifactId>\n  <name>jclouds ultradns-ws provider</name>\n  <description>jclouds components to access UltraDNS Web Services API</description>\n\n  <properties>\n    <test.ultradns-ws.endpoint>https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01</test.ultradns-ws.endpoint>\n    <test.ultradns-ws.api-version>v01</test.ultradns-ws.api-version>\n    <test.ultradns-ws.build-version />\n    <test.ultradns-ws.identity />\n    <test.ultradns-ws.credential />\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>jar</type>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-slf4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>ch.qos.logback</groupId>\n      <artifactId>logback-classic</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <!-- to prevent live tests from clashing with eachother -->\n                  <threadCount>1</threadCount>\n                  <systemPropertyVariables>\n                    <test.ultradns-ws.endpoint>${test.ultradns-ws.endpoint}</test.ultradns-ws.endpoint>\n                    <test.ultradns-ws.api-version>${test.ultradns-ws.api-version}</test.ultradns-ws.api-version>\n                    <test.ultradns-ws.build-version>${test.ultradns-ws.build-version}</test.ultradns-ws.build-version>\n                    <test.ultradns-ws.identity>${test.ultradns-ws.identity}</test.ultradns-ws.identity>\n                    <test.ultradns-ws.credential>${test.ultradns-ws.credential}</test.ultradns-ws.credential>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/UltraDNSWSApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws;\n\nimport java.io.Closeable;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.POST;\n\nimport org.jclouds.rest.annotations.Delegate;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.VirtualHost;\nimport org.jclouds.rest.annotations.XMLResponseParser;\nimport org.jclouds.ultradns.ws.domain.IdAndName;\nimport org.jclouds.ultradns.ws.features.DirectionalGroupApi;\nimport org.jclouds.ultradns.ws.features.DirectionalPoolApi;\nimport org.jclouds.ultradns.ws.features.ResourceRecordApi;\nimport org.jclouds.ultradns.ws.features.RoundRobinPoolApi;\nimport org.jclouds.ultradns.ws.features.TaskApi;\nimport org.jclouds.ultradns.ws.features.TrafficControllerPoolApi;\nimport org.jclouds.ultradns.ws.features.ZoneApi;\nimport org.jclouds.ultradns.ws.filters.SOAPWrapWithPasswordAuth;\nimport org.jclouds.ultradns.ws.xml.AccountHandler;\nimport org.jclouds.ultradns.ws.xml.RegionListHandler;\n\nimport com.google.common.collect.Multimap;\n\n/**\n * Provides access to Neustar UltraDNS via the SOAP API\n * <p/>\n * \n * @see <a href=\"https://www.ultradns.net/api/NUS_API_XML_SOAP.pdf\" />\n */\n@RequestFilters(SOAPWrapWithPasswordAuth.class)\n@VirtualHost\npublic interface UltraDNSWSApi extends Closeable {\n   /**\n    * Returns the account of the current user.\n    */\n   @Named(\"getAccountsListOfUser\")\n   @POST\n   @XMLResponseParser(AccountHandler.class)\n   @Payload(\"<v01:getAccountsListOfUser/>\")\n   IdAndName getCurrentAccount();\n\n   /**\n    * Lists the directional regions available in the account.\n    */\n   @Named(\"getAvailableRegions\")\n   @POST\n   @XMLResponseParser(RegionListHandler.class)\n   @Payload(\"<v01:getAvailableRegions/>\")\n   Multimap<IdAndName, String> getRegionsByIdAndName();\n\n   /**\n    * Provides access to Zone features.\n    */\n   @Delegate\n   ZoneApi getZoneApi();\n\n   /**\n    * Provides access to Resource Record features.\n    * \n    * @param zoneName\n    *           zoneName including a trailing dot\n    */\n   @Delegate\n   ResourceRecordApi getResourceRecordApiForZone(@PayloadParam(\"zoneName\") String zoneName);\n\n   /**\n    * Provides access to Round Robin Pool features.\n    * \n    * @param zoneName\n    *           zoneName including a trailing dot\n    */\n   @Delegate\n   RoundRobinPoolApi getRoundRobinPoolApiForZone(@PayloadParam(\"zoneName\") String zoneName);\n\n   /**\n    * Provides access to Traffic Controller Pool features.\n    * \n    * @param zoneName\n    *           zoneName including a trailing dot\n    */\n   @Delegate\n   TrafficControllerPoolApi getTrafficControllerPoolApiForZone(@PayloadParam(\"zoneName\") String zoneName);\n\n   /**\n    * Provides access to Account-Level Directional Group features.\n    * \n    * @param accountId\n    *           id of the account where the groups live.\n    */\n   @Delegate\n   DirectionalGroupApi getDirectionalGroupApiForAccount(@PayloadParam(\"accountId\") String accountId);\n\n   /**\n    * Provides access to Directional Pool features.\n    * \n    * @param zoneName\n    *           zoneName including a trailing dot\n    */\n   @Delegate\n   DirectionalPoolApi getDirectionalPoolApiForZone(@PayloadParam(\"zoneName\") String zoneName);\n\n   /**\n    * Provides access to Task features.\n    */\n   @Delegate\n   TaskApi getTaskApi();\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/UltraDNSWSApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.rest.internal.BaseHttpApiMetadata;\nimport org.jclouds.ultradns.ws.config.UltraDNSWSHttpApiModule;\n\n/**\n * Implementation of {@link ApiMetadata} for Neustar's UltraDNSWS api.\n */\npublic class UltraDNSWSApiMetadata extends BaseHttpApiMetadata<UltraDNSWSApi> {\n\n   @Override\n   public Builder toBuilder() {\n      return new Builder().fromApiMetadata(this);\n   }\n\n   public UltraDNSWSApiMetadata() {\n      this(new Builder());\n   }\n\n   protected UltraDNSWSApiMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = BaseHttpApiMetadata.defaultProperties();\n      return properties;\n   }\n\n   public static class Builder extends BaseHttpApiMetadata.Builder<UltraDNSWSApi, Builder> {\n\n      protected Builder() {\n         id(\"ultradns-ws\")\n         .name(\"Neustar UltraDNS WS Api\")\n         .identityName(\"Username\")\n         .credentialName(\"Password\")\n         .version(\"v01\")\n         .documentation(URI.create(\"https://portal.ultradns.com/static/docs/NUS_API_XML_SOAP.pdf\"))\n         .defaultEndpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .defaultProperties(UltraDNSWSApiMetadata.defaultProperties())\n         .defaultModule(UltraDNSWSHttpApiModule.class);\n      }\n\n      @Override\n      public UltraDNSWSApiMetadata build() {\n         return new UltraDNSWSApiMetadata(this);\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/UltraDNSWSError.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws;\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static java.lang.String.format;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.Optional;\n\npublic final class UltraDNSWSError {\n   public static UltraDNSWSError fromCodeAndDescription(int code, Optional<String> description) {\n      return new UltraDNSWSError(code, description);\n   }\n\n   private final int code;\n   private final Optional<String> description;\n\n   private UltraDNSWSError(int code, Optional<String> description) {\n      this.code = code;\n      this.description = checkNotNull(description, \"description for code %s\", code);\n   }\n\n   /**\n    * The error code. ex {@code 1801}\n    */\n   public int getCode() {\n      return code;\n   }\n\n   /**\n    * The description of the error. ex {@code Zone does not exist in the system.}\n    */\n   public Optional<String> getDescription() {\n      return description;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(code, description);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      UltraDNSWSError that = UltraDNSWSError.class.cast(obj);\n      return equal(this.code, that.code) && equal(this.description, that.description);\n   }\n\n   @Override\n   public String toString() {\n      return description.isPresent() ? format(\"Error %s: %s\", code, description.get()) : format(\"Error %s\", code);\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/UltraDNSWSExceptions.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws;\n\n/**\n * Exceptions likely to be encountered when using {@link UltraDNSWSApi}\n */\npublic final class UltraDNSWSExceptions {\n   private UltraDNSWSExceptions() {\n      throw new AssertionError(\"intentionally not implemented\");\n   }\n\n   /**\n    * The Zone or other resource already exists\n    */\n   public static class ResourceAlreadyExistsException extends IllegalStateException {\n      private static final long serialVersionUID = 1L;\n\n      public ResourceAlreadyExistsException(String message, Throwable cause) {\n         super(message, cause);\n      }\n   }\n   \n   /**\n    * Error 7021: Geolocation/Source IP overlap(s) found: Region: Utah (Group: US )\n    */\n   public static class DirectionalGroupOverlapException extends IllegalStateException {\n      private static final long serialVersionUID = 1L;\n\n      public DirectionalGroupOverlapException(String message, Throwable cause) {\n         super(message, cause);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/UltraDNSWSProviderMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws;\n\nimport java.net.URI;\nimport java.util.Properties;\n\nimport org.jclouds.providers.ProviderMetadata;\nimport org.jclouds.providers.internal.BaseProviderMetadata;\n\nimport com.google.auto.service.AutoService;\n\n/**\n * Implementation of {@link ProviderMetadata} for Neustar UltraDNS.\n */\n@AutoService(ProviderMetadata.class)\npublic class UltraDNSWSProviderMetadata extends BaseProviderMetadata {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   @Override\n   public Builder toBuilder() {\n      return builder().fromProviderMetadata(this);\n   }\n\n   public UltraDNSWSProviderMetadata() {\n      super(builder());\n   }\n\n   public UltraDNSWSProviderMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static Properties defaultProperties() {\n      Properties properties = new Properties();\n      return properties;\n   }\n\n   public static class Builder extends BaseProviderMetadata.Builder {\n\n      protected Builder() {\n         id(\"ultradns-ws\")\n         .name(\"Neustar UltraDNS WS\")\n         .apiMetadata(new UltraDNSWSApiMetadata())\n         .homepage(URI.create(\"http://www.neustar.biz/enterprise/dns-services/what-is-external-dns\"))\n         .console(URI.create(\"https://portal.ultradns.com\"))\n         .iso3166Codes(\"US-CA\", \"US-VA\") // TODO\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .defaultProperties(UltraDNSWSProviderMetadata.defaultProperties());\n      }\n\n      @Override\n      public UltraDNSWSProviderMetadata build() {\n         return new UltraDNSWSProviderMetadata(this);\n      }\n\n      @Override\n      public Builder fromProviderMetadata(ProviderMetadata in) {\n         super.fromProviderMetadata(in);\n         return this;\n      }\n\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/UltraDNSWSResponseException.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws;\n\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.javax.annotation.Nullable;\n\n/**\n * @see UltraDNSWSError\n */\npublic class UltraDNSWSResponseException extends HttpResponseException {\n\n   private static final long serialVersionUID = 5493782874839736777L;\n\n   private final transient UltraDNSWSError error;\n\n   public UltraDNSWSResponseException(HttpCommand command, HttpResponse response, UltraDNSWSError error) {\n      super(error.toString(), command, response);\n      this.error = error;\n   }\n\n   @Nullable\n   public UltraDNSWSError getError() {\n      return error;\n   }\n\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/binders/DirectionalGroupCoordinatesToXML.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.binders;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.UriTemplates;\nimport org.jclouds.rest.Binder;\nimport org.jclouds.ultradns.ws.domain.DirectionalGroupCoordinates;\n\nimport com.google.common.collect.ImmutableMap;\n\npublic class DirectionalGroupCoordinatesToXML implements Binder {\n   private static final String TEMPLATE = \"<v01:getDirectionalDNSRecordsForGroup><groupName>{groupName}</groupName><hostName>{recordName}</hostName><zoneName>{zoneName}</zoneName><poolRecordType>{recordType}</poolRecordType></v01:getDirectionalDNSRecordsForGroup>\";\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object in) {\n      DirectionalGroupCoordinates group = DirectionalGroupCoordinates.class.cast(in);\n      ImmutableMap<String, Object> variables = ImmutableMap.<String, Object> builder()\n                                                           .put(\"zoneName\", group.getZoneName())\n                                                           .put(\"recordName\", group.getRecordName())\n                                                           .put(\"recordType\", group.getRecordType())\n                                                           .put(\"groupName\", group.getGroupName()).build();\n      return (R) request.toBuilder().payload(UriTemplates.expand(TEMPLATE, variables)).build();\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/binders/DirectionalRecordAndGeoGroupToXML.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.binders;\n\nimport static java.lang.String.format;\n\nimport java.util.Collection;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.MapBinder;\nimport org.jclouds.ultradns.ws.domain.DirectionalGroup;\nimport org.jclouds.ultradns.ws.domain.DirectionalPoolRecord;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Joiner;\n\npublic class DirectionalRecordAndGeoGroupToXML implements MapBinder {\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      DirectionalPoolRecord record = DirectionalPoolRecord.class.cast(postParams.get(\"record\"));\n      DirectionalGroup group = DirectionalGroup.class.cast(postParams.get(\"group\"));\n      String xml = toXML(postParams.get(\"poolId\"), record, group, postParams.get(\"dirPoolRecordId\"),\n            postParams.get(\"groupId\"));\n      return (R) request.toBuilder().payload(xml).build();\n   }\n\n   private static final String ADD_TEMPLATE = \"<v01:addDirectionalPoolRecord><transactionID />%s%s%s</AddDirectionalRecordData></v01:addDirectionalPoolRecord>\";\n   private static final String UPDATE_TEMPLATE = \"<v01:updateDirectionalPoolRecord><transactionID /><UpdateDirectionalRecordData directionalPoolRecordId=\\\"%s\\\">%s%s</UpdateDirectionalRecordData></v01:updateDirectionalPoolRecord>\";\n   private static final String NEWGROUP_TEMPLATE = \"<GeolocationGroupData><GroupData groupingType=\\\"DEFINE_NEW_GROUP\\\" />%s</GeolocationGroupData>\";\n   private static final String EXISTINGGROUP_TEMPLATE = \"<GeolocationGroupData><GroupData groupingType=\\\"ASSIGN_EXISTING_GROUP\\\" assignExistingGroupId=\\\"%s\\\" />%s</GeolocationGroupData>\";\n\n   @VisibleForTesting\n   static String toXML(Object poolId, DirectionalPoolRecord record, DirectionalGroup group, Object recordId,\n         Object groupId) {\n      if (poolId == null) {\n         if (group != null)\n            return format(UPDATE_TEMPLATE, recordId, updateRecord(record), geo(group));\n         return format(UPDATE_TEMPLATE, recordId, updateRecord(record), \"\");\n      }\n      if (group == null && groupId == null) {\n         return format(\n               ADD_TEMPLATE,\n               format(\"<AddDirectionalRecordData directionalPoolId=\\\"%s\\\" createAllNonConfiguredGrp=\\\"true\\\">\", poolId),\n               createRecord(record), \"\");\n      }\n      String addRecordToPool = format(\"<AddDirectionalRecordData directionalPoolId=\\\"%s\\\">\", poolId);\n      if (groupId != null) {\n         return format(ADD_TEMPLATE, addRecordToPool, createRecord(record), format(EXISTINGGROUP_TEMPLATE, groupId, \"\"));\n      }\n      return format(ADD_TEMPLATE, addRecordToPool, createRecord(record), format(NEWGROUP_TEMPLATE, geo(group)));\n   }\n\n   private static String createRecord(DirectionalPoolRecord record) {\n      StringBuilder recordConfig = new StringBuilder();\n      recordConfig.append(\"<DirectionalRecordConfiguration recordType=\\\"\").append(record.getType()).append('\"');\n      recordConfig.append(\" TTL=\\\"\").append(record.getTTL()).append('\"');\n      recordConfig.append(\" noResponseRecord=\\\"\").append(record.isNoResponseRecord()).append(\"\\\" >\");\n      recordConfig.append(values(record));\n      recordConfig.append(\"</DirectionalRecordConfiguration>\");\n      return recordConfig.toString();\n   }\n\n   /**\n    * don't pass type or is no response when updating\n    */\n   private static String updateRecord(DirectionalPoolRecord record) {\n      return format(\"<DirectionalRecordConfiguration TTL=\\\"%s\\\" >%s</DirectionalRecordConfiguration>\", record.getTTL(),\n            values(record));\n   }\n\n   private static String values(DirectionalPoolRecord record) {\n      StringBuilder values = new StringBuilder(\"<InfoValues\");\n      for (int i = 0; i < record.getRData().size(); i++) {\n         values.append(' ').append(\"Info\").append(i + 1).append(\"Value=\").append('\"').append(record.getRData().get(i))\n               .append('\"');\n      }\n      values.append(\" />\");\n      return values.toString();\n   }\n\n   private static String geo(DirectionalGroup group) {\n      StringBuilder groupData = new StringBuilder();\n      groupData.append(\"<GeolocationGroupDetails groupName=\\\"\").append(group.getName()).append('\"');\n      if (group.getDescription().isPresent())\n         groupData.append(\" description=\\\"\").append(group.getDescription().get()).append('\"');\n      groupData.append(\" >\");\n      for (Entry<String, Collection<String>> region : group.asMap().entrySet()) {\n         groupData.append(\"<GeolocationGroupDefinitionData regionName=\\\"\").append(region.getKey()).append('\"');\n         groupData.append(\" territoryNames=\\\"\").append(Joiner.on(';').join(region.getValue())).append(\"\\\" />\");\n      }\n      groupData.append(\"</GeolocationGroupDetails>\");\n      return groupData.toString();\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      throw new UnsupportedOperationException(\"use map form\");\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/binders/UpdateDirectionalDNSGroupToXML.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.binders;\n\nimport static java.lang.String.format;\n\nimport java.util.Collection;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.MapBinder;\nimport org.jclouds.ultradns.ws.domain.DirectionalGroup;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Joiner;\n\npublic class UpdateDirectionalDNSGroupToXML implements MapBinder {\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      DirectionalGroup group = DirectionalGroup.class.cast(postParams.get(\"group\"));\n      String xml = toXML(postParams.get(\"dirPoolRecordId\"), group);\n      return (R) request.toBuilder().payload(xml).build();\n   }\n\n   private static final String template = \"<v01:updateDirectionalDNSGroup><transactionID /><dirPoolRecordId>%s</dirPoolRecordId>%s</v01:updateDirectionalDNSGroup>\";\n\n   @VisibleForTesting\n   static String toXML(Object dirPoolRecordId, DirectionalGroup group) {\n      return format(template, dirPoolRecordId, geo(group));\n   }\n\n   private static String geo(DirectionalGroup group) {\n      StringBuilder groupData = new StringBuilder();\n      groupData.append(\"<DirectionalDNSGroupDetail GroupName=\\\"\").append(group.getName()).append('\"');\n      if (group.getDescription().isPresent())\n         groupData.append(\" Description=\\\"\").append(group.getDescription().get()).append('\"');\n      groupData.append(\" ><DirectionalDNSRegion>\");\n      for (Entry<String, Collection<String>> region : group.asMap().entrySet()) {\n         groupData.append(\"<RegionForNewGroups RegionName=\\\"\").append(region.getKey()).append('\"');\n         groupData.append(\" TerritoryName=\\\"\").append(Joiner.on(';').join(region.getValue())).append(\"\\\" />\");\n      }\n      groupData.append(\"</DirectionalDNSRegion></DirectionalDNSGroupDetail>\");\n      return groupData.toString();\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      throw new UnsupportedOperationException(\"use map form\");\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/binders/UpdatePoolRecordToXML.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.binders;\n\nimport static java.lang.String.format;\n\nimport java.util.Map;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.MapBinder;\nimport org.jclouds.ultradns.ws.domain.UpdatePoolRecord;\n\npublic class UpdatePoolRecordToXML implements MapBinder {\n   private static final String HEADER = \"<v01:updatePoolRecord><transactionID /><poolRecordID>%s</poolRecordID><parentPoolId /><childPoolId />\";\n   private static final String FOOTER = \"</v01:updatePoolRecord>\";\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n\n      StringBuilder xml = new StringBuilder();\n      xml.append(format(HEADER, postParams.get(\"poolRecordID\")));\n\n      UpdatePoolRecord update = UpdatePoolRecord.class.cast(postParams.get(\"update\"));\n\n      xml.append(\"<pointsTo>\").append(update.getRData()).append(\"</pointsTo>\");\n      xml.append(\"<priority>\").append(update.getPriority()).append(\"</priority>\");\n      xml.append(\"<failOverDelay>\").append(update.getFailOverDelay()).append(\"</failOverDelay>\");\n      xml.append(\"<ttl>\").append(update.getTTL()).append(\"</ttl>\");\n      xml.append(\"<weight>\").append(update.getWeight()).append(\"</weight>\");\n      xml.append(\"<mode>\").append(update.getMode()).append(\"</mode>\");\n      xml.append(\"<threshold>\").append(update.getThreshold()).append(\"</threshold>\");\n\n      xml.append(FOOTER);\n      return (R) request.toBuilder().payload(xml.toString()).build();\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      throw new UnsupportedOperationException(\"use map form\");\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/binders/ZoneAndResourceRecordToXML.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.binders;\n\nimport static java.lang.String.format;\n\nimport java.util.Map;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.rest.MapBinder;\nimport org.jclouds.ultradns.ws.domain.ResourceRecord;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Optional;\n\npublic class ZoneAndResourceRecordToXML implements MapBinder {\n   private static final String template = \"<v01:createResourceRecord><transactionID /><resourceRecord ZoneName=\\\"%s\\\" Type=\\\"%s\\\" DName=\\\"%s\\\" TTL=\\\"%s\\\">%s</resourceRecord></v01:createResourceRecord>\";\n\n   @SuppressWarnings(\"unchecked\")\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {\n      String zoneName = postParams.get(\"zoneName\").toString();\n      ResourceRecord record = ResourceRecord.class.cast(postParams.get(\"resourceRecord\"));\n      String xml = toXML(zoneName, record);\n      Optional<?> guid = Optional.fromNullable(postParams.get(\"guid\"));\n      if (guid.isPresent()) {\n         xml = update(guid.get(), xml);\n      }\n      return (R) request.toBuilder().payload(xml).build();\n   }\n\n   @VisibleForTesting\n   static String toXML(String zoneName, ResourceRecord record) {\n      StringBuilder values = new StringBuilder(\"<InfoValues\");\n      for (int i = 0; i < record.getRData().size(); i++) {\n         values.append(' ').append(\"Info\").append(i + 1).append(\"Value=\").append('\"')\n               .append(record.getRData().get(i)).append('\"');\n      }\n      values.append(\" />\");\n      return format(template, zoneName, record.getType(), record.getName(), record.getTTL(), values.toString());\n   }\n\n   static String update(Object guid, String xml) {\n      return xml.replace(\"createResourceRecord\", \"updateResourceRecord\").replace(\"<resourceRecord\",\n            format(\"<resourceRecord Guid=\\\"%s\\\"\", guid));\n   }\n\n   @Override\n   public <R extends HttpRequest> R bindToRequest(R request, Object input) {\n      throw new UnsupportedOperationException(\"use map form\");\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/config/UltraDNSWSHttpApiModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.config;\n\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpRetryHandler;\nimport org.jclouds.http.annotation.ClientError;\nimport org.jclouds.http.annotation.Redirection;\nimport org.jclouds.http.annotation.ServerError;\nimport org.jclouds.rest.ConfiguresHttpApi;\nimport org.jclouds.rest.config.HttpApiModule;\nimport org.jclouds.ultradns.ws.UltraDNSWSApi;\nimport org.jclouds.ultradns.ws.handlers.UltraDNSWSErrorHandler;\n\n\n/**\n * Configures the UltraDNSWS connection.\n */\n@ConfiguresHttpApi\npublic class UltraDNSWSHttpApiModule extends HttpApiModule<UltraDNSWSApi> {\n   public UltraDNSWSHttpApiModule() {\n   }\n\n   @Override\n   protected void bindErrorHandlers() {\n      bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(UltraDNSWSErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(UltraDNSWSErrorHandler.class);\n      bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(UltraDNSWSErrorHandler.class);\n   }\n\n   @Override\n   protected void bindRetryHandlers() {\n      bind(HttpRetryHandler.class).annotatedWith(ServerError.class).toInstance(HttpRetryHandler.NEVER_RETRY);\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/domain/AccountLevelGroup.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.domain;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.ultradns.ws.domain.DirectionalPool.Type;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\npublic final class AccountLevelGroup {\n\n   private final String id;\n   private final String name;\n   private final Type type;\n   private final int recordCount;\n\n   private AccountLevelGroup(String id, String name, Type type, int recordCount) {\n      this.id = checkNotNull(id, \"id\");\n      this.name = checkNotNull(name, \"name of %s\", id);\n      this.type = checkNotNull(type, \"type of %s\", id);\n      this.recordCount = recordCount;\n      checkArgument(recordCount >= 0, \"recordCount of %s must be >= 0\", id);\n   }\n\n   public String getId() {\n      return id;\n   }\n\n   public String getName() {\n      return name;\n   }\n\n   public Type getType() {\n      return type;\n   }\n\n   public int getRecordCount() {\n      return recordCount;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, name, type);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      AccountLevelGroup that = AccountLevelGroup.class.cast(obj);\n      return Objects.equal(this.id, that.id) && Objects.equal(this.name, that.name)\n            && Objects.equal(this.type, that.type);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"id\", id).add(\"name\", name).add(\"type\", type)\n            .add(\"recordCount\", recordCount).toString();\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().from(this);\n   }\n\n   public static final class Builder {\n      private String id;\n      private String name;\n      private Type type;\n      private int recordCount = -1;\n\n      /**\n       * @see AccountLevelGroup#getId()\n       */\n      public Builder id(String id) {\n         this.id = id;\n         return this;\n      }\n\n      /**\n       * @see AccountLevelGroup#getName()\n       */\n      public Builder name(String name) {\n         this.name = name;\n         return this;\n      }\n\n      /**\n       * @see AccountLevelGroup#getType()\n       */\n      public Builder type(Type type) {\n         this.type = type;\n         return this;\n      }\n\n      /**\n       * @see AccountLevelGroup#getRecordCount()\n       */\n      public Builder recordCount(int recordCount) {\n         this.recordCount = recordCount;\n         return this;\n      }\n\n      public AccountLevelGroup build() {\n         return new AccountLevelGroup(id, name, type, recordCount);\n      }\n\n      public Builder from(AccountLevelGroup in) {\n         return this.id(in.id).name(in.name).type(in.type).recordCount(in.recordCount);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/domain/DirectionalGroup.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ForwardingMultimap;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.Multimap;\n\n/**\n * A region is a set of territory names.\n */\npublic class DirectionalGroup extends ForwardingMultimap<String, String> {\n\n   private final String name;\n   private final Optional<String> description;\n   private final Multimap<String, String> regionToTerritories;\n\n   private DirectionalGroup(String name, Optional<String> description,\n         Multimap<String, String> regionToTerritories) {\n      this.name = checkNotNull(name, \"name\");\n      this.description = checkNotNull(description, \"description of %s\", name);\n      this.regionToTerritories = checkNotNull(regionToTerritories, \"regionToTerritories of %s\", name);\n   }\n\n   public String getName() {\n      return name;\n   }\n\n   public Optional<String> getDescription() {\n      return description;\n   }\n\n   public Multimap<String, String> getRegionToTerritories() {\n      return regionToTerritories;\n   }\n\n   @Override\n   protected Multimap<String, String> delegate() {\n      return regionToTerritories;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(name, regionToTerritories);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      DirectionalGroup that = DirectionalGroup.class.cast(obj);\n      return equal(this.name, that.name) && equal(this.regionToTerritories, that.regionToTerritories);\n   }\n\n   @Override\n   public String toString() {\n      return toStringHelper(this).omitNullValues().add(\"name\", name).add(\"description\", description.orNull())\n            .add(\"regionToTerritories\", regionToTerritories).toString();\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().from(this);\n   }\n\n   public static final class Builder {\n      private String name;\n      private Optional<String> description = Optional.absent();\n      private ImmutableMultimap.Builder<String, String> regionToTerritories = ImmutableMultimap\n            .<String, String> builder();\n\n      /**\n       * @see DirectionalGroup#getName()\n       */\n      public Builder name(String name) {\n         this.name = name;\n         return this;\n      }\n\n      /**\n       * @see DirectionalGroup#getDescription()\n       */\n      public Builder description(String description) {\n         this.description = Optional.fromNullable(description);\n         return this;\n      }\n\n      /**\n       * adds to current regionToTerritories\n       * \n       * @see DirectionalGroup#getRegionToTerritories()\n       */\n      public Builder mapRegionToTerritories(String region, Iterable<String> territories) {\n         this.regionToTerritories.putAll(region, territories);\n         return this;\n      }\n\n      /**\n       * adds to current regionToTerritories\n       * \n       * @see DirectionalGroup#getRegionToTerritories()\n       */\n      public Builder mapRegionToTerritory(String region, String territory) {\n         this.regionToTerritories.put(region, territory);\n         return this;\n      }\n\n      /**\n       * adds to current regionToTerritories\n       * \n       * @see DirectionalGroup#getRegionToTerritories()\n       */\n      public Builder mapRegion(String region) {\n         this.regionToTerritories.put(region, \"all\");\n         return this;\n      }\n\n      /**\n       * replaces current regionToTerritories\n       * \n       * @see DirectionalGroup#getRegionToTerritories()\n       */\n      public Builder regionToTerritories(Multimap<String, String> regionToTerritories) {\n         this.regionToTerritories = ImmutableMultimap.<String, String> builder().putAll(regionToTerritories);\n         return this;\n      }\n\n      public DirectionalGroup build() {\n         return new DirectionalGroup(name, description, regionToTerritories.build());\n      }\n\n      public Builder from(DirectionalGroup in) {\n         return name(in.getName()).regionToTerritories(in.getRegionToTerritories());\n      }\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/domain/DirectionalGroupCoordinates.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.Objects;\n\npublic class DirectionalGroupCoordinates {\n\n   private final String zoneName;\n   private final String recordName;\n   private final int recordType;\n   private final String groupName;\n\n   private DirectionalGroupCoordinates(String zoneName, String recordName, int recordType, String groupName) {\n      this.zoneName = checkNotNull(zoneName, \"zoneName\");\n      this.recordName = checkNotNull(recordName, \"recordName\");\n      checkArgument(recordType >= 0, \"recordType of %s must be >= 0\", recordName);\n      this.recordType = recordType;\n      this.groupName = checkNotNull(groupName, \"groupName\");\n   }\n\n   /**\n    * the {@link DirectionalPoolRecordDetail#getZoneName() name} of the zone.\n    */\n   public String getZoneName() {\n      return zoneName;\n   }\n\n   /**\n    * the {@link DirectionalPoolRecordDetail#getName() dname} of the record.\n    */\n   public String getRecordName() {\n      return recordName;\n   }\n\n   /**\n    * the {@link DirectionalPoolRecord#getType() recordType} of the record.\n    * \n    * @see DirectionalPoolRecordDetail#getRecord()\n    */\n   public int getRecordType() {\n      return recordType;\n   }\n\n   /**\n    * the {@link DirectionalGroup#getName() name} of the directional group.\n    * \n    * @see DirectionalPoolRecordDetail#getGroup()\n    * @see DirectionalPoolRecordDetail#getGeolocationGroup()\n    * @see DirectionalPoolRecordDetail#getSourceIpGroup()\n    */\n   public String getGroupName() {\n      return groupName;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(zoneName, recordName, recordType, groupName);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      DirectionalGroupCoordinates that = DirectionalGroupCoordinates.class.cast(obj);\n      return equal(this.zoneName, that.zoneName) && equal(this.recordName, that.recordName)\n            && equal(this.recordType, that.recordType) && equal(this.groupName, that.groupName);\n   }\n\n   @Override\n   public String toString() {\n      return toStringHelper(this).add(\"zoneName\", zoneName).add(\"recordName\", recordName).add(\"recordType\", recordType)\n            .add(\"groupName\", groupName).toString();\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().from(this);\n   }\n\n   public static final class Builder {\n      private String zoneName;\n      private String recordName;\n      private int recordType = -1;\n      private String groupName;\n\n      /**\n       * @see DirectionalGroupCoordinates#getZoneName()\n       */\n      public Builder zoneName(String zoneName) {\n         this.zoneName = zoneName;\n         return this;\n      }\n\n      /**\n       * @see DirectionalGroupCoordinates#getRecordName()\n       */\n      public Builder recordName(String recordName) {\n         this.recordName = recordName;\n         return this;\n      }\n\n      /**\n       * @see DirectionalGroupCoordinates#getRecordType()\n       */\n      public Builder recordType(int recordType) {\n         this.recordType = recordType;\n         return this;\n      }\n\n      /**\n       * @see DirectionalGroupCoordinates#getGroupName()\n       */\n      public Builder groupName(String groupName) {\n         this.groupName = groupName;\n         return this;\n      }\n\n      public DirectionalGroupCoordinates build() {\n         return new DirectionalGroupCoordinates(zoneName, recordName, recordType, groupName);\n      }\n\n      public Builder from(DirectionalGroupCoordinates in) {\n         return zoneName(in.zoneName).recordName(in.zoneName).recordType(in.recordType).groupName(in.groupName);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/domain/DirectionalPool.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.Optional;\n\n/**\n * Records are resolved in consideration of the location of the requestor.\n */\npublic final class DirectionalPool {\n\n   private final String zoneId;\n   private final String id;\n   private final Optional<String> name;\n   private final String dname;\n   private final Type type;\n   private final TieBreak tieBreak;\n\n   private DirectionalPool(String zoneId, String id, Optional<String> name, String dname, Type type,\n         TieBreak tieBreak) {\n      this.zoneId = checkNotNull(zoneId, \"zoneId\");\n      this.id = checkNotNull(id, \"id\");\n      this.name = checkNotNull(name, \"name for %s\", id);\n      this.dname = checkNotNull(dname, \"dname for %s\", id);\n      this.type = type;\n      this.tieBreak = tieBreak;\n   }\n\n   public String getZoneId() {\n      return zoneId;\n   }\n\n   public String getId() {\n      return id;\n   }\n\n   /**\n    * The dname of the pool. ex. {@code jclouds.org.}\n    */\n   public String getDName() {\n      return dname;\n   }\n\n   /**\n    * The name of the pool. ex. {@code My Pool}\n    */\n   public Optional<String> getName() {\n      return name;\n   }\n\n   public Type getType() {\n      return type;\n   }\n\n   /**\n    * if {@link #getType} is {@link Type#MIXED}, this can be\n    * {@link TieBreak#SOURCEIP} or {@link TieBreak#GEOLOCATION}, otherwise\n    * {@link TieBreak#GEOLOCATION}\n    */\n   public TieBreak getTieBreak() {\n      return tieBreak;\n   }\n\n   public static enum Type {\n      GEOLOCATION, SOURCEIP, MIXED;\n   }\n\n   /**\n    * currently supported {@link ResourceRecord#getType() types} for directional\n    * groups.\n    * \n    */\n   public static enum RecordType {\n      // A/CNAME\n      IPV4(1),\n\n      // AAAA/CNAME\n      IPV6(28),\n\n      TXT(16),\n\n      SRV(33),\n\n      PTR(12),\n\n      RP(17),\n\n      HINFO(13),\n\n      NAPTR(35),\n\n      MX(15);\n\n      private final int code;\n\n      private RecordType(int code) {\n         this.code = code;\n      }\n\n      /**\n       * The {@link ResourceRecord#getType() type} that can be used in\n       * directional groups.\n       */\n      public int getCode() {\n         return code;\n      }\n   }\n\n   public static enum TieBreak {\n      GEOLOCATION, SOURCEIP;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(zoneId, id, name, dname);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      DirectionalPool that = DirectionalPool.class.cast(obj);\n      return Objects.equal(this.zoneId, that.zoneId) && Objects.equal(this.id, that.id)\n            && Objects.equal(this.name, that.name) && Objects.equal(this.dname, that.dname);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"zoneId\", zoneId).add(\"id\", id).add(\"dname\", dname)\n            .add(\"name\", name.orNull()).add(\"type\", type).add(\"tieBreak\", tieBreak).toString();\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().from(this);\n   }\n\n   public static final class Builder {\n      private String zoneId;\n      private String id;\n      private Optional<String> name = Optional.absent();\n      private String dname;\n      private Type type = Type.GEOLOCATION;\n      private TieBreak tieBreak = TieBreak.GEOLOCATION;\n\n      /**\n       * @see DirectionalPool#getZoneId()\n       */\n      public Builder zoneId(String zoneId) {\n         this.zoneId = zoneId;\n         return this;\n      }\n\n      /**\n       * @see DirectionalPool#getId()\n       */\n      public Builder id(String id) {\n         this.id = id;\n         return this;\n      }\n\n      /**\n       * @see DirectionalPool#getDName()\n       */\n      public Builder dname(String dname) {\n         this.dname = dname;\n         return this;\n      }\n\n      /**\n       * @see DirectionalPool#getName()\n       */\n      public Builder name(String name) {\n         this.name = Optional.fromNullable(name);\n         return this;\n      }\n\n      /**\n       * @see DirectionalPool#getType()\n       */\n      public Builder type(Type type) {\n         this.type = type;\n         return this;\n      }\n\n      /**\n       * @see DirectionalPool#getTieBreak()\n       */\n      public Builder tieBreak(TieBreak tieBreak) {\n         this.tieBreak = tieBreak;\n         return this;\n      }\n\n      public DirectionalPool build() {\n         return new DirectionalPool(zoneId, id, name, dname, type, tieBreak);\n      }\n\n      public Builder from(DirectionalPool in) {\n         return this.zoneId(in.zoneId).id(in.id).name(in.name.orNull()).dname(in.dname).type(in.type)\n               .tieBreak(in.tieBreak);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/domain/DirectionalPoolRecord.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.domain;\n\nimport static com.google.common.base.Functions.toStringFunction;\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.transform;\n\nimport java.util.List;\n\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ImmutableList;\n\npublic class DirectionalPoolRecord {\n   private final String type;\n   private final int ttl;\n   private final boolean noResponseRecord;\n   private final List<String> infoValues;\n\n   private DirectionalPoolRecord(String type, int ttl, boolean noResponseRecord, List<String> infoValues) {\n      this.type = checkNotNull(type, \"type\");\n      checkArgument(ttl >= 0, \"ttl must be >= 0\");\n      this.ttl = ttl;\n      this.noResponseRecord = noResponseRecord;\n      this.infoValues = checkNotNull(infoValues, \"infoValues\");\n   }\n\n   /**\n    * the type. ex. {@code A}\n    */\n   public String getType() {\n      return type;\n   }\n\n   public int getTTL() {\n      return ttl;\n   }\n\n   /**\n    * true if blocks traffic from specified regions by returning No Error, No\n    * Response.\n    */\n   public boolean isNoResponseRecord() {\n      return noResponseRecord;\n   }\n\n   /**\n    * {@link #getType() type}-specific binary values.\n    */\n   public List<String> getRData() {\n      return infoValues;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(noResponseRecord, type, ttl, infoValues);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      DirectionalPoolRecord that = DirectionalPoolRecord.class.cast(obj);\n      return equal(this.type, that.type) && equal(this.ttl, that.ttl)\n            && equal(this.noResponseRecord, that.noResponseRecord) && equal(this.infoValues, that.infoValues);\n   }\n\n   @Override\n   public String toString() {\n      return toStringHelper(this).add(\"type\", type).add(\"ttl\", ttl).add(\"noResponseRecord\", noResponseRecord)\n            .add(\"infoValues\", infoValues).toString();\n   }\n\n   public static Builder drBuilder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return drBuilder().from(this);\n   }\n\n   public static final class Builder {\n      private String type;\n      private int ttl = -1;\n      private boolean noResponseRecord;\n      private ImmutableList.Builder<String> infoValues = ImmutableList.<String> builder();\n\n      /**\n       * @see DirectionalPoolRecord#getType()\n       */\n      public Builder type(String type) {\n         this.type = type;\n         return this;\n      }\n\n      /**\n       * @see DirectionalPoolRecord#getTTL()\n       */\n      public Builder ttl(int ttl) {\n         this.ttl = ttl;\n         return this;\n      }\n\n      /**\n       * @see DirectionalPoolRecord#isNoResponseRecord()\n       */\n      public Builder noResponseRecord(boolean noResponseRecord) {\n         this.noResponseRecord = noResponseRecord;\n         return this;\n      }\n\n      /**\n       * adds to current values\n       * \n       * @see DirectionalPoolRecord#getRData()\n       */\n      public Builder infoValue(Object infoValue) {\n         this.infoValues.add(infoValue.toString());\n         return this;\n      }\n\n      /**\n       * replaces current values\n       * \n       * @see DirectionalPoolRecord#getRData()\n       */\n      public Builder rdata(Object infoValue) {\n         this.infoValues = ImmutableList.<String> builder().add(infoValue.toString());\n         return this;\n      }\n\n      /**\n       * replaces current values\n       * \n       * @see DirectionalPoolRecord#getRData()\n       */\n      public Builder rdata(Iterable<?> infoValues) {\n         this.infoValues = ImmutableList.<String> builder().addAll(transform(infoValues, toStringFunction()));\n         return this;\n      }\n\n      public DirectionalPoolRecord build() {\n         return new DirectionalPoolRecord(type, ttl, noResponseRecord, infoValues.build());\n      }\n\n      public Builder from(DirectionalPoolRecord in) {\n         return type(in.type).ttl(in.ttl).noResponseRecord(in.noResponseRecord).rdata(in.infoValues);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/domain/DirectionalPoolRecordDetail.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.Optional;\n\npublic class DirectionalPoolRecordDetail {\n\n   private final String zoneName;\n   private final String name;\n   private final String id;\n   private final Optional<IdAndName> group;\n   private final Optional<IdAndName> geolocationGroup;\n   private final Optional<IdAndName> sourceIpGroup;\n   private final DirectionalPoolRecord record;\n\n   private DirectionalPoolRecordDetail(String zoneName, String name, String id,\n         Optional<IdAndName> group, Optional<IdAndName> geolocationGroup,\n         Optional<IdAndName> sourceIpGroup, DirectionalPoolRecord record) {\n      this.zoneName = checkNotNull(zoneName, \"zoneName\");\n      this.name = checkNotNull(name, \"name\");\n      this.id = checkNotNull(id, \"id\");\n      this.group = checkNotNull(group, \"group of %s/%s/%s\", zoneName, name, id);\n      this.geolocationGroup = checkNotNull(geolocationGroup, \"geolocationGroup of %s/%s/%s\", zoneName, name, id);\n      this.sourceIpGroup = checkNotNull(sourceIpGroup, \"sourceIpGroup of %s/%s/%s\", zoneName, name, id);\n      this.record = checkNotNull(record, \"record of %s/%s/%s\", zoneName, name, id);\n   }\n\n   public String getZoneName() {\n      return zoneName;\n   }\n\n   public String getName() {\n      return name;\n   }\n\n   public String getId() {\n      return id;\n   }\n\n   /**\n    * group containing all regions that you have not specifically configured in {@link #getGeolocationGroup()}\n    */\n   public Optional<IdAndName> getGroup() {\n      return group;\n   }\n\n   /**\n    * group containing territories.\n    */\n   public Optional<IdAndName> getGeolocationGroup() {\n      return geolocationGroup;\n   }\n\n   /**\n    * group containing IPV4 or IPV6 ranges. \n    */\n   public Optional<IdAndName> getSourceIpGroup() {\n      return sourceIpGroup;\n   }\n\n   public DirectionalPoolRecord getRecord() {\n      return record;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(zoneName, name, id);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      DirectionalPoolRecordDetail that = DirectionalPoolRecordDetail.class.cast(obj);\n      return equal(this.zoneName, that.zoneName) && equal(this.name, that.name) && equal(this.id, that.id);\n   }\n\n   @Override\n   public String toString() {\n      return toStringHelper(this).omitNullValues().add(\"zoneName\", zoneName).add(\"name\", name).add(\"id\", id)\n            .add(\"group\", group.orNull()).add(\"geolocationGroup\", geolocationGroup.orNull())\n            .add(\"sourceIpGroup\", sourceIpGroup.orNull()).add(\"record\", record).toString();\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().from(this);\n   }\n\n   public static final class Builder {\n      private String zoneName;\n      private String name;\n      private String id;\n      private Optional<IdAndName> group = Optional.absent();\n      private Optional<IdAndName> geolocationGroup = Optional.absent();\n      private Optional<IdAndName> sourceIpGroup = Optional.absent();\n      private DirectionalPoolRecord record;\n\n      /**\n       * @see DirectionalPoolRecordDetail#getZoneName()\n       */\n      public Builder zoneName(String zoneName) {\n         this.zoneName = zoneName;\n         return this;\n      }\n\n      /**\n       * @see DirectionalPoolRecordDetail#getName()\n       */\n      public Builder name(String name) {\n         this.name = name;\n         return this;\n      }\n\n      /**\n       * @see DirectionalPoolRecordDetail#getId()\n       */\n      public Builder id(String id) {\n         this.id = id;\n         return this;\n      }\n\n      /**\n       * @see DirectionalPoolRecordDetail#getGroup()\n       */\n      public Builder group(IdAndName group) {\n         this.group = Optional.fromNullable(group);\n         return this;\n      }\n\n      /**\n       * @see DirectionalPoolRecordDetail#getGeolocationGroup()\n       */\n      public Builder geolocationGroup(IdAndName geolocationGroup) {\n         this.geolocationGroup = Optional.fromNullable(geolocationGroup);\n         return this;\n      }\n\n      /**\n       * @see DirectionalPoolRecordDetail#getSourceIpGroup()\n       */\n      public Builder sourceIpGroup(IdAndName sourceIpGroup) {\n         this.sourceIpGroup = Optional.fromNullable(sourceIpGroup);\n         return this;\n      }\n\n      /**\n       * @see DirectionalPoolRecordDetail#getRecord()\n       */\n      public Builder record(DirectionalPoolRecord record) {\n         this.record = record;\n         return this;\n      }\n\n      /**\n       * @see DirectionalPoolRecordDetail#getRecord()\n       */\n      public Builder record(DirectionalPoolRecord.Builder record) {\n         this.record = record.build();\n         return this;\n      }\n\n      public DirectionalPoolRecordDetail build() {\n         return new DirectionalPoolRecordDetail(zoneName, name, id, group, geolocationGroup, sourceIpGroup, record);\n      }\n\n      public Builder from(DirectionalPoolRecordDetail in) {\n         return this.zoneName(in.zoneName).name(in.name).id(in.id).group(in.group.orNull())\n               .geolocationGroup(in.geolocationGroup.orNull()).sourceIpGroup(in.sourceIpGroup.orNull())\n               .record(in.record);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/domain/IdAndName.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Predicates.compose;\nimport static com.google.common.base.Predicates.equalTo;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.Predicate;\n\npublic final class IdAndName {\n\n   public static IdAndName create(String id, String name) {\n      return new IdAndName(id, name);\n   }\n\n   private final String id;\n   private final String name;\n\n   private IdAndName(String id, String name) {\n      this.id = checkNotNull(id, \"id\");\n      this.name = checkNotNull(name, \"name for %s\", id);\n   }\n\n   /**\n    * The id of the resource. ex {@code AAAAAAAAAAAAAAAA}\n    */\n   public String getId() {\n      return id;\n   }\n\n   /**\n    * The name of the resource. ex {@code jclouds}\n    */\n   public String getName() {\n      return name;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, name);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      IdAndName that = IdAndName.class.cast(obj);\n      return Objects.equal(this.id, that.id) && Objects.equal(this.name, that.name);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(\"\").add(\"id\", id).add(\"name\", name).toString();\n   }\n\n   /**\n    * convenience predicate as typically the user is unaware of the system\n    * generated id of a resource\n    * \n    * @param name\n    *           see {@link #getName()}\n    */\n   public static Predicate<IdAndName> nameEqualTo(String name) {\n      return compose(equalTo(name), ToName.INSTANCE);\n   }\n\n   private static enum ToName implements Function<IdAndName, String> {\n      INSTANCE;\n      @Override\n      public String apply(IdAndName input) {\n         return input.getName();\n      }\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/domain/PoolRecordSpec.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.Objects;\n\n/**\n * specifications and status of a current record in the pool.\n */\npublic final class PoolRecordSpec {\n   private final String description;\n   private final String state;\n   private final boolean probingEnabled;\n   private final boolean allFailEnabled;\n   private final int weight;\n   private final int failOverDelay;\n   private final int threshold;\n   private final int ttl;\n\n   private PoolRecordSpec(String description, String state, boolean probingEnabled, boolean allFailEnabled, int weight,\n         int failOverDelay, int threshold, int ttl) {\n      this.description = checkNotNull(description, \"description\");\n      this.state = checkNotNull(state, \"state for %s\", description);\n      this.probingEnabled = probingEnabled;\n      this.allFailEnabled = allFailEnabled;\n      this.weight = weight;\n      checkArgument(weight >= 0, \"weight of %s must be >= 0\", description);\n      this.failOverDelay = failOverDelay;\n      checkArgument(failOverDelay >= 0, \"failOverDelay of %s must be >= 0\", description);\n      this.threshold = threshold;\n      checkArgument(threshold >= 0, \"threshold of %s must be >= 0\", description);\n      this.ttl = ttl;\n      checkArgument(ttl >= 0, \"ttl of %s must be >= 0\", description);\n   }\n\n   /**\n    * correlates to {@link TrafficControllerPoolRecordDetail#getDescription()}\n    */\n   public String getDescription() {\n      return description;\n   }\n\n   /**\n    * known values include {@code Normal} and {@code Normal-NoTest}\n    */\n   public String getState() {\n      return state;\n   }\n\n   /**\n    * correlates to {@link TrafficControllerPoolRecordDetail#isProbingEnabled()}\n    */\n   public boolean isProbingEnabled() {\n      return probingEnabled;\n   }\n\n   /**\n    * undocumented\n    */\n   public boolean isAllFailEnabled() {\n      return allFailEnabled;\n   }\n\n   /**\n    * correlates to {@link TrafficControllerPoolRecordDetail#getWeight()}\n    */\n   public int getWeight() {\n      return weight;\n   }\n\n   /**\n    * at the time of writing, between 0–30 (minutes).\n    */\n   public int getFailOverDelay() {\n      return failOverDelay;\n   }\n\n   /**\n    * how many probes in a region must fail in order for this to fail.\n    */\n   public int getThreshold() {\n      return threshold;\n   }\n\n   /**\n    * The resource record cache time to live (TTL), in seconds.\n    */\n   public int getTTL() {\n      return ttl;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(description, state, probingEnabled, allFailEnabled, weight, failOverDelay, threshold,\n            ttl);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      PoolRecordSpec that = PoolRecordSpec.class.cast(obj);\n      return equal(this.description, that.description) && equal(this.state, that.state)\n            && equal(this.probingEnabled, that.probingEnabled) && equal(this.allFailEnabled, that.allFailEnabled)\n            && equal(this.weight, that.weight) && equal(this.failOverDelay, that.failOverDelay)\n            && equal(this.threshold, that.threshold) && equal(this.ttl, that.ttl);\n   }\n\n   @Override\n   public String toString() {\n      return toStringHelper(this).add(\"description\", description).add(\"state\", state)\n            .add(\"probingEnabled\", probingEnabled).add(\"allFailEnabled\", allFailEnabled).add(\"weight\", weight)\n            .add(\"failOverDelay\", failOverDelay).add(\"threshold\", threshold).add(\"ttl\", ttl).toString();\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().from(this);\n   }\n\n   public static final class Builder {\n      private String description;\n      private String state;\n      private boolean probingEnabled;\n      private boolean allFailEnabled;\n      private int weight;\n      private int failOverDelay;\n      private int threshold;\n      private int ttl;\n\n      /**\n       * @see PoolRecordSpec#getDescription()\n       */\n      public Builder description(String description) {\n         this.description = description;\n         return this;\n      }\n\n      /**\n       * @see PoolRecordSpec#getState()\n       */\n      public Builder state(String state) {\n         this.state = state;\n         return this;\n      }\n\n      /**\n       * @see PoolRecordSpec#isProbingEnabled()\n       */\n      public Builder probingEnabled(boolean probingEnabled) {\n         this.probingEnabled = probingEnabled;\n         return this;\n      }\n\n      /**\n       * @see PoolRecordSpec#isAllFailEnabled()\n       */\n      public Builder allFailEnabled(boolean allFailEnabled) {\n         this.allFailEnabled = allFailEnabled;\n         return this;\n      }\n\n      /**\n       * @see PoolRecordSpec#getWeight()\n       */\n      public Builder weight(int weight) {\n         this.weight = weight;\n         return this;\n      }\n\n      /**\n       * @see PoolRecordSpec#getFailOverDelay()\n       */\n      public Builder failOverDelay(int failOverDelay) {\n         this.failOverDelay = failOverDelay;\n         return this;\n      }\n\n      /**\n       * @see PoolRecordSpec#getThreshold()\n       */\n      public Builder threshold(int threshold) {\n         this.threshold = threshold;\n         return this;\n      }\n\n      /**\n       * @see PoolRecordSpec#getTTL()\n       */\n      public Builder ttl(int ttl) {\n         this.ttl = ttl;\n         return this;\n      }\n\n      public PoolRecordSpec build() {\n         return new PoolRecordSpec(description, state, probingEnabled, allFailEnabled, weight, failOverDelay,\n               threshold, ttl);\n      }\n\n      public Builder from(PoolRecordSpec in) {\n         return this.description(in.description).state(in.state).probingEnabled(in.probingEnabled)\n               .allFailEnabled(in.allFailEnabled).weight(in.weight).failOverDelay(in.failOverDelay)\n               .threshold(in.threshold).ttl(in.ttl);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/domain/ResourceRecord.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.domain;\n\nimport static com.google.common.base.Functions.toStringFunction;\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.transform;\n\nimport java.util.List;\n\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ImmutableList;\n\npublic class ResourceRecord {\n\n   private final String dName;\n   private final int type;\n   private final int ttl;\n   private final List<String> infoValues;\n\n   private ResourceRecord(String dName, int type, int ttl, List<String> infoValues) {\n      this.dName = checkNotNull(dName, \"dName\");\n      checkArgument(type >= 0, \"type of %s must be >= 0\", dName);\n      this.type = type;\n      checkArgument(ttl >= 0, \"ttl of %s must be >= 0\", dName);\n      this.ttl = ttl;\n      this.infoValues = checkNotNull(infoValues, \"infoValues of %s\", dName);\n   }\n\n   /**\n    * the {@code dName} of the record.\n    */\n   public String getName() {\n      return dName;\n   }\n\n   /**\n    * the type value. ex {@code 1} for type {@code A}\n    */\n   public int getType() {\n      return type;\n   }\n\n   public int getTTL() {\n      return ttl;\n   }\n\n   /**\n    * {@link #getType() type}-specific binary values.\n    */\n   public List<String> getRData() {\n      return infoValues;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(dName, type, ttl, infoValues);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      ResourceRecord that = ResourceRecord.class.cast(obj);\n      return equal(this.dName, that.dName) && equal(this.type, that.type) && equal(this.ttl, that.ttl)\n            && equal(this.infoValues, that.infoValues);\n   }\n\n   @Override\n   public String toString() {\n      return toStringHelper(this).omitNullValues().add(\"dName\", dName).add(\"type\", type).add(\"ttl\", ttl)\n            .add(\"infoValues\", infoValues).toString();\n   }\n\n   public static Builder rrBuilder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return rrBuilder().from(this);\n   }\n\n   public static final class Builder {\n      private String dName;\n      private int type = -1;\n      private int ttl = -1;\n      private ImmutableList.Builder<String> infoValues = ImmutableList.<String> builder();\n\n      /**\n       * @see ResourceRecord#getName()\n       */\n      public Builder name(String dName) {\n         this.dName = dName;\n         return this;\n      }\n\n      /**\n       * @see ResourceRecord#getType()\n       */\n      public Builder type(int type) {\n         this.type = type;\n         return this;\n      }\n\n      /**\n       * @see ResourceRecord#getTTL()\n       */\n      public Builder ttl(int ttl) {\n         this.ttl = ttl;\n         return this;\n      }\n\n      /**\n       * adds to current values\n       * \n       * @see ResourceRecord#getRData()\n       */\n      public Builder infoValue(Object infoValue) {\n         this.infoValues.add(infoValue.toString());\n         return this;\n      }\n\n      /**\n       * replaces current values\n       * \n       * @see ResourceRecord#getRData()\n       */\n      public Builder rdata(Object infoValue) {\n         this.infoValues = ImmutableList.<String> builder().add(infoValue.toString());\n         return this;\n      }\n\n      /**\n       * replaces current values\n       * \n       * @see ResourceRecord#getRData()\n       */\n      public Builder rdata(Iterable<?> infoValues) {\n         this.infoValues = ImmutableList.<String> builder().addAll(transform(infoValues, toStringFunction()));\n         return this;\n      }\n\n      public ResourceRecord build() {\n         return new ResourceRecord(dName, type, ttl, infoValues.build());\n      }\n\n      public Builder from(ResourceRecord in) {\n         return name(in.getName()).type(in.getType()).ttl(in.getTTL()).rdata(in.getRData());\n      }\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/domain/ResourceRecordDetail.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Date;\n\nimport com.google.common.base.Objects;\n\npublic class ResourceRecordDetail {\n\n   private final String zoneId;\n   private final String guid;\n   private final String zoneName;\n   private final Date created;\n   private final Date modified;\n   private final ResourceRecord record;\n\n   private ResourceRecordDetail(String zoneId, String guid, String zoneName, Date created, Date modified,\n         ResourceRecord record) {\n      this.zoneId = checkNotNull(zoneId, \"zoneId\");\n      this.guid = checkNotNull(guid, \"guid\");\n      this.zoneName = checkNotNull(zoneName, \"zoneName of %s/%s\", zoneId, guid);\n      this.created = checkNotNull(created, \"created of %s/%s\", zoneId, guid);\n      this.modified = checkNotNull(modified, \"modified of %s/%s\", zoneId, guid);\n      this.record = checkNotNull(record, \"record of %s/%s\", zoneId, guid);\n   }\n\n   public String getZoneId() {\n      return zoneId;\n   }\n\n   public String getGuid() {\n      return guid;\n   }\n\n   public String getZoneName() {\n      return zoneName;\n   }\n\n   public Date getCreated() {\n      return created;\n   }\n\n   public Date getModified() {\n      return modified;\n   }\n\n   /**\n    * the record in the zone file.\n    */\n   public ResourceRecord getRecord() {\n      return record;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(zoneId, guid);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      ResourceRecordDetail that = ResourceRecordDetail.class.cast(obj);\n      return equal(this.zoneId, that.zoneId) && equal(this.guid, that.guid);\n   }\n\n   @Override\n   public String toString() {\n      return toStringHelper(this).omitNullValues().add(\"zoneId\", zoneId).add(\"guid\", guid).add(\"zoneName\", zoneName)\n            .add(\"created\", created).add(\"modified\", modified).add(\"record\", record).toString();\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().from(this);\n   }\n\n   public static final class Builder {\n      private String zoneId;\n      private String guid;\n      private String zoneName;\n      private Date created;\n      private Date modified;\n      private ResourceRecord record;\n\n      /**\n       * @see ResourceRecordDetail#getZoneName()\n       */\n      public Builder zoneName(String zoneName) {\n         this.zoneName = zoneName;\n         return this;\n      }\n\n      /**\n       * @see ResourceRecordDetail#getGuid()\n       */\n      public Builder guid(String guid) {\n         this.guid = guid;\n         return this;\n      }\n\n      /**\n       * @see ResourceRecordDetail#getZoneId()\n       */\n      public Builder zoneId(String zoneId) {\n         this.zoneId = zoneId;\n         return this;\n      }\n\n      /**\n       * @see ResourceRecordDetail#getCreated()\n       */\n      public Builder created(Date created) {\n         this.created = created;\n         return this;\n      }\n\n      /**\n       * @see ResourceRecordDetail#getModified()\n       */\n      public Builder modified(Date modified) {\n         this.modified = modified;\n         return this;\n      }\n\n      /**\n       * @see ResourceRecordDetail#getRecord()\n       */\n      public Builder record(ResourceRecord record) {\n         this.record = record;\n         return this;\n      }\n\n      /**\n       * @see ResourceRecordDetail#getRecord()\n       */\n      public Builder record(ResourceRecord.Builder record) {\n         this.record = record.build();\n         return this;\n      }\n\n      public ResourceRecordDetail build() {\n         return new ResourceRecordDetail(zoneId, guid, zoneName, created, modified, record);\n      }\n\n      public Builder from(ResourceRecordDetail in) {\n         return this.zoneName(in.zoneName).guid(in.guid).zoneId(in.zoneId).created(in.created).modified(in.modified)\n               .record(in.record);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/domain/RoundRobinPool.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\npublic final class RoundRobinPool {\n\n   private final String zoneId;\n   private final String id;\n   private final String name;\n   private final String dname;\n\n   private RoundRobinPool(String zoneId, String id, String name, String dname) {\n      this.zoneId = checkNotNull(zoneId, \"zoneId\");\n      this.id = checkNotNull(id, \"id\");\n      this.name = checkNotNull(name, \"name for %s\", id);\n      this.dname = checkNotNull(dname, \"dname for %s\", id);\n   }\n\n   /**\n    * The ID of the zone.\n    */\n   public String getZoneId() {\n      return zoneId;\n   }\n\n   /**\n    * The ID of the pool.\n    */\n   public String getId() {\n      return id;\n   }\n\n   /**\n    * The name of the pool. ex. {@code My Pool}\n    */\n   public String getName() {\n      return name;\n   }\n\n   /**\n    * The dname of the pool. ex. {@code jclouds.org.}\n    */\n   public String getDName() {\n      return dname;\n   }\n\n   /**\n    * currently supported {@link ResourceRecord#getType() types} for round robin pools.\n    * \n    */\n   public static enum RecordType {\n      A(1),\n      AAAA(28);\n\n      @Override\n      public String toString() {\n         return String.valueOf(code);\n      }\n\n      private final int code;\n\n      private RecordType(int code) {\n         this.code = code;\n      }\n\n      public int getCode() {\n         return code;\n      }\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(zoneId, id, name, dname);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      RoundRobinPool that = RoundRobinPool.class.cast(obj);\n      return Objects.equal(this.zoneId, that.zoneId) && Objects.equal(this.id, that.id)\n            && Objects.equal(this.name, that.name) && Objects.equal(this.dname, that.dname);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"zoneId\", zoneId).add(\"id\", id).add(\"name\", name)\n            .add(\"dname\", dname).toString();\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().from(this);\n   }\n\n   public static final class Builder {\n      private String zoneId;\n      private String id;\n      private String name;\n      private String dname;\n\n      /**\n       * @see RoundRobinPool#getZoneId()\n       */\n      public Builder zoneId(String zoneId) {\n         this.zoneId = zoneId;\n         return this;\n      }\n\n      /**\n       * @see RoundRobinPool#getId()\n       */\n      public Builder id(String id) {\n         this.id = id;\n         return this;\n      }\n\n      /**\n       * @see RoundRobinPool#getName()\n       */\n      public Builder name(String name) {\n         this.name = name;\n         return this;\n      }\n\n      /**\n       * @see RoundRobinPool#getDName()\n       */\n      public Builder dname(String dname) {\n         this.dname = dname;\n         return this;\n      }\n\n      public RoundRobinPool build() {\n         return new RoundRobinPool(zoneId, id, name, dname);\n      }\n\n      public Builder from(RoundRobinPool in) {\n         return this.zoneId(in.zoneId).id(in.id).name(in.name).dname(in.dname);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/domain/Task.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.net.URI;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.Optional;\n\npublic final class Task {\n\n   private final String guid;\n   private final StatusCode statusCode;\n   private final Optional<String> message;\n   private final Optional<URI> resultUrl;\n\n   private Task(String guid, StatusCode statusCode, Optional<String> message, Optional<URI> resultUrl) {\n      this.guid = checkNotNull(guid, \"guid\");\n      this.statusCode = checkNotNull(statusCode, \"statusCode for %s\", guid);\n      this.message = checkNotNull(message, \"message for %s\", guid);\n      this.resultUrl = checkNotNull(resultUrl, \"resultUrl for %s\", guid);\n   }\n\n   /**\n    * The guid of the task. ex. {@statusCode 0b40c7dd-748d-4c49-8506-26f0c7d2ea9c}\n    */\n   public String getGuid() {\n      return guid;\n   }\n\n   /**\n    * The status statusCode of the task\n    */\n   public StatusCode getStatusCode() {\n      return statusCode;\n   }\n\n   /**\n    * The message pertaining to status\n    */\n   public Optional<String> getMessage() {\n      return message;\n   }\n\n   /**\n    * present when {@link #getClass()} is {@link StatusCode#COMPLETE}\n    */\n   public Optional<URI> getResultUrl() {\n      return resultUrl;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(guid);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      Task that = Task.class.cast(obj);\n      return Objects.equal(this.guid, that.guid);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).add(\"guid\", guid).add(\"statusCode\", statusCode).add(\"message\", message)\n            .add(\"resultUrl\", resultUrl).toString();\n   }\n\n   public static enum StatusCode {\n\n      PENDING, IN_PROCESS,\n      /**\n       * For a task with status statusCode {@statusCode COMPLETE}, copy and paste the resultUrl into a browser to pull down the\n       * file, which will be an attachment with the proper MIME type and extension.\n       */\n      COMPLETE, ERROR;\n\n      public static StatusCode fromValue(String statusCode) {\n         return valueOf(checkNotNull(statusCode, \"statusCode\"));\n      }\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().from(this);\n   }\n\n   public static final class Builder {\n      private String guid;\n      private StatusCode statusCode;\n      private Optional<String> message = Optional.absent();\n      private Optional<URI> resultUrl = Optional.absent();\n\n      /**\n       * @see Task#getGuid()\n       */\n      public Builder guid(String guid) {\n         this.guid = guid;\n         return this;\n      }\n\n      /**\n       * @see Task#getStatusCode()\n       */\n      public Builder statusCode(StatusCode statusCode) {\n         this.statusCode = statusCode;\n         return this;\n      }\n\n      /**\n       * @see Task#getMessage()\n       */\n      public Builder message(String message) {\n         this.message = Optional.fromNullable(message);\n         return this;\n      }\n\n      /**\n       * @see Task#getResultUrl()\n       */\n      public Builder resultUrl(URI resultUrl) {\n         this.resultUrl = Optional.fromNullable(resultUrl);\n         return this;\n      }\n\n      public Task build() {\n         return new Task(guid, statusCode, message, resultUrl);\n      }\n\n      public Builder from(Task in) {\n         return this.guid(in.guid).statusCode(in.statusCode).message(in.message.orNull()).resultUrl(in.resultUrl.orNull());\n      }\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/domain/TrafficControllerPool.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\n/**\n * Traffic Controller pools are used to create weighted {@code A} and {@code CNAME} records.\n */\npublic final class TrafficControllerPool {\n\n   private final String zoneId;\n   private final String id;\n   private final String name;\n   private final String dname;\n   private final int statusCode;\n   private final boolean failOverEnabled;\n   private final boolean probingEnabled;\n\n   private TrafficControllerPool(String zoneId, String id, String name, String dname, int statusCode,\n         boolean failOverEnabled, boolean probingEnabled) {\n      this.zoneId = checkNotNull(zoneId, \"zoneId\");\n      this.id = checkNotNull(id, \"id\");\n      this.name = checkNotNull(name, \"name for %s\", id);\n      this.dname = checkNotNull(dname, \"dname for %s\", id);\n      this.statusCode = statusCode;\n      this.failOverEnabled = failOverEnabled;\n      this.probingEnabled = probingEnabled;\n   }\n\n   /**\n    * The ID of the zone.\n    */\n   public String getZoneId() {\n      return zoneId;\n   }\n\n   /**\n    * The ID of the pool.\n    */\n   public String getId() {\n      return id;\n   }\n\n   /**\n    * The name of the pool. ex. {@code My Pool}\n    */\n   public String getName() {\n      return name;\n   }\n\n   /**\n    * The dname of the pool. ex. {@code jclouds.org.}\n    */\n   public String getDName() {\n      return dname;\n   }\n\n   /**\n    * status of the pool\n    */\n   public int getStatusCode() {\n      return statusCode;\n   }\n\n   /**\n    * {@code true} if the pool is active and serving records.\n    */\n   public boolean isFailOverEnabled() {\n      return failOverEnabled;\n   }\n\n   /**\n    * {@code true} indicates the pool is functioning normally. {@code false}\n    * indicates testing only—probing records and reporting results, but not\n    * acting on the results\n    */\n   public boolean isProbingEnabled() {\n      return probingEnabled;\n   }\n\n   /**\n    * currently supported {@link ResourceRecord#getType() types} for traffic\n    * controller pools.\n    * \n    */\n   public static enum RecordType {\n      // A/CNAME\n      IPV4(1),\n\n      // AAAA/CNAME\n      IPV6(28);\n\n      @Override\n      public String toString() {\n         return String.valueOf(code);\n      }\n\n      private final int code;\n\n      private RecordType(int code) {\n         this.code = code;\n      }\n\n      public int getCode() {\n         return code;\n      }\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(zoneId, id, name, dname);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      TrafficControllerPool that = TrafficControllerPool.class.cast(obj);\n      return Objects.equal(this.zoneId, that.zoneId) && Objects.equal(this.id, that.id)\n            && Objects.equal(this.name, that.name) && Objects.equal(this.dname, that.dname);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"zoneId\", zoneId).add(\"id\", id).add(\"name\", name)\n            .add(\"dname\", dname).add(\"status\", statusCode).add(\"failOverEnabled\", failOverEnabled)\n            .add(\"probingEnabled\", probingEnabled).toString();\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().from(this);\n   }\n\n   public static final class Builder {\n      private String zoneId;\n      private String id;\n      private String name;\n      private String dname;\n      private int statusCode;\n      private boolean failOverEnabled;\n      private boolean probingEnabled;\n\n      /**\n       * @see TrafficControllerPool#getZoneId()\n       */\n      public Builder zoneId(String zoneId) {\n         this.zoneId = zoneId;\n         return this;\n      }\n\n      /**\n       * @see TrafficControllerPool#getId()\n       */\n      public Builder id(String id) {\n         this.id = id;\n         return this;\n      }\n\n      /**\n       * @see TrafficControllerPool#getName()\n       */\n      public Builder name(String name) {\n         this.name = name;\n         return this;\n      }\n\n      /**\n       * @see TrafficControllerPool#getDName()\n       */\n      public Builder dname(String dname) {\n         this.dname = dname;\n         return this;\n      }\n\n      /**\n       * @see TrafficControllerPool#getStatusCode()\n       */\n      public Builder statusCode(int statusCode) {\n         this.statusCode = statusCode;\n         return this;\n      }\n      \n      /**\n       * @see TrafficControllerPool#isFailOverEnabled()\n       */\n      public Builder failOverEnabled(boolean failOverEnabled) {\n         this.failOverEnabled = failOverEnabled;\n         return this;\n      }\n\n      /**\n       * @see TrafficControllerPool#isProbingEnabled()\n       */\n      public Builder probingEnabled(boolean probingEnabled) {\n         this.probingEnabled = probingEnabled;\n         return this;\n      }\n\n      public TrafficControllerPool build() {\n         return new TrafficControllerPool(zoneId, id, name, dname, statusCode, failOverEnabled, probingEnabled);\n      }\n\n      public Builder from(TrafficControllerPool in) {\n         return this.zoneId(in.zoneId).id(in.id).name(in.name).dname(in.dname).statusCode(in.statusCode)\n               .failOverEnabled(in.failOverEnabled).probingEnabled(in.probingEnabled);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/domain/TrafficControllerPoolRecord.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.Objects;\n\npublic class TrafficControllerPoolRecord {\n\n   public static TrafficControllerPoolRecord createA(String rdata) {\n      return new TrafficControllerPoolRecord(\"A\", rdata);\n   }\n\n   public static TrafficControllerPoolRecord createCNAME(String rdata) {\n      return new TrafficControllerPoolRecord(\"CNAME\", rdata);\n   }\n   public static TrafficControllerPoolRecord create(String type, String rdata) {\n      return new TrafficControllerPoolRecord(type, rdata);\n   }\n\n   private final String type;\n   private final String rdata;\n\n   private TrafficControllerPoolRecord(String type, String rdata) {\n      this.type = checkNotNull(type, \"type\");\n      this.rdata = checkNotNull(rdata, \"rdata\");\n   }\n\n   /**\n    * the type of the record, either {@code A} or {@code CNAME}\n    */\n   public String getType() {\n      return type;\n   }\n\n   /**\n    * address or cname this points to. ex. {@code jclouds.org.} or\n    * {@code 1.2.3.4}\n    */\n   public String getRData() {\n      return rdata;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(type, rdata);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      TrafficControllerPoolRecord that = TrafficControllerPoolRecord.class.cast(obj);\n      return equal(this.type, that.type) && equal(this.rdata, that.rdata);\n   }\n\n   @Override\n   public String toString() {\n      return toStringHelper(this).add(\"type\", type).add(\"rdata\", rdata).toString();\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/domain/TrafficControllerPoolRecordDetail.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.domain;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\npublic final class TrafficControllerPoolRecordDetail {\n\n   private final String id;\n   private final String poolId;\n   private final TrafficControllerPoolRecord record;\n   private final int weight;\n   private final int priority;\n   private final String forceAnswer;\n   private final boolean probingEnabled;\n   private final Status status;\n   private final boolean serving;\n   private final String description;\n\n   private TrafficControllerPoolRecordDetail(String id, String poolId, TrafficControllerPoolRecord record, int weight,\n         int priority, String forceAnswer, boolean probingEnabled, Status status, boolean serving, String description) {\n      this.id = checkNotNull(id, \"id\");\n      this.poolId = checkNotNull(poolId, \"poolId for %s\", id);\n      this.record = checkNotNull(record, \"record for %s\", poolId);\n      checkArgument(weight >= 0, \"weight of %s must be >= 0\", id);\n      this.weight = weight;\n      checkArgument(priority >= 0, \"priority of %s must be >= 0\", id);\n      this.priority = priority;\n      this.forceAnswer = checkNotNull(forceAnswer, \"forceAnswer for %s\", poolId);\n      this.probingEnabled = probingEnabled;\n      this.status = checkNotNull(status, \"status for %s\", poolId);\n      this.serving = serving;\n      this.description = checkNotNull(description, \"description for %s\", poolId);\n   }\n\n   /**\n    * The ID of the zone.\n    */\n   public String getId() {\n      return id;\n   }\n\n   /**\n    * The pool this record belongs to.\n    */\n   public String getPoolId() {\n      return poolId;\n   }\n\n   /**\n    * the record pointed to\n    */\n   public TrafficControllerPoolRecord getRecord() {\n      return record;\n   }\n\n   /**\n    * 0 or even numbers from 2–100. Determines the traffic load to send to each\n    * server in a Traffic Controller pool. The value 0 indicates that Traffic\n    * Controller always serves the record.\n    */\n   public int getWeight() {\n      return weight;\n   }\n\n   /**\n    * the default value is 1. The value 0 is the special All Fail priority.\n    */\n   public int getPriority() {\n      return priority;\n   }\n\n   public String getForceAnswer() {\n      return forceAnswer;\n   }\n\n   public boolean isProbingEnabled() {\n      return probingEnabled;\n   }\n\n   /**\n    * status of the record\n    */\n   public Status getStatus() {\n      return status;\n   }\n\n   public boolean isServing() {\n      return serving;\n   }\n\n   /**\n    * description of the record\n    */\n   public String getDescription() {\n      return description;\n   }\n\n   public static enum Status {\n\n      OK, WARNING, CRITICAL, FAILURE, DISABLED, UNRECOGNIZED;\n\n      public static Status fromValue(String status) {\n         try {\n            return valueOf(checkNotNull(status, \"status\").toUpperCase());\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, poolId);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      TrafficControllerPoolRecordDetail that = TrafficControllerPoolRecordDetail.class.cast(obj);\n      return Objects.equal(this.id, that.id) && Objects.equal(this.poolId, that.poolId);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).add(\"id\", id).add(\"poolId\", poolId).add(\"record\", record)\n            .add(\"weight\", weight).add(\"priority\", priority).add(\"forceAnswer\", forceAnswer)\n            .add(\"probingEnabled\", probingEnabled).add(\"status\", status).add(\"serving\", serving)\n            .add(\"description\", description).toString();\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().from(this);\n   }\n\n   public static final class Builder {\n      private String id;\n      private String poolId;\n      private TrafficControllerPoolRecord record;\n      private int weight;\n      private int priority;\n      private String forceAnswer;\n      private boolean probingEnabled;\n      private Status status;\n      private boolean serving;\n      private String description;\n\n      /**\n       * @see TrafficControllerPoolRecordDetail#getId()\n       */\n      public Builder id(String id) {\n         this.id = id;\n         return this;\n      }\n\n      /**\n       * @see TrafficControllerPoolRecordDetail#getPoolId()\n       */\n      public Builder poolId(String poolId) {\n         this.poolId = poolId;\n         return this;\n      }\n\n      /**\n       * @see TrafficControllerPoolRecordDetail#getRecord()\n       */\n      public Builder record(TrafficControllerPoolRecord record) {\n         this.record = record;\n         return this;\n      }\n\n      /**\n       * @see TrafficControllerPoolRecordDetail#getWeight()\n       */\n      public Builder weight(int weight) {\n         this.weight = weight;\n         return this;\n      }\n\n      /**\n       * @see TrafficControllerPoolRecordDetail#getPriority()\n       */\n      public Builder priority(int priority) {\n         this.priority = priority;\n         return this;\n      }\n\n      /**\n       * @see TrafficControllerPoolRecordDetail#getForceAnswer()\n       */\n      public Builder forceAnswer(String forceAnswer) {\n         this.forceAnswer = forceAnswer;\n         return this;\n      }\n\n      /**\n       * @see TrafficControllerPoolRecordDetail#isProbingEnabled()\n       */\n      public Builder probingEnabled(boolean probingEnabled) {\n         this.probingEnabled = probingEnabled;\n         return this;\n      }\n\n      /**\n       * @see TrafficControllerPoolRecordDetail#getStatus()\n       */\n      public Builder status(Status status) {\n         this.status = status;\n         return this;\n      }\n\n      /**\n       * @see TrafficControllerPoolRecordDetail#isServing()\n       */\n      public Builder serving(boolean serving) {\n         this.serving = serving;\n         return this;\n      }\n\n      /**\n       * @see TrafficControllerPoolRecordDetail#getDescription()\n       */\n      public Builder description(String description) {\n         this.description = description;\n         return this;\n      }\n\n      public TrafficControllerPoolRecordDetail build() {\n         return new TrafficControllerPoolRecordDetail(id, poolId, record, weight, priority, forceAnswer,\n               probingEnabled, status, serving, description);\n      }\n\n      public Builder from(TrafficControllerPoolRecordDetail in) {\n         return this.id(in.id).poolId(in.poolId).weight(in.weight).record(in.record).priority(in.priority)\n               .forceAnswer(in.forceAnswer).probingEnabled(in.probingEnabled).status(in.status).serving(in.serving)\n               .description(in.description);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/domain/UpdatePoolRecord.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.domain;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.Objects;\n\n/**\n * holds updates for a record\n */\npublic final class UpdatePoolRecord {\n\n   /**\n    * @param spec what to prime updates from\n    * @param rdata new value to point to.\n    */\n   public static UpdatePoolRecord pointingTo(PoolRecordSpec spec, String rdata) {\n      return new Builder().from(spec).rdata(rdata).build();\n   }\n\n   private final String rdata;\n   private final String mode;\n   private final int priority;\n   private final int weight;\n   private final int failOverDelay;\n   private final int threshold;\n   private final int ttl;\n\n   private UpdatePoolRecord(String rdata, String mode, int priority, int weight, int failOverDelay, int threshold,\n         int ttl) {\n      this.rdata = checkNotNull(rdata, \"rdata\");\n      this.mode = checkNotNull(mode, \"mode for %s\", rdata);\n      this.priority = priority;\n      this.weight = weight;\n      checkArgument(weight >= 0, \"weight of %s must be >= 0\", rdata);\n      this.failOverDelay = failOverDelay;\n      checkArgument(failOverDelay >= 0, \"failOverDelay of %s must be >= 0\", rdata);\n      this.threshold = threshold;\n      checkArgument(threshold >= 0, \"threshold of %s must be >= 0\", rdata);\n      this.ttl = ttl;\n      checkArgument(ttl >= 0, \"ttl of %s must be >= 0\", rdata);\n   }\n\n   /**\n    * correlates to {@link TrafficControllerPoolRecord#getRData()}\n    */\n   public String getRData() {\n      return rdata;\n   }\n\n   /**\n    * correlates to {@link PoolRecordSpec#getState()}\n    */\n   public String getMode() {\n      return mode;\n   }\n\n   /**\n    * correlates to {@link PoolRecordSpec#getPriority()}\n    */\n   public int getPriority() {\n      return priority;\n   }\n\n   /**\n    * correlates to {@link PoolRecordSpec#getWeight()}\n    */\n   public int getWeight() {\n      return weight;\n   }\n\n   /**\n    * correlates to {@link PoolRecordSpec#getFailOverDelay()}\n    */\n   public int getFailOverDelay() {\n      return failOverDelay;\n   }\n\n   /**\n    * correlates to {@link PoolRecordSpec#getThreshold()}\n    */\n   public int getThreshold() {\n      return threshold;\n   }\n\n   /**\n    * correlates to {@link PoolRecordSpec#getTTL()}\n    */\n   public int getTTL() {\n      return ttl;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(rdata, mode, priority, weight, failOverDelay, threshold, ttl);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      UpdatePoolRecord that = UpdatePoolRecord.class.cast(obj);\n      return equal(this.rdata, that.rdata) && equal(this.mode, that.mode) && equal(this.priority, that.priority)\n            && equal(this.weight, that.weight) && equal(this.failOverDelay, that.failOverDelay)\n            && equal(this.threshold, that.threshold) && equal(this.ttl, that.ttl);\n   }\n\n   @Override\n   public String toString() {\n      return toStringHelper(this).add(\"rdata\", rdata).add(\"mode\", mode).add(\"priority\", priority)\n            .add(\"weight\", weight).add(\"failOverDelay\", failOverDelay).add(\"threshold\", threshold).add(\"ttl\", ttl)\n            .toString();\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return new Builder().from(this);\n   }\n\n   public static final class Builder {\n      private String rdata;\n      private String mode;\n      private int priority;\n      private int weight;\n      private int failOverDelay;\n      private int threshold;\n      private int ttl;\n\n      /**\n       * @see UpdatePoolRecord#getRData()\n       */\n      public Builder rdata(String rdata) {\n         this.rdata = rdata;\n         return this;\n      }\n\n      /**\n       * @see UpdatePoolRecord#getMode()\n       */\n      public Builder mode(String mode) {\n         this.mode = mode;\n         return this;\n      }\n\n      /**\n       * @see UpdatePoolRecord#getPriority()\n       */\n      public Builder priority(int priority) {\n         this.priority = priority;\n         return this;\n      }\n\n      /**\n       * @see UpdatePoolRecord#getWeight()\n       */\n      public Builder weight(int weight) {\n         this.weight = weight;\n         return this;\n      }\n\n      /**\n       * @see UpdatePoolRecord#getFailOverDelay()\n       */\n      public Builder failOverDelay(int failOverDelay) {\n         this.failOverDelay = failOverDelay;\n         return this;\n      }\n\n      /**\n       * @see UpdatePoolRecord#getThreshold()\n       */\n      public Builder threshold(int threshold) {\n         this.threshold = threshold;\n         return this;\n      }\n\n      /**\n       * @see UpdatePoolRecord#getTTL()\n       */\n      public Builder ttl(int ttl) {\n         this.ttl = ttl;\n         return this;\n      }\n\n      public UpdatePoolRecord build() {\n         return new UpdatePoolRecord(rdata, mode, priority, weight, failOverDelay, threshold, ttl);\n      }\n\n      public Builder from(PoolRecordSpec in) {\n         return this.mode(in.getState()).weight(in.getWeight()).failOverDelay(in.getFailOverDelay())\n               .threshold(in.getThreshold()).ttl(in.getTTL());\n      }\n\n      public Builder from(TrafficControllerPoolRecordDetail in) {\n         return this.weight(in.getWeight()).rdata(in.getRecord().getRData()).priority(in.getPriority());\n      }\n\n      public Builder from(UpdatePoolRecord in) {\n         return this.rdata(in.rdata).mode(in.mode).priority(in.priority).weight(in.weight)\n               .failOverDelay(in.failOverDelay).threshold(in.threshold).ttl(in.ttl);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/domain/Zone.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.domain;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.Optional;\n\npublic final class Zone {\n\n   private final String id;\n   private final String name;\n   private final Type type;\n   private final int typeCode;\n   private final String accountId;\n   private final String ownerId;\n   private final DNSSECStatus dnssecStatus;\n   private final Optional<String> primarySrc;\n\n   private Zone(String id, String name, Type type, int typeCode, String accountId, String ownerId,\n         DNSSECStatus dnssecStatus, Optional<String> primarySrc) {\n      this.id = checkNotNull(id, \"id\");\n      this.name = checkNotNull(name, \"name for %s\", id);\n      checkArgument(typeCode >= 0, \"typeCode of %s must be >= 0\", id);\n      this.typeCode = typeCode;\n      this.type = checkNotNull(type, \"type for %s\", name);\n      this.accountId = checkNotNull(accountId, \"accountId for %s\", name);\n      this.ownerId = checkNotNull(ownerId, \"ownerId for %s\", name);\n      this.dnssecStatus = checkNotNull(dnssecStatus, \"dnssecStatus for %s\", name);\n      this.primarySrc = checkNotNull(primarySrc, \"primarySrc for %s\", name);\n   }\n\n   /**\n    * The ID of the zone.\n    */\n   public String getId() {\n      return id;\n   }\n\n   /**\n    * The name of the domain. ex. {@code jclouds.org.} or {@code 0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa.}\n    */\n   public String getName() {\n      return name;\n   }\n\n   /**\n    * The type of the zone\n    */\n   public Type getType() {\n      return type;\n   }\n\n   /**\n    * The type of the zone\n    */\n   public int getTypeCode() {\n      return typeCode;\n   }\n\n   /**\n    * The account which this domain is a part of\n    */\n   public String getAccountId() {\n      return accountId;\n   }\n\n   /**\n    * The user that created this zone.\n    */\n   public String getOwnerId() {\n      return ownerId;\n   }\n\n   /**\n    * signed status of the zone\n    */\n   public DNSSECStatus getDNSSECStatus() {\n      return dnssecStatus;\n   }\n\n   /**\n    * present when {@link #getType} is {@link Type#SECONDARY}.  ex. {@code 192.168.1.23}\n    */\n   public Optional<String> getPrimarySrc() {\n      return primarySrc;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, name, accountId);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      Zone that = Zone.class.cast(obj);\n      return Objects.equal(this.id, that.id) && Objects.equal(this.name, that.name)\n            && Objects.equal(this.accountId, that.accountId);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"id\", id).add(\"name\", name).add(\"type\", type)\n            .add(\"accountId\", accountId).add(\"ownerId\", ownerId).add(\"dnssecStatus\", dnssecStatus)\n            .add(\"primarySrc\", primarySrc.orNull()).toString();\n   }\n\n   public static enum Type {\n\n      PRIMARY(1), SECONDARY(2), ALIAS(3), UNRECOGNIZED(-1);\n\n      private final int code;\n\n      Type(int code) {\n         this.code = code;\n      }\n\n      public int getCode() {\n         return code;\n      }\n\n      @Override\n      public String toString() {\n         return this.name().toLowerCase();\n      }\n\n      public static Type fromValue(String type) {\n         return fromValue(Integer.parseInt(checkNotNull(type, \"type\")));\n      }\n\n      public static Type fromValue(int code) {\n         switch (code) {\n         case 1:\n            return PRIMARY;\n         case 2:\n            return SECONDARY;\n         case 3:\n            return ALIAS;\n         default:\n            return UNRECOGNIZED;\n         }\n      }\n   }\n\n   public static enum DNSSECStatus {\n\n      SIGNED, UNSIGNED, UNRECOGNIZED;\n\n      public static DNSSECStatus fromValue(String status) {\n         try {\n            return valueOf(checkNotNull(status, \"status\"));\n         } catch (IllegalArgumentException e) {\n            return UNRECOGNIZED;\n         }\n      }\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().from(this);\n   }\n\n   public static final class Builder {\n      private String id;\n      private String name;\n      private Type type;\n      private int typeCode = -1;\n      private String accountId;\n      private String ownerId;\n      private DNSSECStatus dnssecStatus;\n      private Optional<String> primarySrc = Optional.absent();\n\n      /**\n       * @see Zone#getId()\n       */\n      public Builder id(String id) {\n         this.id = id;\n         return this;\n      }\n\n      /**\n       * @see Zone#getName()\n       */\n      public Builder name(String name) {\n         this.name = name;\n         return this;\n      }\n\n      /**\n       * @see Zone#getType()\n       */\n      public Builder type(Type type) {\n         this.type = type;\n         return this;\n      }\n\n      /**\n       * @see Zone#getTypeCode()\n       */\n      public Builder typeCode(int typeCode) {\n         this.typeCode = typeCode;\n         this.type = Type.fromValue(typeCode);\n         return this;\n      }\n\n      /**\n       * @see Zone#getAccountId()\n       */\n      public Builder accountId(String accountId) {\n         this.accountId = accountId;\n         return this;\n      }\n\n      /**\n       * @see Zone#getOwnerId()\n       */\n      public Builder ownerId(String ownerId) {\n         this.ownerId = ownerId;\n         return this;\n      }\n\n      /**\n       * @see Zone#getDNSSECStatus()\n       */\n      public Builder dnssecStatus(DNSSECStatus dnssecStatus) {\n         this.dnssecStatus = dnssecStatus;\n         return this;\n      }\n\n      /**\n       * @see Zone#getPrimarySrc()\n       */\n      public Builder primarySrc(String primarySrc) {\n         this.primarySrc = Optional.fromNullable(primarySrc);\n         return this;\n      }\n\n      public Zone build() {\n         return new Zone(id, name, type, typeCode, accountId, ownerId, dnssecStatus, primarySrc);\n      }\n\n      public Builder from(Zone in) {\n         return this.id(in.id).name(in.name).typeCode(in.typeCode).type(in.type).accountId(in.accountId)\n               .ownerId(in.ownerId).dnssecStatus(in.dnssecStatus).primarySrc(in.primarySrc.orNull());\n      }\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/domain/ZoneProperties.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.domain;\n\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Date;\n\nimport org.jclouds.ultradns.ws.domain.Zone.Type;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\npublic final class ZoneProperties {\n\n   private final String name;\n   private final Type type;\n   private final int typeCode;\n   private final Date modified;\n   private final int resourceRecordCount;\n\n   private ZoneProperties(String name, Type type, int typeCode, Date modified, int resourceRecordCount) {\n      this.name = checkNotNull(name, \"name\");\n      checkArgument(typeCode >= 0, \"typeCode of %s must be >= 0\", name);\n      this.typeCode = typeCode;\n      this.type = checkNotNull(type, \"type for %s\", name);\n      this.modified = checkNotNull(modified, \"modified for %s\", name);\n      this.resourceRecordCount = resourceRecordCount;\n   }\n\n   /**\n    * The name of the domain. ex. {@code jclouds.org.} or {@code 0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa.}\n    */\n   public String getName() {\n      return name;\n   }\n\n   /**\n    * The type of the zone\n    */\n   public Type getType() {\n      return type;\n   }\n\n   /**\n    * The type of the zone\n    */\n   public int getTypeCode() {\n      return typeCode;\n   }\n\n   /**\n    * Last time the zone was modified\n    */\n   public Date getModified() {\n      return modified;\n   }\n\n   /**\n    * The count of records in this zone.\n    */\n   public int getResourceRecordCount() {\n      return resourceRecordCount;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(name);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null || getClass() != obj.getClass())\n         return false;\n      ZoneProperties that = ZoneProperties.class.cast(obj);\n      return Objects.equal(this.name, that.name);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).add(\"name\", name).add(\"type\", type)\n            .add(\"modified\", modified).add(\"resourceRecordCount\", resourceRecordCount).toString();\n   }\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return builder().from(this);\n   }\n\n   public static final class Builder {\n      private String name;\n      private Type type;\n      private int typeCode = -1;\n      private Date modified;\n      private int resourceRecordCount;\n\n      /**\n       * @see ZoneProperties#getName()\n       */\n      public Builder name(String name) {\n         this.name = name;\n         return this;\n      }\n\n      /**\n       * @see ZoneProperties#getType()\n       */\n      public Builder type(Type type) {\n         this.type = type;\n         return this;\n      }\n\n      /**\n       * @see ZoneProperties#getTypeCode()\n       */\n      public Builder typeCode(int typeCode) {\n         this.typeCode = typeCode;\n         this.type = Type.fromValue(typeCode);\n         return this;\n      }\n\n      /**\n       * @see ZoneProperties#getModified()\n       */\n      public Builder modified(Date modified) {\n         this.modified = modified;\n         return this;\n      }\n\n      /**\n       * @see ZoneProperties#getResourceRecordCount()\n       */\n      public Builder resourceRecordCount(int resourceRecordCount) {\n         this.resourceRecordCount = resourceRecordCount;\n         return this;\n      }\n\n      public ZoneProperties build() {\n         return new ZoneProperties(name, type, typeCode, modified, resourceRecordCount);\n      }\n\n      public Builder from(ZoneProperties in) {\n         return this.name(in.name).typeCode(in.typeCode).type(in.type).modified(in.modified)\n               .resourceRecordCount(in.resourceRecordCount);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/features/DirectionalGroupApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.POST;\n\nimport org.jclouds.Fallbacks.EmptyFluentIterableOnNotFoundOr404;\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.jclouds.rest.annotations.BinderParam;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.VirtualHost;\nimport org.jclouds.rest.annotations.XMLResponseParser;\nimport org.jclouds.ultradns.ws.binders.DirectionalGroupCoordinatesToXML;\nimport org.jclouds.ultradns.ws.domain.AccountLevelGroup;\nimport org.jclouds.ultradns.ws.domain.DirectionalGroup;\nimport org.jclouds.ultradns.ws.domain.DirectionalGroupCoordinates;\nimport org.jclouds.ultradns.ws.domain.DirectionalPoolRecordDetail;\nimport org.jclouds.ultradns.ws.filters.SOAPWrapWithPasswordAuth;\nimport org.jclouds.ultradns.ws.xml.AccountLevelGroupsHandler;\nimport org.jclouds.ultradns.ws.xml.DirectionalGroupHandler;\nimport org.jclouds.ultradns.ws.xml.DirectionalPoolRecordDetailListHandler;\nimport org.jclouds.ultradns.ws.xml.ItemListHandler;\n\nimport com.google.common.collect.FluentIterable;\n\n/**\n * @see <a href=\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01?wsdl\" />\n * @see <a href=\"https://www.ultradns.net/api/NUS_API_XML_SOAP.pdf\" />\n */\n@RequestFilters(SOAPWrapWithPasswordAuth.class)\n@VirtualHost\npublic interface DirectionalGroupApi {\n\n   /**\n    * returns the regions and name of the specified directional group or null,\n    * if not found.\n    * \n    * @param groupId\n    *           the {@link DirectionalGroup#getId() id} of the group\n    */\n   @Named(\"getDirectionalDNSGroupDetails\")\n   @POST\n   @XMLResponseParser(DirectionalGroupHandler.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   @Payload(\"<v01:getDirectionalDNSGroupDetails><GroupId>{GroupId}</GroupId></v01:getDirectionalDNSGroupDetails>\")\n   @Nullable\n   DirectionalGroup get(@PayloadParam(\"GroupId\") String groupId);\n\n   /**\n    * Returns all account-level groups.\n    * \n    */\n   @Named(\"getAccountLevelDirectionalGroupsOfZone\")\n   @POST\n   @XMLResponseParser(AccountLevelGroupsHandler.class)\n   @Payload(\"<v01:getAccountLevelDirectionalGroups><accountId>{accountId}</accountId><GroupType /></v01:getAccountLevelDirectionalGroups>\")\n   FluentIterable<AccountLevelGroup> listAccountLevelGroups();\n\n   /**\n    * Returns all the directional pool records in the account-level group.\n    * \n    * @param groupId\n    *           the id of the account-level group containing the records.\n    * @throws ResourceNotFoundException\n    *            if the group doesn't exist\n    */\n   @Named(\"getDirectionalDNSRecordsForAcctLvlGroup\")\n   @POST\n   @XMLResponseParser(DirectionalPoolRecordDetailListHandler.class)\n   @Payload(\"<v01:getDirectionalDNSRecordsForAcctLvlGroup><groupId>{groupId}</groupId></v01:getDirectionalDNSRecordsForAcctLvlGroup>\")\n   FluentIterable<DirectionalPoolRecordDetail> listRecordsByAccountLevelGroup(\n         @PayloadParam(\"groupId\") String groupId) throws ResourceNotFoundException;\n\n   /**\n    * Returns directional group names visible to the account for the fully\n    * qualified {@link hostName} and {@link rrType}\n    * \n    * @param accountId\n    *           the account where the groups exist\n    * @param hostName\n    *           fully qualified hostname including the trailing dot.\n    * @param rrType\n    *           {@link RecordType type} value of the existing records.\n    * @return empty if there are not groups for the specified host and type\n    */\n   @Named(\"getAvailableGroups\")\n   @POST\n   @XMLResponseParser(ItemListHandler.class)\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   @Payload(\"<v01:getAvailableGroups><poolName>{hostName}</poolName><poolRecordType>{rrType}</poolRecordType><accountID>{accountId}</accountID><groupType /></v01:getAvailableGroups>\")\n   FluentIterable<String> listGroupNamesByDNameAndType(\n         @PayloadParam(\"hostName\") String hostName, @PayloadParam(\"rrType\") int rrType);\n\n   /**\n    * Returns all the directional pool records in the pool-level group.\n    * \n    * @param group\n    *           the zone, record name, record type, and group name\n    * @throws ResourceNotFoundException\n    *            if the group doesn't exist\n    */\n   @Named(\"getDirectionalDNSRecordsForGroup\")\n   @POST\n   @XMLResponseParser(DirectionalPoolRecordDetailListHandler.class)\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   FluentIterable<DirectionalPoolRecordDetail> listRecordsByGroupCoordinates(\n         @BinderParam(DirectionalGroupCoordinatesToXML.class) DirectionalGroupCoordinates group)\n         throws ResourceNotFoundException;\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/features/DirectionalPoolApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.features;\n\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.POST;\n\nimport org.jclouds.Fallbacks.EmptyFluentIterableOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.ParamParser;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.VirtualHost;\nimport org.jclouds.rest.annotations.XMLResponseParser;\nimport org.jclouds.ultradns.ws.UltraDNSWSExceptions.DirectionalGroupOverlapException;\nimport org.jclouds.ultradns.ws.UltraDNSWSExceptions.ResourceAlreadyExistsException;\nimport org.jclouds.ultradns.ws.binders.DirectionalRecordAndGeoGroupToXML;\nimport org.jclouds.ultradns.ws.domain.DirectionalGroup;\nimport org.jclouds.ultradns.ws.domain.DirectionalPool;\nimport org.jclouds.ultradns.ws.domain.DirectionalPoolRecord;\nimport org.jclouds.ultradns.ws.domain.DirectionalPoolRecordDetail;\nimport org.jclouds.ultradns.ws.filters.SOAPWrapWithPasswordAuth;\nimport org.jclouds.ultradns.ws.internal.DirectionalPoolRecordTypeToString;\nimport org.jclouds.ultradns.ws.xml.DirectionalPoolListHandler;\nimport org.jclouds.ultradns.ws.xml.DirectionalPoolRecordDetailListHandler;\nimport org.jclouds.ultradns.ws.xml.ElementTextHandler;\n\nimport com.google.common.collect.FluentIterable;\n\n/**\n * @see <a href=\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01?wsdl\" />\n * @see <a href=\"https://www.ultradns.net/api/NUS_API_XML_SOAP.pdf\" />\n */\n@RequestFilters(SOAPWrapWithPasswordAuth.class)\n@VirtualHost\npublic interface DirectionalPoolApi {\n\n   /**\n    * Returns all directional pools in the zone.\n    * \n    * @throws ResourceNotFoundException\n    *            if the zone doesn't exist\n    */\n   @Named(\"getDirectionalPoolsOfZone\")\n   @POST\n   @XMLResponseParser(DirectionalPoolListHandler.class)\n   @Payload(\"<v01:getDirectionalPoolsOfZone><zoneName>{zoneName}</zoneName></v01:getDirectionalPoolsOfZone>\")\n   FluentIterable<DirectionalPool> list() throws ResourceNotFoundException;\n\n   /**\n    * Returns all the directional pool records in the zone with the fully\n    * qualified {@link hostName} and {@link rrType}\n    * \n    * @param dname\n    *           fully qualified hostname including the trailing dot.\n    * @param rrType\n    *           {@link RecordType type} value of the existing records.\n    * @return empty if there are not pools for the specified host or no records\n    *         exist for the type.\n    * @throws ResourceNotFoundException\n    *            if the zone doesn't exist\n    * @see RecordType#getCode()\n    */\n   @Named(\"getDirectionalDNSRecordsForHost\")\n   @POST\n   @XMLResponseParser(DirectionalPoolRecordDetailListHandler.class)\n   @Fallback(EmptyFluentIterableOnNotFoundOr404.class)\n   @Payload(\"<v01:getDirectionalDNSRecordsForHost><zoneName>{zoneName}</zoneName><hostName>{hostName}</hostName><poolRecordType>{poolRecordType}</poolRecordType></v01:getDirectionalDNSRecordsForHost>\")\n   FluentIterable<DirectionalPoolRecordDetail> listRecordsByDNameAndType(@PayloadParam(\"hostName\") String dname,\n         @PayloadParam(\"poolRecordType\") int rrType) throws ResourceNotFoundException;\n\n   /**\n    * creates a directional pool for {@code A} and {@code CNAME} (ipv4) records\n    * \n    * @param name\n    *           {@link DirectionalPool#getName() description} of the Geo pool\n    * @param dname\n    *           {@link DirectionalPool#getDName() dname} of the Geo pool {ex.\n    *           www.jclouds.org.}\n    * @param rrType\n    *           {@link RecordType type} value for the records added to this\n    *           pool..\n    * @return the {@link DirectionalPool#getId() id} of the new pool\n    * @throws ResourceAlreadyExistsException\n    *            if a pool already exists with the same attrs\n    */\n   @Named(\"addDirectionalPool\")\n   @POST\n   @XMLResponseParser(ElementTextHandler.DirPoolID.class)\n   @Payload(\"<v01:addDirectionalPool><transactionID /><AddDirectionalPoolData dirPoolType=\\\"GEOLOCATION\\\" poolRecordType=\\\"{poolRecordType}\\\" zoneName=\\\"{zoneName}\\\" hostName=\\\"{hostName}\\\" description=\\\"{description}\\\"/></v01:addDirectionalPool>\")\n   String createForDNameAndType(@PayloadParam(\"description\") String name, @PayloadParam(\"hostName\") String dname,\n         @PayloadParam(\"poolRecordType\") @ParamParser(DirectionalPoolRecordTypeToString.class) int rrType)\n         throws ResourceAlreadyExistsException;\n\n   /**\n    * creates a resource record in the pool.\n    * \n    * @param poolId\n    *           pool to create the record in.\n    * @param toCreate\n    *           the new record to create.\n    * @param group\n    *           geo groups associated. Use the\n    *           {@link UltraDNSWSApi#getRegionsByIdAndName()} to obtain the\n    *           regionName and territoryNames. To specify all of a region’s\n    *           territories, use\n    *           {@link DirectionalGroup.Builder#mapRegion(String)}\n    * @return the {@link DirectionalPoolRecordDetail#getId() id} of the new record\n    * @throws ResourceAlreadyExistsException\n    *            if a record already exists with the same attrs\n    */\n   @Named(\"addDirectionalPoolRecord\")\n   @POST\n   @XMLResponseParser(ElementTextHandler.DirectionalPoolRecordID.class)\n   @MapBinder(DirectionalRecordAndGeoGroupToXML.class)\n   String addRecordIntoNewGroup(@PayloadParam(\"poolId\") String poolId,\n         @PayloadParam(\"record\") DirectionalPoolRecord toCreate, @PayloadParam(\"group\") DirectionalGroup group)\n         throws ResourceAlreadyExistsException;\n\n   /**\n    * creates a resource record in the pool.\n    * \n    * @param poolId\n    *           pool to create the record in.\n    * @param toCreate\n    *           the new record to create.\n    * @param groupId\n    *           existing group from another record of the same dname and type.\n    *           For example\n    *           {@link DirectionalPoolRecordDetail#getGeolocationGroup()} or\n    *           {@link DirectionalPoolRecordDetail#getGroup()}.\n    * @return the {@link DirectionalPoolRecordDetail#getId() id} of the new record\n    * @throws ResourceAlreadyExistsException\n    *            if a record already exists with the same attrs\n    */\n   @Named(\"addDirectionalPoolRecord\")\n   @POST\n   @XMLResponseParser(ElementTextHandler.DirectionalPoolRecordID.class)\n   @MapBinder(DirectionalRecordAndGeoGroupToXML.class)\n   String addRecordIntoExistingGroup(@PayloadParam(\"poolId\") String poolId,\n         @PayloadParam(\"record\") DirectionalPoolRecord toCreate, @PayloadParam(\"groupId\") String groupId)\n         throws ResourceAlreadyExistsException;\n\n   /**\n    * creates a resource record in the pool, creating and assigning it to the\n    * special \"non configured group\".\n    * \n    * @param poolId\n    *           pool to create the record in.\n    * @param toCreate\n    *           the new record to create.\n    * @return the {@link DirectionalPoolRecordDetail#getId() id} of the new record\n    * @throws ResourceAlreadyExistsException\n    *            if a record already exists with the same attrs\n    */\n   @Named(\"addDirectionalPoolRecord\")\n   @POST\n   @XMLResponseParser(ElementTextHandler.DirectionalPoolRecordID.class)\n   @MapBinder(DirectionalRecordAndGeoGroupToXML.class)\n   String addFirstRecordInNonConfiguredGroup(@PayloadParam(\"poolId\") String poolId,\n         @PayloadParam(\"record\") DirectionalPoolRecord toCreate) throws ResourceAlreadyExistsException;\n\n   /**\n    * updates such as ttl or rdata for an existing directional record.\n    * \n    * @param recordId\n    *           id of the record to update\n    * @param update\n    *           the updated record.\n    * @throws ResourceNotFoundException\n    *            if the record doesn't exist\n    */\n   @Named(\"updateDirectionalPoolRecord\")\n   @POST\n   @MapBinder(DirectionalRecordAndGeoGroupToXML.class)\n   void updateRecord(@PayloadParam(\"dirPoolRecordId\") String recordId,\n         @PayloadParam(\"record\") DirectionalPoolRecord update) throws ResourceNotFoundException;\n\n   /**\n    * updates the geo groups of an existing directional record.\n    * \n    * @param recordId\n    *           id of the record to update\n    * @param update\n    *           the updated record.\n    * @param group\n    *           geo groups associated.\n    * @throws ResourceNotFoundException\n    *            if the record doesn't exist\n    * @throws DirectionalGroupOverlapException\n    *            if there's an overlap with another record in the pool. (ex.\n    *            have the same territories)\n    */\n   @Named(\"updateDirectionalPoolRecord\")\n   @POST\n   @MapBinder(DirectionalRecordAndGeoGroupToXML.class)\n   void updateRecordAndGroup(@PayloadParam(\"dirPoolRecordId\") String recordId,\n         @PayloadParam(\"record\") DirectionalPoolRecord update, @PayloadParam(\"group\") DirectionalGroup group)\n         throws ResourceNotFoundException, DirectionalGroupOverlapException;\n\n   /**\n    * deletes a specific directional pool record\n    * \n    * @param id\n    *           the {@link DirectionalPoolRecordDetail#getId() id} of the\n    *           record.\n    */\n   @Named(\"deleteResourceRecord\")\n   @POST\n   @Payload(\"<v01:deleteDirectionalPoolRecord><transactionID /><dirPoolRecordId>{dirPoolRecordId}</dirPoolRecordId></v01:deleteDirectionalPoolRecord>\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void deleteRecord(@PayloadParam(\"dirPoolRecordId\") String id);\n\n   /**\n    * removes a pool and all its records\n    * \n    * @param id\n    *           the {@link DirectionalPool#getId() id}\n    */\n   @Named(\"deleteDirectionalPool\")\n   @POST\n   @Payload(\"<v01:deleteDirectionalPool><transactionID /><dirPoolID>{dirPoolID}</dirPoolID><retainRecordID /></v01:deleteDirectionalPool>\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void delete(@PayloadParam(\"dirPoolID\") String id);\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/features/ResourceRecordApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.POST;\n\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.VirtualHost;\nimport org.jclouds.rest.annotations.XMLResponseParser;\nimport org.jclouds.ultradns.ws.UltraDNSWSExceptions.ResourceAlreadyExistsException;\nimport org.jclouds.ultradns.ws.binders.ZoneAndResourceRecordToXML;\nimport org.jclouds.ultradns.ws.domain.ResourceRecord;\nimport org.jclouds.ultradns.ws.domain.ResourceRecordDetail;\nimport org.jclouds.ultradns.ws.filters.SOAPWrapWithPasswordAuth;\nimport org.jclouds.ultradns.ws.xml.ElementTextHandler;\nimport org.jclouds.ultradns.ws.xml.ResourceRecordListHandler;\n\nimport com.google.common.collect.FluentIterable;\n\n/**\n * @see <a href=\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01?wsdl\" />\n * @see <a href=\"https://www.ultradns.net/api/NUS_API_XML_SOAP.pdf\" />\n */\n@RequestFilters(SOAPWrapWithPasswordAuth.class)\n@VirtualHost\npublic interface ResourceRecordApi {\n\n   /**\n    * creates a resource record in the zone.\n    * \n    * @param toCreate\n    *           the new record to create.\n    * @return the {@code guid} of the new record\n    * @throws ResourceAlreadyExistsException\n    *            if a record already exists with the same attrs\n    */\n   @Named(\"createResourceRecord\")\n   @POST\n   @XMLResponseParser(ElementTextHandler.Guid.class)\n   @MapBinder(ZoneAndResourceRecordToXML.class)\n   String create(@PayloadParam(\"resourceRecord\") ResourceRecord toCreate)\n         throws ResourceAlreadyExistsException;\n\n   /**\n    * updates an existing resource record in the zone.\n    * \n    * @param guid\n    *           the global unique identifier for the resource record {@see\n    *           ResourceRecordMetadata#getGuid()}\n    * @param updated\n    *           the record to update.\n    * @throws ResourceNotFoundException\n    *            if the guid doesn't exist\n    */\n   @Named(\"updateResourceRecord\")\n   @POST\n   @MapBinder(ZoneAndResourceRecordToXML.class)\n   void update(@PayloadParam(\"guid\") String guid,\n         @PayloadParam(\"resourceRecord\") ResourceRecord toCreate) throws ResourceNotFoundException;\n\n   /**\n    * Returns all the specified record types in the zone.\n    * \n    * @throws ResourceNotFoundException\n    *            if the zone doesn't exist\n    */\n   @Named(\"getResourceRecordsOfZone\")\n   @POST\n   @XMLResponseParser(ResourceRecordListHandler.class)\n   @Payload(\"<v01:getResourceRecordsOfZone><zoneName>{zoneName}</zoneName><rrType>0</rrType></v01:getResourceRecordsOfZone>\")\n   FluentIterable<ResourceRecordDetail> list() throws ResourceNotFoundException;\n\n   /**\n    * Returns all the specified record types in the zone with the fully\n    * qualified {@link hostName}\n    * \n    * @param hostName\n    *           fully qualified hostname including the trailing dot.\n    * @throws ResourceNotFoundException\n    *            if the zone doesn't exist\n    */\n   @Named(\"getResourceRecordsOfDNameByType\")\n   @POST\n   @XMLResponseParser(ResourceRecordListHandler.class)\n   @Payload(\"<v01:getResourceRecordsOfDNameByType><zoneName>{zoneName}</zoneName><hostName>{hostName}</hostName><rrType>0</rrType></v01:getResourceRecordsOfDNameByType>\")\n   FluentIterable<ResourceRecordDetail> listByName(@PayloadParam(\"hostName\") String hostName)\n         throws ResourceNotFoundException;\n\n   /**\n    * Returns all the specified record types in the zone with the fully\n    * qualified {@link hostName} and {@link rrType}\n    * \n    * @param hostName\n    *           fully qualified hostname including the trailing dot.\n    * @param rrType\n    *           type value (ex. for {@code A}, this is {@code 1}\n    * \n    * @throws ResourceNotFoundException\n    *            if the zone doesn't exist\n    */\n   @Named(\"getResourceRecordsOfDNameByType\")\n   @POST\n   @XMLResponseParser(ResourceRecordListHandler.class)\n   @Payload(\"<v01:getResourceRecordsOfDNameByType><zoneName>{zoneName}</zoneName><hostName>{hostName}</hostName><rrType>{rrType}</rrType></v01:getResourceRecordsOfDNameByType>\")\n   FluentIterable<ResourceRecordDetail> listByNameAndType(\n         @PayloadParam(\"hostName\") String hostName, @PayloadParam(\"rrType\") int rrType)\n         throws ResourceNotFoundException;\n\n   /**\n    * deletes a specific resource record\n    * \n    * @param guid\n    *           the global unique identifier for the resource record {@see\n    *           ResourceRecordMetadata#getGuid()}\n    */\n   @Named(\"deleteResourceRecord\")\n   @POST\n   @Payload(\"<v01:deleteResourceRecord><transactionID /><guid>{guid}</guid></v01:deleteResourceRecord>\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void delete(@PayloadParam(\"guid\") String guid);\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/features/RoundRobinPoolApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.POST;\n\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.ParamParser;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.VirtualHost;\nimport org.jclouds.rest.annotations.XMLResponseParser;\nimport org.jclouds.ultradns.ws.UltraDNSWSExceptions.ResourceAlreadyExistsException;\nimport org.jclouds.ultradns.ws.domain.ResourceRecordDetail;\nimport org.jclouds.ultradns.ws.domain.RoundRobinPool;\nimport org.jclouds.ultradns.ws.filters.SOAPWrapWithPasswordAuth;\nimport org.jclouds.ultradns.ws.internal.RoundRobinPoolRecordTypeToString;\nimport org.jclouds.ultradns.ws.xml.ElementTextHandler;\nimport org.jclouds.ultradns.ws.xml.ResourceRecordListHandler;\nimport org.jclouds.ultradns.ws.xml.RoundRobinPoolListHandler;\n\nimport com.google.common.collect.FluentIterable;\n\n/**\n * @see <a href=\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01?wsdl\" />\n * @see <a href=\"https://www.ultradns.net/api/NUS_API_XML_SOAP.pdf\" />\n */\n@RequestFilters(SOAPWrapWithPasswordAuth.class)\n@VirtualHost\npublic interface RoundRobinPoolApi {\n\n   /**\n    * Returns all round robin pools in the zone.\n    * \n    * @throws ResourceNotFoundException\n    *            if the zone doesn't exist\n    */\n   @Named(\"getLoadBalancingPoolsByZone\")\n   @POST\n   @XMLResponseParser(RoundRobinPoolListHandler.class)\n   @Payload(\"<v01:getLoadBalancingPoolsByZone><zoneName>{zoneName}</zoneName><lbPoolType>RR</lbPoolType></v01:getLoadBalancingPoolsByZone>\")\n   FluentIterable<RoundRobinPool> list() throws ResourceNotFoundException;\n\n   /**\n    * Returns all records in the round robin pool.\n    * \n    * @throws ResourceNotFoundException\n    *            if the pool doesn't exist\n    */\n   @Named(\"getRRPoolRecords\")\n   @POST\n   @XMLResponseParser(ResourceRecordListHandler.class)\n   @Payload(\"<v01:getRRPoolRecords><lbPoolId>{poolId}</lbPoolId></v01:getRRPoolRecords>\")\n   FluentIterable<ResourceRecordDetail> listRecords(@PayloadParam(\"poolId\") String poolId)\n         throws ResourceNotFoundException;\n\n   /**\n    * creates a round robin pool.\n    * \n    * @param name\n    *           {@link RoundRobinPool#getName() name} of the RR pool\n    * @param dname\n    *           {@link RoundRobinPool#getDName() dname} of the RR pool {ex.\n    *           www.jclouds.org.}\n    * @param rrType\n    *           the {@link RoundRobinPool.RecordType record type} supported.\n    * @return the {@code guid} of the new pool\n    * @throws ResourceAlreadyExistsException\n    *            if a pool already exists with the same attrs\n    */\n   @Named(\"addRRLBPool\")\n   @POST\n   @XMLResponseParser(ElementTextHandler.RRPoolID.class)\n   @Payload(\"<v01:addRRLBPool><transactionID /><zoneName>{zoneName}</zoneName><hostName>{hostName}</hostName><description>{description}</description><poolRecordType>{poolRecordType}</poolRecordType><rrGUID /></v01:addRRLBPool>\")\n   String createForDNameAndType(@PayloadParam(\"description\") String name, @PayloadParam(\"hostName\") String dname,\n         @PayloadParam(\"poolRecordType\") @ParamParser(RoundRobinPoolRecordTypeToString.class) int rrType)\n         throws ResourceAlreadyExistsException;\n\n   /**\n    * adds a new {@code A} record to the pool\n    * \n    * @param lbPoolID\n    *           the pool to add the record to.\n    * @param ipv4Address\n    *           the ipv4 address\n    * @param ttl\n    *           the {@link ResourceRecord#getTTL ttl} of the record\n    * @return the {@code guid} of the new record\n    * @throws ResourceAlreadyExistsException\n    *            if a record already exists with the same attrs\n    */\n   @Named(\"addRecordToRRPool\")\n   @POST\n   @XMLResponseParser(ElementTextHandler.Guid.class)\n   @Payload(\"<v01:addRecordToRRPool><transactionID /><roundRobinRecord lbPoolID=\\\"{lbPoolID}\\\" info1Value=\\\"{address}\\\" ZoneName=\\\"{zoneName}\\\" Type=\\\"1\\\" TTL=\\\"{ttl}\\\"/></v01:addRecordToRRPool>\")\n   String addARecordWithAddressAndTTL(@PayloadParam(\"lbPoolID\") String lbPoolID,\n         @PayloadParam(\"address\") String ipv4Address, @PayloadParam(\"ttl\") int ttl)\n         throws ResourceAlreadyExistsException;\n\n   /**\n    * updates an existing A or AAAA record in the pool.\n    * \n    * @param lbPoolID\n    *           the pool to add the record to.\n    * @param guid\n    *           the global unique identifier for the resource record {@see\n    *           ResourceRecordMetadata#getGuid()}\n    * @param address\n    *           the ipv4 or ipv6 address\n    * @param ttl\n    *           the {@link ResourceRecord#getTTL ttl} of the record\n    * \n    * @throws ResourceNotFoundException\n    *            if the guid doesn't exist\n    */\n   @Named(\"updateRecordOfRRPool\")\n   @POST\n   @Payload(\"<v01:updateRecordOfRRPool><transactionID /><resourceRecord rrGuid=\\\"{guid}\\\" lbPoolID=\\\"{lbPoolID}\\\" info1Value=\\\"{address}\\\" TTL=\\\"{ttl}\\\"/></v01:updateRecordOfRRPool>\")\n   void updateRecordWithAddressAndTTL(@PayloadParam(\"lbPoolID\") String lbPoolID, @PayloadParam(\"guid\") String guid,\n         @PayloadParam(\"address\") String ipv4Address, @PayloadParam(\"ttl\") int ttl) throws ResourceNotFoundException;\n\n   /**\n    * deletes a specific pooled resource record\n    * \n    * @param guid\n    *           the global unique identifier for the resource record {@see\n    *           ResourceRecordMetadata#getGuid()}\n    */\n   @Named(\"deleteRecordOfRRPool\")\n   @POST\n   @Payload(\"<v01:deleteRecordOfRRPool><transactionID /><guid>{guid}</guid></v01:deleteRecordOfRRPool>\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void deleteRecord(@PayloadParam(\"guid\") String guid);\n\n   /**\n    * adds a new {@code AAAA} record to the pool\n    * \n    * @param lbPoolID\n    *           the pool to add the record to.\n    * @param ipv6Address\n    *           the ipv6 address\n    * @param ttl\n    *           the {@link ResourceRecord#getTTL ttl} of the record\n    * @return the {@code guid} of the new record\n    * @throws ResourceAlreadyExistsException\n    *            if a record already exists with the same attrs\n    */\n   @Named(\"addRecordToRRPool\")\n   @POST\n   @XMLResponseParser(ElementTextHandler.Guid.class)\n   @Payload(\"<v01:addRecordToRRPool><transactionID /><roundRobinRecord lbPoolID=\\\"{lbPoolID}\\\" info1Value=\\\"{address}\\\" ZoneName=\\\"{zoneName}\\\" Type=\\\"28\\\" TTL=\\\"{ttl}\\\"/></v01:addRecordToRRPool>\")\n   String addAAAARecordWithAddressAndTTL(@PayloadParam(\"lbPoolID\") String lbPoolID,\n         @PayloadParam(\"address\") String ipv6Address, @PayloadParam(\"ttl\") int ttl)\n         throws ResourceAlreadyExistsException;\n\n   /**\n    * removes a pool and all its records and probes\n    * \n    * @param id\n    *           the {@link RoundRobinPool#getId() id}\n    */\n   @Named(\"deleteLBPool\")\n   @POST\n   @Payload(\"<v01:deleteLBPool><transactionID /><lbPoolID>{lbPoolID}</lbPoolID><DeleteAll>Yes</DeleteAll><retainRecordId /></v01:deleteLBPool>\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void delete(@PayloadParam(\"lbPoolID\") String id);\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/features/TaskApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.POST;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.VirtualHost;\nimport org.jclouds.rest.annotations.XMLResponseParser;\nimport org.jclouds.ultradns.ws.domain.Task;\nimport org.jclouds.ultradns.ws.filters.SOAPWrapWithPasswordAuth;\nimport org.jclouds.ultradns.ws.xml.ElementTextHandler;\nimport org.jclouds.ultradns.ws.xml.TaskHandler;\nimport org.jclouds.ultradns.ws.xml.TaskListHandler;\n\nimport com.google.common.collect.FluentIterable;\n\n/**\n * @see <a href=\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01?wsdl\" />\n * @see <a href=\"https://www.ultradns.net/api/NUS_API_XML_SOAP.pdf\" />\n */\n@RequestFilters(SOAPWrapWithPasswordAuth.class)\n@VirtualHost\npublic interface TaskApi {\n   /**\n    * Runs a test task\n    * \n    * @return guid of the task created\n    */\n   @Named(\"runTest\")\n   @POST\n   @XMLResponseParser(ElementTextHandler.Guid.class)\n   @Payload(\"<v01:runTest><value>{value}</value></v01:runTest>\")\n   String runTest(@PayloadParam(\"value\") String value);\n\n   /**\n    * @param guid\n    *           guid of the task to get information about.\n    * @return null if not found\n    */\n   @Named(\"getStatusForTask\")\n   @POST\n   @XMLResponseParser(TaskHandler.class)\n   @Payload(\"<v01:getStatusForTask><id><guid>{guid}</guid></id></v01:getStatusForTask>\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   Task get(@PayloadParam(\"guid\") String name);\n\n   /**\n    * Lists all tasks.\n    */\n   @Named(\"getAllTasks\")\n   @POST\n   @XMLResponseParser(TaskListHandler.class)\n   @Payload(\"<v01:getAllTasks/>\")\n   FluentIterable<Task> list();\n\n   /**\n    * clears a background task in either a COMPLETE or ERROR state. \n    * \n    * @param guid\n    *           guid of the task to clear.\n    */\n   @Named(\"clearTask\")\n   @POST\n   @Payload(\"<v01:clearTask><id><guid>{guid}</guid></id></v01:clearTask>\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void clear(@PayloadParam(\"guid\") String name);\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/features/TrafficControllerPoolApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.POST;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.MapBinder;\nimport org.jclouds.rest.annotations.ParamParser;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.VirtualHost;\nimport org.jclouds.rest.annotations.XMLResponseParser;\nimport org.jclouds.ultradns.ws.UltraDNSWSExceptions.ResourceAlreadyExistsException;\nimport org.jclouds.ultradns.ws.binders.UpdatePoolRecordToXML;\nimport org.jclouds.ultradns.ws.domain.PoolRecordSpec;\nimport org.jclouds.ultradns.ws.domain.TrafficControllerPool;\nimport org.jclouds.ultradns.ws.domain.TrafficControllerPoolRecordDetail;\nimport org.jclouds.ultradns.ws.domain.UpdatePoolRecord;\nimport org.jclouds.ultradns.ws.filters.SOAPWrapWithPasswordAuth;\nimport org.jclouds.ultradns.ws.internal.TrafficControllerPoolRecordTypeToString;\nimport org.jclouds.ultradns.ws.xml.AttributeHandler;\nimport org.jclouds.ultradns.ws.xml.ElementTextHandler;\nimport org.jclouds.ultradns.ws.xml.PoolRecordSpecHandler;\nimport org.jclouds.ultradns.ws.xml.TrafficControllerPoolListHandler;\nimport org.jclouds.ultradns.ws.xml.TrafficControllerPoolRecordDetailListHandler;\n\nimport com.google.common.collect.FluentIterable;\n\n/**\n * @see <a href=\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01?wsdl\" />\n * @see <a href=\"https://www.ultradns.net/api/NUS_API_XML_SOAP.pdf\" />\n */\n@RequestFilters(SOAPWrapWithPasswordAuth.class)\n@VirtualHost\npublic interface TrafficControllerPoolApi {\n\n   /**\n    * creates a traffic controller pool.\n    * \n    * @param name\n    *           {@link TrafficControllerPool#getName() name} of the TC pool\n    * @param dname\n    *           {@link TrafficControllerPool#getDName() dname} of the TC pool\n    *           {ex. www.jclouds.org.}\n    * @param rrType\n    *           the {@link TrafficControllerPool.RecordType record type}\n    *           supported.\n    * @return the {@code guid} of the new record\n    * @throws ResourceAlreadyExistsException\n    *            if a pool already exists with the same attrs\n    */\n   @Named(\"addTCLBPool\")\n   @POST\n   @XMLResponseParser(ElementTextHandler.TCPoolID.class)\n   @Payload(\"<v01:addTCLBPool><transactionID /><zoneName>{zoneName}</zoneName><hostName>{hostName}</hostName><description>{description}</description><poolRecordType>{poolRecordType}</poolRecordType><failOver>Enabled</failOver><probing>Enabled</probing><maxActive>0</maxActive><rrGUID /></v01:addTCLBPool>\")\n   String createForDNameAndType(@PayloadParam(\"description\") String name, @PayloadParam(\"hostName\") String dname,\n         @PayloadParam(\"poolRecordType\") @ParamParser(TrafficControllerPoolRecordTypeToString.class) int rrType)\n         throws ResourceAlreadyExistsException;\n\n   /**\n    * Returns all traffic controller pools in the zone.\n    * \n    * @throws ResourceNotFoundException\n    *            if the zone doesn't exist\n    */\n   @Named(\"getLoadBalancingPoolsByZone\")\n   @POST\n   @XMLResponseParser(TrafficControllerPoolListHandler.class)\n   @Payload(\"<v01:getLoadBalancingPoolsByZone><zoneName>{zoneName}</zoneName><lbPoolType>TC</lbPoolType></v01:getLoadBalancingPoolsByZone>\")\n   FluentIterable<TrafficControllerPool> list() throws ResourceNotFoundException;\n\n   /**\n    * Returns all records in the traffic controller pool.\n    * \n    * @throws ResourceNotFoundException\n    *            if the pool doesn't exist\n    */\n   @Named(\"getPoolRecords\")\n   @POST\n   @XMLResponseParser(TrafficControllerPoolRecordDetailListHandler.class)\n   @Payload(\"<v01:getPoolRecords><poolId>{poolId}</poolId></v01:getPoolRecords>\")\n   FluentIterable<TrafficControllerPoolRecordDetail> listRecords(@PayloadParam(\"poolId\") String poolId)\n         throws ResourceNotFoundException;\n\n   /**\n    * Retrieves the name of the specified pool by dname.\n    * \n    * @param dname\n    *           {@see TrafficControllerPool#getDName()} ex. {@code jclouds.org.}\n    * @return null if not found\n    */\n   @Nullable\n   @Named(\"getPoolForPoolHostName>\")\n   @POST\n   @Payload(\"<v01:getPoolForPoolHostName><hostName>{hostName}</hostName></v01:getPoolForPoolHostName>\")\n   @XMLResponseParser(AttributeHandler.PoolName.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   String getNameByDName(@PayloadParam(\"hostName\") String dname);\n\n   /**\n    * removes a pool and all its records and probes\n    * \n    * @param id\n    *           the {@link TrafficControllerPool#getId() id}\n    */\n   @Named(\"deleteLBPool\")\n   @POST\n   @Payload(\"<v01:deleteLBPool><transactionID /><lbPoolID>{lbPoolID}</lbPoolID><DeleteAll>Yes</DeleteAll><retainRecordId /></v01:deleteLBPool>\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void delete(@PayloadParam(\"lbPoolID\") String id);\n\n   /**\n    * adds a new record to the pool with default weight.\n    * \n    * @param rdata\n    *           the ipv4 address or hostname\n    * @param lbPoolID\n    *           the pool to add the record to.\n    * @param ttl\n    *           the {@link PoolRecordSpec#getTTL ttl} of the record\n    * @return the {@link TrafficControllerPoolRecordDetail#getId() id} of the new\n    *         record\n    * @throws ResourceAlreadyExistsException\n    *            if a record already exists with the same attrs\n    */\n   @Named(\"addPoolRecord\")\n   @POST\n   @XMLResponseParser(ElementTextHandler.PoolRecordID.class)\n   @Payload(\"<v01:addPoolRecord><transactionID /><poolID>{poolID}</poolID><pointsTo>{pointsTo}</pointsTo><priority /><failOverDelay /><ttl>{ttl}</ttl><weight /><mode /><threshold /></v01:addPoolRecord>\")\n   String addRecordToPoolWithTTL(@PayloadParam(\"pointsTo\") String rdata, @PayloadParam(\"poolID\") String lbPoolID,\n         @PayloadParam(\"ttl\") int ttl) throws ResourceAlreadyExistsException;\n\n   /**\n    * adds a new record to the pool with a specified weight.\n    * \n    * @param rdata\n    *           the ipv4 address or hostname\n    * @param lbPoolID\n    *           the pool to add the record to.\n    * @param ttl\n    *           the {@link PoolRecordSpec#getTTL ttl} of the record\n    * @param weight\n    *           the {@link PoolRecordSpec#getWeight() weight} of the record\n    * @return the {@link TrafficControllerPoolRecordDetail#getId() id} of the new\n    *         record\n    * @throws ResourceAlreadyExistsException\n    *            if a record already exists with the same attrs\n    */\n   @Named(\"addPoolRecord\")\n   @POST\n   @XMLResponseParser(ElementTextHandler.PoolRecordID.class)\n   @Payload(\"<v01:addPoolRecord><transactionID /><poolID>{poolID}</poolID><pointsTo>{pointsTo}</pointsTo><priority /><failOverDelay /><ttl>{ttl}</ttl><weight>{weight}</weight><mode /><threshold /></v01:addPoolRecord>\")\n   String addRecordToPoolWithTTLAndWeight(@PayloadParam(\"pointsTo\") String rdata,\n         @PayloadParam(\"poolID\") String lbPoolID, @PayloadParam(\"ttl\") int ttl, @PayloadParam(\"weight\") int weight)\n         throws ResourceAlreadyExistsException;\n\n   /**\n    * @param poolRecordID\n    *           {@link TrafficControllerPoolRecordDetail#getId()}\n    * @return null if not found\n    */\n   @Named(\"getPoolRecordSpec>\")\n   @POST\n   @Payload(\"<v01:getPoolRecordSpec><poolRecordId>{poolRecordId}</poolRecordId></v01:getPoolRecordSpec>\")\n   @XMLResponseParser(PoolRecordSpecHandler.class)\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   PoolRecordSpec getRecordSpec(@PayloadParam(\"poolRecordId\") String poolRecordID);\n\n   /**\n    * This request updates an existing pool record.\n    * \n    * @param poolRecordID\n    *           {@link TrafficControllerPoolRecordDetail#getId()}\n    * @param update\n    *           what to update, usually primed via\n    *           {@link UpdatePoolRecord#pointingTo(PoolRecordSpec, String)} or\n    *           {@link org.jclouds.ultradns.ws.domain.UpdatePoolRecord.Builder#from(PoolRecordSpec)}\n    * @throws ResourceNotFoundException\n    *            if the record doesn't exist\n    */\n   @Named(\"updatePoolRecord>\")\n   @POST\n   @MapBinder(UpdatePoolRecordToXML.class)\n   void updateRecord(@PayloadParam(\"poolRecordID\") String poolRecordID, @PayloadParam(\"update\") UpdatePoolRecord update)\n         throws ResourceNotFoundException;\n\n   /**\n    * deletes a specific pooled resource record\n    * \n    * @param poolRecordID\n    *           {@see TrafficControllerPoolRecord#getId()}\n    */\n   @Named(\"deletePoolRecord\")\n   @POST\n   @Payload(\"<v01:deletePoolRecord><transactionID /><poolRecordID>{poolRecordID}</poolRecordID><parentPoolId /><childPoolId /></v01:deletePoolRecord>\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void deleteRecord(@PayloadParam(\"poolRecordID\") String poolRecordID);\n\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/features/ZoneApi.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.features;\n\nimport jakarta.inject.Named;\nimport jakarta.ws.rs.POST;\n\nimport org.jclouds.Fallbacks.NullOnNotFoundOr404;\nimport org.jclouds.Fallbacks.VoidOnNotFoundOr404;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.jclouds.rest.annotations.Fallback;\nimport org.jclouds.rest.annotations.Payload;\nimport org.jclouds.rest.annotations.PayloadParam;\nimport org.jclouds.rest.annotations.RequestFilters;\nimport org.jclouds.rest.annotations.VirtualHost;\nimport org.jclouds.rest.annotations.XMLResponseParser;\nimport org.jclouds.ultradns.ws.UltraDNSWSExceptions.ResourceAlreadyExistsException;\nimport org.jclouds.ultradns.ws.domain.Zone;\nimport org.jclouds.ultradns.ws.domain.Zone.Type;\nimport org.jclouds.ultradns.ws.domain.ZoneProperties;\nimport org.jclouds.ultradns.ws.filters.SOAPWrapWithPasswordAuth;\nimport org.jclouds.ultradns.ws.xml.ZoneListHandler;\nimport org.jclouds.ultradns.ws.xml.ZonePropertiesHandler;\n\nimport com.google.common.collect.FluentIterable;\n\n/**\n * @see <a href=\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01?wsdl\" />\n * @see <a href=\"https://www.ultradns.net/api/NUS_API_XML_SOAP.pdf\" />\n */\n@RequestFilters(SOAPWrapWithPasswordAuth.class)\n@VirtualHost\npublic interface ZoneApi {\n\n   /**\n    * creates a primary zone and its supporting records (SOA, NS and A). The\n    * user who issues this request becomes the owner of this zone.\n    * \n    * @param name\n    *           the fully qualified name of the new zone.\n    * @param accountId\n    *           the account to create the zone in\n    */\n   @Named(\"createPrimaryZone\")\n   @POST\n   @Payload(\"<v01:createPrimaryZone><transactionID /><accountId>{accountId}</accountId><zoneName>{zoneName}</zoneName><forceImport>false</forceImport></v01:createPrimaryZone>\")\n   void createInAccount(@PayloadParam(\"zoneName\") String name, @PayloadParam(\"accountId\") String accountId)\n         throws ResourceAlreadyExistsException;\n\n   /**\n    * @param name\n    *           the fully-qualified name, including the trailing dot, of the\n    *           zone to get information about.\n    * @return null if not found\n    */\n   @Named(\"getGeneralPropertiesForZone\")\n   @POST\n   @XMLResponseParser(ZonePropertiesHandler.class)\n   @Payload(\"<v01:getGeneralPropertiesForZone><zoneName>{zoneName}</zoneName></v01:getGeneralPropertiesForZone>\")\n   @Fallback(NullOnNotFoundOr404.class)\n   @Nullable\n   ZoneProperties get(@PayloadParam(\"zoneName\") String name);\n\n   /**\n    * Lists all zones in the specified account.\n    * \n    * @returns empty if no zones, or account doesn't exist\n    */\n   @Named(\"getZonesOfAccount\")\n   @POST\n   @XMLResponseParser(ZoneListHandler.class)\n   @Payload(\"<v01:getZonesOfAccount><accountId>{accountId}</accountId><zoneType>all</zoneType></v01:getZonesOfAccount>\")\n   FluentIterable<Zone> listByAccount(@PayloadParam(\"accountId\") String accountId);\n\n   /**\n    * Lists all zones in the specified account of type\n    * \n    * @throws ResourceNotFoundException\n    *            if the account doesn't exist\n    */\n   @Named(\"getZonesOfAccount\")\n   @POST\n   @XMLResponseParser(ZoneListHandler.class)\n   @Payload(\"<v01:getZonesOfAccount><accountId>{accountId}</accountId><zoneType>{zoneType}</zoneType></v01:getZonesOfAccount>\")\n   FluentIterable<Zone> listByAccountAndType(@PayloadParam(\"accountId\") String accountId,\n         @PayloadParam(\"zoneType\") Type type) throws ResourceNotFoundException;\n\n   /**\n    * deletes a zone and all its resource records\n    * \n    * @param name\n    *           the fully-qualified name, including the trailing dot, of the\n    *           zone you want to delete.\n    * @return null if not found\n    */\n   @Named(\"deleteZone\")\n   @POST\n   @Payload(\"<v01:deleteZone><transactionID /><zoneName>{zoneName}</zoneName></v01:deleteZone>\")\n   @Fallback(VoidOnNotFoundOr404.class)\n   void delete(@PayloadParam(\"zoneName\") String name);\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/filters/SOAPWrapWithPasswordAuth.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.filters;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static java.lang.String.format;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpRequestFilter;\nimport org.jclouds.io.Payload;\nimport org.jclouds.io.Payloads;\nimport org.jclouds.location.Provider;\n\nimport com.google.common.base.Supplier;\n\npublic class SOAPWrapWithPasswordAuth implements HttpRequestFilter {\n   static final String WSSE_NS = \"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\";\n   static final String PASSWORD_TEXT = \"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\";\n   static final String SOAP_PREFIX = new StringBuilder()\n         .append(\"<soapenv:Envelope xmlns:soapenv=\\\"http://schemas.xmlsoap.org/soap/envelope/\\\" \")\n         .append(\"xmlns:v01=\\\"http://webservice.api.ultra.neustar.com/v01/\\\"><soapenv:Header>\")\n         .append(\"<wsse:Security soapenv:mustUnderstand=\\\"1\\\" xmlns:wsse=\\\"\").append(WSSE_NS).append(\"\\\"><wsse:UsernameToken>\")\n         .append(\"<wsse:Username>%s</wsse:Username>\")\n         .append(\"<wsse:Password Type=\\\"\").append(PASSWORD_TEXT).append(\"\\\">%s</wsse:Password>\")\n         .append(\"</wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body>\").toString();\n   static final String SOAP_SUFFIX = \"</soapenv:Body></soapenv:Envelope>\";\n   \n   private final Supplier<Credentials> creds;\n\n   @Inject\n   public SOAPWrapWithPasswordAuth(@Provider Supplier<Credentials> creds) {\n      this.creds = creds;\n   }\n\n   public HttpRequest filter(HttpRequest request) {\n      checkNotNull(request.getPayload(), \"request is not ready to wrap; payload not present\");\n      Credentials current = creds.get();\n      String body = request.getPayload().getRawContent().toString();\n      Payload wrappedPayload = Payloads.newStringPayload(new StringBuilder()\n            .append(format(SOAP_PREFIX, current.identity, current.credential)).append(body).append(SOAP_SUFFIX)\n            .toString());\n      wrappedPayload.getContentMetadata().setContentType(\"application/xml\");\n      return request.toBuilder().payload(wrappedPayload).build();\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/handlers/UltraDNSWSErrorHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.handlers;\nimport static org.jclouds.http.HttpUtils.closeClientButKeepContentStream;\nimport static org.jclouds.http.HttpUtils.releasePayload;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Provider;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpErrorHandler;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.HttpResponseException;\nimport org.jclouds.http.functions.ParseSax.Factory;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.jclouds.ultradns.ws.UltraDNSWSError;\nimport org.jclouds.ultradns.ws.UltraDNSWSExceptions.DirectionalGroupOverlapException;\nimport org.jclouds.ultradns.ws.UltraDNSWSExceptions.ResourceAlreadyExistsException;\nimport org.jclouds.ultradns.ws.UltraDNSWSResponseException;\nimport org.jclouds.ultradns.ws.xml.UltraWSExceptionHandler;\n\n@Singleton\npublic class UltraDNSWSErrorHandler implements HttpErrorHandler {\n\n   private final Factory factory;\n   private final Provider<UltraWSExceptionHandler> handlers;\n\n   @Inject\n   UltraDNSWSErrorHandler(Factory factory, Provider<UltraWSExceptionHandler> handlers) {\n      this.factory = factory;\n      this.handlers = handlers;\n   }\n\n   public void handleError(HttpCommand command, HttpResponse response) {\n      Exception exception = new HttpResponseException(command, response);\n      try {\n         byte[] data = closeClientButKeepContentStream(response);\n         String message = data != null ? new String(data) : null;\n         if (message != null) {\n            exception = new HttpResponseException(command, response, message);\n            String contentType = response.getPayload().getContentMetadata().getContentType();\n            if (contentType != null && (contentType.indexOf(\"xml\") != -1 || contentType.indexOf(\"unknown\") != -1)) {\n               UltraDNSWSError error = factory.create(handlers.get()).parse(message);\n               if (error != null) {\n                  exception = refineException(new UltraDNSWSResponseException(command, response, error));\n               }\n            }\n         } else {\n            exception = new HttpResponseException(command, response);\n         }\n      } finally {\n         releasePayload(response);\n         command.setException(exception);\n      }\n   }\n\n   /**\n    * there are 51002 potential codes. This defines the ones we are handling.\n    */\n   static final class ErrorCodes {\n      static final int UNKNOWN = 0;\n      /**\n       * Zone does not exist in the system.\n       */\n      static final int ZONE_NOT_FOUND = 1801;\n      /**\n       * Zone already exists in the system.\n       */\n      static final int ZONE_ALREADY_EXISTS = 1802;\n      /**\n       * No resource record with GUID found in the system.\n       */\n      static final int RESOURCE_RECORD_NOT_FOUND = 2103;\n      /**\n       * Resource record exists with the same name and type.\n       */\n      static final int RESOURCE_RECORD_ALREADY_EXISTS = 2111;\n      /**\n       * No Pool or Multiple pools of same type exists for the PoolName\n       */\n      static final int DIRECTIONALPOOL_NOT_FOUND = 2142;\n      /**\n       * Account not found in the system.\n       */\n      static final int ACCOUNT_NOT_FOUND = 2401;\n      /**\n       * Directional Pool Record does not exist in the system\n       */\n      static final int DIRECTIONALPOOL_RECORD_NOT_FOUND = 2705;\n      /**\n       * Pool does not exist in the system.\n       */\n      static final int POOL_NOT_FOUND = 2911;\n      /**\n       * Pool already created for the given rrGUID.\n       */\n      static final int POOL_ALREADY_EXISTS = 2912;\n      /**\n       * Pool Record does not exist.\n       */\n      static final int POOL_RECORD_NOT_FOUND = 3101;\n      /**\n       * Group does not exist.\n       */\n      static final int GROUP_NOT_FOUND = 4003;\n      /**\n       * Resource Record already exists.\n       */\n      static final int POOL_RECORD_ALREADY_EXISTS = 4009;\n      /**\n       * Geolocation/Source IP overlap(s) found\n       */\n      static final int DIRECTIONALPOOL_OVERLAP = 7021;\n   }\n\n   private Exception refineException(UltraDNSWSResponseException exception) {\n      String message = exception.getError().getDescription().or(exception.getMessage());\n      switch (exception.getError().getCode()) {\n      case ErrorCodes.UNKNOWN:\n         if (!exception.getError().getDescription().isPresent())\n            return exception;\n         if (exception.getError().getDescription().get().indexOf(\"Cannot find\") == -1)\n            return exception;\n         return new ResourceNotFoundException(message, exception);\n      case ErrorCodes.ZONE_NOT_FOUND:\n      case ErrorCodes.RESOURCE_RECORD_NOT_FOUND:\n      case ErrorCodes.ACCOUNT_NOT_FOUND:\n      case ErrorCodes.POOL_NOT_FOUND:\n      case ErrorCodes.DIRECTIONALPOOL_NOT_FOUND:\n      case ErrorCodes.DIRECTIONALPOOL_RECORD_NOT_FOUND:\n      case ErrorCodes.POOL_RECORD_NOT_FOUND:\n      case ErrorCodes.GROUP_NOT_FOUND:\n         return new ResourceNotFoundException(message, exception);\n      case ErrorCodes.ZONE_ALREADY_EXISTS:\n      case ErrorCodes.RESOURCE_RECORD_ALREADY_EXISTS:\n      case ErrorCodes.POOL_ALREADY_EXISTS:\n      case ErrorCodes.POOL_RECORD_ALREADY_EXISTS:\n         return new ResourceAlreadyExistsException(message, exception);\n      case ErrorCodes.DIRECTIONALPOOL_OVERLAP:\n         return new DirectionalGroupOverlapException(message, exception);\n      }\n      return exception;\n   }\n\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/internal/DirectionalPoolRecordTypeToString.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.internal;\n\nimport java.util.EnumSet;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.ultradns.ws.domain.DirectionalPool.RecordType;\n\nimport com.google.common.base.Function;\n\n/**\n * pools use the address type also for cnames.\n */\npublic class DirectionalPoolRecordTypeToString implements Function<Object, String> {\n   @Inject\n   private DirectionalPoolRecordTypeToString() {\n   }\n\n   public String apply(Object in) {\n      int rrType = Integer.class.cast(in);\n      for (RecordType type : EnumSet.allOf(RecordType.class)) {\n         if (type.getCode() == rrType) {\n            switch (type) {\n            case IPV4:\n               return \"A\";\n            case IPV6:\n               return \"AAAA\";\n            default:\n               return type.toString();\n            }\n         }\n      }\n      throw new IllegalArgumentException(\"unsupported rrType \" + rrType + \" please see \" + RecordType.class.getName());\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/internal/RoundRobinPoolRecordTypeToString.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.internal;\n\nimport java.util.EnumSet;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.ultradns.ws.domain.RoundRobinPool.RecordType;\n\nimport com.google.common.base.Function;\n\npublic class RoundRobinPoolRecordTypeToString implements Function<Object, String> {\n   @Inject\n   private RoundRobinPoolRecordTypeToString() {\n   }\n\n   public String apply(Object in) {\n      int rrType = Integer.class.cast(in);\n      for (RecordType type : EnumSet.allOf(RecordType.class)) {\n         if (type.getCode() == rrType) {\n            return Integer.toString(rrType);\n         }\n      }\n      throw new IllegalArgumentException(\"unsupported rrType \" + rrType + \" please see \" + RecordType.class.getName());\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/internal/TrafficControllerPoolRecordTypeToString.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.internal;\n\nimport java.util.EnumSet;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.ultradns.ws.domain.TrafficControllerPool.RecordType;\n\nimport com.google.common.base.Function;\n\n/**\n * pools use the address type also for cnames.\n */\npublic class TrafficControllerPoolRecordTypeToString implements Function<Object, String> {\n   @Inject\n   private TrafficControllerPoolRecordTypeToString() {\n   }\n\n   public String apply(Object in) {\n      int rrType = Integer.class.cast(in);\n      for (RecordType type : EnumSet.allOf(RecordType.class)) {\n         if (type.getCode() == rrType) {\n            return Integer.toString(rrType);\n         }\n      }\n      throw new IllegalArgumentException(\"unsupported rrType \" + rrType + \" please see \" + RecordType.class.getName());\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/predicates/DirectionalPoolPredicates.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.ultradns.ws.domain.DirectionalPool;\nimport org.jclouds.ultradns.ws.domain.DirectionalPoolRecordDetail;\n\nimport com.google.common.base.Predicate;\n\n/**\n * Predicates handy when working with DirectionalPool Types\n */\npublic class DirectionalPoolPredicates {\n\n   public static Predicate<DirectionalPool> idEqualTo(String id) {\n      return new IdEqualToPredicate(id);\n   }\n\n   private static final class IdEqualToPredicate implements Predicate<DirectionalPool> {\n      private final String id;\n\n      public IdEqualToPredicate(String id) {\n         this.id = checkNotNull(id, \"id\");\n      }\n\n      @Override\n      public boolean apply(DirectionalPool input) {\n         return input != null && id.equals(input.getId());\n      }\n\n      @Override\n      public String toString() {\n         return \"IdEqualTo(\" + id + \")\";\n      }\n   }\n\n   public static Predicate<DirectionalPoolRecordDetail> recordIdEqualTo(String recordId) {\n      return new RecordIdEqualToPredicate(recordId);\n   }\n\n   private static final class RecordIdEqualToPredicate implements Predicate<DirectionalPoolRecordDetail> {\n      private final String recordId;\n\n      public RecordIdEqualToPredicate(String recordId) {\n         this.recordId = checkNotNull(recordId, \"recordId\");\n      }\n\n      @Override\n      public boolean apply(DirectionalPoolRecordDetail input) {\n         return input != null && recordId.equals(input.getId());\n      }\n\n      @Override\n      public String toString() {\n         return \"RecordIdEqualTo(\" + recordId + \")\";\n      }\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/predicates/TrafficControllerPoolPredicates.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.ultradns.ws.domain.TrafficControllerPool;\nimport org.jclouds.ultradns.ws.domain.TrafficControllerPoolRecordDetail;\n\nimport com.google.common.base.Predicate;\n\n/**\n * Predicates handy when working with TrafficControllerPool Types\n */\npublic class TrafficControllerPoolPredicates {\n\n   public static Predicate<TrafficControllerPool> idEqualTo(String id) {\n      return new IdEqualToPredicate(id);\n   }\n\n   private static final class IdEqualToPredicate implements Predicate<TrafficControllerPool> {\n      private final String id;\n\n      public IdEqualToPredicate(String id) {\n         this.id = checkNotNull(id, \"id\");\n      }\n\n      @Override\n      public boolean apply(TrafficControllerPool input) {\n         return input != null && id.equals(input.getId());\n      }\n\n      @Override\n      public String toString() {\n         return \"IdEqualTo(\" + id + \")\";\n      }\n   }\n\n   public static Predicate<TrafficControllerPoolRecordDetail> recordIdEqualTo(String recordId) {\n      return new RecordIdEqualToPredicate(recordId);\n   }\n\n   private static final class RecordIdEqualToPredicate implements Predicate<TrafficControllerPoolRecordDetail> {\n      private final String recordId;\n\n      public RecordIdEqualToPredicate(String recordId) {\n         this.recordId = checkNotNull(recordId, \"recordId\");\n      }\n\n      @Override\n      public boolean apply(TrafficControllerPoolRecordDetail input) {\n         return input != null && recordId.equals(input.getId());\n      }\n\n      @Override\n      public String toString() {\n         return \"RecordIdEqualTo(\" + recordId + \")\";\n      }\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/predicates/ZonePredicates.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.predicates;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport org.jclouds.ultradns.ws.domain.Zone;\nimport org.jclouds.ultradns.ws.domain.Zone.Type;\n\nimport com.google.common.base.Predicate;\n\n/**\n * Predicates handy when working with Zone Types\n */\npublic class ZonePredicates {\n\n   public static Predicate<Zone> typeEqualTo(Type type) {\n      return new TypeEqualToPredicate(type);\n   }\n\n   private static final class TypeEqualToPredicate implements Predicate<Zone> {\n      private final Type type;\n\n      public TypeEqualToPredicate(Type type) {\n         this.type = checkNotNull(type, \"type\");\n      }\n\n      @Override\n      public boolean apply(Zone input) {\n         return input != null && type.equals(input.getType());\n      }\n\n      @Override\n      public String toString() {\n         return \"TypeEqualTo(\" + type + \")\";\n      }\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/xml/AccountHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.xml;\n\nimport static org.jclouds.util.SaxUtils.cleanseAttributes;\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport java.util.Map;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.ultradns.ws.domain.IdAndName;\nimport org.xml.sax.Attributes;\n\npublic class AccountHandler extends ParseSax.HandlerForGeneratedRequestWithResult<IdAndName> {\n\n   private IdAndName account;\n\n   @Override\n   public IdAndName getResult() {\n      try {\n         return account;\n      } finally {\n         account = null;\n      }\n   }\n\n   @Override\n   public void startElement(String uri, String localName, String qName, Attributes attrs) {\n      Map<String, String> attributes = cleanseAttributes(attrs);\n      if (equalsOrSuffix(qName, \"AccountDetailsData\")) {\n         account = IdAndName.create(attributes.get(\"accountID\"), attributes.get(\"accountName\"));\n      }\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/xml/AccountLevelGroupsHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.xml;\n\nimport static org.jclouds.util.SaxUtils.cleanseAttributes;\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport java.util.Map;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.ultradns.ws.domain.AccountLevelGroup;\nimport org.jclouds.ultradns.ws.domain.DirectionalPool.Type;\nimport org.xml.sax.Attributes;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\n\npublic class AccountLevelGroupsHandler extends\n      ParseSax.HandlerForGeneratedRequestWithResult<FluentIterable<AccountLevelGroup>> {\n\n   private final Builder<AccountLevelGroup> groups = ImmutableSet.<AccountLevelGroup> builder();\n\n   @Override\n   public FluentIterable<AccountLevelGroup> getResult() {\n      return FluentIterable.from(groups.build());\n   }\n\n   @Override\n   public void startElement(String url, String name, String qName, Attributes attrs) {\n      if (equalsOrSuffix(qName, \"AccountLevelGroups\")) {\n         Map<String, String> attributes = cleanseAttributes(attrs);\n         groups.add(AccountLevelGroup.builder()\n                                     .id(attributes.get(\"GroupId\"))\n                                     .name(attributes.get(\"GroupName\"))\n                                     .type(Type.valueOf(attributes.get(\"GroupType\")))\n                                     .recordCount(Integer.parseInt(attributes.get(\"RecordsCount\")))\n                                     .build());\n      }\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/xml/AttributeHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.xml;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.util.SaxUtils.cleanseAttributes;\n\nimport java.util.Map;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.xml.sax.Attributes;\n\npublic abstract class AttributeHandler extends ParseSax.HandlerForGeneratedRequestWithResult<String> {\n\n   public static class PoolName extends AttributeHandler {\n      public PoolName() {\n         super(\"PoolName\");\n      }\n   }\n\n   private final String attributeName;\n   private String attribute = null;\n\n   private AttributeHandler(String attributeName) {\n      this.attributeName = checkNotNull(attributeName, \"attributeName\");\n   }\n\n   @Override\n   public String getResult() {\n      return checkNotNull(attribute, \"%s not present in the response\", attributeName);\n   }\n\n   @Override\n   public void startElement(String uri, String localName, String qName, Attributes attrs) {\n      Map<String, String> attributes = cleanseAttributes(attrs);\n      if (attribute == null && attributes.containsKey(attributeName)) {\n         attribute = attributes.get(attributeName);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/xml/DirectionalGroupHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.xml;\n\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.ultradns.ws.domain.DirectionalGroup;\nimport org.jclouds.ultradns.ws.domain.DirectionalGroup.Builder;\nimport org.xml.sax.Attributes;\n\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.ImmutableSortedSet;\n\npublic class DirectionalGroupHandler extends ParseSax.HandlerForGeneratedRequestWithResult<DirectionalGroup> {\n\n   private final Builder group = DirectionalGroup.builder();\n\n   @Override\n   public DirectionalGroup getResult() {\n      return group.build();\n   }\n\n   @Override\n   public void startElement(String url, String name, String qName, Attributes attrs) {\n      if (equalsOrSuffix(qName, \"DirectionalDNSGroupDetail\")) {\n         group.name(attrs.getValue(\"GroupName\"));\n         group.description(attrs.getValue(\"Description\"));\n      } else if (equalsOrSuffix(qName, \"RegionForNewGroups\")) {\n         String regionName = attrs.getValue(\"RegionName\");\n         Iterable<String> territories = Splitter.on(';').split(attrs.getValue(\"TerritoryName\"));\n         // for some reason, this isn't sorted here, though it is in other parts of the api.  manually sort.\n         group.mapRegionToTerritories(regionName, ImmutableSortedSet.copyOf(territories));\n      }\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/xml/DirectionalPoolListHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.xml;\n\nimport static org.jclouds.util.SaxUtils.cleanseAttributes;\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport java.util.Map;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.ultradns.ws.domain.DirectionalPool;\nimport org.jclouds.ultradns.ws.domain.DirectionalPool.TieBreak;\nimport org.jclouds.ultradns.ws.domain.DirectionalPool.Type;\nimport org.xml.sax.Attributes;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\n\npublic class DirectionalPoolListHandler extends ParseSax.HandlerForGeneratedRequestWithResult<FluentIterable<DirectionalPool>> {\n\n   private final Builder<DirectionalPool> pools = ImmutableSet.<DirectionalPool> builder();\n\n   @Override\n   public FluentIterable<DirectionalPool> getResult() {\n      return FluentIterable.from(pools.build());\n   }\n\n   @Override\n   public void startElement(String url, String name, String qName, Attributes attrs) {\n      if (equalsOrSuffix(qName, \"DirectionalPoolData\")) {\n         Map<String, String> attributes = cleanseAttributes(attrs);\n\n         DirectionalPool.Builder pool = DirectionalPool.builder()\n                                                       .zoneId(attributes.get(\"Zoneid\"))\n                                                       .id(attributes.get(\"dirpoolid\"))\n                                                       .dname(attributes.get(\"Pooldname\"))\n                                                       .name(attributes.get(\"Description\"));\n\n         String type = attributes.get(\"DirPoolType\");\n         if (type != null)\n            pool.type(Type.valueOf(type));\n         \n         String tieBreak = attributes.get(\"TieBreak\");\n         if (tieBreak != null)\n            pool.tieBreak(TieBreak.valueOf(tieBreak));\n\n         pools.add(pool.build());\n      }\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/xml/DirectionalPoolRecordDetailHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.xml;\n\nimport static org.jclouds.util.SaxUtils.cleanseAttributes;\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport java.util.Map;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.ultradns.ws.domain.DirectionalPoolRecord;\nimport org.jclouds.ultradns.ws.domain.DirectionalPoolRecordDetail;\nimport org.jclouds.ultradns.ws.domain.IdAndName;\nimport org.xml.sax.Attributes;\n\npublic class DirectionalPoolRecordDetailHandler extends\n      ParseSax.HandlerForGeneratedRequestWithResult<DirectionalPoolRecordDetail> {\n\n   private DirectionalPoolRecordDetail.Builder drd = DirectionalPoolRecordDetail.builder();\n   private DirectionalPoolRecord.Builder dr = DirectionalPoolRecord.drBuilder();\n\n   private String zoneName;\n   private String dname;\n\n   @Override\n   public DirectionalPoolRecordDetail getResult() {\n      try {\n         return drd.record(dr.build()).build();\n      } finally {\n         drd = DirectionalPoolRecordDetail.builder().zoneName(zoneName).name(dname);\n         dr = DirectionalPoolRecord.drBuilder();\n      }\n   }\n\n   @Override\n   public void startElement(String uri, String localName, String qName, Attributes attrs) {\n      Map<String, String> attributes = cleanseAttributes(attrs);\n      if (attributes.containsKey(\"ZoneName\")) {\n         zoneName = attributes.get(\"ZoneName\");\n         dname = attributes.get(\"DName\");\n         drd.zoneName(zoneName).name(dname);\n      }\n      if (attributes.containsKey(\"DirPoolRecordId\")) {\n         drd.id(attributes.get(\"DirPoolRecordId\"));\n      }\n      if (attributes.containsKey(\"GroupId\")) {\n         drd.group(IdAndName.create(attributes.get(\"GroupId\"), attributes.get(\"GroupName\")));\n      }\n      if (attributes.containsKey(\"GeolocationGroupId\")) {\n         drd.geolocationGroup(IdAndName.create(attributes.get(\"GeolocationGroupId\"),\n               attributes.get(\"GeolocationGroupName\")));\n      }\n      if (attributes.containsKey(\"SourceIPGroupId\")) {\n         drd.sourceIpGroup(IdAndName.create(attributes.get(\"SourceIPGroupId\"), attributes.get(\"SourceIPGroupName\")));\n      }\n      if (attributes.containsKey(\"recordType\")) {\n         dr.type(attributes.get(\"recordType\"));\n         dr.ttl(Integer.parseInt(attributes.get(\"TTL\")));\n         dr.noResponseRecord(\"true\".equalsIgnoreCase(attributes.get(\"noResponseRecord\")));\n      }\n      if (equalsOrSuffix(qName, \"InfoValues\")) {\n         dr.rdata(attributes.values());\n      }\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/xml/DirectionalPoolRecordDetailListHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.xml;\n\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.ultradns.ws.domain.DirectionalPoolRecordDetail;\nimport org.xml.sax.Attributes;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\nimport com.google.inject.Inject;\n\npublic class DirectionalPoolRecordDetailListHandler extends\n      ParseSax.HandlerForGeneratedRequestWithResult<FluentIterable<DirectionalPoolRecordDetail>> {\n\n   private final DirectionalPoolRecordDetailHandler directionalRecordHandler;\n\n   private final Builder<DirectionalPoolRecordDetail> drs = ImmutableSet.<DirectionalPoolRecordDetail> builder();\n\n   @Inject\n   public DirectionalPoolRecordDetailListHandler(DirectionalPoolRecordDetailHandler directionalRecordHandler) {\n      this.directionalRecordHandler = directionalRecordHandler;\n   }\n\n   @Override\n   public FluentIterable<DirectionalPoolRecordDetail> getResult() {\n      return FluentIterable.from(drs.build());\n   }\n\n   @Override\n   public void startElement(String url, String name, String qName, Attributes attributes) {\n      directionalRecordHandler.startElement(url, name, qName, attributes);\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) {\n      if (equalsOrSuffix(qName, \"DirectionalDNSRecordDetail\")) {\n         drs.add(directionalRecordHandler.getResult());\n      }\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/xml/ElementTextHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.xml;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.util.SaxUtils.currentOrNull;\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport org.jclouds.http.functions.ParseSax;\n\npublic abstract class ElementTextHandler extends ParseSax.HandlerForGeneratedRequestWithResult<String> {\n\n   public static class Guid extends ElementTextHandler {\n      public Guid() {\n         super(\"guid\");\n      }\n   }\n\n   public static class RRPoolID extends ElementTextHandler {\n      public RRPoolID() {\n         super(\"RRPoolID\");\n      }\n   }\n\n   public static class TCPoolID extends ElementTextHandler {\n      public TCPoolID() {\n         super(\"TCPoolID\");\n      }\n   }\n\n   public static class PoolRecordID extends ElementTextHandler {\n      public PoolRecordID() {\n         super(\"poolRecordID\");\n      }\n   }\n\n   public static class DirPoolID extends ElementTextHandler {\n      public DirPoolID() {\n         super(\"DirPoolID\");\n      }\n   }\n\n   public static class DirectionalPoolRecordID extends ElementTextHandler {\n      public DirectionalPoolRecordID() {\n         super(\"DirectionalPoolRecordID\");\n      }\n   }\n\n   private final String textElement;\n\n   private StringBuilder currentText = new StringBuilder();\n   private String text = null;\n\n   private ElementTextHandler(String textElement) {\n      this.textElement = checkNotNull(textElement, \"textElement\");\n   }\n\n   @Override\n   public String getResult() {\n      return checkNotNull(text, \"%s not present in the response\", textElement);\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) {\n      if (equalsOrSuffix(qName, textElement)) {\n         text = currentOrNull(currentText);\n      }\n      currentText.setLength(0);\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/xml/ItemListHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.xml;\n\nimport static org.jclouds.util.SaxUtils.currentOrNull;\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport org.jclouds.http.functions.ParseSax;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\n\npublic class ItemListHandler extends ParseSax.HandlerForGeneratedRequestWithResult<FluentIterable<String>> {\n\n   private StringBuilder currentText = new StringBuilder();\n\n   private Builder<String> items = ImmutableSet.<String> builder();\n\n   @Override\n   public FluentIterable<String> getResult() {\n      return FluentIterable.from(items.build());\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) {\n      if (equalsOrSuffix(qName, \"item\")) {\n         items.add(currentOrNull(currentText));\n      }\n      currentText.setLength(0);\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/xml/PoolRecordSpecHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.xml;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static java.lang.Integer.parseInt;\nimport static org.jclouds.util.SaxUtils.cleanseAttributes;\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport java.util.Map;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.ultradns.ws.domain.PoolRecordSpec;\nimport org.xml.sax.Attributes;\n\npublic class PoolRecordSpecHandler extends ParseSax.HandlerForGeneratedRequestWithResult<PoolRecordSpec> {\n\n   private final PoolRecordSpec.Builder builder = PoolRecordSpec.builder();\n\n   @Override\n   public PoolRecordSpec getResult() {\n      return builder.build();\n   }\n\n   @Override\n   public void startElement(String url, String name, String qName, Attributes attrs) {\n      if (!equalsOrSuffix(qName, \"PoolRecordSpecData\")) {\n         return;\n      }\n\n      Map<String, String> attributes = cleanseAttributes(attrs);\n\n      builder.description(attributes.get(\"description\"))\n             .state(attributes.get(\"recordState\"));\n      \n      builder.probingEnabled(trueIfEnabled(attributes, \"probing\"))\n             .allFailEnabled(trueIfEnabled(attributes, \"allFail\"));\n      \n      builder.weight(asInt(attributes, \"weight\"))\n             .failOverDelay(asInt(attributes, \"failOverDelay\"))\n             .threshold(asInt(attributes, \"threshold\"))\n             .ttl(asInt(attributes, \"ttl\"));\n   }\n\n   private boolean trueIfEnabled(Map<String, String> attributes, String name) {\n      return \"ENABLED\".equalsIgnoreCase(attributes.get(name));\n   }\n\n   private int asInt(Map<String, String> attributes, String name) {\n      return parseInt(checkNotNull(attributes.get(name), name));\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/xml/RegionListHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.xml;\n\nimport static org.jclouds.util.SaxUtils.cleanseAttributes;\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport java.util.Map;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.ultradns.ws.domain.IdAndName;\nimport org.xml.sax.Attributes;\n\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableMultimap.Builder;\nimport com.google.common.collect.Multimap;\n\npublic class RegionListHandler extends ParseSax.HandlerForGeneratedRequestWithResult<Multimap<IdAndName, String>> {\n\n   private final Builder<IdAndName, String> regions = ImmutableMultimap.<IdAndName, String> builder();\n\n   @Override\n   public Multimap<IdAndName, String> getResult() {\n      return regions.build();\n   }\n\n   @Override\n   public void startElement(String url, String name, String qName, Attributes attrs) {\n      if (equalsOrSuffix(qName, \"Region\")) {\n         Map<String, String> attributes = cleanseAttributes(attrs);\n         IdAndName region = IdAndName.create(attributes.get(\"RegionID\"), attributes.get(\"RegionName\"));\n         regions.putAll(region, Splitter.on(';').split(attributes.get(\"TerritoryName\")));\n      }\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/xml/ResourceRecordDetailHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.xml;\n\nimport static org.jclouds.util.SaxUtils.cleanseAttributes;\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport java.util.Map;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.ultradns.ws.domain.ResourceRecord;\nimport org.jclouds.ultradns.ws.domain.ResourceRecordDetail;\nimport org.xml.sax.Attributes;\n\nimport com.google.inject.Inject;\n\npublic class ResourceRecordDetailHandler extends\n      ParseSax.HandlerForGeneratedRequestWithResult<ResourceRecordDetail> {\n   private final DateService dateService;\n\n   @Inject\n   private ResourceRecordDetailHandler(DateService dateService) {\n      this.dateService = dateService;\n   }\n\n   private ResourceRecordDetail.Builder rrm = ResourceRecordDetail.builder();\n   private ResourceRecord.Builder rr = ResourceRecord.rrBuilder();\n\n   @Override\n   public ResourceRecordDetail getResult() {\n      try {\n         return rrm.record(rr.build()).build();\n      } finally {\n         rrm = ResourceRecordDetail.builder();\n         rr = ResourceRecord.rrBuilder();\n      }\n   }\n\n   @Override\n   public void startElement(String uri, String localName, String qName, Attributes attrs) {\n      Map<String, String> attributes = cleanseAttributes(attrs);\n      if (equalsOrSuffix(qName, \"ResourceRecord\")) {\n         rrm.zoneId(attributes.get(\"ZoneId\"));\n         rrm.guid(attributes.get(\"Guid\"));\n         rrm.zoneName(attributes.get(\"ZoneName\"));\n         rrm.created(dateService.iso8601DateParse(attributes.get(\"Created\")));\n         rrm.modified(dateService.iso8601DateParse(attributes.get(\"Modified\")));\n         rr.type(Integer.parseInt(attributes.get(\"Type\")));\n         rr.name(attributes.get(\"DName\"));\n         rr.ttl(Integer.parseInt(attributes.get(\"TTL\")));\n      } else if (equalsOrSuffix(qName, \"InfoValues\")) {\n         rr.rdata(attributes.values());\n      }\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/xml/ResourceRecordListHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.xml;\n\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.ultradns.ws.domain.ResourceRecordDetail;\nimport org.xml.sax.Attributes;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\nimport com.google.inject.Inject;\n\npublic class ResourceRecordListHandler extends\n      ParseSax.HandlerForGeneratedRequestWithResult<FluentIterable<ResourceRecordDetail>> {\n\n   private final ResourceRecordDetailHandler resourceRecordHandler;\n\n   private Builder<ResourceRecordDetail> rrs = ImmutableSet.<ResourceRecordDetail> builder();\n\n   @Inject\n   public ResourceRecordListHandler(ResourceRecordDetailHandler resourceRecordHandler) {\n      this.resourceRecordHandler = resourceRecordHandler;\n   }\n\n   @Override\n   public FluentIterable<ResourceRecordDetail> getResult() {\n      return FluentIterable.from(rrs.build());\n   }\n\n   @Override\n   public void startElement(String url, String name, String qName, Attributes attributes) {\n      resourceRecordHandler.startElement(url, name, qName, attributes);\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) {\n      if (equalsOrSuffix(qName, \"ResourceRecord\")) {\n         rrs.add(resourceRecordHandler.getResult());\n      }\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/xml/RoundRobinPoolHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.xml;\n\nimport static org.jclouds.util.SaxUtils.cleanseAttributes;\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport java.util.Map;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.ultradns.ws.domain.RoundRobinPool;\nimport org.jclouds.ultradns.ws.domain.RoundRobinPool.Builder;\nimport org.xml.sax.Attributes;\n\npublic class RoundRobinPoolHandler extends ParseSax.HandlerForGeneratedRequestWithResult<RoundRobinPool> {\n\n   private Builder pool = RoundRobinPool.builder();\n\n   @Override\n   public RoundRobinPool getResult() {\n      try {\n         return pool.build();\n      } finally {\n         pool = RoundRobinPool.builder();\n      }\n   }\n\n   @Override\n   public void startElement(String uri, String localName, String qName, Attributes attrs) {\n      Map<String, String> attributes = cleanseAttributes(attrs);\n      if (equalsOrSuffix(qName, \"LBPoolData\")) {\n         pool.zoneId(attributes.get(\"zoneid\"));\n      } else if (equalsOrSuffix(qName, \"PoolData\")) {\n         pool.id(attributes.get(\"PoolId\")).name(attributes.get(\"description\")).dname(attributes.get(\"PoolDName\"));\n      }\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/xml/RoundRobinPoolListHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.xml;\n\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.ultradns.ws.domain.RoundRobinPool;\nimport org.xml.sax.Attributes;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\nimport com.google.inject.Inject;\n\npublic class RoundRobinPoolListHandler extends ParseSax.HandlerForGeneratedRequestWithResult<FluentIterable<RoundRobinPool>> {\n\n   private final RoundRobinPoolHandler poolHandler;\n\n   private Builder<RoundRobinPool> pools = ImmutableSet.<RoundRobinPool> builder();\n\n   @Inject\n   public RoundRobinPoolListHandler(RoundRobinPoolHandler poolHandler) {\n      this.poolHandler = poolHandler;\n   }\n\n   @Override\n   public FluentIterable<RoundRobinPool> getResult() {\n      return FluentIterable.from(pools.build());\n   }\n\n   @Override\n   public void startElement(String url, String name, String qName, Attributes attributes) {\n      if (equalsOrSuffix(qName, \"LBPoolData\") || equalsOrSuffix(qName, \"PoolData\")) {\n         poolHandler.startElement(url, name, qName, attributes);\n      }\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) {\n      if (equalsOrSuffix(qName, \"LBPoolData\")) {\n         pools.add(poolHandler.getResult());\n      }\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/xml/TaskHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.xml;\n\nimport static org.jclouds.util.SaxUtils.currentOrNull;\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport java.net.URI;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.ultradns.ws.domain.Task;\nimport org.jclouds.ultradns.ws.domain.Task.StatusCode;\nimport org.xml.sax.Attributes;\n\npublic class TaskHandler extends ParseSax.HandlerForGeneratedRequestWithResult<Task> {\n   private StringBuilder currentText = new StringBuilder();\n   private Task.Builder builder = Task.builder();\n\n   @Override\n   public Task getResult() {\n      try {\n         return builder.build();\n      } finally {\n         builder = Task.builder();\n      }\n   }\n\n   @Override\n   public void startElement(String url, String name, String qName, Attributes attributes) {\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) {\n      if (equalsOrSuffix(qName, \"guid\")) {\n         builder.guid(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"code\")) {\n         builder.statusCode(StatusCode.valueOf(currentOrNull(currentText)));\n      } else if (equalsOrSuffix(qName, \"message\")) {\n         builder.message(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"resultUrl\")) {\n         builder.resultUrl(URI.create(currentOrNull(currentText)));\n      }\n      currentText.setLength(0);\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/xml/TaskListHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.xml;\n\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.ultradns.ws.domain.Task;\nimport org.xml.sax.Attributes;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\nimport com.google.inject.Inject;\n\npublic class TaskListHandler extends ParseSax.HandlerForGeneratedRequestWithResult<FluentIterable<Task>> {\n\n   private final TaskHandler taskHandler;\n\n   private Builder<Task> tasks = ImmutableSet.<Task> builder();\n\n   private boolean inTask;\n\n   @Inject\n   public TaskListHandler(TaskHandler taskHandler) {\n      this.taskHandler = taskHandler;\n   }\n\n   @Override\n   public FluentIterable<Task> getResult() {\n      return FluentIterable.from(tasks.build());\n   }\n\n   @Override\n   public void startElement(String url, String name, String qName, Attributes attributes) {\n      if (equalsOrSuffix(qName, \"taskStatus\")) {\n         inTask = true;\n      }\n      if (inTask) {\n         taskHandler.startElement(url, name, qName, attributes);\n      }\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) {\n      if (equalsOrSuffix(qName, \"taskStatus\")) {\n         tasks.add(taskHandler.getResult());\n         inTask = false;\n      } else if (inTask) {\n         taskHandler.endElement(uri, name, qName);\n      }\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      if (inTask) {\n         taskHandler.characters(ch, start, length);\n      }\n   }\n\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/xml/TrafficControllerPoolHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.xml;\n\nimport static org.jclouds.util.SaxUtils.cleanseAttributes;\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport java.util.Map;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.ultradns.ws.domain.TrafficControllerPool;\nimport org.jclouds.ultradns.ws.domain.TrafficControllerPool.Builder;\nimport org.xml.sax.Attributes;\n\npublic class TrafficControllerPoolHandler extends ParseSax.HandlerForGeneratedRequestWithResult<TrafficControllerPool> {\n\n   private Builder pool = TrafficControllerPool.builder();\n\n   @Override\n   public TrafficControllerPool getResult() {\n      try {\n         return pool.build();\n      } finally {\n         pool = TrafficControllerPool.builder();\n      }\n   }\n\n   @Override\n   public void startElement(String uri, String localName, String qName, Attributes attrs) {\n      Map<String, String> attributes = cleanseAttributes(attrs);\n      if (equalsOrSuffix(qName, \"LBPoolData\")) {\n         pool.zoneId(attributes.get(\"zoneid\"));\n      } else if (equalsOrSuffix(qName, \"PoolData\")) {\n         pool.id(attributes.get(\"PoolId\")).name(attributes.get(\"description\")).dname(attributes.get(\"PoolDName\"));\n         pool.statusCode(Integer.parseInt(attributes.get(\"PoolStatus\")));\n         pool.failOverEnabled(\"Enabled\".equalsIgnoreCase(attributes.get(\"FailOver\")));\n         pool.probingEnabled(\"Enabled\".equalsIgnoreCase(attributes.get(\"Probing\")));\n         // MaxActiveServers is always 0 for TC\n      }\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/xml/TrafficControllerPoolListHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.xml;\n\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.ultradns.ws.domain.TrafficControllerPool;\nimport org.xml.sax.Attributes;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\nimport com.google.inject.Inject;\n\npublic class TrafficControllerPoolListHandler extends ParseSax.HandlerForGeneratedRequestWithResult<FluentIterable<TrafficControllerPool>> {\n\n   private final TrafficControllerPoolHandler poolHandler;\n\n   private final Builder<TrafficControllerPool> pools = ImmutableSet.<TrafficControllerPool> builder();\n\n   @Inject\n   public TrafficControllerPoolListHandler(TrafficControllerPoolHandler poolHandler) {\n      this.poolHandler = poolHandler;\n   }\n\n   @Override\n   public FluentIterable<TrafficControllerPool> getResult() {\n      return FluentIterable.from(pools.build());\n   }\n\n   @Override\n   public void startElement(String url, String name, String qName, Attributes attributes) {\n      if (equalsOrSuffix(qName, \"LBPoolData\") || equalsOrSuffix(qName, \"PoolData\")) {\n         poolHandler.startElement(url, name, qName, attributes);\n      }\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) {\n      if (equalsOrSuffix(qName, \"LBPoolData\")) {\n         pools.add(poolHandler.getResult());\n      }\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/xml/TrafficControllerPoolRecordDetailListHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.xml;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static java.lang.Integer.parseInt;\nimport static org.jclouds.util.SaxUtils.cleanseAttributes;\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport java.util.Map;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.ultradns.ws.domain.TrafficControllerPoolRecord;\nimport org.jclouds.ultradns.ws.domain.TrafficControllerPoolRecordDetail;\nimport org.jclouds.ultradns.ws.domain.TrafficControllerPoolRecordDetail.Status;\nimport org.xml.sax.Attributes;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\n\npublic class TrafficControllerPoolRecordDetailListHandler extends\n      ParseSax.HandlerForGeneratedRequestWithResult<FluentIterable<TrafficControllerPoolRecordDetail>> {\n\n   private final Builder<TrafficControllerPoolRecordDetail> records = ImmutableSet.<TrafficControllerPoolRecordDetail> builder();\n\n   @Override\n   public FluentIterable<TrafficControllerPoolRecordDetail> getResult() {\n      return FluentIterable.from(records.build());\n   }\n\n   @Override\n   public void startElement(String url, String name, String qName, Attributes attrs) {\n      if (!equalsOrSuffix(qName, \"PoolRecordData\"))\n         return;\n      Map<String, String> attributes = cleanseAttributes(attrs);\n      TrafficControllerPoolRecord record = TrafficControllerPoolRecord.create(\n            attributes.get(\"recordType\"),\n            attributes.get(\"pointsTo\"));\n      records.add(TrafficControllerPoolRecordDetail.builder()\n                                             .id(attributes.get(\"poolRecordID\"))\n                                             .poolId(attributes.get(\"poolId\"))\n                                             .record(record)\n                                             .weight(parseInt(checkNotNull(attributes.get(\"weight\"), \"weight\")))\n                                             .priority(parseInt(checkNotNull(attributes.get(\"priority\"), \"priority\")))\n                                             .forceAnswer(attributes.get(\"forceAnswer\"))\n                                             .probingEnabled(\"ENABLED\".equalsIgnoreCase(attributes.get(\"probing\")))\n                                             .status(Status.valueOf(attributes.get(\"status\")))\n                                             .serving(\"Yes\".equalsIgnoreCase(attributes.get(\"serving\")))\n                                             .description(attributes.get(\"description\")).build());\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/xml/UltraWSExceptionHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.xml;\n\nimport static org.jclouds.util.SaxUtils.currentOrNull;\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.ultradns.ws.UltraDNSWSError;\n\nimport com.google.common.base.Optional;\n\npublic class UltraWSExceptionHandler extends ParseSax.HandlerForGeneratedRequestWithResult<UltraDNSWSError> {\n\n   private StringBuilder currentText = new StringBuilder();\n   private int code = -1;\n   private String description;\n\n   @Override\n   public UltraDNSWSError getResult() {\n      return code != -1 ? UltraDNSWSError.fromCodeAndDescription(code, Optional.fromNullable(description)) : null;\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) {\n      if (equalsOrSuffix(qName, \"errorCode\")) {\n         code = Integer.parseInt(currentOrNull(currentText));\n      } else if (equalsOrSuffix(qName, \"errorDescription\")) {\n         description = currentOrNull(currentText);\n      }\n      currentText.setLength(0);\n   }\n\n   @Override\n   public void characters(char[] ch, int start, int length) {\n      currentText.append(ch, start, length);\n   }\n\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/xml/ZoneHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.xml;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.util.SaxUtils.cleanseAttributes;\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport java.util.Map;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.ultradns.ws.domain.Zone;\nimport org.jclouds.ultradns.ws.domain.Zone.DNSSECStatus;\nimport org.xml.sax.Attributes;\n\n\npublic class ZoneHandler extends ParseSax.HandlerForGeneratedRequestWithResult<Zone> {\n\n   private Zone zone;\n\n   @Override\n   public Zone getResult() {\n      try {\n         return zone;\n      } finally {\n         zone = null;\n      }\n   }\n\n   @Override\n   public void startElement(String uri, String localName, String qName, Attributes attrs) {\n      Map<String, String> attributes = cleanseAttributes(attrs);\n      if (equalsOrSuffix(qName, \"UltraZone\")) {\n         zone = Zone.builder()\n                    .id(attributes.get(\"zoneId\"))\n                    .name(attributes.get(\"zoneName\"))\n                    .typeCode(Integer.parseInt(checkNotNull(attributes.get(\"zoneType\"), \"zoneType\")))\n                    .accountId(attributes.get(\"accountId\"))\n                    .ownerId(attributes.get(\"owner\"))\n                    .dnssecStatus(DNSSECStatus.fromValue(attributes.get(\"dnssecStatus\")))\n                    .primarySrc(attributes.get(\"primarySrc\")).build();\n      }\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/xml/ZoneListHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.xml;\n\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.ultradns.ws.domain.Zone;\nimport org.xml.sax.Attributes;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.ImmutableSet.Builder;\nimport com.google.inject.Inject;\n\npublic class ZoneListHandler extends ParseSax.HandlerForGeneratedRequestWithResult<FluentIterable<Zone>> {\n\n   private final ZoneHandler zoneHandler;\n\n   private Builder<Zone> zones = ImmutableSet.<Zone> builder();\n\n   @Inject\n   public ZoneListHandler(ZoneHandler zoneHandler) {\n      this.zoneHandler = zoneHandler;\n   }\n\n   @Override\n   public FluentIterable<Zone> getResult() {\n      return FluentIterable.from(zones.build());\n   }\n\n   @Override\n   public void startElement(String url, String name, String qName, Attributes attributes) {\n      if (equalsOrSuffix(qName, \"UltraZone\")) {\n         zoneHandler.startElement(url, name, qName, attributes);\n      }\n   }\n\n   @Override\n   public void endElement(String uri, String name, String qName) {\n      if (equalsOrSuffix(qName, \"UltraZone\")) {\n         zones.add(zoneHandler.getResult());\n      }\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/main/java/org/jclouds/ultradns/ws/xml/ZonePropertiesHandler.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.xml;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.util.SaxUtils.cleanseAttributes;\nimport static org.jclouds.util.SaxUtils.equalsOrSuffix;\n\nimport java.util.Map;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.date.DateService;\nimport org.jclouds.http.functions.ParseSax;\nimport org.jclouds.ultradns.ws.domain.Zone.Type;\nimport org.jclouds.ultradns.ws.domain.ZoneProperties;\nimport org.xml.sax.Attributes;\n\npublic class ZonePropertiesHandler extends ParseSax.HandlerForGeneratedRequestWithResult<ZoneProperties> {\n\n   private final DateService dateService;\n\n   @Inject\n   ZonePropertiesHandler(DateService dateService) {\n      this.dateService = dateService;\n   }\n\n   private ZoneProperties zone;\n\n   @Override\n   public ZoneProperties getResult() {\n      try {\n         return zone;\n      } finally {\n         zone = null;\n      }\n   }\n\n   @Override\n   public void startElement(String uri, String localName, String qName, Attributes attrs) {\n      Map<String, String> attributes = cleanseAttributes(attrs);\n      if (equalsOrSuffix(qName, \"GeneralZoneProperties\")) {\n         Type type = Type.valueOf(checkNotNull(attributes.get(\"zoneType\"), \"zoneType\").toUpperCase());\n         int count = Integer.parseInt(checkNotNull(attributes.get(\"resourceRecordCount\"), \"resourceRecordCount\"));\n         zone = ZoneProperties.builder()\n                              .name(attributes.get(\"name\"))\n                              .typeCode(type.getCode())\n                              .resourceRecordCount(count)\n                              .modified(dateService.iso8601DateParse(attributes.get(\"modified\"))).build();\n      }\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/UltraDNSWSApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws;\nimport static com.google.common.net.HttpHeaders.HOST;\nimport static jakarta.ws.rs.HttpMethod.POST;\nimport static jakarta.ws.rs.core.Response.Status.OK;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.ultradns.ws.internal.BaseUltraDNSWSApiExpectTest;\nimport org.jclouds.ultradns.ws.parse.GetAccountsListOfUserResponseTest;\nimport org.jclouds.ultradns.ws.parse.GetAvailableRegionsResponseTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"UltraDNSWSApiExpectTest\")\npublic class UltraDNSWSApiExpectTest extends BaseUltraDNSWSApiExpectTest {\n\n   HttpRequest getCurrentAccount = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/get_current_account.xml\", \"application/xml\")).build();\n\n   HttpResponse getCurrentAccountResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/account.xml\", \"application/xml\")).build();\n\n   public void testGetCurrentAccountWhenResponseIs2xx() {\n\n      UltraDNSWSApi success = requestSendsResponse(getCurrentAccount, getCurrentAccountResponse);\n\n      assertEquals(\n            success.getCurrentAccount().toString(),\n            new GetAccountsListOfUserResponseTest().expected().toString());\n   }\n\n   HttpRequest getRegionsById = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/list_regions.xml\", \"application/xml\")).build();\n\n   HttpResponse getRegionsByIdResponse = HttpResponse.builder().statusCode(200)\n         .payload(payloadFromResourceWithContentType(\"/regions.xml\", \"application/xml\")).build();\n\n   public void testGetRegionsByIdWhenResponseIs2xx() {\n\n      UltraDNSWSApi success = requestSendsResponse(getRegionsById, getRegionsByIdResponse);\n\n      assertEquals(\n            success.getRegionsByIdAndName().toString(),\n            new GetAvailableRegionsResponseTest().expected().toString());\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/UltraDNSWSApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws;\n\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\n\nimport java.util.Collection;\nimport java.util.Map.Entry;\n\nimport org.jclouds.ultradns.ws.domain.IdAndName;\nimport org.jclouds.ultradns.ws.internal.BaseUltraDNSWSApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"UltraDNSWSApiLiveTest\")\npublic class UltraDNSWSApiLiveTest extends BaseUltraDNSWSApiLiveTest {\n\n   @Test\n   protected void testGetCurrentAccount() {\n      IdAndName account = api.getCurrentAccount();\n      checkAccount(account);\n   }\n\n   private void checkAccount(IdAndName account) {\n      assertNotNull(account.getId(), \"Id cannot be null for \" + account);\n      assertNotNull(account.getName(), \"Name cannot be null for \" + account);\n   }\n\n   @Test\n   public void testListRegions() {\n      for (Entry<IdAndName, Collection<String>> region : api.getRegionsByIdAndName().asMap().entrySet()) {\n         checkRegion(region);\n      }\n   }\n\n   private void checkRegion(Entry<IdAndName, Collection<String>> region) {\n      assertNotNull(region.getKey().getId(), \"Id cannot be null \" + region);\n      assertNotNull(region.getKey().getName(), \"Name cannot be null \" + region);\n      assertNotNull(region.getValue(), \"TerritoryNames cannot be null \" + region);\n      assertFalse(region.getValue().isEmpty(), \"TerritoryNames cannot be empty \" + region);\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/UltraDNSWSProviderMetadataTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws;\n\nimport org.jclouds.providers.internal.BaseProviderMetadataTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"UltraDNSWSProviderMetadataTest\")\npublic class UltraDNSWSProviderMetadataTest extends BaseProviderMetadataTest {\n\n   // no dns abstraction, yet\n   public UltraDNSWSProviderMetadataTest() {\n      super(new UltraDNSWSProviderMetadata(), new UltraDNSWSApiMetadata());\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/binders/ZoneAndResourceRecordToXMLTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.binders;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.ultradns.ws.domain.ResourceRecord;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ZoneAndResourceRecordToXMLTest\")\npublic class ZoneAndResourceRecordToXMLTest {\n\n   private static final String A = \"<v01:createResourceRecord><transactionID /><resourceRecord ZoneName=\\\"jclouds.org.\\\" Type=\\\"1\\\" DName=\\\"www.jclouds.org.\\\" TTL=\\\"3600\\\"><InfoValues Info1Value=\\\"1.1.1.1\\\" /></resourceRecord></v01:createResourceRecord>\";\n\n   public void testA() {\n      assertEquals(ZoneAndResourceRecordToXML.toXML(\"jclouds.org.\", ResourceRecord.rrBuilder()\n                                                                                  .name(\"www.jclouds.org.\")\n                                                                                  .type(1)\n                                                                                  .ttl(3600)\n                                                                                  .rdata(\"1.1.1.1\").build()), A);\n   }\n\n   private static final String MX = \"<v01:createResourceRecord><transactionID /><resourceRecord ZoneName=\\\"jclouds.org.\\\" Type=\\\"15\\\" DName=\\\"mail.jclouds.org.\\\" TTL=\\\"1800\\\"><InfoValues Info1Value=\\\"10\\\" Info2Value=\\\"maileast.jclouds.org.\\\" /></resourceRecord></v01:createResourceRecord>\";\n\n   public void testMX() {\n      assertEquals(ZoneAndResourceRecordToXML.toXML(\"jclouds.org.\", ResourceRecord.rrBuilder()\n                                                                                  .name(\"mail.jclouds.org.\")\n                                                                                  .type(15)\n                                                                                  .ttl(1800)\n                                                                                  .infoValue(10)\n                                                                                  .infoValue(\"maileast.jclouds.org.\").build()), MX);\n   }\n\n   private static final String A_UPDATE = \"<v01:updateResourceRecord><transactionID /><resourceRecord Guid=\\\"ABCDEF\\\" ZoneName=\\\"jclouds.org.\\\" Type=\\\"1\\\" DName=\\\"www.jclouds.org.\\\" TTL=\\\"3600\\\"><InfoValues Info1Value=\\\"1.1.1.1\\\" /></resourceRecord></v01:updateResourceRecord>\";\n\n   public void testUpdate() {\n      assertEquals(ZoneAndResourceRecordToXML.update(\"ABCDEF\", A), A_UPDATE);\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/features/DirectionalGroupApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.features;\nimport static com.google.common.net.HttpHeaders.HOST;\nimport static jakarta.ws.rs.HttpMethod.POST;\nimport static jakarta.ws.rs.core.Response.Status.OK;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.ultradns.ws.UltraDNSWSApi;\nimport org.jclouds.ultradns.ws.domain.DirectionalGroupCoordinates;\nimport org.jclouds.ultradns.ws.internal.BaseUltraDNSWSApiExpectTest;\nimport org.jclouds.ultradns.ws.parse.GetAccountLevelDirectionalGroupsResponseTest;\nimport org.jclouds.ultradns.ws.parse.GetAvailableGroupsResponseTest;\nimport org.jclouds.ultradns.ws.parse.GetDirectionalDNSGroupDetailsResponseTest;\nimport org.jclouds.ultradns.ws.parse.GetDirectionalDNSRecordsForHostResponseTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"DirectionalGroupApiExpectTest\")\npublic class DirectionalGroupApiExpectTest extends BaseUltraDNSWSApiExpectTest {\n\n   HttpRequest listGroupNamesByRecordNameAndType = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/list_directionalgroup_names.xml\", \"application/xml\")).build();\n\n   HttpResponse listGroupNamesByRecordNameAndTypeResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n\n         .payload(payloadFromResourceWithContentType(\"/directionalgroup_names.xml\", \"application/xml\")).build();\n   \n   public void testListGroupNamesByRecordNameAndTypeWhenResponseIs2xx() {\n      UltraDNSWSApi success = requestSendsResponse(listGroupNamesByRecordNameAndType, listGroupNamesByRecordNameAndTypeResponse);\n\n      assertEquals(success.getDirectionalGroupApiForAccount(\"accountid\").listGroupNamesByDNameAndType(\"www.jclouds.org.\", 1).toString(),\n            new GetAvailableGroupsResponseTest().expected().toString());\n   }\n\n   HttpRequest listRecordsByGroupCoordinates = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/list_directionalgroup_records.xml\", \"application/xml\")).build();\n\n   HttpResponse listRecordsByGroupCoordinatesResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n\n         .payload(payloadFromResourceWithContentType(\"/directionalrecords.xml\", \"application/xml\")).build();\n\n   public void testListRecordsByGroupCoordinatesWhenResponseIs2xx() {\n      UltraDNSWSApi success = requestSendsResponse(listRecordsByGroupCoordinates, listRecordsByGroupCoordinatesResponse);\n\n      DirectionalGroupCoordinates group = DirectionalGroupCoordinates.builder()\n                                                                     .zoneName(\"jclouds.org.\")\n                                                                     .recordName(\"www.jclouds.org.\")\n                                                                     .recordType(1)\n                                                                     .groupName(\"EU-www.jclouds.org.\").build();\n      assertEquals(\n            success.getDirectionalGroupApiForAccount(\"accountid\").listRecordsByGroupCoordinates(group).toString(),\n            new GetDirectionalDNSRecordsForHostResponseTest().expected().toString());\n   }\n\n   HttpRequest get = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/get_directionalgroup.xml\", \"application/xml\")).build();\n\n   HttpResponse getResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n\n         .payload(payloadFromResourceWithContentType(\"/directionalgroup.xml\", \"application/xml\")).build();\n   \n   public void testGetWhenResponseIs2xx() {\n      UltraDNSWSApi success = requestSendsResponse(get, getResponse);\n\n      assertEquals(success.getDirectionalGroupApiForAccount(\"accountid\").get(\"0000000000A\").toString(),\n            new GetDirectionalDNSGroupDetailsResponseTest().expected().toString());\n   }\n\n   HttpRequest listAccountLevelGroups = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/list_accountlevelgroups.xml\", \"application/xml\")).build();\n\n   HttpResponse listAccountLevelGroupsResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n\n         .payload(payloadFromResourceWithContentType(\"/accountlevelgroups.xml\", \"application/xml\")).build();\n   \n   public void testListAccountLevelGroupsWhenResponseIs2xx() {\n      UltraDNSWSApi success = requestSendsResponse(listAccountLevelGroups, listAccountLevelGroupsResponse);\n\n      assertEquals(success.getDirectionalGroupApiForAccount(\"accountid\").listAccountLevelGroups().toString(),\n            new GetAccountLevelDirectionalGroupsResponseTest().expected().toString());\n   }\n\n   HttpRequest listRecordsByAccountLevelGroup = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/list_accountlevelgroup_records.xml\", \"application/xml\")).build();\n\n   HttpResponse listRecordsByAccountLevelGroupResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n\n         .payload(payloadFromResourceWithContentType(\"/directionalrecords.xml\", \"application/xml\")).build();\n\n   public void testListRecordsByAccountLevelGroupWhenResponseIs2xx() {\n      UltraDNSWSApi success = requestSendsResponse(listRecordsByAccountLevelGroup, listRecordsByAccountLevelGroupResponse);\n\n      assertEquals(\n            success.getDirectionalGroupApiForAccount(\"accountid\").listRecordsByAccountLevelGroup(\"000000000000000A\").toString(),\n            new GetDirectionalDNSRecordsForHostResponseTest().expected().toString());\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/features/DirectionalGroupApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.EnumSet;\nimport java.util.Set;\n\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.jclouds.ultradns.ws.domain.AccountLevelGroup;\nimport org.jclouds.ultradns.ws.domain.DirectionalGroup;\nimport org.jclouds.ultradns.ws.domain.DirectionalGroupCoordinates;\nimport org.jclouds.ultradns.ws.domain.DirectionalPool;\nimport org.jclouds.ultradns.ws.domain.DirectionalPool.RecordType;\nimport org.jclouds.ultradns.ws.domain.DirectionalPoolRecordDetail;\nimport org.jclouds.ultradns.ws.domain.Zone;\nimport org.jclouds.ultradns.ws.internal.BaseUltraDNSWSApiLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.Sets;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"DirectionalGroupApiLiveTest\")\npublic class DirectionalGroupApiLiveTest extends BaseUltraDNSWSApiLiveTest {\n\n   @Test\n   public void testListAccountLevelGroups() {\n      for (AccountLevelGroup group : api().listAccountLevelGroups()) {\n         checkGroup(group);\n      }\n   }\n\n   private void checkGroup(AccountLevelGroup group) {\n      assertNotNull(group.getId(), \"Id cannot be null \" + group);\n      assertNotNull(group.getName(), \"Name cannot be null \" + group);\n      assertNotNull(group.getType(), \"Type cannot be null \" + group);\n      assertTrue(group.getRecordCount() >= 0, \"RecordCount must be positive \" + group);\n   }\n\n   @Test\n   public void testListRecordsByAccountLevelGroup() {\n      for (AccountLevelGroup group : api().listAccountLevelGroups()) {\n         for (DirectionalPoolRecordDetail rr : api().listRecordsByAccountLevelGroup(group.getId())) {\n            DirectionalPoolApiLiveTest.checkDirectionalRecordDetail(rr);\n         }\n      }\n   }\n\n   @Test\n   public void testGetDirectionalGroup() {\n      for (AccountLevelGroup group : api().listAccountLevelGroups()) {\n         DirectionalGroup withRegions = api().get(group.getId());\n         assertEquals(withRegions.getName(), group.getName());\n         assertTrue(!withRegions.isEmpty());\n      }\n   }\n\n   Set<DirectionalGroupCoordinates> allGroups = Sets.newLinkedHashSet();\n\n   @Test\n   public void testListGroupNamesByRecordNameAndType() {\n      for (Zone zone : api.getZoneApi().listByAccount(account.getId())) {\n         for (DirectionalPool pool : api.getDirectionalPoolApiForZone(zone.getName()).list()) {\n            for (RecordType type : EnumSet.allOf(RecordType.class)) {\n               for (String groupName : api().listGroupNamesByDNameAndType(pool.getDName(), type.getCode())) {\n                  allGroups.add(DirectionalGroupCoordinates.builder()\n                                                           .zoneName(zone.getName())\n                                                           .recordName(pool.getDName())\n                                                           .recordType(type.getCode())\n                                                           .groupName(groupName).build());\n               }\n            }\n         }\n      }\n   }\n\n   @Test(dependsOnMethods = \"testListGroupNamesByRecordNameAndType\")\n   public void testListRecordsByGroupCoordinates() {\n      for (DirectionalGroupCoordinates group : allGroups) {\n         for (DirectionalPoolRecordDetail rr : api().listRecordsByGroupCoordinates(group)) {\n            DirectionalPoolApiLiveTest.checkDirectionalRecordDetail(rr);\n         }\n      }\n   }\n\n   @Test(expectedExceptions = ResourceNotFoundException.class, expectedExceptionsMessageRegExp = \"Group does not exist.\")\n   public void testListRecordsByAccountLevelGroupWhenGroupIdNotFound() {\n      api().listRecordsByAccountLevelGroup(\"AAAAAAAAAAAAAAAA\");\n   }\n\n   private DirectionalGroupApi api() {\n      return api.getDirectionalGroupApiForAccount(account.getId());\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/features/DirectionalPoolApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.features;\nimport static com.google.common.net.HttpHeaders.HOST;\nimport static jakarta.ws.rs.HttpMethod.POST;\nimport static jakarta.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR;\nimport static jakarta.ws.rs.core.Response.Status.OK;\nimport static org.jclouds.ultradns.ws.domain.DirectionalPool.RecordType.IPV4;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.jclouds.ultradns.ws.UltraDNSWSApi;\nimport org.jclouds.ultradns.ws.UltraDNSWSExceptions.ResourceAlreadyExistsException;\nimport org.jclouds.ultradns.ws.domain.DirectionalGroup;\nimport org.jclouds.ultradns.ws.domain.DirectionalPoolRecord;\nimport org.jclouds.ultradns.ws.internal.BaseUltraDNSWSApiExpectTest;\nimport org.jclouds.ultradns.ws.parse.GetDirectionalDNSRecordsForHostResponseTest;\nimport org.jclouds.ultradns.ws.parse.GetDirectionalPoolsByZoneResponseTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\", testName = \"DirectionalPoolApiExpectTest\")\npublic class DirectionalPoolApiExpectTest extends BaseUltraDNSWSApiExpectTest {\n   HttpRequest create = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/create_directionalpool.xml\", \"application/xml\")).build();\n\n   HttpResponse createResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/directionalpool_created.xml\", \"application/xml\")).build();\n\n   public void testCreateWhenResponseIs2xx() {\n      UltraDNSWSApi success = requestSendsResponse(create, createResponse);\n      assertEquals(\n            success.getDirectionalPoolApiForZone(\"jclouds.org.\").createForDNameAndType(\"foo\",\n                  \"www.jclouds.org.\", IPV4.getCode()), \"06063DC355055E68\");\n   }\n\n   HttpResponse alreadyCreated = HttpResponse.builder().statusCode(INTERNAL_SERVER_ERROR.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/directionalpool_already_exists.xml\", \"application/xml\"))\n         .build();\n\n   @Test(expectedExceptions = ResourceAlreadyExistsException.class, expectedExceptionsMessageRegExp = \"Pool already created for this host name : www.jclouds.org.\")\n   public void testCreateWhenResponseError2912() {\n      UltraDNSWSApi already = requestSendsResponse(create, alreadyCreated);\n      already.getDirectionalPoolApiForZone(\"jclouds.org.\").createForDNameAndType(\"foo\", \"www.jclouds.org.\",\n            IPV4.getCode());\n   }\n   \n   HttpRequest addFirstRecordInNonConfiguredGroup = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/create_directionalrecord.xml\", \"application/xml\")).build();\n\n   HttpResponse recordCreatedResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/directionalrecord_created.xml\", \"application/xml\")).build();\n\n   DirectionalPoolRecord record =  DirectionalPoolRecord.drBuilder()\n                                                        .type(\"A\")\n                                                        .ttl(300)\n                                                        .rdata(\"1.1.0.1\").build();\n\n   public void testAddFirstRecordInNonConfiguredGroupWhenResponseIs2xx() {\n      UltraDNSWSApi success = requestSendsResponse(addFirstRecordInNonConfiguredGroup, recordCreatedResponse);\n      assertEquals(\n            success.getDirectionalPoolApiForZone(\"jclouds.org.\").addFirstRecordInNonConfiguredGroup(\"06063DC355055E68\",\n                  record), \"06063DC355058294\");\n   }\n\n   HttpResponse recordAlreadyCreated = HttpResponse.builder().statusCode(INTERNAL_SERVER_ERROR.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/directionalrecord_already_exists.xml\", \"application/xml\"))\n         .build();\n\n   @Test(expectedExceptions = ResourceAlreadyExistsException.class, expectedExceptionsMessageRegExp = \"Resource Record already exists.\")\n   public void testAddFirstRecordInNonConfiguredGroupWhenResponseError1802() {\n      UltraDNSWSApi already = requestSendsResponse(addFirstRecordInNonConfiguredGroup, recordAlreadyCreated);\n      already.getDirectionalPoolApiForZone(\"jclouds.org.\").addFirstRecordInNonConfiguredGroup(\"06063DC355055E68\",\n            record);\n   }\n\n   HttpRequest addRecordIntoNewGroup = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/create_directionalrecord_newgroup.xml\", \"application/xml\"))\n         .build();\n\n   DirectionalGroup group = DirectionalGroup.builder()\n                                            .name(\"Mexas\")\n                                            .description(\"Clients we classify as being in US\")\n                                            .mapRegionToTerritories(\"United States (US)\",\n                                                  ImmutableSet.of(\"Maryland\", \"Texas\"))\n                                            .build();\n\n   public void testAddRecordIntoNewGroupWhenResponseIs2xx() {\n      UltraDNSWSApi success = requestSendsResponse(addRecordIntoNewGroup, recordCreatedResponse);\n      assertEquals(\n            success.getDirectionalPoolApiForZone(\"jclouds.org.\").addRecordIntoNewGroup(\"06063DC355055E68\", record,\n                  group), \"06063DC355058294\");\n   }\n\n   HttpRequest addRecordIntoExistingGroup = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/create_directionalrecord_existinggroup.xml\", \"application/xml\"))\n         .build();\n\n   public void testAddRecordIntoExistingGroupWhenResponseIs2xx() {\n      UltraDNSWSApi success = requestSendsResponse(addRecordIntoExistingGroup, recordCreatedResponse);\n      assertEquals(\n            success.getDirectionalPoolApiForZone(\"jclouds.org.\").addRecordIntoExistingGroup(\"06063DC355055E68\",\n                  record, \"AAABBBCCCDDDEEE\"), \"06063DC355058294\");\n   }\n\n   HttpRequest updateRecord = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/update_directionalrecord.xml\", \"application/xml\")).build();\n\n   HttpResponse updateRecordResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/directionalrecord_updated.xml\", \"application/xml\")).build();\n\n   public void testUpdateRecordWhenResponseIs2xx() {\n      UltraDNSWSApi success = requestSendsResponse(updateRecord, updateRecordResponse);\n      success.getDirectionalPoolApiForZone(\"jclouds.org.\").updateRecord(\"04053D8E57C7931F\", record);\n   }\n\n   HttpResponse recordDoesntExist = HttpResponse.builder().message(\"Server Error\").statusCode(INTERNAL_SERVER_ERROR.getStatusCode())\n         .payload(payloadFromResource(\"/directionalrecord_doesnt_exist.xml\")).build();\n\n   @Test(expectedExceptions = ResourceNotFoundException.class, expectedExceptionsMessageRegExp = \"Directional Pool Record does not exist in the system\")\n   public void testUpdateRecordWhenResponseNotFound() {\n      UltraDNSWSApi notFound = requestSendsResponse(updateRecord, recordDoesntExist);\n      notFound.getDirectionalPoolApiForZone(\"jclouds.org.\").updateRecord(\"04053D8E57C7931F\", record);\n   }\n\n   HttpRequest updateRecordAndGroup = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/update_directionalrecord_group.xml\", \"application/xml\")).build();\n\n   public void testUpdateRecordAndGroupWhenResponseIs2xx() {\n      UltraDNSWSApi success = requestSendsResponse(updateRecordAndGroup, updateRecordResponse);\n      success.getDirectionalPoolApiForZone(\"jclouds.org.\").updateRecordAndGroup(\"04053D8E57C7931F\", record, group);\n   }\n\n   HttpRequest deleteRecord = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/delete_directionalrecord.xml\", \"application/xml\")).build();\n\n   HttpResponse deleteRecordResponse = HttpResponse.builder().statusCode(404)\n         .payload(payloadFromResourceWithContentType(\"/directionalrecord_deleted.xml\", \"application/xml\")).build();\n\n   public void testDeleteRecordWhenResponseIs2xx() {\n      UltraDNSWSApi success = requestSendsResponse(deleteRecord, deleteRecordResponse);\n      success.getDirectionalPoolApiForZone(\"jclouds.org.\").deleteRecord(\"04053D8E57C7931F\");\n   }\n\n   public void testDeleteRecordWhenResponseNotFound() {\n      UltraDNSWSApi notFound = requestSendsResponse(deleteRecord, recordDoesntExist);\n      notFound.getDirectionalPoolApiForZone(\"jclouds.org.\").deleteRecord(\"04053D8E57C7931F\");\n   }\n\n   HttpRequest list = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/list_directionalpools.xml\", \"application/xml\")).build();\n\n   HttpResponse listResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n\n         .payload(payloadFromResourceWithContentType(\"/directionalpools.xml\", \"application/xml\")).build();\n   \n   public void testListWhenResponseIs2xx() {\n      UltraDNSWSApi success = requestSendsResponse(list, listResponse);\n\n      assertEquals(success.getDirectionalPoolApiForZone(\"jclouds.org.\").list().toString(),\n            new GetDirectionalPoolsByZoneResponseTest().expected().toString());\n   }\n\n   HttpRequest listRecords = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/list_directionalrecords.xml\", \"application/xml\")).build();\n\n   HttpResponse listRecordsResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n\n         .payload(payloadFromResourceWithContentType(\"/directionalrecords.xml\", \"application/xml\")).build();\n\n   public void testListRecordsWhenResponseIs2xx() {\n      UltraDNSWSApi success = requestSendsResponse(listRecords, listRecordsResponse);\n\n      assertEquals(success.getDirectionalPoolApiForZone(\"jclouds.org.\").listRecordsByDNameAndType(\"www.jclouds.org.\", 1)\n            .toString(), new GetDirectionalDNSRecordsForHostResponseTest().expected().toString());\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/features/DirectionalPoolApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.features;\n\nimport static com.google.common.base.Predicates.equalTo;\nimport static com.google.common.base.Predicates.not;\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Iterables.isEmpty;\nimport static com.google.common.collect.Sets.newLinkedHashSet;\nimport static java.util.logging.Logger.getAnonymousLogger;\nimport static org.jclouds.ultradns.ws.domain.DirectionalPool.RecordType.IPV4;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\n\nimport java.util.EnumSet;\nimport java.util.Set;\n\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.jclouds.ultradns.ws.UltraDNSWSExceptions.DirectionalGroupOverlapException;\nimport org.jclouds.ultradns.ws.UltraDNSWSExceptions.ResourceAlreadyExistsException;\nimport org.jclouds.ultradns.ws.domain.DirectionalGroup;\nimport org.jclouds.ultradns.ws.domain.DirectionalPool;\nimport org.jclouds.ultradns.ws.domain.DirectionalPool.RecordType;\nimport org.jclouds.ultradns.ws.domain.DirectionalPool.TieBreak;\nimport org.jclouds.ultradns.ws.domain.DirectionalPool.Type;\nimport org.jclouds.ultradns.ws.domain.DirectionalPoolRecord;\nimport org.jclouds.ultradns.ws.domain.DirectionalPoolRecordDetail;\nimport org.jclouds.ultradns.ws.domain.IdAndName;\nimport org.jclouds.ultradns.ws.domain.Zone;\nimport org.jclouds.ultradns.ws.internal.BaseDirectionalApiLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Multimap;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"DirectionalPoolApiLiveTest\")\npublic class DirectionalPoolApiLiveTest extends BaseDirectionalApiLiveTest {\n\n   @Test\n   public void testListDirectionalPools() {\n      for (Zone zone : api.getZoneApi().listByAccount(account.getId())) {\n         for (DirectionalPool pool : api(zone.getName()).list()) {\n            checkDirectional(pool);\n         }\n      }\n   }\n\n   private void checkDirectional(DirectionalPool pool) {\n      assertNotNull(pool.getZoneId(), \"ZoneId cannot be null \" + pool);\n      assertNotNull(pool.getId(), \"Id cannot be null \" + pool);\n      assertNotNull(pool.getDName(), \"DName cannot be null \" + pool);\n      assertNotNull(pool.getName(), \"Name cannot be null \" + pool);\n      assertNotNull(pool.getType(), \"Type cannot be null \" + pool);\n      assertNotNull(pool.getTieBreak(), \"TieBreak cannot be null \" + pool);\n   }\n\n   Set<IdAndName> allDirectionalGroups = newLinkedHashSet();\n\n   @Test\n   public void testListDirectionalRecords() {\n      for (Zone zone : api.getZoneApi().listByAccount(account.getId())) {\n         for (DirectionalPool pool : api(zone.getName()).list()) {\n            for (RecordType type : EnumSet.allOf(RecordType.class)) {\n               for (DirectionalPoolRecordDetail rr : api(zone.getName())\n                     .listRecordsByDNameAndType(pool.getDName(), type.getCode())) {\n                  checkDirectionalRecordDetail(rr);\n                  Iterable<IdAndName> groups = Optional.presentInstances(ImmutableSet.of(rr.getGroup(),\n                        rr.getGeolocationGroup(), rr.getGeolocationGroup()));\n                  assertFalse(isEmpty(groups), \"No groups \" + rr);\n                  for (IdAndName group : groups) {\n                     allDirectionalGroups.add(group);\n                     assertNotNull(group.getId(), \"Id cannot be null \" + group);\n                     assertNotNull(group.getName(), \"Name cannot be null \" + group);\n                  }\n                  assertEquals(rr.getZoneName(), zone.getName());\n                  assertEquals(rr.getName(), pool.getDName());\n                  switch (pool.getType()) {\n                  case GEOLOCATION:\n                     assertNotNull(rr.getGeolocationGroup().or(rr.getGroup()).orNull(),\n                           \"GeolocationGroup or Group must be present \" + rr);\n                     assertNull(rr.getSourceIpGroup().orNull(), \"SourceIpGroup must be absent \" + rr);\n                     break;\n                  case SOURCEIP:\n                     assertNotNull(rr.getSourceIpGroup().orNull(), \"SourceIpGroup must be present \" + rr);\n                     assertNull(rr.getGeolocationGroup().orNull(), \"GeolocationGroup must be absent \" + rr);\n                     break;\n                  case MIXED:\n                     assertNotNull(rr.getGeolocationGroup().or(rr.getSourceIpGroup()).or(rr.getGroup()).orNull(),\n                           \"GeolocationGroup, SourceIpGroup or Group must be present \" + rr);\n                     break;\n                  }\n               }\n            }\n         }\n      }\n   }\n\n   static void checkDirectionalRecord(DirectionalPoolRecord rr) {\n      assertNotNull(rr.getType(), \"Type cannot be null \" + rr);\n      assertNotNull(rr.getTTL(), \"TTL cannot be null \" + rr);\n      assertNotNull(rr.getRData(), \"InfoValues cannot be null \" + rr);\n   }\n\n   static DirectionalPoolRecordDetail checkDirectionalRecordDetail(DirectionalPoolRecordDetail rr) {\n      assertNotNull(rr.getZoneName(), \"ZoneName cannot be null \" + rr);\n      assertNotNull(rr.getName(), \"DName cannot be null \" + rr);\n      assertNotNull(rr.getId(), \"Id cannot be null \" + rr);\n      assertNotNull(rr.getZoneName(), \"ZoneName cannot be null \" + rr);\n      checkDirectionalRecord(rr.getRecord());\n      return rr;\n   }\n\n   @Test(expectedExceptions = ResourceNotFoundException.class, expectedExceptionsMessageRegExp = \"Parent Zone does not exist in the system.\")\n   public void testListDirectionalsWhenZoneIdNotFound() {\n      api(\"AAAAAAAAAAAAAAAA\").list();\n   }\n\n   @Test\n   public void testDeleteWhenNotFound() {\n      api(zoneName).delete(\"06063D9C54C5AE09\");\n   }\n\n   @Test\n   public void testDeleteRecordWhenNotFound() {\n      api(zoneName).deleteRecord(\"06063D9C54C5AE09\");\n   }\n\n   @Test(expectedExceptions = ResourceNotFoundException.class, expectedExceptionsMessageRegExp = \"Directional Pool Record does not exist in the system\")\n   public void testUpdateRecordWhenNotFound() {\n      api(zoneName).updateRecord(\"06063D9C54C5AE09\", cnameRecordCanary);\n   }\n\n   @Test\n   public void testCreateCNAMEPool() {\n      cnamePoolId = api(zoneName).createForDNameAndType(\"Geo pool\", dname, IPV4.getCode());\n      getAnonymousLogger().info(\"created Geo pool: \" + cnamePoolId);\n      Optional<DirectionalPool> ipv4Pool = getPoolById(cnamePoolId);\n      assertTrue(ipv4Pool.isPresent());\n      assertEquals(ipv4Pool.get().getZoneId(), zoneId);\n      assertEquals(ipv4Pool.get().getName().get(), \"Geo pool\");\n      assertEquals(ipv4Pool.get().getDName(), dname);\n      assertEquals(ipv4Pool.get().getType(), Type.GEOLOCATION);\n      assertEquals(ipv4Pool.get().getTieBreak(), TieBreak.GEOLOCATION);\n   }\n\n   @Test(dependsOnMethods = \"testCreateCNAMEPool\", expectedExceptions = ResourceAlreadyExistsException.class)\n   public void testDuplicateCreateCNAMEPool() {\n      api(zoneName).createForDNameAndType(\"Geo pool\", dname, IPV4.getCode());\n   }\n\n   @Test(dependsOnMethods = \"testDuplicateCreateCNAMEPool\")\n   public void addCNAMERecordsToPool() {\n      cnameEU = api(zoneName).addRecordIntoNewGroup(cnamePoolId, cnameRecordEU, eu);\n      getAnonymousLogger().info(\"created CNAME record in ipv4 pool: \" + cnameEU);\n      checkRecordConsistent(dname, cnameEU, cnameRecordEU, eu);\n\n      cnameUS = api(zoneName).addRecordIntoNewGroup(cnamePoolId, cnameRecordUS, us);\n      getAnonymousLogger().info(\"created CNAME record in ipv4 pool: \" + cnameUS);\n      checkRecordConsistent(dname, cnameUS, cnameRecordUS, us);\n\n      cnameCanary = api(zoneName).addRecordIntoNewGroup(cnamePoolId, cnameRecordCanary, nebraska);\n      getAnonymousLogger().info(\"created CNAME record in ipv4 pool: \" + cnameCanary);\n      checkRecordConsistent(dname, cnameCanary, cnameRecordCanary, nebraska);\n   }\n\n   @Test(dependsOnMethods = \"addCNAMERecordsToPool\", expectedExceptions = ResourceAlreadyExistsException.class)\n   public void testDuplicateAddCNAMERecordsToPool() {\n      api(zoneName).addRecordIntoNewGroup(cnamePoolId, cnameRecordEU, eu);\n   }\n\n   @Test(dependsOnMethods = \"testDuplicateAddCNAMERecordsToPool\")\n   public void testUpdateRecordTTL() {\n      cnameRecordCanary = cnameRecordCanary.toBuilder().ttl(180).build();\n      api(zoneName).updateRecord(cnameCanary, cnameRecordCanary);\n      getAnonymousLogger().info(\"updated CNAME record TTL in ipv4 pool: \" + cnameCanary);\n      checkRecordConsistent(dname, cnameCanary, cnameRecordCanary, nebraska);\n   }\n   \n   @Test(dependsOnMethods = \"testUpdateRecordTTL\", expectedExceptions = DirectionalGroupOverlapException.class)\n   public void testUpdateGroupWithOverlappingTerritories() {\n      DirectionalGroup withUtah = nebraska.toBuilder().mapRegionToTerritory(REGION_US, \"Utah\").build();\n      checkGroupByDNameAndIdContainsTerritory(dname, cnameUS, \"Utah\");\n      try {\n         api(zoneName).updateRecordAndGroup(cnameCanary, cnameRecordCanary, withUtah);\n      } finally {\n         checkRecordConsistent(dname, cnameCanary, cnameRecordCanary, nebraska);\n      }\n   }\n\n   @Test(dependsOnMethods = \"testUpdateGroupWithOverlappingTerritories\")\n   public void testUpdateGroupWithLessTerritories() {\n      Multimap<String, String> minusUtah = ImmutableMultimap.<String, String>builder()\n                  .putAll(\"United States (US)\", filter(us.get(REGION_US), not(equalTo(\"Utah\"))))\n                  .build();\n      \n      api(zoneName).updateRecordAndGroup(cnameUS, cnameRecordUS, us.toBuilder()\n                                                                   .regionToTerritories(minusUtah)\n                                                                   .build());\n\n      checkGroupByDNameAndIdDoesntContainTerritory(dname, cnameUS, \"Utah\");\n   }\n\n   @Test(dependsOnMethods = \"testUpdateGroupWithLessTerritories\")\n   public void testUpdateGroupWithMoreTerritories() {\n      DirectionalGroup withUtah = nebraska.toBuilder().mapRegionToTerritory(REGION_US, \"Utah\").build();\n      api(zoneName).updateRecordAndGroup(cnameCanary, cnameRecordCanary, withUtah);\n      getAnonymousLogger().info(\"update CNAME record in ipv4 pool: \" + cnameCanary);\n\n      checkRecordConsistent(dname, cnameCanary, cnameRecordCanary, withUtah);\n\n      checkGroupByDNameAndIdContainsTerritory(dname, cnameCanary, \"Nebraska\");\n      checkGroupByDNameAndIdContainsTerritory(dname, cnameCanary, \"Utah\");\n   }\n\n   @Test(dependsOnMethods = \"testUpdateGroupWithMoreTerritories\")\n   public void testAddRecordIntoGeoGroup() {\n      String geoGroupId = getRecordByDNameAndId(dname, cnameCanary).get().getGeolocationGroup().get().getId();\n      cname2Canary = api(zoneName).addRecordIntoExistingGroup(cnamePoolId, cname2RecordCanary, geoGroupId);\n      getAnonymousLogger().info(\"created CNAME record in ipv4 pool: \" + cname2Canary);\n\n      DirectionalPoolRecordDetail detail = \n            checkRecordConsistentInNonConfiguredGroup(dname, cname2Canary, cname2RecordCanary);\n      assertEquals(detail.getGroup().get().getId(), geoGroupId);\n   }\n\n   @Test(dependsOnMethods = \"testAddRecordIntoGeoGroup\")\n   public void testDeleteRecord() {\n      api(zoneName).deleteRecord(cnameEU);\n      assertFalse(getRecordByDNameAndId(dname, cnameEU).isPresent());\n      assertTrue(getRecordByDNameAndId(dname, cnameUS).isPresent());\n   }\n\n   @Test\n   public void addRecordsWithUnconfiguredGroupToPool() {\n      aPoolId = api(zoneName).createForDNameAndType(\"Geo pool\", \"a-\" + dname, IPV4.getCode());\n      getAnonymousLogger().info(\"created Geo pool: \" + aPoolId);\n      a1Prod = api(zoneName).addFirstRecordInNonConfiguredGroup(aPoolId, a1RecordProd);\n      getAnonymousLogger().info(\"created A record in ipv4 pool: \" + a1Prod);\n\n      checkRecordConsistentInNonConfiguredGroup(\"a-\" + dname, a1Prod, a1RecordProd);\n      checkGroupByDNameAndIdContainsTerritory(\"a-\" + dname, a1Prod, \"Nebraska\");\n\n      a1Canary = api(zoneName).addRecordIntoNewGroup(aPoolId, a1RecordCanary, nebraska);\n      getAnonymousLogger().info(\"created A record in ipv4 pool: \" + a1Canary);\n\n      checkRecordConsistent(\"a-\" + dname, a1Canary, a1RecordCanary, nebraska);\n      checkGroupByDNameAndIdContainsTerritory(\"a-\" + dname, a1Canary, \"Nebraska\");\n      checkGroupByDNameAndIdDoesntContainTerritory(\"a-\" + dname, a1Prod, \"Nebraska\");\n   }\n\n   @Test(dependsOnMethods = \"addRecordsWithUnconfiguredGroupToPool\", expectedExceptions = ResourceAlreadyExistsException.class)\n   public void addDuplicateFirstRecordInNonConfiguredGroup() {\n      api(zoneName).addFirstRecordInNonConfiguredGroup(aPoolId, a1RecordProd);\n   }\n\n   @Test(dependsOnMethods = \"addRecordsWithUnconfiguredGroupToPool\", expectedExceptions = ResourceAlreadyExistsException.class)\n   public void addDuplicateRecordIntoNewGroup() {\n      api(zoneName).addRecordIntoNewGroup(aPoolId, a1RecordCanary, nebraska);\n   }\n\n   @Test(dependsOnMethods = { \"addDuplicateFirstRecordInNonConfiguredGroup\", \"addRecordsWithUnconfiguredGroupToPool\" })\n   public void testRemovingAddsTerritoriesBackIntoNonConfiguredGroup() {\n      api(zoneName).deleteRecord(a1Canary);\n      assertFalse(getRecordByDNameAndId(\"a-\" + dname, a1Canary).isPresent());\n      checkGroupByDNameAndIdContainsTerritory(\"a-\" + dname, a1Prod, \"Nebraska\");\n   }\n\n   @Test(dependsOnMethods = { \"testDeleteRecord\", \"testRemovingAddsTerritoriesBackIntoNonConfiguredGroup\" })\n   public void testDeletePool() {\n      api(zoneName).delete(cnamePoolId);\n      assertFalse(getPoolById(cnamePoolId).isPresent());\n      api(zoneName).delete(aPoolId);\n      assertFalse(getPoolById(aPoolId).isPresent());\n   }\n\n   private DirectionalPoolRecordDetail checkRecordConsistent(String dname, String recordId,\n         DirectionalPoolRecord record, DirectionalGroup group) {\n      DirectionalPoolRecordDetail recordDetail = getRecordByDNameAndId(dname, recordId).get();\n      checkDirectionalRecordDetail(recordDetail);\n      IdAndName rGroup = recordDetail.getGeolocationGroup().get();\n      assertEquals(rGroup.getName(), group.getName());\n      // TODO: look up each key with all and do a comparison\n      if (!group.containsValue(\"all\"))\n         assertEquals(groupApi().get(rGroup.getId()), group);\n      assertFalse(recordDetail.getGroup().isPresent());\n      assertFalse(recordDetail.getSourceIpGroup().isPresent());\n      assertEquals(recordDetail.getName(), dname);\n      assertEquals(recordDetail.getZoneName(), zoneName);\n      assertEquals(recordDetail.getRecord(), record);\n      return recordDetail;\n   }\n\n   private DirectionalPoolRecordDetail checkRecordConsistentInNonConfiguredGroup(String dname, String recordId,\n         DirectionalPoolRecord record) {\n      DirectionalPoolRecordDetail recordDetail = getRecordByDNameAndId(dname, recordId).get();\n      checkDirectionalRecordDetail(recordDetail);\n      IdAndName rGroup = recordDetail.getGroup().get();\n      assertEquals(rGroup.getName(), \"All Non-Configured Regions\");\n      DirectionalGroup allNonConfigured = groupApi().get(rGroup.getId());\n      assertEquals(allNonConfigured.getName(), \"All Non-Configured Regions\");\n      assertEquals(allNonConfigured.size(), 323);\n      assertFalse(recordDetail.getGeolocationGroup().isPresent());\n      assertFalse(recordDetail.getSourceIpGroup().isPresent());\n      assertEquals(recordDetail.getZoneName(), zoneName);\n      assertEquals(recordDetail.getRecord(), record);\n      return recordDetail;\n   }\n\n   private DirectionalPoolApi api(String zoneName) {\n      return api.getDirectionalPoolApiForZone(zoneName);\n   }\n\n   private DirectionalGroupApi groupApi() {\n      return api.getDirectionalGroupApiForAccount(account.getId());\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/features/ResourceRecordApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.features;\nimport static com.google.common.net.HttpHeaders.HOST;\nimport static jakarta.ws.rs.HttpMethod.POST;\nimport static jakarta.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR;\nimport static jakarta.ws.rs.core.Response.Status.OK;\nimport static org.jclouds.ultradns.ws.domain.ResourceRecord.rrBuilder;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.jclouds.ultradns.ws.UltraDNSWSApi;\nimport org.jclouds.ultradns.ws.UltraDNSWSExceptions.ResourceAlreadyExistsException;\nimport org.jclouds.ultradns.ws.domain.ResourceRecord;\nimport org.jclouds.ultradns.ws.internal.BaseUltraDNSWSApiExpectTest;\nimport org.jclouds.ultradns.ws.parse.GetResourceRecordsOfResourceRecordResponseTest;\nimport org.testng.annotations.Test;\n\n\n\n@Test(groups = \"unit\", testName = \"ResourceRecordApiExpectTest\")\npublic class ResourceRecordApiExpectTest extends BaseUltraDNSWSApiExpectTest {\n   HttpRequest create = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/create_rr.xml\", \"application/xml\")).build();\n\n   HttpResponse createResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/rr_created.xml\", \"application/xml\")).build();\n\n   ResourceRecord record = rrBuilder().name(\"mail.jclouds.org.\")\n                                      .type(15)\n                                      .ttl(1800)\n                                      .infoValue(10)\n                                      .infoValue(\"maileast.jclouds.org.\").build();\n\n   public void testCreateWhenResponseIs2xx() {\n      UltraDNSWSApi success = requestSendsResponse(create, createResponse);\n      success.getResourceRecordApiForZone(\"jclouds.org.\").create(record);\n   }\n\n   HttpResponse alreadyCreated = HttpResponse.builder().statusCode(INTERNAL_SERVER_ERROR.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/rr_already_exists.xml\", \"application/xml\")).build();\n\n   @Test(expectedExceptions = ResourceAlreadyExistsException.class, expectedExceptionsMessageRegExp = \"Resource Record of type 15 with these attributes already exists in the system.\")\n   public void testCreateWhenResponseError1802() {\n      UltraDNSWSApi already = requestSendsResponse(create, alreadyCreated);\n      already.getResourceRecordApiForZone(\"jclouds.org.\").create(record);\n   }\n\n   HttpRequest update = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/update_rr.xml\", \"application/xml\")).build();\n\n   HttpResponse updateResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/rr_updated.xml\", \"application/xml\")).build();\n\n   public void testUpdateWhenResponseIs2xx() {\n      UltraDNSWSApi success = requestSendsResponse(update, updateResponse);\n      success.getResourceRecordApiForZone(\"jclouds.org.\").update(\"04053D8E57C7931F\", record);\n   }\n\n   HttpRequest list = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/list_records.xml\", \"application/xml\")).build();\n\n   HttpResponse listResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/records.xml\", \"application/xml\")).build();\n   \n   public void testListWhenResponseIs2xx() {\n      UltraDNSWSApi success = requestSendsResponse(list, listResponse);\n\n      assertEquals(\n            success.getResourceRecordApiForZone(\"jclouds.org.\").list().toString(),\n            new GetResourceRecordsOfResourceRecordResponseTest().expected().toString());\n   }\n\n   HttpResponse zoneDoesntExist = HttpResponse.builder().message(\"Server Error\").statusCode(INTERNAL_SERVER_ERROR.getStatusCode())\n         .payload(payloadFromResource(\"/zone_doesnt_exist.xml\")).build();\n   \n   @Test(expectedExceptions = ResourceNotFoundException.class, expectedExceptionsMessageRegExp = \"Zone does not exist in the system.\")\n   public void testListWhenResponseError1801() {\n      UltraDNSWSApi notFound = requestSendsResponse(list, zoneDoesntExist);\n      notFound.getResourceRecordApiForZone(\"jclouds.org.\").list();\n   }\n\n   HttpRequest listByName = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/list_records_by_name.xml\", \"application/xml\")).build();\n   \n   public void testListByNameWhenResponseIs2xx() {\n      UltraDNSWSApi success = requestSendsResponse(listByName, listResponse);\n\n      assertEquals(\n            success.getResourceRecordApiForZone(\"jclouds.org.\").listByName(\"www.jclouds.org.\").toString(),\n            new GetResourceRecordsOfResourceRecordResponseTest().expected().toString());\n   }\n\n   HttpRequest listByNameAndType = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/list_records_by_name_and_type.xml\", \"application/xml\")).build();\n   \n   public void testListByNameAndTypeWhenResponseIs2xx() {\n      UltraDNSWSApi success = requestSendsResponse(listByNameAndType, listResponse);\n\n      assertEquals(success.getResourceRecordApiForZone(\"jclouds.org.\").listByNameAndType(\"www.jclouds.org.\", 1)\n            .toString(), new GetResourceRecordsOfResourceRecordResponseTest().expected().toString());\n      \n      assertEquals(\n            success.getResourceRecordApiForZone(\"jclouds.org.\")\n                  .listByNameAndType(\"www.jclouds.org.\", 1).toString(),\n            new GetResourceRecordsOfResourceRecordResponseTest().expected().toString());\n   }\n\n   HttpRequest delete = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/delete_rr.xml\", \"application/xml\")).build();\n\n   HttpResponse deleteResponse = HttpResponse.builder().statusCode(404)\n         .payload(payloadFromResourceWithContentType(\"/rr_deleted.xml\", \"application/xml\")).build();\n\n   public void testDeleteWhenResponseIs2xx() {\n      UltraDNSWSApi success = requestSendsResponse(delete, deleteResponse);\n      success.getZoneApi().delete(\"04053D8E57C7931F\");\n   }\n\n   HttpResponse rrDoesntExist = HttpResponse.builder().message(\"Server Error\").statusCode(INTERNAL_SERVER_ERROR.getStatusCode())\n         .payload(payloadFromResource(\"/rr_doesnt_exist.xml\")).build();\n   \n   public void testDeleteWhenResponseRRNotFound() {\n      UltraDNSWSApi notFound = requestSendsResponse(delete, rrDoesntExist);\n      notFound.getZoneApi().delete(\"04053D8E57C7931F\");\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/features/ResourceRecordApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.features;\nimport static com.google.common.base.Predicates.equalTo;\nimport static java.lang.String.format;\nimport static java.util.logging.Logger.getAnonymousLogger;\nimport static org.jclouds.ultradns.ws.domain.ResourceRecord.rrBuilder;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.Assert.fail;\n\nimport java.util.Map.Entry;\nimport java.util.concurrent.atomic.AtomicLong;\n\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.jclouds.ultradns.ws.UltraDNSWSExceptions.ResourceAlreadyExistsException;\nimport org.jclouds.ultradns.ws.domain.ResourceRecord;\nimport org.jclouds.ultradns.ws.domain.ResourceRecordDetail;\nimport org.jclouds.ultradns.ws.domain.Zone;\nimport org.jclouds.ultradns.ws.internal.BaseUltraDNSWSApiLiveTest;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.FluentIterable;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"ResourceRecordApiLiveTest\")\npublic class ResourceRecordApiLiveTest extends BaseUltraDNSWSApiLiveTest {\n\n   @Override\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   public void setup() {\n      super.setup();\n      createZone();\n   }\n\n   static void checkResourceRecord(ResourceRecord rr) {\n      assertNotNull(rr.getName(), \"DName cannot be null for \" +  rr);\n      assertNotNull(rr.getType(), \"Type cannot be null for \" +  rr);\n      assertTrue(rr.getType() > 0, \"Type must be unsigned for \" + rr);\n      assertNotNull(rr.getType(), \"Type cannot be null for \" +  rr);\n      assertNotNull(rr.getTTL(), \"TTL cannot be null for \" +  rr);\n      assertNotNull(rr.getRData(), \"InfoValues cannot be null for \" +  rr);\n   }\n\n   static void checkResourceRecordMetadata(ResourceRecordDetail rr) {\n      assertNotNull(rr.getZoneId(), \"ZoneId cannot be null for \" +  rr);\n      assertNotNull(rr.getGuid(), \"Guid cannot be null for \" +  rr);\n      assertNotNull(rr.getZoneName(), \"ZoneName cannot be null for \" +  rr);\n      assertNotNull(rr.getCreated(), \"Created cannot be null for \" +  rr);\n      assertNotNull(rr.getModified(), \"Modified cannot be null for \" +  rr);\n      checkResourceRecord(rr.getRecord());\n   }\n\n   AtomicLong zones = new AtomicLong();\n\n   @Test\n   public void testListResourceRecords() {\n      for (Zone zone : api.getZoneApi().listByAccount(account.getId())) {\n         zones.incrementAndGet();\n         for (ResourceRecordDetail rr : api(zone.getName()).list()) {\n            recordTypeCounts.getUnchecked(rr.getRecord().getType()).incrementAndGet();\n            checkResourceRecordMetadata(rr);\n         }\n      }\n   }\n\n   LoadingCache<Integer, AtomicLong> recordTypeCounts = CacheBuilder.newBuilder().build(\n         new CacheLoader<Integer, AtomicLong>() {\n            public AtomicLong load(Integer key) throws Exception {\n               return new AtomicLong();\n            }\n         });\n\n   @AfterClass\n   void logSummary() {\n      getAnonymousLogger().info(\"zoneCount: \" + zones);\n      for (Entry<Integer, AtomicLong> entry : recordTypeCounts.asMap().entrySet())\n         getAnonymousLogger().info(format(\"type: %s, count: %s\", entry.getKey(), entry.getValue()));\n   }\n\n   @Test(expectedExceptions = ResourceNotFoundException.class, expectedExceptionsMessageRegExp = \"Zone does not exist in the system.\")\n   public void testListResourceRecordsWhenZoneIdNotFound() {\n      api(\"AAAAAAAAAAAAAAAA\").list();\n   }\n\n   @Test(expectedExceptions = ResourceNotFoundException.class, expectedExceptionsMessageRegExp = \"No Resource Record with GUID found in the system\")\n   public void testUpdateWhenNotFound() {\n      api(zoneName).update(\"AAAAAAAAAAAAAAAA\", mx);\n   }\n\n   @Test\n   public void testDeleteWhenNotFound() {\n      api(zoneName).delete(\"AAAAAAAAAAAAAAAA\");\n   }\n\n   String guid;\n   ResourceRecord mx = rrBuilder().name(\"mail.\" + zoneName)\n                                  .type(15)\n                                  .ttl(1800)\n                                  .infoValue(10)\n                                  .infoValue(\"maileast.jclouds.org.\").build();\n\n   @Test\n   public void testCreateRecord() {\n      guid = api(zoneName).create(mx);\n      getAnonymousLogger().info(\"created record: \" + guid);\n      try {\n         api(zoneName).create(mx);\n         fail();\n      } catch (ResourceAlreadyExistsException e) {\n\n      }\n      assertTrue(listRRs().anyMatch(equalTo(mx)));\n   }\n\n   @Test(dependsOnMethods = \"testCreateRecord\")\n   public void testListResourceRecordsByName() {\n      FluentIterable<ResourceRecord> byName = api(zoneName).listByName(mx.getName()).transform(toRecord);\n      assertTrue(byName.anyMatch(equalTo(mx)));\n   }\n\n   @Test(dependsOnMethods = \"testCreateRecord\")\n   public void testListResourceRecordsByNameAndType() {\n      FluentIterable<ResourceRecord> byNameAndType = api(zoneName).listByNameAndType(mx.getName(), mx.getType())\n            .transform(toRecord);\n      assertTrue(byNameAndType.anyMatch(equalTo(mx)));\n   }\n\n   @Test(dependsOnMethods = { \"testListResourceRecordsByName\", \"testListResourceRecordsByNameAndType\" })\n   public void testUpdateRecord() {\n      mx = mx.toBuilder().ttl(3600).build();\n      api(zoneName).update(guid, mx);\n      assertTrue(listRRs().anyMatch(equalTo(mx)));\n   }\n\n   @Test(dependsOnMethods = \"testUpdateRecord\")\n   public void testDeleteRecord() {\n      api(zoneName).delete(guid);\n      assertFalse(listRRs().anyMatch(equalTo(mx)));\n   }\n\n   static Function<ResourceRecordDetail, ResourceRecord> toRecord = new Function<ResourceRecordDetail, ResourceRecord>() {\n      public ResourceRecord apply(ResourceRecordDetail in) {\n         checkResourceRecordMetadata(in);\n         return in.getRecord();\n      }\n   };\n\n   private FluentIterable<ResourceRecord> listRRs() {\n      return api(zoneName).list().transform(toRecord);\n   }\n\n   private ResourceRecordApi api(String zoneName) {\n      return api.getResourceRecordApiForZone(zoneName);\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/features/RoundRobinPoolApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.features;\nimport static com.google.common.net.HttpHeaders.HOST;\nimport static jakarta.ws.rs.HttpMethod.POST;\nimport static jakarta.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR;\nimport static jakarta.ws.rs.core.Response.Status.OK;\nimport static org.jclouds.ultradns.ws.domain.RoundRobinPool.RecordType.A;\nimport static org.jclouds.ultradns.ws.domain.RoundRobinPool.RecordType.AAAA;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.ultradns.ws.UltraDNSWSApi;\nimport org.jclouds.ultradns.ws.UltraDNSWSExceptions.ResourceAlreadyExistsException;\nimport org.jclouds.ultradns.ws.internal.BaseUltraDNSWSApiExpectTest;\nimport org.jclouds.ultradns.ws.parse.GetRRLoadBalancingPoolsByZoneResponseTest;\nimport org.jclouds.ultradns.ws.parse.GetResourceRecordsOfResourceRecordResponseTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"RoundRobinPoolApiExpectTest\")\npublic class RoundRobinPoolApiExpectTest extends BaseUltraDNSWSApiExpectTest {\n   HttpRequest createA = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/create_rrpool_a.xml\", \"application/xml\")).build();\n\n   HttpRequest createAAAA = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/create_rrpool_aaaa.xml\", \"application/xml\")).build();\n\n   HttpResponse createResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/rrpool_created.xml\", \"application/xml\")).build();\n\n   public void testCreateAWhenResponseIs2xx() {\n      UltraDNSWSApi success = requestSendsResponse(createA, createResponse);\n      assertEquals(\n            success.getRoundRobinPoolApiForZone(\"jclouds.org.\").createForDNameAndType(\"www.jclouds.org.\", \"foo\",\n                  A.getCode()), \"060339AA04175655\");\n   }\n\n   public void testCreateAAAAWhenResponseIs2xx() {\n      UltraDNSWSApi success = requestSendsResponse(createAAAA, createResponse);\n      assertEquals(\n            success.getRoundRobinPoolApiForZone(\"jclouds.org.\").createForDNameAndType(\"www.jclouds.org.\", \"foo\",\n                  AAAA.getCode()), \"060339AA04175655\");\n   }\n\n   HttpResponse alreadyCreated = HttpResponse.builder().statusCode(INTERNAL_SERVER_ERROR.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/lbpool_already_exists.xml\", \"application/xml\")).build();\n\n   @Test(expectedExceptions = ResourceAlreadyExistsException.class, expectedExceptionsMessageRegExp = \"Pool already created for this host name : www.rrpool.adrianc.rrpool.ultradnstest.jclouds.org.\")\n   public void testCreateWhenResponseError2912() {\n      UltraDNSWSApi already = requestSendsResponse(createA, alreadyCreated);\n      already.getRoundRobinPoolApiForZone(\"jclouds.org.\").createForDNameAndType(\"www.jclouds.org.\", \"foo\",\n            A.getCode());\n   }\n\n   HttpRequest list = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/list_rrpools.xml\", \"application/xml\")).build();\n\n   HttpResponse listResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/rrpools.xml\", \"application/xml\")).build();\n   \n   public void testListWhenResponseIs2xx() {\n      UltraDNSWSApi success = requestSendsResponse(list, listResponse);\n\n      assertEquals(\n            success.getRoundRobinPoolApiForZone(\"jclouds.org.\").list().toString(),\n            new GetRRLoadBalancingPoolsByZoneResponseTest().expected().toString());\n   }\n\n   HttpRequest listRecords = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/list_rrrecords.xml\", \"application/xml\")).build();\n\n   HttpResponse listRecordsResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/records.xml\", \"application/xml\")).build();\n\n   public void testListRecordsWhenResponseIs2xx() {\n      UltraDNSWSApi success = requestSendsResponse(listRecords, listRecordsResponse);\n\n      assertEquals(\n            success.getRoundRobinPoolApiForZone(\"jclouds.org.\").listRecords(\"04053D8E57C7931F\").toString(),\n            new GetResourceRecordsOfResourceRecordResponseTest().expected().toString());\n   }\n\n   HttpRequest delete = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/delete_lbpool.xml\", \"application/xml\")).build();\n\n   HttpResponse deleteResponse = HttpResponse.builder().statusCode(404)\n         .payload(payloadFromResourceWithContentType(\"/lbpool_deleted.xml\", \"application/xml\")).build();\n\n   public void testDeleteWhenResponseIs2xx() {\n      UltraDNSWSApi success = requestSendsResponse(delete, deleteResponse);\n      success.getRoundRobinPoolApiForZone(\"jclouds.org.\").delete(\"04053D8E57C7931F\");\n   }\n\n   HttpResponse poolDoesntExist = HttpResponse.builder().message(\"Server Epoolor\").statusCode(INTERNAL_SERVER_ERROR.getStatusCode())\n         .payload(payloadFromResource(\"/lbpool_doesnt_exist.xml\")).build();\n   \n   public void testDeleteWhenResponseRRNotFound() {\n      UltraDNSWSApi notFound = requestSendsResponse(delete, poolDoesntExist);\n      notFound.getRoundRobinPoolApiForZone(\"jclouds.org.\").delete(\"04053D8E57C7931F\");\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/features/RoundRobinPoolApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.features;\n\nimport static com.google.common.base.Predicates.equalTo;\nimport static java.util.logging.Logger.getAnonymousLogger;\nimport static org.jclouds.ultradns.ws.domain.ResourceRecord.rrBuilder;\nimport static org.jclouds.ultradns.ws.domain.RoundRobinPool.RecordType.A;\nimport static org.jclouds.ultradns.ws.domain.RoundRobinPool.RecordType.AAAA;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.Assert.fail;\n\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.jclouds.ultradns.ws.UltraDNSWSExceptions.ResourceAlreadyExistsException;\nimport org.jclouds.ultradns.ws.domain.ResourceRecord;\nimport org.jclouds.ultradns.ws.domain.ResourceRecordDetail;\nimport org.jclouds.ultradns.ws.domain.RoundRobinPool;\nimport org.jclouds.ultradns.ws.domain.Zone;\nimport org.jclouds.ultradns.ws.internal.BaseUltraDNSWSApiLiveTest;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.FluentIterable;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"RoundRobinPoolApiLiveTest\")\npublic class RoundRobinPoolApiLiveTest extends BaseUltraDNSWSApiLiveTest {\n\n   @Override\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   public void setup() {\n      super.setup();\n      createZone();\n   }\n\n   private void checkRRPool(RoundRobinPool pool) {\n      assertNotNull(pool.getZoneId(), \"ZoneId cannot be null for \" + pool);\n      assertNotNull(pool.getId(), \"Id cannot be null for \" + pool);\n      assertNotNull(pool.getName(), \"Name cannot be null for \" + pool);\n      assertNotNull(pool.getDName(), \"DName cannot be null for \" + pool);\n   }\n\n   @Test\n   public void testListRRPools() {\n      for (Zone zone : api.getZoneApi().listByAccount(account.getId())) {\n         for (RoundRobinPool pool : api(zone.getName()).list()) {\n            checkRRPool(pool);\n         }\n      }\n   }\n\n   @Test\n   public void testListRRPoolRecords() {\n      for (Zone zone : api.getZoneApi().listByAccount(account.getId())) {\n         for (RoundRobinPool pool : api(zone.getName()).list()) {\n            for (ResourceRecordDetail record : api(zone.getName()).listRecords(pool.getId())) {\n               ResourceRecordApiLiveTest.checkResourceRecordMetadata(record);\n            }\n         }\n      }\n   }\n\n   @Test(expectedExceptions = ResourceNotFoundException.class, expectedExceptionsMessageRegExp = \"Zone does not exist in the system.\")\n   public void testListRRPoolsWhenZoneIdNotFound() {\n      api(\"AAAAAAAAAAAAAAAA\").list();\n   }\n\n   @Test\n   public void testDeleteWhenNotFound() {\n      api(zoneName).delete(\"06063D9C54C5AE09\");\n   }\n\n   String dname = \"www.rrpool.\" + zoneName;\n   String aPoolId;\n\n   @Test\n   public void testCreateAPool() {\n      aPoolId = api(zoneName).createForDNameAndType(\"A pool\", dname, A.getCode());\n      getAnonymousLogger().info(\"created A rr pool: \" + aPoolId);\n      try {\n         api(zoneName).createForDNameAndType(\"A pool\", dname, A.getCode());\n         fail();\n      } catch (ResourceAlreadyExistsException e) {\n\n      }\n      Optional<RoundRobinPool> aPool = getPoolById(aPoolId);\n      assertTrue(aPool.isPresent());\n      assertEquals(aPool.get().getName(), \"A pool\");\n      assertEquals(aPool.get().getDName(), dname);\n   }\n\n   String aRecord1;\n   String aRecord2;\n\n   @Test(dependsOnMethods = \"testCreateAPool\")\n   public void addARecordToPool() {\n      aRecord1 = api(zoneName).addARecordWithAddressAndTTL(aPoolId, \"1.2.3.4\", 1);\n\n      getAnonymousLogger().info(\"created A record: \" + aRecord1);\n\n      assertTrue(listRRs(aPoolId).anyMatch(\n            equalTo(rrBuilder().name(dname).type(1).ttl(1).rdata(\"1.2.3.4\").build())));\n\n      aRecord2 = api(zoneName).addARecordWithAddressAndTTL(aPoolId, \"3.4.5.6\", 1);\n\n      assertTrue(listRRs(aPoolId).anyMatch(\n            equalTo(rrBuilder().name(dname).type(1).ttl(1).rdata(\"3.4.5.6\").build())));\n\n      getAnonymousLogger().info(\"created A record: \" + aRecord1);\n      try {\n         api(zoneName).addARecordWithAddressAndTTL(aPoolId, \"1.2.3.4\", 1);\n         fail();\n      } catch (ResourceAlreadyExistsException e) {\n\n      }\n   }\n\n   @Test(dependsOnMethods = \"addARecordToPool\")\n   public void testUpdateRecord() {\n      api(zoneName).updateRecordWithAddressAndTTL(aPoolId, aRecord1, \"1.1.1.1\", 0);\n      assertTrue(listRRs(aPoolId).anyMatch(\n            equalTo(rrBuilder().name(dname).type(1).ttl(0).rdata(\"1.1.1.1\").build())));\n   }\n\n   @Test(dependsOnMethods = \"testUpdateRecord\")\n   public void testDeleteRecord() {\n      api(zoneName).deleteRecord(aRecord2);\n      assertTrue(listRRs(aPoolId).anyMatch(\n            equalTo(rrBuilder().name(dname).type(1).ttl(0).rdata(\"1.1.1.1\").build())));\n\n      assertFalse(listRRs(aPoolId).anyMatch(\n            equalTo(rrBuilder().name(dname).type(1).ttl(1).rdata(\"3.4.5.6\").build())));\n   }\n\n   @Test(dependsOnMethods = \"testDeleteRecord\")\n   public void testDeleteAPool() {\n      api(zoneName).delete(aPoolId);\n      assertFalse(getPoolById(aPoolId).isPresent());\n   }\n\n   private String aaaaPoolId;\n\n   @Test\n   public void testCreateAAAAPool() {\n      aaaaPoolId = api(zoneName).createForDNameAndType(\"AAAA pool\", dname, AAAA.getCode());\n      getAnonymousLogger().info(\"created AAAA rr pool: \" + aaaaPoolId);\n      try {\n         api(zoneName).createForDNameAndType(\"AAAA pool\", dname, AAAA.getCode());\n         fail();\n      } catch (ResourceAlreadyExistsException e) {\n\n      }\n      Optional<RoundRobinPool> aPool = getPoolById(aaaaPoolId);\n      assertTrue(aPool.isPresent());\n      assertEquals(aPool.get().getName(), \"AAAA pool\");\n      assertEquals(aPool.get().getDName(), dname);\n   }\n\n   String aaaaRecord1;\n   String aaaaRecord2;\n\n   @Test(dependsOnMethods = \"testCreateAAAAPool\")\n   public void addAAAARecordToPool() {\n      aaaaRecord1 = api(zoneName).addAAAARecordWithAddressAndTTL(aaaaPoolId, \"2001:0DB8:85A3:0000:0000:8A2E:0370:7334\",\n            1);\n\n      getAnonymousLogger().info(\"created AAAA record: \" + aaaaRecord1);\n\n      assertTrue(listRRs(aaaaPoolId).anyMatch(\n            equalTo(rrBuilder().name(dname)\n                               .type(28)\n                               .ttl(1)\n                               .rdata(\"2001:0DB8:85A3:0000:0000:8A2E:0370:7334\")\n                               .build())));\n\n      aaaaRecord2 = api(zoneName).addAAAARecordWithAddressAndTTL(aaaaPoolId, \"2002:0DB8:85A3:0000:0000:8A2E:0370:7334\",\n            1);\n\n      assertTrue(listRRs(aaaaPoolId).anyMatch(\n            equalTo(rrBuilder().name(dname)\n                               .type(28)\n                               .ttl(1)\n                               .rdata(\"2002:0DB8:85A3:0000:0000:8A2E:0370:7334\")\n                               .build())));\n\n      getAnonymousLogger().info(\"created AAAA record: \" + aaaaRecord1);\n      try {\n         api(zoneName).addAAAARecordWithAddressAndTTL(aaaaPoolId, \"2001:0DB8:85A3:0000:0000:8A2E:0370:7334\", 1);\n         fail();\n      } catch (ResourceAlreadyExistsException e) {\n\n      }\n   }\n\n   @Test(dependsOnMethods = \"addAAAARecordToPool\")\n   public void testDeleteAAAAPool() {\n      api(zoneName).delete(aaaaPoolId);\n      assertFalse(getPoolById(aaaaPoolId).isPresent());\n   }\n\n   protected Optional<RoundRobinPool> getPoolById(final String poolId) {\n      return api(zoneName).list().firstMatch(new Predicate<RoundRobinPool>() {\n         public boolean apply(RoundRobinPool in) {\n            return in.getId().equals(poolId);\n         }\n      });\n   }\n\n   private FluentIterable<ResourceRecord> listRRs(String poolId) {\n      return api(zoneName).listRecords(poolId).transform(ResourceRecordApiLiveTest.toRecord);\n   }\n\n   private RoundRobinPoolApi api(String zoneName) {\n      return api.getRoundRobinPoolApiForZone(zoneName);\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/features/TaskApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.features;\nimport static com.google.common.net.HttpHeaders.HOST;\nimport static jakarta.ws.rs.HttpMethod.POST;\nimport static jakarta.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR;\nimport static jakarta.ws.rs.core.Response.Status.OK;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.ultradns.ws.UltraDNSWSApi;\nimport org.jclouds.ultradns.ws.internal.BaseUltraDNSWSApiExpectTest;\nimport org.jclouds.ultradns.ws.parse.GetAllTasksResponseTest;\nimport org.jclouds.ultradns.ws.parse.GetStatusForTaskResponseResponseTest;\nimport org.testng.annotations.Test;\n@Test(groups = \"unit\", testName = \"TaskApiExpectTest\")\npublic class TaskApiExpectTest extends BaseUltraDNSWSApiExpectTest {\n   HttpRequest runTest = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/run_test.xml\", \"application/xml\")).build();\n\n   HttpResponse runTestResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/taskid.xml\", \"application/xml\")).build();\n\n   public void testRunTestWhenResponseIs2xx() {\n      UltraDNSWSApi success = requestSendsResponse(runTest, runTestResponse);\n\n      assertEquals(success.getTaskApi().runTest(\"foo\").toString(), \"8d7a1725-4f4a-4b70-affa-f01dcce1526e\");\n   }\n\n   HttpRequest get = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/get_task.xml\", \"application/xml\")).build();\n\n   HttpResponse getResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/task.xml\", \"application/xml\")).build();\n\n   public void testGetWhenResponseIs2xx() {\n      UltraDNSWSApi success = requestSendsResponse(get, getResponse);\n\n      assertEquals(\n            success.getTaskApi().get(\"0b40c7dd-748d-4c49-8506-26f0c7d2ea9c\").toString(),\n            new GetStatusForTaskResponseResponseTest().expected().toString());\n   }\n   \n   HttpResponse taskDoesntExist = HttpResponse.builder().message(\"Server Error\").statusCode(INTERNAL_SERVER_ERROR.getStatusCode())\n         .payload(payloadFromResource(\"/task_doesnt_exist.xml\")).build();\n   \n   public void testGetWhenResponseError2401() {\n      UltraDNSWSApi notFound = requestSendsResponse(get, taskDoesntExist);\n      assertNull(notFound.getTaskApi().get(\"0b40c7dd-748d-4c49-8506-26f0c7d2ea9c\"));\n   }\n\n   HttpRequest clear = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/clear_task.xml\", \"application/xml\")).build();\n\n   HttpResponse clearResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/task.xml\", \"application/xml\")).build();\n\n   public void testClearWhenResponseIs2xx() {\n      UltraDNSWSApi success = requestSendsResponse(clear, clearResponse);\n      success.getTaskApi().clear(\"0b40c7dd-748d-4c49-8506-26f0c7d2ea9c\");\n   }\n\n   public void testClearWhenResponseError2401() {\n      UltraDNSWSApi notFound = requestSendsResponse(clear, taskDoesntExist);\n      notFound.getTaskApi().clear(\"0b40c7dd-748d-4c49-8506-26f0c7d2ea9c\");\n   }\n   \n   HttpRequest list = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/list_tasks.xml\", \"application/xml\")).build();\n\n   HttpResponse listResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/tasks.xml\", \"application/xml\")).build();\n\n   public void testListWhenResponseIs2xx() {\n      UltraDNSWSApi success = requestSendsResponse(list, listResponse);\n\n      assertEquals(\n            success.getTaskApi().list().toString(),\n            new GetAllTasksResponseTest().expected().toString());\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/features/TaskApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.features;\n\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\n\nimport org.jclouds.ultradns.ws.domain.Task;\nimport org.jclouds.ultradns.ws.internal.BaseUltraDNSWSApiLiveTest;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", testName = \"TaskApiLiveTest\")\npublic class TaskApiLiveTest extends BaseUltraDNSWSApiLiveTest {\n\n   private void checkTask(Task task) {\n      assertNotNull(task.getGuid(), \"Guid cannot be null for \" + task);\n      assertNotNull(task.getStatusCode(), \"StatusCode cannot be null for \" + task);\n      assertNotNull(task.getMessage(), \"While Message can be null, its Optional wrapper cannot \" + task);\n      assertNotNull(task.getResultUrl(), \"While ResultUrl can be null, its Optional wrapper cannot \" + task);\n   }\n\n   @Test\n   public void testListTasks() {\n      for (Task task : api().list()) {\n         checkTask(task);\n      }\n   }\n\n   @Test\n   public void testGetTask() {\n      for (Task task : api().list()) {\n         Task got = api().get(task.getGuid());\n         assertEquals(got.getGuid(), task.getGuid());\n         assertEquals(got.getStatusCode(), task.getStatusCode());\n         assertEquals(got.getMessage(), task.getMessage());\n         assertEquals(got.getResultUrl(), task.getResultUrl());\n      }\n   }\n\n   @Test\n   public void testClearTask() {\n      String guid = api().runTest(\"foo\");\n      checkTask(api().get(guid));\n      api().clear(guid);\n      assertNull(api().get(guid));\n   }\n\n   @Test\n   public void testClearTaskWhenNotFound() {\n      api().clear(\"AAAAAAAAAAAAAAAA\");\n   }\n\n   @Test\n   public void testGetTaskWhenNotFound() {\n      assertNull(api().get(\"AAAAAAAAAAAAAAAA\"));\n   }\n\n   protected TaskApi api() {\n      return api.getTaskApi();\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/features/TrafficControllerPoolApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.features;\nimport static com.google.common.net.HttpHeaders.HOST;\nimport static jakarta.ws.rs.HttpMethod.POST;\nimport static jakarta.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR;\nimport static jakarta.ws.rs.core.Response.Status.OK;\nimport static org.jclouds.ultradns.ws.domain.TrafficControllerPool.RecordType.IPV4;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.jclouds.ultradns.ws.UltraDNSWSApi;\nimport org.jclouds.ultradns.ws.UltraDNSWSExceptions.ResourceAlreadyExistsException;\nimport org.jclouds.ultradns.ws.domain.UpdatePoolRecord;\nimport org.jclouds.ultradns.ws.internal.BaseUltraDNSWSApiExpectTest;\nimport org.jclouds.ultradns.ws.parse.GetPoolRecordSpecResponseTest;\nimport org.jclouds.ultradns.ws.parse.GetTCLoadBalancingPoolsByZoneResponseTest;\nimport org.jclouds.ultradns.ws.parse.GetTCPoolRecordsResponseTest;\nimport org.testng.annotations.Test;\n@Test(groups = \"unit\", testName = \"TrafficControllerPoolApiExpectTest\")\npublic class TrafficControllerPoolApiExpectTest extends BaseUltraDNSWSApiExpectTest {\n   HttpRequest create = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/create_tcpool.xml\", \"application/xml\")).build();\n\n   HttpResponse createResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/tcpool_created.xml\", \"application/xml\")).build();\n\n   public void testCreateWhenResponseIs2xx() {\n      UltraDNSWSApi success = requestSendsResponse(create, createResponse);\n      assertEquals(\n            success.getTrafficControllerPoolApiForZone(\"jclouds.org.\").createForDNameAndType(\"foo\",\n                  \"www.jclouds.org.\", IPV4.getCode()), \"060339AA0417567A\");\n   }\n\n   HttpResponse alreadyCreated = HttpResponse.builder().statusCode(INTERNAL_SERVER_ERROR.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/lbpool_already_exists.xml\", \"application/xml\")).build();\n\n   @Test(expectedExceptions = ResourceAlreadyExistsException.class, expectedExceptionsMessageRegExp = \"Pool already created for this host name : www.rrpool.adrianc.rrpool.ultradnstest.jclouds.org.\")\n   public void testCreateWhenResponseError2912() {\n      UltraDNSWSApi already = requestSendsResponse(create, alreadyCreated);\n      already.getTrafficControllerPoolApiForZone(\"jclouds.org.\").createForDNameAndType(\"foo\", \"www.jclouds.org.\",\n            IPV4.getCode());\n   }\n\n   HttpRequest list = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/list_tcpools.xml\", \"application/xml\")).build();\n\n   HttpResponse listResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/tcpools.xml\", \"application/xml\")).build();\n   \n   public void testListWhenResponseIs2xx() {\n      UltraDNSWSApi success = requestSendsResponse(list, listResponse);\n\n      assertEquals(success.getTrafficControllerPoolApiForZone(\"jclouds.org.\").list().toString(),\n            new GetTCLoadBalancingPoolsByZoneResponseTest().expected().toString());\n   }\n\n   HttpRequest listRecords = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/list_tcrecords.xml\", \"application/xml\")).build();\n\n   HttpResponse listRecordsResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/tcrecords.xml\", \"application/xml\")).build();\n\n   public void testListRecordsWhenResponseIs2xx() {\n      UltraDNSWSApi success = requestSendsResponse(listRecords, listRecordsResponse);\n\n      assertEquals(\n            success.getTrafficControllerPoolApiForZone(\"jclouds.org.\").listRecords(\"04053D8E57C7931F\").toString(),\n            new GetTCPoolRecordsResponseTest().expected().toString());\n   }\n\n   HttpRequest getNameByDName = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/get_tcpool_by_dname.xml\", \"application/xml\")).build();\n\n   HttpResponse getNameByDNameResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/tcpool_name.xml\", \"application/xml\")).build();\n\n   public void testGetNameByDNameWhenResponseIs2xx() {\n      UltraDNSWSApi success = requestSendsResponse(getNameByDName, getNameByDNameResponse);\n      assertEquals(success.getTrafficControllerPoolApiForZone(\"jclouds.org.\").getNameByDName(\"www.foo.com.\"), \"foo\");\n   }\n\n   HttpResponse poolDoesntExist = HttpResponse.builder().message(\"Server Epoolor\").statusCode(INTERNAL_SERVER_ERROR.getStatusCode())\n         .payload(payloadFromResource(\"/lbpool_doesnt_exist.xml\")).build();\n   \n   public void testGetNameByDNameWhenResponseNotFound() {\n      UltraDNSWSApi notFound = requestSendsResponse(getNameByDName, poolDoesntExist);\n      assertNull(notFound.getTrafficControllerPoolApiForZone(\"jclouds.org.\").getNameByDName(\"www.foo.com.\"));\n   }\n\n   HttpRequest delete = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/delete_lbpool.xml\", \"application/xml\")).build();\n\n   HttpResponse deleteResponse = HttpResponse.builder().statusCode(404)\n         .payload(payloadFromResourceWithContentType(\"/lbpool_deleted.xml\", \"application/xml\")).build();\n\n   public void testDeleteWhenResponseIs2xx() {\n      UltraDNSWSApi success = requestSendsResponse(delete, deleteResponse);\n      success.getTrafficControllerPoolApiForZone(\"jclouds.org.\").delete(\"04053D8E57C7931F\");\n   }\n\n   public void testDeleteWhenResponseNotFound() {\n      UltraDNSWSApi notFound = requestSendsResponse(delete, poolDoesntExist);\n      notFound.getTrafficControllerPoolApiForZone(\"jclouds.org.\").delete(\"04053D8E57C7931F\");\n   }\n   \n   HttpRequest createRecord = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/create_tcrecord.xml\", \"application/xml\")).build();\n\n   HttpResponse createRecordResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/tcrecord_created.xml\", \"application/xml\")).build();\n\n   public void testCreateRecordWhenResponseIs2xx() {\n      UltraDNSWSApi success = requestSendsResponse(createRecord, createRecordResponse);\n      assertEquals(success.getTrafficControllerPoolApiForZone(\"jclouds.org.\").addRecordToPoolWithTTL(\"1.2.3.4\", \"04053D8E57C7931F\", 300), \"06063DAC54F8D3D9\");\n   }\n\n   HttpResponse recordAlreadyCreated = HttpResponse.builder().statusCode(INTERNAL_SERVER_ERROR.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/tcrecord_already_exists.xml\", \"application/xml\")).build();\n\n   @Test(expectedExceptions = ResourceAlreadyExistsException.class, expectedExceptionsMessageRegExp = \"Resource Record of type 1 with these attributes already exists in the system.\")\n   public void testCreateWhenResponseError1802() {\n      UltraDNSWSApi already = requestSendsResponse(createRecord, recordAlreadyCreated);\n      already.getTrafficControllerPoolApiForZone(\"jclouds.org.\").addRecordToPoolWithTTL(\"1.2.3.4\", \"04053D8E57C7931F\", 300);\n   }\n\n   HttpRequest createRecordWithWeight = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/create_tcrecord_weight.xml\", \"application/xml\")).build();\n\n   public void testCreateRecordWithWeightWhenResponseIs2xx() {\n      UltraDNSWSApi success = requestSendsResponse(createRecordWithWeight, createRecordResponse);\n      assertEquals(\n            success.getTrafficControllerPoolApiForZone(\"jclouds.org.\").addRecordToPoolWithTTLAndWeight(\"1.2.3.4\",\n                  \"04053D8E57C7931F\", 300, 0), \"06063DAC54F8D3D9\");\n   }\n\n   HttpRequest getRecordSpec = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/get_poolrecordspec.xml\", \"application/xml\")).build();\n\n   HttpResponse getRecordSpecResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/poolrecordspec.xml\", \"application/xml\")).build();\n\n   public void testGetRecordSpecWhenResponseIs2xx() {\n      UltraDNSWSApi success = requestSendsResponse(getRecordSpec, getRecordSpecResponse);\n      assertEquals(success.getTrafficControllerPoolApiForZone(\"jclouds.org.\").getRecordSpec(\"04053D8E57C7931F\"),\n            new GetPoolRecordSpecResponseTest().expected());\n   }\n\n   HttpResponse recordDoesntExist = HttpResponse.builder().message(\"Server Error\").statusCode(INTERNAL_SERVER_ERROR.getStatusCode())\n         .payload(payloadFromResource(\"/tcrecord_doesnt_exist.xml\")).build();\n\n   public void testGetRecordSpecWhenResponseNotFound() {\n      UltraDNSWSApi notFound = requestSendsResponse(getRecordSpec, recordDoesntExist);\n      assertNull(notFound.getTrafficControllerPoolApiForZone(\"jclouds.org.\").getRecordSpec(\"04053D8E57C7931F\"));\n   }\n\n   UpdatePoolRecord update = UpdatePoolRecord.builder()\n                                             .rdata(\"www.baz.com.\")\n                                             .mode(\"Normal\")\n                                             .weight(98)\n                                             .failOverDelay(0)\n                                             .threshold(1)\n                                             .ttl(OK.getStatusCode()).build();\n\n   HttpRequest updateRecord = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/update_poolrecord.xml\", \"application/xml\")).build();\n\n   HttpResponse updateRecordResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/poolrecord_updated.xml\", \"application/xml\")).build();\n\n   public void testUpdateRecordWhenResponseIs2xx() {\n      UltraDNSWSApi success = requestSendsResponse(updateRecord, updateRecordResponse);\n      success.getTrafficControllerPoolApiForZone(\"jclouds.org.\").updateRecord(\"04053D8E57C7931F\", update);\n   }\n\n   @Test(expectedExceptions = ResourceNotFoundException.class, expectedExceptionsMessageRegExp = \"Pool Record does not exist.\")\n   public void testUpdateRecordWhenResponseNotFound() {\n      UltraDNSWSApi notFound = requestSendsResponse(updateRecord, recordDoesntExist);\n      notFound.getTrafficControllerPoolApiForZone(\"jclouds.org.\").updateRecord(\"04053D8E57C7931F\", update);\n   }\n\n   HttpRequest deleteRecord = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/delete_tcrecord.xml\", \"application/xml\")).build();\n\n   HttpResponse deleteRecordResponse = HttpResponse.builder().statusCode(404)\n         .payload(payloadFromResourceWithContentType(\"/tcrecord_deleted.xml\", \"application/xml\")).build();\n\n   public void testDeleteRecordWhenResponseIs2xx() {\n      UltraDNSWSApi success = requestSendsResponse(deleteRecord, deleteRecordResponse);\n      success.getTrafficControllerPoolApiForZone(\"jclouds.org.\").deleteRecord(\"04053D8E57C7931F\");\n   }\n\n   public void testDeleteRecordWhenResponseNotFound() {\n      UltraDNSWSApi notFound = requestSendsResponse(deleteRecord, recordDoesntExist);\n      notFound.getTrafficControllerPoolApiForZone(\"jclouds.org.\").deleteRecord(\"04053D8E57C7931F\");\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/features/TrafficControllerPoolApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.features;\n\nimport static java.util.logging.Logger.getAnonymousLogger;\nimport static org.jclouds.ultradns.ws.domain.TrafficControllerPool.RecordType.IPV4;\nimport static org.jclouds.ultradns.ws.domain.TrafficControllerPoolRecordDetail.Status.UNRECOGNIZED;\nimport static org.jclouds.ultradns.ws.predicates.TrafficControllerPoolPredicates.idEqualTo;\nimport static org.jclouds.ultradns.ws.predicates.TrafficControllerPoolPredicates.recordIdEqualTo;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertNotEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.Assert.fail;\n\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.jclouds.ultradns.ws.UltraDNSWSExceptions.ResourceAlreadyExistsException;\nimport org.jclouds.ultradns.ws.domain.PoolRecordSpec;\nimport org.jclouds.ultradns.ws.domain.TrafficControllerPool;\nimport org.jclouds.ultradns.ws.domain.TrafficControllerPoolRecord;\nimport org.jclouds.ultradns.ws.domain.TrafficControllerPoolRecordDetail;\nimport org.jclouds.ultradns.ws.domain.UpdatePoolRecord;\nimport org.jclouds.ultradns.ws.domain.Zone;\nimport org.jclouds.ultradns.ws.internal.BaseUltraDNSWSApiLiveTest;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.DataProvider;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"TrafficControllerPoolApiLiveTest\")\npublic class TrafficControllerPoolApiLiveTest extends BaseUltraDNSWSApiLiveTest {\n\n   @Override\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   public void setup() {\n      super.setup();\n      createZone();\n   }\n\n   private void checkTCPool(TrafficControllerPool pool) {\n      assertNotNull(pool.getZoneId(), \"ZoneId cannot be null \" + pool);\n      assertNotNull(pool.getId(), \"Id cannot be null \" + pool);\n      assertNotNull(pool.getName(), \"Name cannot be null \" + pool);\n      assertNotNull(pool.getDName(), \"DName cannot be null \" + pool);\n      assertEquals(api(zoneName).getNameByDName(pool.getDName()), pool.getName());\n   }\n\n   @Test\n   public void testListTCPools() {\n      for (Zone zone : api.getZoneApi().listByAccount(account.getId())) {\n         for (TrafficControllerPool pool : api(zone.getName()).list()) {\n            checkTCPool(pool);\n         }\n      }\n   }\n\n   @Test\n   public void testListTCPoolRecords() {\n      for (Zone zone : api.getZoneApi().listByAccount(account.getId())) {\n         for (TrafficControllerPool pool : api(zone.getName()).list()) {\n            for (TrafficControllerPoolRecordDetail record : api(zone.getName()).listRecords(pool.getId())) {\n               checkPoolRecordConsistent(zone.getName(), record);\n            }\n         }\n      }\n   }\n\n   private TrafficControllerPoolRecordDetail checkPoolRecordConsistent(String zoneName, TrafficControllerPoolRecordDetail record) {\n      Optional<TrafficControllerPool> pool = getPoolByZoneAndId(zoneName, record.getPoolId());\n      assertTrue(pool.isPresent(), \"could not get pool for \" + record);\n      assertEquals(record.getDescription(), pool.get().getName());\n      PoolRecordSpec spec = checkPoolRecordSpec(api(zoneName).getRecordSpec(record.getId()));\n      assertEquals(record.getDescription(), spec.getDescription());\n      assertEquals(record.getWeight(), spec.getWeight());\n      assertEquals(record.isProbingEnabled(), spec.isProbingEnabled());\n      return checkTrafficControllerPoolRecord(record);\n   }\n\n   static TrafficControllerPoolRecordDetail checkTrafficControllerPoolRecord(TrafficControllerPoolRecordDetail record) {\n      assertNotNull(record.getId(), \"Id cannot be null for \" + record);\n      assertNotNull(record.getPoolId(), \"PoolId cannot be null for \" + record);\n      assertNotNull(record.getRecord().getRData(), \"Record.RData cannot be null for \" + record);\n      assertNotNull(record.getRecord().getType(), \"Record.Type cannot be null for \" + record);\n      assertTrue(record.getWeight() >= 0, \"Weight must be unsigned for \" + record);\n      assertTrue(record.getPriority() >= 0, \"Priority must be unsigned for \" + record);\n      assertNotNull(record.getStatus(), \"Status cannot be null for \" + record);\n      assertNotEquals(record.getStatus(), UNRECOGNIZED, \"unrecognized status for \" + record);\n      assertNotNull(record.getDescription(), \"Description cannot be null for \" + record);\n      return record;\n   }\n\n   static PoolRecordSpec checkPoolRecordSpec(PoolRecordSpec record) {\n      assertNotNull(record.getDescription(), \"Description cannot be null for \" + record);\n      assertNotNull(record.getState(), \"State cannot be null for \" + record);\n      // TODO: collect all possible states then consider enum\n      assertTrue(ImmutableSet.of(\"Normal\", \"Normal-NoTest\").contains(record.getState()), \"Unknown State for \" + record);\n      assertTrue(record.getWeight() >= 0, \"Weight must be unsigned for \" + record);\n      assertTrue(record.getFailOverDelay() >= 0, \"failOverDelay must be unsigned for \" + record);\n      assertTrue(record.getThreshold() >= 0, \"threshold must be unsigned for \" + record);\n      assertTrue(record.getTTL() >= 0, \"ttl must be unsigned for \" + record);\n      return record;\n   }\n\n   @Test(expectedExceptions = ResourceNotFoundException.class, expectedExceptionsMessageRegExp = \"Zone does not exist in the system.\")\n   public void testListTCPoolsWhenZoneIdNotFound() {\n      api(\"AAAAAAAAAAAAAAAA\").list();\n   }\n\n   @Test\n   public void testDeleteWhenNotFound() {\n      api(zoneName).delete(\"06063D9C54C5AE09\");\n   }\n\n   @Test\n   public void testDeleteRecordWhenNotFound() {\n      api(zoneName).deleteRecord(\"06063D9C54C5AE09\");\n   }\n\n   @Test\n   public void testGetNameByDNameWhenNotFound() {\n      assertNull(api(zoneName).getNameByDName(\"www.razzledazzle.cn.\"));\n   }\n\n   @Test\n   public void testGetRecordSpecWhenNotFound() {\n      assertNull(api(zoneName).getRecordSpec(\"06063D9C54C5AE09\"));\n   }\n\n   @Test(expectedExceptions = ResourceNotFoundException.class, expectedExceptionsMessageRegExp = \"Pool Record does not exist.\")\n   public void testUpdateRecordWhenNotFound() {\n      api(zoneName).updateRecord(\"06063D9C54C5AE09\",\n            UpdatePoolRecord.builder().rdata(\"www.foo.com.\").mode(\"Normal\").build());\n   }\n\n   String dname = \"www.tcpool.\" + zoneName;\n   String poolId;\n\n   @Test\n   public void testCreatePool() {\n      poolId = api(zoneName).createForDNameAndType(\"pool\", dname, IPV4.getCode());\n      getAnonymousLogger().info(\"created tc pool: \" + poolId);\n      try {\n         api(zoneName).createForDNameAndType(\"pool\", dname, IPV4.getCode());\n         fail();\n      } catch (ResourceAlreadyExistsException e) {\n\n      }\n      // ensure there's only one pool for a dname\n      try {\n         api(zoneName).createForDNameAndType(\"pool1\", dname, IPV4.getCode());\n         fail();\n      } catch (ResourceAlreadyExistsException e) {\n\n      }\n      Optional<TrafficControllerPool> pool = getPoolByZoneAndId(zoneName, poolId);\n      assertTrue(pool.isPresent());\n      assertEquals(pool.get().getId(), poolId);\n      assertEquals(pool.get().getName(), \"pool\");\n      assertEquals(pool.get().getDName(), dname);\n      checkTCPool(pool.get());\n   }\n\n   @DataProvider(name = \"records\")\n   public Object[][] createRecords() {\n      Object[][] records = new Object[2][4];\n      records[0][0] = \"1.2.3.4\";\n      records[0][1] = \"A\";\n      records[0][2] = 60;\n      records[0][3] = Optional.of(98);\n      records[1][0] = \"5.6.7.8\";\n      records[1][1] = \"A\";\n      records[1][2] = 60;\n      records[1][3] = Optional.of(2);\n      return records;\n   }\n\n   @Test(dependsOnMethods = \"testCreatePool\", dataProvider = \"records\")\n   public TrafficControllerPoolRecordDetail addRecordToPool(String rdata, String type, int ttl, Optional<Integer> weight) {\n      String recordId;\n      if (weight.isPresent()) {\n         recordId = api(zoneName).addRecordToPoolWithTTLAndWeight(rdata, poolId, ttl, weight.get());\n      } else {\n         recordId = api(zoneName).addRecordToPoolWithTTL(rdata, poolId, ttl);\n      }\n      getAnonymousLogger().info(\"created \" + type + \" record: \" + recordId);\n      TrafficControllerPoolRecordDetail record = checkPoolRecordConsistent(zoneName, getRecordById(recordId).get());\n      PoolRecordSpec recordSpec = checkPoolRecordSpec(api(zoneName).getRecordSpec(recordId));\n      assertEquals(record.getRecord(), TrafficControllerPoolRecord.create(type, rdata));\n      assertEquals(record.getWeight(), weight.or(2).intValue());\n      assertEquals(recordSpec.getTTL(), ttl);\n      return record;\n   }\n\n   String cname1;\n   String cname2;\n\n   @Test(dependsOnMethods = \"testCreatePool\")\n   public void addCNAMERecordsToPool() {\n      cname1 = addRecordToPool(\"www.foo.com.\", \"CNAME\", 30, Optional.<Integer> absent()).getId();\n\n      try {\n         api(zoneName).addRecordToPoolWithTTL(\"www.foo.com.\", poolId, 30);\n         fail();\n      } catch (ResourceAlreadyExistsException e) {\n\n      }\n\n      cname2 = addRecordToPool(\"www.bar.com.\", \"CNAME\", 30, Optional.<Integer> absent()).getId();\n   }\n\n   @Test(dependsOnMethods = \"addCNAMERecordsToPool\")\n   public void testUpdateRecord() {\n      PoolRecordSpec spec = api(zoneName).getRecordSpec(cname2);\n      UpdatePoolRecord update = UpdatePoolRecord.builder().from(spec)\n                                                .rdata(\"www.baz.com.\")\n                                                .weight(98)\n                                                .ttl(200).build();\n\n      api(zoneName).updateRecord(cname2, update);\n\n      TrafficControllerPoolRecordDetail record = getRecordById(cname2).get();\n      assertEquals(record.getRecord().getRData(), \"www.baz.com.\");\n\n      spec = api(zoneName).getRecordSpec(cname2);\n      assertEquals(spec.getWeight(), 98);\n      assertEquals(spec.getTTL(), 200);\n   }\n\n   @Test(dependsOnMethods = \"testUpdateRecord\")\n   public void testDeleteRecord() {\n      api(zoneName).deleteRecord(cname1);\n      assertFalse(getRecordById(cname1).isPresent());\n      assertTrue(getRecordById(cname2).isPresent());\n   }\n\n   @Test(dependsOnMethods = \"testDeleteRecord\")\n   public void testDeletePool() {\n      api(zoneName).delete(poolId);\n      assertFalse(getPoolByZoneAndId(zoneName, poolId).isPresent());\n   }\n\n   private Optional<TrafficControllerPoolRecordDetail> getRecordById(String recordId) {\n      return api(zoneName).listRecords(poolId).firstMatch(recordIdEqualTo(recordId));\n   }\n\n   private Optional<TrafficControllerPool> getPoolByZoneAndId(String zoneName, final String poolId) {\n      return api(zoneName).list().firstMatch(idEqualTo(poolId));\n   }\n\n   private TrafficControllerPoolApi api(String zoneName) {\n      return api.getTrafficControllerPoolApiForZone(zoneName);\n   }\n\n   @Override\n   @AfterClass(groups = { \"integration\", \"live\" })\n   protected void tearDown() {\n      if (poolId != null)\n         api(zoneName).delete(poolId);\n      super.tearDown();\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/features/ZoneApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.features;\nimport static com.google.common.net.HttpHeaders.HOST;\nimport static jakarta.ws.rs.HttpMethod.POST;\nimport static jakarta.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR;\nimport static jakarta.ws.rs.core.Response.Status.OK;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\n\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.jclouds.ultradns.ws.UltraDNSWSApi;\nimport org.jclouds.ultradns.ws.UltraDNSWSExceptions.ResourceAlreadyExistsException;\nimport org.jclouds.ultradns.ws.domain.Zone.Type;\nimport org.jclouds.ultradns.ws.internal.BaseUltraDNSWSApiExpectTest;\nimport org.jclouds.ultradns.ws.parse.GetGeneralPropertiesForZoneResponseTest;\nimport org.jclouds.ultradns.ws.parse.GetZonesOfAccountResponseTest;\nimport org.testng.annotations.Test;\n@Test(groups = \"unit\", testName = \"ZoneApiExpectTest\")\npublic class ZoneApiExpectTest extends BaseUltraDNSWSApiExpectTest {\n   HttpRequest create = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/create_zone.xml\", \"application/xml\")).build();\n\n   HttpResponse createResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/zone_created.xml\", \"application/xml\")).build();\n\n   public void testCreateWhenResponseIs2xx() {\n      UltraDNSWSApi success = requestSendsResponse(create, createResponse);\n      success.getZoneApi().createInAccount(\"jclouds.org.\", \"AAAAAAAAAAAAAAAA\");\n   }\n\n   HttpResponse alreadyCreated = HttpResponse.builder().statusCode(INTERNAL_SERVER_ERROR.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/zone_already_exists.xml\", \"application/xml\")).build();\n\n   @Test(expectedExceptions = ResourceAlreadyExistsException.class, expectedExceptionsMessageRegExp = \"Zone already exists in the system.\")\n   public void testCreateWhenResponseError1802() {\n      UltraDNSWSApi already = requestSendsResponse(create, alreadyCreated);\n      already.getZoneApi().createInAccount(\"jclouds.org.\", \"AAAAAAAAAAAAAAAA\");\n   }\n\n   HttpRequest get = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/get_zone.xml\", \"application/xml\")).build();\n\n   HttpResponse getResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/zoneproperties.xml\", \"application/xml\")).build();\n\n   public void testGetWhenResponseIs2xx() {\n      UltraDNSWSApi success = requestSendsResponse(get, getResponse);\n\n      assertEquals(\n            success.getZoneApi().get(\"jclouds.org.\").toString(),\n            new GetGeneralPropertiesForZoneResponseTest().expected().toString());\n   }\n   \n   HttpResponse zoneDoesntExist = HttpResponse.builder().message(\"Server Error\").statusCode(INTERNAL_SERVER_ERROR.getStatusCode())\n         .payload(payloadFromResource(\"/zone_doesnt_exist.xml\")).build();\n   \n   public void testGetWhenResponseError2401() {\n      UltraDNSWSApi notFound = requestSendsResponse(get, zoneDoesntExist);\n      assertNull(notFound.getZoneApi().get(\"jclouds.org.\"));\n   }\n   \n   HttpRequest listByAccount = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/list_zones_by_account.xml\", \"application/xml\")).build();\n\n   HttpResponse listByAccountResponse = HttpResponse.builder().statusCode(OK.getStatusCode())\n         .payload(payloadFromResourceWithContentType(\"/zones.xml\", \"application/xml\")).build();\n\n   public void testListByAccountWhenResponseIs2xx() {\n      UltraDNSWSApi success = requestSendsResponse(listByAccount, listByAccountResponse);\n\n      assertEquals(\n            success.getZoneApi().listByAccount(\"AAAAAAAAAAAAAAAA\").toString(),\n            new GetZonesOfAccountResponseTest().expected().toString());\n   }\n   \n   HttpResponse accountDoesntExist = HttpResponse.builder().message(\"Server Error\").statusCode(INTERNAL_SERVER_ERROR.getStatusCode())\n         .payload(payloadFromResource(\"/account_doesnt_exist.xml\")).build();\n   \n   @Test(expectedExceptions = ResourceNotFoundException.class, expectedExceptionsMessageRegExp = \"Account not found in the system. ID: AAAAAAAAAAAAAAAA\")\n   public void testListByAccountWhenResponseError2401() {\n      UltraDNSWSApi notFound = requestSendsResponse(listByAccount, accountDoesntExist);\n      notFound.getZoneApi().listByAccount(\"AAAAAAAAAAAAAAAA\");\n   }\n     \n   HttpRequest listByAccountAndType = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/list_zones_by_account_and_type.xml\", \"application/xml\")).build();\n\n   public void testListByAccountAndTypeWhenResponseIs2xx() {\n      UltraDNSWSApi success = requestSendsResponse(listByAccountAndType, listByAccountResponse);\n\n      assertEquals(\n            success.getZoneApi().listByAccountAndType(\"AAAAAAAAAAAAAAAA\", Type.PRIMARY).toString(),\n            new GetZonesOfAccountResponseTest().expected().toString());\n   }\n\n   @Test(expectedExceptions = ResourceNotFoundException.class, expectedExceptionsMessageRegExp = \"Account not found in the system. ID: AAAAAAAAAAAAAAAA\")\n   public void testListByAccountAndTypeWhenResponseError2401() {\n      UltraDNSWSApi notFound = requestSendsResponse(listByAccountAndType, accountDoesntExist);\n      notFound.getZoneApi().listByAccountAndType(\"AAAAAAAAAAAAAAAA\", Type.PRIMARY);\n   }\n\n   HttpRequest delete = HttpRequest.builder().method(POST)\n         .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n         .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n         .payload(payloadFromResourceWithContentType(\"/delete_zone.xml\", \"application/xml\")).build();\n\n   HttpResponse deleteResponse = HttpResponse.builder().statusCode(404)\n         .payload(payloadFromResourceWithContentType(\"/zone_deleted.xml\", \"application/xml\")).build();\n\n   public void testDeleteWhenResponseIs2xx() {\n      UltraDNSWSApi success = requestSendsResponse(delete, deleteResponse);\n      success.getZoneApi().delete(\"jclouds.org.\");\n   }\n\n   public void testDeleteWhenResponseError1801() {\n      UltraDNSWSApi notFound = requestSendsResponse(delete, zoneDoesntExist);\n      notFound.getZoneApi().delete(\"jclouds.org.\");\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/features/ZoneApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.features;\n\nimport static java.util.logging.Logger.getAnonymousLogger;\nimport static org.jclouds.ultradns.ws.domain.Zone.Type.PRIMARY;\nimport static org.jclouds.ultradns.ws.predicates.ZonePredicates.typeEqualTo;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNotNull;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.assertTrue;\nimport static org.testng.Assert.fail;\n\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.jclouds.ultradns.ws.UltraDNSWSExceptions.ResourceAlreadyExistsException;\nimport org.jclouds.ultradns.ws.domain.Zone;\nimport org.jclouds.ultradns.ws.domain.Zone.Type;\nimport org.jclouds.ultradns.ws.domain.ZoneProperties;\nimport org.jclouds.ultradns.ws.internal.BaseUltraDNSWSApiLiveTest;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.FluentIterable;\n\n@Test(groups = \"live\", testName = \"ZoneApiLiveTest\")\npublic class ZoneApiLiveTest extends BaseUltraDNSWSApiLiveTest {\n\n   private void checkZone(Zone zone) {\n      assertNotNull(zone.getId(), \"Id cannot be null for \" + zone);\n      assertNotNull(zone.getName(), \"Name cannot be null for \" + zone);\n      assertNotNull(zone.getType(), \"Type cannot be null for \" + zone);\n      assertNotNull(zone.getTypeCode(), \"TypeCode cannot be null for \" + zone);\n      assertEquals(zone.getTypeCode(), zone.getType().getCode());\n      assertNotNull(zone.getAccountId(), \"AccountId cannot be null for \" + zone);\n      assertEquals(zone.getAccountId(), account.getId());\n      assertNotNull(zone.getOwnerId(), \"OwnerId cannot be null for \" + zone);\n      assertNotNull(zone.getDNSSECStatus(), \"DNSSECStatus cannot be null for \" + zone);\n      assertNotNull(zone.getPrimarySrc(), \"While PrimarySrc can be null, its Optional wrapper cannot \" + zone);\n   }\n\n   @Test\n   public void testListZonesByAccount() {\n      FluentIterable<Zone> response = api().listByAccount(account.getId());\n\n      for (Zone zone : response) {\n         checkZone(zone);\n      }\n\n      if (response.anyMatch(typeEqualTo(PRIMARY))) {\n         assertEquals(api().listByAccountAndType(account.getId(), PRIMARY).toSet(), response\n               .filter(typeEqualTo(PRIMARY)).toSet());\n      }\n   }\n\n   @Test\n   public void testListZonesByAccountWhenAccountIdNotFound() {\n      assertTrue(api().listByAccount(\"AAAAAAAAAAAAAAAA\").isEmpty());\n   }\n\n   @Test\n   public void testGetZone() {\n      for (Zone zone : api().listByAccount(account.getId())) {\n         ZoneProperties zoneProperties = api().get(zone.getName());\n         assertEquals(zoneProperties.getName(), zone.getName());\n         assertEquals(zoneProperties.getType(), zone.getType());\n         assertEquals(zoneProperties.getTypeCode(), zone.getTypeCode());\n         assertNotNull(zoneProperties.getModified(), \"Modified cannot be null for \" + zone);\n         assertTrue(zoneProperties.getResourceRecordCount() >= 0,\n               \"ResourceRecordCount must be positive or zero for a Zone \" + zone);\n      }\n   }\n\n   @Test\n   public void testGetZoneWhenNotFound() {\n      assertNull(api().get(\"AAAAAAAAAAAAAAAA\"));\n   }\n\n   @Test\n   public void testDeleteZoneWhenNotFound() {\n      api().delete(\"AAAAAAAAAAAAAAAA\");\n   }\n\n   @Test(expectedExceptions = ResourceNotFoundException.class, expectedExceptionsMessageRegExp = \"Account not found in the system. ID: AAAAAAAAAAAAAAAA\")\n   public void testCreateZoneBadAccountId() {\n      api().createInAccount(zoneName, \"AAAAAAAAAAAAAAAA\");\n   }\n\n   @Test\n   public void testCreateAndDeleteZone() {\n      try {\n         api().createInAccount(zoneName, account.getId());\n         ZoneProperties newZone = api().get(zoneName);\n         getAnonymousLogger().info(\"created zone: \" + newZone);\n\n         try {\n            api().createInAccount(zoneName, account.getId());\n            fail();\n         } catch (ResourceAlreadyExistsException e) {\n\n         }\n\n         assertEquals(newZone.getName(), zoneName);\n         assertEquals(newZone.getType(), Type.PRIMARY);\n         assertEquals(newZone.getTypeCode(), Type.PRIMARY.getCode());\n         assertNotNull(newZone.getModified(), \"Modified cannot be null for \" + newZone);\n         assertEquals(newZone.getResourceRecordCount(), 5);\n      } finally {\n         api().delete(zoneName);\n      }\n   }\n\n   protected ZoneApi api() {\n      return api.getZoneApi();\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/handlers/UltraDNSWSErrorHandlerTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.handlers;\nimport static com.google.common.base.Throwables.propagate;\nimport static com.google.common.net.HttpHeaders.HOST;\nimport static jakarta.ws.rs.HttpMethod.POST;\nimport static jakarta.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR;\nimport static org.jclouds.rest.internal.BaseRestApiExpectTest.payloadFromStringWithContentType;\nimport static org.jclouds.util.Strings2.toStringAndClose;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\n\nimport org.jclouds.http.HttpCommand;\nimport org.jclouds.http.HttpRequest;\nimport org.jclouds.http.HttpResponse;\nimport org.jclouds.http.functions.config.SaxParserModule;\nimport org.jclouds.io.Payload;\nimport org.jclouds.rest.ResourceNotFoundException;\nimport org.jclouds.ultradns.ws.UltraDNSWSExceptions.DirectionalGroupOverlapException;\nimport org.jclouds.ultradns.ws.UltraDNSWSExceptions.ResourceAlreadyExistsException;\nimport org.jclouds.ultradns.ws.UltraDNSWSResponseException;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Guice;\n@Test(groups = \"unit\")\npublic class UltraDNSWSErrorHandlerTest {\n   UltraDNSWSErrorHandler function = Guice.createInjector(new SaxParserModule()).getInstance(\n         UltraDNSWSErrorHandler.class);\n\n   @Test\n   public void testCode0SetsUltraDNSWSResponseException() throws IOException {\n      HttpRequest request = HttpRequest.builder().method(POST)\n                                                 .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n                                                 .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n                                                 .payload(payloadFromResource(\"/list_tasks.xml\")).build();\n      HttpCommand command = new HttpCommand(request);\n      HttpResponse response = HttpResponse.builder()\n                                          .message(INTERNAL_SERVER_ERROR.getReasonPhrase())\n                                          .statusCode(INTERNAL_SERVER_ERROR.getStatusCode())\n                                          .payload(payloadFromResource(\"/server_fault.xml\")).build();\n\n      function.handleError(command, response);\n\n      assertEquals(command.getException().getClass(), UltraDNSWSResponseException.class);\n      assertEquals(command.getException().getMessage(), \"Error 0\");\n\n      UltraDNSWSResponseException exception = UltraDNSWSResponseException.class.cast(command.getException());\n\n      assertEquals(exception.getError().getCode(), 0);\n   }\n\n   @Test\n   public void testCode0ForDescriptionMatchingCannotFindSetsResourceNotFoundException() throws IOException {\n      HttpRequest request = HttpRequest.builder().method(POST)\n                                                 .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n                                                 .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n                                                 .payload(payloadFromResource(\"/list_tasks.xml\")).build();\n      HttpCommand command = new HttpCommand(request);\n      HttpResponse response = HttpResponse.builder()\n                                          .message(INTERNAL_SERVER_ERROR.getReasonPhrase())\n                                          .statusCode(INTERNAL_SERVER_ERROR.getStatusCode())\n                                          .payload(payloadFromResource(\"/task_doesnt_exist.xml\")).build();\n\n      function.handleError(command, response);\n\n      assertEquals(command.getException().getClass(), ResourceNotFoundException.class);\n      assertEquals(command.getException().getMessage(), \"Cannot find task with guid AAAAAAAAAAAAAAAA\");\n\n      UltraDNSWSResponseException exception = UltraDNSWSResponseException.class.cast(command.getException().getCause());\n\n      assertEquals(exception.getMessage(), \"Error 0: Cannot find task with guid AAAAAAAAAAAAAAAA\");\n      assertEquals(exception.getError().getDescription().get(), \"Cannot find task with guid AAAAAAAAAAAAAAAA\");\n      assertEquals(exception.getError().getCode(), 0);\n   }\n\n   @Test\n   public void testCode2401SetsResourceNotFoundException() throws IOException {\n      HttpRequest request = HttpRequest.builder().method(POST)\n                                                 .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n                                                 .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n                                                 .payload(payloadFromResource(\"/list_zones_by_account.xml\")).build();\n      HttpCommand command = new HttpCommand(request);\n      HttpResponse response = HttpResponse.builder()\n                                          .message(INTERNAL_SERVER_ERROR.getReasonPhrase())\n                                          .statusCode(INTERNAL_SERVER_ERROR.getStatusCode())\n                                          .payload(payloadFromResource(\"/account_doesnt_exist.xml\")).build();\n\n      function.handleError(command, response);\n\n      assertEquals(command.getException().getClass(), ResourceNotFoundException.class);\n      assertEquals(command.getException().getMessage(), \"Account not found in the system. ID: AAAAAAAAAAAAAAAA\");\n\n      UltraDNSWSResponseException exception = UltraDNSWSResponseException.class.cast(command.getException().getCause());\n\n      assertEquals(exception.getMessage(), \"Error 2401: Account not found in the system. ID: AAAAAAAAAAAAAAAA\");\n      assertEquals(exception.getError().getDescription().get(), \"Account not found in the system. ID: AAAAAAAAAAAAAAAA\");\n      assertEquals(exception.getError().getCode(), 2401);\n   }\n\n   @Test\n   public void testCode1801SetsResourceNotFoundException() throws IOException {\n      HttpRequest request = HttpRequest.builder().method(POST)\n                                                 .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n                                                 .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n                                                 .payload(payloadFromResource(\"/get_zone.xml\")).build();\n      HttpCommand command = new HttpCommand(request);\n      HttpResponse response = HttpResponse.builder()\n                                          .message(INTERNAL_SERVER_ERROR.getReasonPhrase())\n                                          .statusCode(INTERNAL_SERVER_ERROR.getStatusCode())\n                                          .payload(payloadFromResource(\"/zone_doesnt_exist.xml\")).build();\n\n      function.handleError(command, response);\n\n      assertEquals(command.getException().getClass(), ResourceNotFoundException.class);\n      assertEquals(command.getException().getMessage(), \"Zone does not exist in the system.\");\n\n      UltraDNSWSResponseException exception = UltraDNSWSResponseException.class.cast(command.getException().getCause());\n\n      assertEquals(exception.getMessage(), \"Error 1801: Zone does not exist in the system.\");\n      assertEquals(exception.getError().getDescription().get(), \"Zone does not exist in the system.\");\n      assertEquals(exception.getError().getCode(), 1801);\n   }\n\n   @Test\n   public void testCode2103SetsResourceNotFoundException() throws IOException {\n      HttpRequest request = HttpRequest.builder().method(POST)\n                                                 .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n                                                 .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n                                                 .payload(payloadFromResource(\"/delete_rr.xml\")).build();\n      HttpCommand command = new HttpCommand(request);\n      HttpResponse response = HttpResponse.builder()\n                                          .message(INTERNAL_SERVER_ERROR.getReasonPhrase())\n                                          .statusCode(INTERNAL_SERVER_ERROR.getStatusCode())\n                                          .payload(payloadFromResource(\"/rr_doesnt_exist.xml\")).build();\n\n      function.handleError(command, response);\n\n      assertEquals(command.getException().getClass(), ResourceNotFoundException.class);\n      assertEquals(command.getException().getMessage(), \"No Resource Record with GUID found in the system AAAAAAAAAAAAAAAA\");\n\n      UltraDNSWSResponseException exception = UltraDNSWSResponseException.class.cast(command.getException().getCause());\n\n      assertEquals(exception.getMessage(), \"Error 2103: No Resource Record with GUID found in the system AAAAAAAAAAAAAAAA\");\n      assertEquals(exception.getError().getDescription().get(), \"No Resource Record with GUID found in the system AAAAAAAAAAAAAAAA\");\n      assertEquals(exception.getError().getCode(), 2103);\n   }\n\n   @Test\n   public void testCode1802SetsResourceAlreadyExistsException() throws IOException {\n      HttpRequest request = HttpRequest.builder().method(POST)\n                                                 .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n                                                 .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n                                                 .payload(payloadFromResource(\"/create_zone.xml\")).build();\n      HttpCommand command = new HttpCommand(request);\n      HttpResponse response = HttpResponse.builder()\n                                          .message(INTERNAL_SERVER_ERROR.getReasonPhrase())\n                                          .statusCode(INTERNAL_SERVER_ERROR.getStatusCode())\n                                          .payload(payloadFromResource(\"/zone_already_exists.xml\")).build();\n\n      function.handleError(command, response);\n\n      assertEquals(command.getException().getClass(), ResourceAlreadyExistsException.class);\n      assertEquals(command.getException().getMessage(), \"Zone already exists in the system.\");\n\n      UltraDNSWSResponseException exception = UltraDNSWSResponseException.class.cast(command.getException().getCause());\n\n      assertEquals(exception.getMessage(), \"Error 1802: Zone already exists in the system.\");\n      assertEquals(exception.getError().getDescription().get(), \"Zone already exists in the system.\");\n      assertEquals(exception.getError().getCode(), 1802);\n   }\n\n   @Test\n   public void testCode2111SetsResourceAlreadyExistsException() throws IOException {\n      HttpRequest request = HttpRequest.builder().method(POST)\n                                                 .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n                                                 .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n                                                 .payload(payloadFromResource(\"/create_rr.xml\")).build();\n      HttpCommand command = new HttpCommand(request);\n      HttpResponse response = HttpResponse.builder()\n                                          .message(INTERNAL_SERVER_ERROR.getReasonPhrase())\n                                          .statusCode(INTERNAL_SERVER_ERROR.getStatusCode())\n                                          .payload(payloadFromResource(\"/rr_already_exists.xml\")).build();\n\n      function.handleError(command, response);\n\n      assertEquals(command.getException().getClass(), ResourceAlreadyExistsException.class);\n      assertEquals(command.getException().getMessage(),\n            \"Resource Record of type 15 with these attributes already exists in the system.\");\n\n      UltraDNSWSResponseException exception = UltraDNSWSResponseException.class.cast(command.getException().getCause());\n\n      assertEquals(exception.getMessage(),\n            \"Error 2111: Resource Record of type 15 with these attributes already exists in the system.\");\n      assertEquals(exception.getError().getDescription().get(),\n            \"Resource Record of type 15 with these attributes already exists in the system.\");\n      assertEquals(exception.getError().getCode(), 2111);\n   }\n\n   @Test\n   public void testCode2911SetsResourceNotFoundException() throws IOException {\n      HttpRequest request = HttpRequest.builder().method(POST)\n                                                 .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n                                                 .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n                                                 .payload(payloadFromResource(\"/delete_lbpool.xml\")).build();\n      HttpCommand command = new HttpCommand(request);\n      HttpResponse response = HttpResponse.builder()\n                                          .message(INTERNAL_SERVER_ERROR.getReasonPhrase())\n                                          .statusCode(INTERNAL_SERVER_ERROR.getStatusCode())\n                                          .payload(payloadFromResource(\"/lbpool_doesnt_exist.xml\")).build();\n\n      function.handleError(command, response);\n\n      assertEquals(command.getException().getClass(), ResourceNotFoundException.class);\n      assertEquals(command.getException().getMessage(), \"Pool does not exist in the system\");\n\n      UltraDNSWSResponseException exception = UltraDNSWSResponseException.class.cast(command.getException().getCause());\n\n      assertEquals(exception.getMessage(), \"Error 2911: Pool does not exist in the system\");\n      assertEquals(exception.getError().getDescription().get(), \"Pool does not exist in the system\");\n      assertEquals(exception.getError().getCode(), 2911);\n   }\n\n   @Test\n   public void testCode2142SetsResourceNotFoundException() throws IOException {\n      HttpRequest request = HttpRequest.builder().method(POST)\n                                                 .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n                                                 .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n                                                 .payload(payloadFromResource(\"/delete_lbpool.xml\")).build();\n      HttpCommand command = new HttpCommand(request);\n      HttpResponse response = HttpResponse.builder()\n                                          .message(INTERNAL_SERVER_ERROR.getReasonPhrase())\n                                          .statusCode(INTERNAL_SERVER_ERROR.getStatusCode())\n                                          .payload(payloadFromResource(\"/directionalpool_doesnt_exist.xml\")).build();\n\n      function.handleError(command, response);\n\n      assertEquals(command.getException().getClass(), ResourceNotFoundException.class);\n      assertEquals(command.getException().getMessage(), \"No Pool or Multiple pools of same type exists for the PoolName : foo.jclouds.org.\");\n\n      UltraDNSWSResponseException exception = UltraDNSWSResponseException.class.cast(command.getException().getCause());\n\n      assertEquals(exception.getMessage(), \"Error 2142: No Pool or Multiple pools of same type exists for the PoolName : foo.jclouds.org.\");\n      assertEquals(exception.getError().getDescription().get(), \"No Pool or Multiple pools of same type exists for the PoolName : foo.jclouds.org.\");\n      assertEquals(exception.getError().getCode(), 2142);\n   }\n\n   @Test\n   public void testCode2912SetsResourceAlreadyExistsException() throws IOException {\n      HttpRequest request = HttpRequest.builder().method(POST)\n                                                 .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n                                                 .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n                                                 .payload(payloadFromResource(\"/create_rrpool_a.xml\")).build();\n      HttpCommand command = new HttpCommand(request);\n      HttpResponse response = HttpResponse.builder()\n                                          .message(INTERNAL_SERVER_ERROR.getReasonPhrase())\n                                          .statusCode(INTERNAL_SERVER_ERROR.getStatusCode())\n                                          .payload(payloadFromResource(\"/lbpool_already_exists.xml\")).build();\n\n      function.handleError(command, response);\n\n      assertEquals(command.getException().getClass(), ResourceAlreadyExistsException.class);\n      assertEquals(command.getException().getMessage(),\n            \"Pool already created for this host name : www.rrpool.adrianc.rrpool.ultradnstest.jclouds.org.\");\n\n      UltraDNSWSResponseException exception = UltraDNSWSResponseException.class.cast(command.getException().getCause());\n\n      assertEquals(exception.getMessage(),\n            \"Error 2912: Pool already created for this host name : www.rrpool.adrianc.rrpool.ultradnstest.jclouds.org.\");\n      assertEquals(exception.getError().getDescription().get(),\n            \"Pool already created for this host name : www.rrpool.adrianc.rrpool.ultradnstest.jclouds.org.\");\n      assertEquals(exception.getError().getCode(), 2912);\n   }\n\n   @Test\n   public void testCode3101SetsResourceNotFoundException() throws IOException {\n      HttpRequest request = HttpRequest.builder().method(POST)\n                                                 .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n                                                 .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n                                                 .payload(payloadFromResource(\"/delete_tcrecord.xml\")).build();\n      HttpCommand command = new HttpCommand(request);\n      HttpResponse response = HttpResponse.builder()\n                                          .message(INTERNAL_SERVER_ERROR.getReasonPhrase())\n                                          .statusCode(INTERNAL_SERVER_ERROR.getStatusCode())\n                                          .payload(payloadFromResource(\"/tcrecord_doesnt_exist.xml\")).build();\n\n      function.handleError(command, response);\n\n      assertEquals(command.getException().getClass(), ResourceNotFoundException.class);\n      assertEquals(command.getException().getMessage(), \"Pool Record does not exist.\");\n\n      UltraDNSWSResponseException exception = UltraDNSWSResponseException.class.cast(command.getException().getCause());\n\n      assertEquals(exception.getMessage(), \"Error 3101: Pool Record does not exist.\");\n      assertEquals(exception.getError().getDescription().get(), \"Pool Record does not exist.\");\n      assertEquals(exception.getError().getCode(), 3101);\n   }\n\n   @Test\n   public void testCode4003SetsResourceNotFoundException() throws IOException {\n      HttpRequest request = HttpRequest.builder().method(POST)\n                                                 .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n                                                 .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n                                                 .payload(payloadFromResource(\"/delete_tcrecord.xml\")).build();\n      HttpCommand command = new HttpCommand(request);\n      HttpResponse response = HttpResponse.builder()\n                                          .message(INTERNAL_SERVER_ERROR.getReasonPhrase())\n                                          .statusCode(INTERNAL_SERVER_ERROR.getStatusCode())\n                                          .payload(payloadFromResource(\"/directionalgroup_doesnt_exist.xml\")).build();\n\n      function.handleError(command, response);\n\n      assertEquals(command.getException().getClass(), ResourceNotFoundException.class);\n      assertEquals(command.getException().getMessage(), \"Group does not exist.\");\n\n      UltraDNSWSResponseException exception = UltraDNSWSResponseException.class.cast(command.getException().getCause());\n\n      assertEquals(exception.getMessage(), \"Error 4003: Group does not exist.\");\n      assertEquals(exception.getError().getDescription().get(), \"Group does not exist.\");\n      assertEquals(exception.getError().getCode(), 4003);\n   }\n\n   @Test\n   public void testCode2705SetsResourceNotFoundException() throws IOException {\n      HttpRequest request = HttpRequest.builder().method(POST)\n                                                 .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n                                                 .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n                                                 .payload(payloadFromResource(\"/delete_directionalrecord.xml\")).build();\n      HttpCommand command = new HttpCommand(request);\n      HttpResponse response = HttpResponse.builder()\n                                          .message(INTERNAL_SERVER_ERROR.getReasonPhrase())\n                                          .statusCode(INTERNAL_SERVER_ERROR.getStatusCode())\n                                          .payload(payloadFromResource(\"/directionalrecord_doesnt_exist.xml\")).build();\n\n      function.handleError(command, response);\n\n      assertEquals(command.getException().getClass(), ResourceNotFoundException.class);\n      assertEquals(command.getException().getMessage(), \"Directional Pool Record does not exist in the system\");\n\n      UltraDNSWSResponseException exception = UltraDNSWSResponseException.class.cast(command.getException().getCause());\n\n      assertEquals(exception.getMessage(), \"Error 2705: Directional Pool Record does not exist in the system\");\n      assertEquals(exception.getError().getDescription().get(), \"Directional Pool Record does not exist in the system\");\n      assertEquals(exception.getError().getCode(), 2705);\n   }\n\n   @Test\n   public void testCode7021SetsDirectionalGroupOverlapException() throws IOException {\n      HttpRequest request = HttpRequest.builder().method(POST)\n                                                 .endpoint(\"https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01\")\n                                                 .addHeader(HOST, \"ultra-api.ultradns.com:8443\")\n                                                 .payload(payloadFromResource(\"/create_directionalrecord_newgroup.xml\")).build();\n      HttpCommand command = new HttpCommand(request);\n      HttpResponse response = HttpResponse.builder()\n                                          .message(INTERNAL_SERVER_ERROR.getReasonPhrase())\n                                          .statusCode(INTERNAL_SERVER_ERROR.getStatusCode())\n                                          .payload(payloadFromResource(\"/directionalgroup_overlap.xml\")).build();\n\n      function.handleError(command, response);\n\n      assertEquals(command.getException().getClass(), DirectionalGroupOverlapException.class);\n      assertEquals(command.getException().getMessage(), \"Geolocation/Source IP overlap(s) found: Region: Utah (Group: US )\");\n\n      UltraDNSWSResponseException exception = UltraDNSWSResponseException.class.cast(command.getException().getCause());\n\n      assertEquals(exception.getMessage(), \"Error 7021: Geolocation/Source IP overlap(s) found: Region: Utah (Group: US )\");\n      assertEquals(exception.getError().getDescription().get(), \"Geolocation/Source IP overlap(s) found: Region: Utah (Group: US )\");\n      assertEquals(exception.getError().getCode(), 7021);\n   }\n\n   private Payload payloadFromResource(String resource) {\n      try {\n         return payloadFromStringWithContentType(toStringAndClose(getClass().getResourceAsStream(resource)),\n               \"application/xml\");\n      } catch (IOException e) {\n         throw propagate(e);\n      }\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/internal/BaseDirectionalApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.internal;\n\nimport static com.google.common.base.Predicates.equalTo;\nimport static com.google.common.base.Predicates.not;\nimport static com.google.common.collect.Iterables.filter;\nimport static com.google.common.collect.Multimaps.filterKeys;\nimport static org.jclouds.ultradns.ws.domain.DirectionalPool.RecordType.IPV4;\nimport static org.jclouds.ultradns.ws.predicates.DirectionalPoolPredicates.recordIdEqualTo;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.ultradns.ws.domain.DirectionalGroup;\nimport org.jclouds.ultradns.ws.domain.DirectionalPool;\nimport org.jclouds.ultradns.ws.domain.DirectionalPoolRecord;\nimport org.jclouds.ultradns.ws.domain.DirectionalPoolRecordDetail;\nimport org.jclouds.ultradns.ws.domain.IdAndName;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.Multimap;\n\n@Test(groups = \"live\")\npublic class BaseDirectionalApiLiveTest extends BaseUltraDNSWSApiLiveTest {\n\n   protected String dname = \"www.\" + zoneName;\n\n   @Override\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   public void setup() {\n      super.setup();\n      setupGroups();\n      createZone();\n   }\n\n   protected String cnamePoolId;\n   \n   protected String cnameEU;\n   protected DirectionalGroup eu = null;\n   protected DirectionalPoolRecord cnameRecordEU = DirectionalPoolRecord.drBuilder()\n                                                                        .type(\"CNAME\")\n                                                                        .ttl(8600)\n                                                                        .rdata(\"eu.\" + dname).build();\n\n   /**\n    * lower ttl as plan to accept territories from canary\n    */\n   protected String cnameUS;\n   protected DirectionalGroup us = null;\n   protected DirectionalPoolRecord cnameRecordUS = DirectionalPoolRecord.drBuilder()\n                                                                        .type(\"CNAME\")\n                                                                        .ttl(300)\n                                                                        .rdata(\"us.\" + dname).build();\n\n   /**\n    * lower ttl as plan to move territories into recordUS\n    */\n   /**\n    * a test state.\n    */\n   protected String cnameCanary;\n   protected DirectionalGroup nebraska = null;\n   protected DirectionalPoolRecord cnameRecordCanary = DirectionalPoolRecord.drBuilder()\n                                                                            .type(\"CNAME\")\n                                                                            .ttl(300)\n                                                                            .rdata(\"canary.\" + dname).build();\n   protected String cname2Canary;\n   protected DirectionalPoolRecord cname2RecordCanary = cnameRecordCanary.toBuilder().rdata(\"parrot.\" + dname).build();\n   \n   protected String aPoolId;\n\n   /**\n    * Uses all non-configured group to support all clients\n    */\n   protected String a1Prod;\n   protected DirectionalPoolRecord a1RecordProd = DirectionalPoolRecord.drBuilder()\n                                                                       .type(\"A\")\n                                                                       .ttl(300)\n                                                                       .rdata(\"1.1.0.1\").build();\n   /**\n    * contains territories currently being tested.\n    */\n   protected String a1Canary;\n   protected DirectionalPoolRecord a1RecordCanary = DirectionalPoolRecord.drBuilder()\n                                                                         .type(\"A\")\n                                                                         .ttl(300)\n                                                                         .rdata(\"1.1.1.1\").build();\n\n   public static final String REGION_US = \"United States (US)\";\n\n   void setupGroups() {\n      // all territories in EU\n      eu = DirectionalGroup.builder()\n                           .name(\"EU\")\n                           .description(\"Clients we classify as being in Europe\")\n                           .mapRegion(\"Europe\").build();\n      nebraska = DirectionalGroup.builder()\n                               .name(\"Canary\")\n                               .description(\"Clients who are testing our service\")\n                               .mapRegionToTerritory(REGION_US, \"Nebraska\").build();\n\n      // in order to pick certain territories, we need to know what they are\n      Multimap<IdAndName, String> availableRegions = api.getRegionsByIdAndName();\n\n      // find the us Territories\n      Iterable<String> usTerritories = filterKeys(availableRegions, \n            IdAndName.nameEqualTo(REGION_US)).values();\n\n      us = DirectionalGroup.builder()\n                           .name(\"US\")\n                           .description(\"Clients we classify as being in US\")\n                           .mapRegionToTerritories(REGION_US, \n                                 filter(usTerritories, not(equalTo(\"Nebraska\")))).build();\n   }\n\n   protected void checkGroupByDNameAndIdContainsTerritory(String dname, String poolRecordId, String territory) {\n      DirectionalGroup regions = getGroup(dname, poolRecordId);\n      assertTrue(regions.values().contains(territory), poolRecordId + \" doesn't contain \" + territory);\n   }\n\n   protected void checkGroupByDNameAndIdDoesntContainTerritory(String dname, String poolRecordId, String territory) {\n      DirectionalGroup regions = getGroup(dname, poolRecordId);\n      assertFalse(regions.values().contains(territory), poolRecordId + \" contains \" + territory);\n   }\n\n   /**\n    * gets the geo group or the non-configured group.\n    */\n   private DirectionalGroup getGroup(String dname, String poolRecordId) {\n      DirectionalPoolRecordDetail record = getRecordByDNameAndId(dname, poolRecordId).get();\n      return api.getDirectionalGroupApiForAccount(account.getId())\n                .get(record.getGeolocationGroup().or(record.getGroup()).get().getId());\n   }\n\n   protected Optional<DirectionalPool> getPoolById(final String cnamePoolId) {\n      return api.getDirectionalPoolApiForZone(zoneName)\n                .list()\n                .firstMatch(new Predicate<DirectionalPool>() {\n                     public boolean apply(DirectionalPool in) {\n                        return in.getId().equals(cnamePoolId);\n                     }\n                  });\n   }\n\n   protected Optional<DirectionalPoolRecordDetail> getRecordByDNameAndId(String dname, String recordId) {\n      return api.getDirectionalPoolApiForZone(zoneName)\n                .listRecordsByDNameAndType(dname, IPV4.getCode())\n                .firstMatch(recordIdEqualTo(recordId));\n   }\n\n   @Override\n   @AfterClass(groups = { \"integration\", \"live\" })\n   protected void tearDown() {\n      if (cnamePoolId != null)\n         api.getDirectionalPoolApiForZone(zoneName).delete(cnamePoolId);\n      if (aPoolId != null)\n         api.getDirectionalPoolApiForZone(zoneName).delete(aPoolId);\n      super.tearDown();\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/internal/BaseUltraDNSWSApiExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.internal;\n\nimport org.jclouds.ultradns.ws.UltraDNSWSApi;\n\npublic class BaseUltraDNSWSApiExpectTest extends BaseUltraDNSWSExpectTest<UltraDNSWSApi> {\n\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/internal/BaseUltraDNSWSApiLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.internal;\n\nimport static com.google.common.base.CaseFormat.LOWER_HYPHEN;\nimport static com.google.common.base.CaseFormat.UPPER_CAMEL;\n\nimport org.jclouds.apis.BaseApiLiveTest;\nimport org.jclouds.ultradns.ws.UltraDNSWSApi;\nimport org.jclouds.ultradns.ws.domain.IdAndName;\nimport org.jclouds.ultradns.ws.domain.Zone;\nimport org.testng.annotations.AfterClass;\nimport org.testng.annotations.BeforeClass;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\nimport com.google.common.base.Predicate;\n\n@Test(groups = \"live\")\npublic class BaseUltraDNSWSApiLiveTest extends BaseApiLiveTest<UltraDNSWSApi> {\n   protected String zoneName = String.format(\"%s-%s.ultradnstest.jclouds.org.\", System.getProperty(\"user.name\")\n         .replace('.', '-'), UPPER_CAMEL.to(LOWER_HYPHEN, getClass().getSimpleName()));\n   protected String zoneId;\n   protected IdAndName account;\n\n   public BaseUltraDNSWSApiLiveTest() {\n      provider = \"ultradns-ws\";\n   }\n\n   @Override\n   @BeforeClass(groups = { \"integration\", \"live\" })\n   public void setup() {\n      super.setup();\n      account = api.getCurrentAccount();\n   }\n\n   protected void createZone() {\n      api.getZoneApi().delete(zoneName);\n      api.getZoneApi().createInAccount(zoneName, account.getId());\n      zoneId = getZoneByName(zoneName).get().getId();\n   }\n\n   protected Optional<Zone> getZoneByName(final String zoneName) {\n      return api.getZoneApi().listByAccount(account.getId()).firstMatch(new Predicate<Zone>() {\n         public boolean apply(Zone in) {\n            return in.getName().equals(zoneName);\n         }\n      });\n   }\n\n   @Override\n   @AfterClass(groups = { \"integration\", \"live\" })\n   protected void tearDown() {\n      if (zoneId != null)\n         api.getZoneApi().delete(zoneName);\n      super.tearDown();\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/internal/BaseUltraDNSWSExpectTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.internal;\n\nimport org.jclouds.rest.internal.BaseRestApiExpectTest;\n\npublic class BaseUltraDNSWSExpectTest<T> extends BaseRestApiExpectTest<T> {\n\n   public BaseUltraDNSWSExpectTest() {\n      provider = \"ultradns-ws\";\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/parse/GetAccountLevelDirectionalGroupsResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.parse;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.ultradns.ws.domain.AccountLevelGroup;\nimport org.jclouds.ultradns.ws.domain.DirectionalPool.Type;\nimport org.jclouds.ultradns.ws.xml.AccountLevelGroupsHandler;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableList;\n\n@Test(testName = \"GetAccountLevelDirectionalGroupsResponseTest\")\npublic class GetAccountLevelDirectionalGroupsResponseTest extends BaseHandlerTest {\n\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/accountlevelgroups.xml\");\n\n      FluentIterable<AccountLevelGroup> expected = expected();\n\n      AccountLevelGroupsHandler handler = injector.getInstance(AccountLevelGroupsHandler.class);\n      FluentIterable<AccountLevelGroup> result = factory.create(handler).parse(is);\n\n      assertEquals(result.toSet().toString(), expected.toSet().toString());\n   }\n\n   public FluentIterable<AccountLevelGroup> expected() {\n      return FluentIterable.from(ImmutableList.<AccountLevelGroup> builder()\n                           .add(AccountLevelGroup.builder()\n                                                 .id(\"000000000000000A\")\n                                                 .name(\"ASIA\")\n                                                 .type(Type.GEOLOCATION)\n                                                 .recordCount(0).build())\n                           .add(AccountLevelGroup.builder()\n                                                 .id(\"000000000000000B\")\n                                                 .name(\"EU\")\n                                                 .type(Type.GEOLOCATION)\n                                                 .recordCount(3).build())\n                           .add(AccountLevelGroup.builder()\n                                                 .id(\"000000000000000C\")\n                                                 .name(\"LATAM\")\n                                                 .type(Type.GEOLOCATION)\n                                                 .recordCount(1).build()).build());\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/parse/GetAccountsListOfUserResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.parse;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.ultradns.ws.domain.IdAndName;\nimport org.jclouds.ultradns.ws.xml.AccountHandler;\nimport org.testng.annotations.Test;\n\n@Test(testName = \"GetAccountsListOfUserResponseTest\")\npublic class GetAccountsListOfUserResponseTest extends BaseHandlerTest {\n\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/account.xml\");\n\n      IdAndName expected = expected();\n\n      AccountHandler handler = injector.getInstance(AccountHandler.class);\n      IdAndName result = factory.create(handler).parse(is);\n\n      assertEquals(result, expected);\n   }\n\n   public IdAndName expected() {\n      return IdAndName.create(\"AAAAAAAAAAAAAAAA\", \"jclouds\");\n   }\n\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/parse/GetAllTasksResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.parse;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\nimport java.net.URI;\n\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.ultradns.ws.domain.Task;\nimport org.jclouds.ultradns.ws.domain.Task.StatusCode;\nimport org.jclouds.ultradns.ws.xml.TaskListHandler;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(testName = \"GetAllTasksResponseTest\")\npublic class GetAllTasksResponseTest extends BaseHandlerTest {\n\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/tasks.xml\");\n\n      FluentIterable<Task> expected = expected();\n\n      TaskListHandler handler = injector.getInstance(TaskListHandler.class);\n      FluentIterable<Task> result = factory.create(handler).parse(is);\n\n      assertEquals(result.toSet().toString(), expected.toSet().toString());\n   }\n\n   public FluentIterable<Task> expected() {\n      return FluentIterable.from(ImmutableSet.<Task> builder()\n                           .add(Task.builder()\n                                    .guid(\"0b40c7dd-748d-4c49-8506-26f0c7d2ea9c\")\n                                    .statusCode(StatusCode.COMPLETE)\n                                    .message(\"Processing complete\")\n                                    .resultUrl(URI.create(\"http://localhost:8008/users/node01/tasks/0b40c7dd-748d-4c49-8506-26f0c7d2ea9c/result\"))\n                                    .build())\n                           .build());\n   }\n\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/parse/GetAvailableGroupsResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.parse;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.ultradns.ws.xml.ItemListHandler;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(testName = \"GetAvailableGroupsResponseTest\")\npublic class GetAvailableGroupsResponseTest extends BaseHandlerTest {\n\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/directionalgroup_names.xml\");\n\n      FluentIterable<String> expected = expected();\n\n      ItemListHandler handler = injector.getInstance(ItemListHandler.class);\n      FluentIterable<String> result = factory.create(handler).parse(is);\n\n      assertEquals(result.toSet().toString(), expected.toSet().toString());\n   }\n\n   public FluentIterable<String> expected() {\n      return FluentIterable.from(ImmutableSet.of(\"EU-foo.jclouds.org.\", \"non-foo.jclouds.org.\"));\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/parse/GetAvailableRegionsResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.parse;\n\nimport static org.jclouds.ultradns.ws.domain.IdAndName.create;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.ultradns.ws.domain.IdAndName;\nimport org.jclouds.ultradns.ws.xml.RegionListHandler;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Multimap;\n\n@Test(testName = \"GetAvailableRegionsResponseTest\")\npublic class GetAvailableRegionsResponseTest extends BaseHandlerTest {\n\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/regions.xml\");\n\n      Multimap<IdAndName, String> expected = expected();\n\n      RegionListHandler handler = injector.getInstance(RegionListHandler.class);\n      Multimap<IdAndName, String> result = factory.create(handler).parse(is);\n\n      assertEquals(result.toString(), expected.toString());\n   }\n\n   public Multimap<IdAndName, String> expected() {\n      return ImmutableMultimap.<IdAndName, String> builder()\n                         .put(create(\"14\", \"Anonymous Proxy (A1)\"), \"Anonymous Proxy\")\n                         .putAll(create(\"3\", \"Antarctica\"), ImmutableSet.<String> builder()\n                                                                               .add(\"Antarctica\")\n                                                                               .add(\"Bouvet Island\")\n                                                                               .add(\"French Southern Territories\")\n                                                                               .build())\n                         .build();\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/parse/GetDirectionalDNSGroupDetailsResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.parse;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.ultradns.ws.domain.DirectionalGroup;\nimport org.jclouds.ultradns.ws.xml.DirectionalGroupHandler;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\n\n@Test(testName = \"GetDirectionalDNSGroupDetailsResponseTest\")\npublic class GetDirectionalDNSGroupDetailsResponseTest extends BaseHandlerTest {\n\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/directionalgroup.xml\");\n\n      DirectionalGroup expected = expected();\n\n      DirectionalGroupHandler handler = injector.getInstance(DirectionalGroupHandler.class);\n      DirectionalGroup result = factory.create(handler).parse(is);\n\n      assertEquals(result.toString(), expected.toString());\n   }\n\n   public DirectionalGroup expected() {\n      return DirectionalGroup.builder()\n                             .name(\"NON-EU\")\n                             .mapRegionToTerritory(\"Anonymous Proxy (A1)\", \"Anonymous Proxy\")\n                             .mapRegionToTerritory(\"Mexico\", \"Mexico\")\n                             .mapRegionToTerritories(\"Antarctica\", ImmutableList.<String> builder()\n                                                                   .add(\"Antarctica\")\n                                                                   .add(\"Bouvet Island\")\n                                                                   .add(\"French Southern Territories\")\n                                                                   .build()).build();\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/parse/GetDirectionalDNSRecordsForHostResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.parse;\n\nimport static org.jclouds.ultradns.ws.domain.IdAndName.create;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.ultradns.ws.domain.DirectionalPoolRecord;\nimport org.jclouds.ultradns.ws.domain.DirectionalPoolRecordDetail;\nimport org.jclouds.ultradns.ws.xml.DirectionalPoolRecordDetailListHandler;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(testName = \"GetDirectionalDNSRecordsForHostResponseTest\")\npublic class GetDirectionalDNSRecordsForHostResponseTest extends BaseHandlerTest {\n\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/directionalrecords.xml\");\n\n      FluentIterable<DirectionalPoolRecordDetail> expected = expected();\n\n      DirectionalPoolRecordDetailListHandler handler = injector.getInstance(DirectionalPoolRecordDetailListHandler.class);\n      FluentIterable<DirectionalPoolRecordDetail> result = factory.create(handler).parse(is);\n\n      assertEquals(result.toSet().toString(), expected.toSet().toString());\n   }\n\n   public FluentIterable<DirectionalPoolRecordDetail> expected() {\n      return FluentIterable.from(ImmutableSet.<DirectionalPoolRecordDetail> builder()\n                           .add(DirectionalPoolRecordDetail.builder()\n                                                       .zoneName(\"geo.jclouds.org.\")\n                                                       .name(\"www.geo.jclouds.org.\")\n                                                       .id(\"A000000000000001\")\n                                                       .geolocationGroup(create(\"C000000000000001\", \"southamerica\"))\n                                                       .record(DirectionalPoolRecord.drBuilder()\n                                                                                .type(\"CNAME\")\n                                                                                .ttl(300)\n                                                                                .noResponseRecord(false)\n                                                                                .rdata(\"southamerica.geo.jclouds.org.\").build()).build())\n                           .add(DirectionalPoolRecordDetail.builder()\n                                                       .zoneName(\"geo.jclouds.org.\")\n                                                       .name(\"www.geo.jclouds.org.\")\n                                                       .id(\"A000000000000002\")\n                                                       .group(create(\"B000000000000001\", \"All Non-Configured Regions\"))\n                                                       .record(DirectionalPoolRecord.drBuilder()\n                                                                                .type(\"A\")\n                                                                                .ttl(500)\n                                                                                .noResponseRecord(false)\n                                                                                .rdata(\"1.1.1.2\").build()).build())\n                           .add(DirectionalPoolRecordDetail.builder()\n                                                       .zoneName(\"geo.jclouds.org.\")\n                                                       .name(\"www.geo.jclouds.org.\")\n                                                       .id(\"A000000000000003\")\n                                                       .geolocationGroup(create(\"C000000000000002\", \"antarctica-unsupported\"))\n                                                       .record(DirectionalPoolRecord.drBuilder()\n                                                                                .type(\"A\")\n                                                                                .ttl(0)\n                                                                                .noResponseRecord(true)\n                                                                                .rdata(\"No Data Response\").build()).build())\n                           .add(DirectionalPoolRecordDetail.builder()\n                                                       .zoneName(\"geo.jclouds.org.\")\n                                                       .name(\"www.geo.jclouds.org.\")\n                                                       .id(\"A000000000000004\")\n                                                       .geolocationGroup(create(\"C000000000000003\", \"alazona\"))\n                                                       .record(DirectionalPoolRecord.drBuilder()\n                                                                                .type(\"A\")\n                                                                                .ttl(86400) // default\n                                                                                .noResponseRecord(false)\n                                                                                .rdata(\"1.1.1.1\").build()).build())\n                           .build());\n   }\n\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/parse/GetDirectionalPoolsByZoneResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.parse;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.ultradns.ws.domain.DirectionalPool;\nimport org.jclouds.ultradns.ws.domain.DirectionalPool.TieBreak;\nimport org.jclouds.ultradns.ws.domain.DirectionalPool.Type;\nimport org.jclouds.ultradns.ws.xml.DirectionalPoolListHandler;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableList;\n\n@Test(testName = \"GetDirectionalPoolsByZoneResponseTest\")\npublic class GetDirectionalPoolsByZoneResponseTest extends BaseHandlerTest {\n\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/directionalpools.xml\");\n\n      FluentIterable<DirectionalPool> expected = expected();\n\n      DirectionalPoolListHandler handler = injector.getInstance(DirectionalPoolListHandler.class);\n      FluentIterable<DirectionalPool> result = factory.create(handler).parse(is);\n\n      assertEquals(result.toSet().toString(), expected.toSet().toString());\n   }\n\n   public FluentIterable<DirectionalPool> expected() {\n      return FluentIterable.from(ImmutableList.<DirectionalPool> builder()\n                           .add(DirectionalPool.builder()\n                                               .zoneId(\"0000000000000001\")\n                                               .id(\"000000000000000A\")\n                                               .dname(\"mixy.jclouds.org.\")\n                                               .type(Type.MIXED)\n                                               .tieBreak(TieBreak.GEOLOCATION)\n                                               .name(\"mixy\").build())\n                           .add(DirectionalPool.builder()\n                                               .zoneId(\"0000000000000002\")\n                                               .id(\"000000000000000B\")\n                                               .dname(\"geo.jclouds.org.\").build()).build());\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/parse/GetGeneralPropertiesForZoneResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.parse;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.ultradns.ws.domain.ZoneProperties;\nimport org.jclouds.ultradns.ws.xml.ZonePropertiesHandler;\nimport org.testng.annotations.Test;\n\n@Test(testName = \"GetGeneralPropertiesForZoneResponseTest\")\npublic class GetGeneralPropertiesForZoneResponseTest extends BaseHandlerTest {\n\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/zoneproperties.xml\");\n\n      ZoneProperties expected = expected();\n\n      ZonePropertiesHandler handler = injector.getInstance(ZonePropertiesHandler.class);\n      ZoneProperties result = factory.create(handler).parse(is);\n\n      assertEquals(result.toString(), expected.toString());\n   }\n\n   public ZoneProperties expected() {\n      return ZoneProperties.builder()\n                           .name(\"jclouds.org.\")\n                           .typeCode(1)\n                           .resourceRecordCount(17)\n                           .modified(new SimpleDateFormatDateService().iso8601DateParse(\"2010-09-05 04:04:17.0\"))\n                           .build();\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/parse/GetPoolForPoolHostNameResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.parse;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.ultradns.ws.xml.AttributeHandler;\nimport org.testng.annotations.Test;\n\n@Test(testName = \"GetPoolForPoolHostNameResponseTest\")\npublic class GetPoolForPoolHostNameResponseTest extends BaseHandlerTest {\n\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/tcpool_name.xml\");\n      AttributeHandler.PoolName handler = injector.getInstance(AttributeHandler.PoolName.class);\n      assertEquals(factory.create(handler).parse(is), \"foo\");\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/parse/GetPoolRecordSpecResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.parse;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.ultradns.ws.domain.PoolRecordSpec;\nimport org.jclouds.ultradns.ws.xml.PoolRecordSpecHandler;\nimport org.testng.annotations.Test;\n\n@Test(testName = \"GetPoolRecordSpecResponseTest\")\npublic class GetPoolRecordSpecResponseTest extends BaseHandlerTest {\n\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/poolrecordspec.xml\");\n\n      PoolRecordSpec expected = expected();\n\n      PoolRecordSpecHandler handler = injector.getInstance(PoolRecordSpecHandler.class);\n      PoolRecordSpec result = factory.create(handler).parse(is);\n\n      assertEquals(result, expected);\n      assertEquals(result.hashCode(), expected.hashCode());\n      assertEquals(result.toString(), expected.toString());\n   }\n\n   public PoolRecordSpec expected() {\n      return PoolRecordSpec.builder()\n                           .description(\"foo\")\n                           .state(\"Normal-NoTest\")\n                           .probingEnabled(false)\n                           .allFailEnabled(false)\n                           .weight(2)\n                           .failOverDelay(0)\n                           .threshold(1)\n                           .ttl(120).build();\n   }\n\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/parse/GetRRLoadBalancingPoolsByZoneResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.parse;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.ultradns.ws.domain.RoundRobinPool;\nimport org.jclouds.ultradns.ws.xml.RoundRobinPoolListHandler;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableList;\n\n@Test(testName = \"GetRRLoadBalancingPoolsByZoneResponseTest\")\npublic class GetRRLoadBalancingPoolsByZoneResponseTest extends BaseHandlerTest {\n\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/rrpools.xml\");\n\n      FluentIterable<RoundRobinPool> expected = expected();\n\n      RoundRobinPoolListHandler handler = injector.getInstance(RoundRobinPoolListHandler.class);\n      FluentIterable<RoundRobinPool> result = factory.create(handler).parse(is);\n\n      assertEquals(result.toSet().toString(), expected.toSet().toString());\n   }\n\n   public FluentIterable<RoundRobinPool> expected() {\n      return FluentIterable.from(ImmutableList.<RoundRobinPool> builder()\n                           .add(RoundRobinPool.builder()\n                                              .zoneId(\"0000000000000001\")\n                                              .id(\"000000000000002\")\n                                              .name(\"uswest1\")\n                                              .dname(\"app-uswest1.jclouds.org.\").build())\n                           .add(RoundRobinPool.builder()\n                                              .zoneId(\"0000000000000001\")\n                                              .id(\"000000000000003\")\n                                              .name(\"uswest2\")\n                                              .dname(\"app-uswest2.jclouds.org.\").build())\n                           .add(RoundRobinPool.builder()\n                                              .zoneId(\"0000000000000001\")\n                                              .id(\"000000000000004\")\n                                              .name(\"euwest\")\n                                              .dname(\"app-euwest.jclouds.org.\").build()).build());\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/parse/GetResourceRecordsOfDNameByTypeResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.parse;\n\nimport static org.jclouds.ultradns.ws.domain.ResourceRecord.rrBuilder;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.ultradns.ws.domain.ResourceRecordDetail;\nimport org.jclouds.ultradns.ws.xml.ResourceRecordListHandler;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableList;\n\n@Test(testName = \"GetResourceRecordsOfDNameByTypeResponseTest\")\npublic class GetResourceRecordsOfDNameByTypeResponseTest extends BaseHandlerTest {\n   SimpleDateFormatDateService dateService = new SimpleDateFormatDateService();\n\n   @Test\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/records_by_name_and_type.xml\");\n\n      FluentIterable<ResourceRecordDetail> expected = expected();\n\n      ResourceRecordListHandler handler = injector.getInstance(ResourceRecordListHandler.class);\n      FluentIterable<ResourceRecordDetail> result = factory.create(handler).parse(is);\n\n      assertEquals(result.toList().toString(), expected.toList().toString());\n   }\n\n   public FluentIterable<ResourceRecordDetail> expected() {\n      ResourceRecordDetail record = ResourceRecordDetail.builder()\n            .zoneId(\"03053D8E57C7A22A\")\n            .guid(\"04053D8E57C7A22F\")\n            .zoneName(\"adrianc.rr.ultradnstest.jclouds.org.\")\n            .created(dateService.iso8601DateParse(\"2013-02-22T08:22:48.000Z\"))\n            .modified(dateService.iso8601DateParse(\"2013-02-22T08:22:49.000Z\"))\n            .record(rrBuilder().name(\"adrianc.rr.ultradnstest.jclouds.org.\")\n                               .type(6)\n                               .ttl(86400)\n                               .infoValue(\"pdns75.ultradns.com.\")\n                               .infoValue(\"adrianc.netflix.com.\")\n                               .infoValue(\"2013022200\")\n                               .infoValue(\"86400\")\n                               .infoValue(\"86400\")\n                               .infoValue(\"86400\")\n                               .infoValue(\"86400\").build()).build();\n      return FluentIterable.from(ImmutableList.of(record));\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/parse/GetResourceRecordsOfResourceRecordResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.parse;\n\nimport static org.jclouds.ultradns.ws.domain.ResourceRecord.rrBuilder;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.date.internal.SimpleDateFormatDateService;\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.ultradns.ws.domain.ResourceRecordDetail;\nimport org.jclouds.ultradns.ws.domain.ResourceRecordDetail.Builder;\nimport org.jclouds.ultradns.ws.xml.ResourceRecordListHandler;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableList;\n\n@Test(testName = \"GetResourceRecordsOfResourceRecordResponseTest\")\npublic class GetResourceRecordsOfResourceRecordResponseTest extends BaseHandlerTest {\n   SimpleDateFormatDateService dateService = new SimpleDateFormatDateService();\n\n   @Test\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/records.xml\");\n\n      FluentIterable<ResourceRecordDetail> expected = expected();\n\n      ResourceRecordListHandler handler = injector.getInstance(ResourceRecordListHandler.class);\n      FluentIterable<ResourceRecordDetail> result = factory.create(handler).parse(is);\n\n      assertEquals(result.toList().toString(), expected.toList().toString());\n   }\n\n   public FluentIterable<ResourceRecordDetail> expected() {\n      Builder builder = ResourceRecordDetail.builder().zoneId(\"0000000000000001\").zoneName(\"jclouds.org.\");\n      ImmutableList<ResourceRecordDetail> records = ImmutableList.<ResourceRecordDetail> builder()\n      .add(builder.guid(\"04023A2507B6468F\")\n                  .created(dateService.iso8601DateParse(\"2010-10-02T16:57:16.000Z\"))\n                  .modified(dateService.iso8601DateParse(\"2011-09-27T23:49:21.000Z\"))\n                  .record(rrBuilder().type(1).name(\"www.jclouds.org.\").ttl(3600).rdata(\"1.2.3.4\")).build())\n      .add(builder.guid(\"0B0338C2023F7969\")\n                  .created(dateService.iso8601DateParse(\"2009-10-12T12:02:23.000Z\"))\n                  .modified(dateService.iso8601DateParse(\"2009-10-12T12:02:23.000Z\"))\n                  .record(rrBuilder().type(2).name(\"jclouds.org.\").ttl(86400).rdata(\"pdns2.ultradns.net.\")).build())\n      .add(builder.guid(\"0B0338C2023F7968\")\n                  .created(dateService.iso8601DateParse(\"2009-10-12T12:02:23.000Z\"))\n                  .modified(dateService.iso8601DateParse(\"2009-10-12T12:02:23.000Z\"))\n                  .record(rrBuilder().type(2).name(\"jclouds.org.\").ttl(86400).rdata(\"pdns1.ultradns.net.\")).build())\n      .add(builder.guid(\"0B0338C2023F796B\")\n                  .created(dateService.iso8601DateParse(\"2009-10-12T12:02:23.000Z\"))\n                  .modified(dateService.iso8601DateParse(\"2009-10-12T12:02:23.000Z\"))\n                  .record(rrBuilder().type(2).name(\"jclouds.org.\").ttl(86400).rdata(\"pdns4.ultradns.org.\")).build())\n      .add(builder.guid(\"0B0338C2023F7983\")\n                  .created(dateService.iso8601DateParse(\"2009-10-12T12:02:23.000Z\"))\n                  .modified(dateService.iso8601DateParse(\"2011-09-27T23:49:22.000Z\"))\n                  .record(rrBuilder().type(6).name(\"jclouds.org.\").ttl(3600).rdata(Splitter.on(' ').split(\n                               \"pdns2.ultradns.net. admin.jclouds.org. 2011092701 10800 3600 604800 86400\"))).build())\n      .add(builder.guid(\"0B0338C2023F796E\")\n                  .created(dateService.iso8601DateParse(\"2009-10-12T12:02:23.000Z\"))\n                  .modified(dateService.iso8601DateParse(\"2011-09-27T23:49:22.000Z\"))\n                  .record(rrBuilder().type(1).name(\"jclouds.org.\").ttl(3600).rdata(\"1.2.3.4\")).build())\n      .add(builder.guid(\"0B0338C2023F796C\")\n                  .created(dateService.iso8601DateParse(\"2009-10-12T12:02:23.000Z\"))\n                  .modified(dateService.iso8601DateParse(\"2009-10-12T12:02:23.000Z\"))\n                  .record(rrBuilder().type(2).name(\"jclouds.org.\").ttl(86400).rdata(\"pdns5.ultradns.info.\")).build())\n      .add(builder.guid(\"0B0338C2023F796D\")\n                  .created(dateService.iso8601DateParse(\"2009-10-12T12:02:23.000Z\"))\n                  .modified(dateService.iso8601DateParse(\"2009-10-12T12:02:23.000Z\"))\n                  .record(rrBuilder().type(2).name(\"jclouds.org.\").ttl(86400).rdata(\"pdns6.ultradns.co.uk.\")).build())\n      .add(builder.guid(\"0B0338C2023F796A\")\n                  .created(dateService.iso8601DateParse(\"2009-10-12T12:02:23.000Z\"))\n                  .modified(dateService.iso8601DateParse(\"2009-10-12T12:02:23.000Z\"))\n                  .record(rrBuilder().type(2).name(\"jclouds.org.\").ttl(86400).rdata(\"pdns3.ultradns.org.\")).build())\n      .build();\n      return FluentIterable.from(records);\n   }\n\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/parse/GetStatusForTaskResponseResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.parse;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\nimport java.net.URI;\n\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.ultradns.ws.domain.Task;\nimport org.jclouds.ultradns.ws.domain.Task.StatusCode;\nimport org.jclouds.ultradns.ws.xml.TaskHandler;\nimport org.testng.annotations.Test;\n\n@Test(testName = \"GetStatusForTaskResponseResponseTest\")\npublic class GetStatusForTaskResponseResponseTest extends BaseHandlerTest {\n\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/task.xml\");\n\n      Task expected = expected();\n\n      TaskHandler handler = injector.getInstance(TaskHandler.class);\n      Task result = factory.create(handler).parse(is);\n\n      assertEquals(result.toString(), expected.toString());\n   }\n\n   public Task expected() {\n      return Task.builder()\n                 .guid(\"0b40c7dd-748d-4c49-8506-26f0c7d2ea9c\")\n                 .statusCode(StatusCode.COMPLETE)\n                 .message(\"Processing complete\")\n                 .resultUrl(URI.create(\"http://localhost:8008/users/node01/tasks/0b40c7dd-748d-4c49-8506-26f0c7d2ea9c/result\"))\n                 .build();\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/parse/GetTCLoadBalancingPoolsByZoneResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.parse;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.ultradns.ws.domain.TrafficControllerPool;\nimport org.jclouds.ultradns.ws.xml.TrafficControllerPoolListHandler;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableList;\n\n@Test(testName = \"GetTCLoadBalancingPoolsByZoneResponseTest\")\npublic class GetTCLoadBalancingPoolsByZoneResponseTest extends BaseHandlerTest {\n\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/tcpools.xml\");\n\n      FluentIterable<TrafficControllerPool> expected = expected();\n\n      TrafficControllerPoolListHandler handler = injector.getInstance(TrafficControllerPoolListHandler.class);\n      FluentIterable<TrafficControllerPool> result = factory.create(handler).parse(is);\n\n      assertEquals(result.toSet().toString(), expected.toSet().toString());\n   }\n\n   public FluentIterable<TrafficControllerPool> expected() {\n      return FluentIterable.from(ImmutableList.<TrafficControllerPool> builder()\n                           .add(TrafficControllerPool.builder()\n                                                     .zoneId(\"0000000000000001\")\n                                                     .id(\"000000000000002\")\n                                                     .name(\"us-west-1c\")\n                                                     .dname(\"us-west-1c.discovery.jclouds.org.\")\n                                                     .statusCode(1)\n                                                     .failOverEnabled(true)\n                                                     .probingEnabled(true).build()).build());\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/parse/GetTCPoolRecordsResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.parse;\n\nimport static org.jclouds.ultradns.ws.domain.TrafficControllerPoolRecord.createCNAME;\nimport static org.jclouds.ultradns.ws.domain.TrafficControllerPoolRecordDetail.Status.OK;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.ultradns.ws.domain.TrafficControllerPoolRecordDetail;\nimport org.jclouds.ultradns.ws.xml.TrafficControllerPoolRecordDetailListHandler;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(testName = \"GetTCPoolRecordsResponseTest\")\npublic class GetTCPoolRecordsResponseTest extends BaseHandlerTest {\n\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/tcrecords.xml\");\n\n      FluentIterable<TrafficControllerPoolRecordDetail> expected = expected();\n\n      TrafficControllerPoolRecordDetailListHandler handler = injector.getInstance(TrafficControllerPoolRecordDetailListHandler.class);\n      FluentIterable<TrafficControllerPoolRecordDetail> result = factory.create(handler).parse(is);\n\n      assertEquals(result.toSet().toString(), expected.toSet().toString());\n   }\n\n   public FluentIterable<TrafficControllerPoolRecordDetail> expected() {\n      return FluentIterable.from(ImmutableSet.<TrafficControllerPoolRecordDetail> builder()\n                           .add(TrafficControllerPoolRecordDetail.builder()\n                                                           .id(\"0000000000000001\")\n                                                           .poolId(\"0000000000000001\")\n                                                           .record(createCNAME(\"canary.jclouds.org.\"))\n                                                           .weight(2)\n                                                           .priority(2)\n                                                           .forceAnswer(\"Normal\")\n                                                           .probingEnabled(true)\n                                                           .status(OK)\n                                                           .serving(true)\n                                                           .description(\"canary app\").build())\n                           .add(TrafficControllerPoolRecordDetail.builder()\n                                                           .id(\"0000000000000002\")\n                                                           .poolId(\"0000000000000001\")\n                                                           .record(createCNAME(\"prod.jclouds.org.\"))\n                                                           .weight(98)\n                                                           .priority(1)\n                                                           .forceAnswer(\"Normal\")\n                                                           .probingEnabled(true)\n                                                           .status(OK)\n                                                           .serving(true)\n                                                           .description(\"prod app\").build())\n                           .build());\n   }\n\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/parse/GetZonesOfAccountResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.parse;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.ultradns.ws.domain.Zone;\nimport org.jclouds.ultradns.ws.domain.Zone.DNSSECStatus;\nimport org.jclouds.ultradns.ws.xml.ZoneListHandler;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.FluentIterable;\nimport com.google.common.collect.ImmutableSet;\n\n@Test(testName = \"GetZonesOfAccountResponseTest\")\npublic class GetZonesOfAccountResponseTest extends BaseHandlerTest {\n\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/zones.xml\");\n\n      FluentIterable<Zone> expected = expected();\n\n      ZoneListHandler handler = injector.getInstance(ZoneListHandler.class);\n      FluentIterable<Zone> result = factory.create(handler).parse(is);\n\n      assertEquals(result.toSet().toString(), expected.toSet().toString());\n   }\n\n   public FluentIterable<Zone> expected() {\n      return FluentIterable.from(ImmutableSet.<Zone> builder()\n                           .add(Zone.builder()\n                                    .name(\"jclouds.org.\")\n                                    .typeCode(1)\n                                    .accountId(\"AAAAAAAAAAAAAAAA\")\n                                    .ownerId(\"EEEEEEEEEEEEEEEE\")\n                                    .id(\"0000000000000001\")\n                                    .dnssecStatus(DNSSECStatus.UNSIGNED).build())\n                           .add(Zone.builder()\n                                    .name(\"0.1.2.3.4.5.6.7.ip6.arpa.\")\n                                    .typeCode(1)\n                                    .accountId(\"AAAAAAAAAAAAAAAA\")\n                                    .ownerId(\"EEEEEEEEEEEEEEEE\")\n                                    .id(\"0000000000000002\")\n                                    .dnssecStatus(DNSSECStatus.UNSIGNED).build())\n                           .build());\n   }\n\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/parse/RunTestResponseTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.parse;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.ultradns.ws.xml.ElementTextHandler;\nimport org.testng.annotations.Test;\n\n@Test(testName = \"RunTestResponseTest\")\npublic class RunTestResponseTest extends BaseHandlerTest {\n\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/taskid.xml\");\n\n      ElementTextHandler.Guid handler = injector.getInstance(ElementTextHandler.Guid.class);\n      assertEquals(factory.create(handler).parse(is), \"8d7a1725-4f4a-4b70-affa-f01dcce1526e\");\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/parse/TaskNotFoundTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.parse;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.ultradns.ws.UltraDNSWSError;\nimport org.jclouds.ultradns.ws.xml.UltraWSExceptionHandler;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\n\n@Test(testName = \"TaskNotFoundTest\")\npublic class TaskNotFoundTest extends BaseHandlerTest {\n\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/task_doesnt_exist.xml\");\n\n      UltraDNSWSError expected = expected();\n\n      UltraWSExceptionHandler handler = injector.getInstance(UltraWSExceptionHandler.class);\n      UltraDNSWSError result = factory.create(handler).parse(is);\n\n      assertEquals(result, expected);\n   }\n\n   public UltraDNSWSError expected() {\n      return UltraDNSWSError.fromCodeAndDescription(0, Optional.of(\"Cannot find task with guid AAAAAAAAAAAAAAAA\"));\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/parse/UltraWSExceptionTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.parse;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.InputStream;\n\nimport org.jclouds.http.functions.BaseHandlerTest;\nimport org.jclouds.ultradns.ws.UltraDNSWSError;\nimport org.jclouds.ultradns.ws.xml.UltraWSExceptionHandler;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Optional;\n\n@Test(testName = \"UltraWSExceptionTest\")\npublic class UltraWSExceptionTest extends BaseHandlerTest {\n\n   public void test() {\n      InputStream is = getClass().getResourceAsStream(\"/zone_doesnt_exist.xml\");\n\n      UltraDNSWSError expected = expected();\n\n      UltraWSExceptionHandler handler = injector.getInstance(UltraWSExceptionHandler.class);\n      UltraDNSWSError result = factory.create(handler).parse(is);\n\n      assertEquals(result, expected);\n   }\n\n   public UltraDNSWSError expected() {\n      return UltraDNSWSError.fromCodeAndDescription(1801, Optional.of(\"Zone does not exist in the system.\"));\n   }\n\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/predicates/DirectionalPoolPredicatesTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.predicates;\n\nimport static org.jclouds.ultradns.ws.domain.IdAndName.create;\nimport static org.jclouds.ultradns.ws.predicates.DirectionalPoolPredicates.idEqualTo;\nimport static org.jclouds.ultradns.ws.predicates.DirectionalPoolPredicates.recordIdEqualTo;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.ultradns.ws.domain.DirectionalPool;\nimport org.jclouds.ultradns.ws.domain.DirectionalPool.TieBreak;\nimport org.jclouds.ultradns.ws.domain.DirectionalPool.Type;\nimport org.jclouds.ultradns.ws.domain.DirectionalPoolRecord;\nimport org.jclouds.ultradns.ws.domain.DirectionalPoolRecordDetail;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"DirectionalPoolPredicatesTest\")\npublic class DirectionalPoolPredicatesTest {\n   DirectionalPool pool = DirectionalPool.builder()\n                                         .zoneId(\"0000000000000001\")\n                                         .id(\"000000000000000A\")\n                                         .dname(\"mixy.jclouds.org.\")\n                                         .type(Type.MIXED)\n                                         .tieBreak(TieBreak.GEOLOCATION)\n                                         .name(\"mixy\").build();\n\n   @Test\n   public void testIdEqualToWhenEqual() {\n      assertTrue(idEqualTo(\"000000000000000A\").apply(pool));\n   }\n\n   @Test\n   public void testIdEqualToWhenNotEqual() {\n      assertFalse(idEqualTo(\"000000000000000B\").apply(pool));\n   }\n\n   DirectionalPoolRecordDetail record = DirectionalPoolRecordDetail.builder()\n      .zoneName(\"geo.jclouds.org.\")\n      .name(\"www.geo.jclouds.org.\")\n      .id(\"A000000000000001\")\n      .geolocationGroup(create(\"C000000000000001\", \"southamerica\"))\n      .record(DirectionalPoolRecord.drBuilder()\n                               .type(\"CNAME\")\n                               .ttl(300)\n                               .noResponseRecord(false)\n                               .rdata(\"southamerica.geo.jclouds.org.\").build()).build();\n   @Test\n   public void testRecordIdEqualToWhenEqual() {\n      assertTrue(recordIdEqualTo(\"A000000000000001\").apply(record));\n   }\n\n   @Test\n   public void testRecordIdEqualToWhenNotEqual() {\n      assertFalse(recordIdEqualTo(\"A000000000000002\").apply(record));\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/predicates/TrafficControllerPoolPredicatesTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.predicates;\n\nimport static org.jclouds.ultradns.ws.domain.TrafficControllerPoolRecord.createCNAME;\nimport static org.jclouds.ultradns.ws.predicates.TrafficControllerPoolPredicates.idEqualTo;\nimport static org.jclouds.ultradns.ws.predicates.TrafficControllerPoolPredicates.recordIdEqualTo;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.ultradns.ws.domain.TrafficControllerPool;\nimport org.jclouds.ultradns.ws.domain.TrafficControllerPoolRecordDetail;\nimport org.jclouds.ultradns.ws.domain.TrafficControllerPoolRecordDetail.Status;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"TrafficControllerPoolPredicatesTest\")\npublic class TrafficControllerPoolPredicatesTest {\n   TrafficControllerPool pool = TrafficControllerPool.builder()\n                                                     .zoneId(\"0000000000000001\")\n                                                     .id(\"000000000000002\")\n                                                     .name(\"us-west-1c.discovery.jclouds.org.\")\n                                                     .dname(\"us-west-1c.discovery.jclouds.org.\")\n                                                     .statusCode(1)\n                                                     .failOverEnabled(true)\n                                                     .probingEnabled(true).build();\n\n   @Test\n   public void testIdEqualToWhenEqual() {\n      assertTrue(idEqualTo(\"000000000000002\").apply(pool));\n   }\n\n   @Test\n   public void testIdEqualToWhenNotEqual() {\n      assertFalse(idEqualTo(\"000000000000003\").apply(pool));\n   }\n\n   TrafficControllerPoolRecordDetail record = TrafficControllerPoolRecordDetail.builder()\n                                                                   .id(\"0000000000000001\")\n                                                                   .poolId(\"0000000000000001\")\n                                                                   .record(createCNAME(\"canary.jclouds.org.\"))\n                                                                   .weight(2)\n                                                                   .priority(2)\n                                                                   .forceAnswer(\"Normal\")\n                                                                   .probingEnabled(true)\n                                                                   .status(Status.OK)\n                                                                   .serving(true)\n                                                                   .description(\"canary app\").build();\n\n   @Test\n   public void testRecordIdEqualToWhenEqual() {\n      assertTrue(recordIdEqualTo(\"0000000000000001\").apply(record));\n   }\n\n   @Test\n   public void testRecordIdEqualToWhenNotEqual() {\n      assertFalse(recordIdEqualTo(\"0000000000000002\").apply(record));\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/java/org/jclouds/ultradns/ws/predicates/ZonePredicatesTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.ultradns.ws.predicates;\n\nimport static org.jclouds.ultradns.ws.predicates.ZonePredicates.typeEqualTo;\nimport static org.testng.Assert.assertFalse;\nimport static org.testng.Assert.assertTrue;\n\nimport org.jclouds.ultradns.ws.domain.Zone;\nimport org.jclouds.ultradns.ws.domain.Zone.DNSSECStatus;\nimport org.jclouds.ultradns.ws.domain.Zone.Type;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ZonePredicatesTest\")\npublic class ZonePredicatesTest {\n   Zone zone = Zone.builder()\n                   .name(\"jclouds.org.\")\n                   .typeCode(1)\n                   .accountId(\"AAAAAAAAAAAAAAAA\")\n                   .ownerId(\"EEEEEEEEEEEEEEEE\")\n                   .id(\"0000000000000001\")\n                   .dnssecStatus(DNSSECStatus.UNSIGNED).build();\n\n   @Test\n   public void testTypeEqualsWhenEqual() {\n      assertTrue(typeEqualTo(Type.PRIMARY).apply(zone));\n   }\n\n   @Test\n   public void testTypeEqualsWhenNotEqual() {\n      assertFalse(typeEqualTo(Type.SECONDARY).apply(zone));\n   }\n}\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/account.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n\t<soap:Body>\n\t\t<ns1:getAccountsListOfUserResponse\n\t\t\txmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\">\n\t\t\t<AccountsList xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">\n\t\t\t\t<ns2:AccountDetailsData accountID=\"AAAAAAAAAAAAAAAA\"\n\t\t\t\t\taccountName=\"jclouds\" />\n\t\t\t</AccountsList>\n\t\t</ns1:getAccountsListOfUserResponse>\n\t</soap:Body>\n</soap:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/account_doesnt_exist.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n   <soap:Body>\n      <soap:Fault>\n         <faultcode>soap:Server</faultcode>\n         <faultstring>Fault occurred while processing.</faultstring>\n         <detail>\n            <ns1:UltraWSException xmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\">\n               <errorCode xsi:type=\"xs:int\" xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">2401</errorCode>\n               <errorDescription xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">Account not found in the system. ID: AAAAAAAAAAAAAAAA</errorDescription>\n            </ns1:UltraWSException>\n         </detail>\n      </soap:Fault>\n   </soap:Body>\n</soap:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/accountlevelgroup_records.xml",
    "content": "<?xml version=\"1.0\"?>\n<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n\t<soap:Body>\n\t\t<ns1:getDirectionalDNSRecordsForAcctLvlGroupResponse\n\t\t\txmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\">\n\t\t\t<DirectionalDNSRecordDetailList\n\t\t\t\txmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">\n\t\t\t\t<ns2:DirectionalDNSRecordDetail\n\t\t\t\t\tDirPoolRecordId=\"06023D94130C8F89\" ZoneName=\"netflix.com.\"\n\t\t\t\t\tDName=\"ccs-int-eu.netflix.com.\">\n\t\t\t\t\t<ns2:DirectionalDNSRecord recordType=\"CNAME\"\n\t\t\t\t\t\tTTL=\"3600\" noResponseRecord=\"false\">\n\t\t\t\t\t\t<ns2:InfoValues\n\t\t\t\t\t\t\tInfo1Value=\"ccs-int-frontend-1181536117.eu-west-1.elb.amazonaws.com.\" />\n\t\t\t\t\t</ns2:DirectionalDNSRecord>\n\t\t\t\t</ns2:DirectionalDNSRecordDetail>\n\t\t\t\t<ns2:DirectionalDNSRecordDetail\n\t\t\t\t\tDirPoolRecordId=\"06023D94130C8F61\" ZoneName=\"netflix.com.\" DName=\"ccs-int.netflix.com.\">\n\t\t\t\t\t<ns2:DirectionalDNSRecord recordType=\"CNAME\"\n\t\t\t\t\t\tTTL=\"3600\" noResponseRecord=\"false\">\n\t\t\t\t\t\t<ns2:InfoValues\n\t\t\t\t\t\t\tInfo1Value=\"ccs-int-frontend-1181536117.eu-west-1.elb.amazonaws.com.\" />\n\t\t\t\t\t</ns2:DirectionalDNSRecord>\n\t\t\t\t</ns2:DirectionalDNSRecordDetail>\n\t\t\t\t<ns2:DirectionalDNSRecordDetail\n\t\t\t\t\tDirPoolRecordId=\"06023D161000DE02\" ZoneName=\"netflix.com.\"\n\t\t\t\t\tDName=\"nrdpv6.nccp.netflix.com.\">\n\t\t\t\t\t<ns2:DirectionalDNSRecord recordType=\"CNAME\"\n\t\t\t\t\t\tTTL=\"3600\" noResponseRecord=\"false\">\n\t\t\t\t\t\t<ns2:InfoValues\n\t\t\t\t\t\t\tInfo1Value=\"dualstack.nccp-wildcard-nccp-netflix-com-1840524669.eu-west-1.elb.amazonaws.com.\" />\n\t\t\t\t\t</ns2:DirectionalDNSRecord>\n\t\t\t\t</ns2:DirectionalDNSRecordDetail>\n\t\t\t</DirectionalDNSRecordDetailList>\n\t\t</ns1:getDirectionalDNSRecordsForAcctLvlGroupResponse>\n\t</soap:Body>\n</soap:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/accountlevelgroups.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n\t<soap:Body>\n\t\t<ns1:getAccountLevelDirectionalGroupsResponse\n\t\t\txmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\">\n\t\t\t<GroupsList xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">\n\t\t\t\t<ns2:AccountLevelGroups GroupId=\"000000000000000A\"\n\t\t\t\t\tGroupName=\"ASIA\" RecordsCount=\"0\" GroupType=\"GEOLOCATION\" />\n\t\t\t\t<ns2:AccountLevelGroups GroupId=\"000000000000000B\"\n\t\t\t\t\tGroupName=\"EU\" RecordsCount=\"3\" GroupType=\"GEOLOCATION\" />\n\t\t\t\t<ns2:AccountLevelGroups GroupId=\"000000000000000C\"\n\t\t\t\t\tGroupName=\"LATAM\" RecordsCount=\"1\" GroupType=\"GEOLOCATION\" />\n\t\t\t</GroupsList>\n\t\t</ns1:getAccountLevelDirectionalGroupsResponse>\n\t</soap:Body>\n</soap:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/clear_task.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v01=\"http://webservice.api.ultra.neustar.com/v01/\"><soapenv:Header><wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:UsernameToken><wsse:Username>identity</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">credential</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body><v01:clearTask><id><guid>0b40c7dd-748d-4c49-8506-26f0c7d2ea9c</guid></id></v01:clearTask></soapenv:Body></soapenv:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/create_directionalpool.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v01=\"http://webservice.api.ultra.neustar.com/v01/\"><soapenv:Header><wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:UsernameToken><wsse:Username>identity</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">credential</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body><v01:addDirectionalPool><transactionID /><AddDirectionalPoolData dirPoolType=\"GEOLOCATION\" poolRecordType=\"A\" zoneName=\"jclouds.org.\" hostName=\"www.jclouds.org.\" description=\"foo\"/></v01:addDirectionalPool></soapenv:Body></soapenv:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/create_directionalrecord.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v01=\"http://webservice.api.ultra.neustar.com/v01/\"><soapenv:Header><wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:UsernameToken><wsse:Username>identity</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">credential</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body><v01:addDirectionalPoolRecord><transactionID /><AddDirectionalRecordData directionalPoolId=\"06063DC355055E68\" createAllNonConfiguredGrp=\"true\"><DirectionalRecordConfiguration recordType=\"A\" TTL=\"300\" noResponseRecord=\"false\" ><InfoValues Info1Value=\"1.1.0.1\" /></DirectionalRecordConfiguration></AddDirectionalRecordData></v01:addDirectionalPoolRecord></soapenv:Body></soapenv:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/create_directionalrecord_existinggroup.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v01=\"http://webservice.api.ultra.neustar.com/v01/\"><soapenv:Header><wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:UsernameToken><wsse:Username>identity</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">credential</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body><v01:addDirectionalPoolRecord><transactionID /><AddDirectionalRecordData directionalPoolId=\"06063DC355055E68\"><DirectionalRecordConfiguration recordType=\"A\" TTL=\"300\" noResponseRecord=\"false\" ><InfoValues Info1Value=\"1.1.0.1\" /></DirectionalRecordConfiguration><GeolocationGroupData><GroupData groupingType=\"ASSIGN_EXISTING_GROUP\" assignExistingGroupId=\"AAABBBCCCDDDEEE\" /></GeolocationGroupData></AddDirectionalRecordData></v01:addDirectionalPoolRecord></soapenv:Body></soapenv:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/create_directionalrecord_newgroup.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v01=\"http://webservice.api.ultra.neustar.com/v01/\"><soapenv:Header><wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:UsernameToken><wsse:Username>identity</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">credential</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body><v01:addDirectionalPoolRecord><transactionID /><AddDirectionalRecordData directionalPoolId=\"06063DC355055E68\"><DirectionalRecordConfiguration recordType=\"A\" TTL=\"300\" noResponseRecord=\"false\" ><InfoValues Info1Value=\"1.1.0.1\" /></DirectionalRecordConfiguration><GeolocationGroupData><GroupData groupingType=\"DEFINE_NEW_GROUP\" /><GeolocationGroupDetails groupName=\"Mexas\" description=\"Clients we classify as being in US\" ><GeolocationGroupDefinitionData regionName=\"United States (US)\" territoryNames=\"Maryland;Texas\" /></GeolocationGroupDetails></GeolocationGroupData></AddDirectionalRecordData></v01:addDirectionalPoolRecord></soapenv:Body></soapenv:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/create_rr.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v01=\"http://webservice.api.ultra.neustar.com/v01/\"><soapenv:Header><wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:UsernameToken><wsse:Username>identity</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">credential</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body><v01:createResourceRecord><transactionID /><resourceRecord ZoneName=\"jclouds.org.\" Type=\"15\" DName=\"mail.jclouds.org.\" TTL=\"1800\"><InfoValues Info1Value=\"10\" Info2Value=\"maileast.jclouds.org.\" /></resourceRecord></v01:createResourceRecord></soapenv:Body></soapenv:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/create_rrpool_a.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v01=\"http://webservice.api.ultra.neustar.com/v01/\"><soapenv:Header><wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:UsernameToken><wsse:Username>identity</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">credential</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body><v01:addRRLBPool><transactionID /><zoneName>jclouds.org.</zoneName><hostName>foo</hostName><description>www.jclouds.org.</description><poolRecordType>1</poolRecordType><rrGUID /></v01:addRRLBPool></soapenv:Body></soapenv:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/create_rrpool_aaaa.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v01=\"http://webservice.api.ultra.neustar.com/v01/\"><soapenv:Header><wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:UsernameToken><wsse:Username>identity</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">credential</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body><v01:addRRLBPool><transactionID /><zoneName>jclouds.org.</zoneName><hostName>foo</hostName><description>www.jclouds.org.</description><poolRecordType>28</poolRecordType><rrGUID /></v01:addRRLBPool></soapenv:Body></soapenv:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/create_tcpool.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v01=\"http://webservice.api.ultra.neustar.com/v01/\"><soapenv:Header><wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:UsernameToken><wsse:Username>identity</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">credential</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body><v01:addTCLBPool><transactionID /><zoneName>jclouds.org.</zoneName><hostName>www.jclouds.org.</hostName><description>foo</description><poolRecordType>1</poolRecordType><failOver>Enabled</failOver><probing>Enabled</probing><maxActive>0</maxActive><rrGUID /></v01:addTCLBPool></soapenv:Body></soapenv:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/create_tcrecord.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v01=\"http://webservice.api.ultra.neustar.com/v01/\"><soapenv:Header><wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:UsernameToken><wsse:Username>identity</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">credential</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body><v01:addPoolRecord><transactionID /><poolID>04053D8E57C7931F</poolID><pointsTo>1.2.3.4</pointsTo><priority /><failOverDelay /><ttl>300</ttl><weight /><mode /><threshold /></v01:addPoolRecord></soapenv:Body></soapenv:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/create_tcrecord_weight.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v01=\"http://webservice.api.ultra.neustar.com/v01/\"><soapenv:Header><wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:UsernameToken><wsse:Username>identity</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">credential</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body><v01:addPoolRecord><transactionID /><poolID>04053D8E57C7931F</poolID><pointsTo>1.2.3.4</pointsTo><priority /><failOverDelay /><ttl>300</ttl><weight>0</weight><mode /><threshold /></v01:addPoolRecord></soapenv:Body></soapenv:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/create_zone.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v01=\"http://webservice.api.ultra.neustar.com/v01/\"><soapenv:Header><wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:UsernameToken><wsse:Username>identity</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">credential</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body><v01:createPrimaryZone><transactionID /><accountId>AAAAAAAAAAAAAAAA</accountId><zoneName>jclouds.org.</zoneName><forceImport>false</forceImport></v01:createPrimaryZone></soapenv:Body></soapenv:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/delete_directionalrecord.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v01=\"http://webservice.api.ultra.neustar.com/v01/\"><soapenv:Header><wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:UsernameToken><wsse:Username>identity</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">credential</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body><v01:deleteDirectionalPoolRecord><transactionID /><dirPoolRecordId>04053D8E57C7931F</dirPoolRecordId></v01:deleteDirectionalPoolRecord></soapenv:Body></soapenv:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/delete_lbpool.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v01=\"http://webservice.api.ultra.neustar.com/v01/\"><soapenv:Header><wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:UsernameToken><wsse:Username>identity</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">credential</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body><v01:deleteLBPool><transactionID /><lbPoolID>04053D8E57C7931F</lbPoolID><DeleteAll>Yes</DeleteAll><retainRecordId /></v01:deleteLBPool></soapenv:Body></soapenv:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/delete_rr.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v01=\"http://webservice.api.ultra.neustar.com/v01/\"><soapenv:Header><wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:UsernameToken><wsse:Username>identity</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">credential</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body><v01:deleteZone><transactionID /><zoneName>04053D8E57C7931F</zoneName></v01:deleteZone></soapenv:Body></soapenv:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/delete_tcrecord.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v01=\"http://webservice.api.ultra.neustar.com/v01/\"><soapenv:Header><wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:UsernameToken><wsse:Username>identity</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">credential</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body><v01:deletePoolRecord><transactionID /><poolRecordID>04053D8E57C7931F</poolRecordID><parentPoolId /><childPoolId /></v01:deletePoolRecord></soapenv:Body></soapenv:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/delete_zone.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v01=\"http://webservice.api.ultra.neustar.com/v01/\"><soapenv:Header><wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:UsernameToken><wsse:Username>identity</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">credential</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body><v01:deleteZone><transactionID /><zoneName>jclouds.org.</zoneName></v01:deleteZone></soapenv:Body></soapenv:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/directionalgroup.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n\t<soap:Body>\n\t\t<ns1:getDirectionalDNSGroupDetailsResponse\n\t\t\txmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\">\n\t\t\t<DirectionalDNSGroupDetail\n\t\t\t\txmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\" GroupName=\"NON-EU\">\n\t\t\t\t<ns2:DirectionalDNSRegion>\n\t\t\t\t\t<ns2:RegionForNewGroups RegionName=\"Anonymous Proxy (A1)\"\n\t\t\t\t\t\tTerritoryName=\"Anonymous Proxy\" />\n\t\t\t\t\t<ns2:RegionForNewGroups RegionName=\"Mexico\"\n\t\t\t\t\t\tTerritoryName=\"Mexico\" />\n\t\t\t\t\t<ns2:RegionForNewGroups RegionName=\"Antarctica\"\n\t\t\t\t\t\tTerritoryName=\"Bouvet Island;French Southern Territories;Antarctica\" />\n\t\t\t\t</ns2:DirectionalDNSRegion>\n\t\t\t</DirectionalDNSGroupDetail>\n\t\t</ns1:getDirectionalDNSGroupDetailsResponse>\n\t</soap:Body>\n</soap:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/directionalgroup_doesnt_exist.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n\t<soap:Body>\n\t\t<soap:Fault>\n\t\t\t<faultcode>soap:Server</faultcode>\n\t\t\t<faultstring>Fault occurred while processing.</faultstring>\n\t\t\t<detail>\n\t\t\t\t<ns1:UltraWSException xmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\">\n\t\t\t\t\t<errorCode xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\"\n\t\t\t\t\t\txmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\t\t\t\t\t\txsi:type=\"xs:int\">4003</errorCode>\n\t\t\t\t\t<errorDescription xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">Group does not exist.</errorDescription>\n\t\t\t\t</ns1:UltraWSException>\n\t\t\t</detail>\n\t\t</soap:Fault>\n\t</soap:Body>\n</soap:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/directionalgroup_names.xml",
    "content": "<?xml version=\"1.0\"?>\n<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n\t<soap:Body>\n\t\t<ns1:getAvailableGroupsResponse\n\t\t\txmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\">\n\t\t\t<DirectionalDNSAvailableGroups\n\t\t\t\txmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">\n\t\t\t\t<item>EU-foo.jclouds.org.</item>\n\t\t\t\t<item>non-foo.jclouds.org.</item>\n\t\t\t</DirectionalDNSAvailableGroups>\n\t\t</ns1:getAvailableGroupsResponse>\n\t</soap:Body>\n</soap:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/directionalgroup_overlap.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n\t<soap:Body>\n\t\t<soap:Fault>\n\t\t\t<faultcode>soap:Server</faultcode>\n\t\t\t<faultstring>Fault occurred while processing.</faultstring>\n\t\t\t<detail>\n\t\t\t\t<ns1:UltraWSException xmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\">\n\t\t\t\t\t<errorCode xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\"\n\t\t\t\t\t\txmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\t\t\t\t\t\txsi:type=\"xs:int\">7021</errorCode>\n\t\t\t\t\t<errorDescription xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">Geolocation/Source IP overlap(s) found: Region: Utah (Group: US )</errorDescription>\n\t\t\t\t</ns1:UltraWSException>\n\t\t\t</detail>\n\t\t</soap:Fault>\n\t</soap:Body>\n</soap:Envelope>\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/directionalpool_already_exists.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n\t<soap:Body>\n\t\t<soap:Fault>\n\t\t\t<faultcode>soap:Server</faultcode>\n\t\t\t<faultstring>\n\t\t\t\tFault occurred while processing.\n\t\t\t</faultstring>\n\t\t\t<detail>\n\t\t\t\t<ns1:UltraWSException xmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\">\n\t\t\t\t\t<errorCode xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\"\n\t\t\t\t\t\txmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\t\t\t\t\t\txsi:type=\"xs:int\">2912</errorCode>\n\t\t\t\t\t<errorDescription xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">Pool already created for this host name : www.jclouds.org.</errorDescription>\n\t\t\t\t</ns1:UltraWSException>\n\t\t\t</detail>\n\t\t</soap:Fault>\n\t</soap:Body>\n</soap:Envelope>\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/directionalpool_created.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n\t<soap:Body>\n\t\t<ns1:addDirectionalPoolResponse\n\t\t\txmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\">\n\t\t\t<DirPoolID xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">06063DC355055E68</DirPoolID>\n\t\t</ns1:addDirectionalPoolResponse>\n\t</soap:Body>\n</soap:Envelope>\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/directionalpool_deleted.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n\t<soap:Body>\n\t\t<ns1:deleteDirectionalPoolResponse\n\t\t\txmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\">\n\t\t\t<result xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">Successful</result>\n\t\t</ns1:deleteDirectionalPoolResponse>\n\t</soap:Body>\n</soap:Envelope>\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/directionalpool_doesnt_exist.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n\t<soap:Body>\n\t\t<soap:Fault>\n\t\t\t<faultcode>soap:Server</faultcode>\n\t\t\t<faultstring>Fault occurred while processing.</faultstring>\n\t\t\t<detail>\n\t\t\t\t<ns1:UltraWSException xmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\">\n\t\t\t\t\t<errorCode xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\"\n\t\t\t\t\t\txmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\t\t\t\t\t\txsi:type=\"xs:int\">2142</errorCode>\n\t\t\t\t\t<errorDescription xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">No Pool or Multiple pools of same type exists for the PoolName : foo.jclouds.org.</errorDescription>\n\t\t\t\t</ns1:UltraWSException>\n\t\t\t</detail>\n\t\t</soap:Fault>\n\t</soap:Body>\n</soap:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/directionalpools.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n\t<soap:Body>\n\t\t<ns1:getDirectionalPoolsOfZoneResponse\n\t\t\txmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\">\n\t\t\t<DirectionalPoolList xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">\n\t\t\t\t<ns2:DirectionalPoolData dirpoolid=\"000000000000000A\"\n\t\t\t\t\tZoneid=\"0000000000000001\" Pooldname=\"mixy.jclouds.org.\"\n\t\t\t\t\tDirPoolType=\"MIXED\" TieBreak=\"GEOLOCATION\" Description=\"mixy\" />\n\t\t\t\t<ns2:DirectionalPoolData dirpoolid=\"000000000000000B\"\n\t\t\t\t\tZoneid=\"0000000000000002\" Pooldname=\"geo.jclouds.org.\" />\n\t\t\t</DirectionalPoolList>\n\t\t</ns1:getDirectionalPoolsOfZoneResponse>\n\t</soap:Body>\n</soap:Envelope>\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/directionalrecord_already_exists.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n\t<soap:Body>\n\t\t<soap:Fault>\n\t\t\t<faultcode>soap:Server</faultcode>\n\t\t\t<faultstring>Fault occurred while processing.</faultstring>\n\t\t\t<detail>\n\t\t\t\t<ns1:UltraWSException xmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\">\n\t\t\t\t\t<errorCode xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\"\n\t\t\t\t\t\txmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\t\t\t\t\t\txsi:type=\"xs:int\">4009</errorCode>\n\t\t\t\t\t<errorDescription xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">Resource Record already exists.</errorDescription>\n\t\t\t\t</ns1:UltraWSException>\n\t\t\t</detail>\n\t\t</soap:Fault>\n\t</soap:Body>\n</soap:Envelope>\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/directionalrecord_created.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n\t<soap:Body>\n\t\t<ns1:addDirectionalPoolRecordResponse\n\t\t\txmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\">\n\t\t\t<DirectionalPoolRecordID\n\t\t\t\txmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">06063DC355058294</DirectionalPoolRecordID>\n\t\t</ns1:addDirectionalPoolRecordResponse>\n\t</soap:Body>\n</soap:Envelope>\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/directionalrecord_deleted.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n\t<soap:Body>\n\t\t<ns1:deleteDirectionalPoolRecordResponse\n\t\t\txmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\">\n\t\t\t<result xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">Successful</result>\n\t\t</ns1:deleteDirectionalPoolRecordResponse>\n\t</soap:Body>\n</soap:Envelope>\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/directionalrecord_doesnt_exist.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n\t<soap:Body>\n\t\t<soap:Fault>\n\t\t\t<faultcode>soap:Server</faultcode>\n\t\t\t<faultstring>Fault occurred while processing.</faultstring>\n\t\t\t<detail>\n\t\t\t\t<ns1:UltraWSException xmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\">\n\t\t\t\t\t<errorCode xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\"\n\t\t\t\t\t\txmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\t\t\t\t\t\txsi:type=\"xs:int\">2705</errorCode>\n\t\t\t\t\t<errorDescription xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">Directional Pool Record does not exist in the system</errorDescription>\n\t\t\t\t</ns1:UltraWSException>\n\t\t\t</detail>\n\t\t</soap:Fault>\n\t</soap:Body>\n</soap:Envelope>\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/directionalrecord_updated.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n\t<soap:Body>\n\t\t<ns1:updateDirectionalPoolRecordResponse\n\t\t\txmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\">\n\t\t\t<result xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">Successful</result>\n\t\t</ns1:updateDirectionalPoolRecordResponse>\n\t</soap:Body>\n</soap:Envelope>\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/directionalrecords.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n\t<soap:Body>\n\t\t<ns1:getDirectionalDNSRecordsForHostResponse\n\t\t\txmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\">\n\t\t\t<DirectionalDNSRecordDetailList\n\t\t\t\txmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\" ZoneName=\"geo.jclouds.org.\"\n\t\t\t\tDName=\"www.geo.jclouds.org.\">\n\t\t\t\t<ns2:DirectionalDNSRecordDetail\n\t\t\t\t\tGeolocationGroupName=\"southamerica\" GeolocationGroupId=\"C000000000000001\"\n\t\t\t\t\tTerritoriesCount=\"16\" DirPoolRecordId=\"A000000000000001\">\n\t\t\t\t\t<ns2:DirectionalDNSRecord recordType=\"CNAME\"\n\t\t\t\t\t\tTTL=\"300\" noResponseRecord=\"false\">\n\t\t\t\t\t\t<ns2:InfoValues Info1Value=\"southamerica.geo.jclouds.org.\" />\n\t\t\t\t\t</ns2:DirectionalDNSRecord>\n\t\t\t\t</ns2:DirectionalDNSRecordDetail>\n\t\t\t\t<ns2:DirectionalDNSRecordDetail\n\t\t\t\t\tTerritoriesCount=\"302/323\" DirPoolRecordId=\"A000000000000002\"\n\t\t\t\t\tGroupName=\"All Non-Configured Regions\" GroupId=\"B000000000000001\">\n\t\t\t\t\t<ns2:DirectionalDNSRecord recordType=\"A\"\n\t\t\t\t\t\tTTL=\"500\" noResponseRecord=\"false\">\n\t\t\t\t\t\t<ns2:InfoValues Info1Value=\"1.1.1.2\" />\n\t\t\t\t\t</ns2:DirectionalDNSRecord>\n\t\t\t\t</ns2:DirectionalDNSRecordDetail>\n\t\t\t\t<ns2:DirectionalDNSRecordDetail\n\t\t\t\t\tGeolocationGroupName=\"antarctica-unsupported\" GeolocationGroupId=\"C000000000000002\"\n\t\t\t\t\tTerritoriesCount=\"3\" DirPoolRecordId=\"A000000000000003\">\n\t\t\t\t\t<ns2:DirectionalDNSRecord recordType=\"A\"\n\t\t\t\t\t\tTTL=\"0\" noResponseRecord=\"true\">\n\t\t\t\t\t\t<ns2:InfoValues Info1Value=\"No Data Response\" />\n\t\t\t\t\t</ns2:DirectionalDNSRecord>\n\t\t\t\t</ns2:DirectionalDNSRecordDetail>\n\t\t\t\t<ns2:DirectionalDNSRecordDetail\n\t\t\t\t\tGeolocationGroupName=\"alazona\" GeolocationGroupId=\"C000000000000003\"\n\t\t\t\t\tTerritoriesCount=\"2\" DirPoolRecordId=\"A000000000000004\">\n\t\t\t\t\t<ns2:DirectionalDNSRecord recordType=\"A\"\n\t\t\t\t\t\tTTL=\"86400\" noResponseRecord=\"false\">\n\t\t\t\t\t\t<ns2:InfoValues Info1Value=\"1.1.1.1\" />\n\t\t\t\t\t</ns2:DirectionalDNSRecord>\n\t\t\t\t</ns2:DirectionalDNSRecordDetail>\n\t\t\t</DirectionalDNSRecordDetailList>\n\t\t</ns1:getDirectionalDNSRecordsForHostResponse>\n\t</soap:Body>\n</soap:Envelope>\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/get_current_account.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v01=\"http://webservice.api.ultra.neustar.com/v01/\"><soapenv:Header><wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:UsernameToken><wsse:Username>identity</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">credential</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body><v01:getAccountsListOfUser/></soapenv:Body></soapenv:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/get_directionalgroup.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v01=\"http://webservice.api.ultra.neustar.com/v01/\"><soapenv:Header><wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:UsernameToken><wsse:Username>identity</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">credential</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body><v01:getDirectionalDNSGroupDetails><GroupId>0000000000A</GroupId></v01:getDirectionalDNSGroupDetails></soapenv:Body></soapenv:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/get_poolrecordspec.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v01=\"http://webservice.api.ultra.neustar.com/v01/\"><soapenv:Header><wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:UsernameToken><wsse:Username>identity</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">credential</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body><v01:getPoolRecordSpec><poolRecordId>04053D8E57C7931F</poolRecordId></v01:getPoolRecordSpec></soapenv:Body></soapenv:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/get_task.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v01=\"http://webservice.api.ultra.neustar.com/v01/\"><soapenv:Header><wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:UsernameToken><wsse:Username>identity</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">credential</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body><v01:getStatusForTask><id><guid>0b40c7dd-748d-4c49-8506-26f0c7d2ea9c</guid></id></v01:getStatusForTask></soapenv:Body></soapenv:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/get_tcpool_by_dname.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v01=\"http://webservice.api.ultra.neustar.com/v01/\"><soapenv:Header><wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:UsernameToken><wsse:Username>identity</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">credential</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body><v01:getPoolForPoolHostName><hostName>www.foo.com.</hostName></v01:getPoolForPoolHostName></soapenv:Body></soapenv:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/get_zone.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v01=\"http://webservice.api.ultra.neustar.com/v01/\"><soapenv:Header><wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:UsernameToken><wsse:Username>identity</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">credential</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body><v01:getGeneralPropertiesForZone><zoneName>jclouds.org.</zoneName></v01:getGeneralPropertiesForZone></soapenv:Body></soapenv:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/group_doesnt_exist.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n\t<soap:Body>\n\t\t<soap:Fault>\n\t\t\t<faultcode>soap:Server</faultcode>\n\t\t\t<faultstring>Fault occurred while processing.</faultstring>\n\t\t\t<detail>\n\t\t\t\t<ns1:UltraWSException xmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\">\n\t\t\t\t\t<errorCode xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\"\n\t\t\t\t\t\txmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\t\t\t\t\t\txsi:type=\"xs:int\">4003</errorCode>\n\t\t\t\t\t<errorDescription xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">Group does not exist.</errorDescription>\n\t\t\t\t</ns1:UltraWSException>\n\t\t\t</detail>\n\t\t</soap:Fault>\n\t</soap:Body>\n</soap:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/lbpool_already_exists.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><soap:Fault><faultcode>soap:Server</faultcode><faultstring>Fault occurred while processing.</faultstring><detail><ns1:UltraWSException xmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\"><errorCode xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"xs:int\">2912</errorCode><errorDescription xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">Pool already created for this host name : www.rrpool.adrianc.rrpool.ultradnstest.jclouds.org.</errorDescription></ns1:UltraWSException></detail></soap:Fault></soap:Body></soap:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/lbpool_deleted.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><ns1:deleteResourceRecordResponse xmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\"><result xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">Successful</result></ns1:deleteResourceRecordResponse></soap:Body></soap:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/lbpool_doesnt_exist.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><soap:Fault><faultcode>soap:Server</faultcode><faultstring>Fault occurred while processing.</faultstring><detail><ns1:UltraWSException xmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\"><errorCode xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"xs:int\">2911</errorCode><errorDescription xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">Pool does not exist in the system</errorDescription></ns1:UltraWSException></detail></soap:Fault></soap:Body></soap:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/list_accountlevelgroup_records.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v01=\"http://webservice.api.ultra.neustar.com/v01/\"><soapenv:Header><wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:UsernameToken><wsse:Username>identity</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">credential</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body><v01:getDirectionalDNSRecordsForAcctLvlGroup><groupId>000000000000000A</groupId></v01:getDirectionalDNSRecordsForAcctLvlGroup></soapenv:Body></soapenv:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/list_accountlevelgroups.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v01=\"http://webservice.api.ultra.neustar.com/v01/\"><soapenv:Header><wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:UsernameToken><wsse:Username>identity</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">credential</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body><v01:getAccountLevelDirectionalGroups><accountId>accountid</accountId><GroupType /></v01:getAccountLevelDirectionalGroups></soapenv:Body></soapenv:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/list_directionalgroup_names.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v01=\"http://webservice.api.ultra.neustar.com/v01/\"><soapenv:Header><wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:UsernameToken><wsse:Username>identity</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">credential</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body><v01:getAvailableGroups><poolName>www.jclouds.org.</poolName><poolRecordType>1</poolRecordType><accountID>accountid</accountID><groupType /></v01:getAvailableGroups></soapenv:Body></soapenv:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/list_directionalgroup_records.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v01=\"http://webservice.api.ultra.neustar.com/v01/\"><soapenv:Header><wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:UsernameToken><wsse:Username>identity</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">credential</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body><v01:getDirectionalDNSRecordsForGroup><groupName>EU-www.jclouds.org.</groupName><hostName>www.jclouds.org.</hostName><zoneName>jclouds.org.</zoneName><poolRecordType>1</poolRecordType></v01:getDirectionalDNSRecordsForGroup></soapenv:Body></soapenv:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/list_directionalpools.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v01=\"http://webservice.api.ultra.neustar.com/v01/\"><soapenv:Header><wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:UsernameToken><wsse:Username>identity</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">credential</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body><v01:getDirectionalPoolsOfZone><zoneName>jclouds.org.</zoneName></v01:getDirectionalPoolsOfZone></soapenv:Body></soapenv:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/list_directionalrecords.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v01=\"http://webservice.api.ultra.neustar.com/v01/\"><soapenv:Header><wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:UsernameToken><wsse:Username>identity</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">credential</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body><v01:getDirectionalDNSRecordsForHost><zoneName>jclouds.org.</zoneName><hostName>www.jclouds.org.</hostName><poolRecordType>1</poolRecordType></v01:getDirectionalDNSRecordsForHost></soapenv:Body></soapenv:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/list_records.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v01=\"http://webservice.api.ultra.neustar.com/v01/\"><soapenv:Header><wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:UsernameToken><wsse:Username>identity</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">credential</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body><v01:getResourceRecordsOfZone><zoneName>jclouds.org.</zoneName><rrType>0</rrType></v01:getResourceRecordsOfZone></soapenv:Body></soapenv:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/list_records_by_name.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v01=\"http://webservice.api.ultra.neustar.com/v01/\"><soapenv:Header><wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:UsernameToken><wsse:Username>identity</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">credential</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body><v01:getResourceRecordsOfDNameByType><zoneName>jclouds.org.</zoneName><hostName>www.jclouds.org.</hostName><rrType>0</rrType></v01:getResourceRecordsOfDNameByType></soapenv:Body></soapenv:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/list_records_by_name_and_type.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v01=\"http://webservice.api.ultra.neustar.com/v01/\"><soapenv:Header><wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:UsernameToken><wsse:Username>identity</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">credential</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body><v01:getResourceRecordsOfDNameByType><zoneName>jclouds.org.</zoneName><hostName>www.jclouds.org.</hostName><rrType>1</rrType></v01:getResourceRecordsOfDNameByType></soapenv:Body></soapenv:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/list_regions.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v01=\"http://webservice.api.ultra.neustar.com/v01/\"><soapenv:Header><wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:UsernameToken><wsse:Username>identity</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">credential</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body><v01:getAvailableRegions/></soapenv:Body></soapenv:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/list_rrpools.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v01=\"http://webservice.api.ultra.neustar.com/v01/\"><soapenv:Header><wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:UsernameToken><wsse:Username>identity</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">credential</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body><v01:getLoadBalancingPoolsByZone><zoneName>jclouds.org.</zoneName><lbPoolType>RR</lbPoolType></v01:getLoadBalancingPoolsByZone></soapenv:Body></soapenv:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/list_rrrecords.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v01=\"http://webservice.api.ultra.neustar.com/v01/\"><soapenv:Header><wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:UsernameToken><wsse:Username>identity</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">credential</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body><v01:getRRPoolRecords><lbPoolId>04053D8E57C7931F</lbPoolId></v01:getRRPoolRecords></soapenv:Body></soapenv:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/list_tasks.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v01=\"http://webservice.api.ultra.neustar.com/v01/\"><soapenv:Header><wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:UsernameToken><wsse:Username>identity</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">credential</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body><v01:getAllTasks/></soapenv:Body></soapenv:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/list_tcpools.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v01=\"http://webservice.api.ultra.neustar.com/v01/\"><soapenv:Header><wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:UsernameToken><wsse:Username>identity</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">credential</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body><v01:getLoadBalancingPoolsByZone><zoneName>jclouds.org.</zoneName><lbPoolType>TC</lbPoolType></v01:getLoadBalancingPoolsByZone></soapenv:Body></soapenv:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/list_tcrecords.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v01=\"http://webservice.api.ultra.neustar.com/v01/\"><soapenv:Header><wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:UsernameToken><wsse:Username>identity</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">credential</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body><v01:getPoolRecords><poolId>04053D8E57C7931F</poolId></v01:getPoolRecords></soapenv:Body></soapenv:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/list_zones_by_account.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v01=\"http://webservice.api.ultra.neustar.com/v01/\"><soapenv:Header><wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:UsernameToken><wsse:Username>identity</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">credential</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body><v01:getZonesOfAccount><accountId>AAAAAAAAAAAAAAAA</accountId><zoneType>all</zoneType></v01:getZonesOfAccount></soapenv:Body></soapenv:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/list_zones_by_account_and_type.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v01=\"http://webservice.api.ultra.neustar.com/v01/\"><soapenv:Header><wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:UsernameToken><wsse:Username>identity</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">credential</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body><v01:getZonesOfAccount><accountId>AAAAAAAAAAAAAAAA</accountId><zoneType>primary</zoneType></v01:getZonesOfAccount></soapenv:Body></soapenv:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/logback.xml",
    "content": "<?xml version=\"1.0\"?>\n<configuration scan=\"false\">\n    <appender name=\"FILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n\n    <appender name=\"WIREFILE\" class=\"ch.qos.logback.core.FileAppender\">\n        <file>target/test-data/jclouds-wire.log</file>\n\n        <encoder>\n            <Pattern>%d %-5p [%c] [%thread] %m%n</Pattern>\n        </encoder>\n    </appender>\n    \n    <root>\n        <level value=\"warn\" />\n    </root>\n\n    <logger name=\"org.jclouds\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"FILE\" />\n    </logger>\n\n    <logger name=\"jclouds.wire\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n\n    <logger name=\"jclouds.headers\">\n        <level value=\"DEBUG\" />\n        <appender-ref ref=\"WIREFILE\" />\n    </logger>\n\n</configuration>\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/poolrecord_updated.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><ns1:updatePoolRecordResponse xmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\"><result xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">Successful</result></ns1:updatePoolRecordResponse></soap:Body></soap:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/poolrecordspec.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n\t<soap:Body>\n\t\t<ns1:getPoolRecordSpecResponse\n\t\t\txmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\">\n\t\t\t<PoolRecordSpecData xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\"\n\t\t\t\tdescription=\"foo\" recordState=\"Normal-NoTest\" probing=\"DISABLED\"\n\t\t\t\tallFail=\"DISABLED\" weight=\"2\" failOverDelay=\"0\" threshold=\"1\" ttl=\"120\" />\n\t\t</ns1:getPoolRecordSpecResponse>\n\t</soap:Body>\n</soap:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/records.xml",
    "content": "<?xml version=\"1.0\"?>\n<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n  <soap:Body>\n    <ns1:getResourceRecordsOfZoneResponse xmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\">\n      <ResourceRecordList xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">\n        <ns2:ResourceRecord ZoneName=\"jclouds.org.\" Type=\"1\" DName=\"www.jclouds.org.\" TTL=\"3600\" Guid=\"04023A2507B6468F\" ZoneId=\"0000000000000001\" LName=\"www.jclouds.org.\" Created=\"2010-10-02T16:57:16.000Z\" Modified=\"2011-09-27T23:49:21.000Z\">\n          <ns2:InfoValues Info1Value=\"1.2.3.4\"/>\n        </ns2:ResourceRecord>\n        <ns2:ResourceRecord ZoneName=\"jclouds.org.\" Type=\"2\" DName=\"jclouds.org.\" TTL=\"86400\" Guid=\"0B0338C2023F7969\" ZoneId=\"0000000000000001\" LName=\"jclouds.org.\" Created=\"2009-10-12T12:02:23.000Z\" Modified=\"2009-10-12T12:02:23.000Z\">\n          <ns2:InfoValues Info1Value=\"pdns2.ultradns.net.\"/>\n        </ns2:ResourceRecord>\n        <ns2:ResourceRecord ZoneName=\"jclouds.org.\" Type=\"2\" DName=\"jclouds.org.\" TTL=\"86400\" Guid=\"0B0338C2023F7968\" ZoneId=\"0000000000000001\" LName=\"jclouds.org.\" Created=\"2009-10-12T12:02:23.000Z\" Modified=\"2009-10-12T12:02:23.000Z\">\n          <ns2:InfoValues Info1Value=\"pdns1.ultradns.net.\"/>\n        </ns2:ResourceRecord>\n        <ns2:ResourceRecord ZoneName=\"jclouds.org.\" Type=\"2\" DName=\"jclouds.org.\" TTL=\"86400\" Guid=\"0B0338C2023F796B\" ZoneId=\"0000000000000001\" LName=\"jclouds.org.\" Created=\"2009-10-12T12:02:23.000Z\" Modified=\"2009-10-12T12:02:23.000Z\">\n          <ns2:InfoValues Info1Value=\"pdns4.ultradns.org.\"/>\n        </ns2:ResourceRecord>\n        <ns2:ResourceRecord ZoneName=\"jclouds.org.\" Type=\"6\" DName=\"jclouds.org.\" TTL=\"3600\" Guid=\"0B0338C2023F7983\" ZoneId=\"0000000000000001\" LName=\"jclouds.org.\" Created=\"2009-10-12T12:02:23.000Z\" Modified=\"2011-09-27T23:49:22.000Z\">\n          <ns2:InfoValues Info1Value=\"pdns2.ultradns.net.\" Info2Value=\"admin.jclouds.org.\" Info3Value=\"2011092701\" Info4Value=\"10800\" Info5Value=\"3600\" Info6Value=\"604800\" Info7Value=\"86400\"/>\n        </ns2:ResourceRecord>\n        <ns2:ResourceRecord ZoneName=\"jclouds.org.\" Type=\"1\" DName=\"jclouds.org.\" TTL=\"3600\" Guid=\"0B0338C2023F796E\" ZoneId=\"0000000000000001\" LName=\"jclouds.org.\" Created=\"2009-10-12T12:02:23.000Z\" Modified=\"2011-09-27T23:49:22.000Z\">\n          <ns2:InfoValues Info1Value=\"1.2.3.4\"/>\n        </ns2:ResourceRecord>\n        <ns2:ResourceRecord ZoneName=\"jclouds.org.\" Type=\"2\" DName=\"jclouds.org.\" TTL=\"86400\" Guid=\"0B0338C2023F796C\" ZoneId=\"0000000000000001\" LName=\"jclouds.org.\" Created=\"2009-10-12T12:02:23.000Z\" Modified=\"2009-10-12T12:02:23.000Z\">\n          <ns2:InfoValues Info1Value=\"pdns5.ultradns.info.\"/>\n        </ns2:ResourceRecord>\n        <ns2:ResourceRecord ZoneName=\"jclouds.org.\" Type=\"2\" DName=\"jclouds.org.\" TTL=\"86400\" Guid=\"0B0338C2023F796D\" ZoneId=\"0000000000000001\" LName=\"jclouds.org.\" Created=\"2009-10-12T12:02:23.000Z\" Modified=\"2009-10-12T12:02:23.000Z\">\n          <ns2:InfoValues Info1Value=\"pdns6.ultradns.co.uk.\"/>\n        </ns2:ResourceRecord>\n        <ns2:ResourceRecord ZoneName=\"jclouds.org.\" Type=\"2\" DName=\"jclouds.org.\" TTL=\"86400\" Guid=\"0B0338C2023F796A\" ZoneId=\"0000000000000001\" LName=\"jclouds.org.\" Created=\"2009-10-12T12:02:23.000Z\" Modified=\"2009-10-12T12:02:23.000Z\">\n          <ns2:InfoValues Info1Value=\"pdns3.ultradns.org.\"/>\n        </ns2:ResourceRecord>\n      </ResourceRecordList>\n    </ns1:getResourceRecordsOfZoneResponse>\n  </soap:Body>\n</soap:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/records_by_name_and_type.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><ns1:getResourceRecordsOfDNameByTypeResponse xmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\"><ResourceRecordList xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\"><ns2:ResourceRecord ZoneName=\"adrianc.rr.ultradnstest.jclouds.org.\" Type=\"6\" DName=\"adrianc.rr.ultradnstest.jclouds.org.\" TTL=\"86400\" Guid=\"04053D8E57C7A22F\" ZoneId=\"03053D8E57C7A22A\" LName=\"adrianc.rr.ultradnstest.jclouds.org.\" Created=\"2013-02-22T08:22:48.000Z\" Modified=\"2013-02-22T08:22:49.000Z\"><ns2:InfoValues Info1Value=\"pdns75.ultradns.com.\" Info2Value=\"adrianc.netflix.com.\" Info3Value=\"2013022200\" Info4Value=\"86400\" Info5Value=\"86400\" Info6Value=\"86400\" Info7Value=\"86400\"/></ns2:ResourceRecord></ResourceRecordList></ns1:getResourceRecordsOfDNameByTypeResponse></soap:Body></soap:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/regions.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n\t<soap:Body>\n\t\t<ns1:getAvailableRegionsResponse\n\t\t\txmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\">\n\t\t\t<DirectionalDNSAvailableRegionList\n\t\t\t\txmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">\n\t\t\t\t<ns2:Region TerritoryName=\"Anonymous Proxy\" RegionName=\"Anonymous Proxy (A1)\"\n\t\t\t\t\tRegionID=\"14\" />\n\t\t\t\t<ns2:Region TerritoryName=\"Antarctica;Bouvet Island;French Southern Territories\"\n\t\t\t\t\tRegionName=\"Antarctica\" RegionID=\"3\" />\n\t\t\t</DirectionalDNSAvailableRegionList>\n\t\t</ns1:getAvailableRegionsResponse>\n\t</soap:Body>\n</soap:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/rr_already_exists.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><soap:Fault><faultcode>soap:Server</faultcode><faultstring>Fault occurred while processing.</faultstring><detail><ns1:UltraWSException xmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\"><errorCode xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"xs:int\">2111</errorCode><errorDescription xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">Resource Record of type 15 with these attributes already exists in the system.</errorDescription></ns1:UltraWSException></detail></soap:Fault></soap:Body></soap:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/rr_created.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><ns1:createResourceRecordResponse xmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\"><guid xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">04063D9D54C6A01F</guid></ns1:createResourceRecordResponse></soap:Body></soap:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/rr_deleted.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><ns1:deleteResourceRecordResponse xmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\"><result xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">Successful</result></ns1:deleteResourceRecordResponse></soap:Body></soap:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/rr_doesnt_exist.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><soap:Fault><faultcode>soap:Server</faultcode><faultstring>Fault occurred while processing.</faultstring><detail><ns1:UltraWSException xmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\"><errorCode xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"xs:int\">2103</errorCode><errorDescription xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">No Resource Record with GUID found in the system AAAAAAAAAAAAAAAA</errorDescription></ns1:UltraWSException></detail></soap:Fault></soap:Body></soap:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/rr_updated.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><ns1:updateResourceRecordResponse xmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\"><result xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">Successful</result></ns1:updateResourceRecordResponse></soap:Body></soap:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/rrpool_created.xml",
    "content": "<env:Body>\n\t<v01:addRRLBPoolResponse xmlns:web=\"http://webservice.api.ultra.neustar.com/\">\n\t\t<RRPoolID>060339AA04175655</RRPoolID>\n\t</v01:addRRLBPoolResponse>\n</env:Body>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/rrpools.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n\t<soap:Body>\n\t\t<ns1:getLoadBalancingPoolsByZoneResponse\n\t\t\txmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\">\n\t\t\t<LBPoolList xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">\n\t\t\t\t<ns2:LBPoolData zoneid=\"0000000000000001\">\n\t\t\t\t\t<ns2:PoolData description=\"uswest1\"\n\t\t\t\t\t\tPoolId=\"000000000000002\" PoolType=\"RD\" PoolDName=\"app-uswest1.jclouds.org.\"\n\t\t\t\t\t\tResponseMethod=\"RR\" />\n\t\t\t\t</ns2:LBPoolData>\n\t\t\t\t<ns2:LBPoolData zoneid=\"0000000000000001\">\n\t\t\t\t\t<ns2:PoolData description=\"uswest2\"\n\t\t\t\t\t\tPoolId=\"000000000000003\" PoolType=\"RD\" PoolDName=\"app-uswest2.jclouds.org.\"\n\t\t\t\t\t\tResponseMethod=\"RR\" />\n\t\t\t\t</ns2:LBPoolData>\n\t\t\t\t<ns2:LBPoolData zoneid=\"0000000000000001\">\n\t\t\t\t\t<ns2:PoolData description=\"euwest\"\n\t\t\t\t\t\tPoolId=\"000000000000004\" PoolType=\"RD\" PoolDName=\"app-euwest.jclouds.org.\"\n\t\t\t\t\t\tResponseMethod=\"RR\" />\n\t\t\t\t</ns2:LBPoolData>\n\t\t\t</LBPoolList>\n\t\t</ns1:getLoadBalancingPoolsByZoneResponse>\n\t</soap:Body>\n</soap:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/run_test.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v01=\"http://webservice.api.ultra.neustar.com/v01/\"><soapenv:Header><wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:UsernameToken><wsse:Username>identity</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">credential</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body><v01:runTest><value>foo</value></v01:runTest></soapenv:Body></soapenv:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/server_fault.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n\t<soap:Body>\n\t\t<soap:Fault>\n\t\t\t<faultcode>soap:Server</faultcode>\n\t\t\t<faultstring>Fault occurred while processing.</faultstring>\n\t\t\t<detail>\n\t\t\t\t<ns1:UltraWSException xmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\">\n\t\t\t\t\t<errorCode xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\"\n\t\t\t\t\t\txmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\t\t\t\t\t\txsi:type=\"xs:int\">0</errorCode>\n\t\t\t\t\t<errorDescription xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\"\n\t\t\t\t\t\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:nil=\"true\" />\n\t\t\t\t</ns1:UltraWSException>\n\t\t\t</detail>\n\t\t</soap:Fault>\n\t</soap:Body>\n</soap:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/task.xml",
    "content": "<soap:Body>\n\t<ns1:getStatusForTaskResponse\n\t\txmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\">\n\t\t<TaskStatus xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">\n\t\t\t<ns2:id>\n\t\t\t\t<ns2:guid>0b40c7dd-748d-4c49-8506-26f0c7d2ea9c</ns2:guid>\n\t\t\t</ns2:id>\n\t\t\t<ns2:code>COMPLETE</ns2:code>\n\t\t\t<ns2:message>Processing complete</ns2:message>\n\t\t\t<ns2:resultUrl>http://localhost:8008/users/node01/tasks/0b40c7dd-748d-4c49-8506-26f0c7d2ea9c/result</ns2:resultUrl>\n\t\t</TaskStatus>\n\t</ns1:getStatusForTaskResponse>\n</soap:Body>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/task_doesnt_exist.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n\t<soap:Body>\n\t\t<soap:Fault>\n\t\t\t<faultcode>soap:Server</faultcode>\n\t\t\t<faultstring>Fault occurred while processing.</faultstring>\n\t\t\t<detail>\n\t\t\t\t<ns1:UltraWSException xmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\">\n\t\t\t\t\t<errorCode xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\"\n\t\t\t\t\t\txmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\t\t\t\t\t\txsi:type=\"xs:int\">0</errorCode>\n\t\t\t\t\t<errorDescription xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">Cannot find task with guid AAAAAAAAAAAAAAAA</errorDescription>\n\t\t\t\t</ns1:UltraWSException>\n\t\t\t</detail>\n\t\t</soap:Fault>\n\t</soap:Body>\n</soap:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/taskid.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n   <soap:Body>\n      <ns1:runTestResponse xmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\">\n         <TaskId xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">\n            <ns2:guid>8d7a1725-4f4a-4b70-affa-f01dcce1526e</ns2:guid>\n         </TaskId>\n      </ns1:runTestResponse>\n   </soap:Body>\n</soap:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/tasks.xml",
    "content": "<soap:Body>\n\t<ns1:getAllTasksResponse xmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\">\n\t\t<TaskStatusList xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">\n\t\t\t<ns2:taskStatus>\n\t\t\t\t<ns2:id>\n\t\t\t\t\t<ns2:guid>0b40c7dd-748d-4c49-8506-26f0c7d2ea9c</ns2:guid>\n\t\t\t\t</ns2:id>\n\t\t\t\t<ns2:code>COMPLETE</ns2:code>\n\t\t\t\t<ns2:message>Processing complete</ns2:message>\n\t\t\t\t<ns2:resultUrl>http://localhost:8008/users/node01/tasks/0b40c7dd-748d-4c49-8506-26f0c7d2ea9c/result</ns2:resultUrl>\n\t\t\t</ns2:taskStatus>\n\t\t</TaskStatusList>\n\t</ns1:getAllTasksResponse>\n</soap:Body>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/tcpool_created.xml",
    "content": "<env:Body>\n\t<v01:addTCLBPoolResponse xmlns:web=\"http://webservice.api.ultra.neustar.com/\">\n\t\t<TCPoolID>060339AA0417567A</TCPoolID>\n\t</v01:addTCLBPoolResponse>\n</env:Body>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/tcpool_name.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n\t<soap:Body>\n\t\t<ns1:getPoolForPoolHostNameResponse\n\t\t\txmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\">\n\t\t\t<LBPoolData xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">\n\t\t\t\t<ns2:PoolData PoolName=\"foo\" PoolType=\"TC\" />\n\t\t\t</LBPoolData>\n\t\t</ns1:getPoolForPoolHostNameResponse>\n\t</soap:Body>\n</soap:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/tcpools.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n\t<soap:Body>\n\t\t<ns1:getLoadBalancingPoolsByZoneResponse\n\t\t\txmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\">\n\t\t\t<LBPoolList xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">\n\t\t\t\t<ns2:LBPoolData zoneid=\"0000000000000001\">\n\t\t\t\t\t<ns2:PoolData description=\"us-west-1c\"\n\t\t\t\t\t\tPoolId=\"000000000000002\" PoolType=\"TC\" PoolStatus=\"1\"\n\t\t\t\t\t\tPoolDName=\"us-west-1c.discovery.jclouds.org.\" FailOver=\"Enabled\"\n\t\t\t\t\t\tProbing=\"Enabled\" MaxActiveServers=\"0\" />\n\t\t\t\t</ns2:LBPoolData>\n\t\t\t</LBPoolList>\n\t\t</ns1:getLoadBalancingPoolsByZoneResponse>\n\t</soap:Body>\n</soap:Envelope>\n"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/tcrecord_already_exists.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><soap:Fault><faultcode>soap:Server</faultcode><faultstring>Fault occurred while processing.</faultstring><detail><ns1:UltraWSException xmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\"><errorCode xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"xs:int\">2111</errorCode><errorDescription xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">Resource Record of type 1 with these attributes already exists in the system.</errorDescription></ns1:UltraWSException></detail></soap:Fault></soap:Body></soap:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/tcrecord_created.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><ns1:addPoolRecordResponse xmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\"><poolRecordID xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">06063DAC54F8D3D9</poolRecordID></ns1:addPoolRecordResponse></soap:Body></soap:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/tcrecord_deleted.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><ns1:deletePoolRecordResponse xmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\"><result xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">Successful</result></ns1:deletePoolRecordResponse></soap:Body></soap:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/tcrecord_doesnt_exist.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><soap:Fault><faultcode>soap:Server</faultcode><faultstring>Fault occurred while processing.</faultstring><detail><ns1:UltraWSException xmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\"><errorCode xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"xs:int\">3101</errorCode><errorDescription xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">Pool Record does not exist.</errorDescription></ns1:UltraWSException></detail></soap:Fault></soap:Body></soap:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/tcrecords.xml",
    "content": "<?xml version=\"1.0\"?>\n<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n\t<soap:Body>\n\t\t<ns1:getPoolRecordsResponse\n\t\t\txmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\">\n\t\t\t<PoolRecordsList xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">\n\t\t\t\t<ns2:PoolRecordData poolRecordID=\"0000000000000001\"\n\t\t\t\t\tpoolId=\"0000000000000001\" pointsTo=\"canary.jclouds.org.\" weight=\"2\"\n\t\t\t\t\tpriority=\"2\" recordType=\"CNAME\" forceAnswer=\"Normal\" probing=\"ENABLED\"\n\t\t\t\t\tstatus=\"OK\" serving=\"Yes\" description=\"canary app\" />\n\t\t\t\t<ns2:PoolRecordData poolRecordID=\"0000000000000002\"\n\t\t\t\t\tpoolId=\"0000000000000001\" pointsTo=\"prod.jclouds.org.\" weight=\"98\"\n\t\t\t\t\tpriority=\"1\" recordType=\"CNAME\" forceAnswer=\"Normal\" probing=\"ENABLED\"\n\t\t\t\t\tstatus=\"OK\" serving=\"Yes\" description=\"prod app\" />\n\t\t\t</PoolRecordsList>\n\t\t</ns1:getPoolRecordsResponse>\n\t</soap:Body>\n</soap:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/update_directionalrecord.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v01=\"http://webservice.api.ultra.neustar.com/v01/\"><soapenv:Header><wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:UsernameToken><wsse:Username>identity</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">credential</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body><v01:updateDirectionalPoolRecord><transactionID /><UpdateDirectionalRecordData directionalPoolRecordId=\"04053D8E57C7931F\"><DirectionalRecordConfiguration TTL=\"300\" ><InfoValues Info1Value=\"1.1.0.1\" /></DirectionalRecordConfiguration></UpdateDirectionalRecordData></v01:updateDirectionalPoolRecord></soapenv:Body></soapenv:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/update_directionalrecord_group.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v01=\"http://webservice.api.ultra.neustar.com/v01/\"><soapenv:Header><wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:UsernameToken><wsse:Username>identity</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">credential</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body><v01:updateDirectionalPoolRecord><transactionID /><UpdateDirectionalRecordData directionalPoolRecordId=\"04053D8E57C7931F\"><DirectionalRecordConfiguration TTL=\"300\" ><InfoValues Info1Value=\"1.1.0.1\" /></DirectionalRecordConfiguration><GeolocationGroupDetails groupName=\"Mexas\" description=\"Clients we classify as being in US\" ><GeolocationGroupDefinitionData regionName=\"United States (US)\" territoryNames=\"Maryland;Texas\" /></GeolocationGroupDetails></UpdateDirectionalRecordData></v01:updateDirectionalPoolRecord></soapenv:Body></soapenv:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/update_poolrecord.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v01=\"http://webservice.api.ultra.neustar.com/v01/\"><soapenv:Header><wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:UsernameToken><wsse:Username>identity</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">credential</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body><v01:updatePoolRecord><transactionID /><poolRecordID>04053D8E57C7931F</poolRecordID><parentPoolId /><childPoolId /><pointsTo>www.baz.com.</pointsTo><priority>0</priority><failOverDelay>0</failOverDelay><ttl>200</ttl><weight>98</weight><mode>Normal</mode><threshold>1</threshold></v01:updatePoolRecord></soapenv:Body></soapenv:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/update_rr.xml",
    "content": "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v01=\"http://webservice.api.ultra.neustar.com/v01/\"><soapenv:Header><wsse:Security soapenv:mustUnderstand=\"1\" xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"><wsse:UsernameToken><wsse:Username>identity</wsse:Username><wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">credential</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header><soapenv:Body><v01:updateResourceRecord><transactionID /><resourceRecord Guid=\"04053D8E57C7931F\" ZoneName=\"jclouds.org.\" Type=\"15\" DName=\"mail.jclouds.org.\" TTL=\"1800\"><InfoValues Info1Value=\"10\" Info2Value=\"maileast.jclouds.org.\" /></resourceRecord></v01:updateResourceRecord></soapenv:Body></soapenv:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/zone_already_exists.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><soap:Fault><faultcode>soap:Server</faultcode><faultstring>Fault occurred while processing.</faultstring><detail><ns1:UltraWSException xmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\"><errorCode xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"xs:int\">1802</errorCode><errorDescription xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">Zone already exists in the system.</errorDescription></ns1:UltraWSException></detail></soap:Fault></soap:Body></soap:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/zone_created.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n\t<soap:Body>\n\t\t<ns1:createPrimaryZoneResponse\n\t\t\txmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\">\n\t\t\t<result xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">Successful</result>\n\t\t</ns1:createPrimaryZoneResponse>\n\t</soap:Body>\n</soap:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/zone_deleted.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><ns1:deleteZoneResponse xmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\"><result xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">Successful</result></ns1:deleteZoneResponse></soap:Body></soap:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/zone_doesnt_exist.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n   <soap:Body>\n      <soap:Fault>\n         <faultcode>soap:Server</faultcode>\n         <faultstring>Fault occurred while processing.</faultstring>\n         <detail>\n            <ns1:UltraWSException xmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\">\n               <errorCode xsi:type=\"xs:int\" xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">1801</errorCode>\n               <errorDescription xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">Zone does not exist in the system.</errorDescription>\n            </ns1:UltraWSException>\n         </detail>\n      </soap:Fault>\n   </soap:Body>\n</soap:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/zoneproperties.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n   <soap:Body>\n      <ns1:getGeneralPropertiesForZoneResponse xmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\">\n         <GeneralZoneProperties resourceRecordCount=\"17\" name=\"jclouds.org.\" zoneType=\"primary\" modified=\"2010-09-05 04:04:17.0\" xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\"/>\n      </ns1:getGeneralPropertiesForZoneResponse>\n   </soap:Body>\n</soap:Envelope>"
  },
  {
    "path": "providers/ultradns-ws/src/test/resources/zones.xml",
    "content": "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n   <soap:Body>\n      <ns1:getZonesOfAccountResponse xmlns:ns1=\"http://webservice.api.ultra.neustar.com/v01/\">\n         <ZoneList xmlns:ns2=\"http://schema.ultraservice.neustar.com/v01/\">\n            <ns2:UltraZone zoneName=\"jclouds.org.\" zoneType=\"1\" accountId=\"AAAAAAAAAAAAAAAA\" owner=\"EEEEEEEEEEEEEEEE\" zoneId=\"0000000000000001\" dnssecStatus=\"UNSIGNED\"/>\n            <ns2:UltraZone zoneName=\"0.1.2.3.4.5.6.7.ip6.arpa.\" zoneType=\"1\" accountId=\"AAAAAAAAAAAAAAAA\" owner=\"EEEEEEEEEEEEEEEE\" zoneId=\"0000000000000002\" dnssecStatus=\"UNSIGNED\"/>\n         </ZoneList>\n      </ns1:getZonesOfAccountResponse>\n   </soap:Body>\n</soap:Envelope>"
  },
  {
    "path": "resources/checkstyle-suppressions.xml",
    "content": "<?xml version=\"1.0\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n\n\n<!DOCTYPE suppressions PUBLIC\n        \"-//Puppy Crawl//DTD Suppressions 1.0//EN\"\n        \"http://www.puppycrawl.com/dtds/suppressions_1_0.dtd\">\n<suppressions>\n    <!-- Turn off all checks for generated files -->\n    <suppress files=\"AutoValue_.*.java\" checks=\".*\" />\n</suppressions>\n"
  },
  {
    "path": "resources/checkstyle.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<!DOCTYPE module PUBLIC \"-//Puppy Crawl//DTD Check Configuration 1.3//EN\" \"http://www.puppycrawl.com/dtds/configuration_1_3.dtd\">\n\n<module name=\"Checker\">\n    <property name=\"severity\" value=\"warning\"/>\n    <module name=\"NewlineAtEndOfFile\">\n        <property name=\"lineSeparator\" value=\"lf\"/>\n    </module>\n    <module name=\"TreeWalker\">\n        <module name=\"AvoidStarImport\"/>\n        <module name=\"EmptyStatement\"/>\n        <module name=\"IllegalInstantiation\">\n            <property name=\"classes\" value=\"java.lang.Boolean,java.lang.Short,java.lang.Integer,java.lang.Long\"/>\n        </module>\n        <module name=\"InterfaceIsType\"/>\n<!--\n        jclouds prefers 120 character line lengths but has many files with\n        longer lines\n        <module name=\"LineLength\">\n            <property name=\"ignorePattern\" value=\"^import\\s.*;$\"/>\n            <property name=\"max\" value=\"120\"/>\n        </module>\n-->\n        <module name=\"MissingOverride\"/>\n        <module name=\"ModifierOrder\"/>\n        <module name=\"MultipleVariableDeclarations\"/>\n        <module name=\"NoWhitespaceAfter\">\n            <!-- ARRAY_INIT disabled -->\n            <property name=\"tokens\" value=\"BNOT, DEC, DOT, INC, LNOT, UNARY_MINUS, UNARY_PLUS\"/>\n        </module>\n        <module name=\"NoWhitespaceBefore\"/>\n        <module name=\"RedundantImport\"/>\n       <!-- <module name=\"RedundantModifier\"/> -->\n        <module name=\"SimplifyBooleanExpression\"/>\n        <module name=\"TypeName\"/>\n        <module name=\"UnnecessaryParentheses\"/>\n        <module name=\"UnusedImports\">\n            <property name=\"processJavadoc\" value=\"true\"/>\n        </module>\n        <module name=\"IllegalImport\">\n            <!-- Avoid importing AutoValue shaded packages such as Guava -->\n            <property name=\"illegalPkgs\" value=\"sun,autovalue,org.testng.internal\"/>\n        </module>\n        <module name=\"WhitespaceAfter\">\n            <!-- TYPECAST disabled -->\n            <property name=\"tokens\" value=\"COMMA, SEMI\"/>\n        </module>\n        <module name=\"WhitespaceAround\">\n            <property name=\"ignoreEnhancedForColon\" value=\"false\" />\n            <!-- TODO: enable LCURLY, RCURLY, SLIST -->\n            <property name=\"tokens\" value=\"ASSIGN, BAND, BAND_ASSIGN, BOR, BOR_ASSIGN, BSR, BSR_ASSIGN, BXOR, BXOR_ASSIGN, COLON, DIV, DIV_ASSIGN, EQUAL, GE, GT, LAND, LE, LITERAL_ASSERT, LITERAL_CATCH, LITERAL_DO, LITERAL_ELSE, LITERAL_FINALLY, LITERAL_FOR, LITERAL_IF, LITERAL_RETURN, LITERAL_SYNCHRONIZED, LITERAL_TRY, LITERAL_WHILE, LOR, LT, MINUS, MINUS_ASSIGN, MOD, MOD_ASSIGN, NOT_EQUAL, PLUS, PLUS_ASSIGN, QUESTION, SL, SL_ASSIGN, SR, SR_ASSIGN, STAR, STAR_ASSIGN, TYPE_EXTENSION_AND\" />\n        </module>\n    </module>\n    <module name=\"Header\">\n        <property name=\"header\" value=\"/*\\n\n* Licensed to the Apache Software Foundation (ASF) under one or more\\n\n* contributor license agreements.  See the NOTICE file distributed with\\n\n* this work for additional information regarding copyright ownership.\\n\n* The ASF licenses this file to You under the Apache License, Version 2.0\\n\n* (the &quot;License&quot;); you may not use this file except in compliance with\\n\n* the License.  You may obtain a copy of the License at\\n\n*\\n\n*     http://www.apache.org/licenses/LICENSE-2.0\\n\n*\\n\n* Unless required by applicable law or agreed to in writing, software\\n\n* distributed under the License is distributed on an &quot;AS IS&quot; BASIS,\\n\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\\n\n* See the License for the specific language governing permissions and\\n\n* limitations under the License.\\n\n*/\\n\"/>\n        <property name=\"fileExtensions\" value=\"java\"/>\n    </module>\n    <module name=\"RegexpMultiline\">\n        <property name=\"format\" value=\"@author\"/>\n        <property name=\"message\" value=\"Do not use Javadoc @author annotation\"/>\n    </module>\n    <module name=\"RegexpMultiline\">\n        <property name=\"format\" value=\"\\r\\n\"/>\n        <property name=\"message\" value=\"Do not use Windows line endings\"/>\n        <property name=\"fileExtensions\" value=\"java,xml,json\"/>\n    </module>\n</module>\n"
  },
  {
    "path": "resources/modernizer_exclusions.txt",
    "content": "com/google/common/base/Charsets.ISO_8859_1:Ljava/nio/charset/Charset;\ncom/google/common/base/Charsets.US_ASCII:Ljava/nio/charset/Charset;\ncom/google/common/base/Charsets.UTF_8:Ljava/nio/charset/Charset;\ncom/google/common/base/Objects.equal:(Ljava/lang/Object;Ljava/lang/Object;)Z\ncom/google/common/base/Objects.hashCode:([Ljava/lang/Object;)I\ncom/google/common/collect/Lists.newArrayList:()Ljava/util/ArrayList;\ncom/google/common/collect/Lists.newArrayListWithCapacity:(I)Ljava/util/ArrayList;\ncom/google/common/collect/Lists.newLinkedList:()Ljava/util/LinkedList;\ncom/google/common/collect/Maps.newConcurrentMap:()Ljava/util/concurrent/ConcurrentMap;\ncom/google/common/collect/Maps.newHashMap:()Ljava/util/HashMap;\ncom/google/common/collect/Maps.newHashMap:(Ljava/util/Map;)Ljava/util/HashMap;\ncom/google/common/collect/Maps.newLinkedHashMap:()Ljava/util/LinkedHashMap;\ncom/google/common/collect/Maps.newLinkedHashMap:(Ljava/util/Map;)Ljava/util/LinkedHashMap;\ncom/google/common/collect/Maps.newTreeMap:()Ljava/util/TreeMap;\ncom/google/common/collect/Sets.newHashSet:()Ljava/util/HashSet;\ncom/google/common/collect/Sets.newLinkedHashSet:()Ljava/util/LinkedHashSet;\ncom/google/common/collect/Sets.newTreeSet:()Ljava/util/TreeSet;\ncom/google/common/primitives/Ints.compare:(II)I\ncom/google/common/primitives/Longs.compare:(JJ)I\ncom/google/inject/Inject\ncom/google/inject/Provider\n"
  },
  {
    "path": "resources/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <artifactId>jclouds-project</artifactId>\n    <groupId>org.apache.jclouds</groupId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../project/pom.xml</relativePath>\n  </parent>    \n  <artifactId>jclouds-resources</artifactId>\n  <name>jclouds shared Maven resources</name>\n\n  <!-- Cannot be run on a clean repo, because of a self-dependency. Install into the \n       local repo with 'mvn clean install' first. -->\n  <build>\n    <resources>\n      <resource>\n        <targetPath>resources</targetPath>\n        <directory>${project.basedir}</directory>\n        <includes>\n          <include>checkstyle.xml</include>\n          <include>checkstyle-suppressions.xml</include>\n          <include>modernizer_exclusions.txt</include>\n        </includes>\n      </resource>\n    </resources>\n    <plugins>\n      <plugin>\n        <artifactId>maven-checkstyle-plugin</artifactId>\n        <configuration>\n          <configLocation>checkstyle.xml</configLocation>\n          <includeTestSourceDirectory>true</includeTestSourceDirectory>\n          <failOnViolation>true</failOnViolation>\n          <failsOnError>true</failsOnError>\n          <!-- fails on itself as it uses the author tag in a module definition -->\n          <resourceExcludes>checkstyle.xml</resourceExcludes>\n          <violationSeverity>warning</violationSeverity>\n        </configuration>\n      </plugin>\n      <plugin>\n        <groupId>org.gaul</groupId>\n        <artifactId>modernizer-maven-plugin</artifactId>\n        <configuration>\n          <javaVersion>1.7</javaVersion>\n          <!-- ${project.basedir} required here as 1.1.0 of the modernizer plugin\n            can't find the exclusions file otherwise -->\n          <exclusionsFile>${project.basedir}/modernizer_exclusions.txt</exclusionsFile>\n        </configuration>\n      </plugin>\n    </plugins>\n  </build>\n</project>\n"
  },
  {
    "path": "scriptbuilder/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.scriptbuilder.*;version=\"${project.version}\";-noimport:=true\n\nBundle-Activator: \\\n    org.jclouds.scriptbuilder.functionloader.osgi.Activator\n"
  },
  {
    "path": "scriptbuilder/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../project/pom.xml</relativePath>\n  </parent>\n  <artifactId>jclouds-scriptbuilder</artifactId>\n  <name>jclouds script builder</name>\n  <description>creates scripts that can be used to manage services</description>\n\n  <properties>\n    <jclouds.test.listener />\n  </properties>\n\n  <dependencies>\n    <dependency>\n      <groupId>${project.groupId}</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.gaul</groupId>\n      <artifactId>modernizer-maven-annotations</artifactId>\n      <optional>true</optional>\n    </dependency>\n    <dependency>\n      <groupId>org.osgi</groupId>\n      <artifactId>org.osgi.core</artifactId>\n      <scope>provided</scope>\n    </dependency>\n  </dependencies>\n\n</project>\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/EnvBuilder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\n\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.jclouds.scriptbuilder.domain.ShellToken;\nimport org.jclouds.scriptbuilder.util.Utils;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Maps;\n\n/**\n * Creates an environment file\n */\npublic class EnvBuilder {\n\n   @VisibleForTesting\n   Map<String, String> variables = Maps.newHashMap();\n\n   /**\n    * Exports a variable inside the script\n    * \n    * @param name name of the variable in UPPER_UNDERSCORE case format\n    */\n   public EnvBuilder export(String name, String value) {\n      variables.put(checkNotNull(name, \"name\"), checkNotNull(value, \"value\"));\n      return this;\n   }\n\n   /**\n    * builds the environment file, by adding the following\n    * <ol>\n    * <li>example usage</li>\n    * <li>variable exports</li>\n    * <li>return statement</li>\n    * </ol>\n    * \n    * @param osFamily\n    *           whether to write a cmd or bash script.\n    */\n   public String build(final OsFamily osFamily) {\n      StringBuilder builder = new StringBuilder();\n      builder.append(Utils.writeComment(\" Env file: please do not confuse people by making this executable\", osFamily));\n      builder.append(Utils.writeComment(\"\", osFamily));\n      builder.append(Utils.writeComment(\" Example usage to set a variable\", osFamily));\n      builder.append(Utils.writeComment(\"\", osFamily));\n      builder.append(Utils.writeComment(\" \"\n               + Utils.writeVariableExporters(ImmutableMap.of(\"MAVEN_OPTS\", \"-Xms64m -Xmx128m\"),\n                        osFamily), osFamily));\n      builder.append(Utils.writeVariableExporters(variables, osFamily));\n      builder.append(ShellToken.LF.to(osFamily));\n      builder.append(Utils.writeComment(\n               \" Please retain this statement so that the script can be validated\", osFamily));\n      builder.append(ShellToken.RETURN.to(osFamily)).append(\" 0\")\n               .append(ShellToken.LF.to(osFamily));\n      return builder.toString();\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/ExitInsteadOfReturn.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder;\n\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.jclouds.scriptbuilder.domain.ShellToken;\nimport org.jclouds.scriptbuilder.domain.Statement;\n\nimport com.google.common.collect.ForwardingObject;\n\n/**\n * you cannot return from a top-level script, so if you are using snippets that\n * issue {@code return} then you'll want to wrap them in this.\n */\npublic class ExitInsteadOfReturn extends ForwardingObject implements Statement {\n   private final Statement delegate;\n\n   public ExitInsteadOfReturn(Statement delegate) {\n      this.delegate = delegate;\n   }\n\n   @Override\n   public Iterable<String> functionDependencies(OsFamily family) {\n      return delegate().functionDependencies(family);\n   }\n\n   @Override\n   public String render(OsFamily family) {\n      return delegate().render(family).toString().replaceAll(ShellToken.RETURN.to(family), ShellToken.EXIT.to(family));\n   }\n\n   @Override\n   protected Statement delegate() {\n      return delegate;\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/InitScript.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.concat;\nimport static java.lang.String.format;\nimport static org.jclouds.scriptbuilder.ScriptBuilder.call;\nimport static org.jclouds.scriptbuilder.ScriptBuilder.findPid;\nimport static org.jclouds.scriptbuilder.ScriptBuilder.forget;\nimport static org.jclouds.scriptbuilder.domain.Statements.createRunScript;\nimport static org.jclouds.scriptbuilder.domain.Statements.interpret;\nimport static org.jclouds.scriptbuilder.domain.Statements.kill;\nimport static org.jclouds.scriptbuilder.domain.Statements.newStatementList;\nimport static org.jclouds.scriptbuilder.domain.Statements.switchArg;\n\nimport java.util.Map;\n\nimport org.jclouds.scriptbuilder.domain.AcceptsStatementVisitor;\nimport org.jclouds.scriptbuilder.domain.CreateRunScript;\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.jclouds.scriptbuilder.domain.Statement;\nimport org.jclouds.scriptbuilder.domain.StatementList;\nimport org.jclouds.scriptbuilder.domain.StatementVisitor;\n\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ForwardingObject;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Creates an init script file\n */\npublic class InitScript extends ForwardingObject implements Statement, AcceptsStatementVisitor {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n      protected String instanceName;\n      protected String instanceHome = \"{tmp}{fs}{varl}INSTANCE_NAME{varr}\";\n      protected String logDir = \"{varl}INSTANCE_HOME{varr}\";\n      protected Map<String, String> exports = ImmutableMap.of();\n      protected StatementList init = new StatementList();\n      protected StatementList run = new StatementList();\n\n      /**\n       * @see InitScript#getInstanceName()\n       */\n      public Builder name(String instanceName) {\n         this.instanceName = checkNotNull(instanceName, \"INSTANCE_NAME\");\n         return this;\n      }\n\n      /**\n       * @see InitScript#getInstanceHome()\n       */\n      public Builder home(String instanceHome) {\n         this.instanceHome = checkNotNull(instanceHome, \"INSTANCE_HOME\");\n         return this;\n      }\n\n      /**\n       * @see InitScript#getLogDir()\n       */\n      public Builder logDir(String logDir) {\n         this.logDir = checkNotNull(logDir, \"LOG_DIR\");\n         return this;\n      }\n\n      /**\n       * @param exports keys are the variables to export in UPPER_UNDERSCORE case format\n       * @see InitScript#getExportedVariables()\n       */\n      public Builder exportVariables(Map<String, String> exports) {\n         this.exports = ImmutableMap.copyOf(checkNotNull(exports, \"exports\"));\n         return this;\n      }\n\n      /**\n       * @see InitScript#getRun()\n       */\n      public Builder run(Statement run) {\n         this.run = new StatementList(checkNotNull(run, \"run\"));\n         return this;\n      }\n\n      /**\n       * @see InitScript#getRun()\n       */\n      public Builder run(Statement... run) {\n         this.run = new StatementList(checkNotNull(run, \"run\"));\n         return this;\n      }\n\n      /**\n       * @see InitScript#getRun()\n       */\n      public Builder run(Iterable<Statement> run) {\n         this.run = new StatementList(checkNotNull(run, \"run\"));\n         return this;\n      }\n\n      /**\n       * @see InitScript#getRun()\n       */\n      public Builder run(StatementList run) {\n         this.run = checkNotNull(run, \"run\");\n         return this;\n      }\n\n      /**\n       * @see InitScript#getInit()\n       */\n      public Builder init(Statement init) {\n         this.init = new StatementList(checkNotNull(init, \"init\"));\n         return this;\n      }\n\n      /**\n       * @see InitScript#getInit()\n       */\n      public Builder init(Statement... init) {\n         this.init = new StatementList(checkNotNull(init, \"init\"));\n         return this;\n      }\n\n      /**\n       * @see InitScript#getInit()\n       */\n      public Builder init(Iterable<Statement> init) {\n         this.init = new StatementList(checkNotNull(init, \"init\"));\n         return this;\n      }\n\n      /**\n       * @see InitScript#getInit()\n       */\n      public Builder init(StatementList init) {\n         this.init = checkNotNull(init, \"init\");\n         return this;\n      }\n\n      public InitScript build() {\n         return new InitScript(instanceName, instanceHome, logDir, exports, init, run);\n      }\n\n   }\n\n   protected final String instanceName;\n   protected final String instanceHome;\n   protected final String logDir;\n   protected final Map<String, String> exports;\n   protected final StatementList init;\n   protected final StatementList run;\n   protected final ScriptBuilder delegate;\n\n   /**\n    * @param exports keys are the variables to export in UPPER_UNDERSCORE case format\n    */\n   protected InitScript(String instanceName, String instanceHome, String logDir, Map<String, String> exports,\n         StatementList init, StatementList run) {\n      this.instanceName = checkNotNull(instanceName, \"INSTANCE_NAME\");\n      this.instanceHome = checkNotNull(instanceHome, \"INSTANCE_HOME\");\n      this.logDir = checkNotNull(logDir, \"LOG_DIR\");\n      this.exports = ImmutableMap.<String, String> copyOf(checkNotNull(exports, \"exports\"));\n      this.init = checkNotNull(init, \"init\");\n      this.run = checkNotNull(run, \"run\");\n      checkArgument(!run.delegate().isEmpty(), \"you must specify at least one statement to run\");\n      this.delegate = makeInitScriptStatement(instanceName, instanceHome, logDir, exports, init, run);\n   }\n\n   /**\n    *\n    * @param exports keys are the variables to export in UPPER_UNDERSCORE case format\n    */\n   public static ScriptBuilder makeInitScriptStatement(String instanceName, String instanceHome, String logDir,\n         Map<String, String> exports, StatementList init, StatementList run) {\n      Map<String, String> defaultExports = ImmutableMap.of(\"INSTANCE_NAME\", instanceName, \"INSTANCE_HOME\", instanceHome,\n            \"LOG_DIR\", logDir);\n      String exitStatusFile = format(\"%s/rc\", logDir);\n      run = new StatementList(ImmutableList.<Statement> builder().add(interpret(\"rm -f \" + exitStatusFile))\n            .add(interpret(format(\"trap 'echo $?>%s' 0 1 2 3 15\", exitStatusFile))).addAll(run.delegate()).build());\n\n      CreateRunScript createRunScript = createRunScript(instanceName,\n            concat(exports.keySet(), defaultExports.keySet()), \"{varl}INSTANCE_HOME{varr}\", run);\n\n      return new ScriptBuilder()\n            .addEnvironmentVariableScope(\"default\", defaultExports)\n            .addEnvironmentVariableScope(instanceName, exports)\n            .addStatement(\n                  switchArg(\n                        1,\n                        new ImmutableMap.Builder<String, Statement>()\n                              .put(\"init\", newStatementList(call(\"default\"), call(instanceName), init, createRunScript))\n                              .put(\"status\",\n                                    newStatementList(call(\"default\"), findPid(\"{varl}INSTANCE_NAME{varr}\"),\n                                          interpret(\"echo {varl}FOUND_PID{varr}{lf}\")))\n                              .put(\"stop\",\n                                    newStatementList(call(\"default\"), findPid(\"{varl}INSTANCE_NAME{varr}\"), kill()))\n                              .put(\"start\",\n                                    newStatementList(\n                                          call(\"default\"),\n                                          forget(\"{varl}INSTANCE_NAME{varr}\",\n                                                \"{varl}INSTANCE_HOME{varr}{fs}{varl}INSTANCE_NAME{varr}.{sh}\",\n                                                \"{varl}LOG_DIR{varr}\")))\n                              .put(\"stdout\",\n                                    newStatementList(call(\"default\"),\n                                          interpret(\"cat {varl}LOG_DIR{varr}{fs}stdout.log{lf}\")))\n                              .put(\"stderr\",\n                                    newStatementList(call(\"default\"),\n                                          interpret(\"cat {varl}LOG_DIR{varr}{fs}stderr.log{lf}\")))\n                              .put(\"exitstatus\",\n                                    newStatementList(call(\"default\"),\n                                          interpret(\"[ -f $LOG_DIR/rc ] && cat $LOG_DIR/rc\")))\n                              .put(\"tail\",\n                                    newStatementList(call(\"default\"),\n                                          interpret(\"tail {varl}LOG_DIR{varr}{fs}stdout.log{lf}\")))\n                              .put(\"tailerr\",\n                                    newStatementList(call(\"default\"),\n                                          interpret(\"tail {varl}LOG_DIR{varr}{fs}stderr.log{lf}\")))\n                              .put(\"run\",\n                                    newStatementList(call(\"default\"),\n                                          interpret(\"{varl}INSTANCE_HOME{varr}{fs}{varl}INSTANCE_NAME{varr}.{sh}{lf}\")))\n                              .build()));\n   }\n\n   /**\n    *\n    * @return what will be bound to the INSTANCE_NAME variable, and uniquely\n    *         identifies the process\n    */\n   public String getInstanceName() {\n      return instanceName;\n   }\n\n   /**\n    * default {@code /tmp/$INSTANCE_NAME}\n    * <br/>\n    * <h3>note</h3> The parent directory\n    * should be set with unix sticky-bit or otherwise made available to all\n    * users. Otherwise, new instances by other users may fail due to not being\n    * able to create a directory.  This is why the default is set to {@code /tmp}\n    *\n    * @return what will be bound to the INSTANCE_HOME variable, and represents\n    *         the working directory of the instance\n    */\n   public String getInstanceHome() {\n      return instanceHome;\n   }\n\n   /**\n    * default {@code $INSTANCE_HOME}\n    *\n    * @return what will be bound to the LOG_DIR variable, and represents where\n    *         stdout and stderr.logs are written.\n    */\n   public String getLogDir() {\n      return logDir;\n   }\n\n   /**\n    *\n    * @return statements that will be executed upon the init command\n    */\n   public StatementList getInitStatement() {\n      return init;\n   }\n\n   /**\n    *\n    * @return statements that will be executed upon the run or start commands\n    */\n   public StatementList getRunStatement() {\n      return init;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(instanceName);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (obj == null)\n         return false;\n      if (!(obj instanceof InitScript)) {\n         return false;\n      }\n      InitScript that = (InitScript) obj;\n      return equal(this.instanceName, that.instanceName);\n   }\n\n   @Override\n   public String toString() {\n      return toStringHelper(this).add(\"INSTANCE_NAME\", instanceName).toString();\n   }\n\n   @Override\n   public void accept(StatementVisitor visitor) {\n      delegate().accept(visitor);\n   }\n\n   @Override\n   public Iterable<String> functionDependencies(OsFamily family) {\n      return delegate().functionDependencies(family);\n   }\n\n   @Override\n   public String render(OsFamily family) {\n      return delegate().render(family);\n   }\n\n   @Override\n   protected ScriptBuilder delegate() {\n      return delegate;\n   }\n\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/ScriptBuilder.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.Set;\n\nimport org.jclouds.scriptbuilder.domain.AcceptsStatementVisitor;\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.jclouds.scriptbuilder.domain.ShellToken;\nimport org.jclouds.scriptbuilder.domain.Statement;\nimport org.jclouds.scriptbuilder.domain.StatementVisitor;\nimport org.jclouds.scriptbuilder.domain.Statements;\nimport org.jclouds.scriptbuilder.util.Utils;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableMap.Builder;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Lists;\nimport com.google.common.collect.Maps;\nimport com.google.common.collect.Sets;\n\n/**\n * Creates a shell script.\n */\npublic class ScriptBuilder implements Statement, AcceptsStatementVisitor {\n\n   @VisibleForTesting\n   List<Statement> statements = Lists.newArrayList();\n\n   @VisibleForTesting\n   Map<String, Map<String, String>> variableScopes = Maps.newLinkedHashMap();\n\n   @VisibleForTesting\n   List<String> variablesToUnset = Lists.newArrayList(\"PATH\", \"JAVA_HOME\", \"LIBRARY_PATH\");\n\n   public ScriptBuilder addStatement(Statement statement) {\n      statements.add(checkNotNull(statement, \"statement\"));\n      return this;\n   }\n\n   /**\n    * Unsets a variable to ensure it is set within the script.\n    * @param variable name in UPPER_UNDERSCORE case format\n    */\n   public ScriptBuilder unsetEnvironmentVariable(String name) {\n      variablesToUnset.add(checkNotNull(name, \"name\"));\n      return this;\n   }\n\n   /**\n    * Exports a variable inside the script\n    * @param scopeName\n    * @param variables keys are the variables to export in UPPER_UNDERSCORE case format\n    */\n   public ScriptBuilder addEnvironmentVariableScope(String scopeName, Map<String, String> variables) {\n      variableScopes.put(checkNotNull(scopeName, \"scopeName\"), checkNotNull(variables, \"variables\"));\n      return this;\n   }\n\n   // TODO: make scriptbuilder smart enough to know when a statement is a direct\n   // child of the script, and automatically convert\n   public static Statement forget(String instanceName, String script, String logDir) {\n      return new ExitInsteadOfReturn(Statements.forget(instanceName, script, logDir));\n   }\n\n   public static Statement findPid(String pid) {\n      return new ExitInsteadOfReturn(Statements.findPid(pid));\n   }\n\n   public static Statement call(String fn, String... args) {\n      return new ExitInsteadOfReturn(Statements.call(fn, args));\n   }\n\n   /**\n    * builds the shell script, by adding the following\n    * <ol>\n    * <li>shell declaration line</li>\n    * <li>variable exports</li>\n    * <li>case/switch</li>\n    * </ol>\n    *\n    * @param osFamily\n    *           whether to write a cmd or bash script.\n    */\n\n   @Override\n   public String render(OsFamily osFamily) {\n      Map<String, String> functions = Maps.newLinkedHashMap();\n      functions.put(\"abort\", Utils.writeFunctionFromResource(\"abort\", osFamily));\n\n      for (Entry<String, Map<String, String>> entry : variableScopes.entrySet()) {\n         functions.put(entry.getKey(), Utils.writeFunction(entry.getKey(), Utils.writeVariableExporters(entry\n                  .getValue(), osFamily)));\n      }\n      StringBuilder builder = new StringBuilder();\n      builder.append(ShellToken.BEGIN_SCRIPT.to(osFamily));\n      builder.append(Utils.writeUnsetVariables(variablesToUnset, osFamily));\n      Map<String, String> functionsToWrite = resolveFunctionDependenciesForStatements(functions, statements, osFamily);\n      writeFunctions(functionsToWrite, osFamily, builder);\n      builder.append(Utils.writeZeroPath(osFamily));\n      StringBuilder statementBuilder = new StringBuilder();\n      for (Statement statement : statements) {\n         statementBuilder.append(statement.render(osFamily));\n      }\n      builder.append(statementBuilder.toString());\n      builder.append(ShellToken.END_SCRIPT.to(osFamily));\n      return builder.toString();\n   }\n\n   public static void writeFunctions(Map<String, String> functionsToWrite, OsFamily osFamily, StringBuilder builder) {\n      if (!functionsToWrite.isEmpty()) {\n         builder.append(ShellToken.BEGIN_FUNCTIONS.to(osFamily));\n         for (String function : functionsToWrite.values()) {\n            builder.append(Utils.replaceTokens(function, ShellToken.tokenValueMap(osFamily)));\n         }\n         builder.append(ShellToken.END_FUNCTIONS.to(osFamily));\n      }\n   }\n\n   @VisibleForTesting\n   public static Map<String, String> resolveFunctionDependenciesForStatements(Map<String, String> knownFunctions,\n         Iterable<Statement> statements, final OsFamily osFamily) {\n      Builder<String, String> builder = ImmutableMap.builder();\n      builder.putAll(knownFunctions);\n      Set<String> dependentFunctions = ImmutableSet.copyOf(Iterables.concat(Iterables.transform(statements,\n            new Function<Statement, Iterable<String>>() {\n               @Override\n               public Iterable<String> apply(Statement from) {\n                  return from.functionDependencies(osFamily);\n               }\n            })));\n      for (String unresolved : Sets.difference(dependentFunctions, knownFunctions.keySet()))\n         builder.put(unresolved, Utils.writeFunctionFromResource(unresolved, osFamily));\n      return builder.build();\n   }\n\n   @Override\n   public Iterable<String> functionDependencies(OsFamily family) {\n      return ImmutableSet.<String> of();\n   }\n\n   @Override\n   public void accept(StatementVisitor visitor) {\n      for (Statement statement : statements) {\n         visitor.visit(statement);\n      }\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/domain/AcceptsStatementVisitor.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.domain;\n\npublic interface AcceptsStatementVisitor {\n\n   void accept(StatementVisitor visitor);\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/domain/AdminAccessVisitor.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.domain;\n\nimport org.jclouds.scriptbuilder.statements.login.AdminAccess;\n\npublic abstract class AdminAccessVisitor implements StatementVisitor {\n   public abstract void visit(AdminAccess input);\n\n   @Override\n   public void visit(Statement input) {\n      if (input == null)\n         return;\n      if (input instanceof AcceptsStatementVisitor) {\n         AcceptsStatementVisitor.class.cast(input).accept(this);\n      } else if (input instanceof AdminAccess) {\n         visit(AdminAccess.class.cast(input));\n      }\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/domain/AppendFile.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static org.jclouds.scriptbuilder.domain.Statements.interpret;\n\nimport java.util.Map;\nimport java.util.Map.Entry;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Maps;\n\n/**\n * Creates a run script\n */\npublic class AppendFile implements Statement {\n   public static final String DELIMITER = \"END_OF_JCLOUDS_FILE\";\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n      protected String path;\n      protected Iterable<String> lines = ImmutableSet.of();\n      protected String delimiter = DELIMITER;\n      protected boolean expandVariables;\n\n      /**\n       * @see AppendFile#getPath()\n       */\n      public Builder path(String path) {\n         this.path = path;\n         return this;\n      }\n\n      /**\n       * @see AppendFile#getLines()\n       */\n      public Builder lines(Iterable<String> lines) {\n         this.lines = ImmutableList.copyOf(lines);\n         return this;\n      }\n\n      /**\n       * @see AppendFile#getDelimiter()\n       */\n      public Builder delimiter(String delimiter) {\n         this.delimiter = delimiter;\n         return this;\n      }\n\n      /**\n       * @see AppendFile#shouldExpandVariables()\n       */\n      public Builder expandVariables(boolean expandVariables) {\n         this.expandVariables = expandVariables;\n         return this;\n      }\n\n      public AppendFile build() {\n         return new AppendFile(path, lines, delimiter, expandVariables);\n      }\n   }\n\n   protected final String path;\n   protected final Iterable<String> lines;\n   protected final String delimiter;\n   protected final boolean expandVariables;\n\n   protected AppendFile(String path, Iterable<String> lines, String delimiter, boolean expandVariables) {\n      this.path = checkNotNull(path, \"PATH\");\n      this.lines = checkNotNull(lines, \"lines\");\n      this.delimiter = checkNotNull(delimiter, \"delimiter\");\n      checkState(!Iterables.isEmpty(lines), \"you must pass something to execute\");\n      this.expandVariables = expandVariables;\n   }\n\n   public static String escapeVarTokens(String toEscape, OsFamily family) {\n      Map<String, String> inputToEscape = Maps.newHashMap();\n      for (ShellToken token : ImmutableList.of(ShellToken.VARL, ShellToken.VARR)) {\n         if (!token.to(family).equals(\"\")) {\n            String tokenS = \"{\" + token.toString().toLowerCase() + \"}\";\n            inputToEscape.put(tokenS, \"{escvar}\" + tokenS);\n         }\n      }\n      for (Entry<String, String> entry : inputToEscape.entrySet()) {\n         toEscape = toEscape.replace(entry.getKey(), entry.getValue());\n      }\n      return toEscape;\n   }\n\n   @Override\n   public Iterable<String> functionDependencies(OsFamily family) {\n      return ImmutableList.of();\n   }\n\n   @Override\n   public String render(OsFamily family) {\n      if (family == OsFamily.UNIX) {\n         return interpret(hereFile()).render(family);\n      } else {\n         return interpret(appendToWindowsFile()).render(family);\n      }\n   }\n\n   protected String appendToWindowsFile() {\n      StringBuilder builder = new StringBuilder();\n      for (String line : lines) {\n         builder.append(appendLineToWindowsFile(line, path));\n      }\n      return builder.toString();\n   }\n\n   protected String hereFile() {\n      StringBuilder hereFile = startHereFile();\n      for (String line : lines) {\n         hereFile.append('\\t').append(line).append(\"\\n\");\n      }\n      hereFile.append(delimiter).append(\"\\n\");\n      return hereFile.toString();\n   }\n\n   public StringBuilder startHereFile() {\n      StringBuilder hereFile = new StringBuilder().append(\"cat >> \").append(path);\n      if (expandVariables)\n         return hereFile.append(\" <<-\").append(delimiter).append(\"\\n\");\n      return hereFile.append(\" <<-'\").append(delimiter).append(\"'\\n\");\n   }\n\n   protected String appendLineToWindowsFile(String line, String path) {\n      String quote = \"\";\n      if (!ShellToken.VQ.to(OsFamily.WINDOWS).equals(\"\")) {\n         quote = \"'\";\n      } else {\n         line = escapeVarTokens(line, OsFamily.WINDOWS);\n      }\n      return String.format(\"echo %s%s%s >>%s{lf}\", quote, line, quote, path);\n   }\n\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/domain/Call.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Arrays;\nimport java.util.Map;\n\nimport org.jclouds.scriptbuilder.util.Utils;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Statement used in a shell script\n */\npublic class Call implements Statement {\n\n   public static final Map<OsFamily, String> OS_TO_CALL = ImmutableMap.of(OsFamily.UNIX,\n            \"{function}{args} || return 1\\n\", OsFamily.WINDOWS,\n            \"call :{function}{args}\\r\\nif errorlevel 1 goto abort\\r\\n\");\n\n   private String function;\n   private String[] args;\n\n   public Call(String function, String... args) {\n      this.function = checkNotNull(function, \"function\");\n      this.args = checkNotNull(args, \"args\");\n   }\n\n   public String render(OsFamily family) {\n      StringBuilder args = new StringBuilder();\n      for (String arg : this.args) {\n         args.append(\" \").append(Utils.replaceTokens(arg, ShellToken.tokenValueMap(family)));\n      }\n      StringBuilder call = new StringBuilder();\n      call.append(Utils.replaceTokens(OS_TO_CALL.get(family), ImmutableMap.of(\"function\", function,\n               \"args\", args.toString())));\n      return call.toString();\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + Arrays.hashCode(args);\n      result = prime * result + ((function == null) ? 0 : function.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      Call other = (Call) obj;\n      if (!Arrays.equals(args, other.args))\n         return false;\n      if (function == null) {\n         if (other.function != null)\n            return false;\n      } else if (!function.equals(other.function))\n         return false;\n      return true;\n   }\n\n   @Override\n   public Iterable<String> functionDependencies(OsFamily family) {\n      return ImmutableList.of(function);\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/domain/CreateOrOverwriteFile.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.domain;\n\n\n/**\n * Creates a run script\n */\npublic class CreateOrOverwriteFile extends AppendFile {\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder extends AppendFile.Builder {\n\n      @Override\n      public Builder path(String path) {\n         return Builder.class.cast(super.path(path));\n      }\n\n      @Override\n      public Builder lines(Iterable<String> lines) {\n         return Builder.class.cast(super.lines(lines));\n      }\n\n      @Override\n      public Builder delimiter(String delimiter) {\n         return Builder.class.cast(super.delimiter(delimiter));\n      }\n\n      @Override\n      public Builder expandVariables(boolean expandVariables) {\n         return Builder.class.cast(super.expandVariables(expandVariables));\n      }\n\n      @Override\n      public CreateOrOverwriteFile build() {\n         return new CreateOrOverwriteFile(path, lines, delimiter, expandVariables);\n      }\n\n   }\n\n   protected CreateOrOverwriteFile(String path, Iterable<String> lines, String delimiter, boolean expandVariables) {\n      super(path, lines, delimiter, expandVariables);\n   }\n\n   @Override\n   protected String appendToWindowsFile() {\n      return String.format(\"copy /y CON %s{lf}\", path) + super.appendToWindowsFile();\n   }\n\n   @Override\n   public StringBuilder startHereFile() {\n      StringBuilder hereFile = new StringBuilder().append(\"cat > \").append(path);\n      if (expandVariables)\n         return hereFile.append(\" <<-\").append(delimiter).append(\"\\n\");\n      return hereFile.append(\" <<-'\").append(delimiter).append(\"'\\n\");\n   }\n\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/domain/CreateRunScript.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Predicates.instanceOf;\nimport static com.google.common.collect.Iterables.any;\nimport static com.google.common.collect.Lists.newArrayList;\nimport static java.lang.String.format;\nimport static org.jclouds.scriptbuilder.domain.Statements.appendFile;\nimport static org.jclouds.scriptbuilder.domain.Statements.createOrOverwriteFile;\nimport static org.jclouds.scriptbuilder.domain.Statements.exec;\nimport static org.jclouds.scriptbuilder.domain.Statements.interpret;\n\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.scriptbuilder.ExitInsteadOfReturn;\nimport org.jclouds.scriptbuilder.ScriptBuilder;\nimport org.jclouds.scriptbuilder.util.Utils;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableList.Builder;\nimport com.google.common.collect.Iterables;\n\n/**\n * Creates a run script\n */\npublic class CreateRunScript extends StatementList {\n   public static final String DELIMITER = \"END_OF_JCLOUDS_SCRIPT\";\n   final String instanceName;\n   final Iterable<String> exports;\n   final String pwd;\n   \n   /**\n    * @param exports\n    *            variable names to export in UPPER_UNDERSCORE case format\n    */\n   public CreateRunScript(String instanceName, Iterable<String> exports, String pwd, Iterable<Statement> statements) {\n      super(statements);\n      this.instanceName = checkNotNull(instanceName, \"INSTANCE_NAME\");\n      this.exports = checkNotNull(exports, \"exports\");\n      this.pwd = checkNotNull(pwd, \"pwd\").replaceAll(\"[/\\\\\\\\]\", \"{fs}\");\n   }\n\n   public static class AddExport implements Statement {\n      final String export;\n      final String value;\n      \n      /**\n       * @param export\n       *            variable name in UPPER_UNDERSCORE case format\n       */\n      public AddExport(String export, String value) {\n         this.export = checkNotNull(export, \"export\");\n         this.value = checkNotNull(value, \"value\");\n      }\n\n      public static final Map<OsFamily, String> OS_TO_EXPORT_PATTERN = ImmutableMap.of(OsFamily.UNIX,\n            \"export {export}='{value}'\\n\", OsFamily.WINDOWS, \"set {export}={value}\\r\\n\");\n\n      @Override\n      public Iterable<String> functionDependencies(OsFamily family) {\n         return ImmutableList.of();\n      }\n\n      @Override\n      public String render(OsFamily family) {\n         return Utils\n               .replaceTokens(OS_TO_EXPORT_PATTERN.get(family), ImmutableMap.of(\"export\", export, \"value\", value));\n      }\n   }\n\n   @Override\n   public Iterable<String> functionDependencies(OsFamily family) {\n      return ImmutableList.of();\n   }\n\n   @Override\n   public String render(OsFamily family) {\n      if (checkNotNull(family, \"family\") == OsFamily.WINDOWS)\n         throw new UnsupportedOperationException(\"windows not yet implemented\");\n      List<Statement> statements = newArrayList();\n      final Map<String, String> tokenMap = ShellToken.tokenValueMap(family);\n      String runScript = Utils.replaceTokens(pwd + \"{fs}\" + instanceName + \".{sh}\", tokenMap);\n      statements.add(interpret(String.format(\"{md} %s{lf}\", pwd)));\n      StringBuilder builder = new StringBuilder();\n      builder.append(\"\\n\");\n      addUnixRunScriptHeader(runScript, builder);\n      builder.append(\"\\n\");\n      addUnixRunScript(runScript, builder);\n      builder.append(\"\\n\");\n      addUnixRunScriptFooter(runScript, builder);\n      builder.append(\"\\n\");\n      statements.add(interpret(builder.toString()));\n      statements.add(exec(\"chmod u+x \" + runScript));\n      return new StatementList(statements).render(family);\n   }\n\n   private void addUnixRunScriptFooter(String runScript, StringBuilder builder) {\n      builder.append(\"# add runscript footer\\n\");\n      Iterable<String> endScript = Splitter.on(ShellToken.LF.to(OsFamily.UNIX)).split(\n            ShellToken.END_SCRIPT.to(OsFamily.UNIX));\n      builder.append(appendFile(runScript, endScript, DELIMITER).render(OsFamily.UNIX));\n   }\n\n   private void addUnixRunScript(String runScript, StringBuilder builder) {\n      builder.append(\"# add desired commands from the user\\n\");\n      Builder<String> userCommands = ImmutableList.builder();\n      userCommands.add(\"cd \" + pwd);\n      for (Statement statement : statements) {\n         if (statement instanceof Call\n               || (statement instanceof StatementList && any(StatementList.class.cast(statement).delegate(),\n                     instanceOf(Call.class)))) {\n            statement = new ExitInsteadOfReturn(statement);\n         }\n         userCommands.addAll(Splitter.on('\\n').split(statement.render(OsFamily.UNIX)));\n      }\n      builder.append(appendFile(runScript, userCommands.build(), DELIMITER).render(OsFamily.UNIX));\n   }\n\n   private void addUnixRunScriptHeader(String runScript, StringBuilder builder) {\n      builder.append(\"# create runscript header\\n\");\n\n      Builder<String> beginningOfFile = ImmutableList.builder();\n      beginningOfFile.addAll(Splitter.on(ShellToken.LF.to(OsFamily.UNIX)).split(\n            ShellToken.BEGIN_SCRIPT.to(OsFamily.UNIX)));\n      beginningOfFile.add(format(\"PROMPT_COMMAND='echo -ne \\\\\\\"\\\\033]0;%s\\\\007\\\\\\\"'\", instanceName));\n      beginningOfFile.add(Utils.writeZeroPath(OsFamily.UNIX));\n      beginningOfFile.add(format(\"export INSTANCE_NAME='%s'\", instanceName));\n      builder.append(createOrOverwriteFile(runScript, beginningOfFile.build(), DELIMITER).render(OsFamily.UNIX));\n\n      // expanding variables here.\n      builder.append(AppendFile.builder().path(runScript).delimiter(DELIMITER).expandVariables(true)\n            .lines(Iterables.transform(exports, new Function<String, String>() {\n\n               @Override\n               public String apply(String export) {\n                  return new StringBuilder().append(\"export \").append(export).append(\"='$\")\n                        .append(export).append(\"'\").toString();\n               }\n            })).build().render(OsFamily.UNIX));\n\n      Map<String, String> functionsToWrite = ScriptBuilder.resolveFunctionDependenciesForStatements(\n            ImmutableMap.<String, String> of(\"abort\", Utils.writeFunctionFromResource(\"abort\", OsFamily.UNIX)),\n            statements, OsFamily.UNIX);\n\n      // if there are more functions than simply abort\n      if (functionsToWrite.size() > 1) {\n         StringBuilder functions = new StringBuilder();\n         ScriptBuilder.writeFunctions(functionsToWrite, OsFamily.UNIX, functions);\n         builder.append(appendFile(runScript, functions.toString(), DELIMITER).render(OsFamily.UNIX));\n      }\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/domain/GitRepoAndRef.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.net.URI;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.Optional;\n\n/**\n * Description of git coordinates to checkout.\n */\npublic class GitRepoAndRef  {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return new Builder().fromGitRepoAndRef(this);\n   }\n\n   public static class Builder {\n\n      protected URI repository;\n      protected Optional<String> branch = Optional.absent();\n      protected Optional<String> tag = Optional.absent();\n\n      /**\n       * @see GitRepoAndRef#getRepository()\n       */\n      public Builder repository(URI repository) {\n         this.repository = repository;\n         return this;\n      }\n\n      /**\n       * @see GitRepoAndRef#getRepository()\n       */\n      public Builder repository(String repository) {\n         return repository(URI.create(repository));\n      }\n\n      /**\n       * @see GitRepoAndRef#getBranch()\n       */\n      public Builder branch(String branch) {\n         this.branch = Optional.fromNullable(branch);\n         return this;\n      }\n\n      /**\n       * @see GitRepoAndRef#getTag()\n       */\n      public Builder tag(String tag) {\n         this.tag = Optional.fromNullable(tag);\n         return this;\n      }\n\n      public GitRepoAndRef build() {\n         return new GitRepoAndRef(repository, branch, tag);\n      }\n\n      public Builder fromGitRepoAndRef(GitRepoAndRef in) {\n         return this.repository(in.getRepository()).branch(in.getBranch().orNull()).tag(in.getTag().orNull());\n      }\n   }\n\n   protected final URI repository;\n   protected final Optional<String> branch;\n   protected final Optional<String> tag;\n\n   protected GitRepoAndRef(URI repository, Optional<String> branch, Optional<String> tag) {\n      this.repository = checkNotNull(repository, \"repository\");\n      this.branch = checkNotNull(branch, \"branch\");\n      this.tag = checkNotNull(tag, \"tag\");\n   }\n\n   /**\n    * The (possibly remote) repository to clone from.\n    */\n   public URI getRepository() {\n      return repository;\n   }\n\n   /**\n    * Instead of pointing the newly created HEAD to the branch pointed to by the cloned repository's\n    * HEAD, point to this branch instead. In a non-bare repository, this is the branch that will be\n    * checked out.\n    */\n   public Optional<String> getBranch() {\n      return branch;\n   }\n\n   /**\n    * checkout the following tag on the branch\n    */\n   public Optional<String> getTag() {\n      return tag;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(repository, branch, tag);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      GitRepoAndRef other = GitRepoAndRef.class.cast(obj);\n      return Objects.equal(this.repository, other.repository) && Objects.equal(this.branch, other.branch)\n               && Objects.equal(this.tag, other.tag);\n   }\n\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"repository\", repository).add(\"branch\", branch.orNull())\n               .add(\"tag\", tag.orNull()).toString();\n   }\n\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/domain/InitMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.net.URI;\n\n/**\n * Defines the environment of a process that can be started in the background on an operating\n * system.\n */\npublic class InitMetadata {\n\n   private final String name;\n   private final String platformHome;\n   private final URI endPoint;\n   private final String startDir;\n   private final String stopDir;\n   private final String configDir;\n   private final String dataDir;\n   private final String logDir;\n   private final String goldDir;\n\n   public InitMetadata(String name, String platformHome, URI endPoint, String startDir,\n            String stopDir, String configDir, String dataDir, String logDir, String goldDir) {\n      this.name = checkNotNull(name, \"name\");\n      this.platformHome = checkNotNull(platformHome, \"platformHome\");\n      this.endPoint = endPoint;\n      this.startDir = checkNotNull(startDir, \"startDir\");\n      this.stopDir = checkNotNull(stopDir, \"stopDir\");\n      this.configDir = checkNotNull(configDir, \"configDir\");\n      this.dataDir = checkNotNull(dataDir, \"dataDir\");\n      this.logDir = checkNotNull(logDir, \"LOG_DIR\");\n      this.goldDir = checkNotNull(goldDir, \"goldDir\");\n   }\n\n   /**\n    * working directory when starting the server.\n    */\n   public String getStartDir() {\n      return startDir;\n   }\n\n   /**\n    * working directory when stopping the server.\n    */\n   public String getStopDir() {\n      return stopDir;\n   }\n\n   /**\n    * Where the platform that this process is an instance of is located. This is analogous to the\n    * CATALINA_HOME on the tomcat platform.\n    */\n   public String getPlatformHome() {\n      return platformHome;\n   }\n\n   /**\n    * what uniquely identifies your process in a listing. Note that this will become a part of the\n    * process args.\n    */\n   public String getName() {\n      return name;\n   }\n\n   /**\n    * holds configuration files of the process. These are generated or copied from data in the\n    * {@link #getGoldDir gold copy directory}.\n    */\n   public String getConfigDir() {\n      return configDir;\n   }\n\n   /**\n    * holds files that are generated at runtime, but are not temporary. Ex. customer data, state,\n    * etc. These files survive recreation of the instance.\n    */\n   public String getDataDir() {\n      return dataDir;\n   }\n\n   /**\n    * where all logs are written. The following files are created here:\n    * <ul>\n    * <li>stdout.log - where stdout is piped to upon start.</li>\n    * <li>stderr.log - where stderr is piped to upon start.</li>\n    * <li>pid.log - holds the process id, if the process is running.</li>\n    * </ul>\n    */\n   public String getLogDir() {\n      return logDir;\n   }\n\n   /**\n    * on-disk, read-only location of the artifacts needed to recreate this process.\n    */\n   public String getGoldDir() {\n      return goldDir;\n   }\n\n   /**\n    * the named ip and port that this process will bind server sockets to, as well the protocol used\n    * to test it.\n    */\n   public URI getEndPoint() {\n      return endPoint;\n   }\n\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/domain/InterpretableStatement.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Arrays;\n\nimport org.jclouds.scriptbuilder.util.Utils;\n\nimport com.google.common.base.Joiner;\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Statement used in a shell script\n */\npublic class InterpretableStatement implements Statement {\n\n   private String[] statements;\n\n   public InterpretableStatement(String... statements) {\n      this.statements = checkNotNull(statements, \"statements\");\n   }\n\n   public String render(OsFamily family) {\n      return Utils\n               .replaceTokens(Joiner.on(ShellToken.LF.to(family)).join(statements), ShellToken.tokenValueMap(family));\n   }\n\n   @Override\n   public Iterable<String> functionDependencies(OsFamily family) {\n      return ImmutableList.of();\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + Arrays.hashCode(statements);\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      InterpretableStatement other = (InterpretableStatement) obj;\n      if (!Arrays.equals(statements, other.statements))\n         return false;\n      return true;\n   }\n\n   @Override\n   public String toString() {\n      return \"[statements=\" + Arrays.toString(statements) + \"]\";\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/domain/JavaInitMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.net.URI;\n\n/**\n * Defines the environment of a java process that can be started in the background on an operating\n * system.\n * \n * @see InitMetadata\n */\npublic class JavaInitMetadata extends InitMetadata {\n   private final String javaHome;\n   private final String[] classpath;\n   private final String mainClass;\n   private final String[] opts;\n   private final String[] args;\n\n   public JavaInitMetadata(String name, String platformHome, URI endPoint, String startDir,\n            String stopDir, String configDir, String dataDir, String logDir, String goldDir,\n            String javaHome, String[] classpath, String mainClass, String[] opts, String[] args) {\n      super(name, platformHome, endPoint, startDir, stopDir, configDir, dataDir, logDir, goldDir);\n      this.javaHome = checkNotNull(javaHome, \"JAVA_HOME\");\n      this.classpath = checkNotNull(classpath, \"classpath\");\n      this.mainClass = checkNotNull(mainClass, \"mainClass\");\n      this.opts = checkNotNull(opts, \"opts\");\n      this.args = checkNotNull(args, \"args\");\n   }\n\n   public String getJavaHome() {\n      return javaHome;\n   }\n\n   public String[] getClasspath() {\n      return classpath;\n   }\n\n   public String getMainClass() {\n      return mainClass;\n   }\n\n   public String[] getOpts() {\n      return opts;\n   }\n\n   public String[] getArgs() {\n      return args;\n   }\n\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/domain/Kill.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Statement used in a shell script\n */\npublic class Kill implements Statement {\n\n   public static final Map<OsFamily, String> OS_TO_KILL = ImmutableMap.of(OsFamily.UNIX,\n            \"[ -n \\\"$FOUND_PID\\\" ]  && {\\n   echo stopping $FOUND_PID\\n   kill -9 $FOUND_PID\\n}\\n\",\n            OsFamily.WINDOWS,\n            \"if defined FOUND_PID (\\r\\n   TASKKILL /F /T /PID %FOUND_PID% >NUL\\r\\n)\\r\\n\");\n\n   public Kill() {\n   }\n\n   public String render(OsFamily family) {\n      return OS_TO_KILL.get(checkNotNull(family, \"family\"));\n   }\n\n   @Override\n   public Iterable<String> functionDependencies(OsFamily family) {\n      return ImmutableList.of();\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/domain/LiteralStatement.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Statement used in a shell script without modifications apart from a trailing newline.\n */\npublic class LiteralStatement implements Statement {\n\n   private String statement;\n\n   public LiteralStatement(String statement) {\n      this.statement = checkNotNull(statement, \"statement\");\n   }\n\n   public String render(OsFamily family) {\n      return statement + ShellToken.LF.to(family);\n   }\n\n   @Override\n   public Iterable<String> functionDependencies(OsFamily family) {\n      return ImmutableList.of();\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(statement);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (!(obj instanceof LiteralStatement))\n         return false;\n      LiteralStatement other = LiteralStatement.class.cast(obj);\n      return Objects.equal(statement, other.statement);\n   }\n\n   @Override\n   public String toString() {\n      return statement + \"{lf}\";\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/domain/OsFamily.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.domain;\n\n/**\n * Type of an Operating System.\n */\npublic enum OsFamily {\n\n   /**\n    * All versions of Microsoft Windows\n    */\n   WINDOWS,\n   /**\n    * All Unix and Unix-like operating systems\n    */\n   UNIX\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/domain/PipeHttpResponseTo.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.domain;\n\nimport static com.google.common.base.Preconditions.checkArgument;\n\nimport java.net.URI;\nimport java.util.Map.Entry;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Joiner;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Multimap;\n\n/**\n * Pipes the content of the http response to a shell command that accepts input from stdin\n */\npublic class PipeHttpResponseTo extends InterpretableStatement {\n   /**\n    * \n    * @param toExec\n    *           what to invoke\n    * @param method\n    *           http method: ex GET\n    * @param endpoint\n    *           uri corresponding to the request\n    * @param headers\n    *           request headers to send\n    */\n   public PipeHttpResponseTo(Statement toExec, String method, URI endpoint, Multimap<String, String> headers) {\n      super(String.format(\"%s -X %s %s %s |(%s)\\n\", SaveHttpResponseTo.CURL, method, Joiner.on(' ').join(\n               Iterables.transform(headers.entries(), new Function<Entry<String, String>, String>() {\n\n                  @Override\n                  public String apply(Entry<String, String> from) {\n                     return String.format(\"-H \\\"%s: %s\\\"\", from.getKey(), from.getValue());\n                  }\n\n               })), endpoint.toASCIIString(), toExec.render(OsFamily.UNIX)));\n   }\n\n   public String render(OsFamily family) {\n      checkArgument(family != OsFamily.WINDOWS, \"windows not supported\");\n      return super.render(family);\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/domain/PipeHttpResponseToBash.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.domain;\n\nimport java.net.URI;\n\nimport com.google.common.collect.Multimap;\n\n/**\n * Pipes the content of the http response to bash\n */\npublic class PipeHttpResponseToBash extends PipeHttpResponseTo {\n   /**\n    * \n    * \n    * @param method\n    *           http method: ex GET\n    * @param endpoint\n    *           uri corresponding to the request\n    * @param headers\n    *           request headers to send\n    */\n   public PipeHttpResponseToBash(String method, URI endpoint, Multimap<String, String> headers) {\n      super(Statements.interpret(\"bash\"), method, endpoint, headers);\n   }\n\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/domain/PipeHttpResponseToTarxpzfIntoDirectory.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.domain;\n\nimport java.net.URI;\n\nimport com.google.common.collect.Multimap;\n\n/**\n * Pipes the content of the http response to tar -xpzf\n */\npublic class PipeHttpResponseToTarxpzfIntoDirectory extends PipeHttpResponseTo {\n   /**\n    * \n    * \n    * @param method\n    *           http method: ex GET\n    * @param endpoint\n    *           uri corresponding to the request\n    * @param headers\n    *           request headers to send\n    */\n   public PipeHttpResponseToTarxpzfIntoDirectory(String method, URI endpoint, Multimap<String, String> headers,\n            String directory) {\n      super(Statements.interpret(String.format(\"{md} %s &&{cd} %s &&tar -xpzf -\", directory, directory)), method,\n               endpoint, headers);\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/domain/SaveHttpResponseTo.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.domain;\n\nimport java.net.URI;\nimport java.util.Map;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Joiner;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Multimap;\n\n/**\n * saves the content of the http response to a file\n */\npublic class SaveHttpResponseTo extends InterpretableStatement {\n   public static final String CURL = \"curl -q -s -S -L --connect-timeout 10 --max-time 600 --retry 20\";\n\n   /**\n    * \n    * @param dir\n    *           location to save file\n    * @param method\n    *           http method: ex GET\n    * @param endpoint\n    *           uri corresponding to the request\n    * @param headers\n    *           request headers to send\n    */\n   public SaveHttpResponseTo(String dir, String file, String method, URI endpoint, Multimap<String, String> headers) {\n      super(String.format(\n            \"({md} %s && {cd} %s && [ ! -f %s ] && %s -C - -X %s %s %s >%s)\\n\",\n            dir,\n            dir,\n            file,\n            CURL,\n            method,\n            Joiner.on(' ').join(\n                  Iterables.transform(headers.entries(), new Function<Map.Entry<String, String>, String>() {\n\n                     @Override\n                     public String apply(Map.Entry<String, String> from) {\n                        return String.format(\"-H \\\"%s: %s\\\"\", from.getKey(), from.getValue());\n                     }\n\n                  })), endpoint.toASCIIString(), file));\n\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/domain/ShellToken.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\n\nimport com.google.common.base.CaseFormat;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\nimport com.google.common.collect.Maps;\n\n/**\n * Constants used in shell scripting.\n */\npublic enum ShellToken {\n\n   FS, RM, CD, TMP, UID, ROOT, CLOSE_FD, PS, MD, ESCVAR,\n\n   /**\n    * If variable values need to be quoted when they include spaces, this will contain quotation\n    * mark\n    */\n   VQ,\n   /**\n    * Left hand side of the function declaration directly before the name of the function.\n    */\n   FNCL,\n   /**\n    * Right hand side of the function declaration directly after the name of the function. opens the\n    * code block\n    */\n   FNCR,\n   /**\n    * End the function. exits successfully and closes the code block.\n    */\n   FNCE, BEGIN_SCRIPT, END_SCRIPT, BEGIN_FUNCTIONS, EXIT, END_FUNCTIONS, EXPORT, LF, SH, SOURCE, REM, RETURN, ARGS, VARL, VARR, LIBRARY_PATH_VARIABLE;\n\n   private static final LoadingCache<OsFamily, Map<String, String>> familyToTokenValueMap = CacheBuilder.newBuilder().build(\n         new CacheLoader<OsFamily, Map<String, String>>() {\n\n            @Override\n            public Map<String, String> load(OsFamily from) {\n               Map<String, String> map = Maps.newHashMap();\n               for (ShellToken token : ShellToken.values()) {\n                  map.put(CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, token.toString()), token.to(from));\n               }\n               return map;\n            }\n\n         });\n\n   public static Map<String, String> tokenValueMap(OsFamily family) {\n      return familyToTokenValueMap.getUnchecked(family);\n   }\n\n   @SuppressWarnings(\"fallthrough\")\n   public String to(OsFamily family) {\n      checkNotNull(family, \"family\");\n      switch (this) {\n         case FS:\n            switch (family) {\n               case WINDOWS:\n                  return \"\\\\\";\n               case UNIX:\n                  return \"/\";\n            }\n         case FNCL:\n            switch (family) {\n               case WINDOWS:\n                  return \":\";\n               case UNIX:\n                  return \"function \";\n            }\n         case FNCR:\n            switch (family) {\n               case WINDOWS:\n                  return \"\\r\\n\";\n               case UNIX:\n                  return \" {\\n\";\n            }\n         case FNCE:\n            switch (family) {\n               case WINDOWS:\n                  return \"   exit /b 0\\r\\n\";\n               case UNIX:\n                  return \"   return $?\\n}\\n\";\n            }\n         case ESCVAR:\n            switch (family) {\n               case WINDOWS:\n                  return \"%\";\n               case UNIX:\n                  return \"\\\\\";\n            }\n         case PS:\n            switch (family) {\n               case WINDOWS:\n                  return \";\";\n               case UNIX:\n                  return \":\";\n            }\n         case CLOSE_FD:\n            switch (family) {\n               case WINDOWS:\n                  return \">NUL\";\n               case UNIX:\n                  return \">&-\";\n            }\n         case RM:\n            switch (family) {\n               case WINDOWS:\n                  return \"del\";\n               case UNIX:\n                  return \"rm\";\n            }\n         case MD:\n            switch (family) {\n               case WINDOWS:\n                  return \"md\";\n               case UNIX:\n                  return \"mkdir -p\";\n            }\n         case VQ:\n            switch (family) {\n               case WINDOWS:\n                  return \"\";\n               case UNIX:\n                  return \"\\\"\";\n            }\n         case BEGIN_FUNCTIONS:\n            switch (family) {\n               case WINDOWS:\n                  return \"GOTO FUNCTION_END\\r\\n\";\n               case UNIX:\n                  return \"\";\n            }\n         case END_FUNCTIONS:\n            switch (family) {\n               case WINDOWS:\n                  return \":FUNCTION_END\\r\\n\";\n               case UNIX:\n                  return \"\";\n            }\n         case BEGIN_SCRIPT:\n            switch (family) {\n               case WINDOWS:\n                  return \"@echo off\\r\\n\";\n               case UNIX:\n                  return \"#!/bin/bash\\nset +u\\nshopt -s xpg_echo\\nshopt -s expand_aliases\\n\";\n            }\n         case END_SCRIPT:\n            switch (family) {\n               case WINDOWS:\n                  return \"exit /b 0\\r\\n\";\n               case UNIX:\n                  return \"exit $?\\n\";\n            }\n         case EXPORT:\n            switch (family) {\n               case WINDOWS:\n                  return \"set\";\n               case UNIX:\n                  return \"export\";\n            }\n         case RETURN:\n            switch (family) {\n               case WINDOWS:\n                  return \"exit /b\";\n               case UNIX:\n                  return \"return\";\n            }\n         case EXIT:\n            switch (family) {\n               case WINDOWS:\n                  return \"exit /b\";\n               case UNIX:\n                  return \"exit\";\n            }\n         case ROOT:\n            switch (family) {\n               case WINDOWS:\n                  return \"c:\\\\\";\n               case UNIX:\n                  return \"/\";\n            }\n         case TMP:\n            switch (family) {\n               case WINDOWS:\n                  return \"%TEMP%\";\n               case UNIX:\n                  return \"/tmp\";\n            }\n         case UID:\n            switch (family) {\n               case WINDOWS:\n                  return \"%USERNAME%\";\n               case UNIX:\n                  return \"$USER\";\n            }\n         case LF:\n            switch (family) {\n               case WINDOWS:\n                  return \"\\r\\n\";\n               case UNIX:\n                  return \"\\n\";\n            }\n         case SH:\n            switch (family) {\n               case WINDOWS:\n                  return \"cmd\";\n               case UNIX:\n                  return \"sh\";\n            }\n         case LIBRARY_PATH_VARIABLE:\n            switch (family) {\n               case WINDOWS:\n                  return \"PATH\";\n               case UNIX:\n                  return \"LD_LIBRARY_PATH\";\n            }\n         case SOURCE:\n            switch (family) {\n               case WINDOWS:\n                  return \"@call\";\n               case UNIX:\n                  return \".\";\n            }\n         case CD:\n            switch (family) {\n               case WINDOWS:\n                  return \"cd /d\";\n               case UNIX:\n                  return \"cd\";\n            }\n         case REM:\n            switch (family) {\n               case WINDOWS:\n                  return \"@rem\";\n               case UNIX:\n                  return \"#\";\n            }\n         case ARGS:\n            switch (family) {\n               case WINDOWS:\n                  return \"%*\";\n               case UNIX:\n                  return \"$@\";\n            }\n         case VARL:\n            switch (family) {\n               case WINDOWS:\n                  return \"%\";\n               case UNIX:\n                  return \"$\";\n            }\n         case VARR:\n            switch (family) {\n               case WINDOWS:\n                  return \"%\";\n               case UNIX:\n                  return \"\";\n            }\n         default:\n            throw new UnsupportedOperationException(\"token \" + this + \" not configured\");\n      }\n   }\n\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/domain/Statement.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.domain;\n\n/**\n * Statement used in a shell script\n */\npublic interface Statement {\n   Iterable<String> functionDependencies(OsFamily family);\n\n   String render(OsFamily family);\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/domain/StatementList.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.List;\n\nimport com.google.common.collect.ForwardingList;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableList.Builder;\n\n/**\n * Statements used in a shell script\n */\npublic class StatementList extends ForwardingList<Statement> implements Statement, AcceptsStatementVisitor {\n\n   public final List<Statement> statements;\n\n   public StatementList(Statement... statements) {\n      this.statements = ImmutableList.copyOf(checkNotNull(statements, \"statements\"));\n   }\n\n   public StatementList(Iterable<Statement> statements) {\n      this.statements = ImmutableList.copyOf(checkNotNull(statements, \"statements\"));\n   }\n\n   public String render(OsFamily family) {\n      StringBuilder statementsBuilder = new StringBuilder();\n      for (Statement statement : delegate()) {\n         statementsBuilder.append(statement.render(family));\n      }\n      return statementsBuilder.toString();\n   }\n\n   @Override\n   public Iterable<String> functionDependencies(OsFamily family) {\n      Builder<String> functions = ImmutableList.builder();\n      for (Statement statement : delegate()) {\n         functions.addAll(statement.functionDependencies(family));\n      }\n      return functions.build();\n   }\n\n   @Override\n   public void accept(StatementVisitor visitor) {\n      for (Statement statement : delegate()) {\n         visitor.visit(statement);\n      }\n   }\n\n   @Override\n   public List<Statement> delegate() {\n      return statements;\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/domain/StatementVisitor.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.domain;\n\npublic interface StatementVisitor {\n   void visit(Statement in);\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/domain/Statements.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.domain;\n\nimport java.net.URI;\nimport java.util.Map;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMultimap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Multimap;\n\n/**\n * Statements used in shell scripts.\n */\npublic class Statements {\n   private static final Kill KILL = new Kill();\n\n   public static Statement newStatementList(Statement... statements) {\n      return new StatementList(statements);\n   }\n\n   public static Statement switchArg(int arg, Map<String, Statement> valueToActions) {\n      return new SwitchArg(arg, valueToActions);\n   }\n\n   public static Statement rm(final String path) {\n      return new Statement() {\n\n         @Override\n         public Iterable<String> functionDependencies(OsFamily family) {\n            return ImmutableList.of();\n         }\n\n         @Override\n         public String render(OsFamily family) {\n            if (family == OsFamily.WINDOWS)\n               return exec(String.format(\"{rm} %s 2{closeFd}\", path)).render(family);\n            else\n               return exec(String.format(\"{rm} %s\", path)).render(family);\n         }\n\n      };\n   }\n\n   public static Statement call(String function, String... args) {\n      return new Call(function, args);\n   }\n\n   public static Statement appendFile(String path, String line, String delimiter) {\n      return AppendFile.builder().path(path).lines(ImmutableSet.of(line)).delimiter(delimiter).build();\n   }\n\n   public static Statement appendFile(String path, Iterable<String> lines) {\n      return AppendFile.builder().path(path).lines(lines).build();\n   }\n\n   public static Statement appendFile(String path, Iterable<String> lines, String delimiter) {\n      return AppendFile.builder().path(path).lines(lines).delimiter(delimiter).build();\n   }\n\n   public static Statement createOrOverwriteFile(String path, Iterable<String> lines) {\n      return CreateOrOverwriteFile.builder().path(path).lines(lines).build();\n   }\n\n   public static Statement createOrOverwriteFile(String path, Iterable<String> lines, String delimiter) {\n      return CreateOrOverwriteFile.builder().path(path).lines(lines).delimiter(delimiter).build();\n   }\n\n   /**\n    * @param exports\n    *            variable names to export in UPPER_UNDERSCORE case format\n    */\n   public static CreateRunScript createRunScript(String instanceName, Iterable<String> exports, String pwd,\n         Iterable<Statement> statements) {// TODO: convert so\n      // that\n      // createRunScript\n      // can take from a\n      // variable\n      return new CreateRunScript(instanceName, exports, pwd, statements);\n   }\n\n   /**\n    * Stores the pid into the variable {@code FOUND_PID} if successful.\n    * \n    * @param args\n    *           - what to search for in the process tree.\n    */\n   public static Statement findPid(String args) {\n      return new Call(\"findPid\", args);\n   }\n\n   /**\n    * \n    * Runs the script in a way that it can be matched later with\n    * {@link #findPid}\n    * \n    * @param instanceName\n    *           - what to match the process on\n    * @param script\n    *           - what to run in the background\n    * @param logDir\n    *           - where to write the following logs:\n    *           <ol>\n    *           <li>stdout.log</li>\n    *           <li>stderr.log</li>\n    *           </ol>\n    */\n   public static Statement forget(String instanceName, String script, String logDir) {\n      return new Call(\"forget\", instanceName, script, logDir);\n   }\n\n   /**\n    * Kills the pid and subprocesses related to the variable {@code FOUND_PID}\n    * if set.\n    * \n    * @see #findPid\n    */\n   public static Statement kill() {\n      return KILL;\n   }\n\n   /**\n    * statement can have multiple newlines, note you should use {@code lf} to be\n    * portable\n    * \n    * @see ShellToken\n    */\n   public static Statement interpret(String... portableStatements) {\n      return new InterpretableStatement(portableStatements);\n   }\n\n   /**\n    * sends statement only appending a newline\n    */\n   public static Statement literal(String literalStatement) {\n      return new LiteralStatement(literalStatement);\n   }\n\n   /**\n    * interprets and adds a newline to the statement\n    */\n   public static Statement exec(String portableStatement) {\n      return interpret(portableStatement + \"{lf}\");\n   }\n\n   /**\n    * untar, ungzip the data received from the request parameters.\n    * \n    * @param method\n    *           http method: ex GET\n    * @param endpoint\n    *           uri corresponding to the request\n    * @param headers\n    *           request headers to send\n    * @param directory\n    */\n   public static Statement extractTargzIntoDirectory(String method, URI endpoint, Multimap<String, String> headers,\n         String directory) {\n      return new PipeHttpResponseToTarxpzfIntoDirectory(method, endpoint, headers, directory);\n   }\n\n   /**\n    * like {@link #extractTargzIntoDirectory(URI, String)} except that it\n    * flattens the first directory in the archive\n    * \n    * For example, {@code apache-maven-3.0.4-bin.tar.gz} normally extracts\n    * directories like {@code ./apache-maven-3.0.4/bin}. This command eliminates\n    * the intermediate directory, in the example {@code ./apache-maven-3.0.4/}\n    * \n    * @param tgz remote ref to download\n    * @param dest path where the files in the intermediate directory will end\n    */\n   public static Statement extractTargzAndFlattenIntoDirectory(URI tgz, String dest) {\n      return new StatementList(ImmutableSet.<Statement> builder()\n            .add(exec(\"export TAR_TEMP=\\\"$(mktemp -d)\\\"\"))\n            .add(extractTargzIntoDirectory(tgz, \"\\\"${TAR_TEMP}\\\"\"))\n            .add(exec(\"mkdir -p \" + dest))\n            .add(exec(\"mv \\\"${TAR_TEMP}\\\"/*/* \" + dest))\n            .add(exec(\"rm -rf \\\"${TAR_TEMP}\\\"\"))\n            .build());\n   }\n   \n   public static Statement extractTargzIntoDirectory(URI targz, String directory) {\n      return extractTargzIntoDirectory(\"GET\", targz, ImmutableMultimap.<String, String> of(), directory);\n   }\n\n   /**\n    * unzip the data received from the request parameters.\n    * \n    * @param method\n    *           http method: ex GET\n    * @param endpoint\n    *           uri corresponding to the request\n    * @param headers\n    *           request headers to send\n    * @param directory\n    */\n   public static Statement extractZipIntoDirectory(String method, URI endpoint, Multimap<String, String> headers,\n         String directory) {\n      return new UnzipHttpResponseIntoDirectory(method, endpoint, headers, directory);\n   }\n\n   public static Statement saveHttpResponseTo(URI source, String dir, String file) {\n      return new SaveHttpResponseTo(dir, file, \"GET\", source, ImmutableMultimap.<String, String> of());\n   }\n\n   /**\n    * exec the data received from the request parameters.\n    * \n    * @param method\n    *           http method: ex GET\n    * @param endpoint\n    *           uri corresponding to the request\n    * @param headers\n    *           request headers to send\n    */\n   public static Statement pipeHttpResponseToBash(String method, URI endpoint, Multimap<String, String> headers) {\n      return new PipeHttpResponseToBash(method, endpoint, headers);\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/domain/StoppableJavaInitMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.net.URI;\n\n/**\n * A java process that has a graceful shutdown mechanism.\n * \n * @see JavaInitMetadata\n */\npublic class StoppableJavaInitMetadata extends JavaInitMetadata {\n   private final String[] stopClasspath;\n   private final String stopClass;\n   private final String[] stopOpts;\n   private final String[] stopArgs;\n\n   public StoppableJavaInitMetadata(String name, String platformHome, URI endPoint,\n            String startDir, String stopDir, String configDir, String dataDir, String logDir,\n            String goldDir, String javaHome, String[] classpath, String mainClass, String[] opts,\n            String[] args, String[] stopClasspath, String stopClass, String[] stopOpts,\n            String[] stopArgs) {\n      super(name, platformHome, endPoint, startDir, stopDir, configDir, dataDir, logDir, goldDir,\n               javaHome, classpath, mainClass, opts, args);\n      this.stopClasspath = checkNotNull(stopClasspath, \"stopClasspath\");\n      this.stopClass = checkNotNull(stopClass, \"stopClass\");\n      this.stopOpts = checkNotNull(stopOpts, \"stopOpts\");\n      this.stopArgs = checkNotNull(stopArgs, \"stopArgs\");\n   }\n\n   public String[] getStopClasspath() {\n      return stopClasspath;\n   }\n\n   public String getStopClass() {\n      return stopClass;\n   }\n\n   public String[] getStopOpts() {\n      return stopOpts;\n   }\n\n   public String[] getStopArgs() {\n      return stopArgs;\n   }\n\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/domain/SwitchArg.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.domain;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\nimport org.jclouds.scriptbuilder.util.Utils;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Joiner;\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\nimport com.google.common.collect.Lists;\n\n/**\n * Statement used in a shell script\n */\npublic class SwitchArg implements Statement, AcceptsStatementVisitor {\n\n   private static final String INDENT = \"   \";\n\n   public static final Map<OsFamily, String> OS_TO_SWITCH_PATTERN = ImmutableMap.of(OsFamily.UNIX, \"case ${arg} in\\n\",\n            OsFamily.WINDOWS, \"goto CASE_%{arg}\\r\\n\");\n\n   public static final Map<OsFamily, String> OS_TO_END_SWITCH_PATTERN = ImmutableMap.of(OsFamily.UNIX, \"esac\\n\",\n            OsFamily.WINDOWS, \":END_SWITCH\\r\\n\");\n\n   public static final Map<OsFamily, String> OS_TO_CASE_PATTERN = ImmutableMap.of(OsFamily.UNIX,\n            \"{value})\\n{action};;\\n\", OsFamily.WINDOWS, \":CASE_{value}\\r\\n{action}GOTO END_SWITCH\\r\\n\");\n\n   private final int arg;\n\n   private final Map<String, Statement> valueToActions;\n\n   /**\n    * Generates a switch statement based on {@code arg}. If its value is found to be a key in\n    * {@code valueToActions}, the corresponding action is invoked.\n    * \n    * <p/>\n    * Ex. arg is {@code 1} - the first argument to the script<br/>\n    * and valueToActions is {\"start\" -> \"echo hello\", \"stop\" -> \"echo goodbye\"}<br/>\n    * the script created will respond accordingly:<br/>\n    * {@code ./script start }<br/>\n    * << returns hello<br/>\n    * {@code ./script stop }<br/>\n    * << returns goodbye<br/>\n    * \n    * @param arg\n    *           - shell arg to switch on\n    * @param valueToActions\n    *           - case statements, if the value of the arg matches a key, the corresponding value\n    *           will be invoked.\n    */\n   public SwitchArg(int arg, Map<String, Statement> valueToActions) {\n      this.arg = arg;\n      this.valueToActions = checkNotNull(valueToActions, \"valueToActions\");\n   }\n\n   public String render(OsFamily family) {\n      StringBuilder switchClause = new StringBuilder();\n      addArgValidation(switchClause, family);\n      switchClause.append(Utils.replaceTokens(OS_TO_SWITCH_PATTERN.get(family), ImmutableMap.of(\"arg\", arg + \"\")));\n\n      for (Entry<String, Statement> entry : valueToActions.entrySet()) {\n\n         StringBuilder actionBuilder = new StringBuilder();\n         boolean shouldIndent = true;\n         boolean inRunScript = false;\n         boolean inCreateFile = false;\n         for (String line : Splitter.on(ShellToken.LF.to(family)).split(entry.getValue().render(family))) {\n            if (shouldIndent)\n               actionBuilder.append(INDENT);\n            actionBuilder.append(line).append(ShellToken.LF.to(family));\n            if (line.indexOf(CreateRunScript.DELIMITER) != -1) {\n               inRunScript = inRunScript ? false : true;\n\n            }\n            if (line.indexOf(AppendFile.DELIMITER) != -1) {\n               inCreateFile = inCreateFile ? false : true;\n            }\n            shouldIndent = !inCreateFile && !inRunScript;\n\n         }\n         actionBuilder.delete(actionBuilder.lastIndexOf(ShellToken.LF.to(family)), actionBuilder.length());\n         switchClause.append(Utils.replaceTokens(OS_TO_CASE_PATTERN.get(family), ImmutableMap.of(\"value\", entry\n                  .getKey(), \"action\", actionBuilder.toString())));\n      }\n\n      switchClause.append(OS_TO_END_SWITCH_PATTERN.get(family));\n      return switchClause.toString();\n   }\n\n   @VisibleForTesting\n   void addArgValidation(StringBuilder switchClause, OsFamily family) {\n      if (family.equals(OsFamily.WINDOWS)) {\n         for (String value : valueToActions.keySet()) {\n            switchClause.append(\"if not \\\"%\").append(arg).append(String.format(\"\\\" == \\\"%s\\\" \", value));\n         }\n         switchClause.append(\"(\\r\\n   set EXCEPTION=bad argument: %\").append(arg).append(\" not in \");\n         switchClause.append(Joiner.on(\" \").join(valueToActions.keySet()));\n         switchClause.append(\"\\r\\n   goto abort\\r\\n)\\r\\n\");\n      }\n   }\n\n   @Override\n   public Iterable<String> functionDependencies(OsFamily family) {\n      List<String> functions = Lists.newArrayList();\n      for (Statement statement : valueToActions.values()) {\n         Iterables.addAll(functions, statement.functionDependencies(family));\n      }\n      return functions;\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + arg;\n      result = prime * result + ((valueToActions == null) ? 0 : valueToActions.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      SwitchArg other = (SwitchArg) obj;\n      if (arg != other.arg)\n         return false;\n      if (valueToActions == null) {\n         if (other.valueToActions != null)\n            return false;\n      } else if (!valueToActions.equals(other.valueToActions))\n         return false;\n      return true;\n   }\n\n   @Override\n   public void accept(StatementVisitor visitor) {\n      for (Statement statement : valueToActions.values()) {\n         visitor.visit(statement);\n      }\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/domain/UnzipHttpResponseIntoDirectory.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.domain;\n\nimport static com.google.common.collect.Iterables.transform;\nimport static java.lang.String.format;\n\nimport java.net.URI;\nimport java.util.Map.Entry;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Joiner;\nimport com.google.common.collect.Multimap;\n\n/**\n * unzips the content into a directory\n */\npublic class UnzipHttpResponseIntoDirectory extends InterpretableStatement {\n   /**\n    * \n    * \n    * @param method\n    *           http method: ex GET\n    * @param endpoint\n    *           uri corresponding to the request\n    * @param headers\n    *           request headers to send\n    */\n   public UnzipHttpResponseIntoDirectory(String method, URI endpoint, Multimap<String, String> headers, String dir) {\n      super(\n               format(\n                        \"({md} %s &&{cd} %s &&curl -X -L %s -s --retry 20 %s %s >extract.zip && unzip -o -qq extract.zip&& rm extract.zip)\\n\",\n                        dir, dir, method, Joiner.on(' ').join(\n                                 transform(headers.entries(), new Function<Entry<String, String>, String>() {\n\n                                    @Override\n                                    public String apply(Entry<String, String> from) {\n                                       return String.format(\"-H \\\"%s: %s\\\"\", from.getKey(), from.getValue());\n                                    }\n\n                                 })), endpoint.toASCIIString()));\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/domain/chef/DataBag.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.domain.chef;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.Map;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.collect.ForwardingMap;\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * A Data bag to be configured for a Chef Solo run.\n * \n * @since Chef 0.10.4\n */\npublic class DataBag extends ForwardingMap<String, String> {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n      private String name;\n      private ImmutableMap.Builder<String, String> items = ImmutableMap.builder();\n\n      public Builder name(String name) {\n         this.name = checkNotNull(name, \"name must be set\");\n         return this;\n      }\n\n      public Builder item(String name, String jsonData) {\n         this.items.put(checkNotNull(name, \"name must be set\"), checkNotNull(jsonData, \"jsonData must be set\"));\n         return this;\n      }\n\n      public Builder items(Map<String, String> items) {\n         this.items.putAll(checkNotNull(items, \"items must be set\"));\n         return this;\n      }\n\n      public DataBag build() {\n         return new DataBag(name, items.build());\n      }\n\n   }\n\n   private String name;\n\n   private Map<String, String> items;\n\n   public DataBag(String name, Map<String, String> items) {\n      this.name = checkNotNull(name, \"name must be set\");\n      this.items = ImmutableMap.copyOf(checkNotNull(items, \"items must be set\"));\n   }\n\n   @Override\n   protected Map<String, String> delegate() {\n      return items;\n   }\n\n   public String getName() {\n      return name;\n   }\n\n   public Map<String, String> getItems() {\n      return items;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(name);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) {\n         return true;\n      }\n      if (obj == null) {\n         return false;\n      }\n      if (getClass() != obj.getClass()) {\n         return false;\n      }\n      DataBag other = (DataBag) obj;\n      return Objects.equal(name, other.name);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).add(\"name\", name).toString();\n   }\n\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/domain/chef/Role.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.domain.chef;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.Optional;\n\n/**\n * A Role to be configured for a Chef Solo run.\n */\npublic class Role {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n      private String name;\n      private String description;\n      private String jsonDefaultAttributes;\n      private String jsonOverrideAttributes;\n      private RunList runlist;\n\n      public Builder name(String name) {\n         this.name = checkNotNull(name, \"name must be set\");\n         return this;\n      }\n\n      public Builder description(String description) {\n         this.description = checkNotNull(description, \"description must be set\");\n         return this;\n      }\n\n      public Builder jsonDefaultAttributes(String jsonDefaultAttributes) {\n         this.jsonDefaultAttributes = checkNotNull(jsonDefaultAttributes, \"jsonDefaultAttributes must be set\");\n         return this;\n      }\n\n      public Builder jsonOverrideAttributes(String jsonOverrideAttributes) {\n         this.jsonOverrideAttributes = checkNotNull(jsonOverrideAttributes, \"jsonOverrideAttributes must be set\");\n         return this;\n      }\n\n      public Builder runlist(RunList runlist) {\n         this.runlist = checkNotNull(runlist, \"runlist must be set\");\n         return this;\n      }\n\n      public Role build() {\n         return new Role(name, Optional.fromNullable(description), Optional.fromNullable(jsonDefaultAttributes),\n               Optional.fromNullable(jsonOverrideAttributes), Optional.fromNullable(runlist));\n      }\n   }\n\n   private String name;\n   private Optional<String> description;\n   private Optional<String> jsonDefaultAttributes;\n   private Optional<String> jsonOverrideAttributes;\n   private RunList runlist;\n\n   protected Role(String name, Optional<String> description, Optional<String> jsonDefaultAttributes,\n         Optional<String> jsonOverrideAttributes, Optional<RunList> runlist) {\n      this.name = checkNotNull(name, \"name must be set\");\n      this.description = checkNotNull(description, \"description must be set\");\n      this.jsonDefaultAttributes = checkNotNull(jsonDefaultAttributes, \"jsonDefaultAttributes must be set\");\n      this.jsonOverrideAttributes = checkNotNull(jsonOverrideAttributes, \"jsonOverrideAttributes must be set\");\n      this.runlist = checkNotNull(runlist, \"runlist must be set\").or(RunList.builder().build());\n   }\n\n   public String toJsonString() {\n      StringBuilder json = new StringBuilder();\n      json.append(\"{\");\n      json.append(\"\\\"name\\\": \\\"\").append(name).append(\"\\\",\");\n      json.append(\"\\\"description\\\":\\\"\").append(description.or(\"\")).append(\"\\\",\");\n      json.append(\"\\\"default_attributes\\\":\").append(jsonDefaultAttributes.or(\"{}\")).append(\",\");\n      json.append(\"\\\"override_attributes\\\":\").append(jsonOverrideAttributes.or(\"{}\")).append(\",\");\n      json.append(\"\\\"json_class\\\":\\\"Chef::Role\\\",\");\n      json.append(\"\\\"chef_type\\\":\\\"role\\\",\");\n      json.append(\"\\\"run_list\\\":\" + runlist.toString());\n      json.append(\"}\");\n      return json.toString();\n   }\n\n   public String getName() {\n      return name;\n   }\n\n   public Optional<String> getDescription() {\n      return description;\n   }\n\n   public Optional<String> getJsonDefaultAttributes() {\n      return jsonDefaultAttributes;\n   }\n\n   public Optional<String> getJsonOverrideAttributes() {\n      return jsonOverrideAttributes;\n   }\n\n   public RunList getRunlist() {\n      return runlist;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(name);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) {\n         return true;\n      }\n      if (obj == null) {\n         return false;\n      }\n      if (getClass() != obj.getClass()) {\n         return false;\n      }\n      Role other = Role.class.cast(obj);\n      return Objects.equal(name, other.name);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"name\", name).add(\"description\", description.orNull())\n            .toString();\n   }\n\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/domain/chef/RunList.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.domain.chef;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.transform;\n\nimport java.util.List;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Joiner;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.Lists;\n\n/**\n * A Run list to be executed in a Chef Solo run.\n */\npublic class RunList {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n      private ImmutableList.Builder<String> runlist = ImmutableList.builder();\n\n      public Builder recipe(String recipe) {\n         this.runlist.add(\"recipe[\" + checkNotNull(recipe, \"recipe must be set\") + \"]\");\n         return this;\n      }\n\n      public Builder recipes(Iterable<String> recipes) {\n         this.runlist.addAll(Lists.newArrayList(transform(checkNotNull(recipes, \"recipes must be set\"),\n               new Function<String, String>() {\n                  @Override\n                  public String apply(String input) {\n                     return \"recipe[\" + input + \"]\";\n                  }\n               })));\n         return this;\n      }\n\n      public Builder role(String role) {\n         this.runlist.add(\"role[\" + checkNotNull(role, \"role must be set\") + \"]\");\n         return this;\n      }\n\n      public Builder roles(Iterable<String> roles) {\n         this.runlist.addAll(Lists.newArrayList(transform(checkNotNull(roles, \"roles must be set\"),\n               new Function<String, String>() {\n                  @Override\n                  public String apply(String input) {\n                     return \"role[\" + input + \"]\";\n                  }\n               })));\n         return this;\n      }\n\n      public RunList build() {\n         return new RunList(runlist.build());\n      }\n   }\n\n   private List<String> runlist;\n\n   protected RunList(List<String> runlist) {\n      this.runlist = ImmutableList.<String> copyOf(checkNotNull(runlist, \"runlist must be set\"));\n   }\n\n   public List<String> getRunlist() {\n      return runlist;\n   }\n\n   @Override\n   public String toString() {\n      return \"[\" + Joiner.on(',').join(transform(runlist, new Function<String, String>() {\n         @Override\n         public String apply(String input) {\n            return \"\\\"\" + input + \"\\\"\";\n         }\n      })) + \"]\";\n   }\n\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/functionloader/BasicFunctionLoader.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.functionloader;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.io.Resources.getResource;\nimport static java.lang.String.format;\nimport static org.jclouds.scriptbuilder.domain.ShellToken.SH;\n\nimport java.io.IOException;\n\nimport org.jclouds.scriptbuilder.domain.OsFamily;\n\nimport com.google.common.io.Resources;\n\n/**\n * A {@link FunctionLoader} implementation which loads the target function from the classpath.\n */\npublic enum BasicFunctionLoader implements FunctionLoader {\n   INSTANCE;\n\n   /**\n    * Loads a function from the classpath using the current or the Thread Context Class Loader.\n    * \n    * @param function\n    *           The function name to load.\n    * @param family\n    *           This operating system family of the function.\n    * @return The function as {@link String}\n    * @throws FunctionNotFoundException\n    */\n   @Override\n   public String loadFunction(String function, OsFamily family) throws FunctionNotFoundException {\n      try {\n         return Resources.toString(\n               getResource(BasicFunctionLoader.class, format(\"/functions/%s.%s\", function, SH.to(family))), UTF_8);\n      } catch (IOException e) {\n         throw new FunctionNotFoundException(function, family, e);\n      }\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/functionloader/CurrentFunctionLoader.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.functionloader;\n\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport org.jclouds.scriptbuilder.functionloader.filters.LicenseHeaderFilter;\n\nimport com.google.common.util.concurrent.Atomics;\n\n/**\n * Means to access the current {@link FunctionLoader} instance;\n */\npublic class CurrentFunctionLoader {\n\n   private static final AtomicReference<FunctionLoader> ref = Atomics.<FunctionLoader>newReference(\n            BasicFunctionLoader.INSTANCE);\n\n   public static FunctionLoader get() {\n      // Filter out license headers in function scripts\n      return new LicenseHeaderFilter(ref.get());\n   }\n\n   public static FunctionLoader set(FunctionLoader loader) {\n      return ref.getAndSet(loader);\n   }\n\n   public static FunctionLoader reset() {\n      return ref.getAndSet(BasicFunctionLoader.INSTANCE);\n   }\n\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/functionloader/FunctionLoader.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.functionloader;\n\nimport org.jclouds.scriptbuilder.domain.OsFamily;\n\n/**\n * A function loader interface.\n */\npublic interface FunctionLoader {\n\n  /**\n   * Loads a function and returns it as {@link String}.\n   * @param function The function name to load.\n   * @param family   This operating system family of the function.\n   * @return         The function as {@link String}.\n   * @throws FunctionNotFoundException\n   */\n  String loadFunction(String function, OsFamily family) throws FunctionNotFoundException;\n\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/functionloader/FunctionNotFoundException.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.functionloader;\n\nimport org.jclouds.scriptbuilder.domain.OsFamily;\n\npublic class FunctionNotFoundException extends RuntimeException {\n\n   private static final long serialVersionUID = 1L;\n\n  public FunctionNotFoundException(String functionName, OsFamily family) {\n    super(\"function: \" + functionName + \" not found for family: \" + family);\n  }\n\n  public FunctionNotFoundException(String functionName, OsFamily family, Throwable cause) {\n    super(\"function: \" + functionName + \" not found for family: \" + family, cause);\n  }\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/functionloader/filters/LicenseHeaderFilter.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.functionloader.filters;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.io.IOException;\n\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.jclouds.scriptbuilder.domain.ShellToken;\nimport org.jclouds.scriptbuilder.functionloader.FunctionLoader;\nimport org.jclouds.scriptbuilder.functionloader.FunctionNotFoundException;\n\nimport com.google.common.io.CharSource;\nimport com.google.common.io.LineProcessor;\n\n/**\n * FunctionLoader decorator to filters out license header comments from a file.\n */\npublic class LicenseHeaderFilter implements FunctionLoader {\n\n   /** The target function loader. */\n   private final FunctionLoader delegate;\n\n   public LicenseHeaderFilter(FunctionLoader delegate) {\n      this.delegate = checkNotNull(delegate, \"delegate\");\n   }\n\n   @Override\n   public String loadFunction(String function, OsFamily family) throws FunctionNotFoundException {\n      return filter(delegate.loadFunction(function, family), family);\n   }\n\n   /**\n    * Filters out license header comments from a file.\n    * @param lines The lines to filter.\n    * @param family The {@link OsFamily} of the file.\n    * @return The filtered file.\n    */\n   public String filter(String lines, OsFamily family) {\n      try {\n         return CharSource.wrap(checkNotNull(lines, \"lines\")).readLines(\n               new LicenseHeaderProcessor(checkNotNull(family, \"family\")));\n      } catch (IOException e) {\n         // Don't fail; just return the original text with the comments\n         return lines;\n      }\n   }\n\n   /**\n    * Line by line processor.\n    *\n    */\n   private static class LicenseHeaderProcessor implements LineProcessor<String> {\n\n      /** Search token used to identify license header comments beginning. */\n      private static final String LICENSE_TOKEN_START = \"Licensed to the Apache Software Foundation\";\n      \n      /** Search token used to identify license header comments end. */\n      private static final String LICENSE_TOKEN_END = \"limitations under the License\";\n\n      /** The resulting text, without the license header comments. */\n      private final StringBuilder builder;\n\n      /** The comment token for the given OsFamily */\n      private final String commentToken;\n      \n      /** The line termination token for the given OsFamily */\n      private final String lineTerminationToken;\n\n      /** Flag to indicate that a license header comment is being processed. */\n      private boolean isLicenseComment;\n\n      public LicenseHeaderProcessor(OsFamily family) {\n         builder = new StringBuilder();\n         commentToken = ShellToken.REM.to(family);\n         lineTerminationToken = ShellToken.LF.to(family);\n         isLicenseComment = false;\n      }\n\n      @Override\n      public boolean processLine(String line) throws IOException {\n         String trimmed = line.trim();\n         boolean isComment = isCommentLine(trimmed);\n\n         if (isComment && line.contains(LICENSE_TOKEN_START)) {\n            // License found, start skipping following comment lines\n            isLicenseComment = true;\n         }\n\n         // Remove empty comment lines (licenses are prefixed and suffixed with\n         // empty comments)\n         if (!isLicenseComment && !isEmptyCommentLine(trimmed)) {\n            builder.append(line);\n            builder.append(lineTerminationToken);\n         }\n         \n         if (isLicenseComment && line.contains(LICENSE_TOKEN_END)) {\n            // Reset the license flag to avoid filtering other comments\n            isLicenseComment = false;\n         }\n\n         return true; // Continue processing lines\n      }\n\n      @Override\n      public String getResult() {\n         return builder.toString();\n      }\n\n      /**\n       * Checks if the given line is an empty comment line.\n       */\n      private boolean isEmptyCommentLine(String line) {\n         // ShellToken.REM.to(WINDOWS) has a '@' prefix but not all comments do\n         return line.equals(commentToken) || line.equals(\"REM\");\n      }\n\n      /**\n       * Checks if the given line is a comment line.\n       */\n      private boolean isCommentLine(String line) {\n         // ShellToken.REM.to(WINDOWS) has a '@' prefix but not all comments do\n         return line.startsWith(commentToken) || line.startsWith(\"REM\");\n      }\n   }\n\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/functionloader/osgi/Activator.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.functionloader.osgi;\n\nimport org.jclouds.scriptbuilder.functionloader.CurrentFunctionLoader;\nimport org.osgi.framework.BundleActivator;\nimport org.osgi.framework.BundleContext;\n\npublic class Activator implements BundleActivator {\n\n   BundleFunctionLoader functionLoader;\n\n   /**\n    * Called when this bundle is started so the Framework can perform the bundle-specific activities\n    * necessary to start this bundle. This method can be used to register services or to allocate\n    * any resources that this bundle needs.\n    * <p/>\n    * <p/>\n    * This method must complete and return to its caller in a timely manner.\n    * \n    * @param context\n    *           The execution context of the bundle being started.\n    * @throws Exception\n    *            If this method throws an exception, this bundle is marked as stopped and the\n    *            Framework will remove this bundle's listeners, unregister all services registered\n    *            by this bundle, and release all services used by this bundle.\n    */\n   @Override\n   public void start(BundleContext context) throws Exception {\n      functionLoader = new BundleFunctionLoader(context);\n      functionLoader.start();\n      CurrentFunctionLoader.set(new ServiceFunctionLoader(context));\n   }\n\n   /**\n    * Called when this bundle is stopped so the Framework can perform the bundle-specific activities\n    * necessary to stop the bundle. In general, this method should undo the work that the\n    * <code>BundleActivator.start</code> method started. There should be no active threads that were\n    * started by this bundle when this bundle returns. A stopped bundle must not call any Framework\n    * objects.\n    * <p/>\n    * <p/>\n    * This method must complete and return to its caller in a timely manner.\n    * \n    * @param context\n    *           The execution context of the bundle being stopped.\n    * @throws Exception\n    *            If this method throws an exception, the bundle is still marked as stopped, and the\n    *            Framework will remove the bundle's listeners, unregister all services registered by\n    *            the bundle, and release all services used by the bundle.\n    */\n   @Override\n   public void stop(BundleContext context) throws Exception {\n      if (functionLoader != null) {\n         CurrentFunctionLoader.reset();\n         functionLoader.stop();\n         functionLoader = null;\n      }\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/functionloader/osgi/BundleFunctionLoader.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.functionloader.osgi;\n\nimport java.io.IOException;\nimport java.net.URL;\nimport java.util.Dictionary;\nimport java.util.Enumeration;\nimport java.util.Hashtable;\n\nimport org.gaul.modernizer_maven_annotations.SuppressModernizer;\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.jclouds.scriptbuilder.domain.ShellToken;\nimport org.jclouds.scriptbuilder.functionloader.FunctionLoader;\nimport org.jclouds.scriptbuilder.functionloader.FunctionNotFoundException;\nimport org.osgi.framework.Bundle;\nimport org.osgi.framework.BundleContext;\nimport org.osgi.framework.ServiceRegistration;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.io.Resources;\n\n/**\n * A {@link FunctionLoader} which searches for functions in the {@link Bundle} resources.\n */\npublic class BundleFunctionLoader implements FunctionLoader {\n\n   private final BundleContext bundleContext;\n   private ServiceRegistration registration;\n\n   /**\n    * Constructor\n    * \n    * @param bundleContext\n    */\n   public BundleFunctionLoader(BundleContext bundleContext) {\n      this.bundleContext = bundleContext;\n   }\n\n   /**\n    * Starts the loader. Looks up for {@link Bundle} resources and registers itself in the service\n    * registry. It adds a property to the service which advertise all the functions found in the\n    * local resources.\n    */\n   public void start() {\n      Bundle bundle = bundleContext.getBundle();\n      Enumeration<?> entries = bundle.findEntries(\"/functions/\", \"*.*\", false);\n      StringBuilder sb = new StringBuilder();\n      while (entries.hasMoreElements()) {\n         URL url = (URL) entries.nextElement();\n         String function = url.getFile();\n         sb.append(function);\n         if (entries.hasMoreElements()) {\n            sb.append(\" \");\n         }\n      }\n      String functions = sb.toString();\n      registerFunction(functions);\n   }\n\n   /**\n    * Unregisters itself from the service registry.\n    */\n   public void stop() {\n      registration.unregister();\n   }\n\n   /**\n    * Loads the function from the {@link Bundle} resources.\n    * \n    * @param function\n    *           The function name to load.\n    * @param family\n    *           This operating system family of the function.\n    * @return\n    * @throws FunctionNotFoundException\n    */\n   @Override\n   public String loadFunction(String function, OsFamily family) throws FunctionNotFoundException {\n      try {\n         return Resources.toString(bundleContext.getBundle().getResource(\n                  String.format(\"/functions/%s.%s\", function, ShellToken.SH.to(family))), Charsets.UTF_8);\n      } catch (IOException e) {\n         throw new FunctionNotFoundException(function, family, e);\n      }\n   }\n\n   @SuppressModernizer  // for BundleContext.registerService(String, Object, Dictionary)\n   private void registerFunction(String functions) {\n      String[] className = { FunctionLoader.class.getName() };\n      Dictionary<String, Object> dictionary = new Hashtable<String, Object>(1);\n      dictionary.put(\"function\", functions);\n      registration = bundleContext.registerService(className, this, dictionary);\n   }\n\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/functionloader/osgi/ServiceFunctionLoader.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.functionloader.osgi;\n\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.jclouds.scriptbuilder.domain.ShellToken;\nimport org.jclouds.scriptbuilder.functionloader.FunctionLoader;\nimport org.jclouds.scriptbuilder.functionloader.FunctionNotFoundException;\nimport org.osgi.framework.BundleContext;\nimport org.osgi.framework.InvalidSyntaxException;\nimport org.osgi.framework.ServiceReference;\n\nimport com.google.common.base.Strings;\n\n/**\n * A {@link FunctionLoader} implementation which delegates loading to the OSGi service registry.\n */\npublic class ServiceFunctionLoader implements FunctionLoader {\n\n   private final BundleContext bundleContext;\n\n   public ServiceFunctionLoader(BundleContext bundleContext) {\n      this.bundleContext = bundleContext;\n   }\n\n   /**\n    * Looks up the service registry for an applicable {@link FunctionLoader} and delegates to it.\n    * \n    * @param function\n    *           The function name to load.\n    * @param family\n    *           This operating system family of the function.\n    * @return The function as {@link String}\n    * @throws FunctionNotFoundException\n    */\n   @Override\n   public String loadFunction(String function, OsFamily family) throws FunctionNotFoundException {\n      ServiceReference[] references = null;\n      String filter = String.format(\"(function=*%s.%s*)\", function, ShellToken.SH.to(family));\n      try {\n         references = bundleContext.getServiceReferences(FunctionLoader.class.getName(), filter);\n        if (references != null) {\n          for (ServiceReference reference : references) {\n            FunctionLoader loader = (FunctionLoader) bundleContext.getService(reference);\n            String f = loader.loadFunction(function, family);\n            if (!Strings.isNullOrEmpty(f)) {\n              return f;\n            }\n          }\n        }\n      } catch (InvalidSyntaxException e) {\n         throw new FunctionNotFoundException(function, family, e);\n      } finally {\n         if (references != null) {\n            for (ServiceReference reference : references) {\n               bundleContext.ungetService(reference);\n            }\n         }\n      }\n      throw new FunctionNotFoundException(function, family);\n   }\n\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/functions/CredentialsFromAdminAccess.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.functions;\n\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.scriptbuilder.domain.AcceptsStatementVisitor;\nimport org.jclouds.scriptbuilder.domain.Statement;\nimport org.jclouds.scriptbuilder.domain.StatementVisitor;\nimport org.jclouds.scriptbuilder.statements.login.AdminAccess;\n\nimport com.google.common.base.Function;\nimport com.google.common.util.concurrent.Atomics;\n\npublic enum CredentialsFromAdminAccess implements Function<Statement, Credentials> {\n   INSTANCE;\n   @Override\n   public Credentials apply(@Nullable Statement input) {\n      if (input == null)\n         return null;\n      if (input instanceof AcceptsStatementVisitor) {\n         final AtomicReference<Credentials> credsHolder = Atomics.newReference();\n         AcceptsStatementVisitor.class.cast(input).accept(new StatementVisitor() {\n\n            @Override\n            public void visit(Statement in) {\n               if (credsHolder.get() == null) {\n                  Credentials creds = apply(in);\n                  if (creds != null)\n                     credsHolder.set(creds);\n               }\n            }\n\n         });\n         return credsHolder.get();\n      } else if (input instanceof AdminAccess) {\n         return AdminAccess.class.cast(input).getAdminCredentials();\n      } else {\n         return null;\n      }\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/functions/InitAdminAccess.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.functions;\n\nimport jakarta.inject.Inject;\n\nimport org.jclouds.scriptbuilder.domain.AdminAccessVisitor;\nimport org.jclouds.scriptbuilder.statements.login.AdminAccess;\nimport org.jclouds.scriptbuilder.statements.login.AdminAccess.Configuration;\n\npublic class InitAdminAccess extends AdminAccessVisitor {\n   private final AdminAccess.Configuration adminAccessConfiguration;\n\n   @Inject\n   public InitAdminAccess(Configuration adminAccessConfiguration) {\n      this.adminAccessConfiguration = adminAccessConfiguration;\n   }\n\n   @Override\n   public void visit(AdminAccess input) {\n      input.init(adminAccessConfiguration);\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/statements/chef/ChefSolo.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.statements.chef;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.transform;\nimport static org.jclouds.scriptbuilder.domain.Statements.createOrOverwriteFile;\nimport static org.jclouds.scriptbuilder.domain.Statements.exec;\n\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Map;\n\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.jclouds.scriptbuilder.domain.Statement;\nimport org.jclouds.scriptbuilder.domain.StatementList;\nimport org.jclouds.scriptbuilder.domain.Statements;\nimport org.jclouds.scriptbuilder.domain.chef.DataBag;\nimport org.jclouds.scriptbuilder.domain.chef.Role;\nimport org.jclouds.scriptbuilder.domain.chef.RunList;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Function;\nimport com.google.common.base.Joiner;\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Lists;\n\n/**\n * Bootstraps a node using Chef Solo.\n * \n * \n * @see InstallChefGems\n * @see InstallRuby\n * @see InstallRubyGems\n */\npublic class ChefSolo implements Statement {\n\n   public static final String DEFAULT_SOLO_PATH = \"/var/chef\";\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n      private String fileCachePath = DEFAULT_SOLO_PATH;\n      private String rolePath;\n      private String databagPath;\n      private ImmutableList.Builder<String> cookbookPath = ImmutableList.builder();\n      private String cookbooksArchiveLocation;\n      private String jsonAttributes;\n      private String group;\n      private Integer interval;\n      private String logLevel;\n      private String logFile;\n      private String nodeName;\n      private Integer splay;\n      private String user;\n      private List<Role> roles = Lists.newArrayList();\n      private List<DataBag> databags = Lists.newArrayList();\n      private RunList runlist;\n\n      /**\n       * Directory where Chef Solo will store files.\n       */\n      public Builder fileCachePath(String fileCachePath) {\n         this.fileCachePath = checkNotNull(fileCachePath, \"fileCachePath\");\n         return this;\n      }\n\n      /**\n       * Directory where Chef Solo will store roles.\n       */\n      public Builder rolePath(String rolePath) {\n         this.rolePath = checkNotNull(rolePath, \"rolePath\");\n         return this;\n      }\n\n      /**\n       * Directory where Chef Solo will store data bags.\n       */\n      public Builder dataBagPath(String dataBagPath) {\n         this.databagPath = checkNotNull(dataBagPath, \"dataBagPath\");\n         return this;\n      }\n\n      /**\n       * Directory where Chef Solo will look for cookbooks.\n       */\n      public Builder cookbookPath(String cookbookPath) {\n         this.cookbookPath.add(checkNotNull(cookbookPath, \"cookbookPath\"));\n         return this;\n      }\n\n      /**\n       * Directories where Chef Solo will look for cookbooks.\n       */\n      public Builder cookbookPaths(Iterable<String> cookbookPaths) {\n         this.cookbookPath.addAll(checkNotNull(cookbookPaths, \"cookbookPath\"));\n         return this;\n      }\n\n      /**\n       * Local file path or remote URL of a cookbook tar file. Chef solo will\n       * download and unpack its contents in the {@link #fileCachePath}\n       * directory.\n       */\n      public Builder cookbooksArchiveLocation(String cookbooksArchiveLocation) {\n         this.cookbooksArchiveLocation = checkNotNull(cookbooksArchiveLocation, \"cookbooksArchiveLocation\");\n         return this;\n      }\n\n      /**\n       * JSON attributes to customize cookbook values.\n       */\n      public Builder jsonAttributes(String jsonAttributes) {\n         this.jsonAttributes = checkNotNull(jsonAttributes, \"jsonAttributes\");\n         return this;\n      }\n\n      /**\n       * The goup to set privilege to.\n       */\n      public Builder group(String group) {\n         this.group = checkNotNull(group, \"group\");\n         return this;\n      }\n\n      /**\n       * Run chef-client periodically, in seconds.\n       */\n      public Builder interval(Integer interval) {\n         this.interval = checkNotNull(interval, \"interval\");\n         return this;\n      }\n\n      /**\n       * Set he Log level (debug, info, warn, error, fatal).\n       */\n      public Builder logLevel(String logLevel) {\n         this.logLevel = checkNotNull(logLevel, \"logLevel\");\n         return this;\n      }\n\n      /**\n       * Set the log file location, by default STDOUT.\n       */\n      public Builder logFile(String logFile) {\n         this.logFile = checkNotNull(logFile, \"logFile\");\n         return this;\n      }\n\n      /**\n       * Set the name for the node. By default the hostname will be used.\n       */\n      public Builder nodeName(String nodeName) {\n         this.nodeName = checkNotNull(nodeName, \"nodeName\");\n         return this;\n      }\n\n      /**\n       * The splay time for running at intervals, in seconds.\n       */\n      public Builder splay(Integer splay) {\n         this.splay = checkNotNull(splay, \"splay\");\n         return this;\n      }\n\n      /**\n       * The user to set privilege to.\n       */\n      public Builder user(String user) {\n         this.user = checkNotNull(user, \"user\");\n         return this;\n      }\n\n      /**\n       * Creates a role.\n       */\n      public Builder defineRole(Role role) {\n         this.roles.add(checkNotNull(role, \"role\"));\n         return this;\n      }\n\n      /**\n       * Creates a set of roles.\n       */\n      public Builder defineRoles(Iterable<Role> roles) {\n         this.roles = ImmutableList.<Role> copyOf(checkNotNull(roles, \"roles\"));\n         return this;\n      }\n\n      /**\n       * Creates a data bag.\n       * \n       * @since Chef 0.10.4\n       */\n      public Builder defineDataBag(DataBag dataBag) {\n         this.databags.add(checkNotNull(dataBag, \"dataBag\"));\n         return this;\n      }\n\n      /**\n       * Creates a set of data bags.\n       * \n       * @since Chef 0.10.4\n       */\n      public Builder defineDataBags(Iterable<DataBag> databags) {\n         this.databags = ImmutableList.<DataBag> copyOf(checkNotNull(databags, \"databags\"));\n         return this;\n      }\n\n      /**\n       * The run list to be executed in the Chef Solo run.\n       */\n      public Builder runlist(RunList runlist) {\n         this.runlist = checkNotNull(runlist, \"runlist\");\n         return this;\n      }\n\n      public ChefSolo build() {\n         return new ChefSolo(Optional.of(fileCachePath), Optional.fromNullable(rolePath),\n               Optional.fromNullable(databagPath), Optional.of(cookbookPath.build()),\n               Optional.fromNullable(cookbooksArchiveLocation), Optional.fromNullable(jsonAttributes),\n               Optional.fromNullable(group), Optional.fromNullable(interval), Optional.fromNullable(logLevel),\n               Optional.fromNullable(logFile), Optional.fromNullable(nodeName), Optional.fromNullable(splay),\n               Optional.fromNullable(user), Optional.of(roles), Optional.of(databags), Optional.fromNullable(runlist));\n      }\n\n   }\n\n   private String fileCachePath;\n   private String rolePath;\n   private String databagPath;\n   private List<String> cookbookPath;\n   private Optional<String> cookbooksArchiveLocation;\n   private Optional<String> jsonAttributes;\n   private Optional<String> group;\n   private Optional<Integer> interval;\n   private Optional<String> logLevel;\n   private Optional<String> logFile;\n   private Optional<String> nodeName;\n   private Optional<Integer> splay;\n   private Optional<String> user;\n   private Optional<List<Role>> roles;\n   private Optional<List<DataBag>> databags;\n   private RunList runlist;\n\n   protected ChefSolo(Optional<String> fileCachePath, Optional<String> rolePath, Optional<String> databagPath,\n         Optional<ImmutableList<String>> cookbookPath, Optional<String> cookbooksArchiveLocation,\n         Optional<String> jsonAttributes, Optional<String> group, Optional<Integer> interval,\n         Optional<String> logLevel, Optional<String> logFile, Optional<String> nodeName, Optional<Integer> splay,\n         Optional<String> user, Optional<List<Role>> roles, Optional<List<DataBag>> databags, Optional<RunList> runlist) {\n      this.fileCachePath = checkNotNull(fileCachePath, \"fileCachePath must be set\").or(DEFAULT_SOLO_PATH);\n      this.rolePath = checkNotNull(rolePath, \"rolePath must be set\").or(this.fileCachePath + \"/roles\");\n      this.databagPath = checkNotNull(databagPath, \"databagPath must be set\").or(this.fileCachePath + \"/data_bags\");\n      this.cookbooksArchiveLocation = checkNotNull(cookbooksArchiveLocation, \"cookbooksArchiveLocation must be set\");\n      this.jsonAttributes = checkNotNull(jsonAttributes, \"jsonAttributes must be set\");\n      this.group = checkNotNull(group, \"group must be set\");\n      this.interval = checkNotNull(interval, \"interval must be set\");\n      this.logLevel = checkNotNull(logLevel, \"logLevel must be set\");\n      this.logFile = checkNotNull(logFile, \"logFile must be set\");\n      this.nodeName = checkNotNull(nodeName, \"nodeName must be set\");\n      this.splay = checkNotNull(splay, \"splay must be set\");\n      this.user = checkNotNull(user, \"user must be set\");\n      this.roles = checkNotNull(roles, \"roles must be set\");\n      this.databags = checkNotNull(databags, \"databags must be set\");\n      this.runlist = checkNotNull(runlist, \"runlist must be set\").or(RunList.builder().build());\n      this.user = checkNotNull(user, \"user must be set\");\n      if (!checkNotNull(cookbookPath, \"cookbookPath must be set\").isPresent() || cookbookPath.get().isEmpty()) {\n         this.cookbookPath = ImmutableList.<String> of(this.fileCachePath + \"/cookbooks\");\n      } else {\n         this.cookbookPath = ImmutableList.<String> copyOf(cookbookPath.get());\n      }\n   }\n\n   @Override\n   public String render(OsFamily family) {\n      if (family == OsFamily.WINDOWS) {\n         throw new UnsupportedOperationException(\"windows not yet implemented\");\n      }\n\n      ImmutableList.Builder<Statement> statements = ImmutableList.builder();\n\n      checkChefIsInstalled(statements);\n      createSoloConfiguration(statements);\n      createRolesIfNecessary(statements);\n      createDatabagsIfNecessary(statements);\n      createNodeConfiguration(statements);\n\n      ImmutableMap.Builder<String, String> options = ImmutableMap.builder();\n      options.put(\"-c\", fileCachePath + \"/solo.rb\");\n      options.put(\"-j\", fileCachePath + \"/node.json\");\n      options.put(\"-N\", nodeName.or(\"`hostname`\"));\n\n      if (group.isPresent()) {\n         options.put(\"-g\", group.get());\n      }\n      if (interval.isPresent()) {\n         options.put(\"-i\", interval.get().toString());\n      }\n      if (logLevel.isPresent()) {\n         options.put(\"-l\", logLevel.get());\n      }\n      if (logFile.isPresent()) {\n         options.put(\"-L\", logFile.get());\n      }\n      if (cookbooksArchiveLocation.isPresent()) {\n         options.put(\"-r\", cookbooksArchiveLocation.get());\n      }\n      if (splay.isPresent()) {\n         options.put(\"-s\", splay.get().toString());\n      }\n      if (user.isPresent()) {\n         options.put(\"-u\", user.get());\n      }\n\n      String strOptions = Joiner.on(' ').withKeyValueSeparator(\" \").join(options.build());\n      statements.add(Statements.exec(String.format(\"chef-solo %s\", strOptions)));\n\n      return new StatementList(statements.build()).render(family);\n   }\n\n   @Override\n   public Iterable<String> functionDependencies(OsFamily family) {\n      return Collections.emptyList();\n   }\n   \n   private void checkChefIsInstalled(ImmutableList.Builder<Statement> statements) {\n      statements.add(exec(\"if ! hash chef-solo 2>/dev/null; then\"));\n      statements.add(exec(\"echo 'chef-solo not found. Please, install Chef first'\"));\n      statements.add(exec(\"exit 1\"));\n      statements.add(exec(\"fi\"));\n   }\n\n   @VisibleForTesting\n   void createSoloConfiguration(ImmutableList.Builder<Statement> statements) {\n      statements.add(exec(\"{md} \" + fileCachePath));\n      for (String path : cookbookPath) {\n         statements.add(exec(\"{md} \" + path));\n      }\n      String cookbookPathJoined = Joiner.on(',').join(transform(cookbookPath, quote()));\n      statements.add(createOrOverwriteFile(\n            fileCachePath + \"/solo.rb\",\n            ImmutableSet.of(\"file_cache_path \\\"\" + fileCachePath + \"\\\"\", //\n                  \"cookbook_path [\" + cookbookPathJoined + \"]\", \"role_path \\\"\" + rolePath + \"\\\"\", \"data_bag_path \\\"\"\n                        + databagPath + \"\\\"\")));\n   }\n\n   @VisibleForTesting\n   void createNodeConfiguration(ImmutableList.Builder<Statement> statements) {\n      StringBuilder json = new StringBuilder();\n      if (jsonAttributes.isPresent()) {\n         // Start the node configuration with the attributes, but remove the\n         // last bracket to append the run list to the json configuration\n         String attributes = jsonAttributes.get();\n         json.append(attributes, 0, attributes.lastIndexOf('}'));\n         json.append(\",\");\n      } else {\n         json.append(\"{\");\n      }\n      json.append(\"\\\"run_list\\\":\");\n      json.append(runlist.toString());\n      json.append(\"}\");\n\n      statements.add(createOrOverwriteFile(fileCachePath + \"/node.json\", ImmutableSet.of(json.toString())));\n   }\n\n   @VisibleForTesting\n   void createRolesIfNecessary(ImmutableList.Builder<Statement> statements) {\n      // The roles directory must contain one file for each role definition\n      if (roles.isPresent() && !roles.get().isEmpty()) {\n         statements.add(exec(\"{md} \" + rolePath));\n         for (Role role : roles.get()) {\n            statements.add(createOrOverwriteFile(rolePath + \"/\" + role.getName() + \".json\",\n                  ImmutableSet.of(role.toJsonString())));\n         }\n      }\n   }\n\n   @VisibleForTesting\n   void createDatabagsIfNecessary(ImmutableList.Builder<Statement> statements) {\n      // Each data bag item must be defined in a file inside the data bag\n      // directory, and each data bag item must have its own JSON file.\n      if (databags.isPresent() && !databags.get().isEmpty()) {\n         statements.add(exec(\"{md} \" + databagPath));\n         for (DataBag databag : databags.get()) {\n            String databagFolder = databagPath + \"/\" + databag.getName();\n            statements.add(exec(\"{md} \" + databagFolder));\n            for (Map.Entry<String, String> item : databag.getItems().entrySet()) {\n               statements.add(createOrOverwriteFile(databagFolder + \"/\" + item.getKey() + \".json\",\n                     ImmutableSet.of(item.getValue())));\n            }\n         }\n      }\n   }\n\n   private static Function<String, String> quote() {\n      return new Function<String, String>() {\n         @Override\n         public String apply(String input) {\n            return \"\\\"\" + input + \"\\\"\";\n         }\n      };\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/statements/chef/InstallChefGems.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.statements.chef;\n\nimport static org.jclouds.scriptbuilder.domain.Statements.exec;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.jclouds.scriptbuilder.domain.Statement;\n\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Installs Chef gems onto a host.\n * <p>\n * If you only want to install the Chef client and don't care about the version\n * of Ruby and Rubygems, use the {@link InstallChefUsingOmnibus} statement\n * instead.\n * \n * \n * @see InstallChefUsingOmnibus\n * @see InstallRuby\n * @see InstallRubyGems\n */\npublic class InstallChefGems implements Statement {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n      private Optional<String> version = Optional.absent();\n\n      /**\n       * The version of the Chef gem to install.\n       * <p>\n       * Can be something like '>= 0.10.8'.\n       */\n      public Builder version(@Nullable String version) {\n         this.version = Optional.fromNullable(version);\n         return this;\n      }\n\n      public InstallChefGems build() {\n         return new InstallChefGems(version);\n      }\n   }\n\n   private Optional<String> version;\n\n   protected InstallChefGems(Optional<String> version) {\n      this.version = version;\n   }\n\n   @Override\n   public String render(OsFamily family) {\n      if (family == OsFamily.WINDOWS) {\n         throw new UnsupportedOperationException(\"windows not yet implemented\");\n      }\n\n      Statement statement = version.isPresent() ? exec(String.format(\"gem install chef -v '%s' --no-rdoc --no-ri\",\n            version.get())) : exec(\"gem install chef --no-rdoc --no-ri\");\n\n      return statement.render(family);\n   }\n\n   @Override\n   public Iterable<String> functionDependencies(OsFamily family) {\n      return ImmutableSet.<String> of();\n   }\n\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/statements/chef/InstallChefUsingOmnibus.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.statements.chef;\n\nimport static org.jclouds.scriptbuilder.domain.Statements.call;\nimport static org.jclouds.scriptbuilder.domain.Statements.exec;\nimport static org.jclouds.scriptbuilder.domain.Statements.pipeHttpResponseToBash;\nimport static org.jclouds.scriptbuilder.domain.Statements.saveHttpResponseTo;\n\nimport java.net.URI;\n\nimport org.jclouds.scriptbuilder.domain.StatementList;\n\nimport com.google.common.collect.ImmutableMultimap;\n\n/**\n * Installs the Chef client using the Omnibus installer.\n * <p>\n * This will install an entire ruby distribution with all required gems in a\n * concrete directory so there is no need to manually download or configure any\n * Ruby version or gem.\n * <p>\n * If you want more control on the Ruby version or the gems being installed, use\n * the {@link InstallChefGems} statement instead.\n * \n * \n * @see InstallChefGems\n * @see org.jclouds.scriptbuilder.statements.ruby.InstallRuby\n */\npublic class InstallChefUsingOmnibus extends StatementList {\n\n   /** The URL for the Omnibus installer */\n   public static final String OMNIBUS_INSTALLER = \"https://www.opscode.com/chef/install.sh\";\n\n   public InstallChefUsingOmnibus() {\n      super(call(\"setupPublicCurl\"), pipeHttpResponseToBash(\"GET\", URI.create(OMNIBUS_INSTALLER),\n            ImmutableMultimap.<String, String> of()));\n   }\n\n   public InstallChefUsingOmnibus(String chefVersion) {\n      super(call(\"setupPublicCurl\"), saveHttpResponseTo(URI.create(OMNIBUS_INSTALLER), \"/tmp\", \"install-chef.sh\"),\n            exec(\"sh /tmp/install-chef.sh -v \" + chefVersion));\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/statements/git/CloneGitRepo.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.statements.git;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.net.URI;\n\nimport org.jclouds.scriptbuilder.domain.GitRepoAndRef;\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.jclouds.scriptbuilder.domain.Statement;\nimport org.jclouds.scriptbuilder.domain.Statements;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.Optional;\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.collect.Iterables;\n\n/**\n * Clones a gitRepoAndRef into a newly created directory, creates\n * remote-tracking branches for each branch in the cloned gitRepoAndRef (visible\n * using git branch -r), and creates and checks out an initial branch that is\n * forked from the cloned gitRepoAndRef's currently active branch. PWD is set to\n * the directory being checked out.\n */\npublic class CloneGitRepo implements Statement {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public Builder toBuilder() {\n      return new Builder().fromCloneGitRepo(this);\n   }\n\n   public static class Builder {\n\n      protected GitRepoAndRef.Builder gitRepoAndRef = GitRepoAndRef.builder();\n      protected Optional<String> directory = Optional.absent();\n\n      /**\n       * @see GitRepoAndRef#getRepository()\n       */\n      public Builder repository(URI repository) {\n         this.gitRepoAndRef.repository(repository);\n         return this;\n      }\n\n      /**\n       * @see GitRepoAndRef#getRepository()\n       */\n      public Builder repository(String repository) {\n         return repository(URI.create(repository));\n      }\n\n      /**\n       * @see GitRepoAndRef#getBranch()\n       */\n      public Builder branch(String branch) {\n         this.gitRepoAndRef.branch(branch);\n         return this;\n      }\n\n      /**\n       * @see GitRepoAndRef#getTag()\n       */\n      public Builder tag(String tag) {\n         this.gitRepoAndRef.tag(tag);\n         return this;\n      }\n\n      /**\n       * @see CloneGitRepo#getGitRepoAndRef()\n       */\n      public Builder gitRepoAndRef(GitRepoAndRef gitRepoAndRef) {\n         this.gitRepoAndRef.fromGitRepoAndRef(gitRepoAndRef);\n         return this;\n      }\n\n      /**\n       * @see CloneGitRepo#getDirectory()\n       */\n      public Builder directory(String directory) {\n         this.directory = Optional.fromNullable(directory);\n         return this;\n      }\n\n      public CloneGitRepo build() {\n         return new CloneGitRepo(gitRepoAndRef.build(), directory);\n      }\n\n      public Builder fromCloneGitRepo(CloneGitRepo in) {\n         return this.gitRepoAndRef(in.getGitRepoAndRef()).directory(in.getDirectory().orNull());\n      }\n   }\n\n   protected final GitRepoAndRef gitRepoAndRef;\n   protected final Optional<String> directory;\n\n   protected CloneGitRepo(GitRepoAndRef gitRepoAndRef, Optional<String> directory) {\n      this.gitRepoAndRef = checkNotNull(gitRepoAndRef, \"gitRepoAndRef\");\n      this.directory = checkNotNull(directory, \"directory\");\n   }\n\n   /**\n    * The coordinates to checkout\n    */\n   public GitRepoAndRef getGitRepoAndRef() {\n      return gitRepoAndRef;\n   }\n   \n   /**\n    * The name of a new directory to clone into. The \"humanish\" part of the\n    * source gitRepoAndRef is used if no directory is explicitly given (repo for\n    * /path/to/repo.git and foo for host.xz:foo/.git).\n    */\n   public Optional<String> getDirectory() {\n      return directory;\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(gitRepoAndRef, directory);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      CloneGitRepo other = CloneGitRepo.class.cast(obj);\n      return Objects.equal(this.gitRepoAndRef, other.gitRepoAndRef) && Objects.equal(this.directory, other.directory);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public Iterable<String> functionDependencies(OsFamily arg0) {\n      return ImmutableSet.<String> of();\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String render(OsFamily arg0) {\n      StringBuilder command = new StringBuilder();\n      command.append(\"git clone\");\n      if (gitRepoAndRef.getBranch().isPresent())\n         command.append(\" -b \").append(gitRepoAndRef.getBranch().get());\n      command.append(' ').append(gitRepoAndRef.getRepository().toASCIIString());\n      if (directory.isPresent())\n         command.append(' ').append(directory.get());\n      command.append(\"{lf}\");\n      command.append(\"{cd} \").append(\n            directory.or(Iterables.getLast(Splitter.on('/').split(gitRepoAndRef.getRepository().getPath())).replace(\".git\", \"\")));\n      if (gitRepoAndRef.getTag().isPresent()) {\n         command.append(\"{lf}\").append(\"git checkout \").append(gitRepoAndRef.getTag().get());\n      }\n      return Statements.exec(command.toString()).render(arg0);\n   }\n\n   /**\n    * {@inheritDoc}\n    */\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).omitNullValues().add(\"gitRepoAndRef\", gitRepoAndRef)\n            .add(\"directory\", directory.orNull()).toString();\n   }\n\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/statements/git/InstallGit.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.statements.git;\n\nimport static org.jclouds.scriptbuilder.domain.Statements.call;\n\nimport org.jclouds.scriptbuilder.domain.StatementList;\n\n/**\n * Installs git onto a host\n */\npublic class InstallGit extends StatementList {\n\n   public InstallGit() {\n      super(call(\"setupPublicCurl\"), call(\"installGit\"));\n   }\n\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/statements/java/InstallJDK.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.statements.java;\n\nimport static org.jclouds.scriptbuilder.domain.Statements.call;\n\nimport java.net.URI;\n\nimport org.jclouds.scriptbuilder.domain.Statement;\nimport org.jclouds.scriptbuilder.domain.StatementList;\n\n/**\n * Installs a default JDK to a host\n */\npublic class InstallJDK {\n\n   public static Statement fromOpenJDK() {\n      return new FromOpenJDK();\n   }\n\n   public static Statement fromURL(URI url) {\n      return new FromURL(url);\n   }\n\n   public static class FromOpenJDK extends StatementList {\n\n      public FromOpenJDK() {\n         super(call(\"setupPublicCurl\"), call(\"installOpenJDK\"));\n      }\n\n   }\n\n   public static class FromURL extends StatementList {\n\n      public FromURL() {\n         super(call(\"setupPublicCurl\"), call(\"installJDKFromURL\"));\n      }\n\n      public FromURL(URI jdk7Url) {\n         super(call(\"setupPublicCurl\"), call(\"installJDKFromURL\", jdk7Url.toASCIIString()));\n      }\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/statements/login/AdminAccess.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.statements.login;\n\nimport static com.google.common.base.Charsets.UTF_8;\nimport static com.google.common.base.Preconditions.checkArgument;\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Preconditions.checkState;\nimport static com.google.common.base.Predicates.isNull;\nimport static com.google.common.base.Throwables.propagate;\nimport static com.google.common.collect.Iterables.any;\nimport static com.google.common.collect.Lists.newArrayList;\nimport static org.jclouds.scriptbuilder.statements.login.ShadowStatements.resetLoginUserPasswordTo;\nimport static org.jclouds.scriptbuilder.statements.ssh.SshStatements.lockSshd;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.Map;\n\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.jclouds.scriptbuilder.domain.Statement;\nimport org.jclouds.scriptbuilder.domain.StatementList;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.io.Files;\n\n/**\n * Controls the administrative access to a node. By default, it will perform the following:\n * \n * <ul>\n *   <li>setup a new admin user which folks should use as opposed to any built-in account</li>\n *   <ul>\n *     <li>associate a random (or given) password to that account\n *     <ul>\n *       <li>securely (using sha 512 on client side and literally rewriting the shadow entry, \n *           rather than sending password plaintext to OS in a script)</li>\n *       <li>but note password access is often blocked in any case, see below</li>\n *     </ul>\n *     <li>associate the users' ssh public key with the account for login</li> \n *     <li>associate it with the os group wheel</li> \n *   </ul> \n *   <li>set up sudoers for password-less access to root for this user (shouldGrantSudo)</li>\n *   <ul>\n *     <li>creating os group wheel and assigning the new admin user to it</li> \n *     <li>create (overwriting) sudoers file to grant root access for wheel members</li>\n *   </ul>\n *   <li>reset password for the user logging in (e.g. root, because root password is \n *   sometimes known to the provider), securely and randomly as described above (resetLoginPassword)</li>\n *   <li>lockdown sshd_config for no root login, nor passwords allowed (lockSsh)</li> \n * </ul>\n */\npublic class AdminAccess implements Statement {\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static AdminAccess standard() {\n      return new Builder().build();\n   }\n\n   public interface Configuration {\n      Supplier<String> defaultAdminUsername();\n\n      Supplier<Map<String, String>> defaultAdminSshKeys();\n\n      Supplier<String> passwordGenerator();\n\n      Function<String, String> cryptFunction();\n   }\n\n   public static class Builder {\n      private Function<String, String> cryptFunction;\n      private String adminUsername;\n      private String adminFullName;\n      private String adminHome;\n      private String adminPublicKey;\n      private File adminPublicKeyFile;\n      private String adminPrivateKey;\n      private File adminPrivateKeyFile;\n      private String adminPassword;\n      private String loginPassword;\n      private boolean lockSsh = true;\n      private boolean grantSudoToAdminUser = true;\n      private boolean authorizeAdminPublicKey = true;\n      private boolean installAdminPrivateKey = false;\n      private boolean resetLoginPassword = true;\n      \n      public Builder cryptFunction(Function<String, String> cryptFunction) {\n         this.cryptFunction = cryptFunction;\n         return this;\n      }\n      \n      public Builder adminUsername(String adminUsername) {\n         this.adminUsername = checkNotRoot(adminUsername);\n         return this;\n      }\n\n      public Builder adminFullName(String adminFullName) {\n         this.adminFullName = adminFullName;\n         return this;\n      }\n\n\n      public Builder adminHome(String adminHome) {\n         this.adminHome = adminHome;\n         return this;\n      }\n\n      public Builder adminPassword(String adminPassword) {\n         this.adminPassword = adminPassword;\n         return this;\n      }\n\n      public Builder loginPassword(String loginPassword) {\n         this.loginPassword = loginPassword;\n         return this;\n      }\n\n      public Builder lockSsh(boolean lockSsh) {\n         this.lockSsh = lockSsh;\n         return this;\n      }\n\n      public Builder resetLoginPassword(boolean resetLoginPassword) {\n         this.resetLoginPassword = resetLoginPassword;\n         return this;\n      }\n\n      public Builder authorizeAdminPublicKey(boolean authorizeAdminPublicKey) {\n         this.authorizeAdminPublicKey = authorizeAdminPublicKey;\n         return this;\n      }\n\n      public Builder installAdminPrivateKey(boolean installAdminPrivateKey) {\n         this.installAdminPrivateKey = installAdminPrivateKey;\n         return this;\n      }\n\n      public Builder grantSudoToAdminUser(boolean grantSudoToAdminUser) {\n         this.grantSudoToAdminUser = grantSudoToAdminUser;\n         return this;\n      }\n\n      public Builder adminPublicKey(File adminPublicKey) {\n         this.adminPublicKeyFile = adminPublicKey;\n         this.adminPublicKey = null;\n         return this;\n      }\n\n      public Builder adminPublicKey(String adminPublicKey) {\n         this.adminPublicKey = adminPublicKey;\n         this.adminPublicKeyFile = null;\n         return this;\n      }\n\n      public Builder adminPrivateKey(File adminPrivateKey) {\n         this.adminPrivateKeyFile = adminPrivateKey;\n         this.adminPrivateKey = null;\n         return this;\n      }\n\n      public Builder adminPrivateKey(String adminPrivateKey) {\n         this.adminPrivateKey = adminPrivateKey;\n         this.adminPrivateKeyFile = null;\n         return this;\n      }\n      \n      public Builder from(AdminAccessBuilderSpec spec) {\n         return spec.copyTo(this);\n      }\n\n      public Builder from(String spec) {\n         return from(AdminAccessBuilderSpec.parse(spec));\n      }\n\n      public AdminAccess build() {\n         return new AdminAccess(buildConfig());\n      }\n\n      protected Config buildConfig() {\n         try {\n            String adminPublicKey = this.adminPublicKey;\n            if (adminPublicKey == null && adminPublicKeyFile != null)\n               adminPublicKey = Files.toString(adminPublicKeyFile, UTF_8);\n            String adminPrivateKey = this.adminPrivateKey;\n            if (adminPrivateKey == null && adminPrivateKeyFile != null)\n               adminPrivateKey = Files.toString(adminPrivateKeyFile, UTF_8);\n            return new Config(adminUsername, adminFullName, adminHome, adminPublicKey, adminPrivateKey, adminPassword, loginPassword,\n                     lockSsh, grantSudoToAdminUser, authorizeAdminPublicKey, installAdminPrivateKey, resetLoginPassword,\n                     cryptFunction);\n         } catch (IOException e) {\n            throw propagate(e);\n         }\n      }\n   }\n\n   protected static class Config {\n      private final String adminUsername;\n      private final String adminFullName;\n      private final String adminHome;\n      private final String adminPublicKey;\n      private final String adminPrivateKey;\n      private final String adminPassword;\n      private final String loginPassword;\n      private final boolean grantSudoToAdminUser;\n      private final boolean installAdminPrivateKey;\n      private final boolean resetLoginPassword;\n      private final Function<String, String> cryptFunction;\n      private final Credentials adminCredentials;\n      private boolean authorizeAdminPublicKey;\n      private boolean lockSsh;\n\n      protected Config(@Nullable String adminUsername, @Nullable String adminFullName, @Nullable String adminHome, @Nullable String adminPublicKey,\n               @Nullable String adminPrivateKey, @Nullable String adminPassword, @Nullable String loginPassword,\n               boolean lockSsh, boolean grantSudoToAdminUser, boolean authorizeAdminPublicKey,\n               boolean installAdminPrivateKey, boolean resetLoginPassword, Function<String, String> cryptFunction) {\n         this.adminUsername = adminUsername;\n         this.adminFullName = adminFullName;\n         this.adminHome = adminHome;\n         this.adminPublicKey = adminPublicKey;\n         this.adminPrivateKey = adminPrivateKey;\n         this.adminPassword = adminPassword;\n         this.loginPassword = loginPassword;\n         this.lockSsh = lockSsh;\n         this.grantSudoToAdminUser = grantSudoToAdminUser;\n         this.authorizeAdminPublicKey = authorizeAdminPublicKey;\n         this.installAdminPrivateKey = installAdminPrivateKey;\n         this.resetLoginPassword = resetLoginPassword;\n         this.cryptFunction = cryptFunction;\n         if (adminUsername != null && authorizeAdminPublicKey && adminPrivateKey != null)\n            this.adminCredentials = new Credentials(adminUsername, adminPrivateKey);\n         else if (adminUsername != null && adminPassword != null) {\n            this.adminCredentials = new Credentials(adminUsername, adminPassword);\n            // if we're using password make sure we don't auth pubkey and that we don't lock ssh\n            this.authorizeAdminPublicKey = false;\n            this.lockSsh = false;\n         }\n         else\n            this.adminCredentials = null;\n      }\n\n      public String getAdminUsername() {\n         return adminUsername;\n      }\n\n      public String getAdminFullName() {\n         return adminFullName;\n      }\n\n      public String getAdminHome() {\n         return adminHome;\n      }\n\n      public String getAdminPublicKey() {\n         return adminPublicKey;\n      }\n\n      public String getAdminPrivateKey() {\n         return adminPrivateKey;\n      }\n\n      public String getAdminPassword() {\n         return adminPassword;\n      }\n\n      public String getLoginPassword() {\n         return loginPassword;\n      }\n\n      public boolean shouldLockSsh() {\n         return lockSsh;\n      }\n\n      public boolean shouldGrantSudoToAdminUser() {\n         return grantSudoToAdminUser;\n      }\n\n      public boolean shouldAuthorizeAdminPublicKey() {\n         return authorizeAdminPublicKey;\n      }\n\n      public boolean shouldInstallAdminPrivateKey() {\n         return installAdminPrivateKey;\n      }\n\n      public boolean shouldResetLoginPassword() {\n         return resetLoginPassword;\n      }\n\n      public Function<String, String> getCryptFunction() {\n         return cryptFunction;\n      }\n\n      public Credentials getAdminCredentials() {\n         return adminCredentials;\n      }\n\n      @Override\n      public String toString() {\n         StringBuilder builder = new StringBuilder();\n         builder.append(\"Config [adminUsername=\").append(adminUsername).append(\", adminFullName=\").append(adminFullName)\n                  .append(\", adminHome=\").append(adminHome)\n                  .append(\", adminPublicKey=\").append(adminPublicKey == null ? \"null\" : \"present\")\n                  .append(\", adminPrivateKey=\").append(adminPrivateKey == null ? \"null\" : \"present\")\n                  .append(\", adminPassword=\").append(adminPassword == null ? \"null\" : \"present\")\n                  .append(\", loginPassword=\").append(loginPassword == null ? \"null\" : \"present\").append(\", lockSsh=\")\n                  .append(lockSsh).append(\", grantSudoToAdminUser=\").append(grantSudoToAdminUser)\n                  .append(\", authorizeAdminPublicKey=\").append(authorizeAdminPublicKey)\n                  .append(\", installAdminPrivateKey=\").append(installAdminPrivateKey).append(\", resetLoginPassword=\")\n                  .append(resetLoginPassword).append(\", cryptFunction=\").append(cryptFunction)\n                  .append(\", adminCredentials=\").append(adminCredentials).append(\"]\");\n         return builder.toString();\n      }\n      \n      \n   }\n\n   @VisibleForTesting\n   Config config;\n\n   protected AdminAccess(Config in) {\n      this.config = checkNotNull(in, \"in\");\n   }\n\n   /**\n    * \n    * @return new credentials or null if unchanged or unavailable\n    */\n   @Nullable\n   public Credentials getAdminCredentials() {\n      return config.getAdminCredentials();\n   }\n\n   @Nullable\n   public String getAdminPassword() {\n      return config.getAdminPassword();\n   }\n\n   public boolean shouldGrantSudoToAdminUser() {\n      return config.shouldGrantSudoToAdminUser();\n   }\n\n   @Override\n   public Iterable<String> functionDependencies(OsFamily family) {\n      return ImmutableList.of();\n   }\n\n   public AdminAccess init(Configuration configuration) {\n      Builder builder = AdminAccess.builder();\n      builder.cryptFunction(config.getCryptFunction() != null ? config.getCryptFunction() : configuration.cryptFunction());\n      builder.adminUsername(config.getAdminUsername() != null ? config.getAdminUsername() : configuration\n               .defaultAdminUsername().get());\n      builder.adminFullName(config.getAdminFullName() != null ? config.getAdminFullName() : builder.adminUsername);\n      builder.adminHome(config.getAdminHome());\n      builder.adminPassword(config.getAdminPassword() != null ? config.getAdminPassword() : configuration\n               .passwordGenerator().get());\n      Map<String, String> adminSshKeys = (config.getAdminPublicKey() != null && config.getAdminPrivateKey() != null) ? ImmutableMap\n               .of(\"public\", config.getAdminPublicKey(), \"private\", config.getAdminPrivateKey())\n               : configuration.defaultAdminSshKeys().get();\n      builder.adminPublicKey(adminSshKeys.get(\"public\"));\n      builder.adminPrivateKey(adminSshKeys.get(\"private\"));\n      builder.loginPassword(config.getLoginPassword() != null ? config.getLoginPassword() : configuration\n               .passwordGenerator().get());\n      builder.grantSudoToAdminUser(config.shouldGrantSudoToAdminUser());\n      builder.authorizeAdminPublicKey(config.shouldAuthorizeAdminPublicKey());\n      builder.installAdminPrivateKey(config.shouldInstallAdminPrivateKey());\n      builder.lockSsh(config.shouldLockSsh());\n      builder.resetLoginPassword(config.shouldResetLoginPassword());\n      this.config = builder.buildConfig();\n      return this;\n   }\n\n   @Override\n   public String render(OsFamily family) {\n      checkNotNull(family, \"family\");\n      if (family == OsFamily.WINDOWS)\n         throw new UnsupportedOperationException(\"windows not yet implemented\");\n      checkState(\n            !any(newArrayList(config.getAdminUsername(), config.getAdminPassword(), config.getAdminPublicKey(),\n                  config.getAdminPrivateKey(), config.getLoginPassword()), isNull()), \"please call init() first\");\n      checkNotRoot(config.getAdminUsername());\n      checkNotNull(config.getAdminPassword(), \"adminPassword\");\n      checkNotNull(config.getAdminPublicKey(), \"adminPublicKey\");\n      checkNotNull(config.getAdminPrivateKey(), \"adminPrivateKey\");\n      checkNotNull(config.getLoginPassword(), \"loginPassword\");\n      \n      ImmutableList.Builder<Statement> statements = ImmutableList.builder();\n      UserAdd.Builder userBuilder = UserAdd.builder();\n      userBuilder.login(config.getAdminUsername());\n      userBuilder.fullName(config.getAdminFullName());\n      if (config.getAdminHome() != null)\n         userBuilder.home(config.getAdminHome());\n      if (config.shouldAuthorizeAdminPublicKey())\n         userBuilder.authorizeRSAPublicKey(config.getAdminPublicKey());\n      userBuilder.password(config.getAdminPassword());\n      if (config.shouldInstallAdminPrivateKey())\n         userBuilder.installRSAPrivateKey(config.getAdminPrivateKey());\n      if (config.shouldGrantSudoToAdminUser()) {\n         statements.add(SudoStatements.createWheel());\n         userBuilder.group(\"wheel\");\n      }\n      statements.add(userBuilder.cryptFunction(config.getCryptFunction()).build());\n      if (config.shouldLockSsh())\n         statements.add(lockSshd());\n      if (config.shouldResetLoginPassword()) {\n         statements.add(resetLoginUserPasswordTo(config.getCryptFunction(), config.getLoginPassword()));\n      }\n      return new StatementList(statements.build()).render(family);\n   }\n\n   private static String checkNotRoot(String user) {\n      checkArgument(!\"root\".equals(checkNotNull(user, \"adminUsername\")), \"cannot create admin user 'root'; \"\n            + \"ensure jclouds is not running as root, or specify an explicit non-root username in AdminAccess\");\n      return user;\n   }\n\n   @Override\n   public String toString() {\n      StringBuilder builder2 = new StringBuilder();\n      builder2.append(\"AdminAccess [config=\").append(config).append(\", getAdminCredentials()=\")\n               .append(getAdminCredentials()).append(\", shouldGrantSudoToAdminUser()=\")\n               .append(shouldGrantSudoToAdminUser()).append(\"]\");\n      return builder2.toString();\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/statements/login/AdminAccessBuilderSpec.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.statements.login;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.MoreObjects.toStringHelper;\nimport static com.google.common.base.Preconditions.checkArgument;\n\nimport java.io.File;\nimport java.util.Arrays;\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\n\nimport com.google.common.annotations.VisibleForTesting;\nimport com.google.common.base.Objects;\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * A specification of a {@link AdminAccess.Builder} configuration.\n * \n * <p>\n * {@code AdminAccess.Builder} supports parsing configuration off of a string, which makes it\n * especially useful for command-line configuration of a {@code AdminAccess.Builder}.\n * \n * <p>\n * The string syntax is a series of comma-separated keys or key-value pairs, each corresponding to a\n * {@code AdminAccess.Builder} method.\n * <ul>\n * <li>{@code adminUsername=[String]}: sets {@link AdminAccess.Builder#adminUsername}.\n * <li>{@code adminHome=[String]}: sets {@link AdminAccess.Builder#adminHome}.\n * <li>{@code adminPublicKeyFile=[String]}: sets {@link AdminAccess.Builder#adminPublicKeyFile}.\n * <li>{@code adminPrivateKeyFile=[String]}: sets {@link AdminAccess.Builder#adminPrivateKeyFile}. *\n * <li>{@code adminPassword=[String]}: sets {@link AdminAccess.Builder#adminPassword}.\n * <li>{@code loginPassword=[String]}: sets {@link AdminAccess.Builder#loginPassword}.\n * <li>{@code lockSsh=[Boolean]}: sets {@link TemplateBuilder#lockSsh}.\n * <li>{@code grantSudoToAdminUser=[Boolean]}: sets {@link TemplateBuilder#grantSudoToAdminUser}.\n * <li>{@code authorizeAdminPublicKey=[Boolean]}: sets\n * {@link TemplateBuilder#authorizeAdminPublicKey}.\n * <li>{@code installAdminPrivateKey=[Boolean]}: sets {@link TemplateBuilder#installAdminPrivateKey}.\n * <li>{@code resetLoginPassword=[Boolean]}: sets {@link TemplateBuilder#resetLoginPassword}.\n * </ul>\n * \n * <p>\n * Whitespace before and after commas and equal signs is ignored. Keys may not be repeated and both\n * private key and public key must be passed through files, as they might include weird characters.\n * \n * <p>\n * {@code AdminAccessBuilderSpec} does not support configuring {@code AdminAccess.Builder} methods\n * with non-value parameters. These must be configured in code.\n * \n * <p>\n * A new {@code AdminAccess.Builder} can be instantiated from a {@code AdminAccessBuilderSpec} using\n * {@link AdminAccess.Builder#from(AdminAccessBuilderSpec)} or\n * {@link AdminAccess.Builder#from(String)}.\n * \n * <p>\n * Design inspired by {@link CacheBuilderSpec}\n * \n * @since 1.5\n */\n\npublic class AdminAccessBuilderSpec {\n\n   /** Parses a single value. */\n   protected interface ValueParser {\n      void parse(AdminAccessBuilderSpec spec, String key, @Nullable String value);\n   }\n\n   /** Splits each key-value pair. */\n   protected static final Splitter KEYS_SPLITTER = Splitter.on(',').trimResults();\n\n   /** Splits the key from the value. */\n   protected static final Splitter KEY_VALUE_SPLITTER = Splitter.on('=').trimResults();\n\n   /** Map of names to ValueParser. */\n   protected static final ImmutableMap<String, ValueParser> VALUE_PARSERS = ImmutableMap\n            .<String, ValueParser> builder().put(\"adminUsername\", new AdminUserNameParser())\n            .put(\"adminHome\", new AdminHomeParser()).put(\"adminPublicKeyFile\", new AdminPublicKeyFileParser())\n            .put(\"adminPrivateKeyFile\", new AdminPrivateKeyFileParser())\n            .put(\"adminPassword\", new AdminPasswordParser()).put(\"loginPassword\", new LoginPasswordParser())\n            .put(\"lockSsh\", new LockSshParser()).put(\"grantSudoToAdminUser\", new GrantSudoToAdminUserParser())\n            .put(\"authorizeAdminPublicKey\", new AuthorizeAdminPublicKeyParser())\n            .put(\"installAdminPrivateKey\", new InstallAdminPrivateKeyParser())\n            .put(\"resetLoginPassword\", new ResetLoginPasswordParser()).build();\n\n   @VisibleForTesting\n   String adminUsername;\n   @VisibleForTesting\n   String adminHome;\n   @VisibleForTesting\n   File adminPublicKeyFile;\n   @VisibleForTesting\n   File adminPrivateKeyFile;\n   @VisibleForTesting\n   String adminPassword;\n   @VisibleForTesting\n   String loginPassword;\n   @VisibleForTesting\n   Boolean lockSsh;\n   @VisibleForTesting\n   Boolean grantSudoToAdminUser;\n   @VisibleForTesting\n   Boolean authorizeAdminPublicKey;\n   @VisibleForTesting\n   Boolean installAdminPrivateKey;\n   @VisibleForTesting\n   Boolean resetLoginPassword;\n\n   /** Base class for parsing strings. */\n   abstract static class StringParser implements ValueParser {\n      protected abstract void set(AdminAccessBuilderSpec spec, String value);\n\n      @Override\n      public void parse(AdminAccessBuilderSpec spec, String key, String value) {\n         checkArgument(value != null && !value.isEmpty(), \"value of key %s omitted\", key);\n         set(spec, value);\n      }\n   }\n\n   /** Base class for parsing booleans. */\n   abstract static class BooleanParser implements ValueParser {\n      protected abstract void parseBoolean(AdminAccessBuilderSpec spec, boolean value);\n\n      @Override\n      public void parse(AdminAccessBuilderSpec spec, String key, String value) {\n         checkArgument(value != null && !value.isEmpty(), \"value of key %s omitted\", key);\n         try {\n            parseBoolean(spec, Boolean.parseBoolean(value));\n         } catch (NumberFormatException e) {\n            throw new IllegalArgumentException(String.format(\"key %s value set to %s, must be booleans\", key, value), e);\n         }\n      }\n   }\n\n   /** Base class for parsing files. */\n   abstract static class FileParser implements ValueParser {\n      protected abstract void set(AdminAccessBuilderSpec spec, File value);\n\n      @Override\n      public void parse(AdminAccessBuilderSpec spec, String key, String value) {\n         checkArgument(value != null && !value.isEmpty(), \"value of key %s omitted\", key);\n         File file = new File(value);\n         if (!file.exists()) {\n            throw new IllegalArgumentException(String.format(\"key %s value set to %s, must be an existing file\", key,\n                     value));\n         }\n         set(spec, file);\n      }\n   }\n\n   /** Parse adminUsername */\n   static class AdminUserNameParser extends StringParser {\n      @Override\n      protected void set(AdminAccessBuilderSpec spec, String value) {\n         checkArgument(spec.adminUsername == null, \"admin username was already set to \", spec.adminUsername);\n         spec.adminUsername = value;\n      }\n   }\n\n   /** Parse adminHome */\n   static class AdminHomeParser extends StringParser {\n      @Override\n      protected void set(AdminAccessBuilderSpec spec, String value) {\n         checkArgument(spec.adminHome == null, \"admin home was already set to \", spec.adminHome);\n         spec.adminHome = value;\n      }\n   }\n\n   /** Parse adminPublicKeyFile */\n   static class AdminPublicKeyFileParser extends FileParser {\n      @Override\n      protected void set(AdminAccessBuilderSpec spec, File value) {\n         checkArgument(spec.adminPublicKeyFile == null, \"admin public key file was already set to \",\n                  spec.adminPublicKeyFile);\n         spec.adminPublicKeyFile = value;\n      }\n   }\n\n   /** Parse adminPrivateKeyFile */\n   static class AdminPrivateKeyFileParser extends FileParser {\n      @Override\n      protected void set(AdminAccessBuilderSpec spec, File value) {\n         checkArgument(spec.adminPrivateKeyFile == null, \"admin private key file was already set to \",\n                  spec.adminPrivateKeyFile);\n         spec.adminPrivateKeyFile = value;\n      }\n   }\n\n   /** Parse adminPassword */\n   static class AdminPasswordParser extends StringParser {\n      @Override\n      protected void set(AdminAccessBuilderSpec spec, String value) {\n         checkArgument(spec.adminPassword == null, \"admin password was already set to \", spec.adminPassword);\n         spec.adminPassword = value;\n      }\n   }\n\n   /** Parse loginPassword */\n   static class LoginPasswordParser extends StringParser {\n      @Override\n      protected void set(AdminAccessBuilderSpec spec, String value) {\n         checkArgument(spec.loginPassword == null, \"login password was already set to \", spec.loginPassword);\n         spec.loginPassword = value;\n      }\n   }\n\n   /** Parse lockSsh */\n   static class LockSshParser extends BooleanParser {\n      @Override\n      protected void parseBoolean(AdminAccessBuilderSpec spec, boolean value) {\n         checkArgument(spec.loginPassword == null, \"lockSsh was already set to \", spec.lockSsh);\n         spec.lockSsh = value;\n      }\n   }\n\n   /** Parse grantSudoToAdminUser */\n   static class GrantSudoToAdminUserParser extends BooleanParser {\n      @Override\n      protected void parseBoolean(AdminAccessBuilderSpec spec, boolean value) {\n         checkArgument(spec.grantSudoToAdminUser == null, \"grant sudo to admin user was already set to \",\n                  spec.grantSudoToAdminUser);\n         spec.grantSudoToAdminUser = value;\n      }\n   }\n\n   /** Parse authorizeAdminPublicKey */\n   static class AuthorizeAdminPublicKeyParser extends BooleanParser {\n      @Override\n      protected void parseBoolean(AdminAccessBuilderSpec spec, boolean value) {\n         checkArgument(spec.authorizeAdminPublicKey == null, \"authorize admin public key was already set to \",\n                  spec.authorizeAdminPublicKey);\n         spec.authorizeAdminPublicKey = value;\n      }\n   }\n\n   /** Parse installPrivateKey */\n   static class InstallAdminPrivateKeyParser extends BooleanParser {\n      @Override\n      protected void parseBoolean(AdminAccessBuilderSpec spec, boolean value) {\n         checkArgument(spec.installAdminPrivateKey == null, \"install admin private key was already set to \",\n                  spec.installAdminPrivateKey);\n         spec.installAdminPrivateKey = value;\n      }\n   }\n\n   /** Parse resetLoginPassword */\n   static class ResetLoginPasswordParser extends BooleanParser {\n      @Override\n      protected void parseBoolean(AdminAccessBuilderSpec spec, boolean value) {\n         checkArgument(spec.resetLoginPassword == null, \"reset login password was already set to \",\n                  spec.resetLoginPassword);\n         spec.resetLoginPassword = value;\n      }\n   }\n\n   /** Specification; used for toParseableString(). */\n   // transient in case people using serializers don't want this to show up\n   protected transient String[] specifications;\n\n   protected AdminAccessBuilderSpec() {\n      // we want serializers like Gson to work w/o using sun.misc.Unsafe,\n      // prohibited in GAE. This also implies fields are not final.\n      // see http://code.google.com/p/jclouds/issues/detail?spec=925\n   }\n\n   protected AdminAccessBuilderSpec(String... specifications) {\n      this.specifications = specifications;\n   }\n\n   /**\n    * Creates a AdminAccessBuilderSpec from multiple specifications,\n    * \n    * @param adminAccessSpecification\n    *           the string form\n    */\n   public static AdminAccessBuilderSpec parse(String adminAccessSpecification) {\n      AdminAccessBuilderSpec spec = new AdminAccessBuilderSpec(adminAccessSpecification);\n      if (!adminAccessSpecification.isEmpty()) {\n         for (String keyValuePair : KEYS_SPLITTER.split(adminAccessSpecification)) {\n            List<String> keyAndValue = ImmutableList.copyOf(KEY_VALUE_SPLITTER.split(keyValuePair));\n            checkArgument(!keyAndValue.isEmpty(), \"blank key-value pair\");\n            checkArgument(keyAndValue.size() <= 2, \"key-value pair %s with more than one equals sign\", keyValuePair);\n\n            // Find the ValueParser for the current key.\n            String key = keyAndValue.get(0);\n            ValueParser valueParser = VALUE_PARSERS.get(key);\n            checkArgument(valueParser != null, \"unknown key %s\", key);\n\n            String value = keyAndValue.size() == 1 ? null : keyAndValue.get(1);\n            valueParser.parse(spec, key, value);\n         }\n      }\n      return spec;\n   }\n\n   /**\n    * Returns a AdminAccess.Builder configured according to this instance's specification.\n    */\n   public AdminAccess.Builder copyTo(AdminAccess.Builder builder) {\n      if (adminUsername != null) {\n         builder.adminUsername(adminUsername);\n      }\n      if (adminHome != null) {\n         builder.adminHome(adminHome);\n      }\n      if (adminPublicKeyFile != null) {\n         builder.adminPublicKey(adminPublicKeyFile);\n      }\n      if (adminPrivateKeyFile != null) {\n         builder.adminPrivateKey(adminPrivateKeyFile);\n      }\n      if (adminPassword != null) {\n         builder.adminPassword(adminPassword);\n      }\n      if (loginPassword != null) {\n         builder.loginPassword(loginPassword);\n      }\n      if (lockSsh != null) {\n         builder.lockSsh(lockSsh);\n      }\n      if (grantSudoToAdminUser != null) {\n         builder.grantSudoToAdminUser(grantSudoToAdminUser);\n      }\n      if (authorizeAdminPublicKey != null) {\n         builder.authorizeAdminPublicKey(authorizeAdminPublicKey);\n      }\n      if (installAdminPrivateKey != null) {\n         builder.installAdminPrivateKey(installAdminPrivateKey);\n      }\n      if (resetLoginPassword != null) {\n         builder.resetLoginPassword(resetLoginPassword);\n      }\n      return builder;\n   }\n\n   /**\n    * Returns a string that can be used to parse an equivalent {@code AdminAccessSpec}. The order\n    * and form of this representation is not guaranteed, except that reparsing its output will\n    * produce a {@code AdminAccessSpec} equal to this instance.\n    */\n   public String[] toParsableStrings() {\n      return specifications;\n   }\n\n   /**\n    * Returns a string representation for this AdminAccessSpec instance. The form of this\n    * representation is not guaranteed.\n    */\n   @Override\n   public String toString() {\n      return toStringHelper(this).addValue(Arrays.toString(toParsableStrings())).toString();\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(adminUsername, adminHome, adminPublicKeyFile, adminPrivateKeyFile, adminPassword,\n               loginPassword, lockSsh, grantSudoToAdminUser, authorizeAdminPublicKey, installAdminPrivateKey,\n               resetLoginPassword);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj) {\n         return true;\n      }\n      if (!(obj instanceof AdminAccessBuilderSpec)) {\n         return false;\n      }\n      AdminAccessBuilderSpec that = (AdminAccessBuilderSpec) obj;\n      return equal(adminUsername, that.adminUsername) && equal(adminHome, that.adminHome)\n               && equal(adminPublicKeyFile, that.adminPublicKeyFile)\n               && equal(adminPrivateKeyFile, that.adminPrivateKeyFile) && equal(adminPassword, that.adminPassword)\n               && equal(loginPassword, that.loginPassword) && equal(lockSsh, that.lockSsh)\n               && equal(grantSudoToAdminUser, that.grantSudoToAdminUser)\n               && equal(authorizeAdminPublicKey, that.authorizeAdminPublicKey)\n               && equal(installAdminPrivateKey, that.installAdminPrivateKey)\n               && equal(resetLoginPassword, that.resetLoginPassword);\n   }\n\n   public String getAdminUsername() {\n      return adminUsername;\n   }\n\n   public String getAdminHome() {\n      return adminHome;\n   }\n\n   public File getAdminPublicKeyFile() {\n      return adminPublicKeyFile;\n   }\n\n   public File getAdminPrivateKeyFile() {\n      return adminPrivateKeyFile;\n   }\n\n   public String getAdminPassword() {\n      return adminPassword;\n   }\n\n   public String getLoginPassword() {\n      return loginPassword;\n   }\n\n   public Boolean getLockSsh() {\n      return lockSsh;\n   }\n\n   public Boolean getGrantSudoToAdminUser() {\n      return grantSudoToAdminUser;\n   }\n\n   public Boolean getInstallAdminPrivateKey() {\n      return installAdminPrivateKey;\n   }\n\n   public Boolean getResetLoginPassword() {\n      return resetLoginPassword;\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/statements/login/ReplaceShadowPasswordEntry.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.statements.login;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.base.Throwables.propagate;\nimport static java.lang.String.format;\nimport static org.jclouds.scriptbuilder.domain.Statements.exec;\n\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.jclouds.scriptbuilder.domain.Statement;\nimport org.jclouds.scriptbuilder.domain.StatementList;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Replaces the password entry for a user in the shadow file, using SHA-512\n * crypt syntax.\n */\npublic class ReplaceShadowPasswordEntry implements Statement {\n\n   private final Function<String, String> cryptFunction;\n   private final String login;\n   private final String password;\n\n   public ReplaceShadowPasswordEntry(Function<String, String> cryptFunction, String login, String password) {\n      this.cryptFunction = checkNotNull(cryptFunction, \"cryptFunction\");\n      this.login = checkNotNull(login, \"login\");\n      this.password = checkNotNull(password, \"password\");\n   }\n\n   @Override\n   public Iterable<String> functionDependencies(OsFamily family) {\n      return ImmutableList.of();\n   }\n\n   @Override\n   public String render(OsFamily family) {\n      checkNotNull(family, \"family\");\n      if (family == OsFamily.WINDOWS)\n         throw new UnsupportedOperationException(\"windows not yet implemented\");\n      try {\n         String shadowPasswordEntry = cryptFunction.apply(password);\n         String shadowFile = \"/etc/shadow\";\n         // note we are using awk variables so that the user can be defined as a\n         // shell variable (ex. $USER) As the block is in single quotes,\n         // shell interpolation wouldn't work otherwise\n         Statement replaceEntryInTempFile = exec(format(\n               \"awk -v user=^%1$s: -v password='%2$s' 'BEGIN { FS=OFS=\\\":\\\" } $0 ~ user { $2 = password } 1' %3$s >%3$s.%1$s\",\n               login, shadowPasswordEntry, shadowFile));\n         // would have preferred to use exec <>3 && style, but for some reason\n         // the sha512 line breaks in both awk and sed during an inline\n         // expansion. unfortunately, we have to save a temp file. In this case,\n         // somewhat avoiding collisions by naming the file .user, conceding it\n         // isn't using any locks to prevent overlapping changes\n         Statement replaceShadowFile = exec(format(\"test -f %2$s.%1$s && mv %2$s.%1$s %2$s\", login, shadowFile));\n         return new StatementList(ImmutableList.of(replaceEntryInTempFile, replaceShadowFile)).render(family);\n      } catch (Exception e) {\n         propagate(e);\n         return null;\n      }\n   }\n\n   @Override\n   public int hashCode() {\n      final int prime = 31;\n      int result = 1;\n      result = prime * result + ((login == null) ? 0 : login.hashCode());\n      return result;\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (this == obj)\n         return true;\n      if (obj == null)\n         return false;\n      if (getClass() != obj.getClass())\n         return false;\n      ReplaceShadowPasswordEntry other = (ReplaceShadowPasswordEntry) obj;\n      if (login == null) {\n         if (other.login != null)\n            return false;\n      } else if (!login.equals(other.login))\n         return false;\n      return true;\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/statements/login/ReplaceShadowPasswordEntryOfLoginUser.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.statements.login;\n\nimport com.google.common.base.Function;\n\n\npublic class ReplaceShadowPasswordEntryOfLoginUser extends ReplaceShadowPasswordEntry {\n\n   public ReplaceShadowPasswordEntryOfLoginUser(Function<String, String> cryptFunction, String password) {\n      super(cryptFunction, \"${SUDO_USER:=${USER}}\", password);\n   }\n\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/statements/login/ShadowStatements.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.statements.login;\n\nimport com.google.common.base.Function;\n\n/**\n * Statements used to manipulate the shadow file\n */\npublic class ShadowStatements {\n\n   /**\n    * note must be run as root, and will either reset the root password, or whoever sudoed to root.\n    */\n   public static ReplaceShadowPasswordEntryOfLoginUser resetLoginUserPasswordTo(Function<String, String> cryptFunction,\n         String password) {\n      return new ReplaceShadowPasswordEntryOfLoginUser(cryptFunction, password);\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/statements/login/SudoStatements.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.statements.login;\n\nimport org.jclouds.scriptbuilder.domain.Statement;\n\n/**\n * Statements used in sudo control\n */\npublic class SudoStatements {\n\n   /**\n    * create new sudoers file with the wheel group authorized to all commands without a password\n    */\n   public static Statement createWheel() {\n      return new Sudoers();\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/statements/login/Sudoers.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.statements.login;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.scriptbuilder.domain.Statements.createOrOverwriteFile;\nimport static org.jclouds.scriptbuilder.domain.Statements.exec;\n\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.jclouds.scriptbuilder.domain.Statement;\nimport org.jclouds.scriptbuilder.domain.StatementList;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableList.Builder;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Control /etc/sudoers\n */\n@Beta\npublic class Sudoers implements Statement {\n   private static final String sudoers = \"/etc/sudoers\";\n\n   public String render(OsFamily family) {\n      checkNotNull(family, \"family\");\n      if (family == OsFamily.WINDOWS)\n         throw new UnsupportedOperationException(\"windows not yet implemented\");\n      Builder<Statement> statements = ImmutableList.builder();\n      statements.add(createOrOverwriteFile(sudoers, ImmutableSet.of(\n            \"Defaults    env_reset\",\n            \"Defaults    secure_path=\\\"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\\\"\",\n            \"root ALL = (ALL) ALL\", \n            \"%wheel ALL = (ALL) NOPASSWD:ALL\"))\n      );\n      statements.add(exec(\"chmod 0440 \" + sudoers));\n      return new StatementList(statements.build()).render(family);\n   }\n\n   @Override\n   public Iterable<String> functionDependencies(OsFamily family) {\n      return ImmutableList.of();\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/statements/login/UserAdd.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.statements.login;\n\nimport static com.google.common.base.Objects.equal;\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.jclouds.scriptbuilder.domain.Statement;\nimport org.jclouds.scriptbuilder.domain.StatementList;\nimport org.jclouds.scriptbuilder.domain.Statements;\nimport org.jclouds.scriptbuilder.statements.ssh.AuthorizeRSAPublicKeys;\nimport org.jclouds.scriptbuilder.statements.ssh.InstallRSAPrivateKey;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Joiner;\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\nimport com.google.common.base.Strings;\nimport com.google.common.base.Throwables;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Lists;\n\n/**\n * Creates a statement that will add a given user to a machine (\"login\"), with optional\n * password, groups, private key, and authorized keys.\n * <p>\n * This is supported on most *nix environments. Not currently supported on Windows.\n * <p>\n * Note that some places where this is used may have stricter requirements on the parameters\n * (for example {@link AdminAccess} requires password and keys).\n */\npublic class UserAdd implements Statement {\n   public static UserAdd.Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n      private Function<String, String> cryptFunction;\n      private String defaultHome = \"/home/users\";\n      private String home;\n      private String login;\n      private String password;\n      private String RSAPrivateKey;\n      private List<String> groups = Lists.newArrayList();\n      private List<String> authorizeRSAPublicKeys = Lists.newArrayList();\n      private String shell = \"/bin/bash\";\n      private String fullName;\n\n      /**\n       * @see  org.jclouds.compute.functions.Sha512Crypt\n       */\n      public Builder cryptFunction(Function<String, String> cryptFunction) {\n         this.cryptFunction = cryptFunction;\n         return this;\n      }\n\n      /**\n       * See --home in `man useradd`.\n       */\n      public UserAdd.Builder home(String home) {\n         this.home = home;\n         return this;\n      }\n\n      /**\n       * See --base-dir in `man useradd`.\n       */\n      public UserAdd.Builder defaultHome(String defaultHome) {\n         this.defaultHome = defaultHome;\n         return this;\n      }\n\n      /** the username of the user to add (not the login to use when performing the add) */\n      public UserAdd.Builder login(String login) {\n         this.login = login;\n         return this;\n      }\n\n      /** the password to add for the user (not the password to use when logging in to perform the add) */\n      public UserAdd.Builder password(String password) {\n         this.password = password;\n         return this;\n      }\n\n      public UserAdd.Builder group(String group) {\n         this.groups.add(checkNotNull(group, \"group\"));\n         return this;\n      }\n\n      public UserAdd.Builder groups(Iterable<String> groups) {\n         this.groups = ImmutableList.<String> copyOf(checkNotNull(groups, \"groups\"));\n         return this;\n      }\n\n      public UserAdd.Builder installRSAPrivateKey(String RSAPrivateKey) {\n         this.RSAPrivateKey = RSAPrivateKey;\n         return this;\n      }\n\n      public UserAdd.Builder authorizeRSAPublicKey(String RSAPublicKey) {\n         this.authorizeRSAPublicKeys.add(checkNotNull(RSAPublicKey, \"RSAPublicKey\"));\n         return this;\n      }\n\n      public UserAdd.Builder authorizeRSAPublicKeys(Iterable<String> RSAPublicKeys) {\n         this.authorizeRSAPublicKeys = ImmutableList.<String> copyOf(checkNotNull(RSAPublicKeys, \"RSAPublicKeys\"));\n         return this;\n      }\n\n      public UserAdd.Builder shell(String shell) {\n         this.shell = shell;\n         return this;\n      }\n\n      public UserAdd.Builder fullName(String fullName) {\n         this.fullName = fullName;\n         return this;\n      }\n\n      public UserAdd build() {\n         return new UserAdd(cryptFunction, login, groups, password, RSAPrivateKey, authorizeRSAPublicKeys, home,\n               defaultHome, shell, fullName);\n      }\n   }\n\n   public UserAdd(Function<String, String> cryptFunction, String login, List<String> groups, @Nullable String password,\n         @Nullable String installRSAPrivateKey, List<String> authorizeRSAPublicKeys, String defaultHome, String shell) {\n      this(cryptFunction, login, groups, password, installRSAPrivateKey, authorizeRSAPublicKeys, null, defaultHome,\n            shell, login);\n   }\n\n   public UserAdd(Function<String, String> cryptFunction, String login, List<String> groups, @Nullable String password,\n         @Nullable String installRSAPrivateKey, List<String> authorizeRSAPublicKeys, @Nullable String home,\n         String defaultHome, String shell, String fullName) {\n      this.login = checkNotNull(login, \"login\");\n      this.password = password;\n      this.cryptFunction = password == null ? null : checkNotNull(cryptFunction,\n            \"cryptFunction must be set! ex. org.jclouds.compute.functions.Sha512Crypt.INSTANCE\");\n      this.groups = ImmutableList.copyOf(checkNotNull(groups, \"groups\"));\n      this.installRSAPrivateKey = installRSAPrivateKey;\n      this.authorizeRSAPublicKeys = ImmutableList\n            .copyOf(checkNotNull(authorizeRSAPublicKeys, \"authorizeRSAPublicKeys\"));\n      this.home = home;\n      this.defaultHome = checkNotNull(defaultHome, \"defaultHome\");\n      this.shell = checkNotNull(shell, \"shell\");\n      this.fullName = fullName;\n   }\n\n   private final Function<String, String> cryptFunction;\n   private final String home;\n   private final String defaultHome;\n   private final String login;\n   private final List<String> groups;\n   private final String password;\n   private final String installRSAPrivateKey;\n   private final List<String> authorizeRSAPublicKeys;\n   private final String shell;\n   private final String fullName;\n\n   @Override\n   public Iterable<String> functionDependencies(OsFamily family) {\n      return ImmutableList.of();\n   }\n\n   @Override\n   public String render(OsFamily family) {\n      checkNotNull(family, \"family\");\n      if (family == OsFamily.WINDOWS)\n         throw new UnsupportedOperationException(\"windows not yet implemented\");\n      String homeDir = (home != null) ? home : (defaultHome + '/' + login);\n      String usersDir = homeDir.substring(0, homeDir.lastIndexOf('/'));\n      ImmutableList.Builder<Statement> statements = ImmutableList.builder();\n      // useradd cannot create the default homedir\n      statements.add(Statements.exec(\"{md} \" + usersDir));\n      // make sure the folder is globally accessible even with umask 0077\n      statements.add(Statements.exec(\"chmod 0755 \" + usersDir));\n\n      ImmutableMap.Builder<String, String> userAddOptions = ImmutableMap.builder();\n      // Include the username as the full name for now.\n\n      if (Strings.isNullOrEmpty(fullName)) {\n         userAddOptions.put(\"-c\", login);\n      } else {\n         userAddOptions.put(\"-c\", \"'\" + fullName + \"'\");\n      }\n\n      userAddOptions.put(\"-s\", shell);\n      if (!groups.isEmpty()) {\n         for (String group : groups)\n            statements.add(Statements.exec(\"getent group \" + group + \" || groupadd -f \" + group));\n\n         List<String> groups = Lists.newArrayList(this.groups);\n         String primaryGroup = groups.remove(0);\n         userAddOptions.put(\"-g\", primaryGroup);\n         if (!groups.isEmpty())\n            userAddOptions.put(\"-G\", Joiner.on(',').join(groups));\n\n      }\n      userAddOptions.put(\"-m\", \"\");\n      userAddOptions.put(\"-d\", homeDir);\n      if (password != null) {\n         try {\n            userAddOptions.put(\"-p\", \"'\" + cryptFunction.apply(password) + \"'\");\n         } catch (Exception e) {\n            Throwables.propagate(e);\n         }\n      }\n\n      String options = Joiner.on(' ').withKeyValueSeparator(\" \").join(userAddOptions.build());\n\n      statements.add(Statements.exec(String.format(\"useradd %s %s\", options, login)));\n\n      if (!authorizeRSAPublicKeys.isEmpty() || installRSAPrivateKey != null) {\n         String sshDir = homeDir + \"{fs}.ssh\";\n         if (!authorizeRSAPublicKeys.isEmpty())\n            statements.add(new AuthorizeRSAPublicKeys(sshDir, authorizeRSAPublicKeys, login));\n         if (installRSAPrivateKey != null)\n            statements.add(new InstallRSAPrivateKey(sshDir, installRSAPrivateKey));\n      }\n      statements.add(Statements.exec(String.format(\"chown -R %s %s\", login, homeDir)));\n      return new StatementList(statements.build()).render(family);\n   }\n\n   @Override\n   public boolean equals(Object o) {\n      if (this == o)\n         return true;\n      if (o == null || getClass() != o.getClass())\n         return false;\n      UserAdd that = UserAdd.class.cast(o);\n      return equal(this.login, that.login);\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(login);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(\"\").add(\"login\", login).toString();\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/statements/ruby/InstallRuby.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.statements.ruby;\n\nimport static org.jclouds.scriptbuilder.domain.Statements.call;\n\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.jclouds.scriptbuilder.domain.StatementList;\n\n/**\n * Installs Ruby onto a host.\n */\npublic class InstallRuby extends StatementList {\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n      public InstallRuby build() {\n         return new InstallRuby();\n      }\n   }\n\n   protected InstallRuby() {\n      super(call(\"setupPublicCurl\"), call(\"installRuby\"));\n   }\n\n   @Override\n   public String render(OsFamily family) {\n      if (family == OsFamily.WINDOWS) {\n         throw new UnsupportedOperationException(\"windows not yet implemented\");\n      }\n      return super.render(family);\n   }\n\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/statements/ruby/InstallRubyGems.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.statements.ruby;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.scriptbuilder.domain.Statements.exec;\nimport static org.jclouds.scriptbuilder.domain.Statements.extractTargzAndFlattenIntoDirectory;\n\nimport java.net.URI;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.jclouds.scriptbuilder.domain.Statement;\nimport org.jclouds.scriptbuilder.domain.StatementList;\n\nimport com.google.common.base.Optional;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Installs RubyGems onto a host.\n */\npublic class InstallRubyGems implements Statement {\n\n   public static final String DEFAULT_RUBYGEMS_VERSION = \"1.8.10\";\n   private static final String RUBYGEMS_URI_TEMPLATE = \"http://production.cf.rubygems.org/rubygems/rubygems-%s.tgz\";\n\n   public static Builder builder() {\n      return new Builder();\n   }\n\n   public static class Builder {\n      private Optional<String> version = Optional.absent();\n      private boolean updateSystem = false;\n      private Optional<String> updateSystemVersion = Optional.absent();\n      private boolean updateExistingGems = false;\n\n      /**\n       * The version of RubyGems to install.\n       */\n      public Builder version(@Nullable String version) {\n         this.version = Optional.fromNullable(version);\n         return this;\n      }\n\n      /**\n       * Update the gem system after installing RubyGems.\n       */\n      public Builder updateSystem(boolean updateSystem) {\n         this.updateSystem = updateSystem;\n         this.updateSystemVersion = Optional.absent();\n         return this;\n      }\n\n      /**\n       * Update the gem system after installing RubyGems, forcing the update to\n       * a concrete version.\n       */\n      public Builder updateSystem(boolean updateSystem, @Nullable String updateSystemVersion) {\n         this.updateSystem = updateSystem;\n         this.updateSystemVersion = Optional.fromNullable(updateSystemVersion);\n         return this;\n      }\n\n      /**\n       * Update the existing gems after installing RubyGems.\n       */\n      public Builder updateExistingGems(boolean updateExistingGems) {\n         this.updateExistingGems = updateExistingGems;\n         return this;\n      }\n\n      public InstallRubyGems build() {\n         return new InstallRubyGems(version, updateSystem, updateSystemVersion, updateExistingGems);\n      }\n\n   }\n\n   private Optional<String> version;\n   private boolean updateSystem;\n   private Optional<String> updateSystemVersion;\n   private boolean updateExistingGems;\n\n   protected InstallRubyGems(Optional<String> version, boolean updateSystem, Optional<String> updateSystemVersion,\n         boolean updateExistingGems) {\n      this.version = checkNotNull(version, \"version must be set\");\n      this.updateSystem = updateSystem;\n      this.updateSystemVersion = checkNotNull(updateSystemVersion, \"updateSystemVersion must be set\");\n      this.updateExistingGems = updateExistingGems;\n   }\n\n   @Override\n   public String render(OsFamily family) {\n      if (family == OsFamily.WINDOWS) {\n         throw new UnsupportedOperationException(\"windows not yet implemented\");\n      }\n\n      URI rubygemsUri = URI.create(String.format(RUBYGEMS_URI_TEMPLATE, version.or(DEFAULT_RUBYGEMS_VERSION)));\n\n      ImmutableList.Builder<Statement> statements = ImmutableList.builder();\n      statements.add(exec(\"if ! hash gem 2>/dev/null; then\"));\n      statements.add(exec(\"(\"));\n      statements.add(extractTargzAndFlattenIntoDirectory(rubygemsUri, \"/tmp/rubygems\"));\n      statements.add(exec(\"{cd} /tmp/rubygems\"));\n      statements.add(exec(\"ruby setup.rb --no-format-executable\"));\n      statements.add(exec(\"{rm} -fr /tmp/rubygems\"));\n      statements.add(exec(\")\"));\n      statements.add(exec(\"fi\"));\n\n      if (updateSystem) {\n         statements.add(updateSystemVersion.isPresent() ? exec(\"gem update --system \" + updateSystemVersion.get())\n               : exec(\"gem update --system\"));\n      }\n      if (updateExistingGems) {\n         statements.add(exec(\"gem update --no-rdoc --no-ri\"));\n      }\n\n      return new StatementList(statements.build()).render(family);\n   }\n\n   @Override\n   public Iterable<String> functionDependencies(OsFamily family) {\n      return ImmutableSet.<String> of();\n   }\n\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/statements/ssh/AuthorizeRSAPublicKeys.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.statements.ssh;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.scriptbuilder.domain.Statements.appendFile;\nimport static org.jclouds.scriptbuilder.domain.Statements.exec;\n\nimport java.util.List;\n\nimport org.jclouds.javax.annotation.Nullable;\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.jclouds.scriptbuilder.domain.Statement;\nimport org.jclouds.scriptbuilder.domain.StatementList;\n\nimport com.google.common.base.Joiner;\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableList.Builder;\n\npublic class AuthorizeRSAPublicKeys implements Statement {\n   private final String sshDir;\n   private final List<String> publicKeys;\n   private final String owner;\n   \n   public AuthorizeRSAPublicKeys(Iterable<String> publicKeys) {\n      this(\"~/.ssh\", publicKeys, null);\n   }\n   \n   public AuthorizeRSAPublicKeys(Iterable<String> publicKeys, @Nullable String owner) {\n      this(\"~/.ssh\", publicKeys, owner);\n   }\n\n   public AuthorizeRSAPublicKeys(String sshDir, Iterable<String> publicKeys, @Nullable String owner) {\n      this.sshDir = checkNotNull(sshDir, \"sshDir\");\n      this.publicKeys = ImmutableList.copyOf(checkNotNull(publicKeys, \"publicKeys\"));\n      this.owner = owner;\n   }\n\n   @Override\n   public Iterable<String> functionDependencies(OsFamily family) {\n      return ImmutableList.of();\n   }\n\n   @Override\n   public String render(OsFamily family) {\n      checkNotNull(family, \"family\");\n      if (family == OsFamily.WINDOWS)\n         throw new UnsupportedOperationException(\"windows not yet implemented\");\n      Builder<Statement> statements = ImmutableList.builder();\n      statements.add(exec(\"mkdir -p \" + sshDir));\n      String authorizedKeys = sshDir + \"{fs}authorized_keys\";\n      statements.add(appendFile(authorizedKeys, Splitter.on('\\n').split(Joiner.on(\"\\n\\n\").join(publicKeys))));\n      statements.add(exec(\"chmod 600 \" + authorizedKeys));\n      if (owner != null) {\n         statements.add(exec(String.format(\"chown -R %s %s\", owner, sshDir)));\n      }\n      return new StatementList(statements.build()).render(family);\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/statements/ssh/InstallRSAPrivateKey.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.statements.ssh;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.scriptbuilder.domain.Statements.appendFile;\nimport static org.jclouds.scriptbuilder.domain.Statements.exec;\n\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.jclouds.scriptbuilder.domain.Statement;\nimport org.jclouds.scriptbuilder.domain.StatementList;\n\nimport com.google.common.base.Splitter;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableList.Builder;\n\npublic class InstallRSAPrivateKey implements Statement {\n   private final String sshDir;\n   private final String privateKey;\n\n   public InstallRSAPrivateKey(String privateKey) {\n      this(\"~/.ssh\", privateKey);\n   }\n\n   public InstallRSAPrivateKey(String sshDir, String privateKey) {\n      this.sshDir = checkNotNull(sshDir, \"sshDir\");\n      this.privateKey = checkNotNull(privateKey, \"privateKey\");\n   }\n\n   @Override\n   public Iterable<String> functionDependencies(OsFamily family) {\n      return ImmutableList.of();\n   }\n\n   @Override\n   public String render(OsFamily family) {\n      checkNotNull(family, \"family\");\n      if (family == OsFamily.WINDOWS)\n         throw new UnsupportedOperationException(\"windows not yet implemented\");\n      Builder<Statement> statements = ImmutableList.builder();\n      statements.add(exec(\"{md} \" + sshDir));\n      String idRsa = sshDir + \"{fs}id_rsa\";\n      statements.add(exec(\"{rm} \" + idRsa));\n      statements.add(appendFile(idRsa, Splitter.on('\\n').split(privateKey)));\n      statements.add(exec(\"chmod 600 \" + idRsa));\n      return new StatementList(statements.build()).render(family);\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/statements/ssh/SshStatements.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.statements.ssh;\n\nimport java.util.Map;\n\nimport org.jclouds.scriptbuilder.domain.Statement;\n\nimport com.google.common.collect.ImmutableMap;\n\n/**\n * Statements used in ssh control\n */\npublic class SshStatements {\n\n   /**\n    * lock sshd down so root cannot login, and password auth is disabled,\n    */\n   public static Statement lockSshd() {\n      return sshdConfig(ImmutableMap.of(\"PasswordAuthentication\", \"no\", \"PermitRootLogin\", \"no\"));\n   }\n\n   public static Statement sshdConfig(Map<String, String> params) {\n      return new SshdConfig(params);\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/statements/ssh/SshdConfig.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.statements.ssh;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static org.jclouds.scriptbuilder.domain.Statements.exec;\nimport static org.jclouds.scriptbuilder.domain.Statements.newStatementList;\n\nimport java.util.Map;\n\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.jclouds.scriptbuilder.domain.Statement;\n\nimport com.google.common.base.Joiner;\nimport com.google.common.collect.ImmutableList;\n\n/**\n * Control sshd_config\n */\npublic class SshdConfig implements Statement {\n   private static final String sshdConfig = \"/etc/ssh/sshd_config\";\n\n   private final Map<String, String> params;\n\n   public SshdConfig(Map<String, String> params) {\n      this.params = checkNotNull(params, \"params\");\n   }\n\n   public String render(OsFamily family) {\n      String linesToPrepend = Joiner.on('\\n').withKeyValueSeparator(\" \").join(params);\n      Statement prependSshdConfig = exec(String.format(\n               \"exec 3<> %1$s && awk -v TEXT=\\\"%2$s\\n\\\" 'BEGIN {print TEXT}{print}' %1$s >&3\", sshdConfig,\n               linesToPrepend));\n      Statement reloadSshdConfig = exec(\"hash service 2>&- && service ssh reload 2>&- || service sshd reload 2>&- || /etc/init.d/ssh* reload\");\n      return newStatementList(prependSshdConfig, reloadSshdConfig).render(family);\n   }\n\n   @Override\n   public Iterable<String> functionDependencies(OsFamily family) {\n      return ImmutableList.of();\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/java/org/jclouds/scriptbuilder/util/Utils.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.util;\n\nimport java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.jclouds.scriptbuilder.domain.ShellToken;\nimport org.jclouds.scriptbuilder.functionloader.CurrentFunctionLoader;\n\nimport com.google.common.base.CaseFormat;\nimport com.google.common.base.Function;\nimport com.google.common.base.Joiner;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Iterables;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\n/**\n * Utilities used to build init scripts.\n */\npublic class Utils {\n\n   /**\n    * \n    * In {@link ShellToken}, the values whose names end in {@code _VARIABLE} designate variable\n    * names we know how to translate from one platform to another. For example\n    * {@link ShellToken#LIBRARY_PATH_VARIABLE} means that we can translate the variable named\n    * {@code LIBRARY_PATH} to the proper platform-specific name.\n    */\n   public static final class VariableNameForOsFamily implements Function<String, String> {\n      private final OsFamily family;\n\n      public VariableNameForOsFamily(OsFamily family) {\n         this.family = family;\n      }\n\n      @Override\n      public String apply(String input) {\n         String variableNameKey = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, input) + \"Variable\";\n         if (ShellToken.tokenValueMap(family).containsKey(variableNameKey))\n            return ShellToken.tokenValueMap(family).get(variableNameKey);\n         return input;\n      }\n   }\n\n   /**\n    * matches any expression inside curly braces (where the expression does not including an open\n    * curly brace)\n    */\n   private static final Pattern pattern = Pattern.compile(\"\\\\{([^\\\\{]+?)\\\\}\");\n\n   /**\n    * replaces tokens that are expressed as <code>{token}</code>\n    * \n    * <p/>\n    * ex. if input is \"hello {where}\"<br/>\n    * and replacements is \"where\" -> \"world\" <br/>\n    * then replaceTokens returns \"hello world\"\n    * \n    * @param input\n    *           source to replace\n    * @param replacements\n    *           token/value pairs\n    */\n   public static String replaceTokens(String input, Map<String, String> replacements) {\n      Matcher matcher = pattern.matcher(input);\n      StringBuilder builder = new StringBuilder();\n      int i = 0;\n      while (matcher.find()) {\n         String replacement = replacements.get(matcher.group(1));\n         builder.append(input, i, matcher.start());\n         if (replacement == null)\n            builder.append(matcher.group(0));\n         else\n            builder.append(replacement);\n         i = matcher.end();\n      }\n      builder.append(input, i, input.length());\n      return builder.toString();\n   }\n\n   /**\n    * converts a map into variable exports relevant to the specified platform.\n    * <p/>\n    * ex. if {@code keys} is the map: \"MAVEN_OPTS\" -> \"-Xms64m -Xmx256m\" <br/>\n    * and family is UNIX<br/>\n    * then writeVariableExporters returns literally {@code export MAVEN_OPTS=\"-Xms64m -Xmx256m\"\\n}\n    * \n    * @param exports\n    *           keys are the variables to export in UPPER_UNDERSCORE case format\n    * @param family\n    *           operating system for formatting\n    * @see VariableNameForOsFamily\n    */\n   public static String writeVariableExporters(Map<String, String> exports, final OsFamily family) {\n      exports = transformKeys(exports, new VariableNameForOsFamily(family));\n      return replaceTokens(writeVariableExporters(exports), ShellToken.tokenValueMap(family));\n   }\n\n   /**\n    * converts a map into variable exporters in shell intermediate language.\n    * \n    * @param exports\n    *           keys are the variables to export in UPPER_UNDERSCORE case format\n    */\n   public static String writeVariableExporters(Map<String, String> exports) {\n      StringBuilder initializers = new StringBuilder();\n      for (Entry<String, String> entry : exports.entrySet()) {\n         initializers.append(String.format(\"{export} %s={vq}%s{vq}{lf}\", entry.getKey(), entry.getValue()));\n      }\n      return initializers.toString();\n   }\n\n   public static String writeFunction(String function, String source, OsFamily family) {\n      return replaceTokens(writeFunction(function, source), ShellToken.tokenValueMap(family));\n   }\n\n   public static String writeFunctionFromResource(String function, OsFamily family) {\n      String toReturn = CurrentFunctionLoader.get().loadFunction(function, family);\n      String lf = ShellToken.LF.to(family);\n      return toReturn.endsWith(lf) ? toReturn : new StringBuilder(toReturn).append(lf).toString();\n   }\n\n   public static String writeFunction(String function, String source) {\n      return String.format(\"{fncl}%s{fncr}%s{fnce}\", function, source.replaceAll(\"^\", \"   \"));\n   }\n\n   public static final Map<OsFamily, String> OS_TO_POSITIONAL_VAR_PATTERN = ImmutableMap.of(OsFamily.UNIX,\n            \"set {key}=$1\\nshift\\n\", OsFamily.WINDOWS, \"set {key}=%1\\r\\nshift\\r\\n\");\n\n   public static final Map<OsFamily, String> OS_TO_LOCAL_VAR_PATTERN = ImmutableMap.of(OsFamily.UNIX,\n            \"set {key}=\\\"{value}\\\"\\n\", OsFamily.WINDOWS, \"set {key}={value}\\r\\n\");\n\n   /**\n    * Writes an initialization statement for use inside a script or a function.\n    * \n    * @param positionalVariables\n    *           - transfer the value of args into these statements. Note that there is no check to\n    *           ensure that all source args are indeed present.\n    * \n    */\n   public static String writePositionalVars(Iterable<String> positionalVariables, OsFamily family) {\n      StringBuilder initializers = new StringBuilder();\n      for (String positionalVariable : positionalVariables) {\n         initializers.append(replaceTokens(OS_TO_POSITIONAL_VAR_PATTERN.get(family), ImmutableMap.of(\"key\",\n                  positionalVariable)));\n      }\n      return initializers.toString();\n   }\n\n   /**\n    * Ensures that variables come from a known source instead of bleeding in from a profile\n    * \n    * @param variablesToUnset\n    *           - System variables to unset\n    * @see VariableNameForOsFamily\n    */\n   public static String writeUnsetVariables(Iterable<String> variablesToUnset, OsFamily family) {\n      variablesToUnset = Iterables.transform(variablesToUnset, new VariableNameForOsFamily(family));\n      switch (family) {\n         case UNIX:\n            return String.format(\"unset %s\\n\", Joiner.on(' ').join(variablesToUnset));\n         case WINDOWS:\n            StringBuilder initializers = new StringBuilder();\n            for (String variableToUnset : variablesToUnset) {\n               initializers.append(replaceTokens(OS_TO_LOCAL_VAR_PATTERN.get(family), ImmutableMap.of(\"key\",\n                        variableToUnset, \"value\", \"\")));\n            }\n            return initializers.toString();\n         default:\n            throw new UnsupportedOperationException(\"unsupported os: \" + family);\n      }\n\n   }\n\n   public static final Map<OsFamily, String> OS_TO_ZERO_PATH = ImmutableMap.of(OsFamily.WINDOWS,\n            \"set PATH=c:\\\\windows\\\\;C:\\\\windows\\\\system32;c:\\\\windows\\\\system32\\\\wbem\\r\\n\", OsFamily.UNIX,\n            \"export PATH=/usr/ucb/bin:/bin:/sbin:/usr/bin:/usr/sbin\\n\");\n\n   /**\n    * @return line used to zero out the path of the script such that basic commands such as unix ps\n    *         will work.\n    */\n   public static String writeZeroPath(OsFamily family) {\n      return OS_TO_ZERO_PATH.get(family);\n   }\n\n   public static String writeComment(String comment, OsFamily family) {\n      return String.format(\"%s%s%s\", ShellToken.REM.to(family), comment, ShellToken.LF.to(family));\n   }\n\n    /**\n     * change the keys but keep the values in-tact.\n     *\n     * @param <K1> input key type\n     * @param <K2> output key type\n     * @param <V>  value type\n     * @param in   input map to transform\n     * @param fn   how to transform the values\n     * @return immutableMap with the new keys.\n     */\n    public static <K1, K2, V> Map<K2, V> transformKeys(Map<K1, V> in, Function<K1, K2> fn) {\n        checkNotNull(in, \"input map\");\n        checkNotNull(fn, \"function\");\n        ImmutableMap.Builder<K2, V> returnVal = ImmutableMap.builder();\n        for (Entry<K1, V> entry : in.entrySet())\n            returnVal.put(fn.apply(entry.getKey()), entry.getValue());\n        return returnVal.build();\n    }\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/resources/functions/.gitattributes",
    "content": "*.sh -crlf\n"
  },
  {
    "path": "scriptbuilder/src/main/resources/functions/abort.cmd",
    "content": "REM\r\nREM Licensed to the Apache Software Foundation (ASF) under one or more\r\nREM contributor license agreements.  See the NOTICE file distributed with\r\nREM this work for additional information regarding copyright ownership.\r\nREM The ASF licenses this file to You under the Apache License, Version 2.0\r\nREM (the \"License\"); you may not use this file except in compliance with\r\nREM the License.  You may obtain a copy of the License at\r\nREM\r\nREM     http://www.apache.org/licenses/LICENSE-2.0\r\nREM\r\nREM Unless required by applicable law or agreed to in writing, software\r\nREM distributed under the License is distributed on an \"AS IS\" BASIS,\r\nREM WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\nREM See the License for the specific language governing permissions and\r\nREM limitations under the License.\r\nREM\r\n:abort\r\n   echo aborting: %EXCEPTION%\r\n   exit /b 1\r\n"
  },
  {
    "path": "scriptbuilder/src/main/resources/functions/abort.sh",
    "content": "#\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements.  See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License.  You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nfunction abort {\n   echo \"aborting: $@\" 1>&2\n   exit 1\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/resources/functions/findPid.cmd",
    "content": "REM\r\nREM Licensed to the Apache Software Foundation (ASF) under one or more\r\nREM contributor license agreements.  See the NOTICE file distributed with\r\nREM this work for additional information regarding copyright ownership.\r\nREM The ASF licenses this file to You under the Apache License, Version 2.0\r\nREM (the \"License\"); you may not use this file except in compliance with\r\nREM the License.  You may obtain a copy of the License at\r\nREM\r\nREM     http://www.apache.org/licenses/LICENSE-2.0\r\nREM\r\nREM Unless required by applicable law or agreed to in writing, software\r\nREM distributed under the License is distributed on an \"AS IS\" BASIS,\r\nREM WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\nREM See the License for the specific language governing permissions and\r\nREM limitations under the License.\r\nREM\r\n:findPid\r\n   set FOUND_PID=\r\n   set _expression=%1\r\n   shift\r\n   set FIND_PROCESS=TASKLIST /FI \"WINDOWTITLE eq %_expression%\" /NH\r\n   FOR /F \"usebackq tokens=2 delims= \" %%A IN (`cmd /c \"%FIND_PROCESS% 2>NUL\"`) DO (\r\n      SET FOUND_PID=%%A\r\n   )\r\n   if defined FOUND_PID (\r\n      exit /b 0\r\n   ) else (\r\n      set EXCEPTION=%_expression% not found\r\n      exit /b 1\r\n   )\r\n"
  },
  {
    "path": "scriptbuilder/src/main/resources/functions/findPid.sh",
    "content": "#\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements.  See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License.  You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nfunction findPid {\n   unset FOUND_PID;\n   [ $# -eq 1 ] || {\n      abort \"findPid requires a parameter of pattern to match\"\n      return 1\n   }\n   local PATTERN=\"$1\"; shift\n   local _FOUND=`ps auxwww|grep \"$PATTERN\"|grep -v \" $0\"|grep -v grep|grep -v $$|awk '{print $2}'`\n   [ -n \"$_FOUND\" ] && {\n      export FOUND_PID=$_FOUND\n      return 0\n   } || {\n      return 1\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/resources/functions/forget.cmd",
    "content": "REM\nREM Licensed to the Apache Software Foundation (ASF) under one or more\nREM contributor license agreements.  See the NOTICE file distributed with\nREM this work for additional information regarding copyright ownership.\nREM The ASF licenses this file to You under the Apache License, Version 2.0\nREM (the \"License\"); you may not use this file except in compliance with\nREM the License.  You may obtain a copy of the License at\nREM\nREM     http://www.apache.org/licenses/LICENSE-2.0\nREM\nREM Unless required by applicable law or agreed to in writing, software\nREM distributed under the License is distributed on an \"AS IS\" BASIS,\nREM WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nREM See the License for the specific language governing permissions and\nREM limitations under the License.\nREM\n:forget\r\n   SETLOCAL\r\n   set FOUND_PID=\r\n   set NEXT_MINUTE=\r\n   set INSTANCE_NAME=%1\r\n   shift\r\n   set SCRIPT=%1\r\n   shift\r\n   set LOG_DIR=%1\r\n   shift\r\n   CALL :findProcess %INSTANCE_NAME%\r\n   if defined FOUND_PID (\r\n      echo %INSTANCE_NAME% already running pid [%FOUND_PID%]\r\n   ) else (\r\n      CALL :nextMinute\r\n      set _DATE=%DATE:~4%\r\n      set CMD=schtasks /create /sd %_DATE% /tn %INSTANCE_NAME% /ru System /tr \"cmd /c title %INSTANCE_NAME%&%SCRIPT% >%LOG_DIR%\\stdout.log 2>%LOG_DIR%\\stderr.log\" /sc:once /st %NEXT_MINUTE%\r\n      echo %INSTANCE_NAME% will start at %NEXT_MINUTE%\r\n      set SECONDS=%TIME:~6,2%\r\n      set /a SECOND=60-SECONDS\r\n      %CMD% >NUL\r\n      ping -n %SECONDS% 127.0.0.1 > NUL 2>&1\r\n      CALL :findProcess %INSTANCE_NAME%\r\n      if not defined FOUND_PID (\r\n         set EXCEPTION=%INSTANCE_NAME% did not start\r\n         abort\r\n      )\r\n   ) \r\n   exit /b 0\r\n"
  },
  {
    "path": "scriptbuilder/src/main/resources/functions/forget.sh",
    "content": "#\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements.  See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License.  You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nfunction forget {\n   unset FOUND_PID;\n   [ $# -eq 3 ] || {\n      abort \"forget requires parameters INSTANCE_NAME SCRIPT LOG_DIR\"\n      return 1\n   }\n   local INSTANCE_NAME=\"$1\"; shift\n   local SCRIPT=\"$1\"; shift\n   local LOG_DIR=\"$1\"; shift\n   mkdir -p $LOG_DIR\n   findPid $INSTANCE_NAME\n   [ -n \"$FOUND_PID\" -a -f $LOG_DIR/stdout.log ] && {\n      echo $INSTANCE_NAME already running pid $FOUND_PID\n      return 1;\n   } || {\n      nohup $SCRIPT >$LOG_DIR/stdout.log 2>$LOG_DIR/stderr.log &\n      RETURN=$?\n      # this is generally followed by findPid, so we shouldn't exit \n      # immediately as the proc may not have registered in ps, yet\n      test $RETURN && sleep 1\n      return $RETURN;\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/resources/functions/installGit.sh",
    "content": "#\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements.  See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License.  You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nfunction installGit() {\n  if which dpkg &> /dev/null; then\n    ensure_cmd_or_install_package_apt git git-core\n  elif which rpm &> /dev/null; then\n    case $(uname -r) in\n      *el5)\n        wget http://download.fedoraproject.org/pub/epel/5/$(uname -i)/epel-release-5-4.noarch.rpm &&\n        rpm -Uvh epel-release-5-4.noarch.rpm\n        rm -f epel-release-5-4.noarch.rpm;;\n      *el6)\n        wget http://download.fedoraproject.org/pub/epel/6/$(uname -i)/epel-release-6-7.noarch.rpm &&\n        rpm -Uvh epel-release-6-7.noarch.rpm \n        rm -f epel-release-6-7.noarch.rpm;; \n    esac\n    ensure_cmd_or_install_package_yum git git-core\n  else\n    abort \"we only support apt-get and yum right now... please contribute!\"\n    return 1\n  fi\n  return 0  \n}\n"
  },
  {
    "path": "scriptbuilder/src/main/resources/functions/installJDKFromURL.sh",
    "content": "#\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements.  See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License.  You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# note this does not work until someone addresses user auth\n# https://issues.jenkins-ci.org/browse/JENKINS-10556\n# https://forums.oracle.com/forums/thread.jspa?messageID=10236239&tstart=0\nfunction installJDKFromURL() {\n  if hash curl 2>/dev/null; then\n    if [ `uname -m` == 'x86_64' ]; then\n      local url=${1:-http://download.oracle.com/otn-pub/java/jdk/7/jdk-7-linux-x64.tar.gz}\n    else\n      local url=${1:-http://download.oracle.com/otn-pub/java/jdk/7/jdk-7-linux-i586.tar.gz}\n    fi\n    curl -q -s -S -L --connect-timeout 10 --max-time 600 --retry 20 -X GET $url |(mkdir -p /usr/local &&cd /usr/local &&tar -xpzf -)\n    mv /usr/local/jdk* /usr/local/jdk/\n    test -n \\\"$SUDO_USER\\\" && cat >> /home/$SUDO_USER/.bashrc <<-'END_OF_JCLOUDS_FILE'\n\texport JAVA_HOME=/usr/local/jdk\n\texport PATH=$JAVA_HOME/bin:$PATH\nEND_OF_JCLOUDS_FILE\n    cat >> /etc/bashrc <<-'END_OF_JCLOUDS_FILE'\n\texport JAVA_HOME=/usr/local/jdk\n\texport PATH=$JAVA_HOME/bin:$PATH\nEND_OF_JCLOUDS_FILE\n    cat >> $HOME/.bashrc <<-'END_OF_JCLOUDS_FILE'\n\texport JAVA_HOME=/usr/local/jdk\n\texport PATH=$JAVA_HOME/bin:$PATH\nEND_OF_JCLOUDS_FILE\n    cat >> /etc/skel/.bashrc <<-'END_OF_JCLOUDS_FILE'\n\texport JAVA_HOME=/usr/local/jdk\n\texport PATH=$JAVA_HOME/bin:$PATH\nEND_OF_JCLOUDS_FILE\n    # TODO: eventhough we are setting the above, sometimes images (ex.\n    # cloudservers ubuntu) kick out of .bashrc (ex. [ -z \"$PS1\" ] &&\n    # return), for this reason, we should also explicitly link.\n    # A better way would be to update using alternatives or the like\n    ln -fs /usr/local/jdk/bin/java /usr/bin/java\n    /usr/bin/java -version || abort \"cannot run /usr/bin/java\"\n  else\n    abort \"curl not available.. cannot install openjdk\"\n  fi\n  return 0\n}"
  },
  {
    "path": "scriptbuilder/src/main/resources/functions/installOpenJDK.sh",
    "content": "#\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements.  See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License.  You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# adds JAVA_HOME and into PATH in global and user-specific profiles\nfunction setupJavaHomeInProfile() {\n  PROFILES=(/etc/bashrc $HOME/.bashrc /etc/skel/.bashrc)\n  test -n \"$SUDO_USER\" &&\n    PROFILES=(${PROFILES[*]} `getent passwd $SUDO_USER| cut -f6 -d:`/.bashrc)\n  for PROFILE in ${PROFILES[*]}; do\n    cat >> $PROFILE <<-'END_OF_JCLOUDS_FILE'\n\texport JAVA_HOME=/usr/local/jdk\n\texport PATH=$JAVA_HOME/bin:$PATH\nEND_OF_JCLOUDS_FILE\n  done\n}\n\n# resets JAVA_HOME to what an openjdk installer created\nfunction findOpenJDK() {\n  local oldJavaHome=$JAVA_HOME\n  unset JAVA_HOME\n  for CANDIDATE in $oldJavaHome `ls -d /usr/lib/jvm/java-*-openjdk* 2>&-`; do\n    if [ -n \"$CANDIDATE\" -a -x \"$CANDIDATE/bin/java\" ]; then\n      export JAVA_HOME=$CANDIDATE\n      break\n    fi\n  done\n}\n\n# assures JDK installed and JAVA_HOME to a link at /usr/local/jdk\nfunction installOpenJDK() {\n  if [ \"$JAVA_HOME\" == \"/usr/local/jdk\" ]; then\n    echo skipping as JAVA_HOME is already set to /usr/local/jdk\n    return 0\n  fi\n  if [ -n \"$JAVA_HOME\" -a -x \"$JAVA_HOME/bin/java\" ]; then\n    echo reusing JAVA_HOME $JAVA_HOME\n  else\n    if which dpkg &> /dev/null; then\n      apt-get-update && \\\n          PACKAGE=$(apt-cache search --names-only '^openjdk-.-jdk$' | sort -r | cut -d' ' -f1 | head -1) && \\\n          [ ! -z \"$PACKAGE\" ] && \\\n          {  apt-get-install $PACKAGE-headless || apt-get-install $PACKAGE; }\n    elif which rpm &> /dev/null; then\n      PACKAGE=$(repoquery --qf='%{name}' --pkgnarrow=available 'java-*-openjdk-devel' | sort -r | head -1) && \\\n        [ ! -z \"$PACKAGE\" ] && \\\n        yum-install $PACKAGE\n    else\n      abort \"we only support apt-get and yum right now... please contribute\"\n    fi\n    findOpenJDK\n    if [ -n \"$JAVA_HOME\" ]; then\n      echo installed JAVA_HOME $JAVA_HOME\n    else\n      abort \"JDK installation failed\"\n    fi\n  fi\n  rm -rf /usr/local/jdk\n  ln -Fs $JAVA_HOME /usr/local/jdk\n  /usr/local/jdk/bin/java -version || abort \"cannot run java\"\n  setupJavaHomeInProfile\n}"
  },
  {
    "path": "scriptbuilder/src/main/resources/functions/installRuby.sh",
    "content": "#\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements.  See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License.  You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nfunction installRuby() {\n  if ! hash ruby 2>/dev/null; then\n    if which dpkg &> /dev/null; then\n      apt-get-update\n      apt-get install -y ruby ruby-dev build-essential\n    elif which rpm &> /dev/null; then\n      # Disable chef from the base repo (http://tickets.opscode.com/browse/CHEF-2906)\n      sed -i \"s/\\[base\\]/\\0\\n\\exclude=ruby*/g\" /etc/yum.repos.d/CentOS-Base.repo\n      # Make sure to install an appropriate ruby version\n      yum erase -y ruby ruby-libs\n      rpm -Uvh http://rbel.co/rbel5\n      yum install -y ruby ruby-devel make gcc gcc-c++ automake autoconf\n    else\n      abort \"we only support apt-get and yum right now... please contribute\"\n    fi\n  fi\n}\n"
  },
  {
    "path": "scriptbuilder/src/main/resources/functions/nextMinute.cmd",
    "content": "REM\nREM Licensed to the Apache Software Foundation (ASF) under one or more\nREM contributor license agreements.  See the NOTICE file distributed with\nREM this work for additional information regarding copyright ownership.\nREM The ASF licenses this file to You under the Apache License, Version 2.0\nREM (the \"License\"); you may not use this file except in compliance with\nREM the License.  You may obtain a copy of the License at\nREM\nREM     http://www.apache.org/licenses/LICENSE-2.0\nREM\nREM Unless required by applicable law or agreed to in writing, software\nREM distributed under the License is distributed on an \"AS IS\" BASIS,\nREM WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nREM See the License for the specific language governing permissions and\nREM limitations under the License.\nREM\n:nextMinute\r\n   SETLOCAL\r\n   set HOURS=%TIME:~0,2%\r\n   set MINUTES=%TIME:~3,2%\r\n\r\n   set /a HOURS=%HOURS%\r\n   set /a MINUTES+=1\r\n\r\n   if %MINUTES% EQU 60 (set MINUTES=0&set /a HOURS+=1)\r\n   if %HOURS% EQU 24 (set HOURS=0)\r\n\r\n   if %HOURS% LSS 10 set HOURS=0%HOURS%\r\n   if %MINUTES% LSS 10 set MINUTES=0%MINUTES%\r\n\r\n   ENDLOCAL&SET NEXT_MINUTE=%HOURS%:%MINUTES%:00\r\n   exit /b 0\r\n"
  },
  {
    "path": "scriptbuilder/src/main/resources/functions/setupPublicCurl.sh",
    "content": "#\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements.  See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License.  You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nalias apt-get-update=\"apt-get update -qq\"\nalias apt-get-install=\"apt-get install -f -y -qq --force-yes\"\nalias yum-install=\"yum --quiet --nogpgcheck -y install\"\n\nfunction ensure_cmd_or_install_package_apt(){\n  local cmd=$1\n  shift\n  local pkg=$*\n  \n  hash $cmd 2>/dev/null || ( apt-get-update && apt-get-install $pkg )\n}\n\nfunction ensure_cmd_or_install_package_yum(){\n  local cmd=$1\n  shift\n  local pkg=$*\n  hash $cmd 2>/dev/null || yum-install $pkg\n}\n\nfunction ensure_netutils_apt() {\n  ensure_cmd_or_install_package_apt nslookup dnsutils\n  ensure_cmd_or_install_package_apt curl curl\n}\n\nfunction ensure_netutils_yum() {\n  ensure_cmd_or_install_package_yum nslookup bind-utils\n  ensure_cmd_or_install_package_yum curl curl\n}\n\n# most network services require that the hostname is in\n# the /etc/hosts file, or they won't operate\nfunction ensure_hostname_in_hosts() {\n  [ -n \"$SSH_CONNECTION\" ] && {\n    local ipaddr=`echo $SSH_CONNECTION | awk '{print $3}'`\n  } || {\n    local ipaddr=`hostname -i`\n  }\n  # NOTE: we blindly trust existing hostname settings in /etc/hosts\n  egrep -q `hostname -s` /etc/hosts || echo \"$ipaddr `hostname -f` `hostname -s`\" >> /etc/hosts\n}\n\n# download locations for many services are at public dns\nfunction ensure_can_resolve_public_dns() {\n  nslookup yahoo.com | grep yahoo.com > /dev/null || echo nameserver 208.67.222.222 >> /etc/resolv.conf\n}\n\nfunction setupPublicCurl() {\n  ensure_hostname_in_hosts\n  if which dpkg &> /dev/null; then\n    ensure_netutils_apt\n  elif which rpm &> /dev/null; then\n    ensure_netutils_yum\n  else\n    abort \"we only support apt-get and yum right now... please contribute!\"\n    return 1\n  fi\n  ensure_can_resolve_public_dns\n  return 0  \n}\n"
  },
  {
    "path": "scriptbuilder/src/main/resources/functions/sourceEnvFile.cmd",
    "content": "REM\nREM Licensed to the Apache Software Foundation (ASF) under one or more\nREM contributor license agreements.  See the NOTICE file distributed with\nREM this work for additional information regarding copyright ownership.\nREM The ASF licenses this file to You under the Apache License, Version 2.0\nREM (the \"License\"); you may not use this file except in compliance with\nREM the License.  You may obtain a copy of the License at\nREM\nREM     http://www.apache.org/licenses/LICENSE-2.0\nREM\nREM Unless required by applicable law or agreed to in writing, software\nREM distributed under the License is distributed on an \"AS IS\" BASIS,\nREM WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nREM See the License for the specific language governing permissions and\nREM limitations under the License.\nREM\n:sourceEnvFile\r\n   set ENV_FILE=%1\r\n   shift\r\n   if not defined ENV_FILE (\r\n      set EXCEPTION=sourceEnvFile requires a parameter of the file to source\r\n      exit /b 1\r\n   )\r\n   call %ENV_FILE%\r\n   if errorlevel 1 (\r\n      set EXCEPTION=Please append 'exit /b 0' to the end of '%ENV_FILE%'\r\n      exit /b 1\r\n   )\r\n   exit /b 0\r\n"
  },
  {
    "path": "scriptbuilder/src/main/resources/functions/sourceEnvFile.sh",
    "content": "#\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements.  See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License.  You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nfunction sourceEnvFile {\n   [ $# -eq 1 ] || {\n      abort \"sourceEnvFile requires a parameter of the file to source\"\n      return 1\n   }\n   local ENV_FILE=\"$1\"; shift\n   . \"$ENV_FILE\" || {\n      abort \"Please append 'return 0' to the end of '$ENV_FILE'\"\n      return 1\n   }\n   return 0\n}"
  },
  {
    "path": "scriptbuilder/src/main/resources/functions/stop.cmd",
    "content": "REM\nREM Licensed to the Apache Software Foundation (ASF) under one or more\nREM contributor license agreements.  See the NOTICE file distributed with\nREM this work for additional information regarding copyright ownership.\nREM The ASF licenses this file to You under the Apache License, Version 2.0\nREM (the \"License\"); you may not use this file except in compliance with\nREM the License.  You may obtain a copy of the License at\nREM\nREM     http://www.apache.org/licenses/LICENSE-2.0\nREM\nREM Unless required by applicable law or agreed to in writing, software\nREM distributed under the License is distributed on an \"AS IS\" BASIS,\nREM WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nREM See the License for the specific language governing permissions and\nREM limitations under the License.\nREM\n:abort\r\n   CALL :findProcess %INSTANCE_NAME%\r\n   if defined _pid (\r\n      echo stopping %INSTANCE_NAME%\r\n      TASKKILL /F /T /PID %FOUND_PID% >NUL\r\n   )\r\n   schtasks /end /tn %INSTANCE_NAME% >NUL 2>NUL\r\n   schtasks /delete /tn %INSTANCE_NAME% /F >NUL 2>NUL\r\n   exit /b 0\r\n"
  },
  {
    "path": "scriptbuilder/src/main/resources/functions/validateEnvFile.cmd",
    "content": "REM\nREM Licensed to the Apache Software Foundation (ASF) under one or more\nREM contributor license agreements.  See the NOTICE file distributed with\nREM this work for additional information regarding copyright ownership.\nREM The ASF licenses this file to You under the Apache License, Version 2.0\nREM (the \"License\"); you may not use this file except in compliance with\nREM the License.  You may obtain a copy of the License at\nREM\nREM     http://www.apache.org/licenses/LICENSE-2.0\nREM\nREM Unless required by applicable law or agreed to in writing, software\nREM distributed under the License is distributed on an \"AS IS\" BASIS,\nREM WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nREM See the License for the specific language governing permissions and\nREM limitations under the License.\nREM\n:validateEnvFile\r\n   set ENV_FILE=%1\r\n   shift\r\n   if not defined ENV_FILE (\r\n      set EXCEPTION=validateEnvFile requires a parameter of the file to source\r\n      exit /b 1\r\n   )\r\n   if not exist \"%ENV_FILE%\" (\r\n      set EXCEPTION=env file '%ENV_FILE%' does not exist\r\n      exit /b 1\r\n   )\r\n   exit /b 0\r\n"
  },
  {
    "path": "scriptbuilder/src/main/resources/functions/validateEnvFile.sh",
    "content": "#\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements.  See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License.  You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nfunction validateEnvFile {\n   [ $# -eq 1 ] || {\n      abort \"validateEnvFile requires a parameter of the file to source\"\n      return 1\n   }\n   local ENV_FILE=\"$1\"; shift\n   [ -f \"$ENV_FILE\" ] || {\n      abort \"env file '$ENV_FILE' does not exist\"\n      return 1\n   }\n   [ -r \"$ENV_FILE\" ] || {\n      abort \"env file '$ENV_FILE' is not readable\"\n      return 1\n   }\n   grep '\\<exit\\>' \"$ENV_FILE\" > /dev/null && {\n      abort \"please remove the 'exit' statement from env file '$ENV_FILE'\"\n      return 1\n   }\n   [ -x \"$ENV_FILE\" ] && {\n      abort \"please remove the execute permission from env file '$ENV_FILE'\"\n      return 1\n   }\n   return 0\n}"
  },
  {
    "path": "scriptbuilder/src/test/java/org/jclouds/scriptbuilder/EnvBuilderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.net.MalformedURLException;\n\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.jclouds.scriptbuilder.domain.ShellToken;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.io.Resources;\n\n/**\n * Tests possible uses of EnvBuilder\n */\npublic class EnvBuilderTest {\n\n   EnvBuilder testScriptBuilder = new EnvBuilder().export(\"JAVA_HOME\",\n            \"/apps/jdk1.6\");\n\n   @Test\n   public void testBuildSimpleWindows() throws MalformedURLException, IOException {\n      assertEquals(testScriptBuilder.build(OsFamily.WINDOWS),\n              Resources.toString(Resources.getResource(\"test_env.\"\n                        + ShellToken.SH.to(OsFamily.WINDOWS)), Charsets.UTF_8));\n   }\n\n   @Test\n   public void testBuildSimpleUNIX() throws MalformedURLException, IOException {\n      assertEquals(testScriptBuilder.build(OsFamily.UNIX),\n               Resources.toString(Resources.getResource(\"test_env.\"\n                        + ShellToken.SH.to(OsFamily.UNIX)), Charsets.UTF_8));\n   }\n\n   @Test\n   public void testExport() {\n      EnvBuilder builder = new EnvBuilder();\n      builder.export(\"JAVA_HOME\", \"/apps/jdk1.6\");\n      assertEquals(builder.variables, ImmutableMap.of(\"JAVA_HOME\", \"/apps/jdk1.6\"));\n   }\n\n   @Test\n   public void testNoExport() {\n      EnvBuilder builder = new EnvBuilder();\n      assertEquals(builder.variables.size(), 0);\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testExportNPE() {\n      new EnvBuilder().export(null, null);\n   }\n\n}\n"
  },
  {
    "path": "scriptbuilder/src/test/java/org/jclouds/scriptbuilder/InitScriptTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder;\n\nimport static org.jclouds.scriptbuilder.domain.Statements.appendFile;\nimport static org.jclouds.scriptbuilder.domain.Statements.call;\nimport static org.jclouds.scriptbuilder.domain.Statements.exec;\nimport static org.jclouds.scriptbuilder.domain.Statements.interpret;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.net.MalformedURLException;\n\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.jclouds.scriptbuilder.domain.ShellToken;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.io.Resources;\n\n/**\n * Tests possible uses of InitScript\n */\npublic class InitScriptTest {\n   InitScript testInitScript = InitScript\n         .builder()\n         .name(\"mkebsboot\")\n         .home(\"/mnt/tmp\")\n         .exportVariables(ImmutableMap.of(\"tmpDir\", \"/mnt/tmp\"))\n         .run(appendFile(\"{tmp}{fs}{uid}{fs}scripttest{fs}temp.txt\", ImmutableList.<String> of(\"hello world\")),\n               exec(\"find /\")).build();\n\n   public void testBuildSimpleWindows() throws MalformedURLException, IOException {\n      assertEquals(\n            testInitScript.render(OsFamily.WINDOWS),\n            Resources.toString(Resources.getResource(\"test_init.\" + ShellToken.SH.to(OsFamily.WINDOWS)), Charsets.UTF_8));\n   }\n\n   public void testBuildSimpleUNIX() throws MalformedURLException, IOException {\n      assertEquals(\n            testInitScript.render(OsFamily.UNIX),\n            Resources.toString(Resources.getResource(\"test_init.\" + ShellToken.SH.to(OsFamily.UNIX)), Charsets.UTF_8));\n   }\n\n   public void testBuildEBS() throws MalformedURLException, IOException {\n      assertEquals(InitScript\n            .builder()\n            .name(\"mkebsboot\")\n            .home(\"tmp\")\n            .logDir(\"/tmp/logs\")\n            .exportVariables(ImmutableMap.of(\"imageDir\", \"/mnt/tmp\", \"ebsDevice\", \"/dev/sdh\", \"ebsMountPoint\", \"/mnt/ebs\"))\n            .run(interpret(\n                              \"echo creating a filesystem and mounting the ebs volume\",\n                              \"{md} {varl}IMAGE_DIR{varr} {varl}EBS_MOUNT_POINT{varr}\",\n                              \"rm -rf {varl}IMAGE_DIR{varr}/*\",\n                              \"yes| mkfs -t ext3 {varl}EBS_DEVICE{varr} 2>&-\",\n                              \"mount {varl}EBS_DEVICE{varr} {varl}EBS_MOUNT_POINT{varr}\",\n                              \"echo making a local working copy of the boot disk\",\n                              \"rsync -ax --exclude /ubuntu/.bash_history --exclude /home/*/.bash_history --exclude /etc/ssh/ssh_host_* --exclude /etc/ssh/moduli --exclude /etc/udev/rules.d/*persistent-net.rules --exclude /var/lib/ec2/* --exclude=/mnt/* --exclude=/proc/* --exclude=/tmp/* --exclude=/dev/log / {varl}IMAGE_DIR{varr}\",\n                              \"echo preparing the local working copy\",\n                              \"touch {varl}IMAGE_DIR{varr}/etc/init.d/ec2-init-user-data\",\n                              \"echo copying the local working copy to the ebs mount\", \"{cd} {varl}IMAGE_DIR{varr}\",\n                              \"tar -cSf - * | tar xf - -C {varl}EBS_MOUNT_POINT{varr}\", \"echo size of ebs\",\n                              \"du -sk {varl}EBS_MOUNT_POINT{varr}\", \"echo size of source\",\n                              \"du -sk {varl}IMAGE_DIR{varr}\", \"rm -rf {varl}IMAGE_DIR{varr}/*\",\n                              \"umount {varl}EBS_MOUNT_POINT{varr}\", \"echo ----COMPLETE----\")).build().render(OsFamily.UNIX),\n            Resources.toString(Resources.getResource(\"test_ebs.\" + ShellToken.SH.to(OsFamily.UNIX)), Charsets.UTF_8));\n   }\n\n   InitScript testCallInRun = InitScript.builder().name(\"testcall\").init(exec(\"echo hello\"))\n         .run(call(\"sourceEnvFile\", \"foo\"), exec(\"find /\")).build();\n\n   @Test\n   public void testCallInRunUNIX() throws MalformedURLException, IOException {\n      assertEquals(\n            testCallInRun.render(OsFamily.UNIX),\n            Resources.toString(Resources.getResource(\"test_init_script.\" + ShellToken.SH.to(OsFamily.UNIX)), Charsets.UTF_8));\n   }\n\n}\n"
  },
  {
    "path": "scriptbuilder/src/test/java/org/jclouds/scriptbuilder/ScriptBuilderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder;\n\nimport static org.jclouds.scriptbuilder.ScriptBuilder.call;\nimport static org.jclouds.scriptbuilder.ScriptBuilder.findPid;\nimport static org.jclouds.scriptbuilder.domain.Statements.appendFile;\nimport static org.jclouds.scriptbuilder.domain.Statements.interpret;\nimport static org.jclouds.scriptbuilder.domain.Statements.kill;\nimport static org.jclouds.scriptbuilder.domain.Statements.newStatementList;\nimport static org.jclouds.scriptbuilder.domain.Statements.switchArg;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.net.MalformedURLException;\nimport java.util.Map;\n\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.jclouds.scriptbuilder.domain.ShellToken;\nimport org.jclouds.scriptbuilder.domain.Statement;\nimport org.jclouds.scriptbuilder.domain.SwitchArg;\nimport org.jclouds.scriptbuilder.util.Utils;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\nimport com.google.common.io.Resources;\n\n/**\n * Tests possible uses of ScriptBuilder\n */\npublic class ScriptBuilderTest {\n\n   ScriptBuilder testScriptBuilder = new ScriptBuilder()\n         .unsetEnvironmentVariable(\"RUNTIME\")\n         .addEnvironmentVariableScope(\"default\", ImmutableMap.of(\"RUNTIME\", \"Moo\"))\n         .addStatement(\n               switchArg(1, ImmutableMap.of(\n                     \"start\",\n                     newStatementList(call(\"default\"), interpret(\"echo start {varl}RUNTIME{varr}{lf}\")),\n                     \"stop\",\n                     newStatementList(call(\"default\"), interpret(\"echo stop {varl}RUNTIME{varr}{lf}\")),\n                     \"status\",\n                     newStatementList(\n                           appendFile(\"{tmp}{fs}{uid}{fs}scripttest{fs}temp.txt\",\n                                 ImmutableList.<String> of(\"hello world\")),\n                           interpret(\"echo {vq}the following should be []: [{varl}RUNTIME{varr}]{vq}{lf}\")))));\n\n   @Test\n   public void testBuildSimpleWindows() throws MalformedURLException, IOException {\n      assertEquals(\n            testScriptBuilder.render(OsFamily.WINDOWS),\n            Resources.toString(Resources.getResource(\"test_script.\" + ShellToken.SH.to(OsFamily.WINDOWS)), Charsets.UTF_8));\n   }\n\n   @Test\n   public void testBuildSimpleUNIX() throws MalformedURLException, IOException {\n      assertEquals(\n            testScriptBuilder.render(OsFamily.UNIX),\n            Resources.toString(Resources.getResource(\"test_script.\" + ShellToken.SH.to(OsFamily.UNIX)), Charsets.UTF_8));\n   }\n\n   ScriptBuilder findPidBuilder = new ScriptBuilder().addStatement(findPid(\"{args}\")).addStatement(\n         interpret(\"echo {varl}FOUND_PID{varr}{lf}\"));\n\n   @Test\n   public void testFindPidWindows() throws MalformedURLException, IOException {\n      assertEquals(\n            findPidBuilder.render(OsFamily.WINDOWS),\n            Resources.toString(Resources.getResource(\"test_find_pid.\" + ShellToken.SH.to(OsFamily.WINDOWS)), Charsets.UTF_8));\n   }\n\n   @Test\n   public void testFindPidUNIX() throws MalformedURLException, IOException {\n      assertEquals(\n            findPidBuilder.render(OsFamily.UNIX),\n            Resources.toString(Resources.getResource(\"test_find_pid.\" + ShellToken.SH.to(OsFamily.UNIX)), Charsets.UTF_8));\n   }\n\n   ScriptBuilder seekAndDestroyBuilder = new ScriptBuilder().addStatement(findPid(\"{args}\")).addStatement(kill());\n\n   @Test\n   public void testSeekAndDestroyWindows() throws MalformedURLException, IOException {\n      assertEquals(seekAndDestroyBuilder.render(OsFamily.WINDOWS), Resources.toString(\n            Resources.getResource(\"test_seek_and_destroy.\" + ShellToken.SH.to(OsFamily.WINDOWS)), Charsets.UTF_8));\n   }\n\n   @Test\n   public void testSeekAndDestroyUNIX() throws MalformedURLException, IOException {\n      assertEquals(\n            seekAndDestroyBuilder.render(OsFamily.UNIX),\n            Resources.toString(Resources.getResource(\"test_seek_and_destroy.\" + ShellToken.SH.to(OsFamily.UNIX)), Charsets.UTF_8));\n   }\n\n   @Test\n   public void testSwitchOn() {\n      ScriptBuilder builder = new ScriptBuilder();\n      builder.addStatement(switchArg(1,\n            ImmutableMap.of(\"start\", interpret(\"echo started{lf}\"), \"stop\", interpret(\"echo stopped{lf}\"))));\n      assertEquals(builder.statements, ImmutableList.of(new SwitchArg(1, ImmutableMap.of(\"start\",\n            interpret(\"echo started{lf}\"), \"stop\", interpret(\"echo stopped{lf}\")))));\n   }\n\n   @Test\n   public void testNoSwitchOn() {\n      ScriptBuilder builder = new ScriptBuilder();\n      assertEquals(builder.statements.size(), 0);\n   }\n\n   @Test\n   public void testExport() {\n      ScriptBuilder builder = new ScriptBuilder();\n      builder.addEnvironmentVariableScope(\"default\", ImmutableMap.of(\"JAVA_HOME\", \"/apps/jdk1.6\"));\n      assertEquals(builder.variableScopes, ImmutableMap.of(\"default\", ImmutableMap.of(\"JAVA_HOME\", \"/apps/jdk1.6\")));\n   }\n\n   @Test\n   public void testNoExport() {\n      ScriptBuilder builder = new ScriptBuilder();\n      assertEquals(builder.variableScopes.size(), 0);\n   }\n\n   @Test(expectedExceptions = NullPointerException.class)\n   public void testExportNPE() {\n      new ScriptBuilder().addEnvironmentVariableScope(null, null);\n   }\n   \n   @Test\n   public void testResolveFunctionDependenciesForStatementsUNIX() {\n      ImmutableMap<String, String> defaultFunctions = ImmutableMap.of(\"abort\",\n               Utils.writeFunctionFromResource(\"abort\", OsFamily.UNIX));\n\n      for (String fn : defaultFunctions.values()) {\n         assertEquals(-1, fn.indexOf(\"\\r\\n\"), \"windows linefeeds!\");\n      }\n\n      Map<String, String> resolvedFunctions = ScriptBuilder.resolveFunctionDependenciesForStatements(defaultFunctions,\n               ImmutableSet.<Statement> of(call(\"nonewline\")), OsFamily.UNIX);\n\n      assertEquals(\n               resolvedFunctions,\n               ImmutableMap.of(\"abort\", Utils.writeFunctionFromResource(\"abort\", OsFamily.UNIX), \"nonewline\",\n                        Utils.writeFunctionFromResource(\"nonewline\", OsFamily.UNIX)));\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/AppendFileTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.domain;\n\nimport static org.jclouds.scriptbuilder.domain.Statements.appendFile;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.io.Resources;\n\n@Test(groups = \"unit\")\npublic class AppendFileTest {\n   Statement statement = appendFile(\"{root}etc{fs}chef{fs}client.rb\", ImmutableList.of(\"log_level :info\",\n            \"log_location STDOUT\", String.format(\"chef_server_url \\\"%s\\\"\", \"http://localhost:4000\")));\n\n   public void testUNIX() throws IOException {\n      assertEquals(statement.render(OsFamily.UNIX), Resources.toString(Resources\n               .getResource(\"client_rb_append.\" + ShellToken.SH.to(OsFamily.UNIX)), Charsets.UTF_8));\n   }\n\n   public void testWINDOWS() throws IOException {\n      assertEquals(statement.render(OsFamily.WINDOWS), Resources.toString(Resources\n               .getResource(\"client_rb_append.\" + ShellToken.SH.to(OsFamily.WINDOWS)), Charsets.UTF_8));\n   }\n\n}\n"
  },
  {
    "path": "scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/CallTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.domain;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class CallTest {\n\n   public void testCallNoArgsUNIX() {\n      Call call = new Call(\"help\");\n      assertEquals(call.render(OsFamily.UNIX), \"help || return 1\\n\");\n   }\n\n   public void testCallNoArgsWINDOWS() {\n      Call call = new Call(\"help\");\n      assertEquals(call.render(OsFamily.WINDOWS), \"call :help\\r\\nif errorlevel 1 goto abort\\r\\n\");\n   }\n\n   public void testCallArgsUNIX() {\n      Call call = new Call(\"help\", \"me\", \"rhonda\");\n      assertEquals(call.render(OsFamily.UNIX), \"help me rhonda || return 1\\n\");\n   }\n\n   public void testCallArgsWINDOWS() {\n      Call call = new Call(\"help\", \"me\", \"rhonda\");\n      assertEquals(call.render(OsFamily.WINDOWS),\n               \"call :help me rhonda\\r\\nif errorlevel 1 goto abort\\r\\n\");\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/CreateOrOverwriteFileTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.domain;\n\nimport static org.jclouds.scriptbuilder.domain.Statements.createOrOverwriteFile;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.io.Resources;\n\n@Test(groups = \"unit\")\npublic class CreateOrOverwriteFileTest {\n   Statement statement = createOrOverwriteFile(\"{root}etc{fs}chef{fs}client.rb\", ImmutableList.of(\"log_level :info\",\n            \"log_location STDOUT\", String.format(\"chef_server_url \\\"%s\\\"\", \"http://localhost:4000\")));\n\n   public void testUNIX() throws IOException {\n      assertEquals(statement.render(OsFamily.UNIX), Resources.toString(Resources\n               .getResource(\"client_rb_overwrite.\" + ShellToken.SH.to(OsFamily.UNIX)), Charsets.UTF_8));\n   }\n\n   public void testWINDOWS() throws IOException {\n      assertEquals(statement.render(OsFamily.WINDOWS), Resources.toString(Resources\n               .getResource(\"client_rb_overwrite.\" + ShellToken.SH.to(OsFamily.WINDOWS)), Charsets.UTF_8));\n   }\n\n}\n"
  },
  {
    "path": "scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/CreateRunScriptTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.domain;\n\nimport static org.jclouds.scriptbuilder.domain.Statements.appendFile;\nimport static org.jclouds.scriptbuilder.domain.Statements.createRunScript;\nimport static org.jclouds.scriptbuilder.domain.Statements.exec;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.io.Resources;\n\n@Test(groups = \"unit\")\npublic class CreateRunScriptTest {\n   Statement statement = createRunScript(\n            \"yahooprod\",\n            ImmutableList.<String> of(\"JAVA_HOME\"),\n            \"{tmp}{fs}{uid}{fs}scripttest\",\n            ImmutableList\n                     .<Statement> of(\n                              exec(\"echo hello\"),\n                              appendFile(\"{tmp}{fs}{uid}{fs}scripttest{fs}temp.txt\", ImmutableList\n                                       .<String> of(\"hello world\")),\n                              exec(\"echo {varl}JAVA_HOME{varr}{fs}bin{fs}java -DinstanceName={varl}INSTANCE_NAME{varr} myServer.Main\")));\n\n   public void testUNIX() throws IOException {\n      assertEquals(statement.render(OsFamily.UNIX), Resources.toString(Resources\n               .getResource(\"test_runrun.\" + ShellToken.SH.to(OsFamily.UNIX)), Charsets.UTF_8));\n   }\n\n   @Test(expectedExceptions = UnsupportedOperationException.class)\n   public void testWINDOWSUnimplemented() throws IOException {\n      statement.render(OsFamily.WINDOWS);\n   }\n\n}\n"
  },
  {
    "path": "scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/PipeHttpResponseToTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.domain;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMultimap;\n\n@Test(groups = \"unit\")\npublic class PipeHttpResponseToTest {\n   PipeHttpResponseTo bash = new PipeHttpResponseTo(Statements.interpret(\"bash\"), \"GET\", URI\n            .create(\"https://adriancolehappy.s3.amazonaws.com/java/install\"), ImmutableMultimap.of(\"Host\",\n            \"adriancolehappy.s3.amazonaws.com\", \"Date\", \"Sun, 12 Sep 2010 08:25:19 GMT\", \"Authorization\",\n            \"AWS 0ASHDJAS82:JASHFDA=\"));\n\n   PipeHttpResponseToBash bash2 = new PipeHttpResponseToBash(\"GET\", URI\n            .create(\"https://adriancolehappy.s3.amazonaws.com/java/install\"), ImmutableMultimap.of(\"Host\",\n            \"adriancolehappy.s3.amazonaws.com\", \"Date\", \"Sun, 12 Sep 2010 08:25:19 GMT\", \"Authorization\",\n            \"AWS 0ASHDJAS82:JASHFDA=\"));\n\n   public void testPipeHttpResponseToBashUNIX() {\n      assertEquals(\n               bash.render(OsFamily.UNIX),\n               \"curl -q -s -S -L --connect-timeout 10 --max-time 600 --retry 20 -X GET -H \\\"Host: adriancolehappy.s3.amazonaws.com\\\" -H \\\"Date: Sun, 12 Sep 2010 08:25:19 GMT\\\" -H \\\"Authorization: AWS 0ASHDJAS82:JASHFDA=\\\" https://adriancolehappy.s3.amazonaws.com/java/install |(bash)\\n\");\n      assertEquals(bash2.render(OsFamily.UNIX), bash.render(OsFamily.UNIX));\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class)\n   public void testPipeHttpResponseToBashWINDOWS() {\n      bash.render(OsFamily.WINDOWS);\n   }\n\n   PipeHttpResponseTo untar = new PipeHttpResponseTo(Statements\n            .interpret(\"{md} {root}stage{fs} &&{cd} {root}stage{fs} &&tar -xpzf -\"), \"GET\", URI\n            .create(\"https://adriancolehappy.s3.amazonaws.com/java/install\"), ImmutableMultimap.of(\"Host\",\n            \"adriancolehappy.s3.amazonaws.com\", \"Date\", \"Sun, 12 Sep 2010 08:25:19 GMT\", \"Authorization\",\n            \"AWS 0ASHDJAS82:JASHFDA=\"));\n\n   PipeHttpResponseTo untar2 = new PipeHttpResponseToTarxpzfIntoDirectory(\"GET\", URI\n            .create(\"https://adriancolehappy.s3.amazonaws.com/java/install\"), ImmutableMultimap.of(\"Host\",\n            \"adriancolehappy.s3.amazonaws.com\", \"Date\", \"Sun, 12 Sep 2010 08:25:19 GMT\", \"Authorization\",\n            \"AWS 0ASHDJAS82:JASHFDA=\"), \"{root}stage{fs}\");\n\n   public void testPipeHttpResponseToUntarUNIX() {\n      assertEquals(\n               untar.render(OsFamily.UNIX),\n               \"curl -q -s -S -L --connect-timeout 10 --max-time 600 --retry 20 -X GET -H \\\"Host: adriancolehappy.s3.amazonaws.com\\\" -H \\\"Date: Sun, 12 Sep 2010 08:25:19 GMT\\\" -H \\\"Authorization: AWS 0ASHDJAS82:JASHFDA=\\\" https://adriancolehappy.s3.amazonaws.com/java/install |(mkdir -p /stage/ &&cd /stage/ &&tar -xpzf -)\\n\");\n      assertEquals(untar.render(OsFamily.UNIX), untar2.render(OsFamily.UNIX));\n\n   }\n\n}\n"
  },
  {
    "path": "scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/SaveHttpResponseToTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.domain;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMultimap;\n\n@Test(groups = \"unit\", testName = \"SaveHttpResponseToTest\")\npublic class SaveHttpResponseToTest {\n\n   public void testSaveHttpResponseToDirAndFileUNIX() {\n      SaveHttpResponseTo testWithDir = new SaveHttpResponseTo(\"/tmp\", \"install\", \"GET\",\n            URI.create(\"https://adriancolehappy.s3.amazonaws.com/java/install\"), ImmutableMultimap.of(\"Host\",\n                  \"adriancolehappy.s3.amazonaws.com\", \"Date\", \"Sun, 12 Sep 2010 08:25:19 GMT\", \"Authorization\",\n                  \"AWS 0ASHDJAS82:JASHFDA=\"));\n      assertEquals(\n            testWithDir.render(OsFamily.UNIX),\n            \"(mkdir -p /tmp && cd /tmp && [ ! -f install ] && curl -q -s -S -L --connect-timeout 10 --max-time 600 --retry 20 -C - -X GET -H \\\"Host: adriancolehappy.s3.amazonaws.com\\\" -H \\\"Date: Sun, 12 Sep 2010 08:25:19 GMT\\\" -H \\\"Authorization: AWS 0ASHDJAS82:JASHFDA=\\\" https://adriancolehappy.s3.amazonaws.com/java/install >install)\\n\");\n   }\n\n}\n"
  },
  {
    "path": "scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/ShellTokenTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.domain;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Map;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\n\n@Test(groups = \"unit\")\npublic class ShellTokenTest {\n\n   public void testTokenValueMapUNIX() {\n      Map<String, String> expected = new ImmutableMap.Builder<String, String>().put(\"fs\", \"/\").put(\n               \"ps\", \":\").put(\"lf\", \"\\n\").put(\"sh\", \"sh\").put(\"source\", \".\").put(\"rem\", \"#\").put(\n               \"args\", \"$@\").put(\"varl\", \"$\").put(\"return\", \"return\").put(\"exit\", \"exit\").put(\n               \"varr\", \"\").put(\"libraryPathVariable\", \"LD_LIBRARY_PATH\").put(\"beginScript\",\n               \"#!/bin/bash\\nset +u\\nshopt -s xpg_echo\\nshopt -s expand_aliases\\n\").put(\n               \"endScript\", \"exit $?\\n\").put(\"vq\", \"\\\"\").put(\"beginFunctions\", \"\").put(\n               \"endFunctions\", \"\").put(\"fncl\", \"function \").put(\"fncr\", \" {\\n\").put(\"fnce\",\n               \"   return $?\\n}\\n\").put(\"export\", \"export\").put(\"rm\", \"rm\").put(\"cd\", \"cd\").put(\n               \"tmp\", \"/tmp\").put(\"uid\", \"$USER\").put(\"root\", \"/\").put(\"closeFd\", \">&-\").put(\"md\",\n               \"mkdir -p\").put(\"escvar\", \"\\\\\").build();\n      assertEquals(ShellToken.tokenValueMap(OsFamily.UNIX), expected);\n   }\n\n   public void testTokenValueMapWindows() {\n      Map<String, String> expected = new ImmutableMap.Builder<String, String>().put(\"fs\", \"\\\\\")\n               .put(\"ps\", \";\").put(\"lf\", \"\\r\\n\").put(\"sh\", \"cmd\").put(\"source\", \"@call\").put(\"rem\",\n                        \"@rem\").put(\"args\", \"%*\").put(\"varl\", \"%\").put(\"exit\", \"exit /b\").put(\n                        \"varr\", \"%\").put(\"libraryPathVariable\", \"PATH\").put(\"return\", \"exit /b\")\n               .put(\"vq\", \"\").put(\"beginFunctions\", \"GOTO FUNCTION_END\\r\\n\").put(\"endFunctions\",\n                        \":FUNCTION_END\\r\\n\").put(\"beginScript\", \"@echo off\\r\\n\").put(\"endScript\",\n                        \"exit /b 0\\r\\n\").put(\"fncl\", \":\").put(\"fncr\", \"\\r\\n\").put(\"fnce\",\n                        \"   exit /b 0\\r\\n\").put(\"export\", \"set\").put(\"rm\", \"del\")\n               .put(\"cd\", \"cd /d\").put(\"tmp\", \"%TEMP%\").put(\"uid\", \"%USERNAME%\")\n               .put(\"root\", \"c:\\\\\").put(\"closeFd\", \">NUL\").put(\"md\", \"md\").put(\"escvar\", \"%\")\n               .build();\n\n      assertEquals(ShellToken.tokenValueMap(OsFamily.WINDOWS), expected);\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/StatementListTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.domain;\n\nimport static org.jclouds.scriptbuilder.domain.Statements.call;\nimport static org.jclouds.scriptbuilder.domain.Statements.interpret;\nimport static org.jclouds.scriptbuilder.domain.Statements.newStatementList;\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class StatementListTest {\n   Statement statement = newStatementList(call(\"default\"), interpret(\"echo started{lf}\"));\n\n   public void testUNIX() {\n      assertEquals(statement.render(OsFamily.UNIX), \"default || return 1\\necho started\\n\");\n   }\n\n   public void testWINDOWS() {\n      assertEquals(statement.render(OsFamily.WINDOWS),\n               \"call :default\\r\\nif errorlevel 1 goto abort\\r\\necho started\\r\\n\");\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/StatementsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.domain;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\n\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"StatementsTest\")\npublic class StatementsTest {\n\n   public void testSaveHttpResponseToUNIX() {\n      Statement save = Statements.saveHttpResponseTo(\n            URI.create(\"https://s3.amazonaws.com/MinecraftDownload/launcher/minecraft_server.jar\"), \"/opt/minecraft\",\n            \"minecraft_server.jar\");\n      assertEquals(\n            save.render(OsFamily.UNIX),\n            \"(mkdir -p /opt/minecraft && cd /opt/minecraft && [ ! -f minecraft_server.jar ] && curl -q -s -S -L --connect-timeout 10 --max-time 600 --retry 20 -C - -X GET  https://s3.amazonaws.com/MinecraftDownload/launcher/minecraft_server.jar >minecraft_server.jar)\\n\");\n   }\n\n   public void testExtractTargzIntoDirectoryUNIX() {\n      Statement save = Statements\n            .extractTargzIntoDirectory(\n                  URI.create(\"https://s3.amazonaws.com/MinecraftDownload/launcher/minecraft_server.tar.gz\"),\n                  \"/opt/minecraft\");\n      assertEquals(\n            save.render(OsFamily.UNIX),\n            \"curl -q -s -S -L --connect-timeout 10 --max-time 600 --retry 20 -X GET  https://s3.amazonaws.com/MinecraftDownload/launcher/minecraft_server.tar.gz |(mkdir -p /opt/minecraft &&cd /opt/minecraft &&tar -xpzf -)\\n\");\n   }\n   \n   public void testExtractTargzAndFlattenIntoDirectoryUNIX() {\n      Statement save = Statements\n            .extractTargzAndFlattenIntoDirectory(\n                  URI.create(\"http://www.us.apache.org/dist/maven/binaries/apache-maven-3.0.4-bin.tar.gz\"),\n                  \"/usr/local/maven\");\n      assertEquals(\n            save.render(OsFamily.UNIX),\n            \"export TAR_TEMP=\\\"$(mktemp -d)\\\"\\n\" +\n            \"curl -q -s -S -L --connect-timeout 10 --max-time 600 --retry 20 -X GET  http://www.us.apache.org/dist/maven/binaries/apache-maven-3.0.4-bin.tar.gz |(mkdir -p \\\"${TAR_TEMP}\\\" &&cd \\\"${TAR_TEMP}\\\" &&tar -xpzf -)\\n\" +\n            \"mkdir -p /usr/local/maven\\n\" +\n            \"mv \\\"${TAR_TEMP}\\\"/*/* /usr/local/maven\\n\" +\n            \"rm -rf \\\"${TAR_TEMP}\\\"\\n\");\n   }\n\n\n}\n"
  },
  {
    "path": "scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/SwitchArgTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.domain;\n\nimport static org.jclouds.scriptbuilder.domain.Statements.appendFile;\nimport static org.jclouds.scriptbuilder.domain.Statements.interpret;\nimport static org.jclouds.scriptbuilder.domain.Statements.newStatementList;\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\n\n@Test(groups = \"unit\")\npublic class SwitchArgTest {\n\n   public void testSwitchArgUNIX() {\n      assertEquals(new SwitchArg(1, ImmutableMap.of(\"0\", newStatementList(appendFile(\n               \"{tmp}{fs}{uid}{fs}scripttest{fs}temp.txt\", ImmutableList.of(\"hello world\")),\n               interpret(\"echo hello zero{lf}\")), \"1\", interpret(\"echo hello one{lf}\"))).render(OsFamily.UNIX),\n      \"case $1 in\\n\" +\n      \"0)\\n\" +\n      \"   cat >> /tmp/$USER/scripttest/temp.txt <<-'END_OF_JCLOUDS_FILE'\\n\" +\n      \"\\thello world\\n\" +\n      \"END_OF_JCLOUDS_FILE\\n\" +\n      \"   echo hello zero\\n\" +\n      \"   ;;\\n\" +\n      \"1)\\n\" +\n      \"   echo hello one\\n\" +\n      \"   ;;\\n\" +\n      \"esac\\n\");\n   }\n\n   public void testSwitchArgWindows() {\n      assertEquals(\n               new SwitchArg(1, ImmutableMap.of(\"0\", interpret(\"echo hello zero{lf}\"), \"1\",\n                        interpret(\"echo hello one{lf}\"))).render(OsFamily.WINDOWS),\n               \"if not \\\"%1\\\" == \\\"0\\\" if not \\\"%1\\\" == \\\"1\\\" (\\r\\n   set EXCEPTION=bad argument: %1 not in 0 1\\r\\n   goto abort\\r\\n)\\r\\ngoto CASE_%1\\r\\n:CASE_0\\r\\n   echo hello zero\\r\\n   GOTO END_SWITCH\\r\\n:CASE_1\\r\\n   echo hello one\\r\\n   GOTO END_SWITCH\\r\\n:END_SWITCH\\r\\n\");\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/UnzipHttpResponseIntoDirectoryToTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.domain;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.net.URI;\n\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMultimap;\n\n@Test(groups = \"unit\")\npublic class UnzipHttpResponseIntoDirectoryToTest {\n\n   UnzipHttpResponseIntoDirectory jboss = new UnzipHttpResponseIntoDirectory(\n            \"GET\",\n            URI\n                     .create(\"http://superb-sea2.dl.sourceforge.net/project/jboss/JBoss/JBoss-5.0.0.CR2/jboss-5.0.0.CR2-jdk6.zip\"),\n            ImmutableMultimap.<String, String> of(), \"/tmp\");\n\n   public void testUnzipHttpResponseIntoDirectoryUNIX() {\n      assertEquals(\n               jboss.render(OsFamily.UNIX),\n               \"(mkdir -p /tmp &&cd /tmp &&curl -X -L GET -s --retry 20  http://superb-sea2.dl.sourceforge.net/project/jboss/JBoss/JBoss-5.0.0.CR2/jboss-5.0.0.CR2-jdk6.zip >extract.zip && unzip -o -qq extract.zip&& rm extract.zip)\\n\");\n   }\n   public void testUnzipHttpResponseIntoDirectoryWINDOWS() {\n     \n               jboss.render(OsFamily.WINDOWS);  }\n}\n"
  },
  {
    "path": "scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/chef/RoleTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.domain.chef;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\n/**\n * Unit tests for the {@link Role} class.\n */\n@Test(groups = \"unit\", testName = \"RoleTest\")\npublic class RoleTest {\n\n   public void testToJsonStringWithOnlyName() {\n      Role role = Role.builder().name(\"foo\").build();\n      assertEquals(role.toJsonString(), \"{\\\"name\\\": \\\"foo\\\",\\\"description\\\":\\\"\\\",\\\"default_attributes\\\":{},\"\n            + \"\\\"override_attributes\\\":{},\\\"json_class\\\":\\\"Chef::Role\\\",\\\"chef_type\\\":\\\"role\\\",\\\"run_list\\\":[]}\");\n   }\n\n   public void testToJsonStringWithDescription() {\n      Role role = Role.builder().name(\"foo\").description(\"Foo role\").build();\n      assertEquals(role.toJsonString(), \"{\\\"name\\\": \\\"foo\\\",\\\"description\\\":\\\"Foo role\\\",\\\"default_attributes\\\":{},\"\n            + \"\\\"override_attributes\\\":{},\\\"json_class\\\":\\\"Chef::Role\\\",\\\"chef_type\\\":\\\"role\\\",\\\"run_list\\\":[]}\");\n   }\n\n   public void testToJsonStringWithDefaultAttributes() {\n      Role role = Role.builder().name(\"foo\").jsonDefaultAttributes(\"{\\\"foo\\\":\\\"bar\\\"}\").build();\n      assertEquals(role.toJsonString(),\n            \"{\\\"name\\\": \\\"foo\\\",\\\"description\\\":\\\"\\\",\\\"default_attributes\\\":{\\\"foo\\\":\\\"bar\\\"},\"\n                  + \"\\\"override_attributes\\\":{},\\\"json_class\\\":\\\"Chef::Role\\\",\\\"chef_type\\\":\\\"role\\\",\"\n                  + \"\\\"run_list\\\":[]}\");\n   }\n\n   public void testToJsonStringWithOverrideAttributes() {\n      Role role = Role.builder().name(\"foo\").jsonOverrideAttributes(\"{\\\"foo\\\":\\\"bar\\\"}\").build();\n      assertEquals(role.toJsonString(), \"{\\\"name\\\": \\\"foo\\\",\\\"description\\\":\\\"\\\",\\\"default_attributes\\\":{},\"\n            + \"\\\"override_attributes\\\":{\\\"foo\\\":\\\"bar\\\"},\\\"json_class\\\":\\\"Chef::Role\\\",\\\"chef_type\\\":\\\"role\\\",\"\n            + \"\\\"run_list\\\":[]}\");\n   }\n\n   public void testToJsonStringWithSingleRecipe() {\n      RunList runlist = RunList.builder().recipe(\"apache2\").build();\n      Role role = Role.builder().name(\"foo\").runlist(runlist).build();\n      assertEquals(role.toJsonString(),\n            \"{\\\"name\\\": \\\"foo\\\",\\\"description\\\":\\\"\\\",\\\"default_attributes\\\":{},\\\"override_attributes\\\":{},\"\n                  + \"\\\"json_class\\\":\\\"Chef::Role\\\",\\\"chef_type\\\":\\\"role\\\",\\\"run_list\\\":[\\\"recipe[apache2]\\\"]}\");\n   }\n\n   public void testToJsonStringWithMultipleRecipes() {\n      RunList runlist = RunList.builder().recipe(\"apache2\").recipe(\"git\").build();\n      Role role = Role.builder().name(\"foo\").runlist(runlist).build();\n      assertEquals(role.toJsonString(),\n            \"{\\\"name\\\": \\\"foo\\\",\\\"description\\\":\\\"\\\",\\\"default_attributes\\\":{},\\\"override_attributes\\\":{},\"\n                  + \"\\\"json_class\\\":\\\"Chef::Role\\\",\\\"chef_type\\\":\\\"role\\\",\"\n                  + \"\\\"run_list\\\":[\\\"recipe[apache2]\\\",\\\"recipe[git]\\\"]}\");\n   }\n\n   public void testToJsonStringWithSingleRole() {\n      RunList runlist = RunList.builder().role(\"webserver\").build();\n      Role role = Role.builder().name(\"foo\").runlist(runlist).build();\n      assertEquals(role.toJsonString(),\n            \"{\\\"name\\\": \\\"foo\\\",\\\"description\\\":\\\"\\\",\\\"default_attributes\\\":{},\\\"override_attributes\\\":{},\"\n                  + \"\\\"json_class\\\":\\\"Chef::Role\\\",\\\"chef_type\\\":\\\"role\\\",\\\"run_list\\\":[\\\"role[webserver]\\\"]}\");\n   }\n\n   public void testToJsonStringWithMultipleRoles() {\n      RunList runlist = RunList.builder().role(\"webserver\").role(\"firewall\").build();\n      Role role = Role.builder().name(\"foo\").runlist(runlist).build();\n      assertEquals(role.toJsonString(),\n            \"{\\\"name\\\": \\\"foo\\\",\\\"description\\\":\\\"\\\",\\\"default_attributes\\\":{},\\\"override_attributes\\\":{},\"\n                  + \"\\\"json_class\\\":\\\"Chef::Role\\\",\\\"chef_type\\\":\\\"role\\\",\"\n                  + \"\\\"run_list\\\":[\\\"role[webserver]\\\",\\\"role[firewall]\\\"]}\");\n   }\n\n   public void testToJsonStringWithRolesAndRecipes() {\n      RunList runlist = RunList.builder().role(\"webserver\").recipe(\"git\").build();\n      Role role = Role.builder().name(\"foo\").runlist(runlist).build();\n      assertEquals(role.toJsonString(),\n            \"{\\\"name\\\": \\\"foo\\\",\\\"description\\\":\\\"\\\",\\\"default_attributes\\\":{},\\\"override_attributes\\\":{},\"\n                  + \"\\\"json_class\\\":\\\"Chef::Role\\\",\\\"chef_type\\\":\\\"role\\\",\"\n                  + \"\\\"run_list\\\":[\\\"role[webserver]\\\",\\\"recipe[git]\\\"]}\");\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/chef/RunListTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.domain.chef;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.testng.annotations.Test;\n\n/**\n * Unit tests for the {@link RunList} class.\n */\n@Test(groups = \"unit\", testName = \"RunListTest\")\npublic class RunListTest {\n\n   public void testToStringEmptyRunlist() {\n      assertEquals(RunList.builder().build().toString(), \"[]\");\n   }\n\n   public void testToStringWithRecipe() {\n      assertEquals(RunList.builder().recipe(\"apache2\").build().toString(), \"[\\\"recipe[apache2]\\\"]\");\n   }\n\n   public void testToStringWithRole() {\n      assertEquals(RunList.builder().role(\"webserver\").build().toString(), \"[\\\"role[webserver]\\\"]\");\n   }\n\n   public void testToStringWithRecipeAndRole() {\n      assertEquals(RunList.builder().recipe(\"apache2\").role(\"webserver\").build().toString(),\n            \"[\\\"recipe[apache2]\\\",\\\"role[webserver]\\\"]\");\n   }\n\n}\n"
  },
  {
    "path": "scriptbuilder/src/test/java/org/jclouds/scriptbuilder/functions/CredentialsFromAdminAccessTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.functions;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.scriptbuilder.InitScript;\nimport org.jclouds.scriptbuilder.domain.Statement;\nimport org.jclouds.scriptbuilder.domain.Statements;\nimport org.jclouds.scriptbuilder.statements.login.AdminAccess;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\n\n@Test(groups = \"unit\")\npublic class CredentialsFromAdminAccessTest {\n\n   public void testWhenNotAdminAccess() {\n\n      Statement statement = Statements.exec(\"echo hello\");\n      assertEquals(CredentialsFromAdminAccess.INSTANCE.apply(statement), null);\n\n      Statement statementList = Statements.newStatementList(statement);\n      assertEquals(CredentialsFromAdminAccess.INSTANCE.apply(statementList), null);\n\n   }\n\n   public void testWhenAdminAccess() {\n      AdminAccess.Configuration configuration = createMock(AdminAccess.Configuration.class);\n      AdminAccess statement = createMock(AdminAccess.class);\n      Credentials creds = createMock(Credentials.class);\n\n      expect(statement.getAdminCredentials()).andReturn(creds);\n\n      replay(configuration);\n      replay(statement);\n      replay(creds);\n\n      assertEquals(CredentialsFromAdminAccess.INSTANCE.apply(statement), creds);\n\n      verify(configuration);\n      verify(statement);\n      verify(creds);\n   }\n\n   public void testWhenAdminAccessInsideList() {\n      AdminAccess.Configuration configuration = createMock(AdminAccess.Configuration.class);\n      AdminAccess statement = createMock(AdminAccess.class);\n      Credentials creds = createMock(Credentials.class);\n\n      expect(statement.getAdminCredentials()).andReturn(creds);\n\n      replay(configuration);\n      replay(statement);\n      replay(creds);\n\n      assertEquals(CredentialsFromAdminAccess.INSTANCE.apply(Statements.newStatementList(statement)), creds);\n\n      verify(configuration);\n      verify(statement);\n      verify(creds);\n   }\n\n   public void testWhenAdminAccessInsideInitBuilder() {\n      AdminAccess.Configuration configuration = createMock(AdminAccess.Configuration.class);\n      AdminAccess statement = createMock(AdminAccess.class);\n      Credentials creds = createMock(Credentials.class);\n\n      expect(statement.getAdminCredentials()).andReturn(creds);\n\n      replay(configuration);\n      replay(statement);\n      replay(creds);\n      \n      InitScript testInitBuilder = InitScript.builder().name(\"mkebsboot\").home(\"/mnt/tmp\")\n            .exportVariables(ImmutableMap.of(\"tmpDir\", \"/mnt/tmp\")).run(statement).build();\n      \n      assertEquals(CredentialsFromAdminAccess.INSTANCE.apply(testInitBuilder), creds);\n\n      verify(configuration);\n      verify(statement);\n      verify(creds);\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/test/java/org/jclouds/scriptbuilder/functions/InitAdminAccessTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.functions;\n\nimport static org.easymock.EasyMock.createMock;\nimport static org.easymock.EasyMock.expect;\nimport static org.easymock.EasyMock.replay;\nimport static org.easymock.EasyMock.verify;\n\nimport org.jclouds.scriptbuilder.InitScript;\nimport org.jclouds.scriptbuilder.domain.Statements;\nimport org.jclouds.scriptbuilder.statements.login.AdminAccess;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\n\n@Test(groups = \"unit\")\npublic class InitAdminAccessTest {\n\n   public void testWhenNotAdminAccess() {\n      AdminAccess.Configuration configuration = createMock(AdminAccess.Configuration.class);\n\n      InitAdminAccess initAdminAccess = new InitAdminAccess(configuration);\n      replay(configuration);\n\n      initAdminAccess.visit(Statements.exec(\"echo hello\"));\n\n      initAdminAccess.visit(Statements.newStatementList(Statements.exec(\"echo hello\")));\n      verify(configuration);\n\n   }\n\n   public void testWhenAdminAccess() {\n      AdminAccess.Configuration configuration = createMock(AdminAccess.Configuration.class);\n      AdminAccess statement = createMock(AdminAccess.class);\n      AdminAccess newStatement = createMock(AdminAccess.class);\n\n      expect(statement.init(configuration)).andReturn(newStatement);\n\n      replay(configuration);\n      replay(statement);\n      replay(newStatement);\n      InitAdminAccess initAdminAccess = new InitAdminAccess(configuration);\n\n      initAdminAccess.visit(statement);\n\n      verify(configuration);\n      verify(statement);\n      verify(newStatement);\n   }\n\n   public void testWhenAdminAccessInsideList() {\n      AdminAccess.Configuration configuration = createMock(AdminAccess.Configuration.class);\n      AdminAccess statement = createMock(AdminAccess.class);\n      AdminAccess newStatement = createMock(AdminAccess.class);\n\n      expect(statement.init(configuration)).andReturn(newStatement);\n\n      replay(configuration);\n      replay(statement);\n      replay(newStatement);\n      InitAdminAccess initAdminAccess = new InitAdminAccess(configuration);\n\n      initAdminAccess.visit(Statements.newStatementList(statement));\n\n      verify(configuration);\n      verify(statement);\n      verify(newStatement);\n   }\n   \n\n   public void testWhenAdminAccessInsideInitBuilder() {\n      AdminAccess.Configuration configuration = createMock(AdminAccess.Configuration.class);\n      AdminAccess statement = createMock(AdminAccess.class);\n      AdminAccess newStatement = createMock(AdminAccess.class);\n\n      expect(statement.init(configuration)).andReturn(newStatement);\n\n      replay(configuration);\n      replay(statement);\n      replay(newStatement);\n\n      InitScript testInitBuilder = InitScript.builder().name(\"mkebsboot\").home(\"/mnt/tmp\")\n            .exportVariables(ImmutableMap.of(\"tmpDir\", \"/mnt/tmp\")).run(statement).build();\n      \n      InitAdminAccess initAdminAccess = new InitAdminAccess(configuration);\n\n      initAdminAccess.visit(testInitBuilder);\n\n      verify(configuration);\n      verify(statement);\n      verify(newStatement);\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/test/java/org/jclouds/scriptbuilder/statements/chef/ChefSoloTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.statements.chef;\n\nimport static org.jclouds.scriptbuilder.domain.Statements.createOrOverwriteFile;\nimport static org.jclouds.scriptbuilder.domain.Statements.exec;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertTrue;\n\nimport java.io.IOException;\n\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.jclouds.scriptbuilder.domain.Statement;\nimport org.jclouds.scriptbuilder.domain.chef.DataBag;\nimport org.jclouds.scriptbuilder.domain.chef.Role;\nimport org.jclouds.scriptbuilder.domain.chef.RunList;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * Unit tests for the {@link ChefSoloTest} statement.\n */\n@Test(groups = \"unit\", testName = \"ChefSoloTest\")\npublic class ChefSoloTest {\n\n   public void testCreateDefaultSoloConfiguration() {\n      ImmutableList.Builder<Statement> statements = ImmutableList.builder();\n      ChefSolo solo = ChefSolo.builder().build();\n\n      solo.createSoloConfiguration(statements);\n      ImmutableList<Statement> statementList = statements.build();\n\n      assertEquals(statementList.size(), 3);\n      assertEquals(statementList.get(0), exec(\"{md} \" + ChefSolo.DEFAULT_SOLO_PATH));\n      assertEquals(statementList.get(1), exec(\"{md} \" + ChefSolo.DEFAULT_SOLO_PATH + \"/cookbooks\"));\n\n      Statement expected = createOrOverwriteFile(\n            ChefSolo.DEFAULT_SOLO_PATH + \"/solo.rb\",\n            ImmutableSet.of(\"file_cache_path \\\"\" + ChefSolo.DEFAULT_SOLO_PATH + \"\\\"\", //\n                  \"cookbook_path [\\\"\" + ChefSolo.DEFAULT_SOLO_PATH + \"/cookbooks\\\"]\", \"role_path \\\"\"\n                        + ChefSolo.DEFAULT_SOLO_PATH + \"/roles\\\"\", \"data_bag_path \\\"\" + ChefSolo.DEFAULT_SOLO_PATH\n                        + \"/data_bags\\\"\"));\n\n      assertEquals(statementList.get(2).render(OsFamily.UNIX), expected.render(OsFamily.UNIX));\n   }\n\n   public void testCreateCustomSoloConfiguration() {\n      ImmutableList.Builder<Statement> statements = ImmutableList.builder();\n      ChefSolo solo = ChefSolo.builder().fileCachePath(\"/tmp\").cookbookPath(\"/tmp/foo\").cookbookPath(\"/tmp/bar\")\n            .rolePath(\"/tmp/roles\").dataBagPath(\"/tmp/databags\").build();\n\n      solo.createSoloConfiguration(statements);\n      ImmutableList<Statement> statementList = statements.build();\n\n      assertEquals(statementList.size(), 4);\n      assertEquals(statementList.get(0), exec(\"{md} /tmp\"));\n      assertEquals(statementList.get(1), exec(\"{md} /tmp/foo\"));\n      assertEquals(statementList.get(2), exec(\"{md} /tmp/bar\"));\n\n      Statement expected = createOrOverwriteFile(\"/tmp/solo.rb\", ImmutableSet.of(\"file_cache_path \\\"/tmp\\\"\", //\n            \"cookbook_path [\\\"/tmp/foo\\\",\\\"/tmp/bar\\\"]\", \"role_path \\\"/tmp/roles\\\"\", \"data_bag_path \\\"/tmp/databags\\\"\"));\n\n      assertEquals(statementList.get(3).render(OsFamily.UNIX), expected.render(OsFamily.UNIX));\n   }\n\n   public void testCreateDefaultNodeConfiguration() {\n      ImmutableList.Builder<Statement> statements = ImmutableList.builder();\n      ChefSolo solo = ChefSolo.builder().build();\n\n      solo.createNodeConfiguration(statements);\n      ImmutableList<Statement> statementList = statements.build();\n\n      Statement expected = createOrOverwriteFile(ChefSolo.DEFAULT_SOLO_PATH + \"/node.json\",\n            ImmutableSet.of(\"{\\\"run_list\\\":[]}\"));\n\n      assertEquals(statementList.size(), 1);\n      assertEquals(statementList.get(0).render(OsFamily.UNIX), expected.render(OsFamily.UNIX));\n   }\n\n   public void testCreateNodeConfigurationWithJsonAttributes() {\n      ImmutableList.Builder<Statement> statements = ImmutableList.builder();\n      ChefSolo solo = ChefSolo.builder().jsonAttributes(\"{\\\"foo\\\":\\\"bar\\\"}\").build();\n\n      solo.createNodeConfiguration(statements);\n      ImmutableList<Statement> statementList = statements.build();\n\n      Statement expected = createOrOverwriteFile(ChefSolo.DEFAULT_SOLO_PATH + \"/node.json\",\n            ImmutableSet.of(\"{\\\"foo\\\":\\\"bar\\\",\\\"run_list\\\":[]}\"));\n\n      assertEquals(statementList.size(), 1);\n      assertEquals(statementList.get(0).render(OsFamily.UNIX), expected.render(OsFamily.UNIX));\n   }\n\n   public void testCreateNodeConfigurationWithRunList() {\n      ImmutableList.Builder<Statement> statements = ImmutableList.builder();\n      RunList runlist = RunList.builder().recipe(\"foo\").role(\"bar\").build();\n      ChefSolo solo = ChefSolo.builder().runlist(runlist).build();\n\n      solo.createNodeConfiguration(statements);\n      ImmutableList<Statement> statementList = statements.build();\n\n      Statement expected = createOrOverwriteFile(ChefSolo.DEFAULT_SOLO_PATH + \"/node.json\",\n            ImmutableSet.of(\"{\\\"run_list\\\":[\\\"recipe[foo]\\\",\\\"role[bar]\\\"]}\"));\n\n      assertEquals(statementList.size(), 1);\n      assertEquals(statementList.get(0).render(OsFamily.UNIX), expected.render(OsFamily.UNIX));\n   }\n\n   public void testCreateNodeConfigurationWithJsonAttributesAndRunList() {\n      ImmutableList.Builder<Statement> statements = ImmutableList.builder();\n      RunList runlist = RunList.builder().recipe(\"foo\").role(\"bar\").build();\n      ChefSolo solo = ChefSolo.builder().jsonAttributes(\"{\\\"foo\\\":\\\"bar\\\"}\").runlist(runlist).build();\n\n      solo.createNodeConfiguration(statements);\n      ImmutableList<Statement> statementList = statements.build();\n\n      Statement expected = createOrOverwriteFile(ChefSolo.DEFAULT_SOLO_PATH + \"/node.json\",\n            ImmutableSet.of(\"{\\\"foo\\\":\\\"bar\\\",\\\"run_list\\\":[\\\"recipe[foo]\\\",\\\"role[bar]\\\"]}\"));\n\n      assertEquals(statementList.size(), 1);\n      assertEquals(statementList.get(0).render(OsFamily.UNIX), expected.render(OsFamily.UNIX));\n   }\n\n   public void testCreateRolesIfNecessaryWithDefaultValues() {\n      ImmutableList.Builder<Statement> statements = ImmutableList.builder();\n      ChefSolo solo = ChefSolo.builder().build();\n\n      solo.createRolesIfNecessary(statements);\n      ImmutableList<Statement> statementList = statements.build();\n\n      assertTrue(statementList.isEmpty());\n   }\n\n   public void testCreateRolesIfNecessaryWithOneRole() {\n      ImmutableList.Builder<Statement> statements = ImmutableList.builder();\n      RunList runlist = RunList.builder().recipe(\"bar\").build();\n      Role role = Role.builder().name(\"foo\").runlist(runlist).build();\n      ChefSolo solo = ChefSolo.builder().defineRole(role).build();\n\n      solo.createRolesIfNecessary(statements);\n      ImmutableList<Statement> statementList = statements.build();\n\n      Statement expected = createOrOverwriteFile(ChefSolo.DEFAULT_SOLO_PATH + \"/roles/\" + role.getName() + \".json\",\n            ImmutableSet.of(role.toJsonString()));\n\n      assertEquals(statementList.size(), 2);\n      assertEquals(statementList.get(0), exec(\"{md} \" + ChefSolo.DEFAULT_SOLO_PATH + \"/roles\"));\n      assertEquals(statementList.get(1).render(OsFamily.UNIX), expected.render(OsFamily.UNIX));\n   }\n\n   public void testCreateRolesIfNecessaryWithOneRoleAndCustomPath() {\n      ImmutableList.Builder<Statement> statements = ImmutableList.builder();\n      RunList runlist = RunList.builder().recipe(\"bar\").build();\n      Role role = Role.builder().name(\"foo\").runlist(runlist).build();\n      ChefSolo solo = ChefSolo.builder().rolePath(\"/tmp/roles\").defineRole(role).build();\n\n      solo.createRolesIfNecessary(statements);\n      ImmutableList<Statement> statementList = statements.build();\n\n      Statement expected = createOrOverwriteFile(\"/tmp/roles/\" + role.getName() + \".json\",\n            ImmutableSet.of(role.toJsonString()));\n\n      assertEquals(statementList.size(), 2);\n      assertEquals(statementList.get(0), exec(\"{md} /tmp/roles\"));\n      assertEquals(statementList.get(1).render(OsFamily.UNIX), expected.render(OsFamily.UNIX));\n   }\n\n   public void testCreateRolesIfNecessaryWithMultipleRoleAndCustomPath() {\n      ImmutableList.Builder<Statement> statements = ImmutableList.builder();\n      Role roleFoo = Role.builder().name(\"foo\").runlist(RunList.builder().recipe(\"foo\").build()).build();\n      Role roleBar = Role.builder().name(\"bar\").runlist(RunList.builder().recipe(\"bar\").build()).build();\n      ChefSolo solo = ChefSolo.builder().rolePath(\"/tmp/roles\").defineRole(roleFoo).defineRole(roleBar).build();\n\n      solo.createRolesIfNecessary(statements);\n      ImmutableList<Statement> statementList = statements.build();\n\n      Statement expectedFoo = createOrOverwriteFile(\"/tmp/roles/\" + roleFoo.getName() + \".json\",\n            ImmutableSet.of(roleFoo.toJsonString()));\n      Statement expectedBar = createOrOverwriteFile(\"/tmp/roles/\" + roleBar.getName() + \".json\",\n            ImmutableSet.of(roleBar.toJsonString()));\n\n      assertEquals(statementList.size(), 3);\n      assertEquals(statementList.get(0), exec(\"{md} /tmp/roles\"));\n      assertEquals(statementList.get(1).render(OsFamily.UNIX), expectedFoo.render(OsFamily.UNIX));\n      assertEquals(statementList.get(2).render(OsFamily.UNIX), expectedBar.render(OsFamily.UNIX));\n   }\n\n   public void testCreateDatabagsIfNecessaryWithDefaultValues() {\n      ImmutableList.Builder<Statement> statements = ImmutableList.builder();\n      ChefSolo solo = ChefSolo.builder().build();\n\n      solo.createDatabagsIfNecessary(statements);\n      ImmutableList<Statement> statementList = statements.build();\n\n      assertTrue(statementList.isEmpty());\n   }\n\n   public void testCreateDatabagsIfNecessaryWithOneDatabag() {\n      ImmutableList.Builder<Statement> statements = ImmutableList.builder();\n      DataBag databag = DataBag.builder().name(\"foo\").item(\"item\", \"{\\\"foo\\\":\\\"bar\\\"}\").build();\n      ChefSolo solo = ChefSolo.builder().defineDataBag(databag).build();\n\n      solo.createDatabagsIfNecessary(statements);\n      ImmutableList<Statement> statementList = statements.build();\n\n      Statement expected = createOrOverwriteFile(ChefSolo.DEFAULT_SOLO_PATH + \"/data_bags/foo/item.json\",\n            ImmutableSet.of(\"{\\\"foo\\\":\\\"bar\\\"}\"));\n\n      assertEquals(statementList.size(), 3);\n      assertEquals(statementList.get(0), exec(\"{md} \" + ChefSolo.DEFAULT_SOLO_PATH + \"/data_bags\"));\n      assertEquals(statementList.get(1), exec(\"{md} \" + ChefSolo.DEFAULT_SOLO_PATH + \"/data_bags/\" + databag.getName()));\n      assertEquals(statementList.get(2).render(OsFamily.UNIX), expected.render(OsFamily.UNIX));\n   }\n\n   public void testCreateDatabagsIfNecessaryWithOneDatabagAndCustomPath() {\n      ImmutableList.Builder<Statement> statements = ImmutableList.builder();\n      DataBag databag = DataBag.builder().name(\"foo\").item(\"item\", \"{\\\"foo\\\":\\\"bar\\\"}\").build();\n      ChefSolo solo = ChefSolo.builder().dataBagPath(\"/tmp/databags\").defineDataBag(databag).build();\n\n      solo.createDatabagsIfNecessary(statements);\n      ImmutableList<Statement> statementList = statements.build();\n\n      Statement expected = createOrOverwriteFile(\"/tmp/databags/foo/item.json\", ImmutableSet.of(\"{\\\"foo\\\":\\\"bar\\\"}\"));\n\n      assertEquals(statementList.size(), 3);\n      assertEquals(statementList.get(0), exec(\"{md} /tmp/databags\"));\n      assertEquals(statementList.get(1), exec(\"{md} /tmp/databags/\" + databag.getName()));\n      assertEquals(statementList.get(2).render(OsFamily.UNIX), expected.render(OsFamily.UNIX));\n   }\n\n   public void testCreateDatabagsIfNecessaryWithOneDatabagWithMultipleItemsAndCustomPath() {\n      ImmutableList.Builder<Statement> statements = ImmutableList.builder();\n      DataBag databag = DataBag.builder().name(\"foo\").item(\"item1\", \"{\\\"foo\\\":\\\"bar\\\"}\")\n            .item(\"item2\", \"{\\\"bar\\\":\\\"foo\\\"}\").build();\n      ChefSolo solo = ChefSolo.builder().dataBagPath(\"/tmp/databags\").defineDataBag(databag).build();\n\n      solo.createDatabagsIfNecessary(statements);\n      ImmutableList<Statement> statementList = statements.build();\n\n      Statement expectedItem1 = createOrOverwriteFile(\"/tmp/databags/foo/item1.json\",\n            ImmutableSet.of(\"{\\\"foo\\\":\\\"bar\\\"}\"));\n      Statement expectedItem2 = createOrOverwriteFile(\"/tmp/databags/foo/item2.json\",\n            ImmutableSet.of(\"{\\\"bar\\\":\\\"foo\\\"}\"));\n\n      assertEquals(statementList.size(), 4);\n      assertEquals(statementList.get(0), exec(\"{md} /tmp/databags\"));\n      assertEquals(statementList.get(1), exec(\"{md} /tmp/databags/\" + databag.getName()));\n      assertEquals(statementList.get(2).render(OsFamily.UNIX), expectedItem1.render(OsFamily.UNIX));\n      assertEquals(statementList.get(3).render(OsFamily.UNIX), expectedItem2.render(OsFamily.UNIX));\n   }\n\n   public void testCreateDatabagsIfNecessaryWithMultipleDatabagsAndCustomPath() {\n      ImmutableList.Builder<Statement> statements = ImmutableList.builder();\n      DataBag databagFoo = DataBag.builder().name(\"foo\").item(\"itemFoo\", \"{\\\"foo\\\":\\\"bar\\\"}\").build();\n      DataBag databagBar = DataBag.builder().name(\"bar\").item(\"itemBar\", \"{\\\"bar\\\":\\\"foo\\\"}\").build();\n      ChefSolo solo = ChefSolo.builder().dataBagPath(\"/tmp/databags\").defineDataBag(databagFoo)\n            .defineDataBag(databagBar).build();\n\n      solo.createDatabagsIfNecessary(statements);\n      ImmutableList<Statement> statementList = statements.build();\n\n      Statement expectedFoo = createOrOverwriteFile(\"/tmp/databags/foo/itemFoo.json\",\n            ImmutableSet.of(\"{\\\"foo\\\":\\\"bar\\\"}\"));\n      Statement expectedBar = createOrOverwriteFile(\"/tmp/databags/bar/itemBar.json\",\n            ImmutableSet.of(\"{\\\"bar\\\":\\\"foo\\\"}\"));\n\n      assertEquals(statementList.size(), 5);\n      assertEquals(statementList.get(0), exec(\"{md} /tmp/databags\"));\n      assertEquals(statementList.get(1), exec(\"{md} /tmp/databags/\" + databagFoo.getName()));\n      assertEquals(statementList.get(2).render(OsFamily.UNIX), expectedFoo.render(OsFamily.UNIX));\n      assertEquals(statementList.get(3), exec(\"{md} /tmp/databags/\" + databagBar.getName()));\n      assertEquals(statementList.get(4).render(OsFamily.UNIX), expectedBar.render(OsFamily.UNIX));\n   }\n\n   public void testCreateDatabagsIfNecessaryWithMultipleDatabagsAndMultipleItemsAndCustomPath() {\n      ImmutableList.Builder<Statement> statements = ImmutableList.builder();\n      DataBag databagFoo = DataBag.builder().name(\"foo\").item(\"itemFoo\", \"{\\\"foo\\\":\\\"bar\\\"}\").build();\n      DataBag databagBar = DataBag.builder().name(\"bar\").item(\"itemBar\", \"{\\\"bar\\\":\\\"foo\\\"}\")\n            .item(\"extra\", \"{\\\"extra\\\":[]}\").build();\n      ChefSolo solo = ChefSolo.builder().dataBagPath(\"/tmp/databags\").defineDataBag(databagFoo)\n            .defineDataBag(databagBar).build();\n\n      solo.createDatabagsIfNecessary(statements);\n      ImmutableList<Statement> statementList = statements.build();\n\n      Statement expectedFoo = createOrOverwriteFile(\"/tmp/databags/foo/itemFoo.json\",\n            ImmutableSet.of(\"{\\\"foo\\\":\\\"bar\\\"}\"));\n      Statement expectedBar = createOrOverwriteFile(\"/tmp/databags/bar/itemBar.json\",\n            ImmutableSet.of(\"{\\\"bar\\\":\\\"foo\\\"}\"));\n      Statement expectedExtra = createOrOverwriteFile(\"/tmp/databags/bar/extra.json\", ImmutableSet.of(\"{\\\"extra\\\":[]}\"));\n\n      assertEquals(statementList.size(), 6);\n      assertEquals(statementList.get(0), exec(\"{md} /tmp/databags\"));\n      assertEquals(statementList.get(1), exec(\"{md} /tmp/databags/\" + databagFoo.getName()));\n      assertEquals(statementList.get(2).render(OsFamily.UNIX), expectedFoo.render(OsFamily.UNIX));\n      assertEquals(statementList.get(3), exec(\"{md} /tmp/databags/\" + databagBar.getName()));\n      assertEquals(statementList.get(4).render(OsFamily.UNIX), expectedBar.render(OsFamily.UNIX));\n      assertEquals(statementList.get(5).render(OsFamily.UNIX), expectedExtra.render(OsFamily.UNIX));\n   }\n\n   @Test(expectedExceptions = UnsupportedOperationException.class, expectedExceptionsMessageRegExp = \"windows not yet implemented\")\n   public void testChefSoloInWindows() {\n      ChefSolo.builder().cookbooksArchiveLocation(\"/tmp/cookbooks\").build().render(OsFamily.WINDOWS);\n   }\n\n   public void testChefWoloWithDefaultConfiguration() throws IOException {\n      String script = ChefSolo.builder().build().render(OsFamily.UNIX);\n      assertEquals(script, checkSoloExists() + createConfigFile() + createNodeFile()\n            + \"chef-solo -c /var/chef/solo.rb -j /var/chef/node.json -N `hostname`\\n\");\n   }\n\n   public void testChefWoloWithNodeName() throws IOException {\n      String script = ChefSolo.builder().nodeName(\"foo\").build().render(OsFamily.UNIX);\n      assertEquals(script, checkSoloExists() + createConfigFile() + createNodeFile()\n            + \"chef-solo -c /var/chef/solo.rb -j /var/chef/node.json -N foo\\n\");\n   }\n\n   public void testChefSoloWithGroup() throws IOException {\n      String script = ChefSolo.builder().group(\"foo\").build().render(OsFamily.UNIX);\n      assertEquals(script, checkSoloExists() + createConfigFile() + createNodeFile()\n            + \"chef-solo -c /var/chef/solo.rb -j /var/chef/node.json -N `hostname` -g foo\\n\");\n   }\n\n   public void testChefSoloWithInterval() throws IOException {\n      String script = ChefSolo.builder().interval(15).build().render(OsFamily.UNIX);\n      assertEquals(script, checkSoloExists() + createConfigFile() + createNodeFile()\n            + \"chef-solo -c /var/chef/solo.rb -j /var/chef/node.json -N `hostname` -i 15\\n\");\n   }\n\n   public void testChefSoloWithLogLevel() throws IOException {\n      String script = ChefSolo.builder().logLevel(\"debug\").build().render(OsFamily.UNIX);\n      assertEquals(script, checkSoloExists() + createConfigFile() + createNodeFile()\n            + \"chef-solo -c /var/chef/solo.rb -j /var/chef/node.json -N `hostname` -l debug\\n\");\n   }\n\n   public void testChefSoloWithLogFile() throws IOException {\n      String script = ChefSolo.builder().logFile(\"/var/log/solo.log\").build().render(OsFamily.UNIX);\n      assertEquals(script, checkSoloExists() + createConfigFile() + createNodeFile()\n            + \"chef-solo -c /var/chef/solo.rb -j /var/chef/node.json -N `hostname` -L /var/log/solo.log\\n\");\n   }\n\n   public void testChefSoloWithCookbooksLocation() throws IOException {\n      String script = ChefSolo.builder().cookbooksArchiveLocation(\"/tmp/cookbooks\").build().render(OsFamily.UNIX);\n      assertEquals(script, checkSoloExists() + createConfigFile() + createNodeFile()\n            + \"chef-solo -c /var/chef/solo.rb -j /var/chef/node.json -N `hostname` -r /tmp/cookbooks\\n\");\n   }\n\n   public void testChefSoloWithSplay() throws IOException {\n      String script = ChefSolo.builder().splay(15).build().render(OsFamily.UNIX);\n      assertEquals(script, checkSoloExists() + createConfigFile() + createNodeFile()\n            + \"chef-solo -c /var/chef/solo.rb -j /var/chef/node.json -N `hostname` -s 15\\n\");\n   }\n\n   public void testChefSoloWithUser() throws IOException {\n      String script = ChefSolo.builder().user(\"foo\").build().render(OsFamily.UNIX);\n      assertEquals(script, checkSoloExists() + createConfigFile() + createNodeFile()\n            + \"chef-solo -c /var/chef/solo.rb -j /var/chef/node.json -N `hostname` -u foo\\n\");\n   }\n\n   private static String createConfigFile() {\n      return \"mkdir -p /var/chef\\nmkdir -p /var/chef/cookbooks\\ncat > /var/chef/solo.rb <<-'END_OF_JCLOUDS_FILE'\\n\"\n            + \"\\tfile_cache_path \\\"/var/chef\\\"\\n\\tcookbook_path [\\\"/var/chef/cookbooks\\\"]\\n\"\n            + \"\\trole_path \\\"/var/chef/roles\\\"\\n\\tdata_bag_path \\\"/var/chef/data_bags\\\"\\nEND_OF_JCLOUDS_FILE\\n\";\n   }\n\n   private static String createNodeFile() {\n      return \"cat > /var/chef/node.json <<-'END_OF_JCLOUDS_FILE'\\n\\t{\\\"run_list\\\":[]}\\nEND_OF_JCLOUDS_FILE\\n\";\n   }\n\n   private static String checkSoloExists() {\n      return \"if ! hash chef-solo 2>/dev/null; then\\necho 'chef-solo not found. Please, install Chef first'\\nexit 1\\nfi\\n\";\n   }\n\n}\n"
  },
  {
    "path": "scriptbuilder/src/test/java/org/jclouds/scriptbuilder/statements/chef/InstallChefGemsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.statements.chef;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\n\nimport org.jclouds.scriptbuilder.InitScript;\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.jclouds.scriptbuilder.domain.ShellToken;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.io.Resources;\n\n/**\n * Unit tests for the {@link InstallChefGems} statement.\n */\n@Test(groups = \"unit\", testName = \"InstallChefGemsTest\")\npublic class InstallChefGemsTest {\n\n   @Test(expectedExceptions = UnsupportedOperationException.class, expectedExceptionsMessageRegExp = \"windows not yet implemented\")\n   public void installChefGemsInWindows() {\n      InstallChefGems.builder().build().render(OsFamily.WINDOWS);\n   }\n\n   public void installChefGemsUnix() throws IOException {\n      assertEquals(InstallChefGems.builder().build().render(OsFamily.UNIX), \"gem install chef --no-rdoc --no-ri\\n\");\n   }\n\n   public void installChefGemsUnixWithCustomVersion() throws IOException {\n      assertEquals(InstallChefGems.builder().version(\">= 0.10.8\").build().render(OsFamily.UNIX),\n            \"gem install chef -v '>= 0.10.8' --no-rdoc --no-ri\\n\");\n   }\n\n   public void installChefGemsUnixInScriptBuilder() throws IOException {\n      assertEquals(InitScript.builder().name(\"install_chef_gems\").run(InstallChefGems.builder().build()).build()\n            .render(OsFamily.UNIX), Resources.toString(\n            Resources.getResource(\"test_install_chef_gems_scriptbuilder.\" + ShellToken.SH.to(OsFamily.UNIX)),\n            Charsets.UTF_8));\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/test/java/org/jclouds/scriptbuilder/statements/chef/InstallChefUsingOmnibusTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.statements.chef;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\n\nimport org.jclouds.scriptbuilder.InitScript;\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.jclouds.scriptbuilder.domain.ShellToken;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.io.Resources;\n\n/**\n * Unit tests for the {@link InstallChefUsingOmnibus} statement.\n */\n@Test(groups = \"unit\", testName = \"InstallChefClientUsingOmnibusTest\")\npublic class InstallChefUsingOmnibusTest {\n\n   @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = \"windows not supported\")\n   public void installChefUsingOmnibusInWindows() {\n      new InstallChefUsingOmnibus().render(OsFamily.WINDOWS);\n   }\n\n   public void installChefUsingOmnibusInUnix() throws IOException {\n      assertEquals(new InstallChefUsingOmnibus().render(OsFamily.UNIX), \"setupPublicCurl || return 1\\n\"\n            + \"curl -q -s -S -L --connect-timeout 10 --max-time 600 --retry 20 \"\n            + \"-X GET  https://www.opscode.com/chef/install.sh |(bash)\\n\");\n   }\n\n   public void installChefUsingOmnibusInUnixInScriptBuilder() throws IOException {\n      assertEquals(InitScript.builder().name(\"install_chef_omnibus\").run(new InstallChefUsingOmnibus()).build()\n            .render(OsFamily.UNIX), Resources.toString(\n            Resources.getResource(\"test_install_chef_omnibus_scriptbuilder.\" + ShellToken.SH.to(OsFamily.UNIX)),\n            Charsets.UTF_8));\n   }\n\n   public void installChefWithVersionUsingOmnibusInUnix() throws IOException {\n      assertEquals(new InstallChefUsingOmnibus(\"11.16.4\").render(OsFamily.UNIX), \"setupPublicCurl || return 1\\n\"\n            + \"(mkdir -p /tmp && cd /tmp && [ ! -f install-chef.sh ] && \"\n            + \"curl -q -s -S -L --connect-timeout 10 --max-time 600 --retry 20 -C - -X GET  https://www.opscode.com/chef/install.sh >install-chef.sh)\\n\"\n            + \"sh /tmp/install-chef.sh -v 11.16.4\\n\");\n   }\n\n   public void installChefWithVersionUsingOmnibusInUnixInScriptBuilder() throws IOException {\n      assertEquals(InitScript.builder().name(\"install_chef_omnibus\").run(new InstallChefUsingOmnibus(\"11.16.4\")).build()\n            .render(OsFamily.UNIX), Resources.toString(\n            Resources.getResource(\"test_install_chef_version_omnibus_scriptbuilder.\" + ShellToken.SH.to(OsFamily.UNIX)),\n            Charsets.UTF_8));\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/test/java/org/jclouds/scriptbuilder/statements/git/CloneGitRepoTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.statements.git;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"CloneGitRepoTest\")\npublic class CloneGitRepoTest {\n\n   public void testUNIX() {\n      assertEquals(CloneGitRepo.builder().repository(\"https://github.com/joyent/node.git\").build()\n               .render(OsFamily.UNIX), \"git clone https://github.com/joyent/node.git\\ncd node\\n\");\n   }\n\n   public void testWithBranchUNIX() {\n      assertEquals(CloneGitRepo.builder().repository(\"https://github.com/joyent/node.git\").branch(\"v0.6\").build()\n               .render(OsFamily.UNIX), \"git clone -b v0.6 https://github.com/joyent/node.git\\ncd node\\n\");\n\n   }\n\n   public void testWithBranchAndTagUNIX() {\n      assertEquals(CloneGitRepo.builder().repository(\"https://github.com/joyent/node.git\").branch(\"v0.6\")\n               .tag(\"v0.6.10\").build().render(OsFamily.UNIX),\n               \"git clone -b v0.6 https://github.com/joyent/node.git\\ncd node\\ngit checkout v0.6.10\\n\");\n   }\n\n   public void testWithDirectoryUNIX() {\n      assertEquals(CloneGitRepo.builder().repository(\"https://github.com/joyent/node.git\").directory(\"/tmp/node-local\")\n               .build().render(OsFamily.UNIX),\n               \"git clone https://github.com/joyent/node.git /tmp/node-local\\ncd /tmp/node-local\\n\");\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/test/java/org/jclouds/scriptbuilder/statements/git/InstallGitTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.statements.git;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\n\nimport org.jclouds.scriptbuilder.InitScript;\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.jclouds.scriptbuilder.domain.ShellToken;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.io.Resources;\n\n@Test(groups = \"unit\", testName = \"InstallGitTest\")\npublic class InstallGitTest {\n\n   public void testInstallGitUNIX() throws IOException {\n      assertEquals(new InstallGit().render(OsFamily.UNIX), \"setupPublicCurl || return 1\\ninstallGit || return 1\\n\");\n   }\n\n   public void testInstallGitUNIXInScriptBuilderSourcesSetupPublicCurl() throws IOException {\n      assertEquals(InitScript.builder().name(\"install_git\").run(new InstallGit()).build().render(OsFamily.UNIX),\n               Resources.toString(Resources.getResource(\"test_install_git_scriptbuilder.\" + ShellToken.SH.to(OsFamily.UNIX)), Charsets.UTF_8));\n   }\n\n}\n"
  },
  {
    "path": "scriptbuilder/src/test/java/org/jclouds/scriptbuilder/statements/java/InstallJDKTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.statements.java;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\nimport java.net.URI;\n\nimport org.jclouds.scriptbuilder.InitScript;\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.jclouds.scriptbuilder.domain.ShellToken;\nimport org.jclouds.scriptbuilder.domain.Statement;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.io.Resources;\n\n@Test(groups = \"unit\", testName = \"InstallJDKTest\")\npublic class InstallJDKTest {\n\n   Statement installJDK = InstallJDK.fromOpenJDK();\n\n   public void testInstallJDKUNIX() throws IOException {\n      assertEquals(InstallJDK.fromOpenJDK().render(OsFamily.UNIX), \"setupPublicCurl || return 1\\ninstallOpenJDK || return 1\\n\");\n   }\n\n   public void testInstallJDKUNIXInScriptBuilderSourcesSetupPublicCurl() throws IOException {\n      assertEquals(InitScript.builder().name(\"install_jdk\").run(InstallJDK.fromOpenJDK()).build().render(OsFamily.UNIX),\n            Resources.toString(Resources.getResource(\"test_install_jdk_scriptbuilder.\" + ShellToken.SH.to(OsFamily.UNIX)), Charsets.UTF_8));\n   }\n\n   public void testInstallJDKUNIXWithURL() throws IOException {\n      assertEquals(InstallJDK.fromURL(URI.create(\"http://foo\")).render(OsFamily.UNIX),\n            \"setupPublicCurl || return 1\\ninstallJDKFromURL http://foo || return 1\\n\");\n   }\n\n}\n"
  },
  {
    "path": "scriptbuilder/src/test/java/org/jclouds/scriptbuilder/statements/login/AdminAccessBuilderSpecTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.statements.login;\n\nimport static java.lang.String.format;\nimport static org.jclouds.scriptbuilder.statements.login.AdminAccessBuilderSpec.parse;\nimport static org.testng.Assert.assertEquals;\nimport static org.testng.Assert.assertNull;\nimport static org.testng.Assert.fail;\n\nimport java.io.File;\nimport java.lang.reflect.Field;\n\nimport jakarta.inject.Provider;\n\nimport org.jclouds.json.Json;\nimport org.jclouds.json.config.GsonModule;\nimport org.jclouds.scriptbuilder.statements.login.AdminAccess.Builder;\nimport org.testng.annotations.Test;\n\nimport com.google.inject.Guice;\n\n/**\n * \n * <p/>\n * inspired by guava {@code CacheBuilderSpecTest}\n */\n@Test(testName = \"AdminAccessBuilderSpecTest\")\npublic class AdminAccessBuilderSpecTest {\n\n   Provider<AdminAccess.Builder> adminAccessBuilders = new Provider<AdminAccess.Builder>() {\n\n      @Override\n      public Builder get() {\n         return new AdminAccess.Builder();\n      }\n\n   };\n\n   public void testParseEmpty() {\n      AdminAccessBuilderSpec spec = parse(\"\");\n      assertNull(spec.adminHome);\n      assertNull(spec.adminPassword);\n      assertNull(spec.adminPrivateKeyFile);\n      assertNull(spec.adminPublicKeyFile);\n      assertNull(spec.adminUsername);\n      assertNull(spec.authorizeAdminPublicKey);\n      assertNull(spec.grantSudoToAdminUser);\n      assertNull(spec.installAdminPrivateKey);\n      assertNull(spec.lockSsh);\n      assertNull(spec.loginPassword);\n      assertNull(spec.resetLoginPassword);\n      assertAdminAccessBuilderEquivalence(adminAccessBuilders.get(), adminAccessBuilders.get().from(spec));\n   }\n\n   public void testParseAdminUsername() {\n      AdminAccessBuilderSpec spec = parse(\"adminUsername=superUser\");\n      assertEquals(spec.adminUsername, \"superUser\");\n      assertNull(spec.adminHome);\n      assertNull(spec.adminPassword);\n      assertNull(spec.adminPrivateKeyFile);\n      assertNull(spec.adminPublicKeyFile);\n      assertNull(spec.authorizeAdminPublicKey);\n      assertNull(spec.grantSudoToAdminUser);\n      assertNull(spec.installAdminPrivateKey);\n      assertNull(spec.lockSsh);\n      assertNull(spec.loginPassword);\n      assertNull(spec.resetLoginPassword);\n      assertAdminAccessBuilderEquivalence(adminAccessBuilders.get().adminUsername(\"superUser\"), adminAccessBuilders\n               .get().from(spec));\n   }\n\n   public void testParseAdminHome() {\n      AdminAccessBuilderSpec spec = parse(\"adminHome=/home/superUser\");\n      assertEquals(spec.getAdminHome(), \"/home/superUser\");\n      assertNull(spec.adminUsername);\n      assertNull(spec.adminPassword);\n      assertNull(spec.adminPrivateKeyFile);\n      assertNull(spec.adminPublicKeyFile);\n      assertNull(spec.authorizeAdminPublicKey);\n      assertNull(spec.grantSudoToAdminUser);\n      assertNull(spec.installAdminPrivateKey);\n      assertNull(spec.lockSsh);\n      assertNull(spec.loginPassword);\n      assertNull(spec.resetLoginPassword);\n      assertAdminAccessBuilderEquivalence(adminAccessBuilders.get().adminHome(\"/home/superUser\"), adminAccessBuilders\n               .get().from(spec));\n   }\n\n   public void testParsePrivateKeyFile() {\n      AdminAccessBuilderSpec spec = parse(\"adminPrivateKeyFile=target/test-classes/test\");\n      assertEquals(spec.getAdminPrivateKeyFile().getPath(), format(\"target%stest-classes%stest\", File.separator, File.separator));\n      assertNull(spec.adminHome);\n      assertNull(spec.adminPassword);\n      assertNull(spec.adminPublicKeyFile);\n      assertNull(spec.authorizeAdminPublicKey);\n      assertNull(spec.grantSudoToAdminUser);\n      assertNull(spec.installAdminPrivateKey);\n      assertNull(spec.lockSsh);\n      assertNull(spec.loginPassword);\n      assertNull(spec.resetLoginPassword);\n      assertAdminAccessBuilderEquivalence(adminAccessBuilders.get().adminHome(\"/home/superUser\"), adminAccessBuilders\n               .get().from(spec));\n   }\n\n   public void testParseLockSSh() {\n      AdminAccessBuilderSpec spec = parse(\"lockSsh=true\");\n      assertEquals(spec.getLockSsh(), Boolean.TRUE);\n      assertNull(spec.adminUsername);\n      assertNull(spec.adminHome);\n      assertNull(spec.adminPassword);\n      assertNull(spec.adminPrivateKeyFile);\n      assertNull(spec.adminPublicKeyFile);\n      assertNull(spec.authorizeAdminPublicKey);\n      assertNull(spec.grantSudoToAdminUser);\n      assertNull(spec.installAdminPrivateKey);\n      assertNull(spec.loginPassword);\n      assertNull(spec.resetLoginPassword);\n      assertAdminAccessBuilderEquivalence(adminAccessBuilders.get().lockSsh(true), adminAccessBuilders.get().from(spec));\n   }\n\n   public void testParseAdminUsernameRepeated() {\n      try {\n         parse(\"adminUsername=superUser, adminUsername=notSoSuperUser\");\n         fail(\"Expected exception\");\n      } catch (IllegalArgumentException expected) {\n         // expected\n      }\n   }\n\n   public void testParseNonExistingFiles() {\n      try {\n         parse(\"adminPrivateKeyFile=nonExistingFile.txt\");\n         fail(\"Expected exception\");\n      } catch (IllegalArgumentException expected) {\n         // expected\n      }\n      try {\n         parse(\"adminPublicKeyFile=nonExistingFile.txt\");\n         fail(\"Expected exception\");\n      } catch (IllegalArgumentException expected) {\n         // expected\n      }\n   }\n\n   @Test\n   public void testNiceJson() {\n      AdminAccessBuilderSpec spec = parse(\"adminUsername=nimda,adminPassword=dictionaryword\");\n      Json json = Guice.createInjector(new GsonModule()).getInstance(Json.class);\n      assertEquals(json.toJson(spec), \"{\\\"adminUsername\\\":\\\"nimda\\\",\\\"adminPassword\\\":\\\"dictionaryword\\\"}\");\n      assertEquals(json.fromJson(json.toJson(spec), AdminAccessBuilderSpec.class), spec);\n   }\n\n   public void testParse_unknownKey() {\n      try {\n         parse(\"foo=17\");\n         fail(\"Expected exception\");\n      } catch (IllegalArgumentException expected) {\n         // expected\n      }\n   }\n\n   public void testAdminAccessBuilderFromString() {\n      AdminAccess.Builder fromString = adminAccessBuilders.get().from(\n               \"adminUsername=nimda,adminPassword=dictionaryword\");\n      AdminAccess.Builder expected = adminAccessBuilders.get().adminUsername(\"nimda\").adminPassword(\"dictionaryword\");\n      assertAdminAccessBuilderEquivalence(expected, fromString);\n   }\n\n   private void assertAdminAccessBuilderEquivalence(AdminAccess.Builder a, AdminAccess.Builder b) {\n      // Labs hack: dig into the TemplateBuilder instances, verifying all fields\n      // are equal.\n      for (Field f : AdminAccess.Builder.class.getFields()) {\n         f.setAccessible(true);\n         try {\n            assertEquals(f.get(a), f.get(b), \"Field \" + f.getName() + \" not equal\");\n         } catch (IllegalArgumentException e) {\n            throw new AssertionError(e.getMessage());\n         } catch (IllegalAccessException e) {\n            throw new AssertionError(e.getMessage());\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/test/java/org/jclouds/scriptbuilder/statements/login/AdminAccessTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.statements.login;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\n\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.io.Resources;\n\n@Test(groups = \"unit\", singleThreaded = true, testName = \"AdminAccessTest\")\npublic class AdminAccessTest {\n\n   public void testStandardUNIX() throws IOException {\n      TestConfiguration.INSTANCE.reset();\n      try {\n         assertEquals(AdminAccess.standard().init(TestConfiguration.INSTANCE).render(OsFamily.UNIX),\n               Resources.toString(Resources.getResource(\"test_adminaccess_standard.sh\"), Charsets.UTF_8));\n      } finally {\n         TestConfiguration.INSTANCE.reset();\n      }\n   }\n\n   public void testWithParamsUNIX() throws IOException {\n      TestConfiguration.INSTANCE.reset();\n      try {\n         assertEquals(\n               AdminAccess.builder().adminPassword(\"bar\").adminPrivateKey(\"fooPrivateKey\")\n                     .adminPublicKey(\"fooPublicKey\").adminUsername(\"foo\").adminHome(\"/over/ridden/foo\").build()\n                     .init(TestConfiguration.INSTANCE).render(OsFamily.UNIX),\n               Resources.toString(Resources.getResource(\"test_adminaccess_params.sh\"), Charsets.UTF_8));\n\n      } finally {\n         TestConfiguration.INSTANCE.reset();\n      }\n   }\n\n   public void testWithParamsAndFullNameUNIX() throws IOException {\n      TestConfiguration.INSTANCE.reset();\n      try {\n         assertEquals(\n               AdminAccess.builder().adminPassword(\"bar\").adminPrivateKey(\"fooPrivateKey\")\n                     .adminPublicKey(\"fooPublicKey\").adminUsername(\"foo\").adminFullName(\"JClouds Foo\")\n                     .adminHome(\"/over/ridden/foo\").build().init(TestConfiguration.INSTANCE).render(OsFamily.UNIX),\n               Resources.toString(Resources.getResource(\"test_adminaccess_params_and_fullname.sh\"), Charsets.UTF_8));\n\n      } finally {\n         TestConfiguration.INSTANCE.reset();\n      }\n   }\n\n   public void testOnlyInstallUserUNIX() throws IOException {\n      TestConfiguration.INSTANCE.reset();\n      try {\n         assertEquals(\n               AdminAccess.builder().grantSudoToAdminUser(false).authorizeAdminPublicKey(true)\n                     .installAdminPrivateKey(true).lockSsh(false).resetLoginPassword(false).build()\n                     .init(TestConfiguration.INSTANCE).render(OsFamily.UNIX),\n               Resources.toString(Resources.getResource(\"test_adminaccess_plainuser.sh\"), Charsets.UTF_8));\n      } finally {\n         TestConfiguration.INSTANCE.reset();\n      }\n   }\n\n   @Test(expectedExceptions = UnsupportedOperationException.class, expectedExceptionsMessageRegExp = \"windows not yet implemented\")\n   public void testCreateWheelWindowsNotSupported() {\n      AdminAccess.standard().init(TestConfiguration.INSTANCE).render(OsFamily.WINDOWS);\n   }\n\n   @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = \"cannot create admin user 'root'; ensure jclouds is not running as root, or specify an explicit non-root username in AdminAccess\")\n   public void testRootNotAllowed() {\n      TestConfiguration.INSTANCE.reset();\n      try {\n         AdminAccess.builder().adminUsername(\"root\").build().init(TestConfiguration.INSTANCE).render(OsFamily.UNIX);\n      } finally {\n         TestConfiguration.INSTANCE.reset();\n      }\n   }\n\n   @Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = \"family\")\n   public void testFamilyRequiredAllowed() {\n      AdminAccess.standard().render(null);\n   }\n\n   @Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = \"please call init\\\\(\\\\) first\")\n   public void testIllegalStateExceptionUnlessCalledInit() {\n      AdminAccess access = AdminAccess.standard();\n      // before rendered, holder is empty\n      assertEquals(access.config.getAdminUsername(), null);\n      assertEquals(access.config.getAdminPassword(), null);\n      assertEquals(access.config.getAdminPublicKey(), null);\n      assertEquals(access.config.getAdminPrivateKey(), null);\n      assertEquals(access.config.getLoginPassword(), null);\n      access.render(OsFamily.UNIX);\n   }\n\n}\n"
  },
  {
    "path": "scriptbuilder/src/test/java/org/jclouds/scriptbuilder/statements/login/ReplaceShadowPasswordEntryOfLoginUserTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.statements.login;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\n\n@Test(groups = \"unit\")\npublic class ReplaceShadowPasswordEntryOfLoginUserTest {\n   Function<String, String> crypt = new Function<String, String>() {\n      public String apply(String in) {\n         assertEquals(in, \"password\");\n         return \"CRYPT\";\n      }\n   };\n\n   public void testWithPasswordUNIX() {\n      String cmd = new ReplaceShadowPasswordEntryOfLoginUser(crypt, \"password\").render(OsFamily.UNIX);\n      assert cmd.startsWith(\"awk -v user=^${SUDO_USER:=${USER}}: -v password='CRYPT\") : cmd;\n      assert cmd\n            .endsWith(\"' 'BEGIN { FS=OFS=\\\":\\\" } $0 ~ user { $2 = password } 1' /etc/shadow >/etc/shadow.${SUDO_USER:=${USER}}\\ntest -f /etc/shadow.${SUDO_USER:=${USER}} && mv /etc/shadow.${SUDO_USER:=${USER}} /etc/shadow\\n\") : cmd;\n   }\n\n   @Test(expectedExceptions = UnsupportedOperationException.class)\n   public void testAddUserWindowsNotSupported() {\n      new ReplaceShadowPasswordEntryOfLoginUser(crypt, \"password\").render(OsFamily.WINDOWS);\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/test/java/org/jclouds/scriptbuilder/statements/login/ReplaceShadowPasswordEntryTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.statements.login;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\n\n@Test(groups = \"unit\")\npublic class ReplaceShadowPasswordEntryTest {\n   Function<String, String> crypt = new Function<String, String>() {\n      public String apply(String in) {\n         assertEquals(in, \"password\");\n         return \"CRYPT\";\n      }\n   };\n\n   public void testWithPasswordUNIX() {\n      String userAdd = new ReplaceShadowPasswordEntry(crypt, \"foo\", \"password\").render(OsFamily.UNIX);\n      assert userAdd.startsWith(\"awk -v user=^foo: -v password='CRYPT\") : userAdd;\n      assert userAdd\n            .endsWith(\"' 'BEGIN { FS=OFS=\\\":\\\" } $0 ~ user { $2 = password } 1' /etc/shadow >/etc/shadow.foo\\ntest -f /etc/shadow.foo && mv /etc/shadow.foo /etc/shadow\\n\") : userAdd;\n   }\n\n   @Test(expectedExceptions = UnsupportedOperationException.class)\n   public void testAddUserWindowsNotSupported() {\n      new ReplaceShadowPasswordEntry(crypt, \"user\", \"password\").render(OsFamily.WINDOWS);\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/test/java/org/jclouds/scriptbuilder/statements/login/SudoStatementsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.statements.login;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class SudoStatementsTest {\n\n   public void testCreateWheelUNIX() {\n      assertEquals(\n               SudoStatements.createWheel().render(OsFamily.UNIX),\n               \"cat > /etc/sudoers <<-'END_OF_JCLOUDS_FILE'\\n\" +\n               \"\\tDefaults    env_reset\\n\" +\n               \"\\tDefaults    secure_path=\\\"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\\\"\\n\" +\n               \"\\troot ALL = (ALL) ALL\\n\" +\n               \"\\t%wheel ALL = (ALL) NOPASSWD:ALL\\n\" +\n               \"END_OF_JCLOUDS_FILE\\n\" +\n               \"chmod 0440 /etc/sudoers\\n\");\n   }\n\n   @Test(expectedExceptions = UnsupportedOperationException.class)\n   public void testCreateWheelWindowsNotSupported() {\n      SudoStatements.createWheel().render(OsFamily.WINDOWS);\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/test/java/org/jclouds/scriptbuilder/statements/login/TestConfiguration.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.statements.login;\n\nimport java.util.Map;\n\nimport org.jclouds.scriptbuilder.statements.login.AdminAccess.Configuration;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.base.Suppliers;\nimport com.google.common.collect.ImmutableMap;\n\npublic enum TestConfiguration implements Configuration {\n   INSTANCE;\n   int pwCount = 0;\n\n   public TestConfiguration reset() {\n      pwCount = 0;\n      return this;\n   }\n\n   private final Supplier<String> defaultAdminUsername = Suppliers.ofInstance(\"defaultAdminUsername\");\n   private final Supplier<Map<String, String>> defaultAdminSshKeys = Suppliers\n         .<Map<String, String>> ofInstance(ImmutableMap.of(\"public\", \"publicKey\", \"private\", \"privateKey\"));\n   private final Supplier<String> passwordGenerator = new Supplier<String>() {\n\n      @Override\n      public String get() {\n         return pwCount++ + \"\";\n      }\n\n   };\n\n   private final Function<String, String> cryptFunction = new Function<String, String>() {\n\n      @Override\n      public String apply(String input) {\n         return String.format(\"crypt(%s)\", input);\n      }\n\n   };\n\n   @Override\n   public Supplier<String> defaultAdminUsername() {\n      return defaultAdminUsername;\n   }\n\n   @Override\n   public Supplier<Map<String, String>> defaultAdminSshKeys() {\n      return defaultAdminSshKeys;\n   }\n\n   @Override\n   public Supplier<String> passwordGenerator() {\n      return passwordGenerator;\n   }\n\n   @Override\n   public Function<String, String> cryptFunction() {\n      return cryptFunction;\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/test/java/org/jclouds/scriptbuilder/statements/login/UserAddTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.statements.login;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableList;\n\n@Test(groups = \"unit\")\npublic class UserAddTest {\n\n   public void testUNIX() {\n      assertEquals(UserAdd.builder().login(\"me\").build().render(OsFamily.UNIX),\n               \"mkdir -p /home/users\\nchmod 0755 /home/users\\nuseradd -c me -s /bin/bash -m  -d /home/users/me me\\nchown -R me /home/users/me\\n\");\n   }\n\n   public void testWithFullNameUNIX() {\n      assertEquals(UserAdd.builder().login(\"me\").fullName(\"JClouds Guy\").build().render(OsFamily.UNIX),\n            \"mkdir -p /home/users\\nchmod 0755 /home/users\\nuseradd -c 'JClouds Guy' -s /bin/bash -m  -d /home/users/me me\\nchown -R me /home/users/me\\n\");\n\n   }\n\n   public void testWithBaseUNIX() {\n      assertEquals(UserAdd.builder().login(\"me\").defaultHome(\"/export/home\").build().render(OsFamily.UNIX),\n               \"mkdir -p /export/home\\nchmod 0755 /export/home\\nuseradd -c me -s /bin/bash -m  -d /export/home/me me\\nchown -R me /export/home/me\\n\");\n   }\n\n   public void testWithGroupUNIX() {\n      assertEquals(UserAdd.builder().login(\"me\").group(\"wheel\").build().render(OsFamily.UNIX),\n               \"mkdir -p /home/users\\nchmod 0755 /home/users\\ngetent group wheel || groupadd -f wheel\\nuseradd -c me -s /bin/bash -g wheel -m  -d /home/users/me me\\nchown -R me /home/users/me\\n\");\n   }\n\n   public void testWithGroupsUNIX() {\n      assertEquals(UserAdd.builder().login(\"me\").groups(ImmutableList.of(\"wheel\", \"candy\")).build().render(\n               OsFamily.UNIX),\n               \"mkdir -p /home/users\\nchmod 0755 /home/users\\ngetent group wheel || groupadd -f wheel\\ngetent group candy || groupadd -f candy\\nuseradd -c me -s /bin/bash -g wheel -G candy -m  -d /home/users/me me\\nchown -R me /home/users/me\\n\");\n   }\n\n   Function<String, String> crypt = new Function<String, String>() {\n      public String apply(String in) {\n         assertEquals(in, \"password\");\n         return \"CRYPT\";\n      }\n   };\n\n   public void testWithPasswordUNIX() {\n      String userAdd = UserAdd.builder().cryptFunction(crypt).login(\"me\").password(\"password\").group(\"wheel\").build().render(OsFamily.UNIX);\n      assert userAdd.startsWith(\"mkdir -p /home/users\\nchmod 0755 /home/users\\ngetent group wheel || groupadd -f wheel\\nuseradd -c me -s /bin/bash -g wheel -m  -d /home/users/me -p 'CRYPT'\") : userAdd;\n      assert userAdd.endsWith(\"' me\\nchown -R me /home/users/me\\n\") : userAdd;\n   }\n\n   public void testWithSshAuthorizedKeyUNIX() {\n      assertEquals(\n               UserAdd.builder().login(\"me\").authorizeRSAPublicKey(\"rsapublickey\").build().render(OsFamily.UNIX),\n               \"mkdir -p /home/users\\nchmod 0755 /home/users\\nuseradd -c me -s /bin/bash -m  -d /home/users/me me\\nmkdir -p /home/users/me/.ssh\\ncat >> /home/users/me/.ssh/authorized_keys <<-'END_OF_JCLOUDS_FILE'\\n\\trsapublickey\\nEND_OF_JCLOUDS_FILE\\nchmod 600 /home/users/me/.ssh/authorized_keys\\nchown -R me /home/users/me/.ssh\\nchown -R me /home/users/me\\n\");\n   }\n\n   public void testWithSshInstalledKeyUNIX() {\n      assertEquals(\n               UserAdd.builder().login(\"me\").installRSAPrivateKey(\"rsaprivate\").build().render(OsFamily.UNIX),\n               \"mkdir -p /home/users\\nchmod 0755 /home/users\\nuseradd -c me -s /bin/bash -m  -d /home/users/me me\\nmkdir -p /home/users/me/.ssh\\nrm /home/users/me/.ssh/id_rsa\\ncat >> /home/users/me/.ssh/id_rsa <<-'END_OF_JCLOUDS_FILE'\\n\\trsaprivate\\nEND_OF_JCLOUDS_FILE\\nchmod 600 /home/users/me/.ssh/id_rsa\\nchown -R me /home/users/me\\n\");\n   }\n\n   public void testWithHomeUNIX() {\n      assertEquals(UserAdd.builder().login(\"me\").home(\"/myhome/myme\").build().render(\n               OsFamily.UNIX),\n               \"mkdir -p /myhome\\nchmod 0755 /myhome\\nuseradd -c me -s /bin/bash -m  -d /myhome/myme me\\nchown -R me /myhome/myme\\n\");\n      \n      assertEquals(UserAdd.builder().login(\"me\").home(\"/myhome/myme\").defaultHome(\"/ignoreddefault\").build().render(\n                              OsFamily.UNIX),\n                              \"mkdir -p /myhome\\nchmod 0755 /myhome\\nuseradd -c me -s /bin/bash -m  -d /myhome/myme me\\nchown -R me /myhome/myme\\n\");\n   }\n\n   @Test(expectedExceptions = UnsupportedOperationException.class)\n   public void testAddUserWindowsNotSupported() {\n      UserAdd.builder().login(\"me\").build().render(OsFamily.WINDOWS);\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/test/java/org/jclouds/scriptbuilder/statements/ruby/InstallRubyGemsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.statements.ruby;\n\nimport static org.jclouds.scriptbuilder.statements.ruby.InstallRubyGems.DEFAULT_RUBYGEMS_VERSION;\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\n\nimport org.jclouds.scriptbuilder.InitScript;\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.jclouds.scriptbuilder.domain.ShellToken;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.io.Resources;\n\n/**\n * Unit tests for the {@link InstallRubyGemsTest} statement.\n */\n@Test(groups = \"unit\", testName = \"InstallRubyGemsTest\")\npublic class InstallRubyGemsTest {\n\n   @Test(expectedExceptions = UnsupportedOperationException.class, expectedExceptionsMessageRegExp = \"windows not yet implemented\")\n   public void installRubyGemsInWindows() {\n      new InstallRuby().render(OsFamily.WINDOWS);\n   }\n\n   public void installRubyGemsDefaultsUnix() throws IOException {\n      assertEquals(InstallRubyGems.builder().build().render(OsFamily.UNIX), installRubyGems(DEFAULT_RUBYGEMS_VERSION));\n   }\n\n   public void installRubyGemsForcingVersion() throws IOException {\n      assertEquals(InstallRubyGems.builder().version(\"1.8.25\").build().render(OsFamily.UNIX), installRubyGems(\"1.8.25\"));\n   }\n\n   public void installRubyGemsAndUpdateSystem() throws IOException {\n      assertEquals(InstallRubyGems.builder().updateSystem(true).build().render(OsFamily.UNIX),\n            installRubyGems(DEFAULT_RUBYGEMS_VERSION) + updateSystem(null));\n   }\n\n   public void installRubyGemsAndUpdateSystemForcingUpdateVersion() throws IOException {\n      assertEquals(InstallRubyGems.builder().updateSystem(true, \"1.8.25\").build().render(OsFamily.UNIX),\n            installRubyGems(DEFAULT_RUBYGEMS_VERSION) + updateSystem(\"1.8.25\"));\n   }\n\n   public void installRubyGemsAndUpdateGems() throws IOException {\n      assertEquals(InstallRubyGems.builder().updateExistingGems(true).build().render(OsFamily.UNIX),\n            installRubyGems(DEFAULT_RUBYGEMS_VERSION) + updateGems());\n   }\n\n   public void installRubyGemsUpdatingSystemAndGems() throws IOException {\n      assertEquals(InstallRubyGems.builder().version(\"1.2.3\").updateSystem(true, \"1.2.4\").updateExistingGems(true)\n            .build().render(OsFamily.UNIX), installRubyGems(\"1.2.3\") + updateSystem(\"1.2.4\") + updateGems());\n   }\n\n   public void installRubyGemsDefaultsWithUpgrade() throws IOException {\n      assertEquals(InstallRubyGems.builder().updateSystem(true).updateExistingGems(true).build().render(OsFamily.UNIX),\n            Resources.toString(Resources.getResource(\"test_install_rubygems.\" + ShellToken.SH.to(OsFamily.UNIX)),\n                  Charsets.UTF_8));\n   }\n\n   public void installRubyGemsUnixDefaultsInScriptBuilder() throws IOException {\n      assertEquals(\n            InitScript.builder().name(\"install_rubygems\").run(InstallRubyGems.builder().build()).build()\n                  .render(OsFamily.UNIX), Resources.toString(\n                  Resources.getResource(\"test_install_rubygems_scriptbuilder.\" + ShellToken.SH.to(OsFamily.UNIX)),\n                  Charsets.UTF_8));\n   }\n\n   private static String installRubyGems(String version) {\n      String script = \"if ! hash gem 2>/dev/null; then\\n\"\n            + \"(\\n\"\n            + \"export TAR_TEMP=\\\"$(mktemp -d)\\\"\\n\"\n            + \"curl -q -s -S -L --connect-timeout 10 --max-time 600 --retry 20 -X GET  http://production.cf.rubygems.org/rubygems/rubygems-\"\n            + version + \".tgz |(mkdir -p \\\"${TAR_TEMP}\\\" &&cd \\\"${TAR_TEMP}\\\" &&tar -xpzf -)\\n\" + \"mkdir -p /tmp/rubygems\\n\"\n            + \"mv \\\"${TAR_TEMP}\\\"/*/* /tmp/rubygems\\n\" + \"rm -rf \\\"${TAR_TEMP}\\\"\\n\" + \"cd /tmp/rubygems\\n\"\n            + \"ruby setup.rb --no-format-executable\\n\" //\n            + \"rm -fr /tmp/rubygems\\n\" + //\n            \")\\n\" + //\n            \"fi\\n\";\n\n      return script;\n   }\n\n   private static String updateSystem(String version) {\n      return version == null ? \"gem update --system\\n\" : \"gem update --system \" + version + \"\\n\";\n   }\n\n   private static String updateGems() {\n      return \"gem update --no-rdoc --no-ri\\n\";\n   }\n\n}\n"
  },
  {
    "path": "scriptbuilder/src/test/java/org/jclouds/scriptbuilder/statements/ruby/InstallRubyTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.statements.ruby;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.io.IOException;\n\nimport org.jclouds.scriptbuilder.InitScript;\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.jclouds.scriptbuilder.domain.ShellToken;\nimport org.testng.annotations.Test;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.io.Resources;\n\n/**\n * Unit tests for the {@link InstallRuby} statement.\n */\n@Test(groups = \"unit\", testName = \"InstallRubyTest\")\npublic class InstallRubyTest {\n\n   @Test(expectedExceptions = UnsupportedOperationException.class, expectedExceptionsMessageRegExp = \"windows not yet implemented\")\n   public void installRubyInWindows() {\n      InstallRuby.builder().build().render(OsFamily.WINDOWS);\n   }\n\n   public void installRubyUnix() throws IOException {\n      assertEquals(InstallRuby.builder().build().render(OsFamily.UNIX), Resources.toString(\n            Resources.getResource(\"test_install_ruby.\" + ShellToken.SH.to(OsFamily.UNIX)), Charsets.UTF_8));\n   }\n\n   public void installRubyUnixInScriptBuilderSourcesSetupPublicCurl() throws IOException {\n      assertEquals(\n            InitScript.builder().name(\"install_ruby\").run(InstallRuby.builder().build()).build().render(OsFamily.UNIX),\n            Resources.toString(\n                  Resources.getResource(\"test_install_ruby_scriptbuilder.\" + ShellToken.SH.to(OsFamily.UNIX)),\n                  Charsets.UTF_8));\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/test/java/org/jclouds/scriptbuilder/statements/ssh/AuthorizeRSAPublicKeyTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.statements.ssh;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableSet;\n\n@Test(groups = \"unit\")\npublic class AuthorizeRSAPublicKeyTest {\n\n   public void testAuthorizeRSAPublicKeyUNIXCurrentUser() {\n      assertEquals(\n               new AuthorizeRSAPublicKeys(ImmutableSet.of(\"ssh-dss AAAAB\"), \"jclouds\").render(OsFamily.UNIX),\n               \"mkdir -p ~/.ssh\\n\" +\n               \"cat >> ~/.ssh/authorized_keys <<-'END_OF_JCLOUDS_FILE'\\n\" +\n               \"\\tssh-dss AAAAB\\n\" +\n               \"END_OF_JCLOUDS_FILE\\n\" +\n               \"chmod 600 ~/.ssh/authorized_keys\\n\" +\n               \"chown -R jclouds ~/.ssh\\n\");\n   }\n   \n   public void testAuthorizeRSAPublicKeyUNIXNoOwner() {\n      assertEquals(\n               new AuthorizeRSAPublicKeys(ImmutableSet.of(\"ssh-dss AAAAB\")).render(OsFamily.UNIX),\n               \"mkdir -p ~/.ssh\\n\" +\n               \"cat >> ~/.ssh/authorized_keys <<-'END_OF_JCLOUDS_FILE'\\n\" +\n               \"\\tssh-dss AAAAB\\n\" +\n               \"END_OF_JCLOUDS_FILE\\n\" +\n               \"chmod 600 ~/.ssh/authorized_keys\\n\");\n   }\n\n   public void testAuthorizeRSAPublicKeyUNIXCurrentUserWith2Keys() {\n      assertEquals(\n               new AuthorizeRSAPublicKeys(ImmutableSet.of(\"ssh-dss AAAAB\", \"ssh-dss CCCCD\"), \"jclouds\").render(OsFamily.UNIX),\n               \"mkdir -p ~/.ssh\\n\" +\n               \"cat >> ~/.ssh/authorized_keys <<-'END_OF_JCLOUDS_FILE'\\n\" +\n               \"\\tssh-dss AAAAB\\n\" +\n               \"\\t\\n\" +\n               \"\\tssh-dss CCCCD\\n\" +\n               \"END_OF_JCLOUDS_FILE\\n\" +\n               \"chmod 600 ~/.ssh/authorized_keys\\n\" +\n               \"chown -R jclouds ~/.ssh\\n\");\n   }\n\n   public void testAuthorizeRSAPublicKeyUNIXSpecifiedDir() {\n      assertEquals(\n               new AuthorizeRSAPublicKeys(\"/home/me/.ssh\", ImmutableSet.of(\"ssh-dss AAAAB\"), \"jclouds\").render(OsFamily.UNIX),\n               \"mkdir -p /home/me/.ssh\\n\" +\n               \"cat >> /home/me/.ssh/authorized_keys <<-'END_OF_JCLOUDS_FILE'\\n\" +\n               \"\\tssh-dss AAAAB\\n\" +\n               \"END_OF_JCLOUDS_FILE\\n\" +\n               \"chmod 600 /home/me/.ssh/authorized_keys\\n\" +\n               \"chown -R jclouds /home/me/.ssh\\n\");\n   }\n\n   public void testAuthorizeRSAPublicKeyUNIXSpecifiedDirWith2Keys() {\n      assertEquals(\n               new AuthorizeRSAPublicKeys(\"/home/me/.ssh\", ImmutableSet.of(\"ssh-dss AAAAB\", \"ssh-dss CCCCD\"), \"jclouds\")\n                        .render(OsFamily.UNIX),\n                        \"mkdir -p /home/me/.ssh\\n\" +\n                              \"cat >> /home/me/.ssh/authorized_keys <<-'END_OF_JCLOUDS_FILE'\\n\" +\n                              \"\\tssh-dss AAAAB\\n\" +\n                              \"\\t\\n\" +\n                              \"\\tssh-dss CCCCD\\n\" +\n                              \"END_OF_JCLOUDS_FILE\\n\" +\n                              \"chmod 600 /home/me/.ssh/authorized_keys\\n\" +\n                              \"chown -R jclouds /home/me/.ssh\\n\");\n   }\n\n   @Test(expectedExceptions = UnsupportedOperationException.class)\n   public void testAuthorizeRSAPublicKeyWINDOWS() {\n      new AuthorizeRSAPublicKeys(ImmutableSet.of(\"ssh-dss AAAAB\"), \"jclouds\").render(OsFamily.WINDOWS);\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/test/java/org/jclouds/scriptbuilder/statements/ssh/InstallRSAPrivateKeyTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.statements.ssh;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\")\npublic class InstallRSAPrivateKeyTest {\n\n   public void testInstallRSAPrivateKeyUNIXCurrentUser() {\n      assertEquals(\n               new InstallRSAPrivateKey(\"-----BEGIN RSA PRIVATE KEY-----\\n-----END RSA PRIVATE KEY-----\\n\")\n                        .render(OsFamily.UNIX),\n                        \"mkdir -p ~/.ssh\\n\" +\n                        \"rm ~/.ssh/id_rsa\\n\" +\n                        \"cat >> ~/.ssh/id_rsa <<-'END_OF_JCLOUDS_FILE'\\n\" +\n                        \"\\t-----BEGIN RSA PRIVATE KEY-----\\n\" +\n                        \"\\t-----END RSA PRIVATE KEY-----\\n\" +\n                        \"\\t\\n\" +\n                        \"END_OF_JCLOUDS_FILE\\n\" +\n                        \"chmod 600 ~/.ssh/id_rsa\\n\");                        \n   }\n\n   public void testInstallRSAPrivateKeyUNIXSpecifiedHome() {\n      assertEquals(\n               new InstallRSAPrivateKey(\"/home/me/.ssh\", \"-----BEGIN RSA PRIVATE KEY-----\\n-----END RSA PRIVATE KEY-----\\n\")\n                        .render(OsFamily.UNIX),\n                        \"mkdir -p /home/me/.ssh\\n\" +\n                        \"rm /home/me/.ssh/id_rsa\\n\" +\n                        \"cat >> /home/me/.ssh/id_rsa <<-'END_OF_JCLOUDS_FILE'\\n\" +\n                        \"\\t-----BEGIN RSA PRIVATE KEY-----\\n\" +\n                        \"\\t-----END RSA PRIVATE KEY-----\\n\" +\n                        \"\\t\\n\" +\n                        \"END_OF_JCLOUDS_FILE\\n\" +\n                        \"chmod 600 /home/me/.ssh/id_rsa\\n\");    }\n\n   @Test(expectedExceptions = UnsupportedOperationException.class)\n   public void testInstallRSAPrivateKeyWINDOWS() {\n      new InstallRSAPrivateKey(\"-----BEGIN RSA PRIVATE KEY-----\\n-----END RSA PRIVATE KEY-----\\n\")\n               .render(OsFamily.WINDOWS);\n   }\n}\n"
  },
  {
    "path": "scriptbuilder/src/test/java/org/jclouds/scriptbuilder/statements/ssh/SshStatementsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.statements.ssh;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\n\n@Test(groups = \"unit\")\npublic class SshStatementsTest {\n\n   public void testLockSshdUNIX() {\n      assertEquals(SshStatements.lockSshd().render(OsFamily.UNIX), new StringBuilder().append(\n               \"exec 3<> /etc/ssh/sshd_config && awk -v TEXT=\\\"\")//\n               .append(\"PasswordAuthentication no\").append(\"\\n\")//\n               .append(\"PermitRootLogin no\").append(\"\\n\")//\n               .append(\"\\\" 'BEGIN {print TEXT}{print}' /etc/ssh/sshd_config >&3\").append(\"\\n\")//\n               .append(\"hash service 2>&- && service ssh reload 2>&- || service sshd reload 2>&- || /etc/init.d/ssh* reload\").append(\"\\n\").toString());\n   }\n\n   public void testSshdConfigUNIX() {\n      assertEquals(SshStatements.sshdConfig(ImmutableMap.of(\"AddressFamily\", \"inet6\")).render(OsFamily.UNIX),\n               new StringBuilder().append(\"exec 3<> /etc/ssh/sshd_config && awk -v TEXT=\\\"\")//\n                        .append(\"AddressFamily inet6\").append(\"\\n\")//\n                        .append(\"\\\" 'BEGIN {print TEXT}{print}' /etc/ssh/sshd_config >&3\").append(\"\\n\")//\n                        .append(\"hash service 2>&- && service ssh reload 2>&- || service sshd reload 2>&- || /etc/init.d/ssh* reload\").append(\"\\n\").toString());\n   }\n\n}\n"
  },
  {
    "path": "scriptbuilder/src/test/java/org/jclouds/scriptbuilder/util/UtilsTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.scriptbuilder.util;\n\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.scriptbuilder.domain.OsFamily;\nimport org.jclouds.scriptbuilder.domain.ShellToken;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableList;\nimport com.google.common.collect.ImmutableMap;\n\n@Test(groups = \"unit\")\npublic class UtilsTest {\n\n   public void testReplaceTokens() {\n      assertEquals(Utils.replaceTokens(\"hello {where}\", ImmutableMap.of(\"where\", \"world\")),\n               \"hello world\");\n   }\n\n   public void testWriteFunctionFromResourceAddsNewlineUNIX() {\n      assertEquals(Utils.writeFunctionFromResource(\"nonewline\", OsFamily.UNIX), \"foo\\n\");\n   }\n   \n\n   public void testWriteFunctionFromResourceAddsNewlineWINDOWS() {\n      assertEquals(Utils.writeFunctionFromResource(\"nonewline\", OsFamily.WINDOWS), \"foo\\r\\n\");\n   }\n   \n   public void testWriteVariableExportersUNIX() {\n      assertEquals(Utils.writeVariableExporters(ImmutableMap.of(\"MAVEN_OPTS\",\n               \"-Xms128m -Xmx256m -XX:+HeapDumpOnOutOfMemoryError\"), OsFamily.UNIX),\n               \"export MAVEN_OPTS=\\\"-Xms128m -Xmx256m -XX:+HeapDumpOnOutOfMemoryError\\\"\\n\");\n   }\n\n   public void testWriteVariableExportersWindows() {\n      assertEquals(Utils.writeVariableExporters(ImmutableMap.of(\"MAVEN_OPTS\",\n               \"-Xms128m -Xmx256m -XX:+HeapDumpOnOutOfMemoryError\"), OsFamily.WINDOWS),\n               \"set MAVEN_OPTS=-Xms128m -Xmx256m -XX:+HeapDumpOnOutOfMemoryError\\r\\n\");\n   }\n   \n   public void testWriteVariableExportersNameReplaceUNIX() {\n      assertEquals(Utils.writeVariableExporters(ImmutableMap.of(\"LIBRARY_PATH\", \"{tmp}\"), OsFamily.UNIX),\n               \"export LD_LIBRARY_PATH=\\\"/tmp\\\"\\n\");\n   }\n\n   public void testWriteVariableExportersNameReplaceWindows() {\n      assertEquals(Utils.writeVariableExporters(ImmutableMap.of(\"LIBRARY_PATH\", \"{tmp}\"), OsFamily.WINDOWS),\n               \"set PATH=%TEMP%\\r\\n\");\n   }\n\n   public void testWritePositionalVarsUNIX() {\n      assertEquals(Utils.writePositionalVars(ImmutableList.of(\"HOST\", \"PORT\"), OsFamily.UNIX),\n               \"set HOST=$1\\nshift\\nset PORT=$1\\nshift\\n\");\n   }\n\n   public void testWritePositionalVarsWindows() {\n      assertEquals(Utils.writePositionalVars(ImmutableList.of(\"HOST\", \"PORT\"), OsFamily.WINDOWS),\n               \"set HOST=%1\\r\\nshift\\r\\nset PORT=%1\\r\\nshift\\r\\n\");\n   }\n\n   public void testWriteUnsetVariablesUNIX() {\n      assertEquals(Utils.writeUnsetVariables(ImmutableList.of(\"HOST\", \"PORT\"), OsFamily.UNIX),\n               \"unset HOST PORT\\n\");\n   }\n\n   public void testWriteUnsetVariablesWindows() {\n      assertEquals(Utils.writeUnsetVariables(ImmutableList.of(\"HOST\", \"PORT\"), OsFamily.WINDOWS),\n               \"set HOST=\\r\\nset PORT=\\r\\n\");\n   }\n   \n\n   public void testWriteUnsetVariablesNameReplaceUNIX() {\n      assertEquals(Utils.writeUnsetVariables(ImmutableList.of(\"LIBRARY_PATH\"), OsFamily.UNIX),\n               \"unset LD_LIBRARY_PATH\\n\");\n   }\n\n   public void testWriteUnsetVariablesNameReplaceWindows() {\n      assertEquals(Utils.writeUnsetVariables(ImmutableList.of(\"LIBRARY_PATH\"), OsFamily.WINDOWS),\n               \"set PATH=\\r\\n\");\n   }\n\n   public void testSingleCurlyBraceDoesntBreakLfTokenReplacement() {\n      assertEquals(Utils.replaceTokens(\"{{lf}\", ShellToken.tokenValueMap(OsFamily.UNIX)),\n            \"{\\n\");\n   }\n\n}\n"
  },
  {
    "path": "scriptbuilder/src/test/resources/.gitattributes",
    "content": "*.sh -crlf\n"
  },
  {
    "path": "scriptbuilder/src/test/resources/client_rb_append.cmd",
    "content": "echo log_level :info >>c:\\etc\\chef\\client.rb\r\necho log_location STDOUT >>c:\\etc\\chef\\client.rb\r\necho chef_server_url \"http://localhost:4000\" >>c:\\etc\\chef\\client.rb\r\n"
  },
  {
    "path": "scriptbuilder/src/test/resources/client_rb_append.sh",
    "content": "cat >> /etc/chef/client.rb <<-'END_OF_JCLOUDS_FILE'\n\tlog_level :info\n\tlog_location STDOUT\n\tchef_server_url \"http://localhost:4000\"\nEND_OF_JCLOUDS_FILE\n"
  },
  {
    "path": "scriptbuilder/src/test/resources/client_rb_overwrite.cmd",
    "content": "copy /y CON c:\\etc\\chef\\client.rb\r\necho log_level :info >>c:\\etc\\chef\\client.rb\r\necho log_location STDOUT >>c:\\etc\\chef\\client.rb\r\necho chef_server_url \"http://localhost:4000\" >>c:\\etc\\chef\\client.rb\r\n"
  },
  {
    "path": "scriptbuilder/src/test/resources/client_rb_overwrite.sh",
    "content": "cat > /etc/chef/client.rb <<-'END_OF_JCLOUDS_FILE'\n\tlog_level :info\n\tlog_location STDOUT\n\tchef_server_url \"http://localhost:4000\"\nEND_OF_JCLOUDS_FILE\n"
  },
  {
    "path": "scriptbuilder/src/test/resources/forget.cmd",
    "content": "@echo off\r\n:: Nohup-like utility for windows written with zero dependencies on non-standard code.\r\n::\r\n:: Usage forget process_name fullpath arguments\r\n::\r\n:: Ex. forget tomcat c:\\apps\\tomcat start\r\n::\r\n:: Uses the schtasks command to launch whatever the command is in the next minute. \r\n:: If the process is already running, it is shutdown first.\r\n::\r\n:: Author Adrian Cole\r\n::\r\nGOTO FUNCTION_END\r\n\r\n:ABORT\r\n   echo aborting: %_result%\r\n   exit /b 1\r\n\r\n:findProcess\r\n   SETLOCAL\r\n   set _proc=\r\n   set _pid=\r\n   set _name=%1\r\n   shift\r\n   set FIND_PROCESS=wmic process where (name=\"cmd.exe\" and CommandLine like \"cmd /c title %_name%%%\") get ProcessId\r\n   for /f \"usebackq skip=1\" %%a in (`cmd /c \"%FIND_PROCESS% 2>NUL\"`) do (\r\n      if not defined _proc (\r\n         set _proc=%%a\r\n         goto :done\r\n      )\r\n   )\r\n   :done\r\n   ENDLOCAL&SET _pid=%_proc%\r\n   exit /b 0\r\n\r\n:nextMinute\r\n   SETLOCAL\r\n   set HOURS=%TIME:~0,2%\r\n   set MINUTES=%TIME:~3,2%\r\n\r\n   set /a HOURS=%HOURS%\r\n   set /a MINUTES+=1\r\n\r\n   if %MINUTES% EQU 60 (set MINUTES=0&set /a HOURS+=1)\r\n   if %HOURS% EQU 24 (set HOURS=0)\r\n\r\n   if %HOURS% LSS 10 set HOURS=0%HOURS%\r\n   if %MINUTES% LSS 10 set MINUTES=0%MINUTES%\r\n\r\n   ENDLOCAL&SET _nextMinute=%HOURS%:%MINUTES%:00\r\n   exit /b 0\r\n\r\n:FUNCTION_END\r\n\r\nSETLOCAL\r\nset PID_TO_KILL=\r\nset NEXT_MINUTE=\r\nset NAME=%1\r\nshift\r\n\r\nCALL :findProcess %NAME%\r\nif defined _pid (\r\n   echo stopping %NAME%\r\n   TASKKILL /F /T /PID %_pid% >NUL\r\n)\r\nschtasks /end /tn %NAME% >NUL 2>NUL\r\nschtasks /delete /tn %NAME% /F >NUL 2>NUL\r\n\r\nCALL :nextMinute\r\nset NEXT_MINUTE=%_nextMinute%\r\nset _DATE=%DATE:~4%\r\nset CMD=schtasks /create /sd %_DATE% /tn %NAME% /ru System  /tr  \"cmd /c title %NAME%&%1 %2 %3 %4 %5 %6 %7 %8 >c:\\stdout.log 2>c:\\stderr.log\" /sc:once /st %NEXT_MINUTE%\r\necho %NAME% will start at %NEXT_MINUTE%\r\n%CMD% >NUL\r\ngoto :eof\r\n"
  },
  {
    "path": "scriptbuilder/src/test/resources/functions/.gitattributes",
    "content": "*.sh -crlf\n"
  },
  {
    "path": "scriptbuilder/src/test/resources/functions/nonewline.cmd",
    "content": "foo\r\n"
  },
  {
    "path": "scriptbuilder/src/test/resources/functions/nonewline.sh",
    "content": "foo"
  },
  {
    "path": "scriptbuilder/src/test/resources/functions/test_install_jdk_from_url.sh",
    "content": "setupPublicCurl || return 1\ncurl -q -s -S -L --connect-timeout 10 --max-time 600 --retry 20 -X GET  http://download.oracle.com/otn-pub/java/jdk/7/jdk-7-linux-x64.tar.gz |(mkdir -p /usr/local &&cd /usr/local &&tar -xpzf -)\nmv /usr/local/jdk* /usr/local/jdk/\ntest -n \"$SUDO_USER\" && \ncat >> /home/$SUDO_USER/.bashrc <<'END_OF_FILE'\nexport JAVA_HOME=/usr/local/jdk\nexport PATH=$JAVA_HOME/bin:$PATH\nEND_OF_FILE\ncat >> /etc/bashrc <<'END_OF_FILE'\nexport JAVA_HOME=/usr/local/jdk\nexport PATH=$JAVA_HOME/bin:$PATH\nEND_OF_FILE\ncat >> $HOME/.bashrc <<'END_OF_FILE'\nexport JAVA_HOME=/usr/local/jdk\nexport PATH=$JAVA_HOME/bin:$PATH\nEND_OF_FILE\ncat >> /etc/skel/.bashrc <<'END_OF_FILE'\nexport JAVA_HOME=/usr/local/jdk\nexport PATH=$JAVA_HOME/bin:$PATH\nEND_OF_FILE\nln -fs /usr/local/jdk/bin/java /usr/bin/java\n"
  },
  {
    "path": "scriptbuilder/src/test/resources/test",
    "content": "-----BEGIN RSA PRIVATE KEY-----\nMIIEogIBAAKCAQEAnJvA40x4OK+9nVYTS0N916VMjC6/qYe/IuDUdy6hdW1wz9IO\nMTS3CPxlE0KuoNO1/M7O7yFso6IragTxUkNqJ2mUOqV0Bf0CEkUIKzeYRGfpx+QM\nPorHbLQXjjFinWKwibZuv6lqtvqwcsrjW7bpWsz9x+0qqKM0o0UhjUMhTRqZoYxo\nE2zUH7WA8JRatE/bQkjv/nWBfI+/WzSDhJn7AjIql0Nd4Q+bxohIJEZu8yDw1H6T\npd7mw83m6UYBk4eZH79r3d2euuQMUKIunyLbw7vNJJ8qYTJQuNYIiJuWKnzzjxuJ\nUfumhdOqfjSobznhAjTLUbA/btZCiQ/TasV4cQIDAQABAoIBAEeOn1b8ZN455qDS\naKR2JTT4cX6ICckznnEYW9xNMTcPl4FN0HBJTuzLLn/bcyFHOxtVf5YiJpqqCb46\nne1hokp54mHdoaLu1Rh19GKS139CH77XA4U8Mh0IOM8e35lcM5/o/LeUeI89Aoyh\nCbupWvzDN543TsuZLv7/InKCXt/0dXhAQpq3UiBT63EITQbyom5fSPnMzqM3F8jD\nE9ZqkX4JsnTPC7FQDIpPCaKjG9YCZqoljz+1ssli3mN66V/JKefcCiVoubalmmT2\ndpvmRtFaKvhAmkWYakYybYg8aDi3YygAHSU1bzxlY4TNiQgPdnTTDAPyeqqVrE1D\nChi+18UCgYEAzlk7c+tFwxZ3ryycOe0loFudUNE5rviHhPgbOHoSTooXh0Hq1Vrb\n2ic+4FbRpoPHLpcLM9LX+arezUdeFBZ8qunjUG6MbUhAeAm/3cfMk+nZg3Skpg8+\nC1D3hxGX4qdhURHvc2QUH7VIUWbucvPgtL8pt1z5Su/EE1Cb2XVsvu8CgYEAwkqZ\n4vTZxI0XqJo6BfUnKGJEDC8xeWr10ELPdXLTCuNDpLSYNedQAxZi9XzvbnbWZ/MF\nZ7IWkzzyAjsX0gpI56cxxtas/chxUboBlUo6ZW8QcPDcU2sKJi318wzElqqvRMNM\nInfLf8nuPC9hyhe49/lFBBSZJeIo396DuqnTPp8CgYBO4NVVLm5wcLo3gDoH+psT\nfXHZXuFJ/T7wmVbuc9tjom30CkKWZDD+Z1olr4pcuKr/KEXj/YkJq0OX/Nv9mcr2\nGooGSPvtGl1qhW+Oe728HPxEv+XghJsXAFBelV8WCR2uO8jotyzqIgYO9+XWk1sm\nPJzZtvSkrJqrN3kb20NCiQKBgDDVP0hj8jgMnl2qJdtJesYTrLbDRdQWpiHqKOqE\nKbca1+2V1ov1z453GfhJpoRFKi6GTl15zWLEdq9I2vvXyesvgrtPSbufnZvE/JDh\nTzwfZip832O4C5z9AExOcTrNO7A0xfYD1goQXuiRoCqDO+JXrJkR9EwpQ8zAyKsp\n9AZRAoGAGq3TYpmlI5oucEURHKsHOrIBirHFD+RaXMynxzgwkRnt6Z5Mg10I7Ddr\nLiGK8/IrF8bg1F7weLVmj93zjvhQTh5yvb1jwVdFGXM2rbR7/P7F6n2f7xM4+lmv\nTq7E9Sv8UVuraAwJihlKCuBtpZM1t2JhcuNjXAZngj7R9j5HIZg=\n-----END RSA PRIVATE KEY-----\n"
  },
  {
    "path": "scriptbuilder/src/test/resources/test_adminaccess_flipped.sh",
    "content": "rm /etc/sudoers\ncat >> /etc/sudoers <<'END_OF_FILE'\nDefaults    env_reset\nDefaults    secure_path=\"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\"\nroot ALL = (ALL) ALL\n%wheel ALL = (ALL) NOPASSWD:ALL\nEND_OF_FILE\nchmod 0440 /etc/sudoers\nmkdir -p /home/users\nchmod 0755 /home/users\ngetent group wheel || groupadd -f wheel\nuseradd -c defaultAdminUsername -s /bin/bash -g wheel -d /home/users/defaultAdminUsername -p 'crypt(0)' defaultAdminUsername\nmkdir -p /home/users/defaultAdminUsername/.ssh\ncat >> /home/users/defaultAdminUsername/.ssh/authorized_keys <<'END_OF_FILE'\npublicKey\nEND_OF_FILE\nchmod 600 /home/users/defaultAdminUsername/.ssh/authorized_keys\nchown -R defaultAdminUsername /home/users/defaultAdminUsername/.ssh\nchown -R defaultAdminUsername /home/users/defaultAdminUsername\nexec 3<> /etc/ssh/sshd_config && awk -v TEXT=\"PasswordAuthentication no\nPermitRootLogin no\n\" 'BEGIN {print TEXT}{print}' /etc/ssh/sshd_config >&3\nhash service 2>/dev/null && service ssh reload || /etc/init.d/ssh* reload\nawk -v user=^${SUDO_USER:=${USER}}: -v password='crypt(1)' 'BEGIN { FS=OFS=\":\" } $0 ~ user { $2 = password } 1' /etc/shadow >/etc/shadow.${SUDO_USER:=${USER}}\ntest -f /etc/shadow.${SUDO_USER:=${USER}} && mv /etc/shadow.${SUDO_USER:=${USER}} /etc/shadow\n"
  },
  {
    "path": "scriptbuilder/src/test/resources/test_adminaccess_params.sh",
    "content": "cat > /etc/sudoers <<-'END_OF_JCLOUDS_FILE'\n\tDefaults    env_reset\n\tDefaults    secure_path=\"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\"\n\troot ALL = (ALL) ALL\n\t%wheel ALL = (ALL) NOPASSWD:ALL\nEND_OF_JCLOUDS_FILE\nchmod 0440 /etc/sudoers\nmkdir -p /over/ridden\nchmod 0755 /over/ridden\ngetent group wheel || groupadd -f wheel\nuseradd -c 'foo' -s /bin/bash -g wheel -m  -d /over/ridden/foo -p 'crypt(bar)' foo\nmkdir -p /over/ridden/foo/.ssh\ncat >> /over/ridden/foo/.ssh/authorized_keys <<-'END_OF_JCLOUDS_FILE'\n\tfooPublicKey\nEND_OF_JCLOUDS_FILE\nchmod 600 /over/ridden/foo/.ssh/authorized_keys\nchown -R foo /over/ridden/foo/.ssh\nchown -R foo /over/ridden/foo\nexec 3<> /etc/ssh/sshd_config && awk -v TEXT=\"PasswordAuthentication no\nPermitRootLogin no\n\" 'BEGIN {print TEXT}{print}' /etc/ssh/sshd_config >&3\nhash service 2>&- && service ssh reload 2>&- || service sshd reload 2>&- || /etc/init.d/ssh* reload\nawk -v user=^${SUDO_USER:=${USER}}: -v password='crypt(0)' 'BEGIN { FS=OFS=\":\" } $0 ~ user { $2 = password } 1' /etc/shadow >/etc/shadow.${SUDO_USER:=${USER}}\ntest -f /etc/shadow.${SUDO_USER:=${USER}} && mv /etc/shadow.${SUDO_USER:=${USER}} /etc/shadow\n"
  },
  {
    "path": "scriptbuilder/src/test/resources/test_adminaccess_params_and_fullname.sh",
    "content": "cat > /etc/sudoers <<-'END_OF_JCLOUDS_FILE'\n\tDefaults    env_reset\n\tDefaults    secure_path=\"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\"\n\troot ALL = (ALL) ALL\n\t%wheel ALL = (ALL) NOPASSWD:ALL\nEND_OF_JCLOUDS_FILE\nchmod 0440 /etc/sudoers\nmkdir -p /over/ridden\nchmod 0755 /over/ridden\ngetent group wheel || groupadd -f wheel\nuseradd -c 'JClouds Foo' -s /bin/bash -g wheel -m  -d /over/ridden/foo -p 'crypt(bar)' foo\nmkdir -p /over/ridden/foo/.ssh\ncat >> /over/ridden/foo/.ssh/authorized_keys <<-'END_OF_JCLOUDS_FILE'\n\tfooPublicKey\nEND_OF_JCLOUDS_FILE\nchmod 600 /over/ridden/foo/.ssh/authorized_keys\nchown -R foo /over/ridden/foo/.ssh\nchown -R foo /over/ridden/foo\nexec 3<> /etc/ssh/sshd_config && awk -v TEXT=\"PasswordAuthentication no\nPermitRootLogin no\n\" 'BEGIN {print TEXT}{print}' /etc/ssh/sshd_config >&3\nhash service 2>&- && service ssh reload 2>&- || service sshd reload 2>&- || /etc/init.d/ssh* reload\nawk -v user=^${SUDO_USER:=${USER}}: -v password='crypt(0)' 'BEGIN { FS=OFS=\":\" } $0 ~ user { $2 = password } 1' /etc/shadow >/etc/shadow.${SUDO_USER:=${USER}}\ntest -f /etc/shadow.${SUDO_USER:=${USER}} && mv /etc/shadow.${SUDO_USER:=${USER}} /etc/shadow\n"
  },
  {
    "path": "scriptbuilder/src/test/resources/test_adminaccess_plainuser.sh",
    "content": "mkdir -p /home/users\nchmod 0755 /home/users\nuseradd -c 'defaultAdminUsername' -s /bin/bash -m  -d /home/users/defaultAdminUsername -p 'crypt(0)' defaultAdminUsername\nmkdir -p /home/users/defaultAdminUsername/.ssh\ncat >> /home/users/defaultAdminUsername/.ssh/authorized_keys <<-'END_OF_JCLOUDS_FILE'\n\tpublicKey\nEND_OF_JCLOUDS_FILE\nchmod 600 /home/users/defaultAdminUsername/.ssh/authorized_keys\nchown -R defaultAdminUsername /home/users/defaultAdminUsername/.ssh\nmkdir -p /home/users/defaultAdminUsername/.ssh\nrm /home/users/defaultAdminUsername/.ssh/id_rsa\ncat >> /home/users/defaultAdminUsername/.ssh/id_rsa <<-'END_OF_JCLOUDS_FILE'\n\tprivateKey\nEND_OF_JCLOUDS_FILE\nchmod 600 /home/users/defaultAdminUsername/.ssh/id_rsa\nchown -R defaultAdminUsername /home/users/defaultAdminUsername\n"
  },
  {
    "path": "scriptbuilder/src/test/resources/test_adminaccess_standard.sh",
    "content": "cat > /etc/sudoers <<-'END_OF_JCLOUDS_FILE'\n\tDefaults    env_reset\n\tDefaults    secure_path=\"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\"\n\troot ALL = (ALL) ALL\n\t%wheel ALL = (ALL) NOPASSWD:ALL\nEND_OF_JCLOUDS_FILE\nchmod 0440 /etc/sudoers\nmkdir -p /home/users\nchmod 0755 /home/users\ngetent group wheel || groupadd -f wheel\nuseradd -c 'defaultAdminUsername' -s /bin/bash -g wheel -m  -d /home/users/defaultAdminUsername -p 'crypt(0)' defaultAdminUsername\nmkdir -p /home/users/defaultAdminUsername/.ssh\ncat >> /home/users/defaultAdminUsername/.ssh/authorized_keys <<-'END_OF_JCLOUDS_FILE'\n\tpublicKey\nEND_OF_JCLOUDS_FILE\nchmod 600 /home/users/defaultAdminUsername/.ssh/authorized_keys\nchown -R defaultAdminUsername /home/users/defaultAdminUsername/.ssh\nchown -R defaultAdminUsername /home/users/defaultAdminUsername\nexec 3<> /etc/ssh/sshd_config && awk -v TEXT=\"PasswordAuthentication no\nPermitRootLogin no\n\" 'BEGIN {print TEXT}{print}' /etc/ssh/sshd_config >&3\nhash service 2>&- && service ssh reload 2>&- || service sshd reload 2>&- || /etc/init.d/ssh* reload\nawk -v user=^${SUDO_USER:=${USER}}: -v password='crypt(1)' 'BEGIN { FS=OFS=\":\" } $0 ~ user { $2 = password } 1' /etc/shadow >/etc/shadow.${SUDO_USER:=${USER}}\ntest -f /etc/shadow.${SUDO_USER:=${USER}} && mv /etc/shadow.${SUDO_USER:=${USER}} /etc/shadow\n"
  },
  {
    "path": "scriptbuilder/src/test/resources/test_ebs.sh",
    "content": "#!/bin/bash\nset +u\nshopt -s xpg_echo\nshopt -s expand_aliases\nunset PATH JAVA_HOME LD_LIBRARY_PATH\n#\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements.  See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License.  You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nfunction abort {\n   echo \"aborting: $@\" 1>&2\n   exit 1\n}\nfunction default {\n   export INSTANCE_NAME=\"mkebsboot\"\nexport INSTANCE_HOME=\"/tmp\"\nexport LOG_DIR=\"/tmp/logs\"\n   return $?\n}\nfunction mkebsboot {\n   export IMAGE_DIR=\"/mnt/tmp\"\nexport EBS_DEVICE=\"/dev/sdh\"\nexport EBS_MOUNT_POINT=\"/mnt/ebs\"\n   return $?\n}\n#\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements.  See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License.  You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nfunction findPid {\n   unset FOUND_PID;\n   [ $# -eq 1 ] || {\n      abort \"findPid requires a parameter of pattern to match\"\n      return 1\n   }\n   local PATTERN=\"$1\"; shift\n   local _FOUND=`ps auxwww|grep \"$PATTERN\"|grep -v \" $0\"|grep -v grep|grep -v $$|awk '{print $2}'`\n   [ -n \"$_FOUND\" ] && {\n      export FOUND_PID=$_FOUND\n      return 0\n   } || {\n      return 1\n   }\n}\n#\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements.  See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License.  You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nfunction forget {\n   unset FOUND_PID;\n   [ $# -eq 3 ] || {\n      abort \"forget requires parameters INSTANCE_NAME SCRIPT LOG_DIR\"\n      return 1\n   }\n   local INSTANCE_NAME=\"$1\"; shift\n   local SCRIPT=\"$1\"; shift\n   local LOG_DIR=\"$1\"; shift\n   mkdir -p $LOG_DIR\n   findPid $INSTANCE_NAME\n   [ -n \"$FOUND_PID\" -a -f $LOG_DIR/stdout.log ] && {\n      echo $INSTANCE_NAME already running pid $FOUND_PID\n      return 1;\n   } || {\n      nohup $SCRIPT >$LOG_DIR/stdout.log 2>$LOG_DIR/stderr.log &\n      RETURN=$?\n      # this is generally followed by findPid, so we shouldn't exit \n      # immediately as the proc may not have registered in ps, yet\n      test $RETURN && sleep 1\n      return $RETURN;\n   }\n}\nexport PATH=/usr/ucb/bin:/bin:/sbin:/usr/bin:/usr/sbin\ncase $1 in\ninit)\n   default || exit 1\n   mkebsboot || exit 1\n   mkdir -p $INSTANCE_HOME\n   \n   # create runscript header\n   cat > $INSTANCE_HOME/mkebsboot.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\t#!/bin/bash\n\tset +u\n\tshopt -s xpg_echo\n\tshopt -s expand_aliases\n\t\n\tPROMPT_COMMAND='echo -ne \\\"\\033]0;mkebsboot\\007\\\"'\n\texport PATH=/usr/ucb/bin:/bin:/sbin:/usr/bin:/usr/sbin\n\n\texport INSTANCE_NAME='mkebsboot'\nEND_OF_JCLOUDS_SCRIPT\n   cat >> $INSTANCE_HOME/mkebsboot.sh <<-END_OF_JCLOUDS_SCRIPT\n\texport IMAGE_DIR='$IMAGE_DIR'\n\texport EBS_DEVICE='$EBS_DEVICE'\n\texport EBS_MOUNT_POINT='$EBS_MOUNT_POINT'\n\texport INSTANCE_NAME='$INSTANCE_NAME'\n\texport INSTANCE_HOME='$INSTANCE_HOME'\n\texport LOG_DIR='$LOG_DIR'\nEND_OF_JCLOUDS_SCRIPT\n   \n   # add desired commands from the user\n   cat >> $INSTANCE_HOME/mkebsboot.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\tcd $INSTANCE_HOME\n\techo creating a filesystem and mounting the ebs volume\n\tmkdir -p $IMAGE_DIR $EBS_MOUNT_POINT\n\trm -rf $IMAGE_DIR/*\n\tyes| mkfs -t ext3 $EBS_DEVICE 2>&-\n\tmount $EBS_DEVICE $EBS_MOUNT_POINT\n\techo making a local working copy of the boot disk\n\trsync -ax --exclude /ubuntu/.bash_history --exclude /home/*/.bash_history --exclude /etc/ssh/ssh_host_* --exclude /etc/ssh/moduli --exclude /etc/udev/rules.d/*persistent-net.rules --exclude /var/lib/ec2/* --exclude=/mnt/* --exclude=/proc/* --exclude=/tmp/* --exclude=/dev/log / $IMAGE_DIR\n\techo preparing the local working copy\n\ttouch $IMAGE_DIR/etc/init.d/ec2-init-user-data\n\techo copying the local working copy to the ebs mount\n\tcd $IMAGE_DIR\n\ttar -cSf - * | tar xf - -C $EBS_MOUNT_POINT\n\techo size of ebs\n\tdu -sk $EBS_MOUNT_POINT\n\techo size of source\n\tdu -sk $IMAGE_DIR\n\trm -rf $IMAGE_DIR/*\n\tumount $EBS_MOUNT_POINT\n\techo ----COMPLETE----\nEND_OF_JCLOUDS_SCRIPT\n   \n   # add runscript footer\n   cat >> $INSTANCE_HOME/mkebsboot.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\texit $?\n\t\nEND_OF_JCLOUDS_SCRIPT\n   \n   chmod u+x $INSTANCE_HOME/mkebsboot.sh\n   ;;\nstatus)\n   default || exit 1\n   findPid $INSTANCE_NAME || exit 1\n   echo $FOUND_PID\n   ;;\nstop)\n   default || exit 1\n   findPid $INSTANCE_NAME || exit 1\n   [ -n \"$FOUND_PID\" ]  && {\n      echo stopping $FOUND_PID\n      kill -9 $FOUND_PID\n   }\n   ;;\nstart)\n   default || exit 1\n   forget $INSTANCE_NAME $INSTANCE_HOME/$INSTANCE_NAME.sh $LOG_DIR || exit 1\n   ;;\ntail)\n   default || exit 1\n   tail $LOG_DIR/stdout.log\n   ;;\ntailerr)\n   default || exit 1\n   tail $LOG_DIR/stderr.log\n   ;;\nrun)\n   default || exit 1\n   $INSTANCE_HOME/$INSTANCE_NAME.sh\n   ;;\nesac\nexit $?\n"
  },
  {
    "path": "scriptbuilder/src/test/resources/test_env.cmd",
    "content": "@rem Env file: please do not confuse people by making this executable\r\n@rem\r\n@rem Example usage to set a variable\r\n@rem\r\n@rem set MAVEN_OPTS=-Xms64m -Xmx128m\r\n\r\nset JAVA_HOME=/apps/jdk1.6\r\n\r\n@rem Please retain this statement so that the script can be validated\r\nexit /b 0\r\n"
  },
  {
    "path": "scriptbuilder/src/test/resources/test_env.sh",
    "content": "# Env file: please do not confuse people by making this executable\n#\n# Example usage to set a variable\n#\n# export MAVEN_OPTS=\"-Xms64m -Xmx128m\"\n\nexport JAVA_HOME=\"/apps/jdk1.6\"\n\n# Please retain this statement so that the script can be validated\nreturn 0\n"
  },
  {
    "path": "scriptbuilder/src/test/resources/test_find_pid.cmd",
    "content": "@echo off\r\nset PATH=\r\nset JAVA_HOME=\r\nset PATH=\r\nGOTO FUNCTION_END\r\n:abort\r\n   echo aborting: %EXCEPTION%\r\n   exit /b 1\r\n:findPid\r\n   set FOUND_PID=\r\n   set _expression=%1\r\n   shift\r\n   set FIND_PROCESS=TASKLIST /FI \"WINDOWTITLE eq %_expression%\" /NH\r\n   FOR /F \"usebackq tokens=2 delims= \" %%A IN (`cmd /c \"%FIND_PROCESS% 2>NUL\"`) DO (\r\n      SET FOUND_PID=%%A\r\n   )\r\n   if defined FOUND_PID (\r\n      exit /b 0\r\n   ) else (\r\n      set EXCEPTION=%_expression% not found\r\n      exit /b 1\r\n   )\r\n:FUNCTION_END\r\nset PATH=c:\\windows\\;C:\\windows\\system32;c:\\windows\\system32\\wbem\r\ncall :findPid %*\r\nif errorlevel 1 goto abort\r\necho %FOUND_PID%\r\nexit /b 0\r\n"
  },
  {
    "path": "scriptbuilder/src/test/resources/test_find_pid.sh",
    "content": "#!/bin/bash\nset +u\nshopt -s xpg_echo\nshopt -s expand_aliases\nunset PATH JAVA_HOME LD_LIBRARY_PATH\nfunction abort {\n   echo \"aborting: $@\" 1>&2\n   exit 1\n}\nfunction findPid {\n   unset FOUND_PID;\n   [ $# -eq 1 ] || {\n      abort \"findPid requires a parameter of pattern to match\"\n      return 1\n   }\n   local PATTERN=\"$1\"; shift\n   local _FOUND=`ps auxwww|grep \"$PATTERN\"|grep -v \" $0\"|grep -v grep|grep -v $$|awk '{print $2}'`\n   [ -n \"$_FOUND\" ] && {\n      export FOUND_PID=$_FOUND\n      return 0\n   } || {\n      return 1\n   }\n}\nexport PATH=/usr/ucb/bin:/bin:/sbin:/usr/bin:/usr/sbin\nfindPid $@ || exit 1\necho $FOUND_PID\nexit $?\n"
  },
  {
    "path": "scriptbuilder/src/test/resources/test_init.sh",
    "content": "#!/bin/bash\nset +u\nshopt -s xpg_echo\nshopt -s expand_aliases\nunset PATH JAVA_HOME LD_LIBRARY_PATH\nfunction abort {\n   echo \"aborting: $@\" 1>&2\n   exit 1\n}\nfunction default {\n   export INSTANCE_NAME=\"mkebsboot\"\nexport INSTANCE_HOME=\"/mnt/tmp\"\nexport LOG_DIR=\"/mnt/tmp\"\n   return $?\n}\nfunction mkebsboot {\n   export TMP_DIR=\"/mnt/tmp\"\n   return $?\n}\nfunction findPid {\n   unset FOUND_PID;\n   [ $# -eq 1 ] || {\n      abort \"findPid requires a parameter of pattern to match\"\n      return 1\n   }\n   local PATTERN=\"$1\"; shift\n   local _FOUND=`ps auxwww|grep \"$PATTERN\"|grep -v \" $0\"|grep -v grep|grep -v $$|awk '{print $2}'`\n   [ -n \"$_FOUND\" ] && {\n      export FOUND_PID=$_FOUND\n      return 0\n   } || {\n      return 1\n   }\n}\nfunction forget {\n   unset FOUND_PID;\n   [ $# -eq 3 ] || {\n      abort \"forget requires parameters INSTANCE_NAME SCRIPT LOG_DIR\"\n      return 1\n   }\n   local INSTANCE_NAME=\"$1\"; shift\n   local SCRIPT=\"$1\"; shift\n   local LOG_DIR=\"$1\"; shift\n   mkdir -p $LOG_DIR\n   findPid $INSTANCE_NAME\n   [ -n \"$FOUND_PID\" -a -f $LOG_DIR/stdout.log ] && {\n      echo $INSTANCE_NAME already running pid $FOUND_PID\n      return 1;\n   } || {\n      nohup $SCRIPT >$LOG_DIR/stdout.log 2>$LOG_DIR/stderr.log &\n      RETURN=$?\n      # this is generally followed by findPid, so we shouldn't exit \n      # immediately as the proc may not have registered in ps, yet\n      test $RETURN && sleep 1\n      return $RETURN;\n   }\n}\nexport PATH=/usr/ucb/bin:/bin:/sbin:/usr/bin:/usr/sbin\ncase $1 in\ninit)\n   default || exit 1\n   mkebsboot || exit 1\n   mkdir -p $INSTANCE_HOME\n   \n   # create runscript header\n   cat > $INSTANCE_HOME/mkebsboot.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\t#!/bin/bash\n\tset +u\n\tshopt -s xpg_echo\n\tshopt -s expand_aliases\n\t\n\tPROMPT_COMMAND='echo -ne \\\"\\033]0;mkebsboot\\007\\\"'\n\texport PATH=/usr/ucb/bin:/bin:/sbin:/usr/bin:/usr/sbin\n\n\texport INSTANCE_NAME='mkebsboot'\nEND_OF_JCLOUDS_SCRIPT\n   cat >> $INSTANCE_HOME/mkebsboot.sh <<-END_OF_JCLOUDS_SCRIPT\n\texport TMP_DIR='$TMP_DIR'\n\texport INSTANCE_NAME='$INSTANCE_NAME'\n\texport INSTANCE_HOME='$INSTANCE_HOME'\n\texport LOG_DIR='$LOG_DIR'\nEND_OF_JCLOUDS_SCRIPT\n   \n   # add desired commands from the user\n   cat >> $INSTANCE_HOME/mkebsboot.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\tcd $INSTANCE_HOME\n\tcat >> /tmp/$USER/scripttest/temp.txt <<-'END_OF_JCLOUDS_FILE'\n\t\thello world\n\tEND_OF_JCLOUDS_FILE\n\t\n\tfind /\n\t\nEND_OF_JCLOUDS_SCRIPT\n   \n   # add runscript footer\n   cat >> $INSTANCE_HOME/mkebsboot.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\texit $?\n\t\nEND_OF_JCLOUDS_SCRIPT\n   \n   chmod u+x $INSTANCE_HOME/mkebsboot.sh\n   ;;\nstatus)\n   default || exit 1\n   findPid $INSTANCE_NAME || exit 1\n   echo $FOUND_PID\n   ;;\nstop)\n   default || exit 1\n   findPid $INSTANCE_NAME || exit 1\n   [ -n \"$FOUND_PID\" ]  && {\n      echo stopping $FOUND_PID\n      kill -9 $FOUND_PID\n   }\n   ;;\nstart)\n   default || exit 1\n   forget $INSTANCE_NAME $INSTANCE_HOME/$INSTANCE_NAME.sh $LOG_DIR || exit 1\n   ;;\ntail)\n   default || exit 1\n   tail $LOG_DIR/stdout.log\n   ;;\ntailerr)\n   default || exit 1\n   tail $LOG_DIR/stderr.log\n   ;;\nrun)\n   default || exit 1\n   $INSTANCE_HOME/$INSTANCE_NAME.sh\n   ;;\nesac\nexit $?\n"
  },
  {
    "path": "scriptbuilder/src/test/resources/test_init_script.sh",
    "content": "#!/bin/bash\nset +u\nshopt -s xpg_echo\nshopt -s expand_aliases\nunset PATH JAVA_HOME LD_LIBRARY_PATH\nfunction abort {\n   echo \"aborting: $@\" 1>&2\n   exit 1\n}\nfunction default {\n   export INSTANCE_NAME=\"testcall\"\nexport INSTANCE_HOME=\"/tmp/$INSTANCE_NAME\"\nexport LOG_DIR=\"$INSTANCE_HOME\"\n   return $?\n}\nfunction testcall {\n      return $?\n}\nfunction findPid {\n   unset FOUND_PID;\n   [ $# -eq 1 ] || {\n      abort \"findPid requires a parameter of pattern to match\"\n      return 1\n   }\n   local PATTERN=\"$1\"; shift\n   local _FOUND=`ps auxwww|grep \"$PATTERN\"|grep -v \" $0\"|grep -v grep|grep -v $$|awk '{print $2}'`\n   [ -n \"$_FOUND\" ] && {\n      export FOUND_PID=$_FOUND\n      return 0\n   } || {\n      return 1\n   }\n}\nfunction forget {\n   unset FOUND_PID;\n   [ $# -eq 3 ] || {\n      abort \"forget requires parameters INSTANCE_NAME SCRIPT LOG_DIR\"\n      return 1\n   }\n   local INSTANCE_NAME=\"$1\"; shift\n   local SCRIPT=\"$1\"; shift\n   local LOG_DIR=\"$1\"; shift\n   mkdir -p $LOG_DIR\n   findPid $INSTANCE_NAME\n   [ -n \"$FOUND_PID\" -a -f $LOG_DIR/stdout.log ] && {\n      echo $INSTANCE_NAME already running pid $FOUND_PID\n      return 1;\n   } || {\n      nohup $SCRIPT >$LOG_DIR/stdout.log 2>$LOG_DIR/stderr.log &\n      RETURN=$?\n      # this is generally followed by findPid, so we shouldn't exit \n      # immediately as the proc may not have registered in ps, yet\n      test $RETURN && sleep 1\n      return $RETURN;\n   }\n}\nexport PATH=/usr/ucb/bin:/bin:/sbin:/usr/bin:/usr/sbin\ncase $1 in\ninit)\n   default || exit 1\n   testcall || exit 1\n   echo hello\n   mkdir -p $INSTANCE_HOME\n   \n   # create runscript header\n   cat > $INSTANCE_HOME/testcall.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\t#!/bin/bash\n\tset +u\n\tshopt -s xpg_echo\n\tshopt -s expand_aliases\n\t\n\tPROMPT_COMMAND='echo -ne \\\"\\033]0;testcall\\007\\\"'\n\texport PATH=/usr/ucb/bin:/bin:/sbin:/usr/bin:/usr/sbin\n\n\texport INSTANCE_NAME='testcall'\nEND_OF_JCLOUDS_SCRIPT\n   cat >> $INSTANCE_HOME/testcall.sh <<-END_OF_JCLOUDS_SCRIPT\n\texport INSTANCE_NAME='$INSTANCE_NAME'\n\texport INSTANCE_HOME='$INSTANCE_HOME'\n\texport LOG_DIR='$LOG_DIR'\nEND_OF_JCLOUDS_SCRIPT\n   cat >> $INSTANCE_HOME/testcall.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\tfunction abort {\n   echo \"aborting: $@\" 1>&2\n   exit 1\n}\nfunction sourceEnvFile {\n   [ $# -eq 1 ] || {\n      abort \"sourceEnvFile requires a parameter of the file to source\"\n      return 1\n   }\n   local ENV_FILE=\"$1\"; shift\n   . \"$ENV_FILE\" || {\n      abort \"Please append 'return 0' to the end of '$ENV_FILE'\"\n      return 1\n   }\n   return 0\n}\n\nEND_OF_JCLOUDS_SCRIPT\n   \n   # add desired commands from the user\n   cat >> $INSTANCE_HOME/testcall.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\tcd $INSTANCE_HOME\n\trm -f $INSTANCE_HOME/rc\n\ttrap 'echo $?>$INSTANCE_HOME/rc' 0 1 2 3 15\n\tsourceEnvFile foo || exit 1\n\t\n\tfind /\n\t\nEND_OF_JCLOUDS_SCRIPT\n   \n   # add runscript footer\n   cat >> $INSTANCE_HOME/testcall.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\texit $?\n\t\nEND_OF_JCLOUDS_SCRIPT\n   \n   chmod u+x $INSTANCE_HOME/testcall.sh\n   ;;\nstatus)\n   default || exit 1\n   findPid $INSTANCE_NAME || exit 1\n   echo $FOUND_PID\n   ;;\nstop)\n   default || exit 1\n   findPid $INSTANCE_NAME || exit 1\n   [ -n \"$FOUND_PID\" ]  && {\n      echo stopping $FOUND_PID\n      kill -9 $FOUND_PID\n   }\n   ;;\nstart)\n   default || exit 1\n   forget $INSTANCE_NAME $INSTANCE_HOME/$INSTANCE_NAME.sh $LOG_DIR || exit 1\n   ;;\nstdout)\n   default || exit 1\n   cat $LOG_DIR/stdout.log\n   ;;\nstderr)\n   default || exit 1\n   cat $LOG_DIR/stderr.log\n   ;;\nexitstatus)\n   default || exit 1\n   [ -f $LOG_DIR/rc ] && cat $LOG_DIR/rc;;\ntail)\n   default || exit 1\n   tail $LOG_DIR/stdout.log\n   ;;\ntailerr)\n   default || exit 1\n   tail $LOG_DIR/stderr.log\n   ;;\nrun)\n   default || exit 1\n   $INSTANCE_HOME/$INSTANCE_NAME.sh\n   ;;\nesac\nexit $?\n"
  },
  {
    "path": "scriptbuilder/src/test/resources/test_install_chef_gems_scriptbuilder.sh",
    "content": "#!/bin/bash\nset +u\nshopt -s xpg_echo\nshopt -s expand_aliases\nunset PATH JAVA_HOME LD_LIBRARY_PATH\nfunction abort {\n   echo \"aborting: $@\" 1>&2\n   exit 1\n}\nfunction default {\n   export INSTANCE_NAME=\"install_chef_gems\"\nexport INSTANCE_HOME=\"/tmp/$INSTANCE_NAME\"\nexport LOG_DIR=\"$INSTANCE_HOME\"\n   return $?\n}\nfunction install_chef_gems {\n      return $?\n}\nfunction findPid {\n   unset FOUND_PID;\n   [ $# -eq 1 ] || {\n      abort \"findPid requires a parameter of pattern to match\"\n      return 1\n   }\n   local PATTERN=\"$1\"; shift\n   local _FOUND=`ps auxwww|grep \"$PATTERN\"|grep -v \" $0\"|grep -v grep|grep -v $$|awk '{print $2}'`\n   [ -n \"$_FOUND\" ] && {\n      export FOUND_PID=$_FOUND\n      return 0\n   } || {\n      return 1\n   }\n}\nfunction forget {\n   unset FOUND_PID;\n   [ $# -eq 3 ] || {\n      abort \"forget requires parameters INSTANCE_NAME SCRIPT LOG_DIR\"\n      return 1\n   }\n   local INSTANCE_NAME=\"$1\"; shift\n   local SCRIPT=\"$1\"; shift\n   local LOG_DIR=\"$1\"; shift\n   mkdir -p $LOG_DIR\n   findPid $INSTANCE_NAME\n   [ -n \"$FOUND_PID\" -a -f $LOG_DIR/stdout.log ] && {\n      echo $INSTANCE_NAME already running pid $FOUND_PID\n      return 1;\n   } || {\n      nohup $SCRIPT >$LOG_DIR/stdout.log 2>$LOG_DIR/stderr.log &\n      RETURN=$?\n      # this is generally followed by findPid, so we shouldn't exit \n      # immediately as the proc may not have registered in ps, yet\n      test $RETURN && sleep 1\n      return $RETURN;\n   }\n}\nexport PATH=/usr/ucb/bin:/bin:/sbin:/usr/bin:/usr/sbin\ncase $1 in\ninit)\n   default || exit 1\n   install_chef_gems || exit 1\n   mkdir -p $INSTANCE_HOME\n   \n   # create runscript header\n   cat > $INSTANCE_HOME/install_chef_gems.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\t#!/bin/bash\n\tset +u\n\tshopt -s xpg_echo\n\tshopt -s expand_aliases\n\t\n\tPROMPT_COMMAND='echo -ne \\\"\\033]0;install_chef_gems\\007\\\"'\n\texport PATH=/usr/ucb/bin:/bin:/sbin:/usr/bin:/usr/sbin\n\n\texport INSTANCE_NAME='install_chef_gems'\nEND_OF_JCLOUDS_SCRIPT\n   cat >> $INSTANCE_HOME/install_chef_gems.sh <<-END_OF_JCLOUDS_SCRIPT\n\texport INSTANCE_NAME='$INSTANCE_NAME'\n\texport INSTANCE_HOME='$INSTANCE_HOME'\n\texport LOG_DIR='$LOG_DIR'\nEND_OF_JCLOUDS_SCRIPT\n   \n   # add desired commands from the user\n   cat >> $INSTANCE_HOME/install_chef_gems.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\tcd $INSTANCE_HOME\n\trm -f $INSTANCE_HOME/rc\n\ttrap 'echo $?>$INSTANCE_HOME/rc' 0 1 2 3 15\n\tgem install chef --no-rdoc --no-ri\n\t\nEND_OF_JCLOUDS_SCRIPT\n   \n   # add runscript footer\n   cat >> $INSTANCE_HOME/install_chef_gems.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\texit $?\n\t\nEND_OF_JCLOUDS_SCRIPT\n   \n   chmod u+x $INSTANCE_HOME/install_chef_gems.sh\n   ;;\nstatus)\n   default || exit 1\n   findPid $INSTANCE_NAME || exit 1\n   echo $FOUND_PID\n   ;;\nstop)\n   default || exit 1\n   findPid $INSTANCE_NAME || exit 1\n   [ -n \"$FOUND_PID\" ]  && {\n      echo stopping $FOUND_PID\n      kill -9 $FOUND_PID\n   }\n   ;;\nstart)\n   default || exit 1\n   forget $INSTANCE_NAME $INSTANCE_HOME/$INSTANCE_NAME.sh $LOG_DIR || exit 1\n   ;;\nstdout)\n   default || exit 1\n   cat $LOG_DIR/stdout.log\n   ;;\nstderr)\n   default || exit 1\n   cat $LOG_DIR/stderr.log\n   ;;\nexitstatus)\n   default || exit 1\n   [ -f $LOG_DIR/rc ] && cat $LOG_DIR/rc;;\ntail)\n   default || exit 1\n   tail $LOG_DIR/stdout.log\n   ;;\ntailerr)\n   default || exit 1\n   tail $LOG_DIR/stderr.log\n   ;;\nrun)\n   default || exit 1\n   $INSTANCE_HOME/$INSTANCE_NAME.sh\n   ;;\nesac\nexit $?\n"
  },
  {
    "path": "scriptbuilder/src/test/resources/test_install_chef_omnibus_scriptbuilder.sh",
    "content": "#!/bin/bash\nset +u\nshopt -s xpg_echo\nshopt -s expand_aliases\nunset PATH JAVA_HOME LD_LIBRARY_PATH\nfunction abort {\n   echo \"aborting: $@\" 1>&2\n   exit 1\n}\nfunction default {\n   export INSTANCE_NAME=\"install_chef_omnibus\"\nexport INSTANCE_HOME=\"/tmp/$INSTANCE_NAME\"\nexport LOG_DIR=\"$INSTANCE_HOME\"\n   return $?\n}\nfunction install_chef_omnibus {\n      return $?\n}\nfunction findPid {\n   unset FOUND_PID;\n   [ $# -eq 1 ] || {\n      abort \"findPid requires a parameter of pattern to match\"\n      return 1\n   }\n   local PATTERN=\"$1\"; shift\n   local _FOUND=`ps auxwww|grep \"$PATTERN\"|grep -v \" $0\"|grep -v grep|grep -v $$|awk '{print $2}'`\n   [ -n \"$_FOUND\" ] && {\n      export FOUND_PID=$_FOUND\n      return 0\n   } || {\n      return 1\n   }\n}\nfunction forget {\n   unset FOUND_PID;\n   [ $# -eq 3 ] || {\n      abort \"forget requires parameters INSTANCE_NAME SCRIPT LOG_DIR\"\n      return 1\n   }\n   local INSTANCE_NAME=\"$1\"; shift\n   local SCRIPT=\"$1\"; shift\n   local LOG_DIR=\"$1\"; shift\n   mkdir -p $LOG_DIR\n   findPid $INSTANCE_NAME\n   [ -n \"$FOUND_PID\" -a -f $LOG_DIR/stdout.log ] && {\n      echo $INSTANCE_NAME already running pid $FOUND_PID\n      return 1;\n   } || {\n      nohup $SCRIPT >$LOG_DIR/stdout.log 2>$LOG_DIR/stderr.log &\n      RETURN=$?\n      # this is generally followed by findPid, so we shouldn't exit \n      # immediately as the proc may not have registered in ps, yet\n      test $RETURN && sleep 1\n      return $RETURN;\n   }\n}\nexport PATH=/usr/ucb/bin:/bin:/sbin:/usr/bin:/usr/sbin\ncase $1 in\ninit)\n   default || exit 1\n   install_chef_omnibus || exit 1\n   mkdir -p $INSTANCE_HOME\n   \n   # create runscript header\n   cat > $INSTANCE_HOME/install_chef_omnibus.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\t#!/bin/bash\n\tset +u\n\tshopt -s xpg_echo\n\tshopt -s expand_aliases\n\t\n\tPROMPT_COMMAND='echo -ne \\\"\\033]0;install_chef_omnibus\\007\\\"'\n\texport PATH=/usr/ucb/bin:/bin:/sbin:/usr/bin:/usr/sbin\n\n\texport INSTANCE_NAME='install_chef_omnibus'\nEND_OF_JCLOUDS_SCRIPT\n   cat >> $INSTANCE_HOME/install_chef_omnibus.sh <<-END_OF_JCLOUDS_SCRIPT\n\texport INSTANCE_NAME='$INSTANCE_NAME'\n\texport INSTANCE_HOME='$INSTANCE_HOME'\n\texport LOG_DIR='$LOG_DIR'\nEND_OF_JCLOUDS_SCRIPT\n   cat >> $INSTANCE_HOME/install_chef_omnibus.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\tfunction abort {\n   echo \"aborting: $@\" 1>&2\n   exit 1\n}\nalias apt-get-update=\"apt-get update -qq\"\nalias apt-get-install=\"apt-get install -f -y -qq --force-yes\"\nalias yum-install=\"yum --quiet --nogpgcheck -y install\"\n\nfunction ensure_cmd_or_install_package_apt(){\n  local cmd=$1\n  shift\n  local pkg=$*\n  \n  hash $cmd 2>/dev/null || ( apt-get-update && apt-get-install $pkg )\n}\n\nfunction ensure_cmd_or_install_package_yum(){\n  local cmd=$1\n  shift\n  local pkg=$*\n  hash $cmd 2>/dev/null || yum-install $pkg\n}\n\nfunction ensure_netutils_apt() {\n  ensure_cmd_or_install_package_apt nslookup dnsutils\n  ensure_cmd_or_install_package_apt curl curl\n}\n\nfunction ensure_netutils_yum() {\n  ensure_cmd_or_install_package_yum nslookup bind-utils\n  ensure_cmd_or_install_package_yum curl curl\n}\n\n# most network services require that the hostname is in\n# the /etc/hosts file, or they won't operate\nfunction ensure_hostname_in_hosts() {\n  [ -n \"$SSH_CONNECTION\" ] && {\n    local ipaddr=`echo $SSH_CONNECTION | awk '{print $3}'`\n  } || {\n    local ipaddr=`hostname -i`\n  }\n  # NOTE: we blindly trust existing hostname settings in /etc/hosts\n  egrep -q `hostname -s` /etc/hosts || echo \"$ipaddr `hostname -f` `hostname -s`\" >> /etc/hosts\n}\n\n# download locations for many services are at public dns\nfunction ensure_can_resolve_public_dns() {\n  nslookup yahoo.com | grep yahoo.com > /dev/null || echo nameserver 208.67.222.222 >> /etc/resolv.conf\n}\n\nfunction setupPublicCurl() {\n  ensure_hostname_in_hosts\n  if which dpkg &> /dev/null; then\n    ensure_netutils_apt\n  elif which rpm &> /dev/null; then\n    ensure_netutils_yum\n  else\n    abort \"we only support apt-get and yum right now... please contribute!\"\n    return 1\n  fi\n  ensure_can_resolve_public_dns\n  return 0  \n}\n\nEND_OF_JCLOUDS_SCRIPT\n   \n   # add desired commands from the user\n   cat >> $INSTANCE_HOME/install_chef_omnibus.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\tcd $INSTANCE_HOME\n\trm -f $INSTANCE_HOME/rc\n\ttrap 'echo $?>$INSTANCE_HOME/rc' 0 1 2 3 15\n\tsetupPublicCurl || exit 1\n\t\n\tcurl -q -s -S -L --connect-timeout 10 --max-time 600 --retry 20 -X GET  https://www.opscode.com/chef/install.sh |(bash)\n\t\nEND_OF_JCLOUDS_SCRIPT\n   \n   # add runscript footer\n   cat >> $INSTANCE_HOME/install_chef_omnibus.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\texit $?\n\t\nEND_OF_JCLOUDS_SCRIPT\n   \n   chmod u+x $INSTANCE_HOME/install_chef_omnibus.sh\n   ;;\nstatus)\n   default || exit 1\n   findPid $INSTANCE_NAME || exit 1\n   echo $FOUND_PID\n   ;;\nstop)\n   default || exit 1\n   findPid $INSTANCE_NAME || exit 1\n   [ -n \"$FOUND_PID\" ]  && {\n      echo stopping $FOUND_PID\n      kill -9 $FOUND_PID\n   }\n   ;;\nstart)\n   default || exit 1\n   forget $INSTANCE_NAME $INSTANCE_HOME/$INSTANCE_NAME.sh $LOG_DIR || exit 1\n   ;;\nstdout)\n   default || exit 1\n   cat $LOG_DIR/stdout.log\n   ;;\nstderr)\n   default || exit 1\n   cat $LOG_DIR/stderr.log\n   ;;\nexitstatus)\n   default || exit 1\n   [ -f $LOG_DIR/rc ] && cat $LOG_DIR/rc;;\ntail)\n   default || exit 1\n   tail $LOG_DIR/stdout.log\n   ;;\ntailerr)\n   default || exit 1\n   tail $LOG_DIR/stderr.log\n   ;;\nrun)\n   default || exit 1\n   $INSTANCE_HOME/$INSTANCE_NAME.sh\n   ;;\nesac\nexit $?\n"
  },
  {
    "path": "scriptbuilder/src/test/resources/test_install_chef_version_omnibus_scriptbuilder.sh",
    "content": "#!/bin/bash\nset +u\nshopt -s xpg_echo\nshopt -s expand_aliases\nunset PATH JAVA_HOME LD_LIBRARY_PATH\nfunction abort {\n   echo \"aborting: $@\" 1>&2\n   exit 1\n}\nfunction default {\n   export INSTANCE_NAME=\"install_chef_omnibus\"\nexport INSTANCE_HOME=\"/tmp/$INSTANCE_NAME\"\nexport LOG_DIR=\"$INSTANCE_HOME\"\n   return $?\n}\nfunction install_chef_omnibus {\n      return $?\n}\nfunction findPid {\n   unset FOUND_PID;\n   [ $# -eq 1 ] || {\n      abort \"findPid requires a parameter of pattern to match\"\n      return 1\n   }\n   local PATTERN=\"$1\"; shift\n   local _FOUND=`ps auxwww|grep \"$PATTERN\"|grep -v \" $0\"|grep -v grep|grep -v $$|awk '{print $2}'`\n   [ -n \"$_FOUND\" ] && {\n      export FOUND_PID=$_FOUND\n      return 0\n   } || {\n      return 1\n   }\n}\nfunction forget {\n   unset FOUND_PID;\n   [ $# -eq 3 ] || {\n      abort \"forget requires parameters INSTANCE_NAME SCRIPT LOG_DIR\"\n      return 1\n   }\n   local INSTANCE_NAME=\"$1\"; shift\n   local SCRIPT=\"$1\"; shift\n   local LOG_DIR=\"$1\"; shift\n   mkdir -p $LOG_DIR\n   findPid $INSTANCE_NAME\n   [ -n \"$FOUND_PID\" -a -f $LOG_DIR/stdout.log ] && {\n      echo $INSTANCE_NAME already running pid $FOUND_PID\n      return 1;\n   } || {\n      nohup $SCRIPT >$LOG_DIR/stdout.log 2>$LOG_DIR/stderr.log &\n      RETURN=$?\n      # this is generally followed by findPid, so we shouldn't exit \n      # immediately as the proc may not have registered in ps, yet\n      test $RETURN && sleep 1\n      return $RETURN;\n   }\n}\nexport PATH=/usr/ucb/bin:/bin:/sbin:/usr/bin:/usr/sbin\ncase $1 in\ninit)\n   default || exit 1\n   install_chef_omnibus || exit 1\n   mkdir -p $INSTANCE_HOME\n   \n   # create runscript header\n   cat > $INSTANCE_HOME/install_chef_omnibus.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\t#!/bin/bash\n\tset +u\n\tshopt -s xpg_echo\n\tshopt -s expand_aliases\n\t\n\tPROMPT_COMMAND='echo -ne \\\"\\033]0;install_chef_omnibus\\007\\\"'\n\texport PATH=/usr/ucb/bin:/bin:/sbin:/usr/bin:/usr/sbin\n\n\texport INSTANCE_NAME='install_chef_omnibus'\nEND_OF_JCLOUDS_SCRIPT\n   cat >> $INSTANCE_HOME/install_chef_omnibus.sh <<-END_OF_JCLOUDS_SCRIPT\n\texport INSTANCE_NAME='$INSTANCE_NAME'\n\texport INSTANCE_HOME='$INSTANCE_HOME'\n\texport LOG_DIR='$LOG_DIR'\nEND_OF_JCLOUDS_SCRIPT\n   cat >> $INSTANCE_HOME/install_chef_omnibus.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\tfunction abort {\n   echo \"aborting: $@\" 1>&2\n   exit 1\n}\nalias apt-get-update=\"apt-get update -qq\"\nalias apt-get-install=\"apt-get install -f -y -qq --force-yes\"\nalias yum-install=\"yum --quiet --nogpgcheck -y install\"\n\nfunction ensure_cmd_or_install_package_apt(){\n  local cmd=$1\n  shift\n  local pkg=$*\n  \n  hash $cmd 2>/dev/null || ( apt-get-update && apt-get-install $pkg )\n}\n\nfunction ensure_cmd_or_install_package_yum(){\n  local cmd=$1\n  shift\n  local pkg=$*\n  hash $cmd 2>/dev/null || yum-install $pkg\n}\n\nfunction ensure_netutils_apt() {\n  ensure_cmd_or_install_package_apt nslookup dnsutils\n  ensure_cmd_or_install_package_apt curl curl\n}\n\nfunction ensure_netutils_yum() {\n  ensure_cmd_or_install_package_yum nslookup bind-utils\n  ensure_cmd_or_install_package_yum curl curl\n}\n\n# most network services require that the hostname is in\n# the /etc/hosts file, or they won't operate\nfunction ensure_hostname_in_hosts() {\n  [ -n \"$SSH_CONNECTION\" ] && {\n    local ipaddr=`echo $SSH_CONNECTION | awk '{print $3}'`\n  } || {\n    local ipaddr=`hostname -i`\n  }\n  # NOTE: we blindly trust existing hostname settings in /etc/hosts\n  egrep -q `hostname -s` /etc/hosts || echo \"$ipaddr `hostname -f` `hostname -s`\" >> /etc/hosts\n}\n\n# download locations for many services are at public dns\nfunction ensure_can_resolve_public_dns() {\n  nslookup yahoo.com | grep yahoo.com > /dev/null || echo nameserver 208.67.222.222 >> /etc/resolv.conf\n}\n\nfunction setupPublicCurl() {\n  ensure_hostname_in_hosts\n  if which dpkg &> /dev/null; then\n    ensure_netutils_apt\n  elif which rpm &> /dev/null; then\n    ensure_netutils_yum\n  else\n    abort \"we only support apt-get and yum right now... please contribute!\"\n    return 1\n  fi\n  ensure_can_resolve_public_dns\n  return 0  \n}\n\nEND_OF_JCLOUDS_SCRIPT\n   \n   # add desired commands from the user\n   cat >> $INSTANCE_HOME/install_chef_omnibus.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\tcd $INSTANCE_HOME\n\trm -f $INSTANCE_HOME/rc\n\ttrap 'echo $?>$INSTANCE_HOME/rc' 0 1 2 3 15\n\tsetupPublicCurl || exit 1\n\t\n\t(mkdir -p /tmp && cd /tmp && [ ! -f install-chef.sh ] && curl -q -s -S -L --connect-timeout 10 --max-time 600 --retry 20 -C - -X GET  https://www.opscode.com/chef/install.sh >install-chef.sh)\n\t\n\tsh /tmp/install-chef.sh -v 11.16.4\n\t\nEND_OF_JCLOUDS_SCRIPT\n   \n   # add runscript footer\n   cat >> $INSTANCE_HOME/install_chef_omnibus.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\texit $?\n\t\nEND_OF_JCLOUDS_SCRIPT\n   \n   chmod u+x $INSTANCE_HOME/install_chef_omnibus.sh\n   ;;\nstatus)\n   default || exit 1\n   findPid $INSTANCE_NAME || exit 1\n   echo $FOUND_PID\n   ;;\nstop)\n   default || exit 1\n   findPid $INSTANCE_NAME || exit 1\n   [ -n \"$FOUND_PID\" ]  && {\n      echo stopping $FOUND_PID\n      kill -9 $FOUND_PID\n   }\n   ;;\nstart)\n   default || exit 1\n   forget $INSTANCE_NAME $INSTANCE_HOME/$INSTANCE_NAME.sh $LOG_DIR || exit 1\n   ;;\nstdout)\n   default || exit 1\n   cat $LOG_DIR/stdout.log\n   ;;\nstderr)\n   default || exit 1\n   cat $LOG_DIR/stderr.log\n   ;;\nexitstatus)\n   default || exit 1\n   [ -f $LOG_DIR/rc ] && cat $LOG_DIR/rc;;\ntail)\n   default || exit 1\n   tail $LOG_DIR/stdout.log\n   ;;\ntailerr)\n   default || exit 1\n   tail $LOG_DIR/stderr.log\n   ;;\nrun)\n   default || exit 1\n   $INSTANCE_HOME/$INSTANCE_NAME.sh\n   ;;\nesac\nexit $?\n"
  },
  {
    "path": "scriptbuilder/src/test/resources/test_install_git_scriptbuilder.sh",
    "content": "#!/bin/bash\nset +u\nshopt -s xpg_echo\nshopt -s expand_aliases\nunset PATH JAVA_HOME LD_LIBRARY_PATH\nfunction abort {\n   echo \"aborting: $@\" 1>&2\n   exit 1\n}\nfunction default {\n   export INSTANCE_NAME=\"install_git\"\nexport INSTANCE_HOME=\"/tmp/$INSTANCE_NAME\"\nexport LOG_DIR=\"$INSTANCE_HOME\"\n   return $?\n}\nfunction install_git {\n      return $?\n}\nfunction findPid {\n   unset FOUND_PID;\n   [ $# -eq 1 ] || {\n      abort \"findPid requires a parameter of pattern to match\"\n      return 1\n   }\n   local PATTERN=\"$1\"; shift\n   local _FOUND=`ps auxwww|grep \"$PATTERN\"|grep -v \" $0\"|grep -v grep|grep -v $$|awk '{print $2}'`\n   [ -n \"$_FOUND\" ] && {\n      export FOUND_PID=$_FOUND\n      return 0\n   } || {\n      return 1\n   }\n}\nfunction forget {\n   unset FOUND_PID;\n   [ $# -eq 3 ] || {\n      abort \"forget requires parameters INSTANCE_NAME SCRIPT LOG_DIR\"\n      return 1\n   }\n   local INSTANCE_NAME=\"$1\"; shift\n   local SCRIPT=\"$1\"; shift\n   local LOG_DIR=\"$1\"; shift\n   mkdir -p $LOG_DIR\n   findPid $INSTANCE_NAME\n   [ -n \"$FOUND_PID\" -a -f $LOG_DIR/stdout.log ] && {\n      echo $INSTANCE_NAME already running pid $FOUND_PID\n      return 1;\n   } || {\n      nohup $SCRIPT >$LOG_DIR/stdout.log 2>$LOG_DIR/stderr.log &\n      RETURN=$?\n      # this is generally followed by findPid, so we shouldn't exit \n      # immediately as the proc may not have registered in ps, yet\n      test $RETURN && sleep 1\n      return $RETURN;\n   }\n}\nexport PATH=/usr/ucb/bin:/bin:/sbin:/usr/bin:/usr/sbin\ncase $1 in\ninit)\n   default || exit 1\n   install_git || exit 1\n   mkdir -p $INSTANCE_HOME\n   \n   # create runscript header\n   cat > $INSTANCE_HOME/install_git.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\t#!/bin/bash\n\tset +u\n\tshopt -s xpg_echo\n\tshopt -s expand_aliases\n\t\n\tPROMPT_COMMAND='echo -ne \\\"\\033]0;install_git\\007\\\"'\n\texport PATH=/usr/ucb/bin:/bin:/sbin:/usr/bin:/usr/sbin\n\n\texport INSTANCE_NAME='install_git'\nEND_OF_JCLOUDS_SCRIPT\n   cat >> $INSTANCE_HOME/install_git.sh <<-END_OF_JCLOUDS_SCRIPT\n\texport INSTANCE_NAME='$INSTANCE_NAME'\n\texport INSTANCE_HOME='$INSTANCE_HOME'\n\texport LOG_DIR='$LOG_DIR'\nEND_OF_JCLOUDS_SCRIPT\n   cat >> $INSTANCE_HOME/install_git.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\tfunction abort {\n   echo \"aborting: $@\" 1>&2\n   exit 1\n}\nalias apt-get-update=\"apt-get update -qq\"\nalias apt-get-install=\"apt-get install -f -y -qq --force-yes\"\nalias yum-install=\"yum --quiet --nogpgcheck -y install\"\n\nfunction ensure_cmd_or_install_package_apt(){\n  local cmd=$1\n  shift\n  local pkg=$*\n  \n  hash $cmd 2>/dev/null || ( apt-get-update && apt-get-install $pkg )\n}\n\nfunction ensure_cmd_or_install_package_yum(){\n  local cmd=$1\n  shift\n  local pkg=$*\n  hash $cmd 2>/dev/null || yum-install $pkg\n}\n\nfunction ensure_netutils_apt() {\n  ensure_cmd_or_install_package_apt nslookup dnsutils\n  ensure_cmd_or_install_package_apt curl curl\n}\n\nfunction ensure_netutils_yum() {\n  ensure_cmd_or_install_package_yum nslookup bind-utils\n  ensure_cmd_or_install_package_yum curl curl\n}\n\n# most network services require that the hostname is in\n# the /etc/hosts file, or they won't operate\nfunction ensure_hostname_in_hosts() {\n  [ -n \"$SSH_CONNECTION\" ] && {\n    local ipaddr=`echo $SSH_CONNECTION | awk '{print $3}'`\n  } || {\n    local ipaddr=`hostname -i`\n  }\n  # NOTE: we blindly trust existing hostname settings in /etc/hosts\n  egrep -q `hostname -s` /etc/hosts || echo \"$ipaddr `hostname -f` `hostname -s`\" >> /etc/hosts\n}\n\n# download locations for many services are at public dns\nfunction ensure_can_resolve_public_dns() {\n  nslookup yahoo.com | grep yahoo.com > /dev/null || echo nameserver 208.67.222.222 >> /etc/resolv.conf\n}\n\nfunction setupPublicCurl() {\n  ensure_hostname_in_hosts\n  if which dpkg &> /dev/null; then\n    ensure_netutils_apt\n  elif which rpm &> /dev/null; then\n    ensure_netutils_yum\n  else\n    abort \"we only support apt-get and yum right now... please contribute!\"\n    return 1\n  fi\n  ensure_can_resolve_public_dns\n  return 0  \n}\nfunction installGit() {\n  if which dpkg &> /dev/null; then\n    ensure_cmd_or_install_package_apt git git-core\n  elif which rpm &> /dev/null; then\n    case $(uname -r) in\n      *el5)\n        wget http://download.fedoraproject.org/pub/epel/5/$(uname -i)/epel-release-5-4.noarch.rpm &&\n        rpm -Uvh epel-release-5-4.noarch.rpm\n        rm -f epel-release-5-4.noarch.rpm;;\n      *el6)\n        wget http://download.fedoraproject.org/pub/epel/6/$(uname -i)/epel-release-6-7.noarch.rpm &&\n        rpm -Uvh epel-release-6-7.noarch.rpm \n        rm -f epel-release-6-7.noarch.rpm;; \n    esac\n    ensure_cmd_or_install_package_yum git git-core\n  else\n    abort \"we only support apt-get and yum right now... please contribute!\"\n    return 1\n  fi\n  return 0  \n}\n\nEND_OF_JCLOUDS_SCRIPT\n   \n   # add desired commands from the user\n   cat >> $INSTANCE_HOME/install_git.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\tcd $INSTANCE_HOME\n\trm -f $INSTANCE_HOME/rc\n\ttrap 'echo $?>$INSTANCE_HOME/rc' 0 1 2 3 15\n\tsetupPublicCurl || exit 1\n\t\n\tinstallGit || exit 1\n\t\nEND_OF_JCLOUDS_SCRIPT\n   \n   # add runscript footer\n   cat >> $INSTANCE_HOME/install_git.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\texit $?\n\t\nEND_OF_JCLOUDS_SCRIPT\n   \n   chmod u+x $INSTANCE_HOME/install_git.sh\n   ;;\nstatus)\n   default || exit 1\n   findPid $INSTANCE_NAME || exit 1\n   echo $FOUND_PID\n   ;;\nstop)\n   default || exit 1\n   findPid $INSTANCE_NAME || exit 1\n   [ -n \"$FOUND_PID\" ]  && {\n      echo stopping $FOUND_PID\n      kill -9 $FOUND_PID\n   }\n   ;;\nstart)\n   default || exit 1\n   forget $INSTANCE_NAME $INSTANCE_HOME/$INSTANCE_NAME.sh $LOG_DIR || exit 1\n   ;;\nstdout)\n   default || exit 1\n   cat $LOG_DIR/stdout.log\n   ;;\nstderr)\n   default || exit 1\n   cat $LOG_DIR/stderr.log\n   ;;\nexitstatus)\n   default || exit 1\n   [ -f $LOG_DIR/rc ] && cat $LOG_DIR/rc;;\ntail)\n   default || exit 1\n   tail $LOG_DIR/stdout.log\n   ;;\ntailerr)\n   default || exit 1\n   tail $LOG_DIR/stderr.log\n   ;;\nrun)\n   default || exit 1\n   $INSTANCE_HOME/$INSTANCE_NAME.sh\n   ;;\nesac\nexit $?\n"
  },
  {
    "path": "scriptbuilder/src/test/resources/test_install_jdk_scriptbuilder.sh",
    "content": "#!/bin/bash\nset +u\nshopt -s xpg_echo\nshopt -s expand_aliases\nunset PATH JAVA_HOME LD_LIBRARY_PATH\nfunction abort {\n   echo \"aborting: $@\" 1>&2\n   exit 1\n}\nfunction default {\n   export INSTANCE_NAME=\"install_jdk\"\nexport INSTANCE_HOME=\"/tmp/$INSTANCE_NAME\"\nexport LOG_DIR=\"$INSTANCE_HOME\"\n   return $?\n}\nfunction install_jdk {\n      return $?\n}\nfunction findPid {\n   unset FOUND_PID;\n   [ $# -eq 1 ] || {\n      abort \"findPid requires a parameter of pattern to match\"\n      return 1\n   }\n   local PATTERN=\"$1\"; shift\n   local _FOUND=`ps auxwww|grep \"$PATTERN\"|grep -v \" $0\"|grep -v grep|grep -v $$|awk '{print $2}'`\n   [ -n \"$_FOUND\" ] && {\n      export FOUND_PID=$_FOUND\n      return 0\n   } || {\n      return 1\n   }\n}\nfunction forget {\n   unset FOUND_PID;\n   [ $# -eq 3 ] || {\n      abort \"forget requires parameters INSTANCE_NAME SCRIPT LOG_DIR\"\n      return 1\n   }\n   local INSTANCE_NAME=\"$1\"; shift\n   local SCRIPT=\"$1\"; shift\n   local LOG_DIR=\"$1\"; shift\n   mkdir -p $LOG_DIR\n   findPid $INSTANCE_NAME\n   [ -n \"$FOUND_PID\" -a -f $LOG_DIR/stdout.log ] && {\n      echo $INSTANCE_NAME already running pid $FOUND_PID\n      return 1;\n   } || {\n      nohup $SCRIPT >$LOG_DIR/stdout.log 2>$LOG_DIR/stderr.log &\n      RETURN=$?\n      # this is generally followed by findPid, so we shouldn't exit \n      # immediately as the proc may not have registered in ps, yet\n      test $RETURN && sleep 1\n      return $RETURN;\n   }\n}\nexport PATH=/usr/ucb/bin:/bin:/sbin:/usr/bin:/usr/sbin\ncase $1 in\ninit)\n   default || exit 1\n   install_jdk || exit 1\n   mkdir -p $INSTANCE_HOME\n   \n   # create runscript header\n   cat > $INSTANCE_HOME/install_jdk.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\t#!/bin/bash\n\tset +u\n\tshopt -s xpg_echo\n\tshopt -s expand_aliases\n\t\n\tPROMPT_COMMAND='echo -ne \\\"\\033]0;install_jdk\\007\\\"'\n\texport PATH=/usr/ucb/bin:/bin:/sbin:/usr/bin:/usr/sbin\n\n\texport INSTANCE_NAME='install_jdk'\nEND_OF_JCLOUDS_SCRIPT\n   cat >> $INSTANCE_HOME/install_jdk.sh <<-END_OF_JCLOUDS_SCRIPT\n\texport INSTANCE_NAME='$INSTANCE_NAME'\n\texport INSTANCE_HOME='$INSTANCE_HOME'\n\texport LOG_DIR='$LOG_DIR'\nEND_OF_JCLOUDS_SCRIPT\n   cat >> $INSTANCE_HOME/install_jdk.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\tfunction abort {\n   echo \"aborting: $@\" 1>&2\n   exit 1\n}\nalias apt-get-update=\"apt-get update -qq\"\nalias apt-get-install=\"apt-get install -f -y -qq --force-yes\"\nalias yum-install=\"yum --quiet --nogpgcheck -y install\"\n\nfunction ensure_cmd_or_install_package_apt(){\n  local cmd=$1\n  shift\n  local pkg=$*\n  \n  hash $cmd 2>/dev/null || ( apt-get-update && apt-get-install $pkg )\n}\n\nfunction ensure_cmd_or_install_package_yum(){\n  local cmd=$1\n  shift\n  local pkg=$*\n  hash $cmd 2>/dev/null || yum-install $pkg\n}\n\nfunction ensure_netutils_apt() {\n  ensure_cmd_or_install_package_apt nslookup dnsutils\n  ensure_cmd_or_install_package_apt curl curl\n}\n\nfunction ensure_netutils_yum() {\n  ensure_cmd_or_install_package_yum nslookup bind-utils\n  ensure_cmd_or_install_package_yum curl curl\n}\n\n# most network services require that the hostname is in\n# the /etc/hosts file, or they won't operate\nfunction ensure_hostname_in_hosts() {\n  [ -n \"$SSH_CONNECTION\" ] && {\n    local ipaddr=`echo $SSH_CONNECTION | awk '{print $3}'`\n  } || {\n    local ipaddr=`hostname -i`\n  }\n  # NOTE: we blindly trust existing hostname settings in /etc/hosts\n  egrep -q `hostname -s` /etc/hosts || echo \"$ipaddr `hostname -f` `hostname -s`\" >> /etc/hosts\n}\n\n# download locations for many services are at public dns\nfunction ensure_can_resolve_public_dns() {\n  nslookup yahoo.com | grep yahoo.com > /dev/null || echo nameserver 208.67.222.222 >> /etc/resolv.conf\n}\n\nfunction setupPublicCurl() {\n  ensure_hostname_in_hosts\n  if which dpkg &> /dev/null; then\n    ensure_netutils_apt\n  elif which rpm &> /dev/null; then\n    ensure_netutils_yum\n  else\n    abort \"we only support apt-get and yum right now... please contribute!\"\n    return 1\n  fi\n  ensure_can_resolve_public_dns\n  return 0  \n}\n# adds JAVA_HOME and into PATH in global and user-specific profiles\nfunction setupJavaHomeInProfile() {\n  PROFILES=(/etc/bashrc $HOME/.bashrc /etc/skel/.bashrc)\n  test -n \"$SUDO_USER\" &&\n    PROFILES=(${PROFILES[*]} `getent passwd $SUDO_USER| cut -f6 -d:`/.bashrc)\n  for PROFILE in ${PROFILES[*]}; do\n    cat >> $PROFILE <<-'END_OF_JCLOUDS_FILE'\n\texport JAVA_HOME=/usr/local/jdk\n\texport PATH=$JAVA_HOME/bin:$PATH\nEND_OF_JCLOUDS_FILE\n  done\n}\n\n# resets JAVA_HOME to what an openjdk installer created\nfunction findOpenJDK() {\n  local oldJavaHome=$JAVA_HOME\n  unset JAVA_HOME\n  for CANDIDATE in $oldJavaHome `ls -d /usr/lib/jvm/java-*-openjdk* 2>&-`; do\n    if [ -n \"$CANDIDATE\" -a -x \"$CANDIDATE/bin/java\" ]; then\n      export JAVA_HOME=$CANDIDATE\n      break\n    fi\n  done\n}\n\n# assures JDK installed and JAVA_HOME to a link at /usr/local/jdk\nfunction installOpenJDK() {\n  if [ \"$JAVA_HOME\" == \"/usr/local/jdk\" ]; then\n    echo skipping as JAVA_HOME is already set to /usr/local/jdk\n    return 0\n  fi\n  if [ -n \"$JAVA_HOME\" -a -x \"$JAVA_HOME/bin/java\" ]; then\n    echo reusing JAVA_HOME $JAVA_HOME\n  else\n    if which dpkg &> /dev/null; then\n      apt-get-update && \\\n          PACKAGE=$(apt-cache search --names-only '^openjdk-.-jdk$' | sort -r | cut -d' ' -f1 | head -1) && \\\n          [ ! -z \"$PACKAGE\" ] && \\\n          {  apt-get-install $PACKAGE-headless || apt-get-install $PACKAGE; }\n    elif which rpm &> /dev/null; then\n      PACKAGE=$(repoquery --qf='%{name}' --pkgnarrow=available 'java-*-openjdk-devel' | sort -r | head -1) && \\\n        [ ! -z \"$PACKAGE\" ] && \\\n        yum-install $PACKAGE\n    else\n      abort \"we only support apt-get and yum right now... please contribute\"\n    fi\n    findOpenJDK\n    if [ -n \"$JAVA_HOME\" ]; then\n      echo installed JAVA_HOME $JAVA_HOME\n    else\n      abort \"JDK installation failed\"\n    fi\n  fi\n  rm -rf /usr/local/jdk\n  ln -Fs $JAVA_HOME /usr/local/jdk\n  /usr/local/jdk/bin/java -version || abort \"cannot run java\"\n  setupJavaHomeInProfile\n}\n\nEND_OF_JCLOUDS_SCRIPT\n   \n   # add desired commands from the user\n   cat >> $INSTANCE_HOME/install_jdk.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\tcd $INSTANCE_HOME\n\trm -f $INSTANCE_HOME/rc\n\ttrap 'echo $?>$INSTANCE_HOME/rc' 0 1 2 3 15\n\tsetupPublicCurl || exit 1\n\tinstallOpenJDK || exit 1\n\t\nEND_OF_JCLOUDS_SCRIPT\n   \n   # add runscript footer\n   cat >> $INSTANCE_HOME/install_jdk.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\texit $?\n\t\nEND_OF_JCLOUDS_SCRIPT\n   \n   chmod u+x $INSTANCE_HOME/install_jdk.sh\n   ;;\nstatus)\n   default || exit 1\n   findPid $INSTANCE_NAME || exit 1\n   echo $FOUND_PID\n   ;;\nstop)\n   default || exit 1\n   findPid $INSTANCE_NAME || exit 1\n   [ -n \"$FOUND_PID\" ]  && {\n      echo stopping $FOUND_PID\n      kill -9 $FOUND_PID\n   }\n   ;;\nstart)\n   default || exit 1\n   forget $INSTANCE_NAME $INSTANCE_HOME/$INSTANCE_NAME.sh $LOG_DIR || exit 1\n   ;;\nstdout)\n   default || exit 1\n   cat $LOG_DIR/stdout.log\n   ;;\nstderr)\n   default || exit 1\n   cat $LOG_DIR/stderr.log\n   ;;\nexitstatus)\n   default || exit 1\n   [ -f $LOG_DIR/rc ] && cat $LOG_DIR/rc;;\ntail)\n   default || exit 1\n   tail $LOG_DIR/stdout.log\n   ;;\ntailerr)\n   default || exit 1\n   tail $LOG_DIR/stderr.log\n   ;;\nrun)\n   default || exit 1\n   $INSTANCE_HOME/$INSTANCE_NAME.sh\n   ;;\nesac\nexit $?\n"
  },
  {
    "path": "scriptbuilder/src/test/resources/test_install_ruby.sh",
    "content": "setupPublicCurl || return 1\ninstallRuby || return 1\n"
  },
  {
    "path": "scriptbuilder/src/test/resources/test_install_ruby_scriptbuilder.sh",
    "content": "#!/bin/bash\nset +u\nshopt -s xpg_echo\nshopt -s expand_aliases\nunset PATH JAVA_HOME LD_LIBRARY_PATH\nfunction abort {\n   echo \"aborting: $@\" 1>&2\n   exit 1\n}\nfunction default {\n   export INSTANCE_NAME=\"install_ruby\"\nexport INSTANCE_HOME=\"/tmp/$INSTANCE_NAME\"\nexport LOG_DIR=\"$INSTANCE_HOME\"\n   return $?\n}\nfunction install_ruby {\n      return $?\n}\nfunction findPid {\n   unset FOUND_PID;\n   [ $# -eq 1 ] || {\n      abort \"findPid requires a parameter of pattern to match\"\n      return 1\n   }\n   local PATTERN=\"$1\"; shift\n   local _FOUND=`ps auxwww|grep \"$PATTERN\"|grep -v \" $0\"|grep -v grep|grep -v $$|awk '{print $2}'`\n   [ -n \"$_FOUND\" ] && {\n      export FOUND_PID=$_FOUND\n      return 0\n   } || {\n      return 1\n   }\n}\nfunction forget {\n   unset FOUND_PID;\n   [ $# -eq 3 ] || {\n      abort \"forget requires parameters INSTANCE_NAME SCRIPT LOG_DIR\"\n      return 1\n   }\n   local INSTANCE_NAME=\"$1\"; shift\n   local SCRIPT=\"$1\"; shift\n   local LOG_DIR=\"$1\"; shift\n   mkdir -p $LOG_DIR\n   findPid $INSTANCE_NAME\n   [ -n \"$FOUND_PID\" -a -f $LOG_DIR/stdout.log ] && {\n      echo $INSTANCE_NAME already running pid $FOUND_PID\n      return 1;\n   } || {\n      nohup $SCRIPT >$LOG_DIR/stdout.log 2>$LOG_DIR/stderr.log &\n      RETURN=$?\n      # this is generally followed by findPid, so we shouldn't exit \n      # immediately as the proc may not have registered in ps, yet\n      test $RETURN && sleep 1\n      return $RETURN;\n   }\n}\nexport PATH=/usr/ucb/bin:/bin:/sbin:/usr/bin:/usr/sbin\ncase $1 in\ninit)\n   default || exit 1\n   install_ruby || exit 1\n   mkdir -p $INSTANCE_HOME\n   \n   # create runscript header\n   cat > $INSTANCE_HOME/install_ruby.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\t#!/bin/bash\n\tset +u\n\tshopt -s xpg_echo\n\tshopt -s expand_aliases\n\t\n\tPROMPT_COMMAND='echo -ne \\\"\\033]0;install_ruby\\007\\\"'\n\texport PATH=/usr/ucb/bin:/bin:/sbin:/usr/bin:/usr/sbin\n\n\texport INSTANCE_NAME='install_ruby'\nEND_OF_JCLOUDS_SCRIPT\n   cat >> $INSTANCE_HOME/install_ruby.sh <<-END_OF_JCLOUDS_SCRIPT\n\texport INSTANCE_NAME='$INSTANCE_NAME'\n\texport INSTANCE_HOME='$INSTANCE_HOME'\n\texport LOG_DIR='$LOG_DIR'\nEND_OF_JCLOUDS_SCRIPT\n   cat >> $INSTANCE_HOME/install_ruby.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\tfunction abort {\n   echo \"aborting: $@\" 1>&2\n   exit 1\n}\nalias apt-get-update=\"apt-get update -qq\"\nalias apt-get-install=\"apt-get install -f -y -qq --force-yes\"\nalias yum-install=\"yum --quiet --nogpgcheck -y install\"\n\nfunction ensure_cmd_or_install_package_apt(){\n  local cmd=$1\n  shift\n  local pkg=$*\n  \n  hash $cmd 2>/dev/null || ( apt-get-update && apt-get-install $pkg )\n}\n\nfunction ensure_cmd_or_install_package_yum(){\n  local cmd=$1\n  shift\n  local pkg=$*\n  hash $cmd 2>/dev/null || yum-install $pkg\n}\n\nfunction ensure_netutils_apt() {\n  ensure_cmd_or_install_package_apt nslookup dnsutils\n  ensure_cmd_or_install_package_apt curl curl\n}\n\nfunction ensure_netutils_yum() {\n  ensure_cmd_or_install_package_yum nslookup bind-utils\n  ensure_cmd_or_install_package_yum curl curl\n}\n\n# most network services require that the hostname is in\n# the /etc/hosts file, or they won't operate\nfunction ensure_hostname_in_hosts() {\n  [ -n \"$SSH_CONNECTION\" ] && {\n    local ipaddr=`echo $SSH_CONNECTION | awk '{print $3}'`\n  } || {\n    local ipaddr=`hostname -i`\n  }\n  # NOTE: we blindly trust existing hostname settings in /etc/hosts\n  egrep -q `hostname -s` /etc/hosts || echo \"$ipaddr `hostname -f` `hostname -s`\" >> /etc/hosts\n}\n\n# download locations for many services are at public dns\nfunction ensure_can_resolve_public_dns() {\n  nslookup yahoo.com | grep yahoo.com > /dev/null || echo nameserver 208.67.222.222 >> /etc/resolv.conf\n}\n\nfunction setupPublicCurl() {\n  ensure_hostname_in_hosts\n  if which dpkg &> /dev/null; then\n    ensure_netutils_apt\n  elif which rpm &> /dev/null; then\n    ensure_netutils_yum\n  else\n    abort \"we only support apt-get and yum right now... please contribute!\"\n    return 1\n  fi\n  ensure_can_resolve_public_dns\n  return 0  \n}\nfunction installRuby() {\n  if ! hash ruby 2>/dev/null; then\n    if which dpkg &> /dev/null; then\n      apt-get-update\n      apt-get install -y ruby ruby-dev build-essential\n    elif which rpm &> /dev/null; then\n      # Disable chef from the base repo (http://tickets.opscode.com/browse/CHEF-2906)\n      sed -i \"s/\\[base\\]/\\0\\n\\exclude=ruby*/g\" /etc/yum.repos.d/CentOS-Base.repo\n      # Make sure to install an appropriate ruby version\n      yum erase -y ruby ruby-libs\n      rpm -Uvh http://rbel.co/rbel5\n      yum install -y ruby ruby-devel make gcc gcc-c++ automake autoconf\n    else\n      abort \"we only support apt-get and yum right now... please contribute\"\n    fi\n  fi\n}\n\nEND_OF_JCLOUDS_SCRIPT\n   \n   # add desired commands from the user\n   cat >> $INSTANCE_HOME/install_ruby.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\tcd $INSTANCE_HOME\n\trm -f $INSTANCE_HOME/rc\n\ttrap 'echo $?>$INSTANCE_HOME/rc' 0 1 2 3 15\n\tsetupPublicCurl || exit 1\n\t\n\tinstallRuby || exit 1\n\t\nEND_OF_JCLOUDS_SCRIPT\n   \n   # add runscript footer\n   cat >> $INSTANCE_HOME/install_ruby.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\texit $?\n\t\nEND_OF_JCLOUDS_SCRIPT\n   \n   chmod u+x $INSTANCE_HOME/install_ruby.sh\n   ;;\nstatus)\n   default || exit 1\n   findPid $INSTANCE_NAME || exit 1\n   echo $FOUND_PID\n   ;;\nstop)\n   default || exit 1\n   findPid $INSTANCE_NAME || exit 1\n   [ -n \"$FOUND_PID\" ]  && {\n      echo stopping $FOUND_PID\n      kill -9 $FOUND_PID\n   }\n   ;;\nstart)\n   default || exit 1\n   forget $INSTANCE_NAME $INSTANCE_HOME/$INSTANCE_NAME.sh $LOG_DIR || exit 1\n   ;;\nstdout)\n   default || exit 1\n   cat $LOG_DIR/stdout.log\n   ;;\nstderr)\n   default || exit 1\n   cat $LOG_DIR/stderr.log\n   ;;\nexitstatus)\n   default || exit 1\n   [ -f $LOG_DIR/rc ] && cat $LOG_DIR/rc;;\ntail)\n   default || exit 1\n   tail $LOG_DIR/stdout.log\n   ;;\ntailerr)\n   default || exit 1\n   tail $LOG_DIR/stderr.log\n   ;;\nrun)\n   default || exit 1\n   $INSTANCE_HOME/$INSTANCE_NAME.sh\n   ;;\nesac\nexit $?\n"
  },
  {
    "path": "scriptbuilder/src/test/resources/test_install_rubygems.sh",
    "content": "if ! hash gem 2>/dev/null; then\n(\nexport TAR_TEMP=\"$(mktemp -d)\"\ncurl -q -s -S -L --connect-timeout 10 --max-time 600 --retry 20 -X GET  http://production.cf.rubygems.org/rubygems/rubygems-1.8.10.tgz |(mkdir -p \"${TAR_TEMP}\" &&cd \"${TAR_TEMP}\" &&tar -xpzf -)\nmkdir -p /tmp/rubygems\nmv \"${TAR_TEMP}\"/*/* /tmp/rubygems\nrm -rf \"${TAR_TEMP}\"\ncd /tmp/rubygems\nruby setup.rb --no-format-executable\nrm -fr /tmp/rubygems\n)\nfi\ngem update --system\ngem update --no-rdoc --no-ri\n"
  },
  {
    "path": "scriptbuilder/src/test/resources/test_install_rubygems_scriptbuilder.sh",
    "content": "#!/bin/bash\nset +u\nshopt -s xpg_echo\nshopt -s expand_aliases\nunset PATH JAVA_HOME LD_LIBRARY_PATH\nfunction abort {\n   echo \"aborting: $@\" 1>&2\n   exit 1\n}\nfunction default {\n   export INSTANCE_NAME=\"install_rubygems\"\nexport INSTANCE_HOME=\"/tmp/$INSTANCE_NAME\"\nexport LOG_DIR=\"$INSTANCE_HOME\"\n   return $?\n}\nfunction install_rubygems {\n      return $?\n}\nfunction findPid {\n   unset FOUND_PID;\n   [ $# -eq 1 ] || {\n      abort \"findPid requires a parameter of pattern to match\"\n      return 1\n   }\n   local PATTERN=\"$1\"; shift\n   local _FOUND=`ps auxwww|grep \"$PATTERN\"|grep -v \" $0\"|grep -v grep|grep -v $$|awk '{print $2}'`\n   [ -n \"$_FOUND\" ] && {\n      export FOUND_PID=$_FOUND\n      return 0\n   } || {\n      return 1\n   }\n}\nfunction forget {\n   unset FOUND_PID;\n   [ $# -eq 3 ] || {\n      abort \"forget requires parameters INSTANCE_NAME SCRIPT LOG_DIR\"\n      return 1\n   }\n   local INSTANCE_NAME=\"$1\"; shift\n   local SCRIPT=\"$1\"; shift\n   local LOG_DIR=\"$1\"; shift\n   mkdir -p $LOG_DIR\n   findPid $INSTANCE_NAME\n   [ -n \"$FOUND_PID\" -a -f $LOG_DIR/stdout.log ] && {\n      echo $INSTANCE_NAME already running pid $FOUND_PID\n      return 1;\n   } || {\n      nohup $SCRIPT >$LOG_DIR/stdout.log 2>$LOG_DIR/stderr.log &\n      RETURN=$?\n      # this is generally followed by findPid, so we shouldn't exit \n      # immediately as the proc may not have registered in ps, yet\n      test $RETURN && sleep 1\n      return $RETURN;\n   }\n}\nexport PATH=/usr/ucb/bin:/bin:/sbin:/usr/bin:/usr/sbin\ncase $1 in\ninit)\n   default || exit 1\n   install_rubygems || exit 1\n   mkdir -p $INSTANCE_HOME\n   \n   # create runscript header\n   cat > $INSTANCE_HOME/install_rubygems.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\t#!/bin/bash\n\tset +u\n\tshopt -s xpg_echo\n\tshopt -s expand_aliases\n\t\n\tPROMPT_COMMAND='echo -ne \\\"\\033]0;install_rubygems\\007\\\"'\n\texport PATH=/usr/ucb/bin:/bin:/sbin:/usr/bin:/usr/sbin\n\n\texport INSTANCE_NAME='install_rubygems'\nEND_OF_JCLOUDS_SCRIPT\n   cat >> $INSTANCE_HOME/install_rubygems.sh <<-END_OF_JCLOUDS_SCRIPT\n\texport INSTANCE_NAME='$INSTANCE_NAME'\n\texport INSTANCE_HOME='$INSTANCE_HOME'\n\texport LOG_DIR='$LOG_DIR'\nEND_OF_JCLOUDS_SCRIPT\n   \n   # add desired commands from the user\n   cat >> $INSTANCE_HOME/install_rubygems.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\tcd $INSTANCE_HOME\n\trm -f $INSTANCE_HOME/rc\n\ttrap 'echo $?>$INSTANCE_HOME/rc' 0 1 2 3 15\n\tif ! hash gem 2>/dev/null; then\n\t(\n\texport TAR_TEMP=\"$(mktemp -d)\"\n\tcurl -q -s -S -L --connect-timeout 10 --max-time 600 --retry 20 -X GET  http://production.cf.rubygems.org/rubygems/rubygems-1.8.10.tgz |(mkdir -p \"${TAR_TEMP}\" &&cd \"${TAR_TEMP}\" &&tar -xpzf -)\n\tmkdir -p /tmp/rubygems\n\tmv \"${TAR_TEMP}\"/*/* /tmp/rubygems\n\trm -rf \"${TAR_TEMP}\"\n\tcd /tmp/rubygems\n\truby setup.rb --no-format-executable\n\trm -fr /tmp/rubygems\n\t)\n\tfi\n\t\nEND_OF_JCLOUDS_SCRIPT\n   \n   # add runscript footer\n   cat >> $INSTANCE_HOME/install_rubygems.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\texit $?\n\t\nEND_OF_JCLOUDS_SCRIPT\n   \n   chmod u+x $INSTANCE_HOME/install_rubygems.sh\n   ;;\nstatus)\n   default || exit 1\n   findPid $INSTANCE_NAME || exit 1\n   echo $FOUND_PID\n   ;;\nstop)\n   default || exit 1\n   findPid $INSTANCE_NAME || exit 1\n   [ -n \"$FOUND_PID\" ]  && {\n      echo stopping $FOUND_PID\n      kill -9 $FOUND_PID\n   }\n   ;;\nstart)\n   default || exit 1\n   forget $INSTANCE_NAME $INSTANCE_HOME/$INSTANCE_NAME.sh $LOG_DIR || exit 1\n   ;;\nstdout)\n   default || exit 1\n   cat $LOG_DIR/stdout.log\n   ;;\nstderr)\n   default || exit 1\n   cat $LOG_DIR/stderr.log\n   ;;\nexitstatus)\n   default || exit 1\n   [ -f $LOG_DIR/rc ] && cat $LOG_DIR/rc;;\ntail)\n   default || exit 1\n   tail $LOG_DIR/stdout.log\n   ;;\ntailerr)\n   default || exit 1\n   tail $LOG_DIR/stderr.log\n   ;;\nrun)\n   default || exit 1\n   $INSTANCE_HOME/$INSTANCE_NAME.sh\n   ;;\nesac\nexit $?\n"
  },
  {
    "path": "scriptbuilder/src/test/resources/test_runrun.sh",
    "content": "mkdir -p /tmp/$USER/scripttest\n\n# create runscript header\ncat > /tmp/$USER/scripttest/yahooprod.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\t#!/bin/bash\n\tset +u\n\tshopt -s xpg_echo\n\tshopt -s expand_aliases\n\t\n\tPROMPT_COMMAND='echo -ne \\\"\\033]0;yahooprod\\007\\\"'\n\texport PATH=/usr/ucb/bin:/bin:/sbin:/usr/bin:/usr/sbin\n\n\texport INSTANCE_NAME='yahooprod'\nEND_OF_JCLOUDS_SCRIPT\ncat >> /tmp/$USER/scripttest/yahooprod.sh <<-END_OF_JCLOUDS_SCRIPT\n\texport JAVA_HOME='$JAVA_HOME'\nEND_OF_JCLOUDS_SCRIPT\n\n# add desired commands from the user\ncat >> /tmp/$USER/scripttest/yahooprod.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\tcd /tmp/$USER/scripttest\n\techo hello\n\t\n\tcat >> /tmp/$USER/scripttest/temp.txt <<-'END_OF_JCLOUDS_FILE'\n\t\thello world\n\tEND_OF_JCLOUDS_FILE\n\t\n\techo $JAVA_HOME/bin/java -DinstanceName=$INSTANCE_NAME myServer.Main\n\t\nEND_OF_JCLOUDS_SCRIPT\n\n# add runscript footer\ncat >> /tmp/$USER/scripttest/yahooprod.sh <<-'END_OF_JCLOUDS_SCRIPT'\n\texit $?\n\t\nEND_OF_JCLOUDS_SCRIPT\n\nchmod u+x /tmp/$USER/scripttest/yahooprod.sh\n"
  },
  {
    "path": "scriptbuilder/src/test/resources/test_runrun_header.sh",
    "content": "mkdir -p /tmp/$USER/scripttest\n\n# create runscript header\n(\ncat <<END_OF_SCRIPT\n#!/bin/bash\nset +u\nshopt -s xpg_echo\nshopt -s expand_aliases\nPROMPT_COMMAND='echo -ne \"\\033]0;yahooprod\\007\"'\nexport PATH=/usr/ucb/bin:/bin:/sbin:/usr/bin:/usr/sbin\nexport INSTANCE_NAME='yahooprod'\nexport JAVA_HOME='$JAVA_HOME'\nEND_OF_SCRIPT\n) > /tmp/$USER/scripttest/yahooprod.sh\n\n# add desired commands from the user\n(\ncat <<'END_OF_SCRIPT'\ncd /tmp/$USER/scripttest\necho hello\necho $JAVA_HOME/bin/java -DinstanceName=$INSTANCE_NAME myServer.Main\nEND_OF_SCRIPT\n) >> /tmp/$USER/scripttest/yahooprod.sh\n\n# add runscript footer\n(\ncat <<'END_OF_SCRIPT'\nexit 0\nEND_OF_SCRIPT\n) >> /tmp/$USER/scripttest/yahooprod.sh\n\nchmod u+x /tmp/$USER/scripttest/yahooprod.sh\n"
  },
  {
    "path": "scriptbuilder/src/test/resources/test_script.cmd",
    "content": "@echo off\r\nset PATH=\r\nset JAVA_HOME=\r\nset PATH=\r\nset RUNTIME=\r\nGOTO FUNCTION_END\r\n:abort\r\n   echo aborting: %EXCEPTION%\r\n   exit /b 1\r\n:default\r\n   set RUNTIME=Moo\r\n   exit /b 0\r\n:FUNCTION_END\r\nset PATH=c:\\windows\\;C:\\windows\\system32;c:\\windows\\system32\\wbem\r\nif not \"%1\" == \"start\" if not \"%1\" == \"stop\" if not \"%1\" == \"status\" (\r\n   set EXCEPTION=bad argument: %1 not in start stop status\r\n   goto abort\r\n)\r\ngoto CASE_%1\r\n:CASE_start\r\n   call :default\r\n   if errorlevel 1 goto abort\r\n   echo start %RUNTIME%\r\n   GOTO END_SWITCH\r\n:CASE_stop\r\n   call :default\r\n   if errorlevel 1 goto abort\r\n   echo stop %RUNTIME%\r\n   GOTO END_SWITCH\r\n:CASE_status\r\n   echo hello world >>%TEMP%\\%USERNAME%\\scripttest\\temp.txt\r\n   echo the following should be []: [%RUNTIME%]\r\n   GOTO END_SWITCH\r\n:END_SWITCH\r\nexit /b 0\r\n"
  },
  {
    "path": "scriptbuilder/src/test/resources/test_script.sh",
    "content": "#!/bin/bash\nset +u\nshopt -s xpg_echo\nshopt -s expand_aliases\nunset PATH JAVA_HOME LD_LIBRARY_PATH RUNTIME\nfunction abort {\n   echo \"aborting: $@\" 1>&2\n   exit 1\n}\nfunction default {\n   export RUNTIME=\"Moo\"\n   return $?\n}\nexport PATH=/usr/ucb/bin:/bin:/sbin:/usr/bin:/usr/sbin\ncase $1 in\nstart)\n   default || exit 1\n   echo start $RUNTIME\n   ;;\nstop)\n   default || exit 1\n   echo stop $RUNTIME\n   ;;\nstatus)\n   cat >> /tmp/$USER/scripttest/temp.txt <<-'END_OF_JCLOUDS_FILE'\n\thello world\nEND_OF_JCLOUDS_FILE\n   echo \"the following should be []: [$RUNTIME]\"\n   ;;\nesac\nexit $?\n"
  },
  {
    "path": "scriptbuilder/src/test/resources/test_seek_and_destroy.cmd",
    "content": "@echo off\r\nset PATH=\r\nset JAVA_HOME=\r\nset PATH=\r\nGOTO FUNCTION_END\r\n:abort\r\n   echo aborting: %EXCEPTION%\r\n   exit /b 1\r\n:findPid\r\n   set FOUND_PID=\r\n   set _expression=%1\r\n   shift\r\n   set FIND_PROCESS=TASKLIST /FI \"WINDOWTITLE eq %_expression%\" /NH\r\n   FOR /F \"usebackq tokens=2 delims= \" %%A IN (`cmd /c \"%FIND_PROCESS% 2>NUL\"`) DO (\r\n      SET FOUND_PID=%%A\r\n   )\r\n   if defined FOUND_PID (\r\n      exit /b 0\r\n   ) else (\r\n      set EXCEPTION=%_expression% not found\r\n      exit /b 1\r\n   )\r\n:FUNCTION_END\r\nset PATH=c:\\windows\\;C:\\windows\\system32;c:\\windows\\system32\\wbem\r\ncall :findPid %*\r\nif errorlevel 1 goto abort\r\nif defined FOUND_PID (\r\n   TASKKILL /F /T /PID %FOUND_PID% >NUL\r\n)\r\nexit /b 0\r\n"
  },
  {
    "path": "scriptbuilder/src/test/resources/test_seek_and_destroy.sh",
    "content": "#!/bin/bash\nset +u\nshopt -s xpg_echo\nshopt -s expand_aliases\nunset PATH JAVA_HOME LD_LIBRARY_PATH\nfunction abort {\n   echo \"aborting: $@\" 1>&2\n   exit 1\n}\nfunction findPid {\n   unset FOUND_PID;\n   [ $# -eq 1 ] || {\n      abort \"findPid requires a parameter of pattern to match\"\n      return 1\n   }\n   local PATTERN=\"$1\"; shift\n   local _FOUND=`ps auxwww|grep \"$PATTERN\"|grep -v \" $0\"|grep -v grep|grep -v $$|awk '{print $2}'`\n   [ -n \"$_FOUND\" ] && {\n      export FOUND_PID=$_FOUND\n      return 0\n   } || {\n      return 1\n   }\n}\nexport PATH=/usr/ucb/bin:/bin:/sbin:/usr/bin:/usr/sbin\nfindPid $@ || exit 1\n[ -n \"$FOUND_PID\" ]  && {\n   echo stopping $FOUND_PID\n   kill -9 $FOUND_PID\n}\nexit $?\n"
  },
  {
    "path": "skeletons/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <parent>\n    <artifactId>jclouds-project</artifactId>\n    <groupId>org.apache.jclouds</groupId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../project/pom.xml</relativePath>\n  </parent>\n  <modelVersion>4.0.0</modelVersion>\n  <artifactId>jclouds-skeletons-project</artifactId>\n  <packaging>pom</packaging>\n  <name>jclouds skeletons project</name>\n  <modules>\n    <module>standalone-compute</module>\n  </modules>\n</project>\n"
  },
  {
    "path": "skeletons/standalone-compute/README.txt",
    "content": "this is a skeleton for a standalone compute provider.\n\nEssentially, a standalone provider is one that doesn't use jclouds http services.  Examples could be native drivers like libvirt or shell-driven ones like virtualbox.\n"
  },
  {
    "path": "skeletons/standalone-compute/bnd.bnd",
    "content": "Export-Package: \\\n    org.jclouds.servermanager.*;version=\"${project.version}\";-noimport:=true\n"
  },
  {
    "path": "skeletons/standalone-compute/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!--\n\n    Licensed to the Apache Software Foundation (ASF) under one or more\n    contributor license agreements.  See the NOTICE file distributed with\n    this work for additional information regarding copyright ownership.\n    The ASF licenses this file to You under the Apache License, Version 2.0\n    (the \"License\"); you may not use this file except in compliance with\n    the License.  You may obtain a copy of the License at\n\n        http://www.apache.org/licenses/LICENSE-2.0\n\n    Unless required by applicable law or agreed to in writing, software\n    distributed under the License is distributed on an \"AS IS\" BASIS,\n    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n    See the License for the specific language governing permissions and\n    limitations under the License.\n\n-->\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n  <modelVersion>4.0.0</modelVersion>\n  <parent>\n    <groupId>org.apache.jclouds</groupId>\n    <artifactId>jclouds-project</artifactId>\n    <version>2.7.1-SNAPSHOT</version>\n    <relativePath>../../project/pom.xml</relativePath>\n  </parent>\n  <groupId>org.apache.jclouds.api</groupId>\n  <artifactId>servermanager</artifactId>\n  <name>jclouds example components for a standalone compute provider</name>\n\n  <properties>\n    <!-- when instances are hung, open a ticket and add here -->\n    <jclouds.compute.blacklist-nodes>trmkrun-ccc,test.trmk-924</jclouds.compute.blacklist-nodes>\n    <test.servermanager.identity>FIXME_IDENTITY</test.servermanager.identity>\n    <test.servermanager.credential>FIXME_CREDENTIAL</test.servermanager.credential>\n    <test.servermanager.endpoint>https://servermanager.com</test.servermanager.endpoint>\n    <test.servermanager.api-version>1.0</test.servermanager.api-version>\n    <test.servermanager.build-version />\n  </properties>\n  <dependencies>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-core</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds</groupId>\n      <artifactId>jclouds-compute</artifactId>\n      <version>${project.version}</version>\n      <type>test-jar</type>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.logging.log4j</groupId>\n      <artifactId>log4j-core</artifactId>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-log4j</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>org.apache.jclouds.driver</groupId>\n      <artifactId>jclouds-jsch</artifactId>\n      <version>${project.version}</version>\n      <scope>test</scope>\n    </dependency>\n    <dependency>\n      <groupId>com.google.auto.service</groupId>\n      <artifactId>auto-service</artifactId>\n      <optional>true</optional>\n    </dependency>\n  </dependencies>\n\n  <profiles>\n    <profile>\n      <id>live</id>\n      <build>\n        <plugins>\n          <plugin>\n            <groupId>org.apache.maven.plugins</groupId>\n            <artifactId>maven-surefire-plugin</artifactId>\n            <executions>\n              <execution>\n                <id>integration</id>\n                <phase>integration-test</phase>\n                <goals>\n                  <goal>test</goal>\n                </goals>\n                <configuration>\n                  <systemPropertyVariables>\n                    <test.servermanager.endpoint>${test.servermanager.endpoint}</test.servermanager.endpoint>\n                    <test.servermanager.api-version>${test.servermanager.api-version}</test.servermanager.api-version>\n                    <test.servermanager.build-version>${test.servermanager.build-version}</test.servermanager.build-version>\n                    <test.servermanager.identity>${test.servermanager.identity}</test.servermanager.identity>\n                    <jclouds.compute.blacklist-nodes>${jclouds.compute.blacklist-nodes}</jclouds.compute.blacklist-nodes>\n                  </systemPropertyVariables>\n                </configuration>\n              </execution>\n            </executions>\n          </plugin>\n        </plugins>\n      </build>\n    </profile>\n  </profiles>\n\n</project>\n"
  },
  {
    "path": "skeletons/standalone-compute/src/main/java/org/jclouds/servermanager/Datacenter.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.servermanager;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\n/**\n * This would be replaced with the real java object related to the underlying data center\n */\npublic class Datacenter {\n\n   public int id;\n   public String name;\n\n   public Datacenter(int id, String name) {\n      this.id = id;\n      this.name = name;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, name);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (obj == null)\n         return false;\n      if (!(obj instanceof Datacenter)) {\n         return false;\n      }\n      Datacenter that = (Datacenter) obj;\n      return Objects.equal(this.id, that.id)\n         && Objects.equal(this.name, that.name);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).add(\"id\", id).add(\"name\", name).toString();\n   }\n\n}\n"
  },
  {
    "path": "skeletons/standalone-compute/src/main/java/org/jclouds/servermanager/Hardware.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.servermanager;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\n/**\n * This would be replaced with the real java object related to the underlying hardware\n */\npublic class Hardware {\n\n   public int id;\n   public String name;\n   public int cores;\n   public int ram;\n   public float disk;\n\n   public Hardware(int id, String name, int cores, int ram, float disk) {\n      this.id = id;\n      this.name = name;\n      this.cores = cores;\n      this.ram = ram;\n      this.disk = disk;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, name, cores, ram, disk);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (obj == null)\n         return false;\n      if (!(obj instanceof Hardware)) {\n         return false;\n      }\n      Hardware that = (Hardware) obj;\n      return Objects.equal(this.id, that.id)\n         && Objects.equal(this.name, that.name)\n         && Objects.equal(this.cores, that.cores)\n         && Objects.equal(this.ram, that.ram)\n         && Objects.equal(this.disk, that.disk);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).add(\"id\", id).add(\"name\", name).add(\"cores\", cores).add(\"ram\", ram)\n            .add(\"disk\", disk).toString();\n   }\n\n}\n"
  },
  {
    "path": "skeletons/standalone-compute/src/main/java/org/jclouds/servermanager/Image.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.servermanager;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\n/**\n * This would be replaced with the real java object related to the underlying image\n */\npublic class Image {\n\n   public int id;\n   public String name;\n\n   public Image(int id, String name) {\n      this.id = id;\n      this.name = name;\n   }\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, name);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (obj == null)\n         return false;\n      if (!(obj instanceof Image)) {\n         return false;\n      }\n      Image that = (Image) obj;\n      return Objects.equal(this.id, that.id)\n         && Objects.equal(this.name, that.name);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).add(\"id\", id).add(\"name\", name).toString();\n   }\n\n}\n"
  },
  {
    "path": "skeletons/standalone-compute/src/main/java/org/jclouds/servermanager/Server.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.servermanager;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.base.Objects;\n\n/**\n * This would be replaced with the real java object related to the underlying server\n */\npublic class Server {\n   public enum Status {\n      ACTIVE, BUILD, TERMINATED, UNRECOGNIZED\n\n   }\n\n   public int id;\n   public String name;\n   public Status status;\n   public String datacenter;\n   public int imageId;\n   public int hardwareId;\n   public String publicAddress;\n   public String privateAddress;\n   public String loginUser;\n   public String password;\n\n   @Override\n   public int hashCode() {\n      return Objects.hashCode(id, name, status, datacenter, imageId, hardwareId, publicAddress, privateAddress,\n            loginUser);\n   }\n\n   @Override\n   public boolean equals(Object obj) {\n      if (obj == null)\n         return false;\n      if (!(obj instanceof Server)) {\n         return false;\n      }\n      Server that = (Server) obj;\n      return Objects.equal(this.id, that.id)\n         && Objects.equal(this.name, that.name)\n         && Objects.equal(this.status, that.status)\n         && Objects.equal(this.datacenter, that.datacenter)\n         && Objects.equal(this.imageId, that.imageId)\n         && Objects.equal(this.hardwareId, that.hardwareId)\n         && Objects.equal(this.publicAddress, that.publicAddress)\n         && Objects.equal(this.privateAddress, that.privateAddress)\n         && Objects.equal(this.loginUser, that.loginUser)\n         && Objects.equal(this.password, that.password);\n   }\n\n   @Override\n   public String toString() {\n      return MoreObjects.toStringHelper(this).add(\"id\", id).add(\"name\", name).add(\"status\", status)\n            .add(\"datacenter\", datacenter).add(\"imageId\", imageId).add(\"hardwareId\", hardwareId)\n            .add(\"publicAddress\", publicAddress).add(\"privateAddress\", privateAddress).add(\"loginUser\", loginUser)\n            .toString();\n   }\n\n}\n"
  },
  {
    "path": "skeletons/standalone-compute/src/main/java/org/jclouds/servermanager/ServerManager.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.servermanager;\n\nimport java.util.Map;\nimport java.util.concurrent.atomic.AtomicInteger;\n\nimport jakarta.inject.Singleton;\n\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Maps;\n\n/**\n * This would be replaced with the real connection to the service that can\n * create/list/reboot/get/destroy things\n */\n@Singleton\npublic class ServerManager {\n\n   private static final Map<Integer, Server> servers = Maps.newHashMap();\n   private static final Map<Integer, Image> images = ImmutableMap.of(1, new Image(1, \"ubuntu\"));\n   private static final Map<Integer, Hardware> hardware = ImmutableMap.of(1, new Hardware(1, \"small\", 1, 512, 10));\n\n   private static final AtomicInteger nodeIds = new AtomicInteger(0);\n\n   /**\n    * simulate creating a server, as this is really going to happen with the api underneath\n    * \n    * @param name\n    * @param name\n    * @param imageId\n    * @param hardwareId\n    * @return new server\n    */\n   public Server createServerInDC(String datacenter, String name, int imageId, int hardwareId) {\n      Server server = new Server();\n      server.id = nodeIds.getAndIncrement();\n      server.name = name;\n      server.datacenter = datacenter;\n      server.imageId = imageId;\n      server.hardwareId = hardwareId;\n      server.publicAddress = \"7.1.1.\" + server.id;\n      server.privateAddress = \"10.1.1.\" + server.id;\n      server.loginUser = \"root\";\n      server.password = \"password\";\n      servers.put(server.id, server);\n      return server;\n   }\n\n   public Server getServer(int serverId) {\n      return servers.get(serverId);\n   }\n\n   public Iterable<Server> listServers() {\n      return servers.values();\n   }\n\n   public Image getImage(int imageId) {\n      return images.get(imageId);\n   }\n\n   public Iterable<Image> listImages() {\n      return images.values();\n   }\n\n   public Hardware getHardware(int hardwareId) {\n      return hardware.get(hardwareId);\n   }\n\n   public Iterable<org.jclouds.servermanager.Hardware> listHardware() {\n      return hardware.values();\n   }\n\n   public void destroyServer(int serverId) {\n      servers.remove(serverId);\n   }\n\n   public void rebootServer(int serverId) {\n   }\n\n   public void stopServer(int serverId) {\n   }\n   \n   public void startServer(int serverId) {\n   }\n}\n"
  },
  {
    "path": "skeletons/standalone-compute/src/main/java/org/jclouds/servermanager/ServerManagerApiMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.servermanager;\n\nimport java.net.URI;\n\nimport org.jclouds.apis.ApiMetadata;\nimport org.jclouds.apis.internal.BaseApiMetadata;\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.servermanager.compute.config.ServerManagerComputeServiceContextModule;\n\nimport com.google.auto.service.AutoService;\n\n/**\n * Implementation of {@link ApiMetadata} for an example of library integration (ServerManager)\n */\n@AutoService(ApiMetadata.class)\npublic class ServerManagerApiMetadata extends BaseApiMetadata {\n\n   @Override\n   public Builder toBuilder() {\n      return new Builder().fromApiMetadata(this);\n   }\n\n   public ServerManagerApiMetadata() {\n      super(new Builder());\n   }\n\n   protected ServerManagerApiMetadata(Builder builder) {\n      super(builder);\n   }\n\n   public static class Builder extends BaseApiMetadata.Builder<Builder> {\n\n      protected Builder() {\n         id(\"servermanager\")\n         .name(\"ServerManager API\")\n         .identityName(\"Unused\")\n         .defaultIdentity(\"foo\")\n         .defaultCredential(\"bar\")\n         .defaultEndpoint(\"http://demo\")\n         .documentation(URI.create(\"http://www.jclouds.org/documentation/userguide/compute\"))\n         .view(ComputeServiceContext.class)\n         .defaultModule(ServerManagerComputeServiceContextModule.class);\n      }\n\n      @Override\n      public ServerManagerApiMetadata build() {\n         return new ServerManagerApiMetadata(this);\n      }\n\n      @Override\n      protected Builder self() {\n         return this;\n      }\n   }\n}\n"
  },
  {
    "path": "skeletons/standalone-compute/src/main/java/org/jclouds/servermanager/compute/config/ServerManagerComputeServiceContextModule.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.servermanager.compute.config;\n\nimport org.jclouds.compute.ComputeServiceAdapter;\nimport org.jclouds.compute.config.ComputeServiceAdapterContextModule;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.domain.Location;\nimport org.jclouds.servermanager.Datacenter;\nimport org.jclouds.servermanager.Hardware;\nimport org.jclouds.servermanager.Image;\nimport org.jclouds.servermanager.Server;\nimport org.jclouds.servermanager.compute.functions.DatacenterToLocation;\nimport org.jclouds.servermanager.compute.functions.ServerManagerHardwareToHardware;\nimport org.jclouds.servermanager.compute.functions.ServerManagerImageToImage;\nimport org.jclouds.servermanager.compute.functions.ServerToNodeMetadata;\nimport org.jclouds.servermanager.compute.strategy.ServerManagerComputeServiceAdapter;\n\nimport com.google.common.base.Function;\nimport com.google.inject.TypeLiteral;\n\npublic class ServerManagerComputeServiceContextModule extends\n         ComputeServiceAdapterContextModule<Server, Hardware, Image, Datacenter> {\n\n   @Override\n   protected void configure() {\n      super.configure();\n      bind(new TypeLiteral<ComputeServiceAdapter<Server, Hardware, Image, Datacenter>>() {\n      }).to(ServerManagerComputeServiceAdapter.class);\n      bind(new TypeLiteral<Function<Server, NodeMetadata>>() {\n      }).to(ServerToNodeMetadata.class);\n      bind(new TypeLiteral<Function<Image, org.jclouds.compute.domain.Image>>() {\n      }).to(ServerManagerImageToImage.class);\n      bind(new TypeLiteral<Function<Hardware, org.jclouds.compute.domain.Hardware>>() {\n      }).to(ServerManagerHardwareToHardware.class);\n      bind(new TypeLiteral<Function<Datacenter, Location>>() {\n      }).to(DatacenterToLocation.class);\n      // to have the compute service adapter override default locations\n      install(new LocationsFromComputeServiceAdapterModule<Server, Hardware, Image, Datacenter>(){});\n   }\n}\n"
  },
  {
    "path": "skeletons/standalone-compute/src/main/java/org/jclouds/servermanager/compute/functions/DatacenterToLocation.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.servermanager.compute.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Provider;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LocationBuilder;\nimport org.jclouds.domain.LocationScope;\nimport org.jclouds.servermanager.Datacenter;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\n\n@Singleton\npublic class DatacenterToLocation implements Function<Datacenter, Location> {\n   private final Provider<Supplier<Location>> provider;\n\n   // allow us to lazy discover the provider of a resource\n   @Inject\n   public DatacenterToLocation(Provider<Supplier<Location>> provider) {\n      this.provider = checkNotNull(provider, \"provider\");\n   }\n\n   @Override\n   public Location apply(Datacenter from) {\n      return new LocationBuilder().scope(LocationScope.ZONE).id(from.id + \"\").description(from.name).parent(\n               provider.get().get()).build();\n   }\n\n}\n"
  },
  {
    "path": "skeletons/standalone-compute/src/main/java/org/jclouds/servermanager/compute/functions/ServerManagerHardwareToHardware.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.servermanager.compute.functions;\n\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.HardwareBuilder;\nimport org.jclouds.compute.domain.Processor;\nimport org.jclouds.compute.domain.Volume;\nimport org.jclouds.compute.domain.internal.VolumeImpl;\n\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableList;\n\n@Singleton\npublic class ServerManagerHardwareToHardware implements Function<org.jclouds.servermanager.Hardware, Hardware> {\n\n   @Override\n   public Hardware apply(org.jclouds.servermanager.Hardware from) {\n      HardwareBuilder builder = new HardwareBuilder();\n      builder.ids(from.id + \"\");\n      builder.name(from.name);\n      builder.processors(ImmutableList.of(new Processor(from.cores, 1.0)));\n      builder.ram(from.ram);\n      builder.volumes(ImmutableList.<Volume> of(new VolumeImpl(from.disk, true, false)));\n      return builder.build();\n   }\n\n}\n"
  },
  {
    "path": "skeletons/standalone-compute/src/main/java/org/jclouds/servermanager/compute/functions/ServerManagerImageToImage.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.servermanager.compute.functions;\n\nimport jakarta.annotation.Resource;\nimport jakarta.inject.Named;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.ImageBuilder;\nimport org.jclouds.compute.domain.OperatingSystem;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.Image.Status;\nimport org.jclouds.compute.reference.ComputeServiceConstants;\nimport org.jclouds.logging.Logger;\n\nimport com.google.common.base.Function;\n\n@Singleton\npublic class ServerManagerImageToImage implements Function<org.jclouds.servermanager.Image, Image> {\n   @Resource\n   @Named(ComputeServiceConstants.COMPUTE_LOGGER)\n   protected Logger logger = Logger.NULL;\n\n   @Override\n   public Image apply(org.jclouds.servermanager.Image from) {\n\n      ImageBuilder builder = new ImageBuilder();\n      builder.ids(from.id + \"\");\n      builder.name(from.name);\n      builder.description(from.name);\n\n      OsFamily family = null;\n      try {\n         family = OsFamily.fromValue(from.name);\n         builder.operatingSystem(new OperatingSystem.Builder().name(from.name).family(family).build());\n      } catch (IllegalArgumentException e) {\n         logger.debug(\"<< didn't match os(%s)\", from);\n      }\n      builder.status(Status.AVAILABLE);\n      return builder.build();\n   }\n\n}\n"
  },
  {
    "path": "skeletons/standalone-compute/src/main/java/org/jclouds/servermanager/compute/functions/ServerToNodeMetadata.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.servermanager.compute.functions;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.FluentIterable.from;\n\nimport java.util.Map;\nimport java.util.Set;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.collect.Memoized;\nimport org.jclouds.compute.domain.Hardware;\nimport org.jclouds.compute.domain.Image;\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.NodeMetadata.Status;\nimport org.jclouds.compute.domain.NodeMetadataBuilder;\nimport org.jclouds.compute.functions.GroupNamingConvention;\nimport org.jclouds.compute.predicates.HardwarePredicates;\nimport org.jclouds.compute.predicates.ImagePredicates;\nimport org.jclouds.domain.Credentials;\nimport org.jclouds.domain.Location;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.location.predicates.LocationPredicates;\nimport org.jclouds.servermanager.Server;\n\nimport com.google.common.base.Function;\nimport com.google.common.base.Supplier;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.ImmutableSet;\n\n@Singleton\npublic class ServerToNodeMetadata implements Function<Server, NodeMetadata> {\n\n   public static final Map<Server.Status, Status> serverStatusToNodeStatus = ImmutableMap\n         .<Server.Status, Status> builder().put(Server.Status.ACTIVE, Status.RUNNING)//\n         .put(Server.Status.BUILD, Status.PENDING)//\n         .put(Server.Status.TERMINATED, Status.TERMINATED)//\n         .put(Server.Status.UNRECOGNIZED, Status.UNRECOGNIZED)//\n         .build();\n\n   private final Supplier<Set<? extends Hardware>> hardware;\n   private final Supplier<Set<? extends Location>> locations;\n   private final Supplier<Set<? extends Image>> images;\n   private final Map<String, Credentials> credentialStore;\n   private final GroupNamingConvention nodeNamingConvention;\n\n   @Inject\n   ServerToNodeMetadata(Map<String, Credentials> credentialStore, @Memoized Supplier<Set<? extends Hardware>> hardware,\n         @Memoized Supplier<Set<? extends Location>> locations, @Memoized Supplier<Set<? extends Image>> images,\n         GroupNamingConvention.Factory namingConvention) {\n      this.nodeNamingConvention = checkNotNull(namingConvention, \"namingConvention\").createWithoutPrefix();\n      this.credentialStore = checkNotNull(credentialStore, \"credentialStore\");\n      this.hardware = checkNotNull(hardware, \"hardware\");\n      this.locations = checkNotNull(locations, \"locations\");\n      this.images = checkNotNull(images, \"images\");\n   }\n\n   @Override\n   public NodeMetadata apply(Server from) {\n      // convert the result object to a jclouds NodeMetadata\n      NodeMetadataBuilder builder = new NodeMetadataBuilder();\n      builder.ids(from.id + \"\");\n      builder.name(from.name);\n      builder.location(from(locations.get()).firstMatch(LocationPredicates.idEquals(from.datacenter)).orNull());\n      builder.group(nodeNamingConvention.groupInUniqueNameOrNull(from.name));\n      builder.imageId(from.imageId + \"\");\n      Image image = from(images.get()).firstMatch(ImagePredicates.idEquals(from.imageId + \"\")).orNull();\n      if (image != null)\n         builder.operatingSystem(image.getOperatingSystem());\n      builder.hardware(from(hardware.get()).firstMatch(HardwarePredicates.idEquals(from.hardwareId + \"\")).orNull());\n      builder.status(serverStatusToNodeStatus.get(from.status));\n      builder.publicAddresses(ImmutableSet.<String> of(from.publicAddress));\n      builder.privateAddresses(ImmutableSet.<String> of(from.privateAddress));\n      builder.credentials(LoginCredentials.fromCredentials(credentialStore.get(from.id + \"\")));\n      return builder.build();\n   }\n}\n"
  },
  {
    "path": "skeletons/standalone-compute/src/main/java/org/jclouds/servermanager/compute/strategy/ServerManagerComputeServiceAdapter.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.servermanager.compute.strategy;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static com.google.common.collect.Iterables.contains;\nimport static com.google.common.collect.Iterables.filter;\n\nimport jakarta.inject.Inject;\nimport jakarta.inject.Singleton;\n\nimport org.jclouds.compute.ComputeServiceAdapter;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.domain.LoginCredentials;\nimport org.jclouds.servermanager.Datacenter;\nimport org.jclouds.servermanager.Hardware;\nimport org.jclouds.servermanager.Image;\nimport org.jclouds.servermanager.Server;\nimport org.jclouds.servermanager.ServerManager;\n\nimport com.google.common.base.Predicate;\nimport com.google.common.collect.ImmutableSet;\n\n/**\n * defines the connection between the {@link ServerManager} implementation and the jclouds\n * {@link ComputeService}\n */\n@Singleton\npublic class ServerManagerComputeServiceAdapter implements ComputeServiceAdapter<Server, Hardware, Image, Datacenter> {\n   private final ServerManager client;\n\n   @Inject\n   public ServerManagerComputeServiceAdapter(ServerManager client) {\n      this.client = checkNotNull(client, \"client\");\n   }\n\n   @Override\n   public NodeAndInitialCredentials<Server>  createNodeWithGroupEncodedIntoName(String tag, String name, Template template) {\n      // create the backend object using parameters from the template.\n      Server from = client.createServerInDC(template.getLocation().getId(), name,\n            Integer.parseInt(template.getImage().getProviderId()),\n            Integer.parseInt(template.getHardware().getProviderId()));\n      return new NodeAndInitialCredentials<Server>(from, from.id + \"\", LoginCredentials.builder().user(from.loginUser)\n            .password(from.password).build());\n   }\n\n   @Override\n   public Iterable<Hardware> listHardwareProfiles() {\n      return client.listHardware();\n   }\n\n   @Override\n   public Iterable<Image> listImages() {\n      return client.listImages();\n   }\n   \n   @Override\n   public Image getImage(String id) {\n      int imageId = Integer.parseInt(id);\n      return client.getImage(imageId);\n   }\n   \n   @Override\n   public Iterable<Server> listNodes() {\n      return client.listServers();\n   }\n\n   @Override\n   public Iterable<Server> listNodesByIds(final Iterable<String> ids) {\n      return filter(listNodes(), new Predicate<Server>() {\n\n            @Override\n            public boolean apply(Server server) {\n               return contains(ids, Integer.toString(server.id));\n            }\n         });\n   }\n   \n   @Override\n   public Iterable<Datacenter> listLocations() {\n      return ImmutableSet.of(new Datacenter(1, \"SFO\"));\n   }\n\n   @Override\n   public Server getNode(String id) {\n      int serverId = Integer.parseInt(id);\n      return client.getServer(serverId);\n   }\n\n   @Override\n   public void destroyNode(String id) {\n      client.destroyServer(Integer.parseInt(id));\n   }\n\n   @Override\n   public void rebootNode(String id) {\n      client.rebootServer(Integer.parseInt(id));      \n   }\n\n   @Override\n   public void resumeNode(String id) {\n      client.startServer(Integer.parseInt(id));      \n      \n   }\n\n   @Override\n   public void suspendNode(String id) {\n      client.stopServer(Integer.parseInt(id));      \n   }\n}\n"
  },
  {
    "path": "skeletons/standalone-compute/src/test/java/org/jclouds/servermanager/compute/ServerManagerComputeServiceContextBuilderTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.servermanager.compute;\n\nimport static org.testng.Assert.assertEquals;\n\nimport java.util.Properties;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.internal.ContextImpl;\nimport org.jclouds.servermanager.ServerManagerApiMetadata;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"unit\", testName = \"ServerManagerContextBuilderTest\")\npublic class ServerManagerComputeServiceContextBuilderTest {\n\n\n   @Test\n   public void testCanBuildWithApiMetadata() {\n      ComputeServiceContext context = ContextBuilder.newBuilder(\n            new ServerManagerApiMetadata()).build(ComputeServiceContext.class);\n      context.close();\n   }\n\n   @Test\n   public void testCanBuildById() {\n      ComputeServiceContext context = ContextBuilder.newBuilder(\"servermanager\").build(ComputeServiceContext.class);\n      context.close();\n   }\n\n   @Test\n   public void testCanBuildWithOverridingProperties() {\n      Properties overrides = new Properties();\n      overrides.setProperty(\"servermanager.endpoint\", \"http://host\");\n      overrides.setProperty(\"servermanager.api-version\", \"1\");\n\n      ComputeServiceContext context = ContextBuilder.newBuilder(\"servermanager\")\n            .overrides(overrides).build(ComputeServiceContext.class);\n\n      context.close();\n   }\n\n   @Test\n   public void testUnwrapIsCorrectType() {\n      ComputeServiceContext context = ContextBuilder.newBuilder(\"servermanager\").build(ComputeServiceContext.class);\n\n      assertEquals(context.unwrap().getClass(), ContextImpl.class);\n\n      context.close();\n   }\n}\n"
  },
  {
    "path": "skeletons/standalone-compute/src/test/java/org/jclouds/servermanager/compute/ServerManagerComputeServiceLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.servermanager.compute;\n\nimport static org.jclouds.compute.util.ComputeServiceUtils.getCores;\nimport static org.testng.Assert.assertEquals;\n\nimport org.jclouds.compute.domain.NodeMetadata;\nimport org.jclouds.compute.domain.OsFamily;\nimport org.jclouds.compute.domain.Template;\nimport org.jclouds.compute.internal.BaseComputeServiceLiveTest;\nimport org.jclouds.ssh.jsch.config.JschSshClientModule;\nimport org.testng.annotations.Test;\n\nimport com.google.common.collect.ImmutableMap;\n\n@Test(groups = \"live\", enabled = true, singleThreaded = true)\npublic class ServerManagerComputeServiceLiveTest extends BaseComputeServiceLiveTest {\n\n   public ServerManagerComputeServiceLiveTest() {\n      provider = \"servermanager\";\n   }\n\n   @Test\n   public void testTemplateBuilder() {\n      Template defaultTemplate = client.templateBuilder().build();\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true);\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().getVersion(), \"5.3\");\n      assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.CENTOS);\n      assertEquals(defaultTemplate.getLocation().getId(), \"1\");\n      assertEquals(getCores(defaultTemplate.getHardware()), 0.5d);\n   }\n\n   @Override\n   protected JschSshClientModule getSshModule() {\n      return new JschSshClientModule();\n   }\n\n   // servermanager does not support metadata\n   @Override\n   protected void checkUserMetadataContains(NodeMetadata node, ImmutableMap<String, String> userMetadata) {\n      assert node.getUserMetadata().equals(ImmutableMap.<String, String> of()) : String.format(\n            \"node userMetadata did not match %s %s\", userMetadata, node);\n   }\n   \n}\n"
  },
  {
    "path": "skeletons/standalone-compute/src/test/java/org/jclouds/servermanager/compute/ServerManagerExperimentLiveTest.java",
    "content": "/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage org.jclouds.servermanager.compute;\n\nimport org.jclouds.ContextBuilder;\nimport org.jclouds.compute.ComputeServiceContext;\nimport org.jclouds.compute.internal.BaseComputeServiceContextLiveTest;\nimport org.jclouds.servermanager.ServerManagerApiMetadata;\nimport org.testng.annotations.Test;\n\n@Test(groups = \"live\", singleThreaded = true, testName = \"ServerManagerExperimentLiveTest\")\npublic class ServerManagerExperimentLiveTest extends BaseComputeServiceContextLiveTest {\n\n   public ServerManagerExperimentLiveTest() {\n      provider = \"servermanager\";\n   }\n\n   @Test\n   public void testAndExperiment() {\n      ComputeServiceContext context = null;\n      try {\n         context = ContextBuilder.newBuilder(new ServerManagerApiMetadata()).build(ComputeServiceContext.class);\n\n         context.getComputeService().listNodes();\n\n      } finally {\n         if (context != null)\n            context.close();\n      }\n   }\n\n}\n"
  },
  {
    "path": "skeletons/standalone-compute/src/test/resources/log4j.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE log4j:configuration SYSTEM \"log4j.dtd\">\n\n<!--\n    For more configuration infromation and examples see the Apache\n    Log4j website: http://logging.apache.org/log4j/\n-->\n<log4j:configuration xmlns:log4j=\"http://jakarta.apache.org/log4j/\"\n                     debug=\"false\">\n\n\n    <appender name=\"S\" class=\"org.apache.log4j.ConsoleAppender\">\n\n        <param name=\"Append\" value=\"true\"/>\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\"/>\n\n        <param name=\"Threshold\" value=\"TRACE\"/>\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\"/>\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n\n\n    <!-- A time/date based rolling appender -->\n    <appender name=\"WIREFILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds-wire.log\"/>\n        <param name=\"Append\" value=\"true\"/>\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\"/>\n\n        <param name=\"Threshold\" value=\"TRACE\"/>\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\"/>\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n\n    <!-- A time/date based rolling appender -->\n    <appender name=\"FILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds.log\"/>\n        <param name=\"Append\" value=\"true\"/>\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\"/>\n\n        <param name=\"Threshold\" value=\"TRACE\"/>\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\"/>\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n    <!-- A time/date based rolling appender -->\n\n    <!-- A time/date based rolling appender -->\n    <appender name=\"COMPUTEFILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds-compute.log\"/>\n        <param name=\"Append\" value=\"true\"/>\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\"/>\n\n        <param name=\"Threshold\" value=\"TRACE\"/>\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\"/>\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n\n    <!-- A time/date based rolling appender -->\n    <appender name=\"SSHFILE\" class=\"org.apache.log4j.DailyRollingFileAppender\">\n        <param name=\"File\" value=\"target/test-data/jclouds-ssh.log\"/>\n        <param name=\"Append\" value=\"true\"/>\n\n        <!-- Rollover at midnight each day -->\n        <param name=\"DatePattern\" value=\"'.'yyyy-MM-dd\"/>\n\n        <param name=\"Threshold\" value=\"TRACE\"/>\n\n        <layout class=\"org.apache.log4j.PatternLayout\">\n            <!-- The default pattern: Date Priority [Category] Message\\n -->\n            <param name=\"ConversionPattern\" value=\"%d %-5p [%c] (%t) %m%n\"/>\n\n            <!--\n                The full pattern: Date MS Priority [Category]\n                (Thread:NDC) Message\\n <param name=\"ConversionPattern\"\n                value=\"%d %-5r %-5p [%c] (%t:%x) %m%n\"/>\n            -->\n        </layout>\n    </appender>\n\n    <appender name=\"ASYNCCOMPUTE\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"COMPUTEFILE\"/>\n    </appender>\n\n    <appender name=\"ASYNCSSH\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"SSHFILE\"/>\n    </appender>\n\n    <appender name=\"ASYNC\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"FILE\"/>\n    </appender>\n\n    <appender name=\"ASYNCWIRE\" class=\"org.apache.log4j.AsyncAppender\">\n        <appender-ref ref=\"WIREFILE\"/>\n    </appender>\n    <!-- ================ -->\n    <!-- Limit categories -->\n    <!-- ================ -->\n\n    <category name=\"org.jclouds\">\n        <priority value=\"DEBUG\"/>\n        <appender-ref ref=\"ASYNC\"/>\n    </category>\n\n    <category name=\"jclouds.headers\">\n        <priority value=\"DEBUG\"/>\n        <appender-ref ref=\"ASYNCWIRE\"/>\n    </category>\n\n    <category name=\"jclouds.ssh\">\n        <priority value=\"DEBUG\"/>\n        <appender-ref ref=\"ASYNCSSH\"/>\n    </category>\n    <category name=\"jclouds.wire\">\n        <priority value=\"DEBUG\"/>\n        <appender-ref ref=\"ASYNCWIRE\"/>\n    </category>\n    <category name=\"jclouds.compute\">\n        <priority value=\"TRACE\"/>\n        <appender-ref ref=\"ASYNCCOMPUTE\"/>\n    </category>\n    <!-- ======================= -->\n    <!-- Setup the Root category -->\n    <!-- ======================= -->\n\n    <root>\n        <priority value=\"TRACE\"/>\n        <appender-ref ref=\"S\"/>\n    </root>\n\n</log4j:configuration>\n"
  }
]